diff --git a/artemis-boot/src/main/java/org/apache/activemq/artemis/boot/Artemis.java b/artemis-boot/src/main/java/org/apache/activemq/artemis/boot/Artemis.java index 1e4ec4ee6e..52a6852dcd 100644 --- a/artemis-boot/src/main/java/org/apache/activemq/artemis/boot/Artemis.java +++ b/artemis-boot/src/main/java/org/apache/activemq/artemis/boot/Artemis.java @@ -32,75 +32,61 @@ import java.util.Comparator; * execution off to the ActiveMQ Artemis cli main. *

*/ -public class Artemis -{ +public class Artemis { - public static void main(String[] args) throws Throwable - { + public static void main(String[] args) throws Throwable { ArrayList dirs = new ArrayList(); String home = System.getProperty("artemis.home"); - if (home != null) - { + if (home != null) { dirs.add(new File(new File(home), "lib")); } String instance = System.getProperty("artemis.instance"); File instanceFile = null; - if (instance != null) - { + if (instance != null) { instanceFile = new File(instance); dirs.add(new File(instanceFile, "lib")); } ArrayList urls = new ArrayList(); - for (File bootdir : dirs) - { - if (bootdir.exists() && bootdir.isDirectory()) - { + for (File bootdir : dirs) { + if (bootdir.exists() && bootdir.isDirectory()) { // Find the jar files in the directory.. ArrayList files = new ArrayList(); - for (File f : bootdir.listFiles()) - { - if (f.getName().endsWith(".jar") || f.getName().endsWith(".zip")) - { + for (File f : bootdir.listFiles()) { + if (f.getName().endsWith(".jar") || f.getName().endsWith(".zip")) { files.add(f); } } // Sort the list by file name.. - Collections.sort(files, new Comparator() - { - public int compare(File file, File file1) - { + Collections.sort(files, new Comparator() { + public int compare(File file, File file1) { return file.getName().compareTo(file1.getName()); } }); - for (File f : files) - { + for (File f : files) { add(urls, f); } } } - if (instance != null) - { + if (instance != null) { System.setProperty("java.io.tmpdir", new File(new File(instance), "tmp").getCanonicalPath()); } // Lets try to covert the logging.configuration setting to a valid URI String loggingConfig = System.getProperty("logging.configuration"); - if (loggingConfig != null) - { + if (loggingConfig != null) { System.setProperty("logging.configuration", fixupFileURI(loggingConfig)); } // Without the etc on the config, things like JGroups configuration wouldn't be loaded - if (instanceFile != null) - { + if (instanceFile != null) { File etcFile = new File(instance, "etc"); // Adding etc to the classLoader so modules can lookup for their configs urls.add(etcFile.toURI().toURL()); @@ -111,35 +97,28 @@ public class Artemis Thread.currentThread().setContextClassLoader(loader); Class clazz = loader.loadClass("org.apache.activemq.artemis.cli.Artemis"); Method method = clazz.getMethod("main", args.getClass()); - try - { + try { method.invoke(null, (Object) args); } - catch (InvocationTargetException e) - { + catch (InvocationTargetException e) { throw e.getTargetException(); } } - static String fixupFileURI(String value) - { - if (value != null && value.startsWith("file:")) - { + static String fixupFileURI(String value) { + if (value != null && value.startsWith("file:")) { value = value.substring("file:".length()); value = new File(value).toURI().toString(); } return value; } - private static void add(ArrayList urls, File file) - { - try - { + private static void add(ArrayList urls, File file) { + try { urls.add(file.toURI().toURL()); } - catch (MalformedURLException e) - { + catch (MalformedURLException e) { e.printStackTrace(); } } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/Artemis.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/Artemis.java index edcdce0b74..4692b1f2fb 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/Artemis.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/Artemis.java @@ -40,23 +40,19 @@ import org.apache.activemq.artemis.cli.commands.tools.PrintData; import org.apache.activemq.artemis.cli.commands.tools.XmlDataExporter; import org.apache.activemq.artemis.cli.commands.tools.XmlDataImporter; -public class Artemis -{ +public class Artemis { + @SuppressWarnings("unchecked") - public static void main(String... args) throws Exception - { - try - { + public static void main(String... args) throws Exception { + try { execute(args); } - catch (ConfigurationException configException) - { + catch (ConfigurationException configException) { System.err.println(configException.getMessage()); System.out.println(); System.out.println("Configuration should be specified as 'scheme:location'. Default configuration is 'xml:${ARTEMIS_INSTANCE}/etc/bootstrap.xml'"); } - catch (RuntimeException re) - { + catch (RuntimeException re) { System.err.println(re.getMessage()); System.out.println(); @@ -66,26 +62,21 @@ public class Artemis } } - public static Object execute(String... args) throws Exception - { + public static Object execute(String... args) throws Exception { return execute(null, null, args); } - public static Object execute(File artemisHome, File artemisInstance, List args) throws Exception - { + public static Object execute(File artemisHome, File artemisInstance, List args) throws Exception { return execute(artemisHome, artemisInstance, (String[]) args.toArray(new String[args.size()])); } - public static Object execute(File artemisHome, File artemisInstance, String... args) throws Exception - { + public static Object execute(File artemisHome, File artemisInstance, String... args) throws Exception { Action action = builder(artemisInstance).build().parse(args); action.setHomeValues(artemisHome, artemisInstance); - if (action.isVerbose()) - { + if (action.isVerbose()) { System.out.print("Executing " + action.getClass().getName() + " "); - for (String arg : args) - { + for (String arg : args) { System.out.print(arg + " "); } System.out.println(); @@ -95,48 +86,31 @@ public class Artemis return action.execute(ActionContext.system()); } - private static Cli.CliBuilder builder(File artemisInstance) - { + private static Cli.CliBuilder builder(File artemisInstance) { String instance = artemisInstance != null ? artemisInstance.getAbsolutePath() : System.getProperty("artemis.instance"); - Cli.CliBuilder builder = Cli.builder("artemis") - .withDescription("ActiveMQ Artemis Command Line") - .withCommand(HelpAction.class) - .withCommand(Producer.class) - .withCommand(Consumer.class) - .withCommand(Browse.class) - .withDefaultCommand(HelpAction.class); + Cli.CliBuilder builder = Cli.builder("artemis").withDescription("ActiveMQ Artemis Command Line").withCommand(HelpAction.class).withCommand(Producer.class).withCommand(Consumer.class).withCommand(Browse.class).withDefaultCommand(HelpAction.class); + builder.withGroup("data").withDescription("data tools group (print|exp|imp|exp|encode|decode|compact) (example ./artemis data print)"). + withDefaultCommand(HelpData.class).withCommands(PrintData.class, XmlDataExporter.class, XmlDataImporter.class, DecodeJournal.class, EncodeJournal.class, CompactJournal.class); - builder.withGroup("data") - .withDescription("data tools group (print|exp|imp|exp|encode|decode|compact) (example ./artemis data print)"). - withDefaultCommand(HelpData.class).withCommands(PrintData.class, XmlDataExporter.class, - XmlDataImporter.class, DecodeJournal.class, EncodeJournal.class, - CompactJournal.class); - - if (instance != null) - { + if (instance != null) { builder = builder.withCommands(Run.class, Stop.class, Kill.class); } - else - { + else { builder = builder.withCommand(Create.class); } return builder; } - - public static void printBanner() throws Exception - { + public static void printBanner() throws Exception { copy(Artemis.class.getResourceAsStream("banner.txt"), System.out); } - private static long copy(InputStream in, OutputStream out) throws Exception - { + private static long copy(InputStream in, OutputStream out) throws Exception { byte[] buffer = new byte[1024]; int len = in.read(buffer); - while (len != -1) - { + while (len != -1) { out.write(buffer, 0, len); len = in.read(buffer); } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/ConfigurationException.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/ConfigurationException.java index 7d3b8e334f..813f4598ce 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/ConfigurationException.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/ConfigurationException.java @@ -16,10 +16,9 @@ */ package org.apache.activemq.artemis.cli; -public class ConfigurationException extends Exception -{ - public ConfigurationException(String message) - { +public class ConfigurationException extends Exception { + + public ConfigurationException(String message) { super(message); } } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Action.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Action.java index e0510ff9a6..72e6c73f9b 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Action.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Action.java @@ -18,8 +18,8 @@ package org.apache.activemq.artemis.cli.commands; import java.io.File; -public interface Action -{ +public interface Action { + boolean isVerbose(); void setHomeValues(File brokerHome, File brokerInstance); diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/ActionAbstract.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/ActionAbstract.java index fb3ea649ee..d5d68bdc32 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/ActionAbstract.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/ActionAbstract.java @@ -20,8 +20,7 @@ import java.io.File; import io.airlift.airline.Option; -public abstract class ActionAbstract implements Action -{ +public abstract class ActionAbstract implements Action { @Option(name = "--verbose", description = "Adds more information on the execution") boolean verbose; @@ -33,40 +32,32 @@ public abstract class ActionAbstract implements Action protected ActionContext context; @Override - public boolean isVerbose() - { + public boolean isVerbose() { return verbose; } @Override - public void setHomeValues(File brokerHome, File brokerInstance) - { - if (brokerHome != null) - { + public void setHomeValues(File brokerHome, File brokerInstance) { + if (brokerHome != null) { this.brokerHome = brokerHome.getAbsolutePath(); } - if (brokerInstance != null) - { + if (brokerInstance != null) { this.brokerInstance = brokerInstance.getAbsolutePath(); } } - public String getBrokerInstance() - { - if (brokerInstance == null) - { + public String getBrokerInstance() { + if (brokerInstance == null) { /* We use File URI for locating files. The ARTEMIS_HOME variable is used to determine file paths. For Windows the ARTEMIS_HOME variable will include back slashes (An invalid file URI character path separator). For this reason we overwrite the ARTEMIS_HOME variable with backslashes replaced with forward slashes. */ brokerInstance = System.getProperty("artemis.instance"); - if (brokerInstance != null) - { + if (brokerInstance != null) { brokerInstance = brokerInstance.replace("\\", "/"); System.setProperty("artemis.instance", brokerInstance); } - if (brokerInstance == null) - { + if (brokerInstance == null) { // if still null we will try to improvise with "." brokerInstance = "."; } @@ -74,23 +65,18 @@ public abstract class ActionAbstract implements Action return brokerInstance; } - - public String getBrokerHome() - { - if (brokerHome == null) - { + public String getBrokerHome() { + if (brokerHome == null) { /* We use File URI for locating files. The ARTEMIS_HOME variable is used to determine file paths. For Windows the ARTEMIS_HOME variable will include back slashes (An invalid file URI character path separator). For this reason we overwrite the ARTEMIS_HOME variable with backslashes replaced with forward slashes. */ brokerHome = System.getProperty("artemis.home"); - if (brokerHome != null) - { + if (brokerHome != null) { brokerHome = brokerHome.replace("\\", "/"); System.setProperty("artemis.home", brokerHome); } - if (brokerHome == null) - { + if (brokerHome == null) { // if still null we will try to improvise with "." brokerHome = "."; } @@ -98,9 +84,7 @@ public abstract class ActionAbstract implements Action return brokerHome; } - - public Object execute(ActionContext context) throws Exception - { + public Object execute(ActionContext context) throws Exception { this.context = context; return null; diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/ActionContext.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/ActionContext.java index 29911e5c3f..244de07a53 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/ActionContext.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/ActionContext.java @@ -19,11 +19,9 @@ package org.apache.activemq.artemis.cli.commands; import java.io.InputStream; import java.io.PrintStream; -public class ActionContext -{ +public class ActionContext { - public ActionContext(InputStream in, PrintStream out, PrintStream err) - { + public ActionContext(InputStream in, PrintStream out, PrintStream err) { this.in = in; this.out = out; this.err = err; @@ -33,8 +31,7 @@ public class ActionContext public PrintStream out; public PrintStream err; - public static ActionContext system() - { + public static ActionContext system() { return new ActionContext(System.in, System.out, System.err); } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Browse.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Browse.java index db26cdb84e..65eac0d1ca 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Browse.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Browse.java @@ -28,14 +28,13 @@ import javax.jms.Destination; import javax.jms.Session; @Command(name = "browser", description = "It will send consume messages from an instance") -public class Browse extends DestAbstract -{ +public class Browse extends DestAbstract { + @Option(name = "--filter", description = "filter to be used with the consumer") String filter; @Override - public Object execute(ActionContext context) throws Exception - { + public Object execute(ActionContext context) throws Exception { super.execute(context); System.out.println("Consumer:: filter = " + filter); @@ -43,18 +42,14 @@ public class Browse extends DestAbstract ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURL, user, password); Destination dest = ActiveMQDestination.createDestination(this.destination, ActiveMQDestination.QUEUE_TYPE); - try (Connection connection = factory.createConnection()) - { + try (Connection connection = factory.createConnection()) { ConsumerThread[] threadsArray = new ConsumerThread[threads]; - for (int i = 0; i < threads; i++) - { + for (int i = 0; i < threads; i++) { Session session; - if (txBatchSize > 0) - { + if (txBatchSize > 0) { session = connection.createSession(true, Session.SESSION_TRANSACTED); } - else - { + else { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } threadsArray[i] = new ConsumerThread(session, dest, i); @@ -62,8 +57,7 @@ public class Browse extends DestAbstract threadsArray[i].setVerbose(verbose).setSleep(sleep).setMessageCount(messageCount).setFilter(filter).setBrowse(true); } - for (ConsumerThread thread : threadsArray) - { + for (ConsumerThread thread : threadsArray) { thread.start(); } @@ -71,8 +65,7 @@ public class Browse extends DestAbstract int received = 0; - for (ConsumerThread thread : threadsArray) - { + for (ConsumerThread thread : threadsArray) { thread.join(); received += thread.getReceived(); } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Configurable.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Configurable.java index 8f3dbf573f..ffdbdad1b4 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Configurable.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Configurable.java @@ -36,15 +36,14 @@ import org.apache.activemq.artemis.jms.server.config.impl.FileJMSConfiguration; /** * Abstract class where we can replace the configuration in various places * */ -public abstract class Configurable extends ActionAbstract -{ +public abstract class Configurable extends ActionAbstract { + @Arguments(description = "Broker Configuration URI, default 'xml:${ARTEMIS_INSTANCE}/etc/bootstrap.xml'") String configuration; @Option(name = "--broker", description = "This would override the broker configuration from the bootstrap") String brokerConfig; - @Inject public GlobalMetadata global; @@ -52,8 +51,7 @@ public abstract class Configurable extends ActionAbstract private FileConfiguration fileConfiguration; - protected void treatError(Exception e, String group, String command) - { + protected void treatError(Exception e, String group, String command) { ActiveMQBootstrapLogger.LOGGER.debug(e.getMessage(), e); System.err.println(); System.err.println("Error:" + e.getMessage()); @@ -61,16 +59,11 @@ public abstract class Configurable extends ActionAbstract helpGroup(group, command); } - protected void helpGroup(String groupName, String commandName) - { - for (CommandGroupMetadata group: global.getCommandGroups()) - { - if (group.getName().equals(groupName)) - { - for (CommandMetadata command: group.getCommands()) - { - if (command.getName().equals(commandName)) - { + protected void helpGroup(String groupName, String commandName) { + for (CommandGroupMetadata group : global.getCommandGroups()) { + if (group.getName().equals(groupName)) { + for (CommandMetadata command : group.getCommands()) { + if (command.getName().equals(commandName)) { Help.help(command); } } @@ -79,13 +72,9 @@ public abstract class Configurable extends ActionAbstract } } - - protected FileConfiguration getFileConfiguration() throws Exception - { - if (fileConfiguration == null) - { - if (getBrokerInstance() == null) - { + protected FileConfiguration getFileConfiguration() throws Exception { + if (fileConfiguration == null) { + if (getBrokerInstance() == null) { final String defaultLocation = "./data"; fileConfiguration = new FileConfiguration(); // These will be the default places in case the file can't be loaded @@ -94,8 +83,7 @@ public abstract class Configurable extends ActionAbstract fileConfiguration.setLargeMessagesDirectory(defaultLocation + "/largemessages"); fileConfiguration.setPagingDirectory(defaultLocation + "/paging"); } - else - { + else { fileConfiguration = new FileConfiguration(); FileJMSConfiguration jmsConfiguration = new FileJMSConfiguration(); @@ -111,20 +99,14 @@ public abstract class Configurable extends ActionAbstract return fileConfiguration; } - - protected BrokerDTO getBrokerDTO() throws Exception - { - if (brokerDTO == null) - { + protected BrokerDTO getBrokerDTO() throws Exception { + if (brokerDTO == null) { getConfiguration(); - brokerDTO = BrokerFactory.createBrokerConfiguration(configuration); - if (brokerConfig != null) - { - if (!brokerConfig.startsWith("file:")) - { + if (brokerConfig != null) { + if (!brokerConfig.startsWith("file:")) { brokerConfig = "file:" + brokerConfig; } @@ -135,10 +117,8 @@ public abstract class Configurable extends ActionAbstract return brokerDTO; } - protected String getConfiguration() - { - if (configuration == null) - { + protected String getConfiguration() { + if (configuration == null) { File xmlFile = new File(new File(new File(getBrokerInstance()), "etc"), "bootstrap.xml"); configuration = "xml:" + xmlFile.toURI().toString().substring("file:".length()); @@ -151,5 +131,4 @@ public abstract class Configurable extends ActionAbstract return configuration; } - } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Consumer.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Consumer.java index 9c6f43317b..7ef438bf87 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Consumer.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Consumer.java @@ -28,9 +28,7 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; import org.apache.activemq.artemis.jms.client.ActiveMQDestination; @Command(name = "consumer", description = "It will send consume messages from an instance") -public class Consumer extends DestAbstract -{ - +public class Consumer extends DestAbstract { @Option(name = "--durable", description = "It will use durable subscription in case of client") boolean durable = false; @@ -45,8 +43,7 @@ public class Consumer extends DestAbstract String filter; @Override - public Object execute(ActionContext context) throws Exception - { + public Object execute(ActionContext context) throws Exception { super.execute(context); System.out.println("Consumer:: filter = " + filter); @@ -54,28 +51,22 @@ public class Consumer extends DestAbstract ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURL, user, password); Destination dest = ActiveMQDestination.createDestination(this.destination, ActiveMQDestination.QUEUE_TYPE); - try (Connection connection = factory.createConnection()) - { + try (Connection connection = factory.createConnection()) { ConsumerThread[] threadsArray = new ConsumerThread[threads]; - for (int i = 0; i < threads; i++) - { + for (int i = 0; i < threads; i++) { Session session; - if (txBatchSize > 0) - { + if (txBatchSize > 0) { session = connection.createSession(true, Session.SESSION_TRANSACTED); } - else - { + else { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } threadsArray[i] = new ConsumerThread(session, dest, i); - threadsArray[i].setVerbose(verbose).setSleep(sleep).setDurable(durable).setBatchSize(txBatchSize).setBreakOnNull(breakOnNull) - .setMessageCount(messageCount).setReceiveTimeOut(receiveTimeout).setFilter(filter).setBrowse(false); + threadsArray[i].setVerbose(verbose).setSleep(sleep).setDurable(durable).setBatchSize(txBatchSize).setBreakOnNull(breakOnNull).setMessageCount(messageCount).setReceiveTimeOut(receiveTimeout).setFilter(filter).setBrowse(false); } - for (ConsumerThread thread : threadsArray) - { + for (ConsumerThread thread : threadsArray) { thread.start(); } @@ -83,8 +74,7 @@ public class Consumer extends DestAbstract int received = 0; - for (ConsumerThread thread : threadsArray) - { + for (ConsumerThread thread : threadsArray) { thread.join(); received += thread.getReceived(); } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Create.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Create.java index 533d7c4c16..2063fc4a11 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Create.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Create.java @@ -57,8 +57,8 @@ import static java.nio.file.attribute.PosixFilePermission.OWNER_WRITE; * CLI action that creates a broker instance directory. */ @Command(name = "create", description = "creates a new broker instance") -public class Create extends InputAbstract -{ +public class Create extends InputAbstract { + private static final Integer DEFAULT_PORT = 61616; private static final Integer AMQP_PORT = 5672; @@ -173,346 +173,278 @@ public class Create extends InputAbstract boolean IS_CYGWIN; - public int getMaxHops() - { + public int getMaxHops() { return maxHops; } - public void setMaxHops(int maxHops) - { + public void setMaxHops(int maxHops) { this.maxHops = maxHops; } - public boolean isNoWeb() - { + public boolean isNoWeb() { return noWeb; } - public void setNoWeb(boolean noWeb) - { + public void setNoWeb(boolean noWeb) { this.noWeb = noWeb; } - public int getPortOffset() - { + public int getPortOffset() { return portOffset; } - public void setPortOffset(int portOffset) - { + public void setPortOffset(int portOffset) { this.portOffset = portOffset; } - public MessageLoadBalancingType getMessageLoadBalancing() - { + public MessageLoadBalancingType getMessageLoadBalancing() { return messageLoadBalancing; } - public void setMessageLoadBalancing(MessageLoadBalancingType messageLoadBalancing) - { + public void setMessageLoadBalancing(MessageLoadBalancingType messageLoadBalancing) { this.messageLoadBalancing = messageLoadBalancing; } - public String getJavaOptions() - { + public String getJavaOptions() { return javaOptions; } - public void setJavaOptions(String javaOptions) - { + public void setJavaOptions(String javaOptions) { this.javaOptions = javaOptions; } - public File getInstance() - { + public File getInstance() { return directory; } - public void setInstance(File directory) - { + public void setInstance(File directory) { this.directory = directory; } - public String getHost() - { - if (host == null) - { + public String getHost() { + if (host == null) { host = "0.0.0.0"; } return host; } - public String getHostForClustered() - { - if (getHost().equals("0.0.0.0")) - { + public String getHostForClustered() { + if (getHost().equals("0.0.0.0")) { host = input("--host", "Host " + host + " is not valid for clustering, please provide a valid IP or hostname", "localhost"); } return host; } - public void setHost(String host) - { + public void setHost(String host) { this.host = host; } - public boolean isForce() - { + public boolean isForce() { return force; } - public void setForce(boolean force) - { + public void setForce(boolean force) { this.force = force; } - public File getHome() - { - if (home == null) - { + public File getHome() { + if (home == null) { home = new File(getBrokerHome()); } return home; } - public void setHome(File home) - { + public void setHome(File home) { this.home = home; } - public boolean isClustered() - { + public boolean isClustered() { return clustered; } - public void setClustered(boolean clustered) - { + public void setClustered(boolean clustered) { this.clustered = clustered; } - public boolean isReplicated() - { + public boolean isReplicated() { return replicated; } - public void setReplicated(boolean replicated) - { + public void setReplicated(boolean replicated) { this.replicated = replicated; } - public boolean isSharedStore() - { + public boolean isSharedStore() { return sharedStore; } - public void setSharedStore(boolean sharedStore) - { + public void setSharedStore(boolean sharedStore) { this.sharedStore = sharedStore; } - public String getEncoding() - { + public String getEncoding() { return encoding; } - public void setEncoding(String encoding) - { + public void setEncoding(String encoding) { this.encoding = encoding; } - public String getData() - { + public String getData() { return data; } - public void setData(String data) - { + public void setData(String data) { this.data = data; } - public String getClusterUser() - { - if (clusterUser == null) - { + public String getClusterUser() { + if (clusterUser == null) { clusterUser = input("--cluster-user", "Please provide the username:", "cluster-admin"); } return clusterUser; } - public void setClusterUser(String clusterUser) - { + public void setClusterUser(String clusterUser) { this.clusterUser = clusterUser; } - public String getClusterPassword() - { - if (clusterPassword == null) - { + public String getClusterPassword() { + if (clusterPassword == null) { clusterPassword = inputPassword("--cluster-password", "Please enter the password:", "password-admin"); } return clusterPassword; } - public void setClusterPassword(String clusterPassword) - { + public void setClusterPassword(String clusterPassword) { this.clusterPassword = clusterPassword; } - public boolean isAllowAnonymous() - { - if (allowAnonymous == null) - { + public boolean isAllowAnonymous() { + if (allowAnonymous == null) { String value = input("--allow-anonymous | --require-login", "Allow anonymous access? (Y/N):", "Y"); allowAnonymous = Boolean.valueOf(value.toLowerCase().equals("y")); } return allowAnonymous.booleanValue(); } - public void setAllowAnonymous(boolean allowGuest) - { + public void setAllowAnonymous(boolean allowGuest) { this.allowAnonymous = Boolean.valueOf(allowGuest); } - public Boolean getRequireLogin() - { - if (requireLogin == null) - { + public Boolean getRequireLogin() { + if (requireLogin == null) { requireLogin = !isAllowAnonymous(); } return requireLogin; } - public void setRequireLogin(Boolean requireLogin) - { + public void setRequireLogin(Boolean requireLogin) { this.requireLogin = requireLogin; } - public String getPassword() - { + public String getPassword() { - if (password == null) - { + if (password == null) { this.password = inputPassword("--password", "Please provide the default password:", "admin"); } return password; } - public void setPassword(String password) - { + public void setPassword(String password) { this.password = password; } - public String getUser() - { - if (user == null) - { + public String getUser() { + if (user == null) { user = input("--user", "Please provide the default username:", "admin"); } return user; } - public void setUser(String user) - { + public void setUser(String user) { this.user = user; } - public String getRole() - { - if (role == null) - { + public String getRole() { + if (role == null) { role = "amq"; } return role; } - public void setRole(String role) - { + public void setRole(String role) { this.role = role; } - public boolean isSlave() - { + public boolean isSlave() { return slave; } - public void setSlave(boolean slave) - { + public void setSlave(boolean slave) { this.slave = slave; } - public boolean isFailoverOnShutodwn() - { + public boolean isFailoverOnShutodwn() { return failoverOnShutodwn; } - public void setFailoverOnShutodwn(boolean failoverOnShutodwn) - { + public void setFailoverOnShutodwn(boolean failoverOnShutodwn) { this.failoverOnShutodwn = failoverOnShutodwn; } - public Boolean getAllowAnonymous() - { + public Boolean getAllowAnonymous() { return allowAnonymous; } - public void setAllowAnonymous(Boolean allowAnonymous) - { + public void setAllowAnonymous(Boolean allowAnonymous) { this.allowAnonymous = allowAnonymous; } @Override - public Object execute(ActionContext context) throws Exception - { + public Object execute(ActionContext context) throws Exception { this.checkDirectory(); super.execute(context); - try - { + try { return run(context); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(context.err); throw e; } } - - /** This method is made public for the testsuite */ - public InputStream openStream(String source) - { + /** + * This method is made public for the testsuite + */ + public InputStream openStream(String source) { return this.getClass().getResourceAsStream(source); } /** * Checks that the directory provided either exists and is writable or doesn't exist but can be created. */ - private void checkDirectory() - { - if (!directory.exists()) - { + private void checkDirectory() { + if (!directory.exists()) { boolean created = directory.mkdirs(); - if (!created) - { + if (!created) { throw new RuntimeException(String.format("Unable to create the path '%s'.", directory)); } } - else if (!directory.canWrite()) - { + else if (!directory.canWrite()) { throw new RuntimeException(String.format("The path '%s' is not writable.", directory)); } } - public Object run(ActionContext context) throws Exception - { + public Object run(ActionContext context) throws Exception { IS_WINDOWS = System.getProperty("os.name").toLowerCase().trim().startsWith("win"); IS_CYGWIN = IS_WINDOWS && "cygwin".equals(System.getenv("OSTYPE")); // requireLogin should set alloAnonymous=false, to avoid user's questions - if (requireLogin != null && requireLogin.booleanValue()) - { + if (requireLogin != null && requireLogin.booleanValue()) { allowAnonymous = Boolean.FALSE; } @@ -524,35 +456,29 @@ public class Create extends InputAbstract filters.put("${failover-on-shutdown}", isFailoverOnShutodwn() ? "true" : "false"); - if (replicated) - { + if (replicated) { clustered = true; filters.put("${replicated.settings}", applyFilters(readTextFile(ETC_REPLICATED_SETTINGS_TXT), filters)); } - else - { + else { filters.put("${replicated.settings}", ""); } - if (sharedStore) - { + if (sharedStore) { clustered = true; filters.put("${shared-store.settings}", applyFilters(readTextFile(ETC_SHARED_STORE_SETTINGS_TXT), filters)); } - else - { + else { filters.put("${shared-store.settings}", ""); } boolean aio; - if (IS_WINDOWS || !supportsLibaio()) - { + if (IS_WINDOWS || !supportsLibaio()) { aio = false; filters.put("${journal.settings}", "NIO"); } - else - { + else { aio = true; filters.put("${journal.settings}", "ASYNCIO"); } @@ -572,8 +498,7 @@ public class Create extends InputAbstract filters.put("${password}", getPassword()); filters.put("${role}", getRole()); - if (clustered) - { + if (clustered) { filters.put("${host}", getHostForClustered()); String connectorSettings = readTextFile(ETC_CONNECTOR_SETTINGS_TXT); connectorSettings = applyFilters(connectorSettings, filters); @@ -584,8 +509,7 @@ public class Create extends InputAbstract filters.put("${cluster-user}", getClusterUser()); filters.put("${cluster-password}", getClusterPassword()); } - else - { + else { filters.put("${host}", getHost()); filters.put("${connector-config.settings}", ""); filters.put("${cluster-security.settings}", ""); @@ -596,8 +520,7 @@ public class Create extends InputAbstract applyJMSObjects(filters); - if (home != null) - { + if (home != null) { filters.put("${home}", path(home, false)); } filters.put("${artemis.home}", path(getHome().toString(), false)); @@ -612,23 +535,20 @@ public class Create extends InputAbstract File dataFolder = new File(directory, "data"); dataFolder.mkdirs(); - if (javaOptions == null || javaOptions.length() == 0) - { + if (javaOptions == null || javaOptions.length() == 0) { javaOptions = ""; } filters.put("${java-opts}", javaOptions); - if (IS_WINDOWS) - { + if (IS_WINDOWS) { write(BIN_ARTEMIS_CMD, null, false); write(BIN_ARTEMIS_SERVICE_EXE); write(BIN_ARTEMIS_SERVICE_XML, filters, false); write(ETC_ARTEMIS_PROFILE_CMD, filters, false); } - if (!IS_WINDOWS || IS_CYGWIN) - { + if (!IS_WINDOWS || IS_CYGWIN) { write(BIN_ARTEMIS, null, true); makeExec(BIN_ARTEMIS); write(BIN_ARTEMIS_SERVICE, null, true); @@ -639,22 +559,17 @@ public class Create extends InputAbstract write(ETC_LOGGING_PROPERTIES, null, false); - if (isAllowAnonymous()) - { + if (isAllowAnonymous()) { filters.put("${bootstrap.guest}", "default-user=\"" + getUser() + "\""); } - else - { + else { filters.put("${bootstrap.guest}", ""); } - - if (noWeb) - { + if (noWeb) { filters.put("${bootstrap-web-settings}", ""); } - else - { + else { filters.put("${bootstrap-web-settings}", applyFilters(readTextFile(ETC_BOOTSTRAP_WEB_SETTINGS_TXT), filters)); } @@ -673,12 +588,10 @@ public class Create extends InputAbstract File service = new File(directory, BIN_ARTEMIS_SERVICE); context.out.println(""); - if (!IS_WINDOWS || IS_CYGWIN) - { + if (!IS_WINDOWS || IS_CYGWIN) { // Does it look like we are on a System V init system? - if (new File("/etc/init.d/").isDirectory()) - { + if (new File("/etc/init.d/").isDirectory()) { context.out.println("Or you can setup the broker as system service and run it in the background:"); context.out.println(""); context.out.println(" sudo ln -s \"%s\" /etc/init.d/".format(service.getCanonicalPath())); @@ -686,8 +599,7 @@ public class Create extends InputAbstract context.out.println(""); } - else - { + else { context.out.println("Or you can run the broker in the background using:"); context.out.println(""); @@ -696,8 +608,7 @@ public class Create extends InputAbstract } } - if (IS_WINDOWS) - { + if (IS_WINDOWS) { service = new File(directory, BIN_ARTEMIS_SERVICE_EXE); context.out.println("Or you can setup the broker as Windows service and run it in the background:"); context.out.println(""); @@ -714,41 +625,36 @@ public class Create extends InputAbstract return null; } - /** It will create the jms configurations */ - private void applyJMSObjects(HashMap filters) - { + /** + * It will create the jms configurations + */ + private void applyJMSObjects(HashMap filters) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); printWriter.println(); - for (String str : getQueueList()) - { + for (String str : getQueueList()) { printWriter.println(" "); } - for (String str : getTopicList()) - { + for (String str : getTopicList()) { printWriter.println(" "); } filters.put("${jms-list.settings}", writer.toString()); } - private void performAutoTune(HashMap filters, boolean aio, File dataFolder) - { - if (noAutoTune) - { + private void performAutoTune(HashMap filters, boolean aio, File dataFolder) { + if (noAutoTune) { filters.put("${journal-buffer.settings}", ""); } - else - { - try - { + else { + try { int writes = 250; System.out.println(""); System.out.println("Auto tuning journal ..."); long time = SyncCalculation.syncTest(dataFolder, 4096, writes, 5, verbose, aio); long nanoseconds = SyncCalculation.toNanos(time, writes); - double writesPerMillisecond = (double)writes / (double) time; + double writesPerMillisecond = (double) writes / (double) time; String writesPerMillisecondStr = new DecimalFormat("###.##").format(writesPerMillisecond); @@ -757,13 +663,12 @@ public class Create extends InputAbstract syncFilter.put("${writesPerMillisecond}", writesPerMillisecondStr); System.out.println("done! Your system can make " + writesPerMillisecondStr + - " writes per millisecond, your journal-buffer-timeout will be " + nanoseconds); + " writes per millisecond, your journal-buffer-timeout will be " + nanoseconds); filters.put("${journal-buffer.settings}", applyFilters(readTextFile(ETC_JOURNAL_BUFFER_SETTINGS), syncFilter)); } - catch (Exception e) - { + catch (Exception e) { filters.put("${journal-buffer.settings}", ""); e.printStackTrace(); System.err.println("Couldn't perform sync calculation, using default values"); @@ -771,105 +676,80 @@ public class Create extends InputAbstract } } - private boolean supportsLibaio() - { - if (LibaioContext.isLoaded()) - { - try (LibaioContext context = new LibaioContext(1, true)) - { + private boolean supportsLibaio() { + if (LibaioContext.isLoaded()) { + try (LibaioContext context = new LibaioContext(1, true)) { File tmpFile = new File(directory, "validateAIO.bin"); boolean supportsLibaio = true; - try - { + try { LibaioFile file = context.openFile(tmpFile, true); file.close(); } - catch (Exception e) - { + catch (Exception e) { supportsLibaio = false; } tmpFile.delete(); - if (!supportsLibaio) - { + if (!supportsLibaio) { System.err.println("The filesystem used on " + directory + " doesn't support libAIO and O_DIRECT files, switching journal-type to NIO"); } return supportsLibaio; } } - else - { + else { return false; } } - private void makeExec(String path) throws IOException - { - try - { + private void makeExec(String path) throws IOException { + try { File file = new File(directory, path); - Files.setPosixFilePermissions(file.toPath(), new HashSet(Arrays.asList( - OWNER_READ, OWNER_WRITE, OWNER_EXECUTE, - GROUP_READ, GROUP_WRITE, GROUP_EXECUTE, - OTHERS_READ, OTHERS_EXECUTE - ))); + Files.setPosixFilePermissions(file.toPath(), new HashSet(Arrays.asList(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE, GROUP_READ, GROUP_WRITE, GROUP_EXECUTE, OTHERS_READ, OTHERS_EXECUTE))); } - catch (Throwable ignore) - { + catch (Throwable ignore) { // Our best effort was not good enough :) } } - - private String[] getQueueList() - { - if (queues == null) - { + private String[] getQueueList() { + if (queues == null) { return new String[0]; } - else - { + else { return queues.split(","); } } - private String[] getTopicList() - { - if (topics == null) - { + private String[] getTopicList() { + if (topics == null) { return new String[0]; } - else - { + else { return topics.split(","); } } - String path(String value, boolean unixPaths) throws IOException - { + String path(String value, boolean unixPaths) throws IOException { return path(new File(value), unixPaths); } - private String path(File value, boolean unixPaths) throws IOException - { - if (unixPaths && IS_CYGWIN) - { + private String path(File value, boolean unixPaths) throws IOException { + if (unixPaths && IS_CYGWIN) { return value.getCanonicalPath(); } - else - { + else { return value.getCanonicalPath(); } } - private void write(String source, HashMap filters, boolean unixTarget) throws IOException - { + private void write(String source, HashMap filters, boolean unixTarget) throws IOException { write(source, new File(directory, source), filters, unixTarget); } - private void write(String source, File target, HashMap filters, boolean unixTarget) throws IOException - { - if (target.exists() && !force) - { + private void write(String source, + File target, + HashMap filters, + boolean unixTarget) throws IOException { + if (target.exists() && !force) { throw new RuntimeException(String.format("The file '%s' already exists. Use --force to overwrite.", target)); } @@ -881,62 +761,49 @@ public class Create extends InputAbstract content = content.replaceAll("\\r?\\n", Matcher.quoteReplacement(separator)); ByteArrayInputStream in = new ByteArrayInputStream(content.getBytes(encoding)); - try (FileOutputStream fout = new FileOutputStream(target)) - { + try (FileOutputStream fout = new FileOutputStream(target)) { copy(in, fout); } } - private String applyFilters(String content, HashMap filters) throws IOException - { + private String applyFilters(String content, HashMap filters) throws IOException { - if (filters != null) - { - for (Map.Entry entry : filters.entrySet()) - { + if (filters != null) { + for (Map.Entry entry : filters.entrySet()) { content = replace(content, entry.getKey(), entry.getValue()); } } return content; } - private String readTextFile(String source) throws IOException - { + private String readTextFile(String source) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); - try (InputStream in = openStream(source)) - { + try (InputStream in = openStream(source)) { copy(in, out); } return new String(out.toByteArray(), "UTF-8"); } - private void write(String source) throws IOException - { + private void write(String source) throws IOException { File target = new File(directory, source); - if (target.exists() && !force) - { + if (target.exists() && !force) { throw new RuntimeException(String.format("The file '%s' already exists. Use --force to overwrite.", target)); } - try (FileOutputStream fout = new FileOutputStream(target)) - { - try (InputStream in = openStream(source)) - { + try (FileOutputStream fout = new FileOutputStream(target)) { + try (InputStream in = openStream(source)) { copy(in, fout); } } } - private String replace(String content, String key, String value) - { + private String replace(String content, String key, String value) { return content.replaceAll(Pattern.quote(key), Matcher.quoteReplacement(value)); } - private void copy(InputStream is, OutputStream os) throws IOException - { + private void copy(InputStream is, OutputStream os) throws IOException { byte[] buffer = new byte[1024 * 4]; int c = is.read(buffer); - while (c >= 0) - { + while (c >= 0) { os.write(buffer, 0, c); c = is.read(buffer); } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/DestAbstract.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/DestAbstract.java index 402f0d98e9..07339669f0 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/DestAbstract.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/DestAbstract.java @@ -17,10 +17,10 @@ package org.apache.activemq.artemis.cli.commands; - import io.airlift.airline.Option; +import io.airlift.airline.Option; + +public class DestAbstract extends ActionAbstract { -public class DestAbstract extends ActionAbstract -{ @Option(name = "--url", description = "URL towards the broker. (default: tcp://localhost:61616)") String brokerURL = "tcp://localhost:61616"; diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/HelpAction.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/HelpAction.java index eecf9c6bc2..41f91f9944 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/HelpAction.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/HelpAction.java @@ -20,35 +20,30 @@ import java.io.File; import io.airlift.airline.Help; -public class HelpAction extends Help implements Action -{ +public class HelpAction extends Help implements Action { + @Override - public boolean isVerbose() - { + public boolean isVerbose() { return false; } @Override - public void setHomeValues(File brokerHome, File brokerInstance) - { + public void setHomeValues(File brokerHome, File brokerInstance) { } @Override - public String getBrokerInstance() - { + public String getBrokerInstance() { return null; } @Override - public String getBrokerHome() - { + public String getBrokerHome() { return null; } @Override - public Object execute(ActionContext context) throws Exception - { + public Object execute(ActionContext context) throws Exception { super.run(); return null; } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/InputAbstract.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/InputAbstract.java index f5180ef17e..c6adf5d0f4 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/InputAbstract.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/InputAbstract.java @@ -21,86 +21,70 @@ import java.util.Scanner; import io.airlift.airline.Option; -public class InputAbstract extends ActionAbstract -{ +public class InputAbstract extends ActionAbstract { private Scanner scanner; @Option(name = "--silent", description = "It will disable all the inputs, and it would make a best guess for any required input") private boolean silentInput = false; - public boolean isSilentInput() - { + public boolean isSilentInput() { return silentInput; } - public void setSilentInput(boolean silentInput) - { + public void setSilentInput(boolean silentInput) { this.silentInput = silentInput; } - protected String input(String propertyName, String prompt, String silentDefault) - { - if (silentInput) - { + protected String input(String propertyName, String prompt, String silentDefault) { + if (silentInput) { return silentDefault; } String inputStr; boolean valid = false; System.out.println(); - do - { + do { context.out.println(propertyName + ": is mandatory with this configuration:"); context.out.println(prompt); inputStr = scanner.nextLine(); - if (inputStr.trim().equals("")) - { + if (inputStr.trim().equals("")) { System.out.println("Invalid Entry!"); } - else - { + else { valid = true; } - } - while (!valid); + } while (!valid); return inputStr.trim(); } - protected String inputPassword(String propertyName, String prompt, String silentDefault) - { - if (silentInput) - { + protected String inputPassword(String propertyName, String prompt, String silentDefault) { + if (silentInput) { return silentDefault; } String inputStr; boolean valid = false; System.out.println(); - do - { + do { context.out.println(propertyName + ": is mandatory with this configuration:"); context.out.println(prompt); inputStr = new String(System.console().readPassword()); - if (inputStr.trim().equals("")) - { + if (inputStr.trim().equals("")) { System.out.println("Invalid Entry!"); } - else - { + else { valid = true; } - } - while (!valid); + } while (!valid); return inputStr.trim(); } @Override - public Object execute(ActionContext context) throws Exception - { + public Object execute(ActionContext context) throws Exception { super.execute(context); this.scanner = new Scanner(context.in); diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Kill.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Kill.java index 8f8ac8088e..73a7e427cf 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Kill.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Kill.java @@ -22,11 +22,10 @@ import io.airlift.airline.Command; import org.apache.activemq.artemis.dto.BrokerDTO; @Command(name = "kill", description = "Kills a broker instance started with --allow-kill") -public class Kill extends Configurable -{ +public class Kill extends Configurable { + @Override - public Object execute(ActionContext context) throws Exception - { + public Object execute(ActionContext context) throws Exception { super.execute(context); BrokerDTO broker = getBrokerDTO(); diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Producer.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Producer.java index 28194364f5..f1b5889c0f 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Producer.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Producer.java @@ -28,8 +28,7 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; import org.apache.activemq.artemis.jms.client.ActiveMQDestination; @Command(name = "producer", description = "It will send messages to an instance") -public class Producer extends DestAbstract -{ +public class Producer extends DestAbstract { @Option(name = "--non-persistent", description = "It will send messages non persistently") boolean nonpersistent = false; @@ -47,43 +46,36 @@ public class Producer extends DestAbstract String msgGroupID = null; @Override - public Object execute(ActionContext context) throws Exception - { + public Object execute(ActionContext context) throws Exception { super.execute(context); ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURL, user, password); Destination dest = ActiveMQDestination.createDestination(this.destination, ActiveMQDestination.QUEUE_TYPE); - try (Connection connection = factory.createConnection()) - { + try (Connection connection = factory.createConnection()) { ProducerThread[] threadsArray = new ProducerThread[threads]; - for (int i = 0; i < threads; i++) - { + for (int i = 0; i < threads; i++) { Session session; - if (txBatchSize > 0) - { + if (txBatchSize > 0) { session = connection.createSession(true, Session.SESSION_TRANSACTED); } - else - { + else { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } threadsArray[i] = new ProducerThread(session, dest, i); threadsArray[i].setVerbose(verbose).setSleep(sleep).setPersistent(!nonpersistent). - setMessageSize(messageSize).setTextMessageSize(textMessageSize). - setMsgTTL(msgTTL).setMsgGroupID(msgGroupID).setTransactionBatchSize(txBatchSize). - setMessageCount(messageCount); + setMessageSize(messageSize).setTextMessageSize(textMessageSize). + setMsgTTL(msgTTL).setMsgGroupID(msgGroupID).setTransactionBatchSize(txBatchSize). + setMessageCount(messageCount); } - for (ProducerThread thread : threadsArray) - { + for (ProducerThread thread : threadsArray) { thread.start(); } int messagesProduced = 0; - for (ProducerThread thread : threadsArray) - { + for (ProducerThread thread : threadsArray) { thread.join(); messagesProduced += thread.getSentCount(); } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Run.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Run.java index 67824ce757..222d903d3e 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Run.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Run.java @@ -37,8 +37,8 @@ import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManager; import org.apache.activemq.artemis.utils.ReusableLatch; @Command(name = "run", description = "runs the broker instance") -public class Run extends Configurable -{ +public class Run extends Configurable { + @Option(name = "--allow-kill", description = "This will allow the server to kill itself. Useful for tests (failover tests for instance)") boolean allowKill; @@ -49,10 +49,10 @@ public class Run extends Configurable /** * This will disable the System.exit at the end of the server.stop, as that means there are other things * happening on the same VM. + * * @param embedded */ - public static void setEmbedded(boolean embedded) - { + public static void setEmbedded(boolean embedded) { Run.embedded = true; } @@ -61,8 +61,7 @@ public class Run extends Configurable private ArrayList components = new ArrayList<>(); @Override - public Object execute(ActionContext context) throws Exception - { + public Object execute(ActionContext context) throws Exception { super.execute(context); Artemis.printBanner(); @@ -79,15 +78,13 @@ public class Run extends Configurable server.start(); - if (broker.web != null) - { + if (broker.web != null) { broker.components.add(broker.web); } - for (ComponentDTO componentDTO : broker.components) - { + for (ComponentDTO componentDTO : broker.components) { Class clazz = this.getClass().getClassLoader().loadClass(componentDTO.componentClassName); - ExternalComponent component = (ExternalComponent)clazz.newInstance(); + ExternalComponent component = (ExternalComponent) clazz.newInstance(); component.configure(componentDTO, getBrokerInstance(), getBrokerHome()); component.start(); components.add(component); @@ -96,9 +93,7 @@ public class Run extends Configurable return null; } - - private void createDirectories(FileConfiguration fileConfiguration) - { + private void createDirectories(FileConfiguration fileConfiguration) { fileConfiguration.getPagingLocation().mkdirs(); fileConfiguration.getJournalLocation().mkdirs(); fileConfiguration.getBindingsLocation().mkdirs(); @@ -107,68 +102,53 @@ public class Run extends Configurable /** * Add a simple shutdown hook to stop the server. + * * @param configurationDir */ - private void addShutdownHook(File configurationDir) - { + private void addShutdownHook(File configurationDir) { latchRunning.countUp(); - final File file = new File(configurationDir,"STOP_ME"); - if (file.exists()) - { - if (!file.delete()) - { + final File file = new File(configurationDir, "STOP_ME"); + if (file.exists()) { + if (!file.delete()) { ActiveMQBootstrapLogger.LOGGER.errorDeletingFile(file.getAbsolutePath()); } } - final File fileKill = new File(configurationDir,"KILL_ME"); - if (fileKill.exists()) - { - if (!fileKill.delete()) - { + final File fileKill = new File(configurationDir, "KILL_ME"); + if (fileKill.exists()) { + if (!fileKill.delete()) { ActiveMQBootstrapLogger.LOGGER.errorDeletingFile(fileKill.getAbsolutePath()); } } final Timer timer = new Timer("ActiveMQ Artemis Server Shutdown Timer", true); - timer.scheduleAtFixedRate(new TimerTask() - { + timer.scheduleAtFixedRate(new TimerTask() { @Override - public void run() - { - if (allowKill && fileKill.exists()) - { - try - { + public void run() { + if (allowKill && fileKill.exists()) { + try { System.err.println("Halting by user request"); fileKill.delete(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } Runtime.getRuntime().halt(0); } - if (file.exists()) - { - try - { - try - { + if (file.exists()) { + try { + try { server.stop(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } timer.cancel(); } - finally - { + finally { System.out.println("Server stopped!"); System.out.flush(); latchRunning.countDown(); - if (!embedded) - { + if (!embedded) { Runtime.getRuntime().exit(0); } } @@ -176,17 +156,12 @@ public class Run extends Configurable } }, 500, 500); - - Runtime.getRuntime().addShutdownHook(new Thread() - { - public void run() - { - try - { + Runtime.getRuntime().addShutdownHook(new Thread() { + public void run() { + try { server.stop(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Stop.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Stop.java index cf609ce7a2..5f89253707 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Stop.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/Stop.java @@ -22,11 +22,10 @@ import io.airlift.airline.Command; import org.apache.activemq.artemis.dto.BrokerDTO; @Command(name = "stop", description = "stops the broker instance") -public class Stop extends Configurable -{ +public class Stop extends Configurable { + @Override - public Object execute(ActionContext context) throws Exception - { + public Object execute(ActionContext context) throws Exception { super.execute(context); BrokerDTO broker = getBrokerDTO(); diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/CompactJournal.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/CompactJournal.java index 38fb785609..af553455a2 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/CompactJournal.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/CompactJournal.java @@ -27,33 +27,28 @@ import org.apache.activemq.artemis.core.journal.impl.JournalImpl; import org.apache.activemq.artemis.core.io.nio.NIOSequentialFileFactory; @Command(name = "compact", description = "Compacts the journal of a non running server") -public final class CompactJournal extends DataAbstract implements Action -{ +public final class CompactJournal extends DataAbstract implements Action { + @Override - public Object execute(ActionContext context) throws Exception - { + public Object execute(ActionContext context) throws Exception { super.execute(context); - try - { + try { Configuration configuration = getFileConfiguration(); compactJournal(new File(getJournal()), "activemq-data", "amq", configuration.getJournalMinFiles(), configuration.getJournalFileSize(), null); compactJournal(new File(getBinding()), "activemq-bindings", "bindings", 2, 1048576, null); } - catch (Exception e) - { + catch (Exception e) { treatError(e, "data", "compact"); } return null; } - void compactJournal(final File directory, - final String journalPrefix, - final String journalSuffix, - final int minFiles, - final int fileSize, - final IOCriticalErrorListener listener) throws Exception - { + final String journalPrefix, + final String journalSuffix, + final int minFiles, + final int fileSize, + final IOCriticalErrorListener listener) throws Exception { NIOSequentialFileFactory nio = new NIOSequentialFileFactory(directory, listener, 1); JournalImpl journal = new JournalImpl(fileSize, minFiles, 0, 0, nio, journalPrefix, journalSuffix, 1); diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/DataAbstract.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/DataAbstract.java index ecd2e377ef..c08dd44841 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/DataAbstract.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/DataAbstract.java @@ -22,9 +22,11 @@ import java.io.File; import io.airlift.airline.Option; import org.apache.activemq.artemis.cli.commands.Configurable; -/** Abstract class for places where you need bindings, journal paging and large messages configuration */ -public abstract class DataAbstract extends Configurable -{ +/** + * Abstract class for places where you need bindings, journal paging and large messages configuration + */ +public abstract class DataAbstract extends Configurable { + @Option(name = "--bindings", description = "The folder used for bindings (default from broker.xml)") public String binding; @@ -37,11 +39,8 @@ public abstract class DataAbstract extends Configurable @Option(name = "--large-messages", description = "The folder used for large-messages (default from broker.xml)") public String largeMessges; - - public String getLargeMessages() throws Exception - { - if (largeMessges == null) - { + public String getLargeMessages() throws Exception { + if (largeMessges == null) { largeMessges = getFileConfiguration().getLargeMessagesLocation().getAbsolutePath(); } @@ -50,11 +49,8 @@ public abstract class DataAbstract extends Configurable return largeMessges; } - - public String getBinding() throws Exception - { - if (binding == null) - { + public String getBinding() throws Exception { + if (binding == null) { binding = getFileConfiguration().getBindingsLocation().getAbsolutePath(); } @@ -63,10 +59,8 @@ public abstract class DataAbstract extends Configurable return binding; } - public String getJournal() throws Exception - { - if (journal == null) - { + public String getJournal() throws Exception { + if (journal == null) { journal = getFileConfiguration().getJournalLocation().getAbsolutePath(); } @@ -75,10 +69,8 @@ public abstract class DataAbstract extends Configurable return journal; } - public String getPaging() throws Exception - { - if (paging == null) - { + public String getPaging() throws Exception { + if (paging == null) { paging = getFileConfiguration().getPagingLocation().getAbsolutePath(); } @@ -87,11 +79,9 @@ public abstract class DataAbstract extends Configurable return paging; } - private void checkIfDirectoryExists(String directory) - { + private void checkIfDirectoryExists(String directory) { File f = new File(directory); - if (!f.exists()) - { + if (!f.exists()) { throw new IllegalStateException("Could not find folder: " + directory + ", please pass --bindings, --journal and --paging as arguments"); } } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/DecodeJournal.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/DecodeJournal.java index 6b608c3480..6b20a735f8 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/DecodeJournal.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/DecodeJournal.java @@ -39,8 +39,7 @@ import org.apache.activemq.artemis.core.io.nio.NIOSequentialFileFactory; import org.apache.activemq.artemis.utils.Base64; @Command(name = "decode", description = "Decode a journal's internal format into a new journal set of files") -public class DecodeJournal extends Configurable implements Action -{ +public class DecodeJournal extends Configurable implements Action { @Option(name = "--directory", description = "The journal folder (default journal folder from broker.xml)") public String directory; @@ -57,34 +56,27 @@ public class DecodeJournal extends Configurable implements Action @Option(name = "--input", description = "The input file name (default=exp.dmp)", required = true) public String input = "exp.dmp"; - public Object execute(ActionContext context) throws Exception - { + public Object execute(ActionContext context) throws Exception { super.execute(context); - try - { - if (directory == null) - { + try { + if (directory == null) { directory = getFileConfiguration().getJournalDirectory(); } importJournal(directory, prefix, suffix, 2, size, input); } - catch (Exception e) - { + catch (Exception e) { treatError(e, "data", "decode"); } return null; } - - public static void importJournal(final String directory, final String journalPrefix, final String journalSuffix, final int minFiles, final int fileSize, - final String fileInput) throws Exception - { + final String fileInput) throws Exception { FileInputStream fileInputStream = new FileInputStream(new File(fileInput)); importJournal(directory, journalPrefix, journalSuffix, minFiles, fileSize, fileInputStream); @@ -95,8 +87,7 @@ public class DecodeJournal extends Configurable implements Action final String journalSuffix, final int minFiles, final int fileSize, - final InputStream stream) throws Exception - { + final InputStream stream) throws Exception { Reader reader = new InputStreamReader(stream); importJournal(directory, journalPrefix, journalSuffix, minFiles, fileSize, reader); } @@ -106,13 +97,11 @@ public class DecodeJournal extends Configurable implements Action final String journalSuffix, final int minFiles, final int fileSize, - final Reader reader) throws Exception - { + final Reader reader) throws Exception { File journalDir = new File(directory); - if (!journalDir.exists()) - { + if (!journalDir.exists()) { if (!journalDir.mkdirs()) System.err.println("Could not create directory " + directory); } @@ -121,8 +110,7 @@ public class DecodeJournal extends Configurable implements Action JournalImpl journal = new JournalImpl(fileSize, minFiles, 0, 0, nio, journalPrefix, journalSuffix, 1); - if (journal.orderFiles().size() != 0) - { + if (journal.orderFiles().size() != 0) { throw new IllegalStateException("Import needs to create a brand new journal"); } @@ -141,12 +129,10 @@ public class DecodeJournal extends Configurable implements Action Map journalRecords = journal.getRecords(); - while ((line = buffReader.readLine()) != null) - { + while ((line = buffReader.readLine()) != null) { lineNumber++; String[] splitLine = line.split(","); - if (splitLine[0].equals("#File")) - { + if (splitLine[0].equals("#File")) { txCounters.clear(); continue; } @@ -154,121 +140,102 @@ public class DecodeJournal extends Configurable implements Action Properties lineProperties = parseLine(splitLine); String operation = null; - try - { + try { operation = lineProperties.getProperty("operation"); - if (operation.equals("AddRecord")) - { + if (operation.equals("AddRecord")) { RecordInfo info = parseRecord(lineProperties); journal.appendAddRecord(info.id, info.userRecordType, info.data, false); } - else if (operation.equals("AddRecordTX")) - { + else if (operation.equals("AddRecordTX")) { long txID = parseLong("txID", lineProperties); AtomicInteger counter = getCounter(txID, txCounters); counter.incrementAndGet(); RecordInfo info = parseRecord(lineProperties); journal.appendAddRecordTransactional(txID, info.id, info.userRecordType, info.data); } - else if (operation.equals("AddRecordTX")) - { + else if (operation.equals("AddRecordTX")) { long txID = parseLong("txID", lineProperties); AtomicInteger counter = getCounter(txID, txCounters); counter.incrementAndGet(); RecordInfo info = parseRecord(lineProperties); journal.appendAddRecordTransactional(txID, info.id, info.userRecordType, info.data); } - else if (operation.equals("UpdateTX")) - { + else if (operation.equals("UpdateTX")) { long txID = parseLong("txID", lineProperties); AtomicInteger counter = getCounter(txID, txCounters); counter.incrementAndGet(); RecordInfo info = parseRecord(lineProperties); journal.appendUpdateRecordTransactional(txID, info.id, info.userRecordType, info.data); } - else if (operation.equals("Update")) - { + else if (operation.equals("Update")) { RecordInfo info = parseRecord(lineProperties); journal.appendUpdateRecord(info.id, info.userRecordType, info.data, false); } - else if (operation.equals("DeleteRecord")) - { + else if (operation.equals("DeleteRecord")) { long id = parseLong("id", lineProperties); // If not found it means the append/update records were reclaimed already - if (journalRecords.get(id) != null) - { + if (journalRecords.get(id) != null) { journal.appendDeleteRecord(id, false); } } - else if (operation.equals("DeleteRecordTX")) - { + else if (operation.equals("DeleteRecordTX")) { long txID = parseLong("txID", lineProperties); long id = parseLong("id", lineProperties); AtomicInteger counter = getCounter(txID, txCounters); counter.incrementAndGet(); // If not found it means the append/update records were reclaimed already - if (journalRecords.get(id) != null) - { + if (journalRecords.get(id) != null) { journal.appendDeleteRecordTransactional(txID, id); } } - else if (operation.equals("Prepare")) - { + else if (operation.equals("Prepare")) { long txID = parseLong("txID", lineProperties); int numberOfRecords = parseInt("numberOfRecords", lineProperties); AtomicInteger counter = getCounter(txID, txCounters); byte[] data = parseEncoding("extraData", lineProperties); - if (counter.get() == numberOfRecords) - { + if (counter.get() == numberOfRecords) { journal.appendPrepareRecord(txID, data, false); } - else - { + else { System.err.println("Transaction " + txID + - " at line " + - lineNumber + - " is incomplete. The prepare record expected " + - numberOfRecords + - " while the import only had " + - counter); + " at line " + + lineNumber + + " is incomplete. The prepare record expected " + + numberOfRecords + + " while the import only had " + + counter); } } - else if (operation.equals("Commit")) - { + else if (operation.equals("Commit")) { long txID = parseLong("txID", lineProperties); int numberOfRecords = parseInt("numberOfRecords", lineProperties); AtomicInteger counter = getCounter(txID, txCounters); - if (counter.get() == numberOfRecords) - { + if (counter.get() == numberOfRecords) { journal.appendCommitRecord(txID, false); } - else - { + else { System.err.println("Transaction " + txID + - " at line " + - lineNumber + - " is incomplete. The commit record expected " + - numberOfRecords + - " while the import only had " + - counter); + " at line " + + lineNumber + + " is incomplete. The commit record expected " + + numberOfRecords + + " while the import only had " + + counter); } } - else if (operation.equals("Rollback")) - { + else if (operation.equals("Rollback")) { long txID = parseLong("txID", lineProperties); journal.appendRollbackRecord(txID, false); } - else - { + else { System.err.println("Invalid operation " + operation + " at line " + lineNumber); } } - catch (Exception ex) - { + catch (Exception ex) { System.err.println("Error at line " + lineNumber + ", operation=" + operation + " msg = " + ex.getMessage()); } } @@ -276,12 +243,10 @@ public class DecodeJournal extends Configurable implements Action journal.stop(); } - protected static AtomicInteger getCounter(final Long txID, final Map txCounters) - { + protected static AtomicInteger getCounter(final Long txID, final Map txCounters) { AtomicInteger counter = txCounters.get(txID); - if (counter == null) - { + if (counter == null) { counter = new AtomicInteger(0); txCounters.put(txID, counter); } @@ -289,17 +254,15 @@ public class DecodeJournal extends Configurable implements Action return counter; } - protected static RecordInfo parseRecord(final Properties properties) throws Exception - { + protected static RecordInfo parseRecord(final Properties properties) throws Exception { long id = parseLong("id", properties); byte userRecordType = parseByte("userRecordType", properties); boolean isUpdate = parseBoolean("isUpdate", properties); byte[] data = parseEncoding("data", properties); - return new RecordInfo(id, userRecordType, data, isUpdate, (short)0); + return new RecordInfo(id, userRecordType, data, isUpdate, (short) 0); } - private static byte[] parseEncoding(final String name, final Properties properties) throws Exception - { + private static byte[] parseEncoding(final String name, final Properties properties) throws Exception { String value = parseString(name, properties); return decode(value); @@ -309,29 +272,25 @@ public class DecodeJournal extends Configurable implements Action * @param properties * @return */ - private static int parseInt(final String name, final Properties properties) throws Exception - { + private static int parseInt(final String name, final Properties properties) throws Exception { String value = parseString(name, properties); return Integer.parseInt(value); } - private static long parseLong(final String name, final Properties properties) throws Exception - { + private static long parseLong(final String name, final Properties properties) throws Exception { String value = parseString(name, properties); return Long.parseLong(value); } - private static boolean parseBoolean(final String name, final Properties properties) throws Exception - { + private static boolean parseBoolean(final String name, final Properties properties) throws Exception { String value = parseString(name, properties); return Boolean.parseBoolean(value); } - private static byte parseByte(final String name, final Properties properties) throws Exception - { + private static byte parseByte(final String name, final Properties properties) throws Exception { String value = parseString(name, properties); return Byte.parseByte(value); @@ -343,30 +302,24 @@ public class DecodeJournal extends Configurable implements Action * @return * @throws Exception */ - private static String parseString(final String name, final Properties properties) throws Exception - { + private static String parseString(final String name, final Properties properties) throws Exception { String value = properties.getProperty(name); - if (value == null) - { + if (value == null) { throw new Exception("property " + name + " not found"); } return value; } - protected static Properties parseLine(final String[] splitLine) - { + protected static Properties parseLine(final String[] splitLine) { Properties properties = new Properties(); - for (String el : splitLine) - { + for (String el : splitLine) { String[] tuple = el.split("@"); - if (tuple.length == 2) - { + if (tuple.length == 2) { properties.put(tuple[0], tuple[1]); } - else - { + else { properties.put(tuple[0], tuple[0]); } } @@ -374,23 +327,18 @@ public class DecodeJournal extends Configurable implements Action return properties; } - private static byte[] decode(final String data) - { + private static byte[] decode(final String data) { return Base64.decode(data, Base64.DONT_BREAK_LINES | Base64.URL_SAFE); } - - public void printUsage() - { - for (int i = 0; i < 10; i++) - { + public void printUsage() { + for (int i = 0; i < 10; i++) { System.err.println(); } System.err.println("This method will export the journal at low level record."); System.err.println(); System.err.println(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { System.err.println(); } } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/EncodeJournal.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/EncodeJournal.java index a408951f72..33953e9c6f 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/EncodeJournal.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/EncodeJournal.java @@ -36,8 +36,7 @@ import org.apache.activemq.artemis.core.io.nio.NIOSequentialFileFactory; import org.apache.activemq.artemis.utils.Base64; @Command(name = "encode", description = "Encode a set of journal files into an internal encoded data format") -public class EncodeJournal extends Configurable implements Action -{ +public class EncodeJournal extends Configurable implements Action { @Option(name = "--directory", description = "The journal folder (default the journal folder from broker.xml)") public String directory; @@ -51,59 +50,48 @@ public class EncodeJournal extends Configurable implements Action @Option(name = "--file-size", description = "The journal size (default 10485760)") public int size = 10485760; - - public Object execute(ActionContext context) throws Exception - { + public Object execute(ActionContext context) throws Exception { super.execute(context); - try - { - if (directory == null) - { + try { + if (directory == null) { directory = getFileConfiguration().getJournalDirectory(); } exportJournal(directory, prefix, suffix, 2, size); } - catch (Exception e) - { + catch (Exception e) { treatError(e, "data", "encode"); } return null; } - public static void exportJournal(final String directory, final String journalPrefix, final String journalSuffix, final int minFiles, - final int fileSize) throws Exception - { - + final int fileSize) throws Exception { exportJournal(directory, journalPrefix, journalSuffix, minFiles, fileSize, System.out); } + public static void exportJournal(final String directory, final String journalPrefix, final String journalSuffix, final int minFiles, final int fileSize, - final String fileName) throws Exception - { + final String fileName) throws Exception { FileOutputStream fileOutputStream = new FileOutputStream(fileName); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream); PrintStream out = new PrintStream(bufferedOutputStream); - try - { + try { exportJournal(directory, journalPrefix, journalSuffix, minFiles, fileSize, out); } - finally - { + finally { out.close(); fileOutputStream.close(); } - } public static void exportJournal(final String directory, @@ -111,16 +99,14 @@ public class EncodeJournal extends Configurable implements Action final String journalSuffix, final int minFiles, final int fileSize, - final PrintStream out) throws Exception - { + final PrintStream out) throws Exception { NIOSequentialFileFactory nio = new NIOSequentialFileFactory(new File(directory), null, 1); JournalImpl journal = new JournalImpl(fileSize, minFiles, 0, 0, nio, journalPrefix, journalSuffix, 1); List files = journal.orderFiles(); - for (JournalFile file : files) - { + for (JournalFile file : files) { out.println("#File," + file); exportJournalFile(out, nio, file); @@ -135,28 +121,24 @@ public class EncodeJournal extends Configurable implements Action */ public static void exportJournalFile(final PrintStream out, final SequentialFileFactory fileFactory, - final JournalFile file) throws Exception - { - JournalImpl.readJournalFile(fileFactory, file, new JournalReaderCallback() - { + final JournalFile file) throws Exception { + JournalImpl.readJournalFile(fileFactory, file, new JournalReaderCallback() { - public void onReadUpdateRecordTX(final long transactionID, final RecordInfo recordInfo) throws Exception - { + public void onReadUpdateRecordTX(final long transactionID, final RecordInfo recordInfo) throws Exception { out.println("operation@UpdateTX,txID@" + transactionID + "," + describeRecord(recordInfo)); } - public void onReadUpdateRecord(final RecordInfo recordInfo) throws Exception - { + public void onReadUpdateRecord(final RecordInfo recordInfo) throws Exception { out.println("operation@Update," + describeRecord(recordInfo)); } - public void onReadRollbackRecord(final long transactionID) throws Exception - { + public void onReadRollbackRecord(final long transactionID) throws Exception { out.println("operation@Rollback,txID@" + transactionID); } - public void onReadPrepareRecord(final long transactionID, final byte[] extraData, final int numberOfRecords) throws Exception - { + public void onReadPrepareRecord(final long transactionID, + final byte[] extraData, + final int numberOfRecords) throws Exception { out.println("operation@Prepare,txID@" + transactionID + ",numberOfRecords@" + numberOfRecords + @@ -164,41 +146,34 @@ public class EncodeJournal extends Configurable implements Action encode(extraData)); } - public void onReadDeleteRecordTX(final long transactionID, final RecordInfo recordInfo) throws Exception - { + public void onReadDeleteRecordTX(final long transactionID, final RecordInfo recordInfo) throws Exception { out.println("operation@DeleteRecordTX,txID@" + transactionID + "," + describeRecord(recordInfo)); } - public void onReadDeleteRecord(final long recordID) throws Exception - { + public void onReadDeleteRecord(final long recordID) throws Exception { out.println("operation@DeleteRecord,id@" + recordID); } - public void onReadCommitRecord(final long transactionID, final int numberOfRecords) throws Exception - { + public void onReadCommitRecord(final long transactionID, final int numberOfRecords) throws Exception { out.println("operation@Commit,txID@" + transactionID + ",numberOfRecords@" + numberOfRecords); } - public void onReadAddRecordTX(final long transactionID, final RecordInfo recordInfo) throws Exception - { + public void onReadAddRecordTX(final long transactionID, final RecordInfo recordInfo) throws Exception { out.println("operation@AddRecordTX,txID@" + transactionID + "," + describeRecord(recordInfo)); } - public void onReadAddRecord(final RecordInfo recordInfo) throws Exception - { + public void onReadAddRecord(final RecordInfo recordInfo) throws Exception { out.println("operation@AddRecord," + describeRecord(recordInfo)); } - public void markAsDataFile(final JournalFile file) - { + public void markAsDataFile(final JournalFile file) { } }); } - private static String describeRecord(final RecordInfo recordInfo) - { + private static String describeRecord(final RecordInfo recordInfo) { return "id@" + recordInfo.id + ",userRecordType@" + recordInfo.userRecordType + @@ -212,26 +187,20 @@ public class EncodeJournal extends Configurable implements Action encode(recordInfo.data); } - private static String encode(final byte[] data) - { + private static String encode(final byte[] data) { return Base64.encodeBytes(data, 0, data.length, Base64.DONT_BREAK_LINES | Base64.URL_SAFE); } - - public void printUsage() - { - for (int i = 0; i < 10; i++) - { + public void printUsage() { + for (int i = 0; i < 10; i++) { System.err.println(); } System.err.println("This method will export the journal at low level record."); System.err.println(); System.err.println(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { System.err.println(); } } - } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/HelpData.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/HelpData.java index 808d6cca61..43534f34b8 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/HelpData.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/HelpData.java @@ -25,36 +25,30 @@ import io.airlift.airline.Help; import org.apache.activemq.artemis.cli.commands.Action; import org.apache.activemq.artemis.cli.commands.ActionContext; -public class HelpData extends Help implements Action -{ +public class HelpData extends Help implements Action { @Override - public boolean isVerbose() - { + public boolean isVerbose() { return false; } @Override - public void setHomeValues(File brokerHome, File brokerInstance) - { + public void setHomeValues(File brokerHome, File brokerInstance) { } @Override - public String getBrokerInstance() - { + public String getBrokerInstance() { return null; } @Override - public String getBrokerHome() - { + public String getBrokerHome() { return null; } @Override - public Object execute(ActionContext context) throws Exception - { + public Object execute(ActionContext context) throws Exception { List commands = new ArrayList<>(1); commands.add("data"); diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/PrintData.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/PrintData.java index c9d2e10828..68dc5dc9ec 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/PrintData.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/PrintData.java @@ -57,35 +57,29 @@ import org.apache.activemq.artemis.core.settings.impl.HierarchicalObjectReposito import org.apache.activemq.artemis.utils.ExecutorFactory; @Command(name = "print", description = "Print data records information (WARNING: don't use while a production server is running)") -public class PrintData extends DataAbstract implements Action -{ +public class PrintData extends DataAbstract implements Action { + @Override - public Object execute(ActionContext context) throws Exception - { + public Object execute(ActionContext context) throws Exception { super.execute(context); - try - { + try { printData(new File(getBinding()), new File(getJournal()), new File(getPaging())); } - catch (Exception e) - { + catch (Exception e) { treatError(e, "data", "print"); } return null; } - public static void printData(File bindingsDirectory, File messagesDirectory, File pagingDirectory) throws Exception - { + public static void printData(File bindingsDirectory, File messagesDirectory, File pagingDirectory) throws Exception { // Having the version on the data report is an information very useful to understand what happened // When debugging stuff Artemis.printBanner(); File serverLockFile = new File(messagesDirectory, "server.lock"); - if (serverLockFile.isFile()) - { - try - { + if (serverLockFile.isFile()) { + try { FileLockNodeManager fileLock = new FileLockNodeManager(messagesDirectory, false); fileLock.start(); System.out.println("********************************************"); @@ -93,8 +87,7 @@ public class PrintData extends DataAbstract implements Action System.out.println("********************************************"); fileLock.stop(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -103,12 +96,10 @@ public class PrintData extends DataAbstract implements Action System.out.println("B I N D I N G S J O U R N A L"); System.out.println("********************************************"); - try - { + try { DescribeJournal.describeBindingsJournal(bindingsDirectory); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } @@ -118,19 +109,15 @@ public class PrintData extends DataAbstract implements Action System.out.println("********************************************"); DescribeJournal describeJournal = null; - try - { + try { describeJournal = DescribeJournal.describeMessagesJournal(messagesDirectory); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); return; } - - try - { + try { System.out.println(); System.out.println("********************************************"); System.out.println("P A G I N G"); @@ -138,20 +125,15 @@ public class PrintData extends DataAbstract implements Action printPages(pagingDirectory, describeJournal); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); return; } - } - - private static void printPages(File pageDirectory, DescribeJournal describeJournal) - { - try - { + private static void printPages(File pageDirectory, DescribeJournal describeJournal) { + try { PageCursorsInfo cursorACKs = calculateCursorsInfo(describeJournal.getRecords()); @@ -159,17 +141,14 @@ public class PrintData extends DataAbstract implements Action ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1); final ExecutorService executor = Executors.newFixedThreadPool(10); - ExecutorFactory execfactory = new ExecutorFactory() - { + ExecutorFactory execfactory = new ExecutorFactory() { @Override - public Executor getExecutor() - { + public Executor getExecutor() { return executor; } }; final StorageManager sm = new NullStorageManager(); - PagingStoreFactory pageStoreFactory = - new PagingStoreFactoryNIO(sm, pageDirectory, 1000L, scheduled, execfactory, false, null); + PagingStoreFactory pageStoreFactory = new PagingStoreFactoryNIO(sm, pageDirectory, 1000L, scheduled, execfactory, false, null); HierarchicalRepository addressSettingsRepository = new HierarchicalObjectRepository(); addressSettingsRepository.setDefault(new AddressSettings()); PagingManager manager = new PagingManagerImpl(pageStoreFactory, addressSettingsRepository); @@ -178,20 +157,17 @@ public class PrintData extends DataAbstract implements Action SimpleString[] stores = manager.getStoreNames(); - for (SimpleString store : stores) - { + for (SimpleString store : stores) { PagingStore pgStore = manager.getPageStore(store); File folder = null; - if (pgStore != null) - { + if (pgStore != null) { folder = pgStore.getFolder(); } System.out.println("####################################################################################################"); System.out.println("Exploring store " + store + " folder = " + folder); int pgid = (int) pgStore.getFirstPage(); - for (int pg = 0; pg < pgStore.getNumberOfPages(); pg++) - { + for (int pg = 0; pg < pgStore.getNumberOfPages(); pg++) { System.out.println("******* Page " + pgid); Page page = pgStore.createPage(pgid); page.open(); @@ -200,14 +176,12 @@ public class PrintData extends DataAbstract implements Action int msgID = 0; - for (PagedMessage msg : msgs) - { + for (PagedMessage msg : msgs) { msg.initMessage(sm); System.out.print("pg=" + pgid + ", msg=" + msgID + ",pgTX=" + msg.getTransactionID() + ",userMessageID=" + (msg.getMessage().getUserID() != null ? msg.getMessage().getUserID() : "") + ", msg=" + msg.getMessage()); System.out.print(",Queues = "); long[] q = msg.getQueueIDs(); - for (int i = 0; i < q.length; i++) - { + for (int i = 0; i < q.length; i++) { System.out.print(q[i]); PagePosition posCheck = new PagePositionImpl(pgid, msgID); @@ -215,29 +189,23 @@ public class PrintData extends DataAbstract implements Action boolean acked = false; Set positions = cursorACKs.getCursorRecords().get(q[i]); - if (positions != null) - { + if (positions != null) { acked = positions.contains(posCheck); } - if (acked) - { + if (acked) { System.out.print(" (ACK)"); } - if (cursorACKs.getCompletePages(q[i]).contains(Long.valueOf(pgid))) - { + if (cursorACKs.getCompletePages(q[i]).contains(Long.valueOf(pgid))) { System.out.println(" (PG-COMPLETE)"); } - - if (i + 1 < q.length) - { + if (i + 1 < q.length) { System.out.print(","); } } - if (msg.getTransactionID() >= 0 && !pgTXs.contains(msg.getTransactionID())) - { + if (msg.getTransactionID() >= 0 && !pgTXs.contains(msg.getTransactionID())) { System.out.print(", **PG_TX_NOT_FOUND**"); } System.out.println(); @@ -250,65 +218,55 @@ public class PrintData extends DataAbstract implements Action } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } - - /** Calculate the acks on the page system */ - protected static PageCursorsInfo calculateCursorsInfo(List records) throws Exception - { + /** + * Calculate the acks on the page system + */ + protected static PageCursorsInfo calculateCursorsInfo(List records) throws Exception { PageCursorsInfo cursorInfo = new PageCursorsInfo(); - - for (RecordInfo record : records) - { + for (RecordInfo record : records) { byte[] data = record.data; ActiveMQBuffer buff = ActiveMQBuffers.wrappedBuffer(data); - if (record.userRecordType == JournalRecordIds.ACKNOWLEDGE_CURSOR) - { + if (record.userRecordType == JournalRecordIds.ACKNOWLEDGE_CURSOR) { JournalStorageManager.CursorAckRecordEncoding encoding = new JournalStorageManager.CursorAckRecordEncoding(); encoding.decode(buff); Set set = cursorInfo.getCursorRecords().get(encoding.queueID); - if (set == null) - { + if (set == null) { set = new HashSet(); cursorInfo.getCursorRecords().put(encoding.queueID, set); } set.add(encoding.position); } - else if (record.userRecordType == JournalRecordIds.PAGE_CURSOR_COMPLETE) - { + else if (record.userRecordType == JournalRecordIds.PAGE_CURSOR_COMPLETE) { JournalStorageManager.CursorAckRecordEncoding encoding = new JournalStorageManager.CursorAckRecordEncoding(); encoding.decode(buff); Long queueID = Long.valueOf(encoding.queueID); Long pageNR = Long.valueOf(encoding.position.getPageNr()); - if (!cursorInfo.getCompletePages(queueID).add(pageNR)) - { + if (!cursorInfo.getCompletePages(queueID).add(pageNR)) { System.err.println("Page " + pageNR + " has been already set as complete on queue " + queueID); } } - else if (record.userRecordType == JournalRecordIds.PAGE_TRANSACTION) - { - if (record.isUpdate) - { + else if (record.userRecordType == JournalRecordIds.PAGE_TRANSACTION) { + if (record.isUpdate) { JournalStorageManager.PageUpdateTXEncoding pageUpdate = new JournalStorageManager.PageUpdateTXEncoding(); pageUpdate.decode(buff); cursorInfo.getPgTXs().add(pageUpdate.pageTX); } - else - { + else { PageTransactionInfoImpl pageTransactionInfo = new PageTransactionInfoImpl(); pageTransactionInfo.decode(buff); @@ -322,52 +280,42 @@ public class PrintData extends DataAbstract implements Action return cursorInfo; } + private static class PageCursorsInfo { - private static class PageCursorsInfo - { private final Map> cursorRecords = new HashMap>(); private final Set pgTXs = new HashSet(); private final Map> completePages = new HashMap>(); - public PageCursorsInfo() - { + public PageCursorsInfo() { } - /** * @return the pgTXs */ - public Set getPgTXs() - { + public Set getPgTXs() { return pgTXs; } - /** * @return the cursorRecords */ - public Map> getCursorRecords() - { + public Map> getCursorRecords() { return cursorRecords; } - /** * @return the completePages */ - public Map> getCompletePages() - { + public Map> getCompletePages() { return completePages; } - public Set getCompletePages(Long queueID) - { + public Set getCompletePages(Long queueID) { Set completePagesSet = completePages.get(queueID); - if (completePagesSet == null) - { + if (completePagesSet == null) { completePagesSet = new HashSet(); completePages.put(queueID, completePagesSet); } @@ -377,5 +325,4 @@ public class PrintData extends DataAbstract implements Action } - } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/XmlDataConstants.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/XmlDataConstants.java index 5c8f0279ca..6d808c898b 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/XmlDataConstants.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/XmlDataConstants.java @@ -20,12 +20,12 @@ package org.apache.activemq.artemis.cli.commands.tools; * The constants shared by org.apache.activemq.tools.XmlDataImporter and * org.apache.activemq.tools.XmlDataExporter. */ -public final class XmlDataConstants -{ - private XmlDataConstants() - { +public final class XmlDataConstants { + + private XmlDataConstants() { // Utility } + static final String XML_VERSION = "1.0"; static final String DOCUMENT_PARENT = "activemq-journal"; static final String BINDINGS_PARENT = "bindings"; diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/XmlDataExporter.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/XmlDataExporter.java index 3ea76ce406..0d96aae24d 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/XmlDataExporter.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/XmlDataExporter.java @@ -92,8 +92,8 @@ import org.apache.activemq.artemis.utils.Base64; import org.apache.activemq.artemis.utils.ExecutorFactory; @Command(name = "exp", description = "Export all message-data using an XML that could be interpreted by any system.") -public final class XmlDataExporter extends DataAbstract implements Action -{ +public final class XmlDataExporter extends DataAbstract implements Action { + private static final Long LARGE_MESSAGE_CHUNK_SIZE = 1000L; private JournalStorageManager storageManager; @@ -125,37 +125,28 @@ public final class XmlDataExporter extends DataAbstract implements Action long bindingsPrinted = 0L; @Override - public Object execute(ActionContext context) throws Exception - { + public Object execute(ActionContext context) throws Exception { super.execute(context); - try - { + try { process(context.out, getBinding(), getJournal(), getPaging(), getLargeMessages()); } - catch (Exception e) - { + catch (Exception e) { treatError(e, "data", "exp"); } return null; } - - public void process(OutputStream out, String bindingsDir, String journalDir, String pagingDir, - String largeMessagesDir) throws Exception - { - config = new ConfigurationImpl() - .setBindingsDirectory(bindingsDir) - .setJournalDirectory(journalDir) - .setPagingDirectory(pagingDir) - .setLargeMessagesDirectory(largeMessagesDir) - .setJournalType(JournalType.NIO); + public void process(OutputStream out, + String bindingsDir, + String journalDir, + String pagingDir, + String largeMessagesDir) throws Exception { + config = new ConfigurationImpl().setBindingsDirectory(bindingsDir).setJournalDirectory(journalDir).setPagingDirectory(pagingDir).setLargeMessagesDirectory(largeMessagesDir).setJournalType(JournalType.NIO); final ExecutorService executor = Executors.newFixedThreadPool(1); - ExecutorFactory executorFactory = new ExecutorFactory() - { + ExecutorFactory executorFactory = new ExecutorFactory() { @Override - public Executor getExecutor() - { + public Executor getExecutor() { return executor; } }; @@ -165,16 +156,12 @@ public final class XmlDataExporter extends DataAbstract implements Action XMLOutputFactory factory = XMLOutputFactory.newInstance(); XMLStreamWriter rawXmlWriter = factory.createXMLStreamWriter(out, "UTF-8"); PrettyPrintHandler handler = new PrettyPrintHandler(rawXmlWriter); - xmlWriter = (XMLStreamWriter) Proxy.newProxyInstance( - XMLStreamWriter.class.getClassLoader(), - new Class[]{XMLStreamWriter.class}, - handler); + xmlWriter = (XMLStreamWriter) Proxy.newProxyInstance(XMLStreamWriter.class.getClassLoader(), new Class[]{XMLStreamWriter.class}, handler); writeXMLData(); } - private void writeXMLData() throws Exception - { + private void writeXMLData() throws Exception { long start = System.currentTimeMillis(); getBindings(); getJmsBindings(); @@ -190,8 +177,7 @@ public final class XmlDataExporter extends DataAbstract implements Action * * @throws Exception will be thrown if anything goes wrong reading the journal */ - private void processMessageJournal() throws Exception - { + private void processMessageJournal() throws Exception { ArrayList acks = new ArrayList<>(); List records = new LinkedList<>(); @@ -206,35 +192,29 @@ public final class XmlDataExporter extends DataAbstract implements Action messageJournal.start(); // Just logging these, no action necessary - TransactionFailureCallback transactionFailureCallback = new TransactionFailureCallback() - { + TransactionFailureCallback transactionFailureCallback = new TransactionFailureCallback() { @Override - public void failedTransaction(long transactionID, List records1, List recordsToDelete) - { + public void failedTransaction(long transactionID, + List records1, + List recordsToDelete) { StringBuilder message = new StringBuilder(); message.append("Encountered failed journal transaction: ").append(transactionID); - for (int i = 0; i < records1.size(); i++) - { - if (i == 0) - { + for (int i = 0; i < records1.size(); i++) { + if (i == 0) { message.append("; Records: "); } message.append(records1.get(i)); - if (i != (records1.size() - 1)) - { + if (i != (records1.size() - 1)) { message.append(", "); } } - for (int i = 0; i < recordsToDelete.size(); i++) - { - if (i == 0) - { + for (int i = 0; i < recordsToDelete.size(); i++) { + if (i == 0) { message.append("; RecordsToDelete: "); } message.append(recordsToDelete.get(i)); - if (i != (recordsToDelete.size() - 1)) - { + if (i != (recordsToDelete.size() - 1)) { message.append(", "); } } @@ -248,66 +228,54 @@ public final class XmlDataExporter extends DataAbstract implements Action // Since we don't use these nullify the reference so that the garbage collector can clean them up preparedTransactions = null; - for (RecordInfo info : records) - { + for (RecordInfo info : records) { byte[] data = info.data; ActiveMQBuffer buff = ActiveMQBuffers.wrappedBuffer(data); Object o = DescribeJournal.newObjectEncoding(info, storageManager); - if (info.getUserRecordType() == JournalRecordIds.ADD_MESSAGE) - { + if (info.getUserRecordType() == JournalRecordIds.ADD_MESSAGE) { messages.put(info.id, ((MessageDescribe) o).getMsg()); } - else if (info.getUserRecordType() == JournalRecordIds.ADD_LARGE_MESSAGE) - { + else if (info.getUserRecordType() == JournalRecordIds.ADD_LARGE_MESSAGE) { messages.put(info.id, ((MessageDescribe) o).getMsg()); } - else if (info.getUserRecordType() == JournalRecordIds.ADD_REF) - { + else if (info.getUserRecordType() == JournalRecordIds.ADD_REF) { ReferenceDescribe ref = (ReferenceDescribe) o; HashMap map = messageRefs.get(info.id); - if (map == null) - { + if (map == null) { HashMap newMap = new HashMap<>(); newMap.put(ref.refEncoding.queueID, ref); messageRefs.put(info.id, newMap); } - else - { + else { map.put(ref.refEncoding.queueID, ref); } } - else if (info.getUserRecordType() == JournalRecordIds.ACKNOWLEDGE_REF) - { + else if (info.getUserRecordType() == JournalRecordIds.ACKNOWLEDGE_REF) { acks.add(info); } - else if (info.userRecordType == JournalRecordIds.ACKNOWLEDGE_CURSOR) - { + else if (info.userRecordType == JournalRecordIds.ACKNOWLEDGE_CURSOR) { CursorAckRecordEncoding encoding = new CursorAckRecordEncoding(); encoding.decode(buff); Set set = cursorRecords.get(encoding.queueID); - if (set == null) - { + if (set == null) { set = new HashSet<>(); cursorRecords.put(encoding.queueID, set); } set.add(encoding.position); } - else if (info.userRecordType == JournalRecordIds.PAGE_TRANSACTION) - { - if (info.isUpdate) - { + else if (info.userRecordType == JournalRecordIds.PAGE_TRANSACTION) { + if (info.isUpdate) { PageUpdateTXEncoding pageUpdate = new PageUpdateTXEncoding(); pageUpdate.decode(buff); pgTXs.add(pageUpdate.pageTX); } - else - { + else { PageTransactionInfoImpl pageTransactionInfo = new PageTransactionInfoImpl(); pageTransactionInfo.decode(buff); @@ -328,33 +296,22 @@ public final class XmlDataExporter extends DataAbstract implements Action * * @param acks the list of ack records we got from the journal */ - private void removeAcked(ArrayList acks) - { - for (RecordInfo info : acks) - { + private void removeAcked(ArrayList acks) { + for (RecordInfo info : acks) { AckDescribe ack = (AckDescribe) DescribeJournal.newObjectEncoding(info, null); HashMap referenceDescribeHashMap = messageRefs.get(info.id); referenceDescribeHashMap.remove(ack.refEncoding.queueID); - if (referenceDescribeHashMap.size() == 0) - { + if (referenceDescribeHashMap.size() == 0) { messages.remove(info.id); messageRefs.remove(info.id); } } } - private void getJmsBindings() throws Exception - { + private void getJmsBindings() throws Exception { SequentialFileFactory bindingsJMS = new NIOSequentialFileFactory(config.getBindingsLocation(), 1); - Journal jmsJournal = new JournalImpl(1024 * 1024, - 2, - config.getJournalCompactMinFiles(), - config.getJournalCompactPercentage(), - bindingsJMS, - "activemq-jms", - "jms", - 1); + Journal jmsJournal = new JournalImpl(1024 * 1024, 2, config.getJournalCompactMinFiles(), config.getJournalCompactPercentage(), bindingsJMS, "activemq-jms", "jms", 1); jmsJournal.start(); @@ -366,46 +323,40 @@ public final class XmlDataExporter extends DataAbstract implements Action jmsJournal.load(data, list, null); - for (RecordInfo record : data) - { + for (RecordInfo record : data) { long id = record.id; ActiveMQBuffer buffer = ActiveMQBuffers.wrappedBuffer(record.data); byte rec = record.getUserRecordType(); - if (rec == JMSJournalStorageManagerImpl.CF_RECORD) - { + if (rec == JMSJournalStorageManagerImpl.CF_RECORD) { PersistedConnectionFactory cf = new PersistedConnectionFactory(); cf.decode(buffer); cf.setId(id); ActiveMQServerLogger.LOGGER.info("Found JMS connection factory: " + cf.getName()); jmsConnectionFactories.put(cf.getName(), cf); } - else if (rec == JMSJournalStorageManagerImpl.DESTINATION_RECORD) - { + else if (rec == JMSJournalStorageManagerImpl.DESTINATION_RECORD) { PersistedDestination destination = new PersistedDestination(); destination.decode(buffer); destination.setId(id); ActiveMQServerLogger.LOGGER.info("Found JMS destination: " + destination.getName()); jmsDestinations.put(new Pair<>(destination.getType(), destination.getName()), destination); } - else if (rec == JMSJournalStorageManagerImpl.BINDING_RECORD) - { + else if (rec == JMSJournalStorageManagerImpl.BINDING_RECORD) { PersistedBindings jndi = new PersistedBindings(); jndi.decode(buffer); jndi.setId(id); Pair key = new Pair<>(jndi.getType(), jndi.getName()); StringBuilder builder = new StringBuilder(); - for (String binding : jndi.getBindings()) - { + for (String binding : jndi.getBindings()) { builder.append(binding).append(" "); } ActiveMQServerLogger.LOGGER.info("Found JMS JNDI binding data for " + jndi.getType() + " " + jndi.getName() + ": " + builder.toString()); jmsJNDI.put(key, jndi); } - else - { + else { throw new IllegalStateException("Invalid record type " + rec); } @@ -417,8 +368,7 @@ public final class XmlDataExporter extends DataAbstract implements Action * * @throws Exception will be thrown if anything goes wrong reading the bindings journal */ - private void getBindings() throws Exception - { + private void getBindings() throws Exception { List records = new LinkedList<>(); Journal bindingsJournal = storageManager.getBindingsJournal(); @@ -429,12 +379,9 @@ public final class XmlDataExporter extends DataAbstract implements Action ((JournalImpl) bindingsJournal).load(records, null, null, false); - for (RecordInfo info : records) - { - if (info.getUserRecordType() == JournalRecordIds.QUEUE_BINDING_RECORD) - { - PersistentQueueBindingEncoding bindingEncoding = - (PersistentQueueBindingEncoding) DescribeJournal.newObjectEncoding(info, null); + for (RecordInfo info : records) { + if (info.getUserRecordType() == JournalRecordIds.QUEUE_BINDING_RECORD) { + PersistentQueueBindingEncoding bindingEncoding = (PersistentQueueBindingEncoding) DescribeJournal.newObjectEncoding(info, null); queueBindings.put(bindingEncoding.getId(), bindingEncoding); } } @@ -442,10 +389,8 @@ public final class XmlDataExporter extends DataAbstract implements Action bindingsJournal.stop(); } - private void printDataAsXML() - { - try - { + private void printDataAsXML() { + try { xmlWriter.writeStartDocument(XmlDataConstants.XML_VERSION); xmlWriter.writeStartElement(XmlDataConstants.DOCUMENT_PARENT); printBindingsAsXML(); @@ -457,23 +402,19 @@ public final class XmlDataExporter extends DataAbstract implements Action xmlWriter.flush(); xmlWriter.close(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } - private void printBindingsAsXML() throws XMLStreamException - { + private void printBindingsAsXML() throws XMLStreamException { xmlWriter.writeStartElement(XmlDataConstants.BINDINGS_PARENT); - for (Map.Entry queueBindingEncodingEntry : queueBindings.entrySet()) - { + for (Map.Entry queueBindingEncodingEntry : queueBindings.entrySet()) { PersistentQueueBindingEncoding bindingEncoding = queueBindings.get(queueBindingEncodingEntry.getKey()); xmlWriter.writeEmptyElement(XmlDataConstants.BINDINGS_CHILD); xmlWriter.writeAttribute(XmlDataConstants.BINDING_ADDRESS, bindingEncoding.getAddress().toString()); String filter = ""; - if (bindingEncoding.getFilterString() != null) - { + if (bindingEncoding.getFilterString() != null) { filter = bindingEncoding.getFilterString().toString(); } xmlWriter.writeAttribute(XmlDataConstants.BINDING_FILTER_STRING, filter); @@ -484,19 +425,16 @@ public final class XmlDataExporter extends DataAbstract implements Action xmlWriter.writeEndElement(); // end BINDINGS_PARENT } - private void printJmsConnectionFactoriesAsXML() throws XMLStreamException - { + private void printJmsConnectionFactoriesAsXML() throws XMLStreamException { xmlWriter.writeStartElement(XmlDataConstants.JMS_CONNECTION_FACTORIES); - for (String jmsConnectionFactoryKey : jmsConnectionFactories.keySet()) - { + for (String jmsConnectionFactoryKey : jmsConnectionFactories.keySet()) { xmlWriter.writeStartElement(XmlDataConstants.JMS_CONNECTION_FACTORY); PersistedConnectionFactory jmsConnectionFactory = jmsConnectionFactories.get(jmsConnectionFactoryKey); xmlWriter.writeStartElement(XmlDataConstants.JMS_CONNECTION_FACTORY_NAME); xmlWriter.writeCharacters(jmsConnectionFactory.getName()); xmlWriter.writeEndElement(); String clientID = jmsConnectionFactory.getConfig().getClientID(); - if (clientID != null) - { + if (clientID != null) { xmlWriter.writeStartElement(XmlDataConstants.JMS_CONNECTION_FACTORY_CLIENT_ID); xmlWriter.writeCharacters(clientID); xmlWriter.writeEndElement(); @@ -538,8 +476,7 @@ public final class XmlDataExporter extends DataAbstract implements Action xmlWriter.writeEndElement(); String discoveryGroupName = jmsConnectionFactory.getConfig().getDiscoveryGroupName(); - if (discoveryGroupName != null) - { + if (discoveryGroupName != null) { xmlWriter.writeStartElement(XmlDataConstants.JMS_CONNECTION_FACTORY_DISCOVERY_GROUP_NAME); xmlWriter.writeCharacters(discoveryGroupName); xmlWriter.writeEndElement(); @@ -556,8 +493,7 @@ public final class XmlDataExporter extends DataAbstract implements Action xmlWriter.writeEndElement(); String groupID = jmsConnectionFactory.getConfig().getGroupID(); - if (groupID != null) - { + if (groupID != null) { xmlWriter.writeStartElement(XmlDataConstants.JMS_CONNECTION_FACTORY_GROUP_ID); xmlWriter.writeCharacters(groupID); xmlWriter.writeEndElement(); @@ -669,8 +605,7 @@ public final class XmlDataExporter extends DataAbstract implements Action xmlWriter.writeEndElement(); xmlWriter.writeStartElement(XmlDataConstants.JMS_CONNECTION_FACTORY_CONNECTORS); - for (String connector : jmsConnectionFactory.getConfig().getConnectorNames()) - { + for (String connector : jmsConnectionFactory.getConfig().getConnectorNames()) { xmlWriter.writeStartElement(XmlDataConstants.JMS_CONNECTION_FACTORY_CONNECTOR); xmlWriter.writeCharacters(connector); xmlWriter.writeEndElement(); @@ -679,8 +614,7 @@ public final class XmlDataExporter extends DataAbstract implements Action xmlWriter.writeStartElement(XmlDataConstants.JMS_JNDI_ENTRIES); PersistedBindings jndi = jmsJNDI.get(new Pair<>(PersistedType.ConnectionFactory, jmsConnectionFactory.getName())); - for (String jndiEntry : jndi.getBindings()) - { + for (String jndiEntry : jndi.getBindings()) { xmlWriter.writeStartElement(XmlDataConstants.JMS_JNDI_ENTRY); xmlWriter.writeCharacters(jndiEntry); xmlWriter.writeEndElement(); @@ -691,11 +625,9 @@ public final class XmlDataExporter extends DataAbstract implements Action xmlWriter.writeEndElement(); } - private void printJmsDestinationsAsXML() throws XMLStreamException - { + private void printJmsDestinationsAsXML() throws XMLStreamException { xmlWriter.writeStartElement(XmlDataConstants.JMS_DESTINATIONS); - for (Pair jmsDestinationsKey : jmsDestinations.keySet()) - { + for (Pair jmsDestinationsKey : jmsDestinations.keySet()) { PersistedDestination jmsDestination = jmsDestinations.get(jmsDestinationsKey); xmlWriter.writeStartElement(XmlDataConstants.JMS_DESTINATION); @@ -704,8 +636,7 @@ public final class XmlDataExporter extends DataAbstract implements Action xmlWriter.writeEndElement(); String selector = jmsDestination.getSelector(); - if (selector != null && selector.length() != 0) - { + if (selector != null && selector.length() != 0) { xmlWriter.writeStartElement(XmlDataConstants.JMS_DESTINATION_SELECTOR); xmlWriter.writeCharacters(selector); xmlWriter.writeEndElement(); @@ -715,11 +646,9 @@ public final class XmlDataExporter extends DataAbstract implements Action xmlWriter.writeCharacters(jmsDestination.getType().toString()); xmlWriter.writeEndElement(); - xmlWriter.writeStartElement(XmlDataConstants.JMS_JNDI_ENTRIES); PersistedBindings jndi = jmsJNDI.get(new Pair<>(jmsDestination.getType(), jmsDestination.getName())); - for (String jndiEntry : jndi.getBindings()) - { + for (String jndiEntry : jndi.getBindings()) { xmlWriter.writeStartElement(XmlDataConstants.JMS_JNDI_ENTRY); xmlWriter.writeCharacters(jndiEntry); xmlWriter.writeEndElement(); @@ -730,14 +659,12 @@ public final class XmlDataExporter extends DataAbstract implements Action xmlWriter.writeEndElement(); } - private void printAllMessagesAsXML() throws XMLStreamException - { + private void printAllMessagesAsXML() throws XMLStreamException { xmlWriter.writeStartElement(XmlDataConstants.MESSAGES_PARENT); // Order here is important. We must process the messages from the journal before we process those from the page // files in order to get the messages in the right order. - for (Map.Entry messageMapEntry : messages.entrySet()) - { + for (Map.Entry messageMapEntry : messages.entrySet()) { printSingleMessageAsXML((ServerMessage) messageMapEntry.getValue(), extractQueueNames(messageRefs.get(messageMapEntry.getKey()))); } @@ -750,23 +677,17 @@ public final class XmlDataExporter extends DataAbstract implements Action * Reads from the page files and prints messages as it finds them (making sure to check acks and transactions * from the journal). */ - private void printPagedMessagesAsXML() - { - try - { + private void printPagedMessagesAsXML() { + try { ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1); final ExecutorService executor = Executors.newFixedThreadPool(10); - ExecutorFactory executorFactory = new ExecutorFactory() - { + ExecutorFactory executorFactory = new ExecutorFactory() { @Override - public Executor getExecutor() - { + public Executor getExecutor() { return executor; } }; - PagingStoreFactory pageStoreFactory = - new PagingStoreFactoryNIO(storageManager, config.getPagingLocation(), 1000L, scheduled, executorFactory, true, - null); + PagingStoreFactory pageStoreFactory = new PagingStoreFactoryNIO(storageManager, config.getPagingLocation(), 1000L, scheduled, executorFactory, true, null); HierarchicalRepository addressSettingsRepository = new HierarchicalObjectRepository<>(); addressSettingsRepository.setDefault(new AddressSettings()); PagingManager manager = new PagingManagerImpl(pageStoreFactory, addressSettingsRepository); @@ -775,18 +696,15 @@ public final class XmlDataExporter extends DataAbstract implements Action SimpleString[] stores = manager.getStoreNames(); - for (SimpleString store : stores) - { + for (SimpleString store : stores) { PagingStore pageStore = manager.getPageStore(store); - if (pageStore != null) - { + if (pageStore != null) { File folder = pageStore.getFolder(); ActiveMQServerLogger.LOGGER.debug("Reading page store " + store + " folder = " + folder); int pageId = (int) pageStore.getFirstPage(); - for (int i = 0; i < pageStore.getNumberOfPages(); i++) - { + for (int i = 0; i < pageStore.getNumberOfPages(); i++) { ActiveMQServerLogger.LOGGER.debug("Reading page " + pageId); Page page = pageStore.createPage(pageId); page.open(); @@ -795,36 +713,30 @@ public final class XmlDataExporter extends DataAbstract implements Action int messageId = 0; - for (PagedMessage message : messages) - { + for (PagedMessage message : messages) { message.initMessage(storageManager); long[] queueIDs = message.getQueueIDs(); List queueNames = new ArrayList<>(); - for (long queueID : queueIDs) - { + for (long queueID : queueIDs) { PagePosition posCheck = new PagePositionImpl(pageId, messageId); boolean acked = false; Set positions = cursorRecords.get(queueID); - if (positions != null) - { + if (positions != null) { acked = positions.contains(posCheck); } - if (!acked) - { + if (!acked) { PersistentQueueBindingEncoding queueBinding = queueBindings.get(queueID); - if (queueBinding != null) - { + if (queueBinding != null) { SimpleString queueName = queueBinding.getQueueName(); queueNames.add(queueName.toString()); } } } - if (queueNames.size() > 0 && (message.getTransactionID() == -1 || pgTXs.contains(message.getTransactionID()))) - { + if (queueNames.size() > 0 && (message.getTransactionID() == -1 || pgTXs.contains(message.getTransactionID()))) { printSingleMessageAsXML(message.getMessage(), queueNames); } @@ -834,20 +746,17 @@ public final class XmlDataExporter extends DataAbstract implements Action pageId++; } } - else - { + else { ActiveMQServerLogger.LOGGER.debug("Page store was null"); } } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } - private void printSingleMessageAsXML(ServerMessage message, List queues) throws XMLStreamException - { + private void printSingleMessageAsXML(ServerMessage message, List queues) throws XMLStreamException { xmlWriter.writeStartElement(XmlDataConstants.MESSAGES_CHILD); printMessageAttributes(message); printMessageProperties(message); @@ -857,16 +766,13 @@ public final class XmlDataExporter extends DataAbstract implements Action messagesPrinted++; } - private void printMessageBody(ServerMessage message) throws XMLStreamException - { + private void printMessageBody(ServerMessage message) throws XMLStreamException { xmlWriter.writeStartElement(XmlDataConstants.MESSAGE_BODY); - if (message.isLargeMessage()) - { + if (message.isLargeMessage()) { printLargeMessageBody((LargeServerMessage) message); } - else - { + else { int size = message.getEndOfBodyPosition() - message.getBodyBuffer().readerIndex(); byte[] buffer = new byte[size]; message.getBodyBuffer().readBytes(buffer); @@ -876,27 +782,22 @@ public final class XmlDataExporter extends DataAbstract implements Action xmlWriter.writeEndElement(); // end MESSAGE_BODY } - private void printLargeMessageBody(LargeServerMessage message) throws XMLStreamException - { + private void printLargeMessageBody(LargeServerMessage message) throws XMLStreamException { xmlWriter.writeAttribute(XmlDataConstants.MESSAGE_IS_LARGE, Boolean.TRUE.toString()); BodyEncoder encoder = null; - try - { + try { encoder = message.getBodyEncoder(); encoder.open(); long totalBytesWritten = 0; Long bufferSize; long bodySize = encoder.getLargeBodySize(); - for (long i = 0; i < bodySize; i += LARGE_MESSAGE_CHUNK_SIZE) - { + for (long i = 0; i < bodySize; i += LARGE_MESSAGE_CHUNK_SIZE) { Long remainder = bodySize - totalBytesWritten; - if (remainder >= LARGE_MESSAGE_CHUNK_SIZE) - { + if (remainder >= LARGE_MESSAGE_CHUNK_SIZE) { bufferSize = LARGE_MESSAGE_CHUNK_SIZE; } - else - { + else { bufferSize = remainder; } ActiveMQBuffer buffer = ActiveMQBuffers.fixedBuffer(bufferSize.intValue()); @@ -906,145 +807,114 @@ public final class XmlDataExporter extends DataAbstract implements Action } encoder.close(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { e.printStackTrace(); } - finally - { - if (encoder != null) - { - try - { + finally { + if (encoder != null) { + try { encoder.close(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { e.printStackTrace(); } } } } - private void printMessageQueues(List queues) throws XMLStreamException - { + private void printMessageQueues(List queues) throws XMLStreamException { xmlWriter.writeStartElement(XmlDataConstants.QUEUES_PARENT); - for (String queueName : queues) - { + for (String queueName : queues) { xmlWriter.writeEmptyElement(XmlDataConstants.QUEUES_CHILD); xmlWriter.writeAttribute(XmlDataConstants.QUEUE_NAME, queueName); } xmlWriter.writeEndElement(); // end QUEUES_PARENT } - private void printMessageProperties(ServerMessage message) throws XMLStreamException - { + private void printMessageProperties(ServerMessage message) throws XMLStreamException { xmlWriter.writeStartElement(XmlDataConstants.PROPERTIES_PARENT); - for (SimpleString key : message.getPropertyNames()) - { + for (SimpleString key : message.getPropertyNames()) { Object value = message.getObjectProperty(key); xmlWriter.writeEmptyElement(XmlDataConstants.PROPERTIES_CHILD); xmlWriter.writeAttribute(XmlDataConstants.PROPERTY_NAME, key.toString()); - if (value instanceof byte[]) - { + if (value instanceof byte[]) { xmlWriter.writeAttribute(XmlDataConstants.PROPERTY_VALUE, encode((byte[]) value)); } - else - { + else { xmlWriter.writeAttribute(XmlDataConstants.PROPERTY_VALUE, value == null ? XmlDataConstants.NULL : value.toString()); } - if (value instanceof Boolean) - { + if (value instanceof Boolean) { xmlWriter.writeAttribute(XmlDataConstants.PROPERTY_TYPE, XmlDataConstants.PROPERTY_TYPE_BOOLEAN); } - else if (value instanceof Byte) - { + else if (value instanceof Byte) { xmlWriter.writeAttribute(XmlDataConstants.PROPERTY_TYPE, XmlDataConstants.PROPERTY_TYPE_BYTE); } - else if (value instanceof Short) - { + else if (value instanceof Short) { xmlWriter.writeAttribute(XmlDataConstants.PROPERTY_TYPE, XmlDataConstants.PROPERTY_TYPE_SHORT); } - else if (value instanceof Integer) - { + else if (value instanceof Integer) { xmlWriter.writeAttribute(XmlDataConstants.PROPERTY_TYPE, XmlDataConstants.PROPERTY_TYPE_INTEGER); } - else if (value instanceof Long) - { + else if (value instanceof Long) { xmlWriter.writeAttribute(XmlDataConstants.PROPERTY_TYPE, XmlDataConstants.PROPERTY_TYPE_LONG); } - else if (value instanceof Float) - { + else if (value instanceof Float) { xmlWriter.writeAttribute(XmlDataConstants.PROPERTY_TYPE, XmlDataConstants.PROPERTY_TYPE_FLOAT); } - else if (value instanceof Double) - { + else if (value instanceof Double) { xmlWriter.writeAttribute(XmlDataConstants.PROPERTY_TYPE, XmlDataConstants.PROPERTY_TYPE_DOUBLE); } - else if (value instanceof String) - { + else if (value instanceof String) { xmlWriter.writeAttribute(XmlDataConstants.PROPERTY_TYPE, XmlDataConstants.PROPERTY_TYPE_STRING); } - else if (value instanceof SimpleString) - { + else if (value instanceof SimpleString) { xmlWriter.writeAttribute(XmlDataConstants.PROPERTY_TYPE, XmlDataConstants.PROPERTY_TYPE_SIMPLE_STRING); } - else if (value instanceof byte[]) - { + else if (value instanceof byte[]) { xmlWriter.writeAttribute(XmlDataConstants.PROPERTY_TYPE, XmlDataConstants.PROPERTY_TYPE_BYTES); } } xmlWriter.writeEndElement(); // end PROPERTIES_PARENT } - private void printMessageAttributes(ServerMessage message) throws XMLStreamException - { + private void printMessageAttributes(ServerMessage message) throws XMLStreamException { xmlWriter.writeAttribute(XmlDataConstants.MESSAGE_ID, Long.toString(message.getMessageID())); xmlWriter.writeAttribute(XmlDataConstants.MESSAGE_PRIORITY, Byte.toString(message.getPriority())); xmlWriter.writeAttribute(XmlDataConstants.MESSAGE_EXPIRATION, Long.toString(message.getExpiration())); xmlWriter.writeAttribute(XmlDataConstants.MESSAGE_TIMESTAMP, Long.toString(message.getTimestamp())); byte rawType = message.getType(); String prettyType = XmlDataConstants.DEFAULT_TYPE_PRETTY; - if (rawType == Message.BYTES_TYPE) - { + if (rawType == Message.BYTES_TYPE) { prettyType = XmlDataConstants.BYTES_TYPE_PRETTY; } - else if (rawType == Message.MAP_TYPE) - { + else if (rawType == Message.MAP_TYPE) { prettyType = XmlDataConstants.MAP_TYPE_PRETTY; } - else if (rawType == Message.OBJECT_TYPE) - { + else if (rawType == Message.OBJECT_TYPE) { prettyType = XmlDataConstants.OBJECT_TYPE_PRETTY; } - else if (rawType == Message.STREAM_TYPE) - { + else if (rawType == Message.STREAM_TYPE) { prettyType = XmlDataConstants.STREAM_TYPE_PRETTY; } - else if (rawType == Message.TEXT_TYPE) - { + else if (rawType == Message.TEXT_TYPE) { prettyType = XmlDataConstants.TEXT_TYPE_PRETTY; } xmlWriter.writeAttribute(XmlDataConstants.MESSAGE_TYPE, prettyType); - if (message.getUserID() != null) - { + if (message.getUserID() != null) { xmlWriter.writeAttribute(XmlDataConstants.MESSAGE_USER_ID, message.getUserID().toString()); } } - private List extractQueueNames(HashMap refMap) - { + private List extractQueueNames(HashMap refMap) { List queues = new ArrayList<>(); - for (ReferenceDescribe ref : refMap.values()) - { + for (ReferenceDescribe ref : refMap.values()) { queues.add(queueBindings.get(ref.refEncoding.queueID).getQueueName().toString()); } return queues; } - private static String encode(final byte[] data) - { + private static String encode(final byte[] data) { return Base64.encodeBytes(data, 0, data.length, Base64.DONT_BREAK_LINES | Base64.URL_SAFE); } @@ -1053,8 +923,8 @@ public final class XmlDataExporter extends DataAbstract implements Action /** * Proxy to handle indenting the XML since javax.xml.stream.XMLStreamWriter doesn't support that. */ - static class PrettyPrintHandler implements InvocationHandler - { + static class PrettyPrintHandler implements InvocationHandler { + private final XMLStreamWriter target; private int depth = 0; @@ -1065,19 +935,15 @@ public final class XmlDataExporter extends DataAbstract implements Action boolean wrap = true; - - public PrettyPrintHandler(XMLStreamWriter target) - { + public PrettyPrintHandler(XMLStreamWriter target) { this.target = target; } @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable - { + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String m = method.getName(); - switch (m) - { + switch (m) { case "writeStartElement": target.writeCharacters(LINE_SEPARATOR); target.writeCharacters(indent(depth)); @@ -1086,8 +952,7 @@ public final class XmlDataExporter extends DataAbstract implements Action break; case "writeEndElement": depth--; - if (wrap) - { + if (wrap) { target.writeCharacters(LINE_SEPARATOR); target.writeCharacters(indent(depth)); } @@ -1108,12 +973,10 @@ public final class XmlDataExporter extends DataAbstract implements Action return null; } - private String indent(int depth) - { + private String indent(int depth) { depth *= 3; // level of indentation char[] output = new char[depth]; - while (depth-- > 0) - { + while (depth-- > 0) { output[depth] = INDENT_CHAR; } return new String(output); diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/XmlDataImporter.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/XmlDataImporter.java index 33aa5f3f2f..854ca984d0 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/XmlDataImporter.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/XmlDataImporter.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.cli.commands.tools; - import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; @@ -63,8 +62,7 @@ import org.apache.activemq.artemis.utils.UUIDGenerator; * for speed and simplicity. */ @Command(name = "imp", description = "Import all message-data using an XML that could be interpreted by any system.") -public final class XmlDataImporter extends ActionAbstract -{ +public final class XmlDataImporter extends ActionAbstract { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -102,37 +100,29 @@ public final class XmlDataImporter extends ActionAbstract @Option(name = "--input", description = "The input file name (default=exp.dmp)", required = true) public String input = "exp.dmp"; - public String getPassword() - { + public String getPassword() { return password; } - public void setPassword(String password) - { + public void setPassword(String password) { this.password = password; } - - public String getUser() - { + public String getUser() { return user; } - public void setUser(String user) - { + public void setUser(String user) { this.user = user; } - @Override - public Object execute(ActionContext context) throws Exception - { + public Object execute(ActionContext context) throws Exception { process(input, host, port, transactional); return null; } - public void process(String inputFile, String host, int port, boolean transactional) throws Exception - { + public void process(String inputFile, String host, int port, boolean transactional) throws Exception { this.process(new FileInputStream(inputFile), host, port, transactional); } @@ -147,8 +137,7 @@ public final class XmlDataImporter extends ActionAbstract * @param session used for sending messages, must use auto-commit for sends * @throws Exception */ - public void process(InputStream inputStream, ClientSession session) throws Exception - { + public void process(InputStream inputStream, ClientSession session) throws Exception { this.process(inputStream, session, null); } @@ -162,44 +151,36 @@ public final class XmlDataImporter extends ActionAbstract * @param session used for sending messages, doesn't need to auto-commit sends * @param managementSession used for management queries, must use auto-commit for sends */ - public void process(InputStream inputStream, ClientSession session, ClientSession managementSession) throws Exception - { + public void process(InputStream inputStream, + ClientSession session, + ClientSession managementSession) throws Exception { reader = XMLInputFactory.newInstance().createXMLStreamReader(inputStream); this.session = session; - if (managementSession != null) - { + if (managementSession != null) { this.managementSession = managementSession; } - else - { + else { this.managementSession = session; } localSession = false; - processXml(); } - public void process(InputStream inputStream, String host, int port, boolean transactional) throws Exception - { + public void process(InputStream inputStream, String host, int port, boolean transactional) throws Exception { reader = XMLInputFactory.newInstance().createXMLStreamReader(inputStream); HashMap connectionParams = new HashMap<>(); connectionParams.put(TransportConstants.HOST_PROP_NAME, host); connectionParams.put(TransportConstants.PORT_PROP_NAME, Integer.toString(port)); - ServerLocator serverLocator = - ActiveMQClient.createServerLocatorWithoutHA(new TransportConfiguration( - NettyConnectorFactory.class.getName(), - connectionParams)); + ServerLocator serverLocator = ActiveMQClient.createServerLocatorWithoutHA(new TransportConfiguration(NettyConnectorFactory.class.getName(), connectionParams)); ClientSessionFactory sf = serverLocator.createSessionFactory(); - if (user != null || password != null) - { + if (user != null || password != null) { session = sf.createSession(user, password, false, !transactional, true, false, 0); managementSession = sf.createSession(user, password, false, true, true, false, 0); } - else - { + else { session = sf.createSession(false, !transactional, true); managementSession = sf.createSession(false, true, true); } @@ -208,53 +189,41 @@ public final class XmlDataImporter extends ActionAbstract processXml(); } - private void processXml() throws Exception - { - try - { - while (reader.hasNext()) - { + private void processXml() throws Exception { + try { + while (reader.hasNext()) { ActiveMQServerLogger.LOGGER.debug("EVENT:[" + reader.getLocation().getLineNumber() + "][" + reader.getLocation().getColumnNumber() + "] "); - if (reader.getEventType() == XMLStreamConstants.START_ELEMENT) - { - if (XmlDataConstants.BINDINGS_CHILD.equals(reader.getLocalName())) - { + if (reader.getEventType() == XMLStreamConstants.START_ELEMENT) { + if (XmlDataConstants.BINDINGS_CHILD.equals(reader.getLocalName())) { bindQueue(); } - else if (XmlDataConstants.MESSAGES_CHILD.equals(reader.getLocalName())) - { + else if (XmlDataConstants.MESSAGES_CHILD.equals(reader.getLocalName())) { processMessage(); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORIES.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORIES.equals(reader.getLocalName())) { createJmsConnectionFactories(); } - else if (XmlDataConstants.JMS_DESTINATIONS.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_DESTINATIONS.equals(reader.getLocalName())) { createJmsDestinations(); } } reader.next(); } - if (!session.isAutoCommitSends()) - { + if (!session.isAutoCommitSends()) { session.commit(); } } - finally - { + finally { // if the session was created in our constructor then close it (otherwise the caller will close it) - if (localSession) - { + if (localSession) { session.close(); managementSession.close(); } } } - private void processMessage() throws Exception - { + private void processMessage() throws Exception { Byte type = 0; Byte priority = 0; Long expiration = 0L; @@ -263,11 +232,9 @@ public final class XmlDataImporter extends ActionAbstract ArrayList queues = new ArrayList<>(); // get message's attributes - for (int i = 0; i < reader.getAttributeCount(); i++) - { + for (int i = 0; i < reader.getAttributeCount(); i++) { String attributeName = reader.getAttributeLocalName(i); - switch (attributeName) - { + switch (attributeName) { case XmlDataConstants.MESSAGE_TYPE: type = getMessageType(reader.getAttributeValue(i)); break; @@ -292,34 +259,27 @@ public final class XmlDataImporter extends ActionAbstract boolean endLoop = false; // loop through the XML and gather up all the message's data (i.e. body, properties, queues, etc.) - while (reader.hasNext()) - { + while (reader.hasNext()) { int eventType = reader.getEventType(); - switch (eventType) - { + switch (eventType) { case XMLStreamConstants.START_ELEMENT: - if (XmlDataConstants.MESSAGE_BODY.equals(reader.getLocalName())) - { + if (XmlDataConstants.MESSAGE_BODY.equals(reader.getLocalName())) { processMessageBody(message); } - else if (XmlDataConstants.PROPERTIES_CHILD.equals(reader.getLocalName())) - { + else if (XmlDataConstants.PROPERTIES_CHILD.equals(reader.getLocalName())) { processMessageProperties(message); } - else if (XmlDataConstants.QUEUES_CHILD.equals(reader.getLocalName())) - { + else if (XmlDataConstants.QUEUES_CHILD.equals(reader.getLocalName())) { processMessageQueues(queues); } break; case XMLStreamConstants.END_ELEMENT: - if (XmlDataConstants.MESSAGES_CHILD.equals(reader.getLocalName())) - { + if (XmlDataConstants.MESSAGES_CHILD.equals(reader.getLocalName())) { endLoop = true; } break; } - if (endLoop) - { + if (endLoop) { break; } reader.next(); @@ -328,11 +288,9 @@ public final class XmlDataImporter extends ActionAbstract sendMessage(queues, message); } - private Byte getMessageType(String value) - { + private Byte getMessageType(String value) { Byte type = Message.DEFAULT_TYPE; - switch (value) - { + switch (value) { case XmlDataConstants.DEFAULT_TYPE_PRETTY: type = Message.DEFAULT_TYPE; break; @@ -355,24 +313,20 @@ public final class XmlDataImporter extends ActionAbstract return type; } - private void sendMessage(ArrayList queues, Message message) throws Exception - { + private void sendMessage(ArrayList queues, Message message) throws Exception { StringBuilder logMessage = new StringBuilder(); String destination = addressMap.get(queues.get(0)); logMessage.append("Sending ").append(message).append(" to address: ").append(destination).append("; routed to queues: "); ByteBuffer buffer = ByteBuffer.allocate(queues.size() * 8); - for (String queue : queues) - { + for (String queue : queues) { long queueID; - if (queueIDs.containsKey(queue)) - { + if (queueIDs.containsKey(queue)) { queueID = queueIDs.get(queue); } - else - { + else { // Get the ID of the queues involved so the message can be routed properly. This is done because we cannot // send directly to a queue, we have to send to an address instead but not all the queues related to the // address may need the message @@ -400,40 +354,32 @@ public final class XmlDataImporter extends ActionAbstract producer.send(message); producer.close(); - if (tempFileName.length() > 0) - { + if (tempFileName.length() > 0) { File tempFile = new File(tempFileName); - if (!tempFile.delete()) - { + if (!tempFile.delete()) { ActiveMQServerLogger.LOGGER.couldNotDeleteTempFile(tempFileName); } tempFileName = ""; } } - private void processMessageQueues(ArrayList queues) - { - for (int i = 0; i < reader.getAttributeCount(); i++) - { - if (XmlDataConstants.QUEUE_NAME.equals(reader.getAttributeLocalName(i))) - { + private void processMessageQueues(ArrayList queues) { + for (int i = 0; i < reader.getAttributeCount(); i++) { + if (XmlDataConstants.QUEUE_NAME.equals(reader.getAttributeLocalName(i))) { queues.add(reader.getAttributeValue(i)); } } } - private void processMessageProperties(Message message) - { + private void processMessageProperties(Message message) { String key = ""; String value = ""; String propertyType = ""; String realValue = null; - for (int i = 0; i < reader.getAttributeCount(); i++) - { + for (int i = 0; i < reader.getAttributeCount(); i++) { String attributeName = reader.getAttributeLocalName(i); - switch (attributeName) - { + switch (attributeName) { case XmlDataConstants.PROPERTY_NAME: key = reader.getAttributeValue(i); break; @@ -446,8 +392,7 @@ public final class XmlDataImporter extends ActionAbstract } } - switch (propertyType) - { + switch (propertyType) { case XmlDataConstants.PROPERTY_TYPE_SHORT: message.putShortProperty(key, Short.parseShort(value)); break; @@ -473,15 +418,13 @@ public final class XmlDataImporter extends ActionAbstract message.putLongProperty(key, Long.parseLong(value)); break; case XmlDataConstants.PROPERTY_TYPE_SIMPLE_STRING: - if (!value.equals(XmlDataConstants.NULL)) - { + if (!value.equals(XmlDataConstants.NULL)) { realValue = value; } message.putStringProperty(new SimpleString(key), new SimpleString(realValue)); break; case XmlDataConstants.PROPERTY_TYPE_STRING: - if (!value.equals(XmlDataConstants.NULL)) - { + if (!value.equals(XmlDataConstants.NULL)) { realValue = value; } message.putStringProperty(key, realValue); @@ -489,33 +432,25 @@ public final class XmlDataImporter extends ActionAbstract } } - private void processMessageBody(Message message) throws XMLStreamException, IOException - { + private void processMessageBody(Message message) throws XMLStreamException, IOException { boolean isLarge = false; - for (int i = 0; i < reader.getAttributeCount(); i++) - { + for (int i = 0; i < reader.getAttributeCount(); i++) { String attributeName = reader.getAttributeLocalName(i); - if (XmlDataConstants.MESSAGE_IS_LARGE.equals(attributeName)) - { + if (XmlDataConstants.MESSAGE_IS_LARGE.equals(attributeName)) { isLarge = Boolean.parseBoolean(reader.getAttributeValue(i)); } } reader.next(); - if (isLarge) - { + if (isLarge) { tempFileName = UUID.randomUUID().toString() + ".tmp"; ActiveMQServerLogger.LOGGER.debug("Creating temp file " + tempFileName + " for large message."); - try (OutputStream out = new FileOutputStream(tempFileName)) - { - while (reader.hasNext()) - { - if (reader.getEventType() == XMLStreamConstants.END_ELEMENT) - { + try (OutputStream out = new FileOutputStream(tempFileName)) { + while (reader.hasNext()) { + if (reader.getEventType() == XMLStreamConstants.END_ELEMENT) { break; } - else - { + else { String characters = new String(reader.getTextCharacters(), reader.getTextStart(), reader.getTextLength()); String trimmedCharacters = characters.trim(); if (trimmedCharacters.length() > 0) // this will skip "indentation" characters @@ -531,25 +466,21 @@ public final class XmlDataImporter extends ActionAbstract BufferedInputStream bufferedInput = new BufferedInputStream(fileInputStream); ((ClientMessage) message).setBodyInputStream(bufferedInput); } - else - { + else { reader.next(); // step past the "indentation" characters to get to the CDATA with the message body String characters = new String(reader.getTextCharacters(), reader.getTextStart(), reader.getTextLength()); message.getBodyBuffer().writeBytes(decode(characters.trim())); } } - private void bindQueue() throws Exception - { + private void bindQueue() throws Exception { String queueName = ""; String address = ""; String filter = ""; - for (int i = 0; i < reader.getAttributeCount(); i++) - { + for (int i = 0; i < reader.getAttributeCount(); i++) { String attributeName = reader.getAttributeLocalName(i); - switch (attributeName) - { + switch (attributeName) { case XmlDataConstants.BINDING_ADDRESS: address = reader.getAttributeValue(i); break; @@ -564,81 +495,66 @@ public final class XmlDataImporter extends ActionAbstract ClientSession.QueueQuery queueQuery = session.queueQuery(new SimpleString(queueName)); - if (!queueQuery.isExists()) - { + if (!queueQuery.isExists()) { session.createQueue(address, queueName, filter, true); ActiveMQServerLogger.LOGGER.debug("Binding queue(name=" + queueName + ", address=" + address + ", filter=" + filter + ")"); } - else - { + else { ActiveMQServerLogger.LOGGER.debug("Binding " + queueName + " already exists so won't re-bind."); } addressMap.put(queueName, address); } - private void createJmsConnectionFactories() throws Exception - { + private void createJmsConnectionFactories() throws Exception { boolean endLoop = false; - while (reader.hasNext()) - { + while (reader.hasNext()) { int eventType = reader.getEventType(); - switch (eventType) - { + switch (eventType) { case XMLStreamConstants.START_ELEMENT: - if (XmlDataConstants.JMS_CONNECTION_FACTORY.equals(reader.getLocalName())) - { + if (XmlDataConstants.JMS_CONNECTION_FACTORY.equals(reader.getLocalName())) { createJmsConnectionFactory(); } break; case XMLStreamConstants.END_ELEMENT: - if (XmlDataConstants.JMS_CONNECTION_FACTORIES.equals(reader.getLocalName())) - { + if (XmlDataConstants.JMS_CONNECTION_FACTORIES.equals(reader.getLocalName())) { endLoop = true; } break; } - if (endLoop) - { + if (endLoop) { break; } reader.next(); } } - private void createJmsDestinations() throws Exception - { + private void createJmsDestinations() throws Exception { boolean endLoop = false; - while (reader.hasNext()) - { + while (reader.hasNext()) { int eventType = reader.getEventType(); - switch (eventType) - { + switch (eventType) { case XMLStreamConstants.START_ELEMENT: - if (XmlDataConstants.JMS_DESTINATION.equals(reader.getLocalName())) - { + if (XmlDataConstants.JMS_DESTINATION.equals(reader.getLocalName())) { createJmsDestination(); } break; case XMLStreamConstants.END_ELEMENT: - if (XmlDataConstants.JMS_DESTINATIONS.equals(reader.getLocalName())) - { + if (XmlDataConstants.JMS_DESTINATIONS.equals(reader.getLocalName())) { endLoop = true; } break; } - if (endLoop) - { + if (endLoop) { break; } reader.next(); } } - private void createJmsConnectionFactory() throws Exception - { + private void createJmsConnectionFactory() throws Exception { String name = ""; String callFailoverTimeout = ""; String callTimeout = ""; @@ -678,202 +594,162 @@ public final class XmlDataImporter extends ActionAbstract boolean endLoop = false; - while (reader.hasNext()) - { + while (reader.hasNext()) { int eventType = reader.getEventType(); - switch (eventType) - { + switch (eventType) { case XMLStreamConstants.START_ELEMENT: - if (XmlDataConstants.JMS_CONNECTION_FACTORY_CALL_FAILOVER_TIMEOUT.equals(reader.getLocalName())) - { + if (XmlDataConstants.JMS_CONNECTION_FACTORY_CALL_FAILOVER_TIMEOUT.equals(reader.getLocalName())) { callFailoverTimeout = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory callFailoverTimeout: " + callFailoverTimeout); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_CALL_TIMEOUT.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_CALL_TIMEOUT.equals(reader.getLocalName())) { callTimeout = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory callTimeout: " + callTimeout); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_CLIENT_FAILURE_CHECK_PERIOD.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_CLIENT_FAILURE_CHECK_PERIOD.equals(reader.getLocalName())) { clientFailureCheckPeriod = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory clientFailureCheckPeriod: " + clientFailureCheckPeriod); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_CLIENT_ID.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_CLIENT_ID.equals(reader.getLocalName())) { clientId = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory clientId: " + clientId); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_CONFIRMATION_WINDOW_SIZE.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_CONFIRMATION_WINDOW_SIZE.equals(reader.getLocalName())) { confirmationWindowSize = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory confirmationWindowSize: " + confirmationWindowSize); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_CONNECTION_TTL.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_CONNECTION_TTL.equals(reader.getLocalName())) { connectionTtl = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory connectionTtl: " + connectionTtl); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_CONNECTOR.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_CONNECTOR.equals(reader.getLocalName())) { connectors = getConnectors(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory getLocalName: " + connectors); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_CONSUMER_MAX_RATE.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_CONSUMER_MAX_RATE.equals(reader.getLocalName())) { consumerMaxRate = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory consumerMaxRate: " + consumerMaxRate); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_CONSUMER_WINDOW_SIZE.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_CONSUMER_WINDOW_SIZE.equals(reader.getLocalName())) { consumerWindowSize = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory consumerWindowSize: " + consumerWindowSize); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_DISCOVERY_GROUP_NAME.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_DISCOVERY_GROUP_NAME.equals(reader.getLocalName())) { discoveryGroupName = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory discoveryGroupName: " + discoveryGroupName); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_DUPS_OK_BATCH_SIZE.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_DUPS_OK_BATCH_SIZE.equals(reader.getLocalName())) { dupsOkBatchSize = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory dupsOkBatchSize: " + dupsOkBatchSize); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_GROUP_ID.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_GROUP_ID.equals(reader.getLocalName())) { groupId = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory groupId: " + groupId); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_LOAD_BALANCING_POLICY_CLASS_NAME.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_LOAD_BALANCING_POLICY_CLASS_NAME.equals(reader.getLocalName())) { loadBalancingPolicyClassName = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory loadBalancingPolicyClassName: " + loadBalancingPolicyClassName); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_MAX_RETRY_INTERVAL.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_MAX_RETRY_INTERVAL.equals(reader.getLocalName())) { maxRetryInterval = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory maxRetryInterval: " + maxRetryInterval); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_MIN_LARGE_MESSAGE_SIZE.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_MIN_LARGE_MESSAGE_SIZE.equals(reader.getLocalName())) { minLargeMessageSize = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory minLargeMessageSize: " + minLargeMessageSize); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_NAME.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_NAME.equals(reader.getLocalName())) { name = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory name: " + name); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_PRODUCER_MAX_RATE.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_PRODUCER_MAX_RATE.equals(reader.getLocalName())) { producerMaxRate = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory producerMaxRate: " + producerMaxRate); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_PRODUCER_WINDOW_SIZE.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_PRODUCER_WINDOW_SIZE.equals(reader.getLocalName())) { producerWindowSize = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory producerWindowSize: " + producerWindowSize); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_RECONNECT_ATTEMPTS.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_RECONNECT_ATTEMPTS.equals(reader.getLocalName())) { reconnectAttempts = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory reconnectAttempts: " + reconnectAttempts); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_RETRY_INTERVAL.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_RETRY_INTERVAL.equals(reader.getLocalName())) { retryInterval = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory retryInterval: " + retryInterval); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_RETRY_INTERVAL_MULTIPLIER.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_RETRY_INTERVAL_MULTIPLIER.equals(reader.getLocalName())) { retryIntervalMultiplier = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory retryIntervalMultiplier: " + retryIntervalMultiplier); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_SCHEDULED_THREAD_POOL_MAX_SIZE.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_SCHEDULED_THREAD_POOL_MAX_SIZE.equals(reader.getLocalName())) { scheduledThreadMaxPoolSize = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory scheduledThreadMaxPoolSize: " + scheduledThreadMaxPoolSize); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_THREAD_POOL_MAX_SIZE.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_THREAD_POOL_MAX_SIZE.equals(reader.getLocalName())) { threadMaxPoolSize = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory threadMaxPoolSize: " + threadMaxPoolSize); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_TRANSACTION_BATCH_SIZE.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_TRANSACTION_BATCH_SIZE.equals(reader.getLocalName())) { transactionBatchSize = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory transactionBatchSize: " + transactionBatchSize); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_TYPE.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_TYPE.equals(reader.getLocalName())) { type = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory type: " + type); } - else if (XmlDataConstants.JMS_JNDI_ENTRIES.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_JNDI_ENTRIES.equals(reader.getLocalName())) { entries = getEntries(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory entries: " + entries); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_AUTO_GROUP.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_AUTO_GROUP.equals(reader.getLocalName())) { autoGroup = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory autoGroup: " + autoGroup); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_BLOCK_ON_ACKNOWLEDGE.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_BLOCK_ON_ACKNOWLEDGE.equals(reader.getLocalName())) { blockOnAcknowledge = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory blockOnAcknowledge: " + blockOnAcknowledge); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_BLOCK_ON_DURABLE_SEND.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_BLOCK_ON_DURABLE_SEND.equals(reader.getLocalName())) { blockOnDurableSend = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory blockOnDurableSend: " + blockOnDurableSend); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_BLOCK_ON_NON_DURABLE_SEND.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_BLOCK_ON_NON_DURABLE_SEND.equals(reader.getLocalName())) { blockOnNonDurableSend = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory blockOnNonDurableSend: " + blockOnNonDurableSend); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_CACHE_LARGE_MESSAGES_CLIENT.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_CACHE_LARGE_MESSAGES_CLIENT.equals(reader.getLocalName())) { cacheLargeMessagesClient = reader.getElementText(); ActiveMQServerLogger.LOGGER.info("JMS connection factory " + name + " cacheLargeMessagesClient: " + cacheLargeMessagesClient); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_COMPRESS_LARGE_MESSAGES.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_COMPRESS_LARGE_MESSAGES.equals(reader.getLocalName())) { compressLargeMessages = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory compressLargeMessages: " + compressLargeMessages); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_FAILOVER_ON_INITIAL_CONNECTION.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_FAILOVER_ON_INITIAL_CONNECTION.equals(reader.getLocalName())) { failoverOnInitialConnection = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory failoverOnInitialConnection: " + failoverOnInitialConnection); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_HA.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_HA.equals(reader.getLocalName())) { ha = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory ha: " + ha); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_PREACKNOWLEDGE.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_PREACKNOWLEDGE.equals(reader.getLocalName())) { preacknowledge = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory preacknowledge: " + preacknowledge); } - else if (XmlDataConstants.JMS_CONNECTION_FACTORY_USE_GLOBAL_POOLS.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_CONNECTION_FACTORY_USE_GLOBAL_POOLS.equals(reader.getLocalName())) { useGlobalPools = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS connection factory useGlobalPools: " + useGlobalPools); } break; case XMLStreamConstants.END_ELEMENT: - if (XmlDataConstants.JMS_CONNECTION_FACTORY.equals(reader.getLocalName())) - { + if (XmlDataConstants.JMS_CONNECTION_FACTORY.equals(reader.getLocalName())) { endLoop = true; } break; } - if (endLoop) - { + if (endLoop) { break; } reader.next(); @@ -881,102 +757,54 @@ public final class XmlDataImporter extends ActionAbstract ClientRequestor requestor = new ClientRequestor(managementSession, "jms.queue.activemq.management"); ClientMessage managementMessage = managementSession.createMessage(false); - ManagementHelper.putOperationInvocation(managementMessage, - ResourceNames.JMS_SERVER, - "createConnectionFactory", - name, - Boolean.parseBoolean(ha), - discoveryGroupName.length() > 0, - Integer.parseInt(type), - connectors, - entries, - clientId, - Long.parseLong(clientFailureCheckPeriod), - Long.parseLong(connectionTtl), - Long.parseLong(callTimeout), - Long.parseLong(callFailoverTimeout), - Integer.parseInt(minLargeMessageSize), - Boolean.parseBoolean(compressLargeMessages), - Integer.parseInt(consumerWindowSize), - Integer.parseInt(consumerMaxRate), - Integer.parseInt(confirmationWindowSize), - Integer.parseInt(producerWindowSize), - Integer.parseInt(producerMaxRate), - Boolean.parseBoolean(blockOnAcknowledge), - Boolean.parseBoolean(blockOnDurableSend), - Boolean.parseBoolean(blockOnNonDurableSend), - Boolean.parseBoolean(autoGroup), - Boolean.parseBoolean(preacknowledge), - loadBalancingPolicyClassName, - Integer.parseInt(transactionBatchSize), - Integer.parseInt(dupsOkBatchSize), - Boolean.parseBoolean(useGlobalPools), - Integer.parseInt(scheduledThreadMaxPoolSize), - Integer.parseInt(threadMaxPoolSize), - Long.parseLong(retryInterval), - Double.parseDouble(retryIntervalMultiplier), - Long.parseLong(maxRetryInterval), - Integer.parseInt(reconnectAttempts), - Boolean.parseBoolean(failoverOnInitialConnection), - groupId); + ManagementHelper.putOperationInvocation(managementMessage, ResourceNames.JMS_SERVER, "createConnectionFactory", name, Boolean.parseBoolean(ha), discoveryGroupName.length() > 0, Integer.parseInt(type), connectors, entries, clientId, Long.parseLong(clientFailureCheckPeriod), Long.parseLong(connectionTtl), Long.parseLong(callTimeout), Long.parseLong(callFailoverTimeout), Integer.parseInt(minLargeMessageSize), Boolean.parseBoolean(compressLargeMessages), Integer.parseInt(consumerWindowSize), Integer.parseInt(consumerMaxRate), Integer.parseInt(confirmationWindowSize), Integer.parseInt(producerWindowSize), Integer.parseInt(producerMaxRate), Boolean.parseBoolean(blockOnAcknowledge), Boolean.parseBoolean(blockOnDurableSend), Boolean.parseBoolean(blockOnNonDurableSend), Boolean.parseBoolean(autoGroup), Boolean.parseBoolean(preacknowledge), loadBalancingPolicyClassName, Integer.parseInt(transactionBatchSize), Integer.parseInt(dupsOkBatchSize), Boolean.parseBoolean(useGlobalPools), Integer.parseInt(scheduledThreadMaxPoolSize), Integer.parseInt(threadMaxPoolSize), Long.parseLong(retryInterval), Double.parseDouble(retryIntervalMultiplier), Long.parseLong(maxRetryInterval), Integer.parseInt(reconnectAttempts), Boolean.parseBoolean(failoverOnInitialConnection), groupId); //Boolean.parseBoolean(cacheLargeMessagesClient)); managementSession.start(); ClientMessage reply = requestor.request(managementMessage); - if (ManagementHelper.hasOperationSucceeded(reply)) - { + if (ManagementHelper.hasOperationSucceeded(reply)) { ActiveMQServerLogger.LOGGER.debug("Created connection factory " + name); } - else - { + else { ActiveMQServerLogger.LOGGER.error("Problem creating " + name); } requestor.close(); } - private void createJmsDestination() throws Exception - { + private void createJmsDestination() throws Exception { String name = ""; String selector = ""; String entries = ""; String type = ""; boolean endLoop = false; - while (reader.hasNext()) - { + while (reader.hasNext()) { int eventType = reader.getEventType(); - switch (eventType) - { + switch (eventType) { case XMLStreamConstants.START_ELEMENT: - if (XmlDataConstants.JMS_DESTINATION_NAME.equals(reader.getLocalName())) - { + if (XmlDataConstants.JMS_DESTINATION_NAME.equals(reader.getLocalName())) { name = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS destination name: " + name); } - else if (XmlDataConstants.JMS_DESTINATION_SELECTOR.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_DESTINATION_SELECTOR.equals(reader.getLocalName())) { selector = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS destination selector: " + selector); } - else if (XmlDataConstants.JMS_DESTINATION_TYPE.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_DESTINATION_TYPE.equals(reader.getLocalName())) { type = reader.getElementText(); ActiveMQServerLogger.LOGGER.debug("JMS destination type: " + type); } - else if (XmlDataConstants.JMS_JNDI_ENTRIES.equals(reader.getLocalName())) - { + else if (XmlDataConstants.JMS_JNDI_ENTRIES.equals(reader.getLocalName())) { entries = getEntries(); } break; case XMLStreamConstants.END_ELEMENT: - if (XmlDataConstants.JMS_DESTINATION.equals(reader.getLocalName())) - { + if (XmlDataConstants.JMS_DESTINATION.equals(reader.getLocalName())) { endLoop = true; } break; } - if (endLoop) - { + if (endLoop) { break; } reader.next(); @@ -984,55 +812,45 @@ public final class XmlDataImporter extends ActionAbstract ClientRequestor requestor = new ClientRequestor(managementSession, "jms.queue.activemq.management"); ClientMessage managementMessage = managementSession.createMessage(false); - if ("Queue".equals(type)) - { + if ("Queue".equals(type)) { ManagementHelper.putOperationInvocation(managementMessage, ResourceNames.JMS_SERVER, "createQueue", name, entries, selector); } - else if ("Topic".equals(type)) - { + else if ("Topic".equals(type)) { ManagementHelper.putOperationInvocation(managementMessage, ResourceNames.JMS_SERVER, "createTopic", name, entries); } managementSession.start(); ClientMessage reply = requestor.request(managementMessage); - if (ManagementHelper.hasOperationSucceeded(reply)) - { + if (ManagementHelper.hasOperationSucceeded(reply)) { ActiveMQServerLogger.LOGGER.debug("Created " + type.toLowerCase() + " " + name); } - else - { + else { ActiveMQServerLogger.LOGGER.error("Problem creating " + name); } requestor.close(); } - private String getEntries() throws Exception - { + private String getEntries() throws Exception { StringBuilder entry = new StringBuilder(); boolean endLoop = false; - while (reader.hasNext()) - { + while (reader.hasNext()) { int eventType = reader.getEventType(); - switch (eventType) - { + switch (eventType) { case XMLStreamConstants.START_ELEMENT: - if (XmlDataConstants.JMS_JNDI_ENTRY.equals(reader.getLocalName())) - { + if (XmlDataConstants.JMS_JNDI_ENTRY.equals(reader.getLocalName())) { String elementText = reader.getElementText(); entry.append(elementText).append(", "); ActiveMQServerLogger.LOGGER.debug("JMS admin object JNDI entry: " + entry.toString()); } break; case XMLStreamConstants.END_ELEMENT: - if (XmlDataConstants.JMS_JNDI_ENTRIES.equals(reader.getLocalName())) - { + if (XmlDataConstants.JMS_JNDI_ENTRIES.equals(reader.getLocalName())) { endLoop = true; } break; } - if (endLoop) - { + if (endLoop) { break; } reader.next(); @@ -1041,31 +859,25 @@ public final class XmlDataImporter extends ActionAbstract return entry.delete(entry.length() - 2, entry.length()).toString(); } - private String getConnectors() throws Exception - { + private String getConnectors() throws Exception { StringBuilder entry = new StringBuilder(); boolean endLoop = false; - while (reader.hasNext()) - { + while (reader.hasNext()) { int eventType = reader.getEventType(); - switch (eventType) - { + switch (eventType) { case XMLStreamConstants.START_ELEMENT: - if (XmlDataConstants.JMS_CONNECTION_FACTORY_CONNECTOR.equals(reader.getLocalName())) - { + if (XmlDataConstants.JMS_CONNECTION_FACTORY_CONNECTOR.equals(reader.getLocalName())) { entry.append(reader.getElementText()).append(", "); } break; case XMLStreamConstants.END_ELEMENT: - if (XmlDataConstants.JMS_CONNECTION_FACTORY_CONNECTORS.equals(reader.getLocalName())) - { + if (XmlDataConstants.JMS_CONNECTION_FACTORY_CONNECTORS.equals(reader.getLocalName())) { endLoop = true; } break; } - if (endLoop) - { + if (endLoop) { break; } reader.next(); @@ -1080,8 +892,7 @@ public final class XmlDataImporter extends ActionAbstract // Private ------------------------------------------------------- - private static byte[] decode(String data) - { + private static byte[] decode(String data) { return Base64.decode(data, Base64.DONT_BREAK_LINES | Base64.URL_SAFE); } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/util/ConsumerThread.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/util/ConsumerThread.java index 8a241b7780..fea2f3e039 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/util/ConsumerThread.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/util/ConsumerThread.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.cli.commands.util; - import javax.jms.BytesMessage; import javax.jms.Destination; import javax.jms.JMSException; @@ -30,8 +29,7 @@ import javax.jms.Topic; import java.util.Enumeration; import java.util.concurrent.CountDownLatch; -public class ConsumerThread extends Thread -{ +public class ConsumerThread extends Thread { int messageCount = 1000; int receiveTimeOut = 3000; @@ -52,57 +50,45 @@ public class ConsumerThread extends Thread CountDownLatch finished; boolean bytesAsText; - public ConsumerThread(Session session, Destination destination, int threadNr) - { + public ConsumerThread(Session session, Destination destination, int threadNr) { super("Consumer " + destination.toString() + ", thread=" + threadNr); this.destination = destination; this.session = session; } @Override - public void run() - { - if (browse) - { + public void run() { + if (browse) { browse(); } - else - { + else { consume(); } } - public void browse() - { + public void browse() { running = true; QueueBrowser consumer = null; String threadName = Thread.currentThread().getName(); System.out.println(threadName + " wait until " + messageCount + " messages are consumed"); - try - { - if (filter != null) - { - consumer = session.createBrowser((Queue)destination, filter); + try { + if (filter != null) { + consumer = session.createBrowser((Queue) destination, filter); } - else - { - consumer = session.createBrowser((Queue)destination); + else { + consumer = session.createBrowser((Queue) destination); } Enumeration enumBrowse = consumer.getEnumeration(); - while (enumBrowse.hasMoreElements()) - { + while (enumBrowse.hasMoreElements()) { Message msg = enumBrowse.nextElement(); - if (msg != null) - { + if (msg != null) { System.out.println(threadName + " Received " + (msg instanceof TextMessage ? ((TextMessage) msg).getText() : msg.getJMSMessageID())); - if (verbose) - { - System.out.println("..." + msg); + if (verbose) { + System.out.println("..." + msg); } - if (bytesAsText && (msg instanceof BytesMessage)) - { + if (bytesAsText && (msg instanceof BytesMessage)) { long length = ((BytesMessage) msg).getBodyLength(); byte[] bytes = new byte[(int) length]; ((BytesMessage) msg).readBytes(bytes); @@ -110,18 +96,15 @@ public class ConsumerThread extends Thread } received++; - if (received >= messageCount) - { + if (received >= messageCount) { break; } } - else - { + else { break; } - if (sleep > 0) - { + if (sleep > 0) { Thread.sleep(sleep); } @@ -129,25 +112,19 @@ public class ConsumerThread extends Thread consumer.close(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } - finally - { - if (finished != null) - { + finally { + if (finished != null) { finished.countDown(); } - if (consumer != null) - { + if (consumer != null) { System.out.println(threadName + " Consumed: " + this.getReceived() + " messages"); - try - { + try { consumer.close(); } - catch (JMSException e) - { + catch (JMSException e) { e.printStackTrace(); } } @@ -156,48 +133,36 @@ public class ConsumerThread extends Thread System.out.println(threadName + " Consumer thread finished"); } - public void consume() - { + public void consume() { running = true; MessageConsumer consumer = null; String threadName = Thread.currentThread().getName(); System.out.println(threadName + " wait until " + messageCount + " messages are consumed"); - try - { - if (durable && destination instanceof Topic) - { - if (filter != null) - { + try { + if (durable && destination instanceof Topic) { + if (filter != null) { consumer = session.createDurableSubscriber((Topic) destination, getName(), filter, false); } - else - { + else { consumer = session.createDurableSubscriber((Topic) destination, getName()); } } - else - { - if (filter != null) - { + else { + if (filter != null) { consumer = session.createConsumer(destination, filter); } - else - { + else { consumer = session.createConsumer(destination); } } - while (running && received < messageCount) - { + while (running && received < messageCount) { Message msg = consumer.receive(receiveTimeOut); - if (msg != null) - { + if (msg != null) { System.out.println(threadName + " Received " + (msg instanceof TextMessage ? ((TextMessage) msg).getText() : msg.getJMSMessageID())); - if (verbose) - { - System.out.println("..." + msg); + if (verbose) { + System.out.println("..." + msg); } - if (bytesAsText && (msg instanceof BytesMessage)) - { + if (bytesAsText && (msg instanceof BytesMessage)) { long length = ((BytesMessage) msg).getBodyLength(); byte[] bytes = new byte[(int) length]; ((BytesMessage) msg).readBytes(bytes); @@ -205,64 +170,49 @@ public class ConsumerThread extends Thread } received++; } - else - { - if (breakOnNull) - { + else { + if (breakOnNull) { break; } } - if (session.getTransacted()) - { - if (batchSize > 0 && received > 0 && received % batchSize == 0) - { + if (session.getTransacted()) { + if (batchSize > 0 && received > 0 && received % batchSize == 0) { System.out.println(threadName + " Committing transaction: " + transactions++); session.commit(); } } - else if (session.getAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE) - { - if (batchSize > 0 && received > 0 && received % batchSize == 0) - { + else if (session.getAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE) { + if (batchSize > 0 && received > 0 && received % batchSize == 0) { System.out.println("Acknowledging last " + batchSize + " messages; messages so far = " + received); msg.acknowledge(); } } - if (sleep > 0) - { + if (sleep > 0) { Thread.sleep(sleep); } } - try - { + try { session.commit(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } - finally - { - if (finished != null) - { + finally { + if (finished != null) { finished.countDown(); } - if (consumer != null) - { + if (consumer != null) { System.out.println(threadName + " Consumed: " + this.getReceived() + " messages"); - try - { + try { consumer.close(); } - catch (JMSException e) - { + catch (JMSException e) { e.printStackTrace(); } } @@ -271,139 +221,114 @@ public class ConsumerThread extends Thread System.out.println(threadName + " Consumer thread finished"); } - public int getReceived() - { + public int getReceived() { return received; } - public boolean isDurable() - { + public boolean isDurable() { return durable; } - public ConsumerThread setDurable(boolean durable) - { + public ConsumerThread setDurable(boolean durable) { this.durable = durable; return this; } - public ConsumerThread setMessageCount(int messageCount) - { + public ConsumerThread setMessageCount(int messageCount) { this.messageCount = messageCount; return this; } - public ConsumerThread setBreakOnNull(boolean breakOnNull) - { + public ConsumerThread setBreakOnNull(boolean breakOnNull) { this.breakOnNull = breakOnNull; return this; } - public int getBatchSize() - { + public int getBatchSize() { return batchSize; } - public ConsumerThread setBatchSize(int batchSize) - { + public ConsumerThread setBatchSize(int batchSize) { this.batchSize = batchSize; return this; } - public int getMessageCount() - { + public int getMessageCount() { return messageCount; } - public boolean isBreakOnNull() - { + public boolean isBreakOnNull() { return breakOnNull; } - public int getReceiveTimeOut() - { + public int getReceiveTimeOut() { return receiveTimeOut; } - public ConsumerThread setReceiveTimeOut(int receiveTimeOut) - { + public ConsumerThread setReceiveTimeOut(int receiveTimeOut) { this.receiveTimeOut = receiveTimeOut; return this; } - public boolean isRunning() - { + public boolean isRunning() { return running; } - public ConsumerThread setRunning(boolean running) - { + public ConsumerThread setRunning(boolean running) { this.running = running; return this; } - public int getSleep() - { + public int getSleep() { return sleep; } - public ConsumerThread setSleep(int sleep) - { + public ConsumerThread setSleep(int sleep) { this.sleep = sleep; return this; } - public CountDownLatch getFinished() - { + public CountDownLatch getFinished() { return finished; } - public ConsumerThread setFinished(CountDownLatch finished) - { + public ConsumerThread setFinished(CountDownLatch finished) { this.finished = finished; return this; } - public boolean isBytesAsText() - { + public boolean isBytesAsText() { return bytesAsText; } - public boolean isVerbose() - { + public boolean isVerbose() { return verbose; } - public ConsumerThread setVerbose(boolean verbose) - { + public ConsumerThread setVerbose(boolean verbose) { this.verbose = verbose; return this; } - public ConsumerThread setBytesAsText(boolean bytesAsText) - { + public ConsumerThread setBytesAsText(boolean bytesAsText) { this.bytesAsText = bytesAsText; return this; } - public String getFilter() - { + public String getFilter() { return filter; } - public ConsumerThread setFilter(String filter) - { + public ConsumerThread setFilter(String filter) { this.filter = filter; return this; } - public boolean isBrowse() - { + public boolean isBrowse() { return browse; } - public ConsumerThread setBrowse(boolean browse) - { + public ConsumerThread setBrowse(boolean browse) { this.browse = browse; return this; } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/util/ProducerThread.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/util/ProducerThread.java index 820ebbd584..427443fb3c 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/util/ProducerThread.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/util/ProducerThread.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.cli.commands.util; - import javax.jms.BytesMessage; import javax.jms.DeliveryMode; import javax.jms.Destination; @@ -33,8 +32,8 @@ import java.util.concurrent.atomic.AtomicInteger; import org.apache.activemq.artemis.utils.ReusableLatch; -public class ProducerThread extends Thread -{ +public class ProducerThread extends Thread { + protected final Session session; boolean verbose; @@ -59,20 +58,16 @@ public class ProducerThread extends Thread final ReusableLatch finished = new ReusableLatch(1); final ReusableLatch paused = new ReusableLatch(0); - - public ProducerThread(Session session, Destination destination, int threadNr) - { + public ProducerThread(Session session, Destination destination, int threadNr) { super("Producer " + destination.toString() + ", thread=" + threadNr); this.destination = destination; this.session = session; } - public void run() - { + public void run() { MessageProducer producer = null; String threadName = Thread.currentThread().getName(); - try - { + try { producer = session.createProducer(destination); producer.setDeliveryMode(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT); producer.setTimeToLive(msgTTL); @@ -82,30 +77,24 @@ public class ProducerThread extends Thread System.out.println(threadName + " Started to calculate elapsed time ...\n"); long tStart = System.currentTimeMillis(); - if (runIndefinitely) - { - while (running) - { + if (runIndefinitely) { + while (running) { paused.await(); sendMessage(producer, threadName); sentCount.incrementAndGet(); } } - else - { - for (sentCount.set(0); sentCount.get() < messageCount && running; sentCount.incrementAndGet()) - { + else { + for (sentCount.set(0); sentCount.get() < messageCount && running; sentCount.incrementAndGet()) { paused.await(); sendMessage(producer, threadName); } } - try - { + try { session.commit(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } System.out.println(threadName + " Produced: " + this.getSentCount() + " messages"); @@ -115,96 +104,74 @@ public class ProducerThread extends Thread System.out.println(threadName + " Elapsed time in milli second : " + (tEnd - tStart) + " milli seconds"); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } - finally - { - if (finished != null) - { + finally { + if (finished != null) { finished.countDown(); } - if (producer != null) - { - try - { + if (producer != null) { + try { producer.close(); } - catch (JMSException e) - { + catch (JMSException e) { e.printStackTrace(); } } } } - private void sendMessage(MessageProducer producer, String threadName) throws Exception - { + private void sendMessage(MessageProducer producer, String threadName) throws Exception { Message message = createMessage(sentCount.get(), threadName); producer.send(message); - if (verbose) - { + if (verbose) { System.out.println(threadName + " Sent: " + (message instanceof TextMessage ? ((TextMessage) message).getText() : message.getJMSMessageID())); } - if (transactionBatchSize > 0 && sentCount.get() > 0 && sentCount.get() % transactionBatchSize == 0) - { + if (transactionBatchSize > 0 && sentCount.get() > 0 && sentCount.get() % transactionBatchSize == 0) { System.out.println(threadName + " Committing transaction: " + transactions++); session.commit(); } - if (sleep > 0) - { + if (sleep > 0) { Thread.sleep(sleep); } } - private void initPayLoad() - { - if (messageSize > 0) - { + private void initPayLoad() { + if (messageSize > 0) { payload = new byte[messageSize]; - for (int i = 0; i < payload.length; i++) - { + for (int i = 0; i < payload.length; i++) { payload[i] = '.'; } } } - protected Message createMessage(int i, String threadName) throws Exception - { + protected Message createMessage(int i, String threadName) throws Exception { Message answer; - if (payload != null) - { + if (payload != null) { answer = session.createBytesMessage(); ((BytesMessage) answer).writeBytes(payload); } - else - { - if (textMessageSize > 0) - { - if (messageText == null) - { + else { + if (textMessageSize > 0) { + if (messageText == null) { messageText = readInputStream(getClass().getResourceAsStream("demo.txt"), textMessageSize, i); } } - else if (payloadUrl != null) - { + else if (payloadUrl != null) { messageText = readInputStream(new URL(payloadUrl).openStream(), -1, i); } - else if (message != null) - { + else if (message != null) { messageText = message; } - else - { + else { messageText = createDefaultMessage(i); } answer = session.createTextMessage(messageText); } - if ((msgGroupID != null) && (!msgGroupID.isEmpty())) - { + if ((msgGroupID != null) && (!msgGroupID.isEmpty())) { answer.setStringProperty("JMSXGroupID", msgGroupID); } @@ -213,218 +180,178 @@ public class ProducerThread extends Thread return answer; } - private String readInputStream(InputStream is, int size, int messageNumber) throws IOException - { + private String readInputStream(InputStream is, int size, int messageNumber) throws IOException { InputStreamReader reader = new InputStreamReader(is); - try - { + try { char[] buffer; - if (size > 0) - { + if (size > 0) { buffer = new char[size]; } - else - { + else { buffer = new char[1024]; } int count; StringBuilder builder = new StringBuilder(); - while ((count = reader.read(buffer)) != -1) - { + while ((count = reader.read(buffer)) != -1) { builder.append(buffer, 0, count); - if (size > 0) break; + if (size > 0) + break; } return builder.toString(); } - catch (IOException ioe) - { + catch (IOException ioe) { return createDefaultMessage(messageNumber); } - finally - { + finally { reader.close(); } } - private String createDefaultMessage(int messageNumber) - { + private String createDefaultMessage(int messageNumber) { return "test message: " + messageNumber; } - public ProducerThread setMessageCount(int messageCount) - { + public ProducerThread setMessageCount(int messageCount) { this.messageCount = messageCount; return this; } - public int getSleep() - { + public int getSleep() { return sleep; } - public ProducerThread setSleep(int sleep) - { + public ProducerThread setSleep(int sleep) { this.sleep = sleep; return this; } - public int getMessageCount() - { + public int getMessageCount() { return messageCount; } - public int getSentCount() - { + public int getSentCount() { return sentCount.get(); } - public boolean isPersistent() - { + public boolean isPersistent() { return persistent; } - public ProducerThread setPersistent(boolean persistent) - { + public ProducerThread setPersistent(boolean persistent) { this.persistent = persistent; return this; } - public boolean isRunning() - { + public boolean isRunning() { return running; } - public ProducerThread setRunning(boolean running) - { + public ProducerThread setRunning(boolean running) { this.running = running; return this; } - public long getMsgTTL() - { + public long getMsgTTL() { return msgTTL; } - public ProducerThread setMsgTTL(long msgTTL) - { + public ProducerThread setMsgTTL(long msgTTL) { this.msgTTL = msgTTL; return this; } - public int getTransactionBatchSize() - { + public int getTransactionBatchSize() { return transactionBatchSize; } - public ProducerThread setTransactionBatchSize(int transactionBatchSize) - { + public ProducerThread setTransactionBatchSize(int transactionBatchSize) { this.transactionBatchSize = transactionBatchSize; return this; } - public String getMsgGroupID() - { + public String getMsgGroupID() { return msgGroupID; } - public ProducerThread setMsgGroupID(String msgGroupID) - { + public ProducerThread setMsgGroupID(String msgGroupID) { this.msgGroupID = msgGroupID; return this; } - public int getTextMessageSize() - { + public int getTextMessageSize() { return textMessageSize; } - public ProducerThread setTextMessageSize(int textMessageSize) - { + public ProducerThread setTextMessageSize(int textMessageSize) { this.textMessageSize = textMessageSize; return this; } - public int getMessageSize() - { + public int getMessageSize() { return messageSize; } - public ProducerThread setMessageSize(int messageSize) - { + public ProducerThread setMessageSize(int messageSize) { this.messageSize = messageSize; return this; } - public ReusableLatch getFinished() - { + public ReusableLatch getFinished() { return finished; } - public ProducerThread setFinished(int value) - { + public ProducerThread setFinished(int value) { finished.setCount(value); return this; } - public String getPayloadUrl() - { + public String getPayloadUrl() { return payloadUrl; } - public ProducerThread setPayloadUrl(String payloadUrl) - { + public ProducerThread setPayloadUrl(String payloadUrl) { this.payloadUrl = payloadUrl; return this; } - public String getMessage() - { + public String getMessage() { return message; } - public ProducerThread setMessage(String message) - { + public ProducerThread setMessage(String message) { this.message = message; return this; } - public boolean isRunIndefinitely() - { + public boolean isRunIndefinitely() { return runIndefinitely; } - public ProducerThread setRunIndefinitely(boolean runIndefinitely) - { + public ProducerThread setRunIndefinitely(boolean runIndefinitely) { this.runIndefinitely = runIndefinitely; return this; } - public ProducerThread pauseProducer() - { + public ProducerThread pauseProducer() { this.paused.countUp(); return this; } - public ProducerThread resumeProducer() - { + public ProducerThread resumeProducer() { this.paused.countDown(); return this; } - public ProducerThread resetCounters() - { + public ProducerThread resetCounters() { this.sentCount.set(0); return this; } - - public boolean isVerbose() - { + public boolean isVerbose() { return verbose; } - public ProducerThread setVerbose(boolean verbose) - { + public ProducerThread setVerbose(boolean verbose) { this.verbose = verbose; return this; } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/util/SyncCalculation.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/util/SyncCalculation.java index b5a88453b6..e3799d90a1 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/util/SyncCalculation.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/util/SyncCalculation.java @@ -35,19 +35,22 @@ import org.apache.activemq.artemis.utils.ReusableLatch; * It will perform a simple test to evaluate how many syncs a disk can make per second * * * */ -public class SyncCalculation -{ +public class SyncCalculation { + /** * It will perform a write test of blockSize * bocks, sinc on each write, for N tries. * It will return the lowest spent time from the tries. */ - public static long syncTest(File datafolder, int blockSize, int blocks, int tries, boolean verbose, boolean aio) throws Exception - { + public static long syncTest(File datafolder, + int blockSize, + int blocks, + int tries, + boolean verbose, + boolean aio) throws Exception { SequentialFileFactory factory = newFactory(datafolder, aio); SequentialFile file = factory.createSequentialFile("test.tmp"); - try - { + try { file.delete(); file.open(); @@ -57,8 +60,7 @@ public class SyncCalculation byte[] block = new byte[blockSize]; - for (int i = 0; i < block.length; i++) - { + for (int i = 0; i < block.length; i++) { block[i] = (byte) 't'; } @@ -68,39 +70,32 @@ public class SyncCalculation final ReusableLatch latch = new ReusableLatch(0); - IOCallback callback = new IOCallback() - { + IOCallback callback = new IOCallback() { @Override - public void done() - { + public void done() { latch.countDown(); } @Override - public void onError(int errorCode, String errorMessage) - { + public void onError(int errorCode, String errorMessage) { } }; DecimalFormat dcformat = new DecimalFormat("###.##"); - for (int ntry = 0; ntry < tries; ntry++) - { + for (int ntry = 0; ntry < tries; ntry++) { - if (verbose) - { + if (verbose) { System.out.println("**************************************************"); System.out.println(ntry + " of " + tries + " calculation"); } file.position(0); long start = System.currentTimeMillis(); - for (int i = 0; i < blocks; i++) - { + for (int i = 0; i < blocks; i++) { bufferBlock.position(0); latch.countUp(); file.writeDirect(bufferBlock, true, callback); - if (!latch.await(5, TimeUnit.SECONDS)) - { + if (!latch.await(5, TimeUnit.SECONDS)) { throw new IOException("Callback wasn't called"); } } @@ -108,9 +103,8 @@ public class SyncCalculation result[ntry] = (end - start); - if (verbose) - { - double writesPerMillisecond = (double)blocks / (double) result[ntry]; + if (verbose) { + double writesPerMillisecond = (double) blocks / (double) result[ntry]; System.out.println("Time = " + result[ntry]); System.out.println("Writes / millisecond = " + dcformat.format(writesPerMillisecond)); System.out.println("bufferTimeout = " + toNanos(result[ntry], blocks)); @@ -121,45 +115,34 @@ public class SyncCalculation factory.releaseDirectBuffer(bufferBlock); long totalTime = Long.MAX_VALUE; - for (int i = 0; i < tries; i++) - { - if (result[i] < totalTime) - { + for (int i = 0; i < tries; i++) { + if (result[i] < totalTime) { totalTime = result[i]; } } return totalTime; } - finally - { - try - { + finally { + try { file.close(); } - catch (Exception e) - { + catch (Exception e) { } - try - { + try { file.delete(); } - catch (Exception e) - { + catch (Exception e) { } - try - { + try { factory.stop(); } - catch (Exception e) - { + catch (Exception e) { } } } - - public static long toNanos(long time, long blocks) - { + public static long toNanos(long time, long blocks) { double blocksPerMillisecond = (double) blocks / (double) (time); @@ -170,18 +153,15 @@ public class SyncCalculation return timeWait; } - private static SequentialFileFactory newFactory(File datafolder, boolean aio) - { - if (aio && LibaioContext.isLoaded()) - { + private static SequentialFileFactory newFactory(File datafolder, boolean aio) { + if (aio && LibaioContext.isLoaded()) { SequentialFileFactory factory = new AIOSequentialFileFactory(datafolder, 1); factory.start(); ((AIOSequentialFileFactory) factory).disableBufferReuse(); return factory; } - else - { + else { SequentialFileFactory factory = new NIOSequentialFileFactory(datafolder, 1); factory.start(); return factory; diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/process/ProcessBuilder.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/process/ProcessBuilder.java index eaf4865538..bbfb82ffd8 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/process/ProcessBuilder.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/process/ProcessBuilder.java @@ -24,19 +24,15 @@ import java.io.InputStreamReader; import org.apache.activemq.artemis.utils.ConcurrentHashSet; -public class ProcessBuilder -{ +public class ProcessBuilder { + static ConcurrentHashSet processes = new ConcurrentHashSet<>(); - static - { - Runtime.getRuntime().addShutdownHook(new Thread() - { - public void run() - { - for (Process p : processes) - { -// if (p.isAlive()) + static { + Runtime.getRuntime().addShutdownHook(new Thread() { + public void run() { + for (Process p : processes) { + // if (p.isAlive()) { p.destroy(); } @@ -45,43 +41,36 @@ public class ProcessBuilder }); } - /** * it will lookup for process that are dead already, eliminating leaks. */ - public static void cleanupProcess() - { - for (Process p: processes) - { -// if (!p.isAlive()) + public static void cleanupProcess() { + for (Process p : processes) { + // if (!p.isAlive()) { processes.remove(p); } } } - - /** * * - * @param logname the prefix for log output + * + * @param logname the prefix for log output * @param location The location where this command is being executed from - * @param hook it will finish the process upon shutdown of the VM - * @param args The arguments being passwed to the the CLI tool + * @param hook it will finish the process upon shutdown of the VM + * @param args The arguments being passwed to the the CLI tool * @return * @throws Exception */ - public static Process build(String logname, File location, boolean hook, String... args) throws Exception - { + public static Process build(String logname, File location, boolean hook, String... args) throws Exception { boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().trim().startsWith("win"); String[] newArgs; - if (IS_WINDOWS) - { + if (IS_WINDOWS) { newArgs = rebuildArgs(args, "cmd", "/c", "artemis.cmd"); } - else - { + else { newArgs = rebuildArgs(args, "./artemis"); } @@ -91,17 +80,11 @@ public class ProcessBuilder Process process = builder.start(); - ProcessLogger outputLogger = new ProcessLogger(true, - process.getInputStream(), - logname, - false); + ProcessLogger outputLogger = new ProcessLogger(true, process.getInputStream(), logname, false); outputLogger.start(); // Adding a reader to System.err, so the VM won't hang on a System.err.println as identified on this forum thread: - ProcessLogger errorLogger = new ProcessLogger(true, - process.getErrorStream(), - logname, - true); + ProcessLogger errorLogger = new ProcessLogger(true, process.getErrorStream(), logname, true); errorLogger.start(); processes.add(process); @@ -111,31 +94,27 @@ public class ProcessBuilder return process; } - public static String[] rebuildArgs(String[] args, String ... prefixArgs) - { + public static String[] rebuildArgs(String[] args, String... prefixArgs) { String[] resultArgs = new String[args.length + prefixArgs.length]; int i = 0; - for (String arg: prefixArgs) - { + for (String arg : prefixArgs) { resultArgs[i++] = arg; } - for (String arg: args) - { + for (String arg : args) { resultArgs[i++] = arg; } return resultArgs; } - /** * Redirect the input stream to a logger (as debug logs) */ - static class ProcessLogger extends Thread - { + static class ProcessLogger extends Thread { + private final InputStream is; private final String logName; @@ -149,8 +128,7 @@ public class ProcessBuilder ProcessLogger(final boolean print, final InputStream is, final String logName, - final boolean sendToErr) throws ClassNotFoundException - { + final boolean sendToErr) throws ClassNotFoundException { this.is = is; this.print = print; this.logName = logName; @@ -159,30 +137,23 @@ public class ProcessBuilder } @Override - public void run() - { - try - { + public void run() { + try { InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; - while ((line = br.readLine()) != null) - { - if (print) - { - if (sendToErr) - { + while ((line = br.readLine()) != null) { + if (print) { + if (sendToErr) { System.err.println(logName + "-err:" + line); } - else - { + else { System.out.println(logName + "-out:" + line); } } } } - catch (IOException e) - { + catch (IOException e) { // ok, stream closed } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/components/ExternalComponent.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/components/ExternalComponent.java index 434fc7125a..4969d6a3b2 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/components/ExternalComponent.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/components/ExternalComponent.java @@ -19,7 +19,7 @@ package org.apache.activemq.artemis.components; import org.apache.activemq.artemis.core.server.ActiveMQComponent; import org.apache.activemq.artemis.dto.ComponentDTO; -public interface ExternalComponent extends ActiveMQComponent -{ +public interface ExternalComponent extends ActiveMQComponent { + void configure(ComponentDTO config, String artemisInstance, String artemisHome) throws Exception; } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/BasicSecurityHandler.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/BasicSecurityHandler.java index ebd71e4239..b8eb2a57db 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/BasicSecurityHandler.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/BasicSecurityHandler.java @@ -24,14 +24,10 @@ import org.apache.activemq.artemis.dto.SecurityDTO; import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManager; import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManagerImpl; -public class BasicSecurityHandler implements SecurityHandler -{ +public class BasicSecurityHandler implements SecurityHandler { - - static String fixupFileURI(String value) - { - if (value != null && value.startsWith("file:")) - { + static String fixupFileURI(String value) { + if (value != null && value.startsWith("file:")) { value = value.substring("file:".length()); value = new File(value).toURI().toString(); } @@ -39,15 +35,10 @@ public class BasicSecurityHandler implements SecurityHandler } @Override - public ActiveMQSecurityManager createSecurityManager(SecurityDTO security) throws Exception - { + public ActiveMQSecurityManager createSecurityManager(SecurityDTO security) throws Exception { BasicSecurityDTO fileSecurity = (BasicSecurityDTO) security; String home = System.getProperty("activemq.home"); - FileSecurityConfiguration securityConfiguration = new FileSecurityConfiguration(fixupFileURI(fileSecurity.users), - fixupFileURI(fileSecurity.roles), - fileSecurity.defaultUser, - fileSecurity.maskPassword, - fileSecurity.passwordCodec); + FileSecurityConfiguration securityConfiguration = new FileSecurityConfiguration(fixupFileURI(fileSecurity.users), fixupFileURI(fileSecurity.roles), fileSecurity.defaultUser, fileSecurity.maskPassword, fileSecurity.passwordCodec); securityConfiguration.start(); return new ActiveMQSecurityManagerImpl(securityConfiguration); } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/BrokerFactory.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/BrokerFactory.java index edcfd7fa22..6ca026bd83 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/BrokerFactory.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/BrokerFactory.java @@ -27,60 +27,47 @@ import org.apache.activemq.artemis.integration.Broker; import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManager; import org.apache.activemq.artemis.utils.FactoryFinder; -public class BrokerFactory -{ +public class BrokerFactory { - public static BrokerDTO createBrokerConfiguration(URI configURI) throws Exception - { - if (configURI.getScheme() == null) - { + public static BrokerDTO createBrokerConfiguration(URI configURI) throws Exception { + if (configURI.getScheme() == null) { throw new ConfigurationException("Invalid configuration URI, no scheme specified: " + configURI); } BrokerFactoryHandler factory = null; - try - { + try { FactoryFinder finder = new FactoryFinder("META-INF/services/org/apache/activemq/artemis/broker/"); factory = (BrokerFactoryHandler) finder.newInstance(configURI.getScheme()); } - catch (IOException ioe) - { + catch (IOException ioe) { throw new ConfigurationException("Invalid configuration URI, can't find configuration scheme: " + configURI.getScheme()); } - return factory.createBroker(configURI); } - public static BrokerDTO createBrokerConfiguration(String configuration) throws Exception - { + public static BrokerDTO createBrokerConfiguration(String configuration) throws Exception { return createBrokerConfiguration(new URI(configuration)); } - static String fixupFileURI(String value) - { - if (value != null && value.startsWith("file:")) - { + static String fixupFileURI(String value) { + if (value != null && value.startsWith("file:")) { value = value.substring("file:".length()); value = new File(value).toURI().toString(); } return value; } - public static Broker createServer(ServerDTO brokerDTO, ActiveMQSecurityManager security) throws Exception - { - if (brokerDTO.configuration != null) - { + public static Broker createServer(ServerDTO brokerDTO, ActiveMQSecurityManager security) throws Exception { + if (brokerDTO.configuration != null) { BrokerHandler handler; URI configURI = brokerDTO.getConfigurationURI(); - try - { + try { FactoryFinder finder = new FactoryFinder("META-INF/services/org/apache/activemq/artemis/broker/server/"); handler = (BrokerHandler) finder.newInstance(configURI.getScheme()); } - catch (IOException ioe) - { + catch (IOException ioe) { throw new ConfigurationException("Invalid configuration URI, can't find configuration scheme: " + configURI.getScheme()); } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/BrokerFactoryHandler.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/BrokerFactoryHandler.java index 04c0e4df32..b0d96d9506 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/BrokerFactoryHandler.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/BrokerFactoryHandler.java @@ -20,7 +20,7 @@ import org.apache.activemq.artemis.dto.BrokerDTO; import java.net.URI; -public interface BrokerFactoryHandler -{ +public interface BrokerFactoryHandler { + BrokerDTO createBroker(URI brokerURI) throws Exception; } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/BrokerHandler.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/BrokerHandler.java index 9f65a8e265..3fe4027b41 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/BrokerHandler.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/BrokerHandler.java @@ -20,7 +20,7 @@ import org.apache.activemq.artemis.dto.ServerDTO; import org.apache.activemq.artemis.integration.Broker; import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManager; -public interface BrokerHandler -{ +public interface BrokerHandler { + Broker createServer(ServerDTO brokerDTO, ActiveMQSecurityManager security); } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/FileBrokerHandler.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/FileBrokerHandler.java index 75ac4f5d11..f6afc7f93d 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/FileBrokerHandler.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/FileBrokerHandler.java @@ -21,11 +21,10 @@ import org.apache.activemq.artemis.integration.Broker; import org.apache.activemq.artemis.integration.FileBroker; import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManager; -public class FileBrokerHandler implements BrokerHandler -{ +public class FileBrokerHandler implements BrokerHandler { + @Override - public Broker createServer(ServerDTO brokerDTO, ActiveMQSecurityManager security) - { + public Broker createServer(ServerDTO brokerDTO, ActiveMQSecurityManager security) { return new FileBroker(brokerDTO, security); } } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/SecurityHandler.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/SecurityHandler.java index 6eb6b0cab3..75768d06c5 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/SecurityHandler.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/SecurityHandler.java @@ -19,7 +19,7 @@ package org.apache.activemq.artemis.factory; import org.apache.activemq.artemis.dto.SecurityDTO; import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManager; -public interface SecurityHandler -{ +public interface SecurityHandler { + ActiveMQSecurityManager createSecurityManager(SecurityDTO securityDTO) throws Exception; } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/SecurityManagerFactory.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/SecurityManagerFactory.java index 1453bd33df..c4223087c1 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/SecurityManagerFactory.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/SecurityManagerFactory.java @@ -22,19 +22,15 @@ import org.apache.activemq.artemis.utils.FactoryFinder; import javax.xml.bind.annotation.XmlRootElement; -public class SecurityManagerFactory -{ +public class SecurityManagerFactory { - public static ActiveMQSecurityManager create(SecurityDTO config) throws Exception - { - if (config != null) - { + public static ActiveMQSecurityManager create(SecurityDTO config) throws Exception { + if (config != null) { FactoryFinder finder = new FactoryFinder("META-INF/services/org/apache/activemq/artemis/broker/security/"); - SecurityHandler securityHandler = (SecurityHandler)finder.newInstance(config.getClass().getAnnotation(XmlRootElement.class).name()); + SecurityHandler securityHandler = (SecurityHandler) finder.newInstance(config.getClass().getAnnotation(XmlRootElement.class).name()); return securityHandler.createSecurityManager(config); } - else - { + else { throw new Exception("No security manager configured!"); } } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/XmlBrokerFactoryHandler.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/XmlBrokerFactoryHandler.java index 11e195d501..adbb04150f 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/XmlBrokerFactoryHandler.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/factory/XmlBrokerFactoryHandler.java @@ -23,14 +23,12 @@ import org.apache.activemq.artemis.dto.XmlUtil; import java.io.File; import java.net.URI; -public class XmlBrokerFactoryHandler implements BrokerFactoryHandler -{ +public class XmlBrokerFactoryHandler implements BrokerFactoryHandler { + @Override - public BrokerDTO createBroker(URI brokerURI) throws Exception - { + public BrokerDTO createBroker(URI brokerURI) throws Exception { File file = new File(brokerURI.getSchemeSpecificPart()); - if (!file.exists()) - { + if (!file.exists()) { throw new ConfigurationException("Invalid configuration URI, can't find file: " + file.getName()); } return XmlUtil.decode(BrokerDTO.class, file); diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/integration/Broker.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/integration/Broker.java index 8e1a4dc431..306675fa7b 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/integration/Broker.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/integration/Broker.java @@ -21,6 +21,6 @@ import org.apache.activemq.artemis.core.server.ActiveMQComponent; /** * A Broker os a set of ActiveMQComponents that create a Server, for instance core and jms. */ -public interface Broker extends ActiveMQComponent -{ +public interface Broker extends ActiveMQComponent { + } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/integration/FileBroker.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/integration/FileBroker.java index ec5a44f48b..b66f6aa97c 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/integration/FileBroker.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/integration/FileBroker.java @@ -28,8 +28,8 @@ import java.lang.management.ManagementFactory; import java.util.ArrayList; import java.util.Map; -public class FileBroker implements Broker -{ +public class FileBroker implements Broker { + private final String configurationUrl; private boolean started; @@ -38,17 +38,13 @@ public class FileBroker implements Broker private Map components; - public FileBroker(ServerDTO broker, ActiveMQSecurityManager security) - { + public FileBroker(ServerDTO broker, ActiveMQSecurityManager security) { this.securityManager = security; this.configurationUrl = broker.configuration; } - - public synchronized void start() throws Exception - { - if (started) - { + public synchronized void start() throws Exception { + if (started) { return; } @@ -64,39 +60,32 @@ public class FileBroker implements Broker ArrayList componentsByStartOrder = getComponentsByStartOrder(components); ActiveMQBootstrapLogger.LOGGER.serverStarting(); - for (ActiveMQComponent component : componentsByStartOrder) - { + for (ActiveMQComponent component : componentsByStartOrder) { component.start(); } started = true; - } @Override - public void stop() throws Exception - { - if (!started) - { + public void stop() throws Exception { + if (!started) { return; } ActiveMQComponent[] mqComponents = new ActiveMQComponent[components.size()]; components.values().toArray(mqComponents); - for (int i = mqComponents.length - 1; i >= 0; i--) - { + for (int i = mqComponents.length - 1; i >= 0; i--) { mqComponents[i].stop(); } started = false; } @Override - public boolean isStarted() - { + public boolean isStarted() { return started; } - public Map getComponents() - { + public Map getComponents() { return components; } @@ -104,12 +93,10 @@ public class FileBroker implements Broker * this makes sure the components are started in the correct order. Its simple at the mo as e only have core and jms but * will need impproving if we get more. * */ - public ArrayList getComponentsByStartOrder(Map components) - { + public ArrayList getComponentsByStartOrder(Map components) { ArrayList activeMQComponents = new ArrayList(); ActiveMQComponent jmsComponent = components.get("jms"); - if (jmsComponent != null) - { + if (jmsComponent != null) { activeMQComponents.add(jmsComponent); } activeMQComponents.add(components.get("core")); diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/integration/bootstrap/ActiveMQBootstrapBundle.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/integration/bootstrap/ActiveMQBootstrapBundle.java index 5f31b01dc2..5bb168ca2a 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/integration/bootstrap/ActiveMQBootstrapBundle.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/integration/bootstrap/ActiveMQBootstrapBundle.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.integration.bootstrap; - import org.jboss.logging.Messages; import org.jboss.logging.annotations.MessageBundle; @@ -28,8 +27,8 @@ import org.jboss.logging.annotations.MessageBundle; * so 109000 to 109999 */ @MessageBundle(projectCode = "AMQ") -public interface ActiveMQBootstrapBundle -{ +public interface ActiveMQBootstrapBundle { + ActiveMQBootstrapBundle BUNDLE = Messages.getBundle(ActiveMQBootstrapBundle.class); } diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/integration/bootstrap/ActiveMQBootstrapLogger.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/integration/bootstrap/ActiveMQBootstrapLogger.java index 3cd976f04b..1f7e6d9707 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/integration/bootstrap/ActiveMQBootstrapLogger.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/integration/bootstrap/ActiveMQBootstrapLogger.java @@ -38,8 +38,8 @@ import org.jboss.logging.annotations.MessageLogger; * so an INFO message would be 101000 to 101999 */ @MessageLogger(projectCode = "AMQ") -public interface ActiveMQBootstrapLogger extends BasicLogger -{ +public interface ActiveMQBootstrapLogger extends BasicLogger { + /** * The default logger. */ diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/util/ServerUtil.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/util/ServerUtil.java index 9b384cd584..6c4689e4a8 100644 --- a/artemis-cli/src/main/java/org/apache/activemq/artemis/util/ServerUtil.java +++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/util/ServerUtil.java @@ -33,68 +33,52 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; -public class ServerUtil -{ - public static Process startServer(String artemisInstance, String serverName) throws Exception - { +public class ServerUtil { + + public static Process startServer(String artemisInstance, String serverName) throws Exception { return startServer(artemisInstance, serverName, 0, 0); } - public static Process startServer(String artemisInstance, String serverName, int id, int timeout) throws Exception - { + public static Process startServer(String artemisInstance, String serverName, int id, int timeout) throws Exception { boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().trim().startsWith("win"); ProcessBuilder builder = null; - if (IS_WINDOWS) - { + if (IS_WINDOWS) { builder = new ProcessBuilder("cmd", "/c", "artemis.cmd", "run"); } - else - { + else { builder = new ProcessBuilder("./artemis", "run"); } builder.directory(new File(artemisInstance + "/bin")); final Process process = builder.start(); - Runtime.getRuntime().addShutdownHook(new Thread() - { - public void run() - { + Runtime.getRuntime().addShutdownHook(new Thread() { + public void run() { process.destroy(); } }); - ProcessLogger outputLogger = new ProcessLogger(true, - process.getInputStream(), - serverName, - false); + ProcessLogger outputLogger = new ProcessLogger(true, process.getInputStream(), serverName, false); outputLogger.start(); // Adding a reader to System.err, so the VM won't hang on a System.err.println as identified on this forum thread: // http://www.jboss.org/index.html?module=bb&op=viewtopic&t=151815 - ProcessLogger errorLogger = new ProcessLogger(true, - process.getErrorStream(), - serverName, - true); + ProcessLogger errorLogger = new ProcessLogger(true, process.getErrorStream(), serverName, true); errorLogger.start(); // wait for start - if (timeout != 0) - { + if (timeout != 0) { waitForServerToStart(id, timeout); } return process; } - public static void waitForServerToStart(int id, int timeout) throws InterruptedException - { + public static void waitForServerToStart(int id, int timeout) throws InterruptedException { long realTimeout = System.currentTimeMillis() + timeout; - while (System.currentTimeMillis() < realTimeout) - { - try - { + while (System.currentTimeMillis() < realTimeout) { + try { HashMap params = new HashMap(); params.put("host", "localhost"); params.put("port", 61616 + id); @@ -103,8 +87,7 @@ public class ServerUtil cf.createConnection().close(); System.out.println("server " + id + " started"); } - catch (Exception e) - { + catch (Exception e) { System.out.println("awaiting server " + id + " start at " + (61616 + id)); Thread.sleep(500); continue; @@ -113,10 +96,8 @@ public class ServerUtil } } - public static void killServer(final Process server) throws Exception - { - if (server != null) - { + public static void killServer(final Process server) throws Exception { + if (server != null) { System.out.println("**********************************"); System.out.println("Killing server " + server); System.out.println("**********************************"); @@ -126,35 +107,30 @@ public class ServerUtil } } - public static int getServer(Connection connection) - { + public static int getServer(Connection connection) { ClientSession session = ((ActiveMQConnection) connection).getInitialSession(); TransportConfiguration transportConfiguration = session.getSessionFactory().getConnectorConfiguration(); String port = (String) transportConfiguration.getParams().get("port"); return Integer.valueOf(port) - 61616; } - public static Connection getServerConnection(int server, Connection... connections) - { - for (Connection connection : connections) - { + public static Connection getServerConnection(int server, Connection... connections) { + for (Connection connection : connections) { ClientSession session = ((ActiveMQConnection) connection).getInitialSession(); TransportConfiguration transportConfiguration = session.getSessionFactory().getConnectorConfiguration(); String port = (String) transportConfiguration.getParams().get("port"); - if (Integer.valueOf(port) == server + 61616) - { + if (Integer.valueOf(port) == server + 61616) { return connection; } } return null; } - /** * Redirect the input stream to a logger (as debug logs) */ - static class ProcessLogger extends Thread - { + static class ProcessLogger extends Thread { + private final InputStream is; private final String logName; @@ -166,8 +142,7 @@ public class ServerUtil ProcessLogger(final boolean print, final InputStream is, final String logName, - final boolean sendToErr) throws ClassNotFoundException - { + final boolean sendToErr) throws ClassNotFoundException { this.is = is; this.print = print; this.logName = logName; @@ -176,30 +151,23 @@ public class ServerUtil } @Override - public void run() - { - try - { + public void run() { + try { InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; - while ((line = br.readLine()) != null) - { - if (print) - { - if (sendToErr) - { + while ((line = br.readLine()) != null) { + if (print) { + if (sendToErr) { System.err.println(logName + "-err:" + line); } - else - { + else { System.out.println(logName + "-out:" + line); } } } } - catch (IOException e) - { + catch (IOException e) { // ok, stream closed } } diff --git a/artemis-cli/src/test/java/org/apache/activemq/cli/test/ArtemisTest.java b/artemis-cli/src/test/java/org/apache/activemq/cli/test/ArtemisTest.java index a42fae92e7..cfcc53f985 100644 --- a/artemis-cli/src/test/java/org/apache/activemq/cli/test/ArtemisTest.java +++ b/artemis-cli/src/test/java/org/apache/activemq/cli/test/ArtemisTest.java @@ -43,41 +43,35 @@ import org.junit.rules.TemporaryFolder; /** * Test to validate that the CLI doesn't throw improper exceptions when invoked. */ -public class ArtemisTest -{ +public class ArtemisTest { + @Rule public TemporaryFolder temporaryFolder; - public ArtemisTest() - { + public ArtemisTest() { File parent = new File("./target/tmp"); parent.mkdirs(); temporaryFolder = new TemporaryFolder(parent); } - @After - public void cleanup() - { + public void cleanup() { System.clearProperty("artemis.instance"); Run.setEmbedded(false); } @Test - public void invalidCliDoesntThrowException() - { + public void invalidCliDoesntThrowException() { testCli("create"); } @Test - public void invalidPathDoesntThrowException() - { - testCli("create","/rawr"); + public void invalidPathDoesntThrowException() { + testCli("create", "/rawr"); } @Test - public void testSync() throws Exception - { + public void testSync() throws Exception { int writes = 2560; int tries = 10; long totalAvg = SyncCalculation.syncTest(temporaryFolder.getRoot(), 4096, writes, tries, true, true); @@ -88,9 +82,9 @@ public class ArtemisTest Assert.assertEquals(0, LibaioContext.getTotalMaxIO()); } + @Test - public void testSimpleRun() throws Exception - { + public void testSimpleRun() throws Exception { String queues = "q1,t2"; String topics = "t1,t2"; Run.setEmbedded(true); @@ -99,24 +93,19 @@ public class ArtemisTest // Some exceptions may happen on the initialization, but they should be ok on start the basic core protocol Artemis.execute("run"); - try (ServerLocator locator = ServerLocatorImpl.newLocator("tcp://localhost:61616"); ClientSessionFactory factory = locator.createSessionFactory(); - ClientSession coreSession = factory.createSession()) - { - for (String str: queues.split(",")) - { + ClientSession coreSession = factory.createSession()) { + for (String str : queues.split(",")) { ClientSession.QueueQuery queryResult = coreSession.queueQuery(SimpleString.toSimpleString("jms.queue." + str)); Assert.assertTrue("Couldn't find queue " + str, queryResult.isExists()); } - for (String str: topics.split(",")) - { + for (String str : topics.split(",")) { ClientSession.QueueQuery queryResult = coreSession.queueQuery(SimpleString.toSimpleString("jms.topic." + str)); Assert.assertTrue("Couldn't find topic " + str, queryResult.isExists()); } } - Assert.assertEquals(Integer.valueOf(1000), Artemis.execute("producer", "--message-count", "1000", "--verbose")); Assert.assertEquals(Integer.valueOf(1000), Artemis.execute("consumer", "--verbose", "--break-on-null", "--receive-timeout", "100")); @@ -125,13 +114,11 @@ public class ArtemisTest Session session = connection.createSession(true, Session.SESSION_TRANSACTED); MessageProducer producer = session.createProducer(ActiveMQDestination.createDestination("queue://TEST", ActiveMQDestination.QUEUE_TYPE)); - TextMessage message = session.createTextMessage("Banana"); message.setStringProperty("fruit", "banana"); producer.send(message); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { message = session.createTextMessage("orange"); message.setStringProperty("fruit", "orange"); producer.send(message); @@ -154,7 +141,7 @@ public class ArtemisTest Assert.assertEquals(Integer.valueOf(1), Artemis.execute("consumer", "--txt-size", "50", "--verbose", "--break-on-null", "--receive-timeout", "100", "--filter", "fruit='banana'")); // Checking it was acked before - Assert.assertEquals(Integer.valueOf(100), Artemis.execute("consumer", "--txt-size", "50", "--verbose", "--break-on-null", "--receive-timeout", "100")); + Assert.assertEquals(Integer.valueOf(100), Artemis.execute("consumer", "--txt-size", "50", "--verbose", "--break-on-null", "--receive-timeout", "100")); Artemis.execute("stop"); Assert.assertTrue(Run.latchRunning.await(5, TimeUnit.SECONDS)); @@ -162,14 +149,11 @@ public class ArtemisTest } - private void testCli(String... args) - { - try - { + private void testCli(String... args) { + try { Artemis.main(args); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); Assert.fail("Exception caught " + e.getMessage()); } diff --git a/artemis-cli/src/test/java/org/apache/activemq/cli/test/FileBrokerTest.java b/artemis-cli/src/test/java/org/apache/activemq/cli/test/FileBrokerTest.java index 5d86f6e681..c796f3f3d1 100644 --- a/artemis-cli/src/test/java/org/apache/activemq/cli/test/FileBrokerTest.java +++ b/artemis-cli/src/test/java/org/apache/activemq/cli/test/FileBrokerTest.java @@ -24,16 +24,14 @@ import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManagerImpl import org.junit.Assert; import org.junit.Test; -public class FileBrokerTest -{ +public class FileBrokerTest { + @Test - public void startWithJMS() throws Exception - { + public void startWithJMS() throws Exception { ServerDTO serverDTO = new ServerDTO(); serverDTO.configuration = "broker.xml"; FileBroker broker = null; - try - { + try { broker = new FileBroker(serverDTO, new ActiveMQSecurityManagerImpl()); broker.start(); JMSServerManagerImpl jmsServerManager = (JMSServerManagerImpl) broker.getComponents().get("jms"); @@ -46,23 +44,19 @@ public class FileBrokerTest Assert.assertTrue(activeMQServer.isStarted()); Assert.assertTrue(broker.isStarted()); } - finally - { - if (broker != null) - { + finally { + if (broker != null) { broker.stop(); } } } @Test - public void startWithoutJMS() throws Exception - { + public void startWithoutJMS() throws Exception { ServerDTO serverDTO = new ServerDTO(); serverDTO.configuration = "broker-nojms.xml"; FileBroker broker = null; - try - { + try { broker = new FileBroker(serverDTO, new ActiveMQSecurityManagerImpl()); broker.start(); JMSServerManagerImpl jmsServerManager = (JMSServerManagerImpl) broker.getComponents().get("jms"); @@ -72,8 +66,7 @@ public class FileBrokerTest Assert.assertTrue(activeMQServer.isStarted()); Assert.assertTrue(broker.isStarted()); } - finally - { + finally { assert broker != null; broker.stop(); } diff --git a/artemis-cli/src/test/java/org/apache/activemq/cli/test/StreamClassPathTest.java b/artemis-cli/src/test/java/org/apache/activemq/cli/test/StreamClassPathTest.java index 0ee3afbcf5..21579dc9b0 100644 --- a/artemis-cli/src/test/java/org/apache/activemq/cli/test/StreamClassPathTest.java +++ b/artemis-cli/src/test/java/org/apache/activemq/cli/test/StreamClassPathTest.java @@ -23,13 +23,13 @@ import org.apache.activemq.artemis.cli.commands.Create; import org.junit.Assert; import org.junit.Test; -public class StreamClassPathTest -{ +public class StreamClassPathTest { - /** Validate if all the known resources are available on the classpath for the jar */ + /** + * Validate if all the known resources are available on the classpath for the jar + */ @Test - public void testFindStreams() throws Exception - { + public void testFindStreams() throws Exception { openStream(Create.BIN_ARTEMIS_CMD); openStream(Create.BIN_ARTEMIS_SERVICE_EXE); openStream(Create.BIN_ARTEMIS_SERVICE_XML); @@ -52,9 +52,7 @@ public class StreamClassPathTest openStream(Create.ETC_JOURNAL_BUFFER_SETTINGS); } - - private void openStream(String source) throws Exception - { + private void openStream(String source) throws Exception { Create create = new Create(); InputStream in = create.openStream(source); Assert.assertNotNull(source + " not found", in); diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQAddressExistsException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQAddressExistsException.java index aeec7a87df..9477bb84c4 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQAddressExistsException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQAddressExistsException.java @@ -19,17 +19,15 @@ package org.apache.activemq.artemis.api.core; /** * An operation failed because an address exists on the server. */ -public final class ActiveMQAddressExistsException extends ActiveMQException -{ +public final class ActiveMQAddressExistsException extends ActiveMQException { + private static final long serialVersionUID = 3032730450033992367L; - public ActiveMQAddressExistsException() - { + public ActiveMQAddressExistsException() { super(ActiveMQExceptionType.ADDRESS_EXISTS); } - public ActiveMQAddressExistsException(String msg) - { + public ActiveMQAddressExistsException(String msg) { super(ActiveMQExceptionType.ADDRESS_EXISTS, msg); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQAddressFullException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQAddressFullException.java index c8cbe458a3..1cd5b6338c 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQAddressFullException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQAddressFullException.java @@ -19,17 +19,15 @@ package org.apache.activemq.artemis.api.core; /** * An address is full. */ -public final class ActiveMQAddressFullException extends ActiveMQException -{ +public final class ActiveMQAddressFullException extends ActiveMQException { + private static final long serialVersionUID = 0; - public ActiveMQAddressFullException(String message) - { + public ActiveMQAddressFullException(String message) { super(ActiveMQExceptionType.ADDRESS_FULL, message); } - public ActiveMQAddressFullException() - { + public ActiveMQAddressFullException() { super(ActiveMQExceptionType.ADDRESS_FULL); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQAlreadyReplicatingException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQAlreadyReplicatingException.java index 125c4921d9..dd3348c260 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQAlreadyReplicatingException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQAlreadyReplicatingException.java @@ -19,17 +19,15 @@ package org.apache.activemq.artemis.api.core; /** * The server is already paired with a replicating backup. */ -public final class ActiveMQAlreadyReplicatingException extends ActiveMQException -{ +public final class ActiveMQAlreadyReplicatingException extends ActiveMQException { + private static final long serialVersionUID = -7352538521961996152L; - public ActiveMQAlreadyReplicatingException() - { + public ActiveMQAlreadyReplicatingException() { super(ActiveMQExceptionType.ALREADY_REPLICATING); } - public ActiveMQAlreadyReplicatingException(String msg) - { + public ActiveMQAlreadyReplicatingException(String msg) { super(ActiveMQExceptionType.ALREADY_REPLICATING, msg); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQBuffer.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQBuffer.java index 63d956c927..12dd09f8cc 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQBuffer.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQBuffer.java @@ -26,10 +26,11 @@ import io.netty.buffer.ByteBuf; * Instances of it can be obtained from {@link ActiveMQBuffers} factory. *

* Much of it derived from Netty ChannelBuffer by Trustin Lee + * * @see ActiveMQBuffers */ -public interface ActiveMQBuffer -{ +public interface ActiveMQBuffer { + /** * Returns the underlying Netty's ByteBuf * @@ -52,11 +53,10 @@ public interface ActiveMQBuffer /** * Sets the {@code readerIndex} of this buffer. * - * @throws IndexOutOfBoundsException - * if the specified {@code readerIndex} is - * less than {@code 0} or - * greater than {@code this.writerIndex} * @param readerIndex The reader's index The reader infex + * @throws IndexOutOfBoundsException if the specified {@code readerIndex} is + * less than {@code 0} or + * greater than {@code this.writerIndex} */ void readerIndex(int readerIndex); @@ -69,10 +69,9 @@ public interface ActiveMQBuffer * Sets the {@code writerIndex} of this buffer. * * @param writerIndex The writer's index - * @throws IndexOutOfBoundsException - * if the specified {@code writerIndex} is - * less than {@code this.readerIndex} or - * greater than {@code this.capacity} + * @throws IndexOutOfBoundsException if the specified {@code writerIndex} is + * less than {@code this.readerIndex} or + * greater than {@code this.capacity} */ void writerIndex(int writerIndex); @@ -123,11 +122,10 @@ public interface ActiveMQBuffer * * @param readerIndex The reader's index * @param writerIndex The writer's index - * @throws IndexOutOfBoundsException - * if the specified {@code readerIndex} is less than 0, - * if the specified {@code writerIndex} is less than the specified - * {@code readerIndex} or if the specified {@code writerIndex} is - * greater than {@code this.capacity} + * @throws IndexOutOfBoundsException if the specified {@code readerIndex} is less than 0, + * if the specified {@code writerIndex} is less than the specified + * {@code readerIndex} or if the specified {@code writerIndex} is + * greater than {@code this.capacity} */ void setIndex(int readerIndex, int writerIndex); @@ -174,9 +172,8 @@ public interface ActiveMQBuffer * Repositions the current {@code readerIndex} to the marked * {@code readerIndex} in this buffer. * - * @throws IndexOutOfBoundsException - * if the current {@code writerIndex} is less than the marked - * {@code readerIndex} + * @throws IndexOutOfBoundsException if the current {@code writerIndex} is less than the marked + * {@code readerIndex} */ void resetReaderIndex(); @@ -192,9 +189,8 @@ public interface ActiveMQBuffer * Repositions the current {@code writerIndex} to the marked * {@code writerIndex} in this buffer. * - * @throws IndexOutOfBoundsException - * if the current {@code readerIndex} is greater than the marked - * {@code writerIndex} + * @throws IndexOutOfBoundsException if the current {@code readerIndex} is greater than the marked + * {@code writerIndex} */ void resetWriterIndex(); @@ -215,11 +211,10 @@ public interface ActiveMQBuffer * * @param index Index into the buffer * @return The byte at the specified index - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 1} is greater than {@code this.capacity} + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or + * {@code index + 1} is greater than {@code this.capacity} */ - byte getByte(int index); + byte getByte(int index); /** * Gets an unsigned byte at the specified absolute {@code index} in this @@ -228,9 +223,8 @@ public interface ActiveMQBuffer * * @param index Index into the buffer * @return an unsigned byte at the specified absolute {@code index} - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 1} is greater than {@code this.capacity} + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or + * {@code index + 1} is greater than {@code this.capacity} */ short getUnsignedByte(int index); @@ -241,9 +235,8 @@ public interface ActiveMQBuffer * * @param index Index into the buffer * @return a 16-bit short integer at the specified absolute {@code index} - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 2} is greater than {@code this.capacity} + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or + * {@code index + 2} is greater than {@code this.capacity} */ short getShort(int index); @@ -254,9 +247,8 @@ public interface ActiveMQBuffer * * @param index Index into the buffer * @return an unsigned 16-bit short integer - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 2} is greater than {@code this.capacity} + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or + * {@code index + 2} is greater than {@code this.capacity} */ int getUnsignedShort(int index); @@ -267,11 +259,10 @@ public interface ActiveMQBuffer * * @param index Index into the buffer * @return a 32-bit integer at the specified absolute {@code index} - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 4} is greater than {@code this.capacity} + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or + * {@code index + 4} is greater than {@code this.capacity} */ - int getInt(int index); + int getInt(int index); /** * Gets an unsigned 32-bit integer at the specified absolute {@code index} @@ -280,11 +271,10 @@ public interface ActiveMQBuffer * * @param index The index into this buffer * @return an unsigned 32-bit integer at the specified absolute {@code index} - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 4} is greater than {@code this.capacity} + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or + * {@code index + 4} is greater than {@code this.capacity} */ - long getUnsignedInt(int index); + long getUnsignedInt(int index); /** * Gets a 64-bit long integer at the specified absolute {@code index} in @@ -293,11 +283,10 @@ public interface ActiveMQBuffer * * @param index Index into the buffer * @return a 64-bit long integer at the specified absolute {@code index} - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 8} is greater than {@code this.capacity} + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or + * {@code index + 8} is greater than {@code this.capacity} */ - long getLong(int index); + long getLong(int index); /** * Transfers this buffer's data to the specified destination starting at @@ -311,11 +300,10 @@ public interface ActiveMQBuffer * the source buffer (i.e. {@code this}). * * @param index Index into the buffer - * @param dst The destination buffer - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * if {@code index + dst.writableBytes} is greater than - * {@code this.capacity} + * @param dst The destination buffer + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or + * if {@code index + dst.writableBytes} is greater than + * {@code this.capacity} */ void getBytes(int index, ActiveMQBuffer dst); @@ -330,13 +318,12 @@ public interface ActiveMQBuffer * the source buffer (i.e. {@code this}). * * @param length the number of bytes to transfer - * @param index Index into the buffer - * @param dst The destination buffer - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0}, - * if {@code index + length} is greater than - * {@code this.capacity}, or - * if {@code length} is greater than {@code dst.writableBytes} + * @param index Index into the buffer + * @param dst The destination buffer + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0}, + * if {@code index + length} is greater than + * {@code this.capacity}, or + * if {@code length} is greater than {@code dst.writableBytes} */ void getBytes(int index, ActiveMQBuffer dst, int length); @@ -346,18 +333,16 @@ public interface ActiveMQBuffer * This method does not modify {@code readerIndex} or {@code writerIndex} * of both the source (i.e. {@code this}) and the destination. * - * @param dst The destination bufferIndex the first index of the destination - * @param length The number of bytes to transfer - * @param index Index into the buffer + * @param dst The destination bufferIndex the first index of the destination + * @param length The number of bytes to transfer + * @param index Index into the buffer * @param dstIndex The index into the destination bufferThe destination buffer - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0}, - * if the specified {@code dstIndex} is less than {@code 0}, - * if {@code index + length} is greater than - * {@code this.capacity}, or - * if {@code dstIndex + length} is greater than - * {@code dst.capacity} + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0}, + * if the specified {@code dstIndex} is less than {@code 0}, + * if {@code index + length} is greater than + * {@code this.capacity}, or + * if {@code dstIndex + length} is greater than + * {@code dst.capacity} */ void getBytes(int index, ActiveMQBuffer dst, int dstIndex, int length); @@ -368,11 +353,10 @@ public interface ActiveMQBuffer * this buffer * * @param index Index into the buffer - * @param dst The destination buffer - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * if {@code index + dst.length} is greater than - * {@code this.capacity} + * @param dst The destination buffer + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or + * if {@code index + dst.length} is greater than + * {@code this.capacity} */ void getBytes(int index, byte[] dst); @@ -384,16 +368,14 @@ public interface ActiveMQBuffer * * @param dstIndex The first index of the destination * @param length The number of bytes to transfer - * @param index Index into the buffer - * @param dst The destination buffer - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0}, - * if the specified {@code dstIndex} is less than {@code 0}, - * if {@code index + length} is greater than - * {@code this.capacity}, or - * if {@code dstIndex + length} is greater than - * {@code dst.length} + * @param index Index into the buffer + * @param dst The destination buffer + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0}, + * if the specified {@code dstIndex} is less than {@code 0}, + * if {@code index + length} is greater than + * {@code this.capacity}, or + * if {@code dstIndex + length} is greater than + * {@code dst.length} */ void getBytes(int index, byte[] dst, int dstIndex, int length); @@ -405,11 +387,10 @@ public interface ActiveMQBuffer * this buffer while the destination's {@code position} will be increased. * * @param index Index into the buffer - * @param dst The destination buffer - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * if {@code index + dst.remaining()} is greater than - * {@code this.capacity} + * @param dst The destination buffer + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or + * if {@code index + dst.remaining()} is greater than + * {@code this.capacity} */ void getBytes(int index, ByteBuffer dst); @@ -420,9 +401,8 @@ public interface ActiveMQBuffer * * @param index Index into the buffer * @return a char at the specified absolute {@code index} - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 2} is greater than {@code this.capacity} + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or + * {@code index + 2} is greater than {@code this.capacity} */ char getChar(int index); @@ -433,9 +413,8 @@ public interface ActiveMQBuffer * * @param index Index into the buffer * @return a float at the specified absolute {@code index} - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 4} is greater than {@code this.capacity} + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or + * {@code index + 4} is greater than {@code this.capacity} */ float getFloat(int index); @@ -446,9 +425,8 @@ public interface ActiveMQBuffer * * @param index Index into the buffer * @return a double at the specified absolute {@code index} - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 8} is greater than {@code this.capacity} + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or + * {@code index + 8} is greater than {@code this.capacity} */ double getDouble(int index); @@ -460,9 +438,8 @@ public interface ActiveMQBuffer * * @param index Index into the buffer * @param value The specified byte - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 1} is greater than {@code this.capacity} + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or + * {@code index + 1} is greater than {@code this.capacity} */ void setByte(int index, byte value); @@ -474,9 +451,8 @@ public interface ActiveMQBuffer * * @param index Index into the buffer * @param value The specified 16-bit short integer - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 2} is greater than {@code this.capacity} + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or + * {@code index + 2} is greater than {@code this.capacity} */ void setShort(int index, short value); @@ -488,9 +464,8 @@ public interface ActiveMQBuffer * * @param index Index into the buffer * @param value The specified 32-bit integer - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 4} is greater than {@code this.capacity} + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or + * {@code index + 4} is greater than {@code this.capacity} */ void setInt(int index, int value); @@ -502,9 +477,8 @@ public interface ActiveMQBuffer * * @param index Index into the buffer * @param value The specified 64-bit long integer - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 8} is greater than {@code this.capacity} + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or + * {@code index + 8} is greater than {@code this.capacity} */ void setLong(int index, long value); @@ -520,11 +494,10 @@ public interface ActiveMQBuffer * the source buffer (i.e. {@code this}). * * @param index Index into the buffer - * @param src The source buffer - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * if {@code index + src.readableBytes} is greater than - * {@code this.capacity} + * @param src The source buffer + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or + * if {@code index + src.readableBytes} is greater than + * {@code this.capacity} */ void setBytes(int index, ActiveMQBuffer src); @@ -539,14 +512,12 @@ public interface ActiveMQBuffer * the source buffer (i.e. {@code this}). * * @param length the number of bytes to transfer - * @param index Index into the buffer - * @param src The source buffer - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0}, - * if {@code index + length} is greater than - * {@code this.capacity}, or - * if {@code length} is greater than {@code src.readableBytes} + * @param index Index into the buffer + * @param src The source buffer + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0}, + * if {@code index + length} is greater than + * {@code this.capacity}, or + * if {@code length} is greater than {@code src.readableBytes} */ void setBytes(int index, ActiveMQBuffer src, int length); @@ -556,18 +527,16 @@ public interface ActiveMQBuffer * This method does not modify {@code readerIndex} or {@code writerIndex} * of both the source (i.e. {@code this}) and the destination. * - * @param src The source bufferIndex the first index of the source - * @param length The number of bytes to transfer - * @param index Index into the buffer + * @param src The source bufferIndex the first index of the source + * @param length The number of bytes to transfer + * @param index Index into the buffer * @param srcIndex The source buffer index - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0}, - * if the specified {@code srcIndex} is less than {@code 0}, - * if {@code index + length} is greater than - * {@code this.capacity}, or - * if {@code srcIndex + length} is greater than - * {@code src.capacity} + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0}, + * if the specified {@code srcIndex} is less than {@code 0}, + * if {@code index + length} is greater than + * {@code this.capacity}, or + * if {@code srcIndex + length} is greater than + * {@code src.capacity} */ void setBytes(int index, ActiveMQBuffer src, int srcIndex, int length); @@ -578,11 +547,10 @@ public interface ActiveMQBuffer * this buffer. * * @param index Index into the buffer - * @param src The source buffer - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * if {@code index + src.length} is greater than - * {@code this.capacity} + * @param src The source buffer + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or + * if {@code index + src.length} is greater than + * {@code this.capacity} */ void setBytes(int index, byte[] src); @@ -592,17 +560,15 @@ public interface ActiveMQBuffer * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * - * @param index Index into the buffer - * @param src The source buffer + * @param index Index into the buffer + * @param src The source buffer * @param srcIndex The source buffer index - * @param length The number of bytes to transfer - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0}, - * if the specified {@code srcIndex} is less than {@code 0}, - * if {@code index + length} is greater than - * {@code this.capacity}, or - * if {@code srcIndex + length} is greater than {@code src.length} + * @param length The number of bytes to transfer + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0}, + * if the specified {@code srcIndex} is less than {@code 0}, + * if {@code index + length} is greater than + * {@code this.capacity}, or + * if {@code srcIndex + length} is greater than {@code src.length} */ void setBytes(int index, byte[] src, int srcIndex, int length); @@ -614,11 +580,10 @@ public interface ActiveMQBuffer * this buffer. * * @param index Index into the buffer - * @param src The source buffer - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * if {@code index + src.remaining()} is greater than - * {@code this.capacity} + * @param src The source buffer + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or + * if {@code index + src.remaining()} is greater than + * {@code this.capacity} */ void setBytes(int index, ByteBuffer src); @@ -630,9 +595,8 @@ public interface ActiveMQBuffer * * @param index Index into the buffer * @param value The specified char - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 2} is greater than {@code this.capacity} + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or + * {@code index + 2} is greater than {@code this.capacity} */ void setChar(int index, char value); @@ -644,9 +608,8 @@ public interface ActiveMQBuffer * * @param index Index into the buffer * @param value The specified float - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 4} is greater than {@code this.capacity} + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or + * {@code index + 4} is greater than {@code this.capacity} */ void setFloat(int index, float value); @@ -658,9 +621,8 @@ public interface ActiveMQBuffer * * @param index Index into the buffer * @param value The specified double - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 8} is greater than {@code this.capacity} + * @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or + * {@code index + 8} is greater than {@code this.capacity} */ void setDouble(int index, double value); @@ -669,8 +631,7 @@ public interface ActiveMQBuffer * the {@code readerIndex} by {@code 1} in this buffer. * * @return a byte at the current {@code readerIndex} - * @throws IndexOutOfBoundsException - * if {@code this.readableBytes} is less than {@code 1} + * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than {@code 1} */ byte readByte(); @@ -679,8 +640,7 @@ public interface ActiveMQBuffer * the {@code readerIndex} by {@code 1} in this buffer. * * @return an unsigned byte at the current {@code readerIndex} - * @throws IndexOutOfBoundsException - * if {@code this.readableBytes} is less than {@code 1} + * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than {@code 1} */ short readUnsignedByte(); @@ -689,8 +649,7 @@ public interface ActiveMQBuffer * and increases the {@code readerIndex} by {@code 2} in this buffer. * * @return a 16-bit short integer at the current {@code readerIndex} - * @throws IndexOutOfBoundsException - * if {@code this.readableBytes} is less than {@code 2} + * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than {@code 2} */ short readShort(); @@ -699,48 +658,43 @@ public interface ActiveMQBuffer * and increases the {@code readerIndex} by {@code 2} in this buffer. * * @return an unsigned 16-bit short integer at the current {@code readerIndex} - * @throws IndexOutOfBoundsException - * if {@code this.readableBytes} is less than {@code 2} + * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than {@code 2} */ - int readUnsignedShort(); + int readUnsignedShort(); /** * Gets a 32-bit integer at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 4} in this buffer. * * @return a 32-bit integer at the current {@code readerIndex} - * @throws IndexOutOfBoundsException - * if {@code this.readableBytes} is less than {@code 4} + * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than {@code 4} */ - int readInt(); + int readInt(); /** * Gets an unsigned 32-bit integer at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 4} in this buffer. * * @return an unsigned 32-bit integer at the current {@code readerIndex} - * @throws IndexOutOfBoundsException - * if {@code this.readableBytes} is less than {@code 4} + * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than {@code 4} */ - long readUnsignedInt(); + long readUnsignedInt(); /** * Gets a 64-bit integer at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 8} in this buffer. * * @return a 64-bit integer at the current {@code readerIndex} - * @throws IndexOutOfBoundsException - * if {@code this.readableBytes} is less than {@code 8} + * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than {@code 8} */ - long readLong(); + long readLong(); /** * Gets a char at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 2} in this buffer. * * @return a char at the current {@code readerIndex} - * @throws IndexOutOfBoundsException - * if {@code this.readableBytes} is less than {@code 2} + * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than {@code 2} */ char readChar(); @@ -749,8 +703,7 @@ public interface ActiveMQBuffer * and increases the {@code readerIndex} by {@code 4} in this buffer. * * @return a float at the current {@code readerIndex} - * @throws IndexOutOfBoundsException - * if {@code this.readableBytes} is less than {@code 4} + * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than {@code 4} */ float readFloat(); @@ -759,8 +712,7 @@ public interface ActiveMQBuffer * and increases the {@code readerIndex} by {@code 8} in this buffer. * * @return a double at the current {@code readerIndex} - * @throws IndexOutOfBoundsException - * if {@code this.readableBytes} is less than {@code 8} + * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than {@code 8} */ double readDouble(); @@ -769,8 +721,7 @@ public interface ActiveMQBuffer * and increases the {@code readerIndex} by {@code 1} in this buffer. * * @return a boolean at the current {@code readerIndex} - * @throws IndexOutOfBoundsException - * if {@code this.readableBytes} is less than {@code 1} + * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than {@code 1} */ boolean readBoolean(); @@ -817,11 +768,8 @@ public interface ActiveMQBuffer * {@code 0} and {@code length} respectively. * * @param length the number of bytes to transfer - * @return the newly created buffer which contains the transferred bytes - * - * @throws IndexOutOfBoundsException - * if {@code length} is greater than {@code this.readableBytes} + * @throws IndexOutOfBoundsException if {@code length} is greater than {@code this.readableBytes} */ ActiveMQBuffer readBytes(int length); @@ -831,11 +779,8 @@ public interface ActiveMQBuffer * of the new slice (= {@code length}). * * @param length the size of the new slice - * * @return the newly created slice - * - * @throws IndexOutOfBoundsException - * if {@code length} is greater than {@code this.readableBytes} + * @throws IndexOutOfBoundsException if {@code length} is greater than {@code this.readableBytes} */ ActiveMQBuffer readSlice(int length); @@ -850,9 +795,8 @@ public interface ActiveMQBuffer * does not. * * @param dst The destination buffer - * @throws IndexOutOfBoundsException - * if {@code dst.writableBytes} is greater than - * {@code this.readableBytes} + * @throws IndexOutOfBoundsException if {@code dst.writableBytes} is greater than + * {@code this.readableBytes} */ void readBytes(ActiveMQBuffer dst); @@ -865,11 +809,10 @@ public interface ActiveMQBuffer * destination by the number of the transferred bytes (= {@code length}) * while {@link #readBytes(ActiveMQBuffer, int, int)} does not. * - * @param dst The destination buffer + * @param dst The destination buffer * @param length The number of bytes to transfer - * @throws IndexOutOfBoundsException - * if {@code length} is greater than {@code this.readableBytes} or - * if {@code length} is greater than {@code dst.writableBytes} + * @throws IndexOutOfBoundsException if {@code length} is greater than {@code this.readableBytes} or + * if {@code length} is greater than {@code dst.writableBytes} */ void readBytes(ActiveMQBuffer dst, int length); @@ -880,13 +823,11 @@ public interface ActiveMQBuffer * * @param dstIndex The destination buffer index * @param length the number of bytes to transfer - * @param dst The destination buffer - * - * @throws IndexOutOfBoundsException - * if the specified {@code dstIndex} is less than {@code 0}, - * if {@code length} is greater than {@code this.readableBytes}, or - * if {@code dstIndex + length} is greater than - * {@code dst.capacity} + * @param dst The destination buffer + * @throws IndexOutOfBoundsException if the specified {@code dstIndex} is less than {@code 0}, + * if {@code length} is greater than {@code this.readableBytes}, or + * if {@code dstIndex + length} is greater than + * {@code dst.capacity} */ void readBytes(ActiveMQBuffer dst, int dstIndex, int length); @@ -896,8 +837,7 @@ public interface ActiveMQBuffer * by the number of the transferred bytes (= {@code dst.length}). * * @param dst The destination buffer - * @throws IndexOutOfBoundsException - * if {@code dst.length} is greater than {@code this.readableBytes} + * @throws IndexOutOfBoundsException if {@code dst.length} is greater than {@code this.readableBytes} */ void readBytes(byte[] dst); @@ -908,12 +848,10 @@ public interface ActiveMQBuffer * * @param dstIndex The destination bufferIndex * @param length the number of bytes to transfer - * @param dst The destination buffer - * - * @throws IndexOutOfBoundsException - * if the specified {@code dstIndex} is less than {@code 0}, - * if {@code length} is greater than {@code this.readableBytes}, or - * if {@code dstIndex + length} is greater than {@code dst.length} + * @param dst The destination buffer + * @throws IndexOutOfBoundsException if the specified {@code dstIndex} is less than {@code 0}, + * if {@code length} is greater than {@code this.readableBytes}, or + * if {@code dstIndex + length} is greater than {@code dst.length} */ void readBytes(byte[] dst, int dstIndex, int length); @@ -924,9 +862,8 @@ public interface ActiveMQBuffer * number of the transferred bytes. * * @param dst The destination buffer - * @throws IndexOutOfBoundsException - * if {@code dst.remaining()} is greater than - * {@code this.readableBytes} + * @throws IndexOutOfBoundsException if {@code dst.remaining()} is greater than + * {@code this.readableBytes} */ void readBytes(ByteBuffer dst); @@ -935,8 +872,7 @@ public interface ActiveMQBuffer * {@code length} in this buffer. * * @param length The number of bytes to skip - * @throws IndexOutOfBoundsException - * if {@code length} is greater than {@code this.readableBytes} + * @throws IndexOutOfBoundsException if {@code length} is greater than {@code this.readableBytes} */ void skipBytes(int length); @@ -945,10 +881,9 @@ public interface ActiveMQBuffer * and increases the {@code writerIndex} by {@code 1} in this buffer. * * @param value The specified byte - * @throws IndexOutOfBoundsException - * if {@code this.writableBytes} is less than {@code 1} + * @throws IndexOutOfBoundsException if {@code this.writableBytes} is less than {@code 1} */ - void writeByte(byte value); + void writeByte(byte value); /** * Sets the specified 16-bit short integer at the current @@ -956,8 +891,7 @@ public interface ActiveMQBuffer * in this buffer. * * @param value The specified 16-bit short integer - * @throws IndexOutOfBoundsException - * if {@code this.writableBytes} is less than {@code 2} + * @throws IndexOutOfBoundsException if {@code this.writableBytes} is less than {@code 2} */ void writeShort(short value); @@ -966,10 +900,9 @@ public interface ActiveMQBuffer * and increases the {@code writerIndex} by {@code 4} in this buffer. * * @param value The specified 32-bit integer - * @throws IndexOutOfBoundsException - * if {@code this.writableBytes} is less than {@code 4} + * @throws IndexOutOfBoundsException if {@code this.writableBytes} is less than {@code 4} */ - void writeInt(int value); + void writeInt(int value); /** * Sets the specified 64-bit long integer at the current @@ -977,18 +910,16 @@ public interface ActiveMQBuffer * in this buffer. * * @param value The specified 64-bit long integer - * @throws IndexOutOfBoundsException - * if {@code this.writableBytes} is less than {@code 8} + * @throws IndexOutOfBoundsException if {@code this.writableBytes} is less than {@code 8} */ - void writeLong(long value); + void writeLong(long value); /** * Sets the specified char at the current {@code writerIndex} * and increases the {@code writerIndex} by {@code 2} in this buffer. * * @param chr The specified char - * @throws IndexOutOfBoundsException - * if {@code this.writableBytes} is less than {@code 2} + * @throws IndexOutOfBoundsException if {@code this.writableBytes} is less than {@code 2} */ void writeChar(char chr); @@ -997,8 +928,7 @@ public interface ActiveMQBuffer * and increases the {@code writerIndex} by {@code 4} in this buffer. * * @param value The specified float - * @throws IndexOutOfBoundsException - * if {@code this.writableBytes} is less than {@code 4} + * @throws IndexOutOfBoundsException if {@code this.writableBytes} is less than {@code 4} */ void writeFloat(float value); @@ -1007,13 +937,13 @@ public interface ActiveMQBuffer * and increases the {@code writerIndex} by {@code 8} in this buffer. * * @param value The specified double - * @throws IndexOutOfBoundsException - * if {@code this.writableBytes} is less than {@code 8} + * @throws IndexOutOfBoundsException if {@code this.writableBytes} is less than {@code 8} */ void writeDouble(double value); /** * Sets the specified boolean at the current {@code writerIndex} + * * @param val The specified boolean */ void writeBoolean(boolean val); @@ -1064,10 +994,9 @@ public interface ActiveMQBuffer * {@link #writeBytes(ActiveMQBuffer, int, int)} does not. * * @param length the number of bytes to transfer - * @param src The source buffer - * @throws IndexOutOfBoundsException - * if {@code length} is greater than {@code this.writableBytes} or - * if {@code length} is greater then {@code src.readableBytes} + * @param src The source buffer + * @throws IndexOutOfBoundsException if {@code length} is greater than {@code this.writableBytes} or + * if {@code length} is greater then {@code src.readableBytes} */ void writeBytes(ActiveMQBuffer src, int length); @@ -1078,13 +1007,11 @@ public interface ActiveMQBuffer * * @param srcIndex the first index of the source * @param length the number of bytes to transfer - * @param src The source buffer - * - * @throws IndexOutOfBoundsException - * if the specified {@code srcIndex} is less than {@code 0}, - * if {@code srcIndex + length} is greater than - * {@code src.capacity}, or - * if {@code length} is greater than {@code this.writableBytes} + * @param src The source buffer + * @throws IndexOutOfBoundsException if the specified {@code srcIndex} is less than {@code 0}, + * if {@code srcIndex + length} is greater than + * {@code src.capacity}, or + * if {@code length} is greater than {@code this.writableBytes} */ void writeBytes(ActiveMQBuffer src, int srcIndex, int length); @@ -1094,8 +1021,7 @@ public interface ActiveMQBuffer * by the number of the transferred bytes (= {@code src.length}). * * @param src The source buffer - * @throws IndexOutOfBoundsException - * if {@code src.length} is greater than {@code this.writableBytes} + * @throws IndexOutOfBoundsException if {@code src.length} is greater than {@code this.writableBytes} */ void writeBytes(byte[] src); @@ -1106,13 +1032,11 @@ public interface ActiveMQBuffer * * @param srcIndex the first index of the source * @param length the number of bytes to transfer - * @param src The source buffer - * - * @throws IndexOutOfBoundsException - * if the specified {@code srcIndex} is less than {@code 0}, - * if {@code srcIndex + length} is greater than - * {@code src.length}, or - * if {@code length} is greater than {@code this.writableBytes} + * @param src The source buffer + * @throws IndexOutOfBoundsException if the specified {@code srcIndex} is less than {@code 0}, + * if {@code srcIndex + length} is greater than + * {@code src.length}, or + * if {@code length} is greater than {@code this.writableBytes} */ void writeBytes(byte[] src, int srcIndex, int length); @@ -1123,9 +1047,8 @@ public interface ActiveMQBuffer * number of the transferred bytes. * * @param src The source buffer - * @throws IndexOutOfBoundsException - * if {@code src.remaining()} is greater than - * {@code this.writableBytes} + * @throws IndexOutOfBoundsException if {@code src.remaining()} is greater than + * {@code this.writableBytes} */ void writeBytes(ByteBuffer src); @@ -1146,7 +1069,7 @@ public interface ActiveMQBuffer * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * - * @param index Index into the buffer + * @param index Index into the buffer * @param length The number of bytes to copy * @return a copy of this buffer's readable bytes. */ @@ -1171,7 +1094,7 @@ public interface ActiveMQBuffer * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * - * @param index Index into the buffer + * @param index Index into the buffer * @param length The number of bytes * @return a slice of this buffer's sub-region. */ @@ -1208,7 +1131,7 @@ public interface ActiveMQBuffer * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * - * @param index Index into the buffer + * @param index Index into the buffer * @param length The number of bytes * @return A converted NIO Buffer */ diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQBuffers.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQBuffers.java index 34fee4d575..22f0f9a9a4 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQBuffers.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQBuffers.java @@ -24,16 +24,15 @@ import org.apache.activemq.artemis.core.buffers.impl.ChannelBufferWrapper; /** * Factory class to create instances of {@link ActiveMQBuffer}. */ -public final class ActiveMQBuffers -{ +public final class ActiveMQBuffers { + /** * Creates a self-expanding ActiveMQBuffer with the given initial size * * @param size the initial size of the created ActiveMQBuffer * @return a self-expanding ActiveMQBuffer starting with the given size */ - public static ActiveMQBuffer dynamicBuffer(final int size) - { + public static ActiveMQBuffer dynamicBuffer(final int size) { return new ChannelBufferWrapper(Unpooled.buffer(size)); } @@ -43,8 +42,7 @@ public final class ActiveMQBuffers * @param bytes the created buffer will be initially filled with this byte array * @return a self-expanding ActiveMQBuffer filled with the given byte array */ - public static ActiveMQBuffer dynamicBuffer(final byte[] bytes) - { + public static ActiveMQBuffer dynamicBuffer(final byte[] bytes) { ActiveMQBuffer buff = dynamicBuffer(bytes.length); buff.writeBytes(bytes); @@ -60,8 +58,7 @@ public final class ActiveMQBuffers * @param underlying the underlying NIO ByteBuffer * @return an ActiveMQBuffer wrapping the underlying NIO ByteBuffer */ - public static ActiveMQBuffer wrappedBuffer(final ByteBuffer underlying) - { + public static ActiveMQBuffer wrappedBuffer(final ByteBuffer underlying) { ActiveMQBuffer buff = new ChannelBufferWrapper(Unpooled.wrappedBuffer(underlying)); buff.clear(); @@ -75,8 +72,7 @@ public final class ActiveMQBuffers * @param underlying the underlying byte array * @return an ActiveMQBuffer wrapping the underlying byte array */ - public static ActiveMQBuffer wrappedBuffer(final byte[] underlying) - { + public static ActiveMQBuffer wrappedBuffer(final byte[] underlying) { return new ChannelBufferWrapper(Unpooled.wrappedBuffer(underlying)); } @@ -86,13 +82,11 @@ public final class ActiveMQBuffers * @param size the size of the created ActiveMQBuffer * @return a fixed ActiveMQBuffer with the given size */ - public static ActiveMQBuffer fixedBuffer(final int size) - { + public static ActiveMQBuffer fixedBuffer(final int size) { return new ChannelBufferWrapper(Unpooled.buffer(size, size)); } - private ActiveMQBuffers() - { + private ActiveMQBuffers() { // Utility class } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQClusterSecurityException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQClusterSecurityException.java index 8d53de7bac..6543e42dc6 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQClusterSecurityException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQClusterSecurityException.java @@ -19,17 +19,15 @@ package org.apache.activemq.artemis.api.core; /** * Security exception thrown when the cluster user fails authentication. */ -public final class ActiveMQClusterSecurityException extends ActiveMQException -{ +public final class ActiveMQClusterSecurityException extends ActiveMQException { + private static final long serialVersionUID = -5890578849781297933L; - public ActiveMQClusterSecurityException() - { + public ActiveMQClusterSecurityException() { super(ActiveMQExceptionType.CLUSTER_SECURITY_EXCEPTION); } - public ActiveMQClusterSecurityException(final String msg) - { + public ActiveMQClusterSecurityException(final String msg) { super(ActiveMQExceptionType.CLUSTER_SECURITY_EXCEPTION, msg); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQConnectionTimedOutException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQConnectionTimedOutException.java index 13c11dd917..1b8a3c72d6 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQConnectionTimedOutException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQConnectionTimedOutException.java @@ -19,17 +19,15 @@ package org.apache.activemq.artemis.api.core; /** * A client timed out will connecting to ActiveMQ Artemis server. */ -public final class ActiveMQConnectionTimedOutException extends ActiveMQException -{ +public final class ActiveMQConnectionTimedOutException extends ActiveMQException { + private static final long serialVersionUID = 3244233758084830372L; - public ActiveMQConnectionTimedOutException() - { + public ActiveMQConnectionTimedOutException() { super(ActiveMQExceptionType.CONNECTION_TIMEDOUT); } - public ActiveMQConnectionTimedOutException(String msg) - { + public ActiveMQConnectionTimedOutException(String msg) { super(ActiveMQExceptionType.CONNECTION_TIMEDOUT, msg); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQDisconnectedException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQDisconnectedException.java index 2ce6882f05..45a0e7aa1b 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQDisconnectedException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQDisconnectedException.java @@ -19,17 +19,15 @@ package org.apache.activemq.artemis.api.core; /** * A client was disconnected from ActiveMQ Artemis server when the server has shut down. */ -public final class ActiveMQDisconnectedException extends ActiveMQException -{ +public final class ActiveMQDisconnectedException extends ActiveMQException { + private static final long serialVersionUID = 7414966383933311627L; - public ActiveMQDisconnectedException() - { + public ActiveMQDisconnectedException() { super(ActiveMQExceptionType.DISCONNECTED); } - public ActiveMQDisconnectedException(String message) - { + public ActiveMQDisconnectedException(String message) { super(ActiveMQExceptionType.DISCONNECTED, message); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQDuplicateIdException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQDuplicateIdException.java index 03260cd58e..c999aaf2f9 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQDuplicateIdException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQDuplicateIdException.java @@ -19,17 +19,15 @@ package org.apache.activemq.artemis.api.core; /** * A DuplicateID was rejected. */ -public final class ActiveMQDuplicateIdException extends ActiveMQException -{ +public final class ActiveMQDuplicateIdException extends ActiveMQException { + private static final long serialVersionUID = -4302979339865777119L; - public ActiveMQDuplicateIdException() - { + public ActiveMQDuplicateIdException() { super(ActiveMQExceptionType.DUPLICATE_ID_REJECTED); } - public ActiveMQDuplicateIdException(String message) - { + public ActiveMQDuplicateIdException(String message) { super(ActiveMQExceptionType.DUPLICATE_ID_REJECTED, message); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQDuplicateMetaDataException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQDuplicateMetaDataException.java index 40f2acbc52..a452011c7e 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQDuplicateMetaDataException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQDuplicateMetaDataException.java @@ -19,17 +19,15 @@ package org.apache.activemq.artemis.api.core; /** * A Session Metadata was set in duplication */ -public final class ActiveMQDuplicateMetaDataException extends ActiveMQException -{ +public final class ActiveMQDuplicateMetaDataException extends ActiveMQException { + private static final long serialVersionUID = 7877182872143004058L; - public ActiveMQDuplicateMetaDataException() - { + public ActiveMQDuplicateMetaDataException() { super(ActiveMQExceptionType.DUPLICATE_METADATA); } - public ActiveMQDuplicateMetaDataException(String msg) - { + public ActiveMQDuplicateMetaDataException(String msg) { super(ActiveMQExceptionType.DUPLICATE_METADATA, msg); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQException.java index 8fa3a18d9d..13a35b1d51 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQException.java @@ -19,19 +19,17 @@ package org.apache.activemq.artemis.api.core; /** * ActiveMQException is the root exception for the ActiveMQ Artemis API. */ -public class ActiveMQException extends Exception -{ +public class ActiveMQException extends Exception { + private static final long serialVersionUID = -4802014152804997417L; private final ActiveMQExceptionType type; - public ActiveMQException() - { + public ActiveMQException() { type = ActiveMQExceptionType.GENERIC_EXCEPTION; } - public ActiveMQException(final String msg) - { + public ActiveMQException(final String msg) { super(msg); type = ActiveMQExceptionType.GENERIC_EXCEPTION; } @@ -39,39 +37,33 @@ public class ActiveMQException extends Exception /* * This constructor is needed only for the native layer */ - public ActiveMQException(int code, String msg) - { + public ActiveMQException(int code, String msg) { super(msg); this.type = ActiveMQExceptionType.getType(code); } - public ActiveMQException(ActiveMQExceptionType type, String msg) - { + public ActiveMQException(ActiveMQExceptionType type, String msg) { super(msg); this.type = type; } - public ActiveMQException(ActiveMQExceptionType type) - { + public ActiveMQException(ActiveMQExceptionType type) { this.type = type; } - public ActiveMQException(ActiveMQExceptionType type, String message, Throwable t) - { + public ActiveMQException(ActiveMQExceptionType type, String message, Throwable t) { super(message, t); this.type = type; } - public ActiveMQExceptionType getType() - { + public ActiveMQExceptionType getType() { return type; } @Override - public String toString() - { + public String toString() { return this.getClass().getSimpleName() + "[errorType=" + type + " message=" + getMessage() + "]"; } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQExceptionType.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQExceptionType.java index 700508e152..6aca1d013d 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQExceptionType.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQExceptionType.java @@ -24,200 +24,151 @@ import java.util.Map; /** * Defines all {@link ActiveMQException} types and their codes. */ -public enum ActiveMQExceptionType -{ +public enum ActiveMQExceptionType { // Error codes ------------------------------------------------- - INTERNAL_ERROR(000) - { + INTERNAL_ERROR(000) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQInternalErrorException(msg); } }, - UNSUPPORTED_PACKET(001) - { + UNSUPPORTED_PACKET(001) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQUnsupportedPacketException(msg); } }, - NOT_CONNECTED(002) - { + NOT_CONNECTED(002) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQNotConnectedException(msg); } }, - CONNECTION_TIMEDOUT(003) - { + CONNECTION_TIMEDOUT(003) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQConnectionTimedOutException(msg); } }, - DISCONNECTED(004) - { + DISCONNECTED(004) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQDisconnectedException(msg); } }, - UNBLOCKED(005) - { + UNBLOCKED(005) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQUnBlockedException(msg); } }, - IO_ERROR(006) - { + IO_ERROR(006) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQIOErrorException(msg); } }, - QUEUE_DOES_NOT_EXIST(100) - { + QUEUE_DOES_NOT_EXIST(100) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQNonExistentQueueException(msg); } }, - QUEUE_EXISTS(101) - { + QUEUE_EXISTS(101) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQQueueExistsException(msg); } }, - OBJECT_CLOSED(102) - { + OBJECT_CLOSED(102) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQObjectClosedException(msg); } }, - INVALID_FILTER_EXPRESSION(103) - { + INVALID_FILTER_EXPRESSION(103) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQInvalidFilterExpressionException(msg); } }, - ILLEGAL_STATE(104) - { + ILLEGAL_STATE(104) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQIllegalStateException(msg); } }, - SECURITY_EXCEPTION(105) - { + SECURITY_EXCEPTION(105) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQSecurityException(msg); } }, - ADDRESS_EXISTS(107) - { + ADDRESS_EXISTS(107) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQAddressExistsException(msg); } }, - INCOMPATIBLE_CLIENT_SERVER_VERSIONS(108) - { + INCOMPATIBLE_CLIENT_SERVER_VERSIONS(108) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQIncompatibleClientServerException(msg); } }, - LARGE_MESSAGE_ERROR_BODY(110) - { + LARGE_MESSAGE_ERROR_BODY(110) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQLargeMessageException(msg); } }, - TRANSACTION_ROLLED_BACK(111) - { + TRANSACTION_ROLLED_BACK(111) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQTransactionRolledBackException(msg); } }, - SESSION_CREATION_REJECTED(112) - { + SESSION_CREATION_REJECTED(112) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQSessionCreationException(msg); } }, - DUPLICATE_ID_REJECTED(113) - { + DUPLICATE_ID_REJECTED(113) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQDuplicateIdException(msg); } }, - DUPLICATE_METADATA(114) - { + DUPLICATE_METADATA(114) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQDuplicateMetaDataException(msg); } }, - TRANSACTION_OUTCOME_UNKNOWN(115) - { + TRANSACTION_OUTCOME_UNKNOWN(115) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQTransactionOutcomeUnknownException(msg); } }, - ALREADY_REPLICATING(116) - { + ALREADY_REPLICATING(116) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQAlreadyReplicatingException(msg); } }, - INTERCEPTOR_REJECTED_PACKET(117) - { + INTERCEPTOR_REJECTED_PACKET(117) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQInterceptorRejectedPacketException(msg); } }, - INVALID_TRANSIENT_QUEUE_USE(118) - { + INVALID_TRANSIENT_QUEUE_USE(118) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQInvalidTransientQueueUseException(msg); } }, @@ -232,27 +183,21 @@ public enum ActiveMQExceptionType NATIVE_ERROR_CANT_ALLOCATE_QUEUE(206), NATIVE_ERROR_PREALLOCATE_FILE(208), NATIVE_ERROR_ALLOCATE_MEMORY(209), - ADDRESS_FULL(210) - { + ADDRESS_FULL(210) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQAddressFullException(msg); } }, - LARGE_MESSAGE_INTERRUPTED(211) - { + LARGE_MESSAGE_INTERRUPTED(211) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQLargeMessageInterruptedException(msg); } }, - CLUSTER_SECURITY_EXCEPTION(212) - { + CLUSTER_SECURITY_EXCEPTION(212) { @Override - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQClusterSecurityException(msg); } @@ -260,11 +205,9 @@ public enum ActiveMQExceptionType private static final Map TYPE_MAP; - static - { + static { HashMap map = new HashMap(); - for (ActiveMQExceptionType type : EnumSet.allOf(ActiveMQExceptionType.class)) - { + for (ActiveMQExceptionType type : EnumSet.allOf(ActiveMQExceptionType.class)) { map.put(type.getCode(), type); } TYPE_MAP = Collections.unmodifiableMap(map); @@ -272,28 +215,23 @@ public enum ActiveMQExceptionType private final int code; - ActiveMQExceptionType(int code) - { + ActiveMQExceptionType(int code) { this.code = code; } - public int getCode() - { + public int getCode() { return code; } - public ActiveMQException createException(String msg) - { + public ActiveMQException createException(String msg) { return new ActiveMQException(msg + ", code:" + this); } - public static ActiveMQException createException(int code, String msg) - { + public static ActiveMQException createException(int code, String msg) { return getType(code).createException(msg); } - public static ActiveMQExceptionType getType(int code) - { + public static ActiveMQExceptionType getType(int code) { ActiveMQExceptionType type = TYPE_MAP.get(code); if (type != null) return type; diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQIOErrorException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQIOErrorException.java index f89ddbd4de..56973d4513 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQIOErrorException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQIOErrorException.java @@ -19,22 +19,19 @@ package org.apache.activemq.artemis.api.core; /** * Unexpected I/O error occurred on the server. */ -public final class ActiveMQIOErrorException extends ActiveMQException -{ +public final class ActiveMQIOErrorException extends ActiveMQException { + private static final long serialVersionUID = 797277117077787396L; - public ActiveMQIOErrorException() - { + public ActiveMQIOErrorException() { super(ActiveMQExceptionType.IO_ERROR); } - public ActiveMQIOErrorException(String msg) - { + public ActiveMQIOErrorException(String msg) { super(ActiveMQExceptionType.IO_ERROR, msg); } - public ActiveMQIOErrorException(String msg, Throwable cause) - { + public ActiveMQIOErrorException(String msg, Throwable cause) { super(ActiveMQExceptionType.IO_ERROR, msg, cause); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQIllegalStateException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQIllegalStateException.java index 8ad6b2161b..3ee855b06d 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQIllegalStateException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQIllegalStateException.java @@ -20,17 +20,15 @@ package org.apache.activemq.artemis.api.core; * An ActiveMQ Artemis resource is not in a legal state (e.g. calling ClientConsumer.receive() if a * MessageHandler is set). */ -public final class ActiveMQIllegalStateException extends ActiveMQException -{ +public final class ActiveMQIllegalStateException extends ActiveMQException { + private static final long serialVersionUID = -4480125401057788511L; - public ActiveMQIllegalStateException() - { + public ActiveMQIllegalStateException() { super(ActiveMQExceptionType.ILLEGAL_STATE); } - public ActiveMQIllegalStateException(String message) - { + public ActiveMQIllegalStateException(String message) { super(ActiveMQExceptionType.ILLEGAL_STATE, message); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQIncompatibleClientServerException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQIncompatibleClientServerException.java index 7522d101b7..0be739dc8c 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQIncompatibleClientServerException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQIncompatibleClientServerException.java @@ -21,17 +21,15 @@ package org.apache.activemq.artemis.api.core; *

* Normally this means you are trying to use a newer client on an older server. */ -public final class ActiveMQIncompatibleClientServerException extends ActiveMQException -{ +public final class ActiveMQIncompatibleClientServerException extends ActiveMQException { + private static final long serialVersionUID = -1662999230291452298L; - public ActiveMQIncompatibleClientServerException() - { + public ActiveMQIncompatibleClientServerException() { super(ActiveMQExceptionType.INCOMPATIBLE_CLIENT_SERVER_VERSIONS); } - public ActiveMQIncompatibleClientServerException(String msg) - { + public ActiveMQIncompatibleClientServerException(String msg) { super(ActiveMQExceptionType.INCOMPATIBLE_CLIENT_SERVER_VERSIONS, msg); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQInterceptorRejectedPacketException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQInterceptorRejectedPacketException.java index 57d60d44c6..e52c113bf4 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQInterceptorRejectedPacketException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQInterceptorRejectedPacketException.java @@ -21,17 +21,15 @@ package org.apache.activemq.artemis.api.core; * See org.apache.activemq.artemis.api.core.client.ServerLocator#addOutgoingInterceptor(org.apache.activemq.artemis.api.core.Interceptor) */ // XXX I doubt any reader will make much sense of this Javadoc's text. -public final class ActiveMQInterceptorRejectedPacketException extends ActiveMQException -{ +public final class ActiveMQInterceptorRejectedPacketException extends ActiveMQException { + private static final long serialVersionUID = -5798841227645281815L; - public ActiveMQInterceptorRejectedPacketException() - { + public ActiveMQInterceptorRejectedPacketException() { super(ActiveMQExceptionType.INTERCEPTOR_REJECTED_PACKET); } - public ActiveMQInterceptorRejectedPacketException(String msg) - { + public ActiveMQInterceptorRejectedPacketException(String msg) { super(ActiveMQExceptionType.INTERCEPTOR_REJECTED_PACKET, msg); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQInternalErrorException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQInternalErrorException.java index 18a5b16166..9da7d80188 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQInternalErrorException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQInternalErrorException.java @@ -19,27 +19,23 @@ package org.apache.activemq.artemis.api.core; /** * Internal error which prevented ActiveMQ Artemis from performing an important operation. */ -public final class ActiveMQInternalErrorException extends ActiveMQException -{ +public final class ActiveMQInternalErrorException extends ActiveMQException { + private static final long serialVersionUID = -5987814047521530695L; - public ActiveMQInternalErrorException() - { + public ActiveMQInternalErrorException() { super(ActiveMQExceptionType.INTERNAL_ERROR); } - public ActiveMQInternalErrorException(String msg) - { + public ActiveMQInternalErrorException(String msg) { super(ActiveMQExceptionType.INTERNAL_ERROR, msg); } - public ActiveMQInternalErrorException(String message, Exception e) - { + public ActiveMQInternalErrorException(String message, Exception e) { super(ActiveMQExceptionType.INTERNAL_ERROR, message, e); } - public ActiveMQInternalErrorException(String message, Throwable t) - { + public ActiveMQInternalErrorException(String message, Throwable t) { super(ActiveMQExceptionType.INTERNAL_ERROR, message, t); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQInterruptedException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQInterruptedException.java index eee402bde2..9a3ff7fc49 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQInterruptedException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQInterruptedException.java @@ -19,12 +19,11 @@ package org.apache.activemq.artemis.api.core; /** * When an interruption happens, we will just throw a non-checked exception. */ -public final class ActiveMQInterruptedException extends RuntimeException -{ +public final class ActiveMQInterruptedException extends RuntimeException { + private static final long serialVersionUID = -5744690023549671221L; - public ActiveMQInterruptedException(Throwable cause) - { + public ActiveMQInterruptedException(Throwable cause) { super(cause); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQInvalidFilterExpressionException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQInvalidFilterExpressionException.java index 60397a29be..f3b0950138 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQInvalidFilterExpressionException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQInvalidFilterExpressionException.java @@ -19,17 +19,15 @@ package org.apache.activemq.artemis.api.core; /** * A filter expression was found to be invalid. */ -public final class ActiveMQInvalidFilterExpressionException extends ActiveMQException -{ +public final class ActiveMQInvalidFilterExpressionException extends ActiveMQException { + private static final long serialVersionUID = 7188625553939665128L; - public ActiveMQInvalidFilterExpressionException() - { + public ActiveMQInvalidFilterExpressionException() { super(ActiveMQExceptionType.INVALID_FILTER_EXPRESSION); } - public ActiveMQInvalidFilterExpressionException(String msg) - { + public ActiveMQInvalidFilterExpressionException(String msg) { super(ActiveMQExceptionType.INVALID_FILTER_EXPRESSION, msg); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQInvalidTransientQueueUseException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQInvalidTransientQueueUseException.java index 8951004398..13416d4bf5 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQInvalidTransientQueueUseException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQInvalidTransientQueueUseException.java @@ -19,17 +19,15 @@ package org.apache.activemq.artemis.api.core; /** * An operation failed because a queue exists on the server. */ -public final class ActiveMQInvalidTransientQueueUseException extends ActiveMQException -{ +public final class ActiveMQInvalidTransientQueueUseException extends ActiveMQException { + private static final long serialVersionUID = -405552292451883063L; - public ActiveMQInvalidTransientQueueUseException() - { + public ActiveMQInvalidTransientQueueUseException() { super(ActiveMQExceptionType.INVALID_TRANSIENT_QUEUE_USE); } - public ActiveMQInvalidTransientQueueUseException(String msg) - { + public ActiveMQInvalidTransientQueueUseException(String msg) { super(ActiveMQExceptionType.INVALID_TRANSIENT_QUEUE_USE, msg); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQLargeMessageException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQLargeMessageException.java index c3f6636fad..9c68cc7b31 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQLargeMessageException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQLargeMessageException.java @@ -19,17 +19,15 @@ package org.apache.activemq.artemis.api.core; /** * A problem occurred while manipulating the body of a large message. */ -public final class ActiveMQLargeMessageException extends ActiveMQException -{ +public final class ActiveMQLargeMessageException extends ActiveMQException { + private static final long serialVersionUID = 1087867463974768491L; - public ActiveMQLargeMessageException() - { + public ActiveMQLargeMessageException() { super(ActiveMQExceptionType.LARGE_MESSAGE_ERROR_BODY); } - public ActiveMQLargeMessageException(String msg) - { + public ActiveMQLargeMessageException(String msg) { super(ActiveMQExceptionType.LARGE_MESSAGE_ERROR_BODY, msg); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQLargeMessageInterruptedException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQLargeMessageInterruptedException.java index 786bf7df53..77c45b93cb 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQLargeMessageInterruptedException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQLargeMessageInterruptedException.java @@ -16,21 +16,18 @@ */ package org.apache.activemq.artemis.api.core; - /** */ // XXX -public class ActiveMQLargeMessageInterruptedException extends ActiveMQException -{ +public class ActiveMQLargeMessageInterruptedException extends ActiveMQException { + private static final long serialVersionUID = 0; - public ActiveMQLargeMessageInterruptedException(String message) - { + public ActiveMQLargeMessageInterruptedException(String message) { super(ActiveMQExceptionType.LARGE_MESSAGE_INTERRUPTED, message); } - public ActiveMQLargeMessageInterruptedException() - { + public ActiveMQLargeMessageInterruptedException() { super(ActiveMQExceptionType.LARGE_MESSAGE_INTERRUPTED); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQNativeIOError.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQNativeIOError.java index e69a7fd3f5..1ed755d2ba 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQNativeIOError.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQNativeIOError.java @@ -16,27 +16,23 @@ */ package org.apache.activemq.artemis.api.core; - /** * An error has happened at ActiveMQ's native (non-Java) code used in reading and writing data. */ // XXX -public final class ActiveMQNativeIOError extends ActiveMQException -{ +public final class ActiveMQNativeIOError extends ActiveMQException { + private static final long serialVersionUID = 2355120980683293085L; - public ActiveMQNativeIOError() - { + public ActiveMQNativeIOError() { super(ActiveMQExceptionType.NATIVE_ERROR_CANT_INITIALIZE_AIO); } - public ActiveMQNativeIOError(String msg) - { + public ActiveMQNativeIOError(String msg) { super(ActiveMQExceptionType.NATIVE_ERROR_CANT_INITIALIZE_AIO, msg); } - public ActiveMQNativeIOError(String msg, Throwable e) - { + public ActiveMQNativeIOError(String msg, Throwable e) { super(ActiveMQExceptionType.NATIVE_ERROR_CANT_INITIALIZE_AIO, msg, e); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQNonExistentQueueException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQNonExistentQueueException.java index 7b6eb6a2e1..79659bb210 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQNonExistentQueueException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQNonExistentQueueException.java @@ -19,17 +19,15 @@ package org.apache.activemq.artemis.api.core; /** * An operation failed because a queue does not exist on the server. */ -public final class ActiveMQNonExistentQueueException extends ActiveMQException -{ +public final class ActiveMQNonExistentQueueException extends ActiveMQException { + private static final long serialVersionUID = -8199298881947523607L; - public ActiveMQNonExistentQueueException() - { + public ActiveMQNonExistentQueueException() { super(ActiveMQExceptionType.QUEUE_DOES_NOT_EXIST); } - public ActiveMQNonExistentQueueException(String msg) - { + public ActiveMQNonExistentQueueException(String msg) { super(ActiveMQExceptionType.QUEUE_DOES_NOT_EXIST, msg); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQNotConnectedException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQNotConnectedException.java index 3a95fcd0de..19375a7efd 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQNotConnectedException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQNotConnectedException.java @@ -19,17 +19,15 @@ package org.apache.activemq.artemis.api.core; /** * A client is not able to connect to ActiveMQ Artemis server. */ -public final class ActiveMQNotConnectedException extends ActiveMQException -{ +public final class ActiveMQNotConnectedException extends ActiveMQException { + private static final long serialVersionUID = -3489189971813613325L; - public ActiveMQNotConnectedException(String message) - { + public ActiveMQNotConnectedException(String message) { super(ActiveMQExceptionType.NOT_CONNECTED, message); } - public ActiveMQNotConnectedException() - { + public ActiveMQNotConnectedException() { super(ActiveMQExceptionType.NOT_CONNECTED); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQObjectClosedException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQObjectClosedException.java index 7ad745f63e..06dad546e5 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQObjectClosedException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQObjectClosedException.java @@ -20,17 +20,15 @@ package org.apache.activemq.artemis.api.core; * A client operation failed because the calling resource (ClientSession, ClientProducer, etc.) is * closed. */ -public final class ActiveMQObjectClosedException extends ActiveMQException -{ +public final class ActiveMQObjectClosedException extends ActiveMQException { + private static final long serialVersionUID = 809024052184914812L; - public ActiveMQObjectClosedException() - { + public ActiveMQObjectClosedException() { super(ActiveMQExceptionType.OBJECT_CLOSED); } - public ActiveMQObjectClosedException(String msg) - { + public ActiveMQObjectClosedException(String msg) { super(ActiveMQExceptionType.OBJECT_CLOSED, msg); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQPropertyConversionException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQPropertyConversionException.java index 842a0fed0b..910f74f452 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQPropertyConversionException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQPropertyConversionException.java @@ -20,13 +20,11 @@ package org.apache.activemq.artemis.api.core; * A PropertyConversionException is thrown by {@code org.apache.activemq.artemis.api.core.Message} methods when a * property can not be converted to the expected type. */ -public final class ActiveMQPropertyConversionException extends RuntimeException -{ +public final class ActiveMQPropertyConversionException extends RuntimeException { private static final long serialVersionUID = -3010008708334904332L; - public ActiveMQPropertyConversionException(final String message) - { + public ActiveMQPropertyConversionException(final String message) { super(message); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQQueueExistsException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQQueueExistsException.java index e88dc17058..426deb8953 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQQueueExistsException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQQueueExistsException.java @@ -19,17 +19,15 @@ package org.apache.activemq.artemis.api.core; /** * An operation failed because a queue exists on the server. */ -public final class ActiveMQQueueExistsException extends ActiveMQException -{ +public final class ActiveMQQueueExistsException extends ActiveMQException { + private static final long serialVersionUID = -405552292451883063L; - public ActiveMQQueueExistsException() - { + public ActiveMQQueueExistsException() { super(ActiveMQExceptionType.QUEUE_EXISTS); } - public ActiveMQQueueExistsException(String msg) - { + public ActiveMQQueueExistsException(String msg) { super(ActiveMQExceptionType.QUEUE_EXISTS, msg); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQSecurityException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQSecurityException.java index b3ce7d283f..da51b3836d 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQSecurityException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQSecurityException.java @@ -21,17 +21,15 @@ import static org.apache.activemq.artemis.api.core.ActiveMQExceptionType.SECURIT /** * A security problem occurred (authentication issues, permission issues,...) */ -public final class ActiveMQSecurityException extends ActiveMQException -{ +public final class ActiveMQSecurityException extends ActiveMQException { + private static final long serialVersionUID = 3291210307590756881L; - public ActiveMQSecurityException() - { + public ActiveMQSecurityException() { super(SECURITY_EXCEPTION); } - public ActiveMQSecurityException(String msg) - { + public ActiveMQSecurityException(String msg) { super(SECURITY_EXCEPTION, msg); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQSessionCreationException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQSessionCreationException.java index c3af3f0cf8..a2c973a4f9 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQSessionCreationException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQSessionCreationException.java @@ -20,17 +20,15 @@ package org.apache.activemq.artemis.api.core; * The creation of a session was rejected by the server (e.g. if the server is starting and has not * finish to be initialized. */ -public final class ActiveMQSessionCreationException extends ActiveMQException -{ +public final class ActiveMQSessionCreationException extends ActiveMQException { + private static final long serialVersionUID = -4486139158452585895L; - public ActiveMQSessionCreationException() - { + public ActiveMQSessionCreationException() { super(ActiveMQExceptionType.SESSION_CREATION_REJECTED); } - public ActiveMQSessionCreationException(String msg) - { + public ActiveMQSessionCreationException(String msg) { super(ActiveMQExceptionType.SESSION_CREATION_REJECTED, msg); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQTransactionOutcomeUnknownException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQTransactionOutcomeUnknownException.java index 447cdca493..d0e56a101a 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQTransactionOutcomeUnknownException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQTransactionOutcomeUnknownException.java @@ -19,17 +19,15 @@ package org.apache.activemq.artemis.api.core; /** * The outcome of a transaction is unknown. */ -public final class ActiveMQTransactionOutcomeUnknownException extends ActiveMQException -{ +public final class ActiveMQTransactionOutcomeUnknownException extends ActiveMQException { + private static final long serialVersionUID = 7940794286427650558L; - public ActiveMQTransactionOutcomeUnknownException() - { + public ActiveMQTransactionOutcomeUnknownException() { super(ActiveMQExceptionType.TRANSACTION_OUTCOME_UNKNOWN); } - public ActiveMQTransactionOutcomeUnknownException(String msg) - { + public ActiveMQTransactionOutcomeUnknownException(String msg) { super(ActiveMQExceptionType.TRANSACTION_OUTCOME_UNKNOWN, msg); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQTransactionRolledBackException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQTransactionRolledBackException.java index e6e4443818..03e4c58717 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQTransactionRolledBackException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQTransactionRolledBackException.java @@ -19,17 +19,15 @@ package org.apache.activemq.artemis.api.core; /** * A transaction was rolled back. */ -public final class ActiveMQTransactionRolledBackException extends ActiveMQException -{ +public final class ActiveMQTransactionRolledBackException extends ActiveMQException { + private static final long serialVersionUID = 5823412198677126300L; - public ActiveMQTransactionRolledBackException() - { + public ActiveMQTransactionRolledBackException() { super(ActiveMQExceptionType.TRANSACTION_ROLLED_BACK); } - public ActiveMQTransactionRolledBackException(String msg) - { + public ActiveMQTransactionRolledBackException(String msg) { super(ActiveMQExceptionType.TRANSACTION_ROLLED_BACK, msg); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQUnBlockedException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQUnBlockedException.java index 19eb18cb6e..5b2a421bed 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQUnBlockedException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQUnBlockedException.java @@ -19,17 +19,15 @@ package org.apache.activemq.artemis.api.core; /** * A blocking call from a client was unblocked during failover. */ -public final class ActiveMQUnBlockedException extends ActiveMQException -{ +public final class ActiveMQUnBlockedException extends ActiveMQException { + private static final long serialVersionUID = -4507889261891160608L; - public ActiveMQUnBlockedException() - { + public ActiveMQUnBlockedException() { super(ActiveMQExceptionType.UNBLOCKED); } - public ActiveMQUnBlockedException(String msg) - { + public ActiveMQUnBlockedException(String msg) { super(ActiveMQExceptionType.UNBLOCKED, msg); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQUnsupportedPacketException.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQUnsupportedPacketException.java index c6cb7643c5..377d2c51d8 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQUnsupportedPacketException.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQUnsupportedPacketException.java @@ -19,17 +19,15 @@ package org.apache.activemq.artemis.api.core; /** * A packet of unsupported type was received by ActiveMQ Artemis PacketHandler. */ -public final class ActiveMQUnsupportedPacketException extends ActiveMQException -{ +public final class ActiveMQUnsupportedPacketException extends ActiveMQException { + private static final long serialVersionUID = -7074681529482463675L; - public ActiveMQUnsupportedPacketException() - { + public ActiveMQUnsupportedPacketException() { super(ActiveMQExceptionType.UNSUPPORTED_PACKET); } - public ActiveMQUnsupportedPacketException(String msg) - { + public ActiveMQUnsupportedPacketException(String msg) { super(ActiveMQExceptionType.UNSUPPORTED_PACKET, msg); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/Pair.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/Pair.java index 4497c6ff2a..b3e130f25a 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/Pair.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/Pair.java @@ -23,12 +23,11 @@ import java.io.Serializable; *

* This is a utility class. */ -public final class Pair implements Serializable -{ +public final class Pair implements Serializable { + private static final long serialVersionUID = -2496357457812368127L; - public Pair(final A a, final B b) - { + public Pair(final A a, final B b) { this.a = a; this.b = b; @@ -41,16 +40,12 @@ public final class Pair implements Serializable private int hash = -1; @Override - public int hashCode() - { - if (hash == -1) - { - if (a == null && b == null) - { + public int hashCode() { + if (hash == -1) { + if (a == null && b == null) { return super.hashCode(); } - else - { + else { hash = (a == null ? 0 : a.hashCode()) + 37 * (b == null ? 0 : b.hashCode()); } } @@ -59,49 +54,41 @@ public final class Pair implements Serializable } @Override - public boolean equals(final Object other) - { - if (other == this) - { + public boolean equals(final Object other) { + if (other == this) { return true; } - if (other instanceof Pair == false) - { + if (other instanceof Pair == false) { return false; } - Pair pother = (Pair)other; + Pair pother = (Pair) other; return (pother.a == null ? a == null : pother.a.equals(a)) && (pother.b == null ? b == null : pother.b.equals(b)); } @Override - public String toString() - { + public String toString() { return "Pair[a=" + a + ", b=" + b + "]"; } - public void setA(A a) - { + public void setA(A a) { hash = -1; this.a = a; } - public A getA() - { + public A getA() { return a; } - public void setB(B b) - { + public void setB(B b) { hash = -1; this.b = b; } - public B getB() - { + public B getB() { return b; } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/SimpleString.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/SimpleString.java index 3c8a35c118..d50e46defc 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/SimpleString.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/SimpleString.java @@ -27,10 +27,9 @@ import org.apache.activemq.artemis.utils.DataConstants; * minimises expensive copying between String objects. *

* This object is used heavily throughout ActiveMQ Artemis for performance reasons. - * */ -public final class SimpleString implements CharSequence, Serializable, Comparable -{ +public final class SimpleString implements CharSequence, Serializable, Comparable { + private static final long serialVersionUID = 4204223851422244307L; // Attributes @@ -53,10 +52,8 @@ public final class SimpleString implements CharSequence, Serializable, Comparabl * @param string String used to instantiate a SimpleString. * @return A new SimpleString */ - public static SimpleString toSimpleString(final String string) - { - if (string == null) - { + public static SimpleString toSimpleString(final String string) { + if (string == null) { return null; } return new SimpleString(string); @@ -70,16 +67,14 @@ public final class SimpleString implements CharSequence, Serializable, Comparabl * * @param string the string to transform */ - public SimpleString(final String string) - { + public SimpleString(final String string) { int len = string.length(); data = new byte[len << 1]; int j = 0; - for (int i = 0; i < len; i++) - { + for (int i = 0; i < len; i++) { char c = string.charAt(i); byte low = (byte) (c & 0xFF); // low byte @@ -99,23 +94,19 @@ public final class SimpleString implements CharSequence, Serializable, Comparabl * * @param data the byte array to use */ - public SimpleString(final byte[] data) - { + public SimpleString(final byte[] data) { this.data = data; } // CharSequence implementation // --------------------------------------------------------------------------- - public int length() - { + public int length() { return data.length >> 1; } - public char charAt(int pos) - { - if (pos < 0 || pos >= data.length >> 1) - { + public char charAt(int pos) { + if (pos < 0 || pos >= data.length >> 1) { throw new IndexOutOfBoundsException(); } pos <<= 1; @@ -123,16 +114,13 @@ public final class SimpleString implements CharSequence, Serializable, Comparabl return (char) ((data[pos] & 0xFF) | (data[pos + 1] << 8) & 0xFF00); } - public CharSequence subSequence(final int start, final int end) - { + public CharSequence subSequence(final int start, final int end) { int len = data.length >> 1; - if (end < start || start < 0 || end > len) - { + if (end < start || start < 0 || end > len) { throw new IndexOutOfBoundsException(); } - else - { + else { int newlen = end - start << 1; byte[] bytes = new byte[newlen]; @@ -144,8 +132,7 @@ public final class SimpleString implements CharSequence, Serializable, Comparabl // Comparable implementation ------------------------------------- - public int compareTo(final SimpleString o) - { + public int compareTo(final SimpleString o) { return toString().compareTo(o.toString()); } @@ -157,8 +144,7 @@ public final class SimpleString implements CharSequence, Serializable, Comparabl * * @return the byte array */ - public byte[] getData() - { + public byte[] getData() { return data; } @@ -168,19 +154,15 @@ public final class SimpleString implements CharSequence, Serializable, Comparabl * @param other the SimpleString to look for * @return true if this SimpleString starts with the same data */ - public boolean startsWith(final SimpleString other) - { + public boolean startsWith(final SimpleString other) { byte[] otherdata = other.data; - if (otherdata.length > data.length) - { + if (otherdata.length > data.length) { return false; } - for (int i = 0; i < otherdata.length; i++) - { - if (data[i] != otherdata[i]) - { + for (int i = 0; i < otherdata.length; i++) { + if (data[i] != otherdata[i]) { return false; } } @@ -189,18 +171,15 @@ public final class SimpleString implements CharSequence, Serializable, Comparabl } @Override - public String toString() - { - if (str == null) - { + public String toString() { + if (str == null) { int len = data.length >> 1; char[] chars = new char[len]; int j = 0; - for (int i = 0; i < len; i++) - { + for (int i = 0; i < len; i++) { int low = data[j++] & 0xFF; int high = data[j++] << 8 & 0xFF00; @@ -215,46 +194,36 @@ public final class SimpleString implements CharSequence, Serializable, Comparabl } @Override - public boolean equals(final Object other) - { - if (this == other) - { + public boolean equals(final Object other) { + if (this == other) { return true; } - if (other instanceof SimpleString) - { + if (other instanceof SimpleString) { SimpleString s = (SimpleString) other; - if (data.length != s.data.length) - { + if (data.length != s.data.length) { return false; } - for (int i = 0; i < data.length; i++) - { - if (data[i] != s.data[i]) - { + for (int i = 0; i < data.length; i++) { + if (data[i] != s.data[i]) { return false; } } return true; } - else - { + else { return false; } } @Override - public int hashCode() - { - if (hash == 0) - { + public int hashCode() { + if (hash == 0) { int tmphash = 0; - for (byte element : data) - { + for (byte element : data) { tmphash = (tmphash << 5) - tmphash + element; // (hash << 5) - hash is same as hash * 31 } hash = tmphash; @@ -270,25 +239,21 @@ public final class SimpleString implements CharSequence, Serializable, Comparabl * @param delim The delimiter to split this SimpleString on. * @return An array of SimpleStrings */ - public SimpleString[] split(final char delim) - { + public SimpleString[] split(final char delim) { List all = null; byte low = (byte) (delim & 0xFF); // low byte byte high = (byte) (delim >> 8 & 0xFF); // high byte int lasPos = 0; - for (int i = 0; i < data.length; i += 2) - { - if (data[i] == low && data[i + 1] == high) - { + for (int i = 0; i < data.length; i += 2) { + if (data[i] == low && data[i + 1] == high) { byte[] bytes = new byte[i - lasPos]; System.arraycopy(data, lasPos, bytes, 0, bytes.length); lasPos = i + 2; // We will create the ArrayList lazily - if (all == null) - { + if (all == null) { // There will be at least 2 strings on this case (which is the actual common usecase) // For that reason I'm allocating the ArrayList with 2 already // I have thought about using LinkedList here but I think this will be good enough already @@ -299,12 +264,10 @@ public final class SimpleString implements CharSequence, Serializable, Comparabl } } - if (all == null) - { + if (all == null) { return new SimpleString[]{this}; } - else - { + else { // Adding the last one byte[] bytes = new byte[data.length - lasPos]; System.arraycopy(data, lasPos, bytes, 0, bytes.length); @@ -322,15 +285,12 @@ public final class SimpleString implements CharSequence, Serializable, Comparabl * @param c the char to check for * @return true if the char is found, false otherwise. */ - public boolean contains(final char c) - { + public boolean contains(final char c) { final byte low = (byte) (c & 0xFF); // low byte final byte high = (byte) (c >> 8 & 0xFF); // high byte - for (int i = 0; i < data.length; i += 2) - { - if (data[i] == low && data[i + 1] == high) - { + for (int i = 0; i < data.length; i += 2) { + if (data[i] == low && data[i + 1] == high) { return true; } } @@ -343,8 +303,7 @@ public final class SimpleString implements CharSequence, Serializable, Comparabl * @param toAdd the String to concatenate with. * @return the concatenated SimpleString */ - public SimpleString concat(final String toAdd) - { + public SimpleString concat(final String toAdd) { return concat(new SimpleString(toAdd)); } @@ -354,8 +313,7 @@ public final class SimpleString implements CharSequence, Serializable, Comparabl * @param toAdd the SimpleString to concatenate with. * @return the concatenated SimpleString */ - public SimpleString concat(final SimpleString toAdd) - { + public SimpleString concat(final SimpleString toAdd) { byte[] bytes = new byte[data.length + toAdd.getData().length]; System.arraycopy(data, 0, bytes, 0, data.length); System.arraycopy(toAdd.getData(), 0, bytes, data.length, toAdd.getData().length); @@ -368,8 +326,7 @@ public final class SimpleString implements CharSequence, Serializable, Comparabl * @param c the char to concate with. * @return the concatenated SimpleString */ - public SimpleString concat(final char c) - { + public SimpleString concat(final char c) { byte[] bytes = new byte[data.length + 2]; System.arraycopy(data, 0, bytes, 0, data.length); bytes[data.length] = (byte) (c & 0xFF); @@ -382,8 +339,7 @@ public final class SimpleString implements CharSequence, Serializable, Comparabl * * @return the size */ - public int sizeof() - { + public int sizeof() { return DataConstants.SIZE_INT + data.length; } @@ -393,8 +349,7 @@ public final class SimpleString implements CharSequence, Serializable, Comparabl * @param str the SimpleString to check * @return the size */ - public static int sizeofString(final SimpleString str) - { + public static int sizeofString(final SimpleString str) { return str.sizeof(); } @@ -404,14 +359,11 @@ public final class SimpleString implements CharSequence, Serializable, Comparabl * @param str the SimpleString to check * @return the size */ - public static int sizeofNullableString(final SimpleString str) - { - if (str == null) - { + public static int sizeofNullableString(final SimpleString str) { + if (str == null) { return 1; } - else - { + else { return 1 + str.sizeof(); } } @@ -421,30 +373,25 @@ public final class SimpleString implements CharSequence, Serializable, Comparabl * This is mainly used by the Parsers on Filters * * @param srcBegin The srcBegin - * @param srcEnd The srcEnd - * @param dst The destination array - * @param dstPos The destination position + * @param srcEnd The srcEnd + * @param dst The destination array + * @param dstPos The destination position */ - public void getChars(final int srcBegin, final int srcEnd, final char[] dst, final int dstPos) - { - if (srcBegin < 0) - { + public void getChars(final int srcBegin, final int srcEnd, final char[] dst, final int dstPos) { + if (srcBegin < 0) { throw new StringIndexOutOfBoundsException(srcBegin); } - if (srcEnd > length()) - { + if (srcEnd > length()) { throw new StringIndexOutOfBoundsException(srcEnd); } - if (srcBegin > srcEnd) - { + if (srcBegin > srcEnd) { throw new StringIndexOutOfBoundsException(srcEnd - srcBegin); } int j = srcBegin * 2; int d = dstPos; - for (int i = srcBegin; i < srcEnd; i++) - { + for (int i = srcBegin; i < srcEnd; i++) { int low = data[j++] & 0xFF; int high = data[j++] << 8 & 0xFF00; diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/core/buffers/impl/ChannelBufferWrapper.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/core/buffers/impl/ChannelBufferWrapper.java index bb45cb70a0..51fea91a01 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/core/buffers/impl/ChannelBufferWrapper.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/core/buffers/impl/ChannelBufferWrapper.java @@ -25,16 +25,14 @@ import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.utils.DataConstants; import org.apache.activemq.artemis.utils.UTF8Util; -public class ChannelBufferWrapper implements ActiveMQBuffer -{ +public class ChannelBufferWrapper implements ActiveMQBuffer { + protected ByteBuf buffer; // NO_UCD (use final) private final boolean releasable; - public static ByteBuf unwrap(ByteBuf buffer) - { + public static ByteBuf unwrap(ByteBuf buffer) { ByteBuf parent; - while ((parent = buffer.unwrap()) != null && - parent != buffer) // this last part is just in case the semantic + while ((parent = buffer.unwrap()) != null && parent != buffer) // this last part is just in case the semantic { // ever changes where unwrap is returning itself buffer = parent; } @@ -42,591 +40,473 @@ public class ChannelBufferWrapper implements ActiveMQBuffer return buffer; } - public ChannelBufferWrapper(final ByteBuf buffer) - { + public ChannelBufferWrapper(final ByteBuf buffer) { this(buffer, false); } - public ChannelBufferWrapper(final ByteBuf buffer, boolean releasable) - { - if (!releasable) - { + public ChannelBufferWrapper(final ByteBuf buffer, boolean releasable) { + if (!releasable) { this.buffer = Unpooled.unreleasableBuffer(buffer); } - else - { + else { this.buffer = buffer; } this.releasable = releasable; } - public boolean readBoolean() - { + public boolean readBoolean() { return readByte() != 0; } - public SimpleString readNullableSimpleString() - { + public SimpleString readNullableSimpleString() { int b = buffer.readByte(); - if (b == DataConstants.NULL) - { + if (b == DataConstants.NULL) { return null; } return readSimpleStringInternal(); } - public String readNullableString() - { + public String readNullableString() { int b = buffer.readByte(); - if (b == DataConstants.NULL) - { + if (b == DataConstants.NULL) { return null; } return readStringInternal(); } - public SimpleString readSimpleString() - { + public SimpleString readSimpleString() { return readSimpleStringInternal(); } - private SimpleString readSimpleStringInternal() - { + private SimpleString readSimpleStringInternal() { int len = buffer.readInt(); byte[] data = new byte[len]; buffer.readBytes(data); return new SimpleString(data); } - public String readString() - { + public String readString() { return readStringInternal(); } - private String readStringInternal() - { + private String readStringInternal() { int len = buffer.readInt(); - if (len < 9) - { + if (len < 9) { char[] chars = new char[len]; - for (int i = 0; i < len; i++) - { - chars[i] = (char)buffer.readShort(); + for (int i = 0; i < len; i++) { + chars[i] = (char) buffer.readShort(); } return new String(chars); } - else if (len < 0xfff) - { + else if (len < 0xfff) { return readUTF(); } - else - { + else { return readSimpleStringInternal().toString(); } } - public String readUTF() - { + public String readUTF() { return UTF8Util.readUTF(this); } - public void writeBoolean(final boolean val) - { - buffer.writeByte((byte)(val ? -1 : 0)); + public void writeBoolean(final boolean val) { + buffer.writeByte((byte) (val ? -1 : 0)); } - public void writeNullableSimpleString(final SimpleString val) - { - if (val == null) - { + public void writeNullableSimpleString(final SimpleString val) { + if (val == null) { buffer.writeByte(DataConstants.NULL); } - else - { + else { buffer.writeByte(DataConstants.NOT_NULL); writeSimpleStringInternal(val); } } - public void writeNullableString(final String val) - { - if (val == null) - { + public void writeNullableString(final String val) { + if (val == null) { buffer.writeByte(DataConstants.NULL); } - else - { + else { buffer.writeByte(DataConstants.NOT_NULL); writeStringInternal(val); } } - public void writeSimpleString(final SimpleString val) - { + public void writeSimpleString(final SimpleString val) { writeSimpleStringInternal(val); } - private void writeSimpleStringInternal(final SimpleString val) - { + private void writeSimpleStringInternal(final SimpleString val) { byte[] data = val.getData(); buffer.writeInt(data.length); buffer.writeBytes(data); } - public void writeString(final String val) - { + public void writeString(final String val) { writeStringInternal(val); } - private void writeStringInternal(final String val) - { + private void writeStringInternal(final String val) { int length = val.length(); buffer.writeInt(length); - if (length < 9) - { + if (length < 9) { // If very small it's more performant to store char by char - for (int i = 0; i < val.length(); i++) - { - buffer.writeShort((short)val.charAt(i)); + for (int i = 0; i < val.length(); i++) { + buffer.writeShort((short) val.charAt(i)); } } - else if (length < 0xfff) - { + else if (length < 0xfff) { // Store as UTF - this is quicker than char by char for most strings writeUTF(val); } - else - { + else { // Store as SimpleString, since can't store utf > 0xffff in length writeSimpleStringInternal(new SimpleString(val)); } } - public void writeUTF(final String utf) - { + public void writeUTF(final String utf) { UTF8Util.saveUTF(this, utf); } - public int capacity() - { + public int capacity() { return buffer.capacity(); } - public ByteBuf byteBuf() - { + public ByteBuf byteBuf() { return buffer; } - public void clear() - { + public void clear() { buffer.clear(); } - public ActiveMQBuffer copy() - { + public ActiveMQBuffer copy() { return new ChannelBufferWrapper(buffer.copy(), releasable); } - public ActiveMQBuffer copy(final int index, final int length) - { + public ActiveMQBuffer copy(final int index, final int length) { return new ChannelBufferWrapper(buffer.copy(index, length), releasable); } - public void discardReadBytes() - { + public void discardReadBytes() { buffer.discardReadBytes(); } - public ActiveMQBuffer duplicate() - { + public ActiveMQBuffer duplicate() { return new ChannelBufferWrapper(buffer.duplicate(), releasable); } - public byte getByte(final int index) - { + public byte getByte(final int index) { return buffer.getByte(index); } - public void getBytes(final int index, final byte[] dst, final int dstIndex, final int length) - { + public void getBytes(final int index, final byte[] dst, final int dstIndex, final int length) { buffer.getBytes(index, dst, dstIndex, length); } - public void getBytes(final int index, final byte[] dst) - { + public void getBytes(final int index, final byte[] dst) { buffer.getBytes(index, dst); } - public void getBytes(final int index, final ByteBuffer dst) - { + public void getBytes(final int index, final ByteBuffer dst) { buffer.getBytes(index, dst); } - public void getBytes(final int index, final ActiveMQBuffer dst, final int dstIndex, final int length) - { + public void getBytes(final int index, final ActiveMQBuffer dst, final int dstIndex, final int length) { buffer.getBytes(index, dst.byteBuf(), dstIndex, length); } - public void getBytes(final int index, final ActiveMQBuffer dst, final int length) - { + public void getBytes(final int index, final ActiveMQBuffer dst, final int length) { buffer.getBytes(index, dst.byteBuf(), length); } - public void getBytes(final int index, final ActiveMQBuffer dst) - { + public void getBytes(final int index, final ActiveMQBuffer dst) { buffer.getBytes(index, dst.byteBuf()); } - public char getChar(final int index) - { - return (char)buffer.getShort(index); + public char getChar(final int index) { + return (char) buffer.getShort(index); } - public double getDouble(final int index) - { + public double getDouble(final int index) { return Double.longBitsToDouble(buffer.getLong(index)); } - public float getFloat(final int index) - { + public float getFloat(final int index) { return Float.intBitsToFloat(buffer.getInt(index)); } - public int getInt(final int index) - { + public int getInt(final int index) { return buffer.getInt(index); } - public long getLong(final int index) - { + public long getLong(final int index) { return buffer.getLong(index); } - public short getShort(final int index) - { + public short getShort(final int index) { return buffer.getShort(index); } - public short getUnsignedByte(final int index) - { + public short getUnsignedByte(final int index) { return buffer.getUnsignedByte(index); } - public long getUnsignedInt(final int index) - { + public long getUnsignedInt(final int index) { return buffer.getUnsignedInt(index); } - public int getUnsignedShort(final int index) - { + public int getUnsignedShort(final int index) { return buffer.getUnsignedShort(index); } - public void markReaderIndex() - { + public void markReaderIndex() { buffer.markReaderIndex(); } - public void markWriterIndex() - { + public void markWriterIndex() { buffer.markWriterIndex(); } - public boolean readable() - { + public boolean readable() { return buffer.isReadable(); } - public int readableBytes() - { + public int readableBytes() { return buffer.readableBytes(); } - public byte readByte() - { + public byte readByte() { return buffer.readByte(); } - public void readBytes(final byte[] dst, final int dstIndex, final int length) - { + public void readBytes(final byte[] dst, final int dstIndex, final int length) { buffer.readBytes(dst, dstIndex, length); } - public void readBytes(final byte[] dst) - { + public void readBytes(final byte[] dst) { buffer.readBytes(dst); } - public void readBytes(final ByteBuffer dst) - { + public void readBytes(final ByteBuffer dst) { buffer.readBytes(dst); } - public void readBytes(final ActiveMQBuffer dst, final int dstIndex, final int length) - { + public void readBytes(final ActiveMQBuffer dst, final int dstIndex, final int length) { buffer.readBytes(dst.byteBuf(), dstIndex, length); } - public void readBytes(final ActiveMQBuffer dst, final int length) - { + public void readBytes(final ActiveMQBuffer dst, final int length) { buffer.readBytes(dst.byteBuf(), length); } - public void readBytes(final ActiveMQBuffer dst) - { + public void readBytes(final ActiveMQBuffer dst) { buffer.readBytes(dst.byteBuf()); } - public ActiveMQBuffer readBytes(final int length) - { + public ActiveMQBuffer readBytes(final int length) { return new ChannelBufferWrapper(buffer.readBytes(length), releasable); } - public char readChar() - { - return (char)buffer.readShort(); + public char readChar() { + return (char) buffer.readShort(); } - public double readDouble() - { + public double readDouble() { return Double.longBitsToDouble(buffer.readLong()); } - public int readerIndex() - { + public int readerIndex() { return buffer.readerIndex(); } - public void readerIndex(final int readerIndex) - { + public void readerIndex(final int readerIndex) { buffer.readerIndex(readerIndex); } - public float readFloat() - { + public float readFloat() { return Float.intBitsToFloat(buffer.readInt()); } - public int readInt() - { + public int readInt() { return buffer.readInt(); } - public long readLong() - { + public long readLong() { return buffer.readLong(); } - public short readShort() - { + public short readShort() { return buffer.readShort(); } - public ActiveMQBuffer readSlice(final int length) - { + public ActiveMQBuffer readSlice(final int length) { return new ChannelBufferWrapper(buffer.readSlice(length), releasable); } - public short readUnsignedByte() - { + public short readUnsignedByte() { return buffer.readUnsignedByte(); } - public long readUnsignedInt() - { + public long readUnsignedInt() { return buffer.readUnsignedInt(); } - public int readUnsignedShort() - { + public int readUnsignedShort() { return buffer.readUnsignedShort(); } - public void resetReaderIndex() - { + public void resetReaderIndex() { buffer.resetReaderIndex(); } - public void resetWriterIndex() - { + public void resetWriterIndex() { buffer.resetWriterIndex(); } - public void setByte(final int index, final byte value) - { + public void setByte(final int index, final byte value) { buffer.setByte(index, value); } - public void setBytes(final int index, final byte[] src, final int srcIndex, final int length) - { + public void setBytes(final int index, final byte[] src, final int srcIndex, final int length) { buffer.setBytes(index, src, srcIndex, length); } - public void setBytes(final int index, final byte[] src) - { + public void setBytes(final int index, final byte[] src) { buffer.setBytes(index, src); } - public void setBytes(final int index, final ByteBuffer src) - { + public void setBytes(final int index, final ByteBuffer src) { buffer.setBytes(index, src); } - public void setBytes(final int index, final ActiveMQBuffer src, final int srcIndex, final int length) - { + public void setBytes(final int index, final ActiveMQBuffer src, final int srcIndex, final int length) { buffer.setBytes(index, src.byteBuf(), srcIndex, length); } - public void setBytes(final int index, final ActiveMQBuffer src, final int length) - { + public void setBytes(final int index, final ActiveMQBuffer src, final int length) { buffer.setBytes(index, src.byteBuf(), length); } - public void setBytes(final int index, final ActiveMQBuffer src) - { + public void setBytes(final int index, final ActiveMQBuffer src) { buffer.setBytes(index, src.byteBuf()); } - public void setChar(final int index, final char value) - { - buffer.setShort(index, (short)value); + public void setChar(final int index, final char value) { + buffer.setShort(index, (short) value); } - public void setDouble(final int index, final double value) - { + public void setDouble(final int index, final double value) { buffer.setLong(index, Double.doubleToLongBits(value)); } - public void setFloat(final int index, final float value) - { + public void setFloat(final int index, final float value) { buffer.setInt(index, Float.floatToIntBits(value)); } - public void setIndex(final int readerIndex, final int writerIndex) - { + public void setIndex(final int readerIndex, final int writerIndex) { buffer.setIndex(readerIndex, writerIndex); } - public void setInt(final int index, final int value) - { + public void setInt(final int index, final int value) { buffer.setInt(index, value); } - public void setLong(final int index, final long value) - { + public void setLong(final int index, final long value) { buffer.setLong(index, value); } - public void setShort(final int index, final short value) - { + public void setShort(final int index, final short value) { buffer.setShort(index, value); } - public void skipBytes(final int length) - { + public void skipBytes(final int length) { buffer.skipBytes(length); } - public ActiveMQBuffer slice() - { + public ActiveMQBuffer slice() { return new ChannelBufferWrapper(buffer.slice(), releasable); } - public ActiveMQBuffer slice(final int index, final int length) - { + public ActiveMQBuffer slice(final int index, final int length) { return new ChannelBufferWrapper(buffer.slice(index, length), releasable); } - public ByteBuffer toByteBuffer() - { + public ByteBuffer toByteBuffer() { return buffer.nioBuffer(); } - public ByteBuffer toByteBuffer(final int index, final int length) - { + public ByteBuffer toByteBuffer(final int index, final int length) { return buffer.nioBuffer(index, length); } - public boolean writable() - { + public boolean writable() { return buffer.isWritable(); } - public int writableBytes() - { + public int writableBytes() { return buffer.writableBytes(); } - public void writeByte(final byte value) - { + public void writeByte(final byte value) { buffer.writeByte(value); } - public void writeBytes(final byte[] src, final int srcIndex, final int length) - { + public void writeBytes(final byte[] src, final int srcIndex, final int length) { buffer.writeBytes(src, srcIndex, length); } - public void writeBytes(final byte[] src) - { + public void writeBytes(final byte[] src) { buffer.writeBytes(src); } - public void writeBytes(final ByteBuffer src) - { + public void writeBytes(final ByteBuffer src) { buffer.writeBytes(src); } - public void writeBytes(final ActiveMQBuffer src, final int srcIndex, final int length) - { + public void writeBytes(final ActiveMQBuffer src, final int srcIndex, final int length) { buffer.writeBytes(src.byteBuf(), srcIndex, length); } - public void writeBytes(final ActiveMQBuffer src, final int length) - { + public void writeBytes(final ActiveMQBuffer src, final int length) { buffer.writeBytes(src.byteBuf(), length); } - public void writeChar(final char chr) - { - buffer.writeShort((short)chr); + public void writeChar(final char chr) { + buffer.writeShort((short) chr); } - public void writeDouble(final double value) - { + public void writeDouble(final double value) { buffer.writeLong(Double.doubleToLongBits(value)); } - public void writeFloat(final float value) - { + public void writeFloat(final float value) { buffer.writeInt(Float.floatToIntBits(value)); } - public void writeInt(final int value) - { + public void writeInt(final int value) { buffer.writeInt(value); } - public void writeLong(final long value) - { + public void writeLong(final long value) { buffer.writeLong(value); } - public int writerIndex() - { + public int writerIndex() { return buffer.writerIndex(); } - public void writerIndex(final int writerIndex) - { + public void writerIndex(final int writerIndex) { buffer.writerIndex(writerIndex); } - public void writeShort(final short value) - { + public void writeShort(final short value) { buffer.writeShort(value); } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQComponent.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQComponent.java index a8428281cc..60dacdcc2d 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQComponent.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQComponent.java @@ -16,8 +16,8 @@ */ package org.apache.activemq.artemis.core.server; -public interface ActiveMQComponent -{ +public interface ActiveMQComponent { + void start() throws Exception; void stop() throws Exception; diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/logs/ActiveMQUtilBundle.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/logs/ActiveMQUtilBundle.java index ae77c5c71a..664470a071 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/logs/ActiveMQUtilBundle.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/logs/ActiveMQUtilBundle.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.logs; - import org.apache.activemq.artemis.api.core.ActiveMQIllegalStateException; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.Message; @@ -31,11 +30,11 @@ import org.jboss.logging.Messages; * so 209000 to 209999 */ @MessageBundle(projectCode = "AMQ") -public interface ActiveMQUtilBundle -{ +public interface ActiveMQUtilBundle { + ActiveMQUtilBundle BUNDLE = Messages.getBundle(ActiveMQUtilBundle.class); - @Message(id = 209000, value = "invalid property: {0}" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 209000, value = "invalid property: {0}", format = Message.Format.MESSAGE_FORMAT) ActiveMQIllegalStateException invalidProperty(String part); @Message(id = 209001, value = "Invalid type: {0}", format = Message.Format.MESSAGE_FORMAT) diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/logs/ActiveMQUtilLogger.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/logs/ActiveMQUtilLogger.java index 6d01c5a8a6..b26d30dc26 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/logs/ActiveMQUtilLogger.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/logs/ActiveMQUtilLogger.java @@ -37,8 +37,8 @@ import org.jboss.logging.annotations.MessageLogger; * so an INFO message would be 201000 to 201999 */ @MessageLogger(projectCode = "AMQ") -public interface ActiveMQUtilLogger extends BasicLogger -{ +public interface ActiveMQUtilLogger extends BasicLogger { + /** * The default logger. */ @@ -46,6 +46,6 @@ public interface ActiveMQUtilLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 202000, value = "Missing privileges to set Thread Context Class Loader on Thread Factory. Using current Thread Context Class Loader", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void missingPrivsForClassloader(); } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/logs/AssertionLoggerHandler.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/logs/AssertionLoggerHandler.java index b366b61f03..e0c1215dba 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/logs/AssertionLoggerHandler.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/logs/AssertionLoggerHandler.java @@ -29,8 +29,7 @@ import org.jboss.logmanager.ExtLogRecord; * * Be careful with this use as this is intended for testing only (such as testcases) */ -public class AssertionLoggerHandler extends ExtHandler -{ +public class AssertionLoggerHandler extends ExtHandler { private static final Map messages = new ConcurrentHashMap<>(); private static boolean capture = false; @@ -39,40 +38,32 @@ public class AssertionLoggerHandler extends ExtHandler * {@inheritDoc} */ @Override - public void flush() - { + public void flush() { } /** * {@inheritDoc} */ @Override - public void close() throws SecurityException - { + public void close() throws SecurityException { } @Override - protected void doPublish(final ExtLogRecord record) - { - if (capture) - { + protected void doPublish(final ExtLogRecord record) { + if (capture) { messages.put(record.getFormattedMessage(), record); } } - /** * is there any record matching Level? * * @param level * @return */ - public static boolean hasLevel(Level level) - { - for (ExtLogRecord record : messages.values()) - { - if (record.getLevel().equals(level)) - { + public static boolean hasLevel(Level level) { + for (ExtLogRecord record : messages.values()) { + if (record.getLevel().equals(level)) { return true; } } @@ -86,37 +77,29 @@ public class AssertionLoggerHandler extends ExtHandler * @param text * @return */ - public static boolean findText(final String... text) - { - for (Map.Entry entry : messages.entrySet()) - { + public static boolean findText(final String... text) { + for (Map.Entry entry : messages.entrySet()) { String key = entry.getKey(); boolean found = true; - for (String txtCheck : text) - { + for (String txtCheck : text) { found = key.contains(txtCheck); - if (!found) - { + if (!found) { // If the main log message doesn't contain what we're looking for let's look in the message from the exception (if there is one). Throwable throwable = entry.getValue().getThrown(); - if (throwable != null && throwable.getMessage() != null) - { + if (throwable != null && throwable.getMessage() != null) { found = throwable.getMessage().contains(txtCheck); - if (!found) - { + if (!found) { break; } } - else - { + else { break; } } } - if (found) - { + if (found) { return true; } } @@ -124,19 +107,16 @@ public class AssertionLoggerHandler extends ExtHandler return false; } - public static final void clear() - { + public static final void clear() { messages.clear(); } - public static final void startCapture() - { + public static final void startCapture() { clear(); capture = true; } - public static final void stopCapture() - { + public static final void stopCapture() { capture = false; clear(); } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ActiveMQThreadFactory.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ActiveMQThreadFactory.java index 00d2a731bd..3c59f34b89 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ActiveMQThreadFactory.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ActiveMQThreadFactory.java @@ -22,8 +22,8 @@ import java.security.PrivilegedAction; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; -public final class ActiveMQThreadFactory implements ThreadFactory -{ +public final class ActiveMQThreadFactory implements ThreadFactory { + private final ThreadGroup group; private final AtomicInteger threadCount = new AtomicInteger(0); @@ -36,8 +36,7 @@ public final class ActiveMQThreadFactory implements ThreadFactory private final AccessControlContext acc; - public ActiveMQThreadFactory(final String groupName, final boolean daemon, final ClassLoader tccl) - { + public ActiveMQThreadFactory(final String groupName, final boolean daemon, final ClassLoader tccl) { group = new ThreadGroup(groupName + "-" + System.identityHashCode(this)); this.threadPriority = Thread.NORM_PRIORITY; @@ -49,36 +48,30 @@ public final class ActiveMQThreadFactory implements ThreadFactory this.acc = (System.getSecurityManager() == null) ? null : AccessController.getContext(); } - public Thread newThread(final Runnable command) - { + public Thread newThread(final Runnable command) { // create a thread in a privileged block if running with Security Manager - if (acc != null && System.getSecurityManager() != null) - { + if (acc != null && System.getSecurityManager() != null) { return AccessController.doPrivileged(new ThreadCreateAction(command), acc); } - else - { + else { return createThread(command); } } - private final class ThreadCreateAction implements PrivilegedAction - { + private final class ThreadCreateAction implements PrivilegedAction { + private final Runnable target; - private ThreadCreateAction(final Runnable target) - { + private ThreadCreateAction(final Runnable target) { this.target = target; } - public Thread run() - { + public Thread run() { return createThread(target); } } - private Thread createThread(final Runnable command) - { + private Thread createThread(final Runnable command) { final Thread t = new Thread(group, command, "Thread-" + threadCount.getAndIncrement() + " (" + group.getName() + ")"); t.setDaemon(daemon); t.setPriority(threadPriority); diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/Base64.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/Base64.java index 9d2481a371..5284246cdb 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/Base64.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/Base64.java @@ -88,8 +88,7 @@ import java.nio.charset.StandardCharsets; * periodically to check for updates or to contribute improvements. *

*/ -public class Base64 -{ +public class Base64 { /* ******** P U B L I C F I E L D S ******** */ @@ -169,203 +168,33 @@ public class Base64 */ // private final static byte[] ALPHABET; /* Host platform me be something funny like EBCDIC, so we hardcode these values. */ - private static final byte[] _STANDARD_ALPHABET = {(byte) 'A', - (byte) 'B', - (byte) 'C', - (byte) 'D', - (byte) 'E', - (byte) 'F', - (byte) 'G', - (byte) 'H', - (byte) 'I', - (byte) 'J', - (byte) 'K', - (byte) 'L', - (byte) 'M', - (byte) 'N', - (byte) 'O', - (byte) 'P', - (byte) 'Q', - (byte) 'R', - (byte) 'S', - (byte) 'T', - (byte) 'U', - (byte) 'V', - (byte) 'W', - (byte) 'X', - (byte) 'Y', - (byte) 'Z', - (byte) 'a', - (byte) 'b', - (byte) 'c', - (byte) 'd', - (byte) 'e', - (byte) 'f', - (byte) 'g', - (byte) 'h', - (byte) 'i', - (byte) 'j', - (byte) 'k', - (byte) 'l', - (byte) 'm', - (byte) 'n', - (byte) 'o', - (byte) 'p', - (byte) 'q', - (byte) 'r', - (byte) 's', - (byte) 't', - (byte) 'u', - (byte) 'v', - (byte) 'w', - (byte) 'x', - (byte) 'y', - (byte) 'z', - (byte) '0', - (byte) '1', - (byte) '2', - (byte) '3', - (byte) '4', - (byte) '5', - (byte) '6', - (byte) '7', - (byte) '8', - (byte) '9', - (byte) '+', - (byte) '/'}; + private static final byte[] _STANDARD_ALPHABET = {(byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/'}; /** * Translates a Base64 value to either its 6-bit reconstruction value * or a negative number indicating some other meaning. */ - private static final byte[] _STANDARD_DECODABET = { - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, // Decimal 0 - 8 - -5, - -5, // Whitespace: Tab and Linefeed - -9, - -9, // Decimal 11 - 12 + private static final byte[] _STANDARD_DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 + -5, -5, // Whitespace: Tab and Linefeed + -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, // Decimal 14 - 26 - -9, - -9, - -9, - -9, - -9, // Decimal 27 - 31 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 + -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, // Decimal 33 - 42 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 62, // Plus sign at decimal 43 - -9, - -9, - -9, // Decimal 44 - 46 + -9, -9, -9, // Decimal 44 - 46 63, // Slash at decimal 47 - 52, - 53, - 54, - 55, - 56, - 57, - 58, - 59, - 60, - 61, // Numbers zero through nine - -9, - -9, - -9, // Decimal 58 - 60 + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine + -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 - -9, - -9, - -9, // Decimal 62 - 64 - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, // Letters 'A' through 'N' - 14, - 15, - 16, - 17, - 18, - 19, - 20, - 21, - 22, - 23, - 24, - 25, // Letters 'O' through 'Z' - -9, - -9, - -9, - -9, - -9, - -9, // Decimal 91 - 96 - 26, - 27, - 28, - 29, - 30, - 31, - 32, - 33, - 34, - 35, - 36, - 37, - 38, // Letters 'a' through 'm' - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 46, - 47, - 48, - 49, - 50, - 51, // Letters 'n' through 'z' - -9, - -9, - -9, - -9 // Decimal 123 - 126 + -9, -9, -9, // Decimal 62 - 64 + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' + 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' + -9, -9, -9, -9, -9, -9, // Decimal 91 - 96 + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' + -9, -9, -9, -9 // Decimal 123 - 126 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 @@ -375,8 +204,7 @@ public class Base64 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ - }; + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */}; /* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */ @@ -385,203 +213,36 @@ public class Base64 * http://www.faqs.org/rfcs/rfc3548.html. * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash." */ - private static final byte[] _URL_SAFE_ALPHABET = { - (byte) 'A', - (byte) 'B', - (byte) 'C', - (byte) 'D', - (byte) 'E', - (byte) 'F', - (byte) 'G', - (byte) 'H', - (byte) 'I', - (byte) 'J', - (byte) 'K', - (byte) 'L', - (byte) 'M', - (byte) 'N', - (byte) 'O', - (byte) 'P', - (byte) 'Q', - (byte) 'R', - (byte) 'S', - (byte) 'T', - (byte) 'U', - (byte) 'V', - (byte) 'W', - (byte) 'X', - (byte) 'Y', - (byte) 'Z', - (byte) 'a', - (byte) 'b', - (byte) 'c', - (byte) 'd', - (byte) 'e', - (byte) 'f', - (byte) 'g', - (byte) 'h', - (byte) 'i', - (byte) 'j', - (byte) 'k', - (byte) 'l', - (byte) 'm', - (byte) 'n', - (byte) 'o', - (byte) 'p', - (byte) 'q', - (byte) 'r', - (byte) 's', - (byte) 't', - (byte) 'u', - (byte) 'v', - (byte) 'w', - (byte) 'x', - (byte) 'y', - (byte) 'z', - (byte) '0', - (byte) '1', - (byte) '2', - (byte) '3', - (byte) '4', - (byte) '5', - (byte) '6', - (byte) '7', - (byte) '8', - (byte) '9', - (byte) '-', - (byte) '_'}; + private static final byte[] _URL_SAFE_ALPHABET = {(byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '-', (byte) '_'}; /** * Used in decoding URL- and Filename-safe dialects of Base64. */ - private static final byte[] _URL_SAFE_DECODABET = { - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, // Decimal 0 - 8 - -5, - -5, // Whitespace: Tab and Linefeed - -9, - -9, // Decimal 11 - 12 + private static final byte[] _URL_SAFE_DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 + -5, -5, // Whitespace: Tab and Linefeed + -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, // Decimal 14 - 26 - -9, - -9, - -9, - -9, - -9, // Decimal 27 - 31 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 + -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, // Decimal 33 - 42 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 -9, // Plus sign at decimal 43 -9, // Decimal 44 62, // Minus sign at decimal 45 -9, // Decimal 46 -9, // Slash at decimal 47 - 52, - 53, - 54, - 55, - 56, - 57, - 58, - 59, - 60, - 61, // Numbers zero through nine - -9, - -9, - -9, // Decimal 58 - 60 + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine + -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 - -9, - -9, - -9, // Decimal 62 - 64 - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, // Letters 'A' through 'N' - 14, - 15, - 16, - 17, - 18, - 19, - 20, - 21, - 22, - 23, - 24, - 25, // Letters 'O' through 'Z' - -9, - -9, - -9, - -9, // Decimal 91 - 94 + -9, -9, -9, // Decimal 62 - 64 + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' + 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' + -9, -9, -9, -9, // Decimal 91 - 94 63, // Underscore at decimal 95 -9, // Decimal 96 - 26, - 27, - 28, - 29, - 30, - 31, - 32, - 33, - 34, - 35, - 36, - 37, - 38, // Letters 'a' through 'm' - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 46, - 47, - 48, - 49, - 50, - 51, // Letters 'n' through 'z' - -9, - -9, - -9, - -9 // Decimal 123 - 126 + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' + -9, -9, -9, -9 // Decimal 123 - 126 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 @@ -591,8 +252,7 @@ public class Base64 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ - }; + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */}; /* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */ @@ -600,203 +260,36 @@ public class Base64 * I don't get the point of this technique, but it is described here: * http://www.faqs.org/qa/rfcc-1940.html. */ - private static final byte[] _ORDERED_ALPHABET = { - (byte) '-', - (byte) '0', - (byte) '1', - (byte) '2', - (byte) '3', - (byte) '4', - (byte) '5', - (byte) '6', - (byte) '7', - (byte) '8', - (byte) '9', - (byte) 'A', - (byte) 'B', - (byte) 'C', - (byte) 'D', - (byte) 'E', - (byte) 'F', - (byte) 'G', - (byte) 'H', - (byte) 'I', - (byte) 'J', - (byte) 'K', - (byte) 'L', - (byte) 'M', - (byte) 'N', - (byte) 'O', - (byte) 'P', - (byte) 'Q', - (byte) 'R', - (byte) 'S', - (byte) 'T', - (byte) 'U', - (byte) 'V', - (byte) 'W', - (byte) 'X', - (byte) 'Y', - (byte) 'Z', - (byte) '_', - (byte) 'a', - (byte) 'b', - (byte) 'c', - (byte) 'd', - (byte) 'e', - (byte) 'f', - (byte) 'g', - (byte) 'h', - (byte) 'i', - (byte) 'j', - (byte) 'k', - (byte) 'l', - (byte) 'm', - (byte) 'n', - (byte) 'o', - (byte) 'p', - (byte) 'q', - (byte) 'r', - (byte) 's', - (byte) 't', - (byte) 'u', - (byte) 'v', - (byte) 'w', - (byte) 'x', - (byte) 'y', - (byte) 'z'}; + private static final byte[] _ORDERED_ALPHABET = {(byte) '-', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) '_', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z'}; /** * Used in decoding the "ordered" dialect of Base64. */ - private static final byte[] _ORDERED_DECODABET = { - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, // Decimal 0 - 8 - -5, - -5, // Whitespace: Tab and Linefeed - -9, - -9, // Decimal 11 - 12 + private static final byte[] _ORDERED_DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 + -5, -5, // Whitespace: Tab and Linefeed + -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, // Decimal 14 - 26 - -9, - -9, - -9, - -9, - -9, // Decimal 27 - 31 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 + -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, - -9, // Decimal 33 - 42 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 -9, // Plus sign at decimal 43 -9, // Decimal 44 0, // Minus sign at decimal 45 -9, // Decimal 46 -9, // Slash at decimal 47 - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, // Numbers zero through nine - -9, - -9, - -9, // Decimal 58 - 60 + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // Numbers zero through nine + -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 - -9, - -9, - -9, // Decimal 62 - 64 - 11, - 12, - 13, - 14, - 15, - 16, - 17, - 18, - 19, - 20, - 21, - 22, - 23, // Letters 'A' through 'M' - 24, - 25, - 26, - 27, - 28, - 29, - 30, - 31, - 32, - 33, - 34, - 35, - 36, // Letters 'N' through 'Z' - -9, - -9, - -9, - -9, // Decimal 91 - 94 + -9, -9, -9, // Decimal 62 - 64 + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, // Letters 'A' through 'M' + 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, // Letters 'N' through 'Z' + -9, -9, -9, -9, // Decimal 91 - 94 37, // Underscore at decimal 95 -9, // Decimal 96 - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 46, - 47, - 48, - 49, - 50, // Letters 'a' through 'm' - 51, - 52, - 53, - 54, - 55, - 56, - 57, - 58, - 59, - 60, - 61, - 62, - 63, // Letters 'n' through 'z' - -9, - -9, - -9, - -9 // Decimal 123 - 126 + 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, // Letters 'a' through 'm' + 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, // Letters 'n' through 'z' + -9, -9, -9, -9 // Decimal 123 - 126 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 @@ -806,8 +299,7 @@ public class Base64 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ - }; + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */}; /* ******** D E T E R M I N E W H I C H A L H A B E T ******** */ @@ -818,18 +310,14 @@ public class Base64 * in which case one of them will be picked, though there is * no guarantee as to which one will be picked. */ - private static byte[] getAlphabet(final int options) - { - if ((options & Base64.URL_SAFE) == Base64.URL_SAFE) - { + private static byte[] getAlphabet(final int options) { + if ((options & Base64.URL_SAFE) == Base64.URL_SAFE) { return Base64._URL_SAFE_ALPHABET; } - else if ((options & Base64.ORDERED) == Base64.ORDERED) - { + else if ((options & Base64.ORDERED) == Base64.ORDERED) { return Base64._ORDERED_ALPHABET; } - else - { + else { return Base64._STANDARD_ALPHABET; } @@ -842,18 +330,14 @@ public class Base64 * in which case one of them will be picked, though there is * no guarantee as to which one will be picked. */ - private static byte[] getDecodabet(final int options) - { - if ((options & Base64.URL_SAFE) == Base64.URL_SAFE) - { + private static byte[] getDecodabet(final int options) { + if ((options & Base64.URL_SAFE) == Base64.URL_SAFE) { return Base64._URL_SAFE_DECODABET; } - else if ((options & Base64.ORDERED) == Base64.ORDERED) - { + else if ((options & Base64.ORDERED) == Base64.ORDERED) { return Base64._ORDERED_DECODABET; } - else - { + else { return Base64._STANDARD_DECODABET; } @@ -862,8 +346,7 @@ public class Base64 /** * Defeats instantiation. */ - private Base64() - { + private Base64() { } /** @@ -873,27 +356,21 @@ public class Base64 * * @param args Input args */ - public static final void main(final String[] args) - { - if (args.length < 3) - { + public static final void main(final String[] args) { + if (args.length < 3) { Base64.usage("Not enough arguments."); } // end if: args.length < 3 - else - { + else { String flag = args[0]; String infile = args[1]; String outfile = args[2]; - if (flag.equals("-e")) - { + if (flag.equals("-e")) { Base64.encodeFileToFile(infile, outfile); } // end if: encode - else if (flag.equals("-d")) - { + else if (flag.equals("-d")) { Base64.decodeFileToFile(infile, outfile); } // end else if: decode - else - { + else { Base64.usage("Unknown flag: " + flag); } // end else } // end else @@ -904,8 +381,7 @@ public class Base64 * * @param msg A message to include with usage info. */ - private static void usage(final String msg) - { + private static void usage(final String msg) { System.err.println(msg); System.err.println("Usage: java Base64 -e|-d inputfile outputfile"); } // end usage @@ -927,8 +403,10 @@ public class Base64 * @return four byte array in Base64 notation. * @since 1.5.1 */ - private static byte[] encode3to4(final byte[] b4, final byte[] threeBytes, final int numSigBytes, final int options) - { + private static byte[] encode3to4(final byte[] b4, + final byte[] threeBytes, + final int numSigBytes, + final int options) { Base64.encode3to4(threeBytes, 0, numSigBytes, b4, 0, options); return b4; } // end encode3to4 @@ -961,8 +439,7 @@ public class Base64 final int numSigBytes, final byte[] destination, final int destOffset, - final int options) - { + final int options) { byte[] ALPHABET = Base64.getAlphabet(options); // 1 2 3 @@ -976,12 +453,10 @@ public class Base64 // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. - int inBuff = (numSigBytes > 0 ? source[srcOffset] << 24 >>> 8 : 0) | (numSigBytes > 1 ? source[srcOffset + 1] << 24 >>> 16 - : 0) | + int inBuff = (numSigBytes > 0 ? source[srcOffset] << 24 >>> 8 : 0) | (numSigBytes > 1 ? source[srcOffset + 1] << 24 >>> 16 : 0) | (numSigBytes > 2 ? source[srcOffset + 2] << 24 >>> 24 : 0); - switch (numSigBytes) - { + switch (numSigBytes) { case 3: destination[destOffset] = ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1] = ALPHABET[inBuff >>> 12 & 0x3f]; @@ -1019,8 +494,7 @@ public class Base64 * @return The Base64-encoded object * @since 1.4 */ - public static String encodeObject(final java.io.Serializable serializableObject) - { + public static String encodeObject(final java.io.Serializable serializableObject) { return Base64.encodeObject(serializableObject, Base64.NO_OPTIONS); } // end encodeObject @@ -1047,8 +521,7 @@ public class Base64 * @see Base64#DONT_BREAK_LINES * @since 2.0 */ - public static String encodeObject(final java.io.Serializable serializableObject, final int options) - { + public static String encodeObject(final java.io.Serializable serializableObject, final int options) { // Streams java.io.ByteArrayOutputStream baos = null; java.io.OutputStream b64os = null; @@ -1058,59 +531,46 @@ public class Base64 // Isolate options int gzip = options & Base64.GZIP; - try - { + try { // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream(baos, Base64.ENCODE | options); // GZip? - if (gzip == Base64.GZIP) - { + if (gzip == Base64.GZIP) { gzos = new java.util.zip.GZIPOutputStream(b64os); oos = new java.io.ObjectOutputStream(gzos); } // end if: gzip - else - { + else { oos = new java.io.ObjectOutputStream(b64os); } oos.writeObject(serializableObject); } // end try - catch (java.io.IOException e) - { + catch (java.io.IOException e) { e.printStackTrace(); return null; } // end catch - finally - { - try - { + finally { + try { oos.close(); } - catch (Exception e) - { + catch (Exception e) { } - try - { + try { gzos.close(); } - catch (Exception e) - { + catch (Exception e) { } - try - { + try { b64os.close(); } - catch (Exception e) - { + catch (Exception e) { } - try - { + try { baos.close(); } - catch (Exception e) - { + catch (Exception e) { } } // end finally @@ -1127,8 +587,7 @@ public class Base64 * @return Base64 String * @since 1.4 */ - public static String encodeBytes(final byte[] source) - { + public static String encodeBytes(final byte[] source) { return Base64.encodeBytes(source, 0, source.length, Base64.NO_OPTIONS); } // end encodeBytes @@ -1152,8 +611,7 @@ public class Base64 * @see Base64#DONT_BREAK_LINES * @since 2.0 */ - public static String encodeBytes(final byte[] source, final int options) - { + public static String encodeBytes(final byte[] source, final int options) { return Base64.encodeBytes(source, 0, source.length, options); } // end encodeBytes @@ -1167,8 +625,7 @@ public class Base64 * @return Encoded String * @since 1.4 */ - public static String encodeBytes(final byte[] source, final int off, final int len) - { + public static String encodeBytes(final byte[] source, final int off, final int len) { return Base64.encodeBytes(source, off, len, Base64.NO_OPTIONS); } // end encodeBytes @@ -1194,21 +651,18 @@ public class Base64 * @see Base64#DONT_BREAK_LINES * @since 2.0 */ - public static String encodeBytes(final byte[] source, final int off, final int len, final int options) - { + public static String encodeBytes(final byte[] source, final int off, final int len, final int options) { // Isolate options int dontBreakLines = options & Base64.DONT_BREAK_LINES; int gzip = options & Base64.GZIP; // Compress? - if (gzip == Base64.GZIP) - { + if (gzip == Base64.GZIP) { java.io.ByteArrayOutputStream baos = null; java.util.zip.GZIPOutputStream gzos = null; Base64.OutputStream b64os = null; - try - { + try { // GZip -> Base64 -> ByteArray baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream(baos, Base64.ENCODE | options); @@ -1217,33 +671,25 @@ public class Base64 gzos.write(source, off, len); gzos.close(); } // end try - catch (java.io.IOException e) - { + catch (java.io.IOException e) { e.printStackTrace(); return null; } // end catch - finally - { - try - { + finally { + try { gzos.close(); } - catch (Exception e) - { + catch (Exception e) { } - try - { + try { b64os.close(); } - catch (Exception e) - { + catch (Exception e) { } - try - { + try { baos.close(); } - catch (Exception e) - { + catch (Exception e) { } } // end finally @@ -1252,8 +698,7 @@ public class Base64 } // end if: compress // Else, don't compress. Better not to use streams at all then. - else - { + else { // Convert option to boolean in way that code likes it. boolean breakLines = dontBreakLines == 0; @@ -1265,21 +710,18 @@ public class Base64 int e = 0; int len2 = len - 2; int lineLength = 0; - for (; d < len2; d += 3, e += 4) - { + for (; d < len2; d += 3, e += 4) { Base64.encode3to4(source, d + off, 3, outBuff, e, options); lineLength += 4; - if (breakLines && lineLength == Base64.MAX_LINE_LENGTH) - { + if (breakLines && lineLength == Base64.MAX_LINE_LENGTH) { outBuff[e + 4] = Base64.NEW_LINE; e++; lineLength = 0; } // end if: end of line } // en dfor: each piece of array - if (d < len) - { + if (d < len) { Base64.encode3to4(source, d + off, len - d, outBuff, e, options); e += 4; } // end if: some padding needed @@ -1321,13 +763,11 @@ public class Base64 final int srcOffset, final byte[] destination, final int destOffset, - final int options) - { + final int options) { byte[] DECODABET = Base64.getDecodabet(options); // Example: Dk== - if (source[srcOffset + 2] == Base64.EQUALS_SIGN) - { + if (source[srcOffset + 2] == Base64.EQUALS_SIGN) { // Two ways to do the same thing. Don't know which way I like best. // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); @@ -1338,8 +778,7 @@ public class Base64 } // Example: DkL= - else if (source[srcOffset + 3] == Base64.EQUALS_SIGN) - { + else if (source[srcOffset + 3] == Base64.EQUALS_SIGN) { // Two ways to do the same thing. Don't know which way I like best. // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) @@ -1353,10 +792,8 @@ public class Base64 } // Example: DkLE - else - { - try - { + else { + try { // Two ways to do the same thing. Don't know which way I like best. // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) @@ -1364,8 +801,7 @@ public class Base64 // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); int outBuff = (DECODABET[source[srcOffset]] & 0xFF) << 18 | (DECODABET[source[srcOffset + 1]] & 0xFF) << 12 | (DECODABET[source[srcOffset + 2]] & 0xFF) << 6 | - DECODABET[source[srcOffset + 3]] & - 0xFF; + DECODABET[source[srcOffset + 3]] & 0xFF; destination[destOffset] = (byte) (outBuff >> 16); destination[destOffset + 1] = (byte) (outBuff >> 8); @@ -1373,8 +809,7 @@ public class Base64 return 3; } - catch (Exception e) - { + catch (Exception e) { System.out.println("" + source[srcOffset] + ": " + DECODABET[source[srcOffset]]); System.out.println("" + source[srcOffset + 1] + ": " + DECODABET[source[srcOffset + 1]]); System.out.println("" + source[srcOffset + 2] + ": " + DECODABET[source[srcOffset + 2]]); @@ -1389,15 +824,14 @@ public class Base64 * the form of a byte array. Does not support automatically * gunzipping or any other "fancy" features. * - * @param source The Base64 encoded data - * @param off The offset of where to begin decoding - * @param len The length of characters to decode + * @param source The Base64 encoded data + * @param off The offset of where to begin decoding + * @param len The length of characters to decode * @param options Specified options * @return decoded data * @since 1.3 */ - public static byte[] decode(final byte[] source, final int off, final int len, final int options) - { + public static byte[] decode(final byte[] source, final int off, final int len, final int options) { byte[] DECODABET = Base64.getDecodabet(options); int len34 = len * 3 / 4; @@ -1409,24 +843,20 @@ public class Base64 int i = 0; byte sbiCrop = 0; byte sbiDecode = 0; - for (i = off; i < off + len; i++) - { + for (i = off; i < off + len; i++) { sbiCrop = (byte) (source[i] & 0x7f); // Only the low seven bits sbiDecode = DECODABET[sbiCrop]; if (sbiDecode >= Base64.WHITE_SPACE_ENC) // White space, Equals sign or better { - if (sbiDecode >= Base64.EQUALS_SIGN_ENC) - { + if (sbiDecode >= Base64.EQUALS_SIGN_ENC) { b4[b4Posn++] = sbiCrop; - if (b4Posn > 3) - { + if (b4Posn > 3) { outBuffPosn += Base64.decode4to3(b4, 0, outBuff, outBuffPosn, options); b4Posn = 0; // If that was the equals sign, break out of 'for' loop - if (sbiCrop == Base64.EQUALS_SIGN) - { + if (sbiCrop == Base64.EQUALS_SIGN) { break; } } // end if: quartet built @@ -1434,8 +864,7 @@ public class Base64 } // end if: equals sign or better } // end if: white space, equals sign or better - else - { + else { System.err.println("Bad Base64 input character at " + i + ": " + source[i] + "(decimal)"); return null; } // end else: @@ -1454,8 +883,7 @@ public class Base64 * @return the decoded data * @since 1.4 */ - public static byte[] decode(final String s) - { + public static byte[] decode(final String s) { return Base64.decode(s, Base64.NO_OPTIONS); } @@ -1468,8 +896,7 @@ public class Base64 * @return the decoded data * @since 1.4 */ - public static byte[] decode(final String s, final int options) - { + public static byte[] decode(final String s, final int options) { byte[] bytes = s.getBytes(Base64.PREFERRED_ENCODING); // @@ -1478,26 +905,22 @@ public class Base64 // Check to see if it's gzip-compressed // GZIP Magic Two-Byte Number: 0x8b1f (35615) - if (bytes != null && bytes.length >= 4) - { + if (bytes != null && bytes.length >= 4) { int head = bytes[0] & 0xff | bytes[1] << 8 & 0xff00; - if (java.util.zip.GZIPInputStream.GZIP_MAGIC == head) - { + if (java.util.zip.GZIPInputStream.GZIP_MAGIC == head) { java.io.ByteArrayInputStream bais = null; java.util.zip.GZIPInputStream gzis = null; java.io.ByteArrayOutputStream baos = null; byte[] buffer = new byte[2048]; int length = 0; - try - { + try { baos = new java.io.ByteArrayOutputStream(); bais = new java.io.ByteArrayInputStream(bytes); gzis = new java.util.zip.GZIPInputStream(bais); - while ((length = gzis.read(buffer)) >= 0) - { + while ((length = gzis.read(buffer)) >= 0) { baos.write(buffer, 0, length); } // end while: reading input @@ -1505,32 +928,24 @@ public class Base64 bytes = baos.toByteArray(); } // end try - catch (java.io.IOException e) - { + catch (java.io.IOException e) { // Just return originally-decoded bytes } // end catch - finally - { - try - { + finally { + try { baos.close(); } - catch (Exception e) - { + catch (Exception e) { } - try - { + try { gzis.close(); } - catch (Exception e) - { + catch (Exception e) { } - try - { + try { bais.close(); } - catch (Exception e) - { + catch (Exception e) { } } // end finally @@ -1548,8 +963,7 @@ public class Base64 * @return The decoded and deserialized object * @since 1.5 */ - public static Object decodeToObject(final String encodedObject) - { + public static Object decodeToObject(final String encodedObject) { // Decode and gunzip if necessary byte[] objBytes = Base64.decode(encodedObject); @@ -1557,38 +971,30 @@ public class Base64 java.io.ObjectInputStream ois = null; Object obj = null; - try - { + try { bais = new java.io.ByteArrayInputStream(objBytes); ois = new java.io.ObjectInputStream(bais); obj = ois.readObject(); } // end try - catch (java.io.IOException e) - { + catch (java.io.IOException e) { e.printStackTrace(); obj = null; } // end catch - catch (java.lang.ClassNotFoundException e) - { + catch (java.lang.ClassNotFoundException e) { e.printStackTrace(); obj = null; } // end catch - finally - { - try - { + finally { + try { bais.close(); } - catch (Exception e) - { + catch (Exception e) { } - try - { + try { ois.close(); } - catch (Exception e) - { + catch (Exception e) { } } // end finally @@ -1603,29 +1009,23 @@ public class Base64 * @return true if successful, false otherwise * @since 2.1 */ - public static boolean encodeToFile(final byte[] dataToEncode, final String filename) - { + public static boolean encodeToFile(final byte[] dataToEncode, final String filename) { boolean success = false; Base64.OutputStream bos = null; - try - { + try { bos = new Base64.OutputStream(new java.io.FileOutputStream(filename), Base64.ENCODE); bos.write(dataToEncode); success = true; } // end try - catch (java.io.IOException e) - { + catch (java.io.IOException e) { success = false; } // end catch: IOException - finally - { - try - { + finally { + try { bos.close(); } - catch (Exception e) - { + catch (Exception e) { } } // end finally @@ -1640,28 +1040,22 @@ public class Base64 * @return true if successful, false otherwise * @since 2.1 */ - public static boolean decodeToFile(final String dataToDecode, final String filename) - { + public static boolean decodeToFile(final String dataToDecode, final String filename) { boolean success = false; Base64.OutputStream bos = null; - try - { + try { bos = new Base64.OutputStream(new java.io.FileOutputStream(filename), Base64.DECODE); bos.write(dataToDecode.getBytes(Base64.PREFERRED_ENCODING)); success = true; } // end try - catch (java.io.IOException e) - { + catch (java.io.IOException e) { success = false; } // end catch: IOException - finally - { - try - { + finally { + try { bos.close(); } - catch (Exception e) - { + catch (Exception e) { } } // end finally @@ -1676,12 +1070,10 @@ public class Base64 * @return decoded byte array or null if unsuccessful * @since 2.1 */ - public static byte[] decodeFromFile(final String filename) - { + public static byte[] decodeFromFile(final String filename) { byte[] decodedData = null; Base64.InputStream bis = null; - try - { + try { // Set up some useful variables java.io.File file = new java.io.File(filename); byte[] buffer = null; @@ -1689,8 +1081,7 @@ public class Base64 int numBytes = 0; // Check for size of file - if (file.length() > Integer.MAX_VALUE) - { + if (file.length() > Integer.MAX_VALUE) { System.err.println("File is too big for this convenience method (" + file.length() + " bytes)."); return null; } // end if: file too big for int index @@ -1700,8 +1091,7 @@ public class Base64 bis = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(file)), Base64.DECODE); // Read until done - while ((numBytes = bis.read(buffer, length, 4096)) >= 0) - { + while ((numBytes = bis.read(buffer, length, 4096)) >= 0) { length += numBytes; } @@ -1710,21 +1100,16 @@ public class Base64 System.arraycopy(buffer, 0, decodedData, 0, length); } // end try - catch (java.io.IOException e) - { + catch (java.io.IOException e) { System.err.println("Error decoding from file " + filename); } // end catch: IOException - finally - { - try - { - if (bis != null) - { + finally { + try { + if (bis != null) { bis.close(); } } - catch (Exception e) - { + catch (Exception e) { } } // end finally @@ -1739,12 +1124,10 @@ public class Base64 * @return base64-encoded string or null if unsuccessful * @since 2.1 */ - public static String encodeFromFile(final String filename) - { + public static String encodeFromFile(final String filename) { String encodedData = null; Base64.InputStream bis = null; - try - { + try { // Set up some useful variables java.io.File file = new java.io.File(filename); byte[] buffer = new byte[Math.max((int) (file.length() * 1.4), 40)]; // Need max() for math on small files @@ -1756,8 +1139,7 @@ public class Base64 bis = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(file)), Base64.ENCODE); // Read until done - while ((numBytes = bis.read(buffer, length, 4096)) >= 0) - { + while ((numBytes = bis.read(buffer, length, 4096)) >= 0) { length += numBytes; } @@ -1765,18 +1147,14 @@ public class Base64 encodedData = new String(buffer, 0, length, Base64.PREFERRED_ENCODING); } // end try - catch (java.io.IOException e) - { + catch (java.io.IOException e) { System.err.println("Error encoding from file " + filename); } // end catch: IOException - finally - { - try - { + finally { + try { bis.close(); } - catch (Exception e) - { + catch (Exception e) { } } // end finally @@ -1791,43 +1169,33 @@ public class Base64 * @return true if the operation is successful * @since 2.2 */ - public static boolean encodeFileToFile(final String infile, final String outfile) - { + public static boolean encodeFileToFile(final String infile, final String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; - try - { - in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), - Base64.ENCODE); + try { + in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; // 64K int read = -1; - while ((read = in.read(buffer)) >= 0) - { + while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } // end while: through file success = true; } - catch (java.io.IOException exc) - { + catch (java.io.IOException exc) { exc.printStackTrace(); } - finally - { - try - { + finally { + try { in.close(); } - catch (Exception exc) - { + catch (Exception exc) { } - try - { + try { out.close(); } - catch (Exception exc) - { + catch (Exception exc) { } } // end finally @@ -1842,43 +1210,33 @@ public class Base64 * @return true if the operation is successful * @since 2.2 */ - public static boolean decodeFileToFile(final String infile, final String outfile) - { + public static boolean decodeFileToFile(final String infile, final String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; - try - { - in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), - Base64.DECODE); + try { + in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; // 64K int read = -1; - while ((read = in.read(buffer)) >= 0) - { + while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } // end while: through file success = true; } - catch (java.io.IOException exc) - { + catch (java.io.IOException exc) { exc.printStackTrace(); } - finally - { - try - { + finally { + try { in.close(); } - catch (Exception exc) - { + catch (Exception exc) { } - try - { + try { out.close(); } - catch (Exception exc) - { + catch (Exception exc) { } } // end finally @@ -1895,8 +1253,8 @@ public class Base64 * @see Base64 * @since 1.3 */ - public static class InputStream extends java.io.FilterInputStream - { + public static class InputStream extends java.io.FilterInputStream { + private final boolean encode; // Encoding or decoding private int position; // Current position in the buffer @@ -1923,8 +1281,7 @@ public class Base64 * @param in the java.io.InputStream from which to read data. * @since 1.3 */ - public InputStream(final java.io.InputStream in) - { + public InputStream(final java.io.InputStream in) { this(in, Base64.DECODE); } // end constructor @@ -1948,8 +1305,7 @@ public class Base64 * @see Base64#DONT_BREAK_LINES * @since 2.0 */ - public InputStream(final java.io.InputStream in, final int options) - { + public InputStream(final java.io.InputStream in, final int options) { super(in); breakLines = (options & Base64.DONT_BREAK_LINES) != Base64.DONT_BREAK_LINES; encode = (options & Base64.ENCODE) == Base64.ENCODE; @@ -1970,86 +1326,68 @@ public class Base64 * @since 1.3 */ @Override - public int read() throws java.io.IOException - { + public int read() throws java.io.IOException { // Do we need to get data? - if (position < 0) - { - if (encode) - { + if (position < 0) { + if (encode) { byte[] b3 = new byte[3]; int numBinaryBytes = 0; - for (int i = 0; i < 3; i++) - { - try - { + for (int i = 0; i < 3; i++) { + try { int b = in.read(); // If end of stream, b is -1. - if (b >= 0) - { + if (b >= 0) { b3[i] = (byte) b; numBinaryBytes++; } // end if: not end of stream } // end try: read - catch (java.io.IOException e) - { + catch (java.io.IOException e) { // Only a problem if we got no data at all. - if (i == 0) - { + if (i == 0) { throw e; } } // end catch } // end for: each needed input byte - if (numBinaryBytes > 0) - { + if (numBinaryBytes > 0) { Base64.encode3to4(b3, 0, numBinaryBytes, buffer, 0, options); position = 0; numSigBytes = 4; } // end if: got data - else - { + else { return -1; } } // end if: encoding // Else decoding - else - { + else { byte[] b4 = new byte[4]; int i = 0; - for (i = 0; i < 4; i++) - { + for (i = 0; i < 4; i++) { // Read four "meaningful" bytes: int b = 0; - do - { + do { b = in.read(); - } - while (b >= 0 && decodabet[b & 0x7f] <= Base64.WHITE_SPACE_ENC); + } while (b >= 0 && decodabet[b & 0x7f] <= Base64.WHITE_SPACE_ENC); - if (b < 0) - { + if (b < 0) { break; // Reads a -1 if end of stream } b4[i] = (byte) b; } // end for: each needed input byte - if (i == 4) - { + if (i == 4) { numSigBytes = Base64.decode4to3(b4, 0, buffer, 0, options); position = 0; } // end if: got four characters - else if (i == 0) - { + else if (i == 0) { return -1; } - else - { + else { // Must have broken out from above. throw new java.io.IOException("Improperly padded Base64 input."); } @@ -2058,29 +1396,24 @@ public class Base64 } // end else: get data // Got data? - if (position >= 0) - { + if (position >= 0) { // End of relevant data? - if ( /*!encode &&*/position >= numSigBytes) - { + if ( /*!encode &&*/position >= numSigBytes) { return -1; } - if (encode && breakLines && lineLength >= Base64.MAX_LINE_LENGTH) - { + if (encode && breakLines && lineLength >= Base64.MAX_LINE_LENGTH) { lineLength = 0; return '\n'; } // end if - else - { + else { lineLength++; // This isn't important when decoding // but throwing an extra "if" seems // just as wasteful. int b = buffer[position++]; - if (position >= bufferLength) - { + if (position >= bufferLength) { position = -1; } @@ -2088,8 +1421,7 @@ public class Base64 // intended to be unsigned. } // end else } // end if: position >= 0 - else - { + else { // When JDK1.4 is more accepted, use an assertion here. throw new java.io.IOException("Error in Base64 code reading stream."); } @@ -2108,27 +1440,22 @@ public class Base64 * @since 1.3 */ @Override - public int read(final byte[] dest, final int off, final int len) throws java.io.IOException - { + public int read(final byte[] dest, final int off, final int len) throws java.io.IOException { int i; int b; - for (i = 0; i < len; i++) - { + for (i = 0; i < len; i++) { b = read(); // if( b < 0 && i == 0 ) // return -1; - if (b >= 0) - { + if (b >= 0) { dest[off + i] = (byte) b; } - else if (i == 0) - { + else if (i == 0) { return -1; } - else - { + else { break; // Out of 'for' loop } } // end for: each byte read @@ -2147,8 +1474,8 @@ public class Base64 * @see Base64 * @since 1.3 */ - public static class OutputStream extends java.io.FilterOutputStream - { + public static class OutputStream extends java.io.FilterOutputStream { + private final boolean encode; private int position; @@ -2177,8 +1504,7 @@ public class Base64 * @param out the java.io.OutputStream to which data will be written. * @since 1.3 */ - public OutputStream(final java.io.OutputStream out) - { + public OutputStream(final java.io.OutputStream out) { this(out, Base64.ENCODE); } // end constructor @@ -2202,8 +1528,7 @@ public class Base64 * @see Base64#DONT_BREAK_LINES * @since 1.3 */ - public OutputStream(final java.io.OutputStream out, final int options) - { + public OutputStream(final java.io.OutputStream out, final int options) { super(out); breakLines = (options & Base64.DONT_BREAK_LINES) != Base64.DONT_BREAK_LINES; encode = (options & Base64.ENCODE) == Base64.ENCODE; @@ -2232,26 +1557,21 @@ public class Base64 * @since 1.3 */ @Override - public void write(final int theByte) throws java.io.IOException - { + public void write(final int theByte) throws java.io.IOException { // Encoding suspended? - if (suspendEncoding) - { + if (suspendEncoding) { super.out.write(theByte); return; } // end if: supsended // Encode? - if (encode) - { + if (encode) { buffer[position++] = (byte) theByte; - if (position >= bufferLength) // Enough to encode. - { + if (position >= bufferLength) { // Enough to encode. out.write(Base64.encode3to4(b4, buffer, bufferLength, options)); lineLength += 4; - if (breakLines && lineLength >= Base64.MAX_LINE_LENGTH) - { + if (breakLines && lineLength >= Base64.MAX_LINE_LENGTH) { out.write(Base64.NEW_LINE); lineLength = 0; } // end if: end of line @@ -2261,22 +1581,18 @@ public class Base64 } // end if: encoding // Else, Decoding - else - { + else { // Meaningful Base64 character? - if (decodabet[theByte & 0x7f] > Base64.WHITE_SPACE_ENC) - { + if (decodabet[theByte & 0x7f] > Base64.WHITE_SPACE_ENC) { buffer[position++] = (byte) theByte; - if (position >= bufferLength) // Enough to output. - { + if (position >= bufferLength) { // Enough to output. int len = Base64.decode4to3(buffer, 0, b4, 0, options); out.write(b4, 0, len); // out.write( Base64.decode4to3( buffer ) ); position = 0; } // end if: enough to output } // end if: meaningful base64 character - else if (decodabet[theByte & 0x7f] != Base64.WHITE_SPACE_ENC) - { + else if (decodabet[theByte & 0x7f] != Base64.WHITE_SPACE_ENC) { throw new java.io.IOException("Invalid character in Base64 data."); } } // end else: decoding @@ -2289,21 +1605,18 @@ public class Base64 * @param theBytes array from which to read bytes * @param off offset for array * @param len max number of bytes to read into array - * @since 1.3 * @throws java.io.IOException Throws IOException + * @since 1.3 */ @Override - public void write(final byte[] theBytes, final int off, final int len) throws java.io.IOException - { + public void write(final byte[] theBytes, final int off, final int len) throws java.io.IOException { // Encoding suspended? - if (suspendEncoding) - { + if (suspendEncoding) { super.out.write(theBytes, off, len); return; } // end if: supsended - for (int i = 0; i < len; i++) - { + for (int i = 0; i < len; i++) { write(theBytes[off + i]); } // end for: each byte written @@ -2312,19 +1625,16 @@ public class Base64 /** * Method added by PHIL. [Thanks, PHIL. -Rob] * This pads the buffer without closing the stream. + * * @throws java.io.IOException On IO Exception */ - public void flushBase64() throws java.io.IOException - { - if (position > 0) - { - if (encode) - { + public void flushBase64() throws java.io.IOException { + if (position > 0) { + if (encode) { out.write(Base64.encode3to4(b4, buffer, position, options)); position = 0; } // end if: encoding - else - { + else { throw new java.io.IOException("Base64 input not properly padded."); } } // end if: buffer partially full @@ -2336,11 +1646,9 @@ public class Base64 * * @throws java.io.IOException Throws IOException * @since 1.3 - * */ @Override - public void close() throws java.io.IOException - { + public void close() throws java.io.IOException { // 1. Ensure that pending characters are written flushBase64(); @@ -2356,11 +1664,11 @@ public class Base64 * Suspends encoding of the stream. * May be helpful if you need to embed a piece of * base640-encoded data in a stream. + * * @throws java.io.IOException On IO Exception * @since 1.5.1 */ - public void suspendEncoding() throws java.io.IOException - { + public void suspendEncoding() throws java.io.IOException { flushBase64(); suspendEncoding = true; } // end suspendEncoding @@ -2372,8 +1680,7 @@ public class Base64 * * @since 1.5.1 */ - public void resumeEncoding() - { + public void resumeEncoding() { suspendEncoding = false; } // end resumeEncoding diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ByteUtil.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ByteUtil.java index f2b4e4f1b7..6e2ca99e83 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ByteUtil.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ByteUtil.java @@ -19,36 +19,28 @@ package org.apache.activemq.artemis.utils; import io.netty.buffer.ByteBuf; import io.netty.buffer.UnpooledByteBufAllocator; -public class ByteUtil -{ +public class ByteUtil { private static final char[] hexArray = "0123456789ABCDEF".toCharArray(); - public static String maxString(String value, int size) - { - if (value.length() < size) - { + public static String maxString(String value, int size) { + if (value.length() < size) { return value; } - else - { + else { return value.substring(0, size / 2) + " ... " + value.substring(value.length() - size / 2); } } - public static String bytesToHex(byte[] bytes, int groupSize) - { - if (bytes == null) - { + + public static String bytesToHex(byte[] bytes, int groupSize) { + if (bytes == null) { return "null"; } - else - { + else { char[] hexChars = new char[bytes.length * 2 + numberOfGroups(bytes, groupSize)]; int outPos = 0; - for (int j = 0; j < bytes.length; j++) - { - if (j > 0 && j % groupSize == 0) - { + for (int j = 0; j < bytes.length; j++) { + if (j > 0 && j % groupSize == 0) { hexChars[outPos++] = ' '; } int v = bytes[j] & 0xFF; @@ -59,20 +51,17 @@ public class ByteUtil } } - private static int numberOfGroups(byte[] bytes, int groupSize) - { + private static int numberOfGroups(byte[] bytes, int groupSize) { int groups = bytes.length / groupSize; - if (bytes.length % groupSize == 0) - { + if (bytes.length % groupSize == 0) { groups--; } return groups; } - public static byte[] longToBytes(long x) - { + public static byte[] longToBytes(long x) { ByteBuf buffer = UnpooledByteBufAllocator.DEFAULT.heapBuffer(8, 8); buffer.writeLong(x); return buffer.array(); diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ClassloadingUtil.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ClassloadingUtil.java index 098bc56d6a..707635eff5 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ClassloadingUtil.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ClassloadingUtil.java @@ -25,101 +25,80 @@ import java.net.URL; * Is't required to use a Security Block on any calls to this class. */ -public final class ClassloadingUtil -{ - private static final String INSTANTIATION_EXCEPTION_MESSAGE = - "Your class must have a constructor without arguments. If it is an inner class, it must be static!"; +public final class ClassloadingUtil { - public static Object newInstanceFromClassLoader(final String className) - { + private static final String INSTANTIATION_EXCEPTION_MESSAGE = "Your class must have a constructor without arguments. If it is an inner class, it must be static!"; + + public static Object newInstanceFromClassLoader(final String className) { ClassLoader loader = ClassloadingUtil.class.getClassLoader(); - try - { + try { Class clazz = loader.loadClass(className); return clazz.newInstance(); } - catch (Throwable t) - { - if (t instanceof InstantiationException) - { + catch (Throwable t) { + if (t instanceof InstantiationException) { System.out.println(INSTANTIATION_EXCEPTION_MESSAGE); } loader = Thread.currentThread().getContextClassLoader(); if (loader == null) throw new RuntimeException("No local context classloader", t); - try - { + try { return loader.loadClass(className).newInstance(); } - catch (InstantiationException e) - { + catch (InstantiationException e) { throw new RuntimeException(INSTANTIATION_EXCEPTION_MESSAGE + " " + className, e); } - catch (ClassNotFoundException e) - { + catch (ClassNotFoundException e) { throw new IllegalStateException(e); } - catch (IllegalAccessException e) - { + catch (IllegalAccessException e) { throw new RuntimeException(e); } } } - public static Object newInstanceFromClassLoader(final String className, Object... objs) - { + public static Object newInstanceFromClassLoader(final String className, Object... objs) { ClassLoader loader = ClassloadingUtil.class.getClassLoader(); - try - { + try { Class[] parametersType = new Class[objs.length]; - for (int i = 0; i < objs.length; i++) - { + for (int i = 0; i < objs.length; i++) { parametersType[i] = objs[i].getClass(); } Class clazz = loader.loadClass(className); return clazz.getConstructor(parametersType).newInstance(objs); } - catch (Throwable t) - { - if (t instanceof InstantiationException) - { + catch (Throwable t) { + if (t instanceof InstantiationException) { System.out.println(INSTANTIATION_EXCEPTION_MESSAGE); } loader = Thread.currentThread().getContextClassLoader(); if (loader == null) throw new RuntimeException("No local context classloader", t); - try - { + try { return loader.loadClass(className).newInstance(); } - catch (InstantiationException e) - { + catch (InstantiationException e) { throw new RuntimeException(INSTANTIATION_EXCEPTION_MESSAGE + " " + className, e); } - catch (ClassNotFoundException e) - { + catch (ClassNotFoundException e) { throw new IllegalStateException(e); } - catch (IllegalAccessException e) - { + catch (IllegalAccessException e) { throw new RuntimeException(e); } } } - public static URL findResource(final String resourceName) - { + public static URL findResource(final String resourceName) { ClassLoader loader = ClassloadingUtil.class.getClassLoader(); - try - { + try { URL resource = loader.getResource(resourceName); if (resource != null) return resource; } - catch (Throwable t) - { + catch (Throwable t) { } loader = Thread.currentThread().getContextClassLoader(); diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ConcurrentHashSet.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ConcurrentHashSet.java index e39b36e6bf..c0fe578b21 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ConcurrentHashSet.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ConcurrentHashSet.java @@ -22,67 +22,56 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** - * * A ConcurrentHashSet. * * Offers same concurrency as ConcurrentHashMap but for a Set - * */ -public class ConcurrentHashSet extends AbstractSet implements ConcurrentSet -{ +public class ConcurrentHashSet extends AbstractSet implements ConcurrentSet { + private final ConcurrentMap theMap; private static final Object dummy = new Object(); - public ConcurrentHashSet() - { + public ConcurrentHashSet() { theMap = new ConcurrentHashMap(); } @Override - public int size() - { + public int size() { return theMap.size(); } @Override - public Iterator iterator() - { + public Iterator iterator() { return theMap.keySet().iterator(); } @Override - public boolean isEmpty() - { + public boolean isEmpty() { return theMap.isEmpty(); } @Override - public boolean add(final E o) - { + public boolean add(final E o) { return theMap.put(o, ConcurrentHashSet.dummy) == null; } @Override - public boolean contains(final Object o) - { + public boolean contains(final Object o) { return theMap.containsKey(o); } @Override - public void clear() - { + public void clear() { theMap.clear(); } @Override - public boolean remove(final Object o) - { + public boolean remove(final Object o) { return theMap.remove(o) == ConcurrentHashSet.dummy; } - public boolean addIfAbsent(final E o) - { + public boolean addIfAbsent(final E o) { Object obj = theMap.putIfAbsent(o, ConcurrentHashSet.dummy); return obj == null; diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ConcurrentSet.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ConcurrentSet.java index e88cac4ac1..e55be241aa 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ConcurrentSet.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ConcurrentSet.java @@ -19,12 +19,11 @@ package org.apache.activemq.artemis.utils; import java.util.Set; /** - * * A ConcurrentSet * * @param The generic class */ -public interface ConcurrentSet extends Set -{ +public interface ConcurrentSet extends Set { + boolean addIfAbsent(E o); } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/DataConstants.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/DataConstants.java index 9ea5cf38b2..38df9b61e2 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/DataConstants.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/DataConstants.java @@ -16,8 +16,8 @@ */ package org.apache.activemq.artemis.utils; -public final class DataConstants -{ +public final class DataConstants { + public static final int SIZE_INT = 4; public static final int SIZE_BOOLEAN = 1; diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/DefaultSensitiveStringCodec.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/DefaultSensitiveStringCodec.java index 8e1a1dbe3e..6028742176 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/DefaultSensitiveStringCodec.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/DefaultSensitiveStringCodec.java @@ -38,31 +38,24 @@ import javax.crypto.spec.SecretKeySpec; * The decode() and encode() method is copied originally from * JBoss AS code base. */ -public class DefaultSensitiveStringCodec implements SensitiveDataCodec -{ +public class DefaultSensitiveStringCodec implements SensitiveDataCodec { + private byte[] internalKey = "clusterpassword".getBytes(); - public String decode(Object secret) throws NoSuchPaddingException, - NoSuchAlgorithmException, - InvalidKeyException, - BadPaddingException, - IllegalBlockSizeException - { + public String decode(Object secret) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { SecretKeySpec key = new SecretKeySpec(internalKey, "Blowfish"); - BigInteger n = new BigInteger((String)secret, 16); + BigInteger n = new BigInteger((String) secret, 16); byte[] encoding = n.toByteArray(); // JBAS-3457: fix leading zeros - if (encoding.length % 8 != 0) - { + if (encoding.length % 8 != 0) { int length = encoding.length; int newLength = ((length / 8) + 1) * 8; int pad = newLength - length; // number of leading zeros byte[] old = encoding; encoding = new byte[newLength]; - for (int i = old.length - 1; i >= 0; i--) - { + for (int i = old.length - 1; i >= 0; i--) { encoding[i + pad] = old[i]; } } @@ -74,12 +67,7 @@ public class DefaultSensitiveStringCodec implements SensitiveDataCodec return new String(decode); } - public Object encode(String secret) throws NoSuchPaddingException, - NoSuchAlgorithmException, - InvalidKeyException, - BadPaddingException, - IllegalBlockSizeException - { + public Object encode(String secret) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { SecretKeySpec key = new SecretKeySpec(internalKey, "Blowfish"); Cipher cipher = Cipher.getInstance("Blowfish"); @@ -89,24 +77,21 @@ public class DefaultSensitiveStringCodec implements SensitiveDataCodec return n.toString(16); } - public void init(Map params) - { + public void init(Map params) { String key = params.get("key"); - if (key != null) - { + if (key != null) { updateKey(key); } } /** * This main class is as documented on configuration-index.md, where the user can mask the password here. * + * * @param args * @throws Exception */ - public static void main(String[] args) throws Exception - { - if (args.length != 1) - { + public static void main(String[] args) throws Exception { + if (args.length != 1) { System.err.println("Use: java -cp org.apache.activemq.artemis.utils.DefaultSensitiveStringCodec password-to-encode"); System.err.println("Error: no password on the args"); System.exit(-1); @@ -116,10 +101,8 @@ public class DefaultSensitiveStringCodec implements SensitiveDataCodec System.out.println("Encoded password (without quotes): \"" + encode + "\""); } - private void updateKey(String key) - { + private void updateKey(String key) { this.internalKey = key.getBytes(); } - } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/FactoryFinder.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/FactoryFinder.java index b26a71e35b..5f4f2a8442 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/FactoryFinder.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/FactoryFinder.java @@ -23,8 +23,8 @@ import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -public class FactoryFinder -{ +public class FactoryFinder { + /** * The strategy that the FactoryFinder uses to find load and instantiate Objects * can be changed out by calling the setObjectFactory method with a custom implementation of ObjectFactory. @@ -33,15 +33,15 @@ public class FactoryFinder * environment where service discovery needs to be done via the container system. For example, * in an OSGi scenario. */ - public interface ObjectFactory - { + public interface ObjectFactory { + /** * @param path the full service path + * @return Object * @throws IllegalAccessException illegal access * @throws InstantiationException on instantiation error - * @throws IOException On IO Error + * @throws IOException On IO Error * @throws ClassNotFoundException On class not found error - * @return Object */ Object create(String path) throws IllegalAccessException, InstantiationException, IOException, ClassNotFoundException; @@ -50,85 +50,69 @@ public class FactoryFinder /** * The default implementation of Object factory which works well in standalone applications. */ - protected static class StandaloneObjectFactory implements ObjectFactory - { + protected static class StandaloneObjectFactory implements ObjectFactory { + final ConcurrentMap classMap = new ConcurrentHashMap(); - public Object create(final String path) throws InstantiationException, IllegalAccessException, ClassNotFoundException, IOException - { + public Object create(final String path) throws InstantiationException, IllegalAccessException, ClassNotFoundException, IOException { Class clazz = classMap.get(path); - if (clazz == null) - { + if (clazz == null) { clazz = loadClass(loadProperties(path)); classMap.put(path, clazz); } return clazz.newInstance(); } - static Class loadClass(Properties properties) throws ClassNotFoundException, IOException - { + static Class loadClass(Properties properties) throws ClassNotFoundException, IOException { String className = properties.getProperty("class"); - if (className == null) - { + if (className == null) { throw new IOException("Expected property is missing: class"); } Class clazz = null; ClassLoader loader = Thread.currentThread().getContextClassLoader(); - if (loader != null) - { - try - { + if (loader != null) { + try { clazz = loader.loadClass(className); } - catch (ClassNotFoundException e) - { + catch (ClassNotFoundException e) { // ignore } } - if (clazz == null) - { + if (clazz == null) { clazz = FactoryFinder.class.getClassLoader().loadClass(className); } return clazz; } - public Properties loadProperties(String uri) throws IOException - { + public Properties loadProperties(String uri) throws IOException { // lets try the thread context class loader first ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - if (classLoader == null) - { + if (classLoader == null) { classLoader = StandaloneObjectFactory.class.getClassLoader(); } InputStream in = classLoader.getResourceAsStream(uri); - if (in == null) - { + if (in == null) { in = FactoryFinder.class.getClassLoader().getResourceAsStream(uri); - if (in == null) - { + if (in == null) { throw new IOException("Could not find factory class for resource: " + uri); } } // lets load the file BufferedInputStream reader = null; - try - { + try { reader = new BufferedInputStream(in); Properties properties = new Properties(); properties.load(reader); return properties; } - finally - { - try - { + finally { + try { reader.close(); } - catch (Exception e) - { + catch (Exception e) { } } } @@ -139,13 +123,11 @@ public class FactoryFinder // ================================================================ private static ObjectFactory objectFactory = new StandaloneObjectFactory(); - public static ObjectFactory getObjectFactory() - { + public static ObjectFactory getObjectFactory() { return objectFactory; } - public static void setObjectFactory(ObjectFactory objectFactory) - { + public static void setObjectFactory(ObjectFactory objectFactory) { FactoryFinder.objectFactory = objectFactory; } @@ -154,8 +136,7 @@ public class FactoryFinder // ================================================================ private final String path; - public FactoryFinder(String path) - { + public FactoryFinder(String path) { this.path = path; } @@ -167,11 +148,10 @@ public class FactoryFinder * @return a newly created instance * @throws IllegalAccessException On illegal access * @throws InstantiationException On can not instantiate exception - * @throws IOException On IOException + * @throws IOException On IOException * @throws ClassNotFoundException When class not on class path */ - public Object newInstance(String key) throws IllegalAccessException, InstantiationException, IOException, ClassNotFoundException - { + public Object newInstance(String key) throws IllegalAccessException, InstantiationException, IOException, ClassNotFoundException { return objectFactory.create(path + key); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/PasswordMaskingUtil.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/PasswordMaskingUtil.java index 7ea3e0fef1..b6f5598820 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/PasswordMaskingUtil.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/PasswordMaskingUtil.java @@ -25,8 +25,8 @@ import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.api.core.ActiveMQExceptionType; import org.apache.activemq.artemis.logs.ActiveMQUtilBundle; -public class PasswordMaskingUtil -{ +public class PasswordMaskingUtil { + /* * Loading the codec class. * @@ -36,8 +36,7 @@ public class PasswordMaskingUtil * * Where only is required. key/value pairs are optional */ - public static SensitiveDataCodec getCodec(String codecDesc) throws ActiveMQException - { + public static SensitiveDataCodec getCodec(String codecDesc) throws ActiveMQException { SensitiveDataCodec codecInstance = null; // semi colons @@ -49,29 +48,23 @@ public class PasswordMaskingUtil final String codecClassName = parts[0]; // load class - codecInstance = AccessController.doPrivileged(new PrivilegedAction>() - { - public SensitiveDataCodec run() - { + codecInstance = AccessController.doPrivileged(new PrivilegedAction>() { + public SensitiveDataCodec run() { ClassLoader loader = Thread.currentThread().getContextClassLoader(); - try - { + try { Class clazz = loader.loadClass(codecClassName); - return (SensitiveDataCodec)clazz.newInstance(); + return (SensitiveDataCodec) clazz.newInstance(); } - catch (Exception e) - { + catch (Exception e) { throw ActiveMQUtilBundle.BUNDLE.errorCreatingCodec(e, codecClassName); } } }); - if (parts.length > 1) - { + if (parts.length > 1) { Map props = new HashMap(); - for (int i = 1; i < parts.length; i++) - { + for (int i = 1; i < parts.length; i++) { String[] keyVal = parts[i].split("="); if (keyVal.length != 2) throw ActiveMQUtilBundle.BUNDLE.invalidProperty(parts[i]); @@ -83,8 +76,7 @@ public class PasswordMaskingUtil return codecInstance; } - public static SensitiveDataCodec getDefaultCodec() - { + public static SensitiveDataCodec getDefaultCodec() { return new DefaultSensitiveStringCodec(); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ReferenceCounter.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ReferenceCounter.java index 4261ca799d..2f46fb1b94 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ReferenceCounter.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ReferenceCounter.java @@ -16,8 +16,8 @@ */ package org.apache.activemq.artemis.utils; -public interface ReferenceCounter -{ +public interface ReferenceCounter { + int increment(); int decrement(); diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ReferenceCounterUtil.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ReferenceCounterUtil.java index 71106b6176..9507cb8860 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ReferenceCounterUtil.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ReferenceCounterUtil.java @@ -19,45 +19,39 @@ package org.apache.activemq.artemis.utils; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicInteger; -public class ReferenceCounterUtil implements ReferenceCounter -{ +public class ReferenceCounterUtil implements ReferenceCounter { + private final Runnable runnable; - /** If executor is null the runnable will be called within the same thread, otherwise the executor will be used */ + /** + * If executor is null the runnable will be called within the same thread, otherwise the executor will be used + */ private final Executor executor; private final AtomicInteger uses = new AtomicInteger(0); - - public ReferenceCounterUtil(Runnable runnable) - { + public ReferenceCounterUtil(Runnable runnable) { this(runnable, null); } - public ReferenceCounterUtil(Runnable runnable, Executor executor) - { + public ReferenceCounterUtil(Runnable runnable, Executor executor) { this.runnable = runnable; this.executor = executor; } @Override - public int increment() - { + public int increment() { return uses.incrementAndGet(); } @Override - public int decrement() - { + public int decrement() { int value = uses.decrementAndGet(); - if (value == 0) - { - if (executor != null) - { + if (value == 0) { + if (executor != null) { executor.execute(runnable); } - else - { + else { runnable.run(); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ReusableLatch.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ReusableLatch.java index 1ec85f44ab..4f04f22930 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ReusableLatch.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ReusableLatch.java @@ -20,7 +20,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.AbstractQueuedSynchronizer; /** - * *

This class will use the framework provided to by AbstractQueuedSynchronizer.

*

AbstractQueuedSynchronizer is the framework for any sort of concurrent synchronization, such as Semaphores, events, etc, based on AtomicIntegers.

* @@ -33,70 +32,59 @@ import java.util.concurrent.locks.AbstractQueuedSynchronizer; *

Note: This latch is reusable. Once it reaches zero, you can call up again, and reuse it on further waits.

* *

For example: prepareTransaction will wait for the current completions, and further adds will be called on the latch. Later on when commit is called you can reuse the same latch.

- * */ -public class ReusableLatch -{ +public class ReusableLatch { + /** * Look at the doc and examples provided by AbstractQueuedSynchronizer for more information - * @see AbstractQueuedSynchronizer*/ + * + * @see AbstractQueuedSynchronizer + */ @SuppressWarnings("serial") - private static class CountSync extends AbstractQueuedSynchronizer - { - public CountSync(int count) - { + private static class CountSync extends AbstractQueuedSynchronizer { + + public CountSync(int count) { setState(count); } - public int getCount() - { + public int getCount() { return getState(); } - public void setCount(final int count) - { + public void setCount(final int count) { setState(count); } @Override - public int tryAcquireShared(final int numberOfAqcquires) - { + public int tryAcquireShared(final int numberOfAqcquires) { return getState() == 0 ? 1 : -1; } - public void add() - { - for (;;) - { + public void add() { + for (;;) { int actualState = getState(); int newState = actualState + 1; - if (compareAndSetState(actualState, newState)) - { + if (compareAndSetState(actualState, newState)) { return; } } } @Override - public boolean tryReleaseShared(final int numberOfReleases) - { - for (;;) - { + public boolean tryReleaseShared(final int numberOfReleases) { + for (;;) { int actualState = getState(); - if (actualState == 0) - { + if (actualState == 0) { return true; } int newState = actualState - numberOfReleases; - if (newState < 0) - { + if (newState < 0) { newState = 0; } - if (compareAndSetState(actualState, newState)) - { + if (compareAndSetState(actualState, newState)) { return newState == 0; } } @@ -105,54 +93,43 @@ public class ReusableLatch private final CountSync control; - public ReusableLatch() - { + public ReusableLatch() { this(0); } - public ReusableLatch(final int count) - { + public ReusableLatch(final int count) { control = new CountSync(count); } - public int getCount() - { + public int getCount() { return control.getCount(); } - public void setCount(final int count) - { + public void setCount(final int count) { control.setCount(count); } - public void countUp() - { + public void countUp() { control.add(); } - public void countDown() - { + public void countDown() { control.releaseShared(1); } - - public void countDown(final int count) - { + public void countDown(final int count) { control.releaseShared(count); } - public void await() throws InterruptedException - { + public void await() throws InterruptedException { control.acquireSharedInterruptibly(1); } - public boolean await(final long milliseconds) throws InterruptedException - { + public boolean await(final long milliseconds) throws InterruptedException { return control.tryAcquireSharedNanos(1, TimeUnit.MILLISECONDS.toNanos(milliseconds)); } - public boolean await(final long timeWait, TimeUnit timeUnit) throws InterruptedException - { + public boolean await(final long timeWait, TimeUnit timeUnit) throws InterruptedException { return control.tryAcquireSharedNanos(1, timeUnit.toNanos(timeWait)); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/SensitiveDataCodec.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/SensitiveDataCodec.java index a47bf85823..b1bfd2b74b 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/SensitiveDataCodec.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/SensitiveDataCodec.java @@ -25,8 +25,8 @@ import java.util.Map; * * It takes in a mask value and decode it. */ -public interface SensitiveDataCodec -{ +public interface SensitiveDataCodec { + T decode(Object mask) throws Exception; void init(Map params); diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/TypedProperties.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/TypedProperties.java index 645c3efb95..432e46ff2c 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/TypedProperties.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/TypedProperties.java @@ -49,8 +49,7 @@ import static org.apache.activemq.artemis.utils.DataConstants.STRING; *

* TODO - should have typed property getters and do conversions herein */ -public final class TypedProperties -{ +public final class TypedProperties { private static final SimpleString AMQ_PROPNAME = new SimpleString("_AMQ_"); @@ -60,12 +59,10 @@ public final class TypedProperties private boolean internalProperties; - public TypedProperties() - { + public TypedProperties() { } - public int getMemoryOffset() - { + public int getMemoryOffset() { // The estimate is basically the encode size + 2 object references for each entry in the map // Note we don't include the attributes or anything else since they already included in the memory estimate // of the ServerMessage @@ -73,403 +70,316 @@ public final class TypedProperties return properties == null ? 0 : size + 2 * DataConstants.SIZE_INT * properties.size(); } - public TypedProperties(final TypedProperties other) - { + public TypedProperties(final TypedProperties other) { properties = other.properties == null ? null : new HashMap(other.properties); size = other.size; } - public boolean hasInternalProperties() - { + public boolean hasInternalProperties() { return internalProperties; } - public void putBooleanProperty(final SimpleString key, final boolean value) - { + public void putBooleanProperty(final SimpleString key, final boolean value) { checkCreateProperties(); doPutValue(key, new BooleanValue(value)); } - public void putByteProperty(final SimpleString key, final byte value) - { + public void putByteProperty(final SimpleString key, final byte value) { checkCreateProperties(); doPutValue(key, new ByteValue(value)); } - public void putBytesProperty(final SimpleString key, final byte[] value) - { + public void putBytesProperty(final SimpleString key, final byte[] value) { checkCreateProperties(); doPutValue(key, value == null ? new NullValue() : new BytesValue(value)); } - public void putShortProperty(final SimpleString key, final short value) - { + public void putShortProperty(final SimpleString key, final short value) { checkCreateProperties(); doPutValue(key, new ShortValue(value)); } - public void putIntProperty(final SimpleString key, final int value) - { + public void putIntProperty(final SimpleString key, final int value) { checkCreateProperties(); doPutValue(key, new IntValue(value)); } - public void putLongProperty(final SimpleString key, final long value) - { + public void putLongProperty(final SimpleString key, final long value) { checkCreateProperties(); doPutValue(key, new LongValue(value)); } - public void putFloatProperty(final SimpleString key, final float value) - { + public void putFloatProperty(final SimpleString key, final float value) { checkCreateProperties(); doPutValue(key, new FloatValue(value)); } - public void putDoubleProperty(final SimpleString key, final double value) - { + public void putDoubleProperty(final SimpleString key, final double value) { checkCreateProperties(); doPutValue(key, new DoubleValue(value)); } - public void putSimpleStringProperty(final SimpleString key, final SimpleString value) - { + public void putSimpleStringProperty(final SimpleString key, final SimpleString value) { checkCreateProperties(); doPutValue(key, value == null ? new NullValue() : new StringValue(value)); } - public void putNullValue(final SimpleString key) - { + public void putNullValue(final SimpleString key) { checkCreateProperties(); doPutValue(key, new NullValue()); } - public void putCharProperty(final SimpleString key, final char value) - { + public void putCharProperty(final SimpleString key, final char value) { checkCreateProperties(); doPutValue(key, new CharValue(value)); } - public void putTypedProperties(final TypedProperties otherProps) - { - if (otherProps == null || otherProps.properties == null) - { + public void putTypedProperties(final TypedProperties otherProps) { + if (otherProps == null || otherProps.properties == null) { return; } checkCreateProperties(); Set> otherEntries = otherProps.properties.entrySet(); - for (Entry otherEntry : otherEntries) - { + for (Entry otherEntry : otherEntries) { doPutValue(otherEntry.getKey(), otherEntry.getValue()); } } - public Object getProperty(final SimpleString key) - { + public Object getProperty(final SimpleString key) { return doGetProperty(key); } - public Boolean getBooleanProperty(final SimpleString key) throws ActiveMQPropertyConversionException - { + public Boolean getBooleanProperty(final SimpleString key) throws ActiveMQPropertyConversionException { Object value = doGetProperty(key); - if (value == null) - { + if (value == null) { return Boolean.valueOf(null); } - else if (value instanceof Boolean) - { + else if (value instanceof Boolean) { return (Boolean) value; } - else if (value instanceof SimpleString) - { + else if (value instanceof SimpleString) { return Boolean.valueOf(((SimpleString) value).toString()); } - else - { + else { throw new ActiveMQPropertyConversionException("Invalid conversion"); } } - public Byte getByteProperty(final SimpleString key) throws ActiveMQPropertyConversionException - { + public Byte getByteProperty(final SimpleString key) throws ActiveMQPropertyConversionException { Object value = doGetProperty(key); - if (value == null) - { + if (value == null) { return Byte.valueOf(null); } - else if (value instanceof Byte) - { + else if (value instanceof Byte) { return (Byte) value; } - else if (value instanceof SimpleString) - { + else if (value instanceof SimpleString) { return Byte.parseByte(((SimpleString) value).toString()); } - else - { + else { throw new ActiveMQPropertyConversionException("Invalid conversion"); } } - public Character getCharProperty(final SimpleString key) throws ActiveMQPropertyConversionException - { + public Character getCharProperty(final SimpleString key) throws ActiveMQPropertyConversionException { Object value = doGetProperty(key); - if (value == null) - { + if (value == null) { throw new NullPointerException("Invalid conversion"); } - if (value instanceof Character) - { + if (value instanceof Character) { return ((Character) value); } - else - { + else { throw new ActiveMQPropertyConversionException("Invalid conversion"); } } - public byte[] getBytesProperty(final SimpleString key) throws ActiveMQPropertyConversionException - { + public byte[] getBytesProperty(final SimpleString key) throws ActiveMQPropertyConversionException { Object value = doGetProperty(key); - if (value == null) - { + if (value == null) { return null; } - else if (value instanceof byte[]) - { + else if (value instanceof byte[]) { return (byte[]) value; } - else - { + else { throw new ActiveMQPropertyConversionException("Invalid conversion"); } } - public Double getDoubleProperty(final SimpleString key) throws ActiveMQPropertyConversionException - { + public Double getDoubleProperty(final SimpleString key) throws ActiveMQPropertyConversionException { Object value = doGetProperty(key); - if (value == null) - { + if (value == null) { return Double.valueOf(null); } - else if (value instanceof Float) - { + else if (value instanceof Float) { return ((Float) value).doubleValue(); } - else if (value instanceof Double) - { + else if (value instanceof Double) { return (Double) value; } - else if (value instanceof SimpleString) - { + else if (value instanceof SimpleString) { return Double.parseDouble(((SimpleString) value).toString()); } - else - { + else { throw new ActiveMQPropertyConversionException("Invalid conversion"); } } - public Integer getIntProperty(final SimpleString key) throws ActiveMQPropertyConversionException - { + public Integer getIntProperty(final SimpleString key) throws ActiveMQPropertyConversionException { Object value = doGetProperty(key); - if (value == null) - { + if (value == null) { return Integer.valueOf(null); } - else if (value instanceof Integer) - { + else if (value instanceof Integer) { return (Integer) value; } - else if (value instanceof Byte) - { + else if (value instanceof Byte) { return ((Byte) value).intValue(); } - else if (value instanceof Short) - { + else if (value instanceof Short) { return ((Short) value).intValue(); } - else if (value instanceof SimpleString) - { + else if (value instanceof SimpleString) { return Integer.parseInt(((SimpleString) value).toString()); } - else - { + else { throw new ActiveMQPropertyConversionException("Invalid conversion"); } } - public Long getLongProperty(final SimpleString key) throws ActiveMQPropertyConversionException - { + public Long getLongProperty(final SimpleString key) throws ActiveMQPropertyConversionException { Object value = doGetProperty(key); - if (value == null) - { + if (value == null) { return Long.valueOf(null); } - else if (value instanceof Long) - { + else if (value instanceof Long) { return (Long) value; } - else if (value instanceof Byte) - { + else if (value instanceof Byte) { return ((Byte) value).longValue(); } - else if (value instanceof Short) - { + else if (value instanceof Short) { return ((Short) value).longValue(); } - else if (value instanceof Integer) - { + else if (value instanceof Integer) { return ((Integer) value).longValue(); } - else if (value instanceof SimpleString) - { + else if (value instanceof SimpleString) { return Long.parseLong(((SimpleString) value).toString()); } - else - { + else { throw new ActiveMQPropertyConversionException("Invalid conversion"); } } - public Short getShortProperty(final SimpleString key) throws ActiveMQPropertyConversionException - { + public Short getShortProperty(final SimpleString key) throws ActiveMQPropertyConversionException { Object value = doGetProperty(key); - if (value == null) - { + if (value == null) { return Short.valueOf(null); } - else if (value instanceof Byte) - { + else if (value instanceof Byte) { return ((Byte) value).shortValue(); } - else if (value instanceof Short) - { + else if (value instanceof Short) { return (Short) value; } - else if (value instanceof SimpleString) - { + else if (value instanceof SimpleString) { return Short.parseShort(((SimpleString) value).toString()); } - else - { + else { throw new ActiveMQPropertyConversionException("Invalid Conversion."); } } - public Float getFloatProperty(final SimpleString key) throws ActiveMQPropertyConversionException - { + public Float getFloatProperty(final SimpleString key) throws ActiveMQPropertyConversionException { Object value = doGetProperty(key); if (value == null) return Float.valueOf(null); - if (value instanceof Float) - { + if (value instanceof Float) { return ((Float) value); } - if (value instanceof SimpleString) - { + if (value instanceof SimpleString) { return Float.parseFloat(((SimpleString) value).toString()); } throw new ActiveMQPropertyConversionException("Invalid conversion: " + key); } - public SimpleString getSimpleStringProperty(final SimpleString key) throws ActiveMQPropertyConversionException - { + public SimpleString getSimpleStringProperty(final SimpleString key) throws ActiveMQPropertyConversionException { Object value = doGetProperty(key); - if (value == null) - { + if (value == null) { return null; } - if (value instanceof SimpleString) - { + if (value instanceof SimpleString) { return (SimpleString) value; } - else if (value instanceof Boolean) - { + else if (value instanceof Boolean) { return new SimpleString(value.toString()); } - else if (value instanceof Character) - { + else if (value instanceof Character) { return new SimpleString(value.toString()); } - else if (value instanceof Byte) - { + else if (value instanceof Byte) { return new SimpleString(value.toString()); } - else if (value instanceof Short) - { + else if (value instanceof Short) { return new SimpleString(value.toString()); } - else if (value instanceof Integer) - { + else if (value instanceof Integer) { return new SimpleString(value.toString()); } - else if (value instanceof Long) - { + else if (value instanceof Long) { return new SimpleString(value.toString()); } - else if (value instanceof Float) - { + else if (value instanceof Float) { return new SimpleString(value.toString()); } - else if (value instanceof Double) - { + else if (value instanceof Double) { return new SimpleString(value.toString()); } throw new ActiveMQPropertyConversionException("Invalid conversion"); } - public Object removeProperty(final SimpleString key) - { + public Object removeProperty(final SimpleString key) { return doRemoveProperty(key); } - public boolean containsProperty(final SimpleString key) - { - if (size == 0) - { + public boolean containsProperty(final SimpleString key) { + if (size == 0) { return false; } - else - { + else { return properties.containsKey(key); } } - public Set getPropertyNames() - { - if (size == 0) - { + public Set getPropertyNames() { + if (size == 0) { return Collections.emptySet(); } - else - { + else { return properties.keySet(); } } - public synchronized void decode(final ActiveMQBuffer buffer) - { + public synchronized void decode(final ActiveMQBuffer buffer) { byte b = buffer.readByte(); - if (b == DataConstants.NULL) - { + if (b == DataConstants.NULL) { properties = null; } - else - { + else { int numHeaders = buffer.readInt(); properties = new HashMap(numHeaders); size = 0; - for (int i = 0; i < numHeaders; i++) - { + for (int i = 0; i < numHeaders; i++) { int len = buffer.readInt(); byte[] data = new byte[len]; buffer.readBytes(data); @@ -479,76 +389,63 @@ public final class TypedProperties PropertyValue val; - switch (type) - { - case NULL: - { + switch (type) { + case NULL: { val = new NullValue(); doPutValue(key, val); break; } - case CHAR: - { + case CHAR: { val = new CharValue(buffer); doPutValue(key, val); break; } - case BOOLEAN: - { + case BOOLEAN: { val = new BooleanValue(buffer); doPutValue(key, val); break; } - case BYTE: - { + case BYTE: { val = new ByteValue(buffer); doPutValue(key, val); break; } - case BYTES: - { + case BYTES: { val = new BytesValue(buffer); doPutValue(key, val); break; } - case SHORT: - { + case SHORT: { val = new ShortValue(buffer); doPutValue(key, val); break; } - case INT: - { + case INT: { val = new IntValue(buffer); doPutValue(key, val); break; } - case LONG: - { + case LONG: { val = new LongValue(buffer); doPutValue(key, val); break; } - case FLOAT: - { + case FLOAT: { val = new FloatValue(buffer); doPutValue(key, val); break; } - case DOUBLE: - { + case DOUBLE: { val = new DoubleValue(buffer); doPutValue(key, val); break; } - case STRING: - { + case STRING: { val = new StringValue(buffer); doPutValue(key, val); break; } - default: - { + default: { throw ActiveMQUtilBundle.BUNDLE.invalidType(type); } } @@ -556,20 +453,16 @@ public final class TypedProperties } } - public synchronized void encode(final ActiveMQBuffer buffer) - { - if (properties == null) - { + public synchronized void encode(final ActiveMQBuffer buffer) { + if (properties == null) { buffer.writeByte(DataConstants.NULL); } - else - { + else { buffer.writeByte(DataConstants.NOT_NULL); buffer.writeInt(properties.size()); - for (Map.Entry entry : properties.entrySet()) - { + for (Map.Entry entry : properties.entrySet()) { SimpleString s = entry.getKey(); byte[] data = s.getData(); buffer.writeInt(data.length); @@ -580,39 +473,30 @@ public final class TypedProperties } } - public int getEncodeSize() - { - if (properties == null) - { + public int getEncodeSize() { + if (properties == null) { return DataConstants.SIZE_BYTE; } - else - { + else { return DataConstants.SIZE_BYTE + DataConstants.SIZE_INT + size; } } - public void clear() - { - if (properties != null) - { + public void clear() { + if (properties != null) { properties.clear(); } } @Override - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder("TypedProperties["); - - if (properties != null) - { + if (properties != null) { Iterator> iter = properties.entrySet().iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { Entry iterItem = iter.next(); sb.append(iterItem.getKey() + "="); @@ -621,46 +505,35 @@ public final class TypedProperties // The second is to convert the PropertyValue into the actual value Object theValue = iterItem.getValue().getValue(); - - if (theValue == null) - { + if (theValue == null) { sb.append("NULL-value"); } - else if (theValue instanceof byte[]) - { - sb.append("[" + ByteUtil.maxString(ByteUtil.bytesToHex((byte [])theValue, 2), 150) + ")"); + else if (theValue instanceof byte[]) { + sb.append("[" + ByteUtil.maxString(ByteUtil.bytesToHex((byte[]) theValue, 2), 150) + ")"); - if (iterItem.getKey().toString().startsWith("_AMQ_ROUTE_TO")) - { + if (iterItem.getKey().toString().startsWith("_AMQ_ROUTE_TO")) { sb.append(",bytesAsLongs("); - try - { + try { ByteBuffer buff = ByteBuffer.wrap((byte[]) theValue); - while (buff.hasRemaining()) - { + while (buff.hasRemaining()) { long bindingID = buff.getLong(); sb.append(bindingID); - if (buff.hasRemaining()) - { + if (buff.hasRemaining()) { sb.append(","); } } } - catch (Throwable e) - { + catch (Throwable e) { sb.append("error-converting-longs=" + e.getMessage()); } sb.append("]"); } } - else - { + else { sb.append(theValue.toString()); } - - if (iter.hasNext()) - { + if (iter.hasNext()) { sb.append(","); } } @@ -671,76 +544,62 @@ public final class TypedProperties // Private ------------------------------------------------------------------------------------ - private void checkCreateProperties() - { - if (properties == null) - { + private void checkCreateProperties() { + if (properties == null) { properties = new HashMap(); } } - private synchronized void doPutValue(final SimpleString key, final PropertyValue value) - { - if (key.startsWith(AMQ_PROPNAME)) - { + private synchronized void doPutValue(final SimpleString key, final PropertyValue value) { + if (key.startsWith(AMQ_PROPNAME)) { internalProperties = true; } PropertyValue oldValue = properties.put(key, value); - if (oldValue != null) - { + if (oldValue != null) { size += value.encodeSize() - oldValue.encodeSize(); } - else - { + else { size += SimpleString.sizeofString(key) + value.encodeSize(); } } - private synchronized Object doRemoveProperty(final SimpleString key) - { - if (properties == null) - { + private synchronized Object doRemoveProperty(final SimpleString key) { + if (properties == null) { return null; } PropertyValue val = properties.remove(key); - if (val == null) - { + if (val == null) { return null; } - else - { + else { size -= SimpleString.sizeofString(key) + val.encodeSize(); return val.getValue(); } } - private synchronized Object doGetProperty(final Object key) - { - if (size == 0) - { + private synchronized Object doGetProperty(final Object key) { + if (size == 0) { return null; } PropertyValue val = properties.get(key); - if (val == null) - { + if (val == null) { return null; } - else - { + else { return val.getValue(); } } // Inner classes ------------------------------------------------------------------------------ - private abstract static class PropertyValue - { + private abstract static class PropertyValue { + abstract Object getValue(); abstract void write(ActiveMQBuffer buffer); @@ -748,401 +607,341 @@ public final class TypedProperties abstract int encodeSize(); @Override - public String toString() - { + public String toString() { return "" + getValue(); } } - private static final class NullValue extends PropertyValue - { - public NullValue() - { + private static final class NullValue extends PropertyValue { + + public NullValue() { } @Override - public Object getValue() - { + public Object getValue() { return null; } @Override - public void write(final ActiveMQBuffer buffer) - { + public void write(final ActiveMQBuffer buffer) { buffer.writeByte(DataConstants.NULL); } @Override - public int encodeSize() - { + public int encodeSize() { return DataConstants.SIZE_BYTE; } } - private static final class BooleanValue extends PropertyValue - { + private static final class BooleanValue extends PropertyValue { + final boolean val; - public BooleanValue(final boolean val) - { + public BooleanValue(final boolean val) { this.val = val; } - public BooleanValue(final ActiveMQBuffer buffer) - { + public BooleanValue(final ActiveMQBuffer buffer) { val = buffer.readBoolean(); } @Override - public Object getValue() - { + public Object getValue() { return val; } @Override - public void write(final ActiveMQBuffer buffer) - { + public void write(final ActiveMQBuffer buffer) { buffer.writeByte(DataConstants.BOOLEAN); buffer.writeBoolean(val); } @Override - public int encodeSize() - { + public int encodeSize() { return DataConstants.SIZE_BYTE + DataConstants.SIZE_BOOLEAN; } } - private static final class ByteValue extends PropertyValue - { + private static final class ByteValue extends PropertyValue { + final byte val; - public ByteValue(final byte val) - { + public ByteValue(final byte val) { this.val = val; } - public ByteValue(final ActiveMQBuffer buffer) - { + public ByteValue(final ActiveMQBuffer buffer) { val = buffer.readByte(); } @Override - public Object getValue() - { + public Object getValue() { return val; } @Override - public void write(final ActiveMQBuffer buffer) - { + public void write(final ActiveMQBuffer buffer) { buffer.writeByte(DataConstants.BYTE); buffer.writeByte(val); } @Override - public int encodeSize() - { + public int encodeSize() { return DataConstants.SIZE_BYTE + DataConstants.SIZE_BYTE; } } - private static final class BytesValue extends PropertyValue - { + private static final class BytesValue extends PropertyValue { + final byte[] val; - public BytesValue(final byte[] val) - { + public BytesValue(final byte[] val) { this.val = val; } - public BytesValue(final ActiveMQBuffer buffer) - { + public BytesValue(final ActiveMQBuffer buffer) { int len = buffer.readInt(); val = new byte[len]; buffer.readBytes(val); } @Override - public Object getValue() - { + public Object getValue() { return val; } @Override - public void write(final ActiveMQBuffer buffer) - { + public void write(final ActiveMQBuffer buffer) { buffer.writeByte(DataConstants.BYTES); buffer.writeInt(val.length); buffer.writeBytes(val); } @Override - public int encodeSize() - { + public int encodeSize() { return DataConstants.SIZE_BYTE + DataConstants.SIZE_INT + val.length; } } - private static final class ShortValue extends PropertyValue - { + private static final class ShortValue extends PropertyValue { + final short val; - public ShortValue(final short val) - { + public ShortValue(final short val) { this.val = val; } - public ShortValue(final ActiveMQBuffer buffer) - { + public ShortValue(final ActiveMQBuffer buffer) { val = buffer.readShort(); } @Override - public Object getValue() - { + public Object getValue() { return val; } @Override - public void write(final ActiveMQBuffer buffer) - { + public void write(final ActiveMQBuffer buffer) { buffer.writeByte(DataConstants.SHORT); buffer.writeShort(val); } @Override - public int encodeSize() - { + public int encodeSize() { return DataConstants.SIZE_BYTE + DataConstants.SIZE_SHORT; } } - private static final class IntValue extends PropertyValue - { + private static final class IntValue extends PropertyValue { + final int val; - public IntValue(final int val) - { + public IntValue(final int val) { this.val = val; } - public IntValue(final ActiveMQBuffer buffer) - { + public IntValue(final ActiveMQBuffer buffer) { val = buffer.readInt(); } @Override - public Object getValue() - { + public Object getValue() { return val; } @Override - public void write(final ActiveMQBuffer buffer) - { + public void write(final ActiveMQBuffer buffer) { buffer.writeByte(DataConstants.INT); buffer.writeInt(val); } @Override - public int encodeSize() - { + public int encodeSize() { return DataConstants.SIZE_BYTE + DataConstants.SIZE_INT; } } - private static final class LongValue extends PropertyValue - { + private static final class LongValue extends PropertyValue { + final long val; - public LongValue(final long val) - { + public LongValue(final long val) { this.val = val; } - public LongValue(final ActiveMQBuffer buffer) - { + public LongValue(final ActiveMQBuffer buffer) { val = buffer.readLong(); } @Override - public Object getValue() - { + public Object getValue() { return val; } @Override - public void write(final ActiveMQBuffer buffer) - { + public void write(final ActiveMQBuffer buffer) { buffer.writeByte(DataConstants.LONG); buffer.writeLong(val); } @Override - public int encodeSize() - { + public int encodeSize() { return DataConstants.SIZE_BYTE + DataConstants.SIZE_LONG; } } - private static final class FloatValue extends PropertyValue - { + private static final class FloatValue extends PropertyValue { + final float val; - public FloatValue(final float val) - { + public FloatValue(final float val) { this.val = val; } - public FloatValue(final ActiveMQBuffer buffer) - { + public FloatValue(final ActiveMQBuffer buffer) { val = Float.intBitsToFloat(buffer.readInt()); } @Override - public Object getValue() - { + public Object getValue() { return val; } @Override - public void write(final ActiveMQBuffer buffer) - { + public void write(final ActiveMQBuffer buffer) { buffer.writeByte(DataConstants.FLOAT); buffer.writeInt(Float.floatToIntBits(val)); } @Override - public int encodeSize() - { + public int encodeSize() { return DataConstants.SIZE_BYTE + DataConstants.SIZE_FLOAT; } } - private static final class DoubleValue extends PropertyValue - { + private static final class DoubleValue extends PropertyValue { + final double val; - public DoubleValue(final double val) - { + public DoubleValue(final double val) { this.val = val; } - public DoubleValue(final ActiveMQBuffer buffer) - { + public DoubleValue(final ActiveMQBuffer buffer) { val = Double.longBitsToDouble(buffer.readLong()); } @Override - public Object getValue() - { + public Object getValue() { return val; } @Override - public void write(final ActiveMQBuffer buffer) - { + public void write(final ActiveMQBuffer buffer) { buffer.writeByte(DataConstants.DOUBLE); buffer.writeLong(Double.doubleToLongBits(val)); } @Override - public int encodeSize() - { + public int encodeSize() { return DataConstants.SIZE_BYTE + DataConstants.SIZE_DOUBLE; } } - private static final class CharValue extends PropertyValue - { + private static final class CharValue extends PropertyValue { + final char val; - public CharValue(final char val) - { + public CharValue(final char val) { this.val = val; } - public CharValue(final ActiveMQBuffer buffer) - { + public CharValue(final ActiveMQBuffer buffer) { val = (char) buffer.readShort(); } @Override - public Object getValue() - { + public Object getValue() { return val; } @Override - public void write(final ActiveMQBuffer buffer) - { + public void write(final ActiveMQBuffer buffer) { buffer.writeByte(DataConstants.CHAR); buffer.writeShort((short) val); } @Override - public int encodeSize() - { + public int encodeSize() { return DataConstants.SIZE_BYTE + DataConstants.SIZE_CHAR; } } - private static final class StringValue extends PropertyValue - { + private static final class StringValue extends PropertyValue { + final SimpleString val; - public StringValue(final SimpleString val) - { + public StringValue(final SimpleString val) { this.val = val; } - public StringValue(final ActiveMQBuffer buffer) - { + public StringValue(final ActiveMQBuffer buffer) { val = buffer.readSimpleString(); } @Override - public Object getValue() - { + public Object getValue() { return val; } @Override - public void write(final ActiveMQBuffer buffer) - { + public void write(final ActiveMQBuffer buffer) { buffer.writeByte(DataConstants.STRING); buffer.writeSimpleString(val); } @Override - public int encodeSize() - { + public int encodeSize() { return DataConstants.SIZE_BYTE + SimpleString.sizeofString(val); } } - public boolean isEmpty() - { + public boolean isEmpty() { return properties.isEmpty(); } - public Map getMap() - { + public Map getMap() { Map m = new HashMap(); - for (Entry entry : properties.entrySet()) - { + for (Entry entry : properties.entrySet()) { Object val = entry.getValue().getValue(); - if (val instanceof SimpleString) - { + if (val instanceof SimpleString) { m.put(entry.getKey().toString(), ((SimpleString) val).toString()); } - else - { + else { m.put(entry.getKey().toString(), val); } } @@ -1152,62 +951,48 @@ public final class TypedProperties /** * Helper for MapMessage#setObjectProperty(String, Object) * - * @param key The SimpleString key - * @param value The Object value + * @param key The SimpleString key + * @param value The Object value * @param properties The typed properties */ - public static void setObjectProperty(final SimpleString key, final Object value, final TypedProperties properties) - { - if (value == null) - { + public static void setObjectProperty(final SimpleString key, final Object value, final TypedProperties properties) { + if (value == null) { properties.putNullValue(key); } - else if (value instanceof Boolean) - { + else if (value instanceof Boolean) { properties.putBooleanProperty(key, (Boolean) value); } - else if (value instanceof Byte) - { + else if (value instanceof Byte) { properties.putByteProperty(key, (Byte) value); } - else if (value instanceof Character) - { + else if (value instanceof Character) { properties.putCharProperty(key, (Character) value); } - else if (value instanceof Short) - { + else if (value instanceof Short) { properties.putShortProperty(key, (Short) value); } - else if (value instanceof Integer) - { + else if (value instanceof Integer) { properties.putIntProperty(key, (Integer) value); } - else if (value instanceof Long) - { + else if (value instanceof Long) { properties.putLongProperty(key, (Long) value); } - else if (value instanceof Float) - { + else if (value instanceof Float) { properties.putFloatProperty(key, (Float) value); } - else if (value instanceof Double) - { + else if (value instanceof Double) { properties.putDoubleProperty(key, (Double) value); } - else if (value instanceof String) - { + else if (value instanceof String) { properties.putSimpleStringProperty(key, new SimpleString((String) value)); } - else if (value instanceof SimpleString) - { + else if (value instanceof SimpleString) { properties.putSimpleStringProperty(key, (SimpleString) value); } - else if (value instanceof byte[]) - { + else if (value instanceof byte[]) { properties.putBytesProperty(key, (byte[]) value); } - else - { + else { throw new ActiveMQPropertyConversionException(value.getClass() + " is not a valid property type"); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/UTF8Util.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/UTF8Util.java index 9aaf1a0113..18dca846c3 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/UTF8Util.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/UTF8Util.java @@ -27,53 +27,43 @@ import org.apache.activemq.artemis.logs.ActiveMQUtilLogger; * * This class will write UTFs directly to the ByteOutput (through the MessageBuffer interface) */ -public final class UTF8Util -{ - private UTF8Util() - { +public final class UTF8Util { + + private UTF8Util() { // utility class } private static final boolean isTrace = ActiveMQUtilLogger.LOGGER.isTraceEnabled(); - private static final ThreadLocal> currenBuffer = - new ThreadLocal>(); + private static final ThreadLocal> currenBuffer = new ThreadLocal>(); - public static void saveUTF(final ActiveMQBuffer out, final String str) - { + public static void saveUTF(final ActiveMQBuffer out, final String str) { StringUtilBuffer buffer = UTF8Util.getThreadLocalBuffer(); - if (str.length() > 0xffff) - { + if (str.length() > 0xffff) { throw ActiveMQUtilBundle.BUNDLE.stringTooLong(str.length()); } final int len = UTF8Util.calculateUTFSize(str, buffer); - if (len > 0xffff) - { + if (len > 0xffff) { throw ActiveMQUtilBundle.BUNDLE.stringTooLong(len); } - out.writeShort((short)len); + out.writeShort((short) len); - if (len > buffer.byteBuffer.length) - { + if (len > buffer.byteBuffer.length) { buffer.resizeByteBuffer(len); } - if (len == (long)str.length()) - { - for (int byteLocation = 0; byteLocation < len; byteLocation++) - { - buffer.byteBuffer[byteLocation] = (byte)buffer.charBuffer[byteLocation]; + if (len == (long) str.length()) { + for (int byteLocation = 0; byteLocation < len; byteLocation++) { + buffer.byteBuffer[byteLocation] = (byte) buffer.charBuffer[byteLocation]; } out.writeBytes(buffer.byteBuffer, 0, len); } - else - { - if (UTF8Util.isTrace) - { + else { + if (UTF8Util.isTrace) { // This message is too verbose for debug, that's why we are using trace here ActiveMQUtilLogger.LOGGER.trace("Saving string with utfSize=" + len + " stringSize=" + str.length()); } @@ -82,47 +72,39 @@ public final class UTF8Util int charCount = 0; - for (int i = 0; i < stringLength; i++) - { + for (int i = 0; i < stringLength; i++) { char charAtPos = buffer.charBuffer[i]; - if (charAtPos >= 1 && charAtPos < 0x7f) - { - buffer.byteBuffer[charCount++] = (byte)charAtPos; + if (charAtPos >= 1 && charAtPos < 0x7f) { + buffer.byteBuffer[charCount++] = (byte) charAtPos; } - else if (charAtPos >= 0x800) - { - buffer.byteBuffer[charCount++] = (byte)(0xE0 | charAtPos >> 12 & 0x0F); - buffer.byteBuffer[charCount++] = (byte)(0x80 | charAtPos >> 6 & 0x3F); - buffer.byteBuffer[charCount++] = (byte)(0x80 | charAtPos >> 0 & 0x3F); + else if (charAtPos >= 0x800) { + buffer.byteBuffer[charCount++] = (byte) (0xE0 | charAtPos >> 12 & 0x0F); + buffer.byteBuffer[charCount++] = (byte) (0x80 | charAtPos >> 6 & 0x3F); + buffer.byteBuffer[charCount++] = (byte) (0x80 | charAtPos >> 0 & 0x3F); } - else - { - buffer.byteBuffer[charCount++] = (byte)(0xC0 | charAtPos >> 6 & 0x1F); - buffer.byteBuffer[charCount++] = (byte)(0x80 | charAtPos >> 0 & 0x3F); + else { + buffer.byteBuffer[charCount++] = (byte) (0xC0 | charAtPos >> 6 & 0x1F); + buffer.byteBuffer[charCount++] = (byte) (0x80 | charAtPos >> 0 & 0x3F); } } out.writeBytes(buffer.byteBuffer, 0, len); } } - public static String readUTF(final ActiveMQBuffer input) - { + public static String readUTF(final ActiveMQBuffer input) { StringUtilBuffer buffer = UTF8Util.getThreadLocalBuffer(); final int size = input.readUnsignedShort(); - if (size > buffer.byteBuffer.length) - { + if (size > buffer.byteBuffer.length) { buffer.resizeByteBuffer(size); } - if (size > buffer.charBuffer.length) - { + if (size > buffer.charBuffer.length) { buffer.resizeCharBuffer(size); } - if (UTF8Util.isTrace) - { + if (UTF8Util.isTrace) { // This message is too verbose for debug, that's why we are using trace here ActiveMQUtilLogger.LOGGER.trace("Reading string with utfSize=" + size); } @@ -133,28 +115,24 @@ public final class UTF8Util input.readBytes(buffer.byteBuffer, 0, size); - while (count < size) - { + while (count < size) { byte1 = buffer.byteBuffer[count++]; - if (byte1 > 0 && byte1 <= 0x7F) - { - buffer.charBuffer[charCount++] = (char)byte1; + if (byte1 > 0 && byte1 <= 0x7F) { + buffer.charBuffer[charCount++] = (char) byte1; } - else - { + else { int c = byte1 & 0xff; - switch (c >> 4) - { + switch (c >> 4) { case 0xc: case 0xd: byte2 = buffer.byteBuffer[count++]; - buffer.charBuffer[charCount++] = (char)((c & 0x1F) << 6 | byte2 & 0x3F); + buffer.charBuffer[charCount++] = (char) ((c & 0x1F) << 6 | byte2 & 0x3F); break; case 0xe: byte2 = buffer.byteBuffer[count++]; byte3 = buffer.byteBuffer[count++]; - buffer.charBuffer[charCount++] = (char)((c & 0x0F) << 12 | (byte2 & 0x3F) << 6 | (byte3 & 0x3F) << 0); + buffer.charBuffer[charCount++] = (char) ((c & 0x0F) << 12 | (byte2 & 0x3F) << 6 | (byte3 & 0x3F) << 0); break; default: throw new InternalError("unhandled utf8 byte " + c); @@ -166,23 +144,19 @@ public final class UTF8Util } - public static StringUtilBuffer getThreadLocalBuffer() - { + public static StringUtilBuffer getThreadLocalBuffer() { SoftReference softReference = UTF8Util.currenBuffer.get(); StringUtilBuffer value; - if (softReference == null) - { + if (softReference == null) { value = new StringUtilBuffer(); softReference = new SoftReference(value); UTF8Util.currenBuffer.set(softReference); } - else - { + else { value = softReference.get(); } - if (value == null) - { + if (value == null) { value = new StringUtilBuffer(); softReference = new SoftReference(value); UTF8Util.currenBuffer.set(softReference); @@ -191,78 +165,63 @@ public final class UTF8Util return value; } - public static void clearBuffer() - { + public static void clearBuffer() { SoftReference ref = UTF8Util.currenBuffer.get(); - if (ref.get() != null) - { + if (ref.get() != null) { ref.clear(); } } - public static int calculateUTFSize(final String str, final StringUtilBuffer stringBuffer) - { + public static int calculateUTFSize(final String str, final StringUtilBuffer stringBuffer) { int calculatedLen = 0; int stringLength = str.length(); - if (stringLength > stringBuffer.charBuffer.length) - { + if (stringLength > stringBuffer.charBuffer.length) { stringBuffer.resizeCharBuffer(stringLength); } str.getChars(0, stringLength, stringBuffer.charBuffer, 0); - for (int i = 0; i < stringLength; i++) - { + for (int i = 0; i < stringLength; i++) { char c = stringBuffer.charBuffer[i]; - if (c >= 1 && c < 0x7f) - { + if (c >= 1 && c < 0x7f) { calculatedLen++; } - else if (c >= 0x800) - { + else if (c >= 0x800) { calculatedLen += 3; } - else - { + else { calculatedLen += 2; } } return calculatedLen; } - public static class StringUtilBuffer - { + public static class StringUtilBuffer { public char[] charBuffer; public byte[] byteBuffer; - public void resizeCharBuffer(final int newSize) - { - if (newSize > charBuffer.length) - { + public void resizeCharBuffer(final int newSize) { + if (newSize > charBuffer.length) { charBuffer = new char[newSize]; } } - public void resizeByteBuffer(final int newSize) - { - if (newSize > byteBuffer.length) - { + public void resizeByteBuffer(final int newSize) { + if (newSize > byteBuffer.length) { byteBuffer = new byte[newSize]; } } - public StringUtilBuffer() - { + public StringUtilBuffer() { this(1024, 1024); } - public StringUtilBuffer(final int sizeChar, final int sizeByte) - { + public StringUtilBuffer(final int sizeChar, final int sizeByte) { charBuffer = new char[sizeChar]; byteBuffer = new byte[sizeByte]; } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/UUID.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/UUID.java index 296f363e83..342bf5dee9 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/UUID.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/UUID.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.utils; - /** * UUID represents Universally Unique Identifiers (aka Global UID in Windows * world). UUIDs are usually generated via UUIDGenerator (or in case of 'Null @@ -41,8 +40,8 @@ package org.apache.activemq.artemis.utils; * bytes). */ -public final class UUID -{ +public final class UUID { + private static final String kHexChars = "0123456789abcdefABCDEF"; public static final byte INDEX_CLOCK_HI = 6; @@ -98,8 +97,7 @@ public final class UUID * @param type UUID type * @param data 16 byte UUID contents */ - public UUID(final int type, final byte[] data) - { + public UUID(final int type, final byte[] data) { mId = data; // Type is multiplexed with time_hi: mId[UUID.INDEX_TYPE] &= (byte) 0x0F; @@ -109,8 +107,7 @@ public final class UUID mId[UUID.INDEX_VARIATION] |= (byte) 0x80; } - public byte[] asBytes() - { + public byte[] asBytes() { return mId; } @@ -129,27 +126,22 @@ public final class UUID private static final int[] kShifts = {3, 7, 17, 21, 29, 4, 9}; @Override - public int hashCode() - { - if (mHashCode == 0) - { + public int hashCode() { + if (mHashCode == 0) { // Let's handle first and last byte separately: int result = mId[0] & 0xFF; result |= result << 16; result |= result << 8; - for (int i = 1; i < 15; i += 2) - { + for (int i = 1; i < 15; i += 2) { int curr = (mId[i] & 0xFF) << 8 | mId[i + 1] & 0xFF; int shift = UUID.kShifts[i >> 1]; - if (shift > 16) - { + if (shift > 16) { result ^= curr << shift | curr >>> 32 - shift; } - else - { + else { result ^= curr << shift; } } @@ -161,12 +153,10 @@ public final class UUID result ^= last << 27; // Let's not accept hash 0 as it indicates 'not hashed yet': - if (result == 0) - { + if (result == 0) { mHashCode = -1; } - else - { + else { mHashCode = result; } } @@ -174,23 +164,19 @@ public final class UUID } @Override - public String toString() - { + public String toString() { /* * Could be synchronized, but there isn't much harm in just taking our * chances (ie. in the worst case we'll form the string more than once... * but result is the same) */ - if (mDesc == null) - { + if (mDesc == null) { StringBuffer b = new StringBuffer(36); - for (int i = 0; i < 16; ++i) - { + for (int i = 0; i < 16; ++i) { // Need to bypass hyphens: - switch (i) - { + switch (i) { case 4: case 6: case 8: @@ -204,8 +190,7 @@ public final class UUID b.append(UUID.kHexChars.charAt(hex >> 4)); b.append(UUID.kHexChars.charAt(hex & 0x0f)); } - if (!UUID.sDescCaching) - { + if (!UUID.sDescCaching) { return b.toString(); } mDesc = b.toString(); @@ -220,16 +205,12 @@ public final class UUID * @return byte array that can be used to recreate a UUID instance from the given String * representation */ - public static byte[] stringToBytes(String uuid) - { + public static byte[] stringToBytes(String uuid) { byte[] data = new byte[16]; int dataIdx = 0; - try - { - for (int i = 0; i < uuid.length(); ) - { - while (uuid.charAt(i) == '-') - { + try { + for (int i = 0; i < uuid.length(); ) { + while (uuid.charAt(i) == '-') { i++; } char c1 = uuid.charAt(i); @@ -240,8 +221,7 @@ public final class UUID data[dataIdx++] = (byte) ((c1Bytes << 4) + c2Bytes); } } - catch (RuntimeException e) - { + catch (RuntimeException e) { throw new IllegalArgumentException(e); } return data; @@ -251,18 +231,14 @@ public final class UUID * Checking equality of UUIDs is easy; just compare the 128-bit number. */ @Override - public boolean equals(final Object o) - { - if (!(o instanceof UUID)) - { + public boolean equals(final Object o) { + if (!(o instanceof UUID)) { return false; } byte[] otherId = ((UUID) o).mId; byte[] thisId = mId; - for (int i = 0; i < 16; ++i) - { - if (otherId[i] != thisId[i]) - { + for (int i = 0; i < 16; ++i) { + if (otherId[i] != thisId[i]) { return false; } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/UUIDGenerator.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/UUIDGenerator.java index 0be8e7b521..4163cdcf30 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/UUIDGenerator.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/UUIDGenerator.java @@ -35,8 +35,8 @@ import java.util.concurrent.TimeUnit; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.logs.ActiveMQUtilLogger; -public final class UUIDGenerator -{ +public final class UUIDGenerator { + private static final UUIDGenerator sSingleton = new UUIDGenerator(); // Windows has some fake adapters that will return the same HARDWARE ADDRESS on any computer. We need to ignore those @@ -56,8 +56,7 @@ public final class UUIDGenerator /** * Constructor is private to enforce singleton access. */ - private UUIDGenerator() - { + private UUIDGenerator() { } /** @@ -65,8 +64,7 @@ public final class UUIDGenerator * * @return Instance of UUID Generator */ - public static UUIDGenerator getInstance() - { + public static UUIDGenerator getInstance() { return UUIDGenerator.sSingleton; } @@ -84,33 +82,27 @@ public final class UUIDGenerator * * @return A Random number generator. */ - public Random getRandomNumberGenerator() - { + public Random getRandomNumberGenerator() { /* * Could be synchronized, but since side effects are trivial (ie. * possibility of generating more than one SecureRandom, of which all but * one are dumped) let's not add synchronization overhead: */ - if (mRnd == null) - { + if (mRnd == null) { mRnd = new SecureRandom(); } return mRnd; } - public UUID generateTimeBasedUUID(final byte[] byteAddr) - { + public UUID generateTimeBasedUUID(final byte[] byteAddr) { byte[] contents = new byte[16]; int pos = 10; - for (int i = 0; i < 6; ++i) - { + for (int i = 0; i < 6; ++i) { contents[pos + i] = byteAddr[i]; } - synchronized (mTimerLock) - { - if (mTimer == null) - { + synchronized (mTimerLock) { + if (mTimer == null) { mTimer = new UUIDTimer(getRandomNumberGenerator()); } @@ -120,8 +112,7 @@ public final class UUIDGenerator return new UUID(UUID.TYPE_TIME_BASED, contents); } - public byte[] generateDummyAddress() - { + public byte[] generateDummyAddress() { Random rnd = getRandomNumberGenerator(); byte[] dummy = new byte[6]; rnd.nextBytes(dummy); @@ -130,8 +121,7 @@ public final class UUIDGenerator */ dummy[0] |= (byte) 0x01; - if (ActiveMQUtilLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQUtilLogger.LOGGER.isDebugEnabled()) { ActiveMQUtilLogger.LOGGER.debug("using dummy address " + UUIDGenerator.asString(dummy)); } return dummy; @@ -143,14 +133,12 @@ public final class UUIDGenerator * * @return A byte array containing the hardware address. */ - public static byte[] getHardwareAddress() - { + public static byte[] getHardwareAddress() { Method getHardwareAddressMethod; Method isUpMethod; Method isLoopbackMethod; Method isVirtualMethod; - try - { + try { getHardwareAddressMethod = NetworkInterface.class.getMethod("getHardwareAddress"); isUpMethod = NetworkInterface.class.getMethod("isUp"); isLoopbackMethod = NetworkInterface.class.getMethod("isLoopback"); @@ -159,49 +147,37 @@ public final class UUIDGenerator ExecutorService executor = Executors.newFixedThreadPool(0); executor.shutdownNow(); } - catch (Throwable t) - { + catch (Throwable t) { // not on Java 6 or not enough security permission return null; } - try - { + try { List ifaces = getAllNetworkInterfaces(); - if (ifaces.size() == 0) - { + if (ifaces.size() == 0) { return null; } - byte[] address = findFirstMatchingHardwareAddress(ifaces, - getHardwareAddressMethod, - isUpMethod, - isLoopbackMethod, - isVirtualMethod); - if (address != null) - { - if (ActiveMQUtilLogger.LOGGER.isDebugEnabled()) - { + byte[] address = findFirstMatchingHardwareAddress(ifaces, getHardwareAddressMethod, isUpMethod, isLoopbackMethod, isVirtualMethod); + if (address != null) { + if (ActiveMQUtilLogger.LOGGER.isDebugEnabled()) { ActiveMQUtilLogger.LOGGER.debug("using hardware address " + UUIDGenerator.asString(address)); } return address; } return null; } - catch (Exception e) - { + catch (Exception e) { return null; } } - public SimpleString generateSimpleStringUUID() - { + public SimpleString generateSimpleStringUUID() { return new SimpleString(generateStringUUID()); } - public UUID generateUUID() - { + public UUID generateUUID() { byte[] address = getAddressBytes(); UUID uid = generateTimeBasedUUID(address); @@ -209,39 +185,30 @@ public final class UUIDGenerator return uid; } - public String generateStringUUID() - { + public String generateStringUUID() { byte[] address = getAddressBytes(); - if (address == null) - { + if (address == null) { return java.util.UUID.randomUUID().toString(); } - else - { + else { return generateTimeBasedUUID(address).toString(); } } - public static byte[] getZeroPaddedSixBytes(final byte[] bytes) - { - if (bytes == null) - { + public static byte[] getZeroPaddedSixBytes(final byte[] bytes) { + if (bytes == null) { return null; } - if (bytes.length > 0 && bytes.length <= 6) - { - if (bytes.length == 6) - { + if (bytes.length > 0 && bytes.length <= 6) { + if (bytes.length == 6) { return bytes; } - else - { + else { // pad with zeroes to have a 6-byte array byte[] paddedAddress = new byte[6]; System.arraycopy(bytes, 0, paddedAddress, 0, bytes.length); - for (int i = bytes.length; i < 6; i++) - { + for (int i = bytes.length; i < 6; i++) { paddedAddress[i] = 0; } return paddedAddress; @@ -252,25 +219,19 @@ public final class UUIDGenerator // Private ------------------------------------------------------- - private static boolean isBlackList(final byte[] address) - { - for (byte[] blackList : UUIDGenerator.BLACK_LIST) - { - if (Arrays.equals(address, blackList)) - { + private static boolean isBlackList(final byte[] address) { + for (byte[] blackList : UUIDGenerator.BLACK_LIST) { + if (Arrays.equals(address, blackList)) { return true; } } return false; } - private byte[] getAddressBytes() - { - if (address == null) - { + private byte[] getAddressBytes() { + if (address == null) { address = UUIDGenerator.getHardwareAddress(); - if (address == null) - { + if (address == null) { address = generateDummyAddress(); } } @@ -278,16 +239,13 @@ public final class UUIDGenerator return address; } - private static String asString(final byte[] bytes) - { - if (bytes == null) - { + private static String asString(final byte[] bytes) { + if (bytes == null) { return null; } StringBuilder s = new StringBuilder(); - for (int i = 0; i < bytes.length - 1; i++) - { + for (int i = 0; i < bytes.length - 1; i++) { s.append(Integer.toHexString(bytes[i])); s.append(":"); } @@ -295,22 +253,18 @@ public final class UUIDGenerator return s.toString(); } - private static List getAllNetworkInterfaces() - { + private static List getAllNetworkInterfaces() { Enumeration networkInterfaces; - try - { + try { networkInterfaces = NetworkInterface.getNetworkInterfaces(); List ifaces = new ArrayList(); - while (networkInterfaces.hasMoreElements()) - { + while (networkInterfaces.hasMoreElements()) { ifaces.add(networkInterfaces.nextElement()); } return ifaces; } - catch (SocketException e) - { + catch (SocketException e) { return Collections.emptyList(); } } @@ -319,40 +273,32 @@ public final class UUIDGenerator final Method getHardwareAddressMethod, final Method isUpMethod, final Method isLoopbackMethod, - final Method isVirtualMethod) - { + final Method isVirtualMethod) { ExecutorService executor = Executors.newFixedThreadPool(ifaces.size()); Collection> tasks = new ArrayList>(ifaces.size()); - for (final NetworkInterface networkInterface : ifaces) - { - tasks.add(new Callable() - { - public byte[] call() throws Exception - { + for (final NetworkInterface networkInterface : ifaces) { + tasks.add(new Callable() { + public byte[] call() throws Exception { boolean up = (Boolean) isUpMethod.invoke(networkInterface); boolean loopback = (Boolean) isLoopbackMethod.invoke(networkInterface); boolean virtual = (Boolean) isVirtualMethod.invoke(networkInterface); - if (loopback || virtual || !up) - { + if (loopback || virtual || !up) { throw new Exception("not suitable interface"); } Object res = getHardwareAddressMethod.invoke(networkInterface); - if (res != null && res instanceof byte[]) - { + if (res != null && res instanceof byte[]) { byte[] address = (byte[]) res; byte[] paddedAddress = UUIDGenerator.getZeroPaddedSixBytes(address); - if (UUIDGenerator.isBlackList(address)) - { + if (UUIDGenerator.isBlackList(address)) { throw new Exception("black listed address"); } - if (paddedAddress != null) - { + if (paddedAddress != null) { return paddedAddress; } } @@ -361,18 +307,15 @@ public final class UUIDGenerator } }); } - try - { + try { // we wait 5 seconds to get the first matching hardware address. After that, we give up and return null byte[] address = executor.invokeAny(tasks, 5, TimeUnit.SECONDS); return address; } - catch (Exception e) - { + catch (Exception e) { return null; } - finally - { + finally { executor.shutdownNow(); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/UUIDTimer.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/UUIDTimer.java index 2af53cec60..b60174fad9 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/UUIDTimer.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/UUIDTimer.java @@ -65,8 +65,7 @@ import java.util.Random; * synchronized context (caller locks on either this object, or a similar timer * lock), and so has no method synchronization. */ -public class UUIDTimer -{ +public class UUIDTimer { // // // Constants /** @@ -126,8 +125,7 @@ public class UUIDTimer */ private int mClockCounter = 0; - UUIDTimer(final Random rnd) - { + UUIDTimer(final Random rnd) { mRnd = rnd; initCounters(rnd); mLastSystemTimestamp = 0L; @@ -135,8 +133,7 @@ public class UUIDTimer mLastUsedTimestamp = 0L; } - private void initCounters(final Random rnd) - { + private void initCounters(final Random rnd) { /* * Let's generate the clock sequence field now; as with counter, this * reduces likelihood of collisions (as explained in UUID specs) @@ -152,8 +149,7 @@ public class UUIDTimer mClockCounter = mClockSequence[2] & 0xFF; } - public void getTimestamp(final byte[] uuidData) - { + public void getTimestamp(final byte[] uuidData) { // First the clock sequence: uuidData[UUID.INDEX_CLOCK_SEQUENCE] = mClockSequence[0]; uuidData[UUID.INDEX_CLOCK_SEQUENCE + 1] = mClockSequence[1]; @@ -164,8 +160,7 @@ public class UUIDTimer * Let's first verify that the system time is not going backwards; * independent of whether we can use it: */ - if (systime < mLastSystemTimestamp) - { + if (systime < mLastSystemTimestamp) { // Logger.logWarning("System time going backwards! (got value // "+systime+", last "+mLastSystemTimestamp); // Let's write it down, still @@ -177,18 +172,15 @@ public class UUIDTimer * used (when generating UUIDs fast with coarse clock resolution; or if * clock has gone backwards over reboot etc). */ - if (systime <= mLastUsedTimestamp) - { + if (systime <= mLastUsedTimestamp) { /* * Can we just use the last time stamp (ok if the counter hasn't hit * max yet) */ - if (mClockCounter < UUIDTimer.kClockMultiplier) - { // yup, still have room + if (mClockCounter < UUIDTimer.kClockMultiplier) { // yup, still have room systime = mLastUsedTimestamp; } - else - { // nope, have to roll over to next value and maybe wait + else { // nope, have to roll over to next value and maybe wait long actDiff = mLastUsedTimestamp - systime; long origTime = systime; systime = mLastUsedTimestamp + 1L; @@ -209,14 +201,12 @@ public class UUIDTimer * been moved backwards, or when coarse clock resolution has forced * us to advance virtual timer too far) */ - if (actDiff >= UUIDTimer.kMaxClockAdvance) - { + if (actDiff >= UUIDTimer.kMaxClockAdvance) { UUIDTimer.slowDown(origTime, actDiff); } } } - else - { + else { /* * Clock has advanced normally; just need to make sure counter is reset * to a low value (need not be 0; good to leave a small residual to @@ -270,10 +260,8 @@ public class UUIDTimer * Delay is kept to just a millisecond or two, to prevent excessive blocking; * but that should be enough to eventually synchronize physical clock with * virtual clock values used for UUIDs. - * */ - private static void slowDown(final long startTime, final long actDiff) - { + private static void slowDown(final long startTime, final long actDiff) { /* * First, let's determine how long we'd like to wait. This is based on how * far ahead are we as of now. @@ -281,45 +269,36 @@ public class UUIDTimer long ratio = actDiff / UUIDTimer.kMaxClockAdvance; long delay; - if (ratio < 2L) - { // 200 msecs or less + if (ratio < 2L) { // 200 msecs or less delay = 1L; } - else if (ratio < 10L) - { // 1 second or less + else if (ratio < 10L) { // 1 second or less delay = 2L; } - else if (ratio < 600L) - { // 1 minute or less + else if (ratio < 600L) { // 1 minute or less delay = 3L; } - else - { + else { delay = 5L; } // Logger.logWarning("Need to wait for "+delay+" milliseconds; virtual // clock advanced too far in the future"); long waitUntil = startTime + delay; int counter = 0; - do - { - try - { + do { + try { Thread.sleep(delay); } - catch (InterruptedException ie) - { + catch (InterruptedException ie) { } delay = 1L; /* * This is just a sanity check: don't want an "infinite" loop if clock * happened to be moved backwards by, say, an hour... */ - if (++counter > UUIDTimer.MAX_WAIT_COUNT) - { + if (++counter > UUIDTimer.MAX_WAIT_COUNT) { break; } - } - while (System.currentTimeMillis() < waitUntil); + } while (System.currentTimeMillis() < waitUntil); } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/uri/SchemaConstants.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/uri/SchemaConstants.java index eee4a17bd5..0114b8a916 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/uri/SchemaConstants.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/uri/SchemaConstants.java @@ -16,8 +16,8 @@ */ package org.apache.activemq.artemis.utils.uri; -public class SchemaConstants -{ +public class SchemaConstants { + public static final String TCP = "tcp"; public static final String UDP = "udp"; diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/uri/URIFactory.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/uri/URIFactory.java index b3ff1b6a96..dae6faaf67 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/uri/URIFactory.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/uri/URIFactory.java @@ -22,70 +22,57 @@ import java.net.URISyntaxException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -public class URIFactory -{ +public class URIFactory { private URI defaultURI; private final Map> schemas = new ConcurrentHashMap<>(); - public URI getDefaultURI() - { + public URI getDefaultURI() { return defaultURI; } - public void setDefaultURI(URI uri) - { + public void setDefaultURI(URI uri) { this.defaultURI = uri; } - public void registerSchema(URISchema schemaFactory) - { + public void registerSchema(URISchema schemaFactory) { schemas.put(schemaFactory.getSchemaName(), schemaFactory); schemaFactory.setFactory(this); } - public void removeSchema(final SchemaConstants schemaName) - { + public void removeSchema(final SchemaConstants schemaName) { schemas.remove(schemaName); } - public URI expandURI(String uriString) throws Exception - { + public URI expandURI(String uriString) throws Exception { return normalise(uriString); } - public T newObject(URI uri, P param) throws Exception - { + public T newObject(URI uri, P param) throws Exception { URISchema schemaFactory = schemas.get(uri.getScheme()); - if (schemaFactory == null) - { + if (schemaFactory == null) { throw new NullPointerException("Schema " + uri.getScheme() + " not found"); } - return schemaFactory.newObject(uri, param); } - public void populateObject(URI uri, T bean) throws Exception - { + public void populateObject(URI uri, T bean) throws Exception { URISchema schemaFactory = schemas.get(uri.getScheme()); - if (schemaFactory == null) - { + if (schemaFactory == null) { throw new NullPointerException("Schema " + uri.getScheme() + " not found"); } schemaFactory.populateObject(uri, bean); } - public URI createSchema(String scheme, T bean) throws Exception - { + public URI createSchema(String scheme, T bean) throws Exception { URISchema schemaFactory = schemas.get(scheme); - if (schemaFactory == null) - { + if (schemaFactory == null) { throw new NullPointerException("Schema " + scheme + " not found"); } return schemaFactory.newURI(bean); @@ -101,32 +88,24 @@ public class URIFactory * * It is the job of the URISchema implementation to handle these fragments as needed. * */ - private URI normalise(String uri) throws URISyntaxException - { - if (uri.startsWith("(")) - { + private URI normalise(String uri) throws URISyntaxException { + if (uri.startsWith("(")) { String[] split = uri.split("\\)"); String[] connectorURIS = split[0].substring(split[0].indexOf('(') + 1).split(","); String factoryQuery = split.length > 1 ? split[1] : ""; StringBuilder builder = new StringBuilder(connectorURIS[0]); - if (factoryQuery != null && factoryQuery.length() > 0) - { - if (connectorURIS[0].contains("?")) - { + if (factoryQuery != null && factoryQuery.length() > 0) { + if (connectorURIS[0].contains("?")) { builder.append("&").append(factoryQuery.substring(1)); } - else - { + else { builder.append(factoryQuery); } } - if (connectorURIS.length > 1) - { + if (connectorURIS.length > 1) { builder.append("#"); - for (int i = 1; i < connectorURIS.length; i++) - { - if (i > 1) - { + for (int i = 1; i < connectorURIS.length; i++) { + if (i > 1) { builder.append(","); } builder.append(connectorURIS[i]); diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/uri/URISchema.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/uri/URISchema.java index e7ee1c1eb1..335833130c 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/uri/URISchema.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/uri/URISchema.java @@ -29,67 +29,53 @@ import java.util.Set; import org.apache.commons.beanutils.BeanUtilsBean; import org.apache.commons.beanutils.FluentPropertyBeanIntrospector; -public abstract class URISchema -{ +public abstract class URISchema { + public abstract String getSchemaName(); - public T newObject(URI uri, P param) throws Exception - { + public T newObject(URI uri, P param) throws Exception { return newObject(uri, null, param); } - public void populateObject(URI uri, T bean) throws Exception - { + public void populateObject(URI uri, T bean) throws Exception { setData(uri, bean, parseQuery(uri.getQuery(), null)); } - public URI newURI(T bean) throws Exception - { + public URI newURI(T bean) throws Exception { return internalNewURI(bean); } private URIFactory parentFactory; - - void setFactory(URIFactory factory) - { + void setFactory(URIFactory factory) { this.parentFactory = factory; } - protected URIFactory getFactory() - { + protected URIFactory getFactory() { return parentFactory; } - - protected String getHost(URI uri) - { + protected String getHost(URI uri) { URI defaultFactory = getDefaultURI(); - if (defaultFactory != null && uri.getHost() == null && defaultFactory.getScheme().equals(uri.getScheme())) - { + if (defaultFactory != null && uri.getHost() == null && defaultFactory.getScheme().equals(uri.getScheme())) { uri = defaultFactory; } return uri.getHost(); } - protected URI getDefaultURI() - { + protected URI getDefaultURI() { URIFactory factory = getFactory(); - if (factory == null) - { + if (factory == null) { return null; } - else - { + else { return factory.getDefaultURI(); } } - protected int getPort(URI uri) - { + protected int getPort(URI uri) { URI defaultFactory = getDefaultURI(); - if (defaultFactory != null && uri.getPort() < 0 && defaultFactory.getScheme().equals(uri.getScheme())) - { + if (defaultFactory != null && uri.getPort() < 0 && defaultFactory.getScheme().equals(uri.getScheme())) { uri = defaultFactory; } return uri.getPort(); @@ -98,13 +84,13 @@ public abstract class URISchema /** * It will create a new Object for the URI selected schema. * the propertyOverrides is used to replace whatever was defined on the URL string - * @param uri The URI - * @param propertyOverrides used to replace whatever was defined on the URL string + * + * @param uri The URI + * @param propertyOverrides used to replace whatever was defined on the URL string * @return new Object * @throws Exception On error */ - public T newObject(URI uri, Map propertyOverrides, P param) throws Exception - { + public T newObject(URI uri, Map propertyOverrides, P param) throws Exception { return internalNewObject(uri, parseQuery(uri.getQuery(), propertyOverrides), param); } @@ -114,83 +100,63 @@ public abstract class URISchema private static final BeanUtilsBean beanUtils = new BeanUtilsBean(); - - static - { + static { // This is to customize the BeanUtils to use Fluent Proeprties as well beanUtils.getPropertyUtils().addBeanIntrospector(new FluentPropertyBeanIntrospector()); } - - public static Map parseQuery(String uri, Map propertyOverrides) throws URISyntaxException - { - try - { + public static Map parseQuery(String uri, + Map propertyOverrides) throws URISyntaxException { + try { Map rc = new HashMap(); - if (uri != null && !uri.isEmpty()) - { + if (uri != null && !uri.isEmpty()) { String[] parameters = uri.split("&"); - for (int i = 0; i < parameters.length; i++) - { + for (int i = 0; i < parameters.length; i++) { int p = parameters[i].indexOf("="); - if (p >= 0) - { + if (p >= 0) { String name = URLDecoder.decode(parameters[i].substring(0, p), "UTF-8"); String value = URLDecoder.decode(parameters[i].substring(p + 1), "UTF-8"); rc.put(name, value); } - else - { - if (!parameters[i].trim().isEmpty()) - { + else { + if (!parameters[i].trim().isEmpty()) { rc.put(parameters[i], null); } } } } - if (propertyOverrides != null) - { - for (Map.Entry entry: propertyOverrides.entrySet()) - { + if (propertyOverrides != null) { + for (Map.Entry entry : propertyOverrides.entrySet()) { rc.put(entry.getKey(), entry.getValue()); } } return rc; } - catch (UnsupportedEncodingException e) - { + catch (UnsupportedEncodingException e) { throw (URISyntaxException) new URISyntaxException(e.toString(), "Invalid encoding").initCause(e); } } - - - protected String printQuery(Map query) - { + protected String printQuery(Map query) { StringBuffer buffer = new StringBuffer(); - for (Map.Entry entry : query.entrySet()) - { + for (Map.Entry entry : query.entrySet()) { buffer.append(entry.getKey() + "=" + entry.getValue()); buffer.append("\n"); } - return buffer.toString(); + return buffer.toString(); } - protected static

P copyData(P source, P target) throws Exception - { - synchronized (beanUtils) - { + protected static

P copyData(P source, P target) throws Exception { + synchronized (beanUtils) { beanUtils.copyProperties(source, target); } return target; } - protected static

P setData(URI uri, P obj, Map query) throws Exception - { - synchronized (beanUtils) - { + protected static

P setData(URI uri, P obj, Map query) throws Exception { + synchronized (beanUtils) { beanUtils.setProperty(obj, "host", uri.getHost()); beanUtils.setProperty(obj, "port", uri.getPort()); beanUtils.setProperty(obj, "userInfo", uri.getUserInfo()); @@ -199,46 +165,36 @@ public abstract class URISchema return obj; } - public static void setData(URI uri, HashMap properties, Set allowableProperties, Map query) - { - if (allowableProperties.contains("host")) - { + public static void setData(URI uri, + HashMap properties, + Set allowableProperties, + Map query) { + if (allowableProperties.contains("host")) { properties.put("host", "" + uri.getHost()); } - if (allowableProperties.contains("port")) - { + if (allowableProperties.contains("port")) { properties.put("port", "" + uri.getPort()); } - if (allowableProperties.contains("userInfo")) - { + if (allowableProperties.contains("userInfo")) { properties.put("userInfo", "" + uri.getUserInfo()); } - for (Map.Entry entry : query.entrySet()) - { - if (allowableProperties.contains(entry.getKey())) - { + for (Map.Entry entry : query.entrySet()) { + if (allowableProperties.contains(entry.getKey())) { properties.put(entry.getKey(), entry.getValue()); } } } - public static String getData(List ignored, Object... beans) throws Exception - { + public static String getData(List ignored, Object... beans) throws Exception { StringBuilder sb = new StringBuilder(); - synchronized (beanUtils) - { - for (Object bean : beans) - { - if (bean != null) - { + synchronized (beanUtils) { + for (Object bean : beans) { + if (bean != null) { PropertyDescriptor[] descriptors = beanUtils.getPropertyUtils().getPropertyDescriptors(bean); - for (PropertyDescriptor descriptor : descriptors) - { - if (descriptor.getReadMethod() != null && isWriteable(descriptor, ignored)) - { + for (PropertyDescriptor descriptor : descriptors) { + if (descriptor.getReadMethod() != null && isWriteable(descriptor, ignored)) { String value = beanUtils.getProperty(bean, descriptor.getName()); - if (value != null) - { + if (value != null) { sb.append("&").append(descriptor.getName()).append("=").append(value); } } @@ -249,23 +205,21 @@ public abstract class URISchema return sb.toString(); } - private static boolean isWriteable(PropertyDescriptor descriptor, List ignored) - { - if (ignored != null && ignored.contains(descriptor.getName())) - { + private static boolean isWriteable(PropertyDescriptor descriptor, List ignored) { + if (ignored != null && ignored.contains(descriptor.getName())) { return false; } Class type = descriptor.getPropertyType(); return (type == Double.class) || - (type == double.class) || - (type == Long.class) || - (type == long.class) || - (type == Integer.class) || - (type == int.class) || - (type == Float.class) || - (type == float.class) || - (type == Boolean.class) || - (type == boolean.class) || - (type == String.class); + (type == double.class) || + (type == Long.class) || + (type == long.class) || + (type == Integer.class) || + (type == int.class) || + (type == Float.class) || + (type == float.class) || + (type == Boolean.class) || + (type == boolean.class) || + (type == String.class); } } diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/ByteUtilTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/ByteUtilTest.java index 3b54fe722f..ada02f4126 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/ByteUtilTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/ByteUtilTest.java @@ -19,31 +19,25 @@ package org.apache.activemq.artemis.utils; import org.junit.Assert; import org.junit.Test; -public class ByteUtilTest -{ +public class ByteUtilTest { + @Test - public void testBytesToString() - { - byte[] byteArray = new byte[] {0, 1, 2, 3}; + public void testBytesToString() { + byte[] byteArray = new byte[]{0, 1, 2, 3}; testEquals("0001 0203", ByteUtil.bytesToHex(byteArray, 2)); testEquals("00 01 02 03", ByteUtil.bytesToHex(byteArray, 1)); testEquals("000102 03", ByteUtil.bytesToHex(byteArray, 3)); } - @Test - public void testMaxString() - { + public void testMaxString() { byte[] byteArray = new byte[20 * 1024]; - System.out.println(ByteUtil.maxString(ByteUtil.bytesToHex(byteArray, 2),150)); + System.out.println(ByteUtil.maxString(ByteUtil.bytesToHex(byteArray, 2), 150)); } - - void testEquals(String string1, String string2) - { - if (!string1.equals(string2)) - { + void testEquals(String string1, String string2) { + if (!string1.equals(string2)) { Assert.fail("String are not the same:=" + string1 + "!=" + string2); } } diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/PairTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/PairTest.java index ed33a80e85..b441c7b92a 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/PairTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/PairTest.java @@ -21,13 +21,10 @@ import org.junit.Test; import org.junit.Assert; import org.apache.activemq.artemis.api.core.Pair; - -public class PairTest extends Assert -{ +public class PairTest extends Assert { @Test - public void testPair() - { + public void testPair() { Pair p = new Pair(Integer.valueOf(12), Integer.valueOf(13)); int hash = p.hashCode(); p.setA(null); diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/ReferenceCounterTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/ReferenceCounterTest.java index 30f637773c..c338fb3c4a 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/ReferenceCounterTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/ReferenceCounterTest.java @@ -26,39 +26,34 @@ import java.util.concurrent.atomic.AtomicInteger; import org.junit.Assert; import org.junit.Test; -public class ReferenceCounterTest extends Assert -{ +public class ReferenceCounterTest extends Assert { + + class LatchRunner implements Runnable { - class LatchRunner implements Runnable - { final CountDownLatch latch = new CountDownLatch(1); final AtomicInteger counts = new AtomicInteger(0); volatile Thread lastThreadUsed; - public void run() - { + public void run() { counts.incrementAndGet(); latch.countDown(); } } @Test - public void testReferenceNoExecutor() throws Exception - { + public void testReferenceNoExecutor() throws Exception { internalTestReferenceNoExecutor(null); } @Test - public void testReferenceWithExecutor() throws Exception - { + public void testReferenceWithExecutor() throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); internalTestReferenceNoExecutor(executor); executor.shutdown(); } @Test - public void testReferenceValidExecutorUsed() throws Exception - { + public void testReferenceValidExecutorUsed() throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); LatchRunner runner = new LatchRunner(); ReferenceCounterUtil counter = new ReferenceCounterUtil(runner, executor); @@ -72,54 +67,43 @@ public class ReferenceCounterTest extends Assert executor.shutdown(); } - public void internalTestReferenceNoExecutor(Executor executor) throws Exception - { + public void internalTestReferenceNoExecutor(Executor executor) throws Exception { LatchRunner runner = new LatchRunner(); final ReferenceCounterUtil ref; - if (executor == null) - { + if (executor == null) { ref = new ReferenceCounterUtil(runner); } - else - { + else { ref = new ReferenceCounterUtil(runner, executor); } Thread[] t = new Thread[100]; - for (int i = 0; i < t.length; i++) - { - t[i] = new Thread() - { - public void run() - { + for (int i = 0; i < t.length; i++) { + t[i] = new Thread() { + public void run() { ref.increment(); } }; t[i].start(); } - for (Thread tx : t) - { + for (Thread tx : t) { tx.join(); } - for (int i = 0; i < t.length; i++) - { - t[i] = new Thread() - { - public void run() - { + for (int i = 0; i < t.length; i++) { + t[i] = new Thread() { + public void run() { ref.decrement(); } }; t[i].start(); } - for (Thread tx : t) - { + for (Thread tx : t) { tx.join(); } @@ -127,6 +111,5 @@ public class ReferenceCounterTest extends Assert assertEquals(1, runner.counts.get()); - } } diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/URIParserTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/URIParserTest.java index 3155fa28c3..5e4849da69 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/URIParserTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/URIParserTest.java @@ -25,8 +25,7 @@ import org.junit.Test; import java.net.URI; import java.util.Map; -public class URIParserTest -{ +public class URIParserTest { /** * this is just a simple test to validate the model @@ -34,10 +33,9 @@ public class URIParserTest * @throws Throwable */ @Test - public void testSchemaFruit() throws Throwable - { + public void testSchemaFruit() throws Throwable { FruitParser parser = new FruitParser(); - Fruit fruit = (Fruit)parser.newObject(new URI("fruit://some:guy@fair-market:3030?color=green&fluentName=something"), null); + Fruit fruit = (Fruit) parser.newObject(new URI("fruit://some:guy@fair-market:3030?color=green&fluentName=something"), null); Assert.assertEquals("fruit", fruit.getName()); Assert.assertEquals(3030, fruit.getPort()); @@ -46,7 +44,6 @@ public class URIParserTest Assert.assertEquals("green", fruit.getColor()); Assert.assertEquals("something", fruit.getFluentName()); - } /** @@ -55,8 +52,7 @@ public class URIParserTest * @throws Throwable */ @Test - public void testSchemaNoHosPropertyt() throws Throwable - { + public void testSchemaNoHosPropertyt() throws Throwable { FruitParser parser = new FruitParser(); FruitBase fruit = parser.newObject(new URI("base://some:guy@fair-market:3030?color=green&fluentName=something"), null); Assert.assertEquals("base", fruit.getName()); @@ -70,10 +66,9 @@ public class URIParserTest * @throws Throwable */ @Test - public void testSchemaNoHostOnURL() throws Throwable - { + public void testSchemaNoHostOnURL() throws Throwable { FruitParser parser = new FruitParser(); - Fruit fruit = (Fruit)parser.newObject(new URI("fruit://some:guy@port?color=green&fluentName=something"), null); + Fruit fruit = (Fruit) parser.newObject(new URI("fruit://some:guy@port?color=green&fluentName=something"), null); System.out.println("fruit:" + fruit); Assert.assertEquals("fruit", fruit.getName()); @@ -81,104 +76,84 @@ public class URIParserTest Assert.assertEquals("something", fruit.getFluentName()); } + class FruitParser extends URIFactory { - class FruitParser extends URIFactory - { - FruitParser() - { + FruitParser() { this.registerSchema(new FruitSchema()); this.registerSchema(new FruitBaseSchema()); } } - class FruitSchema extends URISchema - { + class FruitSchema extends URISchema { + @Override - public String getSchemaName() - { + public String getSchemaName() { return "fruit"; } - @Override - public FruitBase internalNewObject(URI uri, Map query, String fruitName) throws Exception - { + public FruitBase internalNewObject(URI uri, Map query, String fruitName) throws Exception { return setData(uri, new Fruit(getSchemaName()), query); } @Override - protected URI internalNewURI(FruitBase bean) - { + protected URI internalNewURI(FruitBase bean) { return null; } } - class FruitBaseSchema extends URISchema - { + class FruitBaseSchema extends URISchema { + @Override - public String getSchemaName() - { + public String getSchemaName() { return "base"; } - @Override - public FruitBase internalNewObject(URI uri, Map query, String fruitName) throws Exception - { + public FruitBase internalNewObject(URI uri, Map query, String fruitName) throws Exception { return setData(uri, new FruitBase(getSchemaName()), query); } @Override - protected URI internalNewURI(FruitBase bean) - { + protected URI internalNewURI(FruitBase bean) { return null; } } + public static class FruitBase { - public static class FruitBase - { final String name; String fluentName; String color; - FruitBase(final String name) - { + FruitBase(final String name) { this.name = name; } - - public String getName() - { + public String getName() { return name; } - - public String getColor() - { + public String getColor() { return color; } - public void setColor(String color) - { + public void setColor(String color) { this.color = color; } - public String getFluentName() - { + public String getFluentName() { return fluentName; } - public FruitBase setFluentName(String name) - { + public FruitBase setFluentName(String name) { this.fluentName = name; return this; } @Override - public String toString() - { + public String toString() { return "FruitBase{" + "name='" + name + '\'' + ", fluentName='" + fluentName + '\'' + @@ -187,12 +162,9 @@ public class URIParserTest } } - public static class Fruit extends FruitBase - { + public static class Fruit extends FruitBase { - - public Fruit(String name) - { + public Fruit(String name) { super(name); } @@ -200,41 +172,32 @@ public class URIParserTest int port; String userInfo; - - - public void setHost(String host) - { + public void setHost(String host) { this.host = host; } - public String getHost() - { + public String getHost() { return host; } - public void setPort(int port) - { + public void setPort(int port) { this.port = port; } - public int getPort() - { + public int getPort() { return port; } - public void setUserInfo(String userInfo) - { + public void setUserInfo(String userInfo) { this.userInfo = userInfo; } - public String getUserInfo() - { + public String getUserInfo() { return userInfo; } @Override - public String toString() - { + public String toString() { return "Fruit{" + "host='" + host + '\'' + ", port=" + port + diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/config/ActiveMQDefaultConfiguration.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/config/ActiveMQDefaultConfiguration.java index adb2861ba2..6b1bb5cf43 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/config/ActiveMQDefaultConfiguration.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/config/ActiveMQDefaultConfiguration.java @@ -22,8 +22,7 @@ import org.apache.activemq.artemis.core.journal.impl.JournalConstants; /** * Default values of ActiveMQ Artemis configuration parameters. */ -public final class ActiveMQDefaultConfiguration -{ +public final class ActiveMQDefaultConfiguration { /* *

In order to avoid compile time in-lining of constants, all access is done through methods * and all fields are PRIVATE STATIC but not FINAL. This is done following the recommendation at @@ -32,74 +31,61 @@ public final class ActiveMQDefaultConfiguration * @see http://docs.oracle.com/javase/specs/jls/se7/html/jls-13.html#jls-13.4.9 */ - private ActiveMQDefaultConfiguration() - { + private ActiveMQDefaultConfiguration() { // Utility class } - public static long getDefaultClientFailureCheckPeriod() - { + public static long getDefaultClientFailureCheckPeriod() { return DEFAULT_CLIENT_FAILURE_CHECK_PERIOD; } - public static long getDefaultFileDeployerScanPeriod() - { + public static long getDefaultFileDeployerScanPeriod() { return DEFAULT_FILE_DEPLOYER_SCAN_PERIOD; } - public static int getDefaultJournalMaxIoAio() - { + public static int getDefaultJournalMaxIoAio() { return DEFAULT_JOURNAL_MAX_IO_AIO; } - public static int getDefaultJournalBufferTimeoutAio() - { + public static int getDefaultJournalBufferTimeoutAio() { return DEFAULT_JOURNAL_BUFFER_TIMEOUT_AIO; } - public static int getDefaultJournalBufferSizeAio() - { + public static int getDefaultJournalBufferSizeAio() { return DEFAULT_JOURNAL_BUFFER_SIZE_AIO; } - public static int getDefaultJournalMaxIoNio() - { + public static int getDefaultJournalMaxIoNio() { return DEFAULT_JOURNAL_MAX_IO_NIO; } - public static int getDefaultJournalBufferTimeoutNio() - { + public static int getDefaultJournalBufferTimeoutNio() { return DEFAULT_JOURNAL_BUFFER_TIMEOUT_NIO; } - public static int getDefaultJournalBufferSizeNio() - { + public static int getDefaultJournalBufferSizeNio() { return DEFAULT_JOURNAL_BUFFER_SIZE_NIO; } - public static String getPropMaskPassword() - { + public static String getPropMaskPassword() { return PROP_MASK_PASSWORD; } - public static String getPropPasswordCodec() - { + public static String getPropPasswordCodec() { return PROP_PASSWORD_CODEC; } /** * what kind of HA Policy should we use */ - public static String getDefaultHapolicyType() - { + public static String getDefaultHapolicyType() { return DEFAULT_HAPOLICY_TYPE; } /** * The backup strategy to use if we are a backup or for any colocated backups. */ - public static String getDefaultHapolicyBackupStrategy() - { + public static String getDefaultHapolicyBackupStrategy() { return DEFAULT_HAPOLICY_BACKUP_STRATEGY; } @@ -124,7 +110,6 @@ public final class ActiveMQDefaultConfiguration private static String PROP_MASK_PASSWORD = "activemq.usemaskedpassword"; private static String PROP_PASSWORD_CODEC = "activemq.passwordcodec"; - // what kind of HA Policy should we use private static String DEFAULT_HAPOLICY_TYPE = "NONE"; @@ -407,729 +392,637 @@ public final class ActiveMQDefaultConfiguration // How often the reaper will be run to check for timed out group bindings. Only valid for LOCAL handlers private static long DEFAULT_GROUPING_HANDLER_REAPER_PERIOD = 30000; - /** * If true then the ActiveMQ Artemis Server will make use of any Protocol Managers that are in available on the classpath. If false then only the core protocol will be available, unless in Embedded mode where users can inject their own Protocol Managers. */ - public static boolean isDefaultResolveProtocols() - { + public static boolean isDefaultResolveProtocols() { return DEFAULT_RESOLVE_PROTOCOLS; } /** * true means that the server will load configuration from the configuration files */ - public static boolean isDefaultFileDeploymentEnabled() - { + public static boolean isDefaultFileDeploymentEnabled() { return DEFAULT_FILE_DEPLOYMENT_ENABLED; } /** * true means that the server will use the file based journal for persistence. */ - public static boolean isDefaultPersistenceEnabled() - { + public static boolean isDefaultPersistenceEnabled() { return DEFAULT_PERSISTENCE_ENABLED; } /** * Maximum number of threads to use for the scheduled thread pool */ - public static int getDefaultScheduledThreadPoolMaxSize() - { + public static int getDefaultScheduledThreadPoolMaxSize() { return DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE; } /** * Maximum number of threads to use for the thread pool. -1 means 'no limits'. */ - public static int getDefaultThreadPoolMaxSize() - { + public static int getDefaultThreadPoolMaxSize() { return DEFAULT_THREAD_POOL_MAX_SIZE; } /** * true means that security is enabled */ - public static boolean isDefaultSecurityEnabled() - { + public static boolean isDefaultSecurityEnabled() { return DEFAULT_SECURITY_ENABLED; } /** * true means that graceful shutdown is enabled */ - public static boolean isDefaultGracefulShutdownEnabled() - { + public static boolean isDefaultGracefulShutdownEnabled() { return DEFAULT_GRACEFUL_SHUTDOWN_ENABLED; } /** * true means that graceful shutdown is enabled */ - public static long getDefaultGracefulShutdownTimeout() - { + public static long getDefaultGracefulShutdownTimeout() { return DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT; } /** * how long (in ms) to wait before invalidating the security cache */ - public static long getDefaultSecurityInvalidationInterval() - { + public static long getDefaultSecurityInvalidationInterval() { return DEFAULT_SECURITY_INVALIDATION_INTERVAL; } /** * how long (in ms) to wait to acquire a file lock on the journal */ - public static long getDefaultJournalLockAcquisitionTimeout() - { + public static long getDefaultJournalLockAcquisitionTimeout() { return DEFAULT_JOURNAL_LOCK_ACQUISITION_TIMEOUT; } /** * true means that the server supports wild card routing */ - public static boolean isDefaultWildcardRoutingEnabled() - { + public static boolean isDefaultWildcardRoutingEnabled() { return DEFAULT_WILDCARD_ROUTING_ENABLED; } /** * the name of the management address to send management messages to. It is prefixed with "jms.queue" so that JMS clients can send messages to it. */ - public static SimpleString getDefaultManagementAddress() - { + public static SimpleString getDefaultManagementAddress() { return DEFAULT_MANAGEMENT_ADDRESS; } /** * the name of the address that consumers bind to receive management notifications */ - public static SimpleString getDefaultManagementNotificationAddress() - { + public static SimpleString getDefaultManagementNotificationAddress() { return DEFAULT_MANAGEMENT_NOTIFICATION_ADDRESS; } /** * Cluster username. It applies to all cluster configurations. */ - public static String getDefaultClusterUser() - { + public static String getDefaultClusterUser() { return DEFAULT_CLUSTER_USER; } /** * Cluster password. It applies to all cluster configurations. */ - public static String getDefaultClusterPassword() - { + public static String getDefaultClusterPassword() { return DEFAULT_CLUSTER_PASSWORD; } /** * This option controls whether passwords in server configuration need be masked. If set to "true" the passwords are masked. */ - public static boolean isDefaultMaskPassword() - { + public static boolean isDefaultMaskPassword() { return DEFAULT_MASK_PASSWORD; } /** * true means that the management API is available via JMX */ - public static boolean isDefaultJmxManagementEnabled() - { + public static boolean isDefaultJmxManagementEnabled() { return DEFAULT_JMX_MANAGEMENT_ENABLED; } /** * the JMX domain used to registered ActiveMQ Artemis MBeans in the MBeanServer */ - public static String getDefaultJmxDomain() - { + public static String getDefaultJmxDomain() { return DEFAULT_JMX_DOMAIN; } /** * true means that message counters are enabled */ - public static boolean isDefaultMessageCounterEnabled() - { + public static boolean isDefaultMessageCounterEnabled() { return DEFAULT_MESSAGE_COUNTER_ENABLED; } /** * the sample period (in ms) to use for message counters */ - public static long getDefaultMessageCounterSamplePeriod() - { + public static long getDefaultMessageCounterSamplePeriod() { return DEFAULT_MESSAGE_COUNTER_SAMPLE_PERIOD; } /** * how many days to keep message counter history */ - public static int getDefaultMessageCounterMaxDayHistory() - { + public static int getDefaultMessageCounterMaxDayHistory() { return DEFAULT_MESSAGE_COUNTER_MAX_DAY_HISTORY; } /** * if set, this will override how long (in ms) to keep a connection alive without receiving a ping. -1 disables this setting. */ - public static long getDefaultConnectionTtlOverride() - { + public static long getDefaultConnectionTtlOverride() { return DEFAULT_CONNECTION_TTL_OVERRIDE; } /** * should certain incoming packets on the server be handed off to a thread from the thread pool for processing or should they be handled on the remoting thread? */ - public static boolean isDefaultAsyncConnectionExecutionEnabled() - { + public static boolean isDefaultAsyncConnectionExecutionEnabled() { return DEFAULT_ASYNC_CONNECTION_EXECUTION_ENABLED; } /** * how long (in ms) before a transaction can be removed from the resource manager after create time */ - public static long getDefaultTransactionTimeout() - { + public static long getDefaultTransactionTimeout() { return DEFAULT_TRANSACTION_TIMEOUT; } /** * how often (in ms) to scan for timeout transactions */ - public static long getDefaultTransactionTimeoutScanPeriod() - { + public static long getDefaultTransactionTimeoutScanPeriod() { return DEFAULT_TRANSACTION_TIMEOUT_SCAN_PERIOD; } /** * how often (in ms) to scan for expired messages */ - public static long getDefaultMessageExpiryScanPeriod() - { + public static long getDefaultMessageExpiryScanPeriod() { return DEFAULT_MESSAGE_EXPIRY_SCAN_PERIOD; } /** * the priority of the thread expiring messages */ - public static int getDefaultMessageExpiryThreadPriority() - { + public static int getDefaultMessageExpiryThreadPriority() { return DEFAULT_MESSAGE_EXPIRY_THREAD_PRIORITY; } /** * the size of the cache for pre-creating message ID's */ - public static int getDefaultIdCacheSize() - { + public static int getDefaultIdCacheSize() { return DEFAULT_ID_CACHE_SIZE; } /** * true means that ID's are persisted to the journal */ - public static boolean isDefaultPersistIdCache() - { + public static boolean isDefaultPersistIdCache() { return DEFAULT_PERSIST_ID_CACHE; } /** * True means that the delivery count is persisted before delivery. False means that this only happens after a message has been cancelled. */ - public static boolean isDefaultPersistDeliveryCountBeforeDelivery() - { + public static boolean isDefaultPersistDeliveryCountBeforeDelivery() { return DEFAULT_PERSIST_DELIVERY_COUNT_BEFORE_DELIVERY; } /** * the directory to store paged messages in */ - public static String getDefaultPagingDir() - { + public static String getDefaultPagingDir() { return DEFAULT_PAGING_DIR; } /** * the directory to store the persisted bindings to */ - public static String getDefaultBindingsDirectory() - { + public static String getDefaultBindingsDirectory() { return DEFAULT_BINDINGS_DIRECTORY; } /** * true means that the server will create the bindings directory on start up */ - public static boolean isDefaultCreateBindingsDir() - { + public static boolean isDefaultCreateBindingsDir() { return DEFAULT_CREATE_BINDINGS_DIR; } /** * The max number of concurrent reads allowed on paging */ - public static int getDefaultMaxConcurrentPageIo() - { + public static int getDefaultMaxConcurrentPageIo() { return DEFAULT_MAX_CONCURRENT_PAGE_IO; } /** * the directory to store the journal files in */ - public static String getDefaultJournalDir() - { + public static String getDefaultJournalDir() { return DEFAULT_JOURNAL_DIR; } /** * true means that the journal directory will be created */ - public static boolean isDefaultCreateJournalDir() - { + public static boolean isDefaultCreateJournalDir() { return DEFAULT_CREATE_JOURNAL_DIR; } /** * if true wait for transaction data to be synchronized to the journal before returning response to client */ - public static boolean isDefaultJournalSyncTransactional() - { + public static boolean isDefaultJournalSyncTransactional() { return DEFAULT_JOURNAL_SYNC_TRANSACTIONAL; } /** * if true wait for non transaction data to be synced to the journal before returning response to client. */ - public static boolean isDefaultJournalSyncNonTransactional() - { + public static boolean isDefaultJournalSyncNonTransactional() { return DEFAULT_JOURNAL_SYNC_NON_TRANSACTIONAL; } /** * Whether to log messages about the journal write rate */ - public static boolean isDefaultJournalLogWriteRate() - { + public static boolean isDefaultJournalLogWriteRate() { return DEFAULT_JOURNAL_LOG_WRITE_RATE; } /** * the size (in bytes) of each journal file */ - public static int getDefaultJournalFileSize() - { + public static int getDefaultJournalFileSize() { return DEFAULT_JOURNAL_FILE_SIZE; } /** * how many journal files to pre-create */ - public static int getDefaultJournalMinFiles() - { + public static int getDefaultJournalMinFiles() { return DEFAULT_JOURNAL_MIN_FILES; } /** * The percentage of live data on which we consider compacting the journal */ - public static int getDefaultJournalCompactPercentage() - { + public static int getDefaultJournalCompactPercentage() { return DEFAULT_JOURNAL_COMPACT_PERCENTAGE; } /** * The minimal number of data files before we can start compacting */ - public static int getDefaultJournalCompactMinFiles() - { + public static int getDefaultJournalCompactMinFiles() { return DEFAULT_JOURNAL_COMPACT_MIN_FILES; } /** * XXX Only meant to be used by project developers */ - public static int getDefaultJournalPerfBlastPages() - { + public static int getDefaultJournalPerfBlastPages() { return DEFAULT_JOURNAL_PERF_BLAST_PAGES; } /** * XXX Only meant to be used by project developers */ - public static boolean isDefaultRunSyncSpeedTest() - { + public static boolean isDefaultRunSyncSpeedTest() { return DEFAULT_RUN_SYNC_SPEED_TEST; } /** * Interval to log server specific information (e.g. memory usage etc) */ - public static long getDefaultServerDumpInterval() - { + public static long getDefaultServerDumpInterval() { return DEFAULT_SERVER_DUMP_INTERVAL; } /** * Percentage of available memory which will trigger a warning log */ - public static int getDefaultMemoryWarningThreshold() - { + public static int getDefaultMemoryWarningThreshold() { return DEFAULT_MEMORY_WARNING_THRESHOLD; } /** * frequency to sample JVM memory in ms (or -1 to disable memory sampling) */ - public static long getDefaultMemoryMeasureInterval() - { + public static long getDefaultMemoryMeasureInterval() { return DEFAULT_MEMORY_MEASURE_INTERVAL; } /** * the directory to store large messages */ - public static String getDefaultLargeMessagesDir() - { + public static String getDefaultLargeMessagesDir() { return DEFAULT_LARGE_MESSAGES_DIR; } /** * period in milliseconds between consecutive broadcasts */ - public static long getDefaultBroadcastPeriod() - { + public static long getDefaultBroadcastPeriod() { return DEFAULT_BROADCAST_PERIOD; } /** * Period the discovery group waits after receiving the last broadcast from a particular server before removing that servers connector pair entry from its list. */ - public static int getDefaultBroadcastRefreshTimeout() - { + public static int getDefaultBroadcastRefreshTimeout() { return DEFAULT_BROADCAST_REFRESH_TIMEOUT; } /** * how long to keep a connection alive in the absence of any data arriving from the client. This should be greater than the ping period. */ - public static long getDefaultConnectionTtl() - { + public static long getDefaultConnectionTtl() { return DEFAULT_CONNECTION_TTL; } /** * multiplier to apply to successive retry intervals */ - public static double getDefaultRetryIntervalMultiplier() - { + public static double getDefaultRetryIntervalMultiplier() { return DEFAULT_RETRY_INTERVAL_MULTIPLIER; } /** * Limit to the retry-interval growth (due to retry-interval-multiplier) */ - public static long getDefaultMaxRetryInterval() - { + public static long getDefaultMaxRetryInterval() { return DEFAULT_MAX_RETRY_INTERVAL; } /** * maximum number of initial connection attempts, -1 means 'no limits' */ - public static int getDefaultBridgeInitialConnectAttempts() - { + public static int getDefaultBridgeInitialConnectAttempts() { return DEFAULT_BRIDGE_INITIAL_CONNECT_ATTEMPTS; } /** * maximum number of retry attempts, -1 means 'no limits' */ - public static int getDefaultBridgeReconnectAttempts() - { + public static int getDefaultBridgeReconnectAttempts() { return DEFAULT_BRIDGE_RECONNECT_ATTEMPTS; } /** * should duplicate detection headers be inserted in forwarded messages? */ - public static boolean isDefaultBridgeDuplicateDetection() - { + public static boolean isDefaultBridgeDuplicateDetection() { return DEFAULT_BRIDGE_DUPLICATE_DETECTION; } /** * Once the bridge has received this many bytes, it sends a confirmation */ - public static int getDefaultBridgeConfirmationWindowSize() - { + public static int getDefaultBridgeConfirmationWindowSize() { return DEFAULT_BRIDGE_CONFIRMATION_WINDOW_SIZE; } /** * Upon reconnection this configures the number of time the same node on the topology will be retried before reseting the server locator and using the initial connectors */ - public static int getDefaultBridgeConnectSameNode() - { + public static int getDefaultBridgeConnectSameNode() { return DEFAULT_BRIDGE_CONNECT_SAME_NODE; } /** * The period (in milliseconds) used to check if the cluster connection has failed to receive pings from another server */ - public static long getDefaultClusterFailureCheckPeriod() - { + public static long getDefaultClusterFailureCheckPeriod() { return DEFAULT_CLUSTER_FAILURE_CHECK_PERIOD; } /** * how long to keep a connection alive in the absence of any data arriving from the client */ - public static long getDefaultClusterConnectionTtl() - { + public static long getDefaultClusterConnectionTtl() { return DEFAULT_CLUSTER_CONNECTION_TTL; } /** * How long to wait for a reply */ - public static long getDefaultClusterCallTimeout() - { + public static long getDefaultClusterCallTimeout() { return DEFAULT_CLUSTER_CALL_TIMEOUT; } /** * period (in ms) between successive retries */ - public static long getDefaultClusterRetryInterval() - { + public static long getDefaultClusterRetryInterval() { return DEFAULT_CLUSTER_RETRY_INTERVAL; } /** * multiplier to apply to the retry-interval */ - public static double getDefaultClusterRetryIntervalMultiplier() - { + public static double getDefaultClusterRetryIntervalMultiplier() { return DEFAULT_CLUSTER_RETRY_INTERVAL_MULTIPLIER; } /** * Maximum value for retry-interval */ - public static long getDefaultClusterMaxRetryInterval() - { + public static long getDefaultClusterMaxRetryInterval() { return DEFAULT_CLUSTER_MAX_RETRY_INTERVAL; } /** * How many attempts should be made to connect initially */ - public static int getDefaultClusterInitialConnectAttempts() - { + public static int getDefaultClusterInitialConnectAttempts() { return DEFAULT_CLUSTER_INITIAL_CONNECT_ATTEMPTS; } /** * How many attempts should be made to reconnect after failure */ - public static int getDefaultClusterReconnectAttempts() - { + public static int getDefaultClusterReconnectAttempts() { return DEFAULT_CLUSTER_RECONNECT_ATTEMPTS; } /** * should duplicate detection headers be inserted in forwarded messages? */ - public static boolean isDefaultClusterDuplicateDetection() - { + public static boolean isDefaultClusterDuplicateDetection() { return DEFAULT_CLUSTER_DUPLICATE_DETECTION; } - public static boolean isDefaultClusterForwardWhenNoConsumers() - { + public static boolean isDefaultClusterForwardWhenNoConsumers() { return DEFAULT_CLUSTER_FORWARD_WHEN_NO_CONSUMERS; } /** * should messages be load balanced if there are no matching consumers on target? */ - public static String getDefaultClusterMessageLoadBalancingType() - { + public static String getDefaultClusterMessageLoadBalancingType() { return DEFAULT_CLUSTER_MESSAGE_LOAD_BALANCING_TYPE; } /** * maximum number of hops cluster topology is propagated */ - public static int getDefaultClusterMaxHops() - { + public static int getDefaultClusterMaxHops() { return DEFAULT_CLUSTER_MAX_HOPS; } /** * The size (in bytes) of the window used for confirming data from the server connected to. */ - public static int getDefaultClusterConfirmationWindowSize() - { + public static int getDefaultClusterConfirmationWindowSize() { return DEFAULT_CLUSTER_CONFIRMATION_WINDOW_SIZE; } /** * How long to wait for a reply if in the middle of a fail-over. -1 means wait forever. */ - public static long getDefaultClusterCallFailoverTimeout() - { + public static long getDefaultClusterCallFailoverTimeout() { return DEFAULT_CLUSTER_CALL_FAILOVER_TIMEOUT; } /** * how often the cluster connection will notify the cluster of its existence right after joining the cluster */ - public static long getDefaultClusterNotificationInterval() - { + public static long getDefaultClusterNotificationInterval() { return DEFAULT_CLUSTER_NOTIFICATION_INTERVAL; } /** * how many times this cluster connection will notify the cluster of its existence right after joining the cluster */ - public static int getDefaultClusterNotificationAttempts() - { + public static int getDefaultClusterNotificationAttempts() { return DEFAULT_CLUSTER_NOTIFICATION_ATTEMPTS; } /** * whether this is an exclusive divert */ - public static boolean isDefaultDivertExclusive() - { + public static boolean isDefaultDivertExclusive() { return DEFAULT_DIVERT_EXCLUSIVE; } /** * If true then the server will request a backup on another node */ - public static boolean isDefaultHapolicyRequestBackup() - { + public static boolean isDefaultHapolicyRequestBackup() { return DEFAULT_HAPOLICY_REQUEST_BACKUP; } /** * How many times the live server will try to request a backup, -1 means for ever. */ - public static int getDefaultHapolicyBackupRequestRetries() - { + public static int getDefaultHapolicyBackupRequestRetries() { return DEFAULT_HAPOLICY_BACKUP_REQUEST_RETRIES; } /** * How long to wait for retries between attempts to request a backup server. */ - public static long getDefaultHapolicyBackupRequestRetryInterval() - { + public static long getDefaultHapolicyBackupRequestRetryInterval() { return DEFAULT_HAPOLICY_BACKUP_REQUEST_RETRY_INTERVAL; } /** * Whether or not this live server will accept backup requests from other live servers. */ - public static int getDefaultHapolicyMaxBackups() - { + public static int getDefaultHapolicyMaxBackups() { return DEFAULT_HAPOLICY_MAX_BACKUPS; } /** * The offset to use for the Connectors and Acceptors when creating a new backup server. */ - public static int getDefaultHapolicyBackupPortOffset() - { + public static int getDefaultHapolicyBackupPortOffset() { return DEFAULT_HAPOLICY_BACKUP_PORT_OFFSET; } /** * Whether to check the cluster for a (live) server using our own server ID when starting up. This option is only necessary for performing 'fail-back' on replicating servers. Strictly speaking this setting only applies to live servers and not to backups. */ - public static boolean isDefaultCheckForLiveServer() - { + public static boolean isDefaultCheckForLiveServer() { return DEFAULT_CHECK_FOR_LIVE_SERVER; } /** * This specifies how many times a replicated backup server can restart after moving its files on start. Once there are this number of backup journal files the server will stop permanently after if fails back. */ - public static int getDefaultMaxSavedReplicatedJournalsSize() - { + public static int getDefaultMaxSavedReplicatedJournalsSize() { return DEFAULT_MAX_SAVED_REPLICATED_JOURNALS_SIZE; } /** * Will this server, if a backup, restart once it has been stopped because of failback or scaling down. */ - public static boolean isDefaultRestartBackup() - { + public static boolean isDefaultRestartBackup() { return DEFAULT_RESTART_BACKUP; } /** * Whether a server will automatically stop when another places a request to take over its place. The use case is when a regular server stops and its backup takes over its duties, later the main server restarts and requests the server (the former backup) to stop operating. */ - public static boolean isDefaultAllowAutoFailback() - { + public static boolean isDefaultAllowAutoFailback() { return DEFAULT_ALLOW_AUTO_FAILBACK; } /** * if we have to start as a replicated server this is the delay to wait before fail-back occurs */ - public static long getDefaultFailbackDelay() - { + public static long getDefaultFailbackDelay() { return DEFAULT_FAILBACK_DELAY; } /** * Will this backup server come live on a normal server shutdown */ - public static boolean isDefaultFailoverOnServerShutdown() - { + public static boolean isDefaultFailoverOnServerShutdown() { return DEFAULT_FAILOVER_ON_SERVER_SHUTDOWN; } /** * its possible that you only want a server to partake in scale down as a receiver, via a group. In this case set scale-down to false */ - public static boolean isDefaultScaleDownEnabled() - { + public static boolean isDefaultScaleDownEnabled() { return DEFAULT_SCALE_DOWN_ENABLED; } /** * How long to wait for a decision */ - public static int getDefaultGroupingHandlerTimeout() - { + public static int getDefaultGroupingHandlerTimeout() { return DEFAULT_GROUPING_HANDLER_TIMEOUT; } /** * How long a group binding will be used, -1 means for ever. Bindings are removed after this wait elapses. On the remote node this is used to determine how often you should re-query the main coordinator in order to update the last time used accordingly. */ - public static int getDefaultGroupingHandlerGroupTimeout() - { + public static int getDefaultGroupingHandlerGroupTimeout() { return DEFAULT_GROUPING_HANDLER_GROUP_TIMEOUT; } /** * How often the reaper will be run to check for timed out group bindings. Only valid for LOCAL handlers */ - public static long getDefaultGroupingHandlerReaperPeriod() - { + public static long getDefaultGroupingHandlerReaperPeriod() { return DEFAULT_GROUPING_HANDLER_REAPER_PERIOD; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/BaseInterceptor.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/BaseInterceptor.java index 11635c8ed7..200e6b5d03 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/BaseInterceptor.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/BaseInterceptor.java @@ -19,8 +19,8 @@ package org.apache.activemq.artemis.api.core; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; -public interface BaseInterceptor

-{ +public interface BaseInterceptor

{ + /** * Intercepts a packet which is received before it is sent to the channel * diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/BroadcastEndpoint.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/BroadcastEndpoint.java index 7d1a6a8f0b..7a275a478b 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/BroadcastEndpoint.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/BroadcastEndpoint.java @@ -36,8 +36,8 @@ import java.util.concurrent.TimeUnit; * * @see JGroupsBroadcastEndpoint */ -public interface BroadcastEndpoint -{ +public interface BroadcastEndpoint { + /** * This method initializes a BroadcastEndpoint as * a receiving end for broadcasts. After that data can be diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/BroadcastEndpointFactory.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/BroadcastEndpointFactory.java index a68d231f5c..6c33a9e9a7 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/BroadcastEndpointFactory.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/BroadcastEndpointFactory.java @@ -16,10 +16,9 @@ */ package org.apache.activemq.artemis.api.core; - import java.io.Serializable; -public interface BroadcastEndpointFactory extends Serializable -{ +public interface BroadcastEndpointFactory extends Serializable { + BroadcastEndpoint createBroadcastEndpoint() throws Exception; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/BroadcastGroupConfiguration.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/BroadcastGroupConfiguration.java index 14e187beae..095deb0a28 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/BroadcastGroupConfiguration.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/BroadcastGroupConfiguration.java @@ -21,13 +21,12 @@ import java.util.List; import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration; - /** * The basic configuration used to determine how the server will broadcast members * This is analogous to {@link DiscoveryGroupConfiguration} */ -public final class BroadcastGroupConfiguration implements Serializable -{ +public final class BroadcastGroupConfiguration implements Serializable { + private static final long serialVersionUID = 2335634694112319124L; private String name = null; @@ -38,60 +37,50 @@ public final class BroadcastGroupConfiguration implements Serializable private List connectorInfos = null; - public BroadcastGroupConfiguration() - { + public BroadcastGroupConfiguration() { } - public String getName() - { + public String getName() { return name; } - public long getBroadcastPeriod() - { + public long getBroadcastPeriod() { return broadcastPeriod; } - public List getConnectorInfos() - { + public List getConnectorInfos() { return connectorInfos; } - public BroadcastGroupConfiguration setName(final String name) - { + public BroadcastGroupConfiguration setName(final String name) { this.name = name; return this; } - public BroadcastGroupConfiguration setBroadcastPeriod(final long broadcastPeriod) - { + public BroadcastGroupConfiguration setBroadcastPeriod(final long broadcastPeriod) { this.broadcastPeriod = broadcastPeriod; return this; } - public BroadcastGroupConfiguration setConnectorInfos(final List connectorInfos) - { + public BroadcastGroupConfiguration setConnectorInfos(final List connectorInfos) { this.connectorInfos = connectorInfos; return this; } - public BroadcastEndpointFactory getEndpointFactory() - { + public BroadcastEndpointFactory getEndpointFactory() { return endpointFactory; } - public BroadcastGroupConfiguration setEndpointFactory(BroadcastEndpointFactory endpointFactory) - { + public BroadcastGroupConfiguration setEndpointFactory(BroadcastEndpointFactory endpointFactory) { this.endpointFactory = endpointFactory; return this; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + (int)(broadcastPeriod ^ (broadcastPeriod >>> 32)); + result = prime * result + (int) (broadcastPeriod ^ (broadcastPeriod >>> 32)); result = prime * result + ((connectorInfos == null) ? 0 : connectorInfos.hashCode()); result = prime * result + ((endpointFactory == null) ? 0 : endpointFactory.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); @@ -99,33 +88,29 @@ public final class BroadcastGroupConfiguration implements Serializable } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; - BroadcastGroupConfiguration other = (BroadcastGroupConfiguration)obj; + BroadcastGroupConfiguration other = (BroadcastGroupConfiguration) obj; if (broadcastPeriod != other.broadcastPeriod) return false; - if (connectorInfos == null) - { + if (connectorInfos == null) { if (other.connectorInfos != null) return false; } else if (!connectorInfos.equals(other.connectorInfos)) return false; - if (endpointFactory == null) - { + if (endpointFactory == null) { if (other.endpointFactory != null) return false; } else if (!endpointFactory.equals(other.endpointFactory)) return false; - if (name == null) - { + if (name == null) { if (other.name != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/ChannelBroadcastEndpointFactory.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/ChannelBroadcastEndpointFactory.java index 69f22deca6..be5e04c4be 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/ChannelBroadcastEndpointFactory.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/ChannelBroadcastEndpointFactory.java @@ -23,31 +23,27 @@ import org.jgroups.JChannel; * * Note - the underlying JChannel is not closed in this implementation. */ -public class ChannelBroadcastEndpointFactory implements BroadcastEndpointFactory -{ +public class ChannelBroadcastEndpointFactory implements BroadcastEndpointFactory { + private final JChannel channel; private final String channelName; - public ChannelBroadcastEndpointFactory(JChannel channel, String channelName) - { + public ChannelBroadcastEndpointFactory(JChannel channel, String channelName) { this.channel = channel; this.channelName = channelName; } - public JChannel getChannel() - { + public JChannel getChannel() { return channel; } - public String getChannelName() - { + public String getChannelName() { return channelName; } @Override - public BroadcastEndpoint createBroadcastEndpoint() throws Exception - { + public BroadcastEndpoint createBroadcastEndpoint() throws Exception { return new JGroupsChannelBroadcastEndpoint(channel, channelName).initChannel(); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/DiscoveryGroupConfiguration.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/DiscoveryGroupConfiguration.java index 715fee177b..11985fb8a0 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/DiscoveryGroupConfiguration.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/DiscoveryGroupConfiguration.java @@ -32,8 +32,8 @@ import org.apache.activemq.artemis.utils.UUIDGenerator; * If by any reason, both properties are filled, the JGroups takes precedence. That means, if * {@code jgroupsFile != null} then the Grouping method used will be JGroups. */ -public final class DiscoveryGroupConfiguration implements Serializable -{ +public final class DiscoveryGroupConfiguration implements Serializable { + private static final long serialVersionUID = 8657206421727863400L; private String name = UUIDGenerator.getInstance().generateStringUUID(); @@ -47,25 +47,21 @@ public final class DiscoveryGroupConfiguration implements Serializable * */ private BroadcastEndpointFactory endpointFactory; - public DiscoveryGroupConfiguration() - { + public DiscoveryGroupConfiguration() { } - public String getName() - { + public String getName() { return name; } - public long getRefreshTimeout() - { + public long getRefreshTimeout() { return refreshTimeout; } /** * @param name the name to set */ - public DiscoveryGroupConfiguration setName(final String name) - { + public DiscoveryGroupConfiguration setName(final String name) { this.name = name; return this; } @@ -73,8 +69,7 @@ public final class DiscoveryGroupConfiguration implements Serializable /** * @param refreshTimeout the refreshTimeout to set */ - public DiscoveryGroupConfiguration setRefreshTimeout(final long refreshTimeout) - { + public DiscoveryGroupConfiguration setRefreshTimeout(final long refreshTimeout) { this.refreshTimeout = refreshTimeout; return this; } @@ -82,49 +77,48 @@ public final class DiscoveryGroupConfiguration implements Serializable /** * @return the discoveryInitialWaitTimeout */ - public long getDiscoveryInitialWaitTimeout() - { + public long getDiscoveryInitialWaitTimeout() { return discoveryInitialWaitTimeout; } /** * @param discoveryInitialWaitTimeout the discoveryInitialWaitTimeout to set */ - public DiscoveryGroupConfiguration setDiscoveryInitialWaitTimeout(long discoveryInitialWaitTimeout) - { + public DiscoveryGroupConfiguration setDiscoveryInitialWaitTimeout(long discoveryInitialWaitTimeout) { this.discoveryInitialWaitTimeout = discoveryInitialWaitTimeout; return this; } - public BroadcastEndpointFactory getBroadcastEndpointFactory() - { + public BroadcastEndpointFactory getBroadcastEndpointFactory() { return endpointFactory; } - public DiscoveryGroupConfiguration setBroadcastEndpointFactory(BroadcastEndpointFactory endpointFactory) - { + public DiscoveryGroupConfiguration setBroadcastEndpointFactory(BroadcastEndpointFactory endpointFactory) { this.endpointFactory = endpointFactory; return this; } @Override - public boolean equals(Object o) - { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; DiscoveryGroupConfiguration that = (DiscoveryGroupConfiguration) o; - if (discoveryInitialWaitTimeout != that.discoveryInitialWaitTimeout) return false; - if (refreshTimeout != that.refreshTimeout) return false; - if (name != null ? !name.equals(that.name) : that.name != null) return false; + if (discoveryInitialWaitTimeout != that.discoveryInitialWaitTimeout) + return false; + if (refreshTimeout != that.refreshTimeout) + return false; + if (name != null ? !name.equals(that.name) : that.name != null) + return false; return true; } @Override - public int hashCode() - { + public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (int) (refreshTimeout ^ (refreshTimeout >>> 32)); result = 31 * result + (int) (discoveryInitialWaitTimeout ^ (discoveryInitialWaitTimeout >>> 32)); @@ -132,8 +126,7 @@ public final class DiscoveryGroupConfiguration implements Serializable } @Override - public String toString() - { + public String toString() { return "DiscoveryGroupConfiguration{" + "name='" + name + '\'' + ", refreshTimeout=" + refreshTimeout + diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/FilterConstants.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/FilterConstants.java index 0992b7b5d0..0fbd35f6f8 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/FilterConstants.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/FilterConstants.java @@ -20,8 +20,8 @@ package org.apache.activemq.artemis.api.core; * Constants representing pre-defined message attributes that can be referenced in ActiveMQ Artemis core * filter expressions. */ -public final class FilterConstants -{ +public final class FilterConstants { + /** * Name of the ActiveMQ Artemis UserID header. */ @@ -67,8 +67,7 @@ public final class FilterConstants */ public static final SimpleString ACTIVEMQ_PREFIX = new SimpleString("AMQ"); - private FilterConstants() - { + private FilterConstants() { // Utility class } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/Interceptor.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/Interceptor.java index b86d31974c..9db3df2652 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/Interceptor.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/Interceptor.java @@ -25,6 +25,6 @@ import org.apache.activemq.artemis.core.protocol.core.Packet; * {@literal broker.xml}.
* To add it to a client, use {@link org.apache.activemq.artemis.api.core.client.ServerLocator#addIncomingInterceptor(Interceptor)} */ -public interface Interceptor extends BaseInterceptor -{ +public interface Interceptor extends BaseInterceptor { + } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JGroupsBroadcastEndpoint.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JGroupsBroadcastEndpoint.java index 86930956a7..df66450058 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JGroupsBroadcastEndpoint.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JGroupsBroadcastEndpoint.java @@ -30,8 +30,8 @@ import java.util.concurrent.TimeUnit; /** * This class is the implementation of ActiveMQ Artemis members discovery that will use JGroups. */ -public abstract class JGroupsBroadcastEndpoint implements BroadcastEndpoint -{ +public abstract class JGroupsBroadcastEndpoint implements BroadcastEndpoint { + private final String channelName; private boolean clientOpened; @@ -42,15 +42,12 @@ public abstract class JGroupsBroadcastEndpoint implements BroadcastEndpoint private JGroupsReceiver receiver; - public JGroupsBroadcastEndpoint(String channelName) - { + public JGroupsBroadcastEndpoint(String channelName) { this.channelName = channelName; } - public void broadcast(final byte[] data) throws Exception - { - if (broadcastOpened) - { + public void broadcast(final byte[] data) throws Exception { + if (broadcastOpened) { org.jgroups.Message msg = new org.jgroups.Message(); msg.setBuffer(data); @@ -59,34 +56,26 @@ public abstract class JGroupsBroadcastEndpoint implements BroadcastEndpoint } } - public byte[] receiveBroadcast() throws Exception - { - if (clientOpened) - { + public byte[] receiveBroadcast() throws Exception { + if (clientOpened) { return receiver.receiveBroadcast(); } - else - { + else { return null; } } - public byte[] receiveBroadcast(long time, TimeUnit unit) throws Exception - { - if (clientOpened) - { + public byte[] receiveBroadcast(long time, TimeUnit unit) throws Exception { + if (clientOpened) { return receiver.receiveBroadcast(time, unit); } - else - { + else { return null; } } - public synchronized void openClient() throws Exception - { - if (clientOpened) - { + public synchronized void openClient() throws Exception { + if (clientOpened) { return; } internalOpen(); @@ -95,34 +84,29 @@ public abstract class JGroupsBroadcastEndpoint implements BroadcastEndpoint clientOpened = true; } - public synchronized void openBroadcaster() throws Exception - { - if (broadcastOpened) return; + public synchronized void openBroadcaster() throws Exception { + if (broadcastOpened) + return; internalOpen(); broadcastOpened = true; } public abstract JChannel createChannel() throws Exception; - public JGroupsBroadcastEndpoint initChannel() throws Exception - { + public JGroupsBroadcastEndpoint initChannel() throws Exception { this.channel = JChannelManager.getJChannel(channelName, this); return this; } - protected void internalOpen() throws Exception - { + protected void internalOpen() throws Exception { channel.connect(); } - public synchronized void close(boolean isBroadcast) throws Exception - { - if (isBroadcast) - { + public synchronized void close(boolean isBroadcast) throws Exception { + if (isBroadcast) { broadcastOpened = false; } - else - { + else { channel.removeReceiver(receiver); clientOpened = false; } @@ -133,8 +117,7 @@ public abstract class JGroupsBroadcastEndpoint implements BroadcastEndpoint * Closes the channel used in this JGroups Broadcast. * Can be overridden by implementations that use an externally managed channel. */ - protected synchronized void internalCloseChannel() - { + protected synchronized void internalCloseChannel() { channel.close(); } @@ -142,23 +125,20 @@ public abstract class JGroupsBroadcastEndpoint implements BroadcastEndpoint * This class is used to receive messages from a JGroups channel. * Incoming messages are put into a queue. */ - private static final class JGroupsReceiver extends ReceiverAdapter - { + private static final class JGroupsReceiver extends ReceiverAdapter { + private final BlockingQueue dequeue = new LinkedBlockingDeque(); @Override - public void receive(org.jgroups.Message msg) - { + public void receive(org.jgroups.Message msg) { dequeue.add(msg.getBuffer()); } - public byte[] receiveBroadcast() throws Exception - { + public byte[] receiveBroadcast() throws Exception { return dequeue.take(); } - public byte[] receiveBroadcast(long time, TimeUnit unit) throws Exception - { + public byte[] receiveBroadcast(long time, TimeUnit unit) throws Exception { return dequeue.poll(time, unit); } } @@ -168,50 +148,41 @@ public abstract class JGroupsBroadcastEndpoint implements BroadcastEndpoint * controls the life of the JChannel. When reference count is zero, the channel * will be disconnected. */ - protected static class JChannelWrapper - { + protected static class JChannelWrapper { + int refCount = 1; JChannel channel; String channelName; final List receivers = new ArrayList(); - public JChannelWrapper(String channelName, JChannel channel) throws Exception - { + public JChannelWrapper(String channelName, JChannel channel) throws Exception { this.refCount = 1; this.channelName = channelName; this.channel = channel; } - public synchronized void close() - { + public synchronized void close() { refCount--; - if (refCount == 0) - { + if (refCount == 0) { JChannelManager.closeChannel(this.channelName, channel); } } - public void removeReceiver(JGroupsReceiver receiver) - { - synchronized (receivers) - { + public void removeReceiver(JGroupsReceiver receiver) { + synchronized (receivers) { receivers.remove(receiver); } } - public synchronized void connect() throws Exception - { - if (channel.isConnected()) return; - channel.setReceiver(new ReceiverAdapter() - { + public synchronized void connect() throws Exception { + if (channel.isConnected()) + return; + channel.setReceiver(new ReceiverAdapter() { @Override - public void receive(org.jgroups.Message msg) - { - synchronized (receivers) - { - for (JGroupsReceiver r : receivers) - { + public void receive(org.jgroups.Message msg) { + synchronized (receivers) { + for (JGroupsReceiver r : receivers) { r.receive(msg); } } @@ -220,28 +191,23 @@ public abstract class JGroupsBroadcastEndpoint implements BroadcastEndpoint channel.connect(channelName); } - public void addReceiver(JGroupsReceiver jGroupsReceiver) - { - synchronized (receivers) - { + public void addReceiver(JGroupsReceiver jGroupsReceiver) { + synchronized (receivers) { receivers.add(jGroupsReceiver); } } - public void send(org.jgroups.Message msg) throws Exception - { + public void send(org.jgroups.Message msg) throws Exception { channel.send(msg); } - public JChannelWrapper addRef() - { + public JChannelWrapper addRef() { this.refCount++; return this; } @Override - public String toString() - { + public String toString() { return "JChannelWrapper of [" + channel + "] " + refCount + " " + channelName; } } @@ -253,19 +219,17 @@ public abstract class JGroupsBroadcastEndpoint implements BroadcastEndpoint * Wherever a JChannel is needed it should only get it by calling the getChannel() * method of this class. The real disconnect of channels are also done here only. */ - protected static class JChannelManager - { + protected static class JChannelManager { + private static Map channels; - public static synchronized JChannelWrapper getJChannel(String channelName, JGroupsBroadcastEndpoint endpoint) throws Exception - { - if (channels == null) - { + public static synchronized JChannelWrapper getJChannel(String channelName, + JGroupsBroadcastEndpoint endpoint) throws Exception { + if (channels == null) { channels = new HashMap<>(); } JChannelWrapper wrapper = channels.get(channelName); - if (wrapper == null) - { + if (wrapper == null) { wrapper = new JChannelWrapper(channelName, endpoint.createChannel()); channels.put(channelName, wrapper); return wrapper; @@ -273,14 +237,12 @@ public abstract class JGroupsBroadcastEndpoint implements BroadcastEndpoint return wrapper.addRef(); } - public static synchronized void closeChannel(String channelName, JChannel channel) - { + public static synchronized void closeChannel(String channelName, JChannel channel) { channel.setReceiver(null); channel.disconnect(); channel.close(); JChannelWrapper wrapper = channels.remove(channelName); - if (wrapper == null) - { + if (wrapper == null) { throw new IllegalStateException("Did not find channel " + channelName); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JGroupsChannelBroadcastEndpoint.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JGroupsChannelBroadcastEndpoint.java index cb85b8d418..9793c78b1c 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JGroupsChannelBroadcastEndpoint.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JGroupsChannelBroadcastEndpoint.java @@ -23,25 +23,22 @@ import org.jgroups.JChannel; * * Note - this implementation does not close the JChannel, since its externally created. */ -public class JGroupsChannelBroadcastEndpoint extends JGroupsBroadcastEndpoint -{ +public class JGroupsChannelBroadcastEndpoint extends JGroupsBroadcastEndpoint { + private final JChannel jChannel; - public JGroupsChannelBroadcastEndpoint(JChannel jChannel, final String channelName) throws Exception - { + public JGroupsChannelBroadcastEndpoint(JChannel jChannel, final String channelName) throws Exception { super(channelName); this.jChannel = jChannel; } @Override - public JChannel createChannel() throws Exception - { + public JChannel createChannel() throws Exception { return jChannel; } @Override - protected synchronized void internalCloseChannel() - { + protected synchronized void internalCloseChannel() { // no-op, this version takes an externally managed channel. } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JGroupsFileBroadcastEndpoint.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JGroupsFileBroadcastEndpoint.java index 9bd485cf12..67d4cdea97 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JGroupsFileBroadcastEndpoint.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JGroupsFileBroadcastEndpoint.java @@ -23,22 +23,19 @@ import java.net.URL; /** * This class is the implementation of ActiveMQ Artemis members discovery that will use JGroups. */ -public final class JGroupsFileBroadcastEndpoint extends JGroupsBroadcastEndpoint -{ +public final class JGroupsFileBroadcastEndpoint extends JGroupsBroadcastEndpoint { + private String file; - public JGroupsFileBroadcastEndpoint(final String file, final String channelName) throws Exception - { + public JGroupsFileBroadcastEndpoint(final String file, final String channelName) throws Exception { super(channelName); this.file = file; } - public JChannel createChannel() throws Exception - { + public JChannel createChannel() throws Exception { URL configURL = Thread.currentThread().getContextClassLoader().getResource(file); - if (configURL == null) - { + if (configURL == null) { throw new RuntimeException("couldn't find JGroups configuration " + file); } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JGroupsFileBroadcastEndpointFactory.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JGroupsFileBroadcastEndpointFactory.java index 894fa36be7..132ac3ca9c 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JGroupsFileBroadcastEndpointFactory.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JGroupsFileBroadcastEndpointFactory.java @@ -16,36 +16,31 @@ */ package org.apache.activemq.artemis.api.core; -public class JGroupsFileBroadcastEndpointFactory implements BroadcastEndpointFactory -{ +public class JGroupsFileBroadcastEndpointFactory implements BroadcastEndpointFactory { + private String file; private String channelName; @Override - public BroadcastEndpoint createBroadcastEndpoint() throws Exception - { + public BroadcastEndpoint createBroadcastEndpoint() throws Exception { return new JGroupsFileBroadcastEndpoint(file, channelName).initChannel(); } - public String getFile() - { + public String getFile() { return file; } - public JGroupsFileBroadcastEndpointFactory setFile(String file) - { + public JGroupsFileBroadcastEndpointFactory setFile(String file) { this.file = file; return this; } - public String getChannelName() - { + public String getChannelName() { return channelName; } - public JGroupsFileBroadcastEndpointFactory setChannelName(String channelName) - { + public JGroupsFileBroadcastEndpointFactory setChannelName(String channelName) { this.channelName = channelName; return this; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JGroupsPropertiesBroadcastEndpoint.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JGroupsPropertiesBroadcastEndpoint.java index 8650ed50ce..25cefc3789 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JGroupsPropertiesBroadcastEndpoint.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JGroupsPropertiesBroadcastEndpoint.java @@ -22,19 +22,17 @@ import org.jgroups.conf.PlainConfigurator; /** * This class is the implementation of ActiveMQ Artemis members discovery that will use JGroups. */ -public final class JGroupsPropertiesBroadcastEndpoint extends JGroupsBroadcastEndpoint -{ +public final class JGroupsPropertiesBroadcastEndpoint extends JGroupsBroadcastEndpoint { + private String properties; - public JGroupsPropertiesBroadcastEndpoint(final String properties, final String channelName) throws Exception - { + public JGroupsPropertiesBroadcastEndpoint(final String properties, final String channelName) throws Exception { super(channelName); this.properties = properties; } @Override - public JChannel createChannel() throws Exception - { + public JChannel createChannel() throws Exception { PlainConfigurator configurator = new PlainConfigurator(properties); return new JChannel(configurator); } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JGroupsPropertiesBroadcastEndpointFactory.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JGroupsPropertiesBroadcastEndpointFactory.java index b58b69aa33..4d804354fa 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JGroupsPropertiesBroadcastEndpointFactory.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JGroupsPropertiesBroadcastEndpointFactory.java @@ -16,36 +16,31 @@ */ package org.apache.activemq.artemis.api.core; -public class JGroupsPropertiesBroadcastEndpointFactory implements BroadcastEndpointFactory -{ +public class JGroupsPropertiesBroadcastEndpointFactory implements BroadcastEndpointFactory { + private String properties; private String channelName; @Override - public BroadcastEndpoint createBroadcastEndpoint() throws Exception - { + public BroadcastEndpoint createBroadcastEndpoint() throws Exception { return new JGroupsPropertiesBroadcastEndpoint(properties, channelName).initChannel(); } - public String getProperties() - { + public String getProperties() { return properties; } - public JGroupsPropertiesBroadcastEndpointFactory setProperties(String properties) - { + public JGroupsPropertiesBroadcastEndpointFactory setProperties(String properties) { this.properties = properties; return this; } - public String getChannelName() - { + public String getChannelName() { return channelName; } - public JGroupsPropertiesBroadcastEndpointFactory setChannelName(String channelName) - { + public JGroupsPropertiesBroadcastEndpointFactory setChannelName(String channelName) { this.channelName = channelName; return this; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/Message.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/Message.java index 20830ad586..4c2d742604 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/Message.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/Message.java @@ -21,7 +21,6 @@ import java.util.Set; import org.apache.activemq.artemis.utils.UUID; - /** * A Message is a routable instance that has a payload. *

@@ -50,8 +49,8 @@ import org.apache.activemq.artemis.utils.UUID; * If conversion is not allowed (for example calling {@code getFloatProperty} on a property set a * {@code boolean}), a {@link ActiveMQPropertyConversionException} will be thrown. */ -public interface Message -{ +public interface Message { + SimpleString HDR_ACTUAL_EXPIRY_TIME = new SimpleString("_AMQ_ACTUAL_EXPIRY"); SimpleString HDR_ORIGINAL_ADDRESS = new SimpleString("_AMQ_ORIG_ADDRESS"); @@ -372,7 +371,7 @@ public interface Message * @param key property name * @param value property value * @throws ActiveMQPropertyConversionException if the value is not one of the accepted property - * types. + * types. */ Message putObjectProperty(SimpleString key, Object value) throws ActiveMQPropertyConversionException; @@ -389,7 +388,6 @@ public interface Message */ Object removeProperty(SimpleString key); - /** * @see #removeProperty(SimpleString) */ diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/TransportConfiguration.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/TransportConfiguration.java index 982a424eee..a1e25315c9 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/TransportConfiguration.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/TransportConfiguration.java @@ -41,8 +41,8 @@ import org.apache.activemq.artemis.utils.UUIDGenerator; * ClientSessionFactory sf = new ClientSessionFactoryImpl(config); * */ -public class TransportConfiguration implements Serializable -{ +public class TransportConfiguration implements Serializable { + private static final long serialVersionUID = -3994528421527392679L; private String name; @@ -65,16 +65,13 @@ public class TransportConfiguration implements Serializable * @param commaSeparatedHosts the comma separated host string * @return the hosts */ - public static String[] splitHosts(final String commaSeparatedHosts) - { - if (commaSeparatedHosts == null) - { + public static String[] splitHosts(final String commaSeparatedHosts) { + if (commaSeparatedHosts == null) { return new String[0]; } String[] hosts = commaSeparatedHosts.split(","); - for (int i = 0; i < hosts.length; i++) - { + for (int i = 0; i < hosts.length; i++) { hosts[i] = hosts[i].trim(); } return hosts; @@ -83,8 +80,7 @@ public class TransportConfiguration implements Serializable /** * Creates a default TransportConfiguration with no configured transport. */ - public TransportConfiguration() - { + public TransportConfiguration() { this.params = new HashMap<>(); } @@ -96,16 +92,13 @@ public class TransportConfiguration implements Serializable * @param params The parameters needed by the ConnectorFactory * @param name The name of this TransportConfiguration */ - public TransportConfiguration(final String className, final Map params, final String name) - { + public TransportConfiguration(final String className, final Map params, final String name) { factoryClassName = className; - if (params == null || params.isEmpty()) - { + if (params == null || params.isEmpty()) { this.params = TransportConfigurationUtil.getDefaults(className); } - else - { + else { this.params = params; } @@ -119,8 +112,7 @@ public class TransportConfiguration implements Serializable * @param className The class name of the ConnectorFactory * @param params The parameters needed by the ConnectorFactory */ - public TransportConfiguration(final String className, final Map params) - { + public TransportConfiguration(final String className, final Map params) { this(className, params, UUIDGenerator.getInstance().generateStringUUID()); } @@ -129,8 +121,7 @@ public class TransportConfiguration implements Serializable * * @param className The class name of the ConnectorFactory */ - public TransportConfiguration(final String className) - { + public TransportConfiguration(final String className) { this(className, new HashMap(), UUIDGenerator.getInstance().generateStringUUID()); } @@ -139,8 +130,7 @@ public class TransportConfiguration implements Serializable * * @return the name */ - public String getName() - { + public String getName() { return name; } @@ -149,8 +139,7 @@ public class TransportConfiguration implements Serializable * * @return The factory's class name */ - public String getFactoryClassName() - { + public String getFactoryClassName() { return factoryClassName; } @@ -159,62 +148,49 @@ public class TransportConfiguration implements Serializable * * @return the parameters */ - public Map getParams() - { + public Map getParams() { return params; } @Override - public int hashCode() - { + public int hashCode() { return factoryClassName.hashCode(); } @Override - public boolean equals(final Object other) - { - if (other instanceof TransportConfiguration == false) - { + public boolean equals(final Object other) { + if (other instanceof TransportConfiguration == false) { return false; } TransportConfiguration kother = (TransportConfiguration) other; - if (factoryClassName.equals(kother.factoryClassName)) - { - if (params == null || params.isEmpty()) - { + if (factoryClassName.equals(kother.factoryClassName)) { + if (params == null || params.isEmpty()) { return kother.params == null || kother.params.isEmpty(); } - else - { - if (kother.params == null || kother.params.isEmpty()) - { + else { + if (kother.params == null || kother.params.isEmpty()) { return false; } - else if (params.size() == kother.params.size()) - { - for (Map.Entry entry : params.entrySet()) - { + else if (params.size() == kother.params.size()) { + for (Map.Entry entry : params.entrySet()) { Object thisVal = entry.getValue(); Object otherVal = kother.params.get(entry.getKey()); - if (otherVal == null || !otherVal.equals(thisVal)) - { + if (otherVal == null || !otherVal.equals(thisVal)) { return false; } } return true; } - else - { + else { return false; } } } - else - { + else { return false; } } @@ -224,48 +200,39 @@ public class TransportConfiguration implements Serializable * use a Netty Cluster Connection on an InVM ClusterConnection (inVM used on tests) for that * reason I need to test if the two instances of the TransportConfiguration are equivalent while * a test a connector against an acceptor + * * @param otherConfig * @return {@code true} if the factory class names are equivalents */ - public boolean isEquivalent(TransportConfiguration otherConfig) - { - if (this.getFactoryClassName().equals(otherConfig.getFactoryClassName())) - { + public boolean isEquivalent(TransportConfiguration otherConfig) { + if (this.getFactoryClassName().equals(otherConfig.getFactoryClassName())) { return true; } - else if (this.getFactoryClassName().contains("Netty") && otherConfig.getFactoryClassName().contains("Netty")) - { + else if (this.getFactoryClassName().contains("Netty") && otherConfig.getFactoryClassName().contains("Netty")) { return true; } - else if (this.getFactoryClassName().contains("InVM") && otherConfig.getFactoryClassName().contains("InVM")) - { + else if (this.getFactoryClassName().contains("InVM") && otherConfig.getFactoryClassName().contains("InVM")) { return true; } - else - { + else { return false; } } @Override - public String toString() - { + public String toString() { StringBuilder str = new StringBuilder(TransportConfiguration.class.getSimpleName()); str.append("(name=" + name + ", "); str.append("factory=" + replaceWildcardChars(factoryClassName)); str.append(") "); - if (params != null) - { - if (!params.isEmpty()) - { + if (params != null) { + if (!params.isEmpty()) { str.append("?"); } boolean first = true; - for (Map.Entry entry : params.entrySet()) - { - if (!first) - { + for (Map.Entry entry : params.entrySet()) { + if (!first) { str.append("&"); } @@ -273,12 +240,10 @@ public class TransportConfiguration implements Serializable // HORNETQ-1281 - don't log passwords String val; - if (key.equals(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME) || key.equals(TransportConstants.DEFAULT_TRUSTSTORE_PASSWORD)) - { + if (key.equals(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME) || key.equals(TransportConstants.DEFAULT_TRUSTSTORE_PASSWORD)) { val = "****"; } - else - { + else { val = entry.getValue() == null ? "null" : entry.getValue().toString(); } @@ -297,43 +262,35 @@ public class TransportConfiguration implements Serializable * * @param buffer the buffer to encode into */ - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { buffer.writeString(name); buffer.writeString(factoryClassName); buffer.writeInt(params == null ? 0 : params.size()); - if (params != null) - { - for (Map.Entry entry : params.entrySet()) - { + if (params != null) { + for (Map.Entry entry : params.entrySet()) { buffer.writeString(entry.getKey()); Object val = entry.getValue(); - if (val instanceof Boolean) - { + if (val instanceof Boolean) { buffer.writeByte(TransportConfiguration.TYPE_BOOLEAN); buffer.writeBoolean((Boolean) val); } - else if (val instanceof Integer) - { + else if (val instanceof Integer) { buffer.writeByte(TransportConfiguration.TYPE_INT); buffer.writeInt((Integer) val); } - else if (val instanceof Long) - { + else if (val instanceof Long) { buffer.writeByte(TransportConfiguration.TYPE_LONG); buffer.writeLong((Long) val); } - else if (val instanceof String) - { + else if (val instanceof String) { buffer.writeByte(TransportConfiguration.TYPE_STRING); buffer.writeString((String) val); } - else - { + else { throw ActiveMQClientMessageBundle.BUNDLE.invalidEncodeType(val); } } @@ -347,61 +304,50 @@ public class TransportConfiguration implements Serializable * * @param buffer the buffer to decode from */ - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { name = buffer.readString(); factoryClassName = buffer.readString(); int num = buffer.readInt(); - if (params == null) - { - if (num > 0) - { + if (params == null) { + if (num > 0) { params = new HashMap(); } } - else - { + else { params.clear(); } - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { String key = buffer.readString(); byte type = buffer.readByte(); Object val; - switch (type) - { - case TYPE_BOOLEAN: - { + switch (type) { + case TYPE_BOOLEAN: { val = buffer.readBoolean(); break; } - case TYPE_INT: - { + case TYPE_INT: { val = buffer.readInt(); break; } - case TYPE_LONG: - { + case TYPE_LONG: { val = buffer.readLong(); break; } - case TYPE_STRING: - { + case TYPE_STRING: { val = buffer.readString(); break; } - default: - { + default: { throw ActiveMQClientMessageBundle.BUNDLE.invalidType(type); } } @@ -410,8 +356,7 @@ public class TransportConfiguration implements Serializable } } - private static String replaceWildcardChars(final String str) - { + private static String replaceWildcardChars(final String str) { return str.replace('.', '-'); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/TransportConfigurationHelper.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/TransportConfigurationHelper.java index fa1855f12d..09b5653f17 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/TransportConfigurationHelper.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/TransportConfigurationHelper.java @@ -21,7 +21,7 @@ import java.util.Map; /** * Helper interface for specifying default parameters on Transport Configurations. */ -public interface TransportConfigurationHelper -{ +public interface TransportConfigurationHelper { + Map getDefaults(); } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/UDPBroadcastEndpointFactory.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/UDPBroadcastEndpointFactory.java index 17c4b047f4..193bd315e4 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/UDPBroadcastEndpointFactory.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/UDPBroadcastEndpointFactory.java @@ -28,14 +28,13 @@ import java.util.concurrent.TimeUnit; import org.apache.activemq.artemis.core.client.ActiveMQClientLogger; - /** * The configuration used to determine how the server will broadcast members. *

* This is analogous to {@link DiscoveryGroupConfiguration} */ -public final class UDPBroadcastEndpointFactory implements BroadcastEndpointFactory -{ +public final class UDPBroadcastEndpointFactory implements BroadcastEndpointFactory { + private transient String localBindAddress = null; private transient int localBindPort = -1; @@ -44,59 +43,45 @@ public final class UDPBroadcastEndpointFactory implements BroadcastEndpointFacto private int groupPort = -1; - public UDPBroadcastEndpointFactory() - { + public UDPBroadcastEndpointFactory() { } - public BroadcastEndpoint createBroadcastEndpoint() throws Exception - { - return new UDPBroadcastEndpoint() - .setGroupAddress(groupAddress != null ? InetAddress.getByName(groupAddress) : null) - .setGroupPort(groupPort) - .setLocalBindAddress(localBindAddress != null ? InetAddress.getByName(localBindAddress) : null) - .setLocalBindPort(localBindPort); + public BroadcastEndpoint createBroadcastEndpoint() throws Exception { + return new UDPBroadcastEndpoint().setGroupAddress(groupAddress != null ? InetAddress.getByName(groupAddress) : null).setGroupPort(groupPort).setLocalBindAddress(localBindAddress != null ? InetAddress.getByName(localBindAddress) : null).setLocalBindPort(localBindPort); } - public String getGroupAddress() - { + public String getGroupAddress() { return groupAddress; } - public UDPBroadcastEndpointFactory setGroupAddress(String groupAddress) - { + public UDPBroadcastEndpointFactory setGroupAddress(String groupAddress) { this.groupAddress = groupAddress; return this; } - public int getGroupPort() - { + public int getGroupPort() { return groupPort; } - public UDPBroadcastEndpointFactory setGroupPort(int groupPort) - { + public UDPBroadcastEndpointFactory setGroupPort(int groupPort) { this.groupPort = groupPort; return this; } - public int getLocalBindPort() - { + public int getLocalBindPort() { return localBindPort; } - public UDPBroadcastEndpointFactory setLocalBindPort(int localBindPort) - { + public UDPBroadcastEndpointFactory setLocalBindPort(int localBindPort) { this.localBindPort = localBindPort; return this; } - public String getLocalBindAddress() - { + public String getLocalBindAddress() { return localBindAddress; } - public UDPBroadcastEndpointFactory setLocalBindAddress(String localBindAddress) - { + public UDPBroadcastEndpointFactory setLocalBindAddress(String localBindAddress) { this.localBindAddress = localBindAddress; return this; } @@ -105,8 +90,8 @@ public final class UDPBroadcastEndpointFactory implements BroadcastEndpointFacto *

This is the member discovery implementation using direct UDP. It was extracted as a refactoring from * {@link org.apache.activemq.artemis.core.cluster.DiscoveryGroup}

*/ - private static class UDPBroadcastEndpoint implements BroadcastEndpoint - { + private static class UDPBroadcastEndpoint implements BroadcastEndpoint { + private static final int SOCKET_TIMEOUT = 500; private InetAddress localAddress; @@ -123,61 +108,48 @@ public final class UDPBroadcastEndpointFactory implements BroadcastEndpointFacto private volatile boolean open; - public UDPBroadcastEndpoint() - { + public UDPBroadcastEndpoint() { } - public UDPBroadcastEndpoint setGroupAddress(InetAddress groupAddress) - { + public UDPBroadcastEndpoint setGroupAddress(InetAddress groupAddress) { this.groupAddress = groupAddress; return this; } - public UDPBroadcastEndpoint setGroupPort(int groupPort) - { + public UDPBroadcastEndpoint setGroupPort(int groupPort) { this.groupPort = groupPort; return this; } - public UDPBroadcastEndpoint setLocalBindAddress(InetAddress localAddress) - { + public UDPBroadcastEndpoint setLocalBindAddress(InetAddress localAddress) { this.localAddress = localAddress; return this; } - public UDPBroadcastEndpoint setLocalBindPort(int localBindPort) - { + public UDPBroadcastEndpoint setLocalBindPort(int localBindPort) { this.localBindPort = localBindPort; return this; } - - public void broadcast(byte[] data) throws Exception - { + public void broadcast(byte[] data) throws Exception { DatagramPacket packet = new DatagramPacket(data, data.length, groupAddress, groupPort); broadcastingSocket.send(packet); } - public byte[] receiveBroadcast() throws Exception - { + public byte[] receiveBroadcast() throws Exception { final byte[] data = new byte[65535]; final DatagramPacket packet = new DatagramPacket(data, data.length); - while (open) - { - try - { + while (open) { + try { receivingSocket.receive(packet); } // TODO: Do we need this? - catch (InterruptedIOException e) - { + catch (InterruptedIOException e) { continue; } - catch (IOException e) - { - if (open) - { + catch (IOException e) { + if (open) { ActiveMQClientLogger.LOGGER.warn(this + " getting exception when receiving broadcasting.", e); } } @@ -186,23 +158,18 @@ public final class UDPBroadcastEndpointFactory implements BroadcastEndpointFacto return data; } - public byte[] receiveBroadcast(long time, TimeUnit unit) throws Exception - { + public byte[] receiveBroadcast(long time, TimeUnit unit) throws Exception { // We just use the regular method on UDP, there's no timeout support // and this is basically for tests only return receiveBroadcast(); } - public void openBroadcaster() throws Exception - { - if (localBindPort != -1) - { + public void openBroadcaster() throws Exception { + if (localBindPort != -1) { broadcastingSocket = new DatagramSocket(localBindPort, localAddress); } - else - { - if (localAddress != null) - { + else { + if (localAddress != null) { ActiveMQClientLogger.LOGGER.broadcastGroupBindError(); } broadcastingSocket = new DatagramSocket(); @@ -211,29 +178,23 @@ public final class UDPBroadcastEndpointFactory implements BroadcastEndpointFacto open = true; } - public void openClient() throws Exception - { + public void openClient() throws Exception { // HORNETQ-874 - if (checkForLinux() || checkForSolaris() || checkForHp()) - { - try - { + if (checkForLinux() || checkForSolaris() || checkForHp()) { + try { receivingSocket = new MulticastSocket(new InetSocketAddress(groupAddress, groupPort)); } - catch (IOException e) - { + catch (IOException e) { ActiveMQClientLogger.LOGGER.ioDiscoveryError(groupAddress.getHostAddress(), groupAddress instanceof Inet4Address ? "IPv4" : "IPv6"); receivingSocket = new MulticastSocket(groupPort); } } - else - { + else { receivingSocket = new MulticastSocket(groupPort); } - if (localAddress != null) - { + if (localAddress != null) { receivingSocket.setInterface(localAddress); } @@ -245,45 +206,36 @@ public final class UDPBroadcastEndpointFactory implements BroadcastEndpointFacto } //@Todo: using isBroadcast to share endpoint between broadcast and receiving - public void close(boolean isBroadcast) throws Exception - { + public void close(boolean isBroadcast) throws Exception { open = false; - if (broadcastingSocket != null) - { + if (broadcastingSocket != null) { broadcastingSocket.close(); } - if (receivingSocket != null) - { + if (receivingSocket != null) { receivingSocket.close(); } } - private static boolean checkForLinux() - { + private static boolean checkForLinux() { return checkForPresence("os.name", "linux"); } - private static boolean checkForHp() - { + private static boolean checkForHp() { return checkForPresence("os.name", "hp"); } - private static boolean checkForSolaris() - { + private static boolean checkForSolaris() { return checkForPresence("os.name", "sun"); } - private static boolean checkForPresence(String key, String value) - { - try - { + private static boolean checkForPresence(String key, String value) { + try { String tmp = System.getProperty(key); return tmp != null && tmp.trim().toLowerCase().startsWith(value); } - catch (Throwable t) - { + catch (Throwable t) { return false; } } @@ -291,8 +243,7 @@ public final class UDPBroadcastEndpointFactory implements BroadcastEndpointFacto } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((groupAddress == null) ? 0 : groupAddress.hashCode()); @@ -301,8 +252,7 @@ public final class UDPBroadcastEndpointFactory implements BroadcastEndpointFacto } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) @@ -310,8 +260,7 @@ public final class UDPBroadcastEndpointFactory implements BroadcastEndpointFacto if (getClass() != obj.getClass()) return false; UDPBroadcastEndpointFactory other = (UDPBroadcastEndpointFactory) obj; - if (groupAddress == null) - { + if (groupAddress == null) { if (other.groupAddress != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ActiveMQClient.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ActiveMQClient.java index 9619e7cb36..028b6c84f0 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ActiveMQClient.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ActiveMQClient.java @@ -32,8 +32,8 @@ import java.net.URI; * setter methods before creating the sessions. Once a session is created, the factory can no longer * be modified (its setter methods will throw a {@link IllegalStateException}. */ -public final class ActiveMQClient -{ +public final class ActiveMQClient { + public static final String DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME = RoundRobinConnectionLoadBalancingPolicy.class.getCanonicalName(); public static final long DEFAULT_CLIENT_FAILURE_CHECK_PERIOD = ActiveMQDefaultConfiguration.getDefaultClientFailureCheckPeriod(); @@ -119,8 +119,7 @@ public final class ActiveMQClient * * @return the ActiveMQConnectionFactory */ - public static ServerLocator createServerLocator(final String url) throws Exception - { + public static ServerLocator createServerLocator(final String url) throws Exception { ServerLocatorParser parser = new ServerLocatorParser(); return parser.newObject(new URI(url), null); } @@ -132,8 +131,7 @@ public final class ActiveMQClient * @param transportConfigurations * @return the ServerLocator */ - public static ServerLocator createServerLocatorWithoutHA(TransportConfiguration... transportConfigurations) - { + public static ServerLocator createServerLocatorWithoutHA(TransportConfiguration... transportConfigurations) { return new ServerLocatorImpl(false, transportConfigurations); } @@ -141,12 +139,12 @@ public final class ActiveMQClient * Create a ServerLocator which creates session factories using a static list of transportConfigurations, the ServerLocator is not updated automatically * as the cluster topology changes, and no HA backup information is propagated to the client * - * @param ha The Locator will support topology updates and ha (this required the server to be clustered, otherwise the first connection will timeout) + * @param ha The Locator will support topology updates and ha (this required the server to be clustered, otherwise the first connection will timeout) * @param transportConfigurations * @return the ServerLocator */ - public static ServerLocator createServerLocator(final boolean ha, TransportConfiguration... transportConfigurations) - { + public static ServerLocator createServerLocator(final boolean ha, + TransportConfiguration... transportConfigurations) { return new ServerLocatorImpl(ha, transportConfigurations); } @@ -155,26 +153,26 @@ public final class ActiveMQClient * backup information is propagated to the client *

* The UDP address and port are used to listen for live servers in the cluster + * * @param groupConfiguration * @return the ServerLocator */ - public static ServerLocator createServerLocatorWithoutHA(final DiscoveryGroupConfiguration groupConfiguration) - { + public static ServerLocator createServerLocatorWithoutHA(final DiscoveryGroupConfiguration groupConfiguration) { return new ServerLocatorImpl(false, groupConfiguration); } - /** * Create a ServerLocator which creates session factories from a set of live servers, no HA * backup information is propagated to the client The UDP address and port are used to listen for * live servers in the cluster - * @param ha The Locator will support topology updates and ha (this required the server to be - * clustered, otherwise the first connection will timeout) + * + * @param ha The Locator will support topology updates and ha (this required the server to be + * clustered, otherwise the first connection will timeout) * @param groupConfiguration * @return the ServerLocator */ - public static ServerLocator createServerLocator(final boolean ha, final DiscoveryGroupConfiguration groupConfiguration) - { + public static ServerLocator createServerLocator(final boolean ha, + final DiscoveryGroupConfiguration groupConfiguration) { return new ServerLocatorImpl(ha, groupConfiguration); } @@ -188,13 +186,13 @@ public final class ActiveMQClient *

* If the topology includes backup servers that information is also propagated to the client so * that it can know which server to failover onto in case of live server failure. + * * @param initialServers The initial set of servers used to make a connection to the cluster. - * Each one is tried in turn until a successful connection is made. Once a connection - * is made, the cluster topology is downloaded and the rest of the list is ignored. + * Each one is tried in turn until a successful connection is made. Once a connection + * is made, the cluster topology is downloaded and the rest of the list is ignored. * @return the ServerLocator */ - public static ServerLocator createServerLocatorWithHA(TransportConfiguration... initialServers) - { + public static ServerLocator createServerLocatorWithHA(TransportConfiguration... initialServers) { return new ServerLocatorImpl(true, initialServers); } @@ -210,17 +208,15 @@ public final class ActiveMQClient *

* If the topology includes backup servers that information is also propagated to the client so * that it can know which server to failover onto in case of live server failure. + * * @param groupConfiguration * @return the ServerLocator */ - public static ServerLocator createServerLocatorWithHA(final DiscoveryGroupConfiguration groupConfiguration) - { + public static ServerLocator createServerLocatorWithHA(final DiscoveryGroupConfiguration groupConfiguration) { return new ServerLocatorImpl(true, groupConfiguration); } - - private ActiveMQClient() - { + private ActiveMQClient() { // Utility class } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClientConsumer.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClientConsumer.java index 7ab33d1680..0f0d5d1368 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClientConsumer.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClientConsumer.java @@ -31,12 +31,12 @@ import org.apache.activemq.artemis.spi.core.remoting.ConsumerContext; * * @see ClientSession#createConsumer(String) */ -public interface ClientConsumer extends AutoCloseable -{ +public interface ClientConsumer extends AutoCloseable { /** * The server's ID associated with this consumer. * ActiveMQ Artemis implements this as a long but this could be protocol dependent. + * * @return */ ConsumerContext getConsumerContext(); @@ -47,6 +47,7 @@ public interface ClientConsumer extends AutoCloseable * This call will block indefinitely until a message is received. *

* Calling this method on a closed consumer will throw an ActiveMQException. + * * @return a ClientMessage * @throws ActiveMQException if an exception occurs while waiting to receive a message */ @@ -58,6 +59,7 @@ public interface ClientConsumer extends AutoCloseable * This call will block until a message is received or the given timeout expires. *

* Calling this method on a closed consumer will throw an ActiveMQException. + * * @param timeout time (in milliseconds) to wait to receive a message * @return a message or {@code null} if the time out expired * @throws ActiveMQException if an exception occurs while waiting to receive a message @@ -75,6 +77,7 @@ public interface ClientConsumer extends AutoCloseable * required to check the queue status. *

* Calling this method on a closed consumer will throw an ActiveMQException. + * * @return a message or {@code null} if there are no messages in the queue for this consumer * @throws ActiveMQException if an exception occurs while waiting to receive a message */ @@ -84,6 +87,7 @@ public interface ClientConsumer extends AutoCloseable * Returns the MessageHandler associated to this consumer. *

* Calling this method on a closed consumer will throw an ActiveMQException. + * * @return the MessageHandler associated to this consumer or {@code null} * @throws ActiveMQException if an exception occurs while getting the MessageHandler */ @@ -93,6 +97,7 @@ public interface ClientConsumer extends AutoCloseable * Sets the MessageHandler for this consumer to consume messages asynchronously. *

* Calling this method on a closed consumer will throw a ActiveMQException. + * * @param handler a MessageHandler * @throws ActiveMQException if an exception occurs while setting the MessageHandler */ @@ -103,6 +108,7 @@ public interface ClientConsumer extends AutoCloseable *

* Once this consumer is closed, it can not receive messages, whether synchronously or * asynchronously. + * * @throws ActiveMQException */ void close() throws ActiveMQException; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClientMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClientMessage.java index f747119843..d206c56c32 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClientMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClientMessage.java @@ -24,11 +24,10 @@ import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.Message; /** - * * A ClientMessage represents a message sent and/or received by ActiveMQ Artemis. */ -public interface ClientMessage extends Message -{ +public interface ClientMessage extends Message { + /** * Returns the number of times this message was delivered. */ @@ -38,6 +37,7 @@ public interface ClientMessage extends Message * Sets the delivery count for this message. *

* This method is not meant to be called by ActiveMQ Artemis clients. + * * @param deliveryCount message delivery count * @return this ClientMessage */ @@ -49,6 +49,7 @@ public interface ClientMessage extends Message * If the session responsible to acknowledge this message has {@code autoCommitAcks} set to * {@code true}, the transaction will automatically commit the current transaction. Otherwise, * this acknowledgement will not be committed until the client commits the session transaction. + * * @throws ActiveMQException if an error occurred while acknowledging the message. * @see ClientSession#isAutoCommitAcks() */ @@ -60,6 +61,7 @@ public interface ClientMessage extends Message * If the session responsible to acknowledge this message has {@code autoCommitAcks} set to * {@code true}, the transaction will automatically commit the current transaction. Otherwise, * this acknowledgement will not be committed until the client commits the session transaction. + * * @throws ActiveMQException if an error occurred while acknowledging the message. * @see ClientSession#isAutoCommitAcks() */ @@ -71,6 +73,7 @@ public interface ClientMessage extends Message * The use case for this is to make sure there won't be an exception while getting the buffer. * Using getBodyBuffer directly would have the same effect but you could get a Runtime non checked Exception * instead + * * @throws ActiveMQException */ void checkCompletion() throws ActiveMQException; @@ -85,8 +88,8 @@ public interface ClientMessage extends Message *
* This method is used when consuming large messages * - * @throws ActiveMQException * @return this ClientMessage + * @throws ActiveMQException */ ClientMessage setOutputStream(OutputStream out) throws ActiveMQException; @@ -114,11 +117,11 @@ public interface ClientMessage extends Message * Sets the body's IntputStream. *
* This method is used when sending large messages + * * @return this ClientMessage */ ClientMessage setBodyInputStream(InputStream bodyInputStream); - /** * Overridden from {@link Message} to enable fluent API */ diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClientProducer.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClientProducer.java index d4b5a39652..6a30472eb5 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClientProducer.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClientProducer.java @@ -37,8 +37,8 @@ import org.apache.activemq.artemis.api.core.SimpleString; * {@link ServerLocator#setProducerWindowSize(int)}.
*
*/ -public interface ClientProducer extends AutoCloseable -{ +public interface ClientProducer extends AutoCloseable { + /** * Returns the address where messages will be sent. * @@ -58,6 +58,7 @@ public interface ClientProducer extends AutoCloseable * if {@link ServerLocator#setBlockOnDurableSend(boolean)} or * {@link ServerLocator#setBlockOnNonDurableSend(boolean)} are set to true for the * specified message type. + * * @param message the message to send * @throws ActiveMQException if an exception occurs while sending the message */ @@ -69,6 +70,7 @@ public interface ClientProducer extends AutoCloseable * This message will be sent asynchronously. *

* The handler will only get called if {@link ServerLocator#setConfirmationWindowSize(int) -1}. + * * @param message the message to send * @param handler handler to call after receiving a SEND acknowledgement from the server * @throws ActiveMQException if an exception occurs while sending the message @@ -82,6 +84,7 @@ public interface ClientProducer extends AutoCloseable * if {@link ServerLocator#setBlockOnDurableSend(boolean)} or * {@link ServerLocator#setBlockOnNonDurableSend(boolean)} are set to true for the specified * message type. + * * @param address the address where the message will be sent * @param message the message to send * @throws ActiveMQException if an exception occurs while sending the message @@ -94,6 +97,7 @@ public interface ClientProducer extends AutoCloseable * This message will be sent asynchronously. *

* The handler will only get called if {@link ServerLocator#setConfirmationWindowSize(int) -1}. + * * @param address the address where the message will be sent * @param message the message to send * @param handler handler to call after receiving a SEND acknowledgement from the server @@ -108,6 +112,7 @@ public interface ClientProducer extends AutoCloseable * if {@link ServerLocator#setBlockOnDurableSend(boolean)} or * {@link ServerLocator#setBlockOnNonDurableSend(boolean)} are set to true for the specified * message type. + * * @param address the address where the message will be sent * @param message the message to send * @throws ActiveMQException if an exception occurs while sending the message diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClientRequestor.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClientRequestor.java index f950982a9a..71a9ecf1ff 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClientRequestor.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClientRequestor.java @@ -27,8 +27,8 @@ import org.apache.activemq.artemis.core.client.impl.ClientMessageImpl; * The ClientRequestor constructor is given a ClientSession and a request address. * It creates a temporary queue for the responses and provides a request method that sends the request message and waits for its reply. */ -public final class ClientRequestor -{ +public final class ClientRequestor { + private final ClientSession queueSession; private final ClientProducer requestProducer; @@ -42,12 +42,11 @@ public final class ClientRequestor * * The implementation expects a ClientSession with automatic commits of sends and acknowledgements * - * @param session a ClientSession uses to handle requests and replies + * @param session a ClientSession uses to handle requests and replies * @param requestAddress the address to send request messages to * @throws Exception */ - public ClientRequestor(final ClientSession session, final SimpleString requestAddress) throws Exception - { + public ClientRequestor(final ClientSession session, final SimpleString requestAddress) throws Exception { queueSession = session; requestProducer = queueSession.createProducer(requestAddress); @@ -59,8 +58,7 @@ public final class ClientRequestor /** * @see ClientRequestor#ClientRequestor(ClientSession, SimpleString) */ - public ClientRequestor(final ClientSession session, final String requestAddress) throws Exception - { + public ClientRequestor(final ClientSession session, final String requestAddress) throws Exception { this(session, SimpleString.toSimpleString(requestAddress)); } @@ -72,8 +70,7 @@ public final class ClientRequestor * @return the reply message * @throws Exception */ - public ClientMessage request(final ClientMessage request) throws Exception - { + public ClientMessage request(final ClientMessage request) throws Exception { return request(request, 0); } @@ -81,13 +78,12 @@ public final class ClientRequestor * Sends a message to the request address and wait for the given timeout for a reply. * The temporary queue is used for the REPLYTO_HEADER_NAME, and only one reply per request is expected * - * @param request the message to send + * @param request the message to send * @param timeout the timeout to wait for a reply (in milliseconds) * @return the reply message or {@code null} if no message is replied before the timeout elapses * @throws Exception */ - public ClientMessage request(final ClientMessage request, final long timeout) throws Exception - { + public ClientMessage request(final ClientMessage request, final long timeout) throws Exception { request.putStringProperty(ClientMessageImpl.REPLYTO_HEADER_NAME, replyQueue); requestProducer.send(request); return replyConsumer.receive(timeout); @@ -98,8 +94,7 @@ public final class ClientRequestor * * @throws Exception if an exception occurs while closing the ClientRequestor */ - public void close() throws Exception - { + public void close() throws Exception { replyConsumer.close(); requestProducer.close(); queueSession.deleteQueue(replyQueue); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClientSession.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClientSession.java index c955858786..0df09b2d44 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClientSession.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClientSession.java @@ -25,8 +25,7 @@ import org.apache.activemq.artemis.api.core.SimpleString; /** * A ClientSession is a single-thread object required for producing and consuming messages. */ -public interface ClientSession extends XAResource, AutoCloseable -{ +public interface ClientSession extends XAResource, AutoCloseable { /** * This is used to identify a ClientSession as used by the JMS Layer @@ -35,7 +34,6 @@ public interface ClientSession extends XAResource, AutoCloseable */ String JMS_SESSION_IDENTIFIER_PROPERTY = "jms-session"; - /** * Just like {@link ClientSession.AddressQuery#JMS_SESSION_IDENTIFIER_PROPERTY} this is * used to identify the ClientID over JMS Session. @@ -44,15 +42,13 @@ public interface ClientSession extends XAResource, AutoCloseable */ String JMS_SESSION_CLIENT_ID_PROPERTY = "jms-client-id"; - - /** * Information returned by a binding query * * @see ClientSession#addressQuery(SimpleString) */ - public interface AddressQuery - { + public interface AddressQuery { + /** * Returns true if the binding exists, false else. */ @@ -75,8 +71,8 @@ public interface ClientSession extends XAResource, AutoCloseable * * @see ClientSession#queueQuery(SimpleString) */ - public interface QueueQuery - { + public interface QueueQuery { + /** * Returns true if the queue exists, false else. */ @@ -188,7 +184,6 @@ public interface ClientSession extends XAResource, AutoCloseable */ boolean removeFailoverListener(FailoverEventListener listener); - /** * Returns the server's incrementingVersion. * @@ -231,7 +226,10 @@ public interface ClientSession extends XAResource, AutoCloseable * @param durable if the queue is durable * @throws ActiveMQException in an exception occurs while creating the queue */ - void createSharedQueue(SimpleString address, SimpleString queueName, SimpleString filter, boolean durable) throws ActiveMQException; + void createSharedQueue(SimpleString address, + SimpleString queueName, + SimpleString filter, + boolean durable) throws ActiveMQException; /** * Creates a non-temporary queue. @@ -270,7 +268,10 @@ public interface ClientSession extends XAResource, AutoCloseable * @param durable whether the queue is durable or not * @throws ActiveMQException in an exception occurs while creating the queue */ - void createQueue(SimpleString address, SimpleString queueName, SimpleString filter, boolean durable) throws ActiveMQException; + void createQueue(SimpleString address, + SimpleString queueName, + SimpleString filter, + boolean durable) throws ActiveMQException; /** * Creates a non-temporaryqueue. @@ -309,7 +310,9 @@ public interface ClientSession extends XAResource, AutoCloseable * @param filter only messages which match this filter will be put in the queue * @throws ActiveMQException in an exception occurs while creating the queue */ - void createTemporaryQueue(SimpleString address, SimpleString queueName, SimpleString filter) throws ActiveMQException; + void createTemporaryQueue(SimpleString address, + SimpleString queueName, + SimpleString filter) throws ActiveMQException; /** * Creates a temporary queue with a filter. @@ -451,7 +454,9 @@ public interface ClientSession extends XAResource, AutoCloseable * @return a ClientConsumer * @throws ActiveMQException if an exception occurs while creating the ClientConsumer */ - ClientConsumer createConsumer(SimpleString queueName, SimpleString filter, boolean browseOnly) throws ActiveMQException; + ClientConsumer createConsumer(SimpleString queueName, + SimpleString filter, + boolean browseOnly) throws ActiveMQException; /** * Creates a ClientConsumer to consume or browse messages matching the filter from the queue with @@ -499,7 +504,11 @@ public interface ClientSession extends XAResource, AutoCloseable * @return a ClientConsumer * @throws ActiveMQException if an exception occurs while creating the ClientConsumer */ - ClientConsumer createConsumer(String queueName, String filter, int windowSize, int maxRate, boolean browseOnly) throws ActiveMQException; + ClientConsumer createConsumer(String queueName, + String filter, + int windowSize, + int maxRate, + boolean browseOnly) throws ActiveMQException; // Producer Operations ------------------------------------------- diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClientSessionFactory.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClientSessionFactory.java index 6a119aab0d..ae8315f856 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClientSessionFactory.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClientSessionFactory.java @@ -20,15 +20,14 @@ import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; - /** * A ClientSessionFactory is the entry point to create and configure ActiveMQ Artemis resources to produce and consume messages. *
* It is possible to configure a factory using the setter methods only if no session has been created. * Once a session is created, the configuration is fixed and any call to a setter method will throw an IllegalStateException. */ -public interface ClientSessionFactory extends AutoCloseable -{ +public interface ClientSessionFactory extends AutoCloseable { + /** * Creates a session with XA transaction semantics. * @@ -48,7 +47,6 @@ public interface ClientSessionFactory extends AutoCloseable */ ClientSession createTransactedSession() throws ActiveMQException; - /** * Creates a non-transacted session. * Message sends and acknowledgements are automatically committed by the session. This does not @@ -79,7 +77,9 @@ public interface ClientSessionFactory extends AutoCloseable * @return a ClientSession * @throws ActiveMQException if an exception occurs while creating the session */ - ClientSession createSession(boolean autoCommitSends, boolean autoCommitAcks, int ackBatchSize) throws ActiveMQException; + ClientSession createSession(boolean autoCommitSends, + boolean autoCommitAcks, + int ackBatchSize) throws ActiveMQException; /** * Creates a session. @@ -106,7 +106,10 @@ public interface ClientSessionFactory extends AutoCloseable * @return a ClientSession * @throws ActiveMQException if an exception occurs while creating the session */ - ClientSession createSession(boolean xa, boolean autoCommitSends, boolean autoCommitAcks, boolean preAcknowledge) throws ActiveMQException; + ClientSession createSession(boolean xa, + boolean autoCommitSends, + boolean autoCommitAcks, + boolean preAcknowledge) throws ActiveMQException; /** * Creates an authenticated session. @@ -175,9 +178,9 @@ public interface ClientSessionFactory extends AutoCloseable */ RemotingConnection getConnection(); - /** * Return the configuration used + * * @return */ TransportConfiguration getConnectorConfiguration(); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClusterTopologyListener.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClusterTopologyListener.java index 26c86429fc..4617e5bd8b 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClusterTopologyListener.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ClusterTopologyListener.java @@ -23,21 +23,23 @@ package org.apache.activemq.artemis.api.core.client; * the listener receives {@link #nodeUP(TopologyMember, boolean)} for all the current topology * members. */ -public interface ClusterTopologyListener -{ +public interface ClusterTopologyListener { + /** * Triggered when a node joins the cluster. + * * @param member - * @param last if the whole cluster topology is being transmitted (after adding the listener to - * the cluster connection) this parameter will be {@code true} for the last topology - * member. + * @param last if the whole cluster topology is being transmitted (after adding the listener to + * the cluster connection) this parameter will be {@code true} for the last topology + * member. */ void nodeUP(TopologyMember member, boolean last); /** * Triggered when a node leaves the cluster. + * * @param eventUID - * @param nodeID the id of the node leaving the cluster + * @param nodeID the id of the node leaving the cluster */ void nodeDown(long eventUID, String nodeID); } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/FailoverEventListener.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/FailoverEventListener.java index 8435b0ce9a..dae0e6a873 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/FailoverEventListener.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/FailoverEventListener.java @@ -19,8 +19,8 @@ package org.apache.activemq.artemis.api.core.client; /** * A FailoverEvent notifies the client the state if the connection changes occurred on the session. */ -public interface FailoverEventListener -{ +public interface FailoverEventListener { + /** * Notifies that a connection state has changed according the specified event type.
* This method is called when failover is detected, if it fails and when it's completed diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/FailoverEventType.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/FailoverEventType.java index 9176b8f9f9..984e187694 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/FailoverEventType.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/FailoverEventType.java @@ -16,8 +16,7 @@ */ package org.apache.activemq.artemis.api.core.client; -public enum FailoverEventType -{ +public enum FailoverEventType { FAILURE_DETECTED, FAILOVER_COMPLETED, FAILOVER_FAILED; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/MessageHandler.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/MessageHandler.java index 88b7155b8f..4f39d1cc5b 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/MessageHandler.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/MessageHandler.java @@ -21,10 +21,11 @@ package org.apache.activemq.artemis.api.core.client; *

* To receive messages asynchronously, a MessageHandler is set on a ClientConsumer. Every time the * consumer will receive a message, it will call the handler's {@code onMessage()} method. + * * @see ClientConsumer#setMessageHandler(MessageHandler) */ -public interface MessageHandler -{ +public interface MessageHandler { + /** * Notifies the MessageHandler that a message has been received. * diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/SendAcknowledgementHandler.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/SendAcknowledgementHandler.java index 5d7c466c7d..c164f6cdf2 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/SendAcknowledgementHandler.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/SendAcknowledgementHandler.java @@ -33,8 +33,8 @@ import org.apache.activemq.artemis.api.core.Message; * Notice that this notification will only take place if {@code ConfirmationWindowSize} is set to a * positive value at {@link ServerLocator#setConfirmationWindowSize(int)}. */ -public interface SendAcknowledgementHandler -{ +public interface SendAcknowledgementHandler { + /** * Notifies the client that a message sent asynchronously has been received by the server. * diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ServerLocator.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ServerLocator.java index da0c660797..8f086c6bb1 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ServerLocator.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ServerLocator.java @@ -33,8 +33,7 @@ import org.apache.activemq.artemis.spi.core.remoting.ClientProtocolManagerFactor * grouping finder, after the initial connection is made the server will always send updates to the * client. But the listeners will listen for updates on grouping. */ -public interface ServerLocator extends AutoCloseable -{ +public interface ServerLocator extends AutoCloseable { /** * Returns true if close was already called @@ -98,7 +97,9 @@ public interface ServerLocator extends AutoCloseable * @throws Exception if a failure happened in creating the ClientSessionFactory or the * ServerLocator does not know about the passed in transportConfiguration */ - ClientSessionFactory createSessionFactory(final TransportConfiguration transportConfiguration, int reconnectAttempts, boolean failoverOnInitialConnection) throws Exception; + ClientSessionFactory createSessionFactory(final TransportConfiguration transportConfiguration, + int reconnectAttempts, + boolean failoverOnInitialConnection) throws Exception; /** * Returns the period used to check if a client has failed to receive pings from the server. @@ -184,7 +185,6 @@ public interface ServerLocator extends AutoCloseable */ ServerLocator setCallTimeout(long callTimeout); - /** * Returns the blocking calls failover timeout when the client is awaiting failover, * this is over and above the normal call timeout. @@ -741,6 +741,7 @@ public interface ServerLocator extends AutoCloseable /** * Verify if all of the transports are using inVM. + * * @return {@code true} if the locator has all inVM transports. */ boolean allInVM(); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/SessionFailureListener.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/SessionFailureListener.java index aba6f423be..011cee1de0 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/SessionFailureListener.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/SessionFailureListener.java @@ -22,8 +22,8 @@ import org.apache.activemq.artemis.core.remoting.FailureListener; /** * A SessionFailureListener notifies the client when a failure occurred on the session. */ -public interface SessionFailureListener extends FailureListener -{ +public interface SessionFailureListener extends FailureListener { + /** * Notifies that a connection has failed due to the specified exception. *
diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/TopologyMember.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/TopologyMember.java index 84d67218f3..26de0dc2c5 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/TopologyMember.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/TopologyMember.java @@ -25,8 +25,8 @@ import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; * Each TopologyMember represents a single server and possibly any backup server that may take over * its duties (using the nodeId of the original server). */ -public interface TopologyMember -{ +public interface TopologyMember { + /** * Returns the {@code backup-group-name} of the live server and backup servers associated with * Topology entry. diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/loadbalance/ConnectionLoadBalancingPolicy.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/loadbalance/ConnectionLoadBalancingPolicy.java index c5405e9267..fa4f372d72 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/loadbalance/ConnectionLoadBalancingPolicy.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/loadbalance/ConnectionLoadBalancingPolicy.java @@ -19,8 +19,8 @@ package org.apache.activemq.artemis.api.core.client.loadbalance; /** * A ConnectionLoadBalancingPolicy defines a policy to load balance between connections. */ -public interface ConnectionLoadBalancingPolicy -{ +public interface ConnectionLoadBalancingPolicy { + /** * Returns the selected index according to the policy implementation. * diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/loadbalance/FirstElementConnectionLoadBalancingPolicy.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/loadbalance/FirstElementConnectionLoadBalancingPolicy.java index 19947e67eb..2373879fab 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/loadbalance/FirstElementConnectionLoadBalancingPolicy.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/loadbalance/FirstElementConnectionLoadBalancingPolicy.java @@ -16,18 +16,16 @@ */ package org.apache.activemq.artemis.api.core.client.loadbalance; - /** * A {@link FirstElementConnectionLoadBalancingPolicy#select(int)} always returns 0. */ -public final class FirstElementConnectionLoadBalancingPolicy implements ConnectionLoadBalancingPolicy -{ +public final class FirstElementConnectionLoadBalancingPolicy implements ConnectionLoadBalancingPolicy { + /** * @param max param is ignored * @return 0 */ - public int select(final int max) - { + public int select(final int max) { return 0; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/loadbalance/RandomConnectionLoadBalancingPolicy.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/loadbalance/RandomConnectionLoadBalancingPolicy.java index 1710186591..e672b1bda9 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/loadbalance/RandomConnectionLoadBalancingPolicy.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/loadbalance/RandomConnectionLoadBalancingPolicy.java @@ -22,17 +22,17 @@ import org.apache.activemq.artemis.utils.Random; * {@link RandomConnectionLoadBalancingPolicy#select(int)} returns a (pseudo) random integer between * {@code 0} (inclusive) and {@code max} (exclusive). */ -public final class RandomConnectionLoadBalancingPolicy implements ConnectionLoadBalancingPolicy -{ +public final class RandomConnectionLoadBalancingPolicy implements ConnectionLoadBalancingPolicy { + private final Random random = new Random(); /** * Returns a pseudo random number between {@code 0} (inclusive) and {@code max} exclusive. + * * @param max the upper limit of the random number selection * @see java.util.Random#nextInt(int) */ - public int select(final int max) - { + public int select(final int max) { return random.getRandom().nextInt(max); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/loadbalance/RandomStickyConnectionLoadBalancingPolicy.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/loadbalance/RandomStickyConnectionLoadBalancingPolicy.java index 3ce479ba37..556d33ff80 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/loadbalance/RandomStickyConnectionLoadBalancingPolicy.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/loadbalance/RandomStickyConnectionLoadBalancingPolicy.java @@ -21,8 +21,8 @@ import org.apache.activemq.artemis.utils.Random; /** * {@link RandomConnectionLoadBalancingPolicy#select(int)} chooses a the initial node randomly then subsequent requests return the same node */ -public final class RandomStickyConnectionLoadBalancingPolicy implements ConnectionLoadBalancingPolicy -{ +public final class RandomStickyConnectionLoadBalancingPolicy implements ConnectionLoadBalancingPolicy { + private final Random random = new Random(); private int pos = -1; @@ -30,10 +30,8 @@ public final class RandomStickyConnectionLoadBalancingPolicy implements Connecti /** * @see java.util.Random#nextInt(int) */ - public int select(final int max) - { - if (pos == -1) - { + public int select(final int max) { + if (pos == -1) { pos = random.getRandom().nextInt(max); } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/loadbalance/RoundRobinConnectionLoadBalancingPolicy.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/loadbalance/RoundRobinConnectionLoadBalancingPolicy.java index 40e0242ca5..1af74f49d5 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/loadbalance/RoundRobinConnectionLoadBalancingPolicy.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/loadbalance/RoundRobinConnectionLoadBalancingPolicy.java @@ -27,8 +27,8 @@ import org.apache.activemq.artemis.utils.Random; * The first call to {@link #select(int)} will return a random integer between {@code 0} (inclusive) and {@code max} (exclusive). * Subsequent calls will then return an integer in a round-robin fashion. */ -public final class RoundRobinConnectionLoadBalancingPolicy implements ConnectionLoadBalancingPolicy, Serializable -{ +public final class RoundRobinConnectionLoadBalancingPolicy implements ConnectionLoadBalancingPolicy, Serializable { + private static final long serialVersionUID = 7511196010141439559L; private final Random random = new Random(); @@ -37,21 +37,17 @@ public final class RoundRobinConnectionLoadBalancingPolicy implements Connection private int pos; - public int select(final int max) - { - if (first) - { + public int select(final int max) { + if (first) { // We start on a random one pos = random.getRandom().nextInt(max); first = false; } - else - { + else { pos++; - if (pos >= max) - { + if (pos >= max) { pos = 0; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/AcceptorControl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/AcceptorControl.java index 28061823e0..590850d374 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/AcceptorControl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/AcceptorControl.java @@ -21,8 +21,8 @@ import java.util.Map; /** * An AcceptorControl is used to manage Acceptors. */ -public interface AcceptorControl extends ActiveMQComponentControl -{ +public interface AcceptorControl extends ActiveMQComponentControl { + /** * Returns the name of the acceptor */ diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ActiveMQComponentControl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ActiveMQComponentControl.java index 0343439fc9..3fe0660cce 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ActiveMQComponentControl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ActiveMQComponentControl.java @@ -19,8 +19,8 @@ package org.apache.activemq.artemis.api.core.management; /** * An ActiveMQComponentControl is used to manage the life cycle of an ActiveMQ Artemis component. */ -public interface ActiveMQComponentControl -{ +public interface ActiveMQComponentControl { + /** * Returns {@code true} if this component is started, {@code false} else. */ diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ActiveMQServerControl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ActiveMQServerControl.java index 138bc46338..c474d1d8bc 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ActiveMQServerControl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ActiveMQServerControl.java @@ -21,8 +21,8 @@ import javax.management.MBeanOperationInfo; /** * An ActiveMQServerControl is used to manage ActiveMQ Artemis servers. */ -public interface ActiveMQServerControl -{ +public interface ActiveMQServerControl { + /** * Returns this server's version. */ @@ -132,7 +132,6 @@ public interface ActiveMQServerControl */ void setFailoverOnServerShutdown(boolean failoverOnServerShutdown) throws Exception; - /** * returns if clients failover on a server shutdown */ @@ -513,15 +512,14 @@ public interface ActiveMQServerControl void sendQueueInfoToQueue(String queueName, String address) throws Exception; @Operation(desc = "Add security settings for addresses matching the addressMatch", impact = MBeanOperationInfo.ACTION) - void addSecuritySettings( - @Parameter(desc = "an address match", name = "addressMatch") String addressMatch, - @Parameter(desc = "a comma-separated list of roles allowed to send messages", name = "send") String sendRoles, - @Parameter(desc = "a comma-separated list of roles allowed to consume messages", name = "consume") String consumeRoles, - @Parameter(desc = "a comma-separated list of roles allowed to create durable queues", name = "createDurableQueueRoles") String createDurableQueueRoles, - @Parameter(desc = "a comma-separated list of roles allowed to delete durable queues", name = "deleteDurableQueueRoles") String deleteDurableQueueRoles, - @Parameter(desc = "a comma-separated list of roles allowed to create non durable queues", name = "createNonDurableQueueRoles") String createNonDurableQueueRoles, - @Parameter(desc = "a comma-separated list of roles allowed to delete non durable queues", name = "deleteNonDurableQueueRoles") String deleteNonDurableQueueRoles, - @Parameter(desc = "a comma-separated list of roles allowed to send management messages messages", name = "manage") String manageRoles) throws Exception; + void addSecuritySettings(@Parameter(desc = "an address match", name = "addressMatch") String addressMatch, + @Parameter(desc = "a comma-separated list of roles allowed to send messages", name = "send") String sendRoles, + @Parameter(desc = "a comma-separated list of roles allowed to consume messages", name = "consume") String consumeRoles, + @Parameter(desc = "a comma-separated list of roles allowed to create durable queues", name = "createDurableQueueRoles") String createDurableQueueRoles, + @Parameter(desc = "a comma-separated list of roles allowed to delete durable queues", name = "deleteDurableQueueRoles") String deleteDurableQueueRoles, + @Parameter(desc = "a comma-separated list of roles allowed to create non durable queues", name = "createNonDurableQueueRoles") String createNonDurableQueueRoles, + @Parameter(desc = "a comma-separated list of roles allowed to delete non durable queues", name = "deleteNonDurableQueueRoles") String deleteNonDurableQueueRoles, + @Parameter(desc = "a comma-separated list of roles allowed to send management messages messages", name = "manage") String manageRoles) throws Exception; @Operation(desc = "Remove security settings for an address", impact = MBeanOperationInfo.ACTION) void removeSecuritySettings(@Parameter(desc = "an address match", name = "addressMatch") String addressMatch) throws Exception; @@ -600,7 +598,6 @@ public interface ActiveMQServerControl @Parameter(name = "user", desc = "User name") String user, @Parameter(name = "password", desc = "User password") String password) throws Exception; - @Operation(desc = "Destroy a bridge", impact = MBeanOperationInfo.ACTION) void destroyBridge(@Parameter(name = "name", desc = "Name of the bridge") String name) throws Exception; @@ -610,6 +607,6 @@ public interface ActiveMQServerControl void updateDuplicateIdCache(String address, Object[] ids) throws Exception; @Operation(desc = "force the server to stop and to scale down to another server", impact = MBeanOperationInfo.UNKNOWN) - void scaleDown(@Parameter(name = "name", desc = "The connector to use to scale down, if not provided the first appropriate connector will be used")String connector) throws Exception; + void scaleDown(@Parameter(name = "name", desc = "The connector to use to scale down, if not provided the first appropriate connector will be used") String connector) throws Exception; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/AddressControl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/AddressControl.java index 83866db664..7d066bd5fe 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/AddressControl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/AddressControl.java @@ -16,14 +16,13 @@ */ package org.apache.activemq.artemis.api.core.management; - import javax.management.MBeanOperationInfo; /** * An AddressControl is used to manage an address. */ -public interface AddressControl -{ +public interface AddressControl { + /** * Returns the managed address. */ @@ -42,13 +41,12 @@ public interface AddressControl */ String getRolesAsJSON() throws Exception; - @Operation(desc = "returns the number of estimated bytes being used by the queue, used to control paging and blocking", - impact = MBeanOperationInfo.INFO) + impact = MBeanOperationInfo.INFO) long getAddressSize() throws Exception; @Operation(desc = "Returns the sum of messages on queues, including messages in delivery", - impact = MBeanOperationInfo.INFO) + impact = MBeanOperationInfo.INFO) long getNumberOfMessages() throws Exception; /** @@ -63,6 +61,7 @@ public interface AddressControl /** * Returns whether this address is paging. + * * @throws Exception */ boolean isPaging() throws Exception; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/AddressSettingsInfo.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/AddressSettingsInfo.java index f827628baa..63b80cbfda 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/AddressSettingsInfo.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/AddressSettingsInfo.java @@ -19,8 +19,8 @@ package org.apache.activemq.artemis.api.core.management; import org.apache.activemq.artemis.utils.json.JSONObject; // XXX no javadocs -public final class AddressSettingsInfo -{ +public final class AddressSettingsInfo { + private final String addressFullMessagePolicy; private final long maxSizeBytes; @@ -59,27 +59,9 @@ public final class AddressSettingsInfo // Static -------------------------------------------------------- - public static AddressSettingsInfo from(final String jsonString) throws Exception - { + public static AddressSettingsInfo from(final String jsonString) throws Exception { JSONObject object = new JSONObject(jsonString); - return new AddressSettingsInfo(object.getString("addressFullMessagePolicy"), - object.getLong("maxSizeBytes"), - object.getInt("pageSizeBytes"), - object.getInt("pageCacheMaxSize"), - object.getInt("maxDeliveryAttempts"), - object.getLong("redeliveryDelay"), - object.getDouble("redeliveryMultiplier"), - object.getLong("maxRedeliveryDelay"), - object.getString("DLA"), - object.getString("expiryAddress"), - object.getBoolean("lastValueQueue"), - object.getLong("redistributionDelay"), - object.getBoolean("sendToDLAOnNoRoute"), - object.getLong("slowConsumerThreshold"), - object.getLong("slowConsumerCheckPeriod"), - object.getString("slowConsumerPolicy"), - object.getBoolean("autoCreateJmsQueues"), - object.getBoolean("autoDeleteJmsQueues")); + return new AddressSettingsInfo(object.getString("addressFullMessagePolicy"), object.getLong("maxSizeBytes"), object.getInt("pageSizeBytes"), object.getInt("pageCacheMaxSize"), object.getInt("maxDeliveryAttempts"), object.getLong("redeliveryDelay"), object.getDouble("redeliveryMultiplier"), object.getLong("maxRedeliveryDelay"), object.getString("DLA"), object.getString("expiryAddress"), object.getBoolean("lastValueQueue"), object.getLong("redistributionDelay"), object.getBoolean("sendToDLAOnNoRoute"), object.getLong("slowConsumerThreshold"), object.getLong("slowConsumerCheckPeriod"), object.getString("slowConsumerPolicy"), object.getBoolean("autoCreateJmsQueues"), object.getBoolean("autoDeleteJmsQueues")); } // Constructors -------------------------------------------------- @@ -101,8 +83,7 @@ public final class AddressSettingsInfo long slowConsumerCheckPeriod, String slowConsumerPolicy, boolean autoCreateJmsQueues, - boolean autoDeleteJmsQueues) - { + boolean autoDeleteJmsQueues) { this.addressFullMessagePolicy = addressFullMessagePolicy; this.maxSizeBytes = maxSizeBytes; this.pageSizeBytes = pageSizeBytes; @@ -125,98 +106,79 @@ public final class AddressSettingsInfo // Public -------------------------------------------------------- - public int getPageCacheMaxSize() - { + public int getPageCacheMaxSize() { return pageCacheMaxSize; } - public void setPageCacheMaxSize(int pageCacheMaxSize) - { + public void setPageCacheMaxSize(int pageCacheMaxSize) { this.pageCacheMaxSize = pageCacheMaxSize; } - public String getAddressFullMessagePolicy() - { + public String getAddressFullMessagePolicy() { return addressFullMessagePolicy; } - public long getMaxSizeBytes() - { + public long getMaxSizeBytes() { return maxSizeBytes; } - public int getPageSizeBytes() - { + public int getPageSizeBytes() { return pageSizeBytes; } - public int getMaxDeliveryAttempts() - { + public int getMaxDeliveryAttempts() { return maxDeliveryAttempts; } - public long getRedeliveryDelay() - { + public long getRedeliveryDelay() { return redeliveryDelay; } - public String getDeadLetterAddress() - { + public String getDeadLetterAddress() { return deadLetterAddress; } - public String getExpiryAddress() - { + public String getExpiryAddress() { return expiryAddress; } - public boolean isLastValueQueue() - { + public boolean isLastValueQueue() { return lastValueQueue; } - public long getRedistributionDelay() - { + public long getRedistributionDelay() { return redistributionDelay; } - public boolean isSendToDLAOnNoRoute() - { + public boolean isSendToDLAOnNoRoute() { return sendToDLAOnNoRoute; } - public double getRedeliveryMultiplier() - { + public double getRedeliveryMultiplier() { return redeliveryMultiplier; } - public long getMaxRedeliveryDelay() - { + public long getMaxRedeliveryDelay() { return maxRedeliveryDelay; } - public long getSlowConsumerThreshold() - { + public long getSlowConsumerThreshold() { return slowConsumerThreshold; } - public long getSlowConsumerCheckPeriod() - { + public long getSlowConsumerCheckPeriod() { return slowConsumerCheckPeriod; } - public String getSlowConsumerPolicy() - { + public String getSlowConsumerPolicy() { return slowConsumerPolicy; } - public boolean isAutoCreateJmsQueues() - { + public boolean isAutoCreateJmsQueues() { return autoCreateJmsQueues; } - public boolean isAutoDeleteJmsQueues() - { + public boolean isAutoDeleteJmsQueues() { return autoDeleteJmsQueues; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/BridgeControl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/BridgeControl.java index 52b97ae59f..0b17cefdfc 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/BridgeControl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/BridgeControl.java @@ -16,12 +16,11 @@ */ package org.apache.activemq.artemis.api.core.management; - /** * A BridgeControl is used to manage a Bridge. */ -public interface BridgeControl extends ActiveMQComponentControl -{ +public interface BridgeControl extends ActiveMQComponentControl { + /** * Returns the name of this bridge */ diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/BroadcastGroupControl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/BroadcastGroupControl.java index 9f83ac9396..53d5e09eed 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/BroadcastGroupControl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/BroadcastGroupControl.java @@ -19,8 +19,8 @@ package org.apache.activemq.artemis.api.core.management; /** * A BroadcastGroupControl is used to manage a broadcast group. */ -public interface BroadcastGroupControl extends ActiveMQComponentControl -{ +public interface BroadcastGroupControl extends ActiveMQComponentControl { + /** * Returns the configuration name of this broadcast group. */ diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ClusterConnectionControl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ClusterConnectionControl.java index 5767bf603c..53d19d4ac0 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ClusterConnectionControl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ClusterConnectionControl.java @@ -21,8 +21,8 @@ import java.util.Map; /** * A ClusterConnectionControl is used to manage a cluster connection. */ -public interface ClusterConnectionControl extends ActiveMQComponentControl -{ +public interface ClusterConnectionControl extends ActiveMQComponentControl { + /** * Returns the configuration name of this cluster connection. */ @@ -52,6 +52,7 @@ public interface ClusterConnectionControl extends ActiveMQComponentControl * Return the Topology that this Cluster Connection knows about */ String getTopology(); + /** * Returns the maximum number of hops used by this cluster connection. */ diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/CoreNotificationType.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/CoreNotificationType.java index 724b1f946a..105471c5c6 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/CoreNotificationType.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/CoreNotificationType.java @@ -19,8 +19,7 @@ package org.apache.activemq.artemis.api.core.management; /** * This enum defines all core notification types */ -public enum CoreNotificationType implements NotificationType -{ +public enum CoreNotificationType implements NotificationType { BINDING_ADDED(0), BINDING_REMOVED(1), CONSUMER_CREATED(2), @@ -44,13 +43,11 @@ public enum CoreNotificationType implements NotificationType private final int value; - private CoreNotificationType(final int value) - { + private CoreNotificationType(final int value) { this.value = value; } - public int getType() - { + public int getType() { return value; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/DayCounterInfo.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/DayCounterInfo.java index fe2c466a1b..422772f0c1 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/DayCounterInfo.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/DayCounterInfo.java @@ -26,8 +26,7 @@ import org.apache.activemq.artemis.utils.json.JSONObject; * Helper class to create Java Objects from the * JSON serialization returned by {@link QueueControl#listMessageCounterHistory()}. */ -public final class DayCounterInfo -{ +public final class DayCounterInfo { private final String date; @@ -35,12 +34,10 @@ public final class DayCounterInfo // Static -------------------------------------------------------- - public static String toJSON(final DayCounterInfo[] infos) throws JSONException - { + public static String toJSON(final DayCounterInfo[] infos) throws JSONException { JSONObject json = new JSONObject(); JSONArray counters = new JSONArray(); - for (DayCounterInfo info : infos) - { + for (DayCounterInfo info : infos) { JSONObject counter = new JSONObject(); counter.put("date", info.getDate()); counter.put("counters", Arrays.asList(info.getCounters())); @@ -54,19 +51,16 @@ public final class DayCounterInfo * Returns an array of RoleInfo corresponding to the JSON serialization returned * by {@link QueueControl#listMessageCounterHistory()}. */ - public static DayCounterInfo[] fromJSON(final String jsonString) throws JSONException - { + public static DayCounterInfo[] fromJSON(final String jsonString) throws JSONException { JSONObject json = new JSONObject(jsonString); JSONArray dayCounters = json.getJSONArray("dayCounters"); DayCounterInfo[] infos = new DayCounterInfo[dayCounters.length()]; - for (int i = 0; i < dayCounters.length(); i++) - { + for (int i = 0; i < dayCounters.length(); i++) { - JSONObject counter = (JSONObject)dayCounters.get(i); - JSONArray hour = (JSONArray)counter.getJSONArray("counters").get(0); + JSONObject counter = (JSONObject) dayCounters.get(i); + JSONArray hour = (JSONArray) counter.getJSONArray("counters").get(0); int[] hourCounters = new int[24]; - for (int j = 0; j < 24; j++) - { + for (int j = 0; j < 24; j++) { hourCounters[j] = hour.getInt(j); } DayCounterInfo info = new DayCounterInfo(counter.getString("date"), hourCounters); @@ -77,8 +71,7 @@ public final class DayCounterInfo // Constructors -------------------------------------------------- - public DayCounterInfo(final String date, final int[] counters) - { + public DayCounterInfo(final String date, final int[] counters) { this.date = date; this.counters = counters; } @@ -88,8 +81,7 @@ public final class DayCounterInfo /** * Returns the date of the counter. */ - public String getDate() - { + public String getDate() { return date; } @@ -97,8 +89,7 @@ public final class DayCounterInfo * Returns a 24-length array corresponding to the number of messages added to the queue * for the given hour of the day. */ - public int[] getCounters() - { + public int[] getCounters() { return counters; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/DivertControl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/DivertControl.java index e59b19f2da..3e5bca6e5d 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/DivertControl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/DivertControl.java @@ -19,8 +19,8 @@ package org.apache.activemq.artemis.api.core.management; /** * A DivertControl is used to manage a divert. */ -public interface DivertControl -{ +public interface DivertControl { + /** * Returns the filter used by this divert. */ diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ManagementHelper.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ManagementHelper.java index 23afbd9c6b..8cd7e2ec12 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ManagementHelper.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ManagementHelper.java @@ -30,8 +30,7 @@ import org.apache.activemq.artemis.utils.json.JSONObject; /** * Helper class to use ActiveMQ Artemis Core messages to manage server resources. */ -public final class ManagementHelper -{ +public final class ManagementHelper { // Constants ----------------------------------------------------- public static final SimpleString HDR_RESOURCE_NAME = new SimpleString("_AMQ_ResourceName"); @@ -92,8 +91,7 @@ public final class ManagementHelper * @param attribute the name of the attribute * @see ResourceNames */ - public static void putAttribute(final Message message, final String resourceName, final String attribute) - { + public static void putAttribute(final Message message, final String resourceName, final String attribute) { message.putStringProperty(ManagementHelper.HDR_RESOURCE_NAME, new SimpleString(resourceName)); message.putStringProperty(ManagementHelper.HDR_ATTRIBUTE, new SimpleString(attribute)); } @@ -108,8 +106,7 @@ public final class ManagementHelper */ public static void putOperationInvocation(final Message message, final String resourceName, - final String operationName) throws Exception - { + final String operationName) throws Exception { ManagementHelper.putOperationInvocation(message, resourceName, operationName, (Object[]) null); } @@ -125,8 +122,7 @@ public final class ManagementHelper public static void putOperationInvocation(final Message message, final String resourceName, final String operationName, - final Object... parameters) throws Exception - { + final Object... parameters) throws Exception { // store the name of the operation in the headers message.putStringProperty(ManagementHelper.HDR_RESOURCE_NAME, new SimpleString(resourceName)); message.putStringProperty(ManagementHelper.HDR_OPERATION_NAME, new SimpleString(operationName)); @@ -135,46 +131,37 @@ public final class ManagementHelper String paramString; - if (parameters != null) - { + if (parameters != null) { JSONArray jsonArray = ManagementHelper.toJSONArray(parameters); paramString = jsonArray.toString(); } - else - { + else { paramString = null; } message.getBodyBuffer().writeNullableSimpleString(SimpleString.toSimpleString(paramString)); } - private static JSONArray toJSONArray(final Object[] array) throws Exception - { + private static JSONArray toJSONArray(final Object[] array) throws Exception { JSONArray jsonArray = new JSONArray(); - for (Object parameter : array) - { - if (parameter instanceof Map) - { + for (Object parameter : array) { + if (parameter instanceof Map) { Map map = (Map) parameter; JSONObject jsonObject = new JSONObject(); - for (Map.Entry entry : map.entrySet()) - { + for (Map.Entry entry : map.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); - if (val != null) - { - if (val.getClass().isArray()) - { + if (val != null) { + if (val.getClass().isArray()) { val = ManagementHelper.toJSONArray((Object[]) val); } - else - { + else { ManagementHelper.checkType(val); } } @@ -184,27 +171,22 @@ public final class ManagementHelper jsonArray.put(jsonObject); } - else - { - if (parameter != null) - { + else { + if (parameter != null) { Class clz = parameter.getClass(); - if (clz.isArray()) - { + if (clz.isArray()) { Object[] innerArray = (Object[]) parameter; jsonArray.put(ManagementHelper.toJSONArray(innerArray)); } - else - { + else { ManagementHelper.checkType(parameter); jsonArray.put(parameter); } } - else - { + else { jsonArray.put((Object) null); } } @@ -213,52 +195,43 @@ public final class ManagementHelper return jsonArray; } - private static Object[] fromJSONArray(final JSONArray jsonArray) throws Exception - { + private static Object[] fromJSONArray(final JSONArray jsonArray) throws Exception { Object[] array = new Object[jsonArray.length()]; - for (int i = 0; i < jsonArray.length(); i++) - { + for (int i = 0; i < jsonArray.length(); i++) { Object val = jsonArray.get(i); - if (val instanceof JSONArray) - { + if (val instanceof JSONArray) { Object[] inner = ManagementHelper.fromJSONArray((JSONArray) val); array[i] = inner; } - else if (val instanceof JSONObject) - { + else if (val instanceof JSONObject) { JSONObject jsonObject = (JSONObject) val; Map map = new HashMap(); Iterator iter = jsonObject.keys(); - while (iter.hasNext()) - { + while (iter.hasNext()) { String key = iter.next(); Object innerVal = jsonObject.get(key); - if (innerVal instanceof JSONArray) - { + if (innerVal instanceof JSONArray) { innerVal = ManagementHelper.fromJSONArray(((JSONArray) innerVal)); } - else if (innerVal instanceof JSONObject) - { + else if (innerVal instanceof JSONObject) { Map innerMap = new HashMap(); JSONObject o = (JSONObject) innerVal; Iterator it = o.keys(); - while (it.hasNext()) - { + while (it.hasNext()) { String k = (String) it.next(); innerMap.put(k, o.get(k)); } innerVal = innerMap; } - else if (innerVal instanceof Integer) - { + else if (innerVal instanceof Integer) { innerVal = ((Integer) innerVal).longValue(); } @@ -267,14 +240,11 @@ public final class ManagementHelper array[i] = map; } - else - { - if (val == JSONObject.NULL) - { + else { + if (val == JSONObject.NULL) { array[i] = null; } - else - { + else { array[i] = val; } } @@ -283,16 +253,14 @@ public final class ManagementHelper return array; } - private static void checkType(final Object param) - { + private static void checkType(final Object param) { if (param instanceof Integer == false && param instanceof Long == false && param instanceof Double == false && param instanceof String == false && param instanceof Boolean == false && param instanceof Map == false && param instanceof Byte == false && - param instanceof Short == false) - { + param instanceof Short == false) { throw ActiveMQClientMessageBundle.BUNDLE.invalidManagementParam(param.getClass().getName()); } } @@ -300,19 +268,16 @@ public final class ManagementHelper /** * Used by ActiveMQ Artemis management service. */ - public static Object[] retrieveOperationParameters(final Message message) throws Exception - { + public static Object[] retrieveOperationParameters(final Message message) throws Exception { SimpleString sstring = message.getBodyBuffer().readNullableSimpleString(); String jsonString = (sstring == null) ? null : sstring.toString(); - if (jsonString != null) - { + if (jsonString != null) { JSONArray jsonArray = new JSONArray(jsonString); return ManagementHelper.fromJSONArray(jsonArray); } - else - { + else { return null; } } @@ -320,36 +285,31 @@ public final class ManagementHelper /** * Returns whether the JMS message corresponds to the result of a management operation invocation. */ - public static boolean isOperationResult(final Message message) - { + public static boolean isOperationResult(final Message message) { return message.containsProperty(ManagementHelper.HDR_OPERATION_SUCCEEDED); } /** * Returns whether the JMS message corresponds to the result of a management attribute value. */ - public static boolean isAttributesResult(final Message message) - { + public static boolean isAttributesResult(final Message message) { return !ManagementHelper.isOperationResult(message); } /** * Used by ActiveMQ Artemis management service. */ - public static void storeResult(final Message message, final Object result) throws Exception - { + public static void storeResult(final Message message, final Object result) throws Exception { String resultString; - if (result != null) - { + if (result != null) { // Result is stored in body, also encoded as JSON array of length 1 JSONArray jsonArray = ManagementHelper.toJSONArray(new Object[]{result}); resultString = jsonArray.toString(); } - else - { + else { resultString = null; } @@ -362,21 +322,18 @@ public final class ManagementHelper * If an error occurred on the server, {@link #hasOperationSucceeded(Message)} will return {@code false}. * and the result will be a String corresponding to the server exception. */ - public static Object[] getResults(final Message message) throws Exception - { + public static Object[] getResults(final Message message) throws Exception { SimpleString sstring = message.getBodyBuffer().readNullableSimpleString(); String jsonString = (sstring == null) ? null : sstring.toString(); - if (jsonString != null) - { + if (jsonString != null) { JSONArray jsonArray = new JSONArray(jsonString); Object[] res = ManagementHelper.fromJSONArray(jsonArray); return res; } - else - { + else { return null; } } @@ -387,16 +344,13 @@ public final class ManagementHelper * If an error occurred on the server, {@link #hasOperationSucceeded(Message)} will return {@code false}. * and the result will be a String corresponding to the server exception. */ - public static Object getResult(final Message message) throws Exception - { + public static Object getResult(final Message message) throws Exception { Object[] res = ManagementHelper.getResults(message); - if (res != null) - { + if (res != null) { return res[0]; } - else - { + else { return null; } } @@ -404,14 +358,11 @@ public final class ManagementHelper /** * Returns whether the invocation of the management operation on the server resource succeeded. */ - public static boolean hasOperationSucceeded(final Message message) - { - if (!ManagementHelper.isOperationResult(message)) - { + public static boolean hasOperationSucceeded(final Message message) { + if (!ManagementHelper.isOperationResult(message)) { return false; } - if (message.containsProperty(ManagementHelper.HDR_OPERATION_SUCCEEDED)) - { + if (message.containsProperty(ManagementHelper.HDR_OPERATION_SUCCEEDED)) { return message.getBooleanProperty(ManagementHelper.HDR_OPERATION_SUCCEEDED); } return false; @@ -420,10 +371,8 @@ public final class ManagementHelper /** * Used by ActiveMQ Artemis management service. */ - public static Map fromCommaSeparatedKeyValues(final String str) throws Exception - { - if (str == null || str.trim().length() == 0) - { + public static Map fromCommaSeparatedKeyValues(final String str) throws Exception { + if (str == null || str.trim().length() == 0) { return Collections.emptyMap(); } @@ -436,25 +385,21 @@ public final class ManagementHelper /** * Used by ActiveMQ Artemis management service. */ - public static Object[] fromCommaSeparatedArrayOfCommaSeparatedKeyValues(final String str) throws Exception - { - if (str == null || str.trim().length() == 0) - { + public static Object[] fromCommaSeparatedArrayOfCommaSeparatedKeyValues(final String str) throws Exception { + if (str == null || str.trim().length() == 0) { return new Object[0]; } String s = str; // if there is a single item, we wrap it in to make it a JSON object - if (!s.trim().startsWith("{")) - { + if (!s.trim().startsWith("{")) { s = "{" + s + "}"; } JSONArray array = new JSONArray("[" + s + "]"); return ManagementHelper.fromJSONArray(array); } - private ManagementHelper() - { + private ManagementHelper() { } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/NotificationType.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/NotificationType.java index 07fa2804b9..4952179d7f 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/NotificationType.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/NotificationType.java @@ -27,7 +27,7 @@ package org.apache.activemq.artemis.api.core.management; * * see the ActiveMQ Artemis user manual section on "Management Notifications" */ -public interface NotificationType -{ +public interface NotificationType { + int getType(); } \ No newline at end of file diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ObjectNameBuilder.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ObjectNameBuilder.java index 867d87eb46..d9ca3f91aa 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ObjectNameBuilder.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ObjectNameBuilder.java @@ -24,8 +24,7 @@ import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration; /** * Helper class to build ObjectNames for ActiveMQ Artemis resources. */ -public final class ObjectNameBuilder -{ +public final class ObjectNameBuilder { // Constants ----------------------------------------------------- @@ -44,22 +43,18 @@ public final class ObjectNameBuilder // Static -------------------------------------------------------- - public static ObjectNameBuilder create(final String domain) - { - if (domain == null) - { + public static ObjectNameBuilder create(final String domain) { + if (domain == null) { return new ObjectNameBuilder(ActiveMQDefaultConfiguration.getDefaultJmxDomain()); } - else - { + else { return new ObjectNameBuilder(domain); } } // Constructors -------------------------------------------------- - private ObjectNameBuilder(final String domain) - { + private ObjectNameBuilder(final String domain) { this.domain = domain; } @@ -68,8 +63,7 @@ public final class ObjectNameBuilder /** * Returns the ObjectName used by the single {@link ActiveMQServerControl}. */ - public ObjectName getActiveMQServerObjectName() throws Exception - { + public ObjectName getActiveMQServerObjectName() throws Exception { return ObjectName.getInstance(domain + ":module=Core,type=Server"); } @@ -78,8 +72,7 @@ public final class ObjectNameBuilder * * @see AddressControl */ - public ObjectName getAddressObjectName(final SimpleString address) throws Exception - { + public ObjectName getAddressObjectName(final SimpleString address) throws Exception { return createObjectName(ObjectNameBuilder.CORE_MODULE, "Address", address.toString()); } @@ -88,14 +81,8 @@ public final class ObjectNameBuilder * * @see QueueControl */ - public ObjectName getQueueObjectName(final SimpleString address, final SimpleString name) throws Exception - { - return ObjectName.getInstance(String.format("%s:module=%s,type=%s,address=%s,name=%s", - domain, - ObjectNameBuilder.CORE_MODULE, - "Queue", - ObjectName.quote(address.toString()), - ObjectName.quote(name.toString()))); + public ObjectName getQueueObjectName(final SimpleString address, final SimpleString name) throws Exception { + return ObjectName.getInstance(String.format("%s:module=%s,type=%s,address=%s,name=%s", domain, ObjectNameBuilder.CORE_MODULE, "Queue", ObjectName.quote(address.toString()), ObjectName.quote(name.toString()))); } /** @@ -103,8 +90,7 @@ public final class ObjectNameBuilder * * @see DivertControl */ - public ObjectName getDivertObjectName(final String name) throws Exception - { + public ObjectName getDivertObjectName(final String name) throws Exception { return createObjectName(ObjectNameBuilder.CORE_MODULE, "Divert", name.toString()); } @@ -113,8 +99,7 @@ public final class ObjectNameBuilder * * @see AcceptorControl */ - public ObjectName getAcceptorObjectName(final String name) throws Exception - { + public ObjectName getAcceptorObjectName(final String name) throws Exception { return createObjectName(ObjectNameBuilder.CORE_MODULE, "Acceptor", name); } @@ -123,8 +108,7 @@ public final class ObjectNameBuilder * * @see BroadcastGroupControl */ - public ObjectName getBroadcastGroupObjectName(final String name) throws Exception - { + public ObjectName getBroadcastGroupObjectName(final String name) throws Exception { return createObjectName(ObjectNameBuilder.CORE_MODULE, "BroadcastGroup", name); } @@ -133,8 +117,7 @@ public final class ObjectNameBuilder * * @see BridgeControl */ - public ObjectName getBridgeObjectName(final String name) throws Exception - { + public ObjectName getBridgeObjectName(final String name) throws Exception { return createObjectName(ObjectNameBuilder.CORE_MODULE, "Bridge", name); } @@ -143,57 +126,46 @@ public final class ObjectNameBuilder * * @see ClusterConnectionControl */ - public ObjectName getClusterConnectionObjectName(final String name) throws Exception - { + public ObjectName getClusterConnectionObjectName(final String name) throws Exception { return createObjectName(ObjectNameBuilder.CORE_MODULE, "ClusterConnection", name); } /** * Returns the ObjectName used by DiscoveryGroupControl. */ - public ObjectName getDiscoveryGroupObjectName(final String name) throws Exception - { + public ObjectName getDiscoveryGroupObjectName(final String name) throws Exception { return createObjectName(ObjectNameBuilder.CORE_MODULE, "DiscoveryGroup", name); } /** * Returns the ObjectName used by JMSServerControl. */ - public ObjectName getJMSServerObjectName() throws Exception - { + public ObjectName getJMSServerObjectName() throws Exception { return ObjectName.getInstance(domain + ":module=JMS,type=Server"); } /** * Returns the ObjectName used by JMSQueueControl. */ - public ObjectName getJMSQueueObjectName(final String name) throws Exception - { + public ObjectName getJMSQueueObjectName(final String name) throws Exception { return createObjectName(ObjectNameBuilder.JMS_MODULE, "Queue", name); } /** * Returns the ObjectName used by TopicControl. */ - public ObjectName getJMSTopicObjectName(final String name) throws Exception - { + public ObjectName getJMSTopicObjectName(final String name) throws Exception { return createObjectName(ObjectNameBuilder.JMS_MODULE, "Topic", name); } /** * Returns the ObjectName used by ConnectionFactoryControl. */ - public ObjectName getConnectionFactoryObjectName(final String name) throws Exception - { + public ObjectName getConnectionFactoryObjectName(final String name) throws Exception { return createObjectName(ObjectNameBuilder.JMS_MODULE, "ConnectionFactory", name); } - private ObjectName createObjectName(final String module, final String type, final String name) throws Exception - { - return ObjectName.getInstance(String.format("%s:module=%s,type=%s,name=%s", - domain, - module, - type, - ObjectName.quote(name))); + private ObjectName createObjectName(final String module, final String type, final String name) throws Exception { + return ObjectName.getInstance(String.format("%s:module=%s,type=%s,name=%s", domain, module, type, ObjectName.quote(name))); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/Operation.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/Operation.java index ee709bf38d..5495f5a81c 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/Operation.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/Operation.java @@ -33,8 +33,8 @@ import javax.management.MBeanOperationInfo; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Inherited -public @interface Operation -{ +public @interface Operation { + String desc(); int impact() default MBeanOperationInfo.INFO; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/Parameter.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/Parameter.java index a3d8c0e2af..24a7b1f24f 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/Parameter.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/Parameter.java @@ -29,8 +29,8 @@ import java.lang.annotation.Target; */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) -public @interface Parameter -{ +public @interface Parameter { + String name(); String desc() default "N/A"; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/QueueControl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/QueueControl.java index 1813d841c0..8d211ca826 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/QueueControl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/QueueControl.java @@ -19,12 +19,10 @@ package org.apache.activemq.artemis.api.core.management; import javax.management.MBeanOperationInfo; import java.util.Map; - /** * A QueueControl is used to manage a queue. */ -public interface QueueControl -{ +public interface QueueControl { // Attributes ---------------------------------------------------- /** @@ -249,7 +247,6 @@ public interface QueueControl int moveMessages(@Parameter(name = "filter", desc = "A message filter (can be empty)") String filter, @Parameter(name = "otherQueueName", desc = "The name of the queue to move the messages to") String otherQueueName) throws Exception; - /** * Moves all the message corresponding to the specified filter to the specified other queue. *
diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ResourceNames.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ResourceNames.java index 55957f8d32..37f74ed674 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ResourceNames.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ResourceNames.java @@ -22,8 +22,7 @@ package org.apache.activemq.artemis.api.core.management; * Resource's name is build by appending its name to its corresponding type. * For example, the resource name of the "foo" queue is {@code CORE_QUEUE + "foo"}. */ -public final class ResourceNames -{ +public final class ResourceNames { public static final String CORE_SERVER = "core.server"; @@ -51,8 +50,7 @@ public final class ResourceNames public static final String JMS_CONNECTION_FACTORY = "jms.connectionfactory."; - private ResourceNames() - { + private ResourceNames() { } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/RoleInfo.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/RoleInfo.java index 42c5fe9745..a1e82a4645 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/RoleInfo.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/RoleInfo.java @@ -23,8 +23,8 @@ import org.apache.activemq.artemis.utils.json.JSONObject; * Helper class to create Java Objects from the * JSON serialization returned by {@link AddressControl#getRolesAsJSON()}. */ -public final class RoleInfo -{ +public final class RoleInfo { + private final String name; private final boolean send; @@ -45,21 +45,12 @@ public final class RoleInfo * Returns an array of RoleInfo corresponding to the JSON serialization returned * by {@link AddressControl#getRolesAsJSON()}. */ - public static RoleInfo[] from(final String jsonString) throws Exception - { + public static RoleInfo[] from(final String jsonString) throws Exception { JSONArray array = new JSONArray(jsonString); RoleInfo[] roles = new RoleInfo[array.length()]; - for (int i = 0; i < array.length(); i++) - { + for (int i = 0; i < array.length(); i++) { JSONObject r = array.getJSONObject(i); - RoleInfo role = new RoleInfo(r.getString("name"), - r.getBoolean("send"), - r.getBoolean("consume"), - r.getBoolean("createDurableQueue"), - r.getBoolean("deleteDurableQueue"), - r.getBoolean("createNonDurableQueue"), - r.getBoolean("deleteNonDurableQueue"), - r.getBoolean("manage")); + RoleInfo role = new RoleInfo(r.getString("name"), r.getBoolean("send"), r.getBoolean("consume"), r.getBoolean("createDurableQueue"), r.getBoolean("deleteDurableQueue"), r.getBoolean("createNonDurableQueue"), r.getBoolean("deleteNonDurableQueue"), r.getBoolean("manage")); roles[i] = role; } return roles; @@ -72,8 +63,7 @@ public final class RoleInfo final boolean deleteDurableQueue, final boolean createNonDurableQueue, final boolean deleteNonDurableQueue, - final boolean manage) - { + final boolean manage) { this.name = name; this.send = send; this.consume = consume; @@ -87,64 +77,56 @@ public final class RoleInfo /** * Returns the name of the role. */ - public String getName() - { + public String getName() { return name; } /** * Returns whether this role can send messages to the address. */ - public boolean isSend() - { + public boolean isSend() { return send; } /** * Returns whether this role can consume messages from queues bound to the address. */ - public boolean isConsume() - { + public boolean isConsume() { return consume; } /** * Returns whether this role can create durable queues bound to the address. */ - public boolean isCreateDurableQueue() - { + public boolean isCreateDurableQueue() { return createDurableQueue; } /** * Returns whether this role can delete durable queues bound to the address. */ - public boolean isDeleteDurableQueue() - { + public boolean isDeleteDurableQueue() { return deleteDurableQueue; } /** * Returns whether this role can create non-durable queues bound to the address. */ - public boolean isCreateNonDurableQueue() - { + public boolean isCreateNonDurableQueue() { return createNonDurableQueue; } /** * Returns whether this role can delete non-durable queues bound to the address. */ - public boolean isDeleteNonDurableQueue() - { + public boolean isDeleteNonDurableQueue() { return deleteNonDurableQueue; } /** * Returns whether this role can send management messages to the address. */ - public boolean isManage() - { + public boolean isManage() { return manage; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/buffers/impl/ResetLimitWrappedActiveMQBuffer.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/buffers/impl/ResetLimitWrappedActiveMQBuffer.java index 9ab6b2f71d..b3cdfe193b 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/buffers/impl/ResetLimitWrappedActiveMQBuffer.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/buffers/impl/ResetLimitWrappedActiveMQBuffer.java @@ -25,10 +25,9 @@ import org.apache.activemq.artemis.core.message.impl.MessageInternal; /** * A ResetLimitWrappedActiveMQBuffer * TODO: Move this to commons - * */ -public final class ResetLimitWrappedActiveMQBuffer extends ChannelBufferWrapper -{ +public final class ResetLimitWrappedActiveMQBuffer extends ChannelBufferWrapper { + private final int limit; private MessageInternal message; @@ -36,23 +35,21 @@ public final class ResetLimitWrappedActiveMQBuffer extends ChannelBufferWrapper /** * We need to turn of notifications of body changes on reset on the server side when dealing with AMQP conversions, * for that reason this method will set the message to null here + * * @param message */ - public void setMessage(MessageInternal message) - { + public void setMessage(MessageInternal message) { this.message = message; } - public ResetLimitWrappedActiveMQBuffer(final int limit, final ActiveMQBuffer buffer, final MessageInternal message) - { + public ResetLimitWrappedActiveMQBuffer(final int limit, final ActiveMQBuffer buffer, final MessageInternal message) { // a wrapped inside a wrapper will increase the stack size. // we fixed this here due to some profiling testing super(unwrap(buffer.byteBuf())); this.limit = limit; - if (writerIndex() < limit) - { + if (writerIndex() < limit) { writerIndex(limit); } @@ -61,26 +58,21 @@ public final class ResetLimitWrappedActiveMQBuffer extends ChannelBufferWrapper this.message = message; } - private void changed() - { - if (message != null) - { + private void changed() { + if (message != null) { message.bodyChanged(); } } - public void setBuffer(final ActiveMQBuffer buffer) - { - if (this.buffer != null) - { + public void setBuffer(final ActiveMQBuffer buffer) { + if (this.buffer != null) { this.buffer.release(); } this.buffer = buffer.byteBuf(); } @Override - public void clear() - { + public void clear() { changed(); buffer.clear(); @@ -90,12 +82,10 @@ public final class ResetLimitWrappedActiveMQBuffer extends ChannelBufferWrapper } @Override - public void readerIndex(int readerIndex) - { + public void readerIndex(int readerIndex) { changed(); - if (readerIndex < limit) - { + if (readerIndex < limit) { readerIndex = limit; } @@ -103,44 +93,37 @@ public final class ResetLimitWrappedActiveMQBuffer extends ChannelBufferWrapper } @Override - public void resetReaderIndex() - { + public void resetReaderIndex() { changed(); buffer.readerIndex(limit); } @Override - public void resetWriterIndex() - { + public void resetWriterIndex() { changed(); buffer.writerIndex(limit); } @Override - public void setIndex(int readerIndex, int writerIndex) - { + public void setIndex(int readerIndex, int writerIndex) { changed(); - if (readerIndex < limit) - { + if (readerIndex < limit) { readerIndex = limit; } - if (writerIndex < limit) - { + if (writerIndex < limit) { writerIndex = limit; } buffer.setIndex(readerIndex, writerIndex); } @Override - public void writerIndex(int writerIndex) - { + public void writerIndex(int writerIndex) { changed(); - if (writerIndex < limit) - { + if (writerIndex < limit) { writerIndex = limit; } @@ -148,248 +131,217 @@ public final class ResetLimitWrappedActiveMQBuffer extends ChannelBufferWrapper } @Override - public void setByte(final int index, final byte value) - { + public void setByte(final int index, final byte value) { changed(); super.setByte(index, value); } @Override - public void setBytes(final int index, final byte[] src, final int srcIndex, final int length) - { + public void setBytes(final int index, final byte[] src, final int srcIndex, final int length) { changed(); super.setBytes(index, src, srcIndex, length); } @Override - public void setBytes(final int index, final byte[] src) - { + public void setBytes(final int index, final byte[] src) { changed(); super.setBytes(index, src); } @Override - public void setBytes(final int index, final ByteBuffer src) - { + public void setBytes(final int index, final ByteBuffer src) { changed(); super.setBytes(index, src); } @Override - public void setBytes(final int index, final ActiveMQBuffer src, final int srcIndex, final int length) - { + public void setBytes(final int index, final ActiveMQBuffer src, final int srcIndex, final int length) { changed(); super.setBytes(index, src, srcIndex, length); } @Override - public void setBytes(final int index, final ActiveMQBuffer src, final int length) - { + public void setBytes(final int index, final ActiveMQBuffer src, final int length) { changed(); super.setBytes(index, src, length); } @Override - public void setBytes(final int index, final ActiveMQBuffer src) - { + public void setBytes(final int index, final ActiveMQBuffer src) { changed(); super.setBytes(index, src); } @Override - public void setChar(final int index, final char value) - { + public void setChar(final int index, final char value) { changed(); super.setChar(index, value); } @Override - public void setDouble(final int index, final double value) - { + public void setDouble(final int index, final double value) { changed(); super.setDouble(index, value); } @Override - public void setFloat(final int index, final float value) - { + public void setFloat(final int index, final float value) { changed(); super.setFloat(index, value); } @Override - public void setInt(final int index, final int value) - { + public void setInt(final int index, final int value) { changed(); super.setInt(index, value); } @Override - public void setLong(final int index, final long value) - { + public void setLong(final int index, final long value) { changed(); super.setLong(index, value); } @Override - public void setShort(final int index, final short value) - { + public void setShort(final int index, final short value) { changed(); super.setShort(index, value); } @Override - public void writeBoolean(final boolean val) - { + public void writeBoolean(final boolean val) { changed(); super.writeBoolean(val); } @Override - public void writeByte(final byte value) - { + public void writeByte(final byte value) { changed(); super.writeByte(value); } @Override - public void writeBytes(final byte[] src, final int srcIndex, final int length) - { + public void writeBytes(final byte[] src, final int srcIndex, final int length) { changed(); super.writeBytes(src, srcIndex, length); } @Override - public void writeBytes(final byte[] src) - { + public void writeBytes(final byte[] src) { changed(); super.writeBytes(src); } @Override - public void writeBytes(final ByteBuffer src) - { + public void writeBytes(final ByteBuffer src) { changed(); super.writeBytes(src); } @Override - public void writeBytes(final ActiveMQBuffer src, final int srcIndex, final int length) - { + public void writeBytes(final ActiveMQBuffer src, final int srcIndex, final int length) { changed(); super.writeBytes(src, srcIndex, length); } @Override - public void writeBytes(final ActiveMQBuffer src, final int length) - { + public void writeBytes(final ActiveMQBuffer src, final int length) { changed(); super.writeBytes(src, length); } @Override - public void writeChar(final char chr) - { + public void writeChar(final char chr) { changed(); super.writeChar(chr); } @Override - public void writeDouble(final double value) - { + public void writeDouble(final double value) { changed(); super.writeDouble(value); } @Override - public void writeFloat(final float value) - { + public void writeFloat(final float value) { changed(); super.writeFloat(value); } @Override - public void writeInt(final int value) - { + public void writeInt(final int value) { changed(); super.writeInt(value); } @Override - public void writeLong(final long value) - { + public void writeLong(final long value) { changed(); super.writeLong(value); } @Override - public void writeNullableSimpleString(final SimpleString val) - { + public void writeNullableSimpleString(final SimpleString val) { changed(); super.writeNullableSimpleString(val); } @Override - public void writeNullableString(final String val) - { + public void writeNullableString(final String val) { changed(); super.writeNullableString(val); } @Override - public void writeShort(final short value) - { + public void writeShort(final short value) { changed(); super.writeShort(value); } @Override - public void writeSimpleString(final SimpleString val) - { + public void writeSimpleString(final SimpleString val) { changed(); super.writeSimpleString(val); } @Override - public void writeString(final String val) - { + public void writeString(final String val) { changed(); super.writeString(val); } @Override - public void writeUTF(final String utf) - { + public void writeUTF(final String utf) { changed(); super.writeUTF(utf); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/ActiveMQClientLogger.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/ActiveMQClientLogger.java index 8b3d0da9f2..901797c3d7 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/ActiveMQClientLogger.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/ActiveMQClientLogger.java @@ -47,8 +47,8 @@ import org.w3c.dom.Node; * articles. Unused methods should be marked as deprecated. */ @MessageLogger(projectCode = "AMQ") -public interface ActiveMQClientLogger extends BasicLogger -{ +public interface ActiveMQClientLogger extends BasicLogger { + /** * The default logger. */ @@ -92,15 +92,14 @@ public interface ActiveMQClientLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 212007, - value = "connector.create or connectorFactory.createConnector should never throw an exception, implementation is badly behaved, but we will deal with it anyway.", - format = Message.Format.MESSAGE_FORMAT) + value = "connector.create or connectorFactory.createConnector should never throw an exception, implementation is badly behaved, but we will deal with it anyway.", + format = Message.Format.MESSAGE_FORMAT) void createConnectorException(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 212008, - value = "I am closing a core ClientSessionFactory you left open. Please make sure you close all ClientSessionFactories explicitly " - + "before letting them go out of scope! {0}", - format = Message.Format.MESSAGE_FORMAT) + value = "I am closing a core ClientSessionFactory you left open. Please make sure you close all ClientSessionFactories explicitly " + "before letting them go out of scope! {0}", + format = Message.Format.MESSAGE_FORMAT) void factoryLeftOpen(@Cause Exception e, int i); @LogMessage(level = Logger.Level.WARN) @@ -129,8 +128,8 @@ public interface ActiveMQClientLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 212016, - value = "I am closing a core ClientSession you left open. Please make sure you close all ClientSessions explicitly before letting them go out of scope! {0}", - format = Message.Format.MESSAGE_FORMAT) + value = "I am closing a core ClientSession you left open. Please make sure you close all ClientSessions explicitly before letting them go out of scope! {0}", + format = Message.Format.MESSAGE_FORMAT) void clientSessionNotClosed(@Cause Exception e, int identity); @LogMessage(level = Logger.Level.WARN) @@ -183,8 +182,8 @@ public interface ActiveMQClientLogger extends BasicLogger @LogMessage(level = Logger.Level.DEBUG) @Message(id = 212029, - value = "Closing a Server Locator left open. Please make sure you close all Server Locators explicitly before letting them go out of scope! {0}", - format = Message.Format.MESSAGE_FORMAT) + value = "Closing a Server Locator left open. Please make sure you close all Server Locators explicitly before letting them go out of scope! {0}", + format = Message.Format.MESSAGE_FORMAT) void serverLocatorNotClosed(@Cause Exception e, int identity); @LogMessage(level = Logger.Level.WARN) @@ -205,12 +204,8 @@ public interface ActiveMQClientLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 212034, - value = "There are more than one servers on the network broadcasting the same node id. " - + "You will see this message exactly once (per node) if a node is restarted, in which case it can be safely " - + "ignored. But if it is logged continuously it means you really do have more than one node on the same network " - + "active concurrently with the same node id. This could occur if you have a backup node active at the same time as " - + "its live node. nodeID={0}", - format = Message.Format.MESSAGE_FORMAT) + value = "There are more than one servers on the network broadcasting the same node id. " + "You will see this message exactly once (per node) if a node is restarted, in which case it can be safely " + "ignored. But if it is logged continuously it means you really do have more than one node on the same network " + "active concurrently with the same node id. This could occur if you have a backup node active at the same time as " + "its live node. nodeID={0}", + format = Message.Format.MESSAGE_FORMAT) void multipleServersBroadcastingSameNode(String nodeId); @LogMessage(level = Logger.Level.WARN) @@ -219,8 +214,8 @@ public interface ActiveMQClientLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 212036, - value = "Can not find packet to clear: {0} last received command id first stored command id {1}", - format = Message.Format.MESSAGE_FORMAT) + value = "Can not find packet to clear: {0} last received command id first stored command id {1}", + format = Message.Format.MESSAGE_FORMAT) void cannotFindPacketToClear(Integer lastReceivedCommandID, Integer firstStoredCommandID); @LogMessage(level = Logger.Level.WARN) @@ -257,7 +252,7 @@ public interface ActiveMQClientLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 212046, value = "Cannot find activemq-version.properties on classpath: {0}", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void noVersionOnClasspath(String classpath); @LogMessage(level = Logger.Level.WARN) @@ -266,32 +261,32 @@ public interface ActiveMQClientLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 212048, value = "local-bind-address specified for broadcast group but no local-bind-port specified so socket will NOT be bound to a local address/port", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void broadcastGroupBindError(); @LogMessage(level = Logger.Level.WARN) @Message(id = 212049, - value = "Could not bind to {0} ({1} address); " + - "make sure your discovery group-address is of the same type as the IP stack (IPv4 or IPv6)." + - "\nIgnoring discovery group-address, but this may lead to cross talking.", - format = Message.Format.MESSAGE_FORMAT) + value = "Could not bind to {0} ({1} address); " + + "make sure your discovery group-address is of the same type as the IP stack (IPv4 or IPv6)." + + "\nIgnoring discovery group-address, but this may lead to cross talking.", + format = Message.Format.MESSAGE_FORMAT) void ioDiscoveryError(String hostAddress, String s); @LogMessage(level = Logger.Level.WARN) @Message(id = 212050, value = "Compressed large message tried to read {0} bytes from stream {1}", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void compressedLargeMessageError(int length, int nReadBytes); @LogMessage(level = Logger.Level.WARN) @Message(id = 212051, - value = "Invalid concurrent session usage. Sessions are not supposed to be used by more than one thread concurrently.", - format = Message.Format.MESSAGE_FORMAT) + value = "Invalid concurrent session usage. Sessions are not supposed to be used by more than one thread concurrently.", + format = Message.Format.MESSAGE_FORMAT) void invalidConcurrentSessionUsage(@Cause Throwable t); @LogMessage(level = Logger.Level.WARN) @Message(id = 212052, - value = "Packet {0} was answered out of sequence due to a previous server timeout and it''s being ignored", - format = Message.Format.MESSAGE_FORMAT) + value = "Packet {0} was answered out of sequence due to a previous server timeout and it''s being ignored", + format = Message.Format.MESSAGE_FORMAT) void packetOutOfOrder(Object obj, @Cause Throwable t); /** @@ -300,15 +295,14 @@ public interface ActiveMQClientLogger extends BasicLogger */ @LogMessage(level = Logger.Level.WARN) @Message(id = 212053, - value = "CompletionListener/SendAcknowledgementHandler used with confirmationWindowSize=-1. Enable confirmationWindowSize to receive acks from server!", - format = Message.Format.MESSAGE_FORMAT) + value = "CompletionListener/SendAcknowledgementHandler used with confirmationWindowSize=-1. Enable confirmationWindowSize to receive acks from server!", + format = Message.Format.MESSAGE_FORMAT) void confirmationWindowDisabledWarning(); - @LogMessage(level = Logger.Level.WARN) @Message(id = 212054, - value = "Destination address={0} is blocked. If the system is configured to block make sure you consume messages on this configuration.", - format = Message.Format.MESSAGE_FORMAT) + value = "Destination address={0} is blocked. If the system is configured to block make sure you consume messages on this configuration.", + format = Message.Format.MESSAGE_FORMAT) void outOfCreditOnFlowControl(String address); @LogMessage(level = Logger.Level.WARN) diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/ActiveMQClientMessageBundle.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/ActiveMQClientMessageBundle.java index 09cb114d05..f0543d1cda 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/ActiveMQClientMessageBundle.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/ActiveMQClientMessageBundle.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.core.client; - import org.apache.activemq.artemis.api.core.ActiveMQAddressFullException; import org.apache.activemq.artemis.api.core.ActiveMQConnectionTimedOutException; import org.apache.activemq.artemis.api.core.ActiveMQDisconnectedException; @@ -46,8 +45,8 @@ import org.w3c.dom.Node; * so 119000 to 119999 */ @MessageBundle(projectCode = "AMQ") -public interface ActiveMQClientMessageBundle -{ +public interface ActiveMQClientMessageBundle { + ActiveMQClientMessageBundle BUNDLE = Messages.getBundle(ActiveMQClientMessageBundle.class); @Message(id = 119000, value = "ClientSession closed while creating session") @@ -65,83 +64,83 @@ public interface ActiveMQClientMessageBundle @Message(id = 119005, value = "Exception in Netty transport") ActiveMQInternalErrorException nettyError(); - @Message(id = 119006, value = "Channel disconnected") + @Message(id = 119006, value = "Channel disconnected") ActiveMQNotConnectedException channelDisconnected(); - @Message(id = 119007, value = "Cannot connect to server(s). Tried with all available servers.") + @Message(id = 119007, value = "Cannot connect to server(s). Tried with all available servers.") ActiveMQNotConnectedException cannotConnectToServers(); - @Message(id = 119008, value = "Failed to connect to any static connectors") + @Message(id = 119008, value = "Failed to connect to any static connectors") ActiveMQNotConnectedException cannotConnectToStaticConnectors(@Cause Exception e); - @Message(id = 119009, value = "Failed to connect to any static connectors") + @Message(id = 119009, value = "Failed to connect to any static connectors") ActiveMQNotConnectedException cannotConnectToStaticConnectors2(); - @Message(id = 119010, value = "Connection is destroyed") + @Message(id = 119010, value = "Connection is destroyed") ActiveMQNotConnectedException connectionDestroyed(); - @Message(id = 119011, value = "Did not receive data from server for {0}", format = Message.Format.MESSAGE_FORMAT) + @Message(id = 119011, value = "Did not receive data from server for {0}", format = Message.Format.MESSAGE_FORMAT) ActiveMQConnectionTimedOutException connectionTimedOut(Connection transportConnection); - @Message(id = 119012, value = "Timed out waiting to receive initial broadcast from cluster") + @Message(id = 119012, value = "Timed out waiting to receive initial broadcast from cluster") ActiveMQConnectionTimedOutException connectionTimedOutInInitialBroadcast(); - @Message(id = 119013, value = "Timed out waiting to receive cluster topology. Group:{0}", format = Message.Format.MESSAGE_FORMAT) + @Message(id = 119013, value = "Timed out waiting to receive cluster topology. Group:{0}", format = Message.Format.MESSAGE_FORMAT) ActiveMQConnectionTimedOutException connectionTimedOutOnReceiveTopology(DiscoveryGroup discoveryGroup); - @Message(id = 119014, value = "Timed out after waiting {0} ms for response when sending packet {1}", format = Message.Format.MESSAGE_FORMAT) + @Message(id = 119014, value = "Timed out after waiting {0} ms for response when sending packet {1}", format = Message.Format.MESSAGE_FORMAT) ActiveMQConnectionTimedOutException timedOutSendingPacket(long timeout, Byte type); - @Message(id = 119015, value = "The connection was disconnected because of server shutdown") + @Message(id = 119015, value = "The connection was disconnected because of server shutdown") ActiveMQDisconnectedException disconnected(); - @Message(id = 119016, value = "Connection failure detected. Unblocking a blocking call that will never get a response") + @Message(id = 119016, value = "Connection failure detected. Unblocking a blocking call that will never get a response") ActiveMQUnBlockedException unblockingACall(@Cause Throwable t); - @Message(id = 119017, value = "Consumer is closed") + @Message(id = 119017, value = "Consumer is closed") ActiveMQObjectClosedException consumerClosed(); - @Message(id = 119018, value = "Producer is closed") + @Message(id = 119018, value = "Producer is closed") ActiveMQObjectClosedException producerClosed(); - @Message(id = 119019, value = "Session is closed") + @Message(id = 119019, value = "Session is closed") ActiveMQObjectClosedException sessionClosed(); - @Message(id = 119020, value = "Cannot call receive(...) - a MessageHandler is set") + @Message(id = 119020, value = "Cannot call receive(...) - a MessageHandler is set") ActiveMQIllegalStateException messageHandlerSet(); - @Message(id = 119021, value = "Cannot set MessageHandler - consumer is in receive(...)") + @Message(id = 119021, value = "Cannot set MessageHandler - consumer is in receive(...)") ActiveMQIllegalStateException inReceive(); - @Message(id = 119022, value = "Header size ({0}) is too big, use the messageBody for large data, or increase minLargeMessageSize", - format = Message.Format.MESSAGE_FORMAT) + @Message(id = 119022, value = "Header size ({0}) is too big, use the messageBody for large data, or increase minLargeMessageSize", + format = Message.Format.MESSAGE_FORMAT) ActiveMQIllegalStateException headerSizeTooBig(Integer headerSize); - @Message(id = 119023, value = "The large message lost connection with its session, either because of a rollback or a closed session") + @Message(id = 119023, value = "The large message lost connection with its session, either because of a rollback or a closed session") ActiveMQIllegalStateException largeMessageLostSession(); - @Message(id = 119024, value = "Could not select a TransportConfiguration to create SessionFactory") + @Message(id = 119024, value = "Could not select a TransportConfiguration to create SessionFactory") ActiveMQIllegalStateException noTCForSessionFactory(); @Message(id = 119025, value = "Error saving the message body") ActiveMQLargeMessageException errorSavingBody(@Cause Exception e); - @Message(id = 119026, value = "Error reading the LargeMessageBody") + @Message(id = 119026, value = "Error reading the LargeMessageBody") ActiveMQLargeMessageException errorReadingBody(@Cause Exception e); - @Message(id = 119027, value = "Error closing stream from LargeMessageBody") + @Message(id = 119027, value = "Error closing stream from LargeMessageBody") ActiveMQLargeMessageException errorClosingLargeMessage(@Cause Exception e); - @Message(id = 119028, value = "Timeout waiting for LargeMessage Body") + @Message(id = 119028, value = "Timeout waiting for LargeMessage Body") ActiveMQLargeMessageException timeoutOnLargeMessage(); - @Message(id = 119029, value = "Error writing body of message") + @Message(id = 119029, value = "Error writing body of message") ActiveMQLargeMessageException errorWritingLargeMessage(@Cause Exception e); - @Message(id = 119030, value = "The transaction was rolled back on failover to a backup server") + @Message(id = 119030, value = "The transaction was rolled back on failover to a backup server") ActiveMQTransactionRolledBackException txRolledBack(); - @Message(id = 119031, value = "The transaction was rolled back on failover however commit may have been successful") + @Message(id = 119031, value = "The transaction was rolled back on failover however commit may have been successful") ActiveMQTransactionOutcomeUnknownException txOutcomeUnknown(); @Message(id = 119032, value = "Invalid type: {0}", format = Message.Format.MESSAGE_FORMAT) @@ -151,7 +150,7 @@ public interface ActiveMQClientMessageBundle IllegalArgumentException invalidEncodeType(Object type); @Message(id = 119034, value = "Params for management operations must be of the following type: int long double String boolean Map or array thereof but found {0}", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) IllegalArgumentException invalidManagementParam(Object type); @Message(id = 119035, value = "Invalid window size {0}", format = Message.Format.MESSAGE_FORMAT) @@ -223,8 +222,7 @@ public interface ActiveMQClientMessageBundle @Message(id = 119058, value = "Address \"{0}\" is full. Message encode size = {1}B", format = Message.Format.MESSAGE_FORMAT) ActiveMQAddressFullException addressIsFull(String addressName, int size); - @Message(id = 119059, value = "Interceptor {0} rejected packet in a blocking call. This call will never complete." - , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 119059, value = "Interceptor {0} rejected packet in a blocking call. This call will never complete.", format = Message.Format.MESSAGE_FORMAT) ActiveMQInterceptorRejectedPacketException interceptorRejectedPacket(String interceptionResult); @Message(id = 119060, value = "Large Message Transmission interrupted on consumer shutdown.") diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ActiveMQXAResource.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ActiveMQXAResource.java index 9e4756c4a0..7ac184f0a4 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ActiveMQXAResource.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ActiveMQXAResource.java @@ -18,7 +18,7 @@ package org.apache.activemq.artemis.core.client.impl; import javax.transaction.xa.XAResource; -public interface ActiveMQXAResource extends XAResource -{ +public interface ActiveMQXAResource extends XAResource { + XAResource getResource(); } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/AddressQueryImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/AddressQueryImpl.java index a92b8af135..96aed1da9d 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/AddressQueryImpl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/AddressQueryImpl.java @@ -22,33 +22,31 @@ import java.util.List; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.client.ClientSession; -public class AddressQueryImpl implements ClientSession.AddressQuery -{ +public class AddressQueryImpl implements ClientSession.AddressQuery { + private final boolean exists; private final ArrayList queueNames; private final boolean autoCreateJmsQueues; - public AddressQueryImpl(final boolean exists, final List queueNames, final boolean autoCreateJmsQueues) - { + public AddressQueryImpl(final boolean exists, + final List queueNames, + final boolean autoCreateJmsQueues) { this.exists = exists; this.queueNames = new ArrayList(queueNames); this.autoCreateJmsQueues = autoCreateJmsQueues; } - public List getQueueNames() - { + public List getQueueNames() { return queueNames; } - public boolean isExists() - { + public boolean isExists() { return exists; } - public boolean isAutoCreateJmsQueues() - { + public boolean isAutoCreateJmsQueues() { return autoCreateJmsQueues; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/AfterConnectInternalListener.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/AfterConnectInternalListener.java index 0fc7cc76d4..8267a702b8 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/AfterConnectInternalListener.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/AfterConnectInternalListener.java @@ -21,7 +21,7 @@ package org.apache.activemq.artemis.core.client.impl; * This listener is not part of the API and shouldn't be used by users. * (if you do so we can't guarantee any API compatibility on this class) */ -public interface AfterConnectInternalListener -{ +public interface AfterConnectInternalListener { + void onConnection(ClientSessionFactoryInternal sf); } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientConsumerImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientConsumerImpl.java index b9cccecc87..080a5dd02e 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientConsumerImpl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientConsumerImpl.java @@ -44,8 +44,7 @@ import org.apache.activemq.artemis.utils.PriorityLinkedListImpl; import org.apache.activemq.artemis.utils.ReusableLatch; import org.apache.activemq.artemis.utils.TokenBucketLimiter; -public final class ClientConsumerImpl implements ClientConsumerInternal -{ +public final class ClientConsumerImpl implements ClientConsumerInternal { // Constants // ------------------------------------------------------------------------------------ @@ -145,8 +144,7 @@ public final class ClientConsumerImpl implements ClientConsumerInternal final Executor flowControlExecutor, final SessionContext sessionContext, final ClientSession.QueueQuery queueInfo, - final ClassLoader contextClassLoader) - { + final ClassLoader contextClassLoader) { this.consumerContext = consumerContext; this.queueName = queueName; @@ -177,34 +175,28 @@ public final class ClientConsumerImpl implements ClientConsumerInternal // ClientConsumer implementation // ----------------------------------------------------------------- - public ConsumerContext getConsumerContext() - { + public ConsumerContext getConsumerContext() { return consumerContext; } - private ClientMessage receive(final long timeout, final boolean forcingDelivery) throws ActiveMQException - { + private ClientMessage receive(final long timeout, final boolean forcingDelivery) throws ActiveMQException { checkClosed(); - if (largeMessageReceived != null) - { + if (largeMessageReceived != null) { // Check if there are pending packets to be received largeMessageReceived.discardBody(); largeMessageReceived = null; } - if (rateLimiter != null) - { + if (rateLimiter != null) { rateLimiter.limit(); } - if (handler != null) - { + if (handler != null) { throw ActiveMQClientMessageBundle.BUNDLE.messageHandlerSet(); } - if (clientWindowSize == 0) - { + if (clientWindowSize == 0) { startSlowConsumer(); } @@ -219,47 +211,36 @@ public final class ClientConsumerImpl implements ClientConsumerInternal long toWait = timeout == 0 ? Long.MAX_VALUE : timeout; - try - { - while (true) - { + try { + while (true) { ClientMessageInternal m = null; - synchronized (this) - { - while ((stopped || (m = buffer.poll()) == null) && !closed && toWait > 0) - { - if (start == -1) - { + synchronized (this) { + while ((stopped || (m = buffer.poll()) == null) && !closed && toWait > 0) { + if (start == -1) { start = System.currentTimeMillis(); } - if (m == null && forcingDelivery) - { - if (stopped) - { + if (m == null && forcingDelivery) { + if (stopped) { break; } // we only force delivery once per call to receive - if (!deliveryForced) - { + if (!deliveryForced) { callForceDelivery = true; break; } } - try - { + try { wait(toWait); } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } - if (m != null || closed) - { + if (m != null || closed) { break; } @@ -271,26 +252,21 @@ public final class ClientConsumerImpl implements ClientConsumerInternal } } - if (failedOver) - { - if (m == null) - { + if (failedOver) { + if (m == null) { // if failed over and the buffer is null, we reset the state and try it again failedOver = false; deliveryForced = false; toWait = timeout == 0 ? Long.MAX_VALUE : timeout; continue; } - else - { + else { failedOver = false; } } - if (callForceDelivery) - { - if (isTrace) - { + if (callForceDelivery) { + if (isTrace) { ActiveMQClientLogger.LOGGER.trace("Forcing delivery"); } // JBPAPP-6030 - Calling forceDelivery outside of the lock to avoid distributed dead locks @@ -300,32 +276,26 @@ public final class ClientConsumerImpl implements ClientConsumerInternal continue; } - if (m != null) - { + if (m != null) { session.workDone(); - if (m.containsProperty(ClientConsumerImpl.FORCED_DELIVERY_MESSAGE)) - { + if (m.containsProperty(ClientConsumerImpl.FORCED_DELIVERY_MESSAGE)) { long seq = m.getLongProperty(ClientConsumerImpl.FORCED_DELIVERY_MESSAGE); // Need to check if forceDelivery was called at this call // As we could be receiving a message that came from a previous call - if (forcingDelivery && deliveryForced && seq == forceDeliveryCount - 1) - { + if (forcingDelivery && deliveryForced && seq == forceDeliveryCount - 1) { // forced delivery messages are discarded, nothing has been delivered by the queue resetIfSlowConsumer(); - if (isTrace) - { + if (isTrace) { ActiveMQClientLogger.LOGGER.trace("There was nothing on the queue, leaving it now:: returning null"); } return null; } - else - { - if (isTrace) - { + else { + if (isTrace) { ActiveMQClientLogger.LOGGER.trace("Ignored force delivery answer as it belonged to another call"); } // Ignore the message @@ -337,43 +307,35 @@ public final class ClientConsumerImpl implements ClientConsumerInternal flowControlBeforeConsumption(m); - if (expired) - { + if (expired) { m.discardBody(); session.expire(this, m); - if (clientWindowSize == 0) - { + if (clientWindowSize == 0) { startSlowConsumer(); } - if (toWait > 0) - { + if (toWait > 0) { continue; } - else - { + else { return null; } } - if (m.isLargeMessage()) - { + if (m.isLargeMessage()) { largeMessageReceived = m; } - if (isTrace) - { + if (isTrace) { ActiveMQClientLogger.LOGGER.trace("Returning " + m); } return m; } - else - { - if (isTrace) - { + else { + if (isTrace) { ActiveMQClientLogger.LOGGER.trace("Returning null"); } resetIfSlowConsumer(); @@ -381,36 +343,30 @@ public final class ClientConsumerImpl implements ClientConsumerInternal } } } - finally - { + finally { receiverThread = null; } } - public ClientMessage receive(final long timeout) throws ActiveMQException - { + public ClientMessage receive(final long timeout) throws ActiveMQException { ClientMessage msg = receive(timeout, false); - if (msg == null && !closed) - { + if (msg == null && !closed) { msg = receive(0, true); } return msg; } - public ClientMessage receive() throws ActiveMQException - { + public ClientMessage receive() throws ActiveMQException { return receive(0, false); } - public ClientMessage receiveImmediate() throws ActiveMQException - { + public ClientMessage receiveImmediate() throws ActiveMQException { return receive(0, true); } - public MessageHandler getMessageHandler() throws ActiveMQException - { + public MessageHandler getMessageHandler() throws ActiveMQException { checkClosed(); return handler; @@ -418,61 +374,52 @@ public final class ClientConsumerImpl implements ClientConsumerInternal // Must be synchronized since messages may be arriving while handler is being set and might otherwise end // up not queueing enough executors - so messages get stranded - public synchronized ClientConsumerImpl setMessageHandler(final MessageHandler theHandler) throws ActiveMQException - { + public synchronized ClientConsumerImpl setMessageHandler(final MessageHandler theHandler) throws ActiveMQException { checkClosed(); - if (receiverThread != null) - { + if (receiverThread != null) { throw ActiveMQClientMessageBundle.BUNDLE.inReceive(); } boolean noPreviousHandler = handler == null; - if (handler != theHandler && clientWindowSize == 0) - { + if (handler != theHandler && clientWindowSize == 0) { startSlowConsumer(); } handler = theHandler; // if no previous handler existed queue up messages for delivery - if (handler != null && noPreviousHandler) - { + if (handler != null && noPreviousHandler) { requeueExecutors(); } // if unsetting a previous handler may be in onMessage so wait for completion - else if (handler == null && !noPreviousHandler) - { + else if (handler == null && !noPreviousHandler) { waitForOnMessageToComplete(true); } return this; } - public void close() throws ActiveMQException - { + public void close() throws ActiveMQException { doCleanUp(true); } /** * To be used by MDBs to stop any more handling of messages. * - * @throws ActiveMQException * @param future the future to run once the onMessage Thread has completed + * @throws ActiveMQException */ - public Thread prepareForClose(final FutureLatch future) throws ActiveMQException - { + public Thread prepareForClose(final FutureLatch future) throws ActiveMQException { closing = true; resetLargeMessageController(); //execute the future after the last onMessage call - sessionExecutor.execute(new Runnable() - { + sessionExecutor.execute(new Runnable() { @Override - public void run() - { + public void run() { future.run(); } }); @@ -480,37 +427,29 @@ public final class ClientConsumerImpl implements ClientConsumerInternal return onMessageThread; } - public void cleanUp() - { - try - { + public void cleanUp() { + try { doCleanUp(false); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { ActiveMQClientLogger.LOGGER.warn("problem cleaning up: " + this); } } - public boolean isClosed() - { + public boolean isClosed() { return closed; } - public void stop(final boolean waitForOnMessage) throws ActiveMQException - { + public void stop(final boolean waitForOnMessage) throws ActiveMQException { waitForOnMessageToComplete(waitForOnMessage); - if (browseOnly) - { + if (browseOnly) { // stop shouldn't affect browser delivery return; } - synchronized (this) - { - if (stopped) - { + synchronized (this) { + if (stopped) { return; } @@ -518,8 +457,7 @@ public final class ClientConsumerImpl implements ClientConsumerInternal } } - public void clearAtFailover() - { + public void clearAtFailover() { clearBuffer(); // failover will issue a start later @@ -536,70 +474,57 @@ public final class ClientConsumerImpl implements ClientConsumerInternal ackIndividually = false; } - public synchronized void start() - { + public synchronized void start() { stopped = false; requeueExecutors(); } - public Exception getLastException() - { + public Exception getLastException() { return lastException; } // ClientConsumerInternal implementation // -------------------------------------------------------------- - public ClientSession.QueueQuery getQueueInfo() - { + public ClientSession.QueueQuery getQueueInfo() { return queueInfo; } - public SimpleString getFilterString() - { + public SimpleString getFilterString() { return filterString; } - public SimpleString getQueueName() - { + public SimpleString getQueueName() { return queueName; } - public boolean isBrowseOnly() - { + public boolean isBrowseOnly() { return browseOnly; } - public synchronized void handleMessage(final ClientMessageInternal message) throws Exception - { - if (closing) - { + public synchronized void handleMessage(final ClientMessageInternal message) throws Exception { + if (closing) { // This is ok - we just ignore the message return; } - if (message.getBooleanProperty(Message.HDR_LARGE_COMPRESSED)) - { + if (message.getBooleanProperty(Message.HDR_LARGE_COMPRESSED)) { handleCompressedMessage(message); } - else - { + else { handleRegularMessage(message); } } - private void handleRegularMessage(ClientMessageInternal message) - { - if (message.getAddress() == null) - { + private void handleRegularMessage(ClientMessageInternal message) { + if (message.getAddress() == null) { message.setAddressTransient(queueInfo.getAddress()); } message.onReceipt(this); - if (!ackIndividually && message.getPriority() != 4 && !message.containsProperty(ClientConsumerImpl.FORCED_DELIVERY_MESSAGE)) - { + if (!ackIndividually && message.getPriority() != 4 && !message.containsProperty(ClientConsumerImpl.FORCED_DELIVERY_MESSAGE)) { // We have messages of different priorities so we need to ack them individually since the order // of them in the ServerConsumerImpl delivery list might not be the same as the order they are // consumed in, which means that acking all up to won't work @@ -609,16 +534,13 @@ public final class ClientConsumerImpl implements ClientConsumerInternal // Add it to the buffer buffer.addTail(message, message.getPriority()); - if (handler != null) - { + if (handler != null) { // Execute using executor - if (!stopped) - { + if (!stopped) { queueExecutor(); } } - else - { + else { notify(); } } @@ -635,17 +557,14 @@ public final class ClientConsumerImpl implements ClientConsumerInternal * Say that you sent a 1G message full of spaces. That could be just bellow 100K compressed but you wouldn't have * enough memory to decompress it */ - private void handleCompressedMessage(final ClientMessageInternal clMessage) throws Exception - { + private void handleCompressedMessage(final ClientMessageInternal clMessage) throws Exception { ClientLargeMessageImpl largeMessage = new ClientLargeMessageImpl(); largeMessage.retrieveExistingData(clMessage); File largeMessageCache = null; - if (session.isCacheLargeMessageClient()) - { - largeMessageCache = File.createTempFile("tmp-large-message-" + largeMessage.getMessageID() + "-", - ".tmp"); + if (session.isCacheLargeMessageClient()) { + largeMessageCache = File.createTempFile("tmp-large-message-" + largeMessage.getMessageID() + "-", ".tmp"); largeMessageCache.deleteOnExit(); } @@ -667,10 +586,9 @@ public final class ClientConsumerImpl implements ClientConsumerInternal handleRegularMessage(largeMessage); } - public synchronized void handleLargeMessage(final ClientLargeMessageInternal clientLargeMessage, long largeMessageSize) throws Exception - { - if (closing) - { + public synchronized void handleLargeMessage(final ClientLargeMessageInternal clientLargeMessage, + long largeMessageSize) throws Exception { + if (closing) { // This is ok - we just ignore the message return; } @@ -678,10 +596,8 @@ public final class ClientConsumerImpl implements ClientConsumerInternal // Flow control for the first packet, we will have others File largeMessageCache = null; - if (session.isCacheLargeMessageClient()) - { - largeMessageCache = File.createTempFile("tmp-large-message-" + clientLargeMessage.getMessageID() + "-", - ".tmp"); + if (session.isCacheLargeMessageClient()) { + largeMessageCache = File.createTempFile("tmp-large-message-" + clientLargeMessage.getMessageID() + "-", ".tmp"); largeMessageCache.deleteOnExit(); } @@ -691,74 +607,61 @@ public final class ClientConsumerImpl implements ClientConsumerInternal currentLargeMessageController = new LargeMessageControllerImpl(this, largeMessageSize, callTimeout, largeMessageCache); - if (clientLargeMessage.isCompressed()) - { + if (clientLargeMessage.isCompressed()) { clientLargeMessage.setLargeMessageController(new CompressedLargeMessageControllerImpl(currentLargeMessageController)); } - else - { + else { clientLargeMessage.setLargeMessageController(currentLargeMessageController); } handleRegularMessage(clientLargeMessage); } - public synchronized void handleLargeMessageContinuation(final byte[] chunk, final int flowControlSize, final boolean isContinues) throws Exception - { - if (closing) - { + public synchronized void handleLargeMessageContinuation(final byte[] chunk, + final int flowControlSize, + final boolean isContinues) throws Exception { + if (closing) { return; } - if (currentLargeMessageController == null) - { - if (isTrace) - { + if (currentLargeMessageController == null) { + if (isTrace) { ActiveMQClientLogger.LOGGER.trace("Sending back credits for largeController = null " + flowControlSize); } flowControl(flowControlSize, false); } - else - { + else { currentLargeMessageController.addPacket(chunk, flowControlSize, isContinues); } } - public void clear(boolean waitForOnMessage) throws ActiveMQException - { - synchronized (this) - { + public void clear(boolean waitForOnMessage) throws ActiveMQException { + synchronized (this) { // Need to send credits for the messages in the buffer Iterator iter = buffer.iterator(); - while (iter.hasNext()) - { - try - { + while (iter.hasNext()) { + try { ClientMessageInternal message = iter.next(); - if (message.isLargeMessage()) - { + if (message.isLargeMessage()) { ClientLargeMessageInternal largeMessage = (ClientLargeMessageInternal) message; largeMessage.getLargeMessageController().cancel(); } flowControlBeforeConsumption(message); } - catch (Exception e) - { + catch (Exception e) { ActiveMQClientLogger.LOGGER.errorClearingMessages(e); } } clearBuffer(); - try - { + try { resetLargeMessageController(); } - catch (Throwable e) - { + catch (Throwable e) { // nothing that could be done here ActiveMQClientLogger.LOGGER.errorClearingMessages(e); } @@ -769,64 +672,51 @@ public final class ClientConsumerImpl implements ClientConsumerInternal waitForOnMessageToComplete(waitForOnMessage); } - private void resetLargeMessageController() - { + private void resetLargeMessageController() { LargeMessageController controller = currentLargeMessageController; - if (controller != null) - { + if (controller != null) { controller.cancel(); currentLargeMessageController = null; } } - public int getClientWindowSize() - { + public int getClientWindowSize() { return clientWindowSize; } - public int getBufferSize() - { + public int getBufferSize() { return buffer.size(); } - public void acknowledge(final ClientMessage message) throws ActiveMQException - { + public void acknowledge(final ClientMessage message) throws ActiveMQException { ClientMessageInternal cmi = (ClientMessageInternal) message; - if (ackIndividually) - { + if (ackIndividually) { individualAcknowledge(message); } - else - { + else { ackBytes += message.getEncodeSize(); - if (ackBytes >= ackBatchSize) - { + if (ackBytes >= ackBatchSize) { doAck(cmi); } - else - { + else { lastAckedMessage = cmi; } } } - public void individualAcknowledge(ClientMessage message) throws ActiveMQException - { - if (lastAckedMessage != null) - { + public void individualAcknowledge(ClientMessage message) throws ActiveMQException { + if (lastAckedMessage != null) { flushAcks(); } session.individualAcknowledge(this, message); } - public void flushAcks() throws ActiveMQException - { - if (lastAckedMessage != null) - { + public void flushAcks() throws ActiveMQException { + if (lastAckedMessage != null) { doAck(lastAckedMessage); } } @@ -837,18 +727,13 @@ public final class ClientConsumerImpl implements ClientConsumerInternal * * @param discountSlowConsumer When dealing with slowConsumers, we need to discount one credit that was pre-sent when the first receive was called. For largeMessage that is only done at the latest packet */ - public void flowControl(final int messageBytes, final boolean discountSlowConsumer) throws ActiveMQException - { - if (clientWindowSize >= 0) - { + public void flowControl(final int messageBytes, final boolean discountSlowConsumer) throws ActiveMQException { + if (clientWindowSize >= 0) { creditsToSend += messageBytes; - if (creditsToSend >= clientWindowSize) - { - if (clientWindowSize == 0 && discountSlowConsumer) - { - if (isTrace) - { + if (creditsToSend >= clientWindowSize) { + if (clientWindowSize == 0 && discountSlowConsumer) { + if (isTrace) { ActiveMQClientLogger.LOGGER.trace("FlowControl::Sending " + creditsToSend + " -1, for slow consumer"); } @@ -858,15 +743,12 @@ public final class ClientConsumerImpl implements ClientConsumerInternal creditsToSend = 0; - if (credits > 0) - { + if (credits > 0) { sendCredits(credits); } } - else - { - if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) - { + else { + if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) { ActiveMQClientLogger.LOGGER.debug("Sending " + messageBytes + " from flow-control"); } @@ -874,8 +756,7 @@ public final class ClientConsumerImpl implements ClientConsumerInternal creditsToSend = 0; - if (credits > 0) - { + if (credits > 0) { sendCredits(credits); } } @@ -898,66 +779,52 @@ public final class ClientConsumerImpl implements ClientConsumerInternal /** * Sending an initial credit for slow consumers */ - private void startSlowConsumer() - { - if (isTrace) - { + private void startSlowConsumer() { + if (isTrace) { ActiveMQClientLogger.LOGGER.trace("Sending 1 credit to start delivering of one message to slow consumer"); } sendCredits(1); - try - { + try { // We use an executor here to guarantee the messages will arrive in order. // However when starting a slow consumer, we have to guarantee the credit was sent before we can perform any // operations like forceDelivery pendingFlowControl.await(10, TimeUnit.SECONDS); } - catch (InterruptedException e) - { + catch (InterruptedException e) { // will just ignore and forward the ignored Thread.currentThread().interrupt(); } } - private void resetIfSlowConsumer() - { - if (clientWindowSize == 0) - { + private void resetIfSlowConsumer() { + if (clientWindowSize == 0) { sendCredits(0); // If resetting a slow consumer, we need to wait the execution final CountDownLatch latch = new CountDownLatch(1); - flowControlExecutor.execute(new Runnable() - { - public void run() - { + flowControlExecutor.execute(new Runnable() { + public void run() { latch.countDown(); } }); - try - { + try { latch.await(10, TimeUnit.SECONDS); } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } } } - private void requeueExecutors() - { - for (int i = 0; i < buffer.size(); i++) - { + private void requeueExecutors() { + for (int i = 0; i < buffer.size(); i++) { queueExecutor(); } } - private void queueExecutor() - { - if (isTrace) - { + private void queueExecutor() { + if (isTrace) { ActiveMQClientLogger.LOGGER.trace("Adding Runner on Executor for delivery"); } @@ -967,34 +834,26 @@ public final class ClientConsumerImpl implements ClientConsumerInternal /** * @param credits */ - private void sendCredits(final int credits) - { + private void sendCredits(final int credits) { pendingFlowControl.countUp(); - flowControlExecutor.execute(new Runnable() - { - public void run() - { - try - { + flowControlExecutor.execute(new Runnable() { + public void run() { + try { sessionContext.sendConsumerCredits(ClientConsumerImpl.this, credits); } - finally - { + finally { pendingFlowControl.countDown(); } } }); } - private void waitForOnMessageToComplete(boolean waitForOnMessage) - { - if (handler == null) - { + private void waitForOnMessageToComplete(boolean waitForOnMessage) { + if (handler == null) { return; } - if (!waitForOnMessage || Thread.currentThread() == onMessageThread) - { + if (!waitForOnMessage || Thread.currentThread() == onMessageThread) { // If called from inside onMessage then return immediately - otherwise would block return; } @@ -1005,24 +864,19 @@ public final class ClientConsumerImpl implements ClientConsumerInternal boolean ok = future.await(ClientConsumerImpl.CLOSE_TIMEOUT_MILLISECONDS); - if (!ok) - { + if (!ok) { ActiveMQClientLogger.LOGGER.timeOutWaitingForProcessing(); } } - private void checkClosed() throws ActiveMQException - { - if (closed) - { + private void checkClosed() throws ActiveMQException { + if (closed) { throw ActiveMQClientMessageBundle.BUNDLE.consumerClosed(); } } - private void callOnMessage() throws Exception - { - if (closing || stopped) - { + private void callOnMessage() throws Exception { + if (closing || stopped) { return; } @@ -1038,43 +892,33 @@ public final class ClientConsumerImpl implements ClientConsumerInternal // otherwise while this is executing and give NPE when calling onMessage MessageHandler theHandler = handler; - if (theHandler != null) - { - if (rateLimiter != null) - { + if (theHandler != null) { + if (rateLimiter != null) { rateLimiter.limit(); } failedOver = false; - synchronized (this) - { + synchronized (this) { message = buffer.poll(); } - if (message != null) - { - if (message.containsProperty(ClientConsumerImpl.FORCED_DELIVERY_MESSAGE)) - { + if (message != null) { + if (message.containsProperty(ClientConsumerImpl.FORCED_DELIVERY_MESSAGE)) { //Ignore, this could be a relic from a previous receiveImmediate(); return; } - boolean expired = message.isExpired(); flowControlBeforeConsumption(message); - if (!expired) - { - if (isTrace) - { + if (!expired) { + if (isTrace) { ActiveMQClientLogger.LOGGER.trace("Calling handler.onMessage"); } - final ClassLoader originalLoader = AccessController.doPrivileged(new PrivilegedAction() - { - public ClassLoader run() - { + final ClassLoader originalLoader = AccessController.doPrivileged(new PrivilegedAction() { + public ClassLoader run() { ClassLoader originalLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(contextClassLoader); @@ -1084,49 +928,39 @@ public final class ClientConsumerImpl implements ClientConsumerInternal }); onMessageThread = Thread.currentThread(); - try - { + try { theHandler.onMessage(message); } - finally - { - try - { - AccessController.doPrivileged(new PrivilegedAction() - { - public Object run() - { + finally { + try { + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { Thread.currentThread().setContextClassLoader(originalLoader); return null; } }); } - catch (Exception e) - { + catch (Exception e) { ActiveMQClientLogger.LOGGER.warn(e.getMessage(), e); } onMessageThread = null; } - if (isTrace) - { + if (isTrace) { ActiveMQClientLogger.LOGGER.trace("Handler.onMessage done"); } - if (message.isLargeMessage()) - { + if (message.isLargeMessage()) { message.discardBody(); } } - else - { + else { session.expire(this, message); } // If slow consumer, we need to send 1 credit to make sure we get another message - if (clientWindowSize == 0) - { + if (clientWindowSize == 0) { startSlowConsumer(); } } @@ -1137,22 +971,17 @@ public final class ClientConsumerImpl implements ClientConsumerInternal * @param message * @throws ActiveMQException */ - private void flowControlBeforeConsumption(final ClientMessageInternal message) throws ActiveMQException - { + private void flowControlBeforeConsumption(final ClientMessageInternal message) throws ActiveMQException { // Chunk messages will execute the flow control while receiving the chunks - if (message.getFlowControlSize() != 0) - { + if (message.getFlowControlSize() != 0) { // on large messages we should discount 1 on the first packets as we need continuity until the last packet flowControl(message.getFlowControlSize(), !message.isLargeMessage()); } } - private void doCleanUp(final boolean sendCloseMessage) throws ActiveMQException - { - try - { - if (closed) - { + private void doCleanUp(final boolean sendCloseMessage) throws ActiveMQException { + try { + if (closed) { return; } @@ -1168,10 +997,8 @@ public final class ClientConsumerImpl implements ClientConsumerInternal closed = true; - synchronized (this) - { - if (receiverThread != null) - { + synchronized (this) { + if (receiverThread != null) { // Wake up any receive() thread that might be waiting notify(); } @@ -1185,26 +1012,22 @@ public final class ClientConsumerImpl implements ClientConsumerInternal clearBuffer(); - if (sendCloseMessage) - { + if (sendCloseMessage) { sessionContext.closeConsumer(this); } } - catch (Throwable t) - { + catch (Throwable t) { // Consumer close should always return without exception } session.removeConsumer(this); } - private void clearBuffer() - { + private void clearBuffer() { buffer.clear(); } - private void doAck(final ClientMessageInternal message) throws ActiveMQException - { + private void doAck(final ClientMessageInternal message) throws ActiveMQException { ackBytes = 0; lastAckedMessage = null; @@ -1215,16 +1038,13 @@ public final class ClientConsumerImpl implements ClientConsumerInternal // Inner classes // -------------------------------------------------------------------------------- - private class Runner implements Runnable - { - public void run() - { - try - { + private class Runner implements Runnable { + + public void run() { + try { callOnMessage(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQClientLogger.LOGGER.onMessageError(e); lastException = e; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientConsumerInternal.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientConsumerInternal.java index a61ccf66fc..82f3dbb33c 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientConsumerInternal.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientConsumerInternal.java @@ -23,8 +23,8 @@ import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.utils.FutureLatch; -public interface ClientConsumerInternal extends ClientConsumer -{ +public interface ClientConsumerInternal extends ClientConsumer { + SimpleString getQueueName(); SimpleString getFilterString(); @@ -44,8 +44,8 @@ public interface ClientConsumerInternal extends ClientConsumer /** * To be called by things like MDBs during shutdown of the server * - * @throws ActiveMQException * @param future + * @throws ActiveMQException */ Thread prepareForClose(FutureLatch future) throws ActiveMQException; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientLargeMessageImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientLargeMessageImpl.java index 4b9436428b..78c53c95d8 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientLargeMessageImpl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientLargeMessageImpl.java @@ -31,8 +31,7 @@ import org.apache.activemq.artemis.utils.DataConstants; * At the time of sending a regular Message is sent as we won't know the message is considered large * until the buffer is filled up or the user set a streaming. */ -public final class ClientLargeMessageImpl extends ClientMessageImpl implements ClientLargeMessageInternal -{ +public final class ClientLargeMessageImpl extends ClientMessageImpl implements ClientLargeMessageInternal { // Used only when receiving large messages private LargeMessageController largeMessageController; @@ -42,33 +41,27 @@ public final class ClientLargeMessageImpl extends ClientMessageImpl implements C /** * @param largeMessageSize the largeMessageSize to set */ - public void setLargeMessageSize(long largeMessageSize) - { + public void setLargeMessageSize(long largeMessageSize) { this.largeMessageSize = largeMessageSize; } - public long getLargeMessageSize() - { + public long getLargeMessageSize() { return this.largeMessageSize; } // we only need this constructor as this is only used at decoding large messages on client - public ClientLargeMessageImpl() - { + public ClientLargeMessageImpl() { super(); } // Public -------------------------------------------------------- @Override - public int getEncodeSize() - { - if (bodyBuffer != null) - { + public int getEncodeSize() { + if (bodyBuffer != null) { return super.getEncodeSize(); } - else - { + else { return DataConstants.SIZE_INT + DataConstants.SIZE_INT + getHeadersAndPropertiesEncodeSize(); } } @@ -77,31 +70,25 @@ public final class ClientLargeMessageImpl extends ClientMessageImpl implements C * @return the largeMessage */ @Override - public boolean isLargeMessage() - { + public boolean isLargeMessage() { return true; } - public void setLargeMessageController(final LargeMessageController controller) - { + public void setLargeMessageController(final LargeMessageController controller) { largeMessageController = controller; } - public void checkCompletion() throws ActiveMQException - { + public void checkCompletion() throws ActiveMQException { checkBuffer(); } @Override - public ActiveMQBuffer getBodyBuffer() - { + public ActiveMQBuffer getBodyBuffer() { - try - { + try { checkBuffer(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw new RuntimeException(e.getMessage(), e); } @@ -109,39 +96,31 @@ public final class ClientLargeMessageImpl extends ClientMessageImpl implements C } @Override - public int getBodySize() - { + public int getBodySize() { return getLongProperty(Message.HDR_LARGE_BODY_SIZE).intValue(); } - public LargeMessageController getLargeMessageController() - { + public LargeMessageController getLargeMessageController() { return largeMessageController; } @Override - public void saveToOutputStream(final OutputStream out) throws ActiveMQException - { - if (bodyBuffer != null) - { + public void saveToOutputStream(final OutputStream out) throws ActiveMQException { + if (bodyBuffer != null) { // The body was rebuilt on the client, so we need to behave as a regular message on this case super.saveToOutputStream(out); } - else - { + else { largeMessageController.saveBuffer(out); } } @Override - public ClientLargeMessageImpl setOutputStream(final OutputStream out) throws ActiveMQException - { - if (bodyBuffer != null) - { + public ClientLargeMessageImpl setOutputStream(final OutputStream out) throws ActiveMQException { + if (bodyBuffer != null) { super.setOutputStream(out); } - else - { + else { largeMessageController.setOutputStream(out); } @@ -149,42 +128,33 @@ public final class ClientLargeMessageImpl extends ClientMessageImpl implements C } @Override - public boolean waitOutputStreamCompletion(final long timeMilliseconds) throws ActiveMQException - { - if (bodyBuffer != null) - { + public boolean waitOutputStreamCompletion(final long timeMilliseconds) throws ActiveMQException { + if (bodyBuffer != null) { return super.waitOutputStreamCompletion(timeMilliseconds); } - else - { + else { return largeMessageController.waitCompletion(timeMilliseconds); } } @Override - public void discardBody() - { - if (bodyBuffer != null) - { + public void discardBody() { + if (bodyBuffer != null) { super.discardBody(); } - else - { + else { largeMessageController.discardUnusedPackets(); } } - private void checkBuffer() throws ActiveMQException - { - if (bodyBuffer == null) - { + private void checkBuffer() throws ActiveMQException { + if (bodyBuffer == null) { long bodySize = this.largeMessageSize + BODY_OFFSET; - if (bodySize > Integer.MAX_VALUE) - { + if (bodySize > Integer.MAX_VALUE) { bodySize = Integer.MAX_VALUE; } - createBody((int)bodySize); + createBody((int) bodySize); bodyBuffer = new ResetLimitWrappedActiveMQBuffer(BODY_OFFSET, buffer, this); @@ -194,24 +164,21 @@ public final class ClientLargeMessageImpl extends ClientMessageImpl implements C // Inner classes ------------------------------------------------- - private static class ActiveMQOutputStream extends OutputStream - { + private static class ActiveMQOutputStream extends OutputStream { + private final ActiveMQBuffer bufferOut; - ActiveMQOutputStream(ActiveMQBuffer out) - { + ActiveMQOutputStream(ActiveMQBuffer out) { this.bufferOut = out; } @Override - public void write(int b) throws IOException - { - bufferOut.writeByte((byte)(b & 0xff)); + public void write(int b) throws IOException { + bufferOut.writeByte((byte) (b & 0xff)); } } - public void retrieveExistingData(ClientMessageInternal clMessage) - { + public void retrieveExistingData(ClientMessageInternal clMessage) { this.messageID = clMessage.getMessageID(); this.address = clMessage.getAddress(); this.setUserID(clMessage.getUserID()); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientLargeMessageInternal.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientLargeMessageInternal.java index b9fd1597cf..191a99be73 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientLargeMessageInternal.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientLargeMessageInternal.java @@ -16,9 +16,7 @@ */ package org.apache.activemq.artemis.core.client.impl; - -public interface ClientLargeMessageInternal extends ClientMessageInternal -{ +public interface ClientLargeMessageInternal extends ClientMessageInternal { void setLargeMessageController(LargeMessageController controller); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientMessageImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientMessageImpl.java index 78c443fb9a..7668251842 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientMessageImpl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientMessageImpl.java @@ -33,29 +33,28 @@ import org.apache.activemq.artemis.core.message.impl.MessageImpl; import org.apache.activemq.artemis.reader.MessageUtil; /** - * * A ClientMessageImpl */ -public class ClientMessageImpl extends MessageImpl implements ClientMessageInternal -{ +public class ClientMessageImpl extends MessageImpl implements ClientMessageInternal { + // added this constant here so that the client package have no dependency on JMS public static final SimpleString REPLYTO_HEADER_NAME = MessageUtil.REPLYTO_HEADER_NAME; - private int deliveryCount; private ClientConsumerInternal consumer; private int flowControlSize = -1; - /** Used on LargeMessages only */ + /** + * Used on LargeMessages only + */ private InputStream bodyInputStream; /* * Constructor for when reading from remoting */ - public ClientMessageImpl() - { + public ClientMessageImpl() { } /* @@ -66,41 +65,34 @@ public class ClientMessageImpl extends MessageImpl implements ClientMessageInter final long expiration, final long timestamp, final byte priority, - final int initialMessageBufferSize) - { + final int initialMessageBufferSize) { super(type, durable, expiration, timestamp, priority, initialMessageBufferSize); } @Override - public boolean isServerMessage() - { + public boolean isServerMessage() { return false; } @Override - public void onReceipt(final ClientConsumerInternal consumer) - { + public void onReceipt(final ClientConsumerInternal consumer) { this.consumer = consumer; } @Override - public ClientMessageImpl setDeliveryCount(final int deliveryCount) - { + public ClientMessageImpl setDeliveryCount(final int deliveryCount) { this.deliveryCount = deliveryCount; return this; } @Override - public int getDeliveryCount() - { + public int getDeliveryCount() { return deliveryCount; } @Override - public ClientMessageImpl acknowledge() throws ActiveMQException - { - if (consumer != null) - { + public ClientMessageImpl acknowledge() throws ActiveMQException { + if (consumer != null) { consumer.acknowledge(this); } @@ -108,10 +100,8 @@ public class ClientMessageImpl extends MessageImpl implements ClientMessageInter } @Override - public ClientMessageImpl individualAcknowledge() throws ActiveMQException - { - if (consumer != null) - { + public ClientMessageImpl individualAcknowledge() throws ActiveMQException { + if (consumer != null) { consumer.individualAcknowledge(this); } @@ -119,18 +109,15 @@ public class ClientMessageImpl extends MessageImpl implements ClientMessageInter } @Override - public int getFlowControlSize() - { - if (flowControlSize < 0) - { + public int getFlowControlSize() { + if (flowControlSize < 0) { throw new IllegalStateException("Flow Control hasn't been set"); } return flowControlSize; } @Override - public void setFlowControlSize(final int flowControlSize) - { + public void setFlowControlSize(final int flowControlSize) { this.flowControlSize = flowControlSize; } @@ -138,69 +125,58 @@ public class ClientMessageImpl extends MessageImpl implements ClientMessageInter * @return the largeMessage */ @Override - public boolean isLargeMessage() - { + public boolean isLargeMessage() { return false; } @Override - public boolean isCompressed() - { + public boolean isCompressed() { return properties.getBooleanProperty(Message.HDR_LARGE_COMPRESSED); } @Override - public int getBodySize() - { + public int getBodySize() { return buffer.writerIndex() - buffer.readerIndex(); } @Override - public String toString() - { - return "ClientMessage[messageID=" + messageID + ", durable=" + durable + ", address=" + getAddress() + ",userID=" + (getUserID() != null ? getUserID() : "null") + ",properties=" + properties.toString() + "]"; + public String toString() { + return "ClientMessage[messageID=" + messageID + ", durable=" + durable + ", address=" + getAddress() + ",userID=" + (getUserID() != null ? getUserID() : "null") + ",properties=" + properties.toString() + "]"; } @Override - public void saveToOutputStream(final OutputStream out) throws ActiveMQException - { - try - { + public void saveToOutputStream(final OutputStream out) throws ActiveMQException { + try { byte[] readBuffer = new byte[getBodySize()]; getBodyBuffer().readBytes(readBuffer); out.write(readBuffer); out.flush(); } - catch (IOException e) - { + catch (IOException e) { throw ActiveMQClientMessageBundle.BUNDLE.errorSavingBody(e); } } @Override - public ClientMessageImpl setOutputStream(final OutputStream out) throws ActiveMQException - { + public ClientMessageImpl setOutputStream(final OutputStream out) throws ActiveMQException { saveToOutputStream(out); return this; } @Override - public boolean waitOutputStreamCompletion(final long timeMilliseconds) throws ActiveMQException - { + public boolean waitOutputStreamCompletion(final long timeMilliseconds) throws ActiveMQException { return true; } @Override - public void discardBody() - { + public void discardBody() { } /** * @return the bodyInputStream */ @Override - public InputStream getBodyInputStream() - { + public InputStream getBodyInputStream() { return bodyInputStream; } @@ -208,202 +184,170 @@ public class ClientMessageImpl extends MessageImpl implements ClientMessageInter * @param bodyInputStream the bodyInputStream to set */ @Override - public ClientMessageImpl setBodyInputStream(final InputStream bodyInputStream) - { + public ClientMessageImpl setBodyInputStream(final InputStream bodyInputStream) { this.bodyInputStream = bodyInputStream; return this; } @Override - public BodyEncoder getBodyEncoder() throws ActiveMQException - { + public BodyEncoder getBodyEncoder() throws ActiveMQException { return new DecodingContext(); } @Override - public ClientMessageImpl putBooleanProperty(final SimpleString key, final boolean value) - { + public ClientMessageImpl putBooleanProperty(final SimpleString key, final boolean value) { return (ClientMessageImpl) super.putBooleanProperty(key, value); } @Override - public ClientMessageImpl putByteProperty(final SimpleString key, final byte value) - { + public ClientMessageImpl putByteProperty(final SimpleString key, final byte value) { return (ClientMessageImpl) super.putByteProperty(key, value); } @Override - public ClientMessageImpl putBytesProperty(final SimpleString key, final byte[] value) - { + public ClientMessageImpl putBytesProperty(final SimpleString key, final byte[] value) { return (ClientMessageImpl) super.putBytesProperty(key, value); } @Override - public ClientMessageImpl putCharProperty(SimpleString key, char value) - { + public ClientMessageImpl putCharProperty(SimpleString key, char value) { return (ClientMessageImpl) super.putCharProperty(key, value); } @Override - public ClientMessageImpl putCharProperty(String key, char value) - { + public ClientMessageImpl putCharProperty(String key, char value) { return (ClientMessageImpl) super.putCharProperty(key, value); } @Override - public ClientMessageImpl putShortProperty(final SimpleString key, final short value) - { + public ClientMessageImpl putShortProperty(final SimpleString key, final short value) { return (ClientMessageImpl) super.putShortProperty(key, value); } @Override - public ClientMessageImpl putIntProperty(final SimpleString key, final int value) - { + public ClientMessageImpl putIntProperty(final SimpleString key, final int value) { return (ClientMessageImpl) super.putIntProperty(key, value); } @Override - public ClientMessageImpl putLongProperty(final SimpleString key, final long value) - { + public ClientMessageImpl putLongProperty(final SimpleString key, final long value) { return (ClientMessageImpl) super.putLongProperty(key, value); } @Override - public ClientMessageImpl putFloatProperty(final SimpleString key, final float value) - { + public ClientMessageImpl putFloatProperty(final SimpleString key, final float value) { return (ClientMessageImpl) super.putFloatProperty(key, value); } @Override - public ClientMessageImpl putDoubleProperty(final SimpleString key, final double value) - { + public ClientMessageImpl putDoubleProperty(final SimpleString key, final double value) { return (ClientMessageImpl) super.putDoubleProperty(key, value); } @Override - public ClientMessageImpl putStringProperty(final SimpleString key, final SimpleString value) - { + public ClientMessageImpl putStringProperty(final SimpleString key, final SimpleString value) { return (ClientMessageImpl) super.putStringProperty(key, value); } @Override - public ClientMessageImpl putObjectProperty(final SimpleString key, final Object value) throws ActiveMQPropertyConversionException - { + public ClientMessageImpl putObjectProperty(final SimpleString key, + final Object value) throws ActiveMQPropertyConversionException { return (ClientMessageImpl) super.putObjectProperty(key, value); } @Override - public ClientMessageImpl putObjectProperty(final String key, final Object value) throws ActiveMQPropertyConversionException - { + public ClientMessageImpl putObjectProperty(final String key, + final Object value) throws ActiveMQPropertyConversionException { return (ClientMessageImpl) super.putObjectProperty(key, value); } @Override - public ClientMessageImpl putBooleanProperty(final String key, final boolean value) - { + public ClientMessageImpl putBooleanProperty(final String key, final boolean value) { return (ClientMessageImpl) super.putBooleanProperty(key, value); } @Override - public ClientMessageImpl putByteProperty(final String key, final byte value) - { + public ClientMessageImpl putByteProperty(final String key, final byte value) { return (ClientMessageImpl) super.putByteProperty(key, value); } @Override - public ClientMessageImpl putBytesProperty(final String key, final byte[] value) - { + public ClientMessageImpl putBytesProperty(final String key, final byte[] value) { return (ClientMessageImpl) super.putBytesProperty(key, value); } @Override - public ClientMessageImpl putShortProperty(final String key, final short value) - { + public ClientMessageImpl putShortProperty(final String key, final short value) { return (ClientMessageImpl) super.putShortProperty(key, value); } @Override - public ClientMessageImpl putIntProperty(final String key, final int value) - { + public ClientMessageImpl putIntProperty(final String key, final int value) { return (ClientMessageImpl) super.putIntProperty(key, value); } @Override - public ClientMessageImpl putLongProperty(final String key, final long value) - { + public ClientMessageImpl putLongProperty(final String key, final long value) { return (ClientMessageImpl) super.putLongProperty(key, value); } @Override - public ClientMessageImpl putFloatProperty(final String key, final float value) - { + public ClientMessageImpl putFloatProperty(final String key, final float value) { return (ClientMessageImpl) super.putFloatProperty(key, value); } @Override - public ClientMessageImpl putDoubleProperty(final String key, final double value) - { + public ClientMessageImpl putDoubleProperty(final String key, final double value) { return (ClientMessageImpl) super.putDoubleProperty(key, value); } @Override - public ClientMessageImpl putStringProperty(final String key, final String value) - { + public ClientMessageImpl putStringProperty(final String key, final String value) { return (ClientMessageImpl) super.putStringProperty(key, value); } @Override - public ClientMessageImpl writeBodyBufferBytes(byte[] bytes) - { + public ClientMessageImpl writeBodyBufferBytes(byte[] bytes) { return (ClientMessageImpl) super.writeBodyBufferBytes(bytes); } @Override - public ClientMessageImpl writeBodyBufferString(String string) - { + public ClientMessageImpl writeBodyBufferString(String string) { return (ClientMessageImpl) super.writeBodyBufferString(string); } - private final class DecodingContext implements BodyEncoder - { - public DecodingContext() - { + private final class DecodingContext implements BodyEncoder { + + public DecodingContext() { } @Override - public void open() - { + public void open() { getBodyBuffer().readerIndex(0); } @Override - public void close() - { + public void close() { } @Override - public long getLargeBodySize() - { - if (isLargeMessage()) - { + public long getLargeBodySize() { + if (isLargeMessage()) { return getBodyBuffer().writerIndex(); } - else - { + else { return getBodyBuffer().writerIndex() - BODY_OFFSET; } } @Override - public int encode(final ByteBuffer bufferRead) throws ActiveMQException - { + public int encode(final ByteBuffer bufferRead) throws ActiveMQException { ActiveMQBuffer buffer1 = ActiveMQBuffers.wrappedBuffer(bufferRead); return encode(buffer1, bufferRead.capacity()); } @Override - public int encode(final ActiveMQBuffer bufferOut, final int size) - { + public int encode(final ActiveMQBuffer bufferOut, final int size) { byte[] bytes = new byte[size]; getWholeBuffer().readBytes(bytes); bufferOut.writeBytes(bytes, 0, size); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientMessageInternal.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientMessageInternal.java index 97cec9c4c3..07d471922e 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientMessageInternal.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientMessageInternal.java @@ -20,15 +20,18 @@ import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.apache.activemq.artemis.utils.TypedProperties; -public interface ClientMessageInternal extends ClientMessage -{ +public interface ClientMessageInternal extends ClientMessage { TypedProperties getProperties(); - /** Size used for FlowControl */ + /** + * Size used for FlowControl + */ int getFlowControlSize(); - /** Size used for FlowControl */ + /** + * Size used for FlowControl + */ void setFlowControlSize(int flowControlSize); void setAddressTransient(SimpleString address); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientProducerCreditManager.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientProducerCreditManager.java index dd53493e92..3c10e1a236 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientProducerCreditManager.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientProducerCreditManager.java @@ -19,8 +19,8 @@ package org.apache.activemq.artemis.core.client.impl; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.spi.core.remoting.SessionContext; -public interface ClientProducerCreditManager -{ +public interface ClientProducerCreditManager { + ClientProducerCredits getCredits(SimpleString address, boolean anon, SessionContext context); void returnCredits(SimpleString address); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientProducerCreditManagerImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientProducerCreditManagerImpl.java index ddfb7d4e3c..30c8376521 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientProducerCreditManagerImpl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientProducerCreditManagerImpl.java @@ -23,8 +23,8 @@ import java.util.Map; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.spi.core.remoting.SessionContext; -public class ClientProducerCreditManagerImpl implements ClientProducerCreditManager -{ +public class ClientProducerCreditManagerImpl implements ClientProducerCreditManager { + public static final int MAX_UNREFERENCED_CREDITS_CACHE_SIZE = 1000; private final Map producerCredits = new LinkedHashMap(); @@ -35,30 +35,26 @@ public class ClientProducerCreditManagerImpl implements ClientProducerCreditMana private int windowSize; - public ClientProducerCreditManagerImpl(final ClientSessionInternal session, final int windowSize) - { + public ClientProducerCreditManagerImpl(final ClientSessionInternal session, final int windowSize) { this.session = session; this.windowSize = windowSize; } - public synchronized ClientProducerCredits getCredits(final SimpleString address, final boolean anon, SessionContext context) - { - if (windowSize == -1) - { + public synchronized ClientProducerCredits getCredits(final SimpleString address, + final boolean anon, + SessionContext context) { + if (windowSize == -1) { return ClientProducerCreditsNoFlowControl.instance; } - else - { + else { boolean needInit = false; ClientProducerCredits credits; - synchronized (this) - { + synchronized (this) { credits = producerCredits.get(address); - if (credits == null) - { + if (credits == null) { // Doesn't need to be fair since session is single threaded credits = new ClientProducerCreditsImpl(session, address, windowSize); needInit = true; @@ -66,15 +62,13 @@ public class ClientProducerCreditManagerImpl implements ClientProducerCreditMana producerCredits.put(address, credits); } - if (!anon) - { + if (!anon) { credits.incrementRefCount(); // Remove from anon credits (if there) unReferencedCredits.remove(address); } - else - { + else { addToUnReferencedCache(address, credits); } } @@ -82,8 +76,7 @@ public class ClientProducerCreditManagerImpl implements ClientProducerCreditMana // The init is done outside of the lock // otherwise packages may arrive with flow control // while this is still sending requests causing a dead lock - if (needInit) - { + if (needInit) { credits.init(context); } @@ -91,50 +84,40 @@ public class ClientProducerCreditManagerImpl implements ClientProducerCreditMana } } - public synchronized void returnCredits(final SimpleString address) - { + public synchronized void returnCredits(final SimpleString address) { ClientProducerCredits credits = producerCredits.get(address); - if (credits != null && credits.decrementRefCount() == 0) - { + if (credits != null && credits.decrementRefCount() == 0) { addToUnReferencedCache(address, credits); } } - public synchronized void receiveCredits(final SimpleString address, final int credits) - { + public synchronized void receiveCredits(final SimpleString address, final int credits) { ClientProducerCredits cr = producerCredits.get(address); - if (cr != null) - { + if (cr != null) { cr.receiveCredits(credits); } } - public synchronized void receiveFailCredits(final SimpleString address, int credits) - { + public synchronized void receiveFailCredits(final SimpleString address, int credits) { ClientProducerCredits cr = producerCredits.get(address); - if (cr != null) - { + if (cr != null) { cr.receiveFailCredits(credits); } } - public synchronized void reset() - { - for (ClientProducerCredits credits : producerCredits.values()) - { + public synchronized void reset() { + for (ClientProducerCredits credits : producerCredits.values()) { credits.reset(); } } - public synchronized void close() - { + public synchronized void close() { windowSize = -1; - for (ClientProducerCredits credits : producerCredits.values()) - { + for (ClientProducerCredits credits : producerCredits.values()) { credits.close(); } @@ -143,22 +126,18 @@ public class ClientProducerCreditManagerImpl implements ClientProducerCreditMana unReferencedCredits.clear(); } - public synchronized int creditsMapSize() - { + public synchronized int creditsMapSize() { return producerCredits.size(); } - public synchronized int unReferencedCreditsSize() - { + public synchronized int unReferencedCreditsSize() { return unReferencedCredits.size(); } - private void addToUnReferencedCache(final SimpleString address, final ClientProducerCredits credits) - { + private void addToUnReferencedCache(final SimpleString address, final ClientProducerCredits credits) { unReferencedCredits.put(address, credits); - if (unReferencedCredits.size() > MAX_UNREFERENCED_CREDITS_CACHE_SIZE) - { + if (unReferencedCredits.size() > MAX_UNREFERENCED_CREDITS_CACHE_SIZE) { // Remove the oldest entry Iterator> iter = unReferencedCredits.entrySet().iterator(); @@ -171,8 +150,7 @@ public class ClientProducerCreditManagerImpl implements ClientProducerCreditMana } } - private void removeEntry(final SimpleString address, final ClientProducerCredits credits) - { + private void removeEntry(final SimpleString address, final ClientProducerCredits credits) { producerCredits.remove(address); credits.releaseOutstanding(); @@ -180,51 +158,40 @@ public class ClientProducerCreditManagerImpl implements ClientProducerCreditMana credits.close(); } + static class ClientProducerCreditsNoFlowControl implements ClientProducerCredits { - static class ClientProducerCreditsNoFlowControl implements ClientProducerCredits - { static ClientProducerCreditsNoFlowControl instance = new ClientProducerCreditsNoFlowControl(); - public void acquireCredits(int credits) throws InterruptedException - { + public void acquireCredits(int credits) throws InterruptedException { } - public void receiveCredits(int credits) - { + public void receiveCredits(int credits) { } - public void receiveFailCredits(int credits) - { + public void receiveFailCredits(int credits) { } - public boolean isBlocked() - { + public boolean isBlocked() { return false; } - public void init(SessionContext ctx) - { + public void init(SessionContext ctx) { } - public void reset() - { + public void reset() { } - public void close() - { + public void close() { } - public void incrementRefCount() - { + public void incrementRefCount() { } - public int decrementRefCount() - { + public int decrementRefCount() { return 1; } - public void releaseOutstanding() - { + public void releaseOutstanding() { } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientProducerCredits.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientProducerCredits.java index 27e1528ef9..443d7e5254 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientProducerCredits.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientProducerCredits.java @@ -19,8 +19,8 @@ package org.apache.activemq.artemis.core.client.impl; import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.spi.core.remoting.SessionContext; -public interface ClientProducerCredits -{ +public interface ClientProducerCredits { + void acquireCredits(int credits) throws InterruptedException, ActiveMQException; void receiveCredits(int credits); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientProducerCreditsImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientProducerCreditsImpl.java index fa4ad1668d..206f18841d 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientProducerCreditsImpl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientProducerCreditsImpl.java @@ -25,8 +25,8 @@ import org.apache.activemq.artemis.spi.core.remoting.SessionContext; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; -public class ClientProducerCreditsImpl implements ClientProducerCredits -{ +public class ClientProducerCreditsImpl implements ClientProducerCredits { + private final Semaphore semaphore; private final int windowSize; @@ -51,8 +51,7 @@ public class ClientProducerCreditsImpl implements ClientProducerCredits public ClientProducerCreditsImpl(final ClientSessionInternal session, final SimpleString address, - final int windowSize) - { + final int windowSize) { this.session = session; this.address = address; @@ -64,8 +63,7 @@ public class ClientProducerCreditsImpl implements ClientProducerCredits semaphore = new Semaphore(0, false); } - public void init(SessionContext sessionContext) - { + public void init(SessionContext sessionContext) { // We initial request twice as many credits as we request in subsequent requests // This allows the producer to keep sending as more arrive, minimising pauses checkCredits(windowSize); @@ -75,50 +73,38 @@ public class ClientProducerCreditsImpl implements ClientProducerCredits this.sessionContext.linkFlowControl(address, this); } - public void acquireCredits(final int credits) throws InterruptedException, ActiveMQException - { + public void acquireCredits(final int credits) throws InterruptedException, ActiveMQException { checkCredits(credits); - boolean tryAcquire; - synchronized (this) - { + synchronized (this) { tryAcquire = semaphore.tryAcquire(credits); } - if (!tryAcquire) - { - if (!closed) - { + if (!tryAcquire) { + if (!closed) { this.blocked = true; - try - { - while (!semaphore.tryAcquire(credits, 10, TimeUnit.SECONDS)) - { + try { + while (!semaphore.tryAcquire(credits, 10, TimeUnit.SECONDS)) { // I'm using string concatenation here in case address is null // better getting a "null" string than a NPE ActiveMQClientLogger.LOGGER.outOfCreditOnFlowControl("" + address); } } - finally - { + finally { this.blocked = false; } } } - - synchronized (this) - { + synchronized (this) { pendingCredits -= credits; } // check to see if the blocking mode is FAIL on the server - synchronized (this) - { - if (serverRespondedWithFail) - { + synchronized (this) { + if (serverRespondedWithFail) { serverRespondedWithFail = false; // remove existing credits to force the client to ask the server for more on the next send @@ -131,35 +117,29 @@ public class ClientProducerCreditsImpl implements ClientProducerCredits } } - public boolean isBlocked() - { + public boolean isBlocked() { return blocked; } - public int getBalance() - { + public int getBalance() { return semaphore.availablePermits(); } - public void receiveCredits(final int credits) - { - synchronized (this) - { + public void receiveCredits(final int credits) { + synchronized (this) { arriving -= credits; } semaphore.release(credits); } - public void receiveFailCredits(final int credits) - { + public void receiveFailCredits(final int credits) { serverRespondedWithFail = true; // receive credits like normal to keep the sender from blocking receiveCredits(credits); } - public synchronized void reset() - { + public synchronized void reset() { // Any pendingCredits credits from before failover won't arrive, so we re-initialise semaphore.drainPermits(); @@ -174,39 +154,32 @@ public class ClientProducerCreditsImpl implements ClientProducerCredits checkCredits(Math.max(windowSize * 2, beforeFailure)); } - public void close() - { + public void close() { // Closing a producer that is blocking should make it return closed = true; semaphore.release(Integer.MAX_VALUE / 2); } - public synchronized void incrementRefCount() - { + public synchronized void incrementRefCount() { refCount++; } - public synchronized int decrementRefCount() - { + public synchronized int decrementRefCount() { return --refCount; } - public synchronized void releaseOutstanding() - { + public synchronized void releaseOutstanding() { semaphore.drainPermits(); } - private void checkCredits(final int credits) - { + private void checkCredits(final int credits) { int needed = Math.max(credits, windowSize); int toRequest = -1; - synchronized (this) - { - if (semaphore.availablePermits() + arriving < needed) - { + synchronized (this) { + if (semaphore.availablePermits() + arriving < needed) { toRequest = needed - arriving; pendingCredits += toRequest; @@ -214,14 +187,12 @@ public class ClientProducerCreditsImpl implements ClientProducerCredits } } - if (toRequest != -1) - { + if (toRequest != -1) { requestCredits(toRequest); } } - private void requestCredits(final int credits) - { + private void requestCredits(final int credits) { session.sendProducerCreditsMessage(credits, address); } } \ No newline at end of file diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientProducerImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientProducerImpl.java index ae2981a579..6247bfa655 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientProducerImpl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientProducerImpl.java @@ -40,8 +40,8 @@ import org.apache.activemq.artemis.utils.UUIDGenerator; /** * The client-side Producer. */ -public class ClientProducerImpl implements ClientProducerInternal -{ +public class ClientProducerImpl implements ClientProducerInternal { + private final SimpleString address; private final ClientSessionInternal session; @@ -76,8 +76,7 @@ public class ClientProducerImpl implements ClientProducerInternal final boolean autoGroup, final SimpleString groupID, final int minLargeMessageSize, - final SessionContext sessionContext) - { + final SessionContext sessionContext) { this.sessionContext = sessionContext; this.session = session; @@ -90,129 +89,107 @@ public class ClientProducerImpl implements ClientProducerInternal this.blockOnDurableSend = blockOnDurableSend; - if (autoGroup) - { + if (autoGroup) { this.groupID = UUIDGenerator.getInstance().generateSimpleStringUUID(); } - else - { + else { this.groupID = groupID; } this.minLargeMessageSize = minLargeMessageSize; - if (address != null) - { + if (address != null) { producerCredits = session.getCredits(address, false); } - else - { + else { producerCredits = null; } } // ClientProducer implementation ---------------------------------------------------------------- - public SimpleString getAddress() - { + public SimpleString getAddress() { return address; } - public void send(final Message msg) throws ActiveMQException - { + public void send(final Message msg) throws ActiveMQException { checkClosed(); doSend(null, msg, null, false); } - public void send(final SimpleString address1, final Message msg) throws ActiveMQException - { + public void send(final SimpleString address1, final Message msg) throws ActiveMQException { checkClosed(); doSend(address1, msg, null, false); } - public void send(final String address1, final Message message) throws ActiveMQException - { + public void send(final String address1, final Message message) throws ActiveMQException { send(SimpleString.toSimpleString(address1), message); } @Override - public void send(SimpleString address1, Message message, SendAcknowledgementHandler handler) throws ActiveMQException - { + public void send(SimpleString address1, + Message message, + SendAcknowledgementHandler handler) throws ActiveMQException { checkClosed(); boolean confirmationWindowEnabled = session.isConfirmationWindowEnabled(); - if (confirmationWindowEnabled) - { + if (confirmationWindowEnabled) { doSend(address1, message, handler, true); } - else - { + else { doSend(address1, message, null, true); - if (handler != null) - { + if (handler != null) { session.scheduleConfirmation(handler, message); } } } @Override - public void send(Message message, SendAcknowledgementHandler handler) throws ActiveMQException - { + public void send(Message message, SendAcknowledgementHandler handler) throws ActiveMQException { send(null, message, handler); } - public synchronized void close() throws ActiveMQException - { - if (closed) - { + public synchronized void close() throws ActiveMQException { + if (closed) { return; } doCleanup(); } - public void cleanUp() - { - if (closed) - { + public void cleanUp() { + if (closed) { return; } doCleanup(); } - public boolean isClosed() - { + public boolean isClosed() { return closed; } - public boolean isBlockOnDurableSend() - { + public boolean isBlockOnDurableSend() { return blockOnDurableSend; } - public boolean isBlockOnNonDurableSend() - { + public boolean isBlockOnNonDurableSend() { return blockOnNonDurableSend; } - public int getMaxRate() - { + public int getMaxRate() { return rateLimiter == null ? -1 : rateLimiter.getRate(); } // Public --------------------------------------------------------------------------------------- - public ClientProducerCredits getProducerCredits() - { + public ClientProducerCredits getProducerCredits() { return producerCredits; } - private void doCleanup() - { - if (address != null) - { + private void doCleanup() { + if (address != null) { session.returnCredits(address); } @@ -221,13 +198,13 @@ public class ClientProducerImpl implements ClientProducerInternal closed = true; } - private void doSend(final SimpleString address1, final Message msg, final SendAcknowledgementHandler handler, - final boolean forceAsync) throws ActiveMQException - { + private void doSend(final SimpleString address1, + final Message msg, + final SendAcknowledgementHandler handler, + final boolean forceAsync) throws ActiveMQException { session.startCall(); - try - { + try { MessageInternal msgI = (MessageInternal) msg; ClientProducerCredits theCredits; @@ -237,52 +214,42 @@ public class ClientProducerImpl implements ClientProducerInternal // If it's a server's message, it means this is being done through the bridge or some special consumer on the // server's on which case we can't' convert the message into large at the servers if (sessionContext.supportsLargeMessage() && (msgI.getBodyInputStream() != null || msgI.isLargeMessage() || - msgI.getBodyBuffer().writerIndex() > minLargeMessageSize && !msgI.isServerMessage())) - { + msgI.getBodyBuffer().writerIndex() > minLargeMessageSize && !msgI.isServerMessage())) { isLarge = true; } - else - { + else { isLarge = false; } - if (address1 != null) - { - if (!isLarge) - { + if (address1 != null) { + if (!isLarge) { session.setAddress(msg, address1); } - else - { + else { msg.setAddress(address1); } // Anonymous theCredits = session.getCredits(address1, true); } - else - { - if (!isLarge) - { + else { + if (!isLarge) { session.setAddress(msg, this.address); } - else - { + else { msg.setAddress(this.address); } theCredits = producerCredits; } - if (rateLimiter != null) - { + if (rateLimiter != null) { // Rate flow control rateLimiter.limit(); } - if (groupID != null) - { + if (groupID != null) { msgI.putStringProperty(Message.HDR_GROUP_ID, groupID); } @@ -292,25 +259,23 @@ public class ClientProducerImpl implements ClientProducerInternal session.workDone(); - if (isLarge) - { + if (isLarge) { largeMessageSend(sendBlocking, msgI, theCredits, handler); } - else - { + else { sendRegularMessage(msgI, sendBlocking, theCredits, handler); } } - finally - { + finally { session.endCall(); } } - private void sendRegularMessage(final MessageInternal msgI, final boolean sendBlocking, final ClientProducerCredits theCredits, final SendAcknowledgementHandler handler) throws ActiveMQException - { - try - { + private void sendRegularMessage(final MessageInternal msgI, + final boolean sendBlocking, + final ClientProducerCredits theCredits, + final SendAcknowledgementHandler handler) throws ActiveMQException { + try { // This will block if credits are not available // Note, that for a large message, the encode size only includes the properties + headers @@ -321,18 +286,15 @@ public class ClientProducerImpl implements ClientProducerInternal theCredits.acquireCredits(creditSize); } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } sessionContext.sendFullMessage(msgI, sendBlocking, handler, address); } - private void checkClosed() throws ActiveMQException - { - if (closed) - { + private void checkClosed() throws ActiveMQException { + if (closed) { throw ActiveMQClientMessageBundle.BUNDLE.producerClosed(); } } @@ -344,51 +306,45 @@ public class ClientProducerImpl implements ClientProducerInternal * @param handler * @throws ActiveMQException */ - private void largeMessageSend(final boolean sendBlocking, final MessageInternal msgI, - final ClientProducerCredits credits, SendAcknowledgementHandler handler) throws ActiveMQException - { + private void largeMessageSend(final boolean sendBlocking, + final MessageInternal msgI, + final ClientProducerCredits credits, + SendAcknowledgementHandler handler) throws ActiveMQException { int headerSize = msgI.getHeadersAndPropertiesEncodeSize(); - if (msgI.getHeadersAndPropertiesEncodeSize() >= minLargeMessageSize) - { + if (msgI.getHeadersAndPropertiesEncodeSize() >= minLargeMessageSize) { throw ActiveMQClientMessageBundle.BUNDLE.headerSizeTooBig(headerSize); } // msg.getBody() could be Null on LargeServerMessage - if (msgI.getBodyInputStream() == null && msgI.getWholeBuffer() != null) - { + if (msgI.getBodyInputStream() == null && msgI.getWholeBuffer() != null) { msgI.getWholeBuffer().readerIndex(0); } InputStream input; - if (msgI.isServerMessage()) - { + if (msgI.isServerMessage()) { largeMessageSendServer(sendBlocking, msgI, credits, handler); } - else if ((input = msgI.getBodyInputStream()) != null) - { + else if ((input = msgI.getBodyInputStream()) != null) { largeMessageSendStreamed(sendBlocking, msgI, input, credits, handler); } - else - { + else { largeMessageSendBuffered(sendBlocking, msgI, credits, handler); } } - private void sendInitialLargeMessageHeader(MessageInternal msgI, ClientProducerCredits credits) throws ActiveMQException - { + private void sendInitialLargeMessageHeader(MessageInternal msgI, + ClientProducerCredits credits) throws ActiveMQException { int creditsUsed = sessionContext.sendInitialChunkOnLargeMessage(msgI); // On the case of large messages we tried to send credits before but we would starve otherwise // we may find a way to improve the logic and always acquire the credits before // but that's the way it's been tested and been working ATM - try - { + try { credits.acquireCredits(creditsUsed); } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } } @@ -402,9 +358,10 @@ public class ClientProducerImpl implements ClientProducerInternal * @param handler * @throws ActiveMQException */ - private void largeMessageSendServer(final boolean sendBlocking, final MessageInternal msgI, - final ClientProducerCredits credits, SendAcknowledgementHandler handler) throws ActiveMQException - { + private void largeMessageSendServer(final boolean sendBlocking, + final MessageInternal msgI, + final ClientProducerCredits credits, + SendAcknowledgementHandler handler) throws ActiveMQException { sendInitialLargeMessageHeader(msgI, credits); BodyEncoder context = msgI.getBodyEncoder(); @@ -412,11 +369,9 @@ public class ClientProducerImpl implements ClientProducerInternal final long bodySize = context.getLargeBodySize(); context.open(); - try - { + try { - for (int pos = 0; pos < bodySize; ) - { + for (int pos = 0; pos < bodySize; ) { final boolean lastChunk; final int chunkLength = Math.min((int) (bodySize - pos), minLargeMessageSize); @@ -432,18 +387,15 @@ public class ClientProducerImpl implements ClientProducerInternal int creditsUsed = sessionContext.sendLargeMessageChunk(msgI, -1, sendBlocking, lastChunk, bodyBuffer.toByteBuffer().array(), messageHandler); - try - { + try { credits.acquireCredits(creditsUsed); } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } } } - finally - { + finally { context.close(); } } @@ -454,13 +406,12 @@ public class ClientProducerImpl implements ClientProducerInternal * @param handler * @throws ActiveMQException */ - private void - largeMessageSendBuffered(final boolean sendBlocking, final MessageInternal msgI, - final ClientProducerCredits credits, SendAcknowledgementHandler handler) throws ActiveMQException - { + private void largeMessageSendBuffered(final boolean sendBlocking, + final MessageInternal msgI, + final ClientProducerCredits credits, + SendAcknowledgementHandler handler) throws ActiveMQException { msgI.getBodyBuffer().readerIndex(0); - largeMessageSendStreamed(sendBlocking, msgI, new ActiveMQBufferInputStream(msgI.getBodyBuffer()), credits, - handler); + largeMessageSendStreamed(sendBlocking, msgI, new ActiveMQBufferInputStream(msgI.getBodyBuffer()), credits, handler); } /** @@ -470,10 +421,11 @@ public class ClientProducerImpl implements ClientProducerInternal * @param credits * @throws ActiveMQException */ - private void largeMessageSendStreamed(final boolean sendBlocking, final MessageInternal msgI, - final InputStream inputStreamParameter, final ClientProducerCredits credits, - SendAcknowledgementHandler handler) throws ActiveMQException - { + private void largeMessageSendStreamed(final boolean sendBlocking, + final MessageInternal msgI, + final InputStream inputStreamParameter, + final ClientProducerCredits credits, + SendAcknowledgementHandler handler) throws ActiveMQException { boolean lastPacket = false; InputStream input = inputStreamParameter; @@ -484,8 +436,7 @@ public class ClientProducerImpl implements ClientProducerInternal DeflaterReader deflaterReader = null; - if (session.isCompressLargeMessages()) - { + if (session.isCompressLargeMessages()) { msgI.putBooleanProperty(Message.HDR_LARGE_COMPRESSED, true); deflaterReader = new DeflaterReader(inputStreamParameter, messageSize); input = deflaterReader; @@ -495,46 +446,38 @@ public class ClientProducerImpl implements ClientProducerInternal boolean headerSent = false; - while (!lastPacket) - { + while (!lastPacket) { byte[] buff = new byte[minLargeMessageSize]; int pos = 0; - do - { + do { int numberOfBytesRead; int wanted = minLargeMessageSize - pos; - try - { + try { numberOfBytesRead = input.read(buff, pos, wanted); } - catch (IOException e) - { + catch (IOException e) { throw ActiveMQClientMessageBundle.BUNDLE.errorReadingBody(e); } - if (numberOfBytesRead == -1) - { + if (numberOfBytesRead == -1) { lastPacket = true; break; } pos += numberOfBytesRead; - } - while (pos < minLargeMessageSize); + } while (pos < minLargeMessageSize); totalSize += pos; final SessionSendContinuationMessage chunk; - if (lastPacket) - { - if (!session.isCompressLargeMessages()) - { + if (lastPacket) { + if (!session.isCompressLargeMessages()) { messageSize.set(totalSize); } @@ -546,8 +489,7 @@ public class ClientProducerImpl implements ClientProducerInternal buff = buff2; // This is the case where the message is being converted as a regular message - if (!headerSent && session.isCompressLargeMessages() && buff2.length < minLargeMessageSize) - { + if (!headerSent && session.isCompressLargeMessages() && buff2.length < minLargeMessageSize) { msgI.getBodyBuffer().resetReaderIndex(); msgI.getBodyBuffer().resetWriterIndex(); msgI.putLongProperty(Message.HDR_LARGE_BODY_SIZE, deflaterReader.getTotalSize()); @@ -556,51 +498,40 @@ public class ClientProducerImpl implements ClientProducerInternal sendRegularMessage(msgI, sendBlocking, credits, handler); return; } - else - { - if (!headerSent) - { + else { + if (!headerSent) { headerSent = true; sendInitialLargeMessageHeader(msgI, credits); } int creditsSent = sessionContext.sendLargeMessageChunk(msgI, messageSize.get(), sendBlocking, true, buff, handler); - try - { + try { credits.acquireCredits(creditsSent); } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } } } - else - { - if (!headerSent) - { + else { + if (!headerSent) { headerSent = true; sendInitialLargeMessageHeader(msgI, credits); } - int creditsSent = sessionContext.sendLargeMessageChunk(msgI, messageSize.get(), sendBlocking, false, buff, handler); - try - { + try { credits.acquireCredits(creditsSent); } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } } } - try - { + try { input.close(); } - catch (IOException e) - { + catch (IOException e) { throw ActiveMQClientMessageBundle.BUNDLE.errorClosingLargeMessage(e); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientProducerInternal.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientProducerInternal.java index 173821dfdf..6190885e3d 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientProducerInternal.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientProducerInternal.java @@ -19,11 +19,10 @@ package org.apache.activemq.artemis.core.client.impl; import org.apache.activemq.artemis.api.core.client.ClientProducer; /** - * * A ClientProducerInternal */ -public interface ClientProducerInternal extends ClientProducer -{ +public interface ClientProducerInternal extends ClientProducer { + void cleanUp(); ClientProducerCredits getProducerCredits(); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientSessionFactoryImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientSessionFactoryImpl.java index 85e3d8d11d..aa27581e87 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientSessionFactoryImpl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientSessionFactoryImpl.java @@ -65,8 +65,7 @@ import org.apache.activemq.artemis.utils.ExecutorFactory; import org.apache.activemq.artemis.utils.OrderedExecutorFactory; import org.apache.activemq.artemis.utils.UUIDGenerator; -public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, ConnectionLifeCycleListener -{ +public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, ConnectionLifeCycleListener { // Constants // ------------------------------------------------------------------------------------ @@ -103,7 +102,6 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C private final Lock newFailoverLock = new ReentrantLock(); - private final Object connectionLock = new Object(); private final ExecutorFactory orderedExecutorFactory; @@ -133,7 +131,6 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C private Future pingerFuture; private PingRunnable pingRunnable; - private final List incomingInterceptors; private final List outgoingInterceptors; @@ -163,8 +160,7 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C final Executor threadPool, final ScheduledExecutorService scheduledThreadPool, final List incomingInterceptors, - final List outgoingInterceptors) - { + final List outgoingInterceptors) { createTrace = new Exception(); this.serverLocator = serverLocator; @@ -186,13 +182,11 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C // HORNETQ-1314 - if this in an in-vm connection then disable connection monitoring if (connectorFactory.isReliable() && clientFailureCheckPeriod == ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD && - connectionTTL == ActiveMQClient.DEFAULT_CONNECTION_TTL) - { + connectionTTL == ActiveMQClient.DEFAULT_CONNECTION_TTL) { this.clientFailureCheckPeriod = ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD_INVM; this.connectionTTL = ActiveMQClient.DEFAULT_CONNECTION_TTL_INVM; } - else - { + else { this.clientFailureCheckPeriod = clientFailureCheckPeriod; this.connectionTTL = connectionTTL; @@ -222,28 +216,23 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C } - public void disableFinalizeCheck() - { + public void disableFinalizeCheck() { finalizeCheck = false; } - public Lock lockFailover() - { + public Lock lockFailover() { newFailoverLock.lock(); return newFailoverLock; } - public void connect(final int initialConnectAttempts, final boolean failoverOnInitialConnection) throws ActiveMQException - { + public void connect(final int initialConnectAttempts, + final boolean failoverOnInitialConnection) throws ActiveMQException { // Get the connection getConnectionWithRetry(initialConnectAttempts); - if (connection == null) - { - StringBuilder msg = - new StringBuilder("Unable to connect to server using configuration ").append(connectorConfig); - if (backupConfig != null) - { + if (connection == null) { + StringBuilder msg = new StringBuilder("Unable to connect to server using configuration ").append(connectorConfig); + if (backupConfig != null) { msg.append(" and backup configuration ").append(backupConfig); } throw new ActiveMQNotConnectedException(msg.toString()); @@ -251,52 +240,38 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C } - public TransportConfiguration getConnectorConfiguration() - { + public TransportConfiguration getConnectorConfiguration() { return connectorConfig; } - public void setBackupConnector(final TransportConfiguration live, final TransportConfiguration backUp) - { + public void setBackupConnector(final TransportConfiguration live, final TransportConfiguration backUp) { Connector localConnector = connector; // if the connector has never been used (i.e. the getConnection hasn't been called yet), we will need // to create a connector just to validate if the parameters are ok. // so this will create the instance to be used on the isEquivalent check - if (localConnector == null) - { - localConnector = connectorFactory.createConnector(connectorConfig.getParams(), - new DelegatingBufferHandler(), - this, - closeExecutor, - threadPool, - scheduledThreadPool, - clientProtocolManager); + if (localConnector == null) { + localConnector = connectorFactory.createConnector(connectorConfig.getParams(), new DelegatingBufferHandler(), this, closeExecutor, threadPool, scheduledThreadPool, clientProtocolManager); } - if (localConnector.isEquivalent(live.getParams()) && backUp != null && !localConnector.isEquivalent(backUp.getParams())) - { - if (ClientSessionFactoryImpl.isDebug) - { + if (localConnector.isEquivalent(live.getParams()) && backUp != null && !localConnector.isEquivalent(backUp.getParams())) { + if (ClientSessionFactoryImpl.isDebug) { ActiveMQClientLogger.LOGGER.debug("Setting up backup config = " + backUp + " for live = " + live); } backupConfig = backUp; } - else - { - if (ClientSessionFactoryImpl.isDebug) - { + else { + if (ClientSessionFactoryImpl.isDebug) { ActiveMQClientLogger.LOGGER.debug("ClientSessionFactoryImpl received backup update for live/backup pair = " + live + - " / " + - backUp + - " but it didn't belong to " + - connectorConfig); + " / " + + backUp + + " but it didn't belong to " + + connectorConfig); } } } - public Object getBackupConnector() - { + public Object getBackupConnector() { return backupConfig; } @@ -306,184 +281,116 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C final boolean autoCommitSends, final boolean autoCommitAcks, final boolean preAcknowledge, - final int ackBatchSize) throws ActiveMQException - { - return createSessionInternal(username, - password, - xa, - autoCommitSends, - autoCommitAcks, - preAcknowledge, - ackBatchSize); + final int ackBatchSize) throws ActiveMQException { + return createSessionInternal(username, password, xa, autoCommitSends, autoCommitAcks, preAcknowledge, ackBatchSize); } public ClientSession createSession(final boolean autoCommitSends, final boolean autoCommitAcks, - final int ackBatchSize) throws ActiveMQException - { - return createSessionInternal(null, - null, - false, - autoCommitSends, - autoCommitAcks, - serverLocator.isPreAcknowledge(), - ackBatchSize); + final int ackBatchSize) throws ActiveMQException { + return createSessionInternal(null, null, false, autoCommitSends, autoCommitAcks, serverLocator.isPreAcknowledge(), ackBatchSize); } - public ClientSession createXASession() throws ActiveMQException - { - return createSessionInternal(null, - null, - true, - false, - false, - serverLocator.isPreAcknowledge(), - serverLocator.getAckBatchSize()); + public ClientSession createXASession() throws ActiveMQException { + return createSessionInternal(null, null, true, false, false, serverLocator.isPreAcknowledge(), serverLocator.getAckBatchSize()); } - public ClientSession createTransactedSession() throws ActiveMQException - { - return createSessionInternal(null, - null, - false, - false, - false, - serverLocator.isPreAcknowledge(), - serverLocator.getAckBatchSize()); + public ClientSession createTransactedSession() throws ActiveMQException { + return createSessionInternal(null, null, false, false, false, serverLocator.isPreAcknowledge(), serverLocator.getAckBatchSize()); } - public ClientSession createSession() throws ActiveMQException - { - return createSessionInternal(null, - null, - false, - true, - true, - serverLocator.isPreAcknowledge(), - serverLocator.getAckBatchSize()); + public ClientSession createSession() throws ActiveMQException { + return createSessionInternal(null, null, false, true, true, serverLocator.isPreAcknowledge(), serverLocator.getAckBatchSize()); } - public ClientSession createSession(final boolean autoCommitSends, final boolean autoCommitAcks) throws ActiveMQException - { - return createSessionInternal(null, - null, - false, - autoCommitSends, - autoCommitAcks, - serverLocator.isPreAcknowledge(), - serverLocator.getAckBatchSize()); + public ClientSession createSession(final boolean autoCommitSends, + final boolean autoCommitAcks) throws ActiveMQException { + return createSessionInternal(null, null, false, autoCommitSends, autoCommitAcks, serverLocator.isPreAcknowledge(), serverLocator.getAckBatchSize()); } - public ClientSession createSession(final boolean xa, final boolean autoCommitSends, final boolean autoCommitAcks) throws ActiveMQException - { - return createSessionInternal(null, - null, - xa, - autoCommitSends, - autoCommitAcks, - serverLocator.isPreAcknowledge(), - serverLocator.getAckBatchSize()); + public ClientSession createSession(final boolean xa, + final boolean autoCommitSends, + final boolean autoCommitAcks) throws ActiveMQException { + return createSessionInternal(null, null, xa, autoCommitSends, autoCommitAcks, serverLocator.isPreAcknowledge(), serverLocator.getAckBatchSize()); } public ClientSession createSession(final boolean xa, final boolean autoCommitSends, final boolean autoCommitAcks, - final boolean preAcknowledge) throws ActiveMQException - { - return createSessionInternal(null, - null, - xa, - autoCommitSends, - autoCommitAcks, - preAcknowledge, - serverLocator.getAckBatchSize()); + final boolean preAcknowledge) throws ActiveMQException { + return createSessionInternal(null, null, xa, autoCommitSends, autoCommitAcks, preAcknowledge, serverLocator.getAckBatchSize()); } // ConnectionLifeCycleListener implementation -------------------------------------------------- - public void connectionCreated(final ActiveMQComponent component, final Connection connection, final String protocol) - { + public void connectionCreated(final ActiveMQComponent component, + final Connection connection, + final String protocol) { } - public void connectionDestroyed(final Object connectionID) - { + public void connectionDestroyed(final Object connectionID) { // The exception has to be created in the same thread where it's being called // as to avoid a different stack trace cause final ActiveMQException ex = ActiveMQClientMessageBundle.BUNDLE.channelDisconnected(); // It has to use the same executor as the disconnect message is being sent through - closeExecutor.execute(new Runnable() - { - public void run() - { + closeExecutor.execute(new Runnable() { + public void run() { handleConnectionFailure(connectionID, ex); } }); } - public void connectionException(final Object connectionID, final ActiveMQException me) - { + public void connectionException(final Object connectionID, final ActiveMQException me) { handleConnectionFailure(connectionID, me); } // Must be synchronized to prevent it happening concurrently with failover which can lead to // inconsistencies - public void removeSession(final ClientSessionInternal session, final boolean failingOver) - { - synchronized (sessions) - { + public void removeSession(final ClientSessionInternal session, final boolean failingOver) { + synchronized (sessions) { sessions.remove(session); } } - public void connectionReadyForWrites(final Object connectionID, final boolean ready) - { + public void connectionReadyForWrites(final Object connectionID, final boolean ready) { } - public synchronized int numConnections() - { + public synchronized int numConnections() { return connection != null ? 1 : 0; } - public int numSessions() - { + public int numSessions() { return sessions.size(); } - public void addFailureListener(final SessionFailureListener listener) - { + public void addFailureListener(final SessionFailureListener listener) { listeners.add(listener); } - public boolean removeFailureListener(final SessionFailureListener listener) - { + public boolean removeFailureListener(final SessionFailureListener listener) { return listeners.remove(listener); } - public ClientSessionFactoryImpl addFailoverListener(FailoverEventListener listener) - { + public ClientSessionFactoryImpl addFailoverListener(FailoverEventListener listener) { failoverListeners.add(listener); return this; } - public boolean removeFailoverListener(FailoverEventListener listener) - { + public boolean removeFailoverListener(FailoverEventListener listener) { return failoverListeners.remove(listener); } - public void causeExit() - { + public void causeExit() { clientProtocolManager.stop(); } - private void interruptConnectAndCloseAllSessions(boolean close) - { + private void interruptConnectAndCloseAllSessions(boolean close) { clientProtocolManager.stop(); - synchronized (createSessionLock) - { + synchronized (createSessionLock) { closeCleanSessions(close); closed = true; } @@ -492,36 +399,29 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C /** * @param close */ - private void closeCleanSessions(boolean close) - { + private void closeCleanSessions(boolean close) { HashSet sessionsToClose; - synchronized (sessions) - { + synchronized (sessions) { sessionsToClose = new HashSet(sessions); } // work on a copied set. the session will be removed from sessions when session.close() is // called - for (ClientSessionInternal session : sessionsToClose) - { - try - { + for (ClientSessionInternal session : sessionsToClose) { + try { if (close) session.close(); else session.cleanUp(false); } - catch (Exception e1) - { + catch (Exception e1) { ActiveMQClientLogger.LOGGER.unableToCloseSession(e1); } } checkCloseConnection(); } - public void close() - { - if (closed) - { + public void close() { + if (closed) { return; } interruptConnectAndCloseAllSessions(true); @@ -529,45 +429,38 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C serverLocator.factoryClosed(this); } - public void cleanup() - { - if (closed) - { + public void cleanup() { + if (closed) { return; } interruptConnectAndCloseAllSessions(false); } - public boolean isClosed() - { + public boolean isClosed() { return closed || serverLocator.isClosed(); } @Override - public ServerLocator getServerLocator() - { + public ServerLocator getServerLocator() { return serverLocator; } - public void stopPingingAfterOne() - { + public void stopPingingAfterOne() { stopPingingAfterOne = true; } - private void handleConnectionFailure(final Object connectionID, final ActiveMQException me) - { + private void handleConnectionFailure(final Object connectionID, final ActiveMQException me) { handleConnectionFailure(connectionID, me, null); } - private void handleConnectionFailure(final Object connectionID, final ActiveMQException me, String scaleDownTargetNodeID) - { - try - { + private void handleConnectionFailure(final Object connectionID, + final ActiveMQException me, + String scaleDownTargetNodeID) { + try { failoverOrReconnect(connectionID, me, scaleDownTargetNodeID); } - catch (ActiveMQInterruptedException e1) - { + catch (ActiveMQInterruptedException e1) { // this is just a debug, since an interrupt is an expected event (in case of a shutdown) ActiveMQClientLogger.LOGGER.debug(e1.getMessage(), e1); } @@ -575,21 +468,21 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C /** * TODO: Maybe this belongs to ActiveMQClientProtocolManager + * * @param connectionID * @param me */ - private void failoverOrReconnect(final Object connectionID, final ActiveMQException me, String scaleDownTargetNodeID) - { + private void failoverOrReconnect(final Object connectionID, + final ActiveMQException me, + String scaleDownTargetNodeID) { ActiveMQClientLogger.LOGGER.failoverOrReconnect(connectionID, me); Set sessionsToClose = null; if (!clientProtocolManager.isAlive()) return; Lock localFailoverLock = lockFailover(); - try - { - if (connection == null || !connection.getID().equals(connectionID) || !clientProtocolManager.isAlive()) - { + try { + if (connection == null || !connection.getID().equals(connectionID) || !clientProtocolManager.isAlive()) { // We already failed over/reconnected - probably the first failure came in, all the connections were failed // over then an async connection exception or disconnect // came in for one of the already exitLoop connections, so we return true - we don't want to call the @@ -598,8 +491,7 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C return; } - if (ClientSessionFactoryImpl.isTrace) - { + if (ClientSessionFactoryImpl.isTrace) { ActiveMQClientLogger.LOGGER.trace("Client Connection failed, calling failure listeners and trying to reconnect, reconnectAttempts=" + reconnectAttempts); } @@ -634,13 +526,9 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C // failoverLock // until failover is complete - if (reconnectAttempts != 0) - { - - - if (clientProtocolManager.cleanupBeforeFailover(me)) - { + if (reconnectAttempts != 0) { + if (clientProtocolManager.cleanupBeforeFailover(me)) { // Now we absolutely know that no threads are executing in or blocked in // createSession, @@ -654,14 +542,11 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C connection = null; Connector localConnector = connector; - if (localConnector != null) - { - try - { + if (localConnector != null) { + try { localConnector.close(); } - catch (Exception ignore) - { + catch (Exception ignore) { // no-op } } @@ -672,60 +557,48 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C reconnectSessions(oldConnection, reconnectAttempts, me); - if (oldConnection != null) - { + if (oldConnection != null) { oldConnection.destroy(); } - if (connection != null) - { + if (connection != null) { callFailoverListeners(FailoverEventType.FAILOVER_COMPLETED); } } } - else - { + else { RemotingConnection connectionToDestory = connection; - if (connectionToDestory != null) - { + if (connectionToDestory != null) { connectionToDestory.destroy(); } connection = null; } - if (connection == null) - { - synchronized (sessions) - { + if (connection == null) { + synchronized (sessions) { sessionsToClose = new HashSet(sessions); } callFailoverListeners(FailoverEventType.FAILOVER_FAILED); callSessionFailureListeners(me, true, false); } } - finally - { + finally { localFailoverLock.unlock(); } // This needs to be outside the failover lock to prevent deadlock - if (connection != null) - { + if (connection != null) { callSessionFailureListeners(me, true, true); } - if (sessionsToClose != null) - { + if (sessionsToClose != null) { // If connection is null it means we didn't succeed in failing over or reconnecting // so we close all the sessions, so they will throw exceptions when attempted to be used - for (ClientSessionInternal session : sessionsToClose) - { - try - { + for (ClientSessionInternal session : sessionsToClose) { + try { session.cleanUp(true); } - catch (Exception cause) - { + catch (Exception cause) { ActiveMQClientLogger.LOGGER.failedToCleanupSession(cause); } } @@ -738,50 +611,15 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C final boolean autoCommitSends, final boolean autoCommitAcks, final boolean preAcknowledge, - final int ackBatchSize) throws ActiveMQException - { + final int ackBatchSize) throws ActiveMQException { String name = UUIDGenerator.getInstance().generateStringUUID(); + SessionContext context = createSessionChannel(name, username, password, xa, autoCommitSends, autoCommitAcks, preAcknowledge); - SessionContext context = createSessionChannel(name, - username, - password, - xa, - autoCommitSends, - autoCommitAcks, - preAcknowledge); + ClientSessionInternal session = new ClientSessionImpl(this, name, username, password, xa, autoCommitSends, autoCommitAcks, preAcknowledge, serverLocator.isBlockOnAcknowledge(), serverLocator.isAutoGroup(), ackBatchSize, serverLocator.getConsumerWindowSize(), serverLocator.getConsumerMaxRate(), serverLocator.getConfirmationWindowSize(), serverLocator.getProducerWindowSize(), serverLocator.getProducerMaxRate(), serverLocator.isBlockOnNonDurableSend(), serverLocator.isBlockOnDurableSend(), serverLocator.isCacheLargeMessagesClient(), serverLocator.getMinLargeMessageSize(), serverLocator.isCompressLargeMessage(), serverLocator.getInitialMessagePacketSize(), serverLocator.getGroupID(), context, orderedExecutorFactory.getExecutor(), orderedExecutorFactory.getExecutor()); - ClientSessionInternal session = new ClientSessionImpl(this, - name, - username, - password, - xa, - autoCommitSends, - autoCommitAcks, - preAcknowledge, - serverLocator.isBlockOnAcknowledge(), - serverLocator.isAutoGroup(), - ackBatchSize, - serverLocator.getConsumerWindowSize(), - serverLocator.getConsumerMaxRate(), - serverLocator.getConfirmationWindowSize(), - serverLocator.getProducerWindowSize(), - serverLocator.getProducerMaxRate(), - serverLocator.isBlockOnNonDurableSend(), - serverLocator.isBlockOnDurableSend(), - serverLocator.isCacheLargeMessagesClient(), - serverLocator.getMinLargeMessageSize(), - serverLocator.isCompressLargeMessage(), - serverLocator.getInitialMessagePacketSize(), - serverLocator.getGroupID(), - context, - orderedExecutorFactory.getExecutor(), - orderedExecutorFactory.getExecutor()); - - synchronized (sessions) - { - if (closed || !clientProtocolManager.isAlive()) - { + synchronized (sessions) { + if (closed || !clientProtocolManager.isAlive()) { session.close(); return null; } @@ -792,33 +630,28 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C } - - private void callSessionFailureListeners(final ActiveMQException me, final boolean afterReconnect, - final boolean failedOver) - { + private void callSessionFailureListeners(final ActiveMQException me, + final boolean afterReconnect, + final boolean failedOver) { callSessionFailureListeners(me, afterReconnect, failedOver, null); } - private void callSessionFailureListeners(final ActiveMQException me, final boolean afterReconnect, - final boolean failedOver, final String scaleDownTargetNodeID) - { + private void callSessionFailureListeners(final ActiveMQException me, + final boolean afterReconnect, + final boolean failedOver, + final String scaleDownTargetNodeID) { final List listenersClone = new ArrayList(listeners); - for (final SessionFailureListener listener : listenersClone) - { - try - { - if (afterReconnect) - { + for (final SessionFailureListener listener : listenersClone) { + try { + if (afterReconnect) { listener.connectionFailed(me, failedOver, scaleDownTargetNodeID); } - else - { + else { listener.beforeReconnect(me); } } - catch (final Throwable t) - { + catch (final Throwable t) { // Failure of one listener to execute shouldn't prevent others // from // executing @@ -827,18 +660,14 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C } } - private void callFailoverListeners(FailoverEventType type) - { + private void callFailoverListeners(FailoverEventType type) { final List listenersClone = new ArrayList<>(failoverListeners); - for (final FailoverEventListener listener : listenersClone) - { - try - { + for (final FailoverEventListener listener : listenersClone) { + try { listener.failoverEvent(type); } - catch (final Throwable t) - { + catch (final Throwable t) { // Failure of one listener to execute shouldn't prevent others // from // executing @@ -850,41 +679,34 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C /* * Re-attach sessions all pre-existing sessions to the new remoting connection */ - private void reconnectSessions(final RemotingConnection oldConnection, final int reconnectAttempts, final ActiveMQException cause) - { + private void reconnectSessions(final RemotingConnection oldConnection, + final int reconnectAttempts, + final ActiveMQException cause) { HashSet sessionsToFailover; - synchronized (sessions) - { + synchronized (sessions) { sessionsToFailover = new HashSet(sessions); } - for (ClientSessionInternal session : sessionsToFailover) - { + for (ClientSessionInternal session : sessionsToFailover) { session.preHandleFailover(connection); } getConnectionWithRetry(reconnectAttempts); - if (connection == null) - { + if (connection == null) { if (!clientProtocolManager.isAlive()) ActiveMQClientLogger.LOGGER.failedToConnectToServer(); return; } - - - List oldListeners = oldConnection.getFailureListeners(); List newListeners = new ArrayList<>(connection.getFailureListeners()); - for (FailureListener listener : oldListeners) - { + for (FailureListener listener : oldListeners) { // Add all apart from the old DelegatingFailureListener - if (listener instanceof DelegatingFailureListener == false) - { + if (listener instanceof DelegatingFailureListener == false) { newListeners.add(listener); } } @@ -893,93 +715,76 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C // This used to be done inside failover // it needs to be done on the protocol - ((CoreRemotingConnection)connection).syncIDGeneratorSequence(((CoreRemotingConnection) oldConnection).getIDGeneratorSequence()); + ((CoreRemotingConnection) connection).syncIDGeneratorSequence(((CoreRemotingConnection) oldConnection).getIDGeneratorSequence()); - for (ClientSessionInternal session : sessionsToFailover) - { + for (ClientSessionInternal session : sessionsToFailover) { session.handleFailover(connection, cause); } } - private void getConnectionWithRetry(final int reconnectAttempts) - { + private void getConnectionWithRetry(final int reconnectAttempts) { if (!clientProtocolManager.isAlive()) return; - if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) { ActiveMQClientLogger.LOGGER.trace("getConnectionWithRetry::" + reconnectAttempts + - " with retryInterval = " + - retryInterval + - " multiplier = " + - retryIntervalMultiplier, new Exception("trace")); + " with retryInterval = " + + retryInterval + + " multiplier = " + + retryIntervalMultiplier, new Exception("trace")); } long interval = retryInterval; int count = 0; - while (clientProtocolManager.isAlive()) - { - if (ClientSessionFactoryImpl.isDebug) - { + while (clientProtocolManager.isAlive()) { + if (ClientSessionFactoryImpl.isDebug) { ActiveMQClientLogger.LOGGER.debug("Trying reconnection attempt " + count + "/" + reconnectAttempts); } - if (getConnection() != null) - { - if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) - { + if (getConnection() != null) { + if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) { ActiveMQClientLogger.LOGGER.debug("Reconnection successful"); } return; } - else - { + else { // Failed to get connection - if (reconnectAttempts != 0) - { + if (reconnectAttempts != 0) { count++; - if (reconnectAttempts != -1 && count == reconnectAttempts) - { - if (reconnectAttempts != 1) - { + if (reconnectAttempts != -1 && count == reconnectAttempts) { + if (reconnectAttempts != 1) { ActiveMQClientLogger.LOGGER.failedToConnectToServer(reconnectAttempts); } return; } - if (ClientSessionFactoryImpl.isTrace) - { + if (ClientSessionFactoryImpl.isTrace) { ActiveMQClientLogger.LOGGER.waitingForRetry(interval, retryInterval, retryIntervalMultiplier); } - try - { - if (clientProtocolManager.waitOnLatch(interval)) - { + try { + if (clientProtocolManager.waitOnLatch(interval)) { return; } } - catch (InterruptedException ignore) - { + catch (InterruptedException ignore) { throw new ActiveMQInterruptedException(createTrace); } // Exponential back-off long newInterval = (long) (interval * retryIntervalMultiplier); - if (newInterval > maxRetryInterval) - { + if (newInterval > maxRetryInterval) { newInterval = maxRetryInterval; } interval = newInterval; } - else - { + else { ActiveMQClientLogger.LOGGER.debug("Could not connect to any server. Didn't have reconnection configured on the ClientSessionFactory"); return; } @@ -987,110 +792,86 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C } } - private void cancelScheduledTasks() - { + private void cancelScheduledTasks() { Future pingerFutureLocal = pingerFuture; - if (pingerFutureLocal != null) - { + if (pingerFutureLocal != null) { pingerFutureLocal.cancel(false); } PingRunnable pingRunnableLocal = pingRunnable; - if (pingRunnableLocal != null) - { + if (pingRunnableLocal != null) { pingRunnableLocal.cancel(); } pingerFuture = null; pingRunnable = null; } - private void checkCloseConnection() - { - if (connection != null && sessions.size() == 0) - { + private void checkCloseConnection() { + if (connection != null && sessions.size() == 0) { cancelScheduledTasks(); - try - { + try { connection.destroy(); } - catch (Throwable ignore) - { + catch (Throwable ignore) { } connection = null; - try - { - if (connector != null) - { + try { + if (connector != null) { connector.close(); } } - catch (Throwable ignore) - { + catch (Throwable ignore) { } connector = null; } } - public RemotingConnection getConnection() - { + public RemotingConnection getConnection() { if (closed) throw new IllegalStateException("ClientSessionFactory is closed!"); if (!clientProtocolManager.isAlive()) return null; - synchronized (connectionLock) - { - if (connection != null) - { + synchronized (connectionLock) { + if (connection != null) { // a connection already exists, so returning the same one return connection; } - else - { + else { connection = establishNewConnection(); //we check if we can actually connect. // we do it here as to receive the reply connection has to be not null - if (connection != null && liveNodeID != null) - { - try - { - if (!clientProtocolManager.checkForFailover(liveNodeID)) - { + if (connection != null && liveNodeID != null) { + try { + if (!clientProtocolManager.checkForFailover(liveNodeID)) { connection.destroy(); connection = null; } } - catch (ActiveMQException e) - { - if (connection != null) - { + catch (ActiveMQException e) { + if (connection != null) { connection.destroy(); connection = null; } } } - if (connection != null && serverLocator.getAfterConnectInternalListener() != null) - { + if (connection != null && serverLocator.getAfterConnectInternalListener() != null) { serverLocator.getAfterConnectInternalListener().onConnection(this); } - if (serverLocator.getTopology() != null) - { - if (connection != null) - { - if (ClientSessionFactoryImpl.isTrace) - { + if (serverLocator.getTopology() != null) { + if (connection != null) { + if (ClientSessionFactoryImpl.isTrace) { ActiveMQClientLogger.LOGGER.trace(this + "::Subscribing Topology"); } clientProtocolManager.sendSubscribeTopology(serverLocator.isClusterConnection()); } } - else - { + else { ActiveMQClientLogger.LOGGER.debug("serverLocator@" + System.identityHashCode(serverLocator + " had no topology")); } @@ -1099,19 +880,12 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C } } - - protected void schedulePing() - { - if (pingerFuture == null) - { + protected void schedulePing() { + if (pingerFuture == null) { pingRunnable = new ClientSessionFactoryImpl.PingRunnable(); - if (clientFailureCheckPeriod != -1) - { - pingerFuture = scheduledThreadPool.scheduleWithFixedDelay(new ClientSessionFactoryImpl.ActualScheduledPinger(pingRunnable), - 0, - clientFailureCheckPeriod, - TimeUnit.MILLISECONDS); + if (clientFailureCheckPeriod != -1) { + pingerFuture = scheduledThreadPool.scheduleWithFixedDelay(new ClientSessionFactoryImpl.ActualScheduledPinger(pingRunnable), 0, clientFailureCheckPeriod, TimeUnit.MILLISECONDS); } // To make sure the first ping will be sent @@ -1119,18 +893,14 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C } // send a ping every time we create a new remoting connection // to set up its TTL on the server side - else - { + else { pingRunnable.run(); } } - @Override - protected void finalize() throws Throwable - { - if (!closed && finalizeCheck) - { + protected void finalize() throws Throwable { + if (!closed && finalizeCheck) { ActiveMQClientLogger.LOGGER.factoryLeftOpen(createTrace, System.identityHashCode(this)); close(); @@ -1139,65 +909,53 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C super.finalize(); } - protected ConnectorFactory instantiateConnectorFactory(final String connectorFactoryClassName) - { + protected ConnectorFactory instantiateConnectorFactory(final String connectorFactoryClassName) { // Will set the instance here to avoid races where cachedFactory is set to null ConnectorFactory cachedFactory = connectorFactory; // First if cachedFactory had been used already, we take it from the cache. - if (cachedFactory != null && cachedFactory.getClass().getName().equals(connectorFactoryClassName)) - { + if (cachedFactory != null && cachedFactory.getClass().getName().equals(connectorFactoryClassName)) { return cachedFactory; } // else... we will try to instantiate a new one - return AccessController.doPrivileged(new PrivilegedAction() - { - public ConnectorFactory run() - { + return AccessController.doPrivileged(new PrivilegedAction() { + public ConnectorFactory run() { return (ConnectorFactory) ClassloadingUtil.newInstanceFromClassLoader(connectorFactoryClassName); } }); } + public class CloseRunnable implements Runnable { - public class CloseRunnable implements Runnable - { private final RemotingConnection conn; private final String scaleDownTargetNodeID; - public CloseRunnable(RemotingConnection conn, String scaleDownTargetNodeID) - { + public CloseRunnable(RemotingConnection conn, String scaleDownTargetNodeID) { this.conn = conn; this.scaleDownTargetNodeID = scaleDownTargetNodeID; } // Must be executed on new thread since cannot block the Netty thread for a long time and fail // can cause reconnect loop - public void run() - { - try - { + public void run() { + try { CLOSE_RUNNABLES.add(this); - if (scaleDownTargetNodeID == null) - { + if (scaleDownTargetNodeID == null) { conn.fail(ActiveMQClientMessageBundle.BUNDLE.disconnected()); } - else - { + else { conn.fail(ActiveMQClientMessageBundle.BUNDLE.disconnected(), scaleDownTargetNodeID); } } - finally - { + finally { CLOSE_RUNNABLES.remove(this); } } - public ClientSessionFactoryImpl stop() - { + public ClientSessionFactoryImpl stop() { causeExit(); CLOSE_RUNNABLES.remove(this); return ClientSessionFactoryImpl.this; @@ -1205,61 +963,44 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C } - - public void setReconnectAttempts(final int attempts) - { + public void setReconnectAttempts(final int attempts) { reconnectAttempts = attempts; } - public Object getConnector() - { + public Object getConnector() { return connector; } @Override - public ConfirmationWindowWarning getConfirmationWindowWarning() - { + public ConfirmationWindowWarning getConfirmationWindowWarning() { return confirmationWindowWarning; } - protected Connection openTransportConnection(final Connector connector) - { + protected Connection openTransportConnection(final Connector connector) { connector.start(); Connection transportConnection = connector.createConnection(); - if (transportConnection == null) - { - if (ClientSessionFactoryImpl.isDebug) - { + if (transportConnection == null) { + if (ClientSessionFactoryImpl.isDebug) { ActiveMQClientLogger.LOGGER.debug("Connector towards " + connector + " failed"); } - try - { + try { connector.close(); } - catch (Throwable t) - { + catch (Throwable t) { } } return transportConnection; } - protected Connector createConnector(ConnectorFactory connectorFactory, TransportConfiguration configuration) - { - return connectorFactory.createConnector(configuration.getParams(), - new DelegatingBufferHandler(), - this, - closeExecutor, - threadPool, - scheduledThreadPool, - clientProtocolManager); + protected Connector createConnector(ConnectorFactory connectorFactory, TransportConfiguration configuration) { + return connectorFactory.createConnector(configuration.getParams(), new DelegatingBufferHandler(), this, closeExecutor, threadPool, scheduledThreadPool, clientProtocolManager); } - private void checkTransportKeys(final ConnectorFactory factory, final TransportConfiguration tc) - { + private void checkTransportKeys(final ConnectorFactory factory, final TransportConfiguration tc) { } /** @@ -1268,33 +1009,26 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C * * @return */ - protected Connection createTransportConnection() - { + protected Connection createTransportConnection() { Connection transportConnection = null; - try - { - if (ClientSessionFactoryImpl.isDebug) - { + try { + if (ClientSessionFactoryImpl.isDebug) { ActiveMQClientLogger.LOGGER.debug("Trying to connect with connector = " + connectorFactory + - ", parameters = " + - connectorConfig.getParams() + - " connector = " + - connector); + ", parameters = " + + connectorConfig.getParams() + + " connector = " + + connector); } - Connector liveConnector = createConnector(connectorFactory, connectorConfig); - if ((transportConnection = openTransportConnection(liveConnector)) != null) - { + if ((transportConnection = openTransportConnection(liveConnector)) != null) { // if we can't connect the connect method will return null, hence we have to try the backup connector = liveConnector; } - else if (backupConfig != null) - { - if (ClientSessionFactoryImpl.isDebug) - { + else if (backupConfig != null) { + if (ClientSessionFactoryImpl.isDebug) { ActiveMQClientLogger.LOGGER.debug("Trying backup config = " + backupConfig); } @@ -1304,12 +1038,10 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C transportConnection = openTransportConnection(backupConnector); - if ((transportConnection = openTransportConnection(backupConnector)) != null) - { + if ((transportConnection = openTransportConnection(backupConnector)) != null) { /*looks like the backup is now live, let's use that*/ - if (ClientSessionFactoryImpl.isDebug) - { + if (ClientSessionFactoryImpl.isDebug) { ActiveMQClientLogger.LOGGER.debug("Connected to the backup at " + backupConfig); } @@ -1319,41 +1051,32 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C backupConfig = null; connectorFactory = backupConnectorFactory; } - else - { - if (ClientSessionFactoryImpl.isDebug) - { + else { + if (ClientSessionFactoryImpl.isDebug) { ActiveMQClientLogger.LOGGER.debug("Backup is not active yet"); } } } } - catch (Exception cause) - { + catch (Exception cause) { // Sanity catch for badly behaved remoting plugins ActiveMQClientLogger.LOGGER.createConnectorException(cause); - if (transportConnection != null) - { - try - { + if (transportConnection != null) { + try { transportConnection.close(); } - catch (Throwable t) - { + catch (Throwable t) { } } - if (connector != null) - { - try - { + if (connector != null) { + try { connector.close(); } - catch (Throwable t) - { + catch (Throwable t) { } } @@ -1365,85 +1088,73 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C return transportConnection; } - private class DelegatingBufferHandler implements BufferHandler - { - public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) - { + private class DelegatingBufferHandler implements BufferHandler { + + public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) { RemotingConnection theConn = connection; - if (theConn != null && connectionID.equals(theConn.getID())) - { + if (theConn != null && connectionID.equals(theConn.getID())) { theConn.bufferReceived(connectionID, buffer); } - else - { + else { ActiveMQClientLogger.LOGGER.debug("TheConn == null on ClientSessionFactoryImpl::DelegatingBufferHandler, ignoring packet"); } } } - private final class DelegatingFailureListener implements FailureListener - { + private final class DelegatingFailureListener implements FailureListener { + private final Object connectionID; - DelegatingFailureListener(final Object connectionID) - { + DelegatingFailureListener(final Object connectionID) { this.connectionID = connectionID; } @Override - public void connectionFailed(final ActiveMQException me, final boolean failedOver) - { + public void connectionFailed(final ActiveMQException me, final boolean failedOver) { connectionFailed(me, failedOver, null); } @Override - public void connectionFailed(final ActiveMQException me, final boolean failedOver, String scaleDownTargetNodeID) - { + public void connectionFailed(final ActiveMQException me, final boolean failedOver, String scaleDownTargetNodeID) { handleConnectionFailure(connectionID, me, scaleDownTargetNodeID); } @Override - public String toString() - { + public String toString() { return DelegatingFailureListener.class.getSimpleName() + "('reconnectsOrFailover', hash=" + super.hashCode() + ")"; } } - private static final class ActualScheduledPinger implements Runnable - { + private static final class ActualScheduledPinger implements Runnable { + private final WeakReference pingRunnable; - ActualScheduledPinger(final PingRunnable runnable) - { + ActualScheduledPinger(final PingRunnable runnable) { pingRunnable = new WeakReference(runnable); } - public void run() - { + public void run() { PingRunnable runnable = pingRunnable.get(); - if (runnable != null) - { + if (runnable != null) { runnable.run(); } } } - private final class PingRunnable implements Runnable - { + private final class PingRunnable implements Runnable { + private boolean cancelled; private boolean first; private long lastCheck = System.currentTimeMillis(); - public synchronized void run() - { - if (cancelled || stopPingingAfterOne && !first) - { + public synchronized void run() { + if (cancelled || stopPingingAfterOne && !first) { return; } @@ -1451,10 +1162,8 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C long now = System.currentTimeMillis(); - if (clientFailureCheckPeriod != -1 && connectionTTL != -1 && now >= lastCheck + connectionTTL) - { - if (!connection.checkDataReceived()) - { + if (clientFailureCheckPeriod != -1 && connectionTTL != -1 && now >= lastCheck + connectionTTL) { + if (!connection.checkDataReceived()) { // We use a different thread to send the fail // but the exception has to be created here to preserve the stack trace @@ -1462,19 +1171,16 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C cancelled = true; - threadPool.execute(new Runnable() - { + threadPool.execute(new Runnable() { // Must be executed on different thread - public void run() - { + public void run() { connection.fail(me); } }); return; } - else - { + else { lastCheck = now; } } @@ -1485,87 +1191,68 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C /** * */ - public void send() - { + public void send() { clientProtocolManager.ping(connectionTTL); } - public synchronized void cancel() - { + public synchronized void cancel() { cancelled = true; } } - - protected RemotingConnection establishNewConnection() - { + protected RemotingConnection establishNewConnection() { Connection transportConnection = createTransportConnection(); - if (transportConnection == null) - { - if (ClientSessionFactoryImpl.isTrace) - { + if (transportConnection == null) { + if (ClientSessionFactoryImpl.isTrace) { ActiveMQClientLogger.LOGGER.trace("Neither backup or live were active, will just give up now"); } return null; } - RemotingConnection newConnection = clientProtocolManager.connect(transportConnection, callTimeout, - callFailoverTimeout, incomingInterceptors, - outgoingInterceptors, - new SessionFactoryTopologyHandler()); + RemotingConnection newConnection = clientProtocolManager.connect(transportConnection, callTimeout, callFailoverTimeout, incomingInterceptors, outgoingInterceptors, new SessionFactoryTopologyHandler()); newConnection.addFailureListener(new DelegatingFailureListener(newConnection.getID())); schedulePing(); - if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) { ActiveMQClientLogger.LOGGER.trace("returning " + connection); } return newConnection; } - protected SessionContext createSessionChannel(final String name, final String username, final String password, final boolean xa, final boolean autoCommitSends, final boolean autoCommitAcks, - final boolean preAcknowledge) throws ActiveMQException - { - synchronized (createSessionLock) - { - return clientProtocolManager.createSessionContext(name, username, - password, xa, autoCommitSends, autoCommitAcks, preAcknowledge, - serverLocator.getMinLargeMessageSize(), serverLocator.getConfirmationWindowSize()); + final boolean preAcknowledge) throws ActiveMQException { + synchronized (createSessionLock) { + return clientProtocolManager.createSessionContext(name, username, password, xa, autoCommitSends, autoCommitAcks, preAcknowledge, serverLocator.getMinLargeMessageSize(), serverLocator.getConfirmationWindowSize()); } } @Override - public String getLiveNodeId() - { + public String getLiveNodeId() { return liveNodeID; } - class SessionFactoryTopologyHandler implements TopologyResponseHandler - { + class SessionFactoryTopologyHandler implements TopologyResponseHandler { @Override - public void nodeDisconnected(RemotingConnection conn, String nodeID, String scaleDownTargetNodeID) - { + public void nodeDisconnected(RemotingConnection conn, String nodeID, String scaleDownTargetNodeID) { - if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) { ActiveMQClientLogger.LOGGER.trace("Disconnect being called on client:" + - " server locator = " + - serverLocator + - " notifying node " + - nodeID + - " as down", new Exception("trace")); + " server locator = " + + serverLocator + + " notifying node " + + nodeID + + " as down", new Exception("trace")); } serverLocator.notifyNodeDown(System.currentTimeMillis(), nodeID); @@ -1575,19 +1262,21 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C } @Override - public void notifyNodeUp(long uniqueEventID, String nodeID, String backupGroupName, String scaleDownGroupName, Pair connectorPair, boolean isLast) - { + public void notifyNodeUp(long uniqueEventID, + String nodeID, + String backupGroupName, + String scaleDownGroupName, + Pair connectorPair, + boolean isLast) { // if it is our connector then set the live id used for failover - if (connectorPair.getA() != null && connectorPair.getA().equals(connectorConfig)) - { + if (connectorPair.getA() != null && connectorPair.getA().equals(connectorConfig)) { liveNodeID = nodeID; } serverLocator.notifyNodeUp(uniqueEventID, nodeID, backupGroupName, scaleDownGroupName, connectorPair, isLast); } @Override - public void notifyNodeDown(long eventTime, String nodeID) - { + public void notifyNodeDown(long eventTime, String nodeID) { serverLocator.notifyNodeDown(eventTime, nodeID); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientSessionFactoryInternal.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientSessionFactoryInternal.java index 0f12d76c85..ba2dab7694 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientSessionFactoryInternal.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientSessionFactoryInternal.java @@ -24,8 +24,8 @@ import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.api.core.client.SessionFailureListener; import org.apache.activemq.artemis.utils.ConfirmationWindowWarning; -public interface ClientSessionFactoryInternal extends ClientSessionFactory -{ +public interface ClientSessionFactoryInternal extends ClientSessionFactory { + void causeExit(); void addFailureListener(SessionFailureListener listener); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientSessionImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientSessionImpl.java index 49d8660517..5b028b28f1 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientSessionImpl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientSessionImpl.java @@ -50,8 +50,8 @@ import org.apache.activemq.artemis.utils.ConfirmationWindowWarning; import org.apache.activemq.artemis.utils.TokenBucketLimiterImpl; import org.apache.activemq.artemis.utils.XidCodecSupport; -public final class ClientSessionImpl implements ClientSessionInternal, FailureListener -{ +public final class ClientSessionImpl implements ClientSessionInternal, FailureListener { + private final Map metadata = new HashMap(); private final ClientSessionFactoryInternal sessionFactory; @@ -137,7 +137,6 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi */ private Xid currentXID; - private final AtomicInteger concurrentCall = new AtomicInteger(0); private final ConfirmationWindowWarning confirmationWindowWarning; @@ -167,8 +166,7 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi final String groupID, final SessionContext sessionContext, final Executor executor, - final Executor flowControlExecutor) throws ActiveMQException - { + final Executor flowControlExecutor) throws ActiveMQException { this.sessionFactory = sessionFactory; this.name = name; @@ -229,185 +227,153 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi // ClientSession implementation // ----------------------------------------------------------------- - public void createQueue(final SimpleString address, final SimpleString queueName) throws ActiveMQException - { + public void createQueue(final SimpleString address, final SimpleString queueName) throws ActiveMQException { internalCreateQueue(address, queueName, null, false, false); } - public void createQueue(final SimpleString address, final SimpleString queueName, final boolean durable) throws ActiveMQException - { + public void createQueue(final SimpleString address, + final SimpleString queueName, + final boolean durable) throws ActiveMQException { internalCreateQueue(address, queueName, null, durable, false); } - public void createQueue(final String address, final String queueName, final boolean durable) throws ActiveMQException - { + public void createQueue(final String address, + final String queueName, + final boolean durable) throws ActiveMQException { createQueue(SimpleString.toSimpleString(address), SimpleString.toSimpleString(queueName), durable); } public void createSharedQueue(SimpleString address, SimpleString queueName, - boolean durable) throws ActiveMQException - { + boolean durable) throws ActiveMQException { createSharedQueue(address, queueName, null, durable); } public void createSharedQueue(SimpleString address, SimpleString queueName, SimpleString filterString, - boolean durable) throws ActiveMQException - { + boolean durable) throws ActiveMQException { checkClosed(); - startCall(); - try - { + try { sessionContext.createSharedQueue(address, queueName, filterString, durable); } - finally - { + finally { endCall(); } } - public void createQueue(final SimpleString address, final SimpleString queueName, final SimpleString filterString, - final boolean durable) throws ActiveMQException - { + final boolean durable) throws ActiveMQException { internalCreateQueue(address, queueName, filterString, durable, false); } public void createQueue(final String address, final String queueName, final String filterString, - final boolean durable) throws ActiveMQException - { + final boolean durable) throws ActiveMQException { createQueue(SimpleString.toSimpleString(address), SimpleString.toSimpleString(queueName), SimpleString.toSimpleString(filterString), durable); } - public void createTemporaryQueue(final SimpleString address, final SimpleString queueName) throws ActiveMQException - { + public void createTemporaryQueue(final SimpleString address, final SimpleString queueName) throws ActiveMQException { internalCreateQueue(address, queueName, null, false, true); } - public void createTemporaryQueue(final String address, final String queueName) throws ActiveMQException - { - internalCreateQueue(SimpleString.toSimpleString(address), - SimpleString.toSimpleString(queueName), - null, - false, - true); + public void createTemporaryQueue(final String address, final String queueName) throws ActiveMQException { + internalCreateQueue(SimpleString.toSimpleString(address), SimpleString.toSimpleString(queueName), null, false, true); } - public void createTemporaryQueue(final SimpleString address, final SimpleString queueName, final SimpleString filter) throws ActiveMQException - { + public void createTemporaryQueue(final SimpleString address, + final SimpleString queueName, + final SimpleString filter) throws ActiveMQException { internalCreateQueue(address, queueName, filter, false, true); } - public void createTemporaryQueue(final String address, final String queueName, final String filter) throws ActiveMQException - { - internalCreateQueue(SimpleString.toSimpleString(address), - SimpleString.toSimpleString(queueName), - SimpleString.toSimpleString(filter), - false, - true); + public void createTemporaryQueue(final String address, + final String queueName, + final String filter) throws ActiveMQException { + internalCreateQueue(SimpleString.toSimpleString(address), SimpleString.toSimpleString(queueName), SimpleString.toSimpleString(filter), false, true); } - public void deleteQueue(final SimpleString queueName) throws ActiveMQException - { + public void deleteQueue(final SimpleString queueName) throws ActiveMQException { checkClosed(); startCall(); - try - { + try { sessionContext.deleteQueue(queueName); } - finally - { + finally { endCall(); } } - public void deleteQueue(final String queueName) throws ActiveMQException - { + public void deleteQueue(final String queueName) throws ActiveMQException { deleteQueue(SimpleString.toSimpleString(queueName)); } - public QueueQuery queueQuery(final SimpleString queueName) throws ActiveMQException - { + public QueueQuery queueQuery(final SimpleString queueName) throws ActiveMQException { checkClosed(); - startCall(); - try - { + try { return sessionContext.queueQuery(queueName); } - finally - { + finally { endCall(); } } - public AddressQuery addressQuery(final SimpleString address) throws ActiveMQException - { + public AddressQuery addressQuery(final SimpleString address) throws ActiveMQException { checkClosed(); - return sessionContext.addressQuery(address); } - public ClientConsumer createConsumer(final SimpleString queueName) throws ActiveMQException - { + public ClientConsumer createConsumer(final SimpleString queueName) throws ActiveMQException { return createConsumer(queueName, null, false); } - public ClientConsumer createConsumer(final String queueName) throws ActiveMQException - { + public ClientConsumer createConsumer(final String queueName) throws ActiveMQException { return createConsumer(SimpleString.toSimpleString(queueName)); } - public ClientConsumer createConsumer(final SimpleString queueName, final SimpleString filterString) throws ActiveMQException - { + public ClientConsumer createConsumer(final SimpleString queueName, + final SimpleString filterString) throws ActiveMQException { return createConsumer(queueName, filterString, consumerWindowSize, consumerMaxRate, false); } - public void createQueue(final String address, final String queueName) throws ActiveMQException - { + public void createQueue(final String address, final String queueName) throws ActiveMQException { createQueue(SimpleString.toSimpleString(address), SimpleString.toSimpleString(queueName)); } - public ClientConsumer createConsumer(final String queueName, final String filterString) throws ActiveMQException - { + public ClientConsumer createConsumer(final String queueName, final String filterString) throws ActiveMQException { return createConsumer(SimpleString.toSimpleString(queueName), SimpleString.toSimpleString(filterString)); } public ClientConsumer createConsumer(final SimpleString queueName, final SimpleString filterString, - final boolean browseOnly) throws ActiveMQException - { + final boolean browseOnly) throws ActiveMQException { return createConsumer(queueName, filterString, consumerWindowSize, consumerMaxRate, browseOnly); } - public ClientConsumer createConsumer(final SimpleString queueName, final boolean browseOnly) throws ActiveMQException - { + public ClientConsumer createConsumer(final SimpleString queueName, + final boolean browseOnly) throws ActiveMQException { return createConsumer(queueName, null, consumerWindowSize, consumerMaxRate, browseOnly); } - public ClientConsumer createConsumer(final String queueName, final String filterString, final boolean browseOnly) throws ActiveMQException - { - return createConsumer(SimpleString.toSimpleString(queueName), - SimpleString.toSimpleString(filterString), - browseOnly); + public ClientConsumer createConsumer(final String queueName, + final String filterString, + final boolean browseOnly) throws ActiveMQException { + return createConsumer(SimpleString.toSimpleString(queueName), SimpleString.toSimpleString(filterString), browseOnly); } - public ClientConsumer createConsumer(final String queueName, final boolean browseOnly) throws ActiveMQException - { + public ClientConsumer createConsumer(final String queueName, final boolean browseOnly) throws ActiveMQException { return createConsumer(SimpleString.toSimpleString(queueName), null, browseOnly); } @@ -425,8 +391,7 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi final SimpleString filterString, final int windowSize, final int maxRate, - final boolean browseOnly) throws ActiveMQException - { + final boolean browseOnly) throws ActiveMQException { return internalCreateConsumer(queueName, filterString, windowSize, maxRate, browseOnly); } @@ -434,67 +399,55 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi final String filterString, final int windowSize, final int maxRate, - final boolean browseOnly) throws ActiveMQException - { + final boolean browseOnly) throws ActiveMQException { return createConsumer(SimpleString.toSimpleString(queueName), SimpleString.toSimpleString(filterString), windowSize, maxRate, browseOnly); } - public ClientProducer createProducer() throws ActiveMQException - { + public ClientProducer createProducer() throws ActiveMQException { return createProducer((SimpleString) null); } - public ClientProducer createProducer(final SimpleString address) throws ActiveMQException - { + public ClientProducer createProducer(final SimpleString address) throws ActiveMQException { return createProducer(address, producerMaxRate); } - public ClientProducer createProducer(final String address) throws ActiveMQException - { + public ClientProducer createProducer(final String address) throws ActiveMQException { return createProducer(SimpleString.toSimpleString(address)); } - public ClientProducer createProducer(final SimpleString address, final int maxRate) throws ActiveMQException - { + public ClientProducer createProducer(final SimpleString address, final int maxRate) throws ActiveMQException { return internalCreateProducer(address, maxRate); } - public ClientProducer createProducer(final String address, final int rate) throws ActiveMQException - { + public ClientProducer createProducer(final String address, final int rate) throws ActiveMQException { return createProducer(SimpleString.toSimpleString(address), rate); } - public XAResource getXAResource() - { + public XAResource getXAResource() { return this; } - private void rollbackOnFailover(boolean outcomeKnown) throws ActiveMQException - { + private void rollbackOnFailover(boolean outcomeKnown) throws ActiveMQException { rollback(false); - if (outcomeKnown) - { + if (outcomeKnown) { throw ActiveMQClientMessageBundle.BUNDLE.txRolledBack(); } throw ActiveMQClientMessageBundle.BUNDLE.txOutcomeUnknown(); } - public void commit() throws ActiveMQException - { + public void commit() throws ActiveMQException { checkClosed(); - if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) { ActiveMQClientLogger.LOGGER.trace("Sending commit"); } /* * we have failed over since any work was done so we should rollback * */ - if (rollbackOnly) - { + if (rollbackOnly) { rollbackOnFailover(true); } @@ -503,53 +456,43 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi * if we have failed over whilst flushing the acks then we should rollback and throw exception before attempting to * commit as committing might actually commit something but we we wouldn't know and rollback after the commit * */ - if (rollbackOnly) - { + if (rollbackOnly) { rollbackOnFailover(true); } - try - { + try { sessionContext.simpleCommit(); } - catch (ActiveMQException e) - { - if (e.getType() == ActiveMQExceptionType.UNBLOCKED || rollbackOnly) - { + catch (ActiveMQException e) { + if (e.getType() == ActiveMQExceptionType.UNBLOCKED || rollbackOnly) { // The call to commit was unlocked on failover, we therefore rollback the tx, // and throw a transaction rolled back exception instead //or //if we have been set to rollbackonly then we have probably failed over and don't know if the tx has committed rollbackOnFailover(false); } - else - { + else { throw e; } } //oops, we have failed over during the commit and don't know what happened - if (rollbackOnly) - { + if (rollbackOnly) { rollbackOnFailover(false); } workDone = false; } - public boolean isRollbackOnly() - { + public boolean isRollbackOnly() { return rollbackOnly; } - public void rollback() throws ActiveMQException - { + public void rollback() throws ActiveMQException { rollback(false); } - public void rollback(final boolean isLastMessageAsDelivered) throws ActiveMQException - { - if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) - { + public void rollback(final boolean isLastMessageAsDelivered) throws ActiveMQException { + if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) { ActiveMQClientLogger.LOGGER.trace("calling rollback(isLastMessageAsDelivered=" + isLastMessageAsDelivered + ")"); } checkClosed(); @@ -561,15 +504,12 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi boolean wasStarted = started; - if (wasStarted) - { + if (wasStarted) { stop(); } - // We need to make sure we don't get any inflight messages - for (ClientConsumerInternal consumer : cloneConsumers()) - { + for (ClientConsumerInternal consumer : cloneConsumers()) { consumer.clear(true); } @@ -578,8 +518,7 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi sessionContext.simpleRollback(isLastMessageAsDelivered); - if (wasStarted) - { + if (wasStarted) { start(); } @@ -590,63 +529,50 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi final boolean durable, final long expiration, final long timestamp, - final byte priority) - { + final byte priority) { return new ClientMessageImpl(type, durable, expiration, timestamp, priority, initialMessagePacketSize); } - public ClientMessage createMessage(final byte type, final boolean durable) - { + public ClientMessage createMessage(final byte type, final boolean durable) { return this.createMessage(type, durable, 0, System.currentTimeMillis(), (byte) 4); } - public ClientMessage createMessage(final boolean durable) - { + public ClientMessage createMessage(final boolean durable) { return this.createMessage((byte) 0, durable); } - public boolean isClosed() - { + public boolean isClosed() { return closed; } - public boolean isAutoCommitSends() - { + public boolean isAutoCommitSends() { return autoCommitSends; } - public boolean isAutoCommitAcks() - { + public boolean isAutoCommitAcks() { return autoCommitAcks; } - public boolean isBlockOnAcknowledge() - { + public boolean isBlockOnAcknowledge() { return blockOnAcknowledge; } - public boolean isXA() - { + public boolean isXA() { return xa; } - public void resetIfNeeded() throws ActiveMQException - { - if (rollbackOnly) - { + public void resetIfNeeded() throws ActiveMQException { + if (rollbackOnly) { ActiveMQClientLogger.LOGGER.resettingSessionAfterFailure(); rollback(false); } } - public ClientSessionImpl start() throws ActiveMQException - { + public ClientSessionImpl start() throws ActiveMQException { checkClosed(); - if (!started) - { - for (ClientConsumerInternal clientConsumerInternal : cloneConsumers()) - { + if (!started) { + for (ClientConsumerInternal clientConsumerInternal : cloneConsumers()) { clientConsumerInternal.start(); } @@ -658,19 +584,15 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi return this; } - public void stop() throws ActiveMQException - { + public void stop() throws ActiveMQException { stop(true); } - public void stop(final boolean waitForOnMessage) throws ActiveMQException - { + public void stop(final boolean waitForOnMessage) throws ActiveMQException { checkClosed(); - if (started) - { - for (ClientConsumerInternal clientConsumerInternal : cloneConsumers()) - { + if (started) { + for (ClientConsumerInternal clientConsumerInternal : cloneConsumers()) { clientConsumerInternal.stop(waitForOnMessage); } @@ -680,209 +602,173 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi } } - public void addFailureListener(final SessionFailureListener listener) - { + public void addFailureListener(final SessionFailureListener listener) { sessionFactory.addFailureListener(listener); } - public boolean removeFailureListener(final SessionFailureListener listener) - { + public boolean removeFailureListener(final SessionFailureListener listener) { return sessionFactory.removeFailureListener(listener); } - public void addFailoverListener(FailoverEventListener listener) - { + public void addFailoverListener(FailoverEventListener listener) { sessionFactory.addFailoverListener(listener); } - public boolean removeFailoverListener(FailoverEventListener listener) - { + public boolean removeFailoverListener(FailoverEventListener listener) { return sessionFactory.removeFailoverListener(listener); } - public int getVersion() - { + public int getVersion() { return sessionContext.getServerVersion(); } - public boolean isClosing() - { + public boolean isClosing() { return inClose; } @Override - public String getNodeId() - { + public String getNodeId() { return sessionFactory.getLiveNodeId(); } // ClientSessionInternal implementation // ------------------------------------------------------------ - public int getMinLargeMessageSize() - { + public int getMinLargeMessageSize() { return minLargeMessageSize; } - public boolean isCompressLargeMessages() - { + public boolean isCompressLargeMessages() { return compressLargeMessages; } /** * @return the cacheLargeMessageClient */ - public boolean isCacheLargeMessageClient() - { + public boolean isCacheLargeMessageClient() { return cacheLargeMessageClient; } - public String getName() - { + public String getName() { return name; } /** * Acknowledges all messages received by the consumer so far. */ - public void acknowledge(final ClientConsumer consumer, final Message message) throws ActiveMQException - { + public void acknowledge(final ClientConsumer consumer, final Message message) throws ActiveMQException { // if we're pre-acknowledging then we don't need to do anything - if (preAcknowledge) - { + if (preAcknowledge) { return; } checkClosed(); - if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) { ActiveMQClientLogger.LOGGER.debug("client ack messageID = " + message.getMessageID()); } startCall(); - try - { + try { sessionContext.sendACK(false, blockOnAcknowledge, consumer, message); } - finally - { + finally { endCall(); } } - public void individualAcknowledge(final ClientConsumer consumer, final Message message) throws ActiveMQException - { + public void individualAcknowledge(final ClientConsumer consumer, final Message message) throws ActiveMQException { // if we're pre-acknowledging then we don't need to do anything - if (preAcknowledge) - { + if (preAcknowledge) { return; } checkClosed(); startCall(); - try - { + try { sessionContext.sendACK(true, blockOnAcknowledge, consumer, message); } - finally - { + finally { endCall(); } } - public void expire(final ClientConsumer consumer, final Message message) throws ActiveMQException - { + public void expire(final ClientConsumer consumer, final Message message) throws ActiveMQException { checkClosed(); // We don't send expiries for pre-ack since message will already have been acked on server - if (!preAcknowledge) - { + if (!preAcknowledge) { sessionContext.expireMessage(consumer, message); } } - public void addConsumer(final ClientConsumerInternal consumer) - { - synchronized (consumers) - { + public void addConsumer(final ClientConsumerInternal consumer) { + synchronized (consumers) { consumers.put(consumer.getConsumerContext(), consumer); } } - public void addProducer(final ClientProducerInternal producer) - { - synchronized (producers) - { + public void addProducer(final ClientProducerInternal producer) { + synchronized (producers) { producers.add(producer); } } - public void removeConsumer(final ClientConsumerInternal consumer) throws ActiveMQException - { - synchronized (consumers) - { + public void removeConsumer(final ClientConsumerInternal consumer) throws ActiveMQException { + synchronized (consumers) { consumers.remove(consumer.getConsumerContext()); } } - public void removeProducer(final ClientProducerInternal producer) - { - synchronized (producers) - { + public void removeProducer(final ClientProducerInternal producer) { + synchronized (producers) { producers.remove(producer); } } - public void handleReceiveMessage(final ConsumerContext consumerID, final ClientMessageInternal message) throws Exception - { + public void handleReceiveMessage(final ConsumerContext consumerID, + final ClientMessageInternal message) throws Exception { ClientConsumerInternal consumer = getConsumer(consumerID); - if (consumer != null) - { + if (consumer != null) { consumer.handleMessage(message); } } - public void handleReceiveLargeMessage(final ConsumerContext consumerID, ClientLargeMessageInternal clientLargeMessage, long largeMessageSize) throws Exception - { + public void handleReceiveLargeMessage(final ConsumerContext consumerID, + ClientLargeMessageInternal clientLargeMessage, + long largeMessageSize) throws Exception { ClientConsumerInternal consumer = getConsumer(consumerID); - if (consumer != null) - { + if (consumer != null) { consumer.handleLargeMessage(clientLargeMessage, largeMessageSize); } } - public void handleReceiveContinuation(final ConsumerContext consumerID, byte[] chunk, int flowControlSize, boolean isContinues) throws Exception - { + public void handleReceiveContinuation(final ConsumerContext consumerID, + byte[] chunk, + int flowControlSize, + boolean isContinues) throws Exception { ClientConsumerInternal consumer = getConsumer(consumerID); - if (consumer != null) - { + if (consumer != null) { consumer.handleLargeMessageContinuation(chunk, flowControlSize, isContinues); } } @Override - public void handleConsumerDisconnect(ConsumerContext context) throws ActiveMQException - { + public void handleConsumerDisconnect(ConsumerContext context) throws ActiveMQException { final ClientConsumerInternal consumer = getConsumer(context); - if (consumer != null) - { - executor.execute(new Runnable() - { + if (consumer != null) { + executor.execute(new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { consumer.close(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { ActiveMQClientLogger.LOGGER.unableToCloseConsumer(e); } } @@ -890,32 +776,26 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi } } - public void close() throws ActiveMQException - { - if (closed) - { + public void close() throws ActiveMQException { + if (closed) { ActiveMQClientLogger.LOGGER.debug("Session was already closed, giving up now, this=" + this); return; } - if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) { ActiveMQClientLogger.LOGGER.debug("Calling close on session " + this); } - try - { + try { closeChildren(); - synchronized (this) - { + synchronized (this) { producerCreditManager.close(); } inClose = true; sessionContext.sessionClose(); } - catch (Throwable e) - { + catch (Throwable e) { // Session close should always return without exception // Note - we only log at trace @@ -925,10 +805,8 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi doCleanup(false); } - public synchronized void cleanUp(boolean failingOver) throws ActiveMQException - { - if (closed) - { + public synchronized void cleanUp(boolean failingOver) throws ActiveMQException { + if (closed) { return; } @@ -939,14 +817,12 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi doCleanup(failingOver); } - public ClientSessionImpl setSendAcknowledgementHandler(final SendAcknowledgementHandler handler) - { + public ClientSessionImpl setSendAcknowledgementHandler(final SendAcknowledgementHandler handler) { sessionContext.setSendAcknowledgementHandler(handler); return this; } - public void preHandleFailover(RemotingConnection connection) - { + public void preHandleFailover(RemotingConnection connection) { // We lock the channel to prevent any packets to be added to the re-send // cache during the failover process //we also do this before the connection fails over to give the session a chance to block for failover @@ -955,32 +831,25 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi // Needs to be synchronized to prevent issues with occurring concurrently with close() - public void handleFailover(final RemotingConnection backupConnection, ActiveMQException cause) - { - synchronized (this) - { - if (closed) - { + public void handleFailover(final RemotingConnection backupConnection, ActiveMQException cause) { + synchronized (this) { + if (closed) { return; } boolean resetCreditManager = false; - try - { + try { // TODO remove this and encapsulate it boolean reattached = sessionContext.reattachOnNewConnection(backupConnection); - if (!reattached) - { - for (ClientConsumerInternal consumer : cloneConsumers()) - { + if (!reattached) { + for (ClientConsumerInternal consumer : cloneConsumers()) { consumer.clearAtFailover(); } - // The session wasn't found on the server - probably we're failing over onto a backup server where the // session won't exist or the target server has been restarted - in this case the session will need to be // recreated, @@ -992,37 +861,29 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi // has already been executed on the server, that's why we can't find the session- in this case we *don't* // want // to recreate the session, we just want to unblock the blocking call - if (!inClose && mayAttemptToFailover) - { - sessionContext.recreateSession(username, password, - minLargeMessageSize, xa, autoCommitSends, - autoCommitAcks, preAcknowledge, defaultAddress); + if (!inClose && mayAttemptToFailover) { + sessionContext.recreateSession(username, password, minLargeMessageSize, xa, autoCommitSends, autoCommitAcks, preAcknowledge, defaultAddress); - for (Map.Entry entryx : consumers.entrySet()) - { + for (Map.Entry entryx : consumers.entrySet()) { ClientConsumerInternal consumerInternal = entryx.getValue(); sessionContext.recreateConsumerOnServer(consumerInternal); } - if ((!autoCommitAcks || !autoCommitSends) && workDone) - { + if ((!autoCommitAcks || !autoCommitSends) && workDone) { // this is protected by a lock, so we can guarantee nothing will sneak here // while we do our work here rollbackOnly = true; } - if (currentXID != null) - { + if (currentXID != null) { sessionContext.xaFailed(currentXID); rollbackOnly = true; } // Now start the session if it was already started - if (started) - { - for (ClientConsumerInternal consumer : cloneConsumers()) - { + if (started) { + for (ClientConsumerInternal consumer : cloneConsumers()) { consumer.clearAtFailover(); consumer.start(); } @@ -1036,17 +897,14 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi sessionContext.returnBlocking(cause); } } - catch (Throwable t) - { + catch (Throwable t) { ActiveMQClientLogger.LOGGER.failedToHandleFailover(t); } - finally - { + finally { sessionContext.releaseCommunications(); } - if (resetCreditManager) - { + if (resetCreditManager) { producerCreditManager.reset(); // Also need to send more credits for consumers, otherwise the system could hand with the server @@ -1056,112 +914,89 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi HashMap metaDataToSend; - synchronized (metadata) - { + synchronized (metadata) { metaDataToSend = new HashMap(metadata); } sessionContext.resetMetadata(metaDataToSend); - } - public void addMetaData(String key, String data) throws ActiveMQException - { - synchronized (metadata) - { + public void addMetaData(String key, String data) throws ActiveMQException { + synchronized (metadata) { metadata.put(key, data); } sessionContext.addSessionMetadata(key, data); } - public void addUniqueMetaData(String key, String data) throws ActiveMQException - { + public void addUniqueMetaData(String key, String data) throws ActiveMQException { sessionContext.addUniqueMetaData(key, data); } - public ClientSessionFactory getSessionFactory() - { + public ClientSessionFactory getSessionFactory() { return sessionFactory; } - public void setAddress(final Message message, final SimpleString address) - { - if (defaultAddress == null) - { + public void setAddress(final Message message, final SimpleString address) { + if (defaultAddress == null) { defaultAddress = address; message.setAddress(address); } - else - { - if (!address.equals(defaultAddress)) - { + else { + if (!address.equals(defaultAddress)) { message.setAddress(address); } - else - { + else { message.setAddress(null); } } } - public void setPacketSize(final int packetSize) - { - if (packetSize > this.initialMessagePacketSize) - { + public void setPacketSize(final int packetSize) { + if (packetSize > this.initialMessagePacketSize) { this.initialMessagePacketSize = (int) (packetSize * 1.2); } } - public void workDone() - { + public void workDone() { workDone = true; } - public void sendProducerCreditsMessage(final int credits, final SimpleString address) - { + public void sendProducerCreditsMessage(final int credits, final SimpleString address) { sessionContext.sendProducerCreditsMessage(credits, address); } - public synchronized ClientProducerCredits getCredits(final SimpleString address, final boolean anon) - { + public synchronized ClientProducerCredits getCredits(final SimpleString address, final boolean anon) { ClientProducerCredits credits = producerCreditManager.getCredits(address, anon, sessionContext); return credits; } - public void returnCredits(final SimpleString address) - { + public void returnCredits(final SimpleString address) { producerCreditManager.returnCredits(address); } - public void handleReceiveProducerCredits(final SimpleString address, final int credits) - { + public void handleReceiveProducerCredits(final SimpleString address, final int credits) { producerCreditManager.receiveCredits(address, credits); } - public void handleReceiveProducerFailCredits(final SimpleString address, int credits) - { + public void handleReceiveProducerFailCredits(final SimpleString address, int credits) { producerCreditManager.receiveFailCredits(address, credits); } - public ClientProducerCreditManager getProducerCreditManager() - { + public ClientProducerCreditManager getProducerCreditManager() { return producerCreditManager; } - public void startCall() - { - if (concurrentCall.incrementAndGet() > 1) - { + public void startCall() { + if (concurrentCall.incrementAndGet() > 1) { ActiveMQClientLogger.LOGGER.invalidConcurrentSessionUsage(new Exception("trace")); } } - public void endCall() - { + public void endCall() { concurrentCall.decrementAndGet(); } @@ -1172,17 +1007,14 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi // XAResource implementation // -------------------------------------------------------------------- - public void commit(final Xid xid, final boolean onePhase) throws XAException - { - if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) - { + public void commit(final Xid xid, final boolean onePhase) throws XAException { + if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) { ActiveMQClientLogger.LOGGER.trace("call commit(xid=" + convert(xid)); } checkXA(); // we should never throw rollback if we have already prepared - if (rollbackOnly) - { + if (rollbackOnly) { ActiveMQClientLogger.LOGGER.commitAfterFailover(); } @@ -1190,17 +1022,14 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi // done this startCall(); - try - { + try { sessionContext.xaCommit(xid, onePhase); workDone = false; } - catch (XAException xae) - { + catch (XAException xae) { throw xae; } - catch (Throwable t) - { + catch (Throwable t) { ActiveMQClientLogger.LOGGER.failoverDuringCommit(); // Any error on commit -> RETRY @@ -1209,56 +1038,44 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi xaException.initCause(t); throw xaException; } - finally - { + finally { endCall(); } } - public void end(final Xid xid, final int flags) throws XAException - { - if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) - { + public void end(final Xid xid, final int flags) throws XAException { + if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) { ActiveMQClientLogger.LOGGER.trace("Calling end:: " + convert(xid) + ", flags=" + convertTXFlag(flags)); } checkXA(); - try - { - if (rollbackOnly) - { - try - { + try { + if (rollbackOnly) { + try { rollback(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { ActiveMQClientLogger.LOGGER.debug("Error on rollback during end call!", ignored); } throw new XAException(XAException.XAER_RMFAIL); } - try - { + try { flushAcks(); startCall(); - try - { + try { sessionContext.xaEnd(xid, flags); } - finally - { + finally { endCall(); } } - catch (XAException xae) - { + catch (XAException xae) { throw xae; } - catch (Throwable t) - { + catch (Throwable t) { ActiveMQClientLogger.LOGGER.errorCallingEnd(t); // This could occur if the TM interrupts the thread XAException xaException = new XAException(XAException.XAER_RMFAIL); @@ -1266,47 +1083,38 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi throw xaException; } } - finally - { + finally { currentXID = null; } } - public void forget(final Xid xid) throws XAException - { + public void forget(final Xid xid) throws XAException { checkXA(); startCall(); - try - { + try { sessionContext.xaForget(xid); } - catch (XAException xae) - { + catch (XAException xae) { throw xae; } - catch (Throwable t) - { + catch (Throwable t) { // This could occur if the TM interrupts the thread XAException xaException = new XAException(XAException.XAER_RMFAIL); xaException.initCause(t); throw xaException; } - finally - { + finally { endCall(); } } - public int getTransactionTimeout() throws XAException - { + public int getTransactionTimeout() throws XAException { checkXA(); - try - { + try { return sessionContext.recoverSessionTimeout(); } - catch (Throwable t) - { + catch (Throwable t) { // This could occur if the TM interrupts the thread XAException xaException = new XAException(XAException.XAER_RMFAIL); xaException.initCause(t); @@ -1314,16 +1122,13 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi } } - public boolean setTransactionTimeout(final int seconds) throws XAException - { + public boolean setTransactionTimeout(final int seconds) throws XAException { checkXA(); - try - { + try { return sessionContext.configureTransactionTimeout(seconds); } - catch (Throwable t) - { + catch (Throwable t) { // This could occur if the TM interrupts the thread XAException xaException = new XAException(XAException.XAER_RMFAIL); xaException.initCause(t); @@ -1331,27 +1136,23 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi } } - public boolean isSameRM(final XAResource xares) throws XAException - { + public boolean isSameRM(final XAResource xares) throws XAException { checkXA(); - if (forceNotSameRM) - { + if (forceNotSameRM) { return false; } ClientSessionInternal other = getSessionInternalFromXAResource(xares); - if (other == null) - { + if (other == null) { return false; } String liveNodeId = sessionFactory.getLiveNodeId(); String otherLiveNodeId = ((ClientSessionFactoryInternal) other.getSessionFactory()).getLiveNodeId(); - if (liveNodeId != null && otherLiveNodeId != null) - { + if (liveNodeId != null && otherLiveNodeId != null) { return liveNodeId.equals(otherLiveNodeId); } @@ -1359,34 +1160,26 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi return sessionFactory == other.getSessionFactory(); } - private ClientSessionInternal getSessionInternalFromXAResource(final XAResource xares) - { - if (xares == null) - { + private ClientSessionInternal getSessionInternalFromXAResource(final XAResource xares) { + if (xares == null) { return null; } - if (xares instanceof ClientSessionInternal) - { + if (xares instanceof ClientSessionInternal) { return (ClientSessionInternal) xares; } - else if (xares instanceof ActiveMQXAResource) - { - return getSessionInternalFromXAResource(((ActiveMQXAResource)xares).getResource()); + else if (xares instanceof ActiveMQXAResource) { + return getSessionInternalFromXAResource(((ActiveMQXAResource) xares).getResource()); } return null; } - public int prepare(final Xid xid) throws XAException - { + public int prepare(final Xid xid) throws XAException { checkXA(); - if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) { ActiveMQClientLogger.LOGGER.trace("Calling prepare:: " + convert(xid)); } - - if (rollbackOnly) - { + if (rollbackOnly) { throw new XAException(XAException.XAER_RMFAIL); } @@ -1394,35 +1187,27 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi // done this startCall(); - try - { + try { return sessionContext.xaPrepare(xid); } - catch (XAException xae) - { + catch (XAException xae) { throw xae; } - catch (ActiveMQException e) - { - if (e.getType() == ActiveMQExceptionType.UNBLOCKED) - { + catch (ActiveMQException e) { + if (e.getType() == ActiveMQExceptionType.UNBLOCKED) { // Unblocked on failover - try - { + try { // will retry once after failover & unblock return sessionContext.xaPrepare(xid); } - catch (Throwable t) - { + catch (Throwable t) { // ignore and rollback } ActiveMQClientLogger.LOGGER.failoverDuringPrepareRollingBack(); - try - { + try { rollback(false); } - catch (Throwable t) - { + catch (Throwable t) { // This could occur if the TM interrupts the thread XAException xaException = new XAException(XAException.XAER_RMFAIL); xaException.initCause(t); @@ -1441,8 +1226,7 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi xaException.initCause(e); throw xaException; } - catch (Throwable t) - { + catch (Throwable t) { ActiveMQClientLogger.LOGGER.errorDuringPrepare(t); // This could occur if the TM interrupts the thread @@ -1450,24 +1234,19 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi xaException.initCause(t); throw xaException; } - finally - { + finally { endCall(); } } - public Xid[] recover(final int flags) throws XAException - { + public Xid[] recover(final int flags) throws XAException { checkXA(); - if ((flags & XAResource.TMSTARTRSCAN) == XAResource.TMSTARTRSCAN) - { - try - { + if ((flags & XAResource.TMSTARTRSCAN) == XAResource.TMSTARTRSCAN) { + try { return sessionContext.xaScan(); } - catch (Throwable t) - { + catch (Throwable t) { // This could occur if the TM interrupts the thread XAException xaException = new XAException(XAException.XAER_RMFAIL); xaException.initCause(t); @@ -1478,54 +1257,43 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi return new Xid[0]; } - public void rollback(final Xid xid) throws XAException - { + public void rollback(final Xid xid) throws XAException { checkXA(); - if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) { ActiveMQClientLogger.LOGGER.trace("Calling rollback:: " + convert(xid)); } - try - { + try { boolean wasStarted = started; - if (wasStarted) - { + if (wasStarted) { stop(false); } // We need to make sure we don't get any inflight messages - for (ClientConsumerInternal consumer : cloneConsumers()) - { + for (ClientConsumerInternal consumer : cloneConsumers()) { consumer.clear(false); } flushAcks(); - try - { + try { sessionContext.xaRollback(xid, wasStarted); } - finally - { - if (wasStarted) - { + finally { + if (wasStarted) { start(); } } workDone = false; } - catch (XAException xae) - { + catch (XAException xae) { throw xae; } - catch (ActiveMQException e) - { - if (e.getType() == ActiveMQExceptionType.UNBLOCKED) - { + catch (ActiveMQException e) { + if (e.getType() == ActiveMQExceptionType.UNBLOCKED) { // Unblocked on failover throw new XAException(XAException.XA_RETRY); } @@ -1535,8 +1303,7 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi xaException.initCause(e); throw xaException; } - catch (Throwable t) - { + catch (Throwable t) { // This could occur if the TM interrupts the thread XAException xaException = new XAException(XAException.XAER_RMFAIL); xaException.initCause(t); @@ -1544,40 +1311,31 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi } } - public void start(final Xid xid, final int flags) throws XAException - { - if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) - { + public void start(final Xid xid, final int flags) throws XAException { + if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) { ActiveMQClientLogger.LOGGER.trace("Calling start:: " + convert(xid) + " clientXID=" + xid + " flags = " + convertTXFlag(flags)); } checkXA(); - try - { + try { sessionContext.xaStart(xid, flags); this.currentXID = xid; } - catch (XAException xae) - { + catch (XAException xae) { throw xae; } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { // we can retry this only because we know for sure that no work would have been done - if (e.getType() == ActiveMQExceptionType.UNBLOCKED) - { - try - { + if (e.getType() == ActiveMQExceptionType.UNBLOCKED) { + try { sessionContext.xaStart(xid, flags); } - catch (XAException xae) - { + catch (XAException xae) { throw xae; } - catch (Throwable t) - { + catch (Throwable t) { // This could occur if the TM interrupts the thread XAException xaException = new XAException(XAException.XAER_RMFAIL); xaException.initCause(t); @@ -1590,8 +1348,7 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi xaException.initCause(e); throw xaException; } - catch (Throwable t) - { + catch (Throwable t) { // This could occur if the TM interrupts the thread XAException xaException = new XAException(XAException.XAER_RMFAIL); xaException.initCause(t); @@ -1601,44 +1358,35 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi // FailureListener implementation -------------------------------------------- - public void connectionFailed(final ActiveMQException me, boolean failedOver) - { - try - { + public void connectionFailed(final ActiveMQException me, boolean failedOver) { + try { cleanUp(false); } - catch (Exception e) - { + catch (Exception e) { ActiveMQClientLogger.LOGGER.failedToCleanupSession(e); } } - public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) { connectionFailed(me, failedOver); } // Public // ---------------------------------------------------------------------------- - public void setForceNotSameRM(final boolean force) - { + public void setForceNotSameRM(final boolean force) { forceNotSameRM = force; } - public RemotingConnection getConnection() - { + public RemotingConnection getConnection() { return sessionContext.getRemotingConnection(); } @Override - public String toString() - { + public String toString() { StringBuilder buffer = new StringBuilder(); - synchronized (metadata) - { - for (Map.Entry entry : metadata.entrySet()) - { + synchronized (metadata) { + for (Map.Entry entry : metadata.entrySet()) { buffer.append(entry.getKey() + "=" + entry.getValue() + ","); } } @@ -1667,12 +1415,10 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi final SimpleString filterString, final int windowSize, final int maxRate, - final boolean browseOnly) throws ActiveMQException - { + final boolean browseOnly) throws ActiveMQException { checkClosed(); - ClientConsumerInternal consumer = sessionContext.createConsumer(queueName, filterString, windowSize, maxRate, - ackBatchSize, browseOnly, executor, flowControlExecutor); + ClientConsumerInternal consumer = sessionContext.createConsumer(queueName, filterString, windowSize, maxRate, ackBatchSize, browseOnly, executor, flowControlExecutor); addConsumer(consumer); @@ -1681,28 +1427,18 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi // consumer // TODO: this could semantically change on other servers. I know for instance on stomp this is just an ignore - if (windowSize != 0) - { + if (windowSize != 0) { sessionContext.sendConsumerCredits(consumer, windowSize); } return consumer; } - private ClientProducer internalCreateProducer(final SimpleString address, final int maxRate) throws ActiveMQException - { + private ClientProducer internalCreateProducer(final SimpleString address, + final int maxRate) throws ActiveMQException { checkClosed(); - ClientProducerInternal producer = new ClientProducerImpl(this, - address, - maxRate == -1 ? null - : new TokenBucketLimiterImpl(maxRate, false), - autoCommitSends && blockOnNonDurableSend, - autoCommitSends && blockOnDurableSend, - autoGroup, - groupID == null ? null : new SimpleString(groupID), - minLargeMessageSize, - sessionContext); + ClientProducerInternal producer = new ClientProducerImpl(this, address, maxRate == -1 ? null : new TokenBucketLimiterImpl(maxRate, false), autoCommitSends && blockOnNonDurableSend, autoCommitSends && blockOnDurableSend, autoGroup, groupID == null ? null : new SimpleString(groupID), minLargeMessageSize, sessionContext); addProducer(producer); @@ -1713,61 +1449,48 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi final SimpleString queueName, final SimpleString filterString, final boolean durable, - final boolean temp) throws ActiveMQException - { + final boolean temp) throws ActiveMQException { checkClosed(); - if (durable && temp) - { + if (durable && temp) { throw ActiveMQClientMessageBundle.BUNDLE.queueMisConfigured(); } startCall(); - try - { + try { sessionContext.createQueue(address, queueName, filterString, durable, temp); } - finally - { + finally { endCall(); } } - private void checkXA() throws XAException - { - if (!xa) - { + private void checkXA() throws XAException { + if (!xa) { ActiveMQClientLogger.LOGGER.sessionNotXA(); throw new XAException(XAException.XAER_RMFAIL); } } - private void checkClosed() throws ActiveMQException - { - if (closed || inClose) - { + private void checkClosed() throws ActiveMQException { + if (closed || inClose) { throw ActiveMQClientMessageBundle.BUNDLE.sessionClosed(); } } - private ClientConsumerInternal getConsumer(final ConsumerContext consumerContext) - { - synchronized (consumers) - { + private ClientConsumerInternal getConsumer(final ConsumerContext consumerContext) { + synchronized (consumers) { ClientConsumerInternal consumer = consumers.get(consumerContext); return consumer; } } - private void doCleanup(boolean failingOver) - { - if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) - { + private void doCleanup(boolean failingOver) { + if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) { ActiveMQClientLogger.LOGGER.debug("calling cleanup on " + this); } - synchronized (this) - { + synchronized (this) { closed = true; sessionContext.cleanup(); @@ -1776,19 +1499,16 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi sessionFactory.removeSession(this, failingOver); } - private void cleanUpChildren() throws ActiveMQException - { + private void cleanUpChildren() throws ActiveMQException { Set consumersClone = cloneConsumers(); - for (ClientConsumerInternal consumer : consumersClone) - { + for (ClientConsumerInternal consumer : consumersClone) { consumer.cleanUp(); } Set producersClone = cloneProducers(); - for (ClientProducerInternal producer : producersClone) - { + for (ClientProducerInternal producer : producersClone) { producer.cleanUp(); } } @@ -1798,12 +1518,10 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi * * @return */ - public Set cloneProducers() - { + public Set cloneProducers() { Set producersClone; - synchronized (producers) - { + synchronized (producers) { producersClone = new HashSet(producers); } return producersClone; @@ -1814,35 +1532,28 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi * * @return */ - public Set cloneConsumers() - { - synchronized (consumers) - { + public Set cloneConsumers() { + synchronized (consumers) { return new HashSet(consumers.values()); } } - private void closeChildren() throws ActiveMQException - { + private void closeChildren() throws ActiveMQException { Set consumersClone = cloneConsumers(); - for (ClientConsumer consumer : consumersClone) - { + for (ClientConsumer consumer : consumersClone) { consumer.close(); } Set producersClone = cloneProducers(); - for (ClientProducer producer : producersClone) - { + for (ClientProducer producer : producersClone) { producer.close(); } } - private void flushAcks() throws ActiveMQException - { - for (ClientConsumerInternal consumer : cloneConsumers()) - { + private void flushAcks() throws ActiveMQException { + for (ClientConsumerInternal consumer : cloneConsumers()) { consumer.flushAcks(); } } @@ -1857,8 +1568,7 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi * @param xid * @return */ - public static Object convert(Xid xid) - { + public static Object convert(Xid xid) { ActiveMQBuffer buffer = ActiveMQBuffers.dynamicBuffer(200); XidCodecSupport.encodeXid(xid, buffer); @@ -1867,52 +1577,40 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi return "xid=" + obj + ",clientXID=" + xid; } - private String convertTXFlag(final int flags) - { - if (flags == XAResource.TMSUSPEND) - { + private String convertTXFlag(final int flags) { + if (flags == XAResource.TMSUSPEND) { return "SESS_XA_SUSPEND"; } - else if (flags == XAResource.TMSUCCESS) - { + else if (flags == XAResource.TMSUCCESS) { return "TMSUCCESS"; } - else if (flags == XAResource.TMFAIL) - { + else if (flags == XAResource.TMFAIL) { return "TMFAIL"; } - else if (flags == XAResource.TMJOIN) - { + else if (flags == XAResource.TMJOIN) { return "TMJOIN"; } - else if (flags == XAResource.TMRESUME) - { + else if (flags == XAResource.TMRESUME) { return "TMRESUME"; } - else if (flags == XAResource.TMNOFLAGS) - { + else if (flags == XAResource.TMNOFLAGS) { // Don't need to flush since the previous end will have done this return "TMNOFLAGS"; } - else - { + else { return "XAER_INVAL(" + flags + ")"; } } @Override - public void setStopSignal() - { + public void setStopSignal() { mayAttemptToFailover = false; } @Override - public boolean isConfirmationWindowEnabled() - { - if (confirmationWindowWarning.disabled) - { - if (!confirmationWindowWarning.warningIssued.get()) - { + public boolean isConfirmationWindowEnabled() { + if (confirmationWindowWarning.disabled) { + if (!confirmationWindowWarning.warningIssued.get()) { ActiveMQClientLogger.LOGGER.confirmationWindowDisabledWarning(); confirmationWindowWarning.warningIssued.set(true); } @@ -1922,13 +1620,10 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi } @Override - public void scheduleConfirmation(final SendAcknowledgementHandler handler, final Message message) - { - executor.execute(new Runnable() - { + public void scheduleConfirmation(final SendAcknowledgementHandler handler, final Message message) { + executor.execute(new Runnable() { @Override - public void run() - { + public void run() { handler.sendAcknowledged(message); } }); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientSessionInternal.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientSessionInternal.java index 94696f7c65..3a8524501c 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientSessionInternal.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientSessionInternal.java @@ -25,8 +25,8 @@ import org.apache.activemq.artemis.api.core.client.SendAcknowledgementHandler; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; import org.apache.activemq.artemis.spi.core.remoting.ConsumerContext; -public interface ClientSessionInternal extends ClientSession -{ +public interface ClientSessionInternal extends ClientSession { + String getName(); void acknowledge(ClientConsumer consumer, Message message) throws ActiveMQException; @@ -51,9 +51,14 @@ public interface ClientSessionInternal extends ClientSession void handleReceiveMessage(ConsumerContext consumerID, ClientMessageInternal message) throws Exception; - void handleReceiveLargeMessage(ConsumerContext consumerID, ClientLargeMessageInternal clientLargeMessage, long largeMessageSize) throws Exception; + void handleReceiveLargeMessage(ConsumerContext consumerID, + ClientLargeMessageInternal clientLargeMessage, + long largeMessageSize) throws Exception; - void handleReceiveContinuation(ConsumerContext consumerID, byte[] chunk, int flowControlSize, boolean isContinues) throws Exception; + void handleReceiveContinuation(ConsumerContext consumerID, + byte[] chunk, + int flowControlSize, + boolean isContinues) throws Exception; void handleConsumerDisconnect(ConsumerContext consumerContext) throws ActiveMQException; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/CompressedLargeMessageControllerImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/CompressedLargeMessageControllerImpl.java index c616f6bcb1..1e93ced0af 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/CompressedLargeMessageControllerImpl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/CompressedLargeMessageControllerImpl.java @@ -33,50 +33,43 @@ import org.apache.activemq.artemis.utils.InflaterReader; import org.apache.activemq.artemis.utils.InflaterWriter; import org.apache.activemq.artemis.utils.UTF8Util; -final class CompressedLargeMessageControllerImpl implements LargeMessageController -{ +final class CompressedLargeMessageControllerImpl implements LargeMessageController { + private static final String OPERATION_NOT_SUPPORTED = "Operation not supported"; private final LargeMessageController bufferDelegate; - public CompressedLargeMessageControllerImpl(final LargeMessageController bufferDelegate) - { + public CompressedLargeMessageControllerImpl(final LargeMessageController bufferDelegate) { this.bufferDelegate = bufferDelegate; } /** * */ - public void discardUnusedPackets() - { + public void discardUnusedPackets() { bufferDelegate.discardUnusedPackets(); } /** * Add a buff to the List, or save it to the OutputStream if set */ - public void addPacket(byte[] chunk, int flowControlSize, boolean isContinues) - { + public void addPacket(byte[] chunk, int flowControlSize, boolean isContinues) { bufferDelegate.addPacket(chunk, flowControlSize, isContinues); } - public synchronized void cancel() - { + public synchronized void cancel() { bufferDelegate.cancel(); } - public synchronized void close() - { + public synchronized void close() { bufferDelegate.cancel(); } - public void setOutputStream(final OutputStream output) throws ActiveMQException - { + public void setOutputStream(final OutputStream output) throws ActiveMQException { bufferDelegate.setOutputStream(new InflaterWriter(output)); } - public synchronized void saveBuffer(final OutputStream output) throws ActiveMQException - { + public synchronized void saveBuffer(final OutputStream output) throws ActiveMQException { setOutputStream(output); waitCompletion(0); } @@ -84,31 +77,25 @@ final class CompressedLargeMessageControllerImpl implements LargeMessageControll /** * @param timeWait Milliseconds to Wait. 0 means forever */ - public synchronized boolean waitCompletion(final long timeWait) throws ActiveMQException - { + public synchronized boolean waitCompletion(final long timeWait) throws ActiveMQException { return bufferDelegate.waitCompletion(timeWait); } @Override - public int capacity() - { + public int capacity() { return -1; } DataInputStream dataInput = null; - private DataInputStream getStream() - { - if (dataInput == null) - { - try - { + private DataInputStream getStream() { + if (dataInput == null) { + try { InputStream input = new ActiveMQBufferInputStream(bufferDelegate); dataInput = new DataInputStream(new InflaterReader(input)); } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } @@ -116,509 +103,408 @@ final class CompressedLargeMessageControllerImpl implements LargeMessageControll return dataInput; } - private void positioningNotSupported() - { + private void positioningNotSupported() { throw new IllegalStateException("Position not supported over compressed large messages"); } - public byte readByte() - { - try - { + public byte readByte() { + try { return getStream().readByte(); } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } @Override - public byte getByte(final int index) - { + public byte getByte(final int index) { positioningNotSupported(); return 0; } @Override - public void getBytes(final int index, final ActiveMQBuffer dst, final int dstIndex, final int length) - { + public void getBytes(final int index, final ActiveMQBuffer dst, final int dstIndex, final int length) { positioningNotSupported(); } @Override - public void getBytes(final int index, final byte[] dst, final int dstIndex, final int length) - { + public void getBytes(final int index, final byte[] dst, final int dstIndex, final int length) { positioningNotSupported(); } @Override - public void getBytes(final int index, final ByteBuffer dst) - { + public void getBytes(final int index, final ByteBuffer dst) { positioningNotSupported(); } @Override - public int getInt(final int index) - { + public int getInt(final int index) { positioningNotSupported(); return 0; } @Override - public long getLong(final int index) - { + public long getLong(final int index) { positioningNotSupported(); return 0; } @Override - public short getShort(final int index) - { + public short getShort(final int index) { positioningNotSupported(); return 0; } @Override - public void setByte(final int index, final byte value) - { + public void setByte(final int index, final byte value) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } @Override - public void setBytes(final int index, final ActiveMQBuffer src, final int srcIndex, final int length) - { + public void setBytes(final int index, final ActiveMQBuffer src, final int srcIndex, final int length) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } @Override - public void setBytes(final int index, final byte[] src, final int srcIndex, final int length) - { + public void setBytes(final int index, final byte[] src, final int srcIndex, final int length) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } @Override - public void setBytes(final int index, final ByteBuffer src) - { + public void setBytes(final int index, final ByteBuffer src) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } @Override - public void setInt(final int index, final int value) - { + public void setInt(final int index, final int value) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } @Override - public void setLong(final int index, final long value) - { + public void setLong(final int index, final long value) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } @Override - public void setShort(final int index, final short value) - { + public void setShort(final int index, final short value) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } @Override - public ByteBuffer toByteBuffer(final int index, final int length) - { + public ByteBuffer toByteBuffer(final int index, final int length) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public int readerIndex() - { + public int readerIndex() { return 0; } - public void readerIndex(final int readerIndex) - { + public void readerIndex(final int readerIndex) { // TODO } - public int writerIndex() - { + public int writerIndex() { // TODO return 0; } - public long getSize() - { + public long getSize() { return this.bufferDelegate.getSize(); } - public void writerIndex(final int writerIndex) - { + public void writerIndex(final int writerIndex) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public void setIndex(final int readerIndex, final int writerIndex) - { + public void setIndex(final int readerIndex, final int writerIndex) { positioningNotSupported(); } - public void clear() - { + public void clear() { } - public boolean readable() - { + public boolean readable() { return true; } - public boolean writable() - { + public boolean writable() { return false; } - public int readableBytes() - { + public int readableBytes() { return 1; } - public int writableBytes() - { + public int writableBytes() { return 0; } - public void markReaderIndex() - { + public void markReaderIndex() { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public void resetReaderIndex() - { + public void resetReaderIndex() { // TODO: reset positioning if possible } - public void markWriterIndex() - { + public void markWriterIndex() { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public void resetWriterIndex() - { + public void resetWriterIndex() { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public void discardReadBytes() - { + public void discardReadBytes() { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public short getUnsignedByte(final int index) - { + public short getUnsignedByte(final int index) { return (short) (getByte(index) & 0xFF); } - public int getUnsignedShort(final int index) - { + public int getUnsignedShort(final int index) { return getShort(index) & 0xFFFF; } - public long getUnsignedInt(final int index) - { + public long getUnsignedInt(final int index) { return getInt(index) & 0xFFFFFFFFL; } - public void getBytes(int index, final byte[] dst) - { + public void getBytes(int index, final byte[] dst) { // TODO: optimize this by using System.arraycopy - for (int i = 0; i < dst.length; i++) - { + for (int i = 0; i < dst.length; i++) { dst[i] = getByte(index++); } } - public void getBytes(final int index, final ActiveMQBuffer dst) - { + public void getBytes(final int index, final ActiveMQBuffer dst) { getBytes(index, dst, dst.writableBytes()); } - public void getBytes(final int index, final ActiveMQBuffer dst, final int length) - { - if (length > dst.writableBytes()) - { + public void getBytes(final int index, final ActiveMQBuffer dst, final int length) { + if (length > dst.writableBytes()) { throw new IndexOutOfBoundsException(); } getBytes(index, dst, dst.writerIndex(), length); dst.writerIndex(dst.writerIndex() + length); } - public void setBytes(final int index, final byte[] src) - { + public void setBytes(final int index, final byte[] src) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public void setBytes(final int index, final ActiveMQBuffer src) - { + public void setBytes(final int index, final ActiveMQBuffer src) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public void setBytes(final int index, final ActiveMQBuffer src, final int length) - { + public void setBytes(final int index, final ActiveMQBuffer src, final int length) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public short readUnsignedByte() - { - try - { + public short readUnsignedByte() { + try { return (short) getStream().readUnsignedByte(); } - catch (Exception e) - { + catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } - public short readShort() - { - try - { + public short readShort() { + try { return getStream().readShort(); } - catch (Exception e) - { + catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } - public int readUnsignedShort() - { - try - { + public int readUnsignedShort() { + try { return getStream().readUnsignedShort(); } - catch (Exception e) - { + catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } - public int readInt() - { - try - { + public int readInt() { + try { return getStream().readInt(); } - catch (Exception e) - { + catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } - public long readUnsignedInt() - { + public long readUnsignedInt() { return readInt() & 0xFFFFFFFFL; } - public long readLong() - { - try - { + public long readLong() { + try { return getStream().readLong(); } - catch (Exception e) - { + catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } - public void readBytes(final byte[] dst, final int dstIndex, final int length) - { - try - { + public void readBytes(final byte[] dst, final int dstIndex, final int length) { + try { int nReadBytes = getStream().read(dst, dstIndex, length); - if (nReadBytes < length) - { + if (nReadBytes < length) { ActiveMQClientLogger.LOGGER.compressedLargeMessageError(length, nReadBytes); } } - catch (Exception e) - { + catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } - public void readBytes(final byte[] dst) - { + public void readBytes(final byte[] dst) { readBytes(dst, 0, dst.length); } - public void readBytes(final ActiveMQBuffer dst) - { + public void readBytes(final ActiveMQBuffer dst) { readBytes(dst, dst.writableBytes()); } - public void readBytes(final ActiveMQBuffer dst, final int length) - { - if (length > dst.writableBytes()) - { + public void readBytes(final ActiveMQBuffer dst, final int length) { + if (length > dst.writableBytes()) { throw new IndexOutOfBoundsException(); } readBytes(dst, dst.writerIndex(), length); dst.writerIndex(dst.writerIndex() + length); } - public void readBytes(final ActiveMQBuffer dst, final int dstIndex, final int length) - { + public void readBytes(final ActiveMQBuffer dst, final int dstIndex, final int length) { byte[] destBytes = new byte[length]; readBytes(destBytes); dst.setBytes(dstIndex, destBytes); } - public void readBytes(final ByteBuffer dst) - { + public void readBytes(final ByteBuffer dst) { byte[] bytesToGet = new byte[dst.remaining()]; readBytes(bytesToGet); dst.put(bytesToGet); } - public void skipBytes(final int length) - { + public void skipBytes(final int length) { - try - { - for (int i = 0; i < length; i++) - { + try { + for (int i = 0; i < length; i++) { getStream().read(); } } - catch (Exception e) - { + catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } - public void writeByte(final byte value) - { + public void writeByte(final byte value) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public void writeShort(final short value) - { + public void writeShort(final short value) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public void writeInt(final int value) - { + public void writeInt(final int value) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public void writeLong(final long value) - { + public void writeLong(final long value) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public void writeBytes(final byte[] src, final int srcIndex, final int length) - { + public void writeBytes(final byte[] src, final int srcIndex, final int length) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public void writeBytes(final byte[] src) - { + public void writeBytes(final byte[] src) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public void writeBytes(final ActiveMQBuffer src, final int length) - { + public void writeBytes(final ActiveMQBuffer src, final int length) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public void writeBytes(final ByteBuffer src) - { + public void writeBytes(final ByteBuffer src) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public ByteBuffer toByteBuffer() - { + public ByteBuffer toByteBuffer() { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public Object getUnderlyingBuffer() - { + public Object getUnderlyingBuffer() { return this; } @Override - public boolean readBoolean() - { + public boolean readBoolean() { return readByte() != 0; } @Override - public char readChar() - { + public char readChar() { return (char) readShort(); } - public char getChar(final int index) - { + public char getChar(final int index) { return (char) getShort(index); } - public double getDouble(final int index) - { + public double getDouble(final int index) { return Double.longBitsToDouble(getLong(index)); } - public float getFloat(final int index) - { + public float getFloat(final int index) { return Float.intBitsToFloat(getInt(index)); } - public ActiveMQBuffer readBytes(final int length) - { + public ActiveMQBuffer readBytes(final int length) { byte[] bytesToGet = new byte[length]; readBytes(bytesToGet); return ActiveMQBuffers.wrappedBuffer(bytesToGet); } @Override - public double readDouble() - { + public double readDouble() { return Double.longBitsToDouble(readLong()); } @Override - public float readFloat() - { + public float readFloat() { return Float.intBitsToFloat(readInt()); } @Override - public SimpleString readNullableSimpleString() - { + public SimpleString readNullableSimpleString() { int b = readByte(); - if (b == DataConstants.NULL) - { + if (b == DataConstants.NULL) { return null; } - else - { + else { return readSimpleString(); } } @Override - public String readNullableString() - { + public String readNullableString() { int b = readByte(); - if (b == DataConstants.NULL) - { + if (b == DataConstants.NULL) { return null; } - else - { + else { return readString(); } } @Override - public SimpleString readSimpleString() - { + public SimpleString readSimpleString() { int len = readInt(); byte[] data = new byte[len]; readBytes(data); @@ -626,145 +512,119 @@ final class CompressedLargeMessageControllerImpl implements LargeMessageControll } @Override - public String readString() - { + public String readString() { int len = readInt(); - if (len < 9) - { + if (len < 9) { char[] chars = new char[len]; - for (int i = 0; i < len; i++) - { + for (int i = 0; i < len; i++) { chars[i] = (char) readShort(); } return new String(chars); } - else if (len < 0xfff) - { + else if (len < 0xfff) { return readUTF(); } - else - { + else { return readSimpleString().toString(); } } @Override - public String readUTF() - { + public String readUTF() { return UTF8Util.readUTF(this); } @Override - public void writeBoolean(final boolean val) - { + public void writeBoolean(final boolean val) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } @Override - public void writeChar(final char val) - { + public void writeChar(final char val) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } @Override - public void writeDouble(final double val) - { + public void writeDouble(final double val) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } @Override - public void writeFloat(final float val) - { + public void writeFloat(final float val) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } @Override - public void writeNullableSimpleString(final SimpleString val) - { + public void writeNullableSimpleString(final SimpleString val) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } @Override - public void writeNullableString(final String val) - { + public void writeNullableString(final String val) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } @Override - public void writeSimpleString(final SimpleString val) - { + public void writeSimpleString(final SimpleString val) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } @Override - public void writeString(final String val) - { + public void writeString(final String val) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } @Override - public void writeUTF(final String utf) - { + public void writeUTF(final String utf) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public ActiveMQBuffer copy() - { + public ActiveMQBuffer copy() { throw new UnsupportedOperationException(); } - public ActiveMQBuffer slice(final int index, final int length) - { + public ActiveMQBuffer slice(final int index, final int length) { throw new UnsupportedOperationException(); } // Inner classes ------------------------------------------------- - public ByteBuf byteBuf() - { + public ByteBuf byteBuf() { return null; } - public ActiveMQBuffer copy(final int index, final int length) - { + public ActiveMQBuffer copy(final int index, final int length) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public ActiveMQBuffer duplicate() - { + public ActiveMQBuffer duplicate() { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public ActiveMQBuffer readSlice(final int length) - { + public ActiveMQBuffer readSlice(final int length) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public void setChar(final int index, final char value) - { + public void setChar(final int index, final char value) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public void setDouble(final int index, final double value) - { + public void setDouble(final int index, final double value) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public void setFloat(final int index, final float value) - { + public void setFloat(final int index, final float value) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public ActiveMQBuffer slice() - { + public ActiveMQBuffer slice() { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } - public void writeBytes(final ActiveMQBuffer src, final int srcIndex, final int length) - { + public void writeBytes(final ActiveMQBuffer src, final int srcIndex, final int length) { throw new IllegalAccessError(OPERATION_NOT_SUPPORTED); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/DelegatingSession.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/DelegatingSession.java index 3c81c8eaea..a4296bce23 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/DelegatingSession.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/DelegatingSession.java @@ -42,8 +42,8 @@ import org.apache.activemq.artemis.utils.ConcurrentHashSet; * We wrap the real session, so we can add a finalizer on this and close the session * on GC if it has not already been closed */ -public class DelegatingSession implements ClientSessionInternal -{ +public class DelegatingSession implements ClientSessionInternal { + private final ClientSessionInternal session; private final Exception creationStack; @@ -54,29 +54,23 @@ public class DelegatingSession implements ClientSessionInternal public static volatile boolean debug; - public static void dumpSessionCreationStacks() - { + public static void dumpSessionCreationStacks() { ActiveMQClientLogger.LOGGER.dumpingSessionStacks(); - for (DelegatingSession session : DelegatingSession.sessions) - { + for (DelegatingSession session : DelegatingSession.sessions) { ActiveMQClientLogger.LOGGER.dumpingSessionStack(session.creationStack); } } - - public ClientSessionInternal getInternalSession() - { + public ClientSessionInternal getInternalSession() { return session; } @Override - protected void finalize() throws Throwable - { + protected void finalize() throws Throwable { // In some scenarios we have seen the JDK finalizing the DelegatingSession while the call to session.close() was still in progress // - if (!closed && !session.isClosed()) - { + if (!closed && !session.isClosed()) { ActiveMQClientLogger.LOGGER.clientSessionNotClosed(creationStack, System.identityHashCode(this)); close(); @@ -85,87 +79,71 @@ public class DelegatingSession implements ClientSessionInternal super.finalize(); } - public DelegatingSession(final ClientSessionInternal session) - { + public DelegatingSession(final ClientSessionInternal session) { this.session = session; creationStack = new Exception(); - if (DelegatingSession.debug) - { + if (DelegatingSession.debug) { DelegatingSession.sessions.add(this); } } - public boolean isClosing() - { + public boolean isClosing() { return session.isClosing(); } - public void acknowledge(final ClientConsumer consumer, final Message message) throws ActiveMQException - { + public void acknowledge(final ClientConsumer consumer, final Message message) throws ActiveMQException { session.acknowledge(consumer, message); } - public void individualAcknowledge(final ClientConsumer consumer, final Message message) throws ActiveMQException - { + public void individualAcknowledge(final ClientConsumer consumer, final Message message) throws ActiveMQException { session.individualAcknowledge(consumer, message); } - public void addConsumer(final ClientConsumerInternal consumer) - { + public void addConsumer(final ClientConsumerInternal consumer) { session.addConsumer(consumer); } - public void addFailureListener(final SessionFailureListener listener) - { + public void addFailureListener(final SessionFailureListener listener) { session.addFailureListener(listener); } - public void addFailoverListener(FailoverEventListener listener) - { + public void addFailoverListener(FailoverEventListener listener) { session.addFailoverListener(listener); } - public void addProducer(final ClientProducerInternal producer) - { + public void addProducer(final ClientProducerInternal producer) { session.addProducer(producer); } - public AddressQuery addressQuery(final SimpleString address) throws ActiveMQException - { + public AddressQuery addressQuery(final SimpleString address) throws ActiveMQException { return session.addressQuery(address); } - public void cleanUp(boolean failingOver) throws ActiveMQException - { + public void cleanUp(boolean failingOver) throws ActiveMQException { session.cleanUp(failingOver); } - public void close() throws ActiveMQException - { + public void close() throws ActiveMQException { closed = true; - if (DelegatingSession.debug) - { + if (DelegatingSession.debug) { DelegatingSession.sessions.remove(this); } session.close(); } - public void commit() throws ActiveMQException - { + public void commit() throws ActiveMQException { session.commit(); } - public void commit(final Xid xid, final boolean onePhase) throws XAException - { + public void commit(final Xid xid, final boolean onePhase) throws XAException { session.commit(xid, onePhase); } - public ClientMessage createMessage(final boolean durable) - { + public ClientMessage createMessage(final boolean durable) { return session.createMessage(durable); } @@ -173,20 +151,17 @@ public class DelegatingSession implements ClientSessionInternal final boolean durable, final long expiration, final long timestamp, - final byte priority) - { + final byte priority) { return session.createMessage(type, durable, expiration, timestamp, priority); } - public ClientMessage createMessage(final byte type, final boolean durable) - { + public ClientMessage createMessage(final byte type, final boolean durable) { return session.createMessage(type, durable); } public ClientConsumer createConsumer(final SimpleString queueName, final SimpleString filterString, - final boolean browseOnly) throws ActiveMQException - { + final boolean browseOnly) throws ActiveMQException { return session.createConsumer(queueName, filterString, browseOnly); } @@ -194,23 +169,22 @@ public class DelegatingSession implements ClientSessionInternal final SimpleString filterString, final int windowSize, final int maxRate, - final boolean browseOnly) throws ActiveMQException - { + final boolean browseOnly) throws ActiveMQException { return session.createConsumer(queueName, filterString, windowSize, maxRate, browseOnly); } - public ClientConsumer createConsumer(final SimpleString queueName, final SimpleString filterString) throws ActiveMQException - { + public ClientConsumer createConsumer(final SimpleString queueName, + final SimpleString filterString) throws ActiveMQException { return session.createConsumer(queueName, filterString); } - public ClientConsumer createConsumer(final SimpleString queueName) throws ActiveMQException - { + public ClientConsumer createConsumer(final SimpleString queueName) throws ActiveMQException { return session.createConsumer(queueName); } - public ClientConsumer createConsumer(final String queueName, final String filterString, final boolean browseOnly) throws ActiveMQException - { + public ClientConsumer createConsumer(final String queueName, + final String filterString, + final boolean browseOnly) throws ActiveMQException { return session.createConsumer(queueName, filterString, browseOnly); } @@ -218,439 +192,375 @@ public class DelegatingSession implements ClientSessionInternal final String filterString, final int windowSize, final int maxRate, - final boolean browseOnly) throws ActiveMQException - { + final boolean browseOnly) throws ActiveMQException { return session.createConsumer(queueName, filterString, windowSize, maxRate, browseOnly); } - public ClientConsumer createConsumer(final String queueName, final String filterString) throws ActiveMQException - { + public ClientConsumer createConsumer(final String queueName, final String filterString) throws ActiveMQException { return session.createConsumer(queueName, filterString); } - public ClientConsumer createConsumer(final String queueName) throws ActiveMQException - { + public ClientConsumer createConsumer(final String queueName) throws ActiveMQException { return session.createConsumer(queueName); } - public ClientConsumer createConsumer(final SimpleString queueName, final boolean browseOnly) throws ActiveMQException - { + public ClientConsumer createConsumer(final SimpleString queueName, + final boolean browseOnly) throws ActiveMQException { return session.createConsumer(queueName, browseOnly); } - public ClientConsumer createConsumer(final String queueName, final boolean browseOnly) throws ActiveMQException - { + public ClientConsumer createConsumer(final String queueName, final boolean browseOnly) throws ActiveMQException { return session.createConsumer(queueName, browseOnly); } - public ClientProducer createProducer() throws ActiveMQException - { + public ClientProducer createProducer() throws ActiveMQException { return session.createProducer(); } - public ClientProducer createProducer(final SimpleString address, final int rate) throws ActiveMQException - { + public ClientProducer createProducer(final SimpleString address, final int rate) throws ActiveMQException { return session.createProducer(address, rate); } - public ClientProducer createProducer(final SimpleString address) throws ActiveMQException - { + public ClientProducer createProducer(final SimpleString address) throws ActiveMQException { return session.createProducer(address); } - public ClientProducer createProducer(final String address) throws ActiveMQException - { + public ClientProducer createProducer(final String address) throws ActiveMQException { return session.createProducer(address); } - public void createQueue(final String address, final String queueName) throws ActiveMQException - { + public void createQueue(final String address, final String queueName) throws ActiveMQException { session.createQueue(address, queueName); } - public void createQueue(final SimpleString address, final SimpleString queueName) throws ActiveMQException - { + public void createQueue(final SimpleString address, final SimpleString queueName) throws ActiveMQException { session.createQueue(address, queueName); } - public void createQueue(final SimpleString address, final SimpleString queueName, final boolean durable) throws ActiveMQException - { + public void createQueue(final SimpleString address, + final SimpleString queueName, + final boolean durable) throws ActiveMQException { session.createQueue(address, queueName, durable); } @Override - public void createSharedQueue(SimpleString address, SimpleString queueName, boolean durable) throws ActiveMQException - { + public void createSharedQueue(SimpleString address, + SimpleString queueName, + boolean durable) throws ActiveMQException { session.createSharedQueue(address, queueName, durable); } @Override - public void createSharedQueue(SimpleString address, SimpleString queueName, SimpleString filter, boolean durable) throws ActiveMQException - { + public void createSharedQueue(SimpleString address, + SimpleString queueName, + SimpleString filter, + boolean durable) throws ActiveMQException { session.createSharedQueue(address, queueName, filter, durable); } public void createQueue(final SimpleString address, final SimpleString queueName, final SimpleString filterString, - final boolean durable) throws ActiveMQException - { + final boolean durable) throws ActiveMQException { session.createQueue(address, queueName, filterString, durable); } - public void createQueue(final String address, final String queueName, final boolean durable) throws ActiveMQException - { + public void createQueue(final String address, + final String queueName, + final boolean durable) throws ActiveMQException { session.createQueue(address, queueName, durable); } public void createQueue(final String address, final String queueName, final String filterString, - final boolean durable) throws ActiveMQException - { + final boolean durable) throws ActiveMQException { session.createQueue(address, queueName, filterString, durable); } - public void createTemporaryQueue(final SimpleString address, final SimpleString queueName, final SimpleString filter) throws ActiveMQException - { + public void createTemporaryQueue(final SimpleString address, + final SimpleString queueName, + final SimpleString filter) throws ActiveMQException { session.createTemporaryQueue(address, queueName, filter); } - public void createTemporaryQueue(final SimpleString address, final SimpleString queueName) throws ActiveMQException - { + public void createTemporaryQueue(final SimpleString address, final SimpleString queueName) throws ActiveMQException { session.createTemporaryQueue(address, queueName); } - public void createTemporaryQueue(final String address, final String queueName, final String filter) throws ActiveMQException - { + public void createTemporaryQueue(final String address, + final String queueName, + final String filter) throws ActiveMQException { session.createTemporaryQueue(address, queueName, filter); } - public void createTemporaryQueue(final String address, final String queueName) throws ActiveMQException - { + public void createTemporaryQueue(final String address, final String queueName) throws ActiveMQException { session.createTemporaryQueue(address, queueName); } - public void deleteQueue(final SimpleString queueName) throws ActiveMQException - { + public void deleteQueue(final SimpleString queueName) throws ActiveMQException { session.deleteQueue(queueName); } - public void deleteQueue(final String queueName) throws ActiveMQException - { + public void deleteQueue(final String queueName) throws ActiveMQException { session.deleteQueue(queueName); } - public void end(final Xid xid, final int flags) throws XAException - { + public void end(final Xid xid, final int flags) throws XAException { session.end(xid, flags); } - public void expire(final ClientConsumer consumer, final Message message) throws ActiveMQException - { + public void expire(final ClientConsumer consumer, final Message message) throws ActiveMQException { session.expire(consumer, message); } - public void forget(final Xid xid) throws XAException - { + public void forget(final Xid xid) throws XAException { session.forget(xid); } - public RemotingConnection getConnection() - { + public RemotingConnection getConnection() { return session.getConnection(); } - public int getMinLargeMessageSize() - { + public int getMinLargeMessageSize() { return session.getMinLargeMessageSize(); } - public String getName() - { + public String getName() { return session.getName(); } - public int getTransactionTimeout() throws XAException - { + public int getTransactionTimeout() throws XAException { return session.getTransactionTimeout(); } - public int getVersion() - { + public int getVersion() { return session.getVersion(); } - public XAResource getXAResource() - { + public XAResource getXAResource() { return session.getXAResource(); } - public void preHandleFailover(RemotingConnection connection) - { + public void preHandleFailover(RemotingConnection connection) { session.preHandleFailover(connection); } - public void handleFailover(final RemotingConnection backupConnection, ActiveMQException cause) - { + public void handleFailover(final RemotingConnection backupConnection, ActiveMQException cause) { session.handleFailover(backupConnection, cause); } @Override - public void handleReceiveMessage(ConsumerContext consumerID, ClientMessageInternal message) throws Exception - { + public void handleReceiveMessage(ConsumerContext consumerID, ClientMessageInternal message) throws Exception { session.handleReceiveMessage(consumerID, message); } @Override - public void handleReceiveLargeMessage(ConsumerContext consumerID, ClientLargeMessageInternal clientLargeMessage, long largeMessageSize) throws Exception - { + public void handleReceiveLargeMessage(ConsumerContext consumerID, + ClientLargeMessageInternal clientLargeMessage, + long largeMessageSize) throws Exception { session.handleReceiveLargeMessage(consumerID, clientLargeMessage, largeMessageSize); } @Override - public void handleReceiveContinuation(ConsumerContext consumerID, byte[] chunk, int flowControlSize, boolean isContinues) throws Exception - { + public void handleReceiveContinuation(ConsumerContext consumerID, + byte[] chunk, + int flowControlSize, + boolean isContinues) throws Exception { session.handleReceiveContinuation(consumerID, chunk, flowControlSize, isContinues); } @Override - public void handleConsumerDisconnect(ConsumerContext consumerContext) throws ActiveMQException - { + public void handleConsumerDisconnect(ConsumerContext consumerContext) throws ActiveMQException { session.handleConsumerDisconnect(consumerContext); } - public boolean isAutoCommitAcks() - { + public boolean isAutoCommitAcks() { return session.isAutoCommitAcks(); } - public boolean isAutoCommitSends() - { + public boolean isAutoCommitSends() { return session.isAutoCommitSends(); } - public boolean isBlockOnAcknowledge() - { + public boolean isBlockOnAcknowledge() { return session.isBlockOnAcknowledge(); } - public boolean isCacheLargeMessageClient() - { + public boolean isCacheLargeMessageClient() { return session.isCacheLargeMessageClient(); } - public boolean isClosed() - { + public boolean isClosed() { return session.isClosed(); } - public boolean isSameRM(final XAResource xares) throws XAException - { + public boolean isSameRM(final XAResource xares) throws XAException { return session.isSameRM(xares); } - public boolean isXA() - { + public boolean isXA() { return session.isXA(); } - public int prepare(final Xid xid) throws XAException - { + public int prepare(final Xid xid) throws XAException { return session.prepare(xid); } - public QueueQuery queueQuery(final SimpleString queueName) throws ActiveMQException - { + public QueueQuery queueQuery(final SimpleString queueName) throws ActiveMQException { return session.queueQuery(queueName); } - public Xid[] recover(final int flag) throws XAException - { + public Xid[] recover(final int flag) throws XAException { return session.recover(flag); } - public void removeConsumer(final ClientConsumerInternal consumer) throws ActiveMQException - { + public void removeConsumer(final ClientConsumerInternal consumer) throws ActiveMQException { session.removeConsumer(consumer); } - public boolean removeFailureListener(final SessionFailureListener listener) - { + public boolean removeFailureListener(final SessionFailureListener listener) { return session.removeFailureListener(listener); } - public boolean removeFailoverListener(FailoverEventListener listener) - { + public boolean removeFailoverListener(FailoverEventListener listener) { return session.removeFailoverListener(listener); } - public void removeProducer(final ClientProducerInternal producer) - { + public void removeProducer(final ClientProducerInternal producer) { session.removeProducer(producer); } - public void rollback() throws ActiveMQException - { + public void rollback() throws ActiveMQException { session.rollback(); } - public boolean isRollbackOnly() - { + public boolean isRollbackOnly() { return session.isRollbackOnly(); } - public void rollback(final boolean considerLastMessageAsDelivered) throws ActiveMQException - { + public void rollback(final boolean considerLastMessageAsDelivered) throws ActiveMQException { session.rollback(considerLastMessageAsDelivered); } - public void rollback(final Xid xid) throws XAException - { + public void rollback(final Xid xid) throws XAException { session.rollback(xid); } - public DelegatingSession setSendAcknowledgementHandler(final SendAcknowledgementHandler handler) - { + public DelegatingSession setSendAcknowledgementHandler(final SendAcknowledgementHandler handler) { session.setSendAcknowledgementHandler(handler); return this; } - public boolean setTransactionTimeout(final int seconds) throws XAException - { + public boolean setTransactionTimeout(final int seconds) throws XAException { return session.setTransactionTimeout(seconds); } - public void resetIfNeeded() throws ActiveMQException - { + public void resetIfNeeded() throws ActiveMQException { session.resetIfNeeded(); } - public DelegatingSession start() throws ActiveMQException - { + public DelegatingSession start() throws ActiveMQException { session.start(); return this; } - public void start(final Xid xid, final int flags) throws XAException - { + public void start(final Xid xid, final int flags) throws XAException { session.start(xid, flags); } - public void stop() throws ActiveMQException - { + public void stop() throws ActiveMQException { session.stop(); } - public ClientSessionFactory getSessionFactory() - { + public ClientSessionFactory getSessionFactory() { return session.getSessionFactory(); } - public void setForceNotSameRM(final boolean force) - { + public void setForceNotSameRM(final boolean force) { session.setForceNotSameRM(force); } - public void workDone() - { + public void workDone() { session.workDone(); } - public void sendProducerCreditsMessage(final int credits, final SimpleString address) - { + public void sendProducerCreditsMessage(final int credits, final SimpleString address) { session.sendProducerCreditsMessage(credits, address); } - public ClientProducerCredits getCredits(final SimpleString address, final boolean anon) - { + public ClientProducerCredits getCredits(final SimpleString address, final boolean anon) { return session.getCredits(address, anon); } - public void returnCredits(final SimpleString address) - { + public void returnCredits(final SimpleString address) { session.returnCredits(address); } - public void handleReceiveProducerCredits(final SimpleString address, final int credits) - { + public void handleReceiveProducerCredits(final SimpleString address, final int credits) { session.handleReceiveProducerCredits(address, credits); } - public void handleReceiveProducerFailCredits(final SimpleString address, final int credits) - { + public void handleReceiveProducerFailCredits(final SimpleString address, final int credits) { session.handleReceiveProducerFailCredits(address, credits); } - public ClientProducerCreditManager getProducerCreditManager() - { + public ClientProducerCreditManager getProducerCreditManager() { return session.getProducerCreditManager(); } - public void setAddress(Message message, SimpleString address) - { + public void setAddress(Message message, SimpleString address) { session.setAddress(message, address); } - public void setPacketSize(int packetSize) - { + public void setPacketSize(int packetSize) { session.setPacketSize(packetSize); } - public void addMetaData(String key, String data) throws ActiveMQException - { + public void addMetaData(String key, String data) throws ActiveMQException { session.addMetaData(key, data); } - public boolean isCompressLargeMessages() - { + public boolean isCompressLargeMessages() { return session.isCompressLargeMessages(); } @Override - public String toString() - { + public String toString() { return "DelegatingSession [session=" + session + "]"; } @Override - public void addUniqueMetaData(String key, String data) throws ActiveMQException - { + public void addUniqueMetaData(String key, String data) throws ActiveMQException { session.addUniqueMetaData(key, data); } - public void startCall() - { + public void startCall() { session.startCall(); } - public void endCall() - { + public void endCall() { session.endCall(); } @Override - public void setStopSignal() - { + public void setStopSignal() { session.setStopSignal(); } @Override - public boolean isConfirmationWindowEnabled() - { + public boolean isConfirmationWindowEnabled() { return session.isConfirmationWindowEnabled(); } @Override - public void scheduleConfirmation(SendAcknowledgementHandler handler, Message msg) - { + public void scheduleConfirmation(SendAcknowledgementHandler handler, Message msg) { session.scheduleConfirmation(handler, msg); } @Override - public String getNodeId() - { + public String getNodeId() { return session.getNodeId(); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/LargeMessageController.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/LargeMessageController.java index 141c0c585a..ced3028e4b 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/LargeMessageController.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/LargeMessageController.java @@ -21,11 +21,10 @@ import java.io.OutputStream; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.ActiveMQException; -public interface LargeMessageController extends ActiveMQBuffer -{ +public interface LargeMessageController extends ActiveMQBuffer { + /** * Returns the size of this buffer. - */ long getSize(); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/LargeMessageControllerImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/LargeMessageControllerImpl.java index d3b2d1a477..7f44cff7ad 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/LargeMessageControllerImpl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/LargeMessageControllerImpl.java @@ -48,8 +48,7 @@ import org.apache.activemq.artemis.utils.UTF8Util; * packets until they are read using the ChannelBuffer interface, or the setOutputStream or * saveStream are called. */ -public class LargeMessageControllerImpl implements LargeMessageController -{ +public class LargeMessageControllerImpl implements LargeMessageController { // Constants ----------------------------------------------------- private static final String READ_ONLY_ERROR_MESSAGE = "This is a read-only buffer, setOperations are not supported"; @@ -100,16 +99,14 @@ public class LargeMessageControllerImpl implements LargeMessageController public LargeMessageControllerImpl(final ClientConsumerInternal consumerInternal, final long totalSize, - final long readTimeout) - { + final long readTimeout) { this(consumerInternal, totalSize, readTimeout, null); } public LargeMessageControllerImpl(final ClientConsumerInternal consumerInternal, final long totalSize, final long readTimeout, - final File cachedFile) - { + final File cachedFile) { this(consumerInternal, totalSize, readTimeout, cachedFile, 10 * 1024); } @@ -117,17 +114,14 @@ public class LargeMessageControllerImpl implements LargeMessageController final long totalSize, final long readTimeout, final File cachedFile, - final int bufferSize) - { + final int bufferSize) { this.consumerInternal = consumerInternal; this.readTimeout = readTimeout; this.totalSize = totalSize; - if (cachedFile == null) - { + if (cachedFile == null) { fileCache = null; } - else - { + else { fileCache = new FileCache(cachedFile); } this.bufferSize = bufferSize; @@ -135,22 +129,18 @@ public class LargeMessageControllerImpl implements LargeMessageController // Public -------------------------------------------------------- - public void setLocal(boolean local) - { + public void setLocal(boolean local) { this.local = local; } - public void discardUnusedPackets() - { - if (outStream == null) - { - if (local) return; - try - { + public void discardUnusedPackets() { + if (outStream == null) { + if (local) + return; + try { checkForPacket(totalSize - 1); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } } @@ -159,24 +149,18 @@ public class LargeMessageControllerImpl implements LargeMessageController * TODO: move this to ConsumerContext as large message is a protocol specific thing * Add a buff to the List, or save it to the OutputStream if set */ - public void addPacket(byte[] chunk, int flowControlSize, boolean isContinues) - { + public void addPacket(byte[] chunk, int flowControlSize, boolean isContinues) { int flowControlCredit = 0; - synchronized (this) - { + synchronized (this) { packetAdded = true; - if (outStream != null) - { - try - { - if (!isContinues) - { + if (outStream != null) { + try { + if (!isContinues) { streamEnded = true; } - if (fileCache != null) - { + if (fileCache != null) { fileCache.cachePackage(chunk); } @@ -186,70 +170,55 @@ public class LargeMessageControllerImpl implements LargeMessageController notifyAll(); - if (streamEnded) - { + if (streamEnded) { outStream.close(); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQClientLogger.LOGGER.errorAddingPacket(e); handledException = e; } } - else - { - if (fileCache != null) - { - try - { + else { + if (fileCache != null) { + try { fileCache.cachePackage(chunk); } - catch (Exception e) - { + catch (Exception e) { ActiveMQClientLogger.LOGGER.errorAddingPacket(e); handledException = e; } } - largeMessageData.offer(new LargeData(chunk, flowControlSize, isContinues)); } } - if (flowControlCredit != 0) - { - try - { + if (flowControlCredit != 0) { + try { consumerInternal.flowControl(flowControlCredit, !isContinues); } - catch (Exception e) - { + catch (Exception e) { ActiveMQClientLogger.LOGGER.errorAddingPacket(e); handledException = e; } } } - public void cancel() - { + public void cancel() { this.handledException = ActiveMQClientMessageBundle.BUNDLE.largeMessageInterrupted(); - synchronized (this) - { + synchronized (this) { int totalSize = 0; LargeData polledPacket = null; - while ((polledPacket = largeMessageData.poll()) != null) - { + while ((polledPacket = largeMessageData.poll()) != null) { totalSize += polledPacket.getFlowControlSize(); } - try - { + try { consumerInternal.flowControl(totalSize, false); } - catch (Exception ignored) - { + catch (Exception ignored) { // what else can we do here? ActiveMQClientLogger.LOGGER.errorCallingCancel(ignored); } @@ -262,32 +231,25 @@ public class LargeMessageControllerImpl implements LargeMessageController } } - public synchronized void close() - { - if (fileCache != null) - { + public synchronized void close() { + if (fileCache != null) { fileCache.close(); } } - public void setOutputStream(final OutputStream output) throws ActiveMQException - { + public void setOutputStream(final OutputStream output) throws ActiveMQException { int totalFlowControl = 0; boolean continues = false; - synchronized (this) - { - if (currentPacket != null) - { + synchronized (this) { + if (currentPacket != null) { sendPacketToOutput(output, currentPacket); currentPacket = null; } - while (handledException == null) - { + while (handledException == null) { LargeData packet = largeMessageData.poll(); - if (packet == null) - { + if (packet == null) { break; } totalFlowControl += packet.getFlowControlSize(); @@ -300,16 +262,13 @@ public class LargeMessageControllerImpl implements LargeMessageController outStream = output; } - if (totalFlowControl > 0) - { + if (totalFlowControl > 0) { consumerInternal.flowControl(totalFlowControl, !continues); } } - public synchronized void saveBuffer(final OutputStream output) throws ActiveMQException - { - if (streamClosed) - { + public synchronized void saveBuffer(final OutputStream output) throws ActiveMQException { + if (streamClosed) { throw ActiveMQClientMessageBundle.BUNDLE.largeMessageLostSession(); } setOutputStream(output); @@ -320,10 +279,8 @@ public class LargeMessageControllerImpl implements LargeMessageController * @param timeWait Milliseconds to Wait. 0 means forever * @throws ActiveMQException */ - public synchronized boolean waitCompletion(final long timeWait) throws ActiveMQException - { - if (outStream == null) - { + public synchronized boolean waitCompletion(final long timeWait) throws ActiveMQException { + if (outStream == null) { // There is no stream.. it will never achieve the end of streaming return false; } @@ -332,34 +289,26 @@ public class LargeMessageControllerImpl implements LargeMessageController // If timeWait = 0, we will use the readTimeout // And we will check if no packets have arrived within readTimeout milliseconds - if (timeWait != 0) - { + if (timeWait != 0) { timeOut = System.currentTimeMillis() + timeWait; } - else - { + else { timeOut = System.currentTimeMillis() + readTimeout; } - while (!streamEnded && handledException == null) - { - try - { + while (!streamEnded && handledException == null) { + try { this.wait(timeWait == 0 ? readTimeout : timeWait); } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } - if (!streamEnded && handledException == null) - { - if (timeWait != 0 && System.currentTimeMillis() > timeOut) - { + if (!streamEnded && handledException == null) { + if (timeWait != 0 && System.currentTimeMillis() > timeOut) { throw ActiveMQClientMessageBundle.BUNDLE.timeoutOnLargeMessage(); } - else if (System.currentTimeMillis() > timeOut && !packetAdded) - { + else if (System.currentTimeMillis() > timeOut && !packetAdded) { throw ActiveMQClientMessageBundle.BUNDLE.timeoutOnLargeMessage(); } } @@ -374,21 +323,15 @@ public class LargeMessageControllerImpl implements LargeMessageController /** * @throws ActiveMQException */ - private void checkException() throws ActiveMQException - { + private void checkException() throws ActiveMQException { // it's not needed to copy it as we never set it back to null // once the exception is set, the controller is pretty much useless - if (handledException != null) - { - if (handledException instanceof ActiveMQException) - { - throw (ActiveMQException)handledException; + if (handledException != null) { + if (handledException instanceof ActiveMQException) { + throw (ActiveMQException) handledException; } - else - { - throw new ActiveMQException(ActiveMQExceptionType.LARGE_MESSAGE_ERROR_BODY, - "Error on saving LargeMessageBufferImpl", - handledException); + else { + throw new ActiveMQException(ActiveMQExceptionType.LARGE_MESSAGE_ERROR_BODY, "Error on saving LargeMessageBufferImpl", handledException); } } } @@ -396,54 +339,45 @@ public class LargeMessageControllerImpl implements LargeMessageController // Channel Buffer Implementation --------------------------------- @Override - public int capacity() - { + public int capacity() { return -1; } - public byte readByte() - { + public byte readByte() { return getByte(readerIndex++); } @Override - public byte getByte(final int index) - { - return getByte((long)index); + public byte getByte(final int index) { + return getByte((long) index); } - private byte getByte(final long index) - { + private byte getByte(final long index) { checkForPacket(index); - if (fileCache != null && index < packetPosition) - { + if (fileCache != null && index < packetPosition) { return fileCache.getByteFromCache(index); } - else - { - return currentPacket.getChunk()[(int)(index - packetPosition)]; + else { + return currentPacket.getChunk()[(int) (index - packetPosition)]; } } @Override - public void getBytes(final int index, final ActiveMQBuffer dst, final int dstIndex, final int length) - { + public void getBytes(final int index, final ActiveMQBuffer dst, final int dstIndex, final int length) { byte[] destBytes = new byte[length]; getBytes(index, destBytes); dst.setBytes(dstIndex, destBytes); } - private void getBytes(final long index, final ActiveMQBuffer dst, final int dstIndex, final int length) - { + private void getBytes(final long index, final ActiveMQBuffer dst, final int dstIndex, final int length) { byte[] destBytes = new byte[length]; getBytes(index, destBytes); dst.setBytes(dstIndex, destBytes); } @Override - public void getBytes(final int index, final byte[] dst, final int dstIndex, final int length) - { + public void getBytes(final int index, final byte[] dst, final int dstIndex, final int length) { byte[] bytesToGet = new byte[length]; getBytes(index, bytesToGet); @@ -451,8 +385,7 @@ public class LargeMessageControllerImpl implements LargeMessageController System.arraycopy(bytesToGet, 0, dst, dstIndex, length); } - public void getBytes(final long index, final byte[] dst, final int dstIndex, final int length) - { + public void getBytes(final long index, final byte[] dst, final int dstIndex, final int length) { byte[] bytesToGet = new byte[length]; getBytes(index, bytesToGet); @@ -461,577 +394,472 @@ public class LargeMessageControllerImpl implements LargeMessageController } @Override - public void getBytes(final int index, final ByteBuffer dst) - { + public void getBytes(final int index, final ByteBuffer dst) { byte[] bytesToGet = new byte[dst.remaining()]; getBytes(index, bytesToGet); dst.put(bytesToGet); } - public void getBytes(final long index, final ByteBuffer dst) - { + public void getBytes(final long index, final ByteBuffer dst) { byte[] bytesToGet = new byte[dst.remaining()]; getBytes(index, bytesToGet); dst.put(bytesToGet); } - public void getBytes(final int index, final OutputStream out, final int length) throws IOException - { + public void getBytes(final int index, final OutputStream out, final int length) throws IOException { byte[] bytesToGet = new byte[length]; getBytes(index, bytesToGet); out.write(bytesToGet); } - public void getBytes(final long index, final OutputStream out, final int length) throws IOException - { + public void getBytes(final long index, final OutputStream out, final int length) throws IOException { byte[] bytesToGet = new byte[length]; getBytes(index, bytesToGet); out.write(bytesToGet); } - public int getBytes(final int index, final GatheringByteChannel out, final int length) throws IOException - { + public int getBytes(final int index, final GatheringByteChannel out, final int length) throws IOException { byte[] bytesToGet = new byte[length]; getBytes(index, bytesToGet); return out.write(ByteBuffer.wrap(bytesToGet)); } - public int getInt(final int index) - { + public int getInt(final int index) { return (getByte(index) & 0xff) << 24 | (getByte(index + 1) & 0xff) << 16 | (getByte(index + 2) & 0xff) << 8 | (getByte(index + 3) & 0xff) << 0; } - public int getInt(final long index) - { + public int getInt(final long index) { return (getByte(index) & 0xff) << 24 | (getByte(index + 1) & 0xff) << 16 | (getByte(index + 2) & 0xff) << 8 | (getByte(index + 3) & 0xff) << 0; } @Override - public long getLong(final int index) - { - return ((long)getByte(index) & 0xff) << 56 | ((long)getByte(index + 1) & 0xff) << 48 | - ((long)getByte(index + 2) & 0xff) << 40 | - ((long)getByte(index + 3) & 0xff) << 32 | - ((long)getByte(index + 4) & 0xff) << 24 | - ((long)getByte(index + 5) & 0xff) << 16 | - ((long)getByte(index + 6) & 0xff) << 8 | - ((long)getByte(index + 7) & 0xff) << 0; + public long getLong(final int index) { + return ((long) getByte(index) & 0xff) << 56 | ((long) getByte(index + 1) & 0xff) << 48 | + ((long) getByte(index + 2) & 0xff) << 40 | + ((long) getByte(index + 3) & 0xff) << 32 | + ((long) getByte(index + 4) & 0xff) << 24 | + ((long) getByte(index + 5) & 0xff) << 16 | + ((long) getByte(index + 6) & 0xff) << 8 | + ((long) getByte(index + 7) & 0xff) << 0; } - public long getLong(final long index) - { - return ((long)getByte(index) & 0xff) << 56 | ((long)getByte(index + 1) & 0xff) << 48 | - ((long)getByte(index + 2) & 0xff) << 40 | - ((long)getByte(index + 3) & 0xff) << 32 | - ((long)getByte(index + 4) & 0xff) << 24 | - ((long)getByte(index + 5) & 0xff) << 16 | - ((long)getByte(index + 6) & 0xff) << 8 | - ((long)getByte(index + 7) & 0xff) << 0; + public long getLong(final long index) { + return ((long) getByte(index) & 0xff) << 56 | ((long) getByte(index + 1) & 0xff) << 48 | + ((long) getByte(index + 2) & 0xff) << 40 | + ((long) getByte(index + 3) & 0xff) << 32 | + ((long) getByte(index + 4) & 0xff) << 24 | + ((long) getByte(index + 5) & 0xff) << 16 | + ((long) getByte(index + 6) & 0xff) << 8 | + ((long) getByte(index + 7) & 0xff) << 0; } @Override - public short getShort(final int index) - { - return (short)(getByte(index) << 8 | getByte(index + 1) & 0xFF); + public short getShort(final int index) { + return (short) (getByte(index) << 8 | getByte(index + 1) & 0xFF); } - public short getShort(final long index) - { - return (short)(getByte(index) << 8 | getByte(index + 1) & 0xFF); + public short getShort(final long index) { + return (short) (getByte(index) << 8 | getByte(index + 1) & 0xFF); } - private int getUnsignedMedium(final int index) - { + private int getUnsignedMedium(final int index) { return (getByte(index) & 0xff) << 16 | (getByte(index + 1) & 0xff) << 8 | (getByte(index + 2) & 0xff) << 0; } - public int getUnsignedMedium(final long index) - { + public int getUnsignedMedium(final long index) { return (getByte(index) & 0xff) << 16 | (getByte(index + 1) & 0xff) << 8 | (getByte(index + 2) & 0xff) << 0; } @Override - public void setByte(final int index, final byte value) - { + public void setByte(final int index, final byte value) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } @Override - public void setBytes(final int index, final ActiveMQBuffer src, final int srcIndex, final int length) - { + public void setBytes(final int index, final ActiveMQBuffer src, final int srcIndex, final int length) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } @Override - public void setBytes(final int index, final byte[] src, final int srcIndex, final int length) - { + public void setBytes(final int index, final byte[] src, final int srcIndex, final int length) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } @Override - public void setBytes(final int index, final ByteBuffer src) - { + public void setBytes(final int index, final ByteBuffer src) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } @Override - public void setInt(final int index, final int value) - { + public void setInt(final int index, final int value) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } @Override - public void setLong(final int index, final long value) - { + public void setLong(final int index, final long value) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } @Override - public void setShort(final int index, final short value) - { + public void setShort(final int index, final short value) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } @Override - public ByteBuffer toByteBuffer(final int index, final int length) - { + public ByteBuffer toByteBuffer(final int index, final int length) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public int readerIndex() - { - return (int)readerIndex; + public int readerIndex() { + return (int) readerIndex; } - public void readerIndex(final int readerIndex) - { - try - { + public void readerIndex(final int readerIndex) { + try { checkForPacket(readerIndex); } - catch (Exception e) - { + catch (Exception e) { ActiveMQClientLogger.LOGGER.errorReadingIndex(e); throw new RuntimeException(e.getMessage(), e); } this.readerIndex = readerIndex; } - public int writerIndex() - { - return (int)totalSize; + public int writerIndex() { + return (int) totalSize; } - public long getSize() - { + public long getSize() { return totalSize; } - public void writerIndex(final int writerIndex) - { + public void writerIndex(final int writerIndex) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public void setIndex(final int readerIndex, final int writerIndex) - { - try - { + public void setIndex(final int readerIndex, final int writerIndex) { + try { checkForPacket(readerIndex); } - catch (Exception e) - { + catch (Exception e) { ActiveMQClientLogger.LOGGER.errorSettingIndex(e); throw new RuntimeException(e.getMessage(), e); } this.readerIndex = readerIndex; } - public void clear() - { + public void clear() { } - public boolean readable() - { + public boolean readable() { return true; } - public boolean writable() - { + public boolean writable() { return false; } - public int readableBytes() - { + public int readableBytes() { long readableBytes = totalSize - readerIndex; - if (readableBytes > Integer.MAX_VALUE) - { + if (readableBytes > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } - else - { - return (int)(totalSize - readerIndex); + else { + return (int) (totalSize - readerIndex); } } - public int writableBytes() - { + public int writableBytes() { return 0; } - public void markReaderIndex() - { + public void markReaderIndex() { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public void resetReaderIndex() - { - try - { + public void resetReaderIndex() { + try { checkForPacket(0); } - catch (Exception e) - { + catch (Exception e) { ActiveMQClientLogger.LOGGER.errorReSettingIndex(e); throw new RuntimeException(e.getMessage(), e); } } - public void markWriterIndex() - { + public void markWriterIndex() { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public void resetWriterIndex() - { + public void resetWriterIndex() { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public void discardReadBytes() - { + public void discardReadBytes() { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public short getUnsignedByte(final int index) - { - return (short)(getByte(index) & 0xFF); + public short getUnsignedByte(final int index) { + return (short) (getByte(index) & 0xFF); } - public int getUnsignedShort(final int index) - { + public int getUnsignedShort(final int index) { return getShort(index) & 0xFFFF; } - public int getMedium(final int index) - { + public int getMedium(final int index) { int value = getUnsignedMedium(index); - if ((value & 0x800000) != 0) - { + if ((value & 0x800000) != 0) { value |= 0xff000000; } return value; } - public long getUnsignedInt(final int index) - { + public long getUnsignedInt(final int index) { return getInt(index) & 0xFFFFFFFFL; } - public void getBytes(int index, final byte[] dst) - { + public void getBytes(int index, final byte[] dst) { // TODO: optimize this by using System.arraycopy - for (int i = 0; i < dst.length; i++) - { + for (int i = 0; i < dst.length; i++) { dst[i] = getByte(index++); } } - public void getBytes(long index, final byte[] dst) - { + public void getBytes(long index, final byte[] dst) { // TODO: optimize this by using System.arraycopy - for (int i = 0; i < dst.length; i++) - { + for (int i = 0; i < dst.length; i++) { dst[i] = getByte(index++); } } - public void getBytes(final int index, final ActiveMQBuffer dst) - { + public void getBytes(final int index, final ActiveMQBuffer dst) { getBytes(index, dst, dst.writableBytes()); } - public void getBytes(final int index, final ActiveMQBuffer dst, final int length) - { - if (length > dst.writableBytes()) - { + public void getBytes(final int index, final ActiveMQBuffer dst, final int length) { + if (length > dst.writableBytes()) { throw new IndexOutOfBoundsException(); } getBytes(index, dst, dst.writerIndex(), length); dst.writerIndex(dst.writerIndex() + length); } - public void setBytes(final int index, final byte[] src) - { + public void setBytes(final int index, final byte[] src) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public void setBytes(final int index, final ActiveMQBuffer src) - { + public void setBytes(final int index, final ActiveMQBuffer src) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public void setBytes(final int index, final ActiveMQBuffer src, final int length) - { + public void setBytes(final int index, final ActiveMQBuffer src, final int length) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public void setZero(final int index, final int length) - { + public void setZero(final int index, final int length) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public short readUnsignedByte() - { - return (short)(readByte() & 0xFF); + public short readUnsignedByte() { + return (short) (readByte() & 0xFF); } - public short readShort() - { + public short readShort() { short v = getShort(readerIndex); readerIndex += 2; return v; } - public int readUnsignedShort() - { + public int readUnsignedShort() { return readShort() & 0xFFFF; } - public int readMedium() - { + public int readMedium() { int value = readUnsignedMedium(); - if ((value & 0x800000) != 0) - { + if ((value & 0x800000) != 0) { value |= 0xff000000; } return value; } - public int readUnsignedMedium() - { + public int readUnsignedMedium() { int v = getUnsignedMedium(readerIndex); readerIndex += 3; return v; } - public int readInt() - { + public int readInt() { int v = getInt(readerIndex); readerIndex += 4; return v; } - public int readInt(final int pos) - { + public int readInt(final int pos) { int v = getInt(pos); return v; } - public long readUnsignedInt() - { + public long readUnsignedInt() { return readInt() & 0xFFFFFFFFL; } - public long readLong() - { + public long readLong() { long v = getLong(readerIndex); readerIndex += 8; return v; } - public void readBytes(final byte[] dst, final int dstIndex, final int length) - { + public void readBytes(final byte[] dst, final int dstIndex, final int length) { getBytes(readerIndex, dst, dstIndex, length); readerIndex += length; } - public void readBytes(final byte[] dst) - { + public void readBytes(final byte[] dst) { readBytes(dst, 0, dst.length); } - public void readBytes(final ActiveMQBuffer dst) - { + public void readBytes(final ActiveMQBuffer dst) { readBytes(dst, dst.writableBytes()); } - public void readBytes(final ActiveMQBuffer dst, final int length) - { - if (length > dst.writableBytes()) - { + public void readBytes(final ActiveMQBuffer dst, final int length) { + if (length > dst.writableBytes()) { throw new IndexOutOfBoundsException(); } readBytes(dst, dst.writerIndex(), length); dst.writerIndex(dst.writerIndex() + length); } - public void readBytes(final ActiveMQBuffer dst, final int dstIndex, final int length) - { + public void readBytes(final ActiveMQBuffer dst, final int dstIndex, final int length) { getBytes(readerIndex, dst, dstIndex, length); readerIndex += length; } - public void readBytes(final ByteBuffer dst) - { + public void readBytes(final ByteBuffer dst) { int length = dst.remaining(); getBytes(readerIndex, dst); readerIndex += length; } - public int readBytes(final GatheringByteChannel out, final int length) throws IOException - { - int readBytes = getBytes((int)readerIndex, out, length); + public int readBytes(final GatheringByteChannel out, final int length) throws IOException { + int readBytes = getBytes((int) readerIndex, out, length); readerIndex += readBytes; return readBytes; } - public void readBytes(final OutputStream out, final int length) throws IOException - { + public void readBytes(final OutputStream out, final int length) throws IOException { getBytes(readerIndex, out, length); readerIndex += length; } - public void skipBytes(final int length) - { + public void skipBytes(final int length) { long newReaderIndex = readerIndex + length; checkForPacket(newReaderIndex); readerIndex = newReaderIndex; } - public void writeByte(final byte value) - { + public void writeByte(final byte value) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public void writeShort(final short value) - { + public void writeShort(final short value) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public void writeMedium(final int value) - { + public void writeMedium(final int value) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public void writeInt(final int value) - { + public void writeInt(final int value) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public void writeLong(final long value) - { + public void writeLong(final long value) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public void writeBytes(final byte[] src, final int srcIndex, final int length) - { + public void writeBytes(final byte[] src, final int srcIndex, final int length) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public void writeBytes(final byte[] src) - { + public void writeBytes(final byte[] src) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public void writeBytes(final ActiveMQBuffer src) - { + public void writeBytes(final ActiveMQBuffer src) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public void writeBytes(final ActiveMQBuffer src, final int length) - { + public void writeBytes(final ActiveMQBuffer src, final int length) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public void writeBytes(final ByteBuffer src) - { + public void writeBytes(final ByteBuffer src) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public int writeBytes(final InputStream in, final int length) throws IOException - { + public int writeBytes(final InputStream in, final int length) throws IOException { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public int writeBytes(final ScatteringByteChannel in, final int length) throws IOException - { + public int writeBytes(final ScatteringByteChannel in, final int length) throws IOException { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public void writeZero(final int length) - { + public void writeZero(final int length) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public ByteBuffer toByteBuffer() - { + public ByteBuffer toByteBuffer() { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public ByteBuffer[] toByteBuffers() - { + public ByteBuffer[] toByteBuffers() { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public ByteBuffer[] toByteBuffers(final int index, final int length) - { + public ByteBuffer[] toByteBuffers(final int index, final int length) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public String toString(final String charsetName) - { + public String toString(final String charsetName) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public Object getUnderlyingBuffer() - { + public Object getUnderlyingBuffer() { return this; } @Override - public boolean readBoolean() - { + public boolean readBoolean() { return readByte() != 0; } @Override - public char readChar() - { - return (char)readShort(); + public char readChar() { + return (char) readShort(); } - public char getChar(final int index) - { - return (char)getShort(index); + public char getChar(final int index) { + return (char) getShort(index); } - public double getDouble(final int index) - { + public double getDouble(final int index) { return Double.longBitsToDouble(getLong(index)); } - public float getFloat(final int index) - { + public float getFloat(final int index) { return Float.intBitsToFloat(getInt(index)); } - public ActiveMQBuffer readBytes(final int length) - { + public ActiveMQBuffer readBytes(final int length) { byte[] bytesToGet = new byte[length]; getBytes(readerIndex, bytesToGet); readerIndex += length; @@ -1039,48 +867,39 @@ public class LargeMessageControllerImpl implements LargeMessageController } @Override - public double readDouble() - { + public double readDouble() { return Double.longBitsToDouble(readLong()); } @Override - public float readFloat() - { + public float readFloat() { return Float.intBitsToFloat(readInt()); } @Override - public SimpleString readNullableSimpleString() - { + public SimpleString readNullableSimpleString() { int b = readByte(); - if (b == DataConstants.NULL) - { + if (b == DataConstants.NULL) { return null; } - else - { + else { return readSimpleString(); } } @Override - public String readNullableString() - { + public String readNullableString() { int b = readByte(); - if (b == DataConstants.NULL) - { + if (b == DataConstants.NULL) { return null; } - else - { + else { return readString(); } } @Override - public SimpleString readSimpleString() - { + public SimpleString readSimpleString() { int len = readInt(); byte[] data = new byte[len]; readBytes(data); @@ -1088,98 +907,81 @@ public class LargeMessageControllerImpl implements LargeMessageController } @Override - public String readString() - { + public String readString() { int len = readInt(); - if (len < 9) - { + if (len < 9) { char[] chars = new char[len]; - for (int i = 0; i < len; i++) - { - chars[i] = (char)readShort(); + for (int i = 0; i < len; i++) { + chars[i] = (char) readShort(); } return new String(chars); } - else if (len < 0xfff) - { + else if (len < 0xfff) { return readUTF(); } - else - { + else { return readSimpleString().toString(); } } @Override - public String readUTF() - { + public String readUTF() { return UTF8Util.readUTF(this); } @Override - public void writeBoolean(final boolean val) - { + public void writeBoolean(final boolean val) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } @Override - public void writeChar(final char val) - { + public void writeChar(final char val) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } @Override - public void writeDouble(final double val) - { + public void writeDouble(final double val) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } @Override - public void writeFloat(final float val) - { + public void writeFloat(final float val) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } @Override - public void writeNullableSimpleString(final SimpleString val) - { + public void writeNullableSimpleString(final SimpleString val) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } @Override - public void writeNullableString(final String val) - { + public void writeNullableString(final String val) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } @Override - public void writeSimpleString(final SimpleString val) - { + public void writeSimpleString(final SimpleString val) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } @Override - public void writeString(final String val) - { + public void writeString(final String val) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } @Override - public void writeUTF(final String utf) - { + public void writeUTF(final String utf) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public ActiveMQBuffer copy() - { + public ActiveMQBuffer copy() { throw new UnsupportedOperationException(); } - public ActiveMQBuffer slice(final int index, final int length) - { + public ActiveMQBuffer slice(final int index, final int length) { throw new UnsupportedOperationException(); } @@ -1188,38 +990,30 @@ public class LargeMessageControllerImpl implements LargeMessageController * @param packet * @throws ActiveMQException */ - private void sendPacketToOutput(final OutputStream output, final LargeData packet) throws ActiveMQException - { - try - { + private void sendPacketToOutput(final OutputStream output, final LargeData packet) throws ActiveMQException { + try { output.write(packet.getChunk()); - if (!packet.isContinues()) - { + if (!packet.isContinues()) { streamEnded = true; output.close(); } } - catch (IOException e) - { + catch (IOException e) { throw ActiveMQClientMessageBundle.BUNDLE.errorWritingLargeMessage(e); } } - private void popPacket() - { - try - { + private void popPacket() { + try { - if (streamEnded) - { + if (streamEnded) { // no more packets, we are over the last one already throw new IndexOutOfBoundsException(); } int sizeToAdd = currentPacket != null ? currentPacket.chunk.length : 1; currentPacket = largeMessageData.poll(readTimeout, TimeUnit.SECONDS); - if (currentPacket == null) - { + if (currentPacket == null) { throw new IndexOutOfBoundsException(); } @@ -1236,53 +1030,42 @@ public class LargeMessageControllerImpl implements LargeMessageController packetLastPosition = packetPosition + currentPacket.getChunk().length; } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw e; } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } } - private void checkForPacket(final long index) - { - if (outStream != null) - { + private void checkForPacket(final long index) { + if (outStream != null) { throw new IllegalAccessError("Can't read the messageBody after setting outputStream"); } - if (index >= totalSize) - { + if (index >= totalSize) { throw new IndexOutOfBoundsException(); } - if (streamClosed) - { + if (streamClosed) { throw new IllegalAccessError("The consumer associated with this large message was closed before the body was read"); } - if (fileCache == null) - { - if (index < lastIndex) - { + if (fileCache == null) { + if (index < lastIndex) { throw new IllegalAccessError("LargeMessage have read-only and one-way buffers"); } lastIndex = index; } - while (index >= packetLastPosition && !streamEnded) - { + while (index >= packetLastPosition && !streamEnded) { popPacket(); } } - private final class FileCache - { + private final class FileCache { - public FileCache(final File cachedFile) - { + public FileCache(final File cachedFile) { this.cachedFile = cachedFile; } @@ -1298,18 +1081,14 @@ public class LargeMessageControllerImpl implements LargeMessageController private volatile FileChannel cachedChannel; - private synchronized void readCache(final long position) - { + private synchronized void readCache(final long position) { - try - { - if (position < readCachePositionStart || position > readCachePositionEnd) - { + try { + if (position < readCachePositionStart || position > readCachePositionEnd) { checkOpen(); - if (position > cachedChannel.size()) - { + if (position > cachedChannel.size()) { throw new ArrayIndexOutOfBoundsException("position > " + cachedChannel.size()); } @@ -1317,8 +1096,7 @@ public class LargeMessageControllerImpl implements LargeMessageController cachedChannel.position(readCachePositionStart); - if (readCache == null) - { + if (readCache == null) { readCache = ByteBuffer.allocate(bufferSize); } @@ -1327,27 +1105,23 @@ public class LargeMessageControllerImpl implements LargeMessageController readCachePositionEnd = readCachePositionStart + cachedChannel.read(readCache) - 1; } } - catch (Exception e) - { + catch (Exception e) { ActiveMQClientLogger.LOGGER.errorReadingCache(e); throw new RuntimeException(e.getMessage(), e); } - finally - { + finally { close(); } } - public synchronized byte getByteFromCache(final long position) - { + public synchronized byte getByteFromCache(final long position) { readCache(position); - return readCache.get((int)(position - readCachePositionStart)); + return readCache.get((int) (position - readCachePositionStart)); } - public void cachePackage(final byte[] body) throws Exception - { + public void cachePackage(final byte[] body) throws Exception { checkOpen(); cachedChannel.position(cachedChannel.size()); @@ -1359,39 +1133,30 @@ public class LargeMessageControllerImpl implements LargeMessageController /** * @throws FileNotFoundException */ - public void checkOpen() throws FileNotFoundException - { - if (cachedFile != null || !cachedChannel.isOpen()) - { + public void checkOpen() throws FileNotFoundException { + if (cachedFile != null || !cachedChannel.isOpen()) { cachedRAFile = new RandomAccessFile(cachedFile, "rw"); cachedChannel = cachedRAFile.getChannel(); } } - public void close() - { - if (cachedChannel != null && cachedChannel.isOpen()) - { - try - { + public void close() { + if (cachedChannel != null && cachedChannel.isOpen()) { + try { cachedChannel.close(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQClientLogger.LOGGER.errorClosingCache(e); } cachedChannel = null; } - if (cachedRAFile != null) - { - try - { + if (cachedRAFile != null) { + try { cachedRAFile.close(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQClientLogger.LOGGER.errorClosingCache(e); } cachedRAFile = null; @@ -1400,17 +1165,13 @@ public class LargeMessageControllerImpl implements LargeMessageController } @Override - protected void finalize() - { + protected void finalize() { close(); - if (cachedFile != null && cachedFile.exists()) - { - try - { + if (cachedFile != null && cachedFile.exists()) { + try { cachedFile.delete(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQClientLogger.LOGGER.errorFinalisingCache(e); } } @@ -1418,83 +1179,69 @@ public class LargeMessageControllerImpl implements LargeMessageController } - public ByteBuf byteBuf() - { + public ByteBuf byteBuf() { return null; } - public ActiveMQBuffer copy(final int index, final int length) - { + public ActiveMQBuffer copy(final int index, final int length) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public ActiveMQBuffer duplicate() - { + public ActiveMQBuffer duplicate() { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public ActiveMQBuffer readSlice(final int length) - { + public ActiveMQBuffer readSlice(final int length) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public void setChar(final int index, final char value) - { + public void setChar(final int index, final char value) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public void setDouble(final int index, final double value) - { + public void setDouble(final int index, final double value) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public void setFloat(final int index, final float value) - { + public void setFloat(final int index, final float value) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public ActiveMQBuffer slice() - { + public ActiveMQBuffer slice() { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - public void writeBytes(final ActiveMQBuffer src, final int srcIndex, final int length) - { + public void writeBytes(final ActiveMQBuffer src, final int srcIndex, final int length) { throw new IllegalAccessError(LargeMessageControllerImpl.READ_ONLY_ERROR_MESSAGE); } - private static class LargeData - { + private static class LargeData { + final byte[] chunk; final int flowControlSize; final boolean continues; - public LargeData() - { + public LargeData() { continues = false; flowControlSize = 0; chunk = null; } - public LargeData(byte[] chunk, int flowControlSize, boolean continues) - { + public LargeData(byte[] chunk, int flowControlSize, boolean continues) { this.chunk = chunk; this.flowControlSize = flowControlSize; this.continues = continues; } - public byte[] getChunk() - { + public byte[] getChunk() { return chunk; } - public int getFlowControlSize() - { + public int getFlowControlSize() { return flowControlSize; } - public boolean isContinues() - { + public boolean isContinues() { return continues; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/QueueQueryImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/QueueQueryImpl.java index af76497e2f..27607bc025 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/QueueQueryImpl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/QueueQueryImpl.java @@ -19,8 +19,7 @@ package org.apache.activemq.artemis.core.client.impl; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.client.ClientSession; -public class QueueQueryImpl implements ClientSession.QueueQuery -{ +public class QueueQueryImpl implements ClientSession.QueueQuery { private final boolean exists; @@ -47,8 +46,7 @@ public class QueueQueryImpl implements ClientSession.QueueQuery final SimpleString filterString, final SimpleString address, final SimpleString name, - final boolean exists) - { + final boolean exists) { this(durable, temporary, consumerCount, messageCount, filterString, address, name, exists, false); } @@ -60,8 +58,7 @@ public class QueueQueryImpl implements ClientSession.QueueQuery final SimpleString address, final SimpleString name, final boolean exists, - final boolean autoCreateJmsQueues) - { + final boolean autoCreateJmsQueues) { this.durable = durable; this.temporary = temporary; this.consumerCount = consumerCount; @@ -73,48 +70,39 @@ public class QueueQueryImpl implements ClientSession.QueueQuery this.autoCreateJmsQueues = autoCreateJmsQueues; } - public SimpleString getName() - { + public SimpleString getName() { return name; } - public SimpleString getAddress() - { + public SimpleString getAddress() { return address; } - public int getConsumerCount() - { + public int getConsumerCount() { return consumerCount; } - public SimpleString getFilterString() - { + public SimpleString getFilterString() { return filterString; } - public long getMessageCount() - { + public long getMessageCount() { return messageCount; } - public boolean isDurable() - { + public boolean isDurable() { return durable; } - public boolean isAutoCreateJmsQueues() - { + public boolean isAutoCreateJmsQueues() { return autoCreateJmsQueues; } - public boolean isTemporary() - { + public boolean isTemporary() { return temporary; } - public boolean isExists() - { + public boolean isExists() { return exists; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ServerLocatorImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ServerLocatorImpl.java index 64b5b928d9..708c087b06 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ServerLocatorImpl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ServerLocatorImpl.java @@ -71,16 +71,14 @@ import org.apache.activemq.artemis.utils.UUIDGenerator; * This is the implementation of {@link org.apache.activemq.artemis.api.core.client.ServerLocator} and all * the proper javadoc is located on that interface. */ -public final class ServerLocatorImpl implements ServerLocatorInternal, DiscoveryListener -{ - private enum STATE - { +public final class ServerLocatorImpl implements ServerLocatorInternal, DiscoveryListener { + + private enum STATE { INITIALIZED, CLOSED, CLOSING } private static final long serialVersionUID = -1615857864410205260L; - // This is the default value private ClientProtocolManagerFactory protocolManagerFactory = ActiveMQClientProtocolManagerFactory.getInstance(); @@ -215,54 +213,41 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery // To be used on test assertions public static Runnable finalizeCallback = null; - public static synchronized void clearThreadPools() - { + public static synchronized void clearThreadPools() { - if (globalThreadPool != null) - { + if (globalThreadPool != null) { globalThreadPool.shutdown(); - try - { - if (!globalThreadPool.awaitTermination(10, TimeUnit.SECONDS)) - { + try { + if (!globalThreadPool.awaitTermination(10, TimeUnit.SECONDS)) { throw new IllegalStateException("Couldn't finish the globalThreadPool"); } } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } - finally - { + finally { globalThreadPool = null; } } - if (globalScheduledThreadPool != null) - { + if (globalScheduledThreadPool != null) { globalScheduledThreadPool.shutdown(); - try - { - if (!globalScheduledThreadPool.awaitTermination(10, TimeUnit.SECONDS)) - { + try { + if (!globalScheduledThreadPool.awaitTermination(10, TimeUnit.SECONDS)) { throw new IllegalStateException("Couldn't finish the globalScheduledThreadPool"); } } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } - finally - { + finally { globalScheduledThreadPool = null; } } } - private static synchronized ExecutorService getGlobalThreadPool() - { - if (globalThreadPool == null) - { + private static synchronized ExecutorService getGlobalThreadPool() { + if (globalThreadPool == null) { ThreadFactory factory = new ActiveMQThreadFactory("ActiveMQ-client-global-threads", true, getThisClassLoader()); globalThreadPool = Executors.newCachedThreadPool(factory); @@ -271,13 +256,9 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery return globalThreadPool; } - private static synchronized ScheduledExecutorService getGlobalScheduledThreadPool() - { - if (globalScheduledThreadPool == null) - { - ThreadFactory factory = new ActiveMQThreadFactory("ActiveMQ-client-global-scheduled-threads", - true, - getThisClassLoader()); + private static synchronized ScheduledExecutorService getGlobalScheduledThreadPool() { + if (globalScheduledThreadPool == null) { + ThreadFactory factory = new ActiveMQThreadFactory("ActiveMQ-client-global-scheduled-threads", true, getThisClassLoader()); globalScheduledThreadPool = Executors.newScheduledThreadPool(ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, @@ -287,82 +268,61 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery return globalScheduledThreadPool; } - private synchronized void setThreadPools() - { - if (threadPool != null) - { + private synchronized void setThreadPools() { + if (threadPool != null) { return; } - else if (useGlobalPools) - { + else if (useGlobalPools) { threadPool = getGlobalThreadPool(); scheduledThreadPool = getGlobalScheduledThreadPool(); } - else - { + else { this.shutdownPool = true; - ThreadFactory factory = new ActiveMQThreadFactory("ActiveMQ-client-factory-threads-" + System.identityHashCode(this), - true, - getThisClassLoader()); + ThreadFactory factory = new ActiveMQThreadFactory("ActiveMQ-client-factory-threads-" + System.identityHashCode(this), true, getThisClassLoader()); - if (threadPoolMaxSize == -1) - { + if (threadPoolMaxSize == -1) { threadPool = Executors.newCachedThreadPool(factory); } - else - { + else { threadPool = Executors.newFixedThreadPool(threadPoolMaxSize, factory); } - factory = new ActiveMQThreadFactory("ActiveMQ-client-factory-pinger-threads-" + System.identityHashCode(this), - true, - getThisClassLoader()); + factory = new ActiveMQThreadFactory("ActiveMQ-client-factory-pinger-threads-" + System.identityHashCode(this), true, getThisClassLoader()); scheduledThreadPool = Executors.newScheduledThreadPool(scheduledThreadPoolMaxSize, factory); } } - private static ClassLoader getThisClassLoader() - { - return AccessController.doPrivileged(new PrivilegedAction() - { - public ClassLoader run() - { + private static ClassLoader getThisClassLoader() { + return AccessController.doPrivileged(new PrivilegedAction() { + public ClassLoader run() { return ClientSessionFactoryImpl.class.getClassLoader(); } }); } - - private void instantiateLoadBalancingPolicy() - { - if (connectionLoadBalancingPolicyClassName == null) - { + private void instantiateLoadBalancingPolicy() { + if (connectionLoadBalancingPolicyClassName == null) { throw new IllegalStateException("Please specify a load balancing policy class name on the session factory"); } - AccessController.doPrivileged(new PrivilegedAction() - { - public Object run() - { + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { loadBalancingPolicy = (ConnectionLoadBalancingPolicy) ClassloadingUtil.newInstanceFromClassLoader(connectionLoadBalancingPolicyClassName); return null; } }); } - private synchronized void initialise() throws ActiveMQException - { + private synchronized void initialise() throws ActiveMQException { if (state == STATE.INITIALIZED) return; - synchronized (stateGuard) - { + synchronized (stateGuard) { if (state == STATE.CLOSING) throw new ActiveMQIllegalStateException(); - try - { + try { state = STATE.INITIALIZED; latch = new CountDownLatch(1); @@ -370,8 +330,7 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery instantiateLoadBalancingPolicy(); - if (discoveryGroupConfiguration != null) - { + if (discoveryGroupConfiguration != null) { discoveryGroup = createDiscoveryGroup(nodeID, discoveryGroupConfiguration); discoveryGroup.registerListener(this); @@ -379,26 +338,23 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery discoveryGroup.start(); } } - catch (Exception e) - { + catch (Exception e) { state = null; throw ActiveMQClientMessageBundle.BUNDLE.failedToInitialiseSessionFactory(e); } } } - private static DiscoveryGroup createDiscoveryGroup(String nodeID, DiscoveryGroupConfiguration config) throws Exception - { - DiscoveryGroup group = new DiscoveryGroup(nodeID, config.getName(), - config.getRefreshTimeout(), config.getBroadcastEndpointFactory(), null); + private static DiscoveryGroup createDiscoveryGroup(String nodeID, + DiscoveryGroupConfiguration config) throws Exception { + DiscoveryGroup group = new DiscoveryGroup(nodeID, config.getName(), config.getRefreshTimeout(), config.getBroadcastEndpointFactory(), null); return group; } private ServerLocatorImpl(final Topology topology, final boolean useHA, final DiscoveryGroupConfiguration discoveryGroupConfiguration, - final TransportConfiguration[] transportConfigs) - { + final TransportConfiguration[] transportConfigs) { traceException.fillInStackTrace(); this.topology = topology == null ? new Topology(this) : topology; @@ -474,27 +430,21 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery clusterConnection = false; } - public static ServerLocator newLocator(String uri) - { - try - { + public static ServerLocator newLocator(String uri) { + try { return newLocator(new URI(uri)); } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } } - public static ServerLocator newLocator(URI uri) - { - try - { + public static ServerLocator newLocator(URI uri) { + try { ServerLocatorParser parser = new ServerLocatorParser(); return parser.newObject(uri, null); } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } } @@ -502,11 +452,9 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery /** * Create a ServerLocatorImpl using UDP discovery to lookup cluster */ - public ServerLocatorImpl(final boolean useHA, final DiscoveryGroupConfiguration groupConfiguration) - { + public ServerLocatorImpl(final boolean useHA, final DiscoveryGroupConfiguration groupConfiguration) { this(new Topology(null), useHA, groupConfiguration, null); - if (useHA) - { + if (useHA) { // We only set the owner at where the Topology was created. // For that reason we can't set it at the main constructor topology.setOwner(this); @@ -518,11 +466,9 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery * * @param transportConfigs */ - public ServerLocatorImpl(final boolean useHA, final TransportConfiguration... transportConfigs) - { + public ServerLocatorImpl(final boolean useHA, final TransportConfiguration... transportConfigs) { this(new Topology(null), useHA, null, transportConfigs); - if (useHA) - { + if (useHA) { // We only set the owner at where the Topology was created. // For that reason we can't set it at the main constructor topology.setOwner(this); @@ -534,8 +480,7 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery */ public ServerLocatorImpl(final Topology topology, final boolean useHA, - final DiscoveryGroupConfiguration groupConfiguration) - { + final DiscoveryGroupConfiguration groupConfiguration) { this(topology, useHA, groupConfiguration, null); } @@ -546,15 +491,12 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery */ public ServerLocatorImpl(final Topology topology, final boolean useHA, - final TransportConfiguration... transportConfigs) - { + final TransportConfiguration... transportConfigs) { this(topology, useHA, null, transportConfigs); } - public void resetToInitialConnectors() - { - synchronized (topologyArrayGuard) - { + public void resetToInitialConnectors() { + synchronized (topologyArrayGuard) { receivedTopology = false; topologyArray = null; topology.clear(); @@ -564,12 +506,9 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery /* * I'm not using isAllInVM here otherwsie BeanProperties would translate this as a property for the URL */ - public boolean allInVM() - { - for (TransportConfiguration config: getStaticTransportConfigurations()) - { - if (!config.getFactoryClassName().contains("InVMConnectorFactory")) - { + public boolean allInVM() { + for (TransportConfiguration config : getStaticTransportConfigurations()) { + if (!config.getFactoryClassName().contains("InVMConnectorFactory")) { return false; } } @@ -577,8 +516,7 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery return true; } - private ServerLocatorImpl(ServerLocatorImpl locator) - { + private ServerLocatorImpl(ServerLocatorImpl locator) { ha = locator.ha; finalizeCheck = locator.finalizeCheck; clusterConnection = locator.clusterConnection; @@ -623,25 +561,21 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery clusterTransportConfiguration = locator.clusterTransportConfiguration; } - private synchronized TransportConfiguration selectConnector() - { + private synchronized TransportConfiguration selectConnector() { Pair[] usedTopology; - synchronized (topologyArrayGuard) - { + synchronized (topologyArrayGuard) { usedTopology = topologyArray; } // if the topologyArray is null, we will use the initialConnectors - if (usedTopology != null) - { + if (usedTopology != null) { int pos = loadBalancingPolicy.select(usedTopology.length); Pair pair = usedTopology[pos]; return pair.getA(); } - else - { + else { // Get from initialconnectors int pos = loadBalancingPolicy.select(initialConnectors.length); @@ -650,26 +584,19 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery } } - public void start(Executor executor) throws Exception - { + public void start(Executor executor) throws Exception { initialise(); this.startExecutor = executor; - if (executor != null) - { - executor.execute(new Runnable() - { - public void run() - { - try - { + if (executor != null) { + executor.execute(new Runnable() { + public void run() { + try { connect(); } - catch (Exception e) - { - if (!isClosed()) - { + catch (Exception e) { + if (!isClosed()) { ActiveMQClientLogger.LOGGER.errorConnectingToNodes(e); } } @@ -678,46 +605,35 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery } } - - public ClientProtocolManager newProtocolManager() - { + public ClientProtocolManager newProtocolManager() { return getProtocolManagerFactory().newProtocolManager(); } - public ClientProtocolManagerFactory getProtocolManagerFactory() - { - if (protocolManagerFactory == null) - { + public ClientProtocolManagerFactory getProtocolManagerFactory() { + if (protocolManagerFactory == null) { // this could happen over serialization from older versions protocolManagerFactory = ActiveMQClientProtocolManagerFactory.getInstance(); } return protocolManagerFactory; } - public void setProtocolManagerFactory(ClientProtocolManagerFactory protocolManagerFactory) - { + public void setProtocolManagerFactory(ClientProtocolManagerFactory protocolManagerFactory) { this.protocolManagerFactory = protocolManagerFactory; } - - public void disableFinalizeCheck() - { + public void disableFinalizeCheck() { finalizeCheck = false; } @Override - public ClientSessionFactoryInternal connect() throws ActiveMQException - { + public ClientSessionFactoryInternal connect() throws ActiveMQException { return connect(false); } - private ClientSessionFactoryInternal connect(final boolean skipWarnings) throws ActiveMQException - { - synchronized (this) - { + private ClientSessionFactoryInternal connect(final boolean skipWarnings) throws ActiveMQException { + synchronized (this) { // static list of initial connectors - if (getNumInitialConnectors() > 0 && discoveryGroup == null) - { + if (getNumInitialConnectors() > 0 && discoveryGroup == null) { ClientSessionFactoryInternal sf = (ClientSessionFactoryInternal) staticConnector.connect(skipWarnings); addFactory(sf); return sf; @@ -728,46 +644,37 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery } @Override - public ClientSessionFactoryInternal connectNoWarnings() throws ActiveMQException - { + public ClientSessionFactoryInternal connectNoWarnings() throws ActiveMQException { return connect(true); } - public ServerLocatorImpl setAfterConnectionInternalListener(AfterConnectInternalListener listener) - { + public ServerLocatorImpl setAfterConnectionInternalListener(AfterConnectInternalListener listener) { this.afterConnectListener = listener; return this; } - public AfterConnectInternalListener getAfterConnectInternalListener() - { + public AfterConnectInternalListener getAfterConnectInternalListener() { return afterConnectListener; } - public ClientSessionFactory createSessionFactory(String nodeID) throws Exception - { + public ClientSessionFactory createSessionFactory(String nodeID) throws Exception { TopologyMember topologyMember = topology.getMember(nodeID); - if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) { ActiveMQClientLogger.LOGGER.trace("Creating connection factory towards " + nodeID + " = " + topologyMember + ", topology=" + topology.describe()); } - if (topologyMember == null) - { + if (topologyMember == null) { return null; } - if (topologyMember.getLive() != null) - { + if (topologyMember.getLive() != null) { ClientSessionFactoryInternal factory = (ClientSessionFactoryInternal) createSessionFactory(topologyMember.getLive()); - if (topologyMember.getBackup() != null) - { + if (topologyMember.getBackup() != null) { factory.setBackupConnector(topologyMember.getLive(), topologyMember.getBackup()); } return factory; } - if (topologyMember.getLive() == null && topologyMember.getBackup() != null) - { + if (topologyMember.getLive() == null && topologyMember.getBackup() != null) { // This shouldn't happen, however I wanted this to consider all possible cases ClientSessionFactoryInternal factory = (ClientSessionFactoryInternal) createSessionFactory(topologyMember.getBackup()); return factory; @@ -776,36 +683,19 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery return null; } - public ClientSessionFactory createSessionFactory(final TransportConfiguration transportConfiguration) throws Exception - { + public ClientSessionFactory createSessionFactory(final TransportConfiguration transportConfiguration) throws Exception { assertOpen(); initialise(); - ClientSessionFactoryInternal factory = new ClientSessionFactoryImpl(this, - transportConfiguration, - callTimeout, - callFailoverTimeout, - clientFailureCheckPeriod, - connectionTTL, - retryInterval, - retryIntervalMultiplier, - maxRetryInterval, - reconnectAttempts, - threadPool, - scheduledThreadPool, - incomingInterceptors, - outgoingInterceptors); + ClientSessionFactoryInternal factory = new ClientSessionFactoryImpl(this, transportConfiguration, callTimeout, callFailoverTimeout, clientFailureCheckPeriod, connectionTTL, retryInterval, retryIntervalMultiplier, maxRetryInterval, reconnectAttempts, threadPool, scheduledThreadPool, incomingInterceptors, outgoingInterceptors); addToConnecting(factory); - try - { - try - { + try { + try { factory.connect(reconnectAttempts, failoverOnInitialConnection); } - catch (ActiveMQException e1) - { + catch (ActiveMQException e1) { //we need to make sure is closed just for garbage collection factory.close(); throw e1; @@ -813,42 +703,26 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery addFactory(factory); return factory; } - finally - { + finally { removeFromConnecting(factory); } } - public ClientSessionFactory createSessionFactory(final TransportConfiguration transportConfiguration, int reconnectAttempts, boolean failoverOnInitialConnection) throws Exception - { + public ClientSessionFactory createSessionFactory(final TransportConfiguration transportConfiguration, + int reconnectAttempts, + boolean failoverOnInitialConnection) throws Exception { assertOpen(); initialise(); - ClientSessionFactoryInternal factory = new ClientSessionFactoryImpl(this, - transportConfiguration, - callTimeout, - callFailoverTimeout, - clientFailureCheckPeriod, - connectionTTL, - retryInterval, - retryIntervalMultiplier, - maxRetryInterval, - reconnectAttempts, - threadPool, - scheduledThreadPool, - incomingInterceptors, - outgoingInterceptors); + ClientSessionFactoryInternal factory = new ClientSessionFactoryImpl(this, transportConfiguration, callTimeout, callFailoverTimeout, clientFailureCheckPeriod, connectionTTL, retryInterval, retryIntervalMultiplier, maxRetryInterval, reconnectAttempts, threadPool, scheduledThreadPool, incomingInterceptors, outgoingInterceptors); addToConnecting(factory); - try - { - try - { + try { + try { factory.connect(reconnectAttempts, failoverOnInitialConnection); } - catch (ActiveMQException e1) - { + catch (ActiveMQException e1) { //we need to make sure is closed just for garbage collection factory.close(); throw e1; @@ -856,147 +730,108 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery addFactory(factory); return factory; } - finally - { + finally { removeFromConnecting(factory); } } - private void removeFromConnecting(ClientSessionFactoryInternal factory) - { - synchronized (connectingFactories) - { + private void removeFromConnecting(ClientSessionFactoryInternal factory) { + synchronized (connectingFactories) { connectingFactories.remove(factory); } } - private void addToConnecting(ClientSessionFactoryInternal factory) - { - synchronized (connectingFactories) - { + private void addToConnecting(ClientSessionFactoryInternal factory) { + synchronized (connectingFactories) { assertOpen(); connectingFactories.add(factory); } } - public ClientSessionFactory createSessionFactory() throws ActiveMQException - { + public ClientSessionFactory createSessionFactory() throws ActiveMQException { assertOpen(); initialise(); - if (this.getNumInitialConnectors() == 0 && discoveryGroup != null) - { + if (this.getNumInitialConnectors() == 0 && discoveryGroup != null) { // Wait for an initial broadcast to give us at least one node in the cluster long timeout = clusterConnection ? 0 : discoveryGroupConfiguration.getDiscoveryInitialWaitTimeout(); boolean ok = discoveryGroup.waitForBroadcast(timeout); - if (!ok) - { + if (!ok) { throw ActiveMQClientMessageBundle.BUNDLE.connectionTimedOutInInitialBroadcast(); } } ClientSessionFactoryInternal factory = null; - synchronized (this) - { + synchronized (this) { boolean retry; int attempts = 0; - do - { + do { retry = false; TransportConfiguration tc = selectConnector(); - if (tc == null) - { + if (tc == null) { throw ActiveMQClientMessageBundle.BUNDLE.noTCForSessionFactory(); } // try each factory in the list until we find one which works - try - { - factory = new ClientSessionFactoryImpl(this, - tc, - callTimeout, - callFailoverTimeout, - clientFailureCheckPeriod, - connectionTTL, - retryInterval, - retryIntervalMultiplier, - maxRetryInterval, - reconnectAttempts, - threadPool, - scheduledThreadPool, - incomingInterceptors, - outgoingInterceptors); - try - { + try { + factory = new ClientSessionFactoryImpl(this, tc, callTimeout, callFailoverTimeout, clientFailureCheckPeriod, connectionTTL, retryInterval, retryIntervalMultiplier, maxRetryInterval, reconnectAttempts, threadPool, scheduledThreadPool, incomingInterceptors, outgoingInterceptors); + try { addToConnecting(factory); factory.connect(initialConnectAttempts, failoverOnInitialConnection); } - finally - { + finally { removeFromConnecting(factory); } } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { factory.close(); factory = null; - if (e.getType() == ActiveMQExceptionType.NOT_CONNECTED) - { + if (e.getType() == ActiveMQExceptionType.NOT_CONNECTED) { attempts++; - synchronized (topologyArrayGuard) - { + synchronized (topologyArrayGuard) { - if (topologyArray != null && attempts == topologyArray.length) - { + if (topologyArray != null && attempts == topologyArray.length) { throw ActiveMQClientMessageBundle.BUNDLE.cannotConnectToServers(); } - if (topologyArray == null && attempts == this.getNumInitialConnectors()) - { + if (topologyArray == null && attempts == this.getNumInitialConnectors()) { throw ActiveMQClientMessageBundle.BUNDLE.cannotConnectToServers(); } } retry = true; } - else - { + else { throw e; } } - } - while (retry); + } while (retry); // We always wait for the topology, as the server // will send a single element if not cluster // so clients can know the id of the server they are connected to final long timeout = System.currentTimeMillis() + callTimeout; - while (!isClosed() && !receivedTopology && timeout > System.currentTimeMillis()) - { + while (!isClosed() && !receivedTopology && timeout > System.currentTimeMillis()) { // Now wait for the topology - try - { + try { wait(1000); } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } } - // We are waiting for the topology here, // however to avoid a race where the connection is closed (and receivedtopology set to true) // between the wait and this timeout here, we redo the check for timeout. // if this becomes false there's no big deal and we will just ignore the issue // notice that we can't add more locks here otherwise there wouldn't be able to avoid a deadlock final boolean hasTimedOut = timeout > System.currentTimeMillis(); - if (!hasTimedOut && !receivedTopology) - { + if (!hasTimedOut && !receivedTopology) { if (factory != null) factory.cleanup(); throw ActiveMQClientMessageBundle.BUNDLE.connectionTimedOutOnReceiveTopology(discoveryGroup); @@ -1009,487 +844,403 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery } - public boolean isHA() - { + public boolean isHA() { return ha; } - public boolean isCacheLargeMessagesClient() - { + public boolean isCacheLargeMessagesClient() { return cacheLargeMessagesClient; } - public ServerLocatorImpl setCacheLargeMessagesClient(final boolean cached) - { + public ServerLocatorImpl setCacheLargeMessagesClient(final boolean cached) { cacheLargeMessagesClient = cached; return this; } - public long getClientFailureCheckPeriod() - { + public long getClientFailureCheckPeriod() { return clientFailureCheckPeriod; } - public ServerLocatorImpl setClientFailureCheckPeriod(final long clientFailureCheckPeriod) - { + public ServerLocatorImpl setClientFailureCheckPeriod(final long clientFailureCheckPeriod) { checkWrite(); this.clientFailureCheckPeriod = clientFailureCheckPeriod; return this; } - public long getConnectionTTL() - { + public long getConnectionTTL() { return connectionTTL; } - public ServerLocatorImpl setConnectionTTL(final long connectionTTL) - { + public ServerLocatorImpl setConnectionTTL(final long connectionTTL) { checkWrite(); this.connectionTTL = connectionTTL; return this; } - public long getCallTimeout() - { + public long getCallTimeout() { return callTimeout; } - public ServerLocatorImpl setCallTimeout(final long callTimeout) - { + public ServerLocatorImpl setCallTimeout(final long callTimeout) { checkWrite(); this.callTimeout = callTimeout; return this; } - public long getCallFailoverTimeout() - { + public long getCallFailoverTimeout() { return callFailoverTimeout; } - public ServerLocatorImpl setCallFailoverTimeout(long callFailoverTimeout) - { + public ServerLocatorImpl setCallFailoverTimeout(long callFailoverTimeout) { checkWrite(); this.callFailoverTimeout = callFailoverTimeout; return this; } - public int getMinLargeMessageSize() - { + public int getMinLargeMessageSize() { return minLargeMessageSize; } - public ServerLocatorImpl setMinLargeMessageSize(final int minLargeMessageSize) - { + public ServerLocatorImpl setMinLargeMessageSize(final int minLargeMessageSize) { checkWrite(); this.minLargeMessageSize = minLargeMessageSize; return this; } - public int getConsumerWindowSize() - { + public int getConsumerWindowSize() { return consumerWindowSize; } - public ServerLocatorImpl setConsumerWindowSize(final int consumerWindowSize) - { + public ServerLocatorImpl setConsumerWindowSize(final int consumerWindowSize) { checkWrite(); this.consumerWindowSize = consumerWindowSize; return this; } - public int getConsumerMaxRate() - { + public int getConsumerMaxRate() { return consumerMaxRate; } - public ServerLocatorImpl setConsumerMaxRate(final int consumerMaxRate) - { + public ServerLocatorImpl setConsumerMaxRate(final int consumerMaxRate) { checkWrite(); this.consumerMaxRate = consumerMaxRate; return this; } - public int getConfirmationWindowSize() - { + public int getConfirmationWindowSize() { return confirmationWindowSize; } - public ServerLocatorImpl setConfirmationWindowSize(final int confirmationWindowSize) - { + public ServerLocatorImpl setConfirmationWindowSize(final int confirmationWindowSize) { checkWrite(); this.confirmationWindowSize = confirmationWindowSize; return this; } - public int getProducerWindowSize() - { + public int getProducerWindowSize() { return producerWindowSize; } - public ServerLocatorImpl setProducerWindowSize(final int producerWindowSize) - { + public ServerLocatorImpl setProducerWindowSize(final int producerWindowSize) { checkWrite(); this.producerWindowSize = producerWindowSize; return this; } - public int getProducerMaxRate() - { + public int getProducerMaxRate() { return producerMaxRate; } - public ServerLocatorImpl setProducerMaxRate(final int producerMaxRate) - { + public ServerLocatorImpl setProducerMaxRate(final int producerMaxRate) { checkWrite(); this.producerMaxRate = producerMaxRate; return this; } - public boolean isBlockOnAcknowledge() - { + public boolean isBlockOnAcknowledge() { return blockOnAcknowledge; } - public ServerLocatorImpl setBlockOnAcknowledge(final boolean blockOnAcknowledge) - { + public ServerLocatorImpl setBlockOnAcknowledge(final boolean blockOnAcknowledge) { checkWrite(); this.blockOnAcknowledge = blockOnAcknowledge; return this; } - public boolean isBlockOnDurableSend() - { + public boolean isBlockOnDurableSend() { return blockOnDurableSend; } - public ServerLocatorImpl setBlockOnDurableSend(final boolean blockOnDurableSend) - { + public ServerLocatorImpl setBlockOnDurableSend(final boolean blockOnDurableSend) { checkWrite(); this.blockOnDurableSend = blockOnDurableSend; return this; } - public boolean isBlockOnNonDurableSend() - { + public boolean isBlockOnNonDurableSend() { return blockOnNonDurableSend; } - public ServerLocatorImpl setBlockOnNonDurableSend(final boolean blockOnNonDurableSend) - { + public ServerLocatorImpl setBlockOnNonDurableSend(final boolean blockOnNonDurableSend) { checkWrite(); this.blockOnNonDurableSend = blockOnNonDurableSend; return this; } - public boolean isAutoGroup() - { + public boolean isAutoGroup() { return autoGroup; } - public ServerLocatorImpl setAutoGroup(final boolean autoGroup) - { + public ServerLocatorImpl setAutoGroup(final boolean autoGroup) { checkWrite(); this.autoGroup = autoGroup; return this; } - public boolean isPreAcknowledge() - { + public boolean isPreAcknowledge() { return preAcknowledge; } - public ServerLocatorImpl setPreAcknowledge(final boolean preAcknowledge) - { + public ServerLocatorImpl setPreAcknowledge(final boolean preAcknowledge) { checkWrite(); this.preAcknowledge = preAcknowledge; return this; } - public int getAckBatchSize() - { + public int getAckBatchSize() { return ackBatchSize; } - public ServerLocatorImpl setAckBatchSize(final int ackBatchSize) - { + public ServerLocatorImpl setAckBatchSize(final int ackBatchSize) { checkWrite(); this.ackBatchSize = ackBatchSize; return this; } - public boolean isUseGlobalPools() - { + public boolean isUseGlobalPools() { return useGlobalPools; } - public ServerLocatorImpl setUseGlobalPools(final boolean useGlobalPools) - { + public ServerLocatorImpl setUseGlobalPools(final boolean useGlobalPools) { checkWrite(); this.useGlobalPools = useGlobalPools; return this; } - public int getScheduledThreadPoolMaxSize() - { + public int getScheduledThreadPoolMaxSize() { return scheduledThreadPoolMaxSize; } - public ServerLocatorImpl setScheduledThreadPoolMaxSize(final int scheduledThreadPoolMaxSize) - { + public ServerLocatorImpl setScheduledThreadPoolMaxSize(final int scheduledThreadPoolMaxSize) { checkWrite(); this.scheduledThreadPoolMaxSize = scheduledThreadPoolMaxSize; return this; } - public int getThreadPoolMaxSize() - { + public int getThreadPoolMaxSize() { return threadPoolMaxSize; } - public ServerLocatorImpl setThreadPoolMaxSize(final int threadPoolMaxSize) - { + public ServerLocatorImpl setThreadPoolMaxSize(final int threadPoolMaxSize) { checkWrite(); this.threadPoolMaxSize = threadPoolMaxSize; return this; } - public long getRetryInterval() - { + public long getRetryInterval() { return retryInterval; } - public ServerLocatorImpl setRetryInterval(final long retryInterval) - { + public ServerLocatorImpl setRetryInterval(final long retryInterval) { checkWrite(); this.retryInterval = retryInterval; return this; } - public long getMaxRetryInterval() - { + public long getMaxRetryInterval() { return maxRetryInterval; } - public ServerLocatorImpl setMaxRetryInterval(final long retryInterval) - { + public ServerLocatorImpl setMaxRetryInterval(final long retryInterval) { checkWrite(); maxRetryInterval = retryInterval; return this; } - public double getRetryIntervalMultiplier() - { + public double getRetryIntervalMultiplier() { return retryIntervalMultiplier; } - public ServerLocatorImpl setRetryIntervalMultiplier(final double retryIntervalMultiplier) - { + public ServerLocatorImpl setRetryIntervalMultiplier(final double retryIntervalMultiplier) { checkWrite(); this.retryIntervalMultiplier = retryIntervalMultiplier; return this; } - public int getReconnectAttempts() - { + public int getReconnectAttempts() { return reconnectAttempts; } - public ServerLocatorImpl setReconnectAttempts(final int reconnectAttempts) - { + public ServerLocatorImpl setReconnectAttempts(final int reconnectAttempts) { checkWrite(); this.reconnectAttempts = reconnectAttempts; return this; } - public ServerLocatorImpl setInitialConnectAttempts(int initialConnectAttempts) - { + public ServerLocatorImpl setInitialConnectAttempts(int initialConnectAttempts) { checkWrite(); this.initialConnectAttempts = initialConnectAttempts; return this; } - public int getInitialConnectAttempts() - { + public int getInitialConnectAttempts() { return initialConnectAttempts; } - public boolean isFailoverOnInitialConnection() - { + public boolean isFailoverOnInitialConnection() { return this.failoverOnInitialConnection; } - public ServerLocatorImpl setFailoverOnInitialConnection(final boolean failover) - { + public ServerLocatorImpl setFailoverOnInitialConnection(final boolean failover) { checkWrite(); this.failoverOnInitialConnection = failover; return this; } - public String getConnectionLoadBalancingPolicyClassName() - { + public String getConnectionLoadBalancingPolicyClassName() { return connectionLoadBalancingPolicyClassName; } - public ServerLocatorImpl setConnectionLoadBalancingPolicyClassName(final String loadBalancingPolicyClassName) - { + public ServerLocatorImpl setConnectionLoadBalancingPolicyClassName(final String loadBalancingPolicyClassName) { checkWrite(); connectionLoadBalancingPolicyClassName = loadBalancingPolicyClassName; return this; } - public TransportConfiguration[] getStaticTransportConfigurations() - { - if (initialConnectors == null) return new TransportConfiguration[]{}; + public TransportConfiguration[] getStaticTransportConfigurations() { + if (initialConnectors == null) + return new TransportConfiguration[]{}; return Arrays.copyOf(initialConnectors, initialConnectors.length); } - public DiscoveryGroupConfiguration getDiscoveryGroupConfiguration() - { + public DiscoveryGroupConfiguration getDiscoveryGroupConfiguration() { return discoveryGroupConfiguration; } - public ServerLocatorImpl addIncomingInterceptor(final Interceptor interceptor) - { + public ServerLocatorImpl addIncomingInterceptor(final Interceptor interceptor) { incomingInterceptors.add(interceptor); return this; } - public ServerLocatorImpl addOutgoingInterceptor(final Interceptor interceptor) - { + public ServerLocatorImpl addOutgoingInterceptor(final Interceptor interceptor) { outgoingInterceptors.add(interceptor); return this; } - public boolean removeIncomingInterceptor(final Interceptor interceptor) - { + public boolean removeIncomingInterceptor(final Interceptor interceptor) { return incomingInterceptors.remove(interceptor); } - public boolean removeOutgoingInterceptor(final Interceptor interceptor) - { + public boolean removeOutgoingInterceptor(final Interceptor interceptor) { return outgoingInterceptors.remove(interceptor); } - public int getInitialMessagePacketSize() - { + public int getInitialMessagePacketSize() { return initialMessagePacketSize; } - public ServerLocatorImpl setInitialMessagePacketSize(final int size) - { + public ServerLocatorImpl setInitialMessagePacketSize(final int size) { checkWrite(); initialMessagePacketSize = size; return this; } - public ServerLocatorImpl setGroupID(final String groupID) - { + public ServerLocatorImpl setGroupID(final String groupID) { checkWrite(); this.groupID = groupID; return this; } - public String getGroupID() - { + public String getGroupID() { return groupID; } - public boolean isCompressLargeMessage() - { + public boolean isCompressLargeMessage() { return compressLargeMessage; } - public ServerLocatorImpl setCompressLargeMessage(boolean avoid) - { + public ServerLocatorImpl setCompressLargeMessage(boolean avoid) { this.compressLargeMessage = avoid; return this; } - private void checkWrite() - { - synchronized (stateGuard) - { - if (state != null && state != STATE.CLOSED) - { + private void checkWrite() { + synchronized (stateGuard) { + if (state != null && state != STATE.CLOSED) { throw new IllegalStateException("Cannot set attribute on SessionFactory after it has been used"); } } } - private int getNumInitialConnectors() - { - if (initialConnectors == null) return 0; + private int getNumInitialConnectors() { + if (initialConnectors == null) + return 0; return initialConnectors.length; } - public ServerLocatorImpl setIdentity(String identity) - { + public ServerLocatorImpl setIdentity(String identity) { this.identity = identity; return this; } - public ServerLocatorImpl setNodeID(String nodeID) - { + public ServerLocatorImpl setNodeID(String nodeID) { this.nodeID = nodeID; return this; } - public String getNodeID() - { + public String getNodeID() { return nodeID; } - public ServerLocatorImpl setClusterConnection(boolean clusterConnection) - { + public ServerLocatorImpl setClusterConnection(boolean clusterConnection) { this.clusterConnection = clusterConnection; return this; } - public boolean isClusterConnection() - { + public boolean isClusterConnection() { return clusterConnection; } - public TransportConfiguration getClusterTransportConfiguration() - { + public TransportConfiguration getClusterTransportConfiguration() { return clusterTransportConfiguration; } - public ServerLocatorImpl setClusterTransportConfiguration(TransportConfiguration tc) - { + public ServerLocatorImpl setClusterTransportConfiguration(TransportConfiguration tc) { this.clusterTransportConfiguration = tc; return this; } @Override - protected void finalize() throws Throwable - { - if (finalizeCheck) - { + protected void finalize() throws Throwable { + if (finalizeCheck) { close(); } super.finalize(); } - public void cleanup() - { + public void cleanup() { doClose(false); } - public void close() - { + public void close() { doClose(true); } - private void doClose(final boolean sendClose) - { - synchronized (stateGuard) - { - if (state == STATE.CLOSED) - { - if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) - { + private void doClose(final boolean sendClose) { + synchronized (stateGuard) { + if (state == STATE.CLOSED) { + if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) { ActiveMQClientLogger.LOGGER.debug(this + " is already closed when calling closed"); } return; @@ -1500,108 +1251,83 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery if (latch != null) latch.countDown(); - synchronized (connectingFactories) - { - for (ClientSessionFactoryInternal csf : connectingFactories) - { + synchronized (connectingFactories) { + for (ClientSessionFactoryInternal csf : connectingFactories) { csf.causeExit(); } } - if (discoveryGroup != null) - { - synchronized (this) - { - try - { + if (discoveryGroup != null) { + synchronized (this) { + try { discoveryGroup.stop(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQClientLogger.LOGGER.failedToStopDiscovery(e); } } } - else - { + else { staticConnector.disconnect(); } - synchronized (connectingFactories) - { - for (ClientSessionFactoryInternal csf : connectingFactories) - { + synchronized (connectingFactories) { + for (ClientSessionFactoryInternal csf : connectingFactories) { csf.causeExit(); } - for (ClientSessionFactoryInternal csf : connectingFactories) - { + for (ClientSessionFactoryInternal csf : connectingFactories) { csf.close(); } connectingFactories.clear(); } Set clonedFactory; - synchronized (factories) - { + synchronized (factories) { clonedFactory = new HashSet(factories); factories.clear(); } - for (ClientSessionFactoryInternal factory : clonedFactory) - { + for (ClientSessionFactoryInternal factory : clonedFactory) { factory.causeExit(); } - for (ClientSessionFactory factory : clonedFactory) - { - if (sendClose) - { + for (ClientSessionFactory factory : clonedFactory) { + if (sendClose) { factory.close(); } - else - { + else { factory.cleanup(); } } - if (shutdownPool) - { - if (threadPool != null) - { + if (shutdownPool) { + if (threadPool != null) { threadPool.shutdown(); - try - { - if (!threadPool.awaitTermination(10000, TimeUnit.MILLISECONDS)) - { + try { + if (!threadPool.awaitTermination(10000, TimeUnit.MILLISECONDS)) { ActiveMQClientLogger.LOGGER.timedOutWaitingForTermination(); } } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } } - if (scheduledThreadPool != null) - { + if (scheduledThreadPool != null) { scheduledThreadPool.shutdown(); - try - { - if (!scheduledThreadPool.awaitTermination(10000, TimeUnit.MILLISECONDS)) - { + try { + if (!scheduledThreadPool.awaitTermination(10000, TimeUnit.MILLISECONDS)) { ActiveMQClientLogger.LOGGER.timedOutWaitingForScheduledPoolTermination(); } } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } } } - synchronized (stateGuard) - { + synchronized (stateGuard) { state = STATE.CLOSED; } } @@ -1612,42 +1338,33 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery * Look for callers of this method! */ @Override - public void notifyNodeDown(final long eventTime, final String nodeID) - { + public void notifyNodeDown(final long eventTime, final String nodeID) { - if (!ha) - { + if (!ha) { // there's no topology here return; } - if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) { ActiveMQClientLogger.LOGGER.trace("nodeDown " + this + " nodeID=" + nodeID + " as being down", new Exception("trace")); } topology.removeMember(eventTime, nodeID); - if (clusterConnection) - { + if (clusterConnection) { updateArraysAndPairs(); } - else - { - synchronized (topologyArrayGuard) - { - if (topology.isEmpty()) - { + else { + synchronized (topologyArrayGuard) { + if (topology.isEmpty()) { // Resetting the topology to its original condition as it was brand new receivedTopology = false; topologyArray = null; } - else - { + else { updateArraysAndPairs(); - if (topology.nodes() == 1 && topology.getMember(this.nodeID) != null) - { + if (topology.nodes() == 1 && topology.getMember(this.nodeID) != null) { // Resetting the topology to its original condition as it was brand new receivedTopology = false; } @@ -1662,10 +1379,8 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery final String backupGroupName, final String scaleDownGroupName, final Pair connectorPair, - final boolean last) - { - if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) - { + final boolean last) { + if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) { ActiveMQClientLogger.LOGGER.trace("NodeUp " + this + "::nodeID=" + nodeID + ", connectorPair=" + connectorPair, new Exception("trace")); } @@ -1675,26 +1390,21 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery TopologyMember actMember = topology.getMember(nodeID); - if (actMember != null && actMember.getLive() != null && actMember.getBackup() != null) - { + if (actMember != null && actMember.getLive() != null && actMember.getBackup() != null) { HashSet clonedFactories = new HashSet(); - synchronized (factories) - { + synchronized (factories) { clonedFactories.addAll(factories); } - for (ClientSessionFactory factory : clonedFactories) - { + for (ClientSessionFactory factory : clonedFactories) { ((ClientSessionFactoryInternal) factory).setBackupConnector(actMember.getLive(), actMember.getBackup()); } } updateArraysAndPairs(); - if (last) - { - synchronized (this) - { + if (last) { + synchronized (this) { receivedTopology = true; // Notify if waiting on getting topology notifyAll(); @@ -1703,10 +1413,8 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery } @Override - public String toString() - { - if (identity != null) - { + public String toString() { + if (identity != null) { return "ServerLocatorImpl (identity=" + identity + ") [initialConnectors=" + Arrays.toString(initialConnectors == null ? new TransportConfiguration[0] : initialConnectors) + @@ -1721,19 +1429,14 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery } @SuppressWarnings("unchecked") - private void updateArraysAndPairs() - { - synchronized (topologyArrayGuard) - { + private void updateArraysAndPairs() { + synchronized (topologyArrayGuard) { Collection membersCopy = topology.getMembers(); - Pair[] topologyArrayLocal = - (Pair[]) Array.newInstance(Pair.class, - membersCopy.size()); + Pair[] topologyArrayLocal = (Pair[]) Array.newInstance(Pair.class, membersCopy.size()); int count = 0; - for (TopologyMemberImpl pair : membersCopy) - { + for (TopologyMemberImpl pair : membersCopy) { topologyArrayLocal[count++] = pair.getConnector(); } @@ -1741,22 +1444,17 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery } } - public synchronized void connectorsChanged(List newConnectors) - { - if (receivedTopology) - { + public synchronized void connectorsChanged(List newConnectors) { + if (receivedTopology) { return; } - TransportConfiguration[] newInitialconnectors = (TransportConfiguration[]) Array.newInstance(TransportConfiguration.class, - newConnectors.size()); + TransportConfiguration[] newInitialconnectors = (TransportConfiguration[]) Array.newInstance(TransportConfiguration.class, newConnectors.size()); int count = 0; - for (DiscoveryEntry entry : newConnectors) - { + for (DiscoveryEntry entry : newConnectors) { newInitialconnectors[count++] = entry.getConnector(); - if (ha && topology.getMember(entry.getNodeID()) == null) - { + if (ha && topology.getMember(entry.getNodeID()) == null) { TopologyMemberImpl member = new TopologyMemberImpl(entry.getNodeID(), null, null, entry.getConnector(), null); // on this case we set it as zero as any update coming from server should be accepted topology.updateMember(0, entry.getNodeID(), member); @@ -1765,47 +1463,36 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery this.initialConnectors = newInitialconnectors.length == 0 ? null : newInitialconnectors; - if (clusterConnection && !receivedTopology && this.getNumInitialConnectors() > 0) - { + if (clusterConnection && !receivedTopology && this.getNumInitialConnectors() > 0) { // The node is alone in the cluster. We create a connection to the new node // to trigger the node notification to form the cluster. - Runnable connectRunnable = new Runnable() - { - public void run() - { - try - { + Runnable connectRunnable = new Runnable() { + public void run() { + try { connect(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { ActiveMQClientLogger.LOGGER.errorConnectingToNodes(e); } } }; - if (startExecutor != null) - { + if (startExecutor != null) { startExecutor.execute(connectRunnable); } - else - { + else { connectRunnable.run(); } } } - public void factoryClosed(final ClientSessionFactory factory) - { - synchronized (factories) - { + public void factoryClosed(final ClientSessionFactory factory) { + synchronized (factories) { factories.remove(factory); - if (!clusterConnection && factories.isEmpty()) - { + if (!clusterConnection && factories.isEmpty()) { // Go back to using the broadcast or static list - synchronized (topologyArrayGuard) - { + synchronized (topologyArrayGuard) { receivedTopology = false; topologyArray = null; @@ -1814,64 +1501,54 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery } } - public Topology getTopology() - { + public Topology getTopology() { return topology; } @Override - public boolean isConnectable() - { + public boolean isConnectable() { return getNumInitialConnectors() > 0 || getDiscoveryGroupConfiguration() != null; } - public ServerLocatorImpl addClusterTopologyListener(final ClusterTopologyListener listener) - { + public ServerLocatorImpl addClusterTopologyListener(final ClusterTopologyListener listener) { topology.addClusterTopologyListener(listener); return this; } - public void removeClusterTopologyListener(final ClusterTopologyListener listener) - { + public void removeClusterTopologyListener(final ClusterTopologyListener listener) { topology.removeClusterTopologyListener(listener); } - private void addFactory(ClientSessionFactoryInternal factory) - { - if (factory == null) - { + private void addFactory(ClientSessionFactoryInternal factory) { + if (factory == null) { return; } - if (isClosed()) - { + if (isClosed()) { factory.close(); return; } TransportConfiguration backup = null; - if (ha) - { + if (ha) { backup = topology.getBackupForConnector((Connector) factory.getConnector()); } factory.setBackupConnector(factory.getConnectorConfiguration(), backup); - synchronized (factories) - { + synchronized (factories) { factories.add(factory); } } - private final class StaticConnector implements Serializable - { + private final class StaticConnector implements Serializable { + private static final long serialVersionUID = 6772279632415242634L; private List connectors; - public ClientSessionFactory connect(boolean skipWarnings) throws ActiveMQException - { + public ClientSessionFactory connect(boolean skipWarnings) throws ActiveMQException { assertOpen(); initialise(); @@ -1880,39 +1557,29 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery createConnectors(); - try - { + try { int retryNumber = 0; - while (csf == null && !isClosed()) - { + while (csf == null && !isClosed()) { retryNumber++; - for (Connector conn : connectors) - { - if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) - { + for (Connector conn : connectors) { + if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) { ActiveMQClientLogger.LOGGER.debug(this + "::Submitting connect towards " + conn); } csf = conn.tryConnect(); - if (csf != null) - { - csf.getConnection().addFailureListener(new FailureListener() - { + if (csf != null) { + csf.getConnection().addFailureListener(new FailureListener() { // Case the node where the cluster connection was connected is gone, we need to restart the // connection @Override - public void connectionFailed(ActiveMQException exception, boolean failedOver) - { - if (clusterConnection && exception.getType() == ActiveMQExceptionType.DISCONNECTED) - { - try - { + public void connectionFailed(ActiveMQException exception, boolean failedOver) { + if (clusterConnection && exception.getType() == ActiveMQExceptionType.DISCONNECTED) { + try { ServerLocatorImpl.this.start(startExecutor); } - catch (Exception e) - { + catch (Exception e) { // There isn't much to be done if this happens here ActiveMQClientLogger.LOGGER.errorStartingLocator(e); } @@ -1920,33 +1587,31 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery } @Override - public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) - { + public void connectionFailed(final ActiveMQException me, + boolean failedOver, + String scaleDownTargetNodeID) { connectionFailed(me, failedOver); } @Override - public String toString() - { + public String toString() { return "FailureListener('restarts cluster connections')"; } }); - if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) { ActiveMQClientLogger.LOGGER.debug("Returning " + csf + - " after " + - retryNumber + - " retries on StaticConnector " + - ServerLocatorImpl.this); + " after " + + retryNumber + + " retries on StaticConnector " + + ServerLocatorImpl.this); } return csf; } } - if (initialConnectAttempts >= 0 && retryNumber > initialConnectAttempts) - { + if (initialConnectAttempts >= 0 && retryNumber > initialConnectAttempts) { break; } @@ -1955,23 +1620,20 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery } } - catch (RejectedExecutionException e) - { + catch (RejectedExecutionException e) { if (isClosed() || skipWarnings) return null; ActiveMQClientLogger.LOGGER.debug("Rejected execution", e); throw e; } - catch (Exception e) - { + catch (Exception e) { if (isClosed() || skipWarnings) return null; ActiveMQClientLogger.LOGGER.errorConnectingToNodes(e); throw ActiveMQClientMessageBundle.BUNDLE.cannotConnectToStaticConnectors(e); } - if (isClosed() || skipWarnings) - { + if (isClosed() || skipWarnings) { return null; } @@ -1979,37 +1641,18 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery throw ActiveMQClientMessageBundle.BUNDLE.cannotConnectToStaticConnectors2(); } - private synchronized void createConnectors() - { - if (connectors != null) - { - for (Connector conn : connectors) - { - if (conn != null) - { + private synchronized void createConnectors() { + if (connectors != null) { + for (Connector conn : connectors) { + if (conn != null) { conn.disconnect(); } } } connectors = new ArrayList(); - if (initialConnectors != null) - { - for (TransportConfiguration initialConnector : initialConnectors) - { - ClientSessionFactoryInternal factory = new ClientSessionFactoryImpl(ServerLocatorImpl.this, - initialConnector, - callTimeout, - callFailoverTimeout, - clientFailureCheckPeriod, - connectionTTL, - retryInterval, - retryIntervalMultiplier, - maxRetryInterval, - reconnectAttempts, - threadPool, - scheduledThreadPool, - incomingInterceptors, - outgoingInterceptors); + if (initialConnectors != null) { + for (TransportConfiguration initialConnector : initialConnectors) { + ClientSessionFactoryInternal factory = new ClientSessionFactoryImpl(ServerLocatorImpl.this, initialConnector, callTimeout, callFailoverTimeout, clientFailureCheckPeriod, connectionTTL, retryInterval, retryIntervalMultiplier, maxRetryInterval, reconnectAttempts, threadPool, scheduledThreadPool, incomingInterceptors, outgoingInterceptors); factory.disableFinalizeCheck(); @@ -2018,26 +1661,20 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery } } - public synchronized void disconnect() - { - if (connectors != null) - { - for (Connector connector : connectors) - { + public synchronized void disconnect() { + if (connectors != null) { + for (Connector connector : connectors) { connector.disconnect(); } } } @Override - protected void finalize() throws Throwable - { - if (!isClosed() && finalizeCheck) - { + protected void finalize() throws Throwable { + if (!isClosed() && finalizeCheck) { ActiveMQClientLogger.LOGGER.serverLocatorNotClosed(traceException, System.identityHashCode(this)); - if (ServerLocatorImpl.finalizeCallback != null) - { + if (ServerLocatorImpl.finalizeCallback != null) { ServerLocatorImpl.finalizeCallback.run(); } @@ -2047,53 +1684,43 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery super.finalize(); } - private final class Connector - { + private final class Connector { + private final TransportConfiguration initialConnector; private volatile ClientSessionFactoryInternal factory; - public Connector(TransportConfiguration initialConnector, ClientSessionFactoryInternal factory) - { + public Connector(TransportConfiguration initialConnector, ClientSessionFactoryInternal factory) { this.initialConnector = initialConnector; this.factory = factory; } - public ClientSessionFactory tryConnect() throws ActiveMQException - { - if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) - { + public ClientSessionFactory tryConnect() throws ActiveMQException { + if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) { ActiveMQClientLogger.LOGGER.debug(this + "::Trying to connect to " + factory); } - try - { + try { ClientSessionFactoryInternal factoryToUse = factory; - if (factoryToUse != null) - { + if (factoryToUse != null) { addToConnecting(factoryToUse); - try - { + try { factoryToUse.connect(1, false); } - finally - { + finally { removeFromConnecting(factoryToUse); } } return factoryToUse; } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { ActiveMQClientLogger.LOGGER.debug(this + "::Exception on establish connector initial connection", e); return null; } } - public void disconnect() - { - if (factory != null) - { + public void disconnect() { + if (factory != null) { factory.causeExit(); factory.cleanup(); factory = null; @@ -2101,35 +1728,28 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery } @Override - public String toString() - { + public String toString() { return "Connector [initialConnector=" + initialConnector + "]"; } } } - private void assertOpen() - { - synchronized (stateGuard) - { - if (state != null && state != STATE.INITIALIZED) - { + private void assertOpen() { + synchronized (stateGuard) { + if (state != null && state != STATE.INITIALIZED) { throw new IllegalStateException("Server locator is closed (maybe it was garbage collected)"); } } } - public boolean isClosed() - { - synchronized (stateGuard) - { + public boolean isClosed() { + synchronized (stateGuard) { return state != STATE.INITIALIZED; } } - private Object writeReplace() throws ObjectStreamException - { + private Object writeReplace() throws ObjectStreamException { ServerLocatorImpl clone = new ServerLocatorImpl(this); return clone; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ServerLocatorInternal.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ServerLocatorInternal.java index f805ca0d11..42da78964f 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ServerLocatorInternal.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ServerLocatorInternal.java @@ -25,8 +25,8 @@ import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.api.core.Pair; import org.apache.activemq.artemis.spi.core.remoting.ClientProtocolManager; -public interface ServerLocatorInternal extends ServerLocator -{ +public interface ServerLocatorInternal extends ServerLocator { + void start(Executor executor) throws Exception; void factoryClosed(final ClientSessionFactory factory); @@ -35,9 +35,11 @@ public interface ServerLocatorInternal extends ServerLocator ServerLocatorInternal setAfterConnectionInternalListener(AfterConnectInternalListener listener); - /** Used to better identify Cluster Connection Locators on logs. To facilitate eventual debugging. + /** + * Used to better identify Cluster Connection Locators on logs. To facilitate eventual debugging. * - * This method used to be on tests interface, but I'm now making it part of the public interface since*/ + * This method used to be on tests interface, but I'm now making it part of the public interface since + */ ServerLocatorInternal setIdentity(String identity); ServerLocatorInternal setNodeID(String nodeID); @@ -53,15 +55,19 @@ public interface ServerLocatorInternal extends ServerLocator /** * Like {@link #connect()} but it does not log warnings if it fails to connect. + * * @throws ActiveMQException */ ClientSessionFactoryInternal connectNoWarnings() throws ActiveMQException; - void notifyNodeUp(long uniqueEventID, String nodeID, String backupGroupName, String scaleDownGroupName, - Pair connectorPair, boolean last); + void notifyNodeUp(long uniqueEventID, + String nodeID, + String backupGroupName, + String scaleDownGroupName, + Pair connectorPair, + boolean last); /** - * * @param uniqueEventID 0 means get the previous ID +1 * @param nodeID */ diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/Topology.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/Topology.java index 2c181c5274..83c327e3df 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/Topology.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/Topology.java @@ -31,8 +31,7 @@ import org.apache.activemq.artemis.api.core.client.ClusterTopologyListener; import org.apache.activemq.artemis.core.client.ActiveMQClientLogger; import org.apache.activemq.artemis.spi.core.remoting.Connector; -public final class Topology -{ +public final class Topology { private final Set topologyListeners; @@ -57,75 +56,62 @@ public final class Topology private Map mapDelete; - private static final class DirectExecutor implements Executor - { - public void execute(final Runnable runnable) - { + private static final class DirectExecutor implements Executor { + + public void execute(final Runnable runnable) { runnable.run(); } } - public Topology(final Object owner) - { + + public Topology(final Object owner) { this(owner, new DirectExecutor()); } - public Topology(final Object owner, final Executor executor) - { + public Topology(final Object owner, final Executor executor) { this.topologyListeners = new HashSet<>(); this.topology = new ConcurrentHashMap<>(); - if (executor == null) - { + if (executor == null) { throw new IllegalArgumentException("Executor is required"); } this.executor = executor; this.owner = owner; - if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) - { - ActiveMQClientLogger.LOGGER.trace("Topology@" + Integer.toHexString(System.identityHashCode(this)) + " CREATE", - new Exception("trace")); + if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) { + ActiveMQClientLogger.LOGGER.trace("Topology@" + Integer.toHexString(System.identityHashCode(this)) + " CREATE", new Exception("trace")); } } /** * It will remove all elements as if it haven't received anyone from the server. */ - public void clear() - { + public void clear() { topology.clear(); } - public void addClusterTopologyListener(final ClusterTopologyListener listener) - { - if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) - { + public void addClusterTopologyListener(final ClusterTopologyListener listener) { + if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) { ActiveMQClientLogger.LOGGER.trace(this + "::Adding topology listener " + listener, new Exception("Trace")); } - synchronized (topologyListeners) - { + synchronized (topologyListeners) { topologyListeners.add(listener); } this.sendTopology(listener); } - public void removeClusterTopologyListener(final ClusterTopologyListener listener) - { - if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) - { + public void removeClusterTopologyListener(final ClusterTopologyListener listener) { + if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) { ActiveMQClientLogger.LOGGER.trace(this + "::Removing topology listener " + listener, new Exception("Trace")); } - synchronized (topologyListeners) - { + synchronized (topologyListeners) { topologyListeners.remove(listener); } } - /** This is called by the server when the node is activated from backup state. It will always succeed */ - public void updateAsLive(final String nodeId, final TopologyMemberImpl memberInput) - { - synchronized (this) - { - if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) - { + /** + * This is called by the server when the node is activated from backup state. It will always succeed + */ + public void updateAsLive(final String nodeId, final TopologyMemberImpl memberInput) { + synchronized (this) { + if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) { ActiveMQClientLogger.LOGGER.debug(this + "::node " + nodeId + "=" + memberInput); } memberInput.setUniqueEventID(System.currentTimeMillis()); @@ -137,48 +123,40 @@ public final class Topology /** * After the node is started, it will resend the notifyLive a couple of times to avoid gossip between two servers + * * @param nodeId */ - public void resendNode(final String nodeId) - { - synchronized (this) - { + public void resendNode(final String nodeId) { + synchronized (this) { TopologyMemberImpl memberInput = topology.get(nodeId); - if (memberInput != null) - { + if (memberInput != null) { memberInput.setUniqueEventID(System.currentTimeMillis()); sendMemberUp(nodeId, memberInput); } } } - /** This is called by the server when the node is activated from backup state. It will always succeed */ - public TopologyMemberImpl updateBackup(final TopologyMemberImpl memberInput) - { + /** + * This is called by the server when the node is activated from backup state. It will always succeed + */ + public TopologyMemberImpl updateBackup(final TopologyMemberImpl memberInput) { final String nodeId = memberInput.getNodeId(); - if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) { ActiveMQClientLogger.LOGGER.trace(this + "::updateBackup::" + nodeId + ", memberInput=" + memberInput); } - synchronized (this) - { + synchronized (this) { TopologyMemberImpl currentMember = getMember(nodeId); - if (currentMember == null) - { - if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) - { - ActiveMQClientLogger.LOGGER.trace("There's no live to be updated on backup update, node=" + nodeId + " memberInput=" + memberInput, - new Exception("trace")); + if (currentMember == null) { + if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) { + ActiveMQClientLogger.LOGGER.trace("There's no live to be updated on backup update, node=" + nodeId + " memberInput=" + memberInput, new Exception("trace")); } currentMember = memberInput; topology.put(nodeId, currentMember); } - TopologyMemberImpl newMember = - new TopologyMemberImpl(nodeId, currentMember.getBackupGroupName(), currentMember.getScaleDownGroupName(), currentMember.getLive(), - memberInput.getBackup()); + TopologyMemberImpl newMember = new TopologyMemberImpl(nodeId, currentMember.getBackupGroupName(), currentMember.getScaleDownGroupName(), currentMember.getLive(), memberInput.getBackup()); newMember.setUniqueEventID(System.currentTimeMillis()); topology.remove(nodeId); topology.put(nodeId, newMember); @@ -190,64 +168,51 @@ public final class Topology /** * @param uniqueEventID an unique identifier for when the change was made. We will use current - * time millis for starts, and a ++ of that number for shutdown. + * time millis for starts, and a ++ of that number for shutdown. * @param nodeId * @param memberInput * @return {@code true} if an update did take place. Note that backups are *always* updated. */ - public boolean updateMember(final long uniqueEventID, final String nodeId, final TopologyMemberImpl memberInput) - { + public boolean updateMember(final long uniqueEventID, final String nodeId, final TopologyMemberImpl memberInput) { Long deleteTme = getMapDelete().get(nodeId); - if (deleteTme != null && uniqueEventID != 0 && uniqueEventID < deleteTme) - { + if (deleteTme != null && uniqueEventID != 0 && uniqueEventID < deleteTme) { ActiveMQClientLogger.LOGGER.debug("Update uniqueEvent=" + uniqueEventID + - ", nodeId=" + - nodeId + - ", memberInput=" + - memberInput + - " being rejected as there was a delete done after that"); + ", nodeId=" + + nodeId + + ", memberInput=" + + memberInput + + " being rejected as there was a delete done after that"); return false; } - synchronized (this) - { + synchronized (this) { TopologyMemberImpl currentMember = topology.get(nodeId); - if (currentMember == null) - { - if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) - { - ActiveMQClientLogger.LOGGER.trace(this + "::NewMemberAdd nodeId=" + nodeId + " member = " + memberInput, - new Exception("trace")); + if (currentMember == null) { + if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) { + ActiveMQClientLogger.LOGGER.trace(this + "::NewMemberAdd nodeId=" + nodeId + " member = " + memberInput, new Exception("trace")); } memberInput.setUniqueEventID(uniqueEventID); topology.put(nodeId, memberInput); sendMemberUp(nodeId, memberInput); return true; } - if (uniqueEventID > currentMember.getUniqueEventID()) - { - TopologyMemberImpl newMember = - new TopologyMemberImpl(nodeId, memberInput.getBackupGroupName(), memberInput.getScaleDownGroupName(), memberInput.getLive(), - memberInput.getBackup()); + if (uniqueEventID > currentMember.getUniqueEventID()) { + TopologyMemberImpl newMember = new TopologyMemberImpl(nodeId, memberInput.getBackupGroupName(), memberInput.getScaleDownGroupName(), memberInput.getLive(), memberInput.getBackup()); - if (newMember.getLive() == null && currentMember.getLive() != null) - { + if (newMember.getLive() == null && currentMember.getLive() != null) { newMember.setLive(currentMember.getLive()); } - if (newMember.getBackup() == null && currentMember.getBackup() != null) - { + if (newMember.getBackup() == null && currentMember.getBackup() != null) { newMember.setBackup(currentMember.getBackup()); } - if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) { ActiveMQClientLogger.LOGGER.trace(this + "::updated currentMember=nodeID=" + nodeId + ", currentMember=" + - currentMember + ", memberInput=" + memberInput + "newMember=" + - newMember, - new Exception("trace")); + currentMember + ", memberInput=" + memberInput + "newMember=" + + newMember, new Exception("trace")); } newMember.setUniqueEventID(uniqueEventID); @@ -261,8 +226,7 @@ public final class Topology * always add the backup, better to try to reconnect to something that's not there then to * not know about it at all */ - if (currentMember.getBackup() == null && memberInput.getBackup() != null) - { + if (currentMember.getBackup() == null && memberInput.getBackup() != null) { currentMember.setBackup(memberInput.getBackup()); } return false; @@ -273,39 +237,30 @@ public final class Topology * @param nodeId * @param memberToSend */ - private void sendMemberUp(final String nodeId, final TopologyMemberImpl memberToSend) - { + private void sendMemberUp(final String nodeId, final TopologyMemberImpl memberToSend) { final ArrayList copy = copyListeners(); - if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) { ActiveMQClientLogger.LOGGER.trace(this + "::prepare to send " + nodeId + " to " + copy.size() + " elements"); } - if (copy.size() > 0) - { - executor.execute(new Runnable() - { - public void run() - { - for (ClusterTopologyListener listener : copy) - { - if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) - { + if (copy.size() > 0) { + executor.execute(new Runnable() { + public void run() { + for (ClusterTopologyListener listener : copy) { + if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) { ActiveMQClientLogger.LOGGER.trace(Topology.this + " informing " + - listener + - " about node up = " + - nodeId + - " connector = " + - memberToSend.getConnector()); + listener + + " about node up = " + + nodeId + + " connector = " + + memberToSend.getConnector()); } - try - { + try { listener.nodeUP(memberToSend, false); } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQClientLogger.LOGGER.errorSendingTopology(e); } } @@ -317,69 +272,54 @@ public final class Topology /** * @return */ - private ArrayList copyListeners() - { + private ArrayList copyListeners() { ArrayList listenersCopy; - synchronized (topologyListeners) - { + synchronized (topologyListeners) { listenersCopy = new ArrayList<>(topologyListeners); } return listenersCopy; } - boolean removeMember(final long uniqueEventID, final String nodeId) - { + boolean removeMember(final long uniqueEventID, final String nodeId) { TopologyMemberImpl member; - synchronized (this) - { + synchronized (this) { member = topology.get(nodeId); - if (member != null) - { - if (member.getUniqueEventID() > uniqueEventID) - { + if (member != null) { + if (member.getUniqueEventID() > uniqueEventID) { ActiveMQClientLogger.LOGGER.debug("The removeMember was issued before the node " + nodeId + " was started, ignoring call"); member = null; } - else - { + else { getMapDelete().put(nodeId, uniqueEventID); member = topology.remove(nodeId); } } } - if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) { ActiveMQClientLogger.LOGGER.trace("removeMember " + this + - " removing nodeID=" + - nodeId + - ", result=" + - member + - ", size = " + - topology.size(), new Exception("trace")); + " removing nodeID=" + + nodeId + + ", result=" + + member + + ", size = " + + topology.size(), new Exception("trace")); } - if (member != null) - { + if (member != null) { final ArrayList copy = copyListeners(); - executor.execute(new Runnable() - { - public void run() - { - for (ClusterTopologyListener listener : copy) - { - if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) - { + executor.execute(new Runnable() { + public void run() { + for (ClusterTopologyListener listener : copy) { + if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) { ActiveMQClientLogger.LOGGER.trace(this + " informing " + listener + " about node down = " + nodeId); } - try - { + try { listener.nodeDown(uniqueEventID, nodeId); } - catch (Exception e) - { + catch (Exception e) { ActiveMQClientLogger.LOGGER.errorSendingTopologyNodedown(e); } } @@ -389,36 +329,29 @@ public final class Topology return member != null; } - public synchronized void sendTopology(final ClusterTopologyListener listener) - { - if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) - { + public synchronized void sendTopology(final ClusterTopologyListener listener) { + if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) { ActiveMQClientLogger.LOGGER.debug(this + " is sending topology to " + listener); } - executor.execute(new Runnable() - { - public void run() - { + executor.execute(new Runnable() { + public void run() { int count = 0; final Map copy; - synchronized (Topology.this) - { + synchronized (Topology.this) { copy = new HashMap(topology); } - for (Map.Entry entry : copy.entrySet()) - { - if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) - { + for (Map.Entry entry : copy.entrySet()) { + if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) { ActiveMQClientLogger.LOGGER.debug(Topology.this + " sending " + - entry.getKey() + - " / " + - entry.getValue().getConnector() + - " to " + - listener); + entry.getKey() + + " / " + + entry.getValue().getConnector() + + " to " + + listener); } listener.nodeUP(entry.getValue(), ++count == copy.size()); } @@ -426,17 +359,13 @@ public final class Topology }); } - public synchronized TopologyMemberImpl getMember(final String nodeID) - { + public synchronized TopologyMemberImpl getMember(final String nodeID) { return topology.get(nodeID); } - public synchronized TopologyMemberImpl getMember(final TransportConfiguration configuration) - { - for (TopologyMemberImpl member : topology.values()) - { - if (member.isMember(configuration)) - { + public synchronized TopologyMemberImpl getMember(final TransportConfiguration configuration) { + for (TopologyMemberImpl member : topology.values()) { + if (member.isMember(configuration)) { return member; } } @@ -444,77 +373,63 @@ public final class Topology return null; } - public synchronized boolean isEmpty() - { + public synchronized boolean isEmpty() { return topology.isEmpty(); } - public Collection getMembers() - { + public Collection getMembers() { ArrayList members; - synchronized (this) - { + synchronized (this) { members = new ArrayList<>(topology.values()); } return members; } - synchronized int nodes() - { + synchronized int nodes() { int count = 0; - for (TopologyMemberImpl member : topology.values()) - { - if (member.getLive() != null) - { + for (TopologyMemberImpl member : topology.values()) { + if (member.getLive() != null) { count++; } - if (member.getBackup() != null) - { + if (member.getBackup() != null) { count++; } } return count; } - public synchronized String describe() - { + public synchronized String describe() { return describe(""); } - private synchronized String describe(final String text) - { + private synchronized String describe(final String text) { StringBuilder desc = new StringBuilder(text + "topology on " + this + ":\n"); - for (Entry entry : new HashMap<>(topology).entrySet()) - { + for (Entry entry : new HashMap<>(topology).entrySet()) { desc.append("\t").append(entry.getKey()).append(" => ").append(entry.getValue()).append("\n"); } desc.append("\t" + "nodes=").append(nodes()).append("\t").append("members=").append(members()); - if (topology.isEmpty()) - { + if (topology.isEmpty()) { desc.append("\tEmpty"); } return desc.toString(); } - private int members() - { + private int members() { return topology.size(); } - /** The owner exists mainly for debug purposes. - * When enabling logging and tracing, the Topology updates will include the owner, what will enable to identify - * what instances are receiving the updates, what will enable better debugging.*/ - public void setOwner(final Object owner) - { + /** + * The owner exists mainly for debug purposes. + * When enabling logging and tracing, the Topology updates will include the owner, what will enable to identify + * what instances are receiving the updates, what will enable better debugging. + */ + public void setOwner(final Object owner) { this.owner = owner; } - public TransportConfiguration getBackupForConnector(final Connector connector) - { - for (TopologyMemberImpl member : topology.values()) - { - if (member.getLive() != null && connector.isEquivalent(member.getLive().getParams())) - { + public TransportConfiguration getBackupForConnector(final Connector connector) { + for (TopologyMemberImpl member : topology.values()) { + if (member.getLive() != null && connector.isEquivalent(member.getLive().getParams())) { return member.getBackup(); } } @@ -522,19 +437,15 @@ public final class Topology } @Override - public String toString() - { - if (owner == null) - { + public String toString() { + if (owner == null) { return "Topology@" + Integer.toHexString(System.identityHashCode(this)); } return "Topology@" + Integer.toHexString(System.identityHashCode(this)) + "[owner=" + owner + "]"; } - private synchronized Map getMapDelete() - { - if (mapDelete == null) - { + private synchronized Map getMapDelete() { + if (mapDelete == null) { mapDelete = new ConcurrentHashMap<>(); } return mapDelete; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/TopologyMemberImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/TopologyMemberImpl.java index 4f71b8fe65..f220457bff 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/TopologyMemberImpl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/TopologyMemberImpl.java @@ -21,8 +21,8 @@ import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.api.core.client.TopologyMember; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; -public final class TopologyMemberImpl implements TopologyMember -{ +public final class TopologyMemberImpl implements TopologyMember { + private static final long serialVersionUID = 1123652191795626133L; private final Pair connector; @@ -38,9 +38,11 @@ public final class TopologyMemberImpl implements TopologyMember private final String nodeId; - public TopologyMemberImpl(String nodeId, final String backupGroupName, final String scaleDownGroupName, final TransportConfiguration a, - final TransportConfiguration b) - { + public TopologyMemberImpl(String nodeId, + final String backupGroupName, + final String scaleDownGroupName, + final TransportConfiguration a, + final TransportConfiguration b) { this.nodeId = nodeId; this.backupGroupName = backupGroupName; this.scaleDownGroupName = scaleDownGroupName; @@ -49,90 +51,72 @@ public final class TopologyMemberImpl implements TopologyMember } @Override - public TransportConfiguration getLive() - { + public TransportConfiguration getLive() { return connector.getA(); } @Override - public TransportConfiguration getBackup() - { + public TransportConfiguration getBackup() { return connector.getB(); } - public void setBackup(final TransportConfiguration param) - { + public void setBackup(final TransportConfiguration param) { connector.setB(param); } - public void setLive(final TransportConfiguration param) - { + public void setLive(final TransportConfiguration param) { connector.setA(param); } @Override - public String getNodeId() - { + public String getNodeId() { return nodeId; } @Override - public long getUniqueEventID() - { + public long getUniqueEventID() { return uniqueEventID; } @Override - public String getBackupGroupName() - { + public String getBackupGroupName() { return backupGroupName; } @Override - public String getScaleDownGroupName() - { + public String getScaleDownGroupName() { return scaleDownGroupName; } /** * @param uniqueEventID the uniqueEventID to set */ - public void setUniqueEventID(final long uniqueEventID) - { + public void setUniqueEventID(final long uniqueEventID) { this.uniqueEventID = uniqueEventID; } - public Pair getConnector() - { + public Pair getConnector() { return connector; } - - public boolean isMember(RemotingConnection connection) - { + public boolean isMember(RemotingConnection connection) { TransportConfiguration connectorConfig = connection.getTransportConnection() != null ? connection.getTransportConnection().getConnectorConfig() : null; return isMember(connectorConfig); } - public boolean isMember(TransportConfiguration configuration) - { - if (getConnector().getA() != null && getConnector().getA().equals(configuration) || - getConnector().getB() != null && getConnector().getB().equals(configuration)) - { + public boolean isMember(TransportConfiguration configuration) { + if (getConnector().getA() != null && getConnector().getA().equals(configuration) || getConnector().getB() != null && getConnector().getB().equals(configuration)) { return true; } - else - { + else { return false; } } - @Override - public String toString() - { + public String toString() { return "TopologyMember[id = " + nodeId + ", connector=" + connector + ", backupGroupName=" + backupGroupName + ", scaleDownGroupName=" + scaleDownGroupName + "]"; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/cluster/DiscoveryEntry.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/cluster/DiscoveryEntry.java index 3af57c50d9..59de1fd77f 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/cluster/DiscoveryEntry.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/cluster/DiscoveryEntry.java @@ -18,38 +18,32 @@ package org.apache.activemq.artemis.core.cluster; import org.apache.activemq.artemis.api.core.TransportConfiguration; -public class DiscoveryEntry -{ +public class DiscoveryEntry { + private final String nodeID; private final TransportConfiguration connector; private final long lastUpdate; - - public DiscoveryEntry(final String nodeID, final TransportConfiguration connector, final long lastUpdate) - { + public DiscoveryEntry(final String nodeID, final TransportConfiguration connector, final long lastUpdate) { this.nodeID = nodeID; this.connector = connector; this.lastUpdate = lastUpdate; } - public String getNodeID() - { + public String getNodeID() { return nodeID; } - public TransportConfiguration getConnector() - { + public TransportConfiguration getConnector() { return connector; } - public long getLastUpdate() - { + public long getLastUpdate() { return lastUpdate; } @Override - public String toString() - { + public String toString() { return "DiscoveryEntry[nodeID=" + nodeID + ", connector=" + connector + ", lastUpdate=" + lastUpdate + "]"; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/cluster/DiscoveryGroup.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/cluster/DiscoveryGroup.java index bb4ea6d1a6..5e8fe77b70 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/cluster/DiscoveryGroup.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/cluster/DiscoveryGroup.java @@ -44,10 +44,9 @@ import org.apache.activemq.artemis.utils.TypedProperties; * * We will probably keep both interfaces for a while as UDP is a simple solution requiring no extra dependencies which * is suitable for users looking for embedded solutions. - * */ -public final class DiscoveryGroup implements ActiveMQComponent -{ +public final class DiscoveryGroup implements ActiveMQComponent { + private static final boolean isTrace = ActiveMQClientLogger.LOGGER.isTraceEnabled(); private final List listeners = new ArrayList(); @@ -84,10 +83,11 @@ public final class DiscoveryGroup implements ActiveMQComponent * @param service * @throws Exception */ - public DiscoveryGroup(final String nodeID, final String name, final long timeout, + public DiscoveryGroup(final String nodeID, + final String name, + final long timeout, BroadcastEndpointFactory endpointFactory, - NotificationService service) throws Exception - { + NotificationService service) throws Exception { this.nodeID = nodeID; this.name = name; this.timeout = timeout; @@ -95,10 +95,8 @@ public final class DiscoveryGroup implements ActiveMQComponent this.notificationService = service; } - public synchronized void start() throws Exception - { - if (started) - { + public synchronized void start() throws Exception { + if (started) { return; } @@ -112,8 +110,7 @@ public final class DiscoveryGroup implements ActiveMQComponent thread.start(); - if (notificationService != null) - { + if (notificationService != null) { TypedProperties props = new TypedProperties(); props.putSimpleStringProperty(new SimpleString("name"), new SimpleString(name)); @@ -128,113 +125,90 @@ public final class DiscoveryGroup implements ActiveMQComponent * This will start the DiscoveryRunnable and run it directly. * This is useful for a test process where we need this execution blocking a thread. */ - public void internalRunning() throws Exception - { + public void internalRunning() throws Exception { endpoint.openClient(); started = true; DiscoveryRunnable runnable = new DiscoveryRunnable(); runnable.run(); } - public void stop() - { - synchronized (this) - { - if (!started) - { + public void stop() { + synchronized (this) { + if (!started) { return; } started = false; } - synchronized (waitLock) - { + synchronized (waitLock) { waitLock.notifyAll(); } - try - { + try { endpoint.close(false); } - catch (Exception e1) - { + catch (Exception e1) { ActiveMQClientLogger.LOGGER.errorStoppingDiscoveryBroadcastEndpoint(endpoint, e1); } - try - { - if (thread != null) - { + try { + if (thread != null) { thread.interrupt(); thread.join(10000); - if (thread.isAlive()) - { + if (thread.isAlive()) { ActiveMQClientLogger.LOGGER.timedOutStoppingDiscovery(); } } } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } thread = null; - if (notificationService != null) - { + if (notificationService != null) { TypedProperties props = new TypedProperties(); props.putSimpleStringProperty(new SimpleString("name"), new SimpleString(name)); Notification notification = new Notification(nodeID, CoreNotificationType.DISCOVERY_GROUP_STOPPED, props); - try - { + try { notificationService.sendNotification(notification); } - catch (Exception e) - { + catch (Exception e) { ActiveMQClientLogger.LOGGER.errorSendingNotifOnDiscoveryStop(e); } } } - public boolean isStarted() - { + public boolean isStarted() { return started; } - public String getName() - { + public String getName() { return name; } - public synchronized List getDiscoveryEntries() - { + public synchronized List getDiscoveryEntries() { List list = new ArrayList(connectors.values()); return list; } - public boolean waitForBroadcast(final long timeout) - { - synchronized (waitLock) - { + public boolean waitForBroadcast(final long timeout) { + synchronized (waitLock) { long start = System.currentTimeMillis(); long toWait = timeout; - while (started && !received && (toWait > 0 || timeout == 0)) - { - try - { + while (started && !received && (toWait > 0 || timeout == 0)) { + try { waitLock.wait(toWait); } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } - if (timeout != 0) - { + if (timeout != 0) { long now = System.currentTimeMillis(); toWait -= now - start; @@ -255,42 +229,32 @@ public final class DiscoveryGroup implements ActiveMQComponent * This is a sanity check to catch any cases where two different nodes are broadcasting the same node id either * due to misconfiguration or problems in failover */ - private void checkUniqueID(final String originatingNodeID, final String uniqueID) - { + private void checkUniqueID(final String originatingNodeID, final String uniqueID) { String currentUniqueID = uniqueIDMap.get(originatingNodeID); - if (currentUniqueID == null) - { + if (currentUniqueID == null) { uniqueIDMap.put(originatingNodeID, uniqueID); } - else - { - if (!currentUniqueID.equals(uniqueID)) - { + else { + if (!currentUniqueID.equals(uniqueID)) { ActiveMQClientLogger.LOGGER.multipleServersBroadcastingSameNode(originatingNodeID); uniqueIDMap.put(originatingNodeID, uniqueID); } } } - class DiscoveryRunnable implements Runnable - { - public void run() - { + class DiscoveryRunnable implements Runnable { + + public void run() { byte[] data = null; - while (started) - { - try - { - try - { + while (started) { + try { + try { data = endpoint.receiveBroadcast(); - if (data == null) - { - if (started) - { + if (data == null) { + if (started) { // This is totally unexpected, so I'm not even bothering on creating // a log entry for that ActiveMQClientLogger.LOGGER.warn("Unexpected null data received from DiscoveryEndpoint"); @@ -298,14 +262,11 @@ public final class DiscoveryGroup implements ActiveMQComponent break; } } - catch (Exception e) - { - if (!started) - { + catch (Exception e) { + if (!started) { return; } - else - { + else { ActiveMQClientLogger.LOGGER.errorReceivingPAcketInDiscovery(e); } } @@ -318,10 +279,8 @@ public final class DiscoveryGroup implements ActiveMQComponent checkUniqueID(originatingNodeID, uniqueID); - if (nodeID.equals(originatingNodeID)) - { - if (checkExpiration()) - { + if (nodeID.equals(originatingNodeID)) { + if (checkExpiration()) { callListeners(); } // Ignore traffic from own node @@ -334,8 +293,7 @@ public final class DiscoveryGroup implements ActiveMQComponent DiscoveryEntry[] entriesRead = new DiscoveryEntry[size]; // Will first decode all the elements outside of any lock - for (int i = 0; i < size; i++) - { + for (int i = 0; i < size; i++) { TransportConfiguration connector = new TransportConfiguration(); connector.decode(buffer); @@ -343,12 +301,9 @@ public final class DiscoveryGroup implements ActiveMQComponent entriesRead[i] = new DiscoveryEntry(originatingNodeID, connector, System.currentTimeMillis()); } - synchronized (DiscoveryGroup.this) - { - for (DiscoveryEntry entry : entriesRead) - { - if (connectors.put(originatingNodeID, entry) == null) - { + synchronized (DiscoveryGroup.this) { + for (DiscoveryEntry entry : entriesRead) { + if (connectors.put(originatingNodeID, entry) == null) { changed = true; } } @@ -357,28 +312,23 @@ public final class DiscoveryGroup implements ActiveMQComponent } //only call the listeners if we have changed //also make sure that we aren't stopping to avoid deadlock - if (changed && started) - { - if (isTrace) - { + if (changed && started) { + if (isTrace) { ActiveMQClientLogger.LOGGER.trace("Connectors changed on Discovery:"); - for (DiscoveryEntry connector : connectors.values()) - { + for (DiscoveryEntry connector : connectors.values()) { ActiveMQClientLogger.LOGGER.trace(connector); } } callListeners(); } - synchronized (waitLock) - { + synchronized (waitLock) { received = true; waitLock.notifyAll(); } } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQClientLogger.LOGGER.failedToReceiveDatagramInDiscovery(e); } } @@ -386,39 +336,31 @@ public final class DiscoveryGroup implements ActiveMQComponent } - public synchronized void registerListener(final DiscoveryListener listener) - { + public synchronized void registerListener(final DiscoveryListener listener) { listeners.add(listener); - if (!connectors.isEmpty()) - { + if (!connectors.isEmpty()) { listener.connectorsChanged(getDiscoveryEntries()); } } - public synchronized void unregisterListener(final DiscoveryListener listener) - { + public synchronized void unregisterListener(final DiscoveryListener listener) { listeners.remove(listener); } - private void callListeners() - { - for (DiscoveryListener listener : listeners) - { - try - { + private void callListeners() { + for (DiscoveryListener listener : listeners) { + try { listener.connectorsChanged(getDiscoveryEntries()); } - catch (Throwable t) - { + catch (Throwable t) { // Catch it so exception doesn't prevent other listeners from running ActiveMQClientLogger.LOGGER.failedToCallListenerInDiscovery(t); } } } - private boolean checkExpiration() - { + private boolean checkExpiration() { boolean changed = false; long now = System.currentTimeMillis(); @@ -426,14 +368,11 @@ public final class DiscoveryGroup implements ActiveMQComponent // Weed out any expired connectors - while (iter.hasNext()) - { + while (iter.hasNext()) { Map.Entry entry = iter.next(); - if (entry.getValue().getLastUpdate() + timeout <= now) - { - if (isTrace) - { + if (entry.getValue().getLastUpdate() + timeout <= now) { + if (isTrace) { ActiveMQClientLogger.LOGGER.trace("Timed out node on discovery:" + entry.getValue()); } iter.remove(); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/cluster/DiscoveryListener.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/cluster/DiscoveryListener.java index e37578ceeb..fa86e616d6 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/cluster/DiscoveryListener.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/cluster/DiscoveryListener.java @@ -21,7 +21,7 @@ import java.util.List; /** * To be called any time Discovery changes its list of nodes. */ -public interface DiscoveryListener -{ +public interface DiscoveryListener { + void connectorsChanged(List newConnectors); } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/exception/ActiveMQXAException.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/exception/ActiveMQXAException.java index c66d4eebed..e7283e05de 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/exception/ActiveMQXAException.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/exception/ActiveMQXAException.java @@ -18,19 +18,17 @@ package org.apache.activemq.artemis.core.exception; import javax.transaction.xa.XAException; -public class ActiveMQXAException extends XAException -{ +public class ActiveMQXAException extends XAException { + private static final long serialVersionUID = 6535914602965015803L; - public ActiveMQXAException(final int errorCode, final String message) - { + public ActiveMQXAException(final int errorCode, final String message) { super(message); this.errorCode = errorCode; } - public ActiveMQXAException(final int errorCode) - { + public ActiveMQXAException(final int errorCode) { super(errorCode); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/message/BodyEncoder.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/message/BodyEncoder.java index bfc9cdef62..baafaac853 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/message/BodyEncoder.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/message/BodyEncoder.java @@ -26,8 +26,8 @@ import org.apache.activemq.artemis.api.core.ActiveMQException; *
* Used to send large streams over the wire */ -public interface BodyEncoder -{ +public interface BodyEncoder { + /** * This method must not be called directly by ActiveMQ Artemis clients. */ diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/message/impl/MessageImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/message/impl/MessageImpl.java index 45982019f7..eae2de37f3 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/message/impl/MessageImpl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/message/impl/MessageImpl.java @@ -40,8 +40,8 @@ import org.apache.activemq.artemis.utils.UUID; *

* All messages handled by ActiveMQ Artemis core are of this type */ -public abstract class MessageImpl implements MessageInternal -{ +public abstract class MessageImpl implements MessageInternal { + public static final SimpleString HDR_ROUTE_TO_IDS = new SimpleString("_AMQ_ROUTE_TO"); public static final SimpleString HDR_SCALEDOWN_TO_IDS = new SimpleString("_AMQ_SCALEDOWN_TO"); @@ -92,8 +92,7 @@ public abstract class MessageImpl implements MessageInternal // Constructors -------------------------------------------------- - protected MessageImpl() - { + protected MessageImpl() { properties = new TypedProperties(); } @@ -112,8 +111,7 @@ public abstract class MessageImpl implements MessageInternal final long expiration, final long timestamp, final byte priority, - final int initialMessageBufferSize) - { + final int initialMessageBufferSize) { this(); this.type = type; this.durable = durable; @@ -123,8 +121,7 @@ public abstract class MessageImpl implements MessageInternal createBody(initialMessageBufferSize); } - protected MessageImpl(final int initialMessageBufferSize) - { + protected MessageImpl(final int initialMessageBufferSize) { this(); createBody(initialMessageBufferSize); } @@ -132,16 +129,14 @@ public abstract class MessageImpl implements MessageInternal /* * Copy constructor */ - protected MessageImpl(final MessageImpl other) - { + protected MessageImpl(final MessageImpl other) { this(other, other.getProperties()); } /* * Copy constructor */ - protected MessageImpl(final MessageImpl other, TypedProperties properties) - { + protected MessageImpl(final MessageImpl other, TypedProperties properties) { messageID = other.getMessageID(); userID = other.getUserID(); address = other.getAddress(); @@ -155,15 +150,13 @@ public abstract class MessageImpl implements MessageInternal // This MUST be synchronized using the monitor on the other message to prevent it running concurrently // with getEncodedBuffer(), otherwise can introduce race condition when delivering concurrently to // many subscriptions and bridging to other nodes in a cluster - synchronized (other) - { + synchronized (other) { bufferValid = other.bufferValid; endOfBodyPosition = other.endOfBodyPosition; endOfMessagePosition = other.endOfMessagePosition; copied = other.copied; - if (other.buffer != null) - { + if (other.buffer != null) { other.bufferUsed = true; // We need to copy the underlying buffer too, since the different messsages thereafter might have different @@ -177,8 +170,7 @@ public abstract class MessageImpl implements MessageInternal // Message implementation ---------------------------------------- - public int getEncodeSize() - { + public int getEncodeSize() { int headersPropsSize = getHeadersAndPropertiesEncodeSize(); int bodyPos = getEndOfBodyPosition(); @@ -188,8 +180,7 @@ public abstract class MessageImpl implements MessageInternal return DataConstants.SIZE_INT + bodySize + DataConstants.SIZE_INT + headersPropsSize; } - public int getHeadersAndPropertiesEncodeSize() - { + public int getHeadersAndPropertiesEncodeSize() { return DataConstants.SIZE_LONG + // Message ID DataConstants.SIZE_BYTE + // user id null? (userID == null ? 0 : 16) + @@ -202,17 +193,13 @@ public abstract class MessageImpl implements MessageInternal /* PropertySize and Properties */properties.getEncodeSize(); } - - public void encodeHeadersAndProperties(final ActiveMQBuffer buffer) - { + public void encodeHeadersAndProperties(final ActiveMQBuffer buffer) { buffer.writeLong(messageID); buffer.writeNullableSimpleString(address); - if (userID == null) - { + if (userID == null) { buffer.writeByte(DataConstants.NULL); } - else - { + else { buffer.writeByte(DataConstants.NOT_NULL); buffer.writeBytes(userID.asBytes()); } @@ -224,18 +211,15 @@ public abstract class MessageImpl implements MessageInternal properties.encode(buffer); } - public void decodeHeadersAndProperties(final ActiveMQBuffer buffer) - { + public void decodeHeadersAndProperties(final ActiveMQBuffer buffer) { messageID = buffer.readLong(); address = buffer.readNullableSimpleString(); - if (buffer.readByte() == DataConstants.NOT_NULL) - { + if (buffer.readByte() == DataConstants.NOT_NULL) { byte[] bytes = new byte[16]; buffer.readBytes(bytes); userID = new UUID(UUID.TYPE_TIME_BASED, bytes); } - else - { + else { userID = null; } type = buffer.readByte(); @@ -246,8 +230,7 @@ public abstract class MessageImpl implements MessageInternal properties.decode(buffer); } - public void copyHeadersAndProperties(final MessageInternal msg) - { + public void copyHeadersAndProperties(final MessageInternal msg) { messageID = msg.getMessageID(); address = msg.getAddress(); userID = msg.getUserID(); @@ -259,38 +242,31 @@ public abstract class MessageImpl implements MessageInternal properties = msg.getTypedProperties(); } - public ActiveMQBuffer getBodyBuffer() - { - if (bodyBuffer == null) - { + public ActiveMQBuffer getBodyBuffer() { + if (bodyBuffer == null) { bodyBuffer = new ResetLimitWrappedActiveMQBuffer(BODY_OFFSET, buffer, this); } return bodyBuffer; } - public Message writeBodyBufferBytes(byte[] bytes) - { + public Message writeBodyBufferBytes(byte[] bytes) { getBodyBuffer().writeBytes(bytes); return this; } - public Message writeBodyBufferString(String string) - { + public Message writeBodyBufferString(String string) { getBodyBuffer().writeString(string); return this; } - public void checkCompletion() throws ActiveMQException - { + public void checkCompletion() throws ActiveMQException { // no op on regular messages } - - public synchronized ActiveMQBuffer getBodyBufferCopy() - { + public synchronized ActiveMQBuffer getBodyBufferCopy() { // Must copy buffer before sending it ActiveMQBuffer newBuffer = buffer.copy(0, buffer.capacity()); @@ -300,18 +276,15 @@ public abstract class MessageImpl implements MessageInternal return new ResetLimitWrappedActiveMQBuffer(BODY_OFFSET, newBuffer, null); } - public long getMessageID() - { + public long getMessageID() { return messageID; } - public UUID getUserID() - { + public UUID getUserID() { return userID; } - public MessageImpl setUserID(final UUID userID) - { + public MessageImpl setUserID(final UUID userID) { this.userID = userID; return this; } @@ -320,8 +293,7 @@ public abstract class MessageImpl implements MessageInternal * this doesn't need to be synchronized as setAddress is protecting the buffer, * not the address */ - public SimpleString getAddress() - { + public SimpleString getAddress() { return address; } @@ -330,13 +302,10 @@ public abstract class MessageImpl implements MessageInternal * This synchronization can probably be removed since setAddress is always called from a single thread. * However I will keep it as it's harmless and it's been well tested */ - public Message setAddress(final SimpleString address) - { + public Message setAddress(final SimpleString address) { // This is protecting the buffer - synchronized (this) - { - if (this.address != address) - { + synchronized (this) { + if (this.address != address) { this.address = address; bufferValid = false; @@ -346,25 +315,20 @@ public abstract class MessageImpl implements MessageInternal return this; } - public byte getType() - { + public byte getType() { return type; } - public void setType(byte type) - { + public void setType(byte type) { this.type = type; } - public boolean isDurable() - { + public boolean isDurable() { return durable; } - public MessageImpl setDurable(final boolean durable) - { - if (this.durable != durable) - { + public MessageImpl setDurable(final boolean durable) { + if (this.durable != durable) { this.durable = durable; bufferValid = false; @@ -372,15 +336,12 @@ public abstract class MessageImpl implements MessageInternal return this; } - public long getExpiration() - { + public long getExpiration() { return expiration; } - public MessageImpl setExpiration(final long expiration) - { - if (this.expiration != expiration) - { + public MessageImpl setExpiration(final long expiration) { + if (this.expiration != expiration) { this.expiration = expiration; bufferValid = false; @@ -388,15 +349,12 @@ public abstract class MessageImpl implements MessageInternal return this; } - public long getTimestamp() - { + public long getTimestamp() { return timestamp; } - public MessageImpl setTimestamp(final long timestamp) - { - if (this.timestamp != timestamp) - { + public MessageImpl setTimestamp(final long timestamp) { + if (this.timestamp != timestamp) { this.timestamp = timestamp; bufferValid = false; @@ -404,15 +362,12 @@ public abstract class MessageImpl implements MessageInternal return this; } - public byte getPriority() - { + public byte getPriority() { return priority; } - public MessageImpl setPriority(final byte priority) - { - if (this.priority != priority) - { + public MessageImpl setPriority(final byte priority) { + if (this.priority != priority) { this.priority = priority; bufferValid = false; @@ -420,23 +375,19 @@ public abstract class MessageImpl implements MessageInternal return this; } - public boolean isExpired() - { - if (expiration == 0) - { + public boolean isExpired() { + if (expiration == 0) { return false; } return System.currentTimeMillis() - expiration >= 0; } - public Map toMap() - { + public Map toMap() { Map map = new HashMap(); map.put("messageID", messageID); - if (userID != null) - { + if (userID != null) { map.put("userID", "ID:" + userID.toString()); } map.put("address", address.toString()); @@ -445,22 +396,19 @@ public abstract class MessageImpl implements MessageInternal map.put("expiration", expiration); map.put("timestamp", timestamp); map.put("priority", priority); - for (SimpleString propName : properties.getPropertyNames()) - { + for (SimpleString propName : properties.getPropertyNames()) { map.put(propName.toString(), properties.getProperty(propName)); } return map; } - public void decodeFromBuffer(final ActiveMQBuffer buffer) - { + public void decodeFromBuffer(final ActiveMQBuffer buffer) { this.buffer = buffer; decode(); } - public void bodyChanged() - { + public void bodyChanged() { // If the body is changed we must copy the buffer otherwise can affect the previously sent message // which might be in the Netty write queue checkCopy(); @@ -470,46 +418,38 @@ public abstract class MessageImpl implements MessageInternal endOfBodyPosition = -1; } - public synchronized void checkCopy() - { - if (!copied) - { + public synchronized void checkCopy() { + if (!copied) { forceCopy(); copied = true; } } - public synchronized void resetCopied() - { + public synchronized void resetCopied() { copied = false; } - public int getEndOfMessagePosition() - { + public int getEndOfMessagePosition() { return endOfMessagePosition; } - public int getEndOfBodyPosition() - { - if (endOfBodyPosition < 0) - { + public int getEndOfBodyPosition() { + if (endOfBodyPosition < 0) { endOfBodyPosition = buffer.writerIndex(); } return endOfBodyPosition; } // Encode to journal or paging - public void encode(final ActiveMQBuffer buff) - { + public void encode(final ActiveMQBuffer buff) { encodeToBuffer(); buff.writeBytes(buffer, BUFFER_HEADER_SPACE, endOfMessagePosition - BUFFER_HEADER_SPACE); } // Decode from journal or paging - public void decode(final ActiveMQBuffer buff) - { + public void decode(final ActiveMQBuffer buff) { int start = buff.readerIndex(); endOfBodyPosition = buff.readInt(); @@ -527,20 +467,17 @@ public abstract class MessageImpl implements MessageInternal buff.readerIndex(start + length); } - public synchronized ActiveMQBuffer getEncodedBuffer() - { + public synchronized ActiveMQBuffer getEncodedBuffer() { ActiveMQBuffer buff = encodeToBuffer(); - if (bufferUsed) - { + if (bufferUsed) { ActiveMQBuffer copied = buff.copy(0, buff.capacity()); copied.setIndex(0, endOfMessagePosition); return copied; } - else - { + else { buffer.setIndex(0, endOfMessagePosition); bufferUsed = true; @@ -549,17 +486,14 @@ public abstract class MessageImpl implements MessageInternal } } - public void setAddressTransient(final SimpleString address) - { + public void setAddressTransient(final SimpleString address) { this.address = address; } - // Properties // --------------------------------------------------------------------------------------- - public Message putBooleanProperty(final SimpleString key, final boolean value) - { + public Message putBooleanProperty(final SimpleString key, final boolean value) { properties.putBooleanProperty(key, value); bufferValid = false; @@ -567,8 +501,7 @@ public abstract class MessageImpl implements MessageInternal return this; } - public Message putByteProperty(final SimpleString key, final byte value) - { + public Message putByteProperty(final SimpleString key, final byte value) { properties.putByteProperty(key, value); bufferValid = false; @@ -576,8 +509,7 @@ public abstract class MessageImpl implements MessageInternal return this; } - public Message putBytesProperty(final SimpleString key, final byte[] value) - { + public Message putBytesProperty(final SimpleString key, final byte[] value) { properties.putBytesProperty(key, value); bufferValid = false; @@ -586,8 +518,7 @@ public abstract class MessageImpl implements MessageInternal } @Override - public Message putCharProperty(SimpleString key, char value) - { + public Message putCharProperty(SimpleString key, char value) { properties.putCharProperty(key, value); bufferValid = false; @@ -595,40 +526,35 @@ public abstract class MessageImpl implements MessageInternal } @Override - public Message putCharProperty(String key, char value) - { + public Message putCharProperty(String key, char value) { properties.putCharProperty(new SimpleString(key), value); bufferValid = false; return this; } - public Message putShortProperty(final SimpleString key, final short value) - { + public Message putShortProperty(final SimpleString key, final short value) { properties.putShortProperty(key, value); bufferValid = false; return this; } - public Message putIntProperty(final SimpleString key, final int value) - { + public Message putIntProperty(final SimpleString key, final int value) { properties.putIntProperty(key, value); bufferValid = false; return this; } - public Message putLongProperty(final SimpleString key, final long value) - { + public Message putLongProperty(final SimpleString key, final long value) { properties.putLongProperty(key, value); bufferValid = false; return this; } - public Message putFloatProperty(final SimpleString key, final float value) - { + public Message putFloatProperty(final SimpleString key, final float value) { properties.putFloatProperty(key, value); bufferValid = false; @@ -636,8 +562,7 @@ public abstract class MessageImpl implements MessageInternal return this; } - public Message putDoubleProperty(final SimpleString key, final double value) - { + public Message putDoubleProperty(final SimpleString key, final double value) { properties.putDoubleProperty(key, value); bufferValid = false; @@ -645,8 +570,7 @@ public abstract class MessageImpl implements MessageInternal return this; } - public Message putStringProperty(final SimpleString key, final SimpleString value) - { + public Message putStringProperty(final SimpleString key, final SimpleString value) { properties.putSimpleStringProperty(key, value); bufferValid = false; @@ -654,16 +578,15 @@ public abstract class MessageImpl implements MessageInternal return this; } - public Message putObjectProperty(final SimpleString key, final Object value) throws ActiveMQPropertyConversionException - { + public Message putObjectProperty(final SimpleString key, + final Object value) throws ActiveMQPropertyConversionException { TypedProperties.setObjectProperty(key, value, properties); bufferValid = false; return this; } - public Message putObjectProperty(final String key, final Object value) throws ActiveMQPropertyConversionException - { + public Message putObjectProperty(final String key, final Object value) throws ActiveMQPropertyConversionException { putObjectProperty(new SimpleString(key), value); bufferValid = false; @@ -671,8 +594,7 @@ public abstract class MessageImpl implements MessageInternal return this; } - public Message putBooleanProperty(final String key, final boolean value) - { + public Message putBooleanProperty(final String key, final boolean value) { properties.putBooleanProperty(new SimpleString(key), value); bufferValid = false; @@ -680,8 +602,7 @@ public abstract class MessageImpl implements MessageInternal return this; } - public Message putByteProperty(final String key, final byte value) - { + public Message putByteProperty(final String key, final byte value) { properties.putByteProperty(new SimpleString(key), value); bufferValid = false; @@ -689,8 +610,7 @@ public abstract class MessageImpl implements MessageInternal return this; } - public Message putBytesProperty(final String key, final byte[] value) - { + public Message putBytesProperty(final String key, final byte[] value) { properties.putBytesProperty(new SimpleString(key), value); bufferValid = false; @@ -698,8 +618,7 @@ public abstract class MessageImpl implements MessageInternal return this; } - public Message putShortProperty(final String key, final short value) - { + public Message putShortProperty(final String key, final short value) { properties.putShortProperty(new SimpleString(key), value); bufferValid = false; @@ -707,8 +626,7 @@ public abstract class MessageImpl implements MessageInternal return this; } - public Message putIntProperty(final String key, final int value) - { + public Message putIntProperty(final String key, final int value) { properties.putIntProperty(new SimpleString(key), value); bufferValid = false; @@ -716,8 +634,7 @@ public abstract class MessageImpl implements MessageInternal return this; } - public Message putLongProperty(final String key, final long value) - { + public Message putLongProperty(final String key, final long value) { properties.putLongProperty(new SimpleString(key), value); bufferValid = false; @@ -725,8 +642,7 @@ public abstract class MessageImpl implements MessageInternal return this; } - public Message putFloatProperty(final String key, final float value) - { + public Message putFloatProperty(final String key, final float value) { properties.putFloatProperty(new SimpleString(key), value); bufferValid = false; @@ -734,8 +650,7 @@ public abstract class MessageImpl implements MessageInternal return this; } - public Message putDoubleProperty(final String key, final double value) - { + public Message putDoubleProperty(final String key, final double value) { properties.putDoubleProperty(new SimpleString(key), value); bufferValid = false; @@ -743,8 +658,7 @@ public abstract class MessageImpl implements MessageInternal return this; } - public Message putStringProperty(final String key, final String value) - { + public Message putStringProperty(final String key, final String value) { properties.putSimpleStringProperty(new SimpleString(key), SimpleString.toSimpleString(value)); bufferValid = false; @@ -752,8 +666,7 @@ public abstract class MessageImpl implements MessageInternal return this; } - public Message putTypedProperties(final TypedProperties otherProps) - { + public Message putTypedProperties(final TypedProperties otherProps) { properties.putTypedProperties(otherProps); bufferValid = false; @@ -761,180 +674,145 @@ public abstract class MessageImpl implements MessageInternal return this; } - public Object getObjectProperty(final SimpleString key) - { + public Object getObjectProperty(final SimpleString key) { return properties.getProperty(key); } - public Boolean getBooleanProperty(final SimpleString key) throws ActiveMQPropertyConversionException - { + public Boolean getBooleanProperty(final SimpleString key) throws ActiveMQPropertyConversionException { return properties.getBooleanProperty(key); } - public Boolean getBooleanProperty(final String key) throws ActiveMQPropertyConversionException - { + public Boolean getBooleanProperty(final String key) throws ActiveMQPropertyConversionException { return properties.getBooleanProperty(new SimpleString(key)); } - public Byte getByteProperty(final SimpleString key) throws ActiveMQPropertyConversionException - { + public Byte getByteProperty(final SimpleString key) throws ActiveMQPropertyConversionException { return properties.getByteProperty(key); } - public Byte getByteProperty(final String key) throws ActiveMQPropertyConversionException - { + public Byte getByteProperty(final String key) throws ActiveMQPropertyConversionException { return properties.getByteProperty(new SimpleString(key)); } - public byte[] getBytesProperty(final SimpleString key) throws ActiveMQPropertyConversionException - { + public byte[] getBytesProperty(final SimpleString key) throws ActiveMQPropertyConversionException { return properties.getBytesProperty(key); } - public byte[] getBytesProperty(final String key) throws ActiveMQPropertyConversionException - { + public byte[] getBytesProperty(final String key) throws ActiveMQPropertyConversionException { return getBytesProperty(new SimpleString(key)); } - public Double getDoubleProperty(final SimpleString key) throws ActiveMQPropertyConversionException - { + public Double getDoubleProperty(final SimpleString key) throws ActiveMQPropertyConversionException { return properties.getDoubleProperty(key); } - public Double getDoubleProperty(final String key) throws ActiveMQPropertyConversionException - { + public Double getDoubleProperty(final String key) throws ActiveMQPropertyConversionException { return properties.getDoubleProperty(new SimpleString(key)); } - public Integer getIntProperty(final SimpleString key) throws ActiveMQPropertyConversionException - { + public Integer getIntProperty(final SimpleString key) throws ActiveMQPropertyConversionException { return properties.getIntProperty(key); } - public Integer getIntProperty(final String key) throws ActiveMQPropertyConversionException - { + public Integer getIntProperty(final String key) throws ActiveMQPropertyConversionException { return properties.getIntProperty(new SimpleString(key)); } - public Long getLongProperty(final SimpleString key) throws ActiveMQPropertyConversionException - { + public Long getLongProperty(final SimpleString key) throws ActiveMQPropertyConversionException { return properties.getLongProperty(key); } - public Long getLongProperty(final String key) throws ActiveMQPropertyConversionException - { + public Long getLongProperty(final String key) throws ActiveMQPropertyConversionException { return properties.getLongProperty(new SimpleString(key)); } - public Short getShortProperty(final SimpleString key) throws ActiveMQPropertyConversionException - { + public Short getShortProperty(final SimpleString key) throws ActiveMQPropertyConversionException { return properties.getShortProperty(key); } - public Short getShortProperty(final String key) throws ActiveMQPropertyConversionException - { + public Short getShortProperty(final String key) throws ActiveMQPropertyConversionException { return properties.getShortProperty(new SimpleString(key)); } - public Float getFloatProperty(final SimpleString key) throws ActiveMQPropertyConversionException - { + public Float getFloatProperty(final SimpleString key) throws ActiveMQPropertyConversionException { return properties.getFloatProperty(key); } - public Float getFloatProperty(final String key) throws ActiveMQPropertyConversionException - { + public Float getFloatProperty(final String key) throws ActiveMQPropertyConversionException { return properties.getFloatProperty(new SimpleString(key)); } - public String getStringProperty(final SimpleString key) throws ActiveMQPropertyConversionException - { + public String getStringProperty(final SimpleString key) throws ActiveMQPropertyConversionException { SimpleString str = getSimpleStringProperty(key); - if (str == null) - { + if (str == null) { return null; } - else - { + else { return str.toString(); } } - public String getStringProperty(final String key) throws ActiveMQPropertyConversionException - { + public String getStringProperty(final String key) throws ActiveMQPropertyConversionException { return getStringProperty(new SimpleString(key)); } - public SimpleString getSimpleStringProperty(final SimpleString key) throws ActiveMQPropertyConversionException - { + public SimpleString getSimpleStringProperty(final SimpleString key) throws ActiveMQPropertyConversionException { return properties.getSimpleStringProperty(key); } - public SimpleString getSimpleStringProperty(final String key) throws ActiveMQPropertyConversionException - { + public SimpleString getSimpleStringProperty(final String key) throws ActiveMQPropertyConversionException { return properties.getSimpleStringProperty(new SimpleString(key)); } - public Object getObjectProperty(final String key) - { + public Object getObjectProperty(final String key) { return properties.getProperty(new SimpleString(key)); } - public Object removeProperty(final SimpleString key) - { + public Object removeProperty(final SimpleString key) { bufferValid = false; return properties.removeProperty(key); } - public Object removeProperty(final String key) - { + public Object removeProperty(final String key) { bufferValid = false; return properties.removeProperty(new SimpleString(key)); } - public boolean containsProperty(final SimpleString key) - { + public boolean containsProperty(final SimpleString key) { return properties.containsProperty(key); } - public boolean containsProperty(final String key) - { + public boolean containsProperty(final String key) { return properties.containsProperty(new SimpleString(key)); } - public Set getPropertyNames() - { + public Set getPropertyNames() { return properties.getPropertyNames(); } - public ActiveMQBuffer getWholeBuffer() - { + public ActiveMQBuffer getWholeBuffer() { return buffer; } - public BodyEncoder getBodyEncoder() throws ActiveMQException - { + public BodyEncoder getBodyEncoder() throws ActiveMQException { return new DecodingContext(); } - public TypedProperties getTypedProperties() - { + public TypedProperties getTypedProperties() { return this.properties; } @Override - public boolean equals(Object other) - { + public boolean equals(Object other) { - if (this == other) - { + if (this == other) { return true; } - if (other instanceof MessageImpl) - { + if (other instanceof MessageImpl) { MessageImpl message = (MessageImpl) other; if (this.getMessageID() == message.getMessageID()) @@ -950,10 +828,10 @@ public abstract class MessageImpl implements MessageInternal * I'm leaving this message here without any callers for a reason: * During debugs it's important eventually to identify what's on the bodies, and this method will give you a good idea about them. * Add the message.bodyToString() to the Watch variables on the debugger view and this will show up like a charm!!! + * * @return */ - public String bodyToString() - { + public String bodyToString() { getEndOfBodyPosition(); int readerIndex1 = this.buffer.readerIndex(); buffer.readerIndex(0); @@ -962,8 +840,7 @@ public abstract class MessageImpl implements MessageInternal buffer.readerIndex(readerIndex1); byte[] buffer2 = null; - if (bodyBuffer != null) - { + if (bodyBuffer != null) { int readerIndex2 = this.bodyBuffer.readerIndex(); bodyBuffer.readerIndex(0); buffer2 = new byte[bodyBuffer.writerIndex() - bodyBuffer.readerIndex()]; @@ -974,13 +851,9 @@ public abstract class MessageImpl implements MessageInternal return "ServerMessage@" + Integer.toHexString(System.identityHashCode(this)) + "[" + ",bodyStart=" + getEndOfBodyPosition() + " buffer=" + ByteUtil.bytesToHex(buffer1, 1) + ", bodyBuffer=" + ByteUtil.bytesToHex(buffer2, 1); } - - - @Override - public int hashCode() - { - return 31 + (int)(messageID ^ (messageID >>> 32)); + public int hashCode() { + return 31 + (int) (messageID ^ (messageID >>> 32)); } // Public -------------------------------------------------------- @@ -991,20 +864,16 @@ public abstract class MessageImpl implements MessageInternal // Private ------------------------------------------------------- - public TypedProperties getProperties() - { + public TypedProperties getProperties() { return properties; } // This must be synchronized as it can be called concurrently id the message is being delivered // concurrently to // many queues - the first caller in this case will actually encode it - private synchronized ActiveMQBuffer encodeToBuffer() - { - if (!bufferValid) - { - if (bufferUsed) - { + private synchronized ActiveMQBuffer encodeToBuffer() { + if (!bufferValid) { + if (bufferUsed) { // Cannot use same buffer - must copy forceCopy(); @@ -1021,13 +890,11 @@ public abstract class MessageImpl implements MessageInternal // Position at end of body and skip past the message end position int. // check for enough room in the buffer even though it is dynamic - if ((bodySize + 4) > buffer.capacity()) - { + if ((bodySize + 4) > buffer.capacity()) { buffer.setIndex(0, bodySize); buffer.writeInt(0); } - else - { + else { buffer.setIndex(0, bodySize + DataConstants.SIZE_INT); } @@ -1045,8 +912,7 @@ public abstract class MessageImpl implements MessageInternal return buffer; } - private void decode() - { + private void decode() { endOfBodyPosition = buffer.getInt(BUFFER_HEADER_SPACE); buffer.readerIndex(endOfBodyPosition + DataConstants.SIZE_INT); @@ -1058,8 +924,7 @@ public abstract class MessageImpl implements MessageInternal bufferValid = true; } - public void createBody(final int initialMessageBufferSize) - { + public void createBody(final int initialMessageBufferSize) { buffer = ActiveMQBuffers.dynamicBuffer(initialMessageBufferSize); // There's a bug in netty which means a dynamic buffer won't resize until you write a byte @@ -1068,16 +933,14 @@ public abstract class MessageImpl implements MessageInternal buffer.setIndex(BODY_OFFSET, BODY_OFFSET); } - private void forceCopy() - { + private void forceCopy() { // Must copy buffer before sending it buffer = buffer.copy(0, buffer.capacity()); buffer.setIndex(0, getEndOfBodyPosition()); - if (bodyBuffer != null) - { + if (bodyBuffer != null) { bodyBuffer.setBuffer(buffer); } @@ -1086,35 +949,29 @@ public abstract class MessageImpl implements MessageInternal // Inner classes ------------------------------------------------- - private final class DecodingContext implements BodyEncoder - { + private final class DecodingContext implements BodyEncoder { + private int lastPos = 0; - public DecodingContext() - { + public DecodingContext() { } - public void open() - { + public void open() { } - public void close() - { + public void close() { } - public long getLargeBodySize() - { + public long getLargeBodySize() { return buffer.writerIndex(); } - public int encode(final ByteBuffer bufferRead) throws ActiveMQException - { + public int encode(final ByteBuffer bufferRead) throws ActiveMQException { ActiveMQBuffer buffer = ActiveMQBuffers.wrappedBuffer(bufferRead); return encode(buffer, bufferRead.capacity()); } - public int encode(final ActiveMQBuffer bufferOut, final int size) - { + public int encode(final ActiveMQBuffer bufferOut, final int size) { bufferOut.writeBytes(getWholeBuffer(), lastPos, size); lastPos += size; return size; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/message/impl/MessageInternal.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/message/impl/MessageInternal.java index 1606658c6a..728f1c557c 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/message/impl/MessageInternal.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/message/impl/MessageInternal.java @@ -25,8 +25,8 @@ import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.message.BodyEncoder; import org.apache.activemq.artemis.utils.TypedProperties; -public interface MessageInternal extends Message -{ +public interface MessageInternal extends Message { + void decodeFromBuffer(ActiveMQBuffer buffer); int getEndOfMessagePosition(); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/ClientPacketDecoder.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/ClientPacketDecoder.java index 4b49a6e632..a7930cba6b 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/ClientPacketDecoder.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/ClientPacketDecoder.java @@ -27,14 +27,13 @@ import org.apache.activemq.artemis.core.protocol.core.impl.PacketDecoder; import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionReceiveClientLargeMessage; import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionReceiveMessage; -public class ClientPacketDecoder extends PacketDecoder -{ +public class ClientPacketDecoder extends PacketDecoder { + private static final long serialVersionUID = 6952614096979334582L; public static final ClientPacketDecoder INSTANCE = new ClientPacketDecoder(); @Override - public Packet decode(final ActiveMQBuffer in) - { + public Packet decode(final ActiveMQBuffer in) { final byte packetType = in.readByte(); Packet packet = decode(packetType); @@ -45,24 +44,19 @@ public class ClientPacketDecoder extends PacketDecoder } @Override - public Packet decode(byte packetType) - { + public Packet decode(byte packetType) { Packet packet; - switch (packetType) - { - case SESS_RECEIVE_MSG: - { + switch (packetType) { + case SESS_RECEIVE_MSG: { packet = new SessionReceiveMessage(new ClientMessageImpl()); break; } - case SESS_RECEIVE_LARGE_MSG: - { + case SESS_RECEIVE_LARGE_MSG: { packet = new SessionReceiveClientLargeMessage(new ClientLargeMessageImpl()); break; } - default: - { + default: { packet = super.decode(packetType); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/Channel.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/Channel.java index c73e7c9fbb..fba1a1c3c9 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/Channel.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/Channel.java @@ -30,45 +30,52 @@ import org.apache.activemq.artemis.api.core.ActiveMQException; *

* A Channel *does not* support concurrent access by more than one thread! */ -public interface Channel -{ +public interface Channel { + /** * Returns the id of this channel. + * * @return the id */ long getID(); - /** For protocol check */ + /** + * For protocol check + */ boolean supports(byte packetID); /** * Sends a packet on this channel. + * * @param packet the packet to send * @return false if the packet was rejected by an outgoing interceptor; true if the send was - * successful + * successful */ boolean send(Packet packet); /** * Sends a packet on this channel using batching algorithm if appropriate + * * @param packet the packet to send * @return false if the packet was rejected by an outgoing interceptor; true if the send was - * successful + * successful */ boolean sendBatched(Packet packet); /** * Sends a packet on this channel and then blocks until it has been written to the connection. + * * @param packet the packet to send * @return false if the packet was rejected by an outgoing interceptor; true if the send was - * successful + * successful */ boolean sendAndFlush(Packet packet); /** * Sends a packet on this channel and then blocks until a response is received or a timeout * occurs. - * @param packet the packet to send + * + * @param packet the packet to send * @param expectedPacket the packet being expected. * @return the response * @throws ActiveMQException if an error occurs during the send @@ -78,6 +85,7 @@ public interface Channel /** * Sets the {@link org.apache.activemq.artemis.core.protocol.core.ChannelHandler} that this channel should * forward received packets to. + * * @param handler the handler */ void setHandler(ChannelHandler handler); @@ -85,6 +93,7 @@ public interface Channel /** * Gets the {@link org.apache.activemq.artemis.core.protocol.core.ChannelHandler} that this channel should * forward received packets to. + * * @return the current channel handler */ ChannelHandler getHandler(); @@ -100,6 +109,7 @@ public interface Channel * Transfers the connection used by this channel to the one specified. *

* All new packets will be sent via this connection. + * * @param newConnection the new connection */ void transferConnection(CoreRemotingConnection newConnection); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/ChannelHandler.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/ChannelHandler.java index 2b357e42b7..a44b6d5234 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/ChannelHandler.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/ChannelHandler.java @@ -16,13 +16,12 @@ */ package org.apache.activemq.artemis.core.protocol.core; - /** * A ChannelHandler is used by {@link Channel}. When a channel receives a packet it will call its handler to deal with the * packet. */ -public interface ChannelHandler -{ +public interface ChannelHandler { + /** * called by the channel when a packet is received.. * diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/CommandConfirmationHandler.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/CommandConfirmationHandler.java index 35d923b7fb..bc07019957 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/CommandConfirmationHandler.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/CommandConfirmationHandler.java @@ -16,13 +16,12 @@ */ package org.apache.activemq.artemis.core.protocol.core; - /** * A CommandConfirmationHandler is used by the channel to confirm confirmations of packets. *

*/ -public interface CommandConfirmationHandler -{ +public interface CommandConfirmationHandler { + /** * called by channel after a confirmation has been received. * diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/CoreRemotingConnection.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/CoreRemotingConnection.java index 51237074f5..f2aa5b48d9 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/CoreRemotingConnection.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/CoreRemotingConnection.java @@ -19,15 +19,15 @@ package org.apache.activemq.artemis.core.protocol.core; import org.apache.activemq.artemis.core.security.ActiveMQPrincipal; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; - /** * Extension of RemotingConnection for the ActiveMQ Artemis core protocol */ -public interface CoreRemotingConnection extends RemotingConnection -{ +public interface CoreRemotingConnection extends RemotingConnection { - /** The client protocol used on the communication. - * This will determine if the client has support for certain packet types */ + /** + * The client protocol used on the communication. + * This will determine if the client has support for certain packet types + */ int getClientVersion(); /** @@ -40,7 +40,8 @@ public interface CoreRemotingConnection extends RemotingConnection * Returns the channel with the channel id specified. *

* If it does not exist create it with the confirmation window size. - * @param channelID the channel id + * + * @param channelID the channel id * @param confWindowSize the confirmation window size * @return the channel */ @@ -71,36 +72,42 @@ public interface CoreRemotingConnection extends RemotingConnection /** * Resets the id generator used to generate id's. + * * @param id the first id to set it to */ void syncIDGeneratorSequence(long id); /** * Returns the next id to be chosen. + * * @return the id */ long getIDGeneratorSequence(); /** * Returns the current timeout for blocking calls + * * @return the timeout in milliseconds */ long getBlockingCallTimeout(); /** * Returns the current timeout for blocking calls + * * @return the timeout in milliseconds */ long getBlockingCallFailoverTimeout(); /** * Returns the transfer lock used when transferring connections. + * * @return the lock */ Object getTransferLock(); /** * Returns the default security principal + * * @return the principal */ ActiveMQPrincipal getDefaultActiveMQPrincipal(); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/Packet.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/Packet.java index 3da787cff0..ddb734ee80 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/Packet.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/Packet.java @@ -22,8 +22,8 @@ import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; /** * A Packet represents a packet of data transmitted over a connection. */ -public interface Packet -{ +public interface Packet { + /** * Sets the channel id that should be used once the packet has been successfully decoded it is * sent to the correct channel. diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQClientProtocolManager.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQClientProtocolManager.java index d938b85670..73ea52925b 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQClientProtocolManager.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQClientProtocolManager.java @@ -72,8 +72,8 @@ import org.apache.activemq.artemis.utils.VersionLoader; * Implementations of this class need to be stateless. */ -public class ActiveMQClientProtocolManager implements ClientProtocolManager -{ +public class ActiveMQClientProtocolManager implements ClientProtocolManager { + private static final String handshake = "ARTEMIS"; private final int versionID = VersionLoader.getVersion().getIncrementingVersion(); @@ -106,117 +106,89 @@ public class ActiveMQClientProtocolManager implements ClientProtocolManager private final CountDownLatch waitLatch = new CountDownLatch(1); - - public ActiveMQClientProtocolManager() - { + public ActiveMQClientProtocolManager() { } - public String getName() - { + public String getName() { return ActiveMQClient.DEFAULT_CORE_PROTOCOL; } - public void setSessionFactory(ClientSessionFactory factory) - { - this.factoryInternal = (ClientSessionFactoryInternal)factory; + public void setSessionFactory(ClientSessionFactory factory) { + this.factoryInternal = (ClientSessionFactoryInternal) factory; } - public ClientSessionFactory getSessionFactory() - { + public ClientSessionFactory getSessionFactory() { return this.factoryInternal; } @Override - public void addChannelHandlers(ChannelPipeline pipeline) - { + public void addChannelHandlers(ChannelPipeline pipeline) { pipeline.addLast("activemq-decoder", new ActiveMQFrameDecoder2()); } - public boolean waitOnLatch(long milliseconds) throws InterruptedException - { + public boolean waitOnLatch(long milliseconds) throws InterruptedException { return waitLatch.await(milliseconds, TimeUnit.MILLISECONDS); } - public Channel getChannel0() - { - if (connection == null) - { + public Channel getChannel0() { + if (connection == null) { return null; } - else - { + else { return connection.getChannel(ChannelImpl.CHANNEL_ID.PING.id, -1); } } - public RemotingConnection getCurrentConnection() - { + public RemotingConnection getCurrentConnection() { return connection; } - - public Channel getChannel1() - { - if (connection == null) - { + public Channel getChannel1() { + if (connection == null) { return null; } - else - { + else { return connection.getChannel(1, -1); } } - public Lock lockSessionCreation() - { - try - { + public Lock lockSessionCreation() { + try { Lock localFailoverLock = factoryInternal.lockFailover(); - try - { - if (connection == null) - { + try { + if (connection == null) { return null; } Lock lock = getChannel1().getLock(); // Lock it - this must be done while the failoverLock is held - while (isAlive() && !lock.tryLock(100, TimeUnit.MILLISECONDS)) - { + while (isAlive() && !lock.tryLock(100, TimeUnit.MILLISECONDS)) { } return lock; } - finally - { + finally { localFailoverLock.unlock(); } // We can now release the failoverLock } - catch (InterruptedException e) - { + catch (InterruptedException e) { Thread.currentThread().interrupt(); return null; } } - - public void stop() - { + public void stop() { alive = false; - - synchronized (inCreateSessionGuard) - { + synchronized (inCreateSessionGuard) { if (inCreateSessionLatch != null) inCreateSessionLatch.countDown(); } - Channel channel1 = getChannel1(); - if (channel1 != null) - { + if (channel1 != null) { channel1.returnBlocking(); } @@ -224,15 +196,12 @@ public class ActiveMQClientProtocolManager implements ClientProtocolManager } - public boolean isAlive() - { + public boolean isAlive() { return alive; } - @Override - public void ping(long connectionTTL) - { + public void ping(long connectionTTL) { Channel channel = connection.getChannel(ChannelImpl.CHANNEL_ID.PING.id, -1); Ping ping = new Ping(connectionTTL); @@ -243,37 +212,26 @@ public class ActiveMQClientProtocolManager implements ClientProtocolManager } @Override - public void sendSubscribeTopology(final boolean isServer) - { - getChannel0().send(new SubscribeClusterTopologyUpdatesMessageV2(isServer, - VersionLoader.getVersion() - .getIncrementingVersion())); + public void sendSubscribeTopology(final boolean isServer) { + getChannel0().send(new SubscribeClusterTopologyUpdatesMessageV2(isServer, VersionLoader.getVersion().getIncrementingVersion())); } @Override - public SessionContext createSessionContext(String name, String username, String password, - boolean xa, boolean autoCommitSends, boolean autoCommitAcks, - boolean preAcknowledge, int minLargeMessageSize, int confirmationWindowSize) throws ActiveMQException - { - for (Version clientVersion : VersionLoader.getClientVersions()) - { - try - { - return createSessionContext(clientVersion, - name, - username, - password, - xa, - autoCommitSends, - autoCommitAcks, - preAcknowledge, - minLargeMessageSize, - confirmationWindowSize); + public SessionContext createSessionContext(String name, + String username, + String password, + boolean xa, + boolean autoCommitSends, + boolean autoCommitAcks, + boolean preAcknowledge, + int minLargeMessageSize, + int confirmationWindowSize) throws ActiveMQException { + for (Version clientVersion : VersionLoader.getClientVersions()) { + try { + return createSessionContext(clientVersion, name, username, password, xa, autoCommitSends, autoCommitAcks, preAcknowledge, minLargeMessageSize, confirmationWindowSize); } - catch (ActiveMQException e) - { - if (e.getType() != ActiveMQExceptionType.INCOMPATIBLE_CLIENT_SERVER_VERSIONS) - { + catch (ActiveMQException e) { + if (e.getType() != ActiveMQExceptionType.INCOMPATIBLE_CLIENT_SERVER_VERSIONS) { throw e; } } @@ -282,10 +240,16 @@ public class ActiveMQClientProtocolManager implements ClientProtocolManager throw new ActiveMQException(ActiveMQExceptionType.INCOMPATIBLE_CLIENT_SERVER_VERSIONS); } - public SessionContext createSessionContext(Version clientVersion, String name, String username, String password, - boolean xa, boolean autoCommitSends, boolean autoCommitAcks, - boolean preAcknowledge, int minLargeMessageSize, int confirmationWindowSize) throws ActiveMQException - { + public SessionContext createSessionContext(Version clientVersion, + String name, + String username, + String password, + boolean xa, + boolean autoCommitSends, + boolean autoCommitAcks, + boolean preAcknowledge, + int minLargeMessageSize, + int confirmationWindowSize) throws ActiveMQException { if (!isAlive()) throw ActiveMQClientMessageBundle.BUNDLE.clientSessionClosed(); @@ -293,20 +257,17 @@ public class ActiveMQClientProtocolManager implements ClientProtocolManager CreateSessionResponseMessage response = null; boolean retry; - do - { + do { retry = false; Lock lock = null; - try - { + try { lock = lockSessionCreation(); // We now set a flag saying createSession is executing - synchronized (inCreateSessionGuard) - { + synchronized (inCreateSessionGuard) { if (!isAlive()) throw ActiveMQClientMessageBundle.BUNDLE.clientSessionClosed(); inCreateSession = true; @@ -315,32 +276,17 @@ public class ActiveMQClientProtocolManager implements ClientProtocolManager long sessionChannelID = connection.generateChannelID(); - Packet request = new CreateSessionMessage(name, - sessionChannelID, - clientVersion.getIncrementingVersion(), - username, - password, - minLargeMessageSize, - xa, - autoCommitSends, - autoCommitAcks, - preAcknowledge, - confirmationWindowSize, - null); + Packet request = new CreateSessionMessage(name, sessionChannelID, clientVersion.getIncrementingVersion(), username, password, minLargeMessageSize, xa, autoCommitSends, autoCommitAcks, preAcknowledge, confirmationWindowSize, null); - - try - { + try { // channel1 reference here has to go away response = (CreateSessionResponseMessage) getChannel1().sendBlocking(request, PacketImpl.CREATESESSION_RESP); } - catch (ActiveMQException cause) - { + catch (ActiveMQException cause) { if (!isAlive()) throw cause; - if (cause.getType() == ActiveMQExceptionType.UNBLOCKED) - { + if (cause.getType() == ActiveMQExceptionType.UNBLOCKED) { // This means the thread was blocked on create session and failover unblocked it // so failover could occur @@ -348,37 +294,29 @@ public class ActiveMQClientProtocolManager implements ClientProtocolManager continue; } - else - { + else { throw cause; } } sessionChannel = connection.getChannel(sessionChannelID, confirmationWindowSize); - } - catch (Throwable t) - { - if (lock != null) - { + catch (Throwable t) { + if (lock != null) { lock.unlock(); lock = null; } - if (t instanceof ActiveMQException) - { + if (t instanceof ActiveMQException) { throw (ActiveMQException) t; } - else - { + else { throw ActiveMQClientMessageBundle.BUNDLE.failedToCreateSession(t); } } - finally - { - if (lock != null) - { + finally { + if (lock != null) { lock.unlock(); } @@ -386,60 +324,48 @@ public class ActiveMQClientProtocolManager implements ClientProtocolManager inCreateSession = false; inCreateSessionLatch.countDown(); } - } - while (retry); - + } while (retry); // these objects won't be null, otherwise it would keep retrying on the previous loop return new ActiveMQSessionContext(name, connection, sessionChannel, response.getServerVersion(), confirmationWindowSize); } - public boolean cleanupBeforeFailover(ActiveMQException cause) - { + public boolean cleanupBeforeFailover(ActiveMQException cause) { boolean needToInterrupt; CountDownLatch exitLockLatch; Lock lock = lockSessionCreation(); - if (lock == null) - { + if (lock == null) { return false; } - try - { - synchronized (inCreateSessionGuard) - { + try { + synchronized (inCreateSessionGuard) { needToInterrupt = inCreateSession; exitLockLatch = inCreateSessionLatch; } } - finally - { + finally { lock.unlock(); } - if (needToInterrupt) - { + if (needToInterrupt) { forceReturnChannel1(cause); // Now we need to make sure that the thread has actually exited and returned it's // connections // before failover occurs - while (inCreateSession && isAlive()) - { - try - { - if (exitLockLatch != null) - { + while (inCreateSession && isAlive()) { + try { + if (exitLockLatch != null) { exitLockLatch.await(500, TimeUnit.MILLISECONDS); } } - catch (InterruptedException e1) - { + catch (InterruptedException e1) { throw new ActiveMQInterruptedException(e1); } } @@ -449,37 +375,31 @@ public class ActiveMQClientProtocolManager implements ClientProtocolManager } @Override - public boolean checkForFailover(String liveNodeID) throws ActiveMQException - { + public boolean checkForFailover(String liveNodeID) throws ActiveMQException { CheckFailoverMessage packet = new CheckFailoverMessage(liveNodeID); - CheckFailoverReplyMessage message = (CheckFailoverReplyMessage) getChannel1().sendBlocking(packet, - PacketImpl.CHECK_FOR_FAILOVER_REPLY); + CheckFailoverReplyMessage message = (CheckFailoverReplyMessage) getChannel1().sendBlocking(packet, PacketImpl.CHECK_FOR_FAILOVER_REPLY); return message.isOkToFailover(); } - - public RemotingConnection connect(Connection transportConnection, long callTimeout, long callFailoverTimeout, - List incomingInterceptors, List outgoingInterceptors, - TopologyResponseHandler topologyResponseHandler) - { - this.connection = new RemotingConnectionImpl(getPacketDecoder(), transportConnection, - callTimeout, callFailoverTimeout, - incomingInterceptors, outgoingInterceptors); + public RemotingConnection connect(Connection transportConnection, + long callTimeout, + long callFailoverTimeout, + List incomingInterceptors, + List outgoingInterceptors, + TopologyResponseHandler topologyResponseHandler) { + this.connection = new RemotingConnectionImpl(getPacketDecoder(), transportConnection, callTimeout, callFailoverTimeout, incomingInterceptors, outgoingInterceptors); this.topologyResponseHandler = topologyResponseHandler; getChannel0().setHandler(new Channel0Handler(connection)); - sendHandshake(transportConnection); return connection; } - private void sendHandshake(Connection transportConnection) - { - if (transportConnection.isUsingProtocolHandling()) - { + private void sendHandshake(Connection transportConnection) { + if (transportConnection.isUsingProtocolHandling()) { // no need to send handshake on inVM as inVM is not using the NettyProtocolHandling ActiveMQBuffer amqbuffer = connection.createTransportBuffer(handshake.length()); amqbuffer.writeBytes(handshake.getBytes()); @@ -487,29 +407,24 @@ public class ActiveMQClientProtocolManager implements ClientProtocolManager } } + private class Channel0Handler implements ChannelHandler { - private class Channel0Handler implements ChannelHandler - { private final CoreRemotingConnection conn; - private Channel0Handler(final CoreRemotingConnection conn) - { + private Channel0Handler(final CoreRemotingConnection conn) { this.conn = conn; } - public void handlePacket(final Packet packet) - { + public void handlePacket(final Packet packet) { final byte type = packet.getType(); - if (type == PacketImpl.DISCONNECT || type == PacketImpl.DISCONNECT_V2) - { + if (type == PacketImpl.DISCONNECT || type == PacketImpl.DISCONNECT_V2) { final DisconnectMessage msg = (DisconnectMessage) packet; String scaleDownTargetNodeID = null; SimpleString nodeID = msg.getNodeID(); - if (packet instanceof DisconnectMessage_V2) - { + if (packet instanceof DisconnectMessage_V2) { final DisconnectMessage_V2 msg_v2 = (DisconnectMessage_V2) packet; scaleDownTargetNodeID = msg_v2.getScaleDownNodeID() == null ? null : msg_v2.getScaleDownNodeID().toString(); } @@ -517,23 +432,19 @@ public class ActiveMQClientProtocolManager implements ClientProtocolManager if (topologyResponseHandler != null) topologyResponseHandler.nodeDisconnected(conn, nodeID == null ? null : nodeID.toString(), scaleDownTargetNodeID); } - else if (type == PacketImpl.CLUSTER_TOPOLOGY) - { + else if (type == PacketImpl.CLUSTER_TOPOLOGY) { ClusterTopologyChangeMessage topMessage = (ClusterTopologyChangeMessage) packet; notifyTopologyChange(topMessage); } - else if (type == PacketImpl.CLUSTER_TOPOLOGY_V2) - { + else if (type == PacketImpl.CLUSTER_TOPOLOGY_V2) { ClusterTopologyChangeMessage_V2 topMessage = (ClusterTopologyChangeMessage_V2) packet; notifyTopologyChange(topMessage); } - else if (type == PacketImpl.CLUSTER_TOPOLOGY || type == PacketImpl.CLUSTER_TOPOLOGY_V2 || type == PacketImpl.CLUSTER_TOPOLOGY_V3) - { + else if (type == PacketImpl.CLUSTER_TOPOLOGY || type == PacketImpl.CLUSTER_TOPOLOGY_V2 || type == PacketImpl.CLUSTER_TOPOLOGY_V3) { ClusterTopologyChangeMessage topMessage = (ClusterTopologyChangeMessage) packet; notifyTopologyChange(topMessage); } - else if (type == PacketImpl.CHECK_FOR_FAILOVER_REPLY) - { + else if (type == PacketImpl.CHECK_FOR_FAILOVER_REPLY) { System.out.println("Channel0Handler.handlePacket"); } } @@ -541,73 +452,57 @@ public class ActiveMQClientProtocolManager implements ClientProtocolManager /** * @param topMessage */ - private void notifyTopologyChange(final ClusterTopologyChangeMessage topMessage) - { + private void notifyTopologyChange(final ClusterTopologyChangeMessage topMessage) { final long eventUID; final String backupGroupName; final String scaleDownGroupName; - if (topMessage instanceof ClusterTopologyChangeMessage_V3) - { + if (topMessage instanceof ClusterTopologyChangeMessage_V3) { eventUID = ((ClusterTopologyChangeMessage_V3) topMessage).getUniqueEventID(); backupGroupName = ((ClusterTopologyChangeMessage_V3) topMessage).getBackupGroupName(); scaleDownGroupName = ((ClusterTopologyChangeMessage_V3) topMessage).getScaleDownGroupName(); } - else if (topMessage instanceof ClusterTopologyChangeMessage_V2) - { + else if (topMessage instanceof ClusterTopologyChangeMessage_V2) { eventUID = ((ClusterTopologyChangeMessage_V2) topMessage).getUniqueEventID(); backupGroupName = ((ClusterTopologyChangeMessage_V2) topMessage).getBackupGroupName(); scaleDownGroupName = null; } - else - { + else { eventUID = System.currentTimeMillis(); backupGroupName = null; scaleDownGroupName = null; } - if (topMessage.isExit()) - { - if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) - { + if (topMessage.isExit()) { + if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) { ActiveMQClientLogger.LOGGER.debug("Notifying " + topMessage.getNodeID() + " going down"); } - if (topologyResponseHandler != null) - { + if (topologyResponseHandler != null) { topologyResponseHandler.notifyNodeDown(eventUID, topMessage.getNodeID()); } } - else - { + else { Pair transportConfig = topMessage.getPair(); - if (transportConfig.getA() == null && transportConfig.getB() == null) - { - transportConfig = new Pair<>(conn.getTransportConnection() - .getConnectorConfig(), - null); + if (transportConfig.getA() == null && transportConfig.getB() == null) { + transportConfig = new Pair<>(conn.getTransportConnection().getConnectorConfig(), null); } - if (topologyResponseHandler != null) - { + if (topologyResponseHandler != null) { topologyResponseHandler.notifyNodeUp(eventUID, topMessage.getNodeID(), backupGroupName, scaleDownGroupName, transportConfig, topMessage.isLast()); } } } } - protected PacketDecoder getPacketDecoder() - { + protected PacketDecoder getPacketDecoder() { return ClientPacketDecoder.INSTANCE; } - private void forceReturnChannel1(ActiveMQException cause) - { - if (connection != null) - { + private void forceReturnChannel1(ActiveMQException cause) { + if (connection != null) { Channel channel1 = connection.getChannel(1, -1); - if (channel1 != null) - { + if (channel1 != null) { channel1.returnBlocking(cause); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQClientProtocolManagerFactory.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQClientProtocolManagerFactory.java index 7c3435a373..a58834b7cc 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQClientProtocolManagerFactory.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQClientProtocolManagerFactory.java @@ -19,23 +19,20 @@ package org.apache.activemq.artemis.core.protocol.core.impl; import org.apache.activemq.artemis.spi.core.remoting.ClientProtocolManager; import org.apache.activemq.artemis.spi.core.remoting.ClientProtocolManagerFactory; -public class ActiveMQClientProtocolManagerFactory implements ClientProtocolManagerFactory -{ +public class ActiveMQClientProtocolManagerFactory implements ClientProtocolManagerFactory { + private static final long serialVersionUID = 1; private static final ActiveMQClientProtocolManagerFactory INSTANCE = new ActiveMQClientProtocolManagerFactory(); - private ActiveMQClientProtocolManagerFactory() - { + private ActiveMQClientProtocolManagerFactory() { } - public static final ActiveMQClientProtocolManagerFactory getInstance() - { + public static final ActiveMQClientProtocolManagerFactory getInstance() { return INSTANCE; } - public ClientProtocolManager newProtocolManager() - { + public ClientProtocolManager newProtocolManager() { return new ActiveMQClientProtocolManager(); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQConsumerContext.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQConsumerContext.java index 320930d729..08abb91db2 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQConsumerContext.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQConsumerContext.java @@ -18,36 +18,35 @@ package org.apache.activemq.artemis.core.protocol.core.impl; import org.apache.activemq.artemis.spi.core.remoting.ConsumerContext; -public class ActiveMQConsumerContext extends ConsumerContext -{ +public class ActiveMQConsumerContext extends ConsumerContext { + private long id; - public ActiveMQConsumerContext(long id) - { + public ActiveMQConsumerContext(long id) { this.id = id; } - public long getId() - { + public long getId() { return id; } @Override - public boolean equals(Object o) - { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; ActiveMQConsumerContext that = (ActiveMQConsumerContext) o; - if (id != that.id) return false; + if (id != that.id) + return false; return true; } @Override - public int hashCode() - { + public int hashCode() { return (int) (id ^ (id >>> 32)); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQSessionContext.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQSessionContext.java index 23370d5e18..5279de2a79 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQSessionContext.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQSessionContext.java @@ -107,16 +107,18 @@ import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SES import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_RECEIVE_LARGE_MSG; import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_RECEIVE_MSG; -public class ActiveMQSessionContext extends SessionContext -{ +public class ActiveMQSessionContext extends SessionContext { + private final Channel sessionChannel; private final int serverVersion; private int confirmationWindow; private final String name; - - public ActiveMQSessionContext(String name, RemotingConnection remotingConnection, Channel sessionChannel, int serverVersion, int confirmationWindow) - { + public ActiveMQSessionContext(String name, + RemotingConnection remotingConnection, + Channel sessionChannel, + int serverVersion, + int confirmationWindow) { super(remotingConnection); this.name = name; @@ -127,71 +129,55 @@ public class ActiveMQSessionContext extends SessionContext ChannelHandler handler = new ClientSessionPacketHandler(); sessionChannel.setHandler(handler); - - if (confirmationWindow >= 0) - { + if (confirmationWindow >= 0) { sessionChannel.setCommandConfirmationHandler(confirmationHandler); } } - - private final CommandConfirmationHandler confirmationHandler = new CommandConfirmationHandler() - { - public void commandConfirmed(final Packet packet) - { - if (packet.getType() == PacketImpl.SESS_SEND) - { + private final CommandConfirmationHandler confirmationHandler = new CommandConfirmationHandler() { + public void commandConfirmed(final Packet packet) { + if (packet.getType() == PacketImpl.SESS_SEND) { SessionSendMessage ssm = (SessionSendMessage) packet; callSendAck(ssm.getHandler(), ssm.getMessage()); } - else if (packet.getType() == PacketImpl.SESS_SEND_CONTINUATION) - { + else if (packet.getType() == PacketImpl.SESS_SEND_CONTINUATION) { SessionSendContinuationMessage scm = (SessionSendContinuationMessage) packet; - if (!scm.isContinues()) - { + if (!scm.isContinues()) { callSendAck(scm.getHandler(), scm.getMessage()); } } } - private void callSendAck(SendAcknowledgementHandler handler, final Message message) - { - if (handler != null) - { + private void callSendAck(SendAcknowledgementHandler handler, final Message message) { + if (handler != null) { handler.sendAcknowledged(message); } - else if (sendAckHandler != null) - { + else if (sendAckHandler != null) { sendAckHandler.sendAcknowledged(message); } } }; - // Failover utility methods @Override - public void returnBlocking(ActiveMQException cause) - { + public void returnBlocking(ActiveMQException cause) { sessionChannel.returnBlocking(cause); } @Override - public void lockCommunications() - { + public void lockCommunications() { sessionChannel.lock(); } @Override - public void releaseCommunications() - { + public void releaseCommunications() { sessionChannel.setTransferring(false); sessionChannel.unlock(); } - public void cleanup() - { + public void cleanup() { sessionChannel.close(); // if the server is sending a disconnect @@ -200,14 +186,11 @@ public class ActiveMQSessionContext extends SessionContext } @Override - public void linkFlowControl(SimpleString address, ClientProducerCreditsImpl clientProducerCredits) - { + public void linkFlowControl(SimpleString address, ClientProducerCreditsImpl clientProducerCredits) { // nothing to be done here... Flow control here is done on the core side } - - public void setSendAcknowledgementHandler(final SendAcknowledgementHandler handler) - { + public void setSendAcknowledgementHandler(final SendAcknowledgementHandler handler) { sessionChannel.setCommandConfirmationHandler(confirmationHandler); this.sendAckHandler = handler; } @@ -215,37 +198,34 @@ public class ActiveMQSessionContext extends SessionContext public void createSharedQueue(SimpleString address, SimpleString queueName, SimpleString filterString, - boolean durable) throws ActiveMQException - { + boolean durable) throws ActiveMQException { sessionChannel.sendBlocking(new CreateSharedQueueMessage(address, queueName, filterString, durable, true), PacketImpl.NULL_RESPONSE); } - public void deleteQueue(final SimpleString queueName) throws ActiveMQException - { + public void deleteQueue(final SimpleString queueName) throws ActiveMQException { sessionChannel.sendBlocking(new SessionDeleteQueueMessage(queueName), PacketImpl.NULL_RESPONSE); } - public ClientSession.QueueQuery queueQuery(final SimpleString queueName) throws ActiveMQException - { + public ClientSession.QueueQuery queueQuery(final SimpleString queueName) throws ActiveMQException { SessionQueueQueryMessage request = new SessionQueueQueryMessage(queueName); SessionQueueQueryResponseMessage_V2 response = (SessionQueueQueryResponseMessage_V2) sessionChannel.sendBlocking(request, PacketImpl.SESS_QUEUEQUERY_RESP_V2); return response.toQueueQuery(); } - public ClientConsumerInternal createConsumer(SimpleString queueName, SimpleString filterString, - int windowSize, int maxRate, int ackBatchSize, boolean browseOnly, - Executor executor, Executor flowControlExecutor) throws ActiveMQException - { + public ClientConsumerInternal createConsumer(SimpleString queueName, + SimpleString filterString, + int windowSize, + int maxRate, + int ackBatchSize, + boolean browseOnly, + Executor executor, + Executor flowControlExecutor) throws ActiveMQException { long consumerID = idGenerator.generateID(); ActiveMQConsumerContext consumerContext = new ActiveMQConsumerContext(consumerID); - SessionCreateConsumerMessage request = new SessionCreateConsumerMessage(consumerID, - queueName, - filterString, - browseOnly, - true); + SessionCreateConsumerMessage request = new SessionCreateConsumerMessage(consumerID, queueName, filterString, browseOnly, true); SessionQueueQueryResponseMessage_V2 queueInfo = (SessionQueueQueryResponseMessage_V2) sessionChannel.sendBlocking(request, PacketImpl.SESS_QUEUEQUERY_RESP_V2); @@ -253,133 +233,93 @@ public class ActiveMQSessionContext extends SessionContext // could be overridden on the queue settings // The value we send is just a hint - return new ClientConsumerImpl(session, - consumerContext, - queueName, - filterString, - browseOnly, - calcWindowSize(windowSize), - ackBatchSize, - maxRate > 0 ? new TokenBucketLimiterImpl(maxRate, - false) - : null, - executor, - flowControlExecutor, - this, - queueInfo.toQueueQuery(), - lookupTCCL()); + return new ClientConsumerImpl(session, consumerContext, queueName, filterString, browseOnly, calcWindowSize(windowSize), ackBatchSize, maxRate > 0 ? new TokenBucketLimiterImpl(maxRate, false) : null, executor, flowControlExecutor, this, queueInfo.toQueueQuery(), lookupTCCL()); } - - public int getServerVersion() - { + public int getServerVersion() { return serverVersion; } - public ClientSession.AddressQuery addressQuery(final SimpleString address) throws ActiveMQException - { - SessionBindingQueryResponseMessage_V2 response = - (SessionBindingQueryResponseMessage_V2) sessionChannel.sendBlocking(new SessionBindingQueryMessage(address), PacketImpl.SESS_BINDINGQUERY_RESP_V2); + public ClientSession.AddressQuery addressQuery(final SimpleString address) throws ActiveMQException { + SessionBindingQueryResponseMessage_V2 response = (SessionBindingQueryResponseMessage_V2) sessionChannel.sendBlocking(new SessionBindingQueryMessage(address), PacketImpl.SESS_BINDINGQUERY_RESP_V2); return new AddressQueryImpl(response.isExists(), response.getQueueNames(), response.isAutoCreateJmsQueues()); } - @Override - public void closeConsumer(final ClientConsumer consumer) throws ActiveMQException - { + public void closeConsumer(final ClientConsumer consumer) throws ActiveMQException { sessionChannel.sendBlocking(new SessionConsumerCloseMessage(getConsumerID(consumer)), PacketImpl.NULL_RESPONSE); } - public void sendConsumerCredits(final ClientConsumer consumer, final int credits) - { + public void sendConsumerCredits(final ClientConsumer consumer, final int credits) { sessionChannel.send(new SessionConsumerFlowCreditMessage(getConsumerID(consumer), credits)); } - public void forceDelivery(final ClientConsumer consumer, final long sequence) throws ActiveMQException - { + public void forceDelivery(final ClientConsumer consumer, final long sequence) throws ActiveMQException { SessionForceConsumerDelivery request = new SessionForceConsumerDelivery(getConsumerID(consumer), sequence); sessionChannel.send(request); } - public void simpleCommit() throws ActiveMQException - { + public void simpleCommit() throws ActiveMQException { sessionChannel.sendBlocking(new PacketImpl(PacketImpl.SESS_COMMIT), PacketImpl.NULL_RESPONSE); } - public void simpleRollback(boolean lastMessageAsDelivered) throws ActiveMQException - { + public void simpleRollback(boolean lastMessageAsDelivered) throws ActiveMQException { sessionChannel.sendBlocking(new RollbackMessage(lastMessageAsDelivered), PacketImpl.NULL_RESPONSE); } - public void sessionStart() throws ActiveMQException - { + public void sessionStart() throws ActiveMQException { sessionChannel.send(new PacketImpl(PacketImpl.SESS_START)); } - public void sessionStop() throws ActiveMQException - { + public void sessionStop() throws ActiveMQException { sessionChannel.sendBlocking(new PacketImpl(PacketImpl.SESS_STOP), PacketImpl.NULL_RESPONSE); } - public void addSessionMetadata(String key, String data) throws ActiveMQException - { + public void addSessionMetadata(String key, String data) throws ActiveMQException { sessionChannel.sendBlocking(new SessionAddMetaDataMessageV2(key, data), PacketImpl.NULL_RESPONSE); } - - public void addUniqueMetaData(String key, String data) throws ActiveMQException - { + public void addUniqueMetaData(String key, String data) throws ActiveMQException { sessionChannel.sendBlocking(new SessionUniqueAddMetaDataMessage(key, data), PacketImpl.NULL_RESPONSE); } - public void xaCommit(Xid xid, boolean onePhase) throws XAException, ActiveMQException - { + public void xaCommit(Xid xid, boolean onePhase) throws XAException, ActiveMQException { SessionXACommitMessage packet = new SessionXACommitMessage(xid, onePhase); SessionXAResponseMessage response = (SessionXAResponseMessage) sessionChannel.sendBlocking(packet, PacketImpl.SESS_XA_RESP); - if (response.isError()) - { + if (response.isError()) { throw new XAException(response.getResponseCode()); } - if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQClientLogger.LOGGER.isTraceEnabled()) { ActiveMQClientLogger.LOGGER.trace("finished commit on " + ClientSessionImpl.convert(xid) + " with response = " + response); } } - public void xaEnd(Xid xid, int flags) throws XAException, ActiveMQException - { + public void xaEnd(Xid xid, int flags) throws XAException, ActiveMQException { Packet packet; - if (flags == XAResource.TMSUSPEND) - { + if (flags == XAResource.TMSUSPEND) { packet = new PacketImpl(PacketImpl.SESS_XA_SUSPEND); } - else if (flags == XAResource.TMSUCCESS) - { + else if (flags == XAResource.TMSUCCESS) { packet = new SessionXAEndMessage(xid, false); } - else if (flags == XAResource.TMFAIL) - { + else if (flags == XAResource.TMFAIL) { packet = new SessionXAEndMessage(xid, true); } - else - { + else { throw new XAException(XAException.XAER_INVAL); } SessionXAResponseMessage response = (SessionXAResponseMessage) sessionChannel.sendBlocking(packet, PacketImpl.SESS_XA_RESP); - if (response.isError()) - { + if (response.isError()) { throw new XAException(response.getResponseCode()); } } - - public void sendProducerCreditsMessage(final int credits, final SimpleString address) - { + public void sendProducerCreditsMessage(final int credits, final SimpleString address) { sessionChannel.send(new SessionRequestProducerCreditsMessage(credits, address)); } @@ -388,34 +328,31 @@ public class ActiveMQSessionContext extends SessionContext * * @return */ - public boolean supportsLargeMessage() - { + public boolean supportsLargeMessage() { return true; } @Override - public int getCreditsOnSendingFull(MessageInternal msgI) - { + public int getCreditsOnSendingFull(MessageInternal msgI) { return msgI.getEncodeSize(); } - public void sendFullMessage(MessageInternal msgI, boolean sendBlocking, SendAcknowledgementHandler handler, SimpleString defaultAddress) throws ActiveMQException - { + public void sendFullMessage(MessageInternal msgI, + boolean sendBlocking, + SendAcknowledgementHandler handler, + SimpleString defaultAddress) throws ActiveMQException { SessionSendMessage packet = new SessionSendMessage(msgI, sendBlocking, handler); - if (sendBlocking) - { + if (sendBlocking) { sessionChannel.sendBlocking(packet, PacketImpl.NULL_RESPONSE); } - else - { + else { sessionChannel.sendBatched(packet); } } @Override - public int sendInitialChunkOnLargeMessage(MessageInternal msgI) throws ActiveMQException - { + public int sendInitialChunkOnLargeMessage(MessageInternal msgI) throws ActiveMQException { SessionSendLargeMessage initialChunk = new SessionSendLargeMessage(msgI); sessionChannel.send(initialChunk); @@ -424,89 +361,78 @@ public class ActiveMQSessionContext extends SessionContext } @Override - public int sendLargeMessageChunk(MessageInternal msgI, long messageBodySize, boolean sendBlocking, boolean lastChunk, byte[] chunk, SendAcknowledgementHandler messageHandler) throws ActiveMQException - { + public int sendLargeMessageChunk(MessageInternal msgI, + long messageBodySize, + boolean sendBlocking, + boolean lastChunk, + byte[] chunk, + SendAcknowledgementHandler messageHandler) throws ActiveMQException { final boolean requiresResponse = lastChunk && sendBlocking; - final SessionSendContinuationMessage chunkPacket = - new SessionSendContinuationMessage(msgI, chunk, !lastChunk, - requiresResponse, messageBodySize, messageHandler); + final SessionSendContinuationMessage chunkPacket = new SessionSendContinuationMessage(msgI, chunk, !lastChunk, requiresResponse, messageBodySize, messageHandler); - if (requiresResponse) - { + if (requiresResponse) { // When sending it blocking, only the last chunk will be blocking. sessionChannel.sendBlocking(chunkPacket, PacketImpl.NULL_RESPONSE); } - else - { + else { sessionChannel.send(chunkPacket); } return chunkPacket.getPacketSize(); } - public void sendACK(boolean individual, boolean block, final ClientConsumer consumer, final Message message) throws ActiveMQException - { + public void sendACK(boolean individual, + boolean block, + final ClientConsumer consumer, + final Message message) throws ActiveMQException { PacketImpl messagePacket; - if (individual) - { + if (individual) { messagePacket = new SessionIndividualAcknowledgeMessage(getConsumerID(consumer), message.getMessageID(), block); } - else - { + else { messagePacket = new SessionAcknowledgeMessage(getConsumerID(consumer), message.getMessageID(), block); } - if (block) - { + if (block) { sessionChannel.sendBlocking(messagePacket, PacketImpl.NULL_RESPONSE); } - else - { + else { sessionChannel.sendBatched(messagePacket); } } - public void expireMessage(final ClientConsumer consumer, Message message) throws ActiveMQException - { + public void expireMessage(final ClientConsumer consumer, Message message) throws ActiveMQException { SessionExpireMessage messagePacket = new SessionExpireMessage(getConsumerID(consumer), message.getMessageID()); sessionChannel.send(messagePacket); } - - public void sessionClose() throws ActiveMQException - { + public void sessionClose() throws ActiveMQException { sessionChannel.sendBlocking(new SessionCloseMessage(), PacketImpl.NULL_RESPONSE); } - public void xaForget(Xid xid) throws XAException, ActiveMQException - { + public void xaForget(Xid xid) throws XAException, ActiveMQException { SessionXAResponseMessage response = (SessionXAResponseMessage) sessionChannel.sendBlocking(new SessionXAForgetMessage(xid), PacketImpl.SESS_XA_RESP); - if (response.isError()) - { + if (response.isError()) { throw new XAException(response.getResponseCode()); } } - public int xaPrepare(Xid xid) throws XAException, ActiveMQException - { + public int xaPrepare(Xid xid) throws XAException, ActiveMQException { SessionXAPrepareMessage packet = new SessionXAPrepareMessage(xid); SessionXAResponseMessage response = (SessionXAResponseMessage) sessionChannel.sendBlocking(packet, PacketImpl.SESS_XA_RESP); - if (response.isError()) - { + if (response.isError()) { throw new XAException(response.getResponseCode()); } - else - { + else { return response.getResponseCode(); } } - public Xid[] xaScan() throws ActiveMQException - { + public Xid[] xaScan() throws ActiveMQException { SessionXAGetInDoubtXidsResponseMessage response = (SessionXAGetInDoubtXidsResponseMessage) sessionChannel.sendBlocking(new PacketImpl(PacketImpl.SESS_XA_INDOUBT_XIDS), PacketImpl.SESS_XA_INDOUBT_XIDS_RESP); List xids = response.getXids(); @@ -516,71 +442,63 @@ public class ActiveMQSessionContext extends SessionContext return xidArray; } - public void xaRollback(Xid xid, boolean wasStarted) throws ActiveMQException, XAException - { + public void xaRollback(Xid xid, boolean wasStarted) throws ActiveMQException, XAException { SessionXARollbackMessage packet = new SessionXARollbackMessage(xid); SessionXAResponseMessage response = (SessionXAResponseMessage) sessionChannel.sendBlocking(packet, PacketImpl.SESS_XA_RESP); - if (response.isError()) - { + if (response.isError()) { throw new XAException(response.getResponseCode()); } } - public void xaStart(Xid xid, int flags) throws XAException, ActiveMQException - { + public void xaStart(Xid xid, int flags) throws XAException, ActiveMQException { Packet packet; - if (flags == XAResource.TMJOIN) - { + if (flags == XAResource.TMJOIN) { packet = new SessionXAJoinMessage(xid); } - else if (flags == XAResource.TMRESUME) - { + else if (flags == XAResource.TMRESUME) { packet = new SessionXAResumeMessage(xid); } - else if (flags == XAResource.TMNOFLAGS) - { + else if (flags == XAResource.TMNOFLAGS) { // Don't need to flush since the previous end will have done this packet = new SessionXAStartMessage(xid); } - else - { + else { throw new XAException(XAException.XAER_INVAL); } SessionXAResponseMessage response = (SessionXAResponseMessage) sessionChannel.sendBlocking(packet, PacketImpl.SESS_XA_RESP); - if (response.isError()) - { + if (response.isError()) { ActiveMQClientLogger.LOGGER.errorCallingStart(response.getMessage(), response.getResponseCode()); throw new XAException(response.getResponseCode()); } } - public boolean configureTransactionTimeout(int seconds) throws ActiveMQException - { + public boolean configureTransactionTimeout(int seconds) throws ActiveMQException { SessionXASetTimeoutResponseMessage response = (SessionXASetTimeoutResponseMessage) sessionChannel.sendBlocking(new SessionXASetTimeoutMessage(seconds), PacketImpl.SESS_XA_SET_TIMEOUT_RESP); return response.isOK(); } - public int recoverSessionTimeout() throws ActiveMQException - { + public int recoverSessionTimeout() throws ActiveMQException { SessionXAGetTimeoutResponseMessage response = (SessionXAGetTimeoutResponseMessage) sessionChannel.sendBlocking(new PacketImpl(PacketImpl.SESS_XA_GET_TIMEOUT), PacketImpl.SESS_XA_GET_TIMEOUT_RESP); return response.getTimeoutSeconds(); } - public void createQueue(SimpleString address, SimpleString queueName, SimpleString filterString, boolean durable, boolean temp) throws ActiveMQException - { + public void createQueue(SimpleString address, + SimpleString queueName, + SimpleString filterString, + boolean durable, + boolean temp) throws ActiveMQException { CreateQueueMessage request = new CreateQueueMessage(address, queueName, filterString, durable, temp, true); sessionChannel.sendBlocking(request, PacketImpl.NULL_RESPONSE); } @Override - public boolean reattachOnNewConnection(RemotingConnection newConnection) throws ActiveMQException - { + public boolean reattachOnNewConnection(RemotingConnection newConnection) throws ActiveMQException { this.remotingConnection = newConnection; @@ -592,8 +510,7 @@ public class ActiveMQSessionContext extends SessionContext ReattachSessionResponseMessage response = (ReattachSessionResponseMessage) channel1.sendBlocking(request, PacketImpl.REATTACH_SESSION_RESP); - if (response.isReattached()) - { + if (response.isReattached()) { ActiveMQClientLogger.LOGGER.replayingCommands(sessionChannel.getID(), response.getLastConfirmedCommandID()); // The session was found on the server - we reattached transparently ok @@ -601,8 +518,7 @@ public class ActiveMQSessionContext extends SessionContext return true; } - else - { + else { ActiveMQClientLogger.LOGGER.reconnectCreatingNewSession(sessionChannel.getID()); sessionChannel.clearCommands(); @@ -619,148 +535,102 @@ public class ActiveMQSessionContext extends SessionContext final boolean autoCommitSends, final boolean autoCommitAcks, final boolean preAcknowledge, - final SimpleString defaultAddress) throws ActiveMQException - { - Packet createRequest = new CreateSessionMessage(name, - sessionChannel.getID(), - VersionLoader.getVersion().getIncrementingVersion(), - username, - password, - minLargeMessageSize, - xa, - autoCommitSends, - autoCommitAcks, - preAcknowledge, - confirmationWindow, - defaultAddress == null ? null - : defaultAddress.toString()); + final SimpleString defaultAddress) throws ActiveMQException { + Packet createRequest = new CreateSessionMessage(name, sessionChannel.getID(), VersionLoader.getVersion().getIncrementingVersion(), username, password, minLargeMessageSize, xa, autoCommitSends, autoCommitAcks, preAcknowledge, confirmationWindow, defaultAddress == null ? null : defaultAddress.toString()); boolean retry; - do - { - try - { + do { + try { getCreateChannel().sendBlocking(createRequest, PacketImpl.CREATESESSION_RESP); retry = false; } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { // the session was created while its server was starting, retry it: - if (e.getType() == ActiveMQExceptionType.SESSION_CREATION_REJECTED) - { + if (e.getType() == ActiveMQExceptionType.SESSION_CREATION_REJECTED) { ActiveMQClientLogger.LOGGER.retryCreateSessionSeverStarting(name); retry = true; // sleep a little bit to avoid spinning too much - try - { + try { Thread.sleep(10); } - catch (InterruptedException ie) - { + catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw e; } } - else - { + else { throw e; } } - } - while (retry && !session.isClosing()); + } while (retry && !session.isClosing()); } @Override - public void recreateConsumerOnServer(ClientConsumerInternal consumerInternal) throws ActiveMQException - { + public void recreateConsumerOnServer(ClientConsumerInternal consumerInternal) throws ActiveMQException { ClientSession.QueueQuery queueInfo = consumerInternal.getQueueInfo(); // We try and recreate any non durable queues, since they probably won't be there unless // they are defined in broker.xml // This allows e.g. JMS non durable subs and temporary queues to continue to be used after failover - if (!queueInfo.isDurable()) - { - CreateQueueMessage createQueueRequest = new CreateQueueMessage(queueInfo.getAddress(), - queueInfo.getName(), - queueInfo.getFilterString(), - false, - queueInfo.isTemporary(), - false); + if (!queueInfo.isDurable()) { + CreateQueueMessage createQueueRequest = new CreateQueueMessage(queueInfo.getAddress(), queueInfo.getName(), queueInfo.getFilterString(), false, queueInfo.isTemporary(), false); sendPacketWithoutLock(sessionChannel, createQueueRequest); } - SessionCreateConsumerMessage createConsumerRequest = new SessionCreateConsumerMessage(getConsumerID(consumerInternal), - consumerInternal.getQueueName(), - consumerInternal.getFilterString(), - consumerInternal.isBrowseOnly(), - false); + SessionCreateConsumerMessage createConsumerRequest = new SessionCreateConsumerMessage(getConsumerID(consumerInternal), consumerInternal.getQueueName(), consumerInternal.getFilterString(), consumerInternal.isBrowseOnly(), false); sendPacketWithoutLock(sessionChannel, createConsumerRequest); int clientWindowSize = consumerInternal.getClientWindowSize(); - if (clientWindowSize != 0) - { - SessionConsumerFlowCreditMessage packet = new SessionConsumerFlowCreditMessage(getConsumerID(consumerInternal), - clientWindowSize); + if (clientWindowSize != 0) { + SessionConsumerFlowCreditMessage packet = new SessionConsumerFlowCreditMessage(getConsumerID(consumerInternal), clientWindowSize); sendPacketWithoutLock(sessionChannel, packet); } - else - { + else { // https://jira.jboss.org/browse/HORNETQ-522 - SessionConsumerFlowCreditMessage packet = new SessionConsumerFlowCreditMessage(getConsumerID(consumerInternal), - 1); + SessionConsumerFlowCreditMessage packet = new SessionConsumerFlowCreditMessage(getConsumerID(consumerInternal), 1); sendPacketWithoutLock(sessionChannel, packet); } } - public void xaFailed(Xid xid) throws ActiveMQException - { + public void xaFailed(Xid xid) throws ActiveMQException { sendPacketWithoutLock(sessionChannel, new SessionXAAfterFailedMessage(xid)); } - public void restartSession() throws ActiveMQException - { + public void restartSession() throws ActiveMQException { sendPacketWithoutLock(sessionChannel, new PacketImpl(PacketImpl.SESS_START)); } @Override - public void resetMetadata(HashMap metaDataToSend) - { + public void resetMetadata(HashMap metaDataToSend) { // Resetting the metadata after failover - for (Map.Entry entries : metaDataToSend.entrySet()) - { + for (Map.Entry entries : metaDataToSend.entrySet()) { sendPacketWithoutLock(sessionChannel, new SessionAddMetaDataMessageV2(entries.getKey(), entries.getValue(), false)); } } - - private Channel getCreateChannel() - { + private Channel getCreateChannel() { return getCoreConnection().getChannel(1, -1); } - private CoreRemotingConnection getCoreConnection() - { + private CoreRemotingConnection getCoreConnection() { return (CoreRemotingConnection) remotingConnection; } - /** * This doesn't apply to other protocols probably, so it will be an ActiveMQ Artemis exclusive feature * * @throws ActiveMQException */ - private void handleConsumerDisconnected(DisconnectConsumerMessage packet) throws ActiveMQException - { + private void handleConsumerDisconnected(DisconnectConsumerMessage packet) throws ActiveMQException { DisconnectConsumerMessage message = packet; session.handleConsumerDisconnect(new ActiveMQConsumerContext(message.getConsumerId())); } - private void handleReceivedMessagePacket(SessionReceiveMessage messagePacket) throws Exception - { + private void handleReceivedMessagePacket(SessionReceiveMessage messagePacket) throws Exception { ClientMessageInternal msgi = (ClientMessageInternal) messagePacket.getMessage(); msgi.setDeliveryCount(messagePacket.getDeliveryCount()); @@ -770,8 +640,7 @@ public class ActiveMQSessionContext extends SessionContext handleReceiveMessage(new ActiveMQConsumerContext(messagePacket.getConsumerID()), msgi); } - private void handleReceiveLargeMessage(SessionReceiveLargeMessage serverPacket) throws Exception - { + private void handleReceiveLargeMessage(SessionReceiveLargeMessage serverPacket) throws Exception { ClientLargeMessageInternal clientLargeMessage = (ClientLargeMessageInternal) serverPacket.getLargeMessage(); clientLargeMessage.setFlowControlSize(serverPacket.getPacketSize()); @@ -781,73 +650,55 @@ public class ActiveMQSessionContext extends SessionContext handleReceiveLargeMessage(new ActiveMQConsumerContext(serverPacket.getConsumerID()), clientLargeMessage, serverPacket.getLargeMessageSize()); } - - private void handleReceiveContinuation(SessionReceiveContinuationMessage continuationPacket) throws Exception - { - handleReceiveContinuation(new ActiveMQConsumerContext(continuationPacket.getConsumerID()), continuationPacket.getBody(), continuationPacket.getPacketSize(), - continuationPacket.isContinues()); + private void handleReceiveContinuation(SessionReceiveContinuationMessage continuationPacket) throws Exception { + handleReceiveContinuation(new ActiveMQConsumerContext(continuationPacket.getConsumerID()), continuationPacket.getBody(), continuationPacket.getPacketSize(), continuationPacket.isContinues()); } - - protected void handleReceiveProducerCredits(SessionProducerCreditsMessage message) - { + protected void handleReceiveProducerCredits(SessionProducerCreditsMessage message) { handleReceiveProducerCredits(message.getAddress(), message.getCredits()); } - - protected void handleReceiveProducerFailCredits(SessionProducerCreditsFailMessage message) - { + protected void handleReceiveProducerFailCredits(SessionProducerCreditsFailMessage message) { handleReceiveProducerFailCredits(message.getAddress(), message.getCredits()); } - class ClientSessionPacketHandler implements ChannelHandler - { + class ClientSessionPacketHandler implements ChannelHandler { - public void handlePacket(final Packet packet) - { + public void handlePacket(final Packet packet) { byte type = packet.getType(); - try - { - switch (type) - { - case DISCONNECT_CONSUMER: - { + try { + switch (type) { + case DISCONNECT_CONSUMER: { handleConsumerDisconnected((DisconnectConsumerMessage) packet); break; } - case SESS_RECEIVE_CONTINUATION: - { + case SESS_RECEIVE_CONTINUATION: { handleReceiveContinuation((SessionReceiveContinuationMessage) packet); break; } - case SESS_RECEIVE_MSG: - { + case SESS_RECEIVE_MSG: { handleReceivedMessagePacket((SessionReceiveMessage) packet); break; } - case SESS_RECEIVE_LARGE_MSG: - { + case SESS_RECEIVE_LARGE_MSG: { handleReceiveLargeMessage((SessionReceiveLargeMessage) packet); break; } - case PacketImpl.SESS_PRODUCER_CREDITS: - { + case PacketImpl.SESS_PRODUCER_CREDITS: { handleReceiveProducerCredits((SessionProducerCreditsMessage) packet); break; } - case PacketImpl.SESS_PRODUCER_FAIL_CREDITS: - { + case PacketImpl.SESS_PRODUCER_FAIL_CREDITS: { handleReceiveProducerFailCredits((SessionProducerCreditsFailMessage) packet); break; } - case EXCEPTION: - { + case EXCEPTION: { // We can only log these exceptions // maybe we should cache it on SessionContext and throw an exception on any next calls ActiveMQExceptionMessage mem = (ActiveMQExceptionMessage) packet; @@ -856,14 +707,12 @@ public class ActiveMQSessionContext extends SessionContext break; } - default: - { + default: { throw new IllegalStateException("Invalid packet: " + type); } } } - catch (Exception e) - { + catch (Exception e) { ActiveMQClientLogger.LOGGER.failedToHandlePacket(e); } @@ -871,58 +720,46 @@ public class ActiveMQSessionContext extends SessionContext } } - private long getConsumerID(ClientConsumer consumer) - { - return ((ActiveMQConsumerContext)consumer.getConsumerContext()).getId(); + private long getConsumerID(ClientConsumer consumer) { + return ((ActiveMQConsumerContext) consumer.getConsumerContext()).getId(); } - private ClassLoader lookupTCCL() - { - return AccessController.doPrivileged(new PrivilegedAction() - { - public ClassLoader run() - { + private ClassLoader lookupTCCL() { + return AccessController.doPrivileged(new PrivilegedAction() { + public ClassLoader run() { return Thread.currentThread().getContextClassLoader(); } }); } - private int calcWindowSize(final int windowSize) - { + private int calcWindowSize(final int windowSize) { int clientWindowSize; - if (windowSize == -1) - { + if (windowSize == -1) { // No flow control - buffer can increase without bound! Only use with // caution for very fast consumers clientWindowSize = -1; } - else if (windowSize == 0) - { + else if (windowSize == 0) { // Slow consumer - no buffering clientWindowSize = 0; } - else if (windowSize == 1) - { + else if (windowSize == 1) { // Slow consumer = buffer 1 clientWindowSize = 1; } - else if (windowSize > 1) - { + else if (windowSize > 1) { // Client window size is half server window size clientWindowSize = windowSize >> 1; } - else - { + else { throw ActiveMQClientMessageBundle.BUNDLE.invalidWindowSize(windowSize); } return clientWindowSize; } - - private void sendPacketWithoutLock(final Channel parameterChannel, final Packet packet) - { + private void sendPacketWithoutLock(final Channel parameterChannel, final Packet packet) { packet.setChannelID(parameterChannel.getID()); Connection conn = parameterChannel.getConnection().getTransportConnection(); @@ -932,5 +769,4 @@ public class ActiveMQSessionContext extends SessionContext conn.write(buffer, false, false); } - } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/BackwardsCompatibilityUtils.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/BackwardsCompatibilityUtils.java index 2b32f1fe6e..9419796ba8 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/BackwardsCompatibilityUtils.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/BackwardsCompatibilityUtils.java @@ -23,25 +23,21 @@ import org.apache.activemq.artemis.api.core.client.TopologyMember; /** * This is a utility class to house any HornetQ client specific backwards compatibility methods. - * */ -public class BackwardsCompatibilityUtils -{ +public class BackwardsCompatibilityUtils { + private static int INITIAL_ACTIVEMQ_INCREMENTING_VERSION = 126; - public static Pair getTCPair(int clientIncrementingVersion, TopologyMember member) - { - if (clientIncrementingVersion < INITIAL_ACTIVEMQ_INCREMENTING_VERSION) - { + public static Pair getTCPair(int clientIncrementingVersion, + TopologyMember member) { + if (clientIncrementingVersion < INITIAL_ACTIVEMQ_INCREMENTING_VERSION) { return new Pair<>(replaceClassName(member.getLive()), replaceClassName(member.getBackup())); } return new Pair<>(member.getLive(), member.getBackup()); } - private static TransportConfiguration replaceClassName(TransportConfiguration tc) - { - if (tc != null) - { + private static TransportConfiguration replaceClassName(TransportConfiguration tc) { + if (tc != null) { String className = tc.getFactoryClassName().replace("org.apache.activemq.artemis", "org.hornetq").replace("ActiveMQ", "HornetQ"); return new TransportConfiguration(className, tc.getParams(), tc.getName()); } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ChannelImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ChannelImpl.java index 92e52d3201..373bfa4e97 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ChannelImpl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ChannelImpl.java @@ -40,10 +40,9 @@ import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ActiveMQEx import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.PacketsConfirmedMessage; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; -public final class ChannelImpl implements Channel -{ - public enum CHANNEL_ID - { +public final class ChannelImpl implements Channel { + + public enum CHANNEL_ID { /** * Used for core protocol management. */ @@ -67,16 +66,14 @@ public final class ChannelImpl implements Channel public final long id; - CHANNEL_ID(long id) - { + CHANNEL_ID(long id) { this.id = id; } - protected static String idToString(long code) - { - for (CHANNEL_ID channel : EnumSet.allOf(CHANNEL_ID.class)) - { - if (channel.id == code) return channel.toString(); + protected static String idToString(long code) { + for (CHANNEL_ID channel : EnumSet.allOf(CHANNEL_ID.class)) { + if (channel.id == code) + return channel.toString(); } return Long.toString(code); } @@ -122,32 +119,30 @@ public final class ChannelImpl implements Channel private final List interceptors; - public ChannelImpl(final CoreRemotingConnection connection, final long id, final int confWindowSize, final List interceptors) - { + public ChannelImpl(final CoreRemotingConnection connection, + final long id, + final int confWindowSize, + final List interceptors) { this.connection = connection; this.id = id; this.confWindowSize = confWindowSize; - if (confWindowSize != -1) - { + if (confWindowSize != -1) { resendCache = new ConcurrentLinkedQueue(); } - else - { + else { resendCache = null; } this.interceptors = interceptors; } - public boolean supports(final byte packetType) - { + public boolean supports(final byte packetType) { int version = connection.getClientVersion(); - switch (packetType) - { + switch (packetType) { case PacketImpl.CLUSTER_TOPOLOGY_V2: return version >= 122; case PacketImpl.DISCONNECT_CONSUMER: @@ -165,81 +160,65 @@ public final class ChannelImpl implements Channel } } - public long getID() - { + public long getID() { return id; } - public int getLastConfirmedCommandID() - { + public int getLastConfirmedCommandID() { return lastConfirmedCommandID.get(); } - public Lock getLock() - { + public Lock getLock() { return lock; } - public int getConfirmationWindowSize() - { + public int getConfirmationWindowSize() { return confWindowSize; } - public void returnBlocking() - { + public void returnBlocking() { returnBlocking(null); } - public void returnBlocking(Throwable cause) - { + public void returnBlocking(Throwable cause) { lock.lock(); - try - { + try { response = new ActiveMQExceptionMessage(ActiveMQClientMessageBundle.BUNDLE.unblockingACall(cause)); sendCondition.signal(); } - finally - { + finally { lock.unlock(); } } - public boolean sendAndFlush(final Packet packet) - { + public boolean sendAndFlush(final Packet packet) { return send(packet, true, false); } - public boolean send(final Packet packet) - { + public boolean send(final Packet packet) { return send(packet, false, false); } - public boolean sendBatched(final Packet packet) - { + public boolean sendBatched(final Packet packet) { return send(packet, false, true); } - public void setTransferring(boolean transferring) - { + public void setTransferring(boolean transferring) { this.transferring = transferring; } // This must never called by more than one thread concurrently - public boolean send(final Packet packet, final boolean flush, final boolean batch) - { - if (invokeInterceptors(packet, interceptors, connection) != null) - { + public boolean send(final Packet packet, final boolean flush, final boolean batch) { + if (invokeInterceptors(packet, interceptors, connection) != null) { return false; } - synchronized (sendLock) - { + synchronized (sendLock) { packet.setChannelID(id); - if (isTrace) - { + if (isTrace) { ActiveMQClientLogger.LOGGER.trace("Sending packet nonblocking " + packet + " on channeID=" + id); } @@ -247,43 +226,34 @@ public final class ChannelImpl implements Channel lock.lock(); - try - { - if (failingOver) - { + try { + if (failingOver) { // TODO - don't hardcode this timeout - try - { + try { failoverCondition.await(10000, TimeUnit.MILLISECONDS); } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } } // Sanity check - if (transferring) - { + if (transferring) { throw new IllegalStateException("Cannot send a packet while channel is doing failover"); } - if (resendCache != null && packet.isRequiresConfirmations()) - { + if (resendCache != null && packet.isRequiresConfirmations()) { resendCache.add(packet); } } - finally - { + finally { lock.unlock(); } - if (isTrace) - { + if (isTrace) { ActiveMQClientLogger.LOGGER.trace("Writing buffer for channelID=" + id); } - // The actual send must be outside the lock, or with OIO transport, the write can block if the tcp // buffer is full, preventing any incoming buffers being handled and blocking failover connection.getTransportConnection().write(buffer, flush, batch); @@ -297,67 +267,53 @@ public final class ChannelImpl implements Channel * and the client could eventually retry another call, but the server could then answer a previous command issuing a class-cast-exception. * The expectedPacket will be used to filter out undesirable packets that would belong to previous calls. */ - public Packet sendBlocking(final Packet packet, byte expectedPacket) throws ActiveMQException - { + public Packet sendBlocking(final Packet packet, byte expectedPacket) throws ActiveMQException { String interceptionResult = invokeInterceptors(packet, interceptors, connection); - if (interceptionResult != null) - { + if (interceptionResult != null) { // if we don't throw an exception here the client might not unblock throw ActiveMQClientMessageBundle.BUNDLE.interceptorRejectedPacket(interceptionResult); } - if (closed) - { + if (closed) { throw ActiveMQClientMessageBundle.BUNDLE.connectionDestroyed(); } - if (connection.getBlockingCallTimeout() == -1) - { + if (connection.getBlockingCallTimeout() == -1) { throw new IllegalStateException("Cannot do a blocking call timeout on a server side connection"); } // Synchronized since can't be called concurrently by more than one thread and this can occur // E.g. blocking acknowledge() from inside a message handler at some time as other operation on main thread - synchronized (sendBlockingLock) - { + synchronized (sendBlockingLock) { packet.setChannelID(id); final ActiveMQBuffer buffer = packet.encode(connection); lock.lock(); - try - { - if (failingOver) - { - try - { - if (connection.getBlockingCallFailoverTimeout() < 0) - { - while (failingOver) - { + try { + if (failingOver) { + try { + if (connection.getBlockingCallFailoverTimeout() < 0) { + while (failingOver) { failoverCondition.await(); } } - else - { - if (!failoverCondition.await(connection.getBlockingCallFailoverTimeout(), TimeUnit.MILLISECONDS)) - { + else { + if (!failoverCondition.await(connection.getBlockingCallFailoverTimeout(), TimeUnit.MILLISECONDS)) { ActiveMQClientLogger.LOGGER.debug("timed-out waiting for failover condition"); } } } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } } response = null; - if (resendCache != null && packet.isRequiresConfirmations()) - { + if (resendCache != null && packet.isRequiresConfirmations()) { resendCache.add(packet); } @@ -367,25 +323,19 @@ public final class ChannelImpl implements Channel long start = System.currentTimeMillis(); - while (!closed && (response == null || (response.getType() != PacketImpl.EXCEPTION && - response.getType() != expectedPacket)) && toWait > 0) - { - try - { + while (!closed && (response == null || (response.getType() != PacketImpl.EXCEPTION && response.getType() != expectedPacket)) && toWait > 0) { + try { sendCondition.await(toWait, TimeUnit.MILLISECONDS); } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } - if (response != null && response.getType() != PacketImpl.EXCEPTION && response.getType() != expectedPacket) - { + if (response != null && response.getType() != PacketImpl.EXCEPTION && response.getType() != expectedPacket) { ActiveMQClientLogger.LOGGER.packetOutOfOrder(response, new Exception("trace")); } - if (closed) - { + if (closed) { break; } @@ -396,13 +346,11 @@ public final class ChannelImpl implements Channel start = now; } - if (response == null) - { + if (response == null) { throw ActiveMQClientMessageBundle.BUNDLE.timedOutSendingPacket(connection.getBlockingCallTimeout(), packet.getType()); } - if (response.getType() == PacketImpl.EXCEPTION) - { + if (response.getType() == PacketImpl.EXCEPTION) { final ActiveMQExceptionMessage mem = (ActiveMQExceptionMessage) response; ActiveMQException e = mem.getException(); @@ -412,8 +360,7 @@ public final class ChannelImpl implements Channel throw e; } } - finally - { + finally { lock.unlock(); } @@ -426,18 +373,15 @@ public final class ChannelImpl implements Channel * @return the name of the interceptor that returned false or null if no interceptors * returned false. */ - public static String invokeInterceptors(final Packet packet, final List interceptors, final RemotingConnection connection) - { - if (interceptors != null) - { - for (final Interceptor interceptor : interceptors) - { - try - { + public static String invokeInterceptors(final Packet packet, + final List interceptors, + final RemotingConnection connection) { + if (interceptors != null) { + for (final Interceptor interceptor : interceptors) { + try { boolean callNext = interceptor.intercept(packet, connection); - if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQClientLogger.LOGGER.isDebugEnabled()) { // use a StringBuilder for speed since this may be executed a lot StringBuilder msg = new StringBuilder(); msg.append("Invocation of interceptor ").append(interceptor.getClass().getName()).append(" on "). @@ -445,13 +389,11 @@ public final class ChannelImpl implements Channel ActiveMQClientLogger.LOGGER.debug(msg.toString()); } - if (!callNext) - { + if (!callNext) { return interceptor.getClass().getName(); } } - catch (final Throwable e) - { + catch (final Throwable e) { ActiveMQClientLogger.LOGGER.errorCallingInterceptor(e, interceptor); } } @@ -460,53 +402,41 @@ public final class ChannelImpl implements Channel return null; } - public void setCommandConfirmationHandler(final CommandConfirmationHandler handler) - { - if (confWindowSize < 0) - { - final String msg = - "You can't set confirmationHandler on a connection with confirmation-window-size < 0." - + " Look at the documentation for more information."; + public void setCommandConfirmationHandler(final CommandConfirmationHandler handler) { + if (confWindowSize < 0) { + final String msg = "You can't set confirmationHandler on a connection with confirmation-window-size < 0." + " Look at the documentation for more information."; throw new IllegalStateException(msg); } commandConfirmationHandler = handler; } - public void setHandler(final ChannelHandler handler) - { + public void setHandler(final ChannelHandler handler) { this.handler = handler; } - public ChannelHandler getHandler() - { + public ChannelHandler getHandler() { return handler; } - public void close() - { - if (closed) - { + public void close() { + if (closed) { return; } - if (!connection.isDestroyed() && !connection.removeChannel(id)) - { + if (!connection.isDestroyed() && !connection.removeChannel(id)) { throw ActiveMQClientMessageBundle.BUNDLE.noChannelToClose(id); } - if (failingOver) - { + if (failingOver) { unlock(); } closed = true; } - public void transferConnection(final CoreRemotingConnection newConnection) - { + public void transferConnection(final CoreRemotingConnection newConnection) { // Needs to synchronize on the connection to make sure no packets from // the old connection get processed after transfer has occurred - synchronized (connection.getTransferLock()) - { + synchronized (connection.getTransferLock()) { connection.removeChannel(id); // And switch it @@ -521,25 +451,20 @@ public final class ChannelImpl implements Channel } } - public void replayCommands(final int otherLastConfirmedCommandID) - { - if (resendCache != null) - { - if (isTrace) - { + public void replayCommands(final int otherLastConfirmedCommandID) { + if (resendCache != null) { + if (isTrace) { ActiveMQClientLogger.LOGGER.trace("Replaying commands on channelID=" + id); } clearUpTo(otherLastConfirmedCommandID); - for (final Packet packet : resendCache) - { + for (final Packet packet : resendCache) { doWrite(packet); } } } - public void lock() - { + public void lock() { lock.lock(); failingOver = true; @@ -547,8 +472,7 @@ public final class ChannelImpl implements Channel lock.unlock(); } - public void unlock() - { + public void unlock() { lock.lock(); failingOver = false; @@ -558,16 +482,13 @@ public final class ChannelImpl implements Channel lock.unlock(); } - public CoreRemotingConnection getConnection() - { + public CoreRemotingConnection getConnection() { return connection; } // Needs to be synchronized since can be called by remoting service timer thread too for timeout flush - public synchronized void flushConfirmations() - { - if (resendCache != null && receivedBytes != 0) - { + public synchronized void flushConfirmations() { + if (resendCache != null && receivedBytes != 0) { receivedBytes = 0; final Packet confirmed = new PacketsConfirmedMessage(lastConfirmedCommandID.get()); @@ -578,16 +499,13 @@ public final class ChannelImpl implements Channel } } - public void confirm(final Packet packet) - { - if (resendCache != null && packet.isRequiresConfirmations()) - { + public void confirm(final Packet packet) { + if (resendCache != null && packet.isRequiresConfirmations()) { lastConfirmedCommandID.incrementAndGet(); receivedBytes += packet.getPacketSize(); - if (receivedBytes >= confWindowSize) - { + if (receivedBytes >= confWindowSize) { receivedBytes = 0; final Packet confirmed = new PacketsConfirmedMessage(lastConfirmedCommandID.get()); @@ -599,10 +517,8 @@ public final class ChannelImpl implements Channel } } - public void clearCommands() - { - if (resendCache != null) - { + public void clearCommands() { + if (resendCache != null) { lastConfirmedCommandID.set(-1); firstStoredCommandID = 0; @@ -611,88 +527,71 @@ public final class ChannelImpl implements Channel } } - public void handlePacket(final Packet packet) - { - if (packet.getType() == PacketImpl.PACKETS_CONFIRMED) - { - if (resendCache != null) - { + public void handlePacket(final Packet packet) { + if (packet.getType() == PacketImpl.PACKETS_CONFIRMED) { + if (resendCache != null) { final PacketsConfirmedMessage msg = (PacketsConfirmedMessage) packet; clearUpTo(msg.getCommandID()); } - if (!connection.isClient()) - { + if (!connection.isClient()) { handler.handlePacket(packet); } return; } - else - { - if (packet.isResponse()) - { + else { + if (packet.isResponse()) { confirm(packet); lock.lock(); - try - { + try { response = packet; sendCondition.signal(); } - finally - { + finally { lock.unlock(); } } - else if (handler != null) - { + else if (handler != null) { handler.handlePacket(packet); } } } - private void doWrite(final Packet packet) - { + private void doWrite(final Packet packet) { final ActiveMQBuffer buffer = packet.encode(connection); connection.getTransportConnection().write(buffer, false, false); } - private void clearUpTo(final int lastReceivedCommandID) - { + private void clearUpTo(final int lastReceivedCommandID) { final int numberToClear = 1 + lastReceivedCommandID - firstStoredCommandID; - if (numberToClear == -1) - { + if (numberToClear == -1) { throw ActiveMQClientMessageBundle.BUNDLE.invalidCommandID(lastReceivedCommandID); } int sizeToFree = 0; - for (int i = 0; i < numberToClear; i++) - { + for (int i = 0; i < numberToClear; i++) { final Packet packet = resendCache.poll(); - if (packet == null) - { - if (lastReceivedCommandID > 0) - { + if (packet == null) { + if (lastReceivedCommandID > 0) { ActiveMQClientLogger.LOGGER.cannotFindPacketToClear(lastReceivedCommandID, firstStoredCommandID); } firstStoredCommandID = lastReceivedCommandID + 1; return; } - if (packet.getType() != PacketImpl.PACKETS_CONFIRMED) - { + if (packet.getType() != PacketImpl.PACKETS_CONFIRMED) { sizeToFree += packet.getPacketSize(); } - if (commandConfirmationHandler != null) - { + if (commandConfirmationHandler != null) { commandConfirmationHandler.commandConfirmed(packet); } } @@ -701,8 +600,7 @@ public final class ChannelImpl implements Channel } @Override - public String toString() - { + public String toString() { return "Channel[id=" + CHANNEL_ID.idToString(id) + ", handler=" + handler + "]"; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/PacketDecoder.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/PacketDecoder.java index f051de291c..804a26a925 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/PacketDecoder.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/PacketDecoder.java @@ -145,338 +145,271 @@ import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionXAS import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SubscribeClusterTopologyUpdatesMessage; import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SubscribeClusterTopologyUpdatesMessageV2; -public abstract class PacketDecoder implements Serializable -{ +public abstract class PacketDecoder implements Serializable { + public abstract Packet decode(final ActiveMQBuffer in); - public Packet decode(byte packetType) - { + public Packet decode(byte packetType) { Packet packet; - switch (packetType) - { - case PING: - { + switch (packetType) { + case PING: { packet = new Ping(); break; } - case DISCONNECT: - { + case DISCONNECT: { packet = new DisconnectMessage(); break; } - case DISCONNECT_V2: - { + case DISCONNECT_V2: { packet = new DisconnectMessage_V2(); break; } - case DISCONNECT_CONSUMER: - { + case DISCONNECT_CONSUMER: { packet = new DisconnectConsumerMessage(); break; } - case EXCEPTION: - { + case EXCEPTION: { packet = new ActiveMQExceptionMessage(); break; } - case PACKETS_CONFIRMED: - { + case PACKETS_CONFIRMED: { packet = new PacketsConfirmedMessage(); break; } - case CREATESESSION: - { + case CREATESESSION: { packet = new CreateSessionMessage(); break; } - case CHECK_FOR_FAILOVER: - { + case CHECK_FOR_FAILOVER: { packet = new CheckFailoverMessage(); break; } - case CREATESESSION_RESP: - { + case CREATESESSION_RESP: { packet = new CreateSessionResponseMessage(); break; } - case REATTACH_SESSION: - { + case REATTACH_SESSION: { packet = new ReattachSessionMessage(); break; } - case REATTACH_SESSION_RESP: - { + case REATTACH_SESSION_RESP: { packet = new ReattachSessionResponseMessage(); break; } - case SESS_CLOSE: - { + case SESS_CLOSE: { packet = new SessionCloseMessage(); break; } - case SESS_CREATECONSUMER: - { + case SESS_CREATECONSUMER: { packet = new SessionCreateConsumerMessage(); break; } - case SESS_ACKNOWLEDGE: - { + case SESS_ACKNOWLEDGE: { packet = new SessionAcknowledgeMessage(); break; } - case SESS_EXPIRED: - { + case SESS_EXPIRED: { packet = new SessionExpireMessage(); break; } - case SESS_COMMIT: - { + case SESS_COMMIT: { packet = new SessionCommitMessage(); break; } - case SESS_ROLLBACK: - { + case SESS_ROLLBACK: { packet = new RollbackMessage(); break; } - case SESS_QUEUEQUERY: - { + case SESS_QUEUEQUERY: { packet = new SessionQueueQueryMessage(); break; } - case SESS_QUEUEQUERY_RESP: - { + case SESS_QUEUEQUERY_RESP: { packet = new SessionQueueQueryResponseMessage(); break; } - case SESS_QUEUEQUERY_RESP_V2: - { + case SESS_QUEUEQUERY_RESP_V2: { packet = new SessionQueueQueryResponseMessage_V2(); break; } - case CREATE_QUEUE: - { + case CREATE_QUEUE: { packet = new CreateQueueMessage(); break; } - case CREATE_SHARED_QUEUE: - { + case CREATE_SHARED_QUEUE: { packet = new CreateSharedQueueMessage(); break; } - case DELETE_QUEUE: - { + case DELETE_QUEUE: { packet = new SessionDeleteQueueMessage(); break; } - case SESS_BINDINGQUERY: - { + case SESS_BINDINGQUERY: { packet = new SessionBindingQueryMessage(); break; } - case SESS_BINDINGQUERY_RESP: - { + case SESS_BINDINGQUERY_RESP: { packet = new SessionBindingQueryResponseMessage(); break; } - case SESS_BINDINGQUERY_RESP_V2: - { + case SESS_BINDINGQUERY_RESP_V2: { packet = new SessionBindingQueryResponseMessage_V2(); break; } - case SESS_XA_START: - { + case SESS_XA_START: { packet = new SessionXAStartMessage(); break; } - case SESS_XA_FAILED: - { + case SESS_XA_FAILED: { packet = new SessionXAAfterFailedMessage(); break; } - case SESS_XA_END: - { + case SESS_XA_END: { packet = new SessionXAEndMessage(); break; } - case SESS_XA_COMMIT: - { + case SESS_XA_COMMIT: { packet = new SessionXACommitMessage(); break; } - case SESS_XA_PREPARE: - { + case SESS_XA_PREPARE: { packet = new SessionXAPrepareMessage(); break; } - case SESS_XA_RESP: - { + case SESS_XA_RESP: { packet = new SessionXAResponseMessage(); break; } - case SESS_XA_ROLLBACK: - { + case SESS_XA_ROLLBACK: { packet = new SessionXARollbackMessage(); break; } - case SESS_XA_JOIN: - { + case SESS_XA_JOIN: { packet = new SessionXAJoinMessage(); break; } - case SESS_XA_SUSPEND: - { + case SESS_XA_SUSPEND: { packet = new PacketImpl(PacketImpl.SESS_XA_SUSPEND); break; } - case SESS_XA_RESUME: - { + case SESS_XA_RESUME: { packet = new SessionXAResumeMessage(); break; } - case SESS_XA_FORGET: - { + case SESS_XA_FORGET: { packet = new SessionXAForgetMessage(); break; } - case SESS_XA_INDOUBT_XIDS: - { + case SESS_XA_INDOUBT_XIDS: { packet = new PacketImpl(PacketImpl.SESS_XA_INDOUBT_XIDS); break; } - case SESS_XA_INDOUBT_XIDS_RESP: - { + case SESS_XA_INDOUBT_XIDS_RESP: { packet = new SessionXAGetInDoubtXidsResponseMessage(); break; } - case SESS_XA_SET_TIMEOUT: - { + case SESS_XA_SET_TIMEOUT: { packet = new SessionXASetTimeoutMessage(); break; } - case SESS_XA_SET_TIMEOUT_RESP: - { + case SESS_XA_SET_TIMEOUT_RESP: { packet = new SessionXASetTimeoutResponseMessage(); break; } - case SESS_XA_GET_TIMEOUT: - { + case SESS_XA_GET_TIMEOUT: { packet = new PacketImpl(PacketImpl.SESS_XA_GET_TIMEOUT); break; } - case SESS_XA_GET_TIMEOUT_RESP: - { + case SESS_XA_GET_TIMEOUT_RESP: { packet = new SessionXAGetTimeoutResponseMessage(); break; } - case SESS_START: - { + case SESS_START: { packet = new PacketImpl(PacketImpl.SESS_START); break; } - case SESS_STOP: - { + case SESS_STOP: { packet = new PacketImpl(PacketImpl.SESS_STOP); break; } - case SESS_FLOWTOKEN: - { + case SESS_FLOWTOKEN: { packet = new SessionConsumerFlowCreditMessage(); break; } - case SESS_CONSUMER_CLOSE: - { + case SESS_CONSUMER_CLOSE: { packet = new SessionConsumerCloseMessage(); break; } - case SESS_INDIVIDUAL_ACKNOWLEDGE: - { + case SESS_INDIVIDUAL_ACKNOWLEDGE: { packet = new SessionIndividualAcknowledgeMessage(); break; } - case NULL_RESPONSE: - { + case NULL_RESPONSE: { packet = new NullResponseMessage(); break; } - case SESS_RECEIVE_CONTINUATION: - { + case SESS_RECEIVE_CONTINUATION: { packet = new SessionReceiveContinuationMessage(); break; } - case SESS_SEND_CONTINUATION: - { + case SESS_SEND_CONTINUATION: { packet = new SessionSendContinuationMessage(); break; } - case SESS_PRODUCER_REQUEST_CREDITS: - { + case SESS_PRODUCER_REQUEST_CREDITS: { packet = new SessionRequestProducerCreditsMessage(); break; } - case SESS_PRODUCER_CREDITS: - { + case SESS_PRODUCER_CREDITS: { packet = new SessionProducerCreditsMessage(); break; } - case SESS_PRODUCER_FAIL_CREDITS: - { + case SESS_PRODUCER_FAIL_CREDITS: { packet = new SessionProducerCreditsFailMessage(); break; } - case SESS_FORCE_CONSUMER_DELIVERY: - { + case SESS_FORCE_CONSUMER_DELIVERY: { packet = new SessionForceConsumerDelivery(); break; } - case CLUSTER_TOPOLOGY: - { + case CLUSTER_TOPOLOGY: { packet = new ClusterTopologyChangeMessage(); break; } - case CLUSTER_TOPOLOGY_V2: - { + case CLUSTER_TOPOLOGY_V2: { packet = new ClusterTopologyChangeMessage_V2(); break; } - case CLUSTER_TOPOLOGY_V3: - { + case CLUSTER_TOPOLOGY_V3: { packet = new ClusterTopologyChangeMessage_V3(); break; } - case SUBSCRIBE_TOPOLOGY: - { + case SUBSCRIBE_TOPOLOGY: { packet = new SubscribeClusterTopologyUpdatesMessage(); break; } - case SUBSCRIBE_TOPOLOGY_V2: - { + case SUBSCRIBE_TOPOLOGY_V2: { packet = new SubscribeClusterTopologyUpdatesMessageV2(); break; } - case SESS_ADD_METADATA: - { + case SESS_ADD_METADATA: { packet = new SessionAddMetaDataMessage(); break; } - case SESS_ADD_METADATA2: - { + case SESS_ADD_METADATA2: { packet = new SessionAddMetaDataMessageV2(); break; } - case SESS_UNIQUE_ADD_METADATA: - { + case SESS_UNIQUE_ADD_METADATA: { packet = new SessionUniqueAddMetaDataMessage(); break; } - case PacketImpl.CHECK_FOR_FAILOVER_REPLY: - { + case PacketImpl.CHECK_FOR_FAILOVER_REPLY: { packet = new CheckFailoverReplyMessage(); break; } - default: - { + default: { throw ActiveMQClientMessageBundle.BUNDLE.invalidType(packetType); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/PacketImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/PacketImpl.java index d71c60ad1f..06e259bb6a 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/PacketImpl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/PacketImpl.java @@ -21,14 +21,13 @@ import org.apache.activemq.artemis.core.protocol.core.Packet; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; import org.apache.activemq.artemis.utils.DataConstants; -public class PacketImpl implements Packet -{ +public class PacketImpl implements Packet { // Constants ------------------------------------------------------------------------- // The minimal size for all the packets, Common data for all the packets (look at // PacketImpl.encode) public static final int PACKET_HEADERS_SIZE = DataConstants.SIZE_INT + DataConstants.SIZE_BYTE + - DataConstants.SIZE_LONG; + DataConstants.SIZE_LONG; private static final int INITIAL_PACKET_SIZE = 1500; @@ -194,8 +193,6 @@ public class PacketImpl implements Packet public static final byte SESS_UNIQUE_ADD_METADATA = 106; - - // HA public static final byte CLUSTER_TOPOLOGY = 110; @@ -248,30 +245,25 @@ public class PacketImpl implements Packet // Static -------------------------------------------------------- - public PacketImpl(final byte type) - { + public PacketImpl(final byte type) { this.type = type; } // Public -------------------------------------------------------- - public byte getType() - { + public byte getType() { return type; } - public long getChannelID() - { + public long getChannelID() { return channelID; } - public void setChannelID(final long channelID) - { + public void setChannelID(final long channelID) { this.channelID = channelID; } - public ActiveMQBuffer encode(final RemotingConnection connection) - { + public ActiveMQBuffer encode(final RemotingConnection connection) { ActiveMQBuffer buffer = connection.createTransportBuffer(PacketImpl.INITIAL_PACKET_SIZE); // The standard header fields @@ -292,8 +284,7 @@ public class PacketImpl implements Packet return buffer; } - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { channelID = buffer.readLong(); decodeRest(buffer); @@ -301,78 +292,64 @@ public class PacketImpl implements Packet size = buffer.readerIndex(); } - public int getPacketSize() - { - if (size == -1) - { + public int getPacketSize() { + if (size == -1) { throw new IllegalStateException("Packet hasn't been encoded/decoded yet"); } return size; } - public boolean isResponse() - { + public boolean isResponse() { return false; } - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { } - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { } - public boolean isRequiresConfirmations() - { + public boolean isRequiresConfirmations() { return true; } @Override - public String toString() - { + public String toString() { return getParentString() + "]"; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + (int)(channelID ^ (channelID >>> 32)); + result = prime * result + (int) (channelID ^ (channelID >>> 32)); result = prime * result + size; result = prime * result + type; return result; } @Override - public boolean equals(Object obj) - { - if (this == obj) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if (!(obj instanceof PacketImpl)) - { + if (!(obj instanceof PacketImpl)) { return false; } - PacketImpl other = (PacketImpl)obj; + PacketImpl other = (PacketImpl) obj; return (channelID == other.channelID) && (size == other.size) && (type != other.type); } - protected String getParentString() - { - return "PACKET(" + this.getClass().getSimpleName() + ")[type=" + type + ", channelID=" + channelID + ", packetObject=" + this.getClass().getSimpleName(); + protected String getParentString() { + return "PACKET(" + this.getClass().getSimpleName() + ")[type=" + type + ", channelID=" + channelID + ", packetObject=" + this.getClass().getSimpleName(); } - private int stringEncodeSize(final String str) - { + private int stringEncodeSize(final String str) { return DataConstants.SIZE_INT + str.length() * 2; } - protected int nullableStringEncodeSize(final String str) - { + protected int nullableStringEncodeSize(final String str) { return DataConstants.SIZE_BOOLEAN + (str != null ? stringEncodeSize(str) : 0); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/RemotingConnectionImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/RemotingConnectionImpl.java index 4f192d3da1..68687136b5 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/RemotingConnectionImpl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/RemotingConnectionImpl.java @@ -39,8 +39,7 @@ import org.apache.activemq.artemis.spi.core.protocol.AbstractRemotingConnection; import org.apache.activemq.artemis.spi.core.remoting.Connection; import org.apache.activemq.artemis.utils.SimpleIDGenerator; -public class RemotingConnectionImpl extends AbstractRemotingConnection implements CoreRemotingConnection -{ +public class RemotingConnectionImpl extends AbstractRemotingConnection implements CoreRemotingConnection { // Constants // ------------------------------------------------------------------------------------ @@ -92,8 +91,7 @@ public class RemotingConnectionImpl extends AbstractRemotingConnection implement final long blockingCallTimeout, final long blockingCallFailoverTimeout, final List incomingInterceptors, - final List outgoingInterceptors) - { + final List outgoingInterceptors) { this(packetDecoder, transportConnection, blockingCallTimeout, blockingCallFailoverTimeout, incomingInterceptors, outgoingInterceptors, true, null, null); } @@ -105,9 +103,7 @@ public class RemotingConnectionImpl extends AbstractRemotingConnection implement final List incomingInterceptors, final List outgoingInterceptors, final Executor executor, - final SimpleString nodeID) - - { + final SimpleString nodeID) { this(packetDecoder, transportConnection, -1, -1, incomingInterceptors, outgoingInterceptors, false, executor, nodeID); } @@ -119,9 +115,7 @@ public class RemotingConnectionImpl extends AbstractRemotingConnection implement final List outgoingInterceptors, final boolean client, final Executor executor, - final SimpleString nodeID) - - { + final SimpleString nodeID) { super(transportConnection, executor); this.packetDecoder = packetDecoder; @@ -141,13 +135,11 @@ public class RemotingConnectionImpl extends AbstractRemotingConnection implement transportConnection.setProtocolConnection(this); } - // RemotingConnection implementation // ------------------------------------------------------------ @Override - public String toString() - { + public String toString() { return "RemotingConnectionImpl [clientID=" + clientID + ", nodeID=" + nodeID + @@ -159,25 +151,21 @@ public class RemotingConnectionImpl extends AbstractRemotingConnection implement /** * @return the clientVersion */ - public int getClientVersion() - { + public int getClientVersion() { return clientVersion; } /** * @param clientVersion the clientVersion to set */ - public void setClientVersion(int clientVersion) - { + public void setClientVersion(int clientVersion) { this.clientVersion = clientVersion; } - public synchronized Channel getChannel(final long channelID, final int confWindowSize) - { + public synchronized Channel getChannel(final long channelID, final int confWindowSize) { Channel channel = channels.get(channelID); - if (channel == null) - { + if (channel == null) { channel = new ChannelImpl(this, channelID, confWindowSize, outgoingInterceptors); channels.put(channelID, channel); @@ -186,22 +174,17 @@ public class RemotingConnectionImpl extends AbstractRemotingConnection implement return channel; } - public synchronized boolean removeChannel(final long channelID) - { + public synchronized boolean removeChannel(final long channelID) { return channels.remove(channelID) != null; } - public synchronized void putChannel(final long channelID, final Channel channel) - { + public synchronized void putChannel(final long channelID, final Channel channel) { channels.put(channelID, channel); } - public void fail(final ActiveMQException me, String scaleDownTargetNodeID) - { - synchronized (failLock) - { - if (destroyed) - { + public void fail(final ActiveMQException me, String scaleDownTargetNodeID) { + synchronized (failLock) { + if (destroyed) { return; } @@ -210,13 +193,10 @@ public class RemotingConnectionImpl extends AbstractRemotingConnection implement ActiveMQClientLogger.LOGGER.connectionFailureDetected(me.getMessage(), me.getType()); - - try - { + try { transportConnection.forceClose(); } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQClientLogger.LOGGER.warn(e.getMessage(), e); } @@ -227,18 +207,14 @@ public class RemotingConnectionImpl extends AbstractRemotingConnection implement internalClose(); - for (Channel channel : channels.values()) - { + for (Channel channel : channels.values()) { channel.returnBlocking(me); } } - public void destroy() - { - synchronized (failLock) - { - if (destroyed) - { + public void destroy() { + synchronized (failLock) { + if (destroyed) { return; } @@ -250,13 +226,11 @@ public class RemotingConnectionImpl extends AbstractRemotingConnection implement callClosingListeners(); } - public void disconnect(final boolean criticalError) - { + public void disconnect(final boolean criticalError) { disconnect(null, criticalError); } - public void disconnect(String scaleDownNodeID, final boolean criticalError) - { + public void disconnect(String scaleDownNodeID, final boolean criticalError) { Channel channel0 = getChannel(ChannelImpl.CHANNEL_ID.PING.id, -1); // And we remove all channels from the connection, this ensures no more packets will be processed after this @@ -265,12 +239,10 @@ public class RemotingConnectionImpl extends AbstractRemotingConnection implement Set allChannels = new HashSet(channels.values()); - if (!criticalError) - { + if (!criticalError) { removeAllChannels(); } - else - { + else { // We can't hold a lock if a critical error is happening... // as other threads will be holding the lock while hanging on IO channels.clear(); @@ -278,100 +250,80 @@ public class RemotingConnectionImpl extends AbstractRemotingConnection implement // Now we are 100% sure that no more packets will be processed we can flush then send the disconnect - if (!criticalError) - { - for (Channel channel : allChannels) - { + if (!criticalError) { + for (Channel channel : allChannels) { channel.flushConfirmations(); } } Packet disconnect; - if (channel0.supports(PacketImpl.DISCONNECT_V2)) - { + if (channel0.supports(PacketImpl.DISCONNECT_V2)) { disconnect = new DisconnectMessage_V2(nodeID, scaleDownNodeID); } - else - { + else { disconnect = new DisconnectMessage(nodeID); } channel0.sendAndFlush(disconnect); } - public long generateChannelID() - { + public long generateChannelID() { return idGenerator.generateID(); } - public synchronized void syncIDGeneratorSequence(final long id) - { - if (!idGeneratorSynced) - { + public synchronized void syncIDGeneratorSequence(final long id) { + if (!idGeneratorSynced) { idGenerator = new SimpleIDGenerator(id); idGeneratorSynced = true; } } - public long getIDGeneratorSequence() - { + public long getIDGeneratorSequence() { return idGenerator.getCurrentID(); } - public Object getTransferLock() - { + public Object getTransferLock() { return transferLock; } - public boolean isClient() - { + public boolean isClient() { return client; } - public boolean isDestroyed() - { + public boolean isDestroyed() { return destroyed; } - public long getBlockingCallTimeout() - { + public long getBlockingCallTimeout() { return blockingCallTimeout; } @Override - public long getBlockingCallFailoverTimeout() - { + public long getBlockingCallFailoverTimeout() { return blockingCallFailoverTimeout; } //We flush any confirmations on the connection - this prevents idle bridges for example //sitting there with many unacked messages - public void flush() - { - synchronized (transferLock) - { - for (Channel channel : channels.values()) - { + public void flush() { + synchronized (transferLock) { + for (Channel channel : channels.values()) { channel.flushConfirmations(); } } } - public ActiveMQPrincipal getDefaultActiveMQPrincipal() - { + public ActiveMQPrincipal getDefaultActiveMQPrincipal() { return getTransportConnection().getDefaultActiveMQPrincipal(); } // Buffer Handler implementation // ---------------------------------------------------- - public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) - { - try - { + public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) { + try { final Packet packet = packetDecoder.decode(buffer); - if (isTrace) - { + if (isTrace) { ActiveMQClientLogger.LOGGER.trace("handling packet " + packet); } @@ -380,58 +332,47 @@ public class RemotingConnectionImpl extends AbstractRemotingConnection implement super.bufferReceived(connectionID, buffer); } - catch (Exception e) - { + catch (Exception e) { ActiveMQClientLogger.LOGGER.errorDecodingPacket(e); } } - private void doBufferReceived(final Packet packet) - { - if (ChannelImpl.invokeInterceptors(packet, incomingInterceptors, this) != null) - { + private void doBufferReceived(final Packet packet) { + if (ChannelImpl.invokeInterceptors(packet, incomingInterceptors, this) != null) { return; } - synchronized (transferLock) - { + synchronized (transferLock) { final Channel channel = channels.get(packet.getChannelID()); - if (channel != null) - { + if (channel != null) { channel.handlePacket(packet); } } } - protected void removeAllChannels() - { + protected void removeAllChannels() { // We get the transfer lock first - this ensures no packets are being processed AND // it's guaranteed no more packets will be processed once this method is complete - synchronized (transferLock) - { + synchronized (transferLock) { channels.clear(); } } - private void internalClose() - { + private void internalClose() { // We close the underlying transport connection getTransportConnection().close(); - for (Channel channel : channels.values()) - { + for (Channel channel : channels.values()) { channel.close(); } } - public void setClientID(String cID) - { + public void setClientID(String cID) { clientID = cID; } - public String getClientID() - { + public String getClientID() { return clientID; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ActiveMQExceptionMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ActiveMQExceptionMessage.java index ab2a6ed2ae..f99b46530e 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ActiveMQExceptionMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ActiveMQExceptionMessage.java @@ -21,8 +21,7 @@ import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.api.core.ActiveMQExceptionType; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class ActiveMQExceptionMessage extends PacketImpl -{ +public class ActiveMQExceptionMessage extends PacketImpl { private ActiveMQException exception; @@ -30,41 +29,35 @@ public class ActiveMQExceptionMessage extends PacketImpl // Constructors -------------------------------------------------- - public ActiveMQExceptionMessage(final ActiveMQException exception) - { + public ActiveMQExceptionMessage(final ActiveMQException exception) { super(EXCEPTION); this.exception = exception; } - public ActiveMQExceptionMessage() - { + public ActiveMQExceptionMessage() { super(EXCEPTION); } // Public -------------------------------------------------------- @Override - public boolean isResponse() - { + public boolean isResponse() { return true; } - public ActiveMQException getException() - { + public ActiveMQException getException() { return exception; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeInt(exception.getType().getCode()); buffer.writeNullableString(exception.getMessage()); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { int code = buffer.readInt(); String msg = buffer.readNullableString(); @@ -72,14 +65,12 @@ public class ActiveMQExceptionMessage extends PacketImpl } @Override - public String toString() - { + public String toString() { return getParentString() + ", exception= " + exception + "]"; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((exception == null) ? 0 : exception.hashCode()); @@ -87,30 +78,23 @@ public class ActiveMQExceptionMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { - if (this == obj) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if (!super.equals(obj)) - { + if (!super.equals(obj)) { return false; } - if (!(obj instanceof ActiveMQExceptionMessage)) - { + if (!(obj instanceof ActiveMQExceptionMessage)) { return false; } - ActiveMQExceptionMessage other = (ActiveMQExceptionMessage)obj; - if (exception == null) - { - if (other.exception != null) - { + ActiveMQExceptionMessage other = (ActiveMQExceptionMessage) obj; + if (exception == null) { + if (other.exception != null) { return false; } } - else if (!exception.equals(other.exception)) - { + else if (!exception.equals(other.exception)) { return false; } return true; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CheckFailoverMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CheckFailoverMessage.java index fcc4b5ba4e..c618e0b0a3 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CheckFailoverMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CheckFailoverMessage.java @@ -19,35 +19,30 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class CheckFailoverMessage extends PacketImpl -{ +public class CheckFailoverMessage extends PacketImpl { + private String nodeID; - public CheckFailoverMessage(final String nodeID) - { + public CheckFailoverMessage(final String nodeID) { super(CHECK_FOR_FAILOVER); this.nodeID = nodeID; } - public CheckFailoverMessage() - { + public CheckFailoverMessage() { super(CHECK_FOR_FAILOVER); } @Override - public void encodeRest(ActiveMQBuffer buffer) - { + public void encodeRest(ActiveMQBuffer buffer) { buffer.writeNullableString(nodeID); } @Override - public void decodeRest(ActiveMQBuffer buffer) - { + public void decodeRest(ActiveMQBuffer buffer) { nodeID = buffer.readNullableString(); } - public String getNodeID() - { + public String getNodeID() { return nodeID; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CheckFailoverReplyMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CheckFailoverReplyMessage.java index be29fdba65..e09f28259d 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CheckFailoverReplyMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CheckFailoverReplyMessage.java @@ -16,45 +16,38 @@ */ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; - import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class CheckFailoverReplyMessage extends PacketImpl -{ +public class CheckFailoverReplyMessage extends PacketImpl { + private boolean okToFailover; - public CheckFailoverReplyMessage(boolean okToFailover) - { + public CheckFailoverReplyMessage(boolean okToFailover) { super(CHECK_FOR_FAILOVER_REPLY); this.okToFailover = okToFailover; } - public CheckFailoverReplyMessage() - { + public CheckFailoverReplyMessage() { super(CHECK_FOR_FAILOVER_REPLY); } @Override - public boolean isResponse() - { + public boolean isResponse() { return true; } @Override - public void encodeRest(ActiveMQBuffer buffer) - { + public void encodeRest(ActiveMQBuffer buffer) { buffer.writeBoolean(okToFailover); } @Override - public void decodeRest(ActiveMQBuffer buffer) - { + public void decodeRest(ActiveMQBuffer buffer) { okToFailover = buffer.readBoolean(); } - public boolean isOkToFailover() - { + public boolean isOkToFailover() { return okToFailover; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ClusterTopologyChangeMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ClusterTopologyChangeMessage.java index 13ae08f7f2..f0195764b5 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ClusterTopologyChangeMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ClusterTopologyChangeMessage.java @@ -21,8 +21,8 @@ import org.apache.activemq.artemis.api.core.Pair; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class ClusterTopologyChangeMessage extends PacketImpl -{ +public class ClusterTopologyChangeMessage extends PacketImpl { + protected boolean exit; protected String nodeID; @@ -35,8 +35,9 @@ public class ClusterTopologyChangeMessage extends PacketImpl // Constructors -------------------------------------------------- - public ClusterTopologyChangeMessage(final String nodeID, final Pair pair, final boolean last) - { + public ClusterTopologyChangeMessage(final String nodeID, + final Pair pair, + final boolean last) { super(CLUSTER_TOPOLOGY); this.nodeID = nodeID; @@ -48,8 +49,7 @@ public class ClusterTopologyChangeMessage extends PacketImpl this.exit = false; } - public ClusterTopologyChangeMessage(final String nodeID) - { + public ClusterTopologyChangeMessage(final String nodeID) { super(CLUSTER_TOPOLOGY); this.exit = true; @@ -57,8 +57,7 @@ public class ClusterTopologyChangeMessage extends PacketImpl this.nodeID = nodeID; } - public ClusterTopologyChangeMessage() - { + public ClusterTopologyChangeMessage() { super(CLUSTER_TOPOLOGY); } @@ -67,54 +66,43 @@ public class ClusterTopologyChangeMessage extends PacketImpl /** * @param clusterTopologyV2 */ - public ClusterTopologyChangeMessage(byte clusterTopologyV2) - { + public ClusterTopologyChangeMessage(byte clusterTopologyV2) { super(clusterTopologyV2); } - public String getNodeID() - { + public String getNodeID() { return nodeID; } - public Pair getPair() - { + public Pair getPair() { return pair; } - public boolean isLast() - { + public boolean isLast() { return last; } - public boolean isExit() - { + public boolean isExit() { return exit; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeBoolean(exit); buffer.writeString(nodeID); - if (!exit) - { - if (pair.getA() != null) - { + if (!exit) { + if (pair.getA() != null) { buffer.writeBoolean(true); pair.getA().encode(buffer); } - else - { + else { buffer.writeBoolean(false); } - if (pair.getB() != null) - { + if (pair.getB() != null) { buffer.writeBoolean(true); pair.getB().encode(buffer); } - else - { + else { buffer.writeBoolean(false); } buffer.writeBoolean(last); @@ -122,32 +110,26 @@ public class ClusterTopologyChangeMessage extends PacketImpl } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { exit = buffer.readBoolean(); nodeID = buffer.readString(); - if (!exit) - { + if (!exit) { boolean hasLive = buffer.readBoolean(); TransportConfiguration a; - if (hasLive) - { + if (hasLive) { a = new TransportConfiguration(); a.decode(buffer); } - else - { + else { a = null; } boolean hasBackup = buffer.readBoolean(); TransportConfiguration b; - if (hasBackup) - { + if (hasBackup) { b = new TransportConfiguration(); b.decode(buffer); } - else - { + else { b = null; } pair = new Pair(a, b); @@ -156,8 +138,7 @@ public class ClusterTopologyChangeMessage extends PacketImpl } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (exit ? 1231 : 1237); @@ -168,49 +149,37 @@ public class ClusterTopologyChangeMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { - if (this == obj) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if (!super.equals(obj)) - { + if (!super.equals(obj)) { return false; } - if (!(obj instanceof ClusterTopologyChangeMessage)) - { + if (!(obj instanceof ClusterTopologyChangeMessage)) { return false; } ClusterTopologyChangeMessage other = (ClusterTopologyChangeMessage) obj; - if (exit != other.exit) - { + if (exit != other.exit) { return false; } - if (last != other.last) - { + if (last != other.last) { return false; } - if (nodeID == null) - { - if (other.nodeID != null) - { + if (nodeID == null) { + if (other.nodeID != null) { return false; } } - else if (!nodeID.equals(other.nodeID)) - { + else if (!nodeID.equals(other.nodeID)) { return false; } - if (pair == null) - { - if (other.pair != null) - { + if (pair == null) { + if (other.pair != null) { return false; } } - else if (!pair.equals(other.pair)) - { + else if (!pair.equals(other.pair)) { return false; } return true; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ClusterTopologyChangeMessage_V2.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ClusterTopologyChangeMessage_V2.java index ca78ec069e..76860e1f56 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ClusterTopologyChangeMessage_V2.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ClusterTopologyChangeMessage_V2.java @@ -23,14 +23,16 @@ import org.apache.activemq.artemis.api.core.TransportConfiguration; /** * Clebert Suconic */ -public class ClusterTopologyChangeMessage_V2 extends ClusterTopologyChangeMessage -{ +public class ClusterTopologyChangeMessage_V2 extends ClusterTopologyChangeMessage { + protected long uniqueEventID; protected String backupGroupName; - public ClusterTopologyChangeMessage_V2(final long uniqueEventID, final String nodeID, final String backupGroupName, - final Pair pair, final boolean last) - { + public ClusterTopologyChangeMessage_V2(final long uniqueEventID, + final String nodeID, + final String backupGroupName, + final Pair pair, + final boolean last) { super(CLUSTER_TOPOLOGY_V2); this.nodeID = nodeID; @@ -46,8 +48,7 @@ public class ClusterTopologyChangeMessage_V2 extends ClusterTopologyChangeMessag this.backupGroupName = backupGroupName; } - public ClusterTopologyChangeMessage_V2(final long uniqueEventID, final String nodeID) - { + public ClusterTopologyChangeMessage_V2(final long uniqueEventID, final String nodeID) { super(CLUSTER_TOPOLOGY_V2); this.exit = true; @@ -57,53 +58,43 @@ public class ClusterTopologyChangeMessage_V2 extends ClusterTopologyChangeMessag this.uniqueEventID = uniqueEventID; } - public ClusterTopologyChangeMessage_V2() - { + public ClusterTopologyChangeMessage_V2() { super(CLUSTER_TOPOLOGY_V2); } - public ClusterTopologyChangeMessage_V2(byte clusterTopologyV3) - { + public ClusterTopologyChangeMessage_V2(byte clusterTopologyV3) { super(clusterTopologyV3); } /** * @return the uniqueEventID */ - public long getUniqueEventID() - { + public long getUniqueEventID() { return uniqueEventID; } - public String getBackupGroupName() - { + public String getBackupGroupName() { return backupGroupName; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeBoolean(exit); buffer.writeString(nodeID); buffer.writeLong(uniqueEventID); - if (!exit) - { - if (pair.getA() != null) - { + if (!exit) { + if (pair.getA() != null) { buffer.writeBoolean(true); pair.getA().encode(buffer); } - else - { + else { buffer.writeBoolean(false); } - if (pair.getB() != null) - { + if (pair.getB() != null) { buffer.writeBoolean(true); pair.getB().encode(buffer); } - else - { + else { buffer.writeBoolean(false); } buffer.writeBoolean(last); @@ -112,47 +103,39 @@ public class ClusterTopologyChangeMessage_V2 extends ClusterTopologyChangeMessag } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { exit = buffer.readBoolean(); nodeID = buffer.readString(); uniqueEventID = buffer.readLong(); - if (!exit) - { + if (!exit) { boolean hasLive = buffer.readBoolean(); TransportConfiguration a; - if (hasLive) - { + if (hasLive) { a = new TransportConfiguration(); a.decode(buffer); } - else - { + else { a = null; } boolean hasBackup = buffer.readBoolean(); TransportConfiguration b; - if (hasBackup) - { + if (hasBackup) { b = new TransportConfiguration(); b.decode(buffer); } - else - { + else { b = null; } pair = new Pair(a, b); last = buffer.readBoolean(); } - if (buffer.readableBytes() > 0) - { + if (buffer.readableBytes() > 0) { backupGroupName = buffer.readNullableString(); } } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((backupGroupName == null) ? 0 : backupGroupName.hashCode()); @@ -161,34 +144,26 @@ public class ClusterTopologyChangeMessage_V2 extends ClusterTopologyChangeMessag } @Override - public boolean equals(Object obj) - { - if (this == obj) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if (!super.equals(obj)) - { + if (!super.equals(obj)) { return false; } - if (!(obj instanceof ClusterTopologyChangeMessage_V2)) - { + if (!(obj instanceof ClusterTopologyChangeMessage_V2)) { return false; } ClusterTopologyChangeMessage_V2 other = (ClusterTopologyChangeMessage_V2) obj; - if (uniqueEventID != other.uniqueEventID) - { + if (uniqueEventID != other.uniqueEventID) { return false; } - if (backupGroupName == null) - { - if (other.backupGroupName != null) - { + if (backupGroupName == null) { + if (other.backupGroupName != null) { return false; } } - else if (!backupGroupName.equals(other.backupGroupName)) - { + else if (!backupGroupName.equals(other.backupGroupName)) { return false; } return true; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ClusterTopologyChangeMessage_V3.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ClusterTopologyChangeMessage_V3.java index 06143440b0..3942708bae 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ClusterTopologyChangeMessage_V3.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ClusterTopologyChangeMessage_V3.java @@ -20,13 +20,16 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.Pair; import org.apache.activemq.artemis.api.core.TransportConfiguration; -public class ClusterTopologyChangeMessage_V3 extends ClusterTopologyChangeMessage_V2 -{ +public class ClusterTopologyChangeMessage_V3 extends ClusterTopologyChangeMessage_V2 { + private String scaleDownGroupName; - public ClusterTopologyChangeMessage_V3(final long uniqueEventID, final String nodeID, final String backupGroupName, final String scaleDownGroupName, - final Pair pair, final boolean last) - { + public ClusterTopologyChangeMessage_V3(final long uniqueEventID, + final String nodeID, + final String backupGroupName, + final String scaleDownGroupName, + final Pair pair, + final boolean last) { super(CLUSTER_TOPOLOGY_V3); this.nodeID = nodeID; @@ -44,33 +47,28 @@ public class ClusterTopologyChangeMessage_V3 extends ClusterTopologyChangeMessag this.scaleDownGroupName = scaleDownGroupName; } - public ClusterTopologyChangeMessage_V3() - { + public ClusterTopologyChangeMessage_V3() { super(CLUSTER_TOPOLOGY_V3); } - public String getScaleDownGroupName() - { + public String getScaleDownGroupName() { return scaleDownGroupName; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { super.encodeRest(buffer); buffer.writeNullableString(scaleDownGroupName); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { super.decodeRest(buffer); scaleDownGroupName = buffer.readNullableString(); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((scaleDownGroupName == null) ? 0 : scaleDownGroupName.hashCode()); @@ -78,30 +76,23 @@ public class ClusterTopologyChangeMessage_V3 extends ClusterTopologyChangeMessag } @Override - public boolean equals(Object obj) - { - if (this == obj) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if (!super.equals(obj)) - { + if (!super.equals(obj)) { return false; } - if (!(obj instanceof ClusterTopologyChangeMessage_V3)) - { + if (!(obj instanceof ClusterTopologyChangeMessage_V3)) { return false; } ClusterTopologyChangeMessage_V3 other = (ClusterTopologyChangeMessage_V3) obj; - if (scaleDownGroupName == null) - { - if (other.scaleDownGroupName != null) - { + if (scaleDownGroupName == null) { + if (other.scaleDownGroupName != null) { return false; } } - else if (!scaleDownGroupName.equals(other.scaleDownGroupName)) - { + else if (!scaleDownGroupName.equals(other.scaleDownGroupName)) { return false; } return true; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CreateQueueMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CreateQueueMessage.java index e3858426cc..5f65fbe13e 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CreateQueueMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CreateQueueMessage.java @@ -20,8 +20,7 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class CreateQueueMessage extends PacketImpl -{ +public class CreateQueueMessage extends PacketImpl { private SimpleString address; @@ -40,8 +39,7 @@ public class CreateQueueMessage extends PacketImpl final SimpleString filterString, final boolean durable, final boolean temporary, - final boolean requiresResponse) - { + final boolean requiresResponse) { this(); this.address = address; @@ -52,16 +50,14 @@ public class CreateQueueMessage extends PacketImpl this.requiresResponse = requiresResponse; } - public CreateQueueMessage() - { + public CreateQueueMessage() { super(CREATE_QUEUE); } // Public -------------------------------------------------------- @Override - public String toString() - { + public String toString() { StringBuffer buff = new StringBuffer(getParentString()); buff.append(", address=" + address); buff.append(", queueName=" + queueName); @@ -72,64 +68,52 @@ public class CreateQueueMessage extends PacketImpl return buff.toString(); } - public SimpleString getAddress() - { + public SimpleString getAddress() { return address; } - public SimpleString getQueueName() - { + public SimpleString getQueueName() { return queueName; } - public SimpleString getFilterString() - { + public SimpleString getFilterString() { return filterString; } - public boolean isDurable() - { + public boolean isDurable() { return durable; } - public boolean isTemporary() - { + public boolean isTemporary() { return temporary; } - public boolean isRequiresResponse() - { + public boolean isRequiresResponse() { return requiresResponse; } - public void setAddress(SimpleString address) - { + public void setAddress(SimpleString address) { this.address = address; } - public void setQueueName(SimpleString queueName) - { + public void setQueueName(SimpleString queueName) { this.queueName = queueName; } - public void setFilterString(SimpleString filterString) - { + public void setFilterString(SimpleString filterString) { this.filterString = filterString; } - public void setDurable(boolean durable) - { + public void setDurable(boolean durable) { this.durable = durable; } - public void setTemporary(boolean temporary) - { + public void setTemporary(boolean temporary) { this.temporary = temporary; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeSimpleString(address); buffer.writeSimpleString(queueName); buffer.writeNullableSimpleString(filterString); @@ -139,8 +123,7 @@ public class CreateQueueMessage extends PacketImpl } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { address = buffer.readSimpleString(); queueName = buffer.readSimpleString(); filterString = buffer.readNullableSimpleString(); @@ -150,8 +133,7 @@ public class CreateQueueMessage extends PacketImpl } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((address == null) ? 0 : address.hashCode()); @@ -164,17 +146,15 @@ public class CreateQueueMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof CreateQueueMessage)) return false; - CreateQueueMessage other = (CreateQueueMessage)obj; - if (address == null) - { + CreateQueueMessage other = (CreateQueueMessage) obj; + if (address == null) { if (other.address != null) return false; } @@ -182,15 +162,13 @@ public class CreateQueueMessage extends PacketImpl return false; if (durable != other.durable) return false; - if (filterString == null) - { + if (filterString == null) { if (other.filterString != null) return false; } else if (!filterString.equals(other.filterString)) return false; - if (queueName == null) - { + if (queueName == null) { if (other.queueName != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CreateSessionMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CreateSessionMessage.java index d217fc122f..b18821a12c 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CreateSessionMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CreateSessionMessage.java @@ -19,8 +19,8 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class CreateSessionMessage extends PacketImpl -{ +public class CreateSessionMessage extends PacketImpl { + private String name; private long sessionChannelID; @@ -56,8 +56,7 @@ public class CreateSessionMessage extends PacketImpl final boolean autoCommitAcks, final boolean preAcknowledge, final int windowSize, - final String defaultAddress) - { + final String defaultAddress) { super(CREATESESSION); this.name = name; @@ -85,71 +84,58 @@ public class CreateSessionMessage extends PacketImpl this.defaultAddress = defaultAddress; } - public CreateSessionMessage() - { + public CreateSessionMessage() { super(CREATESESSION); } // Public -------------------------------------------------------- - public String getName() - { + public String getName() { return name; } - public long getSessionChannelID() - { + public long getSessionChannelID() { return sessionChannelID; } - public int getVersion() - { + public int getVersion() { return version; } - public String getUsername() - { + public String getUsername() { return username; } - public String getPassword() - { + public String getPassword() { return password; } - public boolean isXA() - { + public boolean isXA() { return xa; } - public boolean isAutoCommitSends() - { + public boolean isAutoCommitSends() { return autoCommitSends; } - public boolean isAutoCommitAcks() - { + public boolean isAutoCommitAcks() { return autoCommitAcks; } - public boolean isPreAcknowledge() - { + public boolean isPreAcknowledge() { return preAcknowledge; } - public int getWindowSize() - { + public int getWindowSize() { return windowSize; } - public String getDefaultAddress() - { + public String getDefaultAddress() { return defaultAddress; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeString(name); buffer.writeLong(sessionChannelID); buffer.writeInt(version); @@ -165,8 +151,7 @@ public class CreateSessionMessage extends PacketImpl } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { name = buffer.readString(); sessionChannelID = buffer.readLong(); version = buffer.readInt(); @@ -182,19 +167,16 @@ public class CreateSessionMessage extends PacketImpl } @Override - public final boolean isRequiresConfirmations() - { + public final boolean isRequiresConfirmations() { return false; } - public int getMinLargeMessageSize() - { + public int getMinLargeMessageSize() { return minLargeMessageSize; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (autoCommitAcks ? 1231 : 1237); @@ -204,7 +186,7 @@ public class CreateSessionMessage extends PacketImpl result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((password == null) ? 0 : password.hashCode()); result = prime * result + (preAcknowledge ? 1231 : 1237); - result = prime * result + (int)(sessionChannelID ^ (sessionChannelID >>> 32)); + result = prime * result + (int) (sessionChannelID ^ (sessionChannelID >>> 32)); result = prime * result + ((username == null) ? 0 : username.hashCode()); result = prime * result + version; result = prime * result + windowSize; @@ -213,21 +195,19 @@ public class CreateSessionMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof CreateSessionMessage)) return false; - CreateSessionMessage other = (CreateSessionMessage)obj; + CreateSessionMessage other = (CreateSessionMessage) obj; if (autoCommitAcks != other.autoCommitAcks) return false; if (autoCommitSends != other.autoCommitSends) return false; - if (defaultAddress == null) - { + if (defaultAddress == null) { if (other.defaultAddress != null) return false; } @@ -235,15 +215,13 @@ public class CreateSessionMessage extends PacketImpl return false; if (minLargeMessageSize != other.minLargeMessageSize) return false; - if (name == null) - { + if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; - if (password == null) - { + if (password == null) { if (other.password != null) return false; } @@ -253,8 +231,7 @@ public class CreateSessionMessage extends PacketImpl return false; if (sessionChannelID != other.sessionChannelID) return false; - if (username == null) - { + if (username == null) { if (other.username != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CreateSessionResponseMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CreateSessionResponseMessage.java index 40fdb5dc9e..6f15777d1c 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CreateSessionResponseMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CreateSessionResponseMessage.java @@ -19,54 +19,46 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class CreateSessionResponseMessage extends PacketImpl -{ +public class CreateSessionResponseMessage extends PacketImpl { + private int serverVersion; - public CreateSessionResponseMessage(final int serverVersion) - { + public CreateSessionResponseMessage(final int serverVersion) { super(CREATESESSION_RESP); this.serverVersion = serverVersion; } - public CreateSessionResponseMessage() - { + public CreateSessionResponseMessage() { super(CREATESESSION_RESP); } @Override - public boolean isResponse() - { + public boolean isResponse() { return true; } - public int getServerVersion() - { + public int getServerVersion() { return serverVersion; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeInt(serverVersion); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { serverVersion = buffer.readInt(); } @Override - public final boolean isRequiresConfirmations() - { + public final boolean isRequiresConfirmations() { return false; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + serverVersion; @@ -74,15 +66,14 @@ public class CreateSessionResponseMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof CreateSessionResponseMessage)) return false; - CreateSessionResponseMessage other = (CreateSessionResponseMessage)obj; + CreateSessionResponseMessage other = (CreateSessionResponseMessage) obj; if (serverVersion != other.serverVersion) return false; return true; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CreateSharedQueueMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CreateSharedQueueMessage.java index 079fcf7ae0..8191f1699c 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CreateSharedQueueMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CreateSharedQueueMessage.java @@ -20,8 +20,7 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class CreateSharedQueueMessage extends PacketImpl -{ +public class CreateSharedQueueMessage extends PacketImpl { private SimpleString address; @@ -37,8 +36,7 @@ public class CreateSharedQueueMessage extends PacketImpl final SimpleString queueName, final SimpleString filterString, final boolean durable, - final boolean requiresResponse) - { + final boolean requiresResponse) { this(); this.address = address; @@ -48,16 +46,14 @@ public class CreateSharedQueueMessage extends PacketImpl this.requiresResponse = requiresResponse; } - public CreateSharedQueueMessage() - { + public CreateSharedQueueMessage() { super(CREATE_SHARED_QUEUE); } // Public -------------------------------------------------------- @Override - public String toString() - { + public String toString() { StringBuffer buff = new StringBuffer(getParentString()); buff.append(", address=" + address); buff.append(", queueName=" + queueName); @@ -67,49 +63,40 @@ public class CreateSharedQueueMessage extends PacketImpl return buff.toString(); } - public SimpleString getAddress() - { + public SimpleString getAddress() { return address; } - public SimpleString getQueueName() - { + public SimpleString getQueueName() { return queueName; } - public SimpleString getFilterString() - { + public SimpleString getFilterString() { return filterString; } - public boolean isRequiresResponse() - { + public boolean isRequiresResponse() { return requiresResponse; } - public void setAddress(SimpleString address) - { + public void setAddress(SimpleString address) { this.address = address; } - public void setQueueName(SimpleString queueName) - { + public void setQueueName(SimpleString queueName) { this.queueName = queueName; } - public void setFilterString(SimpleString filterString) - { + public void setFilterString(SimpleString filterString) { this.filterString = filterString; } - public boolean isDurable() - { + public boolean isDurable() { return durable; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeSimpleString(address); buffer.writeSimpleString(queueName); buffer.writeNullableSimpleString(filterString); @@ -118,8 +105,7 @@ public class CreateSharedQueueMessage extends PacketImpl } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { address = buffer.readSimpleString(); queueName = buffer.readSimpleString(); filterString = buffer.readNullableSimpleString(); @@ -128,8 +114,7 @@ public class CreateSharedQueueMessage extends PacketImpl } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((address == null) ? 0 : address.hashCode()); @@ -141,31 +126,27 @@ public class CreateSharedQueueMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof CreateSharedQueueMessage)) return false; - CreateSharedQueueMessage other = (CreateSharedQueueMessage)obj; - if (address == null) - { + CreateSharedQueueMessage other = (CreateSharedQueueMessage) obj; + if (address == null) { if (other.address != null) return false; } else if (!address.equals(other.address)) return false; - if (filterString == null) - { + if (filterString == null) { if (other.filterString != null) return false; } else if (!filterString.equals(other.filterString)) return false; - if (queueName == null) - { + if (queueName == null) { if (other.queueName != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/DisconnectConsumerMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/DisconnectConsumerMessage.java index f6e706322e..540bc37075 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/DisconnectConsumerMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/DisconnectConsumerMessage.java @@ -16,39 +16,33 @@ */ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; - import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class DisconnectConsumerMessage extends PacketImpl -{ +public class DisconnectConsumerMessage extends PacketImpl { + private long consumerId; - public DisconnectConsumerMessage(final long consumerId) - { + public DisconnectConsumerMessage(final long consumerId) { super(DISCONNECT_CONSUMER); this.consumerId = consumerId; } - public DisconnectConsumerMessage() - { + public DisconnectConsumerMessage() { super(DISCONNECT_CONSUMER); } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeLong(consumerId); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { consumerId = buffer.readLong(); } - public long getConsumerId() - { + public long getConsumerId() { return consumerId; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/DisconnectMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/DisconnectMessage.java index c9f0d66808..13fdc08f6d 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/DisconnectMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/DisconnectMessage.java @@ -20,8 +20,7 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class DisconnectMessage extends PacketImpl -{ +public class DisconnectMessage extends PacketImpl { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -32,45 +31,38 @@ public class DisconnectMessage extends PacketImpl // Constructors -------------------------------------------------- - public DisconnectMessage(final SimpleString nodeID) - { + public DisconnectMessage(final SimpleString nodeID) { super(DISCONNECT); this.nodeID = nodeID; } - public DisconnectMessage() - { + public DisconnectMessage() { super(DISCONNECT); } - public DisconnectMessage(byte disconnectV2) - { + public DisconnectMessage(byte disconnectV2) { super(disconnectV2); } // Public -------------------------------------------------------- - public SimpleString getNodeID() - { + public SimpleString getNodeID() { return nodeID; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeNullableSimpleString(nodeID); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { nodeID = buffer.readNullableSimpleString(); } @Override - public String toString() - { + public String toString() { StringBuffer buf = new StringBuffer(getParentString()); buf.append(", nodeID=" + nodeID); buf.append("]"); @@ -78,14 +70,12 @@ public class DisconnectMessage extends PacketImpl } @Override - public final boolean isRequiresConfirmations() - { + public final boolean isRequiresConfirmations() { return false; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((nodeID == null) ? 0 : nodeID.hashCode()); @@ -93,30 +83,23 @@ public class DisconnectMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { - if (this == obj) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if (!super.equals(obj)) - { + if (!super.equals(obj)) { return false; } - if (!(obj instanceof DisconnectMessage)) - { + if (!(obj instanceof DisconnectMessage)) { return false; } - DisconnectMessage other = (DisconnectMessage)obj; - if (nodeID == null) - { - if (other.nodeID != null) - { + DisconnectMessage other = (DisconnectMessage) obj; + if (nodeID == null) { + if (other.nodeID != null) { return false; } } - else if (!nodeID.equals(other.nodeID)) - { + else if (!nodeID.equals(other.nodeID)) { return false; } return true; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/DisconnectMessage_V2.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/DisconnectMessage_V2.java index cbde5a5045..8d50ed1eb0 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/DisconnectMessage_V2.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/DisconnectMessage_V2.java @@ -19,12 +19,11 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.SimpleString; -public class DisconnectMessage_V2 extends DisconnectMessage -{ +public class DisconnectMessage_V2 extends DisconnectMessage { + private SimpleString scaleDownNodeID; - public DisconnectMessage_V2(final SimpleString nodeID, final String scaleDownNodeID) - { + public DisconnectMessage_V2(final SimpleString nodeID, final String scaleDownNodeID) { super(DISCONNECT_V2); this.nodeID = nodeID; @@ -32,35 +31,30 @@ public class DisconnectMessage_V2 extends DisconnectMessage this.scaleDownNodeID = SimpleString.toSimpleString(scaleDownNodeID); } - public DisconnectMessage_V2() - { + public DisconnectMessage_V2() { super(DISCONNECT_V2); } // Public -------------------------------------------------------- - public SimpleString getScaleDownNodeID() - { + public SimpleString getScaleDownNodeID() { return scaleDownNodeID; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { super.encodeRest(buffer); buffer.writeNullableSimpleString(scaleDownNodeID); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { super.decodeRest(buffer); scaleDownNodeID = buffer.readNullableSimpleString(); } @Override - public String toString() - { + public String toString() { StringBuffer buf = new StringBuffer(getParentString()); buf.append(", nodeID=" + nodeID); buf.append(", scaleDownNodeID=" + scaleDownNodeID); @@ -69,8 +63,7 @@ public class DisconnectMessage_V2 extends DisconnectMessage } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((scaleDownNodeID == null) ? 0 : scaleDownNodeID.hashCode()); @@ -78,30 +71,23 @@ public class DisconnectMessage_V2 extends DisconnectMessage } @Override - public boolean equals(Object obj) - { - if (this == obj) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if (!super.equals(obj)) - { + if (!super.equals(obj)) { return false; } - if (!(obj instanceof DisconnectMessage_V2)) - { + if (!(obj instanceof DisconnectMessage_V2)) { return false; } DisconnectMessage_V2 other = (DisconnectMessage_V2) obj; - if (scaleDownNodeID == null) - { - if (other.scaleDownNodeID != null) - { + if (scaleDownNodeID == null) { + if (other.scaleDownNodeID != null) { return false; } } - else if (!scaleDownNodeID.equals(other.scaleDownNodeID)) - { + else if (!scaleDownNodeID.equals(other.scaleDownNodeID)) { return false; } return true; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/MessagePacket.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/MessagePacket.java index 275f0a5e9e..abcb233f44 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/MessagePacket.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/MessagePacket.java @@ -20,19 +20,17 @@ import org.apache.activemq.artemis.api.core.Message; import org.apache.activemq.artemis.core.message.impl.MessageInternal; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public abstract class MessagePacket extends PacketImpl -{ +public abstract class MessagePacket extends PacketImpl { + protected MessageInternal message; - public MessagePacket(final byte type, final MessageInternal message) - { + public MessagePacket(final byte type, final MessageInternal message) { super(type); this.message = message; } - public Message getMessage() - { + public Message getMessage() { return message; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/NullResponseMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/NullResponseMessage.java index d62781adb2..b979495ece 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/NullResponseMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/NullResponseMessage.java @@ -18,17 +18,14 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class NullResponseMessage extends PacketImpl -{ +public class NullResponseMessage extends PacketImpl { - public NullResponseMessage() - { + public NullResponseMessage() { super(NULL_RESPONSE); } @Override - public boolean isResponse() - { + public boolean isResponse() { return true; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/PacketsConfirmedMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/PacketsConfirmedMessage.java index 7659b25e1c..6cec0acd82 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/PacketsConfirmedMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/PacketsConfirmedMessage.java @@ -19,58 +19,48 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class PacketsConfirmedMessage extends PacketImpl -{ +public class PacketsConfirmedMessage extends PacketImpl { private int commandID; - public PacketsConfirmedMessage(final int commandID) - { + public PacketsConfirmedMessage(final int commandID) { super(PACKETS_CONFIRMED); this.commandID = commandID; } - public PacketsConfirmedMessage() - { + public PacketsConfirmedMessage() { super(PACKETS_CONFIRMED); } // Public -------------------------------------------------------- - public int getCommandID() - { + public int getCommandID() { return commandID; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeInt(commandID); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { commandID = buffer.readInt(); } - @Override - public final boolean isRequiresConfirmations() - { + public final boolean isRequiresConfirmations() { return false; } @Override - public String toString() - { + public String toString() { return getParentString() + ", commandID=" + commandID + "]"; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + commandID; @@ -78,23 +68,18 @@ public class PacketsConfirmedMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { - if (this == obj) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if (!super.equals(obj)) - { + if (!super.equals(obj)) { return false; } - if (!(obj instanceof PacketsConfirmedMessage)) - { + if (!(obj instanceof PacketsConfirmedMessage)) { return false; } - PacketsConfirmedMessage other = (PacketsConfirmedMessage)obj; - if (commandID != other.commandID) - { + PacketsConfirmedMessage other = (PacketsConfirmedMessage) obj; + if (commandID != other.commandID) { return false; } return true; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/Ping.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/Ping.java index 7113d5ad89..2656294bb6 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/Ping.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/Ping.java @@ -23,48 +23,41 @@ import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; * Ping is sent on the client side by {@link org.apache.activemq.artemis.core.client.impl.ClientSessionFactoryImpl}. At the server's * side it is handled by org.apache.activemq.artemis.core.remoting.server.impl.RemotingServiceImpl */ -public final class Ping extends PacketImpl -{ +public final class Ping extends PacketImpl { + private long connectionTTL; - public Ping(final long connectionTTL) - { + public Ping(final long connectionTTL) { super(PING); this.connectionTTL = connectionTTL; } - public Ping() - { + public Ping() { super(PING); } - public long getConnectionTTL() - { + public long getConnectionTTL() { return connectionTTL; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeLong(connectionTTL); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { connectionTTL = buffer.readLong(); } @Override - public boolean isRequiresConfirmations() - { + public boolean isRequiresConfirmations() { return false; } @Override - public String toString() - { + public String toString() { StringBuffer buf = new StringBuffer(getParentString()); buf.append(", connectionTTL=" + connectionTTL); buf.append("]"); @@ -72,32 +65,26 @@ public final class Ping extends PacketImpl } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); - result = prime * result + (int)(connectionTTL ^ (connectionTTL >>> 32)); + result = prime * result + (int) (connectionTTL ^ (connectionTTL >>> 32)); return result; } @Override - public boolean equals(Object obj) - { - if (this == obj) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if (!super.equals(obj)) - { + if (!super.equals(obj)) { return false; } - if (!(obj instanceof Ping)) - { + if (!(obj instanceof Ping)) { return false; } - Ping other = (Ping)obj; - if (connectionTTL != other.connectionTTL) - { + Ping other = (Ping) obj; + if (connectionTTL != other.connectionTTL) { return false; } return true; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReattachSessionMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReattachSessionMessage.java index 2ec31441b6..db35eac3c2 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReattachSessionMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReattachSessionMessage.java @@ -19,14 +19,13 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class ReattachSessionMessage extends PacketImpl -{ +public class ReattachSessionMessage extends PacketImpl { + private String name; private int lastConfirmedCommandID; - public ReattachSessionMessage(final String name, final int lastConfirmedCommandID) - { + public ReattachSessionMessage(final String name, final int lastConfirmedCommandID) { super(REATTACH_SESSION); this.name = name; @@ -34,44 +33,37 @@ public class ReattachSessionMessage extends PacketImpl this.lastConfirmedCommandID = lastConfirmedCommandID; } - public ReattachSessionMessage() - { + public ReattachSessionMessage() { super(REATTACH_SESSION); } - public String getName() - { + public String getName() { return name; } - public int getLastConfirmedCommandID() - { + public int getLastConfirmedCommandID() { return lastConfirmedCommandID; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeString(name); buffer.writeInt(lastConfirmedCommandID); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { name = buffer.readString(); lastConfirmedCommandID = buffer.readInt(); } @Override - public final boolean isRequiresConfirmations() - { + public final boolean isRequiresConfirmations() { return false; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + lastConfirmedCommandID; @@ -80,19 +72,17 @@ public class ReattachSessionMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof ReattachSessionMessage)) return false; - ReattachSessionMessage other = (ReattachSessionMessage)obj; + ReattachSessionMessage other = (ReattachSessionMessage) obj; if (lastConfirmedCommandID != other.lastConfirmedCommandID) return false; - if (name == null) - { + if (name == null) { if (other.name != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReattachSessionResponseMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReattachSessionResponseMessage.java index 1ed282aa59..89c59b6c6e 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReattachSessionResponseMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReattachSessionResponseMessage.java @@ -19,14 +19,13 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class ReattachSessionResponseMessage extends PacketImpl -{ +public class ReattachSessionResponseMessage extends PacketImpl { + private int lastConfirmedCommandID; private boolean reattached; - public ReattachSessionResponseMessage(final int lastConfirmedCommandID, final boolean reattached) - { + public ReattachSessionResponseMessage(final int lastConfirmedCommandID, final boolean reattached) { super(REATTACH_SESSION_RESP); this.lastConfirmedCommandID = lastConfirmedCommandID; @@ -34,52 +33,44 @@ public class ReattachSessionResponseMessage extends PacketImpl this.reattached = reattached; } - public ReattachSessionResponseMessage() - { + public ReattachSessionResponseMessage() { super(REATTACH_SESSION_RESP); } // Public -------------------------------------------------------- - public int getLastConfirmedCommandID() - { + public int getLastConfirmedCommandID() { return lastConfirmedCommandID; } - public boolean isReattached() - { + public boolean isReattached() { return reattached; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeInt(lastConfirmedCommandID); buffer.writeBoolean(reattached); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { lastConfirmedCommandID = buffer.readInt(); reattached = buffer.readBoolean(); } @Override - public boolean isResponse() - { + public boolean isResponse() { return true; } @Override - public final boolean isRequiresConfirmations() - { + public final boolean isRequiresConfirmations() { return false; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + lastConfirmedCommandID; @@ -88,15 +79,14 @@ public class ReattachSessionResponseMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof ReattachSessionResponseMessage)) return false; - ReattachSessionResponseMessage other = (ReattachSessionResponseMessage)obj; + ReattachSessionResponseMessage other = (ReattachSessionResponseMessage) obj; if (lastConfirmedCommandID != other.lastConfirmedCommandID) return false; if (reattached != other.reattached) diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/RollbackMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/RollbackMessage.java index 11c3c6163a..f9f947914c 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/RollbackMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/RollbackMessage.java @@ -19,55 +19,46 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class RollbackMessage extends PacketImpl -{ +public class RollbackMessage extends PacketImpl { - public RollbackMessage() - { + public RollbackMessage() { super(SESS_ROLLBACK); } - public RollbackMessage(final boolean considerLastMessageAsDelivered) - { + public RollbackMessage(final boolean considerLastMessageAsDelivered) { super(SESS_ROLLBACK); this.considerLastMessageAsDelivered = considerLastMessageAsDelivered; } - private boolean considerLastMessageAsDelivered; /** * @return the considerLastMessageAsDelivered */ - public boolean isConsiderLastMessageAsDelivered() - { + public boolean isConsiderLastMessageAsDelivered() { return considerLastMessageAsDelivered; } /** * @param isLastMessageAsDelivered the considerLastMessageAsDelivered to set */ - public void setConsiderLastMessageAsDelivered(final boolean isLastMessageAsDelivered) - { + public void setConsiderLastMessageAsDelivered(final boolean isLastMessageAsDelivered) { considerLastMessageAsDelivered = isLastMessageAsDelivered; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeBoolean(considerLastMessageAsDelivered); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { considerLastMessageAsDelivered = buffer.readBoolean(); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (considerLastMessageAsDelivered ? 1231 : 1237); @@ -75,15 +66,14 @@ public class RollbackMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof RollbackMessage)) return false; - RollbackMessage other = (RollbackMessage)obj; + RollbackMessage other = (RollbackMessage) obj; if (considerLastMessageAsDelivered != other.considerLastMessageAsDelivered) return false; return true; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionAcknowledgeMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionAcknowledgeMessage.java index 49a3308cfd..45a4a25364 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionAcknowledgeMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionAcknowledgeMessage.java @@ -19,16 +19,15 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class SessionAcknowledgeMessage extends PacketImpl -{ +public class SessionAcknowledgeMessage extends PacketImpl { + private long consumerID; private long messageID; private boolean requiresResponse; - public SessionAcknowledgeMessage(final long consumerID, final long messageID, final boolean requiresResponse) - { + public SessionAcknowledgeMessage(final long consumerID, final long messageID, final boolean requiresResponse) { super(SESS_ACKNOWLEDGE); this.consumerID = consumerID; @@ -38,31 +37,26 @@ public class SessionAcknowledgeMessage extends PacketImpl this.requiresResponse = requiresResponse; } - public SessionAcknowledgeMessage() - { + public SessionAcknowledgeMessage() { super(SESS_ACKNOWLEDGE); } // Public -------------------------------------------------------- - public long getConsumerID() - { + public long getConsumerID() { return consumerID; } - public long getMessageID() - { + public long getMessageID() { return messageID; } - public boolean isRequiresResponse() - { + public boolean isRequiresResponse() { return requiresResponse; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeLong(consumerID); buffer.writeLong(messageID); @@ -71,8 +65,7 @@ public class SessionAcknowledgeMessage extends PacketImpl } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { consumerID = buffer.readLong(); messageID = buffer.readLong(); @@ -81,26 +74,24 @@ public class SessionAcknowledgeMessage extends PacketImpl } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); - result = prime * result + (int)(consumerID ^ (consumerID >>> 32)); - result = prime * result + (int)(messageID ^ (messageID >>> 32)); + result = prime * result + (int) (consumerID ^ (consumerID >>> 32)); + result = prime * result + (int) (messageID ^ (messageID >>> 32)); result = prime * result + (requiresResponse ? 1231 : 1237); return result; } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionAcknowledgeMessage)) return false; - SessionAcknowledgeMessage other = (SessionAcknowledgeMessage)obj; + SessionAcknowledgeMessage other = (SessionAcknowledgeMessage) obj; if (consumerID != other.consumerID) return false; if (messageID != other.messageID) diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionAddMetaDataMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionAddMetaDataMessage.java index 4e750fe2fa..b54336e28e 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionAddMetaDataMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionAddMetaDataMessage.java @@ -24,56 +24,48 @@ import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; * * Packet deprecated: It exists only to support old formats */ -public class SessionAddMetaDataMessage extends PacketImpl -{ +public class SessionAddMetaDataMessage extends PacketImpl { + private String key; private String data; - public SessionAddMetaDataMessage() - { + public SessionAddMetaDataMessage() { super(SESS_ADD_METADATA); } - public SessionAddMetaDataMessage(String k, String d) - { + public SessionAddMetaDataMessage(String k, String d) { this(); key = k; data = d; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeString(key); buffer.writeString(data); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { key = buffer.readString(); data = buffer.readString(); } @Override - public final boolean isRequiresConfirmations() - { + public final boolean isRequiresConfirmations() { return false; } - public String getKey() - { + public String getKey() { return key; } - public String getData() - { + public String getData() { return data; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((data == null) ? 0 : data.hashCode()); @@ -82,24 +74,21 @@ public class SessionAddMetaDataMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionAddMetaDataMessage)) return false; - SessionAddMetaDataMessage other = (SessionAddMetaDataMessage)obj; - if (data == null) - { + SessionAddMetaDataMessage other = (SessionAddMetaDataMessage) obj; + if (data == null) { if (other.data != null) return false; } else if (!data.equals(other.data)) return false; - if (key == null) - { + if (key == null) { if (other.key != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionAddMetaDataMessageV2.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionAddMetaDataMessageV2.java index c203eb767e..d0d12fccb4 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionAddMetaDataMessageV2.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionAddMetaDataMessageV2.java @@ -24,8 +24,8 @@ import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; * * This packet replaces {@link SessionAddMetaDataMessage} */ -public class SessionAddMetaDataMessageV2 extends PacketImpl -{ +public class SessionAddMetaDataMessageV2 extends PacketImpl { + private String key; private String data; /** @@ -33,32 +33,27 @@ public class SessionAddMetaDataMessageV2 extends PacketImpl */ private boolean requiresConfirmation = true; - public SessionAddMetaDataMessageV2() - { + public SessionAddMetaDataMessageV2() { super(SESS_ADD_METADATA2); } - protected SessionAddMetaDataMessageV2(byte packetCode) - { + protected SessionAddMetaDataMessageV2(byte packetCode) { super(packetCode); } - public SessionAddMetaDataMessageV2(String k, String d) - { + public SessionAddMetaDataMessageV2(String k, String d) { this(); key = k; data = d; } - protected SessionAddMetaDataMessageV2(final byte packetCode, String k, String d) - { + protected SessionAddMetaDataMessageV2(final byte packetCode, String k, String d) { super(packetCode); key = k; data = d; } - public SessionAddMetaDataMessageV2(String k, String d, boolean requiresConfirmation) - { + public SessionAddMetaDataMessageV2(String k, String d, boolean requiresConfirmation) { this(); key = k; data = d; @@ -66,40 +61,34 @@ public class SessionAddMetaDataMessageV2 extends PacketImpl } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeString(key); buffer.writeString(data); buffer.writeBoolean(requiresConfirmation); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { key = buffer.readString(); data = buffer.readString(); requiresConfirmation = buffer.readBoolean(); } @Override - public final boolean isRequiresConfirmations() - { + public final boolean isRequiresConfirmations() { return requiresConfirmation; } - public String getKey() - { + public String getKey() { return key; } - public String getData() - { + public String getData() { return data; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((data == null) ? 0 : data.hashCode()); @@ -109,24 +98,21 @@ public class SessionAddMetaDataMessageV2 extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionAddMetaDataMessageV2)) return false; - SessionAddMetaDataMessageV2 other = (SessionAddMetaDataMessageV2)obj; - if (data == null) - { + SessionAddMetaDataMessageV2 other = (SessionAddMetaDataMessageV2) obj; + if (data == null) { if (other.data != null) return false; } else if (!data.equals(other.data)) return false; - if (key == null) - { + if (key == null) { if (other.key != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionBindingQueryMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionBindingQueryMessage.java index d2df21e197..73cf603276 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionBindingQueryMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionBindingQueryMessage.java @@ -20,42 +20,36 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class SessionBindingQueryMessage extends PacketImpl -{ +public class SessionBindingQueryMessage extends PacketImpl { + private SimpleString address; - public SessionBindingQueryMessage(final SimpleString address) - { + public SessionBindingQueryMessage(final SimpleString address) { super(SESS_BINDINGQUERY); this.address = address; } - public SessionBindingQueryMessage() - { + public SessionBindingQueryMessage() { super(SESS_BINDINGQUERY); } - public SimpleString getAddress() - { + public SimpleString getAddress() { return address; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeSimpleString(address); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { address = buffer.readSimpleString(); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((address == null) ? 0 : address.hashCode()); @@ -63,17 +57,15 @@ public class SessionBindingQueryMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionBindingQueryMessage)) return false; - SessionBindingQueryMessage other = (SessionBindingQueryMessage)obj; - if (address == null) - { + SessionBindingQueryMessage other = (SessionBindingQueryMessage) obj; + if (address == null) { if (other.address != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionBindingQueryResponseMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionBindingQueryResponseMessage.java index 5561eb6fb5..7d77edcc1c 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionBindingQueryResponseMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionBindingQueryResponseMessage.java @@ -24,17 +24,15 @@ import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; /** - * * A SessionBindingQueryResponseMessage */ -public class SessionBindingQueryResponseMessage extends PacketImpl -{ +public class SessionBindingQueryResponseMessage extends PacketImpl { + protected boolean exists; protected List queueNames; - public SessionBindingQueryResponseMessage(final boolean exists, final List queueNames) - { + public SessionBindingQueryResponseMessage(final boolean exists, final List queueNames) { super(SESS_BINDINGQUERY_RESP); this.exists = exists; @@ -42,58 +40,48 @@ public class SessionBindingQueryResponseMessage extends PacketImpl this.queueNames = queueNames; } - public SessionBindingQueryResponseMessage() - { + public SessionBindingQueryResponseMessage() { super(SESS_BINDINGQUERY_RESP); } - public SessionBindingQueryResponseMessage(byte v2) - { + public SessionBindingQueryResponseMessage(byte v2) { super(v2); } @Override - public boolean isResponse() - { + public boolean isResponse() { return true; } - public boolean isExists() - { + public boolean isExists() { return exists; } - public List getQueueNames() - { + public List getQueueNames() { return queueNames; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeBoolean(exists); buffer.writeInt(queueNames.size()); - for (SimpleString queueName : queueNames) - { + for (SimpleString queueName : queueNames) { buffer.writeSimpleString(queueName); } } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { exists = buffer.readBoolean(); int numQueues = buffer.readInt(); queueNames = new ArrayList(numQueues); - for (int i = 0; i < numQueues; i++) - { + for (int i = 0; i < numQueues; i++) { queueNames.add(buffer.readSimpleString()); } } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (exists ? 1231 : 1237); @@ -102,19 +90,17 @@ public class SessionBindingQueryResponseMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionBindingQueryResponseMessage)) return false; - SessionBindingQueryResponseMessage other = (SessionBindingQueryResponseMessage)obj; + SessionBindingQueryResponseMessage other = (SessionBindingQueryResponseMessage) obj; if (exists != other.exists) return false; - if (queueNames == null) - { + if (queueNames == null) { if (other.queueNames != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionBindingQueryResponseMessage_V2.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionBindingQueryResponseMessage_V2.java index 0d142b1fed..269633c7d6 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionBindingQueryResponseMessage_V2.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionBindingQueryResponseMessage_V2.java @@ -21,12 +21,13 @@ import java.util.List; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.SimpleString; -public class SessionBindingQueryResponseMessage_V2 extends SessionBindingQueryResponseMessage -{ +public class SessionBindingQueryResponseMessage_V2 extends SessionBindingQueryResponseMessage { + private boolean autoCreateJmsQueues; - public SessionBindingQueryResponseMessage_V2(final boolean exists, final List queueNames, final boolean autoCreateJmsQueues) - { + public SessionBindingQueryResponseMessage_V2(final boolean exists, + final List queueNames, + final boolean autoCreateJmsQueues) { super(SESS_BINDINGQUERY_RESP_V2); this.exists = exists; @@ -36,33 +37,28 @@ public class SessionBindingQueryResponseMessage_V2 extends SessionBindingQueryRe this.autoCreateJmsQueues = autoCreateJmsQueues; } - public SessionBindingQueryResponseMessage_V2() - { + public SessionBindingQueryResponseMessage_V2() { super(SESS_BINDINGQUERY_RESP_V2); } - public boolean isAutoCreateJmsQueues() - { + public boolean isAutoCreateJmsQueues() { return autoCreateJmsQueues; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { super.encodeRest(buffer); buffer.writeBoolean(autoCreateJmsQueues); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { super.decodeRest(buffer); autoCreateJmsQueues = buffer.readBoolean(); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (autoCreateJmsQueues ? 1231 : 1237); @@ -70,15 +66,14 @@ public class SessionBindingQueryResponseMessage_V2 extends SessionBindingQueryRe } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionBindingQueryResponseMessage_V2)) return false; - SessionBindingQueryResponseMessage_V2 other = (SessionBindingQueryResponseMessage_V2)obj; + SessionBindingQueryResponseMessage_V2 other = (SessionBindingQueryResponseMessage_V2) obj; if (autoCreateJmsQueues != other.autoCreateJmsQueues) return false; return true; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionCloseMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionCloseMessage.java index ee9e24252a..3024e87a06 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionCloseMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionCloseMessage.java @@ -18,22 +18,17 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class SessionCloseMessage extends PacketImpl -{ +public class SessionCloseMessage extends PacketImpl { - - public SessionCloseMessage() - { + public SessionCloseMessage() { super(SESS_CLOSE); } // Public -------------------------------------------------------- @Override - public boolean equals(final Object other) - { - if (other instanceof SessionCloseMessage == false) - { + public boolean equals(final Object other) { + if (other instanceof SessionCloseMessage == false) { return false; } @@ -41,8 +36,7 @@ public class SessionCloseMessage extends PacketImpl } @Override - public int hashCode() - { + public int hashCode() { // TODO return 0; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionCommitMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionCommitMessage.java index acacbcce5f..215419094c 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionCommitMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionCommitMessage.java @@ -18,11 +18,9 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class SessionCommitMessage extends PacketImpl -{ +public class SessionCommitMessage extends PacketImpl { - public SessionCommitMessage() - { + public SessionCommitMessage() { super(SESS_COMMIT); } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionConsumerCloseMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionConsumerCloseMessage.java index debc8c8b69..a3570a245e 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionConsumerCloseMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionConsumerCloseMessage.java @@ -19,67 +19,58 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class SessionConsumerCloseMessage extends PacketImpl -{ +public class SessionConsumerCloseMessage extends PacketImpl { private long consumerID; - public SessionConsumerCloseMessage(final long objectID) - { + public SessionConsumerCloseMessage(final long objectID) { super(SESS_CONSUMER_CLOSE); consumerID = objectID; } - public SessionConsumerCloseMessage() - { + public SessionConsumerCloseMessage() { super(SESS_CONSUMER_CLOSE); } // Public -------------------------------------------------------- - public long getConsumerID() - { + public long getConsumerID() { return consumerID; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeLong(consumerID); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { consumerID = buffer.readLong(); } @Override - public String toString() - { + public String toString() { return getParentString() + ", consumerID=" + consumerID + "]"; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); - result = prime * result + (int)(consumerID ^ (consumerID >>> 32)); + result = prime * result + (int) (consumerID ^ (consumerID >>> 32)); return result; } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionConsumerCloseMessage)) return false; - SessionConsumerCloseMessage other = (SessionConsumerCloseMessage)obj; + SessionConsumerCloseMessage other = (SessionConsumerCloseMessage) obj; if (consumerID != other.consumerID) return false; return true; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionConsumerFlowCreditMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionConsumerFlowCreditMessage.java index 65db75a2fa..71ab68ae31 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionConsumerFlowCreditMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionConsumerFlowCreditMessage.java @@ -19,75 +19,66 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class SessionConsumerFlowCreditMessage extends PacketImpl -{ +public class SessionConsumerFlowCreditMessage extends PacketImpl { + private long consumerID; private int credits; - public SessionConsumerFlowCreditMessage(final long consumerID, final int credits) - { + public SessionConsumerFlowCreditMessage(final long consumerID, final int credits) { super(SESS_FLOWTOKEN); this.consumerID = consumerID; this.credits = credits; } - public SessionConsumerFlowCreditMessage() - { + public SessionConsumerFlowCreditMessage() { super(SESS_FLOWTOKEN); } // Public -------------------------------------------------------- - public long getConsumerID() - { + public long getConsumerID() { return consumerID; } - public int getCredits() - { + public int getCredits() { return credits; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeLong(consumerID); buffer.writeInt(credits); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { consumerID = buffer.readLong(); credits = buffer.readInt(); } @Override - public String toString() - { + public String toString() { return getParentString() + ", consumerID=" + consumerID + ", credits=" + credits + "]"; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); - result = prime * result + (int)(consumerID ^ (consumerID >>> 32)); + result = prime * result + (int) (consumerID ^ (consumerID >>> 32)); result = prime * result + credits; return result; } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionConsumerFlowCreditMessage)) return false; - SessionConsumerFlowCreditMessage other = (SessionConsumerFlowCreditMessage)obj; + SessionConsumerFlowCreditMessage other = (SessionConsumerFlowCreditMessage) obj; if (consumerID != other.consumerID) return false; if (credits != other.credits) diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionContinuationMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionContinuationMessage.java index e0f891c6cf..901837bc7d 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionContinuationMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionContinuationMessage.java @@ -22,25 +22,22 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; import org.apache.activemq.artemis.utils.DataConstants; -public abstract class SessionContinuationMessage extends PacketImpl -{ +public abstract class SessionContinuationMessage extends PacketImpl { public static final int SESSION_CONTINUATION_BASE_SIZE = PACKET_HEADERS_SIZE + DataConstants.SIZE_INT + - DataConstants.SIZE_BOOLEAN; + DataConstants.SIZE_BOOLEAN; protected byte[] body; protected boolean continues; - public SessionContinuationMessage(final byte type, final byte[] body, final boolean continues) - { + public SessionContinuationMessage(final byte type, final byte[] body, final boolean continues) { super(type); this.body = body; this.continues = continues; } - public SessionContinuationMessage(final byte type) - { + public SessionContinuationMessage(final byte type) { super(type); } @@ -49,14 +46,11 @@ public abstract class SessionContinuationMessage extends PacketImpl /** * @return the body */ - public byte[] getBody() - { - if (size <= 0) - { + public byte[] getBody() { + if (size <= 0) { return new byte[0]; } - else - { + else { return body; } } @@ -64,22 +58,19 @@ public abstract class SessionContinuationMessage extends PacketImpl /** * @return the continues */ - public boolean isContinues() - { + public boolean isContinues() { return continues; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeInt(body.length); buffer.writeBytes(body); buffer.writeBoolean(continues); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { int size = buffer.readInt(); body = new byte[size]; buffer.readBytes(body); @@ -87,8 +78,7 @@ public abstract class SessionContinuationMessage extends PacketImpl } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + Arrays.hashCode(body); @@ -97,15 +87,14 @@ public abstract class SessionContinuationMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionContinuationMessage)) return false; - SessionContinuationMessage other = (SessionContinuationMessage)obj; + SessionContinuationMessage other = (SessionContinuationMessage) obj; if (!Arrays.equals(body, other.body)) return false; if (continues != other.continues) diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionCreateConsumerMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionCreateConsumerMessage.java index 488230f84e..bae39d2f77 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionCreateConsumerMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionCreateConsumerMessage.java @@ -20,8 +20,7 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class SessionCreateConsumerMessage extends PacketImpl -{ +public class SessionCreateConsumerMessage extends PacketImpl { private long id; @@ -37,8 +36,7 @@ public class SessionCreateConsumerMessage extends PacketImpl final SimpleString queueName, final SimpleString filterString, final boolean browseOnly, - final boolean requiresResponse) - { + final boolean requiresResponse) { super(SESS_CREATECONSUMER); this.id = id; @@ -48,14 +46,12 @@ public class SessionCreateConsumerMessage extends PacketImpl this.requiresResponse = requiresResponse; } - public SessionCreateConsumerMessage() - { + public SessionCreateConsumerMessage() { super(SESS_CREATECONSUMER); } @Override - public String toString() - { + public String toString() { StringBuffer buff = new StringBuffer(getParentString()); buff.append(", queueName=" + queueName); buff.append(", filterString=" + filterString); @@ -63,49 +59,40 @@ public class SessionCreateConsumerMessage extends PacketImpl return buff.toString(); } - public long getID() - { + public long getID() { return id; } - public SimpleString getQueueName() - { + public SimpleString getQueueName() { return queueName; } - public SimpleString getFilterString() - { + public SimpleString getFilterString() { return filterString; } - public boolean isBrowseOnly() - { + public boolean isBrowseOnly() { return browseOnly; } - public boolean isRequiresResponse() - { + public boolean isRequiresResponse() { return requiresResponse; } - public void setQueueName(SimpleString queueName) - { + public void setQueueName(SimpleString queueName) { this.queueName = queueName; } - public void setFilterString(SimpleString filterString) - { + public void setFilterString(SimpleString filterString) { this.filterString = filterString; } - public void setBrowseOnly(boolean browseOnly) - { + public void setBrowseOnly(boolean browseOnly) { this.browseOnly = browseOnly; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeLong(id); buffer.writeSimpleString(queueName); buffer.writeNullableSimpleString(filterString); @@ -114,8 +101,7 @@ public class SessionCreateConsumerMessage extends PacketImpl } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { id = buffer.readLong(); queueName = buffer.readSimpleString(); filterString = buffer.readNullableSimpleString(); @@ -124,32 +110,29 @@ public class SessionCreateConsumerMessage extends PacketImpl } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (browseOnly ? 1231 : 1237); result = prime * result + ((filterString == null) ? 0 : filterString.hashCode()); - result = prime * result + (int)(id ^ (id >>> 32)); + result = prime * result + (int) (id ^ (id >>> 32)); result = prime * result + ((queueName == null) ? 0 : queueName.hashCode()); result = prime * result + (requiresResponse ? 1231 : 1237); return result; } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionCreateConsumerMessage)) return false; - SessionCreateConsumerMessage other = (SessionCreateConsumerMessage)obj; + SessionCreateConsumerMessage other = (SessionCreateConsumerMessage) obj; if (browseOnly != other.browseOnly) return false; - if (filterString == null) - { + if (filterString == null) { if (other.filterString != null) return false; } @@ -157,8 +140,7 @@ public class SessionCreateConsumerMessage extends PacketImpl return false; if (id != other.id) return false; - if (queueName == null) - { + if (queueName == null) { if (other.queueName != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionDeleteQueueMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionDeleteQueueMessage.java index 47d0a51fa6..def97d8436 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionDeleteQueueMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionDeleteQueueMessage.java @@ -20,51 +20,44 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class SessionDeleteQueueMessage extends PacketImpl -{ +public class SessionDeleteQueueMessage extends PacketImpl { + private SimpleString queueName; - public SessionDeleteQueueMessage(final SimpleString queueName) - { + public SessionDeleteQueueMessage(final SimpleString queueName) { super(DELETE_QUEUE); this.queueName = queueName; } - public SessionDeleteQueueMessage() - { + public SessionDeleteQueueMessage() { super(DELETE_QUEUE); } @Override - public String toString() - { + public String toString() { StringBuffer buff = new StringBuffer(getParentString()); buff.append(", queueName=" + queueName); buff.append("]"); return buff.toString(); } - public SimpleString getQueueName() - { + public SimpleString getQueueName() { return queueName; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeSimpleString(queueName); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { queueName = buffer.readSimpleString(); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((queueName == null) ? 0 : queueName.hashCode()); @@ -72,17 +65,15 @@ public class SessionDeleteQueueMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionDeleteQueueMessage)) return false; - SessionDeleteQueueMessage other = (SessionDeleteQueueMessage)obj; - if (queueName == null) - { + SessionDeleteQueueMessage other = (SessionDeleteQueueMessage) obj; + if (queueName == null) { if (other.queueName != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionExpireMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionExpireMessage.java index 230831c405..48e9ea4fd1 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionExpireMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionExpireMessage.java @@ -19,8 +19,7 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class SessionExpireMessage extends PacketImpl -{ +public class SessionExpireMessage extends PacketImpl { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -33,8 +32,7 @@ public class SessionExpireMessage extends PacketImpl // Constructors -------------------------------------------------- - public SessionExpireMessage(final long consumerID, final long messageID) - { + public SessionExpireMessage(final long consumerID, final long messageID) { super(SESS_EXPIRED); this.consumerID = consumerID; @@ -42,59 +40,52 @@ public class SessionExpireMessage extends PacketImpl this.messageID = messageID; } - public SessionExpireMessage() - { + public SessionExpireMessage() { super(SESS_EXPIRED); } // Public -------------------------------------------------------- - public long getConsumerID() - { + public long getConsumerID() { return consumerID; } - public long getMessageID() - { + public long getMessageID() { return messageID; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeLong(consumerID); buffer.writeLong(messageID); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { consumerID = buffer.readLong(); messageID = buffer.readLong(); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); - result = prime * result + (int)(consumerID ^ (consumerID >>> 32)); - result = prime * result + (int)(messageID ^ (messageID >>> 32)); + result = prime * result + (int) (consumerID ^ (consumerID >>> 32)); + result = prime * result + (int) (messageID ^ (messageID >>> 32)); return result; } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionExpireMessage)) return false; - SessionExpireMessage other = (SessionExpireMessage)obj; + SessionExpireMessage other = (SessionExpireMessage) obj; if (consumerID != other.consumerID) return false; if (messageID != other.messageID) diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionForceConsumerDelivery.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionForceConsumerDelivery.java index add873cbaa..68856270dd 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionForceConsumerDelivery.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionForceConsumerDelivery.java @@ -20,54 +20,46 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; /** - * * A SessionConsumerForceDelivery */ -public class SessionForceConsumerDelivery extends PacketImpl -{ +public class SessionForceConsumerDelivery extends PacketImpl { + private long consumerID; private long sequence; - public SessionForceConsumerDelivery(final long consumerID, final long sequence) - { + public SessionForceConsumerDelivery(final long consumerID, final long sequence) { super(SESS_FORCE_CONSUMER_DELIVERY); this.consumerID = consumerID; this.sequence = sequence; } - public SessionForceConsumerDelivery() - { + public SessionForceConsumerDelivery() { super(SESS_FORCE_CONSUMER_DELIVERY); } - public long getConsumerID() - { + public long getConsumerID() { return consumerID; } - public long getSequence() - { + public long getSequence() { return sequence; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeLong(consumerID); buffer.writeLong(sequence); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { consumerID = buffer.readLong(); sequence = buffer.readLong(); } @Override - public String toString() - { + public String toString() { StringBuffer buf = new StringBuffer(getParentString()); buf.append(", consumerID=" + consumerID); buf.append(", sequence=" + sequence); @@ -76,25 +68,23 @@ public class SessionForceConsumerDelivery extends PacketImpl } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); - result = prime * result + (int)(consumerID ^ (consumerID >>> 32)); - result = prime * result + (int)(sequence ^ (sequence >>> 32)); + result = prime * result + (int) (consumerID ^ (consumerID >>> 32)); + result = prime * result + (int) (sequence ^ (sequence >>> 32)); return result; } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionForceConsumerDelivery)) return false; - SessionForceConsumerDelivery other = (SessionForceConsumerDelivery)obj; + SessionForceConsumerDelivery other = (SessionForceConsumerDelivery) obj; if (consumerID != other.consumerID) return false; if (sequence != other.sequence) diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionIndividualAcknowledgeMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionIndividualAcknowledgeMessage.java index 74b3f81639..6ca5f88672 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionIndividualAcknowledgeMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionIndividualAcknowledgeMessage.java @@ -19,8 +19,7 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class SessionIndividualAcknowledgeMessage extends PacketImpl -{ +public class SessionIndividualAcknowledgeMessage extends PacketImpl { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -35,8 +34,9 @@ public class SessionIndividualAcknowledgeMessage extends PacketImpl // Constructors -------------------------------------------------- - public SessionIndividualAcknowledgeMessage(final long consumerID, final long messageID, final boolean requiresResponse) - { + public SessionIndividualAcknowledgeMessage(final long consumerID, + final long messageID, + final boolean requiresResponse) { super(SESS_INDIVIDUAL_ACKNOWLEDGE); this.consumerID = consumerID; @@ -46,31 +46,26 @@ public class SessionIndividualAcknowledgeMessage extends PacketImpl this.requiresResponse = requiresResponse; } - public SessionIndividualAcknowledgeMessage() - { + public SessionIndividualAcknowledgeMessage() { super(SESS_INDIVIDUAL_ACKNOWLEDGE); } // Public -------------------------------------------------------- - public long getConsumerID() - { + public long getConsumerID() { return consumerID; } - public long getMessageID() - { + public long getMessageID() { return messageID; } - public boolean isRequiresResponse() - { + public boolean isRequiresResponse() { return requiresResponse; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeLong(consumerID); buffer.writeLong(messageID); @@ -79,8 +74,7 @@ public class SessionIndividualAcknowledgeMessage extends PacketImpl } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { consumerID = buffer.readLong(); messageID = buffer.readLong(); @@ -89,26 +83,24 @@ public class SessionIndividualAcknowledgeMessage extends PacketImpl } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); - result = prime * result + (int)(consumerID ^ (consumerID >>> 32)); - result = prime * result + (int)(messageID ^ (messageID >>> 32)); + result = prime * result + (int) (consumerID ^ (consumerID >>> 32)); + result = prime * result + (int) (messageID ^ (messageID >>> 32)); result = prime * result + (requiresResponse ? 1231 : 1237); return result; } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionIndividualAcknowledgeMessage)) return false; - SessionIndividualAcknowledgeMessage other = (SessionIndividualAcknowledgeMessage)obj; + SessionIndividualAcknowledgeMessage other = (SessionIndividualAcknowledgeMessage) obj; if (consumerID != other.consumerID) return false; if (messageID != other.messageID) diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionProducerCreditsFailMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionProducerCreditsFailMessage.java index 64c7d203ae..6e995bae6c 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionProducerCreditsFailMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionProducerCreditsFailMessage.java @@ -20,14 +20,13 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class SessionProducerCreditsFailMessage extends PacketImpl -{ +public class SessionProducerCreditsFailMessage extends PacketImpl { + private int credits; private SimpleString address; - public SessionProducerCreditsFailMessage(final int credits, final SimpleString address) - { + public SessionProducerCreditsFailMessage(final int credits, final SimpleString address) { super(SESS_PRODUCER_FAIL_CREDITS); this.credits = credits; @@ -35,38 +34,32 @@ public class SessionProducerCreditsFailMessage extends PacketImpl this.address = address; } - public SessionProducerCreditsFailMessage() - { + public SessionProducerCreditsFailMessage() { super(SESS_PRODUCER_FAIL_CREDITS); } - public int getCredits() - { + public int getCredits() { return credits; } - public SimpleString getAddress() - { + public SimpleString getAddress() { return address; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeInt(credits); buffer.writeSimpleString(address); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { credits = buffer.readInt(); address = buffer.readSimpleString(); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((address == null) ? 0 : address.hashCode()); @@ -75,17 +68,15 @@ public class SessionProducerCreditsFailMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionProducerCreditsFailMessage)) return false; - SessionProducerCreditsFailMessage other = (SessionProducerCreditsFailMessage)obj; - if (address == null) - { + SessionProducerCreditsFailMessage other = (SessionProducerCreditsFailMessage) obj; + if (address == null) { if (other.address != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionProducerCreditsMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionProducerCreditsMessage.java index b2f009bae9..c2bd339852 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionProducerCreditsMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionProducerCreditsMessage.java @@ -20,14 +20,13 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class SessionProducerCreditsMessage extends PacketImpl -{ +public class SessionProducerCreditsMessage extends PacketImpl { + private int credits; private SimpleString address; - public SessionProducerCreditsMessage(final int credits, final SimpleString address) - { + public SessionProducerCreditsMessage(final int credits, final SimpleString address) { super(SESS_PRODUCER_CREDITS); this.credits = credits; @@ -35,38 +34,32 @@ public class SessionProducerCreditsMessage extends PacketImpl this.address = address; } - public SessionProducerCreditsMessage() - { + public SessionProducerCreditsMessage() { super(SESS_PRODUCER_CREDITS); } - public int getCredits() - { + public int getCredits() { return credits; } - public SimpleString getAddress() - { + public SimpleString getAddress() { return address; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeInt(credits); buffer.writeSimpleString(address); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { credits = buffer.readInt(); address = buffer.readSimpleString(); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((address == null) ? 0 : address.hashCode()); @@ -75,17 +68,15 @@ public class SessionProducerCreditsMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionProducerCreditsMessage)) return false; - SessionProducerCreditsMessage other = (SessionProducerCreditsMessage)obj; - if (address == null) - { + SessionProducerCreditsMessage other = (SessionProducerCreditsMessage) obj; + if (address == null) { if (other.address != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionQueueQueryMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionQueueQueryMessage.java index f885e423f9..df38bf4e38 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionQueueQueryMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionQueueQueryMessage.java @@ -20,42 +20,36 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class SessionQueueQueryMessage extends PacketImpl -{ +public class SessionQueueQueryMessage extends PacketImpl { + private SimpleString queueName; - public SessionQueueQueryMessage(final SimpleString queueName) - { + public SessionQueueQueryMessage(final SimpleString queueName) { super(SESS_QUEUEQUERY); this.queueName = queueName; } - public SessionQueueQueryMessage() - { + public SessionQueueQueryMessage() { super(SESS_QUEUEQUERY); } - public SimpleString getQueueName() - { + public SimpleString getQueueName() { return queueName; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeSimpleString(queueName); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { queueName = buffer.readSimpleString(); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((queueName == null) ? 0 : queueName.hashCode()); @@ -63,17 +57,15 @@ public class SessionQueueQueryMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionQueueQueryMessage)) return false; - SessionQueueQueryMessage other = (SessionQueueQueryMessage)obj; - if (queueName == null) - { + SessionQueueQueryMessage other = (SessionQueueQueryMessage) obj; + if (queueName == null) { if (other.queueName != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionQueueQueryResponseMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionQueueQueryResponseMessage.java index 08f8f903fd..edd7a4ff04 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionQueueQueryResponseMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionQueueQueryResponseMessage.java @@ -23,8 +23,8 @@ import org.apache.activemq.artemis.core.client.impl.QueueQueryImpl; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; import org.apache.activemq.artemis.core.server.QueueQueryResult; -public class SessionQueueQueryResponseMessage extends PacketImpl -{ +public class SessionQueueQueryResponseMessage extends PacketImpl { + protected SimpleString name; protected boolean exists; @@ -41,19 +41,15 @@ public class SessionQueueQueryResponseMessage extends PacketImpl protected boolean temporary; - public SessionQueueQueryResponseMessage(final QueueQueryResult result) - { - this(result.getName(), result.getAddress(), result.isDurable(), result.isTemporary(), - result.getFilterString(), result.getConsumerCount(), result.getMessageCount(), result.isExists()); + public SessionQueueQueryResponseMessage(final QueueQueryResult result) { + this(result.getName(), result.getAddress(), result.isDurable(), result.isTemporary(), result.getFilterString(), result.getConsumerCount(), result.getMessageCount(), result.isExists()); } - public SessionQueueQueryResponseMessage() - { + public SessionQueueQueryResponseMessage() { this(null, null, false, false, null, 0, 0, false); } - public SessionQueueQueryResponseMessage(byte v2) - { + public SessionQueueQueryResponseMessage(byte v2) { super(v2); } @@ -64,8 +60,7 @@ public class SessionQueueQueryResponseMessage extends PacketImpl final SimpleString filterString, final int consumerCount, final long messageCount, - final boolean exists) - { + final boolean exists) { super(SESS_QUEUEQUERY_RESP); this.durable = durable; @@ -86,54 +81,44 @@ public class SessionQueueQueryResponseMessage extends PacketImpl } @Override - public boolean isResponse() - { + public boolean isResponse() { return true; } - public boolean isExists() - { + public boolean isExists() { return exists; } - public boolean isDurable() - { + public boolean isDurable() { return durable; } - public int getConsumerCount() - { + public int getConsumerCount() { return consumerCount; } - public long getMessageCount() - { + public long getMessageCount() { return messageCount; } - public SimpleString getFilterString() - { + public SimpleString getFilterString() { return filterString; } - public SimpleString getAddress() - { + public SimpleString getAddress() { return address; } - public SimpleString getName() - { + public SimpleString getName() { return name; } - public boolean isTemporary() - { + public boolean isTemporary() { return temporary; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeBoolean(exists); buffer.writeBoolean(durable); buffer.writeBoolean(temporary); @@ -145,8 +130,7 @@ public class SessionQueueQueryResponseMessage extends PacketImpl } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { exists = buffer.readBoolean(); durable = buffer.readBoolean(); temporary = buffer.readBoolean(); @@ -158,8 +142,7 @@ public class SessionQueueQueryResponseMessage extends PacketImpl } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((address == null) ? 0 : address.hashCode()); @@ -167,36 +150,26 @@ public class SessionQueueQueryResponseMessage extends PacketImpl result = prime * result + (durable ? 1231 : 1237); result = prime * result + (exists ? 1231 : 1237); result = prime * result + ((filterString == null) ? 0 : filterString.hashCode()); - result = prime * result + (int)(messageCount ^ (messageCount >>> 32)); + result = prime * result + (int) (messageCount ^ (messageCount >>> 32)); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + (temporary ? 1231 : 1237); return result; } - public ClientSession.QueueQuery toQueueQuery() - { - return new QueueQueryImpl(isDurable(), - isTemporary(), - getConsumerCount(), - getMessageCount(), - getFilterString(), - getAddress(), - getName(), - isExists()); + public ClientSession.QueueQuery toQueueQuery() { + return new QueueQueryImpl(isDurable(), isTemporary(), getConsumerCount(), getMessageCount(), getFilterString(), getAddress(), getName(), isExists()); } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionQueueQueryResponseMessage)) return false; - SessionQueueQueryResponseMessage other = (SessionQueueQueryResponseMessage)obj; - if (address == null) - { + SessionQueueQueryResponseMessage other = (SessionQueueQueryResponseMessage) obj; + if (address == null) { if (other.address != null) return false; } @@ -208,8 +181,7 @@ public class SessionQueueQueryResponseMessage extends PacketImpl return false; if (exists != other.exists) return false; - if (filterString == null) - { + if (filterString == null) { if (other.filterString != null) return false; } @@ -217,8 +189,7 @@ public class SessionQueueQueryResponseMessage extends PacketImpl return false; if (messageCount != other.messageCount) return false; - if (name == null) - { + if (name == null) { if (other.name != null) return false; } @@ -229,5 +200,4 @@ public class SessionQueueQueryResponseMessage extends PacketImpl return true; } - } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionQueueQueryResponseMessage_V2.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionQueueQueryResponseMessage_V2.java index 3f78acf09b..c98ac0a073 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionQueueQueryResponseMessage_V2.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionQueueQueryResponseMessage_V2.java @@ -22,18 +22,15 @@ import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.core.client.impl.QueueQueryImpl; import org.apache.activemq.artemis.core.server.QueueQueryResult; -public class SessionQueueQueryResponseMessage_V2 extends SessionQueueQueryResponseMessage -{ +public class SessionQueueQueryResponseMessage_V2 extends SessionQueueQueryResponseMessage { + private boolean autoCreationEnabled; - public SessionQueueQueryResponseMessage_V2(final QueueQueryResult result) - { - this(result.getName(), result.getAddress(), result.isDurable(), result.isTemporary(), - result.getFilterString(), result.getConsumerCount(), result.getMessageCount(), result.isExists(), result.isAutoCreateJmsQueues()); + public SessionQueueQueryResponseMessage_V2(final QueueQueryResult result) { + this(result.getName(), result.getAddress(), result.isDurable(), result.isTemporary(), result.getFilterString(), result.getConsumerCount(), result.getMessageCount(), result.isExists(), result.isAutoCreateJmsQueues()); } - public SessionQueueQueryResponseMessage_V2() - { + public SessionQueueQueryResponseMessage_V2() { this(null, null, false, false, null, 0, 0, false, false); } @@ -45,8 +42,7 @@ public class SessionQueueQueryResponseMessage_V2 extends SessionQueueQueryRespon final int consumerCount, final long messageCount, final boolean exists, - final boolean autoCreationEnabled) - { + final boolean autoCreationEnabled) { super(SESS_QUEUEQUERY_RESP_V2); this.durable = durable; @@ -68,57 +64,43 @@ public class SessionQueueQueryResponseMessage_V2 extends SessionQueueQueryRespon this.autoCreationEnabled = autoCreationEnabled; } - public boolean isAutoCreationEnabled() - { + public boolean isAutoCreationEnabled() { return autoCreationEnabled; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { super.encodeRest(buffer); buffer.writeBoolean(autoCreationEnabled); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { super.decodeRest(buffer); autoCreationEnabled = buffer.readBoolean(); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (autoCreationEnabled ? 1231 : 1237); return result; } - public ClientSession.QueueQuery toQueueQuery() - { - return new QueueQueryImpl(isDurable(), - isTemporary(), - getConsumerCount(), - getMessageCount(), - getFilterString(), - getAddress(), - getName(), - isExists(), - isAutoCreationEnabled()); + public ClientSession.QueueQuery toQueueQuery() { + return new QueueQueryImpl(isDurable(), isTemporary(), getConsumerCount(), getMessageCount(), getFilterString(), getAddress(), getName(), isExists(), isAutoCreationEnabled()); } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionQueueQueryResponseMessage_V2)) return false; - SessionQueueQueryResponseMessage_V2 other = (SessionQueueQueryResponseMessage_V2)obj; + SessionQueueQueryResponseMessage_V2 other = (SessionQueueQueryResponseMessage_V2) obj; if (autoCreationEnabled != other.autoCreationEnabled) return false; return true; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionReceiveClientLargeMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionReceiveClientLargeMessage.java index 3e651dfb0b..66e509c7ee 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionReceiveClientLargeMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionReceiveClientLargeMessage.java @@ -20,18 +20,16 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.client.impl.ClientLargeMessageInternal; import org.apache.activemq.artemis.core.message.impl.MessageInternal; -public class SessionReceiveClientLargeMessage extends SessionReceiveLargeMessage -{ - public SessionReceiveClientLargeMessage(MessageInternal message) - { +public class SessionReceiveClientLargeMessage extends SessionReceiveLargeMessage { + + public SessionReceiveClientLargeMessage(MessageInternal message) { super(message); } @Override - public void decodeRest(ActiveMQBuffer buffer) - { + public void decodeRest(ActiveMQBuffer buffer) { super.decodeRest(buffer); - ((ClientLargeMessageInternal)getLargeMessage()).setLargeMessageSize(getLargeMessageSize()); + ((ClientLargeMessageInternal) getLargeMessage()).setLargeMessageSize(getLargeMessageSize()); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionReceiveContinuationMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionReceiveContinuationMessage.java index 8a7d49b78a..7ed680acae 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionReceiveContinuationMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionReceiveContinuationMessage.java @@ -19,8 +19,7 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.utils.DataConstants; -public class SessionReceiveContinuationMessage extends SessionContinuationMessage -{ +public class SessionReceiveContinuationMessage extends SessionContinuationMessage { // Constants ----------------------------------------------------- @@ -34,8 +33,7 @@ public class SessionReceiveContinuationMessage extends SessionContinuationMessag // Constructors -------------------------------------------------- - public SessionReceiveContinuationMessage() - { + public SessionReceiveContinuationMessage() { super(SESS_RECEIVE_CONTINUATION); } @@ -48,8 +46,7 @@ public class SessionReceiveContinuationMessage extends SessionContinuationMessag public SessionReceiveContinuationMessage(final long consumerID, final byte[] body, final boolean continues, - final boolean requiresResponse) - { + final boolean requiresResponse) { super(SESS_RECEIVE_CONTINUATION, body, continues); this.consumerID = consumerID; } @@ -58,8 +55,7 @@ public class SessionReceiveContinuationMessage extends SessionContinuationMessag final byte[] body, final boolean continues, final boolean requiresResponse, - final int packetSize) - { + final int packetSize) { this(consumerID, body, continues, requiresResponse); this.size = packetSize; } @@ -67,61 +63,52 @@ public class SessionReceiveContinuationMessage extends SessionContinuationMessag /** * @return the consumerID */ - public long getConsumerID() - { + public long getConsumerID() { return consumerID; } // Public -------------------------------------------------------- @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { super.encodeRest(buffer); buffer.writeLong(consumerID); } + @Override - public int getPacketSize() - { - if (size == -1) - { + public int getPacketSize() { + if (size == -1) { // This packet was created by the LargeMessageController return 0; } - else - { + else { return size; } } - - @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { super.decodeRest(buffer); consumerID = buffer.readLong(); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); - result = prime * result + (int)(consumerID ^ (consumerID >>> 32)); + result = prime * result + (int) (consumerID ^ (consumerID >>> 32)); return result; } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionReceiveContinuationMessage)) return false; - SessionReceiveContinuationMessage other = (SessionReceiveContinuationMessage)obj; + SessionReceiveContinuationMessage other = (SessionReceiveContinuationMessage) obj; if (consumerID != other.consumerID) return false; return true; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionReceiveLargeMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionReceiveLargeMessage.java index 556f6988a3..460cd237ba 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionReceiveLargeMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionReceiveLargeMessage.java @@ -20,11 +20,13 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.message.impl.MessageInternal; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class SessionReceiveLargeMessage extends PacketImpl -{ +public class SessionReceiveLargeMessage extends PacketImpl { + private final MessageInternal message; - /** Since we receive the message before the entire message was received, */ + /** + * Since we receive the message before the entire message was received, + */ private long largeMessageSize; private long consumerID; @@ -32,8 +34,7 @@ public class SessionReceiveLargeMessage extends PacketImpl private int deliveryCount; // To be used on decoding at the client while receiving a large message - public SessionReceiveLargeMessage(final MessageInternal message) - { + public SessionReceiveLargeMessage(final MessageInternal message) { super(SESS_RECEIVE_LARGE_MSG); this.message = message; } @@ -41,8 +42,7 @@ public class SessionReceiveLargeMessage extends PacketImpl public SessionReceiveLargeMessage(final long consumerID, final MessageInternal message, final long largeMessageSize, - final int deliveryCount) - { + final int deliveryCount) { super(SESS_RECEIVE_LARGE_MSG); this.consumerID = consumerID; @@ -54,32 +54,27 @@ public class SessionReceiveLargeMessage extends PacketImpl this.largeMessageSize = largeMessageSize; } - public MessageInternal getLargeMessage() - { + public MessageInternal getLargeMessage() { return message; } - public long getConsumerID() - { + public long getConsumerID() { return consumerID; } - public int getDeliveryCount() - { + public int getDeliveryCount() { return deliveryCount; } /** * @return the largeMessageSize */ - public long getLargeMessageSize() - { + public long getLargeMessageSize() { return largeMessageSize; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeLong(consumerID); buffer.writeInt(deliveryCount); buffer.writeLong(largeMessageSize); @@ -87,8 +82,7 @@ public class SessionReceiveLargeMessage extends PacketImpl } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { consumerID = buffer.readLong(); deliveryCount = buffer.readInt(); largeMessageSize = buffer.readLong(); @@ -96,35 +90,32 @@ public class SessionReceiveLargeMessage extends PacketImpl } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); - result = prime * result + (int)(consumerID ^ (consumerID >>> 32)); + result = prime * result + (int) (consumerID ^ (consumerID >>> 32)); result = prime * result + deliveryCount; - result = prime * result + (int)(largeMessageSize ^ (largeMessageSize >>> 32)); + result = prime * result + (int) (largeMessageSize ^ (largeMessageSize >>> 32)); result = prime * result + ((message == null) ? 0 : message.hashCode()); return result; } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionReceiveLargeMessage)) return false; - SessionReceiveLargeMessage other = (SessionReceiveLargeMessage)obj; + SessionReceiveLargeMessage other = (SessionReceiveLargeMessage) obj; if (consumerID != other.consumerID) return false; if (deliveryCount != other.deliveryCount) return false; if (largeMessageSize != other.largeMessageSize) return false; - if (message == null) - { + if (message == null) { if (other.message != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionReceiveMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionReceiveMessage.java index 2171349267..83fe33c907 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionReceiveMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionReceiveMessage.java @@ -21,8 +21,7 @@ import org.apache.activemq.artemis.core.message.impl.MessageInternal; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; import org.apache.activemq.artemis.utils.DataConstants; -public class SessionReceiveMessage extends MessagePacket -{ +public class SessionReceiveMessage extends MessagePacket { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -31,8 +30,7 @@ public class SessionReceiveMessage extends MessagePacket private int deliveryCount; - public SessionReceiveMessage(final long consumerID, final MessageInternal message, final int deliveryCount) - { + public SessionReceiveMessage(final long consumerID, final MessageInternal message, final int deliveryCount) { super(SESS_RECEIVE_MSG, message); this.consumerID = consumerID; @@ -40,31 +38,26 @@ public class SessionReceiveMessage extends MessagePacket this.deliveryCount = deliveryCount; } - public SessionReceiveMessage(final MessageInternal message) - { + public SessionReceiveMessage(final MessageInternal message) { super(SESS_RECEIVE_MSG, message); } // Public -------------------------------------------------------- - public long getConsumerID() - { + public long getConsumerID() { return consumerID; } - public int getDeliveryCount() - { + public int getDeliveryCount() { return deliveryCount; } @Override - public ActiveMQBuffer encode(final RemotingConnection connection) - { + public ActiveMQBuffer encode(final RemotingConnection connection) { ActiveMQBuffer buffer = message.getEncodedBuffer(); // Sanity check - if (buffer.writerIndex() != message.getEndOfMessagePosition()) - { + if (buffer.writerIndex() != message.getEndOfMessagePosition()) { throw new IllegalStateException("Wrong encode position"); } @@ -87,8 +80,7 @@ public class SessionReceiveMessage extends MessagePacket } @Override - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { channelID = buffer.readLong(); message.decodeFromBuffer(buffer); @@ -105,25 +97,23 @@ public class SessionReceiveMessage extends MessagePacket } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); - result = prime * result + (int)(consumerID ^ (consumerID >>> 32)); + result = prime * result + (int) (consumerID ^ (consumerID >>> 32)); result = prime * result + deliveryCount; return result; } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionReceiveMessage)) return false; - SessionReceiveMessage other = (SessionReceiveMessage)obj; + SessionReceiveMessage other = (SessionReceiveMessage) obj; if (consumerID != other.consumerID) return false; if (deliveryCount != other.deliveryCount) diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionRequestProducerCreditsMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionRequestProducerCreditsMessage.java index 7de5d41580..10fcd630bb 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionRequestProducerCreditsMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionRequestProducerCreditsMessage.java @@ -20,14 +20,13 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class SessionRequestProducerCreditsMessage extends PacketImpl -{ +public class SessionRequestProducerCreditsMessage extends PacketImpl { + private int credits; private SimpleString address; - public SessionRequestProducerCreditsMessage(final int credits, final SimpleString address) - { + public SessionRequestProducerCreditsMessage(final int credits, final SimpleString address) { super(SESS_PRODUCER_REQUEST_CREDITS); this.credits = credits; @@ -35,20 +34,17 @@ public class SessionRequestProducerCreditsMessage extends PacketImpl this.address = address; } - public SessionRequestProducerCreditsMessage() - { + public SessionRequestProducerCreditsMessage() { super(SESS_PRODUCER_REQUEST_CREDITS); } // Public -------------------------------------------------------- - public int getCredits() - { + public int getCredits() { return credits; } - public SimpleString getAddress() - { + public SimpleString getAddress() { return address; } @@ -58,22 +54,19 @@ public class SessionRequestProducerCreditsMessage extends PacketImpl // } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeInt(credits); buffer.writeSimpleString(address); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { credits = buffer.readInt(); address = buffer.readSimpleString(); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((address == null) ? 0 : address.hashCode()); @@ -82,17 +75,15 @@ public class SessionRequestProducerCreditsMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionRequestProducerCreditsMessage)) return false; - SessionRequestProducerCreditsMessage other = (SessionRequestProducerCreditsMessage)obj; - if (address == null) - { + SessionRequestProducerCreditsMessage other = (SessionRequestProducerCreditsMessage) obj; + if (address == null) { if (other.address != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionSendContinuationMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionSendContinuationMessage.java index fd8d50d07c..761b961434 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionSendContinuationMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionSendContinuationMessage.java @@ -23,8 +23,8 @@ import org.apache.activemq.artemis.core.message.impl.MessageInternal; /** * A SessionSendContinuationMessage
*/ -public class SessionSendContinuationMessage extends SessionContinuationMessage -{ +public class SessionSendContinuationMessage extends SessionContinuationMessage { + private boolean requiresResponse; // Used on confirmation handling @@ -48,8 +48,7 @@ public class SessionSendContinuationMessage extends SessionContinuationMessage // Constructors -------------------------------------------------- - public SessionSendContinuationMessage() - { + public SessionSendContinuationMessage() { super(SESS_SEND_CONTINUATION); handler = null; } @@ -59,10 +58,12 @@ public class SessionSendContinuationMessage extends SessionContinuationMessage * @param continues * @param requiresResponse */ - public SessionSendContinuationMessage(final MessageInternal message, final byte[] body, final boolean continues, - final boolean requiresResponse, final long messageBodySize, - SendAcknowledgementHandler handler) - { + public SessionSendContinuationMessage(final MessageInternal message, + final byte[] body, + final boolean continues, + final boolean requiresResponse, + final long messageBodySize, + SendAcknowledgementHandler handler) { super(SESS_SEND_CONTINUATION, body, continues); this.requiresResponse = requiresResponse; this.message = message; @@ -75,50 +76,41 @@ public class SessionSendContinuationMessage extends SessionContinuationMessage /** * @return the requiresResponse */ - public boolean isRequiresResponse() - { + public boolean isRequiresResponse() { return requiresResponse; } - public long getMessageBodySize() - { + public long getMessageBodySize() { return messageBodySize; } - /** * @return the message */ - public MessageInternal getMessage() - { + public MessageInternal getMessage() { return message; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { super.encodeRest(buffer); - if (!continues) - { + if (!continues) { buffer.writeLong(messageBodySize); } buffer.writeBoolean(requiresResponse); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { super.decodeRest(buffer); - if (!continues) - { + if (!continues) { messageBodySize = buffer.readLong(); } requiresResponse = buffer.readBoolean(); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((message == null) ? 0 : message.hashCode()); @@ -128,8 +120,7 @@ public class SessionSendContinuationMessage extends SessionContinuationMessage } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) @@ -137,8 +128,7 @@ public class SessionSendContinuationMessage extends SessionContinuationMessage if (!(obj instanceof SessionSendContinuationMessage)) return false; SessionSendContinuationMessage other = (SessionSendContinuationMessage) obj; - if (message == null) - { + if (message == null) { if (other.message != null) return false; } @@ -151,8 +141,7 @@ public class SessionSendContinuationMessage extends SessionContinuationMessage return true; } - public SendAcknowledgementHandler getHandler() - { + public SendAcknowledgementHandler getHandler() { return handler; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionSendLargeMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionSendLargeMessage.java index aeac5e8434..1bf9bbb026 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionSendLargeMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionSendLargeMessage.java @@ -20,19 +20,18 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.message.impl.MessageInternal; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class SessionSendLargeMessage extends PacketImpl -{ +public class SessionSendLargeMessage extends PacketImpl { - - /** Used only if largeMessage */ + /** + * Used only if largeMessage + */ private final MessageInternal largeMessage; // Static -------------------------------------------------------- // Constructors -------------------------------------------------- - public SessionSendLargeMessage(final MessageInternal largeMessage) - { + public SessionSendLargeMessage(final MessageInternal largeMessage) { super(SESS_SEND_LARGE); this.largeMessage = largeMessage; @@ -40,26 +39,22 @@ public class SessionSendLargeMessage extends PacketImpl // Public -------------------------------------------------------- - public MessageInternal getLargeMessage() - { + public MessageInternal getLargeMessage() { return largeMessage; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { largeMessage.encodeHeadersAndProperties(buffer); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { largeMessage.decodeHeadersAndProperties(buffer); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((largeMessage == null) ? 0 : largeMessage.hashCode()); @@ -67,17 +62,15 @@ public class SessionSendLargeMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionSendLargeMessage)) return false; - SessionSendLargeMessage other = (SessionSendLargeMessage)obj; - if (largeMessage == null) - { + SessionSendLargeMessage other = (SessionSendLargeMessage) obj; + if (largeMessage == null) { if (other.largeMessage != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionSendMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionSendMessage.java index f0fd112a91..525f00a9cb 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionSendMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionSendMessage.java @@ -22,8 +22,7 @@ import org.apache.activemq.artemis.core.message.impl.MessageInternal; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; import org.apache.activemq.artemis.utils.DataConstants; -public class SessionSendMessage extends MessagePacket -{ +public class SessionSendMessage extends MessagePacket { private boolean requiresResponse; @@ -37,40 +36,35 @@ public class SessionSendMessage extends MessagePacket */ private final transient SendAcknowledgementHandler handler; - public SessionSendMessage(final MessageInternal message, final boolean requiresResponse, - final SendAcknowledgementHandler handler) - { + public SessionSendMessage(final MessageInternal message, + final boolean requiresResponse, + final SendAcknowledgementHandler handler) { super(SESS_SEND, message); this.handler = handler; this.requiresResponse = requiresResponse; } - public SessionSendMessage(final MessageInternal message) - { + public SessionSendMessage(final MessageInternal message) { super(SESS_SEND, message); this.handler = null; } // Public -------------------------------------------------------- - public boolean isRequiresResponse() - { + public boolean isRequiresResponse() { return requiresResponse; } - public SendAcknowledgementHandler getHandler() - { + public SendAcknowledgementHandler getHandler() { return handler; } @Override - public ActiveMQBuffer encode(final RemotingConnection connection) - { + public ActiveMQBuffer encode(final RemotingConnection connection) { ActiveMQBuffer buffer = message.getEncodedBuffer(); // Sanity check - if (buffer.writerIndex() != message.getEndOfMessagePosition()) - { + if (buffer.writerIndex() != message.getEndOfMessagePosition()) { throw new IllegalStateException("Wrong encode position"); } @@ -94,8 +88,7 @@ public class SessionSendMessage extends MessagePacket } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { // Buffer comes in after having read standard headers and positioned at Beginning of body part message.decodeFromBuffer(buffer); @@ -109,8 +102,7 @@ public class SessionSendMessage extends MessagePacket } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (requiresResponse ? 1231 : 1237); @@ -118,8 +110,7 @@ public class SessionSendMessage extends MessagePacket } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionUniqueAddMetaDataMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionUniqueAddMetaDataMessage.java index ebe1afe879..e367a8a8bc 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionUniqueAddMetaDataMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionUniqueAddMetaDataMessage.java @@ -16,9 +16,7 @@ */ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; - -public class SessionUniqueAddMetaDataMessage extends SessionAddMetaDataMessageV2 -{ +public class SessionUniqueAddMetaDataMessage extends SessionAddMetaDataMessageV2 { // Constants ----------------------------------------------------- @@ -28,14 +26,11 @@ public class SessionUniqueAddMetaDataMessage extends SessionAddMetaDataMessageV2 // Constructors -------------------------------------------------- - public SessionUniqueAddMetaDataMessage() - { + public SessionUniqueAddMetaDataMessage() { super(SESS_UNIQUE_ADD_METADATA); } - - public SessionUniqueAddMetaDataMessage(String key, String data) - { + public SessionUniqueAddMetaDataMessage(String key, String data) { super(SESS_UNIQUE_ADD_METADATA, key, data); } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAAfterFailedMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAAfterFailedMessage.java index de6759bf19..13700b570c 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAAfterFailedMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAAfterFailedMessage.java @@ -25,8 +25,7 @@ import org.apache.activemq.artemis.utils.XidCodecSupport; /** * to be called after a failure on an XA Session */ -public class SessionXAAfterFailedMessage extends PacketImpl -{ +public class SessionXAAfterFailedMessage extends PacketImpl { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -37,40 +36,34 @@ public class SessionXAAfterFailedMessage extends PacketImpl // Constructors -------------------------------------------------- - public SessionXAAfterFailedMessage(final Xid xid) - { + public SessionXAAfterFailedMessage(final Xid xid) { super(SESS_XA_FAILED); this.xid = xid; } - public SessionXAAfterFailedMessage() - { + public SessionXAAfterFailedMessage() { super(SESS_XA_FAILED); } // Public -------------------------------------------------------- - public Xid getXid() - { + public Xid getXid() { return xid; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { XidCodecSupport.encodeXid(xid, buffer); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { xid = XidCodecSupport.decodeXid(buffer); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((xid == null) ? 0 : xid.hashCode()); @@ -78,17 +71,15 @@ public class SessionXAAfterFailedMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionXAAfterFailedMessage)) return false; - SessionXAAfterFailedMessage other = (SessionXAAfterFailedMessage)obj; - if (xid == null) - { + SessionXAAfterFailedMessage other = (SessionXAAfterFailedMessage) obj; + if (xid == null) { if (other.xid != null) return false; } @@ -97,5 +88,4 @@ public class SessionXAAfterFailedMessage extends PacketImpl return true; } - } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXACommitMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXACommitMessage.java index 7e8198d989..1e1ad764ee 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXACommitMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXACommitMessage.java @@ -22,58 +22,50 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; import org.apache.activemq.artemis.utils.XidCodecSupport; -public class SessionXACommitMessage extends PacketImpl -{ +public class SessionXACommitMessage extends PacketImpl { + private boolean onePhase; private Xid xid; - public SessionXACommitMessage(final Xid xid, final boolean onePhase) - { + public SessionXACommitMessage(final Xid xid, final boolean onePhase) { super(SESS_XA_COMMIT); this.xid = xid; this.onePhase = onePhase; } - public SessionXACommitMessage() - { + public SessionXACommitMessage() { super(SESS_XA_COMMIT); } - public Xid getXid() - { + public Xid getXid() { return xid; } - public boolean isOnePhase() - { + public boolean isOnePhase() { return onePhase; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { XidCodecSupport.encodeXid(xid, buffer); buffer.writeBoolean(onePhase); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { xid = XidCodecSupport.decodeXid(buffer); onePhase = buffer.readBoolean(); } @Override - public String toString() - { + public String toString() { return getParentString() + ", xid=" + xid + ", onePhase=" + onePhase + "]"; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (onePhase ? 1231 : 1237); @@ -82,19 +74,17 @@ public class SessionXACommitMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionXACommitMessage)) return false; - SessionXACommitMessage other = (SessionXACommitMessage)obj; + SessionXACommitMessage other = (SessionXACommitMessage) obj; if (onePhase != other.onePhase) return false; - if (xid == null) - { + if (xid == null) { if (other.xid != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAEndMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAEndMessage.java index 3047df2592..5e99eb9eb1 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAEndMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAEndMessage.java @@ -22,14 +22,13 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; import org.apache.activemq.artemis.utils.XidCodecSupport; -public class SessionXAEndMessage extends PacketImpl -{ +public class SessionXAEndMessage extends PacketImpl { + private Xid xid; private boolean failed; - public SessionXAEndMessage(final Xid xid, final boolean failed) - { + public SessionXAEndMessage(final Xid xid, final boolean failed) { super(SESS_XA_END); this.xid = xid; @@ -37,44 +36,37 @@ public class SessionXAEndMessage extends PacketImpl this.failed = failed; } - public SessionXAEndMessage() - { + public SessionXAEndMessage() { super(SESS_XA_END); } - public boolean isFailed() - { + public boolean isFailed() { return failed; } - public Xid getXid() - { + public Xid getXid() { return xid; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { XidCodecSupport.encodeXid(xid, buffer); buffer.writeBoolean(failed); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { xid = XidCodecSupport.decodeXid(buffer); failed = buffer.readBoolean(); } @Override - public String toString() - { + public String toString() { return getParentString() + ", xid=" + xid + ", failed=" + failed + "]"; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (failed ? 1231 : 1237); @@ -83,19 +75,17 @@ public class SessionXAEndMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionXAEndMessage)) return false; - SessionXAEndMessage other = (SessionXAEndMessage)obj; + SessionXAEndMessage other = (SessionXAEndMessage) obj; if (failed != other.failed) return false; - if (xid == null) - { + if (xid == null) { if (other.xid != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAForgetMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAForgetMessage.java index 41d14f37b1..2f88745620 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAForgetMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAForgetMessage.java @@ -22,42 +22,36 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; import org.apache.activemq.artemis.utils.XidCodecSupport; -public class SessionXAForgetMessage extends PacketImpl -{ +public class SessionXAForgetMessage extends PacketImpl { private Xid xid; - public SessionXAForgetMessage(final Xid xid) - { + + public SessionXAForgetMessage(final Xid xid) { super(SESS_XA_FORGET); this.xid = xid; } - public SessionXAForgetMessage() - { + public SessionXAForgetMessage() { super(SESS_XA_FORGET); } - public Xid getXid() - { + public Xid getXid() { return xid; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { XidCodecSupport.encodeXid(xid, buffer); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { xid = XidCodecSupport.decodeXid(buffer); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((xid == null) ? 0 : xid.hashCode()); @@ -65,17 +59,15 @@ public class SessionXAForgetMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionXAForgetMessage)) return false; - SessionXAForgetMessage other = (SessionXAForgetMessage)obj; - if (xid == null) - { + SessionXAForgetMessage other = (SessionXAForgetMessage) obj; + if (xid == null) { if (other.xid != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAGetInDoubtXidsResponseMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAGetInDoubtXidsResponseMessage.java index 1d18d6daf0..92260b136b 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAGetInDoubtXidsResponseMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAGetInDoubtXidsResponseMessage.java @@ -25,51 +25,43 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; import org.apache.activemq.artemis.utils.XidCodecSupport; -public class SessionXAGetInDoubtXidsResponseMessage extends PacketImpl -{ +public class SessionXAGetInDoubtXidsResponseMessage extends PacketImpl { + private List xids; - public SessionXAGetInDoubtXidsResponseMessage(final List xids) - { + public SessionXAGetInDoubtXidsResponseMessage(final List xids) { super(SESS_XA_INDOUBT_XIDS_RESP); this.xids = xids; } - public SessionXAGetInDoubtXidsResponseMessage() - { + public SessionXAGetInDoubtXidsResponseMessage() { super(SESS_XA_INDOUBT_XIDS_RESP); } @Override - public boolean isResponse() - { + public boolean isResponse() { return true; } - public List getXids() - { + public List getXids() { return xids; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeInt(xids.size()); - for (Xid xid : xids) - { + for (Xid xid : xids) { XidCodecSupport.encodeXid(xid, buffer); } } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { int len = buffer.readInt(); xids = new ArrayList(len); - for (int i = 0; i < len; i++) - { + for (int i = 0; i < len; i++) { Xid xid = XidCodecSupport.decodeXid(buffer); xids.add(xid); @@ -77,8 +69,7 @@ public class SessionXAGetInDoubtXidsResponseMessage extends PacketImpl } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((xids == null) ? 0 : xids.hashCode()); @@ -86,17 +77,15 @@ public class SessionXAGetInDoubtXidsResponseMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionXAGetInDoubtXidsResponseMessage)) return false; - SessionXAGetInDoubtXidsResponseMessage other = (SessionXAGetInDoubtXidsResponseMessage)obj; - if (xids == null) - { + SessionXAGetInDoubtXidsResponseMessage other = (SessionXAGetInDoubtXidsResponseMessage) obj; + if (xids == null) { if (other.xids != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAGetTimeoutResponseMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAGetTimeoutResponseMessage.java index f0537fff23..7f12ec63e5 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAGetTimeoutResponseMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAGetTimeoutResponseMessage.java @@ -19,48 +19,41 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class SessionXAGetTimeoutResponseMessage extends PacketImpl -{ +public class SessionXAGetTimeoutResponseMessage extends PacketImpl { + private int timeoutSeconds; - public SessionXAGetTimeoutResponseMessage(final int timeoutSeconds) - { + public SessionXAGetTimeoutResponseMessage(final int timeoutSeconds) { super(SESS_XA_GET_TIMEOUT_RESP); this.timeoutSeconds = timeoutSeconds; } - public SessionXAGetTimeoutResponseMessage() - { + public SessionXAGetTimeoutResponseMessage() { super(SESS_XA_GET_TIMEOUT_RESP); } @Override - public boolean isResponse() - { + public boolean isResponse() { return true; } - public int getTimeoutSeconds() - { + public int getTimeoutSeconds() { return timeoutSeconds; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeInt(timeoutSeconds); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { timeoutSeconds = buffer.readInt(); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + timeoutSeconds; @@ -68,15 +61,14 @@ public class SessionXAGetTimeoutResponseMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionXAGetTimeoutResponseMessage)) return false; - SessionXAGetTimeoutResponseMessage other = (SessionXAGetTimeoutResponseMessage)obj; + SessionXAGetTimeoutResponseMessage other = (SessionXAGetTimeoutResponseMessage) obj; if (timeoutSeconds != other.timeoutSeconds) return false; return true; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAJoinMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAJoinMessage.java index 8b7844b672..dde0dfbdbb 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAJoinMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAJoinMessage.java @@ -22,42 +22,36 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; import org.apache.activemq.artemis.utils.XidCodecSupport; -public class SessionXAJoinMessage extends PacketImpl -{ +public class SessionXAJoinMessage extends PacketImpl { + private Xid xid; - public SessionXAJoinMessage(final Xid xid) - { + public SessionXAJoinMessage(final Xid xid) { super(SESS_XA_JOIN); this.xid = xid; } - public SessionXAJoinMessage() - { + public SessionXAJoinMessage() { super(SESS_XA_JOIN); } - public Xid getXid() - { + public Xid getXid() { return xid; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { XidCodecSupport.encodeXid(xid, buffer); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { xid = XidCodecSupport.decodeXid(buffer); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((xid == null) ? 0 : xid.hashCode()); @@ -65,17 +59,15 @@ public class SessionXAJoinMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionXAJoinMessage)) return false; - SessionXAJoinMessage other = (SessionXAJoinMessage)obj; - if (xid == null) - { + SessionXAJoinMessage other = (SessionXAJoinMessage) obj; + if (xid == null) { if (other.xid != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAPrepareMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAPrepareMessage.java index 2da03baf1d..948c6dbdb0 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAPrepareMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAPrepareMessage.java @@ -22,44 +22,36 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; import org.apache.activemq.artemis.utils.XidCodecSupport; -public class SessionXAPrepareMessage extends PacketImpl -{ +public class SessionXAPrepareMessage extends PacketImpl { private Xid xid; - public SessionXAPrepareMessage(final Xid xid) - { + public SessionXAPrepareMessage(final Xid xid) { super(SESS_XA_PREPARE); this.xid = xid; } - public SessionXAPrepareMessage() - { + public SessionXAPrepareMessage() { super(SESS_XA_PREPARE); } - - public Xid getXid() - { + public Xid getXid() { return xid; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { XidCodecSupport.encodeXid(xid, buffer); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { xid = XidCodecSupport.decodeXid(buffer); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((xid == null) ? 0 : xid.hashCode()); @@ -67,17 +59,15 @@ public class SessionXAPrepareMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionXAPrepareMessage)) return false; - SessionXAPrepareMessage other = (SessionXAPrepareMessage)obj; - if (xid == null) - { + SessionXAPrepareMessage other = (SessionXAPrepareMessage) obj; + if (xid == null) { if (other.xid != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAResponseMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAResponseMessage.java index 05906efdcd..d19035b550 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAResponseMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAResponseMessage.java @@ -19,16 +19,15 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class SessionXAResponseMessage extends PacketImpl -{ +public class SessionXAResponseMessage extends PacketImpl { + private boolean error; private int responseCode; private String message; - public SessionXAResponseMessage(final boolean isError, final int responseCode, final String message) - { + public SessionXAResponseMessage(final boolean isError, final int responseCode, final String message) { super(SESS_XA_RESP); error = isError; @@ -38,53 +37,45 @@ public class SessionXAResponseMessage extends PacketImpl this.message = message; } - public SessionXAResponseMessage() - { + public SessionXAResponseMessage() { super(SESS_XA_RESP); } // Public -------------------------------------------------------- @Override - public boolean isResponse() - { + public boolean isResponse() { return true; } - public boolean isError() - { + public boolean isError() { return error; } - public int getResponseCode() - { + public int getResponseCode() { return responseCode; } - public String getMessage() - { + public String getMessage() { return message; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeBoolean(error); buffer.writeInt(responseCode); buffer.writeNullableString(message); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { error = buffer.readBoolean(); responseCode = buffer.readInt(); message = buffer.readNullableString(); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (error ? 1231 : 1237); @@ -94,19 +85,17 @@ public class SessionXAResponseMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionXAResponseMessage)) return false; - SessionXAResponseMessage other = (SessionXAResponseMessage)obj; + SessionXAResponseMessage other = (SessionXAResponseMessage) obj; if (error != other.error) return false; - if (message == null) - { + if (message == null) { if (other.message != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAResumeMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAResumeMessage.java index 6055f8f860..dbb6eb05b3 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAResumeMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAResumeMessage.java @@ -22,45 +22,38 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; import org.apache.activemq.artemis.utils.XidCodecSupport; -public class SessionXAResumeMessage extends PacketImpl -{ +public class SessionXAResumeMessage extends PacketImpl { private Xid xid; - public SessionXAResumeMessage(final Xid xid) - { + public SessionXAResumeMessage(final Xid xid) { super(SESS_XA_RESUME); this.xid = xid; } - public SessionXAResumeMessage() - { + public SessionXAResumeMessage() { super(SESS_XA_RESUME); } // Public -------------------------------------------------------- - public Xid getXid() - { + public Xid getXid() { return xid; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { XidCodecSupport.encodeXid(xid, buffer); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { xid = XidCodecSupport.decodeXid(buffer); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((xid == null) ? 0 : xid.hashCode()); @@ -68,17 +61,15 @@ public class SessionXAResumeMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionXAResumeMessage)) return false; - SessionXAResumeMessage other = (SessionXAResumeMessage)obj; - if (xid == null) - { + SessionXAResumeMessage other = (SessionXAResumeMessage) obj; + if (xid == null) { if (other.xid != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXARollbackMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXARollbackMessage.java index ed40eb0c61..e7e337f22b 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXARollbackMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXARollbackMessage.java @@ -22,45 +22,38 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; import org.apache.activemq.artemis.utils.XidCodecSupport; -public class SessionXARollbackMessage extends PacketImpl -{ +public class SessionXARollbackMessage extends PacketImpl { + private Xid xid; - public SessionXARollbackMessage(final Xid xid) - { + public SessionXARollbackMessage(final Xid xid) { super(SESS_XA_ROLLBACK); this.xid = xid; } - public SessionXARollbackMessage() - { + public SessionXARollbackMessage() { super(SESS_XA_ROLLBACK); } // Public -------------------------------------------------------- - public Xid getXid() - { + public Xid getXid() { return xid; } - @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { XidCodecSupport.encodeXid(xid, buffer); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { xid = XidCodecSupport.decodeXid(buffer); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((xid == null) ? 0 : xid.hashCode()); @@ -68,17 +61,15 @@ public class SessionXARollbackMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionXARollbackMessage)) return false; - SessionXARollbackMessage other = (SessionXARollbackMessage)obj; - if (xid == null) - { + SessionXARollbackMessage other = (SessionXARollbackMessage) obj; + if (xid == null) { if (other.xid != null) return false; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXASetTimeoutMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXASetTimeoutMessage.java index 5e1f063460..ff5d72e9a4 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXASetTimeoutMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXASetTimeoutMessage.java @@ -19,44 +19,38 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class SessionXASetTimeoutMessage extends PacketImpl -{ +public class SessionXASetTimeoutMessage extends PacketImpl { + private int timeoutSeconds; - public SessionXASetTimeoutMessage(final int timeoutSeconds) - { + public SessionXASetTimeoutMessage(final int timeoutSeconds) { super(SESS_XA_SET_TIMEOUT); this.timeoutSeconds = timeoutSeconds; } - public SessionXASetTimeoutMessage() - { + public SessionXASetTimeoutMessage() { super(SESS_XA_SET_TIMEOUT); } // Public -------------------------------------------------------- - public int getTimeoutSeconds() - { + public int getTimeoutSeconds() { return timeoutSeconds; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeInt(timeoutSeconds); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { timeoutSeconds = buffer.readInt(); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + timeoutSeconds; @@ -64,15 +58,14 @@ public class SessionXASetTimeoutMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionXASetTimeoutMessage)) return false; - SessionXASetTimeoutMessage other = (SessionXASetTimeoutMessage)obj; + SessionXASetTimeoutMessage other = (SessionXASetTimeoutMessage) obj; if (timeoutSeconds != other.timeoutSeconds) return false; return true; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXASetTimeoutResponseMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXASetTimeoutResponseMessage.java index f9d90a735d..cc84c433e7 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXASetTimeoutResponseMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXASetTimeoutResponseMessage.java @@ -19,50 +19,43 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class SessionXASetTimeoutResponseMessage extends PacketImpl -{ +public class SessionXASetTimeoutResponseMessage extends PacketImpl { + private boolean ok; - public SessionXASetTimeoutResponseMessage(final boolean ok) - { + public SessionXASetTimeoutResponseMessage(final boolean ok) { super(SESS_XA_SET_TIMEOUT_RESP); this.ok = ok; } - public SessionXASetTimeoutResponseMessage() - { + public SessionXASetTimeoutResponseMessage() { super(SESS_XA_SET_TIMEOUT_RESP); } // Public -------------------------------------------------------- @Override - public boolean isResponse() - { + public boolean isResponse() { return true; } - public boolean isOK() - { + public boolean isOK() { return ok; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeBoolean(ok); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { ok = buffer.readBoolean(); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (ok ? 1231 : 1237); @@ -70,15 +63,14 @@ public class SessionXASetTimeoutResponseMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionXASetTimeoutResponseMessage)) return false; - SessionXASetTimeoutResponseMessage other = (SessionXASetTimeoutResponseMessage)obj; + SessionXASetTimeoutResponseMessage other = (SessionXASetTimeoutResponseMessage) obj; if (ok != other.ok) return false; return true; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAStartMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAStartMessage.java index 2d38a03b16..68b37c3372 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAStartMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionXAStartMessage.java @@ -22,8 +22,7 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; import org.apache.activemq.artemis.utils.XidCodecSupport; -public class SessionXAStartMessage extends PacketImpl -{ +public class SessionXAStartMessage extends PacketImpl { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -34,40 +33,34 @@ public class SessionXAStartMessage extends PacketImpl // Constructors -------------------------------------------------- - public SessionXAStartMessage(final Xid xid) - { + public SessionXAStartMessage(final Xid xid) { super(SESS_XA_START); this.xid = xid; } - public SessionXAStartMessage() - { + public SessionXAStartMessage() { super(SESS_XA_START); } // Public -------------------------------------------------------- - public Xid getXid() - { + public Xid getXid() { return xid; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { XidCodecSupport.encodeXid(xid, buffer); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { xid = XidCodecSupport.decodeXid(buffer); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((xid == null) ? 0 : xid.hashCode()); @@ -75,17 +68,15 @@ public class SessionXAStartMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SessionXAStartMessage)) return false; - SessionXAStartMessage other = (SessionXAStartMessage)obj; - if (xid == null) - { + SessionXAStartMessage other = (SessionXAStartMessage) obj; + if (xid == null) { if (other.xid != null) return false; } @@ -94,5 +85,4 @@ public class SessionXAStartMessage extends PacketImpl return true; } - } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SubscribeClusterTopologyUpdatesMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SubscribeClusterTopologyUpdatesMessage.java index 4e3401a9c7..1b8abc95e0 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SubscribeClusterTopologyUpdatesMessage.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SubscribeClusterTopologyUpdatesMessage.java @@ -19,66 +19,56 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class SubscribeClusterTopologyUpdatesMessage extends PacketImpl -{ +public class SubscribeClusterTopologyUpdatesMessage extends PacketImpl { private boolean clusterConnection; - public SubscribeClusterTopologyUpdatesMessage(final boolean clusterConnection) - { + public SubscribeClusterTopologyUpdatesMessage(final boolean clusterConnection) { super(SUBSCRIBE_TOPOLOGY); this.clusterConnection = clusterConnection; } - protected SubscribeClusterTopologyUpdatesMessage(byte packetType, final boolean clusterConnection) - { + protected SubscribeClusterTopologyUpdatesMessage(byte packetType, final boolean clusterConnection) { super(packetType); this.clusterConnection = clusterConnection; } - public SubscribeClusterTopologyUpdatesMessage() - { + public SubscribeClusterTopologyUpdatesMessage() { super(SUBSCRIBE_TOPOLOGY); } - protected SubscribeClusterTopologyUpdatesMessage(byte packetType) - { + protected SubscribeClusterTopologyUpdatesMessage(byte packetType) { super(packetType); } // Public -------------------------------------------------------- - public boolean isClusterConnection() - { + public boolean isClusterConnection() { return clusterConnection; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeBoolean(clusterConnection); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { clusterConnection = buffer.readBoolean(); } @Override - public String toString() - { + public String toString() { return "SubscribeClusterTopologyUpdatesMessage [clusterConnection=" + clusterConnection + - ", toString()=" + - super.toString() + - "]"; + ", toString()=" + + super.toString() + + "]"; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (clusterConnection ? 1231 : 1237); @@ -86,15 +76,14 @@ public class SubscribeClusterTopologyUpdatesMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SubscribeClusterTopologyUpdatesMessage)) return false; - SubscribeClusterTopologyUpdatesMessage other = (SubscribeClusterTopologyUpdatesMessage)obj; + SubscribeClusterTopologyUpdatesMessage other = (SubscribeClusterTopologyUpdatesMessage) obj; if (clusterConnection != other.clusterConnection) return false; return true; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SubscribeClusterTopologyUpdatesMessageV2.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SubscribeClusterTopologyUpdatesMessageV2.java index f380a3d4fb..2be74017a2 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SubscribeClusterTopologyUpdatesMessageV2.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SubscribeClusterTopologyUpdatesMessageV2.java @@ -18,30 +18,24 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; -public class SubscribeClusterTopologyUpdatesMessageV2 extends SubscribeClusterTopologyUpdatesMessage -{ +public class SubscribeClusterTopologyUpdatesMessageV2 extends SubscribeClusterTopologyUpdatesMessage { private int clientVersion; - public SubscribeClusterTopologyUpdatesMessageV2(final boolean clusterConnection, int clientVersion) - { + public SubscribeClusterTopologyUpdatesMessageV2(final boolean clusterConnection, int clientVersion) { super(SUBSCRIBE_TOPOLOGY_V2, clusterConnection); this.clientVersion = clientVersion; } - public SubscribeClusterTopologyUpdatesMessageV2() - { + public SubscribeClusterTopologyUpdatesMessageV2() { super(SUBSCRIBE_TOPOLOGY_V2); } // Public -------------------------------------------------------- - - @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { super.encodeRest(buffer); buffer.writeInt(clientVersion); } @@ -49,21 +43,18 @@ public class SubscribeClusterTopologyUpdatesMessageV2 extends SubscribeClusterTo /** * @return the clientVersion */ - public int getClientVersion() - { + public int getClientVersion() { return clientVersion; } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { super.decodeRest(buffer); clientVersion = buffer.readInt(); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + clientVersion; @@ -71,15 +62,14 @@ public class SubscribeClusterTopologyUpdatesMessageV2 extends SubscribeClusterTo } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof SubscribeClusterTopologyUpdatesMessageV2)) return false; - SubscribeClusterTopologyUpdatesMessageV2 other = (SubscribeClusterTopologyUpdatesMessageV2)obj; + SubscribeClusterTopologyUpdatesMessageV2 other = (SubscribeClusterTopologyUpdatesMessageV2) obj; if (clientVersion != other.clientVersion) return false; return true; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/CloseListener.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/CloseListener.java index 48ec74e2c9..12c8f7ad46 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/CloseListener.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/CloseListener.java @@ -21,8 +21,8 @@ package org.apache.activemq.artemis.core.remoting; *

* {@link org.apache.activemq.artemis.spi.core.protocol.RemotingConnection#addCloseListener(CloseListener)} */ -public interface CloseListener -{ +public interface CloseListener { + /** * called when the connection is closed */ diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/FailureListener.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/FailureListener.java index 2417dd1b39..05e185b414 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/FailureListener.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/FailureListener.java @@ -21,12 +21,12 @@ import org.apache.activemq.artemis.api.core.ActiveMQException; /** * A FailureListener notifies the user when a connection failure occurred. */ -public interface FailureListener -{ +public interface FailureListener { + /** * Notifies that a connection has failed due to the specified exception. * - * @param exception exception which has caused the connection to fail + * @param exception exception which has caused the connection to fail * @param failedOver */ void connectionFailed(ActiveMQException exception, boolean failedOver); @@ -34,7 +34,7 @@ public interface FailureListener /** * Notifies that a connection has failed due to the specified exception. * - * @param exception exception which has caused the connection to fail + * @param exception exception which has caused the connection to fail * @param failedOver * @param scaleDownTargetNodeID the ID of the node to which messages are scaling down */ diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/TransportConfigurationUtil.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/TransportConfigurationUtil.java index 6d704adbb8..721290a64c 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/TransportConfigurationUtil.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/TransportConfigurationUtil.java @@ -29,31 +29,26 @@ import org.apache.activemq.artemis.utils.ClassloadingUtil; * objects. */ -public class TransportConfigurationUtil -{ +public class TransportConfigurationUtil { + private static final Map> DEFAULTS = new HashMap<>(); private static final HashMap EMPTY_HELPER = new HashMap<>(); - public static Map getDefaults(String className) - { - if (className == null) - { + public static Map getDefaults(String className) { + if (className == null) { /* Returns a new clone of the empty helper. This allows any parent objects to update the map key/values without polluting the EMPTY_HELPER map. */ return (Map) EMPTY_HELPER.clone(); } - if (!DEFAULTS.containsKey(className)) - { + if (!DEFAULTS.containsKey(className)) { Object object = instantiateObject(className); - if (object != null && object instanceof TransportConfigurationHelper) - { + if (object != null && object instanceof TransportConfigurationHelper) { DEFAULTS.put(className, ((TransportConfigurationHelper) object).getDefaults()); } - else - { + else { DEFAULTS.put(className, EMPTY_HELPER); } } @@ -63,29 +58,22 @@ public class TransportConfigurationUtil return cloneDefaults(DEFAULTS.get(className)); } - private static Object instantiateObject(final String className) - { - return AccessController.doPrivileged(new PrivilegedAction() - { - public Object run() - { - try - { + private static Object instantiateObject(final String className) { + return AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + try { return ClassloadingUtil.newInstanceFromClassLoader(className); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { return null; } } }); } - private static Map cloneDefaults(Map defaults) - { + private static Map cloneDefaults(Map defaults) { Map cloned = new HashMap(); - for (Map.Entry entry : defaults.entrySet()) - { + for (Map.Entry entry : defaults.entrySet()) { cloned.put((String) entry.getKey(), entry.getValue()); } return cloned; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/ActiveMQAMQPFrameDecoder.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/ActiveMQAMQPFrameDecoder.java index 5d9dae160d..b3e444ce9b 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/ActiveMQAMQPFrameDecoder.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/ActiveMQAMQPFrameDecoder.java @@ -23,18 +23,15 @@ import io.netty.handler.codec.LengthFieldBasedFrameDecoder; /** * A Netty decoder specially optimised to to decode messages on the core protocol only */ -public class ActiveMQAMQPFrameDecoder extends LengthFieldBasedFrameDecoder -{ - public ActiveMQAMQPFrameDecoder() - { +public class ActiveMQAMQPFrameDecoder extends LengthFieldBasedFrameDecoder { + + public ActiveMQAMQPFrameDecoder() { // The interface itself is part of the buffer (hence the -4) - super(Integer.MAX_VALUE, 0, 4, -4 , 0); + super(Integer.MAX_VALUE, 0, 4, -4, 0); } - @Override - protected ByteBuf extractFrame(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) - { + protected ByteBuf extractFrame(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) { return super.extractFrame(ctx, buffer, index, length); } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/ActiveMQChannelHandler.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/ActiveMQChannelHandler.java index 009d1c413e..d2233d102b 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/ActiveMQChannelHandler.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/ActiveMQChannelHandler.java @@ -28,12 +28,11 @@ import org.apache.activemq.artemis.core.client.ActiveMQClientMessageBundle; import org.apache.activemq.artemis.spi.core.remoting.BufferHandler; import org.apache.activemq.artemis.spi.core.remoting.ConnectionLifeCycleListener; - /** * Common handler implementation for client and server side handler. */ -public class ActiveMQChannelHandler extends ChannelDuplexHandler -{ +public class ActiveMQChannelHandler extends ChannelDuplexHandler { + private final ChannelGroup group; private final BufferHandler handler; @@ -44,42 +43,35 @@ public class ActiveMQChannelHandler extends ChannelDuplexHandler protected ActiveMQChannelHandler(final ChannelGroup group, final BufferHandler handler, - final ConnectionLifeCycleListener listener) - { + final ConnectionLifeCycleListener listener) { this.group = group; this.handler = handler; this.listener = listener; } @Override - public void channelActive(final ChannelHandlerContext ctx) throws Exception - { + public void channelActive(final ChannelHandlerContext ctx) throws Exception { group.add(ctx.channel()); ctx.fireChannelActive(); } @Override - public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception - { + public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { // TODO: Think about the id thingy listener.connectionReadyForWrites(channelId(ctx.channel()), ctx.channel().isWritable()); } @Override - public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception - { + public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception { ByteBuf buffer = (ByteBuf) msg; handler.bufferReceived(channelId(ctx.channel()), new ChannelBufferWrapper(buffer)); } @Override - public void channelInactive(final ChannelHandlerContext ctx) throws Exception - { - synchronized (this) - { - if (active) - { + public void channelInactive(final ChannelHandlerContext ctx) throws Exception { + synchronized (this) { + if (active) { listener.connectionDestroyed(channelId(ctx.channel())); active = false; @@ -88,10 +80,8 @@ public class ActiveMQChannelHandler extends ChannelDuplexHandler } @Override - public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception - { - if (!active) - { + public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception { + if (!active) { return; } // We don't want to log this - since it is normal for this to happen during failover/reconnect @@ -101,22 +91,18 @@ public class ActiveMQChannelHandler extends ChannelDuplexHandler ActiveMQException me = ActiveMQClientMessageBundle.BUNDLE.nettyError(); me.initCause(cause); - synchronized (listener) - { - try - { + synchronized (listener) { + try { listener.connectionException(channelId(ctx.channel()), me); active = false; } - catch (Exception ex) - { + catch (Exception ex) { ActiveMQClientLogger.LOGGER.errorCallingLifeCycleListener(ex); } } } - protected static int channelId(Channel channel) - { + protected static int channelId(Channel channel) { return channel.hashCode(); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/ActiveMQFrameDecoder2.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/ActiveMQFrameDecoder2.java index 8feb6558dc..60af9cf2c8 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/ActiveMQFrameDecoder2.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/ActiveMQFrameDecoder2.java @@ -24,16 +24,14 @@ import org.apache.activemq.artemis.utils.DataConstants; /** * A Netty decoder specially optimised to to decode messages on the core protocol only */ -public class ActiveMQFrameDecoder2 extends LengthFieldBasedFrameDecoder -{ - public ActiveMQFrameDecoder2() - { +public class ActiveMQFrameDecoder2 extends LengthFieldBasedFrameDecoder { + + public ActiveMQFrameDecoder2() { super(Integer.MAX_VALUE, 0, DataConstants.SIZE_INT); } @Override - protected ByteBuf extractFrame(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) - { + protected ByteBuf extractFrame(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) { // This is a work around on https://github.com/netty/netty/commit/55fbf007f04fbba7bf50028f3c8b35d6c5ea5947 // Right now we need a copy when sending a message on the server otherwise messages won't be resent to the client ByteBuf frame = ctx.alloc().buffer(length); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/NettyConnection.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/NettyConnection.java index 631259f779..f6fe2676de 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/NettyConnection.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/NettyConnection.java @@ -41,8 +41,8 @@ import org.apache.activemq.artemis.spi.core.remoting.ConnectionLifeCycleListener import org.apache.activemq.artemis.spi.core.remoting.ReadyListener; import org.apache.activemq.artemis.utils.ConcurrentHashSet; -public class NettyConnection implements Connection -{ +public class NettyConnection implements Connection { + // Constants ----------------------------------------------------- private static final int BATCHING_BUFFER_SIZE = 8192; @@ -68,7 +68,7 @@ public class NettyConnection implements Connection private RemotingConnection protocolConnection; -// Static -------------------------------------------------------- + // Static -------------------------------------------------------- // Constructors -------------------------------------------------- @@ -76,8 +76,7 @@ public class NettyConnection implements Connection final Channel channel, final ConnectionLifeCycleListener listener, boolean batchingEnabled, - boolean directDeliver) - { + boolean directDeliver) { this.configuration = configuration; this.channel = channel; @@ -91,53 +90,41 @@ public class NettyConnection implements Connection // Public -------------------------------------------------------- - public Channel getNettyChannel() - { + public Channel getNettyChannel() { return channel; } // Connection implementation ---------------------------- - - public void forceClose() - { - if (channel != null) - { - try - { + public void forceClose() { + if (channel != null) { + try { channel.close(); } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQClientLogger.LOGGER.warn(e.getMessage(), e); } } } - /** * This is exposed so users would have the option to look at any data through interceptors * * @return */ - public Channel getChannel() - { + public Channel getChannel() { return channel; } - public RemotingConnection getProtocolConnection() - { + public RemotingConnection getProtocolConnection() { return protocolConnection; } - public void setProtocolConnection(RemotingConnection protocolConnection) - { + public void setProtocolConnection(RemotingConnection protocolConnection) { this.protocolConnection = protocolConnection; } - public void close() - { - if (closed) - { + public void close() { + if (closed) { return; } @@ -145,17 +132,13 @@ public class NettyConnection implements Connection EventLoop eventLoop = channel.eventLoop(); boolean inEventLoop = eventLoop.inEventLoop(); //if we are in an event loop we need to close the channel after the writes have finished - if (!inEventLoop) - { + if (!inEventLoop) { closeSSLAndChannel(sslHandler, channel); } - else - { - eventLoop.execute(new Runnable() - { + else { + eventLoop.execute(new Runnable() { @Override - public void run() - { + public void run() { closeSSLAndChannel(sslHandler, channel); } }); @@ -166,90 +149,74 @@ public class NettyConnection implements Connection listener.connectionDestroyed(getID()); } - public ActiveMQBuffer createTransportBuffer(final int size) - { + public ActiveMQBuffer createTransportBuffer(final int size) { return new ChannelBufferWrapper(PartialPooledByteBufAllocator.INSTANCE.directBuffer(size), true); } - public Object getID() - { + public Object getID() { // TODO: Think of it return channel.hashCode(); } // This is called periodically to flush the batch buffer - public void checkFlushBatchBuffer() - { - if (!batchingEnabled) - { + public void checkFlushBatchBuffer() { + if (!batchingEnabled) { return; } - if (writeLock.tryAcquire()) - { - try - { - if (batchBuffer != null && batchBuffer.readable()) - { + if (writeLock.tryAcquire()) { + try { + if (batchBuffer != null && batchBuffer.readable()) { channel.writeAndFlush(batchBuffer.byteBuf()); batchBuffer = createTransportBuffer(BATCHING_BUFFER_SIZE); } } - finally - { + finally { writeLock.release(); } } } - public void write(final ActiveMQBuffer buffer) - { + public void write(final ActiveMQBuffer buffer) { write(buffer, false, false); } - public void write(ActiveMQBuffer buffer, final boolean flush, final boolean batched) - { + public void write(ActiveMQBuffer buffer, final boolean flush, final boolean batched) { write(buffer, flush, batched, null); } - public void write(ActiveMQBuffer buffer, final boolean flush, final boolean batched, final ChannelFutureListener futureListener) - { + public void write(ActiveMQBuffer buffer, + final boolean flush, + final boolean batched, + final ChannelFutureListener futureListener) { - try - { + try { writeLock.acquire(); - try - { - if (batchBuffer == null && batchingEnabled && batched && !flush) - { + try { + if (batchBuffer == null && batchingEnabled && batched && !flush) { // Lazily create batch buffer batchBuffer = ActiveMQBuffers.dynamicBuffer(BATCHING_BUFFER_SIZE); } - if (batchBuffer != null) - { + if (batchBuffer != null) { batchBuffer.writeBytes(buffer, 0, buffer.writerIndex()); - if (batchBuffer.writerIndex() >= BATCHING_BUFFER_SIZE || !batched || flush) - { + if (batchBuffer.writerIndex() >= BATCHING_BUFFER_SIZE || !batched || flush) { // If the batch buffer is full or it's flush param or not batched then flush the buffer buffer = batchBuffer; } - else - { + else { return; } - if (!batched || flush) - { + if (!batched || flush) { batchBuffer = null; } - else - { + else { // Create a new buffer batchBuffer = ActiveMQBuffers.dynamicBuffer(BATCHING_BUFFER_SIZE); @@ -260,44 +227,34 @@ public class NettyConnection implements Connection // use a normal promise final ByteBuf buf = buffer.byteBuf(); final ChannelPromise promise; - if (flush || futureListener != null) - { + if (flush || futureListener != null) { promise = channel.newPromise(); } - else - { + else { promise = channel.voidPromise(); } EventLoop eventLoop = channel.eventLoop(); boolean inEventLoop = eventLoop.inEventLoop(); - if (!inEventLoop) - { - if (futureListener != null) - { + if (!inEventLoop) { + if (futureListener != null) { channel.writeAndFlush(buf, promise).addListener(futureListener); } - else - { + else { channel.writeAndFlush(buf, promise); } } - else - { + else { // create a task which will be picked up by the eventloop and trigger the write. // This is mainly needed as this method is triggered by different threads for the same channel. // if we not do this we may produce out of order writes. - final Runnable task = new Runnable() - { + final Runnable task = new Runnable() { @Override - public void run() - { - if (futureListener != null) - { + public void run() { + if (futureListener != null) { channel.writeAndFlush(buf, promise).addListener(futureListener); } - else - { + else { channel.writeAndFlush(buf, promise); } } @@ -306,106 +263,83 @@ public class NettyConnection implements Connection eventLoop.execute(task); } - // only try to wait if not in the eventloop otherwise we will produce a deadlock - if (flush && !inEventLoop) - { - while (true) - { - try - { + if (flush && !inEventLoop) { + while (true) { + try { boolean ok = promise.await(10000); - if (!ok) - { + if (!ok) { ActiveMQClientLogger.LOGGER.timeoutFlushingPacket(); } break; } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } } } } - finally - { + finally { writeLock.release(); } } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } } - public String getRemoteAddress() - { + public String getRemoteAddress() { SocketAddress address = channel.remoteAddress(); - if (address == null) - { + if (address == null) { return null; } return address.toString(); } - public boolean isDirectDeliver() - { + public boolean isDirectDeliver() { return directDeliver; } - public void addReadyListener(final ReadyListener listener) - { + public void addReadyListener(final ReadyListener listener) { readyListeners.add(listener); } - public void removeReadyListener(final ReadyListener listener) - { + public void removeReadyListener(final ReadyListener listener) { readyListeners.remove(listener); } //never allow this - public ActiveMQPrincipal getDefaultActiveMQPrincipal() - { + public ActiveMQPrincipal getDefaultActiveMQPrincipal() { return null; } - void fireReady(final boolean ready) - { - for (ReadyListener listener : readyListeners) - { + void fireReady(final boolean ready) { + for (ReadyListener listener : readyListeners) { listener.readyForWriting(ready); } } - @Override - public TransportConfiguration getConnectorConfig() - { - if (configuration != null) - { + public TransportConfiguration getConnectorConfig() { + if (configuration != null) { return new TransportConfiguration(NettyConnectorFactory.class.getName(), this.configuration); } - else - { + else { return null; } } @Override - public boolean isUsingProtocolHandling() - { + public boolean isUsingProtocolHandling() { return true; } - // Public -------------------------------------------------------- @Override - public String toString() - { + public String toString() { return super.toString() + "[local= " + channel.localAddress() + ", remote=" + channel.remoteAddress() + "]"; } @@ -415,29 +349,22 @@ public class NettyConnection implements Connection // Private ------------------------------------------------------- - - private void closeSSLAndChannel(SslHandler sslHandler, Channel channel) - { - if (sslHandler != null) - { - try - { + private void closeSSLAndChannel(SslHandler sslHandler, Channel channel) { + if (sslHandler != null) { + try { ChannelFuture sslCloseFuture = sslHandler.close(); - if (!sslCloseFuture.awaitUninterruptibly(10000)) - { + if (!sslCloseFuture.awaitUninterruptibly(10000)) { ActiveMQClientLogger.LOGGER.timeoutClosingSSL(); } } - catch (Throwable t) - { + catch (Throwable t) { // ignore } } ChannelFuture closeFuture = channel.close(); - if (!closeFuture.awaitUninterruptibly(10000)) - { + if (!closeFuture.awaitUninterruptibly(10000)) { ActiveMQClientLogger.LOGGER.timeoutClosingNettyChannel(); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/NettyConnector.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/NettyConnector.java index 9efd2c18ae..a6a390efcb 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/NettyConnector.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/NettyConnector.java @@ -103,8 +103,8 @@ import org.apache.activemq.artemis.utils.FutureLatch; import static org.apache.activemq.artemis.utils.Base64.encodeBytes; -public class NettyConnector extends AbstractConnector -{ +public class NettyConnector extends AbstractConnector { + // Constants ----------------------------------------------------- public static final String JAVAX_KEYSTORE_PATH_PROP_NAME = "javax.net.ssl.keyStore"; public static final String JAVAX_KEYSTORE_PASSWORD_PROP_NAME = "javax.net.ssl.keyStorePassword"; @@ -130,13 +130,12 @@ public class NettyConnector extends AbstractConnector // Default Configuration public static final Map DEFAULT_CONFIG; - static - { + static { // Disable resource leak detection for performance reasons by default ResourceLeakDetector.setEnabled(false); // Set default Configuration - Map config = new HashMap(); + Map config = new HashMap(); config.put(TransportConstants.HOST_PROP_NAME, TransportConstants.DEFAULT_HOST); config.put(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_PORT); DEFAULT_CONFIG = Collections.unmodifiableMap(config); @@ -235,31 +234,26 @@ public class NettyConnector extends AbstractConnector final ConnectionLifeCycleListener listener, final Executor closeExecutor, final Executor threadPool, - final ScheduledExecutorService scheduledThreadPool) - { + final ScheduledExecutorService scheduledThreadPool) { this(configuration, handler, listener, closeExecutor, threadPool, scheduledThreadPool, new ActiveMQClientProtocolManager()); } - public NettyConnector(final Map configuration, final BufferHandler handler, final ConnectionLifeCycleListener listener, final Executor closeExecutor, final Executor threadPool, final ScheduledExecutorService scheduledThreadPool, - final ClientProtocolManager protocolManager) - { + final ClientProtocolManager protocolManager) { super(configuration); this.protocolManager = protocolManager; - if (listener == null) - { + if (listener == null) { throw ActiveMQClientMessageBundle.BUNDLE.nullListener(); } - if (handler == null) - { + if (handler == null) { throw ActiveMQClientMessageBundle.BUNDLE.nullHandler(); } @@ -267,102 +261,50 @@ public class NettyConnector extends AbstractConnector this.handler = handler; - sslEnabled = ConfigurationHelper.getBooleanProperty(TransportConstants.SSL_ENABLED_PROP_NAME, - TransportConstants.DEFAULT_SSL_ENABLED, - configuration); - httpEnabled = ConfigurationHelper.getBooleanProperty(TransportConstants.HTTP_ENABLED_PROP_NAME, - TransportConstants.DEFAULT_HTTP_ENABLED, - configuration); - servletPath = ConfigurationHelper.getStringProperty(TransportConstants.SERVLET_PATH, - TransportConstants.DEFAULT_SERVLET_PATH, - configuration); - if (httpEnabled) - { - httpMaxClientIdleTime = ConfigurationHelper.getLongProperty(TransportConstants.HTTP_CLIENT_IDLE_PROP_NAME, - TransportConstants.DEFAULT_HTTP_CLIENT_IDLE_TIME, - configuration); - httpClientIdleScanPeriod = ConfigurationHelper.getLongProperty(TransportConstants.HTTP_CLIENT_IDLE_SCAN_PERIOD, - TransportConstants.DEFAULT_HTTP_CLIENT_SCAN_PERIOD, - configuration); - httpRequiresSessionId = ConfigurationHelper.getBooleanProperty(TransportConstants.HTTP_REQUIRES_SESSION_ID, - TransportConstants.DEFAULT_HTTP_REQUIRES_SESSION_ID, - configuration); + sslEnabled = ConfigurationHelper.getBooleanProperty(TransportConstants.SSL_ENABLED_PROP_NAME, TransportConstants.DEFAULT_SSL_ENABLED, configuration); + httpEnabled = ConfigurationHelper.getBooleanProperty(TransportConstants.HTTP_ENABLED_PROP_NAME, TransportConstants.DEFAULT_HTTP_ENABLED, configuration); + servletPath = ConfigurationHelper.getStringProperty(TransportConstants.SERVLET_PATH, TransportConstants.DEFAULT_SERVLET_PATH, configuration); + if (httpEnabled) { + httpMaxClientIdleTime = ConfigurationHelper.getLongProperty(TransportConstants.HTTP_CLIENT_IDLE_PROP_NAME, TransportConstants.DEFAULT_HTTP_CLIENT_IDLE_TIME, configuration); + httpClientIdleScanPeriod = ConfigurationHelper.getLongProperty(TransportConstants.HTTP_CLIENT_IDLE_SCAN_PERIOD, TransportConstants.DEFAULT_HTTP_CLIENT_SCAN_PERIOD, configuration); + httpRequiresSessionId = ConfigurationHelper.getBooleanProperty(TransportConstants.HTTP_REQUIRES_SESSION_ID, TransportConstants.DEFAULT_HTTP_REQUIRES_SESSION_ID, configuration); } - else - { + else { httpMaxClientIdleTime = 0; httpClientIdleScanPeriod = -1; httpRequiresSessionId = false; } - httpUpgradeEnabled = ConfigurationHelper.getBooleanProperty(TransportConstants.HTTP_UPGRADE_ENABLED_PROP_NAME, - TransportConstants.DEFAULT_HTTP_UPGRADE_ENABLED, - configuration); + httpUpgradeEnabled = ConfigurationHelper.getBooleanProperty(TransportConstants.HTTP_UPGRADE_ENABLED_PROP_NAME, TransportConstants.DEFAULT_HTTP_UPGRADE_ENABLED, configuration); - nioRemotingThreads = ConfigurationHelper.getIntProperty(TransportConstants.NIO_REMOTING_THREADS_PROPNAME, - -1, - configuration); + nioRemotingThreads = ConfigurationHelper.getIntProperty(TransportConstants.NIO_REMOTING_THREADS_PROPNAME, -1, configuration); - useNioGlobalWorkerPool = ConfigurationHelper.getBooleanProperty(TransportConstants.USE_NIO_GLOBAL_WORKER_POOL_PROP_NAME, - TransportConstants.DEFAULT_USE_NIO_GLOBAL_WORKER_POOL, - configuration); + useNioGlobalWorkerPool = ConfigurationHelper.getBooleanProperty(TransportConstants.USE_NIO_GLOBAL_WORKER_POOL_PROP_NAME, TransportConstants.DEFAULT_USE_NIO_GLOBAL_WORKER_POOL, configuration); - useServlet = ConfigurationHelper.getBooleanProperty(TransportConstants.USE_SERVLET_PROP_NAME, - TransportConstants.DEFAULT_USE_SERVLET, - configuration); - host = ConfigurationHelper.getStringProperty(TransportConstants.HOST_PROP_NAME, - TransportConstants.DEFAULT_HOST, - configuration); - port = ConfigurationHelper.getIntProperty(TransportConstants.PORT_PROP_NAME, - TransportConstants.DEFAULT_PORT, - configuration); - localAddress = ConfigurationHelper.getStringProperty(TransportConstants.LOCAL_ADDRESS_PROP_NAME, - TransportConstants.DEFAULT_LOCAL_ADDRESS, - configuration); + useServlet = ConfigurationHelper.getBooleanProperty(TransportConstants.USE_SERVLET_PROP_NAME, TransportConstants.DEFAULT_USE_SERVLET, configuration); + host = ConfigurationHelper.getStringProperty(TransportConstants.HOST_PROP_NAME, TransportConstants.DEFAULT_HOST, configuration); + port = ConfigurationHelper.getIntProperty(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_PORT, configuration); + localAddress = ConfigurationHelper.getStringProperty(TransportConstants.LOCAL_ADDRESS_PROP_NAME, TransportConstants.DEFAULT_LOCAL_ADDRESS, configuration); - localPort = ConfigurationHelper.getIntProperty(TransportConstants.LOCAL_PORT_PROP_NAME, - TransportConstants.DEFAULT_LOCAL_PORT, - configuration); - if (sslEnabled) - { - keyStoreProvider = ConfigurationHelper.getStringProperty(TransportConstants.KEYSTORE_PROVIDER_PROP_NAME, - TransportConstants.DEFAULT_KEYSTORE_PROVIDER, - configuration); + localPort = ConfigurationHelper.getIntProperty(TransportConstants.LOCAL_PORT_PROP_NAME, TransportConstants.DEFAULT_LOCAL_PORT, configuration); + if (sslEnabled) { + keyStoreProvider = ConfigurationHelper.getStringProperty(TransportConstants.KEYSTORE_PROVIDER_PROP_NAME, TransportConstants.DEFAULT_KEYSTORE_PROVIDER, configuration); - keyStorePath = ConfigurationHelper.getStringProperty(TransportConstants.KEYSTORE_PATH_PROP_NAME, - TransportConstants.DEFAULT_KEYSTORE_PATH, - configuration); + keyStorePath = ConfigurationHelper.getStringProperty(TransportConstants.KEYSTORE_PATH_PROP_NAME, TransportConstants.DEFAULT_KEYSTORE_PATH, configuration); - keyStorePassword = ConfigurationHelper.getPasswordProperty(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, - TransportConstants.DEFAULT_KEYSTORE_PASSWORD, - configuration, - ActiveMQDefaultConfiguration.getPropMaskPassword(), - ActiveMQDefaultConfiguration.getPropMaskPassword()); + keyStorePassword = ConfigurationHelper.getPasswordProperty(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, TransportConstants.DEFAULT_KEYSTORE_PASSWORD, configuration, ActiveMQDefaultConfiguration.getPropMaskPassword(), ActiveMQDefaultConfiguration.getPropMaskPassword()); - trustStoreProvider = ConfigurationHelper.getStringProperty(TransportConstants.TRUSTSTORE_PROVIDER_PROP_NAME, - TransportConstants.DEFAULT_TRUSTSTORE_PROVIDER, - configuration); + trustStoreProvider = ConfigurationHelper.getStringProperty(TransportConstants.TRUSTSTORE_PROVIDER_PROP_NAME, TransportConstants.DEFAULT_TRUSTSTORE_PROVIDER, configuration); - trustStorePath = ConfigurationHelper.getStringProperty(TransportConstants.TRUSTSTORE_PATH_PROP_NAME, - TransportConstants.DEFAULT_TRUSTSTORE_PATH, - configuration); + trustStorePath = ConfigurationHelper.getStringProperty(TransportConstants.TRUSTSTORE_PATH_PROP_NAME, TransportConstants.DEFAULT_TRUSTSTORE_PATH, configuration); - trustStorePassword = ConfigurationHelper.getPasswordProperty(TransportConstants.TRUSTSTORE_PASSWORD_PROP_NAME, - TransportConstants.DEFAULT_TRUSTSTORE_PASSWORD, - configuration, - ActiveMQDefaultConfiguration.getPropMaskPassword(), - ActiveMQDefaultConfiguration.getPropMaskPassword()); + trustStorePassword = ConfigurationHelper.getPasswordProperty(TransportConstants.TRUSTSTORE_PASSWORD_PROP_NAME, TransportConstants.DEFAULT_TRUSTSTORE_PASSWORD, configuration, ActiveMQDefaultConfiguration.getPropMaskPassword(), ActiveMQDefaultConfiguration.getPropMaskPassword()); - enabledCipherSuites = ConfigurationHelper.getStringProperty(TransportConstants.ENABLED_CIPHER_SUITES_PROP_NAME, - TransportConstants.DEFAULT_ENABLED_CIPHER_SUITES, - configuration); + enabledCipherSuites = ConfigurationHelper.getStringProperty(TransportConstants.ENABLED_CIPHER_SUITES_PROP_NAME, TransportConstants.DEFAULT_ENABLED_CIPHER_SUITES, configuration); - enabledProtocols = ConfigurationHelper.getStringProperty(TransportConstants.ENABLED_PROTOCOLS_PROP_NAME, - TransportConstants.DEFAULT_ENABLED_PROTOCOLS, - configuration); + enabledProtocols = ConfigurationHelper.getStringProperty(TransportConstants.ENABLED_PROTOCOLS_PROP_NAME, TransportConstants.DEFAULT_ENABLED_PROTOCOLS, configuration); } - else - { + else { keyStoreProvider = TransportConstants.DEFAULT_KEYSTORE_PROVIDER; keyStorePath = TransportConstants.DEFAULT_KEYSTORE_PATH; keyStorePassword = TransportConstants.DEFAULT_KEYSTORE_PASSWORD; @@ -373,30 +315,19 @@ public class NettyConnector extends AbstractConnector enabledProtocols = TransportConstants.DEFAULT_ENABLED_PROTOCOLS; } - tcpNoDelay = ConfigurationHelper.getBooleanProperty(TransportConstants.TCP_NODELAY_PROPNAME, - TransportConstants.DEFAULT_TCP_NODELAY, - configuration); - tcpSendBufferSize = ConfigurationHelper.getIntProperty(TransportConstants.TCP_SENDBUFFER_SIZE_PROPNAME, - TransportConstants.DEFAULT_TCP_SENDBUFFER_SIZE, - configuration); - tcpReceiveBufferSize = ConfigurationHelper.getIntProperty(TransportConstants.TCP_RECEIVEBUFFER_SIZE_PROPNAME, - TransportConstants.DEFAULT_TCP_RECEIVEBUFFER_SIZE, - configuration); + tcpNoDelay = ConfigurationHelper.getBooleanProperty(TransportConstants.TCP_NODELAY_PROPNAME, TransportConstants.DEFAULT_TCP_NODELAY, configuration); + tcpSendBufferSize = ConfigurationHelper.getIntProperty(TransportConstants.TCP_SENDBUFFER_SIZE_PROPNAME, TransportConstants.DEFAULT_TCP_SENDBUFFER_SIZE, configuration); + tcpReceiveBufferSize = ConfigurationHelper.getIntProperty(TransportConstants.TCP_RECEIVEBUFFER_SIZE_PROPNAME, TransportConstants.DEFAULT_TCP_RECEIVEBUFFER_SIZE, configuration); - batchDelay = ConfigurationHelper.getLongProperty(TransportConstants.BATCH_DELAY, - TransportConstants.DEFAULT_BATCH_DELAY, - configuration); + batchDelay = ConfigurationHelper.getLongProperty(TransportConstants.BATCH_DELAY, TransportConstants.DEFAULT_BATCH_DELAY, configuration); - connectTimeoutMillis = ConfigurationHelper.getIntProperty(TransportConstants.NETTY_CONNECT_TIMEOUT, - TransportConstants.DEFAULT_NETTY_CONNECT_TIMEOUT, - configuration); + connectTimeoutMillis = ConfigurationHelper.getIntProperty(TransportConstants.NETTY_CONNECT_TIMEOUT, TransportConstants.DEFAULT_NETTY_CONNECT_TIMEOUT, configuration); this.closeExecutor = closeExecutor; this.scheduledThreadPool = scheduledThreadPool; } @Override - public String toString() - { + public String toString() { return "NettyConnector [host=" + host + ", port=" + port + @@ -415,34 +346,27 @@ public class NettyConnector extends AbstractConnector "]"; } - public synchronized void start() - { - if (channelClazz != null) - { + public synchronized void start() { + if (channelClazz != null) { return; } int threadsToUse; - if (nioRemotingThreads == -1) - { + if (nioRemotingThreads == -1) { // Default to number of cores * 3 threadsToUse = Runtime.getRuntime().availableProcessors() * 3; } - else - { + else { threadsToUse = this.nioRemotingThreads; } - - if (useNioGlobalWorkerPool) - { + if (useNioGlobalWorkerPool) { channelClazz = NioSocketChannel.class; group = SharedNioEventLoopGroup.getInstance(threadsToUse); } - else - { + else { channelClazz = NioSocketChannel.class; group = new NioEventLoopGroup(threadsToUse); } @@ -454,16 +378,13 @@ public class NettyConnector extends AbstractConnector bootstrap.option(ChannelOption.TCP_NODELAY, tcpNoDelay); - if (connectTimeoutMillis != -1) - { + if (connectTimeoutMillis != -1) { bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMillis); } - if (tcpReceiveBufferSize != -1) - { + if (tcpReceiveBufferSize != -1) { bootstrap.option(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize); } - if (tcpSendBufferSize != -1) - { + if (tcpSendBufferSize != -1) { bootstrap.option(ChannelOption.SO_SNDBUF, tcpSendBufferSize); } bootstrap.option(ChannelOption.SO_KEEPALIVE, true); @@ -472,88 +393,70 @@ public class NettyConnector extends AbstractConnector channelGroup = new DefaultChannelGroup("activemq-connector", GlobalEventExecutor.INSTANCE); final SSLContext context; - if (sslEnabled) - { - try - { + if (sslEnabled) { + try { // HORNETQ-680 - override the server-side config if client-side system properties are set String realKeyStorePath = keyStorePath; String realKeyStoreProvider = keyStoreProvider; String realKeyStorePassword = keyStorePassword; - if (System.getProperty(JAVAX_KEYSTORE_PATH_PROP_NAME) != null) - { + if (System.getProperty(JAVAX_KEYSTORE_PATH_PROP_NAME) != null) { realKeyStorePath = System.getProperty(JAVAX_KEYSTORE_PATH_PROP_NAME); } - if (System.getProperty(JAVAX_KEYSTORE_PASSWORD_PROP_NAME) != null) - { + if (System.getProperty(JAVAX_KEYSTORE_PASSWORD_PROP_NAME) != null) { realKeyStorePassword = System.getProperty(JAVAX_KEYSTORE_PASSWORD_PROP_NAME); } - if (System.getProperty(ACTIVEMQ_KEYSTORE_PROVIDER_PROP_NAME) != null) - { + if (System.getProperty(ACTIVEMQ_KEYSTORE_PROVIDER_PROP_NAME) != null) { realKeyStoreProvider = System.getProperty(ACTIVEMQ_KEYSTORE_PROVIDER_PROP_NAME); } - if (System.getProperty(ACTIVEMQ_KEYSTORE_PATH_PROP_NAME) != null) - { + if (System.getProperty(ACTIVEMQ_KEYSTORE_PATH_PROP_NAME) != null) { realKeyStorePath = System.getProperty(ACTIVEMQ_KEYSTORE_PATH_PROP_NAME); } - if (System.getProperty(ACTIVEMQ_KEYSTORE_PASSWORD_PROP_NAME) != null) - { + if (System.getProperty(ACTIVEMQ_KEYSTORE_PASSWORD_PROP_NAME) != null) { realKeyStorePassword = System.getProperty(ACTIVEMQ_KEYSTORE_PASSWORD_PROP_NAME); } String realTrustStorePath = trustStorePath; String realTrustStoreProvider = trustStoreProvider; String realTrustStorePassword = trustStorePassword; - if (System.getProperty(JAVAX_TRUSTSTORE_PATH_PROP_NAME) != null) - { + if (System.getProperty(JAVAX_TRUSTSTORE_PATH_PROP_NAME) != null) { realTrustStorePath = System.getProperty(JAVAX_TRUSTSTORE_PATH_PROP_NAME); } - if (System.getProperty(JAVAX_TRUSTSTORE_PASSWORD_PROP_NAME) != null) - { + if (System.getProperty(JAVAX_TRUSTSTORE_PASSWORD_PROP_NAME) != null) { realTrustStorePassword = System.getProperty(JAVAX_TRUSTSTORE_PASSWORD_PROP_NAME); } - if (System.getProperty(ACTIVEMQ_TRUSTSTORE_PROVIDER_PROP_NAME) != null) - { + if (System.getProperty(ACTIVEMQ_TRUSTSTORE_PROVIDER_PROP_NAME) != null) { realTrustStoreProvider = System.getProperty(ACTIVEMQ_TRUSTSTORE_PROVIDER_PROP_NAME); } - if (System.getProperty(ACTIVEMQ_TRUSTSTORE_PATH_PROP_NAME) != null) - { + if (System.getProperty(ACTIVEMQ_TRUSTSTORE_PATH_PROP_NAME) != null) { realTrustStorePath = System.getProperty(ACTIVEMQ_TRUSTSTORE_PATH_PROP_NAME); } - if (System.getProperty(ACTIVEMQ_TRUSTSTORE_PASSWORD_PROP_NAME) != null) - { + if (System.getProperty(ACTIVEMQ_TRUSTSTORE_PASSWORD_PROP_NAME) != null) { realTrustStorePassword = System.getProperty(ACTIVEMQ_TRUSTSTORE_PASSWORD_PROP_NAME); } context = SSLSupport.createContext(realKeyStoreProvider, realKeyStorePath, realKeyStorePassword, realTrustStoreProvider, realTrustStorePath, realTrustStorePassword); } - catch (Exception e) - { + catch (Exception e) { close(); IllegalStateException ise = new IllegalStateException("Unable to create NettyConnector for " + host + ":" + port); ise.initCause(e); throw ise; } } - else - { + else { context = null; // Unused } - if (context != null && useServlet) - { + if (context != null && useServlet) { // TODO: Fix me //bootstrap.setOption("sslContext", context); } - bootstrap.handler(new ChannelInitializer() - { - public void initChannel(Channel channel) throws Exception - { + bootstrap.handler(new ChannelInitializer() { + public void initChannel(Channel channel) throws Exception { final ChannelPipeline pipeline = channel.pipeline(); - if (sslEnabled && !useServlet) - { + if (sslEnabled && !useServlet) { SSLEngine engine = context.createSSLEngine(); engine.setUseClientMode(true); @@ -565,33 +468,26 @@ public class NettyConnector extends AbstractConnector // we can reset the enabled protocols if a customer protocol isn't specified String[] originalProtocols = engine.getEnabledProtocols(); - if (enabledCipherSuites != null) - { - try - { + if (enabledCipherSuites != null) { + try { engine.setEnabledCipherSuites(SSLSupport.parseCommaSeparatedListIntoArray(enabledCipherSuites)); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { ActiveMQClientLogger.LOGGER.invalidCipherSuite(SSLSupport.parseArrayIntoCommandSeparatedList(engine.getSupportedCipherSuites())); throw e; } } - if (enabledProtocols != null) - { - try - { + if (enabledProtocols != null) { + try { engine.setEnabledProtocols(SSLSupport.parseCommaSeparatedListIntoArray(enabledProtocols)); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { ActiveMQClientLogger.LOGGER.invalidProtocol(SSLSupport.parseArrayIntoCommandSeparatedList(engine.getSupportedProtocols())); throw e; } } - else - { + else { engine.setEnabledProtocols(originalProtocols); } @@ -600,8 +496,7 @@ public class NettyConnector extends AbstractConnector pipeline.addLast(handler); } - if (httpEnabled) - { + if (httpEnabled) { pipeline.addLast(new HttpRequestEncoder()); pipeline.addLast(new HttpResponseDecoder()); @@ -611,8 +506,7 @@ public class NettyConnector extends AbstractConnector pipeline.addLast(new HttpHandler()); } - if (httpUpgradeEnabled) - { + if (httpUpgradeEnabled) { // prepare to handle a HTTP 101 response to upgrade the protocol. final HttpClientCodec httpClientCodec = new HttpClientCodec(); pipeline.addLast(httpClientCodec); @@ -625,8 +519,7 @@ public class NettyConnector extends AbstractConnector } }); - if (batchDelay > 0) - { + if (batchDelay > 0) { flusher = new BatchFlusher(); batchFlusherFuture = scheduledThreadPool.scheduleWithFixedDelay(flusher, batchDelay, batchDelay, TimeUnit.MILLISECONDS); @@ -635,15 +528,12 @@ public class NettyConnector extends AbstractConnector ActiveMQClientLogger.LOGGER.debug("Started Netty Connector version " + TransportConstants.NETTY_VERSION); } - public synchronized void close() - { - if (channelClazz == null) - { + public synchronized void close() { + if (channelClazz == null) { return; } - if (batchFlusherFuture != null) - { + if (batchFlusherFuture != null) { batchFlusherFuture.cancel(false); flusher.cancel(); @@ -662,40 +552,32 @@ public class NettyConnector extends AbstractConnector channelClazz = null; - for (Connection connection : connections.values()) - { + for (Connection connection : connections.values()) { listener.connectionDestroyed(connection.getID()); } connections.clear(); } - public boolean isStarted() - { + public boolean isStarted() { return channelClazz != null; } - public Connection createConnection() - { - if (channelClazz == null) - { + public Connection createConnection() { + if (channelClazz == null) { return null; } // HORNETQ-907 - strip off IPv6 scope-id (if necessary) SocketAddress remoteDestination = new InetSocketAddress(host, port); InetAddress inetAddress = ((InetSocketAddress) remoteDestination).getAddress(); - if (inetAddress instanceof Inet6Address) - { + if (inetAddress instanceof Inet6Address) { Inet6Address inet6Address = (Inet6Address) inetAddress; - if (inet6Address.getScopeId() != 0) - { - try - { + if (inet6Address.getScopeId() != 0) { + try { remoteDestination = new InetSocketAddress(InetAddress.getByAddress(inet6Address.getAddress()), ((InetSocketAddress) remoteDestination).getPort()); } - catch (UnknownHostException e) - { + catch (UnknownHostException e) { throw new IllegalArgumentException(e.getMessage()); } } @@ -705,61 +587,49 @@ public class NettyConnector extends AbstractConnector ChannelFuture future; //port 0 does not work so only use local address if set - if (localPort != 0) - { + if (localPort != 0) { SocketAddress localDestination; - if (localAddress != null) - { + if (localAddress != null) { localDestination = new InetSocketAddress(localAddress, localPort); } - else - { + else { localDestination = new InetSocketAddress(localPort); } future = bootstrap.connect(remoteDestination, localDestination); } - else - { + else { future = bootstrap.connect(remoteDestination); } future.awaitUninterruptibly(); - if (future.isSuccess()) - { + if (future.isSuccess()) { final Channel ch = future.channel(); SslHandler sslHandler = ch.pipeline().get(SslHandler.class); - if (sslHandler != null) - { + if (sslHandler != null) { Future handshakeFuture = sslHandler.handshakeFuture(); - if (handshakeFuture.awaitUninterruptibly(30000)) - { - if (handshakeFuture.isSuccess()) - { + if (handshakeFuture.awaitUninterruptibly(30000)) { + if (handshakeFuture.isSuccess()) { ChannelPipeline channelPipeline = ch.pipeline(); ActiveMQChannelHandler channelHandler = channelPipeline.get(ActiveMQChannelHandler.class); channelHandler.active = true; } - else - { + else { ch.close().awaitUninterruptibly(); ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(handshakeFuture.cause()); return null; } } - else - { + else { //handshakeFuture.setFailure(new SSLException("Handshake was not completed in 30 seconds")); ch.close().awaitUninterruptibly(); return null; } } - if (httpUpgradeEnabled) - { + if (httpUpgradeEnabled) { // Send a HTTP GET + Upgrade request that will be handled by the http-upgrade handler. - try - { + try { //get this first incase it removes itself HttpUpgradeHandler httpUpgradeHandler = (HttpUpgradeHandler) ch.pipeline().get("http-upgrade"); URI uri = new URI("http", null, host, port, null, null, null); @@ -768,11 +638,8 @@ public class NettyConnector extends AbstractConnector request.headers().set(HttpHeaders.Names.UPGRADE, ACTIVEMQ_REMOTING); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE); - final String endpoint = ConfigurationHelper.getStringProperty(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, - null, - configuration); - if (endpoint != null) - { + final String endpoint = ConfigurationHelper.getStringProperty(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, null, configuration); + if (endpoint != null) { request.headers().set(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, endpoint); } @@ -787,19 +654,16 @@ public class NettyConnector extends AbstractConnector // Send the HTTP request. ch.writeAndFlush(request); - if (!httpUpgradeHandler.awaitHandshake()) - { + if (!httpUpgradeHandler.awaitHandshake()) { return null; } } - catch (URISyntaxException e) - { + catch (URISyntaxException e) { ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(e); return null; } } - else - { + else { ChannelPipeline channelPipeline = ch.pipeline(); ActiveMQChannelHandler channelHandler = channelPipeline.get(ActiveMQChannelHandler.class); channelHandler.active = true; @@ -811,12 +675,10 @@ public class NettyConnector extends AbstractConnector connectionListener.connectionCreated(null, conn, protocolManager.getName()); return conn; } - else - { + else { Throwable t = future.cause(); - if (t != null && !(t instanceof ConnectException)) - { + if (t != null && !(t instanceof ConnectException)) { ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(future.cause()); } @@ -834,43 +696,36 @@ public class NettyConnector extends AbstractConnector // Inner classes ------------------------------------------------- - private static final class ActiveMQClientChannelHandler extends ActiveMQChannelHandler - { + private static final class ActiveMQClientChannelHandler extends ActiveMQChannelHandler { + ActiveMQClientChannelHandler(final ChannelGroup group, final BufferHandler handler, - final ConnectionLifeCycleListener listener) - { + final ConnectionLifeCycleListener listener) { super(group, handler, listener); } } - private static class HttpUpgradeHandler extends SimpleChannelInboundHandler - { + private static class HttpUpgradeHandler extends SimpleChannelInboundHandler { + private final ChannelPipeline pipeline; private final HttpClientCodec httpClientCodec; private final CountDownLatch latch = new CountDownLatch(1); private boolean handshakeComplete = false; - public HttpUpgradeHandler(ChannelPipeline pipeline, HttpClientCodec httpClientCodec) - { + public HttpUpgradeHandler(ChannelPipeline pipeline, HttpClientCodec httpClientCodec) { this.pipeline = pipeline; this.httpClientCodec = httpClientCodec; } @Override - public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception - { - if (msg instanceof HttpResponse) - { + public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { + if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; - if (response.getStatus().code() == HttpResponseStatus.SWITCHING_PROTOCOLS.code() - && response.headers().get(HttpHeaders.Names.UPGRADE).equals(ACTIVEMQ_REMOTING)) - { + if (response.getStatus().code() == HttpResponseStatus.SWITCHING_PROTOCOLS.code() && response.headers().get(HttpHeaders.Names.UPGRADE).equals(ACTIVEMQ_REMOTING)) { String accept = response.headers().get(SEC_ACTIVEMQ_REMOTING_ACCEPT); String expectedResponse = createExpectedResponse(MAGIC_NUMBER, ctx.channel().attr(REMOTING_KEY).get()); - if (expectedResponse.equals(accept)) - { + if (expectedResponse.equals(accept)) { // remove the http handlers and flag the activemq channel handler as active pipeline.remove(httpClientCodec); pipeline.remove(this); @@ -878,14 +733,12 @@ public class NettyConnector extends AbstractConnector ActiveMQChannelHandler channelHandler = pipeline.get(ActiveMQChannelHandler.class); channelHandler.active = true; } - else - { + else { ActiveMQClientLogger.LOGGER.httpHandshakeFailed(accept, expectedResponse); ctx.close(); } } - else if (response.getStatus().code() == HttpResponseStatus.FORBIDDEN.code()) - { + else if (response.getStatus().code() == HttpResponseStatus.FORBIDDEN.code()) { ActiveMQClientLogger.LOGGER.httpUpgradeNotSupportedByRemoteAcceptor(); ctx.close(); } @@ -894,31 +747,26 @@ public class NettyConnector extends AbstractConnector } @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception - { + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(cause); ctx.close(); } - public boolean awaitHandshake() - { - try - { - if (!latch.await(30000, TimeUnit.MILLISECONDS)) - { + public boolean awaitHandshake() { + try { + if (!latch.await(30000, TimeUnit.MILLISECONDS)) { return false; } } - catch (InterruptedException e) - { + catch (InterruptedException e) { return false; } return handshakeComplete; } } - class HttpHandler extends ChannelDuplexHandler - { + class HttpHandler extends ChannelDuplexHandler { + private Channel channel; private long lastSendTime = 0; @@ -937,32 +785,24 @@ public class NettyConnector extends AbstractConnector private String cookie; - public HttpHandler() throws Exception - { + public HttpHandler() throws Exception { url = new URI("http", null, host, port, servletPath, null, null).toString(); } @Override - public void channelActive(final ChannelHandlerContext ctx) throws Exception - { + public void channelActive(final ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); channel = ctx.channel(); - if (httpClientIdleScanPeriod > 0) - { + if (httpClientIdleScanPeriod > 0) { task = new HttpIdleTimer(); - java.util.concurrent.Future future = scheduledThreadPool.scheduleAtFixedRate(task, - httpClientIdleScanPeriod, - httpClientIdleScanPeriod, - TimeUnit.MILLISECONDS); + java.util.concurrent.Future future = scheduledThreadPool.scheduleAtFixedRate(task, httpClientIdleScanPeriod, httpClientIdleScanPeriod, TimeUnit.MILLISECONDS); task.setFuture(future); } } @Override - public void channelInactive(final ChannelHandlerContext ctx) throws Exception - { - if (task != null) - { + public void channelInactive(final ChannelHandlerContext ctx) throws Exception { + if (task != null) { task.close(); } @@ -970,16 +810,12 @@ public class NettyConnector extends AbstractConnector } @Override - public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception - { + public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception { FullHttpResponse response = (FullHttpResponse) msg; - if (httpRequiresSessionId && !active) - { + if (httpRequiresSessionId && !active) { Set cookieMap = CookieDecoder.decode(response.headers().get(HttpHeaders.Names.SET_COOKIE)); - for (Cookie cookie : cookieMap) - { - if (cookie.getName().equals("JSESSIONID")) - { + for (Cookie cookie : cookieMap) { + if (cookie.getName().equals("JSESSIONID")) { this.cookie = ClientCookieEncoder.encode(cookie); } } @@ -991,20 +827,14 @@ public class NettyConnector extends AbstractConnector } @Override - public void write(final ChannelHandlerContext ctx, final Object msg, ChannelPromise promise) throws Exception - { - if (msg instanceof ByteBuf) - { - if (httpRequiresSessionId && !active) - { - if (handshaking) - { + public void write(final ChannelHandlerContext ctx, final Object msg, ChannelPromise promise) throws Exception { + if (msg instanceof ByteBuf) { + if (httpRequiresSessionId && !active) { + if (handshaking) { handshaking = true; } - else - { - if (!handShakeFuture.await(5000)) - { + else { + if (!handShakeFuture.await(5000)) { throw new RuntimeException("Handshake failed after timeout"); } } @@ -1013,36 +843,31 @@ public class NettyConnector extends AbstractConnector ByteBuf buf = (ByteBuf) msg; FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, url, buf); httpRequest.headers().add(HttpHeaders.Names.HOST, NettyConnector.this.host); - if (cookie != null) - { + if (cookie != null) { httpRequest.headers().add(HttpHeaders.Names.COOKIE, cookie); } httpRequest.headers().add(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(buf.readableBytes())); ctx.write(httpRequest, promise); lastSendTime = System.currentTimeMillis(); } - else - { + else { ctx.write(msg, promise); lastSendTime = System.currentTimeMillis(); } } - private class HttpIdleTimer implements Runnable - { + private class HttpIdleTimer implements Runnable { + private boolean closed = false; private java.util.concurrent.Future future; - public synchronized void run() - { - if (closed) - { + public synchronized void run() { + if (closed) { return; } - if (!waitingGet && System.currentTimeMillis() > lastSendTime + httpMaxClientIdleTime) - { + if (!waitingGet && System.currentTimeMillis() > lastSendTime + httpMaxClientIdleTime) { FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, url); httpRequest.headers().add(HttpHeaders.Names.HOST, NettyConnector.this.host); waitingGet = true; @@ -1050,15 +875,12 @@ public class NettyConnector extends AbstractConnector } } - public synchronized void setFuture(final java.util.concurrent.Future future) - { + public synchronized void setFuture(final java.util.concurrent.Future future) { this.future = future; } - public void close() - { - if (future != null) - { + public void close() { + if (future != null) { future.cancel(false); } @@ -1067,90 +889,73 @@ public class NettyConnector extends AbstractConnector } } - private class Listener implements ConnectionLifeCycleListener - { - public void connectionCreated(final ActiveMQComponent component, final Connection connection, final String protocol) - { - if (connections.putIfAbsent(connection.getID(), connection) != null) - { + private class Listener implements ConnectionLifeCycleListener { + + public void connectionCreated(final ActiveMQComponent component, + final Connection connection, + final String protocol) { + if (connections.putIfAbsent(connection.getID(), connection) != null) { throw ActiveMQClientMessageBundle.BUNDLE.connectionExists(connection.getID()); } } - public void connectionDestroyed(final Object connectionID) - { - if (connections.remove(connectionID) != null) - { + public void connectionDestroyed(final Object connectionID) { + if (connections.remove(connectionID) != null) { // Execute on different thread to avoid deadlocks - closeExecutor.execute(new Runnable() - { - public void run() - { + closeExecutor.execute(new Runnable() { + public void run() { listener.connectionDestroyed(connectionID); } }); } } - public void connectionException(final Object connectionID, final ActiveMQException me) - { + public void connectionException(final Object connectionID, final ActiveMQException me) { // Execute on different thread to avoid deadlocks - closeExecutor.execute(new Runnable() - { - public void run() - { + closeExecutor.execute(new Runnable() { + public void run() { listener.connectionException(connectionID, me); } }); } - public void connectionReadyForWrites(Object connectionID, boolean ready) - { + public void connectionReadyForWrites(Object connectionID, boolean ready) { } - } - private class BatchFlusher implements Runnable - { + private class BatchFlusher implements Runnable { + private boolean cancelled; - public synchronized void run() - { - if (!cancelled) - { - for (Connection connection : connections.values()) - { + public synchronized void run() { + if (!cancelled) { + for (Connection connection : connections.values()) { connection.checkFlushBatchBuffer(); } } } - public synchronized void cancel() - { + public synchronized void cancel() { cancelled = true; } } - public boolean isEquivalent(Map configuration) - { + public boolean isEquivalent(Map configuration) { //here we only check host and port because these two parameters //is sufficient to determine the target host - String host = ConfigurationHelper.getStringProperty(TransportConstants.HOST_PROP_NAME, - TransportConstants.DEFAULT_HOST, - configuration); - Integer port = ConfigurationHelper.getIntProperty(TransportConstants.PORT_PROP_NAME, - TransportConstants.DEFAULT_PORT, - configuration); + String host = ConfigurationHelper.getStringProperty(TransportConstants.HOST_PROP_NAME, TransportConstants.DEFAULT_HOST, configuration); + Integer port = ConfigurationHelper.getIntProperty(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_PORT, configuration); - if (!port.equals(this.port)) return false; + if (!port.equals(this.port)) + return false; - if (host.equals(this.host)) return true; + if (host.equals(this.host)) + return true; //The host may be an alias. We need to compare raw IP address. boolean result = false; - try - { + try { InetAddress inetAddr1 = InetAddress.getByName(host); InetAddress inetAddr2 = InetAddress.getByName(this.host); String ip1 = inetAddr1.getHostAddress(); @@ -1159,45 +964,37 @@ public class NettyConnector extends AbstractConnector result = ip1.equals(ip2); } - catch (UnknownHostException e) - { + catch (UnknownHostException e) { ActiveMQClientLogger.LOGGER.error("Cannot resolve host", e); } return result; } - public void finalize() throws Throwable - { + public void finalize() throws Throwable { close(); super.finalize(); } //for test purpose only - public Bootstrap getBootStrap() - { + public Bootstrap getBootStrap() { return bootstrap; } - public static void clearThreadPools() - { + public static void clearThreadPools() { SharedNioEventLoopGroup.forceShutdown(); } - private static ClassLoader getThisClassLoader() - { - return AccessController.doPrivileged(new PrivilegedAction() - { - public ClassLoader run() - { + private static ClassLoader getThisClassLoader() { + return AccessController.doPrivileged(new PrivilegedAction() { + public ClassLoader run() { return ClientSessionFactoryImpl.class.getClassLoader(); } }); } - private static String base64(byte[] data) - { + private static String base64(byte[] data) { ByteBuf encodedData = Unpooled.wrappedBuffer(data); ByteBuf encoded = Base64.encode(encodedData); String encodedString = encoded.toString(StandardCharsets.UTF_8); @@ -1211,27 +1008,22 @@ public class NettyConnector extends AbstractConnector * @param size the number of random bytes to create * @return An array of random bytes */ - private static byte[] randomBytes(int size) - { + private static byte[] randomBytes(int size) { byte[] bytes = new byte[size]; - for (int index = 0; index < size; index++) - { + for (int index = 0; index < size; index++) { bytes[index] = (byte) randomNumber(0, 255); } return bytes; } - private static int randomNumber(int minimum, int maximum) - { + private static int randomNumber(int minimum, int maximum) { return (int) (Math.random() * maximum + minimum); } - public static String createExpectedResponse(final String magicNumber, final String secretKey) throws IOException - { - try - { + public static String createExpectedResponse(final String magicNumber, final String secretKey) throws IOException { + try { final String concat = secretKey + magicNumber; final MessageDigest digest = MessageDigest.getInstance("SHA1"); @@ -1239,8 +1031,7 @@ public class NettyConnector extends AbstractConnector final byte[] bytes = digest.digest(); return encodeBytes(bytes); } - catch (NoSuchAlgorithmException e) - { + catch (NoSuchAlgorithmException e) { throw new IOException(e); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/NettyConnectorFactory.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/NettyConnectorFactory.java index 5d871d1f11..99c6a560bf 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/NettyConnectorFactory.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/NettyConnectorFactory.java @@ -26,28 +26,25 @@ import org.apache.activemq.artemis.spi.core.remoting.ConnectionLifeCycleListener import org.apache.activemq.artemis.spi.core.remoting.Connector; import org.apache.activemq.artemis.spi.core.remoting.ConnectorFactory; -public class NettyConnectorFactory implements ConnectorFactory -{ +public class NettyConnectorFactory implements ConnectorFactory { + public Connector createConnector(final Map configuration, final BufferHandler handler, final ConnectionLifeCycleListener listener, final Executor closeExecutor, final Executor threadPool, final ScheduledExecutorService scheduledThreadPool, - final ClientProtocolManager protocolManager) - { + final ClientProtocolManager protocolManager) { return new NettyConnector(configuration, handler, listener, closeExecutor, threadPool, scheduledThreadPool); } @Override - public boolean isReliable() - { + public boolean isReliable() { return false; } @Override - public Map getDefaults() - { + public Map getDefaults() { return NettyConnector.DEFAULT_CONFIG; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/PartialPooledByteBufAllocator.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/PartialPooledByteBufAllocator.java index 3bfd276369..aeede30dab 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/PartialPooledByteBufAllocator.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/PartialPooledByteBufAllocator.java @@ -22,133 +22,112 @@ import io.netty.buffer.CompositeByteBuf; import io.netty.buffer.PooledByteBufAllocator; import io.netty.buffer.UnpooledByteBufAllocator; - /** * A {@link ByteBufAllocator} which is partial pooled. Which means only direct {@link ByteBuf}s are pooled. The rest * is unpooled. */ -public class PartialPooledByteBufAllocator implements ByteBufAllocator -{ +public class PartialPooledByteBufAllocator implements ByteBufAllocator { + private static final ByteBufAllocator POOLED = new PooledByteBufAllocator(false); private static final ByteBufAllocator UNPOOLED = new UnpooledByteBufAllocator(false); public static final PartialPooledByteBufAllocator INSTANCE = new PartialPooledByteBufAllocator(); - private PartialPooledByteBufAllocator() - { + private PartialPooledByteBufAllocator() { } @Override - public ByteBuf buffer() - { + public ByteBuf buffer() { return UNPOOLED.heapBuffer(); } @Override - public ByteBuf buffer(int initialCapacity) - { + public ByteBuf buffer(int initialCapacity) { return UNPOOLED.heapBuffer(initialCapacity); } @Override - public ByteBuf buffer(int initialCapacity, int maxCapacity) - { + public ByteBuf buffer(int initialCapacity, int maxCapacity) { return UNPOOLED.heapBuffer(initialCapacity, maxCapacity); } @Override - public ByteBuf ioBuffer() - { + public ByteBuf ioBuffer() { return UNPOOLED.heapBuffer(); } @Override - public ByteBuf ioBuffer(int initialCapacity) - { + public ByteBuf ioBuffer(int initialCapacity) { return UNPOOLED.heapBuffer(initialCapacity); } @Override - public ByteBuf ioBuffer(int initialCapacity, int maxCapacity) - { + public ByteBuf ioBuffer(int initialCapacity, int maxCapacity) { return UNPOOLED.heapBuffer(initialCapacity, maxCapacity); } @Override - public ByteBuf heapBuffer() - { + public ByteBuf heapBuffer() { return UNPOOLED.heapBuffer(); } @Override - public ByteBuf heapBuffer(int initialCapacity) - { + public ByteBuf heapBuffer(int initialCapacity) { return UNPOOLED.heapBuffer(initialCapacity); } @Override - public ByteBuf heapBuffer(int initialCapacity, int maxCapacity) - { + public ByteBuf heapBuffer(int initialCapacity, int maxCapacity) { return UNPOOLED.heapBuffer(initialCapacity, maxCapacity); } @Override - public ByteBuf directBuffer() - { + public ByteBuf directBuffer() { return POOLED.directBuffer(); } @Override - public ByteBuf directBuffer(int initialCapacity) - { + public ByteBuf directBuffer(int initialCapacity) { return POOLED.directBuffer(initialCapacity); } @Override - public ByteBuf directBuffer(int initialCapacity, int maxCapacity) - { + public ByteBuf directBuffer(int initialCapacity, int maxCapacity) { return POOLED.directBuffer(initialCapacity, maxCapacity); } @Override - public CompositeByteBuf compositeBuffer() - { + public CompositeByteBuf compositeBuffer() { return UNPOOLED.compositeHeapBuffer(); } @Override - public CompositeByteBuf compositeBuffer(int maxNumComponents) - { + public CompositeByteBuf compositeBuffer(int maxNumComponents) { return UNPOOLED.compositeHeapBuffer(maxNumComponents); } @Override - public CompositeByteBuf compositeHeapBuffer() - { + public CompositeByteBuf compositeHeapBuffer() { return UNPOOLED.compositeHeapBuffer(); } @Override - public CompositeByteBuf compositeHeapBuffer(int maxNumComponents) - { + public CompositeByteBuf compositeHeapBuffer(int maxNumComponents) { return UNPOOLED.compositeHeapBuffer(maxNumComponents); } @Override - public CompositeByteBuf compositeDirectBuffer() - { + public CompositeByteBuf compositeDirectBuffer() { return POOLED.compositeDirectBuffer(); } @Override - public CompositeByteBuf compositeDirectBuffer(int maxNumComponents) - { + public CompositeByteBuf compositeDirectBuffer(int maxNumComponents) { return POOLED.compositeDirectBuffer(); } @Override - public boolean isDirectBufferPooled() - { + public boolean isDirectBufferPooled() { return true; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/SharedNioEventLoopGroup.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/SharedNioEventLoopGroup.java index 2e998fd8b4..c553c379a9 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/SharedNioEventLoopGroup.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/SharedNioEventLoopGroup.java @@ -32,52 +32,42 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; -public class SharedNioEventLoopGroup extends NioEventLoopGroup -{ +public class SharedNioEventLoopGroup extends NioEventLoopGroup { + private static SharedNioEventLoopGroup instance; private final AtomicReference> shutdown = new AtomicReference>(); private final AtomicLong nioChannelFactoryCount = new AtomicLong(); private final Promise terminationPromise = ImmediateEventExecutor.INSTANCE.newPromise(); - private SharedNioEventLoopGroup(int numThreads, ThreadFactory factory) - { + private SharedNioEventLoopGroup(int numThreads, ThreadFactory factory) { super(numThreads, factory); } - private static ClassLoader getThisClassLoader() - { - return AccessController.doPrivileged(new PrivilegedAction() - { - public ClassLoader run() - { + private static ClassLoader getThisClassLoader() { + return AccessController.doPrivileged(new PrivilegedAction() { + public ClassLoader run() { return ClientSessionFactoryImpl.class.getClassLoader(); } }); } - public static synchronized void forceShutdown() - { - if (instance != null) - { + public static synchronized void forceShutdown() { + if (instance != null) { instance.shutdown(); instance.nioChannelFactoryCount.set(0); instance = null; } } - public static synchronized SharedNioEventLoopGroup getInstance(int numThreads) - { - if (instance != null) - { + public static synchronized SharedNioEventLoopGroup getInstance(int numThreads) { + if (instance != null) { ScheduledFuture f = instance.shutdown.getAndSet(null); - if (f != null) - { + if (f != null) { f.cancel(false); } } - else - { + else { instance = new SharedNioEventLoopGroup(numThreads, new ActiveMQThreadFactory("ActiveMQ-client-netty-threads", true, getThisClassLoader())); } instance.nioChannelFactoryCount.incrementAndGet(); @@ -85,43 +75,31 @@ public class SharedNioEventLoopGroup extends NioEventLoopGroup } @Override - public Future terminationFuture() - { + public Future terminationFuture() { return terminationPromise; } @Override - public Future shutdownGracefully() - { + public Future shutdownGracefully() { return shutdownGracefully(100, 3000, TimeUnit.MILLISECONDS); } @Override - public Future shutdownGracefully(final long l, final long l2, final TimeUnit timeUnit) - { - if (nioChannelFactoryCount.decrementAndGet() == 0) - { - shutdown.compareAndSet(null, next().scheduleAtFixedRate(new Runnable() - { + public Future shutdownGracefully(final long l, final long l2, final TimeUnit timeUnit) { + if (nioChannelFactoryCount.decrementAndGet() == 0) { + shutdown.compareAndSet(null, next().scheduleAtFixedRate(new Runnable() { @Override - public void run() - { - synchronized (SharedNioEventLoopGroup.class) - { - if (shutdown.get() != null) - { + public void run() { + synchronized (SharedNioEventLoopGroup.class) { + if (shutdown.get() != null) { Future future = SharedNioEventLoopGroup.super.shutdownGracefully(l, l2, timeUnit); - future.addListener(new FutureListener() - { + future.addListener(new FutureListener() { @Override - public void operationComplete(Future future) throws Exception - { - if (future.isSuccess()) - { + public void operationComplete(Future future) throws Exception { + if (future.isSuccess()) { terminationPromise.setSuccess(null); } - else - { + else { terminationPromise.setFailure(future.cause()); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/TransportConstants.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/TransportConstants.java index 941533992a..d82d034016 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/TransportConstants.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/TransportConstants.java @@ -23,8 +23,8 @@ import java.util.Set; import io.netty.util.Version; import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration; -public class TransportConstants -{ +public class TransportConstants { + public static final String SSL_ENABLED_PROP_NAME = "sslEnabled"; public static final String HTTP_ENABLED_PROP_NAME = "httpEnabled"; @@ -53,7 +53,9 @@ public class TransportConstants public static final String USE_INVM_PROP_NAME = "useInvm"; - /** @deprecated use PROTOCOLS_PROP_NAME */ + /** + * @deprecated use PROTOCOLS_PROP_NAME + */ @Deprecated public static final String PROTOCOL_PROP_NAME = "protocol"; @@ -197,8 +199,7 @@ public class TransportConstants public static final long DEFAULT_CONNECTIONS_ALLOWED = -1L; - static - { + static { Set allowableAcceptorKeys = new HashSet(); allowableAcceptorKeys.add(TransportConstants.SSL_ENABLED_PROP_NAME); allowableAcceptorKeys.add(TransportConstants.HTTP_RESPONSE_TIME_PROP_NAME); @@ -273,12 +274,10 @@ public class TransportConstants String version; Version v = Version.identify().get("netty-transport"); - if (v == null) - { + if (v == null) { version = "unknown"; } - else - { + else { version = v.artifactVersion(); } NETTY_VERSION = version; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/ssl/SSLSupport.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/ssl/SSLSupport.java index 4eb10a229d..3593294716 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/ssl/SSLSupport.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/ssl/SSLSupport.java @@ -40,13 +40,15 @@ import org.apache.activemq.artemis.utils.ClassloadingUtil; * (see java.security.Security#getProviders()). The main thing to keep in mind is that PKCS#11 keystores will have a * null keystore path. */ -public class SSLSupport -{ +public class SSLSupport { // Public -------------------------------------------------------- - public static SSLContext createContext(final String keystoreProvider, final String keystorePath, final String keystorePassword, - final String trustStoreProvider, final String trustStorePath, final String trustStorePassword) throws Exception - { + public static SSLContext createContext(final String keystoreProvider, + final String keystorePath, + final String keystorePassword, + final String trustStoreProvider, + final String trustStorePath, + final String trustStorePassword) throws Exception { SSLContext context = SSLContext.getInstance("TLS"); KeyManager[] keyManagers = SSLSupport.loadKeyManagers(keystoreProvider, keystorePath, keystorePassword); TrustManager[] trustManagers = SSLSupport.loadTrustManager(trustStoreProvider, trustStorePath, trustStorePassword); @@ -54,22 +56,18 @@ public class SSLSupport return context; } - public static String[] parseCommaSeparatedListIntoArray(String suites) - { + public static String[] parseCommaSeparatedListIntoArray(String suites) { String[] cipherSuites = suites.split(","); - for (int i = 0; i < cipherSuites.length; i++) - { + for (int i = 0; i < cipherSuites.length; i++) { cipherSuites[i] = cipherSuites[i].trim(); } return cipherSuites; } - public static String parseArrayIntoCommandSeparatedList(String[] suites) - { + public static String parseArrayIntoCommandSeparatedList(String[] suites) { StringBuilder supportedSuites = new StringBuilder(); - for (int i = 0; i < suites.length; i++) - { + for (int i = 0; i < suites.length; i++) { supportedSuites.append(suites[i]); supportedSuites.append(", "); } @@ -82,14 +80,11 @@ public class SSLSupport private static TrustManager[] loadTrustManager(final String trustStoreProvider, final String trustStorePath, - final String trustStorePassword) throws Exception - { - if (trustStorePath == null && (trustStoreProvider == null || (trustStoreProvider != null && !"PKCS11".equals(trustStoreProvider.toUpperCase())))) - { + final String trustStorePassword) throws Exception { + if (trustStorePath == null && (trustStoreProvider == null || (trustStoreProvider != null && !"PKCS11".equals(trustStoreProvider.toUpperCase())))) { return null; } - else - { + else { TrustManagerFactory trustMgrFactory; KeyStore trustStore = SSLSupport.loadKeystore(trustStoreProvider, trustStorePath, trustStorePassword); trustMgrFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); @@ -98,43 +93,37 @@ public class SSLSupport } } - private static KeyStore loadKeystore(final String keystoreProvider, final String keystorePath, final String keystorePassword) throws Exception - { + private static KeyStore loadKeystore(final String keystoreProvider, + final String keystorePath, + final String keystorePassword) throws Exception { KeyStore ks = KeyStore.getInstance(keystoreProvider); InputStream in = null; - try - { - if (keystorePath != null) - { + try { + if (keystorePath != null) { URL keystoreURL = SSLSupport.validateStoreURL(keystorePath); in = keystoreURL.openStream(); } ks.load(in, keystorePassword.toCharArray()); } - finally - { - if (in != null) - { - try - { + finally { + if (in != null) { + try { in.close(); } - catch (IOException ignored) - { + catch (IOException ignored) { } } } return ks; } - private static KeyManager[] loadKeyManagers(final String keyStoreProvider, final String keystorePath, final String keystorePassword) throws Exception - { - if (keystorePath == null && (keyStoreProvider == null || (keyStoreProvider != null && !"PKCS11".equals(keyStoreProvider.toUpperCase())))) - { + private static KeyManager[] loadKeyManagers(final String keyStoreProvider, + final String keystorePath, + final String keystorePassword) throws Exception { + if (keystorePath == null && (keyStoreProvider == null || (keyStoreProvider != null && !"PKCS11".equals(keyStoreProvider.toUpperCase())))) { return null; } - else - { + else { KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); KeyStore ks = SSLSupport.loadKeystore(keyStoreProvider, keystorePath, keystorePassword); kmf.init(ks, keystorePassword.toCharArray()); @@ -143,27 +132,21 @@ public class SSLSupport } } - private static URL validateStoreURL(final String storePath) throws Exception - { + private static URL validateStoreURL(final String storePath) throws Exception { assert storePath != null; // First see if this is a URL - try - { + try { return new URL(storePath); } - catch (MalformedURLException e) - { + catch (MalformedURLException e) { File file = new File(storePath); - if (file.exists() == true && file.isFile()) - { + if (file.exists() == true && file.isFile()) { return file.toURI().toURL(); } - else - { + else { URL url = findResource(storePath); - if (url != null) - { + if (url != null) { return url; } } @@ -172,16 +155,14 @@ public class SSLSupport throw new Exception("Failed to find a store at " + storePath); } - /** This seems duplicate code all over the place, but for security reasons we can't let something like this to be open in a - * utility class, as it would be a door to load anything you like in a safe VM. - * For that reason any class trying to do a privileged block should do with the AccessController directly. + /** + * This seems duplicate code all over the place, but for security reasons we can't let something like this to be open in a + * utility class, as it would be a door to load anything you like in a safe VM. + * For that reason any class trying to do a privileged block should do with the AccessController directly. */ - private static URL findResource(final String resourceName) - { - return AccessController.doPrivileged(new PrivilegedAction() - { - public URL run() - { + private static URL findResource(final String resourceName) { + return AccessController.doPrivileged(new PrivilegedAction() { + public URL run() { return ClassloadingUtil.findResource(resourceName); } }); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/security/ActiveMQPrincipal.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/security/ActiveMQPrincipal.java index fc023fed45..9be922357f 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/security/ActiveMQPrincipal.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/security/ActiveMQPrincipal.java @@ -16,25 +16,22 @@ */ package org.apache.activemq.artemis.core.security; -public class ActiveMQPrincipal -{ +public class ActiveMQPrincipal { + private final String userName; private final String password; - public ActiveMQPrincipal(String userName, String password) - { + public ActiveMQPrincipal(String userName, String password) { this.userName = userName; this.password = password; } - public String getUserName() - { + public String getUserName() { return userName; } - public String getPassword() - { + public String getPassword() { return password; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/security/Role.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/security/Role.java index 7f2cc75fc5..9f98472761 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/security/Role.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/security/Role.java @@ -21,8 +21,8 @@ import java.io.Serializable; /** * A role is used by the security store to define access rights and is configured on a connection factory or an address. */ -public class Role implements Serializable -{ +public class Role implements Serializable { + private static final long serialVersionUID = 3560097227776448872L; private final String name; @@ -48,10 +48,8 @@ public class Role implements Serializable final boolean deleteDurableQueue, final boolean createNonDurableQueue, final boolean deleteNonDurableQueue, - final boolean manage) - { - if (name == null) - { + final boolean manage) { + if (name == null) { throw new NullPointerException("name is null"); } this.name = name; @@ -64,68 +62,54 @@ public class Role implements Serializable this.manage = manage; } - public String getName() - { + public String getName() { return name; } - public boolean isSend() - { + public boolean isSend() { return send; } - public boolean isConsume() - { + public boolean isConsume() { return consume; } - public boolean isCreateDurableQueue() - { + public boolean isCreateDurableQueue() { return createDurableQueue; } - public boolean isDeleteDurableQueue() - { + public boolean isDeleteDurableQueue() { return deleteDurableQueue; } - public boolean isCreateNonDurableQueue() - { + public boolean isCreateNonDurableQueue() { return createNonDurableQueue; } - public boolean isDeleteNonDurableQueue() - { + public boolean isDeleteNonDurableQueue() { return deleteNonDurableQueue; } @Override - public String toString() - { + public String toString() { StringBuffer stringReturn = new StringBuffer("Role {name=" + name + "; allows=["); - if (send) - { + if (send) { stringReturn.append(" send "); } - if (consume) - { + if (consume) { stringReturn.append(" consume "); } - if (createDurableQueue) - { + if (createDurableQueue) { stringReturn.append(" createDurableQueue "); } - if (deleteDurableQueue) - { + if (deleteDurableQueue) { stringReturn.append(" deleteDurableQueue "); } - if (createNonDurableQueue) - { + if (createNonDurableQueue) { stringReturn.append(" createNonDurableQueue "); } - if (deleteNonDurableQueue) - { + if (deleteNonDurableQueue) { stringReturn.append(" deleteNonDurableQueue "); } @@ -135,45 +119,35 @@ public class Role implements Serializable } @Override - public boolean equals(final Object o) - { - if (this == o) - { + public boolean equals(final Object o) { + if (this == o) { return true; } - if (o == null || getClass() != o.getClass()) - { + if (o == null || getClass() != o.getClass()) { return false; } - Role role = (Role)o; + Role role = (Role) o; - if (consume != role.consume) - { + if (consume != role.consume) { return false; } - if (createDurableQueue != role.createDurableQueue) - { + if (createDurableQueue != role.createDurableQueue) { return false; } - if (createNonDurableQueue != role.createNonDurableQueue) - { + if (createNonDurableQueue != role.createNonDurableQueue) { return false; } - if (deleteDurableQueue != role.deleteDurableQueue) - { + if (deleteDurableQueue != role.deleteDurableQueue) { return false; } - if (deleteNonDurableQueue != role.deleteNonDurableQueue) - { + if (deleteNonDurableQueue != role.deleteNonDurableQueue) { return false; } - if (send != role.send) - { + if (send != role.send) { return false; } - if (!name.equals(role.name)) - { + if (!name.equals(role.name)) { return false; } @@ -181,8 +155,7 @@ public class Role implements Serializable } @Override - public int hashCode() - { + public int hashCode() { int result; result = name.hashCode(); result = 31 * result + (send ? 1 : 0); @@ -194,8 +167,7 @@ public class Role implements Serializable return result; } - public boolean isManage() - { + public boolean isManage() { return manage; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/server/QueueQueryResult.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/server/QueueQueryResult.java index 341cf5eb6d..f9740de024 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/server/QueueQueryResult.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/server/QueueQueryResult.java @@ -18,8 +18,8 @@ package org.apache.activemq.artemis.core.server; import org.apache.activemq.artemis.api.core.SimpleString; -public class QueueQueryResult -{ +public class QueueQueryResult { + private SimpleString name; private boolean exists; @@ -39,27 +39,25 @@ public class QueueQueryResult private boolean autoCreateJmsQueues; public QueueQueryResult(final SimpleString name, - final SimpleString address, - final boolean durable, - final boolean temporary, - final SimpleString filterString, - final int consumerCount, - final long messageCount, - final boolean autoCreateJmsQueues) - { + final SimpleString address, + final boolean durable, + final boolean temporary, + final SimpleString filterString, + final int consumerCount, + final long messageCount, + final boolean autoCreateJmsQueues) { this(name, address, durable, temporary, filterString, consumerCount, messageCount, autoCreateJmsQueues, true); } public QueueQueryResult(final SimpleString name, - final SimpleString address, - final boolean durable, - final boolean temporary, - final SimpleString filterString, - final int consumerCount, - final long messageCount, - final boolean autoCreateJmsQueues, - final boolean exists) - { + final SimpleString address, + final boolean durable, + final boolean temporary, + final SimpleString filterString, + final int consumerCount, + final long messageCount, + final boolean autoCreateJmsQueues, + final boolean exists) { this.durable = durable; this.temporary = temporary; @@ -79,48 +77,39 @@ public class QueueQueryResult this.exists = exists; } - public boolean isExists() - { + public boolean isExists() { return exists; } - public boolean isDurable() - { + public boolean isDurable() { return durable; } - public int getConsumerCount() - { + public int getConsumerCount() { return consumerCount; } - public long getMessageCount() - { + public long getMessageCount() { return messageCount; } - public SimpleString getFilterString() - { + public SimpleString getFilterString() { return filterString; } - public SimpleString getAddress() - { + public SimpleString getAddress() { return address; } - public SimpleString getName() - { + public SimpleString getName() { return name; } - public boolean isTemporary() - { + public boolean isTemporary() { return temporary; } - public boolean isAutoCreateJmsQueues() - { + public boolean isAutoCreateJmsQueues() { return autoCreateJmsQueues; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/server/management/Notification.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/server/management/Notification.java index 5eb9f05bcf..ae1f91db54 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/server/management/Notification.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/server/management/Notification.java @@ -21,42 +21,38 @@ import org.apache.activemq.artemis.utils.TypedProperties; /** * A Notification + * * @see org.apache.activemq.artemis.core.server.management.NotificationListener * @see NotificationType */ -public final class Notification -{ +public final class Notification { + private final NotificationType type; private final TypedProperties properties; private final String uid; - public Notification(final String uid, final NotificationType type, final TypedProperties properties) - { + public Notification(final String uid, final NotificationType type, final TypedProperties properties) { this.uid = uid; this.type = type; this.properties = properties; } - public NotificationType getType() - { + public NotificationType getType() { return type; } - public TypedProperties getProperties() - { + public TypedProperties getProperties() { return properties; } - public String getUID() - { + public String getUID() { return uid; } @Override - public String toString() - { + public String toString() { return "Notification[uid=" + uid + ", type=" + type + ", properties=" + properties + "]"; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/server/management/NotificationListener.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/server/management/NotificationListener.java index 18cf4cbcff..7dabeaea8f 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/server/management/NotificationListener.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/server/management/NotificationListener.java @@ -16,8 +16,7 @@ */ package org.apache.activemq.artemis.core.server.management; +public interface NotificationListener { -public interface NotificationListener -{ void onNotification(Notification notification); } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/server/management/NotificationService.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/server/management/NotificationService.java index d6625a6ce1..113bc346c7 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/server/management/NotificationService.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/server/management/NotificationService.java @@ -16,8 +16,8 @@ */ package org.apache.activemq.artemis.core.server.management; -public interface NotificationService -{ +public interface NotificationService { + /** * the message corresponding to a notification will always contain the properties: *
    diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/settings/impl/AddressFullMessagePolicy.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/settings/impl/AddressFullMessagePolicy.java index 4f6c3924d5..ca7158784b 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/settings/impl/AddressFullMessagePolicy.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/settings/impl/AddressFullMessagePolicy.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.core.settings.impl; -public enum AddressFullMessagePolicy -{ +public enum AddressFullMessagePolicy { DROP, PAGE, BLOCK, FAIL; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/transaction/impl/XidImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/transaction/impl/XidImpl.java index 65208e3641..f29bf32c4f 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/transaction/impl/XidImpl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/transaction/impl/XidImpl.java @@ -26,8 +26,8 @@ import org.apache.activemq.artemis.utils.Base64; /** * Xid implementation */ -public class XidImpl implements Xid, Serializable -{ +public class XidImpl implements Xid, Serializable { + private static final long serialVersionUID = 407053232840068514L; private final byte[] branchQualifier; @@ -42,14 +42,12 @@ public class XidImpl implements Xid, Serializable // Static -------------------------------------------------------- - public static String toBase64String(final Xid xid) - { + public static String toBase64String(final Xid xid) { byte[] data = XidImpl.toByteArray(xid); return Base64.encodeBytes(data, 0, data.length, Base64.DONT_BREAK_LINES | Base64.URL_SAFE); } - private static byte[] toByteArray(final Xid xid) - { + private static byte[] toByteArray(final Xid xid) { byte[] branchQualifier = xid.getBranchQualifier(); byte[] globalTransactionId = xid.getGlobalTransactionId(); int formatId = xid.getFormatId(); @@ -58,9 +56,8 @@ public class XidImpl implements Xid, Serializable System.arraycopy(branchQualifier, 0, hashBytes, 0, branchQualifier.length); System.arraycopy(globalTransactionId, 0, hashBytes, branchQualifier.length, globalTransactionId.length); byte[] intBytes = new byte[4]; - for (int i = 0; i < 4; i++) - { - intBytes[i] = (byte)((formatId >> i * 8) % 0xFF); + for (int i = 0; i < 4; i++) { + intBytes[i] = (byte) ((formatId >> i * 8) % 0xFF); } System.arraycopy(intBytes, 0, hashBytes, branchQualifier.length + globalTransactionId.length, 4); return hashBytes; @@ -70,12 +67,12 @@ public class XidImpl implements Xid, Serializable /** * Standard constructor + * * @param branchQualifier * @param formatId * @param globalTransactionId */ - public XidImpl(final byte[] branchQualifier, final int formatId, final byte[] globalTransactionId) - { + public XidImpl(final byte[] branchQualifier, final int formatId, final byte[] globalTransactionId) { this.branchQualifier = branchQualifier; this.formatId = formatId; this.globalTransactionId = globalTransactionId; @@ -83,10 +80,10 @@ public class XidImpl implements Xid, Serializable /** * Copy constructor + * * @param other */ - public XidImpl(final Xid other) - { + public XidImpl(final Xid other) { branchQualifier = copyBytes(other.getBranchQualifier()); formatId = other.getFormatId(); globalTransactionId = copyBytes(other.getGlobalTransactionId()); @@ -94,70 +91,55 @@ public class XidImpl implements Xid, Serializable // Xid implementation ------------------------------------------------------------------ - public byte[] getBranchQualifier() - { + public byte[] getBranchQualifier() { return branchQualifier; } - public int getFormatId() - { + public int getFormatId() { return formatId; } - public byte[] getGlobalTransactionId() - { + public byte[] getGlobalTransactionId() { return globalTransactionId; } // Public ------------------------------------------------------------------------------- @Override - public int hashCode() - { - if (!hashCalculated) - { + public int hashCode() { + if (!hashCalculated) { calcHash(); } return hash; } @Override - public boolean equals(final Object other) - { - if (this == other) - { + public boolean equals(final Object other) { + if (this == other) { return true; } - if (!(other instanceof Xid)) - { + if (!(other instanceof Xid)) { return false; } - Xid xother = (Xid)other; - if (xother.getFormatId() != formatId) - { + Xid xother = (Xid) other; + if (xother.getFormatId() != formatId) { return false; } - if (xother.getBranchQualifier().length != branchQualifier.length) - { + if (xother.getBranchQualifier().length != branchQualifier.length) { return false; } - if (xother.getGlobalTransactionId().length != globalTransactionId.length) - { + if (xother.getGlobalTransactionId().length != globalTransactionId.length) { return false; } - for (int i = 0; i < branchQualifier.length; i++) - { + for (int i = 0; i < branchQualifier.length; i++) { byte[] otherBQ = xother.getBranchQualifier(); - if (branchQualifier[i] != otherBQ[i]) - { + if (branchQualifier[i] != otherBQ[i]) { return false; } } - for (int i = 0; i < globalTransactionId.length; i++) - { + for (int i = 0; i < globalTransactionId.length; i++) { byte[] otherGtx = xother.getGlobalTransactionId(); - if (globalTransactionId[i] != otherGtx[i]) - { + if (globalTransactionId[i] != otherGtx[i]) { return false; } } @@ -165,31 +147,27 @@ public class XidImpl implements Xid, Serializable } @Override - public String toString() - { + public String toString() { return "XidImpl (" + System.identityHashCode(this) + - " bq:" + - stringRep(branchQualifier) + - " formatID:" + - formatId + - " gtxid:" + - stringRep(globalTransactionId) + - " base64:" + toBase64String(this); + " bq:" + + stringRep(branchQualifier) + + " formatID:" + + formatId + + " gtxid:" + + stringRep(globalTransactionId) + + " base64:" + toBase64String(this); } // Private ------------------------------------------------------------------------------- - private String stringRep(final byte[] bytes) - { + private String stringRep(final byte[] bytes) { StringBuffer buff = new StringBuffer(); - for (int i = 0; i < bytes.length; i++) - { + for (int i = 0; i < bytes.length; i++) { byte b = bytes[i]; buff.append(b); - if (i != bytes.length - 1) - { + if (i != bytes.length - 1) { buff.append('.'); } } @@ -197,15 +175,13 @@ public class XidImpl implements Xid, Serializable return buff.toString(); } - private void calcHash() - { + private void calcHash() { byte[] hashBytes = XidImpl.toByteArray(this); hash = Arrays.hashCode(hashBytes); hashCalculated = true; } - private byte[] copyBytes(final byte[] other) - { + private byte[] copyBytes(final byte[] other) { byte[] bytes = new byte[other.length]; System.arraycopy(other, 0, bytes, 0, other.length); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/version/Version.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/version/Version.java index 9327381a15..6e81309127 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/version/Version.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/version/Version.java @@ -16,8 +16,8 @@ */ package org.apache.activemq.artemis.core.version; -public interface Version -{ +public interface Version { + String getFullVersion(); String getVersionName(); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/version/impl/VersionImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/version/impl/VersionImpl.java index 9e1575d822..0394a11df3 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/version/impl/VersionImpl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/version/impl/VersionImpl.java @@ -21,8 +21,8 @@ import java.util.Arrays; import org.apache.activemq.artemis.core.version.Version; -public class VersionImpl implements Version, Serializable -{ +public class VersionImpl implements Version, Serializable { + private static final long serialVersionUID = -5271227256591080403L; private final String versionName; @@ -44,8 +44,7 @@ public class VersionImpl implements Version, Serializable final int minorVersion, final int microVersion, final int incrementingVersion, - final int[] compatibleVersionList) - { + final int[] compatibleVersionList) { this.versionName = versionName; this.majorVersion = majorVersion; @@ -61,42 +60,33 @@ public class VersionImpl implements Version, Serializable // Version implementation ------------------------------------------ - public String getFullVersion() - { + public String getFullVersion() { return versionName; } - public String getVersionName() - { + public String getVersionName() { return versionName; } - public int getMajorVersion() - { + public int getMajorVersion() { return majorVersion; } - public int getMinorVersion() - { + public int getMinorVersion() { return minorVersion; } - public int getMicroVersion() - { + public int getMicroVersion() { return microVersion; } - public int getIncrementingVersion() - { + public int getIncrementingVersion() { return incrementingVersion; } - public boolean isCompatible(int version) - { - for (int element : compatibleVersionList) - { - if (element == version) - { + public boolean isCompatible(int version) { + for (int element : compatibleVersionList) { + if (element == version) { return true; } } @@ -104,8 +94,7 @@ public class VersionImpl implements Version, Serializable } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(compatibleVersionList); @@ -118,50 +107,38 @@ public class VersionImpl implements Version, Serializable } @Override - public boolean equals(Object obj) - { - if (this == obj) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if (obj == null) - { + if (obj == null) { return false; } - if (!(obj instanceof VersionImpl)) - { + if (!(obj instanceof VersionImpl)) { return false; } - VersionImpl other = (VersionImpl)obj; - if (!Arrays.equals(compatibleVersionList, other.compatibleVersionList)) - { + VersionImpl other = (VersionImpl) obj; + if (!Arrays.equals(compatibleVersionList, other.compatibleVersionList)) { return false; } - if (incrementingVersion != other.incrementingVersion) - { + if (incrementingVersion != other.incrementingVersion) { return false; } - if (majorVersion != other.majorVersion) - { + if (majorVersion != other.majorVersion) { return false; } - if (microVersion != other.microVersion) - { + if (microVersion != other.microVersion) { return false; } - if (minorVersion != other.minorVersion) - { + if (minorVersion != other.minorVersion) { return false; } - if (versionName == null) - { - if (other.versionName != null) - { + if (versionName == null) { + if (other.versionName != null) { return false; } } - else if (!versionName.equals(other.versionName)) - { + else if (!versionName.equals(other.versionName)) { return false; } return true; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/reader/BytesMessageUtil.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/reader/BytesMessageUtil.java index c80159645e..806a321402 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/reader/BytesMessageUtil.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/reader/BytesMessageUtil.java @@ -18,82 +18,64 @@ package org.apache.activemq.artemis.reader; import org.apache.activemq.artemis.api.core.Message; -public class BytesMessageUtil extends MessageUtil -{ +public class BytesMessageUtil extends MessageUtil { - public static boolean bytesReadBoolean(Message message) - { + public static boolean bytesReadBoolean(Message message) { return getBodyBuffer(message).readBoolean(); } - public static byte bytesReadByte(Message message) - { + public static byte bytesReadByte(Message message) { return getBodyBuffer(message).readByte(); } - public static int bytesReadUnsignedByte(Message message) - { + public static int bytesReadUnsignedByte(Message message) { return getBodyBuffer(message).readUnsignedByte(); } - public static short bytesReadShort(Message message) - { + public static short bytesReadShort(Message message) { return getBodyBuffer(message).readShort(); } - public static int bytesReadUnsignedShort(Message message) - { + public static int bytesReadUnsignedShort(Message message) { return getBodyBuffer(message).readUnsignedShort(); } - public static char bytesReadChar(Message message) - { - return (char)getBodyBuffer(message).readShort(); + public static char bytesReadChar(Message message) { + return (char) getBodyBuffer(message).readShort(); } - public static int bytesReadInt(Message message) - { + public static int bytesReadInt(Message message) { return getBodyBuffer(message).readInt(); } - public static long bytesReadLong(Message message) - { + public static long bytesReadLong(Message message) { return getBodyBuffer(message).readLong(); } - public static float bytesReadFloat(Message message) - { + public static float bytesReadFloat(Message message) { return Float.intBitsToFloat(getBodyBuffer(message).readInt()); } - public static double bytesReadDouble(Message message) - { + public static double bytesReadDouble(Message message) { return Double.longBitsToDouble(getBodyBuffer(message).readLong()); } - public static String bytesReadUTF(Message message) - { + public static String bytesReadUTF(Message message) { return getBodyBuffer(message).readUTF(); } - - - public static int bytesReadBytes(Message message, final byte[] value) - { + public static int bytesReadBytes(Message message, final byte[] value) { return bytesReadBytes(message, value, value.length); } - public static int bytesReadBytes(Message message, final byte[] value, final int length) - { - if (!getBodyBuffer(message).readable()) - { + public static int bytesReadBytes(Message message, final byte[] value, final int length) { + if (!getBodyBuffer(message).readable()) { return -1; } int read = Math.min(length, getBodyBuffer(message).readableBytes()); - if (read != 0) - { + if (read != 0) { getBodyBuffer(message).readBytes(value, 0, read); } @@ -101,131 +83,99 @@ public class BytesMessageUtil extends MessageUtil } - - public static void bytesWriteBoolean(Message message, boolean value) - { + public static void bytesWriteBoolean(Message message, boolean value) { getBodyBuffer(message).writeBoolean(value); } - - - public static void bytesWriteByte(Message message, byte value) - { + public static void bytesWriteByte(Message message, byte value) { getBodyBuffer(message).writeByte(value); } - - - public static void bytesWriteShort(Message message, short value) - { + public static void bytesWriteShort(Message message, short value) { getBodyBuffer(message).writeShort(value); } - - public static void bytesWriteChar(Message message, char value) - { - getBodyBuffer(message).writeShort((short)value); + public static void bytesWriteChar(Message message, char value) { + getBodyBuffer(message).writeShort((short) value); } - public static void bytesWriteInt(Message message, int value) - { + public static void bytesWriteInt(Message message, int value) { getBodyBuffer(message).writeInt(value); } - public static void bytesWriteLong(Message message, long value) - { + public static void bytesWriteLong(Message message, long value) { getBodyBuffer(message).writeLong(value); } - public static void bytesWriteFloat(Message message, float value) - { + public static void bytesWriteFloat(Message message, float value) { getBodyBuffer(message).writeInt(Float.floatToIntBits(value)); } - public static void bytesWriteDouble(Message message, double value) - { + public static void bytesWriteDouble(Message message, double value) { getBodyBuffer(message).writeLong(Double.doubleToLongBits(value)); } - public static void bytesWriteUTF(Message message, String value) - { + public static void bytesWriteUTF(Message message, String value) { getBodyBuffer(message).writeUTF(value); } - public static void bytesWriteBytes(Message message, byte[] value) - { + public static void bytesWriteBytes(Message message, byte[] value) { getBodyBuffer(message).writeBytes(value); } - public static void bytesWriteBytes(Message message, final byte[] value, final int offset, final int length) - { + public static void bytesWriteBytes(Message message, final byte[] value, final int offset, final int length) { getBodyBuffer(message).writeBytes(value, offset, length); } - /** * Returns true if it could send the Object to any known format + * * @param message * @param value * @return */ - public static boolean bytesWriteObject(Message message, Object value) - { - if (value == null) - { + public static boolean bytesWriteObject(Message message, Object value) { + if (value == null) { throw new NullPointerException("Attempt to write a null value"); } - if (value instanceof String) - { + if (value instanceof String) { bytesWriteUTF(message, (String) value); } - else if (value instanceof Boolean) - { + else if (value instanceof Boolean) { bytesWriteBoolean(message, (Boolean) value); } - else if (value instanceof Character) - { + else if (value instanceof Character) { bytesWriteChar(message, (Character) value); } - else if (value instanceof Byte) - { + else if (value instanceof Byte) { bytesWriteByte(message, (Byte) value); } - else if (value instanceof Short) - { + else if (value instanceof Short) { bytesWriteShort(message, (Short) value); } - else if (value instanceof Integer) - { + else if (value instanceof Integer) { bytesWriteInt(message, (Integer) value); } - else if (value instanceof Long) - { + else if (value instanceof Long) { bytesWriteLong(message, (Long) value); } - else if (value instanceof Float) - { + else if (value instanceof Float) { bytesWriteFloat(message, (Float) value); } - else if (value instanceof Double) - { + else if (value instanceof Double) { bytesWriteDouble(message, (Double) value); } - else if (value instanceof byte[]) - { + else if (value instanceof byte[]) { bytesWriteBytes(message, (byte[]) value); } - else - { + else { return false; } - return true; } - public static void bytesMessageReset(Message message) - { + public static void bytesMessageReset(Message message) { getBodyBuffer(message).resetReaderIndex(); } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/reader/MapMessageUtil.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/reader/MapMessageUtil.java index 6f4035a0cd..9ae4798634 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/reader/MapMessageUtil.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/reader/MapMessageUtil.java @@ -20,14 +20,12 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.Message; import org.apache.activemq.artemis.utils.TypedProperties; -public class MapMessageUtil extends MessageUtil -{ +public class MapMessageUtil extends MessageUtil { /** * Utility method to set the map on a message body */ - public static void writeBodyMap(Message message, TypedProperties properties) - { + public static void writeBodyMap(Message message, TypedProperties properties) { ActiveMQBuffer buff = getBodyBuffer(message); buff.resetWriterIndex(); properties.encode(buff); @@ -36,8 +34,7 @@ public class MapMessageUtil extends MessageUtil /** * Utility method to set the map on a message body */ - public static TypedProperties readBodyMap(Message message) - { + public static TypedProperties readBodyMap(Message message) { TypedProperties map = new TypedProperties(); readBodyMap(message, map); return map; @@ -46,13 +43,10 @@ public class MapMessageUtil extends MessageUtil /** * Utility method to set the map on a message body */ - public static void readBodyMap(Message message, TypedProperties map) - { + public static void readBodyMap(Message message, TypedProperties map) { ActiveMQBuffer buff = getBodyBuffer(message); buff.resetReaderIndex(); map.decode(buff); } - - } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/reader/MessageUtil.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/reader/MessageUtil.java index f017c082e6..9f1a598600 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/reader/MessageUtil.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/reader/MessageUtil.java @@ -32,8 +32,8 @@ import org.apache.activemq.artemis.api.core.SimpleString; * * This provides a helper for core message to act some of the JMS functions used by the JMS wrapper */ -public class MessageUtil -{ +public class MessageUtil { + public static final SimpleString CORRELATIONID_HEADER_NAME = new SimpleString("JMSCorrelationID"); public static final SimpleString REPLYTO_HEADER_NAME = new SimpleString("JMSReplyTo"); @@ -52,137 +52,99 @@ public class MessageUtil public static final SimpleString CONNECTION_ID_PROPERTY_NAME = new SimpleString("__AMQ_CID"); - - - public static ActiveMQBuffer getBodyBuffer(Message message) - { + public static ActiveMQBuffer getBodyBuffer(Message message) { return message.getBodyBuffer(); } - - - public static byte[] getJMSCorrelationIDAsBytes(Message message) - { + public static byte[] getJMSCorrelationIDAsBytes(Message message) { Object obj = message.getObjectProperty(CORRELATIONID_HEADER_NAME); - if (obj instanceof byte[]) - { - return (byte[])obj; + if (obj instanceof byte[]) { + return (byte[]) obj; } - else - { + else { return null; } } - - - public static void setJMSType(Message message, String type) - { + public static void setJMSType(Message message, String type) { message.putStringProperty(TYPE_HEADER_NAME, new SimpleString(type)); } - public static String getJMSType(Message message) - { + public static String getJMSType(Message message) { SimpleString ss = message.getSimpleStringProperty(TYPE_HEADER_NAME); - if (ss != null) - { + if (ss != null) { return ss.toString(); } - else - { + else { return null; } } - - public static final void setJMSCorrelationIDAsBytes(Message message, final byte[] correlationID) throws ActiveMQException - { - if (correlationID == null || correlationID.length == 0) - { + public static final void setJMSCorrelationIDAsBytes(Message message, + final byte[] correlationID) throws ActiveMQException { + if (correlationID == null || correlationID.length == 0) { throw new ActiveMQException("Please specify a non-zero length byte[]"); } message.putBytesProperty(CORRELATIONID_HEADER_NAME, correlationID); } - public static void setJMSCorrelationID(Message message, final String correlationID) - { - if (correlationID == null) - { + public static void setJMSCorrelationID(Message message, final String correlationID) { + if (correlationID == null) { message.removeProperty(CORRELATIONID_HEADER_NAME); } - else - { + else { message.putStringProperty(CORRELATIONID_HEADER_NAME, new SimpleString(correlationID)); } } - public static String getJMSCorrelationID(Message message) - { - try - { + public static String getJMSCorrelationID(Message message) { + try { return message.getStringProperty(CORRELATIONID_HEADER_NAME); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { return null; } } - - public static SimpleString getJMSReplyTo(Message message) - { + public static SimpleString getJMSReplyTo(Message message) { return message.getSimpleStringProperty(REPLYTO_HEADER_NAME); } - public static void setJMSReplyTo(Message message, final SimpleString dest) - { + public static void setJMSReplyTo(Message message, final SimpleString dest) { - if (dest == null) - { + if (dest == null) { message.removeProperty(REPLYTO_HEADER_NAME); } - else - { + else { message.putStringProperty(REPLYTO_HEADER_NAME, dest); } } - - - public static void clearProperties(Message message) - { + public static void clearProperties(Message message) { List toRemove = new ArrayList(); - for (SimpleString propName : message.getPropertyNames()) - { + for (SimpleString propName : message.getPropertyNames()) { if (!propName.startsWith(JMS) || propName.startsWith(JMSX) || - propName.startsWith(JMS_)) - { + propName.startsWith(JMS_)) { toRemove.add(propName); } } - for (SimpleString propName : toRemove) - { + for (SimpleString propName : toRemove) { message.removeProperty(propName); } } - - - public static Set getPropertyNames(Message message) - { + public static Set getPropertyNames(Message message) { HashSet set = new HashSet(); - for (SimpleString propName : message.getPropertyNames()) - { + for (SimpleString propName : message.getPropertyNames()) { if ((!propName.startsWith(JMS) || propName.startsWith(JMSX) || - propName.startsWith(JMS_)) && !propName.startsWith(CONNECTION_ID_PROPERTY_NAME)) - { + propName.startsWith(JMS_)) && !propName.startsWith(CONNECTION_ID_PROPERTY_NAME)) { set.add(propName.toString()); } } @@ -192,10 +154,8 @@ public class MessageUtil return set; } - public static boolean propertyExists(Message message, String name) - { + public static boolean propertyExists(Message message, String name) { return message.containsProperty(new SimpleString(name)) || name.equals(MessageUtil.JMSXDELIVERYCOUNT) || - MessageUtil.JMSXGROUPID.equals(name) && - message.containsProperty(Message.HDR_GROUP_ID); + MessageUtil.JMSXGROUPID.equals(name) && message.containsProperty(Message.HDR_GROUP_ID); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/reader/StreamMessageUtil.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/reader/StreamMessageUtil.java index fdb3db1e58..d59662fe0b 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/reader/StreamMessageUtil.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/reader/StreamMessageUtil.java @@ -21,8 +21,8 @@ import org.apache.activemq.artemis.api.core.Message; import org.apache.activemq.artemis.api.core.Pair; import org.apache.activemq.artemis.utils.DataConstants; -public class StreamMessageUtil extends MessageUtil -{ +public class StreamMessageUtil extends MessageUtil { + /** * Method to read boolean values out of the Stream protocol existent on JMS Stream Messages * Throws IllegalStateException if the type was invalid @@ -30,13 +30,11 @@ public class StreamMessageUtil extends MessageUtil * @param message * @return */ - public static boolean streamReadBoolean(Message message) - { + public static boolean streamReadBoolean(Message message) { ActiveMQBuffer buff = getBodyBuffer(message); byte type = buff.readByte(); - switch (type) - { + switch (type) { case DataConstants.BOOLEAN: return buff.readBoolean(); case DataConstants.STRING: @@ -48,15 +46,12 @@ public class StreamMessageUtil extends MessageUtil } - public static byte streamReadByte(Message message) - { + public static byte streamReadByte(Message message) { ActiveMQBuffer buff = getBodyBuffer(message); int index = buff.readerIndex(); - try - { + try { byte type = buff.readByte(); - switch (type) - { + switch (type) { case DataConstants.BYTE: return buff.readByte(); case DataConstants.STRING: @@ -66,20 +61,17 @@ public class StreamMessageUtil extends MessageUtil throw new IllegalStateException("Invalid conversion"); } } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { buff.readerIndex(index); throw e; } } - public static short streamReadShort(Message message) - { + public static short streamReadShort(Message message) { ActiveMQBuffer buff = getBodyBuffer(message); byte type = buff.readByte(); - switch (type) - { + switch (type) { case DataConstants.BYTE: return buff.readByte(); case DataConstants.SHORT: @@ -92,22 +84,18 @@ public class StreamMessageUtil extends MessageUtil } } - public static char streamReadChar(Message message) - { + public static char streamReadChar(Message message) { ActiveMQBuffer buff = getBodyBuffer(message); byte type = buff.readByte(); - switch (type) - { + switch (type) { case DataConstants.CHAR: - return (char)buff.readShort(); + return (char) buff.readShort(); case DataConstants.STRING: String str = buff.readNullableString(); - if (str == null) - { + if (str == null) { throw new NullPointerException("Invalid conversion"); } - else - { + else { throw new IllegalStateException("Invalid conversion"); } default: @@ -116,12 +104,10 @@ public class StreamMessageUtil extends MessageUtil } - public static int streamReadInteger(Message message) - { + public static int streamReadInteger(Message message) { ActiveMQBuffer buff = getBodyBuffer(message); byte type = buff.readByte(); - switch (type) - { + switch (type) { case DataConstants.BYTE: return buff.readByte(); case DataConstants.SHORT: @@ -136,13 +122,10 @@ public class StreamMessageUtil extends MessageUtil } } - - public static long streamReadLong(Message message) - { + public static long streamReadLong(Message message) { ActiveMQBuffer buff = getBodyBuffer(message); byte type = buff.readByte(); - switch (type) - { + switch (type) { case DataConstants.BYTE: return buff.readByte(); case DataConstants.SHORT: @@ -159,12 +142,10 @@ public class StreamMessageUtil extends MessageUtil } } - public static float streamReadFloat(Message message) - { + public static float streamReadFloat(Message message) { ActiveMQBuffer buff = getBodyBuffer(message); byte type = buff.readByte(); - switch (type) - { + switch (type) { case DataConstants.FLOAT: return Float.intBitsToFloat(buff.readInt()); case DataConstants.STRING: @@ -175,13 +156,10 @@ public class StreamMessageUtil extends MessageUtil } } - - public static double streamReadDouble(Message message) - { + public static double streamReadDouble(Message message) { ActiveMQBuffer buff = getBodyBuffer(message); byte type = buff.readByte(); - switch (type) - { + switch (type) { case DataConstants.FLOAT: return Float.intBitsToFloat(buff.readInt()); case DataConstants.DOUBLE: @@ -194,13 +172,10 @@ public class StreamMessageUtil extends MessageUtil } } - - public static String streamReadString(Message message) - { + public static String streamReadString(Message message) { ActiveMQBuffer buff = getBodyBuffer(message); byte type = buff.readByte(); - switch (type) - { + switch (type) { case DataConstants.BOOLEAN: return String.valueOf(buff.readBoolean()); case DataConstants.BYTE: @@ -208,7 +183,7 @@ public class StreamMessageUtil extends MessageUtil case DataConstants.SHORT: return String.valueOf(buff.readShort()); case DataConstants.CHAR: - return String.valueOf((char)buff.readShort()); + return String.valueOf((char) buff.readShort()); case DataConstants.INT: return String.valueOf(buff.readInt()); case DataConstants.LONG: @@ -227,23 +202,20 @@ public class StreamMessageUtil extends MessageUtil /** * Utility for reading bytes out of streaming. * It will return remainingBytes, bytesRead + * * @param remainingBytes remaining Bytes from previous read. Send it to 0 if it was the first call for the message * @param message * @return a pair of remaining bytes and bytes read */ - public static Pair streamReadBytes(Message message, int remainingBytes, byte[] value) - { + public static Pair streamReadBytes(Message message, int remainingBytes, byte[] value) { ActiveMQBuffer buff = getBodyBuffer(message); - if (remainingBytes == -1) - { + if (remainingBytes == -1) { return new Pair<>(0, -1); } - else if (remainingBytes == 0) - { + else if (remainingBytes == 0) { byte type = buff.readByte(); - if (type != DataConstants.BYTES) - { + if (type != DataConstants.BYTES) { throw new IllegalStateException("Invalid conversion"); } remainingBytes = buff.readInt(); @@ -251,21 +223,18 @@ public class StreamMessageUtil extends MessageUtil int read = Math.min(value.length, remainingBytes); buff.readBytes(value, 0, read); remainingBytes -= read; - if (remainingBytes == 0) - { + if (remainingBytes == 0) { remainingBytes = -1; } return new Pair<>(remainingBytes, read); } - public static Object streamReadObject(Message message) - { + public static Object streamReadObject(Message message) { ActiveMQBuffer buff = getBodyBuffer(message); byte type = buff.readByte(); - switch (type) - { + switch (type) { case DataConstants.BOOLEAN: return buff.readBoolean(); case DataConstants.BYTE: @@ -273,7 +242,7 @@ public class StreamMessageUtil extends MessageUtil case DataConstants.SHORT: return buff.readShort(); case DataConstants.CHAR: - return (char)buff.readShort(); + return (char) buff.readShort(); case DataConstants.INT: return buff.readInt(); case DataConstants.LONG: @@ -295,5 +264,4 @@ public class StreamMessageUtil extends MessageUtil } - } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/reader/TextMessageUtil.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/reader/TextMessageUtil.java index 07abeb8c84..c7515fc365 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/reader/TextMessageUtil.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/reader/TextMessageUtil.java @@ -20,14 +20,12 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.Message; import org.apache.activemq.artemis.api.core.SimpleString; -public class TextMessageUtil extends MessageUtil -{ +public class TextMessageUtil extends MessageUtil { /** * Utility method to set the Text message on a message body */ - public static void writeBodyText(Message message, SimpleString text) - { + public static void writeBodyText(Message message, SimpleString text) { ActiveMQBuffer buff = getBodyBuffer(message); buff.clear(); buff.writeNullableSimpleString(text); @@ -36,8 +34,7 @@ public class TextMessageUtil extends MessageUtil /** * Utility method to set the Text message on a message body */ - public static SimpleString readBodyText(Message message) - { + public static SimpleString readBodyText(Message message) { ActiveMQBuffer buff = getBodyBuffer(message); buff.resetReaderIndex(); return buff.readNullableSimpleString(); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/protocol/AbstractRemotingConnection.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/protocol/AbstractRemotingConnection.java index 7f359b7e1b..453a87cb72 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/protocol/AbstractRemotingConnection.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/protocol/AbstractRemotingConnection.java @@ -30,8 +30,8 @@ import org.apache.activemq.artemis.core.remoting.CloseListener; import org.apache.activemq.artemis.core.remoting.FailureListener; import org.apache.activemq.artemis.spi.core.remoting.Connection; -public abstract class AbstractRemotingConnection implements RemotingConnection -{ +public abstract class AbstractRemotingConnection implements RemotingConnection { + protected final List failureListeners = new CopyOnWriteArrayList(); protected final List closeListeners = new CopyOnWriteArrayList(); protected final Connection transportConnection; @@ -39,35 +39,28 @@ public abstract class AbstractRemotingConnection implements RemotingConnection protected final long creationTime; protected volatile boolean dataReceived; - public AbstractRemotingConnection(final Connection transportConnection, final Executor executor) - { + public AbstractRemotingConnection(final Connection transportConnection, final Executor executor) { this.transportConnection = transportConnection; this.executor = executor; this.creationTime = System.currentTimeMillis(); } - public List getFailureListeners() - { + public List getFailureListeners() { return new ArrayList(failureListeners); } - protected void callFailureListeners(final ActiveMQException me, String scaleDownTargetNodeID) - { + protected void callFailureListeners(final ActiveMQException me, String scaleDownTargetNodeID) { final List listenersClone = new ArrayList(failureListeners); - for (final FailureListener listener : listenersClone) - { - try - { + for (final FailureListener listener : listenersClone) { + try { listener.connectionFailed(me, false, scaleDownTargetNodeID); } - catch (ActiveMQInterruptedException interrupted) - { + catch (ActiveMQInterruptedException interrupted) { // this is an expected behaviour.. no warn or error here ActiveMQClientLogger.LOGGER.debug("thread interrupted", interrupted); } - catch (final Throwable t) - { + catch (final Throwable t) { // Failure of one listener to execute shouldn't prevent others // from // executing @@ -76,19 +69,14 @@ public abstract class AbstractRemotingConnection implements RemotingConnection } } - - protected void callClosingListeners() - { + protected void callClosingListeners() { final List listenersClone = new ArrayList(closeListeners); - for (final CloseListener listener : listenersClone) - { - try - { + for (final CloseListener listener : listenersClone) { + try { listener.connectionClosed(); } - catch (final Throwable t) - { + catch (final Throwable t) { // Failure of one listener to execute shouldn't prevent others // from // executing @@ -97,64 +85,52 @@ public abstract class AbstractRemotingConnection implements RemotingConnection } } - public void setFailureListeners(final List listeners) - { + public void setFailureListeners(final List listeners) { failureListeners.clear(); failureListeners.addAll(listeners); } - public Object getID() - { + public Object getID() { return transportConnection.getID(); } - public String getRemoteAddress() - { + public String getRemoteAddress() { return transportConnection.getRemoteAddress(); } - public void addFailureListener(final FailureListener listener) - { - if (listener == null) - { + public void addFailureListener(final FailureListener listener) { + if (listener == null) { throw ActiveMQClientMessageBundle.BUNDLE.failListenerCannotBeNull(); } failureListeners.add(listener); } - public boolean removeFailureListener(final FailureListener listener) - { - if (listener == null) - { + public boolean removeFailureListener(final FailureListener listener) { + if (listener == null) { throw ActiveMQClientMessageBundle.BUNDLE.failListenerCannotBeNull(); } return failureListeners.remove(listener); } - public void addCloseListener(final CloseListener listener) - { - if (listener == null) - { + public void addCloseListener(final CloseListener listener) { + if (listener == null) { throw ActiveMQClientMessageBundle.BUNDLE.closeListenerCannotBeNull(); } closeListeners.add(listener); } - public boolean removeCloseListener(final CloseListener listener) - { - if (listener == null) - { + public boolean removeCloseListener(final CloseListener listener) { + if (listener == null) { throw ActiveMQClientMessageBundle.BUNDLE.closeListenerCannotBeNull(); } return closeListeners.remove(listener); } - public List removeCloseListeners() - { + public List removeCloseListeners() { List ret = new ArrayList(closeListeners); closeListeners.clear(); @@ -162,8 +138,7 @@ public abstract class AbstractRemotingConnection implements RemotingConnection return ret; } - public List removeFailureListeners() - { + public List removeFailureListeners() { List ret = getFailureListeners(); failureListeners.clear(); @@ -171,30 +146,25 @@ public abstract class AbstractRemotingConnection implements RemotingConnection return ret; } - public void setCloseListeners(List listeners) - { + public void setCloseListeners(List listeners) { closeListeners.clear(); closeListeners.addAll(listeners); } - public ActiveMQBuffer createTransportBuffer(final int size) - { + public ActiveMQBuffer createTransportBuffer(final int size) { return transportConnection.createTransportBuffer(size); } - public Connection getTransportConnection() - { + public Connection getTransportConnection() { return transportConnection; } - public long getCreationTime() - { + public long getCreationTime() { return creationTime; } - public boolean checkDataReceived() - { + public boolean checkDataReceived() { boolean res = dataReceived; dataReceived = false; @@ -205,13 +175,11 @@ public abstract class AbstractRemotingConnection implements RemotingConnection /* * This can be called concurrently by more than one thread so needs to be locked */ - public void fail(final ActiveMQException me) - { + public void fail(final ActiveMQException me) { fail(me, null); } - public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) - { + public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) { dataReceived = true; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/protocol/ConnectionEntry.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/protocol/ConnectionEntry.java index 9004af071f..96a96aa66d 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/protocol/ConnectionEntry.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/protocol/ConnectionEntry.java @@ -18,9 +18,8 @@ package org.apache.activemq.artemis.spi.core.protocol; import java.util.concurrent.Executor; +public class ConnectionEntry { -public class ConnectionEntry -{ public final RemotingConnection connection; public volatile long lastCheck; @@ -29,13 +28,14 @@ public class ConnectionEntry public final Executor connectionExecutor; - public Object getID() - { + public Object getID() { return connection.getID(); } - public ConnectionEntry(final RemotingConnection connection, final Executor connectionExecutor, final long lastCheck, final long ttl) - { + public ConnectionEntry(final RemotingConnection connection, + final Executor connectionExecutor, + final long lastCheck, + final long ttl) { this.connection = connection; this.lastCheck = lastCheck; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/protocol/RemotingConnection.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/protocol/RemotingConnection.java index 99cefa555f..420314b44e 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/protocol/RemotingConnection.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/protocol/RemotingConnection.java @@ -32,10 +32,11 @@ import org.apache.activemq.artemis.spi.core.remoting.Connection; * Perhaps a better name for this class now would be ProtocolConnection as this * represents the link with the used protocol */ -public interface RemotingConnection extends BufferHandler -{ +public interface RemotingConnection extends BufferHandler { + /** * Returns the unique id of the {@link RemotingConnection}. + * * @return the id */ Object getID(); @@ -90,7 +91,6 @@ public interface RemotingConnection extends BufferHandler void setCloseListeners(List listeners); - /** * return all the failure listeners * @@ -100,7 +100,6 @@ public interface RemotingConnection extends BufferHandler List removeFailureListeners(); - /** * set the failure listeners. *

    @@ -129,7 +128,7 @@ public interface RemotingConnection extends BufferHandler /** * called when the underlying connection fails. * - * @param me the exception that caused the failure + * @param me the exception that caused the failure * @param scaleDownTargetNodeID the ID of the node where scale down is targeted */ void fail(ActiveMQException me, String scaleDownTargetNodeID); @@ -148,12 +147,14 @@ public interface RemotingConnection extends BufferHandler /** * Returns whether or not the {@link RemotingConnection} is a client + * * @return true if client, false if a server */ boolean isClient(); /** * Returns true if this {@link RemotingConnection} has been destroyed. + * * @return true if destroyed, otherwise false */ boolean isDestroyed(); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/AbstractConnector.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/AbstractConnector.java index f20ad727e3..fbf86c9a0e 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/AbstractConnector.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/AbstractConnector.java @@ -21,12 +21,11 @@ import java.util.Map; /** * Abstract connector */ -public abstract class AbstractConnector implements Connector -{ +public abstract class AbstractConnector implements Connector { + protected final Map configuration; - protected AbstractConnector(Map configuration) - { + protected AbstractConnector(Map configuration) { this.configuration = configuration; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/BufferDecoder.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/BufferDecoder.java index 7bc01a554a..b96c2621a5 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/BufferDecoder.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/BufferDecoder.java @@ -18,13 +18,14 @@ package org.apache.activemq.artemis.spi.core.remoting; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; -public interface BufferDecoder -{ +public interface BufferDecoder { + /** * called by the remoting system prior to {@link org.apache.activemq.artemis.spi.core.remoting.BufferHandler#bufferReceived(Object, ActiveMQBuffer)}. *

    * The implementation should return true if there is enough data in the buffer to decode. otherwise false. - * * @param buffer the buffer + * * @param buffer the buffer + * * @return true id the buffer can be decoded.. */ int isReadyToHandle(ActiveMQBuffer buffer); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/BufferHandler.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/BufferHandler.java index c728350229..5f390a1728 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/BufferHandler.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/BufferHandler.java @@ -23,8 +23,8 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; *

    * The Buffer Handler will decode the buffer and take the appropriate action, typically forwarding to the correct channel. */ -public interface BufferHandler -{ +public interface BufferHandler { + /** * called by the remoting connection when a buffer is received. * diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ClientProtocolManager.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ClientProtocolManager.java index c10e3256d5..a3f83dc15a 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ClientProtocolManager.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ClientProtocolManager.java @@ -25,12 +25,16 @@ import org.apache.activemq.artemis.api.core.Interceptor; import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; -public interface ClientProtocolManager -{ +public interface ClientProtocolManager { /// Life Cycle Methods: - RemotingConnection connect(Connection transportConnection, long callTimeout, long callFailoverTimeout, List incomingInterceptors, List outgoingInterceptors, TopologyResponseHandler topologyResponseHandler); + RemotingConnection connect(Connection transportConnection, + long callTimeout, + long callFailoverTimeout, + List incomingInterceptors, + List outgoingInterceptors, + TopologyResponseHandler topologyResponseHandler); RemotingConnection getCurrentConnection(); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ClientProtocolManagerFactory.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ClientProtocolManagerFactory.java index 16adbd2782..c9c78a552c 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ClientProtocolManagerFactory.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ClientProtocolManagerFactory.java @@ -16,8 +16,7 @@ */ package org.apache.activemq.artemis.spi.core.remoting; -public interface ClientProtocolManagerFactory -{ +public interface ClientProtocolManagerFactory { ClientProtocolManager newProtocolManager(); } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/Connection.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/Connection.java index d637f8bab4..76e5a3d7df 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/Connection.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/Connection.java @@ -25,8 +25,8 @@ import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; /** * The connection used by a channel to write data to. */ -public interface Connection -{ +public interface Connection { + /** * Create a new ActiveMQBuffer of the given size. * @@ -35,7 +35,6 @@ public interface Connection */ ActiveMQBuffer createTransportBuffer(int size); - RemotingConnection getProtocolConnection(); void setProtocolConnection(RemotingConnection connection); @@ -50,8 +49,8 @@ public interface Connection /** * writes the buffer to the connection and if flush is true returns only when the buffer has been physically written to the connection. * - * @param buffer the buffer to write - * @param flush whether to flush the buffers onto the wire + * @param buffer the buffer to write + * @param flush whether to flush the buffers onto the wire * @param batched whether the packet is allowed to batched for better performance */ void write(ActiveMQBuffer buffer, boolean flush, boolean batched); @@ -59,8 +58,8 @@ public interface Connection /** * writes the buffer to the connection and if flush is true returns only when the buffer has been physically written to the connection. * - * @param buffer the buffer to write - * @param flush whether to flush the buffers onto the wire + * @param buffer the buffer to write + * @param flush whether to flush the buffers onto the wire * @param batched whether the packet is allowed to batched for better performance */ void write(ActiveMQBuffer buffer, boolean flush, boolean batched, ChannelFutureListener futureListener); @@ -72,7 +71,6 @@ public interface Connection */ void write(ActiveMQBuffer buffer); - /** * This should close the internal channel without calling any listeners. * This is to avoid a situation where the broker is busy writing on an internal thread. @@ -87,6 +85,7 @@ public interface Connection /** * Returns a string representation of the remote address this connection is connected to. + * * @return the remote address */ String getRemoteAddress(); @@ -103,6 +102,7 @@ public interface Connection /** * Generates a {@link TransportConfiguration} to be used to connect to the same target this is * connected to. + * * @return TransportConfiguration */ TransportConfiguration getConnectorConfig(); @@ -112,6 +112,7 @@ public interface Connection /** * the InVM Connection has some special handling as it doesn't use Netty ProtocolChannel * we will use this method Instead of using instanceof + * * @return */ boolean isUsingProtocolHandling(); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ConnectionLifeCycleListener.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ConnectionLifeCycleListener.java index d81bbc6e31..b5d7d975fe 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ConnectionLifeCycleListener.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ConnectionLifeCycleListener.java @@ -22,8 +22,8 @@ import org.apache.activemq.artemis.core.server.ActiveMQComponent; /** * A ConnectionLifeCycleListener is called by the remoting implementation to notify of connection events. */ -public interface ConnectionLifeCycleListener -{ +public interface ConnectionLifeCycleListener { + /** * This method is used both by client connector creation and server connection creation through * acceptors. On the client side the {@code component} parameter is normally passed as @@ -34,23 +34,25 @@ public interface ConnectionLifeCycleListener * activemq-server and activemq-client packages while avoiding to pull too much into activemq-core. * The pivotal point keeping us from removing the method is {@link ConnectorFactory} and the * usage of it. - * @param component This will probably be an {@code Acceptor} and only used on the server side. + * + * @param component This will probably be an {@code Acceptor} and only used on the server side. * @param connection the connection that has been created - * @param protocol the messaging protocol type this connection uses + * @param protocol the messaging protocol type this connection uses */ void connectionCreated(ActiveMQComponent component, Connection connection, String protocol); /** * Called when a connection is destroyed. + * * @param connectionID the connection being destroyed. */ void connectionDestroyed(Object connectionID); - /** * Called when an error occurs on the connection. + * * @param connectionID the id of the connection. - * @param me the exception. + * @param me the exception. */ void connectionException(Object connectionID, ActiveMQException me); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/Connector.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/Connector.java index 05d515841f..0f17469576 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/Connector.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/Connector.java @@ -21,8 +21,8 @@ import java.util.Map; /** * A Connector is used by the client for creating and controlling a connection. */ -public interface Connector -{ +public interface Connector { + /** * starts the connector */ @@ -54,6 +54,7 @@ public interface Connector * If the configuration is equivalent to this connector, which means * if the parameter configuration is used to create a connection to a target * node, it will be the same node as of the connections made with this connector. + * * @param configuration * @return true means the configuration is equivalent to the connector. false otherwise. */ diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ConnectorFactory.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ConnectorFactory.java index a1ad5f90e5..3d7c7b30d6 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ConnectorFactory.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ConnectorFactory.java @@ -27,8 +27,8 @@ import org.apache.activemq.artemis.api.core.TransportConfigurationHelper; *

    * A Connector is used to connect to an org.apache.activemq.artemis.spi.core.remoting.Acceptor. */ -public interface ConnectorFactory extends TransportConfigurationHelper -{ +public interface ConnectorFactory extends TransportConfigurationHelper { + /** * creates a new instance of a connector. * diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ConsumerContext.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ConsumerContext.java index 560636fdfa..f2c70cf192 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ConsumerContext.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ConsumerContext.java @@ -16,6 +16,6 @@ */ package org.apache.activemq.artemis.spi.core.remoting; -public abstract class ConsumerContext -{ +public abstract class ConsumerContext { + } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ReadyListener.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ReadyListener.java index aa0a124219..b846a1a1c8 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ReadyListener.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ReadyListener.java @@ -16,8 +16,8 @@ */ package org.apache.activemq.artemis.spi.core.remoting; -public interface ReadyListener -{ +public interface ReadyListener { + void readyForWriting(boolean ready); } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/SessionContext.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/SessionContext.java index 2bbbece4f4..3f1cc14e2d 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/SessionContext.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/SessionContext.java @@ -37,8 +37,8 @@ import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; import org.apache.activemq.artemis.utils.IDGenerator; import org.apache.activemq.artemis.utils.SimpleIDGenerator; -public abstract class SessionContext -{ +public abstract class SessionContext { + protected ClientSessionInternal session; protected SendAcknowledgementHandler sendAckHandler; @@ -47,20 +47,15 @@ public abstract class SessionContext protected final IDGenerator idGenerator = new SimpleIDGenerator(0); - - public SessionContext(RemotingConnection remotingConnection) - { + public SessionContext(RemotingConnection remotingConnection) { this.remotingConnection = remotingConnection; } - - public ClientSessionInternal getSession() - { + public ClientSessionInternal getSession() { return session; } - public void setSession(ClientSessionInternal session) - { + public void setSession(ClientSessionInternal session) { this.session = session; } @@ -73,61 +68,55 @@ public abstract class SessionContext */ public abstract boolean reattachOnNewConnection(RemotingConnection newConnection) throws ActiveMQException; - public RemotingConnection getRemotingConnection() - { + public RemotingConnection getRemotingConnection() { return remotingConnection; } - public abstract void closeConsumer(ClientConsumer consumer) throws ActiveMQException; public abstract void sendConsumerCredits(ClientConsumer consumer, int credits); public abstract boolean supportsLargeMessage(); - protected void handleReceiveLargeMessage(ConsumerContext consumerID, ClientLargeMessageInternal clientLargeMessage, long largeMessageSize) throws Exception - { + protected void handleReceiveLargeMessage(ConsumerContext consumerID, + ClientLargeMessageInternal clientLargeMessage, + long largeMessageSize) throws Exception { ClientSessionInternal session = this.session; - if (session != null) - { + if (session != null) { session.handleReceiveLargeMessage(consumerID, clientLargeMessage, largeMessageSize); } } - protected void handleReceiveMessage(ConsumerContext consumerID, final ClientMessageInternal message) throws Exception - { + protected void handleReceiveMessage(ConsumerContext consumerID, + final ClientMessageInternal message) throws Exception { ClientSessionInternal session = this.session; - if (session != null) - { + if (session != null) { session.handleReceiveMessage(consumerID, message); } } - protected void handleReceiveContinuation(final ConsumerContext consumerID, byte[] chunk, int flowControlSize, boolean isContinues) throws Exception - { + protected void handleReceiveContinuation(final ConsumerContext consumerID, + byte[] chunk, + int flowControlSize, + boolean isContinues) throws Exception { ClientSessionInternal session = this.session; - if (session != null) - { + if (session != null) { session.handleReceiveContinuation(consumerID, chunk, flowControlSize, isContinues); } } - protected void handleReceiveProducerCredits(SimpleString address, int credits) - { + protected void handleReceiveProducerCredits(SimpleString address, int credits) { ClientSessionInternal session = this.session; - if (session != null) - { + if (session != null) { session.handleReceiveProducerCredits(address, credits); } } - protected void handleReceiveProducerFailCredits(SimpleString address, int credits) - { + protected void handleReceiveProducerFailCredits(SimpleString address, int credits) { ClientSessionInternal session = this.session; - if (session != null) - { + if (session != null) { session.handleReceiveProducerFailCredits(address, credits); } @@ -135,7 +124,10 @@ public abstract class SessionContext public abstract int getCreditsOnSendingFull(MessageInternal msgI); - public abstract void sendFullMessage(MessageInternal msgI, boolean sendBlocking, SendAcknowledgementHandler handler, SimpleString defaultAddress) throws ActiveMQException; + public abstract void sendFullMessage(MessageInternal msgI, + boolean sendBlocking, + SendAcknowledgementHandler handler, + SimpleString defaultAddress) throws ActiveMQException; /** * it should return the number of credits (or bytes) used to send this packet @@ -146,9 +138,12 @@ public abstract class SessionContext */ public abstract int sendInitialChunkOnLargeMessage(MessageInternal msgI) throws ActiveMQException; - - public abstract int sendLargeMessageChunk(MessageInternal msgI, long messageBodySize, boolean sendBlocking, boolean lastChunk, byte[] chunk, SendAcknowledgementHandler messageHandler) throws ActiveMQException; - + public abstract int sendLargeMessageChunk(MessageInternal msgI, + long messageBodySize, + boolean sendBlocking, + boolean lastChunk, + byte[] chunk, + SendAcknowledgementHandler messageHandler) throws ActiveMQException; public abstract void setSendAcknowledgementHandler(final SendAcknowledgementHandler handler); @@ -159,7 +154,11 @@ public abstract class SessionContext public abstract void deleteQueue(SimpleString queueName) throws ActiveMQException; - public abstract void createQueue(SimpleString address, SimpleString queueName, SimpleString filterString, boolean durable, boolean temp) throws ActiveMQException; + public abstract void createQueue(SimpleString address, + SimpleString queueName, + SimpleString filterString, + boolean durable, + boolean temp) throws ActiveMQException; public abstract ClientSession.QueueQuery queueQuery(SimpleString queueName) throws ActiveMQException; @@ -169,7 +168,6 @@ public abstract class SessionContext public abstract void simpleCommit() throws ActiveMQException; - /** * If we are doing a simple rollback on the RA, we need to ack the last message sent to the consumer, * otherwise DLQ won't work. @@ -185,7 +183,10 @@ public abstract class SessionContext public abstract void sessionStop() throws ActiveMQException; - public abstract void sendACK(boolean individual, boolean block, final ClientConsumer consumer, final Message message) throws ActiveMQException; + public abstract void sendACK(boolean individual, + boolean block, + final ClientConsumer consumer, + final Message message) throws ActiveMQException; public abstract void expireMessage(final ClientConsumer consumer, Message message) throws ActiveMQException; @@ -213,8 +214,14 @@ public abstract class SessionContext public abstract boolean configureTransactionTimeout(int seconds) throws ActiveMQException; - public abstract ClientConsumerInternal createConsumer(SimpleString queueName, SimpleString filterString, int windowSize, int maxRate, int ackBatchSize, boolean browseOnly, - Executor executor, Executor flowControlExecutor) throws ActiveMQException; + public abstract ClientConsumerInternal createConsumer(SimpleString queueName, + SimpleString filterString, + int windowSize, + int maxRate, + int ackBatchSize, + boolean browseOnly, + Executor executor, + Executor flowControlExecutor) throws ActiveMQException; /** * Performs a round trip to the server requesting what is the current tx timeout on the session @@ -234,7 +241,6 @@ public abstract class SessionContext final boolean preAcknowledge, final SimpleString defaultAddress) throws ActiveMQException; - public abstract void recreateConsumerOnServer(ClientConsumerInternal consumerInternal) throws ActiveMQException; public abstract void xaFailed(Xid xid) throws ActiveMQException; @@ -243,7 +249,6 @@ public abstract class SessionContext public abstract void resetMetadata(HashMap metaDataToSend); - // Failover utility classes /** @@ -257,11 +262,9 @@ public abstract class SessionContext */ public abstract void lockCommunications(); - public abstract void releaseCommunications(); public abstract void cleanup(); - public abstract void linkFlowControl(SimpleString address, ClientProducerCreditsImpl clientProducerCredits); } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/TopologyResponseHandler.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/TopologyResponseHandler.java index 18de8eb22e..eda05ee2fe 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/TopologyResponseHandler.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/TopologyResponseHandler.java @@ -20,8 +20,8 @@ import org.apache.activemq.artemis.api.core.Pair; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; -public interface TopologyResponseHandler -{ +public interface TopologyResponseHandler { + // This is sent when the server is telling the client the node is being disconnected void nodeDisconnected(RemotingConnection conn, String nodeID, String scaleDownTargetNodeID); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/AbstractServerLocatorSchema.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/AbstractServerLocatorSchema.java index 2d23fd852f..3fe97bb261 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/AbstractServerLocatorSchema.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/AbstractServerLocatorSchema.java @@ -22,11 +22,9 @@ import org.apache.activemq.artemis.utils.uri.URISchema; import java.net.URI; import java.util.Map; -public abstract class AbstractServerLocatorSchema extends URISchema -{ +public abstract class AbstractServerLocatorSchema extends URISchema { - protected ConnectionOptions newConnectionOptions(URI uri, Map query) throws Exception - { + protected ConnectionOptions newConnectionOptions(URI uri, Map query) throws Exception { return setData(uri, new ConnectionOptions(), query); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/AbstractTransportConfigurationSchema.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/AbstractTransportConfigurationSchema.java index 702e6e484f..b76fa7fff9 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/AbstractTransportConfigurationSchema.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/AbstractTransportConfigurationSchema.java @@ -21,6 +21,6 @@ import org.apache.activemq.artemis.utils.uri.URISchema; import java.util.List; -public abstract class AbstractTransportConfigurationSchema extends URISchema, String> -{ +public abstract class AbstractTransportConfigurationSchema extends URISchema, String> { + } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/ConnectionOptions.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/ConnectionOptions.java index 2f50b4811e..f08bfd7dde 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/ConnectionOptions.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/ConnectionOptions.java @@ -16,13 +16,13 @@ */ package org.apache.activemq.artemis.uri; + /** * This will represent all the possible options you could setup on URLs * When parsing the URL this will serve as an intermediate object * And it could also be a pl */ -public class ConnectionOptions -{ +public class ConnectionOptions { private boolean ha; @@ -30,53 +30,45 @@ public class ConnectionOptions private int port; - public ConnectionOptions setHost(String host) - { + public ConnectionOptions setHost(String host) { this.host = host; return this; } - public String getHost() - { + public String getHost() { return host; } - - public ConnectionOptions setPort(int port) - { + public ConnectionOptions setPort(int port) { this.port = port; return this; } - public int getPort() - { + public int getPort() { return port; } - public boolean isHa() - { + public boolean isHa() { return ha; } - public void setHa(boolean ha) - { + public void setHa(boolean ha) { this.ha = ha; } - /** Se need both options (ha / HA in case of typos on the URI) */ - public boolean isHA() - { + /** + * Se need both options (ha / HA in case of typos on the URI) + */ + public boolean isHA() { return ha; } - public void setHA(boolean ha) - { + public void setHA(boolean ha) { this.ha = ha; } @Override - public String toString() - { + public String toString() { return "ConnectionOptions{" + "ha=" + ha + '}'; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/ConnectorTransportConfigurationParser.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/ConnectorTransportConfigurationParser.java index 18b6a1ea72..650a3b8288 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/ConnectorTransportConfigurationParser.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/ConnectorTransportConfigurationParser.java @@ -22,10 +22,9 @@ import org.apache.activemq.artemis.utils.uri.URIFactory; import java.util.List; -public class ConnectorTransportConfigurationParser extends URIFactory, String> -{ - public ConnectorTransportConfigurationParser() - { +public class ConnectorTransportConfigurationParser extends URIFactory, String> { + + public ConnectorTransportConfigurationParser() { registerSchema(new TCPTransportConfigurationSchema(TransportConstants.ALLOWABLE_CONNECTOR_KEYS)); registerSchema(new InVMTransportConfigurationSchema()); } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/InVMServerLocatorSchema.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/InVMServerLocatorSchema.java index 327e63aa55..5bbad3798b 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/InVMServerLocatorSchema.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/InVMServerLocatorSchema.java @@ -26,35 +26,28 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.Map; -public class InVMServerLocatorSchema extends AbstractServerLocatorSchema -{ +public class InVMServerLocatorSchema extends AbstractServerLocatorSchema { + @Override - public String getSchemaName() - { + public String getSchemaName() { return SchemaConstants.VM; } @Override - protected ServerLocator internalNewObject(URI uri, Map query, String name) throws Exception - { + protected ServerLocator internalNewObject(URI uri, Map query, String name) throws Exception { TransportConfiguration tc = InVMTransportConfigurationSchema.createTransportConfiguration(uri, query, name, "org.apache.activemq.artemis.core.remoting.impl.invm.InVMConnectorFactory"); ServerLocator factory = ActiveMQClient.createServerLocatorWithoutHA(tc); return URISchema.setData(uri, factory, query); } - - @Override - protected URI internalNewURI(ServerLocator bean) throws Exception - { + protected URI internalNewURI(ServerLocator bean) throws Exception { return getUri(bean.getStaticTransportConfigurations()); } - public static URI getUri(TransportConfiguration[] configurations) throws URISyntaxException - { + public static URI getUri(TransportConfiguration[] configurations) throws URISyntaxException { String host = "0"; - if (configurations != null && configurations.length > 0) - { + if (configurations != null && configurations.length > 0) { TransportConfiguration configuration = configurations[0]; Map params = configuration.getParams(); host = params.get("serverId") == null ? host : params.get("serverId").toString(); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/InVMTransportConfigurationSchema.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/InVMTransportConfigurationSchema.java index f393ff6fb3..b473ba428f 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/InVMTransportConfigurationSchema.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/InVMTransportConfigurationSchema.java @@ -25,44 +25,43 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -public class InVMTransportConfigurationSchema extends AbstractTransportConfigurationSchema -{ +public class InVMTransportConfigurationSchema extends AbstractTransportConfigurationSchema { + /* This is the same as org.apache.activemq.artemis.core.remoting.impl.invm.TransportConstants.CONNECTIONS_ALLOWED, * but this Maven module can't see that class. */ public static final String CONNECTIONS_ALLOWED = "connectionsAllowed"; @Override - public String getSchemaName() - { + public String getSchemaName() { return SchemaConstants.VM; } @Override - protected List internalNewObject(URI uri, Map query, String name) throws Exception - { + protected List internalNewObject(URI uri, + Map query, + String name) throws Exception { List configurations = new ArrayList<>(); configurations.add(createTransportConfiguration(uri, query, name, getFactoryName())); return configurations; } @Override - protected URI internalNewURI(List bean) throws Exception - { + protected URI internalNewURI(List bean) throws Exception { return null; } - protected String getFactoryName() - { + protected String getFactoryName() { return "org.apache.activemq.artemis.core.remoting.impl.invm.InVMConnectorFactory"; } - public static TransportConfiguration createTransportConfiguration(URI uri, Map query, String name, String factoryName) - { + public static TransportConfiguration createTransportConfiguration(URI uri, + Map query, + String name, + String factoryName) { Map inVmTransportConfig = new HashMap<>(); inVmTransportConfig.put("serverId", uri.getHost()); - if (query.containsKey(CONNECTIONS_ALLOWED)) - { + if (query.containsKey(CONNECTIONS_ALLOWED)) { inVmTransportConfig.put(CONNECTIONS_ALLOWED, query.get(CONNECTIONS_ALLOWED)); } return new TransportConfiguration(factoryName, inVmTransportConfig, name); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/JGroupsServerLocatorSchema.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/JGroupsServerLocatorSchema.java index 0d313b9d25..1749d9dd18 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/JGroupsServerLocatorSchema.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/JGroupsServerLocatorSchema.java @@ -28,63 +28,54 @@ import java.io.NotSerializableException; import java.net.URI; import java.util.Map; -public class JGroupsServerLocatorSchema extends AbstractServerLocatorSchema -{ +public class JGroupsServerLocatorSchema extends AbstractServerLocatorSchema { + @Override - public String getSchemaName() - { + public String getSchemaName() { return SchemaConstants.JGROUPS; } @Override - protected ServerLocator internalNewObject(URI uri, Map query, String name) throws Exception - { + protected ServerLocator internalNewObject(URI uri, Map query, String name) throws Exception { ConnectionOptions options = newConnectionOptions(uri, query); DiscoveryGroupConfiguration dcConfig = getDiscoveryGroupConfiguration(uri, query, name); - if (options.isHa()) - { + if (options.isHa()) { return ActiveMQClient.createServerLocatorWithHA(dcConfig); } - else - { + else { return ActiveMQClient.createServerLocatorWithoutHA(dcConfig); } } @Override - protected URI internalNewURI(ServerLocator bean) throws Exception - { + protected URI internalNewURI(ServerLocator bean) throws Exception { DiscoveryGroupConfiguration dgc = bean.getDiscoveryGroupConfiguration(); - BroadcastEndpointFactory endpoint = dgc.getBroadcastEndpointFactory(); + BroadcastEndpointFactory endpoint = dgc.getBroadcastEndpointFactory(); String auth; - if (endpoint instanceof JGroupsFileBroadcastEndpointFactory) - { + if (endpoint instanceof JGroupsFileBroadcastEndpointFactory) { auth = ((JGroupsFileBroadcastEndpointFactory) endpoint).getChannelName(); } - else if (endpoint instanceof JGroupsPropertiesBroadcastEndpointFactory) - { + else if (endpoint instanceof JGroupsPropertiesBroadcastEndpointFactory) { auth = ((JGroupsPropertiesBroadcastEndpointFactory) endpoint).getChannelName(); } - else - { + else { throw new NotSerializableException(endpoint + "not serializable"); } String query = getData(null, bean, dgc, endpoint); dgc.setBroadcastEndpointFactory(endpoint); - return new URI(SchemaConstants.JGROUPS, null, auth, -1, null, query, null); + return new URI(SchemaConstants.JGROUPS, null, auth, -1, null, query, null); } - public static DiscoveryGroupConfiguration getDiscoveryGroupConfiguration(URI uri, Map query, String name) throws Exception - { + public static DiscoveryGroupConfiguration getDiscoveryGroupConfiguration(URI uri, + Map query, + String name) throws Exception { BroadcastEndpointFactory endpointFactory; - if (query.containsKey("file")) - { + if (query.containsKey("file")) { endpointFactory = new JGroupsFileBroadcastEndpointFactory().setChannelName(uri.getAuthority()); } - else - { + else { endpointFactory = new JGroupsPropertiesBroadcastEndpointFactory().setChannelName(uri.getAuthority()); } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/ServerLocatorParser.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/ServerLocatorParser.java index 6cb564bbe8..2bf11a4275 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/ServerLocatorParser.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/ServerLocatorParser.java @@ -19,10 +19,9 @@ package org.apache.activemq.artemis.uri; import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.utils.uri.URIFactory; -public class ServerLocatorParser extends URIFactory -{ - public ServerLocatorParser() - { +public class ServerLocatorParser extends URIFactory { + + public ServerLocatorParser() { registerSchema(new InVMServerLocatorSchema()); registerSchema(new TCPServerLocatorSchema()); registerSchema(new UDPServerLocatorSchema()); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/TCPServerLocatorSchema.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/TCPServerLocatorSchema.java index c1e771d642..c4701a709b 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/TCPServerLocatorSchema.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/TCPServerLocatorSchema.java @@ -28,95 +28,76 @@ import java.net.URI; import java.util.List; import java.util.Map; -public class TCPServerLocatorSchema extends AbstractServerLocatorSchema -{ +public class TCPServerLocatorSchema extends AbstractServerLocatorSchema { + @Override - public String getSchemaName() - { + public String getSchemaName() { return SchemaConstants.TCP; } - @Override - protected ServerLocator internalNewObject(URI uri, Map query, String name) throws Exception - { + protected ServerLocator internalNewObject(URI uri, Map query, String name) throws Exception { ConnectionOptions options = newConnectionOptions(uri, query); - List configurations = - TCPTransportConfigurationSchema.getTransportConfigurations(uri, query, TransportConstants.ALLOWABLE_CONNECTOR_KEYS, name, NettyConnectorFactory.class.getName()); + List configurations = TCPTransportConfigurationSchema.getTransportConfigurations(uri, query, TransportConstants.ALLOWABLE_CONNECTOR_KEYS, name, NettyConnectorFactory.class.getName()); TransportConfiguration[] tcs = new TransportConfiguration[configurations.size()]; configurations.toArray(tcs); - if (options.isHa()) - { + if (options.isHa()) { return ActiveMQClient.createServerLocatorWithHA(tcs); } - else - { + else { return ActiveMQClient.createServerLocatorWithoutHA(tcs); } } @Override - protected URI internalNewURI(ServerLocator bean) throws Exception - { + protected URI internalNewURI(ServerLocator bean) throws Exception { String query = URISchema.getData(null, bean); TransportConfiguration[] staticConnectors = bean.getStaticTransportConfigurations(); return getURI(query, staticConnectors); } - public static URI getURI(String query, TransportConfiguration[] staticConnectors) throws Exception - { - if (staticConnectors == null || staticConnectors.length < 1) - { + public static URI getURI(String query, TransportConfiguration[] staticConnectors) throws Exception { + if (staticConnectors == null || staticConnectors.length < 1) { throw new Exception(); } StringBuilder fragment = new StringBuilder(); - for (int i = 1; i < staticConnectors.length; i++) - { + for (int i = 1; i < staticConnectors.length; i++) { TransportConfiguration connector = staticConnectors[i]; Map params = connector.getParams(); URI extraUri = new URI(SchemaConstants.TCP, null, getHost(params), getPort(params), null, createQuery(params, null), null); - if (i > 1) - { + if (i > 1) { fragment.append(","); } fragment.append(extraUri.toASCIIString()); } Map params = staticConnectors[0].getParams(); - return new URI(SchemaConstants.TCP, null, getHost(params), getPort(params), null, createQuery(params, query), fragment.toString()); + return new URI(SchemaConstants.TCP, null, getHost(params), getPort(params), null, createQuery(params, query), fragment.toString()); } - private static int getPort(Map params) - { + private static int getPort(Map params) { Object port = params.get("port"); - if (port instanceof String) - { + if (port instanceof String) { return Integer.valueOf((String) port); } return port != null ? (int) port : 61616; } - private static String getHost(Map params) - { + private static String getHost(Map params) { return params.get("host") != null ? (String) params.get("host") : "localhost"; } - private static String createQuery(Map params, String query) - { + private static String createQuery(Map params, String query) { StringBuilder cb; - if (query == null) - { + if (query == null) { cb = new StringBuilder(); } - else - { + else { cb = new StringBuilder(query); } - for (String param : params.keySet()) - { - if (cb.length() > 0) - { + for (String param : params.keySet()) { + if (cb.length() > 0) { cb.append("&"); } cb.append(param).append("=").append(params.get(param)); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/TCPTransportConfigurationSchema.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/TCPTransportConfigurationSchema.java index ecb22d6c5b..10fda78302 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/TCPTransportConfigurationSchema.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/TCPTransportConfigurationSchema.java @@ -29,67 +29,60 @@ import org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnectorFactor import org.apache.activemq.artemis.utils.uri.SchemaConstants; import org.apache.activemq.artemis.utils.uri.URISchema; -public class TCPTransportConfigurationSchema extends AbstractTransportConfigurationSchema -{ +public class TCPTransportConfigurationSchema extends AbstractTransportConfigurationSchema { + private final Set allowableProperties; - public TCPTransportConfigurationSchema(Set allowableProperties) - { + public TCPTransportConfigurationSchema(Set allowableProperties) { this.allowableProperties = allowableProperties; } @Override - public String getSchemaName() - { + public String getSchemaName() { return SchemaConstants.TCP; } @Override - protected List internalNewObject(URI uri, Map query, String name) throws Exception - { + protected List internalNewObject(URI uri, + Map query, + String name) throws Exception { return getTransportConfigurations(uri, query, allowableProperties, name, getFactoryName(uri)); } @Override - protected URI internalNewURI(List bean) throws Exception - { + protected URI internalNewURI(List bean) throws Exception { return null; } - public static List getTransportConfigurations(URI uri, Map query, Set allowableProperties, String name, String factoryName) throws URISyntaxException - { + public static List getTransportConfigurations(URI uri, + Map query, + Set allowableProperties, + String name, + String factoryName) throws URISyntaxException { HashMap props = new HashMap<>(); URISchema.setData(uri, props, allowableProperties, query); List transportConfigurations = new ArrayList<>(); - transportConfigurations.add(new TransportConfiguration(factoryName, - props, - name)); + transportConfigurations.add(new TransportConfiguration(factoryName, props, name)); String connectors = uri.getFragment(); - if (connectors != null && !connectors.trim().isEmpty()) - { + if (connectors != null && !connectors.trim().isEmpty()) { String[] split = connectors.split(","); - for (String s : split) - { + for (String s : split) { URI extraUri = new URI(s); HashMap newProps = new HashMap<>(); URISchema.setData(extraUri, newProps, allowableProperties, query); URISchema.setData(extraUri, newProps, allowableProperties, URISchema.parseQuery(extraUri.getQuery(), null)); - transportConfigurations.add(new TransportConfiguration(factoryName, - newProps, - name + ":" + extraUri.toString())); + transportConfigurations.add(new TransportConfiguration(factoryName, newProps, name + ":" + extraUri.toString())); } } return transportConfigurations; } - protected String getFactoryName(URI uri) - { + protected String getFactoryName(URI uri) { //here for backwards compatibility - if (uri.getPath() != null && uri.getPath().contains("hornetq")) - { + if (uri.getPath() != null && uri.getPath().contains("hornetq")) { return "org.hornetq.core.remoting.impl.netty.NettyConnectorFactory"; } return NettyConnectorFactory.class.getName(); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/UDPServerLocatorSchema.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/UDPServerLocatorSchema.java index 96cd818622..b3a85fce2d 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/UDPServerLocatorSchema.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/uri/UDPServerLocatorSchema.java @@ -28,58 +28,53 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -public class UDPServerLocatorSchema extends AbstractServerLocatorSchema -{ +public class UDPServerLocatorSchema extends AbstractServerLocatorSchema { + protected static List IGNORED = new ArrayList<>(); - static - { + + static { IGNORED.add("localBindAddress"); IGNORED.add("localBindPort"); } + @Override - public String getSchemaName() - { + public String getSchemaName() { return SchemaConstants.UDP; } @Override - protected ServerLocator internalNewObject(URI uri, Map query, String name) throws Exception - { + protected ServerLocator internalNewObject(URI uri, Map query, String name) throws Exception { ConnectionOptions options = newConnectionOptions(uri, query); DiscoveryGroupConfiguration dgc = getDiscoveryGroupConfiguration(uri, query, getHost(uri), getPort(uri), name); - if (options.isHa()) - { + if (options.isHa()) { return ActiveMQClient.createServerLocatorWithHA(dgc); } - else - { + else { return ActiveMQClient.createServerLocatorWithoutHA(dgc); } } @Override - protected URI internalNewURI(ServerLocator bean) throws Exception - { + protected URI internalNewURI(ServerLocator bean) throws Exception { DiscoveryGroupConfiguration dgc = bean.getDiscoveryGroupConfiguration(); UDPBroadcastEndpointFactory endpoint = (UDPBroadcastEndpointFactory) dgc.getBroadcastEndpointFactory(); dgc.setBroadcastEndpointFactory(endpoint); String query = URISchema.getData(IGNORED, bean, dgc, endpoint); - return new URI(SchemaConstants.UDP, null, endpoint.getGroupAddress(), endpoint.getGroupPort(), null, query, null); + return new URI(SchemaConstants.UDP, null, endpoint.getGroupAddress(), endpoint.getGroupPort(), null, query, null); } - public static DiscoveryGroupConfiguration getDiscoveryGroupConfiguration(URI uri, Map query, String host, int port, String name) throws Exception - { - UDPBroadcastEndpointFactory endpointFactoryConfiguration = new UDPBroadcastEndpointFactory() - .setGroupAddress(host) - .setGroupPort(port); + public static DiscoveryGroupConfiguration getDiscoveryGroupConfiguration(URI uri, + Map query, + String host, + int port, + String name) throws Exception { + UDPBroadcastEndpointFactory endpointFactoryConfiguration = new UDPBroadcastEndpointFactory().setGroupAddress(host).setGroupPort(port); URISchema.setData(uri, endpointFactoryConfiguration, query); - DiscoveryGroupConfiguration dgc = URISchema.setData(uri, new DiscoveryGroupConfiguration(), query) - .setName(name) - .setBroadcastEndpointFactory(endpointFactoryConfiguration); + DiscoveryGroupConfiguration dgc = URISchema.setData(uri, new DiscoveryGroupConfiguration(), query).setName(name).setBroadcastEndpointFactory(endpointFactoryConfiguration); URISchema.setData(uri, dgc, query); return dgc; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/ActiveMQBufferInputStream.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/ActiveMQBufferInputStream.java index 7854997beb..3cbaac9b2e 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/ActiveMQBufferInputStream.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/ActiveMQBufferInputStream.java @@ -24,8 +24,7 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; /** * Used to send large messages */ -public class ActiveMQBufferInputStream extends InputStream -{ +public class ActiveMQBufferInputStream extends InputStream { /* (non-Javadoc) * @see java.io.InputStream#read() @@ -41,34 +40,27 @@ public class ActiveMQBufferInputStream extends InputStream // Public -------------------------------------------------------- - public ActiveMQBufferInputStream(final ActiveMQBuffer paramByteBuffer) - { + public ActiveMQBufferInputStream(final ActiveMQBuffer paramByteBuffer) { bb = paramByteBuffer; } @Override - public int read() throws IOException - { - if (bb == null) - { + public int read() throws IOException { + if (bb == null) { throw new IOException("read on a closed InputStream"); } - if (remainingBytes() == 0) - { + if (remainingBytes() == 0) { return -1; } - else - { + else { return bb.readByte() & 0xFF; } } @Override - public int read(final byte[] byteArray) throws IOException - { - if (bb == null) - { + public int read(final byte[] byteArray) throws IOException { + if (bb == null) { throw new IOException("read on a closed InputStream"); } @@ -76,30 +68,24 @@ public class ActiveMQBufferInputStream extends InputStream } @Override - public int read(final byte[] byteArray, final int off, final int len) throws IOException - { - if (bb == null) - { + public int read(final byte[] byteArray, final int off, final int len) throws IOException { + if (bb == null) { throw new IOException("read on a closed InputStream"); } - if (byteArray == null) - { + if (byteArray == null) { throw new NullPointerException(); } - if (off < 0 || off > byteArray.length || len < 0 || off + len > byteArray.length || off + len < 0) - { + if (off < 0 || off > byteArray.length || len < 0 || off + len > byteArray.length || off + len < 0) { throw new IndexOutOfBoundsException(); } - if (len == 0) - { + if (len == 0) { return 0; } int size = Math.min(remainingBytes(), len); - if (size == 0) - { + if (size == 0) { return -1; } @@ -108,15 +94,12 @@ public class ActiveMQBufferInputStream extends InputStream } @Override - public long skip(final long len) throws IOException - { - if (bb == null) - { + public long skip(final long len) throws IOException { + if (bb == null) { throw new IOException("skip on a closed InputStream"); } - if (len <= 0L) - { + if (len <= 0L) { return 0L; } @@ -128,10 +111,8 @@ public class ActiveMQBufferInputStream extends InputStream } @Override - public int available() throws IOException - { - if (bb == null) - { + public int available() throws IOException { + if (bb == null) { throw new IOException("available on a closed InputStream"); } @@ -139,25 +120,21 @@ public class ActiveMQBufferInputStream extends InputStream } @Override - public void close() throws IOException - { + public void close() throws IOException { bb = null; } @Override - public synchronized void mark(final int paramInt) - { + public synchronized void mark(final int paramInt) { } @Override - public synchronized void reset() throws IOException - { + public synchronized void reset() throws IOException { throw new IOException("mark/reset not supported"); } @Override - public boolean markSupported() - { + public boolean markSupported() { return false; } @@ -170,12 +147,10 @@ public class ActiveMQBufferInputStream extends InputStream /** * @return */ - private int remainingBytes() - { + private int remainingBytes() { return bb.writerIndex() - bb.readerIndex(); } - // Inner classes ------------------------------------------------- } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/BufferHelper.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/BufferHelper.java index 603379b78f..6659424654 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/BufferHelper.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/BufferHelper.java @@ -22,72 +22,62 @@ import org.apache.activemq.artemis.api.core.SimpleString; /** * Helper methods to read and write from ActiveMQBuffer. */ -public class BufferHelper -{ +public class BufferHelper { - /** Size of a String as if it was a Nullable Simple String */ - public static int sizeOfNullableSimpleString(String str) - { - if (str == null) - { + /** + * Size of a String as if it was a Nullable Simple String + */ + public static int sizeOfNullableSimpleString(String str) { + if (str == null) { return DataConstants.SIZE_BOOLEAN; } - else - { + else { return DataConstants.SIZE_BOOLEAN + sizeOfSimpleString(str); } } - /** Size of a String as it if was a Simple String*/ - public static int sizeOfSimpleString(String str) - { + /** + * Size of a String as it if was a Simple String + */ + public static int sizeOfSimpleString(String str) { return DataConstants.SIZE_INT + str.length() * 2; } - public static void writeAsNullableSimpleString(ActiveMQBuffer buffer, String str) - { + public static void writeAsNullableSimpleString(ActiveMQBuffer buffer, String str) { buffer.writeNullableSimpleString(SimpleString.toSimpleString(str)); } - public static String readNullableSimpleStringAsString(ActiveMQBuffer buffer) - { + public static String readNullableSimpleStringAsString(ActiveMQBuffer buffer) { SimpleString str = buffer.readNullableSimpleString(); return str != null ? str.toString() : null; } - public static void writeAsSimpleString(ActiveMQBuffer buffer, String str) - { + public static void writeAsSimpleString(ActiveMQBuffer buffer, String str) { buffer.writeSimpleString(new SimpleString(str)); } /** * @param buffer */ - public static void writeNullableBoolean(ActiveMQBuffer buffer, Boolean value) - { + public static void writeNullableBoolean(ActiveMQBuffer buffer, Boolean value) { buffer.writeBoolean(value != null); - if (value != null) - { + if (value != null) { buffer.writeBoolean(value.booleanValue()); } } - public static int sizeOfNullableBoolean(Boolean value) - { + public static int sizeOfNullableBoolean(Boolean value) { return DataConstants.SIZE_BOOLEAN + (value != null ? DataConstants.SIZE_BOOLEAN : 0); } - public static Boolean readNullableBoolean(ActiveMQBuffer buffer) - { + public static Boolean readNullableBoolean(ActiveMQBuffer buffer) { boolean isNotNull = buffer.readBoolean(); - if (isNotNull) - { + if (isNotNull) { return buffer.readBoolean(); } - else - { + else { return null; } } @@ -95,12 +85,10 @@ public class BufferHelper /** * @param buffer */ - public static void writeNullableLong(ActiveMQBuffer buffer, Long value) - { + public static void writeNullableLong(ActiveMQBuffer buffer, Long value) { buffer.writeBoolean(value != null); - if (value != null) - { + if (value != null) { buffer.writeLong(value.longValue()); } } @@ -108,37 +96,29 @@ public class BufferHelper /** * @param buffer */ - public static void writeNullableDouble(ActiveMQBuffer buffer, Double value) - { + public static void writeNullableDouble(ActiveMQBuffer buffer, Double value) { buffer.writeBoolean(value != null); - if (value != null) - { + if (value != null) { buffer.writeDouble(value.doubleValue()); } } - public static int sizeOfNullableLong(Long value) - { + public static int sizeOfNullableLong(Long value) { return DataConstants.SIZE_BOOLEAN + (value != null ? DataConstants.SIZE_LONG : 0); } - public static int sizeOfNullableDouble(Double value) - { + public static int sizeOfNullableDouble(Double value) { return DataConstants.SIZE_BOOLEAN + (value != null ? DataConstants.SIZE_DOUBLE : 0); } - - public static Long readNullableLong(ActiveMQBuffer buffer) - { + public static Long readNullableLong(ActiveMQBuffer buffer) { boolean isNotNull = buffer.readBoolean(); - if (isNotNull) - { + if (isNotNull) { return buffer.readLong(); } - else - { + else { return null; } } @@ -146,45 +126,36 @@ public class BufferHelper /** * @param buffer */ - public static void writeNullableInteger(ActiveMQBuffer buffer, Integer value) - { + public static void writeNullableInteger(ActiveMQBuffer buffer, Integer value) { buffer.writeBoolean(value != null); - if (value != null) - { + if (value != null) { buffer.writeInt(value.intValue()); } } - public static int sizeOfNullableInteger(Integer value) - { + public static int sizeOfNullableInteger(Integer value) { return DataConstants.SIZE_BOOLEAN + (value != null ? DataConstants.SIZE_INT : 0); } - public static Integer readNullableInteger(ActiveMQBuffer buffer) - { + public static Integer readNullableInteger(ActiveMQBuffer buffer) { boolean isNotNull = buffer.readBoolean(); - if (isNotNull) - { + if (isNotNull) { return buffer.readInt(); } - else - { + else { return null; } } - public static Double readNullableDouble(ActiveMQBuffer buffer) - { + public static Double readNullableDouble(ActiveMQBuffer buffer) { boolean isNotNull = buffer.readBoolean(); - if (isNotNull) - { + if (isNotNull) { return buffer.readDouble(); } - else - { + else { return null; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/ConfigurationHelper.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/ConfigurationHelper.java index 1743ba68d3..76326b68cc 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/ConfigurationHelper.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/ConfigurationHelper.java @@ -24,170 +24,133 @@ import java.util.HashSet; import java.util.Map; import java.util.Set; +public class ConfigurationHelper { -public class ConfigurationHelper -{ - public static String getStringProperty(final String propName, final String def, final Map props) - { - if (props == null) - { + public static String getStringProperty(final String propName, final String def, final Map props) { + if (props == null) { return def; } Object prop = props.get(propName); - if (prop == null) - { + if (prop == null) { return def; } - else - { - if (prop instanceof String == false) - { + else { + if (prop instanceof String == false) { return prop.toString(); } - else - { - return (String)prop; + else { + return (String) prop; } } } - public static int getIntProperty(final String propName, final int def, final Map props) - { - if (props == null) - { + public static int getIntProperty(final String propName, final int def, final Map props) { + if (props == null) { return def; } Object prop = props.get(propName); - if (prop == null) - { + if (prop == null) { return def; } - else - { + else { // The resource adapter will aways send Strings, hence the conversion here - if (prop instanceof String) - { - return Integer.valueOf((String)prop); + if (prop instanceof String) { + return Integer.valueOf((String) prop); } - else if (prop instanceof Number == false) - { + else if (prop instanceof Number == false) { ActiveMQClientLogger.LOGGER.propertyNotInteger(propName, prop.getClass().getName()); return def; } - else - { - return ((Number)prop).intValue(); + else { + return ((Number) prop).intValue(); } } } - public static long getLongProperty(final String propName, final long def, final Map props) - { - if (props == null) - { + public static long getLongProperty(final String propName, final long def, final Map props) { + if (props == null) { return def; } Object prop = props.get(propName); - if (prop == null) - { + if (prop == null) { return def; } - else - { + else { // The resource adapter will aways send Strings, hence the conversion here - if (prop instanceof String) - { - return Long.valueOf((String)prop); + if (prop instanceof String) { + return Long.valueOf((String) prop); } - else if (prop instanceof Number == false) - { + else if (prop instanceof Number == false) { ActiveMQClientLogger.LOGGER.propertyNotLong(propName, prop.getClass().getName()); return def; } - else - { - return ((Number)prop).longValue(); + else { + return ((Number) prop).longValue(); } } } - public static boolean getBooleanProperty(final String propName, final boolean def, final Map props) - { - if (props == null) - { + public static boolean getBooleanProperty(final String propName, final boolean def, final Map props) { + if (props == null) { return def; } Object prop = props.get(propName); - if (prop == null) - { + if (prop == null) { return def; } - else - { + else { // The resource adapter will aways send Strings, hence the conversion here - if (prop instanceof String) - { - return Boolean.valueOf((String)prop); + if (prop instanceof String) { + return Boolean.valueOf((String) prop); } - else if (prop instanceof Boolean == false) - { + else if (prop instanceof Boolean == false) { ActiveMQClientLogger.LOGGER.propertyNotBoolean(propName, prop.getClass().getName()); return def; } - else - { - return (Boolean)prop; + else { + return (Boolean) prop; } } } - public static Set checkKeys(final Set allowableKeys, final Set keys) - { + public static Set checkKeys(final Set allowableKeys, final Set keys) { Set invalid = new HashSet(); - for (String key : keys) - { - if (!allowableKeys.contains(key)) - { + for (String key : keys) { + if (!allowableKeys.contains(key)) { invalid.add(key); } } return invalid; } - public static Set checkKeysExist(final Set requiredKeys, final Set keys) - { + public static Set checkKeysExist(final Set requiredKeys, final Set keys) { Set invalid = new HashSet(requiredKeys); - for (String key : keys) - { - if (requiredKeys.contains(key)) - { + for (String key : keys) { + if (requiredKeys.contains(key)) { invalid.remove(key); } } return invalid; } - public static String stringSetToCommaListString(final Set invalid) - { + public static String stringSetToCommaListString(final Set invalid) { StringBuilder sb = new StringBuilder(); int count = 0; - for (String key : invalid) - { + for (String key : invalid) { sb.append(key); - if (count != invalid.size() - 1) - { + if (count != invalid.size() - 1) { sb.append(", "); } count++; @@ -196,51 +159,44 @@ public class ConfigurationHelper } public static String getPasswordProperty(final String propName, - final String def, final Map props, - String defaultMaskPassword, String defaultPasswordCodec) - { - if (props == null) - { + final String def, + final Map props, + String defaultMaskPassword, + String defaultPasswordCodec) { + if (props == null) { return def; } Object prop = props.get(propName); - if (prop == null) - { + if (prop == null) { return def; } String value = prop.toString(); Boolean useMask = (Boolean) props.get(defaultMaskPassword); - if (useMask == null || (!useMask)) - { + if (useMask == null || (!useMask)) { return value; } final String classImpl = (String) props.get(defaultPasswordCodec); - if (classImpl == null) - { + if (classImpl == null) { throw ActiveMQClientMessageBundle.BUNDLE.noCodec(); } SensitiveDataCodec codec = null; - try - { + try { codec = PasswordMaskingUtil.getCodec(classImpl); } - catch (ActiveMQException e1) - { + catch (ActiveMQException e1) { throw ActiveMQClientMessageBundle.BUNDLE.failedToGetDecoder(e1); } - try - { + try { return codec.decode(value); } - catch (Exception e) - { + catch (Exception e) { throw ActiveMQClientMessageBundle.BUNDLE.errordecodingPassword(e); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/ConfirmationWindowWarning.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/ConfirmationWindowWarning.java index f1f12a5020..c318858006 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/ConfirmationWindowWarning.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/ConfirmationWindowWarning.java @@ -21,16 +21,15 @@ import java.util.concurrent.atomic.AtomicBoolean; /** * TODO: get rid of this */ -public final class ConfirmationWindowWarning -{ +public final class ConfirmationWindowWarning { + public final boolean disabled; public final AtomicBoolean warningIssued; /** * */ - public ConfirmationWindowWarning(boolean disabled) - { + public ConfirmationWindowWarning(boolean disabled) { this.disabled = disabled; warningIssued = new AtomicBoolean(false); } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/DeflaterReader.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/DeflaterReader.java index 03c8e94718..028720f3e3 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/DeflaterReader.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/DeflaterReader.java @@ -26,8 +26,8 @@ import java.util.zip.Deflater; * The reader takes an inputstream and compress it. * Not for concurrent use. */ -public class DeflaterReader extends InputStream -{ +public class DeflaterReader extends InputStream { + private final Deflater deflater = new Deflater(); private boolean isFinished = false; private boolean compressDone = false; @@ -36,23 +36,19 @@ public class DeflaterReader extends InputStream private final AtomicLong bytesRead; - public DeflaterReader(final InputStream inData, final AtomicLong bytesRead) - { + public DeflaterReader(final InputStream inData, final AtomicLong bytesRead) { input = inData; this.bytesRead = bytesRead; } @Override - public int read() throws IOException - { + public int read() throws IOException { byte[] buffer = new byte[1]; int n = read(buffer, 0, 1); - if (n == 1) - { + if (n == 1) { return buffer[0] & 0xFF; } - if (n == -1 || n == 0) - { + if (n == -1 || n == 0) { return -1; } throw new IOException("Error reading data, invalid n: " + n); @@ -67,10 +63,8 @@ public class DeflaterReader extends InputStream * @throws IOException */ @Override - public int read(final byte[] buffer, int offset, int len) throws IOException - { - if (compressDone) - { + public int read(final byte[] buffer, int offset, int len) throws IOException { + if (compressDone) { return -1; } @@ -80,44 +74,35 @@ public class DeflaterReader extends InputStream int n = 0; int read = 0; - while (len > 0) - { + while (len > 0) { n = deflater.deflate(buffer, offset, len); - if (n == 0) - { - if (isFinished) - { + if (n == 0) { + if (isFinished) { deflater.end(); compressDone = true; break; } - else if (deflater.needsInput()) - { + else if (deflater.needsInput()) { // read some data from inputstream int m = input.read(readBuffer); - if (m == -1) - { + if (m == -1) { deflater.finish(); isFinished = true; } - else - { - if (bytesRead != null) - { + else { + if (bytesRead != null) { bytesRead.addAndGet(m); } deflater.setInput(readBuffer, 0, m); } } - else - { + else { deflater.finish(); isFinished = true; } } - else - { + else { read += n; offset += n; len -= n; @@ -126,14 +111,12 @@ public class DeflaterReader extends InputStream return read; } - public void closeStream() throws IOException - { + public void closeStream() throws IOException { super.close(); input.close(); } - public long getTotalSize() - { + public long getTotalSize() { return bytesRead.get(); } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/ExecutorFactory.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/ExecutorFactory.java index 94a87ddc19..dd0209baa2 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/ExecutorFactory.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/ExecutorFactory.java @@ -18,7 +18,7 @@ package org.apache.activemq.artemis.utils; import java.util.concurrent.Executor; -public interface ExecutorFactory -{ +public interface ExecutorFactory { + Executor getExecutor(); } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/FutureLatch.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/FutureLatch.java index 6e1b9f84bb..b3911615cb 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/FutureLatch.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/FutureLatch.java @@ -19,42 +19,35 @@ package org.apache.activemq.artemis.utils; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -public class FutureLatch implements Runnable -{ +public class FutureLatch implements Runnable { + private final CountDownLatch latch; - public FutureLatch() - { + public FutureLatch() { super(); latch = new CountDownLatch(1); } - public FutureLatch(int latches) - { + public FutureLatch(int latches) { super(); - latch = new CountDownLatch(latches); + latch = new CountDownLatch(latches); } - public boolean await(final long timeout) - { - try - { + public boolean await(final long timeout) { + try { return latch.await(timeout, TimeUnit.MILLISECONDS); } - catch (InterruptedException e) - { + catch (InterruptedException e) { return false; } } - public void run() - { + public void run() { latch.countDown(); } @Override - public String toString() - { + public String toString() { return FutureLatch.class.getSimpleName() + "(latch=" + latch + ")"; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/IDGenerator.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/IDGenerator.java index 13577a7add..4cbc2ff0f7 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/IDGenerator.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/IDGenerator.java @@ -26,8 +26,8 @@ package org.apache.activemq.artemis.utils; * a record indicates a server crash. During server restart, if the journals lack a * {@literal next-recordID} record, we use the last recorded ID plus {@code MAX_INT}. */ -public interface IDGenerator -{ +public interface IDGenerator { + long generateID(); long getCurrentID(); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/InflaterReader.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/InflaterReader.java index 363391a60b..3bc34b69c6 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/InflaterReader.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/InflaterReader.java @@ -26,8 +26,8 @@ import java.util.zip.Inflater; * It takes a compressed input stream and decompressed it as it is being read. * Not for concurrent use. */ -public class InflaterReader extends InputStream -{ +public class InflaterReader extends InputStream { + private Inflater inflater = new Inflater(); private InputStream input; @@ -36,33 +36,26 @@ public class InflaterReader extends InputStream private int pointer; private int length; - public InflaterReader(InputStream input) - { + public InflaterReader(InputStream input) { this(input, 1024); } - public InflaterReader(InputStream input, int bufferSize) - { + public InflaterReader(InputStream input, int bufferSize) { this.input = input; this.readBuffer = new byte[bufferSize]; this.pointer = -1; } - public int read() throws IOException - { - if (pointer == -1) - { - try - { + public int read() throws IOException { + if (pointer == -1) { + try { length = doRead(readBuffer, 0, readBuffer.length); - if (length == 0) - { + if (length == 0) { return -1; } pointer = 0; } - catch (DataFormatException e) - { + catch (DataFormatException e) { IOException e2 = new IOException(e.getMessage()); e2.initCause(e); throw e2; @@ -71,8 +64,7 @@ public class InflaterReader extends InputStream int value = readBuffer[pointer] & 0xFF; pointer++; - if (pointer == length) - { + if (pointer == length) { pointer = -1; } @@ -84,52 +76,42 @@ public class InflaterReader extends InputStream * decompressed output. * returns number of bytes actually got */ - private int doRead(byte[] buf, int offset, int len) throws DataFormatException, IOException - { + private int doRead(byte[] buf, int offset, int len) throws DataFormatException, IOException { int read = 0; int n = 0; byte[] inputBuffer = new byte[len]; - while (len > 0) - { + while (len > 0) { n = inflater.inflate(buf, offset, len); - if (n == 0) - { - if (inflater.finished()) - { + if (n == 0) { + if (inflater.finished()) { break; } - else if (inflater.needsInput()) - { + else if (inflater.needsInput()) { //feeding int m = input.read(inputBuffer); - if (m == -1) - { + if (m == -1) { //it shouldn't be here, throw exception throw new DataFormatException("Input is over while inflater still expecting data"); } - else - { + else { //feed the data in inflater.setInput(inputBuffer, 0, m); n = inflater.inflate(buf, offset, len); - if (n > 0) - { + if (n > 0) { read += n; offset += n; len -= n; } } } - else - { + else { //it shouldn't be here, throw throw new DataFormatException("Inflater is neither finished nor needing input."); } } - else - { + else { read += n; offset += n; len -= n; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/InflaterWriter.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/InflaterWriter.java index ddb34a15ab..767ef6ce39 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/InflaterWriter.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/InflaterWriter.java @@ -30,8 +30,8 @@ import java.util.zip.Inflater; *

    * Not for concurrent use. */ -public class InflaterWriter extends OutputStream -{ +public class InflaterWriter extends OutputStream { + private final Inflater inflater = new Inflater(); private final OutputStream output; @@ -42,8 +42,7 @@ public class InflaterWriter extends OutputStream private final byte[] outputBuffer = new byte[writeBuffer.length * 2]; - public InflaterWriter(final OutputStream output) - { + public InflaterWriter(final OutputStream output) { this.output = output; } @@ -51,20 +50,16 @@ public class InflaterWriter extends OutputStream * Write a compressed byte. */ @Override - public void write(final int b) throws IOException - { - writeBuffer[writePointer] = (byte)(b & 0xFF); + public void write(final int b) throws IOException { + writeBuffer[writePointer] = (byte) (b & 0xFF); writePointer++; - if (writePointer == writeBuffer.length) - { + if (writePointer == writeBuffer.length) { writePointer = 0; - try - { + try { doWrite(); } - catch (DataFormatException e) - { + catch (DataFormatException e) { IOException ie = new IOException("Error decompressing data"); ie.initCause(e); throw ie; @@ -73,23 +68,18 @@ public class InflaterWriter extends OutputStream } @Override - public void close() throws IOException - { - if (writePointer > 0) - { + public void close() throws IOException { + if (writePointer > 0) { inflater.setInput(writeBuffer, 0, writePointer); - try - { + try { int n = inflater.inflate(outputBuffer); - while (n > 0) - { + while (n > 0) { output.write(outputBuffer, 0, n); n = inflater.inflate(outputBuffer); } output.close(); } - catch (DataFormatException e) - { + catch (DataFormatException e) { IOException io = new IOException(e.getMessage()); io.initCause(e); throw io; @@ -97,13 +87,11 @@ public class InflaterWriter extends OutputStream } } - private void doWrite() throws DataFormatException, IOException - { + private void doWrite() throws DataFormatException, IOException { inflater.setInput(writeBuffer); int n = inflater.inflate(outputBuffer); - while (n > 0) - { + while (n > 0) { output.write(outputBuffer, 0, n); n = inflater.inflate(outputBuffer); } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/JNDIUtil.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/JNDIUtil.java index ddbeb04ae1..bbdaaff25f 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/JNDIUtil.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/JNDIUtil.java @@ -24,8 +24,7 @@ import javax.naming.NameNotFoundException; import javax.naming.NamingEnumeration; import javax.naming.NamingException; -public class JNDIUtil -{ +public class JNDIUtil { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -33,25 +32,20 @@ public class JNDIUtil /** * Create a context path recursively. */ - public static Context createContext(final Context c, final String path) throws NamingException - { + public static Context createContext(final Context c, final String path) throws NamingException { Context crtContext = c; - for (StringTokenizer st = new StringTokenizer(path, "/"); st.hasMoreTokens();) - { + for (StringTokenizer st = new StringTokenizer(path, "/"); st.hasMoreTokens(); ) { String tok = st.nextToken(); - try - { + try { Object o = crtContext.lookup(tok); - if (!(o instanceof Context)) - { + if (!(o instanceof Context)) { throw new NamingException("Path " + path + " overwrites and already bound object"); } - crtContext = (Context)o; + crtContext = (Context) o; continue; } - catch (NameNotFoundException e) - { + catch (NameNotFoundException e) { // OK } crtContext = crtContext.createSubcontext(tok); @@ -59,16 +53,13 @@ public class JNDIUtil return crtContext; } - public static void tearDownRecursively(final Context c) throws Exception - { - for (NamingEnumeration ne = c.listBindings(""); ne.hasMore();) - { + public static void tearDownRecursively(final Context c) throws Exception { + for (NamingEnumeration ne = c.listBindings(""); ne.hasMore(); ) { Binding b = ne.next(); String name = b.getName(); Object object = b.getObject(); - if (object instanceof Context) - { - JNDIUtil.tearDownRecursively((Context)object); + if (object instanceof Context) { + JNDIUtil.tearDownRecursively((Context) object); } c.unbind(name); } @@ -80,28 +71,23 @@ public class JNDIUtil * NameNotFoundException is thrown. This method behaves similar to Context.rebind(), but creates * intermediate contexts, if necessary. */ - public static void rebind(final Context c, final String jndiName, final Object o) throws NamingException - { + public static void rebind(final Context c, final String jndiName, final Object o) throws NamingException { Context context = c; String name = jndiName; int idx = jndiName.lastIndexOf('/'); - if (idx != -1) - { + if (idx != -1) { context = JNDIUtil.createContext(c, jndiName.substring(0, idx)); name = jndiName.substring(idx + 1); } boolean failed = false; - try - { + try { context.rebind(name, o); } - catch (Exception ignored) - { + catch (Exception ignored) { failed = true; } - if (failed) - { + if (failed) { context.bind(name, o); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/LinkedList.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/LinkedList.java index 4966ca2f7e..fd64aaf6f7 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/LinkedList.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/LinkedList.java @@ -16,8 +16,8 @@ */ package org.apache.activemq.artemis.utils; -public interface LinkedList -{ +public interface LinkedList { + void addHead(E e); void addTail(E e); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/LinkedListImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/LinkedListImpl.java index 20ad38e416..5d8fa5753f 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/LinkedListImpl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/LinkedListImpl.java @@ -19,15 +19,14 @@ package org.apache.activemq.artemis.utils; import java.lang.reflect.Array; import java.util.NoSuchElementException; - /** * A linked list implementation which allows multiple iterators to exist at the same time on the queue, and which see any * elements added or removed from the queue either directly or via iterators. * * This class is not thread safe. */ -public class LinkedListImpl implements LinkedList -{ +public class LinkedListImpl implements LinkedList { + private static final int INITIAL_ITERATOR_ARRAY_SIZE = 10; private final Node head = new Node(null); @@ -43,13 +42,11 @@ public class LinkedListImpl implements LinkedList private int nextIndex; - public LinkedListImpl() - { + public LinkedListImpl() { iters = createIteratorArray(INITIAL_ITERATOR_ARRAY_SIZE); } - public void addHead(E e) - { + public void addHead(E e) { Node node = new Node(e); node.next = head.next; @@ -58,12 +55,10 @@ public class LinkedListImpl implements LinkedList head.next = node; - if (size == 0) - { + if (size == 0) { tail = node; } - else - { + else { // Need to set the previous element on the former head node.next.prev = node; } @@ -71,14 +66,11 @@ public class LinkedListImpl implements LinkedList size++; } - public void addTail(E e) - { - if (size == 0) - { + public void addTail(E e) { + if (size == 0) { addHead(e); } - else - { + else { Node node = new Node(e); node.prev = tail; @@ -91,51 +83,42 @@ public class LinkedListImpl implements LinkedList } } - public E poll() - { + public E poll() { Node ret = head.next; - if (ret != null) - { + if (ret != null) { removeAfter(head); return ret.val; } - else - { + else { return null; } } - public void clear() - { + public void clear() { tail = head.next = null; size = 0; } - public int size() - { + public int size() { return size; } - public LinkedListIterator iterator() - { + public LinkedListIterator iterator() { return new Iterator(); } - public String toString() - { + public String toString() { StringBuilder str = new StringBuilder("LinkedListImpl [ "); Node node = head; - while (node != null) - { + while (node != null) { str.append(node.toString()); - if (node.next != null) - { + if (node.next != null) { str.append(", "); } @@ -145,36 +128,30 @@ public class LinkedListImpl implements LinkedList return str.toString(); } - public int numIters() - { + public int numIters() { return numIters; } - private Iterator[] createIteratorArray(int size) - { - return (Iterator[])Array.newInstance(Iterator.class, size); + private Iterator[] createIteratorArray(int size) { + return (Iterator[]) Array.newInstance(Iterator.class, size); } - private void removeAfter(Node node) - { + private void removeAfter(Node node) { Node toRemove = node.next; node.next = toRemove.next; - if (toRemove.next != null) - { + if (toRemove.next != null) { toRemove.next.prev = node; } - if (toRemove == tail) - { + if (toRemove == tail) { tail = node; } size--; - if (toRemove.iterCount != 0) - { + if (toRemove.iterCount != 0) { LinkedListImpl.this.nudgeIterators(toRemove); } @@ -183,22 +160,17 @@ public class LinkedListImpl implements LinkedList toRemove.next = toRemove.prev = null; } - private synchronized void nudgeIterators(Node node) - { - for (int i = 0; i < numIters; i++) - { + private synchronized void nudgeIterators(Node node) { + for (int i = 0; i < numIters; i++) { Iterator iter = iters[i]; - if (iter != null) - { + if (iter != null) { iter.nudged(node); } } } - private synchronized void addIter(Iterator iter) - { - if (numIters == iters.length) - { + private synchronized void addIter(Iterator iter) { + if (numIters == iters.length) { resize(2 * numIters); } @@ -207,8 +179,7 @@ public class LinkedListImpl implements LinkedList numIters++; } - private synchronized void resize(int newSize) - { + private synchronized void resize(int newSize) { Iterator[] newIters = createIteratorArray(newSize); System.arraycopy(iters, 0, newIters, 0, numIters); @@ -216,16 +187,12 @@ public class LinkedListImpl implements LinkedList iters = newIters; } - private synchronized void removeIter(Iterator iter) - { - for (int i = 0; i < numIters; i++) - { - if (iter == iters[i]) - { + private synchronized void removeIter(Iterator iter) { + for (int i = 0; i < numIters; i++) { + if (iter == iters[i]) { iters[i] = null; - if (i != numIters - 1) - { + if (i != numIters - 1) { // Fill in the hole System.arraycopy(iters, i + 1, iters, i, numIters - i - 1); @@ -233,8 +200,7 @@ public class LinkedListImpl implements LinkedList numIters--; - if (numIters >= INITIAL_ITERATOR_ARRAY_SIZE && numIters == iters.length / 2) - { + if (numIters >= INITIAL_ITERATOR_ARRAY_SIZE && numIters == iters.length / 2) { resize(numIters); } @@ -247,8 +213,8 @@ public class LinkedListImpl implements LinkedList throw new IllegalStateException("Cannot find iter to remove"); } - private static final class Node - { + private static final class Node { + Node next; Node prev; @@ -257,91 +223,75 @@ public class LinkedListImpl implements LinkedList int iterCount; - Node(E e) - { + Node(E e) { val = e; } - public String toString() - { + public String toString() { return "Node, value = " + val; } } - private class Iterator implements LinkedListIterator - { + private class Iterator implements LinkedListIterator { + Node last; Node current = head.next; boolean repeat; - Iterator() - { - if (current != null) - { + Iterator() { + if (current != null) { current.iterCount++; } addIter(this); } - public void repeat() - { + public void repeat() { repeat = true; } - public boolean hasNext() - { + public boolean hasNext() { Node e = getNode(); - if (e != null && (e != last || repeat)) - { + if (e != null && (e != last || repeat)) { return true; } return canAdvance(); } - public E next() - { + public E next() { Node e = getNode(); - if (repeat) - { + if (repeat) { repeat = false; - if (e != null) - { + if (e != null) { return e.val; } - else - { - if (canAdvance()) - { + else { + if (canAdvance()) { advance(); e = getNode(); return e.val; } - else - { + else { throw new NoSuchElementException(); } } } - if (e == null || e == last) - { - if (canAdvance()) - { + if (e == null || e == last) { + if (canAdvance()) { advance(); e = getNode(); } - else - { + else { throw new NoSuchElementException(); } } @@ -353,15 +303,12 @@ public class LinkedListImpl implements LinkedList return e.val; } - public void remove() - { - if (last == null) - { + public void remove() { + if (last == null) { throw new NoSuchElementException(); } - if (current == null) - { + if (current == null) { throw new NoSuchElementException(); } @@ -370,67 +317,52 @@ public class LinkedListImpl implements LinkedList last = null; } - public void close() - { + public void close() { removeIter(this); } - public void nudged(Node node) - { - if (current == node) - { - if (canAdvance()) - { + public void nudged(Node node) { + if (current == node) { + if (canAdvance()) { advance(); } - else - { - if (current.prev != head) - { + else { + if (current.prev != head) { current.iterCount--; current = current.prev; current.iterCount++; } - else - { + else { current = null; } } } } - private Node getNode() - { - if (current == null) - { + private Node getNode() { + if (current == null) { current = head.next; - if (current != null) - { + if (current != null) { current.iterCount++; } } - if (current != null) - { + if (current != null) { return current; } - else - { + else { return null; } } - private boolean canAdvance() - { - if (current == null) - { + private boolean canAdvance() { + if (current == null) { current = head.next; - if (current != null) - { + if (current != null) { current.iterCount++; } } @@ -438,10 +370,8 @@ public class LinkedListImpl implements LinkedList return current != null && current.next != null; } - private void advance() - { - if (current == null || current.next == null) - { + private void advance() { + if (current == null || current.next == null) { throw new NoSuchElementException(); } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/LinkedListIterator.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/LinkedListIterator.java index 83579e5933..db0461f5ee 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/LinkedListIterator.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/LinkedListIterator.java @@ -18,14 +18,13 @@ package org.apache.activemq.artemis.utils; import java.util.Iterator; - /** * A LinkedListIterator * * This iterator allows the last element to be repeated in the next call to hasNext or next */ -public interface LinkedListIterator extends Iterator, AutoCloseable -{ +public interface LinkedListIterator extends Iterator, AutoCloseable { + void repeat(); void close(); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/MemorySize.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/MemorySize.java index 098d0e5203..dfb3f01e41 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/MemorySize.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/MemorySize.java @@ -20,44 +20,37 @@ import org.apache.activemq.artemis.core.client.ActiveMQClientLogger; import java.lang.ref.WeakReference; +public class MemorySize { -public class MemorySize -{ private static final int numberOfObjects = 10000; - private static Object newObject(final ObjectFactory factory) throws Exception - { + private static Object newObject(final ObjectFactory factory) throws Exception { return factory.createObject(); } - public static boolean is64bitArch() - { + public static boolean is64bitArch() { boolean is64bit = true; // Default to 64 e.g. if can't retrieve property - try - { + try { String arch = System.getProperty("os.arch"); - if (arch != null) - { + if (arch != null) { is64bit = arch.contains("64"); } } - catch (Exception e) - { + catch (Exception e) { // Ignore } return is64bit; } - public interface ObjectFactory - { + public interface ObjectFactory { + Object createObject(); } - public static int calculateSize(final ObjectFactory factory) throws Exception - { + public static int calculateSize(final ObjectFactory factory) throws Exception { final Runtime runtime = Runtime.getRuntime(); MemorySize.getMemorySize(runtime); @@ -74,8 +67,7 @@ public class MemorySize Object[] obj = new Object[MemorySize.numberOfObjects * 2]; - for (i = 0; i < MemorySize.numberOfObjects * 2; i++) - { + for (i = 0; i < MemorySize.numberOfObjects * 2; i++) { obj[i] = MemorySize.newObject(factory); } @@ -85,8 +77,7 @@ public class MemorySize totalMemory1 = runtime.totalMemory(); - for (i = 0; i < MemorySize.numberOfObjects; i++) - { + for (i = 0; i < MemorySize.numberOfObjects; i++) { obj[i] = MemorySize.newObject(factory); } @@ -94,10 +85,9 @@ public class MemorySize totalMemory2 = runtime.totalMemory(); - final int size = Math.round((float)(heap2 - heap1) / MemorySize.numberOfObjects); + final int size = Math.round((float) (heap2 - heap1) / MemorySize.numberOfObjects); - if (totalMemory1 != totalMemory2) - { + if (totalMemory1 != totalMemory2) { // throw new IllegalStateException("Warning: JVM allocated more data what would make results invalid " + // totalMemory1 + ":" + totalMemory2); @@ -107,28 +97,22 @@ public class MemorySize return size; } - private static long getMemorySize(final Runtime runtime) - { - for (int i = 0; i < 5; i++) - { + private static long getMemorySize(final Runtime runtime) { + for (int i = 0; i < 5; i++) { MemorySize.forceGC(); } return runtime.totalMemory() - runtime.freeMemory(); } - private static void forceGC() - { + private static void forceGC() { WeakReference dumbReference = new WeakReference(new Object()); // A loop that will wait GC, using the minimal time as possible - while (dumbReference.get() != null) - { + while (dumbReference.get() != null) { System.gc(); - try - { + try { Thread.sleep(500); } - catch (InterruptedException e) - { + catch (InterruptedException e) { } } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/ObjectInputStreamWithClassLoader.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/ObjectInputStreamWithClassLoader.java index 0c9fa91fbe..ddc3564d83 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/ObjectInputStreamWithClassLoader.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/ObjectInputStreamWithClassLoader.java @@ -26,8 +26,7 @@ import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; -public class ObjectInputStreamWithClassLoader extends ObjectInputStream -{ +public class ObjectInputStreamWithClassLoader extends ObjectInputStream { // Constants ------------------------------------------------------------------------------------ @@ -37,8 +36,7 @@ public class ObjectInputStreamWithClassLoader extends ObjectInputStream // Constructors --------------------------------------------------------------------------------- - public ObjectInputStreamWithClassLoader(final InputStream in) throws IOException - { + public ObjectInputStreamWithClassLoader(final InputStream in) throws IOException { super(in); } @@ -49,54 +47,40 @@ public class ObjectInputStreamWithClassLoader extends ObjectInputStream // Protected ------------------------------------------------------------------------------------ @Override - protected Class resolveClass(final ObjectStreamClass desc) throws IOException, ClassNotFoundException - { - if (System.getSecurityManager() == null) - { + protected Class resolveClass(final ObjectStreamClass desc) throws IOException, ClassNotFoundException { + if (System.getSecurityManager() == null) { return resolveClass0(desc); } - else - { - try - { - return AccessController.doPrivileged(new PrivilegedExceptionAction() - { + else { + try { + return AccessController.doPrivileged(new PrivilegedExceptionAction() { @Override - public Class run() throws Exception - { + public Class run() throws Exception { return resolveClass0(desc); } }); } - catch (PrivilegedActionException e) - { + catch (PrivilegedActionException e) { throw unwrapException(e); } } } @Override - protected Class resolveProxyClass(final String[] interfaces) throws IOException, ClassNotFoundException - { - if (System.getSecurityManager() == null) - { + protected Class resolveProxyClass(final String[] interfaces) throws IOException, ClassNotFoundException { + if (System.getSecurityManager() == null) { return resolveProxyClass0(interfaces); } - else - { - try - { - return AccessController.doPrivileged(new PrivilegedExceptionAction() - { + else { + try { + return AccessController.doPrivileged(new PrivilegedExceptionAction() { @Override - public Class run() throws Exception - { + public Class run() throws Exception { return resolveProxyClass0(interfaces); } }); } - catch (PrivilegedActionException e) - { + catch (PrivilegedActionException e) { throw unwrapException(e); } } @@ -104,89 +88,70 @@ public class ObjectInputStreamWithClassLoader extends ObjectInputStream // Private -------------------------------------------------------------------------------------- - private Class resolveClass0(final ObjectStreamClass desc) throws IOException, ClassNotFoundException - { + private Class resolveClass0(final ObjectStreamClass desc) throws IOException, ClassNotFoundException { String name = desc.getName(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); - try - { + try { // HORNETQ-747 https://issues.jboss.org/browse/HORNETQ-747 // Use Class.forName instead of ClassLoader.loadClass to avoid issues with loading arrays Class clazz = Class.forName(name, false, loader); // sanity check only.. if a classLoader can't find a clazz, it will throw an exception - if (clazz == null) - { + if (clazz == null) { return super.resolveClass(desc); } - else - { + else { return clazz; } } - catch (ClassNotFoundException e) - { + catch (ClassNotFoundException e) { return super.resolveClass(desc); } } - private Class resolveProxyClass0(String[] interfaces) throws IOException, ClassNotFoundException - { + private Class resolveProxyClass0(String[] interfaces) throws IOException, ClassNotFoundException { ClassLoader latestLoader = Thread.currentThread().getContextClassLoader(); ClassLoader nonPublicLoader = null; boolean hasNonPublicInterface = false; // define proxy in class loader of non-public interface(s), if any Class[] classObjs = new Class[interfaces.length]; - for (int i = 0; i < interfaces.length; i++) - { + for (int i = 0; i < interfaces.length; i++) { Class cl = Class.forName(interfaces[i], false, latestLoader); - if ((cl.getModifiers() & Modifier.PUBLIC) == 0) - { - if (hasNonPublicInterface) - { - if (nonPublicLoader != cl.getClassLoader()) - { + if ((cl.getModifiers() & Modifier.PUBLIC) == 0) { + if (hasNonPublicInterface) { + if (nonPublicLoader != cl.getClassLoader()) { throw new IllegalAccessError("conflicting non-public interface class loaders"); } } - else - { + else { nonPublicLoader = cl.getClassLoader(); hasNonPublicInterface = true; } } classObjs[i] = cl; } - try - { + try { return Proxy.getProxyClass(hasNonPublicInterface ? nonPublicLoader : latestLoader, classObjs); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { throw new ClassNotFoundException(null, e); } } - private RuntimeException unwrapException(PrivilegedActionException e) throws IOException, ClassNotFoundException - { + private RuntimeException unwrapException(PrivilegedActionException e) throws IOException, ClassNotFoundException { Throwable c = e.getCause(); - if (c instanceof IOException) - { - throw (IOException)c; + if (c instanceof IOException) { + throw (IOException) c; } - else if (c instanceof ClassNotFoundException) - { - throw (ClassNotFoundException)c; + else if (c instanceof ClassNotFoundException) { + throw (ClassNotFoundException) c; } - else if (c instanceof RuntimeException) - { - throw (RuntimeException)c; + else if (c instanceof RuntimeException) { + throw (RuntimeException) c; } - else if (c instanceof Error) - { - throw (Error)c; + else if (c instanceof Error) { + throw (Error) c; } - else - { + else { throw new RuntimeException(c); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/OrderedExecutorFactory.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/OrderedExecutorFactory.java index b9f92fb8a7..69cc54a146 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/OrderedExecutorFactory.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/OrderedExecutorFactory.java @@ -22,12 +22,11 @@ import java.util.concurrent.Executor; import org.apache.activemq.artemis.api.core.ActiveMQInterruptedException; import org.apache.activemq.artemis.core.client.ActiveMQClientLogger; - /** * A factory for producing executors that run all tasks in order, which delegate to a single common executor instance. */ -public final class OrderedExecutorFactory implements ExecutorFactory -{ +public final class OrderedExecutorFactory implements ExecutorFactory { + private final Executor parent; /** @@ -35,8 +34,7 @@ public final class OrderedExecutorFactory implements ExecutorFactory * * @param parent the parent executor */ - public OrderedExecutorFactory(final Executor parent) - { + public OrderedExecutorFactory(final Executor parent) { this.parent = parent; } @@ -45,8 +43,7 @@ public final class OrderedExecutorFactory implements ExecutorFactory * * @return an ordered executor */ - public Executor getExecutor() - { + public Executor getExecutor() { return new OrderedExecutor(parent); } @@ -56,8 +53,8 @@ public final class OrderedExecutorFactory implements ExecutorFactory * More specifically, any call B to the {@link #execute(Runnable)} method that happens-after another call A to the * same method, will result in B's task running after A's. */ - private static final class OrderedExecutor implements Executor - { + private static final class OrderedExecutor implements Executor { + private final ConcurrentLinkedQueue tasks = new ConcurrentLinkedQueue(); // @protected by tasks @@ -72,45 +69,35 @@ public final class OrderedExecutorFactory implements ExecutorFactory * * @param parent the parent executor */ - public OrderedExecutor(final Executor parent) - { + public OrderedExecutor(final Executor parent) { this.parent = parent; - runner = new Runnable() - { - public void run() - { - for (;;) - { + runner = new Runnable() { + public void run() { + for (;;) { // Optimization, first try without any locks Runnable task = tasks.poll(); - if (task == null) - { - synchronized (tasks) - { + if (task == null) { + synchronized (tasks) { // if it's null we need to retry now holding the lock on tasks // this is because running=false and tasks.empty must be an atomic operation // so we have to retry before setting the tasks to false // this is a different approach to the anti-pattern on synchronize-retry, // as this is just guaranteeing the running=false and tasks.empty being an atomic operation task = tasks.poll(); - if (task == null) - { + if (task == null) { running = false; return; } } } - try - { + try { task.run(); } - catch (ActiveMQInterruptedException e) - { + catch (ActiveMQInterruptedException e) { // This could happen during shutdowns. Nothing to be concerned about here ActiveMQClientLogger.LOGGER.debug("Interrupted Thread", e); } - catch (Throwable t) - { + catch (Throwable t) { ActiveMQClientLogger.LOGGER.caughtunexpectedThrowable(t); } } @@ -123,21 +110,17 @@ public final class OrderedExecutorFactory implements ExecutorFactory * * @param command the task to run. */ - public void execute(final Runnable command) - { - synchronized (tasks) - { + public void execute(final Runnable command) { + synchronized (tasks) { tasks.add(command); - if (!running) - { + if (!running) { running = true; parent.execute(runner); } } } - public String toString() - { + public String toString() { return "OrderedExecutor(running=" + running + ", tasks=" + tasks + ")"; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/PriorityLinkedList.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/PriorityLinkedList.java index e55a0b8948..450f58a8e1 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/PriorityLinkedList.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/PriorityLinkedList.java @@ -16,13 +16,12 @@ */ package org.apache.activemq.artemis.utils; - /** * A type of linked list which maintains items according to a priority * and allows adding and removing of elements at both ends, and peeking */ -public interface PriorityLinkedList -{ +public interface PriorityLinkedList { + void addHead(T t, int priority); void addTail(T t, int priority); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/PriorityLinkedListImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/PriorityLinkedListImpl.java index 72f4692344..b4b6a510aa 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/PriorityLinkedListImpl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/PriorityLinkedListImpl.java @@ -24,8 +24,8 @@ import java.util.NoSuchElementException; *

    * It implements this by maintaining an individual LinkedBlockingDeque for each priority level. */ -public class PriorityLinkedListImpl implements PriorityLinkedList -{ +public class PriorityLinkedListImpl implements PriorityLinkedList { + protected LinkedListImpl[] levels; private int size; @@ -36,39 +36,31 @@ public class PriorityLinkedListImpl implements PriorityLinkedList private int lastPriority = -1; - public PriorityLinkedListImpl(final int priorities) - { + public PriorityLinkedListImpl(final int priorities) { levels = (LinkedListImpl[]) Array.newInstance(LinkedListImpl.class, priorities); - for (int i = 0; i < priorities; i++) - { + for (int i = 0; i < priorities; i++) { levels[i] = new LinkedListImpl(); } } - private void checkHighest(final int priority) - { - if (lastPriority != priority || priority > highestPriority) - { + private void checkHighest(final int priority) { + if (lastPriority != priority || priority > highestPriority) { lastPriority = priority; - if (lastReset == Integer.MAX_VALUE) - { + if (lastReset == Integer.MAX_VALUE) { lastReset = 0; } - else - { + else { lastReset++; } } - if (priority > highestPriority) - { + if (priority > highestPriority) { highestPriority = priority; } } - public void addHead(final T t, final int priority) - { + public void addHead(final T t, final int priority) { checkHighest(priority); levels[priority].addHead(t); @@ -76,8 +68,7 @@ public class PriorityLinkedListImpl implements PriorityLinkedList size++; } - public void addTail(final T t, final int priority) - { + public void addTail(final T t, final int priority) { checkHighest(priority); levels[priority].addTail(t); @@ -85,8 +76,7 @@ public class PriorityLinkedListImpl implements PriorityLinkedList size++; } - public T poll() - { + public T poll() { T t = null; // We are just using a simple prioritization algorithm: @@ -95,22 +85,17 @@ public class PriorityLinkedListImpl implements PriorityLinkedList // TODO - A better prioritization algorithm - for (int i = highestPriority; i >= 0; i--) - { + for (int i = highestPriority; i >= 0; i--) { LinkedListImpl ll = levels[i]; - if (ll.size() != 0) - { + if (ll.size() != 0) { t = ll.poll(); - if (t != null) - { + if (t != null) { size--; - if (ll.size() == 0) - { - if (highestPriority == i) - { + if (ll.size() == 0) { + if (highestPriority == i) { highestPriority--; } } @@ -123,33 +108,28 @@ public class PriorityLinkedListImpl implements PriorityLinkedList return t; } - public void clear() - { - for (LinkedListImpl list : levels) - { + public void clear() { + for (LinkedListImpl list : levels) { list.clear(); } size = 0; } - public int size() - { + public int size() { return size; } - public boolean isEmpty() - { + public boolean isEmpty() { return size == 0; } - public LinkedListIterator iterator() - { + public LinkedListIterator iterator() { return new PriorityLinkedListIterator(); } - private class PriorityLinkedListIterator implements LinkedListIterator - { + private class PriorityLinkedListIterator implements LinkedListIterator { + private int index; private final LinkedListIterator[] cachedIters = new LinkedListIterator[levels.length]; @@ -160,78 +140,63 @@ public class PriorityLinkedListImpl implements PriorityLinkedList volatile boolean closed = false; - PriorityLinkedListIterator() - { + PriorityLinkedListIterator() { index = levels.length - 1; } @Override - protected void finalize() - { + protected void finalize() { close(); } - public void repeat() - { - if (lastIter == null) - { + public void repeat() { + if (lastIter == null) { throw new NoSuchElementException(); } lastIter.repeat(); } - public void close() - { - if (!closed) - { + public void close() { + if (!closed) { closed = true; lastIter = null; - for (LinkedListIterator iter : cachedIters) - { - if (iter != null) - { + for (LinkedListIterator iter : cachedIters) { + if (iter != null) { iter.close(); } } } } - private void checkReset() - { - if (lastReset != resetCount) - { + private void checkReset() { + if (lastReset != resetCount) { index = highestPriority; resetCount = lastReset; } } - public boolean hasNext() - { + public boolean hasNext() { checkReset(); - while (index >= 0) - { + while (index >= 0) { lastIter = cachedIters[index]; - if (lastIter == null) - { + if (lastIter == null) { lastIter = cachedIters[index] = levels[index].iterator(); } boolean b = lastIter.hasNext(); - if (b) - { + if (b) { return true; } index--; - if (index < 0) - { + if (index < 0) { index = levels.length - 1; break; @@ -240,20 +205,16 @@ public class PriorityLinkedListImpl implements PriorityLinkedList return false; } - public T next() - { - if (lastIter == null) - { + public T next() { + if (lastIter == null) { throw new NoSuchElementException(); } return lastIter.next(); } - public void remove() - { - if (lastIter == null) - { + public void remove() { + if (lastIter == null) { throw new NoSuchElementException(); } @@ -266,8 +227,7 @@ public class PriorityLinkedListImpl implements PriorityLinkedList // what would make us eventually having hasNext() returning false // as a bug // Part of the fix for HORNETQ-705 - for (int i = index; i >= 0 && levels[index].size() == 0; i--) - { + for (int i = index; i >= 0 && levels[index].size() == 0; i--) { highestPriority = i; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/Random.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/Random.java index eb53f43565..b93fd7e9da 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/Random.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/Random.java @@ -18,14 +18,13 @@ package org.apache.activemq.artemis.utils; import java.io.Serializable; -public class Random implements Serializable -{ +public class Random implements Serializable { + private static int extraSeed; private static final long serialVersionUID = 40335522290950498L; - private static synchronized long getSeed() - { + private static synchronized long getSeed() { long seed = System.currentTimeMillis() + Random.extraSeed++; return seed; @@ -33,8 +32,7 @@ public class Random implements Serializable private final java.util.Random random = new java.util.Random(Random.getSeed()); - public java.util.Random getRandom() - { + public java.util.Random getRandom() { return random; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/SecurityFormatter.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/SecurityFormatter.java index deac083135..d79f7d6732 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/SecurityFormatter.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/SecurityFormatter.java @@ -23,10 +23,15 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -public class SecurityFormatter -{ - public static Set createSecurity(String sendRoles, String consumeRoles, String createDurableQueueRoles, String deleteDurableQueueRoles, String createNonDurableQueueRoles, String deleteNonDurableQueueRoles, String manageRoles) - { +public class SecurityFormatter { + + public static Set createSecurity(String sendRoles, + String consumeRoles, + String createDurableQueueRoles, + String deleteDurableQueueRoles, + String createNonDurableQueueRoles, + String deleteNonDurableQueueRoles, + String manageRoles) { List createDurableQueue = toList(createDurableQueueRoles); List deleteDurableQueue = toList(deleteDurableQueueRoles); List createNonDurableQueue = toList(createNonDurableQueueRoles); @@ -45,31 +50,19 @@ public class SecurityFormatter allRoles.addAll(manage); Set roles = new HashSet(allRoles.size()); - for (String role : allRoles) - { - roles.add(new Role(role, - send.contains(role), - consume.contains(role), - createDurableQueue.contains(role), - deleteDurableQueue.contains(role), - createNonDurableQueue.contains(role), - deleteNonDurableQueue.contains(role), - manageRoles.contains(role))); + for (String role : allRoles) { + roles.add(new Role(role, send.contains(role), consume.contains(role), createDurableQueue.contains(role), deleteDurableQueue.contains(role), createNonDurableQueue.contains(role), deleteNonDurableQueue.contains(role), manageRoles.contains(role))); } return roles; } - - private static List toList(final String commaSeparatedString) - { + private static List toList(final String commaSeparatedString) { List list = new ArrayList(); - if (commaSeparatedString == null || commaSeparatedString.trim().length() == 0) - { + if (commaSeparatedString == null || commaSeparatedString.trim().length() == 0) { return list; } String[] values = commaSeparatedString.split(","); - for (int i = 0; i < values.length; i++) - { + for (int i = 0; i < values.length; i++) { list.add(values[i].trim()); } return list; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/SimpleIDGenerator.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/SimpleIDGenerator.java index f8b0477101..06a26c7ea4 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/SimpleIDGenerator.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/SimpleIDGenerator.java @@ -16,28 +16,24 @@ */ package org.apache.activemq.artemis.utils; -public class SimpleIDGenerator implements IDGenerator -{ +public class SimpleIDGenerator implements IDGenerator { + private long idSequence; private boolean wrapped; - public SimpleIDGenerator(final long startID) - { + public SimpleIDGenerator(final long startID) { idSequence = startID; } - public synchronized long generateID() - { + public synchronized long generateID() { long id = idSequence++; - if (idSequence == Long.MIN_VALUE) - { + if (idSequence == Long.MIN_VALUE) { wrapped = true; } - if (wrapped) - { + if (wrapped) { // Wrap - Very unlikely to happen throw new IllegalStateException("Exhausted ids to use!"); } @@ -45,8 +41,7 @@ public class SimpleIDGenerator implements IDGenerator return id; } - public synchronized long getCurrentID() - { + public synchronized long getCurrentID() { return idSequence; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/SizeFormatterUtil.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/SizeFormatterUtil.java index b1694d63d4..71698b46c0 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/SizeFormatterUtil.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/SizeFormatterUtil.java @@ -16,8 +16,7 @@ */ package org.apache.activemq.artemis.utils; -public class SizeFormatterUtil -{ +public class SizeFormatterUtil { // Constants ----------------------------------------------------- @@ -31,22 +30,18 @@ public class SizeFormatterUtil // Static -------------------------------------------------------- - public static String sizeof(final long size) - { + public static String sizeof(final long size) { double s = Long.valueOf(size).doubleValue(); String suffix = "B"; - if (s > SizeFormatterUtil.oneGiB) - { + if (s > SizeFormatterUtil.oneGiB) { s /= SizeFormatterUtil.oneGiB; suffix = "GiB"; } - else if (s > SizeFormatterUtil.oneMiB) - { + else if (s > SizeFormatterUtil.oneMiB) { s /= SizeFormatterUtil.oneMiB; suffix = "MiB"; } - else if (s > SizeFormatterUtil.oneKiB) - { + else if (s > SizeFormatterUtil.oneKiB) { s /= SizeFormatterUtil.oneKiB; suffix = "kiB"; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/SoftValueHashMap.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/SoftValueHashMap.java index de588b3792..4eaf1064c7 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/SoftValueHashMap.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/SoftValueHashMap.java @@ -30,8 +30,8 @@ import java.util.concurrent.atomic.AtomicLong; import org.apache.activemq.artemis.core.client.ActiveMQClientLogger; -public class SoftValueHashMap implements Map -{ +public class SoftValueHashMap implements Map { + private final boolean isTrace = ActiveMQClientLogger.LOGGER.isTraceEnabled(); // The soft references that are already good. @@ -50,36 +50,32 @@ public class SoftValueHashMap implemen // Static -------------------------------------------------------- - public abstract interface ValueCache - { + public abstract interface ValueCache { + boolean isLive(); } // Constructors -------------------------------------------------- - public SoftValueHashMap(final int maxElements) - { + public SoftValueHashMap(final int maxElements) { this.maxElements = maxElements; } // Public -------------------------------------------------------- - public void setMaxElements(final int maxElements) - { + public void setMaxElements(final int maxElements) { this.maxElements = maxElements; checkCacheSize(); } - public int getMaxEelements() - { + public int getMaxEelements() { return this.maxElements; } /** * @see java.util.Map#size() */ - public int size() - { + public int size() { processQueue(); return mapDelegate.size(); } @@ -87,8 +83,7 @@ public class SoftValueHashMap implemen /** * @see java.util.Map#isEmpty() */ - public boolean isEmpty() - { + public boolean isEmpty() { processQueue(); return mapDelegate.isEmpty(); } @@ -97,8 +92,7 @@ public class SoftValueHashMap implemen * @param key * @see java.util.Map#containsKey(java.lang.Object) */ - public boolean containsKey(final Object key) - { + public boolean containsKey(final Object key) { processQueue(); return mapDelegate.containsKey(key); } @@ -107,14 +101,11 @@ public class SoftValueHashMap implemen * @param value * @see java.util.Map#containsValue(java.lang.Object) */ - public boolean containsValue(final Object value) - { + public boolean containsValue(final Object value) { processQueue(); - for (AggregatedSoftReference valueIter : mapDelegate.values()) - { + for (AggregatedSoftReference valueIter : mapDelegate.values()) { V valueElement = valueIter.get(); - if (valueElement != null && value.equals(valueElement)) - { + if (valueElement != null && value.equals(valueElement)) { return true; } @@ -126,17 +117,14 @@ public class SoftValueHashMap implemen * @param key * @see java.util.Map#get(java.lang.Object) */ - public V get(final Object key) - { + public V get(final Object key) { processQueue(); AggregatedSoftReference value = mapDelegate.get(key); - if (value != null) - { + if (value != null) { value.used(); return value.get(); } - else - { + else { return null; } } @@ -146,52 +134,41 @@ public class SoftValueHashMap implemen * @param value * @see java.util.Map#put(java.lang.Object, java.lang.Object) */ - public V put(final K key, final V value) - { + public V put(final K key, final V value) { processQueue(); AggregatedSoftReference newRef = createReference(key, value); AggregatedSoftReference oldRef = mapDelegate.put(key, newRef); checkCacheSize(); newRef.used(); - if (oldRef != null) - { + if (oldRef != null) { return oldRef.get(); } - else - { + else { return null; } } - private void checkCacheSize() - { - if (maxElements > 0 && mapDelegate.size() > maxElements) - { + private void checkCacheSize() { + if (maxElements > 0 && mapDelegate.size() > maxElements) { TreeSet usedReferences = new TreeSet(new ComparatorAgregated()); - for (AggregatedSoftReference ref : mapDelegate.values()) - { + for (AggregatedSoftReference ref : mapDelegate.values()) { V v = ref.get(); - if (v != null && !v.isLive()) - { + if (v != null && !v.isLive()) { usedReferences.add(ref); } } - for (AggregatedSoftReference ref : usedReferences) - { - if (ref.used > 0) - { + for (AggregatedSoftReference ref : usedReferences) { + if (ref.used > 0) { Object removed = mapDelegate.remove(ref.key); - if (isTrace) - { + if (isTrace) { ActiveMQClientLogger.LOGGER.trace("Removing " + removed + " with id = " + ref.key + " from SoftValueHashMap"); } - if (mapDelegate.size() <= maxElements) - { + if (mapDelegate.size() <= maxElements) { break; } } @@ -199,33 +176,27 @@ public class SoftValueHashMap implemen } } - class ComparatorAgregated implements Comparator - { - public int compare(AggregatedSoftReference o1, AggregatedSoftReference o2) - { + class ComparatorAgregated implements Comparator { + + public int compare(AggregatedSoftReference o1, AggregatedSoftReference o2) { long k = o1.used - o2.used; - if (k > 0) - { + if (k > 0) { return 1; } - else if (k < 0) - { + else if (k < 0) { return -1; } k = o1.hashCode() - o2.hashCode(); - if (k > 0) - { + if (k > 0) { return 1; } - else if (k < 0) - { + else if (k < 0) { return -1; } - else - { + else { return 0; } } @@ -235,16 +206,13 @@ public class SoftValueHashMap implemen * @param key * @see java.util.Map#remove(java.lang.Object) */ - public V remove(final Object key) - { + public V remove(final Object key) { processQueue(); AggregatedSoftReference ref = mapDelegate.remove(key); - if (ref != null) - { + if (ref != null) { return ref.get(); } - else - { + else { return null; } } @@ -253,11 +221,9 @@ public class SoftValueHashMap implemen * @param m * @see java.util.Map#putAll(java.util.Map) */ - public void putAll(final Map m) - { + public void putAll(final Map m) { processQueue(); - for (Map.Entry e : m.entrySet()) - { + for (Map.Entry e : m.entrySet()) { put(e.getKey(), e.getValue()); } } @@ -265,16 +231,14 @@ public class SoftValueHashMap implemen /** * @see java.util.Map#clear() */ - public void clear() - { + public void clear() { mapDelegate.clear(); } /** * @see java.util.Map#keySet() */ - public Set keySet() - { + public Set keySet() { processQueue(); return mapDelegate.keySet(); } @@ -282,16 +246,13 @@ public class SoftValueHashMap implemen /** * @see java.util.Map#values() */ - public Collection values() - { + public Collection values() { processQueue(); ArrayList list = new ArrayList(); - for (AggregatedSoftReference refs : mapDelegate.values()) - { + for (AggregatedSoftReference refs : mapDelegate.values()) { V value = refs.get(); - if (value != null) - { + if (value != null) { list.add(value); } } @@ -302,15 +263,12 @@ public class SoftValueHashMap implemen /** * @see java.util.Map#entrySet() */ - public Set> entrySet() - { + public Set> entrySet() { processQueue(); HashSet> set = new HashSet>(); - for (Map.Entry pair : mapDelegate.entrySet()) - { + for (Map.Entry pair : mapDelegate.entrySet()) { V value = pair.getValue().get(); - if (value != null) - { + if (value != null) { set.add(new EntryElement(pair.getKey(), value)); } } @@ -322,8 +280,7 @@ public class SoftValueHashMap implemen * @see java.util.Map#equals(java.lang.Object) */ @Override - public boolean equals(final Object o) - { + public boolean equals(final Object o) { processQueue(); return mapDelegate.equals(o); } @@ -332,8 +289,7 @@ public class SoftValueHashMap implemen * @see java.util.Map#hashCode() */ @Override - public int hashCode() - { + public int hashCode() { return mapDelegate.hashCode(); } @@ -344,60 +300,52 @@ public class SoftValueHashMap implemen // Private ------------------------------------------------------- @SuppressWarnings("unchecked") - private void processQueue() - { + private void processQueue() { AggregatedSoftReference ref = null; - while ((ref = (AggregatedSoftReference)this.refQueue.poll()) != null) - { + while ((ref = (AggregatedSoftReference) this.refQueue.poll()) != null) { mapDelegate.remove(ref.key); } } - private AggregatedSoftReference createReference(final K key, final V value) - { + private AggregatedSoftReference createReference(final K key, final V value) { AggregatedSoftReference ref = new AggregatedSoftReference(key, value); return ref; } // Inner classes ------------------------------------------------- - class AggregatedSoftReference extends SoftReference - { + class AggregatedSoftReference extends SoftReference { + final K key; long used = 0; - public long getUsed() - { + public long getUsed() { return used; } - public void used() - { + public void used() { used = usedCounter.incrementAndGet(); } - public AggregatedSoftReference(final K key, final V referent) - { + public AggregatedSoftReference(final K key, final V referent) { super(referent, refQueue); this.key = key; } @Override - public String toString() - { + public String toString() { return "AggregatedSoftReference [key=" + key + ", used=" + used + "]"; } } - static final class EntryElement implements Map.Entry - { + static final class EntryElement implements Map.Entry { + final K key; volatile V value; - EntryElement(final K key, final V value) - { + EntryElement(final K key, final V value) { this.key = key; this.value = value; } @@ -405,24 +353,21 @@ public class SoftValueHashMap implemen /* (non-Javadoc) * @see java.util.Map.Entry#getKey() */ - public K getKey() - { + public K getKey() { return key; } /* (non-Javadoc) * @see java.util.Map.Entry#getValue() */ - public V getValue() - { + public V getValue() { return value; } /* (non-Javadoc) * @see java.util.Map.Entry#setValue(java.lang.Object) */ - public V setValue(final V value) - { + public V setValue(final V value) { this.value = value; return value; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/TimeAndCounterIDGenerator.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/TimeAndCounterIDGenerator.java index 1bfd561fea..96cdb8c2a2 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/TimeAndCounterIDGenerator.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/TimeAndCounterIDGenerator.java @@ -24,8 +24,7 @@ import java.util.concurrent.atomic.AtomicLong; * This IDGenerator doesn't support more than 16777215 IDs per 16 millisecond. It would throw an exception if this happens. *

    */ -public class TimeAndCounterIDGenerator implements IDGenerator -{ +public class TimeAndCounterIDGenerator implements IDGenerator { // Constants ---------------------------------------------------- /** @@ -53,8 +52,7 @@ public class TimeAndCounterIDGenerator implements IDGenerator // Constructors -------------------------------------------------- - public TimeAndCounterIDGenerator() - { + public TimeAndCounterIDGenerator() { refresh(); } @@ -62,25 +60,21 @@ public class TimeAndCounterIDGenerator implements IDGenerator // Public -------------------------------------------------------- - public long generateID() - { + public long generateID() { long idReturn = counter.incrementAndGet(); - if ((idReturn & TimeAndCounterIDGenerator.ID_MASK) == 0) - { + if ((idReturn & TimeAndCounterIDGenerator.ID_MASK) == 0) { final long timePortion = idReturn & TimeAndCounterIDGenerator.TIME_ID_MASK; // Wrapping ID logic - if (timePortion >= newTM()) - { + if (timePortion >= newTM()) { // Unlikely to happen wrapped = true; } - else - { + else { // Else.. no worry... we will just accept the new time portion being added // This time-mark would have been generated some time ago, so this is ok. // tmMark is just a cache to validate the MaxIDs, so there is no need to make it atomic (synchronized) @@ -88,49 +82,42 @@ public class TimeAndCounterIDGenerator implements IDGenerator } } - if (wrapped) - { + if (wrapped) { // This will only happen if a computer can generate more than ID_MASK ids (16 million IDs per 16 // milliseconds) // If this wrapping code starts to happen, it needs revision throw new IllegalStateException("The IDGenerator is being overlaped, and it needs revision as the system generated more than " + TimeAndCounterIDGenerator.ID_MASK + - " ids per 16 milliseconds which exceeded the IDgenerator limit"); + " ids per 16 milliseconds which exceeded the IDgenerator limit"); } return idReturn; } - public long getCurrentID() - { + public long getCurrentID() { return counter.get(); } // for use in testcases - public long getInternalTimeMark() - { + public long getInternalTimeMark() { return tmMark; } // for use in testcases - public void setInternalID(final long id) - { + public void setInternalID(final long id) { counter.set(tmMark | id); } // for use in testcases - public void setInternalDate(final long date) - { + public void setInternalDate(final long date) { tmMark = (date & TimeAndCounterIDGenerator.MASK_TIME) << TimeAndCounterIDGenerator.BITS_TO_MOVE; counter.set(tmMark); } - public synchronized void refresh() - { + public synchronized void refresh() { long oldTm = tmMark; long newTm = newTM(); - while (newTm <= oldTm) - { + while (newTm <= oldTm) { newTm = newTM(); } tmMark = newTm; @@ -138,15 +125,14 @@ public class TimeAndCounterIDGenerator implements IDGenerator } @Override - public String toString() - { + public String toString() { long currentCounter = counter.get(); return "SequenceGenerator(tmMark=" + hex(tmMark) + - ", CurrentCounter = " + - currentCounter + - ", HexCurrentCounter = " + - hex(currentCounter) + - ")"; + ", CurrentCounter = " + + currentCounter + + ", HexCurrentCounter = " + + hex(currentCounter) + + ")"; } // Package protected --------------------------------------------- @@ -155,13 +141,11 @@ public class TimeAndCounterIDGenerator implements IDGenerator // Private ------------------------------------------------------- - private long newTM() - { + private long newTM() { return (System.currentTimeMillis() & TimeAndCounterIDGenerator.MASK_TIME) << TimeAndCounterIDGenerator.BITS_TO_MOVE; } - private String hex(final long x) - { + private String hex(final long x) { return String.format("%1$X", x); } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/TokenBucketLimiter.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/TokenBucketLimiter.java index 0f50eeccc4..d9a0ea6537 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/TokenBucketLimiter.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/TokenBucketLimiter.java @@ -21,12 +21,14 @@ package org.apache.activemq.artemis.utils; * href="http://en.wikipedia.org/wiki/Token_bucket">Token Bucket metaphor. *

    * The rate is specified in cycles per second (or 'Hertz'). + * * @see Token bucket */ -public interface TokenBucketLimiter -{ +public interface TokenBucketLimiter { + /** * Returns the rate in cycles per second (which is the same as saying 'in Hertz'). + * * @see Hertz */ int getRate(); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/TokenBucketLimiterImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/TokenBucketLimiterImpl.java index 450eb5cb14..011ac58652 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/TokenBucketLimiterImpl.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/TokenBucketLimiterImpl.java @@ -18,8 +18,8 @@ package org.apache.activemq.artemis.utils; import java.util.concurrent.TimeUnit; -public class TokenBucketLimiterImpl implements TokenBucketLimiter -{ +public class TokenBucketLimiterImpl implements TokenBucketLimiter { + private final int rate; private final long window; @@ -27,24 +27,22 @@ public class TokenBucketLimiterImpl implements TokenBucketLimiter private final boolean spin; /** - Even thought we don't use TokenBucket in multiThread - the implementation should keep this volatile for correctness - */ + * Even thought we don't use TokenBucket in multiThread + * the implementation should keep this volatile for correctness + */ private volatile long last; /** - Even thought we don't use TokenBucket in multiThread - the implementation should keep this volatile for correctness - */ + * Even thought we don't use TokenBucket in multiThread + * the implementation should keep this volatile for correctness + */ private int tokens; - public TokenBucketLimiterImpl(final int rate, final boolean spin) - { + public TokenBucketLimiterImpl(final int rate, final boolean spin) { this(rate, spin, TimeUnit.SECONDS, 1); } - public TokenBucketLimiterImpl(final int rate, final boolean spin, TimeUnit unit, int unitAmount) - { + public TokenBucketLimiterImpl(final int rate, final boolean spin, TimeUnit unit, int unitAmount) { this.rate = rate; this.spin = spin; @@ -52,64 +50,51 @@ public class TokenBucketLimiterImpl implements TokenBucketLimiter this.window = unit.toMillis(unitAmount); } - public int getRate() - { + public int getRate() { return rate; } - public boolean isSpin() - { + public boolean isSpin() { return spin; } - public void limit() - { - while (!check()) - { - if (spin) - { + public void limit() { + while (!check()) { + if (spin) { Thread.yield(); } - else - { - try - { + else { + try { Thread.sleep(1); } - catch (Exception e) - { + catch (Exception e) { // Ignore } } } } - private boolean check() - { + private boolean check() { long now = System.currentTimeMillis(); - if (last == 0) - { + if (last == 0) { last = now; } long diff = now - last; - if (diff >= window) - { + if (diff >= window) { last = System.currentTimeMillis(); tokens = rate; } - if (tokens > 0) - { + if (tokens > 0) { tokens--; return true; } - else - { + else { return false; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/VersionLoader.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/VersionLoader.java index 0dcf95569e..6e54c5d0a9 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/VersionLoader.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/VersionLoader.java @@ -36,8 +36,8 @@ import org.apache.activemq.artemis.core.version.impl.VersionImpl; /** * This loads the version info in from a version.properties file. */ -public final class VersionLoader -{ +public final class VersionLoader { + public static final String VERSION_PROP_FILE_KEY = "activemq.version.property.filename"; public static final String DEFAULT_PROP_FILE_NAME = "activemq-version.properties"; @@ -46,88 +46,70 @@ public final class VersionLoader private static Version[] versions; - static - { - try - { + static { + try { - try - { - PROP_FILE_NAME = AccessController.doPrivileged(new PrivilegedAction() - { - public String run() - { + try { + PROP_FILE_NAME = AccessController.doPrivileged(new PrivilegedAction() { + public String run() { return System.getProperty(VersionLoader.VERSION_PROP_FILE_KEY); } }); } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQClientLogger.LOGGER.warn(e.getMessage(), e); PROP_FILE_NAME = null; } - if (PROP_FILE_NAME == null) - { + if (PROP_FILE_NAME == null) { PROP_FILE_NAME = VersionLoader.DEFAULT_PROP_FILE_NAME; } VersionLoader.versions = VersionLoader.load(); } - catch (Throwable e) - { + catch (Throwable e) { VersionLoader.versions = null; ActiveMQClientLogger.LOGGER.error(e.getMessage(), e); } } - public static Version[] getClientVersions() - { - if (VersionLoader.versions == null) - { + public static Version[] getClientVersions() { + if (VersionLoader.versions == null) { throw new RuntimeException(VersionLoader.PROP_FILE_NAME + " is not available"); } return VersionLoader.versions; } - public static Version getVersion() - { - if (VersionLoader.versions == null) - { + public static Version getVersion() { + if (VersionLoader.versions == null) { throw new RuntimeException(VersionLoader.PROP_FILE_NAME + " is not available"); } return VersionLoader.versions[0]; } - public static String getClasspathString() - { + public static String getClasspathString() { StringBuffer classpath = new StringBuffer(); ClassLoader applicationClassLoader = VersionImpl.class.getClassLoader(); URL[] urls = ((URLClassLoader) applicationClassLoader).getURLs(); - for (URL url : urls) - { + for (URL url : urls) { classpath.append(url.getFile()).append("\r\n"); } return classpath.toString(); } - private static Version[] load() - { + private static Version[] load() { Properties versionProps = new Properties(); final InputStream in = VersionImpl.class.getClassLoader().getResourceAsStream(VersionLoader.PROP_FILE_NAME); - try - { - if (in == null) - { + try { + if (in == null) { ActiveMQClientLogger.LOGGER.noVersionOnClasspath(getClasspathString()); throw new RuntimeException(VersionLoader.PROP_FILE_NAME + " is not available"); } - try - { + try { versionProps.load(in); String versionName = versionProps.getProperty("activemq.version.versionName"); int majorVersion = Integer.valueOf(versionProps.getProperty("activemq.version.majorVersion")); @@ -136,109 +118,84 @@ public final class VersionLoader int[] incrementingVersions = parseCompatibleVersionList(versionProps.getProperty("activemq.version.incrementingVersion")); int[] compatibleVersionArray = parseCompatibleVersionList(versionProps.getProperty("activemq.version.compatibleVersionList")); List definedVersions = new ArrayList(incrementingVersions.length); - for (int incrementingVersion : incrementingVersions) - { - definedVersions.add(new VersionImpl(versionName, - majorVersion, - minorVersion, - microVersion, - incrementingVersion, - compatibleVersionArray)); + for (int incrementingVersion : incrementingVersions) { + definedVersions.add(new VersionImpl(versionName, majorVersion, minorVersion, microVersion, incrementingVersion, compatibleVersionArray)); } //We want the higher version to be the first - Collections.sort(definedVersions, new Comparator() - { + Collections.sort(definedVersions, new Comparator() { @Override - public int compare(Version version1, Version version2) - { + public int compare(Version version1, Version version2) { return version2.getIncrementingVersion() - version1.getIncrementingVersion(); } }); return definedVersions.toArray(new Version[incrementingVersions.length]); } - catch (IOException e) - { + catch (IOException e) { // if we get here then the messaging hasn't been built properly and the version.properties is skewed in some // way throw new RuntimeException("unable to load " + VersionLoader.PROP_FILE_NAME, e); } } - finally - { - try - { + finally { + try { if (in != null) in.close(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } } - private static int[] parseCompatibleVersionList(String property) throws IOException - { + private static int[] parseCompatibleVersionList(String property) throws IOException { int[] verArray = new int[0]; StringTokenizer tokenizer = new StringTokenizer(property, ","); - while (tokenizer.hasMoreTokens()) - { + while (tokenizer.hasMoreTokens()) { int from = -1, to = -1; String token = tokenizer.nextToken(); int cursor = 0; char firstChar = token.charAt(0); - if (firstChar == '-') - { + if (firstChar == '-') { // "-n" pattern from = 0; cursor++; - for (; cursor < token.length() && Character.isDigit(token.charAt(cursor)); cursor++) - { + for (; cursor < token.length() && Character.isDigit(token.charAt(cursor)); cursor++) { // do nothing } - if (cursor > 1) - { + if (cursor > 1) { to = Integer.parseInt(token.substring(1, cursor)); } } - else if (Character.isDigit(firstChar)) - { - for (; cursor < token.length() && Character.isDigit(token.charAt(cursor)); cursor++) - { + else if (Character.isDigit(firstChar)) { + for (; cursor < token.length() && Character.isDigit(token.charAt(cursor)); cursor++) { // do nothing } from = Integer.parseInt(token.substring(0, cursor)); - if (cursor == token.length()) - { + if (cursor == token.length()) { // just "n" pattern to = from; } - else if (token.charAt(cursor) == '-') - { + else if (token.charAt(cursor) == '-') { cursor++; - if (cursor == token.length()) - { + if (cursor == token.length()) { // "n-" pattern to = Integer.MAX_VALUE; } - else - { + else { // "n-n" pattern to = Integer.parseInt(token.substring(cursor)); } } } - if (from != -1 && to != -1) - { + if (from != -1 && to != -1) { // merge version array int[] newArray = new int[verArray.length + to - from + 1]; System.arraycopy(verArray, 0, newArray, 0, verArray.length); - for (int i = 0; i < to - from + 1; i++) - { + for (int i = 0; i < to - from + 1; i++) { newArray[verArray.length + i] = from + i; } verArray = newArray; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/XMLUtil.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/XMLUtil.java index e9749fee98..e022a0de63 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/XMLUtil.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/XMLUtil.java @@ -43,43 +43,35 @@ import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; -public final class XMLUtil -{ +public final class XMLUtil { - private XMLUtil() - { + private XMLUtil() { // Utility class } - public static Element stringToElement(final String s) throws Exception - { + public static Element stringToElement(final String s) throws Exception { return XMLUtil.readerToElement(new StringReader(s)); } - public static Element urlToElement(final URL url) throws Exception - { + public static Element urlToElement(final URL url) throws Exception { return XMLUtil.readerToElement(new InputStreamReader(url.openStream())); } - public static String readerToString(final Reader r) throws Exception - { + public static String readerToString(final Reader r) throws Exception { // Read into string StringBuilder buff = new StringBuilder(); int c; - while ((c = r.read()) != -1) - { + while ((c = r.read()) != -1) { buff.append((char) c); } return buff.toString(); } - public static Element readerToElement(final Reader r) throws Exception - { + public static Element readerToElement(final Reader r) throws Exception { // Read into string StringBuffer buff = new StringBuffer(); int c; - while ((c = r.read()) != -1) - { + while ((c = r.read()) != -1) { buff.append((char) c); } @@ -96,20 +88,17 @@ public final class XMLUtil return doc.getDocumentElement(); } - public static String elementToString(final Node n) - { + public static String elementToString(final Node n) { String name = n.getNodeName(); short type = n.getNodeType(); - if (Node.CDATA_SECTION_NODE == type) - { + if (Node.CDATA_SECTION_NODE == type) { return ""; } - if (name.startsWith("#")) - { + if (name.startsWith("#")) { return ""; } @@ -117,10 +106,8 @@ public final class XMLUtil sb.append('<').append(name); NamedNodeMap attrs = n.getAttributes(); - if (attrs != null) - { - for (int i = 0; i < attrs.getLength(); i++) - { + if (attrs != null) { + for (int i = 0; i < attrs.getLength(); i++) { Node attr = attrs.item(i); sb.append(' ').append(attr.getNodeName()).append("=\"").append(attr.getNodeValue()).append("\""); } @@ -129,33 +116,26 @@ public final class XMLUtil String textContent = null; NodeList children = n.getChildNodes(); - if (children.getLength() == 0) - { - if ((textContent = XMLUtil.getTextContent(n)) != null && !"".equals(textContent)) - { + if (children.getLength() == 0) { + if ((textContent = XMLUtil.getTextContent(n)) != null && !"".equals(textContent)) { sb.append(textContent).append("'); } - else - { + else { sb.append("/>").append('\n'); } } - else - { + else { sb.append('>').append('\n'); boolean hasValidChildren = false; - for (int i = 0; i < children.getLength(); i++) - { + for (int i = 0; i < children.getLength(); i++) { String childToString = XMLUtil.elementToString(children.item(i)); - if (!"".equals(childToString)) - { + if (!"".equals(childToString)) { sb.append(childToString); hasValidChildren = true; } } - if (!hasValidChildren && (textContent = XMLUtil.getTextContent(n)) != null) - { + if (!hasValidChildren && (textContent = XMLUtil.getTextContent(n)) != null) { sb.append(textContent); } @@ -176,40 +156,31 @@ public final class XMLUtil *

    * TODO implementation of this method is a hack. Implement it properly. */ - public static String getTextContent(final Node n) - { - if (n.hasChildNodes()) - { + public static String getTextContent(final Node n) { + if (n.hasChildNodes()) { StringBuffer sb = new StringBuffer(); NodeList nl = n.getChildNodes(); - for (int i = 0; i < nl.getLength(); i++) - { + for (int i = 0; i < nl.getLength(); i++) { sb.append(XMLUtil.elementToString(nl.item(i))); - if (i < nl.getLength() - 1) - { + if (i < nl.getLength() - 1) { sb.append('\n'); } } String s = sb.toString(); - if (s.length() != 0) - { + if (s.length() != 0) { return s; } } Method[] methods = Node.class.getMethods(); - for (Method getTextContext : methods) - { - if ("getTextContent".equals(getTextContext.getName())) - { - try - { + for (Method getTextContext : methods) { + if ("getTextContent".equals(getTextContext.getName())) { + try { return (String) getTextContext.invoke(n, XMLUtil.EMPTY_ARRAY); } - catch (Exception e) - { + catch (Exception e) { ActiveMQClientLogger.LOGGER.errorOnXMLTransform(e, n); return null; } @@ -218,31 +189,24 @@ public final class XMLUtil String textContent = null; - if (n.hasChildNodes()) - { + if (n.hasChildNodes()) { NodeList nl = n.getChildNodes(); - for (int i = 0; i < nl.getLength(); i++) - { + for (int i = 0; i < nl.getLength(); i++) { Node c = nl.item(i); - if (c.getNodeType() == Node.TEXT_NODE) - { + if (c.getNodeType() == Node.TEXT_NODE) { textContent = n.getNodeValue(); - if (textContent == null) - { + if (textContent == null) { // TODO This is a hack. Get rid of it and implement this properly String s = c.toString(); int idx = s.indexOf("#text:"); - if (idx != -1) - { + if (idx != -1) { textContent = s.substring(idx + 6).trim(); - if (textContent.endsWith("]")) - { + if (textContent.endsWith("]")) { textContent = textContent.substring(0, textContent.length() - 1); } } } - if (textContent == null) - { + if (textContent == null) { break; } } @@ -252,8 +216,7 @@ public final class XMLUtil String s = n.toString(); int i = s.indexOf('>'); int i2 = s.indexOf(""); - if (i == -1) - { + if (i == -1) { throw new IllegalStateException("argument starts with "); } s = s.substring(0, i); @@ -382,21 +328,17 @@ public final class XMLUtil } return xml; }*/ - public static String replaceSystemProps(String xml) - { - while (xml.contains("${")) - { + public static String replaceSystemProps(String xml) { + while (xml.contains("${")) { int start = xml.indexOf("${"); int end = xml.indexOf("}") + 1; - if (end < 0) - { + if (end < 0) { break; } String subString = xml.substring(start, end); String prop = subString.substring(2, subString.length() - 1).trim(); String val = ""; - if (prop.contains(":")) - { + if (prop.contains(":")) { String[] parts = prop.split(":", 2); prop = parts[0].trim(); val = parts[1].trim(); @@ -409,95 +351,76 @@ public final class XMLUtil return xml; } - public static long parseLong(final Node elem) - { + public static long parseLong(final Node elem) { String value = elem.getTextContent().trim(); - try - { + try { return Long.parseLong(value); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { throw ActiveMQClientMessageBundle.BUNDLE.mustBeLong(elem, value); } } - public static int parseInt(final Node elem) - { + public static int parseInt(final Node elem) { String value = elem.getTextContent().trim(); - try - { + try { return Integer.parseInt(value); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { throw ActiveMQClientMessageBundle.BUNDLE.mustBeInteger(elem, value); } } - public static boolean parseBoolean(final Node elem) - { + public static boolean parseBoolean(final Node elem) { String value = elem.getTextContent().trim(); - try - { + try { return Boolean.parseBoolean(value); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { throw ActiveMQClientMessageBundle.BUNDLE.mustBeBoolean(elem, value); } } - public static double parseDouble(final Node elem) - { + public static double parseDouble(final Node elem) { String value = elem.getTextContent().trim(); - try - { + try { return Double.parseDouble(value); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { throw ActiveMQClientMessageBundle.BUNDLE.mustBeDouble(elem, value); } } - public static void validate(final Node node, final String schemaFile) throws Exception - { + public static void validate(final Node node, final String schemaFile) throws Exception { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(findResource(schemaFile)); Validator validator = schema.newValidator(); // validate the DOM tree - try - { + try { validator.validate(new DOMSource(node)); } - catch (SAXException e) - { + catch (SAXException e) { ActiveMQClientLogger.LOGGER.errorOnXMLTransformInvalidConf(e); throw new IllegalStateException("Invalid configuration", e); } } - private static List filter(final NodeList nl, final short[] typesToFilter) - { + private static List filter(final NodeList nl, final short[] typesToFilter) { List nodes = new ArrayList(); outer: - for (int i = 0; i < nl.getLength(); i++) - { + for (int i = 0; i < nl.getLength(); i++) { Node n = nl.item(i); short type = n.getNodeType(); - for (int j = 0; j < typesToFilter.length; j++) - { - if (typesToFilter[j] == type) - { + for (int j = 0; j < typesToFilter.length; j++) { + if (typesToFilter[j] == type) { continue outer; } } @@ -506,18 +429,14 @@ public final class XMLUtil return nodes; } - private static URL findResource(final String resourceName) - { - return AccessController.doPrivileged(new PrivilegedAction() - { - public URL run() - { + private static URL findResource(final String resourceName) { + return AccessController.doPrivileged(new PrivilegedAction() { + public URL run() { return ClassloadingUtil.findResource(resourceName); } }); } - // Inner classes -------------------------------------------------------------------------------- } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/XidCodecSupport.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/XidCodecSupport.java index 59bfcb30b2..6a0916480d 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/XidCodecSupport.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/XidCodecSupport.java @@ -21,8 +21,7 @@ import javax.transaction.xa.Xid; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.transaction.impl.XidImpl; -public class XidCodecSupport -{ +public class XidCodecSupport { // Constants ----------------------------------------------------- @@ -30,8 +29,7 @@ public class XidCodecSupport // Static -------------------------------------------------------- - public static void encodeXid(final Xid xid, final ActiveMQBuffer out) - { + public static void encodeXid(final Xid xid, final ActiveMQBuffer out) { out.writeInt(xid.getFormatId()); out.writeInt(xid.getBranchQualifier().length); out.writeBytes(xid.getBranchQualifier()); @@ -39,8 +37,7 @@ public class XidCodecSupport out.writeBytes(xid.getGlobalTransactionId()); } - public static Xid decodeXid(final ActiveMQBuffer in) - { + public static Xid decodeXid(final ActiveMQBuffer in) { int formatID = in.readInt(); byte[] bq = new byte[in.readInt()]; in.readBytes(bq); @@ -50,8 +47,7 @@ public class XidCodecSupport return xid; } - public static int getXidEncodeLength(final Xid xid) - { + public static int getXidEncodeLength(final Xid xid) { return DataConstants.SIZE_INT * 3 + xid.getBranchQualifier().length + xid.getGlobalTransactionId().length; } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONArray.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONArray.java index daa570971d..0cbaf72ad4 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONArray.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONArray.java @@ -59,25 +59,24 @@ import java.util.Map; * accept: *

      *
    • An extra , (comma) may appear just - * before the closing bracket.
    • + * before the closing bracket. *
    • The {@code null} value will be inserted when there - * is , (comma) elision.
    • + * is , (comma) elision. *
    • Strings may be quoted with ' (single - * quote).
    • + * quote). *
    • Strings do not need to be quoted at all if they do not begin with a quote - * or single quote, and if they do not contain leading or trailing spaces, - * and if they do not contain any of these characters: - * { } [ ] / \ : , = ; # and if they do not look like numbers - * and if they are not the reserved words true, - * false, or {@code null}.
    • + * or single quote, and if they do not contain leading or trailing spaces, + * and if they do not contain any of these characters: + * { } [ ] / \ : , = ; # and if they do not look like numbers + * and if they are not the reserved words true, + * false, or {@code null}. *
    • Values can be separated by ; (semicolon) as - * well as by , (comma).
    • + * well as by , (comma). *
    • Numbers may have the 0- (octal) or - * 0x- (hex) prefix.
    • + * 0x- (hex) prefix. *
    */ -public class JSONArray -{ +public class JSONArray { /** * The arrayList where the JSONArray's properties are kept. @@ -87,65 +86,54 @@ public class JSONArray /** * Construct an empty JSONArray. */ - public JSONArray() - { + public JSONArray() { myArrayList = new ArrayList(); } /** * Construct a JSONArray from a JSONTokener. + * * @param x A JSONTokener * @throws JSONException If there is a syntax error. */ - public JSONArray(final JSONTokener x) throws JSONException - { + public JSONArray(final JSONTokener x) throws JSONException { this(); char c = x.nextClean(); char q; - if (c == '[') - { + if (c == '[') { q = ']'; } - else if (c == '(') - { + else if (c == '(') { q = ')'; } - else - { + else { throw x.syntaxError("A JSONArray text must start with '['"); } - if (x.nextClean() == ']') - { + if (x.nextClean() == ']') { return; } x.back(); - for (;;) - { - if (x.nextClean() == ',') - { + for (;;) { + if (x.nextClean() == ',') { x.back(); myArrayList.add(null); } - else - { + else { x.back(); myArrayList.add(x.nextValue()); } c = x.nextClean(); - switch (c) - { + switch (c) { case ';': case ',': - if (x.nextClean() == ']') - { + if (x.nextClean() == ']') { return; } x.back(); break; case ']': case ')': - if (q != c) - { + if (q != c) { throw x.syntaxError("Expected a '" + Character.valueOf(q) + "'"); } return; @@ -157,22 +145,22 @@ public class JSONArray /** * Construct a JSONArray from a source JSON text. - * @param source A string that begins with - * [ (left bracket) - * and ends with ] (right bracket). - * @throws JSONException If there is a syntax error. + * + * @param source A string that begins with + * [ (left bracket) + * and ends with ] (right bracket). + * @throws JSONException If there is a syntax error. */ - public JSONArray(final String source) throws JSONException - { + public JSONArray(final String source) throws JSONException { this(new JSONTokener(source)); } /** * Construct a JSONArray from a Collection. - * @param collection A Collection. + * + * @param collection A Collection. */ - public JSONArray(final Collection collection) - { + public JSONArray(final Collection collection) { myArrayList = collection == null ? new ArrayList() : new ArrayList(collection); } @@ -180,25 +168,19 @@ public class JSONArray * Construct a JSONArray from a collection of beans. * The collection should have Java Beans. */ - public JSONArray(final Collection collection, final boolean includeSuperClass) - { + public JSONArray(final Collection collection, final boolean includeSuperClass) { myArrayList = collection == null ? new ArrayList() : new ArrayList(collection.size()); - if (collection != null) - { + if (collection != null) { Iterator iter = collection.iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { Object o = iter.next(); - if (o instanceof Map) - { - myArrayList.add(new JSONObject((Map)o, includeSuperClass)); + if (o instanceof Map) { + myArrayList.add(new JSONObject((Map) o, includeSuperClass)); } - else if (!JSONObject.isStandardProperty(o.getClass())) - { + else if (!JSONObject.isStandardProperty(o.getClass())) { myArrayList.add(new JSONObject(o, includeSuperClass)); } - else - { + else { myArrayList.add(o); } } @@ -207,21 +189,18 @@ public class JSONArray /** * Construct a JSONArray from an array + * * @throws JSONException If not an array. */ - public JSONArray(final Object array) throws JSONException - { + public JSONArray(final Object array) throws JSONException { this(); - if (array.getClass().isArray()) - { + if (array.getClass().isArray()) { int length = Array.getLength(array); - for (int i = 0; i < length; i += 1) - { + for (int i = 0; i < length; i += 1) { this.put(Array.get(array, i)); } } - else - { + else { throw new JSONException("JSONArray initial value should be a string or collection or array."); } } @@ -232,43 +211,35 @@ public class JSONArray * * @throws JSONException If not an array. */ - public JSONArray(final Object array, final boolean includeSuperClass) throws JSONException - { + public JSONArray(final Object array, final boolean includeSuperClass) throws JSONException { this(); - if (array.getClass().isArray()) - { + if (array.getClass().isArray()) { int length = Array.getLength(array); - for (int i = 0; i < length; i += 1) - { + for (int i = 0; i < length; i += 1) { Object o = Array.get(array, i); - if (JSONObject.isStandardProperty(o.getClass())) - { + if (JSONObject.isStandardProperty(o.getClass())) { myArrayList.add(o); } - else - { + else { myArrayList.add(new JSONObject(o, includeSuperClass)); } } } - else - { + else { throw new JSONException("JSONArray initial value should be a string or collection or array."); } } /** * Get the object value associated with an index. - * @param index - * The index must be between 0 and length() - 1. + * + * @param index The index must be between 0 and length() - 1. * @return An object value. * @throws JSONException If there is no value for the index. */ - public Object get(final int index) throws JSONException - { + public Object get(final int index) throws JSONException { Object o = opt(index); - if (o == null) - { + if (o == null) { throw new JSONException("JSONArray[" + index + "] not found."); } return o; @@ -279,19 +250,16 @@ public class JSONArray * The string values "true" and "false" are converted to boolean. * * @param index The index must be between 0 and length() - 1. - * @return The truth. + * @return The truth. * @throws JSONException If there is no value for the index or if the - * value is not convertable to boolean. + * value is not convertable to boolean. */ - public boolean getBoolean(final int index) throws JSONException - { + public boolean getBoolean(final int index) throws JSONException { Object o = get(index); - if (o.equals(Boolean.FALSE) || o instanceof String && ((String)o).equalsIgnoreCase("false")) - { + if (o.equals(Boolean.FALSE) || o instanceof String && ((String) o).equalsIgnoreCase("false")) { return false; } - else if (o.equals(Boolean.TRUE) || o instanceof String && ((String)o).equalsIgnoreCase("true")) - { + else if (o.equals(Boolean.TRUE) || o instanceof String && ((String) o).equalsIgnoreCase("true")) { return true; } throw new JSONException("JSONArray[" + index + "] is not a Boolean."); @@ -301,19 +269,16 @@ public class JSONArray * Get the double value associated with an index. * * @param index The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException If the key is not found or if the value cannot - * be converted to a number. + * @return The value. + * @throws JSONException If the key is not found or if the value cannot + * be converted to a number. */ - public double getDouble(final int index) throws JSONException - { + public double getDouble(final int index) throws JSONException { Object o = get(index); - try - { - return o instanceof Number ? ((Number)o).doubleValue() : Double.valueOf((String)o).doubleValue(); + try { + return o instanceof Number ? ((Number) o).doubleValue() : Double.valueOf((String) o).doubleValue(); } - catch (Exception e) - { + catch (Exception e) { throw new JSONException("JSONArray[" + index + "] is not a number."); } } @@ -322,47 +287,44 @@ public class JSONArray * Get the int value associated with an index. * * @param index The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException If the key is not found or if the value cannot - * be converted to a number. - * if the value cannot be converted to a number. + * @return The value. + * @throws JSONException If the key is not found or if the value cannot + * be converted to a number. + * if the value cannot be converted to a number. */ - public int getInt(final int index) throws JSONException - { + public int getInt(final int index) throws JSONException { Object o = get(index); - return o instanceof Number ? ((Number)o).intValue() : (int)getDouble(index); + return o instanceof Number ? ((Number) o).intValue() : (int) getDouble(index); } /** * Get the JSONArray associated with an index. + * * @param index The index must be between 0 and length() - 1. - * @return A JSONArray value. + * @return A JSONArray value. * @throws JSONException If there is no value for the index. or if the - * value is not a JSONArray + * value is not a JSONArray */ - public JSONArray getJSONArray(final int index) throws JSONException - { + public JSONArray getJSONArray(final int index) throws JSONException { Object o = get(index); - if (o instanceof JSONArray) - { - return (JSONArray)o; + if (o instanceof JSONArray) { + return (JSONArray) o; } throw new JSONException("JSONArray[" + index + "] is not a JSONArray."); } /** * Get the JSONObject associated with an index. + * * @param index subscript - * @return A JSONObject value. + * @return A JSONObject value. * @throws JSONException If there is no value for the index or if the - * value is not a JSONObject + * value is not a JSONObject */ - public JSONObject getJSONObject(final int index) throws JSONException - { + public JSONObject getJSONObject(final int index) throws JSONException { Object o = get(index); - if (o instanceof JSONObject) - { - return (JSONObject)o; + if (o instanceof JSONObject) { + return (JSONObject) o; } throw new JSONException("JSONArray[" + index + "] is not a JSONObject."); } @@ -371,34 +333,33 @@ public class JSONArray * Get the long value associated with an index. * * @param index The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException If the key is not found or if the value cannot - * be converted to a number. + * @return The value. + * @throws JSONException If the key is not found or if the value cannot + * be converted to a number. */ - public long getLong(final int index) throws JSONException - { + public long getLong(final int index) throws JSONException { Object o = get(index); - return o instanceof Number ? ((Number)o).longValue() : (long)getDouble(index); + return o instanceof Number ? ((Number) o).longValue() : (long) getDouble(index); } /** * Get the string associated with an index. + * * @param index The index must be between 0 and length() - 1. - * @return A string value. + * @return A string value. * @throws JSONException If there is no value for the index. */ - public String getString(final int index) throws JSONException - { + public String getString(final int index) throws JSONException { return get(index).toString(); } /** * Determine if the value is null. + * * @param index The index must be between 0 and length() - 1. * @return true if the value at the index is null, or if there is no value. */ - public boolean isNull(final int index) - { + public boolean isNull(final int index) { return JSONObject.NULL.equals(opt(index)); } @@ -406,19 +367,17 @@ public class JSONArray * Make a string from the contents of this JSONArray. The * separator string is inserted between each element. * Warning: This method assumes that the data structure is acyclical. + * * @param separator A string that will be inserted between the elements. * @return a string. * @throws JSONException If the array contains an invalid number. */ - public String join(final String separator) throws JSONException - { + public String join(final String separator) throws JSONException { int len = length(); StringBuffer sb = new StringBuffer(); - for (int i = 0; i < len; i += 1) - { - if (i > 0) - { + for (int i = 0; i < len; i += 1) { + if (i > 0) { sb.append(separator); } sb.append(JSONObject.valueToString(myArrayList.get(i))); @@ -431,19 +390,18 @@ public class JSONArray * * @return The length (or size). */ - public int length() - { + public int length() { return myArrayList.size(); } /** * Get the optional object value associated with an index. + * * @param index The index must be between 0 and length() - 1. - * @return An object value, or null if there is no - * object at that index. + * @return An object value, or null if there is no + * object at that index. */ - public Object opt(final int index) - { + public Object opt(final int index) { return index < 0 || index >= length() ? null : myArrayList.get(index); } @@ -453,10 +411,9 @@ public class JSONArray * or if the value is not Boolean.TRUE or the String "true". * * @param index The index must be between 0 and length() - 1. - * @return The truth. + * @return The truth. */ - public boolean optBoolean(final int index) - { + public boolean optBoolean(final int index) { return optBoolean(index, false); } @@ -465,18 +422,15 @@ public class JSONArray * It returns the defaultValue if there is no value at that index or if * it is not a Boolean or the String "true" or "false" (case insensitive). * - * @param index The index must be between 0 and length() - 1. - * @param defaultValue A boolean default. - * @return The truth. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue A boolean default. + * @return The truth. */ - public boolean optBoolean(final int index, final boolean defaultValue) - { - try - { + public boolean optBoolean(final int index, final boolean defaultValue) { + try { return getBoolean(index); } - catch (Exception e) - { + catch (Exception e) { return defaultValue; } } @@ -487,10 +441,9 @@ public class JSONArray * or if the value is not a number and cannot be converted to a number. * * @param index The index must be between 0 and length() - 1. - * @return The value. + * @return The value. */ - public double optDouble(final int index) - { + public double optDouble(final int index) { return optDouble(index, Double.NaN); } @@ -499,18 +452,15 @@ public class JSONArray * The defaultValue is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. * - * @param index subscript - * @param defaultValue The default value. - * @return The value. + * @param index subscript + * @param defaultValue The default value. + * @return The value. */ - public double optDouble(final int index, final double defaultValue) - { - try - { + public double optDouble(final int index, final double defaultValue) { + try { return getDouble(index); } - catch (Exception e) - { + catch (Exception e) { return defaultValue; } } @@ -521,10 +471,9 @@ public class JSONArray * or if the value is not a number and cannot be converted to a number. * * @param index The index must be between 0 and length() - 1. - * @return The value. + * @return The value. */ - public int optInt(final int index) - { + public int optInt(final int index) { return optInt(index, 0); } @@ -532,32 +481,30 @@ public class JSONArray * Get the optional int value associated with an index. * The defaultValue is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. - * @param index The index must be between 0 and length() - 1. - * @param defaultValue The default value. - * @return The value. + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. + * @return The value. */ - public int optInt(final int index, final int defaultValue) - { - try - { + public int optInt(final int index, final int defaultValue) { + try { return getInt(index); } - catch (Exception e) - { + catch (Exception e) { return defaultValue; } } /** * Get the optional JSONArray associated with an index. + * * @param index subscript - * @return A JSONArray value, or null if the index has no value, + * @return A JSONArray value, or null if the index has no value, * or if the value is not a JSONArray. */ - public JSONArray optJSONArray(final int index) - { + public JSONArray optJSONArray(final int index) { Object o = opt(index); - return o instanceof JSONArray ? (JSONArray)o : null; + return o instanceof JSONArray ? (JSONArray) o : null; } /** @@ -566,12 +513,11 @@ public class JSONArray * no value, or if the value is not a JSONObject. * * @param index The index must be between 0 and length() - 1. - * @return A JSONObject value. + * @return A JSONObject value. */ - public JSONObject optJSONObject(final int index) - { + public JSONObject optJSONObject(final int index) { Object o = opt(index); - return o instanceof JSONObject ? (JSONObject)o : null; + return o instanceof JSONObject ? (JSONObject) o : null; } /** @@ -580,10 +526,9 @@ public class JSONArray * or if the value is not a number and cannot be converted to a number. * * @param index The index must be between 0 and length() - 1. - * @return The value. + * @return The value. */ - public long optLong(final int index) - { + public long optLong(final int index) { return optLong(index, 0); } @@ -591,18 +536,16 @@ public class JSONArray * Get the optional long value associated with an index. * The defaultValue is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. - * @param index The index must be between 0 and length() - 1. - * @param defaultValue The default value. - * @return The value. + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. + * @return The value. */ - public long optLong(final int index, final long defaultValue) - { - try - { + public long optLong(final int index, final long defaultValue) { + try { return getLong(index); } - catch (Exception e) - { + catch (Exception e) { return defaultValue; } } @@ -613,10 +556,9 @@ public class JSONArray * is not a string and is not null, then it is converted to a string. * * @param index The index must be between 0 and length() - 1. - * @return A String value. + * @return A String value. */ - public String optString(final int index) - { + public String optString(final int index) { return optString(index, ""); } @@ -624,12 +566,11 @@ public class JSONArray * Get the optional string associated with an index. * The defaultValue is returned if the key is not found. * - * @param index The index must be between 0 and length() - 1. - * @param defaultValue The default value. - * @return A String value. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. + * @return A String value. */ - public String optString(final int index, final String defaultValue) - { + public String optString(final int index, final String defaultValue) { Object o = opt(index); return o != null ? o.toString() : defaultValue; } @@ -640,8 +581,7 @@ public class JSONArray * @param value A boolean value. * @return this. */ - public JSONArray put(final boolean value) - { + public JSONArray put(final boolean value) { put(value ? Boolean.TRUE : Boolean.FALSE); return this; } @@ -649,11 +589,11 @@ public class JSONArray /** * Put a value in the JSONArray, where the value will be a * JSONArray which is produced from a Collection. + * * @param value A Collection value. - * @return this. + * @return this. */ - public JSONArray put(final Collection value) - { + public JSONArray put(final Collection value) { put(new JSONArray(value)); return this; } @@ -662,11 +602,10 @@ public class JSONArray * Append a double value. This increases the array's length by one. * * @param value A double value. - * @throws JSONException if the value is not finite. * @return this. + * @throws JSONException if the value is not finite. */ - public JSONArray put(final double value) throws JSONException - { + public JSONArray put(final double value) throws JSONException { Double d = new Double(value); JSONObject.testValidity(d); put(d); @@ -679,8 +618,7 @@ public class JSONArray * @param value An int value. * @return this. */ - public JSONArray put(final int value) - { + public JSONArray put(final int value) { put(Integer.valueOf(value)); return this; } @@ -691,8 +629,7 @@ public class JSONArray * @param value A long value. * @return this. */ - public JSONArray put(final long value) - { + public JSONArray put(final long value) { put(Long.valueOf(value)); return this; } @@ -700,24 +637,24 @@ public class JSONArray /** * Put a value in the JSONArray, where the value will be a * JSONObject which is produced from a Map. + * * @param value A Map value. - * @return this. + * @return this. */ - public JSONArray put(final Map value) - { + public JSONArray put(final Map value) { put(new JSONObject(value)); return this; } /** * Append an object value. This increases the array's length by one. + * * @param value An object value. The value should be a - * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the - * JSONObject.NULL object. + * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the + * JSONObject.NULL object. * @return this. */ - public JSONArray put(final Object value) - { + public JSONArray put(final Object value) { myArrayList.add(value); return this; } @@ -726,13 +663,13 @@ public class JSONArray * Put or replace a boolean value in the JSONArray. If the index is greater * than the length of the JSONArray, then null elements will be added as * necessary to pad it out. + * * @param index The subscript. * @param value A boolean value. * @return this. * @throws JSONException If the index is negative. */ - public JSONArray put(final int index, final boolean value) throws JSONException - { + public JSONArray put(final int index, final boolean value) throws JSONException { put(index, value ? Boolean.TRUE : Boolean.FALSE); return this; } @@ -740,60 +677,60 @@ public class JSONArray /** * Put a value in the JSONArray, where the value will be a * JSONArray which is produced from a Collection. + * * @param index The subscript. * @param value A Collection value. - * @return this. + * @return this. * @throws JSONException If the index is negative or if the value is - * not finite. + * not finite. */ - public JSONArray put(final int index, final Collection value) throws JSONException - { + public JSONArray put(final int index, final Collection value) throws JSONException { put(index, new JSONArray(value)); return this; } /** * Put or replace a double value. If the index is greater than the length of - * the JSONArray, then null elements will be added as necessary to pad - * it out. + * the JSONArray, then null elements will be added as necessary to pad + * it out. + * * @param index The subscript. * @param value A double value. * @return this. * @throws JSONException If the index is negative or if the value is - * not finite. + * not finite. */ - public JSONArray put(final int index, final double value) throws JSONException - { + public JSONArray put(final int index, final double value) throws JSONException { put(index, new Double(value)); return this; } /** * Put or replace an int value. If the index is greater than the length of - * the JSONArray, then null elements will be added as necessary to pad - * it out. + * the JSONArray, then null elements will be added as necessary to pad + * it out. + * * @param index The subscript. * @param value An int value. * @return this. * @throws JSONException If the index is negative. */ - public JSONArray put(final int index, final int value) throws JSONException - { + public JSONArray put(final int index, final int value) throws JSONException { put(index, Integer.valueOf(value)); return this; } /** * Put or replace a long value. If the index is greater than the length of - * the JSONArray, then null elements will be added as necessary to pad - * it out. + * the JSONArray, then null elements will be added as necessary to pad + * it out. + * * @param index The subscript. * @param value A long value. * @return this. * @throws JSONException If the index is negative. */ - public JSONArray put(final int index, final long value) throws JSONException - { + public JSONArray put(final int index, final long value) throws JSONException { put(index, Long.valueOf(value)); return this; } @@ -801,45 +738,41 @@ public class JSONArray /** * Put a value in the JSONArray, where the value will be a * JSONObject which is produced from a Map. + * * @param index The subscript. * @param value The Map value. - * @return this. + * @return this. * @throws JSONException If the index is negative or if the the value is - * an invalid number. + * an invalid number. */ - public JSONArray put(final int index, final Map value) throws JSONException - { + public JSONArray put(final int index, final Map value) throws JSONException { put(index, new JSONObject(value)); return this; } /** * Put or replace an object value in the JSONArray. If the index is greater - * than the length of the JSONArray, then null elements will be added as - * necessary to pad it out. + * than the length of the JSONArray, then null elements will be added as + * necessary to pad it out. + * * @param index The subscript. * @param value The value to put into the array. The value should be a - * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the - * JSONObject.NULL object. + * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the + * JSONObject.NULL object. * @return this. * @throws JSONException If the index is negative or if the the value is - * an invalid number. + * an invalid number. */ - public JSONArray put(final int index, final Object value) throws JSONException - { + public JSONArray put(final int index, final Object value) throws JSONException { JSONObject.testValidity(value); - if (index < 0) - { + if (index < 0) { throw new JSONException("JSONArray[" + index + "] not found."); } - if (index < length()) - { + if (index < length()) { myArrayList.set(index, value); } - else - { - while (index != length()) - { + else { + while (index != length()) { put(JSONObject.NULL); } put(value); @@ -849,12 +782,12 @@ public class JSONArray /** * Remove an index and close the hole. + * * @param index The index of the element to be removed. * @return The value that was associated with the index, * or null if there was no value. */ - public Object remove(final int index) - { + public Object remove(final int index) { Object o = opt(index); myArrayList.remove(index); return o; @@ -863,21 +796,19 @@ public class JSONArray /** * Produce a JSONObject by combining a JSONArray of names with the values * of this JSONArray. + * * @param names A JSONArray containing a list of key strings. These will be - * paired with the values. + * paired with the values. * @return A JSONObject, or null if there are no names or if this JSONArray * has no values. * @throws JSONException If any of the names are null. */ - public JSONObject toJSONObject(final JSONArray names) throws JSONException - { - if (names == null || names.length() == 0 || length() == 0) - { + public JSONObject toJSONObject(final JSONArray names) throws JSONException { + if (names == null || names.length() == 0 || length() == 0) { return null; } JSONObject jo = new JSONObject(); - for (int i = 0; i < names.length(); i += 1) - { + for (int i = 0; i < names.length(); i += 1) { jo.put(names.getString(i), opt(i)); } return jo; @@ -892,17 +823,14 @@ public class JSONArray * Warning: This method assumes that the data structure is acyclical. * * @return a printable, displayable, transmittable - * representation of the array. + * representation of the array. */ @Override - public String toString() - { - try - { + public String toString() { + try { return '[' + join(",") + ']'; } - catch (Exception e) - { + catch (Exception e) { return ""; } } @@ -910,57 +838,50 @@ public class JSONArray /** * Make a pretty-printed JSON text of this JSONArray. Warning: This method assumes that the data * structure is acyclical. + * * @param indentFactor The number of spaces to add to each level of indentation. * @return a printable, displayable, transmittable representation of the object, beginning with - * [ (left bracket) and ending with ] - *  (right bracket). + * [ (left bracket) and ending with ] + *  (right bracket). * @throws JSONException */ - public String toString(final int indentFactor) throws JSONException - { + public String toString(final int indentFactor) throws JSONException { return toString(indentFactor, 0); } /** * Make a pretty-printed JSON text of this JSONArray. Warning: This method assumes that the data * structure is acyclical. + * * @param indentFactor The number of spaces to add to each level of indentation. - * @param indent The indention of the top level. + * @param indent The indention of the top level. * @return a printable, displayable, transmittable representation of the array. * @throws JSONException */ - String toString(final int indentFactor, final int indent) throws JSONException - { + String toString(final int indentFactor, final int indent) throws JSONException { int len = length(); - if (len == 0) - { + if (len == 0) { return "[]"; } int i; StringBuffer sb = new StringBuffer("["); - if (len == 1) - { + if (len == 1) { sb.append(JSONObject.valueToString(myArrayList.get(0), indentFactor, indent)); } - else - { + else { int newindent = indent + indentFactor; sb.append('\n'); - for (i = 0; i < len; i += 1) - { - if (i > 0) - { + for (i = 0; i < len; i += 1) { + if (i > 0) { sb.append(",\n"); } - for (int j = 0; j < newindent; j += 1) - { + for (int j = 0; j < newindent; j += 1) { sb.append(' '); } sb.append(JSONObject.valueToString(myArrayList.get(i), indentFactor, newindent)); } sb.append('\n'); - for (i = 0; i < indent; i += 1) - { + for (i = 0; i < indent; i += 1) { sb.append(' '); } } @@ -977,32 +898,25 @@ public class JSONArray * @return The writer. * @throws JSONException */ - public Writer write(final Writer writer) throws JSONException - { - try - { + public Writer write(final Writer writer) throws JSONException { + try { boolean b = false; int len = length(); writer.write('['); - for (int i = 0; i < len; i += 1) - { - if (b) - { + for (int i = 0; i < len; i += 1) { + if (b) { writer.write(','); } Object v = myArrayList.get(i); - if (v instanceof JSONObject) - { - ((JSONObject)v).write(writer); + if (v instanceof JSONObject) { + ((JSONObject) v).write(writer); } - else if (v instanceof JSONArray) - { - ((JSONArray)v).write(writer); + else if (v instanceof JSONArray) { + ((JSONArray) v).write(writer); } - else - { + else { writer.write(JSONObject.valueToString(v)); } b = true; @@ -1010,8 +924,7 @@ public class JSONArray writer.write(']'); return writer; } - catch (IOException e) - { + catch (IOException e) { throw new JSONException(e); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONException.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONException.java index 12232d5628..abb79b0429 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONException.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONException.java @@ -26,33 +26,31 @@ package org.apache.activemq.artemis.utils.json; /** * The JSONException is thrown by the JSON.org classes then things are amiss. */ -public class JSONException extends Exception -{ +public class JSONException extends Exception { + /** - * - */ + * + */ private static final long serialVersionUID = -3940674325153571604L; private Throwable cause; /** * Constructs a JSONException with an explanatory message. + * * @param message Detail about the reason for the exception. */ - public JSONException(final String message) - { + public JSONException(final String message) { super(message); } - public JSONException(final Throwable t) - { + public JSONException(final Throwable t) { super(t.getMessage()); cause = t; } @Override - public synchronized Throwable getCause() - { + public synchronized Throwable getCause() { return cause; } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONObject.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONObject.java index 60d87dd85f..c23f7ee2bc 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONObject.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONObject.java @@ -81,54 +81,51 @@ import java.util.TreeSet; * (hex) prefix. * */ -public class JSONObject -{ +public class JSONObject { /** * JSONObject.NULL is equivalent to the value that JavaScript calls null, * whilst Java's null is equivalent to the value that JavaScript calls * undefined. */ - private static final class Null - { + private static final class Null { /** * There is only intended to be a single instance of the NULL object, * so the clone method returns itself. - * @return NULL. + * + * @return NULL. */ @Override - protected Object clone() - { + protected Object clone() { return this; } /** * A Null object is equal to the null value and to itself. - * @param object An object to test for nullness. + * + * @param object An object to test for nullness. * @return true if the object parameter is the JSONObject.NULL object - * or null. + * or null. */ @Override - public boolean equals(final Object object) - { + public boolean equals(final Object object) { return object == null || object == this; } @Override - public int hashCode() - { + public int hashCode() { // TODO return 0; } /** * Get the "null" string value. + * * @return The string "null". */ @Override - public String toString() - { + public String toString() { return "null"; } } @@ -149,8 +146,7 @@ public class JSONObject /** * Construct an empty JSONObject. */ - public JSONObject() - { + public JSONObject() { map = new HashMap(); } @@ -158,40 +154,36 @@ public class JSONObject * Construct a JSONObject from a subset of another JSONObject. * An array of strings is used to identify the keys that should be copied. * Missing keys are ignored. - * @param jo A JSONObject. + * + * @param jo A JSONObject. * @param names An array of strings. - * @exception JSONException If a value is a non-finite number or if a name is duplicated. + * @throws JSONException If a value is a non-finite number or if a name is duplicated. */ - public JSONObject(final JSONObject jo, final String[] names) throws JSONException - { + public JSONObject(final JSONObject jo, final String[] names) throws JSONException { this(); - for (String name : names) - { + for (String name : names) { putOnce(name, jo.opt(name)); } } /** * Construct a JSONObject from a JSONTokener. + * * @param x A JSONTokener object containing the source string. * @throws JSONException If there is a syntax error in the source string - * or a duplicated key. + * or a duplicated key. */ - public JSONObject(final JSONTokener x) throws JSONException - { + public JSONObject(final JSONTokener x) throws JSONException { this(); char c; String key; - if (x.nextClean() != '{') - { + if (x.nextClean() != '{') { throw x.syntaxError("A JSONObject text must begin with '{'"); } - for (;;) - { + for (;;) { c = x.nextClean(); - switch (c) - { + switch (c) { case 0: throw x.syntaxError("A JSONObject text must end with '}'"); case '}': @@ -206,15 +198,12 @@ public class JSONObject */ c = x.nextClean(); - if (c == '=') - { - if (x.next() != '>') - { + if (c == '=') { + if (x.next() != '>') { x.back(); } } - else if (c != ':') - { + else if (c != ':') { throw x.syntaxError("Expected a ':' after a key"); } putOnce(key, x.nextValue()); @@ -223,12 +212,10 @@ public class JSONObject * Pairs are separated by ','. We will also tolerate ';'. */ - switch (x.nextClean()) - { + switch (x.nextClean()) { case ';': case ',': - if (x.nextClean() == '}') - { + if (x.nextClean() == '}') { return; } x.back(); @@ -245,10 +232,9 @@ public class JSONObject * Construct a JSONObject from a Map. * * @param map A map object that can be used to initialize the contents of - * the JSONObject. + * the JSONObject. */ - public JSONObject(final Map map) - { + public JSONObject(final Map map) { this.map = map == null ? new HashMap() : map; } @@ -257,24 +243,19 @@ public class JSONObject * * Note: Use this constructor when the map contains <key,bean>. * - * @param map - A map with Key-Bean data. + * @param map - A map with Key-Bean data. * @param includeSuperClass - Tell whether to include the super class properties. */ - public JSONObject(final Map map, final boolean includeSuperClass) - { + public JSONObject(final Map map, final boolean includeSuperClass) { this.map = new HashMap(); - if (map != null) - { + if (map != null) { Iterator i = map.entrySet().iterator(); - while (i.hasNext()) - { + while (i.hasNext()) { Map.Entry e = i.next(); - if (JSONObject.isStandardProperty(e.getValue().getClass())) - { + if (JSONObject.isStandardProperty(e.getValue().getClass())) { this.map.put(e.getKey(), e.getValue()); } - else - { + else { this.map.put(e.getKey(), new JSONObject(e.getValue(), includeSuperClass)); } } @@ -298,10 +279,9 @@ public class JSONObject * then the JSONObject will contain "name": "Larry Fine". * * @param bean An object that has getter methods that should be used - * to make a JSONObject. + * to make a JSONObject. */ - public JSONObject(final Object bean) - { + public JSONObject(final Object bean) { this(); populateInternalMap(bean, false); } @@ -318,117 +298,93 @@ public class JSONObject * If the second remaining character is not upper case, then the first * character is converted to lower case. * - * @param bean An object that has getter methods that should be used - * to make a JSONObject. + * @param bean An object that has getter methods that should be used + * to make a JSONObject. * @param includeSuperClass If true, include the super class properties. */ - public JSONObject(final Object bean, final boolean includeSuperClass) - { + public JSONObject(final Object bean, final boolean includeSuperClass) { this(); populateInternalMap(bean, includeSuperClass); } - private void populateInternalMap(final Object bean, boolean includeSuperClass) - { + private void populateInternalMap(final Object bean, boolean includeSuperClass) { Class klass = bean.getClass(); /* If klass.getSuperClass is System class then force includeSuperClass to false. */ - if (klass.getClassLoader() == null) - { + if (klass.getClassLoader() == null) { includeSuperClass = false; } Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods(); - for (Method method : methods) - { - try - { - if (Modifier.isPublic(method.getModifiers())) - { + for (Method method : methods) { + try { + if (Modifier.isPublic(method.getModifiers())) { String name = method.getName(); String key = ""; - if (name.startsWith("get")) - { + if (name.startsWith("get")) { key = name.substring(3); } - else if (name.startsWith("is")) - { + else if (name.startsWith("is")) { key = name.substring(2); } - if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) - { - if (key.length() == 1) - { + if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) { + if (key.length() == 1) { key = key.toLowerCase(); } - else if (!Character.isUpperCase(key.charAt(1))) - { + else if (!Character.isUpperCase(key.charAt(1))) { key = key.substring(0, 1).toLowerCase() + key.substring(1); } - Object result = method.invoke(bean, (Object[])null); - if (result == null) - { + Object result = method.invoke(bean, (Object[]) null); + if (result == null) { map.put(key, JSONObject.NULL); } - else if (result.getClass().isArray()) - { + else if (result.getClass().isArray()) { map.put(key, new JSONArray(result, includeSuperClass)); } - else if (result instanceof Collection) - { // List or Set - map.put(key, new JSONArray((Collection)result, includeSuperClass)); + else if (result instanceof Collection) { // List or Set + map.put(key, new JSONArray((Collection) result, includeSuperClass)); } - else if (result instanceof Map) - { - map.put(key, new JSONObject((Map)result, includeSuperClass)); + else if (result instanceof Map) { + map.put(key, new JSONObject((Map) result, includeSuperClass)); } - else if (JSONObject.isStandardProperty(result.getClass())) - { // Primitives, String and Wrapper + else if (JSONObject.isStandardProperty(result.getClass())) { // Primitives, String and Wrapper map.put(key, result); } - else - { - if (result.getClass().getPackage().getName().startsWith("java") || result.getClass() - .getClassLoader() == null) - { + else { + if (result.getClass().getPackage().getName().startsWith("java") || result.getClass().getClassLoader() == null) { map.put(key, result.toString()); } - else - { // User defined Objects + else { // User defined Objects map.put(key, new JSONObject(result, includeSuperClass)); } } } } } - catch (IllegalAccessException e) - { + catch (IllegalAccessException e) { throw new RuntimeException(e); } - catch (JSONException e) - { + catch (JSONException e) { throw new RuntimeException(e); } - catch (InvocationTargetException e) - { + catch (InvocationTargetException e) { throw new RuntimeException(e); } } } - static boolean isStandardProperty(final Class clazz) - { + static boolean isStandardProperty(final Class clazz) { return clazz.isPrimitive() || clazz.isAssignableFrom(Byte.class) || - clazz.isAssignableFrom(Short.class) || - clazz.isAssignableFrom(Integer.class) || - clazz.isAssignableFrom(Long.class) || - clazz.isAssignableFrom(Float.class) || - clazz.isAssignableFrom(Double.class) || - clazz.isAssignableFrom(Character.class) || - clazz.isAssignableFrom(String.class) || - clazz.isAssignableFrom(Boolean.class); + clazz.isAssignableFrom(Short.class) || + clazz.isAssignableFrom(Integer.class) || + clazz.isAssignableFrom(Long.class) || + clazz.isAssignableFrom(Float.class) || + clazz.isAssignableFrom(Double.class) || + clazz.isAssignableFrom(Character.class) || + clazz.isAssignableFrom(String.class) || + clazz.isAssignableFrom(Boolean.class); } /** @@ -437,23 +393,20 @@ public class JSONObject * from the names array, and the values will be the field values associated * with those keys in the object. If a key is not found or not visible, * then it will not be copied into the new JSONObject. + * * @param object An object that has fields that should be used to make a - * JSONObject. - * @param names An array of strings, the names of the fields to be obtained - * from the object. + * JSONObject. + * @param names An array of strings, the names of the fields to be obtained + * from the object. */ - public JSONObject(final Object object, final String[] names) - { + public JSONObject(final Object object, final String[] names) { this(); Class c = object.getClass(); - for (String name : names) - { - try - { + for (String name : names) { + try { putOpt(name, c.getField(name).get(object)); } - catch (Exception e) - { + catch (Exception e) { /* forget about it */ } } @@ -462,14 +415,14 @@ public class JSONObject /** * Construct a JSONObject from a source JSON text string. * This is the most commonly used JSONObject constructor. - * @param source A string beginning - * with { (left brace) and ending - * with } (right brace). - * @exception JSONException If there is a syntax error in the source - * string or a duplicated key. + * + * @param source A string beginning + * with { (left brace) and ending + * with } (right brace). + * @throws JSONException If there is a syntax error in the source + * string or a duplicated key. */ - public JSONObject(final String source) throws JSONException - { + public JSONObject(final String source) throws JSONException { this(new JSONTokener(source)); } @@ -479,26 +432,23 @@ public class JSONObject * JSONArray is stored under the key to hold all of the accumulated values. * If there is already a JSONArray, then the new value is appended to it. * In contrast, the put method replaces the previous value. + * * @param key A key string. * @param value An object to be accumulated under the key. * @return this. * @throws JSONException If the value is an invalid number - * or if the key is null. + * or if the key is null. */ - public JSONObject accumulate(final String key, final Object value) throws JSONException - { + public JSONObject accumulate(final String key, final Object value) throws JSONException { JSONObject.testValidity(value); Object o = opt(key); - if (o == null) - { + if (o == null) { put(key, value instanceof JSONArray ? new JSONArray().put(value) : value); } - else if (o instanceof JSONArray) - { - ((JSONArray)o).put(value); + else if (o instanceof JSONArray) { + ((JSONArray) o).put(value); } - else - { + else { put(key, new JSONArray().put(o).put(value)); } return this; @@ -509,26 +459,23 @@ public class JSONObject * JSONObject, then the key is put in the JSONObject with its value being a * JSONArray containing the value parameter. If the key was already * associated with a JSONArray, then the value parameter is appended to it. + * * @param key A key string. * @param value An object to be accumulated under the key. * @return this. * @throws JSONException If the key is null or if the current value - * associated with the key is not a JSONArray. + * associated with the key is not a JSONArray. */ - public JSONObject append(final String key, final Object value) throws JSONException - { + public JSONObject append(final String key, final Object value) throws JSONException { JSONObject.testValidity(value); Object o = opt(key); - if (o == null) - { + if (o == null) { put(key, new JSONArray().put(value)); } - else if (o instanceof JSONArray) - { - put(key, ((JSONArray)o).put(value)); + else if (o instanceof JSONArray) { + put(key, ((JSONArray) o).put(value)); } - else - { + else { throw new JSONException("JSONObject[" + key + "] is not a JSONArray."); } return this; @@ -537,27 +484,23 @@ public class JSONObject /** * Produce a string from a double. The string "null" will be returned if * the number is not finite. - * @param d A double. + * + * @param d A double. * @return A String. */ - public static String doubleToString(final double d) - { - if (Double.isInfinite(d) || Double.isNaN(d)) - { + public static String doubleToString(final double d) { + if (Double.isInfinite(d) || Double.isNaN(d)) { return "null"; } // Shave off trailing zeros and decimal point, if possible. String s = Double.toString(d); - if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) - { - while (s.endsWith("0")) - { + if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) { + while (s.endsWith("0")) { s = s.substring(0, s.length() - 1); } - if (s.endsWith(".")) - { + if (s.endsWith(".")) { s = s.substring(0, s.length() - 1); } } @@ -567,15 +510,13 @@ public class JSONObject /** * Get the value object associated with a key. * - * @param key A key string. - * @return The object associated with the key. - * @throws JSONException if the key is not found. + * @param key A key string. + * @return The object associated with the key. + * @throws JSONException if the key is not found. */ - public Object get(final String key) throws JSONException - { + public Object get(final String key) throws JSONException { Object o = opt(key); - if (o == null) - { + if (o == null) { throw new JSONException("JSONObject[" + JSONObject.quote(key) + "] not found."); } return o; @@ -584,20 +525,16 @@ public class JSONObject /** * Get the boolean value associated with a key. * - * @param key A key string. - * @return The truth. - * @throws JSONException - * if the value is not a Boolean or the String "true" or "false". + * @param key A key string. + * @return The truth. + * @throws JSONException if the value is not a Boolean or the String "true" or "false". */ - public boolean getBoolean(final String key) throws JSONException - { + public boolean getBoolean(final String key) throws JSONException { Object o = get(key); - if (o.equals(Boolean.FALSE) || o instanceof String && ((String)o).equalsIgnoreCase("false")) - { + if (o.equals(Boolean.FALSE) || o instanceof String && ((String) o).equalsIgnoreCase("false")) { return false; } - else if (o.equals(Boolean.TRUE) || o instanceof String && ((String)o).equalsIgnoreCase("true")) - { + else if (o.equals(Boolean.TRUE) || o instanceof String && ((String) o).equalsIgnoreCase("true")) { return true; } throw new JSONException("JSONObject[" + JSONObject.quote(key) + "] is not a Boolean."); @@ -605,20 +542,18 @@ public class JSONObject /** * Get the double value associated with a key. - * @param key A key string. - * @return The numeric value. + * + * @param key A key string. + * @return The numeric value. * @throws JSONException if the key is not found or - * if the value is not a Number object and cannot be converted to a number. + * if the value is not a Number object and cannot be converted to a number. */ - public double getDouble(final String key) throws JSONException - { + public double getDouble(final String key) throws JSONException { Object o = get(key); - try - { - return o instanceof Number ? ((Number)o).doubleValue() : Double.valueOf((String)o).doubleValue(); + try { + return o instanceof Number ? ((Number) o).doubleValue() : Double.valueOf((String) o).doubleValue(); } - catch (Exception e) - { + catch (Exception e) { throw new JSONException("JSONObject[" + JSONObject.quote(key) + "] is not a number."); } } @@ -627,31 +562,28 @@ public class JSONObject * Get the int value associated with a key. If the number value is too * large for an int, it will be clipped. * - * @param key A key string. - * @return The integer value. - * @throws JSONException if the key is not found or if the value cannot - * be converted to an integer. + * @param key A key string. + * @return The integer value. + * @throws JSONException if the key is not found or if the value cannot + * be converted to an integer. */ - public int getInt(final String key) throws JSONException - { + public int getInt(final String key) throws JSONException { Object o = get(key); - return o instanceof Number ? ((Number)o).intValue() : (int)getDouble(key); + return o instanceof Number ? ((Number) o).intValue() : (int) getDouble(key); } /** * Get the JSONArray value associated with a key. * - * @param key A key string. - * @return A JSONArray which is the value. - * @throws JSONException if the key is not found or - * if the value is not a JSONArray. + * @param key A key string. + * @return A JSONArray which is the value. + * @throws JSONException if the key is not found or + * if the value is not a JSONArray. */ - public JSONArray getJSONArray(final String key) throws JSONException - { + public JSONArray getJSONArray(final String key) throws JSONException { Object o = get(key); - if (o instanceof JSONArray) - { - return (JSONArray)o; + if (o instanceof JSONArray) { + return (JSONArray) o; } throw new JSONException("JSONObject[" + JSONObject.quote(key) + "] is not a JSONArray."); } @@ -659,17 +591,15 @@ public class JSONObject /** * Get the JSONObject value associated with a key. * - * @param key A key string. - * @return A JSONObject which is the value. - * @throws JSONException if the key is not found or - * if the value is not a JSONObject. + * @param key A key string. + * @return A JSONObject which is the value. + * @throws JSONException if the key is not found or + * if the value is not a JSONObject. */ - public JSONObject getJSONObject(final String key) throws JSONException - { + public JSONObject getJSONObject(final String key) throws JSONException { Object o = get(key); - if (o instanceof JSONObject) - { - return (JSONObject)o; + if (o instanceof JSONObject) { + return (JSONObject) o; } throw new JSONException("JSONObject[" + JSONObject.quote(key) + "] is not a JSONObject."); } @@ -678,15 +608,14 @@ public class JSONObject * Get the long value associated with a key. If the number value is too * long for a long, it will be clipped. * - * @param key A key string. - * @return The long value. - * @throws JSONException if the key is not found or if the value cannot - * be converted to a long. + * @param key A key string. + * @return The long value. + * @throws JSONException if the key is not found or if the value cannot + * be converted to a long. */ - public long getLong(final String key) throws JSONException - { + public long getLong(final String key) throws JSONException { Object o = get(key); - return o instanceof Number ? ((Number)o).longValue() : (long)getDouble(key); + return o instanceof Number ? ((Number) o).longValue() : (long) getDouble(key); } /** @@ -694,19 +623,16 @@ public class JSONObject * * @return An array of field names, or null if there are no names. */ - public static String[] getNames(final JSONObject jo) - { + public static String[] getNames(final JSONObject jo) { int length = jo.length(); - if (length == 0) - { + if (length == 0) { return null; } Iterator i = jo.keys(); String[] names = new String[length]; int j = 0; - while (i.hasNext()) - { - names[j] = (String)i.next(); + while (i.hasNext()) { + names[j] = (String) i.next(); j += 1; } return names; @@ -717,22 +643,18 @@ public class JSONObject * * @return An array of field names, or null if there are no names. */ - public static String[] getNames(final Object object) - { - if (object == null) - { + public static String[] getNames(final Object object) { + if (object == null) { return null; } Class klass = object.getClass(); Field[] fields = klass.getFields(); int length = fields.length; - if (length == 0) - { + if (length == 0) { return null; } String[] names = new String[length]; - for (int i = 0; i < length; i += 1) - { + for (int i = 0; i < length; i += 1) { names[i] = fields[i].getName(); } return names; @@ -741,34 +663,33 @@ public class JSONObject /** * Get the string associated with a key. * - * @param key A key string. - * @return A string which is the value. - * @throws JSONException if the key is not found. + * @param key A key string. + * @return A string which is the value. + * @throws JSONException if the key is not found. */ - public String getString(final String key) throws JSONException - { + public String getString(final String key) throws JSONException { return get(key).toString(); } /** * Determine if the JSONObject contains a specific key. - * @param key A key string. - * @return true if the key exists in the JSONObject. + * + * @param key A key string. + * @return true if the key exists in the JSONObject. */ - public boolean has(final String key) - { + public boolean has(final String key) { return map.containsKey(key); } /** * Determine if the value associated with the key is null or if there is - * no value. - * @param key A key string. - * @return true if there is no value associated with the key or if - * the value is the JSONObject.NULL object. + * no value. + * + * @param key A key string. + * @return true if there is no value associated with the key or if + * the value is the JSONObject.NULL object. */ - public boolean isNull(final String key) - { + public boolean isNull(final String key) { return JSONObject.NULL.equals(opt(key)); } @@ -777,8 +698,7 @@ public class JSONObject * * @return An iterator of the keys. */ - public Iterator keys() - { + public Iterator keys() { return map.keySet().iterator(); } @@ -787,23 +707,21 @@ public class JSONObject * * @return The number of keys in the JSONObject. */ - public int length() - { + public int length() { return map.size(); } /** * Produce a JSONArray containing the names of the elements of this * JSONObject. + * * @return A JSONArray containing the key strings, or null if the JSONObject * is empty. */ - public JSONArray names() - { + public JSONArray names() { JSONArray ja = new JSONArray(); Iterator keys = keys(); - while (keys.hasNext()) - { + while (keys.hasNext()) { ja.put(keys.next()); } return ja.length() == 0 ? null : ja; @@ -811,14 +729,13 @@ public class JSONObject /** * Produce a string from a Number. - * @param n A Number + * + * @param n A Number * @return A String. * @throws JSONException If n is a non-finite number. */ - public static String numberToString(final Number n) throws JSONException - { - if (n == null) - { + public static String numberToString(final Number n) throws JSONException { + if (n == null) { throw new JSONException("Null pointer"); } JSONObject.testValidity(n); @@ -826,14 +743,11 @@ public class JSONObject // Shave off trailing zeros and decimal point, if possible. String s = n.toString(); - if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) - { - while (s.endsWith("0")) - { + if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) { + while (s.endsWith("0")) { s = s.substring(0, s.length() - 1); } - if (s.endsWith(".")) - { + if (s.endsWith(".")) { s = s.substring(0, s.length() - 1); } } @@ -842,11 +756,11 @@ public class JSONObject /** * Get an optional value associated with a key. - * @param key A key string. - * @return An object which is the value, or null if there is no value. + * + * @param key A key string. + * @return An object which is the value, or null if there is no value. */ - public Object opt(final String key) - { + public Object opt(final String key) { return key == null ? null : map.get(key); } @@ -855,11 +769,10 @@ public class JSONObject * It returns false if there is no such key, or if the value is not * Boolean.TRUE or the String "true". * - * @param key A key string. - * @return The truth. + * @param key A key string. + * @return The truth. */ - public boolean optBoolean(final String key) - { + public boolean optBoolean(final String key) { return optBoolean(key, false); } @@ -868,18 +781,15 @@ public class JSONObject * It returns the defaultValue if there is no such key, or if it is not * a Boolean or the String "true" or "false" (case insensitive). * - * @param key A key string. - * @param defaultValue The default. - * @return The truth. + * @param key A key string. + * @param defaultValue The default. + * @return The truth. */ - public boolean optBoolean(final String key, final boolean defaultValue) - { - try - { + public boolean optBoolean(final String key, final boolean defaultValue) { + try { return getBoolean(key); } - catch (Exception e) - { + catch (Exception e) { return defaultValue; } } @@ -887,13 +797,13 @@ public class JSONObject /** * Put a key/value pair in the JSONObject, where the value will be a * JSONArray which is produced from a Collection. + * * @param key A key string. * @param value A Collection value. - * @return this. + * @return this. * @throws JSONException */ - public JSONObject put(final String key, final Collection value) throws JSONException - { + public JSONObject put(final String key, final Collection value) throws JSONException { put(key, new JSONArray(value)); return this; } @@ -904,11 +814,10 @@ public class JSONObject * If the value is a string, an attempt will be made to evaluate it as * a number. * - * @param key A string which is the key. - * @return An object which is the value. + * @param key A string which is the key. + * @return An object which is the value. */ - public double optDouble(final String key) - { + public double optDouble(final String key) { return optDouble(key, Double.NaN); } @@ -918,19 +827,16 @@ public class JSONObject * If the value is a string, an attempt will be made to evaluate it as * a number. * - * @param key A key string. - * @param defaultValue The default. - * @return An object which is the value. + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. */ - public double optDouble(final String key, final double defaultValue) - { - try - { + public double optDouble(final String key, final double defaultValue) { + try { Object o = opt(key); - return o instanceof Number ? ((Number)o).doubleValue() : new Double((String)o).doubleValue(); + return o instanceof Number ? ((Number) o).doubleValue() : new Double((String) o).doubleValue(); } - catch (Exception e) - { + catch (Exception e) { return defaultValue; } } @@ -941,11 +847,10 @@ public class JSONObject * If the value is a string, an attempt will be made to evaluate it as * a number. * - * @param key A key string. - * @return An object which is the value. + * @param key A key string. + * @return An object which is the value. */ - public int optInt(final String key) - { + public int optInt(final String key) { return optInt(key, 0); } @@ -955,18 +860,15 @@ public class JSONObject * If the value is a string, an attempt will be made to evaluate it as * a number. * - * @param key A key string. - * @param defaultValue The default. - * @return An object which is the value. + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. */ - public int optInt(final String key, final int defaultValue) - { - try - { + public int optInt(final String key, final int defaultValue) { + try { return getInt(key); } - catch (Exception e) - { + catch (Exception e) { return defaultValue; } } @@ -976,13 +878,12 @@ public class JSONObject * It returns null if there is no such key, or if its value is not a * JSONArray. * - * @param key A key string. - * @return A JSONArray which is the value. + * @param key A key string. + * @return A JSONArray which is the value. */ - public JSONArray optJSONArray(final String key) - { + public JSONArray optJSONArray(final String key) { Object o = opt(key); - return o instanceof JSONArray ? (JSONArray)o : null; + return o instanceof JSONArray ? (JSONArray) o : null; } /** @@ -990,13 +891,12 @@ public class JSONObject * It returns null if there is no such key, or if its value is not a * JSONObject. * - * @param key A key string. - * @return A JSONObject which is the value. + * @param key A key string. + * @return A JSONObject which is the value. */ - public JSONObject optJSONObject(final String key) - { + public JSONObject optJSONObject(final String key) { Object o = opt(key); - return o instanceof JSONObject ? (JSONObject)o : null; + return o instanceof JSONObject ? (JSONObject) o : null; } /** @@ -1005,11 +905,10 @@ public class JSONObject * If the value is a string, an attempt will be made to evaluate it as * a number. * - * @param key A key string. - * @return An object which is the value. + * @param key A key string. + * @return An object which is the value. */ - public long optLong(final String key) - { + public long optLong(final String key) { return optLong(key, 0); } @@ -1019,18 +918,15 @@ public class JSONObject * If the value is a string, an attempt will be made to evaluate it as * a number. * - * @param key A key string. - * @param defaultValue The default. - * @return An object which is the value. + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. */ - public long optLong(final String key, final long defaultValue) - { - try - { + public long optLong(final String key, final long defaultValue) { + try { return getLong(key); } - catch (Exception e) - { + catch (Exception e) { return defaultValue; } } @@ -1040,11 +936,10 @@ public class JSONObject * It returns an empty string if there is no such key. If the value is not * a string and is not null, then it is converted to a string. * - * @param key A key string. - * @return A string which is the value. + * @param key A key string. + * @return A string which is the value. */ - public String optString(final String key) - { + public String optString(final String key) { return optString(key, ""); } @@ -1052,12 +947,11 @@ public class JSONObject * Get an optional string associated with a key. * It returns the defaultValue if there is no such key. * - * @param key A key string. - * @param defaultValue The default. - * @return A string which is the value. + * @param key A key string. + * @param defaultValue The default. + * @return A string which is the value. */ - public String optString(final String key, final String defaultValue) - { + public String optString(final String key, final String defaultValue) { Object o = opt(key); return o != null ? o.toString() : defaultValue; } @@ -1070,8 +964,7 @@ public class JSONObject * @return this. * @throws JSONException If the key is null. */ - public JSONObject put(final String key, final boolean value) throws JSONException - { + public JSONObject put(final String key, final boolean value) throws JSONException { put(key, value ? Boolean.TRUE : Boolean.FALSE); return this; } @@ -1084,8 +977,7 @@ public class JSONObject * @return this. * @throws JSONException If the key is null or if the number is invalid. */ - public JSONObject put(final String key, final double value) throws JSONException - { + public JSONObject put(final String key, final double value) throws JSONException { put(key, new Double(value)); return this; } @@ -1098,8 +990,7 @@ public class JSONObject * @return this. * @throws JSONException If the key is null. */ - public JSONObject put(final String key, final int value) throws JSONException - { + public JSONObject put(final String key, final int value) throws JSONException { put(key, Integer.valueOf(value)); return this; } @@ -1112,8 +1003,7 @@ public class JSONObject * @return this. * @throws JSONException If the key is null. */ - public JSONObject put(final String key, final long value) throws JSONException - { + public JSONObject put(final String key, final long value) throws JSONException { put(key, Long.valueOf(value)); return this; } @@ -1121,13 +1011,13 @@ public class JSONObject /** * Put a key/value pair in the JSONObject, where the value will be a * JSONObject which is produced from a Map. + * * @param key A key string. * @param value A Map value. - * @return this. + * @return this. * @throws JSONException */ - public JSONObject put(final String key, final Map value) throws JSONException - { + public JSONObject put(final String key, final Map value) throws JSONException { put(key, new JSONObject(value)); return this; } @@ -1135,27 +1025,24 @@ public class JSONObject /** * Put a key/value pair in the JSONObject. If the value is null, * then the key will be removed from the JSONObject if it is present. + * * @param key A key string. * @param value An object which is the value. It should be of one of these - * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, - * or the JSONObject.NULL object. + * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, + * or the JSONObject.NULL object. * @return this. * @throws JSONException If the value is non-finite number - * or if the key is null. + * or if the key is null. */ - public JSONObject put(final String key, final Object value) throws JSONException - { - if (key == null) - { + public JSONObject put(final String key, final Object value) throws JSONException { + if (key == null) { throw new JSONException("Null key."); } - if (value != null) - { + if (value != null) { JSONObject.testValidity(value); map.put(key, value); } - else - { + else { remove(key); } return this; @@ -1165,17 +1052,15 @@ public class JSONObject * Put a key/value pair in the JSONObject, but only if the key and the * value are both non-null, and only if there is not already a member * with that name. + * * @param key * @param value * @return his. * @throws JSONException if the key is a duplicate */ - public JSONObject putOnce(final String key, final Object value) throws JSONException - { - if (key != null && value != null) - { - if (opt(key) != null) - { + public JSONObject putOnce(final String key, final Object value) throws JSONException { + if (key != null && value != null) { + if (opt(key) != null) { throw new JSONException("Duplicate key \"" + key + "\""); } put(key, value); @@ -1186,17 +1071,16 @@ public class JSONObject /** * Put a key/value pair in the JSONObject, but only if the * key and the value are both non-null. + * * @param key A key string. * @param value An object which is the value. It should be of one of these - * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, - * or the JSONObject.NULL object. + * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, + * or the JSONObject.NULL object. * @return this. * @throws JSONException If the value is a non-finite number. */ - public JSONObject putOpt(final String key, final Object value) throws JSONException - { - if (key != null && value != null) - { + public JSONObject putOpt(final String key, final Object value) throws JSONException { + if (key != null && value != null) { put(key, value); } return this; @@ -1207,13 +1091,12 @@ public class JSONObject * right places. A backslash will be inserted within </, allowing JSON * text to be delivered in HTML. In JSON text, a string cannot contain a * control character or an unescaped quote or backslash. + * * @param string A String - * @return A String correctly formatted for insertion in a JSON text. + * @return A String correctly formatted for insertion in a JSON text. */ - public static String quote(final String string) - { - if (string == null || string.length() == 0) - { + public static String quote(final String string) { + if (string == null || string.length() == 0) { return "\"\""; } @@ -1225,20 +1108,17 @@ public class JSONObject String t; sb.append('"'); - for (i = 0; i < len; i += 1) - { + for (i = 0; i < len; i += 1) { b = c; c = string.charAt(i); - switch (c) - { + switch (c) { case '\\': case '"': sb.append('\\'); sb.append(c); break; case '/': - if (b == '<') - { + if (b == '<') { sb.append('\\'); } sb.append(c); @@ -1259,13 +1139,11 @@ public class JSONObject sb.append("\\r"); break; default: - if (c < ' ' || c >= '\u0080' && c < '\u00a0' || c >= '\u2000' && c < '\u2100') - { + if (c < ' ' || c >= '\u0080' && c < '\u00a0' || c >= '\u2000' && c < '\u2100') { t = "000" + Integer.toHexString(c); sb.append("\\u" + t.substring(t.length() - 4)); } - else - { + else { sb.append(c); } } @@ -1276,12 +1154,12 @@ public class JSONObject /** * Remove a name and its value, if present. + * * @param key The name to be removed. * @return The value that was associated with the name, * or null if there was no value. */ - public Object remove(final String key) - { + public Object remove(final String key) { return map.remove(key); } @@ -1291,33 +1169,28 @@ public class JSONObject * * @return An iterator of the keys. */ - public Iterator sortedKeys() - { + public Iterator sortedKeys() { return new TreeSet(map.keySet()).iterator(); } /** * Try to convert a string into a number, boolean, or null. If the string * can't be converted, return the string. + * * @param s A String. * @return A simple JSON value. */ - public static Object stringToValue(final String s) - { - if (s.equals("")) - { + public static Object stringToValue(final String s) { + if (s.equals("")) { return s; } - if (s.equalsIgnoreCase("true")) - { + if (s.equalsIgnoreCase("true")) { return Boolean.TRUE; } - if (s.equalsIgnoreCase("false")) - { + if (s.equalsIgnoreCase("false")) { return Boolean.FALSE; } - if (s.equalsIgnoreCase("null")) - { + if (s.equalsIgnoreCase("null")) { return JSONObject.NULL; } @@ -1330,54 +1203,40 @@ public class JSONObject */ char b = s.charAt(0); - if (b >= '0' && b <= '9' || b == '.' || b == '-' || b == '+') - { - if (b == '0') - { - if (s.length() > 2 && (s.charAt(1) == 'x' || s.charAt(1) == 'X')) - { - try - { + if (b >= '0' && b <= '9' || b == '.' || b == '-' || b == '+') { + if (b == '0') { + if (s.length() > 2 && (s.charAt(1) == 'x' || s.charAt(1) == 'X')) { + try { return Integer.valueOf(Integer.parseInt(s.substring(2), 16)); } - catch (Exception e) - { + catch (Exception e) { /* Ignore the error */ } } - else - { - try - { + else { + try { return Integer.valueOf(Integer.parseInt(s, 8)); } - catch (Exception e) - { + catch (Exception e) { /* Ignore the error */ } } } - try - { - if (s.indexOf('.') > -1 || s.indexOf('e') > -1 || s.indexOf('E') > -1) - { + try { + if (s.indexOf('.') > -1 || s.indexOf('e') > -1 || s.indexOf('E') > -1) { return Double.valueOf(s); } - else - { + else { Long myLong = Long.valueOf(s); - if (myLong.longValue() == myLong.intValue()) - { + if (myLong.longValue() == myLong.intValue()) { return Integer.valueOf(myLong.intValue()); } - else - { + else { return myLong; } } } - catch (Exception f) - { + catch (Exception f) { /* Ignore the error */ } } @@ -1386,24 +1245,19 @@ public class JSONObject /** * Throw an exception if the object is a NaN or infinite number. + * * @param o The object to test. * @throws JSONException If o is a non-finite number. */ - static void testValidity(final Object o) throws JSONException - { - if (o != null) - { - if (o instanceof Double) - { - if (((Double)o).isInfinite() || ((Double)o).isNaN()) - { + static void testValidity(final Object o) throws JSONException { + if (o != null) { + if (o instanceof Double) { + if (((Double) o).isInfinite() || ((Double) o).isNaN()) { throw new JSONException("JSON does not allow non-finite numbers."); } } - else if (o instanceof Float) - { - if (((Float)o).isInfinite() || ((Float)o).isNaN()) - { + else if (o instanceof Float) { + if (((Float) o).isInfinite() || ((Float) o).isNaN()) { throw new JSONException("JSON does not allow non-finite numbers."); } } @@ -1413,20 +1267,18 @@ public class JSONObject /** * Produce a JSONArray containing the values of the members of this * JSONObject. + * * @param names A JSONArray containing a list of key strings. This - * determines the sequence of the values in the result. + * determines the sequence of the values in the result. * @return A JSONArray of values. * @throws JSONException If any of the values are non-finite numbers. */ - public JSONArray toJSONArray(final JSONArray names) throws JSONException - { - if (names == null || names.length() == 0) - { + public JSONArray toJSONArray(final JSONArray names) throws JSONException { + if (names == null || names.length() == 0) { return null; } JSONArray ja = new JSONArray(); - for (int i = 0; i < names.length(); i += 1) - { + for (int i = 0; i < names.length(); i += 1) { ja.put(opt(names.getString(i))); } return ja; @@ -1440,22 +1292,18 @@ public class JSONObject * Warning: This method assumes that the data structure is acyclical. * * @return a printable, displayable, portable, transmittable - * representation of the object, beginning - * with { (left brace) and ending - * with } (right brace). + * representation of the object, beginning + * with { (left brace) and ending + * with } (right brace). */ @Override - public String toString() - { - try - { + public String toString() { + try { Iterator keys = keys(); StringBuilder sb = new StringBuilder("{"); - while (keys.hasNext()) - { - if (sb.length() > 1) - { + while (keys.hasNext()) { + if (sb.length() > 1) { sb.append(','); } Object o = keys.next(); @@ -1466,8 +1314,7 @@ public class JSONObject sb.append('}'); return sb.toString(); } - catch (JSONException e) - { + catch (JSONException e) { return null; } } @@ -1476,16 +1323,16 @@ public class JSONObject * Make a prettyprinted JSON text of this JSONObject. *

    * Warning: This method assumes that the data structure is acyclical. + * * @param indentFactor The number of spaces to add to each level of - * indentation. + * indentation. * @return a printable, displayable, portable, transmittable - * representation of the object, beginning - * with { (left brace) and ending - * with } (right brace). + * representation of the object, beginning + * with { (left brace) and ending + * with } (right brace). * @throws JSONException If the object contains an invalid number. */ - public String toString(final int indentFactor) throws JSONException - { + public String toString(final int indentFactor) throws JSONException { return toString(indentFactor, 0); } @@ -1493,60 +1340,51 @@ public class JSONObject * Make a prettyprinted JSON text of this JSONObject. *

    * Warning: This method assumes that the data structure is acyclical. + * * @param indentFactor The number of spaces to add to each level of - * indentation. - * @param indent The indentation of the top level. + * indentation. + * @param indent The indentation of the top level. * @return a printable, displayable, transmittable - * representation of the object, beginning - * with { (left brace) and ending - * with } (right brace). + * representation of the object, beginning + * with { (left brace) and ending + * with } (right brace). * @throws JSONException If the object contains an invalid number. */ - String toString(final int indentFactor, final int indent) throws JSONException - { + String toString(final int indentFactor, final int indent) throws JSONException { int j; int n = length(); - if (n == 0) - { + if (n == 0) { return "{}"; } Iterator keys = sortedKeys(); StringBuffer sb = new StringBuffer("{"); int newindent = indent + indentFactor; Object o; - if (n == 1) - { + if (n == 1) { o = keys.next(); sb.append(JSONObject.quote(o.toString())); sb.append(": "); sb.append(JSONObject.valueToString(map.get(o), indentFactor, indent)); } - else - { - while (keys.hasNext()) - { + else { + while (keys.hasNext()) { o = keys.next(); - if (sb.length() > 1) - { + if (sb.length() > 1) { sb.append(",\n"); } - else - { + else { sb.append('\n'); } - for (j = 0; j < newindent; j += 1) - { + for (j = 0; j < newindent; j += 1) { sb.append(' '); } sb.append(JSONObject.quote(o.toString())); sb.append(": "); sb.append(JSONObject.valueToString(map.get(o), indentFactor, newindent)); } - if (sb.length() > 1) - { + if (sb.length() > 1) { sb.append('\n'); - for (j = 0; j < indent; j += 1) - { + for (j = 0; j < indent; j += 1) { sb.append(' '); } } @@ -1569,52 +1407,43 @@ public class JSONObject * *

    * Warning: This method assumes that the data structure is acyclical. + * * @param value The value to be serialized. * @return a printable, displayable, transmittable - * representation of the object, beginning - * with { (left brace) and ending - * with } (right brace). + * representation of the object, beginning + * with { (left brace) and ending + * with } (right brace). * @throws JSONException If the value is or contains an invalid number. */ - static String valueToString(final Object value) throws JSONException - { - if (value == null || JSONObject.NULL == value) - { + static String valueToString(final Object value) throws JSONException { + if (value == null || JSONObject.NULL == value) { return "null"; } - if (value instanceof JSONString) - { + if (value instanceof JSONString) { String o; - try - { - o = ((JSONString)value).toJSONString(); + try { + o = ((JSONString) value).toJSONString(); } - catch (RuntimeException e) - { + catch (RuntimeException e) { throw new JSONException(e); } if (o == null) throw new JSONException("Bad value from toJSONString: " + o); return o; } - if (value instanceof Number) - { - return JSONObject.numberToString((Number)value); + if (value instanceof Number) { + return JSONObject.numberToString((Number) value); } - if (value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) - { + if (value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) { return value.toString(); } - if (value instanceof Map) - { - return new JSONObject((Map)value).toString(); + if (value instanceof Map) { + return new JSONObject((Map) value).toString(); } - if (value instanceof Collection) - { - return new JSONArray((Collection)value).toString(); + if (value instanceof Collection) { + return new JSONArray((Collection) value).toString(); } - if (value.getClass().isArray()) - { + if (value.getClass().isArray()) { return new JSONArray(value).toString(); } return JSONObject.quote(value.toString()); @@ -1624,61 +1453,50 @@ public class JSONObject * Make a prettyprinted JSON text of an object value. *

    * Warning: This method assumes that the data structure is acyclical. - * @param value The value to be serialized. + * + * @param value The value to be serialized. * @param indentFactor The number of spaces to add to each level of - * indentation. - * @param indent The indentation of the top level. + * indentation. + * @param indent The indentation of the top level. * @return a printable, displayable, transmittable - * representation of the object, beginning - * with { (left brace) and ending - * with } (right brace). + * representation of the object, beginning + * with { (left brace) and ending + * with } (right brace). * @throws JSONException If the object contains an invalid number. */ - static String valueToString(final Object value, final int indentFactor, final int indent) throws JSONException - { - if (value == null || JSONObject.NULL == value) - { + static String valueToString(final Object value, final int indentFactor, final int indent) throws JSONException { + if (value == null || JSONObject.NULL == value) { return "null"; } - try - { - if (value instanceof JSONString) - { - String o = ((JSONString)value).toJSONString(); + try { + if (value instanceof JSONString) { + String o = ((JSONString) value).toJSONString(); if (o != null) return o; } } - catch (RuntimeException e) - { + catch (RuntimeException e) { /* forget about it */ } - if (value instanceof Number) - { - return JSONObject.numberToString((Number)value); + if (value instanceof Number) { + return JSONObject.numberToString((Number) value); } - if (value instanceof Boolean) - { + if (value instanceof Boolean) { return value.toString(); } - if (value instanceof JSONObject) - { - return ((JSONObject)value).toString(indentFactor, indent); + if (value instanceof JSONObject) { + return ((JSONObject) value).toString(indentFactor, indent); } - if (value instanceof JSONArray) - { - return ((JSONArray)value).toString(indentFactor, indent); + if (value instanceof JSONArray) { + return ((JSONArray) value).toString(indentFactor, indent); } - if (value instanceof Map) - { - return new JSONObject((Map)value).toString(indentFactor, indent); + if (value instanceof Map) { + return new JSONObject((Map) value).toString(indentFactor, indent); } - if (value instanceof Collection) - { - return new JSONArray((Collection)value).toString(indentFactor, indent); + if (value instanceof Collection) { + return new JSONArray((Collection) value).toString(indentFactor, indent); } - if (value.getClass().isArray()) - { + if (value.getClass().isArray()) { return new JSONArray(value).toString(indentFactor, indent); } return JSONObject.quote(value.toString()); @@ -1693,34 +1511,27 @@ public class JSONObject * @return The writer. * @throws JSONException */ - public Writer write(final Writer writer) throws JSONException - { - try - { + public Writer write(final Writer writer) throws JSONException { + try { boolean b = false; Iterator keys = keys(); writer.write('{'); - while (keys.hasNext()) - { - if (b) - { + while (keys.hasNext()) { + if (b) { writer.write(','); } Object k = keys.next(); writer.write(JSONObject.quote(k.toString())); writer.write(':'); Object v = map.get(k); - if (v instanceof JSONObject) - { - ((JSONObject)v).write(writer); + if (v instanceof JSONObject) { + ((JSONObject) v).write(writer); } - else if (v instanceof JSONArray) - { - ((JSONArray)v).write(writer); + else if (v instanceof JSONArray) { + ((JSONArray) v).write(writer); } - else - { + else { writer.write(JSONObject.valueToString(v)); } b = true; @@ -1728,8 +1539,7 @@ public class JSONObject writer.write('}'); return writer; } - catch (IOException e) - { + catch (IOException e) { throw new JSONException(e); } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONString.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONString.java index 679ec161d5..07ec907e5f 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONString.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONString.java @@ -31,8 +31,8 @@ package org.apache.activemq.artemis.utils.json; * toJSONString method will be used instead of the default behavior * of using the Object's toString() method and quoting the result. */ -public interface JSONString -{ +public interface JSONString { + /** * The toJSONString method allows a class to produce its own JSON * serialization. diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONTokener.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONTokener.java index 88b1e0389a..5f5153b964 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONTokener.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONTokener.java @@ -33,8 +33,7 @@ import java.io.StringReader; * it. It is used by the JSONObject and JSONArray constructors to parse * JSON source strings. */ -public class JSONTokener -{ +public class JSONTokener { private int index; @@ -47,10 +46,9 @@ public class JSONTokener /** * Construct a JSONTokener from a string. * - * @param reader A reader. + * @param reader A reader. */ - public JSONTokener(final Reader reader) - { + public JSONTokener(final Reader reader) { this.reader = reader.markSupported() ? reader : new BufferedReader(reader); useLastChar = false; index = 0; @@ -59,10 +57,9 @@ public class JSONTokener /** * Construct a JSONTokener from a string. * - * @param s A source string. + * @param s A source string. */ - public JSONTokener(final String s) - { + public JSONTokener(final String s) { this(new StringReader(s)); } @@ -71,10 +68,8 @@ public class JSONTokener * so that you can test for a digit or letter before attempting to parse * the next number or identifier. */ - public void back() throws JSONException - { - if (useLastChar || index <= 0) - { + public void back() throws JSONException { + if (useLastChar || index <= 0) { throw new JSONException("Stepping back two steps is not supported"); } index -= 1; @@ -83,22 +78,19 @@ public class JSONTokener /** * Get the hex value of a character (base16). + * * @param c A character between '0' and '9' or between 'A' and 'F' or - * between 'a' and 'f'. - * @return An int between 0 and 15, or -1 if c was not a hex digit. + * between 'a' and 'f'. + * @return An int between 0 and 15, or -1 if c was not a hex digit. */ - public static int dehexchar(final char c) - { - if (c >= '0' && c <= '9') - { + public static int dehexchar(final char c) { + if (c >= '0' && c <= '9') { return c - '0'; } - if (c >= 'A' && c <= 'F') - { + if (c >= 'A' && c <= 'F') { return c - ('A' - 10); } - if (c >= 'a' && c <= 'f') - { + if (c >= 'a' && c <= 'f') { return c - ('a' - 10); } return -1; @@ -107,13 +99,12 @@ public class JSONTokener /** * Determine if the source string still contains characters that next() * can consume. + * * @return true if not yet at the end of the source. */ - public boolean more() throws JSONException - { + public boolean more() throws JSONException { char nextChar = next(); - if (nextChar == 0) - { + if (nextChar == 0) { return false; } back(); @@ -125,49 +116,42 @@ public class JSONTokener * * @return The next character, or 0 if past the end of the source string. */ - public char next() throws JSONException - { - if (useLastChar) - { + public char next() throws JSONException { + if (useLastChar) { useLastChar = false; - if (lastChar != 0) - { + if (lastChar != 0) { index += 1; } return lastChar; } int c; - try - { + try { c = reader.read(); } - catch (IOException exc) - { + catch (IOException exc) { throw new JSONException(exc); } - if (c <= 0) - { // End of stream + if (c <= 0) { // End of stream lastChar = 0; return 0; } index += 1; - lastChar = (char)c; + lastChar = (char) c; return lastChar; } /** * Consume the next character, and check that it matches a specified * character. + * * @param c The character to match. * @return The character. * @throws JSONException if the character does not match. */ - public char next(final char c) throws JSONException - { + public char next(final char c) throws JSONException { char n = next(); - if (n != c) - { + if (n != c) { throw syntaxError("Expected '" + c + "' and instead saw '" + n + "'"); } return n; @@ -176,45 +160,37 @@ public class JSONTokener /** * Get the next n characters. * - * @param n The number of characters to take. - * @return A string of n characters. - * @throws JSONException - * Substring bounds error if there are not - * n characters remaining in the source string. + * @param n The number of characters to take. + * @return A string of n characters. + * @throws JSONException Substring bounds error if there are not + * n characters remaining in the source string. */ - public String next(final int n) throws JSONException - { - if (n == 0) - { + public String next(final int n) throws JSONException { + if (n == 0) { return ""; } char[] buffer = new char[n]; int pos = 0; - if (useLastChar) - { + if (useLastChar) { useLastChar = false; buffer[0] = lastChar; pos = 1; } - try - { + try { int len; - while (pos < n && (len = reader.read(buffer, pos, n - pos)) != -1) - { + while (pos < n && (len = reader.read(buffer, pos, n - pos)) != -1) { pos += len; } } - catch (IOException exc) - { + catch (IOException exc) { throw new JSONException(exc); } index += pos; - if (pos < n) - { + if (pos < n) { throw syntaxError("Substring bounds error"); } @@ -224,16 +200,14 @@ public class JSONTokener /** * Get the next char in the string, skipping whitespace. + * + * @return A character, or 0 if there are no more characters. * @throws JSONException - * @return A character, or 0 if there are no more characters. */ - public char nextClean() throws JSONException - { - for (;;) - { + public char nextClean() throws JSONException { + for (;;) { char c = next(); - if (c == 0 || c > ' ') - { + if (c == 0 || c > ' ') { return c; } } @@ -244,29 +218,26 @@ public class JSONTokener * Backslash processing is done. The formal JSON format does not * allow strings in single quotes, but an implementation is allowed to * accept them. + * * @param quote The quoting character, either - * " (double quote) or - * ' (single quote). - * @return A String. + * " (double quote) or + * ' (single quote). + * @return A String. * @throws JSONException Unterminated string. */ - public String nextString(final char quote) throws JSONException - { + public String nextString(final char quote) throws JSONException { char c; StringBuffer sb = new StringBuffer(); - for (;;) - { + for (;;) { c = next(); - switch (c) - { + switch (c) { case 0: case '\n': case '\r': throw syntaxError("Unterminated string"); case '\\': c = next(); - switch (c) - { + switch (c) { case 'b': sb.append('\b'); break; @@ -283,18 +254,17 @@ public class JSONTokener sb.append('\r'); break; case 'u': - sb.append((char)Integer.parseInt(next(4), 16)); + sb.append((char) Integer.parseInt(next(4), 16)); break; case 'x': - sb.append((char)Integer.parseInt(next(2), 16)); + sb.append((char) Integer.parseInt(next(2), 16)); break; default: sb.append(c); } break; default: - if (c == quote) - { + if (c == quote) { return sb.toString(); } sb.append(c); @@ -305,19 +275,16 @@ public class JSONTokener /** * Get the text up but not including the specified character or the * end of line, whichever comes first. - * @param d A delimiter character. - * @return A string. + * + * @param d A delimiter character. + * @return A string. */ - public String nextTo(final char d) throws JSONException - { + public String nextTo(final char d) throws JSONException { StringBuffer sb = new StringBuffer(); - for (;;) - { + for (;;) { char c = next(); - if (c == d || c == 0 || c == '\n' || c == '\r') - { - if (c != 0) - { + if (c == d || c == 0 || c == '\n' || c == '\r') { + if (c != 0) { back(); } return sb.toString().trim(); @@ -329,20 +296,17 @@ public class JSONTokener /** * Get the text up but not including one of the specified delimiter * characters or the end of line, whichever comes first. + * * @param delimiters A set of delimiter characters. * @return A string, trimmed. */ - public String nextTo(final String delimiters) throws JSONException - { + public String nextTo(final String delimiters) throws JSONException { char c; StringBuffer sb = new StringBuffer(); - for (;;) - { + for (;;) { c = next(); - if (delimiters.indexOf(c) >= 0 || c == 0 || c == '\n' || c == '\r') - { - if (c != 0) - { + if (delimiters.indexOf(c) >= 0 || c == 0 || c == '\n' || c == '\r') { + if (c != 0) { back(); } return sb.toString().trim(); @@ -354,17 +318,15 @@ public class JSONTokener /** * Get the next value. The value can be a Boolean, Double, Integer, * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. - * @throws JSONException If syntax error. * * @return An object. + * @throws JSONException If syntax error. */ - public Object nextValue() throws JSONException - { + public Object nextValue() throws JSONException { char c = nextClean(); String s; - switch (c) - { + switch (c) { case '"': case '\'': return nextString(c); @@ -387,16 +349,14 @@ public class JSONTokener */ StringBuffer sb = new StringBuffer(); - while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) - { + while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { sb.append(c); c = next(); } back(); s = sb.toString().trim(); - if (s.equals("")) - { + if (s.equals("")) { throw syntaxError("Missing value"); } return JSONObject.stringToValue(s); @@ -405,31 +365,26 @@ public class JSONTokener /** * Skip characters until the next character is the requested character. * If the requested character is not found, no characters are skipped. + * * @param to A character to skip to. * @return The requested character, or zero if the requested character * is not found. */ - public char skipTo(final char to) throws JSONException - { + public char skipTo(final char to) throws JSONException { char c; - try - { + try { int startIndex = index; reader.mark(Integer.MAX_VALUE); - do - { + do { c = next(); - if (c == 0) - { + if (c == 0) { reader.reset(); index = startIndex; return c; } - } - while (c != to); + } while (c != to); } - catch (IOException exc) - { + catch (IOException exc) { throw new JSONException(exc); } @@ -441,10 +396,9 @@ public class JSONTokener * Make a JSONException to signal a syntax error. * * @param message The error message. - * @return A JSONException object, suitable for throwing + * @return A JSONException object, suitable for throwing */ - public JSONException syntaxError(final String message) - { + public JSONException syntaxError(final String message) { return new JSONException(message + toString()); } @@ -454,8 +408,7 @@ public class JSONTokener * @return " at character [this.index]" */ @Override - public String toString() - { + public String toString() { return " at character " + index; } } \ No newline at end of file diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/tests/util/RandomUtil.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/tests/util/RandomUtil.java index a9f9066f82..20a2957e39 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/tests/util/RandomUtil.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/tests/util/RandomUtil.java @@ -25,8 +25,7 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffers; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.transaction.impl.XidImpl; -public final class RandomUtil -{ +public final class RandomUtil { // Constants ----------------------------------------------------- private static final Random random = new Random(System.currentTimeMillis()); @@ -35,124 +34,99 @@ public final class RandomUtil // Static -------------------------------------------------------- - public static String randomString() - { + public static String randomString() { return UUID.randomUUID().toString(); } - public static SimpleString randomSimpleString() - { + public static SimpleString randomSimpleString() { return new SimpleString(RandomUtil.randomString()); } - public static char randomChar() - { + public static char randomChar() { return RandomUtil.randomString().charAt(0); } - public static long randomLong() - { + public static long randomLong() { return RandomUtil.random.nextLong(); } - public static long randomPositiveLong() - { + public static long randomPositiveLong() { return Math.abs(RandomUtil.randomLong()); } - public static int randomInt() - { + public static int randomInt() { return RandomUtil.random.nextInt(); } - public static int randomPositiveInt() - { + public static int randomPositiveInt() { return Math.abs(RandomUtil.randomInt()); } - - public static ActiveMQBuffer randomBuffer(final int size, final long... data) - { + public static ActiveMQBuffer randomBuffer(final int size, final long... data) { ActiveMQBuffer buffer = ActiveMQBuffers.fixedBuffer(size + 8 * data.length); - for (long d : data) - { + for (long d : data) { buffer.writeLong(d); } - for (int i = 0; i < size; i++) - { + for (int i = 0; i < size; i++) { buffer.writeByte(randomByte()); } return buffer; } - - public static int randomInterval(final int min, final int max) - { + public static int randomInterval(final int min, final int max) { return min + randomMax(max - min); } - public static int randomMax(final int max) - { + public static int randomMax(final int max) { int value = randomPositiveInt() % max; - if (value == 0) - { + if (value == 0) { value = max; } return value; } - public static int randomPort() - { + public static int randomPort() { return RandomUtil.random.nextInt(65536); } - public static short randomShort() - { + public static short randomShort() { return (short) RandomUtil.random.nextInt(Short.MAX_VALUE); } - public static byte randomByte() - { + public static byte randomByte() { return Integer.valueOf(RandomUtil.random.nextInt()).byteValue(); } - public static boolean randomBoolean() - { + public static boolean randomBoolean() { return RandomUtil.random.nextBoolean(); } - public static byte[] randomBytes() - { + public static byte[] randomBytes() { return RandomUtil.randomString().getBytes(); } - public static byte[] randomBytes(final int length) - { + public static byte[] randomBytes(final int length) { byte[] bytes = new byte[length]; - for (int i = 0; i < bytes.length; i++) - { + for (int i = 0; i < bytes.length; i++) { bytes[i] = RandomUtil.randomByte(); } return bytes; } - public static double randomDouble() - { + public static double randomDouble() { return RandomUtil.random.nextDouble(); } - public static float randomFloat() - { + public static float randomFloat() { return RandomUtil.random.nextFloat(); } - public static Xid randomXid() - { + public static Xid randomXid() { return new XidImpl(RandomUtil.randomBytes(), RandomUtil.randomInt(), RandomUtil.randomBytes()); } diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/tests/util/SilentTestCase.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/tests/util/SilentTestCase.java index 638a1ff57a..5508fc4f62 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/tests/util/SilentTestCase.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/tests/util/SilentTestCase.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.util; + import org.junit.Before; import org.junit.After; @@ -29,8 +30,8 @@ import org.junit.Assert; * It is meant to avoid cluttering either during test execution when the tested code (expectedly) * writes to these. */ -public abstract class SilentTestCase extends Assert -{ +public abstract class SilentTestCase extends Assert { + private PrintStream origSysOut; private PrintStream origSysErr; @@ -38,8 +39,7 @@ public abstract class SilentTestCase extends Assert private PrintStream sysErr; @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { origSysOut = System.out; origSysErr = System.err; sysOut = new PrintStream(new ByteArrayOutputStream()); @@ -49,8 +49,7 @@ public abstract class SilentTestCase extends Assert } @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { System.setOut(origSysOut); System.setErr(origSysErr); } diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/CompressionUtilTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/CompressionUtilTest.java index 1f8463fd4c..aaeb57801e 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/CompressionUtilTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/CompressionUtilTest.java @@ -31,12 +31,10 @@ import org.apache.activemq.artemis.utils.DeflaterReader; import org.apache.activemq.artemis.utils.InflaterReader; import org.apache.activemq.artemis.utils.InflaterWriter; -public class CompressionUtilTest extends Assert -{ +public class CompressionUtilTest extends Assert { @Test - public void testDeflaterReader() throws Exception - { + public void testDeflaterReader() throws Exception { String inputString = "blahblahblah??blahblahblahblahblah??blablahblah??blablahblah??bla"; byte[] input = inputString.getBytes(StandardCharsets.UTF_8); @@ -48,8 +46,7 @@ public class CompressionUtilTest extends Assert ArrayList zipHolder = new ArrayList(); int b = reader.read(); - while (b != -1) - { + while (b != -1) { zipHolder.add(b); b = reader.read(); } @@ -57,8 +54,7 @@ public class CompressionUtilTest extends Assert assertEquals(input.length, counter.get()); byte[] allCompressed = new byte[zipHolder.size()]; - for (int i = 0; i < allCompressed.length; i++) - { + for (int i = 0; i < allCompressed.length; i++) { allCompressed[i] = (byte) zipHolder.get(i).intValue(); } @@ -73,8 +69,7 @@ public class CompressionUtilTest extends Assert } @Test - public void testDeflaterReader2() throws Exception - { + public void testDeflaterReader2() throws Exception { String inputString = "blahblahblah??blahblahblahblahblah??blablahblah??blablahblah??bla"; byte[] input = inputString.getBytes(StandardCharsets.UTF_8); @@ -87,11 +82,9 @@ public class CompressionUtilTest extends Assert ArrayList zipHolder = new ArrayList(); int n = reader.read(buffer); - while (n != -1) - { - for (int i = 0; i < n; i++) - { - zipHolder.add((int)buffer[i]); + while (n != -1) { + for (int i = 0; i < n; i++) { + zipHolder.add((int) buffer[i]); } n = reader.read(buffer); } @@ -99,8 +92,7 @@ public class CompressionUtilTest extends Assert assertEquals(input.length, counter.get()); byte[] allCompressed = new byte[zipHolder.size()]; - for (int i = 0; i < allCompressed.length; i++) - { + for (int i = 0; i < allCompressed.length; i++) { allCompressed[i] = (byte) zipHolder.get(i).intValue(); } @@ -115,8 +107,7 @@ public class CompressionUtilTest extends Assert } @Test - public void testInflaterReader() throws Exception - { + public void testInflaterReader() throws Exception { String inputString = "blahblahblah??blahblahblahblahblah??blablahblah??blablahblah??bla"; byte[] input = inputString.getBytes(StandardCharsets.UTF_8); byte[] output = new byte[30]; @@ -134,16 +125,14 @@ public class CompressionUtilTest extends Assert ArrayList holder = new ArrayList(); int read = inflater.read(); - while (read != -1) - { + while (read != -1) { holder.add(read); read = inflater.read(); } byte[] result = new byte[holder.size()]; - for (int i = 0; i < result.length; i++) - { + for (int i = 0; i < result.length; i++) { result[i] = holder.get(i).byteValue(); } @@ -154,8 +143,7 @@ public class CompressionUtilTest extends Assert } @Test - public void testInflaterWriter() throws Exception - { + public void testInflaterWriter() throws Exception { String inputString = "blahblahblah??blahblahblahblahblah??blablahblah??blablahblah??bla"; byte[] input = inputString.getBytes(StandardCharsets.UTF_8); byte[] output = new byte[30]; @@ -175,8 +163,7 @@ public class CompressionUtilTest extends Assert byte[] zipBuffer = new byte[12]; int n = byteInput.read(zipBuffer); - while (n > 0) - { + while (n > 0) { writer.write(zipBuffer, 0, n); n = byteInput.read(zipBuffer); } @@ -189,10 +176,8 @@ public class CompressionUtilTest extends Assert assertEquals(inputString, outStr); } - private void compareByteArray(byte[] first, byte[] second, int length) - { - for (int i = 0; i < length; i++) - { + private void compareByteArray(byte[] first, byte[] second, int length) { + for (int i = 0; i < length; i++) { assertEquals(first[i], second[i]); } } diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/ConcurrentHashSetTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/ConcurrentHashSetTest.java index 002428bc7e..8a2e40b4ee 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/ConcurrentHashSetTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/ConcurrentHashSetTest.java @@ -25,8 +25,7 @@ import org.junit.Test; import java.util.Iterator; -public class ConcurrentHashSetTest extends Assert -{ +public class ConcurrentHashSetTest extends Assert { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -42,22 +41,19 @@ public class ConcurrentHashSetTest extends Assert // Public -------------------------------------------------------- @Test - public void testAdd() throws Exception - { + public void testAdd() throws Exception { Assert.assertTrue(set.add(element)); Assert.assertFalse(set.add(element)); } @Test - public void testAddIfAbsent() throws Exception - { + public void testAddIfAbsent() throws Exception { Assert.assertTrue(set.addIfAbsent(element)); Assert.assertFalse(set.addIfAbsent(element)); } @Test - public void testRemove() throws Exception - { + public void testRemove() throws Exception { Assert.assertTrue(set.add(element)); Assert.assertTrue(set.remove(element)); @@ -65,8 +61,7 @@ public class ConcurrentHashSetTest extends Assert } @Test - public void testContains() throws Exception - { + public void testContains() throws Exception { Assert.assertFalse(set.contains(element)); Assert.assertTrue(set.add(element)); @@ -77,8 +72,7 @@ public class ConcurrentHashSetTest extends Assert } @Test - public void testSize() throws Exception - { + public void testSize() throws Exception { Assert.assertEquals(0, set.size()); Assert.assertTrue(set.add(element)); @@ -89,8 +83,7 @@ public class ConcurrentHashSetTest extends Assert } @Test - public void testClear() throws Exception - { + public void testClear() throws Exception { Assert.assertTrue(set.add(element)); Assert.assertTrue(set.contains(element)); @@ -99,8 +92,7 @@ public class ConcurrentHashSetTest extends Assert } @Test - public void testIsEmpty() throws Exception - { + public void testIsEmpty() throws Exception { Assert.assertTrue(set.isEmpty()); Assert.assertTrue(set.add(element)); @@ -111,13 +103,11 @@ public class ConcurrentHashSetTest extends Assert } @Test - public void testIterator() throws Exception - { + public void testIterator() throws Exception { set.add(element); Iterator iterator = set.iterator(); - while (iterator.hasNext()) - { + while (iterator.hasNext()) { String e = iterator.next(); Assert.assertEquals(element, e); } @@ -126,8 +116,7 @@ public class ConcurrentHashSetTest extends Assert // TestCase overrides -------------------------------------------- @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { set = new ConcurrentHashSet(); element = RandomUtil.randomString(); } diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/TimeAndCounterIDGeneratorTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/TimeAndCounterIDGeneratorTest.java index f21d1b1182..923a9f3de1 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/TimeAndCounterIDGeneratorTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/TimeAndCounterIDGeneratorTest.java @@ -24,8 +24,7 @@ import org.junit.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -public class TimeAndCounterIDGeneratorTest extends Assert -{ +public class TimeAndCounterIDGeneratorTest extends Assert { // Constants ----------------------------------------------------- @@ -38,15 +37,13 @@ public class TimeAndCounterIDGeneratorTest extends Assert // Public -------------------------------------------------------- @Test - public void testCalculation() - { + public void testCalculation() { TimeAndCounterIDGenerator seq = new TimeAndCounterIDGenerator(); long max = 11000; long lastNr = 0; - for (long i = 0; i < max; i++) - { + for (long i = 0; i < max; i++) { long seqNr = seq.generateID(); Assert.assertTrue("The sequence generator should aways generate crescent numbers", seqNr > lastNr); @@ -57,8 +54,7 @@ public class TimeAndCounterIDGeneratorTest extends Assert } @Test - public void testCalculationRefresh() - { + public void testCalculationRefresh() { TimeAndCounterIDGenerator seq = new TimeAndCounterIDGenerator(); long id1 = seq.generateID(); @@ -76,8 +72,7 @@ public class TimeAndCounterIDGeneratorTest extends Assert } @Test - public void testCalculationOnMultiThread() throws Throwable - { + public void testCalculationOnMultiThread() throws Throwable { final ConcurrentHashSet hashSet = new ConcurrentHashSet(); final TimeAndCounterIDGenerator seq = new TimeAndCounterIDGenerator(); @@ -92,33 +87,29 @@ public class TimeAndCounterIDGeneratorTest extends Assert final CountDownLatch latchStart = new CountDownLatch(1); - class T1 extends Thread - { + class T1 extends Thread { + Throwable e; @Override - public void run() - { - try - { + public void run() { + try { latchAlign.countDown(); assertTrue("Latch has got to return within a minute", latchStart.await(1, TimeUnit.MINUTES)); long lastValue = 0L; - for (int i = 0; i < NUMBER_OF_IDS; i++) - { + for (int i = 0; i < NUMBER_OF_IDS; i++) { long value = seq.generateID(); Assert.assertTrue(TimeAndCounterIDGeneratorTest.hex(value) + " should be greater than " + - TimeAndCounterIDGeneratorTest.hex(lastValue) + - " on seq " + - seq.toString(), value > lastValue); + TimeAndCounterIDGeneratorTest.hex(lastValue) + + " on seq " + + seq.toString(), value > lastValue); lastValue = value; hashSet.add(value); } } - catch (Throwable e) - { + catch (Throwable e) { this.e = e; } } @@ -127,8 +118,7 @@ public class TimeAndCounterIDGeneratorTest extends Assert T1[] arrays = new T1[NUMBER_OF_THREADS]; - for (int i = 0; i < arrays.length; i++) - { + for (int i = 0; i < arrays.length; i++) { arrays[i] = new T1(); arrays[i].start(); } @@ -137,11 +127,9 @@ public class TimeAndCounterIDGeneratorTest extends Assert latchStart.countDown(); - for (T1 t : arrays) - { + for (T1 t : arrays) { t.join(); - if (t.e != null) - { + if (t.e != null) { throw t.e; } } @@ -153,8 +141,7 @@ public class TimeAndCounterIDGeneratorTest extends Assert } @Test - public void testWrapID() throws Throwable - { + public void testWrapID() throws Throwable { TimeAndCounterIDGenerator seq = new TimeAndCounterIDGenerator(); System.out.println("Current Time = " + TimeAndCounterIDGeneratorTest.hex(System.currentTimeMillis()) + " " + seq); @@ -163,14 +150,12 @@ public class TimeAndCounterIDGeneratorTest extends Assert seq.setInternalID(TimeAndCounterIDGenerator.ID_MASK); // 1 ID about to explode - try - { + try { // This is simulating a situation where we generated more than 268 million messages on the same time interval seq.generateID(); Assert.fail("It was supposed to throw an exception, as the counter was set to explode on this test"); } - catch (Exception e) - { + catch (Exception e) { } seq = new TimeAndCounterIDGenerator(); @@ -185,12 +170,10 @@ public class TimeAndCounterIDGeneratorTest extends Assert seq.generateID(); Assert.assertTrue(TimeAndCounterIDGeneratorTest.hex(timeMark) + " < " + - TimeAndCounterIDGeneratorTest.hex(seq.getInternalTimeMark()), - timeMark < seq.getInternalTimeMark()); + TimeAndCounterIDGeneratorTest.hex(seq.getInternalTimeMark()), timeMark < seq.getInternalTimeMark()); } - private static String hex(final long value) - { + private static String hex(final long value) { return String.format("%1$X", value); } diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/TypedPropertiesConversionTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/TypedPropertiesConversionTest.java index 955b498cc6..56ec47fa9f 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/TypedPropertiesConversionTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/TypedPropertiesConversionTest.java @@ -24,8 +24,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class TypedPropertiesConversionTest -{ +public class TypedPropertiesConversionTest { // Constants ----------------------------------------------------- @@ -44,15 +43,13 @@ public class TypedPropertiesConversionTest // Public -------------------------------------------------------- @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { key = RandomUtil.randomSimpleString(); props = new TypedProperties(); } @Test - public void testBooleanProperty() throws Exception - { + public void testBooleanProperty() throws Exception { Boolean val = RandomUtil.randomBoolean(); props.putBooleanProperty(key, val); @@ -62,51 +59,43 @@ public class TypedPropertiesConversionTest props.putSimpleStringProperty(key, new SimpleString(Boolean.toString(val))); Assert.assertEquals(val, props.getBooleanProperty(key)); - try - { + try { props.putByteProperty(key, RandomUtil.randomByte()); props.getBooleanProperty(key); Assert.fail(); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { } Assert.assertFalse(props.getBooleanProperty(unknownKey)); } @Test - public void testCharProperty() throws Exception - { + public void testCharProperty() throws Exception { Character val = RandomUtil.randomChar(); props.putCharProperty(key, val); Assert.assertEquals(val, props.getCharProperty(key)); Assert.assertEquals(new SimpleString(Character.toString(val)), props.getSimpleStringProperty(key)); - try - { + try { props.putByteProperty(key, RandomUtil.randomByte()); props.getCharProperty(key); Assert.fail(); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { } - try - { + try { props.getCharProperty(unknownKey); Assert.fail(); } - catch (NullPointerException e) - { + catch (NullPointerException e) { } } @Test - public void testByteProperty() throws Exception - { + public void testByteProperty() throws Exception { Byte val = RandomUtil.randomByte(); props.putByteProperty(key, val); @@ -116,29 +105,24 @@ public class TypedPropertiesConversionTest props.putSimpleStringProperty(key, new SimpleString(Byte.toString(val))); Assert.assertEquals(val, props.getByteProperty(key)); - try - { + try { props.putBooleanProperty(key, RandomUtil.randomBoolean()); props.getByteProperty(key); Assert.fail(); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { } - try - { + try { props.getByteProperty(unknownKey); Assert.fail(); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } } @Test - public void testIntProperty() throws Exception - { + public void testIntProperty() throws Exception { Integer val = RandomUtil.randomInt(); props.putIntProperty(key, val); @@ -152,29 +136,24 @@ public class TypedPropertiesConversionTest props.putByteProperty(key, byteVal); Assert.assertEquals(Integer.valueOf(byteVal), props.getIntProperty(key)); - try - { + try { props.putBooleanProperty(key, RandomUtil.randomBoolean()); props.getIntProperty(key); Assert.fail(); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { } - try - { + try { props.getIntProperty(unknownKey); Assert.fail(); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } } @Test - public void testLongProperty() throws Exception - { + public void testLongProperty() throws Exception { Long val = RandomUtil.randomLong(); props.putLongProperty(key, val); @@ -196,29 +175,24 @@ public class TypedPropertiesConversionTest props.putIntProperty(key, intVal); Assert.assertEquals(Long.valueOf(intVal), props.getLongProperty(key)); - try - { + try { props.putBooleanProperty(key, RandomUtil.randomBoolean()); props.getLongProperty(key); Assert.fail(); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { } - try - { + try { props.getLongProperty(unknownKey); Assert.fail(); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } } @Test - public void testDoubleProperty() throws Exception - { + public void testDoubleProperty() throws Exception { Double val = RandomUtil.randomDouble(); props.putDoubleProperty(key, val); @@ -228,29 +202,24 @@ public class TypedPropertiesConversionTest props.putSimpleStringProperty(key, new SimpleString(Double.toString(val))); Assert.assertEquals(val, props.getDoubleProperty(key)); - try - { + try { props.putBooleanProperty(key, RandomUtil.randomBoolean()); props.getDoubleProperty(key); Assert.fail(); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { } - try - { + try { props.getDoubleProperty(unknownKey); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { } } @Test - public void testFloatProperty() throws Exception - { + public void testFloatProperty() throws Exception { Float val = RandomUtil.randomFloat(); props.putFloatProperty(key, val); @@ -261,29 +230,24 @@ public class TypedPropertiesConversionTest props.putSimpleStringProperty(key, new SimpleString(Float.toString(val))); Assert.assertEquals(val, props.getFloatProperty(key)); - try - { + try { props.putBooleanProperty(key, RandomUtil.randomBoolean()); props.getFloatProperty(key); Assert.fail(); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { } - try - { + try { props.getFloatProperty(unknownKey); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { } } @Test - public void testShortProperty() throws Exception - { + public void testShortProperty() throws Exception { Short val = RandomUtil.randomShort(); props.putShortProperty(key, val); @@ -298,50 +262,42 @@ public class TypedPropertiesConversionTest props.putByteProperty(key, byteVal); Assert.assertEquals(Short.valueOf(byteVal), props.getShortProperty(key)); - try - { + try { props.putBooleanProperty(key, RandomUtil.randomBoolean()); props.getShortProperty(key); Assert.fail(); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { } - try - { + try { props.getShortProperty(unknownKey); Assert.fail(); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } } @Test - public void testSimpleStringProperty() throws Exception - { + public void testSimpleStringProperty() throws Exception { SimpleString strVal = RandomUtil.randomSimpleString(); props.putSimpleStringProperty(key, strVal); Assert.assertEquals(strVal, props.getSimpleStringProperty(key)); } @Test - public void testBytesProperty() throws Exception - { + public void testBytesProperty() throws Exception { byte[] val = RandomUtil.randomBytes(); props.putBytesProperty(key, val); Assert.assertArrayEquals(val, props.getBytesProperty(key)); - try - { + try { props.putBooleanProperty(key, RandomUtil.randomBoolean()); props.getBytesProperty(key); Assert.fail(); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { } Assert.assertNull(props.getBytesProperty(unknownKey)); diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/TypedPropertiesTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/TypedPropertiesTest.java index 9f184fac9b..894399bf88 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/TypedPropertiesTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/TypedPropertiesTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.util; + import java.util.Iterator; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; @@ -26,29 +27,24 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class TypedPropertiesTest -{ +public class TypedPropertiesTest { - private static void assertEqualsTypeProperties(final TypedProperties expected, final TypedProperties actual) - { + private static void assertEqualsTypeProperties(final TypedProperties expected, final TypedProperties actual) { Assert.assertNotNull(expected); Assert.assertNotNull(actual); Assert.assertEquals(expected.getEncodeSize(), actual.getEncodeSize()); Assert.assertEquals(expected.getPropertyNames(), actual.getPropertyNames()); Iterator iterator = actual.getPropertyNames().iterator(); - while (iterator.hasNext()) - { + while (iterator.hasNext()) { SimpleString key = iterator.next(); Object expectedValue = expected.getProperty(key); Object actualValue = actual.getProperty(key); - if (expectedValue instanceof byte[] && actualValue instanceof byte[]) - { - byte[] expectedBytes = (byte[])expectedValue; - byte[] actualBytes = (byte[])actualValue; + if (expectedValue instanceof byte[] && actualValue instanceof byte[]) { + byte[] expectedBytes = (byte[]) expectedValue; + byte[] actualBytes = (byte[]) actualValue; Assert.assertArrayEquals(expectedBytes, actualBytes); } - else - { + else { Assert.assertEquals(expectedValue, actualValue); } } @@ -63,8 +59,7 @@ public class TypedPropertiesTest private SimpleString key; @Test - public void testCopyContructor() throws Exception - { + public void testCopyContructor() throws Exception { props.putSimpleStringProperty(key, RandomUtil.randomSimpleString()); TypedProperties copy = new TypedProperties(props); @@ -77,8 +72,7 @@ public class TypedPropertiesTest } @Test - public void testRemove() throws Exception - { + public void testRemove() throws Exception { props.putSimpleStringProperty(key, RandomUtil.randomSimpleString()); Assert.assertTrue(props.containsProperty(key)); @@ -91,8 +85,7 @@ public class TypedPropertiesTest } @Test - public void testClear() throws Exception - { + public void testClear() throws Exception { props.putSimpleStringProperty(key, RandomUtil.randomSimpleString()); Assert.assertTrue(props.containsProperty(key)); @@ -105,52 +98,46 @@ public class TypedPropertiesTest } @Test - public void testKey() throws Exception - { + public void testKey() throws Exception { props.putBooleanProperty(key, true); - boolean bool = (Boolean)props.getProperty(key); + boolean bool = (Boolean) props.getProperty(key); Assert.assertEquals(true, bool); props.putCharProperty(key, 'a'); - char c = (Character)props.getProperty(key); + char c = (Character) props.getProperty(key); Assert.assertEquals('a', c); } @Test - public void testGetPropertyOnEmptyProperties() throws Exception - { + public void testGetPropertyOnEmptyProperties() throws Exception { Assert.assertFalse(props.containsProperty(key)); Assert.assertNull(props.getProperty(key)); } @Test - public void testRemovePropertyOnEmptyProperties() throws Exception - { + public void testRemovePropertyOnEmptyProperties() throws Exception { Assert.assertFalse(props.containsProperty(key)); Assert.assertNull(props.removeProperty(key)); } @Test - public void testNullProperty() throws Exception - { + public void testNullProperty() throws Exception { props.putSimpleStringProperty(key, null); Assert.assertTrue(props.containsProperty(key)); Assert.assertNull(props.getProperty(key)); } @Test - public void testBytesPropertyWithNull() throws Exception - { + public void testBytesPropertyWithNull() throws Exception { props.putBytesProperty(key, null); Assert.assertTrue(props.containsProperty(key)); - byte[] bb = (byte[])props.getProperty(key); + byte[] bb = (byte[]) props.getProperty(key); Assert.assertNull(bb); } @Test - public void testTypedProperties() throws Exception - { + public void testTypedProperties() throws Exception { SimpleString longKey = RandomUtil.randomSimpleString(); long longValue = RandomUtil.randomLong(); SimpleString simpleStringKey = RandomUtil.randomSimpleString(); @@ -168,8 +155,7 @@ public class TypedPropertiesTest } @Test - public void testEmptyTypedProperties() throws Exception - { + public void testEmptyTypedProperties() throws Exception { Assert.assertEquals(0, props.getPropertyNames().size()); props.putTypedProperties(new TypedProperties()); @@ -178,8 +164,7 @@ public class TypedPropertiesTest } @Test - public void testNullTypedProperties() throws Exception - { + public void testNullTypedProperties() throws Exception { Assert.assertEquals(0, props.getPropertyNames().size()); props.putTypedProperties(null); @@ -188,8 +173,7 @@ public class TypedPropertiesTest } @Test - public void testEncodeDecode() throws Exception - { + public void testEncodeDecode() throws Exception { props.putByteProperty(RandomUtil.randomSimpleString(), RandomUtil.randomByte()); props.putBytesProperty(RandomUtil.randomSimpleString(), RandomUtil.randomBytes()); props.putBytesProperty(RandomUtil.randomSimpleString(), null); @@ -225,8 +209,7 @@ public class TypedPropertiesTest } @Test - public void testEncodeDecodeEmpty() throws Exception - { + public void testEncodeDecodeEmpty() throws Exception { TypedProperties emptyProps = new TypedProperties(); ActiveMQBuffer buffer = ActiveMQBuffers.dynamicBuffer(1024); @@ -241,8 +224,7 @@ public class TypedPropertiesTest } @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { props = new TypedProperties(); key = RandomUtil.randomSimpleString(); } diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/XMLUtilTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/XMLUtilTest.java index 99853749c2..f2feeac9eb 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/XMLUtilTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/XMLUtilTest.java @@ -26,15 +26,13 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -public class XMLUtilTest extends SilentTestCase -{ +public class XMLUtilTest extends SilentTestCase { // Constructors -------------------------------------------------- // Public -------------------------------------------------------- @Test - public void testGetTextContext_1() throws Exception - { + public void testGetTextContext_1() throws Exception { String document = "foo"; Element e = XMLUtil.stringToElement(document); @@ -43,8 +41,7 @@ public class XMLUtilTest extends SilentTestCase } @Test - public void testGetTextContext_2() throws Exception - { + public void testGetTextContext_2() throws Exception { String document = "foo"; Element e = XMLUtil.stringToElement(document); @@ -53,8 +50,7 @@ public class XMLUtilTest extends SilentTestCase } @Test - public void testGetTextContext_3() throws Exception - { + public void testGetTextContext_3() throws Exception { String document = ""; Element e = XMLUtil.stringToElement(document); @@ -67,8 +63,7 @@ public class XMLUtilTest extends SilentTestCase } @Test - public void testGetTextContext_4() throws Exception - { + public void testGetTextContext_4() throws Exception { String document = ""; Element e = XMLUtil.stringToElement(document); @@ -81,8 +76,7 @@ public class XMLUtilTest extends SilentTestCase } @Test - public void testGetTextContext_5() throws Exception - { + public void testGetTextContext_5() throws Exception { String document = ""; Element e = XMLUtil.stringToElement(document); @@ -96,11 +90,9 @@ public class XMLUtilTest extends SilentTestCase // try to find boolean found = false; - for (int i = 0; i < nl.getLength(); i++) - { + for (int i = 0; i < nl.getLength(); i++) { Node n = nl.item(i); - if ("b".equals(n.getNodeName())) - { + if ("b".equals(n.getNodeName())) { found = true; } } @@ -108,8 +100,7 @@ public class XMLUtilTest extends SilentTestCase } @Test - public void testEquivalent_1() throws Exception - { + public void testEquivalent_1() throws Exception { String s = ""; String s2 = ""; @@ -117,8 +108,7 @@ public class XMLUtilTest extends SilentTestCase } @Test - public void testEquivalent_2() throws Exception - { + public void testEquivalent_2() throws Exception { String s = ""; String s2 = ""; @@ -126,85 +116,68 @@ public class XMLUtilTest extends SilentTestCase } @Test - public void testEquivalent_3() throws Exception - { + public void testEquivalent_3() throws Exception { String s = ""; String s2 = ""; - try - { - XMLUtil.assertEquivalent(XMLUtil.stringToElement(s), - XMLUtil.stringToElement(s2)); + try { + XMLUtil.assertEquivalent(XMLUtil.stringToElement(s), XMLUtil.stringToElement(s2)); Assert.fail("this should throw exception"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { // expected } } @Test - public void testEquivalent_4() throws Exception - { + public void testEquivalent_4() throws Exception { String s = ""; String s2 = ""; - XMLUtil.assertEquivalent(XMLUtil.stringToElement(s), - XMLUtil.stringToElement(s2)); + XMLUtil.assertEquivalent(XMLUtil.stringToElement(s), XMLUtil.stringToElement(s2)); } @Test - public void testEquivalent_5() throws Exception - { + public void testEquivalent_5() throws Exception { String s = ""; String s2 = ""; - XMLUtil.assertEquivalent(XMLUtil.stringToElement(s), - XMLUtil.stringToElement(s2)); + XMLUtil.assertEquivalent(XMLUtil.stringToElement(s), XMLUtil.stringToElement(s2)); } @Test - public void testEquivalent_6() throws Exception - { + public void testEquivalent_6() throws Exception { String s = ""; String s2 = ""; - XMLUtil.assertEquivalent(XMLUtil.stringToElement(s), - XMLUtil.stringToElement(s2)); + XMLUtil.assertEquivalent(XMLUtil.stringToElement(s), XMLUtil.stringToElement(s2)); } @Test - public void testEquivalent_7() throws Exception - { + public void testEquivalent_7() throws Exception { String s = ""; String s2 = ""; - try - { - XMLUtil.assertEquivalent(XMLUtil.stringToElement(s), - XMLUtil.stringToElement(s2)); + try { + XMLUtil.assertEquivalent(XMLUtil.stringToElement(s), XMLUtil.stringToElement(s2)); Assert.fail("this should throw exception"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { // OK e.printStackTrace(); } } @Test - public void testEquivalent_8() throws Exception - { + public void testEquivalent_8() throws Exception { String s = ""; String s2 = ""; - XMLUtil.assertEquivalent(XMLUtil.stringToElement(s), - XMLUtil.stringToElement(s2)); + XMLUtil.assertEquivalent(XMLUtil.stringToElement(s), XMLUtil.stringToElement(s2)); } @Test - public void testElementToString_1() throws Exception - { + public void testElementToString_1() throws Exception { String s = "somethingelse"; Element e = XMLUtil.stringToElement(s); String tostring = XMLUtil.elementToString(e); @@ -213,8 +186,7 @@ public class XMLUtilTest extends SilentTestCase } @Test - public void testElementToString_2() throws Exception - { + public void testElementToString_2() throws Exception { String s = ""; Element e = XMLUtil.stringToElement(s); String tostring = XMLUtil.elementToString(e); @@ -223,8 +195,7 @@ public class XMLUtilTest extends SilentTestCase } @Test - public void testElementToString_3() throws Exception - { + public void testElementToString_3() throws Exception { String s = ""; Element e = XMLUtil.stringToElement(s); String tostring = XMLUtil.elementToString(e); @@ -233,8 +204,7 @@ public class XMLUtilTest extends SilentTestCase } @Test - public void testElementToString_4() throws Exception - { + public void testElementToString_4() throws Exception { String s = ""; Element e = XMLUtil.stringToElement(s); String tostring = XMLUtil.elementToString(e); @@ -243,22 +213,9 @@ public class XMLUtilTest extends SilentTestCase } @Test - public void testReplaceSystemProperties() - { - String before = "\n" + " content1\n" - + " content2\n" - + " content3\n" - + " ${sysprop2}\n" - + " content5\n" - + " content6\n" - + ""; - String after = "\n" + " content1\n" - + " content2\n" - + " content3\n" - + " content4\n" - + " content5\n" - + " content6\n" - + ""; + public void testReplaceSystemProperties() { + String before = "\n" + " content1\n" + " content2\n" + " content3\n" + " ${sysprop2}\n" + " content5\n" + " content6\n" + ""; + String after = "\n" + " content1\n" + " content2\n" + " content3\n" + " content4\n" + " content5\n" + " content6\n" + ""; System.setProperty("sysprop1", "test1"); System.setProperty("sysprop2", "content4"); String replaced = XMLUtil.replaceSystemProps(before); @@ -266,8 +223,7 @@ public class XMLUtilTest extends SilentTestCase } @Test - public void testStripCDATA() throws Exception - { + public void testStripCDATA() throws Exception { String xml = ""; String stripped = XMLUtil.stripCDATA(xml); diff --git a/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/AppDTO.java b/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/AppDTO.java index 4e9541a54d..5609509b00 100644 --- a/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/AppDTO.java +++ b/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/AppDTO.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.dto; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; @@ -24,8 +23,8 @@ import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "app") @XmlAccessorType(XmlAccessType.FIELD) -public class AppDTO -{ +public class AppDTO { + @XmlAttribute public String url; diff --git a/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/BasicSecurityDTO.java b/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/BasicSecurityDTO.java index 2e9d3911b0..cc1ede1d0b 100644 --- a/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/BasicSecurityDTO.java +++ b/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/BasicSecurityDTO.java @@ -23,8 +23,8 @@ import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "basic-security") @XmlAccessorType(XmlAccessType.FIELD) -public class BasicSecurityDTO extends SecurityDTO -{ +public class BasicSecurityDTO extends SecurityDTO { + @XmlAttribute(required = true) public String users; diff --git a/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/BrokerDTO.java b/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/BrokerDTO.java index a912f52c8d..0b0bb30857 100644 --- a/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/BrokerDTO.java +++ b/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/BrokerDTO.java @@ -25,8 +25,8 @@ import java.util.List; @XmlRootElement(name = "broker") @XmlAccessorType(XmlAccessType.FIELD) -public class BrokerDTO -{ +public class BrokerDTO { + @XmlElementRef public SecurityDTO security; diff --git a/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/ComponentDTO.java b/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/ComponentDTO.java index d12fae57eb..dee281db6c 100644 --- a/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/ComponentDTO.java +++ b/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/ComponentDTO.java @@ -23,8 +23,8 @@ import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "component") @XmlAccessorType(XmlAccessType.FIELD) -public class ComponentDTO -{ +public class ComponentDTO { + @XmlAttribute public String componentClassName; } diff --git a/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/SecurityDTO.java b/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/SecurityDTO.java index 80e58d4143..23d2680280 100644 --- a/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/SecurityDTO.java +++ b/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/SecurityDTO.java @@ -22,6 +22,6 @@ import javax.xml.bind.annotation.XmlType; @XmlType(name = "security") @XmlAccessorType(XmlAccessType.FIELD) -public class SecurityDTO -{ +public class SecurityDTO { + } diff --git a/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/ServerDTO.java b/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/ServerDTO.java index 6110bcd69b..d09bef1a28 100644 --- a/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/ServerDTO.java +++ b/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/ServerDTO.java @@ -25,47 +25,36 @@ import java.net.URI; @XmlRootElement(name = "server") @XmlAccessorType(XmlAccessType.FIELD) -public class ServerDTO -{ +public class ServerDTO { @XmlAttribute public String configuration; - private File configurationFile; private URI configurationURI; - - public URI getConfigurationURI() throws Exception - { - if (configurationURI == null) - { + public URI getConfigurationURI() throws Exception { + if (configurationURI == null) { configurationURI = new URI(fixupFileURI(configuration)); } return configurationURI; } - public File getConfigurationFile() throws Exception - { - if (configurationFile == null) - { + public File getConfigurationFile() throws Exception { + if (configurationFile == null) { configurationFile = new File(new URI(fixupFileURI(configuration)).getSchemeSpecificPart()); } return configurationFile; } - private static String fixupFileURI(String value) - { - if (value != null && value.startsWith("file:")) - { + private static String fixupFileURI(String value) { + if (value != null && value.startsWith("file:")) { value = value.substring("file:".length()); value = new File(value).toURI().toString(); } return value; } - - } diff --git a/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/WebServerDTO.java b/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/WebServerDTO.java index cf2e9a99ee..036e7ecb0a 100644 --- a/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/WebServerDTO.java +++ b/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/WebServerDTO.java @@ -25,8 +25,8 @@ import java.util.List; @XmlRootElement(name = "web") @XmlAccessorType(XmlAccessType.FIELD) -public class WebServerDTO extends ComponentDTO -{ +public class WebServerDTO extends ComponentDTO { + @XmlAttribute public String bind; @@ -36,8 +36,7 @@ public class WebServerDTO extends ComponentDTO @XmlElementRef public List apps; - public WebServerDTO() - { + public WebServerDTO() { componentClassName = "org.apache.activemq.artemis.component.WebServerComponent"; } } diff --git a/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/XmlUtil.java b/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/XmlUtil.java index ffc6492b55..c49dbe5336 100644 --- a/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/XmlUtil.java +++ b/artemis-dto/src/main/java/org/apache/activemq/artemis/dto/XmlUtil.java @@ -32,48 +32,39 @@ import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; -public class XmlUtil -{ +public class XmlUtil { /** * Changes ${property} with values from a properties object */ - static class PropertiesFilter extends StreamReaderDelegate - { + static class PropertiesFilter extends StreamReaderDelegate { static final Pattern pattern = Pattern.compile("\\$\\{([^\\}]+)\\}"); private final Properties props; - public PropertiesFilter(XMLStreamReader parent, Properties props) - { + public PropertiesFilter(XMLStreamReader parent, Properties props) { super(parent); this.props = props; } @Override - public String getAttributeValue(int index) - { + public String getAttributeValue(int index) { return filter(super.getAttributeValue(index)); } - public String filter(String str) - { + public String filter(String str) { int start = 0; - while (true) - { + while (true) { Matcher matcher = pattern.matcher(str); - if (!matcher.find(start)) - { + if (!matcher.find(start)) { break; } String group = matcher.group(1); String property = props.getProperty(group); - if (property != null) - { + if (property != null) { str = matcher.replaceFirst(Matcher.quoteReplacement(property)); } - else - { + else { start = matcher.end(); } } @@ -84,8 +75,7 @@ public class XmlUtil private static final XMLInputFactory factory = XMLInputFactory.newInstance(); - public static T decode(Class clazz, File configuration) throws Exception - { + public static T decode(Class clazz, File configuration) throws Exception { JAXBContext jaxbContext = JAXBContext.newInstance("org.apache.activemq.artemis.dto"); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); @@ -100,8 +90,7 @@ public class XmlUtil //TODO - support properties files Properties props = System.getProperties(); - if (props != null) - { + if (props != null) { reader = new PropertiesFilter(reader, props); } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/ActiveMQJMSClient.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/ActiveMQJMSClient.java index d1f932d5d5..1cf038c1bc 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/ActiveMQJMSClient.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/ActiveMQJMSClient.java @@ -34,15 +34,14 @@ import org.apache.activemq.artemis.uri.ConnectionFactoryParser; /** * A utility class for creating ActiveMQ Artemis client-side JMS managed resources. */ -public class ActiveMQJMSClient -{ +public class ActiveMQJMSClient { + /** * Creates an ActiveMQConnectionFactory; * * @return the ActiveMQConnectionFactory */ - public static ActiveMQConnectionFactory createConnectionFactory(final String url, String name) throws Exception - { + public static ActiveMQConnectionFactory createConnectionFactory(final String url, String name) throws Exception { ConnectionFactoryParser parser = new ConnectionFactoryParser(); return parser.newObject(parser.expandURI(url), name); } @@ -58,35 +57,30 @@ public class ActiveMQJMSClient * updated whenever the cluster topology changes. If the topology includes backup servers that * information is also propagated to the client so that it can know which server to failover onto * in case of live server failure. + * * @param groupConfiguration * @param jmsFactoryType * @return the ActiveMQConnectionFactory */ - public static ActiveMQConnectionFactory createConnectionFactoryWithHA(final DiscoveryGroupConfiguration groupConfiguration, JMSFactoryType jmsFactoryType) - { + public static ActiveMQConnectionFactory createConnectionFactoryWithHA(final DiscoveryGroupConfiguration groupConfiguration, + JMSFactoryType jmsFactoryType) { ActiveMQConnectionFactory factory = null; - if (jmsFactoryType.equals(JMSFactoryType.CF)) - { + if (jmsFactoryType.equals(JMSFactoryType.CF)) { factory = new ActiveMQJMSConnectionFactory(true, groupConfiguration); } - else if (jmsFactoryType.equals(JMSFactoryType.QUEUE_CF)) - { + else if (jmsFactoryType.equals(JMSFactoryType.QUEUE_CF)) { factory = new ActiveMQQueueConnectionFactory(true, groupConfiguration); } - else if (jmsFactoryType.equals(JMSFactoryType.TOPIC_CF)) - { + else if (jmsFactoryType.equals(JMSFactoryType.TOPIC_CF)) { factory = new ActiveMQTopicConnectionFactory(true, groupConfiguration); } - else if (jmsFactoryType.equals(JMSFactoryType.XA_CF)) - { + else if (jmsFactoryType.equals(JMSFactoryType.XA_CF)) { factory = new ActiveMQXAConnectionFactory(true, groupConfiguration); } - else if (jmsFactoryType.equals(JMSFactoryType.QUEUE_XA_CF)) - { + else if (jmsFactoryType.equals(JMSFactoryType.QUEUE_XA_CF)) { factory = new ActiveMQXAQueueConnectionFactory(true, groupConfiguration); } - else if (jmsFactoryType.equals(JMSFactoryType.TOPIC_XA_CF)) - { + else if (jmsFactoryType.equals(JMSFactoryType.TOPIC_XA_CF)) { factory = new ActiveMQXATopicConnectionFactory(true, groupConfiguration); } @@ -102,31 +96,25 @@ public class ActiveMQJMSClient * @param jmsFactoryType * @return the ActiveMQConnectionFactory */ - public static ActiveMQConnectionFactory createConnectionFactoryWithoutHA(final DiscoveryGroupConfiguration groupConfiguration, JMSFactoryType jmsFactoryType) - { + public static ActiveMQConnectionFactory createConnectionFactoryWithoutHA(final DiscoveryGroupConfiguration groupConfiguration, + JMSFactoryType jmsFactoryType) { ActiveMQConnectionFactory factory = null; - if (jmsFactoryType.equals(JMSFactoryType.CF)) - { + if (jmsFactoryType.equals(JMSFactoryType.CF)) { factory = new ActiveMQJMSConnectionFactory(false, groupConfiguration); } - else if (jmsFactoryType.equals(JMSFactoryType.QUEUE_CF)) - { + else if (jmsFactoryType.equals(JMSFactoryType.QUEUE_CF)) { factory = new ActiveMQQueueConnectionFactory(false, groupConfiguration); } - else if (jmsFactoryType.equals(JMSFactoryType.TOPIC_CF)) - { + else if (jmsFactoryType.equals(JMSFactoryType.TOPIC_CF)) { factory = new ActiveMQTopicConnectionFactory(false, groupConfiguration); } - else if (jmsFactoryType.equals(JMSFactoryType.XA_CF)) - { + else if (jmsFactoryType.equals(JMSFactoryType.XA_CF)) { factory = new ActiveMQXAConnectionFactory(false, groupConfiguration); } - else if (jmsFactoryType.equals(JMSFactoryType.QUEUE_XA_CF)) - { + else if (jmsFactoryType.equals(JMSFactoryType.QUEUE_XA_CF)) { factory = new ActiveMQXAQueueConnectionFactory(false, groupConfiguration); } - else if (jmsFactoryType.equals(JMSFactoryType.TOPIC_XA_CF)) - { + else if (jmsFactoryType.equals(JMSFactoryType.TOPIC_XA_CF)) { factory = new ActiveMQXATopicConnectionFactory(false, groupConfiguration); } @@ -142,37 +130,32 @@ public class ActiveMQJMSClient * downloaded and automatically updated whenever the cluster topology changes. If the topology * includes backup servers that information is also propagated to the client so that it can know * which server to failover onto in case of live server failure. + * * @param jmsFactoryType * @param initialServers The initial set of servers used to make a connection to the cluster. - * Each one is tried in turn until a successful connection is made. Once a connection - * is made, the cluster topology is downloaded and the rest of the list is ignored. + * Each one is tried in turn until a successful connection is made. Once a connection + * is made, the cluster topology is downloaded and the rest of the list is ignored. * @return the ActiveMQConnectionFactory */ - public static ActiveMQConnectionFactory createConnectionFactoryWithHA(JMSFactoryType jmsFactoryType, final TransportConfiguration... initialServers) - { + public static ActiveMQConnectionFactory createConnectionFactoryWithHA(JMSFactoryType jmsFactoryType, + final TransportConfiguration... initialServers) { ActiveMQConnectionFactory factory = null; - if (jmsFactoryType.equals(JMSFactoryType.CF)) - { + if (jmsFactoryType.equals(JMSFactoryType.CF)) { factory = new ActiveMQJMSConnectionFactory(true, initialServers); } - else if (jmsFactoryType.equals(JMSFactoryType.QUEUE_CF)) - { + else if (jmsFactoryType.equals(JMSFactoryType.QUEUE_CF)) { factory = new ActiveMQQueueConnectionFactory(true, initialServers); } - else if (jmsFactoryType.equals(JMSFactoryType.TOPIC_CF)) - { + else if (jmsFactoryType.equals(JMSFactoryType.TOPIC_CF)) { factory = new ActiveMQTopicConnectionFactory(true, initialServers); } - else if (jmsFactoryType.equals(JMSFactoryType.XA_CF)) - { + else if (jmsFactoryType.equals(JMSFactoryType.XA_CF)) { factory = new ActiveMQXAConnectionFactory(true, initialServers); } - else if (jmsFactoryType.equals(JMSFactoryType.QUEUE_XA_CF)) - { + else if (jmsFactoryType.equals(JMSFactoryType.QUEUE_XA_CF)) { factory = new ActiveMQXAQueueConnectionFactory(true, initialServers); } - else if (jmsFactoryType.equals(JMSFactoryType.TOPIC_XA_CF)) - { + else if (jmsFactoryType.equals(JMSFactoryType.TOPIC_XA_CF)) { factory = new ActiveMQXATopicConnectionFactory(true, initialServers); } @@ -185,35 +168,30 @@ public class ActiveMQJMSClient *

    * The ActiveMQConnectionFactory is not updated automatically as the cluster topology changes, and * no HA backup information is propagated to the client + * * @param jmsFactoryType * @param transportConfigurations * @return the ActiveMQConnectionFactory */ - public static ActiveMQConnectionFactory createConnectionFactoryWithoutHA(JMSFactoryType jmsFactoryType, final TransportConfiguration... transportConfigurations) - { + public static ActiveMQConnectionFactory createConnectionFactoryWithoutHA(JMSFactoryType jmsFactoryType, + final TransportConfiguration... transportConfigurations) { ActiveMQConnectionFactory factory = null; - if (jmsFactoryType.equals(JMSFactoryType.CF)) - { + if (jmsFactoryType.equals(JMSFactoryType.CF)) { factory = new ActiveMQJMSConnectionFactory(false, transportConfigurations); } - else if (jmsFactoryType.equals(JMSFactoryType.QUEUE_CF)) - { + else if (jmsFactoryType.equals(JMSFactoryType.QUEUE_CF)) { factory = new ActiveMQQueueConnectionFactory(false, transportConfigurations); } - else if (jmsFactoryType.equals(JMSFactoryType.TOPIC_CF)) - { + else if (jmsFactoryType.equals(JMSFactoryType.TOPIC_CF)) { factory = new ActiveMQTopicConnectionFactory(false, transportConfigurations); } - else if (jmsFactoryType.equals(JMSFactoryType.XA_CF)) - { + else if (jmsFactoryType.equals(JMSFactoryType.XA_CF)) { factory = new ActiveMQXAConnectionFactory(false, transportConfigurations); } - else if (jmsFactoryType.equals(JMSFactoryType.QUEUE_XA_CF)) - { + else if (jmsFactoryType.equals(JMSFactoryType.QUEUE_XA_CF)) { factory = new ActiveMQXAQueueConnectionFactory(false, transportConfigurations); } - else if (jmsFactoryType.equals(JMSFactoryType.TOPIC_XA_CF)) - { + else if (jmsFactoryType.equals(JMSFactoryType.TOPIC_XA_CF)) { factory = new ActiveMQXATopicConnectionFactory(false, transportConfigurations); } @@ -226,8 +204,7 @@ public class ActiveMQJMSClient * @param name the name of the topic * @return The Topic */ - public static Topic createTopic(final String name) - { + public static Topic createTopic(final String name) { return ActiveMQDestination.createTopic(name); } @@ -237,13 +214,11 @@ public class ActiveMQJMSClient * @param name the name of the queue * @return The Queue */ - public static Queue createQueue(final String name) - { + public static Queue createQueue(final String name) { return ActiveMQDestination.createQueue(name); } - private ActiveMQJMSClient() - { + private ActiveMQJMSClient() { // Utility class } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/ActiveMQJMSConstants.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/ActiveMQJMSConstants.java index f15bc95385..966a5c4a4b 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/ActiveMQJMSConstants.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/ActiveMQJMSConstants.java @@ -19,8 +19,8 @@ package org.apache.activemq.artemis.api.jms; /** * Constants for ActiveMQ Artemis for property keys used for ActiveMQ Artemis specific extensions to JMS. */ -public class ActiveMQJMSConstants -{ +public class ActiveMQJMSConstants { + public static final String JMS_ACTIVEMQ_INPUT_STREAM = "JMS_AMQ_InputStream"; public static final String JMS_ACTIVEMQ_OUTPUT_STREAM = "JMS_AMQ_OutputStream"; @@ -33,6 +33,5 @@ public class ActiveMQJMSConstants public static final int INDIVIDUAL_ACKNOWLEDGE = 101; - public static final String JMS_ACTIVEMQ_ENABLE_BYTE_ARRAY_JMS_CORRELATION_ID_PROPERTY_NAME = - "amq.jms.support-bytes-id"; + public static final String JMS_ACTIVEMQ_ENABLE_BYTE_ARRAY_JMS_CORRELATION_ID_PROPERTY_NAME = "amq.jms.support-bytes-id"; } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/JMSFactoryType.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/JMSFactoryType.java index 43aea2b298..67d3f57c31 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/JMSFactoryType.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/JMSFactoryType.java @@ -17,15 +17,12 @@ package org.apache.activemq.artemis.api.jms; // XXX no javadocs -public enum JMSFactoryType -{ +public enum JMSFactoryType { CF, QUEUE_CF, TOPIC_CF, XA_CF, QUEUE_XA_CF, TOPIC_XA_CF; - public int intValue() - { + public int intValue() { int val = 0; - switch (this) - { + switch (this) { case CF: val = 0; break; @@ -48,11 +45,9 @@ public enum JMSFactoryType return val; } - public static JMSFactoryType valueOf(int val) - { + public static JMSFactoryType valueOf(int val) { JMSFactoryType type; - switch (val) - { + switch (val) { case 0: type = CF; break; diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/ConnectionFactoryControl.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/ConnectionFactoryControl.java index f222c293fb..52722f352f 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/ConnectionFactoryControl.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/ConnectionFactoryControl.java @@ -29,8 +29,8 @@ import org.apache.activemq.artemis.api.core.management.Parameter; * @see org.apache.activemq.artemis.api.core.client.ServerLocator * @see org.apache.activemq.artemis.api.core.client.ClientSessionFactory */ -public interface ConnectionFactoryControl -{ +public interface ConnectionFactoryControl { + /** * Returns the configuration name of this connection factory. */ @@ -198,7 +198,6 @@ public interface ConnectionFactoryControl */ void setPreAcknowledge(boolean preAcknowledge); - /** * @see org.apache.activemq.artemis.api.core.client.ServerLocator#getConnectionTTL() */ @@ -281,7 +280,6 @@ public interface ConnectionFactoryControl */ void setFailoverOnInitialConnection(boolean failoverOnInitialConnection); - /** * @see org.apache.activemq.artemis.api.core.client.ServerLocator#getProducerWindowSize() */ diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/DestinationControl.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/DestinationControl.java index 94b329e661..678fb21cf3 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/DestinationControl.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/DestinationControl.java @@ -24,8 +24,7 @@ import org.apache.activemq.artemis.api.core.management.Parameter; /** * A DestinationControl is used to manage a JMS Destination. */ -public interface DestinationControl -{ +public interface DestinationControl { // Attributes ---------------------------------------------------- /** diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/JMSConnectionInfo.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/JMSConnectionInfo.java index 4d35f65553..e184c01376 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/JMSConnectionInfo.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/JMSConnectionInfo.java @@ -19,8 +19,7 @@ package org.apache.activemq.artemis.api.jms.management; import org.apache.activemq.artemis.utils.json.JSONArray; import org.apache.activemq.artemis.utils.json.JSONObject; -public class JMSConnectionInfo -{ +public class JMSConnectionInfo { private final String connectionID; @@ -32,24 +31,17 @@ public class JMSConnectionInfo private final String username; - // Static -------------------------------------------------------- - public static JMSConnectionInfo[] from(final String jsonString) throws Exception - { + public static JMSConnectionInfo[] from(final String jsonString) throws Exception { JSONArray array = new JSONArray(jsonString); JMSConnectionInfo[] infos = new JMSConnectionInfo[array.length()]; - for (int i = 0; i < array.length(); i++) - { + for (int i = 0; i < array.length(); i++) { JSONObject obj = array.getJSONObject(i); String cid = obj.isNull("clientID") ? null : obj.getString("clientID"); String uname = obj.isNull("principal") ? null : obj.getString("principal"); - JMSConnectionInfo info = new JMSConnectionInfo(obj.getString("connectionID"), - obj.getString("clientAddress"), - obj.getLong("creationTime"), - cid, - uname); + JMSConnectionInfo info = new JMSConnectionInfo(obj.getString("connectionID"), obj.getString("clientAddress"), obj.getLong("creationTime"), cid, uname); infos[i] = info; } return infos; @@ -61,8 +53,7 @@ public class JMSConnectionInfo final String clientAddress, final long creationTime, final String clientID, - final String username) - { + final String username) { this.connectionID = connectionID; this.clientAddress = clientAddress; this.creationTime = creationTime; @@ -72,28 +63,23 @@ public class JMSConnectionInfo // Public -------------------------------------------------------- - public String getConnectionID() - { + public String getConnectionID() { return connectionID; } - public String getClientAddress() - { + public String getClientAddress() { return clientAddress; } - public long getCreationTime() - { + public long getCreationTime() { return creationTime; } - public String getClientID() - { + public String getClientID() { return clientID; } - public String getUsername() - { + public String getUsername() { return username; } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/JMSConsumerInfo.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/JMSConsumerInfo.java index c92ea82dfa..7f4be56296 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/JMSConsumerInfo.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/JMSConsumerInfo.java @@ -23,8 +23,8 @@ import org.apache.activemq.artemis.utils.json.JSONObject; * Helper class to create Java Objects from the * JSON serialization returned by {@link JMSServerControl#listConsumersAsJSON(String)} and related methods. */ -public class JMSConsumerInfo -{ +public class JMSConsumerInfo { + private final String consumerID; private final String connectionID; @@ -47,21 +47,12 @@ public class JMSConsumerInfo * Returns an array of SubscriptionInfo corresponding to the JSON serialization returned * by {@link TopicControl#listAllSubscriptionsAsJSON()} and related methods. */ - public static JMSConsumerInfo[] from(final String jsonString) throws Exception - { + public static JMSConsumerInfo[] from(final String jsonString) throws Exception { JSONArray array = new JSONArray(jsonString); JMSConsumerInfo[] infos = new JMSConsumerInfo[array.length()]; - for (int i = 0; i < array.length(); i++) - { + for (int i = 0; i < array.length(); i++) { JSONObject sub = array.getJSONObject(i); - JMSConsumerInfo info = new JMSConsumerInfo(sub.getString("consumerID"), - sub.getString("connectionID"), - sub.getString("destinationName"), - sub.getString("destinationType"), - sub.getBoolean("browseOnly"), - sub.getLong("creationTime"), - sub.getBoolean("durable"), - sub.optString("filter", null)); + JMSConsumerInfo info = new JMSConsumerInfo(sub.getString("consumerID"), sub.getString("connectionID"), sub.getString("destinationName"), sub.getString("destinationType"), sub.getBoolean("browseOnly"), sub.getLong("creationTime"), sub.getBoolean("durable"), sub.optString("filter", null)); infos[i] = info; } @@ -72,13 +63,12 @@ public class JMSConsumerInfo private JMSConsumerInfo(final String consumerID, final String connectionID, - final String destinationName, - final String destinationType, - final boolean browseOnly, - final long creationTime, - final boolean durable, - final String filter) - { + final String destinationName, + final String destinationType, + final boolean browseOnly, + final long creationTime, + final boolean durable, + final String filter) { this.consumerID = consumerID; this.connectionID = connectionID; this.destinationName = destinationName; @@ -91,46 +81,38 @@ public class JMSConsumerInfo // Public -------------------------------------------------------- - public String getConsumerID() - { + public String getConsumerID() { return consumerID; } - public String getConnectionID() - { + public String getConnectionID() { return connectionID; } - public String getDestinationName() - { + public String getDestinationName() { return destinationName; } - public String getDestinationType() - { + public String getDestinationType() { return destinationType; } - public boolean isBrowseOnly() - { + public boolean isBrowseOnly() { return browseOnly; } - public long getCreationTime() - { + public long getCreationTime() { return creationTime; } /** * @return the durable */ - public boolean isDurable() - { + public boolean isDurable() { return durable; } - public String getFilter() - { + public String getFilter() { return filter; } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/JMSManagementHelper.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/JMSManagementHelper.java index c7504bb385..33b902b32c 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/JMSManagementHelper.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/JMSManagementHelper.java @@ -25,62 +25,52 @@ import org.apache.activemq.artemis.jms.client.ActiveMQMessage; /** * Helper class to use JMS messages to manage ActiveMQ Artemis server resources. */ -public class JMSManagementHelper -{ - private static org.apache.activemq.artemis.api.core.Message getCoreMessage(final Message jmsMessage) - { - if (jmsMessage instanceof ActiveMQMessage == false) - { - throw new IllegalArgumentException("Cannot send a foreign message as a management message " + jmsMessage.getClass() - .getName()); +public class JMSManagementHelper { + + private static org.apache.activemq.artemis.api.core.Message getCoreMessage(final Message jmsMessage) { + if (jmsMessage instanceof ActiveMQMessage == false) { + throw new IllegalArgumentException("Cannot send a foreign message as a management message " + jmsMessage.getClass().getName()); } - return ((ActiveMQMessage)jmsMessage).getCoreMessage(); + return ((ActiveMQMessage) jmsMessage).getCoreMessage(); } /** * Stores a resource attribute in a JMS message to retrieve the value from the server resource. * - * @param message JMS message + * @param message JMS message * @param resourceName the name of the resource - * @param attribute the name of the attribute + * @param attribute the name of the attribute * @throws JMSException if an exception occurs while putting the information in the message - * * @see org.apache.activemq.artemis.api.core.management.ResourceNames */ - public static void putAttribute(final Message message, final String resourceName, final String attribute) throws JMSException - { + public static void putAttribute(final Message message, + final String resourceName, + final String attribute) throws JMSException { ManagementHelper.putAttribute(JMSManagementHelper.getCoreMessage(message), resourceName, attribute); } /** * Stores an operation invocation in a JMS message to invoke the corresponding operation the value from the server resource. * - * @param message JMS message - * @param resourceName the name of the resource + * @param message JMS message + * @param resourceName the name of the resource * @param operationName the name of the operation to invoke on the resource * @throws JMSException if an exception occurs while putting the information in the message - * * @see org.apache.activemq.artemis.api.core.management.ResourceNames */ public static void putOperationInvocation(final Message message, final String resourceName, - final String operationName) throws JMSException - { - try - { - ManagementHelper.putOperationInvocation(JMSManagementHelper.getCoreMessage(message), - resourceName, - operationName); + final String operationName) throws JMSException { + try { + ManagementHelper.putOperationInvocation(JMSManagementHelper.getCoreMessage(message), resourceName, operationName); } - catch (Exception e) - { + catch (Exception e) { throw JMSManagementHelper.convertFromException(e); } } - private static JMSException convertFromException(final Exception e) - { + private static JMSException convertFromException(final Exception e) { JMSException jmse = new JMSException(e.getMessage()); jmse.initCause(e); @@ -91,28 +81,21 @@ public class JMSManagementHelper /** * Stores an operation invocation in a JMS message to invoke the corresponding operation the value from the server resource. * - * @param message JMS message - * @param resourceName the name of the server resource + * @param message JMS message + * @param resourceName the name of the server resource * @param operationName the name of the operation to invoke on the server resource - * @param parameters the parameters to use to invoke the server resource + * @param parameters the parameters to use to invoke the server resource * @throws JMSException if an exception occurs while putting the information in the message - * * @see org.apache.activemq.artemis.api.core.management.ResourceNames */ public static void putOperationInvocation(final Message message, final String resourceName, final String operationName, - final Object... parameters) throws JMSException - { - try - { - ManagementHelper.putOperationInvocation(JMSManagementHelper.getCoreMessage(message), - resourceName, - operationName, - parameters); + final Object... parameters) throws JMSException { + try { + ManagementHelper.putOperationInvocation(JMSManagementHelper.getCoreMessage(message), resourceName, operationName, parameters); } - catch (Exception e) - { + catch (Exception e) { throw JMSManagementHelper.convertFromException(e); } } @@ -120,24 +103,21 @@ public class JMSManagementHelper /** * Returns whether the JMS message corresponds to the result of a management operation invocation. */ - public static boolean isOperationResult(final Message message) throws JMSException - { + public static boolean isOperationResult(final Message message) throws JMSException { return ManagementHelper.isOperationResult(JMSManagementHelper.getCoreMessage(message)); } /** * Returns whether the JMS message corresponds to the result of a management attribute value. */ - public static boolean isAttributesResult(final Message message) throws JMSException - { + public static boolean isAttributesResult(final Message message) throws JMSException { return ManagementHelper.isAttributesResult(JMSManagementHelper.getCoreMessage(message)); } /** * Returns whether the invocation of the management operation on the server resource succeeded. */ - public static boolean hasOperationSucceeded(final Message message) throws JMSException - { + public static boolean hasOperationSucceeded(final Message message) throws JMSException { return ManagementHelper.hasOperationSucceeded(JMSManagementHelper.getCoreMessage(message)); } @@ -147,8 +127,7 @@ public class JMSManagementHelper * If an error occurred on the server, {@link #hasOperationSucceeded(Message)} will return {@code false}. * and the result will be a String corresponding to the server exception. */ - public static Object[] getResults(final Message message) throws Exception - { + public static Object[] getResults(final Message message) throws Exception { return ManagementHelper.getResults(JMSManagementHelper.getCoreMessage(message)); } @@ -158,13 +137,11 @@ public class JMSManagementHelper * If an error occurred on the server, {@link #hasOperationSucceeded(Message)} will return {@code false}. * and the result will be a String corresponding to the server exception. */ - public static Object getResult(final Message message) throws Exception - { + public static Object getResult(final Message message) throws Exception { return ManagementHelper.getResult(JMSManagementHelper.getCoreMessage(message)); } - private JMSManagementHelper() - { + private JMSManagementHelper() { // Utility class } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/JMSQueueControl.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/JMSQueueControl.java index d12372f493..43e20ab5d0 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/JMSQueueControl.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/JMSQueueControl.java @@ -26,8 +26,7 @@ import org.apache.activemq.artemis.api.core.management.Parameter; /** * A JMSQueueControl is used to manage a JMS queue. */ -public interface JMSQueueControl extends DestinationControl -{ +public interface JMSQueueControl extends DestinationControl { // Attributes ---------------------------------------------------- /** @@ -168,7 +167,6 @@ public interface JMSQueueControl extends DestinationControl * Changes the message's priority corresponding to the specified message ID to the specified priority. * * @param newPriority between 0 and 9 inclusive. - * * @return {@code true} if the message priority was changed */ @Operation(desc = "Change the priority of the message corresponding to the given messageID", impact = MBeanOperationInfo.ACTION) @@ -185,6 +183,7 @@ public interface JMSQueueControl extends DestinationControl @Operation(desc = "Change the priority of the messages corresponding to the given filter", impact = MBeanOperationInfo.ACTION) int changeMessagesPriority(@Parameter(name = "filter", desc = "A message filter") String filter, @Parameter(name = "newPriority", desc = "the new priority (between 0 and 9)") int newPriority) throws Exception; + /** * Moves the message corresponding to the specified message ID to the specified other queue. * @@ -194,7 +193,6 @@ public interface JMSQueueControl extends DestinationControl boolean moveMessage(@Parameter(name = "messageID", desc = "A message ID") String messageID, @Parameter(name = "otherQueueName", desc = "The name of the queue to move the message to") String otherQueueName) throws Exception; - /** * Moves the message corresponding to the specified message ID to the specified other queue. * diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/JMSServerControl.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/JMSServerControl.java index 7cf75190e6..2fd03fc9dd 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/JMSServerControl.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/JMSServerControl.java @@ -24,8 +24,7 @@ import org.apache.activemq.artemis.api.core.management.Parameter; /** * A JMSSserverControl is used to manage ActiveMQ Artemis JMS server. */ -public interface JMSServerControl -{ +public interface JMSServerControl { // Attributes ---------------------------------------------------- /** @@ -107,7 +106,8 @@ public interface JMSServerControl * @return {@code true} if the queue was destroyed, {@code false} else */ @Operation(desc = "Destroy a JMS Queue", impact = MBeanOperationInfo.ACTION) - boolean destroyQueue(@Parameter(name = "name", desc = "Name of the queue to destroy") String name, @Parameter(name = "removeConsumers", desc = "disconnect any consumers connected to this queue") boolean removeConsumers) throws Exception; + boolean destroyQueue(@Parameter(name = "name", desc = "Name of the queue to destroy") String name, + @Parameter(name = "removeConsumers", desc = "disconnect any consumers connected to this queue") boolean removeConsumers) throws Exception; /** * Creates a JMS Topic. @@ -132,7 +132,8 @@ public interface JMSServerControl * @return {@code true} if the topic was destroyed, {@code false} else */ @Operation(desc = "Destroy a JMS Topic", impact = MBeanOperationInfo.ACTION) - boolean destroyTopic(@Parameter(name = "name", desc = "Name of the topic to destroy") String name, @Parameter(name = "removeConsumers", desc = "disconnect any consumers connected to this queue") boolean removeConsumers) throws Exception; + boolean destroyTopic(@Parameter(name = "name", desc = "Name of the topic to destroy") String name, + @Parameter(name = "removeConsumers", desc = "disconnect any consumers connected to this queue") boolean removeConsumers) throws Exception; /** * Destroys a JMS Topic with the specified name. @@ -208,7 +209,6 @@ public interface JMSServerControl @Parameter(name = "failoverOnInitialConnection", desc = "failoverOnInitialConnection") boolean failoverOnInitialConnection, @Parameter(name = "groupId", desc = "groupId") String groupId) throws Exception; - @Operation(desc = "Create a JMS ConnectionFactory", impact = MBeanOperationInfo.ACTION) void createConnectionFactory(@Parameter(name = "name") String name, @Parameter(name = "ha") boolean ha, @@ -246,7 +246,6 @@ public interface JMSServerControl @Parameter(name = "failoverOnInitialConnection", desc = "failoverOnInitialConnection") boolean failoverOnInitialConnection, @Parameter(name = "groupId", desc = "groupId") String groupId) throws Exception; - @Operation(desc = "Destroy a JMS ConnectionFactory", impact = MBeanOperationInfo.ACTION) void destroyConnectionFactory(@Parameter(name = "name", desc = "Name of the ConnectionFactory to destroy") String name) throws Exception; @@ -358,7 +357,6 @@ public interface JMSServerControl @Operation(desc = "List all the prepared transaction, sorted by date, oldest first, with details, in HTML format", impact = MBeanOperationInfo.INFO) String listPreparedTransactionDetailsAsHTML() throws Exception; - /** * List all the prepared transaction, sorted by date, * oldest first, with details, in HTML format diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/JMSSessionInfo.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/JMSSessionInfo.java index f1faf37372..56829c9875 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/JMSSessionInfo.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/JMSSessionInfo.java @@ -20,40 +20,34 @@ import org.apache.activemq.artemis.utils.json.JSONArray; import org.apache.activemq.artemis.utils.json.JSONException; import org.apache.activemq.artemis.utils.json.JSONObject; -public class JMSSessionInfo -{ +public class JMSSessionInfo { + private final String sessionID; private final long creationTime; - public JMSSessionInfo(String sessionID, long creationTime) - { + public JMSSessionInfo(String sessionID, long creationTime) { this.sessionID = sessionID; this.creationTime = creationTime; } - public static JMSSessionInfo[] from(final String jsonString) throws JSONException - { + public static JMSSessionInfo[] from(final String jsonString) throws JSONException { JSONArray array = new JSONArray(jsonString); JMSSessionInfo[] infos = new JMSSessionInfo[array.length()]; - for (int i = 0; i < array.length(); i++) - { + for (int i = 0; i < array.length(); i++) { JSONObject obj = array.getJSONObject(i); - JMSSessionInfo info = new JMSSessionInfo(obj.getString("sessionID"), - obj.getLong("creationTime")); + JMSSessionInfo info = new JMSSessionInfo(obj.getString("sessionID"), obj.getLong("creationTime")); infos[i] = info; } return infos; } - public String getSessionID() - { + public String getSessionID() { return sessionID; } - public long getCreationTime() - { + public long getCreationTime() { return creationTime; } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/SubscriptionInfo.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/SubscriptionInfo.java index cf83b44900..66d04b6a5d 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/SubscriptionInfo.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/SubscriptionInfo.java @@ -23,8 +23,8 @@ import org.apache.activemq.artemis.utils.json.JSONObject; * Helper class to create Java Objects from the * JSON serialization returned by {@link TopicControl#listAllSubscriptionsAsJSON()} and related methods. */ -public class SubscriptionInfo -{ +public class SubscriptionInfo { + private final String queueName; private final String clientID; @@ -45,20 +45,12 @@ public class SubscriptionInfo * Returns an array of SubscriptionInfo corresponding to the JSON serialization returned * by {@link TopicControl#listAllSubscriptionsAsJSON()} and related methods. */ - public static SubscriptionInfo[] from(final String jsonString) throws Exception - { + public static SubscriptionInfo[] from(final String jsonString) throws Exception { JSONArray array = new JSONArray(jsonString); SubscriptionInfo[] infos = new SubscriptionInfo[array.length()]; - for (int i = 0; i < array.length(); i++) - { + for (int i = 0; i < array.length(); i++) { JSONObject sub = array.getJSONObject(i); - SubscriptionInfo info = new SubscriptionInfo(sub.getString("queueName"), - sub.optString("clientID", null), - sub.optString("name", null), - sub.getBoolean("durable"), - sub.optString("selector", null), - sub.getInt("messageCount"), - sub.getInt("deliveringCount")); + SubscriptionInfo info = new SubscriptionInfo(sub.getString("queueName"), sub.optString("clientID", null), sub.optString("name", null), sub.getBoolean("durable"), sub.optString("selector", null), sub.getInt("messageCount"), sub.getInt("deliveringCount")); infos[i] = info; } @@ -73,8 +65,7 @@ public class SubscriptionInfo final boolean durable, final String selector, final int messageCount, - final int deliveringCount) - { + final int deliveringCount) { this.queueName = queueName; this.clientID = clientID; this.name = name; @@ -89,56 +80,49 @@ public class SubscriptionInfo /** * Returns the name of the ActiveMQ Artemis core queue corresponding to this subscription. */ - public String getQueueName() - { + public String getQueueName() { return queueName; } /** * Returns the client ID of this subscription or {@code null}. */ - public String getClientID() - { + public String getClientID() { return clientID; } /** * Returns the name of this subscription. */ - public String getName() - { + public String getName() { return name; } /** * Returns whether this subscription is durable. */ - public boolean isDurable() - { + public boolean isDurable() { return durable; } /** * Returns the JMS message selector associated to this subscription. */ - public String getSelector() - { + public String getSelector() { return selector; } /** * Returns the number of messages currently held by this subscription. */ - public int getMessageCount() - { + public int getMessageCount() { return messageCount; } /** * Returns the number of messages currently delivered to this subscription. */ - public int getDeliveringCount() - { + public int getDeliveringCount() { return deliveringCount; } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/TopicControl.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/TopicControl.java index 86df7e7745..f70c3218b7 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/TopicControl.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/api/jms/management/TopicControl.java @@ -26,8 +26,7 @@ import org.apache.activemq.artemis.api.core.management.Parameter; /** * A TopicControl is used to manage a JMS Topic. */ -public interface TopicControl extends DestinationControl -{ +public interface TopicControl extends DestinationControl { /** * Returns the number of (durable and non-durable) subscribers for this topic. @@ -66,8 +65,6 @@ public interface TopicControl extends DestinationControl @Operation(desc = "Adds the queue to another Registry binding") void addBinding(@Parameter(name = "binding", desc = "the name of the binding for Registry") String binding) throws Exception; - - // Operations ---------------------------------------------------- /** @@ -133,8 +130,8 @@ public interface TopicControl extends DestinationControl */ @Operation(desc = "Count the number of messages matching the filter for the given subscription") int countMessagesForSubscription(@Parameter(name = "clientID", desc = "the client ID") String clientID, - @Parameter(name = "subscriptionName", desc = "the name of the durable subscription") String subscriptionName, - @Parameter(name = "filter", desc = "a JMS filter (can be empty)") String filter) throws Exception; + @Parameter(name = "subscriptionName", desc = "the name of the durable subscription") String subscriptionName, + @Parameter(name = "filter", desc = "a JMS filter (can be empty)") String filter) throws Exception; /** * Drops the subscription specified by the specified client ID and subscription name. diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQBytesMessage.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQBytesMessage.java index 6717c8fb03..72770a49d1 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQBytesMessage.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQBytesMessage.java @@ -56,8 +56,8 @@ import static org.apache.activemq.artemis.reader.BytesMessageUtil.bytesWriteUTF; /** * ActiveMQ Artemis implementation of a JMS {@link BytesMessage}. */ -public class ActiveMQBytesMessage extends ActiveMQMessage implements BytesMessage -{ +public class ActiveMQBytesMessage extends ActiveMQMessage implements BytesMessage { + // Static ------------------------------------------------------- public static final byte TYPE = Message.BYTES_TYPE; @@ -70,32 +70,28 @@ public class ActiveMQBytesMessage extends ActiveMQMessage implements BytesMessag /** * This constructor is used to construct messages prior to sending */ - protected ActiveMQBytesMessage(final ClientSession session) - { + protected ActiveMQBytesMessage(final ClientSession session) { super(ActiveMQBytesMessage.TYPE, session); } /** * Constructor on receipt at client side */ - protected ActiveMQBytesMessage(final ClientMessage message, final ClientSession session) - { + protected ActiveMQBytesMessage(final ClientMessage message, final ClientSession session) { super(message, session); } /** * Foreign message constructor */ - public ActiveMQBytesMessage(final BytesMessage foreign, final ClientSession session) throws JMSException - { + public ActiveMQBytesMessage(final BytesMessage foreign, final ClientSession session) throws JMSException { super(foreign, ActiveMQBytesMessage.TYPE, session); foreign.reset(); byte[] buffer = new byte[1024]; int n = foreign.readBytes(buffer); - while (n != -1) - { + while (n != -1) { writeBytes(buffer, 0, n); n = foreign.readBytes(buffer); } @@ -103,149 +99,115 @@ public class ActiveMQBytesMessage extends ActiveMQMessage implements BytesMessag // BytesMessage implementation ----------------------------------- - public boolean readBoolean() throws JMSException - { + public boolean readBoolean() throws JMSException { checkRead(); - try - { + try { return bytesReadBoolean(message); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public byte readByte() throws JMSException - { + public byte readByte() throws JMSException { checkRead(); - try - { + try { return bytesReadByte(message); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public int readUnsignedByte() throws JMSException - { + public int readUnsignedByte() throws JMSException { checkRead(); - try - { + try { return bytesReadUnsignedByte(message); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public short readShort() throws JMSException - { + public short readShort() throws JMSException { checkRead(); - try - { + try { return bytesReadShort(message); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public int readUnsignedShort() throws JMSException - { + public int readUnsignedShort() throws JMSException { checkRead(); - try - { + try { return bytesReadUnsignedShort(message); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public char readChar() throws JMSException - { + public char readChar() throws JMSException { checkRead(); - try - { + try { return bytesReadChar(message); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public int readInt() throws JMSException - { + public int readInt() throws JMSException { checkRead(); - try - { + try { return bytesReadInt(message); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public long readLong() throws JMSException - { + public long readLong() throws JMSException { checkRead(); - try - { + try { return bytesReadLong(message); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public float readFloat() throws JMSException - { + public float readFloat() throws JMSException { checkRead(); - try - { + try { return bytesReadFloat(message); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public double readDouble() throws JMSException - { + public double readDouble() throws JMSException { checkRead(); - try - { + try { return bytesReadDouble(message); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public String readUTF() throws JMSException - { + public String readUTF() throws JMSException { checkRead(); - try - { + try { return bytesReadUTF(message); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } - catch (Exception e) - { + catch (Exception e) { JMSException je = new JMSException("Failed to get UTF"); je.setLinkedException(e); je.initCause(e); @@ -253,76 +215,63 @@ public class ActiveMQBytesMessage extends ActiveMQMessage implements BytesMessag } } - public int readBytes(final byte[] value) throws JMSException - { + public int readBytes(final byte[] value) throws JMSException { checkRead(); return bytesReadBytes(message, value); } - public int readBytes(final byte[] value, final int length) throws JMSException - { + public int readBytes(final byte[] value, final int length) throws JMSException { checkRead(); return bytesReadBytes(message, value, length); } - public void writeBoolean(final boolean value) throws JMSException - { + public void writeBoolean(final boolean value) throws JMSException { checkWrite(); bytesWriteBoolean(message, value); } - public void writeByte(final byte value) throws JMSException - { + public void writeByte(final byte value) throws JMSException { checkWrite(); bytesWriteByte(message, value); } - public void writeShort(final short value) throws JMSException - { + public void writeShort(final short value) throws JMSException { checkWrite(); bytesWriteShort(message, value); } - public void writeChar(final char value) throws JMSException - { + public void writeChar(final char value) throws JMSException { checkWrite(); bytesWriteChar(message, value); } - public void writeInt(final int value) throws JMSException - { + public void writeInt(final int value) throws JMSException { checkWrite(); bytesWriteInt(message, value); } - public void writeLong(final long value) throws JMSException - { + public void writeLong(final long value) throws JMSException { checkWrite(); bytesWriteLong(message, value); } - public void writeFloat(final float value) throws JMSException - { + public void writeFloat(final float value) throws JMSException { checkWrite(); bytesWriteFloat(message, value); } - public void writeDouble(final double value) throws JMSException - { + public void writeDouble(final double value) throws JMSException { checkWrite(); bytesWriteDouble(message, value); } - public void writeUTF(final String value) throws JMSException - { + public void writeUTF(final String value) throws JMSException { checkWrite(); - try - { + try { bytesWriteUTF(message, value); } - catch (Exception e) - { + catch (Exception e) { JMSException je = new JMSException("Failed to write UTF"); je.setLinkedException(e); je.initCause(e); @@ -331,31 +280,25 @@ public class ActiveMQBytesMessage extends ActiveMQMessage implements BytesMessag } - public void writeBytes(final byte[] value) throws JMSException - { + public void writeBytes(final byte[] value) throws JMSException { checkWrite(); bytesWriteBytes(message, value); } - public void writeBytes(final byte[] value, final int offset, final int length) throws JMSException - { + public void writeBytes(final byte[] value, final int offset, final int length) throws JMSException { checkWrite(); bytesWriteBytes(message, value, offset, length); } - public void writeObject(final Object value) throws JMSException - { + public void writeObject(final Object value) throws JMSException { checkWrite(); - if (!bytesWriteObject(message, value)) - { + if (!bytesWriteObject(message, value)) { throw new MessageFormatException("Invalid object for properties"); } } - public void reset() throws JMSException - { - if (!readOnly) - { + public void reset() throws JMSException { + if (!readOnly) { readOnly = true; bodyLength = message.getBodySize(); @@ -365,70 +308,59 @@ public class ActiveMQBytesMessage extends ActiveMQMessage implements BytesMessag } @Override - public void doBeforeReceive() throws ActiveMQException - { + public void doBeforeReceive() throws ActiveMQException { bodyLength = message.getBodySize(); } // ActiveMQRAMessage overrides ---------------------------------------- @Override - public void clearBody() throws JMSException - { + public void clearBody() throws JMSException { super.clearBody(); - try - { + try { getBuffer().clear(); } - catch (RuntimeException e) - { + catch (RuntimeException e) { JMSException e2 = new JMSException(e.getMessage()); e2.initCause(e); throw e2; } } - public long getBodyLength() throws JMSException - { + public long getBodyLength() throws JMSException { checkRead(); return bodyLength; } @Override - public void doBeforeSend() throws Exception - { + public void doBeforeSend() throws Exception { reset(); } // Public -------------------------------------------------------- @Override - public byte getType() - { + public byte getType() { return ActiveMQBytesMessage.TYPE; } - private ActiveMQBuffer getBuffer() - { + private ActiveMQBuffer getBuffer() { return message.getBodyBuffer(); } @Override - public boolean isBodyAssignableTo(@SuppressWarnings("rawtypes") - Class c) - { + public boolean isBodyAssignableTo(@SuppressWarnings("rawtypes") Class c) { return c.isAssignableFrom(byte[].class); } @Override - protected T getBodyInternal(Class c) - { + protected T getBodyInternal(Class c) { if (bodyLength == 0) return null; byte[] dst = new byte[bodyLength]; message.getBodyBuffer().getBytes(MessageImpl.BODY_OFFSET, dst); - return (T)dst; + return (T) dst; } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQConnection.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQConnection.java index f720abf8c7..a1184b22ab 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQConnection.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQConnection.java @@ -58,8 +58,8 @@ import org.apache.activemq.artemis.utils.VersionLoader; * The flat implementation of {@link TopicConnection} and {@link QueueConnection} is per design, * following the common usage of these as one flat API in JMS 1.1. */ -public class ActiveMQConnection extends ActiveMQConnectionForContextImpl implements TopicConnection, QueueConnection -{ +public class ActiveMQConnection extends ActiveMQConnectionForContextImpl implements TopicConnection, QueueConnection { + // Constants ------------------------------------------------------------------------------------ public static final int TYPE_GENERIC_CONNECTION = 0; @@ -127,10 +127,13 @@ public class ActiveMQConnection extends ActiveMQConnectionForContextImpl impleme // Constructors --------------------------------------------------------------------------------- - public ActiveMQConnection(final String username, final String password, final int connectionType, - final String clientID, final int dupsOKBatchSize, final int transactionBatchSize, - final ClientSessionFactory sessionFactory) - { + public ActiveMQConnection(final String username, + final String password, + final int connectionType, + final String clientID, + final int dupsOKBatchSize, + final int transactionBatchSize, + final ClientSessionFactory sessionFactory) { this.username = username; this.password = password; @@ -160,8 +163,7 @@ public class ActiveMQConnection extends ActiveMQConnectionForContextImpl impleme * For that reason we have this method to force that nonXASession, since the JMS Javadoc * mandates createSession to return a XASession. */ - public Session createNonXASession(final boolean transacted, final int acknowledgeMode) throws JMSException - { + public Session createNonXASession(final boolean transacted, final int acknowledgeMode) throws JMSException { checkClosed(); return createSessionInternal(false, transacted, acknowledgeMode, ActiveMQConnection.TYPE_GENERIC_CONNECTION); @@ -175,8 +177,7 @@ public class ActiveMQConnection extends ActiveMQConnectionForContextImpl impleme * For that reason we have this method to force that nonXASession, since the JMS Javadoc * mandates createSession to return a XASession. */ - public Session createNonXATopicSession(final boolean transacted, final int acknowledgeMode) throws JMSException - { + public Session createNonXATopicSession(final boolean transacted, final int acknowledgeMode) throws JMSException { checkClosed(); return createSessionInternal(false, transacted, acknowledgeMode, ActiveMQConnection.TYPE_TOPIC_CONNECTION); @@ -190,63 +191,51 @@ public class ActiveMQConnection extends ActiveMQConnectionForContextImpl impleme * For that reason we have this method to force that nonXASession, since the JMS Javadoc * mandates createSession to return a XASession. */ - public Session createNonXAQueueSession(final boolean transacted, final int acknowledgeMode) throws JMSException - { + public Session createNonXAQueueSession(final boolean transacted, final int acknowledgeMode) throws JMSException { checkClosed(); return createSessionInternal(false, transacted, acknowledgeMode, ActiveMQConnection.TYPE_QUEUE_CONNECTION); } - // Connection implementation -------------------------------------------------------------------- - public synchronized Session createSession(final boolean transacted, final int acknowledgeMode) throws JMSException - { + public synchronized Session createSession(final boolean transacted, final int acknowledgeMode) throws JMSException { checkClosed(); return createSessionInternal(false, transacted, checkAck(transacted, acknowledgeMode), ActiveMQConnection.TYPE_GENERIC_CONNECTION); } - public String getClientID() throws JMSException - { + public String getClientID() throws JMSException { checkClosed(); return clientID; } - public void setClientID(final String clientID) throws JMSException - { + public void setClientID(final String clientID) throws JMSException { checkClosed(); - if (this.clientID != null) - { + if (this.clientID != null) { throw new IllegalStateException("Client id has already been set"); } - if (!justCreated) - { + if (!justCreated) { throw new IllegalStateException("setClientID can only be called directly after the connection is created"); } - try - { + try { initialSession.addUniqueMetaData(ClientSession.JMS_SESSION_CLIENT_ID_PROPERTY, clientID); } - catch (ActiveMQException e) - { - if (e.getType() == ActiveMQExceptionType.DUPLICATE_METADATA) - { + catch (ActiveMQException e) { + if (e.getType() == ActiveMQExceptionType.DUPLICATE_METADATA) { throw new InvalidClientIDException("clientID=" + clientID + " was already set into another connection"); } } this.clientID = clientID; - try - { + try { this.addSessionMetaData(initialSession); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { JMSException ex = new JMSException("Internal error setting metadata jms-client-id"); ex.setLinkedException(e); ex.initCause(e); @@ -256,22 +245,19 @@ public class ActiveMQConnection extends ActiveMQConnectionForContextImpl impleme justCreated = false; } - public ConnectionMetaData getMetaData() throws JMSException - { + public ConnectionMetaData getMetaData() throws JMSException { checkClosed(); justCreated = false; - if (metaData == null) - { + if (metaData == null) { metaData = new ActiveMQConnectionMetaData(thisVersion); } return metaData; } - public ExceptionListener getExceptionListener() throws JMSException - { + public ExceptionListener getExceptionListener() throws JMSException { checkClosed(); justCreated = false; @@ -279,20 +265,17 @@ public class ActiveMQConnection extends ActiveMQConnectionForContextImpl impleme return exceptionListener; } - public void setExceptionListener(final ExceptionListener listener) throws JMSException - { + public void setExceptionListener(final ExceptionListener listener) throws JMSException { checkClosed(); exceptionListener = listener; justCreated = false; } - public synchronized void start() throws JMSException - { + public synchronized void start() throws JMSException { checkClosed(); - for (ActiveMQSession session : sessions) - { + for (ActiveMQSession session : sessions) { session.start(); } @@ -300,13 +283,10 @@ public class ActiveMQConnection extends ActiveMQConnectionForContextImpl impleme started = true; } - public synchronized void signalStopToAllSessions() - { - for (ActiveMQSession session : sessions) - { + public synchronized void signalStopToAllSessions() { + for (ActiveMQSession session : sessions) { ClientSession coreSession = session.getCoreSession(); - if (coreSession instanceof ClientSessionInternal) - { + if (coreSession instanceof ClientSessionInternal) { ClientSessionInternal internalSession = (ClientSessionInternal) coreSession; internalSession.setStopSignal(); } @@ -314,14 +294,12 @@ public class ActiveMQConnection extends ActiveMQConnectionForContextImpl impleme } - public synchronized void stop() throws JMSException - { + public synchronized void stop() throws JMSException { threadAwareContext.assertNotMessageListenerThread(); checkClosed(); - for (ActiveMQSession session : sessions) - { + for (ActiveMQSession session : sessions) { session.stop(); } @@ -329,67 +307,54 @@ public class ActiveMQConnection extends ActiveMQConnectionForContextImpl impleme started = false; } - public final synchronized void close() throws JMSException - { + public final synchronized void close() throws JMSException { threadAwareContext.assertNotCompletionListenerThread(); threadAwareContext.assertNotMessageListenerThread(); - if (closed) - { + if (closed) { return; } sessionFactory.close(); - try - { - for (ActiveMQSession session : new HashSet(sessions)) - { + try { + for (ActiveMQSession session : new HashSet(sessions)) { session.close(); } - try - { - if (!tempQueues.isEmpty()) - { + try { + if (!tempQueues.isEmpty()) { // Remove any temporary queues - for (SimpleString queueName : tempQueues) - { - if (!initialSession.isClosed()) - { - try - { + for (SimpleString queueName : tempQueues) { + if (!initialSession.isClosed()) { + try { initialSession.deleteQueue(queueName); } - catch (ActiveMQException ignore) - { + catch (ActiveMQException ignore) { // Exception on deleting queue shouldn't prevent close from completing } } } } } - finally - { - if (initialSession != null) - { + finally { + if (initialSession != null) { initialSession.close(); } } closed = true; } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } - public ConnectionConsumer - createConnectionConsumer(final Destination destination, final String messageSelector, - final ServerSessionPool sessionPool, final int maxMessages) throws JMSException - { + public ConnectionConsumer createConnectionConsumer(final Destination destination, + final String messageSelector, + final ServerSessionPool sessionPool, + final int maxMessages) throws JMSException { checkClosed(); checkTempQueues(destination); @@ -398,26 +363,23 @@ public class ActiveMQConnection extends ActiveMQConnectionForContextImpl impleme return null; } - private void checkTempQueues(Destination destination) throws JMSException - { + private void checkTempQueues(Destination destination) throws JMSException { ActiveMQDestination jbdest = (ActiveMQDestination) destination; - if (jbdest.isTemporary() && !containsTemporaryQueue(jbdest.getSimpleAddress())) - { + if (jbdest.isTemporary() && !containsTemporaryQueue(jbdest.getSimpleAddress())) { throw new JMSException("Can not create consumer for temporary destination " + destination + " from another JMS connection"); } } - public ConnectionConsumer - createDurableConnectionConsumer(final Topic topic, final String subscriptionName, - final String messageSelector, final ServerSessionPool sessionPool, - final int maxMessages) throws JMSException - { + public ConnectionConsumer createDurableConnectionConsumer(final Topic topic, + final String subscriptionName, + final String messageSelector, + final ServerSessionPool sessionPool, + final int maxMessages) throws JMSException { checkClosed(); // As spec. section 4.11 - if (connectionType == ActiveMQConnection.TYPE_QUEUE_CONNECTION) - { + if (connectionType == ActiveMQConnection.TYPE_QUEUE_CONNECTION) { String msg = "Cannot create a durable connection consumer on a QueueConnection"; throw new javax.jms.IllegalStateException(msg); } @@ -427,24 +389,21 @@ public class ActiveMQConnection extends ActiveMQConnectionForContextImpl impleme } @Override - public Session createSession(int sessionMode) throws JMSException - { + public Session createSession(int sessionMode) throws JMSException { checkClosed(); return createSessionInternal(false, sessionMode == Session.SESSION_TRANSACTED, sessionMode, ActiveMQSession.TYPE_GENERIC_SESSION); } @Override - public Session createSession() throws JMSException - { + public Session createSession() throws JMSException { checkClosed(); return createSessionInternal(false, false, Session.AUTO_ACKNOWLEDGE, ActiveMQSession.TYPE_GENERIC_SESSION); } // QueueConnection implementation --------------------------------------------------------------- - public QueueSession createQueueSession(final boolean transacted, int acknowledgeMode) throws JMSException - { + public QueueSession createQueueSession(final boolean transacted, int acknowledgeMode) throws JMSException { checkClosed(); return createSessionInternal(false, transacted, checkAck(transacted, acknowledgeMode), ActiveMQSession.TYPE_QUEUE_SESSION); } @@ -453,20 +412,18 @@ public class ActiveMQConnection extends ActiveMQConnectionForContextImpl impleme * I'm keeping this as static as the same check will be done within RA. * This is to conform with TCK Tests where we must return ackMode exactly as they want if transacted=false */ - public static int checkAck(boolean transacted, int acknowledgeMode) - { - if (!transacted && acknowledgeMode == Session.SESSION_TRANSACTED) - { + public static int checkAck(boolean transacted, int acknowledgeMode) { + if (!transacted && acknowledgeMode == Session.SESSION_TRANSACTED) { return Session.AUTO_ACKNOWLEDGE; } return acknowledgeMode; } - public ConnectionConsumer - createConnectionConsumer(final Queue queue, final String messageSelector, - final ServerSessionPool sessionPool, final int maxMessages) throws JMSException - { + public ConnectionConsumer createConnectionConsumer(final Queue queue, + final String messageSelector, + final ServerSessionPool sessionPool, + final int maxMessages) throws JMSException { checkClosed(); checkTempQueues(queue); return null; @@ -474,30 +431,35 @@ public class ActiveMQConnection extends ActiveMQConnectionForContextImpl impleme // TopicConnection implementation --------------------------------------------------------------- - public TopicSession createTopicSession(final boolean transacted, final int acknowledgeMode) throws JMSException - { + public TopicSession createTopicSession(final boolean transacted, final int acknowledgeMode) throws JMSException { checkClosed(); return createSessionInternal(false, transacted, checkAck(transacted, acknowledgeMode), ActiveMQSession.TYPE_TOPIC_SESSION); } - public ConnectionConsumer - createConnectionConsumer(final Topic topic, final String messageSelector, - final ServerSessionPool sessionPool, final int maxMessages) throws JMSException - { + public ConnectionConsumer createConnectionConsumer(final Topic topic, + final String messageSelector, + final ServerSessionPool sessionPool, + final int maxMessages) throws JMSException { checkClosed(); checkTempQueues(topic); return null; } @Override - public ConnectionConsumer createSharedConnectionConsumer(Topic topic, String subscriptionName, String messageSelector, ServerSessionPool sessionPool, int maxMessages) throws JMSException - { + public ConnectionConsumer createSharedConnectionConsumer(Topic topic, + String subscriptionName, + String messageSelector, + ServerSessionPool sessionPool, + int maxMessages) throws JMSException { return null; // we offer RA } @Override - public ConnectionConsumer createSharedDurableConnectionConsumer(Topic topic, String subscriptionName, String messageSelector, ServerSessionPool sessionPool, int maxMessages) throws JMSException - { + public ConnectionConsumer createSharedDurableConnectionConsumer(Topic topic, + String subscriptionName, + String messageSelector, + ServerSessionPool sessionPool, + int maxMessages) throws JMSException { return null; // we offer RA } @@ -509,8 +471,7 @@ public class ActiveMQConnection extends ActiveMQConnectionForContextImpl impleme * @param listener the listener to add * @throws JMSException */ - public void setFailoverListener(final FailoverEventListener listener) throws JMSException - { + public void setFailoverListener(final FailoverEventListener listener) throws JMSException { checkClosed(); justCreated = false; @@ -523,8 +484,7 @@ public class ActiveMQConnection extends ActiveMQConnectionForContextImpl impleme * @return {@link FailoverEventListener} the current failover event listener for this connection * @throws JMSException */ - public FailoverEventListener getFailoverListener() throws JMSException - { + public FailoverEventListener getFailoverListener() throws JMSException { checkClosed(); justCreated = false; @@ -532,54 +492,44 @@ public class ActiveMQConnection extends ActiveMQConnectionForContextImpl impleme return failoverEventListener; } - public void addTemporaryQueue(final SimpleString queueAddress) - { + public void addTemporaryQueue(final SimpleString queueAddress) { tempQueues.add(queueAddress); knownDestinations.add(queueAddress); } - public void removeTemporaryQueue(final SimpleString queueAddress) - { + public void removeTemporaryQueue(final SimpleString queueAddress) { tempQueues.remove(queueAddress); } - public void addKnownDestination(final SimpleString address) - { + public void addKnownDestination(final SimpleString address) { knownDestinations.add(address); } - public boolean containsKnownDestination(final SimpleString address) - { + public boolean containsKnownDestination(final SimpleString address) { return knownDestinations.contains(address); } - public boolean containsTemporaryQueue(final SimpleString queueAddress) - { + public boolean containsTemporaryQueue(final SimpleString queueAddress) { return tempQueues.contains(queueAddress); } - public boolean hasNoLocal() - { + public boolean hasNoLocal() { return hasNoLocal; } - public void setHasNoLocal() - { + public void setHasNoLocal() { hasNoLocal = true; } - public SimpleString getUID() - { + public SimpleString getUID() { return uid; } - public void removeSession(final ActiveMQSession session) - { + public void removeSession(final ActiveMQSession session) { sessions.remove(session); } - public ClientSession getInitialSession() - { + public ClientSession getInitialSession() { return initialSession; } @@ -590,70 +540,48 @@ public class ActiveMQConnection extends ActiveMQConnectionForContextImpl impleme // In case the user forgets to close the connection manually @Override - protected final void finalize() throws Throwable - { - if (!closed) - { + protected final void finalize() throws Throwable { + if (!closed) { ActiveMQJMSClientLogger.LOGGER.connectionLeftOpen(creationStack); close(); } } - protected boolean isXA() - { + protected boolean isXA() { return false; } - protected final ActiveMQSession - createSessionInternal(final boolean isXA, final boolean transacted, int acknowledgeMode, final int type) throws JMSException - { - if (transacted) - { + protected final ActiveMQSession createSessionInternal(final boolean isXA, + final boolean transacted, + int acknowledgeMode, + final int type) throws JMSException { + if (transacted) { acknowledgeMode = Session.SESSION_TRANSACTED; } - try - { + try { ClientSession session; - if (acknowledgeMode == Session.SESSION_TRANSACTED) - { - session = - sessionFactory.createSession(username, password, isXA, false, false, - sessionFactory.getServerLocator().isPreAcknowledge(), - transactionBatchSize); + if (acknowledgeMode == Session.SESSION_TRANSACTED) { + session = sessionFactory.createSession(username, password, isXA, false, false, sessionFactory.getServerLocator().isPreAcknowledge(), transactionBatchSize); } - else if (acknowledgeMode == Session.AUTO_ACKNOWLEDGE) - { - session = - sessionFactory.createSession(username, password, isXA, true, true, - sessionFactory.getServerLocator().isPreAcknowledge(), 0); + else if (acknowledgeMode == Session.AUTO_ACKNOWLEDGE) { + session = sessionFactory.createSession(username, password, isXA, true, true, sessionFactory.getServerLocator().isPreAcknowledge(), 0); } - else if (acknowledgeMode == Session.DUPS_OK_ACKNOWLEDGE) - { - session = - sessionFactory.createSession(username, password, isXA, true, true, - sessionFactory.getServerLocator().isPreAcknowledge(), dupsOKBatchSize); + else if (acknowledgeMode == Session.DUPS_OK_ACKNOWLEDGE) { + session = sessionFactory.createSession(username, password, isXA, true, true, sessionFactory.getServerLocator().isPreAcknowledge(), dupsOKBatchSize); } - else if (acknowledgeMode == Session.CLIENT_ACKNOWLEDGE) - { - session = - sessionFactory.createSession(username, password, isXA, true, false, - sessionFactory.getServerLocator().isPreAcknowledge(), - transactionBatchSize); + else if (acknowledgeMode == Session.CLIENT_ACKNOWLEDGE) { + session = sessionFactory.createSession(username, password, isXA, true, false, sessionFactory.getServerLocator().isPreAcknowledge(), transactionBatchSize); } - else if (acknowledgeMode == ActiveMQJMSConstants.INDIVIDUAL_ACKNOWLEDGE) - { - session = - sessionFactory.createSession(username, password, isXA, true, false, false, transactionBatchSize); + else if (acknowledgeMode == ActiveMQJMSConstants.INDIVIDUAL_ACKNOWLEDGE) { + session = sessionFactory.createSession(username, password, isXA, true, false, false, transactionBatchSize); } - else if (acknowledgeMode == ActiveMQJMSConstants.PRE_ACKNOWLEDGE) - { + else if (acknowledgeMode == ActiveMQJMSConstants.PRE_ACKNOWLEDGE) { session = sessionFactory.createSession(username, password, isXA, true, false, true, transactionBatchSize); } - else - { + else { throw new JMSRuntimeException("Invalid ackmode: " + acknowledgeMode); } @@ -669,8 +597,7 @@ public class ActiveMQConnection extends ActiveMQConnectionForContextImpl impleme sessions.add(jbs); - if (started) - { + if (started) { session.start(); } @@ -678,8 +605,7 @@ public class ActiveMQConnection extends ActiveMQConnectionForContextImpl impleme return jbs; } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } @@ -693,30 +619,27 @@ public class ActiveMQConnection extends ActiveMQConnectionForContextImpl impleme * @param type * @return */ - protected ActiveMQSession createAMQSession(boolean isXA, boolean transacted, int acknowledgeMode, ClientSession session, int type) - { - if (isXA) - { + protected ActiveMQSession createAMQSession(boolean isXA, + boolean transacted, + int acknowledgeMode, + ClientSession session, + int type) { + if (isXA) { return new ActiveMQXASession(this, transacted, true, acknowledgeMode, session, type); } - else - { + else { return new ActiveMQSession(this, transacted, false, acknowledgeMode, session, type); } } - protected final void checkClosed() throws JMSException - { - if (closed) - { + protected final void checkClosed() throws JMSException { + if (closed) { throw new IllegalStateException("Connection is closed"); } } - public void authorize() throws JMSException - { - try - { + public void authorize() throws JMSException { + try { initialSession = sessionFactory.createSession(username, password, false, false, false, false, 0); addSessionMetaData(initialSession); @@ -724,79 +647,62 @@ public class ActiveMQConnection extends ActiveMQConnectionForContextImpl impleme initialSession.addFailureListener(listener); initialSession.addFailoverListener(failoverListener); } - catch (ActiveMQException me) - { + catch (ActiveMQException me) { throw JMSExceptionHelper.convertFromActiveMQException(me); } } - private void addSessionMetaData(ClientSession session) throws ActiveMQException - { + private void addSessionMetaData(ClientSession session) throws ActiveMQException { session.addMetaData(ClientSession.JMS_SESSION_IDENTIFIER_PROPERTY, ""); - if (clientID != null) - { + if (clientID != null) { session.addMetaData(ClientSession.JMS_SESSION_CLIENT_ID_PROPERTY, clientID); } } - public void setReference(ActiveMQConnectionFactory factory) - { + public void setReference(ActiveMQConnectionFactory factory) { this.factoryReference = factory; } - public boolean isStarted() - { + public boolean isStarted() { return started; } - // Inner classes -------------------------------------------------------------------------------- - private static class JMSFailureListener implements SessionFailureListener - { + private static class JMSFailureListener implements SessionFailureListener { + private final WeakReference connectionRef; - JMSFailureListener(final ActiveMQConnection connection) - { + JMSFailureListener(final ActiveMQConnection connection) { connectionRef = new WeakReference(connection); } @Override - public synchronized void connectionFailed(final ActiveMQException me, boolean failedOver) - { - if (me == null) - { + public synchronized void connectionFailed(final ActiveMQException me, boolean failedOver) { + if (me == null) { return; } ActiveMQConnection conn = connectionRef.get(); - if (conn != null) - { - try - { + if (conn != null) { + try { final ExceptionListener exceptionListener = conn.getExceptionListener(); - if (exceptionListener != null) - { - final JMSException je = - new JMSException(me.toString(), failedOver ? EXCEPTION_FAILOVER : EXCEPTION_DISCONNECT); + if (exceptionListener != null) { + final JMSException je = new JMSException(me.toString(), failedOver ? EXCEPTION_FAILOVER : EXCEPTION_DISCONNECT); je.initCause(me); - new Thread(new Runnable() - { - public void run() - { + new Thread(new Runnable() { + public void run() { exceptionListener.onException(je); } }).start(); } } - catch (JMSException e) - { - if (!conn.closed) - { + catch (JMSException e) { + if (!conn.closed) { ActiveMQJMSClientLogger.LOGGER.errorCallingExcListener(e); } } @@ -804,54 +710,43 @@ public class ActiveMQConnection extends ActiveMQConnectionForContextImpl impleme } @Override - public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) { connectionFailed(me, failedOver); } - public void beforeReconnect(final ActiveMQException me) - { + public void beforeReconnect(final ActiveMQException me) { } } - private static class FailoverEventListenerImpl implements FailoverEventListener - { + private static class FailoverEventListenerImpl implements FailoverEventListener { + private final WeakReference connectionRef; - FailoverEventListenerImpl(final ActiveMQConnection connection) - { + FailoverEventListenerImpl(final ActiveMQConnection connection) { connectionRef = new WeakReference(connection); } @Override - public void failoverEvent(final FailoverEventType eventType) - { + public void failoverEvent(final FailoverEventType eventType) { ActiveMQConnection conn = connectionRef.get(); - if (conn != null) - { - try - { + if (conn != null) { + try { final FailoverEventListener failoverListener = conn.getFailoverListener(); - if (failoverListener != null) - { + if (failoverListener != null) { - new Thread(new Runnable() - { - public void run() - { + new Thread(new Runnable() { + public void run() { failoverListener.failoverEvent(eventType); } }).start(); } } - catch (JMSException e) - { - if (!conn.closed) - { + catch (JMSException e) { + if (!conn.closed) { ActiveMQJMSClientLogger.LOGGER.errorCallingFailoverListener(e); } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQConnectionFactory.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQConnectionFactory.java index 0630876b81..912554eb56 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQConnectionFactory.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQConnectionFactory.java @@ -57,9 +57,7 @@ import org.apache.activemq.artemis.uri.ServerLocatorParser; *

    ActiveMQ Artemis implementation of a JMS ConnectionFactory.

    *

    This connection factory will use defaults defined by {@link DefaultConnectionProperties}. */ -public class ActiveMQConnectionFactory implements Externalizable, Referenceable, ConnectionFactory, - XAConnectionFactory, AutoCloseable -{ +public class ActiveMQConnectionFactory implements Externalizable, Referenceable, ConnectionFactory, XAConnectionFactory, AutoCloseable { private ServerLocator serverLocator; @@ -69,67 +67,53 @@ public class ActiveMQConnectionFactory implements Externalizable, Referenceable, private int transactionBatchSize = ActiveMQClient.DEFAULT_ACK_BATCH_SIZE; - private boolean readOnly; + private boolean readOnly; private String user; private String password; - public void writeExternal(ObjectOutput out) throws IOException - { + public void writeExternal(ObjectOutput out) throws IOException { URI uri = toURI(); - try - { + try { out.writeUTF(uri.toASCIIString()); } - catch (Exception e) - { - if (e instanceof IOException) - { + catch (Exception e) { + if (e instanceof IOException) { throw (IOException) e; } throw new IOException(e); } } - public URI toURI() throws IOException - { + public URI toURI() throws IOException { ConnectionFactoryParser parser = new ConnectionFactoryParser(); String scheme; - if (serverLocator.getDiscoveryGroupConfiguration() != null) - { - if (serverLocator.getDiscoveryGroupConfiguration().getBroadcastEndpointFactory() instanceof UDPBroadcastEndpointFactory) - { + if (serverLocator.getDiscoveryGroupConfiguration() != null) { + if (serverLocator.getDiscoveryGroupConfiguration().getBroadcastEndpointFactory() instanceof UDPBroadcastEndpointFactory) { scheme = "udp"; } - else - { + else { scheme = "jgroups"; } } - else - { - if (serverLocator.allInVM()) - { + else { + if (serverLocator.allInVM()) { scheme = "vm"; } - else - { + else { scheme = "tcp"; } } URI uri; - try - { + try { uri = parser.createSchema(scheme, this); } - catch (Exception e) - { - if (e instanceof IOException) - { + catch (Exception e) { + if (e instanceof IOException) { throw (IOException) e; } throw new IOException(e); @@ -137,153 +121,127 @@ public class ActiveMQConnectionFactory implements Externalizable, Referenceable, return uri; } - public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException - { + public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { String url = in.readUTF(); ConnectionFactoryParser parser = new ConnectionFactoryParser(); ServerLocatorParser locatorParser = new ServerLocatorParser(); - try - { + try { URI uri = new URI(url); serverLocator = locatorParser.newObject(uri, null); parser.populateObject(uri, this); } - catch (Exception e) - { + catch (Exception e) { throw new InvalidObjectException(e.getMessage()); } } - /** This will use a default URI from {@link DefaultConnectionProperties} */ - public ActiveMQConnectionFactory() - { + /** + * This will use a default URI from {@link DefaultConnectionProperties} + */ + public ActiveMQConnectionFactory() { this(DefaultConnectionProperties.DEFAULT_BROKER_URL); } - public ActiveMQConnectionFactory(String url) - { + public ActiveMQConnectionFactory(String url) { ConnectionFactoryParser cfParser = new ConnectionFactoryParser(); - try - { + try { URI uri = new URI(url); serverLocator = ServerLocatorImpl.newLocator(uri); cfParser.populateObject(uri, this); } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } - if (getUser() == null) - { + if (getUser() == null) { setUser(DefaultConnectionProperties.DEFAULT_USER); } - if (getPassword() == null) - { + if (getPassword() == null) { setPassword(DefaultConnectionProperties.DEFAULT_PASSWORD); } } - /** For compatibility and users used to this kind of constructor */ - public ActiveMQConnectionFactory(String url, String user, String password) - { + /** + * For compatibility and users used to this kind of constructor + */ + public ActiveMQConnectionFactory(String url, String user, String password) { this(url); setUser(user).setPassword(password); } - public ActiveMQConnectionFactory(final ServerLocator serverLocator) - { + public ActiveMQConnectionFactory(final ServerLocator serverLocator) { this.serverLocator = serverLocator; serverLocator.disableFinalizeCheck(); } - public ActiveMQConnectionFactory(final boolean ha, final DiscoveryGroupConfiguration groupConfiguration) - { - if (ha) - { + public ActiveMQConnectionFactory(final boolean ha, final DiscoveryGroupConfiguration groupConfiguration) { + if (ha) { serverLocator = ActiveMQClient.createServerLocatorWithHA(groupConfiguration); } - else - { + else { serverLocator = ActiveMQClient.createServerLocatorWithoutHA(groupConfiguration); } serverLocator.disableFinalizeCheck(); } - public ActiveMQConnectionFactory(final boolean ha, final TransportConfiguration... initialConnectors) - { - if (ha) - { + public ActiveMQConnectionFactory(final boolean ha, final TransportConfiguration... initialConnectors) { + if (ha) { serverLocator = ActiveMQClient.createServerLocatorWithHA(initialConnectors); } - else - { + else { serverLocator = ActiveMQClient.createServerLocatorWithoutHA(initialConnectors); } serverLocator.disableFinalizeCheck(); } - public Connection createConnection() throws JMSException - { + public Connection createConnection() throws JMSException { return createConnection(user, password); } - public Connection createConnection(final String username, final String password) throws JMSException - { + public Connection createConnection(final String username, final String password) throws JMSException { return createConnectionInternal(username, password, false, ActiveMQConnection.TYPE_GENERIC_CONNECTION); } @Override - public JMSContext createContext() - { + public JMSContext createContext() { return createContext(user, password); } @Override - public JMSContext createContext(final int sessionMode) - { + public JMSContext createContext(final int sessionMode) { return createContext(user, password, sessionMode); } @Override - public JMSContext createContext(final String userName, final String password) - { + public JMSContext createContext(final String userName, final String password) { return createContext(userName, password, JMSContext.AUTO_ACKNOWLEDGE); } @Override - public JMSContext createContext(String userName, String password, int sessionMode) - { + public JMSContext createContext(String userName, String password, int sessionMode) { validateSessionMode(sessionMode); - try - { - ActiveMQConnection connection = - createConnectionInternal(userName, password, false, ActiveMQConnection.TYPE_GENERIC_CONNECTION); + try { + ActiveMQConnection connection = createConnectionInternal(userName, password, false, ActiveMQConnection.TYPE_GENERIC_CONNECTION); return connection.createContext(sessionMode); } - catch (JMSSecurityException e) - { + catch (JMSSecurityException e) { throw new JMSSecurityRuntimeException(e.getMessage(), e.getErrorCode(), e); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } - private static void validateSessionMode(int mode) - { - switch (mode) - { + private static void validateSessionMode(int mode) { + switch (mode) { case JMSContext.AUTO_ACKNOWLEDGE: case JMSContext.CLIENT_ACKNOWLEDGE: case JMSContext.DUPS_OK_ACKNOWLEDGE: - case JMSContext.SESSION_TRANSACTED: - { + case JMSContext.SESSION_TRANSACTED: { return; } default: @@ -291,252 +249,203 @@ public class ActiveMQConnectionFactory implements Externalizable, Referenceable, } } - public QueueConnection createQueueConnection() throws JMSException - { + public QueueConnection createQueueConnection() throws JMSException { return createQueueConnection(null, null); } - public QueueConnection createQueueConnection(final String username, final String password) throws JMSException - { + public QueueConnection createQueueConnection(final String username, final String password) throws JMSException { return createConnectionInternal(username, password, false, ActiveMQConnection.TYPE_QUEUE_CONNECTION); } // TopicConnectionFactory implementation -------------------------------------------------------- - public TopicConnection createTopicConnection() throws JMSException - { + public TopicConnection createTopicConnection() throws JMSException { return createTopicConnection(null, null); } - public TopicConnection createTopicConnection(final String username, final String password) throws JMSException - { + public TopicConnection createTopicConnection(final String username, final String password) throws JMSException { return createConnectionInternal(username, password, false, ActiveMQConnection.TYPE_TOPIC_CONNECTION); } // XAConnectionFactory implementation ----------------------------------------------------------- - public XAConnection createXAConnection() throws JMSException - { + public XAConnection createXAConnection() throws JMSException { return createXAConnection(null, null); } - public XAConnection createXAConnection(final String username, final String password) throws JMSException - { + public XAConnection createXAConnection(final String username, final String password) throws JMSException { return (XAConnection) createConnectionInternal(username, password, true, ActiveMQConnection.TYPE_GENERIC_CONNECTION); } @Override - public XAJMSContext createXAContext() - { + public XAJMSContext createXAContext() { return createXAContext(null, null); } @Override - public XAJMSContext createXAContext(String userName, String password) - { - try - { - ActiveMQConnection connection = - createConnectionInternal(userName, password, true, ActiveMQConnection.TYPE_GENERIC_CONNECTION); + public XAJMSContext createXAContext(String userName, String password) { + try { + ActiveMQConnection connection = createConnectionInternal(userName, password, true, ActiveMQConnection.TYPE_GENERIC_CONNECTION); return connection.createXAContext(); } - catch (JMSSecurityException e) - { + catch (JMSSecurityException e) { throw new JMSSecurityRuntimeException(e.getMessage(), e.getErrorCode(), e); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } // XAQueueConnectionFactory implementation ------------------------------------------------------ - public XAQueueConnection createXAQueueConnection() throws JMSException - { + public XAQueueConnection createXAQueueConnection() throws JMSException { return createXAQueueConnection(null, null); } - public XAQueueConnection createXAQueueConnection(final String username, final String password) throws JMSException - { + public XAQueueConnection createXAQueueConnection(final String username, final String password) throws JMSException { return (XAQueueConnection) createConnectionInternal(username, password, true, ActiveMQConnection.TYPE_QUEUE_CONNECTION); } // XATopicConnectionFactory implementation ------------------------------------------------------ - public XATopicConnection createXATopicConnection() throws JMSException - { + public XATopicConnection createXATopicConnection() throws JMSException { return createXATopicConnection(null, null); } - public XATopicConnection createXATopicConnection(final String username, final String password) throws JMSException - { + public XATopicConnection createXATopicConnection(final String username, final String password) throws JMSException { return (XATopicConnection) createConnectionInternal(username, password, true, ActiveMQConnection.TYPE_TOPIC_CONNECTION); } @Override - public Reference getReference() throws NamingException - { - return new Reference(this.getClass().getCanonicalName(), - new SerializableObjectRefAddr("ActiveMQ-CF", this), - ConnectionFactoryObjectFactory.class.getCanonicalName(), - null); + public Reference getReference() throws NamingException { + return new Reference(this.getClass().getCanonicalName(), new SerializableObjectRefAddr("ActiveMQ-CF", this), ConnectionFactoryObjectFactory.class.getCanonicalName(), null); } - public boolean isHA() - { + public boolean isHA() { return serverLocator.isHA(); } - public synchronized String getConnectionLoadBalancingPolicyClassName() - { + public synchronized String getConnectionLoadBalancingPolicyClassName() { return serverLocator.getConnectionLoadBalancingPolicyClassName(); } - public synchronized void setConnectionLoadBalancingPolicyClassName(final String connectionLoadBalancingPolicyClassName) - { + public synchronized void setConnectionLoadBalancingPolicyClassName(final String connectionLoadBalancingPolicyClassName) { checkWrite(); serverLocator.setConnectionLoadBalancingPolicyClassName(connectionLoadBalancingPolicyClassName); } - public synchronized TransportConfiguration[] getStaticConnectors() - { + public synchronized TransportConfiguration[] getStaticConnectors() { return serverLocator.getStaticTransportConfigurations(); } - public synchronized DiscoveryGroupConfiguration getDiscoveryGroupConfiguration() - { + public synchronized DiscoveryGroupConfiguration getDiscoveryGroupConfiguration() { return serverLocator.getDiscoveryGroupConfiguration(); } - public synchronized String getClientID() - { + public synchronized String getClientID() { return clientID; } - public synchronized void setClientID(final String clientID) - { + public synchronized void setClientID(final String clientID) { checkWrite(); this.clientID = clientID; } - public synchronized int getDupsOKBatchSize() - { + public synchronized int getDupsOKBatchSize() { return dupsOKBatchSize; } - public synchronized void setDupsOKBatchSize(final int dupsOKBatchSize) - { + public synchronized void setDupsOKBatchSize(final int dupsOKBatchSize) { checkWrite(); this.dupsOKBatchSize = dupsOKBatchSize; } - public synchronized int getTransactionBatchSize() - { + public synchronized int getTransactionBatchSize() { return transactionBatchSize; } - public synchronized void setTransactionBatchSize(final int transactionBatchSize) - { + public synchronized void setTransactionBatchSize(final int transactionBatchSize) { checkWrite(); this.transactionBatchSize = transactionBatchSize; } - public synchronized long getClientFailureCheckPeriod() - { + public synchronized long getClientFailureCheckPeriod() { return serverLocator.getClientFailureCheckPeriod(); } - public synchronized void setClientFailureCheckPeriod(final long clientFailureCheckPeriod) - { + public synchronized void setClientFailureCheckPeriod(final long clientFailureCheckPeriod) { checkWrite(); serverLocator.setClientFailureCheckPeriod(clientFailureCheckPeriod); } - public synchronized long getConnectionTTL() - { + public synchronized long getConnectionTTL() { return serverLocator.getConnectionTTL(); } - public synchronized void setConnectionTTL(final long connectionTTL) - { + public synchronized void setConnectionTTL(final long connectionTTL) { checkWrite(); serverLocator.setConnectionTTL(connectionTTL); } - public synchronized long getCallTimeout() - { + public synchronized long getCallTimeout() { return serverLocator.getCallTimeout(); } - public synchronized void setCallTimeout(final long callTimeout) - { + public synchronized void setCallTimeout(final long callTimeout) { checkWrite(); serverLocator.setCallTimeout(callTimeout); } - public synchronized long getCallFailoverTimeout() - { + public synchronized long getCallFailoverTimeout() { return serverLocator.getCallFailoverTimeout(); } - public synchronized void setCallFailoverTimeout(final long callTimeout) - { + public synchronized void setCallFailoverTimeout(final long callTimeout) { checkWrite(); serverLocator.setCallFailoverTimeout(callTimeout); } - public synchronized int getConsumerWindowSize() - { + public synchronized int getConsumerWindowSize() { return serverLocator.getConsumerWindowSize(); } - public synchronized void setConsumerWindowSize(final int consumerWindowSize) - { + public synchronized void setConsumerWindowSize(final int consumerWindowSize) { checkWrite(); serverLocator.setConsumerWindowSize(consumerWindowSize); } - public synchronized int getConsumerMaxRate() - { + public synchronized int getConsumerMaxRate() { return serverLocator.getConsumerMaxRate(); } - public synchronized void setConsumerMaxRate(final int consumerMaxRate) - { + public synchronized void setConsumerMaxRate(final int consumerMaxRate) { checkWrite(); serverLocator.setConsumerMaxRate(consumerMaxRate); } - public synchronized int getConfirmationWindowSize() - { + public synchronized int getConfirmationWindowSize() { return serverLocator.getConfirmationWindowSize(); } - public synchronized void setConfirmationWindowSize(final int confirmationWindowSize) - { + public synchronized void setConfirmationWindowSize(final int confirmationWindowSize) { checkWrite(); serverLocator.setConfirmationWindowSize(confirmationWindowSize); } - public synchronized int getProducerMaxRate() - { + public synchronized int getProducerMaxRate() { return serverLocator.getProducerMaxRate(); } - public synchronized void setProducerMaxRate(final int producerMaxRate) - { + public synchronized void setProducerMaxRate(final int producerMaxRate) { checkWrite(); serverLocator.setProducerMaxRate(producerMaxRate); } - public synchronized int getProducerWindowSize() - { + public synchronized int getProducerWindowSize() { return serverLocator.getProducerWindowSize(); } - public synchronized void setProducerWindowSize(final int producerWindowSize) - { + public synchronized void setProducerWindowSize(final int producerWindowSize) { checkWrite(); serverLocator.setProducerWindowSize(producerWindowSize); } @@ -544,251 +453,206 @@ public class ActiveMQConnectionFactory implements Externalizable, Referenceable, /** * @param cacheLargeMessagesClient */ - public synchronized void setCacheLargeMessagesClient(final boolean cacheLargeMessagesClient) - { + public synchronized void setCacheLargeMessagesClient(final boolean cacheLargeMessagesClient) { checkWrite(); serverLocator.setCacheLargeMessagesClient(cacheLargeMessagesClient); } - public synchronized boolean isCacheLargeMessagesClient() - { + public synchronized boolean isCacheLargeMessagesClient() { return serverLocator.isCacheLargeMessagesClient(); } - public synchronized int getMinLargeMessageSize() - { + public synchronized int getMinLargeMessageSize() { return serverLocator.getMinLargeMessageSize(); } - public synchronized void setMinLargeMessageSize(final int minLargeMessageSize) - { + public synchronized void setMinLargeMessageSize(final int minLargeMessageSize) { checkWrite(); serverLocator.setMinLargeMessageSize(minLargeMessageSize); } - public synchronized boolean isBlockOnAcknowledge() - { + public synchronized boolean isBlockOnAcknowledge() { return serverLocator.isBlockOnAcknowledge(); } - public synchronized void setBlockOnAcknowledge(final boolean blockOnAcknowledge) - { + public synchronized void setBlockOnAcknowledge(final boolean blockOnAcknowledge) { checkWrite(); serverLocator.setBlockOnAcknowledge(blockOnAcknowledge); } - public synchronized boolean isBlockOnNonDurableSend() - { + public synchronized boolean isBlockOnNonDurableSend() { return serverLocator.isBlockOnNonDurableSend(); } - public synchronized void setBlockOnNonDurableSend(final boolean blockOnNonDurableSend) - { + public synchronized void setBlockOnNonDurableSend(final boolean blockOnNonDurableSend) { checkWrite(); serverLocator.setBlockOnNonDurableSend(blockOnNonDurableSend); } - public synchronized boolean isBlockOnDurableSend() - { + public synchronized boolean isBlockOnDurableSend() { return serverLocator.isBlockOnDurableSend(); } - public synchronized void setBlockOnDurableSend(final boolean blockOnDurableSend) - { + public synchronized void setBlockOnDurableSend(final boolean blockOnDurableSend) { checkWrite(); serverLocator.setBlockOnDurableSend(blockOnDurableSend); } - public synchronized boolean isAutoGroup() - { + public synchronized boolean isAutoGroup() { return serverLocator.isAutoGroup(); } - public synchronized void setAutoGroup(final boolean autoGroup) - { + public synchronized void setAutoGroup(final boolean autoGroup) { checkWrite(); serverLocator.setAutoGroup(autoGroup); } - public synchronized boolean isPreAcknowledge() - { + public synchronized boolean isPreAcknowledge() { return serverLocator.isPreAcknowledge(); } - public synchronized void setPreAcknowledge(final boolean preAcknowledge) - { + public synchronized void setPreAcknowledge(final boolean preAcknowledge) { checkWrite(); serverLocator.setPreAcknowledge(preAcknowledge); } - public synchronized long getRetryInterval() - { + public synchronized long getRetryInterval() { return serverLocator.getRetryInterval(); } - public synchronized void setRetryInterval(final long retryInterval) - { + public synchronized void setRetryInterval(final long retryInterval) { checkWrite(); serverLocator.setRetryInterval(retryInterval); } - public synchronized long getMaxRetryInterval() - { + public synchronized long getMaxRetryInterval() { return serverLocator.getMaxRetryInterval(); } - public synchronized void setMaxRetryInterval(final long retryInterval) - { + public synchronized void setMaxRetryInterval(final long retryInterval) { checkWrite(); serverLocator.setMaxRetryInterval(retryInterval); } - public synchronized double getRetryIntervalMultiplier() - { + public synchronized double getRetryIntervalMultiplier() { return serverLocator.getRetryIntervalMultiplier(); } - public synchronized void setRetryIntervalMultiplier(final double retryIntervalMultiplier) - { + public synchronized void setRetryIntervalMultiplier(final double retryIntervalMultiplier) { checkWrite(); serverLocator.setRetryIntervalMultiplier(retryIntervalMultiplier); } - public synchronized int getReconnectAttempts() - { + public synchronized int getReconnectAttempts() { return serverLocator.getReconnectAttempts(); } - public synchronized void setReconnectAttempts(final int reconnectAttempts) - { + public synchronized void setReconnectAttempts(final int reconnectAttempts) { checkWrite(); serverLocator.setReconnectAttempts(reconnectAttempts); } - public synchronized void setInitialConnectAttempts(final int reconnectAttempts) - { + public synchronized void setInitialConnectAttempts(final int reconnectAttempts) { checkWrite(); serverLocator.setInitialConnectAttempts(reconnectAttempts); } - public synchronized int getInitialConnectAttempts() - { + public synchronized int getInitialConnectAttempts() { return serverLocator.getInitialConnectAttempts(); } - public synchronized boolean isFailoverOnInitialConnection() - { + public synchronized boolean isFailoverOnInitialConnection() { return serverLocator.isFailoverOnInitialConnection(); } - public synchronized void setFailoverOnInitialConnection(final boolean failover) - { + public synchronized void setFailoverOnInitialConnection(final boolean failover) { checkWrite(); serverLocator.setFailoverOnInitialConnection(failover); } - public synchronized boolean isUseGlobalPools() - { + public synchronized boolean isUseGlobalPools() { return serverLocator.isUseGlobalPools(); } - public synchronized void setUseGlobalPools(final boolean useGlobalPools) - { + public synchronized void setUseGlobalPools(final boolean useGlobalPools) { checkWrite(); serverLocator.setUseGlobalPools(useGlobalPools); } - public synchronized int getScheduledThreadPoolMaxSize() - { + public synchronized int getScheduledThreadPoolMaxSize() { return serverLocator.getScheduledThreadPoolMaxSize(); } - public synchronized void setScheduledThreadPoolMaxSize(final int scheduledThreadPoolMaxSize) - { + public synchronized void setScheduledThreadPoolMaxSize(final int scheduledThreadPoolMaxSize) { checkWrite(); serverLocator.setScheduledThreadPoolMaxSize(scheduledThreadPoolMaxSize); } - public synchronized int getThreadPoolMaxSize() - { + public synchronized int getThreadPoolMaxSize() { return serverLocator.getThreadPoolMaxSize(); } - public synchronized void setThreadPoolMaxSize(final int threadPoolMaxSize) - { + public synchronized void setThreadPoolMaxSize(final int threadPoolMaxSize) { checkWrite(); serverLocator.setThreadPoolMaxSize(threadPoolMaxSize); } - public synchronized int getInitialMessagePacketSize() - { + public synchronized int getInitialMessagePacketSize() { return serverLocator.getInitialMessagePacketSize(); } - public synchronized void setInitialMessagePacketSize(final int size) - { + public synchronized void setInitialMessagePacketSize(final int size) { checkWrite(); serverLocator.setInitialMessagePacketSize(size); } - public ActiveMQConnectionFactory setUser(String user) - { + public ActiveMQConnectionFactory setUser(String user) { checkWrite(); this.user = user; return this; } - public String getUser() - { + public String getUser() { return user; } - public String getPassword() - { + public String getPassword() { return password; } - public ActiveMQConnectionFactory setPassword(String password) - { + public ActiveMQConnectionFactory setPassword(String password) { checkWrite(); this.password = password; return this; } - public void setGroupID(final String groupID) - { + public void setGroupID(final String groupID) { serverLocator.setGroupID(groupID); } - public String getGroupID() - { + public String getGroupID() { return serverLocator.getGroupID(); } - public boolean isCompressLargeMessage() - { + public boolean isCompressLargeMessage() { return serverLocator.isCompressLargeMessage(); } - public void setCompressLargeMessage(boolean avoidLargeMessages) - { + public void setCompressLargeMessage(boolean avoidLargeMessages) { serverLocator.setCompressLargeMessage(avoidLargeMessages); } - public void close() - { + public void close() { ServerLocator locator0 = serverLocator; if (locator0 != null) locator0.close(); } - public ServerLocator getServerLocator() - { + public ServerLocator getServerLocator() { return serverLocator; } - public int getFactoryType() - { + public int getFactoryType() { return JMSFactoryType.CF.intValue(); } @@ -797,20 +661,17 @@ public class ActiveMQConnectionFactory implements Externalizable, Referenceable, // Protected ------------------------------------------------------------------------------------ protected synchronized ActiveMQConnection createConnectionInternal(final String username, - final String password, - final boolean isXA, - final int type) throws JMSException - { + final String password, + final boolean isXA, + final int type) throws JMSException { readOnly = true; ClientSessionFactory factory; - try - { + try { factory = serverLocator.createSessionFactory(); } - catch (Exception e) - { + catch (Exception e) { JMSException jmse = new JMSException("Failed to create session factory"); jmse.initCause(e); @@ -821,95 +682,42 @@ public class ActiveMQConnectionFactory implements Externalizable, Referenceable, ActiveMQConnection connection = null; - if (isXA) - { - if (type == ActiveMQConnection.TYPE_GENERIC_CONNECTION) - { - connection = new ActiveMQXAConnection(username, - password, - type, - clientID, - dupsOKBatchSize, - transactionBatchSize, - factory); + if (isXA) { + if (type == ActiveMQConnection.TYPE_GENERIC_CONNECTION) { + connection = new ActiveMQXAConnection(username, password, type, clientID, dupsOKBatchSize, transactionBatchSize, factory); } - else if (type == ActiveMQConnection.TYPE_QUEUE_CONNECTION) - { - connection = - new ActiveMQXAConnection(username, - password, - type, - clientID, - dupsOKBatchSize, - transactionBatchSize, - factory); + else if (type == ActiveMQConnection.TYPE_QUEUE_CONNECTION) { + connection = new ActiveMQXAConnection(username, password, type, clientID, dupsOKBatchSize, transactionBatchSize, factory); } - else if (type == ActiveMQConnection.TYPE_TOPIC_CONNECTION) - { - connection = - new ActiveMQXAConnection(username, - password, - type, - clientID, - dupsOKBatchSize, - transactionBatchSize, - factory); + else if (type == ActiveMQConnection.TYPE_TOPIC_CONNECTION) { + connection = new ActiveMQXAConnection(username, password, type, clientID, dupsOKBatchSize, transactionBatchSize, factory); } } - else - { - if (type == ActiveMQConnection.TYPE_GENERIC_CONNECTION) - { - connection = new ActiveMQConnection(username, - password, - type, - clientID, - dupsOKBatchSize, - transactionBatchSize, - factory); + else { + if (type == ActiveMQConnection.TYPE_GENERIC_CONNECTION) { + connection = new ActiveMQConnection(username, password, type, clientID, dupsOKBatchSize, transactionBatchSize, factory); } - else if (type == ActiveMQConnection.TYPE_QUEUE_CONNECTION) - { - connection = - new ActiveMQConnection(username, - password, - type, - clientID, - dupsOKBatchSize, - transactionBatchSize, - factory); + else if (type == ActiveMQConnection.TYPE_QUEUE_CONNECTION) { + connection = new ActiveMQConnection(username, password, type, clientID, dupsOKBatchSize, transactionBatchSize, factory); } - else if (type == ActiveMQConnection.TYPE_TOPIC_CONNECTION) - { - connection = - new ActiveMQConnection(username, - password, - type, - clientID, - dupsOKBatchSize, - transactionBatchSize, - factory); + else if (type == ActiveMQConnection.TYPE_TOPIC_CONNECTION) { + connection = new ActiveMQConnection(username, password, type, clientID, dupsOKBatchSize, transactionBatchSize, factory); } } - if (connection == null) - { + if (connection == null) { throw new JMSException("Failed to create connection: invalid type " + type); } connection.setReference(this); - try - { + try { connection.authorize(); } - catch (JMSException e) - { - try - { + catch (JMSException e) { + try { connection.close(); } - catch (JMSException me) - { + catch (JMSException me) { } throw e; } @@ -918,8 +726,7 @@ public class ActiveMQConnectionFactory implements Externalizable, Referenceable, } @Override - public String toString() - { + public String toString() { return "ActiveMQConnectionFactory [serverLocator=" + serverLocator + ", clientID=" + clientID + @@ -934,26 +741,20 @@ public class ActiveMQConnectionFactory implements Externalizable, Referenceable, "]"; } - // Private -------------------------------------------------------------------------------------- - private void checkWrite() - { - if (readOnly) - { + private void checkWrite() { + if (readOnly) { throw new IllegalStateException("Cannot set attribute on ActiveMQConnectionFactory after it has been used"); } } @Override - protected void finalize() throws Throwable - { - try - { + protected void finalize() throws Throwable { + try { serverLocator.close(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); //not much we can do here } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQConnectionForContext.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQConnectionForContext.java index 0fc785456a..966a84c8f5 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQConnectionForContext.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQConnectionForContext.java @@ -23,10 +23,11 @@ import javax.jms.XAJMSContext; * Interface created to support reference counting all contexts using it. *

    * Necessary to support {@code JMSContext.close()} conditions. + * * @see JMSContext */ -public interface ActiveMQConnectionForContext extends javax.jms.Connection -{ +public interface ActiveMQConnectionForContext extends javax.jms.Connection { + JMSContext createContext(int sessionMode); XAJMSContext createXAContext(); diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQConnectionForContextImpl.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQConnectionForContextImpl.java index 0a19793afe..31eadb9a52 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQConnectionForContextImpl.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQConnectionForContextImpl.java @@ -26,19 +26,14 @@ import org.apache.activemq.artemis.api.jms.ActiveMQJMSConstants; import org.apache.activemq.artemis.utils.ReferenceCounter; import org.apache.activemq.artemis.utils.ReferenceCounterUtil; -public abstract class ActiveMQConnectionForContextImpl implements ActiveMQConnectionForContext -{ +public abstract class ActiveMQConnectionForContextImpl implements ActiveMQConnectionForContext { - final Runnable closeRunnable = new Runnable() - { - public void run() - { - try - { + final Runnable closeRunnable = new Runnable() { + public void run() { + try { close(); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @@ -48,10 +43,8 @@ public abstract class ActiveMQConnectionForContextImpl implements ActiveMQConnec protected final ThreadAwareContext threadAwareContext = new ThreadAwareContext(); - public JMSContext createContext(int sessionMode) - { - switch (sessionMode) - { + public JMSContext createContext(int sessionMode) { + switch (sessionMode) { case Session.AUTO_ACKNOWLEDGE: case Session.CLIENT_ACKNOWLEDGE: case Session.DUPS_OK_ACKNOWLEDGE: @@ -67,26 +60,22 @@ public abstract class ActiveMQConnectionForContextImpl implements ActiveMQConnec return new ActiveMQJMSContext(this, sessionMode, threadAwareContext); } - public XAJMSContext createXAContext() - { + public XAJMSContext createXAContext() { refCounter.increment(); return new ActiveMQXAJMSContext(this, threadAwareContext); } @Override - public void closeFromContext() - { + public void closeFromContext() { refCounter.decrement(); } - protected void incrementRefCounter() - { + protected void incrementRefCounter() { refCounter.increment(); } - public ThreadAwareContext getThreadAwareContext() - { + public ThreadAwareContext getThreadAwareContext() { return threadAwareContext; } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQConnectionMetaData.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQConnectionMetaData.java index 279f6d649b..6af723fc55 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQConnectionMetaData.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQConnectionMetaData.java @@ -27,8 +27,7 @@ import org.apache.activemq.artemis.core.version.Version; /** * ActiveMQ Artemis implementation of a JMS ConnectionMetaData. */ -public class ActiveMQConnectionMetaData implements ConnectionMetaData -{ +public class ActiveMQConnectionMetaData implements ConnectionMetaData { // Constants ----------------------------------------------------- private static final String ACTIVEMQ = "ActiveMQ"; @@ -44,50 +43,41 @@ public class ActiveMQConnectionMetaData implements ConnectionMetaData /** * Create a new ActiveMQConnectionMetaData object. */ - public ActiveMQConnectionMetaData(final Version serverVersion) - { + public ActiveMQConnectionMetaData(final Version serverVersion) { this.serverVersion = serverVersion; } // ConnectionMetaData implementation ----------------------------- - public String getJMSVersion() throws JMSException - { + public String getJMSVersion() throws JMSException { return "2.0"; } - public int getJMSMajorVersion() throws JMSException - { + public int getJMSMajorVersion() throws JMSException { return 2; } - public int getJMSMinorVersion() throws JMSException - { + public int getJMSMinorVersion() throws JMSException { return 0; } - public String getJMSProviderName() throws JMSException - { + public String getJMSProviderName() throws JMSException { return ActiveMQConnectionMetaData.ACTIVEMQ; } - public String getProviderVersion() throws JMSException - { + public String getProviderVersion() throws JMSException { return serverVersion.getFullVersion(); } - public int getProviderMajorVersion() throws JMSException - { + public int getProviderMajorVersion() throws JMSException { return serverVersion.getMajorVersion(); } - public int getProviderMinorVersion() throws JMSException - { + public int getProviderMinorVersion() throws JMSException { return serverVersion.getMinorVersion(); } - public Enumeration getJMSXPropertyNames() throws JMSException - { + public Enumeration getJMSXPropertyNames() throws JMSException { Vector v = new Vector(); v.add("JMSXGroupID"); v.add("JMSXGroupSeq"); diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQDestination.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQDestination.java index 2927f2d69f..9d431f9bbc 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQDestination.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQDestination.java @@ -33,8 +33,7 @@ import org.apache.activemq.artemis.jms.referenceable.SerializableObjectRefAddr; /** * ActiveMQ Artemis implementation of a JMS Destination. */ -public class ActiveMQDestination implements Destination, Serializable, Referenceable -{ +public class ActiveMQDestination implements Destination, Serializable, Referenceable { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -62,13 +61,10 @@ public class ActiveMQDestination implements Destination, Serializable, Reference public static final byte TEMP_TOPIC_TYPE = TOPIC_TYPE | TEMP_MASK; public static final byte TEMP_QUEUE_TYPE = QUEUE_TYPE | TEMP_MASK; - private static final char SEPARATOR = '.'; - private static String escape(final String input) - { - if (input == null) - { + private static String escape(final String input) { + if (input == null) { return ""; } return input.replace("\\", "\\\\").replace(".", "\\."); @@ -77,27 +73,21 @@ public class ActiveMQDestination implements Destination, Serializable, Reference /** * Static helper method for working with destinations. */ - public static ActiveMQDestination createDestination(String name, byte defaultType) - { - if (name.startsWith(QUEUE_QUALIFIED_PREFIX)) - { + public static ActiveMQDestination createDestination(String name, byte defaultType) { + if (name.startsWith(QUEUE_QUALIFIED_PREFIX)) { return new ActiveMQQueue(name.substring(QUEUE_QUALIFIED_PREFIX.length())); } - else if (name.startsWith(TOPIC_QUALIFIED_PREFIX)) - { + else if (name.startsWith(TOPIC_QUALIFIED_PREFIX)) { return new ActiveMQTopic(name.substring(TOPIC_QUALIFIED_PREFIX.length())); } - else if (name.startsWith(TEMP_QUEUE_QUALIFED_PREFIX)) - { + else if (name.startsWith(TEMP_QUEUE_QUALIFED_PREFIX)) { return new ActiveMQQueue(name.substring(TEMP_QUEUE_QUALIFED_PREFIX.length()), true); } - else if (name.startsWith(TEMP_TOPIC_QUALIFED_PREFIX)) - { + else if (name.startsWith(TEMP_TOPIC_QUALIFED_PREFIX)) { return new ActiveMQTopic(name.substring(TEMP_TOPIC_QUALIFED_PREFIX.length()), true); } - switch (defaultType) - { + switch (defaultType) { case QUEUE_TYPE: return new ActiveMQQueue(name); case TOPIC_TYPE: @@ -111,86 +101,72 @@ public class ActiveMQDestination implements Destination, Serializable, Reference } } - - public static Destination fromAddress(final String address) - { - if (address.startsWith(ActiveMQDestination.JMS_QUEUE_ADDRESS_PREFIX)) - { + public static Destination fromAddress(final String address) { + if (address.startsWith(ActiveMQDestination.JMS_QUEUE_ADDRESS_PREFIX)) { String name = address.substring(ActiveMQDestination.JMS_QUEUE_ADDRESS_PREFIX.length()); return createQueue(name); } - else if (address.startsWith(ActiveMQDestination.JMS_TOPIC_ADDRESS_PREFIX)) - { + else if (address.startsWith(ActiveMQDestination.JMS_TOPIC_ADDRESS_PREFIX)) { String name = address.substring(ActiveMQDestination.JMS_TOPIC_ADDRESS_PREFIX.length()); return createTopic(name); } - else if (address.startsWith(ActiveMQDestination.JMS_TEMP_QUEUE_ADDRESS_PREFIX)) - { + else if (address.startsWith(ActiveMQDestination.JMS_TEMP_QUEUE_ADDRESS_PREFIX)) { String name = address.substring(ActiveMQDestination.JMS_TEMP_QUEUE_ADDRESS_PREFIX.length()); return new ActiveMQTemporaryQueue(address, name, null); } - else if (address.startsWith(ActiveMQDestination.JMS_TEMP_TOPIC_ADDRESS_PREFIX)) - { + else if (address.startsWith(ActiveMQDestination.JMS_TEMP_TOPIC_ADDRESS_PREFIX)) { String name = address.substring(ActiveMQDestination.JMS_TEMP_TOPIC_ADDRESS_PREFIX.length()); return new ActiveMQTemporaryTopic(address, name, null); } - else - { + else { throw new JMSRuntimeException("Invalid address " + address); } } - public static String createQueueNameForDurableSubscription(final boolean isDurable, final String clientID, final String subscriptionName) - { - if (clientID != null) - { - if (isDurable) - { + public static String createQueueNameForDurableSubscription(final boolean isDurable, + final String clientID, + final String subscriptionName) { + if (clientID != null) { + if (isDurable) { return ActiveMQDestination.escape(clientID) + SEPARATOR + ActiveMQDestination.escape(subscriptionName); } - else - { + else { return "nonDurable" + SEPARATOR + ActiveMQDestination.escape(clientID) + SEPARATOR + ActiveMQDestination.escape(subscriptionName); } } - else - { - if (isDurable) - { + else { + if (isDurable) { return ActiveMQDestination.escape(subscriptionName); } - else - { + else { return "nonDurable" + SEPARATOR + ActiveMQDestination.escape(subscriptionName); } } } - public static String createQueueNameForSharedSubscription(final boolean isDurable, final String clientID, final String subscriptionName) - { - if (clientID != null) - { + public static String createQueueNameForSharedSubscription(final boolean isDurable, + final String clientID, + final String subscriptionName) { + if (clientID != null) { return (isDurable ? "Durable" : "nonDurable") + SEPARATOR + ActiveMQDestination.escape(clientID) + SEPARATOR + ActiveMQDestination.escape(subscriptionName); } - else - { + else { return (isDurable ? "Durable" : "nonDurable") + SEPARATOR + ActiveMQDestination.escape(subscriptionName); } } - public static Pair decomposeQueueNameForDurableSubscription(final String queueName) - { + public static Pair decomposeQueueNameForDurableSubscription(final String queueName) { StringBuffer[] parts = new StringBuffer[2]; int currentPart = 0; @@ -198,26 +174,21 @@ public class ActiveMQDestination implements Destination, Serializable, Reference parts[1] = new StringBuffer(); int pos = 0; - while (pos < queueName.length()) - { + while (pos < queueName.length()) { char ch = queueName.charAt(pos); pos++; - if (ch == SEPARATOR) - { + if (ch == SEPARATOR) { currentPart++; - if (currentPart >= parts.length) - { + if (currentPart >= parts.length) { throw new JMSRuntimeException("Invalid message queue name: " + queueName); } continue; } - if (ch == '\\') - { - if (pos >= queueName.length()) - { + if (ch == '\\') { + if (pos >= queueName.length()) { throw new JMSRuntimeException("Invalid message queue name: " + queueName); } ch = queueName.charAt(pos); @@ -227,8 +198,7 @@ public class ActiveMQDestination implements Destination, Serializable, Reference parts[currentPart].append(ch); } - if (currentPart != 1) - { + if (currentPart != 1) { throw new JMSRuntimeException("Invalid message queue name: " + queueName); } @@ -237,57 +207,47 @@ public class ActiveMQDestination implements Destination, Serializable, Reference return pair; } - public static SimpleString createQueueAddressFromName(final String name) - { + public static SimpleString createQueueAddressFromName(final String name) { return new SimpleString(JMS_QUEUE_ADDRESS_PREFIX + name); } - public static SimpleString createTopicAddressFromName(final String name) - { + public static SimpleString createTopicAddressFromName(final String name) { return new SimpleString(JMS_TOPIC_ADDRESS_PREFIX + name); } - public static ActiveMQQueue createQueue(final String name) - { + public static ActiveMQQueue createQueue(final String name) { return new ActiveMQQueue(name); } - public static ActiveMQTopic createTopic(final String name) - { + public static ActiveMQTopic createTopic(final String name) { return new ActiveMQTopic(name); } - public static ActiveMQTemporaryQueue createTemporaryQueue(final String name, final ActiveMQSession session) - { + public static ActiveMQTemporaryQueue createTemporaryQueue(final String name, final ActiveMQSession session) { return new ActiveMQTemporaryQueue(JMS_TEMP_QUEUE_ADDRESS_PREFIX.concat(name), name, session); } - public static ActiveMQTemporaryQueue createTemporaryQueue(final String name) - { + public static ActiveMQTemporaryQueue createTemporaryQueue(final String name) { return createTemporaryQueue(name, null); } - public static ActiveMQTemporaryQueue createTemporaryQueue(final ActiveMQSession session) - { + public static ActiveMQTemporaryQueue createTemporaryQueue(final ActiveMQSession session) { String name = UUID.randomUUID().toString(); return createTemporaryQueue(name, session); } - public static ActiveMQTemporaryTopic createTemporaryTopic(final ActiveMQSession session) - { + public static ActiveMQTemporaryTopic createTemporaryTopic(final ActiveMQSession session) { String name = UUID.randomUUID().toString(); return createTemporaryTopic(name, session); } - public static ActiveMQTemporaryTopic createTemporaryTopic(String name, final ActiveMQSession session) - { + public static ActiveMQTemporaryTopic createTemporaryTopic(String name, final ActiveMQSession session) { return new ActiveMQTemporaryTopic(JMS_TEMP_TOPIC_ADDRESS_PREFIX.concat(name), name, session); } - public static ActiveMQTemporaryTopic createTemporaryTopic(String name) - { + public static ActiveMQTemporaryTopic createTemporaryTopic(String name) { return createTemporaryTopic(name, null); } @@ -316,11 +276,11 @@ public class ActiveMQDestination implements Destination, Serializable, Reference // Constructors -------------------------------------------------- - protected ActiveMQDestination(final String address, final String name, + protected ActiveMQDestination(final String address, + final String name, final boolean temporary, final boolean queue, - final ActiveMQSession session) - { + final ActiveMQSession session) { this.address = address; this.name = name; @@ -336,71 +296,54 @@ public class ActiveMQDestination implements Destination, Serializable, Reference // Referenceable implementation --------------------------------------- - public Reference getReference() throws NamingException - { - return new Reference(this.getClass().getCanonicalName(), - new SerializableObjectRefAddr("ActiveMQ-DEST", this), - DestinationObjectFactory.class.getCanonicalName(), - null); + public Reference getReference() throws NamingException { + return new Reference(this.getClass().getCanonicalName(), new SerializableObjectRefAddr("ActiveMQ-DEST", this), DestinationObjectFactory.class.getCanonicalName(), null); } - public void delete() throws JMSException - { - if (session != null) - { - if (session.getCoreSession().isClosed()) - { + public void delete() throws JMSException { + if (session != null) { + if (session.getCoreSession().isClosed()) { // Temporary queues will be deleted when the connection is closed.. nothing to be done then! return; } - if (queue) - { + if (queue) { session.deleteTemporaryQueue(this); } - else - { + else { session.deleteTemporaryTopic(this); } } } - public boolean isQueue() - { + public boolean isQueue() { return queue; } // Public -------------------------------------------------------- - public String getAddress() - { + public String getAddress() { return address; } - public SimpleString getSimpleAddress() - { + public SimpleString getSimpleAddress() { return simpleAddress; } - public String getName() - { + public String getName() { return name; } - public boolean isTemporary() - { + public boolean isTemporary() { return temporary; } @Override - public boolean equals(final Object o) - { - if (this == o) - { + public boolean equals(final Object o) { + if (this == o) { return true; } - if (!(o instanceof ActiveMQDestination)) - { + if (!(o instanceof ActiveMQDestination)) { return false; } @@ -410,8 +353,7 @@ public class ActiveMQDestination implements Destination, Serializable, Reference } @Override - public int hashCode() - { + public int hashCode() { return address.hashCode(); } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQJMSClientBundle.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQJMSClientBundle.java index 5989b3f1cb..f9711173ec 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQJMSClientBundle.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQJMSClientBundle.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.jms.client; - import javax.jms.IllegalStateException; import javax.jms.IllegalStateRuntimeException; import javax.jms.InvalidDestinationException; @@ -42,35 +41,35 @@ import org.jboss.logging.Messages; * so 129000 to 129999 */ @MessageBundle(projectCode = "AMQ") -public interface ActiveMQJMSClientBundle -{ +public interface ActiveMQJMSClientBundle { + ActiveMQJMSClientBundle BUNDLE = Messages.getBundle(ActiveMQJMSClientBundle.class); - @Message(id = 129000, value = "Invalid filter: {0}", format = Message.Format.MESSAGE_FORMAT) + @Message(id = 129000, value = "Invalid filter: {0}", format = Message.Format.MESSAGE_FORMAT) ActiveMQInvalidFilterExpressionException invalidFilter(@Cause Throwable e, SimpleString filter); - @Message(id = 129001, value = "Invalid Subscription Name. It is required to set the subscription name") + @Message(id = 129001, value = "Invalid Subscription Name. It is required to set the subscription name") ActiveMQIllegalStateException invalidSubscriptionName(); - @Message(id = 129002, value = "Destination {0} does not exist", format = Message.Format.MESSAGE_FORMAT) + @Message(id = 129002, value = "Destination {0} does not exist", format = Message.Format.MESSAGE_FORMAT) ActiveMQNonExistentQueueException destinationDoesNotExist(SimpleString destination); - @Message(id = 129003, value = "name cannot be null") + @Message(id = 129003, value = "name cannot be null") IllegalArgumentException nameCannotBeNull(); - @Message(id = 129004, value = "name cannot be empty") + @Message(id = 129004, value = "name cannot be empty") IllegalArgumentException nameCannotBeEmpty(); - @Message(id = 129005, value = "It is illegal to call this method from within a Message Listener") + @Message(id = 129005, value = "It is illegal to call this method from within a Message Listener") IllegalStateRuntimeException callingMethodFromListenerRuntime(); - @Message(id = 129006, value = "It is illegal to call this method from within a Message Listener") + @Message(id = 129006, value = "It is illegal to call this method from within a Message Listener") IllegalStateException callingMethodFromListener(); - @Message(id = 129007, value = "It is illegal to call this method from within a Completion Listener") + @Message(id = 129007, value = "It is illegal to call this method from within a Completion Listener") IllegalStateRuntimeException callingMethodFromCompletionListenerRuntime(); - @Message(id = 129008, value = "It is illegal to call this method from within a Completion Listener") + @Message(id = 129008, value = "It is illegal to call this method from within a Completion Listener") IllegalStateException callingMethodFromCompletionListener(); @Message(id = 129009, value = "Null {0} is not allowed", format = Message.Format.MESSAGE_FORMAT) @@ -83,7 +82,7 @@ public interface ActiveMQJMSClientBundle IllegalStateException onlyValidForByteOrStreamMessages(); @Message(id = 129012, value = "The property name ''{0}'' is not a valid java identifier.", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) JMSRuntimeException invalidJavaIdentifier(String propertyName); @Message(id = 129013, value = "Message is read-only") diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQJMSClientLogger.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQJMSClientLogger.java index 86c756de0a..7eb56cd1dd 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQJMSClientLogger.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQJMSClientLogger.java @@ -38,43 +38,43 @@ import org.jboss.logging.annotations.MessageLogger; * so an INFO message would be 121000 to 121999 */ @MessageLogger(projectCode = "AMQ") -public interface ActiveMQJMSClientLogger extends BasicLogger -{ +public interface ActiveMQJMSClientLogger extends BasicLogger { + /** * The default logger. */ ActiveMQJMSClientLogger LOGGER = Logger.getMessageLogger(ActiveMQJMSClientLogger.class, ActiveMQJMSClientLogger.class.getPackage().getName()); @LogMessage(level = Logger.Level.WARN) - @Message(id = 122000, value = "I''m closing a JMS connection you left open. Please make sure you close all JMS connections explicitly before letting them go out of scope! see stacktrace to find out where it was created" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 122000, value = "I''m closing a JMS connection you left open. Please make sure you close all JMS connections explicitly before letting them go out of scope! see stacktrace to find out where it was created", format = Message.Format.MESSAGE_FORMAT) void connectionLeftOpen(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) - @Message(id = 122001, value = "Unhandled exception thrown from onMessage" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 122001, value = "Unhandled exception thrown from onMessage", format = Message.Format.MESSAGE_FORMAT) void onMessageError(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) - @Message(id = 124000, value = "Failed to call JMS exception listener" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 124000, value = "Failed to call JMS exception listener", format = Message.Format.MESSAGE_FORMAT) void errorCallingExcListener(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) - @Message(id = 124002, value = "Queue Browser failed to create message" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 124002, value = "Queue Browser failed to create message", format = Message.Format.MESSAGE_FORMAT) void errorCreatingMessage(@Cause Throwable e); @LogMessage(level = Logger.Level.ERROR) - @Message(id = 124003, value = "Message Listener failed to prepare message for receipt" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 124003, value = "Message Listener failed to prepare message for receipt", format = Message.Format.MESSAGE_FORMAT) void errorPreparingMessageForReceipt(@Cause Throwable e); @LogMessage(level = Logger.Level.ERROR) - @Message(id = 124004, value = "Message Listener failed to process message" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 124004, value = "Message Listener failed to process message", format = Message.Format.MESSAGE_FORMAT) void errorProcessingMessage(@Cause Throwable e); @LogMessage(level = Logger.Level.ERROR) - @Message(id = 124005, value = "Message Listener failed to recover session" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 124005, value = "Message Listener failed to recover session", format = Message.Format.MESSAGE_FORMAT) void errorRecoveringSession(@Cause Throwable e); @LogMessage(level = Logger.Level.ERROR) - @Message(id = 124006, value = "Failed to call Failover listener" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 124006, value = "Failed to call Failover listener", format = Message.Format.MESSAGE_FORMAT) void errorCallingFailoverListener(@Cause Exception e); } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQJMSConnectionFactory.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQJMSConnectionFactory.java index f268b69622..ef154b0ba7 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQJMSConnectionFactory.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQJMSConnectionFactory.java @@ -23,42 +23,34 @@ import org.apache.activemq.artemis.api.core.DiscoveryGroupConfiguration; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.api.core.client.ServerLocator; - /** * {@inheritDoc} */ -public class ActiveMQJMSConnectionFactory extends ActiveMQConnectionFactory implements TopicConnectionFactory, QueueConnectionFactory -{ +public class ActiveMQJMSConnectionFactory extends ActiveMQConnectionFactory implements TopicConnectionFactory, QueueConnectionFactory { private static final long serialVersionUID = -2810634789345348326L; - public ActiveMQJMSConnectionFactory() - { + public ActiveMQJMSConnectionFactory() { super(); } - public ActiveMQJMSConnectionFactory(String uri) - { + public ActiveMQJMSConnectionFactory(String uri) { super(uri); } - public ActiveMQJMSConnectionFactory(String uri, String user, String password) - { + public ActiveMQJMSConnectionFactory(String uri, String user, String password) { super(uri, user, password); } - public ActiveMQJMSConnectionFactory(ServerLocator serverLocator) - { + public ActiveMQJMSConnectionFactory(ServerLocator serverLocator) { super(serverLocator); } - public ActiveMQJMSConnectionFactory(boolean ha, final DiscoveryGroupConfiguration groupConfiguration) - { + public ActiveMQJMSConnectionFactory(boolean ha, final DiscoveryGroupConfiguration groupConfiguration) { super(ha, groupConfiguration); } - public ActiveMQJMSConnectionFactory(boolean ha, TransportConfiguration... initialConnectors) - { + public ActiveMQJMSConnectionFactory(boolean ha, TransportConfiguration... initialConnectors) { super(ha, initialConnectors); } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQJMSConsumer.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQJMSConsumer.java index 8a2da660a1..f3ba6e246b 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQJMSConsumer.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQJMSConsumer.java @@ -23,175 +23,139 @@ import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageListener; -public class ActiveMQJMSConsumer implements JMSConsumer -{ +public class ActiveMQJMSConsumer implements JMSConsumer { private final ActiveMQJMSContext context; private final MessageConsumer consumer; - ActiveMQJMSConsumer(ActiveMQJMSContext context, MessageConsumer consumer) - { + ActiveMQJMSConsumer(ActiveMQJMSContext context, MessageConsumer consumer) { this.context = context; this.consumer = consumer; } @Override - public String getMessageSelector() - { - try - { + public String getMessageSelector() { + try { return consumer.getMessageSelector(); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public MessageListener getMessageListener() throws JMSRuntimeException - { - try - { + public MessageListener getMessageListener() throws JMSRuntimeException { + try { return consumer.getMessageListener(); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public void setMessageListener(MessageListener listener) throws JMSRuntimeException - { - try - { + public void setMessageListener(MessageListener listener) throws JMSRuntimeException { + try { consumer.setMessageListener(new MessageListenerWrapper(listener)); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public Message receive() - { - try - { + public Message receive() { + try { return context.setLastMessage(this, consumer.receive()); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public Message receive(long timeout) - { - try - { + public Message receive(long timeout) { + try { return context.setLastMessage(this, consumer.receive(timeout)); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public Message receiveNoWait() - { - try - { + public Message receiveNoWait() { + try { return context.setLastMessage(this, consumer.receiveNoWait()); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public void close() - { - try - { + public void close() { + try { consumer.close(); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public T receiveBody(Class c) - { - try - { + public T receiveBody(Class c) { + try { Message message = consumer.receive(); context.setLastMessage(ActiveMQJMSConsumer.this, message); return message == null ? null : message.getBody(c); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public T receiveBody(Class c, long timeout) - { - try - { + public T receiveBody(Class c, long timeout) { + try { Message message = consumer.receive(timeout); context.setLastMessage(ActiveMQJMSConsumer.this, message); return message == null ? null : message.getBody(c); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public T receiveBodyNoWait(Class c) - { - try - { + public T receiveBodyNoWait(Class c) { + try { Message message = consumer.receiveNoWait(); context.setLastMessage(ActiveMQJMSConsumer.this, message); return message == null ? null : message.getBody(c); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } - final class MessageListenerWrapper implements MessageListener - { + final class MessageListenerWrapper implements MessageListener { + private final MessageListener wrapped; - public MessageListenerWrapper(MessageListener wrapped) - { + public MessageListenerWrapper(MessageListener wrapped) { this.wrapped = wrapped; } @Override - public void onMessage(Message message) - { + public void onMessage(Message message) { context.setLastMessage(ActiveMQJMSConsumer.this, message); context.getThreadAwareContext().setCurrentThread(false); - try - { + try { wrapped.onMessage(message); } - finally - { + finally { context.getThreadAwareContext().clearCurrentThread(false); } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQJMSContext.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQJMSContext.java index c449e8b868..3065f27aea 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQJMSContext.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQJMSContext.java @@ -45,8 +45,8 @@ import java.io.Serializable; /** * ActiveMQ Artemis implementation of a JMSContext. */ -public class ActiveMQJMSContext implements JMSContext -{ +public class ActiveMQJMSContext implements JMSContext { + private static final boolean DEFAULT_AUTO_START = true; private final int sessionMode; @@ -64,38 +64,37 @@ public class ActiveMQJMSContext implements JMSContext private boolean xa; private boolean closed; - ActiveMQJMSContext(final ActiveMQConnectionForContext connection, final int ackMode, final boolean xa, ThreadAwareContext threadAwareContext) - { + ActiveMQJMSContext(final ActiveMQConnectionForContext connection, + final int ackMode, + final boolean xa, + ThreadAwareContext threadAwareContext) { this.connection = connection; this.sessionMode = ackMode; this.xa = xa; this.threadAwareContext = threadAwareContext; } - public ActiveMQJMSContext(ActiveMQConnectionForContext connection, int ackMode, ThreadAwareContext threadAwareContext) - { + public ActiveMQJMSContext(ActiveMQConnectionForContext connection, + int ackMode, + ThreadAwareContext threadAwareContext) { this(connection, ackMode, false, threadAwareContext); } - public ActiveMQJMSContext(ActiveMQConnectionForContext connection, ThreadAwareContext threadAwareContext) - { + public ActiveMQJMSContext(ActiveMQConnectionForContext connection, ThreadAwareContext threadAwareContext) { this(connection, SESSION_TRANSACTED, true, threadAwareContext); } // XAJMSContext implementation ------------------------------------- - public JMSContext getContext() - { + public JMSContext getContext() { return this; } - public Session getSession() - { + public Session getSession() { return session; } - public XAResource getXAResource() - { + public XAResource getXAResource() { checkSession(); return ((XASession) session).getXAResource(); } @@ -103,29 +102,23 @@ public class ActiveMQJMSContext implements JMSContext // JMSContext implementation ------------------------------------- @Override - public JMSContext createContext(int sessionMode) - { + public JMSContext createContext(int sessionMode) { return connection.createContext(sessionMode); } @Override - public JMSProducer createProducer() - { + public JMSProducer createProducer() { checkSession(); - try - { + try { return new ActiveMQJMSProducer(this, getInnerProducer()); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } - private synchronized MessageProducer getInnerProducer() throws JMSException - { - if (innerProducer == null) - { + private synchronized MessageProducer getInnerProducer() throws JMSException { + if (innerProducer == null) { innerProducer = session.createProducer(null); } @@ -135,29 +128,21 @@ public class ActiveMQJMSContext implements JMSContext /** * */ - private void checkSession() - { - if (session == null) - { - synchronized (this) - { + private void checkSession() { + if (session == null) { + synchronized (this) { if (closed) throw new IllegalStateRuntimeException("Context is closed"); - if (session == null) - { - try - { - if (xa) - { + if (session == null) { + try { + if (xa) { session = ((XAConnection) connection).createXASession(); } - else - { + else { session = connection.createSession(sessionMode); } } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @@ -166,567 +151,451 @@ public class ActiveMQJMSContext implements JMSContext } @Override - public String getClientID() - { - try - { + public String getClientID() { + try { return connection.getClientID(); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public void setClientID(String clientID) - { - try - { + public void setClientID(String clientID) { + try { connection.setClientID(clientID); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public ConnectionMetaData getMetaData() - { - try - { + public ConnectionMetaData getMetaData() { + try { return connection.getMetaData(); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public ExceptionListener getExceptionListener() - { - try - { + public ExceptionListener getExceptionListener() { + try { return connection.getExceptionListener(); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public void setExceptionListener(ExceptionListener listener) - { - try - { + public void setExceptionListener(ExceptionListener listener) { + try { connection.setExceptionListener(listener); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public void start() - { - try - { + public void start() { + try { connection.start(); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public void stop() - { + public void stop() { threadAwareContext.assertNotMessageListenerThreadRuntime(); - try - { + try { connection.stop(); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public void setAutoStart(boolean autoStart) - { + public void setAutoStart(boolean autoStart) { this.autoStart = autoStart; } @Override - public boolean getAutoStart() - { + public boolean getAutoStart() { return autoStart; } @Override - public void close() - { + public void close() { threadAwareContext.assertNotCompletionListenerThreadRuntime(); threadAwareContext.assertNotMessageListenerThreadRuntime(); - try - { - synchronized (this) - { + try { + synchronized (this) { if (session != null) session.close(); connection.closeFromContext(); closed = true; } } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public BytesMessage createBytesMessage() - { + public BytesMessage createBytesMessage() { checkSession(); - try - { + try { return session.createBytesMessage(); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public MapMessage createMapMessage() - { + public MapMessage createMapMessage() { checkSession(); - try - { + try { return session.createMapMessage(); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public Message createMessage() - { + public Message createMessage() { checkSession(); - try - { + try { return session.createMessage(); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public ObjectMessage createObjectMessage() - { + public ObjectMessage createObjectMessage() { checkSession(); - try - { + try { return session.createObjectMessage(); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public ObjectMessage createObjectMessage(Serializable object) - { + public ObjectMessage createObjectMessage(Serializable object) { checkSession(); - try - { + try { return session.createObjectMessage(object); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public StreamMessage createStreamMessage() - { + public StreamMessage createStreamMessage() { checkSession(); - try - { + try { return session.createStreamMessage(); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public TextMessage createTextMessage() - { + public TextMessage createTextMessage() { checkSession(); - try - { + try { return session.createTextMessage(); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public TextMessage createTextMessage(String text) - { + public TextMessage createTextMessage(String text) { checkSession(); - try - { + try { return session.createTextMessage(text); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public boolean getTransacted() - { + public boolean getTransacted() { checkSession(); - try - { + try { return session.getTransacted(); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public int getSessionMode() - { + public int getSessionMode() { return sessionMode; } @Override - public void commit() - { + public void commit() { threadAwareContext.assertNotCompletionListenerThreadRuntime(); checkSession(); - try - { + try { session.commit(); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public void rollback() - { + public void rollback() { threadAwareContext.assertNotCompletionListenerThreadRuntime(); checkSession(); - try - { + try { session.rollback(); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public void recover() - { + public void recover() { checkSession(); - try - { + try { session.recover(); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public JMSConsumer createConsumer(Destination destination) - { + public JMSConsumer createConsumer(Destination destination) { checkSession(); - try - { + try { ActiveMQJMSConsumer consumer = new ActiveMQJMSConsumer(this, session.createConsumer(destination)); checkAutoStart(); return consumer; } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public JMSConsumer createConsumer(Destination destination, String messageSelector) - { + public JMSConsumer createConsumer(Destination destination, String messageSelector) { checkSession(); - try - { + try { ActiveMQJMSConsumer consumer = new ActiveMQJMSConsumer(this, session.createConsumer(destination, messageSelector)); checkAutoStart(); return consumer; } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public JMSConsumer createConsumer(Destination destination, String messageSelector, boolean noLocal) - { + public JMSConsumer createConsumer(Destination destination, String messageSelector, boolean noLocal) { checkSession(); - try - { + try { ActiveMQJMSConsumer consumer = new ActiveMQJMSConsumer(this, session.createConsumer(destination, messageSelector, noLocal)); checkAutoStart(); return consumer; } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public Queue createQueue(String queueName) - { + public Queue createQueue(String queueName) { checkSession(); - try - { + try { return session.createQueue(queueName); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public Topic createTopic(String topicName) - { + public Topic createTopic(String topicName) { checkSession(); - try - { + try { return session.createTopic(topicName); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public JMSConsumer createDurableConsumer(Topic topic, String name) - { + public JMSConsumer createDurableConsumer(Topic topic, String name) { checkSession(); - try - { + try { ActiveMQJMSConsumer consumer = new ActiveMQJMSConsumer(this, session.createDurableConsumer(topic, name)); checkAutoStart(); return consumer; } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public JMSConsumer createDurableConsumer(Topic topic, String name, String messageSelector, boolean noLocal) - { + public JMSConsumer createDurableConsumer(Topic topic, String name, String messageSelector, boolean noLocal) { checkSession(); - try - { + try { ActiveMQJMSConsumer consumer = new ActiveMQJMSConsumer(this, session.createDurableConsumer(topic, name, messageSelector, noLocal)); checkAutoStart(); return consumer; } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public JMSConsumer createSharedDurableConsumer(Topic topic, String name) - { + public JMSConsumer createSharedDurableConsumer(Topic topic, String name) { checkSession(); - try - { + try { ActiveMQJMSConsumer consumer = new ActiveMQJMSConsumer(this, session.createSharedDurableConsumer(topic, name)); checkAutoStart(); return consumer; } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public JMSConsumer createSharedDurableConsumer(Topic topic, String name, String messageSelector) - { + public JMSConsumer createSharedDurableConsumer(Topic topic, String name, String messageSelector) { checkSession(); - try - { + try { ActiveMQJMSConsumer consumer = new ActiveMQJMSConsumer(this, session.createSharedDurableConsumer(topic, name, messageSelector)); checkAutoStart(); return consumer; } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public JMSConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName) - { + public JMSConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName) { checkSession(); - try - { + try { ActiveMQJMSConsumer consumer = new ActiveMQJMSConsumer(this, session.createSharedConsumer(topic, sharedSubscriptionName)); checkAutoStart(); return consumer; } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public JMSConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName, String messageSelector) - { + public JMSConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName, String messageSelector) { checkSession(); - try - { + try { ActiveMQJMSConsumer consumer = new ActiveMQJMSConsumer(this, session.createSharedConsumer(topic, sharedSubscriptionName, messageSelector)); checkAutoStart(); return consumer; } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public QueueBrowser createBrowser(Queue queue) - { + public QueueBrowser createBrowser(Queue queue) { checkSession(); - try - { + try { QueueBrowser browser = session.createBrowser(queue); checkAutoStart(); return browser; } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public QueueBrowser createBrowser(Queue queue, String messageSelector) - { + public QueueBrowser createBrowser(Queue queue, String messageSelector) { checkSession(); - try - { + try { QueueBrowser browser = session.createBrowser(queue, messageSelector); checkAutoStart(); return browser; } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public TemporaryQueue createTemporaryQueue() - { + public TemporaryQueue createTemporaryQueue() { checkSession(); - try - { + try { return session.createTemporaryQueue(); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public TemporaryTopic createTemporaryTopic() - { + public TemporaryTopic createTemporaryTopic() { checkSession(); - try - { + try { return session.createTemporaryTopic(); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public void unsubscribe(String name) - { + public void unsubscribe(String name) { checkSession(); - try - { + try { session.unsubscribe(name); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public void acknowledge() - { + public void acknowledge() { checkSession(); if (closed) throw new IllegalStateRuntimeException("Context is closed"); - try - { - if (lastMessagesWaitingAck != null) - { + try { + if (lastMessagesWaitingAck != null) { lastMessagesWaitingAck.acknowledge(); } } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @@ -737,17 +606,14 @@ public class ActiveMQJMSContext implements JMSContext * * @return */ - public Session getUsedSession() - { + public Session getUsedSession() { return this.session; } - private synchronized void checkAutoStart() throws JMSException - { + private synchronized void checkAutoStart() throws JMSException { if (closed) throw new IllegalStateRuntimeException("Context is closed"); - if (autoStart) - { + if (autoStart) { connection.start(); } } @@ -755,17 +621,14 @@ public class ActiveMQJMSContext implements JMSContext /** * this is to ensure Context.acknowledge would work on ClientACK */ - Message setLastMessage(final JMSConsumer consumer, final Message lastMessageReceived) - { - if (sessionMode == CLIENT_ACKNOWLEDGE) - { + Message setLastMessage(final JMSConsumer consumer, final Message lastMessageReceived) { + if (sessionMode == CLIENT_ACKNOWLEDGE) { lastMessagesWaitingAck = lastMessageReceived; } return lastMessageReceived; } - public ThreadAwareContext getThreadAwareContext() - { + public ThreadAwareContext getThreadAwareContext() { return threadAwareContext; } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQJMSProducer.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQJMSProducer.java index 538b43d3bb..cd86e8619d 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQJMSProducer.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQJMSProducer.java @@ -47,8 +47,8 @@ import org.apache.activemq.artemis.utils.TypedProperties; * {@link MessageProducer}. IF the user is using the producer in async mode, this may lead to races. * We allow/tolerate this because these are just optional optimizations. */ -public final class ActiveMQJMSProducer implements JMSProducer -{ +public final class ActiveMQJMSProducer implements JMSProducer { + private final ActiveMQJMSContext context; private final MessageProducer producer; private final TypedProperties properties = new TypedProperties(); @@ -64,53 +64,42 @@ public final class ActiveMQJMSProducer implements JMSProducer private byte[] jmsHeaderCorrelationIDAsBytes; private String jmsHeaderType; - ActiveMQJMSProducer(ActiveMQJMSContext context, MessageProducer producer) - { + ActiveMQJMSProducer(ActiveMQJMSContext context, MessageProducer producer) { this.context = context; this.producer = producer; } @Override - public JMSProducer send(Destination destination, Message message) - { - if (message == null) - { + public JMSProducer send(Destination destination, Message message) { + if (message == null) { throw new MessageFormatRuntimeException("null message"); } - try - { - if (jmsHeaderCorrelationID != null) - { + try { + if (jmsHeaderCorrelationID != null) { message.setJMSCorrelationID(jmsHeaderCorrelationID); } - if (jmsHeaderCorrelationIDAsBytes != null && jmsHeaderCorrelationIDAsBytes.length > 0) - { + if (jmsHeaderCorrelationIDAsBytes != null && jmsHeaderCorrelationIDAsBytes.length > 0) { message.setJMSCorrelationIDAsBytes(jmsHeaderCorrelationIDAsBytes); } - if (jmsHeaderReplyTo != null) - { + if (jmsHeaderReplyTo != null) { message.setJMSReplyTo(jmsHeaderReplyTo); } - if (jmsHeaderType != null) - { + if (jmsHeaderType != null) { message.setJMSType(jmsHeaderType); } // XXX HORNETQ-1209 "JMS 2.0" can this be a foreign msg? // if so, then "SimpleString" properties will trigger an error. setProperties(message); - if (completionListener != null) - { + if (completionListener != null) { CompletionListener wrapped = new CompletionListenerWrapper(completionListener); producer.send(destination, message, wrapped); } - else - { + else { producer.send(destination, message); } } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } return this; @@ -122,83 +111,64 @@ public final class ActiveMQJMSProducer implements JMSProducer * @param message * @throws JMSException */ - private void setProperties(Message message) throws JMSException - { - for (SimpleString name : properties.getPropertyNames()) - { + private void setProperties(Message message) throws JMSException { + for (SimpleString name : properties.getPropertyNames()) { message.setObjectProperty(name.toString(), properties.getProperty(name)); } } @Override - public JMSProducer send(Destination destination, String body) - { + public JMSProducer send(Destination destination, String body) { TextMessage message = context.createTextMessage(body); send(destination, message); return this; } @Override - public JMSProducer send(Destination destination, Map body) - { + public JMSProducer send(Destination destination, Map body) { MapMessage message = context.createMapMessage(); - if (body != null) - { - try - { - for (Entry entry : body.entrySet()) - { + if (body != null) { + try { + for (Entry entry : body.entrySet()) { final String name = entry.getKey(); final Object v = entry.getValue(); - if (v instanceof String) - { + if (v instanceof String) { message.setString(name, (String) v); } - else if (v instanceof Long) - { + else if (v instanceof Long) { message.setLong(name, (Long) v); } - else if (v instanceof Double) - { + else if (v instanceof Double) { message.setDouble(name, (Double) v); } - else if (v instanceof Integer) - { + else if (v instanceof Integer) { message.setInt(name, (Integer) v); } - else if (v instanceof Character) - { + else if (v instanceof Character) { message.setChar(name, (Character) v); } - else if (v instanceof Short) - { + else if (v instanceof Short) { message.setShort(name, (Short) v); } - else if (v instanceof Boolean) - { + else if (v instanceof Boolean) { message.setBoolean(name, (Boolean) v); } - else if (v instanceof Float) - { + else if (v instanceof Float) { message.setFloat(name, (Float) v); } - else if (v instanceof Byte) - { + else if (v instanceof Byte) { message.setByte(name, (Byte) v); } - else if (v instanceof byte[]) - { + else if (v instanceof byte[]) { byte[] array = (byte[]) v; message.setBytes(name, array, 0, array.length); } - else - { + else { message.setObject(name, v); } } } - catch (JMSException e) - { + catch (JMSException e) { throw new MessageFormatRuntimeException(e.getMessage()); } } @@ -207,17 +177,13 @@ public final class ActiveMQJMSProducer implements JMSProducer } @Override - public JMSProducer send(Destination destination, byte[] body) - { + public JMSProducer send(Destination destination, byte[] body) { BytesMessage message = context.createBytesMessage(); - if (body != null) - { - try - { + if (body != null) { + try { message.writeBytes(body); } - catch (JMSException e) - { + catch (JMSException e) { throw new MessageFormatRuntimeException(e.getMessage()); } } @@ -226,76 +192,60 @@ public final class ActiveMQJMSProducer implements JMSProducer } @Override - public JMSProducer send(Destination destination, Serializable body) - { + public JMSProducer send(Destination destination, Serializable body) { ObjectMessage message = context.createObjectMessage(body); send(destination, message); return this; } @Override - public JMSProducer setDisableMessageID(boolean value) - { - try - { + public JMSProducer setDisableMessageID(boolean value) { + try { producer.setDisableMessageID(value); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } return this; } @Override - public boolean getDisableMessageID() - { - try - { + public boolean getDisableMessageID() { + try { return producer.getDisableMessageID(); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public JMSProducer setDisableMessageTimestamp(boolean value) - { - try - { + public JMSProducer setDisableMessageTimestamp(boolean value) { + try { producer.setDisableMessageTimestamp(value); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } return this; } @Override - public boolean getDisableMessageTimestamp() - { - try - { + public boolean getDisableMessageTimestamp() { + try { return producer.getDisableMessageTimestamp(); } - catch (JMSException e) - { + catch (JMSException e) { throw JmsExceptionUtils.convertToRuntimeException(e); } } @Override - public JMSProducer setDeliveryMode(int deliveryMode) - { - try - { + public JMSProducer setDeliveryMode(int deliveryMode) { + try { producer.setDeliveryMode(deliveryMode); } - catch (JMSException e) - { + catch (JMSException e) { JMSRuntimeException e2 = new JMSRuntimeException(e.getMessage()); e2.initCause(e); throw e2; @@ -304,14 +254,11 @@ public final class ActiveMQJMSProducer implements JMSProducer } @Override - public int getDeliveryMode() - { - try - { + public int getDeliveryMode() { + try { return producer.getDeliveryMode(); } - catch (JMSException e) - { + catch (JMSException e) { JMSRuntimeException e2 = new JMSRuntimeException(e.getMessage()); e2.initCause(e); throw e2; @@ -319,14 +266,11 @@ public final class ActiveMQJMSProducer implements JMSProducer } @Override - public JMSProducer setPriority(int priority) - { - try - { + public JMSProducer setPriority(int priority) { + try { producer.setPriority(priority); } - catch (JMSException e) - { + catch (JMSException e) { JMSRuntimeException e2 = new JMSRuntimeException(e.getMessage()); e2.initCause(e); throw e2; @@ -335,14 +279,11 @@ public final class ActiveMQJMSProducer implements JMSProducer } @Override - public int getPriority() - { - try - { + public int getPriority() { + try { return producer.getPriority(); } - catch (JMSException e) - { + catch (JMSException e) { JMSRuntimeException e2 = new JMSRuntimeException(e.getMessage()); e2.initCause(e); throw e2; @@ -350,15 +291,12 @@ public final class ActiveMQJMSProducer implements JMSProducer } @Override - public JMSProducer setTimeToLive(long timeToLive) - { - try - { + public JMSProducer setTimeToLive(long timeToLive) { + try { producer.setTimeToLive(timeToLive); return this; } - catch (JMSException e) - { + catch (JMSException e) { JMSRuntimeException e2 = new JMSRuntimeException(e.getMessage()); e2.initCause(e); throw e2; @@ -366,16 +304,13 @@ public final class ActiveMQJMSProducer implements JMSProducer } @Override - public long getTimeToLive() - { + public long getTimeToLive() { long timeToLive = 0; - try - { + try { timeToLive = producer.getTimeToLive(); return timeToLive; } - catch (JMSException e) - { + catch (JMSException e) { JMSRuntimeException e2 = new JMSRuntimeException(e.getMessage()); e2.initCause(e); throw e2; @@ -383,15 +318,12 @@ public final class ActiveMQJMSProducer implements JMSProducer } @Override - public JMSProducer setDeliveryDelay(long deliveryDelay) - { - try - { + public JMSProducer setDeliveryDelay(long deliveryDelay) { + try { producer.setDeliveryDelay(deliveryDelay); return this; } - catch (JMSException e) - { + catch (JMSException e) { JMSRuntimeException e2 = new JMSRuntimeException(e.getMessage()); e2.initCause(e); throw e2; @@ -399,91 +331,78 @@ public final class ActiveMQJMSProducer implements JMSProducer } @Override - public long getDeliveryDelay() - { + public long getDeliveryDelay() { long deliveryDelay = 0; - try - { + try { deliveryDelay = producer.getDeliveryDelay(); } - catch (Exception ignored) - { + catch (Exception ignored) { } return deliveryDelay; } @Override - public JMSProducer setAsync(CompletionListener completionListener) - { + public JMSProducer setAsync(CompletionListener completionListener) { this.completionListener = completionListener; return this; } @Override - public CompletionListener getAsync() - { + public CompletionListener getAsync() { return completionListener; } @Override - public JMSProducer setProperty(String name, boolean value) - { + public JMSProducer setProperty(String name, boolean value) { checkName(name); properties.putBooleanProperty(new SimpleString(name), value); return this; } @Override - public JMSProducer setProperty(String name, byte value) - { + public JMSProducer setProperty(String name, byte value) { checkName(name); properties.putByteProperty(new SimpleString(name), value); return this; } @Override - public JMSProducer setProperty(String name, short value) - { + public JMSProducer setProperty(String name, short value) { checkName(name); properties.putShortProperty(new SimpleString(name), value); return this; } @Override - public JMSProducer setProperty(String name, int value) - { + public JMSProducer setProperty(String name, int value) { checkName(name); properties.putIntProperty(new SimpleString(name), value); return this; } @Override - public JMSProducer setProperty(String name, long value) - { + public JMSProducer setProperty(String name, long value) { checkName(name); properties.putLongProperty(new SimpleString(name), value); return this; } @Override - public JMSProducer setProperty(String name, float value) - { + public JMSProducer setProperty(String name, float value) { checkName(name); properties.putFloatProperty(new SimpleString(name), value); return this; } @Override - public JMSProducer setProperty(String name, double value) - { + public JMSProducer setProperty(String name, double value) { checkName(name); properties.putDoubleProperty(new SimpleString(name), value); return this; } @Override - public JMSProducer setProperty(String name, String value) - { + public JMSProducer setProperty(String name, String value) { checkName(name); SimpleString key = new SimpleString(name); properties.putSimpleStringProperty(key, new SimpleString(value)); @@ -492,212 +411,166 @@ public final class ActiveMQJMSProducer implements JMSProducer } @Override - public JMSProducer setProperty(String name, Object value) - { + public JMSProducer setProperty(String name, Object value) { checkName(name); - try - { + try { TypedProperties.setObjectProperty(new SimpleString(name), value, properties); } - catch (ActiveMQPropertyConversionException amqe) - { + catch (ActiveMQPropertyConversionException amqe) { throw new MessageFormatRuntimeException(amqe.getMessage()); } - catch (RuntimeException e) - { + catch (RuntimeException e) { throw new JMSRuntimeException(e.getMessage()); } return this; } @Override - public JMSProducer clearProperties() - { - try - { + public JMSProducer clearProperties() { + try { stringPropertyNames.clear(); properties.clear(); } - catch (RuntimeException e) - { + catch (RuntimeException e) { throw new JMSRuntimeException(e.getMessage()); } return this; } @Override - public boolean propertyExists(String name) - { + public boolean propertyExists(String name) { return properties.containsProperty(new SimpleString(name)); } @Override - public boolean getBooleanProperty(String name) - { - try - { + public boolean getBooleanProperty(String name) { + try { return properties.getBooleanProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException ce) - { + catch (ActiveMQPropertyConversionException ce) { throw new MessageFormatRuntimeException(ce.getMessage()); } - catch (RuntimeException e) - { + catch (RuntimeException e) { throw new JMSRuntimeException(e.getMessage()); } } @Override - public byte getByteProperty(String name) - { - try - { + public byte getByteProperty(String name) { + try { return properties.getByteProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException ce) - { + catch (ActiveMQPropertyConversionException ce) { throw new MessageFormatRuntimeException(ce.getMessage()); } } @Override - public short getShortProperty(String name) - { - try - { + public short getShortProperty(String name) { + try { return properties.getShortProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException ce) - { + catch (ActiveMQPropertyConversionException ce) { throw new MessageFormatRuntimeException(ce.getMessage()); } } @Override - public int getIntProperty(String name) - { - try - { + public int getIntProperty(String name) { + try { return properties.getIntProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException ce) - { + catch (ActiveMQPropertyConversionException ce) { throw new MessageFormatRuntimeException(ce.getMessage()); } } @Override - public long getLongProperty(String name) - { - try - { + public long getLongProperty(String name) { + try { return properties.getLongProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException ce) - { + catch (ActiveMQPropertyConversionException ce) { throw new MessageFormatRuntimeException(ce.getMessage()); } } @Override - public float getFloatProperty(String name) - { - try - { + public float getFloatProperty(String name) { + try { return properties.getFloatProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException ce) - { + catch (ActiveMQPropertyConversionException ce) { throw new MessageFormatRuntimeException(ce.getMessage()); } } @Override - public double getDoubleProperty(String name) - { - try - { + public double getDoubleProperty(String name) { + try { return properties.getDoubleProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException ce) - { + catch (ActiveMQPropertyConversionException ce) { throw new MessageFormatRuntimeException(ce.getMessage()); } } @Override - public String getStringProperty(String name) - { - try - { + public String getStringProperty(String name) { + try { SimpleString prop = properties.getSimpleStringProperty(new SimpleString(name)); if (prop == null) return null; return prop.toString(); } - catch (ActiveMQPropertyConversionException ce) - { + catch (ActiveMQPropertyConversionException ce) { throw new MessageFormatRuntimeException(ce.getMessage()); } - catch (RuntimeException e) - { + catch (RuntimeException e) { throw new JMSRuntimeException(e.getMessage()); } } @Override - public Object getObjectProperty(String name) - { - try - { + public Object getObjectProperty(String name) { + try { SimpleString key = new SimpleString(name); Object property = properties.getProperty(key); - if (stringPropertyNames.contains(key)) - { + if (stringPropertyNames.contains(key)) { property = property.toString(); } return property; } - catch (ActiveMQPropertyConversionException ce) - { + catch (ActiveMQPropertyConversionException ce) { throw new MessageFormatRuntimeException(ce.getMessage()); } - catch (RuntimeException e) - { + catch (RuntimeException e) { throw new JMSRuntimeException(e.getMessage()); } } @Override - public Set getPropertyNames() - { - try - { + public Set getPropertyNames() { + try { Set simplePropNames = properties.getPropertyNames(); Set propNames = new HashSet(simplePropNames.size()); - for (SimpleString str : simplePropNames) - { + for (SimpleString str : simplePropNames) { propNames.add(str.toString()); } return propNames; } - catch (ActiveMQPropertyConversionException ce) - { + catch (ActiveMQPropertyConversionException ce) { throw new MessageFormatRuntimeException(ce.getMessage()); } - catch (RuntimeException e) - { + catch (RuntimeException e) { throw new JMSRuntimeException(e.getMessage()); } } @Override - public JMSProducer setJMSCorrelationIDAsBytes(byte[] correlationID) - { - if (correlationID == null || correlationID.length == 0) - { + public JMSProducer setJMSCorrelationIDAsBytes(byte[] correlationID) { + if (correlationID == null || correlationID.length == 0) { throw new JMSRuntimeException("Please specify a non-zero length byte[]"); } jmsHeaderCorrelationIDAsBytes = Arrays.copyOf(correlationID, correlationID.length); @@ -705,96 +578,78 @@ public final class ActiveMQJMSProducer implements JMSProducer } @Override - public byte[] getJMSCorrelationIDAsBytes() - { + public byte[] getJMSCorrelationIDAsBytes() { return Arrays.copyOf(jmsHeaderCorrelationIDAsBytes, jmsHeaderCorrelationIDAsBytes.length); } @Override - public JMSProducer setJMSCorrelationID(String correlationID) - { + public JMSProducer setJMSCorrelationID(String correlationID) { jmsHeaderCorrelationID = correlationID; return this; } @Override - public String getJMSCorrelationID() - { + public String getJMSCorrelationID() { return jmsHeaderCorrelationID; } @Override - public JMSProducer setJMSType(String type) - { + public JMSProducer setJMSType(String type) { jmsHeaderType = type; return this; } @Override - public String getJMSType() - { + public String getJMSType() { return jmsHeaderType; } @Override - public JMSProducer setJMSReplyTo(Destination replyTo) - { + public JMSProducer setJMSReplyTo(Destination replyTo) { jmsHeaderReplyTo = replyTo; return this; } @Override - public Destination getJMSReplyTo() - { + public Destination getJMSReplyTo() { return jmsHeaderReplyTo; } - private void checkName(String name) - { - if (name == null) - { + private void checkName(String name) { + if (name == null) { throw ActiveMQJMSClientBundle.BUNDLE.nameCannotBeNull(); } - if (name.equals("")) - { + if (name.equals("")) { throw ActiveMQJMSClientBundle.BUNDLE.nameCannotBeEmpty(); } } - final class CompletionListenerWrapper implements CompletionListener - { + final class CompletionListenerWrapper implements CompletionListener { private final CompletionListener wrapped; - public CompletionListenerWrapper(CompletionListener wrapped) - { + public CompletionListenerWrapper(CompletionListener wrapped) { this.wrapped = wrapped; } @Override - public void onCompletion(Message message) - { + public void onCompletion(Message message) { context.getThreadAwareContext().setCurrentThread(true); - try - { + try { wrapped.onCompletion(message); } - finally - { + finally { context.getThreadAwareContext().clearCurrentThread(true); } } @Override - public void onException(Message message, Exception exception) - { + public void onException(Message message, Exception exception) { context.getThreadAwareContext().setCurrentThread(true); - try - { + try { wrapped.onException(message, exception); } - finally - { + finally { context.getThreadAwareContext().clearCurrentThread(true); } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQMapMessage.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQMapMessage.java index 44b19aa947..35ee0e465d 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQMapMessage.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQMapMessage.java @@ -32,15 +32,13 @@ import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.utils.TypedProperties; - import static org.apache.activemq.artemis.reader.MapMessageUtil.writeBodyMap; import static org.apache.activemq.artemis.reader.MapMessageUtil.readBodyMap; /** * ActiveMQ Artemis implementation of a JMS MapMessage. */ -public final class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage -{ +public final class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { // Constants ----------------------------------------------------- public static final byte TYPE = Message.MAP_TYPE; @@ -58,8 +56,7 @@ public final class ActiveMQMapMessage extends ActiveMQMessage implements MapMess /* * This constructor is used to construct messages prior to sending */ - protected ActiveMQMapMessage(final ClientSession session) - { + protected ActiveMQMapMessage(final ClientSession session) { super(ActiveMQMapMessage.TYPE, session); invalid = true; @@ -68,15 +65,13 @@ public final class ActiveMQMapMessage extends ActiveMQMessage implements MapMess /* * This constructor is used during reading */ - protected ActiveMQMapMessage(final ClientMessage message, final ClientSession session) - { + protected ActiveMQMapMessage(final ClientMessage message, final ClientSession session) { super(message, session); invalid = false; } - public ActiveMQMapMessage() - { + public ActiveMQMapMessage() { invalid = false; } @@ -86,12 +81,10 @@ public final class ActiveMQMapMessage extends ActiveMQMessage implements MapMess * @param foreign * @throws JMSException */ - public ActiveMQMapMessage(final MapMessage foreign, final ClientSession session) throws JMSException - { + public ActiveMQMapMessage(final MapMessage foreign, final ClientSession session) throws JMSException { super(foreign, ActiveMQMapMessage.TYPE, session); Enumeration names = foreign.getMapNames(); - while (names.hasMoreElements()) - { + while (names.hasMoreElements()) { String name = (String) names.nextElement(); Object obj = foreign.getObject(name); setObject(name, obj); @@ -101,88 +94,75 @@ public final class ActiveMQMapMessage extends ActiveMQMessage implements MapMess // Public -------------------------------------------------------- @Override - public byte getType() - { + public byte getType() { return ActiveMQMapMessage.TYPE; } // MapMessage implementation ------------------------------------- - public void setBoolean(final String name, final boolean value) throws JMSException - { + public void setBoolean(final String name, final boolean value) throws JMSException { checkName(name); map.putBooleanProperty(new SimpleString(name), value); invalid = true; } - public void setByte(final String name, final byte value) throws JMSException - { + public void setByte(final String name, final byte value) throws JMSException { checkName(name); map.putByteProperty(new SimpleString(name), value); invalid = true; } - public void setShort(final String name, final short value) throws JMSException - { + public void setShort(final String name, final short value) throws JMSException { checkName(name); map.putShortProperty(new SimpleString(name), value); invalid = true; } - public void setChar(final String name, final char value) throws JMSException - { + public void setChar(final String name, final char value) throws JMSException { checkName(name); map.putCharProperty(new SimpleString(name), value); invalid = true; } - public void setInt(final String name, final int value) throws JMSException - { + public void setInt(final String name, final int value) throws JMSException { checkName(name); map.putIntProperty(new SimpleString(name), value); invalid = true; } - public void setLong(final String name, final long value) throws JMSException - { + public void setLong(final String name, final long value) throws JMSException { checkName(name); map.putLongProperty(new SimpleString(name), value); invalid = true; } - public void setFloat(final String name, final float value) throws JMSException - { + public void setFloat(final String name, final float value) throws JMSException { checkName(name); map.putFloatProperty(new SimpleString(name), value); invalid = true; } - public void setDouble(final String name, final double value) throws JMSException - { + public void setDouble(final String name, final double value) throws JMSException { checkName(name); map.putDoubleProperty(new SimpleString(name), value); invalid = true; } - public void setString(final String name, final String value) throws JMSException - { + public void setString(final String name, final String value) throws JMSException { checkName(name); map.putSimpleStringProperty(new SimpleString(name), value == null ? null : new SimpleString(value)); invalid = true; } - public void setBytes(final String name, final byte[] value) throws JMSException - { + public void setBytes(final String name, final byte[] value) throws JMSException { checkName(name); map.putBytesProperty(new SimpleString(name), value); invalid = true; } - public void setBytes(final String name, final byte[] value, final int offset, final int length) throws JMSException - { + public void setBytes(final String name, final byte[] value, final int offset, final int length) throws JMSException { checkName(name); - if (offset + length > value.length) - { + if (offset + length > value.length) { throw new JMSException("Invalid offset/length"); } byte[] newBytes = new byte[length]; @@ -191,184 +171,142 @@ public final class ActiveMQMapMessage extends ActiveMQMessage implements MapMess invalid = true; } - public void setObject(final String name, final Object value) throws JMSException - { + public void setObject(final String name, final Object value) throws JMSException { checkName(name); - try - { + try { TypedProperties.setObjectProperty(new SimpleString(name), value, map); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } invalid = true; } - public boolean getBoolean(final String name) throws JMSException - { - try - { + public boolean getBoolean(final String name) throws JMSException { + try { return map.getBooleanProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public byte getByte(final String name) throws JMSException - { - try - { + public byte getByte(final String name) throws JMSException { + try { return map.getByteProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public short getShort(final String name) throws JMSException - { - try - { + public short getShort(final String name) throws JMSException { + try { return map.getShortProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public char getChar(final String name) throws JMSException - { - try - { + public char getChar(final String name) throws JMSException { + try { return map.getCharProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public int getInt(final String name) throws JMSException - { - try - { + public int getInt(final String name) throws JMSException { + try { return map.getIntProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public long getLong(final String name) throws JMSException - { - try - { + public long getLong(final String name) throws JMSException { + try { return map.getLongProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public float getFloat(final String name) throws JMSException - { - try - { + public float getFloat(final String name) throws JMSException { + try { return map.getFloatProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public double getDouble(final String name) throws JMSException - { - try - { + public double getDouble(final String name) throws JMSException { + try { return map.getDoubleProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public String getString(final String name) throws JMSException - { - try - { + public String getString(final String name) throws JMSException { + try { SimpleString str = map.getSimpleStringProperty(new SimpleString(name)); - if (str == null) - { + if (str == null) { return null; } - else - { + else { return str.toString(); } } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public byte[] getBytes(final String name) throws JMSException - { - try - { + public byte[] getBytes(final String name) throws JMSException { + try { return map.getBytesProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public Object getObject(final String name) throws JMSException - { + public Object getObject(final String name) throws JMSException { Object val = map.getProperty(new SimpleString(name)); - if (val instanceof SimpleString) - { + if (val instanceof SimpleString) { val = ((SimpleString) val).toString(); } return val; } - public Enumeration getMapNames() throws JMSException - { + public Enumeration getMapNames() throws JMSException { Set simplePropNames = map.getPropertyNames(); Set propNames = new HashSet(simplePropNames.size()); - for (SimpleString str : simplePropNames) - { + for (SimpleString str : simplePropNames) { propNames.add(str.toString()); } return Collections.enumeration(propNames); } - public boolean itemExists(final String name) throws JMSException - { + public boolean itemExists(final String name) throws JMSException { return map.containsProperty(new SimpleString(name)); } - // ActiveMQRAMessage overrides ---------------------------------------- @Override - public void clearBody() throws JMSException - { + public void clearBody() throws JMSException { super.clearBody(); map.clear(); @@ -377,10 +315,8 @@ public final class ActiveMQMapMessage extends ActiveMQMessage implements MapMess } @Override - public void doBeforeSend() throws Exception - { - if (invalid) - { + public void doBeforeSend() throws Exception { + if (invalid) { writeBodyMap(message, map); invalid = false; } @@ -389,8 +325,7 @@ public final class ActiveMQMapMessage extends ActiveMQMessage implements MapMess } @Override - public void doBeforeReceive() throws ActiveMQException - { + public void doBeforeReceive() throws ActiveMQException { super.doBeforeReceive(); readBodyMap(message, map); @@ -407,32 +342,25 @@ public final class ActiveMQMapMessage extends ActiveMQMessage implements MapMess * * @param name the name */ - private void checkName(final String name) throws JMSException - { + private void checkName(final String name) throws JMSException { checkWrite(); - if (name == null) - { + if (name == null) { throw ActiveMQJMSClientBundle.BUNDLE.nameCannotBeNull(); } - if (name.equals("")) - { + if (name.equals("")) { throw ActiveMQJMSClientBundle.BUNDLE.nameCannotBeEmpty(); } } @Override - protected boolean hasNoBody() - { + protected boolean hasNoBody() { return map.isEmpty(); } @Override - public boolean isBodyAssignableTo(@SuppressWarnings("rawtypes") - Class c) - { - if (hasNoBody()) - { + public boolean isBodyAssignableTo(@SuppressWarnings("rawtypes") Class c) { + if (hasNoBody()) { return true; } return c.isAssignableFrom(java.util.Map.class); @@ -440,8 +368,7 @@ public final class ActiveMQMapMessage extends ActiveMQMessage implements MapMess @SuppressWarnings("unchecked") @Override - protected T getBodyInternal(Class c) - { + protected T getBodyInternal(Class c) { return (T) map.getMap(); } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQMessage.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQMessage.java index cc3f2552ec..db72dffd2b 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQMessage.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQMessage.java @@ -45,54 +45,46 @@ import org.apache.activemq.artemis.core.message.impl.MessageInternal; import org.apache.activemq.artemis.reader.MessageUtil; import org.apache.activemq.artemis.utils.UUID; - /** * ActiveMQ Artemis implementation of a JMS Message. *
    * JMS Messages only live on the client side - the server only deals with MessageImpl * instances */ -public class ActiveMQMessage implements javax.jms.Message -{ +public class ActiveMQMessage implements javax.jms.Message { + // Constants ----------------------------------------------------- public static final byte TYPE = org.apache.activemq.artemis.api.core.Message.DEFAULT_TYPE; - public static Map coreMaptoJMSMap(final Map coreMessage) - { + public static Map coreMaptoJMSMap(final Map coreMessage) { Map jmsMessage = new HashMap(); - String deliveryMode = (Boolean)coreMessage.get("durable") ? "PERSISTENT" : "NON_PERSISTENT"; - byte priority = (Byte)coreMessage.get("priority"); - long timestamp = (Long)coreMessage.get("timestamp"); - long expiration = (Long)coreMessage.get("expiration"); + String deliveryMode = (Boolean) coreMessage.get("durable") ? "PERSISTENT" : "NON_PERSISTENT"; + byte priority = (Byte) coreMessage.get("priority"); + long timestamp = (Long) coreMessage.get("timestamp"); + long expiration = (Long) coreMessage.get("expiration"); jmsMessage.put("JMSPriority", priority); jmsMessage.put("JMSTimestamp", timestamp); jmsMessage.put("JMSExpiration", expiration); jmsMessage.put("JMSDeliveryMode", deliveryMode); - for (Map.Entry entry : coreMessage.entrySet()) - { + for (Map.Entry entry : coreMessage.entrySet()) { if (entry.getKey().equals("type") || entry.getKey().equals("durable") || - entry.getKey().equals("expiration") || - entry.getKey().equals("timestamp") || - entry.getKey().equals("priority")) - { + entry.getKey().equals("expiration") || + entry.getKey().equals("timestamp") || + entry.getKey().equals("priority")) { // Ignore } - else if (entry.getKey().equals("userID")) - { + else if (entry.getKey().equals("userID")) { jmsMessage.put("JMSMessageID", entry.getValue().toString()); } - else - { + else { Object value = entry.getValue(); - if (value instanceof SimpleString) - { + if (value instanceof SimpleString) { jmsMessage.put(entry.getKey(), value.toString()); } - else - { + else { jmsMessage.put(entry.getKey(), value); } } @@ -104,8 +96,8 @@ public class ActiveMQMessage implements javax.jms.Message // Static -------------------------------------------------------- private static final HashSet reservedIdentifiers = new HashSet(); - static - { + + static { ActiveMQMessage.reservedIdentifiers.add("NULL"); ActiveMQMessage.reservedIdentifiers.add("TRUE"); ActiveMQMessage.reservedIdentifiers.add("FALSE"); @@ -119,14 +111,12 @@ public class ActiveMQMessage implements javax.jms.Message ActiveMQMessage.reservedIdentifiers.add("ESCAPE"); } - public static ActiveMQMessage createMessage(final ClientMessage message, final ClientSession session) - { + public static ActiveMQMessage createMessage(final ClientMessage message, final ClientSession session) { int type = message.getType(); ActiveMQMessage msg; - switch (type) - { + switch (type) { case ActiveMQMessage.TYPE: // 0 { msg = new ActiveMQMessage(message, session); @@ -142,8 +132,7 @@ public class ActiveMQMessage implements javax.jms.Message msg = new ActiveMQMapMessage(message, session); break; } - case ActiveMQObjectMessage.TYPE: - { + case ActiveMQObjectMessage.TYPE: { msg = new ActiveMQObjectMessage(message, session); break; } @@ -157,8 +146,7 @@ public class ActiveMQMessage implements javax.jms.Message msg = new ActiveMQTextMessage(message, session); break; } - default: - { + default: { throw new JMSRuntimeException("Invalid message type " + type); } } @@ -203,22 +191,19 @@ public class ActiveMQMessage implements javax.jms.Message /* * Create a new message prior to sending */ - protected ActiveMQMessage(final byte type, final ClientSession session) - { - message = session.createMessage(type, true, 0, System.currentTimeMillis(), (byte)4); + protected ActiveMQMessage(final byte type, final ClientSession session) { + message = session.createMessage(type, true, 0, System.currentTimeMillis(), (byte) 4); } - protected ActiveMQMessage(final ClientSession session) - { + protected ActiveMQMessage(final ClientSession session) { this(ActiveMQMessage.TYPE, session); } /** * Constructor for when receiving a message from the server */ - public ActiveMQMessage(final ClientMessage message, final ClientSession session) - { + public ActiveMQMessage(final ClientMessage message, final ClientSession session) { this.message = message; readOnly = true; @@ -231,17 +216,14 @@ public class ActiveMQMessage implements javax.jms.Message /* * A constructor that takes a foreign message */ - public ActiveMQMessage(final Message foreign, final ClientSession session) throws JMSException - { + public ActiveMQMessage(final Message foreign, final ClientSession session) throws JMSException { this(foreign, ActiveMQMessage.TYPE, session); } - public ActiveMQMessage() - { + public ActiveMQMessage() { } - protected ActiveMQMessage(final Message foreign, final byte type, final ClientSession session) throws JMSException - { + protected ActiveMQMessage(final Message foreign, final byte type, final ClientSession session) throws JMSException { this(type, session); setJMSTimestamp(foreign.getJMSTimestamp()); @@ -250,25 +232,20 @@ public class ActiveMQMessage implements javax.jms.Message boolean supportBytesId = !"false".equals(value); - if (supportBytesId) - { - try - { + if (supportBytesId) { + try { byte[] corrIDBytes = foreign.getJMSCorrelationIDAsBytes(); setJMSCorrelationIDAsBytes(corrIDBytes); } - catch (JMSException e) - { + catch (JMSException e) { // specified as String String corrIDString = foreign.getJMSCorrelationID(); - if (corrIDString != null) - { + if (corrIDString != null) { setJMSCorrelationID(corrIDString); } } } - else - { + else { // Some providers, like WSMQ do automatic conversions between native byte[] correlation id // and String correlation id. This makes it impossible for ActiveMQ Artemis to guarantee to return the correct // type as set by the user @@ -276,8 +253,7 @@ public class ActiveMQMessage implements javax.jms.Message // https://jira.jboss.org/jira/browse/HORNETQ-356 // https://jira.jboss.org/jira/browse/HORNETQ-332 String corrIDString = foreign.getJMSCorrelationID(); - if (corrIDString != null) - { + if (corrIDString != null) { setJMSCorrelationID(corrIDString); } } @@ -290,8 +266,7 @@ public class ActiveMQMessage implements javax.jms.Message setJMSType(foreign.getJMSType()); // We can't avoid a cast warning here since getPropertyNames() is on the JMS API - for (Enumeration props = foreign.getPropertyNames(); props.hasMoreElements();) - { + for (Enumeration props = foreign.getPropertyNames(); props.hasMoreElements(); ) { String name = props.nextElement(); Object prop = foreign.getObjectProperty(name); @@ -302,10 +277,8 @@ public class ActiveMQMessage implements javax.jms.Message // javax.jmx.Message implementation ------------------------------ - public String getJMSMessageID() - { - if (msgID == null) - { + public String getJMSMessageID() { + if (msgID == null) { UUID uid = message.getUserID(); msgID = uid == null ? null : "ID:" + uid.toString(); @@ -313,10 +286,8 @@ public class ActiveMQMessage implements javax.jms.Message return msgID; } - public void setJMSMessageID(final String jmsMessageID) throws JMSException - { - if (jmsMessageID != null && !jmsMessageID.startsWith("ID:")) - { + public void setJMSMessageID(final String jmsMessageID) throws JMSException { + if (jmsMessageID != null && !jmsMessageID.startsWith("ID:")) { throw new JMSException("JMSMessageID must start with ID:"); } @@ -325,82 +296,66 @@ public class ActiveMQMessage implements javax.jms.Message msgID = jmsMessageID; } - public long getJMSTimestamp() throws JMSException - { + public long getJMSTimestamp() throws JMSException { return message.getTimestamp(); } - public void setJMSTimestamp(final long timestamp) throws JMSException - { + public void setJMSTimestamp(final long timestamp) throws JMSException { message.setTimestamp(timestamp); } - public byte[] getJMSCorrelationIDAsBytes() throws JMSException - { + public byte[] getJMSCorrelationIDAsBytes() throws JMSException { return MessageUtil.getJMSCorrelationIDAsBytes(message); } - public void setJMSCorrelationIDAsBytes(final byte[] correlationID) throws JMSException - { - try - { + public void setJMSCorrelationIDAsBytes(final byte[] correlationID) throws JMSException { + try { MessageUtil.setJMSCorrelationIDAsBytes(message, correlationID); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { JMSException ex = new JMSException(e.getMessage()); ex.initCause(e); throw ex; } } - public void setJMSCorrelationID(final String correlationID) throws JMSException - { + public void setJMSCorrelationID(final String correlationID) throws JMSException { MessageUtil.setJMSCorrelationID(message, correlationID); jmsCorrelationID = correlationID; } - public String getJMSCorrelationID() throws JMSException - { - if (jmsCorrelationID == null) - { + public String getJMSCorrelationID() throws JMSException { + if (jmsCorrelationID == null) { jmsCorrelationID = MessageUtil.getJMSCorrelationID(message); } return jmsCorrelationID; } - public Destination getJMSReplyTo() throws JMSException - { - if (replyTo == null) - { + public Destination getJMSReplyTo() throws JMSException { + if (replyTo == null) { SimpleString repl = MessageUtil.getJMSReplyTo(message); - if (repl != null) - { + if (repl != null) { replyTo = ActiveMQDestination.fromAddress(repl.toString()); } } return replyTo; } - public void setJMSReplyTo(final Destination dest) throws JMSException - { + public void setJMSReplyTo(final Destination dest) throws JMSException { - if (dest == null) - { + if (dest == null) { MessageUtil.setJMSReplyTo(message, null); replyTo = null; } - else - { - if (dest instanceof ActiveMQDestination == false) - { + else { + if (dest instanceof ActiveMQDestination == false) { throw new InvalidDestinationException("Foreign destination " + dest); } - ActiveMQDestination jbd = (ActiveMQDestination)dest; + ActiveMQDestination jbd = (ActiveMQDestination) dest; MessageUtil.setJMSReplyTo(message, jbd.getSimpleAddress()); @@ -408,10 +363,8 @@ public class ActiveMQMessage implements javax.jms.Message } } - public Destination getJMSDestination() throws JMSException - { - if (dest == null) - { + public Destination getJMSDestination() throws JMSException { + if (dest == null) { SimpleString sdest = message.getAddress(); dest = sdest == null ? null : ActiveMQDestination.fromAddress(sdest.toString()); @@ -420,400 +373,315 @@ public class ActiveMQMessage implements javax.jms.Message return dest; } - public void setJMSDestination(final Destination destination) throws JMSException - { + public void setJMSDestination(final Destination destination) throws JMSException { dest = destination; } - public int getJMSDeliveryMode() throws JMSException - { + public int getJMSDeliveryMode() throws JMSException { return message.isDurable() ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT; } - public void setJMSDeliveryMode(final int deliveryMode) throws JMSException - { - if (deliveryMode == DeliveryMode.PERSISTENT) - { + public void setJMSDeliveryMode(final int deliveryMode) throws JMSException { + if (deliveryMode == DeliveryMode.PERSISTENT) { message.setDurable(true); } - else if (deliveryMode == DeliveryMode.NON_PERSISTENT) - { + else if (deliveryMode == DeliveryMode.NON_PERSISTENT) { message.setDurable(false); } - else - { + else { throw ActiveMQJMSClientBundle.BUNDLE.illegalDeliveryMode(deliveryMode); } } - public boolean getJMSRedelivered() throws JMSException - { + public boolean getJMSRedelivered() throws JMSException { return message.getDeliveryCount() > 1; } - public void setJMSRedelivered(final boolean redelivered) throws JMSException - { - if (!redelivered) - { + public void setJMSRedelivered(final boolean redelivered) throws JMSException { + if (!redelivered) { message.setDeliveryCount(1); } - else - { - if (message.getDeliveryCount() > 1) - { + else { + if (message.getDeliveryCount() > 1) { // do nothing } - else - { + else { message.setDeliveryCount(2); } } } - public void setJMSType(final String type) throws JMSException - { - if (type != null) - { + public void setJMSType(final String type) throws JMSException { + if (type != null) { MessageUtil.setJMSType(message, type); jmsType = type; } } - public String getJMSType() throws JMSException - { - if (jmsType == null) - { + public String getJMSType() throws JMSException { + if (jmsType == null) { jmsType = MessageUtil.getJMSType(message); } return jmsType; } - public long getJMSExpiration() throws JMSException - { + public long getJMSExpiration() throws JMSException { return message.getExpiration(); } - public void setJMSExpiration(final long expiration) throws JMSException - { + public void setJMSExpiration(final long expiration) throws JMSException { message.setExpiration(expiration); } - public int getJMSPriority() throws JMSException - { + public int getJMSPriority() throws JMSException { return message.getPriority(); } - public void setJMSPriority(final int priority) throws JMSException - { + public void setJMSPriority(final int priority) throws JMSException { checkPriority(priority); - message.setPriority((byte)priority); + message.setPriority((byte) priority); } - public void clearProperties() throws JMSException - { + public void clearProperties() throws JMSException { MessageUtil.clearProperties(message); propertiesReadOnly = false; } - public void clearBody() throws JMSException - { + public void clearBody() throws JMSException { readOnly = false; } - public boolean propertyExists(final String name) throws JMSException - { + public boolean propertyExists(final String name) throws JMSException { return MessageUtil.propertyExists(message, name); } - public boolean getBooleanProperty(final String name) throws JMSException - { - try - { + public boolean getBooleanProperty(final String name) throws JMSException { + try { return message.getBooleanProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public byte getByteProperty(final String name) throws JMSException - { - try - { + public byte getByteProperty(final String name) throws JMSException { + try { return message.getByteProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public short getShortProperty(final String name) throws JMSException - { - try - { + public short getShortProperty(final String name) throws JMSException { + try { return message.getShortProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public int getIntProperty(final String name) throws JMSException - { - if (MessageUtil.JMSXDELIVERYCOUNT.equals(name)) - { + public int getIntProperty(final String name) throws JMSException { + if (MessageUtil.JMSXDELIVERYCOUNT.equals(name)) { return message.getDeliveryCount(); } - try - { + try { return message.getIntProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public long getLongProperty(final String name) throws JMSException - { - if (MessageUtil.JMSXDELIVERYCOUNT.equals(name)) - { + public long getLongProperty(final String name) throws JMSException { + if (MessageUtil.JMSXDELIVERYCOUNT.equals(name)) { return message.getDeliveryCount(); } - try - { + try { return message.getLongProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public float getFloatProperty(final String name) throws JMSException - { - try - { + public float getFloatProperty(final String name) throws JMSException { + try { return message.getFloatProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public double getDoubleProperty(final String name) throws JMSException - { - try - { + public double getDoubleProperty(final String name) throws JMSException { + try { return message.getDoubleProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public String getStringProperty(final String name) throws JMSException - { - if (MessageUtil.JMSXDELIVERYCOUNT.equals(name)) - { + public String getStringProperty(final String name) throws JMSException { + if (MessageUtil.JMSXDELIVERYCOUNT.equals(name)) { return String.valueOf(message.getDeliveryCount()); } - try - { - if (MessageUtil.JMSXGROUPID.equals(name)) - { + try { + if (MessageUtil.JMSXGROUPID.equals(name)) { return message.getStringProperty(org.apache.activemq.artemis.api.core.Message.HDR_GROUP_ID); } - else - { + else { return message.getStringProperty(new SimpleString(name)); } } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public Object getObjectProperty(final String name) throws JMSException - { - if (MessageUtil.JMSXDELIVERYCOUNT.equals(name)) - { + public Object getObjectProperty(final String name) throws JMSException { + if (MessageUtil.JMSXDELIVERYCOUNT.equals(name)) { return String.valueOf(message.getDeliveryCount()); } Object val = message.getObjectProperty(name); - if (val instanceof SimpleString) - { - val = ((SimpleString)val).toString(); + if (val instanceof SimpleString) { + val = ((SimpleString) val).toString(); } return val; } @SuppressWarnings("rawtypes") @Override - public Enumeration getPropertyNames() throws JMSException - { + public Enumeration getPropertyNames() throws JMSException { return Collections.enumeration(MessageUtil.getPropertyNames(message)); } - public void setBooleanProperty(final String name, final boolean value) throws JMSException - { + public void setBooleanProperty(final String name, final boolean value) throws JMSException { checkProperty(name); message.putBooleanProperty(new SimpleString(name), value); } - public void setByteProperty(final String name, final byte value) throws JMSException - { + public void setByteProperty(final String name, final byte value) throws JMSException { checkProperty(name); message.putByteProperty(new SimpleString(name), value); } - public void setShortProperty(final String name, final short value) throws JMSException - { + public void setShortProperty(final String name, final short value) throws JMSException { checkProperty(name); message.putShortProperty(new SimpleString(name), value); } - public void setIntProperty(final String name, final int value) throws JMSException - { + public void setIntProperty(final String name, final int value) throws JMSException { checkProperty(name); message.putIntProperty(new SimpleString(name), value); } - public void setLongProperty(final String name, final long value) throws JMSException - { + public void setLongProperty(final String name, final long value) throws JMSException { checkProperty(name); message.putLongProperty(new SimpleString(name), value); } - public void setFloatProperty(final String name, final float value) throws JMSException - { + public void setFloatProperty(final String name, final float value) throws JMSException { checkProperty(name); message.putFloatProperty(new SimpleString(name), value); } - public void setDoubleProperty(final String name, final double value) throws JMSException - { + public void setDoubleProperty(final String name, final double value) throws JMSException { checkProperty(name); message.putDoubleProperty(new SimpleString(name), value); } - public void setStringProperty(final String name, final String value) throws JMSException - { + public void setStringProperty(final String name, final String value) throws JMSException { checkProperty(name); - if (MessageUtil.JMSXGROUPID.equals(name)) - { + if (MessageUtil.JMSXGROUPID.equals(name)) { message.putStringProperty(org.apache.activemq.artemis.api.core.Message.HDR_GROUP_ID, SimpleString.toSimpleString(value)); } - else - { - message.putStringProperty(new SimpleString(name), SimpleString.toSimpleString(value)); + else { + message.putStringProperty(new SimpleString(name), SimpleString.toSimpleString(value)); } } - public void setObjectProperty(final String name, final Object value) throws JMSException - { - if (ActiveMQJMSConstants.JMS_ACTIVEMQ_OUTPUT_STREAM.equals(name)) - { - setOutputStream((OutputStream)value); + public void setObjectProperty(final String name, final Object value) throws JMSException { + if (ActiveMQJMSConstants.JMS_ACTIVEMQ_OUTPUT_STREAM.equals(name)) { + setOutputStream((OutputStream) value); return; } - else if (ActiveMQJMSConstants.JMS_ACTIVEMQ_SAVE_STREAM.equals(name)) - { - saveToOutputStream((OutputStream)value); + else if (ActiveMQJMSConstants.JMS_ACTIVEMQ_SAVE_STREAM.equals(name)) { + saveToOutputStream((OutputStream) value); return; } checkProperty(name); - if (ActiveMQJMSConstants.JMS_ACTIVEMQ_INPUT_STREAM.equals(name)) - { - setInputStream((InputStream)value); + if (ActiveMQJMSConstants.JMS_ACTIVEMQ_INPUT_STREAM.equals(name)) { + setInputStream((InputStream) value); return; } - try - { + try { message.putObjectProperty(new SimpleString(name), value); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public void acknowledge() throws JMSException - { - if (session != null) - { - try - { - if (individualAck) - { + public void acknowledge() throws JMSException { + if (session != null) { + try { + if (individualAck) { message.individualAcknowledge(); } session.commit(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } } @Override - public long getJMSDeliveryTime() throws JMSException - { + public long getJMSDeliveryTime() throws JMSException { Long value; - try - { + try { value = message.getLongProperty(org.apache.activemq.artemis.api.core.Message.HDR_SCHEDULED_DELIVERY_TIME); } - catch (Exception e) - { + catch (Exception e) { return 0; } - if (value == null) - { + if (value == null) { return 0; } - else - { + else { return value.longValue(); } } @Override - public void setJMSDeliveryTime(long deliveryTime) throws JMSException - { + public void setJMSDeliveryTime(long deliveryTime) throws JMSException { message.putLongProperty(org.apache.activemq.artemis.api.core.Message.HDR_SCHEDULED_DELIVERY_TIME, deliveryTime); } @Override - public T getBody(Class c) throws JMSException - { - if (isBodyAssignableTo(c)) - { + public T getBody(Class c) throws JMSException { + if (isBodyAssignableTo(c)) { return getBodyInternal(c); } // XXX HORNETQ-1209 Do we need translations here? @@ -821,24 +689,19 @@ public class ActiveMQMessage implements javax.jms.Message } @SuppressWarnings("unchecked") - protected T getBodyInternal(Class c) throws MessageFormatException - { - InputStream is = ((MessageInternal)message).getBodyInputStream(); - try - { + protected T getBodyInternal(Class c) throws MessageFormatException { + InputStream is = ((MessageInternal) message).getBodyInputStream(); + try { ObjectInputStream ois = new ObjectInputStream(is); - return (T)ois.readObject(); + return (T) ois.readObject(); } - catch (Exception e) - { + catch (Exception e) { throw new MessageFormatException(e.getMessage()); } } - @Override - public boolean isBodyAssignableTo(@SuppressWarnings("rawtypes") Class c) - { + public boolean isBodyAssignableTo(@SuppressWarnings("rawtypes") Class c) { /** * From the specs: *

    @@ -850,120 +713,98 @@ public class ActiveMQMessage implements javax.jms.Message /** * Helper method for {@link #isBodyAssignableTo(Class)}. + * * @return true if the message has no body. */ - protected boolean hasNoBody() - { + protected boolean hasNoBody() { return message.getBodySize() == 0; } // Public -------------------------------------------------------- - public void setIndividualAcknowledge() - { + public void setIndividualAcknowledge() { this.individualAck = true; } - public void resetMessageID(final String newMsgID) - { + public void resetMessageID(final String newMsgID) { this.msgID = newMsgID; } - public ClientMessage getCoreMessage() - { + public ClientMessage getCoreMessage() { return message; } - public void doBeforeSend() throws Exception - { + public void doBeforeSend() throws Exception { message.getBodyBuffer().resetReaderIndex(); } - public void checkBuffer() - { + public void checkBuffer() { message.getBodyBuffer(); } - public void doBeforeReceive() throws ActiveMQException - { + public void doBeforeReceive() throws ActiveMQException { message.checkCompletion(); ActiveMQBuffer body = message.getBodyBuffer(); - if (body != null) - { + if (body != null) { body.resetReaderIndex(); } } - public byte getType() - { + public byte getType() { return ActiveMQMessage.TYPE; } - public void setInputStream(final InputStream input) throws JMSException - { + public void setInputStream(final InputStream input) throws JMSException { checkStream(); - if (readOnly) - { + if (readOnly) { throw ActiveMQJMSClientBundle.BUNDLE.messageNotWritable(); } message.setBodyInputStream(input); } - public void setOutputStream(final OutputStream output) throws JMSException - { + public void setOutputStream(final OutputStream output) throws JMSException { checkStream(); - if (!readOnly) - { + if (!readOnly) { throw new IllegalStateException("OutputStream property is only valid on received messages"); } - try - { + try { message.setOutputStream(output); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } - public void saveToOutputStream(final OutputStream output) throws JMSException - { + public void saveToOutputStream(final OutputStream output) throws JMSException { checkStream(); - if (!readOnly) - { + if (!readOnly) { throw new IllegalStateException("OutputStream property is only valid on received messages"); } - try - { + try { message.saveToOutputStream(output); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } - public boolean waitCompletionOnStream(final long timeWait) throws JMSException - { + public boolean waitCompletionOnStream(final long timeWait) throws JMSException { checkStream(); - try - { + try { return message.waitOutputStreamCompletion(timeWait); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } @Override - public String toString() - { + public String toString() { StringBuffer sb = new StringBuffer("ActiveMQMessage["); sb.append(getJMSMessageID()); sb.append("]:"); @@ -976,93 +817,73 @@ public class ActiveMQMessage implements javax.jms.Message // Protected ----------------------------------------------------- - protected void checkWrite() throws JMSException - { - if (readOnly) - { + protected void checkWrite() throws JMSException { + if (readOnly) { throw ActiveMQJMSClientBundle.BUNDLE.messageNotWritable(); } } - protected void checkRead() throws JMSException - { - if (!readOnly) - { + protected void checkRead() throws JMSException { + if (!readOnly) { throw ActiveMQJMSClientBundle.BUNDLE.messageNotReadable(); } } // Private ------------------------------------------------------------ - private void checkStream() throws JMSException - { - if (!(message.getType() == ActiveMQBytesMessage.TYPE || message.getType() == ActiveMQStreamMessage.TYPE)) - { + private void checkStream() throws JMSException { + if (!(message.getType() == ActiveMQBytesMessage.TYPE || message.getType() == ActiveMQStreamMessage.TYPE)) { throw ActiveMQJMSClientBundle.BUNDLE.onlyValidForByteOrStreamMessages(); } } - private void checkProperty(final String name) throws JMSException - { - if (propertiesReadOnly) - { - if (name.equals(ActiveMQJMSConstants.JMS_ACTIVEMQ_INPUT_STREAM)) - { + private void checkProperty(final String name) throws JMSException { + if (propertiesReadOnly) { + if (name.equals(ActiveMQJMSConstants.JMS_ACTIVEMQ_INPUT_STREAM)) { throw new MessageNotWriteableException("You cannot set the Input Stream on received messages. Did you mean " + ActiveMQJMSConstants.JMS_ACTIVEMQ_OUTPUT_STREAM + - " or " + - ActiveMQJMSConstants.JMS_ACTIVEMQ_SAVE_STREAM + - "?"); + " or " + + ActiveMQJMSConstants.JMS_ACTIVEMQ_SAVE_STREAM + + "?"); } - else - { + else { throw ActiveMQJMSClientBundle.BUNDLE.messageNotWritable(); } } - if (name == null) - { + if (name == null) { throw ActiveMQJMSClientBundle.BUNDLE.nullArgumentNotAllowed("property"); } - if (name.equals("")) - { + if (name.equals("")) { throw new IllegalArgumentException("The name of a property must not be an empty String."); } - if (!isValidJavaIdentifier(name)) - { + if (!isValidJavaIdentifier(name)) { throw ActiveMQJMSClientBundle.BUNDLE.invalidJavaIdentifier(name); } - if (ActiveMQMessage.reservedIdentifiers.contains(name)) - { + if (ActiveMQMessage.reservedIdentifiers.contains(name)) { throw new JMSRuntimeException("The property name '" + name + "' is reserved due to selector syntax."); } - if (name.startsWith("JMS_ACTIVEMQ")) - { + if (name.startsWith("JMS_ACTIVEMQ")) { throw new JMSRuntimeException("The property name '" + name + "' is illegal since it starts with JMS_ACTIVEMQ"); } } - private boolean isValidJavaIdentifier(final String s) - { - if (s == null || s.length() == 0) - { + private boolean isValidJavaIdentifier(final String s) { + if (s == null || s.length() == 0) { return false; } char[] c = s.toCharArray(); - if (!Character.isJavaIdentifierStart(c[0])) - { + if (!Character.isJavaIdentifierStart(c[0])) { return false; } - for (int i = 1; i < c.length; i++) - { - if (!Character.isJavaIdentifierPart(c[i])) - { + for (int i = 1; i < c.length; i++) { + if (!Character.isJavaIdentifierPart(c[i])) { return false; } } @@ -1070,10 +891,8 @@ public class ActiveMQMessage implements javax.jms.Message return true; } - private void checkPriority(final int priority) throws JMSException - { - if (priority < 0 || priority > 9) - { + private void checkPriority(final int priority) throws JMSException { + if (priority < 0 || priority > 9) { throw new JMSException(priority + " is not valid: priority must be between 0 and 9"); } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQMessageConsumer.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQMessageConsumer.java index b3cc69a05b..8841f2a619 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQMessageConsumer.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQMessageConsumer.java @@ -36,8 +36,8 @@ import org.apache.activemq.artemis.api.jms.ActiveMQJMSConstants; /** * ActiveMQ Artemis implementation of a JMS MessageConsumer. */ -public final class ActiveMQMessageConsumer implements QueueReceiver, TopicSubscriber -{ +public final class ActiveMQMessageConsumer implements QueueReceiver, TopicSubscriber { + private final ClientConsumer consumer; private MessageListener listener; @@ -66,8 +66,7 @@ public final class ActiveMQMessageConsumer implements QueueReceiver, TopicSubscr final boolean noLocal, final ActiveMQDestination destination, final String selector, - final SimpleString autoDeleteQueueName) throws JMSException - { + final SimpleString autoDeleteQueueName) throws JMSException { this.connection = connection; this.session = session; @@ -87,91 +86,76 @@ public final class ActiveMQMessageConsumer implements QueueReceiver, TopicSubscr // MessageConsumer implementation -------------------------------- - public String getMessageSelector() throws JMSException - { + public String getMessageSelector() throws JMSException { checkClosed(); return selector; } - public MessageListener getMessageListener() throws JMSException - { + public MessageListener getMessageListener() throws JMSException { checkClosed(); return listener; } - public void setMessageListener(final MessageListener listener) throws JMSException - { + public void setMessageListener(final MessageListener listener) throws JMSException { this.listener = listener; coreListener = listener == null ? null : new JMSMessageListenerWrapper(connection, session, consumer, listener, ackMode); - try - { + try { consumer.setMessageHandler(coreListener); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } - public Message receive() throws JMSException - { + public Message receive() throws JMSException { return getMessage(0, false); } - public Message receive(final long timeout) throws JMSException - { + public Message receive(final long timeout) throws JMSException { return getMessage(timeout, false); } - public Message receiveNoWait() throws JMSException - { + public Message receiveNoWait() throws JMSException { return getMessage(0, true); } - public void close() throws JMSException - { - try - { + public void close() throws JMSException { + try { consumer.close(); - if (autoDeleteQueueName != null) - { + if (autoDeleteQueueName != null) { // If non durable subscriber need to delete subscription too session.deleteQueue(autoDeleteQueueName); } session.removeConsumer(this); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } // QueueReceiver implementation ---------------------------------- - public Queue getQueue() throws JMSException - { + public Queue getQueue() throws JMSException { checkClosed(); - return (Queue)destination; + return (Queue) destination; } // TopicSubscriber implementation -------------------------------- - public Topic getTopic() throws JMSException - { + public Topic getTopic() throws JMSException { checkClosed(); - return (Topic)destination; + return (Topic) destination; } - public boolean getNoLocal() throws JMSException - { + public boolean getNoLocal() throws JMSException { checkClosed(); return noLocal; @@ -180,72 +164,58 @@ public final class ActiveMQMessageConsumer implements QueueReceiver, TopicSubscr // Public -------------------------------------------------------- @Override - public String toString() - { + public String toString() { return "ActiveMQMessageConsumer[" + consumer + "]"; } - public boolean isClosed() - { + public boolean isClosed() { return consumer.isClosed(); } - // Package protected --------------------------------------------- // Protected ----------------------------------------------------- // Private ------------------------------------------------------- - private void checkClosed() throws JMSException - { - if (consumer.isClosed() || session.getCoreSession().isClosed()) - { + private void checkClosed() throws JMSException { + if (consumer.isClosed() || session.getCoreSession().isClosed()) { throw new IllegalStateException("Consumer is closed"); } } - private ActiveMQMessage getMessage(final long timeout, final boolean noWait) throws JMSException - { - try - { + private ActiveMQMessage getMessage(final long timeout, final boolean noWait) throws JMSException { + try { ClientMessage coreMessage; - if (noWait) - { + if (noWait) { coreMessage = consumer.receiveImmediate(); } - else - { + else { coreMessage = consumer.receive(timeout); } ActiveMQMessage jmsMsg = null; - if (coreMessage != null) - { - boolean needSession = - ackMode == Session.CLIENT_ACKNOWLEDGE || ackMode == ActiveMQJMSConstants.INDIVIDUAL_ACKNOWLEDGE; + if (coreMessage != null) { + boolean needSession = ackMode == Session.CLIENT_ACKNOWLEDGE || ackMode == ActiveMQJMSConstants.INDIVIDUAL_ACKNOWLEDGE; jmsMsg = ActiveMQMessage.createMessage(coreMessage, needSession ? session.getCoreSession() : null); jmsMsg.doBeforeReceive(); // We Do the ack after doBeforeRecive, as in the case of large messages, this may fail so we don't want messages redelivered // https://issues.jboss.org/browse/JBPAPP-6110 - if (session.getAcknowledgeMode() == ActiveMQJMSConstants.INDIVIDUAL_ACKNOWLEDGE) - { + if (session.getAcknowledgeMode() == ActiveMQJMSConstants.INDIVIDUAL_ACKNOWLEDGE) { jmsMsg.setIndividualAcknowledge(); } - else - { + else { coreMessage.acknowledge(); } } return jmsMsg; } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQMessageProducer.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQMessageProducer.java index 4dce39f983..e7a6912168 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQMessageProducer.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQMessageProducer.java @@ -42,11 +42,12 @@ import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.api.core.client.SendAcknowledgementHandler; import org.apache.activemq.artemis.utils.UUID; import org.apache.activemq.artemis.utils.UUIDGenerator; + /** * ActiveMQ Artemis implementation of a JMS MessageProducer. */ -public class ActiveMQMessageProducer implements MessageProducer, QueueSender, TopicPublisher -{ +public class ActiveMQMessageProducer implements MessageProducer, QueueSender, TopicPublisher { + private final ActiveMQConnection connection; private final SimpleString connID; @@ -66,9 +67,10 @@ public class ActiveMQMessageProducer implements MessageProducer, QueueSender, To private final ActiveMQDestination defaultDestination; // Constructors -------------------------------------------------- - protected ActiveMQMessageProducer(final ActiveMQConnection connection, final ClientProducer producer, - final ActiveMQDestination defaultDestination, final ClientSession clientSession) throws JMSException - { + protected ActiveMQMessageProducer(final ActiveMQConnection connection, + final ClientProducer producer, + final ActiveMQDestination defaultDestination, + final ClientSession clientSession) throws JMSException { this.connection = connection; connID = connection.getClientID() != null ? new SimpleString(connection.getClientID()) : connection.getUID(); @@ -82,243 +84,228 @@ public class ActiveMQMessageProducer implements MessageProducer, QueueSender, To // MessageProducer implementation -------------------------------- - public void setDisableMessageID(final boolean value) throws JMSException - { + public void setDisableMessageID(final boolean value) throws JMSException { checkClosed(); disableMessageID = value; } - public boolean getDisableMessageID() throws JMSException - { + public boolean getDisableMessageID() throws JMSException { checkClosed(); return disableMessageID; } - public void setDisableMessageTimestamp(final boolean value) throws JMSException - { + public void setDisableMessageTimestamp(final boolean value) throws JMSException { checkClosed(); disableMessageTimestamp = value; } - public boolean getDisableMessageTimestamp() throws JMSException - { + public boolean getDisableMessageTimestamp() throws JMSException { checkClosed(); return disableMessageTimestamp; } - public void setDeliveryMode(final int deliveryMode) throws JMSException - { + public void setDeliveryMode(final int deliveryMode) throws JMSException { checkClosed(); - if (deliveryMode != DeliveryMode.NON_PERSISTENT && deliveryMode != DeliveryMode.PERSISTENT) - { + if (deliveryMode != DeliveryMode.NON_PERSISTENT && deliveryMode != DeliveryMode.PERSISTENT) { throw ActiveMQJMSClientBundle.BUNDLE.illegalDeliveryMode(deliveryMode); } defaultDeliveryMode = deliveryMode; } - public int getDeliveryMode() throws JMSException - { + public int getDeliveryMode() throws JMSException { checkClosed(); return defaultDeliveryMode; } - public void setPriority(final int defaultPriority) throws JMSException - { + public void setPriority(final int defaultPriority) throws JMSException { checkClosed(); - if (defaultPriority < 0 || defaultPriority > 9) - { + if (defaultPriority < 0 || defaultPriority > 9) { throw new JMSException("Illegal priority value: " + defaultPriority); } this.defaultPriority = defaultPriority; } - public int getPriority() throws JMSException - { + public int getPriority() throws JMSException { checkClosed(); return defaultPriority; } - public void setTimeToLive(final long timeToLive) throws JMSException - { + public void setTimeToLive(final long timeToLive) throws JMSException { checkClosed(); defaultTimeToLive = timeToLive; } - public long getTimeToLive() throws JMSException - { + public long getTimeToLive() throws JMSException { checkClosed(); return defaultTimeToLive; } - public Destination getDestination() throws JMSException - { + public Destination getDestination() throws JMSException { checkClosed(); return defaultDestination; } - public void close() throws JMSException - { + public void close() throws JMSException { connection.getThreadAwareContext().assertNotCompletionListenerThread(); - try - { + try { clientProducer.close(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } - public void send(final Message message) throws JMSException - { + public void send(final Message message) throws JMSException { checkDefaultDestination(); doSendx(defaultDestination, message, defaultDeliveryMode, defaultPriority, defaultTimeToLive, null); } public void send(final Message message, final int deliveryMode, - final int priority, final long timeToLive) throws JMSException - { + final int priority, + final long timeToLive) throws JMSException { checkDefaultDestination(); doSendx(defaultDestination, message, deliveryMode, priority, timeToLive, null); } - public void send(final Destination destination, final Message message) throws JMSException - { + public void send(final Destination destination, final Message message) throws JMSException { send(destination, message, defaultDeliveryMode, defaultPriority, defaultTimeToLive); } - public void send(final Destination destination, final Message message, final int deliveryMode, final int priority, - final long timeToLive) throws JMSException - { + public void send(final Destination destination, + final Message message, + final int deliveryMode, + final int priority, + final long timeToLive) throws JMSException { checkClosed(); checkDestination(destination); - doSendx((ActiveMQDestination)destination, message, deliveryMode, priority, timeToLive, null); + doSendx((ActiveMQDestination) destination, message, deliveryMode, priority, timeToLive, null); } @Override - public void setDeliveryDelay(long deliveryDelay) throws JMSException - { + public void setDeliveryDelay(long deliveryDelay) throws JMSException { this.defaultDeliveryDelay = deliveryDelay; } @Override - public long getDeliveryDelay() throws JMSException - { + public long getDeliveryDelay() throws JMSException { return defaultDeliveryDelay; } @Override - public void send(Message message, CompletionListener completionListener) throws JMSException - { + public void send(Message message, CompletionListener completionListener) throws JMSException { send(message, defaultDeliveryMode, defaultPriority, defaultTimeToLive, completionListener); } @Override - public void send(Message message, int deliveryMode, int priority, long timeToLive, - CompletionListener completionListener) throws JMSException - { + public void send(Message message, + int deliveryMode, + int priority, + long timeToLive, + CompletionListener completionListener) throws JMSException { checkCompletionListener(completionListener); checkDefaultDestination(); doSendx(defaultDestination, message, deliveryMode, priority, timeToLive, completionListener); } @Override - public void send(Destination destination, Message message, CompletionListener completionListener) throws JMSException - { + public void send(Destination destination, + Message message, + CompletionListener completionListener) throws JMSException { send(destination, message, defaultDeliveryMode, defaultPriority, defaultTimeToLive, completionListener); } @Override - public void send(Destination destination, Message message, int deliveryMode, int priority, long timeToLive, - CompletionListener completionListener) throws JMSException - { + public void send(Destination destination, + Message message, + int deliveryMode, + int priority, + long timeToLive, + CompletionListener completionListener) throws JMSException { checkClosed(); checkCompletionListener(completionListener); checkDestination(destination); - doSendx((ActiveMQDestination)destination, message, deliveryMode, priority, timeToLive, completionListener); + doSendx((ActiveMQDestination) destination, message, deliveryMode, priority, timeToLive, completionListener); } // TopicPublisher Implementation --------------------------------- - public Topic getTopic() throws JMSException - { - return (Topic)getDestination(); + public Topic getTopic() throws JMSException { + return (Topic) getDestination(); } - public void publish(final Message message) throws JMSException - { + public void publish(final Message message) throws JMSException { send(message); } - public void publish(final Topic topic, final Message message) throws JMSException - { + public void publish(final Topic topic, final Message message) throws JMSException { send(topic, message); } - public void publish(final Message message, final int deliveryMode, final int priority, final long timeToLive) throws JMSException - { + public void publish(final Message message, + final int deliveryMode, + final int priority, + final long timeToLive) throws JMSException { send(message, deliveryMode, priority, timeToLive); } - public void publish(final Topic topic, final Message message, final int deliveryMode, final int priority, - final long timeToLive) throws JMSException - { + public void publish(final Topic topic, + final Message message, + final int deliveryMode, + final int priority, + final long timeToLive) throws JMSException { checkDestination(topic); - doSendx((ActiveMQDestination)topic, message, deliveryMode, priority, timeToLive, null); + doSendx((ActiveMQDestination) topic, message, deliveryMode, priority, timeToLive, null); } // QueueSender Implementation ------------------------------------ - public void send(final Queue queue, final Message message) throws JMSException - { - send((Destination)queue, message); + public void send(final Queue queue, final Message message) throws JMSException { + send((Destination) queue, message); } - public void send(final Queue queue, final Message message, final int deliveryMode, final int priority, - final long timeToLive) throws JMSException - { + public void send(final Queue queue, + final Message message, + final int deliveryMode, + final int priority, + final long timeToLive) throws JMSException { checkDestination(queue); - doSendx((ActiveMQDestination)queue, message, deliveryMode, priority, timeToLive, null); + doSendx((ActiveMQDestination) queue, message, deliveryMode, priority, timeToLive, null); } - public Queue getQueue() throws JMSException - { - return (Queue)getDestination(); + public Queue getQueue() throws JMSException { + return (Queue) getDestination(); } // Public -------------------------------------------------------- @Override - public String toString() - { + public String toString() { return "ActiveMQMessageProducer->" + clientProducer; } /** * Check if the default destination has been set */ - private void checkDefaultDestination() - { - if (defaultDestination == null) - { + private void checkDefaultDestination() { + if (defaultDestination == null) { throw new UnsupportedOperationException("Cannot specify destination if producer has a default destination"); } } @@ -326,103 +313,81 @@ public class ActiveMQMessageProducer implements MessageProducer, QueueSender, To /** * Check if the destination is sent correctly */ - private void checkDestination(Destination destination) throws InvalidDestinationException - { - if (destination != null && !(destination instanceof ActiveMQDestination)) - { + private void checkDestination(Destination destination) throws InvalidDestinationException { + if (destination != null && !(destination instanceof ActiveMQDestination)) { throw new InvalidDestinationException("Foreign destination:" + destination); } - if (destination != null && defaultDestination != null) - { + if (destination != null && defaultDestination != null) { throw new UnsupportedOperationException("Cannot specify destination if producer has a default destination"); } - if (destination == null) - { + if (destination == null) { throw ActiveMQJMSClientBundle.BUNDLE.nullTopic(); } } - private void checkCompletionListener(CompletionListener completionListener) - { - if (completionListener == null) - { + private void checkCompletionListener(CompletionListener completionListener) { + if (completionListener == null) { throw ActiveMQJMSClientBundle.BUNDLE.nullArgumentNotAllowed("CompletionListener"); } } - - private void doSendx(ActiveMQDestination destination, final Message jmsMessage, final int deliveryMode, - final int priority, final long timeToLive, - CompletionListener completionListener) throws JMSException - { + private void doSendx(ActiveMQDestination destination, + final Message jmsMessage, + final int deliveryMode, + final int priority, + final long timeToLive, + CompletionListener completionListener) throws JMSException { jmsMessage.setJMSDeliveryMode(deliveryMode); jmsMessage.setJMSPriority(priority); - - if (timeToLive == 0) - { + if (timeToLive == 0) { jmsMessage.setJMSExpiration(0); } - else - { + else { jmsMessage.setJMSExpiration(System.currentTimeMillis() + timeToLive); } - if (!disableMessageTimestamp) - { + if (!disableMessageTimestamp) { jmsMessage.setJMSTimestamp(System.currentTimeMillis()); } - else - { + else { jmsMessage.setJMSTimestamp(0); } SimpleString address = null; - if (destination == null) - { - if (defaultDestination == null) - { + if (destination == null) { + if (defaultDestination == null) { throw new UnsupportedOperationException("Destination must be specified on send with an anonymous producer"); } destination = defaultDestination; } - else - { - if (defaultDestination != null) - { - if (!destination.equals(defaultDestination)) - { - throw new UnsupportedOperationException("Where a default destination is specified " + "for the sender and a destination is " - + "specified in the arguments to the send, " - + "these destinations must be equal"); + else { + if (defaultDestination != null) { + if (!destination.equals(defaultDestination)) { + throw new UnsupportedOperationException("Where a default destination is specified " + "for the sender and a destination is " + "specified in the arguments to the send, " + "these destinations must be equal"); } } address = destination.getSimpleAddress(); - if (!connection.containsKnownDestination(address)) - { - try - { + if (!connection.containsKnownDestination(address)) { + try { ClientSession.AddressQuery query = clientSession.addressQuery(address); // if it's autoCreateJMSQueue we will let the PostOffice.route to execute the creation at the server's side // as that's a more efficient path for such operation - if (!query.isExists() && !query.isAutoCreateJmsQueues()) - { + if (!query.isExists() && !query.isAutoCreateJmsQueues()) { throw new InvalidDestinationException("Destination " + address + " does not exist"); } - else - { + else { connection.addKnownDestination(address); } } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } @@ -433,33 +398,26 @@ public class ActiveMQMessageProducer implements MessageProducer, QueueSender, To boolean foreign = false; // First convert from foreign message if appropriate - if (!(jmsMessage instanceof ActiveMQMessage)) - { + if (!(jmsMessage instanceof ActiveMQMessage)) { // JMS 1.1 Sect. 3.11.4: A provider must be prepared to accept, from a client, // a message whose implementation is not one of its own. - if (jmsMessage instanceof BytesMessage) - { - activeMQJmsMessage = new ActiveMQBytesMessage((BytesMessage)jmsMessage, clientSession); + if (jmsMessage instanceof BytesMessage) { + activeMQJmsMessage = new ActiveMQBytesMessage((BytesMessage) jmsMessage, clientSession); } - else if (jmsMessage instanceof MapMessage) - { - activeMQJmsMessage = new ActiveMQMapMessage((MapMessage)jmsMessage, clientSession); + else if (jmsMessage instanceof MapMessage) { + activeMQJmsMessage = new ActiveMQMapMessage((MapMessage) jmsMessage, clientSession); } - else if (jmsMessage instanceof ObjectMessage) - { - activeMQJmsMessage = new ActiveMQObjectMessage((ObjectMessage)jmsMessage, clientSession); + else if (jmsMessage instanceof ObjectMessage) { + activeMQJmsMessage = new ActiveMQObjectMessage((ObjectMessage) jmsMessage, clientSession); } - else if (jmsMessage instanceof StreamMessage) - { - activeMQJmsMessage = new ActiveMQStreamMessage((StreamMessage)jmsMessage, clientSession); + else if (jmsMessage instanceof StreamMessage) { + activeMQJmsMessage = new ActiveMQStreamMessage((StreamMessage) jmsMessage, clientSession); } - else if (jmsMessage instanceof TextMessage) - { - activeMQJmsMessage = new ActiveMQTextMessage((TextMessage)jmsMessage, clientSession); + else if (jmsMessage instanceof TextMessage) { + activeMQJmsMessage = new ActiveMQTextMessage((TextMessage) jmsMessage, clientSession); } - else - { + else { activeMQJmsMessage = new ActiveMQMessage(jmsMessage, clientSession); } @@ -468,13 +426,11 @@ public class ActiveMQMessageProducer implements MessageProducer, QueueSender, To foreign = true; } - else - { - activeMQJmsMessage = (ActiveMQMessage)jmsMessage; + else { + activeMQJmsMessage = (ActiveMQMessage) jmsMessage; } - if (!disableMessageID) - { + if (!disableMessageID) { // Generate a JMS id UUID uid = UUIDGenerator.getInstance().generateUUID(); @@ -484,19 +440,16 @@ public class ActiveMQMessageProducer implements MessageProducer, QueueSender, To activeMQJmsMessage.resetMessageID(null); } - if (foreign) - { + if (foreign) { jmsMessage.setJMSMessageID(activeMQJmsMessage.getJMSMessageID()); } activeMQJmsMessage.setJMSDestination(destination); - try - { + try { activeMQJmsMessage.doBeforeSend(); } - catch (Exception e) - { + catch (Exception e) { JMSException je = new JMSException(e.getMessage()); je.initCause(e); @@ -504,45 +457,38 @@ public class ActiveMQMessageProducer implements MessageProducer, QueueSender, To throw je; } - if (defaultDeliveryDelay > 0) - { + if (defaultDeliveryDelay > 0) { activeMQJmsMessage.setJMSDeliveryTime(System.currentTimeMillis() + defaultDeliveryDelay); } ClientMessage coreMessage = activeMQJmsMessage.getCoreMessage(); coreMessage.putStringProperty(ActiveMQConnection.CONNECTION_ID_PROPERTY_NAME, connID); - try - { + try { /** * Using a completionListener requires wrapping using a {@link CompletionListenerWrapper}, * so we avoid it if we can. */ - if (completionListener != null) - { + if (completionListener != null) { clientProducer.send(address, coreMessage, new CompletionListenerWrapper(completionListener, jmsMessage, this)); } - else - { + else { clientProducer.send(address, coreMessage); } } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } - private void checkClosed() throws JMSException - { - if (clientProducer.isClosed() || clientSession.isClosed()) - { + private void checkClosed() throws JMSException { + if (clientProducer.isClosed() || clientSession.isClosed()) { throw new IllegalStateException("Producer is closed"); } } - private static final class CompletionListenerWrapper implements SendAcknowledgementHandler - { + private static final class CompletionListenerWrapper implements SendAcknowledgementHandler { + private final CompletionListener completionListener; private final Message jmsMessage; private final ActiveMQMessageProducer producer; @@ -551,53 +497,44 @@ public class ActiveMQMessageProducer implements MessageProducer, QueueSender, To * @param jmsMessage * @param producer */ - public CompletionListenerWrapper(CompletionListener listener, Message jmsMessage, ActiveMQMessageProducer producer) - { + public CompletionListenerWrapper(CompletionListener listener, + Message jmsMessage, + ActiveMQMessageProducer producer) { this.completionListener = listener; this.jmsMessage = jmsMessage; this.producer = producer; } @Override - public void sendAcknowledged(org.apache.activemq.artemis.api.core.Message clientMessage) - { - if (jmsMessage instanceof StreamMessage) - { - try - { - ((StreamMessage)jmsMessage).reset(); + public void sendAcknowledged(org.apache.activemq.artemis.api.core.Message clientMessage) { + if (jmsMessage instanceof StreamMessage) { + try { + ((StreamMessage) jmsMessage).reset(); } - catch (JMSException e) - { + catch (JMSException e) { // HORNETQ-1209 XXX ignore? } } - if (jmsMessage instanceof BytesMessage) - { - try - { - ((BytesMessage)jmsMessage).reset(); + if (jmsMessage instanceof BytesMessage) { + try { + ((BytesMessage) jmsMessage).reset(); } - catch (JMSException e) - { + catch (JMSException e) { // HORNETQ-1209 XXX ignore? } } - try - { + try { producer.connection.getThreadAwareContext().setCurrentThread(true); completionListener.onCompletion(jmsMessage); } - finally - { + finally { producer.connection.getThreadAwareContext().clearCurrentThread(true); } } @Override - public String toString() - { + public String toString() { return CompletionListenerWrapper.class.getSimpleName() + "( completionListener=" + completionListener + ")"; } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQObjectMessage.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQObjectMessage.java index e382c30dc2..eebccd17c4 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQObjectMessage.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQObjectMessage.java @@ -38,8 +38,7 @@ import org.apache.activemq.artemis.utils.ObjectInputStreamWithClassLoader; *

    * Serialization is slooooow! */ -public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMessage -{ +public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMessage { // Constants ----------------------------------------------------- public static final byte TYPE = Message.OBJECT_TYPE; @@ -53,21 +52,18 @@ public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMess // Constructors -------------------------------------------------- - protected ActiveMQObjectMessage(final ClientSession session) - { + protected ActiveMQObjectMessage(final ClientSession session) { super(ActiveMQObjectMessage.TYPE, session); } - protected ActiveMQObjectMessage(final ClientMessage message, final ClientSession session) - { + protected ActiveMQObjectMessage(final ClientMessage message, final ClientSession session) { super(message, session); } /** * A copy constructor for foreign JMS ObjectMessages. */ - public ActiveMQObjectMessage(final ObjectMessage foreign, final ClientSession session) throws JMSException - { + public ActiveMQObjectMessage(final ObjectMessage foreign, final ClientSession session) throws JMSException { super(foreign, ActiveMQObjectMessage.TYPE, session); setObject(foreign.getObject()); @@ -76,17 +72,14 @@ public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMess // Public -------------------------------------------------------- @Override - public byte getType() - { + public byte getType() { return ActiveMQObjectMessage.TYPE; } @Override - public void doBeforeSend() throws Exception - { + public void doBeforeSend() throws Exception { message.getBodyBuffer().clear(); - if (data != null) - { + if (data != null) { message.getBodyBuffer().writeInt(data.length); message.getBodyBuffer().writeBytes(data); } @@ -95,17 +88,14 @@ public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMess } @Override - public void doBeforeReceive() throws ActiveMQException - { + public void doBeforeReceive() throws ActiveMQException { super.doBeforeReceive(); - try - { + try { int len = message.getBodyBuffer().readInt(); data = new byte[len]; message.getBodyBuffer().readBytes(data); } - catch (Exception e) - { + catch (Exception e) { data = null; } @@ -113,14 +103,11 @@ public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMess // ObjectMessage implementation ---------------------------------- - public void setObject(final Serializable object) throws JMSException - { + public void setObject(final Serializable object) throws JMSException { checkWrite(); - if (object != null) - { - try - { + if (object != null) { + try { ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); ObjectOutputStream oos = new ObjectOutputStream(baos); @@ -131,8 +118,7 @@ public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMess data = baos.toByteArray(); } - catch (Exception e) - { + catch (Exception e) { JMSException je = new JMSException("Failed to serialize object"); je.setLinkedException(e); je.initCause(e); @@ -142,22 +128,18 @@ public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMess } // lazy deserialize the Object the first time the client requests it - public Serializable getObject() throws JMSException - { - if (data == null || data.length == 0) - { + public Serializable getObject() throws JMSException { + if (data == null || data.length == 0) { return null; } - try - { + try { ByteArrayInputStream bais = new ByteArrayInputStream(data); ObjectInputStream ois = new ObjectInputStreamWithClassLoader(bais); - Serializable object = (Serializable)ois.readObject(); + Serializable object = (Serializable) ois.readObject(); return object; } - catch (Exception e) - { + catch (Exception e) { JMSException je = new JMSException(e.getMessage()); je.setStackTrace(e.getStackTrace()); throw je; @@ -165,38 +147,30 @@ public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMess } @Override - public void clearBody() throws JMSException - { + public void clearBody() throws JMSException { super.clearBody(); data = null; } @Override - protected T getBodyInternal(Class c) throws MessageFormatException - { - try - { - return (T)getObject(); + protected T getBodyInternal(Class c) throws MessageFormatException { + try { + return (T) getObject(); } - catch (JMSException e) - { + catch (JMSException e) { throw new MessageFormatException("Deserialization error on ActiveMQObjectMessage"); } } @Override - public boolean isBodyAssignableTo(@SuppressWarnings("rawtypes") - Class c) - { + public boolean isBodyAssignableTo(@SuppressWarnings("rawtypes") Class c) { if (data == null) // we have no body return true; - try - { + try { return Serializable.class == c || Object.class == c || c.isInstance(getObject()); } - catch (JMSException e) - { + catch (JMSException e) { return false; } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQQueue.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQQueue.java index 0fac316e24..7660dfa83f 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQQueue.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQQueue.java @@ -25,15 +25,14 @@ import org.apache.activemq.artemis.api.core.SimpleString; *
    * This class can be instantiated directly. */ -public class ActiveMQQueue extends ActiveMQDestination implements Queue -{ +public class ActiveMQQueue extends ActiveMQDestination implements Queue { + // Constants ----------------------------------------------------- private static final long serialVersionUID = -1106092883162295462L; // Static -------------------------------------------------------- - public static SimpleString createAddressFromName(final String name) - { + public static SimpleString createAddressFromName(final String name) { return new SimpleString(JMS_QUEUE_ADDRESS_PREFIX + name); } @@ -41,31 +40,25 @@ public class ActiveMQQueue extends ActiveMQDestination implements Queue // Constructors -------------------------------------------------- - public ActiveMQQueue(final String name) - { + public ActiveMQQueue(final String name) { super(JMS_QUEUE_ADDRESS_PREFIX + name, name, false, true, null); } - public ActiveMQQueue(final String name, boolean temporary) - { + public ActiveMQQueue(final String name, boolean temporary) { super(JMS_QUEUE_ADDRESS_PREFIX + name, name, temporary, true, null); } - - /** * @param address * @param name * @param temporary * @param session */ - public ActiveMQQueue(String address, String name, boolean temporary, ActiveMQSession session) - { + public ActiveMQQueue(String address, String name, boolean temporary, ActiveMQSession session) { super(address, name, temporary, true, session); } - public ActiveMQQueue(final String address, final String name) - { + public ActiveMQQueue(final String address, final String name) { super(address, name, false, true, null); } @@ -73,14 +66,12 @@ public class ActiveMQQueue extends ActiveMQDestination implements Queue // Public -------------------------------------------------------- - public String getQueueName() - { + public String getQueueName() { return name; } @Override - public String toString() - { + public String toString() { return "ActiveMQQueue[" + name + "]"; } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQQueueBrowser.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQQueueBrowser.java index a716eff929..493029bf44 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQQueueBrowser.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQQueueBrowser.java @@ -32,8 +32,7 @@ import org.apache.activemq.artemis.api.core.client.ClientSession; /** * ActiveMQ Artemis implementation of a JMS QueueBrowser. */ -public final class ActiveMQQueueBrowser implements QueueBrowser -{ +public final class ActiveMQQueueBrowser implements QueueBrowser { // Constants ------------------------------------------------------------------------------------ // Static --------------------------------------------------------------------------------------- @@ -50,65 +49,55 @@ public final class ActiveMQQueueBrowser implements QueueBrowser // Constructors --------------------------------------------------------------------------------- - protected ActiveMQQueueBrowser(final ActiveMQQueue queue, final String messageSelector, final ClientSession session) throws JMSException - { + protected ActiveMQQueueBrowser(final ActiveMQQueue queue, + final String messageSelector, + final ClientSession session) throws JMSException { this.session = session; this.queue = queue; - if (messageSelector != null) - { + if (messageSelector != null) { filterString = new SimpleString(SelectorTranslator.convertToActiveMQFilterString(messageSelector)); } } // QueueBrowser implementation ------------------------------------------------------------------- - public void close() throws JMSException - { - if (consumer != null) - { - try - { + public void close() throws JMSException { + if (consumer != null) { + try { consumer.close(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } } - public Enumeration getEnumeration() throws JMSException - { - try - { + public Enumeration getEnumeration() throws JMSException { + try { close(); consumer = session.createConsumer(queue.getSimpleAddress(), filterString, true); return new BrowserEnumeration(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } - public String getMessageSelector() throws JMSException - { + public String getMessageSelector() throws JMSException { return filterString == null ? null : filterString.toString(); } - public Queue getQueue() throws JMSException - { + public Queue getQueue() throws JMSException { return queue; } // Public --------------------------------------------------------------------------------------- @Override - public String toString() - { + public String toString() { return "ActiveMQQueueBrowser->" + consumer; } @@ -120,48 +109,39 @@ public final class ActiveMQQueueBrowser implements QueueBrowser // Inner classes -------------------------------------------------------------------------------- - private final class BrowserEnumeration implements Enumeration - { + private final class BrowserEnumeration implements Enumeration { + ClientMessage current = null; - public boolean hasMoreElements() - { - if (current == null) - { - try - { + public boolean hasMoreElements() { + if (current == null) { + try { current = consumer.receiveImmediate(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { return false; } } return current != null; } - public ActiveMQMessage nextElement() - { + public ActiveMQMessage nextElement() { ActiveMQMessage msg; - if (hasMoreElements()) - { + if (hasMoreElements()) { ClientMessage next = current; current = null; msg = ActiveMQMessage.createMessage(next, session); - try - { + try { msg.doBeforeReceive(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQJMSClientLogger.LOGGER.errorCreatingMessage(e); return null; } return msg; } - else - { + else { throw new NoSuchElementException(); } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQQueueConnectionFactory.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQQueueConnectionFactory.java index 64da71684f..6fdce7066e 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQQueueConnectionFactory.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQQueueConnectionFactory.java @@ -26,42 +26,35 @@ import org.apache.activemq.artemis.api.jms.JMSFactoryType; /** * {@inheritDoc} */ -public class ActiveMQQueueConnectionFactory extends ActiveMQConnectionFactory implements QueueConnectionFactory -{ +public class ActiveMQQueueConnectionFactory extends ActiveMQConnectionFactory implements QueueConnectionFactory { + private static final long serialVersionUID = 5312455021322463546L; - public ActiveMQQueueConnectionFactory() - { + public ActiveMQQueueConnectionFactory() { super(); } - public ActiveMQQueueConnectionFactory(String url) - { + public ActiveMQQueueConnectionFactory(String url) { super(url); } - public ActiveMQQueueConnectionFactory(ServerLocator serverLocator) - { + public ActiveMQQueueConnectionFactory(ServerLocator serverLocator) { super(serverLocator); } - public ActiveMQQueueConnectionFactory(boolean ha, final DiscoveryGroupConfiguration groupConfiguration) - { + public ActiveMQQueueConnectionFactory(boolean ha, final DiscoveryGroupConfiguration groupConfiguration) { super(ha, groupConfiguration); } - public ActiveMQQueueConnectionFactory(String url, String user, String password) - { + public ActiveMQQueueConnectionFactory(String url, String user, String password) { super(url, user, password); } - public ActiveMQQueueConnectionFactory(boolean ha, TransportConfiguration... initialConnectors) - { + public ActiveMQQueueConnectionFactory(boolean ha, TransportConfiguration... initialConnectors) { super(ha, initialConnectors); } - public int getFactoryType() - { + public int getFactoryType() { return JMSFactoryType.QUEUE_CF.intValue(); } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQSession.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQSession.java index 30397e8b33..758ad36147 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQSession.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQSession.java @@ -66,8 +66,8 @@ import org.apache.activemq.artemis.api.core.client.ClientSession.QueueQuery; * Note that we *do not* support JMS ASF (Application Server Facilities) optional * constructs such as ConnectionConsumer */ -public class ActiveMQSession implements QueueSession, TopicSession -{ +public class ActiveMQSession implements QueueSession, TopicSession { + public static final int TYPE_GENERIC_SESSION = 0; public static final int TYPE_QUEUE_SESSION = 1; @@ -99,8 +99,7 @@ public class ActiveMQSession implements QueueSession, TopicSession final boolean xa, final int ackMode, final ClientSession session, - final int sessionType) - { + final int sessionType) { this.connection = connection; this.ackMode = ackMode; @@ -116,36 +115,31 @@ public class ActiveMQSession implements QueueSession, TopicSession // Session implementation ---------------------------------------- - public BytesMessage createBytesMessage() throws JMSException - { + public BytesMessage createBytesMessage() throws JMSException { checkClosed(); return new ActiveMQBytesMessage(session); } - public MapMessage createMapMessage() throws JMSException - { + public MapMessage createMapMessage() throws JMSException { checkClosed(); return new ActiveMQMapMessage(session); } - public Message createMessage() throws JMSException - { + public Message createMessage() throws JMSException { checkClosed(); return new ActiveMQMessage(session); } - public ObjectMessage createObjectMessage() throws JMSException - { + public ObjectMessage createObjectMessage() throws JMSException { checkClosed(); return new ActiveMQObjectMessage(session); } - public ObjectMessage createObjectMessage(final Serializable object) throws JMSException - { + public ObjectMessage createObjectMessage(final Serializable object) throws JMSException { checkClosed(); ActiveMQObjectMessage msg = new ActiveMQObjectMessage(session); @@ -155,15 +149,13 @@ public class ActiveMQSession implements QueueSession, TopicSession return msg; } - public StreamMessage createStreamMessage() throws JMSException - { + public StreamMessage createStreamMessage() throws JMSException { checkClosed(); return new ActiveMQStreamMessage(session); } - public TextMessage createTextMessage() throws JMSException - { + public TextMessage createTextMessage() throws JMSException { checkClosed(); ActiveMQTextMessage msg = new ActiveMQTextMessage(session); @@ -173,8 +165,7 @@ public class ActiveMQSession implements QueueSession, TopicSession return msg; } - public TextMessage createTextMessage(final String text) throws JMSException - { + public TextMessage createTextMessage(final String text) throws JMSException { checkClosed(); ActiveMQTextMessage msg = new ActiveMQTextMessage(session); @@ -184,76 +175,59 @@ public class ActiveMQSession implements QueueSession, TopicSession return msg; } - public boolean getTransacted() throws JMSException - { + public boolean getTransacted() throws JMSException { checkClosed(); return transacted; } - public int getAcknowledgeMode() throws JMSException - { + public int getAcknowledgeMode() throws JMSException { checkClosed(); return ackMode; } - public boolean isXA() - { + public boolean isXA() { return xa; } - public void commit() throws JMSException - { - if (!transacted) - { + public void commit() throws JMSException { + if (!transacted) { throw new IllegalStateException("Cannot commit a non-transacted session"); } - if (xa) - { + if (xa) { throw new TransactionInProgressException("Cannot call commit on an XA session"); } - try - { + try { session.commit(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } - public void rollback() throws JMSException - { - if (!transacted) - { + public void rollback() throws JMSException { + if (!transacted) { throw new IllegalStateException("Cannot rollback a non-transacted session"); } - if (xa) - { + if (xa) { throw new TransactionInProgressException("Cannot call rollback on an XA session"); } - try - { + try { session.rollback(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } - public void close() throws JMSException - { + public void close() throws JMSException { connection.getThreadAwareContext().assertNotCompletionListenerThread(); connection.getThreadAwareContext().assertNotMessageListenerThread(); - synchronized (connection) - { - try - { - for (ActiveMQMessageConsumer cons : new HashSet(consumers)) - { + synchronized (connection) { + try { + for (ActiveMQMessageConsumer cons : new HashSet(consumers)) { cons.close(); } @@ -261,71 +235,56 @@ public class ActiveMQSession implements QueueSession, TopicSession connection.removeSession(this); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } } - public void recover() throws JMSException - { - if (transacted) - { + public void recover() throws JMSException { + if (transacted) { throw new IllegalStateException("Cannot recover a transacted session"); } - try - { + try { session.rollback(true); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } recoverCalled = true; } - public MessageListener getMessageListener() throws JMSException - { + public MessageListener getMessageListener() throws JMSException { checkClosed(); return null; } - public void setMessageListener(final MessageListener listener) throws JMSException - { + public void setMessageListener(final MessageListener listener) throws JMSException { checkClosed(); } - public void run() - { + public void run() { } - public MessageProducer createProducer(final Destination destination) throws JMSException - { - if (destination != null && !(destination instanceof ActiveMQDestination)) - { + public MessageProducer createProducer(final Destination destination) throws JMSException { + if (destination != null && !(destination instanceof ActiveMQDestination)) { throw new InvalidDestinationException("Not an ActiveMQ Artemis Destination:" + destination); } - try - { - ActiveMQDestination jbd = (ActiveMQDestination)destination; + try { + ActiveMQDestination jbd = (ActiveMQDestination) destination; - if (jbd != null) - { + if (jbd != null) { ClientSession.AddressQuery response = session.addressQuery(jbd.getSimpleAddress()); - if (!response.isExists()) - { - if (response.isAutoCreateJmsQueues()) - { + if (!response.isExists()) { + if (response.isAutoCreateJmsQueues()) { session.createQueue(jbd.getSimpleAddress(), jbd.getSimpleAddress(), true); } - else - { + else { throw new InvalidDestinationException("Destination " + jbd.getName() + " does not exist"); } } @@ -337,157 +296,128 @@ public class ActiveMQSession implements QueueSession, TopicSession return new ActiveMQMessageProducer(connection, producer, jbd, session); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } - public MessageConsumer createConsumer(final Destination destination) throws JMSException - { + public MessageConsumer createConsumer(final Destination destination) throws JMSException { return createConsumer(destination, null, false); } - public MessageConsumer createConsumer(final Destination destination, final String messageSelector) throws JMSException - { + public MessageConsumer createConsumer(final Destination destination, + final String messageSelector) throws JMSException { return createConsumer(destination, messageSelector, false); } public MessageConsumer createConsumer(final Destination destination, final String messageSelector, - final boolean noLocal) throws JMSException - { - if (destination == null) - { + final boolean noLocal) throws JMSException { + if (destination == null) { throw new InvalidDestinationException("Cannot create a consumer with a null destination"); } - if (!(destination instanceof ActiveMQDestination)) - { + if (!(destination instanceof ActiveMQDestination)) { throw new InvalidDestinationException("Not an ActiveMQDestination:" + destination); } - ActiveMQDestination jbdest = (ActiveMQDestination)destination; + ActiveMQDestination jbdest = (ActiveMQDestination) destination; - if (jbdest.isTemporary() && !connection.containsTemporaryQueue(jbdest.getSimpleAddress())) - { + if (jbdest.isTemporary() && !connection.containsTemporaryQueue(jbdest.getSimpleAddress())) { throw new JMSException("Can not create consumer for temporary destination " + destination + - " from another JMS connection"); + " from another JMS connection"); } return createConsumer(jbdest, null, messageSelector, noLocal, ConsumerDurability.NON_DURABLE); } - public Queue createQueue(final String queueName) throws JMSException - { + public Queue createQueue(final String queueName) throws JMSException { // As per spec. section 4.11 - if (sessionType == ActiveMQSession.TYPE_TOPIC_SESSION) - { + if (sessionType == ActiveMQSession.TYPE_TOPIC_SESSION) { throw new IllegalStateException("Cannot create a queue using a TopicSession"); } - try - { + try { ActiveMQQueue queue = lookupQueue(queueName, false); - if (queue == null) - { + if (queue == null) { queue = lookupQueue(queueName, true); } - if (queue == null) - { + if (queue == null) { throw new JMSException("There is no queue with name " + queueName); } - else - { + else { return queue; } } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } - public Topic createTopic(final String topicName) throws JMSException - { + public Topic createTopic(final String topicName) throws JMSException { // As per spec. section 4.11 - if (sessionType == ActiveMQSession.TYPE_QUEUE_SESSION) - { + if (sessionType == ActiveMQSession.TYPE_QUEUE_SESSION) { throw new IllegalStateException("Cannot create a topic on a QueueSession"); } - try - { + try { ActiveMQTopic topic = lookupTopic(topicName, false); - if (topic == null) - { + if (topic == null) { topic = lookupTopic(topicName, true); } - if (topic == null) - { + if (topic == null) { throw new JMSException("There is no topic with name " + topicName); } - else - { + else { return topic; } } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } - public TopicSubscriber createDurableSubscriber(final Topic topic, final String name) throws JMSException - { + public TopicSubscriber createDurableSubscriber(final Topic topic, final String name) throws JMSException { return createDurableSubscriber(topic, name, null, false); } public TopicSubscriber createDurableSubscriber(final Topic topic, final String name, String messageSelector, - final boolean noLocal) throws JMSException - { + final boolean noLocal) throws JMSException { // As per spec. section 4.11 - if (sessionType == ActiveMQSession.TYPE_QUEUE_SESSION) - { + if (sessionType == ActiveMQSession.TYPE_QUEUE_SESSION) { throw new IllegalStateException("Cannot create a durable subscriber on a QueueSession"); } checkTopic(topic); - if (!(topic instanceof ActiveMQDestination)) - { + if (!(topic instanceof ActiveMQDestination)) { throw new InvalidDestinationException("Not an ActiveMQTopic:" + topic); } - if ("".equals(messageSelector)) - { + if ("".equals(messageSelector)) { messageSelector = null; } - ActiveMQDestination jbdest = (ActiveMQDestination)topic; + ActiveMQDestination jbdest = (ActiveMQDestination) topic; - if (jbdest.isQueue()) - { + if (jbdest.isQueue()) { throw new InvalidDestinationException("Cannot create a subscriber on a queue"); } return createConsumer(jbdest, name, messageSelector, noLocal, ConsumerDurability.DURABLE); } - private void checkTopic(Topic topic) throws InvalidDestinationException - { - if (topic == null) - { + private void checkTopic(Topic topic) throws InvalidDestinationException { + if (topic == null) { throw ActiveMQJMSClientBundle.BUNDLE.nullTopic(); } } @Override - public MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName) throws JMSException - { + public MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName) throws JMSException { return createSharedConsumer(topic, sharedSubscriptionName, null); } @@ -506,62 +436,55 @@ public class ActiveMQSession implements QueueSession, TopicSession * @throws JMSException */ @Override - public MessageConsumer createSharedConsumer(Topic topic, String name, String messageSelector) throws JMSException - { - if (sessionType == ActiveMQSession.TYPE_QUEUE_SESSION) - { + public MessageConsumer createSharedConsumer(Topic topic, String name, String messageSelector) throws JMSException { + if (sessionType == ActiveMQSession.TYPE_QUEUE_SESSION) { throw new IllegalStateException("Cannot create a shared consumer on a QueueSession"); } checkTopic(topic); ActiveMQTopic localTopic; - if (topic instanceof ActiveMQTopic) - { - localTopic = (ActiveMQTopic)topic; + if (topic instanceof ActiveMQTopic) { + localTopic = (ActiveMQTopic) topic; } - else - { + else { localTopic = new ActiveMQTopic(topic.getTopicName()); } return internalCreateSharedConsumer(localTopic, name, messageSelector, ConsumerDurability.NON_DURABLE, true); } @Override - public MessageConsumer createDurableConsumer(Topic topic, String name) throws JMSException - { + public MessageConsumer createDurableConsumer(Topic topic, String name) throws JMSException { return createDurableConsumer(topic, name, null, false); } @Override - public MessageConsumer createDurableConsumer(Topic topic, String name, String messageSelector, boolean noLocal) throws JMSException - { - if (sessionType == ActiveMQSession.TYPE_QUEUE_SESSION) - { + public MessageConsumer createDurableConsumer(Topic topic, + String name, + String messageSelector, + boolean noLocal) throws JMSException { + if (sessionType == ActiveMQSession.TYPE_QUEUE_SESSION) { throw new IllegalStateException("Cannot create a durable consumer on a QueueSession"); } checkTopic(topic); ActiveMQTopic localTopic; - if (topic instanceof ActiveMQTopic) - { - localTopic = (ActiveMQTopic)topic; + if (topic instanceof ActiveMQTopic) { + localTopic = (ActiveMQTopic) topic; } - else - { + else { localTopic = new ActiveMQTopic(topic.getTopicName()); } return createConsumer(localTopic, name, messageSelector, noLocal, ConsumerDurability.DURABLE); } @Override - public MessageConsumer createSharedDurableConsumer(Topic topic, String name) throws JMSException - { + public MessageConsumer createSharedDurableConsumer(Topic topic, String name) throws JMSException { return createSharedDurableConsumer(topic, name, null); } @Override - public MessageConsumer createSharedDurableConsumer(Topic topic, String name, String messageSelector) throws JMSException - { - if (sessionType == ActiveMQSession.TYPE_QUEUE_SESSION) - { + public MessageConsumer createSharedDurableConsumer(Topic topic, + String name, + String messageSelector) throws JMSException { + if (sessionType == ActiveMQSession.TYPE_QUEUE_SESSION) { throw new IllegalStateException("Cannot create a shared durable consumer on a QueueSession"); } @@ -569,44 +492,36 @@ public class ActiveMQSession implements QueueSession, TopicSession ActiveMQTopic localTopic; - if (topic instanceof ActiveMQTopic) - { - localTopic = (ActiveMQTopic)topic; + if (topic instanceof ActiveMQTopic) { + localTopic = (ActiveMQTopic) topic; } - else - { + else { localTopic = new ActiveMQTopic(topic.getTopicName()); } return internalCreateSharedConsumer(localTopic, name, messageSelector, ConsumerDurability.DURABLE, true); } - enum ConsumerDurability - { + enum ConsumerDurability { DURABLE, NON_DURABLE; } - /** * This is an internal method for shared consumers */ private ActiveMQMessageConsumer internalCreateSharedConsumer(final ActiveMQDestination dest, - final String subscriptionName, - String selectorString, - ConsumerDurability durability, - final boolean shared) throws JMSException - { - try - { + final String subscriptionName, + String selectorString, + ConsumerDurability durability, + final boolean shared) throws JMSException { + try { - if (dest.isQueue()) - { + if (dest.isQueue()) { // This is not really possible unless someone makes a mistake on code // createSharedConsumer only accpets Topics by declaration throw new RuntimeException("Internal error: createSharedConsumer is only meant for Topics"); } - if (subscriptionName == null) - { + if (subscriptionName == null) { throw ActiveMQJMSClientBundle.BUNDLE.invalidSubscriptionName(); } @@ -614,8 +529,7 @@ public class ActiveMQSession implements QueueSession, TopicSession SimpleString coreFilterString = null; - if (selectorString != null) - { + if (selectorString != null) { coreFilterString = new SimpleString(SelectorTranslator.convertToActiveMQFilterString(selectorString)); } @@ -625,99 +539,76 @@ public class ActiveMQSession implements QueueSession, TopicSession AddressQuery response = session.addressQuery(dest.getSimpleAddress()); - if (!response.isExists()) - { + if (!response.isExists()) { throw ActiveMQJMSClientBundle.BUNDLE.destinationDoesNotExist(dest.getSimpleAddress()); } SimpleString queueName; - if (dest.isTemporary() && durability == ConsumerDurability.DURABLE) - { + if (dest.isTemporary() && durability == ConsumerDurability.DURABLE) { throw new InvalidDestinationException("Cannot create a durable subscription on a temporary topic"); } - queueName = new SimpleString(ActiveMQDestination.createQueueNameForDurableSubscription(durability == ConsumerDurability.DURABLE, connection.getClientID(), - subscriptionName)); + queueName = new SimpleString(ActiveMQDestination.createQueueNameForDurableSubscription(durability == ConsumerDurability.DURABLE, connection.getClientID(), subscriptionName)); - if (durability == ConsumerDurability.DURABLE) - { - try - { + if (durability == ConsumerDurability.DURABLE) { + try { session.createSharedQueue(dest.getSimpleAddress(), queueName, coreFilterString, true); } - catch (ActiveMQQueueExistsException ignored) - { + catch (ActiveMQQueueExistsException ignored) { // We ignore this because querying and then creating the queue wouldn't be idempotent // we could also add a parameter to ignore existence what would require a bigger work around to avoid // compatibility. } } - else - { + else { session.createSharedQueue(dest.getSimpleAddress(), queueName, coreFilterString, false); } consumer = session.createConsumer(queueName, null, false); - ActiveMQMessageConsumer jbc = new ActiveMQMessageConsumer(connection, this, - consumer, - false, - dest, - selectorString, - autoDeleteQueueName); + ActiveMQMessageConsumer jbc = new ActiveMQMessageConsumer(connection, this, consumer, false, dest, selectorString, autoDeleteQueueName); consumers.add(jbc); return jbc; } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } - - private ActiveMQMessageConsumer createConsumer(final ActiveMQDestination dest, - final String subscriptionName, - String selectorString, final boolean noLocal, - ConsumerDurability durability) throws JMSException - { - try - { + final String subscriptionName, + String selectorString, + final boolean noLocal, + ConsumerDurability durability) throws JMSException { + try { selectorString = "".equals(selectorString) ? null : selectorString; - if (noLocal) - { + if (noLocal) { connection.setHasNoLocal(); String filter; - if (connection.getClientID() != null) - { - filter = - ActiveMQConnection.CONNECTION_ID_PROPERTY_NAME.toString() + "<>'" + connection.getClientID() + - "'"; + if (connection.getClientID() != null) { + filter = ActiveMQConnection.CONNECTION_ID_PROPERTY_NAME.toString() + "<>'" + connection.getClientID() + + "'"; } - else - { + else { filter = ActiveMQConnection.CONNECTION_ID_PROPERTY_NAME.toString() + "<>'" + connection.getUID() + "'"; } - if (selectorString != null) - { + if (selectorString != null) { selectorString += " AND " + filter; } - else - { + else { selectorString = filter; } } SimpleString coreFilterString = null; - if (selectorString != null) - { + if (selectorString != null) { coreFilterString = new SimpleString(SelectorTranslator.convertToActiveMQFilterString(selectorString)); } @@ -725,18 +616,14 @@ public class ActiveMQSession implements QueueSession, TopicSession SimpleString autoDeleteQueueName = null; - if (dest.isQueue()) - { + if (dest.isQueue()) { AddressQuery response = session.addressQuery(dest.getSimpleAddress()); - if (!response.isExists()) - { - if (response.isAutoCreateJmsQueues()) - { + if (!response.isExists()) { + if (response.isAutoCreateJmsQueues()) { session.createQueue(dest.getSimpleAddress(), dest.getSimpleAddress(), true); } - else - { + else { throw new InvalidDestinationException("Destination " + dest.getName() + " does not exist"); } } @@ -745,12 +632,10 @@ public class ActiveMQSession implements QueueSession, TopicSession consumer = session.createConsumer(dest.getSimpleAddress(), coreFilterString, false); } - else - { + else { AddressQuery response = session.addressQuery(dest.getSimpleAddress()); - if (!response.isExists()) - { + if (!response.isExists()) { throw new InvalidDestinationException("Topic " + dest.getName() + " does not exist"); } @@ -758,8 +643,7 @@ public class ActiveMQSession implements QueueSession, TopicSession SimpleString queueName; - if (subscriptionName == null) - { + if (subscriptionName == null) { if (durability != ConsumerDurability.NON_DURABLE) throw new RuntimeException("Subscription name cannot be null for durable topic consumer"); // Non durable sub @@ -772,35 +656,28 @@ public class ActiveMQSession implements QueueSession, TopicSession autoDeleteQueueName = queueName; } - else - { + else { // Durable sub if (durability != ConsumerDurability.DURABLE) throw new RuntimeException("Subscription name must be null for non-durable topic consumer"); - if (connection.getClientID() == null) - { + if (connection.getClientID() == null) { throw new IllegalStateException("Cannot create durable subscription - client ID has not been set"); } - if (dest.isTemporary()) - { + if (dest.isTemporary()) { throw new InvalidDestinationException("Cannot create a durable subscription on a temporary topic"); } - queueName = new SimpleString(ActiveMQDestination.createQueueNameForDurableSubscription(true, connection.getClientID(), - subscriptionName)); + queueName = new SimpleString(ActiveMQDestination.createQueueNameForDurableSubscription(true, connection.getClientID(), subscriptionName)); QueueQuery subResponse = session.queueQuery(queueName); - if (!subResponse.isExists()) - { + if (!subResponse.isExists()) { session.createQueue(dest.getSimpleAddress(), queueName, coreFilterString, true); } - else - { + else { // Already exists - if (subResponse.getConsumerCount() > 0) - { + if (subResponse.getConsumerCount() > 0) { throw new IllegalStateException("Cannot create a subscriber on the durable subscription since it already has subscriber(s)"); } @@ -816,18 +693,16 @@ public class ActiveMQSession implements QueueSession, TopicSession SimpleString oldFilterString = subResponse.getFilterString(); boolean selectorChanged = coreFilterString == null && oldFilterString != null || - oldFilterString == null && - coreFilterString != null || - oldFilterString != null && - coreFilterString != null && - !oldFilterString.equals(coreFilterString); + oldFilterString == null && coreFilterString != null || + oldFilterString != null && + coreFilterString != null && + !oldFilterString.equals(coreFilterString); SimpleString oldTopicName = subResponse.getAddress(); boolean topicChanged = !oldTopicName.equals(dest.getSimpleAddress()); - if (selectorChanged || topicChanged) - { + if (selectorChanged || topicChanged) { // Delete the old durable sub session.deleteQueue(queueName); @@ -840,108 +715,82 @@ public class ActiveMQSession implements QueueSession, TopicSession } } - ActiveMQMessageConsumer jbc = new ActiveMQMessageConsumer(connection, - this, - consumer, - noLocal, - dest, - selectorString, - autoDeleteQueueName); + ActiveMQMessageConsumer jbc = new ActiveMQMessageConsumer(connection, this, consumer, noLocal, dest, selectorString, autoDeleteQueueName); consumers.add(jbc); return jbc; } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } - public void ackAllConsumers() throws JMSException - { + public void ackAllConsumers() throws JMSException { checkClosed(); } - public QueueBrowser createBrowser(final Queue queue) throws JMSException - { + public QueueBrowser createBrowser(final Queue queue) throws JMSException { return createBrowser(queue, null); } - public QueueBrowser createBrowser(final Queue queue, String filterString) throws JMSException - { + public QueueBrowser createBrowser(final Queue queue, String filterString) throws JMSException { // As per spec. section 4.11 - if (sessionType == ActiveMQSession.TYPE_TOPIC_SESSION) - { + if (sessionType == ActiveMQSession.TYPE_TOPIC_SESSION) { throw new IllegalStateException("Cannot create a browser on a TopicSession"); } - if (queue == null) - { + if (queue == null) { throw new InvalidDestinationException("Cannot create a browser with a null queue"); } - if (!(queue instanceof ActiveMQDestination)) - { + if (!(queue instanceof ActiveMQDestination)) { throw new InvalidDestinationException("Not an ActiveMQQueue:" + queue); } - if ("".equals(filterString)) - { + if ("".equals(filterString)) { filterString = null; } // eager test of the filter syntax as required by JMS spec - try - { - if (filterString != null) - { + try { + if (filterString != null) { SelectorParser.parse(filterString.trim()); } } - catch (FilterException e) - { + catch (FilterException e) { throw JMSExceptionHelper.convertFromActiveMQException(ActiveMQJMSClientBundle.BUNDLE.invalidFilter(e, new SimpleString(filterString))); } - ActiveMQDestination jbq = (ActiveMQDestination)queue; + ActiveMQDestination jbq = (ActiveMQDestination) queue; - if (!jbq.isQueue()) - { + if (!jbq.isQueue()) { throw new InvalidDestinationException("Cannot create a browser on a topic"); } - try - { + try { AddressQuery response = session.addressQuery(new SimpleString(jbq.getAddress())); - if (!response.isExists()) - { - if (response.isAutoCreateJmsQueues()) - { + if (!response.isExists()) { + if (response.isAutoCreateJmsQueues()) { session.createQueue(jbq.getSimpleAddress(), jbq.getSimpleAddress(), true); } - else - { + else { throw new InvalidDestinationException("Destination " + jbq.getName() + " does not exist"); } } } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } - return new ActiveMQQueueBrowser((ActiveMQQueue)jbq, filterString, session); + return new ActiveMQQueueBrowser((ActiveMQQueue) jbq, filterString, session); } - public TemporaryQueue createTemporaryQueue() throws JMSException - { + public TemporaryQueue createTemporaryQueue() throws JMSException { // As per spec. section 4.11 - if (sessionType == ActiveMQSession.TYPE_TOPIC_SESSION) - { + if (sessionType == ActiveMQSession.TYPE_TOPIC_SESSION) { throw new IllegalStateException("Cannot create a temporary queue using a TopicSession"); } - try - { + try { ActiveMQTemporaryQueue queue = ActiveMQDestination.createTemporaryQueue(this); SimpleString simpleAddress = queue.getSimpleAddress(); @@ -952,22 +801,18 @@ public class ActiveMQSession implements QueueSession, TopicSession return queue; } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } - public TemporaryTopic createTemporaryTopic() throws JMSException - { + public TemporaryTopic createTemporaryTopic() throws JMSException { // As per spec. section 4.11 - if (sessionType == ActiveMQSession.TYPE_QUEUE_SESSION) - { + if (sessionType == ActiveMQSession.TYPE_QUEUE_SESSION) { throw new IllegalStateException("Cannot create a temporary topic on a QueueSession"); } - try - { + try { ActiveMQTemporaryTopic topic = ActiveMQDestination.createTemporaryTopic(this); SimpleString simpleAddress = topic.getSimpleAddress(); @@ -983,156 +828,130 @@ public class ActiveMQSession implements QueueSession, TopicSession return topic; } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } - public void unsubscribe(final String name) throws JMSException - { + public void unsubscribe(final String name) throws JMSException { // As per spec. section 4.11 - if (sessionType == ActiveMQSession.TYPE_QUEUE_SESSION) - { + if (sessionType == ActiveMQSession.TYPE_QUEUE_SESSION) { throw new IllegalStateException("Cannot unsubscribe using a QueueSession"); } - SimpleString queueName = new SimpleString(ActiveMQDestination.createQueueNameForDurableSubscription(true, connection.getClientID(), - name)); + SimpleString queueName = new SimpleString(ActiveMQDestination.createQueueNameForDurableSubscription(true, connection.getClientID(), name)); - try - { + try { QueueQuery response = session.queueQuery(queueName); - if (!response.isExists()) - { + if (!response.isExists()) { throw new InvalidDestinationException("Cannot unsubscribe, subscription with name " + name + - " does not exist"); + " does not exist"); } - if (response.getConsumerCount() != 0) - { + if (response.getConsumerCount() != 0) { throw new IllegalStateException("Cannot unsubscribe durable subscription " + name + - " since it has active subscribers"); + " since it has active subscribers"); } session.deleteQueue(queueName); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } // XASession implementation - public Session getSession() throws JMSException - { - if (!xa) - { + public Session getSession() throws JMSException { + if (!xa) { throw new IllegalStateException("Isn't an XASession"); } return this; } - public XAResource getXAResource() - { + public XAResource getXAResource() { return session.getXAResource(); } // QueueSession implementation - public QueueReceiver createReceiver(final Queue queue, final String messageSelector) throws JMSException - { - return (QueueReceiver)createConsumer(queue, messageSelector); + public QueueReceiver createReceiver(final Queue queue, final String messageSelector) throws JMSException { + return (QueueReceiver) createConsumer(queue, messageSelector); } - public QueueReceiver createReceiver(final Queue queue) throws JMSException - { - return (QueueReceiver)createConsumer(queue); + public QueueReceiver createReceiver(final Queue queue) throws JMSException { + return (QueueReceiver) createConsumer(queue); } - public QueueSender createSender(final Queue queue) throws JMSException - { - return (QueueSender)createProducer(queue); + public QueueSender createSender(final Queue queue) throws JMSException { + return (QueueSender) createProducer(queue); } // XAQueueSession implementation - public QueueSession getQueueSession() throws JMSException - { - return (QueueSession)getSession(); + public QueueSession getQueueSession() throws JMSException { + return (QueueSession) getSession(); } // TopicSession implementation - public TopicPublisher createPublisher(final Topic topic) throws JMSException - { - return (TopicPublisher)createProducer(topic); + public TopicPublisher createPublisher(final Topic topic) throws JMSException { + return (TopicPublisher) createProducer(topic); } - public TopicSubscriber createSubscriber(final Topic topic, final String messageSelector, final boolean noLocal) throws JMSException - { - return (TopicSubscriber)createConsumer(topic, messageSelector, noLocal); + public TopicSubscriber createSubscriber(final Topic topic, + final String messageSelector, + final boolean noLocal) throws JMSException { + return (TopicSubscriber) createConsumer(topic, messageSelector, noLocal); } - public TopicSubscriber createSubscriber(final Topic topic) throws JMSException - { - return (TopicSubscriber)createConsumer(topic); + public TopicSubscriber createSubscriber(final Topic topic) throws JMSException { + return (TopicSubscriber) createConsumer(topic); } // XATopicSession implementation - public TopicSession getTopicSession() throws JMSException - { - return (TopicSession)getSession(); + public TopicSession getTopicSession() throws JMSException { + return (TopicSession) getSession(); } // Public -------------------------------------------------------- @Override - public String toString() - { + public String toString() { return "ActiveMQSession->" + session; } - public ClientSession getCoreSession() - { + public ClientSession getCoreSession() { return session; } - public boolean isRecoverCalled() - { + public boolean isRecoverCalled() { return recoverCalled; } - public void setRecoverCalled(final boolean recoverCalled) - { + public void setRecoverCalled(final boolean recoverCalled) { this.recoverCalled = recoverCalled; } - public void deleteTemporaryTopic(final ActiveMQDestination tempTopic) throws JMSException - { - if (!tempTopic.isTemporary()) - { + public void deleteTemporaryTopic(final ActiveMQDestination tempTopic) throws JMSException { + if (!tempTopic.isTemporary()) { throw new InvalidDestinationException("Not a temporary topic " + tempTopic); } - try - { + try { AddressQuery response = session.addressQuery(tempTopic.getSimpleAddress()); - if (!response.isExists()) - { + if (!response.isExists()) { throw new InvalidDestinationException("Cannot delete temporary topic " + tempTopic.getName() + - " does not exist"); + " does not exist"); } - if (response.getQueueNames().size() > 1) - { + if (response.getQueueNames().size() > 1) { throw new IllegalStateException("Cannot delete temporary topic " + tempTopic.getName() + - " since it has subscribers"); + " since it has subscribers"); } SimpleString address = tempTopic.getSimpleAddress(); @@ -1141,32 +960,26 @@ public class ActiveMQSession implements QueueSession, TopicSession connection.removeTemporaryQueue(address); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } - public void deleteTemporaryQueue(final ActiveMQDestination tempQueue) throws JMSException - { - if (!tempQueue.isTemporary()) - { + public void deleteTemporaryQueue(final ActiveMQDestination tempQueue) throws JMSException { + if (!tempQueue.isTemporary()) { throw new InvalidDestinationException("Not a temporary queue " + tempQueue); } - try - { + try { QueueQuery response = session.queueQuery(tempQueue.getSimpleAddress()); - if (!response.isExists()) - { + if (!response.isExists()) { throw new InvalidDestinationException("Cannot delete temporary queue " + tempQueue.getName() + - " does not exist"); + " does not exist"); } - if (response.getConsumerCount() > 0) - { + if (response.getConsumerCount() > 0) { throw new IllegalStateException("Cannot delete temporary queue " + tempQueue.getName() + - " since it has subscribers"); + " since it has subscribers"); } SimpleString address = tempQueue.getSimpleAddress(); @@ -1175,53 +988,41 @@ public class ActiveMQSession implements QueueSession, TopicSession connection.removeTemporaryQueue(address); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } - public void start() throws JMSException - { - try - { + public void start() throws JMSException { + try { session.start(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } - public void stop() throws JMSException - { - try - { + public void stop() throws JMSException { + try { session.stop(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw JMSExceptionHelper.convertFromActiveMQException(e); } } - public void removeConsumer(final ActiveMQMessageConsumer consumer) - { + public void removeConsumer(final ActiveMQMessageConsumer consumer) { consumers.remove(consumer); } // Package protected --------------------------------------------- - void deleteQueue(final SimpleString queueName) throws JMSException - { - if (!session.isClosed()) - { - try - { + void deleteQueue(final SimpleString queueName) throws JMSException { + if (!session.isClosed()) { + try { session.deleteQueue(queueName); } - catch (ActiveMQException ignore) - { + catch (ActiveMQException ignore) { // Exception on deleting queue shouldn't prevent close from completing } } @@ -1231,61 +1032,49 @@ public class ActiveMQSession implements QueueSession, TopicSession // Private ------------------------------------------------------- - private void checkClosed() throws JMSException - { - if (session.isClosed()) - { + private void checkClosed() throws JMSException { + if (session.isClosed()) { throw new IllegalStateException("Session is closed"); } } - private ActiveMQQueue lookupQueue(final String queueName, boolean isTemporary) throws ActiveMQException - { + private ActiveMQQueue lookupQueue(final String queueName, boolean isTemporary) throws ActiveMQException { ActiveMQQueue queue; - if (isTemporary) - { + if (isTemporary) { queue = ActiveMQDestination.createTemporaryQueue(queueName); } - else - { + else { queue = ActiveMQDestination.createQueue(queueName); } QueueQuery response = session.queueQuery(queue.getSimpleAddress()); - if (!response.isExists() && !response.isAutoCreateJmsQueues()) - { + if (!response.isExists() && !response.isAutoCreateJmsQueues()) { return null; } - else - { + else { return queue; } } - private ActiveMQTopic lookupTopic(final String topicName, final boolean isTemporary) throws ActiveMQException - { + private ActiveMQTopic lookupTopic(final String topicName, final boolean isTemporary) throws ActiveMQException { ActiveMQTopic topic; - if (isTemporary) - { + if (isTemporary) { topic = ActiveMQDestination.createTemporaryTopic(topicName); } - else - { + else { topic = ActiveMQDestination.createTopic(topicName); } AddressQuery query = session.addressQuery(topic.getSimpleAddress()); - if (!query.isExists()) - { + if (!query.isExists()) { return null; } - else - { + else { return topic; } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQStreamMessage.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQStreamMessage.java index 32c63da590..4a8d5a8636 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQStreamMessage.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQStreamMessage.java @@ -44,206 +44,162 @@ import static org.apache.activemq.artemis.reader.StreamMessageUtil.streamReadStr /** * ActiveMQ Artemis implementation of a JMS StreamMessage. */ -public final class ActiveMQStreamMessage extends ActiveMQMessage implements StreamMessage -{ +public final class ActiveMQStreamMessage extends ActiveMQMessage implements StreamMessage { + public static final byte TYPE = Message.STREAM_TYPE; - protected ActiveMQStreamMessage(final ClientSession session) - { + protected ActiveMQStreamMessage(final ClientSession session) { super(ActiveMQStreamMessage.TYPE, session); } - protected ActiveMQStreamMessage(final ClientMessage message, final ClientSession session) - { + protected ActiveMQStreamMessage(final ClientMessage message, final ClientSession session) { super(message, session); } - public ActiveMQStreamMessage(final StreamMessage foreign, final ClientSession session) throws JMSException - { + public ActiveMQStreamMessage(final StreamMessage foreign, final ClientSession session) throws JMSException { super(foreign, ActiveMQStreamMessage.TYPE, session); foreign.reset(); - try - { - while (true) - { + try { + while (true) { Object obj = foreign.readObject(); writeObject(obj); } } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { // Ignore } } // For testing only - public ActiveMQStreamMessage() - { - message = new ClientMessageImpl((byte)0, false, 0, 0, (byte)4, 1500); + public ActiveMQStreamMessage() { + message = new ClientMessageImpl((byte) 0, false, 0, 0, (byte) 4, 1500); } // Public -------------------------------------------------------- @Override - public byte getType() - { + public byte getType() { return ActiveMQStreamMessage.TYPE; } // StreamMessage implementation ---------------------------------- - public boolean readBoolean() throws JMSException - { + public boolean readBoolean() throws JMSException { checkRead(); - try - { + try { return streamReadBoolean(message); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { throw new MessageFormatException(e.getMessage()); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public byte readByte() throws JMSException - { + public byte readByte() throws JMSException { checkRead(); - try - { + try { return streamReadByte(message); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { throw new MessageFormatException(e.getMessage()); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public short readShort() throws JMSException - { + public short readShort() throws JMSException { checkRead(); - try - { + try { return streamReadShort(message); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { throw new MessageFormatException(e.getMessage()); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public char readChar() throws JMSException - { + public char readChar() throws JMSException { checkRead(); - try - { + try { return streamReadChar(message); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { throw new MessageFormatException(e.getMessage()); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public int readInt() throws JMSException - { + public int readInt() throws JMSException { checkRead(); - try - { + try { return streamReadInteger(message); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { throw new MessageFormatException(e.getMessage()); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public long readLong() throws JMSException - { + public long readLong() throws JMSException { checkRead(); - try - { + try { return streamReadLong(message); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { throw new MessageFormatException(e.getMessage()); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public float readFloat() throws JMSException - { + public float readFloat() throws JMSException { checkRead(); - try - { + try { return streamReadFloat(message); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { throw new MessageFormatException(e.getMessage()); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public double readDouble() throws JMSException - { + public double readDouble() throws JMSException { checkRead(); - try - { + try { return streamReadDouble(message); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { throw new MessageFormatException(e.getMessage()); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public String readString() throws JMSException - { + public String readString() throws JMSException { checkRead(); - try - { + try { return streamReadString(message); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { throw new MessageFormatException(e.getMessage()); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } @@ -253,178 +209,144 @@ public final class ActiveMQStreamMessage extends ActiveMQMessage implements Stre */ private int len = 0; - public int readBytes(final byte[] value) throws JMSException - { + public int readBytes(final byte[] value) throws JMSException { checkRead(); - try - { + try { Pair pairRead = streamReadBytes(message, len, value); len = pairRead.getA(); return pairRead.getB(); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { throw new MessageFormatException(e.getMessage()); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public Object readObject() throws JMSException - { + public Object readObject() throws JMSException { checkRead(); - try - { + try { return streamReadObject(message); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { throw new MessageFormatException(e.getMessage()); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public void writeBoolean(final boolean value) throws JMSException - { + public void writeBoolean(final boolean value) throws JMSException { checkWrite(); getBuffer().writeByte(DataConstants.BOOLEAN); getBuffer().writeBoolean(value); } - public void writeByte(final byte value) throws JMSException - { + public void writeByte(final byte value) throws JMSException { checkWrite(); getBuffer().writeByte(DataConstants.BYTE); getBuffer().writeByte(value); } - public void writeShort(final short value) throws JMSException - { + public void writeShort(final short value) throws JMSException { checkWrite(); getBuffer().writeByte(DataConstants.SHORT); getBuffer().writeShort(value); } - public void writeChar(final char value) throws JMSException - { + public void writeChar(final char value) throws JMSException { checkWrite(); getBuffer().writeByte(DataConstants.CHAR); - getBuffer().writeShort((short)value); + getBuffer().writeShort((short) value); } - public void writeInt(final int value) throws JMSException - { + public void writeInt(final int value) throws JMSException { checkWrite(); getBuffer().writeByte(DataConstants.INT); getBuffer().writeInt(value); } - public void writeLong(final long value) throws JMSException - { + public void writeLong(final long value) throws JMSException { checkWrite(); getBuffer().writeByte(DataConstants.LONG); getBuffer().writeLong(value); } - public void writeFloat(final float value) throws JMSException - { + public void writeFloat(final float value) throws JMSException { checkWrite(); getBuffer().writeByte(DataConstants.FLOAT); getBuffer().writeInt(Float.floatToIntBits(value)); } - public void writeDouble(final double value) throws JMSException - { + public void writeDouble(final double value) throws JMSException { checkWrite(); getBuffer().writeByte(DataConstants.DOUBLE); getBuffer().writeLong(Double.doubleToLongBits(value)); } - public void writeString(final String value) throws JMSException - { + public void writeString(final String value) throws JMSException { checkWrite(); getBuffer().writeByte(DataConstants.STRING); getBuffer().writeNullableString(value); } - public void writeBytes(final byte[] value) throws JMSException - { + public void writeBytes(final byte[] value) throws JMSException { checkWrite(); getBuffer().writeByte(DataConstants.BYTES); getBuffer().writeInt(value.length); getBuffer().writeBytes(value); } - public void writeBytes(final byte[] value, final int offset, final int length) throws JMSException - { + public void writeBytes(final byte[] value, final int offset, final int length) throws JMSException { checkWrite(); getBuffer().writeByte(DataConstants.BYTES); getBuffer().writeInt(length); getBuffer().writeBytes(value, offset, length); } - public void writeObject(final Object value) throws JMSException - { - if (value instanceof String) - { - writeString((String)value); + public void writeObject(final Object value) throws JMSException { + if (value instanceof String) { + writeString((String) value); } - else if (value instanceof Boolean) - { - writeBoolean((Boolean)value); + else if (value instanceof Boolean) { + writeBoolean((Boolean) value); } - else if (value instanceof Byte) - { - writeByte((Byte)value); + else if (value instanceof Byte) { + writeByte((Byte) value); } - else if (value instanceof Short) - { - writeShort((Short)value); + else if (value instanceof Short) { + writeShort((Short) value); } - else if (value instanceof Integer) - { - writeInt((Integer)value); + else if (value instanceof Integer) { + writeInt((Integer) value); } - else if (value instanceof Long) - { - writeLong((Long)value); + else if (value instanceof Long) { + writeLong((Long) value); } - else if (value instanceof Float) - { - writeFloat((Float)value); + else if (value instanceof Float) { + writeFloat((Float) value); } - else if (value instanceof Double) - { - writeDouble((Double)value); + else if (value instanceof Double) { + writeDouble((Double) value); } - else if (value instanceof byte[]) - { - writeBytes((byte[])value); + else if (value instanceof byte[]) { + writeBytes((byte[]) value); } - else if (value instanceof Character) - { - writeChar((Character)value); + else if (value instanceof Character) { + writeChar((Character) value); } - else if (value == null) - { + else if (value == null) { writeString(null); } - else - { + else { throw new MessageFormatException("Invalid object type: " + value.getClass()); } } - public void reset() throws JMSException - { - if (!readOnly) - { + public void reset() throws JMSException { + if (!readOnly) { readOnly = true; } getBuffer().resetReaderIndex(); @@ -433,28 +355,24 @@ public final class ActiveMQStreamMessage extends ActiveMQMessage implements Stre // ActiveMQRAMessage overrides ---------------------------------------- @Override - public void clearBody() throws JMSException - { + public void clearBody() throws JMSException { super.clearBody(); getBuffer().clear(); } @Override - public void doBeforeSend() throws Exception - { + public void doBeforeSend() throws Exception { reset(); } - private ActiveMQBuffer getBuffer() - { + private ActiveMQBuffer getBuffer() { return message.getBodyBuffer(); } @SuppressWarnings("rawtypes") @Override - public boolean isBodyAssignableTo(Class c) - { + public boolean isBodyAssignableTo(Class c) { return false; } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQTemporaryQueue.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQTemporaryQueue.java index b61d835db4..fa01409ed6 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQTemporaryQueue.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQTemporaryQueue.java @@ -18,14 +18,12 @@ package org.apache.activemq.artemis.jms.client; import javax.jms.TemporaryQueue; - /** * ActiveMQ Artemis implementation of a JMS TemporaryQueue. *
    * This class can be instantiated directly. */ -public class ActiveMQTemporaryQueue extends ActiveMQQueue implements TemporaryQueue -{ +public class ActiveMQTemporaryQueue extends ActiveMQQueue implements TemporaryQueue { // Constants ----------------------------------------------------- private static final long serialVersionUID = -4624930377557954624L; @@ -36,7 +34,6 @@ public class ActiveMQTemporaryQueue extends ActiveMQQueue implements TemporaryQu // Constructors -------------------------------------------------- - // TemporaryQueue implementation ------------------------------------------ // Public -------------------------------------------------------- @@ -46,14 +43,12 @@ public class ActiveMQTemporaryQueue extends ActiveMQQueue implements TemporaryQu * @param name * @param session */ - public ActiveMQTemporaryQueue(String address, String name, ActiveMQSession session) - { + public ActiveMQTemporaryQueue(String address, String name, ActiveMQSession session) { super(address, name, true, session); } @Override - public String toString() - { + public String toString() { return "ActiveMQTemporaryQueue[" + name + "]"; } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQTemporaryTopic.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQTemporaryTopic.java index 609eaea017..07c3ec9dcb 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQTemporaryTopic.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQTemporaryTopic.java @@ -18,8 +18,7 @@ package org.apache.activemq.artemis.jms.client; import javax.jms.TemporaryTopic; -public class ActiveMQTemporaryTopic extends ActiveMQTopic implements TemporaryTopic -{ +public class ActiveMQTemporaryTopic extends ActiveMQTopic implements TemporaryTopic { // Constants ----------------------------------------------------- @@ -31,9 +30,7 @@ public class ActiveMQTemporaryTopic extends ActiveMQTopic implements TemporaryTo // Constructors -------------------------------------------------- - protected ActiveMQTemporaryTopic(final String address, final String name, - final ActiveMQSession session) - { + protected ActiveMQTemporaryTopic(final String address, final String name, final ActiveMQSession session) { super(address, name, true, session); } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQTextMessage.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQTextMessage.java index 2f95d853ea..b9fba2d6b1 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQTextMessage.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQTextMessage.java @@ -28,14 +28,12 @@ import org.apache.activemq.artemis.api.core.client.ClientSession; import static org.apache.activemq.artemis.reader.TextMessageUtil.readBodyText; import static org.apache.activemq.artemis.reader.TextMessageUtil.writeBodyText; - /** * ActiveMQ Artemis implementation of a JMS TextMessage. *
    * This class was ported from SpyTextMessage in JBossMQ. */ -public class ActiveMQTextMessage extends ActiveMQMessage implements TextMessage -{ +public class ActiveMQTextMessage extends ActiveMQMessage implements TextMessage { // Constants ----------------------------------------------------- public static final byte TYPE = Message.TEXT_TYPE; @@ -50,21 +48,18 @@ public class ActiveMQTextMessage extends ActiveMQMessage implements TextMessage // Constructors -------------------------------------------------- - public ActiveMQTextMessage(final ClientSession session) - { + public ActiveMQTextMessage(final ClientSession session) { super(ActiveMQTextMessage.TYPE, session); } - public ActiveMQTextMessage(final ClientMessage message, final ClientSession session) - { + public ActiveMQTextMessage(final ClientMessage message, final ClientSession session) { super(message, session); } /** * A copy constructor for non-ActiveMQ Artemis JMS TextMessages. */ - public ActiveMQTextMessage(final TextMessage foreign, final ClientSession session) throws JMSException - { + public ActiveMQTextMessage(final TextMessage foreign, final ClientSession session) throws JMSException { super(foreign, ActiveMQTextMessage.TYPE, session); setText(foreign.getText()); @@ -73,44 +68,36 @@ public class ActiveMQTextMessage extends ActiveMQMessage implements TextMessage // Public -------------------------------------------------------- @Override - public byte getType() - { + public byte getType() { return ActiveMQTextMessage.TYPE; } // TextMessage implementation ------------------------------------ - public void setText(final String text) throws JMSException - { + public void setText(final String text) throws JMSException { checkWrite(); - if (text != null) - { + if (text != null) { this.text = new SimpleString(text); } - else - { + else { this.text = null; } writeBodyText(message, this.text); } - public String getText() - { - if (text != null) - { + public String getText() { + if (text != null) { return text.toString(); } - else - { + else { return null; } } @Override - public void clearBody() throws JMSException - { + public void clearBody() throws JMSException { super.clearBody(); text = null; @@ -119,22 +106,19 @@ public class ActiveMQTextMessage extends ActiveMQMessage implements TextMessage // ActiveMQRAMessage override ----------------------------------------- @Override - public void doBeforeReceive() throws ActiveMQException - { + public void doBeforeReceive() throws ActiveMQException { super.doBeforeReceive(); text = readBodyText(message); } @Override - protected T getBodyInternal(Class c) - { + protected T getBodyInternal(Class c) { return (T) getText(); } @Override - public boolean isBodyAssignableTo(@SuppressWarnings("rawtypes") Class c) - { + public boolean isBodyAssignableTo(@SuppressWarnings("rawtypes") Class c) { if (text == null) return true; return c.isAssignableFrom(java.lang.String.class); diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQTopic.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQTopic.java index d7a6f38529..d959d2655e 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQTopic.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQTopic.java @@ -25,15 +25,13 @@ import org.apache.activemq.artemis.api.core.SimpleString; *
    * This class can be instantiated directly. */ -public class ActiveMQTopic extends ActiveMQDestination implements Topic -{ +public class ActiveMQTopic extends ActiveMQDestination implements Topic { // Constants ----------------------------------------------------- private static final long serialVersionUID = 7873614001276404156L; // Static -------------------------------------------------------- - public static SimpleString createAddressFromName(final String name) - { + public static SimpleString createAddressFromName(final String name) { return new SimpleString(JMS_TOPIC_ADDRESS_PREFIX + name); } @@ -41,41 +39,34 @@ public class ActiveMQTopic extends ActiveMQDestination implements Topic // Constructors -------------------------------------------------- - public ActiveMQTopic(final String name) - { + public ActiveMQTopic(final String name) { this(name, false); } - public ActiveMQTopic(final String name, boolean temporary) - { + public ActiveMQTopic(final String name, boolean temporary) { super(JMS_TOPIC_ADDRESS_PREFIX + name, name, temporary, false, null); } - /** * @param address * @param name * @param temporary * @param session */ - protected ActiveMQTopic(String address, String name, boolean temporary, ActiveMQSession session) - { + protected ActiveMQTopic(String address, String name, boolean temporary, ActiveMQSession session) { super(address, name, temporary, false, session); } - // Topic implementation ------------------------------------------ - public String getTopicName() - { + public String getTopicName() { return name; } // Public -------------------------------------------------------- @Override - public String toString() - { + public String toString() { return "ActiveMQTopic[" + name + "]"; } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQTopicConnectionFactory.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQTopicConnectionFactory.java index ab882380ad..bc588d3ecf 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQTopicConnectionFactory.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQTopicConnectionFactory.java @@ -26,42 +26,35 @@ import org.apache.activemq.artemis.api.jms.JMSFactoryType; /** * {@inheritDoc} */ -public class ActiveMQTopicConnectionFactory extends ActiveMQConnectionFactory implements TopicConnectionFactory -{ +public class ActiveMQTopicConnectionFactory extends ActiveMQConnectionFactory implements TopicConnectionFactory { + private static final long serialVersionUID = 7317051989866548455L; - public ActiveMQTopicConnectionFactory() - { + public ActiveMQTopicConnectionFactory() { super(); } - public ActiveMQTopicConnectionFactory(String url) - { + public ActiveMQTopicConnectionFactory(String url) { super(url); } - public ActiveMQTopicConnectionFactory(String url, String user, String password) - { + public ActiveMQTopicConnectionFactory(String url, String user, String password) { super(url, user, password); } - public ActiveMQTopicConnectionFactory(ServerLocator serverLocator) - { + public ActiveMQTopicConnectionFactory(ServerLocator serverLocator) { super(serverLocator); } - public ActiveMQTopicConnectionFactory(final boolean ha, final DiscoveryGroupConfiguration groupConfiguration) - { + public ActiveMQTopicConnectionFactory(final boolean ha, final DiscoveryGroupConfiguration groupConfiguration) { super(ha, groupConfiguration); } - public ActiveMQTopicConnectionFactory(final boolean ha, final TransportConfiguration... initialConnectors) - { + public ActiveMQTopicConnectionFactory(final boolean ha, final TransportConfiguration... initialConnectors) { super(ha, initialConnectors); } - public int getFactoryType() - { + public int getFactoryType() { return JMSFactoryType.TOPIC_CF.intValue(); } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQXAConnection.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQXAConnection.java index 772d75e01a..bae4e89f1a 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQXAConnection.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQXAConnection.java @@ -32,41 +32,39 @@ import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; * The flat implementation of {@link XATopicConnection} and {@link XAQueueConnection} is per design, * following common practices of JMS 1.1. */ -public final class ActiveMQXAConnection extends ActiveMQConnection implements XATopicConnection, XAQueueConnection -{ +public final class ActiveMQXAConnection extends ActiveMQConnection implements XATopicConnection, XAQueueConnection { - public ActiveMQXAConnection(final String username, final String password, final int connectionType, - final String clientID, final int dupsOKBatchSize, final int transactionBatchSize, - final ClientSessionFactory sessionFactory) - { + public ActiveMQXAConnection(final String username, + final String password, + final int connectionType, + final String clientID, + final int dupsOKBatchSize, + final int transactionBatchSize, + final ClientSessionFactory sessionFactory) { super(username, password, connectionType, clientID, dupsOKBatchSize, transactionBatchSize, sessionFactory); } @Override - public XASession createXASession() throws JMSException - { + public XASession createXASession() throws JMSException { checkClosed(); - return (XASession)createSessionInternal(isXA(), true, Session.SESSION_TRANSACTED, ActiveMQSession.TYPE_GENERIC_SESSION); + return (XASession) createSessionInternal(isXA(), true, Session.SESSION_TRANSACTED, ActiveMQSession.TYPE_GENERIC_SESSION); } @Override - public XAQueueSession createXAQueueSession() throws JMSException - { + public XAQueueSession createXAQueueSession() throws JMSException { checkClosed(); - return (XAQueueSession)createSessionInternal(isXA(), true, Session.SESSION_TRANSACTED, ActiveMQSession.TYPE_QUEUE_SESSION); + return (XAQueueSession) createSessionInternal(isXA(), true, Session.SESSION_TRANSACTED, ActiveMQSession.TYPE_QUEUE_SESSION); } @Override - public XATopicSession createXATopicSession() throws JMSException - { + public XATopicSession createXATopicSession() throws JMSException { checkClosed(); - return (XATopicSession)createSessionInternal(isXA(), true, Session.SESSION_TRANSACTED, ActiveMQSession.TYPE_TOPIC_SESSION); + return (XATopicSession) createSessionInternal(isXA(), true, Session.SESSION_TRANSACTED, ActiveMQSession.TYPE_TOPIC_SESSION); } @Override - protected boolean isXA() - { + protected boolean isXA() { return true; } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQXAConnectionFactory.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQXAConnectionFactory.java index d520fc08c2..ec2ddb22c4 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQXAConnectionFactory.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQXAConnectionFactory.java @@ -29,46 +29,37 @@ import org.apache.activemq.artemis.api.jms.JMSFactoryType; *

    * We consider the XAConnectionFactory to be the most complete possible option. It can be casted to any other connection factory since it is fully functional */ -public class ActiveMQXAConnectionFactory extends ActiveMQConnectionFactory implements XATopicConnectionFactory, - XAQueueConnectionFactory -{ +public class ActiveMQXAConnectionFactory extends ActiveMQConnectionFactory implements XATopicConnectionFactory, XAQueueConnectionFactory { + private static final long serialVersionUID = 743611571839154115L; - public ActiveMQXAConnectionFactory() - { + public ActiveMQXAConnectionFactory() { super(); } - public ActiveMQXAConnectionFactory(String uri) - { + public ActiveMQXAConnectionFactory(String uri) { super(uri); } - public ActiveMQXAConnectionFactory(String url, String user, String password) - { + public ActiveMQXAConnectionFactory(String url, String user, String password) { super(url, user, password); } - public ActiveMQXAConnectionFactory(ServerLocator serverLocator) - { + public ActiveMQXAConnectionFactory(ServerLocator serverLocator) { super(serverLocator); } - public ActiveMQXAConnectionFactory(final boolean ha, final DiscoveryGroupConfiguration groupConfiguration) - { + public ActiveMQXAConnectionFactory(final boolean ha, final DiscoveryGroupConfiguration groupConfiguration) { super(ha, groupConfiguration); } - public ActiveMQXAConnectionFactory(final boolean ha, final TransportConfiguration... initialConnectors) - { + public ActiveMQXAConnectionFactory(final boolean ha, final TransportConfiguration... initialConnectors) { super(ha, initialConnectors); } @Override - public int getFactoryType() - { + public int getFactoryType() { return JMSFactoryType.XA_CF.intValue(); } - } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQXAJMSContext.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQXAJMSContext.java index 2449d265c1..ac330b0dff 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQXAJMSContext.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQXAJMSContext.java @@ -18,10 +18,9 @@ package org.apache.activemq.artemis.jms.client; import javax.jms.XAJMSContext; -public class ActiveMQXAJMSContext extends ActiveMQJMSContext implements XAJMSContext -{ - public ActiveMQXAJMSContext(ActiveMQConnectionForContext connection, ThreadAwareContext threadAwareContext) - { +public class ActiveMQXAJMSContext extends ActiveMQJMSContext implements XAJMSContext { + + public ActiveMQXAJMSContext(ActiveMQConnectionForContext connection, ThreadAwareContext threadAwareContext) { super(connection, threadAwareContext); } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQXAQueueConnectionFactory.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQXAQueueConnectionFactory.java index 445b069d73..fca68567d6 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQXAQueueConnectionFactory.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQXAQueueConnectionFactory.java @@ -26,42 +26,35 @@ import org.apache.activemq.artemis.api.jms.JMSFactoryType; /** * {@inheritDoc} */ -public class ActiveMQXAQueueConnectionFactory extends ActiveMQConnectionFactory implements XAQueueConnectionFactory -{ +public class ActiveMQXAQueueConnectionFactory extends ActiveMQConnectionFactory implements XAQueueConnectionFactory { + private static final long serialVersionUID = 8612457847251087454L; - public ActiveMQXAQueueConnectionFactory() - { + public ActiveMQXAQueueConnectionFactory() { super(); } - public ActiveMQXAQueueConnectionFactory(String uri) - { + public ActiveMQXAQueueConnectionFactory(String uri) { super(uri); } - public ActiveMQXAQueueConnectionFactory(String url, String user, String password) - { + public ActiveMQXAQueueConnectionFactory(String url, String user, String password) { super(url, user, password); } - public ActiveMQXAQueueConnectionFactory(ServerLocator serverLocator) - { + public ActiveMQXAQueueConnectionFactory(ServerLocator serverLocator) { super(serverLocator); } - public ActiveMQXAQueueConnectionFactory(final boolean ha, final DiscoveryGroupConfiguration groupConfiguration) - { + public ActiveMQXAQueueConnectionFactory(final boolean ha, final DiscoveryGroupConfiguration groupConfiguration) { super(ha, groupConfiguration); } - public ActiveMQXAQueueConnectionFactory(final boolean ha, final TransportConfiguration... initialConnectors) - { + public ActiveMQXAQueueConnectionFactory(final boolean ha, final TransportConfiguration... initialConnectors) { super(ha, initialConnectors); } - public int getFactoryType() - { + public int getFactoryType() { return JMSFactoryType.QUEUE_XA_CF.intValue(); } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQXASession.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQXASession.java index b4b9df3795..815b488d98 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQXASession.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQXASession.java @@ -21,8 +21,7 @@ import javax.jms.XATopicSession; import org.apache.activemq.artemis.api.core.client.ClientSession; -public class ActiveMQXASession extends ActiveMQSession implements XAQueueSession, XATopicSession -{ +public class ActiveMQXASession extends ActiveMQSession implements XAQueueSession, XATopicSession { /** * @param connection @@ -37,8 +36,7 @@ public class ActiveMQXASession extends ActiveMQSession implements XAQueueSession boolean xa, int ackMode, ClientSession session, - int sessionType) - { + int sessionType) { super(connection, transacted, xa, ackMode, session, sessionType); } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQXATopicConnectionFactory.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQXATopicConnectionFactory.java index 6e52d1995d..de20159f7f 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQXATopicConnectionFactory.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQXATopicConnectionFactory.java @@ -26,42 +26,35 @@ import org.apache.activemq.artemis.api.jms.JMSFactoryType; /** * {@inheritDoc} */ -public class ActiveMQXATopicConnectionFactory extends ActiveMQConnectionFactory implements XATopicConnectionFactory -{ +public class ActiveMQXATopicConnectionFactory extends ActiveMQConnectionFactory implements XATopicConnectionFactory { + private static final long serialVersionUID = -7018290426884419693L; - public ActiveMQXATopicConnectionFactory() - { + public ActiveMQXATopicConnectionFactory() { super(); } - public ActiveMQXATopicConnectionFactory(String uri) - { + public ActiveMQXATopicConnectionFactory(String uri) { super(uri); } - public ActiveMQXATopicConnectionFactory(String url, String user, String password) - { + public ActiveMQXATopicConnectionFactory(String url, String user, String password) { super(url, user, password); } - public ActiveMQXATopicConnectionFactory(final ServerLocator serverLocator) - { + public ActiveMQXATopicConnectionFactory(final ServerLocator serverLocator) { super(serverLocator); } - public ActiveMQXATopicConnectionFactory(final boolean ha, final DiscoveryGroupConfiguration groupConfiguration) - { + public ActiveMQXATopicConnectionFactory(final boolean ha, final DiscoveryGroupConfiguration groupConfiguration) { super(ha, groupConfiguration); } - public ActiveMQXATopicConnectionFactory(final boolean ha, final TransportConfiguration... initialConnectors) - { + public ActiveMQXATopicConnectionFactory(final boolean ha, final TransportConfiguration... initialConnectors) { super(ha, initialConnectors); } - public int getFactoryType() - { + public int getFactoryType() { return JMSFactoryType.TOPIC_XA_CF.intValue(); } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/DefaultConnectionProperties.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/DefaultConnectionProperties.java index fbe50dc637..328ab7196e 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/DefaultConnectionProperties.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/DefaultConnectionProperties.java @@ -32,8 +32,8 @@ import java.security.PrivilegedAction; * AMQ_PASSWORD or org.apache.activemq.AMQ_PASSWORD null * */ -public class DefaultConnectionProperties -{ +public class DefaultConnectionProperties { + public static final String DEFAULT_BROKER_HOST; public static final int DEFAULT_BROKER_PORT; public static final String DEFAULT_BROKER_BIND_URL; @@ -41,18 +41,13 @@ public class DefaultConnectionProperties public static final String DEFAULT_USER; public static final String DEFAULT_PASSWORD; - static String getProperty(final String defaultValue, final String... propertyNames) - { - return AccessController.doPrivileged(new PrivilegedAction() - { + static String getProperty(final String defaultValue, final String... propertyNames) { + return AccessController.doPrivileged(new PrivilegedAction() { @Override - public String run() - { - for (String name : propertyNames) - { + public String run() { + for (String name : propertyNames) { String property = System.getProperty(name); - if (property != null && !property.isEmpty()) - { + if (property != null && !property.isEmpty()) { return property; } } @@ -61,8 +56,7 @@ public class DefaultConnectionProperties }); } - static - { + static { String host = getProperty("localhost", "AMQ_HOST", "org.apache.activemq.AMQ_HOST"); String port = getProperty("61616", "AMQ_PORT", "org.apache.activemq.AMQ_PORT"); DEFAULT_BROKER_HOST = host; @@ -71,8 +65,7 @@ public class DefaultConnectionProperties DEFAULT_USER = getProperty(null, "AMQ_USER", "org.apache.activemq.AMQ_USER"); DEFAULT_PASSWORD = getProperty(null, "AMQ_PASSWORD", "org.apache.activemq.AMQ_PASSWORD"); - if (DEFAULT_USER != null && DEFAULT_PASSWORD != null) - { + if (DEFAULT_USER != null && DEFAULT_PASSWORD != null) { url += "?user=" + DEFAULT_USER + "&password=" + DEFAULT_PASSWORD; } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/JMSExceptionHelper.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/JMSExceptionHelper.java index ae85f56d83..666fa9dc4e 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/JMSExceptionHelper.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/JMSExceptionHelper.java @@ -23,14 +23,11 @@ import javax.jms.JMSSecurityException; import org.apache.activemq.artemis.api.core.ActiveMQException; -public final class JMSExceptionHelper -{ +public final class JMSExceptionHelper { - public static JMSException convertFromActiveMQException(final ActiveMQException me) - { + public static JMSException convertFromActiveMQException(final ActiveMQException me) { JMSException je; - switch (me.getType()) - { + switch (me.getType()) { case CONNECTION_TIMEDOUT: je = new JMSException(me.getMessage()); break; diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/JMSMessageListenerWrapper.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/JMSMessageListenerWrapper.java index a5a7d2dec9..1a6c95a016 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/JMSMessageListenerWrapper.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/JMSMessageListenerWrapper.java @@ -25,8 +25,8 @@ import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.apache.activemq.artemis.api.core.client.MessageHandler; import org.apache.activemq.artemis.api.jms.ActiveMQJMSConstants; -public class JMSMessageListenerWrapper implements MessageHandler -{ +public class JMSMessageListenerWrapper implements MessageHandler { + private final ActiveMQConnection connection; private final ActiveMQSession session; @@ -43,8 +43,7 @@ public class JMSMessageListenerWrapper implements MessageHandler final ActiveMQSession session, final ClientConsumer consumer, final MessageListener listener, - final int ackMode) - { + final int ackMode) { this.connection = connection; this.session = session; @@ -62,55 +61,43 @@ public class JMSMessageListenerWrapper implements MessageHandler * In this method we apply the JMS acknowledgement and redelivery semantics * as per JMS spec */ - public void onMessage(final ClientMessage message) - { + public void onMessage(final ClientMessage message) { ActiveMQMessage msg = ActiveMQMessage.createMessage(message, session.getCoreSession()); - if (individualACK) - { + if (individualACK) { msg.setIndividualAcknowledge(); } - try - { + try { msg.doBeforeReceive(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQJMSClientLogger.LOGGER.errorPreparingMessageForReceipt(e); return; } - if (transactedOrClientAck) - { - try - { + if (transactedOrClientAck) { + try { message.acknowledge(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { ActiveMQJMSClientLogger.LOGGER.errorProcessingMessage(e); } } - try - { + try { connection.getThreadAwareContext().setCurrentThread(false); listener.onMessage(msg); } - catch (RuntimeException e) - { + catch (RuntimeException e) { // See JMS 1.1 spec, section 4.5.2 ActiveMQJMSClientLogger.LOGGER.onMessageError(e); - if (!transactedOrClientAck) - { - try - { - if (individualACK) - { + if (!transactedOrClientAck) { + try { + if (individualACK) { message.individualAcknowledge(); } @@ -118,28 +105,22 @@ public class JMSMessageListenerWrapper implements MessageHandler session.setRecoverCalled(true); } - catch (Exception e2) - { + catch (Exception e2) { ActiveMQJMSClientLogger.LOGGER.errorRecoveringSession(e2); } } } - finally - { + finally { connection.getThreadAwareContext().clearCurrentThread(false); } - if (!session.isRecoverCalled() && !individualACK) - { - try - { + if (!session.isRecoverCalled() && !individualACK) { + try { // We don't want to call this if the consumer was closed from inside onMessage - if (!consumer.isClosed() && !transactedOrClientAck) - { + if (!consumer.isClosed() && !transactedOrClientAck) { message.acknowledge(); } } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { ActiveMQJMSClientLogger.LOGGER.errorProcessingMessage(e); } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/JmsExceptionUtils.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/JmsExceptionUtils.java index a69cd6ab4f..aea050fd5b 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/JmsExceptionUtils.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/JmsExceptionUtils.java @@ -41,59 +41,48 @@ import javax.jms.TransactionRolledBackRuntimeException; /** * */ -public final class JmsExceptionUtils -{ - private JmsExceptionUtils() - { +public final class JmsExceptionUtils { + + private JmsExceptionUtils() { // utility class } /** * Converts instances of sub-classes of {@link JMSException} into the corresponding sub-class of * {@link JMSRuntimeException}. + * * @param e * @return */ - public static JMSRuntimeException convertToRuntimeException(JMSException e) - { - if (e instanceof javax.jms.IllegalStateException) - { + public static JMSRuntimeException convertToRuntimeException(JMSException e) { + if (e instanceof javax.jms.IllegalStateException) { return new IllegalStateRuntimeException(e.getMessage(), e.getErrorCode(), e); } - if (e instanceof InvalidClientIDException) - { + if (e instanceof InvalidClientIDException) { return new InvalidClientIDRuntimeException(e.getMessage(), e.getErrorCode(), e); } - if (e instanceof InvalidDestinationException) - { + if (e instanceof InvalidDestinationException) { return new InvalidDestinationRuntimeException(e.getMessage(), e.getErrorCode(), e); } - if (e instanceof InvalidSelectorException) - { + if (e instanceof InvalidSelectorException) { return new InvalidSelectorRuntimeException(e.getMessage(), e.getErrorCode(), e); } - if (e instanceof JMSSecurityException) - { + if (e instanceof JMSSecurityException) { return new JMSSecurityRuntimeException(e.getMessage(), e.getErrorCode(), e); } - if (e instanceof MessageFormatException) - { + if (e instanceof MessageFormatException) { return new MessageFormatRuntimeException(e.getMessage(), e.getErrorCode(), e); } - if (e instanceof MessageNotWriteableException) - { + if (e instanceof MessageNotWriteableException) { return new MessageNotWriteableRuntimeException(e.getMessage(), e.getErrorCode(), e); } - if (e instanceof ResourceAllocationException) - { + if (e instanceof ResourceAllocationException) { return new ResourceAllocationRuntimeException(e.getMessage(), e.getErrorCode(), e); } - if (e instanceof TransactionInProgressException) - { + if (e instanceof TransactionInProgressException) { return new TransactionInProgressRuntimeException(e.getMessage(), e.getErrorCode(), e); } - if (e instanceof TransactionRolledBackException) - { + if (e instanceof TransactionRolledBackException) { return new TransactionRolledBackRuntimeException(e.getMessage(), e.getErrorCode(), e); } return new JMSRuntimeException(e.getMessage(), e.getErrorCode(), e); diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/SelectorTranslator.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/SelectorTranslator.java index 15509f9695..d227f89a5d 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/SelectorTranslator.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/SelectorTranslator.java @@ -20,7 +20,6 @@ import java.util.ArrayList; import java.util.List; /** - * * This class converts a JMS selector expression into an ActiveMQ Artemis core filter expression. * * JMS selector and ActiveMQ Artemis filters use the same syntax but have different identifiers. @@ -33,12 +32,10 @@ import java.util.List; * * This makes it less trivial than a simple search and replace. */ -public class SelectorTranslator -{ - public static String convertToActiveMQFilterString(final String selectorString) - { - if (selectorString == null) - { +public class SelectorTranslator { + + public static String convertToActiveMQFilterString(final String selectorString) { + if (selectorString == null) { return null; } @@ -56,8 +53,7 @@ public class SelectorTranslator } - private static String parse(final String input, final String match, final String replace) - { + private static String parse(final String input, final String match, final String replace) { final char quote = '\''; boolean inQuote = false; @@ -68,42 +64,35 @@ public class SelectorTranslator boolean replaceInQuotes = match.charAt(0) == quote; - for (int i = 0; i < input.length(); i++) - { + for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); - if (c == quote) - { + if (c == quote) { inQuote = !inQuote; } - if ((!inQuote || replaceInQuotes) && c == match.charAt(matchPos)) - { + if ((!inQuote || replaceInQuotes) && c == match.charAt(matchPos)) { matchPos++; - if (matchPos == match.length()) - { + if (matchPos == match.length()) { boolean matched = true; // Check that name is not part of another identifier name // Check character after match - if (i < input.length() - 1 && Character.isJavaIdentifierPart(input.charAt(i + 1))) - { + if (i < input.length() - 1 && Character.isJavaIdentifierPart(input.charAt(i + 1))) { matched = false; } // Check character before match int posBeforeStart = i - match.length(); - if (posBeforeStart >= 0 && Character.isJavaIdentifierPart(input.charAt(posBeforeStart))) - { + if (posBeforeStart >= 0 && Character.isJavaIdentifierPart(input.charAt(posBeforeStart))) { matched = false; } - if (matched) - { + if (matched) { positions.add(i - match.length() + 1); } @@ -112,20 +101,17 @@ public class SelectorTranslator matchPos = 0; } } - else - { + else { matchPos = 0; } } - if (!positions.isEmpty()) - { + if (!positions.isEmpty()) { StringBuffer buff = new StringBuffer(); int startPos = 0; - for (int pos : positions) - { + for (int pos : positions) { String substr = input.substring(startPos, pos); buff.append(substr); @@ -135,15 +121,13 @@ public class SelectorTranslator startPos = pos + match.length(); } - if (startPos < input.length()) - { + if (startPos < input.length()) { buff.append(input.substring(startPos, input.length())); } return buff.toString(); } - else - { + else { return input; } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ThreadAwareContext.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ThreadAwareContext.java index 4828b3417f..10624ceb94 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ThreadAwareContext.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ThreadAwareContext.java @@ -24,12 +24,13 @@ import java.util.Set; /** * Restricts what can be called on context passed in wrapped CompletionListener. */ -public class ThreadAwareContext -{ +public class ThreadAwareContext { + /** * Necessary in order to assert some methods ({@link javax.jms.JMSContext#stop()} * {@link javax.jms.JMSContext#close()} etc) are not getting called from within a * {@link javax.jms.CompletionListener}. + * * @see ThreadAwareContext#assertNotMessageListenerThread() */ private Thread completionListenerThread; @@ -45,36 +46,30 @@ public class ThreadAwareContext *

    * Meant to inform an JMSContext which is the thread that CANNOT call some of its methods. *

    + * * @param isCompletionListener : indicating whether current thread is from CompletionListener - * or from MessageListener. + * or from MessageListener. */ - public void setCurrentThread(boolean isCompletionListener) - { - if (isCompletionListener) - { + public void setCurrentThread(boolean isCompletionListener) { + if (isCompletionListener) { completionListenerThread = Thread.currentThread(); } - else - { + else { messageListenerThreads.add(Thread.currentThread().getId()); } } - /** * Clear current thread from the context * * @param isCompletionListener : indicating whether current thread is from CompletionListener - * or from MessageListener. + * or from MessageListener. */ - public void clearCurrentThread(boolean isCompletionListener) - { - if (isCompletionListener) - { + public void clearCurrentThread(boolean isCompletionListener) { + if (isCompletionListener) { completionListenerThread = null; } - else - { + else { messageListenerThreads.remove(Thread.currentThread().getId()); } } @@ -85,15 +80,14 @@ public class ThreadAwareContext * Note that the code must work without any need for further synchronization, as there is the * requirement that only one CompletionListener be called at a time. In other words, * CompletionListener calling is single-threaded. + * * @see javax.jms.JMSContext#close() * @see javax.jms.JMSContext#stop() * @see javax.jms.JMSContext#commit() * @see javax.jms.JMSContext#rollback() */ - public void assertNotCompletionListenerThreadRuntime() - { - if (completionListenerThread == Thread.currentThread()) - { + public void assertNotCompletionListenerThreadRuntime() { + if (completionListenerThread == Thread.currentThread()) { throw ActiveMQJMSClientBundle.BUNDLE.callingMethodFromCompletionListenerRuntime(); } } @@ -109,10 +103,8 @@ public class ThreadAwareContext * @see javax.jms.Connection#close() * @see javax.jms.MessageProducer#close() */ - public void assertNotCompletionListenerThread() throws javax.jms.IllegalStateException - { - if (completionListenerThread == Thread.currentThread()) - { + public void assertNotCompletionListenerThread() throws javax.jms.IllegalStateException { + if (completionListenerThread == Thread.currentThread()) { throw ActiveMQJMSClientBundle.BUNDLE.callingMethodFromCompletionListener(); } } @@ -123,20 +115,19 @@ public class ThreadAwareContext * Note that the code must work without any need for further synchronization, as there is the * requirement that only one MessageListener be called at a time. In other words, * MessageListener calling is single-threaded. + * * @see javax.jms.JMSContext#close() * @see javax.jms.JMSContext#stop() */ - public void assertNotMessageListenerThreadRuntime() - { - if (messageListenerThreads.contains(Thread.currentThread().getId())) - { + public void assertNotMessageListenerThreadRuntime() { + if (messageListenerThreads.contains(Thread.currentThread().getId())) { throw ActiveMQJMSClientBundle.BUNDLE.callingMethodFromListenerRuntime(); } } /** * Asserts a {@link javax.jms.MessageListener} is not calling from its own {@link javax.jms.Connection} or - * {@link javax.jms.MessageConsumer}. + * {@link javax.jms.MessageConsumer}. *

    * Note that the code must work without any need for further synchronization, as there is the * requirement that only one MessageListener be called at a time. In other words, @@ -145,10 +136,8 @@ public class ThreadAwareContext * @see javax.jms.Connection#close() * @see javax.jms.MessageConsumer#close() */ - public void assertNotMessageListenerThread() throws IllegalStateException - { - if (messageListenerThreads.contains(Thread.currentThread().getId())) - { + public void assertNotMessageListenerThread() throws IllegalStateException { + if (messageListenerThreads.contains(Thread.currentThread().getId())) { throw ActiveMQJMSClientBundle.BUNDLE.callingMethodFromListener(); } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/referenceable/ConnectionFactoryObjectFactory.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/referenceable/ConnectionFactoryObjectFactory.java index ca9ab6d721..b61a51ee8f 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/referenceable/ConnectionFactoryObjectFactory.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/referenceable/ConnectionFactoryObjectFactory.java @@ -24,18 +24,19 @@ import javax.naming.Reference; import javax.naming.spi.ObjectFactory; /** - * * A ConnectionFactoryObjectFactory. * * Given a reference - reconstructs an ActiveMQRAConnectionFactory */ -public class ConnectionFactoryObjectFactory implements ObjectFactory -{ - public Object getObjectInstance(final Object ref, final Name name, final Context ctx, final Hashtable props) throws Exception - { - Reference r = (Reference)ref; +public class ConnectionFactoryObjectFactory implements ObjectFactory { - byte[] bytes = (byte[])r.get("ActiveMQ-CF").getContent(); + public Object getObjectInstance(final Object ref, + final Name name, + final Context ctx, + final Hashtable props) throws Exception { + Reference r = (Reference) ref; + + byte[] bytes = (byte[]) r.get("ActiveMQ-CF").getContent(); // Deserialize return SerializableObjectRefAddr.deserialize(bytes); diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/referenceable/DestinationObjectFactory.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/referenceable/DestinationObjectFactory.java index 7ae8ed135f..59533e05a1 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/referenceable/DestinationObjectFactory.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/referenceable/DestinationObjectFactory.java @@ -24,18 +24,19 @@ import javax.naming.Reference; import javax.naming.spi.ObjectFactory; /** - * * A DestinationObjectFactory. * * Given a Reference - reconstructs an ActiveMQDestination */ -public class DestinationObjectFactory implements ObjectFactory -{ - public Object getObjectInstance(final Object ref, final Name name, final Context ctx, final Hashtable props) throws Exception - { - Reference r = (Reference)ref; +public class DestinationObjectFactory implements ObjectFactory { - byte[] bytes = (byte[])r.get("ActiveMQ-DEST").getContent(); + public Object getObjectInstance(final Object ref, + final Name name, + final Context ctx, + final Hashtable props) throws Exception { + Reference r = (Reference) ref; + + byte[] bytes = (byte[]) r.get("ActiveMQ-DEST").getContent(); // Deserialize return SerializableObjectRefAddr.deserialize(bytes); diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/referenceable/SerializableObjectRefAddr.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/referenceable/SerializableObjectRefAddr.java index d4877c1840..a6e227fdc4 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/referenceable/SerializableObjectRefAddr.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/referenceable/SerializableObjectRefAddr.java @@ -26,25 +26,22 @@ import javax.naming.NamingException; import javax.naming.RefAddr; /** - * * A SerializableObjectRefAddr. * * A RefAddr that can be used for any serializable object. * * Basically the address is the serialized form of the object as a byte[] */ -public class SerializableObjectRefAddr extends RefAddr -{ +public class SerializableObjectRefAddr extends RefAddr { + private static final long serialVersionUID = 9158134548376171898L; private final byte[] bytes; - public SerializableObjectRefAddr(final String type, final Object content) throws NamingException - { + public SerializableObjectRefAddr(final String type, final Object content) throws NamingException { super(type); - try - { + try { // Serialize the object ByteArrayOutputStream bos = new ByteArrayOutputStream(); @@ -56,20 +53,17 @@ public class SerializableObjectRefAddr extends RefAddr bytes = bos.toByteArray(); } - catch (IOException e) - { + catch (IOException e) { throw new NamingException("Failed to serialize object:" + content + ", " + e.getMessage()); } } @Override - public Object getContent() - { + public Object getContent() { return bytes; } - public static Object deserialize(final byte[] bytes) throws IOException, ClassNotFoundException - { + public static Object deserialize(final byte[] bytes) throws IOException, ClassNotFoundException { ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bis); diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jndi/ActiveMQInitialContextFactory.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jndi/ActiveMQInitialContextFactory.java index 31e76db565..ba7474f19d 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jndi/ActiveMQInitialContextFactory.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jndi/ActiveMQInitialContextFactory.java @@ -37,8 +37,8 @@ import org.apache.activemq.artemis.uri.ConnectionFactoryParser; * child context depending on the QoS such as transient or durable and queue or * topic. */ -public class ActiveMQInitialContextFactory implements InitialContextFactory -{ +public class ActiveMQInitialContextFactory implements InitialContextFactory { + public static final String REFRESH_TIMEOUT = "refreshTimeout"; public static final String DISCOVERY_INITIAL_WAIT_TIMEOUT = "discoveryInitialWaitTimeout"; public static final String DYNAMIC_QUEUE_CONTEXT = "dynamicQueues"; @@ -47,50 +47,39 @@ public class ActiveMQInitialContextFactory implements InitialContextFactory private String queuePrefix = "queue."; private String topicPrefix = "topic."; - public Context getInitialContext(Hashtable environment) throws NamingException - { + public Context getInitialContext(Hashtable environment) throws NamingException { // lets create a factory Map data = new ConcurrentHashMap<>(); - for (Iterator iter = environment.entrySet().iterator(); iter.hasNext(); ) - { + for (Iterator iter = environment.entrySet().iterator(); iter.hasNext(); ) { Map.Entry entry = (Map.Entry) iter.next(); String key = entry.getKey().toString(); - if (key.startsWith(connectionFactoryPrefix)) - { + if (key.startsWith(connectionFactoryPrefix)) { String jndiName = key.substring(connectionFactoryPrefix.length()); - try - { + try { ConnectionFactory factory = createConnectionFactory((String) environment.get(key), jndiName); data.put(jndiName, factory); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); throw new NamingException("Invalid broker URL"); } } } - - createQueues(data, environment); createTopics(data, environment); - data.put(DYNAMIC_QUEUE_CONTEXT, new LazyCreateContext() - { + data.put(DYNAMIC_QUEUE_CONTEXT, new LazyCreateContext() { private static final long serialVersionUID = 6503881346214855588L; - protected Object createEntry(String name) - { + protected Object createEntry(String name) { return ActiveMQJMSClient.createQueue(name); } }); - data.put(DYNAMIC_TOPIC_CONTEXT, new LazyCreateContext() - { + data.put(DYNAMIC_TOPIC_CONTEXT, new LazyCreateContext() { private static final long serialVersionUID = 2019166796234979615L; - protected Object createEntry(String name) - { + protected Object createEntry(String name) { return ActiveMQJMSClient.createTopic(name); } }); @@ -100,56 +89,45 @@ public class ActiveMQInitialContextFactory implements InitialContextFactory // Properties // ------------------------------------------------------------------------- - public String getTopicPrefix() - { + public String getTopicPrefix() { return topicPrefix; } - public void setTopicPrefix(String topicPrefix) - { + public void setTopicPrefix(String topicPrefix) { this.topicPrefix = topicPrefix; } - public String getQueuePrefix() - { + public String getQueuePrefix() { return queuePrefix; } - public void setQueuePrefix(String queuePrefix) - { + public void setQueuePrefix(String queuePrefix) { this.queuePrefix = queuePrefix; } // Implementation methods // ------------------------------------------------------------------------- - protected ReadOnlyContext createContext(Hashtable environment, Map data) - { + protected ReadOnlyContext createContext(Hashtable environment, Map data) { return new ReadOnlyContext(environment, data); } - protected void createQueues(Map data, Hashtable environment) - { - for (Iterator iter = environment.entrySet().iterator(); iter.hasNext(); ) - { + protected void createQueues(Map data, Hashtable environment) { + for (Iterator iter = environment.entrySet().iterator(); iter.hasNext(); ) { Map.Entry entry = (Map.Entry) iter.next(); String key = entry.getKey().toString(); - if (key.startsWith(queuePrefix)) - { + if (key.startsWith(queuePrefix)) { String jndiName = key.substring(queuePrefix.length()); data.put(jndiName, createQueue(entry.getValue().toString())); } } } - protected void createTopics(Map data, Hashtable environment) - { - for (Iterator iter = environment.entrySet().iterator(); iter.hasNext(); ) - { + protected void createTopics(Map data, Hashtable environment) { + for (Iterator iter = environment.entrySet().iterator(); iter.hasNext(); ) { Map.Entry entry = (Map.Entry) iter.next(); String key = entry.getKey().toString(); - if (key.startsWith(topicPrefix)) - { + if (key.startsWith(topicPrefix)) { String jndiName = key.substring(topicPrefix.length()); data.put(jndiName, createTopic(entry.getValue().toString())); } @@ -159,24 +137,21 @@ public class ActiveMQInitialContextFactory implements InitialContextFactory /** * Factory method to create new Queue instances */ - protected Queue createQueue(String name) - { + protected Queue createQueue(String name) { return ActiveMQJMSClient.createQueue(name); } /** * Factory method to create new Topic instances */ - protected Topic createTopic(String name) - { + protected Topic createTopic(String name) { return ActiveMQJMSClient.createTopic(name); } /** * Factory method to create a new connection factory from the given environment */ - protected ConnectionFactory createConnectionFactory(String uri, String name) throws Exception - { + protected ConnectionFactory createConnectionFactory(String uri, String name) throws Exception { ConnectionFactoryParser parser = new ConnectionFactoryParser(); return parser.newObject(parser.expandURI(uri), name); } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jndi/LazyCreateContext.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jndi/LazyCreateContext.java index b2e83534a7..a817d69e46 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jndi/LazyCreateContext.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jndi/LazyCreateContext.java @@ -19,19 +19,15 @@ package org.apache.activemq.artemis.jndi; import javax.naming.NameNotFoundException; import javax.naming.NamingException; -public abstract class LazyCreateContext extends ReadOnlyContext -{ - public Object lookup(String name) throws NamingException - { - try - { +public abstract class LazyCreateContext extends ReadOnlyContext { + + public Object lookup(String name) throws NamingException { + try { return super.lookup(name); } - catch (NameNotFoundException e) - { + catch (NameNotFoundException e) { Object answer = createEntry(name); - if (answer == null) - { + if (answer == null) { throw e; } internalBind(name, answer); diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jndi/NameParserImpl.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jndi/NameParserImpl.java index ae7f417a28..b469cb8cd0 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jndi/NameParserImpl.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jndi/NameParserImpl.java @@ -21,10 +21,9 @@ import javax.naming.Name; import javax.naming.NameParser; import javax.naming.NamingException; -public class NameParserImpl implements NameParser -{ - public Name parse(String name) throws NamingException - { +public class NameParserImpl implements NameParser { + + public Name parse(String name) throws NamingException { return new CompositeName(name); } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jndi/ReadOnlyContext.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jndi/ReadOnlyContext.java index 69f5e9c3ab..f0daa9f2a1 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jndi/ReadOnlyContext.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jndi/ReadOnlyContext.java @@ -60,8 +60,8 @@ import org.apache.activemq.artemis.core.client.ActiveMQClientLogger; * */ @SuppressWarnings("unchecked") -public class ReadOnlyContext implements Context, Serializable -{ +public class ReadOnlyContext implements Context, Serializable { + public static final String SEPARATOR = "/"; protected static final NameParser NAME_PARSER = new NameParserImpl(); private static final long serialVersionUID = -5754338187296859149L; @@ -73,49 +73,38 @@ public class ReadOnlyContext implements Context, Serializable private boolean frozen; private String nameInNamespace = ""; - public ReadOnlyContext() - { + public ReadOnlyContext() { environment = new Hashtable(); bindings = new HashMap(); treeBindings = new HashMap(); } - public ReadOnlyContext(Hashtable env) - { - if (env == null) - { + public ReadOnlyContext(Hashtable env) { + if (env == null) { this.environment = new Hashtable(); } - else - { + else { this.environment = new Hashtable(env); } this.bindings = Collections.EMPTY_MAP; this.treeBindings = Collections.EMPTY_MAP; } - public ReadOnlyContext(Hashtable environment, Map bindings) - { - if (environment == null) - { + public ReadOnlyContext(Hashtable environment, Map bindings) { + if (environment == null) { this.environment = new Hashtable(); } - else - { + else { this.environment = new Hashtable(environment); } this.bindings = new HashMap(); treeBindings = new HashMap(); - if (bindings != null) - { - for (Map.Entry binding : bindings.entrySet()) - { - try - { + if (bindings != null) { + for (Map.Entry binding : bindings.entrySet()) { + try { internalBind(binding.getKey(), binding.getValue()); } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQClientLogger.LOGGER.error("Failed to bind " + binding.getKey() + "=" + binding.getValue(), e); } } @@ -123,32 +112,27 @@ public class ReadOnlyContext implements Context, Serializable frozen = true; } - public ReadOnlyContext(Hashtable environment, Map bindings, String nameInNamespace) - { + public ReadOnlyContext(Hashtable environment, Map bindings, String nameInNamespace) { this(environment, bindings); this.nameInNamespace = nameInNamespace; } - protected ReadOnlyContext(ReadOnlyContext clone, Hashtable env) - { + protected ReadOnlyContext(ReadOnlyContext clone, Hashtable env) { this.bindings = clone.bindings; this.treeBindings = clone.treeBindings; this.environment = new Hashtable(env); } - protected ReadOnlyContext(ReadOnlyContext clone, Hashtable env, String nameInNamespace) - { + protected ReadOnlyContext(ReadOnlyContext clone, Hashtable env, String nameInNamespace) { this(clone, env); this.nameInNamespace = nameInNamespace; } - public void freeze() - { + public void freeze() { frozen = true; } - boolean isFrozen() - { + boolean isFrozen() { return frozen; } @@ -167,44 +151,37 @@ public class ReadOnlyContext implements Context, Serializable * @return * @throws javax.naming.NamingException */ - protected Map internalBind(String name, Object value) throws NamingException - { + protected Map internalBind(String name, Object value) throws NamingException { assert name != null && name.length() > 0; assert !frozen; Map newBindings = new HashMap(); int pos = name.indexOf('/'); - if (pos == -1) - { - if (treeBindings.put(name, value) != null) - { + if (pos == -1) { + if (treeBindings.put(name, value) != null) { throw new NamingException("Something already bound at " + name); } bindings.put(name, value); newBindings.put(name, value); } - else - { + else { String segment = name.substring(0, pos); assert segment != null; assert !segment.equals(""); Object o = treeBindings.get(segment); - if (o == null) - { + if (o == null) { o = newContext(); treeBindings.put(segment, o); bindings.put(segment, o); newBindings.put(segment, o); } - else if (!(o instanceof ReadOnlyContext)) - { + else if (!(o instanceof ReadOnlyContext)) { throw new NamingException("Something already bound where a subcontext should go"); } ReadOnlyContext readOnlyContext = (ReadOnlyContext) o; String remainder = name.substring(pos + 1); Map subBindings = readOnlyContext.internalBind(remainder, value); - for (Iterator iterator = subBindings.entrySet().iterator(); iterator.hasNext(); ) - { + for (Iterator iterator = subBindings.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry entry = (Map.Entry) iterator.next(); String subName = segment + "/" + (String) entry.getKey(); Object bound = entry.getValue(); @@ -215,70 +192,55 @@ public class ReadOnlyContext implements Context, Serializable return newBindings; } - protected ReadOnlyContext newContext() - { + protected ReadOnlyContext newContext() { return new ReadOnlyContext(); } - public Object addToEnvironment(String propName, Object propVal) throws NamingException - { + public Object addToEnvironment(String propName, Object propVal) throws NamingException { return environment.put(propName, propVal); } - public Hashtable getEnvironment() throws NamingException - { + public Hashtable getEnvironment() throws NamingException { return (Hashtable) environment.clone(); } - public Object removeFromEnvironment(String propName) throws NamingException - { + public Object removeFromEnvironment(String propName) throws NamingException { return environment.remove(propName); } - public Object lookup(String name) throws NamingException - { - if (name.length() == 0) - { + public Object lookup(String name) throws NamingException { + if (name.length() == 0) { return this; } Object result = treeBindings.get(name); - if (result == null) - { + if (result == null) { result = bindings.get(name); } - if (result == null) - { + if (result == null) { int pos = name.indexOf(':'); - if (pos > 0) - { + if (pos > 0) { String scheme = name.substring(0, pos); Context ctx = NamingManager.getURLContext(scheme, environment); - if (ctx == null) - { + if (ctx == null) { throw new NamingException("scheme " + scheme + " not recognized"); } return ctx.lookup(name); } - else - { + else { // Split out the first name of the path // and look for it in the bindings map. CompositeName path = new CompositeName(name); - if (path.size() == 0) - { + if (path.size() == 0) { return this; } - else - { + else { String first = path.get(0); Object obj = bindings.get(first); - if (obj == null) - { + if (obj == null) { throw new NameNotFoundException(name); } - else if (obj instanceof Context && path.size() > 1) - { + else if (obj instanceof Context && path.size() > 1) { Context subContext = (Context) obj; obj = subContext.lookup(path.getSuffix(1)); } @@ -286,31 +248,24 @@ public class ReadOnlyContext implements Context, Serializable } } } - if (result instanceof LinkRef) - { + if (result instanceof LinkRef) { LinkRef ref = (LinkRef) result; result = lookup(ref.getLinkName()); } - if (result instanceof Reference) - { - try - { + if (result instanceof Reference) { + try { result = NamingManager.getObjectInstance(result, null, null, this.environment); } - catch (NamingException e) - { + catch (NamingException e) { throw e; } - catch (Exception e) - { + catch (Exception e) { throw (NamingException) new NamingException("could not look up : " + name).initCause(e); } } - if (result instanceof ReadOnlyContext) - { + if (result instanceof ReadOnlyContext) { String prefix = getNameInNamespace(); - if (prefix.length() > 0) - { + if (prefix.length() > 0) { prefix = prefix + SEPARATOR; } result = new ReadOnlyContext((ReadOnlyContext) result, environment, prefix + name); @@ -318,217 +273,173 @@ public class ReadOnlyContext implements Context, Serializable return result; } - public Object lookup(Name name) throws NamingException - { + public Object lookup(Name name) throws NamingException { return lookup(name.toString()); } - public Object lookupLink(String name) throws NamingException - { + public Object lookupLink(String name) throws NamingException { return lookup(name); } - public Name composeName(Name name, Name prefix) throws NamingException - { + public Name composeName(Name name, Name prefix) throws NamingException { Name result = (Name) prefix.clone(); result.addAll(name); return result; } - public String composeName(String name, String prefix) throws NamingException - { + public String composeName(String name, String prefix) throws NamingException { CompositeName result = new CompositeName(prefix); result.addAll(new CompositeName(name)); return result.toString(); } - public NamingEnumeration list(String name) throws NamingException - { + public NamingEnumeration list(String name) throws NamingException { Object o = lookup(name); - if (o == this) - { + if (o == this) { return new ListEnumeration(); } - else if (o instanceof Context) - { + else if (o instanceof Context) { return ((Context) o).list(""); } - else - { + else { throw new NotContextException(); } } - public NamingEnumeration listBindings(String name) throws NamingException - { + public NamingEnumeration listBindings(String name) throws NamingException { Object o = lookup(name); - if (o == this) - { + if (o == this) { return new ListBindingEnumeration(); } - else if (o instanceof Context) - { + else if (o instanceof Context) { return ((Context) o).listBindings(""); } - else - { + else { throw new NotContextException(); } } - public Object lookupLink(Name name) throws NamingException - { + public Object lookupLink(Name name) throws NamingException { return lookupLink(name.toString()); } - public NamingEnumeration list(Name name) throws NamingException - { + public NamingEnumeration list(Name name) throws NamingException { return list(name.toString()); } - public NamingEnumeration listBindings(Name name) throws NamingException - { + public NamingEnumeration listBindings(Name name) throws NamingException { return listBindings(name.toString()); } - public void bind(Name name, Object obj) throws NamingException - { + public void bind(Name name, Object obj) throws NamingException { throw new OperationNotSupportedException(); } - public void bind(String name, Object obj) throws NamingException - { + public void bind(String name, Object obj) throws NamingException { throw new OperationNotSupportedException(); } - public void close() throws NamingException - { + public void close() throws NamingException { // ignore } - public Context createSubcontext(Name name) throws NamingException - { + public Context createSubcontext(Name name) throws NamingException { throw new OperationNotSupportedException(); } - public Context createSubcontext(String name) throws NamingException - { + public Context createSubcontext(String name) throws NamingException { throw new OperationNotSupportedException(); } - public void destroySubcontext(Name name) throws NamingException - { + public void destroySubcontext(Name name) throws NamingException { throw new OperationNotSupportedException(); } - public void destroySubcontext(String name) throws NamingException - { + public void destroySubcontext(String name) throws NamingException { throw new OperationNotSupportedException(); } - public String getNameInNamespace() throws NamingException - { + public String getNameInNamespace() throws NamingException { return nameInNamespace; } - public NameParser getNameParser(Name name) throws NamingException - { + public NameParser getNameParser(Name name) throws NamingException { return NAME_PARSER; } - public NameParser getNameParser(String name) throws NamingException - { + public NameParser getNameParser(String name) throws NamingException { return NAME_PARSER; } - public void rebind(Name name, Object obj) throws NamingException - { + public void rebind(Name name, Object obj) throws NamingException { throw new OperationNotSupportedException(); } - public void rebind(String name, Object obj) throws NamingException - { + public void rebind(String name, Object obj) throws NamingException { throw new OperationNotSupportedException(); } - public void rename(Name oldName, Name newName) throws NamingException - { + public void rename(Name oldName, Name newName) throws NamingException { throw new OperationNotSupportedException(); } - public void rename(String oldName, String newName) throws NamingException - { + public void rename(String oldName, String newName) throws NamingException { throw new OperationNotSupportedException(); } - public void unbind(Name name) throws NamingException - { + public void unbind(Name name) throws NamingException { throw new OperationNotSupportedException(); } - public void unbind(String name) throws NamingException - { + public void unbind(String name) throws NamingException { throw new OperationNotSupportedException(); } - private abstract class LocalNamingEnumeration implements NamingEnumeration - { - private final Iterator i = bindings.entrySet() - .iterator(); + private abstract class LocalNamingEnumeration implements NamingEnumeration { - public boolean hasMore() throws NamingException - { + private final Iterator i = bindings.entrySet().iterator(); + + public boolean hasMore() throws NamingException { return i.hasNext(); } - public boolean hasMoreElements() - { + public boolean hasMoreElements() { return i.hasNext(); } - protected Map.Entry getNext() - { + protected Map.Entry getNext() { return (Map.Entry) i.next(); } - public void close() throws NamingException - { + public void close() throws NamingException { } } - private class ListEnumeration extends LocalNamingEnumeration - { - ListEnumeration() - { + private class ListEnumeration extends LocalNamingEnumeration { + + ListEnumeration() { } - public Object next() throws NamingException - { + public Object next() throws NamingException { return nextElement(); } - public Object nextElement() - { + public Object nextElement() { Map.Entry entry = getNext(); - return new NameClassPair((String) entry.getKey(), entry.getValue() - .getClass() - .getName()); + return new NameClassPair((String) entry.getKey(), entry.getValue().getClass().getName()); } } - private class ListBindingEnumeration extends LocalNamingEnumeration - { - ListBindingEnumeration() - { + private class ListBindingEnumeration extends LocalNamingEnumeration { + + ListBindingEnumeration() { } - public Object next() throws NamingException - { + public Object next() throws NamingException { return nextElement(); } - public Object nextElement() - { + public Object nextElement() { Map.Entry entry = getNext(); return new Binding((String) entry.getKey(), entry.getValue()); } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/AbstractCFSchema.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/AbstractCFSchema.java index 407c9dbc33..b93d2eae4b 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/AbstractCFSchema.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/AbstractCFSchema.java @@ -24,15 +24,12 @@ import org.apache.activemq.artemis.core.client.ActiveMQClientLogger; import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; import org.apache.activemq.artemis.utils.uri.URISchema; -public abstract class AbstractCFSchema extends URISchema -{ +public abstract class AbstractCFSchema extends URISchema { - protected JMSConnectionOptions newConectionOptions(URI uri, Map query) throws Exception - { + protected JMSConnectionOptions newConectionOptions(URI uri, Map query) throws Exception { String type = query.get("type"); // We do this check here to guarantee proper logging - if (JMSConnectionOptions.convertCFType(type) == null) - { + if (JMSConnectionOptions.convertCFType(type) == null) { ActiveMQClientLogger.LOGGER.invalidCFType(type, uri.toString()); } return setData(uri, new JMSConnectionOptions(), query); diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/ConnectionFactoryParser.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/ConnectionFactoryParser.java index 50a3644778..1e3e32d1b6 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/ConnectionFactoryParser.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/ConnectionFactoryParser.java @@ -20,10 +20,9 @@ package org.apache.activemq.artemis.uri; import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; import org.apache.activemq.artemis.utils.uri.URIFactory; -public class ConnectionFactoryParser extends URIFactory -{ - public ConnectionFactoryParser() - { +public class ConnectionFactoryParser extends URIFactory { + + public ConnectionFactoryParser() { registerSchema(new TCPSchema()); registerSchema(new UDPSchema()); registerSchema(new JGroupsSchema()); diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/InVMSchema.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/InVMSchema.java index adbff6676c..b161786377 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/InVMSchema.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/InVMSchema.java @@ -23,27 +23,24 @@ import org.apache.activemq.artemis.utils.uri.SchemaConstants; import java.net.URI; import java.util.Map; -public class InVMSchema extends AbstractCFSchema -{ +public class InVMSchema extends AbstractCFSchema { + @Override - public String getSchemaName() - { + public String getSchemaName() { return SchemaConstants.VM; } @Override - protected ActiveMQConnectionFactory internalNewObject(URI uri, Map query, String name) throws Exception - { + protected ActiveMQConnectionFactory internalNewObject(URI uri, + Map query, + String name) throws Exception { JMSConnectionOptions options = newConectionOptions(uri, query); - ActiveMQConnectionFactory factory = - ActiveMQJMSClient.createConnectionFactoryWithoutHA(options.getFactoryTypeEnum(), - InVMTransportConfigurationSchema.createTransportConfiguration(uri, query, name, "org.apache.activemq.artemis.core.remoting.impl.invm.InVMConnectorFactory")); + ActiveMQConnectionFactory factory = ActiveMQJMSClient.createConnectionFactoryWithoutHA(options.getFactoryTypeEnum(), InVMTransportConfigurationSchema.createTransportConfiguration(uri, query, name, "org.apache.activemq.artemis.core.remoting.impl.invm.InVMConnectorFactory")); return setData(uri, factory, query); } @Override - protected URI internalNewURI(ActiveMQConnectionFactory bean) throws Exception - { + protected URI internalNewURI(ActiveMQConnectionFactory bean) throws Exception { return InVMServerLocatorSchema.getUri(bean.getStaticConnectors()); } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/JGroupsSchema.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/JGroupsSchema.java index 15e5865b82..a6b368037c 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/JGroupsSchema.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/JGroupsSchema.java @@ -30,53 +30,47 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; import org.apache.activemq.artemis.utils.uri.SchemaConstants; import org.apache.activemq.artemis.utils.uri.URISchema; -public class JGroupsSchema extends AbstractCFSchema -{ +public class JGroupsSchema extends AbstractCFSchema { + @Override - public String getSchemaName() - { + public String getSchemaName() { return SchemaConstants.JGROUPS; } @Override - public ActiveMQConnectionFactory internalNewObject(URI uri, Map query, String name) throws Exception - { + public ActiveMQConnectionFactory internalNewObject(URI uri, + Map query, + String name) throws Exception { JMSConnectionOptions options = newConectionOptions(uri, query); DiscoveryGroupConfiguration dcConfig = JGroupsServerLocatorSchema.getDiscoveryGroupConfiguration(uri, query, name); ActiveMQConnectionFactory factory; - if (options.isHa()) - { + if (options.isHa()) { factory = ActiveMQJMSClient.createConnectionFactoryWithHA(dcConfig, options.getFactoryTypeEnum()); } - else - { - factory = ActiveMQJMSClient.createConnectionFactoryWithoutHA(dcConfig, options.getFactoryTypeEnum()); + else { + factory = ActiveMQJMSClient.createConnectionFactoryWithoutHA(dcConfig, options.getFactoryTypeEnum()); } return URISchema.setData(uri, factory, query); } @Override - protected URI internalNewURI(ActiveMQConnectionFactory bean) throws Exception - { + protected URI internalNewURI(ActiveMQConnectionFactory bean) throws Exception { DiscoveryGroupConfiguration dgc = bean.getDiscoveryGroupConfiguration(); - BroadcastEndpointFactory endpoint = dgc.getBroadcastEndpointFactory(); + BroadcastEndpointFactory endpoint = dgc.getBroadcastEndpointFactory(); String auth; - if (endpoint instanceof JGroupsFileBroadcastEndpointFactory) - { + if (endpoint instanceof JGroupsFileBroadcastEndpointFactory) { auth = ((JGroupsFileBroadcastEndpointFactory) endpoint).getChannelName(); } - else if (endpoint instanceof JGroupsPropertiesBroadcastEndpointFactory) - { + else if (endpoint instanceof JGroupsPropertiesBroadcastEndpointFactory) { auth = ((JGroupsPropertiesBroadcastEndpointFactory) endpoint).getChannelName(); } - else - { + else { throw new NotSerializableException(endpoint + "not serializable"); } String query = URISchema.getData(null, bean, dgc, endpoint); dgc.setBroadcastEndpointFactory(endpoint); - return new URI(SchemaConstants.JGROUPS, null, auth, -1, null, query, null); + return new URI(SchemaConstants.JGROUPS, null, auth, -1, null, query, null); } } diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/JMSConnectionOptions.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/JMSConnectionOptions.java index 0f158002c2..04d8e8f16c 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/JMSConnectionOptions.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/JMSConnectionOptions.java @@ -24,52 +24,41 @@ import org.apache.activemq.artemis.api.jms.JMSFactoryType; * When parsing the URL this will serve as an intermediate object * And it could also be a pl */ -public class JMSConnectionOptions extends ConnectionOptions -{ +public class JMSConnectionOptions extends ConnectionOptions { + private JMSFactoryType factoryType = JMSFactoryType.CF; - public JMSFactoryType getFactoryTypeEnum() - { + public JMSFactoryType getFactoryTypeEnum() { return factoryType; } - public String getType() - { + public String getType() { return factoryType.toString(); } - - public void setType(final String type) - { + public void setType(final String type) { this.factoryType = convertCFType(type); - if (factoryType == null) - { + if (factoryType == null) { factoryType = JMSFactoryType.CF; } } - public static JMSFactoryType convertCFType(String type) - { - try - { - if (type == null) - { + public static JMSFactoryType convertCFType(String type) { + try { + if (type == null) { return JMSFactoryType.CF; } - else - { + else { return Enum.valueOf(JMSFactoryType.class, type); } } - catch (Exception e) - { + catch (Exception e) { return null; } } @Override - public String toString() - { + public String toString() { return "JMSConnectionOptions{" + ", factoryType=" + factoryType + '}'; diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/TCPSchema.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/TCPSchema.java index b318718de7..7a35a41ecd 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/TCPSchema.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/TCPSchema.java @@ -28,21 +28,20 @@ import java.net.URI; import java.util.List; import java.util.Map; -public class TCPSchema extends AbstractCFSchema -{ +public class TCPSchema extends AbstractCFSchema { + @Override - public String getSchemaName() - { + public String getSchemaName() { return SchemaConstants.TCP; } @Override - protected ActiveMQConnectionFactory internalNewObject(URI uri, Map query, String name) throws Exception - { + protected ActiveMQConnectionFactory internalNewObject(URI uri, + Map query, + String name) throws Exception { JMSConnectionOptions options = newConectionOptions(uri, query); - List configurations = - TCPTransportConfigurationSchema.getTransportConfigurations(uri, query, TransportConstants.ALLOWABLE_CONNECTOR_KEYS, name, NettyConnectorFactory.class.getName()); + List configurations = TCPTransportConfigurationSchema.getTransportConfigurations(uri, query, TransportConstants.ALLOWABLE_CONNECTOR_KEYS, name, NettyConnectorFactory.class.getName()); TransportConfiguration[] tcs = new TransportConfiguration[configurations.size()]; @@ -50,21 +49,18 @@ public class TCPSchema extends AbstractCFSchema ActiveMQConnectionFactory factory; - if (options.isHa()) - { + if (options.isHa()) { factory = ActiveMQJMSClient.createConnectionFactoryWithHA(options.getFactoryTypeEnum(), tcs); } - else - { - factory = ActiveMQJMSClient.createConnectionFactoryWithoutHA(options.getFactoryTypeEnum(), tcs); + else { + factory = ActiveMQJMSClient.createConnectionFactoryWithoutHA(options.getFactoryTypeEnum(), tcs); } return URISchema.setData(uri, factory, query); } @Override - protected URI internalNewURI(ActiveMQConnectionFactory bean) throws Exception - { + protected URI internalNewURI(ActiveMQConnectionFactory bean) throws Exception { String query = URISchema.getData(null, bean); TransportConfiguration[] staticConnectors = bean.getStaticConnectors(); return TCPServerLocatorSchema.getURI(query, staticConnectors); diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/UDPSchema.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/UDPSchema.java index e0a6faa39a..9c83755a7e 100644 --- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/UDPSchema.java +++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/uri/UDPSchema.java @@ -27,40 +27,37 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; import org.apache.activemq.artemis.utils.uri.SchemaConstants; import org.apache.activemq.artemis.utils.uri.URISchema; -public class UDPSchema extends AbstractCFSchema -{ +public class UDPSchema extends AbstractCFSchema { + @Override - public String getSchemaName() - { + public String getSchemaName() { return SchemaConstants.UDP; } @Override - public ActiveMQConnectionFactory internalNewObject(URI uri, Map query, String name) throws Exception - { + public ActiveMQConnectionFactory internalNewObject(URI uri, + Map query, + String name) throws Exception { JMSConnectionOptions options = newConectionOptions(uri, query); DiscoveryGroupConfiguration dgc = UDPServerLocatorSchema.getDiscoveryGroupConfiguration(uri, query, getHost(uri), getPort(uri), name); ActiveMQConnectionFactory factory; - if (options.isHa()) - { + if (options.isHa()) { factory = ActiveMQJMSClient.createConnectionFactoryWithHA(dgc, options.getFactoryTypeEnum()); } - else - { - factory = ActiveMQJMSClient.createConnectionFactoryWithoutHA(dgc, options.getFactoryTypeEnum()); + else { + factory = ActiveMQJMSClient.createConnectionFactoryWithoutHA(dgc, options.getFactoryTypeEnum()); } return URISchema.setData(uri, factory, query); } @Override - protected URI internalNewURI(ActiveMQConnectionFactory bean) throws Exception - { + protected URI internalNewURI(ActiveMQConnectionFactory bean) throws Exception { DiscoveryGroupConfiguration dgc = bean.getDiscoveryGroupConfiguration(); UDPBroadcastEndpointFactory endpoint = (UDPBroadcastEndpointFactory) dgc.getBroadcastEndpointFactory(); String query = URISchema.getData(UDPServerLocatorSchema.IGNORED, bean, dgc, endpoint); dgc.setBroadcastEndpointFactory(endpoint); - return new URI(SchemaConstants.UDP, null, endpoint.getGroupAddress(), endpoint.getGroupPort(), null, query, null); + return new URI(SchemaConstants.UDP, null, endpoint.getGroupAddress(), endpoint.getGroupPort(), null, query, null); } } diff --git a/artemis-jms-client/src/test/java/org/apache/activemq/artemis/uri/ConnectionFactoryURITest.java b/artemis-jms-client/src/test/java/org/apache/activemq/artemis/uri/ConnectionFactoryURITest.java index d3f047edd0..8169553fba 100644 --- a/artemis-jms-client/src/test/java/org/apache/activemq/artemis/uri/ConnectionFactoryURITest.java +++ b/artemis-jms-client/src/test/java/org/apache/activemq/artemis/uri/ConnectionFactoryURITest.java @@ -45,61 +45,55 @@ import org.apache.commons.beanutils.BeanUtilsBean; import org.junit.Assert; import org.junit.Test; -public class ConnectionFactoryURITest -{ +public class ConnectionFactoryURITest { + ConnectionFactoryParser parser = new ConnectionFactoryParser(); @Test - public void testQUEUE_XA_CF() throws Exception - { + public void testQUEUE_XA_CF() throws Exception { ActiveMQConnectionFactory factory = parser.newObject(new URI("tcp://localhost:3030?ha=true&type=QUEUE_XA_CF"), null); Assert.assertTrue(ActiveMQXAQueueConnectionFactory.class.getName().equals(factory.getClass().getName())); } @Test - public void testTOPICXA_CF() throws Exception - { + public void testTOPICXA_CF() throws Exception { ActiveMQConnectionFactory factory = parser.newObject(new URI("tcp://localhost:3030?ha=true&type=TOPIC_XA_CF"), null); Assert.assertTrue(ActiveMQXATopicConnectionFactory.class.getName().equals(factory.getClass().getName())); } + @Test - public void testQUEUE_CF() throws Exception - { + public void testQUEUE_CF() throws Exception { ActiveMQConnectionFactory factory = parser.newObject(new URI("tcp://localhost:3030?ha=true&type=QUEUE_CF"), null); Assert.assertTrue(ActiveMQQueueConnectionFactory.class.getName().equals(factory.getClass().getName())); } @Test - public void testTOPIC_CF() throws Exception - { + public void testTOPIC_CF() throws Exception { ActiveMQConnectionFactory factory = parser.newObject(new URI("tcp://localhost:3030?ha=true&type=TOPIC_CF"), null); Assert.assertTrue(ActiveMQTopicConnectionFactory.class.getName().equals(factory.getClass().getName())); } @Test - public void testCF() throws Exception - { + public void testCF() throws Exception { ActiveMQConnectionFactory factory = parser.newObject(new URI("tcp://localhost:3030?ha=true&type=CF"), null); Assert.assertTrue(ActiveMQJMSConnectionFactory.class.getName().equals(factory.getClass().getName())); } @Test - public void testNoCF() throws Exception - { + public void testNoCF() throws Exception { ActiveMQConnectionFactory factory = parser.newObject(new URI("tcp://localhost:3030?ha=true"), null); Assert.assertTrue(ActiveMQJMSConnectionFactory.class.getName().equals(factory.getClass().getName())); } @Test - public void testTCPAllProperties() throws Exception - { + public void testTCPAllProperties() throws Exception { StringBuilder sb = new StringBuilder(); sb.append("tcp://localhost:3030?ha=true"); BeanUtilsBean bean = new BeanUtilsBean(); @@ -110,8 +104,7 @@ public class ConnectionFactoryURITest } @Test - public void testTCPAllNettyConnectorProperties() throws Exception - { + public void testTCPAllNettyConnectorProperties() throws Exception { Map props = new HashMap<>(); Set allowableConnectorKeys = TransportConstants.ALLOWABLE_CONNECTOR_KEYS; StringBuilder sb = new StringBuilder(); @@ -122,19 +115,15 @@ public class ConnectionFactoryURITest Map params = factory.getStaticConnectors()[0].getParams(); Assert.assertEquals(params.get("host"), "localhost"); Assert.assertEquals(params.get("port"), "3030"); - for (Map.Entry entry : params.entrySet()) - { - if (!entry.getKey().equals("host") && !entry.getKey().equals("port")) - { + for (Map.Entry entry : params.entrySet()) { + if (!entry.getKey().equals("host") && !entry.getKey().equals("port")) { Assert.assertEquals(entry.getValue(), props.get(entry.getKey())); } } } - @Test - public void testTCPAllNettyConnectorPropertiesMultiple() throws Exception - { + public void testTCPAllNettyConnectorPropertiesMultiple() throws Exception { Map props = new HashMap<>(); Set allowableConnectorKeys = TransportConstants.ALLOWABLE_CONNECTOR_KEYS; StringBuilder sb = new StringBuilder(); @@ -152,32 +141,28 @@ public class ConnectionFactoryURITest TransportConfiguration[] staticConnectors = factory.getStaticConnectors(); Assert.assertEquals(3, staticConnectors.length); - checkTC(props, staticConnectors[0],0); - checkTC(props2, staticConnectors[1],1); - checkTC(props3, staticConnectors[2],2); + checkTC(props, staticConnectors[0], 0); + checkTC(props2, staticConnectors[1], 1); + checkTC(props3, staticConnectors[2], 2); } - private void checkTC(Map props, TransportConfiguration staticConnector, int offfSet) - { + private void checkTC(Map props, TransportConfiguration staticConnector, int offfSet) { TransportConfiguration connector = staticConnector; Assert.assertEquals(connector.getParams().get("host"), "localhost" + offfSet); Assert.assertEquals(connector.getParams().get("port"), "" + (61616 + offfSet)); Map params = connector.getParams(); - for (Map.Entry entry : params.entrySet()) - { - if (!entry.getKey().equals("host") && !entry.getKey().equals("port")) - { + for (Map.Entry entry : params.entrySet()) { + if (!entry.getKey().equals("host") && !entry.getKey().equals("port")) { Assert.assertEquals(entry.getValue(), props.get(entry.getKey())); } } } - private void populateConnectorParams(Map props, Set allowableConnectorKeys, StringBuilder sb) - { - for (String allowableConnectorKey : allowableConnectorKeys) - { - if (!allowableConnectorKey.equals("host") && !allowableConnectorKey.equals("port")) - { + private void populateConnectorParams(Map props, + Set allowableConnectorKeys, + StringBuilder sb) { + for (String allowableConnectorKey : allowableConnectorKeys) { + if (!allowableConnectorKey.equals("host") && !allowableConnectorKey.equals("port")) { String value = RandomUtil.randomString(); props.put(allowableConnectorKey, value); sb.append("&").append(allowableConnectorKey).append("=").append(value); @@ -186,8 +171,7 @@ public class ConnectionFactoryURITest } @Test - public void testTCPURI() throws Exception - { + public void testTCPURI() throws Exception { TransportConfiguration tc = new TransportConfiguration(NettyConnectorFactory.class.getName()); HashMap params = new HashMap<>(); params.put("host", "localhost1"); @@ -205,16 +189,14 @@ public class ConnectionFactoryURITest } @Test - public void testUDP() throws Exception - { + public void testUDP() throws Exception { ActiveMQConnectionFactory factory = parser.newObject(new URI("udp://localhost:3030?ha=true&type=QUEUE_XA_CF"), null); Assert.assertTrue(ActiveMQXAQueueConnectionFactory.class.getName().equals(factory.getClass().getName())); } @Test - public void testUDPAllProperties() throws Exception - { + public void testUDPAllProperties() throws Exception { StringBuilder sb = new StringBuilder(); sb.append("udp://localhost:3030?ha=true"); BeanUtilsBean bean = new BeanUtilsBean(); @@ -225,15 +207,11 @@ public class ConnectionFactoryURITest } @Test - public void testUDPURI() throws Exception - { + public void testUDPURI() throws Exception { DiscoveryGroupConfiguration discoveryGroupConfiguration = new DiscoveryGroupConfiguration(); UDPBroadcastEndpointFactory endpoint = new UDPBroadcastEndpointFactory(); endpoint.setGroupPort(3333).setGroupAddress("wahey").setLocalBindPort(555).setLocalBindAddress("uhuh"); - discoveryGroupConfiguration.setName("foo") - .setRefreshTimeout(12345) - .setDiscoveryInitialWaitTimeout(5678) - .setBroadcastEndpointFactory(endpoint); + discoveryGroupConfiguration.setName("foo").setRefreshTimeout(12345).setDiscoveryInitialWaitTimeout(5678).setBroadcastEndpointFactory(endpoint); ActiveMQConnectionFactory connectionFactoryWithHA = ActiveMQJMSClient.createConnectionFactoryWithHA(discoveryGroupConfiguration, JMSFactoryType.CF); URI tcp = parser.createSchema("udp", connectionFactoryWithHA); ActiveMQConnectionFactory factory = parser.newObject(tcp, null); @@ -252,22 +230,19 @@ public class ConnectionFactoryURITest Assert.assertEquals(dgc.getDiscoveryInitialWaitTimeout(), 5678); Assert.assertEquals(dgc.getRefreshTimeout(), 12345); - BeanUtilsBean bean = new BeanUtilsBean(); checkEquals(bean, connectionFactoryWithHA, factory); } @Test - public void testInvalidCFType() throws Exception - { + public void testInvalidCFType() throws Exception { ActiveMQConnectionFactory factory = parser.newObject(new URI("udp://localhost:3030?ha=true&type=QUEUE_XA_CFInvalid"), null); Assert.assertTrue(ActiveMQJMSConnectionFactory.class.getName().equals(factory.getClass().getName())); } @Test - public void testJGroupsFile() throws Exception - { + public void testJGroupsFile() throws Exception { ActiveMQConnectionFactory factory = parser.newObject(new URI("jgroups://channel-name?file=/path/to/some/file/channel-file.xml&test=33"), null); Assert.assertTrue(ActiveMQJMSConnectionFactory.class.getName().equals(factory.getClass().getName())); @@ -277,8 +252,7 @@ public class ConnectionFactoryURITest } @Test - public void testJGroupsKeyValue() throws Exception - { + public void testJGroupsKeyValue() throws Exception { ActiveMQConnectionFactory factory = parser.newObject(new URI("jgroups://channel-name?properties=param=value;param2=value2&test=33"), null); Assert.assertTrue(ActiveMQJMSConnectionFactory.class.getName().equals(factory.getClass().getName())); @@ -288,8 +262,7 @@ public class ConnectionFactoryURITest } @Test - public void testJGroupsAllProperties() throws Exception - { + public void testJGroupsAllProperties() throws Exception { StringBuilder sb = new StringBuilder(); sb.append("jgroups://?file=param=value;param=value&channelName=channelName&ha=true"); BeanUtilsBean bean = new BeanUtilsBean(); @@ -299,18 +272,11 @@ public class ConnectionFactoryURITest checkEquals(bean, factory, factory2); } - @Test - public void testJGroupsFileURI() throws Exception - { + public void testJGroupsFileURI() throws Exception { DiscoveryGroupConfiguration discoveryGroupConfiguration = new DiscoveryGroupConfiguration(); - JGroupsFileBroadcastEndpointFactory endpointFactory = new JGroupsFileBroadcastEndpointFactory() - .setChannelName("channel-name") - .setFile("channel-file.xml"); - discoveryGroupConfiguration.setName("foo") - .setRefreshTimeout(12345) - .setDiscoveryInitialWaitTimeout(5678) - .setBroadcastEndpointFactory(endpointFactory); + JGroupsFileBroadcastEndpointFactory endpointFactory = new JGroupsFileBroadcastEndpointFactory().setChannelName("channel-name").setFile("channel-file.xml"); + discoveryGroupConfiguration.setName("foo").setRefreshTimeout(12345).setDiscoveryInitialWaitTimeout(5678).setBroadcastEndpointFactory(endpointFactory); ActiveMQConnectionFactory connectionFactoryWithHA = ActiveMQJMSClient.createConnectionFactoryWithHA(discoveryGroupConfiguration, JMSFactoryType.CF); URI tcp = parser.createSchema("jgroups", connectionFactoryWithHA); ActiveMQConnectionFactory factory = parser.newObject(tcp, null); @@ -326,22 +292,15 @@ public class ConnectionFactoryURITest Assert.assertEquals(fileBroadcastEndpointFactory.getFile(), "channel-file.xml"); Assert.assertEquals(fileBroadcastEndpointFactory.getChannelName(), "channel-name"); - BeanUtilsBean bean = new BeanUtilsBean(); checkEquals(bean, connectionFactoryWithHA, factory); } @Test - public void testJGroupsPropertiesURI() throws Exception - { + public void testJGroupsPropertiesURI() throws Exception { DiscoveryGroupConfiguration discoveryGroupConfiguration = new DiscoveryGroupConfiguration(); - JGroupsPropertiesBroadcastEndpointFactory endpointFactory = new JGroupsPropertiesBroadcastEndpointFactory() - .setChannelName("channel-name") - .setProperties("param=val,param2-val2"); - discoveryGroupConfiguration.setName("foo") - .setRefreshTimeout(12345) - .setDiscoveryInitialWaitTimeout(5678) - .setBroadcastEndpointFactory(endpointFactory); + JGroupsPropertiesBroadcastEndpointFactory endpointFactory = new JGroupsPropertiesBroadcastEndpointFactory().setChannelName("channel-name").setProperties("param=val,param2-val2"); + discoveryGroupConfiguration.setName("foo").setRefreshTimeout(12345).setDiscoveryInitialWaitTimeout(5678).setBroadcastEndpointFactory(endpointFactory); ActiveMQConnectionFactory connectionFactoryWithHA = ActiveMQJMSClient.createConnectionFactoryWithHA(discoveryGroupConfiguration, JMSFactoryType.CF); URI tcp = parser.createSchema("jgroups", connectionFactoryWithHA); ActiveMQConnectionFactory factory = parser.newObject(tcp, null); @@ -361,33 +320,28 @@ public class ConnectionFactoryURITest checkEquals(bean, connectionFactoryWithHA, factory); } - private void populate(StringBuilder sb, BeanUtilsBean bean, ActiveMQConnectionFactory factory) throws IllegalAccessException, InvocationTargetException - { + private void populate(StringBuilder sb, + BeanUtilsBean bean, + ActiveMQConnectionFactory factory) throws IllegalAccessException, InvocationTargetException { PropertyDescriptor[] descriptors = bean.getPropertyUtils().getPropertyDescriptors(factory); - for (PropertyDescriptor descriptor : descriptors) - { - if (descriptor.getWriteMethod() != null && descriptor.getReadMethod() != null) - { - if (descriptor.getPropertyType() == String.class) - { + for (PropertyDescriptor descriptor : descriptors) { + if (descriptor.getWriteMethod() != null && descriptor.getReadMethod() != null) { + if (descriptor.getPropertyType() == String.class) { String value = RandomUtil.randomString(); bean.setProperty(factory, descriptor.getName(), value); sb.append("&").append(descriptor.getName()).append("=").append(value); } - else if (descriptor.getPropertyType() == int.class) - { + else if (descriptor.getPropertyType() == int.class) { int value = RandomUtil.randomPositiveInt(); bean.setProperty(factory, descriptor.getName(), value); sb.append("&").append(descriptor.getName()).append("=").append(value); } - else if (descriptor.getPropertyType() == long.class) - { + else if (descriptor.getPropertyType() == long.class) { long value = RandomUtil.randomPositiveLong(); bean.setProperty(factory, descriptor.getName(), value); sb.append("&").append(descriptor.getName()).append("=").append(value); } - else if (descriptor.getPropertyType() == double.class) - { + else if (descriptor.getPropertyType() == double.class) { double value = RandomUtil.randomDouble(); bean.setProperty(factory, descriptor.getName(), value); sb.append("&").append(descriptor.getName()).append("=").append(value); @@ -396,14 +350,13 @@ public class ConnectionFactoryURITest } } - private void checkEquals(BeanUtilsBean bean, ActiveMQConnectionFactory factory, ActiveMQConnectionFactory factory2) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException - { + private void checkEquals(BeanUtilsBean bean, + ActiveMQConnectionFactory factory, + ActiveMQConnectionFactory factory2) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { PropertyDescriptor[] descriptors = bean.getPropertyUtils().getPropertyDescriptors(factory); - for (PropertyDescriptor descriptor : descriptors) - { - if (descriptor.getWriteMethod() != null && descriptor.getReadMethod() != null) - { - Assert.assertEquals(descriptor.getName() + " incorrect", bean.getProperty(factory, descriptor.getName()),bean.getProperty(factory2, descriptor.getName())); + for (PropertyDescriptor descriptor : descriptors) { + if (descriptor.getWriteMethod() != null && descriptor.getReadMethod() != null) { + Assert.assertEquals(descriptor.getName() + " incorrect", bean.getProperty(factory, descriptor.getName()), bean.getProperty(factory2, descriptor.getName())); } } } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/ActiveMQJMSBridgeLogger.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/ActiveMQJMSBridgeLogger.java index 76194a81da..975c6a722b 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/ActiveMQJMSBridgeLogger.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/ActiveMQJMSBridgeLogger.java @@ -40,56 +40,55 @@ import org.jboss.logging.annotations.MessageLogger; * so an INFO message would be 341000 to 341999 */ @MessageLogger(projectCode = "AMQ") -public interface ActiveMQJMSBridgeLogger extends BasicLogger -{ +public interface ActiveMQJMSBridgeLogger extends BasicLogger { + /** * The default logger. */ ActiveMQJMSBridgeLogger LOGGER = Logger.getMessageLogger(ActiveMQJMSBridgeLogger.class, ActiveMQJMSBridgeLogger.class.getPackage().getName()); @LogMessage(level = Logger.Level.INFO) - @Message(id = 341000, value = "Failed to set up JMS bridge connections. Most probably the source or target servers are unavailable." + - " Will retry after a pause of {0} ms", format = Message.Format.MESSAGE_FORMAT) + @Message(id = 341000, value = "Failed to set up JMS bridge connections. Most probably the source or target servers are unavailable." + " Will retry after a pause of {0} ms", format = Message.Format.MESSAGE_FORMAT) void failedToSetUpBridge(long failureRetryInterval); @LogMessage(level = Logger.Level.INFO) - @Message(id = 341001, value = "JMS Bridge Succeeded in reconnecting to servers" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 341001, value = "JMS Bridge Succeeded in reconnecting to servers", format = Message.Format.MESSAGE_FORMAT) void bridgeReconnected(); @LogMessage(level = Logger.Level.INFO) - @Message(id = 341002, value = "Succeeded in connecting to servers" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 341002, value = "Succeeded in connecting to servers", format = Message.Format.MESSAGE_FORMAT) void bridgeConnected(); @LogMessage(level = Logger.Level.WARN) - @Message(id = 342000, value = "Attempt to start JMS Bridge, but is already started" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 342000, value = "Attempt to start JMS Bridge, but is already started", format = Message.Format.MESSAGE_FORMAT) void errorBridgeAlreadyStarted(); @LogMessage(level = Logger.Level.WARN) - @Message(id = 342001, value = "Failed to start JMS Bridge" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 342001, value = "Failed to start JMS Bridge", format = Message.Format.MESSAGE_FORMAT) void errorStartingBridge(); @LogMessage(level = Logger.Level.WARN) - @Message(id = 342002, value = "Failed to unregisted JMS Bridge {0}" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 342002, value = "Failed to unregisted JMS Bridge {0}", format = Message.Format.MESSAGE_FORMAT) void errorUnregisteringBridge(ObjectName objectName); @LogMessage(level = Logger.Level.WARN) - @Message(id = 342003, value = "JMS Bridge unable to set up connections, bridge will be stopped" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 342003, value = "JMS Bridge unable to set up connections, bridge will be stopped", format = Message.Format.MESSAGE_FORMAT) void errorConnectingBridge(); @LogMessage(level = Logger.Level.WARN) - @Message(id = 342004, value = "JMS Bridge Will retry after a pause of {0} ms" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 342004, value = "JMS Bridge Will retry after a pause of {0} ms", format = Message.Format.MESSAGE_FORMAT) void bridgeRetry(long failureRetryInterval); @LogMessage(level = Logger.Level.WARN) - @Message(id = 342005, value = "JMS Bridge unable to set up connections, bridge will not be started" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 342005, value = "JMS Bridge unable to set up connections, bridge will not be started", format = Message.Format.MESSAGE_FORMAT) void bridgeNotStarted(); @LogMessage(level = Logger.Level.WARN) - @Message(id = 342006, value = "Detected failure on bridge connection" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 342006, value = "Detected failure on bridge connection", format = Message.Format.MESSAGE_FORMAT) void bridgeFailure(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) - @Message(id = 342009, value = "JMS Bridge failed to send + acknowledge batch, closing JMS objects" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 342009, value = "JMS Bridge failed to send + acknowledge batch, closing JMS objects", format = Message.Format.MESSAGE_FORMAT) void bridgeAckError(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @@ -97,10 +96,10 @@ public interface ActiveMQJMSBridgeLogger extends BasicLogger void bridgeConnectError(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) - @Message(id = 344001, value = "Failed to start source connection" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 344001, value = "Failed to start source connection", format = Message.Format.MESSAGE_FORMAT) void jmsBridgeSrcConnectError(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) - @Message(id = 344002, value = "Failed to start JMS Bridge. QoS Mode: {0} requires a Transaction Manager, none found" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 344002, value = "Failed to start JMS Bridge. QoS Mode: {0} requires a Transaction Manager, none found", format = Message.Format.MESSAGE_FORMAT) void jmsBridgeTransactionManagerMissing(QualityOfServiceMode qosMode); } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/ConnectionFactoryFactory.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/ConnectionFactoryFactory.java index 41ea05f23f..e8cb003e29 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/ConnectionFactoryFactory.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/ConnectionFactoryFactory.java @@ -16,7 +16,7 @@ */ package org.apache.activemq.artemis.jms.bridge; -public interface ConnectionFactoryFactory -{ +public interface ConnectionFactoryFactory { + Object createConnectionFactory() throws Exception; } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/DestinationFactory.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/DestinationFactory.java index b53822285d..5b9bb5b68d 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/DestinationFactory.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/DestinationFactory.java @@ -18,7 +18,7 @@ package org.apache.activemq.artemis.jms.bridge; import javax.jms.Destination; -public interface DestinationFactory -{ +public interface DestinationFactory { + Destination createDestination() throws Exception; } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/JMSBridge.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/JMSBridge.java index 3f0bab656f..f42aa30c0e 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/JMSBridge.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/JMSBridge.java @@ -20,8 +20,8 @@ import javax.transaction.TransactionManager; import org.apache.activemq.artemis.core.server.ActiveMQComponent; -public interface JMSBridge extends ActiveMQComponent -{ +public interface JMSBridge extends ActiveMQComponent { + void pause() throws Exception; void resume() throws Exception; diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/JMSBridgeControl.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/JMSBridgeControl.java index 6079ca7a81..b32d0a407c 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/JMSBridgeControl.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/JMSBridgeControl.java @@ -18,8 +18,8 @@ package org.apache.activemq.artemis.jms.bridge; import org.apache.activemq.artemis.api.core.management.ActiveMQComponentControl; -public interface JMSBridgeControl extends ActiveMQComponentControl -{ +public interface JMSBridgeControl extends ActiveMQComponentControl { + void pause() throws Exception; void resume() throws Exception; diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/QualityOfServiceMode.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/QualityOfServiceMode.java index b34d80f261..fdf2aa3587 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/QualityOfServiceMode.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/QualityOfServiceMode.java @@ -64,34 +64,27 @@ package org.apache.activemq.artemis.jms.bridge; * using QOS_ONCE_AND_ONLY_ONCE but may be a good choice depending on your * specific application. */ -public enum QualityOfServiceMode -{ +public enum QualityOfServiceMode { AT_MOST_ONCE(0), DUPLICATES_OK(1), ONCE_AND_ONLY_ONCE(2); private final int value; - QualityOfServiceMode(final int value) - { + QualityOfServiceMode(final int value) { this.value = value; } - public int intValue() - { + public int intValue() { return value; } - public static QualityOfServiceMode valueOf(final int value) - { - if (value == AT_MOST_ONCE.value) - { + public static QualityOfServiceMode valueOf(final int value) { + if (value == AT_MOST_ONCE.value) { return AT_MOST_ONCE; } - if (value == DUPLICATES_OK.value) - { + if (value == DUPLICATES_OK.value) { return DUPLICATES_OK; } - if (value == ONCE_AND_ONLY_ONCE.value) - { + if (value == ONCE_AND_ONLY_ONCE.value) { return ONCE_AND_ONLY_ONCE; } throw new IllegalArgumentException("invalid QualityOfServiceMode value: " + value); diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/impl/JMSBridgeControlImpl.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/impl/JMSBridgeControlImpl.java index e2fa7f70b3..79b10d747d 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/impl/JMSBridgeControlImpl.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/impl/JMSBridgeControlImpl.java @@ -22,198 +22,159 @@ import org.apache.activemq.artemis.jms.bridge.QualityOfServiceMode; import javax.management.StandardMBean; -public class JMSBridgeControlImpl extends StandardMBean implements JMSBridgeControl -{ +public class JMSBridgeControlImpl extends StandardMBean implements JMSBridgeControl { private final JMSBridge bridge; // Constructors -------------------------------------------------- - public JMSBridgeControlImpl(final JMSBridge bridge) throws Exception - { + public JMSBridgeControlImpl(final JMSBridge bridge) throws Exception { super(JMSBridgeControl.class); this.bridge = bridge; } // Public -------------------------------------------------------- - public void pause() throws Exception - { + public void pause() throws Exception { bridge.pause(); } - public void resume() throws Exception - { + public void resume() throws Exception { bridge.resume(); } - public boolean isStarted() - { + public boolean isStarted() { return bridge.isStarted(); } - public void start() throws Exception - { + public void start() throws Exception { bridge.start(); } - public void stop() throws Exception - { + public void stop() throws Exception { bridge.stop(); } - public String getClientID() - { + public String getClientID() { return bridge.getClientID(); } - public long getFailureRetryInterval() - { + public long getFailureRetryInterval() { return bridge.getFailureRetryInterval(); } - public int getMaxBatchSize() - { + public int getMaxBatchSize() { return bridge.getMaxBatchSize(); } - public long getMaxBatchTime() - { + public long getMaxBatchTime() { return bridge.getMaxBatchTime(); } - public int getMaxRetries() - { + public int getMaxRetries() { return bridge.getMaxRetries(); } - public String getQualityOfServiceMode() - { + public String getQualityOfServiceMode() { QualityOfServiceMode mode = bridge.getQualityOfServiceMode(); - if (mode != null) - { + if (mode != null) { return mode.name(); } - else - { + else { return null; } } - public String getSelector() - { + public String getSelector() { return bridge.getSelector(); } - public String getSourcePassword() - { + public String getSourcePassword() { return bridge.getSourcePassword(); } - public String getSourceUsername() - { + public String getSourceUsername() { return bridge.getSourceUsername(); } - public String getSubscriptionName() - { + public String getSubscriptionName() { return bridge.getSubscriptionName(); } - public String getTargetPassword() - { + public String getTargetPassword() { return bridge.getTargetPassword(); } - public String getTargetUsername() - { + public String getTargetUsername() { return bridge.getTargetUsername(); } - public boolean isAddMessageIDInHeader() - { + public boolean isAddMessageIDInHeader() { return bridge.isAddMessageIDInHeader(); } - public boolean isFailed() - { + public boolean isFailed() { return bridge.isFailed(); } - public boolean isPaused() - { + public boolean isPaused() { return bridge.isPaused(); } - public void setAddMessageIDInHeader(final boolean value) - { + public void setAddMessageIDInHeader(final boolean value) { bridge.setAddMessageIDInHeader(value); } - public void setClientID(final String clientID) - { + public void setClientID(final String clientID) { bridge.setClientID(clientID); } - public void setFailureRetryInterval(final long interval) - { + public void setFailureRetryInterval(final long interval) { bridge.setFailureRetryInterval(interval); } - public void setMaxBatchSize(final int size) - { + public void setMaxBatchSize(final int size) { bridge.setMaxBatchSize(size); } - public void setMaxBatchTime(final long time) - { + public void setMaxBatchTime(final long time) { bridge.setMaxBatchTime(time); } - public void setMaxRetries(final int retries) - { + public void setMaxRetries(final int retries) { bridge.setMaxRetries(retries); } - public void setQualityOfServiceMode(String mode) - { - if (mode != null) - { + public void setQualityOfServiceMode(String mode) { + if (mode != null) { bridge.setQualityOfServiceMode(QualityOfServiceMode.valueOf(mode)); } - else - { + else { mode = null; } } - public void setSelector(final String selector) - { + public void setSelector(final String selector) { bridge.setSelector(selector); } - public void setSourcePassword(final String pwd) - { + public void setSourcePassword(final String pwd) { bridge.setSourcePassword(pwd); } - public void setSourceUsername(final String name) - { + public void setSourceUsername(final String name) { bridge.setSourceUsername(name); } - public void setSubscriptionName(final String subname) - { + public void setSubscriptionName(final String subname) { bridge.setSubscriptionName(subname); } - public void setTargetPassword(final String pwd) - { + public void setTargetPassword(final String pwd) { bridge.setTargetPassword(pwd); } - public void setTargetUsername(final String name) - { + public void setTargetUsername(final String name) { bridge.setTargetUsername(name); } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/impl/JMSBridgeImpl.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/impl/JMSBridgeImpl.java index 4424418edf..ea6ea41892 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/impl/JMSBridgeImpl.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/impl/JMSBridgeImpl.java @@ -69,8 +69,8 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -public final class JMSBridgeImpl implements JMSBridge -{ +public final class JMSBridgeImpl implements JMSBridge { + private static final String[] RESOURCE_RECOVERY_CLASS_NAMES = new String[]{"org.jboss.as.messaging.jms.AS7RecoveryRegistry"}; private static boolean trace = ActiveMQJMSBridgeLogger.LOGGER.isTraceEnabled(); @@ -179,8 +179,7 @@ public final class JMSBridgeImpl implements JMSBridge /* * Constructor for MBean */ - public JMSBridgeImpl() - { + public JMSBridgeImpl() { messages = new LinkedList(); executor = createExecutor(); } @@ -201,28 +200,9 @@ public final class JMSBridgeImpl implements JMSBridge final long maxBatchTime, final String subName, final String clientID, - final boolean addMessageIDInHeader) - { + final boolean addMessageIDInHeader) { - this(sourceCff, - targetCff, - sourceDestinationFactory, - targetDestinationFactory, - sourceUsername, - sourcePassword, - targetUsername, - targetPassword, - selector, - failureRetryInterval, - maxRetries, - qosMode, - maxBatchSize, - maxBatchTime, - subName, - clientID, - addMessageIDInHeader, - null, - null); + this(sourceCff, targetCff, sourceDestinationFactory, targetDestinationFactory, sourceUsername, sourcePassword, targetUsername, targetPassword, selector, failureRetryInterval, maxRetries, qosMode, maxBatchSize, maxBatchTime, subName, clientID, addMessageIDInHeader, null, null); } public JMSBridgeImpl(final ConnectionFactoryFactory sourceCff, @@ -243,28 +223,8 @@ public final class JMSBridgeImpl implements JMSBridge final String clientID, final boolean addMessageIDInHeader, final MBeanServer mbeanServer, - final String objectName) - { - this(sourceCff, - targetCff, - sourceDestinationFactory, - targetDestinationFactory, - sourceUsername, - sourcePassword, - targetUsername, - targetPassword, - selector, - failureRetryInterval, - maxRetries, - qosMode, - maxBatchSize, - maxBatchTime, - subName, - clientID, - addMessageIDInHeader, - mbeanServer, - objectName, - DEFAULT_FAILOVER_TIMEOUT); + final String objectName) { + this(sourceCff, targetCff, sourceDestinationFactory, targetDestinationFactory, sourceUsername, sourcePassword, targetUsername, targetPassword, selector, failureRetryInterval, maxRetries, qosMode, maxBatchSize, maxBatchTime, subName, clientID, addMessageIDInHeader, mbeanServer, objectName, DEFAULT_FAILOVER_TIMEOUT); } public JMSBridgeImpl(final ConnectionFactoryFactory sourceCff, @@ -286,8 +246,7 @@ public final class JMSBridgeImpl implements JMSBridge final boolean addMessageIDInHeader, final MBeanServer mbeanServer, final String objectName, - final long failoverTimeout) - { + final long failoverTimeout) { this(); this.sourceCff = sourceCff; @@ -328,62 +287,51 @@ public final class JMSBridgeImpl implements JMSBridge checkParams(); - if (mbeanServer != null) - { - if (objectName != null) - { + if (mbeanServer != null) { + if (objectName != null) { this.mbeanServer = mbeanServer; - try - { + try { JMSBridgeControlImpl controlBean = new JMSBridgeControlImpl(this); this.objectName = ObjectName.getInstance(objectName); StandardMBean mbean = new StandardMBean(controlBean, JMSBridgeControl.class); mbeanServer.registerMBean(mbean, this.objectName); ActiveMQJMSBridgeLogger.LOGGER.debug("Registered JMSBridge instance as: " + this.objectName.getCanonicalName()); } - catch (Exception e) - { + catch (Exception e) { throw new IllegalStateException("Failed to register JMSBridge MBean", e); } } - else - { + else { throw new IllegalArgumentException("objectName is required when specifying an MBeanServer"); } } - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Created " + this); } } // ActiveMQComponent overrides -------------------------------------------------- - public synchronized void start() throws Exception - { - synchronized (stoppingGuard) - { + public synchronized void start() throws Exception { + synchronized (stoppingGuard) { stopping = false; } locateRecoveryRegistry(); - if (started) - { + if (started) { ActiveMQJMSBridgeLogger.LOGGER.errorBridgeAlreadyStarted(); return; } - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Starting " + this); } // bridge has been stopped and is restarted - if (executor.isShutdown()) - { + if (executor.isShutdown()) { executor = createExecutor(); } @@ -396,15 +344,12 @@ public final class JMSBridgeImpl implements JMSBridge boolean ok; // Check to see if the QoSMode requires a TM - if (qualityOfServiceMode.equals(QualityOfServiceMode.ONCE_AND_ONLY_ONCE) && sourceCff != targetCff) - { - if (tm == null) - { + if (qualityOfServiceMode.equals(QualityOfServiceMode.ONCE_AND_ONLY_ONCE) && sourceCff != targetCff) { + if (tm == null) { tm = ServiceUtils.getTransactionManager(); } - if (tm == null) - { + if (tm == null) { ActiveMQJMSBridgeLogger.LOGGER.jmsBridgeTransactionManagerMissing(qualityOfServiceMode); throw new RuntimeException(); } @@ -412,51 +357,42 @@ public final class JMSBridgeImpl implements JMSBridge // There may already be a JTA transaction associated to the thread Transaction toResume = null; - try - { + try { toResume = tm.suspend(); ok = setupJMSObjects(); } - finally - { - if (toResume != null) - { + finally { + if (toResume != null) { tm.resume(toResume); } } } - else - { + else { ok = setupJMSObjects(); } - if (ok) - { + if (ok) { connectedSource = true; connectedTarget = true; startSource(); } - else - { + else { ActiveMQJMSBridgeLogger.LOGGER.errorStartingBridge(); handleFailureOnStartup(); } } - private void startSource() throws JMSException - { + private void startSource() throws JMSException { // start the source connection sourceConn.start(); started = true; - if (maxBatchTime != -1) - { - if (JMSBridgeImpl.trace) - { + if (maxBatchTime != -1) { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Starting time checker thread"); } @@ -465,75 +401,60 @@ public final class JMSBridgeImpl implements JMSBridge executor.execute(timeChecker); batchExpiryTime = System.currentTimeMillis() + maxBatchTime; - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Started time checker thread"); } } executor.execute(new SourceReceiver()); - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Started " + this); } } - private void initPasswords() throws ActiveMQException - { - if (useMaskedPassword) - { + private void initPasswords() throws ActiveMQException { + if (useMaskedPassword) { SensitiveDataCodec codecInstance = new DefaultSensitiveStringCodec(); - if (passwordCodec != null) - { + if (passwordCodec != null) { codecInstance = PasswordMaskingUtil.getCodec(passwordCodec); } - try - { - if (this.sourcePassword != null) - { + try { + if (this.sourcePassword != null) { sourcePassword = codecInstance.decode(sourcePassword); } - if (this.targetPassword != null) - { + if (this.targetPassword != null) { targetPassword = codecInstance.decode(targetPassword); } } - catch (Exception e) - { + catch (Exception e) { throw ActiveMQJMSServerBundle.BUNDLE.errorDecodingPassword(e); } } } - public void stop() throws Exception - { - synchronized (stoppingGuard) - { - if (stopping) return; + public void stop() throws Exception { + synchronized (stoppingGuard) { + if (stopping) + return; stopping = true; } - synchronized (this) - { - if (JMSBridgeImpl.trace) - { + synchronized (this) { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Stopping " + this); } - if (!connectedSource && sourceConn != null) - { + if (!connectedSource && sourceConn != null) { sourceConn.close(); } - if (!connectedTarget && targetConn != null) - { + if (!connectedTarget && targetConn != null) { targetConn.close(); } - synchronized (lock) - { + synchronized (lock) { started = false; executor.shutdownNow(); @@ -541,86 +462,66 @@ public final class JMSBridgeImpl implements JMSBridge boolean ok = executor.awaitTermination(60, TimeUnit.SECONDS); - if (!ok) - { + if (!ok) { throw new Exception("fail to stop JMS Bridge"); } - if (tx != null) - { + if (tx != null) { // Terminate any transaction - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Rolling back remaining tx"); } - try - { + try { tx.rollback(); } - catch (Exception ignore) - { - if (JMSBridgeImpl.trace) - { + catch (Exception ignore) { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Failed to rollback", ignore); } } - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Rolled back remaining tx"); } } - try - { + try { sourceConn.close(); } - catch (Exception ignore) - { - if (JMSBridgeImpl.trace) - { + catch (Exception ignore) { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Failed to close source conn", ignore); } } - if (targetConn != null) - { - try - { + if (targetConn != null) { + try { targetConn.close(); } - catch (Exception ignore) - { - if (JMSBridgeImpl.trace) - { + catch (Exception ignore) { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Failed to close target conn", ignore); } } } - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Stopped " + this); } } } - public synchronized boolean isStarted() - { + public synchronized boolean isStarted() { return started; } - public void destroy() - { - if (mbeanServer != null && objectName != null) - { - try - { + public void destroy() { + if (mbeanServer != null && objectName != null) { + try { mbeanServer.unregisterMBean(objectName); } - catch (Exception e) - { + catch (Exception e) { ActiveMQJMSBridgeLogger.LOGGER.errorUnregisteringBridge(objectName); } } @@ -628,261 +529,217 @@ public final class JMSBridgeImpl implements JMSBridge // JMSBridge implementation ------------------------------------------------------------ - public synchronized void pause() throws Exception - { - if (JMSBridgeImpl.trace) - { + public synchronized void pause() throws Exception { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Pausing " + this); } - synchronized (lock) - { + synchronized (lock) { paused = true; sourceConn.stop(); } - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Paused " + this); } } - public synchronized void resume() throws Exception - { - if (JMSBridgeImpl.trace) - { + public synchronized void resume() throws Exception { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Resuming " + this); } - synchronized (lock) - { + synchronized (lock) { paused = false; sourceConn.start(); } - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Resumed " + this); } } - public DestinationFactory getSourceDestinationFactory() - { + public DestinationFactory getSourceDestinationFactory() { return sourceDestinationFactory; } - public void setSourceDestinationFactory(final DestinationFactory dest) - { + public void setSourceDestinationFactory(final DestinationFactory dest) { checkBridgeNotStarted(); JMSBridgeImpl.checkNotNull(dest, "TargetDestinationFactory"); sourceDestinationFactory = dest; } - public DestinationFactory getTargetDestinationFactory() - { + public DestinationFactory getTargetDestinationFactory() { return targetDestinationFactory; } - public void setTargetDestinationFactory(final DestinationFactory dest) - { + public void setTargetDestinationFactory(final DestinationFactory dest) { checkBridgeNotStarted(); JMSBridgeImpl.checkNotNull(dest, "TargetDestinationFactory"); targetDestinationFactory = dest; } - public synchronized String getSourceUsername() - { + public synchronized String getSourceUsername() { return sourceUsername; } - public synchronized void setSourceUsername(final String name) - { + public synchronized void setSourceUsername(final String name) { checkBridgeNotStarted(); sourceUsername = name; } - public synchronized String getSourcePassword() - { + public synchronized String getSourcePassword() { return sourcePassword; } - public synchronized void setSourcePassword(final String pwd) - { + public synchronized void setSourcePassword(final String pwd) { checkBridgeNotStarted(); sourcePassword = pwd; } - public synchronized String getTargetUsername() - { + public synchronized String getTargetUsername() { return targetUsername; } - public synchronized void setTargetUsername(final String name) - { + public synchronized void setTargetUsername(final String name) { checkBridgeNotStarted(); targetUsername = name; } - public synchronized String getTargetPassword() - { + public synchronized String getTargetPassword() { return targetPassword; } - public synchronized void setTargetPassword(final String pwd) - { + public synchronized void setTargetPassword(final String pwd) { checkBridgeNotStarted(); targetPassword = pwd; } - public synchronized String getSelector() - { + public synchronized String getSelector() { return selector; } - public synchronized void setSelector(final String selector) - { + public synchronized void setSelector(final String selector) { checkBridgeNotStarted(); this.selector = selector; } - public synchronized long getFailureRetryInterval() - { + public synchronized long getFailureRetryInterval() { return failureRetryInterval; } - public synchronized void setFailureRetryInterval(final long interval) - { + public synchronized void setFailureRetryInterval(final long interval) { checkBridgeNotStarted(); - if (interval < 1) - { + if (interval < 1) { throw new IllegalArgumentException("FailureRetryInterval must be >= 1"); } failureRetryInterval = interval; } - public synchronized int getMaxRetries() - { + public synchronized int getMaxRetries() { return maxRetries; } - public synchronized void setMaxRetries(final int retries) - { + public synchronized void setMaxRetries(final int retries) { checkBridgeNotStarted(); JMSBridgeImpl.checkValidValue(retries, "MaxRetries"); maxRetries = retries; } - public synchronized QualityOfServiceMode getQualityOfServiceMode() - { + public synchronized QualityOfServiceMode getQualityOfServiceMode() { return qualityOfServiceMode; } - public synchronized void setQualityOfServiceMode(final QualityOfServiceMode mode) - { + public synchronized void setQualityOfServiceMode(final QualityOfServiceMode mode) { checkBridgeNotStarted(); JMSBridgeImpl.checkNotNull(mode, "QualityOfServiceMode"); qualityOfServiceMode = mode; } - public synchronized int getMaxBatchSize() - { + public synchronized int getMaxBatchSize() { return maxBatchSize; } - public synchronized void setMaxBatchSize(final int size) - { + public synchronized void setMaxBatchSize(final int size) { checkBridgeNotStarted(); JMSBridgeImpl.checkMaxBatchSize(size); maxBatchSize = size; } - public synchronized long getMaxBatchTime() - { + public synchronized long getMaxBatchTime() { return maxBatchTime; } - public synchronized void setMaxBatchTime(final long time) - { + public synchronized void setMaxBatchTime(final long time) { checkBridgeNotStarted(); JMSBridgeImpl.checkValidValue(time, "MaxBatchTime"); maxBatchTime = time; } - public synchronized String getSubscriptionName() - { + public synchronized String getSubscriptionName() { return subName; } - public synchronized void setSubscriptionName(final String subname) - { + public synchronized void setSubscriptionName(final String subname) { checkBridgeNotStarted(); subName = subname; } - public synchronized String getClientID() - { + public synchronized String getClientID() { return clientID; } - public synchronized void setClientID(final String clientID) - { + public synchronized void setClientID(final String clientID) { checkBridgeNotStarted(); this.clientID = clientID; } - public boolean isAddMessageIDInHeader() - { + public boolean isAddMessageIDInHeader() { return addMessageIDInHeader; } - public void setAddMessageIDInHeader(final boolean value) - { + public void setAddMessageIDInHeader(final boolean value) { addMessageIDInHeader = value; } - public synchronized boolean isPaused() - { + public synchronized boolean isPaused() { return paused; } - public synchronized boolean isFailed() - { + public synchronized boolean isFailed() { return failed; } - public synchronized void setSourceConnectionFactoryFactory(final ConnectionFactoryFactory cff) - { + public synchronized void setSourceConnectionFactoryFactory(final ConnectionFactoryFactory cff) { checkBridgeNotStarted(); JMSBridgeImpl.checkNotNull(cff, "SourceConnectionFactoryFactory"); sourceCff = cff; } - public synchronized void setTargetConnectionFactoryFactory(final ConnectionFactoryFactory cff) - { + public synchronized void setTargetConnectionFactoryFactory(final ConnectionFactoryFactory cff) { checkBridgeNotStarted(); JMSBridgeImpl.checkNotNull(cff, "TargetConnectionFactoryFactory"); targetCff = cff; } - public void setTransactionManager(final TransactionManager tm) - { + public void setTransactionManager(final TransactionManager tm) { this.tm = tm; } @@ -890,16 +747,14 @@ public final class JMSBridgeImpl implements JMSBridge // Private ------------------------------------------------------------------- - private synchronized void checkParams() - { + private synchronized void checkParams() { checkNotNull(sourceCff, "sourceCff"); checkNotNull(targetCff, "targetCff"); checkNotNull(sourceDestinationFactory, "sourceDestinationFactory"); checkNotNull(targetDestinationFactory, "targetDestinationFactory"); checkValidValue(failureRetryInterval, "failureRetryInterval"); checkValidValue(maxRetries, "maxRetries"); - if (failureRetryInterval == -1 && maxRetries > 0) - { + if (failureRetryInterval == -1 && maxRetries > 0) { throw new IllegalArgumentException("If failureRetryInterval == -1 maxRetries must be set to -1"); } checkMaxBatchSize(maxBatchSize); @@ -912,10 +767,8 @@ public final class JMSBridgeImpl implements JMSBridge * * @throws IllegalArgumentException if the object is null */ - private static void checkNotNull(final Object obj, final String name) - { - if (obj == null) - { + private static void checkNotNull(final Object obj, final String name) { + if (obj == null) { throw new IllegalArgumentException(name + " cannot be null"); } } @@ -925,10 +778,8 @@ public final class JMSBridgeImpl implements JMSBridge * * @throws IllegalStateException if the bridge is started */ - private void checkBridgeNotStarted() - { - if (started) - { + private void checkBridgeNotStarted() { + if (started) { throw new IllegalStateException("Cannot set bridge attributes while it is started"); } } @@ -938,26 +789,20 @@ public final class JMSBridgeImpl implements JMSBridge * * @throws IllegalArgumentException if the value is not valid */ - private static void checkValidValue(final long value, final String name) - { - if (!(value == -1 || value > 0)) - { + private static void checkValidValue(final long value, final String name) { + if (!(value == -1 || value > 0)) { throw new IllegalArgumentException(name + " must be > 0 or -1"); } } - private static void checkMaxBatchSize(final int size) - { - if (!(size >= 1)) - { + private static void checkMaxBatchSize(final int size) { + if (!(size >= 1)) { throw new IllegalArgumentException("maxBatchSize must be >= 1"); } } - private void enlistResources(final Transaction tx) throws Exception - { - if (JMSBridgeImpl.trace) - { + private void enlistResources(final Transaction tx) throws Exception { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Enlisting resources in tx"); } @@ -969,62 +814,49 @@ public final class JMSBridgeImpl implements JMSBridge tx.enlistResource(resDest); - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Enlisted resources in tx"); } } - private void delistResources(final Transaction tx) - { - if (JMSBridgeImpl.trace) - { + private void delistResources(final Transaction tx) { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Delisting resources from tx"); } XAResource resSource = ((XASession) sourceSession).getXAResource(); - try - { + try { tx.delistResource(resSource, XAResource.TMSUCCESS); } - catch (Exception e) - { - if (JMSBridgeImpl.trace) - { + catch (Exception e) { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Failed to delist source resource", e); } } XAResource resDest = ((XASession) targetSession).getXAResource(); - try - { + try { tx.delistResource(resDest, XAResource.TMSUCCESS); } - catch (Exception e) - { - if (JMSBridgeImpl.trace) - { + catch (Exception e) { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Failed to delist target resource", e); } } - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Delisted resources from tx"); } } - private Transaction startTx() throws Exception - { - if (JMSBridgeImpl.trace) - { + private Transaction startTx() throws Exception { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Starting JTA transaction"); } - if (tm == null) - { + if (tm == null) { tm = ServiceUtils.getTransactionManager(); } @@ -1041,88 +873,72 @@ public final class JMSBridgeImpl implements JMSBridge tm.suspend(); - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Started JTA transaction"); } return tx; } - private Connection createConnection(final String username, final String password, + private Connection createConnection(final String username, + final String password, final ConnectionFactoryFactory cff, final String clientID, final boolean isXA, - boolean isSource) throws Exception - { + boolean isSource) throws Exception { Connection conn; Object cf = cff.createConnectionFactory(); - if (cf instanceof ActiveMQConnectionFactory && registry != null) - { + if (cf instanceof ActiveMQConnectionFactory && registry != null) { registry.register(XARecoveryConfig.newConfig((ActiveMQConnectionFactory) cf, username, password)); } - if (qualityOfServiceMode == QualityOfServiceMode.ONCE_AND_ONLY_ONCE && !(cf instanceof XAConnectionFactory)) - { + if (qualityOfServiceMode == QualityOfServiceMode.ONCE_AND_ONLY_ONCE && !(cf instanceof XAConnectionFactory)) { throw new IllegalArgumentException("Connection factory must be XAConnectionFactory"); } - if (username == null) - { - if (isXA) - { - if (JMSBridgeImpl.trace) - { + if (username == null) { + if (isXA) { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Creating an XA connection"); } conn = ((XAConnectionFactory) cf).createXAConnection(); } - else - { - if (JMSBridgeImpl.trace) - { + else { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Creating a non XA connection"); } conn = ((ConnectionFactory) cf).createConnection(); } } - else - { - if (isXA) - { - if (JMSBridgeImpl.trace) - { + else { + if (isXA) { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Creating an XA connection"); } conn = ((XAConnectionFactory) cf).createXAConnection(username, password); } - else - { - if (JMSBridgeImpl.trace) - { + else { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Creating a non XA connection"); } conn = ((ConnectionFactory) cf).createConnection(username, password); } } - if (clientID != null) - { + if (clientID != null) { conn.setClientID(clientID); } boolean ha = false; BridgeFailoverListener failoverListener = null; - if (conn instanceof ActiveMQConnection) - { + if (conn instanceof ActiveMQConnection) { ActiveMQConnectionFactory activeMQCF = (ActiveMQConnectionFactory) cf; ha = activeMQCF.isHA(); - if (ha) - { + if (ha) { ActiveMQConnection activeMQConn = (ActiveMQConnection) conn; failoverListener = new BridgeFailoverListener(isSource); activeMQConn.setFailoverListener(failoverListener); @@ -1167,28 +983,22 @@ public final class JMSBridgeImpl implements JMSBridge * *before* the batch has been sent * */ - private boolean setupJMSObjects() - { - try - { - if (sourceCff == targetCff) - { + private boolean setupJMSObjects() { + try { + if (sourceCff == targetCff) { // Source and target destinations are on the server - we can get once and only once // just using a local transacted session // everything becomes once and only once forwardMode = JMSBridgeImpl.FORWARD_MODE_LOCALTX; } - else - { + else { // Different servers - if (qualityOfServiceMode == QualityOfServiceMode.ONCE_AND_ONLY_ONCE) - { + if (qualityOfServiceMode == QualityOfServiceMode.ONCE_AND_ONLY_ONCE) { // Use XA forwardMode = JMSBridgeImpl.FORWARD_MODE_XA; } - else - { + else { forwardMode = JMSBridgeImpl.FORWARD_MODE_NONTX; } } @@ -1199,66 +1009,52 @@ public final class JMSBridgeImpl implements JMSBridge targetDestination = targetDestinationFactory.createDestination(); // bridging on the same server - if (forwardMode == JMSBridgeImpl.FORWARD_MODE_LOCALTX) - { + if (forwardMode == JMSBridgeImpl.FORWARD_MODE_LOCALTX) { // We simply use a single local transacted session for consuming and sending sourceConn = createConnection(sourceUsername, sourcePassword, sourceCff, clientID, false, true); sourceSession = sourceConn.createSession(true, Session.SESSION_TRANSACTED); } - else // bridging across different servers - { + else { // bridging across different servers // QoS = ONCE_AND_ONLY_ONCE - if (forwardMode == JMSBridgeImpl.FORWARD_MODE_XA) - { + if (forwardMode == JMSBridgeImpl.FORWARD_MODE_XA) { // Create an XASession for consuming from the source - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Creating XA source session"); } sourceConn = createConnection(sourceUsername, sourcePassword, sourceCff, clientID, true, true); sourceSession = ((XAConnection) sourceConn).createXASession(); } - else // QoS = DUPLICATES_OK || AT_MOST_ONCE - { - if (JMSBridgeImpl.trace) - { + else { // QoS = DUPLICATES_OK || AT_MOST_ONCE + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Creating non XA source session"); } sourceConn = createConnection(sourceUsername, sourcePassword, sourceCff, clientID, false, true); - if (qualityOfServiceMode == QualityOfServiceMode.AT_MOST_ONCE && maxBatchSize == 1) - { + if (qualityOfServiceMode == QualityOfServiceMode.AT_MOST_ONCE && maxBatchSize == 1) { sourceSession = sourceConn.createSession(false, Session.AUTO_ACKNOWLEDGE); } - else - { + else { sourceSession = sourceConn.createSession(false, Session.CLIENT_ACKNOWLEDGE); } } } - if (subName == null) - { - if (selector == null) - { + if (subName == null) { + if (selector == null) { sourceConsumer = sourceSession.createConsumer(sourceDestination); } - else - { + else { sourceConsumer = sourceSession.createConsumer(sourceDestination, selector, false); } } - else - { + else { // Durable subscription - if (selector == null) - { + if (selector == null) { sourceConsumer = sourceSession.createDurableSubscriber((Topic) sourceDestination, subName); } - else - { + else { sourceConsumer = sourceSession.createDurableSubscriber((Topic) sourceDestination, subName, selector, false); } } @@ -1266,18 +1062,14 @@ public final class JMSBridgeImpl implements JMSBridge // Now the sending session // bridging on the same server - if (forwardMode == JMSBridgeImpl.FORWARD_MODE_LOCALTX) - { + if (forwardMode == JMSBridgeImpl.FORWARD_MODE_LOCALTX) { targetConn = sourceConn; targetSession = sourceSession; } - else // bridging across different servers - { + else { // bridging across different servers // QoS = ONCE_AND_ONLY_ONCE - if (forwardMode == JMSBridgeImpl.FORWARD_MODE_XA) - { - if (JMSBridgeImpl.trace) - { + if (forwardMode == JMSBridgeImpl.FORWARD_MODE_XA) { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Creating XA dest session"); } @@ -1287,10 +1079,8 @@ public final class JMSBridgeImpl implements JMSBridge targetSession = ((XAConnection) targetConn).createXASession(); } - else // QoS = DUPLICATES_OK || AT_MOST_ONCE - { - if (JMSBridgeImpl.trace) - { + else { // QoS = DUPLICATES_OK || AT_MOST_ONCE + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Creating non XA dest session"); } @@ -1302,15 +1092,12 @@ public final class JMSBridgeImpl implements JMSBridge targetConn = createConnection(targetUsername, targetPassword, targetCff, null, false, false); - targetSession = targetConn.createSession(transacted, transacted ? Session.SESSION_TRANSACTED - : Session.AUTO_ACKNOWLEDGE); + targetSession = targetConn.createSession(transacted, transacted ? Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE); } } - if (forwardMode == JMSBridgeImpl.FORWARD_MODE_XA) - { - if (JMSBridgeImpl.trace) - { + if (forwardMode == JMSBridgeImpl.FORWARD_MODE_XA) { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Starting JTA transaction"); } @@ -1323,8 +1110,7 @@ public final class JMSBridgeImpl implements JMSBridge return true; } - catch (Exception e) - { + catch (Exception e) { // We shouldn't log this, as it's expected when trying to connect when target/source is not available // If this fails we should attempt to cleanup or we might end up in some weird state @@ -1338,113 +1124,86 @@ public final class JMSBridgeImpl implements JMSBridge } } - private void cleanup() - { + private void cleanup() { // Stop the source connection - try - { + try { sourceConn.stop(); } - catch (Throwable ignore) - { - if (JMSBridgeImpl.trace) - { + catch (Throwable ignore) { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Failed to stop source connection", ignore); } } - if (tx != null) - { - try - { + if (tx != null) { + try { delistResources(tx); } - catch (Throwable ignore) - { - if (JMSBridgeImpl.trace) - { + catch (Throwable ignore) { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Failed to delist resources", ignore); } } - try - { + try { // Terminate the tx tx.rollback(); } - catch (Throwable ignore) - { - if (JMSBridgeImpl.trace) - { + catch (Throwable ignore) { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Failed to rollback", ignore); } } } // Close the old objects - try - { + try { sourceConn.close(); } - catch (Throwable ignore) - { - if (JMSBridgeImpl.trace) - { + catch (Throwable ignore) { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Failed to close source connection", ignore); } } - try - { - if (targetConn != null) - { + try { + if (targetConn != null) { targetConn.close(); } } - catch (Throwable ignore) - { - if (JMSBridgeImpl.trace) - { + catch (Throwable ignore) { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Failed to close target connection", ignore); } } } - private void pause(final long interval) - { + private void pause(final long interval) { long start = System.currentTimeMillis(); - while (System.currentTimeMillis() - start < failureRetryInterval) - { - try - { + while (System.currentTimeMillis() - start < failureRetryInterval) { + try { Thread.sleep(failureRetryInterval); } - catch (InterruptedException ex) - { + catch (InterruptedException ex) { } } } - private boolean setupJMSObjectsWithRetry() - { - if (JMSBridgeImpl.trace) - { + private boolean setupJMSObjectsWithRetry() { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Setting up connections"); } int count = 0; - while (true && !stopping) - { + while (true && !stopping) { boolean ok = setupJMSObjects(); - if (ok) - { + if (ok) { return true; } count++; - if (maxRetries != -1 && count == maxRetries) - { + if (maxRetries != -1 && count == maxRetries) { break; } @@ -1457,174 +1216,138 @@ public final class JMSBridgeImpl implements JMSBridge return false; } - private void sendBatch() - { - if (JMSBridgeImpl.trace) - { + private void sendBatch() { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Sending batch of " + messages.size() + " messages"); } - if (paused) - { + if (paused) { // Don't send now - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Paused, so not sending now"); } return; } - if (forwardMode == JMSBridgeImpl.FORWARD_MODE_LOCALTX) - { + if (forwardMode == JMSBridgeImpl.FORWARD_MODE_LOCALTX) { sendBatchLocalTx(); } - else if (forwardMode == JMSBridgeImpl.FORWARD_MODE_XA) - { + else if (forwardMode == JMSBridgeImpl.FORWARD_MODE_XA) { sendBatchXA(); } - else - { + else { sendBatchNonTransacted(); } } - private void sendBatchNonTransacted() - { - try - { - if (qualityOfServiceMode == QualityOfServiceMode.ONCE_AND_ONLY_ONCE || - (qualityOfServiceMode == QualityOfServiceMode.AT_MOST_ONCE && maxBatchSize > 1)) - { + private void sendBatchNonTransacted() { + try { + if (qualityOfServiceMode == QualityOfServiceMode.ONCE_AND_ONLY_ONCE || (qualityOfServiceMode == QualityOfServiceMode.AT_MOST_ONCE && maxBatchSize > 1)) { // We client ack before sending - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Client acking source session"); } messages.getLast().acknowledge(); - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Client acked source session"); } } boolean exHappened; - do - { + do { exHappened = false; - try - { + try { sendMessages(); } - catch (TransactionRolledbackException e) - { + catch (TransactionRolledbackException e) { ActiveMQJMSBridgeLogger.LOGGER.warn(e.getMessage() + ", retrying TX", e); exHappened = true; } - } - while (exHappened); + } while (exHappened); - if (maxBatchSize > 1) - { + if (maxBatchSize > 1) { // The sending session is transacted - we need to commit it - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Committing target session"); } targetSession.commit(); - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Committed target session"); } } - if (qualityOfServiceMode == QualityOfServiceMode.DUPLICATES_OK) - { + if (qualityOfServiceMode == QualityOfServiceMode.DUPLICATES_OK) { // We client ack after sending // Note we could actually use Session.DUPS_OK_ACKNOWLEDGE here // For a slightly less strong delivery guarantee - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Client acking source session"); } messages.getLast().acknowledge(); - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Client acked source session"); } } } - catch (Exception e) - { - if (!stopping) - { + catch (Exception e) { + if (!stopping) { ActiveMQJMSBridgeLogger.LOGGER.bridgeAckError(e); } // We don't call failure otherwise failover would be broken with ActiveMQ // We let the ExceptionListener to deal with failures - if (connectedSource) - { - try - { + if (connectedSource) { + try { sourceSession.recover(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } } - finally - { + finally { // Clear the messages messages.clear(); } } - private void sendBatchXA() - { - try - { + private void sendBatchXA() { + try { sendMessages(); // Commit the JTA transaction and start another delistResources(tx); - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Committing JTA transaction"); } tx.commit(); - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Committed JTA transaction"); } } - catch (Exception e) - { - try - { + catch (Exception e) { + try { // we call this just in case there is a failure other than failover tx.rollback(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } ActiveMQJMSBridgeLogger.LOGGER.bridgeAckError(e); @@ -1634,10 +1357,8 @@ public final class JMSBridgeImpl implements JMSBridge //will be done through exception listener. //handleFailureOnSend(); } - finally - { - try - { + finally { + try { tx = startTx(); enlistResources(tx); @@ -1646,8 +1367,7 @@ public final class JMSBridgeImpl implements JMSBridge messages.clear(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQJMSBridgeLogger.LOGGER.bridgeAckError(e); handleFailureOnSend(); @@ -1655,69 +1375,55 @@ public final class JMSBridgeImpl implements JMSBridge } } - private void sendBatchLocalTx() - { - try - { + private void sendBatchLocalTx() { + try { sendMessages(); - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Committing source session"); } sourceSession.commit(); - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Committed source session"); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQJMSBridgeLogger.LOGGER.bridgeAckError(e); - try - { + try { sourceSession.rollback(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } - try - { + try { targetSession.rollback(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } // We don't call failure here, we let the exception listener to deal with it } - finally - { + finally { messages.clear(); } } - private void sendMessages() throws Exception - { + private void sendMessages() throws Exception { Iterator iter = messages.iterator(); Message msg = null; - while (iter.hasNext()) - { + while (iter.hasNext()) { msg = iter.next(); - if (addMessageIDInHeader) - { + if (addMessageIDInHeader) { addMessageIDInHeader(msg); } - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Sending message " + msg); } @@ -1725,37 +1431,31 @@ public final class JMSBridgeImpl implements JMSBridge long timeToLive = msg.getJMSExpiration(); - if (timeToLive != 0) - { + if (timeToLive != 0) { timeToLive -= System.currentTimeMillis(); - if (timeToLive <= 0) - { + if (timeToLive <= 0) { timeToLive = 1; // Should have already expired - set to 1 so it expires when it is consumed or delivered } } targetProducer.send(targetDestination, msg, msg.getJMSDeliveryMode(), msg.getJMSPriority(), timeToLive); - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Sent message " + msg); } } } - private void handleFailureOnSend() - { + private void handleFailureOnSend() { handleFailure(new FailureHandler()); } - private void handleFailureOnStartup() - { + private void handleFailureOnStartup() { handleFailure(new StartupFailureHandler()); } - private void handleFailure(final Runnable failureHandler) - { + private void handleFailure(final Runnable failureHandler) { failed = true; // Failure must be handled on a separate thread to the calling thread (either onMessage or start). @@ -1765,16 +1465,14 @@ public final class JMSBridgeImpl implements JMSBridge executor.execute(failureHandler); } - private void addMessageIDInHeader(final Message msg) throws Exception - { + private void addMessageIDInHeader(final Message msg) throws Exception { // We concatenate the old message id as a header in the message // This allows the target to then use this as the JMSCorrelationID of any response message // thus enabling a distributed request-response pattern. // Each bridge (if there are more than one) in the chain can concatenate the message id // So in the case of multiple bridges having routed the message this can be used in a multi-hop // distributed request/response - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Adding old message id in Message header"); } @@ -1784,12 +1482,10 @@ public final class JMSBridgeImpl implements JMSBridge val = msg.getStringProperty(ActiveMQJMSConstants.AMQ_MESSAGING_BRIDGE_MESSAGE_ID_LIST); - if (val == null) - { + if (val == null) { val = msg.getJMSMessageID(); } - else - { + else { StringBuffer sb = new StringBuffer(val); sb.append(",").append(msg.getJMSMessageID()); @@ -1805,19 +1501,16 @@ public final class JMSBridgeImpl implements JMSBridge * calling clearProperties, so we need to save and re-add all the old properties so we * don't lose them!! */ - private static void copyProperties(final Message msg) throws JMSException - { + private static void copyProperties(final Message msg) throws JMSException { @SuppressWarnings("unchecked") Enumeration en = msg.getPropertyNames(); Map oldProps = null; - while (en.hasMoreElements()) - { + while (en.hasMoreElements()) { String propName = en.nextElement(); - if (oldProps == null) - { + if (oldProps == null) { oldProps = new HashMap(); } @@ -1826,25 +1519,21 @@ public final class JMSBridgeImpl implements JMSBridge msg.clearProperties(); - if (oldProps != null) - { + if (oldProps != null) { Iterator> oldPropsIter = oldProps.entrySet().iterator(); - while (oldPropsIter.hasNext()) - { + while (oldPropsIter.hasNext()) { Entry entry = oldPropsIter.next(); String propName = entry.getKey(); Object val = entry.getValue(); - if (val instanceof byte[] == false) - { + if (val instanceof byte[] == false) { //Can't set byte[] array props through the JMS API - if we're bridging an ActiveMQ Artemis message it might have such props msg.setObjectProperty(propName, entry.getValue()); } - else if (msg instanceof ActiveMQMessage) - { + else if (msg instanceof ActiveMQMessage) { ((ActiveMQMessage) msg).getCoreMessage().putBytesProperty(propName, (byte[]) val); } } @@ -1855,8 +1544,7 @@ public final class JMSBridgeImpl implements JMSBridge * Creates a 3-sized thread pool executor (1 thread for the sourceReceiver, 1 for the timeChecker * and 1 for the eventual failureHandler) */ - private ExecutorService createExecutor() - { + private ExecutorService createExecutor() { return Executors.newFixedThreadPool(3); } @@ -1867,35 +1555,27 @@ public final class JMSBridgeImpl implements JMSBridge * to ensure that message delivery does not happen concurrently with * transaction enlistment of the XAResource (see HORNETQ-27) */ - private final class SourceReceiver extends Thread - { - SourceReceiver() - { + private final class SourceReceiver extends Thread { + + SourceReceiver() { super("jmsbridge-source-receiver-thread"); } @Override - @SuppressWarnings("WaitNotInLoop") // both lock.wait(..) either returns, throws or continue, thus avoiding spurious wakes - public void run() - { - while (started) - { - if (stopping) - { + @SuppressWarnings("WaitNotInLoop") + // both lock.wait(..) either returns, throws or continue, thus avoiding spurious wakes + public void run() { + while (started) { + if (stopping) { return; } - synchronized (lock) - { - if (paused || failed) - { - try - { + synchronized (lock) { + if (paused || failed) { + try { lock.wait(500); } - catch (InterruptedException e) - { - if (stopping) - { + catch (InterruptedException e) { + if (stopping) { return; } throw new ActiveMQInterruptedException(e); @@ -1904,39 +1584,30 @@ public final class JMSBridgeImpl implements JMSBridge } Message msg = null; - try - { + try { msg = sourceConsumer.receive(1000); - if (msg instanceof ActiveMQMessage) - { + if (msg instanceof ActiveMQMessage) { // We need to check the buffer mainly in the case of LargeMessages // As we need to reconstruct the buffer before resending the message ((ActiveMQMessage) msg).checkBuffer(); } } - catch (JMSException jmse) - { - if (JMSBridgeImpl.trace) - { + catch (JMSException jmse) { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace(this + " exception while receiving a message", jmse); } } - if (msg == null) - { - try - { + if (msg == null) { + try { lock.wait(500); } - catch (InterruptedException e) - { - if (JMSBridgeImpl.trace) - { + catch (InterruptedException e) { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace(this + " thread was interrupted"); } - if (stopping) - { + if (stopping) { return; } throw new ActiveMQInterruptedException(e); @@ -1944,8 +1615,7 @@ public final class JMSBridgeImpl implements JMSBridge continue; } - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace(this + " received message " + msg); } @@ -1953,22 +1623,18 @@ public final class JMSBridgeImpl implements JMSBridge batchExpiryTime = System.currentTimeMillis() + maxBatchTime; - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace(this + " rescheduled batchExpiryTime to " + batchExpiryTime); } - if (maxBatchSize != -1 && messages.size() >= maxBatchSize) - { - if (JMSBridgeImpl.trace) - { + if (maxBatchSize != -1 && messages.size() >= maxBatchSize) { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace(this + " maxBatchSize has been reached so sending batch"); } sendBatch(); - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace(this + " sent batch"); } } @@ -1977,55 +1643,45 @@ public final class JMSBridgeImpl implements JMSBridge } } - private class FailureHandler implements Runnable - { + private class FailureHandler implements Runnable { + /** * Start the source connection - note the source connection must not be started before * otherwise messages will be received and ignored */ - protected void startSourceConnection() - { - try - { + protected void startSourceConnection() { + try { sourceConn.start(); } - catch (JMSException e) - { + catch (JMSException e) { ActiveMQJMSBridgeLogger.LOGGER.jmsBridgeSrcConnectError(e); } } - protected void succeeded() - { + protected void succeeded() { ActiveMQJMSBridgeLogger.LOGGER.bridgeReconnected(); connectedSource = true; connectedTarget = true; - synchronized (lock) - { + synchronized (lock) { failed = false; startSourceConnection(); } } - protected void failed() - { + protected void failed() { // We haven't managed to recreate connections or maxRetries = 0 ActiveMQJMSBridgeLogger.LOGGER.errorConnectingBridge(); - try - { + try { stop(); } - catch (Exception ignore) - { + catch (Exception ignore) { } } - public void run() - { - if (JMSBridgeImpl.trace) - { + public void run() { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Failure handler running"); } @@ -2036,8 +1692,7 @@ public final class JMSBridgeImpl implements JMSBridge boolean ok = false; - if (maxRetries > 0 || maxRetries == -1) - { + if (maxRetries > 0 || maxRetries == -1) { ActiveMQJMSBridgeLogger.LOGGER.bridgeRetry(failureRetryInterval); pause(failureRetryInterval); @@ -2046,34 +1701,29 @@ public final class JMSBridgeImpl implements JMSBridge ok = setupJMSObjectsWithRetry(); } - if (!ok) - { + if (!ok) { failed(); } - else - { + else { succeeded(); } } } - private class StartupFailureHandler extends FailureHandler - { + private class StartupFailureHandler extends FailureHandler { + @Override - protected void failed() - { + protected void failed() { // Don't call super ActiveMQJMSBridgeLogger.LOGGER.bridgeNotStarted(); } @Override - protected void succeeded() - { + protected void succeeded() { // Don't call super - a bit ugly in this case but better than taking the lock twice. ActiveMQJMSBridgeLogger.LOGGER.bridgeConnected(); - synchronized (lock) - { + synchronized (lock) { connectedSource = true; connectedTarget = true; @@ -2083,53 +1733,41 @@ public final class JMSBridgeImpl implements JMSBridge // Start the source connection - note the source connection must not be started before // otherwise messages will be received and ignored - try - { + try { startSource(); } - catch (JMSException e) - { + catch (JMSException e) { ActiveMQJMSBridgeLogger.LOGGER.jmsBridgeSrcConnectError(e); } } } } - private class BatchTimeChecker implements Runnable - { - public void run() - { - if (JMSBridgeImpl.trace) - { + private class BatchTimeChecker implements Runnable { + + public void run() { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace(this + " running"); } - synchronized (lock) - { - while (started) - { + synchronized (lock) { + while (started) { long toWait = batchExpiryTime - System.currentTimeMillis(); - if (toWait <= 0) - { - if (JMSBridgeImpl.trace) - { + if (toWait <= 0) { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace(this + " waited enough"); } - synchronized (lock) - { - if (!failed && !messages.isEmpty()) - { - if (JMSBridgeImpl.trace) - { + synchronized (lock) { + if (!failed && !messages.isEmpty()) { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace(this + " got some messages so sending batch"); } sendBatch(); - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace(this + " sent batch"); } } @@ -2137,30 +1775,23 @@ public final class JMSBridgeImpl implements JMSBridge batchExpiryTime = System.currentTimeMillis() + maxBatchTime; } - else - { - try - { - if (JMSBridgeImpl.trace) - { + else { + try { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace(this + " waiting for " + toWait); } lock.wait(toWait); - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace(this + " woke up"); } } - catch (InterruptedException e) - { - if (JMSBridgeImpl.trace) - { + catch (InterruptedException e) { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace(this + " thread was interrupted"); } - if (stopping) - { + if (stopping) { return; } throw new ActiveMQInterruptedException(e); @@ -2172,60 +1803,48 @@ public final class JMSBridgeImpl implements JMSBridge } } - private class BridgeExceptionListener implements ExceptionListener - { + private class BridgeExceptionListener implements ExceptionListener { + boolean ha; BridgeFailoverListener failoverListener; private final boolean isSource; - public BridgeExceptionListener(boolean ha, BridgeFailoverListener failoverListener, boolean isSource) - { + public BridgeExceptionListener(boolean ha, BridgeFailoverListener failoverListener, boolean isSource) { this.ha = ha; this.failoverListener = failoverListener; this.isSource = isSource; } - public void onException(final JMSException e) - { - if (stopping) - { + public void onException(final JMSException e) { + if (stopping) { return; } ActiveMQJMSBridgeLogger.LOGGER.bridgeFailure(e); - if (isSource) - { + if (isSource) { connectedSource = false; } - else - { + else { connectedTarget = false; } - synchronized (lock) - { - if (stopping) - { + synchronized (lock) { + if (stopping) { return; } - if (failed) - { + if (failed) { // The failure has already been detected and is being handled - if (JMSBridgeImpl.trace) - { + if (JMSBridgeImpl.trace) { ActiveMQJMSBridgeLogger.LOGGER.trace("Failure recovery already in progress"); } } - else - { + else { boolean shouldHandleFailure = true; - if (ha) - { + if (ha) { //make sure failover happened shouldHandleFailure = !failoverListener.waitForFailover(); } - if (shouldHandleFailure) - { + if (shouldHandleFailure) { handleFailure(new FailureHandler()); } } @@ -2233,82 +1852,63 @@ public final class JMSBridgeImpl implements JMSBridge } } - - private void locateRecoveryRegistry() - { - if (registry == null) - { - for (String locatorClasse : RESOURCE_RECOVERY_CLASS_NAMES) - { - try - { + private void locateRecoveryRegistry() { + if (registry == null) { + for (String locatorClasse : RESOURCE_RECOVERY_CLASS_NAMES) { + try { ServiceLoader sl = ServiceLoader.load(ActiveMQRegistry.class); - if (sl.iterator().hasNext()) - { + if (sl.iterator().hasNext()) { registry = sl.iterator().next(); } } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQJMSBridgeLogger.LOGGER.debug("unable to load recovery registry " + locatorClasse, e); } - if (registry != null) - { + if (registry != null) { break; } } - if (registry != null) - { + if (registry != null) { ActiveMQJMSBridgeLogger.LOGGER.debug("Recovery Registry located = " + registry); } } } - public boolean isUseMaskedPassword() - { + public boolean isUseMaskedPassword() { return useMaskedPassword; } - public void setUseMaskedPassword(boolean maskPassword) - { + public void setUseMaskedPassword(boolean maskPassword) { this.useMaskedPassword = maskPassword; } - public String getPasswordCodec() - { + public String getPasswordCodec() { return passwordCodec; } - public void setPasswordCodec(String passwordCodec) - { + public void setPasswordCodec(String passwordCodec) { this.passwordCodec = passwordCodec; } - private class BridgeFailoverListener implements FailoverEventListener - { + private class BridgeFailoverListener implements FailoverEventListener { + private final boolean isSource; volatile FailoverEventType lastEvent; - public BridgeFailoverListener(boolean isSource) - { + public BridgeFailoverListener(boolean isSource) { this.isSource = isSource; } @Override - public void failoverEvent(FailoverEventType eventType) - { - synchronized (this) - { + public void failoverEvent(FailoverEventType eventType) { + synchronized (this) { lastEvent = eventType; - if (eventType == FailoverEventType.FAILURE_DETECTED) - { - if (isSource) - { + if (eventType == FailoverEventType.FAILURE_DETECTED) { + if (isSource) { connectedSource = false; } - else - { + else { connectedTarget = false; } } @@ -2317,32 +1917,25 @@ public final class JMSBridgeImpl implements JMSBridge } //return true if failover completed successfully - public boolean waitForFailover() - { + public boolean waitForFailover() { long toWait = failoverTimeout; long start = 0; long waited = 0; boolean timedOut = false; FailoverEventType result = null; - synchronized (this) - { - while ((lastEvent == null || lastEvent == FailoverEventType.FAILURE_DETECTED)) - { - try - { - if (toWait <= 0) - { + synchronized (this) { + while ((lastEvent == null || lastEvent == FailoverEventType.FAILURE_DETECTED)) { + try { + if (toWait <= 0) { timedOut = true; break; } start = System.currentTimeMillis(); this.wait(toWait); } - catch (InterruptedException e) - { + catch (InterruptedException e) { } - finally - { + finally { waited = System.currentTimeMillis() - start; toWait = failoverTimeout - waited; } @@ -2351,8 +1944,7 @@ public final class JMSBridgeImpl implements JMSBridge lastEvent = null; } - if (timedOut) - { + if (timedOut) { //timeout, presumably failover failed. ActiveMQJMSBridgeLogger.LOGGER.debug("Timed out waiting for failover completion " + this); return false; @@ -2361,14 +1953,11 @@ public final class JMSBridgeImpl implements JMSBridge /* * make sure we reset the connected flags * */ - if (result == FailoverEventType.FAILOVER_COMPLETED) - { - if (isSource) - { + if (result == FailoverEventType.FAILOVER_COMPLETED) { + if (isSource) { connectedSource = true; } - else - { + else { connectedTarget = true; } return true; @@ -2378,15 +1967,12 @@ public final class JMSBridgeImpl implements JMSBridge } } - public long getFailoverTimeout() - { + public long getFailoverTimeout() { return failoverTimeout; } - public void setFailoverTimeout(long failoverTimeout) - { + public void setFailoverTimeout(long failoverTimeout) { this.failoverTimeout = failoverTimeout; } - } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/impl/JNDIConnectionFactoryFactory.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/impl/JNDIConnectionFactoryFactory.java index 291201bbf6..15e6a225e8 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/impl/JNDIConnectionFactoryFactory.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/impl/JNDIConnectionFactoryFactory.java @@ -20,16 +20,13 @@ import org.apache.activemq.artemis.jms.bridge.ConnectionFactoryFactory; import java.util.Hashtable; +public class JNDIConnectionFactoryFactory extends JNDIFactorySupport implements ConnectionFactoryFactory { -public class JNDIConnectionFactoryFactory extends JNDIFactorySupport implements ConnectionFactoryFactory -{ - public JNDIConnectionFactoryFactory(final Hashtable jndiProperties, final String lookup) - { + public JNDIConnectionFactoryFactory(final Hashtable jndiProperties, final String lookup) { super(jndiProperties, lookup); } - public Object createConnectionFactory() throws Exception - { + public Object createConnectionFactory() throws Exception { return createObject(); } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/impl/JNDIDestinationFactory.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/impl/JNDIDestinationFactory.java index 26b63c5f05..3479267095 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/impl/JNDIDestinationFactory.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/impl/JNDIDestinationFactory.java @@ -22,15 +22,13 @@ import java.util.Hashtable; import javax.jms.Destination; -public class JNDIDestinationFactory extends JNDIFactorySupport implements DestinationFactory -{ - public JNDIDestinationFactory(final Hashtable jndiProperties, final String lookup) - { +public class JNDIDestinationFactory extends JNDIFactorySupport implements DestinationFactory { + + public JNDIDestinationFactory(final Hashtable jndiProperties, final String lookup) { super(jndiProperties, lookup); } - public Destination createDestination() throws Exception - { - return (Destination)createObject(); + public Destination createDestination() throws Exception { + return (Destination) createObject(); } } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/impl/JNDIFactorySupport.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/impl/JNDIFactorySupport.java index cfb2421da8..c29793a574 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/impl/JNDIFactorySupport.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/bridge/impl/JNDIFactorySupport.java @@ -20,42 +20,35 @@ import java.util.Hashtable; import javax.naming.InitialContext; -public abstract class JNDIFactorySupport -{ +public abstract class JNDIFactorySupport { + protected Hashtable jndiProperties; protected String lookup; - protected JNDIFactorySupport(final Hashtable jndiProperties, final String lookup) - { + protected JNDIFactorySupport(final Hashtable jndiProperties, final String lookup) { this.jndiProperties = jndiProperties; this.lookup = lookup; } - protected Object createObject() throws Exception - { + protected Object createObject() throws Exception { InitialContext ic = null; Object obj = null; - try - { - if (jndiProperties == null) - { + try { + if (jndiProperties == null) { ic = new InitialContext(); } - else - { + else { ic = new InitialContext(jndiProperties); } obj = ic.lookup(lookup); } - finally - { - if (ic != null) - { + finally { + if (ic != null) { ic.close(); } } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/management/impl/JMSConnectionFactoryControlImpl.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/management/impl/JMSConnectionFactoryControlImpl.java index 59ecd3e082..efa1df541c 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/management/impl/JMSConnectionFactoryControlImpl.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/management/impl/JMSConnectionFactoryControlImpl.java @@ -29,8 +29,7 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; import org.apache.activemq.artemis.jms.server.JMSServerManager; import org.apache.activemq.artemis.jms.server.config.ConnectionFactoryConfiguration; -public class JMSConnectionFactoryControlImpl extends StandardMBean implements ConnectionFactoryControl -{ +public class JMSConnectionFactoryControlImpl extends StandardMBean implements ConnectionFactoryControl { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -50,8 +49,7 @@ public class JMSConnectionFactoryControlImpl extends StandardMBean implements Co public JMSConnectionFactoryControlImpl(final ConnectionFactoryConfiguration cfConfig, final ActiveMQConnectionFactory cf, final JMSServerManager jmsManager, - final String name) throws NotCompliantMBeanException - { + final String name) throws NotCompliantMBeanException { super(ConnectionFactoryControl.class); this.cfConfig = cfConfig; this.cf = cf; @@ -63,405 +61,327 @@ public class JMSConnectionFactoryControlImpl extends StandardMBean implements Co // ManagedConnectionFactoryMBean implementation ------------------ - public String[] getRegistryBindings() - { + public String[] getRegistryBindings() { return jmsManager.getBindingsOnConnectionFactory(name); } - public boolean isCompressLargeMessages() - { + public boolean isCompressLargeMessages() { return cf.isCompressLargeMessage(); } - public void setCompressLargeMessages(final boolean compress) - { + public void setCompressLargeMessages(final boolean compress) { cfConfig.setCompressLargeMessages(compress); recreateCF(); } - public boolean isHA() - { + public boolean isHA() { return cfConfig.isHA(); } - public int getFactoryType() - { + public int getFactoryType() { return cfConfig.getFactoryType().intValue(); } - public String getClientID() - { + public String getClientID() { return cfConfig.getClientID(); } - public long getClientFailureCheckPeriod() - { + public long getClientFailureCheckPeriod() { return cfConfig.getClientFailureCheckPeriod(); } - public void setClientID(String clientID) - { + public void setClientID(String clientID) { cfConfig.setClientID(clientID); recreateCF(); } - public void setDupsOKBatchSize(int dupsOKBatchSize) - { + public void setDupsOKBatchSize(int dupsOKBatchSize) { cfConfig.setDupsOKBatchSize(dupsOKBatchSize); recreateCF(); } - public void setTransactionBatchSize(int transactionBatchSize) - { + public void setTransactionBatchSize(int transactionBatchSize) { cfConfig.setTransactionBatchSize(transactionBatchSize); recreateCF(); } - public void setClientFailureCheckPeriod(long clientFailureCheckPeriod) - { + public void setClientFailureCheckPeriod(long clientFailureCheckPeriod) { cfConfig.setClientFailureCheckPeriod(clientFailureCheckPeriod); recreateCF(); } - public void setConnectionTTL(long connectionTTL) - { + public void setConnectionTTL(long connectionTTL) { cfConfig.setConnectionTTL(connectionTTL); recreateCF(); } - public void setCallTimeout(long callTimeout) - { + public void setCallTimeout(long callTimeout) { cfConfig.setCallTimeout(callTimeout); recreateCF(); } - public void setCallFailoverTimeout(long callTimeout) - { + public void setCallFailoverTimeout(long callTimeout) { cfConfig.setCallFailoverTimeout(callTimeout); recreateCF(); } - public void setConsumerWindowSize(int consumerWindowSize) - { + public void setConsumerWindowSize(int consumerWindowSize) { cfConfig.setConsumerWindowSize(consumerWindowSize); recreateCF(); } - public void setConsumerMaxRate(int consumerMaxRate) - { + public void setConsumerMaxRate(int consumerMaxRate) { cfConfig.setConsumerMaxRate(consumerMaxRate); recreateCF(); } - public void setConfirmationWindowSize(int confirmationWindowSize) - { + public void setConfirmationWindowSize(int confirmationWindowSize) { cfConfig.setConfirmationWindowSize(confirmationWindowSize); recreateCF(); } - public void setProducerMaxRate(int producerMaxRate) - { + public void setProducerMaxRate(int producerMaxRate) { cfConfig.setProducerMaxRate(producerMaxRate); recreateCF(); } - public int getProducerWindowSize() - { + public int getProducerWindowSize() { return cfConfig.getProducerWindowSize(); } - public void setProducerWindowSize(int producerWindowSize) - { + public void setProducerWindowSize(int producerWindowSize) { cfConfig.setProducerWindowSize(producerWindowSize); recreateCF(); } - public void setCacheLargeMessagesClient(boolean cacheLargeMessagesClient) - { + public void setCacheLargeMessagesClient(boolean cacheLargeMessagesClient) { cfConfig.setCacheLargeMessagesClient(cacheLargeMessagesClient); recreateCF(); } - public boolean isCacheLargeMessagesClient() - { + public boolean isCacheLargeMessagesClient() { return cfConfig.isCacheLargeMessagesClient(); } - public void setMinLargeMessageSize(int minLargeMessageSize) - { + public void setMinLargeMessageSize(int minLargeMessageSize) { cfConfig.setMinLargeMessageSize(minLargeMessageSize); recreateCF(); } - public void setBlockOnNonDurableSend(boolean blockOnNonDurableSend) - { + public void setBlockOnNonDurableSend(boolean blockOnNonDurableSend) { cfConfig.setBlockOnNonDurableSend(blockOnNonDurableSend); recreateCF(); } - public void setBlockOnAcknowledge(boolean blockOnAcknowledge) - { + public void setBlockOnAcknowledge(boolean blockOnAcknowledge) { cfConfig.setBlockOnAcknowledge(blockOnAcknowledge); recreateCF(); } - public void setBlockOnDurableSend(boolean blockOnDurableSend) - { + public void setBlockOnDurableSend(boolean blockOnDurableSend) { cfConfig.setBlockOnDurableSend(blockOnDurableSend); recreateCF(); } - public void setAutoGroup(boolean autoGroup) - { + public void setAutoGroup(boolean autoGroup) { cfConfig.setAutoGroup(autoGroup); recreateCF(); } - public void setPreAcknowledge(boolean preAcknowledge) - { + public void setPreAcknowledge(boolean preAcknowledge) { cfConfig.setPreAcknowledge(preAcknowledge); recreateCF(); } - public void setMaxRetryInterval(long retryInterval) - { + public void setMaxRetryInterval(long retryInterval) { cfConfig.setMaxRetryInterval(retryInterval); recreateCF(); } - public void setRetryIntervalMultiplier(double retryIntervalMultiplier) - { + public void setRetryIntervalMultiplier(double retryIntervalMultiplier) { cfConfig.setRetryIntervalMultiplier(retryIntervalMultiplier); recreateCF(); } - public void setReconnectAttempts(int reconnectAttempts) - { + public void setReconnectAttempts(int reconnectAttempts) { cfConfig.setReconnectAttempts(reconnectAttempts); recreateCF(); } - public void setFailoverOnInitialConnection(boolean failover) - { + public void setFailoverOnInitialConnection(boolean failover) { cfConfig.setFailoverOnInitialConnection(failover); recreateCF(); } - public boolean isUseGlobalPools() - { + public boolean isUseGlobalPools() { return cfConfig.isUseGlobalPools(); } - public void setScheduledThreadPoolMaxSize(int scheduledThreadPoolMaxSize) - { + public void setScheduledThreadPoolMaxSize(int scheduledThreadPoolMaxSize) { cfConfig.setScheduledThreadPoolMaxSize(scheduledThreadPoolMaxSize); recreateCF(); } - public int getThreadPoolMaxSize() - { + public int getThreadPoolMaxSize() { return cfConfig.getThreadPoolMaxSize(); } - public void setThreadPoolMaxSize(int threadPoolMaxSize) - { + public void setThreadPoolMaxSize(int threadPoolMaxSize) { cfConfig.setThreadPoolMaxSize(threadPoolMaxSize); recreateCF(); } - public int getInitialMessagePacketSize() - { + public int getInitialMessagePacketSize() { return cf.getInitialMessagePacketSize(); } - public void setGroupID(String groupID) - { + public void setGroupID(String groupID) { cfConfig.setGroupID(groupID); recreateCF(); } - public String getGroupID() - { + public String getGroupID() { return cfConfig.getGroupID(); } - public void setUseGlobalPools(boolean useGlobalPools) - { + public void setUseGlobalPools(boolean useGlobalPools) { cfConfig.setUseGlobalPools(useGlobalPools); recreateCF(); } - public int getScheduledThreadPoolMaxSize() - { + public int getScheduledThreadPoolMaxSize() { return cfConfig.getScheduledThreadPoolMaxSize(); } - public void setRetryInterval(long retryInterval) - { + public void setRetryInterval(long retryInterval) { cfConfig.setRetryInterval(retryInterval); recreateCF(); } - public long getMaxRetryInterval() - { + public long getMaxRetryInterval() { return cfConfig.getMaxRetryInterval(); } - public String getConnectionLoadBalancingPolicyClassName() - { + public String getConnectionLoadBalancingPolicyClassName() { return cfConfig.getLoadBalancingPolicyClassName(); } - public void setConnectionLoadBalancingPolicyClassName(String name) - { + public void setConnectionLoadBalancingPolicyClassName(String name) { cfConfig.setLoadBalancingPolicyClassName(name); recreateCF(); } - public TransportConfiguration[] getStaticConnectors() - { + public TransportConfiguration[] getStaticConnectors() { return cf.getStaticConnectors(); } - public DiscoveryGroupConfiguration getDiscoveryGroupConfiguration() - { + public DiscoveryGroupConfiguration getDiscoveryGroupConfiguration() { return cf.getDiscoveryGroupConfiguration(); } - public void addBinding(@Parameter(name = "binding", desc = "the name of the binding for the Registry") String binding) throws Exception - { + public void addBinding(@Parameter(name = "binding", desc = "the name of the binding for the Registry") String binding) throws Exception { jmsManager.addConnectionFactoryToBindingRegistry(name, binding); } - public void removeBinding(@Parameter(name = "binding", desc = "the name of the binding for the Registry") String binding) throws Exception - { + public void removeBinding(@Parameter(name = "binding", desc = "the name of the binding for the Registry") String binding) throws Exception { jmsManager.removeConnectionFactoryFromBindingRegistry(name, binding); } - public long getCallTimeout() - { + public long getCallTimeout() { return cfConfig.getCallTimeout(); } - public long getCallFailoverTimeout() - { + public long getCallFailoverTimeout() { return cfConfig.getCallFailoverTimeout(); } - public int getConsumerMaxRate() - { + public int getConsumerMaxRate() { return cfConfig.getConsumerMaxRate(); } - public int getConsumerWindowSize() - { + public int getConsumerWindowSize() { return cfConfig.getConsumerWindowSize(); } - public int getProducerMaxRate() - { + public int getProducerMaxRate() { return cfConfig.getProducerMaxRate(); } - public int getConfirmationWindowSize() - { + public int getConfirmationWindowSize() { return cfConfig.getConfirmationWindowSize(); } - public int getDupsOKBatchSize() - { + public int getDupsOKBatchSize() { return cfConfig.getDupsOKBatchSize(); } - public boolean isBlockOnAcknowledge() - { + public boolean isBlockOnAcknowledge() { return cfConfig.isBlockOnAcknowledge(); } - public boolean isBlockOnNonDurableSend() - { + public boolean isBlockOnNonDurableSend() { return cfConfig.isBlockOnNonDurableSend(); } - public boolean isBlockOnDurableSend() - { + public boolean isBlockOnDurableSend() { return cfConfig.isBlockOnDurableSend(); } - public boolean isPreAcknowledge() - { + public boolean isPreAcknowledge() { return cfConfig.isPreAcknowledge(); } - public String getName() - { + public String getName() { return name; } - public long getConnectionTTL() - { + public long getConnectionTTL() { return cfConfig.getConnectionTTL(); } - public int getReconnectAttempts() - { + public int getReconnectAttempts() { return cfConfig.getReconnectAttempts(); } - public boolean isFailoverOnInitialConnection() - { + public boolean isFailoverOnInitialConnection() { return cfConfig.isFailoverOnInitialConnection(); } - public int getMinLargeMessageSize() - { + public int getMinLargeMessageSize() { return cfConfig.getMinLargeMessageSize(); } - public long getRetryInterval() - { + public long getRetryInterval() { return cfConfig.getRetryInterval(); } - public double getRetryIntervalMultiplier() - { + public double getRetryIntervalMultiplier() { return cfConfig.getRetryIntervalMultiplier(); } - public int getTransactionBatchSize() - { + public int getTransactionBatchSize() { return cfConfig.getTransactionBatchSize(); } - public boolean isAutoGroup() - { + public boolean isAutoGroup() { return cfConfig.isAutoGroup(); } @Override - public MBeanInfo getMBeanInfo() - { + public MBeanInfo getMBeanInfo() { MBeanInfo info = super.getMBeanInfo(); - return new MBeanInfo(info.getClassName(), - info.getDescription(), - info.getAttributes(), - info.getConstructors(), - MBeanInfoHelper.getMBeanOperationsInfo(ConnectionFactoryControl.class), - info.getNotifications()); + return new MBeanInfo(info.getClassName(), info.getDescription(), info.getAttributes(), info.getConstructors(), MBeanInfoHelper.getMBeanOperationsInfo(ConnectionFactoryControl.class), info.getNotifications()); } // Package protected --------------------------------------------- // Protected ----------------------------------------------------- - private void recreateCF() - { - try - { + private void recreateCF() { + try { this.cf = jmsManager.recreateCF(this.name, this.cfConfig); } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/management/impl/JMSQueueControlImpl.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/management/impl/JMSQueueControlImpl.java index dd255f57b7..ed2d9224c5 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/management/impl/JMSQueueControlImpl.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/management/impl/JMSQueueControlImpl.java @@ -37,8 +37,8 @@ import org.apache.activemq.artemis.jms.server.JMSServerManager; import org.apache.activemq.artemis.utils.json.JSONArray; import org.apache.activemq.artemis.utils.json.JSONObject; -public class JMSQueueControlImpl extends StandardMBean implements JMSQueueControl -{ +public class JMSQueueControlImpl extends StandardMBean implements JMSQueueControl { + private final ActiveMQDestination managedQueue; private final JMSServerManager jmsServerManager; @@ -52,22 +52,17 @@ public class JMSQueueControlImpl extends StandardMBean implements JMSQueueContro /** * Returns null if the string is null or empty */ - public static String createFilterFromJMSSelector(final String selectorStr) throws ActiveMQException - { - return selectorStr == null || selectorStr.trim().length() == 0 ? null - : SelectorTranslator.convertToActiveMQFilterString(selectorStr); + public static String createFilterFromJMSSelector(final String selectorStr) throws ActiveMQException { + return selectorStr == null || selectorStr.trim().length() == 0 ? null : SelectorTranslator.convertToActiveMQFilterString(selectorStr); } - private static String createFilterForJMSMessageID(final String jmsMessageID) throws Exception - { + private static String createFilterForJMSMessageID(final String jmsMessageID) throws Exception { return FilterConstants.ACTIVEMQ_USERID + " = '" + jmsMessageID + "'"; } - static String toJSON(final Map[] messages) - { + static String toJSON(final Map[] messages) { JSONArray array = new JSONArray(); - for (Map message : messages) - { + for (Map message : messages) { array.put(new JSONObject(message)); } return array.toString(); @@ -78,8 +73,7 @@ public class JMSQueueControlImpl extends StandardMBean implements JMSQueueContro public JMSQueueControlImpl(final ActiveMQDestination managedQueue, final QueueControl coreQueueControl, final JMSServerManager jmsServerManager, - final MessageCounter counter) throws Exception - { + final MessageCounter counter) throws Exception { super(JMSQueueControl.class); this.managedQueue = managedQueue; this.jmsServerManager = jmsServerManager; @@ -91,127 +85,103 @@ public class JMSQueueControlImpl extends StandardMBean implements JMSQueueContro // ManagedJMSQueueMBean implementation --------------------------- - public String getName() - { + public String getName() { return managedQueue.getName(); } - public String getAddress() - { + public String getAddress() { return managedQueue.getAddress(); } - public boolean isTemporary() - { + public boolean isTemporary() { return managedQueue.isTemporary(); } - public long getMessageCount() - { + public long getMessageCount() { return coreQueueControl.getMessageCount(); } - public long getMessagesAdded() - { + public long getMessagesAdded() { return coreQueueControl.getMessagesAdded(); } - public int getConsumerCount() - { + public int getConsumerCount() { return coreQueueControl.getConsumerCount(); } - public int getDeliveringCount() - { + public int getDeliveringCount() { return coreQueueControl.getDeliveringCount(); } - public long getScheduledCount() - { + public long getScheduledCount() { return coreQueueControl.getScheduledCount(); } - public boolean isDurable() - { + public boolean isDurable() { return coreQueueControl.isDurable(); } - public String getDeadLetterAddress() - { + public String getDeadLetterAddress() { return coreQueueControl.getDeadLetterAddress(); } - public String getExpiryAddress() - { + public String getExpiryAddress() { return coreQueueControl.getExpiryAddress(); } - public String getFirstMessageAsJSON() throws Exception - { + public String getFirstMessageAsJSON() throws Exception { return coreQueueControl.getFirstMessageAsJSON(); } - public Long getFirstMessageTimestamp() throws Exception - { + public Long getFirstMessageTimestamp() throws Exception { return coreQueueControl.getFirstMessageTimestamp(); } - public Long getFirstMessageAge() throws Exception - { + public Long getFirstMessageAge() throws Exception { return coreQueueControl.getFirstMessageAge(); } @Override - public void addBinding(String binding) throws Exception - { + public void addBinding(String binding) throws Exception { jmsServerManager.addQueueToBindingRegistry(managedQueue.getName(), binding); } - public String[] getRegistryBindings() - { + public String[] getRegistryBindings() { return jmsServerManager.getBindingsOnQueue(managedQueue.getName()); } - public boolean removeMessage(final String messageID) throws Exception - { + public boolean removeMessage(final String messageID) throws Exception { String filter = JMSQueueControlImpl.createFilterForJMSMessageID(messageID); int removed = coreQueueControl.removeMessages(filter); - if (removed != 1) - { + if (removed != 1) { throw new IllegalArgumentException("No message found for JMSMessageID: " + messageID); } return true; } - public int removeMessages(final String filterStr) throws Exception - { + public int removeMessages(final String filterStr) throws Exception { String filter = JMSQueueControlImpl.createFilterFromJMSSelector(filterStr); return coreQueueControl.removeMessages(filter); } - public Map[] listMessages(final String filterStr) throws Exception - { - try - { + public Map[] listMessages(final String filterStr) throws Exception { + try { String filter = JMSQueueControlImpl.createFilterFromJMSSelector(filterStr); Map[] coreMessages = coreQueueControl.listMessages(filter); return toJMSMap(coreMessages); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw new IllegalStateException(e.getMessage()); } } - private Map[] toJMSMap(Map[] coreMessages) - { + private Map[] toJMSMap(Map[] coreMessages) { Map[] jmsMessages = new Map[coreMessages.length]; int i = 0; - for (Map coreMessage : coreMessages) - { + for (Map coreMessage : coreMessages) { Map jmsMessage = ActiveMQMessage.coreMaptoJMSMap(coreMessage); jmsMessages[i++] = jmsMessage; } @@ -219,215 +189,175 @@ public class JMSQueueControlImpl extends StandardMBean implements JMSQueueContro } @Override - public Map[] listScheduledMessages() throws Exception - { + public Map[] listScheduledMessages() throws Exception { Map[] coreMessages = coreQueueControl.listScheduledMessages(); return toJMSMap(coreMessages); } @Override - public String listScheduledMessagesAsJSON() throws Exception - { + public String listScheduledMessagesAsJSON() throws Exception { return coreQueueControl.listScheduledMessagesAsJSON(); } @Override - public Map[]> listDeliveringMessages() throws Exception - { - try - { + public Map[]> listDeliveringMessages() throws Exception { + try { Map[]> returnMap = new HashMap[]>(); - // the workingMap from the queue-control Map[]> workingMap = coreQueueControl.listDeliveringMessages(); - for (Map.Entry[]> entry : workingMap.entrySet()) - { + for (Map.Entry[]> entry : workingMap.entrySet()) { returnMap.put(entry.getKey(), toJMSMap(entry.getValue())); } return returnMap; } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw new IllegalStateException(e.getMessage()); } } @Override - public String listDeliveringMessagesAsJSON() throws Exception - { + public String listDeliveringMessagesAsJSON() throws Exception { return coreQueueControl.listDeliveringMessagesAsJSON(); } - public String listMessagesAsJSON(final String filter) throws Exception - { + public String listMessagesAsJSON(final String filter) throws Exception { return JMSQueueControlImpl.toJSON(listMessages(filter)); } - public long countMessages(final String filterStr) throws Exception - { + public long countMessages(final String filterStr) throws Exception { String filter = JMSQueueControlImpl.createFilterFromJMSSelector(filterStr); return coreQueueControl.countMessages(filter); } - public boolean expireMessage(final String messageID) throws Exception - { + public boolean expireMessage(final String messageID) throws Exception { String filter = JMSQueueControlImpl.createFilterForJMSMessageID(messageID); int expired = coreQueueControl.expireMessages(filter); - if (expired != 1) - { + if (expired != 1) { throw new IllegalArgumentException("No message found for JMSMessageID: " + messageID); } return true; } - public int expireMessages(final String filterStr) throws Exception - { + public int expireMessages(final String filterStr) throws Exception { String filter = JMSQueueControlImpl.createFilterFromJMSSelector(filterStr); return coreQueueControl.expireMessages(filter); } - public boolean sendMessageToDeadLetterAddress(final String messageID) throws Exception - { + public boolean sendMessageToDeadLetterAddress(final String messageID) throws Exception { String filter = JMSQueueControlImpl.createFilterForJMSMessageID(messageID); int dead = coreQueueControl.sendMessagesToDeadLetterAddress(filter); - if (dead != 1) - { + if (dead != 1) { throw new IllegalArgumentException("No message found for JMSMessageID: " + messageID); } return true; } - public int sendMessagesToDeadLetterAddress(final String filterStr) throws Exception - { + public int sendMessagesToDeadLetterAddress(final String filterStr) throws Exception { String filter = JMSQueueControlImpl.createFilterFromJMSSelector(filterStr); return coreQueueControl.sendMessagesToDeadLetterAddress(filter); } - public boolean changeMessagePriority(final String messageID, final int newPriority) throws Exception - { + public boolean changeMessagePriority(final String messageID, final int newPriority) throws Exception { String filter = JMSQueueControlImpl.createFilterForJMSMessageID(messageID); int changed = coreQueueControl.changeMessagesPriority(filter, newPriority); - if (changed != 1) - { + if (changed != 1) { throw new IllegalArgumentException("No message found for JMSMessageID: " + messageID); } return true; } - public int changeMessagesPriority(final String filterStr, final int newPriority) throws Exception - { + public int changeMessagesPriority(final String filterStr, final int newPriority) throws Exception { String filter = JMSQueueControlImpl.createFilterFromJMSSelector(filterStr); return coreQueueControl.changeMessagesPriority(filter, newPriority); } - public boolean moveMessage(final String messageID, final String otherQueueName) throws Exception - { + public boolean moveMessage(final String messageID, final String otherQueueName) throws Exception { return moveMessage(messageID, otherQueueName, false); } - public boolean moveMessage(final String messageID, final String otherQueueName, final boolean rejectDuplicates) throws Exception - { + public boolean moveMessage(final String messageID, + final String otherQueueName, + final boolean rejectDuplicates) throws Exception { String filter = JMSQueueControlImpl.createFilterForJMSMessageID(messageID); ActiveMQDestination otherQueue = ActiveMQDestination.createQueue(otherQueueName); int moved = coreQueueControl.moveMessages(filter, otherQueue.getAddress(), rejectDuplicates); - if (moved != 1) - { + if (moved != 1) { throw new IllegalArgumentException("No message found for JMSMessageID: " + messageID); } return true; } - public int moveMessages(final String filterStr, final String otherQueueName, final boolean rejectDuplicates) throws Exception - { + public int moveMessages(final String filterStr, + final String otherQueueName, + final boolean rejectDuplicates) throws Exception { String filter = JMSQueueControlImpl.createFilterFromJMSSelector(filterStr); ActiveMQDestination otherQueue = ActiveMQDestination.createQueue(otherQueueName); return coreQueueControl.moveMessages(filter, otherQueue.getAddress(), rejectDuplicates); } - - public int moveMessages(final String filterStr, final String otherQueueName) throws Exception - { + public int moveMessages(final String filterStr, final String otherQueueName) throws Exception { return moveMessages(filterStr, otherQueueName, false); } @Operation(desc = "List all the existent consumers on the Queue") - public String listConsumersAsJSON() throws Exception - { + public String listConsumersAsJSON() throws Exception { return coreQueueControl.listConsumersAsJSON(); } - public String listMessageCounter() - { - try - { + public String listMessageCounter() { + try { return MessageCounterInfo.toJSon(counter); } - catch (Exception e) - { + catch (Exception e) { throw new IllegalStateException(e); } } - public void resetMessageCounter() throws Exception - { + public void resetMessageCounter() throws Exception { coreQueueControl.resetMessageCounter(); } - public String listMessageCounterAsHTML() - { + public String listMessageCounterAsHTML() { return MessageCounterHelper.listMessageCounterAsHTML(new MessageCounter[]{counter}); } - public String listMessageCounterHistory() throws Exception - { + public String listMessageCounterHistory() throws Exception { return MessageCounterHelper.listMessageCounterHistory(counter); } - public String listMessageCounterHistoryAsHTML() - { + public String listMessageCounterHistoryAsHTML() { return MessageCounterHelper.listMessageCounterHistoryAsHTML(new MessageCounter[]{counter}); } - public boolean isPaused() throws Exception - { + public boolean isPaused() throws Exception { return coreQueueControl.isPaused(); } - public void pause() throws Exception - { + public void pause() throws Exception { coreQueueControl.pause(); } - public void resume() throws Exception - { + public void resume() throws Exception { coreQueueControl.resume(); } - public String getSelector() - { + public String getSelector() { return coreQueueControl.getFilter(); } - public void flushExecutor() - { + public void flushExecutor() { coreQueueControl.flushExecutor(); } @Override - public MBeanInfo getMBeanInfo() - { + public MBeanInfo getMBeanInfo() { MBeanInfo info = super.getMBeanInfo(); - return new MBeanInfo(info.getClassName(), - info.getDescription(), - info.getAttributes(), - info.getConstructors(), - MBeanInfoHelper.getMBeanOperationsInfo(JMSQueueControl.class), - info.getNotifications()); + return new MBeanInfo(info.getClassName(), info.getDescription(), info.getAttributes(), info.getConstructors(), MBeanInfoHelper.getMBeanOperationsInfo(JMSQueueControl.class), info.getNotifications()); } // Package protected --------------------------------------------- diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/management/impl/JMSServerControlImpl.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/management/impl/JMSServerControlImpl.java index 9e50cc2bf6..eacc91f9ee 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/management/impl/JMSServerControlImpl.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/management/impl/JMSServerControlImpl.java @@ -57,9 +57,7 @@ import org.apache.activemq.artemis.utils.TypedProperties; import org.apache.activemq.artemis.utils.json.JSONArray; import org.apache.activemq.artemis.utils.json.JSONObject; -public class JMSServerControlImpl extends AbstractControl implements JMSServerControl, NotificationEmitter, - org.apache.activemq.artemis.core.server.management.NotificationListener -{ +public class JMSServerControlImpl extends AbstractControl implements JMSServerControl, NotificationEmitter, org.apache.activemq.artemis.core.server.management.NotificationListener { // Constants ----------------------------------------------------- @@ -73,57 +71,46 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo // Static -------------------------------------------------------- - private static String[] convert(final Object[] bindings) - { + private static String[] convert(final Object[] bindings) { String[] theBindings = new String[bindings.length]; - for (int i = 0, bindingsLength = bindings.length; i < bindingsLength; i++) - { + for (int i = 0, bindingsLength = bindings.length; i < bindingsLength; i++) { theBindings[i] = bindings[i].toString().trim(); } return theBindings; } - private static String[] toArray(final String commaSeparatedString) - { - if (commaSeparatedString == null || commaSeparatedString.trim().length() == 0) - { + private static String[] toArray(final String commaSeparatedString) { + if (commaSeparatedString == null || commaSeparatedString.trim().length() == 0) { return new String[0]; } String[] values = commaSeparatedString.split(","); String[] trimmed = new String[values.length]; - for (int i = 0; i < values.length; i++) - { + for (int i = 0; i < values.length; i++) { trimmed[i] = values[i].trim(); trimmed[i] = trimmed[i].replace(",", ","); } return trimmed; } - private static String[] determineJMSDestination(String coreAddress) - { + private static String[] determineJMSDestination(String coreAddress) { String[] result = new String[2]; // destination name & type - if (coreAddress.startsWith(ActiveMQDestination.JMS_QUEUE_ADDRESS_PREFIX)) - { + if (coreAddress.startsWith(ActiveMQDestination.JMS_QUEUE_ADDRESS_PREFIX)) { result[0] = coreAddress.substring(ActiveMQDestination.JMS_QUEUE_ADDRESS_PREFIX.length()); result[1] = "queue"; } - else if (coreAddress.startsWith(ActiveMQDestination.JMS_TEMP_QUEUE_ADDRESS_PREFIX)) - { + else if (coreAddress.startsWith(ActiveMQDestination.JMS_TEMP_QUEUE_ADDRESS_PREFIX)) { result[0] = coreAddress.substring(ActiveMQDestination.JMS_TEMP_QUEUE_ADDRESS_PREFIX.length()); result[1] = "tempqueue"; } - else if (coreAddress.startsWith(ActiveMQDestination.JMS_TOPIC_ADDRESS_PREFIX)) - { + else if (coreAddress.startsWith(ActiveMQDestination.JMS_TOPIC_ADDRESS_PREFIX)) { result[0] = coreAddress.substring(ActiveMQDestination.JMS_TOPIC_ADDRESS_PREFIX.length()); result[1] = "topic"; } - else if (coreAddress.startsWith(ActiveMQDestination.JMS_TEMP_TOPIC_ADDRESS_PREFIX)) - { + else if (coreAddress.startsWith(ActiveMQDestination.JMS_TEMP_TOPIC_ADDRESS_PREFIX)) { result[0] = coreAddress.substring(ActiveMQDestination.JMS_TEMP_TOPIC_ADDRESS_PREFIX.length()); result[1] = "temptopic"; } - else - { + else { ActiveMQJMSServerLogger.LOGGER.debug("JMSServerControlImpl.determineJMSDestination()" + coreAddress); // not related to JMS return null; @@ -131,23 +118,18 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo return result; } - public static MBeanNotificationInfo[] getNotificationInfos() - { + public static MBeanNotificationInfo[] getNotificationInfos() { JMSNotificationType[] values = JMSNotificationType.values(); String[] names = new String[values.length]; - for (int i = 0; i < values.length; i++) - { + for (int i = 0; i < values.length; i++) { names[i] = values[i].toString(); } - return new MBeanNotificationInfo[]{new MBeanNotificationInfo(names, - JMSServerControl.class.getName(), - "Notifications emitted by a JMS Server")}; + return new MBeanNotificationInfo[]{new MBeanNotificationInfo(names, JMSServerControl.class.getName(), "Notifications emitted by a JMS Server")}; } // Constructors -------------------------------------------------- - public JMSServerControlImpl(final JMSServerManager server) throws Exception - { + public JMSServerControlImpl(final JMSServerManager server) throws Exception { super(JMSServerControl.class, server.getActiveMQServer().getStorageManager()); this.server = server; broadcaster = new NotificationBroadcasterSupport(); @@ -166,44 +148,29 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo boolean useDiscovery, int cfType, String[] connectorNames, - Object[] bindings) throws Exception - { + Object[] bindings) throws Exception { checkStarted(); clearIO(); - try - { - if (useDiscovery) - { - if (connectorNames == null || connectorNames.length == 0) - { + try { + if (useDiscovery) { + if (connectorNames == null || connectorNames.length == 0) { throw new IllegalArgumentException("no discovery group name supplied"); } - server.createConnectionFactory(name, - ha, - JMSFactoryType.valueOf(cfType), - connectorNames[0], - JMSServerControlImpl.convert(bindings)); + server.createConnectionFactory(name, ha, JMSFactoryType.valueOf(cfType), connectorNames[0], JMSServerControlImpl.convert(bindings)); } - else - { + else { List connectorList = new ArrayList(connectorNames.length); - for (String str : connectorNames) - { + for (String str : connectorNames) { connectorList.add(str); } - server.createConnectionFactory(name, - ha, - JMSFactoryType.valueOf(cfType), - connectorList, - JMSServerControlImpl.convert(bindings)); + server.createConnectionFactory(name, ha, JMSFactoryType.valueOf(cfType), connectorList, JMSServerControlImpl.convert(bindings)); } } - finally - { + finally { blockOnIO(); } } @@ -243,43 +210,8 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo long maxRetryInterval, int reconnectAttempts, boolean failoverOnInitialConnection, - String groupId) throws Exception - { - createConnectionFactory(name, - ha, - useDiscovery, - cfType, - toArray(connectors), - toArray(bindings), - clientID, - clientFailureCheckPeriod, - connectionTTL, - callTimeout, - callFailoverTimeout, - minLargeMessageSize, - compressLargeMessages, - consumerWindowSize, - consumerMaxRate, - confirmationWindowSize, - producerWindowSize, - producerMaxRate, - blockOnAcknowledge, - blockOnDurableSend, - blockOnNonDurableSend, - autoGroup, - preAcknowledge, - loadBalancingPolicyClassName, - transactionBatchSize, - dupsOKBatchSize, - useGlobalPools, - scheduledThreadPoolMaxSize, - threadPoolMaxSize, - retryInterval, - retryIntervalMultiplier, - maxRetryInterval, - reconnectAttempts, - failoverOnInitialConnection, - groupId); + String groupId) throws Exception { + createConnectionFactory(name, ha, useDiscovery, cfType, toArray(connectors), toArray(bindings), clientID, clientFailureCheckPeriod, connectionTTL, callTimeout, callFailoverTimeout, minLargeMessageSize, compressLargeMessages, consumerWindowSize, consumerMaxRate, confirmationWindowSize, producerWindowSize, producerMaxRate, blockOnAcknowledge, blockOnDurableSend, blockOnNonDurableSend, autoGroup, preAcknowledge, loadBalancingPolicyClassName, transactionBatchSize, dupsOKBatchSize, useGlobalPools, scheduledThreadPoolMaxSize, threadPoolMaxSize, retryInterval, retryIntervalMultiplier, maxRetryInterval, reconnectAttempts, failoverOnInitialConnection, groupId); } @Override @@ -317,71 +249,32 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo long maxRetryInterval, int reconnectAttempts, boolean failoverOnInitialConnection, - String groupId) throws Exception - { + String groupId) throws Exception { checkStarted(); clearIO(); - try - { - ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl() - .setName(name) - .setHA(ha) - .setBindings(bindings) - .setFactoryType(JMSFactoryType.valueOf(cfType)) - .setClientID(clientID) - .setClientFailureCheckPeriod(clientFailureCheckPeriod) - .setConnectionTTL(connectionTTL) - .setCallTimeout(callTimeout) - .setCallFailoverTimeout(callFailoverTimeout) - .setMinLargeMessageSize(minLargeMessageSize) - .setCompressLargeMessages(compressLargeMessages) - .setConsumerWindowSize(consumerWindowSize) - .setConsumerMaxRate(consumerMaxRate) - .setConfirmationWindowSize(confirmationWindowSize) - .setProducerWindowSize(producerWindowSize) - .setProducerMaxRate(producerMaxRate) - .setBlockOnAcknowledge(blockOnAcknowledge) - .setBlockOnDurableSend(blockOnDurableSend) - .setBlockOnNonDurableSend(blockOnNonDurableSend) - .setAutoGroup(autoGroup) - .setPreAcknowledge(preAcknowledge) - .setTransactionBatchSize(transactionBatchSize) - .setDupsOKBatchSize(dupsOKBatchSize) - .setUseGlobalPools(useGlobalPools) - .setScheduledThreadPoolMaxSize(scheduledThreadPoolMaxSize) - .setThreadPoolMaxSize(threadPoolMaxSize) - .setRetryInterval(retryInterval) - .setRetryIntervalMultiplier(retryIntervalMultiplier) - .setMaxRetryInterval(maxRetryInterval) - .setReconnectAttempts(reconnectAttempts) - .setFailoverOnInitialConnection(failoverOnInitialConnection) - .setGroupID(groupId); + try { + ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl().setName(name).setHA(ha).setBindings(bindings).setFactoryType(JMSFactoryType.valueOf(cfType)).setClientID(clientID).setClientFailureCheckPeriod(clientFailureCheckPeriod).setConnectionTTL(connectionTTL).setCallTimeout(callTimeout).setCallFailoverTimeout(callFailoverTimeout).setMinLargeMessageSize(minLargeMessageSize).setCompressLargeMessages(compressLargeMessages).setConsumerWindowSize(consumerWindowSize).setConsumerMaxRate(consumerMaxRate).setConfirmationWindowSize(confirmationWindowSize).setProducerWindowSize(producerWindowSize).setProducerMaxRate(producerMaxRate).setBlockOnAcknowledge(blockOnAcknowledge).setBlockOnDurableSend(blockOnDurableSend).setBlockOnNonDurableSend(blockOnNonDurableSend).setAutoGroup(autoGroup).setPreAcknowledge(preAcknowledge).setTransactionBatchSize(transactionBatchSize).setDupsOKBatchSize(dupsOKBatchSize).setUseGlobalPools(useGlobalPools).setScheduledThreadPoolMaxSize(scheduledThreadPoolMaxSize).setThreadPoolMaxSize(threadPoolMaxSize).setRetryInterval(retryInterval).setRetryIntervalMultiplier(retryIntervalMultiplier).setMaxRetryInterval(maxRetryInterval).setReconnectAttempts(reconnectAttempts).setFailoverOnInitialConnection(failoverOnInitialConnection).setGroupID(groupId); - if (useDiscovery) - { + if (useDiscovery) { configuration.setDiscoveryGroupName(connectorNames[0]); } - else - { + else { ArrayList connectorNamesList = new ArrayList(); - for (String nameC : connectorNames) - { + for (String nameC : connectorNames) { connectorNamesList.add(nameC); } configuration.setConnectorNames(connectorNamesList); } - if (loadBalancingPolicyClassName != null && !loadBalancingPolicyClassName.trim().equals("")) - { + if (loadBalancingPolicyClassName != null && !loadBalancingPolicyClassName.trim().equals("")) { configuration.setLoadBalancingPolicyClassName(loadBalancingPolicyClassName); } server.createConnectionFactory(true, configuration, bindings); } - finally - { + finally { blockOnIO(); } } @@ -396,206 +289,166 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo boolean useDiscovery, int cfType, String connectors, - String bindings) throws Exception - { + String bindings) throws Exception { createConnectionFactory(name, ha, useDiscovery, cfType, toArray(connectors), toArray(bindings)); } - public boolean createQueue(final String name) throws Exception - { + public boolean createQueue(final String name) throws Exception { return createQueue(name, null, null, true); } - public boolean createQueue(final String name, final String bindings) throws Exception - { + public boolean createQueue(final String name, final String bindings) throws Exception { return createQueue(name, bindings, null, true); } @Override - public boolean createQueue(String name, String bindings, String selector) throws Exception - { + public boolean createQueue(String name, String bindings, String selector) throws Exception { return createQueue(name, bindings, selector, true); } public boolean createQueue(@Parameter(name = "name", desc = "Name of the queue to create") String name, @Parameter(name = "bindings", desc = "comma-separated list of Registry bindings (use ',' if u need to use commas in your bindings name)") String bindings, @Parameter(name = "selector", desc = "the jms selector") String selector, - @Parameter(name = "durable", desc = "is the queue persistent and resilient to restart") boolean durable) throws Exception - { + @Parameter(name = "durable", desc = "is the queue persistent and resilient to restart") boolean durable) throws Exception { checkStarted(); clearIO(); - try - { - return server.createQueue(true, name, selector, durable, - JMSServerControlImpl.toArray(bindings)); + try { + return server.createQueue(true, name, selector, durable, JMSServerControlImpl.toArray(bindings)); } - finally - { + finally { blockOnIO(); } } - public boolean destroyQueue(final String name) throws Exception - { + public boolean destroyQueue(final String name) throws Exception { return destroyQueue(name, false); } - public boolean destroyQueue(final String name, final boolean removeConsumers) throws Exception - { + public boolean destroyQueue(final String name, final boolean removeConsumers) throws Exception { checkStarted(); clearIO(); - try - { + try { return server.destroyQueue(name, removeConsumers); } - finally - { + finally { blockOnIO(); } } - public boolean createTopic(String name) throws Exception - { + public boolean createTopic(String name) throws Exception { return createTopic(name, null); } - public boolean createTopic(final String topicName, final String bindings) throws Exception - { + public boolean createTopic(final String topicName, final String bindings) throws Exception { checkStarted(); clearIO(); - try - { + try { return server.createTopic(true, topicName, JMSServerControlImpl.toArray(bindings)); } - finally - { + finally { blockOnIO(); } } - public boolean destroyTopic(final String name) throws Exception - { + public boolean destroyTopic(final String name) throws Exception { return destroyTopic(name, true); } - - public boolean destroyTopic(final String name, final boolean removeConsumers) throws Exception - { + public boolean destroyTopic(final String name, final boolean removeConsumers) throws Exception { checkStarted(); clearIO(); - try - { + try { return server.destroyTopic(name, removeConsumers); } - finally - { + finally { blockOnIO(); } } - public void destroyConnectionFactory(final String name) throws Exception - { + public void destroyConnectionFactory(final String name) throws Exception { checkStarted(); clearIO(); - try - { + try { server.destroyConnectionFactory(name); } - finally - { + finally { blockOnIO(); } } - public boolean isStarted() - { + public boolean isStarted() { return server.isStarted(); } - public String getVersion() - { + public String getVersion() { checkStarted(); return server.getVersion(); } - public String[] getQueueNames() - { + public String[] getQueueNames() { checkStarted(); clearIO(); - try - { + try { Object[] queueControls = server.getActiveMQServer().getManagementService().getResources(JMSQueueControl.class); String[] names = new String[queueControls.length]; - for (int i = 0; i < queueControls.length; i++) - { + for (int i = 0; i < queueControls.length; i++) { JMSQueueControl queueControl = (JMSQueueControl) queueControls[i]; names[i] = queueControl.getName(); } return names; } - finally - { + finally { blockOnIO(); } } - public String[] getTopicNames() - { + public String[] getTopicNames() { checkStarted(); clearIO(); - try - { + try { Object[] topicControls = server.getActiveMQServer().getManagementService().getResources(TopicControl.class); String[] names = new String[topicControls.length]; - for (int i = 0; i < topicControls.length; i++) - { + for (int i = 0; i < topicControls.length; i++) { TopicControl topicControl = (TopicControl) topicControls[i]; names[i] = topicControl.getName(); } return names; } - finally - { + finally { blockOnIO(); } } - public String[] getConnectionFactoryNames() - { + public String[] getConnectionFactoryNames() { checkStarted(); clearIO(); - try - { - Object[] cfControls = server.getActiveMQServer() - .getManagementService() - .getResources(ConnectionFactoryControl.class); + try { + Object[] cfControls = server.getActiveMQServer().getManagementService().getResources(ConnectionFactoryControl.class); String[] names = new String[cfControls.length]; - for (int i = 0; i < cfControls.length; i++) - { + for (int i = 0; i < cfControls.length; i++) { ConnectionFactoryControl cfControl = (ConnectionFactoryControl) cfControls[i]; names[i] = cfControl.getName(); } return names; } - finally - { + finally { blockOnIO(); } } @@ -604,132 +457,108 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo public void removeNotificationListener(final NotificationListener listener, final NotificationFilter filter, - final Object handback) throws ListenerNotFoundException - { + final Object handback) throws ListenerNotFoundException { broadcaster.removeNotificationListener(listener, filter, handback); } - public void removeNotificationListener(final NotificationListener listener) throws ListenerNotFoundException - { + public void removeNotificationListener(final NotificationListener listener) throws ListenerNotFoundException { broadcaster.removeNotificationListener(listener); } public void addNotificationListener(final NotificationListener listener, final NotificationFilter filter, - final Object handback) throws IllegalArgumentException - { + final Object handback) throws IllegalArgumentException { broadcaster.addNotificationListener(listener, filter, handback); } - public MBeanNotificationInfo[] getNotificationInfo() - { + public MBeanNotificationInfo[] getNotificationInfo() { return JMSServerControlImpl.getNotificationInfos(); } - public String[] listRemoteAddresses() throws Exception - { + public String[] listRemoteAddresses() throws Exception { checkStarted(); clearIO(); - try - { + try { return server.listRemoteAddresses(); } - finally - { + finally { blockOnIO(); } } - public String[] listRemoteAddresses(final String ipAddress) throws Exception - { + public String[] listRemoteAddresses(final String ipAddress) throws Exception { checkStarted(); clearIO(); - try - { + try { return server.listRemoteAddresses(ipAddress); } - finally - { + finally { blockOnIO(); } } - public boolean closeConnectionsForAddress(final String ipAddress) throws Exception - { + public boolean closeConnectionsForAddress(final String ipAddress) throws Exception { checkStarted(); clearIO(); - try - { + try { return server.closeConnectionsForAddress(ipAddress); } - finally - { + finally { blockOnIO(); } } - public boolean closeConsumerConnectionsForAddress(final String address) throws Exception - { + public boolean closeConsumerConnectionsForAddress(final String address) throws Exception { checkStarted(); clearIO(); - try - { + try { return server.closeConsumerConnectionsForAddress(address); } - finally - { + finally { blockOnIO(); } } - public boolean closeConnectionsForUser(final String userName) throws Exception - { + public boolean closeConnectionsForUser(final String userName) throws Exception { checkStarted(); clearIO(); - try - { + try { return server.closeConnectionsForUser(userName); } - finally - { + finally { blockOnIO(); } } - public String[] listConnectionIDs() throws Exception - { + public String[] listConnectionIDs() throws Exception { checkStarted(); clearIO(); - try - { + try { return server.listConnectionIDs(); } - finally - { + finally { blockOnIO(); } } - public String listConnectionsAsJSON() throws Exception - { + public String listConnectionsAsJSON() throws Exception { checkStarted(); clearIO(); - try - { + try { JSONArray array = new JSONArray(); Set connections = server.getActiveMQServer().getRemotingService().getConnections(); @@ -739,19 +568,15 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo Map jmsSessions = new HashMap(); // First separate the real jms sessions, after all we are only interested in those here on the *jms* server controller - for (ServerSession session : sessions) - { - if (session.getMetaData(ClientSession.JMS_SESSION_IDENTIFIER_PROPERTY) != null) - { + for (ServerSession session : sessions) { + if (session.getMetaData(ClientSession.JMS_SESSION_IDENTIFIER_PROPERTY) != null) { jmsSessions.put(session.getConnectionID(), session); } } - for (RemotingConnection connection : connections) - { + for (RemotingConnection connection : connections) { ServerSession session = jmsSessions.get(connection.getID()); - if (session != null) - { + if (session != null) { JSONObject obj = new JSONObject(); obj.put("connectionID", connection.getID().toString()); obj.put("clientAddress", connection.getRemoteAddress()); @@ -764,36 +589,28 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo } return array.toString(); } - finally - { + finally { blockOnIO(); } } - public String listConsumersAsJSON(String connectionID) throws Exception - { + public String listConsumersAsJSON(String connectionID) throws Exception { checkStarted(); clearIO(); - try - { + try { JSONArray array = new JSONArray(); Set connections = server.getActiveMQServer().getRemotingService().getConnections(); - for (RemotingConnection connection : connections) - { - if (connectionID.equals(connection.getID().toString())) - { + for (RemotingConnection connection : connections) { + if (connectionID.equals(connection.getID().toString())) { List sessions = server.getActiveMQServer().getSessions(connectionID); - for (ServerSession session : sessions) - { + for (ServerSession session : sessions) { Set consumers = session.getServerConsumers(); - for (ServerConsumer consumer : consumers) - { + for (ServerConsumer consumer : consumers) { JSONObject obj = toJSONObject(consumer); - if (obj != null) - { + if (obj != null) { array.put(obj); } } @@ -802,87 +619,71 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo } return array.toString(); } - finally - { + finally { blockOnIO(); } } - public String listAllConsumersAsJSON() throws Exception - { + public String listAllConsumersAsJSON() throws Exception { checkStarted(); clearIO(); - try - { + try { JSONArray array = new JSONArray(); Set sessions = server.getActiveMQServer().getSessions(); - for (ServerSession session : sessions) - { + for (ServerSession session : sessions) { Set consumers = session.getServerConsumers(); - for (ServerConsumer consumer : consumers) - { + for (ServerConsumer consumer : consumers) { JSONObject obj = toJSONObject(consumer); - if (obj != null) - { + if (obj != null) { array.put(obj); } } } return array.toString(); } - finally - { + finally { blockOnIO(); } } - public String[] listSessions(final String connectionID) throws Exception - { + public String[] listSessions(final String connectionID) throws Exception { checkStarted(); clearIO(); - try - { + try { return server.listSessions(connectionID); } - finally - { + finally { blockOnIO(); } } - public String listPreparedTransactionDetailsAsJSON() throws Exception - { + public String listPreparedTransactionDetailsAsJSON() throws Exception { checkStarted(); clearIO(); - try - { + try { return server.listPreparedTransactionDetailsAsJSON(); } - finally - { + finally { blockOnIO(); } } - public String listPreparedTransactionDetailsAsHTML() throws Exception - { + public String listPreparedTransactionDetailsAsHTML() throws Exception { checkStarted(); clearIO(); - try - { + try { return server.listPreparedTransactionDetailsAsHTML(); } - finally - { + finally { blockOnIO(); } } @@ -894,106 +695,88 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo * @see org.apache.activemq.artemis.core.management.impl.AbstractControl#fillMBeanOperationInfo() */ @Override - protected MBeanOperationInfo[] fillMBeanOperationInfo() - { + protected MBeanOperationInfo[] fillMBeanOperationInfo() { return MBeanInfoHelper.getMBeanOperationsInfo(JMSServerControl.class); } // Private ------------------------------------------------------- - private void checkStarted() - { - if (!server.isStarted()) - { + private void checkStarted() { + if (!server.isStarted()) { throw new IllegalStateException("ActiveMQ Artemis JMS Server is not started. It can not be managed yet"); } } // Inner classes ------------------------------------------------- - public String[] listTargetDestinations(String sessionID) throws Exception - { + public String[] listTargetDestinations(String sessionID) throws Exception { String[] addresses = server.getActiveMQServer().getActiveMQServerControl().listTargetAddresses(sessionID); Map allDests = new HashMap(); Object[] queueControls = server.getActiveMQServer().getManagementService().getResources(JMSQueueControl.class); - for (Object queueControl2 : queueControls) - { + for (Object queueControl2 : queueControls) { JMSQueueControl queueControl = (JMSQueueControl) queueControl2; allDests.put(queueControl.getAddress(), queueControl); } Object[] topicControls = server.getActiveMQServer().getManagementService().getResources(TopicControl.class); - for (Object topicControl2 : topicControls) - { + for (Object topicControl2 : topicControls) { TopicControl topicControl = (TopicControl) topicControl2; allDests.put(topicControl.getAddress(), topicControl); } List destinations = new ArrayList(); - for (String addresse : addresses) - { + for (String addresse : addresses) { DestinationControl control = allDests.get(addresse); - if (control != null) - { + if (control != null) { destinations.add(control.getAddress()); } } return destinations.toArray(new String[0]); } - public String getLastSentMessageID(String sessionID, String address) throws Exception - { + public String getLastSentMessageID(String sessionID, String address) throws Exception { ServerSession session = server.getActiveMQServer().getSessionByID(sessionID); - if (session != null) - { + if (session != null) { return session.getLastSentMessageID(address); } return null; } - public String getSessionCreationTime(String sessionID) throws Exception - { + public String getSessionCreationTime(String sessionID) throws Exception { ServerSession session = server.getActiveMQServer().getSessionByID(sessionID); - if (session != null) - { + if (session != null) { return String.valueOf(session.getCreationTime()); } return null; } - public String listSessionsAsJSON(final String connectionID) throws Exception - { + public String listSessionsAsJSON(final String connectionID) throws Exception { checkStarted(); clearIO(); JSONArray array = new JSONArray(); - try - { + try { List sessions = server.getActiveMQServer().getSessions(connectionID); - for (ServerSession sess : sessions) - { + for (ServerSession sess : sessions) { JSONObject obj = new JSONObject(); obj.put("sessionID", sess.getName()); obj.put("creationTime", sess.getCreationTime()); array.put(obj); } } - finally - { + finally { blockOnIO(); } return array.toString(); } - public String closeConnectionWithClientID(final String clientID) throws Exception - { + public String closeConnectionWithClientID(final String clientID) throws Exception { return server.getActiveMQServer().destroyConnectionWithSessionMetadata(ClientSession.JMS_SESSION_CLIENT_ID_PROPERTY, clientID); } - private JSONObject toJSONObject(ServerConsumer consumer) throws Exception - { + private JSONObject toJSONObject(ServerConsumer consumer) throws Exception { JSONObject obj = new JSONObject(); obj.put("consumerID", consumer.getID()); obj.put("connectionID", consumer.getConnectionID()); @@ -1003,37 +786,28 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo obj.put("creationTime", consumer.getCreationTime()); // JMS consumer with message filter use the queue's filter Filter queueFilter = consumer.getQueue().getFilter(); - if (queueFilter != null) - { + if (queueFilter != null) { obj.put("filter", queueFilter.getFilterString().toString()); } String[] destinationInfo = determineJMSDestination(consumer.getQueue().getAddress().toString()); - if (destinationInfo == null) - { + if (destinationInfo == null) { return null; } obj.put("destinationName", destinationInfo[0]); obj.put("destinationType", destinationInfo[1]); - if (destinationInfo[1].equals("topic")) - { - try - { - ActiveMQDestination.decomposeQueueNameForDurableSubscription(consumer.getQueue() - .getName() - .toString()); + if (destinationInfo[1].equals("topic")) { + try { + ActiveMQDestination.decomposeQueueNameForDurableSubscription(consumer.getQueue().getName().toString()); obj.put("durable", true); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { obj.put("durable", false); } - catch (JMSRuntimeException e) - { + catch (JMSRuntimeException e) { obj.put("durable", false); } } - else - { + else { obj.put("durable", false); } @@ -1041,14 +815,13 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo } @Override - public void onNotification(org.apache.activemq.artemis.core.server.management.Notification notification) - { - if (!(notification.getType() instanceof JMSNotificationType)) return; + public void onNotification(org.apache.activemq.artemis.core.server.management.Notification notification) { + if (!(notification.getType() instanceof JMSNotificationType)) + return; JMSNotificationType type = (JMSNotificationType) notification.getType(); TypedProperties prop = notification.getProperties(); - this.broadcaster.sendNotification(new Notification(type.toString(), this, - notifSeq.incrementAndGet(), prop.getSimpleStringProperty(JMSNotificationType.MESSAGE).toString())); + this.broadcaster.sendNotification(new Notification(type.toString(), this, notifSeq.incrementAndGet(), prop.getSimpleStringProperty(JMSNotificationType.MESSAGE).toString())); } } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/management/impl/JMSTopicControlImpl.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/management/impl/JMSTopicControlImpl.java index 2c583cff25..213f243513 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/management/impl/JMSTopicControlImpl.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/management/impl/JMSTopicControlImpl.java @@ -40,8 +40,8 @@ import org.apache.activemq.artemis.jms.server.JMSServerManager; import org.apache.activemq.artemis.utils.json.JSONArray; import org.apache.activemq.artemis.utils.json.JSONObject; -public class JMSTopicControlImpl extends StandardMBean implements TopicControl -{ +public class JMSTopicControlImpl extends StandardMBean implements TopicControl { + private final ActiveMQDestination managedTopic; private final AddressControl addressControl; @@ -52,10 +52,8 @@ public class JMSTopicControlImpl extends StandardMBean implements TopicControl // Static -------------------------------------------------------- - public static String createFilterFromJMSSelector(final String selectorStr) throws ActiveMQException - { - return selectorStr == null || selectorStr.trim().length() == 0 ? null - : SelectorTranslator.convertToActiveMQFilterString(selectorStr); + public static String createFilterFromJMSSelector(final String selectorStr) throws ActiveMQException { + return selectorStr == null || selectorStr.trim().length() == 0 ? null : SelectorTranslator.convertToActiveMQFilterString(selectorStr); } // Constructors -------------------------------------------------- @@ -63,8 +61,7 @@ public class JMSTopicControlImpl extends StandardMBean implements TopicControl public JMSTopicControlImpl(final ActiveMQDestination topic, final JMSServerManager jmsServerManager, final AddressControl addressControl, - final ManagementService managementService) throws Exception - { + final ManagementService managementService) throws Exception { super(TopicControl.class); this.jmsServerManager = jmsServerManager; managedTopic = topic; @@ -75,118 +72,95 @@ public class JMSTopicControlImpl extends StandardMBean implements TopicControl // TopicControlMBean implementation ------------------------------ @Override - public void addBinding(String binding) throws Exception - { + public void addBinding(String binding) throws Exception { jmsServerManager.addTopicToBindingRegistry(managedTopic.getName(), binding); } - public String[] getRegistryBindings() - { + public String[] getRegistryBindings() { return jmsServerManager.getBindingsOnTopic(managedTopic.getName()); } - public String getName() - { + public String getName() { return managedTopic.getName(); } - public boolean isTemporary() - { + public boolean isTemporary() { return managedTopic.isTemporary(); } - public String getAddress() - { + public String getAddress() { return managedTopic.getAddress(); } - public long getMessageCount() - { + public long getMessageCount() { return getMessageCount(DurabilityType.ALL); } - public int getDeliveringCount() - { + public int getDeliveringCount() { List queues = getQueues(DurabilityType.ALL); int count = 0; - for (QueueControl queue : queues) - { + for (QueueControl queue : queues) { count += queue.getDeliveringCount(); } return count; } - public long getMessagesAdded() - { + public long getMessagesAdded() { List queues = getQueues(DurabilityType.ALL); int count = 0; - for (QueueControl queue : queues) - { + for (QueueControl queue : queues) { count += queue.getMessagesAdded(); } return count; } - public int getDurableMessageCount() - { + public int getDurableMessageCount() { return getMessageCount(DurabilityType.DURABLE); } - public int getNonDurableMessageCount() - { + public int getNonDurableMessageCount() { return getMessageCount(DurabilityType.NON_DURABLE); } - public int getSubscriptionCount() - { + public int getSubscriptionCount() { return getQueues(DurabilityType.ALL).size(); } - public int getDurableSubscriptionCount() - { + public int getDurableSubscriptionCount() { return getQueues(DurabilityType.DURABLE).size(); } - public int getNonDurableSubscriptionCount() - { + public int getNonDurableSubscriptionCount() { return getQueues(DurabilityType.NON_DURABLE).size(); } - public Object[] listAllSubscriptions() - { + public Object[] listAllSubscriptions() { return listSubscribersInfos(DurabilityType.ALL); } - public String listAllSubscriptionsAsJSON() throws Exception - { + public String listAllSubscriptionsAsJSON() throws Exception { return listSubscribersInfosAsJSON(DurabilityType.ALL); } - public Object[] listDurableSubscriptions() - { + public Object[] listDurableSubscriptions() { return listSubscribersInfos(DurabilityType.DURABLE); } - public String listDurableSubscriptionsAsJSON() throws Exception - { + public String listDurableSubscriptionsAsJSON() throws Exception { return listSubscribersInfosAsJSON(DurabilityType.DURABLE); } - public Object[] listNonDurableSubscriptions() - { + public Object[] listNonDurableSubscriptions() { return listSubscribersInfos(DurabilityType.NON_DURABLE); } - public String listNonDurableSubscriptionsAsJSON() throws Exception - { + public String listNonDurableSubscriptionsAsJSON() throws Exception { return listSubscribersInfosAsJSON(DurabilityType.NON_DURABLE); } - public Map[] listMessagesForSubscription(final String queueName) throws Exception - { - QueueControl coreQueueControl = (QueueControl)managementService.getResource(ResourceNames.CORE_QUEUE + queueName); - if (coreQueueControl == null) - { + public Map[] listMessagesForSubscription(final String queueName) throws Exception { + QueueControl coreQueueControl = (QueueControl) managementService.getResource(ResourceNames.CORE_QUEUE + queueName); + if (coreQueueControl == null) { throw new IllegalArgumentException("No subscriptions with name " + queueName); } @@ -196,40 +170,35 @@ public class JMSTopicControlImpl extends StandardMBean implements TopicControl int i = 0; - for (Map coreMessage : coreMessages) - { + for (Map coreMessage : coreMessages) { jmsMessages[i++] = ActiveMQMessage.coreMaptoJMSMap(coreMessage); } return jmsMessages; } - public String listMessagesForSubscriptionAsJSON(final String queueName) throws Exception - { + public String listMessagesForSubscriptionAsJSON(final String queueName) throws Exception { return JMSQueueControlImpl.toJSON(listMessagesForSubscription(queueName)); } - public int countMessagesForSubscription(final String clientID, final String subscriptionName, final String filterStr) throws Exception - { + public int countMessagesForSubscription(final String clientID, + final String subscriptionName, + final String filterStr) throws Exception { String queueName = ActiveMQDestination.createQueueNameForDurableSubscription(true, clientID, subscriptionName); - QueueControl coreQueueControl = (QueueControl)managementService.getResource(ResourceNames.CORE_QUEUE + queueName); - if (coreQueueControl == null) - { + QueueControl coreQueueControl = (QueueControl) managementService.getResource(ResourceNames.CORE_QUEUE + queueName); + if (coreQueueControl == null) { throw new IllegalArgumentException("No subscriptions with name " + queueName + " for clientID " + clientID); } String filter = JMSTopicControlImpl.createFilterFromJMSSelector(filterStr); return coreQueueControl.listMessages(filter).length; } - public int removeMessages(final String filterStr) throws Exception - { + public int removeMessages(final String filterStr) throws Exception { String filter = JMSTopicControlImpl.createFilterFromJMSSelector(filterStr); int count = 0; String[] queues = addressControl.getQueueNames(); - for (String queue : queues) - { - QueueControl coreQueueControl = (QueueControl)managementService.getResource(ResourceNames.CORE_QUEUE + queue); - if (coreQueueControl != null) - { + for (String queue : queues) { + QueueControl coreQueueControl = (QueueControl) managementService.getResource(ResourceNames.CORE_QUEUE + queue); + if (coreQueueControl != null) { count += coreQueueControl.removeMessages(filter); } } @@ -237,28 +206,23 @@ public class JMSTopicControlImpl extends StandardMBean implements TopicControl return count; } - public void dropDurableSubscription(final String clientID, final String subscriptionName) throws Exception - { + public void dropDurableSubscription(final String clientID, final String subscriptionName) throws Exception { String queueName = ActiveMQDestination.createQueueNameForDurableSubscription(true, clientID, subscriptionName); - QueueControl coreQueueControl = (QueueControl)managementService.getResource(ResourceNames.CORE_QUEUE + queueName); - if (coreQueueControl == null) - { + QueueControl coreQueueControl = (QueueControl) managementService.getResource(ResourceNames.CORE_QUEUE + queueName); + if (coreQueueControl == null) { throw new IllegalArgumentException("No subscriptions with name " + queueName + " for clientID " + clientID); } - ActiveMQServerControl serverControl = (ActiveMQServerControl)managementService.getResource(ResourceNames.CORE_SERVER); + ActiveMQServerControl serverControl = (ActiveMQServerControl) managementService.getResource(ResourceNames.CORE_SERVER); serverControl.destroyQueue(queueName); } - public void dropAllSubscriptions() throws Exception - { - ActiveMQServerControl serverControl = (ActiveMQServerControl)managementService.getResource(ResourceNames.CORE_SERVER); + public void dropAllSubscriptions() throws Exception { + ActiveMQServerControl serverControl = (ActiveMQServerControl) managementService.getResource(ResourceNames.CORE_SERVER); String[] queues = addressControl.getQueueNames(); - for (String queue : queues) - { + for (String queue : queues) { // Drop all subscription shouldn't delete the dummy queue used to identify if the topic exists on the core queues. // we will just ignore this queue - if (!queue.equals(managedTopic.getAddress())) - { + if (!queue.equals(managedTopic.getAddress())) { serverControl.destroyQueue(queue); } } @@ -270,20 +234,16 @@ public class JMSTopicControlImpl extends StandardMBean implements TopicControl // Private ------------------------------------------------------- - private Object[] listSubscribersInfos(final DurabilityType durability) - { + private Object[] listSubscribersInfos(final DurabilityType durability) { List queues = getQueues(durability); List subInfos = new ArrayList(queues.size()); - for (QueueControl queue : queues) - { + for (QueueControl queue : queues) { String clientID = null; String subName = null; - if (queue.isDurable()) - { - Pair pair = ActiveMQDestination.decomposeQueueNameForDurableSubscription(queue.getName() - .toString()); + if (queue.isDurable()) { + Pair pair = ActiveMQDestination.decomposeQueueNameForDurableSubscription(queue.getName().toString()); clientID = pair.getA(); subName = pair.getB(); } @@ -302,27 +262,21 @@ public class JMSTopicControlImpl extends StandardMBean implements TopicControl return subInfos.toArray(new Object[subInfos.size()]); } - private String listSubscribersInfosAsJSON(final DurabilityType durability) throws Exception - { - try - { + private String listSubscribersInfosAsJSON(final DurabilityType durability) throws Exception { + try { List queues = getQueues(durability); JSONArray array = new JSONArray(); - for (QueueControl queue : queues) - { + for (QueueControl queue : queues) { String clientID = null; String subName = null; - if (queue.isDurable() && !queue.getName().startsWith(ResourceNames.JMS_TOPIC)) - { - Pair pair = ActiveMQDestination.decomposeQueueNameForDurableSubscription(queue.getName() - .toString()); + if (queue.isDurable() && !queue.getName().startsWith(ResourceNames.JMS_TOPIC)) { + Pair pair = ActiveMQDestination.decomposeQueueNameForDurableSubscription(queue.getName().toString()); clientID = pair.getA(); subName = pair.getB(); } - else if (queue.getName().startsWith(ResourceNames.JMS_TOPIC)) - { + else if (queue.getName().startsWith(ResourceNames.JMS_TOPIC)) { // in the case of heirarchical topics the queue name will not follow the . pattern of normal // durable subscribers so skip decomposing the name for the client ID and subscription name and just // hard-code it @@ -341,76 +295,58 @@ public class JMSTopicControlImpl extends StandardMBean implements TopicControl info.put("durable", queue.isDurable()); info.put("messageCount", queue.getMessageCount()); info.put("deliveringCount", queue.getDeliveringCount()); - info.put("consumers", new JSONArray(queue.listConsumersAsJSON()) ); + info.put("consumers", new JSONArray(queue.listConsumersAsJSON())); array.put(info); } return array.toString(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); return e.toString(); } } - private int getMessageCount(final DurabilityType durability) - { + private int getMessageCount(final DurabilityType durability) { List queues = getQueues(durability); int count = 0; - for (QueueControl queue : queues) - { + for (QueueControl queue : queues) { count += queue.getMessageCount(); } return count; } - private List getQueues(final DurabilityType durability) - { - try - { + private List getQueues(final DurabilityType durability) { + try { List matchingQueues = new ArrayList(); String[] queues = addressControl.getQueueNames(); - for (String queue : queues) - { - QueueControl coreQueueControl = (QueueControl)managementService.getResource(ResourceNames.CORE_QUEUE + queue); + for (String queue : queues) { + QueueControl coreQueueControl = (QueueControl) managementService.getResource(ResourceNames.CORE_QUEUE + queue); // Ignore the "special" subscription - if (coreQueueControl != null && !coreQueueControl.getName().equals(addressControl.getAddress())) - { - if (durability == DurabilityType.ALL || durability == DurabilityType.DURABLE && - coreQueueControl.isDurable() || - durability == DurabilityType.NON_DURABLE && - !coreQueueControl.isDurable()) - { + if (coreQueueControl != null && !coreQueueControl.getName().equals(addressControl.getAddress())) { + if (durability == DurabilityType.ALL || durability == DurabilityType.DURABLE && coreQueueControl.isDurable() || + durability == DurabilityType.NON_DURABLE && !coreQueueControl.isDurable()) { matchingQueues.add(coreQueueControl); } } } return matchingQueues; } - catch (Exception e) - { + catch (Exception e) { return Collections.emptyList(); } } @Override - public MBeanInfo getMBeanInfo() - { + public MBeanInfo getMBeanInfo() { MBeanInfo info = super.getMBeanInfo(); - return new MBeanInfo(info.getClassName(), - info.getDescription(), - info.getAttributes(), - info.getConstructors(), - MBeanInfoHelper.getMBeanOperationsInfo(TopicControl.class), - info.getNotifications()); + return new MBeanInfo(info.getClassName(), info.getDescription(), info.getAttributes(), info.getConstructors(), MBeanInfoHelper.getMBeanOperationsInfo(TopicControl.class), info.getNotifications()); } // Inner classes ------------------------------------------------- - private enum DurabilityType - { + private enum DurabilityType { ALL, DURABLE, NON_DURABLE } } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/JMSStorageManager.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/JMSStorageManager.java index 278fb3831c..5a084e41d6 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/JMSStorageManager.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/JMSStorageManager.java @@ -24,8 +24,7 @@ import org.apache.activemq.artemis.jms.persistence.config.PersistedDestination; import org.apache.activemq.artemis.jms.persistence.config.PersistedBindings; import org.apache.activemq.artemis.jms.persistence.config.PersistedType; -public interface JMSStorageManager extends ActiveMQComponent -{ +public interface JMSStorageManager extends ActiveMQComponent { void load() throws Exception; diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/config/PersistedBindings.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/config/PersistedBindings.java index 6528c10a39..bdf999b2f5 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/config/PersistedBindings.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/config/PersistedBindings.java @@ -24,8 +24,7 @@ import org.apache.activemq.artemis.core.journal.EncodingSupport; import org.apache.activemq.artemis.utils.BufferHelper; import org.apache.activemq.artemis.utils.DataConstants; -public class PersistedBindings implements EncodingSupport -{ +public class PersistedBindings implements EncodingSupport { // Constants ----------------------------------------------------- @@ -43,16 +42,14 @@ public class PersistedBindings implements EncodingSupport // Constructors -------------------------------------------------- - public PersistedBindings() - { + public PersistedBindings() { } /** * @param type * @param name */ - public PersistedBindings(PersistedType type, String name) - { + public PersistedBindings(PersistedType type, String name) { super(); this.type = type; this.name = name; @@ -60,45 +57,38 @@ public class PersistedBindings implements EncodingSupport // Public -------------------------------------------------------- @Override - public void decode(ActiveMQBuffer buffer) - { + public void decode(ActiveMQBuffer buffer) { type = PersistedType.getType(buffer.readByte()); name = buffer.readSimpleString().toString(); int bindingArraySize = buffer.readInt(); bindings = new ArrayList(bindingArraySize); - for (int i = 0; i < bindingArraySize; i++) - { + for (int i = 0; i < bindingArraySize; i++) { bindings.add(buffer.readSimpleString().toString()); } } @Override - public void encode(ActiveMQBuffer buffer) - { + public void encode(ActiveMQBuffer buffer) { buffer.writeByte(type.getType()); BufferHelper.writeAsSimpleString(buffer, name); buffer.writeInt(bindings.size()); - for (String bindingsEl : bindings) - { + for (String bindingsEl : bindings) { BufferHelper.writeAsSimpleString(buffer, bindingsEl); } } @Override - public int getEncodeSize() - { + public int getEncodeSize() { return DataConstants.SIZE_BYTE + BufferHelper.sizeOfSimpleString(name) + sizeOfBindings(); } - private int sizeOfBindings() - { + private int sizeOfBindings() { int size = DataConstants.SIZE_INT; // for the number of elements written - for (String str : bindings) - { + for (String str : bindings) { size += BufferHelper.sizeOfSimpleString(str); } @@ -108,50 +98,43 @@ public class PersistedBindings implements EncodingSupport /** * @return the id */ - public long getId() - { + public long getId() { return id; } /** * @param id the id to set */ - public void setId(long id) - { + public void setId(long id) { this.id = id; } /** * @return the type */ - public PersistedType getType() - { + public PersistedType getType() { return type; } /** * @return the name */ - public String getName() - { + public String getName() { return name; } /** * @return the bindings */ - public List getBindings() - { + public List getBindings() { return bindings; } - public void addBinding(String address) - { + public void addBinding(String address) { bindings.add(address); } - public void deleteBinding(String address) - { + public void deleteBinding(String address) { bindings.remove(address); } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/config/PersistedConnectionFactory.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/config/PersistedConnectionFactory.java index 406cb573bd..3e7e100e1b 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/config/PersistedConnectionFactory.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/config/PersistedConnectionFactory.java @@ -21,8 +21,7 @@ import org.apache.activemq.artemis.core.journal.EncodingSupport; import org.apache.activemq.artemis.jms.server.config.ConnectionFactoryConfiguration; import org.apache.activemq.artemis.jms.server.config.impl.ConnectionFactoryConfigurationImpl; -public class PersistedConnectionFactory implements EncodingSupport -{ +public class PersistedConnectionFactory implements EncodingSupport { // Constants ----------------------------------------------------- @@ -32,16 +31,14 @@ public class PersistedConnectionFactory implements EncodingSupport private ConnectionFactoryConfiguration config; - public PersistedConnectionFactory() - { + public PersistedConnectionFactory() { super(); } /** * @param config */ - public PersistedConnectionFactory(final ConnectionFactoryConfiguration config) - { + public PersistedConnectionFactory(final ConnectionFactoryConfiguration config) { super(); this.config = config; } @@ -55,45 +52,38 @@ public class PersistedConnectionFactory implements EncodingSupport /** * @return the id */ - public long getId() - { + public long getId() { return id; } - public void setId(final long id) - { + public void setId(final long id) { this.id = id; } - public String getName() - { + public String getName() { return config.getName(); } /** * @return the config */ - public ConnectionFactoryConfiguration getConfig() - { + public ConnectionFactoryConfiguration getConfig() { return config; } @Override - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { config = new ConnectionFactoryConfigurationImpl(); config.decode(buffer); } @Override - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { config.encode(buffer); } @Override - public int getEncodeSize() - { + public int getEncodeSize() { return config.getEncodeSize(); } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/config/PersistedDestination.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/config/PersistedDestination.java index b66babae56..a1097fe61c 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/config/PersistedDestination.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/config/PersistedDestination.java @@ -22,9 +22,7 @@ import org.apache.activemq.artemis.core.journal.EncodingSupport; import org.apache.activemq.artemis.utils.BufferHelper; import org.apache.activemq.artemis.utils.DataConstants; -public class PersistedDestination implements EncodingSupport -{ - +public class PersistedDestination implements EncodingSupport { // Constants ----------------------------------------------------- @@ -43,17 +41,17 @@ public class PersistedDestination implements EncodingSupport // Constructors -------------------------------------------------- - public PersistedDestination() - { + public PersistedDestination() { } - public PersistedDestination(final PersistedType type, final String name) - { + public PersistedDestination(final PersistedType type, final String name) { this(type, name, null, true); } - public PersistedDestination(final PersistedType type, final String name, final String selector, final boolean durable) - { + public PersistedDestination(final PersistedType type, + final String name, + final String selector, + final boolean durable) { this.type = type; this.name = name; this.selector = selector; @@ -69,55 +67,45 @@ public class PersistedDestination implements EncodingSupport // Inner classes ------------------------------------------------- - - public long getId() - { + public long getId() { return id; } - public void setId(final long id) - { + public void setId(final long id) { this.id = id; } - public String getName() - { + public String getName() { return name; } - public PersistedType getType() - { + public PersistedType getType() { return type; } - public String getSelector() - { + public String getSelector() { return selector; } - public boolean isDurable() - { + public boolean isDurable() { return durable; } - public int getEncodeSize() - { + public int getEncodeSize() { return DataConstants.SIZE_BYTE + - BufferHelper.sizeOfSimpleString(name) + - BufferHelper.sizeOfNullableSimpleString(selector) + - DataConstants.SIZE_BOOLEAN; + BufferHelper.sizeOfSimpleString(name) + + BufferHelper.sizeOfNullableSimpleString(selector) + + DataConstants.SIZE_BOOLEAN; } - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { buffer.writeByte(type.getType()); buffer.writeSimpleString(SimpleString.toSimpleString(name)); buffer.writeNullableSimpleString(SimpleString.toSimpleString(selector)); buffer.writeBoolean(durable); } - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { type = PersistedType.getType(buffer.readByte()); name = buffer.readSimpleString().toString(); SimpleString selectorStr = buffer.readNullableSimpleString(); diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/config/PersistedType.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/config/PersistedType.java index beeff60323..b7e52b10d5 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/config/PersistedType.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/config/PersistedType.java @@ -16,14 +16,11 @@ */ package org.apache.activemq.artemis.jms.persistence.config; -public enum PersistedType -{ +public enum PersistedType { ConnectionFactory, Topic, Queue; - public byte getType() - { - switch (this) - { + public byte getType() { + switch (this) { case ConnectionFactory: return 0; case Topic: @@ -35,10 +32,8 @@ public enum PersistedType } } - public static PersistedType getType(byte type) - { - switch (type) - { + public static PersistedType getType(byte type) { + switch (type) { case 0: return ConnectionFactory; case 1: diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/impl/journal/JMSJournalStorageManagerImpl.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/impl/journal/JMSJournalStorageManagerImpl.java index 2d884e7aec..7d7c37d844 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/impl/journal/JMSJournalStorageManagerImpl.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/impl/journal/JMSJournalStorageManagerImpl.java @@ -42,8 +42,7 @@ import org.apache.activemq.artemis.jms.persistence.config.PersistedBindings; import org.apache.activemq.artemis.jms.persistence.config.PersistedType; import org.apache.activemq.artemis.utils.IDGenerator; -public final class JMSJournalStorageManagerImpl implements JMSStorageManager -{ +public final class JMSJournalStorageManagerImpl implements JMSStorageManager { // Constants ----------------------------------------------------- @@ -76,10 +75,8 @@ public final class JMSJournalStorageManagerImpl implements JMSStorageManager // Constructors -------------------------------------------------- public JMSJournalStorageManagerImpl(final IDGenerator idGenerator, final Configuration config, - final ReplicationManager replicator) - { - if (config.getJournalType() != JournalType.NIO && config.getJournalType() != JournalType.ASYNCIO) - { + final ReplicationManager replicator) { + if (config.getJournalType() != JournalType.NIO && config.getJournalType() != JournalType.ASYNCIO) { throw new IllegalArgumentException("Only NIO and AsyncIO are supported journals"); } @@ -89,39 +86,27 @@ public final class JMSJournalStorageManagerImpl implements JMSStorageManager SequentialFileFactory bindingsJMS = new NIOSequentialFileFactory(config.getBindingsLocation(), 1); - Journal localJMS = new JournalImpl(1024 * 1024, - 2, - config.getJournalCompactMinFiles(), - config.getJournalCompactPercentage(), - bindingsJMS, - "activemq-jms", - "jms", - 1); + Journal localJMS = new JournalImpl(1024 * 1024, 2, config.getJournalCompactMinFiles(), config.getJournalCompactPercentage(), bindingsJMS, "activemq-jms", "jms", 1); - if (replicator != null) - { + if (replicator != null) { jmsJournal = new ReplicatedJournal((byte) 2, localJMS, replicator); } - else - { + else { jmsJournal = localJMS; } this.idGenerator = idGenerator; } - // Public -------------------------------------------------------- @Override - public List recoverConnectionFactories() - { + public List recoverConnectionFactories() { List cfs = new ArrayList(mapFactories.values()); return cfs; } @Override - public void storeConnectionFactory(final PersistedConnectionFactory connectionFactory) throws Exception - { + public void storeConnectionFactory(final PersistedConnectionFactory connectionFactory) throws Exception { deleteConnectionFactory(connectionFactory.getName()); long id = idGenerator.generateID(); connectionFactory.setId(id); @@ -129,25 +114,21 @@ public final class JMSJournalStorageManagerImpl implements JMSStorageManager mapFactories.put(connectionFactory.getName(), connectionFactory); } - public void deleteConnectionFactory(final String cfName) throws Exception - { + public void deleteConnectionFactory(final String cfName) throws Exception { PersistedConnectionFactory oldCF = mapFactories.remove(cfName); - if (oldCF != null) - { + if (oldCF != null) { jmsJournal.appendDeleteRecord(oldCF.getId(), false); } } @Override - public List recoverDestinations() - { + public List recoverDestinations() { List destinations = new ArrayList(this.destinations.values()); return destinations; } @Override - public void storeDestination(final PersistedDestination destination) throws Exception - { + public void storeDestination(final PersistedDestination destination) throws Exception { deleteDestination(destination.getType(), destination.getName()); long id = idGenerator.generateID(); destination.setId(id); @@ -155,36 +136,30 @@ public final class JMSJournalStorageManagerImpl implements JMSStorageManager destinations.put(new Pair(destination.getType(), destination.getName()), destination); } - public List recoverPersistedBindings() throws Exception - { + public List recoverPersistedBindings() throws Exception { ArrayList list = new ArrayList(mapBindings.values()); return list; } - public void addBindings(PersistedType type, String name, String... address) throws Exception - { + public void addBindings(PersistedType type, String name, String... address) throws Exception { Pair key = new Pair(type, name); long tx = idGenerator.generateID(); PersistedBindings currentBindings = mapBindings.get(key); - if (currentBindings != null) - { + if (currentBindings != null) { jmsJournal.appendDeleteRecordTransactional(tx, currentBindings.getId()); } - else - { + else { currentBindings = new PersistedBindings(type, name); } mapBindings.put(key, currentBindings); - for (String adItem : address) - { + for (String adItem : address) { currentBindings.addBinding(adItem); } - long newId = idGenerator.generateID(); currentBindings.setId(newId); @@ -194,30 +169,25 @@ public final class JMSJournalStorageManagerImpl implements JMSStorageManager jmsJournal.appendCommitRecord(tx, true); } - public void deleteBindings(PersistedType type, String name, String address) throws Exception - { + public void deleteBindings(PersistedType type, String name, String address) throws Exception { Pair key = new Pair(type, name); long tx = idGenerator.generateID(); PersistedBindings currentBindings = mapBindings.get(key); - if (currentBindings == null) - { + if (currentBindings == null) { return; } - else - { + else { jmsJournal.appendDeleteRecordTransactional(tx, currentBindings.getId()); } currentBindings.deleteBinding(address); - if (currentBindings.getBindings().size() == 0) - { + if (currentBindings.getBindings().size() == 0) { mapBindings.remove(key); } - else - { + else { long newId = idGenerator.generateID(); currentBindings.setId(newId); jmsJournal.appendAddRecordTransactional(tx, newId, BINDING_RECORD, currentBindings); @@ -226,38 +196,30 @@ public final class JMSJournalStorageManagerImpl implements JMSStorageManager jmsJournal.appendCommitRecord(tx, true); } - - public void deleteBindings(PersistedType type, String name) throws Exception - { + public void deleteBindings(PersistedType type, String name) throws Exception { Pair key = new Pair(type, name); PersistedBindings currentBindings = mapBindings.remove(key); - if (currentBindings != null) - { + if (currentBindings != null) { jmsJournal.appendDeleteRecord(currentBindings.getId(), true); } } - public void deleteDestination(final PersistedType type, final String name) throws Exception - { + public void deleteDestination(final PersistedType type, final String name) throws Exception { PersistedDestination destination = destinations.remove(new Pair(type, name)); - if (destination != null) - { + if (destination != null) { jmsJournal.appendDeleteRecord(destination.getId(), false); } } @Override - public boolean isStarted() - { + public boolean isStarted() { return started; } - @Override - public void start() throws Exception - { + public void start() throws Exception { checkAndCreateDir(config.getBindingsLocation(), createDir); jmsJournal.start(); @@ -266,14 +228,12 @@ public final class JMSJournalStorageManagerImpl implements JMSStorageManager } @Override - public void stop() throws Exception - { + public void stop() throws Exception { this.started = false; jmsJournal.stop(); } - public void load() throws Exception - { + public void load() throws Exception { mapFactories.clear(); List data = new ArrayList(); @@ -282,38 +242,33 @@ public final class JMSJournalStorageManagerImpl implements JMSStorageManager jmsJournal.load(data, list, null); - for (RecordInfo record : data) - { + for (RecordInfo record : data) { long id = record.id; ActiveMQBuffer buffer = ActiveMQBuffers.wrappedBuffer(record.data); byte rec = record.getUserRecordType(); - if (rec == CF_RECORD) - { + if (rec == CF_RECORD) { PersistedConnectionFactory cf = new PersistedConnectionFactory(); cf.decode(buffer); cf.setId(id); mapFactories.put(cf.getName(), cf); } - else if (rec == DESTINATION_RECORD) - { + else if (rec == DESTINATION_RECORD) { PersistedDestination destination = new PersistedDestination(); destination.decode(buffer); destination.setId(id); destinations.put(new Pair(destination.getType(), destination.getName()), destination); } - else if (rec == BINDING_RECORD) - { + else if (rec == BINDING_RECORD) { PersistedBindings bindings = new PersistedBindings(); bindings.decode(buffer); bindings.setId(id); Pair key = new Pair(bindings.getType(), bindings.getName()); mapBindings.put(key, bindings); } - else - { + else { throw new IllegalStateException("Invalid record type " + rec); } @@ -327,27 +282,20 @@ public final class JMSJournalStorageManagerImpl implements JMSStorageManager // Private ------------------------------------------------------- + private void checkAndCreateDir(final File dir, final boolean create) { - private void checkAndCreateDir(final File dir, final boolean create) - { - - if (!dir.exists()) - { - if (create) - { - if (!dir.mkdirs()) - { + if (!dir.exists()) { + if (create) { + if (!dir.mkdirs()) { throw new IllegalStateException("Failed to create directory " + dir); } } - else - { + else { throw new IllegalArgumentException("Directory " + dir + " does not exist and will not create it"); } } } - // Inner classes ------------------------------------------------- } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/impl/nullpm/NullJMSStorageManagerImpl.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/impl/nullpm/NullJMSStorageManagerImpl.java index 0816379335..d1b69c171f 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/impl/nullpm/NullJMSStorageManagerImpl.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/persistence/impl/nullpm/NullJMSStorageManagerImpl.java @@ -25,81 +25,66 @@ import org.apache.activemq.artemis.jms.persistence.config.PersistedDestination; import org.apache.activemq.artemis.jms.persistence.config.PersistedBindings; import org.apache.activemq.artemis.jms.persistence.config.PersistedType; -public class NullJMSStorageManagerImpl implements JMSStorageManager -{ +public class NullJMSStorageManagerImpl implements JMSStorageManager { @Override - public void deleteConnectionFactory(String connectionFactory) throws Exception - { + public void deleteConnectionFactory(String connectionFactory) throws Exception { } @Override - public List recoverConnectionFactories() - { + public List recoverConnectionFactories() { return Collections.emptyList(); } @Override - public List recoverDestinations() - { + public List recoverDestinations() { return Collections.emptyList(); } @Override - public void storeConnectionFactory(PersistedConnectionFactory connectionFactory) throws Exception - { + public void storeConnectionFactory(PersistedConnectionFactory connectionFactory) throws Exception { } @Override - public void storeDestination(PersistedDestination destination) - { + public void storeDestination(PersistedDestination destination) { } @Override - public boolean isStarted() - { + public boolean isStarted() { return true; } @Override - public void start() throws Exception - { + public void start() throws Exception { } @Override - public void stop() throws Exception - { + public void stop() throws Exception { } @Override - public void addBindings(PersistedType type, String name, String... address) throws Exception - { + public void addBindings(PersistedType type, String name, String... address) throws Exception { } @Override - public void deleteBindings(PersistedType type, String name, String address) throws Exception - { + public void deleteBindings(PersistedType type, String name, String address) throws Exception { } @Override - public void deleteDestination(PersistedType type, String name) throws Exception - { + public void deleteDestination(PersistedType type, String name) throws Exception { } @Override - public void deleteBindings(PersistedType type, String name) throws Exception - { + public void deleteBindings(PersistedType type, String name) throws Exception { } @Override - public List recoverPersistedBindings() throws Exception - { + public List recoverPersistedBindings() throws Exception { return Collections.emptyList(); } @Override - public void load() throws Exception - { + public void load() throws Exception { } } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/ActiveMQJMSServerBundle.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/ActiveMQJMSServerBundle.java index 11a2ed722a..e591fa47f5 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/ActiveMQJMSServerBundle.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/ActiveMQJMSServerBundle.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.jms.server; - import org.apache.activemq.artemis.api.core.ActiveMQAddressExistsException; import org.apache.activemq.artemis.api.core.ActiveMQIllegalStateException; import org.apache.activemq.artemis.api.core.ActiveMQInternalErrorException; @@ -33,11 +32,11 @@ import org.jboss.logging.Messages; * so 129000 to 129999 */ @MessageBundle(projectCode = "AMQ") -public interface ActiveMQJMSServerBundle -{ +public interface ActiveMQJMSServerBundle { + ActiveMQJMSServerBundle BUNDLE = Messages.getBundle(ActiveMQJMSServerBundle.class); - @Message(id = 129000, value = "Connection Factory {0} does not exist" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 129000, value = "Connection Factory {0} does not exist", format = Message.Format.MESSAGE_FORMAT) ActiveMQInternalErrorException cfDoesntExist(String name); @Message(id = 129003, value = "Discovery Group ''{0}'' does not exist on main config", format = Message.Format.MESSAGE_FORMAT) @@ -46,10 +45,10 @@ public interface ActiveMQJMSServerBundle @Message(id = 129004, value = "No Connector name configured on create ConnectionFactory") ActiveMQIllegalStateException noConnectorNameOnCF(); - @Message(id = 129005, value = "Connector ''{0}'' not found on the main configuration file" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 129005, value = "Connector ''{0}'' not found on the main configuration file", format = Message.Format.MESSAGE_FORMAT) ActiveMQIllegalStateException noConnectorNameConfiguredOnCF(String name); - @Message(id = 129006, value = "Binding {0} is already being used by another connection factory", format = Message.Format.MESSAGE_FORMAT) + @Message(id = 129006, value = "Binding {0} is already being used by another connection factory", format = Message.Format.MESSAGE_FORMAT) ActiveMQAddressExistsException cfBindingsExists(String name); @Message(id = 129007, value = "Error decoding password using codec instance") diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/ActiveMQJMSServerLogger.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/ActiveMQJMSServerLogger.java index 3e818662ec..d17add914d 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/ActiveMQJMSServerLogger.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/ActiveMQJMSServerLogger.java @@ -40,8 +40,8 @@ import org.w3c.dom.Node; * so an INFO message would be 121000 to 121999 */ @MessageLogger(projectCode = "AMQ") -public interface ActiveMQJMSServerLogger extends BasicLogger -{ +public interface ActiveMQJMSServerLogger extends BasicLogger { + /** * The default logger. */ @@ -49,65 +49,64 @@ public interface ActiveMQJMSServerLogger extends BasicLogger @LogMessage(level = Logger.Level.INFO) @Message(id = 121004, value = "JMS Server Manager Caching command for {0} since the JMS Server is not active yet", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void serverCachingCommand(Object runnable); @LogMessage(level = Logger.Level.INFO) @Message(id = 121005, value = "Invalid \"host\" value \"0.0.0.0\" detected for \"{0}\" connector. Switching to \"{1}\". If this new address is incorrect please manually configure the connector to use the proper one.", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void invalidHostForConnector(String name, String newHost); @LogMessage(level = Logger.Level.WARN) - @Message(id = 122007, value = "Queue {0} does not exist on the topic {1}. It was deleted manually probably." , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 122007, value = "Queue {0} does not exist on the topic {1}. It was deleted manually probably.", format = Message.Format.MESSAGE_FORMAT) void noQueueOnTopic(String queueName, String name); @LogMessage(level = Logger.Level.WARN) - @Message(id = 122008, value = "XA Recovery can not connect to any broker on recovery {0}" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 122008, value = "XA Recovery can not connect to any broker on recovery {0}", format = Message.Format.MESSAGE_FORMAT) void recoveryConnectFailed(String s); @LogMessage(level = Logger.Level.WARN) - @Message(id = 122011, value = "error unbinding {0} from Registry" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 122011, value = "error unbinding {0} from Registry", format = Message.Format.MESSAGE_FORMAT) void bindingsUnbindError(@Cause Exception e, String key); @LogMessage(level = Logger.Level.WARN) - @Message(id = 122012, value = "JMS Server Manager error" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 122012, value = "JMS Server Manager error", format = Message.Format.MESSAGE_FORMAT) void jmsServerError(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) - @Message(id = 122013, value = "Error in XA Recovery recover" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 122013, value = "Error in XA Recovery recover", format = Message.Format.MESSAGE_FORMAT) void xaRecoverError(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 122014, value = "Notified of connection failure in xa recovery connectionFactory for provider {0} will attempt reconnect on next pass", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void xaRecoverConnectionError(@Cause Exception e, ClientSessionFactory csf); @LogMessage(level = Logger.Level.DEBUG) - @Message(id = 122016, value = "Error in XA Recovery" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 122016, value = "Error in XA Recovery", format = Message.Format.MESSAGE_FORMAT) void xaRecoveryError(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 122017, value = "Tried to correct invalid \"host\" value \"0.0.0.0\" for \"{0}\" connector, but received an exception.", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void failedToCorrectHost(@Cause Exception e, String name); @LogMessage(level = Logger.Level.WARN) @Message(id = 122018, - value = "Failed to send notification: {0}", - format = Message.Format.MESSAGE_FORMAT) + value = "Failed to send notification: {0}", + format = Message.Format.MESSAGE_FORMAT) void failedToSendNotification(String notification); @LogMessage(level = Logger.Level.DEBUG) - @Message(id = 123000, value = "JMS Server Manager Running cached command for {0}." + - "(In the event of failover after failback has occurred, this message may be output multiple times.)", - format = Message.Format.MESSAGE_FORMAT) + @Message(id = 123000, value = "JMS Server Manager Running cached command for {0}." + "(In the event of failover after failback has occurred, this message may be output multiple times.)", + format = Message.Format.MESSAGE_FORMAT) void serverRunningCachedCommand(Runnable run); @LogMessage(level = Logger.Level.ERROR) - @Message(id = 124000, value = "key attribute missing for JMS configuration {0}" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 124000, value = "key attribute missing for JMS configuration {0}", format = Message.Format.MESSAGE_FORMAT) void jmsConfigMissingKey(Node e); @LogMessage(level = Logger.Level.ERROR) - @Message(id = 124002, value = "Failed to start JMS deployer" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 124002, value = "Failed to start JMS deployer", format = Message.Format.MESSAGE_FORMAT) void jmsDeployerStartError(@Cause Exception e); } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/JMSServerConfigParser.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/JMSServerConfigParser.java index d740e1ae13..3ca65fe060 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/JMSServerConfigParser.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/JMSServerConfigParser.java @@ -23,8 +23,8 @@ import org.apache.activemq.artemis.jms.server.config.JMSQueueConfiguration; import org.apache.activemq.artemis.jms.server.config.TopicConfiguration; import org.w3c.dom.Node; -public interface JMSServerConfigParser -{ +public interface JMSServerConfigParser { + /** * Parse the JMS Configuration XML as a JMSConfiguration object */ @@ -37,6 +37,7 @@ public interface JMSServerConfigParser /** * Parse the topic node as a TopicConfiguration object + * * @param node * @return {@link TopicConfiguration} parsed from the node * @throws Exception @@ -45,6 +46,7 @@ public interface JMSServerConfigParser /** * Parse the Queue Configuration node as a QueueConfiguration object + * * @param node * @return {@link JMSQueueConfiguration} parsed from the node * @throws Exception diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/JMSServerManager.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/JMSServerManager.java index 718254317d..7f6bb88d2f 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/JMSServerManager.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/JMSServerManager.java @@ -31,8 +31,8 @@ import org.apache.activemq.artemis.spi.core.naming.BindingRegistry; /** * The JMS Management interface. */ -public interface JMSServerManager extends ActiveMQComponent -{ +public interface JMSServerManager extends ActiveMQComponent { + String getVersion(); /** @@ -45,16 +45,18 @@ public interface JMSServerManager extends ActiveMQComponent /** * Creates a JMS Queue. * - * @param queueName - * The name of the queue to create + * @param queueName The name of the queue to create * @param selectorString * @param durable * @return true if the queue is created or if it existed and was added to - * the Binding Registry - * @throws Exception - * if problems were encountered creating the queue. + * the Binding Registry + * @throws Exception if problems were encountered creating the queue. */ - boolean createQueue(boolean storeConfig, String queueName, String selectorString, boolean durable, String ...bindings) throws Exception; + boolean createQueue(boolean storeConfig, + String queueName, + String selectorString, + boolean durable, + String... bindings) throws Exception; boolean addTopicToBindingRegistry(final String topicName, final String binding) throws Exception; @@ -65,26 +67,21 @@ public interface JMSServerManager extends ActiveMQComponent /** * Creates a JMS Topic * - * @param topicName - * the name of the topic - * @param bindings - * the names of the binding for the Binding Registry or BindingRegistry + * @param topicName the name of the topic + * @param bindings the names of the binding for the Binding Registry or BindingRegistry * @return true if the topic was created or if it existed and was added to - * the Binding Registry - * @throws Exception - * if a problem occurred creating the topic + * the Binding Registry + * @throws Exception if a problem occurred creating the topic */ - boolean createTopic(boolean storeConfig, String topicName, String ... bindings) throws Exception; + boolean createTopic(boolean storeConfig, String topicName, String... bindings) throws Exception; /** * Remove the topic from the Binding Registry or BindingRegistry. * Calling this method does not destroy the destination. * - * @param name - * the name of the destination to remove from the BindingRegistry + * @param name the name of the destination to remove from the BindingRegistry * @return true if removed - * @throws Exception - * if a problem occurred removing the destination + * @throws Exception if a problem occurred removing the destination */ boolean removeTopicFromBindingRegistry(String name, String binding) throws Exception; @@ -92,11 +89,9 @@ public interface JMSServerManager extends ActiveMQComponent * Remove the topic from the BindingRegistry. * Calling this method does not destroy the destination. * - * @param name - * the name of the destination to remove from the BindingRegistry + * @param name the name of the destination to remove from the BindingRegistry * @return true if removed - * @throws Exception - * if a problem occurred removing the destination + * @throws Exception if a problem occurred removing the destination */ boolean removeTopicFromBindingRegistry(String name) throws Exception; @@ -104,11 +99,9 @@ public interface JMSServerManager extends ActiveMQComponent * Remove the queue from the BindingRegistry. * Calling this method does not destroy the destination. * - * @param name - * the name of the destination to remove from the BindingRegistry + * @param name the name of the destination to remove from the BindingRegistry * @return true if removed - * @throws Exception - * if a problem occurred removing the destination + * @throws Exception if a problem occurred removing the destination */ boolean removeQueueFromBindingRegistry(String name, String binding) throws Exception; @@ -116,11 +109,9 @@ public interface JMSServerManager extends ActiveMQComponent * Remove the queue from the BindingRegistry. * Calling this method does not destroy the destination. * - * @param name - * the name of the destination to remove from the BindingRegistry + * @param name the name of the destination to remove from the BindingRegistry * @return true if removed - * @throws Exception - * if a problem occurred removing the destination + * @throws Exception if a problem occurred removing the destination */ boolean removeQueueFromBindingRegistry(String name) throws Exception; @@ -131,11 +122,9 @@ public interface JMSServerManager extends ActiveMQComponent /** * destroys a queue and removes it from the BindingRegistry * - * @param name - * the name of the queue to destroy + * @param name the name of the queue to destroy * @return true if destroyed - * @throws Exception - * if a problem occurred destroying the queue + * @throws Exception if a problem occurred destroying the queue */ boolean destroyQueue(String name) throws Exception; @@ -143,11 +132,9 @@ public interface JMSServerManager extends ActiveMQComponent * destroys a queue and removes it from the BindingRegistry. * disconnects any consumers connected to the queue. * - * @param name - * the name of the queue to destroy + * @param name the name of the queue to destroy * @return true if destroyed - * @throws Exception - * if a problem occurred destroying the queue + * @throws Exception if a problem occurred destroying the queue */ boolean destroyQueue(String name, boolean removeConsumers) throws Exception; @@ -160,36 +147,39 @@ public interface JMSServerManager extends ActiveMQComponent /** * destroys a topic and removes it from the BindingRegistry * - * @param name - * the name of the topic to destroy + * @param name the name of the topic to destroy * @return true if the topic was destroyed - * @throws Exception - * if a problem occurred destroying the topic + * @throws Exception if a problem occurred destroying the topic */ boolean destroyTopic(String name, boolean removeConsumers) throws Exception; /** * destroys a topic and removes it from theBindingRegistry * - * @param name - * the name of the topic to destroy + * @param name the name of the topic to destroy * @return true if the topic was destroyed - * @throws Exception - * if a problem occurred destroying the topic + * @throws Exception if a problem occurred destroying the topic */ boolean destroyTopic(String name) throws Exception; - /** Call this method to have a CF rebound to the Binding Registry and stored on the Journal - * @throws Exception */ - ActiveMQConnectionFactory recreateCF(String name, ConnectionFactoryConfiguration cf) throws Exception; + /** + * Call this method to have a CF rebound to the Binding Registry and stored on the Journal + * + * @throws Exception + */ + ActiveMQConnectionFactory recreateCF(String name, ConnectionFactoryConfiguration cf) throws Exception; - void createConnectionFactory(String name, boolean ha, JMSFactoryType cfType, String discoveryGroupName, String ... bindings) throws Exception; + void createConnectionFactory(String name, + boolean ha, + JMSFactoryType cfType, + String discoveryGroupName, + String... bindings) throws Exception; void createConnectionFactory(String name, boolean ha, JMSFactoryType cfType, List connectorNames, - String ... bindings) throws Exception; + String... bindings) throws Exception; void createConnectionFactory(String name, boolean ha, @@ -225,7 +215,7 @@ public interface JMSServerManager extends ActiveMQComponent int reconnectAttempts, boolean failoverOnInitialConnection, String groupId, - String ... bindings) throws Exception; + String... bindings) throws Exception; void createConnectionFactory(String name, boolean ha, @@ -261,18 +251,18 @@ public interface JMSServerManager extends ActiveMQComponent int reconnectAttempts, boolean failoverOnInitialConnection, String groupId, - String ... bindings) throws Exception; + String... bindings) throws Exception; - void createConnectionFactory(boolean storeConfig, ConnectionFactoryConfiguration cfConfig, String... bindings) throws Exception; + void createConnectionFactory(boolean storeConfig, + ConnectionFactoryConfiguration cfConfig, + String... bindings) throws Exception; /** * destroys a connection factory. * - * @param name - * the name of the connection factory to destroy + * @param name the name of the connection factory to destroy * @return true if the connection factory was destroyed - * @throws Exception - * if a problem occurred destroying the connection factory + * @throws Exception if a problem occurred destroying the connection factory */ boolean destroyConnectionFactory(String name) throws Exception; diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/ConnectionFactoryConfiguration.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/ConnectionFactoryConfiguration.java index ea7ab933a6..57a955f91e 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/ConnectionFactoryConfiguration.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/ConnectionFactoryConfiguration.java @@ -24,8 +24,8 @@ import org.apache.activemq.artemis.core.journal.EncodingSupport; /** * A ConnectionFactoryConfiguration for {@link javax.jms.ConnectionFactory} objects. */ -public interface ConnectionFactoryConfiguration extends EncodingSupport -{ +public interface ConnectionFactoryConfiguration extends EncodingSupport { + boolean isPersisted(); String getName(); diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/JMSConfiguration.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/JMSConfiguration.java index 2ddffc5f7b..3fd0298936 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/JMSConfiguration.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/JMSConfiguration.java @@ -18,8 +18,8 @@ package org.apache.activemq.artemis.jms.server.config; import java.util.List; -public interface JMSConfiguration -{ +public interface JMSConfiguration { + List getQueueConfigurations(); JMSConfiguration setQueueConfigurations(List queueConfigurations); diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/JMSQueueConfiguration.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/JMSQueueConfiguration.java index a8bbb1ac0f..0f5d427f06 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/JMSQueueConfiguration.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/JMSQueueConfiguration.java @@ -16,8 +16,8 @@ */ package org.apache.activemq.artemis.jms.server.config; -public interface JMSQueueConfiguration -{ +public interface JMSQueueConfiguration { + String getName(); JMSQueueConfiguration setName(String name); diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/TopicConfiguration.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/TopicConfiguration.java index c9bdc7028b..cbd797442d 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/TopicConfiguration.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/TopicConfiguration.java @@ -16,8 +16,8 @@ */ package org.apache.activemq.artemis.jms.server.config; -public interface TopicConfiguration -{ +public interface TopicConfiguration { + String getName(); TopicConfiguration setName(String name); diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/impl/ConnectionFactoryConfigurationImpl.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/impl/ConnectionFactoryConfigurationImpl.java index 373c0a15f5..43c53853f0 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/impl/ConnectionFactoryConfigurationImpl.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/impl/ConnectionFactoryConfigurationImpl.java @@ -34,8 +34,7 @@ import org.apache.activemq.artemis.utils.DataConstants; *

    * Every property on this class has to be also set through encoders through EncodingSupport implementation at this class. */ -public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConfiguration -{ +public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConfiguration { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -120,404 +119,332 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf // Constructors -------------------------------------------------- - public ConnectionFactoryConfigurationImpl() - { + public ConnectionFactoryConfigurationImpl() { } // ConnectionFactoryConfiguration implementation ----------------- - public String[] getBindings() - { + public String[] getBindings() { return bindings; } - public ConnectionFactoryConfiguration setBindings(final String... bindings) - { + public ConnectionFactoryConfiguration setBindings(final String... bindings) { this.bindings = bindings; return this; } - public String getName() - { + public String getName() { return name; } - public ConnectionFactoryConfiguration setName(String name) - { + public ConnectionFactoryConfiguration setName(String name) { this.name = name; return this; } - public boolean isPersisted() - { + public boolean isPersisted() { return persisted; } /** * @return the discoveryGroupName */ - public String getDiscoveryGroupName() - { + public String getDiscoveryGroupName() { return discoveryGroupName; } /** * @param discoveryGroupName the discoveryGroupName to set */ - public ConnectionFactoryConfiguration setDiscoveryGroupName(String discoveryGroupName) - { + public ConnectionFactoryConfiguration setDiscoveryGroupName(String discoveryGroupName) { this.discoveryGroupName = discoveryGroupName; return this; } - public List getConnectorNames() - { + public List getConnectorNames() { return connectorNames; } - public ConnectionFactoryConfiguration setConnectorNames(final List connectorNames) - { + public ConnectionFactoryConfiguration setConnectorNames(final List connectorNames) { this.connectorNames = connectorNames; return this; } - public boolean isHA() - { + public boolean isHA() { return ha; } - public ConnectionFactoryConfiguration setHA(final boolean ha) - { + public ConnectionFactoryConfiguration setHA(final boolean ha) { this.ha = ha; return this; } - public String getClientID() - { + public String getClientID() { return clientID; } - public ConnectionFactoryConfiguration setClientID(final String clientID) - { + public ConnectionFactoryConfiguration setClientID(final String clientID) { this.clientID = clientID; return this; } - public long getClientFailureCheckPeriod() - { + public long getClientFailureCheckPeriod() { return clientFailureCheckPeriod; } - public ConnectionFactoryConfiguration setClientFailureCheckPeriod(final long clientFailureCheckPeriod) - { + public ConnectionFactoryConfiguration setClientFailureCheckPeriod(final long clientFailureCheckPeriod) { this.clientFailureCheckPeriod = clientFailureCheckPeriod; return this; } - public long getConnectionTTL() - { + public long getConnectionTTL() { return connectionTTL; } - public ConnectionFactoryConfiguration setConnectionTTL(final long connectionTTL) - { + public ConnectionFactoryConfiguration setConnectionTTL(final long connectionTTL) { this.connectionTTL = connectionTTL; return this; } - public long getCallTimeout() - { + public long getCallTimeout() { return callTimeout; } - public ConnectionFactoryConfiguration setCallTimeout(final long callTimeout) - { + public ConnectionFactoryConfiguration setCallTimeout(final long callTimeout) { this.callTimeout = callTimeout; return this; } - public long getCallFailoverTimeout() - { + public long getCallFailoverTimeout() { return callFailoverTimeout; } - public ConnectionFactoryConfiguration setCallFailoverTimeout(long callFailoverTimeout) - { + public ConnectionFactoryConfiguration setCallFailoverTimeout(long callFailoverTimeout) { this.callFailoverTimeout = callFailoverTimeout; return this; } - public boolean isCacheLargeMessagesClient() - { + public boolean isCacheLargeMessagesClient() { return cacheLargeMessagesClient; } - public ConnectionFactoryConfiguration setCacheLargeMessagesClient(final boolean cacheLargeMessagesClient) - { + public ConnectionFactoryConfiguration setCacheLargeMessagesClient(final boolean cacheLargeMessagesClient) { this.cacheLargeMessagesClient = cacheLargeMessagesClient; return this; } - public int getMinLargeMessageSize() - { + public int getMinLargeMessageSize() { return minLargeMessageSize; } - public ConnectionFactoryConfiguration setMinLargeMessageSize(final int minLargeMessageSize) - { + public ConnectionFactoryConfiguration setMinLargeMessageSize(final int minLargeMessageSize) { this.minLargeMessageSize = minLargeMessageSize; return this; } - public int getConsumerWindowSize() - { + public int getConsumerWindowSize() { return consumerWindowSize; } - public ConnectionFactoryConfiguration setConsumerWindowSize(final int consumerWindowSize) - { + public ConnectionFactoryConfiguration setConsumerWindowSize(final int consumerWindowSize) { this.consumerWindowSize = consumerWindowSize; return this; } - public int getConsumerMaxRate() - { + public int getConsumerMaxRate() { return consumerMaxRate; } - public ConnectionFactoryConfiguration setConsumerMaxRate(final int consumerMaxRate) - { + public ConnectionFactoryConfiguration setConsumerMaxRate(final int consumerMaxRate) { this.consumerMaxRate = consumerMaxRate; return this; } - public int getConfirmationWindowSize() - { + public int getConfirmationWindowSize() { return confirmationWindowSize; } - public ConnectionFactoryConfiguration setConfirmationWindowSize(final int confirmationWindowSize) - { + public ConnectionFactoryConfiguration setConfirmationWindowSize(final int confirmationWindowSize) { this.confirmationWindowSize = confirmationWindowSize; return this; } - public int getProducerMaxRate() - { + public int getProducerMaxRate() { return producerMaxRate; } - public ConnectionFactoryConfiguration setProducerMaxRate(final int producerMaxRate) - { + public ConnectionFactoryConfiguration setProducerMaxRate(final int producerMaxRate) { this.producerMaxRate = producerMaxRate; return this; } - public int getProducerWindowSize() - { + public int getProducerWindowSize() { return producerWindowSize; } - public ConnectionFactoryConfiguration setProducerWindowSize(final int producerWindowSize) - { + public ConnectionFactoryConfiguration setProducerWindowSize(final int producerWindowSize) { this.producerWindowSize = producerWindowSize; return this; } - public boolean isBlockOnAcknowledge() - { + public boolean isBlockOnAcknowledge() { return blockOnAcknowledge; } - public ConnectionFactoryConfiguration setBlockOnAcknowledge(final boolean blockOnAcknowledge) - { + public ConnectionFactoryConfiguration setBlockOnAcknowledge(final boolean blockOnAcknowledge) { this.blockOnAcknowledge = blockOnAcknowledge; return this; } - public boolean isBlockOnDurableSend() - { + public boolean isBlockOnDurableSend() { return blockOnDurableSend; } - public ConnectionFactoryConfiguration setBlockOnDurableSend(final boolean blockOnDurableSend) - { + public ConnectionFactoryConfiguration setBlockOnDurableSend(final boolean blockOnDurableSend) { this.blockOnDurableSend = blockOnDurableSend; return this; } - public boolean isBlockOnNonDurableSend() - { + public boolean isBlockOnNonDurableSend() { return blockOnNonDurableSend; } - public ConnectionFactoryConfiguration setBlockOnNonDurableSend(final boolean blockOnNonDurableSend) - { + public ConnectionFactoryConfiguration setBlockOnNonDurableSend(final boolean blockOnNonDurableSend) { this.blockOnNonDurableSend = blockOnNonDurableSend; return this; } - public boolean isAutoGroup() - { + public boolean isAutoGroup() { return autoGroup; } - public ConnectionFactoryConfiguration setAutoGroup(final boolean autoGroup) - { + public ConnectionFactoryConfiguration setAutoGroup(final boolean autoGroup) { this.autoGroup = autoGroup; return this; } - public boolean isPreAcknowledge() - { + public boolean isPreAcknowledge() { return preAcknowledge; } - public ConnectionFactoryConfiguration setPreAcknowledge(final boolean preAcknowledge) - { + public ConnectionFactoryConfiguration setPreAcknowledge(final boolean preAcknowledge) { this.preAcknowledge = preAcknowledge; return this; } - public String getLoadBalancingPolicyClassName() - { + public String getLoadBalancingPolicyClassName() { return loadBalancingPolicyClassName; } - public ConnectionFactoryConfiguration setLoadBalancingPolicyClassName(final String loadBalancingPolicyClassName) - { + public ConnectionFactoryConfiguration setLoadBalancingPolicyClassName(final String loadBalancingPolicyClassName) { this.loadBalancingPolicyClassName = loadBalancingPolicyClassName; return this; } - public int getTransactionBatchSize() - { + public int getTransactionBatchSize() { return transactionBatchSize; } - public ConnectionFactoryConfiguration setTransactionBatchSize(final int transactionBatchSize) - { + public ConnectionFactoryConfiguration setTransactionBatchSize(final int transactionBatchSize) { this.transactionBatchSize = transactionBatchSize; return this; } - public int getDupsOKBatchSize() - { + public int getDupsOKBatchSize() { return dupsOKBatchSize; } - public ConnectionFactoryConfiguration setDupsOKBatchSize(final int dupsOKBatchSize) - { + public ConnectionFactoryConfiguration setDupsOKBatchSize(final int dupsOKBatchSize) { this.dupsOKBatchSize = dupsOKBatchSize; return this; } - public long getInitialWaitTimeout() - { + public long getInitialWaitTimeout() { return initialWaitTimeout; } - public ConnectionFactoryConfiguration setInitialWaitTimeout(final long initialWaitTimeout) - { + public ConnectionFactoryConfiguration setInitialWaitTimeout(final long initialWaitTimeout) { this.initialWaitTimeout = initialWaitTimeout; return this; } - public boolean isUseGlobalPools() - { + public boolean isUseGlobalPools() { return useGlobalPools; } - public ConnectionFactoryConfiguration setUseGlobalPools(final boolean useGlobalPools) - { + public ConnectionFactoryConfiguration setUseGlobalPools(final boolean useGlobalPools) { this.useGlobalPools = useGlobalPools; return this; } - public int getScheduledThreadPoolMaxSize() - { + public int getScheduledThreadPoolMaxSize() { return scheduledThreadPoolMaxSize; } - public ConnectionFactoryConfiguration setScheduledThreadPoolMaxSize(final int scheduledThreadPoolMaxSize) - { + public ConnectionFactoryConfiguration setScheduledThreadPoolMaxSize(final int scheduledThreadPoolMaxSize) { this.scheduledThreadPoolMaxSize = scheduledThreadPoolMaxSize; return this; } - public int getThreadPoolMaxSize() - { + public int getThreadPoolMaxSize() { return threadPoolMaxSize; } - public ConnectionFactoryConfiguration setThreadPoolMaxSize(final int threadPoolMaxSize) - { + public ConnectionFactoryConfiguration setThreadPoolMaxSize(final int threadPoolMaxSize) { this.threadPoolMaxSize = threadPoolMaxSize; return this; } - public long getRetryInterval() - { + public long getRetryInterval() { return retryInterval; } - public ConnectionFactoryConfiguration setRetryInterval(final long retryInterval) - { + public ConnectionFactoryConfiguration setRetryInterval(final long retryInterval) { this.retryInterval = retryInterval; return this; } - public double getRetryIntervalMultiplier() - { + public double getRetryIntervalMultiplier() { return retryIntervalMultiplier; } - public ConnectionFactoryConfiguration setRetryIntervalMultiplier(final double retryIntervalMultiplier) - { + public ConnectionFactoryConfiguration setRetryIntervalMultiplier(final double retryIntervalMultiplier) { this.retryIntervalMultiplier = retryIntervalMultiplier; return this; } - public long getMaxRetryInterval() - { + public long getMaxRetryInterval() { return maxRetryInterval; } - public ConnectionFactoryConfiguration setMaxRetryInterval(final long maxRetryInterval) - { + public ConnectionFactoryConfiguration setMaxRetryInterval(final long maxRetryInterval) { this.maxRetryInterval = maxRetryInterval; return this; } - public int getReconnectAttempts() - { + public int getReconnectAttempts() { return reconnectAttempts; } - public ConnectionFactoryConfiguration setReconnectAttempts(final int reconnectAttempts) - { + public ConnectionFactoryConfiguration setReconnectAttempts(final int reconnectAttempts) { this.reconnectAttempts = reconnectAttempts; return this; } - public boolean isFailoverOnInitialConnection() - { + public boolean isFailoverOnInitialConnection() { return failoverOnInitialConnection; } - public ConnectionFactoryConfiguration setFailoverOnInitialConnection(final boolean failover) - { + public ConnectionFactoryConfiguration setFailoverOnInitialConnection(final boolean failover) { failoverOnInitialConnection = failover; return this; } - public String getGroupID() - { + public String getGroupID() { return groupID; } - public ConnectionFactoryConfiguration setGroupID(final String groupID) - { + public ConnectionFactoryConfiguration setGroupID(final String groupID) { this.groupID = groupID; return this; } @@ -525,8 +452,7 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf // Encoding Support Implementation -------------------------------------------------------------- @Override - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { persisted = true; name = buffer.readSimpleString().toString(); @@ -535,12 +461,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf int nConnectors = buffer.readInt(); - if (nConnectors > 0) - { + if (nConnectors > 0) { connectorNames = new ArrayList(nConnectors); - for (int i = 0; i < nConnectors; i++) - { + for (int i = 0; i < nConnectors; i++) { SimpleString str = buffer.readSimpleString(); connectorNames.add(str.toString()); @@ -613,24 +537,20 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf } @Override - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { persisted = true; BufferHelper.writeAsSimpleString(buffer, name); BufferHelper.writeAsNullableSimpleString(buffer, discoveryGroupName); - if (this.connectorNames == null) - { + if (this.connectorNames == null) { buffer.writeInt(0); } - else - { + else { buffer.writeInt(connectorNames.size()); - for (String tc : connectorNames) - { + for (String tc : connectorNames) { BufferHelper.writeAsSimpleString(buffer, tc); } } @@ -701,18 +621,15 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf } @Override - public int getEncodeSize() - { + public int getEncodeSize() { int size = BufferHelper.sizeOfSimpleString(name) + BufferHelper.sizeOfNullableSimpleString(discoveryGroupName); size += DataConstants.SIZE_INT; - if (this.connectorNames != null) - { - for (String tc : connectorNames) - { + if (this.connectorNames != null) { + for (String tc : connectorNames) { size += BufferHelper.sizeOfSimpleString(tc); } } @@ -812,27 +729,23 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf return size; } - public ConnectionFactoryConfiguration setFactoryType(final JMSFactoryType factoryType) - { + public ConnectionFactoryConfiguration setFactoryType(final JMSFactoryType factoryType) { this.factoryType = factoryType; return this; } - public JMSFactoryType getFactoryType() - { + public JMSFactoryType getFactoryType() { return factoryType; } @Override - public ConnectionFactoryConfiguration setCompressLargeMessages(boolean compressLargeMessage) - { + public ConnectionFactoryConfiguration setCompressLargeMessages(boolean compressLargeMessage) { this.compressLargeMessage = compressLargeMessage; return this; } @Override - public boolean isCompressLargeMessages() - { + public boolean isCompressLargeMessages() { return this.compressLargeMessage; } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/impl/FileJMSConfiguration.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/impl/FileJMSConfiguration.java index 8fad9d6e27..0a657ebb3f 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/impl/FileJMSConfiguration.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/impl/FileJMSConfiguration.java @@ -36,8 +36,8 @@ import javax.management.MBeanServer; import java.util.ArrayList; import java.util.Map; -public class FileJMSConfiguration extends JMSConfigurationImpl implements Deployable -{ +public class FileJMSConfiguration extends JMSConfigurationImpl implements Deployable { + private static final String CONFIGURATION_SCHEMA_URL = "schema/artemis-jms.xsd"; private static final String CONFIGURATION_SCHEMA_ROOT_ELEMENT = "jms"; @@ -57,43 +57,39 @@ public class FileJMSConfiguration extends JMSConfigurationImpl implements Deploy private boolean parsed = false; @Override - public void parse(Element config) throws Exception - { + public void parse(Element config) throws Exception { parseConfiguration(config); parsed = true; } @Override - public boolean isParsed() - { + public boolean isParsed() { return parsed; } @Override - public String getRootElement() - { + public String getRootElement() { return CONFIGURATION_SCHEMA_ROOT_ELEMENT; } @Override - public void buildService(ActiveMQSecurityManager securityManager, MBeanServer mBeanServer, Map deployables, Map components) throws Exception - { + public void buildService(ActiveMQSecurityManager securityManager, + MBeanServer mBeanServer, + Map deployables, + Map components) throws Exception { ActiveMQServerImpl server = (ActiveMQServerImpl) components.get("core"); components.put(CONFIGURATION_SCHEMA_ROOT_ELEMENT, new JMSServerManagerImpl(server, this)); } @Override - public String getSchema() - { + public String getSchema() { return CONFIGURATION_SCHEMA_URL; } - /** * Parse the JMS Configuration XML */ - public void parseConfiguration(final Node rootnode) throws Exception - { + public void parseConfiguration(final Node rootnode) throws Exception { ArrayList queues = new ArrayList<>(); ArrayList topics = new ArrayList<>(); @@ -101,25 +97,20 @@ public class FileJMSConfiguration extends JMSConfigurationImpl implements Deploy Element e = (Element) rootnode; String[] elements = new String[]{QUEUE_NODE_NAME, TOPIC_NODE_NAME}; - for (String element : elements) - { + for (String element : elements) { NodeList children = e.getElementsByTagName(element); - for (int i = 0; i < children.getLength(); i++) - { + for (int i = 0; i < children.getLength(); i++) { Node node = children.item(i); Node keyNode = node.getAttributes().getNamedItem(NAME_ATTR); - if (keyNode == null) - { + if (keyNode == null) { ActiveMQJMSServerLogger.LOGGER.jmsConfigMissingKey(node); continue; } - if (node.getNodeName().equals(TOPIC_NODE_NAME)) - { + if (node.getNodeName().equals(TOPIC_NODE_NAME)) { topics.add(parseTopicConfiguration(node)); } - else if (node.getNodeName().equals(QUEUE_NODE_NAME)) - { + else if (node.getNodeName().equals(QUEUE_NODE_NAME)) { queues.add(parseQueueConfiguration(node)); } } @@ -137,8 +128,7 @@ public class FileJMSConfiguration extends JMSConfigurationImpl implements Deploy * @return topic configuration * @throws Exception */ - public static TopicConfiguration parseTopicConfiguration(final Node node) throws Exception - { + public static TopicConfiguration parseTopicConfiguration(final Node node) throws Exception { String topicName = node.getAttributes().getNamedItem(NAME_ATTR).getNodeValue(); return newTopic(topicName); @@ -151,20 +141,17 @@ public class FileJMSConfiguration extends JMSConfigurationImpl implements Deploy * @return jms queue configuration * @throws Exception */ - public static JMSQueueConfiguration parseQueueConfiguration(final Node node) throws Exception - { + public static JMSQueueConfiguration parseQueueConfiguration(final Node node) throws Exception { Element e = (Element) node; NamedNodeMap atts = node.getAttributes(); String queueName = atts.getNamedItem(NAME_ATTR).getNodeValue(); String selectorString = null; boolean durable = XMLConfigurationUtil.getBoolean(e, "durable", DEFAULT_QUEUE_DURABILITY); NodeList children = node.getChildNodes(); - for (int i = 0; i < children.getLength(); i++) - { + for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); - if (QUEUE_SELECTOR_NODE_NAME.equals(children.item(i).getNodeName())) - { + if (QUEUE_SELECTOR_NODE_NAME.equals(children.item(i).getNodeName())) { Node selectorNode = children.item(i); Node attNode = selectorNode.getAttributes().getNamedItem("string"); selectorString = attNode.getNodeValue(); @@ -178,10 +165,8 @@ public class FileJMSConfiguration extends JMSConfigurationImpl implements Deploy * @param topicName * @return */ - protected static TopicConfiguration newTopic(final String topicName) - { - return new TopicConfigurationImpl() - .setName(topicName); + protected static TopicConfiguration newTopic(final String topicName) { + return new TopicConfigurationImpl().setName(topicName); } /** @@ -191,9 +176,8 @@ public class FileJMSConfiguration extends JMSConfigurationImpl implements Deploy * @return */ protected static JMSQueueConfiguration newQueue(final String queueName, - final String selectorString, - final boolean durable) - { + final String selectorString, + final boolean durable) { return new JMSQueueConfigurationImpl(). setName(queueName). setSelector(selectorString). @@ -206,10 +190,8 @@ public class FileJMSConfiguration extends JMSConfigurationImpl implements Deploy * @param domain */ protected void newConfig(final ArrayList queues, - final ArrayList topics, String domain) - { - setQueueConfigurations(queues) - .setTopicConfigurations(topics) - .setDomain(domain); + final ArrayList topics, + String domain) { + setQueueConfigurations(queues).setTopicConfigurations(topics).setDomain(domain); } } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/impl/JMSConfigurationImpl.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/impl/JMSConfigurationImpl.java index 5546bc303d..9b36cfc210 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/impl/JMSConfigurationImpl.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/impl/JMSConfigurationImpl.java @@ -25,9 +25,8 @@ import org.apache.activemq.artemis.jms.server.config.JMSConfiguration; import org.apache.activemq.artemis.jms.server.config.JMSQueueConfiguration; import org.apache.activemq.artemis.jms.server.config.TopicConfiguration; +public class JMSConfigurationImpl implements JMSConfiguration { -public class JMSConfigurationImpl implements JMSConfiguration -{ private List connectionFactoryConfigurations = new ArrayList(); private List queueConfigurations = new ArrayList(); @@ -38,50 +37,41 @@ public class JMSConfigurationImpl implements JMSConfiguration // JMSConfiguration implementation ------------------------------- - public JMSConfigurationImpl() - { + public JMSConfigurationImpl() { } - public List getConnectionFactoryConfigurations() - { + public List getConnectionFactoryConfigurations() { return connectionFactoryConfigurations; } - public JMSConfigurationImpl setConnectionFactoryConfigurations(List connectionFactoryConfigurations) - { + public JMSConfigurationImpl setConnectionFactoryConfigurations(List connectionFactoryConfigurations) { this.connectionFactoryConfigurations = connectionFactoryConfigurations; return this; } - public List getQueueConfigurations() - { + public List getQueueConfigurations() { return queueConfigurations; } - public JMSConfigurationImpl setQueueConfigurations(List queueConfigurations) - { + public JMSConfigurationImpl setQueueConfigurations(List queueConfigurations) { this.queueConfigurations = queueConfigurations; return this; } - public List getTopicConfigurations() - { + public List getTopicConfigurations() { return topicConfigurations; } - public JMSConfigurationImpl setTopicConfigurations(List topicConfigurations) - { + public JMSConfigurationImpl setTopicConfigurations(List topicConfigurations) { this.topicConfigurations = topicConfigurations; return this; } - public String getDomain() - { + public String getDomain() { return domain; } - public JMSConfigurationImpl setDomain(final String domain) - { + public JMSConfigurationImpl setDomain(final String domain) { this.domain = domain; return this; } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/impl/JMSQueueConfigurationImpl.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/impl/JMSQueueConfigurationImpl.java index 2e6a506f6b..52be423043 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/impl/JMSQueueConfigurationImpl.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/impl/JMSQueueConfigurationImpl.java @@ -18,9 +18,7 @@ package org.apache.activemq.artemis.jms.server.config.impl; import org.apache.activemq.artemis.jms.server.config.JMSQueueConfiguration; - -public class JMSQueueConfigurationImpl implements JMSQueueConfiguration -{ +public class JMSQueueConfigurationImpl implements JMSQueueConfiguration { // Constants ----------------------------------------------------- @@ -38,52 +36,43 @@ public class JMSQueueConfigurationImpl implements JMSQueueConfiguration // Constructors -------------------------------------------------- - public JMSQueueConfigurationImpl() - { + public JMSQueueConfigurationImpl() { } // QueueConfiguration implementation ----------------------------- - public String[] getBindings() - { + public String[] getBindings() { return bindings; } - public JMSQueueConfigurationImpl setBindings(String... bindings) - { + public JMSQueueConfigurationImpl setBindings(String... bindings) { this.bindings = bindings; return this; } - public String getName() - { + public String getName() { return name; } - public JMSQueueConfigurationImpl setName(String name) - { + public JMSQueueConfigurationImpl setName(String name) { this.name = name; return this; } - public String getSelector() - { + public String getSelector() { return selector; } - public JMSQueueConfigurationImpl setSelector(String selector) - { + public JMSQueueConfigurationImpl setSelector(String selector) { this.selector = selector; return this; } - public boolean isDurable() - { + public boolean isDurable() { return durable; } - public JMSQueueConfigurationImpl setDurable(boolean durable) - { + public JMSQueueConfigurationImpl setDurable(boolean durable) { this.durable = durable; return this; } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/impl/TopicConfigurationImpl.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/impl/TopicConfigurationImpl.java index 5badcbe1de..e8ad224c6b 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/impl/TopicConfigurationImpl.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/impl/TopicConfigurationImpl.java @@ -18,9 +18,7 @@ package org.apache.activemq.artemis.jms.server.config.impl; import org.apache.activemq.artemis.jms.server.config.TopicConfiguration; - -public class TopicConfigurationImpl implements TopicConfiguration -{ +public class TopicConfigurationImpl implements TopicConfiguration { // Constants ----------------------------------------------------- @@ -34,30 +32,25 @@ public class TopicConfigurationImpl implements TopicConfiguration // Constructors -------------------------------------------------- - public TopicConfigurationImpl() - { + public TopicConfigurationImpl() { } // TopicConfiguration implementation ----------------------------- - public String[] getBindings() - { + public String[] getBindings() { return bindings; } - public TopicConfigurationImpl setBindings(String... bindings) - { + public TopicConfigurationImpl setBindings(String... bindings) { this.bindings = bindings; return this; } - public String getName() - { + public String getName() { return name; } - public TopicConfigurationImpl setName(String name) - { + public TopicConfigurationImpl setName(String name) { this.name = name; return this; } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/impl/TransportConfigurationEncodingSupport.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/impl/TransportConfigurationEncodingSupport.java index 230ff33965..858c68bbcc 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/impl/TransportConfigurationEncodingSupport.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/config/impl/TransportConfigurationEncodingSupport.java @@ -28,20 +28,17 @@ import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.utils.BufferHelper; import org.apache.activemq.artemis.utils.DataConstants; -public class TransportConfigurationEncodingSupport -{ - public static List> decodeConfigs(ActiveMQBuffer buffer) - { +public class TransportConfigurationEncodingSupport { + + public static List> decodeConfigs(ActiveMQBuffer buffer) { int size = buffer.readInt(); List> configs = new ArrayList>(size); - for (int i = 0; i < size; i++) - { + for (int i = 0; i < size; i++) { TransportConfiguration live = decode(buffer); boolean hasBackup = buffer.readBoolean(); TransportConfiguration backup = null; - if (hasBackup) - { + if (hasBackup) { backup = decode(buffer); } configs.add(new Pair(live, backup)); @@ -50,14 +47,12 @@ public class TransportConfigurationEncodingSupport return configs; } - public static TransportConfiguration decode(ActiveMQBuffer buffer) - { + public static TransportConfiguration decode(ActiveMQBuffer buffer) { String name = BufferHelper.readNullableSimpleStringAsString(buffer); String factoryClassName = buffer.readSimpleString().toString(); int paramSize = buffer.readInt(); Map params = new HashMap(); - for (int i = 0; i < paramSize; i++) - { + for (int i = 0; i < paramSize; i++) { String key = buffer.readSimpleString().toString(); String value = buffer.readSimpleString().toString(); params.put(key, value); @@ -67,61 +62,48 @@ public class TransportConfigurationEncodingSupport } public static void encodeConfigs(ActiveMQBuffer buffer, - List> configs) - { + List> configs) { buffer.writeInt(configs == null ? 0 : configs.size()); - if (configs != null) - { - for (Pair pair : configs) - { + if (configs != null) { + for (Pair pair : configs) { encode(buffer, pair.getA()); boolean backup = (pair.getB() != null); buffer.writeBoolean(backup); - if (backup) - { + if (backup) { encode(buffer, pair.getB()); } } } } - public static void encode(ActiveMQBuffer buffer, TransportConfiguration config) - { + public static void encode(ActiveMQBuffer buffer, TransportConfiguration config) { BufferHelper.writeAsNullableSimpleString(buffer, config.getName()); BufferHelper.writeAsSimpleString(buffer, config.getFactoryClassName()); buffer.writeInt(config.getParams().size()); - for (Entry param : config.getParams().entrySet()) - { + for (Entry param : config.getParams().entrySet()) { BufferHelper.writeAsSimpleString(buffer, param.getKey()); BufferHelper.writeAsSimpleString(buffer, param.getValue().toString()); } } - public static int getEncodeSize(TransportConfiguration config) - { - int size = BufferHelper.sizeOfNullableSimpleString(config.getName()) + - BufferHelper.sizeOfSimpleString(config.getFactoryClassName()); + public static int getEncodeSize(TransportConfiguration config) { + int size = BufferHelper.sizeOfNullableSimpleString(config.getName()) + BufferHelper.sizeOfSimpleString(config.getFactoryClassName()); size += DataConstants.SIZE_INT; // number of params - for (Entry param : config.getParams().entrySet()) - { + for (Entry param : config.getParams().entrySet()) { size += BufferHelper.sizeOfSimpleString(param.getKey()); size += BufferHelper.sizeOfSimpleString(param.getValue().toString()); } return size; } - public static int getEncodeSize(List> configs) - { + public static int getEncodeSize(List> configs) { int size = DataConstants.SIZE_INT; // number of configs; - if (configs != null) - { - for (Pair pair : configs) - { + if (configs != null) { + for (Pair pair : configs) { size += getEncodeSize(pair.getA()); size += DataConstants.SIZE_BOOLEAN; // whether there is a backup config - if (pair.getB() != null) - { + if (pair.getB() != null) { size += getEncodeSize(pair.getB()); } } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/embedded/EmbeddedJMS.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/embedded/EmbeddedJMS.java index b09ee884ae..10962f9f9c 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/embedded/EmbeddedJMS.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/embedded/EmbeddedJMS.java @@ -35,21 +35,18 @@ import org.apache.activemq.artemis.spi.core.naming.BindingRegistry; * JMS Endpoints are registered with a simple MapBindingRegistry. If you want to use a different registry * you must set the registry property of this class or call the setRegistry() method if you want to use JNDI */ -public class EmbeddedJMS extends EmbeddedActiveMQ -{ +public class EmbeddedJMS extends EmbeddedActiveMQ { + protected JMSServerManagerImpl serverManager; protected BindingRegistry registry; protected JMSConfiguration jmsConfiguration; protected Context context; - - public BindingRegistry getRegistry() - { + public BindingRegistry getRegistry() { return registry; } - public JMSServerManager getJMSServerManager() - { + public JMSServerManager getJMSServerManager() { return serverManager; } @@ -58,8 +55,7 @@ public class EmbeddedJMS extends EmbeddedActiveMQ * * @param registry */ - public void setRegistry(BindingRegistry registry) - { + public void setRegistry(BindingRegistry registry) { this.registry = registry; } @@ -68,8 +64,7 @@ public class EmbeddedJMS extends EmbeddedActiveMQ * * @param jmsConfiguration */ - public void setJmsConfiguration(JMSConfiguration jmsConfiguration) - { + public void setJmsConfiguration(JMSConfiguration jmsConfiguration) { this.jmsConfiguration = jmsConfiguration; } @@ -78,8 +73,7 @@ public class EmbeddedJMS extends EmbeddedActiveMQ * * @param context */ - public void setContext(Context context) - { + public void setContext(Context context) { this.context = context; } @@ -87,31 +81,26 @@ public class EmbeddedJMS extends EmbeddedActiveMQ * Lookup in the registry for registered object, i.e. a ConnectionFactory. *

    * This is a convenience method. + * * @param name */ - public Object lookup(String name) - { + public Object lookup(String name) { return serverManager.getRegistry().lookup(name); } @Override - public void start() throws Exception - { + public void start() throws Exception { super.initStart(); - if (jmsConfiguration != null) - { + if (jmsConfiguration != null) { serverManager = new JMSServerManagerImpl(activeMQServer, jmsConfiguration); } - else - { + else { FileJMSConfiguration fileConfiguration = new FileJMSConfiguration(); FileDeploymentManager deploymentManager; - if (configResourcePath != null) - { + if (configResourcePath != null) { deploymentManager = new FileDeploymentManager(configResourcePath); } - else - { + else { deploymentManager = new FileDeploymentManager(); } deploymentManager.addDeployable(fileConfiguration); @@ -119,18 +108,18 @@ public class EmbeddedJMS extends EmbeddedActiveMQ serverManager = new JMSServerManagerImpl(activeMQServer, fileConfiguration); } - if (registry == null) - { - if (context != null) registry = new JndiBindingRegistry(context); - else registry = new MapBindingRegistry(); + if (registry == null) { + if (context != null) + registry = new JndiBindingRegistry(context); + else + registry = new MapBindingRegistry(); } serverManager.setRegistry(registry); serverManager.start(); } @Override - public void stop() throws Exception - { + public void stop() throws Exception { serverManager.stop(); } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/impl/JMSServerManagerImpl.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/impl/JMSServerManagerImpl.java index 6c257c845a..ff246f2d64 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/impl/JMSServerManagerImpl.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/impl/JMSServerManagerImpl.java @@ -98,8 +98,8 @@ import org.apache.activemq.artemis.utils.json.JSONObject; * If a JMSConfiguration object is used, the JMS resources can not be * redeployed. */ -public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback -{ +public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback { + private static final String REJECT_FILTER = ActiveMQServerImpl.GENERIC_IGNORED_FILTER; private BindingRegistry registry; @@ -135,8 +135,7 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback private final Map> unRecoveredBindings = new HashMap>(); - public JMSServerManagerImpl(final ActiveMQServer server) throws Exception - { + public JMSServerManagerImpl(final ActiveMQServer server) throws Exception { this.server = server; this.coreConfig = server.getConfiguration(); @@ -149,8 +148,7 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback * @param registry * @throws Exception */ - public JMSServerManagerImpl(final ActiveMQServer server, final BindingRegistry registry) throws Exception - { + public JMSServerManagerImpl(final ActiveMQServer server, final BindingRegistry registry) throws Exception { this.server = server; this.coreConfig = server.getConfiguration(); @@ -158,8 +156,7 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback this.registry = registry; } - public JMSServerManagerImpl(final ActiveMQServer server, final JMSConfiguration configuration) throws Exception - { + public JMSServerManagerImpl(final ActiveMQServer server, final JMSConfiguration configuration) throws Exception { this.server = server; this.coreConfig = server.getConfiguration(); @@ -169,20 +166,16 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback // ActivateCallback implementation ------------------------------------- - public void preActivate() - { + public void preActivate() { } - public synchronized void activated() - { - if (!startCalled) - { + public synchronized void activated() { + if (!startCalled) { return; } - try - { + try { jmsManagementService = new JMSManagementServiceImpl(server.getManagementService(), server, this); @@ -195,8 +188,7 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback deploy(); - for (Runnable run : cachedCommands) - { + for (Runnable run : cachedCommands) { ActiveMQJMSServerLogger.LOGGER.serverRunningCachedCommand(run); run.run(); } @@ -205,28 +197,22 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback recoverBindings(); } - catch (Exception e) - { + catch (Exception e) { active = false; ActiveMQJMSServerLogger.LOGGER.jmsDeployerStartError(e); } } @Override - public void deActivate() - { - try - { - synchronized (this) - { - if (!active) - { + public void deActivate() { + try { + synchronized (this) { + if (!active) { return; } // Storage could be null on a shared store backup server before initialization - if (storage != null && storage.isStarted()) - { + if (storage != null && storage.isStarted()) { storage.stop(); } @@ -236,8 +222,7 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback unbindBindings(connectionFactoryBindings); - for (String connectionFactory : new HashSet(connectionFactories.keySet())) - { + for (String connectionFactory : new HashSet(connectionFactories.keySet())) { shutdownConnectionFactory(connectionFactory); } @@ -251,8 +236,7 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback topics.clear(); // it could be null if a backup - if (jmsManagementService != null) - { + if (jmsManagementService != null) { jmsManagementService.unregisterJMSServer(); jmsManagementService.stop(); @@ -263,28 +247,23 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback active = false; } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @Override - public void activationComplete() - { + public void activationComplete() { } - public void recoverregistryBindings(String name, PersistedType type) throws NamingException - { + public void recoverregistryBindings(String name, PersistedType type) throws NamingException { List bindings = unRecoveredBindings.get(name); - if ((bindings != null) && (bindings.size() > 0)) - { + if ((bindings != null) && (bindings.size() > 0)) { Map> mapBindings; Map objects; - switch (type) - { + switch (type) { case Queue: mapBindings = queueBindings; objects = queues; @@ -304,19 +283,16 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback List bindingsList = mapBindings.get(name); - if (objectToBind == null) - { + if (objectToBind == null) { return; } - if (bindingsList == null) - { + if (bindingsList == null) { bindingsList = new ArrayList(); mapBindings.put(name, bindingsList); } - for (String binding : bindings) - { + for (String binding : bindings) { bindingsList.add(binding); bindToBindings(binding, objectToBind); } @@ -325,18 +301,15 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback } } - private void recoverBindings() throws Exception - { + private void recoverBindings() throws Exception { //now its time to add journal recovered stuff List bindingsSpace = storage.recoverPersistedBindings(); - for (PersistedBindings record : bindingsSpace) - { + for (PersistedBindings record : bindingsSpace) { Map> mapBindings; Map objects; - switch (record.getType()) - { + switch (record.getType()) { case Queue: mapBindings = queueBindings; objects = queues; @@ -355,26 +328,22 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback Object objectToBind = objects.get(record.getName()); List bindingsList = mapBindings.get(record.getName()); - if (objectToBind == null) - { + if (objectToBind == null) { unRecoveredBindings.put(record.getName(), record.getBindings()); continue; } - if (bindingsList == null) - { + if (bindingsList == null) { bindingsList = new ArrayList(); mapBindings.put(record.getName(), bindingsList); } - for (String bindings : record.getBindings()) - { + for (String bindings : record.getBindings()) { bindingsList.add(bindings); bindToBindings(bindings, objectToBind); } } - } // ActiveMQComponent implementation ----------------------------------- @@ -393,10 +362,8 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback * must already be true. * */ - public synchronized void start() throws Exception - { - if (startCalled) - { + public synchronized void start() throws Exception { + if (startCalled) { return; } @@ -413,22 +380,17 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback startCalled = true; server.start(); - } - public void stop() throws Exception - { - synchronized (this) - { - if (!startCalled) - { + public void stop() throws Exception { + synchronized (this) { + if (!startCalled) { return; } startCalled = false; //deactivate in case we haven't been already deActivate(); - if (registry != null) - { + if (registry != null) { registry.close(); } } @@ -438,50 +400,41 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback server.stop(); } - public boolean isStarted() - { + public boolean isStarted() { return server.isStarted(); } // JMSServerManager implementation ------------------------------- - public BindingRegistry getRegistry() - { + public BindingRegistry getRegistry() { return registry; } - public void setRegistry(BindingRegistry registry) - { + public void setRegistry(BindingRegistry registry) { this.registry = registry; } - public ActiveMQServer getActiveMQServer() - { + public ActiveMQServer getActiveMQServer() { return server; } - public void addAddressSettings(final String address, final AddressSettings addressSettings) - { + public void addAddressSettings(final String address, final AddressSettings addressSettings) { server.getAddressSettingsRepository().addMatch(address, addressSettings); } - public AddressSettings getAddressSettings(final String address) - { + public AddressSettings getAddressSettings(final String address) { return server.getAddressSettingsRepository().getMatch(address); } - public void addSecurity(final String addressMatch, final Set roles) - { + public void addSecurity(final String addressMatch, final Set roles) { server.getSecurityRepository().addMatch(addressMatch, roles); } - public Set getSecurity(final String addressMatch) - { + public Set getSecurity(final String addressMatch) { return server.getSecurityRepository().getMatch(addressMatch); } - public synchronized String getVersion() - { + public synchronized String getVersion() { checkInitialised(); return server.getVersion().getFullVersion(); @@ -491,57 +444,46 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback final String queueName, final String selectorString, final boolean durable, - final String... bindings) throws Exception - { + final String... bindings) throws Exception { return internalCreateJMSQueue(storeConfig, queueName, selectorString, durable, false, bindings); } protected boolean internalCreateJMSQueue(final boolean storeConfig, - final String queueName, - final String selectorString, - final boolean durable, - final boolean autoCreated, - final String... bindings) throws Exception - { + final String queueName, + final String selectorString, + final boolean durable, + final boolean autoCreated, + final String... bindings) throws Exception { - if (active && queues.get(queueName) != null) - { + if (active && queues.get(queueName) != null) { return false; } - runAfterActive(new WrappedRunnable() - { + runAfterActive(new WrappedRunnable() { @Override - public String toString() - { + public String toString() { return "createQueue for " + queueName; } @Override - public void runException() throws Exception - { + public void runException() throws Exception { checkBindings(bindings); - if (internalCreateQueue(queueName, selectorString, durable)) - { + if (internalCreateQueue(queueName, selectorString, durable)) { ActiveMQDestination destination = queues.get(queueName); - if (destination == null) - { + if (destination == null) { // sanity check. internalCreateQueue should already have done this check throw new IllegalArgumentException("Queue does not exist"); } String[] usedBindings = null; - if (bindings != null) - { + if (bindings != null) { ArrayList bindingsToAdd = new ArrayList(); - for (String bindingsItem : bindings) - { - if (bindToBindings(bindingsItem, destination)) - { + for (String bindingsItem : bindings) { + if (bindToBindings(bindingsItem, destination)) { bindingsToAdd.add(bindingsItem); } } @@ -550,14 +492,9 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback addToBindings(queueBindings, queueName, usedBindings); } - if (storeConfig && durable) - { - storage.storeDestination(new PersistedDestination(PersistedType.Queue, - queueName, - selectorString, - durable)); - if (usedBindings != null) - { + if (storeConfig && durable) { + storage.storeDestination(new PersistedDestination(PersistedType.Queue, queueName, selectorString, durable)); + if (usedBindings != null) { storage.addBindings(PersistedType.Queue, queueName, usedBindings); } } @@ -569,44 +506,36 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback return true; } - public synchronized boolean createTopic(final boolean storeConfig, final String topicName, final String... bindings) throws Exception - { - if (active && topics.get(topicName) != null) - { + public synchronized boolean createTopic(final boolean storeConfig, + final String topicName, + final String... bindings) throws Exception { + if (active && topics.get(topicName) != null) { return false; } - runAfterActive(new WrappedRunnable() - { + runAfterActive(new WrappedRunnable() { @Override - public String toString() - { + public String toString() { return "createTopic for " + topicName; } @Override - public void runException() throws Exception - { + public void runException() throws Exception { checkBindings(bindings); - if (internalCreateTopic(topicName)) - { + if (internalCreateTopic(topicName)) { ActiveMQDestination destination = topics.get(topicName); - if (destination == null) - { + if (destination == null) { // sanity check. internalCreateQueue should already have done this check throw new IllegalArgumentException("Queue does not exist"); } ArrayList bindingsToAdd = new ArrayList(); - if (bindings != null) - { - for (String bindingsItem : bindings) - { - if (bindToBindings(bindingsItem, destination)) - { + if (bindings != null) { + for (String bindingsItem : bindings) { + if (bindToBindings(bindingsItem, destination)) { bindingsToAdd.add(bindingsItem); } } @@ -615,8 +544,7 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback String[] usedBindings = bindingsToAdd.toArray(new String[bindingsToAdd.size()]); addToBindings(topicBindings, topicName, usedBindings); - if (storeConfig) - { + if (storeConfig) { storage.storeDestination(new PersistedDestination(PersistedType.Topic, topicName)); storage.addBindings(PersistedType.Topic, topicName, usedBindings); } @@ -629,88 +557,74 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback } - public boolean addTopicToBindingRegistry(final String topicName, final String registryBinding) throws Exception - { + public boolean addTopicToBindingRegistry(final String topicName, final String registryBinding) throws Exception { checkInitialised(); checkBindings(registryBinding); ActiveMQTopic destination = topics.get(topicName); - if (destination == null) - { + if (destination == null) { throw new IllegalArgumentException("Topic does not exist"); } - if (destination.getTopicName() == null) - { + if (destination.getTopicName() == null) { throw new IllegalArgumentException(topicName + " is not a topic"); } boolean added = bindToBindings(registryBinding, destination); - if (added) - { + if (added) { addToBindings(topicBindings, topicName, registryBinding); storage.addBindings(PersistedType.Topic, topicName, registryBinding); } return added; } - public String[] getBindingsOnQueue(String queue) - { + public String[] getBindingsOnQueue(String queue) { return getBindingsList(queueBindings, queue); } - public String[] getBindingsOnTopic(String topic) - { + public String[] getBindingsOnTopic(String topic) { return getBindingsList(topicBindings, topic); } - public String[] getBindingsOnConnectionFactory(String factoryName) - { + public String[] getBindingsOnConnectionFactory(String factoryName) { return getBindingsList(connectionFactoryBindings, factoryName); } - public boolean addQueueToBindingRegistry(final String queueName, final String registryBinding) throws Exception - { + public boolean addQueueToBindingRegistry(final String queueName, final String registryBinding) throws Exception { checkInitialised(); checkBindings(registryBinding); ActiveMQQueue destination = queues.get(queueName); - if (destination == null) - { + if (destination == null) { throw new IllegalArgumentException("Queue does not exist"); } - if (destination.getQueueName() == null) - { + if (destination.getQueueName() == null) { throw new IllegalArgumentException(queueName + " is not a queue"); } boolean added = bindToBindings(registryBinding, destination); - if (added) - { + if (added) { addToBindings(queueBindings, queueName, registryBinding); storage.addBindings(PersistedType.Queue, queueName, registryBinding); } return added; } - public boolean addConnectionFactoryToBindingRegistry(final String name, final String registryBinding) throws Exception - { + public boolean addConnectionFactoryToBindingRegistry(final String name, + final String registryBinding) throws Exception { checkInitialised(); checkBindings(registryBinding); ActiveMQConnectionFactory factory = connectionFactories.get(name); - if (factory == null) - { + if (factory == null) { throw new IllegalArgumentException("Factory does not exist"); } - if (registry.lookup(registryBinding) != null) - { + if (registry.lookup(registryBinding) != null) { throw ActiveMQJMSServerBundle.BUNDLE.cfBindingsExists(name); } boolean added = bindToBindings(registryBinding, factory); - if (added) - { + if (added) { addToBindings(connectionFactoryBindings, name, registryBinding); storage.addBindings(PersistedType.ConnectionFactory, name, registryBinding); } @@ -718,14 +632,12 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback } @Override - public boolean removeQueueFromBindingRegistry(String name, String bindings) throws Exception - { + public boolean removeQueueFromBindingRegistry(String name, String bindings) throws Exception { checkInitialised(); boolean removed = removeFromBindings(queueBindings, name, bindings); - if (removed) - { + if (removed) { storage.deleteBindings(PersistedType.Queue, name, bindings); } @@ -733,26 +645,21 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback } @Override - public boolean removeQueueFromBindingRegistry(final String name) throws Exception - { + public boolean removeQueueFromBindingRegistry(final String name) throws Exception { final AtomicBoolean valueReturn = new AtomicBoolean(false); // HORNETQ-911 - make this runAfterActive to prevent WARN messages on shutdown/undeployment when the backup was never activated - runAfterActive(new WrappedRunnable() - { + runAfterActive(new WrappedRunnable() { @Override - public String toString() - { + public String toString() { return "removeQueueFromBindings for " + name; } @Override - public void runException() throws Exception - { + public void runException() throws Exception { checkInitialised(); - if (removeFromBindings(queues, queueBindings, name)) - { + if (removeFromBindings(queues, queueBindings, name)) { storage.deleteDestination(PersistedType.Queue, name); valueReturn.set(true); } @@ -763,17 +670,14 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback } @Override - public boolean removeTopicFromBindingRegistry(String name, String bindings) throws Exception - { + public boolean removeTopicFromBindingRegistry(String name, String bindings) throws Exception { checkInitialised(); - if (removeFromBindings(topicBindings, name, bindings)) - { + if (removeFromBindings(topicBindings, name, bindings)) { storage.deleteBindings(PersistedType.Topic, name, bindings); return true; } - else - { + else { return false; } } @@ -781,26 +685,21 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback /* (non-Javadoc) * @see org.apache.activemq.artemis.jms.server.JMSServerManager#removeTopicFromBindings(java.lang.String, java.lang.String) */ - public boolean removeTopicFromBindingRegistry(final String name) throws Exception - { + public boolean removeTopicFromBindingRegistry(final String name) throws Exception { final AtomicBoolean valueReturn = new AtomicBoolean(false); // HORNETQ-911 - make this runAfterActive to prevent WARN messages on shutdown/undeployment when the backup was never activated - runAfterActive(new WrappedRunnable() - { + runAfterActive(new WrappedRunnable() { @Override - public String toString() - { + public String toString() { return "removeTopicFromBindings for " + name; } @Override - public void runException() throws Exception - { + public void runException() throws Exception { checkInitialised(); - if (removeFromBindings(topics, topicBindings, name)) - { + if (removeFromBindings(topics, topicBindings, name)) { storage.deleteDestination(PersistedType.Topic, name); valueReturn.set(true); } @@ -811,8 +710,7 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback } @Override - public boolean removeConnectionFactoryFromBindingRegistry(String name, String bindings) throws Exception - { + public boolean removeConnectionFactoryFromBindingRegistry(String name, String bindings) throws Exception { checkInitialised(); removeFromBindings(connectionFactoryBindings, name, bindings); @@ -823,8 +721,7 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback } @Override - public boolean removeConnectionFactoryFromBindingRegistry(String name) throws Exception - { + public boolean removeConnectionFactoryFromBindingRegistry(String name) throws Exception { checkInitialised(); removeFromBindings(connectionFactories, connectionFactoryBindings, name); @@ -834,21 +731,18 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback return true; } - public synchronized boolean destroyQueue(final String name) throws Exception - { + public synchronized boolean destroyQueue(final String name) throws Exception { return destroyQueue(name, true); } - public synchronized boolean destroyQueue(final String name, final boolean removeConsumers) throws Exception - { + public synchronized boolean destroyQueue(final String name, final boolean removeConsumers) throws Exception { checkInitialised(); server.destroyQueue(ActiveMQDestination.createQueueAddressFromName(name), null, !removeConsumers, removeConsumers); // if the queue has consumers and 'removeConsumers' is false then the queue won't actually be removed // therefore only remove the queue from Bindings, etc. if the queue is actually removed - if (this.server.getPostOffice().getBinding(ActiveMQDestination.createQueueAddressFromName(name)) == null) - { + if (this.server.getPostOffice().getBinding(ActiveMQDestination.createQueueAddressFromName(name)) == null) { removeFromBindings(queues, queueBindings, name); queues.remove(name); @@ -861,42 +755,33 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback sendNotification(JMSNotificationType.QUEUE_DESTROYED, name); return true; } - else - { + else { return false; } } - public synchronized boolean destroyTopic(final String name) throws Exception - { + public synchronized boolean destroyTopic(final String name) throws Exception { return destroyTopic(name, true); } - public synchronized boolean destroyTopic(final String name, final boolean removeConsumers) throws Exception - { + public synchronized boolean destroyTopic(final String name, final boolean removeConsumers) throws Exception { checkInitialised(); - AddressControl addressControl = (AddressControl) server.getManagementService() - .getResource(ResourceNames.CORE_ADDRESS + ActiveMQDestination.createTopicAddressFromName(name)); - if (addressControl != null) - { - for (String queueName : addressControl.getQueueNames()) - { + AddressControl addressControl = (AddressControl) server.getManagementService().getResource(ResourceNames.CORE_ADDRESS + ActiveMQDestination.createTopicAddressFromName(name)); + if (addressControl != null) { + for (String queueName : addressControl.getQueueNames()) { Binding binding = server.getPostOffice().getBinding(new SimpleString(queueName)); - if (binding == null) - { + if (binding == null) { ActiveMQJMSServerLogger.LOGGER.noQueueOnTopic(queueName, name); continue; } // We can't remove the remote binding. As this would be the bridge associated with the topic on this case - if (binding.getType() != BindingType.REMOTE_QUEUE) - { + if (binding.getType() != BindingType.REMOTE_QUEUE) { server.destroyQueue(SimpleString.toSimpleString(queueName), null, !removeConsumers, removeConsumers); } } - if (addressControl.getQueueNames().length == 0) - { + if (addressControl.getQueueNames().length == 0) { removeFromBindings(topics, topicBindings, name); topics.remove(name); @@ -909,13 +794,11 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback sendNotification(JMSNotificationType.TOPIC_DESTROYED, name); return true; } - else - { + else { return false; } } - else - { + else { return false; } } @@ -924,17 +807,11 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback final boolean ha, final JMSFactoryType cfType, final List connectorNames, - String... registryBindings) throws Exception - { + String... registryBindings) throws Exception { checkInitialised(); ActiveMQConnectionFactory cf = connectionFactories.get(name); - if (cf == null) - { - ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl() - .setName(name) - .setHA(ha) - .setConnectorNames(connectorNames) - .setFactoryType(cfType); + if (cf == null) { + ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl().setName(name).setHA(ha).setConnectorNames(connectorNames).setFactoryType(cfType); createConnectionFactory(true, configuration, registryBindings); } @@ -974,46 +851,11 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback final int reconnectAttempts, final boolean failoverOnInitialConnection, final String groupId, - String... registryBindings) throws Exception - { + String... registryBindings) throws Exception { checkInitialised(); ActiveMQConnectionFactory cf = connectionFactories.get(name); - if (cf == null) - { - ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl() - .setName(name) - .setHA(ha) - .setConnectorNames(connectorNames) - .setClientID(clientID) - .setClientFailureCheckPeriod(clientFailureCheckPeriod) - .setConnectionTTL(connectionTTL) - .setFactoryType(cfType) - .setCallTimeout(callTimeout) - .setCallFailoverTimeout(callFailoverTimeout) - .setCacheLargeMessagesClient(cacheLargeMessagesClient) - .setMinLargeMessageSize(minLargeMessageSize) - .setConsumerWindowSize(consumerWindowSize) - .setConsumerMaxRate(consumerMaxRate) - .setConfirmationWindowSize(confirmationWindowSize) - .setProducerWindowSize(producerWindowSize) - .setProducerMaxRate(producerMaxRate) - .setBlockOnAcknowledge(blockOnAcknowledge) - .setBlockOnDurableSend(blockOnDurableSend) - .setBlockOnNonDurableSend(blockOnNonDurableSend) - .setAutoGroup(autoGroup) - .setPreAcknowledge(preAcknowledge) - .setLoadBalancingPolicyClassName(loadBalancingPolicyClassName) - .setTransactionBatchSize(transactionBatchSize) - .setDupsOKBatchSize(dupsOKBatchSize) - .setUseGlobalPools(useGlobalPools) - .setScheduledThreadPoolMaxSize(scheduledThreadPoolMaxSize) - .setThreadPoolMaxSize(threadPoolMaxSize) - .setRetryInterval(retryInterval) - .setRetryIntervalMultiplier(retryIntervalMultiplier) - .setMaxRetryInterval(maxRetryInterval) - .setReconnectAttempts(reconnectAttempts) - .setFailoverOnInitialConnection(failoverOnInitialConnection) - .setGroupID(groupId); + if (cf == null) { + ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl().setName(name).setHA(ha).setConnectorNames(connectorNames).setClientID(clientID).setClientFailureCheckPeriod(clientFailureCheckPeriod).setConnectionTTL(connectionTTL).setFactoryType(cfType).setCallTimeout(callTimeout).setCallFailoverTimeout(callFailoverTimeout).setCacheLargeMessagesClient(cacheLargeMessagesClient).setMinLargeMessageSize(minLargeMessageSize).setConsumerWindowSize(consumerWindowSize).setConsumerMaxRate(consumerMaxRate).setConfirmationWindowSize(confirmationWindowSize).setProducerWindowSize(producerWindowSize).setProducerMaxRate(producerMaxRate).setBlockOnAcknowledge(blockOnAcknowledge).setBlockOnDurableSend(blockOnDurableSend).setBlockOnNonDurableSend(blockOnNonDurableSend).setAutoGroup(autoGroup).setPreAcknowledge(preAcknowledge).setLoadBalancingPolicyClassName(loadBalancingPolicyClassName).setTransactionBatchSize(transactionBatchSize).setDupsOKBatchSize(dupsOKBatchSize).setUseGlobalPools(useGlobalPools).setScheduledThreadPoolMaxSize(scheduledThreadPoolMaxSize).setThreadPoolMaxSize(threadPoolMaxSize).setRetryInterval(retryInterval).setRetryIntervalMultiplier(retryIntervalMultiplier).setMaxRetryInterval(maxRetryInterval).setReconnectAttempts(reconnectAttempts).setFailoverOnInitialConnection(failoverOnInitialConnection).setGroupID(groupId); createConnectionFactory(true, configuration, registryBindings); } @@ -1053,47 +895,11 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback final int reconnectAttempts, final boolean failoverOnInitialConnection, final String groupId, - final String... registryBindings) throws Exception - { + final String... registryBindings) throws Exception { checkInitialised(); ActiveMQConnectionFactory cf = connectionFactories.get(name); - if (cf == null) - { - ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl() - .setName(name) - .setHA(ha) - .setBindings(registryBindings) - .setDiscoveryGroupName(discoveryGroupName) - .setFactoryType(cfType) - .setClientID(clientID) - .setClientFailureCheckPeriod(clientFailureCheckPeriod) - .setConnectionTTL(connectionTTL) - .setCallTimeout(callTimeout) - .setCallFailoverTimeout(callFailoverTimeout) - .setCacheLargeMessagesClient(cacheLargeMessagesClient) - .setMinLargeMessageSize(minLargeMessageSize) - .setCompressLargeMessages(compressLargeMessages) - .setConsumerWindowSize(consumerWindowSize) - .setConsumerMaxRate(consumerMaxRate) - .setConfirmationWindowSize(confirmationWindowSize) - .setProducerWindowSize(producerWindowSize) - .setProducerMaxRate(producerMaxRate) - .setBlockOnAcknowledge(blockOnAcknowledge) - .setBlockOnDurableSend(blockOnDurableSend) - .setBlockOnNonDurableSend(blockOnNonDurableSend) - .setAutoGroup(autoGroup) - .setPreAcknowledge(preAcknowledge) - .setLoadBalancingPolicyClassName(loadBalancingPolicyClassName) - .setTransactionBatchSize(transactionBatchSize) - .setDupsOKBatchSize(dupsOKBatchSize) - .setUseGlobalPools(useGlobalPools) - .setScheduledThreadPoolMaxSize(scheduledThreadPoolMaxSize) - .setThreadPoolMaxSize(threadPoolMaxSize) - .setRetryInterval(retryInterval) - .setRetryIntervalMultiplier(retryIntervalMultiplier) - .setMaxRetryInterval(maxRetryInterval) - .setReconnectAttempts(reconnectAttempts) - .setFailoverOnInitialConnection(failoverOnInitialConnection); + if (cf == null) { + ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl().setName(name).setHA(ha).setBindings(registryBindings).setDiscoveryGroupName(discoveryGroupName).setFactoryType(cfType).setClientID(clientID).setClientFailureCheckPeriod(clientFailureCheckPeriod).setConnectionTTL(connectionTTL).setCallTimeout(callTimeout).setCallFailoverTimeout(callFailoverTimeout).setCacheLargeMessagesClient(cacheLargeMessagesClient).setMinLargeMessageSize(minLargeMessageSize).setCompressLargeMessages(compressLargeMessages).setConsumerWindowSize(consumerWindowSize).setConsumerMaxRate(consumerMaxRate).setConfirmationWindowSize(confirmationWindowSize).setProducerWindowSize(producerWindowSize).setProducerMaxRate(producerMaxRate).setBlockOnAcknowledge(blockOnAcknowledge).setBlockOnDurableSend(blockOnDurableSend).setBlockOnNonDurableSend(blockOnNonDurableSend).setAutoGroup(autoGroup).setPreAcknowledge(preAcknowledge).setLoadBalancingPolicyClassName(loadBalancingPolicyClassName).setTransactionBatchSize(transactionBatchSize).setDupsOKBatchSize(dupsOKBatchSize).setUseGlobalPools(useGlobalPools).setScheduledThreadPoolMaxSize(scheduledThreadPoolMaxSize).setThreadPoolMaxSize(threadPoolMaxSize).setRetryInterval(retryInterval).setRetryIntervalMultiplier(retryIntervalMultiplier).setMaxRetryInterval(maxRetryInterval).setReconnectAttempts(reconnectAttempts).setFailoverOnInitialConnection(failoverOnInitialConnection); createConnectionFactory(true, configuration, registryBindings); } } @@ -1102,27 +908,20 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback final boolean ha, final JMSFactoryType cfType, final String discoveryGroupName, - final String... registryBindings) throws Exception - { + final String... registryBindings) throws Exception { checkInitialised(); ActiveMQConnectionFactory cf = connectionFactories.get(name); - if (cf == null) - { - ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl() - .setName(name) - .setHA(ha) - .setBindings(registryBindings) - .setDiscoveryGroupName(discoveryGroupName); + if (cf == null) { + ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl().setName(name).setHA(ha).setBindings(registryBindings).setDiscoveryGroupName(discoveryGroupName); createConnectionFactory(true, configuration, registryBindings); } } - public synchronized ActiveMQConnectionFactory recreateCF(String name, ConnectionFactoryConfiguration cf) throws Exception - { + public synchronized ActiveMQConnectionFactory recreateCF(String name, + ConnectionFactoryConfiguration cf) throws Exception { List bindings = connectionFactoryBindings.get(name); - if (bindings == null) - { + if (bindings == null) { throw ActiveMQJMSServerBundle.BUNDLE.cfDoesntExist(name); } @@ -1130,14 +929,12 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback ActiveMQConnectionFactory realCF = internalCreateCFPOJO(cf); - if (cf.isPersisted()) - { + if (cf.isPersisted()) { storage.storeConnectionFactory(new PersistedConnectionFactory(cf)); storage.addBindings(PersistedType.ConnectionFactory, cf.getName(), usedBindings); } - for (String bindingsElement : usedBindings) - { + for (String bindingsElement : usedBindings) { this.bindToBindings(bindingsElement, realCF); } @@ -1146,30 +943,24 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback public synchronized void createConnectionFactory(final boolean storeConfig, final ConnectionFactoryConfiguration cfConfig, - final String... bindings) throws Exception - { - runAfterActive(new WrappedRunnable() - { + final String... bindings) throws Exception { + runAfterActive(new WrappedRunnable() { @Override - public String toString() - { + public String toString() { return "createConnectionFactory for " + cfConfig.getName(); } @Override - public void runException() throws Exception - { + public void runException() throws Exception { checkBindings(bindings); ActiveMQConnectionFactory cf = internalCreateCF(storeConfig, cfConfig); ArrayList bindingsToAdd = new ArrayList(); - for (String bindingsItem : bindings) - { - if (bindToBindings(bindingsItem, cf)) - { + for (String bindingsItem : bindings) { + if (bindToBindings(bindingsItem, cf)) { bindingsToAdd.add(bindingsItem); } } @@ -1177,8 +968,7 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback String[] usedBindings = bindingsToAdd.toArray(new String[bindingsToAdd.size()]); addToBindings(connectionFactoryBindings, cfConfig.getName(), usedBindings); - if (storeConfig) - { + if (storeConfig) { storage.storeConnectionFactory(new PersistedConnectionFactory(cfConfig)); storage.addBindings(PersistedType.ConnectionFactory, cfConfig.getName(), usedBindings); } @@ -1189,70 +979,56 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback }); } - private void sendNotification(JMSNotificationType type, String message) - { + private void sendNotification(JMSNotificationType type, String message) { TypedProperties prop = new TypedProperties(); prop.putSimpleStringProperty(JMSNotificationType.MESSAGE, SimpleString.toSimpleString(message)); Notification notif = new Notification(null, type, prop); - try - { + try { server.getManagementService().sendNotification(notif); } - catch (Exception e) - { + catch (Exception e) { ActiveMQJMSServerLogger.LOGGER.failedToSendNotification(notif.toString()); } } - public JMSStorageManager getJMSStorageManager() - { + public JMSStorageManager getJMSStorageManager() { return storage; } // used on tests only - public void replaceStorageManager(JMSStorageManager newStorage) - { + public void replaceStorageManager(JMSStorageManager newStorage) { this.storage = newStorage; } - private String[] getBindingsList(final Map> map, final String name) - { + private String[] getBindingsList(final Map> map, final String name) { List result = map.get(name); - if (result == null) - { + if (result == null) { return new String[0]; } - else - { + else { String[] strings = new String[result.size()]; result.toArray(strings); return strings; } } - private boolean internalCreateQueue(final String queueName, final String selectorString, final boolean durable) throws Exception - { - if (queues.get(queueName) != null) - { + private boolean internalCreateQueue(final String queueName, + final String selectorString, + final boolean durable) throws Exception { + if (queues.get(queueName) != null) { return false; } - else - { + else { ActiveMQQueue activeMQQueue = ActiveMQDestination.createQueue(queueName); // Convert from JMS selector to core filter String coreFilterString = null; - if (selectorString != null) - { + if (selectorString != null) { coreFilterString = SelectorTranslator.convertToActiveMQFilterString(selectorString); } - Queue queue = server.deployQueue(SimpleString.toSimpleString(activeMQQueue.getAddress()), - SimpleString.toSimpleString(activeMQQueue.getAddress()), - SimpleString.toSimpleString(coreFilterString), - durable, - false); + Queue queue = server.deployQueue(SimpleString.toSimpleString(activeMQQueue.getAddress()), SimpleString.toSimpleString(activeMQQueue.getAddress()), SimpleString.toSimpleString(coreFilterString), durable, false); queues.put(queueName, activeMQQueue); @@ -1272,25 +1048,18 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback * @return * @throws Exception */ - private boolean internalCreateTopic(final String topicName) throws Exception - { + private boolean internalCreateTopic(final String topicName) throws Exception { - if (topics.get(topicName) != null) - { + if (topics.get(topicName) != null) { return false; } - else - { + else { ActiveMQTopic activeMQTopic = ActiveMQDestination.createTopic(topicName); // We create a dummy subscription on the topic, that never receives messages - this is so we can perform JMS // checks when routing messages to a topic that // does not exist - otherwise we would not be able to distinguish from a non existent topic and one with no // subscriptions - core has no notion of a topic - server.deployQueue(SimpleString.toSimpleString(activeMQTopic.getAddress()), - SimpleString.toSimpleString(activeMQTopic.getAddress()), - SimpleString.toSimpleString(JMSServerManagerImpl.REJECT_FILTER), - true, - false); + server.deployQueue(SimpleString.toSimpleString(activeMQTopic.getAddress()), SimpleString.toSimpleString(activeMQTopic.getAddress()), SimpleString.toSimpleString(JMSServerManagerImpl.REJECT_FILTER), true, false); topics.put(topicName, activeMQTopic); @@ -1307,14 +1076,12 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback * @throws Exception */ private ActiveMQConnectionFactory internalCreateCF(final boolean persisted, - final ConnectionFactoryConfiguration cfConfig) throws Exception - { + final ConnectionFactoryConfiguration cfConfig) throws Exception { checkInitialised(); ActiveMQConnectionFactory cf = connectionFactories.get(cfConfig.getName()); - if (cf == null) - { + if (cf == null) { cf = internalCreateCFPOJO(cfConfig); } @@ -1330,56 +1097,43 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback * @return * @throws ActiveMQException */ - protected ActiveMQConnectionFactory internalCreateCFPOJO(final ConnectionFactoryConfiguration cfConfig) throws ActiveMQException - { + protected ActiveMQConnectionFactory internalCreateCFPOJO(final ConnectionFactoryConfiguration cfConfig) throws ActiveMQException { ActiveMQConnectionFactory cf; - if (cfConfig.getDiscoveryGroupName() != null) - { - DiscoveryGroupConfiguration groupConfig = server.getConfiguration() - .getDiscoveryGroupConfigurations() - .get(cfConfig.getDiscoveryGroupName()); + if (cfConfig.getDiscoveryGroupName() != null) { + DiscoveryGroupConfiguration groupConfig = server.getConfiguration().getDiscoveryGroupConfigurations().get(cfConfig.getDiscoveryGroupName()); - if (groupConfig == null) - { + if (groupConfig == null) { throw ActiveMQJMSServerBundle.BUNDLE.discoveryGroupDoesntExist(cfConfig.getDiscoveryGroupName()); } - if (cfConfig.isHA()) - { + if (cfConfig.isHA()) { cf = ActiveMQJMSClient.createConnectionFactoryWithHA(groupConfig, cfConfig.getFactoryType()); } - else - { + else { cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(groupConfig, cfConfig.getFactoryType()); } } - else - { - if (cfConfig.getConnectorNames() == null || cfConfig.getConnectorNames().size() == 0) - { + else { + if (cfConfig.getConnectorNames() == null || cfConfig.getConnectorNames().size() == 0) { throw ActiveMQJMSServerBundle.BUNDLE.noConnectorNameOnCF(); } TransportConfiguration[] configs = new TransportConfiguration[cfConfig.getConnectorNames().size()]; int count = 0; - for (String name : cfConfig.getConnectorNames()) - { + for (String name : cfConfig.getConnectorNames()) { TransportConfiguration connector = server.getConfiguration().getConnectorConfigurations().get(name); - if (connector == null) - { + if (connector == null) { throw ActiveMQJMSServerBundle.BUNDLE.noConnectorNameConfiguredOnCF(name); } correctInvalidNettyConnectorHost(connector); configs[count++] = connector; } - if (cfConfig.isHA()) - { + if (cfConfig.isHA()) { cf = ActiveMQJMSClient.createConnectionFactoryWithHA(cfConfig.getFactoryType(), configs); } - else - { + else { cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(cfConfig.getFactoryType(), configs); } } @@ -1417,23 +1171,19 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback return cf; } - public synchronized boolean destroyConnectionFactory(final String name) throws Exception - { + public synchronized boolean destroyConnectionFactory(final String name) throws Exception { final AtomicBoolean valueReturn = new AtomicBoolean(false); // HORNETQ-911 - make this runAfterActive to prevent WARN messages on shutdown/undeployment when the backup was never activated - runAfterActive(new WrappedRunnable() - { + runAfterActive(new WrappedRunnable() { @Override - public String toString() - { + public String toString() { return "destroyConnectionFactory for " + name; } @Override - public void runException() throws Exception - { + public void runException() throws Exception { shutdownConnectionFactory(name); storage.deleteConnectionFactory(name); @@ -1441,8 +1191,7 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback } }); - if (valueReturn.get()) - { + if (valueReturn.get()) { sendNotification(JMSNotificationType.CONNECTION_FACTORY_DESTROYED, name); } @@ -1453,15 +1202,12 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback * @param name * @throws Exception */ - protected boolean shutdownConnectionFactory(final String name) throws Exception - { + protected boolean shutdownConnectionFactory(final String name) throws Exception { checkInitialised(); List registryBindings = connectionFactoryBindings.get(name); - if (registry != null) - { - for (String registryBinding : registryBindings) - { + if (registry != null) { + for (String registryBinding : registryBindings) { registry.unbind(registryBinding); } } @@ -1474,73 +1220,60 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback return true; } - public String[] listRemoteAddresses() throws Exception - { + public String[] listRemoteAddresses() throws Exception { checkInitialised(); return server.getActiveMQServerControl().listRemoteAddresses(); } - public String[] listRemoteAddresses(final String ipAddress) throws Exception - { + public String[] listRemoteAddresses(final String ipAddress) throws Exception { checkInitialised(); return server.getActiveMQServerControl().listRemoteAddresses(ipAddress); } - public boolean closeConnectionsForAddress(final String ipAddress) throws Exception - { + public boolean closeConnectionsForAddress(final String ipAddress) throws Exception { checkInitialised(); return server.getActiveMQServerControl().closeConnectionsForAddress(ipAddress); } - public boolean closeConsumerConnectionsForAddress(final String address) throws Exception - { + public boolean closeConsumerConnectionsForAddress(final String address) throws Exception { checkInitialised(); return server.getActiveMQServerControl().closeConsumerConnectionsForAddress(address); } - public boolean closeConnectionsForUser(final String userName) throws Exception - { + public boolean closeConnectionsForUser(final String userName) throws Exception { checkInitialised(); return server.getActiveMQServerControl().closeConnectionsForUser(userName); } - public String[] listConnectionIDs() throws Exception - { + public String[] listConnectionIDs() throws Exception { return server.getActiveMQServerControl().listConnectionIDs(); } - public String[] listSessions(final String connectionID) throws Exception - { + public String[] listSessions(final String connectionID) throws Exception { checkInitialised(); return server.getActiveMQServerControl().listSessions(connectionID); } - public String listPreparedTransactionDetailsAsJSON() throws Exception - { + public String listPreparedTransactionDetailsAsJSON() throws Exception { ResourceManager resourceManager = server.getResourceManager(); Map xids = resourceManager.getPreparedTransactionsWithCreationTime(); - if (xids == null || xids.size() == 0) - { + if (xids == null || xids.size() == 0) { return ""; } ArrayList> xidsSortedByCreationTime = new ArrayList>(xids.entrySet()); - Collections.sort(xidsSortedByCreationTime, new Comparator>() - { - public int compare(final Entry entry1, final Entry entry2) - { + Collections.sort(xidsSortedByCreationTime, new Comparator>() { + public int compare(final Entry entry1, final Entry entry2) { // sort by creation time, oldest first return (int) (entry1.getValue() - entry2.getValue()); } }); JSONArray txDetailListJson = new JSONArray(); - for (Map.Entry entry : xidsSortedByCreationTime) - { + for (Map.Entry entry : xidsSortedByCreationTime) { Xid xid = entry.getKey(); Transaction tx = resourceManager.getTransaction(xid); - if (tx == null) - { + if (tx == null) { continue; } TransactionDetail detail = new JMSTransactionDetail(xid, tx, entry.getValue()); @@ -1549,20 +1282,16 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback return txDetailListJson.toString(); } - public String listPreparedTransactionDetailsAsHTML() throws Exception - { + public String listPreparedTransactionDetailsAsHTML() throws Exception { ResourceManager resourceManager = server.getResourceManager(); Map xids = resourceManager.getPreparedTransactionsWithCreationTime(); - if (xids == null || xids.size() == 0) - { + if (xids == null || xids.size() == 0) { return "

    *** Prepared Transaction Details ***

    No entry.

    "; } ArrayList> xidsSortedByCreationTime = new ArrayList>(xids.entrySet()); - Collections.sort(xidsSortedByCreationTime, new Comparator>() - { - public int compare(final Entry entry1, final Entry entry2) - { + Collections.sort(xidsSortedByCreationTime, new Comparator>() { + public int compare(final Entry entry1, final Entry entry2) { // sort by creation time, oldest first return (int) (entry1.getValue() - entry2.getValue()); } @@ -1571,12 +1300,10 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback StringBuilder html = new StringBuilder(); html.append("

    *** Prepared Transaction Details ***

    "); - for (Map.Entry entry : xidsSortedByCreationTime) - { + for (Map.Entry entry : xidsSortedByCreationTime) { Xid xid = entry.getKey(); Transaction tx = resourceManager.getTransaction(xid); - if (tx == null) - { + if (tx == null) { continue; } TransactionDetail detail = new JMSTransactionDetail(xid, tx, entry.getValue()); @@ -1599,15 +1326,13 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback html.append(""); JSONArray msgs = txJson.getJSONArray(TransactionDetail.KEY_TX_RELATED_MESSAGES); - for (int i = 0; i < msgs.length(); i++) - { + for (int i = 0; i < msgs.length(); i++) { JSONObject msgJson = msgs.getJSONObject(i); JSONObject props = msgJson.getJSONObject(TransactionDetail.KEY_MSG_PROPERTIES); StringBuilder propstr = new StringBuilder(); @SuppressWarnings("unchecked") Iterator propkeys = props.keys(); - while (propkeys.hasNext()) - { + while (propkeys.hasNext()) { String key = propkeys.next(); propstr.append(key); propstr.append("="); @@ -1633,74 +1358,58 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback // Private ------------------------------------------------------- - private synchronized void checkInitialised() - { - if (!active) - { + private synchronized void checkInitialised() { + if (!active) { throw new IllegalStateException("Cannot access JMS Server, core server is not yet active"); } } - private void addToBindings(Map> map, String name, String... bindings) - { + private void addToBindings(Map> map, String name, String... bindings) { List list = map.get(name); - if (list == null) - { + if (list == null) { list = new ArrayList(); map.put(name, list); } - for (String bindingsItem : bindings) - { + for (String bindingsItem : bindings) { list.add(bindingsItem); } } - private void checkBindings(final String... bindingsNames) throws NamingException - { - if (bindingsNames != null) - { - for (String bindingsName : bindingsNames) - { - if (registry != null && registry.lookup(bindingsName) != null) - { + private void checkBindings(final String... bindingsNames) throws NamingException { + if (bindingsNames != null) { + for (String bindingsName : bindingsNames) { + if (registry != null && registry.lookup(bindingsName) != null) { throw new NamingException(bindingsName + " already has an object bound"); } } } } - private boolean bindToBindings(final String bindingsName, final Object objectToBind) throws NamingException - { - if (registry != null) - { + private boolean bindToBindings(final String bindingsName, final Object objectToBind) throws NamingException { + if (registry != null) { registry.unbind(bindingsName); registry.bind(bindingsName, objectToBind); } return true; } - private void deploy() throws Exception - { - if (config == null) - { + private void deploy() throws Exception { + if (config == null) { return; } List connectionFactoryConfigurations = config.getConnectionFactoryConfigurations(); - for (ConnectionFactoryConfiguration cfConfig : connectionFactoryConfigurations) - { + for (ConnectionFactoryConfiguration cfConfig : connectionFactoryConfigurations) { createConnectionFactory(false, cfConfig, cfConfig.getBindings()); } List queueConfigs = config.getQueueConfigurations(); - for (JMSQueueConfiguration qConfig : queueConfigs) - { + for (JMSQueueConfiguration qConfig : queueConfigs) { createQueue(false, qConfig.getName(), qConfig.getSelector(), qConfig.isDurable(), qConfig.getBindings()); } List topicConfigs = config.getTopicConfigurations(); - for (TopicConfiguration tConfig : topicConfigs) - { + for (TopicConfiguration tConfig : topicConfigs) { createTopic(false, tConfig.getName(), tConfig.getBindings()); } } @@ -1708,20 +1417,14 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback /** * @param param */ - private void unbindBindings(Map> param) - { - if (registry != null) - { - for (List elementList : param.values()) - { - for (String key : elementList) - { - try - { + private void unbindBindings(Map> param) { + if (registry != null) { + for (List elementList : param.values()) { + for (String key : elementList) { + try { registry.unbind(key); } - catch (Exception e) - { + catch (Exception e) { ActiveMQJMSServerLogger.LOGGER.bindingsUnbindError(e, key); } } @@ -1732,8 +1435,7 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback /** * @throws Exception */ - private void initJournal() throws Exception - { + private void initJournal() throws Exception { this.coreConfig = server.getConfiguration(); createJournal(); @@ -1742,21 +1444,17 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback List cfs = storage.recoverConnectionFactories(); - for (PersistedConnectionFactory cf : cfs) - { + for (PersistedConnectionFactory cf : cfs) { internalCreateCF(true, cf.getConfig()); } List destinations = storage.recoverDestinations(); - for (PersistedDestination destination : destinations) - { - if (destination.getType() == PersistedType.Queue) - { + for (PersistedDestination destination : destinations) { + if (destination.getType() == PersistedType.Queue) { internalCreateQueue(destination.getName(), destination.getSelector(), destination.isDurable()); } - else if (destination.getType() == PersistedType.Topic) - { + else if (destination.getType() == PersistedType.Topic) { internalCreateTopic(destination.getName()); } } @@ -1765,25 +1463,17 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback /** * @throws Exception */ - private void createJournal() throws Exception - { - if (storage == null) - { - if (coreConfig.isPersistenceEnabled()) - { - storage = new JMSJournalStorageManagerImpl(new TimeAndCounterIDGenerator(), - server.getConfiguration(), - server.getReplicationManager()); + private void createJournal() throws Exception { + if (storage == null) { + if (coreConfig.isPersistenceEnabled()) { + storage = new JMSJournalStorageManagerImpl(new TimeAndCounterIDGenerator(), server.getConfiguration(), server.getReplicationManager()); } - else - { + else { storage = new NullJMSStorageManagerImpl(); } } - else - { - if (storage.isStarted()) - { + else { + if (storage.isStarted()) { storage.stop(); } } @@ -1792,24 +1482,19 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback } private synchronized boolean removeFromBindings(final Map keys, - final Map> bindingsMap, - final String name) throws Exception - { + final Map> bindingsMap, + final String name) throws Exception { checkInitialised(); List registryBindings = bindingsMap.remove(name); - if (registryBindings == null || registryBindings.size() == 0) - { + if (registryBindings == null || registryBindings.size() == 0) { return false; } - else - { + else { keys.remove(name); } - if (registry != null) - { + if (registry != null) { Iterator iter = registryBindings.iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { String registryBinding = iter.next(); registry.unbind(registryBinding); iter.remove(); @@ -1819,36 +1504,29 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback } private synchronized boolean removeFromBindings(final Map> bindingsMap, - final String name, - final String bindings) throws Exception - { + final String name, + final String bindings) throws Exception { checkInitialised(); List registryBindings = bindingsMap.get(name); - if (registryBindings == null || registryBindings.size() == 0) - { + if (registryBindings == null || registryBindings.size() == 0) { return false; } - if (registryBindings.remove(bindings)) - { + if (registryBindings.remove(bindings)) { registry.unbind(bindings); return true; } - else - { + else { return false; } } - private boolean runAfterActive(WrappedRunnable runnable) throws Exception - { - if (active) - { + private boolean runAfterActive(WrappedRunnable runnable) throws Exception { + if (active) { runnable.runException(); return true; } - else - { + else { ActiveMQJMSServerLogger.LOGGER.serverCachingCommand(runnable); if (!cachedCommands.contains(runnable)) cachedCommands.add(runnable); @@ -1856,16 +1534,13 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback } } - private abstract class WrappedRunnable implements Runnable - { - public void run() - { - try - { + private abstract class WrappedRunnable implements Runnable { + + public void run() { + try { runException(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQJMSServerLogger.LOGGER.jmsServerError(e); } } @@ -1873,50 +1548,39 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback public abstract void runException() throws Exception; } - private void correctInvalidNettyConnectorHost(TransportConfiguration transportConfiguration) - { + private void correctInvalidNettyConnectorHost(TransportConfiguration transportConfiguration) { Map params = transportConfiguration.getParams(); if (transportConfiguration.getFactoryClassName().equals(NettyConnectorFactory.class.getCanonicalName()) && params.containsKey(TransportConstants.HOST_PROP_NAME) && - params.get(TransportConstants.HOST_PROP_NAME).equals("0.0.0.0")) - { - try - { + params.get(TransportConstants.HOST_PROP_NAME).equals("0.0.0.0")) { + try { String newHost = InetAddress.getLocalHost().getHostName(); ActiveMQJMSServerLogger.LOGGER.invalidHostForConnector(transportConfiguration.getName(), newHost); params.put(TransportConstants.HOST_PROP_NAME, newHost); } - catch (UnknownHostException e) - { + catch (UnknownHostException e) { ActiveMQJMSServerLogger.LOGGER.failedToCorrectHost(e, transportConfiguration.getName()); } } } + class JMSQueueCreator implements QueueCreator { - - - class JMSQueueCreator implements QueueCreator - { private final SimpleString PREFIX = SimpleString.toSimpleString("jms.queue"); + @Override - public boolean create(SimpleString address) throws Exception - { + public boolean create(SimpleString address) throws Exception { AddressSettings settings = server.getAddressSettingsRepository().getMatch(address.toString()); - if (address.startsWith(PREFIX) && settings.isAutoCreateJmsQueues()) - { + if (address.startsWith(PREFIX) && settings.isAutoCreateJmsQueues()) { // stopped here... finish here JMSServerManagerImpl.this.internalCreateJMSQueue(false, address.toString().substring(PREFIX.toString().length() + 1), null, true, true); return true; } - else - { + else { return false; } } } - - } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/management/JMSManagementService.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/management/JMSManagementService.java index a589f48d21..ff6c2400b3 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/management/JMSManagementService.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/management/JMSManagementService.java @@ -24,8 +24,8 @@ import org.apache.activemq.artemis.jms.client.ActiveMQTopic; import org.apache.activemq.artemis.jms.server.JMSServerManager; import org.apache.activemq.artemis.jms.server.config.ConnectionFactoryConfiguration; -public interface JMSManagementService -{ +public interface JMSManagementService { + JMSServerControl registerJMSServer(JMSServerManager server) throws Exception; void unregisterJMSServer() throws Exception; @@ -38,7 +38,9 @@ public interface JMSManagementService void unregisterTopic(String name) throws Exception; - void registerConnectionFactory(String name, ConnectionFactoryConfiguration config, ActiveMQConnectionFactory connectionFactory) throws Exception; + void registerConnectionFactory(String name, + ConnectionFactoryConfiguration config, + ActiveMQConnectionFactory connectionFactory) throws Exception; void unregisterConnectionFactory(String name) throws Exception; diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/management/JMSNotificationType.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/management/JMSNotificationType.java index a2a77e443f..68ec9edfcc 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/management/JMSNotificationType.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/management/JMSNotificationType.java @@ -19,8 +19,7 @@ package org.apache.activemq.artemis.jms.server.management; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.management.NotificationType; -public enum JMSNotificationType implements NotificationType -{ +public enum JMSNotificationType implements NotificationType { QUEUE_CREATED(0), QUEUE_DESTROYED(1), TOPIC_CREATED(2), @@ -32,14 +31,12 @@ public enum JMSNotificationType implements NotificationType private int type; - private JMSNotificationType(int type) - { + private JMSNotificationType(int type) { this.type = type; } @Override - public int getType() - { + public int getType() { return type; } } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/management/impl/JMSManagementServiceImpl.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/management/impl/JMSManagementServiceImpl.java index 5814fbc316..9549d91ba7 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/management/impl/JMSManagementServiceImpl.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/management/impl/JMSManagementServiceImpl.java @@ -41,8 +41,7 @@ import org.apache.activemq.artemis.jms.server.JMSServerManager; import org.apache.activemq.artemis.jms.server.config.ConnectionFactoryConfiguration; import org.apache.activemq.artemis.jms.server.management.JMSManagementService; -public class JMSManagementServiceImpl implements JMSManagementService -{ +public class JMSManagementServiceImpl implements JMSManagementService { // Constants ----------------------------------------------------- @@ -54,8 +53,9 @@ public class JMSManagementServiceImpl implements JMSManagementService // Static -------------------------------------------------------- - public JMSManagementServiceImpl(final ManagementService managementService, final ActiveMQServer server, final JMSServerManager jmsServerManager) - { + public JMSManagementServiceImpl(final ManagementService managementService, + final ActiveMQServer server, + final JMSServerManager jmsServerManager) { this.managementService = managementService; this.jmsServerManager = jmsServerManager; } @@ -64,8 +64,7 @@ public class JMSManagementServiceImpl implements JMSManagementService // JMSManagementRegistration implementation ---------------------- - public synchronized JMSServerControl registerJMSServer(final JMSServerManager server) throws Exception - { + public synchronized JMSServerControl registerJMSServer(final JMSServerManager server) throws Exception { ObjectName objectName = managementService.getObjectNameBuilder().getJMSServerObjectName(); JMSServerControlImpl control = new JMSServerControlImpl(server); managementService.registerInJMX(objectName, control); @@ -73,23 +72,16 @@ public class JMSManagementServiceImpl implements JMSManagementService return control; } - public synchronized void unregisterJMSServer() throws Exception - { + public synchronized void unregisterJMSServer() throws Exception { ObjectName objectName = managementService.getObjectNameBuilder().getJMSServerObjectName(); managementService.unregisterFromJMX(objectName); managementService.unregisterFromRegistry(ResourceNames.JMS_SERVER); } - public synchronized void registerQueue(final ActiveMQQueue queue, final Queue serverQueue) throws Exception - { - QueueControl coreQueueControl = (QueueControl)managementService.getResource(ResourceNames.CORE_QUEUE + queue.getAddress()); + public synchronized void registerQueue(final ActiveMQQueue queue, final Queue serverQueue) throws Exception { + QueueControl coreQueueControl = (QueueControl) managementService.getResource(ResourceNames.CORE_QUEUE + queue.getAddress()); MessageCounterManager messageCounterManager = managementService.getMessageCounterManager(); - MessageCounter counter = new MessageCounter(queue.getName(), - null, - serverQueue, - false, - coreQueueControl.isDurable(), - messageCounterManager.getMaxDayCount()); + MessageCounter counter = new MessageCounter(queue.getName(), null, serverQueue, false, coreQueueControl.isDurable(), messageCounterManager.getMaxDayCount()); messageCounterManager.registerMessageCounter(queue.getName(), counter); ObjectName objectName = managementService.getObjectNameBuilder().getJMSQueueObjectName(queue.getQueueName()); JMSQueueControlImpl control = new JMSQueueControlImpl(queue, coreQueueControl, jmsServerManager, counter); @@ -97,24 +89,21 @@ public class JMSManagementServiceImpl implements JMSManagementService managementService.registerInRegistry(ResourceNames.JMS_QUEUE + queue.getQueueName(), control); } - public synchronized void unregisterQueue(final String name) throws Exception - { + public synchronized void unregisterQueue(final String name) throws Exception { ObjectName objectName = managementService.getObjectNameBuilder().getJMSQueueObjectName(name); managementService.unregisterFromJMX(objectName); managementService.unregisterFromRegistry(ResourceNames.JMS_QUEUE + name); } - public synchronized void registerTopic(final ActiveMQTopic topic) throws Exception - { + public synchronized void registerTopic(final ActiveMQTopic topic) throws Exception { ObjectName objectName = managementService.getObjectNameBuilder().getJMSTopicObjectName(topic.getTopicName()); - AddressControl addressControl = (AddressControl)managementService.getResource(ResourceNames.CORE_ADDRESS + topic.getAddress()); + AddressControl addressControl = (AddressControl) managementService.getResource(ResourceNames.CORE_ADDRESS + topic.getAddress()); JMSTopicControlImpl control = new JMSTopicControlImpl(topic, jmsServerManager, addressControl, managementService); managementService.registerInJMX(objectName, control); managementService.registerInRegistry(ResourceNames.JMS_TOPIC + topic.getTopicName(), control); } - public synchronized void unregisterTopic(final String name) throws Exception - { + public synchronized void unregisterTopic(final String name) throws Exception { ObjectName objectName = managementService.getObjectNameBuilder().getJMSTopicObjectName(name); managementService.unregisterFromJMX(objectName); managementService.unregisterFromRegistry(ResourceNames.JMS_TOPIC + name); @@ -122,34 +111,28 @@ public class JMSManagementServiceImpl implements JMSManagementService public synchronized void registerConnectionFactory(final String name, final ConnectionFactoryConfiguration cfConfig, - final ActiveMQConnectionFactory connectionFactory) throws Exception - { + final ActiveMQConnectionFactory connectionFactory) throws Exception { ObjectName objectName = managementService.getObjectNameBuilder().getConnectionFactoryObjectName(name); JMSConnectionFactoryControlImpl control = new JMSConnectionFactoryControlImpl(cfConfig, connectionFactory, jmsServerManager, name); managementService.registerInJMX(objectName, control); managementService.registerInRegistry(ResourceNames.JMS_CONNECTION_FACTORY + name, control); } - public synchronized void unregisterConnectionFactory(final String name) throws Exception - { + public synchronized void unregisterConnectionFactory(final String name) throws Exception { ObjectName objectName = managementService.getObjectNameBuilder().getConnectionFactoryObjectName(name); managementService.unregisterFromJMX(objectName); managementService.unregisterFromRegistry(ResourceNames.JMS_CONNECTION_FACTORY + name); } - public void stop() throws Exception - { - for (Object resource : managementService.getResources(ConnectionFactoryControl.class)) - { - unregisterConnectionFactory(((ConnectionFactoryControl)resource).getName()); + public void stop() throws Exception { + for (Object resource : managementService.getResources(ConnectionFactoryControl.class)) { + unregisterConnectionFactory(((ConnectionFactoryControl) resource).getName()); } - for (Object resource : managementService.getResources(JMSQueueControl.class)) - { - unregisterQueue(((JMSQueueControl)resource).getName()); + for (Object resource : managementService.getResources(JMSQueueControl.class)) { + unregisterQueue(((JMSQueueControl) resource).getName()); } - for (Object resource : managementService.getResources(TopicControl.class)) - { - unregisterTopic(((TopicControl)resource).getName()); + for (Object resource : managementService.getResources(TopicControl.class)) { + unregisterTopic(((TopicControl) resource).getName()); } } diff --git a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/transaction/JMSTransactionDetail.java b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/transaction/JMSTransactionDetail.java index aead5e0480..cd09f4a2b9 100644 --- a/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/transaction/JMSTransactionDetail.java +++ b/artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/transaction/JMSTransactionDetail.java @@ -30,19 +30,16 @@ import org.apache.activemq.artemis.jms.client.ActiveMQObjectMessage; import org.apache.activemq.artemis.jms.client.ActiveMQStreamMessage; import org.apache.activemq.artemis.jms.client.ActiveMQTextMessage; -public class JMSTransactionDetail extends TransactionDetail -{ - public JMSTransactionDetail(Xid xid, Transaction tx, Long creation) throws Exception - { - super(xid,tx,creation); +public class JMSTransactionDetail extends TransactionDetail { + + public JMSTransactionDetail(Xid xid, Transaction tx, Long creation) throws Exception { + super(xid, tx, creation); } @Override - public String decodeMessageType(ServerMessage msg) - { + public String decodeMessageType(ServerMessage msg) { int type = msg.getType(); - switch (type) - { + switch (type) { case ActiveMQMessage.TYPE: // 0 return "Default"; case ActiveMQObjectMessage.TYPE: // 2 @@ -61,14 +58,11 @@ public class JMSTransactionDetail extends TransactionDetail } @Override - public Map decodeMessageProperties(ServerMessage msg) - { - try - { + public Map decodeMessageProperties(ServerMessage msg) { + try { return ActiveMQMessage.coreMaptoJMSMap(msg.toMap()); } - catch (Throwable t) - { + catch (Throwable t) { return null; } } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/AbstractSequentialFile.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/AbstractSequentialFile.java index acc0732732..dcb22ab37f 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/AbstractSequentialFile.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/AbstractSequentialFile.java @@ -36,8 +36,7 @@ import org.apache.activemq.artemis.core.io.buffer.TimedBufferObserver; import org.apache.activemq.artemis.journal.ActiveMQJournalBundle; import org.apache.activemq.artemis.journal.ActiveMQJournalLogger; -public abstract class AbstractSequentialFile implements SequentialFile -{ +public abstract class AbstractSequentialFile implements SequentialFile { private File file; @@ -69,8 +68,7 @@ public abstract class AbstractSequentialFile implements SequentialFile public AbstractSequentialFile(final File directory, final String file, final SequentialFileFactory factory, - final Executor writerExecutor) - { + final Executor writerExecutor) { super(); this.file = new File(directory, file); this.directory = directory; @@ -80,62 +78,49 @@ public abstract class AbstractSequentialFile implements SequentialFile // Public -------------------------------------------------------- - public final boolean exists() - { + public final boolean exists() { return file.exists(); } - public final String getFileName() - { + public final String getFileName() { return file.getName(); } - public final void delete() throws IOException, InterruptedException, ActiveMQException - { - if (isOpen()) - { + public final void delete() throws IOException, InterruptedException, ActiveMQException { + if (isOpen()) { close(); } - if (file.exists() && !file.delete()) - { + if (file.exists() && !file.delete()) { ActiveMQJournalLogger.LOGGER.errorDeletingFile(this); } } - public void copyTo(SequentialFile newFileName) throws Exception - { - try - { + public void copyTo(SequentialFile newFileName) throws Exception { + try { ActiveMQJournalLogger.LOGGER.debug("Copying " + this + " as " + newFileName); - if (!newFileName.isOpen()) - { + if (!newFileName.isOpen()) { newFileName.open(); } - if (!isOpen()) - { + if (!isOpen()) { this.open(); } - ByteBuffer buffer = ByteBuffer.allocate(10 * 1024); - for (;;) - { + for (;;) { buffer.rewind(); int size = this.read(buffer); newFileName.writeDirect(buffer, false); - if (size < 10 * 1024) - { + if (size < 10 * 1024) { break; } } newFileName.close(); this.close(); } - catch (IOException e) - { + catch (IOException e) { factory.onIOError(new ActiveMQIOErrorException(e.getMessage(), e), e.getMessage(), this); throw e; } @@ -145,35 +130,27 @@ public abstract class AbstractSequentialFile implements SequentialFile * @throws IOException only declare exception due to signature. Sub-class needs it. */ @Override - public void position(final long pos) throws IOException - { + public void position(final long pos) throws IOException { position.set(pos); } - public long position() - { + public long position() { return position.get(); } - public final void renameTo(final String newFileName) throws IOException, InterruptedException, - ActiveMQException - { - try - { + public final void renameTo(final String newFileName) throws IOException, InterruptedException, ActiveMQException { + try { close(); } - catch (IOException e) - { + catch (IOException e) { factory.onIOError(new ActiveMQIOErrorException(e.getMessage(), e), e.getMessage(), this); throw e; } File newFile = new File(directory + "/" + newFileName); - if (!file.equals(newFile)) - { - if (!file.renameTo(newFile)) - { + if (!file.equals(newFile)) { + if (!file.renameTo(newFile)) { throw ActiveMQJournalBundle.BUNDLE.ioRenameFileError(file.getName(), newFileName); } file = newFile; @@ -181,67 +158,53 @@ public abstract class AbstractSequentialFile implements SequentialFile } /** - * @throws IOException we declare throwing IOException because sub-classes need to do it + * @throws IOException we declare throwing IOException because sub-classes need to do it * @throws ActiveMQException */ - public synchronized void close() throws IOException, InterruptedException, ActiveMQException - { + public synchronized void close() throws IOException, InterruptedException, ActiveMQException { final CountDownLatch donelatch = new CountDownLatch(1); - if (writerExecutor != null) - { - writerExecutor.execute(new Runnable() - { - public void run() - { + if (writerExecutor != null) { + writerExecutor.execute(new Runnable() { + public void run() { donelatch.countDown(); } }); - while (!donelatch.await(60, TimeUnit.SECONDS)) - { + while (!donelatch.await(60, TimeUnit.SECONDS)) { ActiveMQJournalLogger.LOGGER.couldNotCompleteTask(new Exception("trace"), file.getName()); } } } - public final boolean fits(final int size) - { - if (timedBuffer == null) - { + public final boolean fits(final int size) { + if (timedBuffer == null) { return position.get() + size <= fileSize; } - else - { + else { return timedBuffer.checkSize(size); } } - public void setTimedBuffer(final TimedBuffer buffer) - { - if (timedBuffer != null) - { + public void setTimedBuffer(final TimedBuffer buffer) { + if (timedBuffer != null) { timedBuffer.setObserver(null); } timedBuffer = buffer; - if (buffer != null) - { + if (buffer != null) { buffer.setObserver(timedBufferObserver); } } - public void write(final ActiveMQBuffer bytes, final boolean sync, final IOCallback callback) throws IOException - { - if (timedBuffer != null) - { + public void write(final ActiveMQBuffer bytes, final boolean sync, final IOCallback callback) throws IOException { + if (timedBuffer != null) { bytes.setIndex(0, bytes.capacity()); timedBuffer.addBytes(bytes, sync, callback); } - else - { + else { ByteBuffer buffer = factory.newBuffer(bytes.capacity()); buffer.put(bytes.toByteBuffer().array()); buffer.rewind(); @@ -249,31 +212,25 @@ public abstract class AbstractSequentialFile implements SequentialFile } } - public void write(final ActiveMQBuffer bytes, final boolean sync) throws IOException, InterruptedException, - ActiveMQException - { - if (sync) - { + public void write(final ActiveMQBuffer bytes, + final boolean sync) throws IOException, InterruptedException, ActiveMQException { + if (sync) { SimpleWaitIOCallback completion = new SimpleWaitIOCallback(); write(bytes, true, completion); completion.waitCompletion(); } - else - { + else { write(bytes, false, DummyCallback.getInstance()); } } - public void write(final EncodingSupport bytes, final boolean sync, final IOCallback callback) - { - if (timedBuffer != null) - { + public void write(final EncodingSupport bytes, final boolean sync, final IOCallback callback) { + if (timedBuffer != null) { timedBuffer.addBytes(bytes, sync, callback); } - else - { + else { ByteBuffer buffer = factory.newBuffer(bytes.getEncodeSize()); // If not using the TimedBuffer, a final copy is necessary @@ -287,69 +244,55 @@ public abstract class AbstractSequentialFile implements SequentialFile } } - public void write(final EncodingSupport bytes, final boolean sync) throws InterruptedException, ActiveMQException - { - if (sync) - { + public void write(final EncodingSupport bytes, final boolean sync) throws InterruptedException, ActiveMQException { + if (sync) { SimpleWaitIOCallback completion = new SimpleWaitIOCallback(); write(bytes, true, completion); completion.waitCompletion(); } - else - { + else { write(bytes, false, DummyCallback.getInstance()); } } - protected File getFile() - { + protected File getFile() { return file; } - private static final class DelegateCallback implements IOCallback - { + private static final class DelegateCallback implements IOCallback { + final List delegates; - private DelegateCallback(final List delegates) - { + private DelegateCallback(final List delegates) { this.delegates = delegates; } - public void done() - { - for (IOCallback callback : delegates) - { - try - { + public void done() { + for (IOCallback callback : delegates) { + try { callback.done(); } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQJournalLogger.LOGGER.errorCompletingCallback(e); } } } - public void onError(final int errorCode, final String errorMessage) - { - for (IOCallback callback : delegates) - { - try - { + public void onError(final int errorCode, final String errorMessage) { + for (IOCallback callback : delegates) { + try { callback.onError(errorCode, errorMessage); } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQJournalLogger.LOGGER.errorCallingErrorCallback(e); } } } } - protected ByteBuffer newBuffer(int size, int limit) - { + protected ByteBuffer newBuffer(int size, int limit) { size = factory.calculateBlockSize(size); limit = factory.calculateBlockSize(limit); @@ -358,50 +301,41 @@ public abstract class AbstractSequentialFile implements SequentialFile return buffer; } - protected class LocalBufferObserver implements TimedBufferObserver - { - public void flushBuffer(final ByteBuffer buffer, final boolean requestedSync, final List callbacks) - { + protected class LocalBufferObserver implements TimedBufferObserver { + + public void flushBuffer(final ByteBuffer buffer, final boolean requestedSync, final List callbacks) { buffer.flip(); - if (buffer.limit() == 0) - { + if (buffer.limit() == 0) { factory.releaseBuffer(buffer); } - else - { + else { writeDirect(buffer, requestedSync, new DelegateCallback(callbacks)); } } - public ByteBuffer newBuffer(final int size, final int limit) - { + public ByteBuffer newBuffer(final int size, final int limit) { return AbstractSequentialFile.this.newBuffer(size, limit); } - public int getRemainingBytes() - { - if (fileSize - position.get() > Integer.MAX_VALUE) - { + public int getRemainingBytes() { + if (fileSize - position.get() > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } - else - { - return (int)(fileSize - position.get()); + else { + return (int) (fileSize - position.get()); } } @Override - public String toString() - { + public String toString() { return "TimedBufferObserver on file (" + getFile().getName() + ")"; } } @Override - public File getJavaFile() - { + public File getJavaFile() { return getFile().getAbsoluteFile(); } } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/AbstractSequentialFileFactory.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/AbstractSequentialFileFactory.java index 61cd0fdb1e..e27f0c5ffe 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/AbstractSequentialFileFactory.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/AbstractSequentialFileFactory.java @@ -37,8 +37,7 @@ import org.apache.activemq.artemis.utils.ActiveMQThreadFactory; /** * An abstract SequentialFileFactory containing basic functionality for both AIO and NIO SequentialFactories */ -public abstract class AbstractSequentialFileFactory implements SequentialFileFactory -{ +public abstract class AbstractSequentialFileFactory implements SequentialFileFactory { // Timeout used to wait executors to shutdown protected static final int EXECUTOR_TIMEOUT = 60; @@ -59,25 +58,22 @@ public abstract class AbstractSequentialFileFactory implements SequentialFileFac * Asynchronous writes need to be done at another executor. * This needs to be done at NIO, or else we would have the callers thread blocking for the return. * At AIO this is necessary as context switches on writes would fire flushes at the kernel. - * */ + */ protected ExecutorService writeExecutor; protected AbstractSequentialFileFactory(final File journalDir, - final boolean buffered, - final int bufferSize, - final int bufferTimeout, - final int maxIO, - final boolean logRates, - final IOCriticalErrorListener criticalErrorListener) - { + final boolean buffered, + final int bufferSize, + final int bufferTimeout, + final int maxIO, + final boolean logRates, + final IOCriticalErrorListener criticalErrorListener) { this.journalDir = journalDir; - if (buffered && bufferTimeout > 0) - { + if (buffered && bufferTimeout > 0) { timedBuffer = new TimedBuffer(bufferSize, bufferTimeout, logRates); } - else - { + else { timedBuffer = null; } this.bufferSize = bufferSize; @@ -86,135 +82,104 @@ public abstract class AbstractSequentialFileFactory implements SequentialFileFac this.maxIO = maxIO; } - public void stop() - { - if (timedBuffer != null) - { + public void stop() { + if (timedBuffer != null) { timedBuffer.stop(); } - if (isSupportsCallbacks() && writeExecutor != null) - { + if (isSupportsCallbacks() && writeExecutor != null) { writeExecutor.shutdown(); - try - { - if (!writeExecutor.awaitTermination(AbstractSequentialFileFactory.EXECUTOR_TIMEOUT, TimeUnit.SECONDS)) - { + try { + if (!writeExecutor.awaitTermination(AbstractSequentialFileFactory.EXECUTOR_TIMEOUT, TimeUnit.SECONDS)) { ActiveMQJournalLogger.LOGGER.timeoutOnWriterShutdown(new Exception("trace")); } } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } } } @Override - public File getDirectory() - { + public File getDirectory() { return journalDir; } - public void start() - { - if (timedBuffer != null) - { + public void start() { + if (timedBuffer != null) { timedBuffer.start(); } - if (isSupportsCallbacks()) - { - writeExecutor = Executors.newSingleThreadExecutor(new ActiveMQThreadFactory("ActiveMQ-Asynchronous-Persistent-Writes" + System.identityHashCode(this), - true, - AbstractSequentialFileFactory.getThisClassLoader())); + if (isSupportsCallbacks()) { + writeExecutor = Executors.newSingleThreadExecutor(new ActiveMQThreadFactory("ActiveMQ-Asynchronous-Persistent-Writes" + System.identityHashCode(this), true, AbstractSequentialFileFactory.getThisClassLoader())); } } - public int getMaxIO() - { + public int getMaxIO() { return maxIO; } @Override - public void onIOError(Exception exception, String message, SequentialFile file) - { - if (critialErrorListener != null) - { + public void onIOError(Exception exception, String message, SequentialFile file) { + if (critialErrorListener != null) { critialErrorListener.onIOException(exception, message, file); } } @Override - public void activateBuffer(final SequentialFile file) - { - if (timedBuffer != null) - { + public void activateBuffer(final SequentialFile file) { + if (timedBuffer != null) { file.setTimedBuffer(timedBuffer); } } - public void flush() - { - if (timedBuffer != null) - { + public void flush() { + if (timedBuffer != null) { timedBuffer.flush(); } } - public void deactivateBuffer() - { - if (timedBuffer != null) - { + public void deactivateBuffer() { + if (timedBuffer != null) { // When moving to a new file, we need to make sure any pending buffer will be transferred to the buffer timedBuffer.flush(); timedBuffer.setObserver(null); } } - public void releaseBuffer(final ByteBuffer buffer) - { + public void releaseBuffer(final ByteBuffer buffer) { } /** * Create the directory if it doesn't exist yet */ - public void createDirs() throws Exception - { + public void createDirs() throws Exception { boolean ok = journalDir.mkdirs(); - if (!ok) - { + if (!ok) { throw new IOException("Failed to create directory " + journalDir); } } - public List listFiles(final String extension) throws Exception - { - FilenameFilter fnf = new FilenameFilter() - { - public boolean accept(final File file, final String name) - { + public List listFiles(final String extension) throws Exception { + FilenameFilter fnf = new FilenameFilter() { + public boolean accept(final File file, final String name) { return name.endsWith("." + extension); } }; String[] fileNames = journalDir.list(fnf); - if (fileNames == null) - { + if (fileNames == null) { return Collections.EMPTY_LIST; } return Arrays.asList(fileNames); } - private static ClassLoader getThisClassLoader() - { - return AccessController.doPrivileged(new PrivilegedAction() - { - public ClassLoader run() - { + private static ClassLoader getThisClassLoader() { + return AccessController.doPrivileged(new PrivilegedAction() { + public ClassLoader run() { return AbstractSequentialFileFactory.class.getClassLoader(); } }); diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/DummyCallback.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/DummyCallback.java index ce21f2aad6..cf59fc4ea4 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/DummyCallback.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/DummyCallback.java @@ -19,31 +19,26 @@ package org.apache.activemq.artemis.core.io; import org.apache.activemq.artemis.core.journal.impl.SyncIOCompletion; import org.apache.activemq.artemis.journal.ActiveMQJournalLogger; -public class DummyCallback extends SyncIOCompletion -{ +public class DummyCallback extends SyncIOCompletion { + private static final DummyCallback instance = new DummyCallback(); - public static DummyCallback getInstance() - { + public static DummyCallback getInstance() { return DummyCallback.instance; } - public void done() - { + public void done() { } - public void onError(final int errorCode, final String errorMessage) - { + public void onError(final int errorCode, final String errorMessage) { ActiveMQJournalLogger.LOGGER.errorWritingData(new Exception(errorMessage), errorMessage, errorCode); } @Override - public void waitCompletion() throws Exception - { + public void waitCompletion() throws Exception { } @Override - public void storeLineUp() - { + public void storeLineUp() { } } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/IOCallback.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/IOCallback.java index 41470e484f..844749169b 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/IOCallback.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/IOCallback.java @@ -19,15 +19,17 @@ package org.apache.activemq.artemis.core.io; /** * The interface used for AIO Callbacks. */ -public interface IOCallback -{ +public interface IOCallback { + /** * Method for sync notifications. When this callback method is called, there is a guarantee the data is written on the disk. - *
    Note:Leave this method as soon as possible, or you would be blocking the whole notification thread */ + *
    Note:Leave this method as soon as possible, or you would be blocking the whole notification thread + */ void done(); /** * Method for error notifications. - * Observation: The whole file will be probably failing if this happens. Like, if you delete the file, you will start to get errors for these operations*/ + * Observation: The whole file will be probably failing if this happens. Like, if you delete the file, you will start to get errors for these operations + */ void onError(int errorCode, String errorMessage); } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/IOCriticalErrorListener.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/IOCriticalErrorListener.java index f2da3e8daa..1a3846287f 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/IOCriticalErrorListener.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/IOCriticalErrorListener.java @@ -19,7 +19,7 @@ package org.apache.activemq.artemis.core.io; /** * TODO Merge this with IOExceptionListener */ -public interface IOCriticalErrorListener -{ +public interface IOCriticalErrorListener { + void onIOException(Exception code, String message, SequentialFile file); } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/IOExceptionListener.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/IOExceptionListener.java index 5c855e52b0..76e2c02e94 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/IOExceptionListener.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/IOExceptionListener.java @@ -16,7 +16,7 @@ */ package org.apache.activemq.artemis.core.io; -public interface IOExceptionListener -{ +public interface IOExceptionListener { + void onIOException(Exception exception, String message); } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/SequentialFile.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/SequentialFile.java index cb9d070f3f..ab61b8d4bd 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/SequentialFile.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/SequentialFile.java @@ -25,8 +25,7 @@ import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.core.journal.EncodingSupport; import org.apache.activemq.artemis.core.io.buffer.TimedBuffer; -public interface SequentialFile -{ +public interface SequentialFile { boolean isOpen(); @@ -36,6 +35,7 @@ public interface SequentialFile /** * The maximum number of simultaneous writes accepted + * * @param maxIO * @throws Exception */ @@ -63,31 +63,33 @@ public interface SequentialFile /** * Write directly to the file without using any buffer + * * @param bytes the ByteBuffer must be compatible with the SequentialFile implementation (AIO or - * NIO). To be safe, use a buffer from the corresponding - * {@link SequentialFileFactory#newBuffer(int)}. + * NIO). To be safe, use a buffer from the corresponding + * {@link SequentialFileFactory#newBuffer(int)}. */ void writeDirect(ByteBuffer bytes, boolean sync, IOCallback callback); /** * Write directly to the file without using intermediate any buffer + * * @param bytes the ByteBuffer must be compatible with the SequentialFile implementation (AIO or - * NIO). To be safe, use a buffer from the corresponding - * {@link SequentialFileFactory#newBuffer(int)}. + * NIO). To be safe, use a buffer from the corresponding + * {@link SequentialFileFactory#newBuffer(int)}. */ void writeDirect(ByteBuffer bytes, boolean sync) throws Exception; /** * @param bytes the ByteBuffer must be compatible with the SequentialFile implementation (AIO or - * NIO). To be safe, use a buffer from the corresponding - * {@link SequentialFileFactory#newBuffer(int)}. + * NIO). To be safe, use a buffer from the corresponding + * {@link SequentialFileFactory#newBuffer(int)}. */ int read(ByteBuffer bytes, IOCallback callback) throws Exception; /** * @param bytes the ByteBuffer must be compatible with the SequentialFile implementation (AIO or - * NIO). To be safe, use a buffer from the corresponding - * {@link SequentialFileFactory#newBuffer(int)}. + * NIO). To be safe, use a buffer from the corresponding + * {@link SequentialFileFactory#newBuffer(int)}. */ int read(ByteBuffer bytes) throws Exception; diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/SequentialFileFactory.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/SequentialFileFactory.java index b9a72caf2e..81203cf50f 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/SequentialFileFactory.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/SequentialFileFactory.java @@ -21,11 +21,10 @@ import java.nio.ByteBuffer; import java.util.List; /** - * * A SequentialFileFactory */ -public interface SequentialFileFactory -{ +public interface SequentialFileFactory { + SequentialFile createSequentialFile(String fileName); int getMaxIO(); @@ -34,6 +33,7 @@ public interface SequentialFileFactory * Lists files that end with the given extension. *

    * This method inserts a ".' before the extension. + * * @param extension * @return * @throws Exception @@ -42,20 +42,27 @@ public interface SequentialFileFactory boolean isSupportsCallbacks(); - /** The SequentialFile will call this method when a disk IO Error happens during the live phase. */ + /** + * The SequentialFile will call this method when a disk IO Error happens during the live phase. + */ void onIOError(Exception exception, String message, SequentialFile file); - /** used for cases where you need direct buffer outside of the journal context. - * This is because the native layer has a method that can be reused in certain cases like paging */ + /** + * used for cases where you need direct buffer outside of the journal context. + * This is because the native layer has a method that can be reused in certain cases like paging + */ ByteBuffer allocateDirectBuffer(int size); - /** used for cases where you need direct buffer outside of the journal context. - * This is because the native layer has a method that can be reused in certain cases like paging */ + /** + * used for cases where you need direct buffer outside of the journal context. + * This is because the native layer has a method that can be reused in certain cases like paging + */ void releaseDirectBuffer(ByteBuffer buffer); /** * Note: You need to release the buffer if is used for reading operations. You don't need to do * it if using writing operations (AIO Buffer Lister will take of writing operations) + * * @param size * @return the allocated ByteBuffer */ diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/aio/AIOSequentialFile.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/aio/AIOSequentialFile.java index 7503681b4a..e011b088d7 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/aio/AIOSequentialFile.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/aio/AIOSequentialFile.java @@ -34,8 +34,8 @@ import org.apache.activemq.artemis.core.journal.impl.SimpleWaitIOCallback; import org.apache.activemq.artemis.jlibaio.LibaioFile; import org.apache.activemq.artemis.utils.ReusableLatch; -public class AIOSequentialFile extends AbstractSequentialFile -{ +public class AIOSequentialFile extends AbstractSequentialFile { + private boolean opened = false; private LibaioFile aioFile; @@ -62,32 +62,27 @@ public class AIOSequentialFile extends AbstractSequentialFile */ private long nextReadSequence = 0; - public AIOSequentialFile(final AIOSequentialFileFactory factory, final int bufferSize, final long bufferTimeoutMilliseconds, final File directory, final String fileName, - final Executor writerExecutor) - { + final Executor writerExecutor) { super(directory, fileName, factory, writerExecutor); this.aioFactory = factory; } - public boolean isOpen() - { + public boolean isOpen() { return opened; } - public int getAlignment() - { + public int getAlignment() { checkOpened(); return aioFile.getBlockSize(); } - public int calculateBlockStart(final int position) - { + public int calculateBlockStart(final int position) { int alignment = getAlignment(); int pos = (position / alignment + (position % alignment != 0 ? 1 : 0)) * alignment; @@ -95,28 +90,19 @@ public class AIOSequentialFile extends AbstractSequentialFile return pos; } - public SequentialFile cloneFile() - { - return new AIOSequentialFile(aioFactory, - -1, - -1, - getFile().getParentFile(), - getFile().getName(), - writerExecutor); + public SequentialFile cloneFile() { + return new AIOSequentialFile(aioFactory, -1, -1, getFile().getParentFile(), getFile().getName(), writerExecutor); } @Override - public synchronized void close() throws IOException, InterruptedException, ActiveMQException - { - if (!opened) - { + public synchronized void close() throws IOException, InterruptedException, ActiveMQException { + if (!opened) { return; } super.close(); - if (!pendingCallbacks.await(10, TimeUnit.SECONDS)) - { + if (!pendingCallbacks.await(10, TimeUnit.SECONDS)) { factory.onIOError(new IOException("Timeout on close"), "Timeout on close", this); } @@ -128,30 +114,24 @@ public class AIOSequentialFile extends AbstractSequentialFile aioFile = null; } - - public synchronized void fill(final int size) throws Exception - { + public synchronized void fill(final int size) throws Exception { checkOpened(); aioFile.fill(size); fileSize = aioFile.getSize(); } - public void open() throws Exception - { + public void open() throws Exception { open(aioFactory.getMaxIO(), true); } - public synchronized void open(final int maxIO, final boolean useExecutor) throws ActiveMQException - { + public synchronized void open(final int maxIO, final boolean useExecutor) throws ActiveMQException { opened = true; - try - { + try { aioFile = aioFactory.libaioContext.openFile(getFile(), true); } - catch (IOException e) - { + catch (IOException e) { factory.onIOError(e, e.getMessage(), this); throw new ActiveMQNativeIOError(e.getMessage(), e); } @@ -161,8 +141,7 @@ public class AIOSequentialFile extends AbstractSequentialFile fileSize = aioFile.getSize(); } - public int read(final ByteBuffer bytes, final IOCallback callback) throws ActiveMQException - { + public int read(final ByteBuffer bytes, final IOCallback callback) throws ActiveMQException { checkOpened(); int bytesToRead = bytes.limit(); @@ -170,15 +149,13 @@ public class AIOSequentialFile extends AbstractSequentialFile bytes.rewind(); - try - { + try { // We don't send the buffer to the callback on read, // because we want the buffer available. // Sending it through the callback would make it released aioFile.read(positionToRead, bytesToRead, bytes, getCallback(callback, null)); } - catch (IOException e) - { + catch (IOException e) { factory.onIOError(e, e.getMessage(), this); throw new ActiveMQNativeIOError(e.getMessage(), e); } @@ -186,8 +163,7 @@ public class AIOSequentialFile extends AbstractSequentialFile return bytesToRead; } - public int read(final ByteBuffer bytes) throws Exception - { + public int read(final ByteBuffer bytes) throws Exception { SimpleWaitIOCallback waitCompletion = new SimpleWaitIOCallback(); int bytesRead = read(bytes, waitCompletion); @@ -197,28 +173,23 @@ public class AIOSequentialFile extends AbstractSequentialFile return bytesRead; } - public void writeDirect(final ByteBuffer bytes, final boolean sync) throws Exception - { - if (sync) - { + public void writeDirect(final ByteBuffer bytes, final boolean sync) throws Exception { + if (sync) { SimpleWaitIOCallback completion = new SimpleWaitIOCallback(); writeDirect(bytes, true, completion); completion.waitCompletion(); } - else - { + else { writeDirect(bytes, false, DummyCallback.getInstance()); } } /** - * * Note: Parameter sync is not used on AIO - * */ - public void writeDirect(final ByteBuffer bytes, final boolean sync, final IOCallback callback) - { + */ + public void writeDirect(final ByteBuffer bytes, final boolean sync, final IOCallback callback) { checkOpened(); final int bytesToWrite = factory.calculateBlockSize(bytes.limit()); @@ -227,54 +198,41 @@ public class AIOSequentialFile extends AbstractSequentialFile AIOSequentialFileFactory.AIOSequentialCallback runnableCallback = getCallback(callback, bytes); runnableCallback.initWrite(positionToWrite, bytesToWrite); - if (writerExecutor != null) - { + if (writerExecutor != null) { writerExecutor.execute(runnableCallback); } - else - { + else { runnableCallback.run(); } } - - - AIOSequentialFileFactory.AIOSequentialCallback getCallback(IOCallback originalCallback, ByteBuffer buffer) - { + AIOSequentialFileFactory.AIOSequentialCallback getCallback(IOCallback originalCallback, ByteBuffer buffer) { AIOSequentialFileFactory.AIOSequentialCallback callback = aioFactory.getCallback(); callback.init(this.nextWritingSequence.getAndIncrement(), originalCallback, aioFile, this, buffer); pendingCallbacks.countUp(); return callback; } - - void done(AIOSequentialFileFactory.AIOSequentialCallback callback) - { - if (callback.writeSequence == -1) - { + void done(AIOSequentialFileFactory.AIOSequentialCallback callback) { + if (callback.writeSequence == -1) { callback.sequentialDone(); pendingCallbacks.countDown(); } - - if (callback.writeSequence == nextReadSequence) - { + if (callback.writeSequence == nextReadSequence) { nextReadSequence++; callback.sequentialDone(); pendingCallbacks.countDown(); flushCallbacks(); } - else - { + else { pendingCallbackList.add(callback); } } - private void flushCallbacks() - { - while (!pendingCallbackList.isEmpty() && pendingCallbackList.peek().writeSequence == nextReadSequence) - { + private void flushCallbacks() { + while (!pendingCallbackList.isEmpty() && pendingCallbackList.peek().writeSequence == nextReadSequence) { AIOSequentialFileFactory.AIOSequentialCallback callback = pendingCallbackList.poll(); callback.sequentialDone(); nextReadSequence++; @@ -282,26 +240,21 @@ public class AIOSequentialFile extends AbstractSequentialFile } } - public void sync() - { + public void sync() { throw new UnsupportedOperationException("This method is not supported on AIO"); } - public long size() throws Exception - { - if (aioFile == null) - { + public long size() throws Exception { + if (aioFile == null) { return getFile().length(); } - else - { + else { return aioFile.getSize(); } } @Override - public String toString() - { + public String toString() { return "AIOSequentialFile:" + getFile().getAbsolutePath(); } @@ -309,8 +262,7 @@ public class AIOSequentialFile extends AbstractSequentialFile // ----------------------------------------------------------------------------------------------------- @Override - protected ByteBuffer newBuffer(int size, int limit) - { + protected ByteBuffer newBuffer(int size, int limit) { size = factory.calculateBlockSize(size); limit = factory.calculateBlockSize(limit); @@ -322,10 +274,8 @@ public class AIOSequentialFile extends AbstractSequentialFile // Private methods // ----------------------------------------------------------------------------------------------------- - private void checkOpened() - { - if (aioFile == null || !opened) - { + private void checkOpened() { + if (aioFile == null || !opened) { throw new NullPointerException("File not opened, file=null"); } } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/aio/AIOSequentialFileFactory.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/aio/AIOSequentialFileFactory.java index 39dad2ff90..0b80ec69cc 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/aio/AIOSequentialFileFactory.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/aio/AIOSequentialFileFactory.java @@ -40,8 +40,8 @@ import org.apache.activemq.artemis.jlibaio.util.CallbackCache; import org.apache.activemq.artemis.journal.ActiveMQJournalLogger; import org.apache.activemq.artemis.utils.ActiveMQThreadFactory; -public final class AIOSequentialFileFactory extends AbstractSequentialFileFactory -{ +public final class AIOSequentialFileFactory extends AbstractSequentialFileFactory { + private static final boolean trace = ActiveMQJournalLogger.LOGGER.isTraceEnabled(); private final ReuseBuffersController buffersControl = new ReuseBuffersController(); @@ -59,37 +59,23 @@ public final class AIOSequentialFileFactory extends AbstractSequentialFileFactor // This method exists just to make debug easier. // I could replace log.trace by log.info temporarily while I was debugging // Journal - private static void trace(final String message) - { + private static void trace(final String message) { ActiveMQJournalLogger.LOGGER.trace(message); } - public AIOSequentialFileFactory(final File journalDir, int maxIO) - { - this(journalDir, - JournalConstants.DEFAULT_JOURNAL_BUFFER_SIZE_AIO, - JournalConstants.DEFAULT_JOURNAL_BUFFER_TIMEOUT_AIO, - maxIO, - false, - null); + public AIOSequentialFileFactory(final File journalDir, int maxIO) { + this(journalDir, JournalConstants.DEFAULT_JOURNAL_BUFFER_SIZE_AIO, JournalConstants.DEFAULT_JOURNAL_BUFFER_TIMEOUT_AIO, maxIO, false, null); } - public AIOSequentialFileFactory(final File journalDir, final IOCriticalErrorListener listener, int maxIO) - { - this(journalDir, - JournalConstants.DEFAULT_JOURNAL_BUFFER_SIZE_AIO, - JournalConstants.DEFAULT_JOURNAL_BUFFER_TIMEOUT_AIO, - maxIO, - false, - listener); + public AIOSequentialFileFactory(final File journalDir, final IOCriticalErrorListener listener, int maxIO) { + this(journalDir, JournalConstants.DEFAULT_JOURNAL_BUFFER_SIZE_AIO, JournalConstants.DEFAULT_JOURNAL_BUFFER_TIMEOUT_AIO, maxIO, false, listener); } public AIOSequentialFileFactory(final File journalDir, final int bufferSize, final int bufferTimeout, final int maxIO, - final boolean logRates) - { + final boolean logRates) { this(journalDir, bufferSize, bufferTimeout, maxIO, logRates, null); } @@ -98,60 +84,44 @@ public final class AIOSequentialFileFactory extends AbstractSequentialFileFactor final int bufferTimeout, final int maxIO, final boolean logRates, - final IOCriticalErrorListener listener) - { + final IOCriticalErrorListener listener) { super(journalDir, true, bufferSize, bufferTimeout, maxIO, logRates, listener); callbackPool = new CallbackCache<>(maxIO); } - public AIOSequentialCallback getCallback() - { + public AIOSequentialCallback getCallback() { AIOSequentialCallback callback = callbackPool.get(); - if (callback == null) - { + if (callback == null) { callback = new AIOSequentialCallback(); } return callback; } - public void enableBufferReuse() - { + public void enableBufferReuse() { this.reuseBuffers = true; } - public void disableBufferReuse() - { + public void disableBufferReuse() { this.reuseBuffers = false; } - - public SequentialFile createSequentialFile(final String fileName) - { - return new AIOSequentialFile(this, - bufferSize, - bufferTimeout, - journalDir, - fileName, - writeExecutor); + public SequentialFile createSequentialFile(final String fileName) { + return new AIOSequentialFile(this, bufferSize, bufferTimeout, journalDir, fileName, writeExecutor); } - public boolean isSupportsCallbacks() - { + public boolean isSupportsCallbacks() { return true; } - public static boolean isSupported() - { + public static boolean isSupported() { return LibaioContext.isLoaded(); } - public ByteBuffer allocateDirectBuffer(final int size) - { + public ByteBuffer allocateDirectBuffer(final int size) { int blocks = size / 512; - if (size % 512 != 0) - { + if (size % 512 != 0) { blocks++; } @@ -163,42 +133,35 @@ public final class AIOSequentialFileFactory extends AbstractSequentialFileFactor return buffer; } - public void releaseDirectBuffer(final ByteBuffer buffer) - { + public void releaseDirectBuffer(final ByteBuffer buffer) { LibaioContext.freeBuffer(buffer); } - public ByteBuffer newBuffer(int size) - { - if (size % 512 != 0) - { + public ByteBuffer newBuffer(int size) { + if (size % 512 != 0) { size = (size / 512 + 1) * 512; } return buffersControl.newBuffer(size); } - public void clearBuffer(final ByteBuffer directByteBuffer) - { + public void clearBuffer(final ByteBuffer directByteBuffer) { directByteBuffer.position(0); libaioContext.memsetBuffer(directByteBuffer); } - public int getAlignment() - { + public int getAlignment() { return 512; } // For tests only - public ByteBuffer wrapBuffer(final byte[] bytes) - { + public ByteBuffer wrapBuffer(final byte[] bytes) { ByteBuffer newbuffer = newBuffer(bytes.length); newbuffer.put(bytes); return newbuffer; } - public int calculateBlockSize(final int position) - { + public int calculateBlockSize(final int position) { int alignment = getAlignment(); int pos = (position / alignment + (position % alignment != 0 ? 1 : 0)) * alignment; @@ -210,25 +173,20 @@ public final class AIOSequentialFileFactory extends AbstractSequentialFileFactor * @see org.apache.activemq.artemis.core.io.SequentialFileFactory#releaseBuffer(java.nio.ByteBuffer) */ @Override - public synchronized void releaseBuffer(final ByteBuffer buffer) - { + public synchronized void releaseBuffer(final ByteBuffer buffer) { LibaioContext.freeBuffer(buffer); } @Override - public void start() - { - if (running.compareAndSet(false, true)) - { + public void start() { + if (running.compareAndSet(false, true)) { super.start(); this.libaioContext = new LibaioContext(maxIO, true); this.running.set(true); - pollerExecutor = Executors.newCachedThreadPool(new ActiveMQThreadFactory("ActiveMQ-AIO-poller-pool" + System.identityHashCode(this), - true, - AIOSequentialFileFactory.getThisClassLoader())); + pollerExecutor = Executors.newCachedThreadPool(new ActiveMQThreadFactory("ActiveMQ-AIO-poller-pool" + System.identityHashCode(this), true, AIOSequentialFileFactory.getThisClassLoader())); pollerExecutor.execute(new PollerRunnable()); } @@ -236,28 +194,22 @@ public final class AIOSequentialFileFactory extends AbstractSequentialFileFactor } @Override - public void stop() - { - if (this.running.compareAndSet(true, false)) - { + public void stop() { + if (this.running.compareAndSet(true, false)) { buffersControl.stop(); libaioContext.close(); libaioContext = null; - if (pollerExecutor != null) - { + if (pollerExecutor != null) { pollerExecutor.shutdown(); - try - { - if (!pollerExecutor.awaitTermination(AbstractSequentialFileFactory.EXECUTOR_TIMEOUT, TimeUnit.SECONDS)) - { + try { + if (!pollerExecutor.awaitTermination(AbstractSequentialFileFactory.EXECUTOR_TIMEOUT, TimeUnit.SECONDS)) { ActiveMQJournalLogger.LOGGER.timeoutOnPollerShutdown(new Exception("trace")); } } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } } @@ -267,8 +219,7 @@ public final class AIOSequentialFileFactory extends AbstractSequentialFileFactor } @Override - protected void finalize() - { + protected void finalize() { stop(); } @@ -276,8 +227,8 @@ public final class AIOSequentialFileFactory extends AbstractSequentialFileFactor * The same callback is used for Runnable executor. * This way we can save some memory over the pool. */ - public class AIOSequentialCallback implements SubmitInfo, Runnable, Comparable - { + public class AIOSequentialCallback implements SubmitInfo, Runnable, Comparable { + IOCallback callback; boolean error = false; AIOSequentialFile sequentialFile; @@ -291,8 +242,7 @@ public final class AIOSequentialFileFactory extends AbstractSequentialFileFactor int bytes; @Override - public String toString() - { + public String toString() { return "AIOSequentialCallback{" + "error=" + error + ", errorMessage='" + errorMessage + '\'' + @@ -302,43 +252,38 @@ public final class AIOSequentialFileFactory extends AbstractSequentialFileFactor '}'; } - public AIOSequentialCallback initWrite(long positionToWrite, int bytesToWrite) - { + public AIOSequentialCallback initWrite(long positionToWrite, int bytesToWrite) { this.position = positionToWrite; this.bytes = bytesToWrite; return this; } - public void run() - { - try - { + public void run() { + try { libaioFile.write(position, bytes, buffer, this); } - catch (IOException e) - { + catch (IOException e) { callback.onError(-1, e.getMessage()); } } - public int compareTo(AIOSequentialCallback other) - { - if (this == other || this.writeSequence == other.writeSequence) - { + public int compareTo(AIOSequentialCallback other) { + if (this == other || this.writeSequence == other.writeSequence) { return 0; } - else if (other.writeSequence < this.writeSequence) - { + else if (other.writeSequence < this.writeSequence) { return 1; } - else - { + else { return -1; } } - public AIOSequentialCallback init(long writeSequence, IOCallback IOCallback, LibaioFile libaioFile, AIOSequentialFile sequentialFile, ByteBuffer usedBuffer) - { + public AIOSequentialCallback init(long writeSequence, + IOCallback IOCallback, + LibaioFile libaioFile, + AIOSequentialFile sequentialFile, + ByteBuffer usedBuffer) { this.callback = IOCallback; this.sequentialFile = sequentialFile; this.error = false; @@ -350,8 +295,7 @@ public final class AIOSequentialFileFactory extends AbstractSequentialFileFactor } @Override - public void onError(int errno, String message) - { + public void onError(int errno, String message) { this.error = true; this.errorCode = errno; this.errorMessage = message; @@ -360,31 +304,25 @@ public final class AIOSequentialFileFactory extends AbstractSequentialFileFactor /** * this is called by libaio. */ - public void done() - { + public void done() { this.sequentialFile.done(this); } /** * This is callbed by the AIOSequentialFile, after determined the callbacks were returned in sequence */ - public void sequentialDone() - { + public void sequentialDone() { - if (error) - { + if (error) { callback.onError(errorCode, errorMessage); errorMessage = null; } - else - { - if (callback != null) - { + else { + if (callback != null) { callback.done(); } - if (buffer != null && reuseBuffers) - { + if (buffer != null && reuseBuffers) { buffersControl.bufferDone(buffer); } @@ -393,10 +331,9 @@ public final class AIOSequentialFileFactory extends AbstractSequentialFileFactor } } - private class PollerRunnable implements Runnable - { - public void run() - { + private class PollerRunnable implements Runnable { + + public void run() { libaioContext.poll(); } } @@ -404,23 +341,20 @@ public final class AIOSequentialFileFactory extends AbstractSequentialFileFactor /** * Class that will control buffer-reuse */ - private class ReuseBuffersController - { + private class ReuseBuffersController { + private volatile long bufferReuseLastTime = System.currentTimeMillis(); private final ConcurrentLinkedQueue reuseBuffersQueue = new ConcurrentLinkedQueue(); private boolean stopped = false; - public ByteBuffer newBuffer(final int size) - { + public ByteBuffer newBuffer(final int size) { // if a new buffer wasn't requested in 10 seconds, we clear the queue // This is being done this way as we don't need another Timeout Thread // just to cleanup this - if (bufferSize > 0 && System.currentTimeMillis() - bufferReuseLastTime > 10000) - { - if (AIOSequentialFileFactory.trace) - { + if (bufferSize > 0 && System.currentTimeMillis() - bufferReuseLastTime > 10000) { + if (AIOSequentialFileFactory.trace) { AIOSequentialFileFactory.trace("Clearing reuse buffers queue with " + reuseBuffersQueue.size() + " elements"); } @@ -432,12 +366,10 @@ public final class AIOSequentialFileFactory extends AbstractSequentialFileFactor // if a buffer is bigger than the configured-bufferSize, we just create a new // buffer. - if (size > bufferSize) - { + if (size > bufferSize) { return LibaioContext.newAlignedBuffer(size, 512); } - else - { + else { // We need to allocate buffers following the rules of the storage // being used (AIO/NIO) int alignedSize = calculateBlockSize(size); @@ -445,15 +377,13 @@ public final class AIOSequentialFileFactory extends AbstractSequentialFileFactor // Try getting a buffer from the queue... ByteBuffer buffer = reuseBuffersQueue.poll(); - if (buffer == null) - { + if (buffer == null) { // if empty create a new one. buffer = LibaioContext.newAlignedBuffer(size, 512); buffer.limit(alignedSize); } - else - { + else { clearBuffer(buffer); // set the limit of the buffer to the bufferSize being required @@ -466,43 +396,34 @@ public final class AIOSequentialFileFactory extends AbstractSequentialFileFactor } } - public synchronized void stop() - { + public synchronized void stop() { stopped = true; clearPoll(); } - public synchronized void clearPoll() - { + public synchronized void clearPoll() { ByteBuffer reusedBuffer; - while ((reusedBuffer = reuseBuffersQueue.poll()) != null) - { + while ((reusedBuffer = reuseBuffersQueue.poll()) != null) { releaseBuffer(reusedBuffer); } } - public void bufferDone(final ByteBuffer buffer) - { - synchronized (this) - { + public void bufferDone(final ByteBuffer buffer) { + synchronized (this) { - if (stopped) - { + if (stopped) { releaseBuffer(buffer); } - else - { + else { bufferReuseLastTime = System.currentTimeMillis(); // If a buffer has any other than the configured bufferSize, the buffer // will be just sent to GC - if (buffer.capacity() == bufferSize) - { + if (buffer.capacity() == bufferSize) { reuseBuffersQueue.offer(buffer); } - else - { + else { releaseBuffer(buffer); } } @@ -510,12 +431,9 @@ public final class AIOSequentialFileFactory extends AbstractSequentialFileFactor } } - private static ClassLoader getThisClassLoader() - { - return AccessController.doPrivileged(new PrivilegedAction() - { - public ClassLoader run() - { + private static ClassLoader getThisClassLoader() { + return AccessController.doPrivileged(new PrivilegedAction() { + public ClassLoader run() { return AIOSequentialFileFactory.class.getClassLoader(); } }); @@ -523,8 +441,7 @@ public final class AIOSequentialFileFactory extends AbstractSequentialFileFactor } @Override - public String toString() - { + public String toString() { return AIOSequentialFileFactory.class.getSimpleName() + "(buffersControl.stopped=" + buffersControl.stopped + "):" + super.toString(); } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/aio/ActiveMQFileLock.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/aio/ActiveMQFileLock.java index a184244434..e8c9e0ce3d 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/aio/ActiveMQFileLock.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/aio/ActiveMQFileLock.java @@ -22,26 +22,22 @@ import java.nio.channels.FileLock; import org.apache.activemq.artemis.jlibaio.LibaioFile; -public class ActiveMQFileLock extends FileLock -{ +public class ActiveMQFileLock extends FileLock { private final LibaioFile file; - public ActiveMQFileLock(final LibaioFile handle) - { - super((FileChannel)null, 0, 0, false); + public ActiveMQFileLock(final LibaioFile handle) { + super((FileChannel) null, 0, 0, false); this.file = handle; } @Override - public boolean isValid() - { + public boolean isValid() { return true; } @Override - public void release() throws IOException - { + public void release() throws IOException { file.close(); } } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/buffer/TimedBuffer.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/buffer/TimedBuffer.java index a61569aabb..d72717a7f6 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/buffer/TimedBuffer.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/buffer/TimedBuffer.java @@ -33,8 +33,7 @@ import org.apache.activemq.artemis.core.journal.EncodingSupport; import org.apache.activemq.artemis.core.journal.impl.dataformat.ByteArrayEncoding; import org.apache.activemq.artemis.journal.ActiveMQJournalLogger; -public class TimedBuffer -{ +public class TimedBuffer { // Constants ----------------------------------------------------- // The number of tries on sleep before switching to spin @@ -96,14 +95,12 @@ public class TimedBuffer // Public -------------------------------------------------------- - public TimedBuffer(final int size, final int timeout, final boolean logRates) - { + public TimedBuffer(final int size, final int timeout, final boolean logRates) { bufferSize = size; this.logRates = logRates; - if (logRates) - { + if (logRates) { logRatesTimer = new Timer(true); } // Setting the interval for nano-sleeps @@ -120,30 +117,24 @@ public class TimedBuffer } // for Debug purposes - public synchronized boolean isUseSleep() - { + public synchronized boolean isUseSleep() { return useSleep; } - public synchronized void setUseSleep(boolean useSleep) - { + public synchronized void setUseSleep(boolean useSleep) { this.useSleep = useSleep; } - public synchronized void start() - { - if (started) - { + public synchronized void start() { + if (started) { return; } // Need to start with the spin limiter acquired - try - { + try { spinLimiter.acquire(); } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } @@ -153,8 +144,7 @@ public class TimedBuffer timerThread.start(); - if (logRates) - { + if (logRates) { logRatesTimerTask = new LogRatesTimerTask(); logRatesTimer.scheduleAtFixedRate(logRatesTimerTask, 2000, 2000); @@ -163,10 +153,8 @@ public class TimedBuffer started = true; } - public void stop() - { - if (!started) - { + public void stop() { + if (!started) { return; } @@ -178,19 +166,15 @@ public class TimedBuffer spinLimiter.release(); - if (logRates) - { + if (logRates) { logRatesTimerTask.cancel(); } - while (timerThread.isAlive()) - { - try - { + while (timerThread.isAlive()) { + try { timerThread.join(); } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } } @@ -198,10 +182,8 @@ public class TimedBuffer started = false; } - public synchronized void setObserver(final TimedBufferObserver observer) - { - if (bufferObserver != null) - { + public synchronized void setObserver(final TimedBufferObserver observer) { + if (bufferObserver != null) { flush(); } @@ -213,21 +195,17 @@ public class TimedBuffer * * @param sizeChecked */ - public synchronized boolean checkSize(final int sizeChecked) - { - if (!started) - { + public synchronized boolean checkSize(final int sizeChecked) { + if (!started) { throw new IllegalStateException("TimedBuffer is not started"); } - if (sizeChecked > bufferSize) - { + if (sizeChecked > bufferSize) { throw new IllegalStateException("Can't write records bigger than the bufferSize(" + bufferSize + ") on the journal"); } - if (bufferLimit == 0 || buffer.writerIndex() + sizeChecked > bufferLimit) - { + if (bufferLimit == 0 || buffer.writerIndex() + sizeChecked > bufferLimit) { // Either there is not enough space left in the buffer for the sized record // Or a flush has just been performed and we need to re-calcualate bufferLimit @@ -237,12 +215,10 @@ public class TimedBuffer final int remainingInFile = bufferObserver.getRemainingBytes(); - if (sizeChecked > remainingInFile) - { + if (sizeChecked > remainingInFile) { return false; } - else - { + else { // There is enough space in the file for this size // Need to re-calculate buffer limit @@ -252,23 +228,19 @@ public class TimedBuffer return true; } } - else - { + else { delayFlush = true; return true; } } - public synchronized void addBytes(final ActiveMQBuffer bytes, final boolean sync, final IOCallback callback) - { + public synchronized void addBytes(final ActiveMQBuffer bytes, final boolean sync, final IOCallback callback) { addBytes(new ByteArrayEncoding(bytes.toByteBuffer().array()), sync, callback); } - public synchronized void addBytes(final EncodingSupport bytes, final boolean sync, final IOCallback callback) - { - if (!started) - { + public synchronized void addBytes(final EncodingSupport bytes, final boolean sync, final IOCallback callback) { + if (!started) { throw new IllegalStateException("TimedBuffer is not started"); } @@ -278,8 +250,7 @@ public class TimedBuffer callbacks.add(callback); - if (sync) - { + if (sync) { pendingSync = true; startSpin(); @@ -287,8 +258,7 @@ public class TimedBuffer } - public void flush() - { + public void flush() { flush(false); } @@ -296,21 +266,16 @@ public class TimedBuffer * force means the Journal is moving to a new file. Any pending write need to be done immediately * or data could be lost */ - public void flush(final boolean force) - { - synchronized (this) - { - if (!started) - { + public void flush(final boolean force) { + synchronized (this) { + if (!started) { throw new IllegalStateException("TimedBuffer is not started"); } - if ((force || !delayFlush) && buffer.writerIndex() > 0) - { + if ((force || !delayFlush) && buffer.writerIndex() > 0) { int pos = buffer.writerIndex(); - if (logRates) - { + if (logRates) { bytesFlushed.addAndGet(pos); } @@ -348,8 +313,8 @@ public class TimedBuffer // Inner classes ------------------------------------------------- - private class LogRatesTimerTask extends TimerTask - { + private class LogRatesTimerTask extends TimerTask { + private boolean closed; private long lastExecution; @@ -359,17 +324,14 @@ public class TimedBuffer private long lastFlushesDone; @Override - public synchronized void run() - { - if (!closed) - { + public synchronized void run() { + if (!closed) { long now = System.currentTimeMillis(); long bytesF = bytesFlushed.get(); long flushesD = flushesDone.get(); - if (lastExecution != 0) - { + if (lastExecution != 0) { double rate = 1000 * (double) (bytesF - lastBytesFlushed) / (now - lastExecution); ActiveMQJournalLogger.LOGGER.writeRate(rate, (long) (rate / (1024 * 1024))); double flushRate = 1000 * (double) (flushesD - lastFlushesDone) / (now - lastExecution); @@ -385,16 +347,15 @@ public class TimedBuffer } @Override - public synchronized boolean cancel() - { + public synchronized boolean cancel() { closed = true; return super.cancel(); } } - private class CheckTimer implements Runnable - { + private class CheckTimer implements Runnable { + private volatile boolean closed = false; int checks = 0; @@ -404,28 +365,22 @@ public class TimedBuffer final int sleepMillis = timeout / 1000000; // truncates final int sleepNanos = timeout % 1000000; - - public void run() - { + public void run() { long lastFlushTime = 0; - while (!closed) - { + while (!closed) { // We flush on the timer if there are pending syncs there and we've waited at least one // timeout since the time of the last flush. // Effectively flushing "resets" the timer // On the timeout verification, notice that we ignore the timeout check if we are using sleep - if (pendingSync) - { - if (isUseSleep()) - { + if (pendingSync) { + if (isUseSleep()) { // if using sleep, we will always flush flush(); lastFlushTime = System.nanoTime(); } - else if (bufferObserver != null && System.nanoTime() > lastFlushTime + timeout) - { + else if (bufferObserver != null && System.nanoTime() > lastFlushTime + timeout) { // if not using flush we will spin and do the time checks manually flush(); lastFlushTime = System.nanoTime(); @@ -435,16 +390,14 @@ public class TimedBuffer sleepIfPossible(); - try - { + try { spinLimiter.acquire(); Thread.yield(); spinLimiter.release(); } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } } @@ -455,43 +408,33 @@ public class TimedBuffer * we will on that case verify up to MAX_CHECKS if nano sleep is behaving well. * if more than 50% of the checks have failed we will cancel the sleep and just use regular spin */ - private void sleepIfPossible() - { - if (isUseSleep()) - { - if (checks < MAX_CHECKS_ON_SLEEP) - { + private void sleepIfPossible() { + if (isUseSleep()) { + if (checks < MAX_CHECKS_ON_SLEEP) { timeBefore = System.nanoTime(); } - try - { + try { sleep(sleepMillis, sleepNanos); } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } - catch (Exception e) - { + catch (Exception e) { setUseSleep(false); ActiveMQJournalLogger.LOGGER.warn(e.getMessage() + ", disabling sleep on TimedBuffer, using spin now", e); } - if (checks < MAX_CHECKS_ON_SLEEP) - { + if (checks < MAX_CHECKS_ON_SLEEP) { long realTimeSleep = System.nanoTime() - timeBefore; // I'm letting the real time to be up to 50% than the requested sleep. - if (realTimeSleep > timeout * 1.5) - { + if (realTimeSleep > timeout * 1.5) { failedChecks++; } - if (++checks >= MAX_CHECKS_ON_SLEEP) - { - if (failedChecks > MAX_CHECKS_ON_SLEEP * 0.5) - { + if (++checks >= MAX_CHECKS_ON_SLEEP) { + if (failedChecks > MAX_CHECKS_ON_SLEEP * 0.5) { ActiveMQJournalLogger.LOGGER.debug("Thread.sleep with nano seconds is not working as expected, Your kernel possibly doesn't support real time. the Journal TimedBuffer will spin for timeouts"); setUseSleep(false); } @@ -500,8 +443,7 @@ public class TimedBuffer } } - public void close() - { + public void close() { closed = true; } } @@ -513,26 +455,21 @@ public class TimedBuffer * @param sleepNanos * @throws InterruptedException */ - protected void sleep(int sleepMillis, int sleepNanos) throws InterruptedException - { + protected void sleep(int sleepMillis, int sleepNanos) throws InterruptedException { Thread.sleep(sleepMillis, sleepNanos); } /** * Sub classes (tests basically) can use this to override disabling spinning */ - protected void stopSpin() - { - if (spinning) - { - try - { + protected void stopSpin() { + if (spinning) { + try { // We acquire the spinLimiter semaphore - this prevents the timer flush thread unnecessarily spinning // when the buffer is inactive spinLimiter.acquire(); } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } @@ -540,19 +477,15 @@ public class TimedBuffer } } - /** * Sub classes (tests basically) can use this to override disabling spinning */ - protected void startSpin() - { - if (!spinning) - { + protected void startSpin() { + if (!spinning) { spinLimiter.release(); spinning = true; } } - } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/buffer/TimedBufferObserver.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/buffer/TimedBufferObserver.java index 7a9659f4e7..7812531ef2 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/buffer/TimedBufferObserver.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/buffer/TimedBufferObserver.java @@ -21,9 +21,7 @@ import java.util.List; import org.apache.activemq.artemis.core.io.IOCallback; - -public interface TimedBufferObserver -{ +public interface TimedBufferObserver { // Constants ----------------------------------------------------- @@ -37,7 +35,9 @@ public interface TimedBufferObserver void flushBuffer(ByteBuffer buffer, boolean syncRequested, List callbacks); - /** Return the number of remaining bytes that still fit on the observer (file) */ + /** + * Return the number of remaining bytes that still fit on the observer (file) + */ int getRemainingBytes(); ByteBuffer newBuffer(int size, int limit); diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/nio/NIOSequentialFile.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/nio/NIOSequentialFile.java index d20045ebe2..ae93a31aec 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/nio/NIOSequentialFile.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/nio/NIOSequentialFile.java @@ -36,8 +36,8 @@ import org.apache.activemq.artemis.core.io.SequentialFileFactory; import org.apache.activemq.artemis.journal.ActiveMQJournalBundle; import org.apache.activemq.artemis.journal.ActiveMQJournalLogger; -public final class NIOSequentialFile extends AbstractSequentialFile -{ +public final class NIOSequentialFile extends AbstractSequentialFile { + private FileChannel channel; private RandomAccessFile rfile; @@ -55,24 +55,20 @@ public final class NIOSequentialFile extends AbstractSequentialFile final File directory, final String file, final int maxIO, - final Executor writerExecutor) - { + final Executor writerExecutor) { super(directory, file, factory, writerExecutor); defaultMaxIO = maxIO; } - public int getAlignment() - { + public int getAlignment() { return 1; } - public int calculateBlockStart(final int position) - { + public int calculateBlockStart(final int position) { return position; } - public synchronized boolean isOpen() - { + public synchronized boolean isOpen() { return channel != null; } @@ -80,50 +76,42 @@ public final class NIOSequentialFile extends AbstractSequentialFile * this.maxIO represents the default maxIO. * Some operations while initializing files on the journal may require a different maxIO */ - public synchronized void open() throws IOException - { + public synchronized void open() throws IOException { open(defaultMaxIO, true); } - public void open(final int maxIO, final boolean useExecutor) throws IOException - { - try - { + public void open(final int maxIO, final boolean useExecutor) throws IOException { + try { rfile = new RandomAccessFile(getFile(), "rw"); channel = rfile.getChannel(); fileSize = channel.size(); } - catch (IOException e) - { + catch (IOException e) { factory.onIOError(new ActiveMQIOErrorException(e.getMessage(), e), e.getMessage(), this); throw e; } - if (writerExecutor != null && useExecutor) - { + if (writerExecutor != null && useExecutor) { maxIOSemaphore = new Semaphore(maxIO); this.maxIO = maxIO; } } - public void fill(final int size) throws IOException - { + public void fill(final int size) throws IOException { ByteBuffer bb = ByteBuffer.allocate(size); bb.limit(size); bb.position(0); - try - { + try { channel.position(0); channel.write(bb); channel.force(false); channel.position(0); } - catch (IOException e) - { + catch (IOException e) { factory.onIOError(new ActiveMQIOErrorException(e.getMessage(), e), e.getMessage(), this); throw e; } @@ -132,33 +120,26 @@ public final class NIOSequentialFile extends AbstractSequentialFile } @Override - public synchronized void close() throws IOException, InterruptedException, ActiveMQException - { + public synchronized void close() throws IOException, InterruptedException, ActiveMQException { super.close(); - if (maxIOSemaphore != null) - { - while (!maxIOSemaphore.tryAcquire(maxIO, 60, TimeUnit.SECONDS)) - { + if (maxIOSemaphore != null) { + while (!maxIOSemaphore.tryAcquire(maxIO, 60, TimeUnit.SECONDS)) { ActiveMQJournalLogger.LOGGER.errorClosingFile(getFileName()); } } maxIOSemaphore = null; - try - { - if (channel != null) - { + try { + if (channel != null) { channel.close(); } - if (rfile != null) - { + if (rfile != null) { rfile.close(); } } - catch (IOException e) - { + catch (IOException e) { factory.onIOError(new ActiveMQIOErrorException(e.getMessage(), e), e.getMessage(), this); throw e; } @@ -169,24 +150,19 @@ public final class NIOSequentialFile extends AbstractSequentialFile notifyAll(); } - public int read(final ByteBuffer bytes) throws Exception - { + public int read(final ByteBuffer bytes) throws Exception { return read(bytes, null); } - public synchronized int read(final ByteBuffer bytes, final IOCallback callback) throws IOException, - ActiveMQIllegalStateException - { - try - { - if (channel == null) - { + public synchronized int read(final ByteBuffer bytes, + final IOCallback callback) throws IOException, ActiveMQIllegalStateException { + try { + if (channel == null) { throw new ActiveMQIllegalStateException("File " + this.getFileName() + " has a null channel"); } int bytesRead = channel.read(bytes); - if (callback != null) - { + if (callback != null) { callback.done(); } @@ -194,10 +170,8 @@ public final class NIOSequentialFile extends AbstractSequentialFile return bytesRead; } - catch (IOException e) - { - if (callback != null) - { + catch (IOException e) { + if (callback != null) { callback.onError(ActiveMQExceptionType.IO_ERROR.getCode(), e.getLocalizedMessage()); } @@ -207,96 +181,76 @@ public final class NIOSequentialFile extends AbstractSequentialFile } } - public void sync() throws IOException - { - if (channel != null) - { - try - { + public void sync() throws IOException { + if (channel != null) { + try { channel.force(false); } - catch (IOException e) - { + catch (IOException e) { factory.onIOError(new ActiveMQIOErrorException(e.getMessage(), e), e.getMessage(), this); throw e; } } } - public long size() throws IOException - { - if (channel == null) - { + public long size() throws IOException { + if (channel == null) { return getFile().length(); } - try - { + try { return channel.size(); } - catch (IOException e) - { + catch (IOException e) { factory.onIOError(new ActiveMQIOErrorException(e.getMessage(), e), e.getMessage(), this); throw e; } } @Override - public void position(final long pos) throws IOException - { - try - { + public void position(final long pos) throws IOException { + try { super.position(pos); channel.position(pos); } - catch (IOException e) - { + catch (IOException e) { factory.onIOError(new ActiveMQIOErrorException(e.getMessage(), e), e.getMessage(), this); throw e; } } @Override - public String toString() - { + public String toString() { return "NIOSequentialFile " + getFile(); } - public SequentialFile cloneFile() - { + public SequentialFile cloneFile() { return new NIOSequentialFile(factory, directory, getFileName(), maxIO, writerExecutor); } - public void writeDirect(final ByteBuffer bytes, final boolean sync, final IOCallback callback) - { - if (callback == null) - { + public void writeDirect(final ByteBuffer bytes, final boolean sync, final IOCallback callback) { + if (callback == null) { throw new NullPointerException("callback parameter need to be set"); } - try - { + try { internalWrite(bytes, sync, callback); } - catch (Exception e) - { + catch (Exception e) { callback.onError(ActiveMQExceptionType.GENERIC_EXCEPTION.getCode(), e.getMessage()); } } - public void writeDirect(final ByteBuffer bytes, final boolean sync) throws Exception - { + public void writeDirect(final ByteBuffer bytes, final boolean sync) throws Exception { internalWrite(bytes, sync, null); } - public void writeInternal(final ByteBuffer bytes) throws Exception - { + public void writeInternal(final ByteBuffer bytes) throws Exception { internalWrite(bytes, true, null); } @Override - protected ByteBuffer newBuffer(int size, final int limit) - { + protected ByteBuffer newBuffer(int size, final int limit) { // For NIO, we don't need to allocate a buffer the entire size of the timed buffer, unlike AIO size = limit; @@ -304,16 +258,14 @@ public final class NIOSequentialFile extends AbstractSequentialFile return super.newBuffer(size, limit); } - private void internalWrite(final ByteBuffer bytes, final boolean sync, final IOCallback callback) throws IOException, ActiveMQIOErrorException, InterruptedException - { - if (!isOpen()) - { - if (callback != null) - { + private void internalWrite(final ByteBuffer bytes, + final boolean sync, + final IOCallback callback) throws IOException, ActiveMQIOErrorException, InterruptedException { + if (!isOpen()) { + if (callback != null) { callback.onError(ActiveMQExceptionType.IO_ERROR.getCode(), "File not opened"); } - else - { + else { throw ActiveMQJournalBundle.BUNDLE.fileNotOpened(); } return; @@ -321,47 +273,36 @@ public final class NIOSequentialFile extends AbstractSequentialFile position.addAndGet(bytes.limit()); - if (maxIOSemaphore == null || callback == null) - { + if (maxIOSemaphore == null || callback == null) { // if maxIOSemaphore == null, that means we are not using executors and the writes are synchronous - try - { + try { doInternalWrite(bytes, sync, callback); } - catch (IOException e) - { + catch (IOException e) { factory.onIOError(new ActiveMQIOErrorException(e.getMessage(), e), e.getMessage(), this); } } - else - { + else { // This is a flow control on writing, just like maxAIO on libaio maxIOSemaphore.acquire(); - writerExecutor.execute(new Runnable() - { - public void run() - { - try - { - try - { + writerExecutor.execute(new Runnable() { + public void run() { + try { + try { doInternalWrite(bytes, sync, callback); } - catch (IOException e) - { + catch (IOException e) { ActiveMQJournalLogger.LOGGER.errorSubmittingWrite(e); factory.onIOError(new ActiveMQIOErrorException(e.getMessage(), e), e.getMessage(), NIOSequentialFile.this); callback.onError(ActiveMQExceptionType.IO_ERROR.getCode(), e.getMessage()); } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQJournalLogger.LOGGER.errorSubmittingWrite(e); callback.onError(ActiveMQExceptionType.IO_ERROR.getCode(), e.getMessage()); } } - finally - { + finally { maxIOSemaphore.release(); } } @@ -376,17 +317,16 @@ public final class NIOSequentialFile extends AbstractSequentialFile * @throws IOException * @throws Exception */ - private void doInternalWrite(final ByteBuffer bytes, final boolean sync, final IOCallback callback) throws IOException - { + private void doInternalWrite(final ByteBuffer bytes, + final boolean sync, + final IOCallback callback) throws IOException { channel.write(bytes); - if (sync) - { + if (sync) { sync(); } - if (callback != null) - { + if (callback != null) { callback.done(); } } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/nio/NIOSequentialFileFactory.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/nio/NIOSequentialFileFactory.java index e64e405f3b..36962b77ad 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/nio/NIOSequentialFileFactory.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/io/nio/NIOSequentialFileFactory.java @@ -25,40 +25,25 @@ import org.apache.activemq.artemis.core.io.IOCriticalErrorListener; import org.apache.activemq.artemis.core.io.SequentialFile; import org.apache.activemq.artemis.core.journal.impl.JournalConstants; -public class NIOSequentialFileFactory extends AbstractSequentialFileFactory -{ - public NIOSequentialFileFactory(final File journalDir, final int maxIO) - { +public class NIOSequentialFileFactory extends AbstractSequentialFileFactory { + + public NIOSequentialFileFactory(final File journalDir, final int maxIO) { this(journalDir, null, maxIO); } - public NIOSequentialFileFactory(final File journalDir, final IOCriticalErrorListener listener, final int maxIO) - { - this(journalDir, - false, - JournalConstants.DEFAULT_JOURNAL_BUFFER_SIZE_NIO, - JournalConstants.DEFAULT_JOURNAL_BUFFER_TIMEOUT_NIO, - maxIO, - false, - listener); + public NIOSequentialFileFactory(final File journalDir, final IOCriticalErrorListener listener, final int maxIO) { + this(journalDir, false, JournalConstants.DEFAULT_JOURNAL_BUFFER_SIZE_NIO, JournalConstants.DEFAULT_JOURNAL_BUFFER_TIMEOUT_NIO, maxIO, false, listener); } - public NIOSequentialFileFactory(final File journalDir, final boolean buffered, final int maxIO) - { + public NIOSequentialFileFactory(final File journalDir, final boolean buffered, final int maxIO) { this(journalDir, buffered, null, maxIO); } public NIOSequentialFileFactory(final File journalDir, final boolean buffered, - final IOCriticalErrorListener listener, final int maxIO) - { - this(journalDir, - buffered, - JournalConstants.DEFAULT_JOURNAL_BUFFER_SIZE_NIO, - JournalConstants.DEFAULT_JOURNAL_BUFFER_TIMEOUT_NIO, - maxIO, - false, - listener); + final IOCriticalErrorListener listener, + final int maxIO) { + this(journalDir, buffered, JournalConstants.DEFAULT_JOURNAL_BUFFER_SIZE_NIO, JournalConstants.DEFAULT_JOURNAL_BUFFER_TIMEOUT_NIO, maxIO, false, listener); } public NIOSequentialFileFactory(final File journalDir, @@ -66,8 +51,7 @@ public class NIOSequentialFileFactory extends AbstractSequentialFileFactory final int bufferSize, final int bufferTimeout, final int maxIO, - final boolean logRates) - { + final boolean logRates) { this(journalDir, buffered, bufferSize, bufferTimeout, maxIO, logRates, null); } @@ -77,48 +61,38 @@ public class NIOSequentialFileFactory extends AbstractSequentialFileFactory final int bufferTimeout, final int maxIO, final boolean logRates, - final IOCriticalErrorListener listener) - { + final IOCriticalErrorListener listener) { super(journalDir, buffered, bufferSize, bufferTimeout, maxIO, logRates, listener); } - public SequentialFile createSequentialFile(final String fileName) - { + public SequentialFile createSequentialFile(final String fileName) { return new NIOSequentialFile(this, journalDir, fileName, maxIO, writeExecutor); } - public boolean isSupportsCallbacks() - { + public boolean isSupportsCallbacks() { return timedBuffer != null; } - - public ByteBuffer allocateDirectBuffer(final int size) - { + public ByteBuffer allocateDirectBuffer(final int size) { // Using direct buffer, as described on https://jira.jboss.org/browse/HORNETQ-467 ByteBuffer buffer2 = null; - try - { + try { buffer2 = ByteBuffer.allocateDirect(size); } - catch (OutOfMemoryError error) - { + catch (OutOfMemoryError error) { // This is a workaround for the way the JDK will deal with native buffers. // the main portion is outside of the VM heap // and the JDK will not have any reference about it to take GC into account // so we force a GC and try again. WeakReference obj = new WeakReference(new Object()); - try - { + try { long timeout = System.currentTimeMillis() + 5000; - while (System.currentTimeMillis() > timeout && obj.get() != null) - { + while (System.currentTimeMillis() > timeout && obj.get() != null) { System.gc(); Thread.sleep(100); } } - catch (InterruptedException e) - { + catch (InterruptedException e) { } buffer2 = ByteBuffer.allocateDirect(size); @@ -127,41 +101,34 @@ public class NIOSequentialFileFactory extends AbstractSequentialFileFactory return buffer2; } - public void releaseDirectBuffer(ByteBuffer buffer) - { + public void releaseDirectBuffer(ByteBuffer buffer) { // nothing we can do on this case. we can just have good faith on GC } - public ByteBuffer newBuffer(final int size) - { + public ByteBuffer newBuffer(final int size) { return ByteBuffer.allocate(size); } - public void clearBuffer(final ByteBuffer buffer) - { + public void clearBuffer(final ByteBuffer buffer) { final int limit = buffer.limit(); buffer.rewind(); - for (int i = 0; i < limit; i++) - { - buffer.put((byte)0); + for (int i = 0; i < limit; i++) { + buffer.put((byte) 0); } buffer.rewind(); } - public ByteBuffer wrapBuffer(final byte[] bytes) - { + public ByteBuffer wrapBuffer(final byte[] bytes) { return ByteBuffer.wrap(bytes); } - public int getAlignment() - { + public int getAlignment() { return 1; } - public int calculateBlockSize(final int bytes) - { + public int calculateBlockSize(final int bytes) { return bytes; } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/EncodingSupport.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/EncodingSupport.java index 3835754228..5bf6839b9a 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/EncodingSupport.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/EncodingSupport.java @@ -21,8 +21,8 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; /** * This interface provides encoding support for the Journal. */ -public interface EncodingSupport -{ +public interface EncodingSupport { + int getEncodeSize(); void encode(ActiveMQBuffer buffer); diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/IOCompletion.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/IOCompletion.java index d0140f17de..ee5e9c37a6 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/IOCompletion.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/IOCompletion.java @@ -18,7 +18,7 @@ package org.apache.activemq.artemis.core.journal; import org.apache.activemq.artemis.core.io.IOCallback; -public interface IOCompletion extends IOCallback -{ +public interface IOCompletion extends IOCallback { + void storeLineUp(); } \ No newline at end of file diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/Journal.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/Journal.java index 6b0beabdf3..3c1f7fd050 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/Journal.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/Journal.java @@ -30,10 +30,9 @@ import org.apache.activemq.artemis.core.server.ActiveMQComponent; * Notice also that even on the callback methods it's possible to pass the sync mode. That will only * make sense on the NIO operations. */ -public interface Journal extends ActiveMQComponent -{ - enum JournalState - { +public interface Journal extends ActiveMQComponent { + + enum JournalState { STOPPED, /** * The journal has some fields initialized and services running. But it is not fully @@ -63,7 +62,11 @@ public interface Journal extends ActiveMQComponent void appendAddRecord(long id, byte recordType, EncodingSupport record, boolean sync) throws Exception; - void appendAddRecord(long id, byte recordType, EncodingSupport record, boolean sync, IOCompletion completionCallback) throws Exception; + void appendAddRecord(long id, + byte recordType, + EncodingSupport record, + boolean sync, + IOCompletion completionCallback) throws Exception; void appendUpdateRecord(long id, byte recordType, byte[] record, boolean sync) throws Exception; @@ -104,15 +107,14 @@ public interface Journal extends ActiveMQComponent * @param sync * @param callback * @param lineUpContext if appendCommitRecord should call a storeLineUp. This is because the - * caller may have already taken into account + * caller may have already taken into account * @throws Exception */ void appendCommitRecord(long txID, boolean sync, IOCompletion callback, boolean lineUpContext) throws Exception; /** - * *

    If the system crashed after a prepare was called, it should store information that is required to bring the transaction - * back to a state it could be committed.

    + * back to a state it could be committed.

    * *

    transactionData allows you to store any other supporting user-data related to the transaction

    * @@ -122,7 +124,10 @@ public interface Journal extends ActiveMQComponent */ void appendPrepareRecord(long txID, EncodingSupport transactionData, boolean sync) throws Exception; - void appendPrepareRecord(long txID, EncodingSupport transactionData, boolean sync, IOCompletion callback) throws Exception; + void appendPrepareRecord(long txID, + EncodingSupport transactionData, + boolean sync, + IOCompletion callback) throws Exception; void appendPrepareRecord(long txID, byte[] transactionData, boolean sync) throws Exception; @@ -143,6 +148,7 @@ public interface Journal extends ActiveMQComponent /** * Load internal data structures, and remain waiting for synchronization to complete. + * * @param state the current state of the journal, this parameter ensures consistency. */ JournalLoadInformation loadSyncOnly(JournalState state) throws Exception; @@ -170,6 +176,7 @@ public interface Journal extends ActiveMQComponent * During the synchronization between a live server and backup, we reserve in the backup the * journal file IDs used in the live server. This call also makes sure the files are created * empty without any kind of headers added. + * * @param fileIds IDs to reserve for synchronization * @return map to be filled with id and journal file pairs for synchronization. * @throws Exception @@ -184,18 +191,21 @@ public interface Journal extends ActiveMQComponent /** * Unlock the Journal and the compacting process. + * * @see Journal#synchronizationLock() */ void synchronizationUnlock(); /** * Force the usage of a new {@link JournalFile}. + * * @throws Exception */ void forceMoveNextFile() throws Exception; /** * Returns the {@link JournalFile}s in use. + * * @return array with all {@link JournalFile}s in use */ JournalFile[] getDataFiles(); @@ -206,6 +216,7 @@ public interface Journal extends ActiveMQComponent /** * This method will start compact using the compactorExecutor and block up to timeout seconds + * * @param timeout the timeout in seconds or block forever if {@code <= 0} * @throws Exception */ diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/JournalLoadInformation.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/JournalLoadInformation.java index 7e13336f31..fe9fdc65d3 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/JournalLoadInformation.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/JournalLoadInformation.java @@ -19,15 +19,13 @@ package org.apache.activemq.artemis.core.journal; /** * This is a POJO containing information about the journal during load time. */ -public class JournalLoadInformation -{ +public class JournalLoadInformation { private int numberOfRecords = 0; private long maxID = -1; - public JournalLoadInformation() - { + public JournalLoadInformation() { super(); } @@ -35,8 +33,7 @@ public class JournalLoadInformation * @param numberOfRecords * @param maxID */ - public JournalLoadInformation(final int numberOfRecords, final long maxID) - { + public JournalLoadInformation(final int numberOfRecords, final long maxID) { super(); this.numberOfRecords = numberOfRecords; this.maxID = maxID; @@ -45,75 +42,63 @@ public class JournalLoadInformation /** * @return the numberOfRecords */ - public int getNumberOfRecords() - { + public int getNumberOfRecords() { return numberOfRecords; } /** * @param numberOfRecords the numberOfRecords to set */ - public void setNumberOfRecords(final int numberOfRecords) - { + public void setNumberOfRecords(final int numberOfRecords) { this.numberOfRecords = numberOfRecords; } /** * @return the maxID */ - public long getMaxID() - { + public long getMaxID() { return maxID; } /** * @param maxID the maxID to set */ - public void setMaxID(final long maxID) - { + public void setMaxID(final long maxID) { this.maxID = maxID; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + (int)(maxID ^ maxID >>> 32); + result = prime * result + (int) (maxID ^ maxID >>> 32); result = prime * result + numberOfRecords; return result; } @Override - public boolean equals(final Object obj) - { - if (this == obj) - { + public boolean equals(final Object obj) { + if (this == obj) { return true; } - if (obj == null) - { + if (obj == null) { return false; } - if (getClass() != obj.getClass()) - { + if (getClass() != obj.getClass()) { return false; } - JournalLoadInformation other = (JournalLoadInformation)obj; - if (maxID != other.maxID) - { + JournalLoadInformation other = (JournalLoadInformation) obj; + if (maxID != other.maxID) { return false; } - if (numberOfRecords != other.numberOfRecords) - { + if (numberOfRecords != other.numberOfRecords) { return false; } return true; } @Override - public String toString() - { + public String toString() { return "JournalLoadInformation [maxID=" + maxID + ", numberOfRecords=" + numberOfRecords + "]"; } } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/LoaderCallback.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/LoaderCallback.java index 4b0e8fab8a..d2c9d32ff0 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/LoaderCallback.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/LoaderCallback.java @@ -16,8 +16,8 @@ */ package org.apache.activemq.artemis.core.journal; -public interface LoaderCallback extends TransactionFailureCallback -{ +public interface LoaderCallback extends TransactionFailureCallback { + void addPreparedTransaction(PreparedTransactionInfo preparedTransaction); void addRecord(RecordInfo info); diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/PreparedTransactionInfo.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/PreparedTransactionInfo.java index d0934ee037..3d82a23cde 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/PreparedTransactionInfo.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/PreparedTransactionInfo.java @@ -19,8 +19,8 @@ package org.apache.activemq.artemis.core.journal; import java.util.ArrayList; import java.util.List; -public class PreparedTransactionInfo -{ +public class PreparedTransactionInfo { + public final long id; public final byte[] extraData; @@ -29,8 +29,7 @@ public class PreparedTransactionInfo public final List recordsToDelete = new ArrayList(); - public PreparedTransactionInfo(final long id, final byte[] extraData) - { + public PreparedTransactionInfo(final long id, final byte[] extraData) { this.id = id; this.extraData = extraData; diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/RecordInfo.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/RecordInfo.java index 5805597d9f..ddc5ea6001 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/RecordInfo.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/RecordInfo.java @@ -16,10 +16,13 @@ */ package org.apache.activemq.artemis.core.journal; -public class RecordInfo -{ - public RecordInfo(final long id, final byte userRecordType, final byte[] data, final boolean isUpdate, final short compactCount) - { +public class RecordInfo { + + public RecordInfo(final long id, + final byte userRecordType, + final byte[] data, + final boolean isUpdate, + final short compactCount) { this.id = id; this.userRecordType = userRecordType; @@ -46,22 +49,18 @@ public class RecordInfo public boolean isUpdate; - public byte getUserRecordType() - { + public byte getUserRecordType() { return userRecordType; } @Override - public int hashCode() - { + public int hashCode() { return (int) (id >>> 32 ^ id); } @Override - public boolean equals(final Object other) - { - if (!(other instanceof RecordInfo)) - { + public boolean equals(final Object other) { + if (!(other instanceof RecordInfo)) { return false; } RecordInfo r = (RecordInfo) other; @@ -70,8 +69,7 @@ public class RecordInfo } @Override - public String toString() - { + public String toString() { return "RecordInfo (id=" + id + ", userRecordType = " + userRecordType + diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/TestableJournal.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/TestableJournal.java index 3a2bb83ed6..4f8dc4a2b7 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/TestableJournal.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/TestableJournal.java @@ -18,8 +18,8 @@ package org.apache.activemq.artemis.core.journal; import org.apache.activemq.artemis.core.journal.impl.JournalFile; -public interface TestableJournal extends Journal -{ +public interface TestableJournal extends Journal { + int getDataFilesCount(); int getFreeFilesCount(); @@ -58,6 +58,7 @@ public interface TestableJournal extends Journal * It will among other things, remove stale files and make them available for reuse. *

    * This method locks the journal. + * * @return true if it needs to re-check due to cleanup or other factors */ boolean checkReclaimStatus() throws Exception; diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/TransactionFailureCallback.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/TransactionFailureCallback.java index c4dbc00a3c..a64a8a76e5 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/TransactionFailureCallback.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/TransactionFailureCallback.java @@ -21,11 +21,12 @@ import java.util.List; /** * A Callback to receive information about bad transactions for extra cleanup required for broken transactions such as large messages. */ -public interface TransactionFailureCallback -{ +public interface TransactionFailureCallback { - /** To be used to inform about transactions without commit records. - * This could be used to remove extra resources associated with the transactions (such as external files received during the transaction) */ + /** + * To be used to inform about transactions without commit records. + * This could be used to remove extra resources associated with the transactions (such as external files received during the transaction) + */ void failedTransaction(long transactionID, List records, List recordsToDelete); } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/AbstractJournalUpdateTask.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/AbstractJournalUpdateTask.java index b36a0c4438..6e9bc698fd 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/AbstractJournalUpdateTask.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/AbstractJournalUpdateTask.java @@ -32,11 +32,9 @@ import org.apache.activemq.artemis.core.journal.impl.dataformat.JournalInternalR import org.apache.activemq.artemis.utils.ConcurrentHashSet; /** - * * Super class for Journal maintenances such as clean up and Compactor */ -public abstract class AbstractJournalUpdateTask implements JournalReaderCallback -{ +public abstract class AbstractJournalUpdateTask implements JournalReaderCallback { // Constants ----------------------------------------------------- @@ -69,8 +67,7 @@ public abstract class AbstractJournalUpdateTask implements JournalReaderCallback final JournalImpl journal, final JournalFilesRepository filesRepository, final Set recordsSnapshot, - final long nextOrderingID) - { + final long nextOrderingID) { super(); this.journal = journal; this.filesRepository = filesRepository; @@ -84,13 +81,11 @@ public abstract class AbstractJournalUpdateTask implements JournalReaderCallback public static SequentialFile writeControlFile(final SequentialFileFactory fileFactory, final List files, final List newFiles, - final List> renames) throws Exception - { + final List> renames) throws Exception { SequentialFile controlFile = fileFactory.createSequentialFile(AbstractJournalUpdateTask.FILE_COMPACT_CONTROL); - try - { + try { controlFile.open(1, false); JournalImpl.initFileHeader(fileFactory, controlFile, 0, 0); @@ -99,56 +94,43 @@ public abstract class AbstractJournalUpdateTask implements JournalReaderCallback // DataFiles first - if (files == null) - { + if (files == null) { filesToRename.writeInt(0); } - else - { + else { filesToRename.writeInt(files.size()); - for (JournalFile file : files) - { + for (JournalFile file : files) { filesToRename.writeUTF(file.getFile().getFileName()); } } // New Files second - if (newFiles == null) - { + if (newFiles == null) { filesToRename.writeInt(0); } - else - { + else { filesToRename.writeInt(newFiles.size()); - for (JournalFile file : newFiles) - { + for (JournalFile file : newFiles) { filesToRename.writeUTF(file.getFile().getFileName()); } } // Renames from clean up third - if (renames == null) - { + if (renames == null) { filesToRename.writeInt(0); } - else - { + else { filesToRename.writeInt(renames.size()); - for (Pair rename : renames) - { + for (Pair rename : renames) { filesToRename.writeUTF(rename.getA()); filesToRename.writeUTF(rename.getB()); } } - JournalInternalRecord controlRecord = new JournalAddRecord(true, - 1, - (byte)0, - new ByteArrayEncoding(filesToRename.toByteBuffer() - .array())); + JournalInternalRecord controlRecord = new JournalAddRecord(true, 1, (byte) 0, new ByteArrayEncoding(filesToRename.toByteBuffer().array())); ActiveMQBuffer renameBuffer = ActiveMQBuffers.dynamicBuffer(filesToRename.writerIndex()); @@ -166,17 +148,16 @@ public abstract class AbstractJournalUpdateTask implements JournalReaderCallback return controlFile; } - finally - { + finally { controlFile.close(); } } - /** Write pending output into file */ - public void flush() throws Exception - { - if (writingChannel != null) - { + /** + * Write pending output into file + */ + public void flush() throws Exception { + if (writingChannel != null) { sequentialFile.position(0); // To Fix the size of the file @@ -190,20 +171,19 @@ public abstract class AbstractJournalUpdateTask implements JournalReaderCallback writingChannel = null; } - public boolean lookupRecord(final long id) - { + public boolean lookupRecord(final long id) { return recordsSnapshot.contains(id); } // Package protected --------------------------------------------- // Protected ----------------------------------------------------- + /** * @throws Exception */ - protected void openFile() throws Exception - { + protected void openFile() throws Exception { flush(); ByteBuffer bufferWrite = fileFactory.newBuffer(journal.getFileSize()); @@ -221,27 +201,23 @@ public abstract class AbstractJournalUpdateTask implements JournalReaderCallback JournalImpl.writeHeader(writingChannel, journal.getUserVersion(), currentFile.getFileID()); } - protected void addToRecordsSnaptshot(final long id) - { + protected void addToRecordsSnaptshot(final long id) { recordsSnapshot.add(id); } /** * @return the writingChannel */ - protected ActiveMQBuffer getWritingChannel() - { + protected ActiveMQBuffer getWritingChannel() { return writingChannel; } - protected void writeEncoder(final JournalInternalRecord record) throws Exception - { + protected void writeEncoder(final JournalInternalRecord record) throws Exception { record.setFileID(currentFile.getRecordID()); record.encode(getWritingChannel()); } - protected void writeEncoder(final JournalInternalRecord record, final int txcounter) throws Exception - { + protected void writeEncoder(final JournalInternalRecord record, final int txcounter) throws Exception { record.setNumberOfRecords(txcounter); writeEncoder(record); } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/FileWrapperJournal.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/FileWrapperJournal.java index 5a0f11f532..ba3807bcd6 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/FileWrapperJournal.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/FileWrapperJournal.java @@ -48,8 +48,8 @@ import org.apache.activemq.artemis.core.journal.impl.dataformat.JournalInternalR * * Its main purpose is to store the data as a Journal would, but without verifying records. */ -public final class FileWrapperJournal extends JournalBase -{ +public final class FileWrapperJournal extends JournalBase { + private final ReentrantLock lockAppend = new ReentrantLock(); private final ConcurrentMap transactions = new ConcurrentHashMap(); @@ -60,29 +60,25 @@ public final class FileWrapperJournal extends JournalBase * @param journal * @throws Exception */ - public FileWrapperJournal(Journal journal) throws Exception - { + public FileWrapperJournal(Journal journal) throws Exception { super(journal.getFileFactory().isSupportsCallbacks(), journal.getFileSize()); - this.journal = (JournalImpl)journal; + this.journal = (JournalImpl) journal; currentFile = this.journal.setUpCurrentFile(JournalImpl.SIZE_HEADER); } @Override - public void start() throws Exception - { + public void start() throws Exception { throw new UnsupportedOperationException(); } @Override - public void stop() throws Exception - { + public void stop() throws Exception { if (currentFile.getFile().isOpen()) currentFile.getFile().close(); } @Override - public boolean isStarted() - { + public boolean isStarted() { throw new UnsupportedOperationException(); } @@ -91,8 +87,11 @@ public final class FileWrapperJournal extends JournalBase // ------------------------ @Override - public void appendAddRecord(long id, byte recordType, EncodingSupport record, boolean sync, IOCompletion callback) throws Exception - { + public void appendAddRecord(long id, + byte recordType, + EncodingSupport record, + boolean sync, + IOCompletion callback) throws Exception { JournalInternalRecord addRecord = new JournalAddRecord(true, id, recordType, record); writeRecord(addRecord, sync, callback); @@ -101,80 +100,81 @@ public final class FileWrapperJournal extends JournalBase /** * Write the record to the current file. */ - private void writeRecord(JournalInternalRecord encoder, final boolean sync, final IOCompletion callback) throws Exception - { + private void writeRecord(JournalInternalRecord encoder, + final boolean sync, + final IOCompletion callback) throws Exception { lockAppend.lock(); - try - { - if (callback != null) - { + try { + if (callback != null) { callback.storeLineUp(); } currentFile = journal.switchFileIfNecessary(encoder.getEncodeSize()); encoder.setFileID(currentFile.getRecordID()); - if (callback != null) - { + if (callback != null) { currentFile.getFile().write(encoder, sync, callback); } - else - { + else { currentFile.getFile().write(encoder, sync); } } - finally - { + finally { lockAppend.unlock(); } } @Override - public void appendDeleteRecord(long id, boolean sync, IOCompletion callback) throws Exception - { + public void appendDeleteRecord(long id, boolean sync, IOCompletion callback) throws Exception { JournalInternalRecord deleteRecord = new JournalDeleteRecord(id); writeRecord(deleteRecord, sync, callback); } @Override - public void appendDeleteRecordTransactional(long txID, long id, EncodingSupport record) throws Exception - { + public void appendDeleteRecordTransactional(long txID, long id, EncodingSupport record) throws Exception { count(txID); JournalInternalRecord deleteRecordTX = new JournalDeleteRecordTX(txID, id, record); writeRecord(deleteRecordTX, false, null); } @Override - public void appendAddRecordTransactional(long txID, long id, byte recordType, EncodingSupport record) throws Exception - { + public void appendAddRecordTransactional(long txID, + long id, + byte recordType, + EncodingSupport record) throws Exception { count(txID); JournalInternalRecord addRecord = new JournalAddRecordTX(true, txID, id, recordType, record); writeRecord(addRecord, false, null); } @Override - public void - appendUpdateRecord(long id, byte recordType, EncodingSupport record, boolean sync, IOCompletion callback) throws Exception - { + public void appendUpdateRecord(long id, + byte recordType, + EncodingSupport record, + boolean sync, + IOCompletion callback) throws Exception { JournalInternalRecord updateRecord = new JournalAddRecord(false, id, recordType, record); writeRecord(updateRecord, sync, callback); } @Override - public void appendUpdateRecordTransactional(long txID, long id, byte recordType, EncodingSupport record) throws Exception - { + public void appendUpdateRecordTransactional(long txID, + long id, + byte recordType, + EncodingSupport record) throws Exception { count(txID); JournalInternalRecord updateRecordTX = new JournalAddRecordTX(false, txID, id, recordType, record); writeRecord(updateRecordTX, false, null); } @Override - public void appendCommitRecord(long txID, boolean sync, IOCompletion callback, boolean lineUpContext) throws Exception - { + public void appendCommitRecord(long txID, + boolean sync, + IOCompletion callback, + boolean lineUpContext) throws Exception { JournalInternalRecord commitRecord = new JournalCompleteRecordTX(TX_RECORD_TYPE.COMMIT, txID, null); AtomicInteger value = transactions.remove(Long.valueOf(txID)); - if (value != null) - { + if (value != null) { commitRecord.setNumberOfRecords(value.get()); } @@ -182,160 +182,138 @@ public final class FileWrapperJournal extends JournalBase } @Override - public void appendPrepareRecord(long txID, EncodingSupport transactionData, boolean sync, IOCompletion callback) throws Exception - { + public void appendPrepareRecord(long txID, + EncodingSupport transactionData, + boolean sync, + IOCompletion callback) throws Exception { JournalInternalRecord prepareRecord = new JournalCompleteRecordTX(TX_RECORD_TYPE.PREPARE, txID, transactionData); AtomicInteger value = transactions.get(Long.valueOf(txID)); - if (value != null) - { + if (value != null) { prepareRecord.setNumberOfRecords(value.get()); } writeRecord(prepareRecord, sync, callback); } - private int count(long txID) throws ActiveMQException - { + private int count(long txID) throws ActiveMQException { AtomicInteger defaultValue = new AtomicInteger(1); AtomicInteger count = transactions.putIfAbsent(Long.valueOf(txID), defaultValue); - if (count != null) - { + if (count != null) { return count.incrementAndGet(); } return defaultValue.get(); } @Override - public String toString() - { + public String toString() { return FileWrapperJournal.class.getName() + "(currentFile=[" + currentFile + "], hash=" + super.toString() + ")"; } // UNSUPPORTED STUFF @Override - public void appendRollbackRecord(long txID, boolean sync, IOCompletion callback) throws Exception - { + public void appendRollbackRecord(long txID, boolean sync, IOCompletion callback) throws Exception { throw new ActiveMQUnsupportedPacketException(); } @Override - public JournalLoadInformation load(LoaderCallback reloadManager) throws Exception - { + public JournalLoadInformation load(LoaderCallback reloadManager) throws Exception { throw new ActiveMQUnsupportedPacketException(); } @Override - public JournalLoadInformation loadInternalOnly() throws Exception - { + public JournalLoadInformation loadInternalOnly() throws Exception { throw new ActiveMQUnsupportedPacketException(); } @Override - public void lineUpContext(IOCompletion callback) - { + public void lineUpContext(IOCompletion callback) { throw new UnsupportedOperationException(); } @Override public JournalLoadInformation load(List committedRecords, - List preparedTransactions, TransactionFailureCallback transactionFailure) throws Exception - { + List preparedTransactions, + TransactionFailureCallback transactionFailure) throws Exception { throw new ActiveMQUnsupportedPacketException(); } @Override - public int getAlignment() throws Exception - { + public int getAlignment() throws Exception { throw new ActiveMQUnsupportedPacketException(); } @Override - public int getNumberOfRecords() - { + public int getNumberOfRecords() { throw new UnsupportedOperationException(); } @Override - public int getUserVersion() - { + public int getUserVersion() { throw new UnsupportedOperationException(); } @Override - public void perfBlast(int pages) - { + public void perfBlast(int pages) { throw new UnsupportedOperationException(); } @Override - public void runDirectJournalBlast() throws Exception - { + public void runDirectJournalBlast() throws Exception { throw new UnsupportedOperationException(); } @Override - public JournalLoadInformation loadSyncOnly(JournalState state) throws Exception - { + public JournalLoadInformation loadSyncOnly(JournalState state) throws Exception { throw new UnsupportedOperationException(); } @Override - public Map createFilesForBackupSync(long[] fileIds) throws Exception - { + public Map createFilesForBackupSync(long[] fileIds) throws Exception { throw new UnsupportedOperationException(); } @Override - public void synchronizationLock() - { + public void synchronizationLock() { throw new UnsupportedOperationException(); } @Override - public void synchronizationUnlock() - { + public void synchronizationUnlock() { throw new UnsupportedOperationException(); } @Override - public void forceMoveNextFile() - { + public void forceMoveNextFile() { throw new UnsupportedOperationException(); } @Override - public JournalFile[] getDataFiles() - { + public JournalFile[] getDataFiles() { throw new UnsupportedOperationException(); } @Override - void scheduleReclaim() - { + void scheduleReclaim() { // no-op } @Override - public SequentialFileFactory getFileFactory() - { + public SequentialFileFactory getFileFactory() { throw new UnsupportedOperationException(); } @Override - public void scheduleCompactAndBlock(int timeout) throws Exception - { + public void scheduleCompactAndBlock(int timeout) throws Exception { throw new UnsupportedOperationException(); } @Override - public void replicationSyncPreserveOldFiles() - { + public void replicationSyncPreserveOldFiles() { throw new UnsupportedOperationException(); } @Override - public void replicationSyncFinished() - { + public void replicationSyncFinished() { throw new UnsupportedOperationException(); } } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalBase.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalBase.java index 1ba8f0b7c3..5a844f30f5 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalBase.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalBase.java @@ -23,170 +23,175 @@ import org.apache.activemq.artemis.core.journal.IOCompletion; import org.apache.activemq.artemis.core.journal.Journal; import org.apache.activemq.artemis.core.journal.impl.dataformat.ByteArrayEncoding; -abstract class JournalBase implements Journal -{ +abstract class JournalBase implements Journal { protected final int fileSize; private final boolean supportsCallback; - public JournalBase(boolean supportsCallback, int fileSize) - { - if (fileSize < JournalImpl.MIN_FILE_SIZE) - { + public JournalBase(boolean supportsCallback, int fileSize) { + if (fileSize < JournalImpl.MIN_FILE_SIZE) { throw new IllegalArgumentException("File size cannot be less than " + JournalImpl.MIN_FILE_SIZE + " bytes"); } this.supportsCallback = supportsCallback; this.fileSize = fileSize; } - public abstract void appendAddRecord(final long id, final byte recordType, final EncodingSupport record, - final boolean sync, final IOCompletion callback) throws Exception; + public abstract void appendAddRecord(final long id, + final byte recordType, + final EncodingSupport record, + final boolean sync, + final IOCompletion callback) throws Exception; - public abstract void appendAddRecordTransactional(final long txID, final long id, final byte recordType, + public abstract void appendAddRecordTransactional(final long txID, + final long id, + final byte recordType, final EncodingSupport record) throws Exception; - public abstract void appendCommitRecord(final long txID, final boolean sync, final IOCompletion callback, + public abstract void appendCommitRecord(final long txID, + final boolean sync, + final IOCompletion callback, boolean lineUpContext) throws Exception; - public abstract void appendDeleteRecord(final long id, final boolean sync, final IOCompletion callback) throws Exception; + public abstract void appendDeleteRecord(final long id, + final boolean sync, + final IOCompletion callback) throws Exception; - public abstract void appendDeleteRecordTransactional(final long txID, final long id, final EncodingSupport record) throws Exception; - - public abstract void appendPrepareRecord(final long txID, final EncodingSupport transactionData, final boolean sync, - final IOCompletion callback) throws Exception; - - public abstract void appendUpdateRecord(final long id, final byte recordType, final EncodingSupport record, - final boolean sync, final IOCompletion callback) throws Exception; - - public abstract void appendUpdateRecordTransactional(final long txID, final long id, final byte recordType, + public abstract void appendDeleteRecordTransactional(final long txID, + final long id, final EncodingSupport record) throws Exception; - public abstract void appendRollbackRecord(final long txID, final boolean sync, final IOCompletion callback) throws Exception; + public abstract void appendPrepareRecord(final long txID, + final EncodingSupport transactionData, + final boolean sync, + final IOCompletion callback) throws Exception; + public abstract void appendUpdateRecord(final long id, + final byte recordType, + final EncodingSupport record, + final boolean sync, + final IOCompletion callback) throws Exception; - public void appendAddRecord(long id, byte recordType, byte[] record, boolean sync) throws Exception - { + public abstract void appendUpdateRecordTransactional(final long txID, + final long id, + final byte recordType, + final EncodingSupport record) throws Exception; + + public abstract void appendRollbackRecord(final long txID, + final boolean sync, + final IOCompletion callback) throws Exception; + + public void appendAddRecord(long id, byte recordType, byte[] record, boolean sync) throws Exception { appendAddRecord(id, recordType, new ByteArrayEncoding(record), sync); } - public void appendAddRecord(long id, byte recordType, EncodingSupport record, boolean sync) throws Exception - { + public void appendAddRecord(long id, byte recordType, EncodingSupport record, boolean sync) throws Exception { SyncIOCompletion callback = getSyncCallback(sync); appendAddRecord(id, recordType, record, sync, callback); - if (callback != null) - { + if (callback != null) { callback.waitCompletion(); } } - public void appendCommitRecord(final long txID, final boolean sync) throws Exception - { + public void appendCommitRecord(final long txID, final boolean sync) throws Exception { SyncIOCompletion syncCompletion = getSyncCallback(sync); appendCommitRecord(txID, sync, syncCompletion, true); - if (syncCompletion != null) - { + if (syncCompletion != null) { syncCompletion.waitCompletion(); } } - public void appendCommitRecord(final long txID, final boolean sync, final IOCompletion callback) throws Exception - { + public void appendCommitRecord(final long txID, final boolean sync, final IOCompletion callback) throws Exception { appendCommitRecord(txID, sync, callback, true); } - public void appendUpdateRecord(final long id, final byte recordType, final byte[] record, final boolean sync) throws Exception - { + public void appendUpdateRecord(final long id, + final byte recordType, + final byte[] record, + final boolean sync) throws Exception { appendUpdateRecord(id, recordType, new ByteArrayEncoding(record), sync); } - public void appendUpdateRecordTransactional(final long txID, final long id, final byte recordType, - final byte[] record) throws Exception - { + public void appendUpdateRecordTransactional(final long txID, + final long id, + final byte recordType, + final byte[] record) throws Exception { appendUpdateRecordTransactional(txID, id, recordType, new ByteArrayEncoding(record)); } - public void appendAddRecordTransactional(final long txID, final long id, final byte recordType, final byte[] record) throws Exception - { + public void appendAddRecordTransactional(final long txID, + final long id, + final byte recordType, + final byte[] record) throws Exception { appendAddRecordTransactional(txID, id, recordType, new ByteArrayEncoding(record)); } - public void appendDeleteRecordTransactional(final long txID, final long id) throws Exception - { + public void appendDeleteRecordTransactional(final long txID, final long id) throws Exception { appendDeleteRecordTransactional(txID, id, NullEncoding.instance); } - public void appendPrepareRecord(final long txID, final byte[] transactionData, final boolean sync) throws Exception - { + public void appendPrepareRecord(final long txID, final byte[] transactionData, final boolean sync) throws Exception { appendPrepareRecord(txID, new ByteArrayEncoding(transactionData), sync); } - public void appendPrepareRecord(final long txID, final EncodingSupport transactionData, final boolean sync) throws Exception - { + public void appendPrepareRecord(final long txID, + final EncodingSupport transactionData, + final boolean sync) throws Exception { SyncIOCompletion syncCompletion = getSyncCallback(sync); appendPrepareRecord(txID, transactionData, sync, syncCompletion); - if (syncCompletion != null) - { + if (syncCompletion != null) { syncCompletion.waitCompletion(); } } - public void appendDeleteRecordTransactional(final long txID, final long id, final byte[] record) throws Exception - { + public void appendDeleteRecordTransactional(final long txID, final long id, final byte[] record) throws Exception { appendDeleteRecordTransactional(txID, id, new ByteArrayEncoding(record)); } - public void - appendUpdateRecord(final long id, final byte recordType, final EncodingSupport record, final boolean sync) throws Exception - { + public void appendUpdateRecord(final long id, + final byte recordType, + final EncodingSupport record, + final boolean sync) throws Exception { SyncIOCompletion callback = getSyncCallback(sync); appendUpdateRecord(id, recordType, record, sync, callback); - if (callback != null) - { + if (callback != null) { callback.waitCompletion(); } } - public void appendRollbackRecord(final long txID, final boolean sync) throws Exception - { + public void appendRollbackRecord(final long txID, final boolean sync) throws Exception { SyncIOCompletion syncCompletion = getSyncCallback(sync); appendRollbackRecord(txID, sync, syncCompletion); - if (syncCompletion != null) - { + if (syncCompletion != null) { syncCompletion.waitCompletion(); } } - public void appendDeleteRecord(final long id, final boolean sync) throws Exception - { + public void appendDeleteRecord(final long id, final boolean sync) throws Exception { SyncIOCompletion callback = getSyncCallback(sync); appendDeleteRecord(id, sync, callback); - if (callback != null) - { + if (callback != null) { callback.waitCompletion(); } } abstract void scheduleReclaim(); - protected SyncIOCompletion getSyncCallback(final boolean sync) - { - if (supportsCallback) - { - if (sync) - { + protected SyncIOCompletion getSyncCallback(final boolean sync) { + if (supportsCallback) { + if (sync) { return new SimpleWaitIOCallback(); } return DummyCallback.getInstance(); @@ -194,29 +199,24 @@ abstract class JournalBase implements Journal return null; } - private static final class NullEncoding implements EncodingSupport - { + private static final class NullEncoding implements EncodingSupport { private static NullEncoding instance = new NullEncoding(); - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { // no-op } - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { // no-op } - public int getEncodeSize() - { + public int getEncodeSize() { return 0; } } - public int getFileSize() - { + public int getFileSize() { return fileSize; } } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalCompactor.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalCompactor.java index 1f657a2a6c..0216c19daa 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalCompactor.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalCompactor.java @@ -40,8 +40,8 @@ import org.apache.activemq.artemis.core.journal.impl.dataformat.JournalInternalR import org.apache.activemq.artemis.core.journal.impl.dataformat.JournalRollbackRecordTX; import org.apache.activemq.artemis.journal.ActiveMQJournalLogger; -public class JournalCompactor extends AbstractJournalUpdateTask implements JournalRecordProvider -{ +public class JournalCompactor extends AbstractJournalUpdateTask implements JournalRecordProvider { + // We try to separate old record from new ones when doing the compacting // this is a split line // We will force a moveNextFiles when the compactCount is bellow than COMPACT_SPLIT_LINE @@ -54,58 +54,51 @@ public class JournalCompactor extends AbstractJournalUpdateTask implements Journ private final Map newTransactions = new HashMap(); - /** Commands that happened during compacting - * We can't process any counts during compacting, as we won't know in what files the records are taking place, so - * we cache those updates. As soon as we are done we take the right account. */ + /** + * Commands that happened during compacting + * We can't process any counts during compacting, as we won't know in what files the records are taking place, so + * we cache those updates. As soon as we are done we take the right account. + */ private final LinkedList pendingCommands = new LinkedList(); public static SequentialFile readControlFile(final SequentialFileFactory fileFactory, final List dataFiles, final List newFiles, - final List> renameFile) throws Exception - { + final List> renameFile) throws Exception { SequentialFile controlFile = fileFactory.createSequentialFile(AbstractJournalUpdateTask.FILE_COMPACT_CONTROL); - if (controlFile.exists()) - { + if (controlFile.exists()) { JournalFile file = new JournalFileImpl(controlFile, 0, JournalImpl.FORMAT_VERSION); final ArrayList records = new ArrayList(); - JournalImpl.readJournalFile(fileFactory, file, new JournalReaderCallbackAbstract() - { + JournalImpl.readJournalFile(fileFactory, file, new JournalReaderCallbackAbstract() { @Override - public void onReadAddRecord(final RecordInfo info) throws Exception - { + public void onReadAddRecord(final RecordInfo info) throws Exception { records.add(info); } }); - if (records.size() == 0) - { + if (records.size() == 0) { return null; } - else - { + else { ActiveMQBuffer input = ActiveMQBuffers.wrappedBuffer(records.get(0).data); int numberDataFiles = input.readInt(); - for (int i = 0; i < numberDataFiles; i++) - { + for (int i = 0; i < numberDataFiles; i++) { dataFiles.add(input.readUTF()); } int numberNewFiles = input.readInt(); - for (int i = 0; i < numberNewFiles; i++) - { + for (int i = 0; i < numberNewFiles; i++) { newFiles.add(input.readUTF()); } int numberRenames = input.readInt(); - for (int i = 0; i < numberRenames; i++) - { + for (int i = 0; i < numberRenames; i++) { String from = input.readUTF(); String to = input.readUTF(); renameFile.add(new Pair(from, to)); @@ -115,24 +108,20 @@ public class JournalCompactor extends AbstractJournalUpdateTask implements Journ return controlFile; } - else - { + else { return null; } } - public List getNewDataFiles() - { + public List getNewDataFiles() { return newDataFiles; } - public Map getNewRecords() - { + public Map getNewRecords() { return newRecords; } - public Map getNewTransactions() - { + public Map getNewTransactions() { return newTransactions; } @@ -140,19 +129,18 @@ public class JournalCompactor extends AbstractJournalUpdateTask implements Journ final JournalImpl journal, final JournalFilesRepository filesRepository, final Set recordsSnapshot, - final long firstFileID) - { + final long firstFileID) { super(fileFactory, journal, filesRepository, recordsSnapshot, firstFileID); } - /** This methods informs the Compactor about the existence of a pending (non committed) transaction */ - public void addPendingTransaction(final long transactionID, final long[] ids) - { + /** + * This methods informs the Compactor about the existence of a pending (non committed) transaction + */ + public void addPendingTransaction(final long transactionID, final long[] ids) { pendingTransactions.put(transactionID, new PendingTransaction(ids)); } - public void addCommandCommit(final JournalTransaction liveTransaction, final JournalFile currentFile) - { + public void addCommandCommit(final JournalTransaction liveTransaction, final JournalFile currentFile) { pendingCommands.add(new CommitCompactCommand(liveTransaction, currentFile)); long[] ids = liveTransaction.getPositiveArray(); @@ -160,32 +148,26 @@ public class JournalCompactor extends AbstractJournalUpdateTask implements Journ PendingTransaction oldTransaction = pendingTransactions.get(liveTransaction.getId()); long[] ids2 = null; - if (oldTransaction != null) - { + if (oldTransaction != null) { ids2 = oldTransaction.pendingIDs; } /** If a delete comes for these records, while the compactor still working, we need to be able to take them into account for later deletes * instead of throwing exceptions about non existent records */ - if (ids != null) - { - for (long id : ids) - { + if (ids != null) { + for (long id : ids) { addToRecordsSnaptshot(id); } } - if (ids2 != null) - { - for (long id : ids2) - { + if (ids2 != null) { + for (long id : ids2) { addToRecordsSnaptshot(id); } } } - public void addCommandRollback(final JournalTransaction liveTransaction, final JournalFile currentFile) - { + public void addCommandRollback(final JournalTransaction liveTransaction, final JournalFile currentFile) { pendingCommands.add(new RollbackCompactCommand(liveTransaction, currentFile)); } @@ -193,8 +175,7 @@ public class JournalCompactor extends AbstractJournalUpdateTask implements Journ * @param id * @param usedFile */ - public void addCommandDelete(final long id, final JournalFile usedFile) - { + public void addCommandDelete(final long id, final JournalFile usedFile) { pendingCommands.add(new DeleteCompactCommand(id, usedFile)); } @@ -202,40 +183,31 @@ public class JournalCompactor extends AbstractJournalUpdateTask implements Journ * @param id * @param usedFile */ - public void addCommandUpdate(final long id, final JournalFile usedFile, final int size) - { + public void addCommandUpdate(final long id, final JournalFile usedFile, final int size) { pendingCommands.add(new UpdateCompactCommand(id, usedFile, size)); } - private void checkSize(final int size) throws Exception - { + private void checkSize(final int size) throws Exception { checkSize(size, -1); } - private void checkSize(final int size, final int compactCount) throws Exception - { - if (getWritingChannel() == null) - { - if (!checkCompact(compactCount)) - { + private void checkSize(final int size, final int compactCount) throws Exception { + if (getWritingChannel() == null) { + if (!checkCompact(compactCount)) { // will need to open a file either way openFile(); } } - else - { - if (compactCount >= 0) - { - if (checkCompact(compactCount)) - { + else { + if (compactCount >= 0) { + if (checkCompact(compactCount)) { // The file was already moved on this case, no need to check for the size. // otherwise we will also need to check for the size return; } } - if (getWritingChannel().writerIndex() + size > getWritingChannel().capacity()) - { + if (getWritingChannel().writerIndex() + size > getWritingChannel().capacity()) { openFile(); } } @@ -248,22 +220,18 @@ public class JournalCompactor extends AbstractJournalUpdateTask implements Journ boolean splitted = false; - private boolean checkCompact(final int compactCount) throws Exception - { - if (compactCount >= COMPACT_SPLIT_LINE && !splitted) - { + private boolean checkCompact(final int compactCount) throws Exception { + if (compactCount >= COMPACT_SPLIT_LINE && !splitted) { willNeedToSplit = true; } - if (willNeedToSplit && compactCount < COMPACT_SPLIT_LINE) - { + if (willNeedToSplit && compactCount < COMPACT_SPLIT_LINE) { willNeedToSplit = false; splitted = false; openFile(); return true; } - else - { + else { return false; } } @@ -271,16 +239,12 @@ public class JournalCompactor extends AbstractJournalUpdateTask implements Journ /** * Replay pending counts that happened during compacting */ - public void replayPendingCommands() - { - for (CompactCommand command : pendingCommands) - { - try - { + public void replayPendingCommands() { + for (CompactCommand command : pendingCommands) { + try { command.execute(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQJournalLogger.LOGGER.errorReplayingCommands(e); } } @@ -290,15 +254,10 @@ public class JournalCompactor extends AbstractJournalUpdateTask implements Journ // JournalReaderCallback implementation ------------------------------------------- - public void onReadAddRecord(final RecordInfo info) throws Exception - { - if (lookupRecord(info.id)) - { - JournalInternalRecord addRecord = new JournalAddRecord(true, - info.id, - info.getUserRecordType(), - new ByteArrayEncoding(info.data)); - addRecord.setCompactCount((short)(info.compactCount + 1)); + public void onReadAddRecord(final RecordInfo info) throws Exception { + if (lookupRecord(info.id)) { + JournalInternalRecord addRecord = new JournalAddRecord(true, info.id, info.getUserRecordType(), new ByteArrayEncoding(info.data)); + addRecord.setCompactCount((short) (info.compactCount + 1)); checkSize(addRecord.getEncodeSize(), info.compactCount); @@ -308,19 +267,13 @@ public class JournalCompactor extends AbstractJournalUpdateTask implements Journ } } - public void onReadAddRecordTX(final long transactionID, final RecordInfo info) throws Exception - { - if (pendingTransactions.get(transactionID) != null || lookupRecord(info.id)) - { + public void onReadAddRecordTX(final long transactionID, final RecordInfo info) throws Exception { + if (pendingTransactions.get(transactionID) != null || lookupRecord(info.id)) { JournalTransaction newTransaction = getNewJournalTransaction(transactionID); - JournalInternalRecord record = new JournalAddRecordTX(true, - transactionID, - info.id, - info.getUserRecordType(), - new ByteArrayEncoding(info.data)); + JournalInternalRecord record = new JournalAddRecordTX(true, transactionID, info.id, info.getUserRecordType(), new ByteArrayEncoding(info.data)); - record.setCompactCount((short)(info.compactCount + 1)); + record.setCompactCount((short) (info.compactCount + 1)); checkSize(record.getEncodeSize(), info.compactCount); @@ -330,21 +283,16 @@ public class JournalCompactor extends AbstractJournalUpdateTask implements Journ } } - public void onReadCommitRecord(final long transactionID, final int numberOfRecords) throws Exception - { + public void onReadCommitRecord(final long transactionID, final int numberOfRecords) throws Exception { - if (pendingTransactions.get(transactionID) != null) - { + if (pendingTransactions.get(transactionID) != null) { // Sanity check, this should never happen ActiveMQJournalLogger.LOGGER.inconsistencyDuringCompacting(transactionID); } - else - { + else { JournalTransaction newTransaction = newTransactions.remove(transactionID); - if (newTransaction != null) - { - JournalInternalRecord commitRecord = - new JournalCompleteRecordTX(TX_RECORD_TYPE.COMMIT, transactionID, null); + if (newTransaction != null) { + JournalInternalRecord commitRecord = new JournalCompleteRecordTX(TX_RECORD_TYPE.COMMIT, transactionID, null); checkSize(commitRecord.getEncodeSize()); @@ -355,25 +303,19 @@ public class JournalCompactor extends AbstractJournalUpdateTask implements Journ } } - public void onReadDeleteRecord(final long recordID) throws Exception - { - if (newRecords.get(recordID) != null) - { + public void onReadDeleteRecord(final long recordID) throws Exception { + if (newRecords.get(recordID) != null) { // Sanity check, it should never happen ActiveMQJournalLogger.LOGGER.inconsistencyDuringCompactingDelete(recordID); } } - public void onReadDeleteRecordTX(final long transactionID, final RecordInfo info) throws Exception - { - if (pendingTransactions.get(transactionID) != null) - { + public void onReadDeleteRecordTX(final long transactionID, final RecordInfo info) throws Exception { + if (pendingTransactions.get(transactionID) != null) { JournalTransaction newTransaction = getNewJournalTransaction(transactionID); - JournalInternalRecord record = new JournalDeleteRecordTX(transactionID, - info.id, - new ByteArrayEncoding(info.data)); + JournalInternalRecord record = new JournalDeleteRecordTX(transactionID, info.id, new ByteArrayEncoding(info.data)); checkSize(record.getEncodeSize()); @@ -384,20 +326,18 @@ public class JournalCompactor extends AbstractJournalUpdateTask implements Journ // else.. nothing to be done } - public void markAsDataFile(final JournalFile file) - { + public void markAsDataFile(final JournalFile file) { // nothing to be done here } - public void onReadPrepareRecord(final long transactionID, final byte[] extraData, final int numberOfRecords) throws Exception - { - if (pendingTransactions.get(transactionID) != null) - { + public void onReadPrepareRecord(final long transactionID, + final byte[] extraData, + final int numberOfRecords) throws Exception { + if (pendingTransactions.get(transactionID) != null) { JournalTransaction newTransaction = getNewJournalTransaction(transactionID); - JournalInternalRecord prepareRecord = - new JournalCompleteRecordTX(TX_RECORD_TYPE.PREPARE, transactionID, new ByteArrayEncoding(extraData)); + JournalInternalRecord prepareRecord = new JournalCompleteRecordTX(TX_RECORD_TYPE.PREPARE, transactionID, new ByteArrayEncoding(extraData)); checkSize(prepareRecord.getEncodeSize()); @@ -408,19 +348,15 @@ public class JournalCompactor extends AbstractJournalUpdateTask implements Journ } } - public void onReadRollbackRecord(final long transactionID) throws Exception - { - if (pendingTransactions.get(transactionID) != null) - { + public void onReadRollbackRecord(final long transactionID) throws Exception { + if (pendingTransactions.get(transactionID) != null) { // Sanity check, this should never happen throw new IllegalStateException("Inconsistency during compacting: RollbackRecord ID = " + transactionID + - " for an already rolled back transaction during compacting"); + " for an already rolled back transaction during compacting"); } - else - { + else { JournalTransaction newTransaction = newTransactions.remove(transactionID); - if (newTransaction != null) - { + if (newTransaction != null) { JournalInternalRecord rollbackRecord = new JournalRollbackRecordTX(transactionID); @@ -434,27 +370,20 @@ public class JournalCompactor extends AbstractJournalUpdateTask implements Journ } } - public void onReadUpdateRecord(final RecordInfo info) throws Exception - { - if (lookupRecord(info.id)) - { - JournalInternalRecord updateRecord = new JournalAddRecord(false, - info.id, - info.userRecordType, - new ByteArrayEncoding(info.data)); + public void onReadUpdateRecord(final RecordInfo info) throws Exception { + if (lookupRecord(info.id)) { + JournalInternalRecord updateRecord = new JournalAddRecord(false, info.id, info.userRecordType, new ByteArrayEncoding(info.data)); - updateRecord.setCompactCount((short)(info.compactCount + 1)); + updateRecord.setCompactCount((short) (info.compactCount + 1)); checkSize(updateRecord.getEncodeSize(), info.compactCount); JournalRecord newRecord = newRecords.get(info.id); - if (newRecord == null) - { + if (newRecord == null) { ActiveMQJournalLogger.LOGGER.compactingWithNoAddRecord(info.id); } - else - { + else { newRecord.addUpdateFile(currentFile, updateRecord.getEncodeSize()); } @@ -462,19 +391,13 @@ public class JournalCompactor extends AbstractJournalUpdateTask implements Journ } } - public void onReadUpdateRecordTX(final long transactionID, final RecordInfo info) throws Exception - { - if (pendingTransactions.get(transactionID) != null || lookupRecord(info.id)) - { + public void onReadUpdateRecordTX(final long transactionID, final RecordInfo info) throws Exception { + if (pendingTransactions.get(transactionID) != null || lookupRecord(info.id)) { JournalTransaction newTransaction = getNewJournalTransaction(transactionID); - JournalInternalRecord updateRecordTX = new JournalAddRecordTX(false, - transactionID, - info.id, - info.userRecordType, - new ByteArrayEncoding(info.data)); + JournalInternalRecord updateRecordTX = new JournalAddRecordTX(false, transactionID, info.id, info.userRecordType, new ByteArrayEncoding(info.data)); - updateRecordTX.setCompactCount((short)(info.compactCount + 1)); + updateRecordTX.setCompactCount((short) (info.compactCount + 1)); checkSize(updateRecordTX.getEncodeSize(), info.compactCount); @@ -482,8 +405,7 @@ public class JournalCompactor extends AbstractJournalUpdateTask implements Journ newTransaction.addPositive(currentFile, info.id, updateRecordTX.getEncodeSize()); } - else - { + else { onReadUpdateRecord(info); } } @@ -492,102 +414,92 @@ public class JournalCompactor extends AbstractJournalUpdateTask implements Journ * @param transactionID * @return */ - private JournalTransaction getNewJournalTransaction(final long transactionID) - { + private JournalTransaction getNewJournalTransaction(final long transactionID) { JournalTransaction newTransaction = newTransactions.get(transactionID); - if (newTransaction == null) - { + if (newTransaction == null) { newTransaction = new JournalTransaction(transactionID, this); newTransactions.put(transactionID, newTransaction); } return newTransaction; } - private abstract static class CompactCommand - { + private abstract static class CompactCommand { + abstract void execute() throws Exception; } - private class DeleteCompactCommand extends CompactCommand - { + private class DeleteCompactCommand extends CompactCommand { + long id; JournalFile usedFile; - public DeleteCompactCommand(final long id, final JournalFile usedFile) - { + public DeleteCompactCommand(final long id, final JournalFile usedFile) { this.id = id; this.usedFile = usedFile; } @Override - void execute() throws Exception - { + void execute() throws Exception { JournalRecord deleteRecord = journal.getRecords().remove(id); - if (deleteRecord == null) - { + if (deleteRecord == null) { ActiveMQJournalLogger.LOGGER.noRecordDuringCompactReplay(id); } - else - { + else { deleteRecord.delete(usedFile); } } } - private static class PendingTransaction - { + private static class PendingTransaction { + long[] pendingIDs; - PendingTransaction(final long[] ids) - { + PendingTransaction(final long[] ids) { pendingIDs = ids; } } - private class UpdateCompactCommand extends CompactCommand - { + private class UpdateCompactCommand extends CompactCommand { + private final long id; private final JournalFile usedFile; private final int size; - public UpdateCompactCommand(final long id, final JournalFile usedFile, final int size) - { + public UpdateCompactCommand(final long id, final JournalFile usedFile, final int size) { this.id = id; this.usedFile = usedFile; this.size = size; } @Override - void execute() throws Exception - { + void execute() throws Exception { JournalRecord updateRecord = journal.getRecords().get(id); updateRecord.addUpdateFile(usedFile, size); } } - private class CommitCompactCommand extends CompactCommand - { + private class CommitCompactCommand extends CompactCommand { + private final JournalTransaction liveTransaction; - /** File containing the commit record */ + /** + * File containing the commit record + */ private final JournalFile commitFile; - public CommitCompactCommand(final JournalTransaction liveTransaction, final JournalFile commitFile) - { + public CommitCompactCommand(final JournalTransaction liveTransaction, final JournalFile commitFile) { this.liveTransaction = liveTransaction; this.commitFile = commitFile; } @Override - void execute() throws Exception - { + void execute() throws Exception { JournalTransaction newTransaction = newTransactions.get(liveTransaction.getId()); - if (newTransaction != null) - { + if (newTransaction != null) { liveTransaction.merge(newTransaction); liveTransaction.commit(commitFile); } @@ -595,25 +507,24 @@ public class JournalCompactor extends AbstractJournalUpdateTask implements Journ } } - private class RollbackCompactCommand extends CompactCommand - { + private class RollbackCompactCommand extends CompactCommand { + private final JournalTransaction liveTransaction; - /** File containing the commit record */ + /** + * File containing the commit record + */ private final JournalFile rollbackFile; - public RollbackCompactCommand(final JournalTransaction liveTransaction, final JournalFile rollbackFile) - { + public RollbackCompactCommand(final JournalTransaction liveTransaction, final JournalFile rollbackFile) { this.liveTransaction = liveTransaction; this.rollbackFile = rollbackFile; } @Override - void execute() throws Exception - { + void execute() throws Exception { JournalTransaction newTransaction = newTransactions.get(liveTransaction.getId()); - if (newTransaction != null) - { + if (newTransaction != null) { liveTransaction.merge(newTransaction); liveTransaction.rollback(rollbackFile); } @@ -622,14 +533,12 @@ public class JournalCompactor extends AbstractJournalUpdateTask implements Journ } @Override - public JournalCompactor getCompactor() - { + public JournalCompactor getCompactor() { return null; } @Override - public Map getRecords() - { + public Map getRecords() { return newRecords; } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalConstants.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalConstants.java index 8bc20c77a7..257065a85f 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalConstants.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalConstants.java @@ -16,12 +16,11 @@ */ package org.apache.activemq.artemis.core.journal.impl; -public final class JournalConstants -{ +public final class JournalConstants { public static final int DEFAULT_JOURNAL_BUFFER_SIZE_AIO = 490 * 1024; - public static final int DEFAULT_JOURNAL_BUFFER_TIMEOUT_AIO = (int)(1000000000d / 2000); - public static final int DEFAULT_JOURNAL_BUFFER_TIMEOUT_NIO = (int)(1000000000d / 300); + public static final int DEFAULT_JOURNAL_BUFFER_TIMEOUT_AIO = (int) (1000000000d / 2000); + public static final int DEFAULT_JOURNAL_BUFFER_TIMEOUT_NIO = (int) (1000000000d / 300); public static final int DEFAULT_JOURNAL_BUFFER_SIZE_NIO = 490 * 1024; } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalFile.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalFile.java index dcfc1a2535..83b3cf8b03 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalFile.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalFile.java @@ -18,8 +18,8 @@ package org.apache.activemq.artemis.core.journal.impl; import org.apache.activemq.artemis.core.io.SequentialFile; -public interface JournalFile -{ +public interface JournalFile { + int getNegCount(JournalFile file); void incNegCount(JournalFile file); @@ -36,24 +36,30 @@ public interface JournalFile int getLiveSize(); - /** The total number of deletes this file has */ + /** + * The total number of deletes this file has + */ int getTotalNegativeToOthers(); /** * Whether this file's contents can deleted and the file reused. + * * @param canDelete if {@code true} then this file's contents are unimportant and may be deleted - * at any time. + * at any time. */ void setCanReclaim(boolean canDelete); /** * Whether this file's contents can deleted and the file reused. + * * @return {@code true} if the file can already be deleted. */ boolean isCanReclaim(); - /** This is a field to identify that records on this file actually belong to the current file. - * The possible implementation for this is fileID & Integer.MAX_VALUE */ + /** + * This is a field to identify that records on this file actually belong to the current file. + * The possible implementation for this is fileID & Integer.MAX_VALUE + */ int getRecordID(); long getFileID(); diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalFileImpl.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalFileImpl.java index 7e96575ff3..4cc23f1347 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalFileImpl.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalFileImpl.java @@ -23,8 +23,8 @@ import java.util.concurrent.atomic.AtomicInteger; import org.apache.activemq.artemis.core.io.SequentialFile; -public class JournalFileImpl implements JournalFile -{ +public class JournalFileImpl implements JournalFile { + private final SequentialFile file; private final long fileID; @@ -45,130 +45,108 @@ public class JournalFileImpl implements JournalFile private final Map negCounts = new ConcurrentHashMap(); - public JournalFileImpl(final SequentialFile file, final long fileID, final int version) - { + public JournalFileImpl(final SequentialFile file, final long fileID, final int version) { this.file = file; this.fileID = fileID; this.version = version; - recordID = (int)(fileID & Integer.MAX_VALUE); + recordID = (int) (fileID & Integer.MAX_VALUE); } - public int getPosCount() - { + public int getPosCount() { return posCount.intValue(); } @Override - public boolean isCanReclaim() - { + public boolean isCanReclaim() { return canReclaim; } @Override - public void setCanReclaim(final boolean canReclaim) - { + public void setCanReclaim(final boolean canReclaim) { this.canReclaim = canReclaim; } - public void incNegCount(final JournalFile file) - { - if (file != this) - { + public void incNegCount(final JournalFile file) { + if (file != this) { totalNegativeToOthers.incrementAndGet(); } getOrCreateNegCount(file).incrementAndGet(); } - public int getNegCount(final JournalFile file) - { + public int getNegCount(final JournalFile file) { AtomicInteger count = negCounts.get(file); - if (count == null) - { + if (count == null) { return 0; } - else - { + else { return count.intValue(); } } - public int getJournalVersion() - { + public int getJournalVersion() { return version; } - public void incPosCount() - { + public void incPosCount() { posCount.incrementAndGet(); } - public void decPosCount() - { + public void decPosCount() { posCount.decrementAndGet(); } - public long getOffset() - { + public long getOffset() { return offset; } - public long getFileID() - { + public long getFileID() { return fileID; } - public int getRecordID() - { + public int getRecordID() { return recordID; } - public void setOffset(final long offset) - { + public void setOffset(final long offset) { this.offset = offset; } - public SequentialFile getFile() - { + public SequentialFile getFile() { return file; } @Override - public String toString() - { - try - { + public String toString() { + try { return "JournalFileImpl: (" + file.getFileName() + " id = " + fileID + ", recordID = " + recordID + ")"; } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); return "Error:" + e.toString(); } } - /** Receive debug information about the journal */ - public String debug() - { + /** + * Receive debug information about the journal + */ + public String debug() { StringBuilder builder = new StringBuilder(); - for (Entry entry : negCounts.entrySet()) - { + for (Entry entry : negCounts.entrySet()) { builder.append(" file = " + entry.getKey() + " negcount value = " + entry.getValue() + "\n"); } return builder.toString(); } - private synchronized AtomicInteger getOrCreateNegCount(final JournalFile file) - { + private synchronized AtomicInteger getOrCreateNegCount(final JournalFile file) { AtomicInteger count = negCounts.get(file); - if (count == null) - { + if (count == null) { count = new AtomicInteger(); negCounts.put(file, count); } @@ -177,25 +155,21 @@ public class JournalFileImpl implements JournalFile } @Override - public void addSize(final int bytes) - { + public void addSize(final int bytes) { liveBytes.addAndGet(bytes); } @Override - public void decSize(final int bytes) - { + public void decSize(final int bytes) { liveBytes.addAndGet(-bytes); } @Override - public int getLiveSize() - { + public int getLiveSize() { return liveBytes.get(); } - public int getTotalNegativeToOthers() - { + public int getTotalNegativeToOthers() { return totalNegativeToOthers.get(); } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalFilesRepository.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalFilesRepository.java index 268a23d8c3..a837dd3bd1 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalFilesRepository.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalFilesRepository.java @@ -39,8 +39,8 @@ import org.apache.activemq.artemis.journal.ActiveMQJournalLogger; * This is a helper class for the Journal, which will control access to dataFiles, openedFiles and freeFiles * Guaranteeing that they will be delivered in order to the Journal */ -public class JournalFilesRepository -{ +public class JournalFilesRepository { + private static final boolean trace = ActiveMQJournalLogger.LOGGER.isTraceEnabled(); /** @@ -53,8 +53,7 @@ public class JournalFilesRepository // This method exists just to make debug easier. // I could replace log.trace by log.info temporarily while I was debugging // Journal - private static void trace(final String message) - { + private static void trace(final String message) { ActiveMQJournalLogger.LOGGER.trace(message); } @@ -86,16 +85,12 @@ public class JournalFilesRepository private Executor openFilesExecutor; - private final Runnable pushOpenRunnable = new Runnable() - { - public void run() - { - try - { + private final Runnable pushOpenRunnable = new Runnable() { + public void run() { + try { pushOpenedFile(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQJournalLogger.LOGGER.errorPushingFile(e); } } @@ -108,18 +103,14 @@ public class JournalFilesRepository final int userVersion, final int maxAIO, final int fileSize, - final int minFiles) - { - if (filePrefix == null) - { + final int minFiles) { + if (filePrefix == null) { throw new IllegalArgumentException("filePrefix cannot be null"); } - if (fileExtension == null) - { + if (fileExtension == null) { throw new IllegalArgumentException("fileExtension cannot be null"); } - if (maxAIO <= 0) - { + if (maxAIO <= 0) { throw new IllegalArgumentException("maxAIO must be a positive number"); } this.fileFactory = fileFactory; @@ -134,53 +125,43 @@ public class JournalFilesRepository // Public -------------------------------------------------------- - public void setExecutor(final Executor fileExecutor) - { + public void setExecutor(final Executor fileExecutor) { this.openFilesExecutor = fileExecutor; } - public void clear() throws Exception - { + public void clear() throws Exception { dataFiles.clear(); freeFiles.clear(); freeFilesCount.set(0); - for (JournalFile file : openedFiles) - { - try - { + for (JournalFile file : openedFiles) { + try { file.getFile().close(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQJournalLogger.LOGGER.errorClosingFile(e); } } openedFiles.clear(); } - public int getMaxAIO() - { + public int getMaxAIO() { return maxAIO; } - public String getFileExtension() - { + public String getFileExtension() { return fileExtension; } - public String getFilePrefix() - { + public String getFilePrefix() { return filePrefix; } - public void calculateNextfileID(final List files) - { + public void calculateNextfileID(final List files) { - for (JournalFile file : files) - { + for (JournalFile file : files) { final long fileIdFromFile = file.getFileID(); final long fileIdFromName = getFileNameID(file.getFile().getFileName()); @@ -199,10 +180,8 @@ public class JournalFilesRepository * * @param targetUpdate */ - public void setNextFileID(final long targetUpdate) - { - while (true) - { + public void setNextFileID(final long targetUpdate) { + while (true) { final long current = nextFileID.get(); if (current >= targetUpdate) return; @@ -212,14 +191,11 @@ public class JournalFilesRepository } } - public void ensureMinFiles() throws Exception - { + public void ensureMinFiles() throws Exception { int filesToCreate = minFiles - (dataFiles.size() + freeFilesCount.get()); - if (filesToCreate > 0) - { - for (int i = 0; i < filesToCreate; i++) - { + if (filesToCreate > 0) { + for (int i = 0; i < filesToCreate; i++) { // Keeping all files opened can be very costly (mainly on AIO) freeFiles.add(createFile(false, false, true, false, -1)); freeFilesCount.getAndIncrement(); @@ -228,14 +204,11 @@ public class JournalFilesRepository } - public void openFile(final JournalFile file, final boolean multiAIO) throws Exception - { - if (multiAIO) - { + public void openFile(final JournalFile file, final boolean multiAIO) throws Exception { + if (multiAIO) { file.getFile().open(); } - else - { + else { file.getFile().open(1, false); } @@ -244,92 +217,74 @@ public class JournalFilesRepository // Data File Operations ========================================== - public JournalFile[] getDataFilesArray() - { + public JournalFile[] getDataFilesArray() { return dataFiles.toArray(new JournalFile[dataFiles.size()]); } - public JournalFile pollLastDataFile() - { + public JournalFile pollLastDataFile() { return dataFiles.pollLast(); } - public void removeDataFile(final JournalFile file) - { - if (!dataFiles.remove(file)) - { + public void removeDataFile(final JournalFile file) { + if (!dataFiles.remove(file)) { ActiveMQJournalLogger.LOGGER.couldNotRemoveFile(file); } } - public int getDataFilesCount() - { + public int getDataFilesCount() { return dataFiles.size(); } - public Collection getDataFiles() - { + public Collection getDataFiles() { return dataFiles; } - public void clearDataFiles() - { + public void clearDataFiles() { dataFiles.clear(); } - public void addDataFileOnTop(final JournalFile file) - { + public void addDataFileOnTop(final JournalFile file) { dataFiles.addFirst(file); - if (CHECK_CONSISTENCE) - { + if (CHECK_CONSISTENCE) { checkDataFiles(); } } - public String debugFiles() - { + public String debugFiles() { StringBuilder buffer = new StringBuilder(); buffer.append("**********\nCurrent File = " + journal.getCurrentFile() + "\n"); buffer.append("**********\nDataFiles:\n"); - for (JournalFile file : dataFiles) - { + for (JournalFile file : dataFiles) { buffer.append(file.toString() + "\n"); } buffer.append("*********\nFreeFiles:\n"); - for (JournalFile file : freeFiles) - { + for (JournalFile file : freeFiles) { buffer.append(file.toString() + "\n"); } return buffer.toString(); } - public synchronized void checkDataFiles() - { + public synchronized void checkDataFiles() { long seq = -1; - for (JournalFile file : dataFiles) - { - if (file.getFileID() <= seq) - { + for (JournalFile file : dataFiles) { + if (file.getFileID() <= seq) { ActiveMQJournalLogger.LOGGER.checkFiles(); ActiveMQJournalLogger.LOGGER.info(debugFiles()); ActiveMQJournalLogger.LOGGER.seqOutOfOrder(); System.exit(-1); } - if (journal.getCurrentFile() != null && journal.getCurrentFile().getFileID() <= file.getFileID()) - { + if (journal.getCurrentFile() != null && journal.getCurrentFile().getFileID() <= file.getFileID()) { ActiveMQJournalLogger.LOGGER.checkFiles(); ActiveMQJournalLogger.LOGGER.info(debugFiles()); - ActiveMQJournalLogger.LOGGER.currentFile(file.getFileID(), journal.getCurrentFile().getFileID(), - file.getFileID(), (journal.getCurrentFile() == file)); + ActiveMQJournalLogger.LOGGER.currentFile(file.getFileID(), journal.getCurrentFile().getFileID(), file.getFileID(), (journal.getCurrentFile() == file)); // throw new RuntimeException ("Check failure!"); } - if (journal.getCurrentFile() == file) - { + if (journal.getCurrentFile() == file) { throw new RuntimeException("Check failure! Current file listed as data file!"); } @@ -337,10 +292,8 @@ public class JournalFilesRepository } long lastFreeId = -1; - for (JournalFile file : freeFiles) - { - if (file.getFileID() <= lastFreeId) - { + for (JournalFile file : freeFiles) { + if (file.getFileID() <= lastFreeId) { ActiveMQJournalLogger.LOGGER.checkFiles(); ActiveMQJournalLogger.LOGGER.info(debugFiles()); ActiveMQJournalLogger.LOGGER.fileIdOutOfOrder(); @@ -350,8 +303,7 @@ public class JournalFilesRepository lastFreeId = file.getFileID(); - if (file.getFileID() < seq) - { + if (file.getFileID() < seq) { ActiveMQJournalLogger.LOGGER.checkFiles(); ActiveMQJournalLogger.LOGGER.info(debugFiles()); ActiveMQJournalLogger.LOGGER.fileTooSmall(); @@ -361,20 +313,17 @@ public class JournalFilesRepository } } - public void addDataFileOnBottom(final JournalFile file) - { + public void addDataFileOnBottom(final JournalFile file) { dataFiles.add(file); - if (CHECK_CONSISTENCE) - { + if (CHECK_CONSISTENCE) { checkDataFiles(); } } // Free File Operations ========================================== - public int getFreeFilesCount() - { + public int getFreeFilesCount() { return freeFilesCount.get(); } @@ -382,8 +331,7 @@ public class JournalFilesRepository * @param file * @throws Exception */ - public synchronized void addFreeFile(final JournalFile file, final boolean renameTmp) throws Exception - { + public synchronized void addFreeFile(final JournalFile file, final boolean renameTmp) throws Exception { addFreeFile(file, renameTmp, true); } @@ -393,73 +341,62 @@ public class JournalFilesRepository * @param checkDelete - should delete the file if max condition has been met * @throws Exception */ - public synchronized void addFreeFile(final JournalFile file, final boolean renameTmp, final boolean checkDelete) throws Exception - { + public synchronized void addFreeFile(final JournalFile file, + final boolean renameTmp, + final boolean checkDelete) throws Exception { long calculatedSize = 0; - try - { + try { calculatedSize = file.getFile().size(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); System.out.println("Can't get file size on " + file); System.exit(-1); } - if (calculatedSize != fileSize) - { + if (calculatedSize != fileSize) { ActiveMQJournalLogger.LOGGER.deletingFile(file); file.getFile().delete(); } - else - if (!checkDelete || (freeFilesCount.get() + dataFiles.size() + 1 + openedFiles.size() < minFiles)) - { - // Re-initialise it + else if (!checkDelete || (freeFilesCount.get() + dataFiles.size() + 1 + openedFiles.size() < minFiles)) { + // Re-initialise it - if (JournalFilesRepository.trace) - { - JournalFilesRepository.trace("Adding free file " + file); - } - - JournalFile jf = reinitializeFile(file); - - if (renameTmp) - { - jf.getFile().renameTo(JournalImpl.renameExtensionFile(jf.getFile().getFileName(), ".tmp")); - } - - freeFiles.add(jf); - freeFilesCount.getAndIncrement(); - } - else - { - if (trace) - { - ActiveMQJournalLogger.LOGGER.trace("DataFiles.size() = " + dataFiles.size()); - ActiveMQJournalLogger.LOGGER.trace("openedFiles.size() = " + openedFiles.size()); - ActiveMQJournalLogger.LOGGER.trace("minfiles = " + minFiles); - ActiveMQJournalLogger.LOGGER.trace("Free Files = " + freeFilesCount.get()); - ActiveMQJournalLogger.LOGGER.trace("File " + file + - " being deleted as freeFiles.size() + dataFiles.size() + 1 + openedFiles.size() (" + - (freeFilesCount.get() + dataFiles.size() + 1 + openedFiles.size()) + - ") < minFiles (" + minFiles + ")"); - } - file.getFile().delete(); + if (JournalFilesRepository.trace) { + JournalFilesRepository.trace("Adding free file " + file); } - if (CHECK_CONSISTENCE) - { + JournalFile jf = reinitializeFile(file); + + if (renameTmp) { + jf.getFile().renameTo(JournalImpl.renameExtensionFile(jf.getFile().getFileName(), ".tmp")); + } + + freeFiles.add(jf); + freeFilesCount.getAndIncrement(); + } + else { + if (trace) { + ActiveMQJournalLogger.LOGGER.trace("DataFiles.size() = " + dataFiles.size()); + ActiveMQJournalLogger.LOGGER.trace("openedFiles.size() = " + openedFiles.size()); + ActiveMQJournalLogger.LOGGER.trace("minfiles = " + minFiles); + ActiveMQJournalLogger.LOGGER.trace("Free Files = " + freeFilesCount.get()); + ActiveMQJournalLogger.LOGGER.trace("File " + file + + " being deleted as freeFiles.size() + dataFiles.size() + 1 + openedFiles.size() (" + + (freeFilesCount.get() + dataFiles.size() + 1 + openedFiles.size()) + + ") < minFiles (" + minFiles + ")"); + } + file.getFile().delete(); + } + + if (CHECK_CONSISTENCE) { checkDataFiles(); } } - public Collection getFreeFiles() - { + public Collection getFreeFiles() { return freeFiles; } - public JournalFile getFreeFile() - { + public JournalFile getFreeFile() { JournalFile file = freeFiles.remove(); freeFilesCount.getAndDecrement(); return file; @@ -467,8 +404,7 @@ public class JournalFilesRepository // Opened files operations ======================================= - public int getOpenedFilesCount() - { + public int getOpenedFilesCount() { return openedFiles.size(); } @@ -477,35 +413,28 @@ public class JournalFilesRepository *

    In case there are no cached opened files, this method will block until the file was opened, * what would happen only if the system is under heavy load by another system (like a backup system, or a DB sharing the same box as ActiveMQ).

    */ - public JournalFile openFile() throws InterruptedException - { - if (JournalFilesRepository.trace) - { + public JournalFile openFile() throws InterruptedException { + if (JournalFilesRepository.trace) { JournalFilesRepository.trace("enqueueOpenFile with openedFiles.size=" + openedFiles.size()); } - if (openFilesExecutor == null) - { + if (openFilesExecutor == null) { pushOpenRunnable.run(); } - else - { + else { openFilesExecutor.execute(pushOpenRunnable); } JournalFile nextFile = null; - while (nextFile == null) - { + while (nextFile == null) { nextFile = openedFiles.poll(5, TimeUnit.SECONDS); - if (nextFile == null) - { + if (nextFile == null) { ActiveMQJournalLogger.LOGGER.errorOpeningFile(new Exception("trace")); } } - if (JournalFilesRepository.trace) - { + if (JournalFilesRepository.trace) { JournalFilesRepository.trace("Returning file " + nextFile); } @@ -515,23 +444,19 @@ public class JournalFilesRepository /** * Open a file and place it into the openedFiles queue */ - public void pushOpenedFile() throws Exception - { + public void pushOpenedFile() throws Exception { JournalFile nextOpenedFile = takeFile(true, true, true, false); - if (JournalFilesRepository.trace) - { + if (JournalFilesRepository.trace) { JournalFilesRepository.trace("pushing openFile " + nextOpenedFile); } - if (!openedFiles.offer(nextOpenedFile)) - { + if (!openedFiles.offer(nextOpenedFile)) { ActiveMQJournalLogger.LOGGER.failedToAddFile(nextOpenedFile); } } - public void closeFile(final JournalFile file) throws Exception - { + public void closeFile(final JournalFile file) throws Exception { fileFactory.deactivateBuffer(); file.getFile().close(); dataFiles.add(file); @@ -547,31 +472,25 @@ public class JournalFilesRepository public JournalFile takeFile(final boolean keepOpened, final boolean multiAIO, final boolean initFile, - final boolean tmpCompactExtension) throws Exception - { + final boolean tmpCompactExtension) throws Exception { JournalFile nextFile = null; nextFile = freeFiles.poll(); - if (nextFile != null) - { + if (nextFile != null) { freeFilesCount.getAndDecrement(); } - if (nextFile == null) - { + if (nextFile == null) { nextFile = createFile(keepOpened, multiAIO, initFile, tmpCompactExtension, -1); } - else - { - if (tmpCompactExtension) - { + else { + if (tmpCompactExtension) { SequentialFile sequentialFile = nextFile.getFile(); sequentialFile.renameTo(sequentialFile.getFileName() + ".cmp"); } - if (keepOpened) - { + if (keepOpened) { openFile(nextFile, multiAIO); } } @@ -586,8 +505,7 @@ public class JournalFilesRepository * * @param fileID the fileID to use when creating the file. */ - public JournalFile createRemoteBackupSyncFile(long fileID) throws Exception - { + public JournalFile createRemoteBackupSyncFile(long fileID) throws Exception { return createFile(false, false, true, false, fileID); } @@ -602,45 +520,34 @@ public class JournalFilesRepository final boolean multiAIO, final boolean init, final boolean tmpCompact, - final long fileIdPreSet) throws Exception - { - if (System.getSecurityManager() == null) - { + final long fileIdPreSet) throws Exception { + if (System.getSecurityManager() == null) { return createFile0(keepOpened, multiAIO, init, tmpCompact, fileIdPreSet); } - else - { - try - { - return AccessController.doPrivileged(new PrivilegedExceptionAction() - { + else { + try { + return AccessController.doPrivileged(new PrivilegedExceptionAction() { @Override - public JournalFile run() throws Exception - { + public JournalFile run() throws Exception { return createFile0(keepOpened, multiAIO, init, tmpCompact, fileIdPreSet); } }); } - catch (PrivilegedActionException e) - { + catch (PrivilegedActionException e) { throw unwrapException(e); } } } - private RuntimeException unwrapException(PrivilegedActionException e) throws Exception - { + private RuntimeException unwrapException(PrivilegedActionException e) throws Exception { Throwable c = e.getCause(); - if (c instanceof RuntimeException) - { + if (c instanceof RuntimeException) { throw (RuntimeException) c; } - else if (c instanceof Error) - { + else if (c instanceof Error) { throw (Error) c; } - else - { + else { throw new RuntimeException(c); } } @@ -649,14 +556,12 @@ public class JournalFilesRepository final boolean multiAIO, final boolean init, final boolean tmpCompact, - final long fileIdPreSet) throws Exception - { + final long fileIdPreSet) throws Exception { long fileID = fileIdPreSet != -1 ? fileIdPreSet : generateFileID(); final String fileName = createFileName(tmpCompact, fileID); - if (JournalFilesRepository.trace) - { + if (JournalFilesRepository.trace) { JournalFilesRepository.trace("Creating file " + fileName); } @@ -666,8 +571,7 @@ public class JournalFilesRepository sequentialFile.open(1, false); - if (init) - { + if (init) { sequentialFile.fill(fileSize); JournalImpl.initFileHeader(fileFactory, sequentialFile, userVersion, fileID); @@ -677,21 +581,17 @@ public class JournalFilesRepository sequentialFile.close(); - if (JournalFilesRepository.trace) - { + if (JournalFilesRepository.trace) { JournalFilesRepository.trace("Renaming file " + tmpFileName + " as " + fileName); } sequentialFile.renameTo(fileName); - if (keepOpened) - { - if (multiAIO) - { + if (keepOpened) { + if (multiAIO) { sequentialFile.open(); } - else - { + else { sequentialFile.open(1, false); } sequentialFile.position(position); @@ -705,44 +605,36 @@ public class JournalFilesRepository * @param fileID * @return */ - private String createFileName(final boolean tmpCompact, final long fileID) - { + private String createFileName(final boolean tmpCompact, final long fileID) { String fileName; - if (tmpCompact) - { + if (tmpCompact) { fileName = filePrefix + "-" + fileID + "." + fileExtension + ".cmp"; } - else - { + else { fileName = filePrefix + "-" + fileID + "." + fileExtension; } return fileName; } - private long generateFileID() - { + private long generateFileID() { return nextFileID.incrementAndGet(); } /** * Get the ID part of the name */ - private long getFileNameID(final String fileName) - { - try - { + private long getFileNameID(final String fileName) { + try { return Long.parseLong(fileName.substring(filePrefix.length() + 1, fileName.indexOf('.'))); } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQJournalLogger.LOGGER.errorRetrievingID(e, fileName); return 0; } } // Discard the old JournalFile and set it with a new ID - private JournalFile reinitializeFile(final JournalFile file) throws Exception - { + private JournalFile reinitializeFile(final JournalFile file) throws Exception { long newFileID = generateFileID(); SequentialFile sf = file.getFile(); @@ -761,8 +653,7 @@ public class JournalFilesRepository } @Override - public String toString() - { + public String toString() { return "JournalFilesRepository(dataFiles=" + dataFiles + ", freeFiles=" + freeFiles + ", openedFiles=" + openedFiles + ")"; } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalImpl.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalImpl.java index 068e6975c5..865cf72423 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalImpl.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalImpl.java @@ -76,8 +76,7 @@ import org.apache.activemq.artemis.utils.DataConstants; *

    *

    Look at {@link JournalImpl#load(LoaderCallback)} for the file layout */ -public class JournalImpl extends JournalBase implements TestableJournal, JournalRecordProvider -{ +public class JournalImpl extends JournalBase implements TestableJournal, JournalRecordProvider { // Constants ----------------------------------------------------- @@ -95,13 +94,11 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal // This method exists just to make debug easier. // I could replace log.trace by log.info temporarily while I was debugging // Journal - private static void trace(final String message) - { + private static void trace(final String message) { ActiveMQJournalLogger.LOGGER.trace(message); } - private static void traceRecord(final String message) - { + private static void traceRecord(final String message) { ActiveMQJournalLogger.LOGGER.trace(message); } @@ -223,12 +220,10 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal final SequentialFileFactory fileFactory, final String filePrefix, final String fileExtension, - final int maxAIO) - { + final int maxAIO) { this(fileSize, minFiles, compactMinFiles, compactPercentage, fileFactory, filePrefix, fileExtension, maxAIO, 0); } - public JournalImpl(final int fileSize, final int minFiles, final int compactMinFiles, @@ -236,29 +231,24 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal final SequentialFileFactory fileFactory, final String filePrefix, final String fileExtension, - final int maxAIO, final int userVersion) - { + final int maxAIO, + final int userVersion) { super(fileFactory.isSupportsCallbacks(), fileSize); - if (fileSize % fileFactory.getAlignment() != 0) - { + if (fileSize % fileFactory.getAlignment() != 0) { throw new IllegalArgumentException("Invalid journal-file-size " + fileSize + ", It should be multiple of " + fileFactory.getAlignment()); } - if (minFiles < 2) - { + if (minFiles < 2) { throw new IllegalArgumentException("minFiles cannot be less than 2"); } - if (compactPercentage < 0 || compactPercentage > 100) - { + if (compactPercentage < 0 || compactPercentage > 100) { throw new IllegalArgumentException("Compact Percentage out of range"); } - if (compactPercentage == 0) - { + if (compactPercentage == 0) { this.compactPercentage = 0; } - else - { + else { this.compactPercentage = compactPercentage / 100f; } @@ -267,46 +257,34 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal this.fileFactory = fileFactory; - filesRepository = new JournalFilesRepository(fileFactory, - this, - filePrefix, - fileExtension, - userVersion, - maxAIO, - fileSize, - minFiles); + filesRepository = new JournalFilesRepository(fileFactory, this, filePrefix, fileExtension, userVersion, maxAIO, fileSize, minFiles); this.userVersion = userVersion; } @Override - public String toString() - { + public String toString() { return "JournalImpl(state=" + state + ", currentFile=[" + currentFile + "], hash=" + super.toString() + ")"; } - public void runDirectJournalBlast() throws Exception - { + public void runDirectJournalBlast() throws Exception { final int numIts = 100000000; ActiveMQJournalLogger.LOGGER.runningJournalBlast(numIts); final CountDownLatch latch = new CountDownLatch(numIts * 2); - class MyAIOCallback implements IOCompletion - { - public void done() - { + class MyAIOCallback implements IOCompletion { + + public void done() { latch.countDown(); } - public void onError(final int errorCode, final String errorMessage) - { + public void onError(final int errorCode, final String errorMessage) { } - public void storeLineUp() - { + public void storeLineUp() { } } @@ -316,20 +294,16 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal final byte[] bytes = new byte[recordSize]; - class MyRecord implements EncodingSupport - { + class MyRecord implements EncodingSupport { - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { } - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { buffer.writeBytes(bytes); } - public int getEncodeSize() - { + public int getEncodeSize() { return recordSize; } @@ -337,8 +311,7 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal MyRecord record = new MyRecord(); - for (int i = 0; i < numIts; i++) - { + for (int i = 0; i < numIts; i++) { appendAddRecord(i, (byte) 1, record, true, task); appendDeleteRecord(i, true, task); } @@ -346,18 +319,15 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal latch.await(); } - public Map getRecords() - { + public Map getRecords() { return records; } - public JournalFile getCurrentFile() - { + public JournalFile getCurrentFile() { return currentFile; } - public JournalCompactor getCompactor() - { + public JournalCompactor getCompactor() { return compactor; } @@ -365,33 +335,27 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal * this method is used internally only however tools may use it to maintenance. * It won't be part of the interface as the tools should be specific to the implementation */ - public List orderFiles() throws Exception - { + public List orderFiles() throws Exception { List fileNames = fileFactory.listFiles(filesRepository.getFileExtension()); List orderedFiles = new ArrayList(fileNames.size()); - for (String fileName : fileNames) - { + for (String fileName : fileNames) { SequentialFile file = fileFactory.createSequentialFile(fileName); - if (file.size() >= SIZE_HEADER) - { + if (file.size() >= SIZE_HEADER) { file.open(); - try - { + try { JournalFileImpl jrnFile = readFileHeader(file); orderedFiles.add(jrnFile); } - finally - { + finally { file.close(); } } - else - { + else { ActiveMQJournalLogger.LOGGER.ignoringShortFile(fileName); file.delete(); } @@ -410,20 +374,17 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal */ public static int readJournalFile(final SequentialFileFactory fileFactory, final JournalFile file, - final JournalReaderCallback reader) throws Exception - { + final JournalReaderCallback reader) throws Exception { file.getFile().open(1, false); ByteBuffer wholeFileBuffer = null; - try - { + try { final int filesize = (int) file.getFile().size(); wholeFileBuffer = fileFactory.newBuffer(filesize); final int journalFileSize = file.getFile().read(wholeFileBuffer); - if (journalFileSize != filesize) - { + if (journalFileSize != filesize) { throw new RuntimeException("Invalid read! The system couldn't read the entire file into memory"); } @@ -432,22 +393,19 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal int lastDataPos = JournalImpl.SIZE_HEADER; - while (wholeFileBuffer.hasRemaining()) - { + while (wholeFileBuffer.hasRemaining()) { final int pos = wholeFileBuffer.position(); byte recordType = wholeFileBuffer.get(); - if (recordType < JournalImpl.ADD_RECORD || recordType > JournalImpl.ROLLBACK_RECORD) - { + if (recordType < JournalImpl.ADD_RECORD || recordType > JournalImpl.ROLLBACK_RECORD) { // I - We scan for any valid record on the file. If a hole // happened on the middle of the file we keep looking until all // the possibilities are gone continue; } - if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), DataConstants.SIZE_INT)) - { + if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), DataConstants.SIZE_INT)) { reader.markAsDataFile(file); wholeFileBuffer.position(pos + 1); @@ -461,18 +419,15 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal // This record is from a previous file-usage. The file was // reused and we need to ignore this record - if (readFileId != file.getRecordID()) - { + if (readFileId != file.getRecordID()) { wholeFileBuffer.position(pos + 1); continue; } short compactCount = 0; - if (file.getJournalVersion() >= 2) - { - if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), DataConstants.SIZE_BYTE)) - { + if (file.getJournalVersion() >= 2) { + if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), DataConstants.SIZE_BYTE)) { reader.markAsDataFile(file); wholeFileBuffer.position(pos + 1); @@ -484,10 +439,8 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal long transactionID = 0; - if (JournalImpl.isTransaction(recordType)) - { - if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), DataConstants.SIZE_LONG)) - { + if (JournalImpl.isTransaction(recordType)) { + if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), DataConstants.SIZE_LONG)) { wholeFileBuffer.position(pos + 1); reader.markAsDataFile(file); continue; @@ -499,10 +452,8 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal long recordID = 0; // If prepare or commit - if (!JournalImpl.isCompleteTransaction(recordType)) - { - if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), DataConstants.SIZE_LONG)) - { + if (!JournalImpl.isCompleteTransaction(recordType)) { + if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), DataConstants.SIZE_LONG)) { wholeFileBuffer.position(pos + 1); reader.markAsDataFile(file); continue; @@ -525,10 +476,8 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal byte[] record = null; - if (JournalImpl.isContainsBody(recordType)) - { - if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), DataConstants.SIZE_INT)) - { + if (JournalImpl.isContainsBody(recordType)) { + if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), DataConstants.SIZE_INT)) { wholeFileBuffer.position(pos + 1); reader.markAsDataFile(file); continue; @@ -536,10 +485,8 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal variableSize = wholeFileBuffer.getInt(); - if (recordType != JournalImpl.DELETE_RECORD_TX) - { - if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), 1)) - { + if (recordType != JournalImpl.DELETE_RECORD_TX) { + if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), 1)) { wholeFileBuffer.position(pos + 1); continue; } @@ -547,8 +494,7 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal userRecordType = wholeFileBuffer.get(); } - if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), variableSize)) - { + if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), variableSize)) { wholeFileBuffer.position(pos + 1); continue; } @@ -562,20 +508,16 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal // currentFile int transactionCheckNumberOfRecords = 0; - if (recordType == JournalImpl.PREPARE_RECORD || recordType == JournalImpl.COMMIT_RECORD) - { - if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), DataConstants.SIZE_INT)) - { + if (recordType == JournalImpl.PREPARE_RECORD || recordType == JournalImpl.COMMIT_RECORD) { + if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), DataConstants.SIZE_INT)) { wholeFileBuffer.position(pos + 1); continue; } transactionCheckNumberOfRecords = wholeFileBuffer.getInt(); - if (recordType == JournalImpl.PREPARE_RECORD) - { - if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), DataConstants.SIZE_INT)) - { + if (recordType == JournalImpl.PREPARE_RECORD) { + if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), DataConstants.SIZE_INT)) { wholeFileBuffer.position(pos + 1); continue; } @@ -591,8 +533,7 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal // of the record, // But we avoid buffer overflows by damaged data if (JournalImpl.isInvalidSize(journalFileSize, pos, recordSize + variableSize + - preparedTransactionExtraDataSize)) - { + preparedTransactionExtraDataSize)) { // Avoid a buffer overflow caused by damaged data... continue // scanning for more pendingTransactions... JournalImpl.trace("Record at position " + pos + @@ -619,8 +560,7 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal wholeFileBuffer.position(pos + variableSize + recordSize + - preparedTransactionExtraDataSize - - DataConstants.SIZE_INT); + preparedTransactionExtraDataSize - DataConstants.SIZE_INT); int checkSize = wholeFileBuffer.getInt(); @@ -628,8 +568,7 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal // informed at the beginning. // This is like testing a hash for the record. (We could replace the // checkSize by some sort of calculated hash) - if (checkSize != variableSize + recordSize + preparedTransactionExtraDataSize) - { + if (checkSize != variableSize + recordSize + preparedTransactionExtraDataSize) { JournalImpl.trace("Record at position " + pos + " recordType = " + recordType + @@ -655,58 +594,38 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal // At this point everything is checked. So we relax and just load // the data now. - switch (recordType) - { - case ADD_RECORD: - { + switch (recordType) { + case ADD_RECORD: { reader.onReadAddRecord(new RecordInfo(recordID, userRecordType, record, false, compactCount)); break; } - case UPDATE_RECORD: - { + case UPDATE_RECORD: { reader.onReadUpdateRecord(new RecordInfo(recordID, userRecordType, record, true, compactCount)); break; } - case DELETE_RECORD: - { + case DELETE_RECORD: { reader.onReadDeleteRecord(recordID); break; } - case ADD_RECORD_TX: - { - reader.onReadAddRecordTX(transactionID, new RecordInfo(recordID, - userRecordType, - record, - false, - compactCount)); + case ADD_RECORD_TX: { + reader.onReadAddRecordTX(transactionID, new RecordInfo(recordID, userRecordType, record, false, compactCount)); break; } - case UPDATE_RECORD_TX: - { - reader.onReadUpdateRecordTX(transactionID, new RecordInfo(recordID, - userRecordType, - record, - true, - compactCount)); + case UPDATE_RECORD_TX: { + reader.onReadUpdateRecordTX(transactionID, new RecordInfo(recordID, userRecordType, record, true, compactCount)); break; } - case DELETE_RECORD_TX: - { - reader.onReadDeleteRecordTX(transactionID, new RecordInfo(recordID, - (byte) 0, - record, - true, - compactCount)); + case DELETE_RECORD_TX: { + reader.onReadDeleteRecordTX(transactionID, new RecordInfo(recordID, (byte) 0, record, true, compactCount)); break; } - case PREPARE_RECORD: - { + case PREPARE_RECORD: { byte[] extraData = new byte[preparedTransactionExtraDataSize]; @@ -716,19 +635,16 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal break; } - case COMMIT_RECORD: - { + case COMMIT_RECORD: { reader.onReadCommitRecord(transactionID, transactionCheckNumberOfRecords); break; } - case ROLLBACK_RECORD: - { + case ROLLBACK_RECORD: { reader.onReadRollbackRecord(transactionID); break; } - default: - { + default: { throw new IllegalStateException("Journal " + file.getFile().getFileName() + " is corrupt, invalid record type " + recordType); @@ -740,8 +656,7 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal // This is a sanity check about the loading code itself. // If this checkSize doesn't match, it means the reading method is // not doing what it was supposed to do - if (checkSize != variableSize + recordSize + preparedTransactionExtraDataSize) - { + if (checkSize != variableSize + recordSize + preparedTransactionExtraDataSize) { throw new IllegalStateException("Internal error on loading file. Position doesn't match with checkSize, file = " + file.getFile() + ", pos = " + pos); @@ -753,24 +668,19 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal return lastDataPos; } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQJournalLogger.LOGGER.errorReadingFile(e); throw new Exception(e.getMessage(), e); } - finally - { - if (wholeFileBuffer != null) - { + finally { + if (wholeFileBuffer != null) { fileFactory.releaseBuffer(wholeFileBuffer); } - try - { + try { file.getFile().close(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } } @@ -783,28 +693,23 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal final byte recordType, final EncodingSupport record, final boolean sync, - final IOCompletion callback) throws Exception - { + final IOCompletion callback) throws Exception { checkJournalIsLoaded(); journalLock.readLock().lock(); - try - { + try { JournalInternalRecord addRecord = new JournalAddRecord(true, id, recordType, record); - if (callback != null) - { + if (callback != null) { callback.storeLineUp(); } lockAppend.lock(); - try - { + try { JournalFile usedFile = appendRecord(addRecord, false, sync, null, callback); - if (JournalImpl.TRACE_RECORDS) - { + if (JournalImpl.TRACE_RECORDS) { JournalImpl.traceRecord("appendAddRecord::id=" + id + ", userRecordType=" + recordType + @@ -814,13 +719,11 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal records.put(id, new JournalRecord(usedFile, addRecord.getEncodeSize())); } - finally - { + finally { lockAppend.unlock(); } } - finally - { + finally { journalLock.readLock().unlock(); } } @@ -830,38 +733,31 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal final byte recordType, final EncodingSupport record, final boolean sync, - final IOCompletion callback) throws Exception - { + final IOCompletion callback) throws Exception { checkJournalIsLoaded(); journalLock.readLock().lock(); - try - { + try { JournalRecord jrnRecord = records.get(id); - if (jrnRecord == null) - { - if (!(compactor != null && compactor.lookupRecord(id))) - { + if (jrnRecord == null) { + if (!(compactor != null && compactor.lookupRecord(id))) { throw new IllegalStateException("Cannot find add info " + id); } } JournalInternalRecord updateRecord = new JournalAddRecord(false, id, recordType, record); - if (callback != null) - { + if (callback != null) { callback.storeLineUp(); } lockAppend.lock(); - try - { + try { JournalFile usedFile = appendRecord(updateRecord, false, sync, null, callback); - if (JournalImpl.TRACE_RECORDS) - { + if (JournalImpl.TRACE_RECORDS) { JournalImpl.traceRecord("appendUpdateRecord::id=" + id + ", userRecordType=" + recordType + @@ -871,91 +767,73 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal // record== null here could only mean there is a compactor, and computing the delete should be done after // compacting is done - if (jrnRecord == null) - { + if (jrnRecord == null) { compactor.addCommandUpdate(id, usedFile, updateRecord.getEncodeSize()); } - else - { + else { jrnRecord.addUpdateFile(usedFile, updateRecord.getEncodeSize()); } } - finally - { + finally { lockAppend.unlock(); } } - finally - { + finally { journalLock.readLock().unlock(); } } - @Override - public void appendDeleteRecord(final long id, final boolean sync, final IOCompletion callback) throws Exception - { + public void appendDeleteRecord(final long id, final boolean sync, final IOCompletion callback) throws Exception { checkJournalIsLoaded(); journalLock.readLock().lock(); - try - { + try { JournalRecord record = null; - if (compactor == null) - { + if (compactor == null) { record = records.remove(id); - if (record == null) - { + if (record == null) { throw new IllegalStateException("Cannot find add info " + id); } } - else - { - if (!records.containsKey(id) && !compactor.lookupRecord(id)) - { + else { + if (!records.containsKey(id) && !compactor.lookupRecord(id)) { throw new IllegalStateException("Cannot find add info " + id + " on compactor or current records"); } } JournalInternalRecord deleteRecord = new JournalDeleteRecord(id); - if (callback != null) - { + if (callback != null) { callback.storeLineUp(); } lockAppend.lock(); - try - { + try { JournalFile usedFile = appendRecord(deleteRecord, false, sync, null, callback); - if (JournalImpl.TRACE_RECORDS) - { + if (JournalImpl.TRACE_RECORDS) { JournalImpl.traceRecord("appendDeleteRecord::id=" + id + ", usedFile = " + usedFile); } // record== null here could only mean there is a compactor, and computing the delete should be done after // compacting is done - if (record == null) - { + if (record == null) { compactor.addCommandDelete(id, usedFile); } - else - { + else { record.delete(usedFile); } } - finally - { + finally { lockAppend.unlock(); } } - finally - { + finally { journalLock.readLock().unlock(); } } @@ -964,25 +842,21 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal public void appendAddRecordTransactional(final long txID, final long id, final byte recordType, - final EncodingSupport record) throws Exception - { + final EncodingSupport record) throws Exception { checkJournalIsLoaded(); journalLock.readLock().lock(); - try - { + try { JournalInternalRecord addRecord = new JournalAddRecordTX(true, txID, id, recordType, record); JournalTransaction tx = getTransactionInfo(txID); lockAppend.lock(); - try - { + try { JournalFile usedFile = appendRecord(addRecord, false, false, tx, null); - if (JournalImpl.TRACE_RECORDS) - { + if (JournalImpl.TRACE_RECORDS) { JournalImpl.traceRecord("appendAddRecordTransactional:txID=" + txID + ",id=" + id + @@ -994,27 +868,22 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal tx.addPositive(usedFile, id, addRecord.getEncodeSize()); } - finally - { + finally { lockAppend.unlock(); } } - finally - { + finally { journalLock.readLock().unlock(); } } - private void checkJournalIsLoaded() - { - if (state != JournalState.LOADED && state != JournalState.SYNCING) - { + private void checkJournalIsLoaded() { + if (state != JournalState.LOADED && state != JournalState.SYNCING) { throw new IllegalStateException("Journal must be in state=" + JournalState.LOADED + ", was [" + state + "]"); } } - private void setJournalState(JournalState newState) - { + private void setJournalState(JournalState newState) { state = newState; } @@ -1022,25 +891,21 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal public void appendUpdateRecordTransactional(final long txID, final long id, final byte recordType, - final EncodingSupport record) throws Exception - { + final EncodingSupport record) throws Exception { checkJournalIsLoaded(); journalLock.readLock().lock(); - try - { + try { JournalInternalRecord updateRecordTX = new JournalAddRecordTX(false, txID, id, recordType, record); JournalTransaction tx = getTransactionInfo(txID); lockAppend.lock(); - try - { + try { JournalFile usedFile = appendRecord(updateRecordTX, false, false, tx, null); - if (JournalImpl.TRACE_RECORDS) - { + if (JournalImpl.TRACE_RECORDS) { JournalImpl.traceRecord("appendUpdateRecordTransactional::txID=" + txID + ",id=" + id + @@ -1052,38 +917,33 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal tx.addPositive(usedFile, id, updateRecordTX.getEncodeSize()); } - finally - { + finally { lockAppend.unlock(); } } - finally - { + finally { journalLock.readLock().unlock(); } } - @Override - public void appendDeleteRecordTransactional(final long txID, final long id, final EncodingSupport record) throws Exception - { + public void appendDeleteRecordTransactional(final long txID, + final long id, + final EncodingSupport record) throws Exception { checkJournalIsLoaded(); journalLock.readLock().lock(); - try - { + try { JournalInternalRecord deleteRecordTX = new JournalDeleteRecordTX(txID, id, record); JournalTransaction tx = getTransactionInfo(txID); lockAppend.lock(); - try - { + try { JournalFile usedFile = appendRecord(deleteRecordTX, false, false, tx, null); - if (JournalImpl.TRACE_RECORDS) - { + if (JournalImpl.TRACE_RECORDS) { JournalImpl.traceRecord("appendDeleteRecordTransactional::txID=" + txID + ", id=" + id + @@ -1093,13 +953,11 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal tx.addNegative(usedFile, id); } - finally - { + finally { lockAppend.unlock(); } } - finally - { + finally { journalLock.readLock().unlock(); } } @@ -1120,197 +978,167 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal public void appendPrepareRecord(final long txID, final EncodingSupport transactionData, final boolean sync, - final IOCompletion callback) throws Exception - { + final IOCompletion callback) throws Exception { checkJournalIsLoaded(); journalLock.readLock().lock(); - try - { + try { JournalTransaction tx = getTransactionInfo(txID); - JournalInternalRecord prepareRecord = - new JournalCompleteRecordTX(TX_RECORD_TYPE.PREPARE, txID, transactionData); + JournalInternalRecord prepareRecord = new JournalCompleteRecordTX(TX_RECORD_TYPE.PREPARE, txID, transactionData); - if (callback != null) - { + if (callback != null) { callback.storeLineUp(); } lockAppend.lock(); - try - { + try { JournalFile usedFile = appendRecord(prepareRecord, true, sync, tx, callback); - if (JournalImpl.TRACE_RECORDS) - { + if (JournalImpl.TRACE_RECORDS) { JournalImpl.traceRecord("appendPrepareRecord::txID=" + txID + ", usedFile = " + usedFile); } tx.prepare(usedFile); } - finally - { + finally { lockAppend.unlock(); } } - finally - { + finally { journalLock.readLock().unlock(); } } @Override - public void lineUpContext(IOCompletion callback) - { + public void lineUpContext(IOCompletion callback) { callback.storeLineUp(); } - /** * Regarding the number of operations in a given file see {@link JournalCompleteRecordTX}. */ @Override - public void appendCommitRecord(final long txID, final boolean sync, final IOCompletion callback, boolean lineUpContext) throws Exception - { + public void appendCommitRecord(final long txID, + final boolean sync, + final IOCompletion callback, + boolean lineUpContext) throws Exception { checkJournalIsLoaded(); journalLock.readLock().lock(); - try - { + try { JournalTransaction tx = transactions.remove(txID); - if (tx == null) - { + if (tx == null) { throw new IllegalStateException("Cannot find tx with id " + txID); } JournalInternalRecord commitRecord = new JournalCompleteRecordTX(TX_RECORD_TYPE.COMMIT, txID, null); - if (callback != null && lineUpContext) - { + if (callback != null && lineUpContext) { callback.storeLineUp(); } lockAppend.lock(); - try - { + try { JournalFile usedFile = appendRecord(commitRecord, true, sync, tx, callback); - if (JournalImpl.TRACE_RECORDS) - { + if (JournalImpl.TRACE_RECORDS) { JournalImpl.traceRecord("appendCommitRecord::txID=" + txID + ", usedFile = " + usedFile); } tx.commit(usedFile); } - finally - { + finally { lockAppend.unlock(); } } - finally - { + finally { journalLock.readLock().unlock(); } } @Override - public void appendRollbackRecord(final long txID, final boolean sync, final IOCompletion callback) throws Exception - { + public void appendRollbackRecord(final long txID, final boolean sync, final IOCompletion callback) throws Exception { checkJournalIsLoaded(); journalLock.readLock().lock(); JournalTransaction tx = null; - try - { + try { tx = transactions.remove(txID); - if (tx == null) - { + if (tx == null) { throw new IllegalStateException("Cannot find tx with id " + txID); } JournalInternalRecord rollbackRecord = new JournalRollbackRecordTX(txID); - if (callback != null) - { + if (callback != null) { callback.storeLineUp(); } lockAppend.lock(); - try - { + try { JournalFile usedFile = appendRecord(rollbackRecord, false, sync, tx, callback); tx.rollback(usedFile); } - finally - { + finally { lockAppend.unlock(); } } - finally - { + finally { journalLock.readLock().unlock(); } } // XXX make it protected? - public int getAlignment() throws Exception - { + public int getAlignment() throws Exception { return fileFactory.getAlignment(); } - private static final class DummyLoader implements LoaderCallback - { + private static final class DummyLoader implements LoaderCallback { + static final LoaderCallback INSTANCE = new DummyLoader(); - public void failedTransaction(final long transactionID, final List records, - final List recordsToDelete) - { + public void failedTransaction(final long transactionID, + final List records, + final List recordsToDelete) { } - public void updateRecord(final RecordInfo info) - { + public void updateRecord(final RecordInfo info) { } - public void deleteRecord(final long id) - { + public void deleteRecord(final long id) { } - public void addRecord(final RecordInfo info) - { + public void addRecord(final RecordInfo info) { } - public void addPreparedTransaction(final PreparedTransactionInfo preparedTransaction) - { + public void addPreparedTransaction(final PreparedTransactionInfo preparedTransaction) { } } - public synchronized JournalLoadInformation loadInternalOnly() throws Exception - { + public synchronized JournalLoadInformation loadInternalOnly() throws Exception { return load(DummyLoader.INSTANCE, true, null); } - public synchronized JournalLoadInformation loadSyncOnly(JournalState syncState) throws Exception - { + public synchronized JournalLoadInformation loadSyncOnly(JournalState syncState) throws Exception { assert syncState == JournalState.SYNCING || syncState == JournalState.SYNCING_UP_TO_DATE; return load(DummyLoader.INSTANCE, true, syncState); } public JournalLoadInformation load(final List committedRecords, final List preparedTransactions, - final TransactionFailureCallback failureCallback) throws Exception - { + final TransactionFailureCallback failureCallback) throws Exception { return load(committedRecords, preparedTransactions, failureCallback, true); } @@ -1320,33 +1148,27 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal public synchronized JournalLoadInformation load(final List committedRecords, final List preparedTransactions, final TransactionFailureCallback failureCallback, - final boolean fixBadTX) throws Exception - { + final boolean fixBadTX) throws Exception { final Set recordsToDelete = new HashSet(); // ArrayList was taking too long to delete elements on checkDeleteSize final List records = new LinkedList(); final int DELETE_FLUSH = 20000; - JournalLoadInformation info = load(new LoaderCallback() - { + JournalLoadInformation info = load(new LoaderCallback() { Runtime runtime = Runtime.getRuntime(); - private void checkDeleteSize() - { + private void checkDeleteSize() { // HORNETQ-482 - Flush deletes only if memory is critical - if (recordsToDelete.size() > DELETE_FLUSH && runtime.freeMemory() < runtime.maxMemory() * 0.2) - { + if (recordsToDelete.size() > DELETE_FLUSH && runtime.freeMemory() < runtime.maxMemory() * 0.2) { ActiveMQJournalLogger.LOGGER.debug("Flushing deletes during loading, deleteCount = " + recordsToDelete.size()); // Clean up when the list is too large, or it won't be possible to load large sets of files // Done as part of JBMESSAGING-1678 Iterator iter = records.iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { RecordInfo record = iter.next(); - if (recordsToDelete.contains(record.id)) - { + if (recordsToDelete.contains(record.id)) { iter.remove(); } } @@ -1357,45 +1179,37 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal } } - public void addPreparedTransaction(final PreparedTransactionInfo preparedTransaction) - { + public void addPreparedTransaction(final PreparedTransactionInfo preparedTransaction) { preparedTransactions.add(preparedTransaction); checkDeleteSize(); } - public void addRecord(final RecordInfo info) - { + public void addRecord(final RecordInfo info) { records.add(info); checkDeleteSize(); } - public void updateRecord(final RecordInfo info) - { + public void updateRecord(final RecordInfo info) { records.add(info); checkDeleteSize(); } - public void deleteRecord(final long id) - { + public void deleteRecord(final long id) { recordsToDelete.add(id); checkDeleteSize(); } public void failedTransaction(final long transactionID, final List records, - final List recordsToDelete) - { - if (failureCallback != null) - { + final List recordsToDelete) { + if (failureCallback != null) { failureCallback.failedTransaction(transactionID, records, recordsToDelete); } } }, fixBadTX, null); - for (RecordInfo record : records) - { - if (!recordsToDelete.contains(record.id)) - { + for (RecordInfo record : records) { + if (!recordsToDelete.contains(record.id)) { committedRecords.add(record); } } @@ -1403,9 +1217,7 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal return info; } - - public void scheduleCompactAndBlock(int timeout) throws Exception - { + public void scheduleCompactAndBlock(int timeout) throws Exception { final AtomicInteger errors = new AtomicInteger(0); final CountDownLatch latch = newLatch(1); @@ -1414,40 +1226,32 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal // We can't use the executor for the compacting... or we would dead lock because of file open and creation // operations (that will use the executor) - compactorExecutor.execute(new Runnable() - { - public void run() - { + compactorExecutor.execute(new Runnable() { + public void run() { - try - { + try { JournalImpl.this.compact(); } - catch (Throwable e) - { + catch (Throwable e) { errors.incrementAndGet(); ActiveMQJournalLogger.LOGGER.errorCompacting(e); e.printStackTrace(); } - finally - { + finally { latch.countDown(); } } }); - try - { + try { awaitLatch(latch, timeout); - if (errors.get() > 0) - { + if (errors.get() > 0) { throw new RuntimeException("Error during compact, look at the logs"); } } - finally - { + finally { compactorRunning.set(false); } } @@ -1459,22 +1263,18 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal * Note: only synchronized methods on journal are methods responsible for the life-cycle such as * stop, start records will still come as this is being executed */ - public synchronized void compact() throws Exception - { - if (compactor != null) - { + public synchronized void compact() throws Exception { + if (compactor != null) { throw new IllegalStateException("There is pending compacting operation"); } compactorLock.writeLock().lock(); - try - { + try { ArrayList dataFilesToProcess = new ArrayList(filesRepository.getDataFilesCount()); boolean previousReclaimValue = isAutoReclaim(); - try - { + try { ActiveMQJournalLogger.LOGGER.debug("Starting compacting operation on journal"); onCompactStart(); @@ -1482,10 +1282,8 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal // We need to guarantee that the journal is frozen for this short time // We don't freeze the journal as we compact, only for the short time where we replace records journalLock.writeLock().lock(); - try - { - if (state != JournalState.LOADED) - { + try { + if (state != JournalState.LOADED) { return; } @@ -1502,20 +1300,14 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal filesRepository.clearDataFiles(); - if (dataFilesToProcess.size() == 0) - { + if (dataFilesToProcess.size() == 0) { trace("Finishing compacting, nothing to process"); return; } - compactor = new JournalCompactor(fileFactory, - this, - filesRepository, - records.keySet(), - dataFilesToProcess.get(0).getFileID()); + compactor = new JournalCompactor(fileFactory, this, filesRepository, records.keySet(), dataFilesToProcess.get(0).getFileID()); - for (Map.Entry entry : transactions.entrySet()) - { + for (Map.Entry entry : transactions.entrySet()) { compactor.addPendingTransaction(entry.getKey(), entry.getValue().getPositiveArray()); entry.getValue().setCompacting(); } @@ -1524,8 +1316,7 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal // after compacting records.clear(); } - finally - { + finally { journalLock.writeLock().unlock(); } @@ -1536,14 +1327,11 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal // Read the files, and use the JournalCompactor class to create the new outputFiles, and the new collections as // well - for (final JournalFile file : dataFilesToProcess) - { - try - { + for (final JournalFile file : dataFilesToProcess) { + try { JournalImpl.readJournalFile(fileFactory, file, compactor); } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQJournalLogger.LOGGER.compactReadError(file); throw new Exception("Error on reading compacting for " + file, e); } @@ -1563,8 +1351,7 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal SequentialFile controlFile = createControlFile(dataFilesToProcess, compactor.getNewDataFiles(), null); journalLock.writeLock().lock(); - try - { + try { // Need to clear the compactor here, or the replay commands will send commands back (infinite loop) compactor = null; @@ -1573,31 +1360,26 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal newDatafiles = localCompactor.getNewDataFiles(); // Restore newRecords created during compacting - for (Map.Entry newRecordEntry : localCompactor.getNewRecords().entrySet()) - { + for (Map.Entry newRecordEntry : localCompactor.getNewRecords().entrySet()) { records.put(newRecordEntry.getKey(), newRecordEntry.getValue()); } // Restore compacted dataFiles - for (int i = newDatafiles.size() - 1; i >= 0; i--) - { + for (int i = newDatafiles.size() - 1; i >= 0; i--) { JournalFile fileToAdd = newDatafiles.get(i); - if (JournalImpl.trace) - { + if (JournalImpl.trace) { JournalImpl.trace("Adding file " + fileToAdd + " back as datafile"); } filesRepository.addDataFileOnTop(fileToAdd); } - if (JournalImpl.trace) - { + if (JournalImpl.trace) { JournalImpl.trace("There are " + filesRepository.getDataFilesCount() + " datafiles Now"); } // Replay pending commands (including updates, deletes and commits) - for (JournalTransaction newTransaction : localCompactor.getNewTransactions().values()) - { + for (JournalTransaction newTransaction : localCompactor.getNewTransactions().values()) { newTransaction.replaceRecordProvider(this); } @@ -1607,25 +1389,20 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal // This has to be done after the replay pending commands, as we need to delete commits // that happened during the compacting - for (JournalTransaction newTransaction : localCompactor.getNewTransactions().values()) - { - if (JournalImpl.trace) - { + for (JournalTransaction newTransaction : localCompactor.getNewTransactions().values()) { + if (JournalImpl.trace) { JournalImpl.trace("Merging pending transaction " + newTransaction + " after compacting the journal"); } JournalTransaction liveTransaction = transactions.get(newTransaction.getId()); - if (liveTransaction != null) - { + if (liveTransaction != null) { liveTransaction.merge(newTransaction); } - else - { + else { ActiveMQJournalLogger.LOGGER.compactMergeError(newTransaction.getId()); } } } - finally - { + finally { journalLock.writeLock().unlock(); } @@ -1636,17 +1413,13 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal ActiveMQJournalLogger.LOGGER.debug("Finished compacting on journal"); } - finally - { + finally { // An Exception was probably thrown, and the compactor was not cleared - if (compactor != null) - { - try - { + if (compactor != null) { + try { compactor.flush(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } compactor = null; @@ -1654,8 +1427,7 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal setAutoReclaim(previousReclaimValue); } } - finally - { + finally { compactorLock.writeLock().unlock(); } @@ -1697,8 +1469,7 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal *

    *

    * FileID and NumberOfElements are the transaction summary, and they will be repeated (N)umberOfFiles times

    */ - public JournalLoadInformation load(final LoaderCallback loadManager) throws Exception - { + public JournalLoadInformation load(final LoaderCallback loadManager) throws Exception { return load(loadManager, true, null); } @@ -1709,16 +1480,14 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal * @return * @throws Exception */ - private synchronized JournalLoadInformation load(final LoaderCallback loadManager, final boolean changeData, - final JournalState replicationSync) throws Exception - { - if (state == JournalState.STOPPED || state == JournalState.LOADED) - { + private synchronized JournalLoadInformation load(final LoaderCallback loadManager, + final boolean changeData, + final JournalState replicationSync) throws Exception { + if (state == JournalState.STOPPED || state == JournalState.LOADED) { throw new IllegalStateException("Journal " + this + " must be in " + JournalState.STARTED + " state, was " + state); } - if (state == replicationSync) - { + if (state == replicationSync) { throw new IllegalStateException("Journal cannot be in state " + JournalState.STARTED); } @@ -1742,25 +1511,20 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal // AtomicLong is used only as a reference, not as an Atomic value final AtomicLong maxID = new AtomicLong(-1); - for (final JournalFile file : orderedFiles) - { + for (final JournalFile file : orderedFiles) { JournalImpl.trace("Loading file " + file.getFile().getFileName()); final AtomicBoolean hasData = new AtomicBoolean(false); - int resultLastPost = JournalImpl.readJournalFile(fileFactory, file, new JournalReaderCallback() - { + int resultLastPost = JournalImpl.readJournalFile(fileFactory, file, new JournalReaderCallback() { - private void checkID(final long id) - { - if (id > maxID.longValue()) - { + private void checkID(final long id) { + if (id > maxID.longValue()) { maxID.set(id); } } - public void onReadAddRecord(final RecordInfo info) throws Exception - { + public void onReadAddRecord(final RecordInfo info) throws Exception { checkID(info.id); hasData.set(true); @@ -1770,8 +1534,7 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal records.put(info.id, new JournalRecord(file, info.data.length + JournalImpl.SIZE_ADD_RECORD + 1)); } - public void onReadUpdateRecord(final RecordInfo info) throws Exception - { + public void onReadUpdateRecord(final RecordInfo info) throws Exception { checkID(info.id); hasData.set(true); @@ -1780,8 +1543,7 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal JournalRecord posFiles = records.get(info.id); - if (posFiles != null) - { + if (posFiles != null) { // It's legal for this to be null. The file(s) with the may // have been deleted // just leaving some updates in this file @@ -1791,27 +1553,23 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal } } - public void onReadDeleteRecord(final long recordID) throws Exception - { + public void onReadDeleteRecord(final long recordID) throws Exception { hasData.set(true); loadManager.deleteRecord(recordID); JournalRecord posFiles = records.remove(recordID); - if (posFiles != null) - { + if (posFiles != null) { posFiles.delete(file); } } - public void onReadUpdateRecordTX(final long transactionID, final RecordInfo info) throws Exception - { + public void onReadUpdateRecordTX(final long transactionID, final RecordInfo info) throws Exception { onReadAddRecordTX(transactionID, info); } - public void onReadAddRecordTX(final long transactionID, final RecordInfo info) throws Exception - { + public void onReadAddRecordTX(final long transactionID, final RecordInfo info) throws Exception { checkID(info.id); @@ -1819,8 +1577,7 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal TransactionHolder tx = loadTransactions.get(transactionID); - if (tx == null) - { + if (tx == null) { tx = new TransactionHolder(transactionID); loadTransactions.put(transactionID, tx); @@ -1830,8 +1587,7 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal JournalTransaction tnp = transactions.get(transactionID); - if (tnp == null) - { + if (tnp == null) { tnp = new JournalTransaction(transactionID, JournalImpl.this); transactions.put(transactionID, tnp); @@ -1841,14 +1597,12 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal // count } - public void onReadDeleteRecordTX(final long transactionID, final RecordInfo info) throws Exception - { + public void onReadDeleteRecordTX(final long transactionID, final RecordInfo info) throws Exception { hasData.set(true); TransactionHolder tx = loadTransactions.get(transactionID); - if (tx == null) - { + if (tx == null) { tx = new TransactionHolder(transactionID); loadTransactions.put(transactionID, tx); @@ -1858,8 +1612,7 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal JournalTransaction tnp = transactions.get(transactionID); - if (tnp == null) - { + if (tnp == null) { tnp = new JournalTransaction(transactionID, JournalImpl.this); transactions.put(transactionID, tnp); @@ -1869,14 +1622,14 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal } - public void onReadPrepareRecord(final long transactionID, final byte[] extraData, final int numberOfRecords) throws Exception - { + public void onReadPrepareRecord(final long transactionID, + final byte[] extraData, + final int numberOfRecords) throws Exception { hasData.set(true); TransactionHolder tx = loadTransactions.get(transactionID); - if (tx == null) - { + if (tx == null) { // The user could choose to prepare empty transactions tx = new TransactionHolder(transactionID); @@ -1889,8 +1642,7 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal JournalTransaction journalTransaction = transactions.get(transactionID); - if (journalTransaction == null) - { + if (journalTransaction == null) { journalTransaction = new JournalTransaction(transactionID, JournalImpl.this); transactions.put(transactionID, journalTransaction); @@ -1898,19 +1650,16 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal boolean healthy = checkTransactionHealth(file, journalTransaction, orderedFiles, numberOfRecords); - if (healthy) - { + if (healthy) { journalTransaction.prepare(file); } - else - { + else { ActiveMQJournalLogger.LOGGER.preparedTXIncomplete(transactionID); tx.invalid = true; } } - public void onReadCommitRecord(final long transactionID, final int numberOfRecords) throws Exception - { + public void onReadCommitRecord(final long transactionID, final int numberOfRecords) throws Exception { TransactionHolder tx = loadTransactions.remove(transactionID); // The commit could be alone on its own journal-file and the @@ -1920,40 +1669,32 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal // point // If we can't find it, we assume the TX was reclaimed and we // ignore this - if (tx != null) - { + if (tx != null) { JournalTransaction journalTransaction = transactions.remove(transactionID); - if (journalTransaction == null) - { + if (journalTransaction == null) { throw new IllegalStateException("Cannot find tx " + transactionID); } boolean healthy = checkTransactionHealth(file, journalTransaction, orderedFiles, numberOfRecords); - if (healthy) - { - for (RecordInfo txRecord : tx.recordInfos) - { - if (txRecord.isUpdate) - { + if (healthy) { + for (RecordInfo txRecord : tx.recordInfos) { + if (txRecord.isUpdate) { loadManager.updateRecord(txRecord); } - else - { + else { loadManager.addRecord(txRecord); } } - for (RecordInfo deleteValue : tx.recordsToDelete) - { + for (RecordInfo deleteValue : tx.recordsToDelete) { loadManager.deleteRecord(deleteValue.id); } journalTransaction.commit(file); } - else - { + else { ActiveMQJournalLogger.LOGGER.txMissingElements(transactionID); journalTransaction.forget(); @@ -1964,20 +1705,17 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal } - public void onReadRollbackRecord(final long transactionID) throws Exception - { + public void onReadRollbackRecord(final long transactionID) throws Exception { TransactionHolder tx = loadTransactions.remove(transactionID); // The rollback could be alone on its own journal-file and the // whole transaction body was reclaimed but the commit-record // So it is completely legal to not find a transaction at this // point - if (tx != null) - { + if (tx != null) { JournalTransaction tnp = transactions.remove(transactionID); - if (tnp == null) - { + if (tnp == null) { throw new IllegalStateException("Cannot find tx " + transactionID); } @@ -1989,30 +1727,25 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal } } - public void markAsDataFile(final JournalFile file) - { + public void markAsDataFile(final JournalFile file) { hasData.set(true); } }); - if (hasData.get()) - { + if (hasData.get()) { lastDataPos = resultLastPost; filesRepository.addDataFileOnBottom(file); } - else - { - if (changeData) - { + else { + if (changeData) { // Empty dataFiles with no data filesRepository.addFreeFile(file, false, false); } } } - if (replicationSync == JournalState.SYNCING) - { + if (replicationSync == JournalState.SYNCING) { assert filesRepository.getDataFiles().isEmpty(); setJournalState(JournalState.SYNCING); return new JournalLoadInformation(0, -1); @@ -2022,28 +1755,20 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal setJournalState(JournalState.LOADED); - for (TransactionHolder transaction : loadTransactions.values()) - { - if ((!transaction.prepared || transaction.invalid) && replicationSync != JournalState.SYNCING_UP_TO_DATE) - { + for (TransactionHolder transaction : loadTransactions.values()) { + if ((!transaction.prepared || transaction.invalid) && replicationSync != JournalState.SYNCING_UP_TO_DATE) { ActiveMQJournalLogger.LOGGER.uncomittedTxFound(transaction.transactionID); - if (changeData) - { + if (changeData) { // I append a rollback record here, because otherwise compacting will be throwing messages because of unknown transactions this.appendRollbackRecord(transaction.transactionID, false); } - loadManager.failedTransaction(transaction.transactionID, - transaction.recordInfos, - transaction.recordsToDelete); + loadManager.failedTransaction(transaction.transactionID, transaction.recordInfos, transaction.recordsToDelete); } - else - { - for (RecordInfo info : transaction.recordInfos) - { - if (info.id > maxID.get()) - { + else { + for (RecordInfo info : transaction.recordInfos) { + if (info.id > maxID.get()) { maxID.set(info.id); } } @@ -2066,17 +1791,14 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal /** * @return true if cleanup was called */ - public final boolean checkReclaimStatus() throws Exception - { + public final boolean checkReclaimStatus() throws Exception { - if (compactorRunning.get()) - { + if (compactorRunning.get()) { return false; } // We can't start reclaim while compacting is working - while (true) - { + while (true) { if (state != JournalImpl.JournalState.LOADED) return false; if (!isAutoReclaim()) @@ -2084,17 +1806,13 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal if (journalLock.readLock().tryLock(250, TimeUnit.MILLISECONDS)) break; } - try - { + try { reclaimer.scan(getDataFiles()); - for (JournalFile file : filesRepository.getDataFiles()) - { - if (file.isCanReclaim()) - { + for (JournalFile file : filesRepository.getDataFiles()) { + if (file.isCanReclaim()) { // File can be reclaimed or deleted - if (JournalImpl.trace) - { + if (JournalImpl.trace) { JournalImpl.trace("Reclaiming file " + file); } @@ -2104,22 +1822,19 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal } } } - finally - { + finally { journalLock.readLock().unlock(); } return false; } - private boolean needsCompact() throws Exception - { + private boolean needsCompact() throws Exception { JournalFile[] dataFiles = getDataFiles(); long totalLiveSize = 0; - for (JournalFile file : dataFiles) - { + for (JournalFile file : dataFiles) { totalLiveSize += file.getLiveSize(); } @@ -2133,49 +1848,38 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal } - private void checkCompact() throws Exception - { - if (compactMinFiles == 0) - { + private void checkCompact() throws Exception { + if (compactMinFiles == 0) { // compacting is disabled return; } - if (state != JournalState.LOADED) - { + if (state != JournalState.LOADED) { return; } - if (!compactorRunning.get() && needsCompact()) - { + if (!compactorRunning.get() && needsCompact()) { scheduleCompact(); } } - private void scheduleCompact() - { - if (!compactorRunning.compareAndSet(false, true)) - { + private void scheduleCompact() { + if (!compactorRunning.compareAndSet(false, true)) { return; } // We can't use the executor for the compacting... or we would dead lock because of file open and creation // operations (that will use the executor) - compactorExecutor.execute(new Runnable() - { - public void run() - { + compactorExecutor.execute(new Runnable() { + public void run() { - try - { + try { JournalImpl.this.compact(); } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQJournalLogger.LOGGER.errorCompacting(e); } - finally - { + finally { compactorRunning.set(false); } } @@ -2185,26 +1889,22 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal // TestableJournal implementation // -------------------------------------------------------------- - public final void setAutoReclaim(final boolean autoReclaim) - { + public final void setAutoReclaim(final boolean autoReclaim) { this.autoReclaim = autoReclaim; } - public final boolean isAutoReclaim() - { + public final boolean isAutoReclaim() { return autoReclaim; } /* Only meant to be used in tests. */ @Override - public String debug() throws Exception - { + public String debug() throws Exception { reclaimer.scan(getDataFiles()); StringBuilder builder = new StringBuilder(); - for (JournalFile file : filesRepository.getDataFiles()) - { + for (JournalFile file : filesRepository.getDataFiles()) { builder.append("DataFile:" + file + " posCounter = " + file.getPosCount() + @@ -2213,29 +1913,24 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal " live size = " + file.getLiveSize() + "\n"); - if (file instanceof JournalFileImpl) - { + if (file instanceof JournalFileImpl) { builder.append(((JournalFileImpl) file).debug()); } } - for (JournalFile file : filesRepository.getFreeFiles()) - { + for (JournalFile file : filesRepository.getFreeFiles()) { builder.append("FreeFile:" + file + "\n"); } - if (currentFile != null) - { + if (currentFile != null) { builder.append("CurrentFile:" + currentFile + " posCounter = " + currentFile.getPosCount() + "\n"); - if (currentFile instanceof JournalFileImpl) - { + if (currentFile instanceof JournalFileImpl) { builder.append(((JournalFileImpl) currentFile).debug()); } } - else - { + else { builder.append("CurrentFile: No current file at this point!"); } @@ -2246,25 +1941,20 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal * Method for use on testcases. * It will call waitComplete on every transaction, so any assertions on the file system will be correct after this */ - public void debugWait() throws InterruptedException - { + public void debugWait() throws InterruptedException { fileFactory.flush(); - for (JournalTransaction tx : transactions.values()) - { + for (JournalTransaction tx : transactions.values()) { tx.waitCallbacks(); } - if (filesExecutor != null && !filesExecutor.isShutdown()) - { + if (filesExecutor != null && !filesExecutor.isShutdown()) { // Send something to the closingExecutor, just to make sure we went // until its end final CountDownLatch latch = newLatch(1); - filesExecutor.execute(new Runnable() - { - public void run() - { + filesExecutor.execute(new Runnable() { + public void run() { latch.countDown(); } }); @@ -2274,119 +1964,95 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal } - public int getDataFilesCount() - { + public int getDataFilesCount() { return filesRepository.getDataFilesCount(); } - public JournalFile[] getDataFiles() - { + public JournalFile[] getDataFiles() { return filesRepository.getDataFilesArray(); } - public int getFreeFilesCount() - { + public int getFreeFilesCount() { return filesRepository.getFreeFilesCount(); } - public int getOpenedFilesCount() - { + public int getOpenedFilesCount() { return filesRepository.getOpenedFilesCount(); } - public int getIDMapSize() - { + public int getIDMapSize() { return records.size(); } @Override - public int getFileSize() - { + public int getFileSize() { return fileSize; } - public int getMinFiles() - { + public int getMinFiles() { return minFiles; } - public String getFilePrefix() - { + public String getFilePrefix() { return filesRepository.getFilePrefix(); } - public String getFileExtension() - { + public String getFileExtension() { return filesRepository.getFileExtension(); } - public int getMaxAIO() - { + public int getMaxAIO() { return filesRepository.getMaxAIO(); } - public int getUserVersion() - { + public int getUserVersion() { return userVersion; } // In some tests we need to force the journal to move to a next file - public void forceMoveNextFile() throws Exception - { + public void forceMoveNextFile() throws Exception { journalLock.readLock().lock(); - try - { + try { lockAppend.lock(); - try - { + try { moveNextFile(false); debugWait(); } - finally - { + finally { lockAppend.unlock(); } } - finally - { + finally { journalLock.readLock().unlock(); } } - public void perfBlast(final int pages) - { + public void perfBlast(final int pages) { new PerfBlast(pages).start(); } // ActiveMQComponent implementation // --------------------------------------------------- - public synchronized boolean isStarted() - { + public synchronized boolean isStarted() { return state != JournalState.STOPPED; } - public synchronized void start() - { - if (state != JournalState.STOPPED) - { + public synchronized void start() { + if (state != JournalState.STOPPED) { throw new IllegalStateException("Journal " + this + " is not stopped, state is " + state); } - filesExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() - { + filesExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() { - public Thread newThread(final Runnable r) - { + public Thread newThread(final Runnable r) { return new Thread(r, "JournalImpl::FilesExecutor"); } }); - compactorExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() - { + compactorExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() { - public Thread newThread(final Runnable r) - { + public Thread newThread(final Runnable r) { return new Thread(r, "JournalImpl::CompactorExecutor"); } }); @@ -2398,28 +2064,22 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal setJournalState(JournalState.STARTED); } - public synchronized void stop() throws Exception - { - if (state == JournalState.STOPPED) - { + public synchronized void stop() throws Exception { + if (state == JournalState.STOPPED) { throw new IllegalStateException("Journal is already stopped"); } - journalLock.writeLock().lock(); - try - { + try { lockAppend.lock(); - try - { + try { setJournalState(JournalState.STOPPED); compactorExecutor.shutdown(); - if (!compactorExecutor.awaitTermination(120, TimeUnit.SECONDS)) - { + if (!compactorExecutor.awaitTermination(120, TimeUnit.SECONDS)) { ActiveMQJournalLogger.LOGGER.couldNotStopCompactor(); } @@ -2427,27 +2087,22 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal filesRepository.setExecutor(null); - if (!filesExecutor.awaitTermination(60, TimeUnit.SECONDS)) - { + if (!filesExecutor.awaitTermination(60, TimeUnit.SECONDS)) { ActiveMQJournalLogger.LOGGER.couldNotStopJournalExecutor(); } - try - { - for (CountDownLatch latch : latches) - { + try { + for (CountDownLatch latch : latches) { latch.countDown(); } } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQJournalLogger.LOGGER.warn(e.getMessage(), e); } fileFactory.deactivateBuffer(); - if (currentFile != null && currentFile.getFile().isOpen()) - { + if (currentFile != null && currentFile.getFile().isOpen()) { currentFile.getFile().close(); } @@ -2457,50 +2112,41 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal currentFile = null; } - finally - { + finally { lockAppend.unlock(); } } - finally - { + finally { journalLock.writeLock().unlock(); } } - public int getNumberOfRecords() - { + public int getNumberOfRecords() { return records.size(); } - protected SequentialFile createControlFile(final List files, final List newFiles, - final Pair cleanupRename) throws Exception - { + final Pair cleanupRename) throws Exception { ArrayList> cleanupList; - if (cleanupRename == null) - { + if (cleanupRename == null) { cleanupList = null; } - else - { + else { cleanupList = new ArrayList>(); cleanupList.add(cleanupRename); } return AbstractJournalUpdateTask.writeControlFile(fileFactory, files, newFiles, cleanupList); } - protected void deleteControlFile(final SequentialFile controlFile) throws Exception - { + protected void deleteControlFile(final SequentialFile controlFile) throws Exception { controlFile.delete(); } /** * being protected as testcases can override this method */ - protected void renameFiles(final List oldFiles, final List newFiles) throws Exception - { + protected void renameFiles(final List oldFiles, final List newFiles) throws Exception { // addFreeFiles has to be called through filesExecutor, or the fileID on the orderedFiles may end up in a wrong // order @@ -2509,26 +2155,19 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal final CountDownLatch done = newLatch(1); - filesExecutor.execute(new Runnable() - { - public void run() - { - try - { - for (JournalFile file : oldFiles) - { - try - { + filesExecutor.execute(new Runnable() { + public void run() { + try { + for (JournalFile file : oldFiles) { + try { filesRepository.addFreeFile(file, false); } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQJournalLogger.LOGGER.errorReinitializingFile(e, file); } } } - finally - { + finally { done.countDown(); } } @@ -2539,8 +2178,7 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal // what could cause a duplicate in case of a crash after the CTR is deleted and before the file is initialized awaitLatch(done, -1); - for (JournalFile file : newFiles) - { + for (JournalFile file : newFiles) { String newName = JournalImpl.renameExtensionFile(file.getFile().getFileName(), ".cmp"); file.getFile().renameTo(newName); } @@ -2551,8 +2189,7 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal * @param name * @return */ - protected static String renameExtensionFile(String name, final String extension) - { + protected static String renameExtensionFile(String name, final String extension) { name = name.substring(0, name.lastIndexOf(extension)); return name; } @@ -2560,23 +2197,20 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal /** * This is an interception point for testcases, when the compacted files are written, before replacing the data structures */ - protected void onCompactStart() throws Exception - { + protected void onCompactStart() throws Exception { } /** * This is an interception point for testcases, when the compacted files are written, to be called * as soon as the compactor gets a writeLock */ - protected void onCompactLockingTheJournal() throws Exception - { + protected void onCompactLockingTheJournal() throws Exception { } /** * This is an interception point for testcases, when the compacted files are written, before replacing the data structures */ - protected void onCompactDone() - { + protected void onCompactDone() { } // Private @@ -2599,35 +2233,29 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal private boolean checkTransactionHealth(final JournalFile currentFile, final JournalTransaction journalTransaction, final List orderedFiles, - final int numberOfRecords) - { + final int numberOfRecords) { return journalTransaction.getCounter(currentFile) == numberOfRecords; } - private static boolean isTransaction(final byte recordType) - { + private static boolean isTransaction(final byte recordType) { return recordType == JournalImpl.ADD_RECORD_TX || recordType == JournalImpl.UPDATE_RECORD_TX || recordType == JournalImpl.DELETE_RECORD_TX || JournalImpl.isCompleteTransaction(recordType); } - private static boolean isCompleteTransaction(final byte recordType) - { + private static boolean isCompleteTransaction(final byte recordType) { return recordType == JournalImpl.COMMIT_RECORD || recordType == JournalImpl.PREPARE_RECORD || recordType == JournalImpl.ROLLBACK_RECORD; } - private static boolean isContainsBody(final byte recordType) - { + private static boolean isContainsBody(final byte recordType) { return recordType >= JournalImpl.ADD_RECORD && recordType <= JournalImpl.DELETE_RECORD_TX; } - private static int getRecordSize(final byte recordType, final int journalVersion) - { + private static int getRecordSize(final byte recordType, final int journalVersion) { // The record size (without the variable portion) int recordSize = 0; - switch (recordType) - { + switch (recordType) { case ADD_RECORD: recordSize = JournalImpl.SIZE_ADD_RECORD; break; @@ -2661,12 +2289,10 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal throw new IllegalStateException("Record other than expected"); } - if (journalVersion >= 2) - { + if (journalVersion >= 2) { return recordSize + 1; } - else - { + else { return recordSize; } } @@ -2676,36 +2302,30 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal * @return * @throws Exception */ - private JournalFileImpl readFileHeader(final SequentialFile file) throws Exception - { + private JournalFileImpl readFileHeader(final SequentialFile file) throws Exception { ByteBuffer bb = fileFactory.newBuffer(JournalImpl.SIZE_HEADER); file.read(bb); int journalVersion = bb.getInt(); - if (journalVersion != JournalImpl.FORMAT_VERSION) - { + if (journalVersion != JournalImpl.FORMAT_VERSION) { boolean isCompatible = false; - for (int v : JournalImpl.COMPATIBLE_VERSIONS) - { - if (v == journalVersion) - { + for (int v : JournalImpl.COMPATIBLE_VERSIONS) { + if (v == journalVersion) { isCompatible = true; } } - if (!isCompatible) - { + if (!isCompatible) { throw ActiveMQJournalBundle.BUNDLE.journalFileMisMatch(); } } int readUserVersion = bb.getInt(); - if (readUserVersion != userVersion) - { + if (readUserVersion != userVersion) { throw ActiveMQJournalBundle.BUNDLE.journalDifferentVersion(); } @@ -2726,15 +2346,13 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal public static int initFileHeader(final SequentialFileFactory fileFactory, final SequentialFile sequentialFile, final int userVersion, - final long fileID) throws Exception - { + final long fileID) throws Exception { // We don't need to release buffers while writing. ByteBuffer bb = fileFactory.newBuffer(JournalImpl.SIZE_HEADER); ActiveMQBuffer buffer = ActiveMQBuffers.wrappedBuffer(bb); - try - { + try { JournalImpl.writeHeader(buffer, userVersion, fileID); bb.rewind(); @@ -2746,8 +2364,7 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal sequentialFile.writeDirect(bb, true); return bufferSize; } - finally - { + finally { // release it by first unwrap the unreleasable buffer and then release it. buffer.byteBuf().unwrap().release(); } @@ -2758,8 +2375,7 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal * @param userVersion * @param fileID */ - public static void writeHeader(final ActiveMQBuffer buffer, final int userVersion, final long fileID) - { + public static void writeHeader(final ActiveMQBuffer buffer, final int userVersion, final long fileID) { buffer.writeInt(JournalImpl.FORMAT_VERSION); buffer.writeInt(userVersion); @@ -2776,8 +2392,7 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal final boolean completeTransaction, final boolean sync, final JournalTransaction tx, - final IOCallback parameterCallback) throws Exception - { + final IOCallback parameterCallback) throws Exception { checkJournalIsLoaded(); final IOCallback callback; @@ -2786,47 +2401,39 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal switchFileIfNecessary(size); - if (tx != null) - { + if (tx != null) { // The callback of a transaction has to be taken inside the lock, // when we guarantee the currentFile will not be changed, // since we individualize the callback per file - if (fileFactory.isSupportsCallbacks()) - { + if (fileFactory.isSupportsCallbacks()) { // Set the delegated callback as a parameter TransactionCallback txcallback = tx.getCallback(currentFile); - if (parameterCallback != null) - { + if (parameterCallback != null) { txcallback.setDelegateCompletion(parameterCallback); } callback = txcallback; } - else - { + else { callback = null; } // We need to add the number of records on currentFile if prepare or commit - if (completeTransaction) - { + if (completeTransaction) { // Filling the number of pendingTransactions at the current file tx.fillNumberOfRecords(currentFile, encoder); } } - else - { + else { callback = parameterCallback; } // Adding fileID encoder.setFileID(currentFile.getRecordID()); - if (callback != null) - { + if (callback != null) { currentFile.getFile().write(encoder, sync, callback); } - else - { + else { currentFile.getFile().write(encoder, sync); } @@ -2834,28 +2441,20 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal } @Override - void scheduleReclaim() - { - if (state != JournalState.LOADED) - { + void scheduleReclaim() { + if (state != JournalState.LOADED) { return; } - if (isAutoReclaim() && !compactorRunning.get()) - { - compactorExecutor.execute(new Runnable() - { - public void run() - { - try - { - if (!checkReclaimStatus()) - { + if (isAutoReclaim() && !compactorRunning.get()) { + compactorExecutor.execute(new Runnable() { + public void run() { + try { + if (!checkReclaimStatus()) { checkCompact(); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQJournalLogger.LOGGER.errorSchedulingCompacting(e); } } @@ -2863,18 +2462,15 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal } } - private JournalTransaction getTransactionInfo(final long txID) - { + private JournalTransaction getTransactionInfo(final long txID) { JournalTransaction tx = transactions.get(txID); - if (tx == null) - { + if (tx == null) { tx = new JournalTransaction(txID, this); JournalTransaction trans = transactions.putIfAbsent(txID, tx); - if (trans != null) - { + if (trans != null) { tx = trans; } } @@ -2885,43 +2481,35 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal /** * @throws Exception */ - private void checkControlFile() throws Exception - { + private void checkControlFile() throws Exception { ArrayList dataFiles = new ArrayList(); ArrayList newFiles = new ArrayList(); ArrayList> renames = new ArrayList>(); SequentialFile controlFile = JournalCompactor.readControlFile(fileFactory, dataFiles, newFiles, renames); - if (controlFile != null) - { - for (String dataFile : dataFiles) - { + if (controlFile != null) { + for (String dataFile : dataFiles) { SequentialFile file = fileFactory.createSequentialFile(dataFile); - if (file.exists()) - { + if (file.exists()) { file.delete(); } } - for (String newFile : newFiles) - { + for (String newFile : newFiles) { SequentialFile file = fileFactory.createSequentialFile(newFile); - if (file.exists()) - { + if (file.exists()) { final String originalName = file.getFileName(); final String newName = originalName.substring(0, originalName.lastIndexOf(".cmp")); file.renameTo(newName); } } - for (Pair rename : renames) - { + for (Pair rename : renames) { SequentialFile fileTmp = fileFactory.createSequentialFile(rename.getA()); SequentialFile fileTo = fileFactory.createSequentialFile(rename.getB()); // We should do the rename only if the tmp file still exist, or else we could // delete a valid file depending on where the crash occurred during the control file delete - if (fileTmp.exists()) - { + if (fileTmp.exists()) { fileTo.delete(); fileTmp.renameTo(rename.getB()); } @@ -2940,16 +2528,13 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal /** * @throws Exception */ - private void cleanupTmpFiles(final String extension) throws Exception - { + private void cleanupTmpFiles(final String extension) throws Exception { List leftFiles = fileFactory.listFiles(getFileExtension() + extension); - if (leftFiles.size() > 0) - { + if (leftFiles.size() > 0) { ActiveMQJournalLogger.LOGGER.tempFilesLeftOpen(); - for (String fileToDelete : leftFiles) - { + for (String fileToDelete : leftFiles) { ActiveMQJournalLogger.LOGGER.deletingOrphanedFile(fileToDelete); SequentialFile file = fileFactory.createSequentialFile(fileToDelete); file.delete(); @@ -2957,14 +2542,11 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal } } - private static boolean isInvalidSize(final int fileSize, final int bufferPos, final int size) - { - if (size < 0) - { + private static boolean isInvalidSize(final int fileSize, final int bufferPos, final int size) { + if (size < 0) { return true; } - else - { + else { final int position = bufferPos + size; return position > fileSize || position < 0; @@ -2976,10 +2558,9 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal // --------------------------------------------------------------------------- // Used on Load - private static final class TransactionHolder - { - public TransactionHolder(final long id) - { + private static final class TransactionHolder { + + public TransactionHolder(final long id) { transactionID = id; } @@ -2997,12 +2578,11 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal } - private static final class JournalFileComparator implements Comparator, Serializable - { + private static final class JournalFileComparator implements Comparator, Serializable { + private static final long serialVersionUID = -6264728973604070321L; - public int compare(final JournalFile f1, final JournalFile f2) - { + public int compare(final JournalFile f1, final JournalFile f2) { long id1 = f1.getFileID(); long id2 = f2.getFileID(); @@ -3010,71 +2590,58 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal } } - private final class PerfBlast extends Thread - { + private final class PerfBlast extends Thread { + private final int pages; - private PerfBlast(final int pages) - { + private PerfBlast(final int pages) { super("activemq-perfblast-thread"); this.pages = pages; } @Override - public void run() - { + public void run() { lockAppend.lock(); - try - { + try { final ByteArrayEncoding byteEncoder = new ByteArrayEncoding(new byte[128 * 1024]); - JournalInternalRecord blastRecord = new JournalInternalRecord() - { + JournalInternalRecord blastRecord = new JournalInternalRecord() { @Override - public int getEncodeSize() - { + public int getEncodeSize() { return byteEncoder.getEncodeSize(); } - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { byteEncoder.encode(buffer); } }; - for (int i = 0; i < pages; i++) - { + for (int i = 0; i < pages; i++) { appendRecord(blastRecord, false, false, null, null); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQJournalLogger.LOGGER.failedToPerfBlast(e); } - finally - { + finally { lockAppend.unlock(); } } } - public final void synchronizationLock() - { + public final void synchronizationLock() { compactorLock.writeLock().lock(); journalLock.writeLock().lock(); } - public final void synchronizationUnlock() - { - try - { + public final void synchronizationUnlock() { + try { compactorLock.writeLock().unlock(); } - finally - { + finally { journalLock.writeLock().unlock(); } } @@ -3089,30 +2656,25 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal * @throws Exception */ @Override - public synchronized Map createFilesForBackupSync(long[] fileIds) throws Exception - { + public synchronized Map createFilesForBackupSync(long[] fileIds) throws Exception { synchronizationLock(); - try - { + try { Map map = new HashMap(); long maxID = -1; - for (long id : fileIds) - { + for (long id : fileIds) { maxID = Math.max(maxID, id); map.put(Long.valueOf(id), filesRepository.createRemoteBackupSyncFile(id)); } filesRepository.setNextFileID(maxID); return map; } - finally - { + finally { synchronizationUnlock(); } } @Override - public SequentialFileFactory getFileFactory() - { + public SequentialFileFactory getFileFactory() { return fileFactory; } @@ -3121,8 +2683,7 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal * @return * @throws Exception */ - protected JournalFile setUpCurrentFile(int lastDataPos) throws Exception - { + protected JournalFile setUpCurrentFile(int lastDataPos) throws Exception { // Create any more files we need filesRepository.ensureMinFiles(); @@ -3130,14 +2691,12 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal // The current file is the last one that has data currentFile = filesRepository.pollLastDataFile(); - if (currentFile != null) - { + if (currentFile != null) { if (!currentFile.getFile().isOpen()) currentFile.getFile().open(); currentFile.getFile().position(currentFile.getFile().calculateBlockStart(lastDataPos)); } - else - { + else { currentFile = filesRepository.getFreeFile(); filesRepository.openFile(currentFile, true); } @@ -3153,21 +2712,17 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal * @return * @throws Exception */ - protected JournalFile switchFileIfNecessary(int size) throws Exception - { + protected JournalFile switchFileIfNecessary(int size) throws Exception { // We take into account the fileID used on the Header - if (size > fileSize - currentFile.getFile().calculateBlockStart(JournalImpl.SIZE_HEADER)) - { + if (size > fileSize - currentFile.getFile().calculateBlockStart(JournalImpl.SIZE_HEADER)) { throw new IllegalArgumentException("Record is too large to store " + size); } - if (!currentFile.getFile().fits(size)) - { + if (!currentFile.getFile().fits(size)) { moveNextFile(true); // The same check needs to be done at the new file also - if (!currentFile.getFile().fits(size)) - { + if (!currentFile.getFile().fits(size)) { // Sanity check, this should never happen throw new IllegalStateException("Invalid logic on buffer allocation"); } @@ -3175,10 +2730,8 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal return currentFile; } - private CountDownLatch newLatch(int countDown) - { - if (state == JournalState.STOPPED) - { + private CountDownLatch newLatch(int countDown) { + if (state == JournalState.STOPPED) { throw new RuntimeException("Server is not started"); } CountDownLatch latch = new CountDownLatch(countDown); @@ -3186,27 +2739,21 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal return latch; } - private void awaitLatch(CountDownLatch latch, int timeout) throws InterruptedException - { - try - { - if (timeout < 0) - { + private void awaitLatch(CountDownLatch latch, int timeout) throws InterruptedException { + try { + if (timeout < 0) { latch.await(); } - else - { + else { latch.await(timeout, TimeUnit.SECONDS); } // in case of an interrupted server, we need to make sure we don't proceed on anything - if (state == JournalState.STOPPED) - { + if (state == JournalState.STOPPED) { throw new RuntimeException("Server is not started"); } } - finally - { + finally { latches.remove(latch); } } @@ -3214,19 +2761,16 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal /** * You need to guarantee lock.acquire() before calling this method! */ - private void moveNextFile(final boolean scheduleReclaim) throws Exception - { + private void moveNextFile(final boolean scheduleReclaim) throws Exception { filesRepository.closeFile(currentFile); currentFile = filesRepository.openFile(); - if (scheduleReclaim) - { + if (scheduleReclaim) { scheduleReclaim(); } - if (trace) - { + if (trace) { ActiveMQJournalLogger.LOGGER.trace("Moving next file " + currentFile); } @@ -3234,26 +2778,21 @@ public class JournalImpl extends JournalBase implements TestableJournal, Journal } @Override - public void replicationSyncPreserveOldFiles() - { + public void replicationSyncPreserveOldFiles() { setAutoReclaim(false); } @Override - public void replicationSyncFinished() - { + public void replicationSyncFinished() { setAutoReclaim(true); } @Override - public void testCompact() - { - try - { + public void testCompact() { + try { scheduleCompactAndBlock(60); } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalReaderCallback.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalReaderCallback.java index 2f627db9e7..ae14ebdcdf 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalReaderCallback.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalReaderCallback.java @@ -18,8 +18,8 @@ package org.apache.activemq.artemis.core.journal.impl; import org.apache.activemq.artemis.core.journal.RecordInfo; -public interface JournalReaderCallback -{ +public interface JournalReaderCallback { + void onReadAddRecord(RecordInfo info) throws Exception; /** diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalReaderCallbackAbstract.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalReaderCallbackAbstract.java index 0214912e54..7bf9d0f460 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalReaderCallbackAbstract.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalReaderCallbackAbstract.java @@ -18,47 +18,38 @@ package org.apache.activemq.artemis.core.journal.impl; import org.apache.activemq.artemis.core.journal.RecordInfo; -public class JournalReaderCallbackAbstract implements JournalReaderCallback -{ +public class JournalReaderCallbackAbstract implements JournalReaderCallback { - public void markAsDataFile(final JournalFile file) - { + public void markAsDataFile(final JournalFile file) { } - public void onReadAddRecord(final RecordInfo info) throws Exception - { + public void onReadAddRecord(final RecordInfo info) throws Exception { } - public void onReadAddRecordTX(final long transactionID, final RecordInfo recordInfo) throws Exception - { + public void onReadAddRecordTX(final long transactionID, final RecordInfo recordInfo) throws Exception { } - public void onReadCommitRecord(final long transactionID, final int numberOfRecords) throws Exception - { + public void onReadCommitRecord(final long transactionID, final int numberOfRecords) throws Exception { } - public void onReadDeleteRecord(final long recordID) throws Exception - { + public void onReadDeleteRecord(final long recordID) throws Exception { } - public void onReadDeleteRecordTX(final long transactionID, final RecordInfo recordInfo) throws Exception - { + public void onReadDeleteRecordTX(final long transactionID, final RecordInfo recordInfo) throws Exception { } - public void onReadPrepareRecord(final long transactionID, final byte[] extraData, final int numberOfRecords) throws Exception - { + public void onReadPrepareRecord(final long transactionID, + final byte[] extraData, + final int numberOfRecords) throws Exception { } - public void onReadRollbackRecord(final long transactionID) throws Exception - { + public void onReadRollbackRecord(final long transactionID) throws Exception { } - public void onReadUpdateRecord(final RecordInfo recordInfo) throws Exception - { + public void onReadUpdateRecord(final RecordInfo recordInfo) throws Exception { } - public void onReadUpdateRecordTX(final long transactionID, final RecordInfo recordInfo) throws Exception - { + public void onReadUpdateRecordTX(final long transactionID, final RecordInfo recordInfo) throws Exception { } } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalRecord.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalRecord.java index 9875cddf8a..a7d4169d4d 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalRecord.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalRecord.java @@ -26,17 +26,16 @@ import org.apache.activemq.artemis.api.core.Pair; * Note: This class used to be called PosFiles * * Used on the ref-count for reclaiming - * */ -public class JournalRecord -{ + */ +public class JournalRecord { + private final JournalFile addFile; private final int size; private List> updateFiles; - public JournalRecord(final JournalFile addFile, final int size) - { + public JournalRecord(final JournalFile addFile, final int size) { this.addFile = addFile; this.size = size; @@ -46,10 +45,8 @@ public class JournalRecord addFile.addSize(size); } - void addUpdateFile(final JournalFile updateFile, final int size) - { - if (updateFiles == null) - { + void addUpdateFile(final JournalFile updateFile, final int size) { + if (updateFiles == null) { updateFiles = new ArrayList>(); } @@ -60,15 +57,12 @@ public class JournalRecord updateFile.addSize(size); } - void delete(final JournalFile file) - { + void delete(final JournalFile file) { file.incNegCount(addFile); addFile.decSize(size); - if (updateFiles != null) - { - for (Pair updFile : updateFiles) - { + if (updateFiles != null) { + for (Pair updFile : updateFiles) { file.incNegCount(updFile.getA()); updFile.getA().decSize(updFile.getB()); } @@ -76,16 +70,13 @@ public class JournalRecord } @Override - public String toString() - { + public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append("JournalRecord(add=" + addFile.getFile().getFileName()); - if (updateFiles != null) - { + if (updateFiles != null) { - for (Pair update : updateFiles) - { + for (Pair update : updateFiles) { buffer.append(", update=" + update.getA().getFile().getFileName()); } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalRecordProvider.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalRecordProvider.java index fe1024375e..6c5107a752 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalRecordProvider.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalRecordProvider.java @@ -25,8 +25,8 @@ import java.util.Map; * * when a commit is read, the JournalTransaction will inquire the JournalCompactor about the existent records */ -public interface JournalRecordProvider -{ +public interface JournalRecordProvider { + JournalCompactor getCompactor(); Map getRecords(); diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalTransaction.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalTransaction.java index 51793fb39a..8a29d600e7 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalTransaction.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalTransaction.java @@ -27,8 +27,7 @@ import java.util.concurrent.atomic.AtomicInteger; import org.apache.activemq.artemis.api.core.ActiveMQExceptionType; import org.apache.activemq.artemis.core.journal.impl.dataformat.JournalInternalRecord; -public class JournalTransaction -{ +public class JournalTransaction { private JournalRecordProvider journal; @@ -52,55 +51,45 @@ public class JournalTransaction private final AtomicInteger counter = new AtomicInteger(); - public JournalTransaction(final long id, final JournalRecordProvider journal) - { + public JournalTransaction(final long id, final JournalRecordProvider journal) { this.id = id; this.journal = journal; } - public void replaceRecordProvider(final JournalRecordProvider provider) - { + public void replaceRecordProvider(final JournalRecordProvider provider) { journal = provider; } /** * @return the id */ - public long getId() - { + public long getId() { return id; } - public int getCounter(final JournalFile file) - { + public int getCounter(final JournalFile file) { return internalgetCounter(file).intValue(); } - public void incCounter(final JournalFile file) - { + public void incCounter(final JournalFile file) { internalgetCounter(file).incrementAndGet(); } - public long[] getPositiveArray() - { - if (pos == null) - { + public long[] getPositiveArray() { + if (pos == null) { return new long[0]; } - else - { + else { int i = 0; long[] ids = new long[pos.size()]; - for (JournalUpdate el : pos) - { + for (JournalUpdate el : pos) { ids[i++] = el.getId(); } return ids; } } - public void setCompacting() - { + public void setCompacting() { compacting = true; // Everything is cleared on the transaction... @@ -108,33 +97,28 @@ public class JournalTransaction clear(); } - /** This is used to merge transactions from compacting */ - public void merge(final JournalTransaction other) - { - if (other.pos != null) - { - if (pos == null) - { + /** + * This is used to merge transactions from compacting + */ + public void merge(final JournalTransaction other) { + if (other.pos != null) { + if (pos == null) { pos = new ArrayList(); } pos.addAll(other.pos); } - if (other.neg != null) - { - if (neg == null) - { + if (other.neg != null) { + if (neg == null) { neg = new ArrayList(); } neg.addAll(other.neg); } - if (other.pendingFiles != null) - { - if (pendingFiles == null) - { + if (other.pendingFiles != null) { + if (pendingFiles == null) { pendingFiles = new HashSet(); } @@ -147,29 +131,24 @@ public class JournalTransaction /** * */ - public void clear() - { + public void clear() { // / Compacting is recreating all the previous files and everything // / so we just clear the list of previous files, previous pos and previous adds // / The transaction may be working at the top from now - if (pendingFiles != null) - { + if (pendingFiles != null) { pendingFiles.clear(); } - if (callbackList != null) - { + if (callbackList != null) { callbackList.clear(); } - if (pos != null) - { + if (pos != null) { pos.clear(); } - if (neg != null) - { + if (neg != null) { neg.clear(); } @@ -184,28 +163,23 @@ public class JournalTransaction * @param currentFile * @param data */ - public void fillNumberOfRecords(final JournalFile currentFile, final JournalInternalRecord data) - { + public void fillNumberOfRecords(final JournalFile currentFile, final JournalInternalRecord data) { data.setNumberOfRecords(getCounter(currentFile)); } - public TransactionCallback getCallback(final JournalFile file) throws Exception - { - if (callbackList == null) - { + public TransactionCallback getCallback(final JournalFile file) throws Exception { + if (callbackList == null) { callbackList = new HashMap(); } currentCallback = callbackList.get(file); - if (currentCallback == null) - { + if (currentCallback == null) { currentCallback = new TransactionCallback(); callbackList.put(file, currentCallback); } - if (currentCallback.getErrorMessage() != null) - { + if (currentCallback.getErrorMessage() != null) { throw ActiveMQExceptionType.createException(currentCallback.getErrorCode(), currentCallback.getErrorMessage()); } @@ -214,28 +188,24 @@ public class JournalTransaction return currentCallback; } - public void addPositive(final JournalFile file, final long id, final int size) - { + public void addPositive(final JournalFile file, final long id, final int size) { incCounter(file); addFile(file); - if (pos == null) - { + if (pos == null) { pos = new ArrayList(); } pos.add(new JournalUpdate(file, id, size)); } - public void addNegative(final JournalFile file, final long id) - { + public void addNegative(final JournalFile file, final long id) { incCounter(file); addFile(file); - if (neg == null) - { + if (neg == null) { neg = new ArrayList(); } @@ -244,58 +214,45 @@ public class JournalTransaction /** * The caller of this method needs to guarantee appendLock.lock at the journal. (unless this is being called from load what is a single thread process). - * */ - public void commit(final JournalFile file) - { + */ + public void commit(final JournalFile file) { JournalCompactor compactor = journal.getCompactor(); - if (compacting) - { + if (compacting) { compactor.addCommandCommit(this, file); } - else - { + else { - if (pos != null) - { - for (JournalUpdate trUpdate : pos) - { + if (pos != null) { + for (JournalUpdate trUpdate : pos) { JournalRecord posFiles = journal.getRecords().get(trUpdate.id); - if (compactor != null && compactor.lookupRecord(trUpdate.id)) - { + if (compactor != null && compactor.lookupRecord(trUpdate.id)) { // This is a case where the transaction was opened after compacting was started, // but the commit arrived while compacting was working // We need to cache the counter update, so compacting will take the correct files when it is done compactor.addCommandUpdate(trUpdate.id, trUpdate.file, trUpdate.size); } - else if (posFiles == null) - { + else if (posFiles == null) { posFiles = new JournalRecord(trUpdate.file, trUpdate.size); journal.getRecords().put(trUpdate.id, posFiles); } - else - { + else { posFiles.addUpdateFile(trUpdate.file, trUpdate.size); } } } - if (neg != null) - { - for (JournalUpdate trDelete : neg) - { - if (compactor != null) - { + if (neg != null) { + for (JournalUpdate trDelete : neg) { + if (compactor != null) { compactor.addCommandDelete(trDelete.id, trDelete.file); } - else - { + else { JournalRecord posFiles = journal.getRecords().remove(trDelete.id); - if (posFiles != null) - { + if (posFiles != null) { posFiles.delete(trDelete.file); } } @@ -305,29 +262,25 @@ public class JournalTransaction // Now add negs for the pos we added in each file in which there were // transactional operations - for (JournalFile jf : pendingFiles) - { + for (JournalFile jf : pendingFiles) { file.incNegCount(jf); } } } - public void waitCallbacks() throws InterruptedException - { - if (callbackList != null) - { - for (TransactionCallback callback : callbackList.values()) - { + public void waitCallbacks() throws InterruptedException { + if (callbackList != null) { + for (TransactionCallback callback : callbackList.values()) { callback.waitCompletion(); } } } - /** Wait completion at the latest file only */ - public void waitCompletion() throws Exception - { - if (currentCallback != null) - { + /** + * Wait completion at the latest file only + */ + public void waitCompletion() throws Exception { + if (currentCallback != null) { currentCallback.waitCompletion(); } } @@ -335,17 +288,14 @@ public class JournalTransaction /** * The caller of this method needs to guarantee appendLock.lock before calling this method if being used outside of the lock context. * or else potFilesMap could be affected - * */ - public void rollback(final JournalFile file) - { + */ + public void rollback(final JournalFile file) { JournalCompactor compactor = journal.getCompactor(); - if (compacting && compactor != null) - { + if (compacting && compactor != null) { compactor.addCommandRollback(this, file); } - else - { + else { // Now add negs for the pos we added in each file in which there were // transactional operations // Note that we do this on rollback as we do on commit, since we need @@ -356,8 +306,7 @@ public class JournalTransaction // just left with a prepare when the tx // has actually been rolled back - for (JournalFile jf : pendingFiles) - { + for (JournalFile jf : pendingFiles) { file.incNegCount(jf); } } @@ -366,52 +315,44 @@ public class JournalTransaction /** * The caller of this method needs to guarantee appendLock.lock before calling this method if being used outside of the lock context. * or else potFilesMap could be affected - * */ - public void prepare(final JournalFile file) - { + */ + public void prepare(final JournalFile file) { // We don't want the prepare record getting deleted before time addFile(file); } - /** Used by load, when the transaction was not loaded correctly */ - public void forget() - { + /** + * Used by load, when the transaction was not loaded correctly + */ + public void forget() { // The transaction was not committed or rolled back in the file, so we // reverse any pos counts we added - for (JournalFile jf : pendingFiles) - { + for (JournalFile jf : pendingFiles) { jf.decPosCount(); } } @Override - public String toString() - { + public String toString() { return "JournalTransaction(" + id + ")"; } - private AtomicInteger internalgetCounter(final JournalFile file) - { - if (lastFile != file) - - { + private AtomicInteger internalgetCounter(final JournalFile file) { + if (lastFile != file) { lastFile = file; counter.set(0); } return counter; } - private void addFile(final JournalFile file) - { - if (pendingFiles == null) - { + private void addFile(final JournalFile file) { + if (pendingFiles == null) { pendingFiles = new HashSet(); } - if (!pendingFiles.contains(file)) - { + if (!pendingFiles.contains(file)) { pendingFiles.add(file); // We add a pos for the transaction itself in the file - this @@ -421,8 +362,8 @@ public class JournalTransaction } } - private static class JournalUpdate - { + private static class JournalUpdate { + private final JournalFile file; long id; @@ -434,8 +375,7 @@ public class JournalTransaction * @param id * @param size */ - private JournalUpdate(final JournalFile file, final long id, final int size) - { + private JournalUpdate(final JournalFile file, final long id, final int size) { super(); this.file = file; this.id = id; @@ -445,8 +385,7 @@ public class JournalTransaction /** * @return the id */ - public long getId() - { + public long getId() { return id; } } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/Reclaimer.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/Reclaimer.java index 2a3e268904..0f559627a2 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/Reclaimer.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/Reclaimer.java @@ -16,11 +16,9 @@ */ package org.apache.activemq.artemis.core.journal.impl; - import org.apache.activemq.artemis.journal.ActiveMQJournalLogger; /** - * *

    The journal consists of an ordered list of journal files Fn where {@code 0 <= n <= N}

    * *

    A journal file can contain either positives (pos) or negatives (neg)

    @@ -34,19 +32,16 @@ import org.apache.activemq.artemis.journal.ActiveMQJournalLogger; *

    2) All pos that correspond to any neg in file Fn, must all live in any file Fm where {@code 0 <= m <= n} * which are also marked for deletion in the same pass of the algorithm.

    */ -public class Reclaimer -{ +public class Reclaimer { + private static boolean trace = ActiveMQJournalLogger.LOGGER.isTraceEnabled(); - private static void trace(final String message) - { + private static void trace(final String message) { ActiveMQJournalLogger.LOGGER.trace(message); } - public void scan(final JournalFile[] files) - { - for (int i = 0; i < files.length; i++) - { + public void scan(final JournalFile[] files) { + for (int i = 0; i < files.length; i++) { // First we evaluate criterion 1) JournalFile currentFile = files[i]; @@ -55,22 +50,18 @@ public class Reclaimer int totNeg = 0; - if (Reclaimer.trace) - { + if (Reclaimer.trace) { Reclaimer.trace("posCount on " + currentFile + " = " + posCount); } - for (int j = i; j < files.length; j++) - { - if (Reclaimer.trace) - { - if (files[j].getNegCount(currentFile) != 0) - { + for (int j = i; j < files.length; j++) { + if (Reclaimer.trace) { + if (files[j].getNegCount(currentFile) != 0) { Reclaimer.trace("Negative from " + files[j] + - " into " + - currentFile + - " = " + - files[j].getNegCount(currentFile)); + " into " + + currentFile + + " = " + + files[j].getNegCount(currentFile)); } } @@ -79,26 +70,20 @@ public class Reclaimer currentFile.setCanReclaim(true); - if (posCount <= totNeg) - { + if (posCount <= totNeg) { // Now we evaluate criterion 2) - for (int j = 0; j <= i; j++) - { + for (int j = 0; j <= i; j++) { JournalFile file = files[j]; int negCount = currentFile.getNegCount(file); - if (negCount != 0) - { - if (file.isCanReclaim()) - { + if (negCount != 0) { + if (file.isCanReclaim()) { // Ok } - else - { - if (Reclaimer.trace) - { + else { + if (Reclaimer.trace) { Reclaimer.trace(currentFile + " Can't be reclaimed because " + file + " has negative values"); } @@ -109,8 +94,7 @@ public class Reclaimer } } } - else - { + else { currentFile.setCanReclaim(false); } } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/SimpleWaitIOCallback.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/SimpleWaitIOCallback.java index 174772f5bd..0efdf8a487 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/SimpleWaitIOCallback.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/SimpleWaitIOCallback.java @@ -23,8 +23,8 @@ import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.api.core.ActiveMQExceptionType; import org.apache.activemq.artemis.journal.ActiveMQJournalLogger; -public final class SimpleWaitIOCallback extends SyncIOCompletion -{ +public final class SimpleWaitIOCallback extends SyncIOCompletion { + private final CountDownLatch latch = new CountDownLatch(1); private volatile String errorMessage; @@ -32,18 +32,15 @@ public final class SimpleWaitIOCallback extends SyncIOCompletion private volatile int errorCode = 0; @Override - public String toString() - { + public String toString() { return SimpleWaitIOCallback.class.getName(); } - public void done() - { + public void done() { latch.countDown(); } - public void onError(final int errorCode1, final String errorMessage1) - { + public void onError(final int errorCode1, final String errorMessage1) { this.errorCode = errorCode1; this.errorMessage = errorMessage1; @@ -54,28 +51,23 @@ public final class SimpleWaitIOCallback extends SyncIOCompletion } @Override - public void waitCompletion() throws InterruptedException, ActiveMQException - { - while (true) - { + public void waitCompletion() throws InterruptedException, ActiveMQException { + while (true) { if (latch.await(2, TimeUnit.SECONDS)) break; } - if (errorMessage != null) - { + if (errorMessage != null) { throw ActiveMQExceptionType.createException(errorCode, errorMessage); } return; } - public boolean waitCompletion(final long timeout) throws InterruptedException, ActiveMQException - { + public boolean waitCompletion(final long timeout) throws InterruptedException, ActiveMQException { boolean retValue = latch.await(timeout, TimeUnit.MILLISECONDS); - if (errorMessage != null) - { + if (errorMessage != null) { throw ActiveMQExceptionType.createException(errorCode, errorMessage); } @@ -83,7 +75,6 @@ public final class SimpleWaitIOCallback extends SyncIOCompletion } @Override - public void storeLineUp() - { + public void storeLineUp() { } } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/SyncIOCompletion.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/SyncIOCompletion.java index ae2af619da..d34c030f98 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/SyncIOCompletion.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/SyncIOCompletion.java @@ -21,8 +21,7 @@ import org.apache.activemq.artemis.core.journal.IOCompletion; /** * Internal class used to manage explicit syncs on the Journal through callbacks. */ -public abstract class SyncIOCompletion implements IOCompletion -{ +public abstract class SyncIOCompletion implements IOCompletion { // Constants ----------------------------------------------------- diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/TransactionCallback.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/TransactionCallback.java index 140927e007..3084dd50f0 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/TransactionCallback.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/TransactionCallback.java @@ -21,8 +21,8 @@ import java.util.concurrent.atomic.AtomicInteger; import org.apache.activemq.artemis.core.io.IOCallback; import org.apache.activemq.artemis.utils.ReusableLatch; -public class TransactionCallback implements IOCallback -{ +public class TransactionCallback implements IOCallback { + private final ReusableLatch countLatch = new ReusableLatch(); private volatile String errorMessage = null; @@ -35,17 +35,14 @@ public class TransactionCallback implements IOCallback private volatile IOCallback delegateCompletion; - public void countUp() - { + public void countUp() { up.incrementAndGet(); countLatch.countUp(); } - public void done() - { + public void done() { countLatch.countDown(); - if (++done == up.get() && delegateCompletion != null) - { + if (++done == up.get() && delegateCompletion != null) { final IOCallback delegateToCall = delegateCompletion; // We need to set the delegateCompletion to null first or blocking commits could miss a callback // What would affect mainly tests @@ -54,26 +51,22 @@ public class TransactionCallback implements IOCallback } } - public void waitCompletion() throws InterruptedException - { + public void waitCompletion() throws InterruptedException { countLatch.await(); - if (errorMessage != null) - { + if (errorMessage != null) { throw new IllegalStateException("Error on Transaction: " + errorCode + " - " + errorMessage); } } - public void onError(final int errorCode, final String errorMessage) - { + public void onError(final int errorCode, final String errorMessage) { this.errorMessage = errorMessage; this.errorCode = errorCode; countLatch.countDown(); - if (delegateCompletion != null) - { + if (delegateCompletion != null) { delegateCompletion.onError(errorCode, errorMessage); } } @@ -81,32 +74,28 @@ public class TransactionCallback implements IOCallback /** * @return the delegateCompletion */ - public IOCallback getDelegateCompletion() - { + public IOCallback getDelegateCompletion() { return delegateCompletion; } /** * @param delegateCompletion the delegateCompletion to set */ - public void setDelegateCompletion(final IOCallback delegateCompletion) - { + public void setDelegateCompletion(final IOCallback delegateCompletion) { this.delegateCompletion = delegateCompletion; } /** * @return the errorMessage */ - public String getErrorMessage() - { + public String getErrorMessage() { return errorMessage; } /** * @return the errorCode */ - public int getErrorCode() - { + public int getErrorCode() { return errorCode; } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/ByteArrayEncoding.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/ByteArrayEncoding.java index 3be9942ae1..be04bc8e61 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/ByteArrayEncoding.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/ByteArrayEncoding.java @@ -19,30 +19,25 @@ package org.apache.activemq.artemis.core.journal.impl.dataformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.journal.EncodingSupport; -public class ByteArrayEncoding implements EncodingSupport -{ +public class ByteArrayEncoding implements EncodingSupport { final byte[] data; - public ByteArrayEncoding(final byte[] data) - { + public ByteArrayEncoding(final byte[] data) { this.data = data; } // Public -------------------------------------------------------- - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { throw new IllegalStateException("operation not supported"); } - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { buffer.writeBytes(data); } - public int getEncodeSize() - { + public int getEncodeSize() { return data.length; } } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalAddRecord.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalAddRecord.java index 87d7e27dcd..69734bc97a 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalAddRecord.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalAddRecord.java @@ -20,8 +20,7 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.journal.EncodingSupport; import org.apache.activemq.artemis.core.journal.impl.JournalImpl; -public class JournalAddRecord extends JournalInternalRecord -{ +public class JournalAddRecord extends JournalInternalRecord { private final long id; @@ -36,8 +35,7 @@ public class JournalAddRecord extends JournalInternalRecord * @param recordType * @param record */ - public JournalAddRecord(final boolean add, final long id, final byte recordType, final EncodingSupport record) - { + public JournalAddRecord(final boolean add, final long id, final byte recordType, final EncodingSupport record) { this.id = id; this.record = record; @@ -48,14 +46,11 @@ public class JournalAddRecord extends JournalInternalRecord } @Override - public void encode(final ActiveMQBuffer buffer) - { - if (add) - { + public void encode(final ActiveMQBuffer buffer) { + if (add) { buffer.writeByte(JournalImpl.ADD_RECORD); } - else - { + else { buffer.writeByte(JournalImpl.UPDATE_RECORD); } @@ -75,8 +70,7 @@ public class JournalAddRecord extends JournalInternalRecord } @Override - public int getEncodeSize() - { + public int getEncodeSize() { return JournalImpl.SIZE_ADD_RECORD + record.getEncodeSize() + 1; } } \ No newline at end of file diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalAddRecordTX.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalAddRecordTX.java index ff22393940..2af8797a09 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalAddRecordTX.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalAddRecordTX.java @@ -20,8 +20,7 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.journal.EncodingSupport; import org.apache.activemq.artemis.core.journal.impl.JournalImpl; -public class JournalAddRecordTX extends JournalInternalRecord -{ +public class JournalAddRecordTX extends JournalInternalRecord { private final long txID; @@ -42,8 +41,7 @@ public class JournalAddRecordTX extends JournalInternalRecord final long txID, final long id, final byte recordType, - final EncodingSupport record) - { + final EncodingSupport record) { this.txID = txID; @@ -57,14 +55,11 @@ public class JournalAddRecordTX extends JournalInternalRecord } @Override - public void encode(final ActiveMQBuffer buffer) - { - if (add) - { + public void encode(final ActiveMQBuffer buffer) { + if (add) { buffer.writeByte(JournalImpl.ADD_RECORD_TX); } - else - { + else { buffer.writeByte(JournalImpl.UPDATE_RECORD_TX); } @@ -86,8 +81,7 @@ public class JournalAddRecordTX extends JournalInternalRecord } @Override - public int getEncodeSize() - { + public int getEncodeSize() { return JournalImpl.SIZE_ADD_RECORD_TX + record.getEncodeSize() + 1; } } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalCompleteRecordTX.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalCompleteRecordTX.java index 17a3d7b380..b0c2c49a2e 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalCompleteRecordTX.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalCompleteRecordTX.java @@ -34,12 +34,12 @@ import org.apache.activemq.artemis.core.journal.impl.JournalImpl; *

    * The commit operation itself is not included in this total. */ -public class JournalCompleteRecordTX extends JournalInternalRecord -{ - public enum TX_RECORD_TYPE - { +public class JournalCompleteRecordTX extends JournalInternalRecord { + + public enum TX_RECORD_TYPE { COMMIT, PREPARE; } + private final TX_RECORD_TYPE txRecordType; private final long txID; @@ -48,8 +48,9 @@ public class JournalCompleteRecordTX extends JournalInternalRecord private int numberOfRecords; - public JournalCompleteRecordTX(final TX_RECORD_TYPE isCommit, final long txID, final EncodingSupport transactionData) - { + public JournalCompleteRecordTX(final TX_RECORD_TYPE isCommit, + final long txID, + final EncodingSupport transactionData) { this.txRecordType = isCommit; this.txID = txID; @@ -58,14 +59,11 @@ public class JournalCompleteRecordTX extends JournalInternalRecord } @Override - public void encode(final ActiveMQBuffer buffer) - { - if (txRecordType == TX_RECORD_TYPE.COMMIT) - { + public void encode(final ActiveMQBuffer buffer) { + if (txRecordType == TX_RECORD_TYPE.COMMIT) { buffer.writeByte(JournalImpl.COMMIT_RECORD); } - else - { + else { buffer.writeByte(JournalImpl.PREPARE_RECORD); } @@ -77,13 +75,11 @@ public class JournalCompleteRecordTX extends JournalInternalRecord buffer.writeInt(numberOfRecords); - if (transactionData != null) - { + if (transactionData != null) { buffer.writeInt(transactionData.getEncodeSize()); } - if (transactionData != null) - { + if (transactionData != null) { transactionData.encode(buffer); } @@ -91,26 +87,21 @@ public class JournalCompleteRecordTX extends JournalInternalRecord } @Override - public void setNumberOfRecords(final int records) - { + public void setNumberOfRecords(final int records) { numberOfRecords = records; } @Override - public int getNumberOfRecords() - { + public int getNumberOfRecords() { return numberOfRecords; } @Override - public int getEncodeSize() - { - if (txRecordType == TX_RECORD_TYPE.COMMIT) - { + public int getEncodeSize() { + if (txRecordType == TX_RECORD_TYPE.COMMIT) { return JournalImpl.SIZE_COMPLETE_TRANSACTION_RECORD + 1; } - else - { + else { return JournalImpl.SIZE_PREPARE_RECORD + (transactionData != null ? transactionData.getEncodeSize() : 0) + 1; } } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalDeleteRecord.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalDeleteRecord.java index 00037ead07..06444eb7e5 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalDeleteRecord.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalDeleteRecord.java @@ -19,21 +19,18 @@ package org.apache.activemq.artemis.core.journal.impl.dataformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.journal.impl.JournalImpl; -public class JournalDeleteRecord extends JournalInternalRecord -{ +public class JournalDeleteRecord extends JournalInternalRecord { private final long id; /** * @param id */ - public JournalDeleteRecord(final long id) - { + public JournalDeleteRecord(final long id) { this.id = id; } - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { buffer.writeByte(JournalImpl.DELETE_RECORD); buffer.writeInt(fileID); @@ -46,8 +43,7 @@ public class JournalDeleteRecord extends JournalInternalRecord } @Override - public int getEncodeSize() - { + public int getEncodeSize() { return JournalImpl.SIZE_DELETE_RECORD + 1; } } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalDeleteRecordTX.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalDeleteRecordTX.java index 939d04d2c5..32dfc36472 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalDeleteRecordTX.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalDeleteRecordTX.java @@ -20,8 +20,7 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.journal.EncodingSupport; import org.apache.activemq.artemis.core.journal.impl.JournalImpl; -public class JournalDeleteRecordTX extends JournalInternalRecord -{ +public class JournalDeleteRecordTX extends JournalInternalRecord { private final long txID; @@ -34,8 +33,7 @@ public class JournalDeleteRecordTX extends JournalInternalRecord * @param id * @param record */ - public JournalDeleteRecordTX(final long txID, final long id, final EncodingSupport record) - { + public JournalDeleteRecordTX(final long txID, final long id, final EncodingSupport record) { this.id = id; this.txID = txID; @@ -44,8 +42,7 @@ public class JournalDeleteRecordTX extends JournalInternalRecord } @Override - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { buffer.writeByte(JournalImpl.DELETE_RECORD_TX); buffer.writeInt(fileID); @@ -58,8 +55,7 @@ public class JournalDeleteRecordTX extends JournalInternalRecord buffer.writeInt(record != null ? record.getEncodeSize() : 0); - if (record != null) - { + if (record != null) { record.encode(buffer); } @@ -67,8 +63,7 @@ public class JournalDeleteRecordTX extends JournalInternalRecord } @Override - public int getEncodeSize() - { + public int getEncodeSize() { return JournalImpl.SIZE_DELETE_RECORD_TX + (record != null ? record.getEncodeSize() : 0) + 1; } } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalInternalRecord.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalInternalRecord.java index 4449045e22..b05f1619bb 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalInternalRecord.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalInternalRecord.java @@ -19,50 +19,40 @@ package org.apache.activemq.artemis.core.journal.impl.dataformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.journal.EncodingSupport; -public abstract class JournalInternalRecord implements EncodingSupport -{ +public abstract class JournalInternalRecord implements EncodingSupport { protected int fileID; protected byte compactCount; - public int getFileID() - { + public int getFileID() { return fileID; } - public void setFileID(final int fileID) - { + public void setFileID(final int fileID) { this.fileID = fileID; } - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { } - public void setNumberOfRecords(final int records) - { + public void setNumberOfRecords(final int records) { } - public int getNumberOfRecords() - { + public int getNumberOfRecords() { return 0; } - public short getCompactCount() - { + public short getCompactCount() { return compactCount; } - public void setCompactCount(final short compactCount) - { - if (compactCount > Byte.MAX_VALUE) - { + public void setCompactCount(final short compactCount) { + if (compactCount > Byte.MAX_VALUE) { this.compactCount = Byte.MAX_VALUE; } - else - { - this.compactCount = (byte)compactCount; + else { + this.compactCount = (byte) compactCount; } } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalRollbackRecordTX.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalRollbackRecordTX.java index 3c9ab8a6f6..fe4391360f 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalRollbackRecordTX.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/dataformat/JournalRollbackRecordTX.java @@ -19,18 +19,16 @@ package org.apache.activemq.artemis.core.journal.impl.dataformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.journal.impl.JournalImpl; -public class JournalRollbackRecordTX extends JournalInternalRecord -{ +public class JournalRollbackRecordTX extends JournalInternalRecord { + private final long txID; - public JournalRollbackRecordTX(final long txID) - { + public JournalRollbackRecordTX(final long txID) { this.txID = txID; } @Override - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { buffer.writeByte(JournalImpl.ROLLBACK_RECORD); buffer.writeInt(fileID); buffer.writeByte(compactCount); @@ -40,8 +38,7 @@ public class JournalRollbackRecordTX extends JournalInternalRecord } @Override - public int getEncodeSize() - { + public int getEncodeSize() { return JournalImpl.SIZE_ROLLBACK_RECORD + 1; } } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/journal/ActiveMQJournalBundle.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/journal/ActiveMQJournalBundle.java index 91a4f04c43..474bf18a78 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/journal/ActiveMQJournalBundle.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/journal/ActiveMQJournalBundle.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.journal; - import org.apache.activemq.artemis.api.core.ActiveMQIOErrorException; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageBundle; @@ -30,19 +29,19 @@ import org.jboss.logging.Messages; * so 149000 to 149999 */ @MessageBundle(projectCode = "AMQ") -public interface ActiveMQJournalBundle -{ +public interface ActiveMQJournalBundle { + ActiveMQJournalBundle BUNDLE = Messages.getBundle(ActiveMQJournalBundle.class); - @Message(id = 149000, value = "failed to rename file {0} to {1}", format = Message.Format.MESSAGE_FORMAT) + @Message(id = 149000, value = "failed to rename file {0} to {1}", format = Message.Format.MESSAGE_FORMAT) ActiveMQIOErrorException ioRenameFileError(String name, String newFileName); - @Message(id = 149001, value = "Journal data belong to a different version") + @Message(id = 149001, value = "Journal data belong to a different version") ActiveMQIOErrorException journalDifferentVersion(); - @Message(id = 149002, value = "Journal files version mismatch. You should export the data from the previous version and import it as explained on the user''s manual") + @Message(id = 149002, value = "Journal files version mismatch. You should export the data from the previous version and import it as explained on the user''s manual") ActiveMQIOErrorException journalFileMisMatch(); - @Message(id = 149003, value = "File not opened") + @Message(id = 149003, value = "File not opened") ActiveMQIOErrorException fileNotOpened(); } diff --git a/artemis-journal/src/main/java/org/apache/activemq/artemis/journal/ActiveMQJournalLogger.java b/artemis-journal/src/main/java/org/apache/activemq/artemis/journal/ActiveMQJournalLogger.java index 4d2429da66..67574d1dff 100644 --- a/artemis-journal/src/main/java/org/apache/activemq/artemis/journal/ActiveMQJournalLogger.java +++ b/artemis-journal/src/main/java/org/apache/activemq/artemis/journal/ActiveMQJournalLogger.java @@ -39,8 +39,8 @@ import org.jboss.logging.annotations.MessageLogger; * so an INFO message would be 141000 to 141999 */ @MessageLogger(projectCode = "AMQ") -public interface ActiveMQJournalLogger extends BasicLogger -{ +public interface ActiveMQJournalLogger extends BasicLogger { + /** * The journal logger. */ @@ -72,9 +72,9 @@ public interface ActiveMQJournalLogger extends BasicLogger @LogMessage(level = Logger.Level.INFO) @Message(id = 141007, value = "Current File on the journal is <= the sequence file.getFileID={0} on the dataFiles" + - "\nCurrentfile.getFileId={1} while the file.getFileID()={2}" + - "\nIs same = ({3})", - format = Message.Format.MESSAGE_FORMAT) + "\nCurrentfile.getFileId={1} while the file.getFileID()={2}" + + "\nIs same = ({3})", + format = Message.Format.MESSAGE_FORMAT) void currentFile(Long fileID, Long id, Long fileFileID, Boolean b); @LogMessage(level = Logger.Level.INFO) @@ -91,7 +91,7 @@ public interface ActiveMQJournalLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 142001, value = "Could not get lock after 60 seconds on closing Asynchronous File: {0}", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void couldNotGetLock(String fileName); @LogMessage(level = Logger.Level.WARN) @@ -104,121 +104,121 @@ public interface ActiveMQJournalLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 142004, value = "Inconsistency during compacting: CommitRecord ID = {0} for an already committed transaction during compacting", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void inconsistencyDuringCompacting(Long transactionID); @LogMessage(level = Logger.Level.WARN) @Message(id = 142005, value = "Inconsistency during compacting: Delete record being read on an existent record (id={0})", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void inconsistencyDuringCompactingDelete(Long recordID); @LogMessage(level = Logger.Level.WARN) @Message(id = 142006, value = "Could not find add Record information for record {0} during compacting", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void compactingWithNoAddRecord(Long id); @LogMessage(level = Logger.Level.WARN) @Message(id = 142007, value = "Can not find record {0} during compact replay", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void noRecordDuringCompactReplay(Long id); @LogMessage(level = Logger.Level.WARN) @Message(id = 142008, value = "Could not remove file {0} from the list of data files", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void couldNotRemoveFile(JournalFile file); @LogMessage(level = Logger.Level.WARN) @Message(id = 142009, value = "Deleting {0} as it does not have the configured size", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void deletingFile(JournalFile file); @LogMessage(level = Logger.Level.WARN) @Message(id = 142010, value = "Failed to add file to opened files queue: {0}. This should NOT happen!", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void failedToAddFile(JournalFile nextOpenedFile); @LogMessage(level = Logger.Level.WARN) @Message(id = 142011, value = "Error on reading compacting for {0}", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void compactReadError(JournalFile file); @LogMessage(level = Logger.Level.WARN) @Message(id = 142012, value = "Couldn''t find tx={0} to merge after compacting", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void compactMergeError(Long id); @LogMessage(level = Logger.Level.WARN) @Message(id = 142013, value = "Prepared transaction {0} was not considered completed, it will be ignored", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void preparedTXIncomplete(Long id); @LogMessage(level = Logger.Level.WARN) @Message(id = 142014, value = "Transaction {0} is missing elements so the transaction is being ignored", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void txMissingElements(Long id); @LogMessage(level = Logger.Level.WARN) @Message(id = 142015, value = "Uncommitted transaction with id {0} found and discarded", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void uncomittedTxFound(Long id); @LogMessage(level = Logger.Level.WARN) @Message(id = 142016, value = "Couldn''t stop compactor executor after 120 seconds", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void couldNotStopCompactor(); @LogMessage(level = Logger.Level.WARN) @Message(id = 142017, value = "Couldn''t stop journal executor after 60 seconds", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void couldNotStopJournalExecutor(); @LogMessage(level = Logger.Level.WARN) @Message(id = 142018, value = "Temporary files were left unnatended after a crash on journal directory, deleting invalid files now", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void tempFilesLeftOpen(); @LogMessage(level = Logger.Level.WARN) - @Message(id = 142019, value = "Deleting orphaned file {0}", format = Message.Format.MESSAGE_FORMAT) + @Message(id = 142019, value = "Deleting orphaned file {0}", format = Message.Format.MESSAGE_FORMAT) void deletingOrphanedFile(String fileToDelete); @LogMessage(level = Logger.Level.WARN) - @Message(id = 142020, value = "Couldn''t get lock after 60 seconds on closing Asynchronous File: {0}", format = Message.Format.MESSAGE_FORMAT) + @Message(id = 142020, value = "Couldn''t get lock after 60 seconds on closing Asynchronous File: {0}", format = Message.Format.MESSAGE_FORMAT) void errorClosingFile(String fileToDelete); @LogMessage(level = Logger.Level.WARN) - @Message(id = 142021, value = "Error on IO callback, {0}", format = Message.Format.MESSAGE_FORMAT) + @Message(id = 142021, value = "Error on IO callback, {0}", format = Message.Format.MESSAGE_FORMAT) void errorOnIOCallback(String errorMessage); @LogMessage(level = Logger.Level.WARN) - @Message(id = 142022, value = "Timed out on AIO poller shutdown", format = Message.Format.MESSAGE_FORMAT) + @Message(id = 142022, value = "Timed out on AIO poller shutdown", format = Message.Format.MESSAGE_FORMAT) void timeoutOnPollerShutdown(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) - @Message(id = 142023, value = "Executor on file {0} couldn''t complete its tasks in 60 seconds.", format = Message.Format.MESSAGE_FORMAT) + @Message(id = 142023, value = "Executor on file {0} couldn''t complete its tasks in 60 seconds.", format = Message.Format.MESSAGE_FORMAT) void couldNotCompleteTask(@Cause Exception e, String name); @LogMessage(level = Logger.Level.WARN) - @Message(id = 142024, value = "Error completing callback", format = Message.Format.MESSAGE_FORMAT) + @Message(id = 142024, value = "Error completing callback", format = Message.Format.MESSAGE_FORMAT) void errorCompletingCallback(@Cause Throwable e); @LogMessage(level = Logger.Level.WARN) - @Message(id = 142025, value = "Error calling onError callback", format = Message.Format.MESSAGE_FORMAT) + @Message(id = 142025, value = "Error calling onError callback", format = Message.Format.MESSAGE_FORMAT) void errorCallingErrorCallback(@Cause Throwable e); @LogMessage(level = Logger.Level.WARN) - @Message(id = 142026, value = "Timed out on AIO writer shutdown", format = Message.Format.MESSAGE_FORMAT) + @Message(id = 142026, value = "Timed out on AIO writer shutdown", format = Message.Format.MESSAGE_FORMAT) void timeoutOnWriterShutdown(@Cause Throwable e); @LogMessage(level = Logger.Level.WARN) - @Message(id = 142027, value = "Error on writing data! {0} code - {1}", format = Message.Format.MESSAGE_FORMAT) + @Message(id = 142027, value = "Error on writing data! {0} code - {1}", format = Message.Format.MESSAGE_FORMAT) void errorWritingData(@Cause Throwable e, String errorMessage, Integer errorCode); @LogMessage(level = Logger.Level.WARN) - @Message(id = 142028, value = "Error replaying pending commands after compacting", format = Message.Format.MESSAGE_FORMAT) + @Message(id = 142028, value = "Error replaying pending commands after compacting", format = Message.Format.MESSAGE_FORMAT) void errorReplayingCommands(@Cause Throwable e); @LogMessage(level = Logger.Level.WARN) - @Message(id = 142029, value = "Error closing file", format = Message.Format.MESSAGE_FORMAT) + @Message(id = 142029, value = "Error closing file", format = Message.Format.MESSAGE_FORMAT) void errorClosingFile(@Cause Throwable e); @LogMessage(level = Logger.Level.WARN) @@ -226,15 +226,15 @@ public interface ActiveMQJournalLogger extends BasicLogger void errorOpeningFile(@Cause Throwable e); @LogMessage(level = Logger.Level.WARN) - @Message(id = 142031, value = "Error retrieving ID part of the file name {0}", format = Message.Format.MESSAGE_FORMAT) + @Message(id = 142031, value = "Error retrieving ID part of the file name {0}", format = Message.Format.MESSAGE_FORMAT) void errorRetrievingID(@Cause Throwable e, String fileName); @LogMessage(level = Logger.Level.WARN) - @Message(id = 142032, value = "Error reading journal file", format = Message.Format.MESSAGE_FORMAT) + @Message(id = 142032, value = "Error reading journal file", format = Message.Format.MESSAGE_FORMAT) void errorReadingFile(@Cause Throwable e); @LogMessage(level = Logger.Level.WARN) - @Message(id = 142033, value = "Error reinitializing file {0}", format = Message.Format.MESSAGE_FORMAT) + @Message(id = 142033, value = "Error reinitializing file {0}", format = Message.Format.MESSAGE_FORMAT) void errorReinitializingFile(@Cause Throwable e, JournalFile file); @LogMessage(level = Logger.Level.WARN) diff --git a/artemis-journal/src/test/java/org/apache/activemq/artemis/core/io/aio/CallbackOrderTest.java b/artemis-journal/src/test/java/org/apache/activemq/artemis/core/io/aio/CallbackOrderTest.java index 82d45024a3..926981cf91 100644 --- a/artemis-journal/src/test/java/org/apache/activemq/artemis/core/io/aio/CallbackOrderTest.java +++ b/artemis-journal/src/test/java/org/apache/activemq/artemis/core/io/aio/CallbackOrderTest.java @@ -27,40 +27,38 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; -/** This will emulate callbacks out of order from libaio*/ -public class CallbackOrderTest -{ +/** + * This will emulate callbacks out of order from libaio + */ +public class CallbackOrderTest { @Rule public TemporaryFolder temporaryFolder; - public CallbackOrderTest() - { + public CallbackOrderTest() { File parent = new File("./target"); parent.mkdirs(); temporaryFolder = new TemporaryFolder(parent); } - /** This method will make sure callbacks will come back in order even when out order from libaio */ + /** + * This method will make sure callbacks will come back in order even when out order from libaio + */ @Test - public void testCallbackOutOfOrder() throws Exception - { + public void testCallbackOutOfOrder() throws Exception { AIOSequentialFileFactory factory = new AIOSequentialFileFactory(temporaryFolder.getRoot(), 100); - AIOSequentialFile file = (AIOSequentialFile)factory.createSequentialFile("test.bin"); + AIOSequentialFile file = (AIOSequentialFile) factory.createSequentialFile("test.bin"); final AtomicInteger count = new AtomicInteger(0); - IOCallback callback = new IOCallback() - { + IOCallback callback = new IOCallback() { @Override - public void done() - { + public void done() { count.incrementAndGet(); } @Override - public void onError(int errorCode, String errorMessage) - { + public void onError(int errorCode, String errorMessage) { } }; @@ -69,20 +67,16 @@ public class CallbackOrderTest // We will repeat the teset a few times, increasing N // to increase possibility of issues due to reuse of callbacks - for (int n = 1; n < 100; n++) - { + for (int n = 1; n < 100; n++) { System.out.println("n = " + n); int N = n; count.set(0); list.clear(); - for (int i = 0; i < N; i++) - { + for (int i = 0; i < N; i++) { list.add(file.getCallback(callback, null)); } - - for (int i = N - 1; i >= 0; i--) - { + for (int i = N - 1; i >= 0; i--) { list.get(i).done(); } diff --git a/artemis-maven-plugin/src/main/java/org/apache/activemq/artemis/maven/ArtemisAbstractPlugin.java b/artemis-maven-plugin/src/main/java/org/apache/activemq/artemis/maven/ArtemisAbstractPlugin.java index 43cc075a79..f7647d3926 100644 --- a/artemis-maven-plugin/src/main/java/org/apache/activemq/artemis/maven/ArtemisAbstractPlugin.java +++ b/artemis-maven-plugin/src/main/java/org/apache/activemq/artemis/maven/ArtemisAbstractPlugin.java @@ -22,24 +22,21 @@ import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Parameter; -public abstract class ArtemisAbstractPlugin extends AbstractMojo -{ +public abstract class ArtemisAbstractPlugin extends AbstractMojo { - - /** It will ignore executioni if ignore has been set to true. This is useful as a property from the build. */ + /** + * It will ignore executioni if ignore has been set to true. This is useful as a property from the build. + */ @Parameter(defaultValue = "") private boolean ignore; - public void execute() throws MojoExecutionException, MojoFailureException - { - if (ignore) - { + public void execute() throws MojoExecutionException, MojoFailureException { + if (ignore) { getLog().debug("******************************************************************************************************"); getLog().debug("Execution of " + getClass().getSimpleName() + " is being ignored as ignore has been set to true"); getLog().debug("******************************************************************************************************"); } - else - { + else { doExecute(); } } diff --git a/artemis-maven-plugin/src/main/java/org/apache/activemq/artemis/maven/ArtemisCLIPlugin.java b/artemis-maven-plugin/src/main/java/org/apache/activemq/artemis/maven/ArtemisCLIPlugin.java index 45aafcb59b..447a57029d 100644 --- a/artemis-maven-plugin/src/main/java/org/apache/activemq/artemis/maven/ArtemisCLIPlugin.java +++ b/artemis-maven-plugin/src/main/java/org/apache/activemq/artemis/maven/ArtemisCLIPlugin.java @@ -33,8 +33,8 @@ import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; @Mojo(name = "cli", defaultPhase = LifecyclePhase.VERIFY) -public class ArtemisCLIPlugin extends ArtemisAbstractPlugin -{ +public class ArtemisCLIPlugin extends ArtemisAbstractPlugin { + private PluginDescriptor descriptor; @Parameter(defaultValue = "server") @@ -67,53 +67,42 @@ public class ArtemisCLIPlugin extends ArtemisAbstractPlugin @Parameter private String testPassword = null; - /** * Validate if the directory is a artemis.home * * * @param path * @return */ - private boolean lookupHome(Path path) - { + private boolean lookupHome(Path path) { - if (path == null) - { + if (path == null) { return false; } Path binFolder = path.resolve("bin"); - if (binFolder == null && Files.exists(binFolder, LinkOption.NOFOLLOW_LINKS)) - { + if (binFolder == null && Files.exists(binFolder, LinkOption.NOFOLLOW_LINKS)) { return false; } Path artemisScript = binFolder.resolve("artemis"); - return artemisScript != null && Files.exists(artemisScript, LinkOption.NOFOLLOW_LINKS); - } @Override - protected void doExecute() throws MojoExecutionException, MojoFailureException - { + protected void doExecute() throws MojoExecutionException, MojoFailureException { // This is to avoid the Run issuing a kill at any point Run.setEmbedded(true); MavenProject project = (MavenProject) getPluginContext().get("project"); - - if (!lookupHome(home.toPath())) - { - if (lookupHome(alternateHome.toPath())) - { + if (!lookupHome(home.toPath())) { + if (lookupHome(alternateHome.toPath())) { home = alternateHome; } - else - { + else { getLog().error("********************************************************************************************"); getLog().error("Could not locate suitable Artemis.home on either " + home + " or " + alternateHome); getLog().error("Use the binary distribution or build the distribution before running the examples"); @@ -123,38 +112,28 @@ public class ArtemisCLIPlugin extends ArtemisAbstractPlugin } } - try - { - if (spawn) - { + try { + if (spawn) { final Process process = org.apache.activemq.artemis.cli.process.ProcessBuilder.build(name, location, true, args); - Runtime.getRuntime().addShutdownHook(new Thread() - { - public void run() - { + Runtime.getRuntime().addShutdownHook(new Thread() { + public void run() { process.destroy(); } }); - if (testURI != null) - { + if (testURI != null) { long timeout = System.currentTimeMillis() + spawnTimeout; - while (System.currentTimeMillis() <= timeout) - { - try (ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(testURI)) - { - if (testUser != null && testPassword != null) - { + while (System.currentTimeMillis() <= timeout) { + try (ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(testURI)) { + if (testUser != null && testPassword != null) { cf.createConnection(testUser, testPassword).close(); } - else - { + else { cf.createConnection().close(); } getLog().info("Server started"); } - catch (Exception e) - { + catch (Exception e) { getLog().info("awaiting server to start"); Thread.sleep(500); continue; @@ -163,8 +142,7 @@ public class ArtemisCLIPlugin extends ArtemisAbstractPlugin } } } - else - { + else { Artemis.execute(home, location, args); } @@ -172,8 +150,7 @@ public class ArtemisCLIPlugin extends ArtemisAbstractPlugin org.apache.activemq.artemis.cli.process.ProcessBuilder.cleanupProcess(); } - catch (Exception e) - { + catch (Exception e) { throw new MojoExecutionException(e.getMessage(), e); } } diff --git a/artemis-maven-plugin/src/main/java/org/apache/activemq/artemis/maven/ArtemisClientPlugin.java b/artemis-maven-plugin/src/main/java/org/apache/activemq/artemis/maven/ArtemisClientPlugin.java index 1716c033d7..be3a19bc01 100644 --- a/artemis-maven-plugin/src/main/java/org/apache/activemq/artemis/maven/ArtemisClientPlugin.java +++ b/artemis-maven-plugin/src/main/java/org/apache/activemq/artemis/maven/ArtemisClientPlugin.java @@ -29,8 +29,7 @@ import org.apache.maven.plugins.annotations.Parameter; * Allows a Java Client to be run which must hve a static main(String[] args) method */ @Mojo(name = "runClient", defaultPhase = LifecyclePhase.VERIFY) -public class ArtemisClientPlugin extends ArtemisAbstractPlugin -{ +public class ArtemisClientPlugin extends ArtemisAbstractPlugin { @Parameter String clientClass; @@ -44,20 +43,16 @@ public class ArtemisClientPlugin extends ArtemisAbstractPlugin private Properties systemProperties; @Override - protected void doExecute() throws MojoExecutionException, MojoFailureException - { - try - { - if (systemProperties != null && !systemProperties.isEmpty()) - { + protected void doExecute() throws MojoExecutionException, MojoFailureException { + try { + if (systemProperties != null && !systemProperties.isEmpty()) { System.getProperties().putAll(systemProperties); } Class aClass = Class.forName(clientClass); Method method = aClass.getDeclaredMethod("main", new Class[]{String[].class}); method.invoke(null, new Object[]{args}); } - catch (Exception e) - { + catch (Exception e) { getLog().error(e); throw new MojoFailureException(e.getMessage()); } diff --git a/artemis-maven-plugin/src/main/java/org/apache/activemq/artemis/maven/ArtemisCreatePlugin.java b/artemis-maven-plugin/src/main/java/org/apache/activemq/artemis/maven/ArtemisCreatePlugin.java index eb3462ecac..e0db71474c 100644 --- a/artemis-maven-plugin/src/main/java/org/apache/activemq/artemis/maven/ArtemisCreatePlugin.java +++ b/artemis-maven-plugin/src/main/java/org/apache/activemq/artemis/maven/ArtemisCreatePlugin.java @@ -46,9 +46,7 @@ import org.eclipse.aether.resolution.ArtifactResolutionException; import org.eclipse.aether.resolution.ArtifactResult; @Mojo(name = "create", defaultPhase = LifecyclePhase.VERIFY) -public class ArtemisCreatePlugin extends ArtemisAbstractPlugin - -{ +public class ArtemisCreatePlugin extends ArtemisAbstractPlugin { @Parameter String name; @@ -58,7 +56,9 @@ public class ArtemisCreatePlugin extends ArtemisAbstractPlugin */ private PluginDescriptor descriptor; - /** Directory to replace the configuration with */ + /** + * Directory to replace the configuration with + */ @Parameter(defaultValue = "${basedir}/target/classes/activemq/server0", required = true) private File configuration; @@ -110,7 +110,9 @@ public class ArtemisCreatePlugin extends ArtemisAbstractPlugin @Parameter(defaultValue = "false") private boolean failoverOnShutdown; - /** it will disable auto-tune*/ + /** + * it will disable auto-tune + */ @Parameter(defaultValue = "true") private boolean noAutoTune; @@ -132,8 +134,6 @@ public class ArtemisCreatePlugin extends ArtemisAbstractPlugin @Parameter ArrayList args = new ArrayList<>(); - - @Parameter private String[] libList; @@ -146,56 +146,43 @@ public class ArtemisCreatePlugin extends ArtemisAbstractPlugin * @param path * @return */ - private boolean lookupHome(Path path) - { + private boolean lookupHome(Path path) { - if (path == null) - { + if (path == null) { return false; } Path binFolder = path.resolve("bin"); - if (binFolder == null && Files.exists(binFolder, LinkOption.NOFOLLOW_LINKS)) - { + if (binFolder == null && Files.exists(binFolder, LinkOption.NOFOLLOW_LINKS)) { return false; } Path artemisScript = binFolder.resolve("artemis"); - return artemisScript != null && Files.exists(artemisScript, LinkOption.NOFOLLOW_LINKS); - } - private void add(List list, String ... str) - { - for (String s: str) - { + private void add(List list, String... str) { + for (String s : str) { list.add(s); } } @Override - protected void doExecute() throws MojoExecutionException, MojoFailureException - { - if (System.getProperty("bypassAddress") != null) - { + protected void doExecute() throws MojoExecutionException, MojoFailureException { + if (System.getProperty("bypassAddress") != null) { System.out.println("BYPASSADDRESS"); } getLog().info("Local " + localRepository); MavenProject project = (MavenProject) getPluginContext().get("project"); - - if (!lookupHome(home.toPath())) - { - if (lookupHome(alternateHome.toPath())) - { + if (!lookupHome(home.toPath())) { + if (lookupHome(alternateHome.toPath())) { home = alternateHome; } - else - { + else { getLog().error("********************************************************************************************"); getLog().error("Could not locate suitable Artemis.home on either " + home + " or " + alternateHome); getLog().error("Use the binary distribution or build the distribution before running the examples"); @@ -205,73 +192,58 @@ public class ArtemisCreatePlugin extends ArtemisAbstractPlugin } } - Map properties = getPluginContext(); Set entries = properties.entrySet(); getLog().info("Entries.size " + entries.size()); - for (Map.Entry entry : entries) - { + for (Map.Entry entry : entries) { getLog().info("... key=" + entry.getKey() + " = " + entry.getValue()); } ArrayList listCommands = new ArrayList<>(); - add(listCommands, "create", "--allow-anonymous", "--silent", "--force", "--no-web", "--user", user, "--password", password, - "--role", role, - "--port-offset", "" + portOffset, - "--data", dataFolder); + add(listCommands, "create", "--allow-anonymous", "--silent", "--force", "--no-web", "--user", user, "--password", password, "--role", role, "--port-offset", "" + portOffset, "--data", dataFolder); - if (allowAnonymous) - { + if (allowAnonymous) { add(listCommands, "--allow-anonymous"); } - else - { + else { add(listCommands, "--require-login"); } - if (!javaOptions.isEmpty()) - { + if (!javaOptions.isEmpty()) { add(listCommands, "--java-options", javaOptions); } - if (slave) - { + if (slave) { add(listCommands, "--slave"); } - if (replicated) - { + if (replicated) { add(listCommands, "--replicated"); } - if (sharedStore) - { + if (sharedStore) { add(listCommands, "--shared-store"); } - if (clustered) - { + if (clustered) { add(listCommands, "--clustered"); add(listCommands, "--message-load-balancing", messageLoadBalancing); } - if (failoverOnShutdown) - { + if (failoverOnShutdown) { add(listCommands, "--failover-on-shutdown"); } - if (noAutoTune) - { + if (noAutoTune) { add(listCommands, "--no-autotune"); } add(listCommands, "--verbose"); - for (String str : args) - { + for (String str : args) { add(listCommands, str); } @@ -279,62 +251,51 @@ public class ArtemisCreatePlugin extends ArtemisAbstractPlugin getLog().debug("***** Server created at " + instance + " with home=" + home + " *****"); - try - { + try { Artemis.execute(home, null, listCommands); - if (configuration != null) - { + if (configuration != null) { String[] list = configuration.list(); - if (list != null) - { + if (list != null) { getLog().debug("************************************************"); getLog().debug("Replacing configuration files:"); - for (String file : configuration.list()) - { + for (String file : configuration.list()) { Path target = instance.toPath().resolve("etc").resolve(file); getLog().debug("Replacing " + file + " into " + target); - Files.copy(configuration.toPath().resolve(file), target, StandardCopyOption.REPLACE_EXISTING); } } } - if (libList != null) - { - for (int i = 0; i < libList.length; i++) - { + if (libList != null) { + for (int i = 0; i < libList.length; i++) { String[] splitString = libList[i].split(":"); getLog().debug("********************" + splitString[0] + "/" + splitString[1] + "/" + splitString[2]); Artifact artifact; - try - { - artifact = new DefaultArtifact( libList[i] ); + try { + artifact = new DefaultArtifact(libList[i]); } - catch ( IllegalArgumentException e ) - { - throw new MojoFailureException( e.getMessage(), e ); + catch (IllegalArgumentException e) { + throw new MojoFailureException(e.getMessage(), e); } ArtifactRequest request = new ArtifactRequest(); - request.setArtifact( artifact ); - request.setRepositories( remoteRepos ); + request.setArtifact(artifact); + request.setRepositories(remoteRepos); getLog().debug("Resolving artifact " + artifact + " from " + remoteRepos); ArtifactResult result; - try - { - result = repositorySystem.resolveArtifact( repoSession, request ); + try { + result = repositorySystem.resolveArtifact(repoSession, request); } - catch ( ArtifactResolutionException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + catch (ArtifactResolutionException e) { + throw new MojoExecutionException(e.getMessage(), e); } File artifactFile = result.getArtifact().getFile(); @@ -347,15 +308,13 @@ public class ArtemisCreatePlugin extends ArtemisAbstractPlugin } } - catch (Exception e) - { + catch (Exception e) { getLog().error(e); throw new MojoFailureException(e.getMessage()); } } - private void copyToLib(File projectLib) throws IOException - { + private void copyToLib(File projectLib) throws IOException { Path target = instance.toPath().resolve("lib").resolve(projectLib.getName()); target.toFile().mkdirs(); getLog().debug("Copying " + projectLib.getName() + " as " + target.toFile().getAbsolutePath()); diff --git a/artemis-native/src/main/java/org/apache/activemq/artemis/jlibaio/LibaioContext.java b/artemis-native/src/main/java/org/apache/activemq/artemis/jlibaio/LibaioContext.java index 8b45f54465..5ada655ef3 100644 --- a/artemis-native/src/main/java/org/apache/activemq/artemis/jlibaio/LibaioContext.java +++ b/artemis-native/src/main/java/org/apache/activemq/artemis/jlibaio/LibaioContext.java @@ -40,8 +40,7 @@ import static io.netty.util.internal.ObjectUtil.checkNotNull; *
    * Interesting reading for this. */ -public class LibaioContext implements Closeable -{ +public class LibaioContext implements Closeable { private static final AtomicLong totalMaxIO = new AtomicLong(0); @@ -54,80 +53,69 @@ public class LibaioContext implements Closeable private static boolean loaded = false; - public static boolean isLoaded() - { + public static boolean isLoaded() { return loaded; } - private static boolean loadLibrary(final String name) - { - try - { + private static boolean loadLibrary(final String name) { + try { System.loadLibrary(name); - if (getNativeVersion() != EXPECTED_NATIVE_VERSION) - { + if (getNativeVersion() != EXPECTED_NATIVE_VERSION) { NativeLogger.LOGGER.incompatibleNativeLibrary(); return false; } - else - { + else { return true; } } - catch (Throwable e) - { + catch (Throwable e) { NativeLogger.LOGGER.debug(name + " -> error loading the native library", e); return false; } } - static - { + static { String[] libraries = new String[]{"artemis-native-64", "artemis-native-32"}; - for (String library : libraries) - { - if (loadLibrary(library)) - { + for (String library : libraries) { + if (loadLibrary(library)) { loaded = true; break; } - else - { + else { NativeLogger.LOGGER.debug("Library " + library + " not found!"); } } - if (!loaded) - { + if (!loaded) { NativeLogger.LOGGER.debug("Couldn't locate LibAIO Wrapper"); } } /** * This is used to validate leaks on tests. + * * @return the number of allocated aio, to be used on test checks. */ - public static long getTotalMaxIO() - { + public static long getTotalMaxIO() { return totalMaxIO.get(); } /** * It will reset all the positions on the buffer to 0, using memset. + * * @param buffer a native buffer. -s */ - public void memsetBuffer(ByteBuffer buffer) - { + * s + */ + public void memsetBuffer(ByteBuffer buffer) { memsetBuffer(buffer, buffer.limit()); } /** * This is used on tests validating for leaks. */ - public static void resetMaxAIO() - { + public static void resetMaxAIO() { totalMaxIO.set(0); } @@ -146,79 +134,71 @@ s */ * The queue size here will use resources defined on the kernel parameter * fs.aio-max-nr . * - * @param queueSize the size to be initialize on libaio - * io_queue_init which can't be higher than /proc/sys/fs/aio-max-nr. + * @param queueSize the size to be initialize on libaio + * io_queue_init which can't be higher than /proc/sys/fs/aio-max-nr. * @param useSemaphore should block on a semaphore avoiding using more submits than what's available. */ - public LibaioContext(int queueSize, boolean useSemaphore) - { - try - { + public LibaioContext(int queueSize, boolean useSemaphore) { + try { this.ioContext = newContext(queueSize); } - catch (Exception e) - { + catch (Exception e) { throw e; } this.queueSize = queueSize; totalMaxIO.addAndGet(queueSize); - if (useSemaphore) - { + if (useSemaphore) { this.ioSpace = new Semaphore(queueSize); } - else - { + else { this.ioSpace = null; } } - /** * Documented at {@link LibaioFile#write(long, int, java.nio.ByteBuffer, SubmitInfo)} - * @param fd the file descriptor - * @param position the write position - * @param size number of bytes to use + * + * @param fd the file descriptor + * @param position the write position + * @param size number of bytes to use * @param bufferWrite the native buffer - * @param callback a callback + * @param callback a callback * @throws IOException in case of error */ - public void submitWrite(int fd,long position, int size, - ByteBuffer bufferWrite, Callback callback) throws IOException - { - try - { - if (ioSpace != null) - { + public void submitWrite(int fd, + long position, + int size, + ByteBuffer bufferWrite, + Callback callback) throws IOException { + try { + if (ioSpace != null) { ioSpace.acquire(); } } - catch (InterruptedException e) - { + catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e.getMessage(), e); } submitWrite(fd, this.ioContext, position, size, bufferWrite, callback); } - public void submitRead(int fd, long position, int size, ByteBuffer bufferWrite, - Callback callback) throws IOException - { - try - { - if (ioSpace != null) - { + public void submitRead(int fd, + long position, + int size, + ByteBuffer bufferWrite, + Callback callback) throws IOException { + try { + if (ioSpace != null) { ioSpace.acquire(); } } - catch (InterruptedException e) - { + catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e.getMessage(), e); } submitRead(fd, this.ioContext, position, size, bufferWrite, callback); } - /** * This is used to close the libaio queues and cleanup the native data used. *
    @@ -226,22 +206,18 @@ s */ * this could cause core dumps or VM crashes. */ @Override - public void close() - { - if (!closed.getAndSet(true)) - { + public void close() { + if (!closed.getAndSet(true)) { totalMaxIO.addAndGet(-queueSize); - if (ioContext != null) - { + if (ioContext != null) { deleteContext(ioContext); } } } @Override - protected void finalize() throws Throwable - { + protected void finalize() throws Throwable { super.finalize(); close(); } @@ -250,13 +226,12 @@ s */ * It will open a file. If you set the direct flag = false then you won't need to use the special buffer. * Notice: This will create an empty file if the file doesn't already exist. * - * @param file the file to be open. + * @param file the file to be open. * @param direct will set ODIRECT. * @return It will return a LibaioFile instance. * @throws IOException in case of error. */ - public LibaioFile openFile(File file, boolean direct) throws IOException - { + public LibaioFile openFile(File file, boolean direct) throws IOException { return openFile(file.getPath(), direct); } @@ -264,13 +239,12 @@ s */ * It will open a file. If you set the direct flag = false then you won't need to use the special buffer. * Notice: This will create an empty file if the file doesn't already exist. * - * @param file the file to be open. + * @param file the file to be open. * @param direct should use O_DIRECT when opening the file. * @return a new open file. * @throws IOException in case of error. */ - public LibaioFile openFile(String file, boolean direct) throws IOException - { + public LibaioFile openFile(String file, boolean direct) throws IOException { checkNotNull(file, "path"); checkNotNull(ioContext, "IOContext"); @@ -283,13 +257,13 @@ s */ /** * It will open a file disassociated with any sort of factory. * This is useful when you won't use reading / writing through libaio like locking files. - * @param file a file name + * + * @param file a file name * @param direct will use O_DIRECT * @return a new file * @throws IOException in case of error. */ - public static LibaioFile openControlFile(String file, boolean direct) throws IOException - { + public static LibaioFile openControlFile(String file, boolean direct) throws IOException { checkNotNull(file, "path"); // note: the native layer will throw an IOException in case of errors @@ -306,7 +280,7 @@ s */ * Thread polling for any reason. *
    * Notice that the native layer will invoke {@link SubmitInfo#onError(int, String)} in case of failures, - * but it won't call done method for you. + * but it won't call done method for you. * * @param callbacks area to receive the callbacks passed on submission.The size of this callback has to * be greater than the parameter max. @@ -316,36 +290,32 @@ s */ * @see LibaioFile#write(long, int, java.nio.ByteBuffer, SubmitInfo) * @see LibaioFile#read(long, int, java.nio.ByteBuffer, SubmitInfo) */ - public int poll(Callback[] callbacks, int min, int max) - { + public int poll(Callback[] callbacks, int min, int max) { int released = poll(ioContext, callbacks, min, max); - if (ioSpace != null) - { - if (released > 0) - { + if (ioSpace != null) { + if (released > 0) { ioSpace.release(released); } } - return released; + return released; } /** * It will start polling and will keep doing until the context is closed. * This will call callbacks on {@link SubmitInfo#onError(int, String)} and - * {@link SubmitInfo#done()}. + * {@link SubmitInfo#done()}. * In case of error, both {@link SubmitInfo#onError(int, String)} and - * {@link SubmitInfo#done()} are called. + * {@link SubmitInfo#done()} are called. */ - public void poll() - { + public void poll() { blockedPoll(ioContext); } - /** Called from the native layer */ - private void done(SubmitInfo info) - { - if (ioSpace != null) - { + /** + * Called from the native layer + */ + private void done(SubmitInfo info) { + if (ioSpace != null) { ioSpace.release(); } info.done(); @@ -364,7 +334,7 @@ s */ /** * it will return a file descriptor. * - * @param path the file name. + * @param path the file name. * @param direct translates as O_DIRECT On open * @return a fd from open C call. */ @@ -380,7 +350,7 @@ s */ *
    * Documented at {@link LibaioFile#newBuffer(int)}. * - * @param size needs to be % alignment + * @param size needs to be % alignment * @param alignment the alignment used at the dispositive * @return a new native buffer used with posix_memalign */ @@ -388,6 +358,7 @@ s */ /** * This will call posix free to release the inner buffer allocated at {@link #newAlignedBuffer(int, int)}. + * * @param buffer a native buffer allocated with {@link #newAlignedBuffer(int, int)}. */ public static native void freeBuffer(ByteBuffer buffer); @@ -396,17 +367,21 @@ s */ * Documented at {@link LibaioFile#write(long, int, java.nio.ByteBuffer, SubmitInfo)}. */ native void submitWrite(int fd, - ByteBuffer libaioContext, - long position, int size, ByteBuffer bufferWrite, - Callback callback) throws IOException; + ByteBuffer libaioContext, + long position, + int size, + ByteBuffer bufferWrite, + Callback callback) throws IOException; /** * Documented at {@link LibaioFile#read(long, int, java.nio.ByteBuffer, SubmitInfo)}. */ native void submitRead(int fd, - ByteBuffer libaioContext, - long position, int size, ByteBuffer bufferWrite, - Callback callback) throws IOException; + ByteBuffer libaioContext, + long position, + int size, + ByteBuffer bufferWrite, + Callback callback) throws IOException; /** * Note: this shouldn't be done concurrently. @@ -431,8 +406,7 @@ s */ static native int getBlockSizeFD(int fd); - public static int getBlockSize(File path) - { + public static int getBlockSize(File path) { return getBlockSize(path.getAbsolutePath()); } diff --git a/artemis-native/src/main/java/org/apache/activemq/artemis/jlibaio/LibaioFile.java b/artemis-native/src/main/java/org/apache/activemq/artemis/jlibaio/LibaioFile.java index bf88d65356..27243fee66 100644 --- a/artemis-native/src/main/java/org/apache/activemq/artemis/jlibaio/LibaioFile.java +++ b/artemis-native/src/main/java/org/apache/activemq/artemis/jlibaio/LibaioFile.java @@ -22,8 +22,8 @@ import java.nio.ByteBuffer; /** * This is an extension to use libaio. */ -public final class LibaioFile -{ +public final class LibaioFile { + protected boolean open; /** * This represents a structure allocated on the native @@ -33,29 +33,25 @@ public final class LibaioFile private int fd; - LibaioFile(int fd, LibaioContext ctx) - { + LibaioFile(int fd, LibaioContext ctx) { this.ctx = ctx; this.fd = fd; } - public int getBlockSize() - { + public int getBlockSize() { return 512; // FIXME //return LibaioContext.getBlockSizeFD(fd); } - public boolean lock() - { + public boolean lock() { return LibaioContext.lock(fd); } /** * {@inheritDoc} */ - public void close() throws IOException - { + public void close() throws IOException { open = false; LibaioContext.close(fd); } @@ -63,8 +59,7 @@ public final class LibaioFile /** * @return The size of the file. */ - public long getSize() - { + public long getSize() { return LibaioContext.getSize(fd); } @@ -82,8 +77,7 @@ public final class LibaioFile * @param callback A callback to be returned on the poll method. * @throws java.io.IOException in case of error */ - public void write(long position, int size, ByteBuffer buffer, Callback callback) throws IOException - { + public void write(long position, int size, ByteBuffer buffer, Callback callback) throws IOException { ctx.submitWrite(fd, position, size, buffer, callback); } @@ -103,8 +97,7 @@ public final class LibaioFile * @throws java.io.IOException in case of error * @see LibaioContext#poll(SubmitInfo[], int, int) */ - public void read(long position, int size, ByteBuffer buffer, Callback callback) throws IOException - { + public void read(long position, int size, ByteBuffer buffer, Callback callback) throws IOException { ctx.submitRead(fd, position, size, buffer, callback); } @@ -118,23 +111,20 @@ public final class LibaioFile * @param size the size of the buffer. * @return the buffer allocated. */ - public ByteBuffer newBuffer(int size) - { + public ByteBuffer newBuffer(int size) { return LibaioContext.newAlignedBuffer(size, 512); } /** * It will preallocate the file with a given size. + * * @param size number of bytes to be filled on the file */ - public void fill(long size) - { - try - { + public void fill(long size) { + try { LibaioContext.fill(fd, size); } - catch (OutOfMemoryError e) - { + catch (OutOfMemoryError e) { NativeLogger.LOGGER.debug("Didn't have enough memory to allocate " + size + " bytes in memory, using simple fallocate"); LibaioContext.fallocate(fd, size); } @@ -142,10 +132,10 @@ public final class LibaioFile /** * It will use fallocate to initialize a file. + * * @param size number of bytes to be filled on the file */ - public void fallocate(long size) - { + public void fallocate(long size) { LibaioContext.fallocate(fd, size); } diff --git a/artemis-native/src/main/java/org/apache/activemq/artemis/jlibaio/NativeLogger.java b/artemis-native/src/main/java/org/apache/activemq/artemis/jlibaio/NativeLogger.java index 449c1685ce..6ebcc8fc7b 100644 --- a/artemis-native/src/main/java/org/apache/activemq/artemis/jlibaio/NativeLogger.java +++ b/artemis-native/src/main/java/org/apache/activemq/artemis/jlibaio/NativeLogger.java @@ -37,14 +37,13 @@ import org.jboss.logging.annotations.MessageLogger; * so an INFO message would be 1000 to 6000 */ @MessageLogger(projectCode = "jlibaio") -public interface NativeLogger extends BasicLogger -{ +public interface NativeLogger extends BasicLogger { + /** * The journal logger. */ NativeLogger LOGGER = Logger.getMessageLogger(NativeLogger.class, NativeLogger.class.getPackage().getName()); - @LogMessage(level = Logger.Level.WARN) @Message(id = 1001, value = "You have a native library with a different version than expected", format = Message.Format.MESSAGE_FORMAT) void incompatibleNativeLibrary(); diff --git a/artemis-native/src/main/java/org/apache/activemq/artemis/jlibaio/SubmitInfo.java b/artemis-native/src/main/java/org/apache/activemq/artemis/jlibaio/SubmitInfo.java index 47feea86d2..36d2103bc1 100644 --- a/artemis-native/src/main/java/org/apache/activemq/artemis/jlibaio/SubmitInfo.java +++ b/artemis-native/src/main/java/org/apache/activemq/artemis/jlibaio/SubmitInfo.java @@ -17,8 +17,8 @@ package org.apache.activemq.artemis.jlibaio; -public interface SubmitInfo -{ +public interface SubmitInfo { + void onError(int errno, String message); void done(); diff --git a/artemis-native/src/main/java/org/apache/activemq/artemis/jlibaio/util/CallbackCache.java b/artemis-native/src/main/java/org/apache/activemq/artemis/jlibaio/util/CallbackCache.java index ec2a630587..00a3826cfd 100644 --- a/artemis-native/src/main/java/org/apache/activemq/artemis/jlibaio/util/CallbackCache.java +++ b/artemis-native/src/main/java/org/apache/activemq/artemis/jlibaio/util/CallbackCache.java @@ -17,14 +17,13 @@ package org.apache.activemq.artemis.jlibaio.util; - import org.apache.activemq.artemis.jlibaio.SubmitInfo; /** * this is an utility class where you can reuse Callbackk objects for your LibaioContext usage. */ -public class CallbackCache -{ +public class CallbackCache { + private final SubmitInfo[] pool; private int put = 0; @@ -34,34 +33,26 @@ public class CallbackCache private final Object lock = new Object(); - public CallbackCache(int size) - { + public CallbackCache(int size) { this.pool = new SubmitInfo[size]; this.size = size; } - public Callback get() - { - synchronized (lock) - { - if (available <= 0) - { + public Callback get() { + synchronized (lock) { + if (available <= 0) { return null; } - else - { - Callback retValue = (Callback)pool[get]; + else { + Callback retValue = (Callback) pool[get]; pool[get] = null; - if (retValue == null) - { + if (retValue == null) { throw new NullPointerException("You should initialize the pool before using it"); } - if (retValue != null) - { + if (retValue != null) { available--; get++; - if (get >= size) - { + if (get >= size) { get = 0; } } @@ -70,20 +61,15 @@ public class CallbackCache } } - public CallbackCache put(Callback callback) - { - if (callback == null) - { + public CallbackCache put(Callback callback) { + if (callback == null) { return null; } - synchronized (lock) - { - if (available < size) - { + synchronized (lock) { + if (available < size) { available++; pool[put++] = callback; - if (put >= size) - { + if (put >= size) { put = 0; } } diff --git a/artemis-native/src/test/java/org/apache/activemq/artemis/jlibaio/test/CallbackCachelTest.java b/artemis-native/src/test/java/org/apache/activemq/artemis/jlibaio/test/CallbackCachelTest.java index f62f8e2457..6785d78d70 100644 --- a/artemis-native/src/test/java/org/apache/activemq/artemis/jlibaio/test/CallbackCachelTest.java +++ b/artemis-native/src/test/java/org/apache/activemq/artemis/jlibaio/test/CallbackCachelTest.java @@ -24,16 +24,13 @@ import org.apache.activemq.artemis.jlibaio.SubmitInfo; import org.junit.Assert; import org.junit.Test; -public class CallbackCachelTest -{ +public class CallbackCachelTest { + @Test - public void testPartiallyInitialized() - { + public void testPartiallyInitialized() { CallbackCache pool = new CallbackCache(100); - - for (int i = 0; i < 50; i++) - { + for (int i = 0; i < 50; i++) { pool.put(new MyPool(i)); } @@ -43,69 +40,59 @@ public class CallbackCachelTest pool.put(value); - // add and remove immediately - for (int i = 0; i < 777; i++) - { + for (int i = 0; i < 777; i++) { pool.put(pool.get()); } - HashSet hashValues = new HashSet<>(); - MyPool getValue; - while ((getValue = pool.get()) != null) - { + while ((getValue = pool.get()) != null) { hashValues.add(getValue); } - Assert.assertEquals(50, hashValues.size()); } - static class MyPool implements SubmitInfo - { + static class MyPool implements SubmitInfo { + public final int i; - MyPool(int i) - { + MyPool(int i) { this.i = i; } - - public int getI() - { + public int getI() { return i; } @Override - public void onError(int errno, String message) - { + public void onError(int errno, String message) { } @Override - public void done() - { + public void done() { } @Override - public boolean equals(Object o) - { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; MyPool myPool = (MyPool) o; - if (i != myPool.i) return false; + if (i != myPool.i) + return false; return true; } @Override - public int hashCode() - { + public int hashCode() { return i; } } diff --git a/artemis-native/src/test/java/org/apache/activemq/artemis/jlibaio/test/LibaioTest.java b/artemis-native/src/test/java/org/apache/activemq/artemis/jlibaio/test/LibaioTest.java index e46caf36d0..c93670ad85 100644 --- a/artemis-native/src/test/java/org/apache/activemq/artemis/jlibaio/test/LibaioTest.java +++ b/artemis-native/src/test/java/org/apache/activemq/artemis/jlibaio/test/LibaioTest.java @@ -41,16 +41,15 @@ import org.junit.rules.TemporaryFolder; * This test is using a different package from {@link LibaioFile} * as I need to validate public methods on the API */ -public class LibaioTest -{ +public class LibaioTest { @BeforeClass - public static void testAIO() - { + public static void testAIO() { Assume.assumeTrue(LibaioContext.isLoaded()); } - /** This is just an arbitrary number for a number of elements you need to pass to the libaio init method + /** + * This is just an arbitrary number for a number of elements you need to pass to the libaio init method * Some of the tests are using half of this number, so if anyone decide to change this please use an even number. */ private static final int LIBAIO_QUEUE_SIZE = 50; @@ -61,25 +60,21 @@ public class LibaioTest public LibaioContext control; @Before - public void setUpFactory() - { + public void setUpFactory() { control = new LibaioContext<>(LIBAIO_QUEUE_SIZE, true); } @After - public void deleteFactory() - { + public void deleteFactory() { control.close(); validateLibaio(); } - public void validateLibaio() - { + public void validateLibaio() { Assert.assertEquals(0, LibaioContext.getTotalMaxIO()); } - public LibaioTest() - { + public LibaioTest() { /* * I didn't use /tmp for three reasons * - Most systems now will use tmpfs which is not compatible with O_DIRECT @@ -92,15 +87,13 @@ public class LibaioTest } @Test - public void testOpen() throws Exception - { + public void testOpen() throws Exception { LibaioFile fileDescriptor = control.openFile(temporaryFolder.newFile("test.bin"), true); fileDescriptor.close(); } @Test - public void testInitAndFallocate() throws Exception - { + public void testInitAndFallocate() throws Exception { LibaioFile fileDescriptor = control.openFile(temporaryFolder.newFile("test.bin"), true); fileDescriptor.fallocate(1024 * 1024); @@ -112,7 +105,6 @@ public class LibaioTest fileDescriptor.close(); - buffer.position(0); LibaioFile fileDescriptor2 = control.openFile(temporaryFolder.newFile("test2.bin"), true); @@ -120,8 +112,7 @@ public class LibaioTest fileDescriptor2.read(0, 1024 * 1024, buffer, new TestInfo()); control.poll(callbacks, 1, 1); - for (int i = 0; i < 1024 * 1024; i++) - { + for (int i = 0; i < 1024 * 1024; i++) { Assert.assertEquals(0, buffer.get()); } @@ -129,8 +120,7 @@ public class LibaioTest } @Test - public void testSubmitWriteOnTwoFiles() throws Exception - { + public void testSubmitWriteOnTwoFiles() throws Exception { File file1 = temporaryFolder.newFile("test.bin"); File file2 = temporaryFolder.newFile("test2.bin"); @@ -138,8 +128,7 @@ public class LibaioTest fillupFile(file1, LIBAIO_QUEUE_SIZE / 2); fillupFile(file2, LIBAIO_QUEUE_SIZE / 2); - LibaioFile[] fileDescriptor = new LibaioFile[]{control.openFile(file1, true), - control.openFile(file2, true)}; + LibaioFile[] fileDescriptor = new LibaioFile[]{control.openFile(file1, true), control.openFile(file2, true)}; Assert.assertEquals((LIBAIO_QUEUE_SIZE / 2) * 512, fileDescriptor[0].getSize()); Assert.assertEquals((LIBAIO_QUEUE_SIZE / 2) * 512, fileDescriptor[1].getSize()); @@ -151,44 +140,36 @@ public class LibaioTest ByteBuffer buffer = LibaioContext.newAlignedBuffer(512, 512); - try - { - for (int i = 0; i < 512; i++) - { + try { + for (int i = 0; i < 512; i++) { buffer.put((byte) 'a'); } TestInfo callback = new TestInfo(); TestInfo[] callbacks = new TestInfo[LIBAIO_QUEUE_SIZE]; - for (int i = 0; i < LIBAIO_QUEUE_SIZE / 2; i++) - { - for (LibaioFile file : fileDescriptor) - { + for (int i = 0; i < LIBAIO_QUEUE_SIZE / 2; i++) { + for (LibaioFile file : fileDescriptor) { file.write(i * 512, 512, buffer, callback); } } Assert.assertEquals(LIBAIO_QUEUE_SIZE, control.poll(callbacks, LIBAIO_QUEUE_SIZE, LIBAIO_QUEUE_SIZE)); - for (Object returnedCallback : callbacks) - { + for (Object returnedCallback : callbacks) { Assert.assertSame(returnedCallback, callback); } - for (LibaioFile file : fileDescriptor) - { + for (LibaioFile file : fileDescriptor) { ByteBuffer bigbuffer = LibaioContext.newAlignedBuffer(512 * 25, 512); file.read(0, 512 * 25, bigbuffer, callback); Assert.assertEquals(1, control.poll(callbacks, 1, LIBAIO_QUEUE_SIZE)); - for (Object returnedCallback : callbacks) - { + for (Object returnedCallback : callbacks) { Assert.assertSame(returnedCallback, callback); } - for (int i = 0; i < 512 * 25; i++) - { + for (int i = 0; i < 512 * 25; i++) { Assert.assertEquals((byte) 'a', bigbuffer.get()); } @@ -197,15 +178,13 @@ public class LibaioTest file.close(); } } - finally - { + finally { LibaioContext.freeBuffer(buffer); } } @Test - public void testSubmitWriteAndRead() throws Exception - { + public void testSubmitWriteAndRead() throws Exception { TestInfo callback = new TestInfo(); TestInfo[] callbacks = new TestInfo[LIBAIO_QUEUE_SIZE]; @@ -215,10 +194,8 @@ public class LibaioTest // ByteBuffer buffer = ByteBuffer.allocateDirect(512); ByteBuffer buffer = LibaioContext.newAlignedBuffer(512, 512); - try - { - for (int i = 0; i < 512; i++) - { + try { + for (int i = 0; i < 512; i++) { buffer.put((byte) 'a'); } @@ -235,8 +212,7 @@ public class LibaioTest buffer = LibaioContext.newAlignedBuffer(512, 512); - for (int i = 0; i < 512; i++) - { + for (int i = 0; i < 512; i++) { buffer.put((byte) 'B'); } @@ -250,13 +226,11 @@ public class LibaioTest Assert.assertEquals(1, control.poll(callbacks, 1, LIBAIO_QUEUE_SIZE)); - for (int i = 0; i < 512; i++) - { + for (int i = 0; i < 512; i++) { Assert.assertEquals('B', buffer.get()); } } - finally - { + finally { LibaioContext.freeBuffer(buffer); fileDescriptor.close(); } @@ -266,9 +240,7 @@ public class LibaioTest /** * This file is making use of libaio without O_DIRECT * We won't need special buffers on this case. - */ - public void testSubmitWriteAndReadRegularBuffers() throws Exception - { + */ public void testSubmitWriteAndReadRegularBuffers() throws Exception { TestInfo callback = new TestInfo(); TestInfo[] callbacks = new TestInfo[LIBAIO_QUEUE_SIZE]; @@ -283,10 +255,8 @@ public class LibaioTest ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER_SIZE); - try - { - for (int i = 0; i < BUFFER_SIZE; i++) - { + try { + for (int i = 0; i < BUFFER_SIZE; i++) { buffer.put((byte) 'a'); } @@ -302,8 +272,7 @@ public class LibaioTest buffer.rewind(); - for (int i = 0; i < BUFFER_SIZE; i++) - { + for (int i = 0; i < BUFFER_SIZE; i++) { buffer.put((byte) 'B'); } @@ -317,20 +286,17 @@ public class LibaioTest Assert.assertEquals(1, control.poll(callbacks, 1, LIBAIO_QUEUE_SIZE)); - for (int i = 0; i < BUFFER_SIZE; i++) - { + for (int i = 0; i < BUFFER_SIZE; i++) { Assert.assertEquals('B', buffer.get()); } } - finally - { + finally { fileDescriptor.close(); } } @Test - public void testSubmitRead() throws Exception - { + public void testSubmitRead() throws Exception { TestInfo callback = new TestInfo(); @@ -345,10 +311,8 @@ public class LibaioTest ByteBuffer buffer = LibaioContext.newAlignedBuffer(512, 512); final int BUFFER_SIZE = 512; - try - { - for (int i = 0; i < BUFFER_SIZE; i++) - { + try { + for (int i = 0; i < BUFFER_SIZE; i++) { buffer.put((byte) '@'); } @@ -364,21 +328,18 @@ public class LibaioTest Assert.assertSame(callback, callbacks[0]); - for (int i = 0; i < BUFFER_SIZE; i++) - { + for (int i = 0; i < BUFFER_SIZE; i++) { Assert.assertEquals('@', buffer.get()); } } - finally - { + finally { LibaioContext.freeBuffer(buffer); fileDescriptor.close(); } } @Test - public void testInvalidWrite() throws Exception - { + public void testInvalidWrite() throws Exception { TestInfo callback = new TestInfo(); @@ -390,11 +351,9 @@ public class LibaioTest LibaioFile fileDescriptor = control.openFile(file, true); - try - { + try { ByteBuffer buffer = ByteBuffer.allocateDirect(300); - for (int i = 0; i < 300; i++) - { + for (int i = 0; i < 300; i++) { buffer.put((byte) 'z'); } @@ -410,8 +369,7 @@ public class LibaioTest System.out.println("Error:" + callbacks[0]); buffer = fileDescriptor.newBuffer(512); - for (int i = 0; i < 512; i++) - { + for (int i = 0; i < 512; i++) { buffer.put((byte) 'z'); } @@ -434,15 +392,13 @@ public class LibaioTest TestInfo.checkLeaks(); } - finally - { + finally { fileDescriptor.close(); } } @Test - public void testLeaks() throws Exception - { + public void testLeaks() throws Exception { File file = temporaryFolder.newFile("test.bin"); fillupFile(file, LIBAIO_QUEUE_SIZE * 2); @@ -453,25 +409,20 @@ public class LibaioTest ByteBuffer bufferWrite = LibaioContext.newAlignedBuffer(512, 512); - try - { - for (int i = 0; i < 512; i++) - { + try { + for (int i = 0; i < 512; i++) { bufferWrite.put((byte) 'B'); } - for (int j = 0; j < LIBAIO_QUEUE_SIZE * 2; j++) - { - for (int i = 0; i < LIBAIO_QUEUE_SIZE; i++) - { + for (int j = 0; j < LIBAIO_QUEUE_SIZE * 2; j++) { + for (int i = 0; i < LIBAIO_QUEUE_SIZE; i++) { TestInfo countClass = new TestInfo(); fileDescriptor.write(i * 512, 512, bufferWrite, countClass); } Assert.assertEquals(LIBAIO_QUEUE_SIZE, control.poll(callbacks, LIBAIO_QUEUE_SIZE, LIBAIO_QUEUE_SIZE)); - for (int i = 0; i < LIBAIO_QUEUE_SIZE; i++) - { + for (int i = 0; i < LIBAIO_QUEUE_SIZE; i++) { Assert.assertNotNull(callbacks[i]); callbacks[i] = null; } @@ -479,15 +430,13 @@ public class LibaioTest TestInfo.checkLeaks(); } - finally - { + finally { LibaioContext.freeBuffer(bufferWrite); } } @Test - public void testLock() throws Exception - { + public void testLock() throws Exception { File file = temporaryFolder.newFile("test.bin"); LibaioFile fileDescriptor = control.openFile(file, true); @@ -497,8 +446,7 @@ public class LibaioTest } @Test - public void testAlloc() throws Exception - { + public void testAlloc() throws Exception { File file = temporaryFolder.newFile("test.bin"); LibaioFile fileDescriptor = control.openFile(file, true); @@ -508,15 +456,12 @@ public class LibaioTest } @Test - public void testReleaseNullBuffer() throws Exception - { + public void testReleaseNullBuffer() throws Exception { boolean failed = false; - try - { + try { LibaioContext.freeBuffer(null); } - catch (Exception expected) - { + catch (Exception expected) { failed = true; } @@ -525,20 +470,17 @@ public class LibaioTest } @Test - public void testMemset() throws Exception - { + public void testMemset() throws Exception { ByteBuffer buffer = LibaioContext.newAlignedBuffer(512 * 8, 512); - for (int i = 0; i < buffer.capacity(); i++) - { + for (int i = 0; i < buffer.capacity(); i++) { buffer.put((byte) 'z'); } buffer.position(0); - for (int i = 0; i < buffer.capacity(); i++) - { + for (int i = 0; i < buffer.capacity(); i++) { Assert.assertEquals((byte) 'z', buffer.get()); } @@ -546,8 +488,7 @@ public class LibaioTest buffer.position(0); - for (int i = 0; i < buffer.capacity(); i++) - { + for (int i = 0; i < buffer.capacity(); i++) { Assert.assertEquals((byte) 0, buffer.get()); } @@ -556,32 +497,27 @@ public class LibaioTest } @Test - public void testIOExceptionConditions() throws Exception - { + public void testIOExceptionConditions() throws Exception { boolean exceptionThrown = false; control.close(); control = new LibaioContext<>(LIBAIO_QUEUE_SIZE, false); - try - { + try { // There is no space for a queue this huge, the native layer should throw the exception LibaioContext newController = new LibaioContext(Integer.MAX_VALUE, false); } - catch (RuntimeException e) - { + catch (RuntimeException e) { exceptionThrown = true; } Assert.assertTrue(exceptionThrown); exceptionThrown = false; - try - { + try { // this should throw an exception, we shouldn't be able to open a directory! control.openFile(temporaryFolder.getRoot(), true); } - catch (IOException expected) - { + catch (IOException expected) { exceptionThrown = true; } @@ -591,12 +527,10 @@ public class LibaioTest LibaioFile fileDescriptor = control.openFile(temporaryFolder.newFile(), true); fileDescriptor.close(); - try - { + try { fileDescriptor.close(); } - catch (IOException expected) - { + catch (IOException expected) { exceptionThrown = true; } @@ -606,25 +540,20 @@ public class LibaioTest ByteBuffer buffer = fileDescriptor.newBuffer(512); - try - { - for (int i = 0; i < 512; i++) - { + try { + for (int i = 0; i < 512; i++) { buffer.put((byte) 'a'); } - for (int i = 0; i < LIBAIO_QUEUE_SIZE; i++) - { + for (int i = 0; i < LIBAIO_QUEUE_SIZE; i++) { fileDescriptor.write(i * 512, 512, buffer, new TestInfo()); } boolean ex = false; - try - { + try { fileDescriptor.write(0, 512, buffer, new TestInfo()); } - catch (Exception e) - { + catch (Exception e) { ex = true; } @@ -651,50 +580,41 @@ public class LibaioTest TestInfo.checkLeaks(); exceptionThrown = false; - try - { + try { LibaioContext.newAlignedBuffer(300, 512); } - catch (RuntimeException e) - { + catch (RuntimeException e) { exceptionThrown = true; } Assert.assertTrue(exceptionThrown); exceptionThrown = false; - try - { + try { LibaioContext.newAlignedBuffer(-512, 512); } - catch (RuntimeException e) - { + catch (RuntimeException e) { exceptionThrown = true; } Assert.assertTrue(exceptionThrown); } - finally - { + finally { LibaioContext.freeBuffer(buffer); } } @Test - public void testBlockedCallback() throws Exception - { + public void testBlockedCallback() throws Exception { final LibaioContext blockedContext = new LibaioContext(500, true); - Thread t = new Thread() - { - public void run() - { + Thread t = new Thread() { + public void run() { blockedContext.poll(); } }; t.start(); - int NUMBER_OF_BLOCKS = 5000; final CountDownLatch latch = new CountDownLatch(NUMBER_OF_BLOCKS); @@ -705,17 +625,15 @@ public class LibaioTest final AtomicInteger errors = new AtomicInteger(0); - class MyCallback implements SubmitInfo - { + class MyCallback implements SubmitInfo { + @Override - public void onError(int errno, String message) - { + public void onError(int errno, String message) { errors.incrementAndGet(); } @Override - public void done() - { + public void done() { latch.countDown(); } } @@ -724,16 +642,13 @@ public class LibaioTest ByteBuffer buffer = LibaioContext.newAlignedBuffer(512, 512); - - for (int i = 0; i < 512; i++) - { - buffer.put((byte)'a'); + for (int i = 0; i < 512; i++) { + buffer.put((byte) 'a'); } long start = System.currentTimeMillis(); - for (int i = 0; i < NUMBER_OF_BLOCKS; i++) - { + for (int i = 0; i < NUMBER_OF_BLOCKS; i++) { aioFile.write(i * 512, 512, buffer, callback); } @@ -741,19 +656,18 @@ public class LibaioTest latch.await(); - System.out.println("time = " + (end - start) + " writes/second=" + NUMBER_OF_BLOCKS * 1000L / (end - start)); -// -// MultiThreadAsynchronousFileTest.debug((sync ? "Sync result:" : "Async result:") + " Records/Second = " + -// MultiThreadAsynchronousFileTest.NUMBER_OF_THREADS * -// MultiThreadAsynchronousFileTest.NUMBER_OF_LINES * -// 1000 / -// (endTime - startTime) + -// " total time = " + -// (endTime - startTime) + -// " total number of records = " + -// MultiThreadAsynchronousFileTest.NUMBER_OF_THREADS * -// MultiThreadAsynchronousFileTest.NUMBER_OF_LINES); + // + // MultiThreadAsynchronousFileTest.debug((sync ? "Sync result:" : "Async result:") + " Records/Second = " + + // MultiThreadAsynchronousFileTest.NUMBER_OF_THREADS * + // MultiThreadAsynchronousFileTest.NUMBER_OF_LINES * + // 1000 / + // (endTime - startTime) + + // " total time = " + + // (endTime - startTime) + + // " total number of records = " + + // MultiThreadAsynchronousFileTest.NUMBER_OF_THREADS * + // MultiThreadAsynchronousFileTest.NUMBER_OF_LINES); Thread.sleep(100); @@ -761,42 +675,34 @@ public class LibaioTest t.join(); } - private void fillupFile(File file, int blocks) throws IOException - { + private void fillupFile(File file, int blocks) throws IOException { FileOutputStream fileOutputStream = new FileOutputStream(file); byte[] bufferWrite = new byte[512]; - for (int i = 0; i < 512; i++) - { + for (int i = 0; i < 512; i++) { bufferWrite[i] = (byte) 0; } - for (int i = 0; i < blocks; i++) - { + for (int i = 0; i < blocks; i++) { fileOutputStream.write(bufferWrite); } fileOutputStream.close(); } + static class TestInfo implements SubmitInfo { - static class TestInfo implements SubmitInfo - { static AtomicInteger count = new AtomicInteger(); @Override - protected void finalize() throws Throwable - { + protected void finalize() throws Throwable { super.finalize(); count.decrementAndGet(); } - public static void checkLeaks() throws InterruptedException - { - for (int i = 0; count.get() != 0 && i < 50; i++) - { + public static void checkLeaks() throws InterruptedException { + for (int i = 0; count.get() != 0 && i < 50; i++) { WeakReference reference = new WeakReference(new Object()); - while (reference.get() != null) - { + while (reference.get() != null) { System.gc(); Thread.sleep(100); } @@ -808,51 +714,42 @@ public class LibaioTest String errorMessage; int errno; - public TestInfo() - { + public TestInfo() { count.incrementAndGet(); } @Override - public void onError(int errno, String message) - { + public void onError(int errno, String message) { this.errno = errno; this.errorMessage = message; this.error = true; } @Override - public void done() - { + public void done() { } - public int getErrno() - { + public int getErrno() { return errno; } - public void setErrno(int errno) - { + public void setErrno(int errno) { this.errno = errno; } - public boolean isError() - { + public boolean isError() { return error; } - public void setError(boolean error) - { + public void setError(boolean error) { this.error = error; } - public String getErrorMessage() - { + public String getErrorMessage() { return errorMessage; } - public void setErrorMessage(String errorMessage) - { + public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } } diff --git a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/ActiveMQProtonRemotingConnection.java b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/ActiveMQProtonRemotingConnection.java index 3b8ca6a35e..ea8582aaa2 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/ActiveMQProtonRemotingConnection.java +++ b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/ActiveMQProtonRemotingConnection.java @@ -28,39 +28,36 @@ import org.proton.plug.AMQPConnectionContext; /** * This is a Server's Connection representation used by ActiveMQ Artemis. */ -public class ActiveMQProtonRemotingConnection extends AbstractRemotingConnection -{ +public class ActiveMQProtonRemotingConnection extends AbstractRemotingConnection { + private final AMQPConnectionContext amqpConnection; private boolean destroyed = false; private final ProtonProtocolManager manager; - - public ActiveMQProtonRemotingConnection(ProtonProtocolManager manager, AMQPConnectionContext amqpConnection, Connection transportConnection, Executor executor) - { + public ActiveMQProtonRemotingConnection(ProtonProtocolManager manager, + AMQPConnectionContext amqpConnection, + Connection transportConnection, + Executor executor) { super(transportConnection, executor); this.manager = manager; this.amqpConnection = amqpConnection; } - public Executor getExecutor() - { + public Executor getExecutor() { return this.executor; } - public ProtonProtocolManager getManager() - { + public ProtonProtocolManager getManager() { return manager; } /* * This can be called concurrently by more than one thread so needs to be locked */ - public void fail(final ActiveMQException me, String scaleDownTargetNodeID) - { - if (destroyed) - { + public void fail(final ActiveMQException me, String scaleDownTargetNodeID) { + if (destroyed) { return; } @@ -76,21 +73,16 @@ public class ActiveMQProtonRemotingConnection extends AbstractRemotingConnection internalClose(); } - @Override - public void destroy() - { - synchronized (this) - { - if (destroyed) - { + public void destroy() { + synchronized (this) { + if (destroyed) { return; } destroyed = true; } - callClosingListeners(); internalClose(); @@ -98,20 +90,17 @@ public class ActiveMQProtonRemotingConnection extends AbstractRemotingConnection } @Override - public boolean isClient() - { + public boolean isClient() { return false; } @Override - public boolean isDestroyed() - { + public boolean isDestroyed() { return destroyed; } @Override - public void disconnect(boolean criticalError) - { + public void disconnect(boolean criticalError) { getTransportConnection().close(); } @@ -119,32 +108,27 @@ public class ActiveMQProtonRemotingConnection extends AbstractRemotingConnection * Disconnect the connection, closing all channels */ @Override - public void disconnect(String scaleDownNodeID, boolean criticalError) - { + public void disconnect(String scaleDownNodeID, boolean criticalError) { getTransportConnection().close(); } @Override - public boolean checkDataReceived() - { + public boolean checkDataReceived() { return amqpConnection.checkDataReceived(); } @Override - public void flush() - { + public void flush() { amqpConnection.flush(); } @Override - public void bufferReceived(Object connectionID, ActiveMQBuffer buffer) - { + public void bufferReceived(Object connectionID, ActiveMQBuffer buffer) { amqpConnection.inputBuffer(buffer.byteBuf()); super.bufferReceived(connectionID, buffer); } - private void internalClose() - { + private void internalClose() { // We close the underlying transport connection getTransportConnection().close(); } diff --git a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/ProtonProtocolManager.java b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/ProtonProtocolManager.java index f50d3e4c5b..3637289db8 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/ProtonProtocolManager.java +++ b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/ProtonProtocolManager.java @@ -46,67 +46,54 @@ import static org.proton.plug.context.AMQPConstants.Connection.DEFAULT_MAX_FRAME /** * A proton protocol manager, basically reads the Proton Input and maps proton resources to ActiveMQ Artemis resources */ -public class ProtonProtocolManager implements ProtocolManager, NotificationListener -{ +public class ProtonProtocolManager implements ProtocolManager, NotificationListener { + private final ActiveMQServer server; private MessageConverter protonConverter; - private final ProtonProtocolManagerFactory factory; - public ProtonProtocolManager(ProtonProtocolManagerFactory factory, ActiveMQServer server) - { + public ProtonProtocolManager(ProtonProtocolManagerFactory factory, ActiveMQServer server) { this.factory = factory; this.server = server; this.protonConverter = new ProtonMessageConverter(server.getStorageManager()); } - public ActiveMQServer getServer() - { + public ActiveMQServer getServer() { return server; } - @Override - public MessageConverter getConverter() - { + public MessageConverter getConverter() { return protonConverter; } @Override - public void onNotification(Notification notification) - { + public void onNotification(Notification notification) { } @Override - public ProtocolManagerFactory getFactory() - { + public ProtocolManagerFactory getFactory() { return factory; } @Override - public void updateInterceptors(List incomingInterceptors, List outgoingInterceptors) - { + public void updateInterceptors(List incomingInterceptors, + List outgoingInterceptors) { // no op } @Override - public ConnectionEntry createConnectionEntry(Acceptor acceptorUsed, Connection remotingConnection) - { + public ConnectionEntry createConnectionEntry(Acceptor acceptorUsed, Connection remotingConnection) { ActiveMQProtonConnectionCallback connectionCallback = new ActiveMQProtonConnectionCallback(this, remotingConnection); long ttl = ActiveMQClient.DEFAULT_CONNECTION_TTL; - if (server.getConfiguration().getConnectionTTLOverride() != -1) - { + if (server.getConfiguration().getConnectionTTLOverride() != -1) { ttl = server.getConfiguration().getConnectionTTLOverride(); } - AMQPServerConnectionContext amqpConnection = ProtonServerConnectionContextFactory.getFactory().createConnection( - connectionCallback, - (int) ttl, - DEFAULT_MAX_FRAME_SIZE, - DEFAULT_CHANNEL_MAX); + AMQPServerConnectionContext amqpConnection = ProtonServerConnectionContextFactory.getFactory().createConnection(connectionCallback, (int) ttl, DEFAULT_MAX_FRAME_SIZE, DEFAULT_CHANNEL_MAX); Executor executor = server.getExecutorFactory().getExecutor(); @@ -114,42 +101,35 @@ public class ProtonProtocolManager implements ProtocolManager, Noti connectionCallback.setProtonConnectionDelegate(delegate); - ConnectionEntry entry = new ConnectionEntry(delegate, executor, - System.currentTimeMillis(), ttl); + ConnectionEntry entry = new ConnectionEntry(delegate, executor, System.currentTimeMillis(), ttl); return entry; } @Override - public void removeHandler(String name) - { + public void removeHandler(String name) { } @Override - public void handleBuffer(RemotingConnection connection, ActiveMQBuffer buffer) - { + public void handleBuffer(RemotingConnection connection, ActiveMQBuffer buffer) { ActiveMQProtonRemotingConnection protonConnection = (ActiveMQProtonRemotingConnection) connection; protonConnection.bufferReceived(protonConnection.getID(), buffer); } @Override - public void addChannelHandlers(ChannelPipeline pipeline) - { + public void addChannelHandlers(ChannelPipeline pipeline) { } @Override - public boolean isProtocol(byte[] array) - { + public boolean isProtocol(byte[] array) { return array.length >= 4 && array[0] == (byte) 'A' && array[1] == (byte) 'M' && array[2] == (byte) 'Q' && array[3] == (byte) 'P'; } @Override - public void handshake(NettyServerConnection connection, ActiveMQBuffer buffer) - { + public void handshake(NettyServerConnection connection, ActiveMQBuffer buffer) { } - } diff --git a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/ProtonProtocolManagerFactory.java b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/ProtonProtocolManagerFactory.java index f45daaec92..7a1d25ee91 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/ProtonProtocolManagerFactory.java +++ b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/ProtonProtocolManagerFactory.java @@ -25,8 +25,8 @@ import org.apache.activemq.artemis.spi.core.protocol.ProtocolManager; import java.util.Collections; import java.util.List; -public class ProtonProtocolManagerFactory extends AbstractProtocolManagerFactory -{ +public class ProtonProtocolManagerFactory extends AbstractProtocolManagerFactory { + private static final String AMQP_PROTOCOL_NAME = "AMQP"; private static final String MODULE_NAME = "artemis-amqp-protocol"; @@ -34,27 +34,25 @@ public class ProtonProtocolManagerFactory extends AbstractProtocolManagerFactory private static String[] SUPPORTED_PROTOCOLS = {AMQP_PROTOCOL_NAME}; @Override - public ProtocolManager createProtocolManager(ActiveMQServer server, List incomingInterceptors, List outgoingInterceptors) - { + public ProtocolManager createProtocolManager(ActiveMQServer server, + List incomingInterceptors, + List outgoingInterceptors) { return new ProtonProtocolManager(this, server); } @Override - public List filterInterceptors(List interceptors) - { + public List filterInterceptors(List interceptors) { // no interceptors on Proton return Collections.emptyList(); } @Override - public String[] getProtocols() - { + public String[] getProtocols() { return SUPPORTED_PROTOCOLS; } @Override - public String getModuleName() - { + public String getModuleName() { return MODULE_NAME; } } diff --git a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/ActiveMQJMSVendor.java b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/ActiveMQJMSVendor.java index 606cf31263..8e7502bf0d 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/ActiveMQJMSVendor.java +++ b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/ActiveMQJMSVendor.java @@ -35,92 +35,75 @@ import org.apache.activemq.artemis.core.server.ServerMessage; import org.apache.activemq.artemis.core.server.impl.ServerMessageImpl; import org.apache.activemq.artemis.utils.IDGenerator; -public class ActiveMQJMSVendor extends JMSVendor -{ +public class ActiveMQJMSVendor extends JMSVendor { private final IDGenerator serverGenerator; - ActiveMQJMSVendor(IDGenerator idGenerator) - { + ActiveMQJMSVendor(IDGenerator idGenerator) { this.serverGenerator = idGenerator; } @Override - public BytesMessage createBytesMessage() - { + public BytesMessage createBytesMessage() { return new ServerJMSBytesMessage(newMessage(org.apache.activemq.artemis.api.core.Message.BYTES_TYPE), 0); } @Override - public StreamMessage createStreamMessage() - { + public StreamMessage createStreamMessage() { return new ServerJMSStreamMessage(newMessage(org.apache.activemq.artemis.api.core.Message.STREAM_TYPE), 0); } @Override - public Message createMessage() - { - return new ServerJMSMessage(newMessage(org.apache.activemq.artemis.api.core.Message.DEFAULT_TYPE), 0 ); + public Message createMessage() { + return new ServerJMSMessage(newMessage(org.apache.activemq.artemis.api.core.Message.DEFAULT_TYPE), 0); } @Override - public TextMessage createTextMessage() - { + public TextMessage createTextMessage() { return new ServerJMSTextMessage(newMessage(org.apache.activemq.artemis.api.core.Message.TEXT_TYPE), 0); } @Override - public ObjectMessage createObjectMessage() - { + public ObjectMessage createObjectMessage() { return null; } @Override - public MapMessage createMapMessage() - { + public MapMessage createMapMessage() { return new ServerJMSMapMessage(newMessage(org.apache.activemq.artemis.api.core.Message.MAP_TYPE), 0); } @Override - public void setJMSXUserID(Message message, String s) - { + public void setJMSXUserID(Message message, String s) { } @Override - public Destination createDestination(String name) - { + public Destination createDestination(String name) { return super.createDestination(name); } @Override - public T createDestination(String name, Class kind) - { + public T createDestination(String name, Class kind) { return super.createDestination(name, kind); } @Override - public void setJMSXGroupID(Message message, String s) - { + public void setJMSXGroupID(Message message, String s) { } @Override - public void setJMSXGroupSequence(Message message, int i) - { + public void setJMSXGroupSequence(Message message, int i) { } @Override - public void setJMSXDeliveryCount(Message message, long l) - { + public void setJMSXDeliveryCount(Message message, long l) { } - - public ServerJMSMessage wrapMessage(int messageType, ServerMessage wrapped, int deliveryCount) - { - switch (messageType) - { + public ServerJMSMessage wrapMessage(int messageType, ServerMessage wrapped, int deliveryCount) { + switch (messageType) { case org.apache.activemq.artemis.api.core.Message.STREAM_TYPE: return new ServerJMSStreamMessage(wrapped, deliveryCount); case org.apache.activemq.artemis.api.core.Message.BYTES_TYPE: @@ -135,19 +118,15 @@ public class ActiveMQJMSVendor extends JMSVendor } - @Override - public String toAddress(Destination destination) - { + public String toAddress(Destination destination) { return null; } - - private ServerMessageImpl newMessage(byte messageType) - { + private ServerMessageImpl newMessage(byte messageType) { ServerMessageImpl message = new ServerMessageImpl(serverGenerator.generateID(), 512); message.setType(messageType); - ((ResetLimitWrappedActiveMQBuffer)message.getBodyBuffer()).setMessage(null); + ((ResetLimitWrappedActiveMQBuffer) message.getBodyBuffer()).setMessage(null); return message; } diff --git a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/ProtonMessageConverter.java b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/ProtonMessageConverter.java index 5cee473866..4de2357b58 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/ProtonMessageConverter.java +++ b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/ProtonMessageConverter.java @@ -25,14 +25,11 @@ import org.apache.activemq.artemis.core.server.ServerMessage; import org.apache.activemq.artemis.spi.core.protocol.MessageConverter; import org.apache.activemq.artemis.utils.IDGenerator; -public class ProtonMessageConverter implements MessageConverter -{ - +public class ProtonMessageConverter implements MessageConverter { ActiveMQJMSVendor activeMQJMSVendor; - public ProtonMessageConverter(IDGenerator idGenerator) - { + public ProtonMessageConverter(IDGenerator idGenerator) { activeMQJMSVendor = new ActiveMQJMSVendor(idGenerator); inboundTransformer = new JMSMappingInboundTransformer(activeMQJMSVendor); outboundTransformer = new JMSMappingOutboundTransformer(activeMQJMSVendor); @@ -42,33 +39,30 @@ public class ProtonMessageConverter implements MessageConverter private final JMSMappingOutboundTransformer outboundTransformer; @Override - public ServerMessage inbound(Object messageSource) throws Exception - { + public ServerMessage inbound(Object messageSource) throws Exception { ServerJMSMessage jmsMessage = inboundJMSType((EncodedMessage) messageSource); - return (ServerMessage)jmsMessage.getInnerMessage(); + return (ServerMessage) jmsMessage.getInnerMessage(); } /** * Just create the JMS Part of the inbound (for testing) + * * @param messageSource * @return * @throws Exception */ - public ServerJMSMessage inboundJMSType(EncodedMessage messageSource) throws Exception - { + public ServerJMSMessage inboundJMSType(EncodedMessage messageSource) throws Exception { EncodedMessage encodedMessageSource = messageSource; - ServerJMSMessage transformedMessage = (ServerJMSMessage)inboundTransformer.transform(encodedMessageSource); + ServerJMSMessage transformedMessage = (ServerJMSMessage) inboundTransformer.transform(encodedMessageSource); transformedMessage.encode(); return transformedMessage; } - @Override - public Object outbound(ServerMessage messageOutbound, int deliveryCount) throws Exception - { + public Object outbound(ServerMessage messageOutbound, int deliveryCount) throws Exception { ServerJMSMessage jmsMessage = activeMQJMSVendor.wrapMessage(messageOutbound.getType(), messageOutbound, deliveryCount); jmsMessage.decode(); diff --git a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/jms/ServerJMSBytesMessage.java b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/jms/ServerJMSBytesMessage.java index 4389c661c9..76e2515310 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/jms/ServerJMSBytesMessage.java +++ b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/jms/ServerJMSBytesMessage.java @@ -47,190 +47,158 @@ import static org.apache.activemq.artemis.reader.BytesMessageUtil.bytesWriteObje import static org.apache.activemq.artemis.reader.BytesMessageUtil.bytesWriteShort; import static org.apache.activemq.artemis.reader.BytesMessageUtil.bytesWriteUTF; -public class ServerJMSBytesMessage extends ServerJMSMessage implements BytesMessage -{ - public ServerJMSBytesMessage(MessageInternal message, int deliveryCount) - { +public class ServerJMSBytesMessage extends ServerJMSMessage implements BytesMessage { + + public ServerJMSBytesMessage(MessageInternal message, int deliveryCount) { super(message, deliveryCount); } @Override - public long getBodyLength() throws JMSException - { + public long getBodyLength() throws JMSException { return message.getEndOfBodyPosition() - MessageImpl.BODY_OFFSET; } @Override - public boolean readBoolean() throws JMSException - { + public boolean readBoolean() throws JMSException { return bytesReadBoolean(message); } @Override - public byte readByte() throws JMSException - { + public byte readByte() throws JMSException { return bytesReadByte(message); } @Override - public int readUnsignedByte() throws JMSException - { + public int readUnsignedByte() throws JMSException { return bytesReadUnsignedByte(message); } @Override - public short readShort() throws JMSException - { + public short readShort() throws JMSException { return bytesReadShort(message); } @Override - public int readUnsignedShort() throws JMSException - { + public int readUnsignedShort() throws JMSException { return bytesReadUnsignedShort(message); } @Override - public char readChar() throws JMSException - { + public char readChar() throws JMSException { return bytesReadChar(message); } @Override - public int readInt() throws JMSException - { + public int readInt() throws JMSException { return bytesReadInt(message); } @Override - public long readLong() throws JMSException - { + public long readLong() throws JMSException { return bytesReadLong(message); } @Override - public float readFloat() throws JMSException - { + public float readFloat() throws JMSException { return bytesReadFloat(message); } @Override - public double readDouble() throws JMSException - { + public double readDouble() throws JMSException { return bytesReadDouble(message); } @Override - public String readUTF() throws JMSException - { + public String readUTF() throws JMSException { return bytesReadUTF(message); } @Override - public int readBytes(byte[] value) throws JMSException - { + public int readBytes(byte[] value) throws JMSException { return bytesReadBytes(message, value); } @Override - public int readBytes(byte[] value, int length) throws JMSException - { + public int readBytes(byte[] value, int length) throws JMSException { return bytesReadBytes(message, value, length); } @Override - public void writeBoolean(boolean value) throws JMSException - { + public void writeBoolean(boolean value) throws JMSException { bytesWriteBoolean(message, value); } @Override - public void writeByte(byte value) throws JMSException - { + public void writeByte(byte value) throws JMSException { bytesWriteByte(message, value); } @Override - public void writeShort(short value) throws JMSException - { + public void writeShort(short value) throws JMSException { bytesWriteShort(message, value); } @Override - public void writeChar(char value) throws JMSException - { + public void writeChar(char value) throws JMSException { bytesWriteChar(message, value); } @Override - public void writeInt(int value) throws JMSException - { + public void writeInt(int value) throws JMSException { bytesWriteInt(message, value); } @Override - public void writeLong(long value) throws JMSException - { + public void writeLong(long value) throws JMSException { bytesWriteLong(message, value); } @Override - public void writeFloat(float value) throws JMSException - { + public void writeFloat(float value) throws JMSException { bytesWriteFloat(message, value); } @Override - public void writeDouble(double value) throws JMSException - { + public void writeDouble(double value) throws JMSException { bytesWriteDouble(message, value); } @Override - public void writeUTF(String value) throws JMSException - { + public void writeUTF(String value) throws JMSException { bytesWriteUTF(message, value); } @Override - public void writeBytes(byte[] value) throws JMSException - { + public void writeBytes(byte[] value) throws JMSException { bytesWriteBytes(message, value); } @Override - public void writeBytes(byte[] value, int offset, int length) throws JMSException - { + public void writeBytes(byte[] value, int offset, int length) throws JMSException { bytesWriteBytes(message, value, offset, length); } @Override - public void writeObject(Object value) throws JMSException - { - if (!bytesWriteObject(message, value)) - { + public void writeObject(Object value) throws JMSException { + if (!bytesWriteObject(message, value)) { throw new JMSException("Can't make conversion of " + value + " to any known type"); } } - public void encode() throws Exception - { + public void encode() throws Exception { super.encode(); // this is to make sure we encode the body-length before it's persisted getBodyLength(); } - - public void decode() throws Exception - { + public void decode() throws Exception { super.decode(); } @Override - public void reset() throws JMSException - { + public void reset() throws JMSException { bytesMessageReset(message); } diff --git a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/jms/ServerJMSMapMessage.java b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/jms/ServerJMSMapMessage.java index 9d5fb9d90b..bbece712d4 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/jms/ServerJMSMapMessage.java +++ b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/jms/ServerJMSMapMessage.java @@ -36,8 +36,7 @@ import static org.apache.activemq.artemis.reader.MapMessageUtil.writeBodyMap; /** * ActiveMQ Artemis implementation of a JMS MapMessage. */ -public final class ServerJMSMapMessage extends ServerJMSMessage implements MapMessage -{ +public final class ServerJMSMapMessage extends ServerJMSMessage implements MapMessage { // Constants ----------------------------------------------------- public static final byte TYPE = Message.MAP_TYPE; @@ -53,68 +52,55 @@ public final class ServerJMSMapMessage extends ServerJMSMessage implements MapMe /* * This constructor is used to construct messages prior to sending */ - public ServerJMSMapMessage(MessageInternal message, int deliveryCount) - { + public ServerJMSMapMessage(MessageInternal message, int deliveryCount) { super(message, deliveryCount); } // MapMessage implementation ------------------------------------- - public void setBoolean(final String name, final boolean value) throws JMSException - { + public void setBoolean(final String name, final boolean value) throws JMSException { map.putBooleanProperty(new SimpleString(name), value); } - public void setByte(final String name, final byte value) throws JMSException - { + public void setByte(final String name, final byte value) throws JMSException { map.putByteProperty(new SimpleString(name), value); } - public void setShort(final String name, final short value) throws JMSException - { + public void setShort(final String name, final short value) throws JMSException { map.putShortProperty(new SimpleString(name), value); } - public void setChar(final String name, final char value) throws JMSException - { + public void setChar(final String name, final char value) throws JMSException { map.putCharProperty(new SimpleString(name), value); } - public void setInt(final String name, final int value) throws JMSException - { + public void setInt(final String name, final int value) throws JMSException { map.putIntProperty(new SimpleString(name), value); } - public void setLong(final String name, final long value) throws JMSException - { + public void setLong(final String name, final long value) throws JMSException { map.putLongProperty(new SimpleString(name), value); } - public void setFloat(final String name, final float value) throws JMSException - { + public void setFloat(final String name, final float value) throws JMSException { map.putFloatProperty(new SimpleString(name), value); } - public void setDouble(final String name, final double value) throws JMSException - { + public void setDouble(final String name, final double value) throws JMSException { map.putDoubleProperty(new SimpleString(name), value); } - public void setString(final String name, final String value) throws JMSException - { + public void setString(final String name, final String value) throws JMSException { map.putSimpleStringProperty(new SimpleString(name), value == null ? null : new SimpleString(value)); } - public void setBytes(final String name, final byte[] value) throws JMSException - { + public void setBytes(final String name, final byte[] value) throws JMSException { map.putBytesProperty(new SimpleString(name), value); } - public void setBytes(final String name, final byte[] value, final int offset, final int length) throws JMSException - { - if (offset + length > value.length) - { + public void setBytes(final String name, final byte[] value, final int offset, final int length) throws JMSException { + if (offset + length > value.length) { throw new JMSException("Invalid offset/length"); } byte[] newBytes = new byte[length]; @@ -122,194 +108,149 @@ public final class ServerJMSMapMessage extends ServerJMSMessage implements MapMe map.putBytesProperty(new SimpleString(name), newBytes); } - public void setObject(final String name, final Object value) throws JMSException - { - try - { + public void setObject(final String name, final Object value) throws JMSException { + try { TypedProperties.setObjectProperty(new SimpleString(name), value, map); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public boolean getBoolean(final String name) throws JMSException - { - try - { + public boolean getBoolean(final String name) throws JMSException { + try { return map.getBooleanProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public byte getByte(final String name) throws JMSException - { - try - { + public byte getByte(final String name) throws JMSException { + try { return map.getByteProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public short getShort(final String name) throws JMSException - { - try - { + public short getShort(final String name) throws JMSException { + try { return map.getShortProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public char getChar(final String name) throws JMSException - { - try - { + public char getChar(final String name) throws JMSException { + try { return map.getCharProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public int getInt(final String name) throws JMSException - { - try - { + public int getInt(final String name) throws JMSException { + try { return map.getIntProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public long getLong(final String name) throws JMSException - { - try - { + public long getLong(final String name) throws JMSException { + try { return map.getLongProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public float getFloat(final String name) throws JMSException - { - try - { + public float getFloat(final String name) throws JMSException { + try { return map.getFloatProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public double getDouble(final String name) throws JMSException - { - try - { + public double getDouble(final String name) throws JMSException { + try { return map.getDoubleProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public String getString(final String name) throws JMSException - { - try - { + public String getString(final String name) throws JMSException { + try { SimpleString str = map.getSimpleStringProperty(new SimpleString(name)); - if (str == null) - { + if (str == null) { return null; } - else - { + else { return str.toString(); } } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public byte[] getBytes(final String name) throws JMSException - { - try - { + public byte[] getBytes(final String name) throws JMSException { + try { return map.getBytesProperty(new SimpleString(name)); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { throw new MessageFormatException(e.getMessage()); } } - public Object getObject(final String name) throws JMSException - { + public Object getObject(final String name) throws JMSException { Object val = map.getProperty(new SimpleString(name)); - if (val instanceof SimpleString) - { + if (val instanceof SimpleString) { val = ((SimpleString) val).toString(); } return val; } - public Enumeration getMapNames() throws JMSException - { + public Enumeration getMapNames() throws JMSException { Set simplePropNames = map.getPropertyNames(); Set propNames = new HashSet(simplePropNames.size()); - for (SimpleString str : simplePropNames) - { + for (SimpleString str : simplePropNames) { propNames.add(str.toString()); } return Collections.enumeration(propNames); } - public boolean itemExists(final String name) throws JMSException - { + public boolean itemExists(final String name) throws JMSException { return map.containsProperty(new SimpleString(name)); } - @Override - public void clearBody() throws JMSException - { + public void clearBody() throws JMSException { super.clearBody(); map.clear(); } - - public void encode() throws Exception - { + public void encode() throws Exception { super.encode(); writeBodyMap(message, map); } - public void decode() throws Exception - { + public void decode() throws Exception { super.decode(); readBodyMap(message, map); } diff --git a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/jms/ServerJMSMessage.java b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/jms/ServerJMSMessage.java index 81699e8c91..315dd129b5 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/jms/ServerJMSMessage.java +++ b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/jms/ServerJMSMessage.java @@ -30,256 +30,207 @@ import org.apache.activemq.artemis.jms.client.ActiveMQDestination; import org.apache.activemq.artemis.jms.client.ActiveMQQueue; import org.apache.activemq.artemis.reader.MessageUtil; -public class ServerJMSMessage implements Message -{ +public class ServerJMSMessage implements Message { + protected final MessageInternal message; protected int deliveryCount; - public MessageInternal getInnerMessage() - { + public MessageInternal getInnerMessage() { return message; } - - public ServerJMSMessage(MessageInternal message, int deliveryCount) - { + public ServerJMSMessage(MessageInternal message, int deliveryCount) { this.message = message; this.deliveryCount = deliveryCount; } - @Override - public final String getJMSMessageID() throws JMSException - { + public final String getJMSMessageID() throws JMSException { return null; } @Override - public final void setJMSMessageID(String id) throws JMSException - { + public final void setJMSMessageID(String id) throws JMSException { } @Override - public final long getJMSTimestamp() throws JMSException - { + public final long getJMSTimestamp() throws JMSException { return message.getTimestamp(); } @Override - public final void setJMSTimestamp(long timestamp) throws JMSException - { + public final void setJMSTimestamp(long timestamp) throws JMSException { message.setTimestamp(timestamp); } - @Override - public final byte[] getJMSCorrelationIDAsBytes() throws JMSException - { + public final byte[] getJMSCorrelationIDAsBytes() throws JMSException { return MessageUtil.getJMSCorrelationIDAsBytes(message); } @Override - public final void setJMSCorrelationIDAsBytes(byte[] correlationID) throws JMSException - { - try - { + public final void setJMSCorrelationIDAsBytes(byte[] correlationID) throws JMSException { + try { MessageUtil.setJMSCorrelationIDAsBytes(message, correlationID); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw new JMSException(e.getMessage()); } } @Override - public final void setJMSCorrelationID(String correlationID) throws JMSException - { + public final void setJMSCorrelationID(String correlationID) throws JMSException { MessageUtil.setJMSCorrelationID(message, correlationID); } @Override - public final String getJMSCorrelationID() throws JMSException - { + public final String getJMSCorrelationID() throws JMSException { return MessageUtil.getJMSCorrelationID(message); } @Override - public final Destination getJMSReplyTo() throws JMSException - { + public final Destination getJMSReplyTo() throws JMSException { SimpleString reply = MessageUtil.getJMSReplyTo(message); - if (reply != null) - { + if (reply != null) { return ActiveMQDestination.fromAddress(reply.toString()); } - else - { + else { return null; } } @Override - public final void setJMSReplyTo(Destination replyTo) throws JMSException - { + public final void setJMSReplyTo(Destination replyTo) throws JMSException { MessageUtil.setJMSReplyTo(message, replyTo == null ? null : ((ActiveMQDestination) replyTo).getSimpleAddress()); } - public final Destination getJMSDestination() throws JMSException - { + public final Destination getJMSDestination() throws JMSException { SimpleString sdest = message.getAddress(); - if (sdest == null) - { + if (sdest == null) { return null; } - else - { - if (!sdest.toString().startsWith("jms.")) - { + else { + if (!sdest.toString().startsWith("jms.")) { return new ActiveMQQueue(sdest.toString(), sdest.toString()); } - else - { + else { return ActiveMQDestination.fromAddress(sdest.toString()); } } } @Override - public final void setJMSDestination(Destination destination) throws JMSException - { - if (destination == null) - { + public final void setJMSDestination(Destination destination) throws JMSException { + if (destination == null) { message.setAddress(null); } - else - { + else { message.setAddress(((ActiveMQDestination) destination).getSimpleAddress()); } } @Override - public final int getJMSDeliveryMode() throws JMSException - { + public final int getJMSDeliveryMode() throws JMSException { return message.isDurable() ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT; } @Override - public final void setJMSDeliveryMode(int deliveryMode) throws JMSException - { - if (deliveryMode == DeliveryMode.PERSISTENT) - { + public final void setJMSDeliveryMode(int deliveryMode) throws JMSException { + if (deliveryMode == DeliveryMode.PERSISTENT) { message.setDurable(true); } - else if (deliveryMode == DeliveryMode.NON_PERSISTENT) - { + else if (deliveryMode == DeliveryMode.NON_PERSISTENT) { message.setDurable(false); } - else - { + else { throw new JMSException("Invalid mode " + deliveryMode); } } @Override - public final boolean getJMSRedelivered() throws JMSException - { + public final boolean getJMSRedelivered() throws JMSException { return false; } @Override - public final void setJMSRedelivered(boolean redelivered) throws JMSException - { + public final void setJMSRedelivered(boolean redelivered) throws JMSException { // no op } @Override - public final String getJMSType() throws JMSException - { + public final String getJMSType() throws JMSException { return MessageUtil.getJMSType(message); } @Override - public final void setJMSType(String type) throws JMSException - { + public final void setJMSType(String type) throws JMSException { MessageUtil.setJMSType(message, type); } @Override - public final long getJMSExpiration() throws JMSException - { + public final long getJMSExpiration() throws JMSException { return message.getExpiration(); } @Override - public final void setJMSExpiration(long expiration) throws JMSException - { + public final void setJMSExpiration(long expiration) throws JMSException { message.setExpiration(expiration); } @Override - public final long getJMSDeliveryTime() throws JMSException - { + public final long getJMSDeliveryTime() throws JMSException { // no op return 0; } @Override - public final void setJMSDeliveryTime(long deliveryTime) throws JMSException - { + public final void setJMSDeliveryTime(long deliveryTime) throws JMSException { // no op } @Override - public final int getJMSPriority() throws JMSException - { + public final int getJMSPriority() throws JMSException { return message.getPriority(); } @Override - public final void setJMSPriority(int priority) throws JMSException - { + public final void setJMSPriority(int priority) throws JMSException { message.setPriority((byte) priority); } @Override - public final void clearProperties() throws JMSException - { + public final void clearProperties() throws JMSException { MessageUtil.clearProperties(message); } @Override - public final boolean propertyExists(String name) throws JMSException - { + public final boolean propertyExists(String name) throws JMSException { return MessageUtil.propertyExists(message, name); } @Override - public final boolean getBooleanProperty(String name) throws JMSException - { + public final boolean getBooleanProperty(String name) throws JMSException { return message.getBooleanProperty(name); } @Override - public final byte getByteProperty(String name) throws JMSException - { + public final byte getByteProperty(String name) throws JMSException { return message.getByteProperty(name); } @Override - public final short getShortProperty(String name) throws JMSException - { + public final short getShortProperty(String name) throws JMSException { return message.getShortProperty(name); } @Override - public final int getIntProperty(String name) throws JMSException - { - if (MessageUtil.JMSXDELIVERYCOUNT.equals(name)) - { + public final int getIntProperty(String name) throws JMSException { + if (MessageUtil.JMSXDELIVERYCOUNT.equals(name)) { return deliveryCount; } @@ -287,10 +238,8 @@ public class ServerJMSMessage implements Message } @Override - public final long getLongProperty(String name) throws JMSException - { - if (MessageUtil.JMSXDELIVERYCOUNT.equals(name)) - { + public final long getLongProperty(String name) throws JMSException { + if (MessageUtil.JMSXDELIVERYCOUNT.equals(name)) { return deliveryCount; } @@ -298,115 +247,95 @@ public class ServerJMSMessage implements Message } @Override - public final float getFloatProperty(String name) throws JMSException - { + public final float getFloatProperty(String name) throws JMSException { return message.getFloatProperty(name); } @Override - public final double getDoubleProperty(String name) throws JMSException - { + public final double getDoubleProperty(String name) throws JMSException { return message.getDoubleProperty(name); } @Override - public final String getStringProperty(String name) throws JMSException - { - if (MessageUtil.JMSXDELIVERYCOUNT.equals(name)) - { + public final String getStringProperty(String name) throws JMSException { + if (MessageUtil.JMSXDELIVERYCOUNT.equals(name)) { return String.valueOf(deliveryCount); } - return message.getStringProperty(name); } @Override - public final Object getObjectProperty(String name) throws JMSException - { + public final Object getObjectProperty(String name) throws JMSException { Object val = message.getObjectProperty(name); - if (val instanceof SimpleString) - { - val = ((SimpleString)val).toString(); + if (val instanceof SimpleString) { + val = ((SimpleString) val).toString(); } return val; } @Override - public final Enumeration getPropertyNames() throws JMSException - { + public final Enumeration getPropertyNames() throws JMSException { return Collections.enumeration(MessageUtil.getPropertyNames(message)); } @Override - public final void setBooleanProperty(String name, boolean value) throws JMSException - { + public final void setBooleanProperty(String name, boolean value) throws JMSException { message.putBooleanProperty(name, value); } @Override - public final void setByteProperty(String name, byte value) throws JMSException - { + public final void setByteProperty(String name, byte value) throws JMSException { message.putByteProperty(name, value); } @Override - public final void setShortProperty(String name, short value) throws JMSException - { + public final void setShortProperty(String name, short value) throws JMSException { message.putShortProperty(name, value); } @Override - public final void setIntProperty(String name, int value) throws JMSException - { + public final void setIntProperty(String name, int value) throws JMSException { message.putIntProperty(name, value); } @Override - public final void setLongProperty(String name, long value) throws JMSException - { + public final void setLongProperty(String name, long value) throws JMSException { message.putLongProperty(name, value); } @Override - public final void setFloatProperty(String name, float value) throws JMSException - { + public final void setFloatProperty(String name, float value) throws JMSException { message.putFloatProperty(name, value); } @Override - public final void setDoubleProperty(String name, double value) throws JMSException - { + public final void setDoubleProperty(String name, double value) throws JMSException { message.putDoubleProperty(name, value); } @Override - public final void setStringProperty(String name, String value) throws JMSException - { + public final void setStringProperty(String name, String value) throws JMSException { message.putStringProperty(name, value); } @Override - public final void setObjectProperty(String name, Object value) throws JMSException - { + public final void setObjectProperty(String name, Object value) throws JMSException { message.putObjectProperty(name, value); } @Override - public final void acknowledge() throws JMSException - { + public final void acknowledge() throws JMSException { // no op } @Override - public void clearBody() throws JMSException - { + public void clearBody() throws JMSException { message.getBodyBuffer().clear(); } @Override - public final T getBody(Class c) throws JMSException - { + public final T getBody(Class c) throws JMSException { // no op.. jms2 not used on the conversion return null; } @@ -414,20 +343,16 @@ public class ServerJMSMessage implements Message /** * Encode the body into the internal message */ - public void encode() throws Exception - { + public void encode() throws Exception { message.getBodyBuffer().resetReaderIndex(); } - - public void decode() throws Exception - { + public void decode() throws Exception { message.getBodyBuffer().resetReaderIndex(); } @Override - public final boolean isBodyAssignableTo(Class c) throws JMSException - { + public final boolean isBodyAssignableTo(Class c) throws JMSException { // no op.. jms2 not used on the conversion return false; } diff --git a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/jms/ServerJMSStreamMessage.java b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/jms/ServerJMSStreamMessage.java index 6b4e0c8e63..1afc8eb160 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/jms/ServerJMSStreamMessage.java +++ b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/jms/ServerJMSStreamMessage.java @@ -40,168 +40,130 @@ import static org.apache.activemq.artemis.reader.StreamMessageUtil.streamReadObj import static org.apache.activemq.artemis.reader.StreamMessageUtil.streamReadShort; import static org.apache.activemq.artemis.reader.StreamMessageUtil.streamReadString; -public final class ServerJMSStreamMessage extends ServerJMSMessage implements StreamMessage -{ +public final class ServerJMSStreamMessage extends ServerJMSMessage implements StreamMessage { + public static final byte TYPE = Message.STREAM_TYPE; private int bodyLength = 0; - - public ServerJMSStreamMessage(MessageInternal message, int deliveryCount) - { + public ServerJMSStreamMessage(MessageInternal message, int deliveryCount) { super(message, deliveryCount); } // StreamMessage implementation ---------------------------------- - public boolean readBoolean() throws JMSException - { - try - { + public boolean readBoolean() throws JMSException { + try { return streamReadBoolean(message); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { throw new MessageFormatException(e.getMessage()); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public byte readByte() throws JMSException - { - try - { + public byte readByte() throws JMSException { + try { return streamReadByte(message); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { throw new MessageFormatException(e.getMessage()); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public short readShort() throws JMSException - { + public short readShort() throws JMSException { - try - { + try { return streamReadShort(message); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { throw new MessageFormatException(e.getMessage()); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public char readChar() throws JMSException - { + public char readChar() throws JMSException { - try - { + try { return streamReadChar(message); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { throw new MessageFormatException(e.getMessage()); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public int readInt() throws JMSException - { + public int readInt() throws JMSException { - try - { + try { return streamReadInteger(message); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { throw new MessageFormatException(e.getMessage()); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public long readLong() throws JMSException - { + public long readLong() throws JMSException { - try - { + try { return streamReadLong(message); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { throw new MessageFormatException(e.getMessage()); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public float readFloat() throws JMSException - { + public float readFloat() throws JMSException { - try - { + try { return streamReadFloat(message); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { throw new MessageFormatException(e.getMessage()); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public double readDouble() throws JMSException - { + public double readDouble() throws JMSException { - try - { + try { return streamReadDouble(message); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { throw new MessageFormatException(e.getMessage()); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public String readString() throws JMSException - { + public String readString() throws JMSException { - try - { + try { return streamReadString(message); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { throw new MessageFormatException(e.getMessage()); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } @@ -211,209 +173,170 @@ public final class ServerJMSStreamMessage extends ServerJMSMessage implements St */ private int len = 0; - public int readBytes(final byte[] value) throws JMSException - { + public int readBytes(final byte[] value) throws JMSException { - try - { + try { Pair pairRead = streamReadBytes(message, len, value); len = pairRead.getA(); return pairRead.getB(); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { throw new MessageFormatException(e.getMessage()); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public Object readObject() throws JMSException - { + public Object readObject() throws JMSException { - if (getBodyBuffer(message).readerIndex() >= message.getEndOfBodyPosition()) - { + if (getBodyBuffer(message).readerIndex() >= message.getEndOfBodyPosition()) { throw new MessageEOFException(""); } - try - { + try { return streamReadObject(message); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { throw new MessageFormatException(e.getMessage()); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public void writeBoolean(final boolean value) throws JMSException - { + public void writeBoolean(final boolean value) throws JMSException { getBuffer().writeByte(DataConstants.BOOLEAN); getBuffer().writeBoolean(value); } - public void writeByte(final byte value) throws JMSException - { + public void writeByte(final byte value) throws JMSException { getBuffer().writeByte(DataConstants.BYTE); getBuffer().writeByte(value); } - public void writeShort(final short value) throws JMSException - { + public void writeShort(final short value) throws JMSException { getBuffer().writeByte(DataConstants.SHORT); getBuffer().writeShort(value); } - public void writeChar(final char value) throws JMSException - { + public void writeChar(final char value) throws JMSException { getBuffer().writeByte(DataConstants.CHAR); getBuffer().writeShort((short) value); } - public void writeInt(final int value) throws JMSException - { + public void writeInt(final int value) throws JMSException { getBuffer().writeByte(DataConstants.INT); getBuffer().writeInt(value); } - public void writeLong(final long value) throws JMSException - { + public void writeLong(final long value) throws JMSException { getBuffer().writeByte(DataConstants.LONG); getBuffer().writeLong(value); } - public void writeFloat(final float value) throws JMSException - { + public void writeFloat(final float value) throws JMSException { getBuffer().writeByte(DataConstants.FLOAT); getBuffer().writeInt(Float.floatToIntBits(value)); } - public void writeDouble(final double value) throws JMSException - { + public void writeDouble(final double value) throws JMSException { getBuffer().writeByte(DataConstants.DOUBLE); getBuffer().writeLong(Double.doubleToLongBits(value)); } - public void writeString(final String value) throws JMSException - { + public void writeString(final String value) throws JMSException { getBuffer().writeByte(DataConstants.STRING); getBuffer().writeNullableString(value); } - public void writeBytes(final byte[] value) throws JMSException - { + public void writeBytes(final byte[] value) throws JMSException { getBuffer().writeByte(DataConstants.BYTES); getBuffer().writeInt(value.length); getBuffer().writeBytes(value); } - public void writeBytes(final byte[] value, final int offset, final int length) throws JMSException - { + public void writeBytes(final byte[] value, final int offset, final int length) throws JMSException { getBuffer().writeByte(DataConstants.BYTES); getBuffer().writeInt(length); getBuffer().writeBytes(value, offset, length); } - public void writeObject(final Object value) throws JMSException - { - if (value instanceof String) - { + public void writeObject(final Object value) throws JMSException { + if (value instanceof String) { writeString((String) value); } - else if (value instanceof Boolean) - { + else if (value instanceof Boolean) { writeBoolean((Boolean) value); } - else if (value instanceof Byte) - { + else if (value instanceof Byte) { writeByte((Byte) value); } - else if (value instanceof Short) - { + else if (value instanceof Short) { writeShort((Short) value); } - else if (value instanceof Integer) - { + else if (value instanceof Integer) { writeInt((Integer) value); } - else if (value instanceof Long) - { + else if (value instanceof Long) { writeLong((Long) value); } - else if (value instanceof Float) - { + else if (value instanceof Float) { writeFloat((Float) value); } - else if (value instanceof Double) - { + else if (value instanceof Double) { writeDouble((Double) value); } - else if (value instanceof byte[]) - { + else if (value instanceof byte[]) { writeBytes((byte[]) value); } - else if (value instanceof Character) - { + else if (value instanceof Character) { writeChar((Character) value); } - else if (value == null) - { + else if (value == null) { writeString(null); } - else - { + else { throw new MessageFormatException("Invalid object type: " + value.getClass()); } } - public void reset() throws JMSException - { + public void reset() throws JMSException { getBuffer().resetReaderIndex(); } // ActiveMQRAMessage overrides ---------------------------------------- @Override - public void clearBody() throws JMSException - { + public void clearBody() throws JMSException { super.clearBody(); getBuffer().clear(); } - private ActiveMQBuffer getBuffer() - { + private ActiveMQBuffer getBuffer() { return message.getBodyBuffer(); } - - public void decode() throws Exception - { + public void decode() throws Exception { super.decode(); } /** * Encode the body into the internal message */ - public void encode() throws Exception - { + public void encode() throws Exception { super.encode(); bodyLength = message.getEndOfBodyPosition(); } diff --git a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/jms/ServerJMSTextMessage.java b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/jms/ServerJMSTextMessage.java index 7ef7042269..95e24b5a7e 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/jms/ServerJMSTextMessage.java +++ b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/converter/jms/ServerJMSTextMessage.java @@ -26,14 +26,12 @@ import org.apache.activemq.artemis.core.message.impl.MessageInternal; import static org.apache.activemq.artemis.reader.TextMessageUtil.readBodyText; import static org.apache.activemq.artemis.reader.TextMessageUtil.writeBodyText; - /** * ActiveMQ Artemis implementation of a JMS TextMessage. *
    * This class was ported from SpyTextMessage in JBossMQ. */ -public class ServerJMSTextMessage extends ServerJMSMessage implements TextMessage -{ +public class ServerJMSTextMessage extends ServerJMSMessage implements TextMessage { // Constants ----------------------------------------------------- public static final byte TYPE = Message.TEXT_TYPE; @@ -51,56 +49,45 @@ public class ServerJMSTextMessage extends ServerJMSMessage implements TextMessag /* * This constructor is used to construct messages prior to sending */ - public ServerJMSTextMessage(MessageInternal message, int deliveryCount) - { + public ServerJMSTextMessage(MessageInternal message, int deliveryCount) { super(message, deliveryCount); } // TextMessage implementation ------------------------------------ - public void setText(final String text) throws JMSException - { - if (text != null) - { + public void setText(final String text) throws JMSException { + if (text != null) { this.text = new SimpleString(text); } - else - { + else { this.text = null; } writeBodyText(message, this.text); } - public String getText() - { - if (text != null) - { + public String getText() { + if (text != null) { return text.toString(); } - else - { + else { return null; } } @Override - public void clearBody() throws JMSException - { + public void clearBody() throws JMSException { super.clearBody(); text = null; } - - public void encode() throws Exception - { + public void encode() throws Exception { super.encode(); writeBodyText(message, text); } - public void decode() throws Exception - { + public void decode() throws Exception { super.decode(); text = readBodyText(message); } diff --git a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/plug/ActiveMQProtonConnectionCallback.java b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/plug/ActiveMQProtonConnectionCallback.java index 9b62b490f4..03c6474d27 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/plug/ActiveMQProtonConnectionCallback.java +++ b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/plug/ActiveMQProtonConnectionCallback.java @@ -34,8 +34,8 @@ import org.proton.plug.AMQPSessionCallback; import org.proton.plug.ServerSASL; import org.proton.plug.sasl.AnonymousServerSASL; -public class ActiveMQProtonConnectionCallback implements AMQPConnectionCallback -{ +public class ActiveMQProtonConnectionCallback implements AMQPConnectionCallback { + private final ProtonProtocolManager manager; private final Connection connection; @@ -46,80 +46,64 @@ public class ActiveMQProtonConnectionCallback implements AMQPConnectionCallback private final ReusableLatch latch = new ReusableLatch(0); - public ActiveMQProtonConnectionCallback(ProtonProtocolManager manager, Connection connection) - { + public ActiveMQProtonConnectionCallback(ProtonProtocolManager manager, Connection connection) { this.manager = manager; this.connection = connection; } @Override - public ServerSASL[] getSASLMechnisms() - { + public ServerSASL[] getSASLMechnisms() { return new ServerSASL[]{new AnonymousServerSASL(), new ActiveMQPlainSASL(manager.getServer().getSecurityStore(), manager.getServer().getSecurityManager())}; } @Override - public void close() - { + public void close() { } - public Executor getExeuctor() - { - if (protonConnectionDelegate != null) - { + public Executor getExeuctor() { + if (protonConnectionDelegate != null) { return protonConnectionDelegate.getExecutor(); } - else - { + else { return null; } } @Override - public void setConnection(AMQPConnectionContext connection) - { + public void setConnection(AMQPConnectionContext connection) { this.amqpConnection = connection; } @Override - public AMQPConnectionContext getConnection() - { + public AMQPConnectionContext getConnection() { return amqpConnection; } - public ActiveMQProtonRemotingConnection getProtonConnectionDelegate() - { + public ActiveMQProtonRemotingConnection getProtonConnectionDelegate() { return protonConnectionDelegate; } - public void setProtonConnectionDelegate(ActiveMQProtonRemotingConnection protonConnectionDelegate) - { + public void setProtonConnectionDelegate(ActiveMQProtonRemotingConnection protonConnectionDelegate) { this.protonConnectionDelegate = protonConnectionDelegate; } - public void onTransport(ByteBuf byteBuf, AMQPConnectionContext amqpConnection) - { + public void onTransport(ByteBuf byteBuf, AMQPConnectionContext amqpConnection) { final int size = byteBuf.writerIndex(); latch.countUp(); - connection.write(new ChannelBufferWrapper(byteBuf, true), false, false, new ChannelFutureListener() - { + connection.write(new ChannelBufferWrapper(byteBuf, true), false, false, new ChannelFutureListener() { @Override - public void operationComplete(ChannelFuture future) throws Exception - { + public void operationComplete(ChannelFuture future) throws Exception { latch.countDown(); } }); - if (amqpConnection.isSyncOnFlush()) - { - try - { + if (amqpConnection.isSyncOnFlush()) { + try { latch.await(5, TimeUnit.SECONDS); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -127,10 +111,8 @@ public class ActiveMQProtonConnectionCallback implements AMQPConnectionCallback amqpConnection.outputDone(size); } - @Override - public AMQPSessionCallback createSessionCallback(AMQPConnectionContext connection) - { + public AMQPSessionCallback createSessionCallback(AMQPConnectionContext connection) { return new ProtonSessionIntegrationCallback(this, manager, connection); } diff --git a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/plug/ProtonSessionIntegrationCallback.java b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/plug/ProtonSessionIntegrationCallback.java index f74d6d793a..88506b6ee1 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/plug/ProtonSessionIntegrationCallback.java +++ b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/plug/ProtonSessionIntegrationCallback.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.core.protocol.proton.plug; - import java.util.concurrent.Executor; import io.netty.buffer.ByteBuf; @@ -49,8 +48,8 @@ import org.proton.plug.SASLResult; import org.proton.plug.context.ProtonPlugSender; import org.proton.plug.sasl.PlainSASLResult; -public class ProtonSessionIntegrationCallback implements AMQPSessionCallback, SessionCallback -{ +public class ProtonSessionIntegrationCallback implements AMQPSessionCallback, SessionCallback { + protected final IDGenerator consumerIDGenerator = new SimpleIDGenerator(0); private final ActiveMQProtonConnectionCallback protonSPI; @@ -63,23 +62,22 @@ public class ProtonSessionIntegrationCallback implements AMQPSessionCallback, Se private AMQPSessionContext protonSession; - public ProtonSessionIntegrationCallback(ActiveMQProtonConnectionCallback protonSPI, ProtonProtocolManager manager, AMQPConnectionContext connection) - { + public ProtonSessionIntegrationCallback(ActiveMQProtonConnectionCallback protonSPI, + ProtonProtocolManager manager, + AMQPConnectionContext connection) { this.protonSPI = protonSPI; this.manager = manager; this.connection = connection; } @Override - public void onFlowConsumer(Object consumer, int credits) - { + public void onFlowConsumer(Object consumer, int credits) { // We have our own flow control on AMQP, so we set activemq's flow control to 0 ((ServerConsumer) consumer).receiveCredits(-1); } @Override - public void init(AMQPSessionContext protonSession, SASLResult saslResult) throws Exception - { + public void init(AMQPSessionContext protonSession, SASLResult saslResult) throws Exception { this.protonSession = protonSession; @@ -87,39 +85,31 @@ public class ProtonSessionIntegrationCallback implements AMQPSessionCallback, Se String user = null; String passcode = null; - if (saslResult != null) - { + if (saslResult != null) { user = saslResult.getUser(); - if (saslResult instanceof PlainSASLResult) - { - passcode = ((PlainSASLResult)saslResult).getPassword(); + if (saslResult instanceof PlainSASLResult) { + passcode = ((PlainSASLResult) saslResult).getPassword(); } } - serverSession = manager.getServer().createSession(name, - user, - passcode, - ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - protonSPI.getProtonConnectionDelegate(), // RemotingConnection remotingConnection, + serverSession = manager.getServer().createSession(name, user, passcode, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, protonSPI.getProtonConnectionDelegate(), // RemotingConnection remotingConnection, false, // boolean autoCommitSends false, // boolean autoCommitAcks, false, // boolean preAcknowledge, true, //boolean xa, - (String) null, - this, - null, - true); + (String) null, this, null, true); } @Override - public void start() - { + public void start() { } @Override - public Object createSender(ProtonPlugSender protonSender, String queue, String filer, boolean browserOnly) throws Exception - { + public Object createSender(ProtonPlugSender protonSender, + String queue, + String filer, + boolean browserOnly) throws Exception { long consumerID = consumerIDGenerator.generateID(); ServerConsumer consumer = serverSession.createConsumer(consumerID, SimpleString.toSimpleString(queue), SimpleString.toSimpleString(filer), browserOnly); @@ -133,39 +123,32 @@ public class ProtonSessionIntegrationCallback implements AMQPSessionCallback, Se } @Override - public void startSender(Object brokerConsumer) throws Exception - { + public void startSender(Object brokerConsumer) throws Exception { ServerConsumer serverConsumer = (ServerConsumer) brokerConsumer; // flow control is done at proton serverConsumer.receiveCredits(-1); } @Override - public void createTemporaryQueue(String queueName) throws Exception - { + public void createTemporaryQueue(String queueName) throws Exception { serverSession.createQueue(SimpleString.toSimpleString(queueName), SimpleString.toSimpleString(queueName), null, true, false); } @Override - public boolean queueQuery(String queueName) throws Exception - { + public boolean queueQuery(String queueName) throws Exception { boolean queryResult = false; QueueQueryResult queueQuery = serverSession.executeQueueQuery(SimpleString.toSimpleString(queueName)); - if (queueQuery.isExists()) - { + if (queueQuery.isExists()) { queryResult = true; } - else - { - if (queueQuery.isAutoCreateJmsQueues()) - { + else { + if (queueQuery.isAutoCreateJmsQueues()) { serverSession.createQueue(new SimpleString(queueName), new SimpleString(queueName), null, false, true); queryResult = true; } - else - { + else { queryResult = false; } } @@ -174,124 +157,104 @@ public class ProtonSessionIntegrationCallback implements AMQPSessionCallback, Se } @Override - public void closeSender(final Object brokerConsumer) throws Exception - { - Runnable runnable = new Runnable() - { + public void closeSender(final Object brokerConsumer) throws Exception { + Runnable runnable = new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { ((ServerConsumer) brokerConsumer).close(false); } - catch (Exception e) - { + catch (Exception e) { } } }; - // Due to the nature of proton this could be happening within flushes from the queue-delivery (depending on how it happened on the protocol) // to avoid deadlocks the close has to be done outside of the main thread on an executor // otherwise you could get a deadlock Executor executor = protonSPI.getExeuctor(); - if (executor != null) - { + if (executor != null) { executor.execute(runnable); } - else - { + else { runnable.run(); } } @Override - public ProtonJMessage encodeMessage(Object message, int deliveryCount) throws Exception - { + public ProtonJMessage encodeMessage(Object message, int deliveryCount) throws Exception { return (ProtonJMessage) manager.getConverter().outbound((ServerMessage) message, deliveryCount); } @Override - public Binary getCurrentTXID() - { + public Binary getCurrentTXID() { return new Binary(ByteUtil.longToBytes(serverSession.getCurrentTransaction().getID())); } @Override - public String tempQueueName() - { + public String tempQueueName() { return UUIDGenerator.getInstance().generateStringUUID(); } @Override - public void commitCurrentTX() throws Exception - { + public void commitCurrentTX() throws Exception { serverSession.commit(); } @Override - public void rollbackCurrentTX() throws Exception - { + public void rollbackCurrentTX() throws Exception { serverSession.rollback(false); } @Override - public void close() throws Exception - { + public void close() throws Exception { serverSession.close(false); } @Override - public void ack(Object brokerConsumer, Object message) throws Exception - { - ((ServerConsumer)brokerConsumer).individualAcknowledge(null, ((ServerMessage)message).getMessageID()); + public void ack(Object brokerConsumer, Object message) throws Exception { + ((ServerConsumer) brokerConsumer).individualAcknowledge(null, ((ServerMessage) message).getMessageID()); } @Override - public void cancel(Object brokerConsumer, Object message, boolean updateCounts) throws Exception - { - ((ServerConsumer)brokerConsumer).individualCancel(((ServerMessage)message).getMessageID(), updateCounts); + public void cancel(Object brokerConsumer, Object message, boolean updateCounts) throws Exception { + ((ServerConsumer) brokerConsumer).individualCancel(((ServerMessage) message).getMessageID(), updateCounts); } @Override - public void resumeDelivery(Object consumer) - { + public void resumeDelivery(Object consumer) { ((ServerConsumer) consumer).receiveCredits(-1); } @Override - public void serverSend(final Receiver receiver, final Delivery delivery, String address, int messageFormat, ByteBuf messageEncoded) throws Exception - { + public void serverSend(final Receiver receiver, + final Delivery delivery, + String address, + int messageFormat, + ByteBuf messageEncoded) throws Exception { EncodedMessage encodedMessage = new EncodedMessage(messageFormat, messageEncoded.array(), messageEncoded.arrayOffset(), messageEncoded.writerIndex()); ServerMessage message = manager.getConverter().inbound(encodedMessage); //use the address on the receiver if not null, if null let's hope it was set correctly on the message - if (address != null) - { + if (address != null) { message.setAddress(new SimpleString(address)); } serverSession.send(message, false); - manager.getServer().getStorageManager().afterCompleteOperations(new IOCallback() - { + manager.getServer().getStorageManager().afterCompleteOperations(new IOCallback() { @Override - public void done() - { - synchronized (connection.getLock()) - { + public void done() { + synchronized (connection.getLock()) { delivery.settle(); connection.flush(); } } @Override - public void onError(int errorCode, String errorMessage) - { - synchronized (connection.getLock()) - { + public void onError(int errorCode, String errorMessage) { + synchronized (connection.getLock()) { receiver.setCondition(new ErrorCondition(AmqpError.ILLEGAL_STATE, errorCode + ":" + errorMessage)); connection.flush(); } @@ -299,31 +262,24 @@ public class ProtonSessionIntegrationCallback implements AMQPSessionCallback, Se }); } - @Override - public void sendProducerCreditsMessage(int credits, SimpleString address) - { + public void sendProducerCreditsMessage(int credits, SimpleString address) { } @Override - public void sendProducerCreditsFailMessage(int credits, SimpleString address) - { + public void sendProducerCreditsFailMessage(int credits, SimpleString address) { } @Override - public int sendMessage(ServerMessage message, ServerConsumer consumer, int deliveryCount) - { + public int sendMessage(ServerMessage message, ServerConsumer consumer, int deliveryCount) { ProtonPlugSender plugSender = (ProtonPlugSender) consumer.getProtocolContext(); - try - { + try { return plugSender.deliverMessage(message, deliveryCount); } - catch (Exception e) - { - synchronized (connection.getLock()) - { + catch (Exception e) { + synchronized (connection.getLock()) { plugSender.getSender().setCondition(new ErrorCondition(AmqpError.INTERNAL_ERROR, e.getMessage())); connection.flush(); } @@ -333,59 +289,50 @@ public class ProtonSessionIntegrationCallback implements AMQPSessionCallback, Se } @Override - public int sendLargeMessage(ServerMessage message, ServerConsumer consumer, long bodySize, int deliveryCount) - { + public int sendLargeMessage(ServerMessage message, ServerConsumer consumer, long bodySize, int deliveryCount) { return 0; } @Override - public int sendLargeMessageContinuation(ServerConsumer consumer, byte[] body, boolean continues, boolean requiresResponse) - { + public int sendLargeMessageContinuation(ServerConsumer consumer, + byte[] body, + boolean continues, + boolean requiresResponse) { return 0; } @Override - public void closed() - { + public void closed() { } @Override - public void addReadyListener(ReadyListener listener) - { + public void addReadyListener(ReadyListener listener) { } @Override - public void removeReadyListener(ReadyListener listener) - { + public void removeReadyListener(ReadyListener listener) { } @Override - public void disconnect(ServerConsumer consumer, String queueName) - { - synchronized (connection.getLock()) - { + public void disconnect(ServerConsumer consumer, String queueName) { + synchronized (connection.getLock()) { ((Link) consumer.getProtocolContext()).close(); connection.flush(); } } - @Override - public boolean hasCredits(ServerConsumer consumer) - { + public boolean hasCredits(ServerConsumer consumer) { ProtonPlugSender plugSender = (ProtonPlugSender) consumer.getProtocolContext(); - if (plugSender != null && plugSender.getSender().getCredit() > 0) - { + if (plugSender != null && plugSender.getSender().getCredit() > 0) { return true; } - else - { + else { return false; } } - } diff --git a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/sasl/ActiveMQPlainSASL.java b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/sasl/ActiveMQPlainSASL.java index 167925e368..c60e9cd110 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/sasl/ActiveMQPlainSASL.java +++ b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/proton/sasl/ActiveMQPlainSASL.java @@ -20,29 +20,23 @@ import org.apache.activemq.artemis.core.security.SecurityStore; import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManager; import org.proton.plug.sasl.ServerSASLPlain; -public class ActiveMQPlainSASL extends ServerSASLPlain -{ +public class ActiveMQPlainSASL extends ServerSASLPlain { private final ActiveMQSecurityManager securityManager; private final SecurityStore securityStore; - - public ActiveMQPlainSASL(SecurityStore securityStore, ActiveMQSecurityManager securityManager) - { + public ActiveMQPlainSASL(SecurityStore securityStore, ActiveMQSecurityManager securityManager) { this.securityManager = securityManager; this.securityStore = securityStore; } @Override - protected boolean authenticate(String user, String password) - { - if (securityStore.isSecurityEnabled()) - { + protected boolean authenticate(String user, String password) { + if (securityStore.isSecurityEnabled()) { return securityManager.validateUser(user, password); } - else - { + else { return true; } } diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/proton/TestConversions.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/proton/TestConversions.java index 07a219a359..0b5cb51f97 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/proton/TestConversions.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/proton/TestConversions.java @@ -48,12 +48,10 @@ import org.junit.Assert; import org.junit.Test; import org.proton.plug.util.NettyWritable; -public class TestConversions extends Assert -{ +public class TestConversions extends Assert { @Test - public void testSimpleConversionBytes() throws Exception - { + public void testSimpleConversionBytes() throws Exception { Map mapprop = createPropertiesMap(); ApplicationProperties properties = new ApplicationProperties(mapprop); MessageImpl message = (MessageImpl) Message.Factory.create(); @@ -61,48 +59,40 @@ public class TestConversions extends Assert byte[] bodyBytes = new byte[4]; - for (int i = 0; i < bodyBytes.length; i++) - { + for (int i = 0; i < bodyBytes.length; i++) { bodyBytes[i] = (byte) 0xff; } message.setBody(new Data(new Binary(bodyBytes))); - EncodedMessage encodedMessage = encodeMessage(message); - ProtonMessageConverter converter = new ProtonMessageConverter(new SimpleIDGenerator(0)); - ServerJMSBytesMessage serverMessage = (ServerJMSBytesMessage)converter.inboundJMSType(encodedMessage); + ServerJMSBytesMessage serverMessage = (ServerJMSBytesMessage) converter.inboundJMSType(encodedMessage); verifyProperties(serverMessage); - assertEquals(bodyBytes.length, serverMessage.getBodyLength()); byte[] newBodyBytes = new byte[4]; serverMessage.readBytes(newBodyBytes); - Assert.assertArrayEquals(bodyBytes, newBodyBytes); - - Object obj = converter.outbound((ServerMessage)serverMessage.getInnerMessage(), 0); + Object obj = converter.outbound((ServerMessage) serverMessage.getInnerMessage(), 0); System.out.println("output = " + obj); } - private void verifyProperties(javax.jms.Message message) throws Exception - { + private void verifyProperties(javax.jms.Message message) throws Exception { assertEquals(true, message.getBooleanProperty("true")); assertEquals(false, message.getBooleanProperty("false")); assertEquals("bar", message.getStringProperty("foo")); } - private Map createPropertiesMap() - { + private Map createPropertiesMap() { Map mapprop = new HashMap<>(); mapprop.put("true", Boolean.TRUE); @@ -112,8 +102,7 @@ public class TestConversions extends Assert } @Test - public void testSimpleConversionMap() throws Exception - { + public void testSimpleConversionMap() throws Exception { Map mapprop = createPropertiesMap(); ApplicationProperties properties = new ApplicationProperties(mapprop); MessageImpl message = (MessageImpl) Message.Factory.create(); @@ -128,33 +117,29 @@ public class TestConversions extends Assert EncodedMessage encodedMessage = encodeMessage(message); ProtonMessageConverter converter = new ProtonMessageConverter(new SimpleIDGenerator(0)); - ServerJMSMapMessage serverMessage = (ServerJMSMapMessage)converter.inboundJMSType(encodedMessage); + ServerJMSMapMessage serverMessage = (ServerJMSMapMessage) converter.inboundJMSType(encodedMessage); verifyProperties(serverMessage); Assert.assertEquals(1, serverMessage.getInt("someint")); Assert.assertEquals("value", serverMessage.getString("somestr")); - Object obj = converter.outbound((ServerMessage)serverMessage.getInnerMessage(), 0); + Object obj = converter.outbound((ServerMessage) serverMessage.getInnerMessage(), 0); reEncodeMsg(obj); - MessageImpl outMessage = (MessageImpl) obj; - AmqpValue value = (AmqpValue)outMessage.getBody(); - Map mapoutput = (Map)value.getValue(); + AmqpValue value = (AmqpValue) outMessage.getBody(); + Map mapoutput = (Map) value.getValue(); assertEquals(Integer.valueOf(1), (Integer) mapoutput.get("someint")); - System.out.println("output = " + obj); } - @Test - public void testSimpleConversionStream() throws Exception - { + public void testSimpleConversionStream() throws Exception { Map mapprop = createPropertiesMap(); ApplicationProperties properties = new ApplicationProperties(mapprop); MessageImpl message = (MessageImpl) Message.Factory.create(); @@ -169,7 +154,7 @@ public class TestConversions extends Assert EncodedMessage encodedMessage = encodeMessage(message); ProtonMessageConverter converter = new ProtonMessageConverter(new SimpleIDGenerator(0)); - ServerJMSStreamMessage serverMessage = (ServerJMSStreamMessage)converter.inboundJMSType(encodedMessage); + ServerJMSStreamMessage serverMessage = (ServerJMSStreamMessage) converter.inboundJMSType(encodedMessage); simulatePersistence(serverMessage); @@ -180,20 +165,19 @@ public class TestConversions extends Assert assertEquals(10, serverMessage.readInt()); assertEquals("10", serverMessage.readString()); - Object obj = converter.outbound((ServerMessage)serverMessage.getInnerMessage(), 0); + Object obj = converter.outbound((ServerMessage) serverMessage.getInnerMessage(), 0); reEncodeMsg(obj); - MessageImpl outMessage = (MessageImpl)obj; - List list = ((AmqpSequence)outMessage.getBody()).getValue(); + MessageImpl outMessage = (MessageImpl) obj; + List list = ((AmqpSequence) outMessage.getBody()).getValue(); Assert.assertEquals(Integer.valueOf(10), list.get(0)); Assert.assertEquals("10", list.get(1)); } @Test - public void testSimpleConversionText() throws Exception - { + public void testSimpleConversionText() throws Exception { Map mapprop = createPropertiesMap(); ApplicationProperties properties = new ApplicationProperties(mapprop); MessageImpl message = (MessageImpl) Message.Factory.create(); @@ -205,24 +189,21 @@ public class TestConversions extends Assert EncodedMessage encodedMessage = encodeMessage(message); ProtonMessageConverter converter = new ProtonMessageConverter(new SimpleIDGenerator(0)); - ServerJMSTextMessage serverMessage = (ServerJMSTextMessage)converter.inboundJMSType(encodedMessage); + ServerJMSTextMessage serverMessage = (ServerJMSTextMessage) converter.inboundJMSType(encodedMessage); simulatePersistence(serverMessage); - verifyProperties(serverMessage); Assert.assertEquals(text, serverMessage.getText()); - - Object obj = converter.outbound((ServerMessage)serverMessage.getInnerMessage(), 0); - + Object obj = converter.outbound((ServerMessage) serverMessage.getInnerMessage(), 0); reEncodeMsg(obj); MessageImpl outMessage = (MessageImpl) obj; - AmqpValue value = (AmqpValue)outMessage.getBody(); - String textValue = (String)value.getValue(); + AmqpValue value = (AmqpValue) outMessage.getBody(); + String textValue = (String) value.getValue(); Assert.assertEquals(text, textValue); @@ -230,17 +211,15 @@ public class TestConversions extends Assert } - private void simulatePersistence(ServerJMSMessage serverMessage) - { + private void simulatePersistence(ServerJMSMessage serverMessage) { serverMessage.getInnerMessage().setAddress(new SimpleString("jms.queue.SomeAddress")); // This is just to simulate what would happen during the persistence of the message // We need to still be able to recover the message when we read it back - ((EncodingSupport)serverMessage.getInnerMessage()).encode(new EmptyBuffer()); + ((EncodingSupport) serverMessage.getInnerMessage()).encode(new EmptyBuffer()); } - private ProtonJMessage reEncodeMsg(Object obj) - { - ProtonJMessage objOut = (ProtonJMessage)obj; + private ProtonJMessage reEncodeMsg(Object obj) { + ProtonJMessage objOut = (ProtonJMessage) obj; ByteBuf nettyBuffer = PooledByteBufAllocator.DEFAULT.heapBuffer(1024); @@ -248,9 +227,7 @@ public class TestConversions extends Assert return objOut; } - - private EncodedMessage encodeMessage(MessageImpl message) - { + private EncodedMessage encodeMessage(MessageImpl message) { ByteBuf buf = PooledByteBufAllocator.DEFAULT.heapBuffer(1024 * 1024); message.encode(new NettyWritable(buf)); byte[] bytesConvert = new byte[buf.writerIndex()]; @@ -258,582 +235,485 @@ public class TestConversions extends Assert return new EncodedMessage(0, bytesConvert, 0, bytesConvert.length); } + class EmptyBuffer implements ActiveMQBuffer { - class EmptyBuffer implements ActiveMQBuffer - { @Override - public ByteBuf byteBuf() - { + public ByteBuf byteBuf() { return null; } @Override - public int capacity() - { + public int capacity() { return 0; } @Override - public int readerIndex() - { + public int readerIndex() { return 0; } @Override - public void readerIndex(int readerIndex) - { + public void readerIndex(int readerIndex) { } @Override - public int writerIndex() - { + public int writerIndex() { return 0; } @Override - public void writerIndex(int writerIndex) - { + public void writerIndex(int writerIndex) { } @Override - public void setIndex(int readerIndex, int writerIndex) - { + public void setIndex(int readerIndex, int writerIndex) { } @Override - public int readableBytes() - { + public int readableBytes() { return 0; } @Override - public int writableBytes() - { + public int writableBytes() { return 0; } @Override - public boolean readable() - { + public boolean readable() { return false; } @Override - public boolean writable() - { + public boolean writable() { return false; } @Override - public void clear() - { + public void clear() { } @Override - public void markReaderIndex() - { + public void markReaderIndex() { } @Override - public void resetReaderIndex() - { + public void resetReaderIndex() { } @Override - public void markWriterIndex() - { + public void markWriterIndex() { } @Override - public void resetWriterIndex() - { + public void resetWriterIndex() { } @Override - public void discardReadBytes() - { + public void discardReadBytes() { } @Override - public byte getByte(int index) - { + public byte getByte(int index) { return 0; } @Override - public short getUnsignedByte(int index) - { + public short getUnsignedByte(int index) { return 0; } @Override - public short getShort(int index) - { + public short getShort(int index) { return 0; } @Override - public int getUnsignedShort(int index) - { + public int getUnsignedShort(int index) { return 0; } @Override - public int getInt(int index) - { + public int getInt(int index) { return 0; } @Override - public long getUnsignedInt(int index) - { + public long getUnsignedInt(int index) { return 0; } @Override - public long getLong(int index) - { + public long getLong(int index) { return 0; } @Override - public void getBytes(int index, ActiveMQBuffer dst) - { + public void getBytes(int index, ActiveMQBuffer dst) { } @Override - public void getBytes(int index, ActiveMQBuffer dst, int length) - { + public void getBytes(int index, ActiveMQBuffer dst, int length) { } @Override - public void getBytes(int index, ActiveMQBuffer dst, int dstIndex, int length) - { + public void getBytes(int index, ActiveMQBuffer dst, int dstIndex, int length) { } @Override - public void getBytes(int index, byte[] dst) - { + public void getBytes(int index, byte[] dst) { } @Override - public void getBytes(int index, byte[] dst, int dstIndex, int length) - { + public void getBytes(int index, byte[] dst, int dstIndex, int length) { } @Override - public void getBytes(int index, ByteBuffer dst) - { + public void getBytes(int index, ByteBuffer dst) { } @Override - public char getChar(int index) - { + public char getChar(int index) { return 0; } @Override - public float getFloat(int index) - { + public float getFloat(int index) { return 0; } @Override - public double getDouble(int index) - { + public double getDouble(int index) { return 0; } @Override - public void setByte(int index, byte value) - { + public void setByte(int index, byte value) { } @Override - public void setShort(int index, short value) - { + public void setShort(int index, short value) { } @Override - public void setInt(int index, int value) - { + public void setInt(int index, int value) { } @Override - public void setLong(int index, long value) - { + public void setLong(int index, long value) { } @Override - public void setBytes(int index, ActiveMQBuffer src) - { + public void setBytes(int index, ActiveMQBuffer src) { } @Override - public void setBytes(int index, ActiveMQBuffer src, int length) - { + public void setBytes(int index, ActiveMQBuffer src, int length) { } @Override - public void setBytes(int index, ActiveMQBuffer src, int srcIndex, int length) - { + public void setBytes(int index, ActiveMQBuffer src, int srcIndex, int length) { } @Override - public void setBytes(int index, byte[] src) - { + public void setBytes(int index, byte[] src) { } @Override - public void setBytes(int index, byte[] src, int srcIndex, int length) - { + public void setBytes(int index, byte[] src, int srcIndex, int length) { } @Override - public void setBytes(int index, ByteBuffer src) - { + public void setBytes(int index, ByteBuffer src) { } @Override - public void setChar(int index, char value) - { + public void setChar(int index, char value) { } @Override - public void setFloat(int index, float value) - { + public void setFloat(int index, float value) { } @Override - public void setDouble(int index, double value) - { + public void setDouble(int index, double value) { } @Override - public byte readByte() - { + public byte readByte() { return 0; } @Override - public short readUnsignedByte() - { + public short readUnsignedByte() { return 0; } @Override - public short readShort() - { + public short readShort() { return 0; } @Override - public int readUnsignedShort() - { + public int readUnsignedShort() { return 0; } @Override - public int readInt() - { + public int readInt() { return 0; } @Override - public long readUnsignedInt() - { + public long readUnsignedInt() { return 0; } @Override - public long readLong() - { + public long readLong() { return 0; } @Override - public char readChar() - { + public char readChar() { return 0; } @Override - public float readFloat() - { + public float readFloat() { return 0; } @Override - public double readDouble() - { + public double readDouble() { return 0; } @Override - public boolean readBoolean() - { + public boolean readBoolean() { return false; } @Override - public SimpleString readNullableSimpleString() - { + public SimpleString readNullableSimpleString() { return null; } @Override - public String readNullableString() - { + public String readNullableString() { return null; } @Override - public SimpleString readSimpleString() - { + public SimpleString readSimpleString() { return null; } @Override - public String readString() - { + public String readString() { return null; } @Override - public String readUTF() - { + public String readUTF() { return null; } @Override - public ActiveMQBuffer readBytes(int length) - { + public ActiveMQBuffer readBytes(int length) { return null; } @Override - public ActiveMQBuffer readSlice(int length) - { + public ActiveMQBuffer readSlice(int length) { return null; } @Override - public void readBytes(ActiveMQBuffer dst) - { + public void readBytes(ActiveMQBuffer dst) { } @Override - public void readBytes(ActiveMQBuffer dst, int length) - { + public void readBytes(ActiveMQBuffer dst, int length) { } @Override - public void readBytes(ActiveMQBuffer dst, int dstIndex, int length) - { + public void readBytes(ActiveMQBuffer dst, int dstIndex, int length) { } @Override - public void readBytes(byte[] dst) - { + public void readBytes(byte[] dst) { } @Override - public void readBytes(byte[] dst, int dstIndex, int length) - { + public void readBytes(byte[] dst, int dstIndex, int length) { } @Override - public void readBytes(ByteBuffer dst) - { + public void readBytes(ByteBuffer dst) { } @Override - public void skipBytes(int length) - { + public void skipBytes(int length) { } @Override - public void writeByte(byte value) - { + public void writeByte(byte value) { } @Override - public void writeShort(short value) - { + public void writeShort(short value) { } @Override - public void writeInt(int value) - { + public void writeInt(int value) { } @Override - public void writeLong(long value) - { + public void writeLong(long value) { } @Override - public void writeChar(char chr) - { + public void writeChar(char chr) { } @Override - public void writeFloat(float value) - { + public void writeFloat(float value) { } @Override - public void writeDouble(double value) - { + public void writeDouble(double value) { } @Override - public void writeBoolean(boolean val) - { + public void writeBoolean(boolean val) { } @Override - public void writeNullableSimpleString(SimpleString val) - { + public void writeNullableSimpleString(SimpleString val) { } @Override - public void writeNullableString(String val) - { + public void writeNullableString(String val) { } @Override - public void writeSimpleString(SimpleString val) - { + public void writeSimpleString(SimpleString val) { } @Override - public void writeString(String val) - { + public void writeString(String val) { } @Override - public void writeUTF(String utf) - { + public void writeUTF(String utf) { } @Override - public void writeBytes(ActiveMQBuffer src, int length) - { + public void writeBytes(ActiveMQBuffer src, int length) { } @Override - public void writeBytes(ActiveMQBuffer src, int srcIndex, int length) - { + public void writeBytes(ActiveMQBuffer src, int srcIndex, int length) { } @Override - public void writeBytes(byte[] src) - { + public void writeBytes(byte[] src) { } @Override - public void writeBytes(byte[] src, int srcIndex, int length) - { + public void writeBytes(byte[] src, int srcIndex, int length) { } @Override - public void writeBytes(ByteBuffer src) - { + public void writeBytes(ByteBuffer src) { } @Override - public ActiveMQBuffer copy() - { + public ActiveMQBuffer copy() { return null; } @Override - public ActiveMQBuffer copy(int index, int length) - { + public ActiveMQBuffer copy(int index, int length) { return null; } @Override - public ActiveMQBuffer slice() - { + public ActiveMQBuffer slice() { return null; } @Override - public ActiveMQBuffer slice(int index, int length) - { + public ActiveMQBuffer slice(int index, int length) { return null; } @Override - public ActiveMQBuffer duplicate() - { + public ActiveMQBuffer duplicate() { return null; } @Override - public ByteBuffer toByteBuffer() - { + public ByteBuffer toByteBuffer() { return null; } @Override - public ByteBuffer toByteBuffer(int index, int length) - { + public ByteBuffer toByteBuffer(int index, int length) { return null; } } diff --git a/artemis-protocols/artemis-hornetq-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/hornetq/HQPropertiesConversionInterceptor.java b/artemis-protocols/artemis-hornetq-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/hornetq/HQPropertiesConversionInterceptor.java index b2c9d5ce4e..cb47e85f41 100644 --- a/artemis-protocols/artemis-hornetq-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/hornetq/HQPropertiesConversionInterceptor.java +++ b/artemis-protocols/artemis-hornetq-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/hornetq/HQPropertiesConversionInterceptor.java @@ -31,12 +31,11 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map; -public class HQPropertiesConversionInterceptor implements Interceptor -{ +public class HQPropertiesConversionInterceptor implements Interceptor { + private static Map dictionary; - static - { + static { Map d = new HashMap(); // Add entries for outgoing messages @@ -67,35 +66,29 @@ public class HQPropertiesConversionInterceptor implements Interceptor } @Override - public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException - { - if (isMessagePacket(packet)) - { + public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException { + if (isMessagePacket(packet)) { handleReceiveMessage((MessagePacket) packet); } return true; } - private void handleReceiveMessage(MessagePacket messagePacket) - { + private void handleReceiveMessage(MessagePacket messagePacket) { Message message = messagePacket.getMessage(); // We are modifying the key set so we iterate over a shallow copy. - for (SimpleString property : new HashSet<>(message.getPropertyNames())) - { - if (dictionary.containsKey(property)) - { + for (SimpleString property : new HashSet<>(message.getPropertyNames())) { + if (dictionary.containsKey(property)) { message.putObjectProperty(dictionary.get(property), message.removeProperty(property)); } } } - private boolean isMessagePacket(Packet packet) - { + private boolean isMessagePacket(Packet packet) { int type = packet.getType(); return type == PacketImpl.SESS_SEND || - type == PacketImpl.SESS_SEND_CONTINUATION || - type == PacketImpl.SESS_SEND_LARGE || - type == PacketImpl.SESS_RECEIVE_LARGE_MSG || - type == PacketImpl.SESS_RECEIVE_MSG; + type == PacketImpl.SESS_SEND_CONTINUATION || + type == PacketImpl.SESS_SEND_LARGE || + type == PacketImpl.SESS_RECEIVE_LARGE_MSG || + type == PacketImpl.SESS_RECEIVE_MSG; } } diff --git a/artemis-protocols/artemis-hornetq-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/hornetq/HornetQProtocolManager.java b/artemis-protocols/artemis-hornetq-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/hornetq/HornetQProtocolManager.java index c40bbd99d5..3d6dab5932 100644 --- a/artemis-protocols/artemis-hornetq-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/hornetq/HornetQProtocolManager.java +++ b/artemis-protocols/artemis-hornetq-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/hornetq/HornetQProtocolManager.java @@ -29,16 +29,17 @@ import java.util.List; /** * HornetQ Protocol Manager */ -class HornetQProtocolManager extends CoreProtocolManager -{ - HornetQProtocolManager(CoreProtocolManagerFactory factory, ActiveMQServer server, List incomingInterceptors, List outgoingInterceptors) - { +class HornetQProtocolManager extends CoreProtocolManager { + + HornetQProtocolManager(CoreProtocolManagerFactory factory, + ActiveMQServer server, + List incomingInterceptors, + List outgoingInterceptors) { super(factory, server, incomingInterceptors, outgoingInterceptors); } @Override - public void handshake(NettyServerConnection connection, ActiveMQBuffer buffer) - { + public void handshake(NettyServerConnection connection, ActiveMQBuffer buffer) { //if we are not an old client then handshake if (buffer.getByte(0) == 'H' && buffer.getByte(1) == 'O' && @@ -46,16 +47,14 @@ class HornetQProtocolManager extends CoreProtocolManager buffer.getByte(3) == 'N' && buffer.getByte(4) == 'E' && buffer.getByte(5) == 'T' && - buffer.getByte(6) == 'Q') - { + buffer.getByte(6) == 'Q') { //todo add some handshaking buffer.readBytes(7); } } @Override - public boolean isProtocol(byte[] array) - { + public boolean isProtocol(byte[] array) { String frameStart = new String(array, StandardCharsets.US_ASCII); return frameStart.startsWith("HORNETQ"); } diff --git a/artemis-protocols/artemis-hornetq-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/hornetq/HornetQProtocolManagerFactory.java b/artemis-protocols/artemis-hornetq-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/hornetq/HornetQProtocolManagerFactory.java index 1574c0715b..a163459b67 100644 --- a/artemis-protocols/artemis-hornetq-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/hornetq/HornetQProtocolManagerFactory.java +++ b/artemis-protocols/artemis-hornetq-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/hornetq/HornetQProtocolManagerFactory.java @@ -18,22 +18,22 @@ package org.apache.activemq.artemis.core.protocol.hornetq; import java.util.List; - import org.apache.activemq.artemis.api.core.Interceptor; import org.apache.activemq.artemis.core.protocol.core.impl.CoreProtocolManagerFactory; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.spi.core.protocol.ProtocolManager; -public class HornetQProtocolManagerFactory extends CoreProtocolManagerFactory -{ +public class HornetQProtocolManagerFactory extends CoreProtocolManagerFactory { + public static final String HORNETQ_PROTOCOL_NAME = "HORNETQ"; private static final String MODULE_NAME = "artemis-hornetq-protocol"; private static String[] SUPPORTED_PROTOCOLS = {HORNETQ_PROTOCOL_NAME}; - public ProtocolManager createProtocolManager(final ActiveMQServer server, final List incomingInterceptors, List outgoingInterceptors) - { + public ProtocolManager createProtocolManager(final ActiveMQServer server, + final List incomingInterceptors, + List outgoingInterceptors) { Interceptor propertyConversionInterceptor = new HQPropertiesConversionInterceptor(); incomingInterceptors.add(propertyConversionInterceptor); outgoingInterceptors.add(propertyConversionInterceptor); @@ -41,14 +41,12 @@ public class HornetQProtocolManagerFactory extends CoreProtocolManagerFactory } @Override - public String[] getProtocols() - { + public String[] getProtocols() { return SUPPORTED_PROTOCOLS; } @Override - public String getModuleName() - { + public String getModuleName() { return MODULE_NAME; } } diff --git a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTConnection.java b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTConnection.java index 08dd1575bc..7bb12c6e65 100644 --- a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTConnection.java +++ b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTConnection.java @@ -29,8 +29,8 @@ import org.apache.activemq.artemis.core.remoting.FailureListener; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; import org.apache.activemq.artemis.spi.core.remoting.Connection; -public class MQTTConnection implements RemotingConnection -{ +public class MQTTConnection implements RemotingConnection { + private final Connection transportConnection; private final long creationTime; @@ -45,60 +45,50 @@ public class MQTTConnection implements RemotingConnection private final List closeListeners = Collections.synchronizedList(new ArrayList()); - public MQTTConnection(Connection transportConnection) throws Exception - { + public MQTTConnection(Connection transportConnection) throws Exception { this.transportConnection = transportConnection; this.creationTime = System.currentTimeMillis(); this.dataReceived = new AtomicBoolean(); this.destroyed = false; } - public Object getID() - { + public Object getID() { return transportConnection.getID(); } @Override - public long getCreationTime() - { + public long getCreationTime() { return creationTime; } @Override - public String getRemoteAddress() - { + public String getRemoteAddress() { return transportConnection.getRemoteAddress(); } @Override - public void addFailureListener(FailureListener listener) - { + public void addFailureListener(FailureListener listener) { failureListeners.add(listener); } @Override - public boolean removeFailureListener(FailureListener listener) - { + public boolean removeFailureListener(FailureListener listener) { return failureListeners.remove(listener); } @Override - public void addCloseListener(CloseListener listener) - { + public void addCloseListener(CloseListener listener) { closeListeners.add(listener); } @Override - public boolean removeCloseListener(CloseListener listener) - { + public boolean removeCloseListener(CloseListener listener) { return closeListeners.remove(listener); } @Override - public List removeCloseListeners() - { - synchronized (closeListeners) - { + public List removeCloseListeners() { + synchronized (closeListeners) { List deletedCloseListeners = new ArrayList(closeListeners); closeListeners.clear(); return deletedCloseListeners; @@ -106,22 +96,18 @@ public class MQTTConnection implements RemotingConnection } @Override - public void setCloseListeners(List listeners) - { + public void setCloseListeners(List listeners) { closeListeners.addAll(listeners); } @Override - public List getFailureListeners() - { + public List getFailureListeners() { return failureListeners; } @Override - public List removeFailureListeners() - { - synchronized (failureListeners) - { + public List removeFailureListeners() { + synchronized (failureListeners) { List deletedFailureListeners = new ArrayList(failureListeners); failureListeners.clear(); return deletedFailureListeners; @@ -129,40 +115,31 @@ public class MQTTConnection implements RemotingConnection } @Override - public void setFailureListeners(List listeners) - { - synchronized (failureListeners) - { + public void setFailureListeners(List listeners) { + synchronized (failureListeners) { failureListeners.clear(); failureListeners.addAll(listeners); } } @Override - public ActiveMQBuffer createTransportBuffer(int size) - { + public ActiveMQBuffer createTransportBuffer(int size) { return transportConnection.createTransportBuffer(size); } @Override - public void fail(ActiveMQException me) - { - synchronized (failureListeners) - { - for (FailureListener listener : failureListeners) - { + public void fail(ActiveMQException me) { + synchronized (failureListeners) { + for (FailureListener listener : failureListeners) { listener.connectionFailed(me, false); } } } @Override - public void fail(ActiveMQException me, String scaleDownTargetNodeID) - { - synchronized (failureListeners) - { - for (FailureListener listener : failureListeners) - { + public void fail(ActiveMQException me, String scaleDownTargetNodeID) { + synchronized (failureListeners) { + for (FailureListener listener : failureListeners) { //FIXME(mtaylor) How do we check if the node has failed over? listener.connectionFailed(me, false); } @@ -170,72 +147,60 @@ public class MQTTConnection implements RemotingConnection } @Override - public void destroy() - { + public void destroy() { //TODO(mtaylor) ensure this properly destroys this connection. destroyed = true; disconnect(false); } @Override - public Connection getTransportConnection() - { + public Connection getTransportConnection() { return transportConnection; } @Override - public boolean isClient() - { + public boolean isClient() { return false; } @Override - public boolean isDestroyed() - { + public boolean isDestroyed() { return destroyed; } @Override - public void disconnect(boolean criticalError) - { + public void disconnect(boolean criticalError) { transportConnection.forceClose(); } @Override - public void disconnect(String scaleDownNodeID, boolean criticalError) - { + public void disconnect(String scaleDownNodeID, boolean criticalError) { transportConnection.forceClose(); } - protected void dataReceived() - { + protected void dataReceived() { dataReceived.set(true); } @Override - public boolean checkDataReceived() - { + public boolean checkDataReceived() { return dataReceived.compareAndSet(true, false); } @Override - public void flush() - { + public void flush() { transportConnection.checkFlushBatchBuffer(); } @Override - public void bufferReceived(Object connectionID, ActiveMQBuffer buffer) - { + public void bufferReceived(Object connectionID, ActiveMQBuffer buffer) { } - public void setConnected(boolean connected) - { + public void setConnected(boolean connected) { this.connected = connected; } - public boolean getConnected() - { + public boolean getConnected() { return connected; } } diff --git a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTConnectionManager.java b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTConnectionManager.java index e4433d2418..fb10717909 100644 --- a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTConnectionManager.java +++ b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTConnectionManager.java @@ -33,8 +33,8 @@ import java.util.UUID; * MQTTConnectionMananager is responsible for handle Connect and Disconnect packets and any resulting behaviour of these * events. */ -public class MQTTConnectionManager -{ +public class MQTTConnectionManager { + private MQTTSession session; //TODO Read in a list of existing client IDs from stored Sessions. @@ -42,8 +42,7 @@ public class MQTTConnectionManager private MQTTLogger log = MQTTLogger.LOGGER; - public MQTTConnectionManager(MQTTSession session) - { + public MQTTConnectionManager(MQTTSession session) { this.session = session; MQTTFailureListener failureListener = new MQTTFailureListener(this); session.getConnection().addFailureListener(failureListener); @@ -52,12 +51,17 @@ public class MQTTConnectionManager /** * Handles the connect packet. See spec for details on each of parameters. */ - synchronized void connect(String cId, String username, String password, boolean will, String willMessage, String willTopic, - boolean willRetain, int willQosLevel, boolean cleanSession) throws Exception - { + synchronized void connect(String cId, + String username, + String password, + boolean will, + String willMessage, + String willTopic, + boolean willRetain, + int willQosLevel, + boolean cleanSession) throws Exception { String clientId = validateClientId(cId, cleanSession); - if (clientId == null) - { + if (clientId == null) { session.getProtocolHandler().sendConnack(MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED); session.getProtocolHandler().disconnect(); return; @@ -70,8 +74,7 @@ public class MQTTConnectionManager session.setServerSession(serverSession); - if (will) - { + if (will) { ServerMessage w = MQTTUtil.createServerMessageFromString(session, willMessage, willTopic, willQosLevel, willRetain); session.getSessionState().setWillMessage(w); } @@ -83,43 +86,29 @@ public class MQTTConnectionManager /** * Creates an internal Server Session. + * * @param username * @param password * @return * @throws Exception */ - ServerSessionImpl createServerSession(String username, String password) throws Exception - { + ServerSessionImpl createServerSession(String username, String password) throws Exception { String id = UUIDGenerator.getInstance().generateStringUUID(); - ActiveMQServer server = session.getServer(); + ActiveMQServer server = session.getServer(); - ServerSession serverSession = server.createSession(id, - username, - password, - ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - session.getConnection(), - MQTTUtil.SESSION_AUTO_COMMIT_SENDS, - MQTTUtil.SESSION_AUTO_COMMIT_ACKS, - MQTTUtil.SESSION_PREACKNOWLEDGE, - MQTTUtil.SESSION_XA, - null, - session.getSessionCallback(), - null, // Session factory - MQTTUtil.SESSION_AUTO_CREATE_QUEUE); + ServerSession serverSession = server.createSession(id, username, password, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, session.getConnection(), MQTTUtil.SESSION_AUTO_COMMIT_SENDS, MQTTUtil.SESSION_AUTO_COMMIT_ACKS, MQTTUtil.SESSION_PREACKNOWLEDGE, MQTTUtil.SESSION_XA, null, session.getSessionCallback(), null, // Session factory + MQTTUtil.SESSION_AUTO_CREATE_QUEUE); return (ServerSessionImpl) serverSession; } - void disconnect() - { - try - { - if (session != null && session.getSessionState() != null) - { + void disconnect() { + try { + if (session != null && session.getSessionState() != null) { String clientId = session.getSessionState().getClientId(); - if (clientId != null) CONNECTED_CLIENTS.remove(clientId); + if (clientId != null) + CONNECTED_CLIENTS.remove(clientId); - if (session.getState().isWill()) - { + if (session.getState().isWill()) { session.getConnectionManager().sendWill(); } } @@ -127,8 +116,7 @@ public class MQTTConnectionManager session.getConnection().disconnect(false); session.getConnection().destroy(); } - catch (Exception e) - { + catch (Exception e) { /* FIXME Failure during disconnect would leave the session state in an unrecoverable state. We should handle errors more gracefully. */ @@ -136,41 +124,32 @@ public class MQTTConnectionManager } } - - private void sendWill() throws Exception - { + private void sendWill() throws Exception { session.getServerSession().send(session.getSessionState().getWillMessage(), true); session.getSessionState().deleteWillMessage(); } - private MQTTSessionState getSessionState(String clientId, boolean cleanSession) throws InterruptedException - { - synchronized (MQTTSession.SESSIONS) - { + private MQTTSessionState getSessionState(String clientId, boolean cleanSession) throws InterruptedException { + synchronized (MQTTSession.SESSIONS) { /* [MQTT-3.1.2-6] If CleanSession is set to 1, the Client and Server MUST discard any previous Session and * start a new one This Session lasts as long as the Network Connection. State data associated with this Session * MUST NOT be reused in any subsequent Session */ - if (cleanSession) - { + if (cleanSession) { MQTTSession.SESSIONS.remove(clientId); return new MQTTSessionState(clientId); } - else - { + else { /* [MQTT-3.1.2-4] Attach an existing session if one exists (if cleanSession flag is false) otherwise create a new one. */ MQTTSessionState state = MQTTSession.SESSIONS.get(clientId); - if (state != null) - { + if (state != null) { // TODO Add a count down latch for handling wait during attached session state. - while (state.getAttached()) - { + while (state.getAttached()) { Thread.sleep(1000); } - return state; + return state; } - else - { + else { state = new MQTTSessionState(clientId); MQTTSession.SESSIONS.put(clientId, state); return state; @@ -179,24 +158,19 @@ public class MQTTConnectionManager } } - private String validateClientId(String clientId, boolean cleanSession) - { - if (clientId == null || clientId.isEmpty()) - { + private String validateClientId(String clientId, boolean cleanSession) { + if (clientId == null || clientId.isEmpty()) { // [MQTT-3.1.3-7] [MQTT-3.1.3-6] If client does not specify a client ID and clean session is set to 1 create it. - if (cleanSession) - { + if (cleanSession) { clientId = UUID.randomUUID().toString(); } - else - { + else { // [MQTT-3.1.3-8] Return ID rejected and disconnect if clean session = false and client id is null return null; } } // If the client ID is not unique (i.e. it has already registered) then do not accept it. - else if (!CONNECTED_CLIENTS.add(clientId)) - { + else if (!CONNECTED_CLIENTS.add(clientId)) { // [MQTT-3.1.3-9] Return ID Rejected if server rejects the client ID return null; } diff --git a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTFailureListener.java b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTFailureListener.java index b33bc5ef2b..ee03bba889 100644 --- a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTFailureListener.java +++ b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTFailureListener.java @@ -24,24 +24,21 @@ import org.apache.activemq.artemis.core.remoting.FailureListener; * Registered with the server and called during connection failure. This class informs the ConnectionManager when a * connection failure has occurred, which subsequently cleans up any connection data. */ -public class MQTTFailureListener implements FailureListener -{ +public class MQTTFailureListener implements FailureListener { + private MQTTConnectionManager connectionManager; - public MQTTFailureListener(MQTTConnectionManager connectionManager) - { + public MQTTFailureListener(MQTTConnectionManager connectionManager) { this.connectionManager = connectionManager; } @Override - public void connectionFailed(ActiveMQException exception, boolean failedOver) - { + public void connectionFailed(ActiveMQException exception, boolean failedOver) { connectionManager.disconnect(); } @Override - public void connectionFailed(ActiveMQException exception, boolean failedOver, String scaleDownTargetNodeID) - { + public void connectionFailed(ActiveMQException exception, boolean failedOver, String scaleDownTargetNodeID) { connectionManager.disconnect(); } } diff --git a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTLogger.java b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTLogger.java index ab3b221992..08f552a7cb 100644 --- a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTLogger.java +++ b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTLogger.java @@ -37,7 +37,7 @@ import org.jboss.logging.annotations.MessageLogger; */ @MessageLogger(projectCode = "AMQ") -public interface MQTTLogger extends BasicLogger -{ +public interface MQTTLogger extends BasicLogger { + MQTTLogger LOGGER = Logger.getMessageLogger(MQTTLogger.class, MQTTLogger.class.getPackage().getName()); } diff --git a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTMessageInfo.java b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTMessageInfo.java index e20119d47e..ca7110f58c 100644 --- a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTMessageInfo.java +++ b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTMessageInfo.java @@ -20,38 +20,33 @@ package org.apache.activemq.artemis.core.protocol.mqtt; /** * MQTT Acks only hold message ID information. From this we must infer the internal message ID and consumer. */ -class MQTTMessageInfo -{ +class MQTTMessageInfo { + private long serverMessageId; private long consumerId; private String address; - MQTTMessageInfo(long serverMessageId, long consumerId, String address) - { + MQTTMessageInfo(long serverMessageId, long consumerId, String address) { this.serverMessageId = serverMessageId; this.consumerId = consumerId; this.address = address; } - long getServerMessageId() - { + long getServerMessageId() { return serverMessageId; } - long getConsumerId() - { + long getConsumerId() { return consumerId; } - String getAddress() - { + String getAddress() { return address; } - public String toString() - { + public String toString() { return ("ServerMessageId: " + serverMessageId + " ConsumerId: " + consumerId + " addr: " + address); } } diff --git a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTProtocolHandler.java b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTProtocolHandler.java index 37610f89b5..6db86df613 100644 --- a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTProtocolHandler.java +++ b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTProtocolHandler.java @@ -44,8 +44,8 @@ import org.apache.activemq.artemis.spi.core.protocol.ConnectionEntry; * This class is responsible for receiving and sending MQTT packets, delegating behaviour to one of the * MQTTConnectionManager, MQTTPublishMananger, MQTTSubscriptionManager classes. */ -public class MQTTProtocolHandler extends ChannelInboundHandlerAdapter -{ +public class MQTTProtocolHandler extends ChannelInboundHandlerAdapter { + private ConnectionEntry connectionEntry; private MQTTConnection connection; @@ -57,34 +57,27 @@ public class MQTTProtocolHandler extends ChannelInboundHandlerAdapter // This Channel Handler is not sharable, therefore it can only ever be associated with a single ctx. private ChannelHandlerContext ctx; - private final MQTTLogger log = MQTTLogger.LOGGER;; + private final MQTTLogger log = MQTTLogger.LOGGER; private boolean stopped = false; - public MQTTProtocolHandler(ActiveMQServer server) - { + public MQTTProtocolHandler(ActiveMQServer server) { this.server = server; } - void setConnection(MQTTConnection connection, ConnectionEntry entry) throws Exception - { + void setConnection(MQTTConnection connection, ConnectionEntry entry) throws Exception { this.connectionEntry = entry; this.connection = connection; this.session = new MQTTSession(this, connection); } - - void stop(boolean error) - { + void stop(boolean error) { stopped = true; } - public void channelRead(ChannelHandlerContext ctx, Object msg) - { - try - { - if (stopped) - { + public void channelRead(ChannelHandlerContext ctx, Object msg) { + try { + if (stopped) { disconnect(); return; } @@ -92,8 +85,7 @@ public class MQTTProtocolHandler extends ChannelInboundHandlerAdapter MqttMessage message = (MqttMessage) msg; // Disconnect if Netty codec failed to decode the stream. - if (message.decoderResult().isFailure()) - { + if (message.decoderResult().isFailure()) { log.debug("Bad Message Disconnecting Client."); disconnect(); return; @@ -103,8 +95,7 @@ public class MQTTProtocolHandler extends ChannelInboundHandlerAdapter MQTTUtil.logMessage(log, message, true); - switch (message.fixedHeader().messageType()) - { + switch (message.fixedHeader().messageType()) { case CONNECT: handleConnect((MqttConnectMessage) message, ctx); break; @@ -151,8 +142,7 @@ public class MQTTProtocolHandler extends ChannelInboundHandlerAdapter disconnect(); } } - catch (Exception e) - { + catch (Exception e) { log.debug("Error processing Control Packet, Disconnecting Client" + e.getMessage()); disconnect(); } @@ -163,35 +153,20 @@ public class MQTTProtocolHandler extends ChannelInboundHandlerAdapter * * @param connect */ - void handleConnect(MqttConnectMessage connect, ChannelHandlerContext ctx) throws Exception - { + void handleConnect(MqttConnectMessage connect, ChannelHandlerContext ctx) throws Exception { this.ctx = ctx; connectionEntry.ttl = connect.variableHeader().keepAliveTimeSeconds() * 750; String clientId = connect.payload().clientIdentifier(); - session.getConnectionManager().connect(clientId, - connect.payload().userName(), - connect.payload().password(), - connect.variableHeader().isWillFlag(), - connect.payload().willMessage(), - connect.payload().willTopic(), - connect.variableHeader().isWillRetain(), - connect.variableHeader().willQos(), - connect.variableHeader().isCleanSession()); + session.getConnectionManager().connect(clientId, connect.payload().userName(), connect.payload().password(), connect.variableHeader().isWillFlag(), connect.payload().willMessage(), connect.payload().willTopic(), connect.variableHeader().isWillRetain(), connect.variableHeader().willQos(), connect.variableHeader().isCleanSession()); } - void disconnect() - { + void disconnect() { session.getConnectionManager().disconnect(); } - void sendConnack(MqttConnectReturnCode returnCode) - { - MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.CONNACK, - false, - MqttQoS.AT_MOST_ONCE, - false, - 0); + void sendConnack(MqttConnectReturnCode returnCode) { + MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.CONNACK, false, MqttQoS.AT_MOST_ONCE, false, 0); MqttConnAckVariableHeader varHeader = new MqttConnAckVariableHeader(returnCode); MqttConnAckMessage message = new MqttConnAckMessage(fixedHeader, varHeader); @@ -202,150 +177,107 @@ public class MQTTProtocolHandler extends ChannelInboundHandlerAdapter /** * The server does not instantiate connections therefore any CONNACK received over a connection is an invalid * control message. + * * @param message */ - void handleConnack(MqttConnAckMessage message) - { + void handleConnack(MqttConnAckMessage message) { log.debug("Received invalid CONNACK from client: " + session.getSessionState().getClientId()); log.debug("Disconnecting client: " + session.getSessionState().getClientId()); disconnect(); } - void handlePublish(MqttPublishMessage message) throws Exception - { - session.getMqttPublishManager().handleMessage(message.variableHeader().messageId(), - message.variableHeader().topicName(), - message.fixedHeader().qosLevel().value(), - message.payload(), - message.fixedHeader().isRetain()); + void handlePublish(MqttPublishMessage message) throws Exception { + session.getMqttPublishManager().handleMessage(message.variableHeader().messageId(), message.variableHeader().topicName(), message.fixedHeader().qosLevel().value(), message.payload(), message.fixedHeader().isRetain()); } - void sendPubAck(int messageId) - { + void sendPubAck(int messageId) { sendPublishProtocolControlMessage(messageId, MqttMessageType.PUBACK); } - void sendPubRel(int messageId) - { + void sendPubRel(int messageId) { sendPublishProtocolControlMessage(messageId, MqttMessageType.PUBREL); } - void sendPubRec(int messageId) - { + void sendPubRec(int messageId) { sendPublishProtocolControlMessage(messageId, MqttMessageType.PUBREC); } - void sendPubComp(int messageId) - { + void sendPubComp(int messageId) { sendPublishProtocolControlMessage(messageId, MqttMessageType.PUBCOMP); } - void sendPublishProtocolControlMessage(int messageId, MqttMessageType messageType) - { + void sendPublishProtocolControlMessage(int messageId, MqttMessageType messageType) { MqttQoS qos = (messageType == MqttMessageType.PUBREL) ? MqttQoS.AT_LEAST_ONCE : MqttQoS.AT_MOST_ONCE; - MqttFixedHeader fixedHeader = new MqttFixedHeader(messageType, - false, - qos, // Spec requires 01 in header for rel - false, - 0); + MqttFixedHeader fixedHeader = new MqttFixedHeader(messageType, false, qos, // Spec requires 01 in header for rel + false, 0); MqttPubAckMessage rel = new MqttPubAckMessage(fixedHeader, MqttMessageIdVariableHeader.from(messageId)); ctx.write(rel); ctx.flush(); } - void handlePuback(MqttPubAckMessage message) throws Exception - { + void handlePuback(MqttPubAckMessage message) throws Exception { session.getMqttPublishManager().handlePubAck(message.variableHeader().messageId()); } - void handlePubrec(MqttMessage message) throws Exception - { - int messageId = ((MqttMessageIdVariableHeader) message.variableHeader()).messageId(); + void handlePubrec(MqttMessage message) throws Exception { + int messageId = ((MqttMessageIdVariableHeader) message.variableHeader()).messageId(); session.getMqttPublishManager().handlePubRec(messageId); } - void handlePubrel(MqttMessage message) - { + void handlePubrel(MqttMessage message) { int messageId = ((MqttMessageIdVariableHeader) message.variableHeader()).messageId(); session.getMqttPublishManager().handlePubRel(messageId); } - void handlePubcomp( MqttMessage message) throws Exception - { + void handlePubcomp(MqttMessage message) throws Exception { int messageId = ((MqttMessageIdVariableHeader) message.variableHeader()).messageId(); session.getMqttPublishManager().handlePubComp(messageId); } - void handleSubscribe(MqttSubscribeMessage message, ChannelHandlerContext ctx) throws Exception - { + void handleSubscribe(MqttSubscribeMessage message, ChannelHandlerContext ctx) throws Exception { MQTTSubscriptionManager subscriptionManager = session.getSubscriptionManager(); int[] qos = subscriptionManager.addSubscriptions(message.payload().topicSubscriptions()); - MqttFixedHeader header = new MqttFixedHeader(MqttMessageType.SUBACK, - false, - MqttQoS.AT_MOST_ONCE, - false, - 0); - MqttSubAckMessage ack = new MqttSubAckMessage(header, - message.variableHeader(), - new MqttSubAckPayload(qos)); + MqttFixedHeader header = new MqttFixedHeader(MqttMessageType.SUBACK, false, MqttQoS.AT_MOST_ONCE, false, 0); + MqttSubAckMessage ack = new MqttSubAckMessage(header, message.variableHeader(), new MqttSubAckPayload(qos)); ctx.write(ack); ctx.flush(); } - void handleSuback(MqttSubAckMessage message) - { + void handleSuback(MqttSubAckMessage message) { disconnect(); } - void handleUnsubscribe(MqttUnsubscribeMessage message) throws Exception - { + void handleUnsubscribe(MqttUnsubscribeMessage message) throws Exception { session.getSubscriptionManager().removeSubscriptions(message.payload().topics()); - MqttFixedHeader header = new MqttFixedHeader(MqttMessageType.UNSUBACK, - false, - MqttQoS.AT_MOST_ONCE, - false, - 0); + MqttFixedHeader header = new MqttFixedHeader(MqttMessageType.UNSUBACK, false, MqttQoS.AT_MOST_ONCE, false, 0); MqttUnsubAckMessage m = new MqttUnsubAckMessage(header, message.variableHeader()); ctx.write(m); ctx.flush(); } - void handleUnsuback(MqttUnsubAckMessage message) - { + void handleUnsuback(MqttUnsubAckMessage message) { disconnect(); } - void handlePingreq(MqttMessage message, ChannelHandlerContext ctx) - { - ctx.write(new MqttMessage(new MqttFixedHeader(MqttMessageType.PINGRESP, - false, - MqttQoS.AT_MOST_ONCE, - false, - 0))); + void handlePingreq(MqttMessage message, ChannelHandlerContext ctx) { + ctx.write(new MqttMessage(new MqttFixedHeader(MqttMessageType.PINGRESP, false, MqttQoS.AT_MOST_ONCE, false, 0))); ctx.flush(); } - void handlePingresp(MqttMessage message) - { + void handlePingresp(MqttMessage message) { disconnect(); } - void handleDisconnect(MqttMessage message) - { - if (session.getSessionState() != null) session.getState().deleteWillMessage(); + void handleDisconnect(MqttMessage message) { + if (session.getSessionState() != null) + session.getState().deleteWillMessage(); disconnect(); } - - protected int send(int messageId, String topicName, int qosLevel, ByteBuf payload, int deliveryCount) - { + protected int send(int messageId, String topicName, int qosLevel, ByteBuf payload, int deliveryCount) { boolean redelivery = qosLevel == 0 ? false : (deliveryCount > 0); - MqttFixedHeader header = new MqttFixedHeader(MqttMessageType.PUBLISH, - redelivery, - MqttQoS.valueOf(qosLevel), - false, - 0); + MqttFixedHeader header = new MqttFixedHeader(MqttMessageType.PUBLISH, redelivery, MqttQoS.valueOf(qosLevel), false, 0); MqttPublishVariableHeader varHeader = new MqttPublishVariableHeader(topicName, messageId); MqttMessage publish = new MqttPublishMessage(header, varHeader, payload); @@ -355,8 +287,7 @@ public class MQTTProtocolHandler extends ChannelInboundHandlerAdapter return 1; } - ActiveMQServer getServer() - { + ActiveMQServer getServer() { return server; } } diff --git a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTProtocolManager.java b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTProtocolManager.java index b92a09f02f..ce75e4d268 100644 --- a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTProtocolManager.java +++ b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTProtocolManager.java @@ -37,74 +37,60 @@ import java.util.List; /** * MQTTProtocolManager */ -class MQTTProtocolManager implements ProtocolManager, NotificationListener -{ +class MQTTProtocolManager implements ProtocolManager, NotificationListener { + private ActiveMQServer server; private MQTTLogger log = MQTTLogger.LOGGER; - public MQTTProtocolManager(ActiveMQServer server) - { + public MQTTProtocolManager(ActiveMQServer server) { this.server = server; } @Override - public void onNotification(Notification notification) - { + public void onNotification(Notification notification) { // TODO handle notifications } - @Override - public ProtocolManagerFactory getFactory() - { + public ProtocolManagerFactory getFactory() { return new MQTTProtocolManagerFactory(); } @Override - public void updateInterceptors(List incomingInterceptors, List outgoingInterceptors) - { + public void updateInterceptors(List incomingInterceptors, List outgoingInterceptors) { // TODO handle interceptors } @Override - public ConnectionEntry createConnectionEntry(Acceptor acceptorUsed, Connection connection) - { - try - { - MQTTConnection mqttConnection = new MQTTConnection(connection); - ConnectionEntry entry = new ConnectionEntry(mqttConnection, - null, - System.currentTimeMillis(), - MQTTUtil.DEFAULT_KEEP_ALIVE_FREQUENCY); + public ConnectionEntry createConnectionEntry(Acceptor acceptorUsed, Connection connection) { + try { + MQTTConnection mqttConnection = new MQTTConnection(connection); + ConnectionEntry entry = new ConnectionEntry(mqttConnection, null, System.currentTimeMillis(), MQTTUtil.DEFAULT_KEEP_ALIVE_FREQUENCY); NettyServerConnection nettyConnection = ((NettyServerConnection) connection); MQTTProtocolHandler protocolHandler = nettyConnection.getChannel().pipeline().get(MQTTProtocolHandler.class); protocolHandler.setConnection(mqttConnection, entry); return entry; } - catch (Exception e) - { + catch (Exception e) { log.error(e); return null; } } @Override - public void removeHandler(String name) - { + public void removeHandler(String name) { // TODO add support for handlers } @Override - public void handleBuffer(RemotingConnection connection, ActiveMQBuffer buffer) - { + public void handleBuffer(RemotingConnection connection, ActiveMQBuffer buffer) { connection.bufferReceived(connection.getID(), buffer); } @Override - public void addChannelHandlers(ChannelPipeline pipeline) - { + public void addChannelHandlers(ChannelPipeline pipeline) { pipeline.addLast(new MqttEncoder()); pipeline.addLast(new MqttDecoder(MQTTUtil.MAX_MESSAGE_SIZE)); @@ -112,29 +98,26 @@ class MQTTProtocolManager implements ProtocolManager, NotificationListener } @Override - public boolean isProtocol(byte[] array) - { + public boolean isProtocol(byte[] array) { boolean mqtt311 = array[4] == 77 && // M - array[5] == 81 && // Q - array[6] == 84 && // T - array[7] == 84; // T + array[5] == 81 && // Q + array[6] == 84 && // T + array[7] == 84; // T // FIXME The actual protocol name is 'MQIsdp' (However we are only passed the first 4 bytes of the protocol name) - boolean mqtt31 = array[4] == 77 && // M - array[5] == 81 && // Q - array[6] == 73 && // I - array[7] == 115; // s + boolean mqtt31 = array[4] == 77 && // M + array[5] == 81 && // Q + array[6] == 73 && // I + array[7] == 115; // s return mqtt311 || mqtt31; } @Override - public MessageConverter getConverter() - { + public MessageConverter getConverter() { return null; } @Override - public void handshake(NettyServerConnection connection, ActiveMQBuffer buffer) - { + public void handshake(NettyServerConnection connection, ActiveMQBuffer buffer) { } } diff --git a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTProtocolManagerFactory.java b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTProtocolManagerFactory.java index 7194d02d5f..33733fe721 100644 --- a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTProtocolManagerFactory.java +++ b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTProtocolManagerFactory.java @@ -23,8 +23,8 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.spi.core.protocol.ProtocolManager; import org.apache.activemq.artemis.spi.core.protocol.ProtocolManagerFactory; -public class MQTTProtocolManagerFactory implements ProtocolManagerFactory -{ +public class MQTTProtocolManagerFactory implements ProtocolManagerFactory { + public static final String MQTT_PROTOCOL_NAME = "MQTT"; private static final String MODULE_NAME = "artemis-mqtt-protocol"; @@ -32,27 +32,25 @@ public class MQTTProtocolManagerFactory implements ProtocolManagerFactory private static final String[] SUPPORTED_PROTOCOLS = {MQTT_PROTOCOL_NAME}; @Override - public ProtocolManager createProtocolManager(ActiveMQServer server, List incomingInterceptors, List outgoingInterceptors) - { + public ProtocolManager createProtocolManager(ActiveMQServer server, + List incomingInterceptors, + List outgoingInterceptors) { return new MQTTProtocolManager(server); } @Override - public List filterInterceptors(List list) - { + public List filterInterceptors(List list) { // TODO Add support for interceptors. return null; } @Override - public String[] getProtocols() - { + public String[] getProtocols() { return SUPPORTED_PROTOCOLS; } @Override - public String getModuleName() - { + public String getModuleName() { return MODULE_NAME; } } diff --git a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTPublishManager.java b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTPublishManager.java index 45260d57a2..ac4042076f 100644 --- a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTPublishManager.java +++ b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTPublishManager.java @@ -30,8 +30,8 @@ import org.apache.activemq.artemis.core.server.impl.ServerMessageImpl; /** * Handles MQTT Exactly Once (QoS level 2) Protocol. */ -public class MQTTPublishManager -{ +public class MQTTPublishManager { + private static final String MANAGEMENT_QUEUE_PREFIX = "$sys.mqtt.queue.qos2."; private SimpleString managementAddress; @@ -44,94 +44,79 @@ public class MQTTPublishManager private final Object lock = new Object(); - public MQTTPublishManager(MQTTSession session) - { + public MQTTPublishManager(MQTTSession session) { this.session = session; } - synchronized void start() throws Exception - { + synchronized void start() throws Exception { createManagementAddress(); createManagementQueue(); createManagementConsumer(); } - synchronized void stop(boolean clean) throws Exception - { - if (managementConsumer != null) - { + synchronized void stop(boolean clean) throws Exception { + if (managementConsumer != null) { managementConsumer.removeItself(); managementConsumer.setStarted(false); managementConsumer.close(false); - if (clean) session.getServer().destroyQueue(managementAddress); + if (clean) + session.getServer().destroyQueue(managementAddress); } } - private void createManagementConsumer() throws Exception - { + private void createManagementConsumer() throws Exception { long consumerId = session.getServer().getStorageManager().generateID(); managementConsumer = session.getServerSession().createConsumer(consumerId, managementAddress, null, false, false, -1); managementConsumer.setStarted(true); } - private void createManagementAddress() - { + private void createManagementAddress() { String clientId = session.getSessionState().getClientId(); managementAddress = new SimpleString(MANAGEMENT_QUEUE_PREFIX + clientId); } - private void createManagementQueue() throws Exception - { - if (session.getServer().locateQueue(managementAddress) == null) - { + private void createManagementQueue() throws Exception { + if (session.getServer().locateQueue(managementAddress) == null) { session.getServerSession().createQueue(managementAddress, managementAddress, null, false, MQTTUtil.DURABLE_MESSAGES); } } - boolean isManagementConsumer(ServerConsumer consumer) - { + boolean isManagementConsumer(ServerConsumer consumer) { return consumer == managementConsumer; } - private int generateMqttId(int qos) - { - if (qos == 1) - { + private int generateMqttId(int qos) { + if (qos == 1) { return session.getSessionState().generateId(); } - else - { + else { Integer mqttid = session.getSessionState().generateId(); - if (mqttid == null) - { + if (mqttid == null) { mqttid = (int) session.getServer().getStorageManager().generateID(); } return mqttid; } } - /** Since MQTT Subscriptions can over lap; a client may receive the same message twice. When this happens the client + /** + * Since MQTT Subscriptions can over lap; a client may receive the same message twice. When this happens the client * returns a PubRec or PubAck with ID. But we need to know which consumer to ack, since we only have the ID to go on we * are not able to decide which consumer to ack. Instead we send MQTT messages with different IDs and store a reference * to original ID and consumer in the Session state. This way we can look up the consumer Id and the message Id from - * the PubAck or PubRec message id. **/ - protected void sendMessage(ServerMessage message, ServerConsumer consumer, int deliveryCount) throws Exception - { + * the PubAck or PubRec message id. * + */ + protected void sendMessage(ServerMessage message, ServerConsumer consumer, int deliveryCount) throws Exception { // This is to allow retries of PubRel. - if (isManagementConsumer(consumer)) - { + if (isManagementConsumer(consumer)) { sendPubRelMessage(message); } - else - { + else { int qos = decideQoS(message, consumer); - if (qos == 0) - { + if (qos == 0) { sendServerMessage((int) message.getMessageID(), (ServerMessageImpl) message, deliveryCount, qos); session.getServerSession().acknowledge(consumer.getID(), message.getMessageID()); } - else - { + else { String consumerAddress = consumer.getQueue().getAddress().toString(); Integer mqttid = generateMqttId(qos); @@ -142,26 +127,21 @@ public class MQTTPublishManager } // INBOUND - void handleMessage(int messageId, String topic, int qos, ByteBuf payload, boolean retain) throws Exception - { - synchronized (lock) - { + void handleMessage(int messageId, String topic, int qos, ByteBuf payload, boolean retain) throws Exception { + synchronized (lock) { ServerMessage serverMessage = MQTTUtil.createServerMessageFromByteBuf(session, topic, retain, qos, payload); - if (qos > 0) - { + if (qos > 0) { serverMessage.setDurable(MQTTUtil.DURABLE_MESSAGES); } - if (qos < 2 || !session.getSessionState().getPubRec().contains(messageId)) - { - if (qos == 2) session.getSessionState().getPubRec().add(messageId); + if (qos < 2 || !session.getSessionState().getPubRec().contains(messageId)) { + if (qos == 2) + session.getSessionState().getPubRec().add(messageId); session.getServerSession().send(serverMessage, true); } - - if (retain) - { + if (retain) { boolean reset = payload instanceof EmptyByteBuf || payload.capacity() == 0; session.getRetainMessageManager().handleRetainedMessage(serverMessage, topic, reset); } @@ -170,10 +150,8 @@ public class MQTTPublishManager } } - void sendPubRelMessage(ServerMessage message) - { - if (message.getIntProperty(MQTTUtil.MQTT_MESSAGE_TYPE_KEY) == MqttMessageType.PUBREL.value()) - { + void sendPubRelMessage(ServerMessage message) { + if (message.getIntProperty(MQTTUtil.MQTT_MESSAGE_TYPE_KEY) == MqttMessageType.PUBREL.value()) { int messageId = message.getIntProperty(MQTTUtil.MQTT_MESSAGE_ID_KEY); MQTTMessageInfo messageInfo = new MQTTMessageInfo(message.getMessageID(), managementConsumer.getID(), message.getAddress().toString()); session.getSessionState().storeMessageRef(messageId, messageInfo, false); @@ -181,36 +159,28 @@ public class MQTTPublishManager } } - private void createMessageAck(final int messageId, final int qos) - { - session.getServer().getStorageManager().afterCompleteOperations(new IOCallback() - { + private void createMessageAck(final int messageId, final int qos) { + session.getServer().getStorageManager().afterCompleteOperations(new IOCallback() { @Override - public void done() - { - if (qos == 1) - { + public void done() { + if (qos == 1) { session.getProtocolHandler().sendPubAck(messageId); } - else if (qos == 2) - { + else if (qos == 2) { session.getProtocolHandler().sendPubRec(messageId); } } @Override - public void onError(int errorCode, String errorMessage) - { + public void onError(int errorCode, String errorMessage) { log.error("Pub Sync Failed"); } }); } - void handlePubRec(int messageId) throws Exception - { + void handlePubRec(int messageId) throws Exception { MQTTMessageInfo messageRef = session.getSessionState().getMessageInfo(messageId); - if (messageRef != null) - { + if (messageRef != null) { ServerMessage pubRel = MQTTUtil.createPubRelMessage(session, managementAddress, messageId); session.getServerSession().send(pubRel, true); session.getServerSession().acknowledge(messageRef.getConsumerId(), messageRef.getServerMessageId()); @@ -218,39 +188,32 @@ public class MQTTPublishManager } } - void handlePubComp(int messageId) throws Exception - { + void handlePubComp(int messageId) throws Exception { MQTTMessageInfo messageInfo = session.getSessionState().getMessageInfo(messageId); // Check to see if this message is stored if not just drop the packet. - if (messageInfo != null) - { + if (messageInfo != null) { session.getServerSession().acknowledge(managementConsumer.getID(), messageInfo.getServerMessageId()); } } - void handlePubRel(int messageId) - { + void handlePubRel(int messageId) { // We don't check to see if a PubRel existed for this message. We assume it did and so send PubComp. session.getSessionState().getPubRec().remove(messageId); session.getProtocolHandler().sendPubComp(messageId); session.getSessionState().removeMessageRef(messageId); } - - void handlePubAck(int messageId) throws Exception - { + void handlePubAck(int messageId) throws Exception { Pair pub1MessageInfo = session.getSessionState().removeOutbandMessageRef(messageId, 1); - if (pub1MessageInfo != null) - { + if (pub1MessageInfo != null) { String mqttAddress = MQTTUtil.convertCoreAddressFilterToMQTT(pub1MessageInfo.getA()); ServerConsumer consumer = session.getSubscriptionManager().getConsumerForAddress(mqttAddress); session.getServerSession().acknowledge(consumer.getID(), pub1MessageInfo.getB()); } } - private void sendServerMessage(int messageId, ServerMessageImpl message, int deliveryCount, int qos) - { + private void sendServerMessage(int messageId, ServerMessageImpl message, int deliveryCount, int qos) { String address = MQTTUtil.convertCoreAddressFilterToMQTT(message.getAddress().toString()).toString(); //FIXME should we be copying the body buffer here? @@ -258,8 +221,7 @@ public class MQTTPublishManager session.getProtocolHandler().send(messageId, address, qos, payload, deliveryCount); } - private int decideQoS(ServerMessage message, ServerConsumer consumer) - { + private int decideQoS(ServerMessage message, ServerConsumer consumer) { int subscriptionQoS = session.getSubscriptionManager().getConsumerQoSLevels().get(consumer.getID()); int qos = message.getIntProperty(MQTTUtil.MQTT_QOS_LEVEL_KEY); diff --git a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTRetainMessageManager.java b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTRetainMessageManager.java index 5fdcb770b5..dd6bbc0b2f 100644 --- a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTRetainMessageManager.java +++ b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTRetainMessageManager.java @@ -25,30 +25,28 @@ import org.apache.activemq.artemis.core.server.MessageReference; import org.apache.activemq.artemis.core.server.Queue; import org.apache.activemq.artemis.core.server.ServerMessage; +public class MQTTRetainMessageManager { -public class MQTTRetainMessageManager -{ private MQTTSession session; - public MQTTRetainMessageManager(MQTTSession session) - { + public MQTTRetainMessageManager(MQTTSession session) { this.session = session; } - /** FIXME - * Retained messages should be handled in the core API. There is currently no support for retained messages - * at the time of writing. Instead we handle retained messages here. This method will create a new queue for - * every address that is used to store retained messages. THere should only ever be one message in the retained - * message queue. When a new subscription is created the queue should be browsed and the message copied onto - * the subscription queue for the consumer. When a new retained message is received the message will be sent to - * the retained queue and the previous retain message consumed to remove it from the queue. */ - void handleRetainedMessage(ServerMessage message, String address, boolean reset) throws Exception - { + /** + * FIXME + * Retained messages should be handled in the core API. There is currently no support for retained messages + * at the time of writing. Instead we handle retained messages here. This method will create a new queue for + * every address that is used to store retained messages. THere should only ever be one message in the retained + * message queue. When a new subscription is created the queue should be browsed and the message copied onto + * the subscription queue for the consumer. When a new retained message is received the message will be sent to + * the retained queue and the previous retain message consumed to remove it from the queue. + */ + void handleRetainedMessage(ServerMessage message, String address, boolean reset) throws Exception { SimpleString retainAddress = new SimpleString(MQTTUtil.convertMQTTAddressFilterToCoreRetain(address)); Queue queue = session.getServer().locateQueue(retainAddress); - if (queue == null) - { + if (queue == null) { queue = session.getServerSession().createQueue(retainAddress, retainAddress, null, false, true); } @@ -56,23 +54,19 @@ public class MQTTRetainMessageManager message.setAddress(retainAddress); Iterator iterator = queue.iterator(); - synchronized (iterator) - { - if (iterator.hasNext()) - { + synchronized (iterator) { + if (iterator.hasNext()) { Long messageId = iterator.next().getMessage().getMessageID(); queue.deleteReference(messageId); } - if (!reset) - { + if (!reset) { session.getServerSession().send(message.copy(), true); } } } - void addRetainedMessagesToQueue(SimpleString queueName, String address) throws Exception - { + void addRetainedMessagesToQueue(SimpleString queueName, String address) throws Exception { // Queue to add the retained messages to Queue queue = session.getServer().locateQueue(queueName); @@ -81,14 +75,11 @@ public class MQTTRetainMessageManager BindingQueryResult bindingQueryResult = session.getServerSession().executeBindingQuery(new SimpleString(retainAddress)); // Iterate over all matching retain queues and add the head message to the original queue. - for (SimpleString retainedQueueName : bindingQueryResult.getQueueNames()) - { + for (SimpleString retainedQueueName : bindingQueryResult.getQueueNames()) { Queue retainedQueue = session.getServer().locateQueue(retainedQueueName); - synchronized (this) - { + synchronized (this) { Iterator i = retainedQueue.iterator(); - if (i.hasNext()) - { + if (i.hasNext()) { ServerMessage message = i.next().getMessage().copy(session.getServer().getStorageManager().generateID()); queue.addTail(message.createReference(queue), true); } diff --git a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTSession.java b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTSession.java index e3516f15bc..64023a4dd3 100644 --- a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTSession.java +++ b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTSession.java @@ -25,9 +25,8 @@ import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +public class MQTTSession { -public class MQTTSession -{ static Map SESSIONS = new ConcurrentHashMap<>(); private final String id = UUID.randomUUID().toString(); @@ -54,8 +53,7 @@ public class MQTTSession private MQTTLogger log = MQTTLogger.LOGGER; - public MQTTSession( MQTTProtocolHandler protocolHandler, MQTTConnection connection) throws Exception - { + public MQTTSession(MQTTProtocolHandler protocolHandler, MQTTConnection connection) throws Exception { this.protocolHandler = protocolHandler; this.connection = connection; @@ -69,105 +67,86 @@ public class MQTTSession } // Called after the client has Connected. - synchronized void start() throws Exception - { + synchronized void start() throws Exception { mqttPublishManager.start(); subscriptionManager.start(); stopped = false; } // TODO ensure resources are cleaned up for GC. - synchronized void stop() throws Exception - { - if (!stopped) - { + synchronized void stop() throws Exception { + if (!stopped) { protocolHandler.stop(false); // TODO this should pass in clean session. subscriptionManager.stop(false); mqttPublishManager.stop(false); - if (serverSession != null) - { + if (serverSession != null) { serverSession.stop(); serverSession.close(false); } - if (state != null) - { + if (state != null) { state.setAttached(false); } } stopped = true; } - boolean getStopped() - { + boolean getStopped() { return stopped; } - MQTTPublishManager getMqttPublishManager() - { + MQTTPublishManager getMqttPublishManager() { return mqttPublishManager; } - MQTTSessionState getState() - { + MQTTSessionState getState() { return state; } - MQTTConnectionManager getConnectionManager() - { + MQTTConnectionManager getConnectionManager() { return mqttConnectionManager; } - MQTTSessionState getSessionState() - { + MQTTSessionState getSessionState() { return state; } - ServerSessionImpl getServerSession() - { + ServerSessionImpl getServerSession() { return serverSession; } - ActiveMQServer getServer() - { + ActiveMQServer getServer() { return protocolHandler.getServer(); } - MQTTSubscriptionManager getSubscriptionManager() - { + MQTTSubscriptionManager getSubscriptionManager() { return subscriptionManager; } - MQTTProtocolHandler getProtocolHandler() - { + MQTTProtocolHandler getProtocolHandler() { return protocolHandler; } - SessionCallback getSessionCallback() - { + SessionCallback getSessionCallback() { return sessionCallback; } - void setServerSession(ServerSessionImpl serverSession) - { + void setServerSession(ServerSessionImpl serverSession) { this.serverSession = serverSession; } - void setSessionState(MQTTSessionState state) - { + void setSessionState(MQTTSessionState state) { this.state = state; state.setAttached(true); } - MQTTRetainMessageManager getRetainMessageManager() - { + MQTTRetainMessageManager getRetainMessageManager() { return retainMessageManager; } - MQTTConnection getConnection() - { + MQTTConnection getConnection() { return connection; } } diff --git a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTSessionCallback.java b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTSessionCallback.java index 63e19a5005..45a9192e0d 100644 --- a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTSessionCallback.java +++ b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTSessionCallback.java @@ -23,26 +23,22 @@ import org.apache.activemq.artemis.core.server.ServerMessage; import org.apache.activemq.artemis.spi.core.protocol.SessionCallback; import org.apache.activemq.artemis.spi.core.remoting.ReadyListener; -public class MQTTSessionCallback implements SessionCallback -{ +public class MQTTSessionCallback implements SessionCallback { + private MQTTSession session; private MQTTLogger log = MQTTLogger.LOGGER; - public MQTTSessionCallback(MQTTSession session) throws Exception - { + public MQTTSessionCallback(MQTTSession session) throws Exception { this.session = session; } @Override - public int sendMessage(ServerMessage message, ServerConsumer consumer, int deliveryCount) - { - try - { + public int sendMessage(ServerMessage message, ServerConsumer consumer, int deliveryCount) { + try { session.getMqttPublishManager().sendMessage(message, consumer, deliveryCount); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); log.warn("Unable to send message: " + message.getMessageID() + " Cause: " + e.getMessage()); } @@ -50,62 +46,54 @@ public class MQTTSessionCallback implements SessionCallback } @Override - public int sendLargeMessageContinuation(ServerConsumer consumerID, byte[] body, boolean continues, boolean requiresResponse) - { + public int sendLargeMessageContinuation(ServerConsumer consumerID, + byte[] body, + boolean continues, + boolean requiresResponse) { log.warn("Sending LARGE MESSAGE"); return 1; } @Override - public void addReadyListener(ReadyListener listener) - { + public void addReadyListener(ReadyListener listener) { session.getConnection().getTransportConnection().addReadyListener(listener); } @Override - public void removeReadyListener(ReadyListener listener) - { + public void removeReadyListener(ReadyListener listener) { session.getConnection().getTransportConnection().removeReadyListener(listener); } @Override - public int sendLargeMessage(ServerMessage message, ServerConsumer consumer, long bodySize, int deliveryCount) - { + public int sendLargeMessage(ServerMessage message, ServerConsumer consumer, long bodySize, int deliveryCount) { return sendMessage(message, consumer, deliveryCount); } @Override - public void disconnect(ServerConsumer consumer, String queueName) - { - try - { + public void disconnect(ServerConsumer consumer, String queueName) { + try { consumer.removeItself(); } - catch (Exception e) - { + catch (Exception e) { log.error(e.getMessage()); } } @Override - public boolean hasCredits(ServerConsumer consumerID) - { + public boolean hasCredits(ServerConsumer consumerID) { return true; } @Override - public void sendProducerCreditsMessage(int credits, SimpleString address) - { + public void sendProducerCreditsMessage(int credits, SimpleString address) { } @Override - public void sendProducerCreditsFailMessage(int credits, SimpleString address) - { + public void sendProducerCreditsFailMessage(int credits, SimpleString address) { } @Override - public void closed() - { + public void closed() { } } diff --git a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTSessionState.java b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTSessionState.java index d6bbd44221..6fd575229b 100644 --- a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTSessionState.java +++ b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTSessionState.java @@ -29,8 +29,8 @@ import io.netty.handler.codec.mqtt.MqttTopicSubscription; import org.apache.activemq.artemis.api.core.Pair; import org.apache.activemq.artemis.core.server.ServerMessage; -public class MQTTSessionState -{ +public class MQTTSessionState { + private String clientId; private ServerMessage willMessage; @@ -60,8 +60,7 @@ public class MQTTSessionState // FIXME We should use a better mechanism for creating packet IDs. private AtomicInteger lastId = new AtomicInteger(0); - public MQTTSessionState(String clientId) - { + public MQTTSessionState(String clientId) { this.clientId = clientId; pubRec = new HashSet<>(); @@ -74,25 +73,19 @@ public class MQTTSessionState addressMessageMap = new ConcurrentHashMap<>(); } - int generateId() - { + int generateId() { lastId.compareAndSet(Short.MAX_VALUE, 1); return lastId.addAndGet(1); } - void addOutbandMessageRef(int mqttId, String address, long serverMessageId, int qos) - { - synchronized (outboundLock) - { + void addOutbandMessageRef(int mqttId, String address, long serverMessageId, int qos) { + synchronized (outboundLock) { outboundMessageReferenceStore.put(mqttId, new Pair(address, serverMessageId)); - if (qos == 2) - { - if (reverseOutboundReferenceStore.containsKey(address)) - { + if (qos == 2) { + if (reverseOutboundReferenceStore.containsKey(address)) { reverseOutboundReferenceStore.get(address).put(serverMessageId, mqttId); } - else - { + else { ConcurrentHashMap serverToMqttId = new ConcurrentHashMap(); serverToMqttId.put(serverMessageId, mqttId); reverseOutboundReferenceStore.put(address, serverToMqttId); @@ -101,22 +94,17 @@ public class MQTTSessionState } } - Pair removeOutbandMessageRef(int mqttId, int qos) - { - synchronized (outboundLock) - { + Pair removeOutbandMessageRef(int mqttId, int qos) { + synchronized (outboundLock) { Pair messageInfo = outboundMessageReferenceStore.remove(mqttId); - if (qos == 1) - { + if (qos == 1) { return messageInfo; } Map map = reverseOutboundReferenceStore.get(messageInfo.getA()); - if (map != null) - { + if (map != null) { map.remove(messageInfo.getB()); - if (map.isEmpty()) - { + if (map.isEmpty()) { reverseOutboundReferenceStore.remove(messageInfo.getA()); } return messageInfo; @@ -125,68 +113,54 @@ public class MQTTSessionState } } - Set getPubRec() - { + Set getPubRec() { return pubRec; } - Set getPub() - { + Set getPub() { return pub; } - boolean getAttached() - { + boolean getAttached() { return attached; } - void setAttached(boolean attached) - { + void setAttached(boolean attached) { this.attached = attached; } - boolean isWill() - { + boolean isWill() { return willMessage != null; } - ServerMessage getWillMessage() - { + ServerMessage getWillMessage() { return willMessage; } - void setWillMessage(ServerMessage willMessage) - { + void setWillMessage(ServerMessage willMessage) { this.willMessage = willMessage; } - void deleteWillMessage() - { + void deleteWillMessage() { willMessage = null; } - Collection getSubscriptions() - { + Collection getSubscriptions() { return subscriptions.values(); } - boolean addSubscription(MqttTopicSubscription subscription) - { - synchronized (subscriptions) - { + boolean addSubscription(MqttTopicSubscription subscription) { + synchronized (subscriptions) { addressMessageMap.putIfAbsent(MQTTUtil.convertMQTTAddressFilterToCore(subscription.topicName()), new ConcurrentHashMap()); MqttTopicSubscription existingSubscription = subscriptions.get(subscription.topicName()); - if (existingSubscription != null) - { - if (subscription.qualityOfService().value() > existingSubscription.qualityOfService().value()) - { + if (existingSubscription != null) { + if (subscription.qualityOfService().value() > existingSubscription.qualityOfService().value()) { subscriptions.put(subscription.topicName(), subscription); return true; } } - else - { + else { subscriptions.put(subscription.topicName(), subscription); return true; } @@ -194,58 +168,46 @@ public class MQTTSessionState return false; } - void removeSubscription(String address) - { - synchronized (subscriptions) - { + void removeSubscription(String address) { + synchronized (subscriptions) { subscriptions.remove(address); addressMessageMap.remove(address); } } - MqttTopicSubscription getSubscription(String address) - { + MqttTopicSubscription getSubscription(String address) { return subscriptions.get(address); } - String getClientId() - { + String getClientId() { return clientId; } - void setClientId(String clientId) - { + void setClientId(String clientId) { this.clientId = clientId; } - void storeMessageRef(Integer mqttId, MQTTMessageInfo messageInfo, boolean storeAddress) - { + void storeMessageRef(Integer mqttId, MQTTMessageInfo messageInfo, boolean storeAddress) { messageRefStore.put(mqttId, messageInfo); - if (storeAddress) - { + if (storeAddress) { Map addressMap = addressMessageMap.get(messageInfo.getAddress()); - if (addressMap != null) - { + if (addressMap != null) { addressMap.put(messageInfo.getServerMessageId(), mqttId); } } } - void removeMessageRef(Integer mqttId) - { + void removeMessageRef(Integer mqttId) { MQTTMessageInfo info = messageRefStore.remove(mqttId); - if (info != null) - { + if (info != null) { Map addressMap = addressMessageMap.get(info.getAddress()); - if (addressMap != null) - { + if (addressMap != null) { addressMap.remove(info.getServerMessageId()); } } } - MQTTMessageInfo getMessageInfo(Integer mqttId) - { + MQTTMessageInfo getMessageInfo(Integer mqttId) { return messageRefStore.get(mqttId); } } diff --git a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTSubscriptionManager.java b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTSubscriptionManager.java index fc6dccbf86..954a1bd1f8 100644 --- a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTSubscriptionManager.java +++ b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTSubscriptionManager.java @@ -27,8 +27,8 @@ import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.server.Queue; import org.apache.activemq.artemis.core.server.ServerConsumer; -public class MQTTSubscriptionManager -{ +public class MQTTSubscriptionManager { + private MQTTSession session; private ConcurrentMap consumerQoSLevels; @@ -37,37 +37,30 @@ public class MQTTSubscriptionManager private MQTTLogger log = MQTTLogger.LOGGER; - public MQTTSubscriptionManager(MQTTSession session) - { + public MQTTSubscriptionManager(MQTTSession session) { this.session = session; consumers = new ConcurrentHashMap<>(); consumerQoSLevels = new ConcurrentHashMap<>(); } - synchronized void start() throws Exception - { - for (MqttTopicSubscription subscription : session.getSessionState().getSubscriptions()) - { + synchronized void start() throws Exception { + for (MqttTopicSubscription subscription : session.getSessionState().getSubscriptions()) { SimpleString q = createQueueForSubscription(subscription.topicName(), subscription.qualityOfService().value()); createConsumerForSubscriptionQueue(q, subscription.topicName(), subscription.qualityOfService().value()); } } - synchronized void stop(boolean clean) throws Exception - { - for (ServerConsumer consumer : consumers.values()) - { + synchronized void stop(boolean clean) throws Exception { + for (ServerConsumer consumer : consumers.values()) { consumer.setStarted(false); consumer.disconnect(); consumer.getQueue().removeConsumer(consumer); consumer.close(false); } - if (clean) - { - for (ServerConsumer consumer : consumers.values()) - { + if (clean) { + for (ServerConsumer consumer : consumers.values()) { session.getServer().destroyQueue(consumer.getQueue().getName()); } } @@ -76,14 +69,12 @@ public class MQTTSubscriptionManager /** * Creates a Queue if it doesn't already exist, based on a topic and address. Returning the queue name. */ - private SimpleString createQueueForSubscription(String topic, int qos) throws Exception - { + private SimpleString createQueueForSubscription(String topic, int qos) throws Exception { String address = MQTTUtil.convertMQTTAddressFilterToCore(topic); SimpleString queue = getQueueNameForTopic(address); Queue q = session.getServer().locateQueue(queue); - if (q == null) - { + if (q == null) { session.getServerSession().createQueue(new SimpleString(address), queue, null, false, MQTTUtil.DURABLE_MESSAGES && qos >= 0); } return queue; @@ -92,8 +83,7 @@ public class MQTTSubscriptionManager /** * Creates a new consumer for the queue associated with a subscription */ - private void createConsumerForSubscriptionQueue(SimpleString queue, String topic, int qos) throws Exception - { + private void createConsumerForSubscriptionQueue(SimpleString queue, String topic, int qos) throws Exception { long cid = session.getServer().getStorageManager().generateID(); ServerConsumer consumer = session.getServerSession().createConsumer(cid, queue, null, false, true, -1); @@ -103,9 +93,7 @@ public class MQTTSubscriptionManager consumerQoSLevels.put(cid, qos); } - - private void addSubscription(MqttTopicSubscription subscription) throws Exception - { + private void addSubscription(MqttTopicSubscription subscription) throws Exception { MqttTopicSubscription s = session.getSessionState().getSubscription(subscription.topicName()); int qos = subscription.qualityOfService().value(); @@ -115,28 +103,23 @@ public class MQTTSubscriptionManager SimpleString q = createQueueForSubscription(topic, qos); - if (s == null) - { + if (s == null) { createConsumerForSubscriptionQueue(q, topic, qos); } - else - { + else { consumerQoSLevels.put(consumers.get(topic).getID(), qos); } session.getRetainMessageManager().addRetainedMessagesToQueue(q, topic); } - void removeSubscriptions(List topics) throws Exception - { - for (String topic : topics) - { + void removeSubscriptions(List topics) throws Exception { + for (String topic : topics) { removeSubscription(topic); } } // FIXME: Do we need this synchronzied? - private synchronized void removeSubscription(String address) throws Exception - { + private synchronized void removeSubscription(String address) throws Exception { ServerConsumer consumer = consumers.get(address); String internalAddress = MQTTUtil.convertMQTTAddressFilterToCore(address); SimpleString internalQueueName = getQueueNameForTopic(internalAddress); @@ -148,8 +131,7 @@ public class MQTTSubscriptionManager consumerQoSLevels.remove(consumer.getID()); } - private SimpleString getQueueNameForTopic(String topic) - { + private SimpleString getQueueNameForTopic(String topic) { return new SimpleString(session.getSessionState().getClientId() + "." + topic); } @@ -158,28 +140,23 @@ public class MQTTSubscriptionManager * * @param subscriptions * @return An array of integers representing the list of accepted QoS for each topic. - * * @throws Exception */ - int[] addSubscriptions(List subscriptions) throws Exception - { + int[] addSubscriptions(List subscriptions) throws Exception { int[] qos = new int[subscriptions.size()]; - for (int i = 0; i < subscriptions.size(); i++) - { + for (int i = 0; i < subscriptions.size(); i++) { addSubscription(subscriptions.get(i)); qos[i] = subscriptions.get(i).qualityOfService().value(); } return qos; } - Map getConsumerQoSLevels() - { + Map getConsumerQoSLevels() { return consumerQoSLevels; } - ServerConsumer getConsumerForAddress(String address) - { + ServerConsumer getConsumerForAddress(String address) { return consumers.get(address); } } diff --git a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTUtil.java b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTUtil.java index c6f1a65395..f2a69719e3 100644 --- a/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTUtil.java +++ b/artemis-protocols/artemis-mqtt-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTUtil.java @@ -33,8 +33,8 @@ import org.apache.activemq.artemis.core.server.impl.ServerMessageImpl; * A Utility Class for creating Server Side objects and converting MQTT concepts to/from Artemis. */ -public class MQTTUtil -{ +public class MQTTUtil { + // TODO These settings should be configurable. public static final int DEFAULT_SERVER_MESSAGE_BUFFER_SIZE = 512; @@ -66,44 +66,40 @@ public class MQTTUtil public static final int DEFAULT_KEEP_ALIVE_FREQUENCY = 5000; - public static String convertMQTTAddressFilterToCore(String filter) - { + public static String convertMQTTAddressFilterToCore(String filter) { return MQTT_ADDRESS_PREFIX + swapMQTTAndCoreWildCards(filter); } - public static String convertCoreAddressFilterToMQTT(String filter) - { - if (filter.startsWith(MQTT_RETAIN_ADDRESS_PREFIX.toString())) - { + public static String convertCoreAddressFilterToMQTT(String filter) { + if (filter.startsWith(MQTT_RETAIN_ADDRESS_PREFIX.toString())) { filter = filter.substring(MQTT_RETAIN_ADDRESS_PREFIX.length(), filter.length()); } - else if (filter.startsWith(MQTT_ADDRESS_PREFIX.toString())) - { + else if (filter.startsWith(MQTT_ADDRESS_PREFIX.toString())) { filter = filter.substring(MQTT_ADDRESS_PREFIX.length(), filter.length()); } return swapMQTTAndCoreWildCards(filter); } - public static String convertMQTTAddressFilterToCoreRetain(String filter) - { + public static String convertMQTTAddressFilterToCoreRetain(String filter) { return MQTT_RETAIN_ADDRESS_PREFIX + swapMQTTAndCoreWildCards(filter); } - public static String swapMQTTAndCoreWildCards(String filter) - { + public static String swapMQTTAndCoreWildCards(String filter) { char[] topicFilter = filter.toCharArray(); - for (int i = 0; i < topicFilter.length; i++) - { - switch (topicFilter[i]) - { + for (int i = 0; i < topicFilter.length; i++) { + switch (topicFilter[i]) { case '/': - topicFilter[i] = '.'; break; + topicFilter[i] = '.'; + break; case '.': - topicFilter[i] = '/'; break; + topicFilter[i] = '/'; + break; case '*': - topicFilter[i] = '+'; break; + topicFilter[i] = '+'; + break; case '+': - topicFilter[i] = '*'; break; + topicFilter[i] = '*'; + break; default: break; } @@ -111,8 +107,10 @@ public class MQTTUtil return String.valueOf(topicFilter); } - private static ServerMessage createServerMessage(MQTTSession session, SimpleString address, boolean retain, int qos) - { + private static ServerMessage createServerMessage(MQTTSession session, + SimpleString address, + boolean retain, + int qos) { long id = session.getServer().getStorageManager().generateID(); ServerMessageImpl message = new ServerMessageImpl(id, DEFAULT_SERVER_MESSAGE_BUFFER_SIZE); @@ -122,8 +120,11 @@ public class MQTTUtil return message; } - public static ServerMessage createServerMessageFromByteBuf(MQTTSession session, String topic, boolean retain, int qos, ByteBuf payload) - { + public static ServerMessage createServerMessageFromByteBuf(MQTTSession session, + String topic, + boolean retain, + int qos, + ByteBuf payload) { String coreAddress = convertMQTTAddressFilterToCore(topic); ServerMessage message = createServerMessage(session, new SimpleString(coreAddress), retain, qos); @@ -132,41 +133,38 @@ public class MQTTUtil return message; } - public static ServerMessage createServerMessageFromString(MQTTSession session, String payload, String topic, int qos, boolean retain) - { + public static ServerMessage createServerMessageFromString(MQTTSession session, + String payload, + String topic, + int qos, + boolean retain) { ServerMessage message = createServerMessage(session, new SimpleString(topic), retain, qos); message.getBodyBuffer().writeString(payload); return message; } - public static ServerMessage createPubRelMessage(MQTTSession session, SimpleString address, int messageId) - { + public static ServerMessage createPubRelMessage(MQTTSession session, SimpleString address, int messageId) { ServerMessage message = createServerMessage(session, address, false, 1); message.putIntProperty(new SimpleString(MQTTUtil.MQTT_MESSAGE_ID_KEY), messageId); message.putIntProperty(new SimpleString(MQTTUtil.MQTT_MESSAGE_TYPE_KEY), MqttMessageType.PUBREL.value()); return message; } - public static void logMessage(MQTTLogger logger, MqttMessage message, boolean inbound) - { + + public static void logMessage(MQTTLogger logger, MqttMessage message, boolean inbound) { StringBuilder log = inbound ? new StringBuilder("Received ") : new StringBuilder("Sent "); - if (message.fixedHeader() != null) - { + if (message.fixedHeader() != null) { log.append(message.fixedHeader().messageType().toString()); - if (message.variableHeader() instanceof MqttPublishVariableHeader) - { + if (message.variableHeader() instanceof MqttPublishVariableHeader) { log.append("(" + ((MqttPublishVariableHeader) message.variableHeader()).messageId() + ") " + message.fixedHeader().qosLevel()); } - else if (message.variableHeader() instanceof MqttMessageIdVariableHeader) - { + else if (message.variableHeader() instanceof MqttMessageIdVariableHeader) { log.append("(" + ((MqttMessageIdVariableHeader) message.variableHeader()).messageId() + ")"); } - if (message.fixedHeader().messageType() == MqttMessageType.SUBSCRIBE) - { - for (MqttTopicSubscription sub : ((MqttSubscribeMessage) message).payload().topicSubscriptions()) - { + if (message.fixedHeader().messageType() == MqttMessageType.SUBSCRIBE) { + for (MqttTopicSubscription sub : ((MqttSubscribeMessage) message).payload().topicSubscriptions()) { log.append("\n\t" + sub.topicName() + " : " + sub.qualityOfService()); } } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/AMQConnectorImpl.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/AMQConnectorImpl.java index 34d0478512..1d17496398 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/AMQConnectorImpl.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/AMQConnectorImpl.java @@ -22,103 +22,88 @@ import org.apache.activemq.artemis.core.protocol.openwire.amq.AMQConnector; import org.apache.activemq.artemis.core.protocol.openwire.amq.AMQConnectorStatistics; import org.apache.activemq.artemis.spi.core.remoting.Acceptor; -public class AMQConnectorImpl implements AMQConnector -{ +public class AMQConnectorImpl implements AMQConnector { + private Acceptor acceptor; - public AMQConnectorImpl(Acceptor acceptorUsed) - { + public AMQConnectorImpl(Acceptor acceptorUsed) { this.acceptor = acceptorUsed; } @Override - public BrokerInfo getBrokerInfo() - { + public BrokerInfo getBrokerInfo() { // TODO Auto-generated method stub return null; } @Override - public AMQConnectorStatistics getStatistics() - { + public AMQConnectorStatistics getStatistics() { // TODO Auto-generated method stub return null; } @Override - public boolean isUpdateClusterClients() - { + public boolean isUpdateClusterClients() { // TODO Auto-generated method stub return false; } @Override - public boolean isRebalanceClusterClients() - { + public boolean isRebalanceClusterClients() { // TODO Auto-generated method stub return false; } @Override - public void updateClientClusterInfo() - { + public void updateClientClusterInfo() { // TODO Auto-generated method stub } @Override - public boolean isUpdateClusterClientsOnRemove() - { + public boolean isUpdateClusterClientsOnRemove() { // TODO Auto-generated method stub return false; } @Override - public int connectionCount() - { + public int connectionCount() { // TODO Auto-generated method stub return 0; } @Override - public boolean isAllowLinkStealing() - { + public boolean isAllowLinkStealing() { // TODO Auto-generated method stub return true; } @Override - public ConnectionControl getConnectionControl() - { + public ConnectionControl getConnectionControl() { return new ConnectionControl(); } @Override - public void onStarted(OpenWireConnection connection) - { + public void onStarted(OpenWireConnection connection) { // TODO Auto-generated method stub } @Override - public void onStopped(OpenWireConnection connection) - { + public void onStopped(OpenWireConnection connection) { // TODO Auto-generated method stub } - public int getMaximumConsumersAllowedPerConnection() - { + public int getMaximumConsumersAllowedPerConnection() { return 1000000;//this belongs to configuration, now hardcoded } - public int getMaximumProducersAllowedPerConnection() - { + public int getMaximumProducersAllowedPerConnection() { return 1000000;//this belongs to configuration, now hardcoded } - public boolean isAuditNetworkProducers() - { + public boolean isAuditNetworkProducers() { return false; } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/AMQTransactionImpl.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/AMQTransactionImpl.java index daa0d9b60e..e356522cdc 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/AMQTransactionImpl.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/AMQTransactionImpl.java @@ -24,55 +24,46 @@ import org.apache.activemq.artemis.core.transaction.impl.TransactionImpl; import javax.transaction.xa.Xid; -public class AMQTransactionImpl extends TransactionImpl -{ +public class AMQTransactionImpl extends TransactionImpl { + private boolean rollbackForClose = false; - public AMQTransactionImpl(StorageManager storageManager, int timeoutSeconds) - { + public AMQTransactionImpl(StorageManager storageManager, int timeoutSeconds) { super(storageManager, timeoutSeconds); } - public AMQTransactionImpl(StorageManager storageManager) - { + public AMQTransactionImpl(StorageManager storageManager) { super(storageManager); } - public AMQTransactionImpl(Xid xid, StorageManager storageManager, int timeoutSeconds) - { + public AMQTransactionImpl(Xid xid, StorageManager storageManager, int timeoutSeconds) { super(xid, storageManager, timeoutSeconds); } - public AMQTransactionImpl(long id, Xid xid, StorageManager storageManager) - { + public AMQTransactionImpl(long id, Xid xid, StorageManager storageManager) { super(id, xid, storageManager); } @Override - public RefsOperation createRefsOperation(Queue queue) - { + public RefsOperation createRefsOperation(Queue queue) { return new AMQrefsOperation(queue, storageManager); } - public class AMQrefsOperation extends RefsOperation - { - public AMQrefsOperation(Queue queue, StorageManager storageManager) - { + public class AMQrefsOperation extends RefsOperation { + + public AMQrefsOperation(Queue queue, StorageManager storageManager) { super(queue, storageManager); } @Override - public void afterRollback(Transaction tx) - { - if (rollbackForClose) - { + public void afterRollback(Transaction tx) { + if (rollbackForClose) { super.afterRollback(tx); } } } - public void setRollbackForClose() - { + public void setRollbackForClose() { this.rollbackForClose = true; } } \ No newline at end of file diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/BrokerState.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/BrokerState.java index 7b12570148..6935afe27f 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/BrokerState.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/BrokerState.java @@ -19,7 +19,6 @@ package org.apache.activemq.artemis.core.protocol.openwire; /** * The class holds related states of an activemq broker. */ -public class BrokerState -{ +public class BrokerState { } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/DataInputWrapper.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/DataInputWrapper.java index 79f7852d0b..32d37d4530 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/DataInputWrapper.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/DataInputWrapper.java @@ -24,34 +24,29 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.utils.UTF8Util; import org.apache.activemq.artemis.utils.UTF8Util.StringUtilBuffer; -public class DataInputWrapper implements DataInput -{ +public class DataInputWrapper implements DataInput { + private static final int DEFAULT_CAPACITY = 1024 * 1024; private static final NotEnoughBytesException exception = new NotEnoughBytesException(); private ByteBuffer internalBuffer; - public DataInputWrapper() - { + public DataInputWrapper() { this(DEFAULT_CAPACITY); } - public DataInputWrapper(int capacity) - { + public DataInputWrapper(int capacity) { this.internalBuffer = ByteBuffer.allocateDirect(capacity); this.internalBuffer.mark(); this.internalBuffer.limit(0); } - public void receiveData(byte[] data) - { + public void receiveData(byte[] data) { int newSize = data.length; int freeSpace = internalBuffer.capacity() - internalBuffer.limit(); - if (freeSpace < newSize) - { + if (freeSpace < newSize) { internalBuffer.reset(); internalBuffer.compact(); - if (internalBuffer.remaining() < newSize) - { + if (internalBuffer.remaining() < newSize) { //need to enlarge } //make sure mark is at zero and position is at effective limit @@ -60,8 +55,7 @@ public class DataInputWrapper implements DataInput internalBuffer.mark(); internalBuffer.position(pos); } - else - { + else { internalBuffer.position(internalBuffer.limit()); internalBuffer.limit(internalBuffer.capacity()); } @@ -70,8 +64,7 @@ public class DataInputWrapper implements DataInput internalBuffer.reset(); } - public void receiveData(ActiveMQBuffer buffer) - { + public void receiveData(ActiveMQBuffer buffer) { int newSize = buffer.readableBytes(); byte[] newData = new byte[newSize]; buffer.readBytes(newData); @@ -79,35 +72,29 @@ public class DataInputWrapper implements DataInput } //invoke after each successful unmarshall - public void mark() - { + public void mark() { this.internalBuffer.mark(); } @Override - public void readFully(byte[] b) throws IOException - { + public void readFully(byte[] b) throws IOException { readFully(b, 0, b.length); } - private void checkSize(int n) throws NotEnoughBytesException - { - if (internalBuffer.remaining() < n) - { + private void checkSize(int n) throws NotEnoughBytesException { + if (internalBuffer.remaining() < n) { throw exception; } } @Override - public void readFully(byte[] b, int off, int len) throws IOException - { + public void readFully(byte[] b, int off, int len) throws IOException { checkSize(len); internalBuffer.get(b, off, len); } @Override - public int skipBytes(int n) throws IOException - { + public int skipBytes(int n) throws IOException { checkSize(n); int pos = internalBuffer.position(); internalBuffer.position(pos + n); @@ -115,83 +102,71 @@ public class DataInputWrapper implements DataInput } @Override - public boolean readBoolean() throws IOException - { + public boolean readBoolean() throws IOException { checkSize(1); byte b = internalBuffer.get(); return b != 0; } @Override - public byte readByte() throws IOException - { + public byte readByte() throws IOException { checkSize(1); return this.internalBuffer.get(); } @Override - public int readUnsignedByte() throws IOException - { + public int readUnsignedByte() throws IOException { checkSize(1); return 0xFF & this.internalBuffer.get(); } @Override - public short readShort() throws IOException - { + public short readShort() throws IOException { checkSize(2); return this.internalBuffer.getShort(); } @Override - public int readUnsignedShort() throws IOException - { + public int readUnsignedShort() throws IOException { checkSize(2); return 0xFFFF & this.internalBuffer.getShort(); } @Override - public char readChar() throws IOException - { + public char readChar() throws IOException { checkSize(2); return this.internalBuffer.getChar(); } @Override - public int readInt() throws IOException - { + public int readInt() throws IOException { checkSize(4); return this.internalBuffer.getInt(); } @Override - public long readLong() throws IOException - { + public long readLong() throws IOException { checkSize(8); return this.internalBuffer.getLong(); } @Override - public float readFloat() throws IOException - { + public float readFloat() throws IOException { checkSize(4); return this.internalBuffer.getFloat(); } @Override - public double readDouble() throws IOException - { + public double readDouble() throws IOException { checkSize(8); return this.internalBuffer.getDouble(); } @Override - public String readLine() throws IOException - { + public String readLine() throws IOException { StringBuilder sb = new StringBuilder(""); char c = this.readChar(); - while (c != '\n') - { + while (c != '\n') { sb.append(c); c = this.readChar(); } @@ -199,19 +174,16 @@ public class DataInputWrapper implements DataInput } @Override - public String readUTF() throws IOException - { + public String readUTF() throws IOException { StringUtilBuffer buffer = UTF8Util.getThreadLocalBuffer(); final int size = this.readUnsignedShort(); - if (size > buffer.byteBuffer.length) - { + if (size > buffer.byteBuffer.length) { buffer.resizeByteBuffer(size); } - if (size > buffer.charBuffer.length) - { + if (size > buffer.charBuffer.length) { buffer.resizeCharBuffer(size); } @@ -221,28 +193,24 @@ public class DataInputWrapper implements DataInput this.readFully(buffer.byteBuffer, 0, size); - while (count < size) - { + while (count < size) { byte1 = buffer.byteBuffer[count++]; - if (byte1 > 0 && byte1 <= 0x7F) - { - buffer.charBuffer[charCount++] = (char)byte1; + if (byte1 > 0 && byte1 <= 0x7F) { + buffer.charBuffer[charCount++] = (char) byte1; } - else - { + else { int c = byte1 & 0xff; - switch (c >> 4) - { + switch (c >> 4) { case 0xc: case 0xd: byte2 = buffer.byteBuffer[count++]; - buffer.charBuffer[charCount++] = (char)((c & 0x1F) << 6 | byte2 & 0x3F); + buffer.charBuffer[charCount++] = (char) ((c & 0x1F) << 6 | byte2 & 0x3F); break; case 0xe: byte2 = buffer.byteBuffer[count++]; byte3 = buffer.byteBuffer[count++]; - buffer.charBuffer[charCount++] = (char)((c & 0x0F) << 12 | (byte2 & 0x3F) << 6 | (byte3 & 0x3F) << 0); + buffer.charBuffer[charCount++] = (char) ((c & 0x0F) << 12 | (byte2 & 0x3F) << 6 | (byte3 & 0x3F) << 0); break; default: throw new InternalError("unhandled utf8 byte " + c); @@ -253,8 +221,7 @@ public class DataInputWrapper implements DataInput return new String(buffer.charBuffer, 0, charCount); } - public boolean readable() - { + public boolean readable() { return this.internalBuffer.hasRemaining(); } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/NotEnoughBytesException.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/NotEnoughBytesException.java index d75c6f5766..d34ec63db4 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/NotEnoughBytesException.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/NotEnoughBytesException.java @@ -18,8 +18,8 @@ package org.apache.activemq.artemis.core.protocol.openwire; import java.io.IOException; -public class NotEnoughBytesException extends IOException -{ +public class NotEnoughBytesException extends IOException { + private static final long serialVersionUID = 3752739907942923658L; } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/OpenWireConnection.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/OpenWireConnection.java index e465ba701d..e7582f2754 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/OpenWireConnection.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/OpenWireConnection.java @@ -106,8 +106,8 @@ import org.apache.activemq.wireformat.WireFormat; /** * Represents an activemq connection. */ -public class OpenWireConnection implements RemotingConnection, CommandVisitor -{ +public class OpenWireConnection implements RemotingConnection, CommandVisitor { + private final OpenWireProtocolManager protocolManager; private final Connection transportConnection; @@ -182,9 +182,10 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor private volatile AMQSession advisorySession; - public OpenWireConnection(Acceptor acceptorUsed, Connection connection, - OpenWireProtocolManager openWireProtocolManager, OpenWireFormat wf) - { + public OpenWireConnection(Acceptor acceptorUsed, + Connection connection, + OpenWireProtocolManager openWireProtocolManager, + OpenWireFormat wf) { this.protocolManager = openWireProtocolManager; this.transportConnection = connection; this.acceptorUsed = new AMQConnectorImpl(acceptorUsed); @@ -193,31 +194,24 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor } @Override - public void bufferReceived(Object connectionID, ActiveMQBuffer buffer) - { - try - { + public void bufferReceived(Object connectionID, ActiveMQBuffer buffer) { + try { dataInput.receiveData(buffer); } - catch (Throwable t) - { + catch (Throwable t) { ActiveMQServerLogger.LOGGER.error("decoding error", t); return; } // this.setDataReceived(); - while (dataInput.readable()) - { - try - { + while (dataInput.readable()) { + try { Object object = null; - try - { + try { object = wireFormat.unmarshal(dataInput); dataInput.mark(); } - catch (NotEnoughBytesException e) - { + catch (NotEnoughBytesException e) { //meaning the dataInput hasn't enough bytes for a command. //in that case we just return and waiting for the next //call of bufferReceived() @@ -229,125 +223,93 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor int commandId = command.getCommandId(); // the connection handles pings, negotiations directly. // and delegate all other commands to manager. - if (command.getClass() == KeepAliveInfo.class) - { + if (command.getClass() == KeepAliveInfo.class) { KeepAliveInfo info = (KeepAliveInfo) command; - if (info.isResponseRequired()) - { + if (info.isResponseRequired()) { info.setResponseRequired(false); protocolManager.sendReply(this, info); } } - else if (command.getClass() == WireFormatInfo.class) - { + else if (command.getClass() == WireFormatInfo.class) { // amq here starts a read/write monitor thread (detect ttl?) negotiate((WireFormatInfo) command); } - else if (command.getClass() == ConnectionInfo.class - || command.getClass() == ConsumerInfo.class - || command.getClass() == RemoveInfo.class - || command.getClass() == SessionInfo.class - || command.getClass() == ProducerInfo.class - || ActiveMQMessage.class.isAssignableFrom(command.getClass()) - || command.getClass() == MessageAck.class - || command.getClass() == TransactionInfo.class - || command.getClass() == DestinationInfo.class - || command.getClass() == ShutdownInfo.class - || command.getClass() == RemoveSubscriptionInfo.class) - { + else if (command.getClass() == ConnectionInfo.class || command.getClass() == ConsumerInfo.class || command.getClass() == RemoveInfo.class || command.getClass() == SessionInfo.class || command.getClass() == ProducerInfo.class || ActiveMQMessage.class.isAssignableFrom(command.getClass()) || command.getClass() == MessageAck.class || command.getClass() == TransactionInfo.class || command.getClass() == DestinationInfo.class || command.getClass() == ShutdownInfo.class || command.getClass() == RemoveSubscriptionInfo.class) { Response response = null; - if (pendingStop) - { + if (pendingStop) { response = new ExceptionResponse(this.stopError); } - else - { + else { response = ((Command) command).visit(this); - if (response instanceof ExceptionResponse) - { - if (!responseRequired) - { - Throwable cause = ((ExceptionResponse)response).getException(); + if (response instanceof ExceptionResponse) { + if (!responseRequired) { + Throwable cause = ((ExceptionResponse) response).getException(); serviceException(cause); response = null; } } } - if (responseRequired) - { - if (response == null) - { + if (responseRequired) { + if (response == null) { response = new Response(); } } // The context may have been flagged so that the response is not // sent. - if (context != null) - { - if (context.isDontSendReponse()) - { + if (context != null) { + if (context.isDontSendReponse()) { context.setDontSendReponse(false); response = null; } } - if (response != null && !protocolManager.isStopping()) - { + if (response != null && !protocolManager.isStopping()) { response.setCorrelationId(commandId); dispatchSync(response); } } - else - { + else { // note!!! wait for negotiation (e.g. use a countdown latch) // before handling any other commands this.protocolManager.handleCommand(this, command); } } - catch (IOException e) - { + catch (IOException e) { ActiveMQServerLogger.LOGGER.error("error decoding", e); } - catch (Throwable t) - { + catch (Throwable t) { ActiveMQServerLogger.LOGGER.error("error decoding", t); } } } - private void negotiate(WireFormatInfo command) throws IOException - { + private void negotiate(WireFormatInfo command) throws IOException { this.wireFormat.renegotiateWireFormat(command); } @Override - public Object getID() - { + public Object getID() { return transportConnection.getID(); } @Override - public long getCreationTime() - { + public long getCreationTime() { return creationTime; } @Override - public String getRemoteAddress() - { + public String getRemoteAddress() { return transportConnection.getRemoteAddress(); } @Override - public void addFailureListener(FailureListener listener) - { - if (listener == null) - { + public void addFailureListener(FailureListener listener) { + if (listener == null) { throw new IllegalStateException("FailureListener cannot be null"); } @@ -355,10 +317,8 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor } @Override - public boolean removeFailureListener(FailureListener listener) - { - if (listener == null) - { + public boolean removeFailureListener(FailureListener listener) { + if (listener == null) { throw new IllegalStateException("FailureListener cannot be null"); } @@ -366,10 +326,8 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor } @Override - public void addCloseListener(CloseListener listener) - { - if (listener == null) - { + public void addCloseListener(CloseListener listener) { + if (listener == null) { throw new IllegalStateException("CloseListener cannot be null"); } @@ -377,10 +335,8 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor } @Override - public boolean removeCloseListener(CloseListener listener) - { - if (listener == null) - { + public boolean removeCloseListener(CloseListener listener) { + if (listener == null) { throw new IllegalStateException("CloseListener cannot be null"); } @@ -388,8 +344,7 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor } @Override - public List removeCloseListeners() - { + public List removeCloseListeners() { List ret = new ArrayList(closeListeners); closeListeners.clear(); @@ -398,26 +353,22 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor } @Override - public void setCloseListeners(List listeners) - { + public void setCloseListeners(List listeners) { closeListeners.clear(); closeListeners.addAll(listeners); } @Override - public List getFailureListeners() - { + public List getFailureListeners() { // we do not return the listeners otherwise the remoting service // would NOT destroy the connection. return Collections.emptyList(); } @Override - public List removeFailureListeners() - { - List ret = new ArrayList( - failureListeners); + public List removeFailureListeners() { + List ret = new ArrayList(failureListeners); failureListeners.clear(); @@ -425,24 +376,20 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor } @Override - public void setFailureListeners(List listeners) - { + public void setFailureListeners(List listeners) { failureListeners.clear(); failureListeners.addAll(listeners); } @Override - public ActiveMQBuffer createTransportBuffer(int size) - { + public ActiveMQBuffer createTransportBuffer(int size) { return ActiveMQBuffers.dynamicBuffer(size); } @Override - public void fail(ActiveMQException me) - { - if (me != null) - { + public void fail(ActiveMQException me) { + if (me != null) { ActiveMQServerLogger.LOGGER.connectionFailureDetected(me.getMessage(), me.getType()); } @@ -457,64 +404,53 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor } @Override - public void destroy() - { + public void destroy() { destroyed = true; transportConnection.close(); - try - { + try { deleteTempQueues(); } - catch (Exception e) - { + catch (Exception e) { //log warning } - synchronized (sendLock) - { + synchronized (sendLock) { callClosingListeners(); } } - private void deleteTempQueues() throws Exception - { + private void deleteTempQueues() throws Exception { Iterator queueNames = tempQueues.iterator(); - while (queueNames.hasNext()) - { + while (queueNames.hasNext()) { String q = queueNames.next(); protocolManager.deleteQueue(q); } } @Override - public Connection getTransportConnection() - { + public Connection getTransportConnection() { return this.transportConnection; } @Override - public boolean isClient() - { + public boolean isClient() { return false; } @Override - public boolean isDestroyed() - { + public boolean isDestroyed() { return destroyed; } @Override - public void disconnect(boolean criticalError) - { + public void disconnect(boolean criticalError) { fail(null); } @Override - public boolean checkDataReceived() - { + public boolean checkDataReceived() { boolean res = dataReceived; dataReceived = false; @@ -523,23 +459,17 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor } @Override - public void flush() - { + public void flush() { } - private void callFailureListeners(final ActiveMQException me) - { - final List listenersClone = new ArrayList( - failureListeners); + private void callFailureListeners(final ActiveMQException me) { + final List listenersClone = new ArrayList(failureListeners); - for (final FailureListener listener : listenersClone) - { - try - { + for (final FailureListener listener : listenersClone) { + try { listener.connectionFailed(me, false); } - catch (final Throwable t) - { + catch (final Throwable t) { // Failure of one listener to execute shouldn't prevent others // from // executing @@ -548,19 +478,14 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor } } - private void callClosingListeners() - { - final List listenersClone = new ArrayList( - closeListeners); + private void callClosingListeners() { + final List listenersClone = new ArrayList(closeListeners); - for (final CloseListener listener : listenersClone) - { - try - { + for (final CloseListener listener : listenersClone) { + try { listener.connectionClosed(); } - catch (final Throwable t) - { + catch (final Throwable t) { // Failure of one listener to execute shouldn't prevent others // from // executing @@ -570,47 +495,38 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor } // throw a WireFormatInfo to the peer - public void init() - { + public void init() { WireFormatInfo info = wireFormat.getPreferedWireFormatInfo(); protocolManager.send(this, info); } - public ConnectionState getState() - { + public ConnectionState getState() { return state; } - public void physicalSend(Command command) throws IOException - { - try - { + public void physicalSend(Command command) throws IOException { + try { ByteSequence bytes = wireFormat.marshal(command); ActiveMQBuffer buffer = OpenWireUtil.toActiveMQBuffer(bytes); - synchronized (sendLock) - { + synchronized (sendLock) { getTransportConnection().write(buffer, false, false); } } - catch (IOException e) - { + catch (IOException e) { throw e; } - catch (Throwable t) - { + catch (Throwable t) { ActiveMQServerLogger.LOGGER.error("error sending", t); } } @Override - public Response processAddConnection(ConnectionInfo info) throws Exception - { + public Response processAddConnection(ConnectionInfo info) throws Exception { WireFormatInfo wireFormatInfo = wireFormat.getPreferedWireFormatInfo(); // Older clients should have been defaulting this field to true.. but // they were not. - if (wireFormatInfo != null && wireFormatInfo.getVersion() <= 2) - { + if (wireFormatInfo != null && wireFormatInfo.getVersion() <= 2) { info.setClientMaster(true); } @@ -620,7 +536,6 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor state.reset(info); - this.faultTolerantConnection = info.isFaultTolerant(); // Setup the context. String clientId = info.getClientId(); @@ -635,43 +550,33 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor context.setMessageAuthorizationPolicy(getMessageAuthorizationPolicy()); context.setNetworkConnection(networkConnection); context.setFaultTolerant(faultTolerantConnection); - context - .setTransactions(new ConcurrentHashMap()); + context.setTransactions(new ConcurrentHashMap()); context.setUserName(info.getUserName()); context.setWireFormatInfo(wireFormatInfo); context.setReconnect(info.isFailoverReconnect()); this.manageable = info.isManageable(); context.setConnectionState(state); - if (info.getClientIp() == null) - { + if (info.getClientIp() == null) { info.setClientIp(getRemoteAddress()); } - try - { + try { protocolManager.addConnection(context, info); } - catch (Exception e) - { - if (e instanceof SecurityException) - { + catch (Exception e) { + if (e instanceof SecurityException) { // close this down - in case the peer of this transport doesn't play // nice - delayedStop(2000, - "Failed with SecurityException: " + e.getLocalizedMessage(), - e); + delayedStop(2000, "Failed with SecurityException: " + e.getLocalizedMessage(), e); } Response resp = new ExceptionResponse(e); return resp; } - if (info.isManageable()) - { + if (info.isManageable()) { // send ConnectionCommand ConnectionControl command = this.acceptorUsed.getConnectionControl(); - command.setFaultTolerant(protocolManager - .isFaultTolerantConfiguration()); - if (info.isFailoverReconnect()) - { + command.setFaultTolerant(protocolManager.isFaultTolerantConfiguration()); + if (info.isFailoverReconnect()) { command.setRebalanceConnection(false); } dispatchAsync(command); @@ -679,86 +584,65 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor return null; } - public void dispatchAsync(Command message) - { - if (!stopping.get()) - { - if (taskRunner == null) - { + public void dispatchAsync(Command message) { + if (!stopping.get()) { + if (taskRunner == null) { dispatchSync(message); } - else - { - synchronized (dispatchQueue) - { + else { + synchronized (dispatchQueue) { dispatchQueue.add(message); } - try - { + try { taskRunner.wakeup(); } - catch (InterruptedException e) - { + catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } - else - { - if (message.isMessageDispatch()) - { + else { + if (message.isMessageDispatch()) { MessageDispatch md = (MessageDispatch) message; TransmitCallback sub = md.getTransmitCallback(); protocolManager.postProcessDispatch(md); - if (sub != null) - { + if (sub != null) { sub.onFailure(); } } } } - public void dispatchSync(Command message) - { - try - { + public void dispatchSync(Command message) { + try { processDispatch(message); } - catch (IOException e) - { + catch (IOException e) { serviceExceptionAsync(e); } } - public void serviceExceptionAsync(final IOException e) - { - if (asyncException.compareAndSet(false, true)) - { - new Thread("Async Exception Handler") - { + public void serviceExceptionAsync(final IOException e) { + if (asyncException.compareAndSet(false, true)) { + new Thread("Async Exception Handler") { @Override - public void run() - { + public void run() { serviceException(e); } }.start(); } } - public void serviceException(Throwable e) - { + public void serviceException(Throwable e) { // are we a transport exception such as not being able to dispatch // synchronously to a transport - if (e instanceof IOException) - { + if (e instanceof IOException) { serviceTransportException((IOException) e); } - else if (e.getClass() == AMQBrokerStoppedException.class) - { + else if (e.getClass() == AMQBrokerStoppedException.class) { // Handle the case where the broker is stopped // But the client is still connected. - if (!stopping.get()) - { + if (!stopping.get()) { ConnectionError ce = new ConnectionError(); ce.setException(e); dispatchSync(ce); @@ -766,12 +650,10 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor this.stopError = e; // Wait a little bit to try to get the output buffer to flush // the exception notification to the client. - try - { + try { Thread.sleep(500); } - catch (InterruptedException ie) - { + catch (InterruptedException ie) { Thread.currentThread().interrupt(); } // Worst case is we just kill the connection before the @@ -779,31 +661,25 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor stopAsync(); } } - else if (!stopping.get() && !inServiceException) - { + else if (!stopping.get() && !inServiceException) { inServiceException = true; - try - { + try { ConnectionError ce = new ConnectionError(); ce.setException(e); - if (pendingStop) - { + if (pendingStop) { dispatchSync(ce); } - else - { + else { dispatchAsync(ce); } } - finally - { + finally { inServiceException = false; } } } - public void serviceTransportException(IOException e) - { + public void serviceTransportException(IOException e) { /* * deal with it later BrokerService bService = * connector.getBrokerService(); if (bService.isShutdownOnSlaveFailure()) @@ -818,164 +694,124 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor */ } - public void setMarkedCandidate(boolean markedCandidate) - { + public void setMarkedCandidate(boolean markedCandidate) { this.markedCandidate = markedCandidate; - if (!markedCandidate) - { + if (!markedCandidate) { timeStamp = 0; blockedCandidate = false; } } - protected void dispatch(Command command) throws IOException - { - try - { + protected void dispatch(Command command) throws IOException { + try { setMarkedCandidate(true); this.physicalSend(command); } - finally - { + finally { setMarkedCandidate(false); } } - protected void processDispatch(Command command) throws IOException - { - MessageDispatch messageDispatch = (MessageDispatch) (command - .isMessageDispatch() ? command : null); - try - { - if (!stopping.get()) - { - if (messageDispatch != null) - { + protected void processDispatch(Command command) throws IOException { + MessageDispatch messageDispatch = (MessageDispatch) (command.isMessageDispatch() ? command : null); + try { + if (!stopping.get()) { + if (messageDispatch != null) { protocolManager.preProcessDispatch(messageDispatch); } dispatch(command); } } - catch (IOException e) - { - if (messageDispatch != null) - { + catch (IOException e) { + if (messageDispatch != null) { TransmitCallback sub = messageDispatch.getTransmitCallback(); protocolManager.postProcessDispatch(messageDispatch); - if (sub != null) - { + if (sub != null) { sub.onFailure(); } messageDispatch = null; throw e; } } - finally - { - if (messageDispatch != null) - { + finally { + if (messageDispatch != null) { TransmitCallback sub = messageDispatch.getTransmitCallback(); protocolManager.postProcessDispatch(messageDispatch); - if (sub != null) - { + if (sub != null) { sub.onSuccess(); } } } } - private AMQMessageAuthorizationPolicy getMessageAuthorizationPolicy() - { + private AMQMessageAuthorizationPolicy getMessageAuthorizationPolicy() { return this.messageAuthorizationPolicy; } - public void delayedStop(final int waitTime, final String reason, - Throwable cause) - { - if (waitTime > 0) - { - synchronized (this) - { + public void delayedStop(final int waitTime, final String reason, Throwable cause) { + if (waitTime > 0) { + synchronized (this) { pendingStop = true; stopError = cause; } - try - { - stopTaskRunnerFactory.execute(new Runnable() - { + try { + stopTaskRunnerFactory.execute(new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { Thread.sleep(waitTime); stopAsync(); } - catch (InterruptedException e) - { + catch (InterruptedException e) { } } }); } - catch (Throwable t) - { + catch (Throwable t) { // log error } } } - public void stopAsync() - { + public void stopAsync() { // If we're in the middle of starting then go no further... for now. - synchronized (this) - { + synchronized (this) { pendingStop = true; - if (starting) - { + if (starting) { // log return; } } - if (stopping.compareAndSet(false, true)) - { - if (context != null) - { + if (stopping.compareAndSet(false, true)) { + if (context != null) { context.getStopping().set(true); } - try - { - stopTaskRunnerFactory.execute(new Runnable() - { + try { + stopTaskRunnerFactory.execute(new Runnable() { @Override - public void run() - { + public void run() { serviceLock.writeLock().lock(); - try - { + try { doStop(); } - catch (Throwable e) - { + catch (Throwable e) { // LOG } - finally - { + finally { stopped.countDown(); serviceLock.writeLock().unlock(); } } }); } - catch (Throwable t) - { + catch (Throwable t) { // LOG stopped.countDown(); } } } - protected void doStop() throws Exception - { + protected void doStop() throws Exception { this.acceptorUsed.onStopped(this); /* * What's a duplex bridge? try { synchronized (this) { if (duplexBridge != @@ -983,17 +819,14 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor * LOG.trace("Exception caught stopping. This exception is ignored.", * ignore); } */ - try - { + try { getTransportConnection().close(); } - catch (Exception e) - { + catch (Exception e) { // log } - if (taskRunner != null) - { + if (taskRunner != null) { taskRunner.shutdown(1); taskRunner = null; } @@ -1001,18 +834,14 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor active = false; // Run the MessageDispatch callbacks so that message references get // cleaned up. - synchronized (dispatchQueue) - { - for (Iterator iter = dispatchQueue.iterator(); iter.hasNext();) - { + synchronized (dispatchQueue) { + for (Iterator iter = dispatchQueue.iterator(); iter.hasNext(); ) { Command command = iter.next(); - if (command.isMessageDispatch()) - { + if (command.isMessageDispatch()) { MessageDispatch md = (MessageDispatch) command; TransmitCallback sub = md.getTransmitCallback(); protocolManager.postProcessDispatch(md); - if (sub != null) - { + if (sub != null) { sub.onFailure(); } } @@ -1022,70 +851,54 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor // // Remove all logical connection associated with this connection // from the broker. - if (!protocolManager.isStopped()) - { + if (!protocolManager.isStopped()) { context.getStopping().set(true); - try - { + try { processRemoveConnection(state.getInfo().getConnectionId(), 0L); } - catch (Throwable ignore) - { + catch (Throwable ignore) { ignore.printStackTrace(); } } } @Override - public Response processAddConsumer(ConsumerInfo info) - { + public Response processAddConsumer(ConsumerInfo info) { Response resp = null; - try - { + try { protocolManager.addConsumer(this, info); } - catch (Exception e) - { - if (e instanceof ActiveMQSecurityException) - { + catch (Exception e) { + if (e instanceof ActiveMQSecurityException) { resp = new ExceptionResponse(new JMSSecurityException(e.getMessage())); } - else - { + else { resp = new ExceptionResponse(e); } } return resp; } - public void addConsumerBrokerExchange(ConsumerId id, AMQSession amqSession, Map consumerMap) - { + public void addConsumerBrokerExchange(ConsumerId id, + AMQSession amqSession, + Map consumerMap) { AMQConsumerBrokerExchange result = consumerExchanges.get(id); - if (result == null) - { - if (consumerMap.size() == 1) - { + if (result == null) { + if (consumerMap.size() == 1) { result = new AMQSingleConsumerBrokerExchange(amqSession, consumerMap.values().iterator().next()); } - else - { + else { result = new AMQCompositeConsumerBrokerExchange(amqSession, consumerMap); } - synchronized (consumerExchanges) - { + synchronized (consumerExchanges) { result.setConnectionContext(context); SessionState ss = state.getSessionState(id.getParentId()); - if (ss != null) - { + if (ss != null) { ConsumerState cs = ss.getConsumerState(id); - if (cs != null) - { + if (cs != null) { ConsumerInfo info = cs.getInfo(); - if (info != null) - { - if (info.getDestination() != null - && info.getDestination().isPattern()) - { + if (info != null) { + if (info.getDestination() != null && info.getDestination().isPattern()) { result.setWildcard(true); } } @@ -1096,28 +909,22 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor } } - public int getConsumerCount() - { + public int getConsumerCount() { int result = 0; - for (SessionId sessionId : state.getSessionIds()) - { + for (SessionId sessionId : state.getSessionIds()) { SessionState sessionState = state.getSessionState(sessionId); - if (sessionState != null) - { + if (sessionState != null) { result += sessionState.getConsumerIds().size(); } } return result; } - public int getProducerCount() - { + public int getProducerCount() { int result = 0; - for (SessionId sessionId : state.getSessionIds()) - { + for (SessionId sessionId : state.getSessionIds()) { SessionState sessionState = state.getSessionState(sessionId); - if (sessionState != null) - { + if (sessionState != null) { result += sessionState.getProducerIds().size(); } } @@ -1125,21 +932,16 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor } @Override - public Response processAddDestination(DestinationInfo dest) throws Exception - { + public Response processAddDestination(DestinationInfo dest) throws Exception { Response resp = null; - try - { + try { protocolManager.addDestination(this, dest); } - catch (Exception e) - { - if (e instanceof ActiveMQSecurityException) - { + catch (Exception e) { + if (e instanceof ActiveMQSecurityException) { resp = new ExceptionResponse(new JMSSecurityException(e.getMessage())); } - else - { + else { resp = new ExceptionResponse(e); } } @@ -1147,25 +949,19 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor } @Override - public Response processAddProducer(ProducerInfo info) throws Exception - { + public Response processAddProducer(ProducerInfo info) throws Exception { Response resp = null; - try - { + try { protocolManager.addProducer(this, info); } - catch (Exception e) - { - if (e instanceof ActiveMQSecurityException) - { + catch (Exception e) { + if (e instanceof ActiveMQSecurityException) { resp = new ExceptionResponse(new JMSSecurityException(e.getMessage())); } - else if (e instanceof ActiveMQNonExistentQueueException) - { + else if (e instanceof ActiveMQNonExistentQueueException) { resp = new ExceptionResponse(new InvalidDestinationException(e.getMessage())); } - else - { + else { resp = new ExceptionResponse(e); } } @@ -1173,18 +969,14 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor } @Override - public Response processAddSession(SessionInfo info) throws Exception - { + public Response processAddSession(SessionInfo info) throws Exception { // Avoid replaying dup commands - if (!state.getSessionIds().contains(info.getSessionId())) - { + if (!state.getSessionIds().contains(info.getSessionId())) { protocolManager.addSession(this, info); - try - { + try { state.addSession(info); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { e.printStackTrace(); protocolManager.removeSession(context, info); } @@ -1193,26 +985,22 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor } @Override - public Response processBeginTransaction(TransactionInfo info) throws Exception - { + public Response processBeginTransaction(TransactionInfo info) throws Exception { TransactionId txId = info.getTransactionId(); - if (!txMap.containsKey(txId)) - { + if (!txMap.containsKey(txId)) { txMap.put(txId, info); } return null; } @Override - public Response processBrokerInfo(BrokerInfo arg0) throws Exception - { + public Response processBrokerInfo(BrokerInfo arg0) throws Exception { throw new IllegalStateException("not implemented! "); } @Override - public Response processCommitTransactionOnePhase(TransactionInfo info) throws Exception - { + public Response processCommitTransactionOnePhase(TransactionInfo info) throws Exception { protocolManager.commitTransactionOnePhase(info); TransactionId txId = info.getTransactionId(); txMap.remove(txId); @@ -1221,8 +1009,7 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor } @Override - public Response processCommitTransactionTwoPhase(TransactionInfo info) throws Exception - { + public Response processCommitTransactionTwoPhase(TransactionInfo info) throws Exception { protocolManager.commitTransactionTwoPhase(info); TransactionId txId = info.getTransactionId(); txMap.remove(txId); @@ -1231,51 +1018,43 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor } @Override - public Response processConnectionControl(ConnectionControl arg0) throws Exception - { + public Response processConnectionControl(ConnectionControl arg0) throws Exception { throw new IllegalStateException("not implemented! "); } @Override - public Response processConnectionError(ConnectionError arg0) throws Exception - { + public Response processConnectionError(ConnectionError arg0) throws Exception { throw new IllegalStateException("not implemented! "); } @Override - public Response processConsumerControl(ConsumerControl arg0) throws Exception - { + public Response processConsumerControl(ConsumerControl arg0) throws Exception { throw new IllegalStateException("not implemented! "); } @Override - public Response processControlCommand(ControlCommand arg0) throws Exception - { + public Response processControlCommand(ControlCommand arg0) throws Exception { throw new IllegalStateException("not implemented! "); } @Override - public Response processEndTransaction(TransactionInfo info) throws Exception - { + public Response processEndTransaction(TransactionInfo info) throws Exception { protocolManager.endTransaction(info); TransactionId txId = info.getTransactionId(); - if (!txMap.containsKey(txId)) - { + if (!txMap.containsKey(txId)) { txMap.put(txId, info); } return null; } @Override - public Response processFlush(FlushCommand arg0) throws Exception - { + public Response processFlush(FlushCommand arg0) throws Exception { throw new IllegalStateException("not implemented! "); } @Override - public Response processForgetTransaction(TransactionInfo info) throws Exception - { + public Response processForgetTransaction(TransactionInfo info) throws Exception { TransactionId txId = info.getTransactionId(); txMap.remove(txId); @@ -1284,102 +1063,76 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor } @Override - public Response processKeepAlive(KeepAliveInfo arg0) throws Exception - { + public Response processKeepAlive(KeepAliveInfo arg0) throws Exception { throw new IllegalStateException("not implemented! "); } @Override - public Response processMessage(Message messageSend) - { + public Response processMessage(Message messageSend) { Response resp = null; - try - { + try { ProducerId producerId = messageSend.getProducerId(); AMQProducerBrokerExchange producerExchange = getProducerBrokerExchange(producerId); final AMQConnectionContext pcontext = producerExchange.getConnectionContext(); final ProducerInfo producerInfo = producerExchange.getProducerState().getInfo(); - boolean sendProducerAck = !messageSend.isResponseRequired() && producerInfo.getWindowSize() > 0 - && !pcontext.isInRecoveryMode(); + boolean sendProducerAck = !messageSend.isResponseRequired() && producerInfo.getWindowSize() > 0 && !pcontext.isInRecoveryMode(); AMQSession session = protocolManager.getSession(producerId.getParentId()); - if (producerExchange.canDispatch(messageSend)) - { + if (producerExchange.canDispatch(messageSend)) { SendingResult result = session.send(producerExchange, messageSend, sendProducerAck); - if (result.isBlockNextSend()) - { - if (!context.isNetworkConnection() && result.isSendFailIfNoSpace()) - { - throw new ResourceAllocationException("Usage Manager Memory Limit reached. Stopping producer (" - + producerId + ") to prevent flooding " - + result.getBlockingAddress() + "." - + " See http://activemq.apache.org/producer-flow-control.html for more info"); + if (result.isBlockNextSend()) { + if (!context.isNetworkConnection() && result.isSendFailIfNoSpace()) { + throw new ResourceAllocationException("Usage Manager Memory Limit reached. Stopping producer (" + producerId + ") to prevent flooding " + result.getBlockingAddress() + "." + " See http://activemq.apache.org/producer-flow-control.html for more info"); } - if (producerInfo.getWindowSize() > 0 || messageSend.isResponseRequired()) - { + if (producerInfo.getWindowSize() > 0 || messageSend.isResponseRequired()) { //in that case don't send the response //this will force the client to wait until //the response is got. context.setDontSendReponse(true); } - else - { + else { //hang the connection until the space is available session.blockingWaitForSpace(producerExchange, result); } } - else if (sendProducerAck) - { + else if (sendProducerAck) { ProducerAck ack = new ProducerAck(producerInfo.getProducerId(), messageSend.getSize()); this.dispatchAsync(ack); } } } - catch (Exception e) - { - if (e instanceof ActiveMQSecurityException) - { + catch (Exception e) { + if (e instanceof ActiveMQSecurityException) { resp = new ExceptionResponse(new JMSSecurityException(e.getMessage())); } - else - { + else { resp = new ExceptionResponse(e); } } return resp; } - private AMQProducerBrokerExchange getProducerBrokerExchange(ProducerId id) throws IOException - { + private AMQProducerBrokerExchange getProducerBrokerExchange(ProducerId id) throws IOException { AMQProducerBrokerExchange result = producerExchanges.get(id); - if (result == null) - { - synchronized (producerExchanges) - { + if (result == null) { + synchronized (producerExchanges) { result = new AMQProducerBrokerExchange(); result.setConnectionContext(context); //todo implement reconnect https://issues.apache.org/jira/browse/ARTEMIS-194 - if (context.isReconnect() - || (context.isNetworkConnection() && this.acceptorUsed - .isAuditNetworkProducers())) - { - if (protocolManager.getPersistenceAdapter() != null) - { + if (context.isReconnect() || (context.isNetworkConnection() && this.acceptorUsed.isAuditNetworkProducers())) { + if (protocolManager.getPersistenceAdapter() != null) { result.setLastStoredSequenceId(protocolManager.getPersistenceAdapter().getLastProducerSequenceId(id)); } } SessionState ss = state.getSessionState(id.getParentId()); - if (ss != null) - { + if (ss != null) { result.setProducerState(ss.getProducerState(id)); ProducerState producerState = ss.getProducerState(id); - if (producerState != null && producerState.getInfo() != null) - { + if (producerState != null && producerState.getInfo() != null) { ProducerInfo info = producerState.getInfo(); - result.setMutable(info.getDestination() == null - || info.getDestination().isComposite()); + result.setMutable(info.getDestination() == null || info.getDestination().isComposite()); } } producerExchanges.put(id, result); @@ -1389,32 +1142,26 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor } @Override - public Response processMessageAck(MessageAck ack) throws Exception - { + public Response processMessageAck(MessageAck ack) throws Exception { AMQConsumerBrokerExchange consumerBrokerExchange = consumerExchanges.get(ack.getConsumerId()); consumerBrokerExchange.acknowledge(ack); return null; } @Override - public Response processMessageDispatch(MessageDispatch arg0) throws Exception - { + public Response processMessageDispatch(MessageDispatch arg0) throws Exception { throw new IllegalStateException("not implemented! "); } @Override - public Response processMessageDispatchNotification( - MessageDispatchNotification arg0) throws Exception - { + public Response processMessageDispatchNotification(MessageDispatchNotification arg0) throws Exception { throw new IllegalStateException("not implemented! "); } @Override - public Response processMessagePull(MessagePull arg0) throws Exception - { + public Response processMessagePull(MessagePull arg0) throws Exception { AMQConsumerBrokerExchange amqConsumerBrokerExchange = consumerExchanges.get(arg0.getConsumerId()); - if (amqConsumerBrokerExchange == null) - { + if (amqConsumerBrokerExchange == null) { throw new IllegalStateException("Consumer does not exist"); } amqConsumerBrokerExchange.processMessagePull(arg0); @@ -1422,75 +1169,57 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor } @Override - public Response processPrepareTransaction(TransactionInfo info) throws Exception - { + public Response processPrepareTransaction(TransactionInfo info) throws Exception { protocolManager.prepareTransaction(info); return null; } @Override - public Response processProducerAck(ProducerAck arg0) throws Exception - { + public Response processProducerAck(ProducerAck arg0) throws Exception { throw new IllegalStateException("not implemented! "); } @Override - public Response processRecoverTransactions(TransactionInfo info) throws Exception - { + public Response processRecoverTransactions(TransactionInfo info) throws Exception { Set sIds = state.getSessionIds(); TransactionId[] recovered = protocolManager.recoverTransactions(sIds); return new DataArrayResponse(recovered); } @Override - public Response processRemoveConnection(ConnectionId id, - long lastDeliveredSequenceId) throws Exception - { + public Response processRemoveConnection(ConnectionId id, long lastDeliveredSequenceId) throws Exception { // Don't allow things to be added to the connection state while we // are shutting down. state.shutdown(); // Cascade the connection stop to the sessions. - for (SessionId sessionId : state.getSessionIds()) - { - try - { + for (SessionId sessionId : state.getSessionIds()) { + try { processRemoveSession(sessionId, lastDeliveredSequenceId); } - catch (Throwable e) - { + catch (Throwable e) { // LOG } } - try - { - protocolManager.removeConnection(context, state.getInfo(), - null); + try { + protocolManager.removeConnection(context, state.getInfo(), null); } - catch (Throwable e) - { + catch (Throwable e) { // log } return null; } @Override - public Response processRemoveConsumer(ConsumerId id, - long lastDeliveredSequenceId) throws Exception - { + public Response processRemoveConsumer(ConsumerId id, long lastDeliveredSequenceId) throws Exception { SessionId sessionId = id.getParentId(); SessionState ss = state.getSessionState(sessionId); - if (ss == null) - { - throw new IllegalStateException( - "Cannot remove a consumer from a session that had not been registered: " - + sessionId); + if (ss == null) { + throw new IllegalStateException("Cannot remove a consumer from a session that had not been registered: " + sessionId); } ConsumerState consumerState = ss.removeConsumer(id); - if (consumerState == null) - { - throw new IllegalStateException( - "Cannot remove a consumer that had not been registered: " + id); + if (consumerState == null) { + throw new IllegalStateException("Cannot remove a consumer that had not been registered: " + id); } ConsumerInfo info = consumerState.getInfo(); info.setLastDeliveredSequenceId(lastDeliveredSequenceId); @@ -1504,20 +1233,16 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor return null; } - private void removeConsumerBrokerExchange(ConsumerId id) - { - synchronized (consumerExchanges) - { + private void removeConsumerBrokerExchange(ConsumerId id) { + synchronized (consumerExchanges) { consumerExchanges.remove(id); } } @Override - public Response processRemoveDestination(DestinationInfo info) throws Exception - { + public Response processRemoveDestination(DestinationInfo info) throws Exception { ActiveMQDestination dest = info.getDestination(); - if (dest.isQueue()) - { + if (dest.isQueue()) { String qName = "jms.queue." + dest.getPhysicalName(); protocolManager.deleteQueue(qName); } @@ -1525,45 +1250,34 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor } @Override - public Response processRemoveProducer(ProducerId id) throws Exception - { + public Response processRemoveProducer(ProducerId id) throws Exception { protocolManager.removeProducer(id); return null; } @Override - public Response processRemoveSession(SessionId id, - long lastDeliveredSequenceId) throws Exception - { + public Response processRemoveSession(SessionId id, long lastDeliveredSequenceId) throws Exception { SessionState session = state.getSessionState(id); - if (session == null) - { - throw new IllegalStateException( - "Cannot remove session that had not been registered: " + id); + if (session == null) { + throw new IllegalStateException("Cannot remove session that had not been registered: " + id); } // Don't let new consumers or producers get added while we are closing // this down. session.shutdown(); // Cascade the connection stop to the consumers and producers. - for (ConsumerId consumerId : session.getConsumerIds()) - { - try - { + for (ConsumerId consumerId : session.getConsumerIds()) { + try { processRemoveConsumer(consumerId, lastDeliveredSequenceId); } - catch (Throwable e) - { + catch (Throwable e) { // LOG.warn("Failed to remove consumer: {}", consumerId, e); } } - for (ProducerId producerId : session.getProducerIds()) - { - try - { + for (ProducerId producerId : session.getProducerIds()) { + try { processRemoveProducer(producerId); } - catch (Throwable e) - { + catch (Throwable e) { // LOG.warn("Failed to remove producer: {}", producerId, e); } } @@ -1573,15 +1287,13 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor } @Override - public Response processRemoveSubscription(RemoveSubscriptionInfo subInfo) throws Exception - { + public Response processRemoveSubscription(RemoveSubscriptionInfo subInfo) throws Exception { protocolManager.removeSubscription(subInfo); return null; } @Override - public Response processRollbackTransaction(TransactionInfo info) throws Exception - { + public Response processRollbackTransaction(TransactionInfo info) throws Exception { protocolManager.rollbackTransaction(info); TransactionId txId = info.getTransactionId(); txMap.remove(txId); @@ -1589,32 +1301,26 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor } @Override - public Response processShutdown(ShutdownInfo info) throws Exception - { + public Response processShutdown(ShutdownInfo info) throws Exception { return null; } @Override - public Response processWireFormat(WireFormatInfo arg0) throws Exception - { + public Response processWireFormat(WireFormatInfo arg0) throws Exception { throw new IllegalStateException("not implemented! "); } - public int getMaximumConsumersAllowedPerConnection() - { + public int getMaximumConsumersAllowedPerConnection() { return this.acceptorUsed.getMaximumConsumersAllowedPerConnection(); } - public int getMaximumProducersAllowedPerConnection() - { + public int getMaximumProducersAllowedPerConnection() { return this.acceptorUsed.getMaximumProducersAllowedPerConnection(); } - public void deliverMessage(MessageDispatch dispatch) - { + public void deliverMessage(MessageDispatch dispatch) { Message m = dispatch.getMessage(); - if (m != null) - { + if (m != null) { long endTime = System.currentTimeMillis(); m.setBrokerOutTime(endTime); } @@ -1622,40 +1328,33 @@ public class OpenWireConnection implements RemotingConnection, CommandVisitor protocolManager.send(this, dispatch); } - public WireFormat getMarshaller() - { + public WireFormat getMarshaller() { return this.wireFormat; } - public void registerTempQueue(SimpleString qName) - { + public void registerTempQueue(SimpleString qName) { tempQueues.add(qName.toString()); } @Override - public void disconnect(String reason, boolean fail) - { + public void disconnect(String reason, boolean fail) { destroy(); } @Override - public void fail(ActiveMQException e, String message) - { + public void fail(ActiveMQException e, String message) { destroy(); } - public void setAdvisorySession(AMQSession amqSession) - { + public void setAdvisorySession(AMQSession amqSession) { this.advisorySession = amqSession; } - public AMQSession getAdvisorySession() - { + public AMQSession getAdvisorySession() { return this.advisorySession; } - public AMQConnectionContext getConext() - { + public AMQConnectionContext getConext() { return this.context; } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/OpenWireMessageConverter.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/OpenWireMessageConverter.java index ce94ee2d32..260ee026a4 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/OpenWireMessageConverter.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/OpenWireMessageConverter.java @@ -60,8 +60,8 @@ import org.apache.activemq.artemis.utils.DataConstants; import org.apache.activemq.artemis.utils.TypedProperties; import org.apache.activemq.artemis.utils.UUIDGenerator; -public class OpenWireMessageConverter implements MessageConverter -{ +public class OpenWireMessageConverter implements MessageConverter { + public static final String AMQ_PREFIX = "__HDR_"; public static final String AMQ_MSG_DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY = AMQ_PREFIX + "dlqDeliveryFailureCause"; @@ -91,24 +91,22 @@ public class OpenWireMessageConverter implements MessageConverter private static final String AMQ_MSG_DROPPABLE = AMQ_PREFIX + "DROPPABLE"; @Override - public ServerMessage inbound(Object message) - { + public ServerMessage inbound(Object message) { // TODO: implement this return null; } - public Object outbound(ServerMessage message, int deliveryCount) - { + public Object outbound(ServerMessage message, int deliveryCount) { // TODO: implement this return null; } //convert an ActiveMQ Artemis message to coreMessage - public static void toCoreMessage(ServerMessageImpl coreMessage, Message messageSend, WireFormat marshaller) throws IOException - { + public static void toCoreMessage(ServerMessageImpl coreMessage, + Message messageSend, + WireFormat marshaller) throws IOException { String type = messageSend.getType(); - if (type != null) - { + if (type != null) { coreMessage.putStringProperty(new SimpleString("JMSType"), new SimpleString(type)); } coreMessage.setDurable(messageSend.isPersistent()); @@ -120,11 +118,9 @@ public class OpenWireMessageConverter implements MessageConverter coreMessage.setType(coreType); ByteSequence contents = messageSend.getContent(); - if (contents != null) - { + if (contents != null) { ActiveMQBuffer body = coreMessage.getBodyBuffer(); - switch (coreType) - { + switch (coreType) { case org.apache.activemq.artemis.api.core.Message.TEXT_TYPE: ByteArrayInputStream tis = new ByteArrayInputStream(contents); DataInputStream tdataIn = new DataInputStream(tis); @@ -149,10 +145,8 @@ public class OpenWireMessageConverter implements MessageConverter InputStream sis = new ByteArrayInputStream(contents); DataInputStream sdis = new DataInputStream(sis); int stype = sdis.read(); - while (stype != -1) - { - switch (stype) - { + while (stype != -1) { + switch (stype) { case MarshallingSupport.BOOLEAN_TYPE: body.writeByte(DataConstants.BOOLEAN); body.writeBoolean(sdis.readBoolean()); @@ -172,7 +166,7 @@ public class OpenWireMessageConverter implements MessageConverter case MarshallingSupport.CHAR_TYPE: body.writeByte(DataConstants.CHAR); char schar = sdis.readChar(); - body.writeShort((short)schar); + body.writeShort((short) schar); break; case MarshallingSupport.DOUBLE_TYPE: body.writeByte(DataConstants.DOUBLE); @@ -227,28 +221,22 @@ public class OpenWireMessageConverter implements MessageConverter coreMessage.putLongProperty(AMQ_MSG_ARRIVAL, messageSend.getArrival()); coreMessage.putLongProperty(AMQ_MSG_BROKER_IN_TIME, messageSend.getBrokerInTime()); BrokerId[] brokers = messageSend.getBrokerPath(); - if (brokers != null) - { + if (brokers != null) { StringBuilder builder = new StringBuilder(); - for (int i = 0; i < brokers.length; i++) - { + for (int i = 0; i < brokers.length; i++) { builder.append(brokers[i].getValue()); - if (i != (brokers.length - 1)) - { + if (i != (brokers.length - 1)) { builder.append(","); //is this separator safe? } } coreMessage.putStringProperty(AMQ_MSG_BROKER_PATH, builder.toString()); } BrokerId[] cluster = messageSend.getCluster(); - if (cluster != null) - { + if (cluster != null) { StringBuilder builder = new StringBuilder(); - for (int i = 0; i < cluster.length; i++) - { + for (int i = 0; i < cluster.length; i++) { builder.append(cluster[i].getValue()); - if (i != (cluster.length - 1)) - { + if (i != (cluster.length - 1)) { builder.append(","); //is this separator safe? } } @@ -257,13 +245,11 @@ public class OpenWireMessageConverter implements MessageConverter coreMessage.putIntProperty(AMQ_MSG_COMMAND_ID, messageSend.getCommandId()); String corrId = messageSend.getCorrelationId(); - if (corrId != null) - { + if (corrId != null) { coreMessage.putStringProperty("JMSCorrelationID", corrId); } DataStructure ds = messageSend.getDataStructure(); - if (ds != null) - { + if (ds != null) { ByteSequence dsBytes = marshaller.marshal(ds); dsBytes.compact(); coreMessage.putBytesProperty(AMQ_MSG_DATASTRUCTURE, dsBytes.data); @@ -273,8 +259,7 @@ public class OpenWireMessageConverter implements MessageConverter destBytes.compact(); coreMessage.putBytesProperty(AMQ_MSG_DESTINATION, destBytes.data); String groupId = messageSend.getGroupID(); - if (groupId != null) - { + if (groupId != null) { coreMessage.putStringProperty(AMQ_MSG_GROUP_ID, groupId); } coreMessage.putIntProperty(AMQ_MSG_GROUP_SEQUENCE, messageSend.getGroupSequence()); @@ -286,46 +271,39 @@ public class OpenWireMessageConverter implements MessageConverter coreMessage.putBytesProperty(AMQ_MSG_MESSAGE_ID, midBytes.data); ActiveMQDestination origDest = messageSend.getOriginalDestination(); - if (origDest != null) - { + if (origDest != null) { ByteSequence origDestBytes = marshaller.marshal(origDest); origDestBytes.compact(); coreMessage.putBytesProperty(AMQ_MSG_ORIG_DESTINATION, origDestBytes.data); } TransactionId origTxId = messageSend.getOriginalTransactionId(); - if (origTxId != null) - { + if (origTxId != null) { ByteSequence origTxBytes = marshaller.marshal(origTxId); origTxBytes.compact(); coreMessage.putBytesProperty(AMQ_MSG_ORIG_TXID, origTxBytes.data); } ProducerId producerId = messageSend.getProducerId(); - if (producerId != null) - { + if (producerId != null) { ByteSequence producerIdBytes = marshaller.marshal(producerId); producerIdBytes.compact(); coreMessage.putBytesProperty(AMQ_MSG_PRODUCER_ID, producerIdBytes.data); } ByteSequence propBytes = messageSend.getMarshalledProperties(); - if (propBytes != null) - { + if (propBytes != null) { propBytes.compact(); coreMessage.putBytesProperty(AMQ_MSG_MARSHALL_PROP, propBytes.data); //unmarshall properties to core so selector will work Map props = messageSend.getProperties(); //Map props = MarshallingSupport.unmarshalPrimitiveMap(new DataInputStream(new ByteArrayInputStream(propBytes))); Iterator> iterEntries = props.entrySet().iterator(); - while (iterEntries.hasNext()) - { + while (iterEntries.hasNext()) { Entry ent = iterEntries.next(); Object value = ent.getValue(); - try - { + try { coreMessage.putObjectProperty(ent.getKey(), value); } - catch (ActiveMQPropertyConversionException e) - { + catch (ActiveMQPropertyConversionException e) { coreMessage.putStringProperty(ent.getKey(), value.toString()); } } @@ -333,8 +311,7 @@ public class OpenWireMessageConverter implements MessageConverter coreMessage.putIntProperty(AMQ_MSG_REDELIVER_COUNTER, messageSend.getRedeliveryCounter()); ActiveMQDestination replyTo = messageSend.getReplyTo(); - if (replyTo != null) - { + if (replyTo != null) { ByteSequence replyToBytes = marshaller.marshal(replyTo); replyToBytes.compact(); coreMessage.putBytesProperty(AMQ_MSG_REPLY_TO, replyToBytes.data); @@ -342,49 +319,41 @@ public class OpenWireMessageConverter implements MessageConverter ConsumerId consumerId = messageSend.getTargetConsumerId(); - if (consumerId != null) - { + if (consumerId != null) { ByteSequence consumerIdBytes = marshaller.marshal(consumerId); consumerIdBytes.compact(); coreMessage.putBytesProperty(AMQ_MSG_CONSUMER_ID, consumerIdBytes.data); } TransactionId txId = messageSend.getTransactionId(); - if (txId != null) - { + if (txId != null) { ByteSequence txIdBytes = marshaller.marshal(txId); txIdBytes.compact(); coreMessage.putBytesProperty(AMQ_MSG_TX_ID, txIdBytes.data); } String userId = messageSend.getUserID(); - if (userId != null) - { + if (userId != null) { coreMessage.putStringProperty(AMQ_MSG_USER_ID, userId); } coreMessage.putBooleanProperty(AMQ_MSG_COMPRESSED, messageSend.isCompressed()); coreMessage.putBooleanProperty(AMQ_MSG_DROPPABLE, messageSend.isDroppable()); } - private static void loadMapIntoProperties(TypedProperties props, Map map) - { + private static void loadMapIntoProperties(TypedProperties props, Map map) { Iterator> iter = map.entrySet().iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { Entry entry = iter.next(); SimpleString key = new SimpleString(entry.getKey()); Object value = entry.getValue(); - if (value instanceof UTF8Buffer) - { - value = ((UTF8Buffer)value).toString(); + if (value instanceof UTF8Buffer) { + value = ((UTF8Buffer) value).toString(); } TypedProperties.setObjectProperty(key, value, props); } } - public static byte toCoreType(byte amqType) - { - switch (amqType) - { + public static byte toCoreType(byte amqType) { + switch (amqType) { case CommandTypes.ACTIVEMQ_BLOB_MESSAGE: throw new IllegalStateException("We don't support BLOB type yet!"); case CommandTypes.ACTIVEMQ_BYTES_MESSAGE: @@ -405,8 +374,8 @@ public class OpenWireMessageConverter implements MessageConverter } public static MessageDispatch createMessageDispatch(ServerMessage message, - int deliveryCount, AMQConsumer consumer) throws IOException - { + int deliveryCount, + AMQConsumer consumer) throws IOException { ActiveMQMessage amqMessage = toAMQMessage(message, consumer.getMarshaller()); MessageDispatch md = new MessageDispatch(); @@ -419,12 +388,10 @@ public class OpenWireMessageConverter implements MessageConverter return md; } - private static ActiveMQMessage toAMQMessage(ServerMessage coreMessage, WireFormat marshaller) throws IOException - { + private static ActiveMQMessage toAMQMessage(ServerMessage coreMessage, WireFormat marshaller) throws IOException { ActiveMQMessage amqMsg = null; byte coreType = coreMessage.getType(); - switch (coreType) - { + switch (coreType) { case org.apache.activemq.artemis.api.core.Message.BYTES_TYPE: amqMsg = new ActiveMQBytesMessage(); break; @@ -448,8 +415,7 @@ public class OpenWireMessageConverter implements MessageConverter } String type = coreMessage.getStringProperty(new SimpleString("JMSType")); - if (type != null) - { + if (type != null) { amqMsg.setJMSType(type); } amqMsg.setPersistent(coreMessage.isDurable()); @@ -458,25 +424,20 @@ public class OpenWireMessageConverter implements MessageConverter amqMsg.setTimestamp(coreMessage.getTimestamp()); Long brokerInTime = (Long) coreMessage.getObjectProperty(AMQ_MSG_BROKER_IN_TIME); - if (brokerInTime == null) - { + if (brokerInTime == null) { brokerInTime = 0L; } amqMsg.setBrokerInTime(brokerInTime); ActiveMQBuffer buffer = coreMessage.getBodyBuffer(); - if (buffer != null) - { + if (buffer != null) { buffer.resetReaderIndex(); byte[] bytes = null; - synchronized (buffer) - { - if (coreType == org.apache.activemq.artemis.api.core.Message.TEXT_TYPE) - { + synchronized (buffer) { + if (coreType == org.apache.activemq.artemis.api.core.Message.TEXT_TYPE) { SimpleString text = buffer.readNullableSimpleString(); - if (text != null) - { + if (text != null) { ByteArrayOutputStream out = new ByteArrayOutputStream(text.length() + 4); DataOutputStream dataOut = new DataOutputStream(out); MarshallingSupport.writeUTF8(dataOut, text.toString()); @@ -484,8 +445,7 @@ public class OpenWireMessageConverter implements MessageConverter out.close(); } } - else if (coreType == org.apache.activemq.artemis.api.core.Message.MAP_TYPE) - { + else if (coreType == org.apache.activemq.artemis.api.core.Message.MAP_TYPE) { TypedProperties mapData = new TypedProperties(); mapData.decode(buffer); @@ -496,23 +456,19 @@ public class OpenWireMessageConverter implements MessageConverter bytes = out.toByteArray(); dataOut.close(); } - else if (coreType == org.apache.activemq.artemis.api.core.Message.OBJECT_TYPE) - { + else if (coreType == org.apache.activemq.artemis.api.core.Message.OBJECT_TYPE) { int len = buffer.readInt(); bytes = new byte[len]; buffer.readBytes(bytes); } - else if (coreType == org.apache.activemq.artemis.api.core.Message.STREAM_TYPE) - { + else if (coreType == org.apache.activemq.artemis.api.core.Message.STREAM_TYPE) { ByteArrayOutputStream out = new ByteArrayOutputStream(buffer.readableBytes()); DataOutputStream dataOut = new DataOutputStream(out); boolean stop = false; - while (!stop && buffer.readable()) - { + while (!stop && buffer.readable()) { byte primitiveType = buffer.readByte(); - switch (primitiveType) - { + switch (primitiveType) { case DataConstants.BOOLEAN: MarshallingSupport.marshalBoolean(dataOut, buffer.readBoolean()); break; @@ -526,7 +482,7 @@ public class OpenWireMessageConverter implements MessageConverter MarshallingSupport.marshalByteArray(dataOut, bytesData); break; case DataConstants.CHAR: - char ch = (char)buffer.readShort(); + char ch = (char) buffer.readShort(); MarshallingSupport.marshalChar(dataOut, ch); break; case DataConstants.DOUBLE: @@ -548,12 +504,10 @@ public class OpenWireMessageConverter implements MessageConverter break; case DataConstants.STRING: String string = buffer.readNullableString(); - if (string == null) - { + if (string == null) { MarshallingSupport.marshalNull(dataOut); } - else - { + else { MarshallingSupport.marshalString(dataOut, string); } break; @@ -566,19 +520,17 @@ public class OpenWireMessageConverter implements MessageConverter bytes = out.toByteArray(); dataOut.close(); } - else - { + else { int n = buffer.readableBytes(); bytes = new byte[n]; buffer.readBytes(bytes); } buffer.resetReaderIndex();// this is important for topics as the buffer - // may be read multiple times + // may be read multiple times } - if (bytes != null) - { + if (bytes != null) { ByteSequence content = new ByteSequence(bytes); amqMsg.setContent(content); } @@ -587,201 +539,167 @@ public class OpenWireMessageConverter implements MessageConverter //we need check null because messages may come from other clients //and those amq specific attribute may not be set. Long arrival = (Long) coreMessage.getObjectProperty(AMQ_MSG_ARRIVAL); - if (arrival == null) - { + if (arrival == null) { //messages from other sources (like core client) may not set this prop arrival = 0L; } amqMsg.setArrival(arrival); String brokerPath = (String) coreMessage.getObjectProperty(AMQ_MSG_BROKER_PATH); - if (brokerPath != null && brokerPath.isEmpty()) - { + if (brokerPath != null && brokerPath.isEmpty()) { String[] brokers = brokerPath.split(","); BrokerId[] bids = new BrokerId[brokers.length]; - for (int i = 0; i < bids.length; i++) - { + for (int i = 0; i < bids.length; i++) { bids[i] = new BrokerId(brokers[i]); } amqMsg.setBrokerPath(bids); } String clusterPath = (String) coreMessage.getObjectProperty(AMQ_MSG_CLUSTER); - if (clusterPath != null && clusterPath.isEmpty()) - { + if (clusterPath != null && clusterPath.isEmpty()) { String[] cluster = clusterPath.split(","); BrokerId[] bids = new BrokerId[cluster.length]; - for (int i = 0; i < bids.length; i++) - { + for (int i = 0; i < bids.length; i++) { bids[i] = new BrokerId(cluster[i]); } amqMsg.setCluster(bids); } Integer commandId = (Integer) coreMessage.getObjectProperty(AMQ_MSG_COMMAND_ID); - if (commandId == null) - { + if (commandId == null) { commandId = -1; } amqMsg.setCommandId(commandId); SimpleString corrId = (SimpleString) coreMessage.getObjectProperty("JMSCorrelationID"); - if (corrId != null) - { + if (corrId != null) { amqMsg.setCorrelationId(corrId.toString()); } byte[] dsBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_DATASTRUCTURE); - if (dsBytes != null) - { + if (dsBytes != null) { ByteSequence seq = new ByteSequence(dsBytes); - DataStructure ds = (DataStructure)marshaller.unmarshal(seq); + DataStructure ds = (DataStructure) marshaller.unmarshal(seq); amqMsg.setDataStructure(ds); } byte[] destBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_DESTINATION); - if (destBytes != null) - { + if (destBytes != null) { ByteSequence seq = new ByteSequence(destBytes); ActiveMQDestination dest = (ActiveMQDestination) marshaller.unmarshal(seq); amqMsg.setDestination(dest); } Object value = coreMessage.getObjectProperty(AMQ_MSG_GROUP_ID); - if (value != null) - { + if (value != null) { String groupId = value.toString(); amqMsg.setGroupID(groupId); } Integer groupSequence = (Integer) coreMessage.getObjectProperty(AMQ_MSG_GROUP_SEQUENCE); - if (groupSequence == null) - { + if (groupSequence == null) { groupSequence = -1; } amqMsg.setGroupSequence(groupSequence); MessageId mid = null; byte[] midBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_MESSAGE_ID); - if (midBytes != null) - { + if (midBytes != null) { ByteSequence midSeq = new ByteSequence(midBytes); - mid = (MessageId)marshaller.unmarshal(midSeq); + mid = (MessageId) marshaller.unmarshal(midSeq); } - else - { + else { mid = new MessageId(UUIDGenerator.getInstance().generateStringUUID() + ":-1"); } amqMsg.setMessageId(mid); byte[] origDestBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_ORIG_DESTINATION); - if (origDestBytes != null) - { + if (origDestBytes != null) { ActiveMQDestination origDest = (ActiveMQDestination) marshaller.unmarshal(new ByteSequence(origDestBytes)); amqMsg.setOriginalDestination(origDest); } byte[] origTxIdBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_ORIG_TXID); - if (origTxIdBytes != null) - { + if (origTxIdBytes != null) { TransactionId origTxId = (TransactionId) marshaller.unmarshal(new ByteSequence(origTxIdBytes)); amqMsg.setOriginalTransactionId(origTxId); } byte[] producerIdBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_PRODUCER_ID); - if (producerIdBytes != null) - { + if (producerIdBytes != null) { ProducerId producerId = (ProducerId) marshaller.unmarshal(new ByteSequence(producerIdBytes)); amqMsg.setProducerId(producerId); } byte[] marshalledBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_MARSHALL_PROP); - if (marshalledBytes != null) - { + if (marshalledBytes != null) { amqMsg.setMarshalledProperties(new ByteSequence(marshalledBytes)); } Integer redeliveryCounter = (Integer) coreMessage.getObjectProperty(AMQ_MSG_REDELIVER_COUNTER); - if (redeliveryCounter != null) - { + if (redeliveryCounter != null) { amqMsg.setRedeliveryCounter(redeliveryCounter); } byte[] replyToBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_REPLY_TO); - if (replyToBytes != null) - { + if (replyToBytes != null) { ActiveMQDestination replyTo = (ActiveMQDestination) marshaller.unmarshal(new ByteSequence(replyToBytes)); amqMsg.setReplyTo(replyTo); } byte[] consumerIdBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_CONSUMER_ID); - if (consumerIdBytes != null) - { + if (consumerIdBytes != null) { ConsumerId consumerId = (ConsumerId) marshaller.unmarshal(new ByteSequence(consumerIdBytes)); amqMsg.setTargetConsumerId(consumerId); } byte[] txIdBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_TX_ID); - if (txIdBytes != null) - { + if (txIdBytes != null) { TransactionId txId = (TransactionId) marshaller.unmarshal(new ByteSequence(txIdBytes)); amqMsg.setTransactionId(txId); } String userId = (String) coreMessage.getObjectProperty(AMQ_MSG_USER_ID); - if (userId != null) - { + if (userId != null) { amqMsg.setUserID(userId); } Boolean isCompressed = (Boolean) coreMessage.getObjectProperty(AMQ_MSG_COMPRESSED); - if (isCompressed != null) - { + if (isCompressed != null) { amqMsg.setCompressed(isCompressed); } Boolean isDroppable = (Boolean) coreMessage.getObjectProperty(AMQ_MSG_DROPPABLE); - if (isDroppable != null) - { + if (isDroppable != null) { amqMsg.setDroppable(isDroppable); } SimpleString dlqCause = (SimpleString) coreMessage.getObjectProperty(AMQ_MSG_DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY); - if (dlqCause != null) - { - try - { + if (dlqCause != null) { + try { amqMsg.setStringProperty(ActiveMQMessage.DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY, dlqCause.toString()); } - catch (JMSException e) - { + catch (JMSException e) { throw new IOException("failure to set dlq property " + dlqCause, e); } } Set props = coreMessage.getPropertyNames(); - if (props != null) - { - for (SimpleString s : props) - { + if (props != null) { + for (SimpleString s : props) { String keyStr = s.toString(); - if (keyStr.startsWith("__AMQ") || keyStr.startsWith("__HDR_")) - { + if (keyStr.startsWith("__AMQ") || keyStr.startsWith("__HDR_")) { continue; } Object prop = coreMessage.getObjectProperty(s); - try - { - if (prop instanceof SimpleString) - { + try { + if (prop instanceof SimpleString) { amqMsg.setObjectProperty(s.toString(), prop.toString()); } - else - { + else { amqMsg.setObjectProperty(s.toString(), prop); } } - catch (JMSException e) - { + catch (JMSException e) { throw new IOException("exception setting property " + s + " : " + prop, e); } } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/OpenWireProtocolManager.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/OpenWireProtocolManager.java index 1a4386d914..10d67a1086 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/OpenWireProtocolManager.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/OpenWireProtocolManager.java @@ -93,8 +93,8 @@ import org.apache.activemq.util.IdGenerator; import org.apache.activemq.util.InetAddressUtil; import org.apache.activemq.util.LongSequenceGenerator; -public class OpenWireProtocolManager implements ProtocolManager, NotificationListener -{ +public class OpenWireProtocolManager implements ProtocolManager, NotificationListener { + private static final IdGenerator BROKER_ID_GENERATOR = new IdGenerator(); private static final IdGenerator ID_GENERATOR = new IdGenerator(); @@ -115,8 +115,7 @@ public class OpenWireProtocolManager implements ProtocolManager, No protected final ProducerId advisoryProducerId = new ProducerId(); // from broker - protected final Map brokerConnectionStates = Collections - .synchronizedMap(new HashMap()); + protected final Map brokerConnectionStates = Collections.synchronizedMap(new HashMap()); private final CopyOnWriteArrayList connections = new CopyOnWriteArrayList(); @@ -134,8 +133,7 @@ public class OpenWireProtocolManager implements ProtocolManager, No private final ScheduledExecutorService scheduledPool; - public OpenWireProtocolManager(OpenWireProtocolManagerFactory factory, ActiveMQServer server) - { + public OpenWireProtocolManager(OpenWireProtocolManagerFactory factory, ActiveMQServer server) { this.factory = factory; this.server = server; this.wireFactory = new OpenWireFormatFactory(); @@ -145,76 +143,60 @@ public class OpenWireProtocolManager implements ProtocolManager, No advisoryProducerId.setConnectionId(ID_GENERATOR.generateId()); ManagementService service = server.getManagementService(); scheduledPool = server.getScheduledPool(); - if (service != null) - { + if (service != null) { service.addNotificationListener(this); } } - - public ProtocolManagerFactory getFactory() - { + public ProtocolManagerFactory getFactory() { return factory; } - @Override - public void updateInterceptors(List incomingInterceptors, List outgoingInterceptors) - { + public void updateInterceptors(List incomingInterceptors, + List outgoingInterceptors) { // NO-OP } @Override - public ConnectionEntry createConnectionEntry(Acceptor acceptorUsed, - Connection connection) - { + public ConnectionEntry createConnectionEntry(Acceptor acceptorUsed, Connection connection) { OpenWireFormat wf = (OpenWireFormat) wireFactory.createWireFormat(); - OpenWireConnection owConn = new OpenWireConnection(acceptorUsed, - connection, this, wf); + OpenWireConnection owConn = new OpenWireConnection(acceptorUsed, connection, this, wf); owConn.init(); - return new ConnectionEntry(owConn, null, System.currentTimeMillis(), - 1 * 60 * 1000); + return new ConnectionEntry(owConn, null, System.currentTimeMillis(), 1 * 60 * 1000); } @Override - public MessageConverter getConverter() - { + public MessageConverter getConverter() { return new OpenWireMessageConverter(); } @Override - public void removeHandler(String name) - { + public void removeHandler(String name) { // TODO Auto-generated method stub } @Override - public void handleBuffer(RemotingConnection connection, ActiveMQBuffer buffer) - { + public void handleBuffer(RemotingConnection connection, ActiveMQBuffer buffer) { } @Override - public void addChannelHandlers(ChannelPipeline pipeline) - { + public void addChannelHandlers(ChannelPipeline pipeline) { // TODO Auto-generated method stub } @Override - public boolean isProtocol(byte[] array) - { - if (array.length < 8) - { - throw new IllegalArgumentException("Protocol header length changed " - + array.length); + public boolean isProtocol(byte[] array) { + if (array.length < 8) { + throw new IllegalArgumentException("Protocol header length changed " + array.length); } int start = this.prefixPacketSize ? 4 : 0; int j = 0; // type - if (array[start] != WireFormatInfo.DATA_STRUCTURE_TYPE) - { + if (array[start] != WireFormatInfo.DATA_STRUCTURE_TYPE) { return false; } start++; @@ -224,10 +206,8 @@ public class OpenWireProtocolManager implements ProtocolManager, No int useLen = remainingLen > magic.length ? magic.length : remainingLen; useLen += start; // magic - for (int i = start; i < useLen; i++) - { - if (array[i] != magic[j]) - { + for (int i = start; i < useLen; i++) { + if (array[i] != magic[j]) { return false; } j++; @@ -236,19 +216,15 @@ public class OpenWireProtocolManager implements ProtocolManager, No } @Override - public void handshake(NettyServerConnection connection, ActiveMQBuffer buffer) - { + public void handshake(NettyServerConnection connection, ActiveMQBuffer buffer) { // TODO Auto-generated method stub } - public void handleCommand(OpenWireConnection openWireConnection, - Object command) throws Exception - { + public void handleCommand(OpenWireConnection openWireConnection, Object command) throws Exception { Command amqCmd = (Command) command; byte type = amqCmd.getDataStructureType(); - switch (type) - { + switch (type) { case CommandTypes.CONNECTION_INFO: break; case CommandTypes.CONNECTION_CONTROL: @@ -267,95 +243,69 @@ public class OpenWireProtocolManager implements ProtocolManager, No } } - public void sendReply(final OpenWireConnection connection, - final Command command) - { - server.getStorageManager().afterCompleteOperations(new IOCallback() - { - public void onError(final int errorCode, final String errorMessage) - { - ActiveMQServerLogger.LOGGER.errorProcessingIOCallback(errorCode, - errorMessage); + public void sendReply(final OpenWireConnection connection, final Command command) { + server.getStorageManager().afterCompleteOperations(new IOCallback() { + public void onError(final int errorCode, final String errorMessage) { + ActiveMQServerLogger.LOGGER.errorProcessingIOCallback(errorCode, errorMessage); } - public void done() - { + public void done() { send(connection, command); } }); } - public boolean send(final OpenWireConnection connection, final Command command) - { - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + public boolean send(final OpenWireConnection connection, final Command command) { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("sending " + command); } - synchronized (connection) - { - if (connection.isDestroyed()) - { + synchronized (connection) { + if (connection.isDestroyed()) { return false; } - try - { + try { connection.physicalSend(command); } - catch (Exception e) - { + catch (Exception e) { return false; } - catch (Throwable t) - { + catch (Throwable t) { return false; } return true; } } - public void addConnection(AMQConnectionContext context, ConnectionInfo info) throws Exception - { + public void addConnection(AMQConnectionContext context, ConnectionInfo info) throws Exception { String username = info.getUserName(); String password = info.getPassword(); - if (!this.validateUser(username, password)) - { + if (!this.validateUser(username, password)) { throw new SecurityException("User name [" + username + "] or password is invalid."); } String clientId = info.getClientId(); - if (clientId == null) - { - throw new InvalidClientIDException( - "No clientID specified for connection request"); + if (clientId == null) { + throw new InvalidClientIDException("No clientID specified for connection request"); } - synchronized (clientIdSet) - { + synchronized (clientIdSet) { AMQConnectionContext oldContext = clientIdSet.get(clientId); - if (oldContext != null) - { - if (context.isAllowLinkStealing()) - { + if (oldContext != null) { + if (context.isAllowLinkStealing()) { clientIdSet.remove(clientId); - if (oldContext.getConnection() != null) - { + if (oldContext.getConnection() != null) { OpenWireConnection connection = oldContext.getConnection(); connection.disconnect(true); } - else - { + else { // log error } } - else - { - throw new InvalidClientIDException("Broker: " + getBrokerName() - + " - Client: " + clientId + " already connected from " - + oldContext.getConnection().getRemoteAddress()); + else { + throw new InvalidClientIDException("Broker: " + getBrokerName() + " - Client: " + clientId + " already connected from " + oldContext.getConnection().getRemoteAddress()); } } - else - { + else { clientIdSet.put(clientId, context); } } @@ -370,20 +320,15 @@ public class OpenWireProtocolManager implements ProtocolManager, No connectionInfos.put(copy.getConnectionId(), copy); // init the conn - addSessions(context.getConnection(), context.getConnectionState() - .getSessionIds()); + addSessions(context.getConnection(), context.getConnectionState().getSessionIds()); } - private void fireAdvisory(AMQConnectionContext context, ActiveMQTopic topic, - Command copy) throws Exception - { + private void fireAdvisory(AMQConnectionContext context, ActiveMQTopic topic, Command copy) throws Exception { this.fireAdvisory(context, topic, copy, null); } - public BrokerId getBrokerId() - { - if (brokerId == null) - { + public BrokerId getBrokerId() { + if (brokerId == null) { brokerId = new BrokerId(BROKER_ID_GENERATOR.generateId()); } return brokerId; @@ -392,27 +337,24 @@ public class OpenWireProtocolManager implements ProtocolManager, No /* * See AdvisoryBroker.fireAdvisory() */ - private void fireAdvisory(AMQConnectionContext context, ActiveMQTopic topic, - Command command, ConsumerId targetConsumerId) throws Exception - { + private void fireAdvisory(AMQConnectionContext context, + ActiveMQTopic topic, + Command command, + ConsumerId targetConsumerId) throws Exception { ActiveMQMessage advisoryMessage = new ActiveMQMessage(); - advisoryMessage.setStringProperty( - AdvisorySupport.MSG_PROPERTY_ORIGIN_BROKER_NAME, getBrokerName()); + advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_ORIGIN_BROKER_NAME, getBrokerName()); String id = getBrokerId() != null ? getBrokerId().getValue() : "NOT_SET"; - advisoryMessage.setStringProperty( - AdvisorySupport.MSG_PROPERTY_ORIGIN_BROKER_ID, id); + advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_ORIGIN_BROKER_ID, id); String url = "tcp://localhost:61616"; - advisoryMessage.setStringProperty( - AdvisorySupport.MSG_PROPERTY_ORIGIN_BROKER_URL, url); + advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_ORIGIN_BROKER_URL, url); // set the data structure advisoryMessage.setDataStructure(command); advisoryMessage.setPersistent(false); advisoryMessage.setType(AdvisorySupport.ADIVSORY_MESSAGE_TYPE); - advisoryMessage.setMessageId(new MessageId(advisoryProducerId, - messageIdGenerator.getNextSequenceId())); + advisoryMessage.setMessageId(new MessageId(advisoryProducerId, messageIdGenerator.getNextSequenceId())); advisoryMessage.setTargetConsumerId(targetConsumerId); advisoryMessage.setDestination(topic); advisoryMessage.setResponseRequired(false); @@ -422,115 +364,84 @@ public class OpenWireProtocolManager implements ProtocolManager, No producerExchange.setConnectionContext(context); producerExchange.setMutable(true); producerExchange.setProducerState(new ProducerState(new ProducerInfo())); - try - { + try { context.setProducerFlowControl(false); AMQSession sess = context.getConnection().getAdvisorySession(); - if (sess != null) - { + if (sess != null) { sess.send(producerExchange, advisoryMessage, false); } } - finally - { + finally { context.setProducerFlowControl(originalFlowControl); } } - public String getBrokerName() - { - if (brokerName == null) - { - try - { - brokerName = InetAddressUtil.getLocalHostName().toLowerCase( - Locale.ENGLISH); + public String getBrokerName() { + if (brokerName == null) { + try { + brokerName = InetAddressUtil.getLocalHostName().toLowerCase(Locale.ENGLISH); } - catch (Exception e) - { + catch (Exception e) { brokerName = "localhost"; } } return brokerName; } - public boolean isFaultTolerantConfiguration() - { + public boolean isFaultTolerantConfiguration() { return false; } - public void postProcessDispatch(MessageDispatch md) - { + public void postProcessDispatch(MessageDispatch md) { // TODO Auto-generated method stub } - public boolean isStopped() - { + public boolean isStopped() { // TODO Auto-generated method stub return false; } - public void preProcessDispatch(MessageDispatch messageDispatch) - { + public void preProcessDispatch(MessageDispatch messageDispatch) { // TODO Auto-generated method stub } - public boolean isStopping() - { + public boolean isStopping() { return false; } - public void addProducer(OpenWireConnection theConn, ProducerInfo info) throws Exception - { + public void addProducer(OpenWireConnection theConn, ProducerInfo info) throws Exception { SessionId sessionId = info.getProducerId().getParentId(); ConnectionId connectionId = sessionId.getParentId(); ConnectionState cs = theConn.getState(); - if (cs == null) - { - throw new IllegalStateException( - "Cannot add a producer to a connection that had not been registered: " - + connectionId); + if (cs == null) { + throw new IllegalStateException("Cannot add a producer to a connection that had not been registered: " + connectionId); } SessionState ss = cs.getSessionState(sessionId); - if (ss == null) - { - throw new IllegalStateException( - "Cannot add a producer to a session that had not been registered: " - + sessionId); + if (ss == null) { + throw new IllegalStateException("Cannot add a producer to a session that had not been registered: " + sessionId); } // Avoid replaying dup commands - if (!ss.getProducerIds().contains(info.getProducerId())) - { + if (!ss.getProducerIds().contains(info.getProducerId())) { ActiveMQDestination destination = info.getDestination(); - if (destination != null - && !AdvisorySupport.isAdvisoryTopic(destination)) - { - if (theConn.getProducerCount() >= theConn - .getMaximumProducersAllowedPerConnection()) - { - throw new IllegalStateException( - "Can't add producer on connection " + connectionId - + ": at maximum limit: " - + theConn.getMaximumProducersAllowedPerConnection()); + if (destination != null && !AdvisorySupport.isAdvisoryTopic(destination)) { + if (theConn.getProducerCount() >= theConn.getMaximumProducersAllowedPerConnection()) { + throw new IllegalStateException("Can't add producer on connection " + connectionId + ": at maximum limit: " + theConn.getMaximumProducersAllowedPerConnection()); } } AMQSession amqSession = sessions.get(sessionId); - if (amqSession == null) - { + if (amqSession == null) { throw new IllegalStateException("Session not exist! : " + sessionId); } amqSession.createProducer(info); - try - { + try { ss.addProducer(info); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { amqSession.removeProducer(info); } @@ -538,46 +449,29 @@ public class OpenWireProtocolManager implements ProtocolManager, No } - public void addConsumer(OpenWireConnection theConn, ConsumerInfo info) throws Exception - { + public void addConsumer(OpenWireConnection theConn, ConsumerInfo info) throws Exception { // Todo: add a destination interceptors holder here (amq supports this) SessionId sessionId = info.getConsumerId().getParentId(); ConnectionId connectionId = sessionId.getParentId(); ConnectionState cs = theConn.getState(); - if (cs == null) - { - throw new IllegalStateException( - "Cannot add a consumer to a connection that had not been registered: " - + connectionId); + if (cs == null) { + throw new IllegalStateException("Cannot add a consumer to a connection that had not been registered: " + connectionId); } SessionState ss = cs.getSessionState(sessionId); - if (ss == null) - { - throw new IllegalStateException( - this.server - + " Cannot add a consumer to a session that had not been registered: " - + sessionId); + if (ss == null) { + throw new IllegalStateException(this.server + " Cannot add a consumer to a session that had not been registered: " + sessionId); } // Avoid replaying dup commands - if (!ss.getConsumerIds().contains(info.getConsumerId())) - { + if (!ss.getConsumerIds().contains(info.getConsumerId())) { ActiveMQDestination destination = info.getDestination(); - if (destination != null - && !AdvisorySupport.isAdvisoryTopic(destination)) - { - if (theConn.getConsumerCount() >= theConn - .getMaximumConsumersAllowedPerConnection()) - { - throw new IllegalStateException( - "Can't add consumer on connection " + connectionId - + ": at maximum limit: " - + theConn.getMaximumConsumersAllowedPerConnection()); + if (destination != null && !AdvisorySupport.isAdvisoryTopic(destination)) { + if (theConn.getConsumerCount() >= theConn.getMaximumConsumersAllowedPerConnection()) { + throw new IllegalStateException("Can't add consumer on connection " + connectionId + ": at maximum limit: " + theConn.getMaximumConsumersAllowedPerConnection()); } } AMQSession amqSession = sessions.get(sessionId); - if (amqSession == null) - { + if (amqSession == null) { throw new IllegalStateException("Session not exist! : " + sessionId); } @@ -587,27 +481,20 @@ public class OpenWireProtocolManager implements ProtocolManager, No } } - public void addSessions(OpenWireConnection theConn, Set sessionSet) - { + public void addSessions(OpenWireConnection theConn, Set sessionSet) { Iterator iter = sessionSet.iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { SessionId sid = iter.next(); - addSession(theConn, theConn.getState().getSessionState(sid).getInfo(), - true); + addSession(theConn, theConn.getState().getSessionState(sid).getInfo(), true); } } - public AMQSession addSession(OpenWireConnection theConn, SessionInfo ss) - { + public AMQSession addSession(OpenWireConnection theConn, SessionInfo ss) { return addSession(theConn, ss, false); } - public AMQSession addSession(OpenWireConnection theConn, SessionInfo ss, - boolean internal) - { - AMQSession amqSession = new AMQSession(theConn.getState().getInfo(), ss, - server, theConn, scheduledPool, this); + public AMQSession addSession(OpenWireConnection theConn, SessionInfo ss, boolean internal) { + AMQSession amqSession = new AMQSession(theConn.getState().getInfo(), ss, server, theConn, scheduledPool, this); amqSession.initialize(); amqSession.setInternal(internal); sessions.put(ss.getSessionId(), amqSession); @@ -615,58 +502,45 @@ public class OpenWireProtocolManager implements ProtocolManager, No return amqSession; } - public void removeConnection(AMQConnectionContext context, - ConnectionInfo info, Throwable error) - { + public void removeConnection(AMQConnectionContext context, ConnectionInfo info, Throwable error) { // todo roll back tx this.connections.remove(context.getConnection()); this.connectionInfos.remove(info.getConnectionId()); String clientId = info.getClientId(); - if (clientId != null) - { + if (clientId != null) { this.clientIdSet.remove(clientId); } } - public void removeSession(AMQConnectionContext context, SessionInfo info) throws Exception - { + public void removeSession(AMQConnectionContext context, SessionInfo info) throws Exception { AMQSession session = sessions.remove(info.getSessionId()); - if (session != null) - { + if (session != null) { session.close(); } } - public void removeProducer(ProducerId id) - { + public void removeProducer(ProducerId id) { SessionId sessionId = id.getParentId(); AMQSession session = sessions.get(sessionId); session.removeProducer(id); } - public AMQPersistenceAdapter getPersistenceAdapter() - { + public AMQPersistenceAdapter getPersistenceAdapter() { // TODO Auto-generated method stub return null; } - public AMQSession getSession(SessionId sessionId) - { + public AMQSession getSession(SessionId sessionId) { return sessions.get(sessionId); } - public void addDestination(OpenWireConnection connection, - DestinationInfo info) throws Exception - { + public void addDestination(OpenWireConnection connection, DestinationInfo info) throws Exception { ActiveMQDestination dest = info.getDestination(); - if (dest.isQueue()) - { - SimpleString qName = new SimpleString("jms.queue." - + dest.getPhysicalName()); + if (dest.isQueue()) { + SimpleString qName = new SimpleString("jms.queue." + dest.getPhysicalName()); ConnectionState state = connection.getState(); ConnectionInfo connInfo = state.getInfo(); - if (connInfo != null) - { + if (connInfo != null) { String user = connInfo.getUserName(); String pass = connInfo.getPassword(); @@ -677,14 +551,12 @@ public class OpenWireProtocolManager implements ProtocolManager, No ((ActiveMQServerImpl) server).checkQueueCreationLimit(user); } this.server.createQueue(qName, qName, null, connInfo == null ? null : SimpleString.toSimpleString(connInfo.getUserName()), false, true); - if (dest.isTemporary()) - { + if (dest.isTemporary()) { connection.registerTempQueue(qName); } } - if (!AdvisorySupport.isAdvisoryTopic(dest)) - { + if (!AdvisorySupport.isAdvisoryTopic(dest)) { AMQConnectionContext context = connection.getConext(); DestinationInfo advInfo = new DestinationInfo(context.getConnectionId(), DestinationInfo.ADD_OPERATION_TYPE, dest); @@ -693,74 +565,58 @@ public class OpenWireProtocolManager implements ProtocolManager, No } } - public void deleteQueue(String q) throws Exception - { + public void deleteQueue(String q) throws Exception { server.destroyQueue(new SimpleString(q)); } - - public void endTransaction(TransactionInfo info) throws Exception - { + public void endTransaction(TransactionInfo info) throws Exception { AMQSession txSession = transactions.get(info.getTransactionId()); - if (txSession != null) - { + if (txSession != null) { txSession.endTransaction(info); } } - public void commitTransactionOnePhase(TransactionInfo info) throws Exception - { + public void commitTransactionOnePhase(TransactionInfo info) throws Exception { AMQSession txSession = transactions.get(info.getTransactionId()); - if (txSession != null) - { + if (txSession != null) { txSession.commitOnePhase(info); } transactions.remove(info.getTransactionId()); } - public void prepareTransaction(TransactionInfo info) throws Exception - { + public void prepareTransaction(TransactionInfo info) throws Exception { XATransactionId xid = (XATransactionId) info.getTransactionId(); AMQSession txSession = transactions.get(xid); - if (txSession != null) - { + if (txSession != null) { txSession.prepareTransaction(xid); } } - public void commitTransactionTwoPhase(TransactionInfo info) throws Exception - { + public void commitTransactionTwoPhase(TransactionInfo info) throws Exception { XATransactionId xid = (XATransactionId) info.getTransactionId(); AMQSession txSession = transactions.get(xid); - if (txSession != null) - { + if (txSession != null) { txSession.commitTwoPhase(xid); } transactions.remove(xid); } - public void rollbackTransaction(TransactionInfo info) throws Exception - { + public void rollbackTransaction(TransactionInfo info) throws Exception { AMQSession txSession = transactions.get(info.getTransactionId()); - if (txSession != null) - { + if (txSession != null) { txSession.rollback(info); } transactions.remove(info.getTransactionId()); } - public TransactionId[] recoverTransactions(Set sIds) - { + public TransactionId[] recoverTransactions(Set sIds) { List recovered = new ArrayList(); - if (sIds != null) - { - for (SessionId sid : sIds) - { + if (sIds != null) { + for (SessionId sid : sIds) { AMQSession s = this.sessions.get(sid); - if (s != null) - { + if (s != null) { s.recover(recovered); } } @@ -768,46 +624,37 @@ public class OpenWireProtocolManager implements ProtocolManager, No return recovered.toArray(new TransactionId[0]); } - public boolean validateUser(String login, String passcode) - { + public boolean validateUser(String login, String passcode) { boolean validated = true; ActiveMQSecurityManager sm = server.getSecurityManager(); - if (sm != null && server.getConfiguration().isSecurityEnabled()) - { + if (sm != null && server.getConfiguration().isSecurityEnabled()) { validated = sm.validateUser(login, passcode); } return validated; } - public void forgetTransaction(TransactionId xid) throws Exception - { + public void forgetTransaction(TransactionId xid) throws Exception { AMQSession txSession = transactions.get(xid); - if (txSession != null) - { + if (txSession != null) { txSession.forget(xid); } transactions.remove(xid); } - public void registerTx(TransactionId txId, AMQSession amqSession) - { + public void registerTx(TransactionId txId, AMQSession amqSession) { transactions.put(txId, amqSession); } //advisory support @Override - public void onNotification(Notification notif) - { - try - { - if (notif.getType() instanceof CoreNotificationType) - { - CoreNotificationType type = (CoreNotificationType)notif.getType(); - switch (type) - { + public void onNotification(Notification notif) { + try { + if (notif.getType() instanceof CoreNotificationType) { + CoreNotificationType type = (CoreNotificationType) notif.getType(); + switch (type) { case CONSUMER_SLOW: fireSlowConsumer(notif); break; @@ -816,14 +663,12 @@ public class OpenWireProtocolManager implements ProtocolManager, No } } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.error("Failed to send notification " + notif, e); } } - private void fireSlowConsumer(Notification notif) throws Exception - { + private void fireSlowConsumer(Notification notif) throws Exception { SimpleString coreSessionId = notif.getProperties().getSimpleStringProperty(ManagementHelper.HDR_SESSION_NAME); Long coreConsumerId = notif.getProperties().getLongProperty(ManagementHelper.HDR_CONSUMER_NAME); SessionId sessionId = sessionIdMap.get(coreSessionId.toString()); @@ -831,8 +676,7 @@ public class OpenWireProtocolManager implements ProtocolManager, No AMQConsumer consumer = session.getConsumer(coreConsumerId); ActiveMQDestination destination = consumer.getDestination(); - if (!AdvisorySupport.isAdvisoryTopic(destination)) - { + if (!AdvisorySupport.isAdvisoryTopic(destination)) { ActiveMQTopic topic = AdvisorySupport.getSlowConsumerAdvisoryTopic(destination); ConnectionId connId = sessionId.getParentId(); OpenWireConnection cc = this.brokerConnectionStates.get(connId); @@ -843,11 +687,8 @@ public class OpenWireProtocolManager implements ProtocolManager, No } } - public void removeSubscription(RemoveSubscriptionInfo subInfo) throws Exception - { - SimpleString subQueueName = new SimpleString( - org.apache.activemq.artemis.jms.client.ActiveMQDestination.createQueueNameForDurableSubscription( - true, subInfo.getClientId(), subInfo.getSubscriptionName())); + public void removeSubscription(RemoveSubscriptionInfo subInfo) throws Exception { + SimpleString subQueueName = new SimpleString(org.apache.activemq.artemis.jms.client.ActiveMQDestination.createQueueNameForDurableSubscription(true, subInfo.getClientId(), subInfo.getSubscriptionName())); server.destroyQueue(subQueueName); } } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/OpenWireProtocolManagerFactory.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/OpenWireProtocolManagerFactory.java index ec23e968e8..2124a859a7 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/OpenWireProtocolManagerFactory.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/OpenWireProtocolManagerFactory.java @@ -25,34 +25,32 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.spi.core.protocol.AbstractProtocolManagerFactory; import org.apache.activemq.artemis.spi.core.protocol.ProtocolManager; -public class OpenWireProtocolManagerFactory extends AbstractProtocolManagerFactory -{ +public class OpenWireProtocolManagerFactory extends AbstractProtocolManagerFactory { + public static final String OPENWIRE_PROTOCOL_NAME = "OPENWIRE"; private static final String MODULE_NAME = "artemis-openwire-protocol"; private static String[] SUPPORTED_PROTOCOLS = {OPENWIRE_PROTOCOL_NAME}; - public ProtocolManager createProtocolManager(final ActiveMQServer server, final List incomingInterceptors, List outgoingInterceptors) - { + public ProtocolManager createProtocolManager(final ActiveMQServer server, + final List incomingInterceptors, + List outgoingInterceptors) { return new OpenWireProtocolManager(this, server); } @Override - public List filterInterceptors(List interceptors) - { + public List filterInterceptors(List interceptors) { return Collections.emptyList(); } @Override - public String[] getProtocols() - { + public String[] getProtocols() { return SUPPORTED_PROTOCOLS; } @Override - public String getModuleName() - { + public String getModuleName() { return MODULE_NAME; } } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/OpenWireUtil.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/OpenWireUtil.java index c43a9f8a55..fbd3aecafc 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/OpenWireUtil.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/OpenWireUtil.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.core.protocol.openwire; - import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.ActiveMQBuffers; import org.apache.activemq.command.ActiveMQDestination; @@ -27,44 +26,36 @@ import org.apache.activemq.artemis.core.server.BindingQueryResult; import org.apache.activemq.util.ByteSequence; import org.apache.activemq.artemis.api.core.SimpleString; -public class OpenWireUtil -{ +public class OpenWireUtil { - public static ActiveMQBuffer toActiveMQBuffer(ByteSequence bytes) - { + public static ActiveMQBuffer toActiveMQBuffer(ByteSequence bytes) { ActiveMQBuffer buffer = ActiveMQBuffers.fixedBuffer(bytes.length); buffer.writeBytes(bytes.data, bytes.offset, bytes.length); return buffer; } - - public static SimpleString toCoreAddress(ActiveMQDestination dest) - { - if (dest.isQueue()) - { + public static SimpleString toCoreAddress(ActiveMQDestination dest) { + if (dest.isQueue()) { return new SimpleString("jms.queue." + dest.getPhysicalName()); } - else - { + else { return new SimpleString("jms.topic." + dest.getPhysicalName()); } } /** * Checks to see if this destination exists. If it does not throw an invalid destination exception. + * * @param destination * @param amqSession */ - public static void validateDestination(ActiveMQDestination destination, AMQSession amqSession) throws Exception - { - if (destination.isQueue()) - { + public static void validateDestination(ActiveMQDestination destination, AMQSession amqSession) throws Exception { + if (destination.isQueue()) { AMQServerSession coreSession = amqSession.getCoreSession(); SimpleString physicalName = OpenWireUtil.toCoreAddress(destination); BindingQueryResult result = coreSession.executeBindingQuery(physicalName); - if (!result.isExists() && !result.isAutoCreateJmsQueues()) - { + if (!result.isExists() && !result.isAutoCreateJmsQueues()) { throw ActiveMQMessageBundle.BUNDLE.noSuchQueue(physicalName); } } @@ -76,8 +67,7 @@ public class OpenWireUtil *AMQ * wildcard --> Core * wildcard (no conversion) *AMQ > wildcard --> Core # wildcard */ - public static String convertWildcard(String physicalName) - { + public static String convertWildcard(String physicalName) { return physicalName.replaceAll("(\\.>)+", ".#"); } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/SendingResult.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/SendingResult.java index a01e41c784..0e21ca4dbf 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/SendingResult.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/SendingResult.java @@ -20,44 +20,37 @@ import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.paging.impl.PagingStoreImpl; import org.apache.activemq.artemis.core.settings.impl.AddressFullMessagePolicy; -public class SendingResult -{ +public class SendingResult { + private boolean blockNextSend; private PagingStoreImpl blockPagingStore; private SimpleString blockingAddress; - public void setBlockNextSend(boolean block) - { + public void setBlockNextSend(boolean block) { this.blockNextSend = block; } - public boolean isBlockNextSend() - { + public boolean isBlockNextSend() { return this.blockNextSend; } - public void setBlockPagingStore(PagingStoreImpl store) - { + public void setBlockPagingStore(PagingStoreImpl store) { this.blockPagingStore = store; } - public PagingStoreImpl getBlockPagingStore() - { + public PagingStoreImpl getBlockPagingStore() { return this.blockPagingStore; } - public void setBlockingAddress(SimpleString address) - { + public void setBlockingAddress(SimpleString address) { this.blockingAddress = address; } - public SimpleString getBlockingAddress() - { + public SimpleString getBlockingAddress() { return this.blockingAddress; } - public boolean isSendFailIfNoSpace() - { + public boolean isSendFailIfNoSpace() { AddressFullMessagePolicy policy = this.blockPagingStore.getAddressFullMessagePolicy(); return policy == AddressFullMessagePolicy.FAIL; } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQAbstractDeadLetterStrategy.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQAbstractDeadLetterStrategy.java index 7f0b4339f7..bcb2eb2d79 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQAbstractDeadLetterStrategy.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQAbstractDeadLetterStrategy.java @@ -19,41 +19,34 @@ package org.apache.activemq.artemis.core.protocol.openwire.amq; import org.apache.activemq.ActiveMQMessageAudit; import org.apache.activemq.command.Message; -public abstract class AMQAbstractDeadLetterStrategy implements AMQDeadLetterStrategy -{ +public abstract class AMQAbstractDeadLetterStrategy implements AMQDeadLetterStrategy { + private boolean processNonPersistent = false; private boolean processExpired = true; private boolean enableAudit = true; private final ActiveMQMessageAudit messageAudit = new ActiveMQMessageAudit(); @Override - public void rollback(Message message) - { - if (message != null && this.enableAudit) - { + public void rollback(Message message) { + if (message != null && this.enableAudit) { messageAudit.rollback(message); } } @Override - public boolean isSendToDeadLetterQueue(Message message) - { + public boolean isSendToDeadLetterQueue(Message message) { boolean result = false; - if (message != null) - { + if (message != null) { result = true; - if (enableAudit && messageAudit.isDuplicate(message)) - { + if (enableAudit && messageAudit.isDuplicate(message)) { result = false; // LOG.debug("Not adding duplicate to DLQ: {}, dest: {}", // message.getMessageId(), message.getDestination()); } - if (!message.isPersistent() && !processNonPersistent) - { + if (!message.isPersistent() && !processNonPersistent) { result = false; } - if (message.isExpired() && !processExpired) - { + if (message.isExpired() && !processExpired) { result = false; } } @@ -64,18 +57,15 @@ public abstract class AMQAbstractDeadLetterStrategy implements AMQDeadLetterStra * @return the processExpired */ @Override - public boolean isProcessExpired() - { + public boolean isProcessExpired() { return this.processExpired; } /** - * @param processExpired - * the processExpired to set + * @param processExpired the processExpired to set */ @Override - public void setProcessExpired(boolean processExpired) - { + public void setProcessExpired(boolean processExpired) { this.processExpired = processExpired; } @@ -83,28 +73,23 @@ public abstract class AMQAbstractDeadLetterStrategy implements AMQDeadLetterStra * @return the processNonPersistent */ @Override - public boolean isProcessNonPersistent() - { + public boolean isProcessNonPersistent() { return this.processNonPersistent; } /** - * @param processNonPersistent - * the processNonPersistent to set + * @param processNonPersistent the processNonPersistent to set */ @Override - public void setProcessNonPersistent(boolean processNonPersistent) - { + public void setProcessNonPersistent(boolean processNonPersistent) { this.processNonPersistent = processNonPersistent; } - public boolean isEnableAudit() - { + public boolean isEnableAudit() { return enableAudit; } - public void setEnableAudit(boolean enableAudit) - { + public void setEnableAudit(boolean enableAudit) { this.enableAudit = enableAudit; } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQBrokerStoppedException.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQBrokerStoppedException.java index 6951783740..b82ccdd6c8 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQBrokerStoppedException.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQBrokerStoppedException.java @@ -16,29 +16,24 @@ */ package org.apache.activemq.artemis.core.protocol.openwire.amq; -public class AMQBrokerStoppedException extends IllegalStateException -{ +public class AMQBrokerStoppedException extends IllegalStateException { private static final long serialVersionUID = -7543507221414251115L; - public AMQBrokerStoppedException() - { + public AMQBrokerStoppedException() { super(); } - public AMQBrokerStoppedException(String message, Throwable cause) - { + public AMQBrokerStoppedException(String message, Throwable cause) { super(message); initCause(cause); } - public AMQBrokerStoppedException(String s) - { + public AMQBrokerStoppedException(String s) { super(s); } - public AMQBrokerStoppedException(Throwable cause) - { + public AMQBrokerStoppedException(Throwable cause) { initCause(cause); } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQCompositeConsumerBrokerExchange.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQCompositeConsumerBrokerExchange.java index 7fe36856c3..e1f1db2e75 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQCompositeConsumerBrokerExchange.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQCompositeConsumerBrokerExchange.java @@ -22,39 +22,31 @@ import org.apache.activemq.command.MessagePull; import java.util.Map; -public class AMQCompositeConsumerBrokerExchange extends AMQConsumerBrokerExchange -{ +public class AMQCompositeConsumerBrokerExchange extends AMQConsumerBrokerExchange { private final Map consumerMap; - public AMQCompositeConsumerBrokerExchange(AMQSession amqSession, Map consumerMap) - { + public AMQCompositeConsumerBrokerExchange(AMQSession amqSession, Map consumerMap) { super(amqSession); this.consumerMap = consumerMap; } - public void processMessagePull(MessagePull messagePull) throws Exception - { + public void processMessagePull(MessagePull messagePull) throws Exception { AMQConsumer amqConsumer = consumerMap.get(messagePull.getDestination()); - if (amqConsumer != null) - { + if (amqConsumer != null) { amqConsumer.processMessagePull(messagePull); } } - public void acknowledge(MessageAck ack) throws Exception - { + public void acknowledge(MessageAck ack) throws Exception { AMQConsumer amqConsumer = consumerMap.get(ack.getDestination()); - if (amqConsumer != null) - { + if (amqConsumer != null) { amqSession.acknowledge(ack, amqConsumer); } } - public void removeConsumer() throws Exception - { - for (AMQConsumer amqConsumer : consumerMap.values()) - { + public void removeConsumer() throws Exception { + for (AMQConsumer amqConsumer : consumerMap.values()) { amqConsumer.removeConsumer(); } } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQConnectionContext.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQConnectionContext.java index a219bb2099..33c40796f5 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQConnectionContext.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQConnectionContext.java @@ -31,8 +31,8 @@ import org.apache.activemq.state.ConnectionState; import org.apache.activemq.artemis.core.protocol.openwire.OpenWireConnection; import org.apache.activemq.artemis.core.protocol.openwire.OpenWireProtocolManager; -public class AMQConnectionContext -{ +public class AMQConnectionContext { + private OpenWireConnection connection; private AMQConnector connector; private OpenWireProtocolManager broker; //use protocol manager to represent the broker @@ -57,28 +57,23 @@ public class AMQConnectionContext private ConnectionState connectionState; private XATransactionId xid; - public AMQConnectionContext() - { + public AMQConnectionContext() { this.messageEvaluationContext = new MessageEvaluationContext(); } - public AMQConnectionContext(MessageEvaluationContext messageEvaluationContext) - { + public AMQConnectionContext(MessageEvaluationContext messageEvaluationContext) { this.messageEvaluationContext = messageEvaluationContext; } - public AMQConnectionContext(ConnectionInfo info) - { + public AMQConnectionContext(ConnectionInfo info) { this(); setClientId(info.getClientId()); setUserName(info.getUserName()); setConnectionId(info.getConnectionId()); } - public AMQConnectionContext copy() - { - AMQConnectionContext rc = new AMQConnectionContext( - this.messageEvaluationContext); + public AMQConnectionContext copy() { + AMQConnectionContext rc = new AMQConnectionContext(this.messageEvaluationContext); rc.connection = this.connection; rc.connector = this.connector; rc.broker = this.broker; @@ -102,20 +97,16 @@ public class AMQConnectionContext return rc; } - public AMQSecurityContext getSecurityContext() - { + public AMQSecurityContext getSecurityContext() { return securityContext; } - public void setSecurityContext(AMQSecurityContext subject) - { + public void setSecurityContext(AMQSecurityContext subject) { this.securityContext = subject; - if (subject != null) - { + if (subject != null) { setUserName(subject.getUserName()); } - else - { + else { setUserName(null); } } @@ -123,73 +114,60 @@ public class AMQConnectionContext /** * @return the broker being used. */ - public OpenWireProtocolManager getBroker() - { + public OpenWireProtocolManager getBroker() { return broker; } /** - * @param broker - * being used + * @param broker being used */ - public void setBroker(OpenWireProtocolManager broker) - { + public void setBroker(OpenWireProtocolManager broker) { this.broker = broker; } /** * @return the connection being used */ - public OpenWireConnection getConnection() - { + public OpenWireConnection getConnection() { return connection; } /** - * @param connection - * being used + * @param connection being used */ - public void setConnection(OpenWireConnection connection) - { + public void setConnection(OpenWireConnection connection) { this.connection = connection; } /** * @return the transaction being used. */ - public AMQTransaction getTransaction() - { + public AMQTransaction getTransaction() { return transaction; } /** - * @param transaction - * being used. + * @param transaction being used. */ - public void setTransaction(AMQTransaction transaction) - { + public void setTransaction(AMQTransaction transaction) { this.transaction = transaction; } /** * @return the connector being used. */ - public AMQConnector getConnector() - { + public AMQConnector getConnector() { return connector; } /** - * @param connector - * being used. + * @param connector being used. */ - public void setConnector(AMQConnector connector) - { + public void setConnector(AMQConnector connector) { this.connector = connector; } - public AMQMessageAuthorizationPolicy getMessageAuthorizationPolicy() - { + public AMQMessageAuthorizationPolicy getMessageAuthorizationPolicy() { return messageAuthorizationPolicy; } @@ -197,200 +175,159 @@ public class AMQConnectionContext * Sets the policy used to decide if the current connection is authorized to * consume a given message */ - public void setMessageAuthorizationPolicy( - AMQMessageAuthorizationPolicy messageAuthorizationPolicy) - { + public void setMessageAuthorizationPolicy(AMQMessageAuthorizationPolicy messageAuthorizationPolicy) { this.messageAuthorizationPolicy = messageAuthorizationPolicy; } /** * @return */ - public boolean isInRecoveryMode() - { + public boolean isInRecoveryMode() { return inRecoveryMode; } - public void setInRecoveryMode(boolean inRecoveryMode) - { + public void setInRecoveryMode(boolean inRecoveryMode) { this.inRecoveryMode = inRecoveryMode; } - public ConcurrentMap getTransactions() - { + public ConcurrentMap getTransactions() { return transactions; } - public void setTransactions( - ConcurrentMap transactions) - { + public void setTransactions(ConcurrentMap transactions) { this.transactions = transactions; } - public boolean isInTransaction() - { + public boolean isInTransaction() { return transaction != null; } - public String getClientId() - { + public String getClientId() { return clientId; } - public void setClientId(String clientId) - { + public void setClientId(String clientId) { this.clientId = clientId; } - public boolean isReconnect() - { + public boolean isReconnect() { return reconnect; } - public void setReconnect(boolean reconnect) - { + public void setReconnect(boolean reconnect) { this.reconnect = reconnect; } - public WireFormatInfo getWireFormatInfo() - { + public WireFormatInfo getWireFormatInfo() { return wireFormatInfo; } - public void setWireFormatInfo(WireFormatInfo wireFormatInfo) - { + public void setWireFormatInfo(WireFormatInfo wireFormatInfo) { this.wireFormatInfo = wireFormatInfo; } - public ConnectionId getConnectionId() - { + public ConnectionId getConnectionId() { return connectionId; } - public void setConnectionId(ConnectionId connectionId) - { + public void setConnectionId(ConnectionId connectionId) { this.connectionId = connectionId; } - public String getUserName() - { + public String getUserName() { return userName; } - public void setUserName(String userName) - { + public void setUserName(String userName) { this.userName = userName; } - public MessageEvaluationContext getMessageEvaluationContext() - { + public MessageEvaluationContext getMessageEvaluationContext() { return messageEvaluationContext; } - public Object getLongTermStoreContext() - { + public Object getLongTermStoreContext() { return longTermStoreContext; } - public void setLongTermStoreContext(Object longTermStoreContext) - { + public void setLongTermStoreContext(Object longTermStoreContext) { this.longTermStoreContext = longTermStoreContext; } - public boolean isProducerFlowControl() - { + public boolean isProducerFlowControl() { return producerFlowControl; } - public void setProducerFlowControl(boolean disableProducerFlowControl) - { + public void setProducerFlowControl(boolean disableProducerFlowControl) { this.producerFlowControl = disableProducerFlowControl; } - public boolean isAllowedToConsume(MessageReference n) throws IOException - { - if (messageAuthorizationPolicy != null) - { - return messageAuthorizationPolicy.isAllowedToConsume(this, - n.getMessage()); + public boolean isAllowedToConsume(MessageReference n) throws IOException { + if (messageAuthorizationPolicy != null) { + return messageAuthorizationPolicy.isAllowedToConsume(this, n.getMessage()); } return true; } - public synchronized boolean isNetworkConnection() - { + public synchronized boolean isNetworkConnection() { return networkConnection; } - public synchronized void setNetworkConnection(boolean networkConnection) - { + public synchronized void setNetworkConnection(boolean networkConnection) { this.networkConnection = networkConnection; } - public AtomicBoolean getStopping() - { + public AtomicBoolean getStopping() { return stopping; } - public void setDontSendReponse(boolean b) - { + public void setDontSendReponse(boolean b) { this.dontSendResponse = b; } - public boolean isDontSendReponse() - { + public boolean isDontSendReponse() { return dontSendResponse; } /** * @return the clientMaster */ - public boolean isClientMaster() - { + public boolean isClientMaster() { return this.clientMaster; } /** - * @param clientMaster - * the clientMaster to set + * @param clientMaster the clientMaster to set */ - public void setClientMaster(boolean clientMaster) - { + public void setClientMaster(boolean clientMaster) { this.clientMaster = clientMaster; } - public boolean isFaultTolerant() - { + public boolean isFaultTolerant() { return faultTolerant; } - public void setFaultTolerant(boolean faultTolerant) - { + public void setFaultTolerant(boolean faultTolerant) { this.faultTolerant = faultTolerant; } - public void setConnectionState(ConnectionState connectionState) - { + public void setConnectionState(ConnectionState connectionState) { this.connectionState = connectionState; } - public ConnectionState getConnectionState() - { + public ConnectionState getConnectionState() { return this.connectionState; } - public void setXid(XATransactionId id) - { + public void setXid(XATransactionId id) { this.xid = id; } - public XATransactionId getXid() - { + public XATransactionId getXid() { return xid; } - public boolean isAllowLinkStealing() - { + public boolean isAllowLinkStealing() { return connector != null && connector.isAllowLinkStealing(); } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQConnector.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQConnector.java index 5a39474ec2..6b4ab7f735 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQConnector.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQConnector.java @@ -20,8 +20,8 @@ import org.apache.activemq.command.BrokerInfo; import org.apache.activemq.command.ConnectionControl; import org.apache.activemq.artemis.core.protocol.openwire.OpenWireConnection; -public interface AMQConnector -{ +public interface AMQConnector { + /** * @return brokerInfo */ @@ -34,7 +34,7 @@ public interface AMQConnector /** * @return true if update client connections when brokers leave/join a - * cluster + * cluster */ boolean isUpdateClusterClients(); @@ -51,7 +51,7 @@ public interface AMQConnector /** * @return true if clients should be updated when a broker is removed from a - * broker + * broker */ boolean isUpdateClusterClientsOnRemove(); diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQConnectorStatistics.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQConnectorStatistics.java index 2d3c89c17b..f6ca7f4fa5 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQConnectorStatistics.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQConnectorStatistics.java @@ -20,8 +20,7 @@ import org.apache.activemq.management.CountStatisticImpl; import org.apache.activemq.management.PollCountStatisticImpl; import org.apache.activemq.management.StatsImpl; -public class AMQConnectorStatistics extends StatsImpl -{ +public class AMQConnectorStatistics extends StatsImpl { protected CountStatisticImpl enqueues; protected CountStatisticImpl dequeues; @@ -29,20 +28,13 @@ public class AMQConnectorStatistics extends StatsImpl protected CountStatisticImpl messages; protected PollCountStatisticImpl messagesCached; - public AMQConnectorStatistics() - { + public AMQConnectorStatistics() { - enqueues = new CountStatisticImpl("enqueues", - "The number of messages that have been sent to the destination"); - dequeues = new CountStatisticImpl("dequeues", - "The number of messages that have been dispatched from the destination"); - consumers = new CountStatisticImpl( - "consumers", - "The number of consumers that that are subscribing to messages from the destination"); - messages = new CountStatisticImpl("messages", - "The number of messages that that are being held by the destination"); - messagesCached = new PollCountStatisticImpl("messagesCached", - "The number of messages that are held in the destination's memory cache"); + enqueues = new CountStatisticImpl("enqueues", "The number of messages that have been sent to the destination"); + dequeues = new CountStatisticImpl("dequeues", "The number of messages that have been dispatched from the destination"); + consumers = new CountStatisticImpl("consumers", "The number of consumers that that are subscribing to messages from the destination"); + messages = new CountStatisticImpl("messages", "The number of messages that that are being held by the destination"); + messagesCached = new PollCountStatisticImpl("messagesCached", "The number of messages that are held in the destination's memory cache"); addStatistic("enqueues", enqueues); addStatistic("dequeues", dequeues); @@ -51,40 +43,33 @@ public class AMQConnectorStatistics extends StatsImpl addStatistic("messagesCached", messagesCached); } - public CountStatisticImpl getEnqueues() - { + public CountStatisticImpl getEnqueues() { return enqueues; } - public CountStatisticImpl getDequeues() - { + public CountStatisticImpl getDequeues() { return dequeues; } - public CountStatisticImpl getConsumers() - { + public CountStatisticImpl getConsumers() { return consumers; } - public PollCountStatisticImpl getMessagesCached() - { + public PollCountStatisticImpl getMessagesCached() { return messagesCached; } - public CountStatisticImpl getMessages() - { + public CountStatisticImpl getMessages() { return messages; } - public void reset() - { + public void reset() { super.reset(); enqueues.reset(); dequeues.reset(); } - public void setEnabled(boolean enabled) - { + public void setEnabled(boolean enabled) { super.setEnabled(enabled); enqueues.setEnabled(enabled); dequeues.setEnabled(enabled); @@ -93,18 +78,15 @@ public class AMQConnectorStatistics extends StatsImpl messagesCached.setEnabled(enabled); } - public void setParent(AMQConnectorStatistics parent) - { - if (parent != null) - { + public void setParent(AMQConnectorStatistics parent) { + if (parent != null) { enqueues.setParent(parent.enqueues); dequeues.setParent(parent.dequeues); consumers.setParent(parent.consumers); messagesCached.setParent(parent.messagesCached); messages.setParent(parent.messages); } - else - { + else { enqueues.setParent(null); dequeues.setParent(null); consumers.setParent(null); @@ -113,8 +95,7 @@ public class AMQConnectorStatistics extends StatsImpl } } - public void setMessagesCached(PollCountStatisticImpl messagesCached) - { + public void setMessagesCached(PollCountStatisticImpl messagesCached) { this.messagesCached = messagesCached; } } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQConsumer.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQConsumer.java index 59f6d26b60..789e527f12 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQConsumer.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQConsumer.java @@ -43,8 +43,8 @@ import org.apache.activemq.artemis.core.server.QueueQueryResult; import org.apache.activemq.artemis.core.server.ServerMessage; import org.apache.activemq.artemis.jms.client.ActiveMQDestination; -public class AMQConsumer implements BrowserListener -{ +public class AMQConsumer implements BrowserListener { + private AMQSession session; private org.apache.activemq.command.ActiveMQDestination actualDest; private ConsumerInfo info; @@ -58,22 +58,22 @@ public class AMQConsumer implements BrowserListener private long messagePullSequence = 0; private MessagePullHandler messagePullHandler; - public AMQConsumer(AMQSession amqSession, org.apache.activemq.command.ActiveMQDestination d, ConsumerInfo info, ScheduledExecutorService scheduledPool) - { + public AMQConsumer(AMQSession amqSession, + org.apache.activemq.command.ActiveMQDestination d, + ConsumerInfo info, + ScheduledExecutorService scheduledPool) { this.session = amqSession; this.actualDest = d; this.info = info; this.scheduledPool = scheduledPool; this.prefetchSize = info.getPrefetchSize(); this.windowAvailable = new AtomicInteger(prefetchSize); - if (prefetchSize == 0) - { + if (prefetchSize == 0) { messagePullHandler = new MessagePullHandler(); } } - public void init() throws Exception - { + public void init() throws Exception { AMQServerSession coreSession = session.getCoreSession(); SimpleString selector = info.getSelector() == null ? null : new SimpleString(info.getSelector()); @@ -82,63 +82,47 @@ public class AMQConsumer implements BrowserListener SimpleString address = new SimpleString(this.actualDest.getPhysicalName()); - if (this.actualDest.isTopic()) - { + if (this.actualDest.isTopic()) { String physicalName = this.actualDest.getPhysicalName(); - if (physicalName.contains(".>")) - { + if (physicalName.contains(".>")) { //wildcard physicalName = OpenWireUtil.convertWildcard(physicalName); } // on recreate we don't need to create queues address = new SimpleString("jms.topic." + physicalName); - if (info.isDurable()) - { - subQueueName = new SimpleString( - ActiveMQDestination.createQueueNameForDurableSubscription( - true, info.getClientId(), info.getSubscriptionName())); + if (info.isDurable()) { + subQueueName = new SimpleString(ActiveMQDestination.createQueueNameForDurableSubscription(true, info.getClientId(), info.getSubscriptionName())); QueueQueryResult result = coreSession.executeQueueQuery(subQueueName); - if (result.isExists()) - { + if (result.isExists()) { // Already exists - if (result.getConsumerCount() > 0) - { - throw new IllegalStateException( - "Cannot create a subscriber on the durable subscription since it already has subscriber(s)"); + if (result.getConsumerCount() > 0) { + throw new IllegalStateException("Cannot create a subscriber on the durable subscription since it already has subscriber(s)"); } SimpleString oldFilterString = result.getFilterString(); - boolean selectorChanged = selector == null - && oldFilterString != null || oldFilterString == null - && selector != null || oldFilterString != null - && selector != null && !oldFilterString.equals(selector); + boolean selectorChanged = selector == null && oldFilterString != null || oldFilterString == null && selector != null || oldFilterString != null && selector != null && !oldFilterString.equals(selector); SimpleString oldTopicName = result.getAddress(); boolean topicChanged = !oldTopicName.equals(address); - if (selectorChanged || topicChanged) - { + if (selectorChanged || topicChanged) { // Delete the old durable sub coreSession.deleteQueue(subQueueName); // Create the new one - coreSession.createQueue(address, subQueueName, selector, - false, true); + coreSession.createQueue(address, subQueueName, selector, false, true); } } - else - { - coreSession.createQueue(address, subQueueName, selector, false, - true); + else { + coreSession.createQueue(address, subQueueName, selector, false, true); } } - else - { + else { subQueueName = new SimpleString(UUID.randomUUID().toString()); coreSession.createQueue(address, subQueueName, selector, true, false); @@ -146,55 +130,44 @@ public class AMQConsumer implements BrowserListener coreSession.createConsumer(nativeId, subQueueName, null, info.isBrowser(), false, -1); } - else - { + else { SimpleString queueName = new SimpleString("jms.queue." + this.actualDest.getPhysicalName()); coreSession.createConsumer(nativeId, queueName, selector, info.isBrowser(), false, -1); } - if (info.isBrowser()) - { + if (info.isBrowser()) { AMQServerConsumer coreConsumer = coreSession.getConsumer(nativeId); coreConsumer.setBrowserListener(this); } } - public long getNativeId() - { + public long getNativeId() { return this.nativeId; } - public ConsumerId getId() - { + public ConsumerId getId() { return info.getConsumerId(); } - public WireFormat getMarshaller() - { + public WireFormat getMarshaller() { return this.session.getMarshaller(); } - public void acquireCredit(int n) throws Exception - { + public void acquireCredit(int n) throws Exception { boolean promptDelivery = windowAvailable.get() == 0; - if (windowAvailable.get() < prefetchSize) - { + if (windowAvailable.get() < prefetchSize) { this.windowAvailable.addAndGet(n); } - if (promptDelivery) - { + if (promptDelivery) { session.getCoreSession().promptDelivery(nativeId); } } - public int handleDeliver(ServerMessage message, int deliveryCount) - { + public int handleDeliver(ServerMessage message, int deliveryCount) { MessageDispatch dispatch; - try - { - if (messagePullHandler != null && !messagePullHandler.checkForcedConsumer(message)) - { + try { + if (messagePullHandler != null && !messagePullHandler.checkForcedConsumer(message)) { return 0; } //decrement deliveryCount as AMQ client tends to add 1. @@ -205,18 +178,15 @@ public class AMQConsumer implements BrowserListener windowAvailable.decrementAndGet(); return size; } - catch (IOException e) - { + catch (IOException e) { return 0; } - catch (Throwable t) - { + catch (Throwable t) { return 0; } } - public void handleDeliverNullDispatch() - { + public void handleDeliverNullDispatch() { MessageDispatch md = new MessageDispatch(); md.setConsumerId(getId()); md.setDestination(actualDest); @@ -224,9 +194,7 @@ public class AMQConsumer implements BrowserListener windowAvailable.decrementAndGet(); } - - public void acknowledge(MessageAck ack) throws Exception - { + public void acknowledge(MessageAck ack) throws Exception { MessageId first = ack.getFirstMessageId(); MessageId lastm = ack.getLastMessageId(); TransactionId tid = ack.getTransactionId(); @@ -236,14 +204,11 @@ public class AMQConsumer implements BrowserListener MessageInfo mi = null; int n = 0; - if (ack.isIndividualAck()) - { + if (ack.isIndividualAck()) { Iterator iter = deliveringRefs.iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { mi = iter.next(); - if (mi.amqId.equals(lastm)) - { + if (mi.amqId.equals(lastm)) { n++; iter.remove(); session.getCoreSession().individualAcknowledge(nativeId, mi.nativeId); @@ -252,95 +217,76 @@ public class AMQConsumer implements BrowserListener } } } - else if (ack.isRedeliveredAck()) - { + else if (ack.isRedeliveredAck()) { //client tells that this message is for redlivery. //do nothing until poisoned. n = 1; } - else if (ack.isPoisonAck()) - { + else if (ack.isPoisonAck()) { //send to dlq Iterator iter = deliveringRefs.iterator(); boolean firstFound = false; - while (iter.hasNext()) - { + while (iter.hasNext()) { mi = iter.next(); - if (mi.amqId.equals(first)) - { + if (mi.amqId.equals(first)) { n++; iter.remove(); session.getCoreSession().moveToDeadLetterAddress(nativeId, mi.nativeId, ack.getPoisonCause()); session.getCoreSession().commit(); - if (single) - { + if (single) { break; } firstFound = true; } - else if (firstFound || first == null) - { + else if (firstFound || first == null) { n++; iter.remove(); session.getCoreSession().moveToDeadLetterAddress(nativeId, mi.nativeId, ack.getPoisonCause()); session.getCoreSession().commit(); - if (mi.amqId.equals(lastm)) - { + if (mi.amqId.equals(lastm)) { break; } } } } - else if (ack.isDeliveredAck() || ack.isExpiredAck()) - { + else if (ack.isDeliveredAck() || ack.isExpiredAck()) { //ToDo: implement with tests n = 1; } - else - { + else { Iterator iter = deliveringRefs.iterator(); boolean firstFound = false; - while (iter.hasNext()) - { + while (iter.hasNext()) { MessageInfo ami = iter.next(); - if (ami.amqId.equals(first)) - { + if (ami.amqId.equals(first)) { n++; - if (!isLocalTx) - { + if (!isLocalTx) { iter.remove(); } - else - { + else { ami.setLocalAcked(true); } - if (single) - { + if (single) { mi = ami; break; } firstFound = true; } - else if (firstFound || first == null) - { + else if (firstFound || first == null) { n++; - if (!isLocalTx) - { + if (!isLocalTx) { iter.remove(); } - else - { + else { ami.setLocalAcked(true); } - if (ami.amqId.equals(lastm)) - { + if (ami.amqId.equals(lastm)) { mi = ami; break; } } } - if (mi != null && !isLocalTx) - { + if (mi != null && !isLocalTx) { session.getCoreSession().acknowledge(nativeId, mi.nativeId); } } @@ -349,8 +295,7 @@ public class AMQConsumer implements BrowserListener } @Override - public void browseFinished() - { + public void browseFinished() { MessageDispatch md = new MessageDispatch(); md.setConsumerId(info.getConsumerId()); md.setMessage(null); @@ -359,132 +304,106 @@ public class AMQConsumer implements BrowserListener session.deliverMessage(md); } - public boolean handledTransactionalMsg() - { + public boolean handledTransactionalMsg() { // TODO Auto-generated method stub return false; } //this is called before session commit a local tx - public void finishTx() throws Exception - { + public void finishTx() throws Exception { MessageInfo lastMi = null; MessageInfo mi = null; Iterator iter = deliveringRefs.iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { mi = iter.next(); - if (mi.isLocalAcked()) - { + if (mi.isLocalAcked()) { iter.remove(); lastMi = mi; } } - if (lastMi != null) - { + if (lastMi != null) { session.getCoreSession().acknowledge(nativeId, lastMi.nativeId); } } - public void rollbackTx(Set acked) throws Exception - { + public void rollbackTx(Set acked) throws Exception { MessageInfo lastMi = null; MessageInfo mi = null; Iterator iter = deliveringRefs.iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { mi = iter.next(); - if (mi.isLocalAcked()) - { + if (mi.isLocalAcked()) { acked.add(mi.nativeId); lastMi = mi; } } - if (lastMi != null) - { + if (lastMi != null) { session.getCoreSession().acknowledge(nativeId, lastMi.nativeId); } } - public org.apache.activemq.command.ActiveMQDestination getDestination() - { + public org.apache.activemq.command.ActiveMQDestination getDestination() { return actualDest; } - public ConsumerInfo getInfo() - { + public ConsumerInfo getInfo() { return info; } - public boolean hasCredits() - { + public boolean hasCredits() { return windowAvailable.get() > 0; } - public void processMessagePull(MessagePull messagePull) throws Exception - { + public void processMessagePull(MessagePull messagePull) throws Exception { windowAvailable.incrementAndGet(); - if (messagePullHandler != null) - { + if (messagePullHandler != null) { messagePullHandler.nextSequence(messagePullSequence++, messagePull.getTimeout()); } } - public void removeConsumer() throws Exception - { + public void removeConsumer() throws Exception { session.removeConsumer(nativeId); } - private class MessagePullHandler - { + private class MessagePullHandler { + private long next = -1; private long timeout; private CountDownLatch latch = new CountDownLatch(1); private ScheduledFuture messagePullFuture; - public void nextSequence(long next, long timeout) throws Exception - { + public void nextSequence(long next, long timeout) throws Exception { this.next = next; this.timeout = timeout; latch = new CountDownLatch(1); session.getCoreSession().forceConsumerDelivery(nativeId, messagePullSequence); //if we are 0 timeout or less we need to wait to get either the forced message or a real message. - if (timeout <= 0) - { + if (timeout <= 0) { latch.await(10, TimeUnit.SECONDS); //this means we have received no message just the forced delivery message - if (this.next >= 0) - { + if (this.next >= 0) { handleDeliverNullDispatch(); } } } - public boolean checkForcedConsumer(ServerMessage message) - { - if (message.containsProperty(ClientConsumerImpl.FORCED_DELIVERY_MESSAGE)) - { + public boolean checkForcedConsumer(ServerMessage message) { + if (message.containsProperty(ClientConsumerImpl.FORCED_DELIVERY_MESSAGE)) { System.out.println("MessagePullHandler.checkForcedConsumer"); - if (next >= 0) - { - if (timeout <= 0) - { + if (next >= 0) { + if (timeout <= 0) { latch.countDown(); } - else - { - messagePullFuture = scheduledPool.schedule(new Runnable() - { + else { + messagePullFuture = scheduledPool.schedule(new Runnable() { @Override - public void run() - { - if (next >= 0) - { + public void run() { + if (next >= 0) { handleDeliverNullDispatch(); } } @@ -493,11 +412,9 @@ public class AMQConsumer implements BrowserListener } return false; } - else - { + else { next = -1; - if (messagePullFuture != null) - { + if (messagePullFuture != null) { messagePullFuture.cancel(true); } latch.countDown(); diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQConsumerBrokerExchange.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQConsumerBrokerExchange.java index 168f557c15..1e87db335e 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQConsumerBrokerExchange.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQConsumerBrokerExchange.java @@ -19,84 +19,71 @@ package org.apache.activemq.artemis.core.protocol.openwire.amq; import org.apache.activemq.command.MessageAck; import org.apache.activemq.command.MessagePull; -public abstract class AMQConsumerBrokerExchange -{ +public abstract class AMQConsumerBrokerExchange { + protected final AMQSession amqSession; private AMQConnectionContext connectionContext; private AMQDestination regionDestination; private AMQSubscription subscription; private boolean wildcard; - public AMQConsumerBrokerExchange(AMQSession amqSession) - { + public AMQConsumerBrokerExchange(AMQSession amqSession) { this.amqSession = amqSession; } /** * @return the connectionContext */ - public AMQConnectionContext getConnectionContext() - { + public AMQConnectionContext getConnectionContext() { return this.connectionContext; } /** - * @param connectionContext - * the connectionContext to set + * @param connectionContext the connectionContext to set */ - public void setConnectionContext(AMQConnectionContext connectionContext) - { + public void setConnectionContext(AMQConnectionContext connectionContext) { this.connectionContext = connectionContext; } /** * @return the regionDestination */ - public AMQDestination getRegionDestination() - { + public AMQDestination getRegionDestination() { return this.regionDestination; } /** - * @param regionDestination - * the regionDestination to set + * @param regionDestination the regionDestination to set */ - public void setRegionDestination(AMQDestination regionDestination) - { + public void setRegionDestination(AMQDestination regionDestination) { this.regionDestination = regionDestination; } /** * @return the subscription */ - public AMQSubscription getSubscription() - { + public AMQSubscription getSubscription() { return this.subscription; } /** - * @param subscription - * the subscription to set + * @param subscription the subscription to set */ - public void setSubscription(AMQSubscription subscription) - { + public void setSubscription(AMQSubscription subscription) { this.subscription = subscription; } /** * @return the wildcard */ - public boolean isWildcard() - { + public boolean isWildcard() { return this.wildcard; } /** - * @param wildcard - * the wildcard to set + * @param wildcard the wildcard to set */ - public void setWildcard(boolean wildcard) - { + public void setWildcard(boolean wildcard) { this.wildcard = wildcard; } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQDeadLetterStrategy.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQDeadLetterStrategy.java index 1b10e934fb..ef99c54a17 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQDeadLetterStrategy.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQDeadLetterStrategy.java @@ -19,12 +19,12 @@ package org.apache.activemq.artemis.core.protocol.openwire.amq; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.Message; -public interface AMQDeadLetterStrategy -{ +public interface AMQDeadLetterStrategy { /** * Allow pluggable strategy for deciding if message should be sent to a dead letter queue * for example, you might not want to ignore expired or non-persistent messages + * * @param message * @return true if message should be sent to a dead letter queue */ diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQDestination.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQDestination.java index 6e0d480b61..ca061034ae 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQDestination.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQDestination.java @@ -28,15 +28,16 @@ import org.apache.activemq.command.ProducerInfo; import org.apache.activemq.usage.MemoryUsage; import org.apache.activemq.usage.Usage; -public interface AMQDestination -{ +public interface AMQDestination { + AMQDeadLetterStrategy DEFAULT_DEAD_LETTER_STRATEGY = new AMQSharedDeadLetterStrategy(); long DEFAULT_BLOCKED_PRODUCER_WARNING_INTERVAL = 30000; void addSubscription(AMQConnectionContext context, AMQSubscription sub) throws Exception; - void removeSubscription(AMQConnectionContext context, AMQSubscription sub, - long lastDeliveredSequenceId) throws Exception; + void removeSubscription(AMQConnectionContext context, + AMQSubscription sub, + long lastDeliveredSequenceId) throws Exception; void addProducer(AMQConnectionContext context, ProducerInfo info) throws Exception; @@ -44,8 +45,10 @@ public interface AMQDestination void send(AMQProducerBrokerExchange producerExchange, Message messageSend) throws Exception; - void acknowledge(AMQConnectionContext context, AMQSubscription sub, - final MessageAck ack, final MessageReference node) throws IOException; + void acknowledge(AMQConnectionContext context, + AMQSubscription sub, + final MessageAck ack, + final MessageReference node) throws IOException; long getInactiveTimoutBeforeGC(); @@ -88,16 +91,14 @@ public interface AMQDestination * resource usage will be triggered. Values of 0 or less will disable * warnings * - * @param blockedProducerWarningInterval - * the interval at which warning about blocked producers will be - * triggered. + * @param blockedProducerWarningInterval the interval at which warning about blocked producers will be + * triggered. */ void setBlockedProducerWarningInterval(long blockedProducerWarningInterval); /** - * * @return the interval at which warning about blocked producers will be - * triggered. + * triggered. */ long getBlockedProducerWarningInterval(); @@ -160,8 +161,7 @@ public interface AMQDestination * @param subs * @param node */ - void messageExpired(AMQConnectionContext context, AMQSubscription subs, - MessageReference node); + void messageExpired(AMQConnectionContext context, AMQSubscription subs, MessageReference node); /** * called when message is consumed @@ -169,8 +169,7 @@ public interface AMQDestination * @param context * @param messageReference */ - void messageConsumed(AMQConnectionContext context, - MessageReference messageReference); + void messageConsumed(AMQConnectionContext context, MessageReference messageReference); /** * Called when message is delivered to the broker @@ -178,8 +177,7 @@ public interface AMQDestination * @param context * @param messageReference */ - void messageDelivered(AMQConnectionContext context, - MessageReference messageReference); + void messageDelivered(AMQConnectionContext context, MessageReference messageReference); /** * Called when a message is discarded - e.g. running low on memory This will @@ -189,8 +187,7 @@ public interface AMQDestination * @param messageReference * @param sub */ - void messageDiscarded(AMQConnectionContext context, AMQSubscription sub, - MessageReference messageReference); + void messageDiscarded(AMQConnectionContext context, AMQSubscription sub, MessageReference messageReference); /** * Called when there is a slow consumer diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQDestinationStatistics.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQDestinationStatistics.java index 33acd86e1a..5259d2950a 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQDestinationStatistics.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQDestinationStatistics.java @@ -22,8 +22,7 @@ import org.apache.activemq.management.SizeStatisticImpl; import org.apache.activemq.management.StatsImpl; import org.apache.activemq.management.TimeStatisticImpl; -public class AMQDestinationStatistics extends StatsImpl -{ +public class AMQDestinationStatistics extends StatsImpl { protected CountStatisticImpl enqueues; protected CountStatisticImpl dequeues; @@ -39,40 +38,25 @@ public class AMQDestinationStatistics extends StatsImpl protected TimeStatisticImpl blockedTime; protected SizeStatisticImpl messageSize; - public AMQDestinationStatistics() - { + public AMQDestinationStatistics() { - enqueues = new CountStatisticImpl("enqueues", - "The number of messages that have been sent to the destination"); - dispatched = new CountStatisticImpl("dispatched", - "The number of messages that have been dispatched from the destination"); - dequeues = new CountStatisticImpl("dequeues", - "The number of messages that have been acknowledged from the destination"); - inflight = new CountStatisticImpl("inflight", - "The number of messages dispatched but awaiting acknowledgement"); - expired = new CountStatisticImpl("expired", - "The number of messages that have expired"); + enqueues = new CountStatisticImpl("enqueues", "The number of messages that have been sent to the destination"); + dispatched = new CountStatisticImpl("dispatched", "The number of messages that have been dispatched from the destination"); + dequeues = new CountStatisticImpl("dequeues", "The number of messages that have been acknowledged from the destination"); + inflight = new CountStatisticImpl("inflight", "The number of messages dispatched but awaiting acknowledgement"); + expired = new CountStatisticImpl("expired", "The number of messages that have expired"); - consumers = new CountStatisticImpl( - "consumers", - "The number of consumers that that are subscribing to messages from the destination"); + consumers = new CountStatisticImpl("consumers", "The number of consumers that that are subscribing to messages from the destination"); consumers.setDoReset(false); - producers = new CountStatisticImpl("producers", - "The number of producers that that are publishing messages to the destination"); + producers = new CountStatisticImpl("producers", "The number of producers that that are publishing messages to the destination"); producers.setDoReset(false); - messages = new CountStatisticImpl("messages", - "The number of messages that that are being held by the destination"); + messages = new CountStatisticImpl("messages", "The number of messages that that are being held by the destination"); messages.setDoReset(false); - messagesCached = new PollCountStatisticImpl("messagesCached", - "The number of messages that are held in the destination's memory cache"); - processTime = new TimeStatisticImpl("processTime", - "information around length of time messages are held by a destination"); - blockedSends = new CountStatisticImpl("blockedSends", - "number of messages that have to wait for flow control"); - blockedTime = new TimeStatisticImpl("blockedTime", - "amount of time messages are blocked for flow control"); - messageSize = new SizeStatisticImpl("messageSize", - "Size of messages passing through the destination"); + messagesCached = new PollCountStatisticImpl("messagesCached", "The number of messages that are held in the destination's memory cache"); + processTime = new TimeStatisticImpl("processTime", "information around length of time messages are held by a destination"); + blockedSends = new CountStatisticImpl("blockedSends", "number of messages that have to wait for flow control"); + blockedTime = new TimeStatisticImpl("blockedTime", "amount of time messages are blocked for flow control"); + messageSize = new SizeStatisticImpl("messageSize", "Size of messages passing through the destination"); addStatistic("enqueues", enqueues); addStatistic("dispatched", dispatched); addStatistic("dequeues", dequeues); @@ -88,80 +72,64 @@ public class AMQDestinationStatistics extends StatsImpl addStatistic("messageSize", messageSize); } - public CountStatisticImpl getEnqueues() - { + public CountStatisticImpl getEnqueues() { return enqueues; } - public CountStatisticImpl getDequeues() - { + public CountStatisticImpl getDequeues() { return dequeues; } - public CountStatisticImpl getInflight() - { + public CountStatisticImpl getInflight() { return inflight; } - public CountStatisticImpl getExpired() - { + public CountStatisticImpl getExpired() { return expired; } - public CountStatisticImpl getConsumers() - { + public CountStatisticImpl getConsumers() { return consumers; } - public CountStatisticImpl getProducers() - { + public CountStatisticImpl getProducers() { return producers; } - public PollCountStatisticImpl getMessagesCached() - { + public PollCountStatisticImpl getMessagesCached() { return messagesCached; } - public CountStatisticImpl getMessages() - { + public CountStatisticImpl getMessages() { return messages; } - public void setMessagesCached(PollCountStatisticImpl messagesCached) - { + public void setMessagesCached(PollCountStatisticImpl messagesCached) { this.messagesCached = messagesCached; } - public CountStatisticImpl getDispatched() - { + public CountStatisticImpl getDispatched() { return dispatched; } - public TimeStatisticImpl getProcessTime() - { + public TimeStatisticImpl getProcessTime() { return this.processTime; } - public CountStatisticImpl getBlockedSends() - { + public CountStatisticImpl getBlockedSends() { return this.blockedSends; } - public TimeStatisticImpl getBlockedTime() - { + public TimeStatisticImpl getBlockedTime() { return this.blockedTime; } - public SizeStatisticImpl getMessageSize() - { + public SizeStatisticImpl getMessageSize() { return this.messageSize; } - public void reset() - { - if (this.isDoReset()) - { + public void reset() { + if (this.isDoReset()) { super.reset(); enqueues.reset(); dequeues.reset(); @@ -174,8 +142,7 @@ public class AMQDestinationStatistics extends StatsImpl } } - public void setEnabled(boolean enabled) - { + public void setEnabled(boolean enabled) { super.setEnabled(enabled); enqueues.setEnabled(enabled); dispatched.setEnabled(enabled); @@ -193,10 +160,8 @@ public class AMQDestinationStatistics extends StatsImpl } - public void setParent(AMQDestinationStatistics parent) - { - if (parent != null) - { + public void setParent(AMQDestinationStatistics parent) { + if (parent != null) { enqueues.setParent(parent.enqueues); dispatched.setParent(parent.dispatched); dequeues.setParent(parent.dequeues); @@ -211,8 +176,7 @@ public class AMQDestinationStatistics extends StatsImpl blockedTime.setParent(parent.blockedTime); messageSize.setParent(parent.messageSize); } - else - { + else { enqueues.setParent(null); dispatched.setParent(null); dequeues.setParent(null); diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQMessageAuthorizationPolicy.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQMessageAuthorizationPolicy.java index a79b2151c2..7401514d8f 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQMessageAuthorizationPolicy.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQMessageAuthorizationPolicy.java @@ -18,8 +18,7 @@ package org.apache.activemq.artemis.core.protocol.openwire.amq; import org.apache.activemq.command.Message; -public interface AMQMessageAuthorizationPolicy -{ +public interface AMQMessageAuthorizationPolicy { /** * Returns true if the given message is able to be dispatched to the connection diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQMessageStore.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQMessageStore.java index 4b10af8a8f..281c6dcb77 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQMessageStore.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQMessageStore.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.core.protocol.openwire.amq; -public interface AMQMessageStore -{ +public interface AMQMessageStore { } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQPersistenceAdapter.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQPersistenceAdapter.java index bdcfdee458..00d9742229 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQPersistenceAdapter.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQPersistenceAdapter.java @@ -23,8 +23,7 @@ import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ProducerId; -public class AMQPersistenceAdapter -{ +public class AMQPersistenceAdapter { /** * Returns a set of all the {@link org.apache.activemq.command.ActiveMQDestination} @@ -32,19 +31,18 @@ public class AMQPersistenceAdapter * * @return active destinations */ - Set getDestinations() - { + Set getDestinations() { return null; } /** * Factory method to create a new queue message store with the given destination name + * * @param destination * @return the message store * @throws IOException */ - AMQMessageStore createQueueMessageStore(ActiveMQQueue destination) throws IOException - { + AMQMessageStore createQueueMessageStore(ActiveMQQueue destination) throws IOException { return null; } @@ -52,11 +50,11 @@ public class AMQPersistenceAdapter * return the last stored producer sequenceId for this producer Id * used to suppress duplicate sends on failover reconnect at the transport * when a reconnect occurs + * * @param id the producerId to find a sequenceId for * @return the last stored sequence id or -1 if no suppression needed */ - public long getLastProducerSequenceId(ProducerId id) - { + public long getLastProducerSequenceId(ProducerId id) { return 0; } } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQProducer.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQProducer.java index 0bdf875e7e..848325e19c 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQProducer.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQProducer.java @@ -19,22 +19,19 @@ package org.apache.activemq.artemis.core.protocol.openwire.amq; import org.apache.activemq.command.ProducerInfo; import org.apache.activemq.artemis.core.protocol.openwire.OpenWireUtil; -public class AMQProducer -{ +public class AMQProducer { + private AMQSession amqSession; private ProducerInfo info; - public AMQProducer(AMQSession amqSession, ProducerInfo info) - { + public AMQProducer(AMQSession amqSession, ProducerInfo info) { this.amqSession = amqSession; this.info = info; } - public void init() throws Exception - { + public void init() throws Exception { // If the destination is specified check that it exists. - if (info.getDestination() != null) - { + if (info.getDestination() != null) { OpenWireUtil.validateDestination(info.getDestination(), amqSession); } } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQProducerBrokerExchange.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQProducerBrokerExchange.java index 7a9c97e92d..d7648cc1c3 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQProducerBrokerExchange.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQProducerBrokerExchange.java @@ -23,8 +23,8 @@ import org.apache.activemq.command.Message; import org.apache.activemq.command.MessageId; import org.apache.activemq.state.ProducerState; -public class AMQProducerBrokerExchange -{ +public class AMQProducerBrokerExchange { + private AMQConnectionContext connectionContext; private AMQDestination regionDestination; private ProducerState producerState; @@ -34,12 +34,10 @@ public class AMQProducerBrokerExchange private boolean isNetworkProducer; private final FlowControlInfo flowControlInfo = new FlowControlInfo(); - public AMQProducerBrokerExchange() - { + public AMQProducerBrokerExchange() { } - public AMQProducerBrokerExchange copy() - { + public AMQProducerBrokerExchange copy() { AMQProducerBrokerExchange rc = new AMQProducerBrokerExchange(); rc.connectionContext = connectionContext.copy(); rc.regionDestination = regionDestination; @@ -51,68 +49,56 @@ public class AMQProducerBrokerExchange /** * @return the connectionContext */ - public AMQConnectionContext getConnectionContext() - { + public AMQConnectionContext getConnectionContext() { return this.connectionContext; } /** - * @param connectionContext - * the connectionContext to set + * @param connectionContext the connectionContext to set */ - public void setConnectionContext(AMQConnectionContext connectionContext) - { + public void setConnectionContext(AMQConnectionContext connectionContext) { this.connectionContext = connectionContext; } /** * @return the mutable */ - public boolean isMutable() - { + public boolean isMutable() { return this.mutable; } /** - * @param mutable - * the mutable to set + * @param mutable the mutable to set */ - public void setMutable(boolean mutable) - { + public void setMutable(boolean mutable) { this.mutable = mutable; } /** * @return the regionDestination */ - public AMQDestination getRegionDestination() - { + public AMQDestination getRegionDestination() { return this.regionDestination; } /** - * @param regionDestination - * the regionDestination to set + * @param regionDestination the regionDestination to set */ - public void setRegionDestination(AMQDestination regionDestination) - { + public void setRegionDestination(AMQDestination regionDestination) { this.regionDestination = regionDestination; } /** * @return the producerState */ - public ProducerState getProducerState() - { + public ProducerState getProducerState() { return this.producerState; } /** - * @param producerState - * the producerState to set + * @param producerState the producerState to set */ - public void setProducerState(ProducerState producerState) - { + public void setProducerState(ProducerState producerState) { this.producerState = producerState; } @@ -121,36 +107,26 @@ public class AMQProducerBrokerExchange * * @return false if message should be ignored as a duplicate */ - public boolean canDispatch(Message messageSend) - { + public boolean canDispatch(Message messageSend) { boolean canDispatch = true; - if (auditProducerSequenceIds && messageSend.isPersistent()) - { - final long producerSequenceId = messageSend.getMessageId() - .getProducerSequenceId(); - if (isNetworkProducer) - { + if (auditProducerSequenceIds && messageSend.isPersistent()) { + final long producerSequenceId = messageSend.getMessageId().getProducerSequenceId(); + if (isNetworkProducer) { // messages are multiplexed on this producer so we need to query the // persistenceAdapter - long lastStoredForMessageProducer = getStoredSequenceIdForMessage(messageSend - .getMessageId()); - if (producerSequenceId <= lastStoredForMessageProducer) - { + long lastStoredForMessageProducer = getStoredSequenceIdForMessage(messageSend.getMessageId()); + if (producerSequenceId <= lastStoredForMessageProducer) { canDispatch = false; } } - else if (producerSequenceId <= lastSendSequenceNumber.get()) - { + else if (producerSequenceId <= lastSendSequenceNumber.get()) { canDispatch = false; - if (messageSend.isInTransaction()) - { + if (messageSend.isInTransaction()) { } - else - { + else { } } - else - { + else { // track current so we can suppress duplicates later in the stream lastSendSequenceNumber.set(producerSequenceId); } @@ -158,105 +134,85 @@ public class AMQProducerBrokerExchange return canDispatch; } - private long getStoredSequenceIdForMessage(MessageId messageId) - { + private long getStoredSequenceIdForMessage(MessageId messageId) { return -1; } - public void setLastStoredSequenceId(long l) - { + public void setLastStoredSequenceId(long l) { } - public void incrementSend() - { + public void incrementSend() { flowControlInfo.incrementSend(); } - public void blockingOnFlowControl(boolean blockingOnFlowControl) - { + public void blockingOnFlowControl(boolean blockingOnFlowControl) { flowControlInfo.setBlockingOnFlowControl(blockingOnFlowControl); } - public void incrementTimeBlocked(AMQDestination destination, long timeBlocked) - { + public void incrementTimeBlocked(AMQDestination destination, long timeBlocked) { flowControlInfo.incrementTimeBlocked(timeBlocked); } - public boolean isBlockedForFlowControl() - { + public boolean isBlockedForFlowControl() { return flowControlInfo.isBlockingOnFlowControl(); } - public void resetFlowControl() - { + public void resetFlowControl() { flowControlInfo.reset(); } - public long getTotalTimeBlocked() - { + public long getTotalTimeBlocked() { return flowControlInfo.getTotalTimeBlocked(); } - public int getPercentageBlocked() - { - double value = flowControlInfo.getSendsBlocked() - / flowControlInfo.getTotalSends(); + public int getPercentageBlocked() { + double value = flowControlInfo.getSendsBlocked() / flowControlInfo.getTotalSends(); return (int) value * 100; } - public static class FlowControlInfo - { + public static class FlowControlInfo { + private AtomicBoolean blockingOnFlowControl = new AtomicBoolean(); private AtomicLong totalSends = new AtomicLong(); private AtomicLong sendsBlocked = new AtomicLong(); private AtomicLong totalTimeBlocked = new AtomicLong(); - public boolean isBlockingOnFlowControl() - { + public boolean isBlockingOnFlowControl() { return blockingOnFlowControl.get(); } - public void setBlockingOnFlowControl(boolean blockingOnFlowControl) - { + public void setBlockingOnFlowControl(boolean blockingOnFlowControl) { this.blockingOnFlowControl.set(blockingOnFlowControl); - if (blockingOnFlowControl) - { + if (blockingOnFlowControl) { incrementSendBlocked(); } } - public long getTotalSends() - { + public long getTotalSends() { return totalSends.get(); } - public void incrementSend() - { + public void incrementSend() { this.totalSends.incrementAndGet(); } - public long getSendsBlocked() - { + public long getSendsBlocked() { return sendsBlocked.get(); } - public void incrementSendBlocked() - { + public void incrementSendBlocked() { this.sendsBlocked.incrementAndGet(); } - public long getTotalTimeBlocked() - { + public long getTotalTimeBlocked() { return totalTimeBlocked.get(); } - public void incrementTimeBlocked(long time) - { + public void incrementTimeBlocked(long time) { this.totalTimeBlocked.addAndGet(time); } - public void reset() - { + public void reset() { blockingOnFlowControl.set(false); totalSends.set(0); sendsBlocked.set(0); diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSecurityContext.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSecurityContext.java index 8cc6238468..539e18e74c 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSecurityContext.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSecurityContext.java @@ -26,20 +26,15 @@ import java.util.concurrent.ConcurrentMap; import org.apache.activemq.command.ActiveMQDestination; -public abstract class AMQSecurityContext -{ +public abstract class AMQSecurityContext { - public static final AMQSecurityContext BROKER_SECURITY_CONTEXT = new AMQSecurityContext( - "ActiveMQBroker") - { + public static final AMQSecurityContext BROKER_SECURITY_CONTEXT = new AMQSecurityContext("ActiveMQBroker") { @Override - public boolean isBrokerContext() - { + public boolean isBrokerContext() { return true; } - public Set getPrincipals() - { + public Set getPrincipals() { return Collections.emptySet(); } }; @@ -49,21 +44,17 @@ public abstract class AMQSecurityContext final ConcurrentMap authorizedReadDests = new ConcurrentHashMap(); final ConcurrentMap authorizedWriteDests = new ConcurrentHashMap(); - public AMQSecurityContext(String userName) - { + public AMQSecurityContext(String userName) { this.userName = userName; } - public boolean isInOneOf(Set allowedPrincipals) - { + public boolean isInOneOf(Set allowedPrincipals) { Iterator allowedIter = allowedPrincipals.iterator(); HashSet userPrincipals = new HashSet(getPrincipals()); - while (allowedIter.hasNext()) - { + while (allowedIter.hasNext()) { Iterator userIter = userPrincipals.iterator(); Object allowedPrincipal = allowedIter.next(); - while (userIter.hasNext()) - { + while (userIter.hasNext()) { if (allowedPrincipal.equals(userIter.next())) return true; } @@ -73,23 +64,19 @@ public abstract class AMQSecurityContext public abstract Set getPrincipals(); - public String getUserName() - { + public String getUserName() { return userName; } - public ConcurrentMap getAuthorizedReadDests() - { + public ConcurrentMap getAuthorizedReadDests() { return authorizedReadDests; } - public ConcurrentMap getAuthorizedWriteDests() - { + public ConcurrentMap getAuthorizedWriteDests() { return authorizedWriteDests; } - public boolean isBrokerContext() - { + public boolean isBrokerContext() { return false; } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQServerConsumer.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQServerConsumer.java index f4aac5a5f8..b0ec7ed3c6 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQServerConsumer.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQServerConsumer.java @@ -31,62 +31,56 @@ import org.apache.activemq.artemis.core.server.impl.ServerConsumerImpl; import org.apache.activemq.artemis.core.server.management.ManagementService; import org.apache.activemq.artemis.spi.core.protocol.SessionCallback; -public class AMQServerConsumer extends ServerConsumerImpl -{ +public class AMQServerConsumer extends ServerConsumerImpl { - public AMQServerConsumer(long consumerID, AMQServerSession serverSession, - QueueBinding binding, Filter filter, boolean started, - boolean browseOnly, StorageManager storageManager, - SessionCallback callback, boolean preAcknowledge, - boolean strictUpdateDeliveryCount, - ManagementService managementService, boolean supportLargeMessage, - Integer credits) throws Exception - { - super(consumerID, serverSession, binding, filter, started, browseOnly, storageManager, - callback, preAcknowledge, strictUpdateDeliveryCount, managementService, - supportLargeMessage, credits); + public AMQServerConsumer(long consumerID, + AMQServerSession serverSession, + QueueBinding binding, + Filter filter, + boolean started, + boolean browseOnly, + StorageManager storageManager, + SessionCallback callback, + boolean preAcknowledge, + boolean strictUpdateDeliveryCount, + ManagementService managementService, + boolean supportLargeMessage, + Integer credits) throws Exception { + super(consumerID, serverSession, binding, filter, started, browseOnly, storageManager, callback, preAcknowledge, strictUpdateDeliveryCount, managementService, supportLargeMessage, credits); } - public void setBrowserListener(BrowserListener listener) - { + public void setBrowserListener(BrowserListener listener) { AMQBrowserDeliverer newBrowserDeliverer = new AMQBrowserDeliverer(this.browserDeliverer); newBrowserDeliverer.listener = listener; this.browserDeliverer = newBrowserDeliverer; } - private class AMQBrowserDeliverer extends BrowserDeliverer - { + private class AMQBrowserDeliverer extends BrowserDeliverer { + private BrowserListener listener = null; - public AMQBrowserDeliverer(final BrowserDeliverer other) - { + public AMQBrowserDeliverer(final BrowserDeliverer other) { super(other.iterator); } @Override - public synchronized void run() - { + public synchronized void run() { // if the reference was busy during the previous iteration, handle it now - if (current != null) - { - try - { + if (current != null) { + try { HandleStatus status = handle(current); - if (status == HandleStatus.BUSY) - { + if (status == HandleStatus.BUSY) { return; } - if (status == HandleStatus.HANDLED) - { + if (status == HandleStatus.HANDLED) { proceedDeliver(current); } current = null; } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorBrowserHandlingMessage(e, current); return; } @@ -95,18 +89,13 @@ public class AMQServerConsumer extends ServerConsumerImpl MessageReference ref = null; HandleStatus status; - while (true) - { - try - { + while (true) { + try { ref = null; - synchronized (messageQueue) - { - if (!iterator.hasNext()) - { + synchronized (messageQueue) { + if (!iterator.hasNext()) { //here we need to send a null for amq browsers - if (listener != null) - { + if (listener != null) { listener.browseFinished(); } break; @@ -117,20 +106,17 @@ public class AMQServerConsumer extends ServerConsumerImpl status = handle(ref); } - if (status == HandleStatus.HANDLED) - { + if (status == HandleStatus.HANDLED) { proceedDeliver(ref); } - else if (status == HandleStatus.BUSY) - { + else if (status == HandleStatus.BUSY) { // keep a reference on the current message reference // to handle it next time the browser deliverer is executed current = ref; break; } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorBrowserHandlingMessage(e, ref); break; } @@ -138,24 +124,19 @@ public class AMQServerConsumer extends ServerConsumerImpl } } - public void amqPutBackToDeliveringList(final List refs) - { - synchronized (this.deliveringRefs) - { - for (MessageReference ref : refs) - { + public void amqPutBackToDeliveringList(final List refs) { + synchronized (this.deliveringRefs) { + for (MessageReference ref : refs) { ref.incrementDeliveryCount(); deliveringRefs.add(ref); } //adjust the order. Suppose deliveringRefs has 2 existing //refs m1, m2, and refs has 3 m3, m4, m5 //new order must be m3, m4, m5, m1, m2 - if (refs.size() > 0) - { + if (refs.size() > 0) { long first = refs.get(0).getMessage().getMessageID(); MessageReference m = deliveringRefs.peek(); - while (m.getMessage().getMessageID() != first) - { + while (m.getMessage().getMessageID() != first) { deliveringRefs.poll(); deliveringRefs.add(m); m = deliveringRefs.peek(); @@ -164,21 +145,18 @@ public class AMQServerConsumer extends ServerConsumerImpl } } - public void moveToDeadLetterAddress(long mid, Throwable cause) throws Exception - { + public void moveToDeadLetterAddress(long mid, Throwable cause) throws Exception { MessageReference ref = removeReferenceByID(mid); - if (ref == null) - { + if (ref == null) { throw new IllegalStateException("Cannot find ref to ack " + mid); } ServerMessage coreMsg = ref.getMessage(); coreMsg.putStringProperty(OpenWireMessageConverter.AMQ_MSG_DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY, cause.toString()); - QueueImpl queue = (QueueImpl)ref.getQueue(); - synchronized (queue) - { + QueueImpl queue = (QueueImpl) ref.getQueue(); + synchronized (queue) { queue.sendToDeadLetterAddress(ref); queue.decDelivering(); } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQServerSession.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQServerSession.java index a28bcfe806..4094a823ef 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQServerSession.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQServerSession.java @@ -60,73 +60,63 @@ import org.apache.activemq.artemis.spi.core.protocol.SessionCallback; import org.apache.activemq.artemis.utils.TypedProperties; import org.apache.activemq.artemis.utils.UUID; -public class AMQServerSession extends ServerSessionImpl -{ +public class AMQServerSession extends ServerSessionImpl { + private boolean internal; - public AMQServerSession(String name, String username, String password, - int minLargeMessageSize, boolean autoCommitSends, - boolean autoCommitAcks, boolean preAcknowledge, - boolean persistDeliveryCountBeforeDelivery, boolean xa, - RemotingConnection connection, StorageManager storageManager, - PostOffice postOffice, ResourceManager resourceManager, - SecurityStore securityStore, ManagementService managementService, - ActiveMQServerImpl activeMQServerImpl, SimpleString managementAddress, - SimpleString simpleString, SessionCallback callback, - QueueCreator queueCreator, - OperationContext context) throws Exception - { - super(name, username, password, - minLargeMessageSize, autoCommitSends, - autoCommitAcks, preAcknowledge, - persistDeliveryCountBeforeDelivery, xa, - connection, storageManager, - postOffice, resourceManager, - securityStore, managementService, - activeMQServerImpl, managementAddress, - simpleString, callback, - context, new AMQTransactionFactory(), - queueCreator); + public AMQServerSession(String name, + String username, + String password, + int minLargeMessageSize, + boolean autoCommitSends, + boolean autoCommitAcks, + boolean preAcknowledge, + boolean persistDeliveryCountBeforeDelivery, + boolean xa, + RemotingConnection connection, + StorageManager storageManager, + PostOffice postOffice, + ResourceManager resourceManager, + SecurityStore securityStore, + ManagementService managementService, + ActiveMQServerImpl activeMQServerImpl, + SimpleString managementAddress, + SimpleString simpleString, + SessionCallback callback, + QueueCreator queueCreator, + OperationContext context) throws Exception { + super(name, username, password, minLargeMessageSize, autoCommitSends, autoCommitAcks, preAcknowledge, persistDeliveryCountBeforeDelivery, xa, connection, storageManager, postOffice, resourceManager, securityStore, managementService, activeMQServerImpl, managementAddress, simpleString, callback, context, new AMQTransactionFactory(), queueCreator); } //create a fake session just for security check - public AMQServerSession(String user, String pass) - { + public AMQServerSession(String user, String pass) { super(user, pass); } - protected void doClose(final boolean failed) throws Exception - { - synchronized (this) - { - if (tx != null && tx.getXid() == null) - { - ((AMQTransactionImpl)tx).setRollbackForClose(); + protected void doClose(final boolean failed) throws Exception { + synchronized (this) { + if (tx != null && tx.getXid() == null) { + ((AMQTransactionImpl) tx).setRollbackForClose(); } } super.doClose(failed); } - public AtomicInteger getConsumerCredits(final long consumerID) - { + public AtomicInteger getConsumerCredits(final long consumerID) { ServerConsumer consumer = consumers.get(consumerID); - if (consumer == null) - { + if (consumer == null) { ActiveMQServerLogger.LOGGER.debug("There is no consumer with id " + consumerID); return null; } - return ((ServerConsumerImpl)consumer).getAvailableCredits(); + return ((ServerConsumerImpl) consumer).getAvailableCredits(); } - public void enableXA() throws Exception - { - if (!this.xa) - { - if (this.tx != null) - { + public void enableXA() throws Exception { + if (!this.xa) { + if (this.tx != null) { //that's not expected, maybe a warning. this.tx.rollback(); this.tx = null; @@ -139,18 +129,15 @@ public class AMQServerSession extends ServerSessionImpl } } - public void enableTx() throws Exception - { - if (this.xa) - { + public void enableTx() throws Exception { + if (this.xa) { throw new IllegalStateException("Session is XA"); } this.autoCommitAcks = false; this.autoCommitSends = false; - if (this.tx != null) - { + if (this.tx != null) { //that's not expected, maybe a warning. this.tx.rollback(); this.tx = null; @@ -160,10 +147,8 @@ public class AMQServerSession extends ServerSessionImpl } //amq specific behavior - public void amqRollback(Set acked) throws Exception - { - if (tx == null) - { + public void amqRollback(Set acked) throws Exception { + if (tx == null) { // Might be null if XA tx = newTransaction(); @@ -171,54 +156,44 @@ public class AMQServerSession extends ServerSessionImpl RefsOperation oper = (RefsOperation) tx.getProperty(TransactionPropertyIndexes.REFS_OPERATION); - if (oper != null) - { + if (oper != null) { List ackRefs = oper.getReferencesToAcknowledge(); Map> toAcks = new HashMap>(); - for (MessageReference ref : ackRefs) - { + for (MessageReference ref : ackRefs) { Long consumerId = ref.getConsumerId(); - if (this.consumers.containsKey(consumerId)) - { - if (acked.contains(ref.getMessage().getMessageID())) - { + if (this.consumers.containsKey(consumerId)) { + if (acked.contains(ref.getMessage().getMessageID())) { List ackList = toAcks.get(consumerId); - if (ackList == null) - { + if (ackList == null) { ackList = new ArrayList(); toAcks.put(consumerId, ackList); } ackList.add(ref); } } - else - { + else { //consumer must have been closed, cancel to queue ref.getQueue().cancel(tx, ref); } } //iterate consumers - if (toAcks.size() > 0) - { + if (toAcks.size() > 0) { Iterator>> iter = toAcks.entrySet().iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { Entry> entry = iter.next(); ServerConsumer consumer = consumers.get(entry.getKey()); - ((AMQServerConsumer)consumer).amqPutBackToDeliveringList(entry.getValue()); + ((AMQServerConsumer) consumer).amqPutBackToDeliveringList(entry.getValue()); } } } tx.rollback(); - if (xa) - { + if (xa) { tx = null; } - else - { + else { tx = newTransaction(); } @@ -228,95 +203,68 @@ public class AMQServerSession extends ServerSessionImpl * The failed flag is used here to control delivery count. * If set to true the delivery count won't decrement. */ - public void amqCloseConsumer(long consumerID, boolean failed) throws Exception - { + public void amqCloseConsumer(long consumerID, boolean failed) throws Exception { final ServerConsumer consumer = consumers.get(consumerID); - if (consumer != null) - { + if (consumer != null) { consumer.close(failed); } - else - { + else { ActiveMQServerLogger.LOGGER.cannotFindConsumer(consumerID); } } @Override public ServerConsumer createConsumer(final long consumerID, - final SimpleString queueName, - final SimpleString filterString, - final boolean browseOnly, - final boolean supportLargeMessage, - final Integer credits) throws Exception - { - if (this.internal) - { + final SimpleString queueName, + final SimpleString filterString, + final boolean browseOnly, + final boolean supportLargeMessage, + final Integer credits) throws Exception { + if (this.internal) { //internal sessions doesn't check security Binding binding = postOffice.getBinding(queueName); - if (binding == null || binding.getType() != BindingType.LOCAL_QUEUE) - { + if (binding == null || binding.getType() != BindingType.LOCAL_QUEUE) { throw ActiveMQMessageBundle.BUNDLE.noSuchQueue(queueName); } Filter filter = FilterImpl.createFilter(filterString); - ServerConsumer consumer = newConsumer(consumerID, this, - (QueueBinding) binding, filter, started, browseOnly, - storageManager, callback, preAcknowledge, - strictUpdateDeliveryCount, managementService, - supportLargeMessage, credits); + ServerConsumer consumer = newConsumer(consumerID, this, (QueueBinding) binding, filter, started, browseOnly, storageManager, callback, preAcknowledge, strictUpdateDeliveryCount, managementService, supportLargeMessage, credits); consumers.put(consumer.getID(), consumer); - if (!browseOnly) - { + if (!browseOnly) { TypedProperties props = new TypedProperties(); - props.putSimpleStringProperty(ManagementHelper.HDR_ADDRESS, - binding.getAddress()); + props.putSimpleStringProperty(ManagementHelper.HDR_ADDRESS, binding.getAddress()); - props.putSimpleStringProperty(ManagementHelper.HDR_CLUSTER_NAME, - binding.getClusterName()); + props.putSimpleStringProperty(ManagementHelper.HDR_CLUSTER_NAME, binding.getClusterName()); - props.putSimpleStringProperty(ManagementHelper.HDR_ROUTING_NAME, - binding.getRoutingName()); + props.putSimpleStringProperty(ManagementHelper.HDR_ROUTING_NAME, binding.getRoutingName()); - props.putIntProperty(ManagementHelper.HDR_DISTANCE, - binding.getDistance()); + props.putIntProperty(ManagementHelper.HDR_DISTANCE, binding.getDistance()); Queue theQueue = (Queue) binding.getBindable(); - props.putIntProperty(ManagementHelper.HDR_CONSUMER_COUNT, - theQueue.getConsumerCount()); + props.putIntProperty(ManagementHelper.HDR_CONSUMER_COUNT, theQueue.getConsumerCount()); // HORNETQ-946 - props.putSimpleStringProperty(ManagementHelper.HDR_USER, - SimpleString.toSimpleString(username)); + props.putSimpleStringProperty(ManagementHelper.HDR_USER, SimpleString.toSimpleString(username)); - props.putSimpleStringProperty(ManagementHelper.HDR_REMOTE_ADDRESS, - SimpleString.toSimpleString(this.remotingConnection - .getRemoteAddress())); + props.putSimpleStringProperty(ManagementHelper.HDR_REMOTE_ADDRESS, SimpleString.toSimpleString(this.remotingConnection.getRemoteAddress())); - props.putSimpleStringProperty(ManagementHelper.HDR_SESSION_NAME, - SimpleString.toSimpleString(name)); + props.putSimpleStringProperty(ManagementHelper.HDR_SESSION_NAME, SimpleString.toSimpleString(name)); - if (filterString != null) - { - props.putSimpleStringProperty(ManagementHelper.HDR_FILTERSTRING, - filterString); + if (filterString != null) { + props.putSimpleStringProperty(ManagementHelper.HDR_FILTERSTRING, filterString); } - Notification notification = new Notification(null, - CoreNotificationType.CONSUMER_CREATED, props); + Notification notification = new Notification(null, CoreNotificationType.CONSUMER_CREATED, props); - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { - ActiveMQServerLogger.LOGGER.debug("Session with user=" + username - + ", connection=" + this.remotingConnection - + " created a consumer on queue " + queueName - + ", filter = " + filterString); + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { + ActiveMQServerLogger.LOGGER.debug("Session with user=" + username + ", connection=" + this.remotingConnection + " created a consumer on queue " + queueName + ", filter = " + filterString); } managementService.sendNotification(notification); @@ -324,28 +272,24 @@ public class AMQServerSession extends ServerSessionImpl return consumer; } - else - { + else { return super.createConsumer(consumerID, queueName, filterString, browseOnly, supportLargeMessage, credits); } } @Override public Queue createQueue(final SimpleString address, - final SimpleString name, - final SimpleString filterString, - final boolean temporary, - final boolean durable) throws Exception - { - if (!this.internal) - { + final SimpleString name, + final SimpleString filterString, + final boolean temporary, + final boolean durable) throws Exception { + if (!this.internal) { return super.createQueue(address, name, filterString, temporary, durable); } Queue queue = server.createQueue(address, name, filterString, SimpleString.toSimpleString(getUsername()), durable, temporary); - if (temporary) - { + if (temporary) { // Temporary queue in core simply means the queue will be deleted if // the remoting connection // dies. It does not mean it will get deleted automatically when the @@ -360,97 +304,77 @@ public class AMQServerSession extends ServerSessionImpl tempQueueCleannerUppers.put(name, cleaner); } - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Queue " + name + " created on address " + name + - " with filter=" + filterString + " temporary = " + - temporary + " durable=" + durable + " on session user=" + this.username + ", connection=" + this.remotingConnection); + " with filter=" + filterString + " temporary = " + + temporary + " durable=" + durable + " on session user=" + this.username + ", connection=" + this.remotingConnection); } return queue; } @Override - protected void doSend(final ServerMessage msg, final boolean direct) throws Exception - { - if (!this.internal) - { + protected void doSend(final ServerMessage msg, final boolean direct) throws Exception { + if (!this.internal) { super.doSend(msg, direct); return; } //bypass security check for internal sessions - if (tx == null || autoCommitSends) - { + if (tx == null || autoCommitSends) { } - else - { + else { routingContext.setTransaction(tx); } - try - { + try { postOffice.route(msg, getQueueCreator(), routingContext, direct); Pair value = targetAddressInfos.get(msg.getAddress()); - if (value == null) - { + if (value == null) { targetAddressInfos.put(msg.getAddress(), new Pair(msg.getUserID(), new AtomicLong(1))); } - else - { + else { value.setA(msg.getUserID()); value.getB().incrementAndGet(); } } - finally - { + finally { routingContext.clear(); } } @Override protected ServerConsumer newConsumer(long consumerID, - ServerSessionImpl serverSessionImpl, QueueBinding binding, - Filter filter, boolean started2, boolean browseOnly, - StorageManager storageManager2, SessionCallback callback2, - boolean preAcknowledge2, boolean strictUpdateDeliveryCount2, - ManagementService managementService2, boolean supportLargeMessage, - Integer credits) throws Exception - { - return new AMQServerConsumer(consumerID, - this, - (QueueBinding) binding, - filter, - started, - browseOnly, - storageManager, - callback, - preAcknowledge, - strictUpdateDeliveryCount, - managementService, - supportLargeMessage, - credits); + ServerSessionImpl serverSessionImpl, + QueueBinding binding, + Filter filter, + boolean started2, + boolean browseOnly, + StorageManager storageManager2, + SessionCallback callback2, + boolean preAcknowledge2, + boolean strictUpdateDeliveryCount2, + ManagementService managementService2, + boolean supportLargeMessage, + Integer credits) throws Exception { + return new AMQServerConsumer(consumerID, this, (QueueBinding) binding, filter, started, browseOnly, storageManager, callback, preAcknowledge, strictUpdateDeliveryCount, managementService, supportLargeMessage, credits); } - public AMQServerConsumer getConsumer(long nativeId) - { + public AMQServerConsumer getConsumer(long nativeId) { return (AMQServerConsumer) this.consumers.get(nativeId); } - public void setInternal(boolean internal) - { + public void setInternal(boolean internal) { this.internal = internal; } - public boolean isInternal() - { + public boolean isInternal() { return this.internal; } - public void moveToDeadLetterAddress(long consumerId, long mid, Throwable cause) throws Exception - { + public void moveToDeadLetterAddress(long consumerId, long mid, Throwable cause) throws Exception { AMQServerConsumer consumer = getConsumer(consumerId); consumer.moveToDeadLetterAddress(mid, cause); } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQServerSessionFactory.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQServerSessionFactory.java index 62997df5fe..9ce21e3938 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQServerSessionFactory.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQServerSessionFactory.java @@ -30,26 +30,31 @@ import org.apache.activemq.artemis.core.transaction.ResourceManager; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; import org.apache.activemq.artemis.spi.core.protocol.SessionCallback; -public class AMQServerSessionFactory implements ServerSessionFactory -{ +public class AMQServerSessionFactory implements ServerSessionFactory { @Override - public ServerSessionImpl createCoreSession(String name, String username, - String password, int minLargeMessageSize, boolean autoCommitSends, - boolean autoCommitAcks, boolean preAcknowledge, - boolean persistDeliveryCountBeforeDelivery, boolean xa, - RemotingConnection connection, StorageManager storageManager, - PostOffice postOffice, ResourceManager resourceManager, - SecurityStore securityStore, ManagementService managementService, - ActiveMQServerImpl activeMQServerImpl, SimpleString managementAddress, - SimpleString simpleString, SessionCallback callback, QueueCreator queueCreator, - OperationContext context) throws Exception - { - return new AMQServerSession(name, username, password, minLargeMessageSize, autoCommitSends, - autoCommitAcks, preAcknowledge, persistDeliveryCountBeforeDelivery, xa, - connection, storageManager, postOffice, resourceManager, securityStore, - managementService, activeMQServerImpl, managementAddress, simpleString, callback, queueCreator, - context); + public ServerSessionImpl createCoreSession(String name, + String username, + String password, + int minLargeMessageSize, + boolean autoCommitSends, + boolean autoCommitAcks, + boolean preAcknowledge, + boolean persistDeliveryCountBeforeDelivery, + boolean xa, + RemotingConnection connection, + StorageManager storageManager, + PostOffice postOffice, + ResourceManager resourceManager, + SecurityStore securityStore, + ManagementService managementService, + ActiveMQServerImpl activeMQServerImpl, + SimpleString managementAddress, + SimpleString simpleString, + SessionCallback callback, + QueueCreator queueCreator, + OperationContext context) throws Exception { + return new AMQServerSession(name, username, password, minLargeMessageSize, autoCommitSends, autoCommitAcks, preAcknowledge, persistDeliveryCountBeforeDelivery, xa, connection, storageManager, postOffice, resourceManager, securityStore, managementService, activeMQServerImpl, managementAddress, simpleString, callback, queueCreator, context); } } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSession.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSession.java index 2c24903339..1d285e00f9 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSession.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSession.java @@ -61,8 +61,8 @@ import org.apache.activemq.artemis.spi.core.protocol.SessionCallback; import org.apache.activemq.artemis.spi.core.remoting.ReadyListener; import org.apache.activemq.wireformat.WireFormat; -public class AMQSession implements SessionCallback -{ +public class AMQSession implements SessionCallback { + private AMQServerSession coreSession; private ConnectionInfo connInfo; private SessionInfo sessInfo; @@ -83,9 +83,12 @@ public class AMQSession implements SessionCallback private OpenWireProtocolManager manager; - public AMQSession(ConnectionInfo connInfo, SessionInfo sessInfo, - ActiveMQServer server, OpenWireConnection connection, ScheduledExecutorService scheduledPool, OpenWireProtocolManager manager) - { + public AMQSession(ConnectionInfo connInfo, + SessionInfo sessInfo, + ActiveMQServer server, + OpenWireConnection connection, + ScheduledExecutorService scheduledPool, + OpenWireProtocolManager manager) { this.connInfo = connInfo; this.sessInfo = sessInfo; this.server = server; @@ -94,53 +97,42 @@ public class AMQSession implements SessionCallback this.manager = manager; } - public void initialize() - { + public void initialize() { String name = sessInfo.getSessionId().toString(); String username = connInfo.getUserName(); String password = connInfo.getPassword(); int minLargeMessageSize = Integer.MAX_VALUE; // disable - // minLargeMessageSize for - // now + // minLargeMessageSize for + // now - try - { - coreSession = (AMQServerSession) server.createSession(name, username, password, - minLargeMessageSize, connection, true, false, false, false, - null, this, new AMQServerSessionFactory(), true); + try { + coreSession = (AMQServerSession) server.createSession(name, username, password, minLargeMessageSize, connection, true, false, false, false, null, this, new AMQServerSessionFactory(), true); long sessionId = sessInfo.getSessionId().getValue(); - if (sessionId == -1) - { + if (sessionId == -1) { this.connection.setAdvisorySession(this); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.error("error init session", e); } } - public void createConsumer(ConsumerInfo info, AMQSession amqSession) throws Exception - { + public void createConsumer(ConsumerInfo info, AMQSession amqSession) throws Exception { //check destination ActiveMQDestination dest = info.getDestination(); ActiveMQDestination[] dests = null; - if (dest.isComposite()) - { + if (dest.isComposite()) { dests = dest.getCompositeDestinations(); } - else - { - dests = new ActiveMQDestination[] {dest}; + else { + dests = new ActiveMQDestination[]{dest}; } Map consumerMap = new HashMap<>(); - for (ActiveMQDestination d : dests) - { - if (d.isQueue()) - { + for (ActiveMQDestination d : dests) { + if (d.isQueue()) { SimpleString queueName = OpenWireUtil.toCoreAddress(d); getCoreServer().getJMSQueueCreator().create(queueName); } @@ -156,119 +148,103 @@ public class AMQSession implements SessionCallback } @Override - public void sendProducerCreditsMessage(int credits, SimpleString address) - { + public void sendProducerCreditsMessage(int credits, SimpleString address) { // TODO Auto-generated method stub } @Override - public void sendProducerCreditsFailMessage(int credits, SimpleString address) - { + public void sendProducerCreditsFailMessage(int credits, SimpleString address) { // TODO Auto-generated method stub } @Override - public int sendMessage(ServerMessage message, ServerConsumer consumerID, int deliveryCount) - { + public int sendMessage(ServerMessage message, ServerConsumer consumerID, int deliveryCount) { AMQConsumer consumer = consumers.get(consumerID.getID()); return consumer.handleDeliver(message, deliveryCount); } @Override - public int sendLargeMessage(ServerMessage message, ServerConsumer consumerID, - long bodySize, int deliveryCount) - { + public int sendLargeMessage(ServerMessage message, ServerConsumer consumerID, long bodySize, int deliveryCount) { // TODO Auto-generated method stub return 0; } @Override - public int sendLargeMessageContinuation(ServerConsumer consumerID, byte[] body, - boolean continues, boolean requiresResponse) - { + public int sendLargeMessageContinuation(ServerConsumer consumerID, + byte[] body, + boolean continues, + boolean requiresResponse) { // TODO Auto-generated method stub return 0; } @Override - public void closed() - { + public void closed() { // TODO Auto-generated method stub } @Override - public void addReadyListener(ReadyListener listener) - { + public void addReadyListener(ReadyListener listener) { // TODO Auto-generated method stub } @Override - public void removeReadyListener(ReadyListener listener) - { + public void removeReadyListener(ReadyListener listener) { // TODO Auto-generated method stub } @Override - public boolean hasCredits(ServerConsumer consumerID) - { + public boolean hasCredits(ServerConsumer consumerID) { AMQConsumer amqConsumer = consumers.get(consumerID.getID()); return amqConsumer.hasCredits(); } @Override - public void disconnect(ServerConsumer consumerId, String queueName) - { + public void disconnect(ServerConsumer consumerId, String queueName) { // TODO Auto-generated method stub } - public AMQServerSession getCoreSession() - { + public AMQServerSession getCoreSession() { return this.coreSession; } - public ActiveMQServer getCoreServer() - { + public ActiveMQServer getCoreServer() { return this.server; } - public void removeConsumer(long consumerId) throws Exception - { + public void removeConsumer(long consumerId) throws Exception { boolean failed = !(this.txId != null || this.isTx); coreSession.amqCloseConsumer(consumerId, failed); consumers.remove(consumerId); } - public void createProducer(ProducerInfo info) throws Exception - { + public void createProducer(ProducerInfo info) throws Exception { AMQProducer producer = new AMQProducer(this, info); producer.init(); producers.put(info.getProducerId().getValue(), producer); } - public void removeProducer(ProducerInfo info) - { + public void removeProducer(ProducerInfo info) { removeProducer(info.getProducerId()); } - public void removeProducer(ProducerId id) - { + public void removeProducer(ProducerId id) { producers.remove(id.getValue()); } public SendingResult send(AMQProducerBrokerExchange producerExchange, - Message messageSend, boolean sendProducerAck) throws Exception - { + Message messageSend, + boolean sendProducerAck) throws Exception { SendingResult result = new SendingResult(); TransactionId tid = messageSend.getTransactionId(); - if (tid != null) - { + if (tid != null) { resetSessionTx(tid); } @@ -276,68 +252,57 @@ public class AMQSession implements SessionCallback ActiveMQDestination destination = messageSend.getDestination(); ActiveMQDestination[] actualDestinations = null; - if (destination.isComposite()) - { + if (destination.isComposite()) { actualDestinations = destination.getCompositeDestinations(); } - else - { - actualDestinations = new ActiveMQDestination[] {destination}; + else { + actualDestinations = new ActiveMQDestination[]{destination}; } - for (ActiveMQDestination dest : actualDestinations) - { + for (ActiveMQDestination dest : actualDestinations) { ServerMessageImpl coreMsg = new ServerMessageImpl(-1, 1024); /* ActiveMQ failover transport will attempt to reconnect after connection failure. Any sent messages that did * not receive acks will be resent. (ActiveMQ broker handles this by returning a last sequence id received to * the client). To handle this in Artemis we use a duplicate ID cache. To do this we check to see if the * message comes from failover connection. If so we add a DUPLICATE_ID to handle duplicates after a resend. */ - if (producerExchange.getConnectionContext().isFaultTolerant() && !messageSend.getProperties().containsKey(ServerMessage.HDR_DUPLICATE_DETECTION_ID)) - { + if (producerExchange.getConnectionContext().isFaultTolerant() && !messageSend.getProperties().containsKey(ServerMessage.HDR_DUPLICATE_DETECTION_ID)) { coreMsg.putStringProperty(ServerMessage.HDR_DUPLICATE_DETECTION_ID.toString(), messageSend.getMessageId().toString()); } OpenWireMessageConverter.toCoreMessage(coreMsg, messageSend, connection.getMarshaller()); SimpleString address = OpenWireUtil.toCoreAddress(dest); coreMsg.setAddress(address); - PagingStoreImpl store = (PagingStoreImpl)server.getPagingManager().getPageStore(address); - if (store.isFull()) - { + PagingStoreImpl store = (PagingStoreImpl) server.getPagingManager().getPageStore(address); + if (store.isFull()) { result.setBlockNextSend(true); result.setBlockPagingStore(store); result.setBlockingAddress(address); //now we hold this message send until the store has space. //we do this by put it in a scheduled task ScheduledExecutorService scheduler = server.getScheduledPool(); - Runnable sendRetryTask = new SendRetryTask(coreMsg, producerExchange, sendProducerAck, - messageSend.getSize(), messageSend.getCommandId()); + Runnable sendRetryTask = new SendRetryTask(coreMsg, producerExchange, sendProducerAck, messageSend.getSize(), messageSend.getCommandId()); scheduler.schedule(sendRetryTask, 10, TimeUnit.MILLISECONDS); } - else - { + else { coreSession.send(coreMsg, false); } } return result; } - public WireFormat getMarshaller() - { + public WireFormat getMarshaller() { return this.connection.getMarshaller(); } - public void acknowledge(MessageAck ack, AMQConsumer consumer) throws Exception - { + public void acknowledge(MessageAck ack, AMQConsumer consumer) throws Exception { TransactionId tid = ack.getTransactionId(); - if (tid != null) - { + if (tid != null) { this.resetSessionTx(ack.getTransactionId()); } consumer.acknowledge(ack); - if (tid == null && ack.getAckType() == MessageAck.STANDARD_ACK_TYPE) - { + if (tid == null && ack.getAckType() == MessageAck.STANDARD_ACK_TYPE) { this.coreSession.commit(); } } @@ -345,28 +310,23 @@ public class AMQSession implements SessionCallback //AMQ session and transactions are create separately. Whether a session //is transactional or not is known only when a TransactionInfo command //comes in. - public void resetSessionTx(TransactionId xid) throws Exception - { - if ((this.txId != null) && (!this.txId.equals(xid))) - { + public void resetSessionTx(TransactionId xid) throws Exception { + if ((this.txId != null) && (!this.txId.equals(xid))) { throw new IllegalStateException("Session already associated with a tx"); } this.isTx = true; - if (this.txId == null) - { + if (this.txId == null) { //now reset session this.txId = xid; - if (xid.isXATransaction()) - { - XATransactionId xaXid = (XATransactionId)xid; + if (xid.isXATransaction()) { + XATransactionId xaXid = (XATransactionId) xid; coreSession.enableXA(); XidImpl coreXid = new XidImpl(xaXid.getBranchQualifier(), xaXid.getFormatId(), xaXid.getGlobalTransactionId()); coreSession.xaStart(coreXid); } - else - { + else { coreSession.enableTx(); } @@ -374,49 +334,39 @@ public class AMQSession implements SessionCallback } } - private void checkTx(TransactionId inId) - { - if (this.txId == null) - { + private void checkTx(TransactionId inId) { + if (this.txId == null) { throw new IllegalStateException("Session has no transaction associated with it"); } - if (!this.txId.equals(inId)) - { + if (!this.txId.equals(inId)) { throw new IllegalStateException("Session already associated with another tx"); } this.isTx = true; } - - public void endTransaction(TransactionInfo info) throws Exception - { + public void endTransaction(TransactionInfo info) throws Exception { checkTx(info.getTransactionId()); - if (txId.isXATransaction()) - { + if (txId.isXATransaction()) { XATransactionId xid = (XATransactionId) txId; XidImpl coreXid = new XidImpl(xid.getBranchQualifier(), xid.getFormatId(), xid.getGlobalTransactionId()); this.coreSession.xaEnd(coreXid); } } - public void commitOnePhase(TransactionInfo info) throws Exception - { + public void commitOnePhase(TransactionInfo info) throws Exception { checkTx(info.getTransactionId()); - if (txId.isXATransaction()) - { + if (txId.isXATransaction()) { XATransactionId xid = (XATransactionId) txId; XidImpl coreXid = new XidImpl(xid.getBranchQualifier(), xid.getFormatId(), xid.getGlobalTransactionId()); this.coreSession.xaCommit(coreXid, true); } - else - { + else { Iterator iter = consumers.values().iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { AMQConsumer consumer = iter.next(); consumer.finishTx(); } @@ -426,15 +376,13 @@ public class AMQSession implements SessionCallback this.txId = null; } - public void prepareTransaction(XATransactionId xid) throws Exception - { + public void prepareTransaction(XATransactionId xid) throws Exception { checkTx(xid); XidImpl coreXid = new XidImpl(xid.getBranchQualifier(), xid.getFormatId(), xid.getGlobalTransactionId()); this.coreSession.xaPrepare(coreXid); } - public void commitTwoPhase(XATransactionId xid) throws Exception - { + public void commitTwoPhase(XATransactionId xid) throws Exception { checkTx(xid); XidImpl coreXid = new XidImpl(xid.getBranchQualifier(), xid.getFormatId(), xid.getGlobalTransactionId()); this.coreSession.xaCommit(coreXid, false); @@ -442,21 +390,17 @@ public class AMQSession implements SessionCallback this.txId = null; } - public void rollback(TransactionInfo info) throws Exception - { + public void rollback(TransactionInfo info) throws Exception { checkTx(info.getTransactionId()); - if (this.txId.isXATransaction()) - { + if (this.txId.isXATransaction()) { XATransactionId xid = (XATransactionId) txId; XidImpl coreXid = new XidImpl(xid.getBranchQualifier(), xid.getFormatId(), xid.getGlobalTransactionId()); this.coreSession.xaRollback(coreXid); } - else - { + else { Iterator iter = consumers.values().iterator(); Set acked = new HashSet(); - while (iter.hasNext()) - { + while (iter.hasNext()) { AMQConsumer consumer = iter.next(); consumer.rollbackTx(acked); } @@ -468,18 +412,15 @@ public class AMQSession implements SessionCallback this.txId = null; } - public void recover(List recovered) - { + public void recover(List recovered) { List xids = this.coreSession.xaGetInDoubtXids(); - for (Xid xid : xids) - { + for (Xid xid : xids) { XATransactionId amqXid = new XATransactionId(xid); recovered.add(amqXid); } } - public void forget(final TransactionId tid) throws Exception - { + public void forget(final TransactionId tid) throws Exception { checkTx(tid); XATransactionId xid = (XATransactionId) tid; XidImpl coreXid = new XidImpl(xid.getBranchQualifier(), xid.getFormatId(), xid.getGlobalTransactionId()); @@ -487,47 +428,43 @@ public class AMQSession implements SessionCallback this.txId = null; } - public ConnectionInfo getConnectionInfo() - { + public ConnectionInfo getConnectionInfo() { return this.connInfo; } - public void setInternal(boolean internal) - { + public void setInternal(boolean internal) { this.coreSession.setInternal(internal); } - public boolean isInternal() - { + public boolean isInternal() { return this.coreSession.isInternal(); } - public void deliverMessage(MessageDispatch dispatch) - { + public void deliverMessage(MessageDispatch dispatch) { this.connection.deliverMessage(dispatch); } - public void close() throws Exception - { + public void close() throws Exception { this.coreSession.close(false); } - public AMQConsumer getConsumer(Long coreConsumerId) - { + public AMQConsumer getConsumer(Long coreConsumerId) { return consumers.get(coreConsumerId); } - private class SendRetryTask implements Runnable - { + private class SendRetryTask implements Runnable { + private ServerMessage coreMsg; private AMQProducerBrokerExchange producerExchange; private boolean sendProducerAck; private int msgSize; private int commandId; - public SendRetryTask(ServerMessage coreMsg, AMQProducerBrokerExchange producerExchange, - boolean sendProducerAck, int msgSize, int commandId) - { + public SendRetryTask(ServerMessage coreMsg, + AMQProducerBrokerExchange producerExchange, + boolean sendProducerAck, + int msgSize, + int commandId) { this.coreMsg = coreMsg; this.producerExchange = producerExchange; this.sendProducerAck = sendProducerAck; @@ -536,44 +473,33 @@ public class AMQSession implements SessionCallback } @Override - public void run() - { - synchronized (AMQSession.this) - { - try - { + public void run() { + synchronized (AMQSession.this) { + try { // check pageStore SimpleString address = coreMsg.getAddress(); - PagingStoreImpl store = (PagingStoreImpl) server - .getPagingManager().getPageStore(address); - if (store.isFull()) - { + PagingStoreImpl store = (PagingStoreImpl) server.getPagingManager().getPageStore(address); + if (store.isFull()) { // if store is still full, schedule another server.getScheduledPool().schedule(this, 10, TimeUnit.MILLISECONDS); } - else - { + else { // now send the message again. coreSession.send(coreMsg, false); - if (sendProducerAck) - { - ProducerInfo producerInfo = producerExchange - .getProducerState().getInfo(); - ProducerAck ack = new ProducerAck( - producerInfo.getProducerId(), msgSize); + if (sendProducerAck) { + ProducerInfo producerInfo = producerExchange.getProducerState().getInfo(); + ProducerAck ack = new ProducerAck(producerInfo.getProducerId(), msgSize); connection.dispatchAsync(ack); } - else - { + else { Response response = new Response(); response.setCorrelationId(commandId); connection.dispatchAsync(response); } } } - catch (Exception e) - { + catch (Exception e) { ExceptionResponse response = new ExceptionResponse(e); response.setCorrelationId(commandId); connection.dispatchAsync(response); @@ -583,8 +509,8 @@ public class AMQSession implements SessionCallback } } - public void blockingWaitForSpace(AMQProducerBrokerExchange producerExchange, SendingResult result) throws IOException - { + public void blockingWaitForSpace(AMQProducerBrokerExchange producerExchange, + SendingResult result) throws IOException { long start = System.currentTimeMillis(); long nextWarn = start; producerExchange.blockingOnFlowControl(true); @@ -596,16 +522,13 @@ public class AMQSession implements SessionCallback long blockedProducerWarningInterval = 30000; ProducerId producerId = producerExchange.getProducerState().getInfo().getProducerId(); - while (store.isFull()) - { - if (context.getStopping().get()) - { + while (store.isFull()) { + if (context.getStopping().get()) { throw new IOException("Connection closed, send aborted."); } long now = System.currentTimeMillis(); - if (now >= nextWarn) - { + if (now >= nextWarn) { ActiveMQServerLogger.LOGGER.memoryLimitReached(producerId.toString(), result.getBlockingAddress().toString(), ((now - start) / 1000)); nextWarn = now + blockedProducerWarningInterval; } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSharedDeadLetterStrategy.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSharedDeadLetterStrategy.java index 44baf0633f..fe9bdf3d36 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSharedDeadLetterStrategy.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSharedDeadLetterStrategy.java @@ -20,38 +20,30 @@ import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.Message; -public class AMQSharedDeadLetterStrategy extends AMQAbstractDeadLetterStrategy -{ +public class AMQSharedDeadLetterStrategy extends AMQAbstractDeadLetterStrategy { + public static final String DEFAULT_DEAD_LETTER_QUEUE_NAME = "ActiveMQ.DLQ"; - private ActiveMQDestination deadLetterQueue = new ActiveMQQueue( - DEFAULT_DEAD_LETTER_QUEUE_NAME); + private ActiveMQDestination deadLetterQueue = new ActiveMQQueue(DEFAULT_DEAD_LETTER_QUEUE_NAME); - public ActiveMQDestination getDeadLetterQueueFor(Message message, - AMQSubscription subscription) - { + public ActiveMQDestination getDeadLetterQueueFor(Message message, AMQSubscription subscription) { return deadLetterQueue; } - public ActiveMQDestination getDeadLetterQueue() - { + public ActiveMQDestination getDeadLetterQueue() { return deadLetterQueue; } - public void setDeadLetterQueue(ActiveMQDestination deadLetterQueue) - { + public void setDeadLetterQueue(ActiveMQDestination deadLetterQueue) { this.deadLetterQueue = deadLetterQueue; } @Override - public boolean isDLQ(ActiveMQDestination destination) - { - if (destination.equals(deadLetterQueue)) - { + public boolean isDLQ(ActiveMQDestination destination) { + if (destination.equals(deadLetterQueue)) { return true; } - else - { + else { return false; } } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSingleConsumerBrokerExchange.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSingleConsumerBrokerExchange.java index 9a1d4f8179..7d3b2d1480 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSingleConsumerBrokerExchange.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSingleConsumerBrokerExchange.java @@ -19,28 +19,24 @@ package org.apache.activemq.artemis.core.protocol.openwire.amq; import org.apache.activemq.command.MessageAck; import org.apache.activemq.command.MessagePull; -public class AMQSingleConsumerBrokerExchange extends AMQConsumerBrokerExchange -{ +public class AMQSingleConsumerBrokerExchange extends AMQConsumerBrokerExchange { + private AMQConsumer consumer; - public AMQSingleConsumerBrokerExchange(AMQSession amqSession, AMQConsumer consumer) - { + public AMQSingleConsumerBrokerExchange(AMQSession amqSession, AMQConsumer consumer) { super(amqSession); this.consumer = consumer; } - public void processMessagePull(MessagePull messagePull) throws Exception - { + public void processMessagePull(MessagePull messagePull) throws Exception { consumer.processMessagePull(messagePull); } - public void removeConsumer() throws Exception - { + public void removeConsumer() throws Exception { consumer.removeConsumer(); } - public void acknowledge(MessageAck ack) throws Exception - { + public void acknowledge(MessageAck ack) throws Exception { amqSession.acknowledge(ack, consumer); } } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSlowConsumerStrategy.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSlowConsumerStrategy.java index f88167fa16..333dd0408d 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSlowConsumerStrategy.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSlowConsumerStrategy.java @@ -16,16 +16,13 @@ */ package org.apache.activemq.artemis.core.protocol.openwire.amq; -public interface AMQSlowConsumerStrategy -{ +public interface AMQSlowConsumerStrategy { /** * Slow consumer event. * - * @param context - * Connection context of the subscription. - * @param subs - * The subscription object for the slow consumer. + * @param context Connection context of the subscription. + * @param subs The subscription object for the slow consumer. */ void slowConsumer(AMQConnectionContext context, AMQSubscription subs); @@ -35,8 +32,7 @@ public interface AMQSlowConsumerStrategy * * If the strategy doesn't is event driven it can just ignore assigned destination. * - * @param destination - * A destination to add to a watch list. + * @param destination A destination to add to a watch list. */ void addDestination(AMQDestination destination); diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSubscription.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSubscription.java index f683eea5cd..a23d675a6d 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSubscription.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSubscription.java @@ -31,11 +31,11 @@ import org.apache.activemq.command.MessagePull; import org.apache.activemq.command.Response; import org.apache.activemq.filter.MessageEvaluationContext; -public interface AMQSubscription extends AMQSubscriptionRecovery -{ +public interface AMQSubscription extends AMQSubscriptionRecovery { /** * Used to add messages that match the subscription. + * * @param node * @throws Exception * @throws InterruptedException @@ -45,6 +45,7 @@ public interface AMQSubscription extends AMQSubscriptionRecovery /** * Used when client acknowledge receipt of dispatched message. + * * @throws IOException * @throws Exception */ @@ -57,12 +58,14 @@ public interface AMQSubscription extends AMQSubscriptionRecovery /** * Returns true if this subscription is a Wildcard subscription. + * * @return true if wildcard subscription. */ boolean isWildcard(); /** * Is the subscription interested in the message? + * * @param node * @param context * @return @@ -72,6 +75,7 @@ public interface AMQSubscription extends AMQSubscriptionRecovery /** * Is the subscription interested in messages in the destination? + * * @param destination * @return */ @@ -79,6 +83,7 @@ public interface AMQSubscription extends AMQSubscriptionRecovery /** * The subscription will be receiving messages from the destination. + * * @param context * @param destination * @throws Exception @@ -87,6 +92,7 @@ public interface AMQSubscription extends AMQSubscriptionRecovery /** * The subscription will be no longer be receiving messages from the destination. + * * @param context * @param destination * @return a list of un-acked messages that were added to the subscription. @@ -106,10 +112,11 @@ public interface AMQSubscription extends AMQSubscriptionRecovery /** * Used by a Slave Broker to update dispatch information + * * @param mdn * @throws Exception */ - void processMessageDispatchNotification(MessageDispatchNotification mdn) throws Exception; + void processMessageDispatchNotification(MessageDispatchNotification mdn) throws Exception; /** * @return number of messages pending delivery @@ -174,6 +181,7 @@ public interface AMQSubscription extends AMQSubscriptionRecovery /** * inform the MessageConsumer on the client to change it's prefetch + * * @param newPrefetch */ void updateConsumerPrefetch(int newPrefetch); @@ -201,6 +209,7 @@ public interface AMQSubscription extends AMQSubscriptionRecovery /** * Informs the Broker if the subscription needs to intervention to recover it's state * e.g. DurableTopicSubscriber may do + * * @return true if recovery required */ boolean isRecoveryRequired(); @@ -235,7 +244,7 @@ public interface AMQSubscription extends AMQSubscriptionRecovery */ long getTimeOfLastMessageAck(); - long getConsumedCount(); + long getConsumedCount(); void incrementConsumedCount(); diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSubscriptionRecovery.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSubscriptionRecovery.java index 74bf147157..1af2357824 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSubscriptionRecovery.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQSubscriptionRecovery.java @@ -22,11 +22,8 @@ import org.apache.activemq.command.ActiveMQDestination; /** * An interface for recoverying transient messages held by the broker for * retractive recovery for subscribers - * - * */ -public interface AMQSubscriptionRecovery -{ +public interface AMQSubscriptionRecovery { /** * Add a message to the SubscriptionRecovery diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQTransaction.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQTransaction.java index afd734e495..ed88110bd2 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQTransaction.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQTransaction.java @@ -31,8 +31,8 @@ import org.apache.activemq.command.TransactionId; import org.apache.activemq.transaction.Synchronization; import org.slf4j.Logger; -public abstract class AMQTransaction -{ +public abstract class AMQTransaction { + public static final byte START_STATE = 0; // can go to: 1,2,3 public static final byte IN_USE_STATE = 1; // can go to: 2,3 public static final byte PREPARED_STATE = 2; // can go to: 3 @@ -41,76 +41,59 @@ public abstract class AMQTransaction private final ArrayList synchronizations = new ArrayList(); private byte state = START_STATE; - protected FutureTask preCommitTask = new FutureTask( - new Callable() - { - public Object call() throws Exception - { - doPreCommit(); - return null; - } - }); - protected FutureTask postCommitTask = new FutureTask( - new Callable() - { - public Object call() throws Exception - { - doPostCommit(); - return null; - } - }); + protected FutureTask preCommitTask = new FutureTask(new Callable() { + public Object call() throws Exception { + doPreCommit(); + return null; + } + }); + protected FutureTask postCommitTask = new FutureTask(new Callable() { + public Object call() throws Exception { + doPostCommit(); + return null; + } + }); - public byte getState() - { + public byte getState() { return state; } - public void setState(byte state) - { + public void setState(byte state) { this.state = state; } - public boolean isCommitted() - { + public boolean isCommitted() { return committed; } - public void setCommitted(boolean committed) - { + public void setCommitted(boolean committed) { this.committed = committed; } - public void addSynchronization(Synchronization r) - { + public void addSynchronization(Synchronization r) { synchronizations.add(r); - if (state == START_STATE) - { + if (state == START_STATE) { state = IN_USE_STATE; } } - public Synchronization findMatching(Synchronization r) - { + public Synchronization findMatching(Synchronization r) { int existing = synchronizations.indexOf(r); - if (existing != -1) - { + if (existing != -1) { return synchronizations.get(existing); } return null; } - public void removeSynchronization(Synchronization r) - { + public void removeSynchronization(Synchronization r) { synchronizations.remove(r); } - public void prePrepare() throws Exception - { + public void prePrepare() throws Exception { // Is it ok to call prepare now given the state of the // transaction? - switch (state) - { + switch (state) { case START_STATE: case IN_USE_STATE: break; @@ -127,46 +110,34 @@ public abstract class AMQTransaction // } } - protected void fireBeforeCommit() throws Exception - { - for (Iterator iter = synchronizations.iterator(); iter - .hasNext();) - { + protected void fireBeforeCommit() throws Exception { + for (Iterator iter = synchronizations.iterator(); iter.hasNext(); ) { Synchronization s = iter.next(); s.beforeCommit(); } } - protected void fireAfterCommit() throws Exception - { - for (Iterator iter = synchronizations.iterator(); iter - .hasNext();) - { + protected void fireAfterCommit() throws Exception { + for (Iterator iter = synchronizations.iterator(); iter.hasNext(); ) { Synchronization s = iter.next(); s.afterCommit(); } } - public void fireAfterRollback() throws Exception - { + public void fireAfterRollback() throws Exception { Collections.reverse(synchronizations); - for (Iterator iter = synchronizations.iterator(); iter - .hasNext();) - { + for (Iterator iter = synchronizations.iterator(); iter.hasNext(); ) { Synchronization s = iter.next(); s.afterRollback(); } } @Override - public String toString() - { - return "Local-" + getTransactionId() + "[synchronizations=" - + synchronizations + "]"; + public String toString() { + return "Local-" + getTransactionId() + "[synchronizations=" + synchronizations + "]"; } - public abstract void commit(boolean onePhase) throws XAException, - IOException; + public abstract void commit(boolean onePhase) throws XAException, IOException; public abstract void rollback() throws XAException, IOException; @@ -176,52 +147,40 @@ public abstract class AMQTransaction public abstract Logger getLog(); - public boolean isPrepared() - { + public boolean isPrepared() { return getState() == PREPARED_STATE; } - public int size() - { + public int size() { return synchronizations.size(); } - protected void waitPostCommitDone(FutureTask postCommitTask) throws XAException, IOException - { - try - { + protected void waitPostCommitDone(FutureTask postCommitTask) throws XAException, IOException { + try { postCommitTask.get(); } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new InterruptedIOException(e.toString()); } - catch (ExecutionException e) - { + catch (ExecutionException e) { Throwable t = e.getCause(); - if (t instanceof XAException) - { + if (t instanceof XAException) { throw (XAException) t; } - else if (t instanceof IOException) - { + else if (t instanceof IOException) { throw (IOException) t; } - else - { + else { throw new XAException(e.toString()); } } } - protected void doPreCommit() throws XAException - { - try - { + protected void doPreCommit() throws XAException { + try { fireBeforeCommit(); } - catch (Throwable e) - { + catch (Throwable e) { // I guess this could happen. Post commit task failed // to execute properly. getLog().warn("PRE COMMIT FAILED: ", e); @@ -232,15 +191,12 @@ public abstract class AMQTransaction } } - protected void doPostCommit() throws XAException - { - try - { + protected void doPostCommit() throws XAException { + try { setCommitted(true); fireAfterCommit(); } - catch (Throwable e) - { + catch (Throwable e) { // I guess this could happen. Post commit task failed // to execute properly. getLog().warn("POST COMMIT FAILED: ", e); diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQTransactionFactory.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQTransactionFactory.java index b3abebc512..3a47333f14 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQTransactionFactory.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQTransactionFactory.java @@ -23,11 +23,10 @@ import org.apache.activemq.artemis.core.protocol.openwire.AMQTransactionImpl; import org.apache.activemq.artemis.core.transaction.Transaction; import org.apache.activemq.artemis.core.transaction.TransactionFactory; -public class AMQTransactionFactory implements TransactionFactory -{ +public class AMQTransactionFactory implements TransactionFactory { + @Override - public Transaction newTransaction(Xid xid, StorageManager storageManager, int timeoutSeconds) - { + public Transaction newTransaction(Xid xid, StorageManager storageManager, int timeoutSeconds) { return new AMQTransactionImpl(xid, storageManager, timeoutSeconds); } } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/BrowserListener.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/BrowserListener.java index a9c2337fcf..0e192dbf71 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/BrowserListener.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/BrowserListener.java @@ -16,7 +16,7 @@ */ package org.apache.activemq.artemis.core.protocol.openwire.amq; -interface BrowserListener -{ +interface BrowserListener { + void browseFinished(); } diff --git a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/MessageInfo.java b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/MessageInfo.java index 849cf1276e..005dd2e87b 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/MessageInfo.java +++ b/artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/MessageInfo.java @@ -18,34 +18,30 @@ package org.apache.activemq.artemis.core.protocol.openwire.amq; import org.apache.activemq.command.MessageId; -public class MessageInfo -{ +public class MessageInfo { + public MessageId amqId; public long nativeId; public int size; //mark message that is acked within a local tx public boolean localAcked; - public MessageInfo(MessageId amqId, long nativeId, int size) - { + public MessageInfo(MessageId amqId, long nativeId, int size) { this.amqId = amqId; this.nativeId = nativeId; this.size = size; } @Override - public String toString() - { + public String toString() { return "native mid: " + this.nativeId + " amqId: " + amqId + " local acked: " + localAcked; } - public void setLocalAcked(boolean ack) - { + public void setLocalAcked(boolean ack) { localAcked = ack; } - public boolean isLocalAcked() - { + public boolean isLocalAcked() { return localAcked; } } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPClientConnectionContext.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPClientConnectionContext.java index c101b12a75..786d0d7fac 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPClientConnectionContext.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPClientConnectionContext.java @@ -21,8 +21,8 @@ import org.proton.plug.exceptions.ActiveMQAMQPException; /** * This is valid only on a client connection. */ -public interface AMQPClientConnectionContext extends AMQPConnectionContext -{ +public interface AMQPClientConnectionContext extends AMQPConnectionContext { + /** * This will send an open and block for its return on AMQP protocol. * diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPClientReceiverContext.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPClientReceiverContext.java index 4c842689f9..26d539e1b8 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPClientReceiverContext.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPClientReceiverContext.java @@ -20,8 +20,8 @@ import java.util.concurrent.TimeUnit; import org.apache.qpid.proton.message.ProtonJMessage; -public interface AMQPClientReceiverContext -{ +public interface AMQPClientReceiverContext { + ProtonJMessage receiveMessage(int time, TimeUnit unit) throws Exception; void flow(int credits); diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPClientSenderContext.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPClientSenderContext.java index fad903aa05..8c40b9d31c 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPClientSenderContext.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPClientSenderContext.java @@ -18,7 +18,7 @@ package org.proton.plug; import org.apache.qpid.proton.message.ProtonJMessage; -public interface AMQPClientSenderContext -{ +public interface AMQPClientSenderContext { + void send(ProtonJMessage message); } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPClientSessionContext.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPClientSessionContext.java index 0f8b61e8b7..6cd0aa74db 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPClientSessionContext.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPClientSessionContext.java @@ -18,8 +18,8 @@ package org.proton.plug; import org.proton.plug.exceptions.ActiveMQAMQPException; -public interface AMQPClientSessionContext extends AMQPSessionContext -{ +public interface AMQPClientSessionContext extends AMQPSessionContext { + AMQPClientSenderContext createSender(String address, boolean preSettled) throws ActiveMQAMQPException; AMQPClientReceiverContext createReceiver(String address) throws ActiveMQAMQPException; diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPConnectionCallback.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPConnectionCallback.java index e31e1d007b..c274469aa3 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPConnectionCallback.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPConnectionCallback.java @@ -18,8 +18,8 @@ package org.proton.plug; import io.netty.buffer.ByteBuf; -public interface AMQPConnectionCallback -{ +public interface AMQPConnectionCallback { + void close(); /** diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPConnectionContext.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPConnectionContext.java index f76addcf4e..45f9804277 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPConnectionContext.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPConnectionContext.java @@ -18,8 +18,7 @@ package org.proton.plug; import io.netty.buffer.ByteBuf; -public interface AMQPConnectionContext -{ +public interface AMQPConnectionContext { void close(); @@ -59,5 +58,4 @@ public interface AMQPConnectionContext */ void outputDone(int numberOfBytes); - } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPConnectionContextFactory.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPConnectionContextFactory.java index 46aa0ddf5a..b1ef1855dd 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPConnectionContextFactory.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPConnectionContextFactory.java @@ -16,12 +16,15 @@ */ package org.proton.plug; -public abstract class AMQPConnectionContextFactory -{ +public abstract class AMQPConnectionContextFactory { + /** * @return */ - public abstract AMQPConnectionContext createConnection(AMQPConnectionCallback connectionCallback,int idleTimeout, int maxFrameSize, int channelMax); + public abstract AMQPConnectionContext createConnection(AMQPConnectionCallback connectionCallback, + int idleTimeout, + int maxFrameSize, + int channelMax); /** * @return diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPServerConnectionContext.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPServerConnectionContext.java index 8f5bc533ca..518c79e2b7 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPServerConnectionContext.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPServerConnectionContext.java @@ -16,6 +16,6 @@ */ package org.proton.plug; -public interface AMQPServerConnectionContext extends AMQPConnectionContext -{ +public interface AMQPServerConnectionContext extends AMQPConnectionContext { + } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPSessionCallback.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPSessionCallback.java index c4734367d1..cce8e0caae 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPSessionCallback.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPSessionCallback.java @@ -26,8 +26,7 @@ import org.proton.plug.context.ProtonPlugSender; /** * These are methods where the Proton Plug component will call your server */ -public interface AMQPSessionCallback -{ +public interface AMQPSessionCallback { void init(AMQPSessionContext session, SASLResult saslResult) throws Exception; @@ -58,7 +57,6 @@ public interface AMQPSessionCallback void close() throws Exception; - void ack(Object brokerConsumer, Object message) throws Exception; /** @@ -70,16 +68,18 @@ public interface AMQPSessionCallback */ void cancel(Object brokerConsumer, Object message, boolean updateCounts) throws Exception; - void resumeDelivery(Object consumer); - /** * @param delivery * @param address * @param messageFormat * @param messageEncoded a Heap Buffer ByteBuffer (safe to convert into byte[]) */ - void serverSend(Receiver receiver, Delivery delivery, String address, int messageFormat, ByteBuf messageEncoded) throws Exception; + void serverSend(Receiver receiver, + Delivery delivery, + String address, + int messageFormat, + ByteBuf messageEncoded) throws Exception; } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPSessionContext.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPSessionContext.java index 5f5f373096..66e9c5ae59 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPSessionContext.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/AMQPSessionContext.java @@ -20,8 +20,8 @@ import org.apache.qpid.proton.engine.Receiver; import org.apache.qpid.proton.engine.Sender; import org.proton.plug.exceptions.ActiveMQAMQPException; -public interface AMQPSessionContext -{ +public interface AMQPSessionContext { + byte[] getTag(); void replaceTag(byte[] tag); diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/ClientSASL.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/ClientSASL.java index 932c261698..c36fd19cd4 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/ClientSASL.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/ClientSASL.java @@ -16,8 +16,8 @@ */ package org.proton.plug; -public interface ClientSASL -{ +public interface ClientSASL { + byte[] getBytes(); String getName(); diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/SASLResult.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/SASLResult.java index 34ce3209d2..f7ff671127 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/SASLResult.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/SASLResult.java @@ -16,8 +16,8 @@ */ package org.proton.plug; -public interface SASLResult -{ +public interface SASLResult { + String getUser(); boolean isSuccess(); diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/ServerSASL.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/ServerSASL.java index 59ecaa313f..ed1c361abc 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/ServerSASL.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/ServerSASL.java @@ -16,8 +16,8 @@ */ package org.proton.plug; -public interface ServerSASL -{ +public interface ServerSASL { + String getName(); SASLResult processSASL(byte[] bytes); diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/AMQPConstants.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/AMQPConstants.java index 485431560c..6287c067cb 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/AMQPConstants.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/AMQPConstants.java @@ -19,14 +19,14 @@ package org.proton.plug.context; /** * Constants derived from the AMQP spec */ -public class AMQPConstants -{ +public class AMQPConstants { + /* * Connection Properties * http://docs.oasis-open.org/amqp/core/v1.0/amqp-core-complete-v1.0.pdf#subsection.2.7.1 * */ - public static class Connection - { + public static class Connection { + public static final int DEFAULT_IDLE_TIMEOUT = -1; public static final int DEFAULT_MAX_FRAME_SIZE = -1;//it should be according to the spec 4294967295l; diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/AbstractConnectionContext.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/AbstractConnectionContext.java index 72858fb147..23447a79fa 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/AbstractConnectionContext.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/AbstractConnectionContext.java @@ -38,8 +38,7 @@ import static org.proton.plug.context.AMQPConstants.Connection.DEFAULT_IDLE_TIME import static org.proton.plug.context.AMQPConstants.Connection.DEFAULT_CHANNEL_MAX; import static org.proton.plug.context.AMQPConstants.Connection.DEFAULT_MAX_FRAME_SIZE; -public abstract class AbstractConnectionContext extends ProtonInitializable implements AMQPConnectionContext -{ +public abstract class AbstractConnectionContext extends ProtonInitializable implements AMQPConnectionContext { protected ProtonHandler handler = ProtonHandler.Factory.create(); @@ -49,18 +48,18 @@ public abstract class AbstractConnectionContext extends ProtonInitializable impl protected LocalListener listener = new LocalListener(); - public AbstractConnectionContext(AMQPConnectionCallback connectionCallback) - { + public AbstractConnectionContext(AMQPConnectionCallback connectionCallback) { this(connectionCallback, DEFAULT_IDLE_TIMEOUT, DEFAULT_MAX_FRAME_SIZE, DEFAULT_CHANNEL_MAX); } - public AbstractConnectionContext(AMQPConnectionCallback connectionCallback, int idleTimeout, int maxFrameSize, int channelMax) - { + public AbstractConnectionContext(AMQPConnectionCallback connectionCallback, + int idleTimeout, + int maxFrameSize, + int channelMax) { this.connectionCallback = connectionCallback; connectionCallback.setConnection(this); Transport transport = handler.getTransport(); - if (idleTimeout > 0) - { + if (idleTimeout > 0) { transport.setIdleTimeout(idleTimeout); transport.tick(idleTimeout / 2); } @@ -69,68 +68,55 @@ public abstract class AbstractConnectionContext extends ProtonInitializable impl handler.addEventHandler(listener); } - public SASLResult getSASLResult() - { + public SASLResult getSASLResult() { return handler.getSASLResult(); } @Override - public void inputBuffer(ByteBuf buffer) - { - if (DebugInfo.debug) - { + public void inputBuffer(ByteBuf buffer) { + if (DebugInfo.debug) { ByteUtil.debugFrame("Buffer Received ", buffer); } handler.inputBuffer(buffer); } - public void destroy() - { + public void destroy() { connectionCallback.close(); } /** * See comment at {@link org.proton.plug.AMQPConnectionContext#isSyncOnFlush()} */ - public boolean isSyncOnFlush() - { + public boolean isSyncOnFlush() { return false; } - - public Object getLock() - { + public Object getLock() { return handler.getLock(); } @Override - public int capacity() - { + public int capacity() { return handler.capacity(); } @Override - public void outputDone(int bytes) - { + public void outputDone(int bytes) { handler.outputDone(bytes); } - public void flush() - { + public void flush() { handler.flush(); } - public void close() - { + public void close() { handler.close(); } - protected AbstractProtonSessionContext getSessionExtension(Session realSession) throws ActiveMQAMQPException - { + protected AbstractProtonSessionContext getSessionExtension(Session realSession) throws ActiveMQAMQPException { AbstractProtonSessionContext sessionExtension = sessions.get(realSession); - if (sessionExtension == null) - { + if (sessionExtension == null) { // how this is possible? Log a warn here sessionExtension = newSessionExtension(realSession); realSession.setContext(sessionExtension); @@ -141,68 +127,53 @@ public abstract class AbstractConnectionContext extends ProtonInitializable impl protected abstract void remoteLinkOpened(Link link) throws Exception; - protected abstract AbstractProtonSessionContext newSessionExtension(Session realSession) throws ActiveMQAMQPException; @Override - public boolean checkDataReceived() - { + public boolean checkDataReceived() { return handler.checkDataReceived(); } @Override - public long getCreationTime() - { + public long getCreationTime() { return handler.getCreationTime(); } - protected void flushBytes() - { + protected void flushBytes() { ByteBuf bytes; // handler.outputBuffer has the lock - while ((bytes = handler.outputBuffer()) != null) - { + while ((bytes = handler.outputBuffer()) != null) { connectionCallback.onTransport(bytes, AbstractConnectionContext.this); } } - // This listener will perform a bunch of things here - class LocalListener extends DefaultEventHandler - { + class LocalListener extends DefaultEventHandler { @Override - public void onSASLInit(ProtonHandler handler, Connection connection) - { + public void onSASLInit(ProtonHandler handler, Connection connection) { handler.createServerSASL(connectionCallback.getSASLMechnisms()); } @Override - public void onTransport(Transport transport) - { + public void onTransport(Transport transport) { flushBytes(); } @Override - public void onRemoteOpen(Connection connection) throws Exception - { - synchronized (getLock()) - { + public void onRemoteOpen(Connection connection) throws Exception { + synchronized (getLock()) { connection.setContext(AbstractConnectionContext.this); connection.open(); } initialise(); } - @Override - public void onRemoteClose(Connection connection) - { - synchronized (getLock()) - { + public void onRemoteClose(Connection connection) { + synchronized (getLock()) { connection.close(); - for (AbstractProtonSessionContext protonSession : sessions.values()) - { + for (AbstractProtonSessionContext protonSession : sessions.values()) { protonSession.close(); } sessions.clear(); @@ -213,38 +184,30 @@ public abstract class AbstractConnectionContext extends ProtonInitializable impl } @Override - public void onLocalOpen(Session session) throws Exception - { + public void onLocalOpen(Session session) throws Exception { getSessionExtension(session); } @Override - public void onRemoteOpen(Session session) throws Exception - { + public void onRemoteOpen(Session session) throws Exception { getSessionExtension(session).initialise(); - synchronized (getLock()) - { + synchronized (getLock()) { session.open(); } } - @Override - public void onLocalClose(Session session) throws Exception - { + public void onLocalClose(Session session) throws Exception { } @Override - public void onRemoteClose(Session session) throws Exception - { - synchronized (getLock()) - { + public void onRemoteClose(Session session) throws Exception { + synchronized (getLock()) { session.close(); } AbstractProtonSessionContext sessionContext = (AbstractProtonSessionContext) session.getContext(); - if (sessionContext != null) - { + if (sessionContext != null) { sessionContext.close(); sessions.remove(session); session.setContext(null); @@ -252,50 +215,40 @@ public abstract class AbstractConnectionContext extends ProtonInitializable impl } @Override - public void onRemoteOpen(Link link) throws Exception - { + public void onRemoteOpen(Link link) throws Exception { remoteLinkOpened(link); } @Override - public void onFlow(Link link) throws Exception - { + public void onFlow(Link link) throws Exception { ((ProtonDeliveryHandler) link.getContext()).onFlow(link.getCredit()); } @Override - public void onRemoteClose(Link link) throws Exception - { + public void onRemoteClose(Link link) throws Exception { link.close(); ProtonDeliveryHandler linkContext = (ProtonDeliveryHandler) link.getContext(); - if (linkContext != null) - { + if (linkContext != null) { linkContext.close(); } } - - public void onRemoteDetach(Link link) throws Exception - { + public void onRemoteDetach(Link link) throws Exception { link.detach(); } - public void onDelivery(Delivery delivery) throws Exception - { + public void onDelivery(Delivery delivery) throws Exception { ProtonDeliveryHandler handler = (ProtonDeliveryHandler) delivery.getLink().getContext(); - if (handler != null) - { + if (handler != null) { handler.onMessage(delivery); } - else - { + else { // TODO: logs System.err.println("Handler is null, can't delivery " + delivery); } } - } } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/AbstractProtonContextSender.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/AbstractProtonContextSender.java index 31ac8a4b92..64fd49edad 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/AbstractProtonContextSender.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/AbstractProtonContextSender.java @@ -30,8 +30,8 @@ import org.proton.plug.util.NettyWritable; /** * A this is a wrapper around an ActiveMQ Artemis ServerConsumer for handling outgoing messages and incoming acks via a Proton Sender */ -public abstract class AbstractProtonContextSender extends ProtonInitializable implements ProtonDeliveryHandler -{ +public abstract class AbstractProtonContextSender extends ProtonInitializable implements ProtonDeliveryHandler { + protected final AbstractProtonSessionContext protonSession; protected final Sender sender; protected final AbstractConnectionContext connection; @@ -39,25 +39,24 @@ public abstract class AbstractProtonContextSender extends ProtonInitializable im protected final AMQPSessionCallback sessionSPI; protected CreditsSemaphore creditsSemaphore = new CreditsSemaphore(0); - - public AbstractProtonContextSender(AbstractConnectionContext connection, Sender sender, AbstractProtonSessionContext protonSession, AMQPSessionCallback server) - { + public AbstractProtonContextSender(AbstractConnectionContext connection, + Sender sender, + AbstractProtonSessionContext protonSession, + AMQPSessionCallback server) { this.connection = connection; this.sender = sender; this.protonSession = protonSession; this.sessionSPI = server; } - public void onFlow(int credits) - { + public void onFlow(int credits) { this.creditsSemaphore.setCredits(credits); } /* * start the session * */ - public void start() throws ActiveMQAMQPException - { + public void start() throws ActiveMQAMQPException { sessionSPI.start(); // protonSession.getServerSession().start(); } @@ -65,12 +64,10 @@ public abstract class AbstractProtonContextSender extends ProtonInitializable im /* * close the session * */ - public void close() throws ActiveMQAMQPException - { + public void close() throws ActiveMQAMQPException { closed = true; protonSession.removeSender(sender); - synchronized (connection.getLock()) - { + synchronized (connection.getLock()) { sender.close(); } @@ -80,31 +77,24 @@ public abstract class AbstractProtonContextSender extends ProtonInitializable im @Override /* * handle an incoming Ack from Proton, basically pass to ActiveMQ Artemis to handle - * */ - public abstract void onMessage(Delivery delivery) throws ActiveMQAMQPException; + * */ public abstract void onMessage(Delivery delivery) throws ActiveMQAMQPException; /* * check the state of the consumer, i.e. are there any more messages. only really needed for browsers? * */ - public void checkState() - { + public void checkState() { } - public Sender getSender() - { + public Sender getSender() { return sender; } - protected int performSend(ProtonJMessage serverMessage, Object context) - { - if (!creditsSemaphore.tryAcquire()) - { - try - { + protected int performSend(ProtonJMessage serverMessage, Object context) { + if (!creditsSemaphore.tryAcquire()) { + try { creditsSemaphore.acquire(); } - catch (InterruptedException e) - { + catch (InterruptedException e) { Thread.currentThread().interrupt(); // nothing to be done here.. we just keep going throw new IllegalStateException(e.getMessage(), e); @@ -118,14 +108,12 @@ public abstract class AbstractProtonContextSender extends ProtonInitializable im byte[] tag = preSettle ? new byte[0] : protonSession.getTag(); ByteBuf nettyBuffer = PooledByteBufAllocator.DEFAULT.heapBuffer(1024); - try - { + try { serverMessage.encode(new NettyWritable(nettyBuffer)); int size = nettyBuffer.writerIndex(); - synchronized (connection.getLock()) - { + synchronized (connection.getLock()) { final Delivery delivery; delivery = sender.delivery(tag, 0, tag.length); delivery.setContext(context); @@ -133,12 +121,10 @@ public abstract class AbstractProtonContextSender extends ProtonInitializable im // this will avoid a copy.. patch provided by Norman using buffer.array() sender.send(nettyBuffer.array(), nettyBuffer.arrayOffset() + nettyBuffer.readerIndex(), nettyBuffer.readableBytes()); - if (preSettle) - { + if (preSettle) { delivery.settle(); } - else - { + else { sender.advance(); } } @@ -147,8 +133,7 @@ public abstract class AbstractProtonContextSender extends ProtonInitializable im return size; } - finally - { + finally { nettyBuffer.release(); } } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/AbstractProtonReceiverContext.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/AbstractProtonReceiverContext.java index 1b4b59ffc4..2cb38b3c9f 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/AbstractProtonReceiverContext.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/AbstractProtonReceiverContext.java @@ -21,10 +21,10 @@ import org.proton.plug.AMQPSessionCallback; import org.proton.plug.exceptions.ActiveMQAMQPException; /** - * handles incoming messages via a Proton Receiver and forwards them to ActiveMQ + * handles incoming messages via a Proton Receiver and forwards them to ActiveMQ */ -public abstract class AbstractProtonReceiverContext extends ProtonInitializable implements ProtonDeliveryHandler -{ +public abstract class AbstractProtonReceiverContext extends ProtonInitializable implements ProtonDeliveryHandler { + protected final AbstractConnectionContext connection; protected final AbstractProtonSessionContext protonSession; @@ -35,32 +35,29 @@ public abstract class AbstractProtonReceiverContext extends ProtonInitializable protected final AMQPSessionCallback sessionSPI; - public AbstractProtonReceiverContext(AMQPSessionCallback sessionSPI, AbstractConnectionContext connection, AbstractProtonSessionContext protonSession, Receiver receiver) - { + public AbstractProtonReceiverContext(AMQPSessionCallback sessionSPI, + AbstractConnectionContext connection, + AbstractProtonSessionContext protonSession, + Receiver receiver) { this.connection = connection; this.protonSession = protonSession; this.receiver = receiver; - if (receiver.getRemoteTarget() != null) - { + if (receiver.getRemoteTarget() != null) { this.address = receiver.getRemoteTarget().getAddress(); } - else - { + else { this.address = null; } this.sessionSPI = sessionSPI; } @Override - public void close() throws ActiveMQAMQPException - { + public void close() throws ActiveMQAMQPException { protonSession.removeReceiver(receiver); } - public void flow(int credits) - { - synchronized (connection.getLock()) - { + public void flow(int credits) { + synchronized (connection.getLock()) { receiver.flow(credits); } connection.flush(); diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/AbstractProtonSessionContext.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/AbstractProtonSessionContext.java index a44c2c1ac7..348f01ea39 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/AbstractProtonSessionContext.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/AbstractProtonSessionContext.java @@ -35,8 +35,8 @@ import org.proton.plug.exceptions.ActiveMQAMQPInternalErrorException; * It has a link between a ProtonSession and a Broker or Client Session * The Broker Session is linked through the ProtonSessionSPI */ -public abstract class AbstractProtonSessionContext extends ProtonInitializable implements AMQPSessionContext -{ +public abstract class AbstractProtonSessionContext extends ProtonInitializable implements AMQPSessionContext { + protected final AbstractConnectionContext connection; protected final AMQPSessionCallback sessionSPI; @@ -51,93 +51,73 @@ public abstract class AbstractProtonSessionContext extends ProtonInitializable i protected boolean closed = false; - public AbstractProtonSessionContext(AMQPSessionCallback sessionSPI, AbstractConnectionContext connection, Session session) - { + public AbstractProtonSessionContext(AMQPSessionCallback sessionSPI, + AbstractConnectionContext connection, + Session session) { this.connection = connection; this.sessionSPI = sessionSPI; this.session = session; } - public void initialise() throws Exception - { - if (!isInitialized()) - { + public void initialise() throws Exception { + if (!isInitialized()) { super.initialise(); - if (sessionSPI != null) - { - try - { + if (sessionSPI != null) { + try { sessionSPI.init(this, connection.getSASLResult()); } - catch (Exception e) - { + catch (Exception e) { throw new ActiveMQAMQPInternalErrorException(e.getMessage(), e); } } } } - /** * TODO: maybe it needs to go? * * @param consumer * @param queueName */ - public void disconnect(Object consumer, String queueName) - { + public void disconnect(Object consumer, String queueName) { AbstractProtonContextSender protonConsumer = senders.remove(consumer); - if (protonConsumer != null) - { - try - { + if (protonConsumer != null) { + try { protonConsumer.close(); } - catch (ActiveMQAMQPException e) - { + catch (ActiveMQAMQPException e) { protonConsumer.getSender().setTarget(null); protonConsumer.getSender().setCondition(new ErrorCondition(e.getAmqpError(), e.getMessage())); } } } - @Override - public byte[] getTag() - { + public byte[] getTag() { return Long.toHexString(currentTag++).getBytes(); } @Override - public void replaceTag(byte[] tag) - { + public void replaceTag(byte[] tag) { // TODO: do we need to reuse this? } @Override - public void close() - { - if (closed) - { + public void close() { + if (closed) { return; } - - // Making a copy to avoid ConcurrentModificationException during the iteration Set receiversCopy = new HashSet<>(); receiversCopy.addAll(receivers.values()); - - for (AbstractProtonReceiverContext protonProducer : receiversCopy) - { - try - { + for (AbstractProtonReceiverContext protonProducer : receiversCopy) { + try { protonProducer.close(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); // TODO Logging } @@ -147,29 +127,23 @@ public abstract class AbstractProtonSessionContext extends ProtonInitializable i Set protonSendersClone = new HashSet<>(); protonSendersClone.addAll(senders.values()); - for (AbstractProtonContextSender protonConsumer : protonSendersClone) - { - try - { + for (AbstractProtonContextSender protonConsumer : protonSendersClone) { + try { protonConsumer.close(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); // TODO Logging } } senders.clear(); - try - { - if (sessionSPI != null) - { + try { + if (sessionSPI != null) { sessionSPI.rollbackCurrentTX(); sessionSPI.close(); } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); // TODO logging } @@ -177,14 +151,12 @@ public abstract class AbstractProtonSessionContext extends ProtonInitializable i } @Override - public void removeSender(Sender sender) throws ActiveMQAMQPException - { + public void removeSender(Sender sender) throws ActiveMQAMQPException { senders.remove(sender); } @Override - public void removeReceiver(Receiver receiver) - { + public void removeReceiver(Receiver receiver) { receivers.remove(receiver); } } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/ProtonDeliveryHandler.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/ProtonDeliveryHandler.java index e8a18f1f80..63bc277ed9 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/ProtonDeliveryHandler.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/ProtonDeliveryHandler.java @@ -20,10 +20,10 @@ import org.apache.qpid.proton.engine.Delivery; import org.proton.plug.exceptions.ActiveMQAMQPException; /** - * An interface to handle deliveries, either messages, acks or transaction calls + * An interface to handle deliveries, either messages, acks or transaction calls */ -public interface ProtonDeliveryHandler -{ +public interface ProtonDeliveryHandler { + void onFlow(int currentCredits); void onMessage(Delivery delivery) throws ActiveMQAMQPException; diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/ProtonInitializable.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/ProtonInitializable.java index cb81b034bc..c065527656 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/ProtonInitializable.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/ProtonInitializable.java @@ -23,57 +23,42 @@ import org.proton.plug.exceptions.ActiveMQAMQPIllegalStateException; import org.proton.plug.exceptions.ActiveMQAMQPTimeoutException; import org.proton.plug.util.FutureRunnable; -public class ProtonInitializable -{ +public class ProtonInitializable { private Runnable afterInit; private boolean initialized = false; - public void afterInit(Runnable afterInit) - { + public void afterInit(Runnable afterInit) { this.afterInit = afterInit; } - - public boolean isInitialized() - { + public boolean isInitialized() { return initialized; } - - public void initialise() throws Exception - { - if (!initialized) - { + public void initialise() throws Exception { + if (!initialized) { initialized = false; - try - { - if (afterInit != null) - { + try { + if (afterInit != null) { afterInit.run(); } } - finally - { + finally { afterInit = null; } } } - - public void waitWithTimeout(FutureRunnable latch) throws ActiveMQAMQPException - { - try - { + public void waitWithTimeout(FutureRunnable latch) throws ActiveMQAMQPException { + try { // TODO Configure this - if (!latch.await(30, TimeUnit.SECONDS)) - { + if (!latch.await(30, TimeUnit.SECONDS)) { throw new ActiveMQAMQPTimeoutException("Timed out waiting for response"); } } - catch (InterruptedException e) - { + catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new ActiveMQAMQPIllegalStateException(e.getMessage()); } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/ProtonPlugSender.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/ProtonPlugSender.java index 95da8e958f..40232ecec6 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/ProtonPlugSender.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/ProtonPlugSender.java @@ -18,8 +18,8 @@ package org.proton.plug.context; import org.apache.qpid.proton.engine.Sender; -public interface ProtonPlugSender -{ +public interface ProtonPlugSender { + int deliverMessage(Object message, int deliveryCount) throws Exception; Sender getSender(); diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/ProtonTransactionHandler.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/ProtonTransactionHandler.java index 78f2406819..b8d9ee1489 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/ProtonTransactionHandler.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/ProtonTransactionHandler.java @@ -39,28 +39,23 @@ import static org.proton.plug.util.DeliveryUtil.readDelivery; /** * handles an amqp Coordinator to deal with transaction boundaries etc */ -public class ProtonTransactionHandler implements ProtonDeliveryHandler -{ +public class ProtonTransactionHandler implements ProtonDeliveryHandler { final AMQPSessionCallback sessionSPI; - public ProtonTransactionHandler(AMQPSessionCallback sessionSPI) - { + public ProtonTransactionHandler(AMQPSessionCallback sessionSPI) { this.sessionSPI = sessionSPI; } @Override - public void onMessage(Delivery delivery) throws ActiveMQAMQPException - { + public void onMessage(Delivery delivery) throws ActiveMQAMQPException { ByteBuf buffer = PooledByteBufAllocator.DEFAULT.heapBuffer(1024); final Receiver receiver; - try - { + try { receiver = ((Receiver) delivery.getLink()); - if (!delivery.isReadable()) - { + if (!delivery.isReadable()) { return; } @@ -72,36 +67,28 @@ public class ProtonTransactionHandler implements ProtonDeliveryHandler Object action = ((AmqpValue) msg.getBody()).getValue(); - if (action instanceof Declare) - { + if (action instanceof Declare) { Binary txID = sessionSPI.getCurrentTXID(); Declared declared = new Declared(); declared.setTxnId(txID); delivery.disposition(declared); delivery.settle(); } - else if (action instanceof Discharge) - { + else if (action instanceof Discharge) { Discharge discharge = (Discharge) action; - if (discharge.getFail()) - { - try - { + if (discharge.getFail()) { + try { sessionSPI.rollbackCurrentTX(); } - catch (Exception e) - { + catch (Exception e) { throw ActiveMQAMQPProtocolMessageBundle.BUNDLE.errorRollingbackCoordinator(e.getMessage()); } } - else - { - try - { + else { + try { sessionSPI.commitCurrentTX(); } - catch (Exception e) - { + catch (Exception e) { throw ActiveMQAMQPProtocolMessageBundle.BUNDLE.errorCommittingCoordinator(e.getMessage()); } } @@ -109,8 +96,7 @@ public class ProtonTransactionHandler implements ProtonDeliveryHandler } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); Rejected rejected = new Rejected(); ErrorCondition condition = new ErrorCondition(); @@ -119,20 +105,17 @@ public class ProtonTransactionHandler implements ProtonDeliveryHandler rejected.setError(condition); delivery.disposition(rejected); } - finally - { + finally { buffer.release(); } } - public void onFlow(int credits) - { + public void onFlow(int credits) { } @Override - public void close() throws ActiveMQAMQPException - { + public void close() throws ActiveMQAMQPException { //noop } } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientConnectionContext.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientConnectionContext.java index 8dce7ec081..a35ebab3f5 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientConnectionContext.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientConnectionContext.java @@ -29,27 +29,25 @@ import org.proton.plug.exceptions.ActiveMQAMQPException; import org.proton.plug.context.ProtonInitializable; import org.proton.plug.util.FutureRunnable; -public class ProtonClientConnectionContext extends AbstractConnectionContext implements AMQPClientConnectionContext -{ - public ProtonClientConnectionContext(AMQPConnectionCallback connectionCallback) - { +public class ProtonClientConnectionContext extends AbstractConnectionContext implements AMQPClientConnectionContext { + + public ProtonClientConnectionContext(AMQPConnectionCallback connectionCallback) { super(connectionCallback); } - public ProtonClientConnectionContext(AMQPConnectionCallback connectionCallback, int idleTimeout, int maxFrameSize, int channelMax) - { + public ProtonClientConnectionContext(AMQPConnectionCallback connectionCallback, + int idleTimeout, + int maxFrameSize, + int channelMax) { super(connectionCallback, idleTimeout, maxFrameSize, channelMax); } // Maybe a client interface? - public void clientOpen(ClientSASL sasl) throws Exception - { + public void clientOpen(ClientSASL sasl) throws Exception { FutureRunnable future = new FutureRunnable(1); - synchronized (handler.getLock()) - { + synchronized (handler.getLock()) { this.afterInit(future); - if (sasl != null) - { + if (sasl != null) { handler.createClientSasl(sasl); } handler.getConnection().open(); @@ -60,13 +58,11 @@ public class ProtonClientConnectionContext extends AbstractConnectionContext imp waitWithTimeout(future); } - public AMQPClientSessionContext createClientSession() throws ActiveMQAMQPException - { + public AMQPClientSessionContext createClientSession() throws ActiveMQAMQPException { FutureRunnable futureRunnable = new FutureRunnable(1); ProtonClientSessionContext sessionImpl; - synchronized (handler.getLock()) - { + synchronized (handler.getLock()) { Session session = handler.getConnection().session(); sessionImpl = (ProtonClientSessionContext) getSessionExtension(session); sessionImpl.afterInit(futureRunnable); @@ -80,8 +76,7 @@ public class ProtonClientConnectionContext extends AbstractConnectionContext imp } @Override - protected AbstractProtonSessionContext newSessionExtension(Session realSession) throws ActiveMQAMQPException - { + protected AbstractProtonSessionContext newSessionExtension(Session realSession) throws ActiveMQAMQPException { AMQPSessionCallback sessionSPI = connectionCallback.createSessionCallback(this); AbstractProtonSessionContext protonSession = new ProtonClientSessionContext(sessionSPI, this, realSession); @@ -90,11 +85,9 @@ public class ProtonClientConnectionContext extends AbstractConnectionContext imp } @Override - protected void remoteLinkOpened(Link link) throws Exception - { + protected void remoteLinkOpened(Link link) throws Exception { Object context = link.getContext(); - if (context != null && context instanceof ProtonInitializable) - { + if (context != null && context instanceof ProtonInitializable) { ((ProtonInitializable) context).initialise(); } } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientConnectionContextFactory.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientConnectionContextFactory.java index ed4379cbe8..2f12043201 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientConnectionContextFactory.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientConnectionContextFactory.java @@ -20,23 +20,23 @@ import org.proton.plug.AMQPConnectionContext; import org.proton.plug.AMQPConnectionContextFactory; import org.proton.plug.AMQPConnectionCallback; -public class ProtonClientConnectionContextFactory extends AMQPConnectionContextFactory -{ +public class ProtonClientConnectionContextFactory extends AMQPConnectionContextFactory { + private static final AMQPConnectionContextFactory theInstance = new ProtonClientConnectionContextFactory(); - public static AMQPConnectionContextFactory getFactory() - { + public static AMQPConnectionContextFactory getFactory() { return theInstance; } - public AMQPConnectionContext createConnection(AMQPConnectionCallback connectionCallback) - { + public AMQPConnectionContext createConnection(AMQPConnectionCallback connectionCallback) { return new ProtonClientConnectionContext(connectionCallback); } @Override - public AMQPConnectionContext createConnection(AMQPConnectionCallback connectionCallback, int idleTimeout, int maxFrameSize, int channelMax) - { + public AMQPConnectionContext createConnection(AMQPConnectionCallback connectionCallback, + int idleTimeout, + int maxFrameSize, + int channelMax) { return new ProtonClientConnectionContext(connectionCallback, idleTimeout, maxFrameSize, channelMax); } } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientContext.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientContext.java index 7156714467..924ca3fd13 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientContext.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientContext.java @@ -31,47 +31,38 @@ import org.proton.plug.context.AbstractProtonSessionContext; import org.proton.plug.exceptions.ActiveMQAMQPException; import org.proton.plug.util.FutureRunnable; -public class ProtonClientContext extends AbstractProtonContextSender implements AMQPClientSenderContext -{ +public class ProtonClientContext extends AbstractProtonContextSender implements AMQPClientSenderContext { FutureRunnable catchUpRunnable = new FutureRunnable(); - public ProtonClientContext(AbstractConnectionContext connection, Sender sender, AbstractProtonSessionContext protonSession, AMQPSessionCallback server) - { + public ProtonClientContext(AbstractConnectionContext connection, + Sender sender, + AbstractProtonSessionContext protonSession, + AMQPSessionCallback server) { super(connection, sender, protonSession, server); } - @Override - public void onMessage(Delivery delivery) throws ActiveMQAMQPException - { - if (delivery.getRemoteState() instanceof Accepted) - { - if (delivery.getContext() instanceof FutureRunnable) - { + public void onMessage(Delivery delivery) throws ActiveMQAMQPException { + if (delivery.getRemoteState() instanceof Accepted) { + if (delivery.getContext() instanceof FutureRunnable) { ((FutureRunnable) delivery.getContext()).countDown(); } } } - public void send(ProtonJMessage message) - { - if (sender.getSenderSettleMode() != SenderSettleMode.SETTLED) - { + public void send(ProtonJMessage message) { + if (sender.getSenderSettleMode() != SenderSettleMode.SETTLED) { catchUpRunnable.countUp(); } performSend(message, catchUpRunnable); } - - public boolean sync(long timeout, TimeUnit unit) - { - try - { + public boolean sync(long timeout, TimeUnit unit) { + try { return catchUpRunnable.await(timeout, unit); } - catch (InterruptedException e) - { + catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientReceiverContext.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientReceiverContext.java index 112ab52a5d..fca6d8ee95 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientReceiverContext.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientReceiverContext.java @@ -36,15 +36,16 @@ import org.proton.plug.exceptions.ActiveMQAMQPException; import static org.proton.plug.util.DeliveryUtil.readDelivery; import static org.proton.plug.util.DeliveryUtil.decodeMessageImpl; -public class ProtonClientReceiverContext extends AbstractProtonReceiverContext implements AMQPClientReceiverContext -{ - public ProtonClientReceiverContext(AMQPSessionCallback sessionSPI, AbstractConnectionContext connection, AbstractProtonSessionContext protonSession, Receiver receiver) - { +public class ProtonClientReceiverContext extends AbstractProtonReceiverContext implements AMQPClientReceiverContext { + + public ProtonClientReceiverContext(AMQPSessionCallback sessionSPI, + AbstractConnectionContext connection, + AbstractProtonSessionContext protonSession, + Receiver receiver) { super(sessionSPI, connection, protonSession, receiver); } - public void onFlow(int credits) - { + public void onFlow(int credits) { } LinkedBlockingDeque queues = new LinkedBlockingDeque<>(); @@ -55,18 +56,15 @@ public class ProtonClientReceiverContext extends AbstractProtonReceiverContext i * This may be called more than once per deliver so we have to cache the buffer until we have received it all. * * */ - public void onMessage(Delivery delivery) throws ActiveMQAMQPException - { + public void onMessage(Delivery delivery) throws ActiveMQAMQPException { ByteBuf buffer = PooledByteBufAllocator.DEFAULT.heapBuffer(1024); - try - { - synchronized (connection.getLock()) - { + try { + synchronized (connection.getLock()) { readDelivery(receiver, buffer); MessageImpl clientMessage = decodeMessageImpl(buffer); // This second method could be better -// clientMessage.decode(buffer.nioBuffer()); + // clientMessage.decode(buffer.nioBuffer()); receiver.advance(); delivery.disposition(Accepted.getInstance()); @@ -74,16 +72,13 @@ public class ProtonClientReceiverContext extends AbstractProtonReceiverContext i } } - finally - { + finally { buffer.release(); } } - @Override - public ProtonJMessage receiveMessage(int time, TimeUnit unit) throws Exception - { + public ProtonJMessage receiveMessage(int time, TimeUnit unit) throws Exception { return queues.poll(time, unit); } } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientSessionContext.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientSessionContext.java index a443b118b3..04febda963 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientSessionContext.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientSessionContext.java @@ -31,20 +31,19 @@ import org.proton.plug.context.AbstractProtonSessionContext; import org.proton.plug.exceptions.ActiveMQAMQPException; import org.proton.plug.util.FutureRunnable; -public class ProtonClientSessionContext extends AbstractProtonSessionContext implements AMQPClientSessionContext -{ - public ProtonClientSessionContext(AMQPSessionCallback sessionSPI, AbstractConnectionContext connection, Session session) - { +public class ProtonClientSessionContext extends AbstractProtonSessionContext implements AMQPClientSessionContext { + + public ProtonClientSessionContext(AMQPSessionCallback sessionSPI, + AbstractConnectionContext connection, + Session session) { super(sessionSPI, connection, session); } - public AMQPClientSenderContext createSender(String address, boolean preSettled) throws ActiveMQAMQPException - { + public AMQPClientSenderContext createSender(String address, boolean preSettled) throws ActiveMQAMQPException { FutureRunnable futureRunnable = new FutureRunnable(1); ProtonClientContext amqpSender; - synchronized (connection.getLock()) - { + synchronized (connection.getLock()) { Sender sender = session.sender(address); sender.setSenderSettleMode(SenderSettleMode.SETTLED); Target target = new Target(); @@ -62,14 +61,12 @@ public class ProtonClientSessionContext extends AbstractProtonSessionContext imp return amqpSender; } - public AMQPClientReceiverContext createReceiver(String address) throws ActiveMQAMQPException - { + public AMQPClientReceiverContext createReceiver(String address) throws ActiveMQAMQPException { FutureRunnable futureRunnable = new FutureRunnable(1); ProtonClientReceiverContext amqpReceiver; - synchronized (connection.getLock()) - { + synchronized (connection.getLock()) { Receiver receiver = session.receiver(address); Source source = new Source(); source.setAddress(address); diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerConnectionContext.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerConnectionContext.java index 77cb170644..2dae0e6072 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerConnectionContext.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerConnectionContext.java @@ -28,49 +28,44 @@ import org.proton.plug.context.AbstractConnectionContext; import org.proton.plug.context.AbstractProtonSessionContext; import org.proton.plug.exceptions.ActiveMQAMQPException; -public class ProtonServerConnectionContext extends AbstractConnectionContext implements AMQPServerConnectionContext -{ - public ProtonServerConnectionContext(AMQPConnectionCallback connectionSP) - { +public class ProtonServerConnectionContext extends AbstractConnectionContext implements AMQPServerConnectionContext { + + public ProtonServerConnectionContext(AMQPConnectionCallback connectionSP) { super(connectionSP); } - public ProtonServerConnectionContext(AMQPConnectionCallback connectionSP, int idleTimeout, int maxFrameSize, int channelMax) - { + public ProtonServerConnectionContext(AMQPConnectionCallback connectionSP, + int idleTimeout, + int maxFrameSize, + int channelMax) { super(connectionSP, idleTimeout, maxFrameSize, channelMax); } - protected AbstractProtonSessionContext newSessionExtension(Session realSession) throws ActiveMQAMQPException - { + protected AbstractProtonSessionContext newSessionExtension(Session realSession) throws ActiveMQAMQPException { AMQPSessionCallback sessionSPI = connectionCallback.createSessionCallback(this); AbstractProtonSessionContext protonSession = new ProtonServerSessionContext(sessionSPI, this, realSession); return protonSession; } - protected void remoteLinkOpened(Link link) throws Exception - { + protected void remoteLinkOpened(Link link) throws Exception { ProtonServerSessionContext protonSession = (ProtonServerSessionContext) getSessionExtension(link.getSession()); link.setSource(link.getRemoteSource()); link.setTarget(link.getRemoteTarget()); - if (link instanceof Receiver) - { + if (link instanceof Receiver) { Receiver receiver = (Receiver) link; - if (link.getRemoteTarget() instanceof Coordinator) - { + if (link.getRemoteTarget() instanceof Coordinator) { Coordinator coordinator = (Coordinator) link.getRemoteTarget(); protonSession.addTransactionHandler(coordinator, receiver); } - else - { + else { protonSession.addReceiver(receiver); receiver.flow(100); } } - else - { + else { Sender sender = (Sender) link; protonSession.addSender(sender); sender.offer(1); diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerConnectionContextFactory.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerConnectionContextFactory.java index 3d538572d1..87242332cd 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerConnectionContextFactory.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerConnectionContextFactory.java @@ -24,26 +24,23 @@ import static org.proton.plug.context.AMQPConstants.Connection.DEFAULT_IDLE_TIME import static org.proton.plug.context.AMQPConstants.Connection.DEFAULT_CHANNEL_MAX; import static org.proton.plug.context.AMQPConstants.Connection.DEFAULT_MAX_FRAME_SIZE; -public class ProtonServerConnectionContextFactory extends AMQPConnectionContextFactory -{ +public class ProtonServerConnectionContextFactory extends AMQPConnectionContextFactory { + private static final ProtonServerConnectionContextFactory theInstance = new ProtonServerConnectionContextFactory(); - public static ProtonServerConnectionContextFactory getFactory() - { + public static ProtonServerConnectionContextFactory getFactory() { return theInstance; } - public AMQPServerConnectionContext createConnection(AMQPConnectionCallback connectionCallback) - { - return createConnection(connectionCallback,DEFAULT_IDLE_TIMEOUT, DEFAULT_MAX_FRAME_SIZE, DEFAULT_CHANNEL_MAX); + public AMQPServerConnectionContext createConnection(AMQPConnectionCallback connectionCallback) { + return createConnection(connectionCallback, DEFAULT_IDLE_TIMEOUT, DEFAULT_MAX_FRAME_SIZE, DEFAULT_CHANNEL_MAX); } @Override - public AMQPServerConnectionContext createConnection(AMQPConnectionCallback connectionCallback, int idleTimeout, int maxFrameSize, int channelMax) - { - return new ProtonServerConnectionContext(connectionCallback, - idleTimeout, - maxFrameSize, - channelMax); + public AMQPServerConnectionContext createConnection(AMQPConnectionCallback connectionCallback, + int idleTimeout, + int maxFrameSize, + int channelMax) { + return new ProtonServerConnectionContext(connectionCallback, idleTimeout, maxFrameSize, channelMax); } } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerReceiverContext.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerReceiverContext.java index 1f687eeee4..bbbfd759bb 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerReceiverContext.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerReceiverContext.java @@ -34,64 +34,52 @@ import org.proton.plug.logger.ActiveMQAMQPProtocolMessageBundle; import static org.proton.plug.util.DeliveryUtil.readDelivery; -public class ProtonServerReceiverContext extends AbstractProtonReceiverContext -{ +public class ProtonServerReceiverContext extends AbstractProtonReceiverContext { private final int numberOfCredits = 100; - public ProtonServerReceiverContext(AMQPSessionCallback sessionSPI, AbstractConnectionContext connection, AbstractProtonSessionContext protonSession, Receiver receiver) - { + public ProtonServerReceiverContext(AMQPSessionCallback sessionSPI, + AbstractConnectionContext connection, + AbstractProtonSessionContext protonSession, + Receiver receiver) { super(sessionSPI, connection, protonSession, receiver); } - public void onFlow(int credits) - { + public void onFlow(int credits) { } - @Override - public void initialise() throws Exception - { + public void initialise() throws Exception { super.initialise(); org.apache.qpid.proton.amqp.messaging.Target target = (org.apache.qpid.proton.amqp.messaging.Target) receiver.getRemoteTarget(); - if (target != null) - { - if (target.getDynamic()) - { + if (target != null) { + if (target.getDynamic()) { //if dynamic we have to create the node (queue) and set the address on the target, the node is temporary and // will be deleted on closing of the session String queue = sessionSPI.tempQueueName(); - - try - { + try { sessionSPI.createTemporaryQueue(queue); } - catch (Exception e) - { + catch (Exception e) { throw new ActiveMQAMQPInternalErrorException(e.getMessage(), e); } target.setAddress(queue.toString()); } - else - { + else { //if not dynamic then we use the targets address as the address to forward the messages to, however there has to //be a queue bound to it so we nee to check this. String address = target.getAddress(); - if (address == null) - { + if (address == null) { throw ActiveMQAMQPProtocolMessageBundle.BUNDLE.targetAddressNotSet(); } - try - { - if (!sessionSPI.queueQuery(address)) - { + try { + if (!sessionSPI.queueQuery(address)) { throw ActiveMQAMQPProtocolMessageBundle.BUNDLE.addressDoesntExist(); } } - catch (Exception e) - { + catch (Exception e) { throw ActiveMQAMQPProtocolMessageBundle.BUNDLE.errorFindingTemporaryQueue(e.getMessage()); } } @@ -106,24 +94,19 @@ public class ProtonServerReceiverContext extends AbstractProtonReceiverContext * This may be called more than once per deliver so we have to cache the buffer until we have received it all. * * */ - public void onMessage(Delivery delivery) throws ActiveMQAMQPException - { + public void onMessage(Delivery delivery) throws ActiveMQAMQPException { Receiver receiver; - try - { + try { receiver = ((Receiver) delivery.getLink()); - if (!delivery.isReadable()) - { + if (!delivery.isReadable()) { System.err.println("!!!!! Readable!!!!!!!"); return; } ByteBuf buffer = PooledByteBufAllocator.DEFAULT.heapBuffer(10 * 1024); - try - { - synchronized (connection.getLock()) - { + try { + synchronized (connection.getLock()) { readDelivery(receiver, buffer); receiver.advance(); @@ -132,19 +115,16 @@ public class ProtonServerReceiverContext extends AbstractProtonReceiverContext delivery.disposition(Accepted.getInstance()); delivery.settle(); - if (receiver.getRemoteCredit() < numberOfCredits / 2) - { + if (receiver.getRemoteCredit() < numberOfCredits / 2) { flow(numberOfCredits); } } } - finally - { + finally { buffer.release(); } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); Rejected rejected = new Rejected(); ErrorCondition condition = new ErrorCondition(); diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerSenderContext.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerSenderContext.java index df173c0268..71efa3c1d4 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerSenderContext.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerSenderContext.java @@ -39,26 +39,25 @@ import org.proton.plug.logger.ActiveMQAMQPProtocolMessageBundle; import org.proton.plug.context.ProtonPlugSender; import org.apache.qpid.proton.amqp.messaging.Source; -public class ProtonServerSenderContext extends AbstractProtonContextSender implements ProtonPlugSender -{ +public class ProtonServerSenderContext extends AbstractProtonContextSender implements ProtonPlugSender { private static final Symbol SELECTOR = Symbol.getSymbol("jms-selector"); private static final Symbol COPY = Symbol.valueOf("copy"); private Object brokerConsumer; - public ProtonServerSenderContext(AbstractConnectionContext connection, Sender sender, AbstractProtonSessionContext protonSession, AMQPSessionCallback server) - { + public ProtonServerSenderContext(AbstractConnectionContext connection, + Sender sender, + AbstractProtonSessionContext protonSession, + AMQPSessionCallback server) { super(connection, sender, protonSession, server); } - public Object getBrokerConsumer() - { + public Object getBrokerConsumer() { return brokerConsumer; } - public void onFlow(int currentCredits) - { + public void onFlow(int currentCredits) { super.onFlow(currentCredits); sessionSPI.onFlowConsumer(brokerConsumer, currentCredits); } @@ -66,20 +65,17 @@ public class ProtonServerSenderContext extends AbstractProtonContextSender imple /* * start the session * */ - public void start() throws ActiveMQAMQPException - { + public void start() throws ActiveMQAMQPException { super.start(); // protonSession.getServerSession().start(); //todo add flow control - try - { + try { // to do whatever you need to make the broker start sending messages to the consumer sessionSPI.startSender(brokerConsumer); //protonSession.getServerSession().receiveConsumerCredits(consumerID, -1); } - catch (Exception e) - { + catch (Exception e) { throw ActiveMQAMQPProtocolMessageBundle.BUNDLE.errorStartingConsumer(e.getMessage()); } } @@ -88,8 +84,7 @@ public class ProtonServerSenderContext extends AbstractProtonContextSender imple * create the actual underlying ActiveMQ Artemis Server Consumer */ @Override - public void initialise() throws Exception - { + public void initialise() throws Exception { super.initialise(); Source source = (Source) sender.getRemoteSource(); @@ -98,63 +93,50 @@ public class ProtonServerSenderContext extends AbstractProtonContextSender imple String selector = null; Map filter = source == null ? null : source.getFilter(); - if (filter != null) - { + if (filter != null) { DescribedType value = (DescribedType) filter.get(SELECTOR); - if (value != null) - { + if (value != null) { selector = value.getDescribed().toString(); } } - if (source != null) - { - if (source.getDynamic()) - { + if (source != null) { + if (source.getDynamic()) { //if dynamic we have to create the node (queue) and set the address on the target, the node is temporary and // will be deleted on closing of the session queue = java.util.UUID.randomUUID().toString(); - try - { + try { sessionSPI.createTemporaryQueue(queue); //protonSession.getServerSession().createQueue(queue, queue, null, true, false); } - catch (Exception e) - { + catch (Exception e) { throw ActiveMQAMQPProtocolMessageBundle.BUNDLE.errorCreatingTemporaryQueue(e.getMessage()); } source.setAddress(queue); } - else - { + else { //if not dynamic then we use the targets address as the address to forward the messages to, however there has to //be a queue bound to it so we nee to check this. queue = source.getAddress(); - if (queue == null) - { + if (queue == null) { throw ActiveMQAMQPProtocolMessageBundle.BUNDLE.sourceAddressNotSet(); } - try - { - if (!sessionSPI.queueQuery(queue)) - { + try { + if (!sessionSPI.queueQuery(queue)) { throw ActiveMQAMQPProtocolMessageBundle.BUNDLE.sourceAddressDoesntExist(); } } - catch (Exception e) - { + catch (Exception e) { throw new ActiveMQAMQPInternalErrorException(e.getMessage(), e); } } boolean browseOnly = source.getDistributionMode() != null && source.getDistributionMode().equals(COPY); - try - { + try { brokerConsumer = sessionSPI.createSender(this, queue, selector, browseOnly); } - catch (Exception e) - { + catch (Exception e) { throw ActiveMQAMQPProtocolMessageBundle.BUNDLE.errorCreatingConsumer(e.getMessage()); } } @@ -163,114 +145,89 @@ public class ProtonServerSenderContext extends AbstractProtonContextSender imple /* * close the session * */ - public void close() throws ActiveMQAMQPException - { + public void close() throws ActiveMQAMQPException { super.close(); - try - { + try { sessionSPI.closeSender(brokerConsumer); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); throw new ActiveMQAMQPInternalErrorException(e.getMessage()); } } - - public void onMessage(Delivery delivery) throws ActiveMQAMQPException - { + public void onMessage(Delivery delivery) throws ActiveMQAMQPException { Object message = delivery.getContext(); boolean preSettle = sender.getRemoteSenderSettleMode() == SenderSettleMode.SETTLED; - DeliveryState remoteState = delivery.getRemoteState(); - if (remoteState != null) - { - if (remoteState instanceof Accepted) - { + if (remoteState != null) { + if (remoteState instanceof Accepted) { //we have to individual ack as we can't guarantee we will get the delivery updates (including acks) in order // from dealer, a perf hit but a must - try - { + try { sessionSPI.ack(brokerConsumer, message); } - catch (Exception e) - { + catch (Exception e) { throw ActiveMQAMQPProtocolMessageBundle.BUNDLE.errorAcknowledgingMessage(message.toString(), e.getMessage()); } } - else if (remoteState instanceof Released) - { - try - { + else if (remoteState instanceof Released) { + try { sessionSPI.cancel(brokerConsumer, message, false); } - catch (Exception e) - { + catch (Exception e) { throw ActiveMQAMQPProtocolMessageBundle.BUNDLE.errorCancellingMessage(message.toString(), e.getMessage()); } } - else if (remoteState instanceof Rejected || remoteState instanceof Modified) - { - try - { + else if (remoteState instanceof Rejected || remoteState instanceof Modified) { + try { sessionSPI.cancel(brokerConsumer, message, true); } - catch (Exception e) - { + catch (Exception e) { throw ActiveMQAMQPProtocolMessageBundle.BUNDLE.errorCancellingMessage(message.toString(), e.getMessage()); } } //todo add tag caching - if (!preSettle) - { + if (!preSettle) { protonSession.replaceTag(delivery.getTag()); } - synchronized (connection.getLock()) - { + synchronized (connection.getLock()) { delivery.settle(); sender.offer(1); } } - else - { + else { //todo not sure if we need to do anything here } } @Override - public synchronized void checkState() - { + public synchronized void checkState() { super.checkState(); sessionSPI.resumeDelivery(brokerConsumer); } - /** * handle an out going message from ActiveMQ Artemis, send via the Proton Sender */ - public int deliverMessage(Object message, int deliveryCount) throws Exception - { - if (closed) - { + public int deliverMessage(Object message, int deliveryCount) throws Exception { + if (closed) { System.err.println("Message can't be delivered as it's closed"); return 0; } //encode the message ProtonJMessage serverMessage; - try - { + try { // This can be done a lot better here serverMessage = sessionSPI.encodeMessage(message, deliveryCount); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); throw new ActiveMQAMQPInternalErrorException(e.getMessage(), e); } @@ -278,5 +235,4 @@ public class ProtonServerSenderContext extends AbstractProtonContextSender imple return performSend(serverMessage, message); } - } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerSessionContext.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerSessionContext.java index c6a19c59f3..bbeeebd2f2 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerSessionContext.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerSessionContext.java @@ -32,17 +32,16 @@ import org.proton.plug.context.AbstractProtonSessionContext; import org.proton.plug.context.ProtonTransactionHandler; import org.proton.plug.exceptions.ActiveMQAMQPException; -public class ProtonServerSessionContext extends AbstractProtonSessionContext -{ +public class ProtonServerSessionContext extends AbstractProtonSessionContext { - public ProtonServerSessionContext(AMQPSessionCallback sessionSPI, AbstractConnectionContext connection, Session session) - { + public ProtonServerSessionContext(AMQPSessionCallback sessionSPI, + AbstractConnectionContext connection, + Session session) { super(sessionSPI, connection, session); } protected Map serverSenders = new HashMap(); - /** * The consumer object from the broker or the key used to store the sender * @@ -51,30 +50,25 @@ public class ProtonServerSessionContext extends AbstractProtonSessionContext * @param deliveryCount * @return the number of bytes sent */ - public int serverDelivery(Object message, Object consumer, int deliveryCount) throws Exception - { + public int serverDelivery(Object message, Object consumer, int deliveryCount) throws Exception { ProtonServerSenderContext protonSender = (ProtonServerSenderContext) serverSenders.get(consumer); - if (protonSender != null) - { + if (protonSender != null) { return protonSender.deliverMessage(message, deliveryCount); } return 0; } - public void addTransactionHandler(Coordinator coordinator, Receiver receiver) - { + public void addTransactionHandler(Coordinator coordinator, Receiver receiver) { ProtonTransactionHandler transactionHandler = new ProtonTransactionHandler(sessionSPI); receiver.setContext(transactionHandler); receiver.open(); receiver.flow(100); } - public void addSender(Sender sender) throws Exception - { + public void addSender(Sender sender) throws Exception { ProtonServerSenderContext protonSender = new ProtonServerSenderContext(connection, sender, this, sessionSPI); - try - { + try { protonSender.initialise(); senders.put(sender, protonSender); serverSenders.put(protonSender.getBrokerConsumer(), protonSender); @@ -82,8 +76,7 @@ public class ProtonServerSessionContext extends AbstractProtonSessionContext sender.open(); protonSender.start(); } - catch (ActiveMQAMQPException e) - { + catch (ActiveMQAMQPException e) { senders.remove(sender); sender.setSource(null); sender.setCondition(new ErrorCondition(e.getAmqpError(), e.getMessage())); @@ -91,28 +84,22 @@ public class ProtonServerSessionContext extends AbstractProtonSessionContext } } - public void removeSender(Sender sender) throws ActiveMQAMQPException - { + public void removeSender(Sender sender) throws ActiveMQAMQPException { ProtonServerSenderContext senderRemoved = (ProtonServerSenderContext) senders.remove(sender); - if (senderRemoved != null) - { + if (senderRemoved != null) { serverSenders.remove(senderRemoved.getBrokerConsumer()); } } - - public void addReceiver(Receiver receiver) throws Exception - { - try - { + public void addReceiver(Receiver receiver) throws Exception { + try { AbstractProtonReceiverContext protonReceiver = new ProtonServerReceiverContext(sessionSPI, connection, this, receiver); protonReceiver.initialise(); receivers.put(receiver, protonReceiver); receiver.setContext(protonReceiver); receiver.open(); } - catch (ActiveMQAMQPException e) - { + catch (ActiveMQAMQPException e) { receivers.remove(receiver); receiver.setTarget(null); receiver.setCondition(new ErrorCondition(e.getAmqpError(), e.getMessage())); diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/exceptions/ActiveMQAMQPException.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/exceptions/ActiveMQAMQPException.java index 3019fcda3b..6e240e35d7 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/exceptions/ActiveMQAMQPException.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/exceptions/ActiveMQAMQPException.java @@ -18,26 +18,22 @@ package org.proton.plug.exceptions; import org.apache.qpid.proton.amqp.Symbol; -public class ActiveMQAMQPException extends Exception -{ +public class ActiveMQAMQPException extends Exception { private static final String ERROR_PREFIX = "amqp:"; - public Symbol getAmqpError() - { + public Symbol getAmqpError() { return amqpError; } private final Symbol amqpError; - public ActiveMQAMQPException(Symbol amqpError, String message, Throwable e) - { + public ActiveMQAMQPException(Symbol amqpError, String message, Throwable e) { super(message, e); this.amqpError = amqpError; } - public ActiveMQAMQPException(Symbol amqpError, String message) - { + public ActiveMQAMQPException(Symbol amqpError, String message) { super(message); this.amqpError = amqpError; } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/exceptions/ActiveMQAMQPIllegalStateException.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/exceptions/ActiveMQAMQPIllegalStateException.java index 33f6da7910..cdbf4fa27e 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/exceptions/ActiveMQAMQPIllegalStateException.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/exceptions/ActiveMQAMQPIllegalStateException.java @@ -18,10 +18,9 @@ package org.proton.plug.exceptions; import org.apache.qpid.proton.amqp.transport.AmqpError; -public class ActiveMQAMQPIllegalStateException extends ActiveMQAMQPException -{ - public ActiveMQAMQPIllegalStateException(String message) - { +public class ActiveMQAMQPIllegalStateException extends ActiveMQAMQPException { + + public ActiveMQAMQPIllegalStateException(String message) { super(AmqpError.ILLEGAL_STATE, message); } } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/exceptions/ActiveMQAMQPInternalErrorException.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/exceptions/ActiveMQAMQPInternalErrorException.java index 896ffd4257..e30073ca06 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/exceptions/ActiveMQAMQPInternalErrorException.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/exceptions/ActiveMQAMQPInternalErrorException.java @@ -18,15 +18,13 @@ package org.proton.plug.exceptions; import org.apache.qpid.proton.amqp.transport.AmqpError; -public class ActiveMQAMQPInternalErrorException extends ActiveMQAMQPException -{ - public ActiveMQAMQPInternalErrorException(String message, Throwable e) - { +public class ActiveMQAMQPInternalErrorException extends ActiveMQAMQPException { + + public ActiveMQAMQPInternalErrorException(String message, Throwable e) { super(AmqpError.INTERNAL_ERROR, message, e); } - public ActiveMQAMQPInternalErrorException(String message) - { + public ActiveMQAMQPInternalErrorException(String message) { super(AmqpError.INTERNAL_ERROR, message); } } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/exceptions/ActiveMQAMQPInvalidFieldException.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/exceptions/ActiveMQAMQPInvalidFieldException.java index c7f385f126..c6978a252c 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/exceptions/ActiveMQAMQPInvalidFieldException.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/exceptions/ActiveMQAMQPInvalidFieldException.java @@ -18,10 +18,9 @@ package org.proton.plug.exceptions; import org.apache.qpid.proton.amqp.transport.AmqpError; -public class ActiveMQAMQPInvalidFieldException extends ActiveMQAMQPException -{ - public ActiveMQAMQPInvalidFieldException(String message) - { +public class ActiveMQAMQPInvalidFieldException extends ActiveMQAMQPException { + + public ActiveMQAMQPInvalidFieldException(String message) { super(AmqpError.INVALID_FIELD, message); } } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/exceptions/ActiveMQAMQPNotImplementedException.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/exceptions/ActiveMQAMQPNotImplementedException.java index a74b218ca0..6a1c95c8de 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/exceptions/ActiveMQAMQPNotImplementedException.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/exceptions/ActiveMQAMQPNotImplementedException.java @@ -18,10 +18,9 @@ package org.proton.plug.exceptions; import org.apache.qpid.proton.amqp.transport.AmqpError; -public class ActiveMQAMQPNotImplementedException extends ActiveMQAMQPException -{ - public ActiveMQAMQPNotImplementedException(String message) - { +public class ActiveMQAMQPNotImplementedException extends ActiveMQAMQPException { + + public ActiveMQAMQPNotImplementedException(String message) { super(AmqpError.NOT_IMPLEMENTED, message); } } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/exceptions/ActiveMQAMQPTimeoutException.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/exceptions/ActiveMQAMQPTimeoutException.java index 9e8eea32b9..25b4ea6807 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/exceptions/ActiveMQAMQPTimeoutException.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/exceptions/ActiveMQAMQPTimeoutException.java @@ -18,10 +18,9 @@ package org.proton.plug.exceptions; import org.apache.qpid.proton.amqp.transport.AmqpError; -public class ActiveMQAMQPTimeoutException extends ActiveMQAMQPException -{ - public ActiveMQAMQPTimeoutException(String message) - { +public class ActiveMQAMQPTimeoutException extends ActiveMQAMQPException { + + public ActiveMQAMQPTimeoutException(String message) { super(AmqpError.ILLEGAL_STATE, message); } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/handler/EventHandler.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/handler/EventHandler.java index 870a9c6a87..e96169fc98 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/handler/EventHandler.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/handler/EventHandler.java @@ -25,8 +25,7 @@ import org.apache.qpid.proton.engine.Transport; /** * EventHandler */ -public interface EventHandler -{ +public interface EventHandler { void onSASLInit(ProtonHandler handler, Connection connection); diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/handler/Events.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/handler/Events.java index e2b06d70e8..2f978c7de2 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/handler/Events.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/handler/Events.java @@ -22,18 +22,14 @@ import org.apache.qpid.proton.engine.Transport; /** * TODO : this needs a better home */ -public final class Events -{ +public final class Events { - public static void dispatchTransport(Transport transport, EventHandler handler) throws Exception - { + public static void dispatchTransport(Transport transport, EventHandler handler) throws Exception { handler.onTransport(transport); } - public static void dispatch(Event event, EventHandler handler) throws Exception - { - switch (event.getType()) - { + public static void dispatch(Event event, EventHandler handler) throws Exception { + switch (event.getType()) { case CONNECTION_INIT: handler.onInit(event.getConnection()); break; diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/handler/ProtonHandler.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/handler/ProtonHandler.java index d258be570a..366663c260 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/handler/ProtonHandler.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/handler/ProtonHandler.java @@ -27,18 +27,15 @@ import org.proton.plug.handler.impl.ProtonHandlerImpl; /** * This is a definition of the public interface for {@link org.proton.plug.handler.impl.ProtonHandlerImpl} */ -public interface ProtonHandler -{ +public interface ProtonHandler { - public static final class Factory - { - public static ProtonHandler create() - { + public static final class Factory { + + public static ProtonHandler create() { return new ProtonHandlerImpl(); } } - /** * It returns true if the transport connection has any capacity available * @@ -123,7 +120,6 @@ public interface ProtonHandler */ void close(); - /** * Get the object used to lock transport, connection and events operations * diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/handler/impl/DefaultEventHandler.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/handler/impl/DefaultEventHandler.java index 8fb4100e19..45d5b67cfc 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/handler/impl/DefaultEventHandler.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/handler/impl/DefaultEventHandler.java @@ -26,143 +26,119 @@ import org.proton.plug.handler.EventHandler; /** * This is useful for cases where you only want to implement a few methods */ -public abstract class DefaultEventHandler implements EventHandler -{ +public abstract class DefaultEventHandler implements EventHandler { + @Override - public void onInit(Connection connection) throws Exception - { + public void onInit(Connection connection) throws Exception { } @Override - public void onLocalOpen(Connection connection) throws Exception - { + public void onLocalOpen(Connection connection) throws Exception { } @Override - public void onRemoteOpen(Connection connection) throws Exception - { + public void onRemoteOpen(Connection connection) throws Exception { } @Override - public void onLocalClose(Connection connection) throws Exception - { + public void onLocalClose(Connection connection) throws Exception { } @Override - public void onRemoteClose(Connection connection) throws Exception - { + public void onRemoteClose(Connection connection) throws Exception { } @Override - public void onFinal(Connection connection) throws Exception - { + public void onFinal(Connection connection) throws Exception { } @Override - public void onInit(Session session) throws Exception - { + public void onInit(Session session) throws Exception { } @Override - public void onLocalOpen(Session session) throws Exception - { + public void onLocalOpen(Session session) throws Exception { } @Override - public void onRemoteOpen(Session session) throws Exception - { + public void onRemoteOpen(Session session) throws Exception { } @Override - public void onLocalClose(Session session) throws Exception - { + public void onLocalClose(Session session) throws Exception { } @Override - public void onRemoteClose(Session session) throws Exception - { + public void onRemoteClose(Session session) throws Exception { } @Override - public void onFinal(Session session) throws Exception - { + public void onFinal(Session session) throws Exception { } @Override - public void onInit(Link link) throws Exception - { + public void onInit(Link link) throws Exception { } @Override - public void onLocalOpen(Link link) throws Exception - { + public void onLocalOpen(Link link) throws Exception { } @Override - public void onRemoteOpen(Link link) throws Exception - { + public void onRemoteOpen(Link link) throws Exception { } @Override - public void onLocalClose(Link link) throws Exception - { + public void onLocalClose(Link link) throws Exception { } @Override - public void onRemoteClose(Link link) throws Exception - { + public void onRemoteClose(Link link) throws Exception { } @Override - public void onFlow(Link link) throws Exception - { + public void onFlow(Link link) throws Exception { } @Override - public void onFinal(Link link) throws Exception - { - - } - - - @Override - public void onRemoteDetach(Link link) throws Exception - { + public void onFinal(Link link) throws Exception { } @Override - public void onDetach(Link link) throws Exception - { + public void onRemoteDetach(Link link) throws Exception { } @Override - public void onDelivery(Delivery delivery) throws Exception - { + public void onDetach(Link link) throws Exception { } @Override - public void onTransport(Transport transport) throws Exception - { + public void onDelivery(Delivery delivery) throws Exception { + + } + + @Override + public void onTransport(Transport transport) throws Exception { } } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/handler/impl/ProtonHandlerImpl.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/handler/impl/ProtonHandlerImpl.java index d2106d5f4a..f7f8f92102 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/handler/impl/ProtonHandlerImpl.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/handler/impl/ProtonHandlerImpl.java @@ -43,8 +43,8 @@ import org.proton.plug.util.DebugInfo; /** * Clebert Suconic */ -public class ProtonHandlerImpl extends ProtonInitializable implements ProtonHandler -{ +public class ProtonHandlerImpl extends ProtonInitializable implements ProtonHandler { + private final Transport transport = Proton.transport(); private final Connection connection = Proton.connection(); @@ -76,55 +76,46 @@ public class ProtonHandlerImpl extends ProtonInitializable implements ProtonHand private int offset = 0; - public ProtonHandlerImpl() - { + public ProtonHandlerImpl() { this.creationTime = System.currentTimeMillis(); transport.bind(connection); connection.collect(collector); } @Override - public int capacity() - { - synchronized (lock) - { + public int capacity() { + synchronized (lock) { return transport.capacity(); } } - public Object getLock() - { + public Object getLock() { return lock; } @Override - public Transport getTransport() - { + public Transport getTransport() { return transport; } @Override - public Connection getConnection() - { + public Connection getConnection() { return connection; } @Override - public ProtonHandler addEventHandler(EventHandler handler) - { + public ProtonHandler addEventHandler(EventHandler handler) { handlers.add(handler); return this; } @Override - public void createServerSASL(ServerSASL[] handlers) - { + public void createServerSASL(ServerSASL[] handlers) { this.serverSasl = transport.sasl(); saslHandlers = new HashMap<>(); String[] names = new String[handlers.length]; int count = 0; - for (ServerSASL handler : handlers) - { + for (ServerSASL handler : handlers) { saslHandlers.put(handler.getName(), handler); names[count++] = handler.getName(); } @@ -134,57 +125,43 @@ public class ProtonHandlerImpl extends ProtonInitializable implements ProtonHand } @Override - public SASLResult getSASLResult() - { + public SASLResult getSASLResult() { return saslResult; } @Override - public void inputBuffer(ByteBuf buffer) - { + public void inputBuffer(ByteBuf buffer) { dataReceived = true; - synchronized (lock) - { - while (buffer.readableBytes() > 0) - { + synchronized (lock) { + while (buffer.readableBytes() > 0) { int capacity = transport.capacity(); - if (!receivedFirstPacket) - { - try - { - if (buffer.getByte(4) == 0x03) - { + if (!receivedFirstPacket) { + try { + if (buffer.getByte(4) == 0x03) { dispatchSASL(); } } - catch (Throwable ignored) - { + catch (Throwable ignored) { ignored.printStackTrace(); } receivedFirstPacket = true; } - - if (capacity > 0) - { + if (capacity > 0) { ByteBuffer tail = transport.tail(); int min = Math.min(capacity, buffer.readableBytes()); tail.limit(min); buffer.readBytes(tail); - flush(); } - else - { - if (capacity == 0) - { + else { + if (capacity == 0) { System.out.println("abandoning: " + buffer.readableBytes()); } - else - { + else { System.out.println("transport closed, discarding: " + buffer.readableBytes() + " capacity = " + transport.capacity()); } break; @@ -193,10 +170,8 @@ public class ProtonHandlerImpl extends ProtonInitializable implements ProtonHand } } - @Override - public boolean checkDataReceived() - { + public boolean checkDataReceived() { boolean res = dataReceived; dataReceived = false; @@ -205,21 +180,17 @@ public class ProtonHandlerImpl extends ProtonInitializable implements ProtonHand } @Override - public long getCreationTime() - { + public long getCreationTime() { return creationTime; } @Override - public void outputDone(int bytes) - { - synchronized (lock) - { + public void outputDone(int bytes) { + synchronized (lock) { transport.pop(bytes); offset -= bytes; - if (offset < 0) - { + if (offset < 0) { throw new IllegalStateException("You called outputDone for more bytes than you actually received. numberOfBytes=" + bytes + ", outcome result=" + offset); } @@ -229,27 +200,22 @@ public class ProtonHandlerImpl extends ProtonInitializable implements ProtonHand } @Override - public ByteBuf outputBuffer() - { + public ByteBuf outputBuffer() { - synchronized (lock) - { + synchronized (lock) { int pending = transport.pending(); - if (pending < 0) - { + if (pending < 0) { return null;//throw new IllegalStateException("xxx need to close the connection"); } int size = pending - offset; - if (size < 0) - { + if (size < 0) { throw new IllegalStateException("negative size: " + pending); } - if (size == 0) - { + if (size == 0) { return null; } @@ -263,10 +229,8 @@ public class ProtonHandlerImpl extends ProtonInitializable implements ProtonHand } } - public void createClientSasl(ClientSASL clientSASL) - { - if (clientSASL != null) - { + public void createClientSasl(ClientSASL clientSASL) { + if (clientSASL != null) { clientSasl = transport.sasl(); clientSasl.setMechanisms(clientSASL.getName()); byte[] initialSasl = clientSASL.getBytes(); @@ -274,18 +238,14 @@ public class ProtonHandlerImpl extends ProtonInitializable implements ProtonHand } } - @Override - public void flush() - { - synchronized (lock) - { + public void flush() { + synchronized (lock) { transport.process(); checkServerSASL(); - if (dispatching) - { + if (dispatching) { return; } @@ -293,73 +253,59 @@ public class ProtonHandlerImpl extends ProtonInitializable implements ProtonHand } - try - { + try { dispatch(); } - finally - { + finally { dispatching = false; } } @Override - public void close() - { - synchronized (lock) - { + public void close() { + synchronized (lock) { connection.close(); } flush(); } - protected void checkServerSASL() - { - if (serverSasl != null && serverSasl.getRemoteMechanisms().length > 0) - { + protected void checkServerSASL() { + if (serverSasl != null && serverSasl.getRemoteMechanisms().length > 0) { // TODO: should we look at the first only? ServerSASL mechanism = saslHandlers.get(serverSasl.getRemoteMechanisms()[0]); - if (mechanism != null) - { + if (mechanism != null) { byte[] dataSASL = new byte[serverSasl.pending()]; serverSasl.recv(dataSASL, 0, dataSASL.length); - if (DebugInfo.debug) - { + if (DebugInfo.debug) { System.out.println("Working on sasl::" + ByteUtil.bytesToHex(dataSASL, 2)); } saslResult = mechanism.processSASL(dataSASL); - if (saslResult != null && saslResult.isSuccess()) - { + if (saslResult != null && saslResult.isSuccess()) { serverSasl.done(Sasl.SaslOutcome.PN_SASL_OK); serverSasl = null; saslHandlers.clear(); saslHandlers = null; } - else - { + else { serverSasl.done(Sasl.SaslOutcome.PN_SASL_AUTH); } serverSasl = null; } - else - { + else { // no auth available, system error serverSasl.done(Sasl.SaslOutcome.PN_SASL_SYS); } } } - private Event popEvent() - { - synchronized (lock) - { + private Event popEvent() { + synchronized (lock) { Event ev = collector.peek(); - if (ev != null) - { + if (ev != null) { // pop will invalidate the event // for that reason we make a new one // Events are reused inside the collector, so we need to make a new one here @@ -370,36 +316,27 @@ public class ProtonHandlerImpl extends ProtonInitializable implements ProtonHand } } - private void dispatchSASL() - { - for (EventHandler h: handlers) - { + private void dispatchSASL() { + for (EventHandler h : handlers) { h.onSASLInit(this, getConnection()); } } - - private void dispatch() - { + private void dispatch() { Event ev; // We don't hold a lock on the entire event processing // because we could have a distributed deadlock // while processing events (for instance onTransport) // while a client is also trying to write here - while ((ev = popEvent()) != null) - { - for (EventHandler h : handlers) - { - if (DebugInfo.debug) - { + while ((ev = popEvent()) != null) { + for (EventHandler h : handlers) { + if (DebugInfo.debug) { System.out.println("Handling " + ev + " towards " + h); } - try - { + try { Events.dispatch(ev, h); } - catch (Exception e) - { + catch (Exception e) { // TODO: logs e.printStackTrace(); connection.setCondition(new ErrorCondition()); @@ -407,14 +344,11 @@ public class ProtonHandlerImpl extends ProtonInitializable implements ProtonHand } } - for (EventHandler h : handlers) - { - try - { + for (EventHandler h : handlers) { + try { h.onTransport(transport); } - catch (Exception e) - { + catch (Exception e) { // TODO: logs e.printStackTrace(); connection.setCondition(new ErrorCondition()); diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/logger/ActiveMQAMQPProtocolMessageBundle.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/logger/ActiveMQAMQPProtocolMessageBundle.java index 978f00fd49..da919ae237 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/logger/ActiveMQAMQPProtocolMessageBundle.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/logger/ActiveMQAMQPProtocolMessageBundle.java @@ -33,10 +33,9 @@ import org.jboss.logging.Messages; * articles. Unused methods should be marked as deprecated. */ @MessageBundle(projectCode = "AMQ") -public interface ActiveMQAMQPProtocolMessageBundle -{ - ActiveMQAMQPProtocolMessageBundle BUNDLE = Messages.getBundle(ActiveMQAMQPProtocolMessageBundle.class); +public interface ActiveMQAMQPProtocolMessageBundle { + ActiveMQAMQPProtocolMessageBundle BUNDLE = Messages.getBundle(ActiveMQAMQPProtocolMessageBundle.class); @Message(id = 219000, value = "target address not set") ActiveMQAMQPInvalidFieldException targetAddressNotSet(); diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/sasl/AnonymousServerSASL.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/sasl/AnonymousServerSASL.java index 7f0a248de8..d52df404d4 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/sasl/AnonymousServerSASL.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/sasl/AnonymousServerSASL.java @@ -19,21 +19,18 @@ package org.proton.plug.sasl; import org.proton.plug.SASLResult; import org.proton.plug.ServerSASL; -public class AnonymousServerSASL implements ServerSASL -{ - public AnonymousServerSASL() - { +public class AnonymousServerSASL implements ServerSASL { + + public AnonymousServerSASL() { } @Override - public String getName() - { + public String getName() { return "ANONYMOUS"; } @Override - public SASLResult processSASL(byte[] bytes) - { + public SASLResult processSASL(byte[] bytes) { return new PlainSASLResult(true, null, null); } } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/sasl/ClientSASLPlain.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/sasl/ClientSASLPlain.java index fbdac71f91..341e7d80db 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/sasl/ClientSASLPlain.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/sasl/ClientSASLPlain.java @@ -22,32 +22,27 @@ import org.proton.plug.ClientSASL; * This is a simple implementation provided with just user/password * TODO: this interface will probaby change as we are challenged with more SASL cases where there is a communication between client and server to determine the authentication */ -public class ClientSASLPlain implements ClientSASL -{ +public class ClientSASLPlain implements ClientSASL { + private String username; private String password; - public ClientSASLPlain(String user, String password) - { + public ClientSASLPlain(String user, String password) { this.username = user; this.password = password; } - public String getName() - { + public String getName() { return "PLAIN"; } - public byte[] getBytes() - { + public byte[] getBytes() { - if (username == null) - { + if (username == null) { username = ""; } - if (password == null) - { + if (password == null) { password = ""; } @@ -59,5 +54,4 @@ public class ClientSASLPlain implements ClientSASL return data; } - } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/sasl/PlainSASLResult.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/sasl/PlainSASLResult.java index 0c68f1638e..fe33886d76 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/sasl/PlainSASLResult.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/sasl/PlainSASLResult.java @@ -18,33 +18,29 @@ package org.proton.plug.sasl; import org.proton.plug.SASLResult; -public class PlainSASLResult implements SASLResult -{ +public class PlainSASLResult implements SASLResult { + private boolean success; private String user; private String password; - public PlainSASLResult(boolean success, String user, String password) - { + public PlainSASLResult(boolean success, String user, String password) { this.success = success; this.user = user; this.password = password; } @Override - public String getUser() - { + public String getUser() { return user; } - public String getPassword() - { + public String getPassword() { return password; } @Override - public boolean isSuccess() - { + public boolean isSuccess() { return success; } } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/sasl/ServerSASLPlain.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/sasl/ServerSASLPlain.java index f7bd86c171..37c8dd3de0 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/sasl/ServerSASLPlain.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/sasl/ServerSASLPlain.java @@ -19,38 +19,32 @@ package org.proton.plug.sasl; import org.proton.plug.SASLResult; import org.proton.plug.ServerSASL; -public class ServerSASLPlain implements ServerSASL -{ +public class ServerSASLPlain implements ServerSASL { + public static final String NAME = "PLAIN"; @Override - public String getName() - { + public String getName() { return NAME; } @Override - public SASLResult processSASL(byte[] data) - { + public SASLResult processSASL(byte[] data) { String username = null; String password = null; String bytes = new String(data); String[] credentials = bytes.split(Character.toString((char) 0)); int offSet = 0; - if (credentials.length > 0) - { - if (credentials[0].length() == 0) - { + if (credentials.length > 0) { + if (credentials[0].length() == 0) { offSet = 1; } - if (credentials.length >= offSet) - { + if (credentials.length >= offSet) { username = credentials[offSet]; } - if (credentials.length >= (offSet + 1)) - { + if (credentials.length >= (offSet + 1)) { password = credentials[offSet + 1]; } } @@ -60,15 +54,13 @@ public class ServerSASLPlain implements ServerSASL return new PlainSASLResult(success, username, password); } - /** * Hook for subclasses to perform the authentication here * * @param user * @param password */ - protected boolean authenticate(String user, String password) - { + protected boolean authenticate(String user, String password) { return true; } } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/ByteUtil.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/ByteUtil.java index c7211c7df7..a378c53460 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/ByteUtil.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/ByteUtil.java @@ -19,50 +19,41 @@ package org.proton.plug.util; import io.netty.buffer.ByteBuf; import io.netty.buffer.UnpooledByteBufAllocator; -public class ByteUtil -{ - public static void debugFrame(String message, ByteBuf byteIn) - { +public class ByteUtil { + + public static void debugFrame(String message, ByteBuf byteIn) { int location = byteIn.readerIndex(); // debugging byte[] frame = new byte[byteIn.writerIndex()]; byteIn.readBytes(frame); - try - { + try { System.out.println(message + "\n" + ByteUtil.formatGroup(ByteUtil.bytesToHex(frame), 8, 16)); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } byteIn.readerIndex(location); } - - public static String formatGroup(String str, int groupSize, int lineBreak) - { + public static String formatGroup(String str, int groupSize, int lineBreak) { StringBuffer buffer = new StringBuffer(); int line = 1; buffer.append("/* 1 */ \""); - for (int i = 0; i < str.length(); i += groupSize) - { + for (int i = 0; i < str.length(); i += groupSize) { buffer.append(str.substring(i, i + Math.min(str.length() - i, groupSize))); - if ((i + groupSize) % lineBreak == 0) - { + if ((i + groupSize) % lineBreak == 0) { buffer.append("\" +\n/* "); line++; - if (line < 10) - { + if (line < 10) { buffer.append(" "); } buffer.append(Integer.toString(line) + " */ \""); } - else if ((i + groupSize) % groupSize == 0 && str.length() - i > groupSize) - { + else if ((i + groupSize) % groupSize == 0 && str.length() - i > groupSize) { buffer.append("\" + \""); } } @@ -75,11 +66,9 @@ public class ByteUtil protected static final char[] hexArray = "0123456789ABCDEF".toCharArray(); - public static String bytesToHex(byte[] bytes) - { + public static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; - for (int j = 0; j < bytes.length; j++) - { + for (int j = 0; j < bytes.length; j++) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; @@ -87,45 +76,35 @@ public class ByteUtil return new String(hexChars); } - public static byte[] hexStringToByteArray(String s) - { + public static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; - for (int i = 0; i < len; i += 2) - { - data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) - + Character.digit(s.charAt(i + 1), 16)); + for (int i = 0; i < len; i += 2) { + data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16)); } return data; } - public static byte[] longToBytes(long x) - { + public static byte[] longToBytes(long x) { ByteBuf buffer = UnpooledByteBufAllocator.DEFAULT.heapBuffer(8, 8); buffer.writeLong(x); return buffer.array(); } - public static String maxString(String value, int size) - { - if (value.length() < size) - { + public static String maxString(String value, int size) { + if (value.length() < size) { return value; } - else - { + else { return value.substring(0, size / 2) + " ... " + value.substring(value.length() - size / 2); } } - public static String bytesToHex(byte[] bytes, int groupSize) - { + public static String bytesToHex(byte[] bytes, int groupSize) { char[] hexChars = new char[bytes.length * 2 + numberOfGroups(bytes, groupSize)]; int outPos = 0; - for (int j = 0; j < bytes.length; j++) - { - if (j > 0 && j % groupSize == 0) - { + for (int j = 0; j < bytes.length; j++) { + if (j > 0 && j % groupSize == 0) { hexChars[outPos++] = ' '; } int v = bytes[j] & 0xFF; @@ -135,17 +114,14 @@ public class ByteUtil return new String(hexChars); } - private static int numberOfGroups(byte[] bytes, int groupSize) - { + private static int numberOfGroups(byte[] bytes, int groupSize) { int groups = bytes.length / groupSize; - if (bytes.length % groupSize == 0) - { + if (bytes.length % groupSize == 0) { groups--; } return groups; } - } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/CodecCache.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/CodecCache.java index 9f16ad78a0..014efb0b1b 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/CodecCache.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/CodecCache.java @@ -20,11 +20,10 @@ import org.apache.qpid.proton.codec.AMQPDefinedTypes; import org.apache.qpid.proton.codec.DecoderImpl; import org.apache.qpid.proton.codec.EncoderImpl; -public class CodecCache -{ +public class CodecCache { + + private static class EncoderDecoderPair { - private static class EncoderDecoderPair - { DecoderImpl decoder = new DecoderImpl(); EncoderImpl encoder = new EncoderImpl(decoder); @@ -33,22 +32,18 @@ public class CodecCache } } - private static final ThreadLocal tlsCodec = new ThreadLocal() - { + private static final ThreadLocal tlsCodec = new ThreadLocal() { @Override - protected EncoderDecoderPair initialValue() - { + protected EncoderDecoderPair initialValue() { return new EncoderDecoderPair(); } }; - public static DecoderImpl getDecoder() - { + public static DecoderImpl getDecoder() { return tlsCodec.get().decoder; } - public static EncoderImpl getEncoder() - { + public static EncoderImpl getEncoder() { return tlsCodec.get().encoder; } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/CreditsSemaphore.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/CreditsSemaphore.java index b087978133..170e8755d8 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/CreditsSemaphore.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/CreditsSemaphore.java @@ -18,67 +18,53 @@ package org.proton.plug.util; import java.util.concurrent.locks.AbstractQueuedSynchronizer; -public class CreditsSemaphore -{ +public class CreditsSemaphore { @SuppressWarnings("serial") - private static class Sync extends AbstractQueuedSynchronizer - { - public Sync(int initial) - { + private static class Sync extends AbstractQueuedSynchronizer { + + public Sync(int initial) { setState(initial); } - public int getCredits() - { + public int getCredits() { return getState(); } @Override - public int tryAcquireShared(final int numberOfAqcquires) - { - for (;;) - { + public int tryAcquireShared(final int numberOfAqcquires) { + for (;;) { int actualSize = getState(); int newValue = actualSize - numberOfAqcquires; - if (newValue < 0) - { - if (actualSize == getState()) - { + if (newValue < 0) { + if (actualSize == getState()) { return -1; } } - else if (compareAndSetState(actualSize, newValue)) - { + else if (compareAndSetState(actualSize, newValue)) { return newValue; } } } @Override - public boolean tryReleaseShared(final int numberOfReleases) - { - for (;;) - { + public boolean tryReleaseShared(final int numberOfReleases) { + for (;;) { int actualSize = getState(); int newValue = actualSize + numberOfReleases; - if (compareAndSetState(actualSize, newValue)) - { + if (compareAndSetState(actualSize, newValue)) { return true; } } } - public void setCredits(final int credits) - { - for (;;) - { + public void setCredits(final int credits) { + for (;;) { int actualState = getState(); - if (compareAndSetState(actualState, credits)) - { + if (compareAndSetState(actualState, credits)) { // This is to wake up any pending threads that could be waiting on queued releaseShared(0); return; @@ -89,44 +75,35 @@ public class CreditsSemaphore private final Sync sync; - - public CreditsSemaphore(int initialCredits) - { + public CreditsSemaphore(int initialCredits) { sync = new Sync(initialCredits); } - public void acquire() throws InterruptedException - { + public void acquire() throws InterruptedException { sync.acquireSharedInterruptibly(1); } - public boolean tryAcquire() - { + public boolean tryAcquire() { return sync.tryAcquireShared(1) >= 0; } - public void release() throws InterruptedException - { + public void release() throws InterruptedException { sync.releaseShared(1); } - public void release(int credits) throws InterruptedException - { + public void release(int credits) throws InterruptedException { sync.releaseShared(credits); } - public void setCredits(int credits) - { + public void setCredits(int credits) { sync.setCredits(credits); } - public int getCredits() - { + public int getCredits() { return sync.getCredits(); } - public boolean hasQueuedThreads() - { + public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/DebugInfo.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/DebugInfo.java index 30e3569538..633bd10542 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/DebugInfo.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/DebugInfo.java @@ -16,7 +16,7 @@ */ package org.proton.plug.util; -public class DebugInfo -{ +public class DebugInfo { + public static final boolean debug = false; } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/DeliveryUtil.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/DeliveryUtil.java index de63a2bb46..4c2272c8ba 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/DeliveryUtil.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/DeliveryUtil.java @@ -21,25 +21,20 @@ import org.apache.qpid.proton.engine.Receiver; import org.apache.qpid.proton.message.Message; import org.apache.qpid.proton.message.impl.MessageImpl; -public class DeliveryUtil -{ +public class DeliveryUtil { - public static int readDelivery(Receiver receiver, ByteBuf buffer) - { + public static int readDelivery(Receiver receiver, ByteBuf buffer) { int initial = buffer.writerIndex(); // optimization by norman int count; - while ((count = receiver.recv(buffer.array(), buffer.arrayOffset() + buffer.writerIndex(), buffer.writableBytes())) > 0) - { + while ((count = receiver.recv(buffer.array(), buffer.arrayOffset() + buffer.writerIndex(), buffer.writableBytes())) > 0) { // Increment the writer index by the number of bytes written into it while calling recv. buffer.writerIndex(buffer.writerIndex() + count); } return buffer.writerIndex() - initial; } - - public static MessageImpl decodeMessageImpl(ByteBuf buffer) - { + public static MessageImpl decodeMessageImpl(ByteBuf buffer) { MessageImpl message = (MessageImpl) Message.Factory.create(); message.decode(buffer.array(), buffer.arrayOffset() + buffer.readerIndex(), buffer.readableBytes()); return message; diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/FutureRunnable.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/FutureRunnable.java index 17476703bc..d878262077 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/FutureRunnable.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/FutureRunnable.java @@ -18,52 +18,43 @@ package org.proton.plug.util; import java.util.concurrent.TimeUnit; -public class FutureRunnable implements Runnable -{ +public class FutureRunnable implements Runnable { + private final ReusableLatch latch; - public FutureRunnable(final int initialIterations) - { + public FutureRunnable(final int initialIterations) { latch = new ReusableLatch(initialIterations); } - public FutureRunnable() - { + public FutureRunnable() { this(0); } - public void run() - { + public void run() { latch.countDown(); } - public void countUp() - { + public void countUp() { latch.countUp(); } - public void countDown() - { + public void countDown() { latch.countDown(); } - public int getCount() - { + public int getCount() { return latch.getCount(); } - public void await() throws InterruptedException - { + public void await() throws InterruptedException { latch.await(); } - public boolean await(long timeWait, TimeUnit timeUnit) throws InterruptedException - { + public boolean await(long timeWait, TimeUnit timeUnit) throws InterruptedException { return latch.await(timeWait, timeUnit); } - public boolean await(long milliseconds) throws InterruptedException - { + public boolean await(long milliseconds) throws InterruptedException { return latch.await(milliseconds); } } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/NettyWritable.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/NettyWritable.java index 472f9daa20..98afd303c5 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/NettyWritable.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/NettyWritable.java @@ -25,92 +25,76 @@ import org.apache.qpid.proton.codec.WritableBuffer; * This is to use NettyBuffer within Proton */ -public class NettyWritable implements WritableBuffer -{ +public class NettyWritable implements WritableBuffer { final ByteBuf nettyBuffer; - public NettyWritable(ByteBuf nettyBuffer) - { + public NettyWritable(ByteBuf nettyBuffer) { this.nettyBuffer = nettyBuffer; } - @Override - public void put(byte b) - { + public void put(byte b) { nettyBuffer.writeByte(b); } @Override - public void putFloat(float f) - { + public void putFloat(float f) { nettyBuffer.writeFloat(f); } @Override - public void putDouble(double d) - { + public void putDouble(double d) { nettyBuffer.writeDouble(d); } @Override - public void put(byte[] src, int offset, int length) - { + public void put(byte[] src, int offset, int length) { nettyBuffer.writeBytes(src, offset, length); } @Override - public void putShort(short s) - { + public void putShort(short s) { nettyBuffer.writeShort(s); } @Override - public void putInt(int i) - { + public void putInt(int i) { nettyBuffer.writeInt(i); } @Override - public void putLong(long l) - { + public void putLong(long l) { nettyBuffer.writeLong(l); } @Override - public boolean hasRemaining() - { + public boolean hasRemaining() { return nettyBuffer.writerIndex() < nettyBuffer.capacity(); } @Override - public int remaining() - { + public int remaining() { return nettyBuffer.capacity() - nettyBuffer.writerIndex(); } @Override - public int position() - { + public int position() { return nettyBuffer.writerIndex(); } @Override - public void position(int position) - { + public void position(int position) { nettyBuffer.writerIndex(position); } @Override - public void put(ByteBuffer payload) - { + public void put(ByteBuffer payload) { nettyBuffer.writeBytes(payload); } @Override - public int limit() - { + public int limit() { return nettyBuffer.capacity(); } } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/ProtonServerMessage.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/ProtonServerMessage.java index 5c2765229c..9c69147b62 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/ProtonServerMessage.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/ProtonServerMessage.java @@ -35,8 +35,8 @@ import org.apache.qpid.proton.message.ProtonJMessage; /** * This is a serverMessage that won't deal with the body */ -public class ProtonServerMessage implements ProtonJMessage -{ +public class ProtonServerMessage implements ProtonJMessage { + private Header header; private DeliveryAnnotations deliveryAnnotations; private MessageAnnotations messageAnnotations; @@ -58,19 +58,16 @@ public class ProtonServerMessage implements ProtonJMessage private static final int PROPERTIES = 0x073; private static final int APPLICATION_PROPERTIES = 0x074; - /** * This will decode a ByteBuffer tha represents the entire message. * Set the limits around the parameter. * * @param buffer a limited buffer for the message */ - public void decode(ByteBuffer buffer) - { + public void decode(ByteBuffer buffer) { DecoderImpl decoder = CodecCache.getDecoder(); - header = null; deliveryAnnotations = null; messageAnnotations = null; @@ -79,519 +76,425 @@ public class ProtonServerMessage implements ProtonJMessage rawBody = null; decoder.setByteBuffer(buffer); - try - { + try { int type = readType(buffer, decoder); - if (type == HEADER_TYPE) - { + if (type == HEADER_TYPE) { header = (Header) readSection(buffer, decoder); type = readType(buffer, decoder); } - if (type == DELIVERY_ANNOTATIONS) - { + if (type == DELIVERY_ANNOTATIONS) { deliveryAnnotations = (DeliveryAnnotations) readSection(buffer, decoder); type = readType(buffer, decoder); } - if (type == MESSAGE_ANNOTATIONS) - { + if (type == MESSAGE_ANNOTATIONS) { messageAnnotations = (MessageAnnotations) readSection(buffer, decoder); type = readType(buffer, decoder); } - if (type == PROPERTIES) - { + if (type == PROPERTIES) { properties = (Properties) readSection(buffer, decoder); type = readType(buffer, decoder); } - if (type == APPLICATION_PROPERTIES) - { + if (type == APPLICATION_PROPERTIES) { applicationProperties = (ApplicationProperties) readSection(buffer, decoder); type = readType(buffer, decoder); } - if (type != EOF) - { + if (type != EOF) { rawBody = new byte[buffer.limit() - buffer.position()]; buffer.get(rawBody); } } - finally - { + finally { decoder.setByteBuffer(null); } } - - public void encode(ByteBuffer buffer) - { + public void encode(ByteBuffer buffer) { WritableBuffer writableBuffer = new WritableBuffer.ByteBufferWrapper(buffer); encode(writableBuffer); } - public int encode(WritableBuffer writableBuffer) - { + public int encode(WritableBuffer writableBuffer) { final int firstPosition = writableBuffer.position(); EncoderImpl encoder = CodecCache.getEncoder(); encoder.setByteBuffer(writableBuffer); - try - { - if (header != null) - { + try { + if (header != null) { encoder.writeObject(header); } - if (deliveryAnnotations != null) - { + if (deliveryAnnotations != null) { encoder.writeObject(deliveryAnnotations); } - if (messageAnnotations != null) - { + if (messageAnnotations != null) { encoder.writeObject(messageAnnotations); } - if (properties != null) - { + if (properties != null) { encoder.writeObject(properties); } - if (applicationProperties != null) - { + if (applicationProperties != null) { encoder.writeObject(applicationProperties); } // It should write either the parsed one or the rawBody - if (parsedBody != null) - { + if (parsedBody != null) { encoder.writeObject(parsedBody); - if (parsedFooter != null) - { + if (parsedFooter != null) { encoder.writeObject(parsedFooter); } } - else if (rawBody != null) - { + else if (rawBody != null) { writableBuffer.put(rawBody, 0, rawBody.length); } return writableBuffer.position() - firstPosition; } - finally - { + finally { encoder.setByteBuffer((WritableBuffer) null); } } - - private int readType(ByteBuffer buffer, DecoderImpl decoder) - { + private int readType(ByteBuffer buffer, DecoderImpl decoder) { int pos = buffer.position(); - if (!buffer.hasRemaining()) - { + if (!buffer.hasRemaining()) { return EOF; } - try - { - if (buffer.get() != 0) - { + try { + if (buffer.get() != 0) { return EOF; } - else - { + else { return ((Number) decoder.readObject()).intValue(); } } - finally - { + finally { buffer.position(pos); } } - - private Section readSection(ByteBuffer buffer, DecoderImpl decoder) - { - if (buffer.hasRemaining()) - { + private Section readSection(ByteBuffer buffer, DecoderImpl decoder) { + if (buffer.hasRemaining()) { return (Section) decoder.readObject(); } - else - { + else { return null; } } - // At the moment we only need encode implemented!!! @Override - public boolean isDurable() - { + public boolean isDurable() { return false; } @Override - public long getDeliveryCount() - { + public long getDeliveryCount() { return 0; } @Override - public short getPriority() - { + public short getPriority() { return 0; } @Override - public boolean isFirstAcquirer() - { + public boolean isFirstAcquirer() { return false; } @Override - public long getTtl() - { + public long getTtl() { return 0; } @Override - public void setDurable(boolean durable) - { + public void setDurable(boolean durable) { } @Override - public void setTtl(long ttl) - { + public void setTtl(long ttl) { } @Override - public void setDeliveryCount(long deliveryCount) - { + public void setDeliveryCount(long deliveryCount) { } @Override - public void setFirstAcquirer(boolean firstAcquirer) - { + public void setFirstAcquirer(boolean firstAcquirer) { } @Override - public void setPriority(short priority) - { + public void setPriority(short priority) { } @Override - public Object getMessageId() - { + public Object getMessageId() { return null; } @Override - public long getGroupSequence() - { + public long getGroupSequence() { return 0; } @Override - public String getReplyToGroupId() - { + public String getReplyToGroupId() { return null; } @Override - public long getCreationTime() - { + public long getCreationTime() { return 0; } @Override - public String getAddress() - { + public String getAddress() { return null; } @Override - public byte[] getUserId() - { + public byte[] getUserId() { return new byte[0]; } @Override - public String getReplyTo() - { + public String getReplyTo() { return null; } @Override - public String getGroupId() - { + public String getGroupId() { return null; } @Override - public String getContentType() - { + public String getContentType() { return null; } @Override - public long getExpiryTime() - { + public long getExpiryTime() { return 0; } @Override - public Object getCorrelationId() - { + public Object getCorrelationId() { return null; } @Override - public String getContentEncoding() - { + public String getContentEncoding() { return null; } @Override - public String getSubject() - { + public String getSubject() { return null; } @Override - public void setGroupSequence(long groupSequence) - { + public void setGroupSequence(long groupSequence) { } @Override - public void setUserId(byte[] userId) - { + public void setUserId(byte[] userId) { } @Override - public void setCreationTime(long creationTime) - { + public void setCreationTime(long creationTime) { } @Override - public void setSubject(String subject) - { + public void setSubject(String subject) { } @Override - public void setGroupId(String groupId) - { + public void setGroupId(String groupId) { } @Override - public void setAddress(String to) - { + public void setAddress(String to) { } @Override - public void setExpiryTime(long absoluteExpiryTime) - { + public void setExpiryTime(long absoluteExpiryTime) { } @Override - public void setReplyToGroupId(String replyToGroupId) - { + public void setReplyToGroupId(String replyToGroupId) { } @Override - public void setContentEncoding(String contentEncoding) - { + public void setContentEncoding(String contentEncoding) { } @Override - public void setContentType(String contentType) - { + public void setContentType(String contentType) { } @Override - public void setReplyTo(String replyTo) - { + public void setReplyTo(String replyTo) { } @Override - public void setCorrelationId(Object correlationId) - { + public void setCorrelationId(Object correlationId) { } @Override - public void setMessageId(Object messageId) - { + public void setMessageId(Object messageId) { } @Override - public Header getHeader() - { + public Header getHeader() { return null; } @Override - public DeliveryAnnotations getDeliveryAnnotations() - { + public DeliveryAnnotations getDeliveryAnnotations() { return null; } @Override - public MessageAnnotations getMessageAnnotations() - { + public MessageAnnotations getMessageAnnotations() { return null; } @Override - public Properties getProperties() - { + public Properties getProperties() { return null; } @Override - public ApplicationProperties getApplicationProperties() - { + public ApplicationProperties getApplicationProperties() { return null; } @Override - public Section getBody() - { + public Section getBody() { return null; } @Override - public Footer getFooter() - { + public Footer getFooter() { return null; } @Override - public void setHeader(Header header) - { + public void setHeader(Header header) { } @Override - public void setDeliveryAnnotations(DeliveryAnnotations deliveryAnnotations) - { + public void setDeliveryAnnotations(DeliveryAnnotations deliveryAnnotations) { } @Override - public void setMessageAnnotations(MessageAnnotations messageAnnotations) - { + public void setMessageAnnotations(MessageAnnotations messageAnnotations) { } @Override - public void setProperties(Properties properties) - { + public void setProperties(Properties properties) { } @Override - public void setApplicationProperties(ApplicationProperties applicationProperties) - { + public void setApplicationProperties(ApplicationProperties applicationProperties) { } @Override - public void setBody(Section body) - { + public void setBody(Section body) { } @Override - public void setFooter(Footer footer) - { + public void setFooter(Footer footer) { } @Override - public int decode(byte[] data, int offset, int length) - { + public int decode(byte[] data, int offset, int length) { return 0; } @Override - public int encode(byte[] data, int offset, int length) - { + public int encode(byte[] data, int offset, int length) { return 0; } @Override - public void load(Object data) - { + public void load(Object data) { } @Override - public Object save() - { + public Object save() { return null; } @Override - public String toAMQPFormat(Object value) - { + public String toAMQPFormat(Object value) { return null; } @Override - public Object parseAMQPFormat(String value) - { + public Object parseAMQPFormat(String value) { return null; } @Override - public void setMessageFormat(MessageFormat format) - { + public void setMessageFormat(MessageFormat format) { } @Override - public MessageFormat getMessageFormat() - { + public MessageFormat getMessageFormat() { return null; } @Override - public void clear() - { + public void clear() { } @Override - public MessageError getError() - { + public MessageError getError() { return null; } @Override - public int encode2(byte[] data, int offset, int length) - { + public int encode2(byte[] data, int offset, int length) { return 0; } } diff --git a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/ReusableLatch.java b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/ReusableLatch.java index 5b16131180..87e00e00fb 100644 --- a/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/ReusableLatch.java +++ b/artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/util/ReusableLatch.java @@ -28,70 +28,58 @@ import java.util.concurrent.locks.AbstractQueuedSynchronizer; *

    Note: This latch is reusable. Once it reaches zero, you can call up again, and reuse it on further waits.

    *

    For example: prepareTransaction will wait for the current completions, and further adds will be called on the latch. Later on when commit is called you can reuse the same latch.

    */ -public class ReusableLatch -{ +public class ReusableLatch { + /** * Look at the doc and examples provided by AbstractQueuedSynchronizer for more information * * @see AbstractQueuedSynchronizer */ @SuppressWarnings("serial") - private static class CountSync extends AbstractQueuedSynchronizer - { - public CountSync(int count) - { + private static class CountSync extends AbstractQueuedSynchronizer { + + public CountSync(int count) { setState(count); } - public int getCount() - { + public int getCount() { return getState(); } - public void setCount(final int count) - { + public void setCount(final int count) { setState(count); } @Override - public int tryAcquireShared(final int numberOfAqcquires) - { + public int tryAcquireShared(final int numberOfAqcquires) { return getState() == 0 ? 1 : -1; } - public void add() - { - for (;;) - { + public void add() { + for (;;) { int actualState = getState(); int newState = actualState + 1; - if (compareAndSetState(actualState, newState)) - { + if (compareAndSetState(actualState, newState)) { return; } } } @Override - public boolean tryReleaseShared(final int numberOfReleases) - { - for (;;) - { + public boolean tryReleaseShared(final int numberOfReleases) { + for (;;) { int actualState = getState(); - if (actualState == 0) - { + if (actualState == 0) { return true; } int newState = actualState - numberOfReleases; - if (newState < 0) - { + if (newState < 0) { newState = 0; } - if (compareAndSetState(actualState, newState)) - { + if (compareAndSetState(actualState, newState)) { return newState == 0; } } @@ -100,54 +88,43 @@ public class ReusableLatch private final CountSync control; - public ReusableLatch() - { + public ReusableLatch() { this(0); } - public ReusableLatch(final int count) - { + public ReusableLatch(final int count) { control = new CountSync(count); } - public int getCount() - { + public int getCount() { return control.getCount(); } - public void setCount(final int count) - { + public void setCount(final int count) { control.setCount(count); } - public void countUp() - { + public void countUp() { control.add(); } - public void countDown() - { + public void countDown() { control.releaseShared(1); } - - public void countDown(final int count) - { + public void countDown(final int count) { control.releaseShared(count); } - public void await() throws InterruptedException - { + public void await() throws InterruptedException { control.acquireSharedInterruptibly(1); } - public boolean await(final long milliseconds) throws InterruptedException - { + public boolean await(final long milliseconds) throws InterruptedException { return control.tryAcquireSharedNanos(1, TimeUnit.MILLISECONDS.toNanos(milliseconds)); } - public boolean await(final long timeWait, TimeUnit timeUnit) throws InterruptedException - { + public boolean await(final long timeWait, TimeUnit timeUnit) throws InterruptedException { return control.tryAcquireSharedNanos(1, timeUnit.toNanos(timeWait)); } } diff --git a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/context/AbstractConnectionContextTest.java b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/context/AbstractConnectionContextTest.java index 51c69ae9ee..10be09f92c 100644 --- a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/context/AbstractConnectionContextTest.java +++ b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/context/AbstractConnectionContextTest.java @@ -29,12 +29,10 @@ import org.proton.plug.ServerSASL; import org.proton.plug.exceptions.ActiveMQAMQPException; import org.proton.plug.handler.EventHandler; -public class AbstractConnectionContextTest -{ +public class AbstractConnectionContextTest { @Test - public void testListenerDoesntThrowNPEWhenClosingLinkWithNullContext() throws Exception - { + public void testListenerDoesntThrowNPEWhenClosingLinkWithNullContext() throws Exception { TestConnectionContext connectionContext = new TestConnectionContext(new TestConnectionCallback()); EventHandler listener = connectionContext.getListener(); @@ -47,67 +45,56 @@ public class AbstractConnectionContextTest listener.onRemoteClose(link); } - private class TestConnectionContext extends AbstractConnectionContext - { + private class TestConnectionContext extends AbstractConnectionContext { - public TestConnectionContext(AMQPConnectionCallback connectionCallback) - { + public TestConnectionContext(AMQPConnectionCallback connectionCallback) { super(connectionCallback); } @Override - protected void remoteLinkOpened(Link link) throws Exception - { + protected void remoteLinkOpened(Link link) throws Exception { } @Override - protected AbstractProtonSessionContext newSessionExtension(Session realSession) throws ActiveMQAMQPException - { + protected AbstractProtonSessionContext newSessionExtension(Session realSession) throws ActiveMQAMQPException { return null; } - public EventHandler getListener() - { + public EventHandler getListener() { return listener; } } - private class TestConnectionCallback implements AMQPConnectionCallback - { + private class TestConnectionCallback implements AMQPConnectionCallback { + @Override - public void close() - { + public void close() { } @Override - public void onTransport(ByteBuf bytes, AMQPConnectionContext connection) - { + public void onTransport(ByteBuf bytes, AMQPConnectionContext connection) { } @Override - public AMQPSessionCallback createSessionCallback(AMQPConnectionContext connection) - { + public AMQPSessionCallback createSessionCallback(AMQPConnectionContext connection) { return null; } @Override - public void setConnection(AMQPConnectionContext connection) - { + public void setConnection(AMQPConnectionContext connection) { } @Override - public AMQPConnectionContext getConnection() - { + public AMQPConnectionContext getConnection() { return null; } @Override - public ServerSASL[] getSASLMechnisms() - { + public ServerSASL[] getSASLMechnisms() { return null; } } diff --git a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/AbstractJMSTest.java b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/AbstractJMSTest.java index df8eff4768..bccea5fe4d 100644 --- a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/AbstractJMSTest.java +++ b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/AbstractJMSTest.java @@ -29,55 +29,45 @@ import org.apache.qpid.amqp_1_0.jms.impl.QueueImpl; import org.proton.plug.test.minimalserver.DumbServer; import org.proton.plug.test.minimalserver.MinimalServer; -public class AbstractJMSTest -{ +public class AbstractJMSTest { + protected final boolean useHawtJMS; protected final boolean useSASL; protected String address = "exampleQueue"; protected MinimalServer server = new MinimalServer(); - public AbstractJMSTest(boolean useHawtJMS, boolean useSASL) - { + public AbstractJMSTest(boolean useHawtJMS, boolean useSASL) { this.useHawtJMS = useHawtJMS; this.useSASL = useSASL; } - public void tearDown() throws Exception - { + public void tearDown() throws Exception { server.stop(); DumbServer.clear(); } - public static void forceGC() - { + public static void forceGC() { System.out.println("#test forceGC"); WeakReference dumbReference = new WeakReference(new Object()); // A loop that will wait GC, using the minimalserver time as possible - while (dumbReference.get() != null) - { + while (dumbReference.get() != null) { System.gc(); - try - { + try { Thread.sleep(100); } - catch (InterruptedException e) - { + catch (InterruptedException e) { } } System.out.println("#test forceGC Done"); } - - protected Connection createConnection() throws JMSException - { + protected Connection createConnection() throws JMSException { final ConnectionFactory factory = createConnectionFactory(); final Connection connection = factory.createConnection(); - connection.setExceptionListener(new ExceptionListener() - { + connection.setExceptionListener(new ExceptionListener() { @Override - public void onException(JMSException exception) - { + public void onException(JMSException exception) { exception.printStackTrace(); } }); @@ -85,48 +75,36 @@ public class AbstractJMSTest return connection; } - - protected ConnectionFactory createConnectionFactory() - { - if (useSASL) - { - if (useHawtJMS) - { -// return new JmsConnectionFactory("aaaaaaaa", "aaaaaaa", "amqp://localhost:" + Constants.PORT); + protected ConnectionFactory createConnectionFactory() { + if (useSASL) { + if (useHawtJMS) { + // return new JmsConnectionFactory("aaaaaaaa", "aaaaaaa", "amqp://localhost:" + Constants.PORT); return null; } - else - { + else { return new ConnectionFactoryImpl("localhost", Constants.PORT, "aaaaaaaa", "aaaaaaa"); } } - else - { - if (useHawtJMS) - { -// return new JmsConnectionFactory("amqp://localhost:" + Constants.PORT); + else { + if (useHawtJMS) { + // return new JmsConnectionFactory("amqp://localhost:" + Constants.PORT); return null; } - else - { + else { return new ConnectionFactoryImpl("localhost", Constants.PORT, null, null); } } } - protected Queue createQueue() - { - if (useHawtJMS) - { -// return new JmsQueue(address); + protected Queue createQueue() { + if (useHawtJMS) { + // return new JmsQueue(address); return null; } - else - { + else { return new QueueImpl(address); } } - } diff --git a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/Constants.java b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/Constants.java index d155566416..bacfd7b75b 100644 --- a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/Constants.java +++ b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/Constants.java @@ -16,7 +16,7 @@ */ package org.proton.plug.test; -public class Constants -{ +public class Constants { + public static final int PORT = 5672; } diff --git a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/ProtonTest.java b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/ProtonTest.java index 2832549b6f..bf972b6fed 100644 --- a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/ProtonTest.java +++ b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/ProtonTest.java @@ -55,31 +55,24 @@ import org.proton.plug.util.ByteUtil; * This is simulating a JMS client against a simple server */ @RunWith(Parameterized.class) -public class ProtonTest extends AbstractJMSTest -{ +public class ProtonTest extends AbstractJMSTest { protected Connection connection; @Parameterized.Parameters(name = "useHawt={0} sasl={1}") - public static Collection data() - { - List list = Arrays.asList(new Object[][]{ - {Boolean.FALSE, Boolean.TRUE}, - {Boolean.FALSE, Boolean.FALSE}}); + public static Collection data() { + List list = Arrays.asList(new Object[][]{{Boolean.FALSE, Boolean.TRUE}, {Boolean.FALSE, Boolean.FALSE}}); System.out.println("Size = " + list.size()); return list; } - public ProtonTest(boolean useHawtJMS, boolean useSASL) - { + public ProtonTest(boolean useHawtJMS, boolean useSASL) { super(useHawtJMS, useSASL); } - @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { DumbServer.clear(); AbstractJMSTest.forceGC(); server.start("127.0.0.1", Constants.PORT, true); @@ -87,10 +80,8 @@ public class ProtonTest extends AbstractJMSTest } @After - public void tearDown() throws Exception - { - if (connection != null) - { + public void tearDown() throws Exception { + if (connection != null) { connection.close(); } @@ -98,64 +89,51 @@ public class ProtonTest extends AbstractJMSTest } @Test - public void testMessagesReceivedInParallel() throws Throwable - { + public void testMessagesReceivedInParallel() throws Throwable { final int numMessages = getNumberOfMessages(); long time = System.currentTimeMillis(); final Queue queue = createQueue(); final ArrayList exceptions = new ArrayList<>(); - Thread t = new Thread(new Runnable() - { + Thread t = new Thread(new Runnable() { @Override - public void run() - { + public void run() { Connection connectionConsumer = null; - try - { + try { connectionConsumer = createConnection(); -// connectionConsumer = connection; + // connectionConsumer = connection; connectionConsumer.start(); Session sessionConsumer = connectionConsumer.createSession(false, Session.AUTO_ACKNOWLEDGE); final MessageConsumer consumer = sessionConsumer.createConsumer(queue); int count = numMessages; - while (count > 0) - { - try - { + while (count > 0) { + try { BytesMessage m = (BytesMessage) consumer.receive(1000); - if (count % 1000 == 0) - { + if (count % 1000 == 0) { System.out.println("Count = " + count + ", property=" + m.getStringProperty("XX")); } Assert.assertNotNull("Could not receive message count=" + count + " on consumer", m); count--; } - catch (JMSException e) - { + catch (JMSException e) { break; } } } - catch (Throwable e) - { + catch (Throwable e) { exceptions.add(e); e.printStackTrace(); } - finally - { - try - { + finally { + try { // if the createconnecion wasn't commented out - if (connectionConsumer != connection) - { + if (connectionConsumer != connection) { connectionConsumer.close(); } } - catch (Throwable ignored) - { + catch (Throwable ignored) { // NO OP } } @@ -168,8 +146,7 @@ public class ProtonTest extends AbstractJMSTest MessageProducer p = session.createProducer(queue); p.setDeliveryMode(DeliveryMode.PERSISTENT); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { BytesMessage message = session.createBytesMessage(); // TODO: this will break stuff if I use a large number message.writeBytes(new byte[5]); @@ -182,21 +159,18 @@ public class ProtonTest extends AbstractJMSTest System.out.println("taken on send = " + taken + " usehawt = " + useHawtJMS + " sasl = " + useSASL); t.join(); - for (Throwable e : exceptions) - { + for (Throwable e : exceptions) { throw e; } taken = (System.currentTimeMillis() - time); System.out.println("taken = " + taken + " usehawt = " + useHawtJMS + " sasl = " + useSASL); connection.close(); -// assertEquals(0, q.getMessageCount()); + // assertEquals(0, q.getMessageCount()); } - @Test - public void testSimpleCreateSessionAndClose() throws Throwable - { + public void testSimpleCreateSessionAndClose() throws Throwable { final QueueImpl queue = new QueueImpl(address); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -206,8 +180,7 @@ public class ProtonTest extends AbstractJMSTest } @Test - public void testSimpleBinary() throws Throwable - { + public void testSimpleBinary() throws Throwable { final int numMessages = 5; long time = System.currentTimeMillis(); final QueueImpl queue = new QueueImpl(address); @@ -215,15 +188,12 @@ public class ProtonTest extends AbstractJMSTest Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); byte[] bytes = new byte[0xf + 1]; - for (int i = 0; i <= 0xf; i++) - { + for (int i = 0; i <= 0xf; i++) { bytes[i] = (byte) i; } - MessageProducer p = session.createProducer(queue); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { BytesMessage message = session.createBytesMessage(); message.writeBytes(bytes); @@ -231,15 +201,12 @@ public class ProtonTest extends AbstractJMSTest p.send(message); } - session.close(); - Session sessionConsumer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); final MessageConsumer consumer = sessionConsumer.createConsumer(queue); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { BytesMessage m = (BytesMessage) consumer.receive(5000); System.out.println("length " + m.getBodyLength()); @@ -251,33 +218,29 @@ public class ProtonTest extends AbstractJMSTest byte[] bytesReceived = new byte[(int) size]; m.readBytes(bytesReceived); - System.out.println("Received " + ByteUtil.bytesToHex(bytesReceived, 1)); Assert.assertArrayEquals(bytes, bytesReceived); } -// assertEquals(0, q.getMessageCount()); + // assertEquals(0, q.getMessageCount()); long taken = (System.currentTimeMillis() - time) / 1000; System.out.println("taken = " + taken); } @Test - public void testMapMessage() throws Exception - { + public void testMapMessage() throws Exception { Queue queue = createQueue(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer p = session.createProducer(queue); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { MapMessage message = session.createMapMessage(); message.setInt("x", i); message.setString("str", "str" + i); p.send(message); } MessageConsumer messageConsumer = session.createConsumer(queue); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { MapMessage m = (MapMessage) messageConsumer.receive(5000); Assert.assertNotNull(m); Assert.assertEquals(i, m.getInt("x")); @@ -288,8 +251,7 @@ public class ProtonTest extends AbstractJMSTest } @Test - public void testProperties() throws Exception - { + public void testProperties() throws Exception { Queue queue = createQueue(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer p = session.createProducer(queue); @@ -322,8 +284,7 @@ public class ProtonTest extends AbstractJMSTest } // @Test - public void testSendWithSimpleClient() throws Exception - { + public void testSendWithSimpleClient() throws Exception { SimpleAMQPConnector connector = new SimpleAMQPConnector(); connector.start(); AMQPClientConnectionContext clientConnection = connector.connect("127.0.0.1", Constants.PORT); @@ -333,10 +294,8 @@ public class ProtonTest extends AbstractJMSTest AMQPClientSessionContext session = clientConnection.createClientSession(); AMQPClientSenderContext clientSender = session.createSender(address, true); - Properties props = new Properties(); - for (int i = 0; i < 1; i++) - { + for (int i = 0; i < 1; i++) { MessageImpl message = (MessageImpl) Message.Factory.create(); HashMap map = new HashMap(); @@ -352,8 +311,7 @@ public class ProtonTest extends AbstractJMSTest connection.start(); MessageConsumer consumer = clientSession.createConsumer(createQueue()); - for (int i = 0; i < 1; i++) - { + for (int i = 0; i < 1; i++) { MapMessage msg = (MapMessage) consumer.receive(5000); System.out.println("Msg " + msg); Assert.assertNotNull(msg); @@ -364,9 +322,7 @@ public class ProtonTest extends AbstractJMSTest } } - - protected int getNumberOfMessages() - { + protected int getNumberOfMessages() { return 10000; } diff --git a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/invm/InVMTestConnector.java b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/invm/InVMTestConnector.java index a4a23e65bf..3085b40d24 100644 --- a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/invm/InVMTestConnector.java +++ b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/invm/InVMTestConnector.java @@ -23,17 +23,15 @@ import org.proton.plug.test.minimalclient.Connector; /** * This is used for testing, where we bypass Netty or any networking for test conditions only */ -public class InVMTestConnector implements Connector -{ +public class InVMTestConnector implements Connector { + @Override - public void start() - { + public void start() { } @Override - public AMQPClientConnectionContext connect(String host, int port) throws Exception - { + public AMQPClientConnectionContext connect(String host, int port) throws Exception { return new ProtonClientConnectionContext(new ProtonINVMSPI()); } } diff --git a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/invm/ProtonINVMSPI.java b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/invm/ProtonINVMSPI.java index d244fa643e..27271e4575 100644 --- a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/invm/ProtonINVMSPI.java +++ b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/invm/ProtonINVMSPI.java @@ -31,8 +31,7 @@ import org.proton.plug.test.minimalserver.MinimalSessionSPI; import org.proton.plug.util.ByteUtil; import org.proton.plug.util.DebugInfo; -public class ProtonINVMSPI implements AMQPConnectionCallback -{ +public class ProtonINVMSPI implements AMQPConnectionCallback { AMQPConnectionContext returningConnection; @@ -42,69 +41,52 @@ public class ProtonINVMSPI implements AMQPConnectionCallback final ExecutorService returningExecutor = Executors.newSingleThreadExecutor(); - public ProtonINVMSPI() - { - mainExecutor.execute(new Runnable() - { - public void run() - { + public ProtonINVMSPI() { + mainExecutor.execute(new Runnable() { + public void run() { Thread.currentThread().setName("MainExecutor-INVM"); } }); - returningExecutor.execute(new Runnable() - { - public void run() - { + returningExecutor.execute(new Runnable() { + public void run() { Thread.currentThread().setName("ReturningExecutor-INVM"); } }); } @Override - public void close() - { + public void close() { mainExecutor.shutdown(); } @Override - public ServerSASL[] getSASLMechnisms() - { + public ServerSASL[] getSASLMechnisms() { return new ServerSASL[]{new AnonymousServerSASL(), new ServerSASLPlain()}; } - @Override - public void onTransport(final ByteBuf bytes, final AMQPConnectionContext connection) - { - if (DebugInfo.debug) - { + public void onTransport(final ByteBuf bytes, final AMQPConnectionContext connection) { + if (DebugInfo.debug) { ByteUtil.debugFrame("InVM->", bytes); } final int size = bytes.writerIndex(); bytes.retain(); - mainExecutor.execute(new Runnable() - { - public void run() - { - try - { - if (DebugInfo.debug) - { + mainExecutor.execute(new Runnable() { + public void run() { + try { + if (DebugInfo.debug) { ByteUtil.debugFrame("InVMDone->", bytes); } serverConnection.inputBuffer(bytes); - try - { + try { connection.outputDone(size); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } - finally - { + finally { bytes.release(); } } @@ -112,75 +94,59 @@ public class ProtonINVMSPI implements AMQPConnectionCallback } @Override - public void setConnection(AMQPConnectionContext connection) - { + public void setConnection(AMQPConnectionContext connection) { returningConnection = connection; } @Override - public AMQPConnectionContext getConnection() - { + public AMQPConnectionContext getConnection() { return returningConnection; } @Override - public AMQPSessionCallback createSessionCallback(AMQPConnectionContext connection) - { + public AMQPSessionCallback createSessionCallback(AMQPConnectionContext connection) { return null; } - class ReturnSPI implements AMQPConnectionCallback - { + class ReturnSPI implements AMQPConnectionCallback { + @Override - public void close() - { + public void close() { } @Override - public ServerSASL[] getSASLMechnisms() - { + public ServerSASL[] getSASLMechnisms() { return new ServerSASL[]{new AnonymousServerSASL(), new ServerSASLPlain()}; } - @Override - public void onTransport(final ByteBuf bytes, final AMQPConnectionContext connection) - { + public void onTransport(final ByteBuf bytes, final AMQPConnectionContext connection) { final int size = bytes.writerIndex(); - if (DebugInfo.debug) - { + if (DebugInfo.debug) { ByteUtil.debugFrame("InVM<-", bytes); } - bytes.retain(); - returningExecutor.execute(new Runnable() - { - public void run() - { - try - { + returningExecutor.execute(new Runnable() { + public void run() { + try { - if (DebugInfo.debug) - { + if (DebugInfo.debug) { ByteUtil.debugFrame("InVM done<-", bytes); } returningConnection.inputBuffer(bytes); - try - { + try { connection.outputDone(size); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } - finally - { + finally { bytes.release(); } } @@ -188,20 +154,17 @@ public class ProtonINVMSPI implements AMQPConnectionCallback } @Override - public AMQPSessionCallback createSessionCallback(AMQPConnectionContext connection) - { + public AMQPSessionCallback createSessionCallback(AMQPConnectionContext connection) { return new MinimalSessionSPI(); } @Override - public void setConnection(AMQPConnectionContext connection) - { + public void setConnection(AMQPConnectionContext connection) { } @Override - public AMQPConnectionContext getConnection() - { + public AMQPConnectionContext getConnection() { return null; } } diff --git a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalclient/AMQPClientSPI.java b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalclient/AMQPClientSPI.java index df353bdbdc..8ef45eb058 100644 --- a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalclient/AMQPClientSPI.java +++ b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalclient/AMQPClientSPI.java @@ -32,78 +32,62 @@ import org.proton.plug.util.ByteUtil; import org.proton.plug.util.DebugInfo; import org.proton.plug.util.ReusableLatch; -public class AMQPClientSPI implements AMQPConnectionCallback -{ +public class AMQPClientSPI implements AMQPConnectionCallback { final Channel channel; protected AMQPConnectionContext connection; - public AMQPClientSPI(Channel channel) - { + public AMQPClientSPI(Channel channel) { this.channel = channel; } - public void setConnection(AMQPConnectionContext connection) - { + public void setConnection(AMQPConnectionContext connection) { this.connection = connection; } - public AMQPConnectionContext getConnection() - { + public AMQPConnectionContext getConnection() { return connection; } @Override - public void close() - { + public void close() { } @Override - public ServerSASL[] getSASLMechnisms() - { + public ServerSASL[] getSASLMechnisms() { return new ServerSASL[]{new AnonymousServerSASL(), new ServerSASLPlain()}; } - final ReusableLatch latch = new ReusableLatch(0); @Override - public void onTransport(final ByteBuf bytes, final AMQPConnectionContext connection) - { - if (DebugInfo.debug) - { + public void onTransport(final ByteBuf bytes, final AMQPConnectionContext connection) { + if (DebugInfo.debug) { ByteUtil.debugFrame("Bytes leaving client", bytes); } final int bufferSize = bytes.writerIndex(); - latch.countUp(); - channel.writeAndFlush(bytes).addListener(new ChannelFutureListener() - { + channel.writeAndFlush(bytes).addListener(new ChannelFutureListener() { @Override - public void operationComplete(ChannelFuture future) throws Exception - { - // -// connection.outputDone(bufferSize); + public void operationComplete(ChannelFuture future) throws Exception { + // + // connection.outputDone(bufferSize); latch.countDown(); } }); - if (connection.isSyncOnFlush()) - { - try - { - if (!latch.await(5, TimeUnit.SECONDS)) - { + if (connection.isSyncOnFlush()) { + try { + if (!latch.await(5, TimeUnit.SECONDS)) { // TODO logs System.err.println("Flush took longer than 5 seconds!!!"); } } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); } } @@ -113,8 +97,7 @@ public class AMQPClientSPI implements AMQPConnectionCallback } @Override - public AMQPSessionCallback createSessionCallback(AMQPConnectionContext connection) - { + public AMQPSessionCallback createSessionCallback(AMQPConnectionContext connection) { return null; } } diff --git a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalclient/Connector.java b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalclient/Connector.java index 0cc5f7de32..e6b67c2608 100644 --- a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalclient/Connector.java +++ b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalclient/Connector.java @@ -18,8 +18,8 @@ package org.proton.plug.test.minimalclient; import org.proton.plug.AMQPClientConnectionContext; -public interface Connector -{ +public interface Connector { + void start(); AMQPClientConnectionContext connect(String host, int port) throws Exception; diff --git a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalclient/SimpleAMQPConnector.java b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalclient/SimpleAMQPConnector.java index 95cf49d765..088e7a10a4 100644 --- a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalclient/SimpleAMQPConnector.java +++ b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalclient/SimpleAMQPConnector.java @@ -31,29 +31,23 @@ import io.netty.channel.socket.nio.NioSocketChannel; import org.proton.plug.AMQPClientConnectionContext; import org.proton.plug.context.client.ProtonClientConnectionContextFactory; -public class SimpleAMQPConnector implements Connector -{ +public class SimpleAMQPConnector implements Connector { + private Bootstrap bootstrap; - public void start() - { + public void start() { bootstrap = new Bootstrap(); bootstrap.channel(NioSocketChannel.class); bootstrap.group(new NioEventLoopGroup(10)); - bootstrap.handler( - new ChannelInitializer() - { - public void initChannel(Channel channel) throws Exception - { + bootstrap.handler(new ChannelInitializer() { + public void initChannel(Channel channel) throws Exception { } - } - ); + }); } - public AMQPClientConnectionContext connect(String host, int port) throws Exception - { + public AMQPClientConnectionContext connect(String host, int port) throws Exception { SocketAddress remoteDestination = new InetSocketAddress(host, port); ChannelFuture future = bootstrap.connect(remoteDestination); @@ -64,19 +58,13 @@ public class SimpleAMQPConnector implements Connector final AMQPClientConnectionContext connection = (AMQPClientConnectionContext) ProtonClientConnectionContextFactory.getFactory().createConnection(clientConnectionSPI); - future.channel().pipeline().addLast( - new ChannelDuplexHandler() - { - + future.channel().pipeline().addLast(new ChannelDuplexHandler() { @Override - public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception - { + public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception { ByteBuf buffer = (ByteBuf) msg; connection.inputBuffer(buffer); } - } - ); - + }); return connection; } diff --git a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalserver/DumbServer.java b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalserver/DumbServer.java index e615a4c247..404fc5a91d 100644 --- a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalserver/DumbServer.java +++ b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalserver/DumbServer.java @@ -21,37 +21,31 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.LinkedBlockingDeque; -public class DumbServer -{ +public class DumbServer { + static ConcurrentMap> maps = new ConcurrentHashMap<>(); - public static BlockingDeque getQueue(String name) - { + public static BlockingDeque getQueue(String name) { BlockingDeque q = maps.get(name); - if (q == null) - { + if (q == null) { q = new LinkedBlockingDeque(); BlockingDeque oldValue = maps.putIfAbsent(name, q); - if (oldValue != null) - { + if (oldValue != null) { q = oldValue; } } return q; } - public static void clear() - { - for (BlockingDeque queue : maps.values()) - { + public static void clear() { + for (BlockingDeque queue : maps.values()) { // We clear the queues just in case there is a component holding it queue.clear(); } maps.clear(); } - public static void put(String queue, Object message) - { + public static void put(String queue, Object message) { getQueue(queue).add(message); } diff --git a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalserver/MinimalConnectionSPI.java b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalserver/MinimalConnectionSPI.java index b23df24601..2dd6befbc9 100644 --- a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalserver/MinimalConnectionSPI.java +++ b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalserver/MinimalConnectionSPI.java @@ -34,117 +34,99 @@ import org.proton.plug.util.ByteUtil; import org.proton.plug.util.DebugInfo; import org.proton.plug.util.ReusableLatch; -public class MinimalConnectionSPI implements AMQPConnectionCallback -{ +public class MinimalConnectionSPI implements AMQPConnectionCallback { + Channel channel; private AMQPConnectionContext connection; - public MinimalConnectionSPI(Channel channel) - { + public MinimalConnectionSPI(Channel channel) { this.channel = channel; } ExecutorService executorService = Executors.newSingleThreadExecutor(); @Override - public void close() - { + public void close() { executorService.shutdown(); } - public void setConnection(AMQPConnectionContext connection) - { + public void setConnection(AMQPConnectionContext connection) { this.connection = connection; } - public AMQPConnectionContext getConnection() - { + public AMQPConnectionContext getConnection() { return connection; } final ReusableLatch latch = new ReusableLatch(0); @Override - public ServerSASL[] getSASLMechnisms() - { + public ServerSASL[] getSASLMechnisms() { return new ServerSASL[]{new AnonymousServerSASL(), new ServerSASLPlain()}; } @Override - public void onTransport(final ByteBuf bytes, final AMQPConnectionContext connection) - { + public void onTransport(final ByteBuf bytes, final AMQPConnectionContext connection) { final int bufferSize = bytes.writerIndex(); - if (DebugInfo.debug) - { + if (DebugInfo.debug) { // some debug byte[] frame = new byte[bytes.writerIndex()]; int readerOriginalPos = bytes.readerIndex(); bytes.getBytes(0, frame); - try - { + try { System.err.println("Buffer Outgoing: " + "\n" + ByteUtil.formatGroup(ByteUtil.bytesToHex(frame), 4, 16)); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } bytes.readerIndex(readerOriginalPos); } - latch.countUp(); // ^^ debug - channel.writeAndFlush(bytes).addListener(new ChannelFutureListener() - { + channel.writeAndFlush(bytes).addListener(new ChannelFutureListener() { @Override - public void operationComplete(ChannelFuture future) throws Exception - { + public void operationComplete(ChannelFuture future) throws Exception { latch.countDown(); // https://issues.apache.org/jira/browse/PROTON-645 -// connection.outputDone(bufferSize); -// if (connection.capacity() > 0) -// { -// channel.read(); -// } + // connection.outputDone(bufferSize); + // if (connection.capacity() > 0) + // { + // channel.read(); + // } } }); channel.flush(); - if (connection.isSyncOnFlush()) - { - try - { - if (!latch.await(5, TimeUnit.SECONDS)) - { + if (connection.isSyncOnFlush()) { + try { + if (!latch.await(5, TimeUnit.SECONDS)) { // TODO logs System.err.println("Flush took longer than 5 seconds!!!"); } } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); } } connection.outputDone(bufferSize); - -// if (connection.capacity() > 0) -// { -// channel.read(); -// } + // if (connection.capacity() > 0) + // { + // channel.read(); + // } } @Override - public AMQPSessionCallback createSessionCallback(AMQPConnectionContext connection) - { + public AMQPSessionCallback createSessionCallback(AMQPConnectionContext connection) { return new MinimalSessionSPI(); } } diff --git a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalserver/MinimalServer.java b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalserver/MinimalServer.java index 8e49dbbe5e..1ed3474522 100644 --- a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalserver/MinimalServer.java +++ b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalserver/MinimalServer.java @@ -16,7 +16,6 @@ */ package org.proton.plug.test.minimalserver; - import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.List; @@ -47,11 +46,9 @@ import org.proton.plug.test.Constants; /** * A Netty TCP Acceptor that supports SSL */ -public class MinimalServer -{ +public class MinimalServer { - static - { + static { // Disable resource leak detection for performance reasons by default ResourceLeakDetector.setEnabled(false); } @@ -73,14 +70,12 @@ public class MinimalServer // Constants.PORT is the default here private int port; - public synchronized void start(String host, int port, final boolean sasl) throws Exception - { + public synchronized void start(String host, int port, final boolean sasl) throws Exception { this.host = host; this.port = port; this.sasl = sasl; - if (channelClazz != null) - { + if (channelClazz != null) { // Already started return; } @@ -93,12 +88,9 @@ public class MinimalServer bootstrap.group(eventLoopGroup); bootstrap.channel(channelClazz); - - ChannelInitializer factory = new ChannelInitializer() - { + ChannelInitializer factory = new ChannelInitializer() { @Override - public void initChannel(Channel channel) throws Exception - { + public void initChannel(Channel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast("amqp-handler", new ProtocolDecoder()); } @@ -108,14 +100,13 @@ public class MinimalServer bootstrap.option(ChannelOption.SO_REUSEADDR, true). childOption(ChannelOption.SO_REUSEADDR, true). childOption(ChannelOption.SO_KEEPALIVE, true). -// childOption(ChannelOption.AUTO_READ, false). - childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); + // childOption(ChannelOption.AUTO_READ, false). + childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); channelGroup = new DefaultChannelGroup("activemq-accepted-channels", GlobalEventExecutor.INSTANCE); serverChannelGroup = new DefaultChannelGroup("activemq-acceptor-channels", GlobalEventExecutor.INSTANCE); - SocketAddress address; address = new InetSocketAddress(host, port); Channel serverChannel = bootstrap.bind(address).syncUninterruptibly().channel(); @@ -123,65 +114,51 @@ public class MinimalServer } - class ProtocolDecoder extends ByteToMessageDecoder - { + class ProtocolDecoder extends ByteToMessageDecoder { AMQPServerConnectionContext connection; - - public ProtocolDecoder() - { + public ProtocolDecoder() { } @Override - public void channelActive(ChannelHandlerContext ctx) throws Exception - { + public void channelActive(ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); connection = ProtonServerConnectionContextFactory.getFactory().createConnection(new MinimalConnectionSPI(ctx.channel())); //ctx.read(); } @Override - protected void decode(final ChannelHandlerContext ctx, ByteBuf byteIn, List out) throws Exception - { + protected void decode(final ChannelHandlerContext ctx, ByteBuf byteIn, List out) throws Exception { connection.inputBuffer(byteIn); ctx.flush(); -// if (connection.capacity() > 0) -// { -// ctx.read(); -// } + // if (connection.capacity() > 0) + // { + // ctx.read(); + // } } } - public synchronized void stop() - { - if (serverChannelGroup != null) - { + public synchronized void stop() { + if (serverChannelGroup != null) { serverChannelGroup.close().awaitUninterruptibly(); } - if (channelGroup != null) - { + if (channelGroup != null) { ChannelGroupFuture future = channelGroup.close().awaitUninterruptibly(); } } - - public static void main(String[] arg) - { + public static void main(String[] arg) { MinimalServer server = new MinimalServer(); - try - { + try { server.start("127.0.0.1", Constants.PORT, true); - - while (true) - { + while (true) { Thread.sleep(360000000); } } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); } } diff --git a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalserver/MinimalSessionSPI.java b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalserver/MinimalSessionSPI.java index 39e9a0ce3b..c4b939ca28 100644 --- a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalserver/MinimalSessionSPI.java +++ b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalserver/MinimalSessionSPI.java @@ -32,118 +32,99 @@ import org.proton.plug.context.server.ProtonServerSessionContext; import org.proton.plug.SASLResult; import org.proton.plug.util.ProtonServerMessage; -public class MinimalSessionSPI implements AMQPSessionCallback -{ +public class MinimalSessionSPI implements AMQPSessionCallback { private SASLResult result; ProtonServerSessionContext session; @Override - public void init(AMQPSessionContext session, SASLResult result) - { + public void init(AMQPSessionContext session, SASLResult result) { this.session = (ProtonServerSessionContext) session; this.result = result; } @Override - public void start() - { + public void start() { } static AtomicInteger tempQueueGenerator = new AtomicInteger(0); - public String tempQueueName() - { + public String tempQueueName() { return "TempQueueName" + tempQueueGenerator.incrementAndGet(); } @Override - public Object createSender(ProtonPlugSender plugSender, String queue, String filer, boolean browserOnly) - { + public Object createSender(ProtonPlugSender plugSender, String queue, String filer, boolean browserOnly) { Consumer consumer = new Consumer(DumbServer.getQueue(queue)); return consumer; } @Override - public void startSender(Object brokerConsumer) - { + public void startSender(Object brokerConsumer) { ((Consumer) brokerConsumer).start(); } @Override - public void createTemporaryQueue(String queueName) - { + public void createTemporaryQueue(String queueName) { } @Override - public void onFlowConsumer(Object consumer, int credits) - { + public void onFlowConsumer(Object consumer, int credits) { } @Override - public boolean queueQuery(String queueName) - { + public boolean queueQuery(String queueName) { return true; } @Override - public void closeSender(Object brokerConsumer) - { + public void closeSender(Object brokerConsumer) { ((Consumer) brokerConsumer).close(); } @Override - public ProtonJMessage encodeMessage(Object message, int deliveryCount) - { + public ProtonJMessage encodeMessage(Object message, int deliveryCount) { // We are storing internally as EncodedMessage on this minimalserver server return (ProtonServerMessage) message; } @Override - public Binary getCurrentTXID() - { + public Binary getCurrentTXID() { return new Binary(new byte[]{1}); } @Override - public void commitCurrentTX() - { + public void commitCurrentTX() { } @Override - public void rollbackCurrentTX() - { + public void rollbackCurrentTX() { } @Override - public void close() - { + public void close() { } @Override - public void ack(Object brokerConsumer, Object message) - { + public void ack(Object brokerConsumer, Object message) { } @Override - public void cancel(Object brokerConsumer, Object message, boolean updateCounts) - { + public void cancel(Object brokerConsumer, Object message, boolean updateCounts) { } @Override - public void resumeDelivery(Object consumer) - { + public void resumeDelivery(Object consumer) { System.out.println("Resume delivery!!!"); ((Consumer) consumer).start(); } @Override - public void serverSend(Receiver receiver, Delivery delivery, String address, int messageFormat, ByteBuf buffer) - { + public void serverSend(Receiver receiver, Delivery delivery, String address, int messageFormat, ByteBuf buffer) { ProtonServerMessage serverMessage = new ProtonServerMessage(); serverMessage.decode(buffer.nioBuffer()); @@ -151,61 +132,47 @@ public class MinimalSessionSPI implements AMQPSessionCallback queue.add(serverMessage); } + class Consumer { - class Consumer - { final BlockingDeque queue; - Consumer(BlockingDeque queue) - { + Consumer(BlockingDeque queue) { this.queue = queue; } boolean running = false; volatile Thread thread; - public void close() - { + public void close() { System.out.println("Closing!!!"); running = false; - if (thread != null) - { - try - { + if (thread != null) { + try { thread.join(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } thread = null; } - public synchronized void start() - { + public synchronized void start() { running = true; - if (thread == null) - { + if (thread == null) { System.out.println("Start!!!"); - thread = new Thread() - { - public void run() - { - try - { - while (running) - { + thread = new Thread() { + public void run() { + try { + while (running) { Object msg = queue.poll(1, TimeUnit.SECONDS); - if (msg != null) - { + if (msg != null) { session.serverDelivery(msg, Consumer.this, 1); } } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } diff --git a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalserver/SimpleServerThreadFactory.java b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalserver/SimpleServerThreadFactory.java index 99a5b205a9..23da4260b0 100644 --- a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalserver/SimpleServerThreadFactory.java +++ b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/minimalserver/SimpleServerThreadFactory.java @@ -21,8 +21,8 @@ import java.security.PrivilegedAction; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; -public final class SimpleServerThreadFactory implements ThreadFactory -{ +public final class SimpleServerThreadFactory implements ThreadFactory { + private final ThreadGroup group; private final AtomicInteger threadCount = new AtomicInteger(0); @@ -33,8 +33,7 @@ public final class SimpleServerThreadFactory implements ThreadFactory private final ClassLoader tccl; - public SimpleServerThreadFactory(final String groupName, final boolean daemon, final ClassLoader tccl) - { + public SimpleServerThreadFactory(final String groupName, final boolean daemon, final ClassLoader tccl) { group = new ThreadGroup(groupName + "-" + System.identityHashCode(this)); this.threadPriority = Thread.NORM_PRIORITY; @@ -44,43 +43,34 @@ public final class SimpleServerThreadFactory implements ThreadFactory this.daemon = daemon; } - public Thread newThread(final Runnable command) - { + public Thread newThread(final Runnable command) { final Thread t; // attach the thread to a group only if there is no security manager: // when sandboxed, the code does not have the RuntimePermission modifyThreadGroup - if (System.getSecurityManager() == null) - { + if (System.getSecurityManager() == null) { t = new Thread(group, command, "Thread-" + threadCount.getAndIncrement() + " (" + group.getName() + ")"); } - else - { + else { t = new Thread(command, "Thread-" + threadCount.getAndIncrement()); } - AccessController.doPrivileged(new PrivilegedAction() - { - public Object run() - { + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { t.setDaemon(daemon); t.setPriority(threadPriority); return null; } }); - try - { - AccessController.doPrivileged(new PrivilegedAction() - { - public Object run() - { + try { + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { t.setContextClassLoader(tccl); return null; } }); } - catch (java.security.AccessControlException e) - { + catch (java.security.AccessControlException e) { e.printStackTrace(); } diff --git a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/sasl/PlainSASLTest.java b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/sasl/PlainSASLTest.java index 00f7e42f94..a085eab219 100644 --- a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/sasl/PlainSASLTest.java +++ b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/sasl/PlainSASLTest.java @@ -22,11 +22,10 @@ import org.proton.plug.sasl.ClientSASLPlain; import org.proton.plug.sasl.PlainSASLResult; import org.proton.plug.sasl.ServerSASLPlain; -public class PlainSASLTest -{ +public class PlainSASLTest { + @Test - public void testPlain() - { + public void testPlain() { ClientSASLPlain plainSASL = new ClientSASLPlain("user-me", "password-secret"); byte[] bytesResult = plainSASL.getBytes(); diff --git a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/util/CreditsSemaphoreTest.java b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/util/CreditsSemaphoreTest.java index 9b88f11d0a..58e6774bf7 100644 --- a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/util/CreditsSemaphoreTest.java +++ b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/util/CreditsSemaphoreTest.java @@ -24,8 +24,8 @@ import org.junit.Assert; import org.junit.Test; import org.proton.plug.util.CreditsSemaphore; -public class CreditsSemaphoreTest -{ +public class CreditsSemaphoreTest { + final CreditsSemaphore semaphore = new CreditsSemaphore(10); final AtomicInteger errors = new AtomicInteger(0); @@ -34,34 +34,26 @@ public class CreditsSemaphoreTest final CountDownLatch waiting = new CountDownLatch(1); - Thread thread = new Thread() - { - public void run() - { - try - { - for (int i = 0; i < 12; i++) - { - if (!semaphore.tryAcquire()) - { + Thread thread = new Thread() { + public void run() { + try { + for (int i = 0; i < 12; i++) { + if (!semaphore.tryAcquire()) { waiting.countDown(); semaphore.acquire(); } acquired.incrementAndGet(); } } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); errors.incrementAndGet(); } } }; - @Test - public void testSetAndRelease() throws Exception - { + public void testSetAndRelease() throws Exception { thread.start(); // 5 seconds would be an eternity here @@ -70,8 +62,7 @@ public class CreditsSemaphoreTest Assert.assertEquals(0, semaphore.getCredits()); long timeout = System.currentTimeMillis() + 1000; - while (!semaphore.hasQueuedThreads() && System.currentTimeMillis() < timeout) - { + while (!semaphore.hasQueuedThreads() && System.currentTimeMillis() < timeout) { Thread.sleep(10); } @@ -87,8 +78,7 @@ public class CreditsSemaphoreTest } @Test - public void testDownAndUp() throws Exception - { + public void testDownAndUp() throws Exception { thread.start(); // 5 seconds would be an eternity here @@ -97,8 +87,7 @@ public class CreditsSemaphoreTest Assert.assertEquals(0, semaphore.getCredits()); long timeout = System.currentTimeMillis() + 1000; - while (!semaphore.hasQueuedThreads() && System.currentTimeMillis() < timeout) - { + while (!semaphore.hasQueuedThreads() && System.currentTimeMillis() < timeout) { Thread.sleep(10); } @@ -113,10 +102,8 @@ public class CreditsSemaphoreTest Assert.assertFalse(semaphore.hasQueuedThreads()); } - @Test - public void testStartedZeroedSetLater() throws Exception - { + public void testStartedZeroedSetLater() throws Exception { semaphore.setCredits(0); thread.start(); @@ -127,8 +114,7 @@ public class CreditsSemaphoreTest Assert.assertEquals(0, semaphore.getCredits()); long timeout = System.currentTimeMillis() + 1000; - while (!semaphore.hasQueuedThreads() && System.currentTimeMillis() < timeout) - { + while (!semaphore.hasQueuedThreads() && System.currentTimeMillis() < timeout) { Thread.sleep(10); } diff --git a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/util/ReusableLatchTest.java b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/util/ReusableLatchTest.java index 862ea952e7..8909b5e3bf 100644 --- a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/util/ReusableLatchTest.java +++ b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/util/ReusableLatchTest.java @@ -22,34 +22,29 @@ import org.junit.Assert; import org.junit.Test; import org.proton.plug.util.ReusableLatch; -public class ReusableLatchTest -{ +public class ReusableLatchTest { + @Test - public void testLatchWithParameterizedDown() throws Exception - { + public void testLatchWithParameterizedDown() throws Exception { ReusableLatch latch = new ReusableLatch(1000); latch.countDown(5000); Assert.assertTrue(latch.await(1000)); - Assert.assertEquals(0, latch.getCount()); } @Test - public void testLatchOnSingleThread() throws Exception - { + public void testLatchOnSingleThread() throws Exception { ReusableLatch latch = new ReusableLatch(); - for (int i = 1; i <= 100; i++) - { + for (int i = 1; i <= 100; i++) { latch.countUp(); Assert.assertEquals(i, latch.getCount()); } - for (int i = 100; i > 0; i--) - { + for (int i = 100; i > 0; i--) { Assert.assertEquals(i, latch.getCount()); latch.countDown(); Assert.assertEquals(i - 1, latch.getCount()); @@ -69,8 +64,7 @@ public class ReusableLatchTest * @throws Exception */ @Test - public void testLatchOnMultiThread() throws Exception - { + public void testLatchOnMultiThread() throws Exception { final ReusableLatch latch = new ReusableLatch(); latch.countUp(); // We hold at least one, so ThreadWaits won't go away @@ -78,56 +72,47 @@ public class ReusableLatchTest final int numberOfThreads = 100; final int numberOfAdds = 100; - class ThreadWait extends Thread - { + class ThreadWait extends Thread { + private volatile boolean waiting = true; @Override - public void run() - { - try - { - if (!latch.await(5000)) - { + public void run() { + try { + if (!latch.await(5000)) { System.err.println("Latch timed out"); } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } waiting = false; } } - class ThreadAdd extends Thread - { + class ThreadAdd extends Thread { + private final CountDownLatch latchReady; private final CountDownLatch latchStart; - ThreadAdd(final CountDownLatch latchReady, final CountDownLatch latchStart) - { + ThreadAdd(final CountDownLatch latchReady, final CountDownLatch latchStart) { this.latchReady = latchReady; this.latchStart = latchStart; } @Override - public void run() - { - try - { + public void run() { + try { latchReady.countDown(); // Everybody should start at the same time, to worse concurrency // effects latchStart.await(); - for (int i = 0; i < numberOfAdds; i++) - { + for (int i = 0; i < numberOfAdds; i++) { latch.countUp(); } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -139,8 +124,7 @@ public class ReusableLatchTest ThreadAdd[] threadAdds = new ThreadAdd[numberOfThreads]; ThreadWait[] waits = new ThreadWait[numberOfThreads]; - for (int i = 0; i < numberOfThreads; i++) - { + for (int i = 0; i < numberOfThreads; i++) { threadAdds[i] = new ThreadAdd(latchReady, latchStart); threadAdds[i].start(); waits[i] = new ThreadWait(); @@ -150,46 +134,39 @@ public class ReusableLatchTest latchReady.await(); latchStart.countDown(); - for (int i = 0; i < numberOfThreads; i++) - { + for (int i = 0; i < numberOfThreads; i++) { threadAdds[i].join(); } - for (int i = 0; i < numberOfThreads; i++) - { + for (int i = 0; i < numberOfThreads; i++) { Assert.assertTrue(waits[i].waiting); } Assert.assertEquals(numberOfThreads * numberOfAdds + 1, latch.getCount()); - class ThreadDown extends Thread - { + class ThreadDown extends Thread { + private final CountDownLatch latchReady; private final CountDownLatch latchStart; - ThreadDown(final CountDownLatch latchReady, final CountDownLatch latchStart) - { + ThreadDown(final CountDownLatch latchReady, final CountDownLatch latchStart) { this.latchReady = latchReady; this.latchStart = latchStart; } @Override - public void run() - { - try - { + public void run() { + try { latchReady.countDown(); // Everybody should start at the same time, to worse concurrency // effects latchStart.await(); - for (int i = 0; i < numberOfAdds; i++) - { + for (int i = 0; i < numberOfAdds; i++) { latch.countDown(); } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -200,8 +177,7 @@ public class ReusableLatchTest ThreadDown[] down = new ThreadDown[numberOfThreads]; - for (int i = 0; i < numberOfThreads; i++) - { + for (int i = 0; i < numberOfThreads; i++) { down[i] = new ThreadDown(latchReady, latchStart); down[i].start(); } @@ -209,46 +185,40 @@ public class ReusableLatchTest latchReady.await(); latchStart.countDown(); - for (int i = 0; i < numberOfThreads; i++) - { + for (int i = 0; i < numberOfThreads; i++) { down[i].join(); } Assert.assertEquals(1, latch.getCount()); - for (int i = 0; i < numberOfThreads; i++) - { + for (int i = 0; i < numberOfThreads; i++) { Assert.assertTrue(waits[i].waiting); } latch.countDown(); - for (int i = 0; i < numberOfThreads; i++) - { + for (int i = 0; i < numberOfThreads; i++) { waits[i].join(); } Assert.assertEquals(0, latch.getCount()); - for (int i = 0; i < numberOfThreads; i++) - { + for (int i = 0; i < numberOfThreads; i++) { Assert.assertFalse(waits[i].waiting); } } @Test - public void testReuseLatch() throws Exception - { + public void testReuseLatch() throws Exception { final ReusableLatch latch = new ReusableLatch(5); - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { latch.countDown(); } latch.countUp(); - class ThreadWait extends Thread - { + class ThreadWait extends Thread { + private volatile boolean waiting = false; private volatile Exception e; @@ -256,19 +226,15 @@ public class ReusableLatchTest private final CountDownLatch readyLatch = new CountDownLatch(1); @Override - public void run() - { + public void run() { waiting = true; readyLatch.countDown(); - try - { - if (!latch.await(1000)) - { + try { + if (!latch.await(1000)) { System.err.println("Latch timed out!"); } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); this.e = e; } @@ -319,8 +285,7 @@ public class ReusableLatchTest } @Test - public void testTimeout() throws Exception - { + public void testTimeout() throws Exception { ReusableLatch latch = new ReusableLatch(); latch.countUp(); diff --git a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/util/SimpleServerAbstractTest.java b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/util/SimpleServerAbstractTest.java index 89934a17db..1bfa0b47e3 100644 --- a/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/util/SimpleServerAbstractTest.java +++ b/artemis-protocols/artemis-proton-plug/src/test/java/org/proton/plug/test/util/SimpleServerAbstractTest.java @@ -26,53 +26,42 @@ import org.proton.plug.test.minimalserver.MinimalServer; import org.junit.After; import org.junit.Before; -public class SimpleServerAbstractTest -{ +public class SimpleServerAbstractTest { protected final boolean useSASL; protected final boolean useInVM; protected MinimalServer server = new MinimalServer(); - public SimpleServerAbstractTest(boolean useSASL, boolean useInVM) - { + public SimpleServerAbstractTest(boolean useSASL, boolean useInVM) { this.useSASL = useSASL; this.useInVM = useInVM; } @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { DumbServer.clear(); AbstractJMSTest.forceGC(); - if (!useInVM) - { + if (!useInVM) { server.start("127.0.0.1", Constants.PORT, useSASL); } - } @After - public void tearDown() throws Exception - { - if (!useInVM) - { + public void tearDown() throws Exception { + if (!useInVM) { server.stop(); } DumbServer.clear(); } - protected Connector newConnector() - { - if (useInVM) - { + protected Connector newConnector() { + if (useInVM) { return new InVMTestConnector(); } - else - { + else { return new SimpleAMQPConnector(); } } - } diff --git a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/ActiveMQStompException.java b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/ActiveMQStompException.java index 76fcf35c40..8688750432 100644 --- a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/ActiveMQStompException.java +++ b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/ActiveMQStompException.java @@ -20,8 +20,8 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; -public class ActiveMQStompException extends Exception -{ +public class ActiveMQStompException extends Exception { + public static final int NONE = 0; public static final int INVALID_EOL_V10 = 1; public static final int INVALID_COMMAND = 2; @@ -34,103 +34,86 @@ public class ActiveMQStompException extends Exception private VersionedStompFrameHandler handler; private boolean disconnect; - public ActiveMQStompException(StompConnection connection, String msg) - { + public ActiveMQStompException(StompConnection connection, String msg) { super(msg); handler = connection.getFrameHandler(); } - public ActiveMQStompException(String msg) - { + public ActiveMQStompException(String msg) { super(msg); handler = null; } - public ActiveMQStompException(String msg, Throwable t) - { + public ActiveMQStompException(String msg, Throwable t) { super(msg, t); this.body = t.getMessage(); handler = null; } //used for version control logic - public ActiveMQStompException(int code, String details) - { + public ActiveMQStompException(int code, String details) { super(details); this.code = code; this.body = details; handler = null; } - void addHeader(String header, String value) - { + void addHeader(String header, String value) { headers.add(new Header(header, value)); } - public void setBody(String body) - { + public void setBody(String body) { this.body = body; } - public StompFrame getFrame() - { + public StompFrame getFrame() { StompFrame frame = null; - if (handler == null) - { + if (handler == null) { frame = new StompFrame(Stomp.Responses.ERROR); } - else - { + else { frame = handler.createStompFrame(Stomp.Responses.ERROR); } frame.addHeader(Stomp.Headers.Error.MESSAGE, this.getMessage()); - for (Header header : headers) - { + for (Header header : headers) { frame.addHeader(header.key, header.val); } - if (body != null) - { + if (body != null) { frame.addHeader(Stomp.Headers.CONTENT_TYPE, "text/plain"); frame.setByteBody(body.getBytes(StandardCharsets.UTF_8)); } - else - { + else { frame.setByteBody(new byte[0]); } frame.setNeedsDisconnect(disconnect); return frame; } - private static final class Header - { + private static final class Header { + public final String key; public final String val; - public Header(String key, String val) - { + public Header(String key, String val) { this.key = key; this.val = val; } } - public void setDisconnect(boolean b) - { + public void setDisconnect(boolean b) { disconnect = b; } - public int getCode() - { + public int getCode() { return code; } - public void setCode(int newCode) - { + public void setCode(int newCode) { code = newCode; } - public ActiveMQStompException setHandler(VersionedStompFrameHandler frameHandler) - { + public ActiveMQStompException setHandler(VersionedStompFrameHandler frameHandler) { this.handler = frameHandler; return this; } diff --git a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/ActiveMQStompProtocolLogger.java b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/ActiveMQStompProtocolLogger.java index 5978583c3a..e9dc4ee5ab 100644 --- a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/ActiveMQStompProtocolLogger.java +++ b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/ActiveMQStompProtocolLogger.java @@ -39,8 +39,8 @@ import org.jboss.logging.annotations.MessageLogger; */ @MessageLogger(projectCode = "AMQ") -public interface ActiveMQStompProtocolLogger extends BasicLogger -{ +public interface ActiveMQStompProtocolLogger extends BasicLogger { + /** * The default logger. */ diff --git a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/ActiveMQStompProtocolMessageBundle.java b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/ActiveMQStompProtocolMessageBundle.java index 7d2d5c03de..b119054bb4 100644 --- a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/ActiveMQStompProtocolMessageBundle.java +++ b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/ActiveMQStompProtocolMessageBundle.java @@ -33,8 +33,8 @@ import org.jboss.logging.Messages; */ @MessageBundle(projectCode = "AMQ") -public interface ActiveMQStompProtocolMessageBundle -{ +public interface ActiveMQStompProtocolMessageBundle { + ActiveMQStompProtocolMessageBundle BUNDLE = Messages.getBundle(ActiveMQStompProtocolMessageBundle.class); @Message(id = 339000, value = "Stomp Connection TTL cannot be negative: {0}", format = Message.Format.MESSAGE_FORMAT) diff --git a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/FrameEventListener.java b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/FrameEventListener.java index 23aa1ce866..2db3928676 100644 --- a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/FrameEventListener.java +++ b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/FrameEventListener.java @@ -16,8 +16,7 @@ */ package org.apache.activemq.artemis.core.protocol.stomp; -public interface FrameEventListener -{ +public interface FrameEventListener { void replySent(StompFrame reply); diff --git a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/SimpleBytes.java b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/SimpleBytes.java index fff613a52a..68f633fdff 100644 --- a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/SimpleBytes.java +++ b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/SimpleBytes.java @@ -18,36 +18,31 @@ package org.apache.activemq.artemis.core.protocol.stomp; import java.nio.charset.StandardCharsets; +public class SimpleBytes { -public class SimpleBytes -{ private final int step; private byte[] contents; private int index; - public SimpleBytes(int initCapacity) - { + public SimpleBytes(int initCapacity) { this.step = initCapacity; contents = new byte[initCapacity]; index = 0; } - public String getString() - { - if (index == 0) return ""; + public String getString() { + if (index == 0) + return ""; return new String(contents, 0, index, StandardCharsets.UTF_8); } - public void reset() - { + public void reset() { index = 0; } - public void append(byte b) - { - if (index >= contents.length) - { + public void append(byte b) { + if (index >= contents.length) { //grow byte[] newBuffer = new byte[contents.length + step]; System.arraycopy(contents, 0, newBuffer, 0, contents.length); diff --git a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/Stomp.java b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/Stomp.java index adaa09dfb1..d1cf45c477 100644 --- a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/Stomp.java +++ b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/Stomp.java @@ -21,14 +21,14 @@ package org.apache.activemq.artemis.core.protocol.stomp; * * @version $Revision: 57 $ */ -public interface Stomp -{ +public interface Stomp { + String NULL = "\u0000"; String NEWLINE = "\n"; - public interface Commands - { + public interface Commands { + String CONNECT = "CONNECT"; String SEND = "SEND"; @@ -53,8 +53,8 @@ public interface Stomp String STOMP = "STOMP"; } - public interface Responses - { + public interface Responses { + String CONNECTED = "CONNECTED"; String ERROR = "ERROR"; @@ -64,8 +64,8 @@ public interface Stomp String RECEIPT = "RECEIPT"; } - public interface Headers - { + public interface Headers { + String SEPARATOR = ":"; String RECEIPT_REQUESTED = "receipt"; @@ -78,13 +78,13 @@ public interface Stomp String CONTENT_TYPE = "content-type"; - public interface Response - { + public interface Response { + String RECEIPT_ID = "receipt-id"; } - public interface Send - { + public interface Send { + String DESTINATION = "destination"; String CORRELATION_ID = "correlation-id"; @@ -100,8 +100,8 @@ public interface Stomp Object PERSISTENT = "persistent"; } - public interface Message - { + public interface Message { + String MESSAGE_ID = "message-id"; String DESTINATION = "destination"; @@ -125,8 +125,8 @@ public interface Stomp String ACK = "ack"; } - public interface Subscribe - { + public interface Subscribe { + String DESTINATION = "destination"; String ACK_MODE = "ack"; @@ -139,8 +139,8 @@ public interface Stomp String NO_LOCAL = "no-local"; - public interface AckModeValues - { + public interface AckModeValues { + String AUTO = "auto"; String CLIENT = "client"; @@ -149,8 +149,8 @@ public interface Stomp } } - public interface Unsubscribe - { + public interface Unsubscribe { + String DESTINATION = "destination"; String ID = "id"; @@ -158,8 +158,8 @@ public interface Stomp String DURABLE_SUBSCRIBER_NAME = "durable-subscriber-name"; } - public interface Connect - { + public interface Connect { + String LOGIN = "login"; String PASSCODE = "passcode"; @@ -175,16 +175,16 @@ public interface Stomp Object HEART_BEAT = "heart-beat"; } - public interface Error - { + public interface Error { + String MESSAGE = "message"; //1.1 String VERSION = "version"; } - public interface Connected - { + public interface Connected { + String SESSION = "session"; String RESPONSE_ID = "response-id"; @@ -197,8 +197,8 @@ public interface Stomp String HEART_BEAT = "heart-beat"; } - public interface Ack - { + public interface Ack { + String MESSAGE_ID = "message-id"; //1.1 diff --git a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompConnection.java b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompConnection.java index 1929b686fd..61d565aa8c 100644 --- a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompConnection.java +++ b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompConnection.java @@ -46,8 +46,8 @@ import org.apache.activemq.artemis.utils.VersionLoader; import static org.apache.activemq.artemis.core.protocol.stomp.ActiveMQStompProtocolMessageBundle.BUNDLE; -public final class StompConnection implements RemotingConnection -{ +public final class StompConnection implements RemotingConnection { + protected static final String CONNECTION_ID_PROP = "__AMQ_CID"; private static final String SERVER_NAME = "ActiveMQ-Artemis/" + VersionLoader.getVersion().getFullVersion() + " ActiveMQ Artemis Messaging Engine"; @@ -94,19 +94,16 @@ public final class StompConnection implements RemotingConnection private final int minLargeMessageSize; - public StompFrame decode(ActiveMQBuffer buffer) throws ActiveMQStompException - { + public StompFrame decode(ActiveMQBuffer buffer) throws ActiveMQStompException { StompFrame frame = null; - try - { + try { frame = frameHandler.decode(buffer); } - catch (ActiveMQStompException e) - { - switch (e.getCode()) - { + catch (ActiveMQStompException e) { + switch (e.getCode()) { case ActiveMQStompException.INVALID_EOL_V10: - if (version != null) throw e; + if (version != null) + throw e; frameHandler = new StompFrameHandlerV12(this); buffer.resetReaderIndex(); frame = decode(buffer); @@ -121,13 +118,13 @@ public final class StompConnection implements RemotingConnection return frame; } - public boolean hasBytes() - { + public boolean hasBytes() { return frameHandler.hasBytes(); } - StompConnection(final Acceptor acceptorUsed, final Connection transportConnection, final StompProtocolManager manager) - { + StompConnection(final Acceptor acceptorUsed, + final Connection transportConnection, + final StompProtocolManager manager) { this.transportConnection = transportConnection; this.manager = manager; @@ -138,19 +135,13 @@ public final class StompConnection implements RemotingConnection this.acceptorUsed = acceptorUsed; - this.enableMessageID = ConfigurationHelper.getBooleanProperty(TransportConstants.STOMP_ENABLE_MESSAGE_ID, - false, - acceptorUsed.getConfiguration()); - this.minLargeMessageSize = ConfigurationHelper.getIntProperty(TransportConstants.STOMP_MIN_LARGE_MESSAGE_SIZE, - ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - acceptorUsed.getConfiguration()); + this.enableMessageID = ConfigurationHelper.getBooleanProperty(TransportConstants.STOMP_ENABLE_MESSAGE_ID, false, acceptorUsed.getConfiguration()); + this.minLargeMessageSize = ConfigurationHelper.getIntProperty(TransportConstants.STOMP_MIN_LARGE_MESSAGE_SIZE, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, acceptorUsed.getConfiguration()); } @Override - public void addFailureListener(final FailureListener listener) - { - if (listener == null) - { + public void addFailureListener(final FailureListener listener) { + if (listener == null) { throw new IllegalStateException("FailureListener cannot be null"); } @@ -158,10 +149,8 @@ public final class StompConnection implements RemotingConnection } @Override - public boolean removeFailureListener(final FailureListener listener) - { - if (listener == null) - { + public boolean removeFailureListener(final FailureListener listener) { + if (listener == null) { throw new IllegalStateException("FailureListener cannot be null"); } @@ -169,10 +158,8 @@ public final class StompConnection implements RemotingConnection } @Override - public void addCloseListener(final CloseListener listener) - { - if (listener == null) - { + public void addCloseListener(final CloseListener listener) { + if (listener == null) { throw new IllegalStateException("CloseListener cannot be null"); } @@ -180,10 +167,8 @@ public final class StompConnection implements RemotingConnection } @Override - public boolean removeCloseListener(final CloseListener listener) - { - if (listener == null) - { + public boolean removeCloseListener(final CloseListener listener) { + if (listener == null) { throw new IllegalStateException("CloseListener cannot be null"); } @@ -191,8 +176,7 @@ public final class StompConnection implements RemotingConnection } @Override - public List removeCloseListeners() - { + public List removeCloseListeners() { List ret = new ArrayList(closeListeners); closeListeners.clear(); @@ -201,8 +185,7 @@ public final class StompConnection implements RemotingConnection } @Override - public List removeFailureListeners() - { + public List removeFailureListeners() { List ret = new ArrayList(failureListeners); failureListeners.clear(); @@ -211,28 +194,24 @@ public final class StompConnection implements RemotingConnection } @Override - public void setCloseListeners(List listeners) - { + public void setCloseListeners(List listeners) { closeListeners.clear(); closeListeners.addAll(listeners); } @Override - public void setFailureListeners(final List listeners) - { + public void setFailureListeners(final List listeners) { failureListeners.clear(); failureListeners.addAll(listeners); } - protected synchronized void setDataReceived() - { + protected synchronized void setDataReceived() { dataReceived = true; } - public synchronized boolean checkDataReceived() - { + public synchronized boolean checkDataReceived() { boolean res = dataReceived; dataReceived = false; @@ -240,32 +219,25 @@ public final class StompConnection implements RemotingConnection return res; } - public void checkDestination(String destination) throws ActiveMQStompException - { - if (autoCreateQueueIfPossible(destination)) - { + public void checkDestination(String destination) throws ActiveMQStompException { + if (autoCreateQueueIfPossible(destination)) { return; } - if (!manager.destinationExists(destination)) - { + if (!manager.destinationExists(destination)) { throw BUNDLE.destinationNotExist(destination).setHandler(frameHandler); } } - public boolean autoCreateQueueIfPossible(String queue) throws ActiveMQStompException - { + public boolean autoCreateQueueIfPossible(String queue) throws ActiveMQStompException { boolean autoCreated = false; - if (queue.startsWith(ResourceNames.JMS_QUEUE) && manager.getServer().getAddressSettingsRepository().getMatch(queue).isAutoCreateJmsQueues() && manager.getServer().locateQueue(new SimpleString(queue)) == null) - { + if (queue.startsWith(ResourceNames.JMS_QUEUE) && manager.getServer().getAddressSettingsRepository().getMatch(queue).isAutoCreateJmsQueues() && manager.getServer().locateQueue(new SimpleString(queue)) == null) { SimpleString queueName = new SimpleString(queue); - try - { + try { manager.getServer().createQueue(queueName, queueName, null, SimpleString.toSimpleString(this.getLogin()), true, false, true); } - catch (Exception e) - { + catch (Exception e) { throw new ActiveMQStompException(e.getMessage(), e).setHandler(frameHandler); } autoCreated = true; @@ -275,17 +247,13 @@ public final class StompConnection implements RemotingConnection } @Override - public ActiveMQBuffer createTransportBuffer(int size) - { + public ActiveMQBuffer createTransportBuffer(int size) { return ActiveMQBuffers.dynamicBuffer(size); } - public void destroy() - { - synchronized (failLock) - { - if (destroyed) - { + public void destroy() { + synchronized (failLock) { + if (destroyed) { return; } } @@ -294,30 +262,24 @@ public final class StompConnection implements RemotingConnection internalClose(); - synchronized (sendLock) - { + synchronized (sendLock) { callClosingListeners(); } } - Acceptor getAcceptorUsed() - { + Acceptor getAcceptorUsed() { return acceptorUsed; } - private void internalClose() - { + private void internalClose() { transportConnection.close(); manager.cleanup(this); } - public void fail(final ActiveMQException me) - { - synchronized (failLock) - { - if (destroyed) - { + public void fail(final ActiveMQException me) { + synchronized (failLock) { + if (destroyed) { return; } @@ -333,99 +295,79 @@ public final class StompConnection implements RemotingConnection internalClose(); } - public void fail(final ActiveMQException me, String scaleDownTargetNodeID) - { + public void fail(final ActiveMQException me, String scaleDownTargetNodeID) { fail(me); } - public void flush() - { + public void flush() { } - public List getFailureListeners() - { + public List getFailureListeners() { // we do not return the listeners otherwise the remoting service // would NOT destroy the connection. return Collections.emptyList(); } - public Object getID() - { + public Object getID() { return transportConnection.getID(); } - public String getRemoteAddress() - { + public String getRemoteAddress() { return transportConnection.getRemoteAddress(); } - public long getCreationTime() - { + public long getCreationTime() { return creationTime; } - public Connection getTransportConnection() - { + public Connection getTransportConnection() { return transportConnection; } - public boolean isClient() - { + public boolean isClient() { return false; } - public boolean isDestroyed() - { + public boolean isDestroyed() { return destroyed; } - public void bufferReceived(Object connectionID, ActiveMQBuffer buffer) - { + public void bufferReceived(Object connectionID, ActiveMQBuffer buffer) { manager.handleBuffer(this, buffer); } - public String getLogin() - { + public String getLogin() { return login; } - public String getPasscode() - { + public String getPasscode() { return passcode; } - public void setClientID(String clientID) - { + public void setClientID(String clientID) { this.clientID = clientID; } - public String getClientID() - { + public String getClientID() { return clientID; } - public boolean isValid() - { + public boolean isValid() { return valid; } - public void setValid(boolean valid) - { + public void setValid(boolean valid) { this.valid = valid; } - private void callFailureListeners(final ActiveMQException me) - { + private void callFailureListeners(final ActiveMQException me) { final List listenersClone = new ArrayList(failureListeners); - for (final FailureListener listener : listenersClone) - { - try - { + for (final FailureListener listener : listenersClone) { + try { listener.connectionFailed(me, false); } - catch (final Throwable t) - { + catch (final Throwable t) { // Failure of one listener to execute shouldn't prevent others // from // executing @@ -434,18 +376,14 @@ public final class StompConnection implements RemotingConnection } } - private void callClosingListeners() - { + private void callClosingListeners() { final List listenersClone = new ArrayList(closeListeners); - for (final CloseListener listener : listenersClone) - { - try - { + for (final CloseListener listener : listenersClone) { + try { listener.connectionClosed(); } - catch (final Throwable t) - { + catch (final Throwable t) { // Failure of one listener to execute shouldn't prevent others // from // executing @@ -458,37 +396,29 @@ public final class StompConnection implements RemotingConnection * accept-version value takes form of "v1,v2,v3..." * we need to return the highest supported version */ - public void negotiateVersion(StompFrame frame) throws ActiveMQStompException - { + public void negotiateVersion(StompFrame frame) throws ActiveMQStompException { String acceptVersion = frame.getHeader(Stomp.Headers.ACCEPT_VERSION); - if (acceptVersion == null) - { + if (acceptVersion == null) { this.version = StompVersions.V1_0; } - else - { + else { StringTokenizer tokenizer = new StringTokenizer(acceptVersion, ","); Set requestVersions = new HashSet(tokenizer.countTokens()); - while (tokenizer.hasMoreTokens()) - { + while (tokenizer.hasMoreTokens()) { requestVersions.add(tokenizer.nextToken()); } - if (requestVersions.contains(StompVersions.V1_2.toString())) - { + if (requestVersions.contains(StompVersions.V1_2.toString())) { this.version = StompVersions.V1_2; } - else if (requestVersions.contains(StompVersions.V1_1.toString())) - { + else if (requestVersions.contains(StompVersions.V1_1.toString())) { this.version = StompVersions.V1_1; } - else if (requestVersions.contains(StompVersions.V1_0.toString())) - { + else if (requestVersions.contains(StompVersions.V1_0.toString())) { this.version = StompVersions.V1_0; } - else - { + else { //not a supported version! ActiveMQStompException error = BUNDLE.versionNotSupported(acceptVersion).setHandler(frameHandler); error.addHeader(Stomp.Headers.Error.VERSION, manager.getSupportedVersionsAsErrorVersion()); @@ -499,9 +429,7 @@ public final class StompConnection implements RemotingConnection } } - - if (this.version != (StompVersions.V1_0)) - { + if (this.version != (StompVersions.V1_0)) { VersionedStompFrameHandler newHandler = VersionedStompFrameHandler.getHandler(this, this.version); newHandler.initDecoder(this.frameHandler); this.frameHandler = newHandler; @@ -510,44 +438,35 @@ public final class StompConnection implements RemotingConnection } //reject if the host doesn't match - public void setHost(String host) throws ActiveMQStompException - { - if (host == null) - { + public void setHost(String host) throws ActiveMQStompException { + if (host == null) { ActiveMQStompException error = BUNDLE.nullHostHeader().setHandler(frameHandler); error.setBody(BUNDLE.hostCannotBeNull()); throw error; } String localHost = manager.getVirtualHostName(); - if (!host.equals(localHost)) - { + if (!host.equals(localHost)) { ActiveMQStompException error = BUNDLE.hostNotMatch().setHandler(frameHandler); error.setBody(BUNDLE.hostNotMatchDetails(host)); throw error; } } - public void handleFrame(StompFrame request) - { + public void handleFrame(StompFrame request) { StompFrame reply = null; - if (stompListener != null) - { + if (stompListener != null) { stompListener.requestAccepted(request); } String cmd = request.getCommand(); - try - { - if (isDestroyed()) - { + try { + if (isDestroyed()) { throw BUNDLE.connectionDestroyed().setHandler(frameHandler); } - if (!initialized) - { - if (!(Stomp.Commands.CONNECT.equals(cmd) || Stomp.Commands.STOMP.equals(cmd))) - { + if (!initialized) { + if (!(Stomp.Commands.CONNECT.equals(cmd) || Stomp.Commands.STOMP.equals(cmd))) { throw BUNDLE.connectionNotEstablished().setHandler(frameHandler); } //decide version @@ -556,295 +475,235 @@ public final class StompConnection implements RemotingConnection reply = frameHandler.handleFrame(request); } - catch (ActiveMQStompException e) - { + catch (ActiveMQStompException e) { reply = e.getFrame(); } - if (reply != null) - { + if (reply != null) { sendFrame(reply); } - if (Stomp.Commands.DISCONNECT.equals(cmd)) - { + if (Stomp.Commands.DISCONNECT.equals(cmd)) { this.disconnect(false); } } - public void sendFrame(StompFrame frame) - { + public void sendFrame(StompFrame frame) { manager.sendReply(this, frame); } - public boolean validateUser(final String login1, final String passcode1) - { + public boolean validateUser(final String login1, final String passcode1) { this.valid = manager.validateUser(login1, passcode1); - if (valid) - { + if (valid) { this.login = login1; this.passcode = passcode1; } return valid; } - public ServerMessageImpl createServerMessage() - { + public ServerMessageImpl createServerMessage() { return manager.createServerMessage(); } - public StompSession getSession(String txID) throws ActiveMQStompException - { + public StompSession getSession(String txID) throws ActiveMQStompException { StompSession session = null; - try - { - if (txID == null) - { + try { + if (txID == null) { session = manager.getSession(this); } - else - { + else { session = manager.getTransactedSession(this, txID); } } - catch (Exception e) - { + catch (Exception e) { throw BUNDLE.errorGetSession(e).setHandler(frameHandler); } return session; } - protected void validate() throws ActiveMQStompException - { - if (!this.valid) - { + protected void validate() throws ActiveMQStompException { + if (!this.valid) { throw BUNDLE.invalidConnection().setHandler(frameHandler); } } - protected void sendServerMessage(ServerMessageImpl message, String txID) throws ActiveMQStompException - { + protected void sendServerMessage(ServerMessageImpl message, String txID) throws ActiveMQStompException { StompSession stompSession = getSession(txID); - if (stompSession.isNoLocal()) - { + if (stompSession.isNoLocal()) { message.putStringProperty(CONNECTION_ID_PROP, getID().toString()); } - if (enableMessageID()) - { - message.putStringProperty("amqMessageId", - "STOMP" + message.getMessageID()); + if (enableMessageID()) { + message.putStringProperty("amqMessageId", "STOMP" + message.getMessageID()); } - try - { - if (minLargeMessageSize == -1 || (message.getBodyBuffer().writerIndex() < minLargeMessageSize)) - { + try { + if (minLargeMessageSize == -1 || (message.getBodyBuffer().writerIndex() < minLargeMessageSize)) { stompSession.sendInternal(message, false); } - else - { + else { stompSession.sendInternalLarge(message, false); } } - catch (Exception e) - { + catch (Exception e) { throw BUNDLE.errorSendMessage(message, e).setHandler(frameHandler); } } @Override - public void disconnect(final boolean criticalError) - { + public void disconnect(final boolean criticalError) { disconnect(null, criticalError); } @Override - public void disconnect(String scaleDownNodeID, final boolean criticalError) - { + public void disconnect(String scaleDownNodeID, final boolean criticalError) { destroy(); } - protected void beginTransaction(String txID) throws ActiveMQStompException - { - try - { + protected void beginTransaction(String txID) throws ActiveMQStompException { + try { manager.beginTransaction(this, txID); } - catch (ActiveMQStompException e) - { + catch (ActiveMQStompException e) { throw e; } - catch (Exception e) - { + catch (Exception e) { throw BUNDLE.errorBeginTx(txID, e).setHandler(frameHandler); } } - public void commitTransaction(String txID) throws ActiveMQStompException - { - try - { + public void commitTransaction(String txID) throws ActiveMQStompException { + try { manager.commitTransaction(this, txID); } - catch (Exception e) - { + catch (Exception e) { throw BUNDLE.errorCommitTx(txID, e).setHandler(frameHandler); } } - public void abortTransaction(String txID) throws ActiveMQStompException - { - try - { + public void abortTransaction(String txID) throws ActiveMQStompException { + try { manager.abortTransaction(this, txID); } - catch (ActiveMQStompException e) - { + catch (ActiveMQStompException e) { throw e; } - catch (Exception e) - { + catch (Exception e) { throw BUNDLE.errorAbortTx(txID, e).setHandler(frameHandler); } } - void subscribe(String destination, String selector, String ack, - String id, String durableSubscriptionName, boolean noLocal) throws ActiveMQStompException - { + void subscribe(String destination, + String selector, + String ack, + String id, + String durableSubscriptionName, + boolean noLocal) throws ActiveMQStompException { autoCreateQueueIfPossible(destination); - if (noLocal) - { + if (noLocal) { String noLocalFilter = CONNECTION_ID_PROP + " <> '" + getID().toString() + "'"; - if (selector == null) - { + if (selector == null) { selector = noLocalFilter; } - else - { + else { selector += " AND " + noLocalFilter; } } - if (ack == null) - { + if (ack == null) { ack = Stomp.Headers.Subscribe.AckModeValues.AUTO; } String subscriptionID = null; - if (id != null) - { + if (id != null) { subscriptionID = id; } - else - { - if (destination == null) - { + else { + if (destination == null) { throw BUNDLE.noDestination().setHandler(frameHandler); } subscriptionID = "subscription/" + destination; } - try - { + try { manager.createSubscription(this, subscriptionID, durableSubscriptionName, destination, selector, ack, noLocal); } - catch (ActiveMQStompException e) - { + catch (ActiveMQStompException e) { throw e; } - catch (Exception e) - { + catch (Exception e) { throw BUNDLE.errorCreatSubscription(subscriptionID, e).setHandler(frameHandler); } } - public void unsubscribe(String subscriptionID, String durableSubscriberName) throws ActiveMQStompException - { - try - { + public void unsubscribe(String subscriptionID, String durableSubscriberName) throws ActiveMQStompException { + try { manager.unsubscribe(this, subscriptionID, durableSubscriberName); } - catch (ActiveMQStompException e) - { + catch (ActiveMQStompException e) { throw e; } - catch (Exception e) - { + catch (Exception e) { throw BUNDLE.errorUnsubscrib(subscriptionID, e).setHandler(frameHandler); } } - public void acknowledge(String messageID, String subscriptionID) throws ActiveMQStompException - { - try - { + public void acknowledge(String messageID, String subscriptionID) throws ActiveMQStompException { + try { manager.acknowledge(this, messageID, subscriptionID); } - catch (ActiveMQStompException e) - { + catch (ActiveMQStompException e) { throw e; } - catch (Exception e) - { + catch (Exception e) { throw BUNDLE.errorAck(messageID, e).setHandler(frameHandler); } } - public String getVersion() - { + public String getVersion() { return String.valueOf(version); } - public String getActiveMQServerName() - { + public String getActiveMQServerName() { return SERVER_NAME; } public StompFrame createStompMessage(ServerMessage serverMessage, - StompSubscription subscription, int deliveryCount) throws Exception - { + StompSubscription subscription, + int deliveryCount) throws Exception { return frameHandler.createMessageFrame(serverMessage, subscription, deliveryCount); } - public void addStompEventListener(FrameEventListener listener) - { + public void addStompEventListener(FrameEventListener listener) { this.stompListener = listener; } //send a ping stomp frame - public void ping(StompFrame pingFrame) - { + public void ping(StompFrame pingFrame) { manager.sendReply(this, pingFrame); } - public void physicalSend(StompFrame frame) throws Exception - { + public void physicalSend(StompFrame frame) throws Exception { ActiveMQBuffer buffer = frame.toActiveMQBuffer(); - synchronized (sendLock) - { + synchronized (sendLock) { getTransportConnection().write(buffer, false, false); } - if (stompListener != null) - { + if (stompListener != null) { stompListener.replySent(frame); } } - public VersionedStompFrameHandler getFrameHandler() - { + public VersionedStompFrameHandler getFrameHandler() { return this.frameHandler; } - public boolean enableMessageID() - { + public boolean enableMessageID() { return enableMessageID; } - public int getMinLargeMessageSize() - { + public int getMinLargeMessageSize() { return minLargeMessageSize; } diff --git a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompDecoder.java b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompDecoder.java index 57ecbb2893..2e493b412b 100644 --- a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompDecoder.java +++ b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompDecoder.java @@ -23,8 +23,8 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import static org.apache.activemq.artemis.core.protocol.stomp.ActiveMQStompProtocolMessageBundle.BUNDLE; -public class StompDecoder -{ +public class StompDecoder { + public static final boolean TRIM_LEADING_HEADER_VALUE_WHITESPACE = true; public static final String COMMAND_ABORT = Stomp.Commands.ABORT; @@ -164,13 +164,11 @@ public class StompDecoder protected final VersionedStompFrameHandler handler; - public StompDecoder(VersionedStompFrameHandler handler) - { + public StompDecoder(VersionedStompFrameHandler handler) { this.handler = handler; } - public boolean hasBytes() - { + public boolean hasBytes() { return data > pos; } @@ -186,12 +184,10 @@ public class StompDecoder * unsupported EOLs ("\r\n" valid for 1.2 only). The StompConnection will switch * to proper version decoders on catching such exceptions. */ - public synchronized StompFrame decode(final ActiveMQBuffer buffer) throws ActiveMQStompException - { + public synchronized StompFrame decode(final ActiveMQBuffer buffer) throws ActiveMQStompException { int readable = buffer.readableBytes(); - if (data + readable >= workingBuffer.length) - { + if (data + readable >= workingBuffer.length) { resizeWorking(data + readable); } @@ -199,20 +195,16 @@ public class StompDecoder data += readable; - if (command == null) - { - if (!parseCommand()) - { + if (command == null) { + if (!parseCommand()) { return null; } } //if command is not null, should it automatically be in //reading headers mode? think of get rid of readingHeaders flag - if (readingHeaders) - { - if (!parseHeaders()) - { + if (readingHeaders) { + if (!parseHeaders()) { return null; } } @@ -223,18 +215,14 @@ public class StompDecoder return ret; } - protected StompFrame parseBody() throws ActiveMQStompException - { + protected StompFrame parseBody() throws ActiveMQStompException { byte[] content = null; - if (contentLength != -1) - { - if (pos + contentLength + 1 > data) - { + if (contentLength != -1) { + if (pos + contentLength + 1 > data) { // Need more bytes } - else - { + else { content = new byte[contentLength]; System.arraycopy(workingBuffer, pos, content, 0, contentLength); @@ -242,19 +230,15 @@ public class StompDecoder pos += contentLength + 1; } } - else - { + else { // Need to scan for terminating NUL - if (bodyStart == -1) - { + if (bodyStart == -1) { bodyStart = pos; } - while (pos < data) - { - if (workingBuffer[pos++] == 0) - { + while (pos < data) { + if (workingBuffer[pos++] == 0) { content = new byte[pos - bodyStart - 1]; System.arraycopy(workingBuffer, bodyStart, content, 0, content.length); @@ -264,11 +248,10 @@ public class StompDecoder } } - if (content != null) - { - if (data > pos) - { - if (workingBuffer[pos] == NEW_LINE) pos++; + if (content != null) { + if (data > pos) { + if (workingBuffer[pos] == NEW_LINE) + pos++; if (data > pos) // More data still in the buffer from the next packet @@ -287,31 +270,24 @@ public class StompDecoder return ret; } - else - { + else { return null; } } - protected boolean parseHeaders() throws ActiveMQStompException - { - if (headerBytesCopyStart == -1) - { + protected boolean parseHeaders() throws ActiveMQStompException { + if (headerBytesCopyStart == -1) { headerBytesCopyStart = pos; } // Now the headers outer: - while (true) - { + while (true) { byte b = workingBuffer[pos++]; - switch (b) - { - case HEADER_SEPARATOR: - { - if (inHeaderName) - { + switch (b) { + case HEADER_SEPARATOR: { + if (inHeaderName) { headerName = new String(workingBuffer, headerBytesCopyStart, pos - headerBytesCopyStart - 1); inHeaderName = false; @@ -325,10 +301,8 @@ public class StompDecoder break; } - case NEW_LINE: - { - if (whiteSpaceOnly) - { + case NEW_LINE: { + if (whiteSpaceOnly) { // Headers are terminated by a blank line readingHeaders = false; @@ -339,8 +313,7 @@ public class StompDecoder headers.put(headerName, headerValue); - if (headerName.equals(Stomp.Headers.CONTENT_LENGTH)) - { + if (headerName.equals(Stomp.Headers.CONTENT_LENGTH)) { contentLength = Integer.parseInt(headerValue.toString()); } @@ -354,13 +327,10 @@ public class StompDecoder break; } - case SPACE: - { + case SPACE: { } - case TAB: - { - if (TRIM_LEADING_HEADER_VALUE_WHITESPACE && headerValueWhitespace) - { + case TAB: { + if (TRIM_LEADING_HEADER_VALUE_WHITESPACE && headerValueWhitespace) { // trim off leading whitespace from header values. // The STOMP spec examples seem to imply that whitespace should be trimmed although it is not // explicit in the spec @@ -374,15 +344,13 @@ public class StompDecoder break; } - default: - { + default: { whiteSpaceOnly = false; headerValueWhitespace = false; } } - if (pos == data) - { + if (pos == data) { // Run out of data return false; @@ -391,8 +359,7 @@ public class StompDecoder return true; } - protected boolean parseCommand() throws ActiveMQStompException - { + protected boolean parseCommand() throws ActiveMQStompException { int offset = 0; boolean nextChar = false; @@ -401,31 +368,26 @@ public class StompDecoder // next STOMP frame is read - we need to deal with this. // Besides, Stomp 1.2 allows for extra EOLs after NULL (i.e. // either "[\r]\n"s or "\n"s) - while (offset < data) - { - if (workingBuffer[offset] == NEW_LINE) - { + while (offset < data) { + if (workingBuffer[offset] == NEW_LINE) { nextChar = false; } - else if (workingBuffer[offset] == CR) - { - if (nextChar) throw BUNDLE.invalidTwoCRs().setHandler(handler); + else if (workingBuffer[offset] == CR) { + if (nextChar) + throw BUNDLE.invalidTwoCRs().setHandler(handler); nextChar = true; } - else - { + else { break; } offset++; } - if (nextChar) - { + if (nextChar) { throw BUNDLE.badCRs().setHandler(handler); } - if (data < 4 + offset) - { + if (data < 4 + offset) { // Need at least four bytes to identify the command // - up to 3 bytes for the command name + potentially another byte for a leading \n return false; @@ -433,24 +395,18 @@ public class StompDecoder byte b = workingBuffer[offset]; - switch (b) - { - case A: - { - if (workingBuffer[offset + 1] == B) - { - if (!tryIncrement(offset + COMMAND_ABORT_LENGTH + 1)) - { + switch (b) { + case A: { + if (workingBuffer[offset + 1] == B) { + if (!tryIncrement(offset + COMMAND_ABORT_LENGTH + 1)) { return false; } // ABORT command = COMMAND_ABORT; } - else - { - if (!tryIncrement(offset + COMMAND_ACK_LENGTH + 1)) - { + else { + if (!tryIncrement(offset + COMMAND_ACK_LENGTH + 1)) { return false; } @@ -459,10 +415,8 @@ public class StompDecoder } break; } - case B: - { - if (!tryIncrement(offset + COMMAND_BEGIN_LENGTH + 1)) - { + case B: { + if (!tryIncrement(offset + COMMAND_BEGIN_LENGTH + 1)) { return false; } @@ -471,12 +425,9 @@ public class StompDecoder break; } - case C: - { - if (workingBuffer[offset + 2] == M) - { - if (!tryIncrement(offset + COMMAND_COMMIT_LENGTH + 1)) - { + case C: { + if (workingBuffer[offset + 2] == M) { + if (!tryIncrement(offset + COMMAND_COMMIT_LENGTH + 1)) { return false; } @@ -484,10 +435,8 @@ public class StompDecoder command = COMMAND_COMMIT; } /**** added by meddy, 27 april 2011, handle header parser for reply to websocket protocol ****/ - else if (workingBuffer[offset + 7] == E) - { - if (!tryIncrement(offset + COMMAND_CONNECTED_LENGTH + 1)) - { + else if (workingBuffer[offset + 7] == E) { + if (!tryIncrement(offset + COMMAND_CONNECTED_LENGTH + 1)) { return false; } @@ -495,10 +444,8 @@ public class StompDecoder command = COMMAND_CONNECTED; } /**** end ****/ - else - { - if (!tryIncrement(offset + COMMAND_CONNECT_LENGTH + 1)) - { + else { + if (!tryIncrement(offset + COMMAND_CONNECT_LENGTH + 1)) { return false; } @@ -507,10 +454,8 @@ public class StompDecoder } break; } - case D: - { - if (!tryIncrement(offset + COMMAND_DISCONNECT_LENGTH + 1)) - { + case D: { + if (!tryIncrement(offset + COMMAND_DISCONNECT_LENGTH + 1)) { return false; } @@ -519,10 +464,8 @@ public class StompDecoder break; } - case R: - { - if (!tryIncrement(offset + COMMAND_RECEIPT_LENGTH + 1)) - { + case R: { + if (!tryIncrement(offset + COMMAND_RECEIPT_LENGTH + 1)) { return false; } @@ -532,10 +475,8 @@ public class StompDecoder break; } /**** added by meddy, 27 april 2011, handle header parser for reply to websocket protocol ****/ - case E: - { - if (!tryIncrement(offset + COMMAND_ERROR_LENGTH + 1)) - { + case E: { + if (!tryIncrement(offset + COMMAND_ERROR_LENGTH + 1)) { return false; } @@ -544,10 +485,8 @@ public class StompDecoder break; } - case M: - { - if (!tryIncrement(offset + COMMAND_MESSAGE_LENGTH + 1)) - { + case M: { + if (!tryIncrement(offset + COMMAND_MESSAGE_LENGTH + 1)) { return false; } @@ -557,32 +496,25 @@ public class StompDecoder break; } /**** end ****/ - case S: - { - if (workingBuffer[offset + 1] == E) - { - if (!tryIncrement(offset + COMMAND_SEND_LENGTH + 1)) - { + case S: { + if (workingBuffer[offset + 1] == E) { + if (!tryIncrement(offset + COMMAND_SEND_LENGTH + 1)) { return false; } // SEND command = COMMAND_SEND; } - else if (workingBuffer[offset + 1] == T) - { - if (!tryIncrement(offset + COMMAND_STOMP_LENGTH + 1)) - { + else if (workingBuffer[offset + 1] == T) { + if (!tryIncrement(offset + COMMAND_STOMP_LENGTH + 1)) { return false; } // STOMP command = COMMAND_STOMP; } - else - { - if (!tryIncrement(offset + COMMAND_SUBSCRIBE_LENGTH + 1)) - { + else { + if (!tryIncrement(offset + COMMAND_SUBSCRIBE_LENGTH + 1)) { return false; } @@ -591,10 +523,8 @@ public class StompDecoder } break; } - case U: - { - if (!tryIncrement(offset + COMMAND_UNSUBSCRIBE_LENGTH + 1)) - { + case U: { + if (!tryIncrement(offset + COMMAND_UNSUBSCRIBE_LENGTH + 1)) { return false; } @@ -603,15 +533,13 @@ public class StompDecoder break; } - default: - { + default: { throwInvalid(); } } // Sanity check - if (workingBuffer[pos - 1] != NEW_LINE) - { + if (workingBuffer[pos - 1] != NEW_LINE) { //give a signal to try other versions ActiveMQStompException error = BUNDLE.notValidNewLine(workingBuffer[pos - 1]).setHandler(handler); error.setCode(ActiveMQStompException.INVALID_EOL_V10); @@ -622,16 +550,14 @@ public class StompDecoder return true; } - public void throwInvalid() throws ActiveMQStompException - { + public void throwInvalid() throws ActiveMQStompException { ActiveMQStompException error = BUNDLE.invalidCommand(this.dumpByteArray(workingBuffer)).setHandler(handler); error.setCode(ActiveMQStompException.INVALID_COMMAND); error.setBody(BUNDLE.invalidFrame(this.dumpByteArray(workingBuffer))); throw error; } - public void init() - { + public void init() { pos = 0; command = null; @@ -657,8 +583,7 @@ public class StompDecoder bodyStart = -1; } - public void resizeWorking(final int newSize) - { + public void resizeWorking(final int newSize) { byte[] oldBuffer = workingBuffer; workingBuffer = new byte[newSize]; @@ -666,41 +591,33 @@ public class StompDecoder System.arraycopy(oldBuffer, 0, workingBuffer, 0, oldBuffer.length); } - public boolean tryIncrement(final int length) - { - if (pos + length >= data) - { + public boolean tryIncrement(final int length) { + if (pos + length >= data) { return false; } - else - { + else { pos += length; return true; } } - private String dumpByteArray(final byte[] bytes) - { + private String dumpByteArray(final byte[] bytes) { StringBuilder str = new StringBuilder(); - for (int i = 0; i < data; i++) - { + for (int i = 0; i < data; i++) { char b = (char) bytes[i]; - if (b < 33 || b > 136) - { + if (b < 33 || b > 136) { //Unreadable characters str.append(bytes[i]); } - else - { + else { str.append(b); } - if (i != bytes.length - 1) - { + if (i != bytes.length - 1) { str.append(","); } } @@ -708,8 +625,9 @@ public class StompDecoder return str.toString(); } - /** This should be overridden by subclasses. */ - public void init(StompDecoder decoder) - { + /** + * This should be overridden by subclasses. + */ + public void init(StompDecoder decoder) { } } diff --git a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompFrame.java b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompFrame.java index 0193fdb290..0834e96863 100644 --- a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompFrame.java +++ b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompFrame.java @@ -27,8 +27,8 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffers; /** * Represents all the data in a STOMP frame. */ -public class StompFrame -{ +public class StompFrame { + protected static final byte[] END_OF_FRAME = new byte[]{0, '\n'}; protected final String command; @@ -47,72 +47,57 @@ public class StompFrame private boolean isPing; - public StompFrame(String command) - { + public StompFrame(String command) { this(command, false); } - public StompFrame(String command, boolean disconnect) - { + public StompFrame(String command, boolean disconnect) { this.command = command; this.headers = new LinkedHashMap(); this.disconnect = disconnect; } - public StompFrame(String command, Map headers, - byte[] content) - { + public StompFrame(String command, Map headers, byte[] content) { this.command = command; this.headers = headers; this.bytesBody = content; } - public String getCommand() - { + public String getCommand() { return command; } - public int getEncodedSize() throws Exception - { - if (buffer == null) - { + public int getEncodedSize() throws Exception { + if (buffer == null) { buffer = toActiveMQBuffer(); } return size; } @Override - public String toString() - { + public String toString() { return "StompFrame[command=" + command + ", headers=" + headers + ", content= " + this.body + " bytes " + Arrays.toString(bytesBody); } - public boolean isPing() - { + public boolean isPing() { return isPing; } - public void setPing(boolean ping) - { + public void setPing(boolean ping) { isPing = ping; } - public ActiveMQBuffer toActiveMQBuffer() throws Exception - { - if (buffer == null) - { - if (bytesBody != null) - { + public ActiveMQBuffer toActiveMQBuffer() throws Exception { + if (buffer == null) { + if (bytesBody != null) { buffer = ActiveMQBuffers.dynamicBuffer(bytesBody.length + 512); } - else - { + else { buffer = ActiveMQBuffers.dynamicBuffer(512); } - if (isPing()) - { + if (isPing()) { buffer.writeByte((byte) 10); return buffer; } @@ -122,8 +107,7 @@ public class StompFrame head.append(Stomp.NEWLINE); // Output the headers. encodeHeaders(head); - if (bytesBody != null && bytesBody.length > 0 && !hasHeader(Stomp.Headers.CONTENT_LENGTH)) - { + if (bytesBody != null && bytesBody.length > 0 && !hasHeader(Stomp.Headers.CONTENT_LENGTH)) { head.append(Stomp.Headers.CONTENT_LENGTH); head.append(Stomp.Headers.SEPARATOR); head.append(bytesBody.length); @@ -133,25 +117,21 @@ public class StompFrame head.append(Stomp.NEWLINE); buffer.writeBytes(head.toString().getBytes(StandardCharsets.UTF_8)); - if (bytesBody != null) - { + if (bytesBody != null) { buffer.writeBytes(bytesBody); } buffer.writeBytes(END_OF_FRAME); size = buffer.writerIndex(); } - else - { + else { buffer.readerIndex(0); } return buffer; } - protected void encodeHeaders(StringBuilder head) - { - for (Map.Entry header : headers.entrySet()) - { + protected void encodeHeaders(StringBuilder head) { + for (Map.Entry header : headers.entrySet()) { head.append(header.getKey()); head.append(Stomp.Headers.SEPARATOR); head.append(header.getValue()); @@ -159,83 +139,70 @@ public class StompFrame } } - public String getHeader(String key) - { + public String getHeader(String key) { return headers.get(key); } - public void addHeader(String key, String val) - { + public void addHeader(String key, String val) { headers.put(key, val); } - public Map getHeadersMap() - { + public Map getHeadersMap() { return headers; } - public class Header - { + public class Header { + public String key; public String val; - public Header(String key, String val) - { + public Header(String key, String val) { this.key = key; this.val = val; } - public String getEncodedKey() - { + public String getEncodedKey() { return encode(key); } - public String getEncodedValue() - { + public String getEncodedValue() { return encode(val); } } - public String encode(String str) - { + public String encode(String str) { int len = str.length(); char[] buffer = new char[2 * len]; int iBuffer = 0; - for (int i = 0; i < len; i++) - { + for (int i = 0; i < len; i++) { char c = str.charAt(i); // \n - if (c == (byte) 10) - { + if (c == (byte) 10) { buffer[iBuffer] = (byte) 92; buffer[++iBuffer] = (byte) 110; } // \r - else if (c == (byte) 13) - { + else if (c == (byte) 13) { buffer[iBuffer] = (byte) 92; buffer[++iBuffer] = (byte) 114; } // \ - else if (c == (byte) 92) - { + else if (c == (byte) 92) { buffer[iBuffer] = (byte) 92; buffer[++iBuffer] = (byte) 92; } // : - else if (c == (byte) 58) - { + else if (c == (byte) 58) { buffer[iBuffer] = (byte) 92; buffer[++iBuffer] = (byte) 99; } - else - { + else { buffer[iBuffer] = c; } iBuffer++; @@ -244,23 +211,18 @@ public class StompFrame return new String(buffer, 0, iBuffer); } - public void setBody(String body) - { + public void setBody(String body) { this.body = body; this.bytesBody = body.getBytes(StandardCharsets.UTF_8); } - public boolean hasHeader(String key) - { + public boolean hasHeader(String key) { return headers.containsKey(key); } - public String getBody() - { - if (body == null) - { - if (bytesBody != null) - { + public String getBody() { + if (body == null) { + if (bytesBody != null) { body = new String(bytesBody, StandardCharsets.UTF_8); } } @@ -268,23 +230,19 @@ public class StompFrame } //Since 1.1, there is a content-type header that needs to take care of - public byte[] getBodyAsBytes() - { + public byte[] getBodyAsBytes() { return bytesBody; } - public boolean needsDisconnect() - { + public boolean needsDisconnect() { return disconnect; } - public void setByteBody(byte[] content) - { + public void setByteBody(byte[] content) { this.bytesBody = content; } - public void setNeedsDisconnect(boolean b) - { + public void setNeedsDisconnect(boolean b) { disconnect = b; } } diff --git a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompFrameInterceptor.java b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompFrameInterceptor.java index c8f85854cc..3737ce0729 100644 --- a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompFrameInterceptor.java +++ b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompFrameInterceptor.java @@ -24,6 +24,6 @@ import org.apache.activemq.artemis.api.core.BaseInterceptor; * To add an interceptor to ActiveMQ Artemis server, you have to modify the server configuration file * {@literal broker.xml}.
    */ -public interface StompFrameInterceptor extends BaseInterceptor -{ +public interface StompFrameInterceptor extends BaseInterceptor { + } diff --git a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompProtocolManager.java b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompProtocolManager.java index b3d926ccab..98d21e4227 100644 --- a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompProtocolManager.java +++ b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompProtocolManager.java @@ -62,8 +62,7 @@ import static org.apache.activemq.artemis.core.protocol.stomp.ActiveMQStompProto /** * StompProtocolManager */ -class StompProtocolManager implements ProtocolManager, NotificationListener -{ +class StompProtocolManager implements ProtocolManager, NotificationListener { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -88,14 +87,15 @@ class StompProtocolManager implements ProtocolManager, No // Constructors -------------------------------------------------- - public StompProtocolManager(final StompProtocolManagerFactory factory, final ActiveMQServer server, final List incomingInterceptors, final List outgoingInterceptors) - { + public StompProtocolManager(final StompProtocolManagerFactory factory, + final ActiveMQServer server, + final List incomingInterceptors, + final List outgoingInterceptors) { this.factory = factory; this.server = server; this.executor = server.getExecutorFactory().getExecutor(); ManagementService service = server.getManagementService(); - if (service != null) - { + if (service != null) { //allow management message to pass destinations.add(service.getManagementAddress().toString()); service.addNotificationListener(this); @@ -105,14 +105,12 @@ class StompProtocolManager implements ProtocolManager, No } @Override - public ProtocolManagerFactory getFactory() - { + public ProtocolManagerFactory getFactory() { return factory; } @Override - public void updateInterceptors(List incoming, List outgoing) - { + public void updateInterceptors(List incoming, List outgoing) { this.incomingInterceptors.clear(); this.incomingInterceptors.addAll(getFactory().filterInterceptors(incoming)); @@ -121,15 +119,13 @@ class StompProtocolManager implements ProtocolManager, No } @Override - public MessageConverter getConverter() - { + public MessageConverter getConverter() { return null; } // ProtocolManager implementation -------------------------------- - public ConnectionEntry createConnectionEntry(final Acceptor acceptorUsed, final Connection connection) - { + public ConnectionEntry createConnectionEntry(final Acceptor acceptorUsed, final Connection connection) { StompConnection conn = new StompConnection(acceptorUsed, connection, this); // Note that STOMP 1.0 has no heartbeat, so if connection ttl is non zero, data must continue to be sent or connection @@ -138,10 +134,8 @@ class StompProtocolManager implements ProtocolManager, No String ttlStr = (String) acceptorUsed.getConfiguration().get(TransportConstants.CONNECTION_TTL); Long ttl = ttlStr == null ? null : Long.valueOf(ttlStr); - if (ttl != null) - { - if (ttl > 0) - { + if (ttl != null) { + if (ttl > 0) { return new ConnectionEntry(conn, null, System.currentTimeMillis(), ttl); } throw BUNDLE.negativeConnectionTTL(ttl); @@ -149,100 +143,81 @@ class StompProtocolManager implements ProtocolManager, No ttl = server.getConfiguration().getConnectionTTLOverride(); - if (ttl != -1) - { + if (ttl != -1) { return new ConnectionEntry(conn, null, System.currentTimeMillis(), ttl); } - else - { + else { // Default to 1 minute - which is same as core protocol return new ConnectionEntry(conn, null, System.currentTimeMillis(), 1 * 60 * 1000); } } - public void removeHandler(String name) - { + public void removeHandler(String name) { } - public void handleBuffer(final RemotingConnection connection, final ActiveMQBuffer buffer) - { + public void handleBuffer(final RemotingConnection connection, final ActiveMQBuffer buffer) { StompConnection conn = (StompConnection) connection; conn.setDataReceived(); - do - { + do { StompFrame request; - try - { + try { request = conn.decode(buffer); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorDecodingPacket(e); return; } - if (request == null) - { + if (request == null) { break; } - try - { + try { invokeInterceptors(this.incomingInterceptors, request, conn); conn.handleFrame(request); } - finally - { + finally { server.getStorageManager().clearContext(); } } while (conn.hasBytes()); } @Override - public void addChannelHandlers(ChannelPipeline pipeline) - { + public void addChannelHandlers(ChannelPipeline pipeline) { } @Override - public boolean isProtocol(byte[] array) - { + public boolean isProtocol(byte[] array) { String frameStart = new String(array, StandardCharsets.US_ASCII); return frameStart.startsWith(Stomp.Commands.CONNECT) || frameStart.startsWith(Stomp.Commands.STOMP); } @Override - public void handshake(NettyServerConnection connection, ActiveMQBuffer buffer) - { + public void handshake(NettyServerConnection connection, ActiveMQBuffer buffer) { //Todo move handshake to here } // Public -------------------------------------------------------- - public boolean send(final StompConnection connection, final StompFrame frame) - { - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + public boolean send(final StompConnection connection, final StompFrame frame) { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("sent " + frame); } invokeInterceptors(this.outgoingInterceptors, frame, connection); - synchronized (connection) - { - if (connection.isDestroyed()) - { + synchronized (connection) { + if (connection.isDestroyed()) { ActiveMQStompProtocolLogger.LOGGER.connectionClosed(connection); return false; } - try - { + try { connection.physicalSend(frame); } - catch (Exception e) - { + catch (Exception e) { ActiveMQStompProtocolLogger.LOGGER.errorSendingFrame(e, frame); return false; } @@ -256,25 +231,12 @@ class StompProtocolManager implements ProtocolManager, No // Private ------------------------------------------------------- - public StompSession getSession(StompConnection connection) throws Exception - { + public StompSession getSession(StompConnection connection) throws Exception { StompSession stompSession = sessions.get(connection.getID()); - if (stompSession == null) - { - stompSession = new StompSession(connection, this, server.getStorageManager() - .newContext(server.getExecutorFactory().getExecutor())); + if (stompSession == null) { + stompSession = new StompSession(connection, this, server.getStorageManager().newContext(server.getExecutorFactory().getExecutor())); String name = UUIDGenerator.getInstance().generateStringUUID(); - ServerSession session = server.createSession(name, - connection.getLogin(), - connection.getPasscode(), - ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - connection, - true, - false, - false, - false, - null, - stompSession, null, true); + ServerSession session = server.createSession(name, connection.getLogin(), connection.getPasscode(), ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, connection, true, false, false, false, null, stompSession, null, true); stompSession.setServerSession(session); sessions.put(connection.getID(), stompSession); } @@ -282,24 +244,12 @@ class StompProtocolManager implements ProtocolManager, No return stompSession; } - public StompSession getTransactedSession(StompConnection connection, String txID) throws Exception - { + public StompSession getTransactedSession(StompConnection connection, String txID) throws Exception { StompSession stompSession = transactedSessions.get(txID); - if (stompSession == null) - { + if (stompSession == null) { stompSession = new StompSession(connection, this, server.getStorageManager().newContext(executor)); String name = UUIDGenerator.getInstance().generateStringUUID(); - ServerSession session = server.createSession(name, - connection.getLogin(), - connection.getPasscode(), - ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - connection, - false, - false, - false, - false, - null, - stompSession, null, true); + ServerSession session = server.createSession(name, connection.getLogin(), connection.getPasscode(), ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, connection, false, false, false, false, null, stompSession, null, true); stompSession.setServerSession(session); transactedSessions.put(txID, stompSession); } @@ -307,45 +257,35 @@ class StompProtocolManager implements ProtocolManager, No return stompSession; } - public void cleanup(final StompConnection connection) - { + public void cleanup(final StompConnection connection) { connection.setValid(false); // Close the session outside of the lock on the StompConnection, otherwise it could dead lock - this.executor.execute(new Runnable() - { - public void run() - { + this.executor.execute(new Runnable() { + public void run() { StompSession session = sessions.remove(connection.getID()); - if (session != null) - { - try - { + if (session != null) { + try { session.getSession().stop(); session.getSession().rollback(true); session.getSession().close(false); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorCleaningStompConn(e); } } // removed the transacted session belonging to the connection Iterator> iterator = transactedSessions.entrySet().iterator(); - while (iterator.hasNext()) - { + while (iterator.hasNext()) { Map.Entry entry = iterator.next(); - if (entry.getValue().getConnection() == connection) - { + if (entry.getValue().getConnection() == connection) { ServerSession serverSession = entry.getValue().getSession(); - try - { + try { serverSession.rollback(true); serverSession.close(false); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorCleaningStompConn(e); } iterator.remove(); @@ -355,89 +295,71 @@ class StompProtocolManager implements ProtocolManager, No }); } - public void sendReply(final StompConnection connection, final StompFrame frame) - { - server.getStorageManager().afterCompleteOperations(new IOCallback() - { - public void onError(final int errorCode, final String errorMessage) - { + public void sendReply(final StompConnection connection, final StompFrame frame) { + server.getStorageManager().afterCompleteOperations(new IOCallback() { + public void onError(final int errorCode, final String errorMessage) { ActiveMQServerLogger.LOGGER.errorProcessingIOCallback(errorCode, errorMessage); - ActiveMQStompException e = new ActiveMQStompException("Error sending reply", - ActiveMQExceptionType.createException(errorCode, errorMessage)) - .setHandler(connection.getFrameHandler()); + ActiveMQStompException e = new ActiveMQStompException("Error sending reply", ActiveMQExceptionType.createException(errorCode, errorMessage)).setHandler(connection.getFrameHandler()); StompFrame error = e.getFrame(); send(connection, error); } - public void done() - { + public void done() { send(connection, frame); } }); } - public String getSupportedVersionsAsString() - { + public String getSupportedVersionsAsString() { String versions = ""; - for (StompVersions version : StompVersions.values()) - { + for (StompVersions version : StompVersions.values()) { versions += " v" + version; } return versions.substring(1); } - public String getSupportedVersionsAsErrorVersion() - { + public String getSupportedVersionsAsErrorVersion() { String versions = ""; - for (StompVersions version : StompVersions.values()) - { + for (StompVersions version : StompVersions.values()) { versions += "," + version; } return versions.substring(1); } - public String getVirtualHostName() - { + public String getVirtualHostName() { return "activemq"; } - public boolean validateUser(String login, String passcode) - { + public boolean validateUser(String login, String passcode) { boolean validated = true; ActiveMQSecurityManager sm = server.getSecurityManager(); - if (sm != null && server.getConfiguration().isSecurityEnabled()) - { + if (sm != null && server.getConfiguration().isSecurityEnabled()) { validated = sm.validateUser(login, passcode); } return validated; } - public ServerMessageImpl createServerMessage() - { + public ServerMessageImpl createServerMessage() { return new ServerMessageImpl(server.getStorageManager().generateID(), 512); } - public void commitTransaction(StompConnection connection, String txID) throws Exception - { + public void commitTransaction(StompConnection connection, String txID) throws Exception { StompSession session = getTransactedSession(connection, txID); - if (session == null) - { + if (session == null) { throw new ActiveMQStompException(connection, "No transaction started: " + txID); } transactedSessions.remove(txID); session.getSession().commit(); } - public void abortTransaction(StompConnection connection, String txID) throws Exception - { + public void abortTransaction(StompConnection connection, String txID) throws Exception { StompSession session = getTransactedSession(connection, txID); - if (session == null) - { + if (session == null) { throw new ActiveMQStompException(connection, "No transaction started: " + txID); } transactedSessions.remove(txID); @@ -446,49 +368,41 @@ class StompProtocolManager implements ProtocolManager, No // Inner classes ------------------------------------------------- public void createSubscription(StompConnection connection, - String subscriptionID, String durableSubscriptionName, - String destination, String selector, String ack, boolean noLocal) throws Exception - { + String subscriptionID, + String durableSubscriptionName, + String destination, + String selector, + String ack, + boolean noLocal) throws Exception { StompSession stompSession = getSession(connection); stompSession.setNoLocal(noLocal); - if (stompSession.containsSubscription(subscriptionID)) - { + if (stompSession.containsSubscription(subscriptionID)) { throw new ActiveMQStompException(connection, "There already is a subscription for: " + subscriptionID + - ". Either use unique subscription IDs or do not create multiple subscriptions for the same destination"); + ". Either use unique subscription IDs or do not create multiple subscriptions for the same destination"); } long consumerID = server.getStorageManager().generateID(); String clientID = (connection.getClientID() != null) ? connection.getClientID() : null; - stompSession.addSubscription(consumerID, - subscriptionID, - clientID, - durableSubscriptionName, - destination, - selector, - ack); + stompSession.addSubscription(consumerID, subscriptionID, clientID, durableSubscriptionName, destination, selector, ack); } public void unsubscribe(StompConnection connection, - String subscriptionID, String durableSubscriberName) throws Exception - { + String subscriptionID, + String durableSubscriberName) throws Exception { StompSession stompSession = getSession(connection); boolean unsubscribed = stompSession.unsubscribe(subscriptionID, durableSubscriberName); - if (!unsubscribed) - { + if (!unsubscribed) { throw new ActiveMQStompException(connection, "Cannot unsubscribe as no subscription exists for id: " + subscriptionID); } } - public void acknowledge(StompConnection connection, String messageID, String subscriptionID) throws Exception - { + public void acknowledge(StompConnection connection, String messageID, String subscriptionID) throws Exception { StompSession stompSession = getSession(connection); stompSession.acknowledge(messageID, subscriptionID); } - public void beginTransaction(StompConnection connection, String txID) throws Exception - { + public void beginTransaction(StompConnection connection, String txID) throws Exception { ActiveMQServerLogger.LOGGER.stompBeginTX(txID); - if (transactedSessions.containsKey(txID)) - { + if (transactedSessions.containsKey(txID)) { ActiveMQServerLogger.LOGGER.stompErrorTXExists(txID); throw new ActiveMQStompException(connection, "Transaction already started: " + txID); } @@ -496,33 +410,28 @@ class StompProtocolManager implements ProtocolManager, No getTransactedSession(connection, txID); } - public boolean destinationExists(String destination) - { + public boolean destinationExists(String destination) { return destinations.contains(destination); } @Override - public void onNotification(Notification notification) - { - if (!(notification.getType() instanceof CoreNotificationType)) return; + public void onNotification(Notification notification) { + if (!(notification.getType() instanceof CoreNotificationType)) + return; CoreNotificationType type = (CoreNotificationType) notification.getType(); TypedProperties props = notification.getProperties(); - switch (type) - { - case BINDING_ADDED: - { - if (!props.containsProperty(ManagementHelper.HDR_BINDING_TYPE)) - { + switch (type) { + case BINDING_ADDED: { + if (!props.containsProperty(ManagementHelper.HDR_BINDING_TYPE)) { throw ActiveMQMessageBundle.BUNDLE.bindingTypeNotSpecified(); } Integer bindingType = props.getIntProperty(ManagementHelper.HDR_BINDING_TYPE); - if (bindingType == BindingType.DIVERT_INDEX) - { + if (bindingType == BindingType.DIVERT_INDEX) { return; } @@ -532,8 +441,7 @@ class StompProtocolManager implements ProtocolManager, No break; } - case BINDING_REMOVED: - { + case BINDING_REMOVED: { SimpleString address = props.getSimpleStringProperty(ManagementHelper.HDR_ADDRESS); destinations.remove(address.toString()); break; @@ -544,26 +452,21 @@ class StompProtocolManager implements ProtocolManager, No } } - public ActiveMQServer getServer() - { + public ActiveMQServer getServer() { return server; } - private void invokeInterceptors(List interceptors, final StompFrame frame, final StompConnection connection) - { - if (interceptors != null && !interceptors.isEmpty()) - { - for (StompFrameInterceptor interceptor : interceptors) - { - try - { - if (!interceptor.intercept(frame, connection)) - { + private void invokeInterceptors(List interceptors, + final StompFrame frame, + final StompConnection connection) { + if (interceptors != null && !interceptors.isEmpty()) { + for (StompFrameInterceptor interceptor : interceptors) { + try { + if (!interceptor.intercept(frame, connection)) { break; } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.error(e); } } diff --git a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompProtocolManagerFactory.java b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompProtocolManagerFactory.java index 381b38dd79..df0442556e 100644 --- a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompProtocolManagerFactory.java +++ b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompProtocolManagerFactory.java @@ -23,34 +23,32 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.spi.core.protocol.AbstractProtocolManagerFactory; import org.apache.activemq.artemis.spi.core.protocol.ProtocolManager; -public class StompProtocolManagerFactory extends AbstractProtocolManagerFactory -{ +public class StompProtocolManagerFactory extends AbstractProtocolManagerFactory { + public static final String STOMP_PROTOCOL_NAME = "STOMP"; private static final String MODULE_NAME = "artemis-stomp-protocol"; private static final String[] SUPPORTED_PROTOCOLS = {STOMP_PROTOCOL_NAME}; - public ProtocolManager createProtocolManager(final ActiveMQServer server, final List incomingInterceptors, List outgoingInterceptors) - { + public ProtocolManager createProtocolManager(final ActiveMQServer server, + final List incomingInterceptors, + List outgoingInterceptors) { return new StompProtocolManager(this, server, incomingInterceptors, outgoingInterceptors); } @Override - public List filterInterceptors(List interceptors) - { + public List filterInterceptors(List interceptors) { return filterInterceptors(StompFrameInterceptor.class, interceptors); } @Override - public String[] getProtocols() - { + public String[] getProtocols() { return SUPPORTED_PROTOCOLS; } @Override - public String getModuleName() - { + public String getModuleName() { return MODULE_NAME; } diff --git a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompSession.java b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompSession.java index f7aad8bc79..227b2337da 100644 --- a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompSession.java +++ b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompSession.java @@ -47,8 +47,8 @@ import org.apache.activemq.artemis.utils.UUIDGenerator; import static org.apache.activemq.artemis.core.protocol.stomp.ActiveMQStompProtocolMessageBundle.BUNDLE; -public class StompSession implements SessionCallback -{ +public class StompSession implements SessionCallback { + private final StompProtocolManager manager; private final StompConnection connection; @@ -66,50 +66,39 @@ public class StompSession implements SessionCallback private final int consumerCredits; - StompSession(final StompConnection connection, final StompProtocolManager manager, OperationContext sessionContext) - { + StompSession(final StompConnection connection, final StompProtocolManager manager, OperationContext sessionContext) { this.connection = connection; this.manager = manager; this.sessionContext = sessionContext; - this.consumerCredits = ConfigurationHelper.getIntProperty(TransportConstants.STOMP_CONSUMERS_CREDIT, - TransportConstants.STOMP_DEFAULT_CONSUMERS_CREDIT, - connection.getAcceptorUsed().getConfiguration()); + this.consumerCredits = ConfigurationHelper.getIntProperty(TransportConstants.STOMP_CONSUMERS_CREDIT, TransportConstants.STOMP_DEFAULT_CONSUMERS_CREDIT, connection.getAcceptorUsed().getConfiguration()); } - void setServerSession(ServerSession session) - { + void setServerSession(ServerSession session) { this.session = session; } - public ServerSession getSession() - { + public ServerSession getSession() { return session; } @Override - public boolean hasCredits(ServerConsumer consumerID) - { + public boolean hasCredits(ServerConsumer consumerID) { return true; } - public void sendProducerCreditsMessage(int credits, SimpleString address) - { + public void sendProducerCreditsMessage(int credits, SimpleString address) { } - public void sendProducerCreditsFailMessage(int credits, SimpleString address) - { + public void sendProducerCreditsFailMessage(int credits, SimpleString address) { } - public int sendMessage(ServerMessage serverMessage, ServerConsumer consumer, int deliveryCount) - { + public int sendMessage(ServerMessage serverMessage, ServerConsumer consumer, int deliveryCount) { LargeServerMessageImpl largeMessage = null; ServerMessage newServerMessage = serverMessage; - try - { + try { StompSubscription subscription = subscriptions.get(consumer.getID()); StompFrame frame = null; - if (serverMessage.isLargeMessage()) - { + if (serverMessage.isLargeMessage()) { newServerMessage = serverMessage.copy(); largeMessage = (LargeServerMessageImpl) serverMessage; @@ -123,15 +112,13 @@ public class StompSession implements SessionCallback encoder.close(); } - if (serverMessage.getBooleanProperty(Message.HDR_LARGE_COMPRESSED)) - { + if (serverMessage.getBooleanProperty(Message.HDR_LARGE_COMPRESSED)) { //decompress ActiveMQBuffer qbuff = newServerMessage.getBodyBuffer(); int bytesToRead = qbuff.writerIndex() - MessageImpl.BODY_OFFSET; Inflater inflater = new Inflater(); inflater.setInput(qbuff.readBytes(bytesToRead).toByteBuffer().array()); - //get the real size of large message long sizeBody = newServerMessage.getLongProperty(Message.HDR_LARGE_BODY_SIZE); @@ -147,17 +134,14 @@ public class StompSession implements SessionCallback int length = frame.getEncodedSize(); - if (subscription.getAck().equals(Stomp.Headers.Subscribe.AckModeValues.AUTO)) - { - if (manager.send(connection, frame)) - { + if (subscription.getAck().equals(Stomp.Headers.Subscribe.AckModeValues.AUTO)) { + if (manager.send(connection, frame)) { //we ack and commit only if the send is successful session.acknowledge(consumer.getID(), newServerMessage.getMessageID()); session.commit(); } } - else - { + else { messagesToAck.put(newServerMessage.getMessageID(), new Pair(consumer.getID(), length)); // Must send AFTER adding to messagesToAck - or could get acked from client BEFORE it's been added! manager.send(connection, frame); @@ -165,14 +149,11 @@ public class StompSession implements SessionCallback return length; } - catch (Exception e) - { + catch (Exception e) { return 0; } - finally - { - if (largeMessage != null) - { + finally { + if (largeMessage != null) { largeMessage.releaseResources(); largeMessage = null; } @@ -180,36 +161,32 @@ public class StompSession implements SessionCallback } - public int sendLargeMessageContinuation(ServerConsumer consumer, byte[] body, boolean continues, boolean requiresResponse) - { + public int sendLargeMessageContinuation(ServerConsumer consumer, + byte[] body, + boolean continues, + boolean requiresResponse) { return 0; } - public int sendLargeMessage(ServerMessage msg, ServerConsumer consumer, long bodySize, int deliveryCount) - { + public int sendLargeMessage(ServerMessage msg, ServerConsumer consumer, long bodySize, int deliveryCount) { return 0; } - public void closed() - { + public void closed() { } - public void addReadyListener(final ReadyListener listener) - { + public void addReadyListener(final ReadyListener listener) { connection.getTransportConnection().addReadyListener(listener); } - public void removeReadyListener(final ReadyListener listener) - { + public void removeReadyListener(final ReadyListener listener) { connection.getTransportConnection().removeReadyListener(listener); } @Override - public void disconnect(ServerConsumer consumerId, String queueName) - { + public void disconnect(ServerConsumer consumerId, String queueName) { StompSubscription stompSubscription = subscriptions.remove(consumerId.getID()); - if (stompSubscription != null) - { + if (stompSubscription != null) { StompFrame frame = connection.getFrameHandler().createStompFrame(Stomp.Responses.ERROR); frame.addHeader(Stomp.Headers.CONTENT_TYPE, "text/plain"); frame.setBody("consumer with ID " + consumerId + " disconnected by server"); @@ -217,13 +194,11 @@ public class StompSession implements SessionCallback } } - public void acknowledge(String messageID, String subscriptionID) throws Exception - { + public void acknowledge(String messageID, String subscriptionID) throws Exception { long id = Long.parseLong(messageID); Pair pair = messagesToAck.remove(id); - if (pair == null) - { + if (pair == null) { throw BUNDLE.failToAckMissingID(id).setHandler(connection.getFrameHandler()); } @@ -232,25 +207,20 @@ public class StompSession implements SessionCallback StompSubscription sub = subscriptions.get(consumerID); - if (subscriptionID != null) - { - if (!sub.getID().equals(subscriptionID)) - { + if (subscriptionID != null) { + if (!sub.getID().equals(subscriptionID)) { throw BUNDLE.subscriptionIDMismatch(subscriptionID, sub.getID()).setHandler(connection.getFrameHandler()); } } - if (this.consumerCredits != -1) - { + if (this.consumerCredits != -1) { session.receiveConsumerCredits(consumerID, credits); } - if (sub.getAck().equals(Stomp.Headers.Subscribe.AckModeValues.CLIENT_INDIVIDUAL)) - { + if (sub.getAck().equals(Stomp.Headers.Subscribe.AckModeValues.CLIENT_INDIVIDUAL)) { session.individualAcknowledge(consumerID, id); } - else - { + else { session.acknowledge(consumerID, id); } @@ -263,40 +233,32 @@ public class StompSession implements SessionCallback String durableSubscriptionName, String destination, String selector, - String ack) throws Exception - { + String ack) throws Exception { SimpleString queue = SimpleString.toSimpleString(destination); int receiveCredits = consumerCredits; - if (ack.equals(Stomp.Headers.Subscribe.AckModeValues.AUTO)) - { + if (ack.equals(Stomp.Headers.Subscribe.AckModeValues.AUTO)) { receiveCredits = -1; } - if (destination.startsWith("jms.topic")) - { + if (destination.startsWith("jms.topic")) { // subscribes to a topic - if (durableSubscriptionName != null) - { - if (clientID == null) - { + if (durableSubscriptionName != null) { + if (clientID == null) { throw BUNDLE.missingClientID(); } queue = SimpleString.toSimpleString(clientID + "." + durableSubscriptionName); QueueQueryResult query = session.executeQueueQuery(queue); - if (!query.isExists()) - { + if (!query.isExists()) { session.createQueue(SimpleString.toSimpleString(destination), queue, SimpleString.toSimpleString(selector), false, true); } } - else - { + else { queue = UUIDGenerator.getInstance().generateSimpleStringUUID(); session.createQueue(SimpleString.toSimpleString(destination), queue, SimpleString.toSimpleString(selector), true, false); } ((ServerSessionImpl) session).createConsumer(consumerID, queue, null, false, false, receiveCredits); } - else - { + else { ((ServerSessionImpl) session).createConsumer(consumerID, queue, SimpleString.toSimpleString(selector), false, false, receiveCredits); } @@ -306,30 +268,24 @@ public class StompSession implements SessionCallback session.start(); } - public boolean unsubscribe(String id, String durableSubscriptionName) throws Exception - { + public boolean unsubscribe(String id, String durableSubscriptionName) throws Exception { Iterator> iterator = subscriptions.entrySet().iterator(); - while (iterator.hasNext()) - { + while (iterator.hasNext()) { Map.Entry entry = iterator.next(); long consumerID = entry.getKey(); StompSubscription sub = entry.getValue(); - if (id != null && id.equals(sub.getID())) - { + if (id != null && id.equals(sub.getID())) { iterator.remove(); session.closeConsumer(consumerID); SimpleString queueName; - if (durableSubscriptionName != null && durableSubscriptionName.trim().length() != 0) - { + if (durableSubscriptionName != null && durableSubscriptionName.trim().length() != 0) { queueName = SimpleString.toSimpleString(id + "." + durableSubscriptionName); } - else - { + else { queueName = SimpleString.toSimpleString(id); } QueueQueryResult query = session.executeQueueQuery(queueName); - if (query.isExists()) - { + if (query.isExists()) { session.deleteQueue(queueName); } return true; @@ -338,51 +294,41 @@ public class StompSession implements SessionCallback return false; } - boolean containsSubscription(String subscriptionID) - { + boolean containsSubscription(String subscriptionID) { Iterator> iterator = subscriptions.entrySet().iterator(); - while (iterator.hasNext()) - { + while (iterator.hasNext()) { Map.Entry entry = iterator.next(); StompSubscription sub = entry.getValue(); - if (sub.getID().equals(subscriptionID)) - { + if (sub.getID().equals(subscriptionID)) { return true; } } return false; } - public RemotingConnection getConnection() - { + public RemotingConnection getConnection() { return connection; } - public OperationContext getContext() - { + public OperationContext getContext() { return sessionContext; } - public boolean isNoLocal() - { + public boolean isNoLocal() { return noLocal; } - public void setNoLocal(boolean noLocal) - { + public void setNoLocal(boolean noLocal) { this.noLocal = noLocal; } - public void sendInternal(ServerMessageImpl message, boolean direct) throws Exception - { + public void sendInternal(ServerMessageImpl message, boolean direct) throws Exception { session.send(message, direct); } - public void sendInternalLarge(ServerMessageImpl message, boolean direct) throws Exception - { + public void sendInternalLarge(ServerMessageImpl message, boolean direct) throws Exception { int headerSize = message.getHeadersAndPropertiesEncodeSize(); - if (headerSize >= connection.getMinLargeMessageSize()) - { + if (headerSize >= connection.getMinLargeMessageSize()) { throw BUNDLE.headerTooBig(); } diff --git a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompSubscription.java b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompSubscription.java index fda64cc063..971af27c8d 100644 --- a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompSubscription.java +++ b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompSubscription.java @@ -16,8 +16,7 @@ */ package org.apache.activemq.artemis.core.protocol.stomp; -public class StompSubscription -{ +public class StompSubscription { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -30,27 +29,23 @@ public class StompSubscription // Constructors -------------------------------------------------- - public StompSubscription(String subID, String ack) - { + public StompSubscription(String subID, String ack) { this.subID = subID; this.ack = ack; } // Public -------------------------------------------------------- - public String getAck() - { + public String getAck() { return ack; } - public String getID() - { + public String getID() { return subID; } @Override - public String toString() - { + public String toString() { return "StompSubscription[id=" + subID + ", ack=" + ack + "]"; } diff --git a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompUtils.java b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompUtils.java index 0dc9d97193..e676431707 100644 --- a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompUtils.java +++ b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompUtils.java @@ -27,8 +27,8 @@ import org.apache.activemq.artemis.core.client.impl.ClientMessageImpl; import org.apache.activemq.artemis.core.message.impl.MessageInternal; import org.apache.activemq.artemis.core.server.impl.ServerMessageImpl; -public class StompUtils -{ +public class StompUtils { + // Constants ----------------------------------------------------- private static final String DEFAULT_MESSAGE_PRIORITY = "4"; @@ -36,22 +36,18 @@ public class StompUtils // Static -------------------------------------------------------- - public static void copyStandardHeadersFromFrameToMessage(StompFrame frame, ServerMessageImpl msg) throws Exception - { + public static void copyStandardHeadersFromFrameToMessage(StompFrame frame, ServerMessageImpl msg) throws Exception { Map headers = new HashMap(frame.getHeadersMap()); String priority = headers.remove(Stomp.Headers.Send.PRIORITY); - if (priority != null) - { + if (priority != null) { msg.setPriority(Byte.parseByte(priority)); } - else - { + else { msg.setPriority(Byte.parseByte(DEFAULT_MESSAGE_PRIORITY)); } String persistent = headers.remove(Stomp.Headers.Send.PERSISTENT); - if (persistent != null) - { + if (persistent != null) { msg.setDurable(Boolean.parseBoolean(persistent)); } @@ -60,64 +56,55 @@ public class StompUtils msg.putObjectProperty("JMSType", headers.remove(Stomp.Headers.Send.TYPE)); String groupID = headers.remove("JMSXGroupID"); - if (groupID != null) - { + if (groupID != null) { msg.putStringProperty(Message.HDR_GROUP_ID, SimpleString.toSimpleString(groupID)); } Object replyTo = headers.remove(Stomp.Headers.Send.REPLY_TO); - if (replyTo != null) - { + if (replyTo != null) { msg.putStringProperty(ClientMessageImpl.REPLYTO_HEADER_NAME, SimpleString.toSimpleString((String) replyTo)); } String expiration = headers.remove(Stomp.Headers.Send.EXPIRATION_TIME); - if (expiration != null) - { + if (expiration != null) { msg.setExpiration(Long.parseLong(expiration)); } // now the general headers - for (Entry entry : headers.entrySet()) - { + for (Entry entry : headers.entrySet()) { String name = entry.getKey(); Object value = entry.getValue(); msg.putObjectProperty(name, value); } } - public static void copyStandardHeadersFromMessageToFrame(MessageInternal message, StompFrame command, int deliveryCount) throws Exception - { + public static void copyStandardHeadersFromMessageToFrame(MessageInternal message, + StompFrame command, + int deliveryCount) throws Exception { command.addHeader(Stomp.Headers.Message.MESSAGE_ID, String.valueOf(message.getMessageID())); command.addHeader(Stomp.Headers.Message.DESTINATION, message.getAddress().toString()); - if (message.getObjectProperty("JMSCorrelationID") != null) - { + if (message.getObjectProperty("JMSCorrelationID") != null) { command.addHeader(Stomp.Headers.Message.CORRELATION_ID, message.getObjectProperty("JMSCorrelationID").toString()); } command.addHeader(Stomp.Headers.Message.EXPIRATION_TIME, "" + message.getExpiration()); command.addHeader(Stomp.Headers.Message.REDELIVERED, String.valueOf(deliveryCount > 1)); command.addHeader(Stomp.Headers.Message.PRORITY, "" + message.getPriority()); - if (message.getStringProperty(ClientMessageImpl.REPLYTO_HEADER_NAME) != null) - { - command.addHeader(Stomp.Headers.Message.REPLY_TO, - message.getStringProperty(ClientMessageImpl.REPLYTO_HEADER_NAME)); + if (message.getStringProperty(ClientMessageImpl.REPLYTO_HEADER_NAME) != null) { + command.addHeader(Stomp.Headers.Message.REPLY_TO, message.getStringProperty(ClientMessageImpl.REPLYTO_HEADER_NAME)); } command.addHeader(Stomp.Headers.Message.TIMESTAMP, "" + message.getTimestamp()); - if (message.getObjectProperty("JMSType") != null) - { + if (message.getObjectProperty("JMSType") != null) { command.addHeader(Stomp.Headers.Message.TYPE, message.getObjectProperty("JMSType").toString()); } // now let's add all the message headers Set names = message.getPropertyNames(); - for (SimpleString name : names) - { + for (SimpleString name : names) { String value = name.toString(); if (name.equals(ClientMessageImpl.REPLYTO_HEADER_NAME) || value.equals("JMSType") || value.equals("JMSCorrelationID") || - value.equals(Stomp.Headers.Message.DESTINATION)) - { + value.equals(Stomp.Headers.Message.DESTINATION)) { continue; } diff --git a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompVersions.java b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompVersions.java index 1be89cd14d..a2e340d767 100644 --- a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompVersions.java +++ b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompVersions.java @@ -19,21 +19,18 @@ package org.apache.activemq.artemis.core.protocol.stomp; /** * Stomp Spec Versions */ -public enum StompVersions -{ +public enum StompVersions { V1_0("1.0"), V1_1("1.1"), V1_2("1.2"); private String version; - private StompVersions(String ver) - { + private StompVersions(String ver) { this.version = ver; } - public String toString() - { + public String toString() { return this.version; } } diff --git a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/VersionedStompFrameHandler.java b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/VersionedStompFrameHandler.java index ccb4a1b0ec..1e0206a0a8 100644 --- a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/VersionedStompFrameHandler.java +++ b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/VersionedStompFrameHandler.java @@ -32,109 +32,85 @@ import org.apache.activemq.artemis.utils.DataConstants; import static org.apache.activemq.artemis.core.protocol.stomp.ActiveMQStompProtocolMessageBundle.BUNDLE; -public abstract class VersionedStompFrameHandler -{ +public abstract class VersionedStompFrameHandler { + protected StompConnection connection; protected StompDecoder decoder; - public static VersionedStompFrameHandler getHandler(StompConnection connection, StompVersions version) - { - if (version == StompVersions.V1_0) - { + public static VersionedStompFrameHandler getHandler(StompConnection connection, StompVersions version) { + if (version == StompVersions.V1_0) { return new StompFrameHandlerV10(connection); } - if (version == StompVersions.V1_1) - { + if (version == StompVersions.V1_1) { return new StompFrameHandlerV11(connection); } - if (version == StompVersions.V1_2) - { + if (version == StompVersions.V1_2) { return new StompFrameHandlerV12(connection); } return null; } - protected VersionedStompFrameHandler(StompConnection connection) - { + protected VersionedStompFrameHandler(StompConnection connection) { this.connection = connection; } - public StompFrame decode(ActiveMQBuffer buffer) throws ActiveMQStompException - { + public StompFrame decode(ActiveMQBuffer buffer) throws ActiveMQStompException { return decoder.decode(buffer); } - public boolean hasBytes() - { + public boolean hasBytes() { return decoder.hasBytes(); } - public StompDecoder getDecoder() - { + public StompDecoder getDecoder() { return decoder; } - public StompFrame handleFrame(StompFrame request) - { + public StompFrame handleFrame(StompFrame request) { StompFrame response = null; - if (Stomp.Commands.SEND.equals(request.getCommand())) - { + if (Stomp.Commands.SEND.equals(request.getCommand())) { response = onSend(request); } - else if (Stomp.Commands.ACK.equals(request.getCommand())) - { + else if (Stomp.Commands.ACK.equals(request.getCommand())) { response = onAck(request); } - else if (Stomp.Commands.NACK.equals(request.getCommand())) - { + else if (Stomp.Commands.NACK.equals(request.getCommand())) { response = onNack(request); } - else if (Stomp.Commands.BEGIN.equals(request.getCommand())) - { + else if (Stomp.Commands.BEGIN.equals(request.getCommand())) { response = onBegin(request); } - else if (Stomp.Commands.COMMIT.equals(request.getCommand())) - { + else if (Stomp.Commands.COMMIT.equals(request.getCommand())) { response = onCommit(request); } - else if (Stomp.Commands.ABORT.equals(request.getCommand())) - { + else if (Stomp.Commands.ABORT.equals(request.getCommand())) { response = onAbort(request); } - else if (Stomp.Commands.SUBSCRIBE.equals(request.getCommand())) - { + else if (Stomp.Commands.SUBSCRIBE.equals(request.getCommand())) { response = onSubscribe(request); } - else if (Stomp.Commands.UNSUBSCRIBE.equals(request.getCommand())) - { + else if (Stomp.Commands.UNSUBSCRIBE.equals(request.getCommand())) { response = onUnsubscribe(request); } - else if (Stomp.Commands.CONNECT.equals(request.getCommand())) - { + else if (Stomp.Commands.CONNECT.equals(request.getCommand())) { response = onConnect(request); } - else if (Stomp.Commands.STOMP.equals(request.getCommand())) - { + else if (Stomp.Commands.STOMP.equals(request.getCommand())) { response = onStomp(request); } - else if (Stomp.Commands.DISCONNECT.equals(request.getCommand())) - { + else if (Stomp.Commands.DISCONNECT.equals(request.getCommand())) { response = onDisconnect(request); } - else - { + else { response = onUnknown(request.getCommand()); } - if (response == null) - { + if (response == null) { response = postprocess(request); } - else - { - if (request.hasHeader(Stomp.Headers.RECEIPT_REQUESTED)) - { + else { + if (request.hasHeader(Stomp.Headers.RECEIPT_REQUESTED)) { response.addHeader(Stomp.Headers.Response.RECEIPT_ID, request.getHeader(Stomp.Headers.RECEIPT_REQUESTED)); } } @@ -156,49 +132,41 @@ public abstract class VersionedStompFrameHandler public abstract StompFrame createStompFrame(String command); - public StompFrame onUnknown(String command) - { + public StompFrame onUnknown(String command) { ActiveMQStompException error = BUNDLE.unknownCommand(command).setHandler(this); StompFrame response = error.getFrame(); return response; } - public StompFrame handleReceipt(String receiptID) - { + public StompFrame handleReceipt(String receiptID) { StompFrame receipt = createStompFrame(Stomp.Responses.RECEIPT); receipt.addHeader(Stomp.Headers.Response.RECEIPT_ID, receiptID); return receipt; } - public StompFrame onCommit(StompFrame request) - { + public StompFrame onCommit(StompFrame request) { StompFrame response = null; String txID = request.getHeader(Stomp.Headers.TRANSACTION); - if (txID == null) - { + if (txID == null) { ActiveMQStompException error = BUNDLE.needTxIDHeader().setHandler(this); response = error.getFrame(); return response; } - try - { + try { connection.commitTransaction(txID); } - catch (ActiveMQStompException e) - { + catch (ActiveMQStompException e) { response = e.getFrame(); } return response; } - public StompFrame onSend(StompFrame frame) - { + public StompFrame onSend(StompFrame frame) { StompFrame response = null; - try - { + try { connection.validate(); String destination = frame.getHeader(Stomp.Headers.Send.DESTINATION); checkDestination(destination); @@ -210,13 +178,11 @@ public abstract class VersionedStompFrameHandler message.setTimestamp(timestamp); message.setAddress(SimpleString.toSimpleString(destination)); StompUtils.copyStandardHeadersFromFrameToMessage(frame, message); - if (frame.hasHeader(Stomp.Headers.CONTENT_LENGTH)) - { + if (frame.hasHeader(Stomp.Headers.CONTENT_LENGTH)) { message.setType(Message.BYTES_TYPE); message.getBodyBuffer().writeBytes(frame.getBodyAsBytes()); } - else - { + else { message.setType(Message.TEXT_TYPE); String text = frame.getBody(); message.getBodyBuffer().writeNullableSimpleString(SimpleString.toSimpleString(text)); @@ -224,12 +190,10 @@ public abstract class VersionedStompFrameHandler connection.sendServerMessage(message, txID); } - catch (ActiveMQStompException e) - { + catch (ActiveMQStompException e) { response = e.getFrame(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQStompException error = BUNDLE.errorHandleSend(e).setHandler(this); response = error.getFrame(); } @@ -237,60 +201,49 @@ public abstract class VersionedStompFrameHandler return response; } - private void checkDestination(String destination) throws ActiveMQStompException - { + private void checkDestination(String destination) throws ActiveMQStompException { connection.checkDestination(destination); } - public StompFrame onBegin(StompFrame frame) - { + public StompFrame onBegin(StompFrame frame) { StompFrame response = null; String txID = frame.getHeader(Stomp.Headers.TRANSACTION); - if (txID == null) - { + if (txID == null) { ActiveMQStompException error = BUNDLE.beginTxNoID().setHandler(this); response = error.getFrame(); } - else - { - try - { + else { + try { connection.beginTransaction(txID); } - catch (ActiveMQStompException e) - { + catch (ActiveMQStompException e) { response = e.getFrame(); } } return response; } - public StompFrame onAbort(StompFrame request) - { + public StompFrame onAbort(StompFrame request) { StompFrame response = null; String txID = request.getHeader(Stomp.Headers.TRANSACTION); - if (txID == null) - { + if (txID == null) { ActiveMQStompException error = BUNDLE.abortTxNoID().setHandler(this); response = error.getFrame(); return response; } - try - { + try { connection.abortTransaction(txID); } - catch (ActiveMQStompException e) - { + catch (ActiveMQStompException e) { response = e.getFrame(); } return response; } - public StompFrame onSubscribe(StompFrame request) - { + public StompFrame onSubscribe(StompFrame request) { StompFrame response = null; String destination = request.getHeader(Stomp.Headers.Subscribe.DESTINATION); @@ -300,39 +253,31 @@ public abstract class VersionedStompFrameHandler String durableSubscriptionName = request.getHeader(Stomp.Headers.Subscribe.DURABLE_SUBSCRIBER_NAME); boolean noLocal = false; - if (request.hasHeader(Stomp.Headers.Subscribe.NO_LOCAL)) - { + if (request.hasHeader(Stomp.Headers.Subscribe.NO_LOCAL)) { noLocal = Boolean.parseBoolean(request.getHeader(Stomp.Headers.Subscribe.NO_LOCAL)); } - try - { + try { connection.subscribe(destination, selector, ack, id, durableSubscriptionName, noLocal); } - catch (ActiveMQStompException e) - { + catch (ActiveMQStompException e) { response = e.getFrame(); } return response; } - public StompFrame postprocess(StompFrame request) - { + public StompFrame postprocess(StompFrame request) { StompFrame response = null; - if (request.hasHeader(Stomp.Headers.RECEIPT_REQUESTED)) - { + if (request.hasHeader(Stomp.Headers.RECEIPT_REQUESTED)) { response = handleReceipt(request.getHeader(Stomp.Headers.RECEIPT_REQUESTED)); - if (request.getCommand().equals(Stomp.Commands.DISCONNECT)) - { + if (request.getCommand().equals(Stomp.Commands.DISCONNECT)) { response.setNeedsDisconnect(true); } } - else - { + else { //request null, disconnect if so. - if (request.getCommand().equals(Stomp.Commands.DISCONNECT)) - { + if (request.getCommand().equals(Stomp.Commands.DISCONNECT)) { this.connection.disconnect(false); } } @@ -340,50 +285,40 @@ public abstract class VersionedStompFrameHandler } public StompFrame createMessageFrame(ServerMessage serverMessage, - StompSubscription subscription, int deliveryCount) throws Exception - { + StompSubscription subscription, + int deliveryCount) throws Exception { StompFrame frame = createStompFrame(Stomp.Responses.MESSAGE); - if (subscription.getID() != null) - { - frame.addHeader(Stomp.Headers.Message.SUBSCRIPTION, - subscription.getID()); + if (subscription.getID() != null) { + frame.addHeader(Stomp.Headers.Message.SUBSCRIPTION, subscription.getID()); } ActiveMQBuffer buffer = serverMessage.getBodyBufferCopy(); - int bodyPos = serverMessage.getEndOfBodyPosition() == -1 ? buffer - .writerIndex() : serverMessage.getEndOfBodyPosition(); + int bodyPos = serverMessage.getEndOfBodyPosition() == -1 ? buffer.writerIndex() : serverMessage.getEndOfBodyPosition(); - buffer.readerIndex(MessageImpl.BUFFER_HEADER_SPACE - + DataConstants.SIZE_INT); + buffer.readerIndex(MessageImpl.BUFFER_HEADER_SPACE + DataConstants.SIZE_INT); int size = bodyPos - buffer.readerIndex(); byte[] data = new byte[size]; - if (serverMessage.containsProperty(Stomp.Headers.CONTENT_LENGTH) - || serverMessage.getType() == Message.BYTES_TYPE) - { + if (serverMessage.containsProperty(Stomp.Headers.CONTENT_LENGTH) || serverMessage.getType() == Message.BYTES_TYPE) { frame.addHeader(Headers.CONTENT_LENGTH, String.valueOf(data.length)); buffer.readBytes(data); } - else - { + else { SimpleString text = buffer.readNullableSimpleString(); - if (text != null) - { + if (text != null) { data = text.toString().getBytes(StandardCharsets.UTF_8); } - else - { + else { data = new byte[0]; } } frame.setByteBody(data); - StompUtils.copyStandardHeadersFromMessageToFrame(serverMessage, frame, - deliveryCount); + StompUtils.copyStandardHeadersFromMessageToFrame(serverMessage, frame, deliveryCount); return frame; } @@ -395,14 +330,12 @@ public abstract class VersionedStompFrameHandler * * @param existingHandler */ - public void initDecoder(VersionedStompFrameHandler existingHandler) - { + public void initDecoder(VersionedStompFrameHandler existingHandler) { throw BUNDLE.invalidCall(); } //sends an ERROR frame back to client if possible then close the connection - public void onError(ActiveMQStompException e) - { + public void onError(ActiveMQStompException e) { this.connection.sendFrame(e.getFrame()); connection.destroy(); } diff --git a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/v10/StompFrameHandlerV10.java b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/v10/StompFrameHandlerV10.java index 3f3ceda1ec..98fead7405 100644 --- a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/v10/StompFrameHandlerV10.java +++ b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/v10/StompFrameHandlerV10.java @@ -30,10 +30,9 @@ import org.apache.activemq.artemis.core.server.ActiveMQServerLogger; import static org.apache.activemq.artemis.core.protocol.stomp.ActiveMQStompProtocolMessageBundle.BUNDLE; -public class StompFrameHandlerV10 extends VersionedStompFrameHandler implements FrameEventListener -{ - public StompFrameHandlerV10(StompConnection connection) - { +public class StompFrameHandlerV10 extends VersionedStompFrameHandler implements FrameEventListener { + + public StompFrameHandlerV10(StompConnection connection) { super(connection); decoder = new StompDecoder(this); decoder.init(); @@ -41,8 +40,7 @@ public class StompFrameHandlerV10 extends VersionedStompFrameHandler implements } @Override - public StompFrame onConnect(StompFrame frame) - { + public StompFrame onConnect(StompFrame frame) { StompFrame response = null; Map headers = frame.getHeadersMap(); String login = headers.get(Stomp.Headers.Connect.LOGIN); @@ -50,27 +48,23 @@ public class StompFrameHandlerV10 extends VersionedStompFrameHandler implements String clientID = headers.get(Stomp.Headers.Connect.CLIENT_ID); String requestID = headers.get(Stomp.Headers.Connect.REQUEST_ID); - if (connection.validateUser(login, passcode)) - { + if (connection.validateUser(login, passcode)) { connection.setClientID(clientID); connection.setValid(true); response = new StompFrameV10(Stomp.Responses.CONNECTED); - if (frame.hasHeader(Stomp.Headers.ACCEPT_VERSION)) - { + if (frame.hasHeader(Stomp.Headers.ACCEPT_VERSION)) { response.addHeader(Stomp.Headers.Connected.VERSION, StompVersions.V1_0.toString()); } response.addHeader(Stomp.Headers.Connected.SESSION, connection.getID().toString()); - if (requestID != null) - { + if (requestID != null) { response.addHeader(Stomp.Headers.Connected.RESPONSE_ID, requestID); } } - else - { + else { //not valid response = new StompFrameV10(Stomp.Responses.ERROR); response.addHeader(Stomp.Headers.Error.MESSAGE, "Failed to connect"); @@ -80,28 +74,23 @@ public class StompFrameHandlerV10 extends VersionedStompFrameHandler implements } @Override - public StompFrame onDisconnect(StompFrame frame) - { + public StompFrame onDisconnect(StompFrame frame) { return null; } @Override - public StompFrame onUnsubscribe(StompFrame request) - { + public StompFrame onUnsubscribe(StompFrame request) { StompFrame response = null; String destination = request.getHeader(Stomp.Headers.Unsubscribe.DESTINATION); String id = request.getHeader(Stomp.Headers.Unsubscribe.ID); String durableSubscriberName = request.getHeader(Stomp.Headers.Unsubscribe.DURABLE_SUBSCRIBER_NAME); String subscriptionID = null; - if (id != null) - { + if (id != null) { subscriptionID = id; } - else - { - if (destination == null) - { + else { + if (destination == null) { ActiveMQStompException error = BUNDLE.needIDorDestination().setHandler(this); response = error.getFrame(); return response; @@ -109,36 +98,30 @@ public class StompFrameHandlerV10 extends VersionedStompFrameHandler implements subscriptionID = "subscription/" + destination; } - try - { + try { connection.unsubscribe(subscriptionID, durableSubscriberName); } - catch (ActiveMQStompException e) - { + catch (ActiveMQStompException e) { return e.getFrame(); } return response; } @Override - public StompFrame onAck(StompFrame request) - { + public StompFrame onAck(StompFrame request) { StompFrame response = null; String messageID = request.getHeader(Stomp.Headers.Ack.MESSAGE_ID); String txID = request.getHeader(Stomp.Headers.TRANSACTION); - if (txID != null) - { + if (txID != null) { ActiveMQServerLogger.LOGGER.stompTXAckNorSupported(); } - try - { + try { connection.acknowledge(messageID, null); } - catch (ActiveMQStompException e) - { + catch (ActiveMQStompException e) { response = e.getFrame(); } @@ -146,35 +129,29 @@ public class StompFrameHandlerV10 extends VersionedStompFrameHandler implements } @Override - public StompFrame onStomp(StompFrame request) - { + public StompFrame onStomp(StompFrame request) { return onUnknown(request.getCommand()); } @Override - public StompFrame onNack(StompFrame request) - { + public StompFrame onNack(StompFrame request) { return onUnknown(request.getCommand()); } @Override - public StompFrame createStompFrame(String command) - { + public StompFrame createStompFrame(String command) { return new StompFrameV10(command); } @Override - public void replySent(StompFrame reply) - { - if (reply.needsDisconnect()) - { + public void replySent(StompFrame reply) { + if (reply.needsDisconnect()) { connection.destroy(); } } @Override - public void requestAccepted(StompFrame request) - { + public void requestAccepted(StompFrame request) { // TODO Auto-generated method stub } diff --git a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/v10/StompFrameV10.java b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/v10/StompFrameV10.java index dfaa5b2863..6623f2469d 100644 --- a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/v10/StompFrameV10.java +++ b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/v10/StompFrameV10.java @@ -18,10 +18,9 @@ package org.apache.activemq.artemis.core.protocol.stomp.v10; import org.apache.activemq.artemis.core.protocol.stomp.StompFrame; -public class StompFrameV10 extends StompFrame -{ - public StompFrameV10(String command) - { +public class StompFrameV10 extends StompFrame { + + public StompFrameV10(String command) { super(command); } diff --git a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/v11/StompFrameHandlerV11.java b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/v11/StompFrameHandlerV11.java index fa6e2c231c..f606481ffc 100644 --- a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/v11/StompFrameHandlerV11.java +++ b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/v11/StompFrameHandlerV11.java @@ -31,14 +31,13 @@ import org.apache.activemq.artemis.core.server.ActiveMQServerLogger; import static org.apache.activemq.artemis.core.protocol.stomp.ActiveMQStompProtocolMessageBundle.BUNDLE; -public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements FrameEventListener -{ +public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements FrameEventListener { + protected static final char ESC_CHAR = '\\'; private HeartBeater heartBeater; - public StompFrameHandlerV11(StompConnection connection) - { + public StompFrameHandlerV11(StompConnection connection) { super(connection); connection.addStompEventListener(this); decoder = new StompDecoderV11(this); @@ -46,8 +45,7 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements } @Override - public StompFrame onConnect(StompFrame frame) - { + public StompFrame onConnect(StompFrame frame) { StompFrame response = null; Map headers = frame.getHeadersMap(); String login = headers.get(Stomp.Headers.Connect.LOGIN); @@ -55,31 +53,24 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements String clientID = headers.get(Stomp.Headers.Connect.CLIENT_ID); String requestID = headers.get(Stomp.Headers.Connect.REQUEST_ID); - try - { - if (connection.validateUser(login, passcode)) - { + try { + if (connection.validateUser(login, passcode)) { connection.setClientID(clientID); connection.setValid(true); response = this.createStompFrame(Stomp.Responses.CONNECTED); // version - response.addHeader(Stomp.Headers.Connected.VERSION, - connection.getVersion()); + response.addHeader(Stomp.Headers.Connected.VERSION, connection.getVersion()); // session - response.addHeader(Stomp.Headers.Connected.SESSION, connection - .getID().toString()); + response.addHeader(Stomp.Headers.Connected.SESSION, connection.getID().toString()); // server - response.addHeader(Stomp.Headers.Connected.SERVER, - connection.getActiveMQServerName()); + response.addHeader(Stomp.Headers.Connected.SERVER, connection.getActiveMQServerName()); - if (requestID != null) - { - response.addHeader(Stomp.Headers.Connected.RESPONSE_ID, - requestID); + if (requestID != null) { + response.addHeader(Stomp.Headers.Connected.RESPONSE_ID, requestID); } // heart-beat. We need to start after connected frame has been sent. @@ -87,21 +78,17 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements // connected frame. String heartBeat = headers.get(Stomp.Headers.Connect.HEART_BEAT); - if (heartBeat != null) - { + if (heartBeat != null) { handleHeartBeat(heartBeat); - if (heartBeater == null) - { + if (heartBeater == null) { response.addHeader(Stomp.Headers.Connected.HEART_BEAT, "0,0"); } - else - { + else { response.addHeader(Stomp.Headers.Connected.HEART_BEAT, heartBeater.getServerHeartBeatValue()); } } } - else - { + else { // not valid response = createStompFrame(Stomp.Responses.ERROR); response.setNeedsDisconnect(true); @@ -110,8 +97,7 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements response.setBody("The login account is not valid."); } } - catch (ActiveMQStompException e) - { + catch (ActiveMQStompException e) { response = e.getFrame(); } @@ -120,11 +106,9 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements //ping parameters, hard-code for now //the server can support min 20 milliseconds and receive ping at 100 milliseconds (20,100) - private void handleHeartBeat(String heartBeatHeader) throws ActiveMQStompException - { + private void handleHeartBeat(String heartBeatHeader) throws ActiveMQStompException { String[] params = heartBeatHeader.split(","); - if (params.length != 2) - { + if (params.length != 2) { throw new ActiveMQStompException(connection, "Incorrect heartbeat header " + heartBeatHeader); } @@ -133,24 +117,19 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements //client receive ping long minAcceptInterval = Long.valueOf(params[1]); - if ((minPingInterval != 0) || (minAcceptInterval != 0)) - { + if ((minPingInterval != 0) || (minAcceptInterval != 0)) { heartBeater = new HeartBeater(minPingInterval, minAcceptInterval); } } @Override - public StompFrame onDisconnect(StompFrame frame) - { - if (this.heartBeater != null) - { + public StompFrame onDisconnect(StompFrame frame) { + if (this.heartBeater != null) { heartBeater.shutdown(); - try - { + try { heartBeater.join(); } - catch (InterruptedException e) - { + catch (InterruptedException e) { ActiveMQServerLogger.LOGGER.errorOnStompHeartBeat(e); } } @@ -158,61 +137,51 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements } @Override - public StompFrame onUnsubscribe(StompFrame request) - { + public StompFrame onUnsubscribe(StompFrame request) { StompFrame response = null; //unsubscribe in 1.1 only needs id header String id = request.getHeader(Stomp.Headers.Unsubscribe.ID); String durableSubscriberName = request.getHeader(Stomp.Headers.Unsubscribe.DURABLE_SUBSCRIBER_NAME); String subscriptionID = null; - if (id != null) - { + if (id != null) { subscriptionID = id; } - else - { + else { response = BUNDLE.needSubscriptionID().setHandler(this).getFrame(); return response; } - try - { + try { connection.unsubscribe(subscriptionID, durableSubscriberName); } - catch (ActiveMQStompException e) - { + catch (ActiveMQStompException e) { response = e.getFrame(); } return response; } @Override - public StompFrame onAck(StompFrame request) - { + public StompFrame onAck(StompFrame request) { StompFrame response = null; String messageID = request.getHeader(Stomp.Headers.Ack.MESSAGE_ID); String txID = request.getHeader(Stomp.Headers.TRANSACTION); String subscriptionID = request.getHeader(Stomp.Headers.Ack.SUBSCRIPTION); - if (txID != null) - { + if (txID != null) { ActiveMQServerLogger.LOGGER.stompTXAckNorSupported(); } - if (subscriptionID == null) - { + if (subscriptionID == null) { response = BUNDLE.needSubscriptionID().setHandler(this).getFrame(); return response; } - try - { + try { connection.acknowledge(messageID, subscriptionID); } - catch (ActiveMQStompException e) - { + catch (ActiveMQStompException e) { response = e.getFrame(); } @@ -220,56 +189,45 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements } @Override - public StompFrame onStomp(StompFrame request) - { - if (!connection.isValid()) - { + public StompFrame onStomp(StompFrame request) { + if (!connection.isValid()) { return onConnect(request); } return null; } @Override - public StompFrame onNack(StompFrame request) - { + public StompFrame onNack(StompFrame request) { //this eventually means discard the message (it never be redelivered again). //we can consider supporting redeliver to a different sub. return onAck(request); } @Override - public void replySent(StompFrame reply) - { - if (reply.getCommand().equals(Stomp.Responses.CONNECTED)) - { + public void replySent(StompFrame reply) { + if (reply.getCommand().equals(Stomp.Responses.CONNECTED)) { //kick off the pinger startHeartBeat(); } - if (reply.needsDisconnect()) - { + if (reply.needsDisconnect()) { connection.disconnect(false); } - else - { + else { //update ping - if (heartBeater != null) - { + if (heartBeater != null) { heartBeater.pinged(); } } } - private void startHeartBeat() - { - if (heartBeater != null) - { + private void startHeartBeat() { + if (heartBeater != null) { heartBeater.start(); } } - public StompFrame createPingFrame() - { + public StompFrame createPingFrame() { StompFrame frame = createStompFrame(Stomp.Commands.STOMP); frame.setPing(true); return frame; @@ -281,8 +239,8 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements //interval, send a ping. //(b) accept ping: if server hasn't received any frame within // 2*serverAcceptPing, disconnect! - private class HeartBeater extends Thread - { + private class HeartBeater extends Thread { + private static final int MIN_SERVER_PING = 500; private static final int MIN_CLIENT_PING = 500; @@ -293,65 +251,52 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements AtomicLong lastAccepted = new AtomicLong(0); StompFrame pingFrame; - public HeartBeater(long clientPing, long clientAcceptPing) - { - if (clientPing != 0) - { + public HeartBeater(long clientPing, long clientAcceptPing) { + if (clientPing != 0) { serverAcceptPing = clientPing > MIN_CLIENT_PING ? clientPing : MIN_CLIENT_PING; } - if (clientAcceptPing != 0) - { + if (clientAcceptPing != 0) { serverPing = clientAcceptPing > MIN_SERVER_PING ? clientAcceptPing : MIN_SERVER_PING; } } - public synchronized void shutdown() - { + public synchronized void shutdown() { shutdown = true; this.notify(); } - public String getServerHeartBeatValue() - { + public String getServerHeartBeatValue() { return String.valueOf(serverPing) + "," + String.valueOf(serverAcceptPing); } - public void pinged() - { + public void pinged() { lastPingTime.set(System.currentTimeMillis()); } @Override - public void run() - { + public void run() { lastAccepted.set(System.currentTimeMillis()); pingFrame = createPingFrame(); - synchronized (this) - { - while (!shutdown) - { + synchronized (this) { + while (!shutdown) { long dur1 = 0; long dur2 = 0; - if (serverPing != 0) - { + if (serverPing != 0) { dur1 = System.currentTimeMillis() - lastPingTime.get(); - if (dur1 >= serverPing) - { + if (dur1 >= serverPing) { lastPingTime.set(System.currentTimeMillis()); connection.ping(pingFrame); dur1 = 0; } } - if (serverAcceptPing != 0) - { + if (serverAcceptPing != 0) { dur2 = System.currentTimeMillis() - lastAccepted.get(); - if (dur2 > (2 * serverAcceptPing)) - { + if (dur2 > (2 * serverAcceptPing)) { connection.disconnect(false); shutdown = true; break; @@ -361,82 +306,68 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements long waitTime1 = 0; long waitTime2 = 0; - if (serverPing > 0) - { + if (serverPing > 0) { waitTime1 = serverPing - dur1; } - if (serverAcceptPing > 0) - { + if (serverAcceptPing > 0) { waitTime2 = serverAcceptPing * 2 - dur2; } long waitTime = 10L; - if ((waitTime1 > 0) && (waitTime2 > 0)) - { + if ((waitTime1 > 0) && (waitTime2 > 0)) { waitTime = Math.min(waitTime1, waitTime2); } - else if (waitTime1 > 0) - { + else if (waitTime1 > 0) { waitTime = waitTime1; } - else if (waitTime2 > 0) - { + else if (waitTime2 > 0) { waitTime = waitTime2; } - try - { + try { this.wait(waitTime); } - catch (InterruptedException e) - { + catch (InterruptedException e) { } } } } - public void pingAccepted() - { + public void pingAccepted() { this.lastAccepted.set(System.currentTimeMillis()); } } @Override - public void requestAccepted(StompFrame request) - { - if (heartBeater != null) - { + public void requestAccepted(StompFrame request) { + if (heartBeater != null) { heartBeater.pingAccepted(); } } @Override - public StompFrame createStompFrame(String command) - { + public StompFrame createStompFrame(String command) { return new StompFrameV11(command); } @Override - public void initDecoder(VersionedStompFrameHandler existingHandler) - { + public void initDecoder(VersionedStompFrameHandler existingHandler) { decoder.init(existingHandler.getDecoder()); } - protected class StompDecoderV11 extends StompDecoder - { + protected class StompDecoderV11 extends StompDecoder { + protected boolean isEscaping = false; protected SimpleBytes holder = new SimpleBytes(1024); - public StompDecoderV11(StompFrameHandlerV11 handler) - { + public StompDecoderV11(StompFrameHandlerV11 handler) { super(handler); } @Override - public void init(StompDecoder decoder) - { + public void init(StompDecoder decoder) { this.data = decoder.data; this.workingBuffer = decoder.workingBuffer; this.pos = decoder.pos; @@ -444,16 +375,14 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements } @Override - public void init() - { + public void init() { super.init(); isEscaping = false; holder.reset(); } @Override - protected boolean parseCommand() throws ActiveMQStompException - { + protected boolean parseCommand() throws ActiveMQStompException { int offset = 0; boolean nextChar = false; @@ -463,45 +392,39 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements // next STOMP frame is read - we need to deal with this. // Besides, Stomp 1.2 allows for extra EOLs after NULL (i.e. // either "[\r]\n"s or "\n"s) - while (true) - { - if (workingBuffer[offset] == NEW_LINE) - { - if (heartBeater != null) - { + while (true) { + if (workingBuffer[offset] == NEW_LINE) { + if (heartBeater != null) { //client ping heartBeater.pingAccepted(); } nextChar = false; } - else if (workingBuffer[offset] == CR) - { - if (nextChar) throw BUNDLE.invalidTwoCRs().setHandler(handler); + else if (workingBuffer[offset] == CR) { + if (nextChar) + throw BUNDLE.invalidTwoCRs().setHandler(handler); nextChar = true; } - else - { + else { break; } offset++; - if (offset == data) return false; //no more bytes + if (offset == data) + return false; //no more bytes } - if (nextChar) - { + if (nextChar) { throw BUNDLE.badCRs().setHandler(handler); } //if some EOLs have been processed, drop those bytes before parsing command - if (offset > 0) - { + if (offset > 0) { System.arraycopy(workingBuffer, offset, workingBuffer, 0, data - offset); data = data - offset; offset = 0; } - if (data < 4) - { + if (data < 4) { // Need at least four bytes to identify the command // - up to 3 bytes for the command name + potentially another byte for a leading \n return false; @@ -509,24 +432,18 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements byte b = workingBuffer[offset]; - switch (b) - { - case A: - { - if (workingBuffer[offset + 1] == StompDecoder.B) - { - if (!tryIncrement(offset + COMMAND_ABORT_LENGTH + eolLen)) - { + switch (b) { + case A: { + if (workingBuffer[offset + 1] == StompDecoder.B) { + if (!tryIncrement(offset + COMMAND_ABORT_LENGTH + eolLen)) { return false; } // ABORT command = COMMAND_ABORT; } - else - { - if (!tryIncrement(offset + COMMAND_ACK_LENGTH + eolLen)) - { + else { + if (!tryIncrement(offset + COMMAND_ACK_LENGTH + eolLen)) { return false; } @@ -535,10 +452,8 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements } break; } - case B: - { - if (!tryIncrement(offset + COMMAND_BEGIN_LENGTH + eolLen)) - { + case B: { + if (!tryIncrement(offset + COMMAND_BEGIN_LENGTH + eolLen)) { return false; } @@ -547,12 +462,9 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements break; } - case C: - { - if (workingBuffer[offset + 2] == M) - { - if (!tryIncrement(offset + COMMAND_COMMIT_LENGTH + eolLen)) - { + case C: { + if (workingBuffer[offset + 2] == M) { + if (!tryIncrement(offset + COMMAND_COMMIT_LENGTH + eolLen)) { return false; } @@ -560,10 +472,8 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements command = COMMAND_COMMIT; } /**** added by meddy, 27 april 2011, handle header parser for reply to websocket protocol ****/ - else if (workingBuffer[offset + 7] == E) - { - if (!tryIncrement(offset + COMMAND_CONNECTED_LENGTH + eolLen)) - { + else if (workingBuffer[offset + 7] == E) { + if (!tryIncrement(offset + COMMAND_CONNECTED_LENGTH + eolLen)) { return false; } @@ -571,10 +481,8 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements command = COMMAND_CONNECTED; } /**** end ****/ - else - { - if (!tryIncrement(offset + COMMAND_CONNECT_LENGTH + eolLen)) - { + else { + if (!tryIncrement(offset + COMMAND_CONNECT_LENGTH + eolLen)) { return false; } @@ -583,10 +491,8 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements } break; } - case D: - { - if (!tryIncrement(offset + COMMAND_DISCONNECT_LENGTH + eolLen)) - { + case D: { + if (!tryIncrement(offset + COMMAND_DISCONNECT_LENGTH + eolLen)) { return false; } @@ -595,10 +501,8 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements break; } - case R: - { - if (!tryIncrement(offset + COMMAND_RECEIPT_LENGTH + eolLen)) - { + case R: { + if (!tryIncrement(offset + COMMAND_RECEIPT_LENGTH + eolLen)) { return false; } @@ -608,10 +512,8 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements break; } /**** added by meddy, 27 april 2011, handle header parser for reply to websocket protocol ****/ - case E: - { - if (!tryIncrement(offset + COMMAND_ERROR_LENGTH + eolLen)) - { + case E: { + if (!tryIncrement(offset + COMMAND_ERROR_LENGTH + eolLen)) { return false; } @@ -620,10 +522,8 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements break; } - case M: - { - if (!tryIncrement(offset + COMMAND_MESSAGE_LENGTH + eolLen)) - { + case M: { + if (!tryIncrement(offset + COMMAND_MESSAGE_LENGTH + eolLen)) { return false; } @@ -633,32 +533,25 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements break; } /**** end ****/ - case S: - { - if (workingBuffer[offset + 1] == E) - { - if (!tryIncrement(offset + COMMAND_SEND_LENGTH + eolLen)) - { + case S: { + if (workingBuffer[offset + 1] == E) { + if (!tryIncrement(offset + COMMAND_SEND_LENGTH + eolLen)) { return false; } // SEND command = COMMAND_SEND; } - else if (workingBuffer[offset + 1] == U) - { - if (!tryIncrement(offset + COMMAND_SUBSCRIBE_LENGTH + eolLen)) - { + else if (workingBuffer[offset + 1] == U) { + if (!tryIncrement(offset + COMMAND_SUBSCRIBE_LENGTH + eolLen)) { return false; } // SUBSCRIBE command = COMMAND_SUBSCRIBE; } - else - { - if (!tryIncrement(offset + StompDecoder.COMMAND_STOMP_LENGTH + eolLen)) - { + else { + if (!tryIncrement(offset + StompDecoder.COMMAND_STOMP_LENGTH + eolLen)) { return false; } @@ -667,10 +560,8 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements } break; } - case U: - { - if (!tryIncrement(offset + COMMAND_UNSUBSCRIBE_LENGTH + eolLen)) - { + case U: { + if (!tryIncrement(offset + COMMAND_UNSUBSCRIBE_LENGTH + eolLen)) { return false; } @@ -679,18 +570,15 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements break; } - case N: - { - if (!tryIncrement(offset + COMMAND_NACK_LENGTH + eolLen)) - { + case N: { + if (!tryIncrement(offset + COMMAND_NACK_LENGTH + eolLen)) { return false; } //NACK command = COMMAND_NACK; break; } - default: - { + default: { throwInvalid(); } } @@ -700,46 +588,35 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements return true; } - protected void checkEol() throws ActiveMQStompException - { - if (workingBuffer[pos - 1] != NEW_LINE) - { + protected void checkEol() throws ActiveMQStompException { + if (workingBuffer[pos - 1] != NEW_LINE) { throwInvalid(); } } @Override - protected boolean parseHeaders() throws ActiveMQStompException - { - + protected boolean parseHeaders() throws ActiveMQStompException { outer: - while (true) - { + while (true) { byte b = workingBuffer[pos++]; - switch (b) - { + switch (b) { //escaping - case ESC_CHAR: - { - if (isEscaping) - { + case ESC_CHAR: { + if (isEscaping) { //this is a backslash holder.append(b); isEscaping = false; } - else - { + else { //begin escaping isEscaping = true; } break; } - case HEADER_SEPARATOR: - { - if (inHeaderName) - { + case HEADER_SEPARATOR: { + if (inHeaderName) { headerName = holder.getString(); holder.reset(); @@ -753,36 +630,28 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements break; } - case StompDecoder.LN: - { - if (isEscaping) - { + case StompDecoder.LN: { + if (isEscaping) { holder.append(StompDecoder.NEW_LINE); isEscaping = false; } - else - { + else { holder.append(b); } break; } - case StompDecoder.c: - { - if (isEscaping) - { + case StompDecoder.c: { + if (isEscaping) { holder.append(StompDecoder.HEADER_SEPARATOR); isEscaping = false; } - else - { + else { holder.append(b); } break; } - case StompDecoder.NEW_LINE: - { - if (whiteSpaceOnly) - { + case StompDecoder.NEW_LINE: { + if (whiteSpaceOnly) { // Headers are terminated by a blank line readingHeaders = false; @@ -794,13 +663,11 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements headers.put(headerName, headerValue); - if (headerName.equals(Stomp.Headers.CONTENT_LENGTH)) - { + if (headerName.equals(Stomp.Headers.CONTENT_LENGTH)) { contentLength = Integer.parseInt(headerValue); } - if (headerName.equals(Stomp.Headers.CONTENT_TYPE)) - { + if (headerName.equals(Stomp.Headers.CONTENT_TYPE)) { contentType = headerValue; } @@ -812,8 +679,7 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements break; } - default: - { + default: { whiteSpaceOnly = false; headerValueWhitespace = false; @@ -821,8 +687,7 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements holder.append(b); } } - if (pos == data) - { + if (pos == data) { // Run out of data return false; } @@ -830,18 +695,14 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements return true; } - protected StompFrame parseBody() throws ActiveMQStompException - { + protected StompFrame parseBody() throws ActiveMQStompException { byte[] content = null; - if (contentLength != -1) - { - if (pos + contentLength + 1 > data) - { + if (contentLength != -1) { + if (pos + contentLength + 1 > data) { // Need more bytes } - else - { + else { content = new byte[contentLength]; System.arraycopy(workingBuffer, pos, content, 0, contentLength); @@ -849,33 +710,26 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements pos += contentLength; //drain all the rest - if (bodyStart == -1) - { + if (bodyStart == -1) { bodyStart = pos; } - while (pos < data) - { - if (workingBuffer[pos++] == 0) - { + while (pos < data) { + if (workingBuffer[pos++] == 0) { break; } } } } - else - { + else { // Need to scan for terminating NUL - if (bodyStart == -1) - { + if (bodyStart == -1) { bodyStart = pos; } - while (pos < data) - { - if (workingBuffer[pos++] == 0) - { + while (pos < data) { + if (workingBuffer[pos++] == 0) { content = new byte[pos - bodyStart - 1]; System.arraycopy(workingBuffer, bodyStart, content, 0, content.length); @@ -885,11 +739,10 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements } } - if (content != null) - { - if (data > pos) - { - if (workingBuffer[pos] == NEW_LINE) pos++; + if (content != null) { + if (data > pos) { + if (workingBuffer[pos] == NEW_LINE) + pos++; if (data > pos) // More data still in the buffer from the next packet @@ -906,8 +759,7 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements return ret; } - else - { + else { return null; } } diff --git a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/v11/StompFrameV11.java b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/v11/StompFrameV11.java index 783c8454c9..e14d3a6051 100644 --- a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/v11/StompFrameV11.java +++ b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/v11/StompFrameV11.java @@ -23,26 +23,22 @@ import java.util.Map; import org.apache.activemq.artemis.core.protocol.stomp.Stomp; import org.apache.activemq.artemis.core.protocol.stomp.StompFrame; -public class StompFrameV11 extends StompFrame -{ +public class StompFrameV11 extends StompFrame { + //stomp 1.1 talks about repetitive headers. protected final List
    allHeaders = new ArrayList
    (); - public StompFrameV11(String command, Map headers, byte[] content) - { + public StompFrameV11(String command, Map headers, byte[] content) { super(command, headers, content); } - public StompFrameV11(String command) - { + public StompFrameV11(String command) { super(command); } @Override - protected void encodeHeaders(StringBuilder head) - { - for (Header h : allHeaders) - { + protected void encodeHeaders(StringBuilder head) { + for (Header h : allHeaders) { head.append(h.getEncodedKey()); head.append(Stomp.Headers.SEPARATOR); head.append(h.getEncodedValue()); @@ -51,15 +47,12 @@ public class StompFrameV11 extends StompFrame } @Override - public void addHeader(String key, String val) - { - if (!headers.containsKey(key)) - { + public void addHeader(String key, String val) { + if (!headers.containsKey(key)) { headers.put(key, val); allHeaders.add(new Header(key, val)); } - else if (!key.equals(Stomp.Headers.CONTENT_LENGTH)) - { + else if (!key.equals(Stomp.Headers.CONTENT_LENGTH)) { allHeaders.add(new Header(key, val)); } } diff --git a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/v12/StompFrameHandlerV12.java b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/v12/StompFrameHandlerV12.java index 7146f1ffe2..0aeafe4de4 100644 --- a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/v12/StompFrameHandlerV12.java +++ b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/v12/StompFrameHandlerV12.java @@ -30,29 +30,26 @@ import org.apache.activemq.artemis.core.server.ServerMessage; import static org.apache.activemq.artemis.core.protocol.stomp.ActiveMQStompProtocolMessageBundle.BUNDLE; -public class StompFrameHandlerV12 extends StompFrameHandlerV11 implements FrameEventListener -{ - public StompFrameHandlerV12(StompConnection connection) - { +public class StompFrameHandlerV12 extends StompFrameHandlerV11 implements FrameEventListener { + + public StompFrameHandlerV12(StompConnection connection) { super(connection); decoder = new StompDecoderV12(this); decoder.init(); } @Override - public StompFrame createStompFrame(String command) - { + public StompFrame createStompFrame(String command) { return new StompFrameV12(command); } @Override public StompFrame createMessageFrame(ServerMessage serverMessage, - StompSubscription subscription, int deliveryCount) throws Exception - { + StompSubscription subscription, + int deliveryCount) throws Exception { StompFrame frame = super.createMessageFrame(serverMessage, subscription, deliveryCount); - if (!subscription.getAck().equals(Stomp.Headers.Subscribe.AckModeValues.AUTO)) - { + if (!subscription.getAck().equals(Stomp.Headers.Subscribe.AckModeValues.AUTO)) { frame.addHeader(Stomp.Headers.Message.ACK, String.valueOf(serverMessage.getMessageID())); } @@ -64,42 +61,36 @@ public class StompFrameHandlerV12 extends StompFrameHandlerV11 implements FrameE * here we use id = messageID */ @Override - public StompFrame onAck(StompFrame request) - { + public StompFrame onAck(StompFrame request) { StompFrame response = null; String messageID = request.getHeader(Stomp.Headers.Ack.ID); String txID = request.getHeader(Stomp.Headers.TRANSACTION); - if (txID != null) - { + if (txID != null) { ActiveMQServerLogger.LOGGER.stompTXAckNorSupported(); } - if (messageID == null) - { + if (messageID == null) { ActiveMQStompException error = BUNDLE.noIDInAck().setHandler(connection.getFrameHandler()); return error.getFrame(); } - try - { + try { connection.acknowledge(messageID, null); } - catch (ActiveMQStompException e) - { + catch (ActiveMQStompException e) { response = e.getFrame(); } return response; } - protected class StompDecoderV12 extends StompDecoderV11 - { + protected class StompDecoderV12 extends StompDecoderV11 { + protected boolean nextEOLChar = false; - public StompDecoderV12(StompFrameHandlerV12 handler) - { + public StompDecoderV12(StompFrameHandlerV12 handler) { super(handler); //1.2 allows '\r\n' @@ -107,33 +98,27 @@ public class StompFrameHandlerV12 extends StompFrameHandlerV11 implements FrameE } @Override - public void init() - { + public void init() { super.init(); nextEOLChar = false; } @Override - protected void checkEol() throws ActiveMQStompException - { + protected void checkEol() throws ActiveMQStompException { //either \n or \r\n - if (workingBuffer[pos - 2] == NEW_LINE) - { + if (workingBuffer[pos - 2] == NEW_LINE) { pos--; } - else if (workingBuffer[pos - 2] != CR) - { + else if (workingBuffer[pos - 2] != CR) { throwInvalid(); } - else if (workingBuffer[pos - 1] != NEW_LINE) - { + else if (workingBuffer[pos - 1] != NEW_LINE) { throwInvalid(); } } @Override - public void init(StompDecoder decoder) - { + public void init(StompDecoder decoder) { this.data = decoder.data; this.workingBuffer = decoder.workingBuffer; this.pos = decoder.pos; @@ -141,35 +126,27 @@ public class StompFrameHandlerV12 extends StompFrameHandlerV11 implements FrameE } @Override - protected boolean parseHeaders() throws ActiveMQStompException - { + protected boolean parseHeaders() throws ActiveMQStompException { outer: - while (true) - { + while (true) { byte b = workingBuffer[pos++]; - switch (b) - { + switch (b) { //escaping - case ESC_CHAR: - { - if (isEscaping) - { + case ESC_CHAR: { + if (isEscaping) { //this is a backslash holder.append(b); isEscaping = false; } - else - { + else { //begin escaping isEscaping = true; } break; } - case HEADER_SEPARATOR: - { - if (inHeaderName) - { + case HEADER_SEPARATOR: { + if (inHeaderName) { headerName = holder.getString(); holder.reset(); @@ -183,59 +160,46 @@ public class StompFrameHandlerV12 extends StompFrameHandlerV11 implements FrameE break; } - case LN: - { - if (isEscaping) - { + case LN: { + if (isEscaping) { holder.append(NEW_LINE); isEscaping = false; } - else - { + else { holder.append(b); } break; } - case RT: - { - if (isEscaping) - { + case RT: { + if (isEscaping) { holder.append(CR); isEscaping = false; } - else - { + else { holder.append(b); } break; } - case CR: - { - if (nextEOLChar) - { + case CR: { + if (nextEOLChar) { throw BUNDLE.invalidTwoCRs().setHandler(handler); } nextEOLChar = true; break; } - case StompDecoder.c: - { - if (isEscaping) - { + case StompDecoder.c: { + if (isEscaping) { holder.append(StompDecoder.HEADER_SEPARATOR); isEscaping = false; } - else - { + else { holder.append(b); } break; } - case NEW_LINE: - { + case NEW_LINE: { nextEOLChar = false; - if (whiteSpaceOnly) - { + if (whiteSpaceOnly) { // Headers are terminated by a blank line readingHeaders = false; break outer; @@ -244,18 +208,15 @@ public class StompFrameHandlerV12 extends StompFrameHandlerV11 implements FrameE String headerValue = holder.getString(); holder.reset(); - if (!headers.containsKey(headerName)) - { + if (!headers.containsKey(headerName)) { headers.put(headerName, headerValue); } - if (headerName.equals(Stomp.Headers.CONTENT_LENGTH)) - { + if (headerName.equals(Stomp.Headers.CONTENT_LENGTH)) { contentLength = Integer.parseInt(headerValue); } - if (headerName.equals(Stomp.Headers.CONTENT_TYPE)) - { + if (headerName.equals(Stomp.Headers.CONTENT_TYPE)) { contentType = headerValue; } @@ -267,8 +228,7 @@ public class StompFrameHandlerV12 extends StompFrameHandlerV11 implements FrameE break; } - default: - { + default: { whiteSpaceOnly = false; headerValueWhitespace = false; @@ -276,8 +236,7 @@ public class StompFrameHandlerV12 extends StompFrameHandlerV11 implements FrameE holder.append(b); } } - if (pos == data) - { + if (pos == data) { // Run out of data return false; } @@ -285,18 +244,14 @@ public class StompFrameHandlerV12 extends StompFrameHandlerV11 implements FrameE return true; } - protected StompFrame parseBody() throws ActiveMQStompException - { + protected StompFrame parseBody() throws ActiveMQStompException { byte[] content = null; - if (contentLength != -1) - { - if (pos + contentLength + 1 > data) - { + if (contentLength != -1) { + if (pos + contentLength + 1 > data) { // Need more bytes } - else - { + else { content = new byte[contentLength]; System.arraycopy(workingBuffer, pos, content, 0, contentLength); @@ -304,33 +259,26 @@ public class StompFrameHandlerV12 extends StompFrameHandlerV11 implements FrameE pos += contentLength; //drain all the rest - if (bodyStart == -1) - { + if (bodyStart == -1) { bodyStart = pos; } - while (pos < data) - { - if (workingBuffer[pos++] == 0) - { + while (pos < data) { + if (workingBuffer[pos++] == 0) { break; } } } } - else - { + else { // Need to scan for terminating NUL - if (bodyStart == -1) - { + if (bodyStart == -1) { bodyStart = pos; } - while (pos < data) - { - if (workingBuffer[pos++] == 0) - { + while (pos < data) { + if (workingBuffer[pos++] == 0) { content = new byte[pos - bodyStart - 1]; System.arraycopy(workingBuffer, bodyStart, content, 0, content.length); @@ -340,11 +288,10 @@ public class StompFrameHandlerV12 extends StompFrameHandlerV11 implements FrameE } } - if (content != null) - { - if (data > pos) - { - if (workingBuffer[pos] == NEW_LINE) pos++; + if (content != null) { + if (data > pos) { + if (workingBuffer[pos] == NEW_LINE) + pos++; if (data > pos) // More data still in the buffer from the next packet @@ -361,8 +308,7 @@ public class StompFrameHandlerV12 extends StompFrameHandlerV11 implements FrameE return ret; } - else - { + else { return null; } } diff --git a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/v12/StompFrameV12.java b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/v12/StompFrameV12.java index fdf8a7037b..471311d9ff 100644 --- a/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/v12/StompFrameV12.java +++ b/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/v12/StompFrameV12.java @@ -20,15 +20,13 @@ import java.util.Map; import org.apache.activemq.artemis.core.protocol.stomp.v11.StompFrameV11; -public class StompFrameV12 extends StompFrameV11 -{ - public StompFrameV12(String command, Map headers, byte[] content) - { +public class StompFrameV12 extends StompFrameV11 { + + public StompFrameV12(String command, Map headers, byte[] content) { super(command, headers, content); } - public StompFrameV12(String command) - { + public StompFrameV12(String command) { super(command); } } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRABundle.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRABundle.java index 7d9c02da74..622c2ec527 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRABundle.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRABundle.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.ra; - import org.apache.activemq.artemis.api.core.ActiveMQIllegalStateException; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.Message; @@ -34,9 +33,11 @@ import javax.resource.NotSupportedException; * so 159000 to 159999 */ @MessageBundle(projectCode = "AMQ") -public interface ActiveMQRABundle -{ - /** Error message for strict behaviour */ +public interface ActiveMQRABundle { + + /** + * Error message for strict behaviour + */ String ISE = "This method is not applicable inside the application server. See the JEE spec, e.g. JEE 7 Section 6.7"; ActiveMQRABundle BUNDLE = Messages.getBundle(ActiveMQRABundle.class); diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRABytesMessage.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRABytesMessage.java index 46d88804e5..26ce7fb77d 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRABytesMessage.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRABytesMessage.java @@ -21,436 +21,409 @@ import java.util.Arrays; import javax.jms.BytesMessage; import javax.jms.JMSException; - /** * A wrapper for a message */ -public class ActiveMQRABytesMessage extends ActiveMQRAMessage implements BytesMessage -{ - /** Whether trace is enabled */ +public class ActiveMQRABytesMessage extends ActiveMQRAMessage implements BytesMessage { + + /** + * Whether trace is enabled + */ private static boolean trace = ActiveMQRALogger.LOGGER.isTraceEnabled(); /** * Create a new wrapper + * * @param message the message * @param session the session */ - public ActiveMQRABytesMessage(final BytesMessage message, final ActiveMQRASession session) - { + public ActiveMQRABytesMessage(final BytesMessage message, final ActiveMQRASession session) { super(message, session); - if (ActiveMQRABytesMessage.trace) - { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("constructor(" + message + ", " + session + ")"); } } /** * Get body length + * * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public long getBodyLength() throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public long getBodyLength() throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("getBodyLength()"); } - return ((BytesMessage)message).getBodyLength(); + return ((BytesMessage) message).getBodyLength(); } /** * Read + * * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public boolean readBoolean() throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public boolean readBoolean() throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("readBoolean()"); } - return ((BytesMessage)message).readBoolean(); + return ((BytesMessage) message).readBoolean(); } /** * Read + * * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public byte readByte() throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public byte readByte() throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("readByte()"); } - return ((BytesMessage)message).readByte(); + return ((BytesMessage) message).readByte(); } /** * Read - * @param value The value + * + * @param value The value * @param length The length * @return The result - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public int readBytes(final byte[] value, final int length) throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public int readBytes(final byte[] value, final int length) throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("readBytes(" + Arrays.toString(value) + ", " + length + ")"); } - return ((BytesMessage)message).readBytes(value, length); + return ((BytesMessage) message).readBytes(value, length); } /** * Read + * * @param value The value * @return The result - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public int readBytes(final byte[] value) throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public int readBytes(final byte[] value) throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("readBytes(" + Arrays.toString(value) + ")"); } - return ((BytesMessage)message).readBytes(value); + return ((BytesMessage) message).readBytes(value); } /** * Read + * * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public char readChar() throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public char readChar() throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("readChar()"); } - return ((BytesMessage)message).readChar(); + return ((BytesMessage) message).readChar(); } /** * Read + * * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public double readDouble() throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public double readDouble() throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("readDouble()"); } - return ((BytesMessage)message).readDouble(); + return ((BytesMessage) message).readDouble(); } /** * Read + * * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public float readFloat() throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public float readFloat() throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("readFloat()"); } - return ((BytesMessage)message).readFloat(); + return ((BytesMessage) message).readFloat(); } /** * Read + * * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public int readInt() throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public int readInt() throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("readInt()"); } - return ((BytesMessage)message).readInt(); + return ((BytesMessage) message).readInt(); } /** * Read + * * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public long readLong() throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public long readLong() throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("readLong()"); } - return ((BytesMessage)message).readLong(); + return ((BytesMessage) message).readLong(); } /** * Read + * * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public short readShort() throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public short readShort() throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("readShort()"); } - return ((BytesMessage)message).readShort(); + return ((BytesMessage) message).readShort(); } /** * Read + * * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public int readUnsignedByte() throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public int readUnsignedByte() throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("readUnsignedByte()"); } - return ((BytesMessage)message).readUnsignedByte(); + return ((BytesMessage) message).readUnsignedByte(); } /** * Read + * * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public int readUnsignedShort() throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public int readUnsignedShort() throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("readUnsignedShort()"); } - return ((BytesMessage)message).readUnsignedShort(); + return ((BytesMessage) message).readUnsignedShort(); } /** * Read + * * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public String readUTF() throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public String readUTF() throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("readUTF()"); } - return ((BytesMessage)message).readUTF(); + return ((BytesMessage) message).readUTF(); } /** * Reset - * @exception JMSException Thrown if an error occurs + * + * @throws JMSException Thrown if an error occurs */ - public void reset() throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public void reset() throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("reset()"); } - ((BytesMessage)message).reset(); + ((BytesMessage) message).reset(); } /** * Write + * * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void writeBoolean(final boolean value) throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public void writeBoolean(final boolean value) throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("writeBoolean(" + value + ")"); } - ((BytesMessage)message).writeBoolean(value); + ((BytesMessage) message).writeBoolean(value); } /** * Write + * * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void writeByte(final byte value) throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public void writeByte(final byte value) throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("writeByte(" + value + ")"); } - ((BytesMessage)message).writeByte(value); + ((BytesMessage) message).writeByte(value); } /** * Write - * @param value The value + * + * @param value The value * @param offset The offset * @param length The length - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void writeBytes(final byte[] value, final int offset, final int length) throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public void writeBytes(final byte[] value, final int offset, final int length) throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("writeBytes(" + Arrays.toString(value) + ", " + offset + ", " + length + ")"); } - ((BytesMessage)message).writeBytes(value, offset, length); + ((BytesMessage) message).writeBytes(value, offset, length); } /** * Write + * * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void writeBytes(final byte[] value) throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public void writeBytes(final byte[] value) throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("writeBytes(" + Arrays.toString(value) + ")"); } - ((BytesMessage)message).writeBytes(value); + ((BytesMessage) message).writeBytes(value); } /** * Write + * * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void writeChar(final char value) throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public void writeChar(final char value) throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("writeChar(" + value + ")"); } - ((BytesMessage)message).writeChar(value); + ((BytesMessage) message).writeChar(value); } /** * Write + * * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void writeDouble(final double value) throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public void writeDouble(final double value) throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("writeDouble(" + value + ")"); } - ((BytesMessage)message).writeDouble(value); + ((BytesMessage) message).writeDouble(value); } /** * Write + * * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void writeFloat(final float value) throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public void writeFloat(final float value) throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("writeFloat(" + value + ")"); } - ((BytesMessage)message).writeFloat(value); + ((BytesMessage) message).writeFloat(value); } /** * Write + * * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void writeInt(final int value) throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public void writeInt(final int value) throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("writeInt(" + value + ")"); } - ((BytesMessage)message).writeInt(value); + ((BytesMessage) message).writeInt(value); } /** * Write + * * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void writeLong(final long value) throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public void writeLong(final long value) throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("writeLong(" + value + ")"); } - ((BytesMessage)message).writeLong(value); + ((BytesMessage) message).writeLong(value); } /** * Write + * * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void writeObject(final Object value) throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public void writeObject(final Object value) throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("writeObject(" + value + ")"); } - ((BytesMessage)message).writeObject(value); + ((BytesMessage) message).writeObject(value); } /** * Write + * * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void writeShort(final short value) throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public void writeShort(final short value) throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("writeShort(" + value + ")"); } - ((BytesMessage)message).writeShort(value); + ((BytesMessage) message).writeShort(value); } /** * Write + * * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void writeUTF(final String value) throws JMSException - { - if (ActiveMQRABytesMessage.trace) - { + public void writeUTF(final String value) throws JMSException { + if (ActiveMQRABytesMessage.trace) { ActiveMQRALogger.LOGGER.trace("writeUTF(" + value + ")"); } - ((BytesMessage)message).writeUTF(value); + ((BytesMessage) message).writeUTF(value); } } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAConnectionFactory.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAConnectionFactory.java index 9c084d2f4c..fdbaec9813 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAConnectionFactory.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAConnectionFactory.java @@ -27,9 +27,8 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; /** * An aggregate interface for the JMS connection factories */ -public interface ActiveMQRAConnectionFactory extends XAQueueConnectionFactory, - XATopicConnectionFactory, Serializable, Referenceable -{ +public interface ActiveMQRAConnectionFactory extends XAQueueConnectionFactory, XATopicConnectionFactory, Serializable, Referenceable { + /** * Connection factory capable of handling connections */ diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAConnectionFactoryImpl.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAConnectionFactoryImpl.java index 679ae1f14e..65078c3ee4 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAConnectionFactoryImpl.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAConnectionFactoryImpl.java @@ -41,8 +41,8 @@ import org.apache.activemq.artemis.jms.referenceable.SerializableObjectRefAddr; /** * The connection factory */ -public class ActiveMQRAConnectionFactoryImpl implements ActiveMQRAConnectionFactory -{ +public class ActiveMQRAConnectionFactoryImpl implements ActiveMQRAConnectionFactory { + /** * Serial version UID */ @@ -70,31 +70,25 @@ public class ActiveMQRAConnectionFactoryImpl implements ActiveMQRAConnectionFact * @param mcf The managed connection factory * @param cm The connection manager */ - public ActiveMQRAConnectionFactoryImpl(final ActiveMQRAManagedConnectionFactory mcf, final ConnectionManager cm) - { - if (ActiveMQRAConnectionFactoryImpl.trace) - { + public ActiveMQRAConnectionFactoryImpl(final ActiveMQRAManagedConnectionFactory mcf, final ConnectionManager cm) { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("constructor(" + mcf + ", " + cm + ")"); } this.mcf = mcf; - if (cm == null) - { + if (cm == null) { // This is standalone usage, no appserver this.cm = new ActiveMQRAConnectionManager(); - if (ActiveMQRAConnectionFactoryImpl.trace) - { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("Created new ConnectionManager=" + this.cm); } } - else - { + else { this.cm = cm; } - if (ActiveMQRAConnectionFactoryImpl.trace) - { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("Using ManagedConnectionFactory=" + mcf + ", ConnectionManager=" + cm); } } @@ -104,10 +98,8 @@ public class ActiveMQRAConnectionFactoryImpl implements ActiveMQRAConnectionFact * * @param reference The reference */ - public void setReference(final Reference reference) - { - if (ActiveMQRAConnectionFactoryImpl.trace) - { + public void setReference(final Reference reference) { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("setReference(" + reference + ")"); } @@ -119,23 +111,15 @@ public class ActiveMQRAConnectionFactoryImpl implements ActiveMQRAConnectionFact * * @return The reference */ - public Reference getReference() - { - if (ActiveMQRAConnectionFactoryImpl.trace) - { + public Reference getReference() { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("getReference()"); } - if (reference == null) - { - try - { - reference = new Reference(this.getClass().getCanonicalName(), - new SerializableObjectRefAddr("ActiveMQ-CF", this), - ConnectionFactoryObjectFactory.class.getCanonicalName(), - null); + if (reference == null) { + try { + reference = new Reference(this.getClass().getCanonicalName(), new SerializableObjectRefAddr("ActiveMQ-CF", this), ConnectionFactoryObjectFactory.class.getCanonicalName(), null); } - catch (NamingException e) - { + catch (NamingException e) { ActiveMQRALogger.LOGGER.errorCreatingReference(e); } } @@ -150,20 +134,14 @@ public class ActiveMQRAConnectionFactoryImpl implements ActiveMQRAConnectionFact * @return The connection * @throws JMSException Thrown if the operation fails */ - public QueueConnection createQueueConnection() throws JMSException - { - if (ActiveMQRAConnectionFactoryImpl.trace) - { + public QueueConnection createQueueConnection() throws JMSException { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createQueueConnection()"); } - ActiveMQRASessionFactoryImpl s = new ActiveMQRASessionFactoryImpl(mcf, - cm, - getResourceAdapter().getTM(), - ActiveMQRAConnectionFactory.QUEUE_CONNECTION); + ActiveMQRASessionFactoryImpl s = new ActiveMQRASessionFactoryImpl(mcf, cm, getResourceAdapter().getTM(), ActiveMQRAConnectionFactory.QUEUE_CONNECTION); - if (ActiveMQRAConnectionFactoryImpl.trace) - { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("Created queue connection: " + s); } @@ -178,24 +156,18 @@ public class ActiveMQRAConnectionFactoryImpl implements ActiveMQRAConnectionFact * @return The connection * @throws JMSException Thrown if the operation fails */ - public QueueConnection createQueueConnection(final String userName, final String password) throws JMSException - { - if (ActiveMQRAConnectionFactoryImpl.trace) - { + public QueueConnection createQueueConnection(final String userName, final String password) throws JMSException { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createQueueConnection(" + userName + ", ****)"); } - ActiveMQRASessionFactoryImpl s = new ActiveMQRASessionFactoryImpl(mcf, - cm, - getResourceAdapter().getTM(), - ActiveMQRAConnectionFactory.QUEUE_CONNECTION); + ActiveMQRASessionFactoryImpl s = new ActiveMQRASessionFactoryImpl(mcf, cm, getResourceAdapter().getTM(), ActiveMQRAConnectionFactory.QUEUE_CONNECTION); s.setUserName(userName); s.setPassword(password); validateUser(s); - if (ActiveMQRAConnectionFactoryImpl.trace) - { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("Created queue connection: " + s); } @@ -208,20 +180,14 @@ public class ActiveMQRAConnectionFactoryImpl implements ActiveMQRAConnectionFact * @return The connection * @throws JMSException Thrown if the operation fails */ - public TopicConnection createTopicConnection() throws JMSException - { - if (ActiveMQRAConnectionFactoryImpl.trace) - { + public TopicConnection createTopicConnection() throws JMSException { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createTopicConnection()"); } - ActiveMQRASessionFactoryImpl s = new ActiveMQRASessionFactoryImpl(mcf, - cm, - getResourceAdapter().getTM(), - ActiveMQRAConnectionFactory.TOPIC_CONNECTION); + ActiveMQRASessionFactoryImpl s = new ActiveMQRASessionFactoryImpl(mcf, cm, getResourceAdapter().getTM(), ActiveMQRAConnectionFactory.TOPIC_CONNECTION); - if (ActiveMQRAConnectionFactoryImpl.trace) - { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("Created topic connection: " + s); } @@ -236,23 +202,17 @@ public class ActiveMQRAConnectionFactoryImpl implements ActiveMQRAConnectionFact * @return The connection * @throws JMSException Thrown if the operation fails */ - public TopicConnection createTopicConnection(final String userName, final String password) throws JMSException - { - if (ActiveMQRAConnectionFactoryImpl.trace) - { + public TopicConnection createTopicConnection(final String userName, final String password) throws JMSException { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createTopicConnection(" + userName + ", ****)"); } - ActiveMQRASessionFactoryImpl s = new ActiveMQRASessionFactoryImpl(mcf, - cm, - getResourceAdapter().getTM(), - ActiveMQRAConnectionFactory.TOPIC_CONNECTION); + ActiveMQRASessionFactoryImpl s = new ActiveMQRASessionFactoryImpl(mcf, cm, getResourceAdapter().getTM(), ActiveMQRAConnectionFactory.TOPIC_CONNECTION); s.setUserName(userName); s.setPassword(password); validateUser(s); - if (ActiveMQRAConnectionFactoryImpl.trace) - { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("Created topic connection: " + s); } @@ -265,17 +225,14 @@ public class ActiveMQRAConnectionFactoryImpl implements ActiveMQRAConnectionFact * @return The connection * @throws JMSException Thrown if the operation fails */ - public Connection createConnection() throws JMSException - { - if (ActiveMQRAConnectionFactoryImpl.trace) - { + public Connection createConnection() throws JMSException { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createConnection()"); } ActiveMQRASessionFactoryImpl s = new ActiveMQRASessionFactoryImpl(mcf, cm, getResourceAdapter().getTM(), ActiveMQRAConnectionFactory.CONNECTION); - if (ActiveMQRAConnectionFactoryImpl.trace) - { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("Created connection: " + s); } @@ -290,10 +247,8 @@ public class ActiveMQRAConnectionFactoryImpl implements ActiveMQRAConnectionFact * @return The connection * @throws JMSException Thrown if the operation fails */ - public Connection createConnection(final String userName, final String password) throws JMSException - { - if (ActiveMQRAConnectionFactoryImpl.trace) - { + public Connection createConnection(final String userName, final String password) throws JMSException { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createConnection(" + userName + ", ****)"); } @@ -303,8 +258,7 @@ public class ActiveMQRAConnectionFactoryImpl implements ActiveMQRAConnectionFact validateUser(s); - if (ActiveMQRAConnectionFactoryImpl.trace) - { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("Created connection: " + s); } @@ -317,20 +271,14 @@ public class ActiveMQRAConnectionFactoryImpl implements ActiveMQRAConnectionFact * @return The connection * @throws JMSException Thrown if the operation fails */ - public XAQueueConnection createXAQueueConnection() throws JMSException - { - if (ActiveMQRAConnectionFactoryImpl.trace) - { + public XAQueueConnection createXAQueueConnection() throws JMSException { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createXAQueueConnection()"); } - ActiveMQRASessionFactoryImpl s = new ActiveMQRASessionFactoryImpl(mcf, - cm, - getResourceAdapter().getTM(), - ActiveMQRAConnectionFactory.XA_QUEUE_CONNECTION); + ActiveMQRASessionFactoryImpl s = new ActiveMQRASessionFactoryImpl(mcf, cm, getResourceAdapter().getTM(), ActiveMQRAConnectionFactory.XA_QUEUE_CONNECTION); - if (ActiveMQRAConnectionFactoryImpl.trace) - { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("Created queue connection: " + s); } @@ -345,23 +293,17 @@ public class ActiveMQRAConnectionFactoryImpl implements ActiveMQRAConnectionFact * @return The connection * @throws JMSException Thrown if the operation fails */ - public XAQueueConnection createXAQueueConnection(final String userName, final String password) throws JMSException - { - if (ActiveMQRAConnectionFactoryImpl.trace) - { + public XAQueueConnection createXAQueueConnection(final String userName, final String password) throws JMSException { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createXAQueueConnection(" + userName + ", ****)"); } - ActiveMQRASessionFactoryImpl s = new ActiveMQRASessionFactoryImpl(mcf, - cm, - getResourceAdapter().getTM(), - ActiveMQRAConnectionFactory.XA_QUEUE_CONNECTION); + ActiveMQRASessionFactoryImpl s = new ActiveMQRASessionFactoryImpl(mcf, cm, getResourceAdapter().getTM(), ActiveMQRAConnectionFactory.XA_QUEUE_CONNECTION); s.setUserName(userName); s.setPassword(password); validateUser(s); - if (ActiveMQRAConnectionFactoryImpl.trace) - { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("Created queue connection: " + s); } @@ -374,20 +316,14 @@ public class ActiveMQRAConnectionFactoryImpl implements ActiveMQRAConnectionFact * @return The connection * @throws JMSException Thrown if the operation fails */ - public XATopicConnection createXATopicConnection() throws JMSException - { - if (ActiveMQRAConnectionFactoryImpl.trace) - { + public XATopicConnection createXATopicConnection() throws JMSException { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createXATopicConnection()"); } - ActiveMQRASessionFactoryImpl s = new ActiveMQRASessionFactoryImpl(mcf, - cm, - getResourceAdapter().getTM(), - ActiveMQRAConnectionFactory.XA_TOPIC_CONNECTION); + ActiveMQRASessionFactoryImpl s = new ActiveMQRASessionFactoryImpl(mcf, cm, getResourceAdapter().getTM(), ActiveMQRAConnectionFactory.XA_TOPIC_CONNECTION); - if (ActiveMQRAConnectionFactoryImpl.trace) - { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("Created topic connection: " + s); } @@ -402,23 +338,17 @@ public class ActiveMQRAConnectionFactoryImpl implements ActiveMQRAConnectionFact * @return The connection * @throws JMSException Thrown if the operation fails */ - public XATopicConnection createXATopicConnection(final String userName, final String password) throws JMSException - { - if (ActiveMQRAConnectionFactoryImpl.trace) - { + public XATopicConnection createXATopicConnection(final String userName, final String password) throws JMSException { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createXATopicConnection(" + userName + ", ****)"); } - ActiveMQRASessionFactoryImpl s = new ActiveMQRASessionFactoryImpl(mcf, - cm, - getResourceAdapter().getTM(), - ActiveMQRAConnectionFactory.XA_TOPIC_CONNECTION); + ActiveMQRASessionFactoryImpl s = new ActiveMQRASessionFactoryImpl(mcf, cm, getResourceAdapter().getTM(), ActiveMQRAConnectionFactory.XA_TOPIC_CONNECTION); s.setUserName(userName); s.setPassword(password); validateUser(s); - if (ActiveMQRAConnectionFactoryImpl.trace) - { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("Created topic connection: " + s); } @@ -431,17 +361,14 @@ public class ActiveMQRAConnectionFactoryImpl implements ActiveMQRAConnectionFact * @return The connection * @throws JMSException Thrown if the operation fails */ - public XAConnection createXAConnection() throws JMSException - { - if (ActiveMQRAConnectionFactoryImpl.trace) - { + public XAConnection createXAConnection() throws JMSException { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createXAConnection()"); } ActiveMQRASessionFactoryImpl s = new ActiveMQRASessionFactoryImpl(mcf, cm, getResourceAdapter().getTM(), ActiveMQRAConnectionFactory.XA_CONNECTION); - if (ActiveMQRAConnectionFactoryImpl.trace) - { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("Created connection: " + s); } @@ -456,10 +383,8 @@ public class ActiveMQRAConnectionFactoryImpl implements ActiveMQRAConnectionFact * @return The connection * @throws JMSException Thrown if the operation fails */ - public XAConnection createXAConnection(final String userName, final String password) throws JMSException - { - if (ActiveMQRAConnectionFactoryImpl.trace) - { + public XAConnection createXAConnection(final String userName, final String password) throws JMSException { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createXAConnection(" + userName + ", ****)"); } @@ -468,8 +393,7 @@ public class ActiveMQRAConnectionFactoryImpl implements ActiveMQRAConnectionFact s.setPassword(password); validateUser(s); - if (ActiveMQRAConnectionFactoryImpl.trace) - { + if (ActiveMQRAConnectionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("Created connection: " + s); } @@ -477,36 +401,30 @@ public class ActiveMQRAConnectionFactoryImpl implements ActiveMQRAConnectionFact } @Override - public JMSContext createContext() - { + public JMSContext createContext() { return createContext(null, null); } @Override - public JMSContext createContext(String userName, String password) - { + public JMSContext createContext(String userName, String password) { return createContext(userName, password, Session.AUTO_ACKNOWLEDGE); } @Override - public JMSContext createContext(String userName, String password, int sessionMode) - { + public JMSContext createContext(String userName, String password, int sessionMode) { @SuppressWarnings("resource") ActiveMQRASessionFactoryImpl conn = new ActiveMQRASessionFactoryImpl(mcf, cm, getResourceAdapter().getTM(), ActiveMQRAConnectionFactory.CONNECTION); conn.setUserName(userName); conn.setPassword(password); - try - { + try { validateUser(conn); } - catch (JMSSecurityException e) - { + catch (JMSSecurityException e) { JMSSecurityRuntimeException e2 = new JMSSecurityRuntimeException(e.getMessage()); e2.initCause(e); throw e2; } - catch (JMSException e) - { + catch (JMSException e) { JMSRuntimeException e2 = new JMSRuntimeException(e.getMessage()); e2.initCause(e); throw e2; @@ -515,35 +433,29 @@ public class ActiveMQRAConnectionFactoryImpl implements ActiveMQRAConnectionFact } @Override - public JMSContext createContext(int sessionMode) - { + public JMSContext createContext(int sessionMode) { return createContext(null, null, sessionMode); } @Override - public XAJMSContext createXAContext() - { + public XAJMSContext createXAContext() { return createXAContext(null, null); } @Override - public XAJMSContext createXAContext(String userName, String password) - { + public XAJMSContext createXAContext(String userName, String password) { ActiveMQRASessionFactoryImpl conn = new ActiveMQRASessionFactoryImpl(mcf, cm, getResourceAdapter().getTM(), ActiveMQRAConnectionFactory.XA_CONNECTION); conn.setUserName(userName); conn.setPassword(password); - try - { + try { validateUser(conn); } - catch (JMSSecurityException e) - { + catch (JMSSecurityException e) { JMSSecurityRuntimeException e2 = new JMSSecurityRuntimeException(e.getMessage()); e2.initCause(e); throw e2; } - catch (JMSException e) - { + catch (JMSException e) { JMSRuntimeException e2 = new JMSRuntimeException(e.getMessage()); e2.initCause(e); throw e2; @@ -551,21 +463,18 @@ public class ActiveMQRAConnectionFactoryImpl implements ActiveMQRAConnectionFact return conn.createXAContext(); } - private void validateUser(ActiveMQRASessionFactoryImpl s) throws JMSException - { + private void validateUser(ActiveMQRASessionFactoryImpl s) throws JMSException { Session session = s.createSession(); session.close(); } @Override - public ActiveMQConnectionFactory getDefaultFactory() throws ResourceException - { + public ActiveMQConnectionFactory getDefaultFactory() throws ResourceException { return ((ActiveMQResourceAdapter) mcf.getResourceAdapter()).getDefaultActiveMQConnectionFactory(); } @Override - public ActiveMQResourceAdapter getResourceAdapter() - { + public ActiveMQResourceAdapter getResourceAdapter() { return (ActiveMQResourceAdapter) mcf.getResourceAdapter(); } } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAConnectionManager.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAConnectionManager.java index 75401dbcdc..e9784aa184 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAConnectionManager.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAConnectionManager.java @@ -24,24 +24,25 @@ import javax.resource.spi.ManagedConnectionFactory; import org.apache.activemq.artemis.utils.ConcurrentHashSet; - /** * The connection manager used in non-managed environments. */ -public class ActiveMQRAConnectionManager implements ConnectionManager -{ - /** Serial version UID */ +public class ActiveMQRAConnectionManager implements ConnectionManager { + + /** + * Serial version UID + */ static final long serialVersionUID = 4409118162975011014L; - /** Trace enabled */ + /** + * Trace enabled + */ private static boolean trace = ActiveMQRALogger.LOGGER.isTraceEnabled(); /** * Constructor */ - public ActiveMQRAConnectionManager() - { - if (ActiveMQRAConnectionManager.trace) - { + public ActiveMQRAConnectionManager() { + if (ActiveMQRAConnectionManager.trace) { ActiveMQRALogger.LOGGER.trace("constructor()"); } } @@ -50,23 +51,22 @@ public class ActiveMQRAConnectionManager implements ConnectionManager /** * Allocates a connection - * @param mcf The managed connection factory + * + * @param mcf The managed connection factory * @param cxRequestInfo The connection request information * @return The connection - * @exception ResourceException Thrown if there is a problem obtaining the connection + * @throws ResourceException Thrown if there is a problem obtaining the connection */ - public Object allocateConnection(final ManagedConnectionFactory mcf, final ConnectionRequestInfo cxRequestInfo) throws ResourceException - { - if (ActiveMQRAConnectionManager.trace) - { + public Object allocateConnection(final ManagedConnectionFactory mcf, + final ConnectionRequestInfo cxRequestInfo) throws ResourceException { + if (ActiveMQRAConnectionManager.trace) { ActiveMQRALogger.LOGGER.trace("allocateConnection(" + mcf + ", " + cxRequestInfo + ")"); } ManagedConnection mc = mcf.createManagedConnection(null, cxRequestInfo); Object c = mc.getConnection(null, cxRequestInfo); - if (ActiveMQRAConnectionManager.trace) - { + if (ActiveMQRAConnectionManager.trace) { ActiveMQRALogger.LOGGER.trace("Allocated connection: " + c + ", with managed connection: " + mc); } @@ -74,16 +74,12 @@ public class ActiveMQRAConnectionManager implements ConnectionManager return c; } - public void stop() - { - for (ManagedConnection conn : connections) - { - try - { + public void stop() { + for (ManagedConnection conn : connections) { + try { conn.destroy(); } - catch (Throwable e) - { + catch (Throwable e) { } } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAConnectionMetaData.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAConnectionMetaData.java index 5411ca6ea8..0b9251ac96 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAConnectionMetaData.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAConnectionMetaData.java @@ -21,34 +21,32 @@ import java.util.Vector; import javax.jms.ConnectionMetaData; - /** * This class implements javax.jms.ConnectionMetaData */ -public class ActiveMQRAConnectionMetaData implements ConnectionMetaData -{ - /** Trace enabled */ +public class ActiveMQRAConnectionMetaData implements ConnectionMetaData { + + /** + * Trace enabled + */ private static boolean trace = ActiveMQRALogger.LOGGER.isTraceEnabled(); /** * Constructor */ - public ActiveMQRAConnectionMetaData() - { - if (ActiveMQRAConnectionMetaData.trace) - { + public ActiveMQRAConnectionMetaData() { + if (ActiveMQRAConnectionMetaData.trace) { ActiveMQRALogger.LOGGER.trace("constructor()"); } } /** * Get the JMS version + * * @return The version */ - public String getJMSVersion() - { - if (ActiveMQRAConnectionMetaData.trace) - { + public String getJMSVersion() { + if (ActiveMQRAConnectionMetaData.trace) { ActiveMQRALogger.LOGGER.trace("getJMSVersion()"); } @@ -57,12 +55,11 @@ public class ActiveMQRAConnectionMetaData implements ConnectionMetaData /** * Get the JMS major version + * * @return The major version */ - public int getJMSMajorVersion() - { - if (ActiveMQRAConnectionMetaData.trace) - { + public int getJMSMajorVersion() { + if (ActiveMQRAConnectionMetaData.trace) { ActiveMQRALogger.LOGGER.trace("getJMSMajorVersion()"); } @@ -71,12 +68,11 @@ public class ActiveMQRAConnectionMetaData implements ConnectionMetaData /** * Get the JMS minor version + * * @return The minor version */ - public int getJMSMinorVersion() - { - if (ActiveMQRAConnectionMetaData.trace) - { + public int getJMSMinorVersion() { + if (ActiveMQRAConnectionMetaData.trace) { ActiveMQRALogger.LOGGER.trace("getJMSMinorVersion()"); } @@ -85,12 +81,11 @@ public class ActiveMQRAConnectionMetaData implements ConnectionMetaData /** * Get the JMS provider name + * * @return The name */ - public String getJMSProviderName() - { - if (ActiveMQRAConnectionMetaData.trace) - { + public String getJMSProviderName() { + if (ActiveMQRAConnectionMetaData.trace) { ActiveMQRALogger.LOGGER.trace("getJMSProviderName()"); } @@ -99,12 +94,11 @@ public class ActiveMQRAConnectionMetaData implements ConnectionMetaData /** * Get the provider version + * * @return The version */ - public String getProviderVersion() - { - if (ActiveMQRAConnectionMetaData.trace) - { + public String getProviderVersion() { + if (ActiveMQRAConnectionMetaData.trace) { ActiveMQRALogger.LOGGER.trace("getJMSProviderName()"); } @@ -113,12 +107,11 @@ public class ActiveMQRAConnectionMetaData implements ConnectionMetaData /** * Get the provider major version + * * @return The version */ - public int getProviderMajorVersion() - { - if (ActiveMQRAConnectionMetaData.trace) - { + public int getProviderMajorVersion() { + if (ActiveMQRAConnectionMetaData.trace) { ActiveMQRALogger.LOGGER.trace("getProviderMajorVersion()"); } @@ -127,12 +120,11 @@ public class ActiveMQRAConnectionMetaData implements ConnectionMetaData /** * Get the provider minor version + * * @return The version */ - public int getProviderMinorVersion() - { - if (ActiveMQRAConnectionMetaData.trace) - { + public int getProviderMinorVersion() { + if (ActiveMQRAConnectionMetaData.trace) { ActiveMQRALogger.LOGGER.trace("getProviderMinorVersion()"); } @@ -141,10 +133,10 @@ public class ActiveMQRAConnectionMetaData implements ConnectionMetaData /** * Get the JMS XPropertyNames + * * @return The names */ - public Enumeration getJMSXPropertyNames() - { + public Enumeration getJMSXPropertyNames() { Vector v = new Vector(); v.add("JMSXGroupID"); v.add("JMSXGroupSeq"); diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAConnectionRequestInfo.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAConnectionRequestInfo.java index 909a0117ab..97350ff09f 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAConnectionRequestInfo.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAConnectionRequestInfo.java @@ -19,42 +19,54 @@ package org.apache.activemq.artemis.ra; import javax.jms.Session; import javax.resource.spi.ConnectionRequestInfo; - /** * Connection request information */ -public class ActiveMQRAConnectionRequestInfo implements ConnectionRequestInfo -{ - /** Trace enabled */ +public class ActiveMQRAConnectionRequestInfo implements ConnectionRequestInfo { + + /** + * Trace enabled + */ private static boolean trace = ActiveMQRALogger.LOGGER.isTraceEnabled(); - /** The user name */ + /** + * The user name + */ private String userName; - /** The password */ + /** + * The password + */ private String password; - /** The client id */ + /** + * The client id + */ private String clientID; - /** The type */ + /** + * The type + */ private final int type; - /** Use transactions */ + /** + * Use transactions + */ private final boolean transacted; - /** The acknowledge mode */ + /** + * The acknowledge mode + */ private final int acknowledgeMode; /** * Constructor + * * @param prop The resource adapter properties * @param type The connection type */ - public ActiveMQRAConnectionRequestInfo(final ActiveMQRAProperties prop, final int type) - { - if (ActiveMQRAConnectionRequestInfo.trace) - { + public ActiveMQRAConnectionRequestInfo(final ActiveMQRAProperties prop, final int type) { + if (ActiveMQRAConnectionRequestInfo.trace) { ActiveMQRALogger.LOGGER.trace("constructor(" + prop + ")"); } @@ -68,20 +80,19 @@ public class ActiveMQRAConnectionRequestInfo implements ConnectionRequestInfo /** * Constructor - * @param transacted Use transactions + * + * @param transacted Use transactions * @param acknowledgeMode The acknowledge mode - * @param type The connection type + * @param type The connection type */ - public ActiveMQRAConnectionRequestInfo(final boolean transacted, final int acknowledgeMode, final int type) - { - if (ActiveMQRAConnectionRequestInfo.trace) - { + public ActiveMQRAConnectionRequestInfo(final boolean transacted, final int acknowledgeMode, final int type) { + if (ActiveMQRAConnectionRequestInfo.trace) { ActiveMQRALogger.LOGGER.trace("constructor(" + transacted + - ", " + - acknowledgeMode + - ", " + - type + - ")"); + ", " + + acknowledgeMode + + ", " + + type + + ")"); } this.transacted = transacted; @@ -91,37 +102,32 @@ public class ActiveMQRAConnectionRequestInfo implements ConnectionRequestInfo /** * Fill in default values if they are missing + * * @param prop The resource adapter properties */ - public void setDefaults(final ActiveMQRAProperties prop) - { - if (ActiveMQRAConnectionRequestInfo.trace) - { + public void setDefaults(final ActiveMQRAProperties prop) { + if (ActiveMQRAConnectionRequestInfo.trace) { ActiveMQRALogger.LOGGER.trace("setDefaults(" + prop + ")"); } - if (userName == null) - { + if (userName == null) { userName = prop.getUserName(); } - if (password == null) - { + if (password == null) { password = prop.getPassword(); } - if (clientID == null) - { + if (clientID == null) { clientID = prop.getClientID(); } } /** * Get the user name + * * @return The value */ - public String getUserName() - { - if (ActiveMQRAConnectionRequestInfo.trace) - { + public String getUserName() { + if (ActiveMQRAConnectionRequestInfo.trace) { ActiveMQRALogger.LOGGER.trace("getUserName()"); } @@ -130,12 +136,11 @@ public class ActiveMQRAConnectionRequestInfo implements ConnectionRequestInfo /** * Set the user name + * * @param userName The value */ - public void setUserName(final String userName) - { - if (ActiveMQRAConnectionRequestInfo.trace) - { + public void setUserName(final String userName) { + if (ActiveMQRAConnectionRequestInfo.trace) { ActiveMQRALogger.LOGGER.trace("setUserName(" + userName + ")"); } @@ -144,12 +149,11 @@ public class ActiveMQRAConnectionRequestInfo implements ConnectionRequestInfo /** * Get the password + * * @return The value */ - public String getPassword() - { - if (ActiveMQRAConnectionRequestInfo.trace) - { + public String getPassword() { + if (ActiveMQRAConnectionRequestInfo.trace) { ActiveMQRALogger.LOGGER.trace("getPassword()"); } @@ -158,12 +162,11 @@ public class ActiveMQRAConnectionRequestInfo implements ConnectionRequestInfo /** * Set the password + * * @param password The value */ - public void setPassword(final String password) - { - if (ActiveMQRAConnectionRequestInfo.trace) - { + public void setPassword(final String password) { + if (ActiveMQRAConnectionRequestInfo.trace) { ActiveMQRALogger.LOGGER.trace("setPassword(****)"); } @@ -172,12 +175,11 @@ public class ActiveMQRAConnectionRequestInfo implements ConnectionRequestInfo /** * Get the client id + * * @return The value */ - public String getClientID() - { - if (ActiveMQRAConnectionRequestInfo.trace) - { + public String getClientID() { + if (ActiveMQRAConnectionRequestInfo.trace) { ActiveMQRALogger.LOGGER.trace("getClientID()"); } @@ -186,12 +188,11 @@ public class ActiveMQRAConnectionRequestInfo implements ConnectionRequestInfo /** * Set the client id + * * @param clientID The value */ - public void setClientID(final String clientID) - { - if (ActiveMQRAConnectionRequestInfo.trace) - { + public void setClientID(final String clientID) { + if (ActiveMQRAConnectionRequestInfo.trace) { ActiveMQRALogger.LOGGER.trace("setClientID(" + clientID + ")"); } @@ -200,12 +201,11 @@ public class ActiveMQRAConnectionRequestInfo implements ConnectionRequestInfo /** * Get the connection type + * * @return The type */ - public int getType() - { - if (ActiveMQRAConnectionRequestInfo.trace) - { + public int getType() { + if (ActiveMQRAConnectionRequestInfo.trace) { ActiveMQRALogger.LOGGER.trace("getType()"); } @@ -214,12 +214,11 @@ public class ActiveMQRAConnectionRequestInfo implements ConnectionRequestInfo /** * Use transactions + * * @return True if transacted; otherwise false */ - public boolean isTransacted() - { - if (ActiveMQRAConnectionRequestInfo.trace) - { + public boolean isTransacted() { + if (ActiveMQRAConnectionRequestInfo.trace) { ActiveMQRALogger.LOGGER.trace("isTransacted() " + transacted); } @@ -228,12 +227,11 @@ public class ActiveMQRAConnectionRequestInfo implements ConnectionRequestInfo /** * Get the acknowledge mode + * * @return The mode */ - public int getAcknowledgeMode() - { - if (ActiveMQRAConnectionRequestInfo.trace) - { + public int getAcknowledgeMode() { + if (ActiveMQRAConnectionRequestInfo.trace) { ActiveMQRALogger.LOGGER.trace("getAcknowledgeMode()"); } @@ -242,46 +240,41 @@ public class ActiveMQRAConnectionRequestInfo implements ConnectionRequestInfo /** * Indicates whether some other object is "equal to" this one. + * * @param obj Object with which to compare * @return True if this object is the same as the obj argument; false otherwise. */ @Override - public boolean equals(final Object obj) - { - if (ActiveMQRAConnectionRequestInfo.trace) - { + public boolean equals(final Object obj) { + if (ActiveMQRAConnectionRequestInfo.trace) { ActiveMQRALogger.LOGGER.trace("equals(" + obj + ")"); } - if (obj == null) - { + if (obj == null) { return false; } - if (obj instanceof ActiveMQRAConnectionRequestInfo) - { - ActiveMQRAConnectionRequestInfo you = (ActiveMQRAConnectionRequestInfo)obj; + if (obj instanceof ActiveMQRAConnectionRequestInfo) { + ActiveMQRAConnectionRequestInfo you = (ActiveMQRAConnectionRequestInfo) obj; return ActiveMQRaUtils.compare(userName, you.getUserName()) && ActiveMQRaUtils.compare(password, you.getPassword()) && - ActiveMQRaUtils.compare(clientID, you.getClientID()) && - type == you.getType() && - transacted == you.isTransacted() && - acknowledgeMode == you.getAcknowledgeMode(); + ActiveMQRaUtils.compare(clientID, you.getClientID()) && + type == you.getType() && + transacted == you.isTransacted() && + acknowledgeMode == you.getAcknowledgeMode(); } - else - { + else { return false; } } /** * Return the hash code for the object + * * @return The hash code */ @Override - public int hashCode() - { - if (ActiveMQRAConnectionRequestInfo.trace) - { + public int hashCode() { + if (ActiveMQRAConnectionRequestInfo.trace) { ActiveMQRALogger.LOGGER.trace("hashCode()"); } @@ -297,8 +290,7 @@ public class ActiveMQRAConnectionRequestInfo implements ConnectionRequestInfo } @Override - public String toString() - { + public String toString() { return "ActiveMQRAConnectionRequestInfo[type=" + type + ", transacted=" + transacted + ", acknowledgeMode=" + acknowledgeMode + ", clientID=" + clientID + ", userName=" + userName + ", password=****]"; diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRACredential.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRACredential.java index 6170dd4c74..d6eccc790b 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRACredential.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRACredential.java @@ -27,42 +27,44 @@ import javax.resource.spi.SecurityException; import javax.resource.spi.security.PasswordCredential; import javax.security.auth.Subject; - /** * Credential information */ -public class ActiveMQRACredential implements Serializable -{ - /** Serial version UID */ +public class ActiveMQRACredential implements Serializable { + + /** + * Serial version UID + */ static final long serialVersionUID = 210476602237497193L; private static boolean trace = ActiveMQRALogger.LOGGER.isTraceEnabled(); - /** The user name */ + /** + * The user name + */ private String userName; - /** The password */ + /** + * The password + */ private String password; /** * Private constructor */ - private ActiveMQRACredential() - { - if (ActiveMQRACredential.trace) - { + private ActiveMQRACredential() { + if (ActiveMQRACredential.trace) { ActiveMQRALogger.LOGGER.trace("constructor()"); } } /** * Get the user name + * * @return The value */ - public String getUserName() - { - if (ActiveMQRACredential.trace) - { + public String getUserName() { + if (ActiveMQRACredential.trace) { ActiveMQRALogger.LOGGER.trace("getUserName()"); } @@ -71,12 +73,11 @@ public class ActiveMQRACredential implements Serializable /** * Set the user name + * * @param userName The value */ - private void setUserName(final String userName) - { - if (ActiveMQRACredential.trace) - { + private void setUserName(final String userName) { + if (ActiveMQRACredential.trace) { ActiveMQRALogger.LOGGER.trace("setUserName(" + userName + ")"); } @@ -85,12 +86,11 @@ public class ActiveMQRACredential implements Serializable /** * Get the password + * * @return The value */ - public String getPassword() - { - if (ActiveMQRACredential.trace) - { + public String getPassword() { + if (ActiveMQRACredential.trace) { ActiveMQRALogger.LOGGER.trace("getPassword()"); } @@ -99,12 +99,11 @@ public class ActiveMQRACredential implements Serializable /** * Set the password + * * @param password The value */ - private void setPassword(final String password) - { - if (ActiveMQRACredential.trace) - { + private void setPassword(final String password) { + if (ActiveMQRACredential.trace) { ActiveMQRALogger.LOGGER.trace("setPassword(****)"); } @@ -113,41 +112,36 @@ public class ActiveMQRACredential implements Serializable /** * Get credentials - * @param mcf The managed connection factory + * + * @param mcf The managed connection factory * @param subject The subject - * @param info The connection request info + * @param info The connection request info * @return The credentials - * @exception SecurityException Thrown if the credentials can't be retrieved + * @throws SecurityException Thrown if the credentials can't be retrieved */ public static ActiveMQRACredential getCredential(final ManagedConnectionFactory mcf, - final Subject subject, - final ConnectionRequestInfo info) throws SecurityException - { - if (ActiveMQRACredential.trace) - { + final Subject subject, + final ConnectionRequestInfo info) throws SecurityException { + if (ActiveMQRACredential.trace) { ActiveMQRALogger.LOGGER.trace("getCredential(" + mcf + ", " + subject + ", " + info + ")"); } ActiveMQRACredential jc = new ActiveMQRACredential(); - if (subject == null && info != null) - { - jc.setUserName(((ActiveMQRAConnectionRequestInfo)info).getUserName()); - jc.setPassword(((ActiveMQRAConnectionRequestInfo)info).getPassword()); + if (subject == null && info != null) { + jc.setUserName(((ActiveMQRAConnectionRequestInfo) info).getUserName()); + jc.setPassword(((ActiveMQRAConnectionRequestInfo) info).getPassword()); } - else if (subject != null) - { + else if (subject != null) { PasswordCredential pwdc = GetCredentialAction.getCredential(subject, mcf); - if (pwdc == null) - { + if (pwdc == null) { throw new SecurityException("No password credentials found"); } jc.setUserName(pwdc.getUserName()); jc.setPassword(new String(pwdc.getPassword())); } - else - { + else { throw new SecurityException("No Subject or ConnectionRequestInfo set, could not get credentials"); } @@ -156,13 +150,12 @@ public class ActiveMQRACredential implements Serializable /** * String representation + * * @return The representation */ @Override - public String toString() - { - if (ActiveMQRACredential.trace) - { + public String toString() { + if (ActiveMQRACredential.trace) { ActiveMQRALogger.LOGGER.trace("toString()"); } @@ -172,23 +165,26 @@ public class ActiveMQRACredential implements Serializable /** * Privileged class to get credentials */ - private static class GetCredentialAction implements PrivilegedAction - { - /** The subject */ + private static class GetCredentialAction implements PrivilegedAction { + + /** + * The subject + */ private final Subject subject; - /** The managed connection factory */ + /** + * The managed connection factory + */ private final ManagedConnectionFactory mcf; /** * Constructor + * * @param subject The subject - * @param mcf The managed connection factory + * @param mcf The managed connection factory */ - GetCredentialAction(final Subject subject, final ManagedConnectionFactory mcf) - { - if (ActiveMQRACredential.trace) - { + GetCredentialAction(final Subject subject, final ManagedConnectionFactory mcf) { + if (ActiveMQRACredential.trace) { ActiveMQRALogger.LOGGER.trace("constructor(" + subject + ", " + mcf + ")"); } @@ -198,22 +194,19 @@ public class ActiveMQRACredential implements Serializable /** * Run + * * @return The credential */ - public PasswordCredential run() - { - if (ActiveMQRACredential.trace) - { + public PasswordCredential run() { + if (ActiveMQRACredential.trace) { ActiveMQRALogger.LOGGER.trace("run()"); } Set creds = subject.getPrivateCredentials(PasswordCredential.class); PasswordCredential pwdc = null; - for (PasswordCredential curCred : creds) - { - if (curCred.getManagedConnectionFactory().equals(mcf)) - { + for (PasswordCredential curCred : creds) { + if (curCred.getManagedConnectionFactory().equals(mcf)) { pwdc = curCred; break; } @@ -223,14 +216,13 @@ public class ActiveMQRACredential implements Serializable /** * Get credentials + * * @param subject The subject - * @param mcf The managed connection factory + * @param mcf The managed connection factory * @return The credential */ - static PasswordCredential getCredential(final Subject subject, final ManagedConnectionFactory mcf) - { - if (ActiveMQRACredential.trace) - { + static PasswordCredential getCredential(final Subject subject, final ManagedConnectionFactory mcf) { + if (ActiveMQRACredential.trace) { ActiveMQRALogger.LOGGER.trace("getCredential(" + subject + ", " + mcf + ")"); } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAJMSContext.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAJMSContext.java index f9d83d1bc5..5d14ba446d 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAJMSContext.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAJMSContext.java @@ -23,39 +23,35 @@ import org.apache.activemq.artemis.jms.client.ThreadAwareContext; import javax.jms.ExceptionListener; import javax.jms.JMSContext; -public class ActiveMQRAJMSContext extends ActiveMQJMSContext -{ - public ActiveMQRAJMSContext(ActiveMQConnectionForContext connection, int ackMode, ThreadAwareContext threadAwareContext) - { +public class ActiveMQRAJMSContext extends ActiveMQJMSContext { + + public ActiveMQRAJMSContext(ActiveMQConnectionForContext connection, + int ackMode, + ThreadAwareContext threadAwareContext) { super(connection, ackMode, threadAwareContext); } - public ActiveMQRAJMSContext(ActiveMQConnectionForContext connection, ThreadAwareContext threadAwareContext) - { + public ActiveMQRAJMSContext(ActiveMQConnectionForContext connection, ThreadAwareContext threadAwareContext) { super(connection, threadAwareContext); } @Override - public JMSContext createContext(int sessionMode) - { + public JMSContext createContext(int sessionMode) { throw ActiveMQRABundle.BUNDLE.illegalJEEMethod(); } @Override - public void stop() - { + public void stop() { throw ActiveMQRABundle.BUNDLE.illegalJEEMethod(); } @Override - public void setClientID(String clientID) - { + public void setClientID(String clientID) { throw ActiveMQRABundle.BUNDLE.illegalJEEMethod(); } @Override - public void setExceptionListener(ExceptionListener listener) - { + public void setExceptionListener(ExceptionListener listener) { throw ActiveMQRABundle.BUNDLE.illegalJEEMethod(); } } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRALocalTransaction.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRALocalTransaction.java index ddd66558a1..c24cdea386 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRALocalTransaction.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRALocalTransaction.java @@ -20,26 +20,28 @@ import javax.jms.JMSException; import javax.resource.ResourceException; import javax.resource.spi.LocalTransaction; - /** * JMS Local transaction */ -public class ActiveMQRALocalTransaction implements LocalTransaction -{ - /** Trace enabled */ +public class ActiveMQRALocalTransaction implements LocalTransaction { + + /** + * Trace enabled + */ private static boolean trace = ActiveMQRALogger.LOGGER.isTraceEnabled(); - /** The managed connection */ + /** + * The managed connection + */ private final ActiveMQRAManagedConnection mc; /** * Constructor + * * @param mc The managed connection */ - public ActiveMQRALocalTransaction(final ActiveMQRAManagedConnection mc) - { - if (ActiveMQRALocalTransaction.trace) - { + public ActiveMQRALocalTransaction(final ActiveMQRAManagedConnection mc) { + if (ActiveMQRALocalTransaction.trace) { ActiveMQRALogger.LOGGER.trace("constructor(" + mc + ")"); } @@ -48,43 +50,37 @@ public class ActiveMQRALocalTransaction implements LocalTransaction /** * Begin - * @exception ResourceException Thrown if the operation fails + * + * @throws ResourceException Thrown if the operation fails */ - public void begin() throws ResourceException - { - if (ActiveMQRALocalTransaction.trace) - { + public void begin() throws ResourceException { + if (ActiveMQRALocalTransaction.trace) { ActiveMQRALogger.LOGGER.trace("begin()"); } - // mc.setInManagedTx(true); + // mc.setInManagedTx(true); } /** * Commit - * @exception ResourceException Thrown if the operation fails + * + * @throws ResourceException Thrown if the operation fails */ - public void commit() throws ResourceException - { - if (ActiveMQRALocalTransaction.trace) - { + public void commit() throws ResourceException { + if (ActiveMQRALocalTransaction.trace) { ActiveMQRALogger.LOGGER.trace("commit()"); } mc.lock(); - try - { - if (mc.getSession().getTransacted()) - { + try { + if (mc.getSession().getTransacted()) { mc.getSession().commit(); } } - catch (JMSException e) - { + catch (JMSException e) { throw new ResourceException("Could not commit LocalTransaction", e); } - finally - { + finally { //mc.setInManagedTx(false); mc.unlock(); } @@ -92,29 +88,24 @@ public class ActiveMQRALocalTransaction implements LocalTransaction /** * Rollback - * @exception ResourceException Thrown if the operation fails + * + * @throws ResourceException Thrown if the operation fails */ - public void rollback() throws ResourceException - { - if (ActiveMQRALocalTransaction.trace) - { + public void rollback() throws ResourceException { + if (ActiveMQRALocalTransaction.trace) { ActiveMQRALogger.LOGGER.trace("rollback()"); } mc.lock(); - try - { - if (mc.getSession().getTransacted()) - { + try { + if (mc.getSession().getTransacted()) { mc.getSession().rollback(); } } - catch (JMSException ex) - { + catch (JMSException ex) { throw new ResourceException("Could not rollback LocalTransaction", ex); } - finally - { + finally { //mc.setInManagedTx(false); mc.unlock(); } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRALogger.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRALogger.java index a34f592280..093e3eed0a 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRALogger.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRALogger.java @@ -42,8 +42,8 @@ import org.jboss.logging.annotations.MessageLogger; * so an INFO message would be 151000 to 151999 */ @MessageLogger(projectCode = "AMQ") -public interface ActiveMQRALogger extends BasicLogger -{ +public interface ActiveMQRALogger extends BasicLogger { + /** * The default logger. */ diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMCFProperties.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMCFProperties.java index 192c120484..dc363e7e7c 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMCFProperties.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMCFProperties.java @@ -21,12 +21,11 @@ import java.io.Serializable; import javax.jms.Queue; import javax.jms.Topic; - /** * The MCF default properties - these are set in the tx-connection-factory at the jms-ds.xml */ -public class ActiveMQRAMCFProperties extends ConnectionFactoryProperties implements Serializable -{ +public class ActiveMQRAMCFProperties extends ConnectionFactoryProperties implements Serializable { + /** * Serial version UID */ @@ -46,7 +45,6 @@ public class ActiveMQRAMCFProperties extends ConnectionFactoryProperties impleme */ private static final String TOPIC_TYPE = Topic.class.getName(); - private String strConnectorClassName; public String strConnectionParameters; @@ -64,10 +62,8 @@ public class ActiveMQRAMCFProperties extends ConnectionFactoryProperties impleme /** * Constructor */ - public ActiveMQRAMCFProperties() - { - if (ActiveMQRAMCFProperties.trace) - { + public ActiveMQRAMCFProperties() { + if (ActiveMQRAMCFProperties.trace) { ActiveMQRALogger.LOGGER.trace("constructor()"); } @@ -79,25 +75,20 @@ public class ActiveMQRAMCFProperties extends ConnectionFactoryProperties impleme * * @return The type */ - public int getType() - { - if (ActiveMQRAMCFProperties.trace) - { + public int getType() { + if (ActiveMQRAMCFProperties.trace) { ActiveMQRALogger.LOGGER.trace("getType()"); } return type; } - public String getConnectorClassName() - { + public String getConnectorClassName() { return strConnectorClassName; } - public void setConnectorClassName(final String connectorClassName) - { - if (ActiveMQRAMCFProperties.trace) - { + public void setConnectorClassName(final String connectorClassName) { + if (ActiveMQRAMCFProperties.trace) { ActiveMQRALogger.LOGGER.trace("setConnectorClassName(" + connectorClassName + ")"); } @@ -105,16 +96,15 @@ public class ActiveMQRAMCFProperties extends ConnectionFactoryProperties impleme setParsedConnectorClassNames(ActiveMQRaUtils.parseConnectorConnectorConfig(connectorClassName)); } + /** * @return the connectionParameters */ - public String getStrConnectionParameters() - { + public String getStrConnectionParameters() { return strConnectionParameters; } - public void setConnectionParameters(final String configuration) - { + public void setConnectionParameters(final String configuration) { strConnectionParameters = configuration; setParsedConnectionParameters(ActiveMQRaUtils.parseConfig(configuration)); } @@ -124,23 +114,18 @@ public class ActiveMQRAMCFProperties extends ConnectionFactoryProperties impleme * * @param defaultType either javax.jms.Topic or javax.jms.Queue */ - public void setSessionDefaultType(final String defaultType) - { - if (ActiveMQRAMCFProperties.trace) - { + public void setSessionDefaultType(final String defaultType) { + if (ActiveMQRAMCFProperties.trace) { ActiveMQRALogger.LOGGER.trace("setSessionDefaultType(" + type + ")"); } - if (defaultType.equals(ActiveMQRAMCFProperties.QUEUE_TYPE)) - { + if (defaultType.equals(ActiveMQRAMCFProperties.QUEUE_TYPE)) { type = ActiveMQRAConnectionFactory.QUEUE_CONNECTION; } - else if (defaultType.equals(ActiveMQRAMCFProperties.TOPIC_TYPE)) - { + else if (defaultType.equals(ActiveMQRAMCFProperties.TOPIC_TYPE)) { type = ActiveMQRAConnectionFactory.TOPIC_CONNECTION; } - else - { + else { type = ActiveMQRAConnectionFactory.CONNECTION; } } @@ -150,23 +135,18 @@ public class ActiveMQRAMCFProperties extends ConnectionFactoryProperties impleme * * @return The default session type */ - public String getSessionDefaultType() - { - if (ActiveMQRAMCFProperties.trace) - { + public String getSessionDefaultType() { + if (ActiveMQRAMCFProperties.trace) { ActiveMQRALogger.LOGGER.trace("getSessionDefaultType()"); } - if (type == ActiveMQRAConnectionFactory.CONNECTION) - { + if (type == ActiveMQRAConnectionFactory.CONNECTION) { return "BOTH"; } - else if (type == ActiveMQRAConnectionFactory.QUEUE_CONNECTION) - { + else if (type == ActiveMQRAConnectionFactory.QUEUE_CONNECTION) { return ActiveMQRAMCFProperties.TOPIC_TYPE; } - else - { + else { return ActiveMQRAMCFProperties.QUEUE_TYPE; } } @@ -176,10 +156,8 @@ public class ActiveMQRAMCFProperties extends ConnectionFactoryProperties impleme * * @return the useTryLock. */ - public Integer getUseTryLock() - { - if (ActiveMQRAMCFProperties.trace) - { + public Integer getUseTryLock() { + if (ActiveMQRAMCFProperties.trace) { ActiveMQRALogger.LOGGER.trace("getUseTryLock()"); } @@ -191,10 +169,8 @@ public class ActiveMQRAMCFProperties extends ConnectionFactoryProperties impleme * * @param useTryLock the useTryLock. */ - public void setUseTryLock(final Integer useTryLock) - { - if (ActiveMQRAMCFProperties.trace) - { + public void setUseTryLock(final Integer useTryLock) { + if (ActiveMQRAMCFProperties.trace) { ActiveMQRALogger.LOGGER.trace("setUseTryLock(" + useTryLock + ")"); } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAManagedConnection.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAManagedConnection.java index e4dc31045b..010467edca 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAManagedConnection.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAManagedConnection.java @@ -59,8 +59,8 @@ import org.apache.activemq.artemis.utils.VersionLoader; /** * The managed connection */ -public final class ActiveMQRAManagedConnection implements ManagedConnection, ExceptionListener -{ +public final class ActiveMQRAManagedConnection implements ManagedConnection, ExceptionListener { + /** * Trace enabled */ @@ -140,10 +140,8 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc final ActiveMQRAConnectionRequestInfo cri, final ActiveMQResourceAdapter ra, final String userName, - final String password) throws ResourceException - { - if (ActiveMQRAManagedConnection.trace) - { + final String password) throws ResourceException { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("constructor(" + mcf + ", " + cri + ", " + userName + ", ****)"); } @@ -161,30 +159,23 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc xaSession = null; xaResource = null; - try - { + try { setup(); } - catch (ResourceException e) - { - try - { + catch (ResourceException e) { + try { destroy(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } throw e; } - catch (Throwable t) - { - try - { + catch (Throwable t) { + try { destroy(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } throw new ResourceException("Error during setup", t); } @@ -198,10 +189,9 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc * @return The connection * @throws ResourceException Thrown if an error occurs */ - public synchronized Object getConnection(final Subject subject, final ConnectionRequestInfo cxRequestInfo) throws ResourceException - { - if (ActiveMQRAManagedConnection.trace) - { + public synchronized Object getConnection(final Subject subject, + final ConnectionRequestInfo cxRequestInfo) throws ResourceException { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("getConnection(" + subject + ", " + cxRequestInfo + ")"); } @@ -209,18 +199,15 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc ActiveMQRACredential credential = ActiveMQRACredential.getCredential(mcf, subject, cxRequestInfo); // Null users are allowed! - if (userName != null && !userName.equals(credential.getUserName())) - { + if (userName != null && !userName.equals(credential.getUserName())) { throw new SecurityException("Password credentials not the same, reauthentication not allowed"); } - if (userName == null && credential.getUserName() != null) - { + if (userName == null && credential.getUserName() != null) { throw new SecurityException("Password credentials not the same, reauthentication not allowed"); } - if (isDestroyed.get()) - { + if (isDestroyed.get()) { throw new IllegalStateException("The managed connection is already destroyed"); } @@ -234,28 +221,22 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc * * @throws ResourceException Failed to close one or more handles. */ - private void destroyHandles() throws ResourceException - { - if (ActiveMQRAManagedConnection.trace) - { + private void destroyHandles() throws ResourceException { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("destroyHandles()"); } - try - { + try { - if (connection != null) - { + if (connection != null) { connection.stop(); } } - catch (Throwable t) - { + catch (Throwable t) { ActiveMQRALogger.LOGGER.trace("Ignored error stopping connection", t); } - for (ActiveMQRASession session : handles) - { + for (ActiveMQRASession session : handles) { session.destroy(); } @@ -267,37 +248,30 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc * * @throws ResourceException Could not property close the session and connection. */ - public void destroy() throws ResourceException - { - if (ActiveMQRAManagedConnection.trace) - { + public void destroy() throws ResourceException { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("destroy()"); } - if (isDestroyed.get() || connection == null) - { + if (isDestroyed.get() || connection == null) { return; } isDestroyed.set(true); - try - { + try { connection.setExceptionListener(null); } - catch (JMSException e) - { + catch (JMSException e) { ActiveMQRALogger.LOGGER.debug("Error unsetting the exception listener " + this, e); } - if (connection != null) - { + if (connection != null) { connection.signalStopToAllSessions(); } destroyHandles(); - try - { + try { /** * (xa|nonXA)Session.close() may NOT be called BEFORE connection.close() *

    @@ -306,38 +280,31 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc *

    * connection close will close the ClientSessionFactory which will close all sessions. */ - if (connection != null) - { + if (connection != null) { connection.close(); } // The following calls should not be necessary, as the connection should close the // ClientSessionFactory, which will close the sessions. - try - { - if (nonXAsession != null) - { + try { + if (nonXAsession != null) { nonXAsession.close(); } - if (xaSession != null) - { + if (xaSession != null) { xaSession.close(); } } - catch (JMSException e) - { + catch (JMSException e) { ActiveMQRALogger.LOGGER.debug("Error closing session " + this, e); } // we must close the ActiveMQConnectionFactory because it contains a ServerLocator - if (connectionFactory != null) - { + if (connectionFactory != null) { connectionFactory.close(); } } - catch (Throwable e) - { + catch (Throwable e) { throw new ResourceException("Could not properly close the session and connection", e); } } @@ -347,15 +314,12 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc * * @throws ResourceException Thrown if an error occurs */ - public void cleanup() throws ResourceException - { - if (ActiveMQRAManagedConnection.trace) - { + public void cleanup() throws ResourceException { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("cleanup()"); } - if (isDestroyed.get()) - { + if (isDestroyed.get()) { throw new IllegalStateException("ManagedConnection already destroyed"); } @@ -379,47 +343,37 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc * @throws ResourceException Failed to associate connection. * @throws IllegalStateException ManagedConnection in an illegal state. */ - public void associateConnection(final Object obj) throws ResourceException - { - if (ActiveMQRAManagedConnection.trace) - { + public void associateConnection(final Object obj) throws ResourceException { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("associateConnection(" + obj + ")"); } - if (!isDestroyed.get() && obj instanceof ActiveMQRASession) - { + if (!isDestroyed.get() && obj instanceof ActiveMQRASession) { ActiveMQRASession h = (ActiveMQRASession) obj; h.setManagedConnection(this); handles.add(h); } - else - { + else { throw new IllegalStateException("ManagedConnection in an illegal state"); } } - public void checkTransactionActive() throws JMSException - { + public void checkTransactionActive() throws JMSException { // don't bother looking at the transaction if there's an active XID - if (!inManagedTx && tm != null) - { - try - { + if (!inManagedTx && tm != null) { + try { Transaction tx = tm.getTransaction(); - if (tx != null) - { + if (tx != null) { int status = tx.getStatus(); // Only allow states that will actually succeed if (status != Status.STATUS_ACTIVE && status != Status.STATUS_PREPARING && status != Status.STATUS_PREPARED && - status != Status.STATUS_COMMITTING) - { + status != Status.STATUS_COMMITTING) { throw new javax.jms.IllegalStateException("Transaction " + tx + " not active"); } } } - catch (SystemException e) - { + catch (SystemException e) { JMSException jmsE = new javax.jms.IllegalStateException("Unexpected exception on the Transaction ManagerTransaction"); jmsE.initCause(e); throw jmsE; @@ -427,14 +381,11 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc } } - /** * Aqquire a lock on the managed connection */ - protected void lock() - { - if (ActiveMQRAManagedConnection.trace) - { + protected void lock() { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("lock()"); } @@ -446,28 +397,22 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc * * @throws JMSException Thrown if an error occurs */ - protected void tryLock() throws JMSException - { - if (ActiveMQRAManagedConnection.trace) - { + protected void tryLock() throws JMSException { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("tryLock()"); } Integer tryLock = mcf.getUseTryLock(); - if (tryLock == null || tryLock.intValue() <= 0) - { + if (tryLock == null || tryLock.intValue() <= 0) { lock(); return; } - try - { - if (lock.tryLock(tryLock.intValue(), TimeUnit.SECONDS) == false) - { + try { + if (lock.tryLock(tryLock.intValue(), TimeUnit.SECONDS) == false) { throw new ResourceAllocationException("Unable to obtain lock in " + tryLock + " seconds: " + this); } } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ResourceAllocationException("Interrupted attempting lock: " + this); } } @@ -475,10 +420,8 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc /** * Unlock the managed connection */ - protected void unlock() - { - if (ActiveMQRAManagedConnection.trace) - { + protected void unlock() { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("unlock()"); } @@ -490,10 +433,8 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc * * @param l The connection event listener to be added. */ - public void addConnectionEventListener(final ConnectionEventListener l) - { - if (ActiveMQRAManagedConnection.trace) - { + public void addConnectionEventListener(final ConnectionEventListener l) { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("addConnectionEventListener(" + l + ")"); } @@ -505,10 +446,8 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc * * @param l The connection event listener to be removed. */ - public void removeConnectionEventListener(final ConnectionEventListener l) - { - if (ActiveMQRAManagedConnection.trace) - { + public void removeConnectionEventListener(final ConnectionEventListener l) { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("removeConnectionEventListener(" + l + ")"); } @@ -521,10 +460,8 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc * @return The XAResource for the connection. * @throws ResourceException XA transaction not supported */ - public XAResource getXAResource() throws ResourceException - { - if (ActiveMQRAManagedConnection.trace) - { + public XAResource getXAResource() throws ResourceException { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("getXAResource()"); } @@ -532,8 +469,7 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc // Spec says a mc must always return the same XA resource, // so we cache it. // - if (xaResource == null) - { + if (xaResource == null) { ClientSessionInternal csi = (ClientSessionInternal) xaSession.getXAResource(); ActiveMQRAXAResource activeMQRAXAResource = new ActiveMQRAXAResource(this, xaSession.getXAResource()); Map xaResourceProperties = new HashMap(); @@ -544,8 +480,7 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc xaResource = ServiceUtils.wrapXAResource(activeMQRAXAResource, xaResourceProperties); } - if (ActiveMQRAManagedConnection.trace) - { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("XAResource=" + xaResource); } @@ -558,17 +493,14 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc * @return The local transaction for the connection. * @throws ResourceException Thrown if operation fails. */ - public LocalTransaction getLocalTransaction() throws ResourceException - { - if (ActiveMQRAManagedConnection.trace) - { + public LocalTransaction getLocalTransaction() throws ResourceException { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("getLocalTransaction()"); } LocalTransaction tx = new ActiveMQRALocalTransaction(this); - if (ActiveMQRAManagedConnection.trace) - { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("LocalTransaction=" + tx); } @@ -582,15 +514,12 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc * @throws ResourceException Thrown if the operation fails. * @throws IllegalStateException Thrown if the managed connection already is destroyed. */ - public ManagedConnectionMetaData getMetaData() throws ResourceException - { - if (ActiveMQRAManagedConnection.trace) - { + public ManagedConnectionMetaData getMetaData() throws ResourceException { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("getMetaData()"); } - if (isDestroyed.get()) - { + if (isDestroyed.get()) { throw new IllegalStateException("The managed connection is already destroyed"); } @@ -603,10 +532,8 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc * @param out The log writer * @throws ResourceException If operation fails */ - public void setLogWriter(final PrintWriter out) throws ResourceException - { - if (ActiveMQRAManagedConnection.trace) - { + public void setLogWriter(final PrintWriter out) throws ResourceException { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("setLogWriter(" + out + ")"); } } @@ -617,10 +544,8 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc * @return Always null * @throws ResourceException If operation fails */ - public PrintWriter getLogWriter() throws ResourceException - { - if (ActiveMQRAManagedConnection.trace) - { + public PrintWriter getLogWriter() throws ResourceException { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("getLogWriter()"); } @@ -632,21 +557,16 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc * * @param exception The JMS exception */ - public void onException(final JMSException exception) - { - if (ActiveMQConnection.EXCEPTION_FAILOVER.equals(exception.getErrorCode())) - { + public void onException(final JMSException exception) { + if (ActiveMQConnection.EXCEPTION_FAILOVER.equals(exception.getErrorCode())) { return; } - if (ActiveMQRAManagedConnection.trace) - { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("onException(" + exception + ")"); } - if (isDestroyed.get()) - { - if (ActiveMQRAManagedConnection.trace) - { + if (isDestroyed.get()) { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("Ignoring error on already destroyed connection " + this, exception); } return; @@ -654,12 +574,10 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc ActiveMQRALogger.LOGGER.handlingJMSFailure(exception); - try - { + try { connection.setExceptionListener(null); } - catch (JMSException e) - { + catch (JMSException e) { ActiveMQRALogger.LOGGER.debug("Unable to unset exception listener", e); } @@ -673,21 +591,16 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc * @return The session * @throws JMSException */ - protected Session getSession() throws JMSException - { - if (xaResource != null && inManagedTx) - { - if (ActiveMQRAManagedConnection.trace) - { + protected Session getSession() throws JMSException { + if (xaResource != null && inManagedTx) { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("getSession() -> XA session " + xaSession.getSession()); } return xaSession.getSession(); } - else - { - if (ActiveMQRAManagedConnection.trace) - { + else { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("getSession() -> non XA session " + nonXAsession); } @@ -700,10 +613,8 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc * * @param event The event to send. */ - protected void sendEvent(final ConnectionEvent event) - { - if (ActiveMQRAManagedConnection.trace) - { + protected void sendEvent(final ConnectionEvent event) { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("sendEvent(" + event + ")"); } @@ -712,10 +623,8 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc // convert to an array to avoid concurrent modification exceptions ConnectionEventListener[] list = eventListeners.toArray(new ConnectionEventListener[eventListeners.size()]); - for (ConnectionEventListener l : list) - { - switch (type) - { + for (ConnectionEventListener l : list) { + switch (type) { case ConnectionEvent.CONNECTION_CLOSED: l.connectionClosed(event); break; @@ -747,10 +656,8 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc * * @param handle The handle to remove. */ - protected void removeHandle(final ActiveMQRASession handle) - { - if (ActiveMQRAManagedConnection.trace) - { + protected void removeHandle(final ActiveMQRASession handle) { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("removeHandle(" + handle + ")"); } @@ -762,10 +669,8 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc * * @return The connection request info for this connection. */ - protected ActiveMQRAConnectionRequestInfo getCRI() - { - if (ActiveMQRAManagedConnection.trace) - { + protected ActiveMQRAConnectionRequestInfo getCRI() { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("getCRI()"); } @@ -777,10 +682,8 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc * * @return The connection factory for this connection. */ - protected ActiveMQRAManagedConnectionFactory getManagedConnectionFactory() - { - if (ActiveMQRAManagedConnection.trace) - { + protected ActiveMQRAManagedConnectionFactory getManagedConnectionFactory() { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("getManagedConnectionFactory()"); } @@ -792,15 +695,12 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc * * @throws JMSException Thrown if the connection can't be started */ - void start() throws JMSException - { - if (ActiveMQRAManagedConnection.trace) - { + void start() throws JMSException { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("start()"); } - if (connection != null) - { + if (connection != null) { connection.start(); } } @@ -810,15 +710,12 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc * * @throws JMSException Thrown if the connection can't be stopped */ - void stop() throws JMSException - { - if (ActiveMQRAManagedConnection.trace) - { + void stop() throws JMSException { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("stop()"); } - if (connection != null) - { + if (connection != null) { connection.stop(); } } @@ -828,10 +725,8 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc * * @return The user name */ - protected String getUserName() - { - if (ActiveMQRAManagedConnection.trace) - { + protected String getUserName() { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("getUserName()"); } @@ -843,28 +738,22 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc * * @throws ResourceException Thrown if a connection couldn't be created */ - private void setup() throws ResourceException - { - if (ActiveMQRAManagedConnection.trace) - { + private void setup() throws ResourceException { + if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("setup()"); } - try - { + try { createCF(); boolean transacted = cri.isTransacted(); int acknowledgeMode = Session.AUTO_ACKNOWLEDGE; - if (cri.getType() == ActiveMQRAConnectionFactory.TOPIC_CONNECTION) - { - if (userName != null && password != null) - { + if (cri.getType() == ActiveMQRAConnectionFactory.TOPIC_CONNECTION) { + if (userName != null && password != null) { connection = (ActiveMQXAConnection) connectionFactory.createXATopicConnection(userName, password); } - else - { + else { connection = (ActiveMQXAConnection) connectionFactory.createXATopicConnection(); } @@ -874,14 +763,11 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc nonXAsession = connection.createNonXATopicSession(transacted, acknowledgeMode); } - else if (cri.getType() == ActiveMQRAConnectionFactory.QUEUE_CONNECTION) - { - if (userName != null && password != null) - { + else if (cri.getType() == ActiveMQRAConnectionFactory.QUEUE_CONNECTION) { + if (userName != null && password != null) { connection = (ActiveMQXAConnection) connectionFactory.createXAQueueConnection(userName, password); } - else - { + else { connection = (ActiveMQXAConnection) connectionFactory.createXAQueueConnection(); } @@ -891,14 +777,11 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc nonXAsession = connection.createNonXAQueueSession(transacted, acknowledgeMode); } - else - { - if (userName != null && password != null) - { + else { + if (userName != null && password != null) { connection = (ActiveMQXAConnection) connectionFactory.createXAConnection(userName, password); } - else - { + else { connection = (ActiveMQXAConnection) connectionFactory.createXAConnection(); } @@ -909,22 +792,18 @@ public final class ActiveMQRAManagedConnection implements ManagedConnection, Exc } } - catch (JMSException je) - { + catch (JMSException je) { throw new ResourceException(je.getMessage(), je); } } - private void createCF() - { - if (connectionFactory == null) - { + private void createCF() { + if (connectionFactory == null) { connectionFactory = ra.createActiveMQConnectionFactory(mcf.getProperties()); } } - protected void setInManagedTx(boolean inManagedTx) - { + protected void setInManagedTx(boolean inManagedTx) { this.inManagedTx = inManagedTx; } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAManagedConnectionFactory.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAManagedConnectionFactory.java index 8621cc2443..be8ae1cfc3 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAManagedConnectionFactory.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAManagedConnectionFactory.java @@ -35,8 +35,8 @@ import org.apache.activemq.artemis.service.extensions.xa.recovery.XARecoveryConf /** * ActiveMQ Artemis ManagedConnectionFactory */ -public final class ActiveMQRAManagedConnectionFactory implements ManagedConnectionFactory, ResourceAdapterAssociation -{ +public final class ActiveMQRAManagedConnectionFactory implements ManagedConnectionFactory, ResourceAdapterAssociation { + /** * Serial version UID */ @@ -74,10 +74,8 @@ public final class ActiveMQRAManagedConnectionFactory implements ManagedConnecti /** * Constructor */ - public ActiveMQRAManagedConnectionFactory() - { - if (ActiveMQRAManagedConnectionFactory.trace) - { + public ActiveMQRAManagedConnectionFactory() { + if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("constructor()"); } @@ -92,10 +90,8 @@ public final class ActiveMQRAManagedConnectionFactory implements ManagedConnecti * @return javax.resource.cci.ConnectionFactory instance * @throws ResourceException Thrown if a connection factory can't be created */ - public Object createConnectionFactory() throws ResourceException - { - if (ActiveMQRAManagedConnectionFactory.trace) - { + public Object createConnectionFactory() throws ResourceException { + if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.debug("createConnectionFactory()"); } @@ -109,10 +105,8 @@ public final class ActiveMQRAManagedConnectionFactory implements ManagedConnecti * @return javax.resource.cci.ConnectionFactory instance * @throws ResourceException Thrown if a connection factory can't be created */ - public Object createConnectionFactory(final ConnectionManager cxManager) throws ResourceException - { - if (ActiveMQRAManagedConnectionFactory.trace) - { + public Object createConnectionFactory(final ConnectionManager cxManager) throws ResourceException { + if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("createConnectionFactory(" + cxManager + ")"); } @@ -120,11 +114,10 @@ public final class ActiveMQRAManagedConnectionFactory implements ManagedConnecti ActiveMQRAConnectionFactory cf = new ActiveMQRAConnectionFactoryImpl(this, cm); - if (ActiveMQRAManagedConnectionFactory.trace) - { + if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("Created connection factory: " + cf + - ", using connection manager: " + - cm); + ", using connection manager: " + + cm); } return cf; } @@ -137,10 +130,9 @@ public final class ActiveMQRAManagedConnectionFactory implements ManagedConnecti * @return The managed connection * @throws ResourceException Thrown if a managed connection can't be created */ - public ManagedConnection createManagedConnection(final Subject subject, final ConnectionRequestInfo cxRequestInfo) throws ResourceException - { - if (ActiveMQRAManagedConnectionFactory.trace) - { + public ManagedConnection createManagedConnection(final Subject subject, + final ConnectionRequestInfo cxRequestInfo) throws ResourceException { + if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("createManagedConnection(" + subject + ", " + cxRequestInfo + ")"); } @@ -148,19 +140,13 @@ public final class ActiveMQRAManagedConnectionFactory implements ManagedConnecti ActiveMQRACredential credential = ActiveMQRACredential.getCredential(this, subject, cri); - if (ActiveMQRAManagedConnectionFactory.trace) - { + if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("jms credential: " + credential); } - ActiveMQRAManagedConnection mc = new ActiveMQRAManagedConnection(this, - cri, - ra, - credential.getUserName(), - credential.getPassword()); + ActiveMQRAManagedConnection mc = new ActiveMQRAManagedConnection(this, cri, ra, credential.getUserName(), credential.getPassword()); - if (ActiveMQRAManagedConnectionFactory.trace) - { + if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("created new managed connection: " + mc); } @@ -169,17 +155,14 @@ public final class ActiveMQRAManagedConnectionFactory implements ManagedConnecti return mc; } - private synchronized void registerRecovery() - { - if (recoveryConnectionFactory == null) - { + private synchronized void registerRecovery() { + if (recoveryConnectionFactory == null) { recoveryConnectionFactory = ra.createRecoveryActiveMQConnectionFactory(mcfProperties); resourceRecovery = ra.getRecoveryManager().register(recoveryConnectionFactory, null, null); } } - public XARecoveryConfig getResourceRecovery() - { + public XARecoveryConfig getResourceRecovery() { return resourceRecovery; } @@ -192,44 +175,37 @@ public final class ActiveMQRAManagedConnectionFactory implements ManagedConnecti * @return The managed connection * @throws ResourceException Thrown if the managed connection can not be found */ - public ManagedConnection matchManagedConnections(@SuppressWarnings("rawtypes") final Set connectionSet, final Subject subject, final ConnectionRequestInfo cxRequestInfo) throws ResourceException - { - if (ActiveMQRAManagedConnectionFactory.trace) - { + public ManagedConnection matchManagedConnections(@SuppressWarnings("rawtypes") final Set connectionSet, + final Subject subject, + final ConnectionRequestInfo cxRequestInfo) throws ResourceException { + if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("matchManagedConnections(" + connectionSet + - ", " + - subject + - ", " + - cxRequestInfo + - ")"); + ", " + + subject + + ", " + + cxRequestInfo + + ")"); } ActiveMQRAConnectionRequestInfo cri = getCRI((ActiveMQRAConnectionRequestInfo) cxRequestInfo); ActiveMQRACredential credential = ActiveMQRACredential.getCredential(this, subject, cri); - if (ActiveMQRAManagedConnectionFactory.trace) - { + if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("Looking for connection matching credentials: " + credential); } Iterator connections = connectionSet.iterator(); - while (connections.hasNext()) - { + while (connections.hasNext()) { Object obj = connections.next(); - if (obj instanceof ActiveMQRAManagedConnection) - { + if (obj instanceof ActiveMQRAManagedConnection) { ActiveMQRAManagedConnection mc = (ActiveMQRAManagedConnection) obj; ManagedConnectionFactory mcf = mc.getManagedConnectionFactory(); - if ((mc.getUserName() == null || mc.getUserName() != null && mc.getUserName() - .equals(credential.getUserName())) && mcf.equals(this)) - { - if (cri.equals(mc.getCRI())) - { - if (ActiveMQRAManagedConnectionFactory.trace) - { + if ((mc.getUserName() == null || mc.getUserName() != null && mc.getUserName().equals(credential.getUserName())) && mcf.equals(this)) { + if (cri.equals(mc.getCRI())) { + if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("Found matching connection: " + mc); } @@ -239,8 +215,7 @@ public final class ActiveMQRAManagedConnectionFactory implements ManagedConnecti } } - if (ActiveMQRAManagedConnectionFactory.trace) - { + if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("No matching connection was found"); } @@ -253,10 +228,8 @@ public final class ActiveMQRAManagedConnectionFactory implements ManagedConnecti * @param out The writer * @throws ResourceException Thrown if the writer can't be set */ - public void setLogWriter(final PrintWriter out) throws ResourceException - { - if (ActiveMQRAManagedConnectionFactory.trace) - { + public void setLogWriter(final PrintWriter out) throws ResourceException { + if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("setLogWriter(" + out + ")"); } } @@ -267,10 +240,8 @@ public final class ActiveMQRAManagedConnectionFactory implements ManagedConnecti * @return The writer * @throws ResourceException Thrown if the writer can't be retrieved */ - public PrintWriter getLogWriter() throws ResourceException - { - if (ActiveMQRAManagedConnectionFactory.trace) - { + public PrintWriter getLogWriter() throws ResourceException { + if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("getLogWriter()"); } @@ -282,10 +253,8 @@ public final class ActiveMQRAManagedConnectionFactory implements ManagedConnecti * * @return The resource adapter */ - public ResourceAdapter getResourceAdapter() - { - if (ActiveMQRAManagedConnectionFactory.trace) - { + public ResourceAdapter getResourceAdapter() { + if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("getResourceAdapter()"); } @@ -300,15 +269,12 @@ public final class ActiveMQRAManagedConnectionFactory implements ManagedConnecti * @param ra The resource adapter * @throws ResourceException Thrown if incorrect resource adapter */ - public void setResourceAdapter(final ResourceAdapter ra) throws ResourceException - { - if (ActiveMQRAManagedConnectionFactory.trace) - { + public void setResourceAdapter(final ResourceAdapter ra) throws ResourceException { + if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("setResourceAdapter(" + ra + ")"); } - if (ra == null || !(ra instanceof ActiveMQResourceAdapter)) - { + if (ra == null || !(ra instanceof ActiveMQResourceAdapter)) { throw new ResourceException("Resource adapter is " + ra); } @@ -323,26 +289,21 @@ public final class ActiveMQRAManagedConnectionFactory implements ManagedConnecti * @return True if this object is the same as the obj argument; false otherwise. */ @Override - public boolean equals(final Object obj) - { - if (ActiveMQRAManagedConnectionFactory.trace) - { + public boolean equals(final Object obj) { + if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("equals(" + obj + ")"); } - if (obj == null) - { + if (obj == null) { return false; } - if (obj instanceof ActiveMQRAManagedConnectionFactory) - { + if (obj instanceof ActiveMQRAManagedConnectionFactory) { ActiveMQRAManagedConnectionFactory other = (ActiveMQRAManagedConnectionFactory) obj; return mcfProperties.equals(other.getProperties()) && ra.equals(other.getResourceAdapter()); } - else - { + else { return false; } } @@ -353,10 +314,8 @@ public final class ActiveMQRAManagedConnectionFactory implements ManagedConnecti * @return The hash code */ @Override - public int hashCode() - { - if (ActiveMQRAManagedConnectionFactory.trace) - { + public int hashCode() { + if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("hashCode()"); } @@ -371,10 +330,8 @@ public final class ActiveMQRAManagedConnectionFactory implements ManagedConnecti * * @return The value */ - public String getSessionDefaultType() - { - if (ActiveMQRAManagedConnectionFactory.trace) - { + public String getSessionDefaultType() { + if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("getSessionDefaultType()"); } @@ -386,10 +343,8 @@ public final class ActiveMQRAManagedConnectionFactory implements ManagedConnecti * * @param type either javax.jms.Topic or javax.jms.Queue */ - public void setSessionDefaultType(final String type) - { - if (ActiveMQRAManagedConnectionFactory.trace) - { + public void setSessionDefaultType(final String type) { + if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("setSessionDefaultType(" + type + ")"); } @@ -399,306 +354,246 @@ public final class ActiveMQRAManagedConnectionFactory implements ManagedConnecti /** * @return the connectionParameters */ - public String getConnectionParameters() - { + public String getConnectionParameters() { return mcfProperties.getStrConnectionParameters(); } - public void setConnectionParameters(final String configuration) - { + public void setConnectionParameters(final String configuration) { mcfProperties.setConnectionParameters(configuration); } /** * @return the transportType */ - public String getConnectorClassName() - { + public String getConnectorClassName() { return mcfProperties.getConnectorClassName(); } - public void setConnectorClassName(final String value) - { + public void setConnectorClassName(final String value) { mcfProperties.setConnectorClassName(value); } - public String getConnectionLoadBalancingPolicyClassName() - { + public String getConnectionLoadBalancingPolicyClassName() { return mcfProperties.getConnectionLoadBalancingPolicyClassName(); } - public void setConnectionLoadBalancingPolicyClassName(final String connectionLoadBalancingPolicyClassName) - { + public void setConnectionLoadBalancingPolicyClassName(final String connectionLoadBalancingPolicyClassName) { mcfProperties.setConnectionLoadBalancingPolicyClassName(connectionLoadBalancingPolicyClassName); } - public String getDiscoveryAddress() - { + public String getDiscoveryAddress() { return mcfProperties.getDiscoveryAddress(); } - public void setDiscoveryAddress(final String discoveryAddress) - { + public void setDiscoveryAddress(final String discoveryAddress) { mcfProperties.setDiscoveryAddress(discoveryAddress); } - public Integer getDiscoveryPort() - { + public Integer getDiscoveryPort() { return mcfProperties.getDiscoveryPort(); } - public void setDiscoveryPort(final Integer discoveryPort) - { + public void setDiscoveryPort(final Integer discoveryPort) { mcfProperties.setDiscoveryPort(discoveryPort); } - public Long getDiscoveryRefreshTimeout() - { + public Long getDiscoveryRefreshTimeout() { return mcfProperties.getDiscoveryRefreshTimeout(); } - public void setDiscoveryRefreshTimeout(final Long discoveryRefreshTimeout) - { + public void setDiscoveryRefreshTimeout(final Long discoveryRefreshTimeout) { mcfProperties.setDiscoveryRefreshTimeout(discoveryRefreshTimeout); } - public Long getDiscoveryInitialWaitTimeout() - { + public Long getDiscoveryInitialWaitTimeout() { return mcfProperties.getDiscoveryInitialWaitTimeout(); } - public void setDiscoveryInitialWaitTimeout(final Long discoveryInitialWaitTimeout) - { + public void setDiscoveryInitialWaitTimeout(final Long discoveryInitialWaitTimeout) { mcfProperties.setDiscoveryInitialWaitTimeout(discoveryInitialWaitTimeout); } - public String getClientID() - { + public String getClientID() { return mcfProperties.getClientID(); } - public void setClientID(final String clientID) - { + public void setClientID(final String clientID) { mcfProperties.setClientID(clientID); } - public Integer getDupsOKBatchSize() - { + public Integer getDupsOKBatchSize() { return mcfProperties.getDupsOKBatchSize(); } - public void setDupsOKBatchSize(final Integer dupsOKBatchSize) - { + public void setDupsOKBatchSize(final Integer dupsOKBatchSize) { mcfProperties.setDupsOKBatchSize(dupsOKBatchSize); } - public Integer getTransactionBatchSize() - { + public Integer getTransactionBatchSize() { return mcfProperties.getTransactionBatchSize(); } - public void setTransactionBatchSize(final Integer transactionBatchSize) - { + public void setTransactionBatchSize(final Integer transactionBatchSize) { mcfProperties.setTransactionBatchSize(transactionBatchSize); } - public Long getClientFailureCheckPeriod() - { + public Long getClientFailureCheckPeriod() { return mcfProperties.getClientFailureCheckPeriod(); } - public void setClientFailureCheckPeriod(final Long clientFailureCheckPeriod) - { + public void setClientFailureCheckPeriod(final Long clientFailureCheckPeriod) { mcfProperties.setClientFailureCheckPeriod(clientFailureCheckPeriod); } - public Long getConnectionTTL() - { + public Long getConnectionTTL() { return mcfProperties.getConnectionTTL(); } - public void setConnectionTTL(final Long connectionTTL) - { + public void setConnectionTTL(final Long connectionTTL) { mcfProperties.setConnectionTTL(connectionTTL); } - public Long getCallTimeout() - { + public Long getCallTimeout() { return mcfProperties.getCallTimeout(); } - public void setCallTimeout(final Long callTimeout) - { + public void setCallTimeout(final Long callTimeout) { mcfProperties.setCallTimeout(callTimeout); } - public Integer getConsumerWindowSize() - { + public Integer getConsumerWindowSize() { return mcfProperties.getConsumerWindowSize(); } - public void setConsumerWindowSize(final Integer consumerWindowSize) - { + public void setConsumerWindowSize(final Integer consumerWindowSize) { mcfProperties.setConsumerWindowSize(consumerWindowSize); } - public Integer getConsumerMaxRate() - { + public Integer getConsumerMaxRate() { return mcfProperties.getConsumerMaxRate(); } - public void setConsumerMaxRate(final Integer consumerMaxRate) - { + public void setConsumerMaxRate(final Integer consumerMaxRate) { mcfProperties.setConsumerMaxRate(consumerMaxRate); } - public Integer getConfirmationWindowSize() - { + public Integer getConfirmationWindowSize() { return mcfProperties.getConfirmationWindowSize(); } - public void setConfirmationWindowSize(final Integer confirmationWindowSize) - { + public void setConfirmationWindowSize(final Integer confirmationWindowSize) { mcfProperties.setConfirmationWindowSize(confirmationWindowSize); } - public Integer getProducerMaxRate() - { + public Integer getProducerMaxRate() { return mcfProperties.getProducerMaxRate(); } - public void setProducerMaxRate(final Integer producerMaxRate) - { + public void setProducerMaxRate(final Integer producerMaxRate) { mcfProperties.setProducerMaxRate(producerMaxRate); } - public Integer getMinLargeMessageSize() - { + public Integer getMinLargeMessageSize() { return mcfProperties.getMinLargeMessageSize(); } - public void setMinLargeMessageSize(final Integer minLargeMessageSize) - { + public void setMinLargeMessageSize(final Integer minLargeMessageSize) { mcfProperties.setMinLargeMessageSize(minLargeMessageSize); } - public Boolean isBlockOnAcknowledge() - { + public Boolean isBlockOnAcknowledge() { return mcfProperties.isBlockOnAcknowledge(); } - public void setBlockOnAcknowledge(final Boolean blockOnAcknowledge) - { + public void setBlockOnAcknowledge(final Boolean blockOnAcknowledge) { mcfProperties.setBlockOnAcknowledge(blockOnAcknowledge); } - public Boolean isBlockOnNonDurableSend() - { + public Boolean isBlockOnNonDurableSend() { return mcfProperties.isBlockOnNonDurableSend(); } - public void setBlockOnNonDurableSend(final Boolean blockOnNonDurableSend) - { + public void setBlockOnNonDurableSend(final Boolean blockOnNonDurableSend) { mcfProperties.setBlockOnNonDurableSend(blockOnNonDurableSend); } - public Boolean isBlockOnDurableSend() - { + public Boolean isBlockOnDurableSend() { return mcfProperties.isBlockOnDurableSend(); } - public void setBlockOnDurableSend(final Boolean blockOnDurableSend) - { + public void setBlockOnDurableSend(final Boolean blockOnDurableSend) { mcfProperties.setBlockOnDurableSend(blockOnDurableSend); } - public Boolean isAutoGroup() - { + public Boolean isAutoGroup() { return mcfProperties.isAutoGroup(); } - public void setAutoGroup(final Boolean autoGroup) - { + public void setAutoGroup(final Boolean autoGroup) { mcfProperties.setAutoGroup(autoGroup); } - public Boolean isPreAcknowledge() - { + public Boolean isPreAcknowledge() { return mcfProperties.isPreAcknowledge(); } - public void setPreAcknowledge(final Boolean preAcknowledge) - { + public void setPreAcknowledge(final Boolean preAcknowledge) { mcfProperties.setPreAcknowledge(preAcknowledge); } - public Long getRetryInterval() - { + public Long getRetryInterval() { return mcfProperties.getRetryInterval(); } - public void setRetryInterval(final Long retryInterval) - { + public void setRetryInterval(final Long retryInterval) { mcfProperties.setRetryInterval(retryInterval); } - public Double getRetryIntervalMultiplier() - { + public Double getRetryIntervalMultiplier() { return mcfProperties.getRetryIntervalMultiplier(); } - public void setRetryIntervalMultiplier(final Double retryIntervalMultiplier) - { + public void setRetryIntervalMultiplier(final Double retryIntervalMultiplier) { mcfProperties.setRetryIntervalMultiplier(retryIntervalMultiplier); } - public Integer getReconnectAttempts() - { + public Integer getReconnectAttempts() { return mcfProperties.getReconnectAttempts(); } - public void setReconnectAttempts(final Integer reconnectAttempts) - { + public void setReconnectAttempts(final Integer reconnectAttempts) { mcfProperties.setReconnectAttempts(reconnectAttempts); } - public Boolean isUseGlobalPools() - { + public Boolean isUseGlobalPools() { return mcfProperties.isUseGlobalPools(); } - public void setUseGlobalPools(final Boolean useGlobalPools) - { + public void setUseGlobalPools(final Boolean useGlobalPools) { mcfProperties.setUseGlobalPools(useGlobalPools); } - public Integer getScheduledThreadPoolMaxSize() - { + public Integer getScheduledThreadPoolMaxSize() { return mcfProperties.getScheduledThreadPoolMaxSize(); } - public void setScheduledThreadPoolMaxSize(final Integer scheduledThreadPoolMaxSize) - { + public void setScheduledThreadPoolMaxSize(final Integer scheduledThreadPoolMaxSize) { mcfProperties.setScheduledThreadPoolMaxSize(scheduledThreadPoolMaxSize); } - public Integer getThreadPoolMaxSize() - { + public Integer getThreadPoolMaxSize() { return mcfProperties.getThreadPoolMaxSize(); } - public void setThreadPoolMaxSize(final Integer threadPoolMaxSize) - { + public void setThreadPoolMaxSize(final Integer threadPoolMaxSize) { mcfProperties.setThreadPoolMaxSize(threadPoolMaxSize); } - public Boolean isHA() - { + public Boolean isHA() { return mcfProperties.isHA(); } - public void setHA(Boolean ha) - { + public void setHA(Boolean ha) { mcfProperties.setHA(ha); } @@ -707,10 +602,8 @@ public final class ActiveMQRAManagedConnectionFactory implements ManagedConnecti * * @return the useTryLock. */ - public Integer getUseTryLock() - { - if (ActiveMQRAManagedConnectionFactory.trace) - { + public Integer getUseTryLock() { + if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("getUseTryLock()"); } @@ -722,10 +615,8 @@ public final class ActiveMQRAManagedConnectionFactory implements ManagedConnecti * * @param useTryLock the useTryLock. */ - public void setUseTryLock(final Integer useTryLock) - { - if (ActiveMQRAManagedConnectionFactory.trace) - { + public void setUseTryLock(final Integer useTryLock) { + if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("setUseTryLock(" + useTryLock + ")"); } @@ -737,10 +628,8 @@ public final class ActiveMQRAManagedConnectionFactory implements ManagedConnecti * * @return The metadata */ - public ConnectionMetaData getMetaData() - { - if (ActiveMQRAManagedConnectionFactory.trace) - { + public ConnectionMetaData getMetaData() { + if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("getMetadata()"); } @@ -752,10 +641,8 @@ public final class ActiveMQRAManagedConnectionFactory implements ManagedConnecti * * @return The properties */ - protected ActiveMQRAMCFProperties getProperties() - { - if (ActiveMQRAManagedConnectionFactory.trace) - { + protected ActiveMQRAMCFProperties getProperties() { + if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("getProperties()"); } @@ -768,20 +655,16 @@ public final class ActiveMQRAManagedConnectionFactory implements ManagedConnecti * @param info The instance that should be updated; may be null * @return The instance */ - private ActiveMQRAConnectionRequestInfo getCRI(final ActiveMQRAConnectionRequestInfo info) - { - if (ActiveMQRAManagedConnectionFactory.trace) - { + private ActiveMQRAConnectionRequestInfo getCRI(final ActiveMQRAConnectionRequestInfo info) { + if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("getCRI(" + info + ")"); } - if (info == null) - { + if (info == null) { // Create a default one return new ActiveMQRAConnectionRequestInfo(ra.getProperties(), mcfProperties.getType()); } - else - { + else { // Fill the one with any defaults info.setDefaults(ra.getProperties()); return info; @@ -789,15 +672,12 @@ public final class ActiveMQRAManagedConnectionFactory implements ManagedConnecti } // this should be called when ActiveMQResourceAdapter.stop() is called since this MCF is registered with it - public void stop() - { - if (resourceRecovery != null) - { + public void stop() { + if (resourceRecovery != null) { ra.getRecoveryManager().unRegister(resourceRecovery); } - if (recoveryConnectionFactory != null) - { + if (recoveryConnectionFactory != null) { recoveryConnectionFactory.close(); recoveryConnectionFactory = null; } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMapMessage.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMapMessage.java index f6498011b3..a507a63f8c 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMapMessage.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMapMessage.java @@ -22,13 +22,14 @@ import java.util.Enumeration; import javax.jms.JMSException; import javax.jms.MapMessage; - /** * A wrapper for a message */ -public class ActiveMQRAMapMessage extends ActiveMQRAMessage implements MapMessage -{ - /** Whether trace is enabled */ +public class ActiveMQRAMapMessage extends ActiveMQRAMessage implements MapMessage { + + /** + * Whether trace is enabled + */ private static boolean trace = ActiveMQRALogger.LOGGER.isTraceEnabled(); /** @@ -37,416 +38,389 @@ public class ActiveMQRAMapMessage extends ActiveMQRAMessage implements MapMessag * @param message the message * @param session the session */ - public ActiveMQRAMapMessage(final MapMessage message, final ActiveMQRASession session) - { + public ActiveMQRAMapMessage(final MapMessage message, final ActiveMQRASession session) { super(message, session); - if (ActiveMQRAMapMessage.trace) - { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("constructor(" + message + ", " + session + ")"); } } /** * Get + * * @param name The name * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public boolean getBoolean(final String name) throws JMSException - { - if (ActiveMQRAMapMessage.trace) - { + public boolean getBoolean(final String name) throws JMSException { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("getBoolean(" + name + ")"); } - return ((MapMessage)message).getBoolean(name); + return ((MapMessage) message).getBoolean(name); } /** * Get + * * @param name The name * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public byte getByte(final String name) throws JMSException - { - if (ActiveMQRAMapMessage.trace) - { + public byte getByte(final String name) throws JMSException { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("getByte(" + name + ")"); } - return ((MapMessage)message).getByte(name); + return ((MapMessage) message).getByte(name); } /** * Get + * * @param name The name * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public byte[] getBytes(final String name) throws JMSException - { - if (ActiveMQRAMapMessage.trace) - { + public byte[] getBytes(final String name) throws JMSException { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("getBytes(" + name + ")"); } - return ((MapMessage)message).getBytes(name); + return ((MapMessage) message).getBytes(name); } /** * Get + * * @param name The name * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public char getChar(final String name) throws JMSException - { - if (ActiveMQRAMapMessage.trace) - { + public char getChar(final String name) throws JMSException { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("getChar(" + name + ")"); } - return ((MapMessage)message).getChar(name); + return ((MapMessage) message).getChar(name); } /** * Get + * * @param name The name * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public double getDouble(final String name) throws JMSException - { - if (ActiveMQRAMapMessage.trace) - { + public double getDouble(final String name) throws JMSException { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("getDouble(" + name + ")"); } - return ((MapMessage)message).getDouble(name); + return ((MapMessage) message).getDouble(name); } /** * Get + * * @param name The name * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public float getFloat(final String name) throws JMSException - { - if (ActiveMQRAMapMessage.trace) - { + public float getFloat(final String name) throws JMSException { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("getFloat(" + name + ")"); } - return ((MapMessage)message).getFloat(name); + return ((MapMessage) message).getFloat(name); } /** * Get + * * @param name The name * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public int getInt(final String name) throws JMSException - { - if (ActiveMQRAMapMessage.trace) - { + public int getInt(final String name) throws JMSException { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("getInt(" + name + ")"); } - return ((MapMessage)message).getInt(name); + return ((MapMessage) message).getInt(name); } /** * Get + * * @param name The name * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public long getLong(final String name) throws JMSException - { - if (ActiveMQRAMapMessage.trace) - { + public long getLong(final String name) throws JMSException { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("getLong(" + name + ")"); } - return ((MapMessage)message).getLong(name); + return ((MapMessage) message).getLong(name); } /** * Get the map names + * * @return The values - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ @SuppressWarnings("rawtypes") - public Enumeration getMapNames() throws JMSException - { - if (ActiveMQRAMapMessage.trace) - { + public Enumeration getMapNames() throws JMSException { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("getMapNames()"); } - return ((MapMessage)message).getMapNames(); + return ((MapMessage) message).getMapNames(); } /** * Get + * * @param name The name * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public Object getObject(final String name) throws JMSException - { - if (ActiveMQRAMapMessage.trace) - { + public Object getObject(final String name) throws JMSException { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("getObject(" + name + ")"); } - return ((MapMessage)message).getObject(name); + return ((MapMessage) message).getObject(name); } /** * Get + * * @param name The name * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public short getShort(final String name) throws JMSException - { - if (ActiveMQRAMapMessage.trace) - { + public short getShort(final String name) throws JMSException { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("getShort(" + name + ")"); } - return ((MapMessage)message).getShort(name); + return ((MapMessage) message).getShort(name); } /** * Get + * * @param name The name * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public String getString(final String name) throws JMSException - { - if (ActiveMQRAMapMessage.trace) - { + public String getString(final String name) throws JMSException { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("getString(" + name + ")"); } - return ((MapMessage)message).getString(name); + return ((MapMessage) message).getString(name); } /** * Does the item exist + * * @param name The name * @return True / false - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public boolean itemExists(final String name) throws JMSException - { - if (ActiveMQRAMapMessage.trace) - { + public boolean itemExists(final String name) throws JMSException { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("itemExists(" + name + ")"); } - return ((MapMessage)message).itemExists(name); + return ((MapMessage) message).itemExists(name); } /** * Set - * @param name The name + * + * @param name The name * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void setBoolean(final String name, final boolean value) throws JMSException - { - if (ActiveMQRAMapMessage.trace) - { + public void setBoolean(final String name, final boolean value) throws JMSException { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("setBoolean(" + name + ", " + value + ")"); } - ((MapMessage)message).setBoolean(name, value); + ((MapMessage) message).setBoolean(name, value); } /** * Set - * @param name The name + * + * @param name The name * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void setByte(final String name, final byte value) throws JMSException - { - if (ActiveMQRAMapMessage.trace) - { + public void setByte(final String name, final byte value) throws JMSException { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("setByte(" + name + ", " + value + ")"); } - ((MapMessage)message).setByte(name, value); + ((MapMessage) message).setByte(name, value); } /** * Set - * @param name The name - * @param value The value + * + * @param name The name + * @param value The value * @param offset The offset * @param length The length - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void setBytes(final String name, final byte[] value, final int offset, final int length) throws JMSException - { - if (ActiveMQRAMapMessage.trace) - { + public void setBytes(final String name, final byte[] value, final int offset, final int length) throws JMSException { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("setBytes(" + name + ", " + Arrays.toString(value) + ", " + offset + ", " + - length + ")"); + length + ")"); } - ((MapMessage)message).setBytes(name, value, offset, length); + ((MapMessage) message).setBytes(name, value, offset, length); } /** * Set - * @param name The name + * + * @param name The name * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void setBytes(final String name, final byte[] value) throws JMSException - { - if (ActiveMQRAMapMessage.trace) - { + public void setBytes(final String name, final byte[] value) throws JMSException { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("setBytes(" + name + ", " + Arrays.toString(value) + ")"); } - ((MapMessage)message).setBytes(name, value); + ((MapMessage) message).setBytes(name, value); } /** * Set - * @param name The name + * + * @param name The name * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void setChar(final String name, final char value) throws JMSException - { - if (ActiveMQRAMapMessage.trace) - { + public void setChar(final String name, final char value) throws JMSException { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("setChar(" + name + ", " + value + ")"); } - ((MapMessage)message).setChar(name, value); + ((MapMessage) message).setChar(name, value); } /** * Set - * @param name The name + * + * @param name The name * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void setDouble(final String name, final double value) throws JMSException - { - if (ActiveMQRAMapMessage.trace) - { + public void setDouble(final String name, final double value) throws JMSException { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("setDouble(" + name + ", " + value + ")"); } - ((MapMessage)message).setDouble(name, value); + ((MapMessage) message).setDouble(name, value); } /** * Set - * @param name The name + * + * @param name The name * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void setFloat(final String name, final float value) throws JMSException - { - if (ActiveMQRAMapMessage.trace) - { + public void setFloat(final String name, final float value) throws JMSException { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("setFloat(" + name + ", " + value + ")"); } - ((MapMessage)message).setFloat(name, value); + ((MapMessage) message).setFloat(name, value); } /** * Set - * @param name The name + * + * @param name The name * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void setInt(final String name, final int value) throws JMSException - { - if (ActiveMQRAMapMessage.trace) - { + public void setInt(final String name, final int value) throws JMSException { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("setInt(" + name + ", " + value + ")"); } - ((MapMessage)message).setInt(name, value); + ((MapMessage) message).setInt(name, value); } /** * Set - * @param name The name + * + * @param name The name * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void setLong(final String name, final long value) throws JMSException - { - if (ActiveMQRAMapMessage.trace) - { + public void setLong(final String name, final long value) throws JMSException { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("setLong(" + name + ", " + value + ")"); } - ((MapMessage)message).setLong(name, value); + ((MapMessage) message).setLong(name, value); } /** * Set - * @param name The name + * + * @param name The name * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void setObject(final String name, final Object value) throws JMSException - { - if (ActiveMQRAMapMessage.trace) - { + public void setObject(final String name, final Object value) throws JMSException { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("setObject(" + name + ", " + value + ")"); } - ((MapMessage)message).setObject(name, value); + ((MapMessage) message).setObject(name, value); } /** * Set - * @param name The name + * + * @param name The name * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void setShort(final String name, final short value) throws JMSException - { - if (ActiveMQRAMapMessage.trace) - { + public void setShort(final String name, final short value) throws JMSException { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("setShort(" + name + ", " + value + ")"); } - ((MapMessage)message).setShort(name, value); + ((MapMessage) message).setShort(name, value); } /** * Set - * @param name The name + * + * @param name The name * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void setString(final String name, final String value) throws JMSException - { - if (ActiveMQRAMapMessage.trace) - { + public void setString(final String name, final String value) throws JMSException { + if (ActiveMQRAMapMessage.trace) { ActiveMQRALogger.LOGGER.trace("setString(" + name + ", " + value + ")"); } - ((MapMessage)message).setString(name, value); + ((MapMessage) message).setString(name, value); } } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMessage.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMessage.java index dc61af3dac..e9f25ffbab 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMessage.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMessage.java @@ -22,12 +22,11 @@ import javax.jms.Message; import java.util.Arrays; import java.util.Enumeration; - /** * A wrapper for a message */ -public class ActiveMQRAMessage implements Message -{ +public class ActiveMQRAMessage implements Message { + /** * Whether trace is enabled */ @@ -49,10 +48,8 @@ public class ActiveMQRAMessage implements Message * @param message the message * @param session the session */ - public ActiveMQRAMessage(final Message message, final ActiveMQRASession session) - { - if (ActiveMQRAMessage.trace) - { + public ActiveMQRAMessage(final Message message, final ActiveMQRASession session) { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("constructor(" + message + ", " + session + ")"); } @@ -65,10 +62,8 @@ public class ActiveMQRAMessage implements Message * * @throws JMSException Thrown if an error occurs */ - public void acknowledge() throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public void acknowledge() throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("acknowledge()"); } @@ -81,10 +76,8 @@ public class ActiveMQRAMessage implements Message * * @throws JMSException Thrown if an error occurs */ - public void clearBody() throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public void clearBody() throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("clearBody()"); } @@ -96,10 +89,8 @@ public class ActiveMQRAMessage implements Message * * @throws JMSException Thrown if an error occurs */ - public void clearProperties() throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public void clearProperties() throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("clearProperties()"); } @@ -113,10 +104,8 @@ public class ActiveMQRAMessage implements Message * @return The value * @throws JMSException Thrown if an error occurs */ - public boolean getBooleanProperty(final String name) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public boolean getBooleanProperty(final String name) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("getBooleanProperty(" + name + ")"); } @@ -130,10 +119,8 @@ public class ActiveMQRAMessage implements Message * @return The value * @throws JMSException Thrown if an error occurs */ - public byte getByteProperty(final String name) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public byte getByteProperty(final String name) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("getByteProperty(" + name + ")"); } @@ -147,10 +134,8 @@ public class ActiveMQRAMessage implements Message * @return The value * @throws JMSException Thrown if an error occurs */ - public double getDoubleProperty(final String name) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public double getDoubleProperty(final String name) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("getDoubleProperty(" + name + ")"); } @@ -164,10 +149,8 @@ public class ActiveMQRAMessage implements Message * @return The value * @throws JMSException Thrown if an error occurs */ - public float getFloatProperty(final String name) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public float getFloatProperty(final String name) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("getFloatProperty(" + name + ")"); } @@ -181,10 +164,8 @@ public class ActiveMQRAMessage implements Message * @return The value * @throws JMSException Thrown if an error occurs */ - public int getIntProperty(final String name) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public int getIntProperty(final String name) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("getIntProperty(" + name + ")"); } @@ -197,10 +178,8 @@ public class ActiveMQRAMessage implements Message * @return The value * @throws JMSException Thrown if an error occurs */ - public String getJMSCorrelationID() throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public String getJMSCorrelationID() throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("getJMSCorrelationID()"); } @@ -213,10 +192,8 @@ public class ActiveMQRAMessage implements Message * @return The value * @throws JMSException Thrown if an error occurs */ - public byte[] getJMSCorrelationIDAsBytes() throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public byte[] getJMSCorrelationIDAsBytes() throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("getJMSCorrelationIDAsBytes()"); } @@ -229,10 +206,8 @@ public class ActiveMQRAMessage implements Message * @return The value * @throws JMSException Thrown if an error occurs */ - public int getJMSDeliveryMode() throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public int getJMSDeliveryMode() throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("getJMSDeliveryMode()"); } @@ -245,10 +220,8 @@ public class ActiveMQRAMessage implements Message * @return The value * @throws JMSException Thrown if an error occurs */ - public Destination getJMSDestination() throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public Destination getJMSDestination() throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("getJMSDestination()"); } @@ -261,10 +234,8 @@ public class ActiveMQRAMessage implements Message * @return The value * @throws JMSException Thrown if an error occurs */ - public long getJMSExpiration() throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public long getJMSExpiration() throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("getJMSExpiration()"); } @@ -277,10 +248,8 @@ public class ActiveMQRAMessage implements Message * @return The value * @throws JMSException Thrown if an error occurs */ - public String getJMSMessageID() throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public String getJMSMessageID() throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("getJMSMessageID()"); } @@ -293,10 +262,8 @@ public class ActiveMQRAMessage implements Message * @return The value * @throws JMSException Thrown if an error occurs */ - public int getJMSPriority() throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public int getJMSPriority() throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("getJMSPriority()"); } @@ -309,10 +276,8 @@ public class ActiveMQRAMessage implements Message * @return The value * @throws JMSException Thrown if an error occurs */ - public boolean getJMSRedelivered() throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public boolean getJMSRedelivered() throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("getJMSRedelivered()"); } @@ -325,10 +290,8 @@ public class ActiveMQRAMessage implements Message * @return The value * @throws JMSException Thrown if an error occurs */ - public Destination getJMSReplyTo() throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public Destination getJMSReplyTo() throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("getJMSReplyTo()"); } @@ -341,10 +304,8 @@ public class ActiveMQRAMessage implements Message * @return The value * @throws JMSException Thrown if an error occurs */ - public long getJMSTimestamp() throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public long getJMSTimestamp() throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("getJMSTimestamp()"); } @@ -357,10 +318,8 @@ public class ActiveMQRAMessage implements Message * @return The value * @throws JMSException Thrown if an error occurs */ - public String getJMSType() throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public String getJMSType() throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("getJMSType()"); } @@ -374,10 +333,8 @@ public class ActiveMQRAMessage implements Message * @return The value * @throws JMSException Thrown if an error occurs */ - public long getLongProperty(final String name) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public long getLongProperty(final String name) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("getLongProperty(" + name + ")"); } @@ -391,10 +348,8 @@ public class ActiveMQRAMessage implements Message * @return The value * @throws JMSException Thrown if an error occurs */ - public Object getObjectProperty(final String name) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public Object getObjectProperty(final String name) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("getObjectProperty(" + name + ")"); } @@ -408,10 +363,8 @@ public class ActiveMQRAMessage implements Message * @throws JMSException Thrown if an error occurs */ @SuppressWarnings("rawtypes") - public Enumeration getPropertyNames() throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public Enumeration getPropertyNames() throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("getPropertyNames()"); } @@ -425,10 +378,8 @@ public class ActiveMQRAMessage implements Message * @return The value * @throws JMSException Thrown if an error occurs */ - public short getShortProperty(final String name) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public short getShortProperty(final String name) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("getShortProperty(" + name + ")"); } @@ -442,10 +393,8 @@ public class ActiveMQRAMessage implements Message * @return The value * @throws JMSException Thrown if an error occurs */ - public String getStringProperty(final String name) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public String getStringProperty(final String name) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("getStringProperty(" + name + ")"); } @@ -459,10 +408,8 @@ public class ActiveMQRAMessage implements Message * @return The value * @throws JMSException Thrown if an error occurs */ - public boolean propertyExists(final String name) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public boolean propertyExists(final String name) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("propertyExists(" + name + ")"); } @@ -476,10 +423,8 @@ public class ActiveMQRAMessage implements Message * @param value The value * @throws JMSException Thrown if an error occurs */ - public void setBooleanProperty(final String name, final boolean value) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public void setBooleanProperty(final String name, final boolean value) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("setBooleanProperty(" + name + ", " + value + ")"); } @@ -493,10 +438,8 @@ public class ActiveMQRAMessage implements Message * @param value The value * @throws JMSException Thrown if an error occurs */ - public void setByteProperty(final String name, final byte value) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public void setByteProperty(final String name, final byte value) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("setByteProperty(" + name + ", " + value + ")"); } @@ -510,10 +453,8 @@ public class ActiveMQRAMessage implements Message * @param value The value * @throws JMSException Thrown if an error occurs */ - public void setDoubleProperty(final String name, final double value) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public void setDoubleProperty(final String name, final double value) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("setDoubleProperty(" + name + ", " + value + ")"); } @@ -527,10 +468,8 @@ public class ActiveMQRAMessage implements Message * @param value The value * @throws JMSException Thrown if an error occurs */ - public void setFloatProperty(final String name, final float value) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public void setFloatProperty(final String name, final float value) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("setFloatProperty(" + name + ", " + value + ")"); } @@ -544,10 +483,8 @@ public class ActiveMQRAMessage implements Message * @param value The value * @throws JMSException Thrown if an error occurs */ - public void setIntProperty(final String name, final int value) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public void setIntProperty(final String name, final int value) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("setIntProperty(" + name + ", " + value + ")"); } @@ -560,10 +497,8 @@ public class ActiveMQRAMessage implements Message * @param correlationID The value * @throws JMSException Thrown if an error occurs */ - public void setJMSCorrelationID(final String correlationID) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public void setJMSCorrelationID(final String correlationID) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("setJMSCorrelationID(" + correlationID + ")"); } @@ -576,10 +511,8 @@ public class ActiveMQRAMessage implements Message * @param correlationID The value * @throws JMSException Thrown if an error occurs */ - public void setJMSCorrelationIDAsBytes(final byte[] correlationID) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public void setJMSCorrelationIDAsBytes(final byte[] correlationID) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("setJMSCorrelationIDAsBytes(" + Arrays.toString(correlationID) + ")"); } @@ -592,10 +525,8 @@ public class ActiveMQRAMessage implements Message * @param deliveryMode The value * @throws JMSException Thrown if an error occurs */ - public void setJMSDeliveryMode(final int deliveryMode) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public void setJMSDeliveryMode(final int deliveryMode) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("setJMSDeliveryMode(" + deliveryMode + ")"); } @@ -608,10 +539,8 @@ public class ActiveMQRAMessage implements Message * @param destination The value * @throws JMSException Thrown if an error occurs */ - public void setJMSDestination(final Destination destination) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public void setJMSDestination(final Destination destination) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("setJMSDestination(" + destination + ")"); } @@ -624,10 +553,8 @@ public class ActiveMQRAMessage implements Message * @param expiration The value * @throws JMSException Thrown if an error occurs */ - public void setJMSExpiration(final long expiration) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public void setJMSExpiration(final long expiration) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("setJMSExpiration(" + expiration + ")"); } @@ -640,10 +567,8 @@ public class ActiveMQRAMessage implements Message * @param id The value * @throws JMSException Thrown if an error occurs */ - public void setJMSMessageID(final String id) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public void setJMSMessageID(final String id) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("setJMSMessageID(" + id + ")"); } @@ -656,10 +581,8 @@ public class ActiveMQRAMessage implements Message * @param priority The value * @throws JMSException Thrown if an error occurs */ - public void setJMSPriority(final int priority) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public void setJMSPriority(final int priority) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("setJMSPriority(" + priority + ")"); } @@ -672,10 +595,8 @@ public class ActiveMQRAMessage implements Message * @param redelivered The value * @throws JMSException Thrown if an error occurs */ - public void setJMSRedelivered(final boolean redelivered) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public void setJMSRedelivered(final boolean redelivered) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("setJMSRedelivered(" + redelivered + ")"); } @@ -688,10 +609,8 @@ public class ActiveMQRAMessage implements Message * @param replyTo The value * @throws JMSException Thrown if an error occurs */ - public void setJMSReplyTo(final Destination replyTo) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public void setJMSReplyTo(final Destination replyTo) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("setJMSReplyTo(" + replyTo + ")"); } @@ -704,10 +623,8 @@ public class ActiveMQRAMessage implements Message * @param timestamp The value * @throws JMSException Thrown if an error occurs */ - public void setJMSTimestamp(final long timestamp) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public void setJMSTimestamp(final long timestamp) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("setJMSTimestamp(" + timestamp + ")"); } @@ -720,10 +637,8 @@ public class ActiveMQRAMessage implements Message * @param type The value * @throws JMSException Thrown if an error occurs */ - public void setJMSType(final String type) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public void setJMSType(final String type) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("setJMSType(" + type + ")"); } @@ -737,10 +652,8 @@ public class ActiveMQRAMessage implements Message * @param value The value * @throws JMSException Thrown if an error occurs */ - public void setLongProperty(final String name, final long value) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public void setLongProperty(final String name, final long value) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("setLongProperty(" + name + ", " + value + ")"); } @@ -754,10 +667,8 @@ public class ActiveMQRAMessage implements Message * @param value The value * @throws JMSException Thrown if an error occurs */ - public void setObjectProperty(final String name, final Object value) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public void setObjectProperty(final String name, final Object value) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("setObjectProperty(" + name + ", " + value + ")"); } @@ -771,10 +682,8 @@ public class ActiveMQRAMessage implements Message * @param value The value * @throws JMSException Thrown if an error occurs */ - public void setShortProperty(final String name, final short value) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public void setShortProperty(final String name, final short value) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("setShortProperty(" + name + ", " + value + ")"); } @@ -788,10 +697,8 @@ public class ActiveMQRAMessage implements Message * @param value The value * @throws JMSException Thrown if an error occurs */ - public void setStringProperty(final String name, final String value) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public void setStringProperty(final String name, final String value) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("setStringProperty(" + name + ", " + value + ")"); } @@ -799,42 +706,33 @@ public class ActiveMQRAMessage implements Message } @Override - public long getJMSDeliveryTime() throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public long getJMSDeliveryTime() throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("getJMSDeliveryTime()"); } return message.getJMSDeliveryTime(); } @Override - public void setJMSDeliveryTime(long deliveryTime) throws JMSException - { + public void setJMSDeliveryTime(long deliveryTime) throws JMSException { - if (ActiveMQRAMessage.trace) - { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("setJMSDeliveryTime(" + deliveryTime + ")"); } message.setJMSDeliveryTime(deliveryTime); } @Override - public T getBody(Class c) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public T getBody(Class c) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("getBody(" + c + ")"); } return message.getBody(c); } @Override - public boolean isBodyAssignableTo(@SuppressWarnings("rawtypes") - Class c) throws JMSException - { - if (ActiveMQRAMessage.trace) - { + public boolean isBodyAssignableTo(@SuppressWarnings("rawtypes") Class c) throws JMSException { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("isBodyAssignableTo(" + c + ")"); } return message.isBodyAssignableTo(c); @@ -846,10 +744,8 @@ public class ActiveMQRAMessage implements Message * @return The hash code */ @Override - public int hashCode() - { - if (ActiveMQRAMessage.trace) - { + public int hashCode() { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("hashCode()"); } @@ -863,19 +759,15 @@ public class ActiveMQRAMessage implements Message * @return True / false */ @Override - public boolean equals(final Object object) - { - if (ActiveMQRAMessage.trace) - { + public boolean equals(final Object object) { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("equals(" + object + ")"); } - if (object != null && object instanceof ActiveMQRAMessage) - { - return message.equals(((ActiveMQRAMessage)object).message); + if (object != null && object instanceof ActiveMQRAMessage) { + return message.equals(((ActiveMQRAMessage) object).message); } - else - { + else { return message.equals(object); } } @@ -886,10 +778,8 @@ public class ActiveMQRAMessage implements Message * @return The string */ @Override - public String toString() - { - if (ActiveMQRAMessage.trace) - { + public String toString() { + if (ActiveMQRAMessage.trace) { ActiveMQRALogger.LOGGER.trace("toString()"); } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMessageConsumer.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMessageConsumer.java index bda4f84a7f..957cbdc833 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMessageConsumer.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMessageConsumer.java @@ -26,69 +26,69 @@ import javax.jms.ObjectMessage; import javax.jms.StreamMessage; import javax.jms.TextMessage; - /** * A wrapper for a message consumer */ -public class ActiveMQRAMessageConsumer implements MessageConsumer -{ - /** Whether trace is enabled */ +public class ActiveMQRAMessageConsumer implements MessageConsumer { + + /** + * Whether trace is enabled + */ private static boolean trace = ActiveMQRALogger.LOGGER.isTraceEnabled(); - /** The wrapped message consumer */ + /** + * The wrapped message consumer + */ protected MessageConsumer consumer; - /** The session for this consumer */ + /** + * The session for this consumer + */ protected ActiveMQRASession session; /** * Create a new wrapper + * * @param consumer the consumer - * @param session the session + * @param session the session */ - public ActiveMQRAMessageConsumer(final MessageConsumer consumer, final ActiveMQRASession session) - { + public ActiveMQRAMessageConsumer(final MessageConsumer consumer, final ActiveMQRASession session) { this.consumer = consumer; this.session = session; - if (ActiveMQRAMessageConsumer.trace) - { + if (ActiveMQRAMessageConsumer.trace) { ActiveMQRALogger.LOGGER.trace("new ActiveMQMessageConsumer " + this + - " consumer=" + - consumer + - " session=" + - session); + " consumer=" + + consumer + + " session=" + + session); } } /** * Close - * @exception JMSException Thrown if an error occurs + * + * @throws JMSException Thrown if an error occurs */ - public void close() throws JMSException - { - if (ActiveMQRAMessageConsumer.trace) - { + public void close() throws JMSException { + if (ActiveMQRAMessageConsumer.trace) { ActiveMQRALogger.LOGGER.trace("close " + this); } - try - { + try { closeConsumer(); } - finally - { + finally { session.removeConsumer(this); } } /** * Check state - * @exception JMSException Thrown if an error occurs + * + * @throws JMSException Thrown if an error occurs */ - void checkState() throws JMSException - { - if (ActiveMQRAMessageConsumer.trace) - { + void checkState() throws JMSException { + if (ActiveMQRAMessageConsumer.trace) { ActiveMQRALogger.LOGGER.trace("checkState()"); } session.checkState(); @@ -96,13 +96,12 @@ public class ActiveMQRAMessageConsumer implements MessageConsumer /** * Get message listener + * * @return The listener - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public MessageListener getMessageListener() throws JMSException - { - if (ActiveMQRAMessageConsumer.trace) - { + public MessageListener getMessageListener() throws JMSException { + if (ActiveMQRAMessageConsumer.trace) { ActiveMQRALogger.LOGGER.trace("getMessageListener()"); } @@ -113,40 +112,35 @@ public class ActiveMQRAMessageConsumer implements MessageConsumer /** * Set message listener + * * @param listener The listener - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void setMessageListener(final MessageListener listener) throws JMSException - { + public void setMessageListener(final MessageListener listener) throws JMSException { session.lock(); - try - { + try { checkState(); session.checkStrict(); - if (listener == null) - { + if (listener == null) { consumer.setMessageListener(null); } - else - { + else { consumer.setMessageListener(wrapMessageListener(listener)); } } - finally - { + finally { session.unlock(); } } /** * Get message selector + * * @return The selector - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public String getMessageSelector() throws JMSException - { - if (ActiveMQRAMessageConsumer.trace) - { + public String getMessageSelector() throws JMSException { + if (ActiveMQRAMessageConsumer.trace) { ActiveMQRALogger.LOGGER.trace("getMessageSelector()"); } @@ -156,127 +150,108 @@ public class ActiveMQRAMessageConsumer implements MessageConsumer /** * Receive + * * @return The message - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public Message receive() throws JMSException - { + public Message receive() throws JMSException { session.lock(); - try - { - if (ActiveMQRAMessageConsumer.trace) - { + try { + if (ActiveMQRAMessageConsumer.trace) { ActiveMQRALogger.LOGGER.trace("receive " + this); } checkState(); Message message = consumer.receive(); - if (ActiveMQRAMessageConsumer.trace) - { + if (ActiveMQRAMessageConsumer.trace) { ActiveMQRALogger.LOGGER.trace("received " + this + " result=" + message); } - if (message == null) - { + if (message == null) { return null; } - else - { + else { return wrapMessage(message); } } - finally - { + finally { session.unlock(); } } /** * Receive + * * @param timeout The timeout value * @return The message - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public Message receive(final long timeout) throws JMSException - { + public Message receive(final long timeout) throws JMSException { session.lock(); - try - { - if (ActiveMQRAMessageConsumer.trace) - { + try { + if (ActiveMQRAMessageConsumer.trace) { ActiveMQRALogger.LOGGER.trace("receive " + this + " timeout=" + timeout); } checkState(); Message message = consumer.receive(timeout); - if (ActiveMQRAMessageConsumer.trace) - { + if (ActiveMQRAMessageConsumer.trace) { ActiveMQRALogger.LOGGER.trace("received " + this + " result=" + message); } - if (message == null) - { + if (message == null) { return null; } - else - { + else { return wrapMessage(message); } } - finally - { + finally { session.unlock(); } } /** * Receive + * * @return The message - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public Message receiveNoWait() throws JMSException - { + public Message receiveNoWait() throws JMSException { session.lock(); - try - { - if (ActiveMQRAMessageConsumer.trace) - { + try { + if (ActiveMQRAMessageConsumer.trace) { ActiveMQRALogger.LOGGER.trace("receiveNoWait " + this); } checkState(); Message message = consumer.receiveNoWait(); - if (ActiveMQRAMessageConsumer.trace) - { + if (ActiveMQRAMessageConsumer.trace) { ActiveMQRALogger.LOGGER.trace("received " + this + " result=" + message); } - if (message == null) - { + if (message == null) { return null; } - else - { + else { return wrapMessage(message); } } - finally - { + finally { session.unlock(); } } /** * Close consumer - * @exception JMSException Thrown if an error occurs + * + * @throws JMSException Thrown if an error occurs */ - void closeConsumer() throws JMSException - { - if (ActiveMQRAMessageConsumer.trace) - { + void closeConsumer() throws JMSException { + if (ActiveMQRAMessageConsumer.trace) { ActiveMQRALogger.LOGGER.trace("closeConsumer()"); } @@ -285,48 +260,41 @@ public class ActiveMQRAMessageConsumer implements MessageConsumer /** * Wrap message + * * @param message The message to be wrapped * @return The wrapped message */ - Message wrapMessage(final Message message) - { - if (ActiveMQRAMessageConsumer.trace) - { + Message wrapMessage(final Message message) { + if (ActiveMQRAMessageConsumer.trace) { ActiveMQRALogger.LOGGER.trace("wrapMessage(" + message + ")"); } - if (message instanceof BytesMessage) - { - return new ActiveMQRABytesMessage((BytesMessage)message, session); + if (message instanceof BytesMessage) { + return new ActiveMQRABytesMessage((BytesMessage) message, session); } - else if (message instanceof MapMessage) - { - return new ActiveMQRAMapMessage((MapMessage)message, session); + else if (message instanceof MapMessage) { + return new ActiveMQRAMapMessage((MapMessage) message, session); } - else if (message instanceof ObjectMessage) - { - return new ActiveMQRAObjectMessage((ObjectMessage)message, session); + else if (message instanceof ObjectMessage) { + return new ActiveMQRAObjectMessage((ObjectMessage) message, session); } - else if (message instanceof StreamMessage) - { - return new ActiveMQRAStreamMessage((StreamMessage)message, session); + else if (message instanceof StreamMessage) { + return new ActiveMQRAStreamMessage((StreamMessage) message, session); } - else if (message instanceof TextMessage) - { - return new ActiveMQRATextMessage((TextMessage)message, session); + else if (message instanceof TextMessage) { + return new ActiveMQRATextMessage((TextMessage) message, session); } return new ActiveMQRAMessage(message, session); } /** * Wrap message listener + * * @param listener The listener to be wrapped * @return The wrapped listener */ - MessageListener wrapMessageListener(final MessageListener listener) - { - if (ActiveMQRAMessageConsumer.trace) - { + MessageListener wrapMessageListener(final MessageListener listener) { + if (ActiveMQRAMessageConsumer.trace) { ActiveMQRALogger.LOGGER.trace("getMessageSelector()"); } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMessageListener.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMessageListener.java index d2bf2d6757..d6110d587f 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMessageListener.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMessageListener.java @@ -19,30 +19,34 @@ package org.apache.activemq.artemis.ra; import javax.jms.Message; import javax.jms.MessageListener; - /** * A wrapper for a message listener */ -public class ActiveMQRAMessageListener implements MessageListener -{ - /** Whether trace is enabled */ +public class ActiveMQRAMessageListener implements MessageListener { + + /** + * Whether trace is enabled + */ private static boolean trace = ActiveMQRALogger.LOGGER.isTraceEnabled(); - /** The message listener */ + /** + * The message listener + */ private final MessageListener listener; - /** The consumer */ + /** + * The consumer + */ private final ActiveMQRAMessageConsumer consumer; /** * Create a new wrapper + * * @param listener the listener * @param consumer the consumer */ - public ActiveMQRAMessageListener(final MessageListener listener, final ActiveMQRAMessageConsumer consumer) - { - if (ActiveMQRAMessageListener.trace) - { + public ActiveMQRAMessageListener(final MessageListener listener, final ActiveMQRAMessageConsumer consumer) { + if (ActiveMQRAMessageListener.trace) { ActiveMQRALogger.LOGGER.trace("constructor(" + listener + ", " + consumer + ")"); } @@ -52,12 +56,11 @@ public class ActiveMQRAMessageListener implements MessageListener /** * On message + * * @param message The message */ - public void onMessage(Message message) - { - if (ActiveMQRAMessageListener.trace) - { + public void onMessage(Message message) { + if (ActiveMQRAMessageListener.trace) { ActiveMQRALogger.LOGGER.trace("onMessage(" + message + ")"); } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMessageProducer.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMessageProducer.java index 1d10d18513..561245f033 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMessageProducer.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMessageProducer.java @@ -22,122 +22,117 @@ import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageProducer; - /** * ActiveMQMessageProducer. */ -public class ActiveMQRAMessageProducer implements MessageProducer -{ - /** Whether trace is enabled */ +public class ActiveMQRAMessageProducer implements MessageProducer { + + /** + * Whether trace is enabled + */ private static boolean trace = ActiveMQRALogger.LOGGER.isTraceEnabled(); - /** The wrapped message producer */ + /** + * The wrapped message producer + */ protected MessageProducer producer; - /** The session for this consumer */ + /** + * The session for this consumer + */ protected ActiveMQRASession session; /** * Create a new wrapper + * * @param producer the producer - * @param session the session + * @param session the session */ - public ActiveMQRAMessageProducer(final MessageProducer producer, final ActiveMQRASession session) - { + public ActiveMQRAMessageProducer(final MessageProducer producer, final ActiveMQRASession session) { this.producer = producer; this.session = session; - if (ActiveMQRAMessageProducer.trace) - { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("new ActiveMQMessageProducer " + this + - " producer=" + - producer + - " session=" + - session); + " producer=" + + producer + + " session=" + + session); } } /** * Close - * @exception JMSException Thrown if an error occurs + * + * @throws JMSException Thrown if an error occurs */ - public void close() throws JMSException - { - if (ActiveMQRAMessageProducer.trace) - { + public void close() throws JMSException { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("close " + this); } - try - { + try { closeProducer(); } - finally - { + finally { session.removeProducer(this); } } /** * Send message - * @param destination The destination - * @param message The message + * + * @param destination The destination + * @param message The message * @param deliveryMode The delivery mode - * @param priority The priority - * @param timeToLive The time to live - * @exception JMSException Thrown if an error occurs + * @param priority The priority + * @param timeToLive The time to live + * @throws JMSException Thrown if an error occurs */ public void send(final Destination destination, final Message message, final int deliveryMode, final int priority, - final long timeToLive) throws JMSException - { + final long timeToLive) throws JMSException { session.lock(); - try - { - if (ActiveMQRAMessageProducer.trace) - { + try { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("send " + this + - " destination=" + - destination + - " message=" + - message + - " deliveryMode=" + - deliveryMode + - " priority=" + - priority + - " ttl=" + - timeToLive); + " destination=" + + destination + + " message=" + + message + + " deliveryMode=" + + deliveryMode + + " priority=" + + priority + + " ttl=" + + timeToLive); } checkState(); producer.send(destination, message, deliveryMode, priority, timeToLive); - if (ActiveMQRAMessageProducer.trace) - { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("sent " + this + " result=" + message); } } - finally - { + finally { session.unlock(); } } /** * Send message + * * @param destination The destination - * @param message The message - * @exception JMSException Thrown if an error occurs + * @param message The message + * @throws JMSException Thrown if an error occurs */ - public void send(final Destination destination, final Message message) throws JMSException - { + public void send(final Destination destination, final Message message) throws JMSException { session.lock(); - try - { - if (ActiveMQRAMessageProducer.trace) - { + try { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("send " + this + " destination=" + destination + " message=" + message); } @@ -145,70 +140,65 @@ public class ActiveMQRAMessageProducer implements MessageProducer producer.send(destination, message); - if (ActiveMQRAMessageProducer.trace) - { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("sent " + this + " result=" + message); } } - finally - { + finally { session.unlock(); } } /** * Send message - * @param message The message + * + * @param message The message * @param deliveryMode The delivery mode - * @param priority The priority - * @param timeToLive The time to live - * @exception JMSException Thrown if an error occurs + * @param priority The priority + * @param timeToLive The time to live + * @throws JMSException Thrown if an error occurs */ - public void send(final Message message, final int deliveryMode, final int priority, final long timeToLive) throws JMSException - { + public void send(final Message message, + final int deliveryMode, + final int priority, + final long timeToLive) throws JMSException { session.lock(); - try - { - if (ActiveMQRAMessageProducer.trace) - { + try { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("send " + this + - " message=" + - message + - " deliveryMode=" + - deliveryMode + - " priority=" + - priority + - " ttl=" + - timeToLive); + " message=" + + message + + " deliveryMode=" + + deliveryMode + + " priority=" + + priority + + " ttl=" + + timeToLive); } checkState(); producer.send(message, deliveryMode, priority, timeToLive); - if (ActiveMQRAMessageProducer.trace) - { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("sent " + this + " result=" + message); } } - finally - { + finally { session.unlock(); } } /** * Send message + * * @param message The message - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void send(final Message message) throws JMSException - { + public void send(final Message message) throws JMSException { session.lock(); - try - { - if (ActiveMQRAMessageProducer.trace) - { + try { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("send " + this + " message=" + message); } @@ -216,26 +206,23 @@ public class ActiveMQRAMessageProducer implements MessageProducer producer.send(message); - if (ActiveMQRAMessageProducer.trace) - { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("sent " + this + " result=" + message); } } - finally - { + finally { session.unlock(); } } /** * Get the delivery mode + * * @return The mode - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public int getDeliveryMode() throws JMSException - { - if (ActiveMQRAMessageProducer.trace) - { + public int getDeliveryMode() throws JMSException { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("getDeliveryMode()"); } @@ -244,13 +231,12 @@ public class ActiveMQRAMessageProducer implements MessageProducer /** * Get the destination + * * @return The destination - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public Destination getDestination() throws JMSException - { - if (ActiveMQRAMessageProducer.trace) - { + public Destination getDestination() throws JMSException { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("getDestination()"); } @@ -259,13 +245,12 @@ public class ActiveMQRAMessageProducer implements MessageProducer /** * Disable message id + * * @return True if disable - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public boolean getDisableMessageID() throws JMSException - { - if (ActiveMQRAMessageProducer.trace) - { + public boolean getDisableMessageID() throws JMSException { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("getDisableMessageID()"); } @@ -274,13 +259,12 @@ public class ActiveMQRAMessageProducer implements MessageProducer /** * Disable message timestamp + * * @return True if disable - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public boolean getDisableMessageTimestamp() throws JMSException - { - if (ActiveMQRAMessageProducer.trace) - { + public boolean getDisableMessageTimestamp() throws JMSException { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("getDisableMessageTimestamp()"); } @@ -289,13 +273,12 @@ public class ActiveMQRAMessageProducer implements MessageProducer /** * Get the priority + * * @return The priority - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public int getPriority() throws JMSException - { - if (ActiveMQRAMessageProducer.trace) - { + public int getPriority() throws JMSException { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("getPriority()"); } @@ -304,13 +287,12 @@ public class ActiveMQRAMessageProducer implements MessageProducer /** * Get the time to live + * * @return The ttl - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public long getTimeToLive() throws JMSException - { - if (ActiveMQRAMessageProducer.trace) - { + public long getTimeToLive() throws JMSException { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("getTimeToLive()"); } @@ -319,13 +301,12 @@ public class ActiveMQRAMessageProducer implements MessageProducer /** * Set the delivery mode + * * @param deliveryMode The mode - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void setDeliveryMode(final int deliveryMode) throws JMSException - { - if (ActiveMQRAMessageProducer.trace) - { + public void setDeliveryMode(final int deliveryMode) throws JMSException { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("setDeliveryMode(" + deliveryMode + ")"); } @@ -334,13 +315,12 @@ public class ActiveMQRAMessageProducer implements MessageProducer /** * Set disable message id + * * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void setDisableMessageID(final boolean value) throws JMSException - { - if (ActiveMQRAMessageProducer.trace) - { + public void setDisableMessageID(final boolean value) throws JMSException { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("setDisableMessageID(" + value + ")"); } @@ -349,13 +329,12 @@ public class ActiveMQRAMessageProducer implements MessageProducer /** * Set disable message timestamp + * * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void setDisableMessageTimestamp(final boolean value) throws JMSException - { - if (ActiveMQRAMessageProducer.trace) - { + public void setDisableMessageTimestamp(final boolean value) throws JMSException { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("setDisableMessageTimestamp(" + value + ")"); } @@ -364,13 +343,12 @@ public class ActiveMQRAMessageProducer implements MessageProducer /** * Set the priority + * * @param defaultPriority The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void setPriority(final int defaultPriority) throws JMSException - { - if (ActiveMQRAMessageProducer.trace) - { + public void setPriority(final int defaultPriority) throws JMSException { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("setPriority(" + defaultPriority + ")"); } @@ -379,13 +357,12 @@ public class ActiveMQRAMessageProducer implements MessageProducer /** * Set the ttl + * * @param timeToLive The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void setTimeToLive(final long timeToLive) throws JMSException - { - if (ActiveMQRAMessageProducer.trace) - { + public void setTimeToLive(final long timeToLive) throws JMSException { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("setTimeToLive(" + timeToLive + ")"); } @@ -393,82 +370,81 @@ public class ActiveMQRAMessageProducer implements MessageProducer } @Override - public void setDeliveryDelay(long deliveryDelay) throws JMSException - { - if (ActiveMQRAMessageProducer.trace) - { + public void setDeliveryDelay(long deliveryDelay) throws JMSException { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("setDeliveryDelay(" + deliveryDelay + ")"); } producer.setDeliveryDelay(deliveryDelay); } @Override - public long getDeliveryDelay() throws JMSException - { - if (ActiveMQRAMessageProducer.trace) - { + public long getDeliveryDelay() throws JMSException { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("getDeliveryDelay()"); } return producer.getDeliveryDelay(); } @Override - public void send(Message message, CompletionListener completionListener) throws JMSException - { - if (ActiveMQRAMessageProducer.trace) - { + public void send(Message message, CompletionListener completionListener) throws JMSException { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("send(" + message + ", " + completionListener + ")"); } producer.send(message, completionListener); } @Override - public void send(Message message, int deliveryMode, int priority, long timeToLive, CompletionListener completionListener) throws JMSException - { - if (ActiveMQRAMessageProducer.trace) - { + public void send(Message message, + int deliveryMode, + int priority, + long timeToLive, + CompletionListener completionListener) throws JMSException { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("send(" + message + ", " + deliveryMode + ", " + priority + ", " + timeToLive + - ", " + completionListener + ")"); + ", " + completionListener + ")"); } producer.send(message, deliveryMode, priority, timeToLive, completionListener); } @Override - public void send(Destination destination, Message message, CompletionListener completionListener) throws JMSException - { - if (ActiveMQRAMessageProducer.trace) - { + public void send(Destination destination, + Message message, + CompletionListener completionListener) throws JMSException { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("send(" + destination + ", " + message + ", " + completionListener + ")"); } producer.send(destination, message, completionListener); } @Override - public void send(Destination destination, Message message, int deliveryMode, int priority, long timeToLive, CompletionListener completionListener) throws JMSException - { - if (ActiveMQRAMessageProducer.trace) - { + public void send(Destination destination, + Message message, + int deliveryMode, + int priority, + long timeToLive, + CompletionListener completionListener) throws JMSException { + if (ActiveMQRAMessageProducer.trace) { ActiveMQRALogger.LOGGER.trace("send(" + destination + ", " + message + ", " + deliveryMode + ", " + priority + - ", " + timeToLive + ", " + completionListener + ")"); + ", " + timeToLive + ", " + completionListener + ")"); } producer.send(destination, message, deliveryMode, priority, timeToLive, completionListener); } - /** + /** * Check state - * @exception JMSException Thrown if an error occurs + * + * @throws JMSException Thrown if an error occurs */ - void checkState() throws JMSException - { + void checkState() throws JMSException { session.checkState(); } /** * Close producer - * @exception JMSException Thrown if an error occurs + * + * @throws JMSException Thrown if an error occurs */ - void closeProducer() throws JMSException - { + void closeProducer() throws JMSException { producer.close(); } } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMetaData.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMetaData.java index 7fc15acd52..da33ca9388 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMetaData.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAMetaData.java @@ -19,26 +19,28 @@ package org.apache.activemq.artemis.ra; import javax.resource.ResourceException; import javax.resource.spi.ManagedConnectionMetaData; - /** * Managed connection meta data */ -public class ActiveMQRAMetaData implements ManagedConnectionMetaData -{ - /** Trace enabled */ +public class ActiveMQRAMetaData implements ManagedConnectionMetaData { + + /** + * Trace enabled + */ private static boolean trace = ActiveMQRALogger.LOGGER.isTraceEnabled(); - /** The managed connection */ + /** + * The managed connection + */ private final ActiveMQRAManagedConnection mc; /** * Constructor + * * @param mc The managed connection */ - public ActiveMQRAMetaData(final ActiveMQRAManagedConnection mc) - { - if (ActiveMQRAMetaData.trace) - { + public ActiveMQRAMetaData(final ActiveMQRAManagedConnection mc) { + if (ActiveMQRAMetaData.trace) { ActiveMQRALogger.LOGGER.trace("constructor(" + mc + ")"); } @@ -47,13 +49,12 @@ public class ActiveMQRAMetaData implements ManagedConnectionMetaData /** * Get the EIS product name + * * @return The name - * @exception ResourceException Thrown if operation fails + * @throws ResourceException Thrown if operation fails */ - public String getEISProductName() throws ResourceException - { - if (ActiveMQRAMetaData.trace) - { + public String getEISProductName() throws ResourceException { + if (ActiveMQRAMetaData.trace) { ActiveMQRALogger.LOGGER.trace("getEISProductName()"); } @@ -62,13 +63,12 @@ public class ActiveMQRAMetaData implements ManagedConnectionMetaData /** * Get the EIS product version + * * @return The version - * @exception ResourceException Thrown if operation fails + * @throws ResourceException Thrown if operation fails */ - public String getEISProductVersion() throws ResourceException - { - if (ActiveMQRAMetaData.trace) - { + public String getEISProductVersion() throws ResourceException { + if (ActiveMQRAMetaData.trace) { ActiveMQRALogger.LOGGER.trace("getEISProductVersion()"); } @@ -77,13 +77,12 @@ public class ActiveMQRAMetaData implements ManagedConnectionMetaData /** * Get the user name + * * @return The user name - * @exception ResourceException Thrown if operation fails + * @throws ResourceException Thrown if operation fails */ - public String getUserName() throws ResourceException - { - if (ActiveMQRAMetaData.trace) - { + public String getUserName() throws ResourceException { + if (ActiveMQRAMetaData.trace) { ActiveMQRALogger.LOGGER.trace("getUserName()"); } @@ -91,14 +90,13 @@ public class ActiveMQRAMetaData implements ManagedConnectionMetaData } /** - * Get the maximum number of connections -- RETURNS 0 - * @return The number - * @exception ResourceException Thrown if operation fails - */ - public int getMaxConnections() throws ResourceException - { - if (ActiveMQRAMetaData.trace) - { + * Get the maximum number of connections -- RETURNS 0 + * + * @return The number + * @throws ResourceException Thrown if operation fails + */ + public int getMaxConnections() throws ResourceException { + if (ActiveMQRAMetaData.trace) { ActiveMQRALogger.LOGGER.trace("getMaxConnections()"); } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAObjectMessage.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAObjectMessage.java index 5525663937..340450de92 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAObjectMessage.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAObjectMessage.java @@ -21,57 +21,55 @@ import java.io.Serializable; import javax.jms.JMSException; import javax.jms.ObjectMessage; - /** * A wrapper for a message */ -public class ActiveMQRAObjectMessage extends ActiveMQRAMessage implements ObjectMessage -{ - /** Whether trace is enabled */ +public class ActiveMQRAObjectMessage extends ActiveMQRAMessage implements ObjectMessage { + + /** + * Whether trace is enabled + */ private static boolean trace = ActiveMQRALogger.LOGGER.isTraceEnabled(); /** * Create a new wrapper + * * @param message the message * @param session the session */ - public ActiveMQRAObjectMessage(final ObjectMessage message, final ActiveMQRASession session) - { + public ActiveMQRAObjectMessage(final ObjectMessage message, final ActiveMQRASession session) { super(message, session); - if (ActiveMQRAObjectMessage.trace) - { + if (ActiveMQRAObjectMessage.trace) { ActiveMQRALogger.LOGGER.trace("constructor(" + message + ", " + session + ")"); } } /** * Get the object + * * @return The object - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public Serializable getObject() throws JMSException - { - if (ActiveMQRAObjectMessage.trace) - { + public Serializable getObject() throws JMSException { + if (ActiveMQRAObjectMessage.trace) { ActiveMQRALogger.LOGGER.trace("getObject()"); } - return ((ObjectMessage)message).getObject(); + return ((ObjectMessage) message).getObject(); } /** * Set the object + * * @param object The object - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void setObject(final Serializable object) throws JMSException - { - if (ActiveMQRAObjectMessage.trace) - { + public void setObject(final Serializable object) throws JMSException { + if (ActiveMQRAObjectMessage.trace) { ActiveMQRALogger.LOGGER.trace("setObject(" + object + ")"); } - ((ObjectMessage)message).setObject(object); + ((ObjectMessage) message).setObject(object); } } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAProperties.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAProperties.java index 76886b8979..a1046b9268 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAProperties.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAProperties.java @@ -24,12 +24,11 @@ import org.apache.activemq.artemis.utils.DefaultSensitiveStringCodec; import org.apache.activemq.artemis.utils.PasswordMaskingUtil; import org.apache.activemq.artemis.utils.SensitiveDataCodec; - /** * The RA default properties - these are set in the ra.xml file */ -public class ActiveMQRAProperties extends ConnectionFactoryProperties implements Serializable -{ +public class ActiveMQRAProperties extends ConnectionFactoryProperties implements Serializable { + /** * Serial version UID */ @@ -87,10 +86,8 @@ public class ActiveMQRAProperties extends ConnectionFactoryProperties implements /** * Constructor */ - public ActiveMQRAProperties() - { - if (ActiveMQRAProperties.trace) - { + public ActiveMQRAProperties() { + if (ActiveMQRAProperties.trace) { ActiveMQRALogger.LOGGER.trace("constructor()"); } } @@ -100,10 +97,8 @@ public class ActiveMQRAProperties extends ConnectionFactoryProperties implements * * @return The value */ - public String getUserName() - { - if (ActiveMQRAProperties.trace) - { + public String getUserName() { + if (ActiveMQRAProperties.trace) { ActiveMQRALogger.LOGGER.trace("getUserName()"); } @@ -115,10 +110,8 @@ public class ActiveMQRAProperties extends ConnectionFactoryProperties implements * * @param userName The value */ - public void setUserName(final String userName) - { - if (ActiveMQRAProperties.trace) - { + public void setUserName(final String userName) { + if (ActiveMQRAProperties.trace) { ActiveMQRALogger.LOGGER.trace("setUserName(" + userName + ")"); } @@ -130,10 +123,8 @@ public class ActiveMQRAProperties extends ConnectionFactoryProperties implements * * @return The value */ - public String getPassword() - { - if (ActiveMQRAProperties.trace) - { + public String getPassword() { + if (ActiveMQRAProperties.trace) { ActiveMQRALogger.LOGGER.trace("getPassword()"); } @@ -150,10 +141,8 @@ public class ActiveMQRAProperties extends ConnectionFactoryProperties implements * * @param password The value */ - public void setPassword(final String password) - { - if (ActiveMQRAProperties.trace) - { + public void setPassword(final String password) { + if (ActiveMQRAProperties.trace) { ActiveMQRALogger.LOGGER.trace("setPassword(****)"); } @@ -163,30 +152,25 @@ public class ActiveMQRAProperties extends ConnectionFactoryProperties implements /** * @return the useJNDI */ - public boolean isUseJNDI() - { + public boolean isUseJNDI() { return useJNDI; } /** * @param value the useJNDI to set */ - public void setUseJNDI(final Boolean value) - { + public void setUseJNDI(final Boolean value) { useJNDI = value; } /** * @return return the jndi params to use */ - public Hashtable getParsedJndiParams() - { + public Hashtable getParsedJndiParams() { return jndiParams; } - - public void setParsedJndiParams(Hashtable params) - { + public void setParsedJndiParams(Hashtable params) { jndiParams = params; } @@ -195,10 +179,8 @@ public class ActiveMQRAProperties extends ConnectionFactoryProperties implements * * @return The value */ - public Boolean getUseLocalTx() - { - if (ActiveMQRAProperties.trace) - { + public Boolean getUseLocalTx() { + if (ActiveMQRAProperties.trace) { ActiveMQRALogger.LOGGER.trace("getUseLocalTx()"); } @@ -210,86 +192,69 @@ public class ActiveMQRAProperties extends ConnectionFactoryProperties implements * * @param localTx The value */ - public void setUseLocalTx(final Boolean localTx) - { - if (ActiveMQRAProperties.trace) - { + public void setUseLocalTx(final Boolean localTx) { + if (ActiveMQRAProperties.trace) { ActiveMQRALogger.LOGGER.trace("setUseLocalTx(" + localTx + ")"); } this.localTx = localTx; } - public int getSetupAttempts() - { + public int getSetupAttempts() { return setupAttempts; } - public void setSetupAttempts(Integer setupAttempts) - { + public void setSetupAttempts(Integer setupAttempts) { this.setupAttempts = setupAttempts; } - public long getSetupInterval() - { + public long getSetupInterval() { return setupInterval; } - public void setSetupInterval(Long setupInterval) - { + public void setSetupInterval(Long setupInterval) { this.setupInterval = setupInterval; } - public boolean isUseMaskedPassword() - { + public boolean isUseMaskedPassword() { return useMaskedPassword; } - public void setUseMaskedPassword(boolean useMaskedPassword) - { + public void setUseMaskedPassword(boolean useMaskedPassword) { this.useMaskedPassword = useMaskedPassword; } - public String getPasswordCodec() - { + public String getPasswordCodec() { return passwordCodec; } - public void setPasswordCodec(String codecs) - { + public void setPasswordCodec(String codecs) { passwordCodec = codecs; } @Override - public String toString() - { + public String toString() { return "ActiveMQRAProperties[localTx=" + localTx + ", userName=" + userName + ", password=****]"; } - public synchronized void init() throws ActiveMQException - { + public synchronized void init() throws ActiveMQException { if (initialized) return; - if (useMaskedPassword) - { + if (useMaskedPassword) { codecInstance = new DefaultSensitiveStringCodec(); - if (passwordCodec != null) - { + if (passwordCodec != null) { codecInstance = PasswordMaskingUtil.getCodec(passwordCodec); } - try - { - if (password != null) - { + try { + if (password != null) { password = codecInstance.decode(password); } } - catch (Exception e) - { + catch (Exception e) { throw ActiveMQRABundle.BUNDLE.errorDecodingPassword(e); } @@ -297,28 +262,23 @@ public class ActiveMQRAProperties extends ConnectionFactoryProperties implements initialized = true; } - public SensitiveDataCodec getCodecInstance() - { + public SensitiveDataCodec getCodecInstance() { return codecInstance; } - public String getJgroupsChannelLocatorClass() - { + public String getJgroupsChannelLocatorClass() { return jgroupsChannelLocatorClass; } - public void setJgroupsChannelLocatorClass(String jgroupsChannelLocatorClass) - { + public void setJgroupsChannelLocatorClass(String jgroupsChannelLocatorClass) { this.jgroupsChannelLocatorClass = jgroupsChannelLocatorClass; } - public String getJgroupsChannelRefName() - { + public String getJgroupsChannelRefName() { return jgroupsChannelRefName; } - public void setJgroupsChannelRefName(String jgroupsChannelRefName) - { + public void setJgroupsChannelRefName(String jgroupsChannelRefName) { this.jgroupsChannelRefName = jgroupsChannelRefName; } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAQueueReceiver.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAQueueReceiver.java index 688ceac951..8bcf6ec782 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAQueueReceiver.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAQueueReceiver.java @@ -20,43 +20,42 @@ import javax.jms.JMSException; import javax.jms.Queue; import javax.jms.QueueReceiver; - /** * A wrapper for a queue receiver */ -public class ActiveMQRAQueueReceiver extends ActiveMQRAMessageConsumer implements QueueReceiver -{ - /** Whether trace is enabled */ +public class ActiveMQRAQueueReceiver extends ActiveMQRAMessageConsumer implements QueueReceiver { + + /** + * Whether trace is enabled + */ private static boolean trace = ActiveMQRALogger.LOGGER.isTraceEnabled(); /** * Create a new wrapper + * * @param consumer the queue receiver - * @param session the session + * @param session the session */ - public ActiveMQRAQueueReceiver(final QueueReceiver consumer, final ActiveMQRASession session) - { + public ActiveMQRAQueueReceiver(final QueueReceiver consumer, final ActiveMQRASession session) { super(consumer, session); - if (ActiveMQRAQueueReceiver.trace) - { + if (ActiveMQRAQueueReceiver.trace) { ActiveMQRALogger.LOGGER.trace("constructor(" + consumer + ", " + session + ")"); } } /** * Get queue + * * @return The queue - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public Queue getQueue() throws JMSException - { - if (ActiveMQRAQueueReceiver.trace) - { + public Queue getQueue() throws JMSException { + if (ActiveMQRAQueueReceiver.trace) { ActiveMQRALogger.LOGGER.trace("getQueue()"); } checkState(); - return ((QueueReceiver)consumer).getQueue(); + return ((QueueReceiver) consumer).getQueue(); } } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAQueueSender.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAQueueSender.java index 8e7174bf09..66128ee694 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAQueueSender.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAQueueSender.java @@ -21,118 +21,109 @@ import javax.jms.Message; import javax.jms.Queue; import javax.jms.QueueSender; - /** * ActiveMQQueueSender. */ -public class ActiveMQRAQueueSender extends ActiveMQRAMessageProducer implements QueueSender -{ - /** Whether trace is enabled */ +public class ActiveMQRAQueueSender extends ActiveMQRAMessageProducer implements QueueSender { + + /** + * Whether trace is enabled + */ private static boolean trace = ActiveMQRALogger.LOGGER.isTraceEnabled(); /** * Create a new wrapper + * * @param producer the producer - * @param session the session + * @param session the session */ - public ActiveMQRAQueueSender(final QueueSender producer, final ActiveMQRASession session) - { + public ActiveMQRAQueueSender(final QueueSender producer, final ActiveMQRASession session) { super(producer, session); - if (ActiveMQRAQueueSender.trace) - { + if (ActiveMQRAQueueSender.trace) { ActiveMQRALogger.LOGGER.trace("constructor(" + producer + ", " + session + ")"); } } /** * Get queue + * * @return The queue - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public Queue getQueue() throws JMSException - { - if (ActiveMQRAQueueSender.trace) - { + public Queue getQueue() throws JMSException { + if (ActiveMQRAQueueSender.trace) { ActiveMQRALogger.LOGGER.trace("getQueue()"); } - return ((QueueSender)producer).getQueue(); + return ((QueueSender) producer).getQueue(); } /** * Send message - * @param destination The destination - * @param message The message + * + * @param destination The destination + * @param message The message * @param deliveryMode The delivery mode - * @param priority The priority - * @param timeToLive The time to live - * @exception JMSException Thrown if an error occurs + * @param priority The priority + * @param timeToLive The time to live + * @throws JMSException Thrown if an error occurs */ public void send(final Queue destination, final Message message, final int deliveryMode, final int priority, - final long timeToLive) throws JMSException - { + final long timeToLive) throws JMSException { session.lock(); - try - { - if (ActiveMQRAQueueSender.trace) - { + try { + if (ActiveMQRAQueueSender.trace) { ActiveMQRALogger.LOGGER.trace("send " + this + - " destination=" + - destination + - " message=" + - message + - " deliveryMode=" + - deliveryMode + - " priority=" + - priority + - " ttl=" + - timeToLive); + " destination=" + + destination + + " message=" + + message + + " deliveryMode=" + + deliveryMode + + " priority=" + + priority + + " ttl=" + + timeToLive); } checkState(); producer.send(destination, message, deliveryMode, priority, timeToLive); - if (ActiveMQRAQueueSender.trace) - { + if (ActiveMQRAQueueSender.trace) { ActiveMQRALogger.LOGGER.trace("sent " + this + " result=" + message); } } - finally - { + finally { session.unlock(); } } /** * Send message + * * @param destination The destination - * @param message The message - * @exception JMSException Thrown if an error occurs + * @param message The message + * @throws JMSException Thrown if an error occurs */ - public void send(final Queue destination, final Message message) throws JMSException - { + public void send(final Queue destination, final Message message) throws JMSException { session.lock(); - try - { - if (ActiveMQRAQueueSender.trace) - { + try { + if (ActiveMQRAQueueSender.trace) { ActiveMQRALogger.LOGGER.trace("send " + this + " destination=" + destination + " message=" + message); } checkState(); producer.send(destination, message); - if (ActiveMQRAQueueSender.trace) - { + if (ActiveMQRAQueueSender.trace) { ActiveMQRALogger.LOGGER.trace("sent " + this + " result=" + message); } } - finally - { + finally { session.unlock(); } } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAService.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAService.java index 9d585373db..1f4cc29e6f 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAService.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAService.java @@ -22,13 +22,11 @@ import javax.management.MBeanServer; import javax.management.ObjectInstance; import javax.management.ObjectName; - /** * An ActiveMQRAService ensures that ActiveMQ Artemis Resource Adapter will be stopped *before* the ActiveMQ Artemis server. * https://jira.jboss.org/browse/HORNETQ-339 */ -public class ActiveMQRAService -{ +public class ActiveMQRAService { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -40,33 +38,27 @@ public class ActiveMQRAService // Constructors -------------------------------------------------- - public ActiveMQRAService(final MBeanServer mBeanServer, final String resourceAdapterObjectName) - { + public ActiveMQRAService(final MBeanServer mBeanServer, final String resourceAdapterObjectName) { this.mBeanServer = mBeanServer; this.resourceAdapterObjectName = resourceAdapterObjectName; } // Public -------------------------------------------------------- - public void stop() - { - try - { + public void stop() { + try { ObjectName objectName = new ObjectName(resourceAdapterObjectName); Set mbeanSet = mBeanServer.queryMBeans(objectName, null); - for (ObjectInstance mbean : mbeanSet) - { - String stateString = (String)mBeanServer.getAttribute(mbean.getObjectName(), "StateString"); + for (ObjectInstance mbean : mbeanSet) { + String stateString = (String) mBeanServer.getAttribute(mbean.getObjectName(), "StateString"); - if ("Started".equalsIgnoreCase(stateString) || "Starting".equalsIgnoreCase(stateString)) - { + if ("Started".equalsIgnoreCase(stateString) || "Starting".equalsIgnoreCase(stateString)) { mBeanServer.invoke(mbean.getObjectName(), "stop", new Object[0], new String[0]); } } } - catch (Exception e) - { + catch (Exception e) { ActiveMQRALogger.LOGGER.errorStoppingRA(e); } } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRASession.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRASession.java index 9efa574974..b5b588a25e 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRASession.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRASession.java @@ -56,12 +56,11 @@ import java.util.Set; import org.apache.activemq.artemis.core.client.impl.ClientSessionFactoryInternal; import org.apache.activemq.artemis.jms.client.ActiveMQSession; - /** * A joint interface for JMS sessions */ -public final class ActiveMQRASession implements QueueSession, TopicSession, XAQueueSession, XATopicSession -{ +public final class ActiveMQRASession implements QueueSession, TopicSession, XAQueueSession, XATopicSession { + /** * Trace enabled */ @@ -98,10 +97,8 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @param mc The managed connection * @param cri The connection request info */ - public ActiveMQRASession(final ActiveMQRAManagedConnection mc, final ActiveMQRAConnectionRequestInfo cri) - { - if (ActiveMQRASession.trace) - { + public ActiveMQRASession(final ActiveMQRAManagedConnection mc, final ActiveMQRAConnectionRequestInfo cri) { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("constructor(" + mc + ", " + cri + ")"); } @@ -117,10 +114,8 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * * @param sf The session factory */ - public void setActiveMQSessionFactory(final ActiveMQRASessionFactory sf) - { - if (ActiveMQRASession.trace) - { + public void setActiveMQSessionFactory(final ActiveMQRASessionFactory sf) { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("setActiveMQSessionFactory(" + sf + ")"); } @@ -133,20 +128,16 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @throws JMSException Thrown if an error occurs * @throws IllegalStateException The session is closed */ - protected void lock() throws JMSException - { - if (ActiveMQRASession.trace) - { + protected void lock() throws JMSException { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("lock()"); } final ActiveMQRAManagedConnection mcLocal = this.mc; - if (mcLocal != null) - { + if (mcLocal != null) { mcLocal.tryLock(); } - else - { + else { throw new IllegalStateException("Connection is not associated with a managed connection. " + this); } } @@ -154,16 +145,13 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu /** * Unlock */ - protected void unlock() - { - if (ActiveMQRASession.trace) - { + protected void unlock() { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("unlock()"); } final ActiveMQRAManagedConnection mcLocal = this.mc; - if (mcLocal != null) - { + if (mcLocal != null) { mcLocal.unlock(); } @@ -177,12 +165,10 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The message * @throws JMSException Thrown if an error occurs */ - public BytesMessage createBytesMessage() throws JMSException - { + public BytesMessage createBytesMessage() throws JMSException { Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createBytesMessage" + session); } @@ -195,12 +181,10 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The message * @throws JMSException Thrown if an error occurs */ - public MapMessage createMapMessage() throws JMSException - { + public MapMessage createMapMessage() throws JMSException { Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createMapMessage(), " + session); } @@ -213,12 +197,10 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The message * @throws JMSException Thrown if an error occurs */ - public Message createMessage() throws JMSException - { + public Message createMessage() throws JMSException { Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createMessage" + session); } @@ -231,12 +213,10 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The message * @throws JMSException Thrown if an error occurs */ - public ObjectMessage createObjectMessage() throws JMSException - { + public ObjectMessage createObjectMessage() throws JMSException { Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createObjectMessage" + session); } @@ -250,12 +230,10 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The message * @throws JMSException Thrown if an error occurs */ - public ObjectMessage createObjectMessage(final Serializable object) throws JMSException - { + public ObjectMessage createObjectMessage(final Serializable object) throws JMSException { Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createObjectMessage(" + object + ")" + session); } @@ -268,12 +246,10 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The message * @throws JMSException Thrown if an error occurs */ - public StreamMessage createStreamMessage() throws JMSException - { + public StreamMessage createStreamMessage() throws JMSException { Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createStreamMessage" + session); } @@ -286,12 +262,10 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The message * @throws JMSException Thrown if an error occurs */ - public TextMessage createTextMessage() throws JMSException - { + public TextMessage createTextMessage() throws JMSException { Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createTextMessage" + session); } @@ -305,12 +279,10 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The message * @throws JMSException Thrown if an error occurs */ - public TextMessage createTextMessage(final String string) throws JMSException - { + public TextMessage createTextMessage(final String string) throws JMSException { Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createTextMessage(" + string + ")" + session); } @@ -323,10 +295,8 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return True if transacted; otherwise false * @throws JMSException Thrown if an error occurs */ - public boolean getTransacted() throws JMSException - { - if (ActiveMQRASession.trace) - { + public boolean getTransacted() throws JMSException { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("getTransacted()"); } @@ -340,10 +310,8 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The message listener * @throws JMSException Thrown if an error occurs */ - public MessageListener getMessageListener() throws JMSException - { - if (ActiveMQRASession.trace) - { + public MessageListener getMessageListener() throws JMSException { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("getMessageListener()"); } @@ -356,10 +324,8 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @param listener The message listener * @throws JMSException Thrown if an error occurs */ - public void setMessageListener(final MessageListener listener) throws JMSException - { - if (ActiveMQRASession.trace) - { + public void setMessageListener(final MessageListener listener) throws JMSException { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("setMessageListener(" + listener + ")"); } @@ -371,10 +337,8 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * * @throws Error Method not allowed. */ - public void run() - { - if (ActiveMQRASession.trace) - { + public void run() { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("run()"); } @@ -387,10 +351,8 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * * @throws JMSException Failed to close session. */ - public void close() throws JMSException - { - if (ActiveMQRASession.trace) - { + public void close() throws JMSException { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("close()"); } @@ -403,33 +365,27 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * * @throws JMSException Failed to close session. */ - public void commit() throws JMSException - { + public void commit() throws JMSException { if (cri.getType() == ActiveMQRAConnectionFactory.XA_CONNECTION || cri.getType() == ActiveMQRAConnectionFactory.XA_QUEUE_CONNECTION || - cri.getType() == ActiveMQRAConnectionFactory.XA_TOPIC_CONNECTION) - { + cri.getType() == ActiveMQRAConnectionFactory.XA_TOPIC_CONNECTION) { throw new TransactionInProgressException("XA connection"); } lock(); - try - { + try { Session session = getSessionInternal(); - if (cri.isTransacted() == false) - { + if (cri.isTransacted() == false) { throw new IllegalStateException("Session is not transacted"); } - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("Commit session " + this); } session.commit(); } - finally - { + finally { unlock(); } } @@ -439,33 +395,27 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * * @throws JMSException Failed to close session. */ - public void rollback() throws JMSException - { + public void rollback() throws JMSException { if (cri.getType() == ActiveMQRAConnectionFactory.XA_CONNECTION || cri.getType() == ActiveMQRAConnectionFactory.XA_QUEUE_CONNECTION || - cri.getType() == ActiveMQRAConnectionFactory.XA_TOPIC_CONNECTION) - { + cri.getType() == ActiveMQRAConnectionFactory.XA_TOPIC_CONNECTION) { throw new TransactionInProgressException("XA connection"); } lock(); - try - { + try { Session session = getSessionInternal(); - if (cri.isTransacted() == false) - { + if (cri.isTransacted() == false) { throw new IllegalStateException("Session is not transacted"); } - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("Rollback session " + this); } session.rollback(); } - finally - { + finally { unlock(); } } @@ -475,27 +425,22 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * * @throws JMSException Failed to close session. */ - public void recover() throws JMSException - { + public void recover() throws JMSException { lock(); - try - { + try { Session session = getSessionInternal(); - if (cri.isTransacted()) - { + if (cri.isTransacted()) { throw new IllegalStateException("Session is transacted"); } - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("Recover session " + this); } session.recover(); } - finally - { + finally { unlock(); } } @@ -507,24 +452,20 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The topic * @throws JMSException Thrown if an error occurs */ - public Topic createTopic(final String topicName) throws JMSException - { - if (cri.getType() == ActiveMQRAConnectionFactory.QUEUE_CONNECTION || cri.getType() == ActiveMQRAConnectionFactory.XA_QUEUE_CONNECTION) - { + public Topic createTopic(final String topicName) throws JMSException { + if (cri.getType() == ActiveMQRAConnectionFactory.QUEUE_CONNECTION || cri.getType() == ActiveMQRAConnectionFactory.XA_QUEUE_CONNECTION) { throw new IllegalStateException("Cannot create topic for javax.jms.QueueSession"); } Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createTopic " + session + " topicName=" + topicName); } Topic result = session.createTopic(topicName); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createdTopic " + session + " topic=" + result); } @@ -538,23 +479,19 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The subscriber * @throws JMSException Thrown if an error occurs */ - public TopicSubscriber createSubscriber(final Topic topic) throws JMSException - { + public TopicSubscriber createSubscriber(final Topic topic) throws JMSException { lock(); - try - { + try { TopicSession session = getTopicSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createSubscriber " + session + " topic=" + topic); } TopicSubscriber result = session.createSubscriber(topic); result = new ActiveMQRATopicSubscriber(result, this); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createdSubscriber " + session + " ActiveMQTopicSubscriber=" + result); } @@ -562,8 +499,7 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu return result; } - finally - { + finally { unlock(); } } @@ -577,29 +513,27 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The subscriber * @throws JMSException Thrown if an error occurs */ - public TopicSubscriber createSubscriber(final Topic topic, final String messageSelector, final boolean noLocal) throws JMSException - { + public TopicSubscriber createSubscriber(final Topic topic, + final String messageSelector, + final boolean noLocal) throws JMSException { lock(); - try - { + try { TopicSession session = getTopicSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createSubscriber " + session + - " topic=" + - topic + - " selector=" + - messageSelector + - " noLocal=" + - noLocal); + " topic=" + + topic + + " selector=" + + messageSelector + + " noLocal=" + + noLocal); } TopicSubscriber result = session.createSubscriber(topic, messageSelector, noLocal); result = new ActiveMQRATopicSubscriber(result, this); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createdSubscriber " + session + " ActiveMQTopicSubscriber=" + result); } @@ -607,8 +541,7 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu return result; } - finally - { + finally { unlock(); } } @@ -621,28 +554,23 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The subscriber * @throws JMSException Thrown if an error occurs */ - public TopicSubscriber createDurableSubscriber(final Topic topic, final String name) throws JMSException - { - if (cri.getType() == ActiveMQRAConnectionFactory.QUEUE_CONNECTION || cri.getType() == ActiveMQRAConnectionFactory.XA_QUEUE_CONNECTION) - { + public TopicSubscriber createDurableSubscriber(final Topic topic, final String name) throws JMSException { + if (cri.getType() == ActiveMQRAConnectionFactory.QUEUE_CONNECTION || cri.getType() == ActiveMQRAConnectionFactory.XA_QUEUE_CONNECTION) { throw new IllegalStateException("Cannot create durable subscriber from javax.jms.QueueSession"); } lock(); - try - { + try { Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createDurableSubscriber " + session + " topic=" + topic + " name=" + name); } TopicSubscriber result = session.createDurableSubscriber(topic, name); result = new ActiveMQRATopicSubscriber(result, this); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createdDurableSubscriber " + session + " ActiveMQTopicSubscriber=" + result); } @@ -650,8 +578,7 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu return result; } - finally - { + finally { unlock(); } } @@ -669,31 +596,27 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu public TopicSubscriber createDurableSubscriber(final Topic topic, final String name, final String messageSelector, - final boolean noLocal) throws JMSException - { + final boolean noLocal) throws JMSException { lock(); - try - { + try { Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createDurableSubscriber " + session + - " topic=" + - topic + - " name=" + - name + - " selector=" + - messageSelector + - " noLocal=" + - noLocal); + " topic=" + + topic + + " name=" + + name + + " selector=" + + messageSelector + + " noLocal=" + + noLocal); } TopicSubscriber result = session.createDurableSubscriber(topic, name, messageSelector, noLocal); result = new ActiveMQRATopicSubscriber(result, this); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createdDurableSubscriber " + session + " ActiveMQTopicSubscriber=" + result); } @@ -701,8 +624,7 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu return result; } - finally - { + finally { unlock(); } } @@ -714,23 +636,19 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The publisher * @throws JMSException Thrown if an error occurs */ - public TopicPublisher createPublisher(final Topic topic) throws JMSException - { + public TopicPublisher createPublisher(final Topic topic) throws JMSException { lock(); - try - { + try { TopicSession session = getTopicSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createPublisher " + session + " topic=" + topic); } TopicPublisher result = session.createPublisher(topic); result = new ActiveMQRATopicPublisher(result, this); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createdPublisher " + session + " publisher=" + result); } @@ -738,8 +656,7 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu return result; } - finally - { + finally { unlock(); } } @@ -750,27 +667,22 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The temporary topic * @throws JMSException Thrown if an error occurs */ - public TemporaryTopic createTemporaryTopic() throws JMSException - { - if (cri.getType() == ActiveMQRAConnectionFactory.QUEUE_CONNECTION || cri.getType() == ActiveMQRAConnectionFactory.XA_QUEUE_CONNECTION) - { + public TemporaryTopic createTemporaryTopic() throws JMSException { + if (cri.getType() == ActiveMQRAConnectionFactory.QUEUE_CONNECTION || cri.getType() == ActiveMQRAConnectionFactory.XA_QUEUE_CONNECTION) { throw new IllegalStateException("Cannot create temporary topic for javax.jms.QueueSession"); } lock(); - try - { + try { Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createTemporaryTopic " + session); } TemporaryTopic temp = session.createTemporaryTopic(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createdTemporaryTopic " + session + " temp=" + temp); } @@ -778,8 +690,7 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu return temp; } - finally - { + finally { unlock(); } } @@ -790,27 +701,22 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @param name The name * @throws JMSException Thrown if an error occurs */ - public void unsubscribe(final String name) throws JMSException - { - if (cri.getType() == ActiveMQRAConnectionFactory.QUEUE_CONNECTION || cri.getType() == ActiveMQRAConnectionFactory.XA_QUEUE_CONNECTION) - { + public void unsubscribe(final String name) throws JMSException { + if (cri.getType() == ActiveMQRAConnectionFactory.QUEUE_CONNECTION || cri.getType() == ActiveMQRAConnectionFactory.XA_QUEUE_CONNECTION) { throw new IllegalStateException("Cannot unsubscribe for javax.jms.QueueSession"); } lock(); - try - { + try { Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("unsubscribe " + session + " name=" + name); } session.unsubscribe(name); } - finally - { + finally { unlock(); } } @@ -822,24 +728,20 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The browser * @throws JMSException Thrown if an error occurs */ - public QueueBrowser createBrowser(final Queue queue) throws JMSException - { - if (cri.getType() == ActiveMQRAConnectionFactory.TOPIC_CONNECTION || cri.getType() == ActiveMQRAConnectionFactory.XA_TOPIC_CONNECTION) - { + public QueueBrowser createBrowser(final Queue queue) throws JMSException { + if (cri.getType() == ActiveMQRAConnectionFactory.TOPIC_CONNECTION || cri.getType() == ActiveMQRAConnectionFactory.XA_TOPIC_CONNECTION) { throw new IllegalStateException("Cannot create browser for javax.jms.TopicSession"); } Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createBrowser " + session + " queue=" + queue); } QueueBrowser result = session.createBrowser(queue); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createdBrowser " + session + " browser=" + result); } @@ -854,24 +756,20 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The browser * @throws JMSException Thrown if an error occurs */ - public QueueBrowser createBrowser(final Queue queue, final String messageSelector) throws JMSException - { - if (cri.getType() == ActiveMQRAConnectionFactory.TOPIC_CONNECTION || cri.getType() == ActiveMQRAConnectionFactory.XA_TOPIC_CONNECTION) - { + public QueueBrowser createBrowser(final Queue queue, final String messageSelector) throws JMSException { + if (cri.getType() == ActiveMQRAConnectionFactory.TOPIC_CONNECTION || cri.getType() == ActiveMQRAConnectionFactory.XA_TOPIC_CONNECTION) { throw new IllegalStateException("Cannot create browser for javax.jms.TopicSession"); } Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createBrowser " + session + " queue=" + queue + " selector=" + messageSelector); } QueueBrowser result = session.createBrowser(queue, messageSelector); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createdBrowser " + session + " browser=" + result); } @@ -885,24 +783,20 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The queue * @throws JMSException Thrown if an error occurs */ - public Queue createQueue(final String queueName) throws JMSException - { - if (cri.getType() == ActiveMQRAConnectionFactory.TOPIC_CONNECTION || cri.getType() == ActiveMQRAConnectionFactory.XA_TOPIC_CONNECTION) - { + public Queue createQueue(final String queueName) throws JMSException { + if (cri.getType() == ActiveMQRAConnectionFactory.TOPIC_CONNECTION || cri.getType() == ActiveMQRAConnectionFactory.XA_TOPIC_CONNECTION) { throw new IllegalStateException("Cannot create browser or javax.jms.TopicSession"); } Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createQueue " + session + " queueName=" + queueName); } Queue result = session.createQueue(queueName); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createdQueue " + session + " queue=" + result); } @@ -916,23 +810,19 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The queue receiver * @throws JMSException Thrown if an error occurs */ - public QueueReceiver createReceiver(final Queue queue) throws JMSException - { + public QueueReceiver createReceiver(final Queue queue) throws JMSException { lock(); - try - { + try { QueueSession session = getQueueSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createReceiver " + session + " queue=" + queue); } QueueReceiver result = session.createReceiver(queue); result = new ActiveMQRAQueueReceiver(result, this); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createdReceiver " + session + " receiver=" + result); } @@ -940,8 +830,7 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu return result; } - finally - { + finally { unlock(); } } @@ -954,23 +843,19 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The queue receiver * @throws JMSException Thrown if an error occurs */ - public QueueReceiver createReceiver(final Queue queue, final String messageSelector) throws JMSException - { + public QueueReceiver createReceiver(final Queue queue, final String messageSelector) throws JMSException { lock(); - try - { + try { QueueSession session = getQueueSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createReceiver " + session + " queue=" + queue + " selector=" + messageSelector); } QueueReceiver result = session.createReceiver(queue, messageSelector); result = new ActiveMQRAQueueReceiver(result, this); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createdReceiver " + session + " receiver=" + result); } @@ -978,8 +863,7 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu return result; } - finally - { + finally { unlock(); } } @@ -991,23 +875,19 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The queue sender * @throws JMSException Thrown if an error occurs */ - public QueueSender createSender(final Queue queue) throws JMSException - { + public QueueSender createSender(final Queue queue) throws JMSException { lock(); - try - { + try { QueueSession session = getQueueSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createSender " + session + " queue=" + queue); } QueueSender result = session.createSender(queue); result = new ActiveMQRAQueueSender(result, this); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createdSender " + session + " sender=" + result); } @@ -1015,8 +895,7 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu return result; } - finally - { + finally { unlock(); } } @@ -1027,27 +906,22 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The temporary queue * @throws JMSException Thrown if an error occurs */ - public TemporaryQueue createTemporaryQueue() throws JMSException - { - if (cri.getType() == ActiveMQRAConnectionFactory.TOPIC_CONNECTION || cri.getType() == ActiveMQRAConnectionFactory.XA_TOPIC_CONNECTION) - { + public TemporaryQueue createTemporaryQueue() throws JMSException { + if (cri.getType() == ActiveMQRAConnectionFactory.TOPIC_CONNECTION || cri.getType() == ActiveMQRAConnectionFactory.XA_TOPIC_CONNECTION) { throw new IllegalStateException("Cannot create temporary queue for javax.jms.TopicSession"); } lock(); - try - { + try { Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createTemporaryQueue " + session); } TemporaryQueue temp = session.createTemporaryQueue(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createdTemporaryQueue " + session + " temp=" + temp); } @@ -1055,8 +929,7 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu return temp; } - finally - { + finally { unlock(); } } @@ -1068,23 +941,19 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The message consumer * @throws JMSException Thrown if an error occurs */ - public MessageConsumer createConsumer(final Destination destination) throws JMSException - { + public MessageConsumer createConsumer(final Destination destination) throws JMSException { lock(); - try - { + try { Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createConsumer " + session + " dest=" + destination); } MessageConsumer result = session.createConsumer(destination); result = new ActiveMQRAMessageConsumer(result, this); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createdConsumer " + session + " consumer=" + result); } @@ -1092,8 +961,7 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu return result; } - finally - { + finally { unlock(); } } @@ -1106,27 +974,24 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The message consumer * @throws JMSException Thrown if an error occurs */ - public MessageConsumer createConsumer(final Destination destination, final String messageSelector) throws JMSException - { + public MessageConsumer createConsumer(final Destination destination, + final String messageSelector) throws JMSException { lock(); - try - { + try { Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createConsumer " + session + - " dest=" + - destination + - " messageSelector=" + - messageSelector); + " dest=" + + destination + + " messageSelector=" + + messageSelector); } MessageConsumer result = session.createConsumer(destination, messageSelector); result = new ActiveMQRAMessageConsumer(result, this); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createdConsumer " + session + " consumer=" + result); } @@ -1134,8 +999,7 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu return result; } - finally - { + finally { unlock(); } } @@ -1151,29 +1015,25 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu */ public MessageConsumer createConsumer(final Destination destination, final String messageSelector, - final boolean noLocal) throws JMSException - { + final boolean noLocal) throws JMSException { lock(); - try - { + try { Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createConsumer " + session + - " dest=" + - destination + - " messageSelector=" + - messageSelector + - " noLocal=" + - noLocal); + " dest=" + + destination + + " messageSelector=" + + messageSelector + + " noLocal=" + + noLocal); } MessageConsumer result = session.createConsumer(destination, messageSelector, noLocal); result = new ActiveMQRAMessageConsumer(result, this); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createdConsumer " + session + " consumer=" + result); } @@ -1181,8 +1041,7 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu return result; } - finally - { + finally { unlock(); } } @@ -1194,23 +1053,19 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The message producer * @throws JMSException Thrown if an error occurs */ - public MessageProducer createProducer(final Destination destination) throws JMSException - { + public MessageProducer createProducer(final Destination destination) throws JMSException { lock(); - try - { + try { Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createProducer " + session + " dest=" + destination); } MessageProducer result = session.createProducer(destination); result = new ActiveMQRAMessageProducer(result, this); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createdProducer " + session + " producer=" + result); } @@ -1218,8 +1073,7 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu return result; } - finally - { + finally { unlock(); } } @@ -1230,10 +1084,8 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The mode * @throws JMSException Thrown if an error occurs */ - public int getAcknowledgeMode() throws JMSException - { - if (ActiveMQRASession.trace) - { + public int getAcknowledgeMode() throws JMSException { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("getAcknowledgeMode()"); } @@ -1244,31 +1096,25 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu /** * Get the XA resource */ - public XAResource getXAResource() - { - if (ActiveMQRASession.trace) - { + public XAResource getXAResource() { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("getXAResource()"); } if (cri.getType() == ActiveMQRAConnectionFactory.CONNECTION || cri.getType() == ActiveMQRAConnectionFactory.QUEUE_CONNECTION || - cri.getType() == ActiveMQRAConnectionFactory.TOPIC_CONNECTION) - { + cri.getType() == ActiveMQRAConnectionFactory.TOPIC_CONNECTION) { return null; } - try - { + try { lock(); return getXAResourceInternal(); } - catch (Throwable t) - { + catch (Throwable t) { return null; } - finally - { + finally { unlock(); } } @@ -1278,8 +1124,7 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * * @return Node ID */ - public String getNodeId() throws JMSException - { + public String getNodeId() throws JMSException { ActiveMQSession session = (ActiveMQSession) getSessionInternal(); ClientSessionFactoryInternal factory = (ClientSessionFactoryInternal) session.getCoreSession().getSessionFactory(); return factory.getLiveNodeId(); @@ -1291,26 +1136,21 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The session * @throws JMSException Thrown if an error occurs */ - public Session getSession() throws JMSException - { - if (ActiveMQRASession.trace) - { + public Session getSession() throws JMSException { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("getNonXAsession()"); } if (cri.getType() == ActiveMQRAConnectionFactory.CONNECTION || cri.getType() == ActiveMQRAConnectionFactory.QUEUE_CONNECTION || - cri.getType() == ActiveMQRAConnectionFactory.TOPIC_CONNECTION) - { + cri.getType() == ActiveMQRAConnectionFactory.TOPIC_CONNECTION) { throw new IllegalStateException("Non XA connection"); } lock(); - try - { + try { return this; } - finally - { + finally { unlock(); } } @@ -1321,26 +1161,21 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The queue session * @throws JMSException Thrown if an error occurs */ - public QueueSession getQueueSession() throws JMSException - { - if (ActiveMQRASession.trace) - { + public QueueSession getQueueSession() throws JMSException { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("getQueueSession()"); } if (cri.getType() == ActiveMQRAConnectionFactory.CONNECTION || cri.getType() == ActiveMQRAConnectionFactory.QUEUE_CONNECTION || - cri.getType() == ActiveMQRAConnectionFactory.TOPIC_CONNECTION) - { + cri.getType() == ActiveMQRAConnectionFactory.TOPIC_CONNECTION) { throw new IllegalStateException("Non XA connection"); } lock(); - try - { + try { return this; } - finally - { + finally { unlock(); } } @@ -1351,48 +1186,40 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @return The topic session * @throws JMSException Thrown if an error occurs */ - public TopicSession getTopicSession() throws JMSException - { - if (ActiveMQRASession.trace) - { + public TopicSession getTopicSession() throws JMSException { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("getTopicSession()"); } if (cri.getType() == ActiveMQRAConnectionFactory.CONNECTION || cri.getType() == ActiveMQRAConnectionFactory.QUEUE_CONNECTION || - cri.getType() == ActiveMQRAConnectionFactory.TOPIC_CONNECTION) - { + cri.getType() == ActiveMQRAConnectionFactory.TOPIC_CONNECTION) { throw new IllegalStateException("Non XA connection"); } lock(); - try - { + try { return this; } - finally - { + finally { unlock(); } } @Override - public MessageConsumer createSharedConsumer(final Topic topic, final String sharedSubscriptionName) throws JMSException - { + public MessageConsumer createSharedConsumer(final Topic topic, + final String sharedSubscriptionName) throws JMSException { lock(); - try - { + try { Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createSharedConsumer " + session + " topic=" + topic + ", sharedSubscriptionName=" + sharedSubscriptionName); } MessageConsumer result = session.createSharedConsumer(topic, sharedSubscriptionName); result = new ActiveMQRAMessageConsumer(result, this); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createdConsumer " + session + " consumer=" + result); } @@ -1400,32 +1227,28 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu return result; } - finally - { + finally { unlock(); } } @Override - public MessageConsumer createSharedConsumer(final Topic topic, final String sharedSubscriptionName, - final String messageSelector) throws JMSException - { + public MessageConsumer createSharedConsumer(final Topic topic, + final String sharedSubscriptionName, + final String messageSelector) throws JMSException { lock(); - try - { + try { Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createSharedConsumer " + session + " topic=" + topic + - ", sharedSubscriptionName=" + sharedSubscriptionName + ", messageSelector=" + messageSelector); + ", sharedSubscriptionName=" + sharedSubscriptionName + ", messageSelector=" + messageSelector); } MessageConsumer result = session.createSharedConsumer(topic, sharedSubscriptionName, messageSelector); result = new ActiveMQRAMessageConsumer(result, this); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createdConsumer " + session + " consumer=" + result); } @@ -1433,30 +1256,25 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu return result; } - finally - { + finally { unlock(); } } @Override - public MessageConsumer createDurableConsumer(final Topic topic, final String name) throws JMSException - { + public MessageConsumer createDurableConsumer(final Topic topic, final String name) throws JMSException { lock(); - try - { + try { Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createSharedConsumer " + session + " topic=" + topic + ", name=" + name); } MessageConsumer result = session.createDurableConsumer(topic, name); result = new ActiveMQRAMessageConsumer(result, this); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createdConsumer " + session + " consumer=" + result); } @@ -1464,31 +1282,29 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu return result; } - finally - { + finally { unlock(); } } @Override - public MessageConsumer createDurableConsumer(Topic topic, String name, String messageSelector, boolean noLocal) throws JMSException - { + public MessageConsumer createDurableConsumer(Topic topic, + String name, + String messageSelector, + boolean noLocal) throws JMSException { lock(); - try - { + try { Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createDurableConsumer " + session + " topic=" + topic + ", name=" + name + - ", messageSelector=" + messageSelector + ", noLocal=" + noLocal); + ", messageSelector=" + messageSelector + ", noLocal=" + noLocal); } MessageConsumer result = session.createDurableConsumer(topic, name, messageSelector, noLocal); result = new ActiveMQRAMessageConsumer(result, this); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createdConsumer " + session + " consumer=" + result); } @@ -1496,31 +1312,26 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu return result; } - finally - { + finally { unlock(); } } @Override - public MessageConsumer createSharedDurableConsumer(Topic topic, String name) throws JMSException - { + public MessageConsumer createSharedDurableConsumer(Topic topic, String name) throws JMSException { lock(); - try - { + try { Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createSharedDurableConsumer " + session + " topic=" + topic + ", name=" + - name); + name); } MessageConsumer result = session.createSharedDurableConsumer(topic, name); result = new ActiveMQRAMessageConsumer(result, this); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createdConsumer " + session + " consumer=" + result); } @@ -1528,31 +1339,28 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu return result; } - finally - { + finally { unlock(); } } @Override - public MessageConsumer createSharedDurableConsumer(Topic topic, String name, String messageSelector) throws JMSException - { + public MessageConsumer createSharedDurableConsumer(Topic topic, + String name, + String messageSelector) throws JMSException { lock(); - try - { + try { Session session = getSessionInternal(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createSharedDurableConsumer " + session + " topic=" + topic + ", name=" + - name + ", messageSelector=" + messageSelector); + name + ", messageSelector=" + messageSelector); } MessageConsumer result = session.createSharedDurableConsumer(topic, name, messageSelector); result = new ActiveMQRAMessageConsumer(result, this); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("createdConsumer " + session + " consumer=" + result); } @@ -1560,8 +1368,7 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu return result; } - finally - { + finally { unlock(); } } @@ -1571,15 +1378,12 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * * @param managedConnection The managed connection */ - void setManagedConnection(final ActiveMQRAManagedConnection managedConnection) - { - if (ActiveMQRASession.trace) - { + void setManagedConnection(final ActiveMQRAManagedConnection managedConnection) { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("setManagedConnection(" + managedConnection + ")"); } - if (mc != null) - { + if (mc != null) { mc.removeHandle(this); } @@ -1589,18 +1393,15 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu /** * for tests only */ - public ManagedConnection getManagedConnection() - { + public ManagedConnection getManagedConnection() { return mc; } /** * Destroy */ - void destroy() - { - if (ActiveMQRASession.trace) - { + void destroy() { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("destroy()"); } @@ -1612,15 +1413,12 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * * @throws JMSException Thrown if an error occurs */ - void start() throws JMSException - { - if (ActiveMQRASession.trace) - { + void start() throws JMSException { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("start()"); } - if (mc != null) - { + if (mc != null) { mc.start(); } } @@ -1630,15 +1428,12 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * * @throws JMSException Thrown if an error occurs */ - void stop() throws JMSException - { - if (ActiveMQRASession.trace) - { + void stop() throws JMSException { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("stop()"); } - if (mc != null) - { + if (mc != null) { mc.stop(); } } @@ -1648,15 +1443,12 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * * @throws JMSException Thrown if an error occurs */ - void checkStrict() throws JMSException - { - if (ActiveMQRASession.trace) - { + void checkStrict() throws JMSException { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("checkStrict()"); } - if (mc != null) - { + if (mc != null) { throw new IllegalStateException(ActiveMQRASessionFactory.ISE); } } @@ -1666,49 +1458,37 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * * @throws JMSException Thrown if an error occurs */ - void closeSession() throws JMSException - { - if (mc != null) - { + void closeSession() throws JMSException { + if (mc != null) { ActiveMQRALogger.LOGGER.trace("Closing session"); - try - { + try { mc.stop(); } - catch (Throwable t) - { + catch (Throwable t) { ActiveMQRALogger.LOGGER.trace("Error stopping managed connection", t); } - synchronized (consumers) - { - for (Iterator i = consumers.iterator(); i.hasNext(); ) - { + synchronized (consumers) { + for (Iterator i = consumers.iterator(); i.hasNext(); ) { ActiveMQRAMessageConsumer consumer = (ActiveMQRAMessageConsumer) i.next(); - try - { + try { consumer.closeConsumer(); } - catch (Throwable t) - { + catch (Throwable t) { ActiveMQRALogger.LOGGER.trace("Error closing consumer", t); } i.remove(); } } - synchronized (producers) - { - for (Iterator i = producers.iterator(); i.hasNext(); ) - { + synchronized (producers) { + for (Iterator i = producers.iterator(); i.hasNext(); ) { ActiveMQRAMessageProducer producer = (ActiveMQRAMessageProducer) i.next(); - try - { + try { producer.closeProducer(); } - catch (Throwable t) - { + catch (Throwable t) { ActiveMQRALogger.LOGGER.trace("Error closing producer", t); } i.remove(); @@ -1728,15 +1508,12 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * * @param consumer The consumer */ - void addConsumer(final MessageConsumer consumer) - { - if (ActiveMQRASession.trace) - { + void addConsumer(final MessageConsumer consumer) { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("addConsumer(" + consumer + ")"); } - synchronized (consumers) - { + synchronized (consumers) { consumers.add(consumer); } } @@ -1746,15 +1523,12 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * * @param consumer The consumer */ - void removeConsumer(final MessageConsumer consumer) - { - if (ActiveMQRASession.trace) - { + void removeConsumer(final MessageConsumer consumer) { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("removeConsumer(" + consumer + ")"); } - synchronized (consumers) - { + synchronized (consumers) { consumers.remove(consumer); } } @@ -1764,15 +1538,12 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * * @param producer The producer */ - void addProducer(final MessageProducer producer) - { - if (ActiveMQRASession.trace) - { + void addProducer(final MessageProducer producer) { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("addProducer(" + producer + ")"); } - synchronized (producers) - { + synchronized (producers) { producers.add(producer); } } @@ -1782,15 +1553,12 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * * @param producer The producer */ - void removeProducer(final MessageProducer producer) - { - if (ActiveMQRASession.trace) - { + void removeProducer(final MessageProducer producer) { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("removeProducer(" + producer + ")"); } - synchronized (producers) - { + synchronized (producers) { producers.remove(producer); } } @@ -1802,17 +1570,14 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @throws JMSException Thrown if an error occurs * @throws IllegalStateException The session is closed */ - Session getSessionInternal() throws JMSException - { - if (mc == null) - { + Session getSessionInternal() throws JMSException { + if (mc == null) { throw new IllegalStateException("The session is closed"); } Session session = mc.getSession(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("getSessionInternal " + session + " for " + this); } @@ -1826,26 +1591,21 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @throws JMSException Thrown if an error occurs * @throws IllegalStateException The session is closed */ - XAResource getXAResourceInternal() throws JMSException - { - if (mc == null) - { + XAResource getXAResourceInternal() throws JMSException { + if (mc == null) { throw new IllegalStateException("The session is closed"); } - try - { + try { XAResource xares = mc.getXAResource(); - if (ActiveMQRASession.trace) - { + if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace("getXAResourceInternal " + xares + " for " + this); } return xares; } - catch (ResourceException e) - { + catch (ResourceException e) { JMSException jmse = new JMSException("Unable to get XA Resource"); jmse.initCause(e); throw jmse; @@ -1859,11 +1619,9 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @throws JMSException Thrown if an error occurs * @throws IllegalStateException The session is closed */ - QueueSession getQueueSessionInternal() throws JMSException - { + QueueSession getQueueSessionInternal() throws JMSException { Session s = getSessionInternal(); - if (!(s instanceof QueueSession)) - { + if (!(s instanceof QueueSession)) { throw new InvalidDestinationException("Attempting to use QueueSession methods on: " + this); } return (QueueSession) s; @@ -1876,20 +1634,16 @@ public final class ActiveMQRASession implements QueueSession, TopicSession, XAQu * @throws JMSException Thrown if an error occurs * @throws IllegalStateException The session is closed */ - TopicSession getTopicSessionInternal() throws JMSException - { + TopicSession getTopicSessionInternal() throws JMSException { Session s = getSessionInternal(); - if (!(s instanceof TopicSession)) - { + if (!(s instanceof TopicSession)) { throw new InvalidDestinationException("Attempting to use TopicSession methods on: " + this); } return (TopicSession) s; } - public void checkState() throws JMSException - { - if (mc != null) - { + public void checkState() throws JMSException { + if (mc != null) { mc.checkTransactionActive(); } } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRASessionFactory.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRASessionFactory.java index 14e5e1ddad..b7b9308b68 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRASessionFactory.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRASessionFactory.java @@ -25,25 +25,30 @@ import javax.jms.XATopicConnection; /** * A joint interface for all connection types */ -public interface ActiveMQRASessionFactory extends XATopicConnection, XAQueueConnection -{ - /** Error message for strict behaviour */ +public interface ActiveMQRASessionFactory extends XATopicConnection, XAQueueConnection { + + /** + * Error message for strict behaviour + */ String ISE = "This method is not applicable inside the application server. See the J2EE spec, e.g. J2EE1.4 Section 6.6"; /** * Add a temporary queue + * * @param temp The temporary queue */ void addTemporaryQueue(TemporaryQueue temp); /** * Add a temporary topic + * * @param temp The temporary topic */ void addTemporaryTopic(TemporaryTopic temp); /** * Notification that a session is closed + * * @param session The session * @throws JMSException for any error */ diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRASessionFactoryImpl.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRASessionFactoryImpl.java index 20f5f51c88..d6d2eabef0 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRASessionFactoryImpl.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRASessionFactoryImpl.java @@ -52,9 +52,8 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionForContextImpl; /** * Implements the JMS Connection API and produces {@link ActiveMQRASession} objects. */ -public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForContextImpl implements - ActiveMQRASessionFactory, ActiveMQConnectionForContext, Referenceable -{ +public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForContextImpl implements ActiveMQRASessionFactory, ActiveMQConnectionForContext, Referenceable { + /** * Trace enabled */ @@ -131,35 +130,29 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon public ActiveMQRASessionFactoryImpl(final ActiveMQRAManagedConnectionFactory mcf, final ConnectionManager cm, final TransactionManager tm, - final int type) - { + final int type) { this.mcf = mcf; this.tm = tm; - if (cm == null) - { + if (cm == null) { this.cm = new ActiveMQRAConnectionManager(); } - else - { + else { this.cm = cm; } this.type = type; - if (ActiveMQRASessionFactoryImpl.trace) - { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("constructor(" + mcf + ", " + cm + ", " + type); } } - public JMSContext createContext(int sessionMode) - { + public JMSContext createContext(int sessionMode) { boolean inJtaTx = inJtaTransaction(); int sessionModeToUse; - switch (sessionMode) - { + switch (sessionMode) { case Session.AUTO_ACKNOWLEDGE: case Session.DUPS_OK_ACKNOWLEDGE: case ActiveMQJMSConstants.INDIVIDUAL_ACKNOWLEDGE: @@ -168,15 +161,13 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon break; //these are prohibited in JEE unless not in a JTA tx where they should be ignored and auto_ack used case Session.CLIENT_ACKNOWLEDGE: - if (!inJtaTx) - { + if (!inJtaTx) { throw ActiveMQRABundle.BUNDLE.invalidSessionTransactedModeRuntime(); } sessionModeToUse = Session.AUTO_ACKNOWLEDGE; break; case Session.SESSION_TRANSACTED: - if (!inJtaTx) - { + if (!inJtaTx) { throw ActiveMQRABundle.BUNDLE.invalidClientAcknowledgeModeRuntime(); } sessionModeToUse = Session.AUTO_ACKNOWLEDGE; @@ -189,8 +180,7 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon return new ActiveMQRAJMSContext(this, sessionModeToUse, threadAwareContext); } - public XAJMSContext createXAContext() - { + public XAJMSContext createXAContext() { incrementRefCounter(); return new ActiveMQRAXAJMSContext(this, threadAwareContext); @@ -201,10 +191,8 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon * * @param reference The reference */ - public void setReference(final Reference reference) - { - if (ActiveMQRASessionFactoryImpl.trace) - { + public void setReference(final Reference reference) { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("setReference(" + reference + ")"); } @@ -216,10 +204,8 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon * * @return The reference */ - public Reference getReference() - { - if (ActiveMQRASessionFactoryImpl.trace) - { + public Reference getReference() { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("getReference()"); } @@ -231,10 +217,8 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon * * @param name The user name */ - public void setUserName(final String name) - { - if (ActiveMQRASessionFactoryImpl.trace) - { + public void setUserName(final String name) { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("setUserName(" + name + ")"); } @@ -246,10 +230,8 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon * * @param password The password */ - public void setPassword(final String password) - { - if (ActiveMQRASessionFactoryImpl.trace) - { + public void setPassword(final String password) { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("setPassword(****)"); } @@ -263,17 +245,14 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon * @throws JMSException Thrown if an error occurs */ @Override - public String getClientID() throws JMSException - { - if (ActiveMQRASessionFactoryImpl.trace) - { + public String getClientID() throws JMSException { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("getClientID()"); } checkClosed(); - if (clientID == null) - { + if (clientID == null) { return ((ActiveMQResourceAdapter) mcf.getResourceAdapter()).getProperties().getClientID(); } @@ -287,10 +266,8 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon * @throws JMSException Thrown if an error occurs */ @Override - public void setClientID(final String cID) throws JMSException - { - if (ActiveMQRASessionFactoryImpl.trace) - { + public void setClientID(final String cID) throws JMSException { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("setClientID(" + cID + ")"); } @@ -305,17 +282,14 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon * @return The queue session * @throws JMSException Thrown if an error occurs */ - public QueueSession createQueueSession(final boolean transacted, final int acknowledgeMode) throws JMSException - { - if (ActiveMQRASessionFactoryImpl.trace) - { + public QueueSession createQueueSession(final boolean transacted, final int acknowledgeMode) throws JMSException { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createQueueSession(" + transacted + ", " + acknowledgeMode + ")"); } checkClosed(); - if (type == ActiveMQRAConnectionFactory.TOPIC_CONNECTION || type == ActiveMQRAConnectionFactory.XA_TOPIC_CONNECTION) - { + if (type == ActiveMQRAConnectionFactory.TOPIC_CONNECTION || type == ActiveMQRAConnectionFactory.XA_TOPIC_CONNECTION) { throw new IllegalStateException("Can not get a queue session from a topic connection"); } @@ -328,18 +302,15 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon * @return The XA queue session * @throws JMSException Thrown if an error occurs */ - public XAQueueSession createXAQueueSession() throws JMSException - { - if (ActiveMQRASessionFactoryImpl.trace) - { + public XAQueueSession createXAQueueSession() throws JMSException { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createXAQueueSession()"); } checkClosed(); if (type == ActiveMQRAConnectionFactory.CONNECTION || type == ActiveMQRAConnectionFactory.TOPIC_CONNECTION || - type == ActiveMQRAConnectionFactory.XA_TOPIC_CONNECTION) - { + type == ActiveMQRAConnectionFactory.XA_TOPIC_CONNECTION) { throw new IllegalStateException("Can not get a topic session from a queue connection"); } @@ -359,18 +330,16 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon public ConnectionConsumer createConnectionConsumer(final Queue queue, final String messageSelector, final ServerSessionPool sessionPool, - final int maxMessages) throws JMSException - { - if (ActiveMQRASessionFactoryImpl.trace) - { + final int maxMessages) throws JMSException { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createConnectionConsumer(" + queue + - ", " + - messageSelector + - ", " + - sessionPool + - ", " + - maxMessages + - ")"); + ", " + + messageSelector + + ", " + + sessionPool + + ", " + + maxMessages + + ")"); } throw new IllegalStateException(ISE); @@ -384,17 +353,14 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon * @return The topic session * @throws JMSException Thrown if an error occurs */ - public TopicSession createTopicSession(final boolean transacted, final int acknowledgeMode) throws JMSException - { - if (ActiveMQRASessionFactoryImpl.trace) - { + public TopicSession createTopicSession(final boolean transacted, final int acknowledgeMode) throws JMSException { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createTopicSession(" + transacted + ", " + acknowledgeMode + ")"); } checkClosed(); - if (type == ActiveMQRAConnectionFactory.QUEUE_CONNECTION || type == ActiveMQRAConnectionFactory.XA_QUEUE_CONNECTION) - { + if (type == ActiveMQRAConnectionFactory.QUEUE_CONNECTION || type == ActiveMQRAConnectionFactory.XA_QUEUE_CONNECTION) { throw new IllegalStateException("Can not get a topic session from a queue connection"); } @@ -407,18 +373,15 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon * @return The XA topic session * @throws JMSException Thrown if an error occurs */ - public XATopicSession createXATopicSession() throws JMSException - { - if (ActiveMQRASessionFactoryImpl.trace) - { + public XATopicSession createXATopicSession() throws JMSException { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createXATopicSession()"); } checkClosed(); if (type == ActiveMQRAConnectionFactory.CONNECTION || type == ActiveMQRAConnectionFactory.QUEUE_CONNECTION || - type == ActiveMQRAConnectionFactory.XA_QUEUE_CONNECTION) - { + type == ActiveMQRAConnectionFactory.XA_QUEUE_CONNECTION) { throw new IllegalStateException("Can not get a topic session from a queue connection"); } @@ -438,18 +401,16 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon public ConnectionConsumer createConnectionConsumer(final Topic topic, final String messageSelector, final ServerSessionPool sessionPool, - final int maxMessages) throws JMSException - { - if (ActiveMQRASessionFactoryImpl.trace) - { + final int maxMessages) throws JMSException { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createConnectionConsumer(" + topic + - ", " + - messageSelector + - ", " + - sessionPool + - ", " + - maxMessages + - ")"); + ", " + + messageSelector + + ", " + + sessionPool + + ", " + + maxMessages + + ")"); } throw new IllegalStateException(ISE); @@ -471,20 +432,18 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon final String subscriptionName, final String messageSelector, final ServerSessionPool sessionPool, - final int maxMessages) throws JMSException - { - if (ActiveMQRASessionFactoryImpl.trace) - { + final int maxMessages) throws JMSException { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createConnectionConsumer(" + topic + - ", " + - subscriptionName + - ", " + - messageSelector + - ", " + - sessionPool + - ", " + - maxMessages + - ")"); + ", " + + subscriptionName + + ", " + + messageSelector + + ", " + + sessionPool + + ", " + + maxMessages + + ")"); } throw new IllegalStateException(ISE); @@ -501,16 +460,14 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon */ public ConnectionConsumer createConnectionConsumer(final Destination destination, final ServerSessionPool pool, - final int maxMessages) throws JMSException - { - if (ActiveMQRASessionFactoryImpl.trace) - { + final int maxMessages) throws JMSException { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createConnectionConsumer(" + destination + - ", " + - pool + - ", " + - maxMessages + - ")"); + ", " + + pool + + ", " + + maxMessages + + ")"); } throw new IllegalStateException(ISE); @@ -530,18 +487,16 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon public ConnectionConsumer createConnectionConsumer(final Destination destination, final String name, final ServerSessionPool pool, - final int maxMessages) throws JMSException - { - if (ActiveMQRASessionFactoryImpl.trace) - { + final int maxMessages) throws JMSException { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createConnectionConsumer(" + destination + - ", " + - name + - ", " + - pool + - ", " + - maxMessages + - ")"); + ", " + + name + + ", " + + pool + + ", " + + maxMessages + + ")"); } throw new IllegalStateException(ISE); @@ -556,10 +511,8 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon * @throws JMSException Thrown if an error occurs */ @Override - public Session createSession(final boolean transacted, final int acknowledgeMode) throws JMSException - { - if (ActiveMQRASessionFactoryImpl.trace) - { + public Session createSession(final boolean transacted, final int acknowledgeMode) throws JMSException { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createSession(" + transacted + ", " + acknowledgeMode + ")"); } @@ -573,10 +526,8 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon * @return The XA session * @throws JMSException Thrown if an error occurs */ - public XASession createXASession() throws JMSException - { - if (ActiveMQRASessionFactoryImpl.trace) - { + public XASession createXASession() throws JMSException { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createXASession()"); } @@ -591,10 +542,8 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon * @throws JMSException Thrown if an error occurs */ @Override - public ConnectionMetaData getMetaData() throws JMSException - { - if (ActiveMQRASessionFactoryImpl.trace) - { + public ConnectionMetaData getMetaData() throws JMSException { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("getMetaData()"); } @@ -609,10 +558,8 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon * @throws JMSException Thrown if an error occurs */ @Override - public ExceptionListener getExceptionListener() throws JMSException - { - if (ActiveMQRASessionFactoryImpl.trace) - { + public ExceptionListener getExceptionListener() throws JMSException { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("getExceptionListener()"); } @@ -626,10 +573,8 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon * @throws JMSException Thrown if an error occurs */ @Override - public void setExceptionListener(final ExceptionListener listener) throws JMSException - { - if (ActiveMQRASessionFactoryImpl.trace) - { + public void setExceptionListener(final ExceptionListener listener) throws JMSException { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("setExceptionListener(" + listener + ")"); } @@ -642,24 +587,19 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon * @throws JMSException Thrown if an error occurs */ @Override - public void start() throws JMSException - { + public void start() throws JMSException { checkClosed(); - if (ActiveMQRASessionFactoryImpl.trace) - { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("start() " + this); } - synchronized (sessions) - { - if (started) - { + synchronized (sessions) { + if (started) { return; } started = true; - for (ActiveMQRASession session : sessions) - { + for (ActiveMQRASession session : sessions) { session.start(); } } @@ -672,10 +612,8 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon * @throws JMSException Thrown if an error occurs */ @Override - public void stop() throws JMSException - { - if (ActiveMQRASessionFactoryImpl.trace) - { + public void stop() throws JMSException { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("stop() " + this); } @@ -688,73 +626,56 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon * @throws JMSException Thrown if an error occurs */ @Override - public void close() throws JMSException - { - if (ActiveMQRASessionFactoryImpl.trace) - { + public void close() throws JMSException { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("close() " + this); } - if (closed) - { + if (closed) { return; } closed = true; - synchronized (sessions) - { - for (Iterator i = sessions.iterator(); i.hasNext(); ) - { + synchronized (sessions) { + for (Iterator i = sessions.iterator(); i.hasNext(); ) { ActiveMQRASession session = i.next(); - try - { + try { session.closeSession(); } - catch (Throwable t) - { + catch (Throwable t) { ActiveMQRALogger.LOGGER.trace("Error closing session", t); } i.remove(); } } - synchronized (tempQueues) - { - for (Iterator i = tempQueues.iterator(); i.hasNext(); ) - { + synchronized (tempQueues) { + for (Iterator i = tempQueues.iterator(); i.hasNext(); ) { TemporaryQueue temp = i.next(); - try - { - if (ActiveMQRASessionFactoryImpl.trace) - { + try { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("Closing temporary queue " + temp + " for " + this); } temp.delete(); } - catch (Throwable t) - { + catch (Throwable t) { ActiveMQRALogger.LOGGER.trace("Error deleting temporary queue", t); } i.remove(); } } - synchronized (tempTopics) - { - for (Iterator i = tempTopics.iterator(); i.hasNext(); ) - { + synchronized (tempTopics) { + for (Iterator i = tempTopics.iterator(); i.hasNext(); ) { TemporaryTopic temp = i.next(); - try - { - if (ActiveMQRASessionFactoryImpl.trace) - { + try { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("Closing temporary topic " + temp + " for " + this); } temp.delete(); } - catch (Throwable t) - { + catch (Throwable t) { ActiveMQRALogger.LOGGER.trace("Error deleting temporary queue", t); } i.remove(); @@ -768,15 +689,12 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon * @param session The session * @throws JMSException Thrown if an error occurs */ - public void closeSession(final ActiveMQRASession session) throws JMSException - { - if (ActiveMQRASessionFactoryImpl.trace) - { + public void closeSession(final ActiveMQRASession session) throws JMSException { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("closeSession(" + session + ")"); } - synchronized (sessions) - { + synchronized (sessions) { sessions.remove(session); } } @@ -786,15 +704,12 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon * * @param temp The temporary queue */ - public void addTemporaryQueue(final TemporaryQueue temp) - { - if (ActiveMQRASessionFactoryImpl.trace) - { + public void addTemporaryQueue(final TemporaryQueue temp) { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("addTemporaryQueue(" + temp + ")"); } - synchronized (tempQueues) - { + synchronized (tempQueues) { tempQueues.add(temp); } } @@ -804,50 +719,49 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon * * @param temp The temporary topic */ - public void addTemporaryTopic(final TemporaryTopic temp) - { - if (ActiveMQRASessionFactoryImpl.trace) - { + public void addTemporaryTopic(final TemporaryTopic temp) { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("addTemporaryTopic(" + temp + ")"); } - synchronized (tempTopics) - { + synchronized (tempTopics) { tempTopics.add(temp); } } @Override - public Session createSession(int sessionMode) throws JMSException - { + public Session createSession(int sessionMode) throws JMSException { return createSession(sessionMode == Session.SESSION_TRANSACTED, sessionMode); } @Override - public Session createSession() throws JMSException - { + public Session createSession() throws JMSException { return createSession(Session.AUTO_ACKNOWLEDGE); } @Override - public ConnectionConsumer createSharedConnectionConsumer(Topic topic, String subscriptionName, String messageSelector, ServerSessionPool sessionPool, int maxMessages) throws JMSException - { - if (ActiveMQRASessionFactoryImpl.trace) - { + public ConnectionConsumer createSharedConnectionConsumer(Topic topic, + String subscriptionName, + String messageSelector, + ServerSessionPool sessionPool, + int maxMessages) throws JMSException { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createSharedConnectionConsumer(" + topic + ", " + subscriptionName + ", " + - messageSelector + ", " + sessionPool + ", " + maxMessages + ")"); + messageSelector + ", " + sessionPool + ", " + maxMessages + ")"); } throw new IllegalStateException(ISE); } @Override - public ConnectionConsumer createSharedDurableConnectionConsumer(Topic topic, String subscriptionName, String messageSelector, ServerSessionPool sessionPool, int maxMessages) throws JMSException - { - if (ActiveMQRASessionFactoryImpl.trace) - { + public ConnectionConsumer createSharedDurableConnectionConsumer(Topic topic, + String subscriptionName, + String messageSelector, + ServerSessionPool sessionPool, + int maxMessages) throws JMSException { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createSharedDurableConnectionConsumer(" + topic + ", " + subscriptionName + - ", " + messageSelector + ", " + sessionPool + ", " + maxMessages + ")"); + ", " + messageSelector + ", " + sessionPool + ", " + maxMessages + ")"); } throw new IllegalStateException(ISE); @@ -860,8 +774,7 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon * @return The session * @throws JMSException Thrown if an error occurs */ - protected ActiveMQRASession allocateConnection(final int sessionType) throws JMSException - { + protected ActiveMQRASession allocateConnection(final int sessionType) throws JMSException { return allocateConnection(false, Session.AUTO_ACKNOWLEDGE, sessionType); } @@ -874,31 +787,27 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon * @return The session * @throws JMSException Thrown if an error occurs */ - protected ActiveMQRASession allocateConnection(boolean transacted, int acknowledgeMode, final int sessionType) throws JMSException - { - if (ActiveMQRASessionFactoryImpl.trace) - { + protected ActiveMQRASession allocateConnection(boolean transacted, + int acknowledgeMode, + final int sessionType) throws JMSException { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("allocateConnection(" + transacted + - ", " + - acknowledgeMode + - ", " + - sessionType + - ")"); + ", " + + acknowledgeMode + + ", " + + sessionType + + ")"); } - try - { - synchronized (sessions) - { - if (sessions.isEmpty() == false) - { + try { + synchronized (sessions) { + if (sessions.isEmpty() == false) { throw new IllegalStateException("Only allowed one session per connection. See the J2EE spec, e.g. J2EE1.4 Section 6.6"); } //from createSession // In a Java EE web or EJB container, when there is an active JTA transaction in progress: //Both arguments {@code transacted} and {@code acknowledgeMode} are ignored. - if (inJtaTransaction()) - { + if (inJtaTransaction()) { transacted = true; //from getAcknowledgeMode // If the session is not transacted, returns the @@ -909,12 +818,10 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon } //In the Java EE web or EJB container, when there is no active JTA transaction in progress // The argument {@code transacted} is ignored. - else - { + else { //The session will always be non-transacted, transacted = false; - switch (acknowledgeMode) - { + switch (acknowledgeMode) { //using one of the two acknowledgement modes AUTO_ACKNOWLEDGE and DUPS_OK_ACKNOWLEDGE. case Session.AUTO_ACKNOWLEDGE: case Session.DUPS_OK_ACKNOWLEDGE: @@ -933,32 +840,26 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon } } - ActiveMQRAConnectionRequestInfo info = new ActiveMQRAConnectionRequestInfo(transacted, - acknowledgeMode, - sessionType); + ActiveMQRAConnectionRequestInfo info = new ActiveMQRAConnectionRequestInfo(transacted, acknowledgeMode, sessionType); info.setUserName(userName); info.setPassword(password); info.setClientID(clientID); info.setDefaults(((ActiveMQResourceAdapter) mcf.getResourceAdapter()).getProperties()); - if (ActiveMQRASessionFactoryImpl.trace) - { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("Allocating session for " + this + " with request info=" + info); } ActiveMQRASession session = (ActiveMQRASession) cm.allocateConnection(mcf, info); - try - { - if (ActiveMQRASessionFactoryImpl.trace) - { + try { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("Allocated " + this + " session=" + session); } session.setActiveMQSessionFactory(this); - if (started) - { + if (started) { session.start(); } @@ -966,40 +867,31 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon return session; } - catch (Throwable t) - { - try - { + catch (Throwable t) { + try { session.close(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } - if (t instanceof Exception) - { + if (t instanceof Exception) { throw (Exception) t; } - else - { + else { throw new RuntimeException("Unexpected error: ", t); } } } } - catch (Exception e) - { + catch (Exception e) { Throwable current = e; - while (current != null && !(current instanceof JMSException)) - { + while (current != null && !(current instanceof JMSException)) { current = current.getCause(); } - if (current != null && current instanceof JMSException) - { + if (current != null && current instanceof JMSException) { throw (JMSException) current; } - else - { + else { JMSException je = new JMSException("Could not create a session: " + e.getMessage()); je.setLinkedException(e); je.initCause(e); @@ -1013,31 +905,24 @@ public final class ActiveMQRASessionFactoryImpl extends ActiveMQConnectionForCon * * @throws IllegalStateException Thrown if closed */ - protected void checkClosed() throws IllegalStateException - { - if (ActiveMQRASessionFactoryImpl.trace) - { + protected void checkClosed() throws IllegalStateException { + if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("checkClosed()" + this); } - if (closed) - { + if (closed) { throw new IllegalStateException("The connection is closed"); } } - private boolean inJtaTransaction() - { + private boolean inJtaTransaction() { boolean inJtaTx = false; - if (tm != null) - { + if (tm != null) { Transaction tx = null; - try - { + try { tx = tm.getTransaction(); } - catch (SystemException e) - { + catch (SystemException e) { //assume false } inJtaTx = tx != null; diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAStreamMessage.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAStreamMessage.java index 711ffe2a3b..2465ae8b11 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAStreamMessage.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAStreamMessage.java @@ -21,389 +21,365 @@ import java.util.Arrays; import javax.jms.JMSException; import javax.jms.StreamMessage; - /** * A wrapper for a message */ -public class ActiveMQRAStreamMessage extends ActiveMQRAMessage implements StreamMessage -{ - /** Whether trace is enabled */ +public class ActiveMQRAStreamMessage extends ActiveMQRAMessage implements StreamMessage { + + /** + * Whether trace is enabled + */ private static boolean trace = ActiveMQRALogger.LOGGER.isTraceEnabled(); /** * Create a new wrapper + * * @param message the message * @param session the session */ - public ActiveMQRAStreamMessage(final StreamMessage message, final ActiveMQRASession session) - { + public ActiveMQRAStreamMessage(final StreamMessage message, final ActiveMQRASession session) { super(message, session); - if (ActiveMQRAStreamMessage.trace) - { + if (ActiveMQRAStreamMessage.trace) { ActiveMQRALogger.LOGGER.trace("constructor(" + message + ", " + session + ")"); } } /** * Read + * * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public boolean readBoolean() throws JMSException - { - if (ActiveMQRAStreamMessage.trace) - { + public boolean readBoolean() throws JMSException { + if (ActiveMQRAStreamMessage.trace) { ActiveMQRALogger.LOGGER.trace("readBoolean()"); } - return ((StreamMessage)message).readBoolean(); + return ((StreamMessage) message).readBoolean(); } /** * Read + * * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public byte readByte() throws JMSException - { - if (ActiveMQRAStreamMessage.trace) - { + public byte readByte() throws JMSException { + if (ActiveMQRAStreamMessage.trace) { ActiveMQRALogger.LOGGER.trace("readByte()"); } - return ((StreamMessage)message).readByte(); + return ((StreamMessage) message).readByte(); } /** * Read + * * @param value The value * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public int readBytes(final byte[] value) throws JMSException - { - if (ActiveMQRAStreamMessage.trace) - { + public int readBytes(final byte[] value) throws JMSException { + if (ActiveMQRAStreamMessage.trace) { ActiveMQRALogger.LOGGER.trace("readBytes(" + Arrays.toString(value) + ")"); } - return ((StreamMessage)message).readBytes(value); + return ((StreamMessage) message).readBytes(value); } /** * Read + * * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public char readChar() throws JMSException - { - if (ActiveMQRAStreamMessage.trace) - { + public char readChar() throws JMSException { + if (ActiveMQRAStreamMessage.trace) { ActiveMQRALogger.LOGGER.trace("readChar()"); } - return ((StreamMessage)message).readChar(); + return ((StreamMessage) message).readChar(); } /** * Read + * * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public double readDouble() throws JMSException - { - if (ActiveMQRAStreamMessage.trace) - { + public double readDouble() throws JMSException { + if (ActiveMQRAStreamMessage.trace) { ActiveMQRALogger.LOGGER.trace("readDouble()"); } - return ((StreamMessage)message).readDouble(); + return ((StreamMessage) message).readDouble(); } /** * Read + * * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public float readFloat() throws JMSException - { - if (ActiveMQRAStreamMessage.trace) - { + public float readFloat() throws JMSException { + if (ActiveMQRAStreamMessage.trace) { ActiveMQRALogger.LOGGER.trace("readFloat()"); } - return ((StreamMessage)message).readFloat(); + return ((StreamMessage) message).readFloat(); } /** * Read + * * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public int readInt() throws JMSException - { - if (ActiveMQRAStreamMessage.trace) - { + public int readInt() throws JMSException { + if (ActiveMQRAStreamMessage.trace) { ActiveMQRALogger.LOGGER.trace("readInt()"); } - return ((StreamMessage)message).readInt(); + return ((StreamMessage) message).readInt(); } /** * Read + * * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public long readLong() throws JMSException - { - if (ActiveMQRAStreamMessage.trace) - { + public long readLong() throws JMSException { + if (ActiveMQRAStreamMessage.trace) { ActiveMQRALogger.LOGGER.trace("readLong()"); } - return ((StreamMessage)message).readLong(); + return ((StreamMessage) message).readLong(); } /** * Read + * * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public Object readObject() throws JMSException - { - if (ActiveMQRAStreamMessage.trace) - { + public Object readObject() throws JMSException { + if (ActiveMQRAStreamMessage.trace) { ActiveMQRALogger.LOGGER.trace("readObject()"); } - return ((StreamMessage)message).readObject(); + return ((StreamMessage) message).readObject(); } /** * Read + * * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public short readShort() throws JMSException - { - if (ActiveMQRAStreamMessage.trace) - { + public short readShort() throws JMSException { + if (ActiveMQRAStreamMessage.trace) { ActiveMQRALogger.LOGGER.trace("readShort()"); } - return ((StreamMessage)message).readShort(); + return ((StreamMessage) message).readShort(); } /** * Read + * * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public String readString() throws JMSException - { - if (ActiveMQRAStreamMessage.trace) - { + public String readString() throws JMSException { + if (ActiveMQRAStreamMessage.trace) { ActiveMQRALogger.LOGGER.trace("readString()"); } - return ((StreamMessage)message).readString(); + return ((StreamMessage) message).readString(); } /** * Reset - * @exception JMSException Thrown if an error occurs + * + * @throws JMSException Thrown if an error occurs */ - public void reset() throws JMSException - { - if (ActiveMQRAStreamMessage.trace) - { + public void reset() throws JMSException { + if (ActiveMQRAStreamMessage.trace) { ActiveMQRALogger.LOGGER.trace("reset()"); } - ((StreamMessage)message).reset(); + ((StreamMessage) message).reset(); } /** * Write + * * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void writeBoolean(final boolean value) throws JMSException - { - if (ActiveMQRAStreamMessage.trace) - { + public void writeBoolean(final boolean value) throws JMSException { + if (ActiveMQRAStreamMessage.trace) { ActiveMQRALogger.LOGGER.trace("writeBoolean(" + value + ")"); } - ((StreamMessage)message).writeBoolean(value); + ((StreamMessage) message).writeBoolean(value); } /** * Write + * * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void writeByte(final byte value) throws JMSException - { - if (ActiveMQRAStreamMessage.trace) - { + public void writeByte(final byte value) throws JMSException { + if (ActiveMQRAStreamMessage.trace) { ActiveMQRALogger.LOGGER.trace("writeByte(" + value + ")"); } - ((StreamMessage)message).writeByte(value); + ((StreamMessage) message).writeByte(value); } /** * Write - * @param value The value + * + * @param value The value * @param offset The offset * @param length The length - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void writeBytes(final byte[] value, final int offset, final int length) throws JMSException - { - if (ActiveMQRAStreamMessage.trace) - { + public void writeBytes(final byte[] value, final int offset, final int length) throws JMSException { + if (ActiveMQRAStreamMessage.trace) { ActiveMQRALogger.LOGGER.trace("writeBytes(" + Arrays.toString(value) + ", " + offset + ", " + length + ")"); } - ((StreamMessage)message).writeBytes(value, offset, length); + ((StreamMessage) message).writeBytes(value, offset, length); } /** * Write + * * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void writeBytes(final byte[] value) throws JMSException - { - if (ActiveMQRAStreamMessage.trace) - { + public void writeBytes(final byte[] value) throws JMSException { + if (ActiveMQRAStreamMessage.trace) { ActiveMQRALogger.LOGGER.trace("writeBytes(" + Arrays.toString(value) + ")"); } - ((StreamMessage)message).writeBytes(value); + ((StreamMessage) message).writeBytes(value); } /** * Write + * * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void writeChar(final char value) throws JMSException - { - if (ActiveMQRAStreamMessage.trace) - { + public void writeChar(final char value) throws JMSException { + if (ActiveMQRAStreamMessage.trace) { ActiveMQRALogger.LOGGER.trace("writeChar(" + value + ")"); } - ((StreamMessage)message).writeChar(value); + ((StreamMessage) message).writeChar(value); } /** * Write + * * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void writeDouble(final double value) throws JMSException - { - if (ActiveMQRAStreamMessage.trace) - { + public void writeDouble(final double value) throws JMSException { + if (ActiveMQRAStreamMessage.trace) { ActiveMQRALogger.LOGGER.trace("writeDouble(" + value + ")"); } - ((StreamMessage)message).writeDouble(value); + ((StreamMessage) message).writeDouble(value); } /** * Write + * * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void writeFloat(final float value) throws JMSException - { - if (ActiveMQRAStreamMessage.trace) - { + public void writeFloat(final float value) throws JMSException { + if (ActiveMQRAStreamMessage.trace) { ActiveMQRALogger.LOGGER.trace("writeFloat(" + value + ")"); } - ((StreamMessage)message).writeFloat(value); + ((StreamMessage) message).writeFloat(value); } /** * Write + * * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void writeInt(final int value) throws JMSException - { - if (ActiveMQRAStreamMessage.trace) - { + public void writeInt(final int value) throws JMSException { + if (ActiveMQRAStreamMessage.trace) { ActiveMQRALogger.LOGGER.trace("writeInt(" + value + ")"); } - ((StreamMessage)message).writeInt(value); + ((StreamMessage) message).writeInt(value); } /** * Write + * * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void writeLong(final long value) throws JMSException - { - if (ActiveMQRAStreamMessage.trace) - { + public void writeLong(final long value) throws JMSException { + if (ActiveMQRAStreamMessage.trace) { ActiveMQRALogger.LOGGER.trace("writeLong(" + value + ")"); } - ((StreamMessage)message).writeLong(value); + ((StreamMessage) message).writeLong(value); } /** * Write + * * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void writeObject(final Object value) throws JMSException - { - if (ActiveMQRAStreamMessage.trace) - { + public void writeObject(final Object value) throws JMSException { + if (ActiveMQRAStreamMessage.trace) { ActiveMQRALogger.LOGGER.trace("writeObject(" + value + ")"); } - ((StreamMessage)message).writeObject(value); + ((StreamMessage) message).writeObject(value); } /** * Write + * * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void writeShort(final short value) throws JMSException - { - if (ActiveMQRAStreamMessage.trace) - { + public void writeShort(final short value) throws JMSException { + if (ActiveMQRAStreamMessage.trace) { ActiveMQRALogger.LOGGER.trace("writeShort(" + value + ")"); } - ((StreamMessage)message).writeShort(value); + ((StreamMessage) message).writeShort(value); } /** * Write + * * @param value The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void writeString(final String value) throws JMSException - { - if (ActiveMQRAStreamMessage.trace) - { + public void writeString(final String value) throws JMSException { + if (ActiveMQRAStreamMessage.trace) { ActiveMQRALogger.LOGGER.trace("writeString(" + value + ")"); } - ((StreamMessage)message).writeString(value); + ((StreamMessage) message).writeString(value); } } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRATextMessage.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRATextMessage.java index 312335326e..0ab9fb3b07 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRATextMessage.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRATextMessage.java @@ -19,57 +19,55 @@ package org.apache.activemq.artemis.ra; import javax.jms.JMSException; import javax.jms.TextMessage; - /** * A wrapper for a message */ -public class ActiveMQRATextMessage extends ActiveMQRAMessage implements TextMessage -{ - /** Whether trace is enabled */ +public class ActiveMQRATextMessage extends ActiveMQRAMessage implements TextMessage { + + /** + * Whether trace is enabled + */ private static boolean trace = ActiveMQRALogger.LOGGER.isTraceEnabled(); /** * Create a new wrapper + * * @param message the message * @param session the session */ - public ActiveMQRATextMessage(final TextMessage message, final ActiveMQRASession session) - { + public ActiveMQRATextMessage(final TextMessage message, final ActiveMQRASession session) { super(message, session); - if (ActiveMQRATextMessage.trace) - { + if (ActiveMQRATextMessage.trace) { ActiveMQRALogger.LOGGER.trace("constructor(" + message + ", " + session + ")"); } } /** * Get text + * * @return The text - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public String getText() throws JMSException - { - if (ActiveMQRATextMessage.trace) - { + public String getText() throws JMSException { + if (ActiveMQRATextMessage.trace) { ActiveMQRALogger.LOGGER.trace("getText()"); } - return ((TextMessage)message).getText(); + return ((TextMessage) message).getText(); } /** * Set text + * * @param string The text - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void setText(final String string) throws JMSException - { - if (ActiveMQRATextMessage.trace) - { + public void setText(final String string) throws JMSException { + if (ActiveMQRATextMessage.trace) { ActiveMQRALogger.LOGGER.trace("setText(" + string + ")"); } - ((TextMessage)message).setText(string); + ((TextMessage) message).setText(string); } } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRATopicPublisher.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRATopicPublisher.java index 622aeea9e7..87ddd227f3 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRATopicPublisher.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRATopicPublisher.java @@ -21,191 +21,177 @@ import javax.jms.Message; import javax.jms.Topic; import javax.jms.TopicPublisher; - /** * ActiveMQQueueSender. */ -public class ActiveMQRATopicPublisher extends ActiveMQRAMessageProducer implements TopicPublisher -{ - /** Whether trace is enabled */ +public class ActiveMQRATopicPublisher extends ActiveMQRAMessageProducer implements TopicPublisher { + + /** + * Whether trace is enabled + */ private static boolean trace = ActiveMQRALogger.LOGGER.isTraceEnabled(); /** * Create a new wrapper + * * @param producer the producer - * @param session the session + * @param session the session */ - public ActiveMQRATopicPublisher(final TopicPublisher producer, final ActiveMQRASession session) - { + public ActiveMQRATopicPublisher(final TopicPublisher producer, final ActiveMQRASession session) { super(producer, session); - if (ActiveMQRATopicPublisher.trace) - { + if (ActiveMQRATopicPublisher.trace) { ActiveMQRALogger.LOGGER.trace("constructor(" + producer + ", " + session + ")"); } } /** * Get the topic + * * @return The topic - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public Topic getTopic() throws JMSException - { - if (ActiveMQRATopicPublisher.trace) - { + public Topic getTopic() throws JMSException { + if (ActiveMQRATopicPublisher.trace) { ActiveMQRALogger.LOGGER.trace("getTopic()"); } - return ((TopicPublisher)producer).getTopic(); + return ((TopicPublisher) producer).getTopic(); } /** * Publish message - * @param message The message + * + * @param message The message * @param deliveryMode The delivery mode - * @param priority The priority - * @param timeToLive The time to live - * @exception JMSException Thrown if an error occurs + * @param priority The priority + * @param timeToLive The time to live + * @throws JMSException Thrown if an error occurs */ - public void publish(final Message message, final int deliveryMode, final int priority, final long timeToLive) throws JMSException - { + public void publish(final Message message, + final int deliveryMode, + final int priority, + final long timeToLive) throws JMSException { session.lock(); - try - { - if (ActiveMQRATopicPublisher.trace) - { + try { + if (ActiveMQRATopicPublisher.trace) { ActiveMQRALogger.LOGGER.trace("send " + this + - " message=" + - message + - " deliveryMode=" + - deliveryMode + - " priority=" + - priority + - " ttl=" + - timeToLive); + " message=" + + message + + " deliveryMode=" + + deliveryMode + + " priority=" + + priority + + " ttl=" + + timeToLive); } checkState(); - ((TopicPublisher)producer).publish(message, deliveryMode, priority, timeToLive); + ((TopicPublisher) producer).publish(message, deliveryMode, priority, timeToLive); - if (ActiveMQRATopicPublisher.trace) - { + if (ActiveMQRATopicPublisher.trace) { ActiveMQRALogger.LOGGER.trace("sent " + this + " result=" + message); } } - finally - { + finally { session.unlock(); } } /** * Publish message + * * @param message The message - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public void publish(final Message message) throws JMSException - { + public void publish(final Message message) throws JMSException { session.lock(); - try - { - if (ActiveMQRATopicPublisher.trace) - { + try { + if (ActiveMQRATopicPublisher.trace) { ActiveMQRALogger.LOGGER.trace("send " + this + " message=" + message); } checkState(); - ((TopicPublisher)producer).publish(message); + ((TopicPublisher) producer).publish(message); - if (ActiveMQRATopicPublisher.trace) - { + if (ActiveMQRATopicPublisher.trace) { ActiveMQRALogger.LOGGER.trace("sent " + this + " result=" + message); } } - finally - { + finally { session.unlock(); } } /** * Publish message - * @param destination The destination - * @param message The message + * + * @param destination The destination + * @param message The message * @param deliveryMode The delivery mode - * @param priority The priority - * @param timeToLive The time to live - * @exception JMSException Thrown if an error occurs + * @param priority The priority + * @param timeToLive The time to live + * @throws JMSException Thrown if an error occurs */ public void publish(final Topic destination, final Message message, final int deliveryMode, final int priority, - final long timeToLive) throws JMSException - { + final long timeToLive) throws JMSException { session.lock(); - try - { - if (ActiveMQRATopicPublisher.trace) - { + try { + if (ActiveMQRATopicPublisher.trace) { ActiveMQRALogger.LOGGER.trace("send " + this + - " destination=" + - destination + - " message=" + - message + - " deliveryMode=" + - deliveryMode + - " priority=" + - priority + - " ttl=" + - timeToLive); + " destination=" + + destination + + " message=" + + message + + " deliveryMode=" + + deliveryMode + + " priority=" + + priority + + " ttl=" + + timeToLive); } checkState(); - ((TopicPublisher)producer).publish(destination, message, deliveryMode, priority, timeToLive); + ((TopicPublisher) producer).publish(destination, message, deliveryMode, priority, timeToLive); - if (ActiveMQRATopicPublisher.trace) - { + if (ActiveMQRATopicPublisher.trace) { ActiveMQRALogger.LOGGER.trace("sent " + this + " result=" + message); } } - finally - { + finally { session.unlock(); } } /** * Publish message + * * @param destination The destination - * @param message The message - * @exception JMSException Thrown if an error occurs + * @param message The message + * @throws JMSException Thrown if an error occurs */ - public void publish(final Topic destination, final Message message) throws JMSException - { + public void publish(final Topic destination, final Message message) throws JMSException { session.lock(); - try - { - if (ActiveMQRATopicPublisher.trace) - { + try { + if (ActiveMQRATopicPublisher.trace) { ActiveMQRALogger.LOGGER.trace("send " + this + " destination=" + destination + " message=" + message); } checkState(); - ((TopicPublisher)producer).publish(destination, message); + ((TopicPublisher) producer).publish(destination, message); - if (ActiveMQRATopicPublisher.trace) - { + if (ActiveMQRATopicPublisher.trace) { ActiveMQRALogger.LOGGER.trace("sent " + this + " result=" + message); } } - finally - { + finally { session.unlock(); } } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRATopicSubscriber.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRATopicSubscriber.java index e264799186..626020f650 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRATopicSubscriber.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRATopicSubscriber.java @@ -20,59 +20,57 @@ import javax.jms.JMSException; import javax.jms.Topic; import javax.jms.TopicSubscriber; - /** * A wrapper for a topic subscriber */ -public class ActiveMQRATopicSubscriber extends ActiveMQRAMessageConsumer implements TopicSubscriber -{ - /** Whether trace is enabled */ +public class ActiveMQRATopicSubscriber extends ActiveMQRAMessageConsumer implements TopicSubscriber { + + /** + * Whether trace is enabled + */ private static boolean trace = ActiveMQRALogger.LOGGER.isTraceEnabled(); /** * Create a new wrapper + * * @param consumer the topic subscriber - * @param session the session + * @param session the session */ - public ActiveMQRATopicSubscriber(final TopicSubscriber consumer, final ActiveMQRASession session) - { + public ActiveMQRATopicSubscriber(final TopicSubscriber consumer, final ActiveMQRASession session) { super(consumer, session); - if (ActiveMQRATopicSubscriber.trace) - { + if (ActiveMQRATopicSubscriber.trace) { ActiveMQRALogger.LOGGER.trace("constructor(" + consumer + ", " + session + ")"); } } /** * Get the no local value + * * @return The value - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public boolean getNoLocal() throws JMSException - { - if (ActiveMQRATopicSubscriber.trace) - { + public boolean getNoLocal() throws JMSException { + if (ActiveMQRATopicSubscriber.trace) { ActiveMQRALogger.LOGGER.trace("getNoLocal()"); } checkState(); - return ((TopicSubscriber)consumer).getNoLocal(); + return ((TopicSubscriber) consumer).getNoLocal(); } /** * Get the topic + * * @return The topic - * @exception JMSException Thrown if an error occurs + * @throws JMSException Thrown if an error occurs */ - public Topic getTopic() throws JMSException - { - if (ActiveMQRATopicSubscriber.trace) - { + public Topic getTopic() throws JMSException { + if (ActiveMQRATopicSubscriber.trace) { ActiveMQRALogger.LOGGER.trace("getTopic()"); } checkState(); - return ((TopicSubscriber)consumer).getTopic(); + return ((TopicSubscriber) consumer).getTopic(); } } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAXAJMSContext.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAXAJMSContext.java index f3b9e26dd6..bfee4bb61e 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAXAJMSContext.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAXAJMSContext.java @@ -21,10 +21,9 @@ import org.apache.activemq.artemis.jms.client.ThreadAwareContext; import javax.jms.XAJMSContext; -public class ActiveMQRAXAJMSContext extends ActiveMQRAJMSContext implements XAJMSContext -{ - public ActiveMQRAXAJMSContext(ActiveMQConnectionForContext connection, ThreadAwareContext threadAwareContext) - { +public class ActiveMQRAXAJMSContext extends ActiveMQRAJMSContext implements XAJMSContext { + + public ActiveMQRAXAJMSContext(ActiveMQConnectionForContext connection, ThreadAwareContext threadAwareContext) { super(connection, threadAwareContext); } } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAXAResource.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAXAResource.java index 60fd8993bd..e2baea6853 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAXAResource.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRAXAResource.java @@ -27,26 +27,31 @@ import org.apache.activemq.artemis.core.client.impl.ActiveMQXAResource; /** * ActiveMQXAResource. */ -public class ActiveMQRAXAResource implements ActiveMQXAResource -{ - /** Trace enabled */ +public class ActiveMQRAXAResource implements ActiveMQXAResource { + + /** + * Trace enabled + */ private static boolean trace = ActiveMQRALogger.LOGGER.isTraceEnabled(); - /** The managed connection */ + /** + * The managed connection + */ private final ActiveMQRAManagedConnection managedConnection; - /** The resource */ + /** + * The resource + */ private final XAResource xaResource; /** * Create a new ActiveMQXAResource. + * * @param managedConnection the managed connection - * @param xaResource the xa resource + * @param xaResource the xa resource */ - public ActiveMQRAXAResource(final ActiveMQRAManagedConnection managedConnection, final XAResource xaResource) - { - if (ActiveMQRAXAResource.trace) - { + public ActiveMQRAXAResource(final ActiveMQRAManagedConnection managedConnection, final XAResource xaResource) { + if (ActiveMQRAXAResource.trace) { ActiveMQRALogger.LOGGER.trace("constructor(" + managedConnection + ", " + xaResource + ")"); } @@ -56,35 +61,30 @@ public class ActiveMQRAXAResource implements ActiveMQXAResource /** * Start - * @param xid A global transaction identifier + * + * @param xid A global transaction identifier * @param flags One of TMNOFLAGS, TMJOIN, or TMRESUME - * @exception XAException An error has occurred + * @throws XAException An error has occurred */ - public void start(final Xid xid, final int flags) throws XAException - { - if (ActiveMQRAXAResource.trace) - { + public void start(final Xid xid, final int flags) throws XAException { + if (ActiveMQRAXAResource.trace) { ActiveMQRALogger.LOGGER.trace("start(" + xid + ", " + flags + ")"); } managedConnection.lock(); ClientSessionInternal sessionInternal = (ClientSessionInternal) xaResource; - try - { + try { //this resets any tx stuff, we assume here that the tm and jca layer are well behaved when it comes to this sessionInternal.resetIfNeeded(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { ActiveMQRALogger.LOGGER.problemResettingXASession(); } - try - { + try { xaResource.start(xid, flags); } - finally - { + finally { managedConnection.setInManagedTx(true); managedConnection.unlock(); } @@ -92,24 +92,21 @@ public class ActiveMQRAXAResource implements ActiveMQXAResource /** * End - * @param xid A global transaction identifier + * + * @param xid A global transaction identifier * @param flags One of TMSUCCESS, TMFAIL, or TMSUSPEND. - * @exception XAException An error has occurred + * @throws XAException An error has occurred */ - public void end(final Xid xid, final int flags) throws XAException - { - if (ActiveMQRAXAResource.trace) - { + public void end(final Xid xid, final int flags) throws XAException { + if (ActiveMQRAXAResource.trace) { ActiveMQRALogger.LOGGER.trace("end(" + xid + ", " + flags + ")"); } managedConnection.lock(); - try - { + try { xaResource.end(xid, flags); } - finally - { + finally { managedConnection.setInManagedTx(false); managedConnection.unlock(); } @@ -117,14 +114,13 @@ public class ActiveMQRAXAResource implements ActiveMQXAResource /** * Prepare + * * @param xid A global transaction identifier * @return XA_RDONLY or XA_OK - * @exception XAException An error has occurred + * @throws XAException An error has occurred */ - public int prepare(final Xid xid) throws XAException - { - if (ActiveMQRAXAResource.trace) - { + public int prepare(final Xid xid) throws XAException { + if (ActiveMQRAXAResource.trace) { ActiveMQRALogger.LOGGER.trace("prepare(" + xid + ")"); } @@ -133,14 +129,13 @@ public class ActiveMQRAXAResource implements ActiveMQXAResource /** * Commit - * @param xid A global transaction identifier + * + * @param xid A global transaction identifier * @param onePhase If true, the resource manager should use a one-phase commit protocol to commit the work done on behalf of xid. - * @exception XAException An error has occurred + * @throws XAException An error has occurred */ - public void commit(final Xid xid, final boolean onePhase) throws XAException - { - if (ActiveMQRAXAResource.trace) - { + public void commit(final Xid xid, final boolean onePhase) throws XAException { + if (ActiveMQRAXAResource.trace) { ActiveMQRALogger.LOGGER.trace("commit(" + xid + ", " + onePhase + ")"); } @@ -149,13 +144,12 @@ public class ActiveMQRAXAResource implements ActiveMQXAResource /** * Rollback + * * @param xid A global transaction identifier - * @exception XAException An error has occurred + * @throws XAException An error has occurred */ - public void rollback(final Xid xid) throws XAException - { - if (ActiveMQRAXAResource.trace) - { + public void rollback(final Xid xid) throws XAException { + if (ActiveMQRAXAResource.trace) { ActiveMQRALogger.LOGGER.trace("rollback(" + xid + ")"); } @@ -164,23 +158,20 @@ public class ActiveMQRAXAResource implements ActiveMQXAResource /** * Forget + * * @param xid A global transaction identifier - * @exception XAException An error has occurred + * @throws XAException An error has occurred */ - public void forget(final Xid xid) throws XAException - { - if (ActiveMQRAXAResource.trace) - { + public void forget(final Xid xid) throws XAException { + if (ActiveMQRAXAResource.trace) { ActiveMQRALogger.LOGGER.trace("forget(" + xid + ")"); } managedConnection.lock(); - try - { + try { xaResource.forget(xid); } - finally - { + finally { managedConnection.setInManagedTx(true); managedConnection.setInManagedTx(false); managedConnection.unlock(); @@ -189,14 +180,13 @@ public class ActiveMQRAXAResource implements ActiveMQXAResource /** * IsSameRM + * * @param xaRes An XAResource object whose resource manager instance is to be compared with the resource manager instance of the target object. * @return True if its the same RM instance; otherwise false. - * @exception XAException An error has occurred + * @throws XAException An error has occurred */ - public boolean isSameRM(final XAResource xaRes) throws XAException - { - if (ActiveMQRAXAResource.trace) - { + public boolean isSameRM(final XAResource xaRes) throws XAException { + if (ActiveMQRAXAResource.trace) { ActiveMQRALogger.LOGGER.trace("isSameRM(" + xaRes + ")"); } @@ -205,14 +195,13 @@ public class ActiveMQRAXAResource implements ActiveMQXAResource /** * Recover + * * @param flag One of TMSTARTRSCAN, TMENDRSCAN, TMNOFLAGS * @return Zero or more XIDs - * @exception XAException An error has occurred + * @throws XAException An error has occurred */ - public Xid[] recover(final int flag) throws XAException - { - if (ActiveMQRAXAResource.trace) - { + public Xid[] recover(final int flag) throws XAException { + if (ActiveMQRAXAResource.trace) { ActiveMQRALogger.LOGGER.trace("recover(" + flag + ")"); } @@ -221,13 +210,12 @@ public class ActiveMQRAXAResource implements ActiveMQXAResource /** * Get the transaction timeout in seconds + * * @return The transaction timeout - * @exception XAException An error has occurred + * @throws XAException An error has occurred */ - public int getTransactionTimeout() throws XAException - { - if (ActiveMQRAXAResource.trace) - { + public int getTransactionTimeout() throws XAException { + if (ActiveMQRAXAResource.trace) { ActiveMQRALogger.LOGGER.trace("getTransactionTimeout()"); } @@ -236,14 +224,13 @@ public class ActiveMQRAXAResource implements ActiveMQXAResource /** * Set the transaction timeout + * * @param seconds The number of seconds * @return True if the transaction timeout value is set successfully; otherwise false. - * @exception XAException An error has occurred + * @throws XAException An error has occurred */ - public boolean setTransactionTimeout(final int seconds) throws XAException - { - if (ActiveMQRAXAResource.trace) - { + public boolean setTransactionTimeout(final int seconds) throws XAException { + if (ActiveMQRAXAResource.trace) { ActiveMQRALogger.LOGGER.trace("setTransactionTimeout(" + seconds + ")"); } @@ -251,8 +238,7 @@ public class ActiveMQRAXAResource implements ActiveMQXAResource } @Override - public XAResource getResource() - { + public XAResource getResource() { return xaResource; } } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRaUtils.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRaUtils.java index 8832155945..c72084df76 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRaUtils.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRaUtils.java @@ -31,13 +31,12 @@ import org.jgroups.JChannel; /** * Various utility functions */ -public final class ActiveMQRaUtils -{ +public final class ActiveMQRaUtils { + /** * Private constructor */ - private ActiveMQRaUtils() - { + private ActiveMQRaUtils() { } /** @@ -48,17 +47,14 @@ public final class ActiveMQRaUtils * @return True if object equals else false. */ @SuppressWarnings("StringEquality") - public static boolean compare(final String me, final String you) - { + public static boolean compare(final String me, final String you) { // If both null or intern equals - if (me == you) - { + if (me == you) { return true; } // if me null and you are not - if (me == null) - { + if (me == null) { return false; } @@ -73,17 +69,14 @@ public final class ActiveMQRaUtils * @param you Second value * @return True if object equals else false. */ - public static boolean compare(final Integer me, final Integer you) - { + public static boolean compare(final Integer me, final Integer you) { // If both null or intern equals - if (me == you) - { + if (me == you) { return true; } // if me null and you are not - if (me == null) - { + if (me == null) { return false; } @@ -98,17 +91,14 @@ public final class ActiveMQRaUtils * @param you Second value * @return True if object equals else false. */ - public static boolean compare(final Long me, final Long you) - { + public static boolean compare(final Long me, final Long you) { // If both null or intern equals - if (me == you) - { + if (me == you) { return true; } // if me null and you are not - if (me == null) - { + if (me == null) { return false; } @@ -123,17 +113,14 @@ public final class ActiveMQRaUtils * @param you Second value * @return True if object equals else false. */ - public static boolean compare(final Double me, final Double you) - { + public static boolean compare(final Double me, final Double you) { // If both null or intern equals - if (me == you) - { + if (me == you) { return true; } // if me null and you are not - if (me == null) - { + if (me == null) { return false; } @@ -148,17 +135,14 @@ public final class ActiveMQRaUtils * @param you Second value * @return True if object equals else false. */ - public static boolean compare(final Boolean me, final Boolean you) - { + public static boolean compare(final Boolean me, final Boolean you) { // If both null or intern equals - if (me == you) - { + if (me == you) { return true; } // if me null and you are not - if (me == null) - { + if (me == null) { return false; } @@ -175,8 +159,7 @@ public final class ActiveMQRaUtils * @return the object * @throws Exception for any error */ - public static Object lookup(final Context context, final String name, final Class clazz) throws Exception - { + public static Object lookup(final Context context, final String name, final Class clazz) throws Exception { return context.lookup(name); } @@ -186,18 +169,15 @@ public final class ActiveMQRaUtils * @param config * @return hash-table with configuration option pairs */ - public static Hashtable parseHashtableConfig(final String config) - { + public static Hashtable parseHashtableConfig(final String config) { Hashtable hashtable = new Hashtable(); String[] topElements = config.split(";"); - for (String element : topElements) - { + for (String element : topElements) { String[] expression = element.split("="); - if (expression.length != 2) - { + if (expression.length != 2) { throw new IllegalArgumentException("Invalid expression " + element + " at " + config); } @@ -207,25 +187,21 @@ public final class ActiveMQRaUtils return hashtable; } - public static List> parseConfig(final String config) - { + public static List> parseConfig(final String config) { List> result = new ArrayList>(); String[] topElements = config.split(","); - for (String topElement : topElements) - { + for (String topElement : topElements) { HashMap map = new HashMap(); result.add(map); String[] elements = topElement.split(";"); - for (String element : elements) - { + for (String element : elements) { String[] expression = element.split("="); - if (expression.length != 2) - { + if (expression.length != 2) { throw new IllegalArgumentException("Invalid expression " + element + " at " + config); } @@ -233,18 +209,15 @@ public final class ActiveMQRaUtils } } - return result; } - public static List parseConnectorConnectorConfig(String config) - { + public static List parseConnectorConnectorConfig(String config) { List res = new ArrayList(); String[] elements = config.split(","); - for (String element : elements) - { + for (String element : elements) { res.add(element.trim()); } @@ -256,22 +229,17 @@ public final class ActiveMQRaUtils * RA is configured using jgroups stack, we need to pass a Channel object. As is impossible with * JCA, we use this method to allow a JChannel object to be located. */ - public static JChannel locateJGroupsChannel(final String locatorClass, final String name) - { - return AccessController.doPrivileged(new PrivilegedAction() - { - public JChannel run() - { - try - { + public static JChannel locateJGroupsChannel(final String locatorClass, final String name) { + return AccessController.doPrivileged(new PrivilegedAction() { + public JChannel run() { + try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class aClass = loader.loadClass(locatorClass); Object o = aClass.newInstance(); Method m = aClass.getMethod("locateChannel", new Class[]{String.class}); return (JChannel) m.invoke(o, name); } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQRALogger.LOGGER.debug(e.getMessage(), e); return null; } @@ -284,32 +252,24 @@ public final class ActiveMQRaUtils * utility class, as it would be a door to load anything you like in a safe VM. * For that reason any class trying to do a privileged block should do with the AccessController directly. */ - private static Object safeInitNewInstance(final String className) - { - return AccessController.doPrivileged(new PrivilegedAction() - { - public Object run() - { + private static Object safeInitNewInstance(final String className) { + return AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { ClassLoader loader = getClass().getClassLoader(); - try - { + try { Class clazz = loader.loadClass(className); return clazz.newInstance(); } - catch (Throwable t) - { - try - { + catch (Throwable t) { + try { loader = Thread.currentThread().getContextClassLoader(); if (loader != null) return loader.loadClass(className).newInstance(); } - catch (RuntimeException e) - { + catch (RuntimeException e) { throw e; } - catch (Exception e) - { + catch (Exception e) { } throw new IllegalArgumentException("Could not find class " + className); @@ -318,5 +278,4 @@ public final class ActiveMQRaUtils }); } - } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQResourceAdapter.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQResourceAdapter.java index f34682e66a..8768265ff6 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQResourceAdapter.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQResourceAdapter.java @@ -61,8 +61,8 @@ import org.jgroups.JChannel; /** * The resource adapter for ActiveMQ */ -public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable -{ +public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable { + private static final long serialVersionUID = 4756893709825838770L; /** @@ -90,7 +90,6 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable */ private String unparsedProperties; - /** * The resource adapter connector classnames before parsing */ @@ -125,10 +124,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable /** * Constructor */ - public ActiveMQResourceAdapter() - { - if (ActiveMQResourceAdapter.trace) - { + public ActiveMQResourceAdapter() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("constructor()"); } @@ -138,8 +135,7 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable recoveryManager = new RecoveryManager(); } - public TransactionManager getTM() - { + public TransactionManager getTM() { return tm; } @@ -150,25 +146,20 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * @param spec The activation spec * @throws ResourceException Thrown if an error occurs */ - public void endpointActivation(final MessageEndpointFactory endpointFactory, final ActivationSpec spec) throws ResourceException - { - if (spec == null) - { + public void endpointActivation(final MessageEndpointFactory endpointFactory, + final ActivationSpec spec) throws ResourceException { + if (spec == null) { throw ActiveMQRABundle.BUNDLE.noActivationSpec(); } - if (!configured.getAndSet(true)) - { - try - { + if (!configured.getAndSet(true)) { + try { setup(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw new ResourceException("Unable to create activation", e); } } - if (ActiveMQResourceAdapter.trace) - { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("endpointActivation(" + endpointFactory + ", " + spec + ")"); } @@ -183,16 +174,13 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * @param endpointFactory The endpoint factory * @param spec The activation spec */ - public void endpointDeactivation(final MessageEndpointFactory endpointFactory, final ActivationSpec spec) - { - if (ActiveMQResourceAdapter.trace) - { + public void endpointDeactivation(final MessageEndpointFactory endpointFactory, final ActivationSpec spec) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("endpointDeactivation(" + endpointFactory + ", " + spec + ")"); } ActiveMQActivation activation = activations.remove(spec); - if (activation != null) - { + if (activation != null) { activation.stop(); } } @@ -204,26 +192,20 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * @return The XA resources * @throws ResourceException Thrown if an error occurs or unsupported */ - public XAResource[] getXAResources(final ActivationSpec[] specs) throws ResourceException - { - if (ActiveMQResourceAdapter.trace) - { + public XAResource[] getXAResources(final ActivationSpec[] specs) throws ResourceException { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getXAResources(" + Arrays.toString(specs) + ")"); } - if (useAutoRecovery) - { + if (useAutoRecovery) { // let the TM handle the recovery return null; } - else - { + else { List xaresources = new ArrayList(); - for (ActivationSpec spec : specs) - { + for (ActivationSpec spec : specs) { ActiveMQActivation activation = activations.get(spec); - if (activation != null) - { + if (activation != null) { xaresources.addAll(activation.getXAResources()); } } @@ -237,10 +219,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * @param ctx The bootstrap context * @throws ResourceAdapterInternalException Thrown if an error occurs */ - public void start(final BootstrapContext ctx) throws ResourceAdapterInternalException - { - if (ActiveMQResourceAdapter.trace) - { + public void start(final BootstrapContext ctx) throws ResourceAdapterInternalException { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("start(" + ctx + ")"); } @@ -250,14 +230,11 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable this.ctx = ctx; - if (!configured.getAndSet(true)) - { - try - { + if (!configured.getAndSet(true)) { + try { setup(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw new ResourceAdapterInternalException("Unable to create activation", e); } } @@ -268,41 +245,33 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable /** * Stop */ - public void stop() - { - if (ActiveMQResourceAdapter.trace) - { + public void stop() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("stop()"); } - for (Map.Entry entry : activations.entrySet()) - { - try - { + for (Map.Entry entry : activations.entrySet()) { + try { entry.getValue().stop(); } - catch (Exception ignored) - { + catch (Exception ignored) { ActiveMQRALogger.LOGGER.debug("Ignored", ignored); } } activations.clear(); - for (ActiveMQRAManagedConnectionFactory managedConnectionFactory : managedConnectionFactories) - { + for (ActiveMQRAManagedConnectionFactory managedConnectionFactory : managedConnectionFactories) { managedConnectionFactory.stop(); } managedConnectionFactories.clear(); - if (defaultActiveMQConnectionFactory != null) - { + if (defaultActiveMQConnectionFactory != null) { defaultActiveMQConnectionFactory.close(); } - if (recoveryActiveMQConnectionFactory != null) - { + if (recoveryActiveMQConnectionFactory != null) { recoveryActiveMQConnectionFactory.close(); } @@ -311,40 +280,32 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable ActiveMQRALogger.LOGGER.raStopped(); } - public void setUseAutoRecovery(Boolean useAutoRecovery) - { + public void setUseAutoRecovery(Boolean useAutoRecovery) { this.useAutoRecovery = useAutoRecovery; } - public Boolean isUseAutoRecovery() - { + public Boolean isUseAutoRecovery() { return this.useAutoRecovery; } - public Boolean isUseMaskedPassword() - { + public Boolean isUseMaskedPassword() { return this.raProperties.isUseMaskedPassword(); } - public void setUseMaskedPassword(Boolean useMaskedPassword) - { + public void setUseMaskedPassword(Boolean useMaskedPassword) { this.raProperties.setUseMaskedPassword(useMaskedPassword); } - public void setPasswordCodec(String passwordCodec) - { + public void setPasswordCodec(String passwordCodec) { this.raProperties.setPasswordCodec(passwordCodec); } - public String getPasswordCodec() - { + public String getPasswordCodec() { return this.raProperties.getPasswordCodec(); } - public void setConnectorClassName(final String connectorClassName) - { - if (ActiveMQResourceAdapter.trace) - { + public void setConnectorClassName(final String connectorClassName) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setTransportType(" + connectorClassName + ")"); } unparsedConnectors = connectorClassName; @@ -352,56 +313,44 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable raProperties.setParsedConnectorClassNames(ActiveMQRaUtils.parseConnectorConnectorConfig(connectorClassName)); } - public String getConnectorClassName() - { + public String getConnectorClassName() { return unparsedConnectors; } - public String getConnectionParameters() - { + public String getConnectionParameters() { return unparsedProperties; } - public void setConnectionParameters(final String config) - { - if (config != null) - { + public void setConnectionParameters(final String config) { + if (config != null) { this.unparsedProperties = config; raProperties.setParsedConnectionParameters(ActiveMQRaUtils.parseConfig(config)); } } - - public Boolean getHA() - { + public Boolean getHA() { return raProperties.isHA(); } - public void setHA(final Boolean ha) - { + public void setHA(final Boolean ha) { this.raProperties.setHA(ha); } - public String getEntries() - { + public String getEntries() { return entries; } - public String getJndiName() - { - if (!(entries == null || entries.isEmpty())) - { + public String getJndiName() { + if (!(entries == null || entries.isEmpty())) { Matcher m = Pattern.compile("\"(.*?)\"").matcher(entries); - if (m.find()) - { + if (m.find()) { return m.group(1); } } return null; } - public void setEntries(String entries) - { + public void setEntries(String entries) { this.entries = entries; } @@ -410,33 +359,27 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public String getDiscoveryAddress() - { - if (ActiveMQResourceAdapter.trace) - { + public String getDiscoveryAddress() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getDiscoveryGroupAddress()"); } return raProperties.getDiscoveryAddress(); } - public void setJgroupsFile(String jgroupsFile) - { + public void setJgroupsFile(String jgroupsFile) { raProperties.setJgroupsFile(jgroupsFile); } - public String getJgroupsFile() - { + public String getJgroupsFile() { return raProperties.getJgroupsFile(); } - public String getJgroupsChannelName() - { + public String getJgroupsChannelName() { return raProperties.getJgroupsChannelName(); } - public void setJgroupsChannelName(String jgroupsChannelName) - { + public void setJgroupsChannelName(String jgroupsChannelName) { raProperties.setJgroupsChannelName(jgroupsChannelName); } @@ -445,10 +388,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param dgn The value */ - public void setDiscoveryAddress(final String dgn) - { - if (ActiveMQResourceAdapter.trace) - { + public void setDiscoveryAddress(final String dgn) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setDiscoveryGroupAddress(" + dgn + ")"); } @@ -460,10 +401,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Integer getDiscoveryPort() - { - if (ActiveMQResourceAdapter.trace) - { + public Integer getDiscoveryPort() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getDiscoveryGroupPort()"); } @@ -475,10 +414,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param discoveryLocalBindAddress the address value */ - public void setDiscoveryLocalBindAddress(final String discoveryLocalBindAddress) - { - if (ActiveMQResourceAdapter.trace) - { + public void setDiscoveryLocalBindAddress(final String discoveryLocalBindAddress) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setDiscoveryLocalBindAddress(" + discoveryLocalBindAddress + ")"); } @@ -490,10 +427,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return the address value */ - public String getDiscoveryLocalBindAddress() - { - if (ActiveMQResourceAdapter.trace) - { + public String getDiscoveryLocalBindAddress() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getDiscoveryLocalBindAddress()"); } @@ -505,10 +440,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param dgp The value */ - public void setDiscoveryPort(final Integer dgp) - { - if (ActiveMQResourceAdapter.trace) - { + public void setDiscoveryPort(final Integer dgp) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setDiscoveryGroupPort(" + dgp + ")"); } @@ -520,10 +453,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Long getDiscoveryRefreshTimeout() - { - if (ActiveMQResourceAdapter.trace) - { + public Long getDiscoveryRefreshTimeout() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getDiscoveryRefreshTimeout()"); } @@ -535,10 +466,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param discoveryRefreshTimeout The value */ - public void setDiscoveryRefreshTimeout(final Long discoveryRefreshTimeout) - { - if (ActiveMQResourceAdapter.trace) - { + public void setDiscoveryRefreshTimeout(final Long discoveryRefreshTimeout) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setDiscoveryRefreshTimeout(" + discoveryRefreshTimeout + ")"); } @@ -550,10 +479,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Long getDiscoveryInitialWaitTimeout() - { - if (ActiveMQResourceAdapter.trace) - { + public Long getDiscoveryInitialWaitTimeout() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getDiscoveryInitialWaitTimeout()"); } @@ -565,10 +492,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param discoveryInitialWaitTimeout The value */ - public void setDiscoveryInitialWaitTimeout(final Long discoveryInitialWaitTimeout) - { - if (ActiveMQResourceAdapter.trace) - { + public void setDiscoveryInitialWaitTimeout(final Long discoveryInitialWaitTimeout) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setDiscoveryInitialWaitTimeout(" + discoveryInitialWaitTimeout + ")"); } @@ -580,10 +505,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Long getClientFailureCheckPeriod() - { - if (ActiveMQResourceAdapter.trace) - { + public Long getClientFailureCheckPeriod() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getClientFailureCheckPeriod()"); } @@ -595,10 +518,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param clientFailureCheckPeriod The value */ - public void setClientFailureCheckPeriod(final Long clientFailureCheckPeriod) - { - if (ActiveMQResourceAdapter.trace) - { + public void setClientFailureCheckPeriod(final Long clientFailureCheckPeriod) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setClientFailureCheckPeriod(" + clientFailureCheckPeriod + ")"); } @@ -610,10 +531,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Long getConnectionTTL() - { - if (ActiveMQResourceAdapter.trace) - { + public Long getConnectionTTL() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getConnectionTTL()"); } @@ -625,10 +544,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param connectionTTL The value */ - public void setConnectionTTL(final Long connectionTTL) - { - if (ActiveMQResourceAdapter.trace) - { + public void setConnectionTTL(final Long connectionTTL) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setConnectionTTL(" + connectionTTL + ")"); } @@ -640,10 +557,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Boolean isCacheLargeMessagesClient() - { - if (ActiveMQResourceAdapter.trace) - { + public Boolean isCacheLargeMessagesClient() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("isCacheLargeMessagesClient()"); } @@ -655,10 +570,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param cacheLargeMessagesClient The value */ - public void setCacheLargeMessagesClient(final Boolean cacheLargeMessagesClient) - { - if (ActiveMQResourceAdapter.trace) - { + public void setCacheLargeMessagesClient(final Boolean cacheLargeMessagesClient) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setCacheLargeMessagesClient(" + cacheLargeMessagesClient + ")"); } @@ -670,10 +583,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Boolean isCompressLargeMessage() - { - if (ActiveMQResourceAdapter.trace) - { + public Boolean isCompressLargeMessage() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("isCompressLargeMessage()"); } @@ -685,10 +596,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param failoverOnInitialConnection The value */ - public void setFailoverOnInitialConnection(final Boolean failoverOnInitialConnection) - { - if (ActiveMQResourceAdapter.trace) - { + public void setFailoverOnInitialConnection(final Boolean failoverOnInitialConnection) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setFailoverOnInitialConnection(" + failoverOnInitialConnection + ")"); } @@ -700,10 +609,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Boolean isFailoverOnInitialConnection() - { - if (ActiveMQResourceAdapter.trace) - { + public Boolean isFailoverOnInitialConnection() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("isFailoverOnInitialConnection()"); } @@ -715,10 +622,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param compressLargeMessage The value */ - public void setCompressLargeMessage(final Boolean compressLargeMessage) - { - if (ActiveMQResourceAdapter.trace) - { + public void setCompressLargeMessage(final Boolean compressLargeMessage) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setCompressLargeMessage(" + compressLargeMessage + ")"); } @@ -730,10 +635,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Long getCallTimeout() - { - if (ActiveMQResourceAdapter.trace) - { + public Long getCallTimeout() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getCallTimeout()"); } @@ -745,10 +648,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param callTimeout The value */ - public void setCallTimeout(final Long callTimeout) - { - if (ActiveMQResourceAdapter.trace) - { + public void setCallTimeout(final Long callTimeout) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setCallTimeout(" + callTimeout + ")"); } @@ -760,10 +661,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Long getCallFailoverTimeout() - { - if (ActiveMQResourceAdapter.trace) - { + public Long getCallFailoverTimeout() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getCallFailoverTimeout()"); } @@ -775,10 +674,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param callFailoverTimeout The value */ - public void setCallFailoverTimeout(final Long callFailoverTimeout) - { - if (ActiveMQResourceAdapter.trace) - { + public void setCallFailoverTimeout(final Long callFailoverTimeout) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setCallFailoverTimeout(" + callFailoverTimeout + ")"); } @@ -790,10 +687,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Integer getDupsOKBatchSize() - { - if (ActiveMQResourceAdapter.trace) - { + public Integer getDupsOKBatchSize() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getDupsOKBatchSize()"); } @@ -805,10 +700,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param dupsOKBatchSize The value */ - public void setDupsOKBatchSize(final Integer dupsOKBatchSize) - { - if (ActiveMQResourceAdapter.trace) - { + public void setDupsOKBatchSize(final Integer dupsOKBatchSize) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setDupsOKBatchSize(" + dupsOKBatchSize + ")"); } @@ -820,10 +713,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Integer getTransactionBatchSize() - { - if (ActiveMQResourceAdapter.trace) - { + public Integer getTransactionBatchSize() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getTransactionBatchSize()"); } @@ -835,10 +726,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param transactionBatchSize The value */ - public void setTransactionBatchSize(final Integer transactionBatchSize) - { - if (ActiveMQResourceAdapter.trace) - { + public void setTransactionBatchSize(final Integer transactionBatchSize) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setTransactionBatchSize(" + transactionBatchSize + ")"); } @@ -850,10 +739,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Integer getConsumerWindowSize() - { - if (ActiveMQResourceAdapter.trace) - { + public Integer getConsumerWindowSize() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getConsumerWindowSize()"); } @@ -865,10 +752,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param consumerWindowSize The value */ - public void setConsumerWindowSize(final Integer consumerWindowSize) - { - if (ActiveMQResourceAdapter.trace) - { + public void setConsumerWindowSize(final Integer consumerWindowSize) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setConsumerWindowSize(" + consumerWindowSize + ")"); } @@ -880,10 +765,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Integer getConsumerMaxRate() - { - if (ActiveMQResourceAdapter.trace) - { + public Integer getConsumerMaxRate() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getConsumerMaxRate()"); } @@ -895,10 +778,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param consumerMaxRate The value */ - public void setConsumerMaxRate(final Integer consumerMaxRate) - { - if (ActiveMQResourceAdapter.trace) - { + public void setConsumerMaxRate(final Integer consumerMaxRate) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setConsumerMaxRate(" + consumerMaxRate + ")"); } @@ -910,10 +791,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Integer getConfirmationWindowSize() - { - if (ActiveMQResourceAdapter.trace) - { + public Integer getConfirmationWindowSize() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getConfirmationWindowSize()"); } @@ -925,10 +804,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param confirmationWindowSize The value */ - public void setConfirmationWindowSize(final Integer confirmationWindowSize) - { - if (ActiveMQResourceAdapter.trace) - { + public void setConfirmationWindowSize(final Integer confirmationWindowSize) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setConfirmationWindowSize(" + confirmationWindowSize + ")"); } @@ -940,10 +817,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Integer getProducerMaxRate() - { - if (ActiveMQResourceAdapter.trace) - { + public Integer getProducerMaxRate() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getProducerMaxRate()"); } @@ -955,10 +830,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param producerMaxRate The value */ - public void setProducerMaxRate(final Integer producerMaxRate) - { - if (ActiveMQResourceAdapter.trace) - { + public void setProducerMaxRate(final Integer producerMaxRate) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setProducerMaxRate(" + producerMaxRate + ")"); } @@ -970,10 +843,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Integer getProducerWindowSize() - { - if (ActiveMQResourceAdapter.trace) - { + public Integer getProducerWindowSize() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getProducerWindowSize()"); } @@ -985,10 +856,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param producerWindowSize The value */ - public void setProducerWindowSize(final Integer producerWindowSize) - { - if (ActiveMQResourceAdapter.trace) - { + public void setProducerWindowSize(final Integer producerWindowSize) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setProducerWindowSize(" + producerWindowSize + ")"); } @@ -1000,10 +869,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Integer getMinLargeMessageSize() - { - if (ActiveMQResourceAdapter.trace) - { + public Integer getMinLargeMessageSize() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getMinLargeMessageSize()"); } @@ -1015,10 +882,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param minLargeMessageSize The value */ - public void setMinLargeMessageSize(final Integer minLargeMessageSize) - { - if (ActiveMQResourceAdapter.trace) - { + public void setMinLargeMessageSize(final Integer minLargeMessageSize) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setMinLargeMessageSize(" + minLargeMessageSize + ")"); } @@ -1030,10 +895,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Boolean getBlockOnAcknowledge() - { - if (ActiveMQResourceAdapter.trace) - { + public Boolean getBlockOnAcknowledge() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getBlockOnAcknowledge()"); } @@ -1045,10 +908,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param blockOnAcknowledge The value */ - public void setBlockOnAcknowledge(final Boolean blockOnAcknowledge) - { - if (ActiveMQResourceAdapter.trace) - { + public void setBlockOnAcknowledge(final Boolean blockOnAcknowledge) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setBlockOnAcknowledge(" + blockOnAcknowledge + ")"); } @@ -1060,10 +921,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Boolean getBlockOnNonDurableSend() - { - if (ActiveMQResourceAdapter.trace) - { + public Boolean getBlockOnNonDurableSend() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getBlockOnNonDurableSend()"); } @@ -1075,10 +934,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param blockOnNonDurableSend The value */ - public void setBlockOnNonDurableSend(final Boolean blockOnNonDurableSend) - { - if (ActiveMQResourceAdapter.trace) - { + public void setBlockOnNonDurableSend(final Boolean blockOnNonDurableSend) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setBlockOnNonDurableSend(" + blockOnNonDurableSend + ")"); } @@ -1090,10 +947,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Boolean getBlockOnDurableSend() - { - if (ActiveMQResourceAdapter.trace) - { + public Boolean getBlockOnDurableSend() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getBlockOnDurableSend()"); } @@ -1105,10 +960,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param blockOnDurableSend The value */ - public void setBlockOnDurableSend(final Boolean blockOnDurableSend) - { - if (ActiveMQResourceAdapter.trace) - { + public void setBlockOnDurableSend(final Boolean blockOnDurableSend) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setBlockOnDurableSend(" + blockOnDurableSend + ")"); } @@ -1120,10 +973,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Boolean getAutoGroup() - { - if (ActiveMQResourceAdapter.trace) - { + public Boolean getAutoGroup() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getAutoGroup()"); } @@ -1135,10 +986,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param autoGroup The value */ - public void setAutoGroup(final Boolean autoGroup) - { - if (ActiveMQResourceAdapter.trace) - { + public void setAutoGroup(final Boolean autoGroup) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setAutoGroup(" + autoGroup + ")"); } @@ -1150,10 +999,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Boolean getPreAcknowledge() - { - if (ActiveMQResourceAdapter.trace) - { + public Boolean getPreAcknowledge() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getPreAcknowledge()"); } @@ -1165,10 +1012,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param preAcknowledge The value */ - public void setPreAcknowledge(final Boolean preAcknowledge) - { - if (ActiveMQResourceAdapter.trace) - { + public void setPreAcknowledge(final Boolean preAcknowledge) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setPreAcknowledge(" + preAcknowledge + ")"); } @@ -1180,10 +1025,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Integer getInitialConnectAttempts() - { - if (ActiveMQResourceAdapter.trace) - { + public Integer getInitialConnectAttempts() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getInitialConnectAttempts()"); } @@ -1195,10 +1038,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param initialConnectAttempts The value */ - public void setInitialConnectAttempts(final Integer initialConnectAttempts) - { - if (ActiveMQResourceAdapter.trace) - { + public void setInitialConnectAttempts(final Integer initialConnectAttempts) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setInitialConnectionAttempts(" + initialConnectAttempts + ")"); } @@ -1210,10 +1051,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Integer getInitialMessagePacketSize() - { - if (ActiveMQResourceAdapter.trace) - { + public Integer getInitialMessagePacketSize() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getInitialMessagePacketSize()"); } @@ -1225,10 +1064,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param initialMessagePacketSize The value */ - public void setInitialMessagePacketSize(final Integer initialMessagePacketSize) - { - if (ActiveMQResourceAdapter.trace) - { + public void setInitialMessagePacketSize(final Integer initialMessagePacketSize) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setInitialMessagePacketSize(" + initialMessagePacketSize + ")"); } @@ -1240,10 +1077,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Long getRetryInterval() - { - if (ActiveMQResourceAdapter.trace) - { + public Long getRetryInterval() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getRetryInterval()"); } @@ -1255,10 +1090,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param retryInterval The value */ - public void setRetryInterval(final Long retryInterval) - { - if (ActiveMQResourceAdapter.trace) - { + public void setRetryInterval(final Long retryInterval) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setRetryInterval(" + retryInterval + ")"); } @@ -1270,10 +1103,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Double getRetryIntervalMultiplier() - { - if (ActiveMQResourceAdapter.trace) - { + public Double getRetryIntervalMultiplier() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getRetryIntervalMultiplier()"); } @@ -1285,10 +1116,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param retryIntervalMultiplier The value */ - public void setRetryIntervalMultiplier(final Double retryIntervalMultiplier) - { - if (ActiveMQResourceAdapter.trace) - { + public void setRetryIntervalMultiplier(final Double retryIntervalMultiplier) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setRetryIntervalMultiplier(" + retryIntervalMultiplier + ")"); } @@ -1300,10 +1129,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Long getMaxRetryInterval() - { - if (ActiveMQResourceAdapter.trace) - { + public Long getMaxRetryInterval() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getMaxRetryInterval()"); } @@ -1315,10 +1142,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param maxRetryInterval The value */ - public void setMaxRetryInterval(final Long maxRetryInterval) - { - if (ActiveMQResourceAdapter.trace) - { + public void setMaxRetryInterval(final Long maxRetryInterval) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setMaxRetryInterval(" + maxRetryInterval + ")"); } @@ -1330,10 +1155,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Integer getReconnectAttempts() - { - if (ActiveMQResourceAdapter.trace) - { + public Integer getReconnectAttempts() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getReconnectAttempts()"); } @@ -1345,67 +1168,53 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param reconnectAttempts The value */ - public void setReconnectAttempts(final Integer reconnectAttempts) - { - if (ActiveMQResourceAdapter.trace) - { + public void setReconnectAttempts(final Integer reconnectAttempts) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setReconnectAttempts(" + reconnectAttempts + ")"); } raProperties.setReconnectAttempts(reconnectAttempts); } - public String getConnectionLoadBalancingPolicyClassName() - { + public String getConnectionLoadBalancingPolicyClassName() { return raProperties.getConnectionLoadBalancingPolicyClassName(); } - public void setConnectionLoadBalancingPolicyClassName(final String connectionLoadBalancingPolicyClassName) - { - if (ActiveMQResourceAdapter.trace) - { + public void setConnectionLoadBalancingPolicyClassName(final String connectionLoadBalancingPolicyClassName) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setFailoverOnServerShutdown(" + connectionLoadBalancingPolicyClassName + ")"); } raProperties.setConnectionLoadBalancingPolicyClassName(connectionLoadBalancingPolicyClassName); } - public Integer getScheduledThreadPoolMaxSize() - { + public Integer getScheduledThreadPoolMaxSize() { return raProperties.getScheduledThreadPoolMaxSize(); } - public void setScheduledThreadPoolMaxSize(final Integer scheduledThreadPoolMaxSize) - { - if (ActiveMQResourceAdapter.trace) - { + public void setScheduledThreadPoolMaxSize(final Integer scheduledThreadPoolMaxSize) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setFailoverOnServerShutdown(" + scheduledThreadPoolMaxSize + ")"); } raProperties.setScheduledThreadPoolMaxSize(scheduledThreadPoolMaxSize); } - public Integer getThreadPoolMaxSize() - { + public Integer getThreadPoolMaxSize() { return raProperties.getThreadPoolMaxSize(); } - public void setThreadPoolMaxSize(final Integer threadPoolMaxSize) - { - if (ActiveMQResourceAdapter.trace) - { + public void setThreadPoolMaxSize(final Integer threadPoolMaxSize) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setFailoverOnServerShutdown(" + threadPoolMaxSize + ")"); } raProperties.setThreadPoolMaxSize(threadPoolMaxSize); } - public Boolean getUseGlobalPools() - { + public Boolean getUseGlobalPools() { return raProperties.isUseGlobalPools(); } - public void setUseGlobalPools(final Boolean useGlobalPools) - { - if (ActiveMQResourceAdapter.trace) - { + public void setUseGlobalPools(final Boolean useGlobalPools) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setFailoverOnServerShutdown(" + useGlobalPools + ")"); } raProperties.setUseGlobalPools(useGlobalPools); @@ -1416,10 +1225,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public String getUserName() - { - if (ActiveMQResourceAdapter.trace) - { + public String getUserName() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getUserName()"); } @@ -1431,10 +1238,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param userName The value */ - public void setUserName(final String userName) - { - if (ActiveMQResourceAdapter.trace) - { + public void setUserName(final String userName) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setUserName(" + userName + ")"); } @@ -1446,10 +1251,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public String getPassword() - { - if (ActiveMQResourceAdapter.trace) - { + public String getPassword() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getPassword()"); } @@ -1461,10 +1264,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param password The value */ - public void setPassword(final String password) - { - if (ActiveMQResourceAdapter.trace) - { + public void setPassword(final String password) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setPassword(****)"); } @@ -1474,35 +1275,30 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable /** * @return the useJNDI */ - public boolean isUseJNDI() - { + public boolean isUseJNDI() { return raProperties.isUseJNDI(); } /** * @param value the useJNDI to set */ - public void setUseJNDI(final Boolean value) - { + public void setUseJNDI(final Boolean value) { raProperties.setUseJNDI(value); } /** * @return return the jndi params to use */ - public String getJndiParams() - { + public String getJndiParams() { return unparsedJndiParams; } - public void setJndiParams(String jndiParams) - { + public void setJndiParams(String jndiParams) { unparsedJndiParams = jndiParams; raProperties.setParsedJndiParams(ActiveMQRaUtils.parseHashtableConfig(jndiParams)); } - public Hashtable getParsedJndiParams() - { + public Hashtable getParsedJndiParams() { return raProperties.getParsedJndiParams(); } @@ -1511,10 +1307,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public String getClientID() - { - if (ActiveMQResourceAdapter.trace) - { + public String getClientID() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getClientID()"); } @@ -1526,10 +1320,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param clientID The client id */ - public void setClientID(final String clientID) - { - if (ActiveMQResourceAdapter.trace) - { + public void setClientID(final String clientID) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setClientID(" + clientID + ")"); } @@ -1541,10 +1333,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public String getGroupID() - { - if (ActiveMQResourceAdapter.trace) - { + public String getGroupID() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getGroupID()"); } @@ -1556,10 +1346,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param groupID The group id */ - public void setGroupID(final String groupID) - { - if (ActiveMQResourceAdapter.trace) - { + public void setGroupID(final String groupID) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setGroupID(" + groupID + ")"); } @@ -1571,10 +1359,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The value */ - public Boolean getUseLocalTx() - { - if (ActiveMQResourceAdapter.trace) - { + public Boolean getUseLocalTx() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getUseLocalTx()"); } @@ -1586,47 +1372,37 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @param localTx The value */ - public void setUseLocalTx(final Boolean localTx) - { - if (ActiveMQResourceAdapter.trace) - { + public void setUseLocalTx(final Boolean localTx) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setUseXA(" + localTx + ")"); } raProperties.setUseLocalTx(localTx); } - public int getSetupAttempts() - { - if (ActiveMQResourceAdapter.trace) - { + public int getSetupAttempts() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getSetupAttempts()"); } return raProperties.getSetupAttempts(); } - public void setSetupAttempts(Integer setupAttempts) - { - if (ActiveMQResourceAdapter.trace) - { + public void setSetupAttempts(Integer setupAttempts) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setSetupAttempts(" + setupAttempts + ")"); } raProperties.setSetupAttempts(setupAttempts); } - public long getSetupInterval() - { - if (ActiveMQResourceAdapter.trace) - { + public long getSetupInterval() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getSetupInterval()"); } return raProperties.getSetupInterval(); } - public void setSetupInterval(Long interval) - { - if (ActiveMQResourceAdapter.trace) - { + public void setSetupInterval(Long interval) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("setSetupInterval(" + interval + ")"); } raProperties.setSetupInterval(interval); @@ -1639,20 +1415,16 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * @return True if this object is the same as the obj argument; false otherwise. */ @Override - public boolean equals(final Object obj) - { - if (ActiveMQResourceAdapter.trace) - { + public boolean equals(final Object obj) { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("equals(" + obj + ")"); } - if (obj == null) - { + if (obj == null) { return false; } - if (obj instanceof ActiveMQResourceAdapter) - { + if (obj instanceof ActiveMQResourceAdapter) { return raProperties.equals(((ActiveMQResourceAdapter) obj).getProperties()); } return false; @@ -1664,10 +1436,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * @return The hash code */ @Override - public int hashCode() - { - if (ActiveMQResourceAdapter.trace) - { + public int hashCode() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("hashCode()"); } @@ -1679,15 +1449,12 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The manager */ - public WorkManager getWorkManager() - { - if (ActiveMQResourceAdapter.trace) - { + public WorkManager getWorkManager() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getWorkManager()"); } - if (ctx == null) - { + if (ctx == null) { return null; } @@ -1703,43 +1470,34 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable final Integer transactionBatchSize, final boolean deliveryTransacted, final boolean useLocalTx, - final Integer txTimeout) throws Exception - { + final Integer txTimeout) throws Exception { ClientSession result; // if we are CMP or BMP using local tx we ignore the ack mode as we are transactional - if (deliveryTransacted || useLocalTx) - { + if (deliveryTransacted || useLocalTx) { // JBPAPP-8845 // If transacted we need to send the ack flush as soon as possible // as if any transaction times out, we need the ack on the server already - if (useLocalTx) - { + if (useLocalTx) { result = parameterFactory.createSession(user, pass, false, false, false, false, 0); } - else - { + else { result = parameterFactory.createSession(user, pass, true, false, false, false, 0); } } - else - { - if (preAck != null && preAck) - { + else { + if (preAck != null && preAck) { result = parameterFactory.createSession(user, pass, false, true, true, true, -1); } - else - { + else { // only auto ack and dups ok are supported - switch (ackMode) - { + switch (ackMode) { case Session.AUTO_ACKNOWLEDGE: result = parameterFactory.createSession(user, pass, false, true, true, false, 0); break; case Session.DUPS_OK_ACKNOWLEDGE: - int actDupsOkBatchSize = dupsOkBatchSize != null ? dupsOkBatchSize - : ActiveMQClient.DEFAULT_ACK_BATCH_SIZE; + int actDupsOkBatchSize = dupsOkBatchSize != null ? dupsOkBatchSize : ActiveMQClient.DEFAULT_ACK_BATCH_SIZE; result = parameterFactory.createSession(user, pass, false, true, true, false, actDupsOkBatchSize); break; default: @@ -1754,9 +1512,7 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable } - - public RecoveryManager getRecoveryManager() - { + public RecoveryManager getRecoveryManager() { return recoveryManager; } @@ -1765,10 +1521,8 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * * @return The properties */ - protected ActiveMQRAProperties getProperties() - { - if (ActiveMQResourceAdapter.trace) - { + protected ActiveMQRAProperties getProperties() { + if (ActiveMQResourceAdapter.trace) { ActiveMQRALogger.LOGGER.trace("getProperties()"); } @@ -1778,29 +1532,23 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable /** * Setup the factory */ - protected void setup() throws ActiveMQException - { + protected void setup() throws ActiveMQException { raProperties.init(); defaultActiveMQConnectionFactory = createActiveMQConnectionFactory(raProperties); recoveryActiveMQConnectionFactory = createRecoveryActiveMQConnectionFactory(raProperties); recoveryManager.register(recoveryActiveMQConnectionFactory, raProperties.getUserName(), raProperties.getPassword()); } - public Map getActivations() - { + public Map getActivations() { return activations; } - public ActiveMQConnectionFactory getDefaultActiveMQConnectionFactory() throws ResourceException - { - if (!configured.getAndSet(true)) - { - try - { + public ActiveMQConnectionFactory getDefaultActiveMQConnectionFactory() throws ResourceException { + if (!configured.getAndSet(true)) { + try { setup(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw new ResourceException("Unable to create activation", e); } } @@ -1810,16 +1558,14 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable /** * @see ActiveMQRAProperties#getJgroupsChannelLocatorClass() */ - public String getJgroupsChannelLocatorClass() - { + public String getJgroupsChannelLocatorClass() { return raProperties.getJgroupsChannelLocatorClass(); } /** * @see ActiveMQRAProperties#setJgroupsChannelLocatorClass(String) */ - public void setJgroupsChannelLocatorClass(String jgroupsChannelLocatorClass) - { + public void setJgroupsChannelLocatorClass(String jgroupsChannelLocatorClass) { raProperties.setJgroupsChannelLocatorClass(jgroupsChannelLocatorClass); } @@ -1827,158 +1573,116 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable * @return * @see ActiveMQRAProperties#getJgroupsChannelRefName() */ - public String getJgroupsChannelRefName() - { + public String getJgroupsChannelRefName() { return raProperties.getJgroupsChannelRefName(); } /** * @see ActiveMQRAProperties#setJgroupsChannelRefName(java.lang.String) */ - public void setJgroupsChannelRefName(String jgroupsChannelRefName) - { + public void setJgroupsChannelRefName(String jgroupsChannelRefName) { raProperties.setJgroupsChannelRefName(jgroupsChannelRefName); } - public ActiveMQConnectionFactory createActiveMQConnectionFactory(final ConnectionFactoryProperties overrideProperties) - { + public ActiveMQConnectionFactory createActiveMQConnectionFactory(final ConnectionFactoryProperties overrideProperties) { ActiveMQConnectionFactory cf; - List connectorClassName = overrideProperties.getParsedConnectorClassNames() != null ? overrideProperties.getParsedConnectorClassNames() - : raProperties.getParsedConnectorClassNames(); + List connectorClassName = overrideProperties.getParsedConnectorClassNames() != null ? overrideProperties.getParsedConnectorClassNames() : raProperties.getParsedConnectorClassNames(); - String discoveryAddress = overrideProperties.getDiscoveryAddress() != null ? overrideProperties.getDiscoveryAddress() - : getDiscoveryAddress(); + String discoveryAddress = overrideProperties.getDiscoveryAddress() != null ? overrideProperties.getDiscoveryAddress() : getDiscoveryAddress(); Boolean ha = overrideProperties.isHA() != null ? overrideProperties.isHA() : getHA(); - String jgroupsFileName = overrideProperties.getJgroupsFile() != null ? overrideProperties.getJgroupsFile() - : getJgroupsFile(); + String jgroupsFileName = overrideProperties.getJgroupsFile() != null ? overrideProperties.getJgroupsFile() : getJgroupsFile(); - String jgroupsChannel = overrideProperties.getJgroupsChannelName() != null ? overrideProperties.getJgroupsChannelName() - : getJgroupsChannelName(); + String jgroupsChannel = overrideProperties.getJgroupsChannelName() != null ? overrideProperties.getJgroupsChannelName() : getJgroupsChannelName(); String jgroupsLocatorClassName = raProperties.getJgroupsChannelLocatorClass(); - if (ha == null) - { + if (ha == null) { ha = ActiveMQClient.DEFAULT_IS_HA; } - if (discoveryAddress != null || jgroupsFileName != null || jgroupsLocatorClassName != null) - { + if (discoveryAddress != null || jgroupsFileName != null || jgroupsLocatorClassName != null) { BroadcastEndpointFactory endpointFactory = null; - if (jgroupsLocatorClassName != null) - { + if (jgroupsLocatorClassName != null) { String jchannelRefName = raProperties.getJgroupsChannelRefName(); JChannel jchannel = ActiveMQRaUtils.locateJGroupsChannel(jgroupsLocatorClassName, jchannelRefName); endpointFactory = new ChannelBroadcastEndpointFactory(jchannel, jgroupsChannel); } - else if (discoveryAddress != null) - { - Integer discoveryPort = overrideProperties.getDiscoveryPort() != null ? overrideProperties.getDiscoveryPort() - : getDiscoveryPort(); - if (discoveryPort == null) - { + else if (discoveryAddress != null) { + Integer discoveryPort = overrideProperties.getDiscoveryPort() != null ? overrideProperties.getDiscoveryPort() : getDiscoveryPort(); + if (discoveryPort == null) { discoveryPort = ActiveMQClient.DEFAULT_DISCOVERY_PORT; } - String localBindAddress = overrideProperties.getDiscoveryLocalBindAddress() != null ? overrideProperties.getDiscoveryLocalBindAddress() - : raProperties.getDiscoveryLocalBindAddress(); - endpointFactory = new UDPBroadcastEndpointFactory() - .setGroupAddress(discoveryAddress) - .setGroupPort(discoveryPort) - .setLocalBindAddress(localBindAddress) - .setLocalBindPort(-1); + String localBindAddress = overrideProperties.getDiscoveryLocalBindAddress() != null ? overrideProperties.getDiscoveryLocalBindAddress() : raProperties.getDiscoveryLocalBindAddress(); + endpointFactory = new UDPBroadcastEndpointFactory().setGroupAddress(discoveryAddress).setGroupPort(discoveryPort).setLocalBindAddress(localBindAddress).setLocalBindPort(-1); } - else if (jgroupsFileName != null) - { - endpointFactory = new JGroupsFileBroadcastEndpointFactory() - .setChannelName(jgroupsChannel) - .setFile(jgroupsFileName); + else if (jgroupsFileName != null) { + endpointFactory = new JGroupsFileBroadcastEndpointFactory().setChannelName(jgroupsChannel).setFile(jgroupsFileName); } - Long refreshTimeout = overrideProperties.getDiscoveryRefreshTimeout() != null ? overrideProperties.getDiscoveryRefreshTimeout() - : raProperties.getDiscoveryRefreshTimeout(); - if (refreshTimeout == null) - { + Long refreshTimeout = overrideProperties.getDiscoveryRefreshTimeout() != null ? overrideProperties.getDiscoveryRefreshTimeout() : raProperties.getDiscoveryRefreshTimeout(); + if (refreshTimeout == null) { refreshTimeout = ActiveMQClient.DEFAULT_DISCOVERY_REFRESH_TIMEOUT; } - Long initialTimeout = overrideProperties.getDiscoveryInitialWaitTimeout() != null ? overrideProperties.getDiscoveryInitialWaitTimeout() - : raProperties.getDiscoveryInitialWaitTimeout(); + Long initialTimeout = overrideProperties.getDiscoveryInitialWaitTimeout() != null ? overrideProperties.getDiscoveryInitialWaitTimeout() : raProperties.getDiscoveryInitialWaitTimeout(); - if (initialTimeout == null) - { + if (initialTimeout == null) { initialTimeout = ActiveMQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT; } - DiscoveryGroupConfiguration groupConfiguration = new DiscoveryGroupConfiguration() - .setRefreshTimeout(refreshTimeout) - .setDiscoveryInitialWaitTimeout(initialTimeout) - .setBroadcastEndpointFactory(endpointFactory); + DiscoveryGroupConfiguration groupConfiguration = new DiscoveryGroupConfiguration().setRefreshTimeout(refreshTimeout).setDiscoveryInitialWaitTimeout(initialTimeout).setBroadcastEndpointFactory(endpointFactory); - if (ActiveMQRALogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQRALogger.LOGGER.isDebugEnabled()) { ActiveMQRALogger.LOGGER.debug("Creating Connection Factory on the resource adapter for discovery=" + groupConfiguration + " with ha=" + ha); } - if (ha) - { + if (ha) { cf = ActiveMQJMSClient.createConnectionFactoryWithHA(groupConfiguration, JMSFactoryType.XA_CF); } - else - { + else { cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(groupConfiguration, JMSFactoryType.XA_CF); } } - else if (connectorClassName != null) - { + else if (connectorClassName != null) { TransportConfiguration[] transportConfigurations = new TransportConfiguration[connectorClassName.size()]; List> connectionParams; - if (overrideProperties.getParsedConnectorClassNames() != null) - { + if (overrideProperties.getParsedConnectorClassNames() != null) { connectionParams = overrideProperties.getParsedConnectionParameters(); } - else - { + else { connectionParams = raProperties.getParsedConnectionParameters(); } - for (int i = 0; i < connectorClassName.size(); i++) - { + for (int i = 0; i < connectorClassName.size(); i++) { TransportConfiguration tc; - if (connectionParams == null || i >= connectionParams.size()) - { + if (connectionParams == null || i >= connectionParams.size()) { tc = new TransportConfiguration(connectorClassName.get(i)); ActiveMQRALogger.LOGGER.debug("No connector params provided using default"); } - else - { + else { tc = new TransportConfiguration(connectorClassName.get(i), connectionParams.get(i)); } transportConfigurations[i] = tc; } - - if (ActiveMQRALogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQRALogger.LOGGER.isDebugEnabled()) { ActiveMQRALogger.LOGGER.debug("Creating Connection Factory on the resource adapter for transport=" + - Arrays.toString(transportConfigurations) + " with ha=" + ha); + Arrays.toString(transportConfigurations) + " with ha=" + ha); } - if (ha) - { + if (ha) { cf = ActiveMQJMSClient.createConnectionFactoryWithHA(JMSFactoryType.XA_CF, transportConfigurations); } - else - { + else { cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.XA_CF, transportConfigurations); } } - else - { + else { throw new IllegalArgumentException("must provide either TransportType or DiscoveryGroupAddress and DiscoveryGroupPort for ResourceAdapter Connection Factory"); } @@ -1986,124 +1690,87 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable return cf; } - public ActiveMQConnectionFactory createRecoveryActiveMQConnectionFactory(final ConnectionFactoryProperties overrideProperties) - { + public ActiveMQConnectionFactory createRecoveryActiveMQConnectionFactory(final ConnectionFactoryProperties overrideProperties) { ActiveMQConnectionFactory cf; - List connectorClassName = overrideProperties.getParsedConnectorClassNames() != null ? overrideProperties.getParsedConnectorClassNames() - : raProperties.getParsedConnectorClassNames(); + List connectorClassName = overrideProperties.getParsedConnectorClassNames() != null ? overrideProperties.getParsedConnectorClassNames() : raProperties.getParsedConnectorClassNames(); - String discoveryAddress = overrideProperties.getDiscoveryAddress() != null ? overrideProperties.getDiscoveryAddress() - : getDiscoveryAddress(); + String discoveryAddress = overrideProperties.getDiscoveryAddress() != null ? overrideProperties.getDiscoveryAddress() : getDiscoveryAddress(); - String jgroupsFileName = overrideProperties.getJgroupsFile() != null ? overrideProperties.getJgroupsFile() - : getJgroupsFile(); + String jgroupsFileName = overrideProperties.getJgroupsFile() != null ? overrideProperties.getJgroupsFile() : getJgroupsFile(); - String jgroupsChannel = overrideProperties.getJgroupsChannelName() != null ? overrideProperties.getJgroupsChannelName() - : getJgroupsChannelName(); + String jgroupsChannel = overrideProperties.getJgroupsChannelName() != null ? overrideProperties.getJgroupsChannelName() : getJgroupsChannelName(); - if (connectorClassName == null) - { + if (connectorClassName == null) { BroadcastEndpointFactory endpointFactory = null; - if (discoveryAddress != null) - { - Integer discoveryPort = overrideProperties.getDiscoveryPort() != null ? overrideProperties.getDiscoveryPort() - : getDiscoveryPort(); - if (discoveryPort == null) - { + if (discoveryAddress != null) { + Integer discoveryPort = overrideProperties.getDiscoveryPort() != null ? overrideProperties.getDiscoveryPort() : getDiscoveryPort(); + if (discoveryPort == null) { discoveryPort = ActiveMQClient.DEFAULT_DISCOVERY_PORT; } - String localBindAddress = overrideProperties.getDiscoveryLocalBindAddress() != null ? overrideProperties.getDiscoveryLocalBindAddress() - : raProperties.getDiscoveryLocalBindAddress(); - endpointFactory = new UDPBroadcastEndpointFactory() - .setGroupAddress(discoveryAddress) - .setGroupPort(discoveryPort) - .setLocalBindAddress(localBindAddress) - .setLocalBindPort(-1); + String localBindAddress = overrideProperties.getDiscoveryLocalBindAddress() != null ? overrideProperties.getDiscoveryLocalBindAddress() : raProperties.getDiscoveryLocalBindAddress(); + endpointFactory = new UDPBroadcastEndpointFactory().setGroupAddress(discoveryAddress).setGroupPort(discoveryPort).setLocalBindAddress(localBindAddress).setLocalBindPort(-1); } - else if (jgroupsFileName != null) - { - endpointFactory = new JGroupsFileBroadcastEndpointFactory() - .setChannelName(jgroupsChannel) - .setFile(jgroupsFileName); + else if (jgroupsFileName != null) { + endpointFactory = new JGroupsFileBroadcastEndpointFactory().setChannelName(jgroupsChannel).setFile(jgroupsFileName); } - else - { + else { String jgroupsLocatorClass = raProperties.getJgroupsChannelLocatorClass(); - if (jgroupsLocatorClass != null) - { + if (jgroupsLocatorClass != null) { String jgroupsChannelRefName = raProperties.getJgroupsChannelRefName(); JChannel jchannel = ActiveMQRaUtils.locateJGroupsChannel(jgroupsLocatorClass, jgroupsChannelRefName); endpointFactory = new ChannelBroadcastEndpointFactory(jchannel, jgroupsChannel); } - if (endpointFactory == null) - { + if (endpointFactory == null) { throw new IllegalArgumentException("must provide either TransportType or DiscoveryGroupAddress and DiscoveryGroupPort for ResourceAdapter Connection Factory"); } } - Long refreshTimeout = overrideProperties.getDiscoveryRefreshTimeout() != null ? overrideProperties.getDiscoveryRefreshTimeout() - : raProperties.getDiscoveryRefreshTimeout(); - if (refreshTimeout == null) - { + Long refreshTimeout = overrideProperties.getDiscoveryRefreshTimeout() != null ? overrideProperties.getDiscoveryRefreshTimeout() : raProperties.getDiscoveryRefreshTimeout(); + if (refreshTimeout == null) { refreshTimeout = ActiveMQClient.DEFAULT_DISCOVERY_REFRESH_TIMEOUT; } - Long initialTimeout = overrideProperties.getDiscoveryInitialWaitTimeout() != null ? overrideProperties.getDiscoveryInitialWaitTimeout() - : raProperties.getDiscoveryInitialWaitTimeout(); - if (initialTimeout == null) - { + Long initialTimeout = overrideProperties.getDiscoveryInitialWaitTimeout() != null ? overrideProperties.getDiscoveryInitialWaitTimeout() : raProperties.getDiscoveryInitialWaitTimeout(); + if (initialTimeout == null) { initialTimeout = ActiveMQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT; } - DiscoveryGroupConfiguration groupConfiguration = new DiscoveryGroupConfiguration() - .setRefreshTimeout(refreshTimeout) - .setDiscoveryInitialWaitTimeout(initialTimeout) - .setBroadcastEndpointFactory(endpointFactory); + DiscoveryGroupConfiguration groupConfiguration = new DiscoveryGroupConfiguration().setRefreshTimeout(refreshTimeout).setDiscoveryInitialWaitTimeout(initialTimeout).setBroadcastEndpointFactory(endpointFactory); groupConfiguration.setRefreshTimeout(refreshTimeout); - if (ActiveMQRALogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQRALogger.LOGGER.isDebugEnabled()) { ActiveMQRALogger.LOGGER.debug("Creating Recovery Connection Factory on the resource adapter for discovery=" + groupConfiguration); } cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(groupConfiguration, JMSFactoryType.XA_CF); } - else - { + else { TransportConfiguration[] transportConfigurations = new TransportConfiguration[connectorClassName.size()]; List> connectionParams; - if (overrideProperties.getParsedConnectorClassNames() != null) - { + if (overrideProperties.getParsedConnectorClassNames() != null) { connectionParams = overrideProperties.getParsedConnectionParameters(); } - else - { + else { connectionParams = raProperties.getParsedConnectionParameters(); } - for (int i = 0; i < connectorClassName.size(); i++) - { + for (int i = 0; i < connectorClassName.size(); i++) { TransportConfiguration tc; - if (connectionParams == null || i >= connectionParams.size()) - { + if (connectionParams == null || i >= connectionParams.size()) { tc = new TransportConfiguration(connectorClassName.get(i)); ActiveMQRALogger.LOGGER.debug("No connector params provided using default"); } - else - { + else { tc = new TransportConfiguration(connectorClassName.get(i), connectionParams.get(i)); } transportConfigurations[i] = tc; } - - if (ActiveMQRALogger.LOGGER.isDebugEnabled()) - { - ActiveMQRALogger.LOGGER.debug("Creating Recovery Connection Factory on the resource adapter for transport=" + - Arrays.toString(transportConfigurations)); + if (ActiveMQRALogger.LOGGER.isDebugEnabled()) { + ActiveMQRALogger.LOGGER.debug("Creating Recovery Connection Factory on the resource adapter for transport=" + Arrays.toString(transportConfigurations)); } cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.XA_CF, transportConfigurations); @@ -2118,235 +1785,164 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable } public Map overrideConnectionParameters(final Map connectionParams, - final Map overrideConnectionParams) - { + final Map overrideConnectionParams) { Map map = new HashMap(); - if (connectionParams != null) - { + if (connectionParams != null) { map.putAll(connectionParams); } - if (overrideConnectionParams != null) - { - for (Map.Entry stringObjectEntry : overrideConnectionParams.entrySet()) - { + if (overrideConnectionParams != null) { + for (Map.Entry stringObjectEntry : overrideConnectionParams.entrySet()) { map.put(stringObjectEntry.getKey(), stringObjectEntry.getValue()); } } return map; } - private void setParams(final ActiveMQConnectionFactory cf, - final ConnectionFactoryProperties overrideProperties) - { - Boolean val = overrideProperties.isAutoGroup() != null ? overrideProperties.isAutoGroup() - : raProperties.isAutoGroup(); - if (val != null) - { + private void setParams(final ActiveMQConnectionFactory cf, final ConnectionFactoryProperties overrideProperties) { + Boolean val = overrideProperties.isAutoGroup() != null ? overrideProperties.isAutoGroup() : raProperties.isAutoGroup(); + if (val != null) { cf.setAutoGroup(val); } - val = overrideProperties.isBlockOnAcknowledge() != null ? overrideProperties.isBlockOnAcknowledge() - : raProperties.isBlockOnAcknowledge(); - if (val != null) - { + val = overrideProperties.isBlockOnAcknowledge() != null ? overrideProperties.isBlockOnAcknowledge() : raProperties.isBlockOnAcknowledge(); + if (val != null) { cf.setBlockOnAcknowledge(val); } - val = overrideProperties.isBlockOnNonDurableSend() != null ? overrideProperties.isBlockOnNonDurableSend() - : raProperties.isBlockOnNonDurableSend(); - if (val != null) - { + val = overrideProperties.isBlockOnNonDurableSend() != null ? overrideProperties.isBlockOnNonDurableSend() : raProperties.isBlockOnNonDurableSend(); + if (val != null) { cf.setBlockOnNonDurableSend(val); } - val = overrideProperties.isBlockOnDurableSend() != null ? overrideProperties.isBlockOnDurableSend() - : raProperties.isBlockOnDurableSend(); - if (val != null) - { + val = overrideProperties.isBlockOnDurableSend() != null ? overrideProperties.isBlockOnDurableSend() : raProperties.isBlockOnDurableSend(); + if (val != null) { cf.setBlockOnDurableSend(val); } - val = overrideProperties.isPreAcknowledge() != null ? overrideProperties.isPreAcknowledge() - : raProperties.isPreAcknowledge(); - if (val != null) - { + val = overrideProperties.isPreAcknowledge() != null ? overrideProperties.isPreAcknowledge() : raProperties.isPreAcknowledge(); + if (val != null) { cf.setPreAcknowledge(val); } - val = overrideProperties.isUseGlobalPools() != null ? overrideProperties.isUseGlobalPools() - : raProperties.isUseGlobalPools(); - if (val != null) - { + val = overrideProperties.isUseGlobalPools() != null ? overrideProperties.isUseGlobalPools() : raProperties.isUseGlobalPools(); + if (val != null) { cf.setUseGlobalPools(val); } - val = overrideProperties.isCacheLargeMessagesClient() != null ? overrideProperties.isCacheLargeMessagesClient() - : raProperties.isCacheLargeMessagesClient(); - if (val != null) - { + val = overrideProperties.isCacheLargeMessagesClient() != null ? overrideProperties.isCacheLargeMessagesClient() : raProperties.isCacheLargeMessagesClient(); + if (val != null) { cf.setCacheLargeMessagesClient(val); } - val = overrideProperties.isCompressLargeMessage() != null ? overrideProperties.isCompressLargeMessage() - : raProperties.isCompressLargeMessage(); - if (val != null) - { + val = overrideProperties.isCompressLargeMessage() != null ? overrideProperties.isCompressLargeMessage() : raProperties.isCompressLargeMessage(); + if (val != null) { cf.setCompressLargeMessage(val); } - val = overrideProperties.isFailoverOnInitialConnection() != null ? overrideProperties.isFailoverOnInitialConnection() - : raProperties.isFailoverOnInitialConnection(); - if (val != null) - { + val = overrideProperties.isFailoverOnInitialConnection() != null ? overrideProperties.isFailoverOnInitialConnection() : raProperties.isFailoverOnInitialConnection(); + if (val != null) { cf.setFailoverOnInitialConnection(val); } - Integer val2 = overrideProperties.getConsumerMaxRate() != null ? overrideProperties.getConsumerMaxRate() - : raProperties.getConsumerMaxRate(); - if (val2 != null) - { + Integer val2 = overrideProperties.getConsumerMaxRate() != null ? overrideProperties.getConsumerMaxRate() : raProperties.getConsumerMaxRate(); + if (val2 != null) { cf.setConsumerMaxRate(val2); } - val2 = overrideProperties.getConsumerWindowSize() != null ? overrideProperties.getConsumerWindowSize() - : raProperties.getConsumerWindowSize(); - if (val2 != null) - { + val2 = overrideProperties.getConsumerWindowSize() != null ? overrideProperties.getConsumerWindowSize() : raProperties.getConsumerWindowSize(); + if (val2 != null) { cf.setConsumerWindowSize(val2); } - val2 = overrideProperties.getDupsOKBatchSize() != null ? overrideProperties.getDupsOKBatchSize() - : raProperties.getDupsOKBatchSize(); - if (val2 != null) - { + val2 = overrideProperties.getDupsOKBatchSize() != null ? overrideProperties.getDupsOKBatchSize() : raProperties.getDupsOKBatchSize(); + if (val2 != null) { cf.setDupsOKBatchSize(val2); } - val2 = overrideProperties.getMinLargeMessageSize() != null ? overrideProperties.getMinLargeMessageSize() - : raProperties.getMinLargeMessageSize(); - if (val2 != null) - { + val2 = overrideProperties.getMinLargeMessageSize() != null ? overrideProperties.getMinLargeMessageSize() : raProperties.getMinLargeMessageSize(); + if (val2 != null) { cf.setMinLargeMessageSize(val2); } - val2 = overrideProperties.getProducerMaxRate() != null ? overrideProperties.getProducerMaxRate() - : raProperties.getProducerMaxRate(); - if (val2 != null) - { + val2 = overrideProperties.getProducerMaxRate() != null ? overrideProperties.getProducerMaxRate() : raProperties.getProducerMaxRate(); + if (val2 != null) { cf.setProducerMaxRate(val2); } - val2 = overrideProperties.getProducerWindowSize() != null ? overrideProperties.getProducerWindowSize() - : raProperties.getProducerWindowSize(); - if (val2 != null) - { + val2 = overrideProperties.getProducerWindowSize() != null ? overrideProperties.getProducerWindowSize() : raProperties.getProducerWindowSize(); + if (val2 != null) { cf.setProducerWindowSize(val2); } - val2 = overrideProperties.getConfirmationWindowSize() != null ? overrideProperties.getConfirmationWindowSize() - : raProperties.getConfirmationWindowSize(); - if (val2 != null) - { + val2 = overrideProperties.getConfirmationWindowSize() != null ? overrideProperties.getConfirmationWindowSize() : raProperties.getConfirmationWindowSize(); + if (val2 != null) { cf.setConfirmationWindowSize(val2); } - val2 = overrideProperties.getReconnectAttempts() != null ? overrideProperties.getReconnectAttempts() - : raProperties.getReconnectAttempts(); - if (val2 != null) - { + val2 = overrideProperties.getReconnectAttempts() != null ? overrideProperties.getReconnectAttempts() : raProperties.getReconnectAttempts(); + if (val2 != null) { cf.setReconnectAttempts(val2); } - else - { + else { //the global default is 0 but we should always try to reconnect JCA cf.setReconnectAttempts(-1); } - val2 = overrideProperties.getThreadPoolMaxSize() != null ? overrideProperties.getThreadPoolMaxSize() - : raProperties.getThreadPoolMaxSize(); - if (val2 != null) - { + val2 = overrideProperties.getThreadPoolMaxSize() != null ? overrideProperties.getThreadPoolMaxSize() : raProperties.getThreadPoolMaxSize(); + if (val2 != null) { cf.setThreadPoolMaxSize(val2); } - val2 = overrideProperties.getScheduledThreadPoolMaxSize() != null ? overrideProperties.getScheduledThreadPoolMaxSize() - : raProperties.getScheduledThreadPoolMaxSize(); - if (val2 != null) - { + val2 = overrideProperties.getScheduledThreadPoolMaxSize() != null ? overrideProperties.getScheduledThreadPoolMaxSize() : raProperties.getScheduledThreadPoolMaxSize(); + if (val2 != null) { cf.setScheduledThreadPoolMaxSize(val2); } - val2 = overrideProperties.getTransactionBatchSize() != null ? overrideProperties.getTransactionBatchSize() - : raProperties.getTransactionBatchSize(); - if (val2 != null) - { + val2 = overrideProperties.getTransactionBatchSize() != null ? overrideProperties.getTransactionBatchSize() : raProperties.getTransactionBatchSize(); + if (val2 != null) { cf.setTransactionBatchSize(val2); } - val2 = overrideProperties.getInitialConnectAttempts() != null ? overrideProperties.getInitialConnectAttempts() - : raProperties.getInitialConnectAttempts(); - if (val2 != null) - { + val2 = overrideProperties.getInitialConnectAttempts() != null ? overrideProperties.getInitialConnectAttempts() : raProperties.getInitialConnectAttempts(); + if (val2 != null) { cf.setInitialConnectAttempts(val2); } - val2 = overrideProperties.getInitialMessagePacketSize() != null ? overrideProperties.getInitialMessagePacketSize() - : raProperties.getInitialMessagePacketSize(); - if (val2 != null) - { + val2 = overrideProperties.getInitialMessagePacketSize() != null ? overrideProperties.getInitialMessagePacketSize() : raProperties.getInitialMessagePacketSize(); + if (val2 != null) { cf.setInitialMessagePacketSize(val2); } - Long val3 = overrideProperties.getClientFailureCheckPeriod() != null ? overrideProperties.getClientFailureCheckPeriod() - : raProperties.getClientFailureCheckPeriod(); - if (val3 != null) - { + Long val3 = overrideProperties.getClientFailureCheckPeriod() != null ? overrideProperties.getClientFailureCheckPeriod() : raProperties.getClientFailureCheckPeriod(); + if (val3 != null) { cf.setClientFailureCheckPeriod(val3); } - val3 = overrideProperties.getCallTimeout() != null ? overrideProperties.getCallTimeout() - : raProperties.getCallTimeout(); - if (val3 != null) - { + val3 = overrideProperties.getCallTimeout() != null ? overrideProperties.getCallTimeout() : raProperties.getCallTimeout(); + if (val3 != null) { cf.setCallTimeout(val3); } - val3 = overrideProperties.getCallFailoverTimeout() != null ? overrideProperties.getCallFailoverTimeout() - : raProperties.getCallFailoverTimeout(); - if (val3 != null) - { + val3 = overrideProperties.getCallFailoverTimeout() != null ? overrideProperties.getCallFailoverTimeout() : raProperties.getCallFailoverTimeout(); + if (val3 != null) { cf.setCallFailoverTimeout(val3); } - val3 = overrideProperties.getConnectionTTL() != null ? overrideProperties.getConnectionTTL() - : raProperties.getConnectionTTL(); - if (val3 != null) - { + val3 = overrideProperties.getConnectionTTL() != null ? overrideProperties.getConnectionTTL() : raProperties.getConnectionTTL(); + if (val3 != null) { cf.setConnectionTTL(val3); } - val3 = overrideProperties.getRetryInterval() != null ? overrideProperties.getRetryInterval() - : raProperties.getRetryInterval(); - if (val3 != null) - { + val3 = overrideProperties.getRetryInterval() != null ? overrideProperties.getRetryInterval() : raProperties.getRetryInterval(); + if (val3 != null) { cf.setRetryInterval(val3); } - val3 = overrideProperties.getMaxRetryInterval() != null ? overrideProperties.getMaxRetryInterval() - : raProperties.getMaxRetryInterval(); - if (val3 != null) - { + val3 = overrideProperties.getMaxRetryInterval() != null ? overrideProperties.getMaxRetryInterval() : raProperties.getMaxRetryInterval(); + if (val3 != null) { cf.setMaxRetryInterval(val3); } - Double val4 = overrideProperties.getRetryIntervalMultiplier() != null ? overrideProperties.getRetryIntervalMultiplier() - : raProperties.getRetryIntervalMultiplier(); - if (val4 != null) - { + Double val4 = overrideProperties.getRetryIntervalMultiplier() != null ? overrideProperties.getRetryIntervalMultiplier() : raProperties.getRetryIntervalMultiplier(); + if (val4 != null) { cf.setRetryIntervalMultiplier(val4); } - String val5 = overrideProperties.getClientID() != null ? overrideProperties.getClientID() - : raProperties.getClientID(); - if (val5 != null) - { + String val5 = overrideProperties.getClientID() != null ? overrideProperties.getClientID() : raProperties.getClientID(); + if (val5 != null) { cf.setClientID(val5); } - val5 = overrideProperties.getConnectionLoadBalancingPolicyClassName() != null ? overrideProperties.getConnectionLoadBalancingPolicyClassName() - : raProperties.getConnectionLoadBalancingPolicyClassName(); - if (val5 != null) - { + val5 = overrideProperties.getConnectionLoadBalancingPolicyClassName() != null ? overrideProperties.getConnectionLoadBalancingPolicyClassName() : raProperties.getConnectionLoadBalancingPolicyClassName(); + if (val5 != null) { cf.setConnectionLoadBalancingPolicyClassName(val5); } } - public void setManagedConnectionFactory(ActiveMQRAManagedConnectionFactory activeMQRAManagedConnectionFactory) - { + public void setManagedConnectionFactory(ActiveMQRAManagedConnectionFactory activeMQRAManagedConnectionFactory) { managedConnectionFactories.add(activeMQRAManagedConnectionFactory); } - public SensitiveDataCodec getCodecInstance() - { + public SensitiveDataCodec getCodecInstance() { return raProperties.getCodecInstance(); } } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ConnectionFactoryProperties.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ConnectionFactoryProperties.java index 0cea642ded..770dd3ad83 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ConnectionFactoryProperties.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ConnectionFactoryProperties.java @@ -19,8 +19,8 @@ package org.apache.activemq.artemis.ra; import java.util.List; import java.util.Map; -public class ConnectionFactoryProperties -{ +public class ConnectionFactoryProperties { + /** * Trace enabled */ @@ -121,710 +121,565 @@ public class ConnectionFactoryProperties /** * @return the transportType */ - public List getParsedConnectorClassNames() - { + public List getParsedConnectorClassNames() { return connectorClassName; } - public List> getParsedConnectionParameters() - { + public List> getParsedConnectionParameters() { return connectionParameters; } - public void setParsedConnectionParameters(final List> connectionParameters) - { + public void setParsedConnectionParameters(final List> connectionParameters) { this.connectionParameters = connectionParameters; hasBeenUpdated = true; } - public void setParsedConnectorClassNames(final List value) - { + public void setParsedConnectorClassNames(final List value) { connectorClassName = value; hasBeenUpdated = true; } - public Boolean isHA() - { + public Boolean isHA() { return ha; } - public void setHA(final Boolean ha) - { + public void setHA(final Boolean ha) { hasBeenUpdated = true; this.ha = ha; } - public Boolean isCacheLargeMessagesClient() - { + public Boolean isCacheLargeMessagesClient() { return cacheLargeMessagesClient; } - public void setCacheLargeMessagesClient(Boolean cacheLargeMessagesClient) - { + public void setCacheLargeMessagesClient(Boolean cacheLargeMessagesClient) { hasBeenUpdated = true; this.cacheLargeMessagesClient = cacheLargeMessagesClient; } - public Boolean isCompressLargeMessage() - { + public Boolean isCompressLargeMessage() { return compressLargeMessage; } - public void setCompressLargeMessage(Boolean compressLargeMessage) - { + public void setCompressLargeMessage(Boolean compressLargeMessage) { hasBeenUpdated = true; this.compressLargeMessage = compressLargeMessage; } - public String getConnectionLoadBalancingPolicyClassName() - { - if (ConnectionFactoryProperties.trace) - { + public String getConnectionLoadBalancingPolicyClassName() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("getConnectionLoadBalancingPolicyClassName()"); } return connectionLoadBalancingPolicyClassName; } - public void setConnectionLoadBalancingPolicyClassName(final String connectionLoadBalancingPolicyClassName) - { - if (ConnectionFactoryProperties.trace) - { + public void setConnectionLoadBalancingPolicyClassName(final String connectionLoadBalancingPolicyClassName) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setSessionDefaultType(" + connectionLoadBalancingPolicyClassName + ")"); } hasBeenUpdated = true; this.connectionLoadBalancingPolicyClassName = connectionLoadBalancingPolicyClassName; } - public String getDiscoveryAddress() - { - if (ConnectionFactoryProperties.trace) - { + public String getDiscoveryAddress() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("getDiscoveryAddress()"); } return discoveryAddress; } - public void setDiscoveryAddress(final String discoveryAddress) - { - if (ConnectionFactoryProperties.trace) - { + public void setDiscoveryAddress(final String discoveryAddress) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setDiscoveryAddress(" + discoveryAddress + ")"); } hasBeenUpdated = true; this.discoveryAddress = discoveryAddress; } - public Integer getDiscoveryPort() - { - if (ConnectionFactoryProperties.trace) - { + public Integer getDiscoveryPort() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("getDiscoveryPort()"); } return discoveryPort; } - public void setDiscoveryLocalBindAddress(final String discoveryLocalBindAddress) - { - if (ConnectionFactoryProperties.trace) - { + public void setDiscoveryLocalBindAddress(final String discoveryLocalBindAddress) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setDiscoveryLocalBindAddress(" + discoveryLocalBindAddress + ")"); } hasBeenUpdated = true; this.discoveryLocalBindAddress = discoveryLocalBindAddress; } - public String getDiscoveryLocalBindAddress() - { - if (ConnectionFactoryProperties.trace) - { + public String getDiscoveryLocalBindAddress() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("getDiscoveryLocalBindAddress()"); } return discoveryLocalBindAddress; } - public void setDiscoveryPort(final Integer discoveryPort) - { - if (ConnectionFactoryProperties.trace) - { + public void setDiscoveryPort(final Integer discoveryPort) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setDiscoveryPort(" + discoveryPort + ")"); } hasBeenUpdated = true; this.discoveryPort = discoveryPort; } - public Long getDiscoveryRefreshTimeout() - { - if (ConnectionFactoryProperties.trace) - { + public Long getDiscoveryRefreshTimeout() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("getDiscoveryRefreshTimeout()"); } return discoveryRefreshTimeout; } - public void setDiscoveryRefreshTimeout(final Long discoveryRefreshTimeout) - { - if (ConnectionFactoryProperties.trace) - { + public void setDiscoveryRefreshTimeout(final Long discoveryRefreshTimeout) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setDiscoveryRefreshTimeout(" + discoveryRefreshTimeout + ")"); } hasBeenUpdated = true; this.discoveryRefreshTimeout = discoveryRefreshTimeout; } - public Long getDiscoveryInitialWaitTimeout() - { - if (ConnectionFactoryProperties.trace) - { + public Long getDiscoveryInitialWaitTimeout() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("getDiscoveryInitialWaitTimeout()"); } return discoveryInitialWaitTimeout; } - public void setDiscoveryInitialWaitTimeout(final Long discoveryInitialWaitTimeout) - { - if (ConnectionFactoryProperties.trace) - { + public void setDiscoveryInitialWaitTimeout(final Long discoveryInitialWaitTimeout) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setDiscoveryInitialWaitTimeout(" + discoveryInitialWaitTimeout + ")"); } hasBeenUpdated = true; this.discoveryInitialWaitTimeout = discoveryInitialWaitTimeout; } - public String getClientID() - { - if (ConnectionFactoryProperties.trace) - { + public String getClientID() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("getClientID()"); } return clientID; } - public void setClientID(final String clientID) - { - if (ConnectionFactoryProperties.trace) - { + public void setClientID(final String clientID) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setClientID(" + clientID + ")"); } hasBeenUpdated = true; this.clientID = clientID; } - public Integer getDupsOKBatchSize() - { - if (ConnectionFactoryProperties.trace) - { + public Integer getDupsOKBatchSize() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("getDupsOKBatchSize()"); } return dupsOKBatchSize; } - public void setDupsOKBatchSize(final Integer dupsOKBatchSize) - { - if (ConnectionFactoryProperties.trace) - { + public void setDupsOKBatchSize(final Integer dupsOKBatchSize) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setDupsOKBatchSize(" + dupsOKBatchSize + ")"); } hasBeenUpdated = true; this.dupsOKBatchSize = dupsOKBatchSize; } - public Integer getTransactionBatchSize() - { - if (ConnectionFactoryProperties.trace) - { + public Integer getTransactionBatchSize() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("getTransactionBatchSize()"); } return transactionBatchSize; } - public void setTransactionBatchSize(final Integer transactionBatchSize) - { - if (ConnectionFactoryProperties.trace) - { + public void setTransactionBatchSize(final Integer transactionBatchSize) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setTransactionBatchSize(" + transactionBatchSize + ")"); } hasBeenUpdated = true; this.transactionBatchSize = transactionBatchSize; } - public Long getClientFailureCheckPeriod() - { - if (ConnectionFactoryProperties.trace) - { + public Long getClientFailureCheckPeriod() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("getClientFailureCheckPeriod()"); } return clientFailureCheckPeriod; } - public void setClientFailureCheckPeriod(final Long clientFailureCheckPeriod) - { - if (ConnectionFactoryProperties.trace) - { + public void setClientFailureCheckPeriod(final Long clientFailureCheckPeriod) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setClientFailureCheckPeriod(" + clientFailureCheckPeriod + ")"); } hasBeenUpdated = true; this.clientFailureCheckPeriod = clientFailureCheckPeriod; } - public Long getConnectionTTL() - { - if (ConnectionFactoryProperties.trace) - { + public Long getConnectionTTL() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("getConnectionTTL()"); } return connectionTTL; } - public void setConnectionTTL(final Long connectionTTL) - { - if (ConnectionFactoryProperties.trace) - { + public void setConnectionTTL(final Long connectionTTL) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setConnectionTTL(" + connectionTTL + ")"); } hasBeenUpdated = true; this.connectionTTL = connectionTTL; } - public Long getCallTimeout() - { - if (ConnectionFactoryProperties.trace) - { + public Long getCallTimeout() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("getCallTimeout()"); } return callTimeout; } - public void setCallTimeout(final Long callTimeout) - { - if (ConnectionFactoryProperties.trace) - { + public void setCallTimeout(final Long callTimeout) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setCallTimeout(" + callTimeout + ")"); } hasBeenUpdated = true; this.callTimeout = callTimeout; } - public Long getCallFailoverTimeout() - { - if (ConnectionFactoryProperties.trace) - { + public Long getCallFailoverTimeout() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("getCallFailoverTimeout()"); } return callFailoverTimeout; } - public void setCallFailoverTimeout(final Long callFailoverTimeout) - { - if (ConnectionFactoryProperties.trace) - { + public void setCallFailoverTimeout(final Long callFailoverTimeout) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setCallFailoverTimeout(" + callFailoverTimeout + ")"); } hasBeenUpdated = true; this.callFailoverTimeout = callFailoverTimeout; } - public Integer getConsumerWindowSize() - { - if (ConnectionFactoryProperties.trace) - { + public Integer getConsumerWindowSize() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("getConsumerWindowSize()"); } return consumerWindowSize; } - public void setConsumerWindowSize(final Integer consumerWindowSize) - { - if (ConnectionFactoryProperties.trace) - { + public void setConsumerWindowSize(final Integer consumerWindowSize) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setConsumerWindowSize(" + consumerWindowSize + ")"); } hasBeenUpdated = true; this.consumerWindowSize = consumerWindowSize; } - public Integer getConsumerMaxRate() - { - if (ConnectionFactoryProperties.trace) - { + public Integer getConsumerMaxRate() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("getConsumerMaxRate()"); } return consumerMaxRate; } - public void setConsumerMaxRate(final Integer consumerMaxRate) - { - if (ConnectionFactoryProperties.trace) - { + public void setConsumerMaxRate(final Integer consumerMaxRate) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setConsumerMaxRate(" + consumerMaxRate + ")"); } hasBeenUpdated = true; this.consumerMaxRate = consumerMaxRate; } - public Integer getConfirmationWindowSize() - { - if (ConnectionFactoryProperties.trace) - { + public Integer getConfirmationWindowSize() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("getConfirmationWindowSize()"); } return confirmationWindowSize; } - public void setConfirmationWindowSize(final Integer confirmationWindowSize) - { - if (ConnectionFactoryProperties.trace) - { + public void setConfirmationWindowSize(final Integer confirmationWindowSize) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setConfirmationWindowSize(" + confirmationWindowSize + ")"); } hasBeenUpdated = true; this.confirmationWindowSize = confirmationWindowSize; } - public Boolean isFailoverOnInitialConnection() - { + public Boolean isFailoverOnInitialConnection() { return failoverOnInitialConnection; } - public void setFailoverOnInitialConnection(Boolean failoverOnInitialConnection) - { + public void setFailoverOnInitialConnection(Boolean failoverOnInitialConnection) { hasBeenUpdated = true; this.failoverOnInitialConnection = failoverOnInitialConnection; } - public Integer getProducerMaxRate() - { - if (ConnectionFactoryProperties.trace) - { + public Integer getProducerMaxRate() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("getProducerMaxRate()"); } return producerMaxRate; } - public void setProducerMaxRate(final Integer producerMaxRate) - { - if (ConnectionFactoryProperties.trace) - { + public void setProducerMaxRate(final Integer producerMaxRate) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setProducerMaxRate(" + producerMaxRate + ")"); } hasBeenUpdated = true; this.producerMaxRate = producerMaxRate; } - public Integer getProducerWindowSize() - { - if (ConnectionFactoryProperties.trace) - { + public Integer getProducerWindowSize() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("getProducerWindowSize()"); } return producerWindowSize; } - public void setProducerWindowSize(final Integer producerWindowSize) - { - if (ConnectionFactoryProperties.trace) - { + public void setProducerWindowSize(final Integer producerWindowSize) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setProducerWindowSize(" + producerWindowSize + ")"); } hasBeenUpdated = true; this.producerWindowSize = producerWindowSize; } - public Integer getMinLargeMessageSize() - { - if (ConnectionFactoryProperties.trace) - { + public Integer getMinLargeMessageSize() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("getMinLargeMessageSize()"); } return minLargeMessageSize; } - public void setMinLargeMessageSize(final Integer minLargeMessageSize) - { - if (ConnectionFactoryProperties.trace) - { + public void setMinLargeMessageSize(final Integer minLargeMessageSize) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setMinLargeMessageSize(" + minLargeMessageSize + ")"); } hasBeenUpdated = true; this.minLargeMessageSize = minLargeMessageSize; } - public Boolean isBlockOnAcknowledge() - { - if (ConnectionFactoryProperties.trace) - { + public Boolean isBlockOnAcknowledge() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("isBlockOnAcknowledge()"); } return blockOnAcknowledge; } - public void setBlockOnAcknowledge(final Boolean blockOnAcknowledge) - { - if (ConnectionFactoryProperties.trace) - { + public void setBlockOnAcknowledge(final Boolean blockOnAcknowledge) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setBlockOnAcknowledge(" + blockOnAcknowledge + ")"); } hasBeenUpdated = true; this.blockOnAcknowledge = blockOnAcknowledge; } - public Boolean isBlockOnNonDurableSend() - { - if (ConnectionFactoryProperties.trace) - { + public Boolean isBlockOnNonDurableSend() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("isBlockOnNonDurableSend()"); } return blockOnNonDurableSend; } - public void setBlockOnNonDurableSend(final Boolean blockOnNonDurableSend) - { - if (ConnectionFactoryProperties.trace) - { + public void setBlockOnNonDurableSend(final Boolean blockOnNonDurableSend) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setBlockOnNonDurableSend(" + blockOnNonDurableSend + ")"); } hasBeenUpdated = true; this.blockOnNonDurableSend = blockOnNonDurableSend; } - public Boolean isBlockOnDurableSend() - { - if (ConnectionFactoryProperties.trace) - { + public Boolean isBlockOnDurableSend() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("isBlockOnDurableSend()"); } return blockOnDurableSend; } - public void setBlockOnDurableSend(final Boolean blockOnDurableSend) - { - if (ConnectionFactoryProperties.trace) - { + public void setBlockOnDurableSend(final Boolean blockOnDurableSend) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setBlockOnDurableSend(" + blockOnDurableSend + ")"); } hasBeenUpdated = true; this.blockOnDurableSend = blockOnDurableSend; } - public Boolean isAutoGroup() - { - if (ConnectionFactoryProperties.trace) - { + public Boolean isAutoGroup() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("isAutoGroup()"); } return autoGroup; } - public void setAutoGroup(final Boolean autoGroup) - { - if (ConnectionFactoryProperties.trace) - { + public void setAutoGroup(final Boolean autoGroup) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setAutoGroup(" + autoGroup + ")"); } hasBeenUpdated = true; this.autoGroup = autoGroup; } - public Boolean isPreAcknowledge() - { - if (ConnectionFactoryProperties.trace) - { + public Boolean isPreAcknowledge() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("isPreAcknowledge()"); } return preAcknowledge; } - public void setPreAcknowledge(final Boolean preAcknowledge) - { - if (ConnectionFactoryProperties.trace) - { + public void setPreAcknowledge(final Boolean preAcknowledge) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setPreAcknowledge(" + preAcknowledge + ")"); } hasBeenUpdated = true; this.preAcknowledge = preAcknowledge; } - public Long getRetryInterval() - { - if (ConnectionFactoryProperties.trace) - { + public Long getRetryInterval() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("getRetryInterval()"); } return retryInterval; } - public void setRetryInterval(final Long retryInterval) - { - if (ConnectionFactoryProperties.trace) - { + public void setRetryInterval(final Long retryInterval) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setRetryInterval(" + retryInterval + ")"); } hasBeenUpdated = true; this.retryInterval = retryInterval; } - public Double getRetryIntervalMultiplier() - { - if (ConnectionFactoryProperties.trace) - { + public Double getRetryIntervalMultiplier() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("getRetryIntervalMultiplier()"); } return retryIntervalMultiplier; } - public void setRetryIntervalMultiplier(final Double retryIntervalMultiplier) - { - if (ConnectionFactoryProperties.trace) - { + public void setRetryIntervalMultiplier(final Double retryIntervalMultiplier) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setRetryIntervalMultiplier(" + retryIntervalMultiplier + ")"); } hasBeenUpdated = true; this.retryIntervalMultiplier = retryIntervalMultiplier; } - public Long getMaxRetryInterval() - { + public Long getMaxRetryInterval() { return maxRetryInterval; } - public void setMaxRetryInterval(Long maxRetryInterval) - { + public void setMaxRetryInterval(Long maxRetryInterval) { hasBeenUpdated = true; this.maxRetryInterval = maxRetryInterval; } - public Integer getReconnectAttempts() - { - if (ConnectionFactoryProperties.trace) - { + public Integer getReconnectAttempts() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("getReconnectAttempts()"); } return reconnectAttempts; } - public void setReconnectAttempts(final Integer reconnectAttempts) - { - if (ConnectionFactoryProperties.trace) - { + public void setReconnectAttempts(final Integer reconnectAttempts) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setReconnectAttempts(" + reconnectAttempts + ")"); } hasBeenUpdated = true; this.reconnectAttempts = reconnectAttempts; } - public Boolean isUseGlobalPools() - { - if (ConnectionFactoryProperties.trace) - { + public Boolean isUseGlobalPools() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("isUseGlobalPools()"); } return useGlobalPools; } - public void setUseGlobalPools(final Boolean useGlobalPools) - { - if (ConnectionFactoryProperties.trace) - { + public void setUseGlobalPools(final Boolean useGlobalPools) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setUseGlobalPools(" + useGlobalPools + ")"); } hasBeenUpdated = true; this.useGlobalPools = useGlobalPools; } - public Integer getScheduledThreadPoolMaxSize() - { - if (ConnectionFactoryProperties.trace) - { + public Integer getScheduledThreadPoolMaxSize() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("getScheduledThreadPoolMaxSize()"); } return scheduledThreadPoolMaxSize; } - public void setScheduledThreadPoolMaxSize(final Integer scheduledThreadPoolMaxSize) - { - if (ConnectionFactoryProperties.trace) - { + public void setScheduledThreadPoolMaxSize(final Integer scheduledThreadPoolMaxSize) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setScheduledThreadPoolMaxSize(" + scheduledThreadPoolMaxSize + ")"); } hasBeenUpdated = true; this.scheduledThreadPoolMaxSize = scheduledThreadPoolMaxSize; } - public Integer getThreadPoolMaxSize() - { - if (ConnectionFactoryProperties.trace) - { + public Integer getThreadPoolMaxSize() { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("getThreadPoolMaxSize()"); } return threadPoolMaxSize; } - public void setThreadPoolMaxSize(final Integer threadPoolMaxSize) - { - if (ConnectionFactoryProperties.trace) - { + public void setThreadPoolMaxSize(final Integer threadPoolMaxSize) { + if (ConnectionFactoryProperties.trace) { ActiveMQRALogger.LOGGER.trace("setThreadPoolMaxSize(" + threadPoolMaxSize + ")"); } hasBeenUpdated = true; this.threadPoolMaxSize = threadPoolMaxSize; } - public String getGroupID() - { + public String getGroupID() { return groupID; } - public void setGroupID(String groupID) - { + public void setGroupID(String groupID) { hasBeenUpdated = true; this.groupID = groupID; } - public Integer getInitialConnectAttempts() - { + public Integer getInitialConnectAttempts() { return initialConnectAttempts; } - public void setInitialConnectAttempts(Integer initialConnectAttempts) - { + public void setInitialConnectAttempts(Integer initialConnectAttempts) { hasBeenUpdated = true; this.initialConnectAttempts = initialConnectAttempts; } - public Integer getInitialMessagePacketSize() - { + public Integer getInitialMessagePacketSize() { return initialMessagePacketSize; } - public void setInitialMessagePacketSize(Integer initialMessagePacketSize) - { + public void setInitialMessagePacketSize(Integer initialMessagePacketSize) { hasBeenUpdated = true; this.initialMessagePacketSize = initialMessagePacketSize; } - public String getJgroupsFile() - { + public String getJgroupsFile() { return jgroupsFile; } - public void setJgroupsFile(String jgroupsFile) - { + public void setJgroupsFile(String jgroupsFile) { this.jgroupsFile = jgroupsFile; hasBeenUpdated = true; } - public String getJgroupsChannelName() - { + public String getJgroupsChannelName() { return jgroupsChannelName; } - public void setJgroupsChannelName(String jgroupsChannelName) - { + public void setJgroupsChannelName(String jgroupsChannelName) { this.jgroupsChannelName = jgroupsChannelName; hasBeenUpdated = true; } - public boolean isHasBeenUpdated() - { + public boolean isHasBeenUpdated() { return hasBeenUpdated; } } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/inflow/ActiveMQActivation.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/inflow/ActiveMQActivation.java index 1d9de07942..3e4f97d812 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/inflow/ActiveMQActivation.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/inflow/ActiveMQActivation.java @@ -56,8 +56,8 @@ import org.apache.activemq.artemis.utils.SensitiveDataCodec; /** * The activation. */ -public class ActiveMQActivation -{ +public class ActiveMQActivation { + /** * Trace enabled */ @@ -113,14 +113,11 @@ public class ActiveMQActivation private final AtomicBoolean inFailure = new AtomicBoolean(false); private XARecoveryConfig resourceRecovery; - static - { - try - { + static { + try { ONMESSAGE = MessageListener.class.getMethod("onMessage", new Class[]{Message.class}); } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } } @@ -135,28 +132,22 @@ public class ActiveMQActivation */ public ActiveMQActivation(final ActiveMQResourceAdapter ra, final MessageEndpointFactory endpointFactory, - final ActiveMQActivationSpec spec) throws ResourceException - { + final ActiveMQActivationSpec spec) throws ResourceException { spec.validate(); - if (ActiveMQActivation.trace) - { + if (ActiveMQActivation.trace) { ActiveMQRALogger.LOGGER.trace("constructor(" + ra + ", " + endpointFactory + ", " + spec + ")"); } - if (ra.isUseMaskedPassword()) - { + if (ra.isUseMaskedPassword()) { String pass = spec.getOwnPassword(); - if (pass != null) - { + if (pass != null) { SensitiveDataCodec codec = ra.getCodecInstance(); - try - { + try { spec.setPassword(codec.decode(pass)); } - catch (Exception e) - { + catch (Exception e) { throw new ResourceException(e); } } @@ -165,12 +156,10 @@ public class ActiveMQActivation this.ra = ra; this.endpointFactory = endpointFactory; this.spec = spec; - try - { + try { isDeliveryTransacted = endpointFactory.isDeliveryTransacted(ActiveMQActivation.ONMESSAGE); } - catch (Exception e) - { + catch (Exception e) { throw new ResourceException(e); } } @@ -180,10 +169,8 @@ public class ActiveMQActivation * * @return The value */ - public ActiveMQActivationSpec getActivationSpec() - { - if (ActiveMQActivation.trace) - { + public ActiveMQActivationSpec getActivationSpec() { + if (ActiveMQActivation.trace) { ActiveMQRALogger.LOGGER.trace("getActivationSpec()"); } @@ -195,10 +182,8 @@ public class ActiveMQActivation * * @return The value */ - public MessageEndpointFactory getMessageEndpointFactory() - { - if (ActiveMQActivation.trace) - { + public MessageEndpointFactory getMessageEndpointFactory() { + if (ActiveMQActivation.trace) { ActiveMQRALogger.LOGGER.trace("getMessageEndpointFactory()"); } @@ -210,10 +195,8 @@ public class ActiveMQActivation * * @return The value */ - public boolean isDeliveryTransacted() - { - if (ActiveMQActivation.trace) - { + public boolean isDeliveryTransacted() { + if (ActiveMQActivation.trace) { ActiveMQRALogger.LOGGER.trace("isDeliveryTransacted()"); } @@ -225,10 +208,8 @@ public class ActiveMQActivation * * @return The value */ - public WorkManager getWorkManager() - { - if (ActiveMQActivation.trace) - { + public WorkManager getWorkManager() { + if (ActiveMQActivation.trace) { ActiveMQRALogger.LOGGER.trace("getWorkManager()"); } @@ -240,10 +221,8 @@ public class ActiveMQActivation * * @return The value */ - public boolean isTopic() - { - if (ActiveMQActivation.trace) - { + public boolean isTopic() { + if (ActiveMQActivation.trace) { ActiveMQRALogger.LOGGER.trace("isTopic()"); } @@ -255,10 +234,8 @@ public class ActiveMQActivation * * @throws ResourceException Thrown if an error occurs */ - public void start() throws ResourceException - { - if (ActiveMQActivation.trace) - { + public void start() throws ResourceException { + if (ActiveMQActivation.trace) { ActiveMQRALogger.LOGGER.trace("start()"); } deliveryActive.set(true); @@ -268,30 +245,25 @@ public class ActiveMQActivation /** * @return the topicTemporaryQueue */ - public SimpleString getTopicTemporaryQueue() - { + public SimpleString getTopicTemporaryQueue() { return topicTemporaryQueue; } /** * @param topicTemporaryQueue the topicTemporaryQueue to set */ - public void setTopicTemporaryQueue(SimpleString topicTemporaryQueue) - { + public void setTopicTemporaryQueue(SimpleString topicTemporaryQueue) { this.topicTemporaryQueue = topicTemporaryQueue; } /** * @return the list of XAResources for this activation endpoint */ - public List getXAResources() - { + public List getXAResources() { List xaresources = new ArrayList(); - for (ActiveMQMessageHandler handler : handlers) - { + for (ActiveMQMessageHandler handler : handlers) { XAResource xares = handler.getXAResource(); - if (xares != null) - { + if (xares != null) { xaresources.add(xares); } } @@ -301,10 +273,8 @@ public class ActiveMQActivation /** * Stop the activation */ - public void stop() - { - if (ActiveMQActivation.trace) - { + public void stop() { + if (ActiveMQActivation.trace) { ActiveMQRALogger.LOGGER.trace("stop()"); } @@ -317,8 +287,7 @@ public class ActiveMQActivation * * @throws Exception Thrown if an error occurs */ - protected synchronized void setup() throws Exception - { + protected synchronized void setup() throws Exception { ActiveMQRALogger.LOGGER.debug("Setting up " + spec); setupCF(); @@ -327,49 +296,40 @@ public class ActiveMQActivation Exception firstException = null; - for (int i = 0; i < spec.getMaxSession(); i++) - { + for (int i = 0; i < spec.getMaxSession(); i++) { ClientSessionFactory cf = null; ClientSession session = null; - try - { + try { cf = factory.getServerLocator().createSessionFactory(); session = setupSession(cf); ActiveMQMessageHandler handler = new ActiveMQMessageHandler(this, ra.getTM(), (ClientSessionInternal) session, cf, i); handler.setup(); handlers.add(handler); } - catch (Exception e) - { - if (cf != null) - { + catch (Exception e) { + if (cf != null) { cf.close(); } - if (session != null) - { + if (session != null) { session.close(); } - if (firstException == null) - { + if (firstException == null) { firstException = e; } } } //if we have any exceptions close all the handlers and throw the first exception. //we don't want partially configured activations, i.e. only 8 out of 15 sessions started so best to stop and log the error. - if (firstException != null) - { - for (ActiveMQMessageHandler handler : handlers) - { + if (firstException != null) { + for (ActiveMQMessageHandler handler : handlers) { handler.teardown(); } throw firstException; } //now start them all together. - for (ActiveMQMessageHandler handler : handlers) - { + for (ActiveMQMessageHandler handler : handlers) { handler.start(); } @@ -381,12 +341,10 @@ public class ActiveMQActivation /** * Teardown the activation */ - protected synchronized void teardown() - { + protected synchronized void teardown() { ActiveMQRALogger.LOGGER.debug("Tearing down " + spec); - if (resourceRecovery != null) - { + if (resourceRecovery != null) { ra.getRecoveryManager().unRegister(resourceRecovery); } @@ -394,8 +352,7 @@ public class ActiveMQActivation // We need to do from last to first as any temporary queue will have been created on the first handler // So we invert the handlers here - for (int i = 0; i < handlers.size(); i++) - { + for (int i = 0; i < handlers.size(); i++) { // The index here is the complimentary so it's inverting the array handlersCopy[i] = handlers.get(handlers.size() - i - 1); } @@ -404,11 +361,9 @@ public class ActiveMQActivation FutureLatch future = new FutureLatch(handlersCopy.length); List interruptThreads = new ArrayList<>(); - for (ActiveMQMessageHandler handler : handlersCopy) - { + for (ActiveMQMessageHandler handler : handlersCopy) { Thread thread = handler.interruptConsumer(future); - if (thread != null) - { + if (thread != null) { interruptThreads.add(thread); } } @@ -416,27 +371,20 @@ public class ActiveMQActivation //wait for all the consumers to complete any onmessage calls boolean stuckThreads = !future.await(factory.getCallTimeout()); //if any are stuck then we need to interrupt them - if (stuckThreads) - { - for (Thread interruptThread : interruptThreads) - { - try - { + if (stuckThreads) { + for (Thread interruptThread : interruptThreads) { + try { interruptThread.interrupt(); } - catch (Exception e) - { + catch (Exception e) { //ok } } } - Thread threadTearDown = new Thread("TearDown/ActiveMQActivation") - { - public void run() - { - for (ActiveMQMessageHandler handler : handlersCopy) - { + Thread threadTearDown = new Thread("TearDown/ActiveMQActivation") { + public void run() { + for (ActiveMQMessageHandler handler : handlersCopy) { handler.teardown(); } } @@ -447,91 +395,71 @@ public class ActiveMQActivation // if that failed we will then close the connection factory, and interrupt the thread threadTearDown.start(); - try - { + try { threadTearDown.join(factory.getCallTimeout()); } - catch (InterruptedException e) - { + catch (InterruptedException e) { // nothing to be done on this context.. we will just keep going as we need to send an interrupt to threadTearDown and give up } - if (threadTearDown.isAlive()) - { - if (factory != null) - { + if (threadTearDown.isAlive()) { + if (factory != null) { // This will interrupt any threads waiting on reconnect factory.close(); factory = null; } threadTearDown.interrupt(); - try - { + try { threadTearDown.join(5000); } - catch (InterruptedException e) - { + catch (InterruptedException e) { // nothing to be done here.. we are going down anyways } - if (threadTearDown.isAlive()) - { + if (threadTearDown.isAlive()) { ActiveMQRALogger.LOGGER.threadCouldNotFinish(threadTearDown.toString()); } } - if (spec.isHasBeenUpdated() && factory != null) - { + if (spec.isHasBeenUpdated() && factory != null) { factory.close(); factory = null; } - ActiveMQRALogger.LOGGER.debug("Tearing down complete " + this); } - protected void setupCF() throws Exception - { - if (spec.getConnectionFactoryLookup() != null) - { + protected void setupCF() throws Exception { + if (spec.getConnectionFactoryLookup() != null) { Context ctx; - if (spec.getParsedJndiParams() == null) - { + if (spec.getParsedJndiParams() == null) { ctx = new InitialContext(); } - else - { + else { ctx = new InitialContext(spec.getParsedJndiParams()); } Object fac = ctx.lookup(spec.getConnectionFactoryLookup()); - if (fac instanceof ActiveMQConnectionFactory) - { + if (fac instanceof ActiveMQConnectionFactory) { factory = (ActiveMQConnectionFactory) fac; } - else - { + else { ActiveMQRAConnectionFactory raFact = (ActiveMQRAConnectionFactory) fac; - if (spec.isHasBeenUpdated()) - { + if (spec.isHasBeenUpdated()) { factory = raFact.getResourceAdapter().createActiveMQConnectionFactory(spec); } - else - { + else { factory = raFact.getDefaultFactory(); - if (factory != ra.getDefaultActiveMQConnectionFactory()) - { + if (factory != ra.getDefaultActiveMQConnectionFactory()) { ActiveMQRALogger.LOGGER.warnDifferentConnectionfactory(); } } } } - else if (spec.isHasBeenUpdated()) - { + else if (spec.isHasBeenUpdated()) { factory = ra.createActiveMQConnectionFactory(spec); } - else - { + else { factory = ra.getDefaultActiveMQConnectionFactory(); } } @@ -543,28 +471,16 @@ public class ActiveMQActivation * @return The connection * @throws Exception Thrown if an error occurs */ - protected ClientSession setupSession(ClientSessionFactory cf) throws Exception - { + protected ClientSession setupSession(ClientSessionFactory cf) throws Exception { ClientSession result = null; - try - { - result = ra.createSession(cf, - spec.getAcknowledgeModeInt(), - spec.getUser(), - spec.getPassword(), - ra.getPreAcknowledge(), - ra.getDupsOKBatchSize(), - ra.getTransactionBatchSize(), - isDeliveryTransacted, - spec.isUseLocalTx(), - spec.getTransactionTimeout()); + try { + result = ra.createSession(cf, spec.getAcknowledgeModeInt(), spec.getUser(), spec.getPassword(), ra.getPreAcknowledge(), ra.getDupsOKBatchSize(), ra.getTransactionBatchSize(), isDeliveryTransacted, spec.isUseLocalTx(), spec.getTransactionTimeout()); result.addMetaData("resource-adapter", "inbound"); result.addMetaData(ClientSession.JMS_SESSION_IDENTIFIER_PROPERTY, ""); String clientID = ra.getClientID() == null ? spec.getClientID() : ra.getClientID(); - if (clientID != null) - { + if (clientID != null) { result.addMetaData(ClientSession.JMS_SESSION_CLIENT_ID_PROPERTY, clientID); } @@ -572,123 +488,99 @@ public class ActiveMQActivation return result; } - catch (Throwable t) - { - try - { - if (result != null) - { + catch (Throwable t) { + try { + if (result != null) { result.close(); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQRALogger.LOGGER.trace("Ignored error closing connection", e); } - if (t instanceof Exception) - { + if (t instanceof Exception) { throw (Exception) t; } throw new RuntimeException("Error configuring connection", t); } } - public SimpleString getAddress() - { + public SimpleString getAddress() { return destination.getSimpleAddress(); } - protected void setupDestination() throws Exception - { + protected void setupDestination() throws Exception { String destinationName = spec.getDestination(); - if (spec.isUseJNDI()) - { + if (spec.isUseJNDI()) { Context ctx; - if (spec.getParsedJndiParams() == null) - { + if (spec.getParsedJndiParams() == null) { ctx = new InitialContext(); } - else - { + else { ctx = new InitialContext(spec.getParsedJndiParams()); } ActiveMQRALogger.LOGGER.debug("Using context " + ctx.getEnvironment() + " for " + spec); - if (ActiveMQActivation.trace) - { + if (ActiveMQActivation.trace) { ActiveMQRALogger.LOGGER.trace("setupDestination(" + ctx + ")"); } String destinationTypeString = spec.getDestinationType(); - if (destinationTypeString != null && !destinationTypeString.trim().equals("")) - { + if (destinationTypeString != null && !destinationTypeString.trim().equals("")) { ActiveMQRALogger.LOGGER.debug("Destination type defined as " + destinationTypeString); Class destinationType; - if (Topic.class.getName().equals(destinationTypeString)) - { + if (Topic.class.getName().equals(destinationTypeString)) { destinationType = Topic.class; isTopic = true; } - else - { + else { destinationType = Queue.class; } ActiveMQRALogger.LOGGER.debug("Retrieving " + destinationType.getName() + " \"" + destinationName + "\" from JNDI"); - try - { + try { destination = (ActiveMQDestination) ActiveMQRaUtils.lookup(ctx, destinationName, destinationType); } - catch (Exception e) - { - if (destinationName == null) - { + catch (Exception e) { + if (destinationName == null) { throw ActiveMQRABundle.BUNDLE.noDestinationName(); } String calculatedDestinationName = destinationName.substring(destinationName.lastIndexOf('/') + 1); ActiveMQRALogger.LOGGER.debug("Unable to retrieve " + destinationName + - " from JNDI. Creating a new " + destinationType.getName() + - " named " + calculatedDestinationName + " to be used by the MDB."); + " from JNDI. Creating a new " + destinationType.getName() + + " named " + calculatedDestinationName + " to be used by the MDB."); // If there is no binding on naming, we will just create a new instance - if (isTopic) - { + if (isTopic) { destination = (ActiveMQDestination) ActiveMQJMSClient.createTopic(calculatedDestinationName); } - else - { + else { destination = (ActiveMQDestination) ActiveMQJMSClient.createQueue(calculatedDestinationName); } } } - else - { + else { ActiveMQRALogger.LOGGER.debug("Destination type not defined in MDB activation configuration."); ActiveMQRALogger.LOGGER.debug("Retrieving " + Destination.class.getName() + " \"" + destinationName + "\" from JNDI"); destination = (ActiveMQDestination) ActiveMQRaUtils.lookup(ctx, destinationName, Destination.class); - if (destination instanceof Topic) - { + if (destination instanceof Topic) { isTopic = true; } } } - else - { + else { ActiveMQRALogger.LOGGER.instantiatingDestination(spec.getDestinationType(), spec.getDestination()); - if (Topic.class.getName().equals(spec.getDestinationType())) - { + if (Topic.class.getName().equals(spec.getDestinationType())) { destination = (ActiveMQDestination) ActiveMQJMSClient.createTopic(spec.getDestination()); isTopic = true; } - else - { + else { destination = (ActiveMQDestination) ActiveMQJMSClient.createQueue(spec.getDestination()); } } @@ -700,15 +592,13 @@ public class ActiveMQActivation * @return The value */ @Override - public String toString() - { + public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(ActiveMQActivation.class.getName()).append('('); buffer.append("spec=").append(spec.getClass().getName()); buffer.append(" mepf=").append(endpointFactory.getClass().getName()); buffer.append(" active=").append(deliveryActive.get()); - if (spec.getDestination() != null) - { + if (spec.getDestination() != null) { buffer.append(" destination=").append(spec.getDestination()); } buffer.append(" transacted=").append(isDeliveryTransacted); @@ -721,18 +611,14 @@ public class ActiveMQActivation * * @param failure the reason for the failure */ - public void handleFailure(Throwable failure) - { - if (failure instanceof ActiveMQException && ((ActiveMQException) failure).getType() == ActiveMQExceptionType.QUEUE_DOES_NOT_EXIST) - { + public void handleFailure(Throwable failure) { + if (failure instanceof ActiveMQException && ((ActiveMQException) failure).getType() == ActiveMQExceptionType.QUEUE_DOES_NOT_EXIST) { ActiveMQRALogger.LOGGER.awaitingTopicQueueCreation(getActivationSpec().getDestination()); } - else if (failure instanceof ActiveMQException && ((ActiveMQException) failure).getType() == ActiveMQExceptionType.NOT_CONNECTED) - { + else if (failure instanceof ActiveMQException && ((ActiveMQException) failure).getType() == ActiveMQExceptionType.NOT_CONNECTED) { ActiveMQRALogger.LOGGER.awaitingJMSServerCreation(); } - else - { + else { ActiveMQRALogger.LOGGER.failureInActivation(failure, spec); } int reconnectCount = 0; @@ -742,90 +628,72 @@ public class ActiveMQActivation // Only enter the failure loop once if (inFailure.getAndSet(true)) return; - try - { + try { Throwable lastException = failure; - while (deliveryActive.get() && (setupAttempts == -1 || reconnectCount < setupAttempts)) - { + while (deliveryActive.get() && (setupAttempts == -1 || reconnectCount < setupAttempts)) { teardown(); - try - { + try { Thread.sleep(setupInterval); } - catch (InterruptedException e) - { + catch (InterruptedException e) { ActiveMQRALogger.LOGGER.debug("Interrupted trying to reconnect " + spec, e); break; } - if (reconnectCount < 1) - { + if (reconnectCount < 1) { ActiveMQRALogger.LOGGER.attemptingReconnect(spec); } - try - { + try { setup(); ActiveMQRALogger.LOGGER.reconnected(); break; } - catch (Throwable t) - { - if (failure instanceof ActiveMQException && ((ActiveMQException) failure).getType() == ActiveMQExceptionType.QUEUE_DOES_NOT_EXIST) - { - if (lastException == null || !(t instanceof ActiveMQNonExistentQueueException)) - { + catch (Throwable t) { + if (failure instanceof ActiveMQException && ((ActiveMQException) failure).getType() == ActiveMQExceptionType.QUEUE_DOES_NOT_EXIST) { + if (lastException == null || !(t instanceof ActiveMQNonExistentQueueException)) { lastException = t; ActiveMQRALogger.LOGGER.awaitingTopicQueueCreation(getActivationSpec().getDestination()); } } - else if (failure instanceof ActiveMQException && ((ActiveMQException) failure).getType() == ActiveMQExceptionType.NOT_CONNECTED) - { - if (lastException == null || !(t instanceof ActiveMQNotConnectedException)) - { + else if (failure instanceof ActiveMQException && ((ActiveMQException) failure).getType() == ActiveMQExceptionType.NOT_CONNECTED) { + if (lastException == null || !(t instanceof ActiveMQNotConnectedException)) { lastException = t; ActiveMQRALogger.LOGGER.awaitingJMSServerCreation(); } } - else - { + else { ActiveMQRALogger.LOGGER.errorReconnecting(t, spec); } } ++reconnectCount; } } - finally - { + finally { // Leaving failure recovery loop inFailure.set(false); } } - public ActiveMQConnectionFactory getConnectionFactory() - { + public ActiveMQConnectionFactory getConnectionFactory() { return this.factory; } /** * Handles the setup */ - private class SetupActivation implements Work - { - public void run() - { - try - { + private class SetupActivation implements Work { + + public void run() { + try { setup(); } - catch (Throwable t) - { + catch (Throwable t) { handleFailure(t); } } - public void release() - { + public void release() { } } } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/inflow/ActiveMQActivationSpec.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/inflow/ActiveMQActivationSpec.java index 4d71fdde38..4541eef106 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/inflow/ActiveMQActivationSpec.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/inflow/ActiveMQActivationSpec.java @@ -40,8 +40,8 @@ import org.apache.activemq.artemis.ra.ActiveMQResourceAdapter; * The activation spec * These properties are set on the MDB ActivactionProperties */ -public class ActiveMQActivationSpec extends ConnectionFactoryProperties implements ActivationSpec, Serializable -{ +public class ActiveMQActivationSpec extends ConnectionFactoryProperties implements ActivationSpec, Serializable { + private static final long serialVersionUID = -7997041053897964654L; private static final int DEFAULT_MAX_SESSION = 15; @@ -138,10 +138,8 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen /** * Constructor */ - public ActiveMQActivationSpec() - { - if (ActiveMQActivationSpec.trace) - { + public ActiveMQActivationSpec() { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("constructor()"); } @@ -163,10 +161,8 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @return The resource adapter */ - public ResourceAdapter getResourceAdapter() - { - if (ActiveMQActivationSpec.trace) - { + public ResourceAdapter getResourceAdapter() { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("getResourceAdapter()"); } @@ -176,10 +172,8 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen /** * @return the useJNDI */ - public boolean isUseJNDI() - { - if (useJNDI == null) - { + public boolean isUseJNDI() { + if (useJNDI == null) { return ra.isUseJNDI(); } return useJNDI; @@ -188,33 +182,27 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen /** * @param value the useJNDI to set */ - public void setUseJNDI(final boolean value) - { + public void setUseJNDI(final boolean value) { useJNDI = value; } /** * @return return the jndi params to use */ - public String getJndiParams() - { - if (jndiParams == null) - { + public String getJndiParams() { + if (jndiParams == null) { return ra.getJndiParams(); } return jndiParams; } - public void setJndiParams(String jndiParams) - { + public void setJndiParams(String jndiParams) { this.jndiParams = jndiParams; parsedJndiParams = ActiveMQRaUtils.parseHashtableConfig(jndiParams); } - public Hashtable getParsedJndiParams() - { - if (parsedJndiParams == null) - { + public Hashtable getParsedJndiParams() { + if (parsedJndiParams == null) { return ra.getParsedJndiParams(); } return parsedJndiParams; @@ -226,15 +214,12 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * @param ra The resource adapter * @throws ResourceException Thrown if incorrect resource adapter */ - public void setResourceAdapter(final ResourceAdapter ra) throws ResourceException - { - if (ActiveMQActivationSpec.trace) - { + public void setResourceAdapter(final ResourceAdapter ra) throws ResourceException { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("setResourceAdapter(" + ra + ")"); } - if (ra == null || !(ra instanceof ActiveMQResourceAdapter)) - { + if (ra == null || !(ra instanceof ActiveMQResourceAdapter)) { throw new ResourceException("Resource adapter is " + ra); } @@ -246,10 +231,8 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @return The value */ - public String getConnectionFactoryLookup() - { - if (ActiveMQActivationSpec.trace) - { + public String getConnectionFactoryLookup() { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("getConnectionFactoryLookup() ->" + connectionFactoryLookup); } @@ -261,10 +244,8 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @param value The value */ - public void setConnectionFactoryLookup(final String value) - { - if (ActiveMQActivationSpec.trace) - { + public void setConnectionFactoryLookup(final String value) { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("setConnectionFactoryLookup(" + value + ")"); } @@ -276,10 +257,8 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @return The value */ - public String getDestination() - { - if (ActiveMQActivationSpec.trace) - { + public String getDestination() { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("getDestination()"); } @@ -291,10 +270,8 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @param value The value */ - public void setDestination(final String value) - { - if (ActiveMQActivationSpec.trace) - { + public void setDestination(final String value) { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("setDestination(" + value + ")"); } @@ -306,8 +283,7 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @return The value */ - public String getDestinationLookup() - { + public String getDestinationLookup() { return getDestination(); } @@ -316,8 +292,7 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @param value The value */ - public void setDestinationLookup(final String value) - { + public void setDestinationLookup(final String value) { setDestination(value); setUseJNDI(true); } @@ -327,10 +302,8 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @return The value */ - public String getDestinationType() - { - if (ActiveMQActivationSpec.trace) - { + public String getDestinationType() { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("getDestinationType()"); } @@ -342,10 +315,8 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @param value The value */ - public void setDestinationType(final String value) - { - if (ActiveMQActivationSpec.trace) - { + public void setDestinationType(final String value) { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("setDestinationType(" + value + ")"); } @@ -357,10 +328,8 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @return The value */ - public String getMessageSelector() - { - if (ActiveMQActivationSpec.trace) - { + public String getMessageSelector() { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("getMessageSelector()"); } @@ -372,10 +341,8 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @param value The value */ - public void setMessageSelector(final String value) - { - if (ActiveMQActivationSpec.trace) - { + public void setMessageSelector(final String value) { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("setMessageSelector(" + value + ")"); } @@ -387,19 +354,15 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @return The value */ - public String getAcknowledgeMode() - { - if (ActiveMQActivationSpec.trace) - { + public String getAcknowledgeMode() { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("getAcknowledgeMode()"); } - if (Session.DUPS_OK_ACKNOWLEDGE == acknowledgeMode) - { + if (Session.DUPS_OK_ACKNOWLEDGE == acknowledgeMode) { return "Dups-ok-acknowledge"; } - else - { + else { return "Auto-acknowledge"; } } @@ -409,23 +372,18 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @param value The value */ - public void setAcknowledgeMode(final String value) - { - if (ActiveMQActivationSpec.trace) - { + public void setAcknowledgeMode(final String value) { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("setAcknowledgeMode(" + value + ")"); } - if ("DUPS_OK_ACKNOWLEDGE".equalsIgnoreCase(value) || "Dups-ok-acknowledge".equalsIgnoreCase(value)) - { + if ("DUPS_OK_ACKNOWLEDGE".equalsIgnoreCase(value) || "Dups-ok-acknowledge".equalsIgnoreCase(value)) { acknowledgeMode = Session.DUPS_OK_ACKNOWLEDGE; } - else if ("AUTO_ACKNOWLEDGE".equalsIgnoreCase(value) || "Auto-acknowledge".equalsIgnoreCase(value)) - { + else if ("AUTO_ACKNOWLEDGE".equalsIgnoreCase(value) || "Auto-acknowledge".equalsIgnoreCase(value)) { acknowledgeMode = Session.AUTO_ACKNOWLEDGE; } - else - { + else { throw new IllegalArgumentException("Unsupported acknowledgement mode " + value); } } @@ -433,10 +391,8 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen /** * @return the acknowledgement mode */ - public int getAcknowledgeModeInt() - { - if (ActiveMQActivationSpec.trace) - { + public int getAcknowledgeModeInt() { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("getAcknowledgeMode()"); } @@ -448,19 +404,15 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @return The value */ - public String getSubscriptionDurability() - { - if (ActiveMQActivationSpec.trace) - { + public String getSubscriptionDurability() { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("getSubscriptionDurability()"); } - if (subscriptionDurability) - { + if (subscriptionDurability) { return "Durable"; } - else - { + else { return "NonDurable"; } } @@ -470,10 +422,8 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @param value The value */ - public void setSubscriptionDurability(final String value) - { - if (ActiveMQActivationSpec.trace) - { + public void setSubscriptionDurability(final String value) { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("setSubscriptionDurability(" + value + ")"); } @@ -485,10 +435,8 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @return The value */ - public boolean isSubscriptionDurable() - { - if (ActiveMQActivationSpec.trace) - { + public boolean isSubscriptionDurable() { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("isSubscriptionDurable()"); } @@ -500,10 +448,8 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @return The value */ - public String getSubscriptionName() - { - if (ActiveMQActivationSpec.trace) - { + public String getSubscriptionName() { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("getSubscriptionName()"); } @@ -515,24 +461,19 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @param value The value */ - public void setSubscriptionName(final String value) - { - if (ActiveMQActivationSpec.trace) - { + public void setSubscriptionName(final String value) { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("setSubscriptionName(" + value + ")"); } subscriptionName = value; } - /** * @return the shareDurableSubscriptions */ - public boolean isShareSubscriptions() - { - if (ActiveMQActivationSpec.trace) - { + public boolean isShareSubscriptions() { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("isShareSubscriptions() = " + shareSubscriptions); } @@ -542,10 +483,8 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen /** * @param shareSubscriptions the shareDurableSubscriptions to set */ - public void setShareSubscriptions(boolean shareSubscriptions) - { - if (ActiveMQActivationSpec.trace) - { + public void setShareSubscriptions(boolean shareSubscriptions) { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("setShareSubscriptions(" + shareSubscriptions + ")"); } @@ -557,19 +496,15 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @return The value */ - public String getUser() - { - if (ActiveMQActivationSpec.trace) - { + public String getUser() { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("getUser()"); } - if (user == null) - { + if (user == null) { return ra.getUserName(); } - else - { + else { return user; } } @@ -579,10 +514,8 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @param value The value */ - public void setUser(final String value) - { - if (ActiveMQActivationSpec.trace) - { + public void setUser(final String value) { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("setUser(" + value + ")"); } @@ -594,25 +527,20 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @return The value */ - public String getPassword() - { - if (ActiveMQActivationSpec.trace) - { + public String getPassword() { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("getPassword()"); } - if (password == null) - { + if (password == null) { return ra.getPassword(); } - else - { + else { return password; } } - public String getOwnPassword() - { + public String getOwnPassword() { return password; } @@ -621,10 +549,8 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @param value The value */ - public void setPassword(final String value) throws Exception - { - if (ActiveMQActivationSpec.trace) - { + public void setPassword(final String value) throws Exception { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("setPassword(****)"); } @@ -636,15 +562,12 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @return The value */ - public Integer getMaxSession() - { - if (ActiveMQActivationSpec.trace) - { + public Integer getMaxSession() { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("getMaxSession()"); } - if (maxSession == null) - { + if (maxSession == null) { return DEFAULT_MAX_SESSION; } @@ -656,10 +579,8 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @param value The value */ - public void setMaxSession(final Integer value) - { - if (ActiveMQActivationSpec.trace) - { + public void setMaxSession(final Integer value) { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("setMaxSession(" + value + ")"); } @@ -671,10 +592,8 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @return The value */ - public Integer getTransactionTimeout() - { - if (ActiveMQActivationSpec.trace) - { + public Integer getTransactionTimeout() { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("getTransactionTimeout()"); } @@ -686,81 +605,63 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @param value The value */ - public void setTransactionTimeout(final Integer value) - { - if (ActiveMQActivationSpec.trace) - { + public void setTransactionTimeout(final Integer value) { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("setTransactionTimeout(" + value + ")"); } transactionTimeout = value; } - public Boolean isUseLocalTx() - { - if (localTx == null) - { + public Boolean isUseLocalTx() { + if (localTx == null) { return ra.getUseLocalTx(); } - else - { + else { return localTx; } } - public void setUseLocalTx(final Boolean localTx) - { + public void setUseLocalTx(final Boolean localTx) { this.localTx = localTx; } - public int getSetupAttempts() - { - if (ActiveMQActivationSpec.trace) - { + public int getSetupAttempts() { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("getSetupAttempts()"); } - if (setupAttempts == null) - { + if (setupAttempts == null) { return ra.getSetupAttempts(); } - else - { + else { return setupAttempts; } } - public void setSetupAttempts(int setupAttempts) - { - if (ActiveMQActivationSpec.trace) - { + public void setSetupAttempts(int setupAttempts) { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("setSetupAttempts(" + setupAttempts + ")"); } this.setupAttempts = setupAttempts; } - public long getSetupInterval() - { - if (ActiveMQActivationSpec.trace) - { + public long getSetupInterval() { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("getSetupInterval()"); } - if (setupInterval == null) - { + if (setupInterval == null) { return ra.getSetupInterval(); } - else - { + else { return setupInterval; } } - public void setSetupInterval(long setupInterval) - { - if (ActiveMQActivationSpec.trace) - { + public void setSetupInterval(long setupInterval) { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("setSetupInterval(" + setupInterval + ")"); } @@ -772,47 +673,38 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * * @throws InvalidPropertyException Thrown if a validation exception occurs */ - public void validate() throws InvalidPropertyException - { - if (ActiveMQActivationSpec.trace) - { + public void validate() throws InvalidPropertyException { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("validate()"); } List errorMessages = new ArrayList(); List propsNotSet = new ArrayList(); - try - { - if (destination == null || destination.trim().equals("")) - { + try { + if (destination == null || destination.trim().equals("")) { propsNotSet.add(new PropertyDescriptor("destination", ActiveMQActivationSpec.class)); errorMessages.add("Destination is mandatory."); } - if (destinationType != null && !Topic.class.getName().equals(destinationType) && !Queue.class.getName().equals(destinationType)) - { + if (destinationType != null && !Topic.class.getName().equals(destinationType) && !Queue.class.getName().equals(destinationType)) { propsNotSet.add(new PropertyDescriptor("destinationType", ActiveMQActivationSpec.class)); errorMessages.add("If set, the destinationType must be either 'javax.jms.Topic' or 'javax.jms.Queue'."); } - if ((destinationType == null || destinationType.length() == 0 || Topic.class.getName().equals(destinationType)) && isSubscriptionDurable() && (subscriptionName == null || subscriptionName.length() == 0)) - { + if ((destinationType == null || destinationType.length() == 0 || Topic.class.getName().equals(destinationType)) && isSubscriptionDurable() && (subscriptionName == null || subscriptionName.length() == 0)) { propsNotSet.add(new PropertyDescriptor("subscriptionName", ActiveMQActivationSpec.class)); errorMessages.add("If subscription is durable then subscription name must be specified."); } } - catch (IntrospectionException e) - { + catch (IntrospectionException e) { e.printStackTrace(); } - if (propsNotSet.size() > 0) - { + if (propsNotSet.size() > 0) { StringBuffer b = new StringBuffer(); b.append("Invalid settings:"); - for (Iterator iter = errorMessages.iterator(); iter.hasNext();) - { + for (Iterator iter = errorMessages.iterator(); iter.hasNext(); ) { b.append(" "); b.append(iter.next()); } @@ -823,15 +715,12 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen } } - public String getConnectorClassName() - { + public String getConnectorClassName() { return strConnectorClassName; } - public void setConnectorClassName(final String connectorClassName) - { - if (ActiveMQActivationSpec.trace) - { + public void setConnectorClassName(final String connectorClassName) { + if (ActiveMQActivationSpec.trace) { ActiveMQRALogger.LOGGER.trace("setConnectorClassName(" + connectorClassName + ")"); } @@ -843,13 +732,11 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen /** * @return the connectionParameters */ - public String getConnectionParameters() - { + public String getConnectionParameters() { return strConnectionParameters; } - public void setConnectionParameters(final String configuration) - { + public void setConnectionParameters(final String configuration) { strConnectionParameters = configuration; setParsedConnectionParameters(ActiveMQRaUtils.parseConfig(configuration)); } @@ -860,31 +747,26 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen * @return The value */ @Override - public String toString() - { + public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(ActiveMQActivationSpec.class.getName()).append('('); buffer.append("ra=").append(ra); - if (messageSelector != null) - { + if (messageSelector != null) { buffer.append(" connectionFactoryLookup=").append(connectionFactoryLookup); } buffer.append(" destination=").append(destination); buffer.append(" destinationType=").append(destinationType); - if (messageSelector != null) - { + if (messageSelector != null) { buffer.append(" selector=").append(messageSelector); } buffer.append(" ack=").append(getAcknowledgeMode()); buffer.append(" durable=").append(subscriptionDurability); buffer.append(" clientID=").append(getClientID()); - if (subscriptionName != null) - { + if (subscriptionName != null) { buffer.append(" subscription=").append(subscriptionName); } buffer.append(" user=").append(user); - if (password != null) - { + if (password != null) { buffer.append(" password=").append("****"); } buffer.append(" maxSession=").append(maxSession); @@ -893,52 +775,40 @@ public class ActiveMQActivationSpec extends ConnectionFactoryProperties implemen } // here for backwards compatibilty - public void setUseDLQ(final boolean b) - { + public void setUseDLQ(final boolean b) { } - public void setDLQJNDIName(final String name) - { + public void setDLQJNDIName(final String name) { } - public void setDLQHandler(final String handler) - { + public void setDLQHandler(final String handler) { } - public void setDLQMaxResent(final int maxResent) - { + public void setDLQMaxResent(final int maxResent) { } - public void setProviderAdapterJNDI(final String jndi) - { + public void setProviderAdapterJNDI(final String jndi) { } /** * @param keepAlive the keepAlive to set */ - public void setKeepAlive(boolean keepAlive) - { + public void setKeepAlive(boolean keepAlive) { } /** * @param keepAliveMillis the keepAliveMillis to set */ - public void setKeepAliveMillis(long keepAliveMillis) - { + public void setKeepAliveMillis(long keepAliveMillis) { } - - public void setReconnectInterval(long interval) - { + public void setReconnectInterval(long interval) { } - public void setMinSession(final Integer value) - { + public void setMinSession(final Integer value) { } - public void setMaxMessages(final Integer value) - { + public void setMaxMessages(final Integer value) { } - } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/inflow/ActiveMQMessageHandler.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/inflow/ActiveMQMessageHandler.java index 905b0decbf..149eea2e12 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/inflow/ActiveMQMessageHandler.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/inflow/ActiveMQMessageHandler.java @@ -48,8 +48,8 @@ import org.apache.activemq.artemis.utils.VersionLoader; /** * The message handler */ -public class ActiveMQMessageHandler implements MessageHandler -{ +public class ActiveMQMessageHandler implements MessageHandler { + /** * Trace enabled */ @@ -84,8 +84,7 @@ public class ActiveMQMessageHandler implements MessageHandler final TransactionManager tm, final ClientSessionInternal session, final ClientSessionFactory cf, - final int sessionNr) - { + final int sessionNr) { this.activation = activation; this.session = session; this.cf = cf; @@ -93,10 +92,8 @@ public class ActiveMQMessageHandler implements MessageHandler this.tm = tm; } - public void setup() throws Exception - { - if (ActiveMQMessageHandler.trace) - { + public void setup() throws Exception { + if (ActiveMQMessageHandler.trace) { ActiveMQRALogger.LOGGER.trace("setup()"); } @@ -105,50 +102,39 @@ public class ActiveMQMessageHandler implements MessageHandler // Create the message consumer SimpleString selectorString = selector == null || selector.trim().equals("") ? null : new SimpleString(selector); - if (activation.isTopic() && spec.isSubscriptionDurable()) - { - SimpleString queueName = new SimpleString(ActiveMQDestination.createQueueNameForDurableSubscription(true, - spec.getClientID(), - spec.getSubscriptionName())); + if (activation.isTopic() && spec.isSubscriptionDurable()) { + SimpleString queueName = new SimpleString(ActiveMQDestination.createQueueNameForDurableSubscription(true, spec.getClientID(), spec.getSubscriptionName())); QueueQuery subResponse = session.queueQuery(queueName); - if (!subResponse.isExists()) - { + if (!subResponse.isExists()) { session.createQueue(activation.getAddress(), queueName, selectorString, true); } - else - { + else { // The check for already exists should be done only at the first session // As a deployed MDB could set up multiple instances in order to process messages in parallel. - if (sessionNr == 0 && subResponse.getConsumerCount() > 0) - { - if (!spec.isShareSubscriptions()) - { + if (sessionNr == 0 && subResponse.getConsumerCount() > 0) { + if (!spec.isShareSubscriptions()) { throw new javax.jms.IllegalStateException("Cannot create a subscriber on the durable subscription since it already has subscriber(s)"); } - else if (ActiveMQRALogger.LOGGER.isDebugEnabled()) - { + else if (ActiveMQRALogger.LOGGER.isDebugEnabled()) { ActiveMQRALogger.LOGGER.debug("the mdb on destination " + queueName + " already had " + - subResponse.getConsumerCount() + - " consumers but the MDB is configured to share subscriptions, so no exceptions are thrown"); + subResponse.getConsumerCount() + + " consumers but the MDB is configured to share subscriptions, so no exceptions are thrown"); } } SimpleString oldFilterString = subResponse.getFilterString(); boolean selectorChanged = selector == null && oldFilterString != null || - oldFilterString == null && - selector != null || - (oldFilterString != null && selector != null && !oldFilterString.toString() - .equals(selector)); + oldFilterString == null && selector != null || + (oldFilterString != null && selector != null && !oldFilterString.toString().equals(selector)); SimpleString oldTopicName = subResponse.getAddress(); boolean topicChanged = !oldTopicName.equals(activation.getAddress()); - if (selectorChanged || topicChanged) - { + if (selectorChanged || topicChanged) { // Delete the old durable sub session.deleteQueue(queueName); @@ -158,31 +144,25 @@ public class ActiveMQMessageHandler implements MessageHandler } consumer = (ClientConsumerInternal) session.createConsumer(queueName, null, false); } - else - { + else { SimpleString tempQueueName; - if (activation.isTopic()) - { - if (activation.getTopicTemporaryQueue() == null) - { + if (activation.isTopic()) { + if (activation.getTopicTemporaryQueue() == null) { tempQueueName = new SimpleString(UUID.randomUUID().toString()); session.createTemporaryQueue(activation.getAddress(), tempQueueName, selectorString); activation.setTopicTemporaryQueue(tempQueueName); } - else - { + else { tempQueueName = activation.getTopicTemporaryQueue(); QueueQuery queueQuery = session.queueQuery(tempQueueName); - if (!queueQuery.isExists()) - { + if (!queueQuery.isExists()) { // this is because we could be using remote servers (in cluster maybe) // and the queue wasn't created on that node yet. session.createTemporaryQueue(activation.getAddress(), tempQueueName, selectorString); } } } - else - { + else { tempQueueName = activation.getAddress(); } consumer = (ClientConsumerInternal) session.createConsumer(tempQueueName, selectorString); @@ -192,8 +172,7 @@ public class ActiveMQMessageHandler implements MessageHandler MessageEndpointFactory endpointFactory = activation.getMessageEndpointFactory(); useLocalTx = !activation.isDeliveryTransacted() && activation.getActivationSpec().isUseLocalTx(); transacted = activation.isDeliveryTransacted(); - if (activation.isDeliveryTransacted() && !activation.getActivationSpec().isUseLocalTx()) - { + if (activation.isDeliveryTransacted() && !activation.getActivationSpec().isUseLocalTx()) { Map xaResourceProperties = new HashMap(); xaResourceProperties.put(ActiveMQXAResourceWrapper.ACTIVEMQ_JNDI_NAME, ((ActiveMQResourceAdapter) spec.getResourceAdapter()).getJndiName()); xaResourceProperties.put(ActiveMQXAResourceWrapper.ACTIVEMQ_NODE_ID, ((ClientSessionFactoryInternal) cf).getLiveNodeId()); @@ -204,30 +183,24 @@ public class ActiveMQMessageHandler implements MessageHandler endpoint = endpointFactory.createEndpoint(xaResource); useXA = true; } - else - { + else { endpoint = endpointFactory.createEndpoint(null); useXA = false; } consumer.setMessageHandler(this); } - XAResource getXAResource() - { + XAResource getXAResource() { return useXA ? session : null; } - public Thread interruptConsumer(FutureLatch future) - { - try - { - if (consumer != null) - { + public Thread interruptConsumer(FutureLatch future) { + try { + if (consumer != null) { return consumer.prepareForClose(future); } } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQRALogger.LOGGER.errorInterruptingHandler(endpoint.toString(), consumer.toString(), e); } return null; @@ -236,86 +209,67 @@ public class ActiveMQMessageHandler implements MessageHandler /** * Stop the handler */ - public void teardown() - { - if (ActiveMQMessageHandler.trace) - { + public void teardown() { + if (ActiveMQMessageHandler.trace) { ActiveMQRALogger.LOGGER.trace("teardown()"); } - try - { - if (endpoint != null) - { + try { + if (endpoint != null) { endpoint.release(); endpoint = null; } } - catch (Throwable t) - { + catch (Throwable t) { ActiveMQRALogger.LOGGER.debug("Error releasing endpoint " + endpoint, t); } - try - { + try { consumer.close(); - if (activation.getTopicTemporaryQueue() != null) - { + if (activation.getTopicTemporaryQueue() != null) { // We need to delete temporary topics when the activation is stopped or messages will build up on the server SimpleString tmpQueue = activation.getTopicTemporaryQueue(); QueueQuery subResponse = session.queueQuery(tmpQueue); - if (subResponse.getConsumerCount() == 0) - { + if (subResponse.getConsumerCount() == 0) { // This is optional really, since we now use temporaryQueues, we could simply ignore this // and the server temporary queue would remove this as soon as the queue was removed session.deleteQueue(tmpQueue); } } } - catch (Throwable t) - { + catch (Throwable t) { ActiveMQRALogger.LOGGER.debug("Error closing core-queue consumer", t); } - try - { - if (session != null) - { + try { + if (session != null) { session.close(); } } - catch (Throwable t) - { + catch (Throwable t) { ActiveMQRALogger.LOGGER.debug("Error releasing session " + session, t); } - try - { - if (cf != null) - { + try { + if (cf != null) { cf.close(); } } - catch (Throwable t) - { + catch (Throwable t) { ActiveMQRALogger.LOGGER.debug("Error releasing session factory " + session, t); } } - public void onMessage(final ClientMessage message) - { - if (ActiveMQMessageHandler.trace) - { + public void onMessage(final ClientMessage message) { + if (ActiveMQMessageHandler.trace) { ActiveMQRALogger.LOGGER.trace("onMessage(" + message + ")"); } ActiveMQMessage msg = ActiveMQMessage.createMessage(message, session); boolean beforeDelivery = false; - try - { - if (activation.getActivationSpec().getTransactionTimeout() > 0 && tm != null) - { + try { + if (activation.getActivationSpec().getTransactionTimeout() > 0 && tm != null) { tm.setTransactionTimeout(activation.getActivationSpec().getTransactionTimeout()); } endpoint.beforeDelivery(ActiveMQActivation.ONMESSAGE); @@ -324,66 +278,52 @@ public class ActiveMQMessageHandler implements MessageHandler //In the transacted case the message must be acked *before* onMessage is called - if (transacted) - { + if (transacted) { message.acknowledge(); } ((MessageListener) endpoint).onMessage(msg); - if (!transacted) - { + if (!transacted) { message.acknowledge(); } - try - { + try { endpoint.afterDelivery(); } - catch (ResourceException e) - { + catch (ResourceException e) { ActiveMQRALogger.LOGGER.unableToCallAfterDelivery(e); return; } - if (useLocalTx) - { + if (useLocalTx) { session.commit(); } - if (trace) - { + if (trace) { ActiveMQRALogger.LOGGER.trace("finished onMessage on " + message); } } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQRALogger.LOGGER.errorDeliveringMessage(e); // we need to call before/afterDelivery as a pair - if (beforeDelivery) - { - if (useXA && tm != null) - { + if (beforeDelivery) { + if (useXA && tm != null) { // This is the job for the container, // however if the container throws an exception because of some other errors, // there are situations where the container is not setting the rollback only // this is to avoid a scenario where afterDelivery would kick in - try - { + try { Transaction tx = tm.getTransaction(); - if (tx != null) - { + if (tx != null) { tx.setRollbackOnly(); } } - catch (Exception e1) - { + catch (Exception e1) { ActiveMQRALogger.LOGGER.warn("unnable to clear the transaction", e1); - try - { + try { session.rollback(); } - catch (ActiveMQException e2) - { + catch (ActiveMQException e2) { ActiveMQRALogger.LOGGER.warn("Unable to rollback", e2); return; } @@ -391,47 +331,37 @@ public class ActiveMQMessageHandler implements MessageHandler } MessageEndpoint endToUse = endpoint; - try - { + try { // to avoid a NPE that would happen while the RA is in tearDown - if (endToUse != null) - { + if (endToUse != null) { endToUse.afterDelivery(); } } - catch (ResourceException e1) - { + catch (ResourceException e1) { ActiveMQRALogger.LOGGER.unableToCallAfterDelivery(e1); } } - if (useLocalTx || !activation.isDeliveryTransacted()) - { - try - { + if (useLocalTx || !activation.isDeliveryTransacted()) { + try { session.rollback(true); } - catch (ActiveMQException e1) - { + catch (ActiveMQException e1) { ActiveMQRALogger.LOGGER.unableToRollbackTX(); } } } - finally - { - try - { + finally { + try { session.resetIfNeeded(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { ActiveMQRALogger.LOGGER.unableToResetSession(); } } } - public void start() throws ActiveMQException - { + public void start() throws ActiveMQException { session.start(); } } diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/recovery/RecoveryManager.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/recovery/RecoveryManager.java index addb7b37d3..6fd11d4614 100644 --- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/recovery/RecoveryManager.java +++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/recovery/RecoveryManager.java @@ -26,100 +26,78 @@ import org.apache.activemq.artemis.utils.ConcurrentHashSet; import java.util.ServiceLoader; import java.util.Set; -public final class RecoveryManager -{ +public final class RecoveryManager { + private ActiveMQRegistry registry; - private static final String RESOURCE_RECOVERY_CLASS_NAMES = "org.jboss.as.messaging.jms.AS7RecoveryRegistry;" - + "org.jboss.as.integration.activemq.recovery.AS5RecoveryRegistry"; + private static final String RESOURCE_RECOVERY_CLASS_NAMES = "org.jboss.as.messaging.jms.AS7RecoveryRegistry;" + "org.jboss.as.integration.activemq.recovery.AS5RecoveryRegistry"; private final Set resources = new ConcurrentHashSet(); - public void start(final boolean useAutoRecovery) - { - if (useAutoRecovery) - { + public void start(final boolean useAutoRecovery) { + if (useAutoRecovery) { locateRecoveryRegistry(); } - else - { + else { registry = null; } } - public XARecoveryConfig register(ActiveMQConnectionFactory factory, String userName, String password) - { + public XARecoveryConfig register(ActiveMQConnectionFactory factory, String userName, String password) { ActiveMQRALogger.LOGGER.debug("registering recovery for factory : " + factory); XARecoveryConfig config = XARecoveryConfig.newConfig(factory, userName, password); resources.add(config); - if (registry != null) - { + if (registry != null) { registry.register(config); } return config; } - - public void unRegister(XARecoveryConfig resourceRecovery) - { - if (registry != null) - { + public void unRegister(XARecoveryConfig resourceRecovery) { + if (registry != null) { registry.unRegister(resourceRecovery); } } - public void stop() - { - if (registry != null) - { - for (XARecoveryConfig recovery : resources) - { + public void stop() { + if (registry != null) { + for (XARecoveryConfig recovery : resources) { registry.unRegister(recovery); } registry.stop(); } - resources.clear(); } - private void locateRecoveryRegistry() - { + private void locateRecoveryRegistry() { String[] locatorClasses = RESOURCE_RECOVERY_CLASS_NAMES.split(";"); - for (String locatorClasse : locatorClasses) - { - try - { + for (String locatorClasse : locatorClasses) { + try { ServiceLoader sl = ServiceLoader.load(ActiveMQRegistry.class); - if (sl.iterator().hasNext()) - { + if (sl.iterator().hasNext()) { registry = sl.iterator().next(); } - else - { + else { registry = ActiveMQRegistryImpl.getInstance(); } } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQRALogger.LOGGER.debug("unable to load recovery registry " + locatorClasse, e); } - if (registry != null) - { + if (registry != null) { break; } } - if (registry != null) - { + if (registry != null) { ActiveMQRALogger.LOGGER.debug("Recovery Registry located = " + registry); } } - public Set getResources() - { + public Set getResources() { return resources; } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/ActiveMQ.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/ActiveMQ.java index d637f1f051..ad8656fa9e 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/ActiveMQ.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/ActiveMQ.java @@ -32,8 +32,7 @@ import org.jboss.resteasy.core.Headers; import org.jboss.resteasy.spi.ResteasyProviderFactory; import org.jboss.resteasy.util.GenericType; -public class ActiveMQ -{ +public class ActiveMQ { /** * Sets the message body to a serialized @@ -42,8 +41,7 @@ public class ActiveMQ * @param message * @param object */ - public static void setEntity(ClientMessage message, Serializable object) - { + public static void setEntity(ClientMessage message, Serializable object) { setEntity(message, object, null); } @@ -55,12 +53,11 @@ public class ActiveMQ * @param object * @param contentType HTTP Content-Type header */ - public static void setEntity(ClientMessage message, Serializable object, String contentType) - { - if (contentType != null) message.putStringProperty(HttpHeaderProperty.CONTENT_TYPE, contentType); + public static void setEntity(ClientMessage message, Serializable object, String contentType) { + if (contentType != null) + message.putStringProperty(HttpHeaderProperty.CONTENT_TYPE, contentType); byte[] data; - try - { + try { ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); ObjectOutputStream oos = new ObjectOutputStream(baos); @@ -71,8 +68,7 @@ public class ActiveMQ data = baos.toByteArray(); } - catch (IOException e) - { + catch (IOException e) { throw new RuntimeException(e); } @@ -81,12 +77,10 @@ public class ActiveMQ } - public static void setHttpHeader(ClientMessage message, String name, String value) - { + public static void setHttpHeader(ClientMessage message, String name, String value) { message.putStringProperty(HttpHeaderProperty.toPropertyName(name), value); } - /** * Get an HTTP header value from a JMS Message * @@ -94,8 +88,7 @@ public class ActiveMQ * @param name * @return the HTTP header String */ - public static String getHttpHeader(ClientMessage message, String name) - { + public static String getHttpHeader(ClientMessage message, String name) { return message.getStringProperty(HttpHeaderProperty.toPropertyName(name)); } @@ -106,8 +99,7 @@ public class ActiveMQ * @param type * @return */ - public static T getEntity(ClientMessage message, Class type) - { + public static T getEntity(ClientMessage message, Class type) { return getEntity(message, type, null, ResteasyProviderFactory.getInstance()); } @@ -119,8 +111,7 @@ public class ActiveMQ * @param factory * @return */ - public static T getEntity(ClientMessage message, Class type, ResteasyProviderFactory factory) - { + public static T getEntity(ClientMessage message, Class type, ResteasyProviderFactory factory) { return getEntity(message, type, null, factory); } @@ -134,46 +125,42 @@ public class ActiveMQ * @throws UnknownMediaType * @throws UnmarshalException */ - public static T getEntity(ClientMessage message, GenericType type, ResteasyProviderFactory factory) throws UnknownMediaType, UnmarshalException - { + public static T getEntity(ClientMessage message, + GenericType type, + ResteasyProviderFactory factory) throws UnknownMediaType, UnmarshalException { return getEntity(message, type.getType(), type.getGenericType(), factory); } - public static T getEntity(ClientMessage msg, Class type, Type genericType, ResteasyProviderFactory factory) - { + public static T getEntity(ClientMessage msg, Class type, Type genericType, ResteasyProviderFactory factory) { int size = msg.getBodySize(); - if (size <= 0) return null; + if (size <= 0) + return null; byte[] body = new byte[size]; msg.getBodyBuffer().readBytes(body); - String contentType = msg.getStringProperty(HttpHeaderProperty.CONTENT_TYPE); - if (contentType == null) - { + if (contentType == null) { throw new UnknownMediaType("Message did not have a Content-Type header cannot extract entity"); } MediaType ct = MediaType.valueOf(contentType); MessageBodyReader reader = factory.getMessageBodyReader(type, genericType, null, ct); - if (reader == null) - { + 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 - { + try { return reader.readFrom(type, genericType, null, ct, new Headers(), new ByteArrayInputStream(body)); } - catch (IOException e) - { + catch (IOException e) { throw new RuntimeException(e); } - finally - { + finally { ResteasyProviderFactory.popContextData(Providers.class); - if (current != null) ResteasyProviderFactory.pushContext(Providers.class, current); + if (current != null) + ResteasyProviderFactory.pushContext(Providers.class, current); } } @@ -183,8 +170,7 @@ public class ActiveMQ * @param msg * @return */ - public static boolean isHttpMessage(ClientMessage msg) - { + public static boolean isHttpMessage(ClientMessage msg) { Boolean aBoolean = msg.getBooleanProperty(HttpMessageHelper.POSTED_AS_HTTP_MESSAGE); return aBoolean != null && aBoolean.booleanValue() == true; } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/ActiveMQRestBundle.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/ActiveMQRestBundle.java index 75dea96572..f65f0a8d9e 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/ActiveMQRestBundle.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/ActiveMQRestBundle.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.rest; - import org.jboss.logging.annotations.MessageBundle; /** @@ -27,6 +26,6 @@ import org.jboss.logging.annotations.MessageBundle; * so 199000 to 199999 */ @MessageBundle(projectCode = "AMQ") -public class ActiveMQRestBundle -{ +public class ActiveMQRestBundle { + } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/ActiveMQRestLogger.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/ActiveMQRestLogger.java index 227ab1edab..524a9fd798 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/ActiveMQRestLogger.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/ActiveMQRestLogger.java @@ -40,8 +40,8 @@ import org.jboss.logging.annotations.MessageLogger; * so an INFO message would be 191000 to 191999 */ @MessageLogger(projectCode = "AMQ") -public interface ActiveMQRestLogger extends BasicLogger -{ +public interface ActiveMQRestLogger extends BasicLogger { + ActiveMQRestLogger LOGGER = Logger.getMessageLogger(ActiveMQRestLogger.class, ActiveMQRestLogger.class.getPackage().getName()); @LogMessage(level = Logger.Level.INFO) diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/HttpHeaderProperty.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/HttpHeaderProperty.java index 9f26e5fb12..f8ae43c896 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/HttpHeaderProperty.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/HttpHeaderProperty.java @@ -16,8 +16,8 @@ */ package org.apache.activemq.artemis.rest; -public class HttpHeaderProperty -{ +public class HttpHeaderProperty { + public static final String CONTENT_TYPE = "http_content$type"; /** @@ -28,8 +28,7 @@ public class HttpHeaderProperty * @param httpHeader * @return */ - public static String toPropertyName(String httpHeader) - { + public static String toPropertyName(String httpHeader) { httpHeader = httpHeader.replace('-', '$'); return "http_" + httpHeader.toLowerCase(); } @@ -40,9 +39,9 @@ public class HttpHeaderProperty * @param name * @return null if property name isn't an HTTP header name. */ - public static String fromPropertyName(String name) - { - if (!name.startsWith("http_")) return null; + public static String fromPropertyName(String name) { + if (!name.startsWith("http_")) + return null; return name.substring("http_".length()).replace('$', '-'); } } \ No newline at end of file diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/Jms.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/Jms.java index 9be8261618..5f25d48b57 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/Jms.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/Jms.java @@ -31,8 +31,8 @@ import javax.ws.rs.ext.Providers; import java.io.ByteArrayInputStream; import java.lang.reflect.Type; -public class Jms -{ +public class Jms { + /** * Set a JMS Message property to the value of an HTTP header * @@ -40,32 +40,27 @@ public class Jms * @param name * @param value */ - public static void setHttpHeader(Message message, String name, String value) - { - try - { + public static void setHttpHeader(Message message, String name, String value) { + try { message.setStringProperty(HttpHeaderProperty.toPropertyName(name), value); } - catch (JMSException e) - { + 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 - { + public static String getHttpHeader(Message message, String name) { + try { return message.getStringProperty(HttpHeaderProperty.toPropertyName(name)); } - catch (JMSException e) - { + catch (JMSException e) { throw new RuntimeException(e); } } @@ -78,8 +73,7 @@ public class Jms * @param * @return */ - public static T getEntity(Message message, Class type) - { + public static T getEntity(Message message, Class type) { return getEntity(message, type, null, ResteasyProviderFactory.getInstance()); } @@ -92,8 +86,7 @@ public class Jms * @param * @return */ - public static T getEntity(Message message, Class type, ResteasyProviderFactory factory) - { + public static T getEntity(Message message, Class type, ResteasyProviderFactory factory) { return getEntity(message, type, null, factory); } @@ -108,20 +101,18 @@ public class Jms * @throws UnknownMediaType * @throws UnmarshalException */ - public static T getEntity(Message message, GenericType type, ResteasyProviderFactory factory) throws UnknownMediaType - { + public static T getEntity(Message message, + GenericType type, + ResteasyProviderFactory factory) throws UnknownMediaType { return getEntity(message, type.getType(), type.getGenericType(), factory); } - public static boolean isHttpMessage(Message message) - { - try - { + public static boolean isHttpMessage(Message message) { + try { Boolean aBoolean = message.getBooleanProperty(HttpMessageHelper.POSTED_AS_HTTP_MESSAGE); return aBoolean != null && aBoolean.booleanValue() == true; } - catch (JMSException e) - { + catch (JMSException e) { return false; } } @@ -138,26 +129,23 @@ public class Jms * @throws UnknownMediaType * @throws UnmarshalException */ - public static T getEntity(Message message, Class type, Type genericType, ResteasyProviderFactory factory) throws UnknownMediaType - { - if (!isHttpMessage(message)) - { - try - { + public static T getEntity(Message message, + Class type, + Type genericType, + ResteasyProviderFactory factory) throws UnknownMediaType { + if (!isHttpMessage(message)) { + try { return (T) ((ObjectMessage) message).getObject(); } - catch (JMSException e) - { + catch (JMSException e) { throw new RuntimeException(e); } } BytesMessage bytesMessage = (BytesMessage) message; - try - { + try { long size = bytesMessage.getBodyLength(); - if (size <= 0) - { + if (size <= 0) { return null; } @@ -165,31 +153,27 @@ public class Jms bytesMessage.readBytes(body); String contentType = message.getStringProperty(HttpHeaderProperty.CONTENT_TYPE); - if (contentType == null) - { + if (contentType == null) { throw new UnknownMediaType("Message did not have a Content-Type header cannot extract entity"); } MediaType ct = MediaType.valueOf(contentType); MessageBodyReader reader = factory.getMessageBodyReader(type, genericType, null, ct); - if (reader == null) - { + 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 - { + try { return reader.readFrom(type, genericType, null, ct, new Headers(), new ByteArrayInputStream(body)); } - finally - { + finally { ResteasyProviderFactory.popContextData(Providers.class); - if (current != null) ResteasyProviderFactory.pushContext(Providers.class, current); + if (current != null) + ResteasyProviderFactory.pushContext(Providers.class, current); } } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/MessageServiceConfiguration.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/MessageServiceConfiguration.java index 1c49275d6a..ff9e8e752e 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/MessageServiceConfiguration.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/MessageServiceConfiguration.java @@ -20,8 +20,8 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "rest-messaging") -public class MessageServiceConfiguration -{ +public class MessageServiceConfiguration { + private int producerSessionPoolSize = 10; private long producerTimeToLive = -1; private int timeoutTaskInterval = 1; @@ -35,123 +35,101 @@ public class MessageServiceConfiguration private boolean useLinkHeaders = false; @XmlElement(name = "server-in-vm-id") - public String getInVmId() - { + public String getInVmId() { return inVmId; } - public void setInVmId(String inVmId) - { + public void setInVmId(String inVmId) { this.inVmId = inVmId; } @XmlElement(name = "use-link-headers") - public boolean isUseLinkHeaders() - { + public boolean isUseLinkHeaders() { return useLinkHeaders; } - public void setUseLinkHeaders(boolean useLinkHeaders) - { + public void setUseLinkHeaders(boolean useLinkHeaders) { this.useLinkHeaders = useLinkHeaders; } @XmlElement(name = "default-durable-send") - public boolean isDefaultDurableSend() - { + public boolean isDefaultDurableSend() { return defaultDurableSend; } - public void setDefaultDurableSend(boolean defaultDurableSend) - { + public void setDefaultDurableSend(boolean defaultDurableSend) { this.defaultDurableSend = defaultDurableSend; } @XmlElement(name = "dups-ok") - public boolean isDupsOk() - { + public boolean isDupsOk() { return dupsOk; } - public void setDupsOk(boolean dupsOk) - { + public void setDupsOk(boolean dupsOk) { this.dupsOk = dupsOk; } @XmlElement(name = "topic-push-store-dir") - public String getTopicPushStoreDirectory() - { + public String getTopicPushStoreDirectory() { return topicPushStoreDirectory; } - public void setTopicPushStoreDirectory(String topicPushStoreDirectory) - { + public void setTopicPushStoreDirectory(String topicPushStoreDirectory) { this.topicPushStoreDirectory = topicPushStoreDirectory; } @XmlElement(name = "queue-push-store-dir") - public String getQueuePushStoreDirectory() - { + public String getQueuePushStoreDirectory() { return queuePushStoreDirectory; } - public void setQueuePushStoreDirectory(String queuePushStoreDirectory) - { + public void setQueuePushStoreDirectory(String queuePushStoreDirectory) { this.queuePushStoreDirectory = queuePushStoreDirectory; } @XmlElement(name = "producer-time-to-live") - public long getProducerTimeToLive() - { + public long getProducerTimeToLive() { return producerTimeToLive; } - public void setProducerTimeToLive(long producerTimeToLive) - { + public void setProducerTimeToLive(long producerTimeToLive) { this.producerTimeToLive = producerTimeToLive; } @XmlElement(name = "producer-session-pool-size") - public int getProducerSessionPoolSize() - { + public int getProducerSessionPoolSize() { return producerSessionPoolSize; } - public void setProducerSessionPoolSize(int producerSessionPoolSize) - { + public void setProducerSessionPoolSize(int producerSessionPoolSize) { this.producerSessionPoolSize = producerSessionPoolSize; } @XmlElement(name = "session-timeout-task-interval") - public int getTimeoutTaskInterval() - { + public int getTimeoutTaskInterval() { return timeoutTaskInterval; } - public void setTimeoutTaskInterval(int timeoutTaskInterval) - { + public void setTimeoutTaskInterval(int timeoutTaskInterval) { this.timeoutTaskInterval = timeoutTaskInterval; } @XmlElement(name = "consumer-session-timeout-seconds") - public int getConsumerSessionTimeoutSeconds() - { + public int getConsumerSessionTimeoutSeconds() { return consumerSessionTimeoutSeconds; } - public void setConsumerSessionTimeoutSeconds(int consumerSessionTimeoutSeconds) - { + public void setConsumerSessionTimeoutSeconds(int consumerSessionTimeoutSeconds) { this.consumerSessionTimeoutSeconds = consumerSessionTimeoutSeconds; } @XmlElement(name = "consumer-window-size") - public int getConsumerWindowSize() - { + public int getConsumerWindowSize() { return consumerWindowSize; } - public void setConsumerWindowSize(int consumerWindowSize) - { + public void setConsumerWindowSize(int consumerWindowSize) { this.consumerWindowSize = consumerWindowSize; } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/MessageServiceManager.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/MessageServiceManager.java index 6b21ca3b88..1bef82c51d 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/MessageServiceManager.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/MessageServiceManager.java @@ -42,8 +42,8 @@ import org.apache.activemq.artemis.rest.util.TimeoutTask; import org.apache.activemq.artemis.spi.core.naming.BindingRegistry; import org.apache.activemq.artemis.utils.XMLUtil; -public class MessageServiceManager -{ +public class MessageServiceManager { + protected ExecutorService threadPool; protected QueueServiceManager queueManager = new QueueServiceManager(); protected TopicServiceManager topicManager = new TopicServiceManager(); @@ -54,85 +54,67 @@ public class MessageServiceManager protected String configResourcePath; protected BindingRegistry registry; - public BindingRegistry getRegistry() - { + public BindingRegistry getRegistry() { return registry; } - public void setRegistry(BindingRegistry registry) - { + public void setRegistry(BindingRegistry registry) { this.registry = registry; } - public int getTimeoutTaskInterval() - { + public int getTimeoutTaskInterval() { return timeoutTaskInterval; } - public void setTimeoutTaskInterval(int timeoutTaskInterval) - { + public void setTimeoutTaskInterval(int timeoutTaskInterval) { this.timeoutTaskInterval = timeoutTaskInterval; - if (timeoutTask != null) - { + if (timeoutTask != null) { timeoutTask.setInterval(timeoutTaskInterval); } } - public ExecutorService getThreadPool() - { + public ExecutorService getThreadPool() { return threadPool; } - public void setThreadPool(ExecutorService threadPool) - { + public void setThreadPool(ExecutorService threadPool) { this.threadPool = threadPool; } - public QueueServiceManager getQueueManager() - { + public QueueServiceManager getQueueManager() { return queueManager; } - public TopicServiceManager getTopicManager() - { + public TopicServiceManager getTopicManager() { return topicManager; } - public MessageServiceConfiguration getConfiguration() - { + public MessageServiceConfiguration getConfiguration() { return configuration; } - public String getConfigResourcePath() - { + public String getConfigResourcePath() { return configResourcePath; } - public void setConfigResourcePath(String configResourcePath) - { + public void setConfigResourcePath(String configResourcePath) { this.configResourcePath = configResourcePath; } - public void setConfiguration(MessageServiceConfiguration configuration) - { + public void setConfiguration(MessageServiceConfiguration configuration) { this.configuration = configuration; this.configSet = true; } - public void start() throws Exception - { - if (configuration == null || configSet == false) - { - if (configResourcePath == null) - { + public void start() throws Exception { + if (configuration == null || configSet == false) { + if (configResourcePath == null) { configuration = new MessageServiceConfiguration(); } - else - { + else { URL url = getClass().getClassLoader().getResource(configResourcePath); - if (url == null) - { + if (url == null) { // The URL is outside of the classloader. Trying a pure url now url = new URL(configResourcePath); } @@ -140,11 +122,11 @@ public class MessageServiceManager Reader reader = new InputStreamReader(url.openStream()); String xml = XMLUtil.readerToString(reader); xml = XMLUtil.replaceSystemProps(xml); - configuration = (MessageServiceConfiguration) jaxb.createUnmarshaller().unmarshal( - new StringReader(xml)); + configuration = (MessageServiceConfiguration) jaxb.createUnmarshaller().unmarshal(new StringReader(xml)); } } - if (threadPool == null) threadPool = Executors.newCachedThreadPool(); + if (threadPool == null) + threadPool = Executors.newCachedThreadPool(); timeoutTaskInterval = configuration.getTimeoutTaskInterval(); timeoutTask = new TimeoutTask(timeoutTaskInterval); threadPool.execute(timeoutTask); @@ -157,29 +139,25 @@ public class MessageServiceManager HashMap transportConfig = new HashMap(); transportConfig.put(TransportConstants.SERVER_ID_PROP_NAME, configuration.getInVmId()); - ServerLocator consumerLocator = new ServerLocatorImpl(false, new TransportConfiguration(InVMConnectorFactory.class.getName(), transportConfig)); ActiveMQRestLogger.LOGGER.debug("Created ServerLocator: " + consumerLocator); - if (configuration.getConsumerWindowSize() != -1) - { + if (configuration.getConsumerWindowSize() != -1) { consumerLocator.setConsumerWindowSize(configuration.getConsumerWindowSize()); } ClientSessionFactory consumerSessionFactory = consumerLocator.createSessionFactory(); ActiveMQRestLogger.LOGGER.debug("Created ClientSessionFactory: " + consumerSessionFactory); - ServerLocator defaultLocator = new ServerLocatorImpl(false, new TransportConfiguration(InVMConnectorFactory.class.getName(), transportConfig)); + ServerLocator defaultLocator = new ServerLocatorImpl(false, new TransportConfiguration(InVMConnectorFactory.class.getName(), transportConfig)); ClientSessionFactory sessionFactory = defaultLocator.createSessionFactory(); LinkStrategy linkStrategy = new LinkHeaderLinkStrategy(); - if (configuration.isUseLinkHeaders()) - { + if (configuration.isUseLinkHeaders()) { linkStrategy = new LinkHeaderLinkStrategy(); } - else - { + else { linkStrategy = new CustomHeaderLinkStrategy(); } @@ -211,11 +189,12 @@ public class MessageServiceManager topicManager.start(); } - public void stop() - { - if (queueManager != null) queueManager.stop(); + public void stop() { + if (queueManager != null) + queueManager.stop(); queueManager = null; - if (topicManager != null) topicManager.stop(); + if (topicManager != null) + topicManager.stop(); topicManager = null; } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/UnknownMediaType.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/UnknownMediaType.java index 72b4f06ebf..cc4d35656b 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/UnknownMediaType.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/UnknownMediaType.java @@ -16,12 +16,11 @@ */ package org.apache.activemq.artemis.rest; -public class UnknownMediaType extends RuntimeException -{ +public class UnknownMediaType extends RuntimeException { + private static final long serialVersionUID = -1445038845165315001L; - public UnknownMediaType(String s) - { + public UnknownMediaType(String s) { super(s); } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/UnmarshalException.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/UnmarshalException.java index 4f195dcdbf..abc3f0e68c 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/UnmarshalException.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/UnmarshalException.java @@ -16,17 +16,15 @@ */ package org.apache.activemq.artemis.rest; -public class UnmarshalException extends RuntimeException -{ +public class UnmarshalException extends RuntimeException { + private static final long serialVersionUID = 3932027442263719425L; - public UnmarshalException(String s) - { + public UnmarshalException(String s) { super(s); } - public UnmarshalException(String s, Throwable throwable) - { + public UnmarshalException(String s, Throwable throwable) { super(s, throwable); } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/integration/ActiveMQBootstrapListener.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/integration/ActiveMQBootstrapListener.java index 06f46744f5..6f08dd219b 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/integration/ActiveMQBootstrapListener.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/integration/ActiveMQBootstrapListener.java @@ -22,33 +22,28 @@ import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; -public class ActiveMQBootstrapListener implements ServletContextListener -{ +public class ActiveMQBootstrapListener implements ServletContextListener { + private EmbeddedJMS jms; - public void contextInitialized(ServletContextEvent contextEvent) - { + public void contextInitialized(ServletContextEvent contextEvent) { ServletContext context = contextEvent.getServletContext(); jms = new EmbeddedJMS(); jms.setRegistry(new ServletContextBindingRegistry(context)); - try - { + try { jms.start(); } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } } - public void contextDestroyed(ServletContextEvent servletContextEvent) - { - try - { - if (jms != null) jms.stop(); + public void contextDestroyed(ServletContextEvent servletContextEvent) { + try { + if (jms != null) + jms.stop(); } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/integration/EmbeddedRestActiveMQ.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/integration/EmbeddedRestActiveMQ.java index f39e50ea2c..9ac9b06a47 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/integration/EmbeddedRestActiveMQ.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/integration/EmbeddedRestActiveMQ.java @@ -21,14 +21,13 @@ import org.jboss.resteasy.plugins.server.tjws.TJWSEmbeddedJaxrsServer; import org.apache.activemq.artemis.rest.MessageServiceManager; import org.jboss.resteasy.test.TestPortProvider; -public class EmbeddedRestActiveMQ -{ +public class EmbeddedRestActiveMQ { + protected TJWSEmbeddedJaxrsServer tjws = new TJWSEmbeddedJaxrsServer(); protected EmbeddedActiveMQ embeddedActiveMQ; protected MessageServiceManager manager = new MessageServiceManager(); - public EmbeddedRestActiveMQ() - { + public EmbeddedRestActiveMQ() { int port = TestPortProvider.getPort(); tjws.setPort(port); tjws.setRootResourcePath(""); @@ -36,33 +35,27 @@ public class EmbeddedRestActiveMQ initEmbeddedActiveMQ(); } - protected void initEmbeddedActiveMQ() - { + protected void initEmbeddedActiveMQ() { embeddedActiveMQ = new EmbeddedActiveMQ(); } - public TJWSEmbeddedJaxrsServer getTjws() - { + public TJWSEmbeddedJaxrsServer getTjws() { return tjws; } - public void setTjws(TJWSEmbeddedJaxrsServer tjws) - { + public void setTjws(TJWSEmbeddedJaxrsServer tjws) { this.tjws = tjws; } - public EmbeddedActiveMQ getEmbeddedActiveMQ() - { + public EmbeddedActiveMQ getEmbeddedActiveMQ() { return embeddedActiveMQ; } - public MessageServiceManager getManager() - { + public MessageServiceManager getManager() { return manager; } - public void start() throws Exception - { + public void start() throws Exception { embeddedActiveMQ.start(); tjws.start(); manager.start(); @@ -70,21 +63,16 @@ public class EmbeddedRestActiveMQ tjws.getDeployment().getRegistry().addSingletonResource(manager.getTopicManager().getDestination()); } - public void stop() throws Exception - { - try - { + public void stop() throws Exception { + try { tjws.stop(); } - catch (Exception e) - { + catch (Exception e) { } - try - { + try { manager.stop(); } - catch (Exception e) - { + catch (Exception e) { } embeddedActiveMQ.stop(); } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/integration/EmbeddedRestActiveMQJMS.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/integration/EmbeddedRestActiveMQJMS.java index 95813d2a5c..75fd361ef8 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/integration/EmbeddedRestActiveMQJMS.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/integration/EmbeddedRestActiveMQJMS.java @@ -19,22 +19,20 @@ package org.apache.activemq.artemis.rest.integration; import org.apache.activemq.artemis.jms.server.embedded.EmbeddedJMS; import org.apache.activemq.artemis.spi.core.naming.BindingRegistry; -public class EmbeddedRestActiveMQJMS extends EmbeddedRestActiveMQ -{ +public class EmbeddedRestActiveMQJMS extends EmbeddedRestActiveMQ { + @Override - protected void initEmbeddedActiveMQ() - { + protected void initEmbeddedActiveMQ() { embeddedActiveMQ = new EmbeddedJMS(); } - public BindingRegistry getRegistry() - { - if (embeddedActiveMQ == null) return null; + public BindingRegistry getRegistry() { + if (embeddedActiveMQ == null) + return null; return ((EmbeddedJMS) embeddedActiveMQ).getRegistry(); } - public EmbeddedJMS getEmbeddedJMS() - { + public EmbeddedJMS getEmbeddedJMS() { return (EmbeddedJMS) embeddedActiveMQ; } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/integration/RestMessagingBootstrapListener.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/integration/RestMessagingBootstrapListener.java index a216d0125a..d777435699 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/integration/RestMessagingBootstrapListener.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/integration/RestMessagingBootstrapListener.java @@ -23,41 +23,34 @@ import javax.servlet.ServletContextListener; import org.apache.activemq.artemis.rest.MessageServiceManager; import org.jboss.resteasy.spi.Registry; -public class RestMessagingBootstrapListener implements ServletContextListener -{ +public class RestMessagingBootstrapListener implements ServletContextListener { + MessageServiceManager manager; - public void contextInitialized(ServletContextEvent contextEvent) - { + public void contextInitialized(ServletContextEvent contextEvent) { ServletContext context = contextEvent.getServletContext(); String configfile = context.getInitParameter("rest.messaging.config.file"); Registry registry = (Registry) context.getAttribute(Registry.class.getName()); - if (registry == null) - { + if (registry == null) { throw new RuntimeException("You must install RESTEasy as a Bootstrap Listener and it must be listed before this class"); } manager = new MessageServiceManager(); - if (configfile != null) - { + if (configfile != null) { manager.setConfigResourcePath(configfile); } - try - { + try { manager.start(); registry.addSingletonResource(manager.getQueueManager().getDestination()); registry.addSingletonResource(manager.getTopicManager().getDestination()); } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } } - public void contextDestroyed(ServletContextEvent servletContextEvent) - { - if (manager != null) - { + public void contextDestroyed(ServletContextEvent servletContextEvent) { + if (manager != null) { manager.stop(); } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/integration/ServletContextBindingRegistry.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/integration/ServletContextBindingRegistry.java index 64c795cb30..f6e0699882 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/integration/ServletContextBindingRegistry.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/integration/ServletContextBindingRegistry.java @@ -20,32 +20,27 @@ import org.apache.activemq.artemis.spi.core.naming.BindingRegistry; import javax.servlet.ServletContext; -public class ServletContextBindingRegistry implements BindingRegistry -{ +public class ServletContextBindingRegistry implements BindingRegistry { + private ServletContext servletContext; - public ServletContextBindingRegistry(ServletContext servletContext) - { + public ServletContextBindingRegistry(ServletContext servletContext) { this.servletContext = servletContext; } - public Object lookup(String name) - { + public Object lookup(String name) { return servletContext.getAttribute(name); } - public boolean bind(String name, Object obj) - { + public boolean bind(String name, Object obj) { servletContext.setAttribute(name, obj); return true; } - public void unbind(String name) - { + public void unbind(String name) { servletContext.removeAttribute(name); } - public void close() - { + public void close() { } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/AcknowledgedQueueConsumer.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/AcknowledgedQueueConsumer.java index 52aaefe92d..e78603b74d 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/AcknowledgedQueueConsumer.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/AcknowledgedQueueConsumer.java @@ -38,20 +38,22 @@ import org.apache.activemq.artemis.rest.util.Constants; import org.apache.activemq.artemis.rest.util.LinkStrategy; import org.apache.activemq.artemis.rest.ActiveMQRestLogger; -public class AcknowledgedQueueConsumer extends QueueConsumer -{ +public class AcknowledgedQueueConsumer extends QueueConsumer { + protected long counter; protected String startup = Long.toString(System.currentTimeMillis()); protected volatile Acknowledgement ack; - public AcknowledgedQueueConsumer(ClientSessionFactory factory, String destination, String id, DestinationServiceManager serviceManager, String selector) throws ActiveMQException - { + public AcknowledgedQueueConsumer(ClientSessionFactory factory, + String destination, + String id, + DestinationServiceManager serviceManager, + String selector) throws ActiveMQException { super(factory, destination, id, serviceManager, selector); autoAck = false; } - public synchronized Acknowledgement getAck() - { + public synchronized Acknowledgement getAck() { return ack; } @@ -59,16 +61,13 @@ public class AcknowledgedQueueConsumer extends QueueConsumer @POST public synchronized Response poll(@HeaderParam(Constants.WAIT_HEADER) @DefaultValue("0") long wait, @PathParam("index") long index, - @Context UriInfo info) - { + @Context UriInfo info) { ActiveMQRestLogger.LOGGER.debug("Handling POST request for \"" + info.getPath() + "\""); - if (closed) - { + if (closed) { UriBuilder builder = info.getBaseUriBuilder(); String path = info.getMatchedURIs().get(1); - builder.path(path) - .path("acknowledge-next"); + builder.path(path).path("acknowledge-next"); String uri = builder.build().toString(); // redirect to another acknowledge-next @@ -78,43 +77,31 @@ public class AcknowledgedQueueConsumer extends QueueConsumer return checkIndexAndPoll(wait, info, info.getMatchedURIs().get(1), index); } - @Override - public synchronized void shutdown() - { + public synchronized void shutdown() { super.shutdown(); - if (ack != null) - { + if (ack != null) { ack = null; } } - @Path("acknowledgement/{ackToken}") @POST - public synchronized Response acknowledge( - @PathParam("ackToken") String ackToken, - @FormParam("acknowledge") boolean doAcknowledge, - @Context UriInfo uriInfo) - { + public synchronized Response acknowledge(@PathParam("ackToken") String ackToken, + @FormParam("acknowledge") boolean doAcknowledge, + @Context UriInfo uriInfo) { ActiveMQRestLogger.LOGGER.debug("Handling POST request for \"" + uriInfo.getPath() + "\""); ping(0); String basePath = uriInfo.getMatchedURIs().get(1); - if (closed) - { - Response.ResponseBuilder builder = Response.status(Response.Status.PRECONDITION_FAILED) - .entity("Could not acknowledge message, it was probably requeued from a timeout") - .type("text/plain"); + if (closed) { + Response.ResponseBuilder builder = Response.status(Response.Status.PRECONDITION_FAILED).entity("Could not acknowledge message, it was probably requeued from a timeout").type("text/plain"); setAcknowledgeLinks(uriInfo, basePath, builder, "-1"); return builder.build(); } - if (ack == null || !ack.getAckToken().equals(ackToken)) - { - Response.ResponseBuilder builder = Response.status(Response.Status.PRECONDITION_FAILED) - .entity("Could not acknowledge message, it was probably requeued from a timeout or you have an old link") - .type("text/plain"); + if (ack == null || !ack.getAckToken().equals(ackToken)) { + Response.ResponseBuilder builder = Response.status(Response.Status.PRECONDITION_FAILED).entity("Could not acknowledge message, it was probably requeued from a timeout or you have an old link").type("text/plain"); setAcknowledgeLinks(uriInfo, basePath, builder, "-1"); return builder.build(); } @@ -123,43 +110,37 @@ public class AcknowledgedQueueConsumer extends QueueConsumer previousIndex = -2; lastConsumed = null; - if (ack.wasSet() && doAcknowledge != ack.isAcknowledged()) - { + if (ack.wasSet() && doAcknowledge != ack.isAcknowledged()) { StringBuilder msg = new StringBuilder("Could not "); - if (doAcknowledge == false) msg.append("un"); + if (doAcknowledge == false) + msg.append("un"); msg.append("acknowledge message because it has already been "); - if (doAcknowledge == true) msg.append("un"); + if (doAcknowledge == true) + msg.append("un"); msg.append("acknowledged"); - Response.ResponseBuilder builder = Response.status(Response.Status.PRECONDITION_FAILED) - .entity(msg.toString()) - .type("text/plain"); + Response.ResponseBuilder builder = Response.status(Response.Status.PRECONDITION_FAILED).entity(msg.toString()).type("text/plain"); setAcknowledgeLinks(uriInfo, basePath, builder, "-1"); return builder.build(); } - if (ack.wasSet() && doAcknowledge == ack.isAcknowledged()) - { + if (ack.wasSet() && doAcknowledge == ack.isAcknowledged()) { Response.ResponseBuilder builder = Response.noContent(); setAcknowledgeLinks(uriInfo, basePath, builder, "-1"); return builder.build(); } - if (doAcknowledge) - { - try - { + if (doAcknowledge) { + try { ack.acknowledge(); //System.out.println("Acknowledge message: " + ack.getMessage()); ack.getMessage().acknowledge(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw new RuntimeException(e); } } - else - { + else { ack.unacknowledge(); unacknowledge(); } @@ -169,108 +150,95 @@ public class AcknowledgedQueueConsumer extends QueueConsumer } @Override - protected ClientMessage receive(long timeoutSecs) throws Exception - { + protected ClientMessage receive(long timeoutSecs) throws Exception { ClientMessage msg = super.receive(timeoutSecs); return msg; } @Override - protected ClientMessage receiveFromConsumer(long timeoutSecs) throws Exception - { + protected ClientMessage receiveFromConsumer(long timeoutSecs) throws Exception { ClientMessage message = super.receiveFromConsumer(timeoutSecs); - if (message != null) - { + if (message != null) { ack = new Acknowledgement((counter++) + startup, message); //System.out.println("---> Setting ack: " + ack.getAckToken()); } return message; } - - protected String getAckToken() - { + protected String getAckToken() { return ack.getAckToken(); } - protected void unacknowledge() - { + protected void unacknowledge() { // we close current session so that message is redelivered // for temporary queues/topics, create a new session before closing old so we don't lose the temporary topic/queue ClientConsumer old = consumer; ClientSession oldSession = session; - try - { + try { createSession(); } - catch (Exception e) - { + catch (Exception e) { shutdown(); throw new RuntimeException(e); } - finally - { - try - { + finally { + try { old.close(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { } - try - { + try { oldSession.close(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { } } } - - protected void setAcknowledgeLinks(UriInfo uriInfo, String basePath, Response.ResponseBuilder builder, String index) - { + protected void setAcknowledgeLinks(UriInfo uriInfo, + String basePath, + Response.ResponseBuilder builder, + String index) { setAcknowledgeNextLink(serviceManager.getLinkStrategy(), builder, uriInfo, basePath, index); setSessionLink(builder, uriInfo, basePath); } - @Override - protected void setMessageResponseLinks(UriInfo info, String basePath, Response.ResponseBuilder builder, String index) - { + protected void setMessageResponseLinks(UriInfo info, + String basePath, + Response.ResponseBuilder builder, + String index) { setAcknowledgementLink(builder, info, basePath); setSessionLink(builder, info, basePath); } @Override - protected void setPollTimeoutLinks(UriInfo info, String basePath, Response.ResponseBuilder builder, String index) - { + protected void setPollTimeoutLinks(UriInfo info, String basePath, Response.ResponseBuilder builder, String index) { setAcknowledgeNextLink(serviceManager.getLinkStrategy(), builder, info, basePath, index); setSessionLink(builder, info, basePath); } - public void setAcknowledgementLink(Response.ResponseBuilder response, UriInfo info, String basePath) - { + public void setAcknowledgementLink(Response.ResponseBuilder response, UriInfo info, String basePath) { UriBuilder builder = info.getBaseUriBuilder(); - builder.path(basePath) - .path("acknowledgement") - .path(getAckToken()); + builder.path(basePath).path("acknowledgement").path(getAckToken()); String uri = builder.build().toString(); serviceManager.getLinkStrategy().setLinkHeader(response, "acknowledgement", "acknowledgement", uri, MediaType.APPLICATION_FORM_URLENCODED); } - public static void setAcknowledgeNextLink(LinkStrategy linkStrategy, Response.ResponseBuilder response, UriInfo info, String basePath, String index) - { - if (index == null) throw new IllegalArgumentException("index cannot be null"); + public static void setAcknowledgeNextLink(LinkStrategy linkStrategy, + Response.ResponseBuilder response, + UriInfo info, + String basePath, + String index) { + if (index == null) + throw new IllegalArgumentException("index cannot be null"); UriBuilder builder = info.getBaseUriBuilder(); - builder.path(basePath) - .path("acknowledge-next" + index); + builder.path(basePath).path("acknowledge-next" + index); String uri = builder.build().toString(); linkStrategy.setLinkHeader(response, "acknowledge-next", "acknowledge-next", uri, MediaType.APPLICATION_FORM_URLENCODED); } - } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/Acknowledgement.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/Acknowledgement.java index 97af2b34d9..5f38c8fec0 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/Acknowledgement.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/Acknowledgement.java @@ -18,49 +18,44 @@ package org.apache.activemq.artemis.rest.queue; import org.apache.activemq.artemis.api.core.client.ClientMessage; -public class Acknowledgement -{ +public class Acknowledgement { + private final String ackToken; private final ClientMessage message; private boolean wasSet; private boolean acknowledged; - public Acknowledgement(String ackToken, ClientMessage message) - { + public Acknowledgement(String ackToken, ClientMessage message) { this.ackToken = ackToken; this.message = message; } - public String getAckToken() - { + public String getAckToken() { return ackToken; } - public ClientMessage getMessage() - { + public ClientMessage getMessage() { return message; } - public boolean wasSet() - { + public boolean wasSet() { return wasSet; } - public void acknowledge() - { - if (wasSet) throw new RuntimeException("Ack state is immutable"); + public void acknowledge() { + if (wasSet) + throw new RuntimeException("Ack state is immutable"); wasSet = true; acknowledged = true; } - public void unacknowledge() - { - if (wasSet) throw new RuntimeException("Ack state is immutable"); + public void unacknowledge() { + if (wasSet) + throw new RuntimeException("Ack state is immutable"); wasSet = true; } - public boolean isAcknowledged() - { + public boolean isAcknowledged() { return acknowledged; } } \ No newline at end of file diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/ConsumedHttpMessage.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/ConsumedHttpMessage.java index e28d326764..3437a679c5 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/ConsumedHttpMessage.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/ConsumedHttpMessage.java @@ -20,29 +20,24 @@ import org.apache.activemq.artemis.api.core.client.ClientMessage; import javax.ws.rs.core.Response; -public class ConsumedHttpMessage extends ConsumedMessage -{ +public class ConsumedHttpMessage extends ConsumedMessage { + private byte[] data; - public ConsumedHttpMessage(ClientMessage message) - { + public ConsumedHttpMessage(ClientMessage message) { super(message); } @Override - public void build(Response.ResponseBuilder builder) - { + public void build(Response.ResponseBuilder builder) { buildHeaders(builder); - if (data == null) - { + if (data == null) { int size = message.getBodySize(); - if (size > 0) - { + if (size > 0) { data = new byte[size]; message.getBodyBuffer().readBytes(data); } - else - { + else { data = new byte[0]; } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/ConsumedMessage.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/ConsumedMessage.java index f8ce86d5f2..9c5b7a46a0 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/ConsumedMessage.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/ConsumedMessage.java @@ -23,31 +23,26 @@ import org.apache.activemq.artemis.rest.ActiveMQRestLogger; import javax.ws.rs.core.Response; -public abstract class ConsumedMessage -{ +public abstract class ConsumedMessage { + public static final String POSTED_AS_HTTP_MESSAGE = "postedAsHttpMessage"; protected ClientMessage message; - public ConsumedMessage(ClientMessage message) - { + public ConsumedMessage(ClientMessage message) { this.message = message; } - public long getMessageID() - { + public long getMessageID() { return message.getMessageID(); } public abstract void build(Response.ResponseBuilder builder); - protected void buildHeaders(Response.ResponseBuilder builder) - { - for (SimpleString key : message.getPropertyNames()) - { + protected void buildHeaders(Response.ResponseBuilder builder) { + for (SimpleString key : message.getPropertyNames()) { String k = key.toString(); String headerName = HttpHeaderProperty.fromPropertyName(k); - if (headerName == null) - { + if (headerName == null) { continue; } builder.header(headerName, message.getStringProperty(k)); @@ -55,19 +50,15 @@ public abstract class ConsumedMessage } } - public static ConsumedMessage createConsumedMessage(ClientMessage message) - { + public static ConsumedMessage createConsumedMessage(ClientMessage message) { Boolean aBoolean = message.getBooleanProperty(POSTED_AS_HTTP_MESSAGE); - if (aBoolean != null && aBoolean.booleanValue()) - { + if (aBoolean != null && aBoolean.booleanValue()) { return new ConsumedHttpMessage(message); } - else if (message.getType() == ClientMessage.OBJECT_TYPE) - { + else if (message.getType() == ClientMessage.OBJECT_TYPE) { return new ConsumedObjectMessage(message); } - else - { + else { throw new IllegalArgumentException("ClientMessage must be an HTTP message or an Object message: " + message + " type: " + message.getType()); } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/ConsumedObjectMessage.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/ConsumedObjectMessage.java index 857a3c52a2..004070ce0f 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/ConsumedObjectMessage.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/ConsumedObjectMessage.java @@ -22,35 +22,30 @@ import javax.ws.rs.core.Response; import java.io.ByteArrayInputStream; import java.io.ObjectInputStream; -public class ConsumedObjectMessage extends ConsumedMessage -{ +public class ConsumedObjectMessage extends ConsumedMessage { + protected Object readObject; - public ConsumedObjectMessage(ClientMessage message) - { + public ConsumedObjectMessage(ClientMessage message) { super(message); - if (message.getType() != ClientMessage.OBJECT_TYPE) throw new IllegalArgumentException("Client message must be an OBJECT_TYPE"); + if (message.getType() != ClientMessage.OBJECT_TYPE) + throw new IllegalArgumentException("Client message must be an OBJECT_TYPE"); } @Override - public void build(Response.ResponseBuilder builder) - { + public void build(Response.ResponseBuilder builder) { buildHeaders(builder); - if (readObject == null) - { + if (readObject == null) { int size = message.getBodyBuffer().readInt(); - if (size > 0) - { + if (size > 0) { byte[] body = new byte[size]; message.getBodyBuffer().readBytes(body); ByteArrayInputStream bais = new ByteArrayInputStream(body); - try - { + try { ObjectInputStream ois = new ObjectInputStream(bais); readObject = ois.readObject(); } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/ConsumersResource.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/ConsumersResource.java index 9e73b02dc8..4c742472ca 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/ConsumersResource.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/ConsumersResource.java @@ -38,8 +38,8 @@ import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.rest.ActiveMQRestLogger; import org.apache.activemq.artemis.rest.util.TimeoutTask; -public class ConsumersResource implements TimeoutTask.Callback -{ +public class ConsumersResource implements TimeoutTask.Callback { + protected ConcurrentMap queueConsumers = new ConcurrentHashMap(); protected ClientSessionFactory sessionFactory; protected String destination; @@ -51,85 +51,70 @@ public class ConsumersResource implements TimeoutTask.Callback protected static final int ACKNOWLEDGED = 0x01; protected static final int SELECTOR_SET = 0x02; - public DestinationServiceManager getServiceManager() - { + public DestinationServiceManager getServiceManager() { return serviceManager; } - public void setServiceManager(DestinationServiceManager serviceManager) - { + public void setServiceManager(DestinationServiceManager serviceManager) { this.serviceManager = serviceManager; } - public ClientSessionFactory getSessionFactory() - { + public ClientSessionFactory getSessionFactory() { return sessionFactory; } - public void setSessionFactory(ClientSessionFactory sessionFactory) - { + public void setSessionFactory(ClientSessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } - public String getDestination() - { + public String getDestination() { return destination; } - public void setDestination(String destination) - { + public void setDestination(String destination) { this.destination = destination; } - public int getConsumerTimeoutSeconds() - { + public int getConsumerTimeoutSeconds() { return consumerTimeoutSeconds; } - public void setConsumerTimeoutSeconds(int consumerTimeoutSeconds) - { + public void setConsumerTimeoutSeconds(int consumerTimeoutSeconds) { this.consumerTimeoutSeconds = consumerTimeoutSeconds; } - public boolean testTimeout(String target, boolean autoShutdown) - { + public boolean testTimeout(String target, boolean autoShutdown) { QueueConsumer consumer = queueConsumers.get(target); - if (consumer == null) return false; - if (System.currentTimeMillis() - consumer.getLastPingTime() > consumerTimeoutSeconds * 1000) - { + if (consumer == null) + return false; + if (System.currentTimeMillis() - consumer.getLastPingTime() > consumerTimeoutSeconds * 1000) { ActiveMQRestLogger.LOGGER.shutdownRestConsumer(consumer.getId()); - if (autoShutdown) - { + if (autoShutdown) { shutdown(consumer); } return true; } - else - { + else { return false; } } - public void shutdown(String target) - { + public void shutdown(String target) { QueueConsumer consumer = queueConsumers.get(target); - if (consumer == null) return; + if (consumer == null) + return; shutdown(consumer); } - private void shutdown(QueueConsumer consumer) - { - synchronized (consumer) - { + private void shutdown(QueueConsumer consumer) { + synchronized (consumer) { consumer.shutdown(); queueConsumers.remove(consumer.getId()); } } - public void stop() - { - for (QueueConsumer consumer : queueConsumers.values()) - { + public void stop() { + for (QueueConsumer consumer : queueConsumers.values()) { consumer.shutdown(); } } @@ -137,25 +122,20 @@ public class ConsumersResource implements TimeoutTask.Callback @POST public Response createSubscription(@FormParam("autoAck") @DefaultValue("true") boolean autoAck, @FormParam("selector") String selector, - @Context UriInfo uriInfo) - { + @Context UriInfo uriInfo) { ActiveMQRestLogger.LOGGER.debug("Handling POST request for \"" + uriInfo.getPath() + "\""); - try - { + try { QueueConsumer consumer = null; int attributes = 0; - if (selector != null) - { + if (selector != null) { attributes = attributes | SELECTOR_SET; } - if (autoAck) - { + if (autoAck) { consumer = createConsumer(selector); } - else - { + else { attributes |= ACKNOWLEDGED; consumer = createAcknowledgedConsumer(selector); } @@ -166,43 +146,36 @@ public class ConsumersResource implements TimeoutTask.Callback location.path(consumer.getId()); Response.ResponseBuilder builder = Response.created(location.build()); - if (autoAck) - { + if (autoAck) { QueueConsumer.setConsumeNextLink(serviceManager.getLinkStrategy(), builder, uriInfo, uriInfo.getMatchedURIs().get(0) + "/" + attributesSegment + "/" + consumer.getId(), "-1"); } - else - { + else { AcknowledgedQueueConsumer.setAcknowledgeNextLink(serviceManager.getLinkStrategy(), builder, uriInfo, uriInfo.getMatchedURIs().get(0) + "/" + attributesSegment + "/" + consumer.getId(), "-1"); } return builder.build(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw new RuntimeException(e); } - finally - { + finally { } } - protected void addConsumer(QueueConsumer consumer) - { + protected void addConsumer(QueueConsumer consumer) { queueConsumers.put(consumer.getId(), consumer); serviceManager.getTimeoutTask().add(this, consumer.getId()); } - public QueueConsumer createConsumer(String selector) throws ActiveMQException - { + public QueueConsumer createConsumer(String selector) throws ActiveMQException { String genId = sessionCounter.getAndIncrement() + "-queue-" + destination + "-" + startup; QueueConsumer consumer = new QueueConsumer(sessionFactory, destination, genId, serviceManager, selector); addConsumer(consumer); return consumer; } - public QueueConsumer createAcknowledgedConsumer(String selector) throws ActiveMQException - { + public QueueConsumer createAcknowledgedConsumer(String selector) throws ActiveMQException { String genId = sessionCounter.getAndIncrement() + "-queue-" + destination + "-" + startup; QueueConsumer consumer = new AcknowledgedQueueConsumer(sessionFactory, destination, genId, serviceManager, selector); addConsumer(consumer); @@ -213,8 +186,7 @@ public class ConsumersResource implements TimeoutTask.Callback @GET public Response getConsumer(@PathParam("attributes") int attributes, @PathParam("consumer-id") String consumerId, - @Context UriInfo uriInfo) throws Exception - { + @Context UriInfo uriInfo) throws Exception { ActiveMQRestLogger.LOGGER.debug("Handling GET request for \"" + uriInfo.getPath() + "\""); return headConsumer(attributes, consumerId, uriInfo); @@ -224,31 +196,25 @@ public class ConsumersResource implements TimeoutTask.Callback @HEAD public Response headConsumer(@PathParam("attributes") int attributes, @PathParam("consumer-id") String consumerId, - @Context UriInfo uriInfo) throws Exception - { + @Context UriInfo uriInfo) throws Exception { ActiveMQRestLogger.LOGGER.debug("Handling HEAD request for \"" + uriInfo.getPath() + "\""); QueueConsumer consumer = findConsumer(attributes, consumerId, uriInfo); Response.ResponseBuilder builder = Response.noContent(); // we synchronize just in case a failed request is still processing - synchronized (consumer) - { - if ((attributes & ACKNOWLEDGED) > 0) - { + synchronized (consumer) { + if ((attributes & ACKNOWLEDGED) > 0) { AcknowledgedQueueConsumer ackedConsumer = (AcknowledgedQueueConsumer) consumer; Acknowledgement ack = ackedConsumer.getAck(); - if (ack == null || ack.wasSet()) - { + if (ack == null || ack.wasSet()) { AcknowledgedQueueConsumer.setAcknowledgeNextLink(serviceManager.getLinkStrategy(), builder, uriInfo, uriInfo.getMatchedURIs().get(1) + "/attributes-" + attributes + "/" + consumer.getId(), Long.toString(consumer.getConsumeIndex())); } - else - { + else { ackedConsumer.setAcknowledgementLink(builder, uriInfo, uriInfo.getMatchedURIs().get(1) + "/attributes-" + attributes + "/" + consumer.getId()); } } - else - { + else { QueueConsumer.setConsumeNextLink(serviceManager.getLinkStrategy(), builder, uriInfo, uriInfo.getMatchedURIs().get(1) + "/attributes-" + attributes + "/" + consumer.getId(), Long.toString(consumer.getConsumeIndex())); } } @@ -256,34 +222,26 @@ public class ConsumersResource implements TimeoutTask.Callback } @Path("attributes-{attributes}/{consumer-id}") - public QueueConsumer findConsumer( - @PathParam("attributes") int attributes, - @PathParam("consumer-id") String consumerId, - @Context UriInfo uriInfo) throws Exception - { + public QueueConsumer findConsumer(@PathParam("attributes") int attributes, + @PathParam("consumer-id") String consumerId, + @Context UriInfo uriInfo) throws Exception { QueueConsumer consumer = queueConsumers.get(consumerId); - if (consumer == null) - { - if ((attributes & SELECTOR_SET) > 0) - { + if (consumer == null) { + if ((attributes & SELECTOR_SET) > 0) { - Response.ResponseBuilder builder = Response.status(Response.Status.GONE) - .entity("Cannot reconnect to selector-based consumer. You must recreate the consumer session.") - .type("text/plain"); + Response.ResponseBuilder builder = Response.status(Response.Status.GONE).entity("Cannot reconnect to selector-based consumer. You must recreate the consumer session.").type("text/plain"); UriBuilder uriBuilder = uriInfo.getBaseUriBuilder(); uriBuilder.path(uriInfo.getMatchedURIs().get(1)); serviceManager.getLinkStrategy().setLinkHeader(builder, "pull-consumers", "pull-consumers", uriBuilder.build().toString(), null); throw new WebApplicationException(builder.build()); } - if ((attributes & ACKNOWLEDGED) > 0) - { + if ((attributes & ACKNOWLEDGED) > 0) { QueueConsumer tmp = new AcknowledgedQueueConsumer(sessionFactory, destination, consumerId, serviceManager, null); consumer = addReconnectedConsumerToMap(consumerId, tmp); } - else - { + else { QueueConsumer tmp = new QueueConsumer(sessionFactory, destination, consumerId, serviceManager, null); consumer = addReconnectedConsumerToMap(consumerId, tmp); } @@ -291,37 +249,27 @@ public class ConsumersResource implements TimeoutTask.Callback return consumer; } - private QueueConsumer addReconnectedConsumerToMap(String consumerId, QueueConsumer tmp) - { + private QueueConsumer addReconnectedConsumerToMap(String consumerId, QueueConsumer tmp) { QueueConsumer consumer; consumer = queueConsumers.putIfAbsent(consumerId, tmp); - if (consumer != null) - { + if (consumer != null) { tmp.shutdown(); } - else - { + else { consumer = tmp; serviceManager.getTimeoutTask().add(this, consumer.getId()); } return consumer; } - @Path("attributes-{attributes}/{consumer-id}") @DELETE - public void closeSession( - @PathParam("consumer-id") String consumerId, - @Context UriInfo uriInfo) - { + public void closeSession(@PathParam("consumer-id") String consumerId, @Context UriInfo uriInfo) { ActiveMQRestLogger.LOGGER.debug("Handling DELETE request for \"" + uriInfo.getPath() + "\""); QueueConsumer consumer = queueConsumers.remove(consumerId); - if (consumer == null) - { - throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND) - .entity("Failed to match a consumer to URL" + consumerId) - .type("text/plain").build()); + if (consumer == null) { + throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).entity("Failed to match a consumer to URL" + consumerId).type("text/plain").build()); } consumer.shutdown(); } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/DestinationResource.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/DestinationResource.java index 05948c036a..e28ad897e5 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/DestinationResource.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/DestinationResource.java @@ -16,39 +16,33 @@ */ package org.apache.activemq.artemis.rest.queue; -public class DestinationResource -{ +public class DestinationResource { + protected String destination; protected PostMessage sender; protected DestinationServiceManager serviceManager; - public DestinationServiceManager getServiceManager() - { + public DestinationServiceManager getServiceManager() { return serviceManager; } - public void setServiceManager(DestinationServiceManager serviceManager) - { + public void setServiceManager(DestinationServiceManager serviceManager) { this.serviceManager = serviceManager; } - public PostMessage getSender() - { + public PostMessage getSender() { return sender; } - public void setSender(PostMessage sender) - { + public void setSender(PostMessage sender) { this.sender = sender; } - public String getDestination() - { + public String getDestination() { return destination; } - public void setDestination(String destination) - { + public void setDestination(String destination) { this.destination = destination; } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/DestinationServiceManager.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/DestinationServiceManager.java index 16abc8740a..7d69bd999b 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/DestinationServiceManager.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/DestinationServiceManager.java @@ -25,8 +25,8 @@ import org.apache.activemq.artemis.rest.util.LinkStrategy; import org.apache.activemq.artemis.rest.util.TimeoutTask; import org.apache.activemq.artemis.spi.core.naming.BindingRegistry; -public abstract class DestinationServiceManager -{ +public abstract class DestinationServiceManager { + protected ServerLocator locator; protected ClientSessionFactory sessionFactory; protected ServerLocator consumerServerLocator; @@ -40,143 +40,118 @@ public abstract class DestinationServiceManager protected LinkStrategy linkStrategy; protected BindingRegistry registry; - public BindingRegistry getRegistry() - { + public BindingRegistry getRegistry() { return registry; } - public void setRegistry(BindingRegistry registry) - { + public void setRegistry(BindingRegistry registry) { this.registry = registry; } - public LinkStrategy getLinkStrategy() - { + public LinkStrategy getLinkStrategy() { return linkStrategy; } - public void setLinkStrategy(LinkStrategy linkStrategy) - { + public void setLinkStrategy(LinkStrategy linkStrategy) { this.linkStrategy = linkStrategy; } - public long getProducerTimeToLive() - { + public long getProducerTimeToLive() { return producerTimeToLive; } - public void setProducerTimeToLive(long producerTimeToLive) - { + public void setProducerTimeToLive(long producerTimeToLive) { this.producerTimeToLive = producerTimeToLive; } - public int getProducerPoolSize() - { + public int getProducerPoolSize() { return producerPoolSize; } - public void setProducerPoolSize(int producerPoolSize) - { + public void setProducerPoolSize(int producerPoolSize) { this.producerPoolSize = producerPoolSize; } - public ClientSessionFactory getConsumerSessionFactory() - { + public ClientSessionFactory getConsumerSessionFactory() { return consumerSessionFactory; } - public void setConsumerSessionFactory(ClientSessionFactory consumerSessionFactory) - { + public void setConsumerSessionFactory(ClientSessionFactory consumerSessionFactory) { this.consumerSessionFactory = consumerSessionFactory; } /** * @return the consumerServerLocator */ - public ServerLocator getConsumerServerLocator() - { + public ServerLocator getConsumerServerLocator() { return consumerServerLocator; } /** * @param consumerServerLocator the consumerServerLocator to set */ - public void setConsumerServerLocator(ServerLocator consumerServerLocator) - { + public void setConsumerServerLocator(ServerLocator consumerServerLocator) { this.consumerServerLocator = consumerServerLocator; } - public TimeoutTask getTimeoutTask() - { + public TimeoutTask getTimeoutTask() { return timeoutTask; } - public void setTimeoutTask(TimeoutTask timeoutTask) - { + public void setTimeoutTask(TimeoutTask timeoutTask) { this.timeoutTask = timeoutTask; } - public DestinationSettings getDefaultSettings() - { + public DestinationSettings getDefaultSettings() { return defaultSettings; } - public void setDefaultSettings(DestinationSettings defaultSettings) - { + public void setDefaultSettings(DestinationSettings defaultSettings) { this.defaultSettings = defaultSettings; } - public ServerLocator getServerLocator() - { + public ServerLocator getServerLocator() { return this.locator; } - public void setServerLocator(ServerLocator locator) - { + public void setServerLocator(ServerLocator locator) { this.locator = locator; } - public ClientSessionFactory getSessionFactory() - { + public ClientSessionFactory getSessionFactory() { return sessionFactory; } - public void setSessionFactory(ClientSessionFactory sessionFactory) - { + public void setSessionFactory(ClientSessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } - public String getPushStoreFile() - { + public String getPushStoreFile() { return pushStoreFile; } - public void setPushStoreFile(String pushStoreFile) - { + public void setPushStoreFile(String pushStoreFile) { this.pushStoreFile = pushStoreFile; } - protected void initDefaults() - { - if (locator == null) - { + protected void initDefaults() { + if (locator == null) { locator = ActiveMQClient.createServerLocatorWithoutHA(new TransportConfiguration(InVMConnectorFactory.class.getName())); } - if (sessionFactory == null) - { - try - { + if (sessionFactory == null) { + try { sessionFactory = locator.createSessionFactory(); } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } - if (consumerSessionFactory == null) consumerSessionFactory = sessionFactory; + if (consumerSessionFactory == null) + consumerSessionFactory = sessionFactory; - if (timeoutTask == null) throw new RuntimeException("TimeoutTask is not set"); + if (timeoutTask == null) + throw new RuntimeException("TimeoutTask is not set"); } public abstract void start() throws Exception; diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/DestinationSettings.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/DestinationSettings.java index ed443a96d4..35657eee85 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/DestinationSettings.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/DestinationSettings.java @@ -16,46 +16,39 @@ */ package org.apache.activemq.artemis.rest.queue; -public class DestinationSettings -{ +public class DestinationSettings { + protected boolean duplicatesAllowed; private boolean durableSend; private int consumerSessionTimeoutSeconds = 1000; - public boolean isDuplicatesAllowed() - { + public boolean isDuplicatesAllowed() { return duplicatesAllowed; } - public void setDuplicatesAllowed(boolean duplicatesAllowed) - { + public void setDuplicatesAllowed(boolean duplicatesAllowed) { this.duplicatesAllowed = duplicatesAllowed; } - public int getConsumerSessionTimeoutSeconds() - { + public int getConsumerSessionTimeoutSeconds() { return consumerSessionTimeoutSeconds; } - public void setConsumerSessionTimeoutSeconds(int consumerSessionTimeoutSeconds) - { + public void setConsumerSessionTimeoutSeconds(int consumerSessionTimeoutSeconds) { this.consumerSessionTimeoutSeconds = consumerSessionTimeoutSeconds; } - public boolean isDurableSend() - { + public boolean isDurableSend() { return durableSend; } - public void setDurableSend(boolean durableSend) - { + public void setDurableSend(boolean durableSend) { this.durableSend = durableSend; } public static final DestinationSettings defaultSettings; - static - { + static { defaultSettings = new DestinationSettings(); defaultSettings.setDuplicatesAllowed(true); defaultSettings.setDurableSend(false); diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/PostMessage.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/PostMessage.java index b2211d2b1a..c99cdf15fb 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/PostMessage.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/PostMessage.java @@ -43,8 +43,8 @@ import org.apache.activemq.artemis.rest.ActiveMQRestLogger; import org.apache.activemq.artemis.utils.UUID; import org.apache.activemq.artemis.utils.UUIDGenerator; -public class PostMessage -{ +public class PostMessage { + protected ClientSessionFactory sessionFactory; protected String destination; protected boolean defaultDurable = false; @@ -55,32 +55,30 @@ public class PostMessage protected ArrayBlockingQueue pool; protected int poolSize = 10; - protected static class Pooled - { + protected static class Pooled { + public ClientSession session; public ClientProducer producer; - private Pooled(ClientSession session, ClientProducer producer) - { + private Pooled(ClientSession session, ClientProducer producer) { this.session = session; this.producer = producer; } } - protected String generateDupId() - { + protected String generateDupId() { return startupTime + Long.toString(counter.incrementAndGet()); } - public void publish(HttpHeaders headers, byte[] body, String dup, + public void publish(HttpHeaders headers, + byte[] body, + String dup, boolean durable, Long ttl, Long expiration, - Integer priority) throws Exception - { + Integer priority) throws Exception { Pooled pooled = getPooled(); - try - { + try { ClientProducer producer = pooled.producer; ClientMessage message = createActiveMQMessage(headers, body, durable, ttl, expiration, priority, pooled.session); message.putStringProperty(ClientMessage.HDR_DUPLICATE_DETECTION_ID.toString(), dup); @@ -88,14 +86,11 @@ public class PostMessage ActiveMQRestLogger.LOGGER.debug("Sent message: " + message); pool.add(pooled); } - catch (Exception ex) - { - try - { + catch (Exception ex) { + try { pooled.session.close(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { } addPooled(); throw ex; @@ -104,12 +99,14 @@ public class PostMessage @PUT @Path("{id}") - public Response putWithId(@PathParam("id") String dupId, @QueryParam("durable") Boolean durable, + public Response putWithId(@PathParam("id") String dupId, + @QueryParam("durable") Boolean durable, @QueryParam("ttl") Long ttl, @QueryParam("expiration") Long expiration, @QueryParam("priority") Integer priority, - @Context HttpHeaders headers, @Context UriInfo uriInfo, byte[] body) - { + @Context HttpHeaders headers, + @Context UriInfo uriInfo, + byte[] body) { ActiveMQRestLogger.LOGGER.debug("Handling PUT request for \"" + uriInfo.getRequestUri() + "\""); return internalPostWithId(dupId, durable, ttl, expiration, priority, headers, uriInfo, body); @@ -117,19 +114,27 @@ public class PostMessage @POST @Path("{id}") - public Response postWithId(@PathParam("id") String dupId, @QueryParam("durable") Boolean durable, + public Response postWithId(@PathParam("id") String dupId, + @QueryParam("durable") Boolean durable, @QueryParam("ttl") Long ttl, @QueryParam("expiration") Long expiration, @QueryParam("priority") Integer priority, - @Context HttpHeaders headers, @Context UriInfo uriInfo, byte[] body) - { + @Context HttpHeaders headers, + @Context UriInfo uriInfo, + byte[] body) { ActiveMQRestLogger.LOGGER.debug("Handling POST request for \"" + uriInfo.getRequestUri() + "\""); return internalPostWithId(dupId, durable, ttl, expiration, priority, headers, uriInfo, body); } - private Response internalPostWithId(String dupId, Boolean durable, Long ttl, Long expiration, Integer priority, HttpHeaders headers, UriInfo uriInfo, byte[] body) - { + private Response internalPostWithId(String dupId, + Boolean durable, + Long ttl, + Long expiration, + Integer priority, + HttpHeaders headers, + UriInfo uriInfo, + byte[] body) { String matched = uriInfo.getMatchedURIs().get(1); UriBuilder nextBuilder = uriInfo.getBaseUriBuilder(); String nextId = generateDupId(); @@ -137,20 +142,14 @@ public class PostMessage URI next = nextBuilder.build(); boolean isDurable = defaultDurable; - if (durable != null) - { + if (durable != null) { isDurable = durable.booleanValue(); } - try - { + try { publish(headers, body, dupId, isDurable, ttl, expiration, priority); } - catch (Exception e) - { - Response error = Response.serverError() - .entity("Problem posting message: " + e.getMessage()) - .type("text/plain") - .build(); + catch (Exception e) { + Response error = Response.serverError().entity("Problem posting message: " + e.getMessage()).type("text/plain").build(); throw new WebApplicationException(e, error); } Response.ResponseBuilder builder = Response.status(201); @@ -158,139 +157,112 @@ public class PostMessage return builder.build(); } - public long getProducerTimeToLive() - { + public long getProducerTimeToLive() { return producerTimeToLive; } - public void setProducerTimeToLive(long producerTimeToLive) - { + public void setProducerTimeToLive(long producerTimeToLive) { this.producerTimeToLive = producerTimeToLive; } - public DestinationServiceManager getServiceManager() - { + public DestinationServiceManager getServiceManager() { return serviceManager; } - public void setServiceManager(DestinationServiceManager serviceManager) - { + public void setServiceManager(DestinationServiceManager serviceManager) { this.serviceManager = serviceManager; } - public ClientSessionFactory getSessionFactory() - { + public ClientSessionFactory getSessionFactory() { return sessionFactory; } - public void setSessionFactory(ClientSessionFactory sessionFactory) - { + public void setSessionFactory(ClientSessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } - public String getDestination() - { + public String getDestination() { return destination; } - public void setDestination(String destination) - { + public void setDestination(String destination) { this.destination = destination; } - public boolean isDefaultDurable() - { + public boolean isDefaultDurable() { return defaultDurable; } - public void setDefaultDurable(boolean defaultDurable) - { + public void setDefaultDurable(boolean defaultDurable) { this.defaultDurable = defaultDurable; } - public int getPoolSize() - { + public int getPoolSize() { return poolSize; } - public void setPoolSize(int poolSize) - { + public void setPoolSize(int poolSize) { this.poolSize = poolSize; } - public void init() throws Exception - { + public void init() throws Exception { pool = new ArrayBlockingQueue(poolSize); - for (int i = 0; i < poolSize; i++) - { + for (int i = 0; i < poolSize; i++) { addPooled(); } } - protected void addPooled() throws ActiveMQException - { + protected void addPooled() throws ActiveMQException { ClientSession session = sessionFactory.createSession(); ClientProducer producer = session.createProducer(destination); session.start(); pool.add(new Pooled(session, producer)); } - protected Pooled getPooled() throws InterruptedException - { + protected Pooled getPooled() throws InterruptedException { Pooled pooled = pool.poll(1, TimeUnit.SECONDS); - if (pooled == null) - { + if (pooled == null) { throw new WebApplicationException(Response.status(503).entity("Timed out waiting for available producer.").type("text/plain").build()); } return pooled; } - public void cleanup() - { - for (Pooled pooled : pool) - { - try - { + public void cleanup() { + for (Pooled pooled : pool) { + try { pooled.session.close(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw new RuntimeException(e); } } } - - protected ClientMessage createActiveMQMessage(HttpHeaders headers, byte[] body, + protected ClientMessage createActiveMQMessage(HttpHeaders headers, + byte[] body, boolean durable, Long ttl, Long expiration, Integer priority, - ClientSession session) throws Exception - { + ClientSession session) throws Exception { ClientMessage message = session.createMessage(Message.BYTES_TYPE, durable); // HORNETQ-962 UUID uid = UUIDGenerator.getInstance().generateUUID(); message.setUserID(uid); - if (expiration != null) - { + if (expiration != null) { message.setExpiration(expiration.longValue()); } - else if (ttl != null) - { + else if (ttl != null) { message.setExpiration(System.currentTimeMillis() + ttl.longValue()); } - else if (producerTimeToLive > 0) - { + else if (producerTimeToLive > 0) { message.setExpiration(System.currentTimeMillis() + producerTimeToLive); } - if (priority != null) - { + if (priority != null) { byte p = priority.byteValue(); - if (p >= 0 && p <= 9) - { + if (p >= 0 && p <= 9) { message.setPriority(p); } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/PostMessageDupsOk.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/PostMessageDupsOk.java index b8905e467d..ef0da88403 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/PostMessageDupsOk.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/PostMessageDupsOk.java @@ -34,31 +34,27 @@ import java.net.URI; /** * Implements simple "create" link. Returns 201 with Location of created resource as per HTTP */ -public class PostMessageDupsOk extends PostMessage -{ +public class PostMessageDupsOk extends PostMessage { - public void publish(HttpHeaders headers, byte[] body, boolean durable, + public void publish(HttpHeaders headers, + byte[] body, + boolean durable, Long ttl, Long expiration, - Integer priority) throws Exception - { + Integer priority) throws Exception { Pooled pooled = getPooled(); - try - { + try { ClientProducer producer = pooled.producer; ClientMessage message = createActiveMQMessage(headers, body, durable, ttl, expiration, priority, pooled.session); producer.send(message); ActiveMQRestLogger.LOGGER.debug("Sent message: " + message); pool.add(pooled); } - catch (Exception ex) - { - try - { + catch (Exception ex) { + try { pooled.session.close(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { } addPooled(); throw ex; @@ -72,25 +68,18 @@ public class PostMessageDupsOk extends PostMessage @QueryParam("expiration") Long expiration, @QueryParam("priority") Integer priority, @Context UriInfo uriInfo, - byte[] body) - { + byte[] body) { ActiveMQRestLogger.LOGGER.debug("Handling POST request for \"" + uriInfo.getRequestUri() + "\""); - try - { + try { boolean isDurable = defaultDurable; - if (durable != null) - { + if (durable != null) { isDurable = durable.booleanValue(); } publish(headers, body, isDurable, ttl, expiration, priority); } - catch (Exception e) - { - Response error = Response.serverError() - .entity("Problem posting message: " + e.getMessage()) - .type("text/plain") - .build(); + catch (Exception e) { + Response error = Response.serverError().entity("Problem posting message: " + e.getMessage()).type("text/plain").build(); throw new WebApplicationException(e, error); } Response.ResponseBuilder builder = Response.status(201); diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/PostMessageNoDups.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/PostMessageNoDups.java index de65ccbcbc..b2b34e2ab5 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/PostMessageNoDups.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/PostMessageNoDups.java @@ -26,12 +26,10 @@ import javax.ws.rs.core.UriInfo; /** * implements reliable "create", "create-next" pattern defined by REST-* Messaging specificaiton */ -public class PostMessageNoDups extends PostMessage -{ +public class PostMessageNoDups extends PostMessage { @POST - public Response redirectCreation(@Context UriInfo uriInfo) - { + public Response redirectCreation(@Context UriInfo uriInfo) { ActiveMQRestLogger.LOGGER.debug("Handling POST request for \"" + uriInfo.getPath() + "\""); String id = generateDupId(); diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/QueueConsumer.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/QueueConsumer.java index 48053a431f..77768395af 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/QueueConsumer.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/QueueConsumer.java @@ -41,8 +41,8 @@ import org.apache.activemq.artemis.jms.client.SelectorTranslator; /** * Auto-acknowleged consumer */ -public class QueueConsumer -{ +public class QueueConsumer { + protected ClientSessionFactory factory; protected ClientSession session; protected ClientConsumer consumer; @@ -60,34 +60,33 @@ public class QueueConsumer protected long previousIndex = -1; protected ConsumedMessage lastConsumed; - public long getConsumeIndex() - { - if (lastConsumed == null) return -1; + public long getConsumeIndex() { + if (lastConsumed == null) + return -1; return lastConsumed.getMessageID(); } - public DestinationServiceManager getServiceManager() - { + public DestinationServiceManager getServiceManager() { return serviceManager; } - public void setServiceManager(DestinationServiceManager serviceManager) - { + public void setServiceManager(DestinationServiceManager serviceManager) { this.serviceManager = serviceManager; } - public long getLastPingTime() - { + public long getLastPingTime() { return lastPing; } - protected void ping(long offsetSecs) - { + protected void ping(long offsetSecs) { lastPing = System.currentTimeMillis() + (offsetSecs * 1000); } - public QueueConsumer(ClientSessionFactory factory, String destination, String id, DestinationServiceManager serviceManager, String selector) throws ActiveMQException - { + public QueueConsumer(ClientSessionFactory factory, + String destination, + String id, + DestinationServiceManager serviceManager, + String selector) throws ActiveMQException { this.factory = factory; this.destination = destination; this.id = id; @@ -97,57 +96,47 @@ public class QueueConsumer createSession(); } - public String getId() - { + public String getId() { return id; } - public boolean isClosed() - { + public boolean isClosed() { return closed; } - public synchronized void shutdown() - { - if (closed) return; + public synchronized void shutdown() { + if (closed) + return; closed = true; lastConsumed = null; previousIndex = -2; - try - { + try { consumer.close(); ActiveMQRestLogger.LOGGER.debug("Closed consumer: " + consumer); } - catch (Exception e) - { + catch (Exception e) { } - try - { + try { session.close(); ActiveMQRestLogger.LOGGER.debug("Closed session: " + session); } - catch (Exception e) - { + catch (Exception e) { } session = null; consumer = null; } - @Path("consume-next{index}") @POST public synchronized Response poll(@HeaderParam(Constants.WAIT_HEADER) @DefaultValue("0") long wait, @PathParam("index") long index, - @Context UriInfo info) - { + @Context UriInfo info) { ActiveMQRestLogger.LOGGER.debug("Handling POST request for \"" + info.getRequestUri() + "\""); - if (closed) - { + if (closed) { UriBuilder builder = info.getBaseUriBuilder(); - builder.path(info.getMatchedURIs().get(1)) - .path("consume-next"); + builder.path(info.getMatchedURIs().get(1)).path("consume-next"); String uri = builder.build().toString(); // redirect to another consume-next @@ -157,44 +146,34 @@ public class QueueConsumer return checkIndexAndPoll(wait, info, info.getMatchedURIs().get(1), index); } - protected Response checkIndexAndPoll(long wait, UriInfo info, String basePath, long index) - { + protected Response checkIndexAndPoll(long wait, UriInfo info, String basePath, long index) { ping(wait); - if (lastConsumed == null && index > 0) - { + if (lastConsumed == null && index > 0) { return Response.status(412).entity("You are using an old consume-next link and are out of sync with the JMS session on the server").type("text/plain").build(); } - if (lastConsumed != null) - { - if (index == previousIndex) - { + if (lastConsumed != null) { + if (index == previousIndex) { String token = Long.toString(lastConsumed.getMessageID()); return getMessageResponse(lastConsumed, info, basePath, token).build(); } - if (index != lastConsumed.getMessageID()) - { + if (index != lastConsumed.getMessageID()) { return Response.status(412).entity("You are using an old consume-next link and are out of sync with the JMS session on the server").type("text/plain").build(); } } - try - { + try { return pollWithIndex(wait, info, basePath, index); } - finally - { + finally { ping(0); // ping again as we don't want wait time included in timeout. } } - protected Response pollWithIndex(long wait, UriInfo info, String basePath, long index) - { - try - { + protected Response pollWithIndex(long wait, UriInfo info, String basePath, long index) { + try { ClientMessage message = receive(wait); - if (message == null) - { + if (message == null) { Response.ResponseBuilder builder = Response.status(503).entity("Timed out waiting for message receive.").type("text/plain"); setPollTimeoutLinks(info, basePath, builder, Long.toString(index)); return builder.build(); @@ -203,40 +182,34 @@ public class QueueConsumer lastConsumed = ConsumedMessage.createConsumedMessage(message); String token = Long.toString(lastConsumed.getMessageID()); Response response = getMessageResponse(lastConsumed, info, basePath, token).build(); - if (autoAck) message.acknowledge(); + if (autoAck) + message.acknowledge(); return response; } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } } - protected void createSession() throws ActiveMQException - { + protected void createSession() throws ActiveMQException { session = factory.createSession(true, true, 0); ActiveMQRestLogger.LOGGER.debug("Created session: " + session); - if (selector == null) - { + if (selector == null) { consumer = session.createConsumer(destination); } - else - { + else { consumer = session.createConsumer(destination, SelectorTranslator.convertToActiveMQFilterString(selector)); } ActiveMQRestLogger.LOGGER.debug("Created consumer: " + consumer); session.start(); } - protected ClientMessage receiveFromConsumer(long timeoutSecs) throws Exception - { + protected ClientMessage receiveFromConsumer(long timeoutSecs) throws Exception { ClientMessage m = null; - if (timeoutSecs <= 0) - { + if (timeoutSecs <= 0) { m = consumer.receive(1); } - else - { + else { m = consumer.receive(timeoutSecs * 1000); } @@ -245,43 +218,47 @@ public class QueueConsumer return m; } - protected ClientMessage receive(long timeoutSecs) throws Exception - { + protected ClientMessage receive(long timeoutSecs) throws Exception { return receiveFromConsumer(timeoutSecs); } - protected void setPollTimeoutLinks(UriInfo info, String basePath, Response.ResponseBuilder builder, String index) - { + protected void setPollTimeoutLinks(UriInfo info, String basePath, Response.ResponseBuilder builder, String index) { setSessionLink(builder, info, basePath); setConsumeNextLink(serviceManager.getLinkStrategy(), builder, info, basePath, index); } - protected Response.ResponseBuilder getMessageResponse(ConsumedMessage msg, UriInfo info, String basePath, String index) - { + protected Response.ResponseBuilder getMessageResponse(ConsumedMessage msg, + UriInfo info, + String basePath, + String index) { Response.ResponseBuilder responseBuilder = Response.ok(); setMessageResponseLinks(info, basePath, responseBuilder, index); msg.build(responseBuilder); return responseBuilder; } - protected void setMessageResponseLinks(UriInfo info, String basePath, Response.ResponseBuilder responseBuilder, String index) - { + protected void setMessageResponseLinks(UriInfo info, + String basePath, + Response.ResponseBuilder responseBuilder, + String index) { setConsumeNextLink(serviceManager.getLinkStrategy(), responseBuilder, info, basePath, index); setSessionLink(responseBuilder, info, basePath); } - public static void setConsumeNextLink(LinkStrategy linkStrategy, Response.ResponseBuilder response, UriInfo info, String basePath, String index) - { - if (index == null) throw new IllegalArgumentException("index cannot be null"); + public static void setConsumeNextLink(LinkStrategy linkStrategy, + Response.ResponseBuilder response, + UriInfo info, + String basePath, + String index) { + if (index == null) + throw new IllegalArgumentException("index cannot be null"); UriBuilder builder = info.getBaseUriBuilder(); - builder.path(basePath) - .path("consume-next" + index); + builder.path(basePath).path("consume-next" + index); String uri = builder.build().toString(); linkStrategy.setLinkHeader(response, "consume-next", "consume-next", uri, MediaType.APPLICATION_FORM_URLENCODED); } - public void setSessionLink(Response.ResponseBuilder response, UriInfo info, String basePath) - { + public void setSessionLink(Response.ResponseBuilder response, UriInfo info, String basePath) { UriBuilder builder = info.getBaseUriBuilder(); builder.path(basePath); String uri = builder.build().toString(); diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/QueueDeployment.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/QueueDeployment.java index 9e5f9dcafa..d5105604b8 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/QueueDeployment.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/QueueDeployment.java @@ -16,27 +16,23 @@ */ package org.apache.activemq.artemis.rest.queue; -public class QueueDeployment extends DestinationSettings -{ +public class QueueDeployment extends DestinationSettings { + private String name; - public QueueDeployment() - { + public QueueDeployment() { } - public QueueDeployment(String name, boolean duplicatesAllowed) - { + public QueueDeployment(String name, boolean duplicatesAllowed) { this.name = name; this.duplicatesAllowed = duplicatesAllowed; } - public String getName() - { + public String getName() { return name; } - public void setName(String name) - { + public void setName(String name) { this.name = name; } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/QueueDestinationsResource.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/QueueDestinationsResource.java index 526af641e0..3f17af076d 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/QueueDestinationsResource.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/QueueDestinationsResource.java @@ -43,87 +43,71 @@ import org.apache.activemq.artemis.jms.server.config.impl.FileJMSConfiguration; import org.w3c.dom.Document; @Path(Constants.PATH_FOR_QUEUES) -public class QueueDestinationsResource -{ +public class QueueDestinationsResource { + private Map queues = new ConcurrentHashMap(); private QueueServiceManager manager; - public QueueDestinationsResource(QueueServiceManager manager) - { + public QueueDestinationsResource(QueueServiceManager manager) { this.manager = manager; } @POST @Consumes("application/activemq.jms.queue+xml") - public Response createJmsQueue(@Context UriInfo uriInfo, Document document) - { + public Response createJmsQueue(@Context UriInfo uriInfo, Document document) { ActiveMQRestLogger.LOGGER.debug("Handling POST request for \"" + uriInfo.getPath() + "\""); - try - { + try { JMSQueueConfiguration queue = FileJMSConfiguration.parseQueueConfiguration(document.getDocumentElement()); ActiveMQQueue activeMQQueue = ActiveMQDestination.createQueue(queue.getName()); String queueName = activeMQQueue.getAddress(); ClientSession session = manager.getSessionFactory().createSession(false, false, false); - try - { + try { ClientSession.QueueQuery query = session.queueQuery(new SimpleString(queueName)); - if (!query.isExists()) - { - if (queue.getSelector() != null) - { + if (!query.isExists()) { + if (queue.getSelector() != null) { session.createQueue(queueName, queueName, queue.getSelector(), queue.isDurable()); } - else - { + else { session.createQueue(queueName, queueName, queue.isDurable()); } } - else - { + else { throw new WebApplicationException(Response.status(412).type("text/plain").entity("Queue already exists.").build()); } } - finally - { - try - { + finally { + try { session.close(); } - catch (Exception ignored) - { + catch (Exception ignored) { } } URI uri = uriInfo.getRequestUriBuilder().path(queueName).build(); return Response.created(uri).build(); } - catch (Exception e) - { - if (e instanceof WebApplicationException) throw (WebApplicationException) e; + catch (Exception e) { + if (e instanceof WebApplicationException) + throw (WebApplicationException) e; throw new WebApplicationException(e, Response.serverError().type("text/plain").entity("Failed to create queue.").build()); } } - public Map getQueues() - { + public Map getQueues() { return queues; } @Path("/{queue-name}") - public synchronized QueueResource findQueue(@PathParam("queue-name") String name) throws Exception - { + public synchronized QueueResource findQueue(@PathParam("queue-name") String name) throws Exception { QueueResource queue = queues.get(name); - if (queue == null) - { + if (queue == null) { String queueName = name; ClientSession session = manager.getSessionFactory().createSession(false, false, false); - try - { + try { ClientSession.QueueQuery query = session.queueQuery(new SimpleString(queueName)); - if (!query.isExists()) - { + if (!query.isExists()) { throw new WebApplicationException(Response.status(404).type("text/plain").entity("Queue '" + name + "' does not exist").build()); } DestinationSettings queueSettings = manager.getDefaultSettings(); @@ -131,22 +115,21 @@ public class QueueDestinationsResource queue = createQueueResource(queueName, defaultDurable, queueSettings.getConsumerSessionTimeoutSeconds(), queueSettings.isDuplicatesAllowed()); } - finally - { - try - { + finally { + try { session.close(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { } } } return queue; } - public QueueResource createQueueResource(String queueName, boolean defaultDurable, int timeoutSeconds, boolean duplicates) throws Exception - { + public QueueResource createQueueResource(String queueName, + boolean defaultDurable, + int timeoutSeconds, + boolean duplicates) throws Exception { QueueResource queueResource = new QueueResource(); queueResource.setQueueDestinationsResource(this); queueResource.setDestination(queueName); @@ -165,12 +148,10 @@ public class QueueDestinationsResource queueResource.setPushConsumers(push); PostMessage sender = null; - if (duplicates) - { + if (duplicates) { sender = new PostMessageDupsOk(); } - else - { + else { sender = new PostMessageNoDups(); } sender.setServiceManager(manager); @@ -182,12 +163,10 @@ public class QueueDestinationsResource sender.init(); queueResource.setSender(sender); - if (manager.getPushStore() != null) - { + if (manager.getPushStore() != null) { push.setPushStore(manager.getPushStore()); List regs = manager.getPushStore().getByDestination(queueName); - for (PushRegistration reg : regs) - { + for (PushRegistration reg : regs) { push.addRegistration(reg); } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/QueueResource.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/QueueResource.java index 84cd98a8b6..869c38f6b2 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/QueueResource.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/QueueResource.java @@ -32,18 +32,16 @@ import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.rest.queue.push.PushConsumerResource; import org.apache.activemq.artemis.rest.ActiveMQRestLogger; -public class QueueResource extends DestinationResource -{ +public class QueueResource extends DestinationResource { + protected ConsumersResource consumers; protected PushConsumerResource pushConsumers; private QueueDestinationsResource queueDestinationsResource; - public void start() throws Exception - { + public void start() throws Exception { } - public void stop() - { + public void stop() { consumers.stop(); pushConsumers.stop(); sender.cleanup(); @@ -51,17 +49,11 @@ public class QueueResource extends DestinationResource @GET @Produces("application/xml") - public Response get(@Context UriInfo uriInfo, @Context HttpServletRequest requestContext) - { + public Response get(@Context UriInfo uriInfo, @Context HttpServletRequest requestContext) { ActiveMQRestLogger.LOGGER.debug("Handling GET request for \"" + destination + "\" from " + requestContext.getRemoteAddr() + ":" + requestContext.getRemotePort()); StringBuilder msg = new StringBuilder(); - msg.append("") - .append("").append(destination).append("") - .append("") - .append("") - .append("") - .append("") + msg.append("").append("").append(destination).append("").append("").append("").append("").append("") .append(""); @@ -75,8 +67,7 @@ public class QueueResource extends DestinationResource @HEAD @Produces("application/xml") - public Response head(@Context UriInfo uriInfo) - { + public Response head(@Context UriInfo uriInfo) { ActiveMQRestLogger.LOGGER.debug("Handling HEAD request for \"" + uriInfo.getRequestUri() + "\""); Response.ResponseBuilder builder = Response.ok(); @@ -87,28 +78,24 @@ public class QueueResource extends DestinationResource return builder.build(); } - protected void setSenderLink(Response.ResponseBuilder response, UriInfo info) - { + protected void setSenderLink(Response.ResponseBuilder response, UriInfo info) { String uri = createSenderLink(info); serviceManager.getLinkStrategy().setLinkHeader(response, "create", "create", uri, null); } - protected String createSenderLink(UriInfo info) - { + protected String createSenderLink(UriInfo info) { UriBuilder builder = info.getRequestUriBuilder(); builder.path("create"); String uri = builder.build().toString(); return uri; } - protected void setSenderWithIdLink(Response.ResponseBuilder response, UriInfo info) - { + protected void setSenderWithIdLink(Response.ResponseBuilder response, UriInfo info) { String uri = createSenderWithIdLink(info); serviceManager.getLinkStrategy().setLinkHeader(response, "create-with-id", "create-with-id", uri, null); } - protected String createSenderWithIdLink(UriInfo info) - { + protected String createSenderWithIdLink(UriInfo info) { UriBuilder builder = info.getRequestUriBuilder(); builder.path("create"); String uri = builder.build().toString(); @@ -116,92 +103,74 @@ public class QueueResource extends DestinationResource return uri; } - protected void setConsumersLink(Response.ResponseBuilder response, UriInfo info) - { + protected void setConsumersLink(Response.ResponseBuilder response, UriInfo info) { String uri = createConsumersLink(info); serviceManager.getLinkStrategy().setLinkHeader(response, "pull-consumers", "pull-consumers", uri, null); } - protected String createConsumersLink(UriInfo info) - { + protected String createConsumersLink(UriInfo info) { UriBuilder builder = info.getRequestUriBuilder(); builder.path("pull-consumers"); String uri = builder.build().toString(); return uri; } - protected void setPushConsumersLink(Response.ResponseBuilder response, UriInfo info) - { + protected void setPushConsumersLink(Response.ResponseBuilder response, UriInfo info) { String uri = createPushConsumersLink(info); serviceManager.getLinkStrategy().setLinkHeader(response, "push-consumers", "push-consumers", uri, null); } - protected String createPushConsumersLink(UriInfo info) - { + protected String createPushConsumersLink(UriInfo info) { UriBuilder builder = info.getRequestUriBuilder(); builder.path("push-consumers"); String uri = builder.build().toString(); return uri; } - - public void setConsumers(ConsumersResource consumers) - { + public void setConsumers(ConsumersResource consumers) { this.consumers = consumers; } @Path("create") - public PostMessage post() throws Exception - { + public PostMessage post() throws Exception { return sender; } - @Path("pull-consumers") - public ConsumersResource getConsumers() - { + public ConsumersResource getConsumers() { return consumers; } - public void setPushConsumers(PushConsumerResource pushConsumers) - { + public void setPushConsumers(PushConsumerResource pushConsumers) { this.pushConsumers = pushConsumers; } @Path("push-consumers") - public PushConsumerResource getPushConsumers() - { + public PushConsumerResource getPushConsumers() { return pushConsumers; } - public void setQueueDestinationsResource(QueueDestinationsResource queueDestinationsResource) - { + public void setQueueDestinationsResource(QueueDestinationsResource queueDestinationsResource) { this.queueDestinationsResource = queueDestinationsResource; } - @DELETE - public void deleteQueue(@Context UriInfo uriInfo) throws Exception - { + public void deleteQueue(@Context UriInfo uriInfo) throws Exception { ActiveMQRestLogger.LOGGER.debug("Handling DELETE request for \"" + uriInfo.getPath() + "\""); queueDestinationsResource.getQueues().remove(destination); stop(); ClientSession session = serviceManager.getSessionFactory().createSession(false, false, false); - try - { + try { SimpleString queueName = new SimpleString(destination); session.deleteQueue(queueName); } - finally - { - try - { + finally { + try { session.close(); } - catch (Exception ignored) - { + catch (Exception ignored) { } } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/QueueServiceManager.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/QueueServiceManager.java index fee8ecd601..1e643afe79 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/QueueServiceManager.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/QueueServiceManager.java @@ -24,73 +24,61 @@ import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.rest.queue.push.PushStore; import org.apache.activemq.artemis.rest.queue.push.FilePushStore; -public class QueueServiceManager extends DestinationServiceManager -{ +public class QueueServiceManager extends DestinationServiceManager { + protected PushStore pushStore; protected List queues = new ArrayList(); protected QueueDestinationsResource destination; - public List getQueues() - { + public List getQueues() { return queues; } - public void setQueues(List queues) - { + public void setQueues(List queues) { this.queues = queues; } - public PushStore getPushStore() - { + public PushStore getPushStore() { return pushStore; } - public void setPushStore(PushStore pushStore) - { + public void setPushStore(PushStore pushStore) { this.pushStore = pushStore; } - public QueueDestinationsResource getDestination() - { + public QueueDestinationsResource getDestination() { return destination; } - public void setDestination(QueueDestinationsResource destination) - { + public void setDestination(QueueDestinationsResource destination) { this.destination = destination; } @Override - public void start() throws Exception - { + public void start() throws Exception { initDefaults(); destination = new QueueDestinationsResource(this); started = true; - if (pushStoreFile != null && pushStore == null) - { + if (pushStoreFile != null && pushStore == null) { pushStore = new FilePushStore(pushStoreFile); } - for (QueueDeployment queueDeployment : queues) - { + for (QueueDeployment queueDeployment : queues) { deploy(queueDeployment); } } - public void deploy(QueueDeployment queueDeployment) throws Exception - { - if (!started) - { + public void deploy(QueueDeployment queueDeployment) throws Exception { + if (!started) { throw new Exception("You must start() this class instance before deploying"); } String queueName = queueDeployment.getName(); ClientSession session = sessionFactory.createSession(false, false, false); ClientSession.QueueQuery query = session.queueQuery(new SimpleString(queueName)); - if (!query.isExists()) - { + if (!query.isExists()) { session.createQueue(queueName, queueName, queueDeployment.isDurableSend()); } session.close(); @@ -100,20 +88,17 @@ public class QueueServiceManager extends DestinationServiceManager } @Override - public void stop() - { - if (started == false) return; - for (QueueResource queue : destination.getQueues().values()) - { + public void stop() { + if (started == false) + return; + for (QueueResource queue : destination.getQueues().values()) { queue.stop(); } - try - { + try { timeoutTask.stop(); sessionFactory.close(); } - catch (Exception e) - { + catch (Exception e) { } } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/ActiveMQPushStrategy.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/ActiveMQPushStrategy.java index 62230f1d4d..db5eb4a51f 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/ActiveMQPushStrategy.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/ActiveMQPushStrategy.java @@ -26,40 +26,33 @@ import org.jboss.resteasy.spi.Link; /** * Forwarding to an ActiveMQ/REST-* endpoing */ -public class ActiveMQPushStrategy extends UriTemplateStrategy -{ +public class ActiveMQPushStrategy extends UriTemplateStrategy { + protected boolean initialized = false; - public void start() throws Exception - { + public void start() throws Exception { // initialize(); } - protected void initialize() throws Exception - { + protected void initialize() throws Exception { super.start(); initialized = true; initAuthentication(); ClientRequest request = executor.createRequest(registration.getTarget().getHref()); - for (XmlHttpHeader header : registration.getHeaders()) - { + for (XmlHttpHeader header : registration.getHeaders()) { request.header(header.getName(), header.getValue()); } ClientResponse res = request.head(); - if (res.getStatus() != 200) - { + if (res.getStatus() != 200) { throw new RuntimeException("Failed to query REST destination for init information. Status: " + res.getStatus()); } - String url = (String)res.getHeaders().getFirst("msg-create-with-id"); - if (url == null) - { - if (res.getLinkHeader() == null) - { + String url = (String) res.getHeaders().getFirst("msg-create-with-id"); + if (url == null) { + if (res.getLinkHeader() == null) { throw new RuntimeException("Could not find create-with-id URL"); } Link link = res.getLinkHeader().getLinkByTitle("create-with-id"); - if (link == null) - { + if (link == null) { throw new RuntimeException("Could not find create-with-id URL"); } url = link.getHref(); @@ -68,18 +61,14 @@ public class ActiveMQPushStrategy extends UriTemplateStrategy } @Override - public boolean push(ClientMessage message) - { + public boolean push(ClientMessage message) { // we initialize lazily just in case target is in same VM - if (!initialized) - { - try - { + if (!initialized) { + try { initialize(); initialized = true; } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException("Failed to initialize.", e); } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/FilePushStore.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/FilePushStore.java index f719d677d6..f1bbe10923 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/FilePushStore.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/FilePushStore.java @@ -29,92 +29,83 @@ import org.apache.activemq.artemis.rest.ActiveMQRestLogger; import org.apache.activemq.artemis.rest.queue.push.xml.PushRegistration; import org.apache.activemq.artemis.rest.topic.PushTopicRegistration; -public class FilePushStore implements PushStore -{ +public class FilePushStore implements PushStore { + protected Map map = new HashMap(); protected File dir; protected JAXBContext ctx; - public FilePushStore(String dirname) throws Exception - { + public FilePushStore(String dirname) throws Exception { this.dir = new File(dirname); this.ctx = JAXBContext.newInstance(PushRegistration.class, PushTopicRegistration.class); - if (this.dir.exists()) - { + if (this.dir.exists()) { ActiveMQRestLogger.LOGGER.loadingRestStore(dir.getAbsolutePath()); - for (File file : this.dir.listFiles()) - { - if (!file.isFile()) continue; + for (File file : this.dir.listFiles()) { + if (!file.isFile()) + continue; PushRegistration reg = null; - try - { - reg = (PushRegistration)ctx.createUnmarshaller().unmarshal(file); + try { + reg = (PushRegistration) ctx.createUnmarshaller().unmarshal(file); reg.setLoadedFrom(file); ActiveMQRestLogger.LOGGER.addingPushRegistration(reg.getId()); map.put(reg.getId(), reg); } - catch (Exception e) - { + catch (Exception e) { ActiveMQRestLogger.LOGGER.errorLoadingStore(e, file.getName()); } } } } - public synchronized List getRegistrations() - { + public synchronized List getRegistrations() { List list = new ArrayList(map.values()); return list; } - public synchronized List getByDestination(String destination) - { + public synchronized List getByDestination(String destination) { List list = new ArrayList(); - for (PushRegistration reg : map.values()) - { - if (reg.getDestination().equals(destination)) - { + for (PushRegistration reg : map.values()) { + if (reg.getDestination().equals(destination)) { list.add(reg); } } return list; } - public synchronized void update(PushRegistration reg) throws Exception - { - if (reg.getLoadedFrom() == null) return; + public synchronized void update(PushRegistration reg) throws Exception { + if (reg.getLoadedFrom() == null) + return; save(reg); } - protected void save(PushRegistration reg) throws JAXBException - { + protected void save(PushRegistration reg) throws JAXBException { Marshaller marshaller = ctx.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - marshaller.marshal(reg, (File)reg.getLoadedFrom()); + marshaller.marshal(reg, (File) reg.getLoadedFrom()); } - public synchronized void add(PushRegistration reg) throws Exception - { + public synchronized void add(PushRegistration reg) throws Exception { map.put(reg.getId(), reg); - if (!this.dir.exists()) this.dir.mkdirs(); + if (!this.dir.exists()) + this.dir.mkdirs(); File fp = new File(dir, "reg-" + reg.getId() + ".xml"); reg.setLoadedFrom(fp); //System.out.println("******* Saving: " + fp.getAbsolutePath()); save(reg); } - public synchronized void remove(PushRegistration reg) throws Exception - { + public synchronized void remove(PushRegistration reg) throws Exception { map.remove(reg.getId()); - if (reg.getLoadedFrom() == null) return; - File fp = (File)reg.getLoadedFrom(); + if (reg.getLoadedFrom() == null) + return; + File fp = (File) reg.getLoadedFrom(); fp.delete(); } - public synchronized void removeAll() throws Exception - { + public synchronized void removeAll() throws Exception { ArrayList copy = new ArrayList(map.values()); - for (PushRegistration reg : copy) remove(reg); + for (PushRegistration reg : copy) + remove(reg); this.dir.delete(); } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/PushConsumer.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/PushConsumer.java index d2a7ce430e..906ff78d69 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/PushConsumer.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/PushConsumer.java @@ -27,8 +27,8 @@ import org.apache.activemq.artemis.rest.queue.push.xml.PushRegistration; import java.util.ArrayList; import java.util.List; -public class PushConsumer -{ +public class PushConsumer { + protected PushRegistration registration; protected ClientSessionFactory factory; protected List sessions; @@ -38,8 +38,11 @@ public class PushConsumer protected PushStrategy strategy; protected PushStore store; - public PushConsumer(ClientSessionFactory factory, String destination, String id, PushRegistration registration, PushStore store) - { + public PushConsumer(ClientSessionFactory factory, + String destination, + String id, + PushRegistration registration, + PushStore store) { this.factory = factory; this.destination = destination; this.id = id; @@ -47,41 +50,32 @@ public class PushConsumer this.store = store; } - public PushStrategy getStrategy() - { + public PushStrategy getStrategy() { return strategy; } - public PushRegistration getRegistration() - { + public PushRegistration getRegistration() { return registration; } - public String getDestination() - { + public String getDestination() { return destination; } - public void start() throws Exception - { - if (registration.getTarget().getClassName() != null) - { + public void start() throws Exception { + if (registration.getTarget().getClassName() != null) { Class clazz = Thread.currentThread().getContextClassLoader().loadClass(registration.getTarget().getClassName()); strategy = (PushStrategy) clazz.newInstance(); } - else if (registration.getTarget().getRelationship() != null) - { - if (registration.getTarget().getRelationship().equals("destination")) - { + else if (registration.getTarget().getRelationship() != null) { + if (registration.getTarget().getRelationship().equals("destination")) { strategy = new ActiveMQPushStrategy(); } - else if (registration.getTarget().getRelationship().equals("template")) - { + else if (registration.getTarget().getRelationship().equals("template")) { strategy = new UriTemplateStrategy(); } } - if (strategy == null) - { + if (strategy == null) { strategy = new UriStrategy(); } strategy.setRegistration(registration); @@ -90,18 +84,15 @@ public class PushConsumer sessions = new ArrayList(); consumers = new ArrayList(); - for (int i = 0; i < registration.getSessionCount(); i++) - { + for (int i = 0; i < registration.getSessionCount(); i++) { ClientSession session = factory.createSession(false, false, 0); ClientConsumer consumer; - if (registration.getSelector() != null) - { + if (registration.getSelector() != null) { consumer = session.createConsumer(destination, SelectorTranslator.convertToActiveMQFilterString(registration.getSelector())); } - else - { + else { consumer = session.createConsumer(destination); } consumer.setMessageHandler(new PushConsumerMessageHandler(this, session)); @@ -113,47 +104,35 @@ public class PushConsumer } } - public void stop() - { - for (ClientSession session : sessions) - { - try - { - if (session != null) - { + public void stop() { + for (ClientSession session : sessions) { + try { + if (session != null) { session.close(); } } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { } } - try - { - if (strategy != null) - { + try { + if (strategy != null) { strategy.stop(); } } - catch (Exception e) - { + catch (Exception e) { } } - public void disableFromFailure() - { + public void disableFromFailure() { registration.setEnabled(false); - try - { - if (registration.isDurable()) - { + try { + if (registration.isDurable()) { store.update(registration); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQRestLogger.LOGGER.errorUpdatingStore(e); } stop(); diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/PushConsumerMessageHandler.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/PushConsumerMessageHandler.java index f0dce06436..4ac2f80f2f 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/PushConsumerMessageHandler.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/PushConsumerMessageHandler.java @@ -22,60 +22,49 @@ import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.api.core.client.MessageHandler; import org.apache.activemq.artemis.rest.ActiveMQRestLogger; -public class PushConsumerMessageHandler implements MessageHandler -{ +public class PushConsumerMessageHandler implements MessageHandler { + private ClientSession session; private PushConsumer pushConsumer; - PushConsumerMessageHandler(PushConsumer pushConsumer, ClientSession session) - { + PushConsumerMessageHandler(PushConsumer pushConsumer, ClientSession session) { this.pushConsumer = pushConsumer; this.session = session; } @Override - public void onMessage(ClientMessage clientMessage) - { + public void onMessage(ClientMessage clientMessage) { ActiveMQRestLogger.LOGGER.debug(this + ": receiving " + clientMessage); - try - { + try { clientMessage.acknowledge(); ActiveMQRestLogger.LOGGER.debug(this + ": acknowledged " + clientMessage); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw new RuntimeException(e.getMessage(), e); } ActiveMQRestLogger.LOGGER.debug(this + ": pushing " + clientMessage + " via " + pushConsumer.getStrategy()); boolean acknowledge = pushConsumer.getStrategy().push(clientMessage); - if (acknowledge) - { - try - { + if (acknowledge) { + try { ActiveMQRestLogger.LOGGER.debug("Acknowledging: " + clientMessage.getMessageID()); session.commit(); return; } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw new RuntimeException(e); } } - else - { - try - { + else { + try { session.rollback(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw new RuntimeException(e.getMessage(), e); } - if (pushConsumer.getRegistration().isDisableOnFailure()) - { + if (pushConsumer.getRegistration().isDisableOnFailure()) { ActiveMQRestLogger.LOGGER.errorPushingMessage(pushConsumer.getRegistration().getTarget()); pushConsumer.disableFromFailure(); return; diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/PushConsumerResource.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/PushConsumerResource.java index 7bd225b255..d1a3f16f79 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/PushConsumerResource.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/PushConsumerResource.java @@ -36,8 +36,8 @@ import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.rest.queue.push.xml.PushRegistration; import org.apache.activemq.artemis.rest.ActiveMQRestLogger; -public class PushConsumerResource -{ +public class PushConsumerResource { + protected Map consumers = new ConcurrentHashMap(); protected ClientSessionFactory sessionFactory; protected String destination; @@ -45,32 +45,27 @@ public class PushConsumerResource protected final AtomicLong sessionCounter = new AtomicLong(1); protected PushStore pushStore; - public void start() - { + public void start() { } - public void stop() - { - for (PushConsumer consumer : consumers.values()) - { + public void stop() { + for (PushConsumer consumer : consumers.values()) { consumer.stop(); } } - public PushStore getPushStore() - { + public PushStore getPushStore() { return pushStore; } - public void setPushStore(PushStore pushStore) - { + public void setPushStore(PushStore pushStore) { this.pushStore = pushStore; } - public void addRegistration(PushRegistration reg) throws Exception - { - if (reg.isEnabled() == false) return; + public void addRegistration(PushRegistration reg) throws Exception { + if (reg.isEnabled() == false) + return; PushConsumer consumer = new PushConsumer(sessionFactory, destination, reg.getId(), reg, pushStore); consumer.start(); consumers.put(reg.getId(), consumer); @@ -78,8 +73,7 @@ public class PushConsumerResource @POST @Consumes("application/xml") - public Response create(@Context UriInfo uriInfo, PushRegistration registration) - { + public Response create(@Context UriInfo uriInfo, PushRegistration registration) { ActiveMQRestLogger.LOGGER.debug("Handling POST request for \"" + uriInfo.getPath() + "\""); // todo put some logic here to check for duplicates @@ -87,16 +81,13 @@ public class PushConsumerResource registration.setId(genId); registration.setDestination(destination); PushConsumer consumer = new PushConsumer(sessionFactory, destination, genId, registration, pushStore); - try - { + try { consumer.start(); - if (registration.isDurable() && pushStore != null) - { + if (registration.isDurable() && pushStore != null) { pushStore.add(registration); } } - catch (Exception e) - { + catch (Exception e) { consumer.stop(); throw new WebApplicationException(e, Response.serverError().entity("Failed to start consumer.").type("text/plain").build()); } @@ -110,13 +101,11 @@ public class PushConsumerResource @GET @Path("{consumer-id}") @Produces("application/xml") - public PushRegistration getConsumer(@Context UriInfo uriInfo, @PathParam("consumer-id") String consumerId) - { + public PushRegistration getConsumer(@Context UriInfo uriInfo, @PathParam("consumer-id") String consumerId) { ActiveMQRestLogger.LOGGER.debug("Handling GET request for \"" + uriInfo.getPath() + "\""); PushConsumer consumer = consumers.get(consumerId); - if (consumer == null) - { + if (consumer == null) { throw new WebApplicationException(Response.status(404).entity("Could not find consumer.").type("text/plain").build()); } return consumer.getRegistration(); @@ -124,40 +113,33 @@ public class PushConsumerResource @DELETE @Path("{consumer-id}") - public void deleteConsumer(@Context UriInfo uriInfo, @PathParam("consumer-id") String consumerId) - { + public void deleteConsumer(@Context UriInfo uriInfo, @PathParam("consumer-id") String consumerId) { ActiveMQRestLogger.LOGGER.debug("Handling DELETE request for \"" + uriInfo.getPath() + "\""); PushConsumer consumer = consumers.remove(consumerId); - if (consumer == null) - { + if (consumer == null) { throw new WebApplicationException(Response.status(404).entity("Could not find consumer.").type("text/plain").build()); } consumer.stop(); } - public Map getConsumers() - { + public Map getConsumers() { return consumers; } - public ClientSessionFactory getSessionFactory() - { + public ClientSessionFactory getSessionFactory() { return sessionFactory; } - public void setSessionFactory(ClientSessionFactory sessionFactory) - { + public void setSessionFactory(ClientSessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } - public String getDestination() - { + public String getDestination() { return destination; } - public void setDestination(String destination) - { + public void setDestination(String destination) { this.destination = destination; } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/PushStore.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/PushStore.java index 987bd5b953..e053347f87 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/PushStore.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/PushStore.java @@ -20,8 +20,8 @@ import org.apache.activemq.artemis.rest.queue.push.xml.PushRegistration; import java.util.List; -public interface PushStore -{ +public interface PushStore { + void add(PushRegistration reg) throws Exception; void remove(PushRegistration reg) throws Exception; diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/PushStrategy.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/PushStrategy.java index 0a8dcc1c3b..8812223b50 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/PushStrategy.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/PushStrategy.java @@ -19,8 +19,8 @@ package org.apache.activemq.artemis.rest.queue.push; import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.apache.activemq.artemis.rest.queue.push.xml.PushRegistration; -public interface PushStrategy -{ +public interface PushStrategy { + /** * Return false if unable to connect. Push consumer may be disabled if configured to do so when * unable to connect. Throw an exception if the message sent was unaccepted by the receiver. diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/UriStrategy.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/UriStrategy.java index 6539e2d41f..fcc7da8bb5 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/UriStrategy.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/UriStrategy.java @@ -48,8 +48,8 @@ import org.jboss.resteasy.client.ClientResponse; import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor; import org.jboss.resteasy.specimpl.ResteasyUriBuilder; -public class UriStrategy implements PushStrategy -{ +public class UriStrategy implements PushStrategy { + ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(); protected HttpClient client = new DefaultHttpClient(connManager); protected BasicHttpContext localContext; @@ -59,32 +59,27 @@ public class UriStrategy implements PushStrategy protected String method; protected String contentType; - UriStrategy() - { + UriStrategy() { connManager.setDefaultMaxPerRoute(100); connManager.setMaxTotal(1000); } - public void setRegistration(PushRegistration reg) - { + public void setRegistration(PushRegistration reg) { this.registration = reg; } - public void start() throws Exception - { + public void start() throws Exception { initAuthentication(); method = registration.getTarget().getMethod(); - if (method == null) method = "POST"; + if (method == null) + method = "POST"; contentType = registration.getTarget().getType(); targetUri = ResteasyUriBuilder.fromTemplate(registration.getTarget().getHref()); } - protected void initAuthentication() - { - if (registration.getAuthenticationMechanism() != null) - { - if (registration.getAuthenticationMechanism().getType() instanceof BasicAuth) - { + protected void initAuthentication() { + if (registration.getAuthenticationMechanism() != null) { + if (registration.getAuthenticationMechanism().getType() instanceof BasicAuth) { BasicAuth basic = (BasicAuth) registration.getAuthenticationMechanism().getType(); UsernamePasswordCredentials creds = new UsernamePasswordCredentials(basic.getUsername(), basic.getPassword()); AuthScope authScope = new AuthScope(AuthScope.ANY); @@ -103,58 +98,47 @@ public class UriStrategy implements PushStrategy } } - public void stop() - { + public void stop() { connManager.shutdown(); } - public boolean push(ClientMessage message) - { + public boolean push(ClientMessage message) { ActiveMQRestLogger.LOGGER.debug("Pushing " + message); String uri = createUri(message); - for (int i = 0; i < registration.getMaxRetries(); i++) - { + for (int i = 0; i < registration.getMaxRetries(); i++) { long wait = registration.getRetryWaitMillis(); System.out.println("Creating request from " + uri); ClientRequest request = executor.createRequest(uri); request.followRedirects(false); ActiveMQRestLogger.LOGGER.debug("Created request " + request); - for (XmlHttpHeader header : registration.getHeaders()) - { + for (XmlHttpHeader header : registration.getHeaders()) { ActiveMQRestLogger.LOGGER.debug("Setting XmlHttpHeader: " + header.getName() + "=" + header.getValue()); request.header(header.getName(), header.getValue()); } HttpMessageHelper.buildMessage(message, request, contentType); ClientResponse res = null; - try - { + try { ActiveMQRestLogger.LOGGER.debug(method + " " + uri); res = request.httpMethod(method); int status = res.getStatus(); ActiveMQRestLogger.LOGGER.debug("Status of push: " + status); - if (status == 503) - { + if (status == 503) { String retryAfter = res.getStringHeaders().getFirst("Retry-After"); - if (retryAfter != null) - { + if (retryAfter != null) { wait = Long.parseLong(retryAfter) * 1000; } } - else if (status == 307) - { + else if (status == 307) { uri = res.getLocation().toString(); wait = 0; } - else if ((status >= 200 && status < 299) || status == 303 || status == 304) - { + else if ((status >= 200 && status < 299) || status == 303 || status == 304) { ActiveMQRestLogger.LOGGER.debug("Success"); return true; } - else if (status >= 400) - { - switch (status) - { + else if (status >= 400) { + switch (status) { case 400: // these usually mean the message you are trying to send is crap, let dead letter logic take over case 411: case 412: @@ -182,52 +166,44 @@ public class UriStrategy implements PushStrategy } } } - catch (Exception e) - { + catch (Exception e) { ActiveMQRestLogger.LOGGER.debug("failed to push message to " + uri, e); e.printStackTrace(); return false; } - finally - { + finally { if (res != null) res.releaseConnection(); } - try - { - if (wait > 0) Thread.sleep(wait); + try { + if (wait > 0) + Thread.sleep(wait); } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new RuntimeException("Interrupted"); } } return false; } - protected String createUri(ClientMessage message) - { + protected String createUri(ClientMessage message) { String uri = targetUri.build().toString(); return uri; } - static class PreemptiveAuth implements HttpRequestInterceptor - { - public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException - { + static class PreemptiveAuth implements HttpRequestInterceptor { + + public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); // If no auth scheme available yet, try to initialize it preemptively - if (authState.getAuthScheme() == null) - { + if (authState.getAuthScheme() == null) { AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth"); CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); - if (authScheme != null) - { + if (authScheme != null) { Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort())); - if (creds == null) - { + if (creds == null) { throw new HttpException("No credentials for preemptive authentication"); } authState.setAuthScheme(authScheme); diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/UriTemplateStrategy.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/UriTemplateStrategy.java index f739628a7b..ee595e7fb6 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/UriTemplateStrategy.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/UriTemplateStrategy.java @@ -18,10 +18,9 @@ package org.apache.activemq.artemis.rest.queue.push; import org.apache.activemq.artemis.api.core.client.ClientMessage; -public class UriTemplateStrategy extends UriStrategy -{ - protected String createUri(ClientMessage message) - { +public class UriTemplateStrategy extends UriStrategy { + + protected String createUri(ClientMessage message) { String dupId = registration.getId() + "-" + message.getMessageID() + "-" + message.getTimestamp(); String uri = targetUri.build(dupId).toString(); return uri; diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/Authentication.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/Authentication.java index 341b9983f6..037ad8555b 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/Authentication.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/Authentication.java @@ -25,27 +25,24 @@ import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement @XmlAccessorType(XmlAccessType.PROPERTY) -public class Authentication implements Serializable -{ +public class Authentication implements Serializable { + private static final long serialVersionUID = -6218446923598032634L; private AuthenticationType type; @XmlElementRef - public AuthenticationType getType() - { + public AuthenticationType getType() { return type; } - public void setType(AuthenticationType type) - { + public void setType(AuthenticationType type) { this.type = type; } @Override - public String toString() - { + public String toString() { return "Authentication{" + - "type=" + type + - '}'; + "type=" + type + + '}'; } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/AuthenticationType.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/AuthenticationType.java index 38cc03ed7d..380bd04042 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/AuthenticationType.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/AuthenticationType.java @@ -20,7 +20,7 @@ import javax.xml.bind.annotation.XmlSeeAlso; import java.io.Serializable; @XmlSeeAlso({BasicAuth.class, DigestAuth.class}) -public class AuthenticationType implements Serializable -{ +public class AuthenticationType implements Serializable { + private static final long serialVersionUID = -4856752055689300045L; } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/BasicAuth.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/BasicAuth.java index 89c4955681..0392fbd39f 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/BasicAuth.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/BasicAuth.java @@ -21,35 +21,30 @@ import javax.xml.bind.annotation.XmlType; @XmlRootElement(name = "basic-auth") @XmlType(propOrder = {"username", "password"}) -public class BasicAuth extends AuthenticationType -{ +public class BasicAuth extends AuthenticationType { + private static final long serialVersionUID = 2052716241089832934L; private String username; private String password; - public String getUsername() - { + public String getUsername() { return username; } - public void setUsername(String username) - { + public void setUsername(String username) { this.username = username; } - public String getPassword() - { + public String getPassword() { return password; } - public void setPassword(String password) - { + public void setPassword(String password) { this.password = password; } @Override - public String toString() - { + public String toString() { return "BasicAuth{" + "username='" + username + '\'' + ", password='" + password + '\'' + diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/DigestAuth.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/DigestAuth.java index 4b2e966179..7ead7e8092 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/DigestAuth.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/DigestAuth.java @@ -19,7 +19,7 @@ package org.apache.activemq.artemis.rest.queue.push.xml; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "digest") -public class DigestAuth extends BasicAuth -{ +public class DigestAuth extends BasicAuth { + private static final long serialVersionUID = 1857805131477468686L; } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/PushRegistration.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/PushRegistration.java index 2321c2f62b..af3a12900c 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/PushRegistration.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/PushRegistration.java @@ -31,8 +31,8 @@ import java.util.List; @XmlRootElement(name = "push-registration") @XmlAccessorType(XmlAccessType.PROPERTY) @XmlType(propOrder = {"enabled", "destination", "durable", "selector", "target", "maxRetries", "retryWaitMillis", "disableOnFailure", "authenticationMechanism", "headers", "sessionCount"}) -public class PushRegistration implements Serializable -{ +public class PushRegistration implements Serializable { + private static final long serialVersionUID = -2749818399978544262L; private String id; private boolean durable; @@ -49,150 +49,123 @@ public class PushRegistration implements Serializable private int sessionCount = 1; @XmlElement - public int getMaxRetries() - { + public int getMaxRetries() { return maxRetries; } - public void setMaxRetries(int maxRetries) - { + public void setMaxRetries(int maxRetries) { this.maxRetries = maxRetries; } @XmlElement - public long getRetryWaitMillis() - { + public long getRetryWaitMillis() { return retryWaitMillis; } - public void setRetryWaitMillis(long retryWaitMillis) - { + public void setRetryWaitMillis(long retryWaitMillis) { this.retryWaitMillis = retryWaitMillis; } @XmlElement - public boolean isDisableOnFailure() - { + public boolean isDisableOnFailure() { return disableOnFailure; } - public void setDisableOnFailure(boolean disableOnFailure) - { + public void setDisableOnFailure(boolean disableOnFailure) { this.disableOnFailure = disableOnFailure; } @XmlElement - public boolean isEnabled() - { + public boolean isEnabled() { return enabled; } - public void setEnabled(boolean enabled) - { + public void setEnabled(boolean enabled) { this.enabled = enabled; } @XmlTransient - public Object getLoadedFrom() - { + public Object getLoadedFrom() { return loadedFrom; } - public void setLoadedFrom(Object loadedFrom) - { + public void setLoadedFrom(Object loadedFrom) { this.loadedFrom = loadedFrom; } @XmlAttribute - public String getId() - { + public String getId() { return id; } - public void setId(String id) - { + public void setId(String id) { this.id = id; } @XmlElement - public String getDestination() - { + public String getDestination() { return destination; } - public void setDestination(String destination) - { + public void setDestination(String destination) { this.destination = destination; } @XmlElement - public boolean isDurable() - { + public boolean isDurable() { return durable; } - public void setDurable(boolean durable) - { + public void setDurable(boolean durable) { this.durable = durable; } - public String getSelector() - { + public String getSelector() { return selector; } - public void setSelector(String selector) - { + public void setSelector(String selector) { this.selector = selector; } @XmlElementRef - public XmlLink getTarget() - { + public XmlLink getTarget() { return target; } - public void setTarget(XmlLink target) - { + public void setTarget(XmlLink target) { this.target = target; } @XmlElementRef - public Authentication getAuthenticationMechanism() - { + public Authentication getAuthenticationMechanism() { return authenticationMechanism; } - public void setAuthenticationMechanism(Authentication authenticationMechanism) - { + public void setAuthenticationMechanism(Authentication authenticationMechanism) { this.authenticationMechanism = authenticationMechanism; } @XmlElementRef - public List getHeaders() - { + public List getHeaders() { return headers; } - public void setHeaders(List headers) - { + public void setHeaders(List headers) { this.headers = headers; } @XmlElement - public int getSessionCount() - { + public int getSessionCount() { return sessionCount; } - public void setSessionCount(int sessionCount) - { + public void setSessionCount(int sessionCount) { this.sessionCount = sessionCount; } @Override - public String toString() - { + public String toString() { return "PushRegistration{" + "id='" + id + '\'' + ", durable=" + durable + diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/XmlHttpHeader.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/XmlHttpHeader.java index 5b02f786bd..b44468f9c2 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/XmlHttpHeader.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/XmlHttpHeader.java @@ -26,40 +26,35 @@ import javax.xml.bind.annotation.XmlValue; @XmlRootElement(name = "header") @XmlAccessorType(XmlAccessType.PROPERTY) -public class XmlHttpHeader implements Serializable -{ +public class XmlHttpHeader implements Serializable { + private static final long serialVersionUID = -3900391946161818601L; private String name; private String value; @XmlAttribute - public String getName() - { + public String getName() { return name; } - public void setName(String name) - { + public void setName(String name) { this.name = name; } @XmlValue - public String getValue() - { + public String getValue() { return value; } - public void setValue(String value) - { + public void setValue(String value) { this.value = value; } @Override - public String toString() - { + public String toString() { return "XmlHttpHeader{" + - "name='" + name + '\'' + - ", value='" + value + '\'' + - '}'; + "name='" + name + '\'' + + ", value='" + value + '\'' + + '}'; } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/XmlLink.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/XmlLink.java index 7c70da05ca..2cd4c09078 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/XmlLink.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/push/xml/XmlLink.java @@ -25,8 +25,8 @@ import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "link") @XmlAccessorType(XmlAccessType.PROPERTY) -public class XmlLink implements Serializable -{ +public class XmlLink implements Serializable { + private static final long serialVersionUID = -6517264072911034419L; protected String method; protected String className; @@ -35,69 +35,58 @@ public class XmlLink implements Serializable protected String href; @XmlAttribute(name = "class") - public String getClassName() - { + public String getClassName() { return className; } - public void setClassName(String className) - { + public void setClassName(String className) { this.className = className; } @XmlAttribute - public String getMethod() - { + public String getMethod() { return method; } - public void setMethod(String method) - { + public void setMethod(String method) { this.method = method; } @XmlAttribute(name = "rel") - public String getRelationship() - { + public String getRelationship() { return rel; } - public void setRelationship(String relationship) - { + public void setRelationship(String relationship) { rel = relationship; } @XmlAttribute - public String getHref() - { + public String getHref() { return href; } - public void setHref(String href) - { + public void setHref(String href) { this.href = href; } @XmlAttribute - public String getType() - { + public String getType() { return type; } - public void setType(String type) - { + public void setType(String type) { this.type = type; } @Override - public String toString() - { + public String toString() { return "XmlLink{" + - "className='" + className + '\'' + - ", rel='" + rel + '\'' + - ", href='" + href + '\'' + - ", type='" + type + '\'' + - ", method='" + method + '\'' + - '}'; + "className='" + className + '\'' + + ", rel='" + rel + '\'' + + ", href='" + href + '\'' + + ", type='" + type + '\'' + + ", method='" + method + '\'' + + '}'; } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/AcknowledgedSubscriptionResource.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/AcknowledgedSubscriptionResource.java index e3227057ad..93f7eddd3e 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/AcknowledgedSubscriptionResource.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/AcknowledgedSubscriptionResource.java @@ -21,46 +21,45 @@ import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.rest.queue.AcknowledgedQueueConsumer; import org.apache.activemq.artemis.rest.queue.DestinationServiceManager; -public class AcknowledgedSubscriptionResource extends AcknowledgedQueueConsumer implements Subscription -{ +public class AcknowledgedSubscriptionResource extends AcknowledgedQueueConsumer implements Subscription { + private boolean durable; private long timeout; private boolean deleteWhenIdle; - public AcknowledgedSubscriptionResource(ClientSessionFactory factory, String destination, String id, DestinationServiceManager serviceManager, String selector, boolean durable, Long timeout) throws ActiveMQException - { + public AcknowledgedSubscriptionResource(ClientSessionFactory factory, + String destination, + String id, + DestinationServiceManager serviceManager, + String selector, + boolean durable, + Long timeout) throws ActiveMQException { super(factory, destination, id, serviceManager, selector); this.timeout = timeout; this.durable = durable; } - public boolean isDurable() - { + public boolean isDurable() { return durable; } - public void setDurable(boolean durable) - { + public void setDurable(boolean durable) { this.durable = durable; } - public long getTimeout() - { + public long getTimeout() { return timeout; } - public void setTimeout(long timeout) - { + public void setTimeout(long timeout) { this.timeout = timeout; } - public boolean isDeleteWhenIdle() - { + public boolean isDeleteWhenIdle() { return deleteWhenIdle; } - public void setDeleteWhenIdle(boolean deleteWhenIdle) - { + public void setDeleteWhenIdle(boolean deleteWhenIdle) { this.deleteWhenIdle = deleteWhenIdle; } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/FileTopicPushStore.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/FileTopicPushStore.java index 0f8b1456c0..417b65d02c 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/FileTopicPushStore.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/FileTopicPushStore.java @@ -22,22 +22,18 @@ 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 -{ - public FileTopicPushStore(String dirname) throws Exception - { +public class FileTopicPushStore extends FilePushStore implements TopicPushStore { + + public FileTopicPushStore(String dirname) throws Exception { super(dirname); } @Override - public synchronized List getByTopic(String topic) - { + public synchronized List getByTopic(String topic) { List list = new ArrayList(); - for (PushRegistration reg : map.values()) - { - PushTopicRegistration topicReg = (PushTopicRegistration)reg; - if (topicReg.getTopic().equals(topic)) - { + for (PushRegistration reg : map.values()) { + PushTopicRegistration topicReg = (PushTopicRegistration) reg; + if (topicReg.getTopic().equals(topic)) { list.add(topicReg); } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/PushSubscription.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/PushSubscription.java index ae0a8750b2..da1cf34deb 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/PushSubscription.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/PushSubscription.java @@ -24,43 +24,40 @@ import org.apache.activemq.artemis.rest.ActiveMQRestLogger; import org.apache.activemq.artemis.rest.queue.push.PushConsumer; import org.apache.activemq.artemis.rest.queue.push.xml.PushRegistration; -public class PushSubscription extends PushConsumer -{ - public PushSubscription(ClientSessionFactory factory, String destination, String id, PushRegistration registration, PushStore store) - { +public class PushSubscription extends PushConsumer { + + public PushSubscription(ClientSessionFactory factory, + String destination, + String id, + PushRegistration registration, + PushStore store) { super(factory, destination, id, registration, store); } @Override - public void disableFromFailure() - { + public void disableFromFailure() { super.disableFromFailure(); - if (registration.isDurable()) deleteSubscriberQueue(); + if (registration.isDurable()) + deleteSubscriberQueue(); } - protected void deleteSubscriberQueue() - { + protected void deleteSubscriberQueue() { String subscriptionName = registration.getDestination(); ClientSession session = null; - try - { + try { session = factory.createSession(); session.deleteQueue(subscriptionName); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { ActiveMQRestLogger.LOGGER.errorDeletingSubscriberQueue(e); } - finally - { - try - { + finally { + try { if (session != null) session.close(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { } } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/PushSubscriptionsResource.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/PushSubscriptionsResource.java index 3ebf01a3e7..de4a16a90d 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/PushSubscriptionsResource.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/PushSubscriptionsResource.java @@ -38,8 +38,8 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; -public class PushSubscriptionsResource -{ +public class PushSubscriptionsResource { + protected Map consumers = new ConcurrentHashMap(); protected ClientSessionFactory sessionFactory; protected String destination; @@ -47,74 +47,60 @@ public class PushSubscriptionsResource protected final AtomicLong sessionCounter = new AtomicLong(1); protected TopicPushStore pushStore; - public void stop() - { - for (PushConsumer consumer : consumers.values()) - { + public void stop() { + for (PushConsumer consumer : consumers.values()) { consumer.stop(); - if (consumer.getRegistration().isDurable() == false) - { + if (consumer.getRegistration().isDurable() == false) { deleteSubscriberQueue(consumer); } } } - public TopicPushStore getPushStore() - { + public TopicPushStore getPushStore() { return pushStore; } - public void setPushStore(TopicPushStore pushStore) - { + public void setPushStore(TopicPushStore pushStore) { this.pushStore = pushStore; } - public ClientSession createSubscription(String subscriptionName, boolean durable) - { + public ClientSession createSubscription(String subscriptionName, boolean durable) { ClientSession session = null; - try - { + try { session = sessionFactory.createSession(); - if (durable) - { + if (durable) { session.createQueue(destination, subscriptionName, true); } - else - { + else { session.createTemporaryQueue(destination, subscriptionName); } return session; } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw new RuntimeException(e); } } - public void addRegistration(PushTopicRegistration reg) throws Exception - { - if (reg.isEnabled() == false) return; + public void addRegistration(PushTopicRegistration reg) throws Exception { + if (reg.isEnabled() == false) + return; String destination = reg.getDestination(); ClientSession session = sessionFactory.createSession(false, false, false); ClientSession.QueueQuery query = session.queueQuery(new SimpleString(destination)); ClientSession createSession = null; - if (!query.isExists()) - { + if (!query.isExists()) { createSession = createSubscription(destination, reg.isDurable()); } PushSubscription consumer = new PushSubscription(sessionFactory, reg.getDestination(), reg.getId(), reg, pushStore); - try - { + try { consumer.start(); } - catch (Exception e) - { + catch (Exception e) { consumer.stop(); throw new Exception("Failed starting push subscriber for " + destination + " of push subscriber: " + reg.getTarget(), e); } - finally - { + finally { closeSession(createSession); closeSession(session); } @@ -123,49 +109,38 @@ public class PushSubscriptionsResource } - private void closeSession(ClientSession createSession) - { - if (createSession != null) - { - try - { + private void closeSession(ClientSession createSession) { + if (createSession != null) { + try { createSession.close(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { } } } - @POST - public Response create(@Context UriInfo uriInfo, PushTopicRegistration registration) - { + public Response create(@Context UriInfo uriInfo, PushTopicRegistration registration) { ActiveMQRestLogger.LOGGER.debug("Handling POST request for \"" + uriInfo.getPath() + "\""); //System.out.println("PushRegistration: " + registration); // todo put some logic here to check for duplicates String genId = sessionCounter.getAndIncrement() + "-topic-" + destination + "-" + startup; - if (registration.getDestination() == null) - { + if (registration.getDestination() == null) { registration.setDestination(genId); } registration.setId(genId); registration.setTopic(destination); ClientSession createSession = createSubscription(genId, registration.isDurable()); - try - { + try { PushSubscription consumer = new PushSubscription(sessionFactory, genId, genId, registration, pushStore); - try - { + try { consumer.start(); - if (registration.isDurable() && pushStore != null) - { + if (registration.isDurable() && pushStore != null) { pushStore.add(registration); } } - catch (Exception e) - { + catch (Exception e) { consumer.stop(); throw new WebApplicationException(e, Response.serverError().entity("Failed to start consumer.").type("text/plain").build()); } @@ -175,8 +150,7 @@ public class PushSubscriptionsResource location.path(genId); return Response.created(location.build()).build(); } - finally - { + finally { closeSession(createSession); } } @@ -184,13 +158,11 @@ public class PushSubscriptionsResource @GET @Path("{consumer-id}") @Produces("application/xml") - public PushTopicRegistration getConsumer(@Context UriInfo uriInfo, @PathParam("consumer-id") String consumerId) - { + public PushTopicRegistration getConsumer(@Context UriInfo uriInfo, @PathParam("consumer-id") String consumerId) { ActiveMQRestLogger.LOGGER.debug("Handling GET request for \"" + uriInfo.getPath() + "\""); PushConsumer consumer = consumers.get(consumerId); - if (consumer == null) - { + if (consumer == null) { throw new WebApplicationException(Response.status(404).entity("Could not find consumer.").type("text/plain").build()); } return (PushTopicRegistration) consumer.getRegistration(); @@ -198,59 +170,48 @@ public class PushSubscriptionsResource @DELETE @Path("{consumer-id}") - public void deleteConsumer(@Context UriInfo uriInfo, @PathParam("consumer-id") String consumerId) - { + public void deleteConsumer(@Context UriInfo uriInfo, @PathParam("consumer-id") String consumerId) { ActiveMQRestLogger.LOGGER.debug("Handling DELETE request for \"" + uriInfo.getPath() + "\""); PushConsumer consumer = consumers.remove(consumerId); - if (consumer == null) - { + if (consumer == null) { throw new WebApplicationException(Response.status(404).entity("Could not find consumer.").type("text/plain").build()); } consumer.stop(); deleteSubscriberQueue(consumer); } - public Map getConsumers() - { + public Map getConsumers() { return consumers; } - public ClientSessionFactory getSessionFactory() - { + public ClientSessionFactory getSessionFactory() { return sessionFactory; } - public void setSessionFactory(ClientSessionFactory sessionFactory) - { + public void setSessionFactory(ClientSessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } - public String getDestination() - { + public String getDestination() { return destination; } - public void setDestination(String destination) - { + public void setDestination(String destination) { this.destination = destination; } - private void deleteSubscriberQueue(PushConsumer consumer) - { + private void deleteSubscriberQueue(PushConsumer consumer) { String subscriptionName = consumer.getDestination(); ClientSession session = null; - try - { + try { session = sessionFactory.createSession(); session.deleteQueue(subscriptionName); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { } - finally - { + finally { closeSession(session); } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/PushTopicRegistration.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/PushTopicRegistration.java index ad38523730..89d9a62a13 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/PushTopicRegistration.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/PushTopicRegistration.java @@ -27,19 +27,17 @@ import org.apache.activemq.artemis.rest.queue.push.xml.PushRegistration; @XmlRootElement(name = "push-topic-registration") @XmlAccessorType(XmlAccessType.PROPERTY) @XmlType(propOrder = {"topic"}) -public class PushTopicRegistration extends PushRegistration -{ +public class PushTopicRegistration extends PushRegistration { + private static final long serialVersionUID = -2526239344680405891L; private String topic; @XmlElement - public String getTopic() - { + public String getTopic() { return topic; } - public void setTopic(String topic) - { + public void setTopic(String topic) { this.topic = topic; } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/Subscription.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/Subscription.java index 9d75cb0246..1da22e5343 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/Subscription.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/Subscription.java @@ -16,8 +16,8 @@ */ package org.apache.activemq.artemis.rest.topic; -public interface Subscription -{ +public interface Subscription { + boolean isDurable(); void setDurable(boolean isDurable); diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/SubscriptionResource.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/SubscriptionResource.java index 8e3566aeae..fac54b6a97 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/SubscriptionResource.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/SubscriptionResource.java @@ -21,46 +21,45 @@ import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.rest.queue.DestinationServiceManager; import org.apache.activemq.artemis.rest.queue.QueueConsumer; -public class SubscriptionResource extends QueueConsumer implements Subscription -{ +public class SubscriptionResource extends QueueConsumer implements Subscription { + protected boolean durable; protected long timeout; private boolean deleteWhenIdle; - public SubscriptionResource(ClientSessionFactory factory, String destination, String id, DestinationServiceManager serviceManager, String selector, boolean durable, long timeout) throws ActiveMQException - { + public SubscriptionResource(ClientSessionFactory factory, + String destination, + String id, + DestinationServiceManager serviceManager, + String selector, + boolean durable, + long timeout) throws ActiveMQException { super(factory, destination, id, serviceManager, selector); this.durable = durable; this.timeout = timeout; } - public boolean isDurable() - { + public boolean isDurable() { return durable; } - public void setDurable(boolean durable) - { + public void setDurable(boolean durable) { this.durable = durable; } - public long getTimeout() - { + public long getTimeout() { return timeout; } - public void setTimeout(long timeout) - { + public void setTimeout(long timeout) { this.timeout = timeout; } - public boolean isDeleteWhenIdle() - { + public boolean isDeleteWhenIdle() { return deleteWhenIdle; } - public void setDeleteWhenIdle(boolean deleteWhenIdle) - { + public void setDeleteWhenIdle(boolean deleteWhenIdle) { this.deleteWhenIdle = deleteWhenIdle; } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/SubscriptionsResource.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/SubscriptionsResource.java index 444e8f42c2..005d7a0cd3 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/SubscriptionsResource.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/SubscriptionsResource.java @@ -44,8 +44,8 @@ import org.apache.activemq.artemis.rest.queue.DestinationServiceManager; import org.apache.activemq.artemis.rest.queue.QueueConsumer; import org.apache.activemq.artemis.rest.util.TimeoutTask; -public class SubscriptionsResource implements TimeoutTask.Callback -{ +public class SubscriptionsResource implements TimeoutTask.Callback { + protected ConcurrentMap queueConsumers = new ConcurrentHashMap(); protected ClientSessionFactory sessionFactory; protected String destination; @@ -54,92 +54,77 @@ public class SubscriptionsResource implements TimeoutTask.Callback protected int consumerTimeoutSeconds; protected DestinationServiceManager serviceManager; - public DestinationServiceManager getServiceManager() - { + public DestinationServiceManager getServiceManager() { return serviceManager; } - public void setServiceManager(DestinationServiceManager serviceManager) - { + public void setServiceManager(DestinationServiceManager serviceManager) { this.serviceManager = serviceManager; } - public int getConsumerTimeoutSeconds() - { + public int getConsumerTimeoutSeconds() { return consumerTimeoutSeconds; } - public void setConsumerTimeoutSeconds(int consumerTimeoutSeconds) - { + public void setConsumerTimeoutSeconds(int consumerTimeoutSeconds) { this.consumerTimeoutSeconds = consumerTimeoutSeconds; } - public ClientSessionFactory getSessionFactory() - { + public ClientSessionFactory getSessionFactory() { return sessionFactory; } - public void setSessionFactory(ClientSessionFactory sessionFactory) - { + public void setSessionFactory(ClientSessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } - public String getDestination() - { + public String getDestination() { return destination; } - public void setDestination(String destination) - { + public void setDestination(String destination) { this.destination = destination; } - public boolean testTimeout(String target, boolean autoShutdown) - { + public boolean testTimeout(String target, boolean autoShutdown) { QueueConsumer consumer = queueConsumers.get(target); Subscription subscription = (Subscription) consumer; - if (consumer == null) return false; - if (System.currentTimeMillis() - consumer.getLastPingTime() > subscription.getTimeout()) - { + if (consumer == null) + return false; + if (System.currentTimeMillis() - consumer.getLastPingTime() > subscription.getTimeout()) { ActiveMQRestLogger.LOGGER.shutdownRestSubscription(consumer.getId()); - if (autoShutdown) - { + if (autoShutdown) { shutdown(consumer); } return true; } - else - { + else { return false; } } - public void shutdown(String target) - { + public void shutdown(String target) { QueueConsumer consumer = queueConsumers.get(target); - if (consumer == null) return; + if (consumer == null) + return; shutdown(consumer); } - private void shutdown(QueueConsumer consumer) - { - synchronized (consumer) - { + private void shutdown(QueueConsumer consumer) { + synchronized (consumer) { consumer.shutdown(); queueConsumers.remove(consumer.getId()); Subscription subscription = (Subscription) consumer; - if (subscription.isDeleteWhenIdle()) deleteSubscriberQueue(consumer); + if (subscription.isDeleteWhenIdle()) + deleteSubscriberQueue(consumer); } } - public void stop() - { - for (QueueConsumer consumer : queueConsumers.values()) - { + public void stop() { + for (QueueConsumer consumer : queueConsumers.values()) { consumer.shutdown(); Subscription subscription = (Subscription) consumer; - if (!subscription.isDurable()) - { + if (!subscription.isDurable()) { deleteSubscriberQueue(consumer); } @@ -147,8 +132,7 @@ public class SubscriptionsResource implements TimeoutTask.Callback queueConsumers.clear(); } - protected String generateSubscriptionName() - { + protected String generateSubscriptionName() { return startup + "-" + sessionCounter.getAndIncrement() + "-" + destination; } @@ -159,69 +143,54 @@ public class SubscriptionsResource implements TimeoutTask.Callback @FormParam("selector") String selector, @FormParam("delete-when-idle") Boolean destroyWhenIdle, @FormParam("idle-timeout") Long timeout, - @Context UriInfo uriInfo) - { + @Context UriInfo uriInfo) { ActiveMQRestLogger.LOGGER.debug("Handling POST request for \"" + uriInfo.getPath() + "\""); if (timeout == null) timeout = Long.valueOf(consumerTimeoutSeconds * 1000); boolean deleteWhenIdle = !durable; // default is true if non-durable - if (destroyWhenIdle != null) deleteWhenIdle = destroyWhenIdle.booleanValue(); + if (destroyWhenIdle != null) + deleteWhenIdle = destroyWhenIdle.booleanValue(); - if (subscriptionName != null) - { + if (subscriptionName != null) { // see if this is a reconnect QueueConsumer consumer = queueConsumers.get(subscriptionName); - if (consumer != null) - { + if (consumer != null) { boolean acked = consumer instanceof AcknowledgedSubscriptionResource; acked = !acked; - if (acked != autoAck) - { - throw new WebApplicationException( - Response.status(412).entity("Consumer already exists and ack-modes don't match.").type("text/plain").build() - ); + if (acked != autoAck) { + throw new WebApplicationException(Response.status(412).entity("Consumer already exists and ack-modes don't match.").type("text/plain").build()); } Subscription sub = (Subscription) consumer; - if (sub.isDurable() != durable) - { - throw new WebApplicationException( - Response.status(412).entity("Consumer already exists and durability doesn't match.").type("text/plain").build() - ); + if (sub.isDurable() != durable) { + throw new WebApplicationException(Response.status(412).entity("Consumer already exists and durability doesn't match.").type("text/plain").build()); } Response.ResponseBuilder builder = Response.noContent(); String pathToPullSubscriptions = uriInfo.getMatchedURIs().get(0); - if (autoAck) - { + if (autoAck) { headAutoAckSubscriptionResponse(uriInfo, consumer, builder, pathToPullSubscriptions); consumer.setSessionLink(builder, uriInfo, pathToPullSubscriptions + "/auto-ack/" + consumer.getId()); } - else - { + else { headAcknowledgedConsumerResponse(uriInfo, (AcknowledgedQueueConsumer) consumer, builder); consumer.setSessionLink(builder, uriInfo, pathToPullSubscriptions + "/acknowledged/" + consumer.getId()); } return builder.build(); } } - else - { + else { subscriptionName = generateSubscriptionName(); } ClientSession session = null; - try - { + try { // if this is not a reconnect, create the subscription queue - if (!subscriptionExists(subscriptionName)) - { + if (!subscriptionExists(subscriptionName)) { session = sessionFactory.createSession(); - if (durable) - { + if (durable) { session.createQueue(destination, subscriptionName, true); } - else - { + else { session.createTemporaryQueue(destination, subscriptionName); } } @@ -230,53 +199,50 @@ public class SubscriptionsResource implements TimeoutTask.Callback serviceManager.getTimeoutTask().add(this, consumer.getId()); UriBuilder location = uriInfo.getAbsolutePathBuilder(); - if (autoAck) location.path("auto-ack"); - else location.path("acknowledged"); + if (autoAck) + location.path("auto-ack"); + else + location.path("acknowledged"); location.path(consumer.getId()); Response.ResponseBuilder builder = Response.created(location.build()); - if (autoAck) - { + if (autoAck) { QueueConsumer.setConsumeNextLink(serviceManager.getLinkStrategy(), builder, uriInfo, uriInfo.getMatchedURIs().get(0) + "/auto-ack/" + consumer.getId(), "-1"); } - else - { + else { AcknowledgedQueueConsumer.setAcknowledgeNextLink(serviceManager.getLinkStrategy(), builder, uriInfo, uriInfo.getMatchedURIs().get(0) + "/acknowledged/" + consumer.getId(), "-1"); } return builder.build(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw new RuntimeException(e); } - finally - { - if (session != null) - { - try - { + finally { + if (session != null) { + try { session.close(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { } } } } - protected QueueConsumer createConsumer(boolean durable, boolean autoAck, String subscriptionName, String selector, long timeout, boolean deleteWhenIdle) throws ActiveMQException - { + protected QueueConsumer createConsumer(boolean durable, + boolean autoAck, + String subscriptionName, + String selector, + long timeout, + boolean deleteWhenIdle) throws ActiveMQException { QueueConsumer consumer; - if (autoAck) - { + if (autoAck) { SubscriptionResource subscription = new SubscriptionResource(sessionFactory, subscriptionName, subscriptionName, serviceManager, selector, durable, timeout); subscription.setDurable(durable); subscription.setDeleteWhenIdle(deleteWhenIdle); consumer = subscription; } - else - { + else { AcknowledgedSubscriptionResource subscription = new AcknowledgedSubscriptionResource(sessionFactory, subscriptionName, subscriptionName, serviceManager, selector, durable, timeout); subscription.setDurable(durable); subscription.setDeleteWhenIdle(deleteWhenIdle); @@ -288,8 +254,7 @@ public class SubscriptionsResource implements TimeoutTask.Callback @Path("auto-ack/{consumer-id}") @GET public Response getAutoAckSubscription(@PathParam("consumer-id") String consumerId, - @Context UriInfo uriInfo) throws Exception - { + @Context UriInfo uriInfo) throws Exception { ActiveMQRestLogger.LOGGER.debug("Handling GET request for \"" + uriInfo.getPath() + "\""); return internalHeadAutoAckSubscription(uriInfo, consumerId); @@ -298,15 +263,13 @@ public class SubscriptionsResource implements TimeoutTask.Callback @Path("auto-ack/{consumer-id}") @HEAD public Response headAutoAckSubscription(@PathParam("consumer-id") String consumerId, - @Context UriInfo uriInfo) throws Exception - { + @Context UriInfo uriInfo) throws Exception { ActiveMQRestLogger.LOGGER.debug("Handling HEAD request for \"" + uriInfo.getPath() + "\""); return internalHeadAutoAckSubscription(uriInfo, consumerId); } - private Response internalHeadAutoAckSubscription(UriInfo uriInfo, String consumerId) - { + private Response internalHeadAutoAckSubscription(UriInfo uriInfo, String consumerId) { QueueConsumer consumer = findAutoAckSubscription(consumerId); Response.ResponseBuilder builder = Response.noContent(); String pathToPullSubscriptions = uriInfo.getMatchedURIs().get(1); @@ -315,22 +278,20 @@ public class SubscriptionsResource implements TimeoutTask.Callback return builder.build(); } - private void headAutoAckSubscriptionResponse(UriInfo uriInfo, QueueConsumer consumer, Response.ResponseBuilder builder, String pathToPullSubscriptions) - { + private void headAutoAckSubscriptionResponse(UriInfo uriInfo, + QueueConsumer consumer, + Response.ResponseBuilder builder, + String pathToPullSubscriptions) { // we synchronize just in case a failed request is still processing - synchronized (consumer) - { + synchronized (consumer) { QueueConsumer.setConsumeNextLink(serviceManager.getLinkStrategy(), builder, uriInfo, pathToPullSubscriptions + "/acknowledged/" + consumer.getId(), Long.toString(consumer.getConsumeIndex())); } } @Path("auto-ack/{subscription-id}") - public QueueConsumer findAutoAckSubscription( - @PathParam("subscription-id") String subscriptionId) - { + public QueueConsumer findAutoAckSubscription(@PathParam("subscription-id") String subscriptionId) { QueueConsumer consumer = queueConsumers.get(subscriptionId); - if (consumer == null) - { + if (consumer == null) { consumer = recreateTopicConsumer(subscriptionId, true); } return consumer; @@ -339,8 +300,7 @@ public class SubscriptionsResource implements TimeoutTask.Callback @Path("acknowledged/{consumer-id}") @GET public Response getAcknowledgedConsumer(@PathParam("consumer-id") String consumerId, - @Context UriInfo uriInfo) throws Exception - { + @Context UriInfo uriInfo) throws Exception { ActiveMQRestLogger.LOGGER.debug("Handling GET request for \"" + uriInfo.getPath() + "\""); return internalHeadAcknowledgedConsumer(uriInfo, consumerId); @@ -349,15 +309,13 @@ public class SubscriptionsResource implements TimeoutTask.Callback @Path("acknowledged/{consumer-id}") @HEAD public Response headAcknowledgedConsumer(@PathParam("consumer-id") String consumerId, - @Context UriInfo uriInfo) throws Exception - { + @Context UriInfo uriInfo) throws Exception { ActiveMQRestLogger.LOGGER.debug("Handling HEAD request for \"" + uriInfo.getPath() + "\""); return internalHeadAcknowledgedConsumer(uriInfo, consumerId); } - private Response internalHeadAcknowledgedConsumer(UriInfo uriInfo, String consumerId) - { + private Response internalHeadAcknowledgedConsumer(UriInfo uriInfo, String consumerId) { AcknowledgedQueueConsumer consumer = (AcknowledgedQueueConsumer) findAcknoledgeSubscription(consumerId); Response.ResponseBuilder builder = Response.ok(); headAcknowledgedConsumerResponse(uriInfo, consumer, builder); @@ -365,103 +323,80 @@ public class SubscriptionsResource implements TimeoutTask.Callback return builder.build(); } - private void headAcknowledgedConsumerResponse(UriInfo uriInfo, AcknowledgedQueueConsumer consumer, Response.ResponseBuilder builder) - { + private void headAcknowledgedConsumerResponse(UriInfo uriInfo, + AcknowledgedQueueConsumer consumer, + Response.ResponseBuilder builder) { // we synchronize just in case a failed request is still processing - synchronized (consumer) - { + synchronized (consumer) { Acknowledgement ack = consumer.getAck(); - if (ack == null || ack.wasSet()) - { + if (ack == null || ack.wasSet()) { AcknowledgedQueueConsumer.setAcknowledgeNextLink(serviceManager.getLinkStrategy(), builder, uriInfo, uriInfo.getMatchedURIs().get(1) + "/acknowledged/" + consumer.getId(), Long.toString(consumer.getConsumeIndex())); } - else - { + else { consumer.setAcknowledgementLink(builder, uriInfo, uriInfo.getMatchedURIs().get(1) + "/acknowledged/" + consumer.getId()); } } } @Path("acknowledged/{subscription-id}") - public QueueConsumer findAcknoledgeSubscription( - @PathParam("subscription-id") String subscriptionId) - { + public QueueConsumer findAcknoledgeSubscription(@PathParam("subscription-id") String subscriptionId) { QueueConsumer consumer = queueConsumers.get(subscriptionId); - if (consumer == null) - { + if (consumer == null) { consumer = recreateTopicConsumer(subscriptionId, false); } return consumer; } - private boolean subscriptionExists(String subscriptionId) - { + private boolean subscriptionExists(String subscriptionId) { ClientSession session = null; - try - { + try { session = sessionFactory.createSession(); ClientSession.QueueQuery query = session.queueQuery(new SimpleString(subscriptionId)); return query.isExists(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw new RuntimeException(e); } - finally - { - if (session != null) - { - try - { + finally { + if (session != null) { + try { session.close(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { } } } } - private QueueConsumer recreateTopicConsumer(String subscriptionId, boolean autoAck) - { + private QueueConsumer recreateTopicConsumer(String subscriptionId, boolean autoAck) { QueueConsumer consumer; - if (subscriptionExists(subscriptionId)) - { + if (subscriptionExists(subscriptionId)) { QueueConsumer tmp = null; - try - { + try { tmp = createConsumer(true, autoAck, subscriptionId, null, consumerTimeoutSeconds * 1000, false); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw new RuntimeException(e); } consumer = queueConsumers.putIfAbsent(subscriptionId, tmp); - if (consumer == null) - { + if (consumer == null) { consumer = tmp; serviceManager.getTimeoutTask().add(this, subscriptionId); } - else - { + else { tmp.shutdown(); } } - else - { - throw new WebApplicationException(Response.status(405) - .entity("Failed to find subscriber " + subscriptionId + " you will have to reconnect") - .type("text/plain").build()); + else { + throw new WebApplicationException(Response.status(405).entity("Failed to find subscriber " + subscriptionId + " you will have to reconnect").type("text/plain").build()); } return consumer; } - @Path("acknowledged/{subscription-id}") @DELETE - public void deleteAckSubscription(@Context UriInfo uriInfo, @PathParam("subscription-id") String consumerId) - { + public void deleteAckSubscription(@Context UriInfo uriInfo, @PathParam("subscription-id") String consumerId) { ActiveMQRestLogger.LOGGER.debug("Handling DELETE request for \"" + uriInfo.getPath() + "\""); internalDeleteSubscription(consumerId); @@ -469,50 +404,38 @@ public class SubscriptionsResource implements TimeoutTask.Callback @Path("auto-ack/{subscription-id}") @DELETE - public void deleteSubscription(@Context UriInfo uriInfo, @PathParam("subscription-id") String consumerId) - { + public void deleteSubscription(@Context UriInfo uriInfo, @PathParam("subscription-id") String consumerId) { ActiveMQRestLogger.LOGGER.debug("Handling DELETE request for \"" + uriInfo.getPath() + "\""); internalDeleteSubscription(consumerId); } - private void internalDeleteSubscription(String consumerId) - { + private void internalDeleteSubscription(String consumerId) { QueueConsumer consumer = queueConsumers.remove(consumerId); - if (consumer == null) - { + if (consumer == null) { String msg = "Failed to match a subscription to URL " + consumerId; - throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND) - .entity(msg) - .type("text/plain").build()); + throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).entity(msg).type("text/plain").build()); } consumer.shutdown(); deleteSubscriberQueue(consumer); } - private void deleteSubscriberQueue(QueueConsumer consumer) - { + private void deleteSubscriberQueue(QueueConsumer consumer) { String subscriptionName = consumer.getId(); ClientSession session = null; - try - { + try { session = sessionFactory.createSession(); session.deleteQueue(subscriptionName); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { } - finally - { - if (session != null) - { - try - { + finally { + if (session != null) { + try { session.close(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { } } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/TopicDeployment.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/TopicDeployment.java index f8d28d7ef9..938e45de8d 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/TopicDeployment.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/TopicDeployment.java @@ -18,27 +18,23 @@ package org.apache.activemq.artemis.rest.topic; import org.apache.activemq.artemis.rest.queue.DestinationSettings; -public class TopicDeployment extends DestinationSettings -{ +public class TopicDeployment extends DestinationSettings { + private String name; - public TopicDeployment() - { + public TopicDeployment() { } - public TopicDeployment(String name, boolean duplicatesAllowed) - { + public TopicDeployment(String name, boolean duplicatesAllowed) { this.name = name; this.duplicatesAllowed = duplicatesAllowed; } - public String getName() - { + public String getName() { return name; } - public void setName(String name) - { + public void setName(String name) { this.name = name; } } \ No newline at end of file diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/TopicDestinationsResource.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/TopicDestinationsResource.java index e9e33728a7..e084b03e35 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/TopicDestinationsResource.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/TopicDestinationsResource.java @@ -44,75 +44,61 @@ import org.apache.activemq.artemis.rest.queue.PostMessageNoDups; import org.w3c.dom.Document; @Path("/topics") -public class TopicDestinationsResource -{ +public class TopicDestinationsResource { + private Map topics = new ConcurrentHashMap(); private TopicServiceManager manager; - public TopicDestinationsResource(TopicServiceManager manager) - { + public TopicDestinationsResource(TopicServiceManager manager) { this.manager = manager; } @POST @Consumes("application/activemq.jms.topic+xml") - public Response createJmsQueue(@Context UriInfo uriInfo, Document document) - { + public Response createJmsQueue(@Context UriInfo uriInfo, Document document) { ActiveMQRestLogger.LOGGER.debug("Handling POST request for \"" + uriInfo.getPath() + "\""); - try - { + try { TopicConfiguration topic = FileJMSConfiguration.parseTopicConfiguration(document.getDocumentElement()); ActiveMQTopic activeMQTopic = ActiveMQDestination.createTopic(topic.getName()); String topicName = activeMQTopic.getAddress(); ClientSession session = manager.getSessionFactory().createSession(false, false, false); - try - { + try { ClientSession.QueueQuery query = session.queueQuery(new SimpleString(topicName)); - if (!query.isExists()) - { + if (!query.isExists()) { session.createQueue(topicName, topicName, "__AMQX=-1", true); } - else - { + else { throw new WebApplicationException(Response.status(412).type("text/plain").entity("Queue already exists.").build()); } } - finally - { - try - { + finally { + try { session.close(); } - catch (Exception ignored) - { + catch (Exception ignored) { } } URI uri = uriInfo.getRequestUriBuilder().path(topicName).build(); return Response.created(uri).build(); } - catch (Exception e) - { - if (e instanceof WebApplicationException) throw (WebApplicationException) e; + catch (Exception e) { + if (e instanceof WebApplicationException) + throw (WebApplicationException) e; throw new WebApplicationException(e, Response.serverError().type("text/plain").entity("Failed to create queue.").build()); } } - @Path("/{topic-name}") - public TopicResource findTopic(@PathParam("topic-name") String name) throws Exception - { + public TopicResource findTopic(@PathParam("topic-name") String name) throws Exception { TopicResource topic = topics.get(name); - if (topic == null) - { + if (topic == null) { ClientSession session = manager.getSessionFactory().createSession(false, false, false); - try - { + try { ClientSession.QueueQuery query = session.queueQuery(new SimpleString(name)); - if (!query.isExists()) - { + if (!query.isExists()) { System.err.println("Topic '" + name + "' does not exist"); throw new WebApplicationException(Response.status(404).type("text/plain").entity("Topic '" + name + "' does not exist").build()); } @@ -121,27 +107,25 @@ public class TopicDestinationsResource topic = createTopicResource(name, defaultDurable, queueSettings.getConsumerSessionTimeoutSeconds(), queueSettings.isDuplicatesAllowed()); } - finally - { - try - { + finally { + try { session.close(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { } } } return topic; } - public Map getTopics() - { + public Map getTopics() { return topics; } - public TopicResource createTopicResource(String topicName, boolean defaultDurable, int timeoutSeconds, boolean duplicates) throws Exception - { + public TopicResource createTopicResource(String topicName, + boolean defaultDurable, + int timeoutSeconds, + boolean duplicates) throws Exception { TopicResource topicResource = new TopicResource(); topicResource.setTopicDestinationsResource(this); topicResource.setDestination(topicName); @@ -159,12 +143,10 @@ public class TopicDestinationsResource topicResource.setPushSubscriptions(push); PostMessage sender = null; - if (duplicates) - { + if (duplicates) { sender = new PostMessageDupsOk(); } - else - { + else { sender = new PostMessageNoDups(); } sender.setDefaultDurable(defaultDurable); @@ -176,12 +158,10 @@ public class TopicDestinationsResource sender.init(); topicResource.setSender(sender); - if (manager.getPushStore() != null) - { + if (manager.getPushStore() != null) { push.setPushStore(manager.getPushStore()); List regs = manager.getPushStore().getByTopic(topicName); - for (PushTopicRegistration reg : regs) - { + for (PushTopicRegistration reg : regs) { push.addRegistration(reg); } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/TopicPushStore.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/TopicPushStore.java index 56097410aa..fd8f51a309 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/TopicPushStore.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/TopicPushStore.java @@ -20,7 +20,7 @@ import org.apache.activemq.artemis.rest.queue.push.PushStore; import java.util.List; -public interface TopicPushStore extends PushStore -{ +public interface TopicPushStore extends PushStore { + List getByTopic(String topic); } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/TopicResource.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/TopicResource.java index b7bd8cb72b..85a8616921 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/TopicResource.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/TopicResource.java @@ -32,18 +32,16 @@ import org.apache.activemq.artemis.rest.ActiveMQRestLogger; import org.apache.activemq.artemis.rest.queue.DestinationResource; import org.apache.activemq.artemis.rest.queue.PostMessage; -public class TopicResource extends DestinationResource -{ +public class TopicResource extends DestinationResource { + protected SubscriptionsResource subscriptions; protected PushSubscriptionsResource pushSubscriptions; private TopicDestinationsResource topicDestinationsResource; - public void start() throws Exception - { + public void start() throws Exception { } - public void stop() - { + public void stop() { subscriptions.stop(); pushSubscriptions.stop(); sender.cleanup(); @@ -51,17 +49,11 @@ public class TopicResource extends DestinationResource @GET @Produces("application/xml") - public Response get(@Context UriInfo uriInfo) - { + public Response get(@Context UriInfo uriInfo) { ActiveMQRestLogger.LOGGER.debug("Handling GET request for \"" + uriInfo.getPath() + "\""); StringBuilder msg = new StringBuilder(); - msg.append("") - .append("").append(destination).append("") - .append("") - .append("") - .append("") - .append("") + msg.append("").append("").append(destination).append("").append("").append("").append("").append("") .append(""); @@ -75,8 +67,7 @@ public class TopicResource extends DestinationResource @HEAD @Produces("application/xml") - public Response head(@Context UriInfo uriInfo) - { + public Response head(@Context UriInfo uriInfo) { ActiveMQRestLogger.LOGGER.debug("Handling HEAD request for \"" + uriInfo.getPath() + "\""); Response.ResponseBuilder builder = Response.ok(); @@ -87,28 +78,24 @@ public class TopicResource extends DestinationResource return builder.build(); } - protected void setSenderLink(Response.ResponseBuilder response, UriInfo info) - { + protected void setSenderLink(Response.ResponseBuilder response, UriInfo info) { String uri = createSenderLink(info); serviceManager.getLinkStrategy().setLinkHeader(response, "create", "create", uri, null); } - protected String createSenderLink(UriInfo info) - { + protected String createSenderLink(UriInfo info) { UriBuilder builder = info.getRequestUriBuilder(); builder.path("create"); String uri = builder.build().toString(); return uri; } - protected void setSenderWithIdLink(Response.ResponseBuilder response, UriInfo info) - { + protected void setSenderWithIdLink(Response.ResponseBuilder response, UriInfo info) { String uri = createSenderWithIdLink(info); serviceManager.getLinkStrategy().setLinkHeader(response, "create-with-id", "create-with-id", uri, null); } - protected String createSenderWithIdLink(UriInfo info) - { + protected String createSenderWithIdLink(UriInfo info) { UriBuilder builder = info.getRequestUriBuilder(); builder.path("create"); String uri = builder.build().toString(); @@ -116,99 +103,81 @@ public class TopicResource extends DestinationResource return uri; } - protected void setSubscriptionsLink(Response.ResponseBuilder response, UriInfo info) - { + protected void setSubscriptionsLink(Response.ResponseBuilder response, UriInfo info) { String uri = createSubscriptionsLink(info); serviceManager.getLinkStrategy().setLinkHeader(response, "pull-subscriptions", "pull-subscriptions", uri, null); } - protected String createSubscriptionsLink(UriInfo info) - { + protected String createSubscriptionsLink(UriInfo info) { UriBuilder builder = info.getRequestUriBuilder(); builder.path("pull-subscriptions"); String uri = builder.build().toString(); return uri; } - protected void setPushSubscriptionsLink(Response.ResponseBuilder response, UriInfo info) - { + protected void setPushSubscriptionsLink(Response.ResponseBuilder response, UriInfo info) { String uri = createPushSubscriptionsLink(info); serviceManager.getLinkStrategy().setLinkHeader(response, "push-subscriptions", "push-subscriptions", uri, null); } - protected String createPushSubscriptionsLink(UriInfo info) - { + protected String createPushSubscriptionsLink(UriInfo info) { UriBuilder builder = info.getRequestUriBuilder(); builder.path("push-subscriptions"); String uri = builder.build().toString(); return uri; } - public void setSubscriptions(SubscriptionsResource subscriptions) - { + public void setSubscriptions(SubscriptionsResource subscriptions) { this.subscriptions = subscriptions; } @Path("create") - public PostMessage post() throws Exception - { + public PostMessage post() throws Exception { return sender; } - @Path("pull-subscriptions") - public SubscriptionsResource getSubscriptions() - { + public SubscriptionsResource getSubscriptions() { return subscriptions; } @Path("push-subscriptions") - public PushSubscriptionsResource getPushSubscriptions() - { + public PushSubscriptionsResource getPushSubscriptions() { return pushSubscriptions; } - public void setPushSubscriptions(PushSubscriptionsResource pushSubscriptions) - { + public void setPushSubscriptions(PushSubscriptionsResource pushSubscriptions) { this.pushSubscriptions = pushSubscriptions; } @DELETE - public void deleteTopic(@Context UriInfo uriInfo) throws Exception - { + public void deleteTopic(@Context UriInfo uriInfo) throws Exception { ActiveMQRestLogger.LOGGER.debug("Handling DELETE request for \"" + uriInfo.getPath() + "\""); topicDestinationsResource.getTopics().remove(destination); - try - { + try { stop(); } - catch (Exception ignored) - { + catch (Exception ignored) { } ClientSession session = serviceManager.getSessionFactory().createSession(false, false, false); - try - { + try { SimpleString topicName = new SimpleString(destination); session.deleteQueue(topicName); } - finally - { - try - { + finally { + try { session.close(); } - catch (Exception ignored) - { + catch (Exception ignored) { } } } - public void setTopicDestinationsResource(TopicDestinationsResource topicDestinationsResource) - { + public void setTopicDestinationsResource(TopicDestinationsResource topicDestinationsResource) { this.topicDestinationsResource = topicDestinationsResource; } } \ No newline at end of file diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/TopicServiceManager.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/TopicServiceManager.java index 59c34d57c8..a6bece1aee 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/TopicServiceManager.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/topic/TopicServiceManager.java @@ -23,80 +23,66 @@ import org.apache.activemq.artemis.rest.queue.DestinationServiceManager; import java.util.ArrayList; import java.util.List; -public class TopicServiceManager extends DestinationServiceManager -{ +public class TopicServiceManager extends DestinationServiceManager { + protected TopicPushStore pushStore; protected List topics = new ArrayList(); protected TopicDestinationsResource destination; - public TopicPushStore getPushStore() - { + public TopicPushStore getPushStore() { return pushStore; } - public void setPushStore(TopicPushStore pushStore) - { + public void setPushStore(TopicPushStore pushStore) { this.pushStore = pushStore; } - public List getTopics() - { + public List getTopics() { return topics; } - public void setTopics(List topics) - { + public void setTopics(List topics) { this.topics = topics; } - public TopicDestinationsResource getDestination() - { + public TopicDestinationsResource getDestination() { return destination; } - public void setDestination(TopicDestinationsResource destination) - { + public void setDestination(TopicDestinationsResource destination) { this.destination = destination; } - public void start() throws Exception - { + public void start() throws Exception { initDefaults(); started = true; - if (pushStoreFile != null && pushStore == null) - { + if (pushStoreFile != null && pushStore == null) { pushStore = new FileTopicPushStore(pushStoreFile); } - if (destination == null) - { + if (destination == null) { destination = new TopicDestinationsResource(this); } - for (TopicDeployment topic : topics) - { + for (TopicDeployment topic : topics) { deploy(topic); } } - public void deploy(TopicDeployment topicDeployment) throws Exception - { - if (!started) - { + public void deploy(TopicDeployment topicDeployment) throws Exception { + if (!started) { throw new Exception("You must start() this class instance before deploying"); } String queueName = topicDeployment.getName(); ClientSession session = sessionFactory.createSession(false, false, false); ClientSession.QueueQuery query = session.queueQuery(new SimpleString(queueName)); boolean defaultDurable = topicDeployment.isDurableSend(); - if (query.isExists()) - { + if (query.isExists()) { defaultDurable = query.isDurable(); } - else - { + else { session.createQueue(queueName, queueName, topicDeployment.isDurableSend()); } session.close(); @@ -104,19 +90,16 @@ public class TopicServiceManager extends DestinationServiceManager destination.createTopicResource(queueName, defaultDurable, topicDeployment.getConsumerSessionTimeoutSeconds(), topicDeployment.isDuplicatesAllowed()); } - public void stop() - { - if (started == false) return; - for (TopicResource topic : destination.getTopics().values()) - { + public void stop() { + if (started == false) + return; + for (TopicResource topic : destination.getTopics().values()) { topic.stop(); } - try - { + try { sessionFactory.close(); } - catch (Exception e) - { + catch (Exception e) { } } } \ No newline at end of file diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/util/Constants.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/util/Constants.java index b4b8b47456..9eb990ae97 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/util/Constants.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/util/Constants.java @@ -16,8 +16,8 @@ */ package org.apache.activemq.artemis.rest.util; -public interface Constants -{ +public interface Constants { + String WAIT_HEADER = "Accept-Wait"; String PATH_FOR_QUEUES = "/queues"; } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/util/CustomHeaderLinkStrategy.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/util/CustomHeaderLinkStrategy.java index 7a8e28ade4..702f226d5b 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/util/CustomHeaderLinkStrategy.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/util/CustomHeaderLinkStrategy.java @@ -18,27 +18,22 @@ package org.apache.activemq.artemis.rest.util; import javax.ws.rs.core.Response; -public class CustomHeaderLinkStrategy implements LinkStrategy -{ - public void setLinkHeader(Response.ResponseBuilder builder, String title, String rel, String href, String type) - { +public class CustomHeaderLinkStrategy implements LinkStrategy { + + public void setLinkHeader(Response.ResponseBuilder builder, String title, String rel, String href, String type) { String headerName = null; - if (title != null) - { + if (title != null) { headerName = title; } - else if (rel != null) - { + else if (rel != null) { headerName = rel; } - else - { + else { throw new RuntimeException("Cannot figure out header name"); } headerName = "msg-" + headerName; builder.header(headerName, href); - if (type != null) - { + if (type != null) { builder.header(headerName + "-type", type); } } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/util/HttpMessageHelper.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/util/HttpMessageHelper.java index 203c53924e..989453d718 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/util/HttpMessageHelper.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/util/HttpMessageHelper.java @@ -30,49 +30,40 @@ import java.io.ObjectInputStream; import java.util.List; import java.util.Map.Entry; -public class HttpMessageHelper -{ +public class HttpMessageHelper { + public static final String POSTED_AS_HTTP_MESSAGE = "postedAsHttpMessage"; - public static boolean isTransferableHttpHeader(String key) - { + public static boolean isTransferableHttpHeader(String key) { String lowerKey = key.toLowerCase(); return lowerKey.toLowerCase().startsWith("content") || lowerKey.toLowerCase().equals("link"); } - public static void buildMessage(ClientMessage message, Response.ResponseBuilder builder) - { - for (SimpleString key : message.getPropertyNames()) - { + public static void buildMessage(ClientMessage message, Response.ResponseBuilder builder) { + for (SimpleString key : message.getPropertyNames()) { String k = key.toString(); String headerName = HttpHeaderProperty.fromPropertyName(k); - if (headerName == null) - { + if (headerName == null) { continue; } builder.header(headerName, message.getStringProperty(k)); } int size = message.getBodySize(); - if (size > 0) - { + if (size > 0) { byte[] body = new byte[size]; message.getBodyBuffer().readBytes(body); Boolean aBoolean = message.getBooleanProperty(POSTED_AS_HTTP_MESSAGE); - if (aBoolean != null && aBoolean.booleanValue()) - { + if (aBoolean != null && aBoolean.booleanValue()) { builder.entity(body); } - else - { + else { ByteArrayInputStream bais = new ByteArrayInputStream(body); Object obj = null; - try - { + try { ObjectInputStream ois = new ObjectInputStream(bais); obj = ois.readObject(); } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } builder.entity(obj); @@ -80,14 +71,11 @@ public class HttpMessageHelper } } - public static void buildMessage(ClientMessage message, ClientRequest request, String contentType) - { - for (SimpleString key : message.getPropertyNames()) - { + public static void buildMessage(ClientMessage message, ClientRequest request, String contentType) { + for (SimpleString key : message.getPropertyNames()) { String k = key.toString(); String headerName = HttpHeaderProperty.fromPropertyName(k); - if (headerName == null || headerName.contains("content-length")) - { + if (headerName == null || headerName.contains("content-length")) { continue; } String value = message.getStringProperty(k); @@ -95,55 +83,46 @@ public class HttpMessageHelper request.header(headerName, value); ActiveMQRestLogger.LOGGER.debug("Examining " + headerName + ": " + value); // override default content type if it is set as a message property - if (headerName.equalsIgnoreCase("content-type")) - { + if (headerName.equalsIgnoreCase("content-type")) { contentType = value; ActiveMQRestLogger.LOGGER.debug("Using contentType: " + contentType); } } int size = message.getBodySize(); - if (size > 0) - { + if (size > 0) { Boolean aBoolean = message.getBooleanProperty(POSTED_AS_HTTP_MESSAGE); - if (aBoolean != null && aBoolean.booleanValue()) - { + if (aBoolean != null && aBoolean.booleanValue()) { byte[] body = new byte[size]; message.getBodyBuffer().readBytes(body); ActiveMQRestLogger.LOGGER.debug("Building Message from HTTP message"); request.body(contentType, body); } - else - { + else { // assume posted as a JMS or ActiveMQ Artemis object message size = message.getBodyBuffer().readInt(); byte[] body = new byte[size]; message.getBodyBuffer().readBytes(body); ByteArrayInputStream bais = new ByteArrayInputStream(body); Object obj = null; - try - { + try { ObjectInputStream ois = new ObjectInputStream(bais); obj = ois.readObject(); ActiveMQRestLogger.LOGGER.debug("**** Building Message from object: " + obj.toString()); request.body(contentType, obj); } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } } } } - public static void writeHttpMessage(HttpHeaders headers, byte[] body, ClientMessage message) throws Exception - { + public static void writeHttpMessage(HttpHeaders headers, byte[] body, ClientMessage message) throws Exception { MultivaluedMap hdrs = headers.getRequestHeaders(); - for (Entry> entry : hdrs.entrySet()) - { + for (Entry> entry : hdrs.entrySet()) { String key = entry.getKey(); - if (isTransferableHttpHeader(key)) - { + if (isTransferableHttpHeader(key)) { List vals = entry.getValue(); String value = concatenateHeaderValue(vals); message.putStringProperty(HttpHeaderProperty.toPropertyName(key), value); @@ -153,17 +132,13 @@ public class HttpMessageHelper message.getBodyBuffer().writeBytes(body); } - public static String concatenateHeaderValue(List vals) - { - if (vals == null) - { + public static String concatenateHeaderValue(List vals) { + if (vals == null) { return ""; } StringBuilder val = new StringBuilder(); - for (String v : vals) - { - if (val.length() > 0) - { + for (String v : vals) { + if (val.length() > 0) { val.append(","); } val.append(v); diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/util/LinkHeaderLinkStrategy.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/util/LinkHeaderLinkStrategy.java index fe13deb030..a4dfea6b4e 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/util/LinkHeaderLinkStrategy.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/util/LinkHeaderLinkStrategy.java @@ -20,8 +20,8 @@ import org.jboss.resteasy.spi.Link; import javax.ws.rs.core.Response; -public class LinkHeaderLinkStrategy implements LinkStrategy -{ +public class LinkHeaderLinkStrategy implements LinkStrategy { + /** * @param builder * @param title user friendly name @@ -29,14 +29,12 @@ public class LinkHeaderLinkStrategy implements LinkStrategy * @param href * @param type */ - public void setLinkHeader(Response.ResponseBuilder builder, String title, String rel, String href, String type) - { + public void setLinkHeader(Response.ResponseBuilder builder, String title, String rel, String href, String type) { Link link = new Link(title, rel, href, type, null); setLinkHeader(builder, link); } - public void setLinkHeader(Response.ResponseBuilder builder, Link link) - { + public void setLinkHeader(Response.ResponseBuilder builder, Link link) { builder.header("Link", link); } diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/util/LinkStrategy.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/util/LinkStrategy.java index cff9ff31a4..e49f8f5f4c 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/util/LinkStrategy.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/util/LinkStrategy.java @@ -18,7 +18,7 @@ package org.apache.activemq.artemis.rest.util; import javax.ws.rs.core.Response; -public interface LinkStrategy -{ +public interface LinkStrategy { + void setLinkHeader(Response.ResponseBuilder builder, String title, String rel, String href, String type); } \ No newline at end of file diff --git a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/util/TimeoutTask.java b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/util/TimeoutTask.java index bc13bf2fbe..0e5d496a0f 100644 --- a/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/util/TimeoutTask.java +++ b/artemis-rest/src/main/java/org/apache/activemq/artemis/rest/util/TimeoutTask.java @@ -25,8 +25,8 @@ import java.util.concurrent.locks.ReentrantLock; import org.apache.activemq.artemis.rest.ActiveMQRestLogger; -public class TimeoutTask implements Runnable -{ +public class TimeoutTask implements Runnable { + protected boolean running = true; protected int interval = 10; protected final Lock callbacksLock = new ReentrantLock(); @@ -35,90 +35,71 @@ public class TimeoutTask implements Runnable protected Map pendingCallbacks = new HashMap(); protected Thread thread; - public TimeoutTask(int interval) - { + public TimeoutTask(int interval) { this.interval = interval; } - public interface Callback - { + public interface Callback { + boolean testTimeout(String token, boolean autoShutdown); void shutdown(String token); } - public synchronized void add(Callback callback, String token) - { - if (callbacksLock.tryLock()) - { - try - { + public synchronized void add(Callback callback, String token) { + if (callbacksLock.tryLock()) { + try { callbacks.put(token, callback); } - finally - { + finally { callbacksLock.unlock(); } } - else - { + else { pendingCallbacksLock.lock(); - try - { + try { pendingCallbacks.put(token, callback); } - finally - { + finally { pendingCallbacksLock.unlock(); } } } - public synchronized void remove(String token) - { + public synchronized void remove(String token) { callbacksLock.lock(); - try - { + try { callbacks.remove(token); } - finally - { + finally { callbacksLock.unlock(); } } - public synchronized void stop() - { + public synchronized void stop() { running = false; thread.interrupt(); } - public synchronized int getInterval() - { + public synchronized int getInterval() { return interval; } - public synchronized void setInterval(int interval) - { + public synchronized void setInterval(int interval) { this.interval = interval; } - public void start() - { + public void start() { thread = new Thread(this); thread.start(); } - public void run() - { - while (running) - { - try - { + public void run() { + while (running) { + try { Thread.sleep(interval * 1000); } - catch (InterruptedException e) - { + catch (InterruptedException e) { running = false; break; } @@ -131,64 +112,52 @@ public class TimeoutTask implements Runnable int deadConsumers = 0; callbacksLock.lock(); - try - { + try { long startTime = System.currentTimeMillis(); List tokens = new ArrayList(callbacks.size()); - for (String token : callbacks.keySet()) - { + for (String token : callbacks.keySet()) { tokens.add(token); } - for (String token : tokens) - { + for (String token : tokens) { Callback callback = callbacks.get(token); - if (callback.testTimeout(token, false)) - { + if (callback.testTimeout(token, false)) { deadConsumers += 1; expiredCallbacks.put(token, callback); callbacks.remove(token); } - else - { + else { liveConsumers += 1; } } ActiveMQRestLogger.LOGGER.debug("Finished testing callbacks for timeouts in " + - (System.currentTimeMillis() - startTime) + "ms. " + - "(Live: " + liveConsumers + ", Expired: " + deadConsumers + ")"); + (System.currentTimeMillis() - startTime) + "ms. " + + "(Live: " + liveConsumers + ", Expired: " + deadConsumers + ")"); // Next, move any pending callback additions to the main callbacks map. pendingCallbacksLock.lock(); - try - { - if (pendingCallbacks.size() > 0) - { + try { + if (pendingCallbacks.size() > 0) { ActiveMQRestLogger.LOGGER.debug("Found " + pendingCallbacks.size() + " callbacks to add."); callbacks.putAll(pendingCallbacks); pendingCallbacks.clear(); } } - finally - { + finally { pendingCallbacksLock.unlock(); } } - finally - { + finally { callbacksLock.unlock(); } // Finally, freely shutdown all expired consumers. - if (expiredCallbacks.size() > 0) - { + if (expiredCallbacks.size() > 0) { long startTime = System.currentTimeMillis(); List tokens = new ArrayList(expiredCallbacks.size()); - for (String token : expiredCallbacks.keySet()) - { + for (String token : expiredCallbacks.keySet()) { tokens.add(token); } - for (String token : tokens) - { + for (String token : tokens) { Callback expired = expiredCallbacks.get(token); expired.shutdown(token); } diff --git a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/AutoAckQueueTest.java b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/AutoAckQueueTest.java index eefd818ffe..e7ef1fd238 100644 --- a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/AutoAckQueueTest.java +++ b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/AutoAckQueueTest.java @@ -25,11 +25,10 @@ import org.jboss.resteasy.test.TestPortProvider; import org.junit.Assert; import org.junit.Test; -public class AutoAckQueueTest extends MessageTestBase -{ +public class AutoAckQueueTest extends MessageTestBase { + @Test - public void testSuccessFirst() throws Exception - { + public void testSuccessFirst() throws Exception { String testName = "testSuccessFirst"; QueueDeployment deployment = new QueueDeployment(); deployment.setDuplicatesAllowed(true); diff --git a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/AutoAckTopicTest.java b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/AutoAckTopicTest.java index 04cbbce050..6d23b2c4dc 100644 --- a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/AutoAckTopicTest.java +++ b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/AutoAckTopicTest.java @@ -24,11 +24,10 @@ import org.jboss.resteasy.test.TestPortProvider; import org.junit.Assert; import org.junit.Test; -public class AutoAckTopicTest extends MessageTestBase -{ +public class AutoAckTopicTest extends MessageTestBase { + @Test - public void testSuccessFirst() throws Exception - { + public void testSuccessFirst() throws Exception { String testName = "AutoAckTopicTest.testSuccessFirst"; TopicDeployment deployment = new TopicDeployment(); deployment.setDuplicatesAllowed(true); @@ -44,7 +43,6 @@ public class AutoAckTopicTest extends MessageTestBase Link sender = getLinkByTitle(manager.getTopicManager().getLinkStrategy(), response, "create"); Link subscriptions = getLinkByTitle(manager.getTopicManager().getLinkStrategy(), response, "pull-subscriptions"); - ClientResponse res = subscriptions.request().post(); res.releaseConnection(); Assert.assertEquals(201, res.getStatus()); @@ -54,7 +52,6 @@ public class AutoAckTopicTest extends MessageTestBase Assert.assertNotNull(consumeNext1); System.out.println("consumeNext1: " + consumeNext1); - res = subscriptions.request().post(); res.releaseConnection(); Assert.assertEquals(201, res.getStatus()); @@ -64,7 +61,6 @@ public class AutoAckTopicTest extends MessageTestBase Assert.assertNotNull(consumeNext2); System.out.println("consumeNext2: " + consumeNext2); - res = sender.request().body("text/plain", "1").post(); res.releaseConnection(); Assert.assertEquals(201, res.getStatus()); @@ -100,8 +96,7 @@ public class AutoAckTopicTest extends MessageTestBase } @Test - public void testNewSubNotBlockedByTimeoutTask() throws Exception - { + public void testNewSubNotBlockedByTimeoutTask() throws Exception { // Default config is 1s interval, 300s timeout. // Create a topic @@ -149,31 +144,26 @@ public class AutoAckTopicTest extends MessageTestBase t.interrupt(); } - private class NewPullSubscriber implements Runnable - { + private class NewPullSubscriber implements Runnable { + private final String url; private boolean isFinished = false; private boolean failed = false; - public NewPullSubscriber(String url) - { + public NewPullSubscriber(String url) { this.url = url; } - public boolean isFinished() - { + public boolean isFinished() { return isFinished; } - public boolean isFailed() - { + public boolean isFailed() { return failed; } - public void run() - { - try - { + public void run() { + try { isFinished = false; ClientRequest request = new ClientRequest(url); ClientResponse response = request.post(); @@ -182,48 +172,41 @@ public class AutoAckTopicTest extends MessageTestBase Assert.assertEquals(201, response.getStatus()); isFinished = true; } - catch (Exception e) - { + catch (Exception e) { System.out.println("Exception " + e); failed = true; } } } - private class AcceptWaitListener implements Runnable - { + private class AcceptWaitListener implements Runnable { + private final int acceptWaitTime = 8; private String url; private boolean isFinished = false; private boolean failed = false; - public AcceptWaitListener(String url) - { + public AcceptWaitListener(String url) { this.url = url; } - public boolean isFinished() - { + public boolean isFinished() { return this.isFinished; } - public boolean isFailed() - { + public boolean isFailed() { return this.failed; } - public void run() - { - try - { + public void run() { + try { ClientRequest req = new ClientRequest(url); req.header("Accept-Wait", acceptWaitTime); ClientResponse response = req.post(); response.releaseConnection(); isFinished = true; } - catch (Exception e) - { + catch (Exception e) { failed = true; } } diff --git a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/ClientAckQueueTest.java b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/ClientAckQueueTest.java index 059174816e..4a61d59328 100644 --- a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/ClientAckQueueTest.java +++ b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/ClientAckQueueTest.java @@ -29,19 +29,16 @@ import org.junit.Test; import static org.jboss.resteasy.test.TestPortProvider.generateURL; -public class ClientAckQueueTest extends MessageTestBase -{ +public class ClientAckQueueTest extends MessageTestBase { @BeforeClass - public static void setup() throws Exception - { + public static void setup() throws Exception { QueueDeployment deployment1 = new QueueDeployment("testQueue", true); manager.getQueueManager().deploy(deployment1); } @Test - public void testAckTimeoutX2() throws Exception - { + public void testAckTimeoutX2() throws Exception { QueueDeployment deployment = new QueueDeployment(); deployment.setConsumerSessionTimeoutSeconds(1); deployment.setDuplicatesAllowed(true); @@ -55,8 +52,7 @@ public class ClientAckQueueTest extends MessageTestBase testAckTimeout(); } - public void testAckTimeout() throws Exception - { + public void testAckTimeout() throws Exception { ClientRequest request = new ClientRequest(generateURL("/queues/testAck")); ClientResponse response = Util.head(request); @@ -74,7 +70,6 @@ public class ClientAckQueueTest extends MessageTestBase res.releaseConnection(); Assert.assertEquals(201, res.getStatus()); - res = consumeNext.request().post(String.class); res.releaseConnection(); Assert.assertEquals(200, res.getStatus()); @@ -109,21 +104,18 @@ public class ClientAckQueueTest extends MessageTestBase System.out.println("consumeNext: " + consumeNext); ClientResponse ackRes = ack.request().formParameter("acknowledge", "true").post(); - if (ackRes.getStatus() != 204) - { + if (ackRes.getStatus() != 204) { System.out.println(ackRes.getEntity(String.class)); } ackRes.releaseConnection(); Assert.assertEquals(204, ackRes.getStatus()); - Assert.assertEquals(204, session.request().delete().getStatus()); } } @Test - public void testSuccessFirstX2() throws Exception - { + public void testSuccessFirstX2() throws Exception { String testName = "testSuccessFirstX2"; QueueDeployment queueDeployment = new QueueDeployment(testName, true); @@ -135,8 +127,7 @@ public class ClientAckQueueTest extends MessageTestBase testSuccessFirst(3, testName); } - public void testSuccessFirst(int start, String queueName) throws Exception - { + public void testSuccessFirst(int start, String queueName) throws Exception { ClientRequest request = new ClientRequest(generateURL(Util.getUrlPath(queueName))); ClientResponse response = Util.head(request); @@ -202,8 +193,7 @@ public class ClientAckQueueTest extends MessageTestBase } @Test - public void testPullX2() throws Exception - { + public void testPullX2() throws Exception { String testName = "testPullX2"; QueueDeployment queueDeployment = new QueueDeployment(testName, true); @@ -215,8 +205,7 @@ public class ClientAckQueueTest extends MessageTestBase testPull(4, testName); } - public void testPull(int start, String queueName) throws Exception - { + public void testPull(int start, String queueName) throws Exception { ClientRequest request = new ClientRequest(generateURL(Util.getUrlPath(queueName))); ClientResponse response = Util.head(request); @@ -255,7 +244,6 @@ public class ClientAckQueueTest extends MessageTestBase res.releaseConnection(); Assert.assertEquals(201, res.getStatus()); - res = consumeNext.request().post(String.class); Assert.assertEquals(200, res.getStatus()); Assert.assertEquals(Integer.toString(start++), res.getEntity()); @@ -287,8 +275,7 @@ public class ClientAckQueueTest extends MessageTestBase } @Test - public void testReconnectX2() throws Exception - { + public void testReconnectX2() throws Exception { String testName = "testReconnectX2"; QueueDeployment queueDeployment = new QueueDeployment(testName, true); @@ -300,8 +287,7 @@ public class ClientAckQueueTest extends MessageTestBase testReconnect(testName); } - public void testReconnect(String queueName) throws Exception - { + public void testReconnect(String queueName) throws Exception { ClientRequest request = new ClientRequest(generateURL(Util.getUrlPath(queueName))); ClientResponse response = Util.head(request); @@ -340,7 +326,6 @@ public class ClientAckQueueTest extends MessageTestBase res.releaseConnection(); Assert.assertEquals(201, res.getStatus()); - res = consumeNext.request().header(Constants.WAIT_HEADER, "10").post(String.class); res.releaseConnection(); Assert.assertEquals(200, res.getStatus()); diff --git a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/ClientAckTopicTest.java b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/ClientAckTopicTest.java index a92d6725df..c4a89f46e4 100644 --- a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/ClientAckTopicTest.java +++ b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/ClientAckTopicTest.java @@ -28,19 +28,16 @@ import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -public class ClientAckTopicTest extends MessageTestBase -{ +public class ClientAckTopicTest extends MessageTestBase { @BeforeClass - public static void setup() throws Exception - { + public static void setup() throws Exception { TopicDeployment deployment1 = new TopicDeployment("testQueue", true); manager.getTopicManager().deploy(deployment1); } @Test - public void testAckTimeoutX2() throws Exception - { + public void testAckTimeoutX2() throws Exception { TopicDeployment deployment = new TopicDeployment(); deployment.setConsumerSessionTimeoutSeconds(1); deployment.setDuplicatesAllowed(true); @@ -54,10 +51,7 @@ public class ClientAckTopicTest extends MessageTestBase testAckTimeout(); } - - public void testAckTimeout() throws Exception - { - + public void testAckTimeout() throws Exception { ClientRequest request = new ClientRequest(TestPortProvider.generateURL("/topics/testAck")); @@ -67,15 +61,12 @@ public class ClientAckTopicTest extends MessageTestBase Link sender = getLinkByTitle(manager.getTopicManager().getLinkStrategy(), response, "create"); System.out.println("create: " + sender); Link subscriptions = getLinkByTitle(manager.getTopicManager().getLinkStrategy(), response, "pull-subscriptions"); - response = subscriptions.request().formParameter("autoAck", "false") - .formParameter("durable", "true") - .post(); + response = subscriptions.request().formParameter("autoAck", "false").formParameter("durable", "true").post(); response.releaseConnection(); Assert.assertEquals(201, response.getStatus()); Link sub1 = response.getLocationLink(); Assert.assertNotNull(sub1); - Link consumeNext = getLinkByTitle(manager.getTopicManager().getLinkStrategy(), response, "acknowledge-next"); System.out.println("poller: " + consumeNext); @@ -84,7 +75,6 @@ public class ClientAckTopicTest extends MessageTestBase res.releaseConnection(); Assert.assertEquals(201, res.getStatus()); - res = consumeNext.request().post(String.class); res.releaseConnection(); Assert.assertEquals(200, res.getStatus()); @@ -100,8 +90,7 @@ public class ClientAckTopicTest extends MessageTestBase Thread.sleep(2000); ClientResponse ackRes = ack.request().formParameter("acknowledge", "true").post(); - if (ackRes.getStatus() == 500) - { + if (ackRes.getStatus() == 500) { System.out.println("Failure: " + ackRes.getEntity(String.class)); } ackRes.releaseConnection(); @@ -121,8 +110,7 @@ public class ClientAckTopicTest extends MessageTestBase System.out.println("consumeNext: " + consumeNext); ClientResponse ackRes = ack.request().formParameter("acknowledge", "true").post(); - if (ackRes.getStatus() != 204) - { + if (ackRes.getStatus() != 204) { System.out.println(ackRes.getEntity(String.class)); } ackRes.releaseConnection(); @@ -132,8 +120,7 @@ public class ClientAckTopicTest extends MessageTestBase } @Test - public void testSuccessFirst() throws Exception - { + public void testSuccessFirst() throws Exception { ClientRequest request = new ClientRequest(TestPortProvider.generateURL("/topics/testQueue")); ClientResponse response = request.head(); @@ -142,11 +129,8 @@ public class ClientAckTopicTest extends MessageTestBase Link sender = getLinkByTitle(manager.getTopicManager().getLinkStrategy(), response, "create"); System.out.println("create: " + sender); - Link subscriptions = getLinkByTitle(manager.getTopicManager().getLinkStrategy(), response, "pull-subscriptions"); - response = subscriptions.request().formParameter("autoAck", "false") - .formParameter("durable", "true") - .post(); + response = subscriptions.request().formParameter("autoAck", "false").formParameter("durable", "true").post(); response.releaseConnection(); Assert.assertEquals(201, response.getStatus()); Link sub1 = response.getLocationLink(); @@ -196,8 +180,7 @@ public class ClientAckTopicTest extends MessageTestBase } @Test - public void testSuccessFirstNonDurable() throws Exception - { + public void testSuccessFirstNonDurable() throws Exception { ClientRequest request = new ClientRequest(TestPortProvider.generateURL("/topics/testQueue")); ClientResponse response = request.head(); @@ -206,11 +189,8 @@ public class ClientAckTopicTest extends MessageTestBase Link sender = getLinkByTitle(manager.getTopicManager().getLinkStrategy(), response, "create"); System.out.println("create: " + sender); - Link subscriptions = getLinkByTitle(manager.getTopicManager().getLinkStrategy(), response, "pull-subscriptions"); - response = subscriptions.request().formParameter("autoAck", "false") - .formParameter("durable", "false") - .post(); + response = subscriptions.request().formParameter("autoAck", "false").formParameter("durable", "false").post(); response.releaseConnection(); Assert.assertEquals(201, response.getStatus()); Link sub1 = response.getLocationLink(); @@ -260,8 +240,7 @@ public class ClientAckTopicTest extends MessageTestBase } @Test - public void testPull() throws Exception - { + public void testPull() throws Exception { ClientRequest request = new ClientRequest(TestPortProvider.generateURL("/topics/testQueue")); ClientResponse response = request.head(); @@ -270,9 +249,7 @@ public class ClientAckTopicTest extends MessageTestBase Link sender = getLinkByTitle(manager.getTopicManager().getLinkStrategy(), response, "create"); System.out.println("create: " + sender); Link subscriptions = getLinkByTitle(manager.getTopicManager().getLinkStrategy(), response, "pull-subscriptions"); - response = subscriptions.request().formParameter("autoAck", "false") - .formParameter("durable", "true") - .post(); + response = subscriptions.request().formParameter("autoAck", "false").formParameter("durable", "true").post(); response.releaseConnection(); Assert.assertEquals(201, response.getStatus()); Link sub1 = response.getLocationLink(); diff --git a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/CreateDestinationTest.java b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/CreateDestinationTest.java index bf73808726..f5dc9f4b7f 100644 --- a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/CreateDestinationTest.java +++ b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/CreateDestinationTest.java @@ -25,17 +25,15 @@ import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -public class CreateDestinationTest extends MessageTestBase -{ +public class CreateDestinationTest extends MessageTestBase { + @BeforeClass - public static void reg() - { + public static void reg() { server.getJaxrsServer().getDeployment().getProviderFactory().registerProvider(org.jboss.resteasy.plugins.providers.DocumentProvider.class); } @Test - public void testCreateQueue() throws Exception - { + public void testCreateQueue() throws Exception { String queueConfig = "true"; ClientRequest create = new ClientRequest(TestPortProvider.generateURL("/queues")); ClientResponse cRes = create.body("application/activemq.jms.queue+xml", queueConfig).post(); @@ -68,7 +66,6 @@ public class CreateDestinationTest extends MessageTestBase consumeNext = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), res, "consume-next"); System.out.println("consumeNext: " + consumeNext); - res = sender.request().body("text/plain", Integer.toString(2)).post(); res.releaseConnection(); Assert.assertEquals(201, res.getStatus()); @@ -89,8 +86,7 @@ public class CreateDestinationTest extends MessageTestBase } @Test - public void testCreateTopic() throws Exception - { + public void testCreateTopic() throws Exception { String queueConfig = ""; ClientRequest create = new ClientRequest(TestPortProvider.generateURL("/topics")); ClientResponse cRes = create.body("application/activemq.jms.topic+xml", queueConfig).post(); @@ -105,7 +101,6 @@ public class CreateDestinationTest extends MessageTestBase Link sender = getLinkByTitle(manager.getTopicManager().getLinkStrategy(), response, "create"); Link subscriptions = getLinkByTitle(manager.getTopicManager().getLinkStrategy(), response, "pull-subscriptions"); - ClientResponse res = subscriptions.request().post(); res.releaseConnection(); Assert.assertEquals(201, res.getStatus()); @@ -115,7 +110,6 @@ public class CreateDestinationTest extends MessageTestBase Assert.assertNotNull(consumeNext1); System.out.println("consumeNext1: " + consumeNext1); - res = subscriptions.request().post(); res.releaseConnection(); Assert.assertEquals(201, res.getStatus()); @@ -124,7 +118,6 @@ public class CreateDestinationTest extends MessageTestBase Link consumeNext2 = getLinkByTitle(manager.getTopicManager().getLinkStrategy(), res, "consume-next"); Assert.assertNotNull(consumeNext1); - res = sender.request().body("text/plain", Integer.toString(1)).post(); res.releaseConnection(); Assert.assertEquals(201, res.getStatus()); @@ -164,8 +157,7 @@ public class CreateDestinationTest extends MessageTestBase } @Test - public void testCreateQueueWithBadContentType() throws Exception - { + public void testCreateQueueWithBadContentType() throws Exception { String queueConfig = "true"; ClientRequest create = new ClientRequest(TestPortProvider.generateURL("/queues")); ClientResponse cRes = create.body("application/x-www-form-urlencoded", queueConfig).post(); @@ -175,8 +167,7 @@ public class CreateDestinationTest extends MessageTestBase } @Test - public void testCreateTopicWithBadContentType() throws Exception - { + public void testCreateTopicWithBadContentType() throws Exception { String queueConfig = ""; ClientRequest create = new ClientRequest(TestPortProvider.generateURL("/topics")); ClientResponse cRes = create.body("application/x-www-form-urlencoded", queueConfig).post(); diff --git a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/DupQueueTest.java b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/DupQueueTest.java index 957177b4b0..396a044284 100644 --- a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/DupQueueTest.java +++ b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/DupQueueTest.java @@ -26,11 +26,10 @@ import org.junit.Test; import static org.jboss.resteasy.test.TestPortProvider.generateURL; -public class DupQueueTest extends MessageTestBase -{ +public class DupQueueTest extends MessageTestBase { + @Test - public void testDup() throws Exception - { + public void testDup() throws Exception { String testName = "testDup"; QueueDeployment deployment = new QueueDeployment(); deployment.setDuplicatesAllowed(false); @@ -94,8 +93,7 @@ public class DupQueueTest extends MessageTestBase } @Test - public void testDupWithId() throws Exception - { + public void testDupWithId() throws Exception { String testName = "testDupWithId"; QueueDeployment deployment = new QueueDeployment(); deployment.setDuplicatesAllowed(false); diff --git a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/Embedded.java b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/Embedded.java index f87c3418a0..36ca637638 100644 --- a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/Embedded.java +++ b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/Embedded.java @@ -27,15 +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 -{ +public class Embedded { + protected MessageServiceManager manager = new MessageServiceManager(); protected MessageServiceConfiguration config = new MessageServiceConfiguration(); protected ActiveMQServer activeMQServer; protected TJWSEmbeddedJaxrsServer tjws = new TJWSEmbeddedJaxrsServer(); - public Embedded() - { + public Embedded() { int port = TestPortProvider.getPort(); System.out.println("default port is: " + port); tjws.setPort(port); @@ -43,45 +42,34 @@ public class Embedded tjws.setSecurityDomain(null); } - public MessageServiceConfiguration getConfig() - { + public MessageServiceConfiguration getConfig() { return config; } - public void setConfig(MessageServiceConfiguration config) - { + public void setConfig(MessageServiceConfiguration config) { this.config = config; } - public ActiveMQServer getActiveMQServer() - { + public ActiveMQServer getActiveMQServer() { return activeMQServer; } - public void setActiveMQServer(ActiveMQServer activeMQServer) - { + public void setActiveMQServer(ActiveMQServer activeMQServer) { this.activeMQServer = activeMQServer; } - public TJWSEmbeddedJaxrsServer getJaxrsServer() - { + public TJWSEmbeddedJaxrsServer getJaxrsServer() { return tjws; } - public MessageServiceManager getManager() - { + public MessageServiceManager getManager() { return manager; } - public void start() throws Exception - { + public void start() throws Exception { System.out.println("\nStarting Embedded"); - if (activeMQServer == null) - { - Configuration configuration = new ConfigurationImpl() - .setPersistenceEnabled(false) - .setSecurityEnabled(false) - .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())); + if (activeMQServer == null) { + Configuration configuration = new ConfigurationImpl().setPersistenceEnabled(false).setSecurityEnabled(false).addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())); activeMQServer = ActiveMQServers.newActiveMQServer(configuration); activeMQServer.start(); @@ -94,8 +82,7 @@ public class Embedded } - public void stop() throws Exception - { + public void stop() throws Exception { System.out.println("\nStopping Embedded"); manager.stop(); tjws.stop(); diff --git a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/EmbeddedTest.java b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/EmbeddedTest.java index ac8ecc2d1f..a869dafae8 100644 --- a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/EmbeddedTest.java +++ b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/EmbeddedTest.java @@ -41,20 +41,15 @@ import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -public class EmbeddedTest -{ +public class EmbeddedTest { + public static EmbeddedRestActiveMQJMS server; @BeforeClass - public static void startEmbedded() throws Exception - { + public static void startEmbedded() throws Exception { server = new EmbeddedRestActiveMQJMS(); server.getManager().setConfigResourcePath("activemq-rest.xml"); - FileSecurityConfiguration securityConfiguration = new FileSecurityConfiguration("artemis-users.properties", - "artemis-roles.properties", - "guest", - false, - null); + FileSecurityConfiguration securityConfiguration = new FileSecurityConfiguration("artemis-users.properties", "artemis-roles.properties", "guest", false, null); securityConfiguration.start(); server.getEmbeddedJMS().setSecurityManager(new ActiveMQSecurityManagerImpl(securityConfiguration)); server.start(); @@ -64,44 +59,37 @@ public class EmbeddedTest } @AfterClass - public static void stopEmbedded() throws Exception - { + public static void stopEmbedded() throws Exception { server.stop(); server = null; } - public static void publish(String destination, Serializable object, String contentType) throws Exception - { + 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 - { + try { Assert.assertNotNull("Destination was null", dest); MessageProducer producer = session.createProducer(dest); ObjectMessage message = session.createObjectMessage(); - if (contentType != null) - { + if (contentType != null) { message.setStringProperty(HttpHeaderProperty.CONTENT_TYPE, contentType); } message.setObject(object); producer.send(message); } - finally - { + finally { conn.close(); } } - @Test - public void testTransform() throws Exception - { + public void testTransform() throws Exception { ClientRequest request = new ClientRequest(TestPortProvider.generateURL("/queues/jms.queue.exampleQueue")); diff --git a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/FindDestinationTest.java b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/FindDestinationTest.java index 9c84ec07db..f6eaf17fe8 100644 --- a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/FindDestinationTest.java +++ b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/FindDestinationTest.java @@ -24,11 +24,10 @@ import org.jboss.resteasy.test.TestPortProvider; import org.junit.Assert; import org.junit.Test; -public class FindDestinationTest extends MessageTestBase -{ +public class FindDestinationTest extends MessageTestBase { + @Test - public void testFindQueue() throws Exception - { + public void testFindQueue() throws Exception { String testName = "testFindQueue"; server.getActiveMQServer().createQueue(new SimpleString(testName), new SimpleString(testName), null, false, false); @@ -59,8 +58,7 @@ public class FindDestinationTest extends MessageTestBase } @Test - public void testFindTopic() throws Exception - { + public void testFindTopic() throws Exception { server.getActiveMQServer().createQueue(new SimpleString("testTopic"), new SimpleString("testTopic"), null, false, false); ClientRequest request = new ClientRequest(TestPortProvider.generateURL("/topics/testTopic")); diff --git a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/JMSTest.java b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/JMSTest.java index cc5f0e785a..e4cca189d3 100644 --- a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/JMSTest.java +++ b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/JMSTest.java @@ -44,63 +44,53 @@ import org.junit.Test; import static org.jboss.resteasy.test.TestPortProvider.generateURL; -public class JMSTest extends MessageTestBase -{ +public class JMSTest extends MessageTestBase { + public static ConnectionFactory connectionFactory; @BeforeClass - public static void setup() throws Exception - { + public static void setup() throws Exception { connectionFactory = new ActiveMQJMSConnectionFactory(manager.getQueueManager().getServerLocator()); } @XmlRootElement - public static class Order implements Serializable - { + public static class Order implements Serializable { + private static final long serialVersionUID = 1397854679589606480L; private String name; private String amount; - public String getName() - { + public String getName() { return name; } - public void setName(String name) - { + public void setName(String name) { this.name = name; } - public String getAmount() - { + public String getAmount() { return amount; } - public void setAmount(String amount) - { + public void setAmount(String amount) { this.amount = amount; } @Override - public boolean equals(Object o) - { - if (this == o) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if (o == null || getClass() != o.getClass()) - { + if (o == null || getClass() != o.getClass()) { return false; } Order order = (Order) o; - if (!amount.equals(order.amount)) - { + if (!amount.equals(order.amount)) { return false; } - if (!name.equals(order.name)) - { + if (!name.equals(order.name)) { return false; } @@ -108,61 +98,51 @@ public class JMSTest extends MessageTestBase } @Override - public int hashCode() - { + public int hashCode() { int result = name.hashCode(); result = 31 * result + amount.hashCode(); return result; } } - public static Destination createDestination(String dest) - { + 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 - { + public static void publish(String dest, Serializable object, String contentType) throws Exception { Connection conn = connectionFactory.createConnection(); - try - { + 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) - { + if (contentType != null) { message.setStringProperty(HttpHeaderProperty.CONTENT_TYPE, contentType); } message.setObject(object); producer.send(message); } - finally - { + finally { conn.close(); } } + public static class Listener implements MessageListener { - public static class Listener implements MessageListener - { public static Order order; public static String messageID = null; public static CountDownLatch latch = new CountDownLatch(1); - public void onMessage(Message message) - { - try - { + public void onMessage(Message message) { + try { order = Jms.getEntity(message, Order.class); messageID = message.getJMSMessageID(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } latch.countDown(); @@ -170,8 +150,7 @@ public class JMSTest extends MessageTestBase } @Test - public void testJmsConsumer() throws Exception - { + public void testJmsConsumer() throws Exception { String queueName = ActiveMQDestination.createQueueAddressFromName("testQueue2").toString(); System.out.println("Queue name: " + queueName); QueueDeployment deployment = new QueueDeployment(); @@ -180,8 +159,7 @@ public class JMSTest extends MessageTestBase deployment.setName(queueName); manager.getQueueManager().deploy(deployment); Connection conn = connectionFactory.createConnection(); - try - { + try { Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = createDestination(queueName); MessageConsumer consumer = session.createConsumer(destination); @@ -213,16 +191,13 @@ public class JMSTest extends MessageTestBase Assert.assertNotNull(Listener.messageID); } } - finally - { + finally { conn.close(); } } - @Test - public void testJmsProducer() throws Exception - { + public void testJmsProducer() throws Exception { String queueName = ActiveMQDestination.createQueueAddressFromName("testQueue").toString(); System.out.println("Queue name: " + queueName); QueueDeployment deployment = new QueueDeployment(); @@ -250,8 +225,7 @@ public class JMSTest extends MessageTestBase order.setAmount("$5.00"); publish(queueName, order, null); - ClientResponse res = - consumeNext.request().header("Accept-Wait", "2").accept("application/xml").post(String.class); + 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); diff --git a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/MessageTestBase.java b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/MessageTestBase.java index 58f389b41d..63491d3632 100644 --- a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/MessageTestBase.java +++ b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/MessageTestBase.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.rest.test; + import java.lang.reflect.Field; import org.apache.activemq.artemis.rest.MessageServiceManager; @@ -27,60 +28,51 @@ import org.jboss.resteasy.spi.Link; import org.junit.AfterClass; import org.junit.BeforeClass; -public class MessageTestBase -{ +public class MessageTestBase { + public static Embedded server; public static MessageServiceManager manager; private static Field executorField; - static - { - try - { + static { + try { executorField = BaseClientResponse.class.getDeclaredField("executor"); } - catch (NoSuchFieldException e) - { + catch (NoSuchFieldException e) { throw new RuntimeException(e); } executorField.setAccessible(true); } @BeforeClass - public static void setupActiveMQServerAndManager() throws Exception - { + public static void setupActiveMQServerAndManager() throws Exception { server = new Embedded(); server.start(); manager = server.getManager(); } @AfterClass - public static void shutdownActiveMQServerAndManager() throws Exception - { + public static void shutdownActiveMQServerAndManager() throws Exception { manager = null; server.stop(); server = null; } - public static Link getLinkByTitle(LinkStrategy strategy, ClientResponse response, String title) - { - if (strategy instanceof LinkHeaderLinkStrategy) - { + public static Link getLinkByTitle(LinkStrategy strategy, ClientResponse response, String title) { + if (strategy instanceof LinkHeaderLinkStrategy) { return response.getLinkHeader().getLinkByTitle(title); } - else - { + else { String headerName = "msg-" + title; String href = (String) response.getHeaders().getFirst(headerName); - if (href == null) return null; + if (href == null) + return null; //System.out.println(headerName + ": " + href); Link l = new Link(title, null, href, null, null); - try - { + try { l.setExecutor((ClientExecutor) executorField.get(response)); } - catch (IllegalAccessException e) - { + catch (IllegalAccessException e) { throw new RuntimeException(e); } return l; diff --git a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/PersistentPushQueueConsumerTest.java b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/PersistentPushQueueConsumerTest.java index 5a185a4e57..d0e6c4fd02 100644 --- a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/PersistentPushQueueConsumerTest.java +++ b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/PersistentPushQueueConsumerTest.java @@ -39,18 +39,14 @@ import static org.jboss.resteasy.test.TestPortProvider.generateURL; /** * Test durable queue push consumers */ -public class PersistentPushQueueConsumerTest -{ +public class PersistentPushQueueConsumerTest { + public static MessageServiceManager manager; protected static ResteasyDeployment deployment; public static ActiveMQServer activeMQServer; - public static void startup() throws Exception - { - Configuration configuration = new ConfigurationImpl() - .setPersistenceEnabled(false) - .setSecurityEnabled(false) - .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())); + public static void startup() throws Exception { + Configuration configuration = new ConfigurationImpl().setPersistenceEnabled(false).setSecurityEnabled(false).addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())); activeMQServer = ActiveMQServers.newActiveMQServer(configuration); activeMQServer.start(); @@ -62,8 +58,7 @@ public class PersistentPushQueueConsumerTest deployment.getRegistry().addSingletonResource(manager.getTopicManager().getDestination()); } - public static void shutdown() throws Exception - { + public static void shutdown() throws Exception { manager.stop(); manager = null; EmbeddedContainer.stop(); @@ -73,10 +68,8 @@ public class PersistentPushQueueConsumerTest } @Test - public void testBridge() throws Exception - { - try - { + public void testBridge() throws Exception { + try { startup(); String testName = "testBridge"; @@ -133,14 +126,12 @@ public class PersistentPushQueueConsumerTest manager.getQueueManager().getPushStore().removeAll(); } - finally - { + finally { shutdown(); } } - private void deployBridgeQueues(String testName) throws Exception - { + private void deployBridgeQueues(String testName) throws Exception { QueueDeployment deployment = new QueueDeployment(); deployment.setDuplicatesAllowed(true); deployment.setDurableSend(false); @@ -154,10 +145,8 @@ public class PersistentPushQueueConsumerTest } @Test - public void testFailure() throws Exception - { - try - { + public void testFailure() throws Exception { + try { startup(); String testName = "testFailure"; @@ -206,8 +195,7 @@ public class PersistentPushQueueConsumerTest manager.getQueueManager().getPushStore().removeAll(); } - finally - { + finally { shutdown(); } } diff --git a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/PersistentPushTopicConsumerTest.java b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/PersistentPushTopicConsumerTest.java index f80e52fc7d..d44cea97b5 100644 --- a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/PersistentPushTopicConsumerTest.java +++ b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/PersistentPushTopicConsumerTest.java @@ -49,36 +49,29 @@ import static org.jboss.resteasy.test.TestPortProvider.generateURL; /** * Test durable queue push consumers */ -public class PersistentPushTopicConsumerTest -{ +public class PersistentPushTopicConsumerTest { + public static ActiveMQServer server; public static MessageServiceManager manager; protected static ResteasyDeployment deployment; @BeforeClass - public static void setup() throws Exception - { - Configuration configuration = new ConfigurationImpl() - .setPersistenceEnabled(false) - .setSecurityEnabled(false) - .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())); + public static void setup() throws Exception { + Configuration configuration = new ConfigurationImpl().setPersistenceEnabled(false).setSecurityEnabled(false).addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())); server = ActiveMQServers.newActiveMQServer(configuration); server.start(); } @AfterClass - public static void cleanup() throws Exception - { + public static void cleanup() throws Exception { server.stop(); server = null; } - public static void startup() throws Exception - { + public static void startup() throws Exception { deployment = EmbeddedContainer.start(); - manager = new MessageServiceManager(); manager.start(); deployment.getRegistry().addSingletonResource(manager.getQueueManager().getDestination()); @@ -87,8 +80,7 @@ public class PersistentPushTopicConsumerTest deployment.getRegistry().addPerRequestResource(Receiver.class); } - public static void shutdown() throws Exception - { + public static void shutdown() throws Exception { manager.stop(); manager = null; EmbeddedContainer.stop(); @@ -96,10 +88,8 @@ public class PersistentPushTopicConsumerTest } @Test - public void testFailure() throws Exception - { - try - { + public void testFailure() throws Exception { + try { String testName = "testFailure"; startup(); deployTopic(testName); @@ -149,18 +139,14 @@ public class PersistentPushTopicConsumerTest manager.getQueueManager().getPushStore().removeAll(); } - finally - { + finally { shutdown(); } } - @Test - public void testSuccessFirst() throws Exception - { - try - { + public void testSuccessFirst() throws Exception { + try { String testName = "testSuccessFirst"; startup(); deployTopic(testName); @@ -211,15 +197,14 @@ public class PersistentPushTopicConsumerTest manager.getTopicManager().getPushStore().removeAll(); } - finally - { + finally { shutdown(); } } @Path("/subscribers") - public static class Receiver - { + public static class Receiver { + public static String subscriber1; public static String subscriber2; public static CountDownLatch latch = new CountDownLatch(2); @@ -227,8 +212,7 @@ public class PersistentPushTopicConsumerTest @Path("1") @POST @Consumes("text/plain") - public void postOne(String msg) - { + public void postOne(String msg) { System.out.println("in subscribers 1!!!!!!!!!! " + msg); subscriber1 = msg; latch.countDown(); @@ -237,22 +221,19 @@ public class PersistentPushTopicConsumerTest @Path("2") @POST @Consumes("text/plain") - public void postTwo(String msg) - { + public void postTwo(String msg) { System.out.println("in subscribers 2!!!!!!!!!! " + msg); subscriber2 = msg; latch.countDown(); } } - private void deployTopic(String topicName) throws Exception - { + private void deployTopic(String topicName) throws Exception { TopicDeployment deployment = new TopicDeployment(); deployment.setDuplicatesAllowed(true); deployment.setDurableSend(false); deployment.setName(topicName); manager.getTopicManager().deploy(deployment); - } } \ No newline at end of file diff --git a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/PushQueueConsumerTest.java b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/PushQueueConsumerTest.java index 7a7a0e50c1..f6573b6823 100644 --- a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/PushQueueConsumerTest.java +++ b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/PushQueueConsumerTest.java @@ -34,23 +34,20 @@ import java.util.concurrent.atomic.AtomicInteger; import static org.jboss.resteasy.test.TestPortProvider.generateURL; -public class PushQueueConsumerTest extends MessageTestBase -{ - enum PushRegistrationType - { +public class PushQueueConsumerTest extends MessageTestBase { + + enum PushRegistrationType { CLASS, BRIDGE, URI, TEMPLATE } @Test - public void testBridge() throws Exception - { + public void testBridge() throws Exception { Link destinationForConsumption = null; ClientResponse consumerResponse = null; Link pushSubscription = null; String messageContent = "1"; - try - { + try { // The name of the queue used for the test should match the name of the test String queue = "testBridge"; String queueToPushTo = "pushedFrom-" + queue; @@ -72,17 +69,14 @@ public class PushQueueConsumerTest extends MessageTestBase consumerResponse = consume(destinationForConsumption, messageContent); } - finally - { + finally { cleanupConsumer(consumerResponse); cleanupSubscription(pushSubscription); } } - private void cleanupSubscription(Link pushSubscription) throws Exception - { - if (pushSubscription != null) - { + private void cleanupSubscription(Link pushSubscription) throws Exception { + if (pushSubscription != null) { ClientResponse response = pushSubscription.request().delete(); response.releaseConnection(); Assert.assertEquals(204, response.getStatus()); @@ -90,15 +84,13 @@ public class PushQueueConsumerTest extends MessageTestBase } @Test - public void testClass() throws Exception - { + public void testClass() throws Exception { Link destinationForConsumption = null; ClientResponse consumerResponse = null; Link pushSubscription = null; String messageContent = "1"; - try - { + try { // The name of the queue used for the test should match the name of the test String queue = "testClass"; String queueToPushTo = "pushedFrom-" + queue; @@ -121,23 +113,20 @@ public class PushQueueConsumerTest extends MessageTestBase consumerResponse = consume(destinationForConsumption, messageContent); } - finally - { + finally { cleanupConsumer(consumerResponse); cleanupSubscription(pushSubscription); } } @Test - public void testTemplate() throws Exception - { + public void testTemplate() throws Exception { Link destinationForConsumption = null; ClientResponse consumerResponse = null; Link pushSubscription = null; String messageContent = "1"; - try - { + try { // The name of the queue used for the test should match the name of the test String queue = "testTemplate"; String queueToPushTo = "pushedFrom-" + queue; @@ -162,47 +151,41 @@ public class PushQueueConsumerTest extends MessageTestBase consumerResponse = consume(destinationForConsumption, messageContent); } - finally - { + finally { cleanupConsumer(consumerResponse); cleanupSubscription(pushSubscription); } } @Path("/my") - public static class MyResource - { + public static class MyResource { + public static String got_it; @PUT - public void put(String str) - { + public void put(String str) { got_it = str; } } @Path("/myConcurrent") - public static class MyConcurrentResource - { + public static class MyConcurrentResource { + public static AtomicInteger concurrentInvocations = new AtomicInteger(); public static AtomicInteger maxConcurrentInvocations = new AtomicInteger(); @PUT - public void put(String str) - { + public void put(String str) { concurrentInvocations.getAndIncrement(); - if (concurrentInvocations.get() > maxConcurrentInvocations.get()) - { + if (concurrentInvocations.get() > maxConcurrentInvocations.get()) { maxConcurrentInvocations.set(concurrentInvocations.get()); } - try - { + try { // sleep here so the concurrent invocations can stack up Thread.sleep(1000); } - catch (InterruptedException e) - { + catch (InterruptedException e) { e.printStackTrace(); } @@ -211,13 +194,11 @@ public class PushQueueConsumerTest extends MessageTestBase } @Test - public void testUri() throws Exception - { + public void testUri() throws Exception { Link pushSubscription = null; String messageContent = "1"; - try - { + try { // The name of the queue used for the test should match the name of the test String queue = "testUri"; String queueToPushTo = "pushedFrom-" + queue; @@ -239,21 +220,18 @@ public class PushQueueConsumerTest extends MessageTestBase Assert.assertEquals(messageContent, MyResource.got_it); } - finally - { + finally { cleanupSubscription(pushSubscription); } } @Test - public void testUriWithMultipleSessions() throws Exception - { + public void testUriWithMultipleSessions() throws Exception { Link pushSubscription = null; String messageContent = "1"; final int CONCURRENT = 10; - try - { + try { // The name of the queue used for the test should match the name of the test String queue = "testUriWithMultipleSessions"; String queueToPushTo = "pushedFrom-" + queue; @@ -269,27 +247,23 @@ public class PushQueueConsumerTest extends MessageTestBase pushSubscription = createPushRegistration(generateURL("/myConcurrent"), pushSubscriptions, PushRegistrationType.URI, CONCURRENT); - for (int i = 0; i < CONCURRENT; i++) - { + for (int i = 0; i < CONCURRENT; i++) { sendMessage(destinationForSend, messageContent); } // wait until all the invocations have completed - while (MyConcurrentResource.concurrentInvocations.get() > 0) - { + while (MyConcurrentResource.concurrentInvocations.get() > 0) { Thread.sleep(100); } Assert.assertEquals(CONCURRENT, MyConcurrentResource.maxConcurrentInvocations.get()); } - finally - { + finally { cleanupSubscription(pushSubscription); } } - private void deployQueue(String queueName) throws Exception - { + private void deployQueue(String queueName) throws Exception { QueueDeployment deployment = new QueueDeployment(); deployment.setDuplicatesAllowed(true); deployment.setDurableSend(false); @@ -297,8 +271,7 @@ public class PushQueueConsumerTest extends MessageTestBase manager.getQueueManager().deploy(deployment); } - private ClientResponse consume(Link destination, String expectedContent) throws Exception - { + private ClientResponse consume(Link destination, String expectedContent) throws Exception { ClientResponse response; response = destination.request().header(Constants.WAIT_HEADER, "1").post(String.class); Assert.assertEquals(200, response.getStatus()); @@ -307,15 +280,13 @@ public class PushQueueConsumerTest extends MessageTestBase return response; } - private void sendMessage(Link sender, String content) throws Exception - { + private void sendMessage(Link sender, String content) throws Exception { ClientResponse sendMessageResponse = sender.request().body("text/plain", content).post(); sendMessageResponse.releaseConnection(); Assert.assertEquals(201, sendMessageResponse.getStatus()); } - private ClientResponse setAutoAck(ClientResponse response, boolean ack) throws Exception - { + private ClientResponse setAutoAck(ClientResponse response, boolean ack) throws Exception { Link pullConsumers = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "pull-consumers"); ClientResponse autoAckResponse = pullConsumers.request().formParameter("autoAck", Boolean.toString(ack)).post(); autoAckResponse.releaseConnection(); @@ -323,10 +294,8 @@ public class PushQueueConsumerTest extends MessageTestBase return autoAckResponse; } - private void cleanupConsumer(ClientResponse consumerResponse) throws Exception - { - if (consumerResponse != null) - { + private void cleanupConsumer(ClientResponse consumerResponse) throws Exception { + if (consumerResponse != null) { Link consumer = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), consumerResponse, "consumer"); ClientResponse response = consumer.request().delete(); response.releaseConnection(); @@ -334,33 +303,32 @@ public class PushQueueConsumerTest extends MessageTestBase } } - private Link createPushRegistration(String queueToPushTo, Link pushSubscriptions, PushRegistrationType pushRegistrationType) throws Exception - { + private Link createPushRegistration(String queueToPushTo, + Link pushSubscriptions, + PushRegistrationType pushRegistrationType) throws Exception { return createPushRegistration(queueToPushTo, pushSubscriptions, pushRegistrationType, 1); } - private Link createPushRegistration(String queueToPushTo, Link pushSubscriptions, PushRegistrationType pushRegistrationType, int sessionCount) throws Exception - { + private Link createPushRegistration(String queueToPushTo, + Link pushSubscriptions, + PushRegistrationType pushRegistrationType, + int sessionCount) throws Exception { PushRegistration reg = new PushRegistration(); reg.setDurable(false); XmlLink target = new XmlLink(); - if (pushRegistrationType == PushRegistrationType.CLASS) - { + if (pushRegistrationType == PushRegistrationType.CLASS) { target.setHref(generateURL(Util.getUrlPath(queueToPushTo))); target.setClassName(ActiveMQPushStrategy.class.getName()); } - else if (pushRegistrationType == PushRegistrationType.BRIDGE) - { + else if (pushRegistrationType == PushRegistrationType.BRIDGE) { target.setHref(generateURL(Util.getUrlPath(queueToPushTo))); target.setRelationship("destination"); } - else if (pushRegistrationType == PushRegistrationType.TEMPLATE) - { + else if (pushRegistrationType == PushRegistrationType.TEMPLATE) { target.setHref(queueToPushTo); target.setRelationship("template"); } - else if (pushRegistrationType == PushRegistrationType.URI) - { + else if (pushRegistrationType == PushRegistrationType.URI) { target.setMethod("put"); target.setHref(queueToPushTo); } diff --git a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/PushTopicConsumerTest.java b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/PushTopicConsumerTest.java index 46998792a5..320567c5d4 100644 --- a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/PushTopicConsumerTest.java +++ b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/PushTopicConsumerTest.java @@ -34,26 +34,24 @@ import org.junit.Test; import static org.jboss.resteasy.test.TestPortProvider.generateURL; -public class PushTopicConsumerTest extends MessageTestBase -{ +public class PushTopicConsumerTest extends MessageTestBase { + @BeforeClass - public static void setup() throws Exception - { -// TopicDeployment deployment = new TopicDeployment(); -// deployment.setDuplicatesAllowed(true); -// deployment.setDurableSend(false); -// deployment.setName("testTopic"); -// manager.getTopicManager().deploy(deployment); -// QueueDeployment deployment2 = new QueueDeployment(); -// deployment2.setDuplicatesAllowed(true); -// deployment2.setDurableSend(false); -// deployment2.setName("forwardQueue"); -// manager.getQueueManager().deploy(deployment2); + public static void setup() throws Exception { + // TopicDeployment deployment = new TopicDeployment(); + // deployment.setDuplicatesAllowed(true); + // deployment.setDurableSend(false); + // deployment.setName("testTopic"); + // manager.getTopicManager().deploy(deployment); + // QueueDeployment deployment2 = new QueueDeployment(); + // deployment2.setDuplicatesAllowed(true); + // deployment2.setDurableSend(false); + // deployment2.setName("forwardQueue"); + // manager.getQueueManager().deploy(deployment2); } @Test - public void testBridge() throws Exception - { + public void testBridge() throws Exception { TopicDeployment deployment = new TopicDeployment(); deployment.setDuplicatesAllowed(true); deployment.setDurableSend(false); @@ -112,8 +110,7 @@ public class PushTopicConsumerTest extends MessageTestBase } @Test - public void testClass() throws Exception - { + public void testClass() throws Exception { TopicDeployment deployment = new TopicDeployment(); deployment.setDuplicatesAllowed(true); deployment.setDurableSend(false); @@ -172,8 +169,7 @@ public class PushTopicConsumerTest extends MessageTestBase } @Test - public void testTemplate() throws Exception - { + public void testTemplate() throws Exception { TopicDeployment deployment = new TopicDeployment(); deployment.setDuplicatesAllowed(true); deployment.setDurableSend(false); @@ -233,40 +229,35 @@ public class PushTopicConsumerTest extends MessageTestBase } @Path("/my") - public static class MyResource - { + public static class MyResource { + public static String gotit; @PUT - public void put(String str) - { + public void put(String str) { gotit = str; } } @Path("/myConcurrent") - public static class MyConcurrentResource - { + public static class MyConcurrentResource { + public static AtomicInteger concurrentInvocations = new AtomicInteger(); public static AtomicInteger maxConcurrentInvocations = new AtomicInteger(); @PUT - public void put(String str) - { + public void put(String str) { concurrentInvocations.getAndIncrement(); - if (concurrentInvocations.get() > maxConcurrentInvocations.get()) - { + if (concurrentInvocations.get() > maxConcurrentInvocations.get()) { maxConcurrentInvocations.set(concurrentInvocations.get()); } - try - { + try { // sleep here so the concurrent invocations can stack up Thread.sleep(1000); } - catch (InterruptedException e) - { + catch (InterruptedException e) { e.printStackTrace(); } @@ -275,8 +266,7 @@ public class PushTopicConsumerTest extends MessageTestBase } @Test - public void testUri() throws Exception - { + public void testUri() throws Exception { TopicDeployment deployment = new TopicDeployment(); deployment.setDuplicatesAllowed(true); deployment.setDurableSend(false); @@ -318,8 +308,7 @@ public class PushTopicConsumerTest extends MessageTestBase } @Test - public void testUriWithMultipleSessions() throws Exception - { + public void testUriWithMultipleSessions() throws Exception { final int CONCURRENT = 10; TopicDeployment deployment = new TopicDeployment(); @@ -351,16 +340,14 @@ public class PushTopicConsumerTest extends MessageTestBase Link pushSubscription = response.getLocationLink(); response.releaseConnection(); - for (int i = 0; i < CONCURRENT; i++) - { + for (int i = 0; i < CONCURRENT; i++) { response = sender.request().body("text/plain", Integer.toString(1)).post(); response.releaseConnection(); Assert.assertEquals(201, response.getStatus()); } // wait until all the invocations have completed - while (MyConcurrentResource.concurrentInvocations.get() > 0) - { + while (MyConcurrentResource.concurrentInvocations.get() > 0) { Thread.sleep(100); } diff --git a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/RawAckTest.java b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/RawAckTest.java index 5a68b18f21..a67a0ebee7 100644 --- a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/RawAckTest.java +++ b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/RawAckTest.java @@ -42,8 +42,8 @@ import org.junit.Test; /** * Play with ActiveMQ */ -public class RawAckTest -{ +public class RawAckTest { + protected static ActiveMQServer activeMQServer; static ServerLocator serverLocator; static ClientSessionFactory sessionFactory; @@ -52,12 +52,8 @@ public class RawAckTest static ClientSession session; @BeforeClass - public static void setup() throws Exception - { - Configuration configuration = new ConfigurationImpl() - .setPersistenceEnabled(false) - .setSecurityEnabled(false) - .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())); + public static void setup() throws Exception { + Configuration configuration = new ConfigurationImpl().setPersistenceEnabled(false).setSecurityEnabled(false).addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())); activeMQServer = ActiveMQServers.newActiveMQServer(configuration); activeMQServer.start(); @@ -75,28 +71,24 @@ public class RawAckTest } @AfterClass - public static void shutdown() throws Exception - { + public static void shutdown() throws Exception { serverLocator.close(); activeMQServer.stop(); } static boolean passed = false; - private static class MyThread extends Thread - { + private static class MyThread extends Thread { + final ClientConsumer consumer; - private MyThread(ClientConsumer consumer) - { + private MyThread(ClientConsumer consumer) { this.consumer = consumer; } @Override - public void run() - { - try - { + public void run() { + try { ClientMessage message = consumer.receiveImmediate(); int size = message.getBodyBuffer().readInt(); byte[] bytes = new byte[size]; @@ -105,24 +97,21 @@ public class RawAckTest System.out.println(str); message.acknowledge(); message = consumer.receive(1); - if (message != null) - { + if (message != null) { System.err.println("Not expecting another message: type=" + message.getType()); throw new RuntimeException("Failed, receive extra message"); } Assert.assertNull(message); passed = true; } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } } @Test - public void testAck() throws Exception - { + public void testAck() throws Exception { ClientMessage message; diff --git a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/RepostingQueueTest.java b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/RepostingQueueTest.java index 6251cfcc39..714ff2d468 100644 --- a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/RepostingQueueTest.java +++ b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/RepostingQueueTest.java @@ -40,18 +40,16 @@ import static org.jboss.resteasy.test.TestPortProvider.generateURL; * post on old ack-next after an ack * ack with an old ack link */ -public class RepostingQueueTest extends MessageTestBase -{ +public class RepostingQueueTest extends MessageTestBase { + @BeforeClass - public static void setup() throws Exception - { + public static void setup() throws Exception { QueueDeployment deployment1 = new QueueDeployment("testQueue", true); manager.getQueueManager().deploy(deployment1); } @Test - public void testPostOnSameConsumeNext() throws Exception - { + public void testPostOnSameConsumeNext() throws Exception { ClientRequest request = new ClientRequest(generateURL("/queues/testQueue")); ClientResponse response = request.head(); @@ -78,7 +76,6 @@ public class RepostingQueueTest extends MessageTestBase consumeNext = MessageTestBase.getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "consume-next"); System.out.println("session 1st consumeNext: " + consumeNext); - response = sender.request().body("text/plain", Integer.toString(2)).post(); response.releaseConnection(); Assert.assertEquals(201, response.getStatus()); @@ -120,8 +117,7 @@ public class RepostingQueueTest extends MessageTestBase } @Test - public void testPostOnOldConsumeNext() throws Exception - { + public void testPostOnOldConsumeNext() throws Exception { ClientRequest request = new ClientRequest(generateURL("/queues/testQueue")); ClientResponse response = request.head(); @@ -149,7 +145,6 @@ public class RepostingQueueTest extends MessageTestBase Link firstConsumeNext = consumeNext; System.out.println("session 1st consumeNext: " + consumeNext); - response = sender.request().body("text/plain", Integer.toString(2)).post(); response.releaseConnection(); Assert.assertEquals(201, response.getStatus()); @@ -182,8 +177,7 @@ public class RepostingQueueTest extends MessageTestBase } @Test - public void testPostOnSameConsumeNextWithTimeout() throws Exception - { + public void testPostOnSameConsumeNextWithTimeout() throws Exception { ClientRequest request = new ClientRequest(generateURL("/queues/testQueue")); ClientResponse response = request.head(); @@ -219,7 +213,6 @@ public class RepostingQueueTest extends MessageTestBase consumeNext = MessageTestBase.getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "consume-next"); System.out.println("session 2nd consumeNext: " + consumeNext); - response = sender.request().body("text/plain", Integer.toString(3)).post(); response.releaseConnection(); Assert.assertEquals(201, response.getStatus()); @@ -234,8 +227,7 @@ public class RepostingQueueTest extends MessageTestBase } @Test - public void testPostOnSameAcknowledgeNextAndAck() throws Exception - { + public void testPostOnSameAcknowledgeNextAndAck() throws Exception { ClientRequest request = new ClientRequest(generateURL("/queues/testQueue")); ClientResponse response = request.head(); @@ -273,7 +265,6 @@ public class RepostingQueueTest extends MessageTestBase consumeNext = MessageTestBase.getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "acknowledge-next"); System.out.println("session 1st acknowledge-next: " + consumeNext); - response = sender.request().body("text/plain", Integer.toString(2)).post(); response.releaseConnection(); Assert.assertEquals(201, response.getStatus()); @@ -306,8 +297,7 @@ public class RepostingQueueTest extends MessageTestBase } @Test - public void testRepostSuccessfulUnacknowledge() throws Exception - { + public void testRepostSuccessfulUnacknowledge() throws Exception { ClientRequest request = new ClientRequest(generateURL("/queues/testQueue")); ClientResponse response = request.head(); @@ -345,7 +335,6 @@ public class RepostingQueueTest extends MessageTestBase consumeNext = MessageTestBase.getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "acknowledge-next"); System.out.println("session 1st acknowledge-next: " + consumeNext); - response = consumeNext.request().header(Constants.WAIT_HEADER, "10").post(String.class); Assert.assertEquals(200, response.getStatus()); Assert.assertEquals("1", response.getEntity(String.class)); @@ -374,8 +363,7 @@ public class RepostingQueueTest extends MessageTestBase } @Test - public void testRepostAckAfterUnacknowledge() throws Exception - { + public void testRepostAckAfterUnacknowledge() throws Exception { ClientRequest request = new ClientRequest(generateURL("/queues/testQueue")); ClientResponse response = request.head(); @@ -411,7 +399,6 @@ public class RepostingQueueTest extends MessageTestBase consumeNext = MessageTestBase.getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "acknowledge-next"); System.out.println("session 1st acknowledge-next: " + consumeNext); - response = consumeNext.request().header(Constants.WAIT_HEADER, "10").post(String.class); Assert.assertEquals(200, response.getStatus()); Assert.assertEquals("1", response.getEntity(String.class)); @@ -440,8 +427,7 @@ public class RepostingQueueTest extends MessageTestBase } @Test - public void testRepostUnAckAfterAcknowledge() throws Exception - { + public void testRepostUnAckAfterAcknowledge() throws Exception { ClientRequest request = new ClientRequest(generateURL("/queues/testQueue")); ClientResponse response = request.head(); @@ -477,7 +463,6 @@ public class RepostingQueueTest extends MessageTestBase consumeNext = MessageTestBase.getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "acknowledge-next"); System.out.println("session 1st acknowledge-next: " + consumeNext); - response = sender.request().body("text/plain", Integer.toString(2)).post(); response.releaseConnection(); Assert.assertEquals(201, response.getStatus()); @@ -510,8 +495,7 @@ public class RepostingQueueTest extends MessageTestBase } @Test - public void testPostOnOldAcknowledgeNextAndAck() throws Exception - { + public void testPostOnOldAcknowledgeNextAndAck() throws Exception { ClientRequest request = new ClientRequest(generateURL("/queues/testQueue")); ClientResponse response = request.head(); diff --git a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/RepostingTopicTest.java b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/RepostingTopicTest.java index 18516da1d6..28b9132e6a 100644 --- a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/RepostingTopicTest.java +++ b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/RepostingTopicTest.java @@ -40,18 +40,16 @@ import static org.jboss.resteasy.test.TestPortProvider.generateURL; * post on old ack-next after an ack * ack with an old ack link */ -public class RepostingTopicTest extends MessageTestBase -{ +public class RepostingTopicTest extends MessageTestBase { + @BeforeClass - public static void setup() throws Exception - { + public static void setup() throws Exception { TopicDeployment deployment1 = new TopicDeployment("testTopic", true); manager.getTopicManager().deploy(deployment1); } @Test - public void testReconnectOnNamedSubscriber() throws Exception - { + public void testReconnectOnNamedSubscriber() throws Exception { ClientRequest request = new ClientRequest(generateURL("/topics/testTopic")); ClientResponse response = request.head(); @@ -71,7 +69,6 @@ public class RepostingTopicTest extends MessageTestBase response.releaseConnection(); Assert.assertEquals(201, response.getStatus()); - // recreate subscription a second time as named. Should pick up old one. response = consumers.request().formParameter("name", "bill").post(); @@ -88,7 +85,6 @@ public class RepostingTopicTest extends MessageTestBase Assert.assertEquals("2", response.getEntity(String.class)); response.releaseConnection(); - Link session = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "consumer"); response = session.request().delete(); response.releaseConnection(); @@ -96,8 +92,7 @@ public class RepostingTopicTest extends MessageTestBase } @Test - public void testRestartOnDurableNamedSubscriber() throws Exception - { + public void testRestartOnDurableNamedSubscriber() throws Exception { ClientRequest request = new ClientRequest(generateURL("/topics/testTopic")); ClientResponse response = request.head(); @@ -117,7 +112,6 @@ public class RepostingTopicTest extends MessageTestBase response.releaseConnection(); Assert.assertEquals(201, response.getStatus()); - manager.getTopicManager().getDestination().findTopic("testTopic").getSubscriptions().stop(); // recreate subscription a second time as named. Should pick up old one. @@ -136,7 +130,6 @@ public class RepostingTopicTest extends MessageTestBase Assert.assertEquals("2", response.getEntity(String.class)); response.releaseConnection(); - Link session = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "consumer"); response = session.request().delete(); response.releaseConnection(); @@ -144,8 +137,7 @@ public class RepostingTopicTest extends MessageTestBase } @Test - public void testRestartOnNonDurableNamedSubscriber() throws Exception - { + public void testRestartOnNonDurableNamedSubscriber() throws Exception { ClientRequest request = new ClientRequest(generateURL("/topics/testTopic")); ClientResponse response = request.head(); @@ -184,8 +176,7 @@ public class RepostingTopicTest extends MessageTestBase } @Test - public void testPostOnSameConsumeNext() throws Exception - { + public void testPostOnSameConsumeNext() throws Exception { ClientRequest request = new ClientRequest(generateURL("/topics/testTopic")); ClientResponse response = request.head(); @@ -212,7 +203,6 @@ public class RepostingTopicTest extends MessageTestBase consumeNext = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "consume-next"); System.out.println("session 1st consumeNext: " + consumeNext); - response = sender.request().body("text/plain", Integer.toString(2)).post(); response.releaseConnection(); Assert.assertEquals(201, response.getStatus()); @@ -234,7 +224,6 @@ public class RepostingTopicTest extends MessageTestBase Assert.assertEquals("2", response.getEntity(String.class)); response.releaseConnection(); - session = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "consumer"); System.out.println("session: " + session); consumeNext = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "consume-next"); @@ -255,8 +244,7 @@ public class RepostingTopicTest extends MessageTestBase } @Test - public void testPostOnOldConsumeNext() throws Exception - { + public void testPostOnOldConsumeNext() throws Exception { ClientRequest request = new ClientRequest(generateURL("/topics/testTopic")); ClientResponse response = request.head(); @@ -284,7 +272,6 @@ public class RepostingTopicTest extends MessageTestBase Link firstConsumeNext = consumeNext; System.out.println("session 1st consumeNext: " + consumeNext); - response = sender.request().body("text/plain", Integer.toString(2)).post(); response.releaseConnection(); Assert.assertEquals(201, response.getStatus()); @@ -317,8 +304,7 @@ public class RepostingTopicTest extends MessageTestBase } @Test - public void testPostOnSameConsumeNextWithTimeout() throws Exception - { + public void testPostOnSameConsumeNextWithTimeout() throws Exception { ClientRequest request = new ClientRequest(generateURL("/topics/testTopic")); ClientResponse response = request.head(); @@ -354,7 +340,6 @@ public class RepostingTopicTest extends MessageTestBase consumeNext = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "consume-next"); System.out.println("session 2nd consumeNext: " + consumeNext); - response = sender.request().body("text/plain", Integer.toString(3)).post(); response.releaseConnection(); Assert.assertEquals(201, response.getStatus()); @@ -369,8 +354,7 @@ public class RepostingTopicTest extends MessageTestBase } @Test - public void testPostOnSameAcknowledgeNextAndAck() throws Exception - { + public void testPostOnSameAcknowledgeNextAndAck() throws Exception { ClientRequest request = new ClientRequest(generateURL("/topics/testTopic")); ClientResponse response = request.head(); @@ -408,7 +392,6 @@ public class RepostingTopicTest extends MessageTestBase consumeNext = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "acknowledge-next"); System.out.println("session 1st acknowledge-next: " + consumeNext); - response = sender.request().body("text/plain", Integer.toString(2)).post(); response.releaseConnection(); Assert.assertEquals(201, response.getStatus()); @@ -441,8 +424,7 @@ public class RepostingTopicTest extends MessageTestBase } @Test - public void testRepostSuccessfulUnacknowledge() throws Exception - { + public void testRepostSuccessfulUnacknowledge() throws Exception { ClientRequest request = new ClientRequest(generateURL("/topics/testTopic")); ClientResponse response = request.head(); @@ -480,7 +462,6 @@ public class RepostingTopicTest extends MessageTestBase consumeNext = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "acknowledge-next"); System.out.println("session 1st acknowledge-next: " + consumeNext); - response = consumeNext.request().header(Constants.WAIT_HEADER, "10").post(String.class); Assert.assertEquals(200, response.getStatus()); Assert.assertEquals("1", response.getEntity(String.class)); @@ -509,8 +490,7 @@ public class RepostingTopicTest extends MessageTestBase } @Test - public void testRepostAckAfterUnacknowledge() throws Exception - { + public void testRepostAckAfterUnacknowledge() throws Exception { ClientRequest request = new ClientRequest(generateURL("/topics/testTopic")); ClientResponse response = request.head(); @@ -546,7 +526,6 @@ public class RepostingTopicTest extends MessageTestBase consumeNext = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "acknowledge-next"); System.out.println("session 1st acknowledge-next: " + consumeNext); - response = consumeNext.request().header(Constants.WAIT_HEADER, "10").post(String.class); Assert.assertEquals(200, response.getStatus()); Assert.assertEquals("1", response.getEntity(String.class)); @@ -575,8 +554,7 @@ public class RepostingTopicTest extends MessageTestBase } @Test - public void testRepostUnAckAfterAcknowledge() throws Exception - { + public void testRepostUnAckAfterAcknowledge() throws Exception { ClientRequest request = new ClientRequest(generateURL("/topics/testTopic")); ClientResponse response = request.head(); @@ -612,7 +590,6 @@ public class RepostingTopicTest extends MessageTestBase consumeNext = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "acknowledge-next"); System.out.println("session 1st acknowledge-next: " + consumeNext); - response = sender.request().body("text/plain", Integer.toString(2)).post(); response.releaseConnection(); Assert.assertEquals(201, response.getStatus()); @@ -645,8 +622,7 @@ public class RepostingTopicTest extends MessageTestBase } @Test - public void testPostOnOldAcknowledgeNextAndAck() throws Exception - { + public void testPostOnOldAcknowledgeNextAndAck() throws Exception { ClientRequest request = new ClientRequest(generateURL("/topics/testTopic")); ClientResponse response = request.head(); @@ -701,7 +677,6 @@ public class RepostingTopicTest extends MessageTestBase Assert.assertEquals(204, response.getStatus()); consumeNext = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "acknowledge-next"); - response = consumeNext.request().post(String.class); response.releaseConnection(); Assert.assertEquals(503, response.getStatus()); diff --git a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/RoundtripTimeTest.java b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/RoundtripTimeTest.java index 724c473cd3..389a9ead67 100644 --- a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/RoundtripTimeTest.java +++ b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/RoundtripTimeTest.java @@ -25,11 +25,10 @@ import org.junit.Test; import static org.jboss.resteasy.test.TestPortProvider.generateURL; -public class RoundtripTimeTest extends MessageTestBase -{ +public class RoundtripTimeTest extends MessageTestBase { + @Test - public void testSuccessFirst() throws Exception - { + public void testSuccessFirst() throws Exception { QueueDeployment deployment = new QueueDeployment(); deployment.setDuplicatesAllowed(true); deployment.setDurableSend(false); @@ -49,19 +48,16 @@ public class RoundtripTimeTest extends MessageTestBase Link consumeNext = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "consume-next"); System.out.println("consume-next: " + consumeNext); - long start = System.currentTimeMillis(); int num = 100; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { response = sender.request().body("text/plain", Integer.toString(i + 1)).post(); response.releaseConnection(); } long end = System.currentTimeMillis() - start; System.out.println(num + " iterations took " + end + "ms"); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { response = consumeNext.request().post(String.class); consumeNext = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "consume-next"); Assert.assertEquals(200, response.getStatus()); diff --git a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/SelectorTest.java b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/SelectorTest.java index de4c10f417..2d6d3f2d8a 100644 --- a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/SelectorTest.java +++ b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/SelectorTest.java @@ -42,14 +42,13 @@ import org.junit.Test; import static org.jboss.resteasy.test.TestPortProvider.generateURL; -public class SelectorTest extends MessageTestBase -{ +public class SelectorTest extends MessageTestBase { + public static ConnectionFactory connectionFactory; public static String topicName = ActiveMQDestination.createQueueAddressFromName("testTopic").toString(); @BeforeClass - public static void setup() throws Exception - { + public static void setup() throws Exception { connectionFactory = new ActiveMQJMSConnectionFactory(manager.getQueueManager().getServerLocator()); System.out.println("Queue name: " + topicName); TopicDeployment deployment = new TopicDeployment(); @@ -60,52 +59,43 @@ public class SelectorTest extends MessageTestBase } @XmlRootElement - public static class Order implements Serializable - { + public static class Order implements Serializable { + private static final long serialVersionUID = 482698090549294508L; private String name; private String amount; - public String getName() - { + public String getName() { return name; } - public void setName(String name) - { + public void setName(String name) { this.name = name; } - public String getAmount() - { + public String getAmount() { return amount; } - public void setAmount(String amount) - { + public void setAmount(String amount) { this.amount = amount; } @Override - public boolean equals(Object o) - { - if (this == o) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if (o == null || getClass() != o.getClass()) - { + if (o == null || getClass() != o.getClass()) { return false; } Order order = (Order) o; - if (!amount.equals(order.amount)) - { + if (!amount.equals(order.amount)) { return false; } - if (!name.equals(order.name)) - { + if (!name.equals(order.name)) { return false; } @@ -113,83 +103,71 @@ public class SelectorTest extends MessageTestBase } @Override - public String toString() - { + public String toString() { return "Order{" + "name='" + name + '\'' + '}'; } @Override - public int hashCode() - { + public int hashCode() { int result = name.hashCode(); result = 31 * result + amount.hashCode(); return result; } } - public static Destination createDestination(String dest) - { + 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, String tag) throws Exception - { + public static void publish(String dest, Serializable object, String contentType, String tag) throws Exception { Connection conn = connectionFactory.createConnection(); - try - { + 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) - { + if (contentType != null) { message.setStringProperty(HttpHeaderProperty.CONTENT_TYPE, contentType); } - if (tag != null) - { + if (tag != null) { message.setStringProperty("MyTag", tag); } message.setObject(object); producer.send(message); } - finally - { + finally { conn.close(); } } @Path("/push") - public static class PushReceiver - { + public static class PushReceiver { + public static Order oneOrder; public static Order twoOrder; @POST @Path("one") - public void one(Order order) - { + public void one(Order order) { oneOrder = order; } @POST @Path("two") - public void two(Order order) - { + public void two(Order order) { twoOrder = order; } - } @Test - public void testPush() throws Exception - { + public void testPush() throws Exception { server.getJaxrsServer().getDeployment().getRegistry().addPerRequestResource(PushReceiver.class); ClientRequest request = new ClientRequest(generateURL("/topics/" + topicName)); @@ -261,10 +239,8 @@ public class SelectorTest extends MessageTestBase response.releaseConnection(); } - @Test - public void testPull() throws Exception - { + public void testPull() throws Exception { ClientRequest request = new ClientRequest(generateURL("/topics/" + topicName)); ClientResponse response = request.head(); @@ -272,19 +248,16 @@ public class SelectorTest extends MessageTestBase Assert.assertEquals(200, response.getStatus()); Link consumers = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "pull-subscriptions"); System.out.println("pull: " + consumers); - response = consumers.request().formParameter("autoAck", "true") - .formParameter("selector", "MyTag = '1'").post(); + response = consumers.request().formParameter("autoAck", "true").formParameter("selector", "MyTag = '1'").post(); response.releaseConnection(); Link consumeOne = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "consume-next"); System.out.println("consumeOne: " + consumeOne); - response = consumers.request().formParameter("autoAck", "true") - .formParameter("selector", "MyTag = '2'").post(); + response = consumers.request().formParameter("autoAck", "true").formParameter("selector", "MyTag = '2'").post(); response.releaseConnection(); Link consumeTwo = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "consume-next"); System.out.println("consumeTwo: " + consumeTwo); - // test that Accept header is used to set content-type { Order order = new Order(); @@ -319,8 +292,7 @@ public class SelectorTest extends MessageTestBase } } - private Link consumeOrder(Order order, Link consumeNext) throws Exception - { + private Link consumeOrder(Order order, Link consumeNext) throws Exception { ClientResponse response = consumeNext.request().header("Accept-Wait", "4").accept("application/xml").post(String.class); Assert.assertEquals(200, response.getStatus()); Assert.assertEquals("application/xml", response.getHeaders().getFirst("Content-Type").toString().toLowerCase()); diff --git a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/SessionTest.java b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/SessionTest.java index 68b42a8fcc..e9c8386916 100644 --- a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/SessionTest.java +++ b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/SessionTest.java @@ -28,11 +28,10 @@ import org.junit.Test; import static org.jboss.resteasy.test.TestPortProvider.generateURL; -public class SessionTest extends MessageTestBase -{ +public class SessionTest extends MessageTestBase { + @BeforeClass - public static void setup() throws Exception - { + public static void setup() throws Exception { QueueDeployment deployment1 = new QueueDeployment("testQueue", true); manager.getQueueManager().deploy(deployment1); TopicDeployment deployment = new TopicDeployment(); @@ -44,8 +43,7 @@ public class SessionTest extends MessageTestBase } @Test - public void testRestartFromAutoAckSession() throws Exception - { + public void testRestartFromAutoAckSession() throws Exception { ClientRequest request = new ClientRequest(generateURL("/queues/testQueue")); ClientResponse response = request.head(); @@ -98,10 +96,8 @@ public class SessionTest extends MessageTestBase Assert.assertEquals(204, response.getStatus()); } - @Test - public void testTopicRestartFromAutoAckSession() throws Exception - { + public void testTopicRestartFromAutoAckSession() throws Exception { ClientRequest request = new ClientRequest(generateURL("/topics/testTopic")); ClientResponse response = request.head(); @@ -156,10 +152,8 @@ public class SessionTest extends MessageTestBase Assert.assertEquals(204, response.getStatus()); } - @Test - public void testRestartFromAckSession() throws Exception - { + public void testRestartFromAckSession() throws Exception { ClientRequest request = new ClientRequest(generateURL("/queues/testQueue")); ClientResponse response = request.head(); @@ -235,8 +229,7 @@ public class SessionTest extends MessageTestBase } @Test - public void testTopicRestartFromAckSession() throws Exception - { + public void testTopicRestartFromAckSession() throws Exception { ClientRequest request = new ClientRequest(generateURL("/topics/testTopic")); ClientResponse response = request.head(); diff --git a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/TransformTest.java b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/TransformTest.java index e1852b4846..b5854e4ec3 100644 --- a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/TransformTest.java +++ b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/TransformTest.java @@ -37,12 +37,10 @@ import org.junit.Test; import static org.jboss.resteasy.test.TestPortProvider.generateURL; -public class TransformTest extends MessageTestBase -{ +public class TransformTest extends MessageTestBase { @BeforeClass - public static void setup() throws Exception - { + public static void setup() throws Exception { QueueDeployment deployment = new QueueDeployment(); deployment.setDuplicatesAllowed(true); deployment.setDurableSend(false); @@ -51,81 +49,74 @@ public class TransformTest extends MessageTestBase } @XmlRootElement - public static class Order implements Serializable - { + public static class Order implements Serializable { + private static final long serialVersionUID = 2510412973800601968L; private String name; private String amount; - public String getName() - { + public String getName() { return name; } - public void setName(String name) - { + public void setName(String name) { this.name = name; } - public String getAmount() - { + public String getAmount() { return amount; } - public void setAmount(String 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; + 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; + if (!amount.equals(order.amount)) + return false; + if (!name.equals(order.name)) + return false; return true; } @Override - public int hashCode() - { + public int hashCode() { int result = name.hashCode(); result = 31 * result + amount.hashCode(); return result; } } - public static void publish(String destination, Serializable object, String contentType) throws Exception - { + public static void publish(String destination, Serializable object, String contentType) throws Exception { ClientSession session = manager.getQueueManager().getSessionFactory().createSession(); - try - { + try { ClientProducer producer = session.createProducer(destination); ClientMessage message = session.createMessage(Message.OBJECT_TYPE, false); - if (contentType == null) - { + if (contentType == null) { ActiveMQ.setEntity(message, object); } - else ActiveMQ.setEntity(message, object, contentType); + else + ActiveMQ.setEntity(message, object, contentType); producer.send(message); session.start(); } - finally - { + finally { session.close(); } } - @Test - public void testTransform() throws Exception - { + public void testTransform() throws Exception { ClientRequest request = new ClientRequest(generateURL("/queues/testQueue")); @@ -147,7 +138,6 @@ public class TransformTest extends MessageTestBase order.setAmount("$5.00"); publish("testQueue", order, null); - response = consumeNext.request().accept("application/xml").post(String.class); Assert.assertEquals(200, response.getStatus()); Assert.assertEquals("application/xml", response.getHeaders().getFirst("Content-Type").toString().toLowerCase()); @@ -193,20 +183,17 @@ public class TransformTest extends MessageTestBase } } - public static class Listener implements MessageHandler - { + public static class Listener implements MessageHandler { + public static Order order; public static CountDownLatch latch = new CountDownLatch(1); - public void onMessage(ClientMessage clientMessage) - { + public void onMessage(ClientMessage clientMessage) { System.out.println("onMessage!"); - try - { + try { order = ActiveMQ.getEntity(clientMessage, Order.class); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } latch.countDown(); @@ -214,8 +201,7 @@ public class TransformTest extends MessageTestBase } @Test - public void testJmsConsumer() throws Exception - { + public void testJmsConsumer() throws Exception { QueueDeployment deployment = new QueueDeployment(); deployment.setDuplicatesAllowed(true); deployment.setDurableSend(false); @@ -223,8 +209,7 @@ public class TransformTest extends MessageTestBase deployment.setName(queueName); manager.getQueueManager().deploy(deployment); ClientSession session = manager.getQueueManager().getSessionFactory().createSession(); - try - { + try { session.createConsumer(queueName).setMessageHandler(new Listener()); session.start(); @@ -255,8 +240,7 @@ public class TransformTest extends MessageTestBase Assert.assertEquals(order, Listener.order); } } - finally - { + finally { session.close(); } } diff --git a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/Util.java b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/Util.java index 10a14ed624..f7ab521896 100644 --- a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/Util.java +++ b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/Util.java @@ -22,28 +22,24 @@ import org.jboss.resteasy.client.ClientResponse; import org.jboss.resteasy.spi.Link; import org.junit.Assert; -public final class Util -{ - private Util() - { +public final class Util { + + private Util() { // Utility class } - static ClientResponse head(ClientRequest request) throws Exception - { + static ClientResponse head(ClientRequest request) throws Exception { ClientResponse response = request.head(); response.releaseConnection(); Assert.assertEquals(200, response.getStatus()); return response; } - static String getUrlPath(String queueName) - { + static String getUrlPath(String queueName) { return Constants.PATH_FOR_QUEUES + "/" + queueName; } - static ClientResponse setAutoAck(Link link, boolean ack) throws Exception - { + static ClientResponse setAutoAck(Link link, boolean ack) throws Exception { ClientResponse response; response = link.request().formParameter("autoAck", Boolean.toString(ack)).post(); response.releaseConnection(); diff --git a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/XmlTest.java b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/XmlTest.java index b3303eb4bd..a3c521c03c 100644 --- a/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/XmlTest.java +++ b/artemis-rest/src/test/java/org/apache/activemq/artemis/rest/test/XmlTest.java @@ -22,21 +22,20 @@ import org.junit.Test; import javax.xml.bind.JAXBContext; import java.io.StringReader; -public class XmlTest -{ +public class XmlTest { + @Test - public void testPush() throws Exception - { + public void testPush() throws Exception { String xml = "\n" + - " jms.queue.bar\n" + - " true\n" + - " 10\n" + - " \n" + - " \n" + - " guestgeheim" + - " \n" + - "
    bar
    " + - "
    "; + " jms.queue.bar\n" + + " true\n" + + " 10\n" + + " \n" + + " \n" + + " guestgeheim" + + " \n" + + "
    bar
    " + + ""; JAXBContext ctx = JAXBContext.newInstance(PushRegistration.class); PushRegistration reg = (PushRegistration) ctx.createUnmarshaller().unmarshal(new StringReader(xml)); diff --git a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/ArithmeticExpression.java b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/ArithmeticExpression.java index 9d666a221c..5440cb9d97 100755 --- a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/ArithmeticExpression.java +++ b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/ArithmeticExpression.java @@ -16,14 +16,12 @@ */ package org.apache.activemq.artemis.selector.filter; - /** * An expression which performs an operation on two expression values * * @version $Revision: 1.2 $ */ -public abstract class ArithmeticExpression extends BinaryExpression -{ +public abstract class ArithmeticExpression extends BinaryExpression { protected static final int INTEGER = 1; protected static final int LONG = 2; @@ -34,108 +32,83 @@ public abstract class ArithmeticExpression extends BinaryExpression * @param left * @param right */ - public ArithmeticExpression(Expression left, Expression right) - { + public ArithmeticExpression(Expression left, Expression right) { super(left, right); convertStringExpressions = ComparisonExpression.CONVERT_STRING_EXPRESSIONS.get() != null; } - public static Expression createPlus(Expression left, Expression right) - { - return new ArithmeticExpression(left, right) - { - protected Object evaluate(Object lvalue, Object rvalue) - { - if (lvalue instanceof String) - { + public static Expression createPlus(Expression left, Expression right) { + return new ArithmeticExpression(left, right) { + protected Object evaluate(Object lvalue, Object rvalue) { + if (lvalue instanceof String) { String text = (String) lvalue; String answer = text + rvalue; return answer; } - else - { + else { return plus(asNumber(lvalue), asNumber(rvalue)); } } - public String getExpressionSymbol() - { + public String getExpressionSymbol() { return "+"; } }; } - public static Expression createMinus(Expression left, Expression right) - { - return new ArithmeticExpression(left, right) - { - protected Object evaluate(Object lvalue, Object rvalue) - { + public static Expression createMinus(Expression left, Expression right) { + return new ArithmeticExpression(left, right) { + protected Object evaluate(Object lvalue, Object rvalue) { return minus(asNumber(lvalue), asNumber(rvalue)); } - public String getExpressionSymbol() - { + public String getExpressionSymbol() { return "-"; } }; } - public static Expression createMultiply(Expression left, Expression right) - { - return new ArithmeticExpression(left, right) - { + public static Expression createMultiply(Expression left, Expression right) { + return new ArithmeticExpression(left, right) { - protected Object evaluate(Object lvalue, Object rvalue) - { + protected Object evaluate(Object lvalue, Object rvalue) { return multiply(asNumber(lvalue), asNumber(rvalue)); } - public String getExpressionSymbol() - { + public String getExpressionSymbol() { return "*"; } }; } - public static Expression createDivide(Expression left, Expression right) - { - return new ArithmeticExpression(left, right) - { + public static Expression createDivide(Expression left, Expression right) { + return new ArithmeticExpression(left, right) { - protected Object evaluate(Object lvalue, Object rvalue) - { + protected Object evaluate(Object lvalue, Object rvalue) { return divide(asNumber(lvalue), asNumber(rvalue)); } - public String getExpressionSymbol() - { + public String getExpressionSymbol() { return "/"; } }; } - public static Expression createMod(Expression left, Expression right) - { - return new ArithmeticExpression(left, right) - { + public static Expression createMod(Expression left, Expression right) { + return new ArithmeticExpression(left, right) { - protected Object evaluate(Object lvalue, Object rvalue) - { + protected Object evaluate(Object lvalue, Object rvalue) { return mod(asNumber(lvalue), asNumber(rvalue)); } - public String getExpressionSymbol() - { + public String getExpressionSymbol() { return "%"; } }; } - protected Number plus(Number left, Number right) - { - switch (numberType(left, right)) - { + protected Number plus(Number left, Number right) { + switch (numberType(left, right)) { case INTEGER: return new Integer(left.intValue() + right.intValue()); case LONG: @@ -145,10 +118,8 @@ public abstract class ArithmeticExpression extends BinaryExpression } } - protected Number minus(Number left, Number right) - { - switch (numberType(left, right)) - { + protected Number minus(Number left, Number right) { + switch (numberType(left, right)) { case INTEGER: return new Integer(left.intValue() - right.intValue()); case LONG: @@ -158,10 +129,8 @@ public abstract class ArithmeticExpression extends BinaryExpression } } - protected Number multiply(Number left, Number right) - { - switch (numberType(left, right)) - { + protected Number multiply(Number left, Number right) { + switch (numberType(left, right)) { case INTEGER: return new Integer(left.intValue() * right.intValue()); case LONG: @@ -171,61 +140,46 @@ public abstract class ArithmeticExpression extends BinaryExpression } } - protected Number divide(Number left, Number right) - { + protected Number divide(Number left, Number right) { return new Double(left.doubleValue() / right.doubleValue()); } - protected Number mod(Number left, Number right) - { + protected Number mod(Number left, Number right) { return new Double(left.doubleValue() % right.doubleValue()); } - private int numberType(Number left, Number right) - { - if (isDouble(left) || isDouble(right)) - { + private int numberType(Number left, Number right) { + if (isDouble(left) || isDouble(right)) { return DOUBLE; } - else if (left instanceof Long || right instanceof Long) - { + else if (left instanceof Long || right instanceof Long) { return LONG; } - else - { + else { return INTEGER; } } - private boolean isDouble(Number n) - { + private boolean isDouble(Number n) { return n instanceof Float || n instanceof Double; } - protected Number asNumber(Object value) - { - if (value instanceof Number) - { + protected Number asNumber(Object value) { + if (value instanceof Number) { return (Number) value; } - else - { - if (convertStringExpressions && value instanceof String) - { + else { + if (convertStringExpressions && value instanceof String) { String v = (String) value; - try - { - if (v.contains(".")) - { + try { + if (v.contains(".")) { return new Double(v); } - else - { + else { return new Long(v); } } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { throw new RuntimeException("Cannot convert value: " + value + " into a number"); } } @@ -233,16 +187,13 @@ public abstract class ArithmeticExpression extends BinaryExpression } } - public Object evaluate(Filterable message) throws FilterException - { + public Object evaluate(Filterable message) throws FilterException { Object lvalue = left.evaluate(message); - if (lvalue == null) - { + if (lvalue == null) { return null; } Object rvalue = right.evaluate(message); - if (rvalue == null) - { + if (rvalue == null) { return null; } return evaluate(lvalue, rvalue); diff --git a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/BinaryExpression.java b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/BinaryExpression.java index e705a1f876..edee834de2 100755 --- a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/BinaryExpression.java +++ b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/BinaryExpression.java @@ -16,47 +16,40 @@ */ package org.apache.activemq.artemis.selector.filter; - /** * An expression which performs an operation on two expression values. * * @version $Revision: 1.2 $ */ -public abstract class BinaryExpression implements Expression -{ +public abstract class BinaryExpression implements Expression { + protected Expression left; protected Expression right; - public BinaryExpression(Expression left, Expression right) - { + public BinaryExpression(Expression left, Expression right) { this.left = left; this.right = right; } - public Expression getLeft() - { + public Expression getLeft() { return left; } - public Expression getRight() - { + public Expression getRight() { return right; } - /** * @see java.lang.Object#toString() */ - public String toString() - { + public String toString() { return "(" + left.toString() + " " + getExpressionSymbol() + " " + right.toString() + ")"; } /** * @see java.lang.Object#hashCode() */ - public int hashCode() - { + public int hashCode() { int result = left.hashCode(); result = 31 * result + right.hashCode(); result = 31 * result + getExpressionSymbol().hashCode(); @@ -66,32 +59,26 @@ public abstract class BinaryExpression implements Expression /** * @see java.lang.Object#equals(java.lang.Object) */ - public boolean equals(Object o) - { - if (this == o) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if (o == null || getClass() != o.getClass()) - { + if (o == null || getClass() != o.getClass()) { return false; } - final BinaryExpression that = (BinaryExpression)o; + final BinaryExpression that = (BinaryExpression) o; - if (!this.getExpressionSymbol().equals(that.getExpressionSymbol())) - { + if (!this.getExpressionSymbol().equals(that.getExpressionSymbol())) { return false; } - if (left != null && !left.equals(that.left)) - { + if (left != null && !left.equals(that.left)) { return false; } - if (right != null && !right.equals(that.right)) - { + if (right != null && !right.equals(that.right)) { return false; } @@ -109,16 +96,14 @@ public abstract class BinaryExpression implements Expression /** * @param expression */ - public void setRight(Expression expression) - { + public void setRight(Expression expression) { right = expression; } /** * @param expression */ - public void setLeft(Expression expression) - { + public void setLeft(Expression expression) { left = expression; } diff --git a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/BooleanExpression.java b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/BooleanExpression.java index 0d5cecf424..220850b951 100755 --- a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/BooleanExpression.java +++ b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/BooleanExpression.java @@ -16,15 +16,13 @@ */ package org.apache.activemq.artemis.selector.filter; - /** * A BooleanExpression is an expression that always * produces a Boolean result. * * @version $Revision: 1.2 $ */ -public interface BooleanExpression extends Expression -{ +public interface BooleanExpression extends Expression { /** * @param message diff --git a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/ComparisonExpression.java b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/ComparisonExpression.java index 2aecfbcb3a..f9dec71b3b 100755 --- a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/ComparisonExpression.java +++ b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/ComparisonExpression.java @@ -21,14 +21,12 @@ import java.util.List; import java.util.Set; import java.util.regex.Pattern; - /** * A filter performing a comparison of two objects * * @version $Revision: 1.2 $ */ -public abstract class ComparisonExpression extends BinaryExpression implements BooleanExpression -{ +public abstract class ComparisonExpression extends BinaryExpression implements BooleanExpression { public static final ThreadLocal CONVERT_STRING_EXPRESSIONS = new ThreadLocal(); @@ -39,24 +37,20 @@ public abstract class ComparisonExpression extends BinaryExpression implements B * @param left * @param right */ - public ComparisonExpression(Expression left, Expression right) - { + public ComparisonExpression(Expression left, Expression right) { super(left, right); convertStringExpressions = CONVERT_STRING_EXPRESSIONS.get() != null; } - public static BooleanExpression createBetween(Expression value, Expression left, Expression right) - { + public static BooleanExpression createBetween(Expression value, Expression left, Expression right) { return LogicExpression.createAND(createGreaterThanEqual(value, left), createLessThanEqual(value, right)); } - public static BooleanExpression createNotBetween(Expression value, Expression left, Expression right) - { + public static BooleanExpression createNotBetween(Expression value, Expression left, Expression right) { return LogicExpression.createOR(createLessThan(value, left), createGreaterThan(value, right)); } - static - { + static { REGEXP_CONTROL_CHARS.add(Character.valueOf('.')); REGEXP_CONTROL_CHARS.add(Character.valueOf('\\')); REGEXP_CONTROL_CHARS.add(Character.valueOf('[')); @@ -79,27 +73,22 @@ public abstract class ComparisonExpression extends BinaryExpression implements B REGEXP_CONTROL_CHARS.add(Character.valueOf('!')); } - static class LikeExpression extends UnaryExpression implements BooleanExpression - { + static class LikeExpression extends UnaryExpression implements BooleanExpression { Pattern likePattern; /** */ - public LikeExpression(Expression right, String like, int escape) - { + public LikeExpression(Expression right, String like, int escape) { super(right); StringBuffer regexp = new StringBuffer(like.length() * 2); regexp.append("\\A"); // The beginning of the input - for (int i = 0; i < like.length(); i++) - { + for (int i = 0; i < like.length(); i++) { char c = like.charAt(i); - if (escape == (0xFFFF & c)) - { + if (escape == (0xFFFF & c)) { i++; - if (i >= like.length()) - { + if (i >= like.length()) { // nothing left to escape... break; } @@ -108,21 +97,17 @@ public abstract class ComparisonExpression extends BinaryExpression implements B regexp.append("\\x"); regexp.append(Integer.toHexString(0xFFFF & t)); } - else if (c == '%') - { + else if (c == '%') { regexp.append(".*?"); // Do a non-greedy match } - else if (c == '_') - { + else if (c == '_') { regexp.append("."); // match one } - else if (REGEXP_CONTROL_CHARS.contains(new Character(c))) - { + else if (REGEXP_CONTROL_CHARS.contains(new Character(c))) { regexp.append("\\x"); regexp.append(Integer.toHexString(0xFFFF & c)); } - else - { + else { regexp.append(c); } } @@ -134,26 +119,22 @@ public abstract class ComparisonExpression extends BinaryExpression implements B /** * @see org.apache.activemq.filter.UnaryExpression#getExpressionSymbol() */ - public String getExpressionSymbol() - { + public String getExpressionSymbol() { return "LIKE"; } /** * @see org.apache.activemq.filter.Expression#evaluate(Filterable) */ - public Object evaluate(Filterable message) throws FilterException - { + public Object evaluate(Filterable message) throws FilterException { Object rv = this.getRight().evaluate(message); - if (rv == null) - { + if (rv == null) { return null; } - if (!(rv instanceof String)) - { + if (!(rv instanceof String)) { return Boolean.FALSE; // throw new RuntimeException("LIKE can only operate on String // identifiers. LIKE attempted on: '" + rv.getClass()); @@ -162,186 +143,149 @@ public abstract class ComparisonExpression extends BinaryExpression implements B return likePattern.matcher((String) rv).matches() ? Boolean.TRUE : Boolean.FALSE; } - public boolean matches(Filterable message) throws FilterException - { + public boolean matches(Filterable message) throws FilterException { Object object = evaluate(message); return object != null && object == Boolean.TRUE; } } - public static BooleanExpression createLike(Expression left, String right, String escape) - { - if (escape != null && escape.length() != 1) - { + public static BooleanExpression createLike(Expression left, String right, String escape) { + if (escape != null && escape.length() != 1) { throw new RuntimeException("The ESCAPE string litteral is invalid. It can only be one character. Litteral used: " + escape); } int c = -1; - if (escape != null) - { + if (escape != null) { c = 0xFFFF & escape.charAt(0); } return new LikeExpression(left, right, c); } - public static BooleanExpression createNotLike(Expression left, String right, String escape) - { + public static BooleanExpression createNotLike(Expression left, String right, String escape) { return UnaryExpression.createNOT(createLike(left, right, escape)); } - public static BooleanExpression createInFilter(Expression left, List elements) - { + public static BooleanExpression createInFilter(Expression left, List elements) { - if (!(left instanceof PropertyExpression)) - { + if (!(left instanceof PropertyExpression)) { throw new RuntimeException("Expected a property for In expression, got: " + left); } return UnaryExpression.createInExpression((PropertyExpression) left, elements, false); } - public static BooleanExpression createNotInFilter(Expression left, List elements) - { + public static BooleanExpression createNotInFilter(Expression left, List elements) { - if (!(left instanceof PropertyExpression)) - { + if (!(left instanceof PropertyExpression)) { throw new RuntimeException("Expected a property for In expression, got: " + left); } return UnaryExpression.createInExpression((PropertyExpression) left, elements, true); } - public static BooleanExpression createIsNull(Expression left) - { + public static BooleanExpression createIsNull(Expression left) { return doCreateEqual(left, ConstantExpression.NULL); } - public static BooleanExpression createIsNotNull(Expression left) - { + public static BooleanExpression createIsNotNull(Expression left) { return UnaryExpression.createNOT(doCreateEqual(left, ConstantExpression.NULL)); } - public static BooleanExpression createNotEqual(Expression left, Expression right) - { + public static BooleanExpression createNotEqual(Expression left, Expression right) { return UnaryExpression.createNOT(createEqual(left, right)); } - public static BooleanExpression createEqual(Expression left, Expression right) - { + public static BooleanExpression createEqual(Expression left, Expression right) { checkEqualOperand(left); checkEqualOperand(right); checkEqualOperandCompatibility(left, right); return doCreateEqual(left, right); } - private static BooleanExpression doCreateEqual(Expression left, Expression right) - { - return new ComparisonExpression(left, right) - { + private static BooleanExpression doCreateEqual(Expression left, Expression right) { + return new ComparisonExpression(left, right) { - public Object evaluate(Filterable message) throws FilterException - { + public Object evaluate(Filterable message) throws FilterException { Object lv = left.evaluate(message); Object rv = right.evaluate(message); // Iff one of the values is null - if (lv == null ^ rv == null) - { + if (lv == null ^ rv == null) { return Boolean.FALSE; } - if (lv == rv || lv.equals(rv)) - { + if (lv == rv || lv.equals(rv)) { return Boolean.TRUE; } - if (lv instanceof Comparable && rv instanceof Comparable) - { + if (lv instanceof Comparable && rv instanceof Comparable) { return compare((Comparable) lv, (Comparable) rv); } return Boolean.FALSE; } - protected boolean asBoolean(int answer) - { + protected boolean asBoolean(int answer) { return answer == 0; } - public String getExpressionSymbol() - { + public String getExpressionSymbol() { return "="; } }; } - public static BooleanExpression createGreaterThan(final Expression left, final Expression right) - { + public static BooleanExpression createGreaterThan(final Expression left, final Expression right) { checkLessThanOperand(left); checkLessThanOperand(right); - return new ComparisonExpression(left, right) - { - protected boolean asBoolean(int answer) - { + return new ComparisonExpression(left, right) { + protected boolean asBoolean(int answer) { return answer > 0; } - public String getExpressionSymbol() - { + public String getExpressionSymbol() { return ">"; } }; } - public static BooleanExpression createGreaterThanEqual(final Expression left, final Expression right) - { + public static BooleanExpression createGreaterThanEqual(final Expression left, final Expression right) { checkLessThanOperand(left); checkLessThanOperand(right); - return new ComparisonExpression(left, right) - { - protected boolean asBoolean(int answer) - { + return new ComparisonExpression(left, right) { + protected boolean asBoolean(int answer) { return answer >= 0; } - public String getExpressionSymbol() - { + public String getExpressionSymbol() { return ">="; } }; } - public static BooleanExpression createLessThan(final Expression left, final Expression right) - { + public static BooleanExpression createLessThan(final Expression left, final Expression right) { checkLessThanOperand(left); checkLessThanOperand(right); - return new ComparisonExpression(left, right) - { + return new ComparisonExpression(left, right) { - protected boolean asBoolean(int answer) - { + protected boolean asBoolean(int answer) { return answer < 0; } - public String getExpressionSymbol() - { + public String getExpressionSymbol() { return "<"; } }; } - public static BooleanExpression createLessThanEqual(final Expression left, final Expression right) - { + public static BooleanExpression createLessThanEqual(final Expression left, final Expression right) { checkLessThanOperand(left); checkLessThanOperand(right); - return new ComparisonExpression(left, right) - { + return new ComparisonExpression(left, right) { - protected boolean asBoolean(int answer) - { + protected boolean asBoolean(int answer) { return answer <= 0; } - public String getExpressionSymbol() - { + public String getExpressionSymbol() { return "<="; } }; @@ -352,21 +296,17 @@ public abstract class ComparisonExpression extends BinaryExpression implements B * * @param expr */ - public static void checkLessThanOperand(Expression expr) - { - if (expr instanceof ConstantExpression) - { + public static void checkLessThanOperand(Expression expr) { + if (expr instanceof ConstantExpression) { Object value = ((ConstantExpression) expr).getValue(); - if (value instanceof Number) - { + if (value instanceof Number) { return; } // Else it's boolean or a String.. throw new RuntimeException("Value '" + expr + "' cannot be compared."); } - if (expr instanceof BooleanExpression) - { + if (expr instanceof BooleanExpression) { throw new RuntimeException("Value '" + expr + "' cannot be compared."); } } @@ -377,13 +317,10 @@ public abstract class ComparisonExpression extends BinaryExpression implements B * * @param expr */ - public static void checkEqualOperand(Expression expr) - { - if (expr instanceof ConstantExpression) - { + public static void checkEqualOperand(Expression expr) { + if (expr instanceof ConstantExpression) { Object value = ((ConstantExpression) expr).getValue(); - if (value == null) - { + if (value == null) { throw new RuntimeException("'" + expr + "' cannot be compared."); } } @@ -393,247 +330,185 @@ public abstract class ComparisonExpression extends BinaryExpression implements B * @param left * @param right */ - private static void checkEqualOperandCompatibility(Expression left, Expression right) - { - if (left instanceof ConstantExpression && right instanceof ConstantExpression) - { - if (left instanceof BooleanExpression && !(right instanceof BooleanExpression)) - { + private static void checkEqualOperandCompatibility(Expression left, Expression right) { + if (left instanceof ConstantExpression && right instanceof ConstantExpression) { + if (left instanceof BooleanExpression && !(right instanceof BooleanExpression)) { throw new RuntimeException("'" + left + "' cannot be compared with '" + right + "'"); } } } - public Object evaluate(Filterable message) throws FilterException - { + public Object evaluate(Filterable message) throws FilterException { Comparable lv = (Comparable) left.evaluate(message); - if (lv == null) - { + if (lv == null) { return null; } Comparable rv = (Comparable) right.evaluate(message); - if (rv == null) - { + if (rv == null) { return null; } return compare(lv, rv); } - protected Boolean compare(Comparable lv, Comparable rv) - { + protected Boolean compare(Comparable lv, Comparable rv) { Class lc = lv.getClass(); Class rc = rv.getClass(); // If the the objects are not of the same type, // try to convert up to allow the comparison. - if (lc != rc) - { - try - { - if (lc == Boolean.class) - { - if (convertStringExpressions && rc == String.class) - { + if (lc != rc) { + try { + if (lc == Boolean.class) { + if (convertStringExpressions && rc == String.class) { rv = Boolean.valueOf((String) rv); } - else - { + else { return Boolean.FALSE; } } - else if (lc == Byte.class) - { - if (rc == Short.class) - { + else if (lc == Byte.class) { + if (rc == Short.class) { lv = Short.valueOf(((Number) lv).shortValue()); } - else if (rc == Integer.class) - { + else if (rc == Integer.class) { lv = Integer.valueOf(((Number) lv).intValue()); } - else if (rc == Long.class) - { + else if (rc == Long.class) { lv = Long.valueOf(((Number) lv).longValue()); } - else if (rc == Float.class) - { + else if (rc == Float.class) { lv = new Float(((Number) lv).floatValue()); } - else if (rc == Double.class) - { + else if (rc == Double.class) { lv = new Double(((Number) lv).doubleValue()); } - else if (convertStringExpressions && rc == String.class) - { + else if (convertStringExpressions && rc == String.class) { rv = Byte.valueOf((String) rv); } - else - { + else { return Boolean.FALSE; } } - else if (lc == Short.class) - { - if (rc == Integer.class) - { + else if (lc == Short.class) { + if (rc == Integer.class) { lv = Integer.valueOf(((Number) lv).intValue()); } - else if (rc == Long.class) - { + else if (rc == Long.class) { lv = Long.valueOf(((Number) lv).longValue()); } - else if (rc == Float.class) - { + else if (rc == Float.class) { lv = new Float(((Number) lv).floatValue()); } - else if (rc == Double.class) - { + else if (rc == Double.class) { lv = new Double(((Number) lv).doubleValue()); } - else if (convertStringExpressions && rc == String.class) - { + else if (convertStringExpressions && rc == String.class) { rv = Short.valueOf((String) rv); } - else - { + else { return Boolean.FALSE; } } - else if (lc == Integer.class) - { - if (rc == Long.class) - { + else if (lc == Integer.class) { + if (rc == Long.class) { lv = Long.valueOf(((Number) lv).longValue()); } - else if (rc == Float.class) - { + else if (rc == Float.class) { lv = new Float(((Number) lv).floatValue()); } - else if (rc == Double.class) - { + else if (rc == Double.class) { lv = new Double(((Number) lv).doubleValue()); } - else if (convertStringExpressions && rc == String.class) - { + else if (convertStringExpressions && rc == String.class) { rv = Integer.valueOf((String) rv); } - else - { + else { return Boolean.FALSE; } } - else if (lc == Long.class) - { - if (rc == Integer.class) - { + else if (lc == Long.class) { + if (rc == Integer.class) { rv = Long.valueOf(((Number) rv).longValue()); } - else if (rc == Float.class) - { + else if (rc == Float.class) { lv = new Float(((Number) lv).floatValue()); } - else if (rc == Double.class) - { + else if (rc == Double.class) { lv = new Double(((Number) lv).doubleValue()); } - else if (convertStringExpressions && rc == String.class) - { + else if (convertStringExpressions && rc == String.class) { rv = Long.valueOf((String) rv); } - else - { + else { return Boolean.FALSE; } } - else if (lc == Float.class) - { - if (rc == Integer.class) - { + else if (lc == Float.class) { + if (rc == Integer.class) { rv = new Float(((Number) rv).floatValue()); } - else if (rc == Long.class) - { + else if (rc == Long.class) { rv = new Float(((Number) rv).floatValue()); } - else if (rc == Double.class) - { + else if (rc == Double.class) { lv = new Double(((Number) lv).doubleValue()); } - else if (convertStringExpressions && rc == String.class) - { + else if (convertStringExpressions && rc == String.class) { rv = Float.valueOf((String) rv); } - else - { + else { return Boolean.FALSE; } } - else if (lc == Double.class) - { - if (rc == Integer.class) - { + else if (lc == Double.class) { + if (rc == Integer.class) { rv = new Double(((Number) rv).doubleValue()); } - else if (rc == Long.class) - { + else if (rc == Long.class) { rv = new Double(((Number) rv).doubleValue()); } - else if (rc == Float.class) - { + else if (rc == Float.class) { rv = new Double(((Number) rv).doubleValue()); } - else if (convertStringExpressions && rc == String.class) - { + else if (convertStringExpressions && rc == String.class) { rv = Double.valueOf((String) rv); } - else - { + else { return Boolean.FALSE; } } - else if (convertStringExpressions && lc == String.class) - { + else if (convertStringExpressions && lc == String.class) { - if (rc == Boolean.class) - { + if (rc == Boolean.class) { lv = Boolean.valueOf((String) lv); } - else if (rc == Byte.class) - { + else if (rc == Byte.class) { lv = Byte.valueOf((String) lv); } - else if (rc == Short.class) - { + else if (rc == Short.class) { lv = Short.valueOf((String) lv); } - else if (rc == Integer.class) - { + else if (rc == Integer.class) { lv = Integer.valueOf((String) lv); } - else if (rc == Long.class) - { + else if (rc == Long.class) { lv = Long.valueOf((String) lv); } - else if (rc == Float.class) - { + else if (rc == Float.class) { lv = Float.valueOf((String) lv); } - else if (rc == Double.class) - { + else if (rc == Double.class) { lv = Double.valueOf((String) lv); } - else - { + else { return Boolean.FALSE; } } - else - { + else { return Boolean.FALSE; } } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { return Boolean.FALSE; } } @@ -642,8 +517,7 @@ public abstract class ComparisonExpression extends BinaryExpression implements B protected abstract boolean asBoolean(int answer); - public boolean matches(Filterable message) throws FilterException - { + public boolean matches(Filterable message) throws FilterException { Object object = evaluate(message); return object != null && object == Boolean.TRUE; } diff --git a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/ConstantExpression.java b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/ConstantExpression.java index a0b556b647..60080b0d10 100755 --- a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/ConstantExpression.java +++ b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/ConstantExpression.java @@ -18,24 +18,20 @@ package org.apache.activemq.artemis.selector.filter; import java.math.BigDecimal; - /** * Represents a constant expression * * @version $Revision: 1.2 $ */ -public class ConstantExpression implements Expression -{ +public class ConstantExpression implements Expression { - static class BooleanConstantExpression extends ConstantExpression implements BooleanExpression - { - public BooleanConstantExpression(Object value) - { + static class BooleanConstantExpression extends ConstantExpression implements BooleanExpression { + + public BooleanConstantExpression(Object value) { super(value); } - public boolean matches(Filterable message) throws FilterException - { + public boolean matches(Filterable message) throws FilterException { Object object = evaluate(message); return object != null && object == Boolean.TRUE; } @@ -47,92 +43,75 @@ public class ConstantExpression implements Expression private Object value; - public ConstantExpression(Object value) - { + public ConstantExpression(Object value) { this.value = value; } - public static ConstantExpression createFromDecimal(String text) - { + public static ConstantExpression createFromDecimal(String text) { // Strip off the 'l' or 'L' if needed. - if (text.endsWith("l") || text.endsWith("L")) - { + if (text.endsWith("l") || text.endsWith("L")) { text = text.substring(0, text.length() - 1); } Number value; - try - { + try { value = new Long(text); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { // The number may be too big to fit in a long. value = new BigDecimal(text); } long l = value.longValue(); - if (Integer.MIN_VALUE <= l && l <= Integer.MAX_VALUE) - { + if (Integer.MIN_VALUE <= l && l <= Integer.MAX_VALUE) { value = Integer.valueOf(value.intValue()); } return new ConstantExpression(value); } - public static ConstantExpression createFromHex(String text) - { + public static ConstantExpression createFromHex(String text) { Number value = Long.valueOf(Long.parseLong(text.substring(2), 16)); long l = value.longValue(); - if (Integer.MIN_VALUE <= l && l <= Integer.MAX_VALUE) - { + if (Integer.MIN_VALUE <= l && l <= Integer.MAX_VALUE) { value = Integer.valueOf(value.intValue()); } return new ConstantExpression(value); } - public static ConstantExpression createFromOctal(String text) - { + public static ConstantExpression createFromOctal(String text) { Number value = Long.valueOf(Long.parseLong(text, 8)); long l = value.longValue(); - if (Integer.MIN_VALUE <= l && l <= Integer.MAX_VALUE) - { + if (Integer.MIN_VALUE <= l && l <= Integer.MAX_VALUE) { value = Integer.valueOf(value.intValue()); } return new ConstantExpression(value); } - public static ConstantExpression createFloat(String text) - { + public static ConstantExpression createFloat(String text) { Number value = new Double(text); return new ConstantExpression(value); } - public Object evaluate(Filterable message) throws FilterException - { + public Object evaluate(Filterable message) throws FilterException { return value; } - public Object getValue() - { + public Object getValue() { return value; } /** * @see java.lang.Object#toString() */ - public String toString() - { - if (value == null) - { + public String toString() { + if (value == null) { return "NULL"; } - if (value instanceof Boolean) - { + if (value instanceof Boolean) { return ((Boolean) value).booleanValue() ? "TRUE" : "FALSE"; } - if (value instanceof String) - { + if (value instanceof String) { return encodeString((String) value); } return value.toString(); @@ -141,27 +120,22 @@ public class ConstantExpression implements Expression /** * @see java.lang.Object#hashCode() */ - public int hashCode() - { + public int hashCode() { return value != null ? value.hashCode() : 0; } /** * @see java.lang.Object#equals(Object) */ - public boolean equals(final Object o) - { - if (this == o) - { + public boolean equals(final Object o) { + if (this == o) { return true; } - if (o == null || getClass() != o.getClass()) - { + if (o == null || getClass() != o.getClass()) { return false; } - final ConstantExpression that = (ConstantExpression)o; - if (value != null && !value.equals(that.value)) - { + final ConstantExpression that = (ConstantExpression) o; + if (value != null && !value.equals(that.value)) { return false; } return true; @@ -174,15 +148,12 @@ public class ConstantExpression implements Expression * @param s * @return */ - public static String encodeString(String s) - { + public static String encodeString(String s) { StringBuffer b = new StringBuffer(); b.append('\''); - for (int i = 0; i < s.length(); i++) - { + for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); - if (c == '\'') - { + if (c == '\'') { b.append(c); } b.append(c); diff --git a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/Expression.java b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/Expression.java index 633d32f715..a8a09a7faf 100755 --- a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/Expression.java +++ b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/Expression.java @@ -16,14 +16,12 @@ */ package org.apache.activemq.artemis.selector.filter; - /** * Represents an expression * * @version $Revision: 1.2 $ */ -public interface Expression -{ +public interface Expression { /** * @return the value of this expression diff --git a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/FilterException.java b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/FilterException.java index bfcf569792..18089d7fa0 100644 --- a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/FilterException.java +++ b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/FilterException.java @@ -16,28 +16,23 @@ */ package org.apache.activemq.artemis.selector.filter; -public class FilterException extends Exception -{ +public class FilterException extends Exception { private static final long serialVersionUID = -6892363158919485507L; - public FilterException() - { + public FilterException() { super(); } - public FilterException(String message, Throwable cause) - { + public FilterException(String message, Throwable cause) { super(message, cause); } - public FilterException(String message) - { + public FilterException(String message) { super(message); } - public FilterException(Throwable cause) - { + public FilterException(Throwable cause) { super(cause); } diff --git a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/Filterable.java b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/Filterable.java index 3c6a0006f7..53396137d7 100755 --- a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/Filterable.java +++ b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/Filterable.java @@ -22,8 +22,7 @@ package org.apache.activemq.artemis.selector.filter; * * @version $Revision: 1.4 $ */ -public interface Filterable -{ +public interface Filterable { /** * This method is used by message filters which do content based routing (Like the XPath diff --git a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/LogicExpression.java b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/LogicExpression.java index 1d515b1489..2fc852c043 100755 --- a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/LogicExpression.java +++ b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/LogicExpression.java @@ -16,36 +16,29 @@ */ package org.apache.activemq.artemis.selector.filter; - /** * A filter performing a comparison of two objects * * @version $Revision: 1.2 $ */ -public abstract class LogicExpression extends BinaryExpression implements BooleanExpression -{ +public abstract class LogicExpression extends BinaryExpression implements BooleanExpression { /** * @param left * @param right */ - public LogicExpression(BooleanExpression left, BooleanExpression right) - { + public LogicExpression(BooleanExpression left, BooleanExpression right) { super(left, right); } - public static BooleanExpression createOR(BooleanExpression lvalue, BooleanExpression rvalue) - { - return new LogicExpression(lvalue, rvalue) - { + public static BooleanExpression createOR(BooleanExpression lvalue, BooleanExpression rvalue) { + return new LogicExpression(lvalue, rvalue) { - public Object evaluate(Filterable message) throws FilterException - { + public Object evaluate(Filterable message) throws FilterException { Boolean lv = (Boolean) left.evaluate(message); // Can we do an OR shortcut?? - if (lv != null && lv.booleanValue()) - { + if (lv != null && lv.booleanValue()) { return Boolean.TRUE; } @@ -53,30 +46,24 @@ public abstract class LogicExpression extends BinaryExpression implements Boolea return rv == null ? null : rv; } - public String getExpressionSymbol() - { + public String getExpressionSymbol() { return "OR"; } }; } - public static BooleanExpression createAND(BooleanExpression lvalue, BooleanExpression rvalue) - { - return new LogicExpression(lvalue, rvalue) - { + public static BooleanExpression createAND(BooleanExpression lvalue, BooleanExpression rvalue) { + return new LogicExpression(lvalue, rvalue) { - public Object evaluate(Filterable message) throws FilterException - { + public Object evaluate(Filterable message) throws FilterException { Boolean lv = (Boolean) left.evaluate(message); // Can we do an AND shortcut?? - if (lv == null) - { + if (lv == null) { return null; } - if (!lv.booleanValue()) - { + if (!lv.booleanValue()) { return Boolean.FALSE; } @@ -84,8 +71,7 @@ public abstract class LogicExpression extends BinaryExpression implements Boolea return rv == null ? null : rv; } - public String getExpressionSymbol() - { + public String getExpressionSymbol() { return "AND"; } }; @@ -93,8 +79,7 @@ public abstract class LogicExpression extends BinaryExpression implements Boolea public abstract Object evaluate(Filterable message) throws FilterException; - public boolean matches(Filterable message) throws FilterException - { + public boolean matches(Filterable message) throws FilterException { Object object = evaluate(message); return object != null && object == Boolean.TRUE; } diff --git a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/PropertyExpression.java b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/PropertyExpression.java index 574ffc090c..0e0977ca42 100755 --- a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/PropertyExpression.java +++ b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/PropertyExpression.java @@ -16,55 +16,46 @@ */ package org.apache.activemq.artemis.selector.filter; - /** * Represents a property expression * * @version $Revision: 1.5 $ */ -public class PropertyExpression implements Expression -{ +public class PropertyExpression implements Expression { private final String name; - public PropertyExpression(String name) - { + public PropertyExpression(String name) { this.name = name; } - public Object evaluate(Filterable message) throws FilterException - { + public Object evaluate(Filterable message) throws FilterException { return message.getProperty(name); } - public String getName() - { + public String getName() { return name; } /** * @see java.lang.Object#toString() */ - public String toString() - { + public String toString() { return name; } /** * @see java.lang.Object#hashCode() */ - public int hashCode() - { + public int hashCode() { return name.hashCode(); } /** * @see java.lang.Object#equals(java.lang.Object) */ - public boolean equals(Object o) - { - if (o == null || !this.getClass().equals(o.getClass())) - { + public boolean equals(Object o) { + if (o == null || !this.getClass().equals(o.getClass())) { return false; } return name.equals(((PropertyExpression) o).name); diff --git a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/UnaryExpression.java b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/UnaryExpression.java index 98ba54beb6..7ae3da51ef 100755 --- a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/UnaryExpression.java +++ b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/UnaryExpression.java @@ -22,95 +22,77 @@ import java.util.HashSet; import java.util.Iterator; import java.util.List; - /** * An expression which performs an operation on two expression values * * @version $Revision: 1.3 $ */ -public abstract class UnaryExpression implements Expression -{ +public abstract class UnaryExpression implements Expression { private static final BigDecimal BD_LONG_MIN_VALUE = BigDecimal.valueOf(Long.MIN_VALUE); protected Expression right; - public UnaryExpression(Expression left) - { + public UnaryExpression(Expression left) { this.right = left; } - public static Expression createNegate(Expression left) - { - return new UnaryExpression(left) - { - public Object evaluate(Filterable message) throws FilterException - { + public static Expression createNegate(Expression left) { + return new UnaryExpression(left) { + public Object evaluate(Filterable message) throws FilterException { Object rvalue = right.evaluate(message); - if (rvalue == null) - { + if (rvalue == null) { return null; } - if (rvalue instanceof Number) - { + if (rvalue instanceof Number) { return negate((Number) rvalue); } return null; } - public String getExpressionSymbol() - { + public String getExpressionSymbol() { return "-"; } }; } - public static BooleanExpression createInExpression(PropertyExpression right, List elements, final boolean not) - { + public static BooleanExpression createInExpression(PropertyExpression right, + List elements, + final boolean not) { // Use a HashSet if there are many elements. Collection t; - if (elements.size() == 0) - { + if (elements.size() == 0) { t = null; } - else if (elements.size() < 5) - { + else if (elements.size() < 5) { t = elements; } - else - { + else { t = new HashSet(elements); } final Collection inList = t; - return new BooleanUnaryExpression(right) - { - public Object evaluate(Filterable message) throws FilterException - { + return new BooleanUnaryExpression(right) { + public Object evaluate(Filterable message) throws FilterException { Object rvalue = right.evaluate(message); - if (rvalue == null) - { + if (rvalue == null) { return null; } - if (rvalue.getClass() != String.class) - { + if (rvalue.getClass() != String.class) { return null; } - if ((inList != null && inList.contains(rvalue)) ^ not) - { + if ((inList != null && inList.contains(rvalue)) ^ not) { return Boolean.TRUE; } - else - { + else { return Boolean.FALSE; } } - public String toString() - { + public String toString() { StringBuffer answer = new StringBuffer(); answer.append(right); answer.append(" "); @@ -118,11 +100,9 @@ public abstract class UnaryExpression implements Expression answer.append(" ( "); int count = 0; - for (Iterator i = inList.iterator(); i.hasNext(); ) - { + for (Iterator i = inList.iterator(); i.hasNext(); ) { Object o = (Object) i.next(); - if (count != 0) - { + if (count != 0) { answer.append(", "); } answer.append(o); @@ -133,116 +113,91 @@ public abstract class UnaryExpression implements Expression return answer.toString(); } - public String getExpressionSymbol() - { - if (not) - { + public String getExpressionSymbol() { + if (not) { return "NOT IN"; } - else - { + else { return "IN"; } } }; } - abstract static class BooleanUnaryExpression extends UnaryExpression implements BooleanExpression - { - public BooleanUnaryExpression(Expression left) - { + abstract static class BooleanUnaryExpression extends UnaryExpression implements BooleanExpression { + + public BooleanUnaryExpression(Expression left) { super(left); } - public boolean matches(Filterable message) throws FilterException - { + public boolean matches(Filterable message) throws FilterException { Object object = evaluate(message); return object != null && object == Boolean.TRUE; } } - public static BooleanExpression createNOT(BooleanExpression left) - { - return new BooleanUnaryExpression(left) - { - public Object evaluate(Filterable message) throws FilterException - { + public static BooleanExpression createNOT(BooleanExpression left) { + return new BooleanUnaryExpression(left) { + public Object evaluate(Filterable message) throws FilterException { Boolean lvalue = (Boolean) right.evaluate(message); - if (lvalue == null) - { + if (lvalue == null) { return null; } return lvalue.booleanValue() ? Boolean.FALSE : Boolean.TRUE; } - public String getExpressionSymbol() - { + public String getExpressionSymbol() { return "NOT"; } }; } - public static BooleanExpression createXPath(final String xpath) - { + public static BooleanExpression createXPath(final String xpath) { return new XPathExpression(xpath); } - public static BooleanExpression createXQuery(final String xpath) - { + public static BooleanExpression createXQuery(final String xpath) { return new XQueryExpression(xpath); } - public static BooleanExpression createBooleanCast(Expression left) - { - return new BooleanUnaryExpression(left) - { - public Object evaluate(Filterable message) throws FilterException - { + public static BooleanExpression createBooleanCast(Expression left) { + return new BooleanUnaryExpression(left) { + public Object evaluate(Filterable message) throws FilterException { Object rvalue = right.evaluate(message); - if (rvalue == null) - { + if (rvalue == null) { return null; } - if (!rvalue.getClass().equals(Boolean.class)) - { + if (!rvalue.getClass().equals(Boolean.class)) { return Boolean.FALSE; } return ((Boolean) rvalue).booleanValue() ? Boolean.TRUE : Boolean.FALSE; } - public String toString() - { + public String toString() { return right.toString(); } - public String getExpressionSymbol() - { + public String getExpressionSymbol() { return ""; } }; } - private static Number negate(Number left) - { + private static Number negate(Number left) { Class clazz = left.getClass(); - if (clazz == Integer.class) - { + if (clazz == Integer.class) { return new Integer(-left.intValue()); } - else if (clazz == Long.class) - { + else if (clazz == Long.class) { return new Long(-left.longValue()); } - else if (clazz == Float.class) - { + else if (clazz == Float.class) { return new Float(-left.floatValue()); } - else if (clazz == Double.class) - { + else if (clazz == Double.class) { return new Double(-left.doubleValue()); } - else if (clazz == BigDecimal.class) - { + else if (clazz == BigDecimal.class) { // We ussually get a big deciamal when we have Long.MIN_VALUE // constant in the // Selector. Long.MIN_VALUE is too big to store in a Long as a @@ -253,41 +208,35 @@ public abstract class UnaryExpression implements Expression BigDecimal bd = (BigDecimal) left; bd = bd.negate(); - if (BD_LONG_MIN_VALUE.compareTo(bd) == 0) - { + if (BD_LONG_MIN_VALUE.compareTo(bd) == 0) { return Long.valueOf(Long.MIN_VALUE); } return bd; } - else - { + else { throw new RuntimeException("Don't know how to negate: " + left); } } - public Expression getRight() - { + public Expression getRight() { return right; } - public void setRight(Expression expression) - { + public void setRight(Expression expression) { right = expression; } /** * @see java.lang.Object#toString() */ - public String toString() - { + public String toString() { return "(" + getExpressionSymbol() + " " + right.toString() + ")"; } /** * @see java.lang.Object#hashCode() */ - public int hashCode() - { + public int hashCode() { int result = right.hashCode(); result = 31 * result + getExpressionSymbol().hashCode(); return result; @@ -296,27 +245,22 @@ public abstract class UnaryExpression implements Expression /** * @see java.lang.Object#equals(java.lang.Object) */ - public boolean equals(Object o) - { - if (this == o) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if (o == null || getClass() != o.getClass()) - { + if (o == null || getClass() != o.getClass()) { return false; } - final BinaryExpression that = (BinaryExpression)o; + final BinaryExpression that = (BinaryExpression) o; - if (!this.getExpressionSymbol().equals(that.getExpressionSymbol())) - { + if (!this.getExpressionSymbol().equals(that.getExpressionSymbol())) { return false; } - if (right != null && !right.equals(that.right)) - { + if (right != null && !right.equals(that.right)) { return false; } diff --git a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/XPathExpression.java b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/XPathExpression.java index 9c9b286da0..978e9bfab1 100755 --- a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/XPathExpression.java +++ b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/XPathExpression.java @@ -19,60 +19,50 @@ package org.apache.activemq.artemis.selector.filter; /** * Used to evaluate an XPath Expression in a JMS selector. */ -public final class XPathExpression implements BooleanExpression -{ +public final class XPathExpression implements BooleanExpression { public static XPathEvaluatorFactory XPATH_EVALUATOR_FACTORY = null; - static - { + static { // Install the xalan xpath evaluator if it available. new XalanXPathEvaluator("//root").evaluate(""); - try - { - XPATH_EVALUATOR_FACTORY = new XPathExpression.XPathEvaluatorFactory() - { - public XPathExpression.XPathEvaluator create(String xpath) - { + try { + XPATH_EVALUATOR_FACTORY = new XPathExpression.XPathEvaluatorFactory() { + public XPathExpression.XPathEvaluator create(String xpath) { return new XalanXPathEvaluator(xpath); } }; } - catch (Throwable e) - { + catch (Throwable e) { } } private final String xpath; private final XPathEvaluator evaluator; - public interface XPathEvaluatorFactory - { + public interface XPathEvaluatorFactory { + XPathEvaluator create(String xpath); } - public interface XPathEvaluator - { + public interface XPathEvaluator { + boolean evaluate(Filterable message) throws FilterException; } - XPathExpression(String xpath) - { - if (XPATH_EVALUATOR_FACTORY == null) - { + XPathExpression(String xpath) { + if (XPATH_EVALUATOR_FACTORY == null) { throw new IllegalArgumentException("XPATH support not enabled."); } this.xpath = xpath; this.evaluator = XPATH_EVALUATOR_FACTORY.create(xpath); } - public Object evaluate(Filterable message) throws FilterException - { + public Object evaluate(Filterable message) throws FilterException { return evaluator.evaluate(message) ? Boolean.TRUE : Boolean.FALSE; } - public String toString() - { + public String toString() { return "XPATH " + ConstantExpression.encodeString(xpath); } @@ -81,8 +71,7 @@ public final class XPathExpression implements BooleanExpression * @return true if the expression evaluates to Boolean.TRUE. * @throws FilterException */ - public boolean matches(Filterable message) throws FilterException - { + public boolean matches(Filterable message) throws FilterException { Object object = evaluate(message); return object != null && object == Boolean.TRUE; } diff --git a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/XQueryExpression.java b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/XQueryExpression.java index 3d928b061f..404bf06586 100755 --- a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/XQueryExpression.java +++ b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/XQueryExpression.java @@ -16,27 +16,23 @@ */ package org.apache.activemq.artemis.selector.filter; - /** * Used to evaluate an XQuery Expression in a JMS selector. */ -public final class XQueryExpression implements BooleanExpression -{ +public final class XQueryExpression implements BooleanExpression { + private final String xpath; - XQueryExpression(String xpath) - { + XQueryExpression(String xpath) { super(); this.xpath = xpath; } - public Object evaluate(Filterable message) throws FilterException - { + public Object evaluate(Filterable message) throws FilterException { return Boolean.FALSE; } - public String toString() - { + public String toString() { return "XQUERY " + ConstantExpression.encodeString(xpath); } @@ -45,8 +41,7 @@ public final class XQueryExpression implements BooleanExpression * @return true if the expression evaluates to Boolean.TRUE. * @throws FilterException */ - public boolean matches(Filterable message) throws FilterException - { + public boolean matches(Filterable message) throws FilterException { Object object = evaluate(message); return object != null && object == Boolean.TRUE; } diff --git a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/XalanXPathEvaluator.java b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/XalanXPathEvaluator.java index 0b09058437..798c21477e 100644 --- a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/XalanXPathEvaluator.java +++ b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/XalanXPathEvaluator.java @@ -27,36 +27,28 @@ import org.w3c.dom.Document; import org.w3c.dom.traversal.NodeIterator; import org.xml.sax.InputSource; - -public class XalanXPathEvaluator implements XPathExpression.XPathEvaluator -{ +public class XalanXPathEvaluator implements XPathExpression.XPathEvaluator { private final String xpath; - public XalanXPathEvaluator(String xpath) - { + public XalanXPathEvaluator(String xpath) { this.xpath = xpath; } - public boolean evaluate(Filterable m) throws FilterException - { + public boolean evaluate(Filterable m) throws FilterException { String stringBody = m.getBodyAs(String.class); - if (stringBody != null) - { + if (stringBody != null) { return evaluate(stringBody); } return false; } - protected boolean evaluate(String text) - { + protected boolean evaluate(String text) { return evaluate(new InputSource(new StringReader(text))); } - protected boolean evaluate(InputSource inputSource) - { - try - { + protected boolean evaluate(InputSource inputSource) { + try { DocumentBuilder dbuilder = createDocumentBuilder(); Document doc = dbuilder.parse(inputSource); @@ -69,20 +61,17 @@ public class XalanXPathEvaluator implements XPathExpression.XPathEvaluator XObject result = cachedXPathAPI.eval(doc, xpath); if (result.bool()) return true; - else - { + else { NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc, xpath); return (iterator.nextNode() != null); } } - catch (Throwable e) - { + catch (Throwable e) { return false; } } - private DocumentBuilder createDocumentBuilder() throws ParserConfigurationException - { + private DocumentBuilder createDocumentBuilder() throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); diff --git a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/impl/LRUCache.java b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/impl/LRUCache.java index 67851d192c..bbd6aced8e 100644 --- a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/impl/LRUCache.java +++ b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/impl/LRUCache.java @@ -26,16 +26,15 @@ import java.util.Map; * @param */ -public class LRUCache extends LinkedHashMap -{ +public class LRUCache extends LinkedHashMap { + private static final long serialVersionUID = -342098639681884413L; protected int maxCacheSize = 10000; /** * Default constructor for an LRU Cache The default capacity is 10000 */ - public LRUCache() - { + public LRUCache() { this(0, 10000, 0.75f, true); } @@ -44,8 +43,7 @@ public class LRUCache extends LinkedHashMap * * @param maximumCacheSize */ - public LRUCache(int maximumCacheSize) - { + public LRUCache(int maximumCacheSize) { this(0, maximumCacheSize, 0.75f, true); } @@ -62,8 +60,7 @@ public class LRUCache extends LinkedHashMap * the load factor is non-positive. */ - public LRUCache(int initialCapacity, int maximumCacheSize, float loadFactor, boolean accessOrder) - { + public LRUCache(int initialCapacity, int maximumCacheSize, float loadFactor, boolean accessOrder) { super(initialCapacity, loadFactor, accessOrder); this.maxCacheSize = maximumCacheSize; } @@ -71,30 +68,25 @@ public class LRUCache extends LinkedHashMap /** * @return Returns the maxCacheSize. */ - public int getMaxCacheSize() - { + public int getMaxCacheSize() { return maxCacheSize; } /** * @param maxCacheSize The maxCacheSize to set. */ - public void setMaxCacheSize(int maxCacheSize) - { + public void setMaxCacheSize(int maxCacheSize) { this.maxCacheSize = maxCacheSize; } - protected boolean removeEldestEntry(Map.Entry eldest) - { - if (size() > maxCacheSize) - { + protected boolean removeEldestEntry(Map.Entry eldest) { + if (size() > maxCacheSize) { onCacheEviction(eldest); return true; } return false; } - protected void onCacheEviction(Map.Entry eldest) - { + protected void onCacheEviction(Map.Entry eldest) { } } diff --git a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/impl/SelectorParser.java b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/impl/SelectorParser.java index c3301187ce..1eaf05d656 100644 --- a/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/impl/SelectorParser.java +++ b/artemis-selector/src/main/java/org/apache/activemq/artemis/selector/impl/SelectorParser.java @@ -26,8 +26,7 @@ import org.apache.activemq.artemis.selector.strict.StrictParser; /** */ -public class SelectorParser -{ +public class SelectorParser { private static final LRUCache cache = new LRUCache(100); private static final String CONVERT_STRING_EXPRESSIONS_PREFIX = "convert_string_expressions:"; @@ -35,44 +34,35 @@ public class SelectorParser private static final String NO_CONVERT_STRING_EXPRESSIONS_PREFIX = "no_convert_string_expressions:"; private static final String NO_HYPHENATED_PROPS_PREFIX = "no_hyphenated_props:"; - public static BooleanExpression parse(String sql) throws FilterException - { + public static BooleanExpression parse(String sql) throws FilterException { Object result = cache.get(sql); - if (result instanceof FilterException) - { + if (result instanceof FilterException) { throw (FilterException) result; } - else if (result instanceof BooleanExpression) - { + else if (result instanceof BooleanExpression) { return (BooleanExpression) result; } - else - { + else { String actual = sql; boolean convertStringExpressions = false; boolean hyphenatedProps = false; - while (true) - { - if (actual.startsWith(CONVERT_STRING_EXPRESSIONS_PREFIX)) - { + while (true) { + if (actual.startsWith(CONVERT_STRING_EXPRESSIONS_PREFIX)) { convertStringExpressions = true; actual = actual.substring(CONVERT_STRING_EXPRESSIONS_PREFIX.length()); continue; } - if (actual.startsWith(HYPHENATED_PROPS_PREFIX)) - { + if (actual.startsWith(HYPHENATED_PROPS_PREFIX)) { hyphenatedProps = true; actual = actual.substring(HYPHENATED_PROPS_PREFIX.length()); continue; } - if (actual.startsWith(NO_CONVERT_STRING_EXPRESSIONS_PREFIX)) - { + if (actual.startsWith(NO_CONVERT_STRING_EXPRESSIONS_PREFIX)) { convertStringExpressions = false; actual = actual.substring(NO_CONVERT_STRING_EXPRESSIONS_PREFIX.length()); continue; } - if (actual.startsWith(NO_HYPHENATED_PROPS_PREFIX)) - { + if (actual.startsWith(NO_HYPHENATED_PROPS_PREFIX)) { hyphenatedProps = false; actual = actual.substring(NO_HYPHENATED_PROPS_PREFIX.length()); continue; @@ -80,44 +70,36 @@ public class SelectorParser break; } - if (convertStringExpressions) - { + if (convertStringExpressions) { ComparisonExpression.CONVERT_STRING_EXPRESSIONS.set(true); } - try - { + try { BooleanExpression e = null; - if (hyphenatedProps) - { + if (hyphenatedProps) { HyphenatedParser parser = new HyphenatedParser(new StringReader(actual)); e = parser.JmsSelector(); } - else - { + else { StrictParser parser = new StrictParser(new StringReader(actual)); e = parser.JmsSelector(); } cache.put(sql, e); return e; } - catch (Throwable e) - { + catch (Throwable e) { FilterException fe = new FilterException(actual, e); cache.put(sql, fe); throw fe; } - finally - { - if (convertStringExpressions) - { + finally { + if (convertStringExpressions) { ComparisonExpression.CONVERT_STRING_EXPRESSIONS.remove(); } } } } - public static void clearCache() - { + public static void clearCache() { cache.clear(); } } diff --git a/artemis-selector/src/test/java/org/apache/activemq/artemis/selector/SelectorParserTest.java b/artemis-selector/src/test/java/org/apache/activemq/artemis/selector/SelectorParserTest.java index 6b924ec0d3..d234ae1fe1 100755 --- a/artemis-selector/src/test/java/org/apache/activemq/artemis/selector/SelectorParserTest.java +++ b/artemis-selector/src/test/java/org/apache/activemq/artemis/selector/SelectorParserTest.java @@ -29,29 +29,24 @@ import org.junit.Test; /** * @version $Revision: 1.2 $ */ -public class SelectorParserTest -{ +public class SelectorParserTest { - public void info(String msg) - { + public void info(String msg) { System.out.println(msg); } @Test - public void testParseXPath() throws Exception - { + public void testParseXPath() throws Exception { BooleanExpression filter = parse("XPATH '//title[@lang=''eng'']'"); Assert.assertTrue("Created XPath expression", filter instanceof XPathExpression); info("Expression: " + filter); } @Test - public void testParseWithParensAround() throws Exception - { + public void testParseWithParensAround() throws Exception { String[] values = {"x = 1 and y = 2", "(x = 1) and (y = 2)", "((x = 1) and (y = 2))"}; - for (int i = 0; i < values.length; i++) - { + for (int i = 0; i < values.length; i++) { String value = values[i]; info("Parsing: " + value); @@ -70,15 +65,13 @@ public class SelectorParserTest } } - protected void assertPropertyExpression(String message, Expression expression, String expected) - { + protected void assertPropertyExpression(String message, Expression expression, String expected) { Assert.assertTrue(message + ". Must be PropertyExpression", expression instanceof PropertyExpression); PropertyExpression propExp = (PropertyExpression) expression; Assert.assertEquals(message + ". Property name", expected, propExp.getName()); } - protected BooleanExpression parse(String text) throws Exception - { + protected BooleanExpression parse(String text) throws Exception { return SelectorParser.parse(text); } } diff --git a/artemis-selector/src/test/java/org/apache/activemq/artemis/selector/SelectorTest.java b/artemis-selector/src/test/java/org/apache/activemq/artemis/selector/SelectorTest.java index 6103f33775..abd1a85a69 100755 --- a/artemis-selector/src/test/java/org/apache/activemq/artemis/selector/SelectorTest.java +++ b/artemis-selector/src/test/java/org/apache/activemq/artemis/selector/SelectorTest.java @@ -28,11 +28,9 @@ import org.junit.Test; /** * @version $Revision: 1.7 $ */ -public class SelectorTest -{ +public class SelectorTest { - class MockMessage implements Filterable - { + class MockMessage implements Filterable { HashMap properties = new HashMap(); private String text; @@ -41,110 +39,87 @@ public class SelectorTest private String type; private Object localConnectionId; - public void setDestination(Object destination) - { + public void setDestination(Object destination) { this.destination = destination; } - public void setJMSMessageID(String messageId) - { + public void setJMSMessageID(String messageId) { this.messageId = messageId; } - public void setJMSType(String type) - { + public void setJMSType(String type) { this.type = type; } - public void setText(String text) - { + public void setText(String text) { this.text = text; } - public void setBooleanProperty(String key, boolean value) - { + public void setBooleanProperty(String key, boolean value) { properties.put(key, value); } - public void setStringProperty(String key, String value) - { + public void setStringProperty(String key, String value) { properties.put(key, value); } - public void setByteProperty(String key, byte value) - { + public void setByteProperty(String key, byte value) { properties.put(key, value); } - public void setDoubleProperty(String key, double value) - { + public void setDoubleProperty(String key, double value) { properties.put(key, value); } - public void setFloatProperty(String key, float value) - { + public void setFloatProperty(String key, float value) { properties.put(key, value); } - public void setLongProperty(String key, long value) - { + public void setLongProperty(String key, long value) { properties.put(key, value); } - public void setIntProperty(String key, int value) - { + public void setIntProperty(String key, int value) { properties.put(key, value); } - public void setShortProperty(String key, short value) - { + public void setShortProperty(String key, short value) { properties.put(key, value); } - public void setObjectProperty(String key, Object value) - { + public void setObjectProperty(String key, Object value) { properties.put(key, value); } - public T getBodyAs(Class type) throws FilterException - { - if (type == String.class) - { + public T getBodyAs(Class type) throws FilterException { + if (type == String.class) { return type.cast(text); } return null; } - public Object getProperty(String name) - { - if ("JMSType".equals(name)) - { + public Object getProperty(String name) { + if ("JMSType".equals(name)) { return type; } - if ("JMSMessageID".equals(name)) - { + if ("JMSMessageID".equals(name)) { return messageId; } return properties.get(name); } - public Object getDestination() - { + public Object getDestination() { return destination; } - public Object getLocalConnectionId() - { + public Object getLocalConnectionId() { return localConnectionId; } - } - @Test - public void testBooleanSelector() throws Exception - { + public void testBooleanSelector() throws Exception { MockMessage message = createMessage(); assertSelector(message, "(trueProp OR falseProp) AND trueProp", true); @@ -153,8 +128,7 @@ public class SelectorTest } @Test - public void testXPathSelectors() throws Exception - { + public void testXPathSelectors() throws Exception { MockMessage message = new MockMessage(); message.setJMSType("xml"); @@ -197,8 +171,7 @@ public class SelectorTest } @Test - public void testJMSPropertySelectors() throws Exception - { + public void testJMSPropertySelectors() throws Exception { MockMessage message = createMessage(); message.setJMSType("selector-test"); message.setJMSMessageID("id:test:1:1:1:1"); @@ -218,8 +191,7 @@ public class SelectorTest } @Test - public void testBasicSelectors() throws Exception - { + public void testBasicSelectors() throws Exception { MockMessage message = createMessage(); assertSelector(message, "name = 'James'", true); @@ -230,8 +202,7 @@ public class SelectorTest } @Test - public void testPropertyTypes() throws Exception - { + public void testPropertyTypes() throws Exception { MockMessage message = createMessage(); assertSelector(message, "byteProp = 123", true); assertSelector(message, "byteProp = 10", false); @@ -258,8 +229,7 @@ public class SelectorTest } @Test - public void testAndSelectors() throws Exception - { + public void testAndSelectors() throws Exception { MockMessage message = createMessage(); assertSelector(message, "name = 'James' and rank < 200", true); @@ -269,8 +239,7 @@ public class SelectorTest } @Test - public void testOrSelectors() throws Exception - { + public void testOrSelectors() throws Exception { MockMessage message = createMessage(); assertSelector(message, "name = 'James' or rank < 200", true); @@ -281,8 +250,7 @@ public class SelectorTest } @Test - public void testPlus() throws Exception - { + public void testPlus() throws Exception { MockMessage message = createMessage(); assertSelector(message, "rank + 2 = 125", true); @@ -294,8 +262,7 @@ public class SelectorTest } @Test - public void testMinus() throws Exception - { + public void testMinus() throws Exception { MockMessage message = createMessage(); assertSelector(message, "rank - 2 = 121", true); @@ -304,8 +271,7 @@ public class SelectorTest } @Test - public void testMultiply() throws Exception - { + public void testMultiply() throws Exception { MockMessage message = createMessage(); assertSelector(message, "rank * 2 = 246", true); @@ -314,8 +280,7 @@ public class SelectorTest } @Test - public void testDivide() throws Exception - { + public void testDivide() throws Exception { MockMessage message = createMessage(); assertSelector(message, "rank / version = 61.5", true); @@ -326,8 +291,7 @@ public class SelectorTest } @Test - public void testBetween() throws Exception - { + public void testBetween() throws Exception { MockMessage message = createMessage(); assertSelector(message, "rank between 100 and 150", true); @@ -335,8 +299,7 @@ public class SelectorTest } @Test - public void testIn() throws Exception - { + public void testIn() throws Exception { MockMessage message = createMessage(); assertSelector(message, "name in ('James', 'Bob', 'Gromit')", true); @@ -348,8 +311,7 @@ public class SelectorTest } @Test - public void testIsNull() throws Exception - { + public void testIsNull() throws Exception { MockMessage message = createMessage(); assertSelector(message, "dummy is null", true); @@ -359,37 +321,32 @@ public class SelectorTest } @Test - public void testLike() throws Exception - { + public void testLike() throws Exception { MockMessage message = createMessage(); message.setStringProperty("modelClassId", "com.whatever.something.foo.bar"); message.setStringProperty("modelInstanceId", "170"); message.setStringProperty("modelRequestError", "abc"); message.setStringProperty("modelCorrelatedClientId", "whatever"); - assertSelector(message, "modelClassId LIKE 'com.whatever.something.%' AND modelInstanceId = '170' AND (modelRequestError IS NULL OR modelCorrelatedClientId = 'whatever')", - true); + assertSelector(message, "modelClassId LIKE 'com.whatever.something.%' AND modelInstanceId = '170' AND (modelRequestError IS NULL OR modelCorrelatedClientId = 'whatever')", true); message.setStringProperty("modelCorrelatedClientId", "shouldFailNow"); - assertSelector(message, "modelClassId LIKE 'com.whatever.something.%' AND modelInstanceId = '170' AND (modelRequestError IS NULL OR modelCorrelatedClientId = 'whatever')", - false); + assertSelector(message, "modelClassId LIKE 'com.whatever.something.%' AND modelInstanceId = '170' AND (modelRequestError IS NULL OR modelCorrelatedClientId = 'whatever')", false); message = createMessage(); message.setStringProperty("modelClassId", "com.whatever.something.foo.bar"); message.setStringProperty("modelInstanceId", "170"); message.setStringProperty("modelCorrelatedClientId", "shouldNotMatch"); - assertSelector(message, "modelClassId LIKE 'com.whatever.something.%' AND modelInstanceId = '170' AND (modelRequestError IS NULL OR modelCorrelatedClientId = 'whatever')", - true); + assertSelector(message, "modelClassId LIKE 'com.whatever.something.%' AND modelInstanceId = '170' AND (modelRequestError IS NULL OR modelCorrelatedClientId = 'whatever')", true); } /** * Test cases from Mats Henricson */ @Test - public void testMatsHenricsonUseCases() throws Exception - { + public void testMatsHenricsonUseCases() throws Exception { MockMessage message = createMessage(); assertSelector(message, "SessionserverId=1870414179", false); @@ -411,8 +368,7 @@ public class SelectorTest } @Test - public void testFloatComparisons() throws Exception - { + public void testFloatComparisons() throws Exception { MockMessage message = createMessage(); // JMS 1.1 Section 3.8.1.1 : Approximate literals use the Java @@ -462,15 +418,13 @@ public class SelectorTest } @Test - public void testStringQuoteParsing() throws Exception - { + public void testStringQuoteParsing() throws Exception { MockMessage message = createMessage(); assertSelector(message, "quote = '''In God We Trust'''", true); } @Test - public void testLikeComparisons() throws Exception - { + public void testLikeComparisons() throws Exception { MockMessage message = createMessage(); assertSelector(message, "quote LIKE '''In G_d We Trust'''", true); @@ -492,16 +446,14 @@ public class SelectorTest } @Test - public void testInvalidSelector() throws Exception - { + public void testInvalidSelector() throws Exception { MockMessage message = createMessage(); assertInvalidSelector(message, "3+5"); assertInvalidSelector(message, "True AND 3+5"); assertInvalidSelector(message, "=TEST 'test'"); } - protected MockMessage createMessage() - { + protected MockMessage createMessage() { MockMessage message = createMessage("FOO.BAR"); message.setJMSType("selector-test"); message.setJMSMessageID("connection:1:1:1:1"); @@ -526,28 +478,23 @@ public class SelectorTest return message; } - protected void assertInvalidSelector(MockMessage message, String text) - { - try - { + protected void assertInvalidSelector(MockMessage message, String text) { + try { SelectorParser.parse(text); Assert.fail("Created a valid selector"); } - catch (FilterException e) - { + catch (FilterException e) { } } - protected void assertSelector(MockMessage message, String text, boolean expected) throws FilterException - { + protected void assertSelector(MockMessage message, String text, boolean expected) throws FilterException { BooleanExpression selector = SelectorParser.parse(text); Assert.assertTrue("Created a valid selector", selector != null); boolean value = selector.matches(message); Assert.assertEquals("Selector for: " + text, expected, value); } - protected MockMessage createMessage(String subject) - { + protected MockMessage createMessage(String subject) { MockMessage message = new MockMessage(); message.setDestination(subject); return message; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/api/core/management/MessageCounterInfo.java b/artemis-server/src/main/java/org/apache/activemq/artemis/api/core/management/MessageCounterInfo.java index 46aae8685a..dba80b617b 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/api/core/management/MessageCounterInfo.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/api/core/management/MessageCounterInfo.java @@ -26,8 +26,8 @@ import org.apache.activemq.artemis.utils.json.JSONObject; * Helper class to create Java Objects from the * JSON serialization returned by {@link QueueControl#listMessageCounter()}. */ -public final class MessageCounterInfo -{ +public final class MessageCounterInfo { + private final String name; private final String subscription; @@ -48,12 +48,12 @@ public final class MessageCounterInfo /** * Returns a JSON String serialization of a {@link MessageCounter} object. + * * @param counter * @return * @throws Exception */ - public static String toJSon(final MessageCounter counter) throws Exception - { + public static String toJSon(final MessageCounter counter) throws Exception { DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM); JSONObject json = new JSONObject(counter); @@ -69,8 +69,7 @@ public final class MessageCounterInfo * Returns an array of RoleInfo corresponding to the JSON serialization returned * by {@link QueueControl#listMessageCounter()}. */ - public static MessageCounterInfo fromJSON(final String jsonString) throws Exception - { + public static MessageCounterInfo fromJSON(final String jsonString) throws Exception { JSONObject data = new JSONObject(jsonString); String name = data.getString("destinationName"); String subscription = data.getString("destinationSubscription"); @@ -82,15 +81,7 @@ public final class MessageCounterInfo String lastAddTimestamp = data.getString("lastAddTimestamp"); String updateTimestamp = data.getString("updateTimestamp"); - return new MessageCounterInfo(name, - subscription, - durable, - count, - countDelta, - depth, - depthDelta, - lastAddTimestamp, - updateTimestamp); + return new MessageCounterInfo(name, subscription, durable, count, countDelta, depth, depthDelta, lastAddTimestamp, updateTimestamp); } // Constructors -------------------------------------------------- @@ -103,8 +94,7 @@ public final class MessageCounterInfo final int depth, final int depthDelta, final String lastAddTimestamp, - final String udpateTimestamp) - { + final String udpateTimestamp) { this.name = name; this.subscription = subscription; this.durable = durable; @@ -121,72 +111,63 @@ public final class MessageCounterInfo /** * Returns the name of the queue. */ - public String getName() - { + public String getName() { return name; } /** * Returns the name of the subscription. */ - public String getSubscription() - { + public String getSubscription() { return subscription; } /** * Returns whether the queue is durable. */ - public boolean isDurable() - { + public boolean isDurable() { return durable; } /** * Returns the number of messages added to the queue since it was created. */ - public long getCount() - { + public long getCount() { return count; } /** * Returns the number of messages added to the queue since the last counter sample. */ - public long getCountDelta() - { + public long getCountDelta() { return countDelta; } /** * Returns the number of messages currently in the queue. */ - public int getDepth() - { + public int getDepth() { return depth; } /** * Returns the number of messages in the queue since last counter sample. */ - public int getDepthDelta() - { + public int getDepthDelta() { return depthDelta; } /** * Returns the timestamp of the last time a message was added to the queue. */ - public String getLastAddTimestamp() - { + public String getLastAddTimestamp() { return lastAddTimestamp; } /** * Returns the timestamp of the last time the queue was updated. */ - public String getUdpateTimestamp() - { + public String getUdpateTimestamp() { return udpateTimestamp; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/BackupStrategy.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/BackupStrategy.java index 05df5e9436..2d7a30ac1b 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/BackupStrategy.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/BackupStrategy.java @@ -16,9 +16,7 @@ */ package org.apache.activemq.artemis.core.config; - -public enum BackupStrategy -{ +public enum BackupStrategy { FULL, SCALE_DOWN } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/BridgeConfiguration.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/BridgeConfiguration.java index 7a996de58f..0ce0ce8aad 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/BridgeConfiguration.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/BridgeConfiguration.java @@ -22,8 +22,8 @@ import java.util.List; import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration; import org.apache.activemq.artemis.api.core.client.ActiveMQClient; -public final class BridgeConfiguration implements Serializable -{ +public final class BridgeConfiguration implements Serializable { + private static final long serialVersionUID = -1057244274380572226L; private String name = null; @@ -72,35 +72,29 @@ public final class BridgeConfiguration implements Serializable // The bridge shouldn't be sending blocking anyways private long callTimeout = ActiveMQClient.DEFAULT_CALL_TIMEOUT; - - public BridgeConfiguration() - { + public BridgeConfiguration() { } - public String getName() - { + public String getName() { return name; } /** * @param name the name to set */ - public BridgeConfiguration setName(final String name) - { + public BridgeConfiguration setName(final String name) { this.name = name; return this; } - public String getQueueName() - { + public String getQueueName() { return queueName; } /** * @param queueName the queueName to set */ - public BridgeConfiguration setQueueName(final String queueName) - { + public BridgeConfiguration setQueueName(final String queueName) { this.queueName = queueName; return this; } @@ -108,13 +102,11 @@ public final class BridgeConfiguration implements Serializable /** * @return the connectionTTL */ - public long getConnectionTTL() - { + public long getConnectionTTL() { return connectionTTL; } - public BridgeConfiguration setConnectionTTL(long connectionTTL) - { + public BridgeConfiguration setConnectionTTL(long connectionTTL) { this.connectionTTL = connectionTTL; return this; } @@ -122,193 +114,164 @@ public final class BridgeConfiguration implements Serializable /** * @return the maxRetryInterval */ - public long getMaxRetryInterval() - { + public long getMaxRetryInterval() { return maxRetryInterval; } - public BridgeConfiguration setMaxRetryInterval(long maxRetryInterval) - { + public BridgeConfiguration setMaxRetryInterval(long maxRetryInterval) { this.maxRetryInterval = maxRetryInterval; return this; } - public String getForwardingAddress() - { + public String getForwardingAddress() { return forwardingAddress; } /** * @param forwardingAddress the forwardingAddress to set */ - public BridgeConfiguration setForwardingAddress(final String forwardingAddress) - { + public BridgeConfiguration setForwardingAddress(final String forwardingAddress) { this.forwardingAddress = forwardingAddress; return this; } - public String getFilterString() - { + public String getFilterString() { return filterString; } /** * @param filterString the filterString to set */ - public BridgeConfiguration setFilterString(final String filterString) - { + public BridgeConfiguration setFilterString(final String filterString) { this.filterString = filterString; return this; } - public String getTransformerClassName() - { + public String getTransformerClassName() { return transformerClassName; } /** * @param transformerClassName the transformerClassName to set */ - public BridgeConfiguration setTransformerClassName(final String transformerClassName) - { + public BridgeConfiguration setTransformerClassName(final String transformerClassName) { this.transformerClassName = transformerClassName; return this; } - public List getStaticConnectors() - { + public List getStaticConnectors() { return staticConnectors; } /** * @param staticConnectors the staticConnectors to set */ - public BridgeConfiguration setStaticConnectors(final List staticConnectors) - { + public BridgeConfiguration setStaticConnectors(final List staticConnectors) { this.staticConnectors = staticConnectors; return this; } - public String getDiscoveryGroupName() - { + public String getDiscoveryGroupName() { return discoveryGroupName; } /** * @param discoveryGroupName the discoveryGroupName to set */ - public BridgeConfiguration setDiscoveryGroupName(final String discoveryGroupName) - { + public BridgeConfiguration setDiscoveryGroupName(final String discoveryGroupName) { this.discoveryGroupName = discoveryGroupName; return this; } - public boolean isHA() - { + public boolean isHA() { return ha; } /** - * * @param ha is the bridge supporting HA? */ - public BridgeConfiguration setHA(final boolean ha) - { + public BridgeConfiguration setHA(final boolean ha) { this.ha = ha; return this; } - public long getRetryInterval() - { + public long getRetryInterval() { return retryInterval; } /** * @param retryInterval the retryInterval to set */ - public BridgeConfiguration setRetryInterval(final long retryInterval) - { + public BridgeConfiguration setRetryInterval(final long retryInterval) { this.retryInterval = retryInterval; return this; } - public double getRetryIntervalMultiplier() - { + public double getRetryIntervalMultiplier() { return retryIntervalMultiplier; } /** * @param retryIntervalMultiplier the retryIntervalMultiplier to set */ - public BridgeConfiguration setRetryIntervalMultiplier(final double retryIntervalMultiplier) - { + public BridgeConfiguration setRetryIntervalMultiplier(final double retryIntervalMultiplier) { this.retryIntervalMultiplier = retryIntervalMultiplier; return this; } - public int getInitialConnectAttempts() - { + public int getInitialConnectAttempts() { return initialConnectAttempts; } /** * @param initialConnectAttempts the initialConnectAttempts to set */ - public BridgeConfiguration setInitialConnectAttempts(final int initialConnectAttempts) - { + public BridgeConfiguration setInitialConnectAttempts(final int initialConnectAttempts) { this.initialConnectAttempts = initialConnectAttempts; return this; } - public int getReconnectAttempts() - { + public int getReconnectAttempts() { return reconnectAttempts; } /** * @param reconnectAttempts the reconnectAttempts to set */ - public BridgeConfiguration setReconnectAttempts(final int reconnectAttempts) - { + public BridgeConfiguration setReconnectAttempts(final int reconnectAttempts) { this.reconnectAttempts = reconnectAttempts; return this; } - public boolean isUseDuplicateDetection() - { + public boolean isUseDuplicateDetection() { return useDuplicateDetection; } /** * @param useDuplicateDetection the useDuplicateDetection to set */ - public BridgeConfiguration setUseDuplicateDetection(final boolean useDuplicateDetection) - { + public BridgeConfiguration setUseDuplicateDetection(final boolean useDuplicateDetection) { this.useDuplicateDetection = useDuplicateDetection; return this; } - public int getConfirmationWindowSize() - { + public int getConfirmationWindowSize() { return confirmationWindowSize; } /** * @param confirmationWindowSize the confirmationWindowSize to set */ - public BridgeConfiguration setConfirmationWindowSize(final int confirmationWindowSize) - { + public BridgeConfiguration setConfirmationWindowSize(final int confirmationWindowSize) { this.confirmationWindowSize = confirmationWindowSize; return this; } - public long getClientFailureCheckPeriod() - { + public long getClientFailureCheckPeriod() { return clientFailureCheckPeriod; } - public BridgeConfiguration setClientFailureCheckPeriod(long clientFailureCheckPeriod) - { + public BridgeConfiguration setClientFailureCheckPeriod(long clientFailureCheckPeriod) { this.clientFailureCheckPeriod = clientFailureCheckPeriod; return this; } @@ -316,35 +279,29 @@ public final class BridgeConfiguration implements Serializable /** * @return the minLargeMessageSize */ - public int getMinLargeMessageSize() - { + public int getMinLargeMessageSize() { return minLargeMessageSize; } - public BridgeConfiguration setMinLargeMessageSize(int minLargeMessageSize) - { + public BridgeConfiguration setMinLargeMessageSize(int minLargeMessageSize) { this.minLargeMessageSize = minLargeMessageSize; return this; } - public String getUser() - { + public String getUser() { return user; } - public BridgeConfiguration setUser(String user) - { + public BridgeConfiguration setUser(String user) { this.user = user; return this; } - public String getPassword() - { + public String getPassword() { return password; } - public BridgeConfiguration setPassword(String password) - { + public BridgeConfiguration setPassword(String password) { this.password = password; return this; } @@ -352,58 +309,53 @@ public final class BridgeConfiguration implements Serializable /** * @return the callTimeout */ - public long getCallTimeout() - { + public long getCallTimeout() { return callTimeout; } - public int getReconnectAttemptsOnSameNode() - { + public int getReconnectAttemptsOnSameNode() { return reconnectAttemptsOnSameNode; } - public BridgeConfiguration setReconnectAttemptsOnSameNode(int reconnectAttemptsOnSameNode) - { + public BridgeConfiguration setReconnectAttemptsOnSameNode(int reconnectAttemptsOnSameNode) { this.reconnectAttemptsOnSameNode = reconnectAttemptsOnSameNode; return this; } /** - * * At this point this is only changed on testcases * The bridge shouldn't be sending blocking anyways + * * @param callTimeout the callTimeout to set */ - public BridgeConfiguration setCallTimeout(long callTimeout) - { + public BridgeConfiguration setCallTimeout(long callTimeout) { this.callTimeout = callTimeout; return this; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + (int)(callTimeout ^ (callTimeout >>> 32)); - result = prime * result + (int)(clientFailureCheckPeriod ^ (clientFailureCheckPeriod >>> 32)); + result = prime * result + (int) (callTimeout ^ (callTimeout >>> 32)); + result = prime * result + (int) (clientFailureCheckPeriod ^ (clientFailureCheckPeriod >>> 32)); result = prime * result + confirmationWindowSize; - result = prime * result + (int)(connectionTTL ^ (connectionTTL >>> 32)); + result = prime * result + (int) (connectionTTL ^ (connectionTTL >>> 32)); result = prime * result + ((discoveryGroupName == null) ? 0 : discoveryGroupName.hashCode()); result = prime * result + ((filterString == null) ? 0 : filterString.hashCode()); result = prime * result + ((forwardingAddress == null) ? 0 : forwardingAddress.hashCode()); result = prime * result + (ha ? 1231 : 1237); - result = prime * result + (int)(maxRetryInterval ^ (maxRetryInterval >>> 32)); + result = prime * result + (int) (maxRetryInterval ^ (maxRetryInterval >>> 32)); result = prime * result + minLargeMessageSize; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((password == null) ? 0 : password.hashCode()); result = prime * result + ((queueName == null) ? 0 : queueName.hashCode()); result = prime * result + initialConnectAttempts; result = prime * result + reconnectAttempts; - result = prime * result + (int)(retryInterval ^ (retryInterval >>> 32)); + result = prime * result + (int) (retryInterval ^ (retryInterval >>> 32)); long temp; temp = Double.doubleToLongBits(retryIntervalMultiplier); - result = prime * result + (int)(temp ^ (temp >>> 32)); + result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + ((staticConnectors == null) ? 0 : staticConnectors.hashCode()); result = prime * result + ((transformerClassName == null) ? 0 : transformerClassName.hashCode()); result = prime * result + (useDuplicateDetection ? 1231 : 1237); @@ -412,15 +364,14 @@ public final class BridgeConfiguration implements Serializable } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; - BridgeConfiguration other = (BridgeConfiguration)obj; + BridgeConfiguration other = (BridgeConfiguration) obj; if (callTimeout != other.callTimeout) return false; if (clientFailureCheckPeriod != other.clientFailureCheckPeriod) @@ -429,22 +380,19 @@ public final class BridgeConfiguration implements Serializable return false; if (connectionTTL != other.connectionTTL) return false; - if (discoveryGroupName == null) - { + if (discoveryGroupName == null) { if (other.discoveryGroupName != null) return false; } else if (!discoveryGroupName.equals(other.discoveryGroupName)) return false; - if (filterString == null) - { + if (filterString == null) { if (other.filterString != null) return false; } else if (!filterString.equals(other.filterString)) return false; - if (forwardingAddress == null) - { + if (forwardingAddress == null) { if (other.forwardingAddress != null) return false; } @@ -456,22 +404,19 @@ public final class BridgeConfiguration implements Serializable return false; if (minLargeMessageSize != other.minLargeMessageSize) return false; - if (name == null) - { + if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; - if (password == null) - { + if (password == null) { if (other.password != null) return false; } else if (!password.equals(other.password)) return false; - if (queueName == null) - { + if (queueName == null) { if (other.queueName != null) return false; } @@ -485,15 +430,13 @@ public final class BridgeConfiguration implements Serializable return false; if (Double.doubleToLongBits(retryIntervalMultiplier) != Double.doubleToLongBits(other.retryIntervalMultiplier)) return false; - if (staticConnectors == null) - { + if (staticConnectors == null) { if (other.staticConnectors != null) return false; } else if (!staticConnectors.equals(other.staticConnectors)) return false; - if (transformerClassName == null) - { + if (transformerClassName == null) { if (other.transformerClassName != null) return false; } @@ -501,8 +444,7 @@ public final class BridgeConfiguration implements Serializable return false; if (useDuplicateDetection != other.useDuplicateDetection) return false; - if (user == null) - { + if (user == null) { if (other.user != null) return false; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ClusterConnectionConfiguration.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ClusterConnectionConfiguration.java index ccb3e7c7e2..d1256115ed 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ClusterConnectionConfiguration.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ClusterConnectionConfiguration.java @@ -24,8 +24,8 @@ import java.io.Serializable; import java.util.Collections; import java.util.List; -public final class ClusterConnectionConfiguration implements Serializable -{ +public final class ClusterConnectionConfiguration implements Serializable { + private static final long serialVersionUID = 8948303813427795935L; private String name; @@ -72,28 +72,23 @@ public final class ClusterConnectionConfiguration implements Serializable private int clusterNotificationAttempts = ActiveMQDefaultConfiguration.getDefaultClusterNotificationAttempts(); - public ClusterConnectionConfiguration() - { + public ClusterConnectionConfiguration() { } - public String getName() - { + public String getName() { return name; } - public ClusterConnectionConfiguration setName(String name) - { + public ClusterConnectionConfiguration setName(String name) { this.name = name; return this; } - public String getAddress() - { + public String getAddress() { return address; } - public ClusterConnectionConfiguration setAddress(String address) - { + public ClusterConnectionConfiguration setAddress(String address) { this.address = address; return this; } @@ -101,156 +96,130 @@ public final class ClusterConnectionConfiguration implements Serializable /** * @return the clientFailureCheckPeriod */ - public long getClientFailureCheckPeriod() - { + public long getClientFailureCheckPeriod() { return clientFailureCheckPeriod; } /** * @return the connectionTTL */ - public long getConnectionTTL() - { + public long getConnectionTTL() { return connectionTTL; } /** * @return the retryIntervalMultiplier */ - public double getRetryIntervalMultiplier() - { + public double getRetryIntervalMultiplier() { return retryIntervalMultiplier; } /** * @return the maxRetryInterval */ - public long getMaxRetryInterval() - { + public long getMaxRetryInterval() { return maxRetryInterval; } /** * @return the initialConnectAttempts */ - public int getInitialConnectAttempts() - { + public int getInitialConnectAttempts() { return initialConnectAttempts; } /** * @return the reconnectAttempts */ - public int getReconnectAttempts() - { + public int getReconnectAttempts() { return reconnectAttempts; } - public long getCallTimeout() - { + public long getCallTimeout() { return callTimeout; } - public long getCallFailoverTimeout() - { + public long getCallFailoverTimeout() { return callFailoverTimeout; } - public String getConnectorName() - { + public String getConnectorName() { return connectorName; } - public ClusterConnectionConfiguration setConnectorName(String connectorName) - { + public ClusterConnectionConfiguration setConnectorName(String connectorName) { this.connectorName = connectorName; return this; } - public boolean isDuplicateDetection() - { + public boolean isDuplicateDetection() { return duplicateDetection; } - public MessageLoadBalancingType getMessageLoadBalancingType() - { + public MessageLoadBalancingType getMessageLoadBalancingType() { return messageLoadBalancingType; } - public int getMaxHops() - { + public int getMaxHops() { return maxHops; } - public ClusterConnectionConfiguration setMaxHops(int maxHops) - { + public ClusterConnectionConfiguration setMaxHops(int maxHops) { this.maxHops = maxHops; return this; } - public int getConfirmationWindowSize() - { + public int getConfirmationWindowSize() { return confirmationWindowSize; } - public ClusterConnectionConfiguration setConfirmationWindowSize(int confirmationWindowSize) - { + public ClusterConnectionConfiguration setConfirmationWindowSize(int confirmationWindowSize) { this.confirmationWindowSize = confirmationWindowSize; return this; } - public List getStaticConnectors() - { + public List getStaticConnectors() { return staticConnectors; } - public ClusterConnectionConfiguration setStaticConnectors(List staticConnectors) - { + public ClusterConnectionConfiguration setStaticConnectors(List staticConnectors) { this.staticConnectors = staticConnectors; return this; } - public String getDiscoveryGroupName() - { + public String getDiscoveryGroupName() { return discoveryGroupName; } - public ClusterConnectionConfiguration setDiscoveryGroupName(String discoveryGroupName) - { + public ClusterConnectionConfiguration setDiscoveryGroupName(String discoveryGroupName) { this.discoveryGroupName = discoveryGroupName; return this; } - public long getRetryInterval() - { + public long getRetryInterval() { return retryInterval; } - public boolean isAllowDirectConnectionsOnly() - { + public boolean isAllowDirectConnectionsOnly() { return allowDirectConnectionsOnly; } - public ClusterConnectionConfiguration setAllowDirectConnectionsOnly(boolean allowDirectConnectionsOnly) - { + public ClusterConnectionConfiguration setAllowDirectConnectionsOnly(boolean allowDirectConnectionsOnly) { this.allowDirectConnectionsOnly = allowDirectConnectionsOnly; return this; } - /** * @return the minLargeMessageSize */ - public int getMinLargeMessageSize() - { + public int getMinLargeMessageSize() { return minLargeMessageSize; } /** * @param minLargeMessageSize the minLargeMessageSize to set */ - public ClusterConnectionConfiguration setMinLargeMessageSize(final int minLargeMessageSize) - { + public ClusterConnectionConfiguration setMinLargeMessageSize(final int minLargeMessageSize) { this.minLargeMessageSize = minLargeMessageSize; return this; } @@ -258,8 +227,7 @@ public final class ClusterConnectionConfiguration implements Serializable /** * @param clientFailureCheckPeriod the clientFailureCheckPeriod to set */ - public ClusterConnectionConfiguration setClientFailureCheckPeriod(long clientFailureCheckPeriod) - { + public ClusterConnectionConfiguration setClientFailureCheckPeriod(long clientFailureCheckPeriod) { this.clientFailureCheckPeriod = clientFailureCheckPeriod; return this; } @@ -267,8 +235,7 @@ public final class ClusterConnectionConfiguration implements Serializable /** * @param connectionTTL the connectionTTL to set */ - public ClusterConnectionConfiguration setConnectionTTL(long connectionTTL) - { + public ClusterConnectionConfiguration setConnectionTTL(long connectionTTL) { this.connectionTTL = connectionTTL; return this; } @@ -276,8 +243,7 @@ public final class ClusterConnectionConfiguration implements Serializable /** * @param retryInterval the retryInterval to set */ - public ClusterConnectionConfiguration setRetryInterval(long retryInterval) - { + public ClusterConnectionConfiguration setRetryInterval(long retryInterval) { this.retryInterval = retryInterval; return this; } @@ -285,8 +251,7 @@ public final class ClusterConnectionConfiguration implements Serializable /** * @param retryIntervalMultiplier the retryIntervalMultiplier to set */ - public ClusterConnectionConfiguration setRetryIntervalMultiplier(double retryIntervalMultiplier) - { + public ClusterConnectionConfiguration setRetryIntervalMultiplier(double retryIntervalMultiplier) { this.retryIntervalMultiplier = retryIntervalMultiplier; return this; } @@ -294,8 +259,7 @@ public final class ClusterConnectionConfiguration implements Serializable /** * @param maxRetryInterval the maxRetryInterval to set */ - public ClusterConnectionConfiguration setMaxRetryInterval(long maxRetryInterval) - { + public ClusterConnectionConfiguration setMaxRetryInterval(long maxRetryInterval) { this.maxRetryInterval = maxRetryInterval; return this; } @@ -303,8 +267,7 @@ public final class ClusterConnectionConfiguration implements Serializable /** * @param initialConnectAttempts the reconnectAttempts to set */ - public ClusterConnectionConfiguration setInitialConnectAttempts(int initialConnectAttempts) - { + public ClusterConnectionConfiguration setInitialConnectAttempts(int initialConnectAttempts) { this.initialConnectAttempts = initialConnectAttempts; return this; } @@ -312,8 +275,7 @@ public final class ClusterConnectionConfiguration implements Serializable /** * @param reconnectAttempts the reconnectAttempts to set */ - public ClusterConnectionConfiguration setReconnectAttempts(int reconnectAttempts) - { + public ClusterConnectionConfiguration setReconnectAttempts(int reconnectAttempts) { this.reconnectAttempts = reconnectAttempts; return this; } @@ -321,8 +283,7 @@ public final class ClusterConnectionConfiguration implements Serializable /** * @param callTimeout the callTimeout to set */ - public ClusterConnectionConfiguration setCallTimeout(long callTimeout) - { + public ClusterConnectionConfiguration setCallTimeout(long callTimeout) { this.callTimeout = callTimeout; return this; } @@ -330,8 +291,7 @@ public final class ClusterConnectionConfiguration implements Serializable /** * @param callFailoverTimeout the callTimeout to set */ - public ClusterConnectionConfiguration setCallFailoverTimeout(long callFailoverTimeout) - { + public ClusterConnectionConfiguration setCallFailoverTimeout(long callFailoverTimeout) { this.callFailoverTimeout = callFailoverTimeout; return this; } @@ -339,8 +299,7 @@ public final class ClusterConnectionConfiguration implements Serializable /** * @param duplicateDetection the duplicateDetection to set */ - public ClusterConnectionConfiguration setDuplicateDetection(boolean duplicateDetection) - { + public ClusterConnectionConfiguration setDuplicateDetection(boolean duplicateDetection) { this.duplicateDetection = duplicateDetection; return this; } @@ -349,8 +308,7 @@ public final class ClusterConnectionConfiguration implements Serializable * @param messageLoadBalancingType * @return */ - public ClusterConnectionConfiguration setMessageLoadBalancingType(MessageLoadBalancingType messageLoadBalancingType) - { + public ClusterConnectionConfiguration setMessageLoadBalancingType(MessageLoadBalancingType messageLoadBalancingType) { this.messageLoadBalancingType = messageLoadBalancingType; return this; } @@ -358,72 +316,65 @@ public final class ClusterConnectionConfiguration implements Serializable /* * returns the cluster update interval * */ - public long getClusterNotificationInterval() - { + public long getClusterNotificationInterval() { return clusterNotificationInterval; } - public ClusterConnectionConfiguration setClusterNotificationInterval(long clusterNotificationInterval) - { + public ClusterConnectionConfiguration setClusterNotificationInterval(long clusterNotificationInterval) { this.clusterNotificationInterval = clusterNotificationInterval; return this; } - public int getClusterNotificationAttempts() - { + public int getClusterNotificationAttempts() { return clusterNotificationAttempts; } - public ClusterConnectionConfiguration setClusterNotificationAttempts(int clusterNotificationAttempts) - { + public ClusterConnectionConfiguration setClusterNotificationAttempts(int clusterNotificationAttempts) { this.clusterNotificationAttempts = clusterNotificationAttempts; return this; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((address == null) ? 0 : address.hashCode()); result = prime * result + (allowDirectConnectionsOnly ? 1231 : 1237); - result = prime * result + (int)(callFailoverTimeout ^ (callFailoverTimeout >>> 32)); - result = prime * result + (int)(callTimeout ^ (callTimeout >>> 32)); - result = prime * result + (int)(clientFailureCheckPeriod ^ (clientFailureCheckPeriod >>> 32)); + result = prime * result + (int) (callFailoverTimeout ^ (callFailoverTimeout >>> 32)); + result = prime * result + (int) (callTimeout ^ (callTimeout >>> 32)); + result = prime * result + (int) (clientFailureCheckPeriod ^ (clientFailureCheckPeriod >>> 32)); result = prime * result + clusterNotificationAttempts; - result = prime * result + (int)(clusterNotificationInterval ^ (clusterNotificationInterval >>> 32)); + result = prime * result + (int) (clusterNotificationInterval ^ (clusterNotificationInterval >>> 32)); result = prime * result + confirmationWindowSize; - result = prime * result + (int)(connectionTTL ^ (connectionTTL >>> 32)); + result = prime * result + (int) (connectionTTL ^ (connectionTTL >>> 32)); result = prime * result + ((connectorName == null) ? 0 : connectorName.hashCode()); result = prime * result + ((discoveryGroupName == null) ? 0 : discoveryGroupName.hashCode()); result = prime * result + (duplicateDetection ? 1231 : 1237); result = prime * result + (messageLoadBalancingType == null ? 0 : messageLoadBalancingType.hashCode()); result = prime * result + maxHops; - result = prime * result + (int)(maxRetryInterval ^ (maxRetryInterval >>> 32)); + result = prime * result + (int) (maxRetryInterval ^ (maxRetryInterval >>> 32)); result = prime * result + minLargeMessageSize; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + initialConnectAttempts; result = prime * result + reconnectAttempts; - result = prime * result + (int)(retryInterval ^ (retryInterval >>> 32)); + result = prime * result + (int) (retryInterval ^ (retryInterval >>> 32)); long temp; temp = Double.doubleToLongBits(retryIntervalMultiplier); - result = prime * result + (int)(temp ^ (temp >>> 32)); + result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + ((staticConnectors == null) ? 0 : staticConnectors.hashCode()); return result; } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; - ClusterConnectionConfiguration other = (ClusterConnectionConfiguration)obj; - if (address == null) - { + ClusterConnectionConfiguration other = (ClusterConnectionConfiguration) obj; + if (address == null) { if (other.address != null) return false; } @@ -445,15 +396,13 @@ public final class ClusterConnectionConfiguration implements Serializable return false; if (connectionTTL != other.connectionTTL) return false; - if (connectorName == null) - { + if (connectorName == null) { if (other.connectorName != null) return false; } else if (!connectorName.equals(other.connectorName)) return false; - if (discoveryGroupName == null) - { + if (discoveryGroupName == null) { if (other.discoveryGroupName != null) return false; } @@ -469,8 +418,7 @@ public final class ClusterConnectionConfiguration implements Serializable return false; if (minLargeMessageSize != other.minLargeMessageSize) return false; - if (name == null) - { + if (name == null) { if (other.name != null) return false; } @@ -484,8 +432,7 @@ public final class ClusterConnectionConfiguration implements Serializable return false; if (Double.doubleToLongBits(retryIntervalMultiplier) != Double.doubleToLongBits(other.retryIntervalMultiplier)) return false; - if (staticConnectors == null) - { + if (staticConnectors == null) { if (other.staticConnectors != null) return false; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/Configuration.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/Configuration.java index 1a99aee961..ed9edb14a7 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/Configuration.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/Configuration.java @@ -34,8 +34,8 @@ import org.apache.activemq.artemis.core.settings.impl.ResourceLimitSettings; /** * A Configuration is used to configure ActiveMQ Artemis servers. */ -public interface Configuration -{ +public interface Configuration { + /** * To be used on dependency management on the application server */ @@ -295,7 +295,8 @@ public interface Configuration */ Configuration setDiscoveryGroupConfigurations(Map configs); - Configuration addDiscoveryGroupConfiguration(final String key, DiscoveryGroupConfiguration discoveryGroupConfiguration); + Configuration addDiscoveryGroupConfiguration(final String key, + DiscoveryGroupConfiguration discoveryGroupConfiguration); /** * Returns the grouping handler configured for this server. @@ -467,6 +468,7 @@ public interface Configuration /** * The location of the journal related to artemis.instance. + * * @return */ File getJournalLocation(); @@ -687,7 +689,6 @@ public interface Configuration */ Configuration setPagingDirectory(String dir); - /** * The paging location related to artemis.instance */ @@ -701,7 +702,9 @@ public interface Configuration */ String getLargeMessagesDirectory(); - /** The large message location related to artemis.instance */ + /** + * The large message location related to artemis.instance + */ File getLargeMessagesLocation(); /** diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ConfigurationUtils.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ConfigurationUtils.java index c83ca9f0d3..e2a0a44a62 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ConfigurationUtils.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ConfigurationUtils.java @@ -35,125 +35,94 @@ import org.apache.activemq.artemis.core.server.cluster.ha.ScaleDownPolicy; import org.apache.activemq.artemis.core.server.cluster.ha.SharedStoreMasterPolicy; import org.apache.activemq.artemis.core.server.cluster.ha.SharedStoreSlavePolicy; -public final class ConfigurationUtils -{ +public final class ConfigurationUtils { - private ConfigurationUtils() - { + private ConfigurationUtils() { // Utility class } - public static ClusterConnectionConfiguration getReplicationClusterConfiguration(Configuration conf, String replicationCluster) throws ActiveMQIllegalStateException - { + public static ClusterConnectionConfiguration getReplicationClusterConfiguration(Configuration conf, + String replicationCluster) throws ActiveMQIllegalStateException { if (replicationCluster == null || replicationCluster.isEmpty()) return conf.getClusterConfigurations().get(0); - for (ClusterConnectionConfiguration clusterConf : conf.getClusterConfigurations()) - { + for (ClusterConnectionConfiguration clusterConf : conf.getClusterConfigurations()) { if (replicationCluster.equals(clusterConf.getName())) return clusterConf; } throw new ActiveMQIllegalStateException("Missing cluster-configuration for replication-clustername '" + replicationCluster + "'."); } - public static HAPolicy getHAPolicy(HAPolicyConfiguration conf) throws ActiveMQIllegalStateException - { - if (conf == null) - { + public static HAPolicy getHAPolicy(HAPolicyConfiguration conf) throws ActiveMQIllegalStateException { + if (conf == null) { return new LiveOnlyPolicy(); } - switch (conf.getType()) - { - case LIVE_ONLY: - { + switch (conf.getType()) { + case LIVE_ONLY: { LiveOnlyPolicyConfiguration pc = (LiveOnlyPolicyConfiguration) conf; return new LiveOnlyPolicy(getScaleDownPolicy(pc.getScaleDownConfiguration())); } - case REPLICATED: - { + case REPLICATED: { ReplicatedPolicyConfiguration pc = (ReplicatedPolicyConfiguration) conf; return new ReplicatedPolicy(pc.isCheckForLiveServer(), pc.getGroupName(), pc.getClusterName()); } - case REPLICA: - { + case REPLICA: { ReplicaPolicyConfiguration pc = (ReplicaPolicyConfiguration) conf; return new ReplicaPolicy(pc.getClusterName(), pc.getMaxSavedReplicatedJournalsSize(), pc.getGroupName(), pc.isRestartBackup(), pc.isAllowFailBack(), pc.getFailbackDelay(), getScaleDownPolicy(pc.getScaleDownConfiguration())); } - case SHARED_STORE_MASTER: - { + case SHARED_STORE_MASTER: { SharedStoreMasterPolicyConfiguration pc = (SharedStoreMasterPolicyConfiguration) conf; return new SharedStoreMasterPolicy(pc.getFailbackDelay(), pc.isFailoverOnServerShutdown()); } - case SHARED_STORE_SLAVE: - { + case SHARED_STORE_SLAVE: { SharedStoreSlavePolicyConfiguration pc = (SharedStoreSlavePolicyConfiguration) conf; return new SharedStoreSlavePolicy(pc.getFailbackDelay(), pc.isFailoverOnServerShutdown(), pc.isRestartBackup(), pc.isAllowFailBack(), getScaleDownPolicy(pc.getScaleDownConfiguration())); } - case COLOCATED: - { + case COLOCATED: { ColocatedPolicyConfiguration pc = (ColocatedPolicyConfiguration) conf; HAPolicyConfiguration backupConf = pc.getBackupConfig(); BackupPolicy backupPolicy; - if (backupConf == null) - { + if (backupConf == null) { backupPolicy = new ReplicaPolicy(); } - else - { + else { backupPolicy = (BackupPolicy) getHAPolicy(backupConf); } HAPolicyConfiguration liveConf = pc.getLiveConfig(); HAPolicy livePolicy; - if (liveConf == null) - { + if (liveConf == null) { livePolicy = new ReplicatedPolicy(); } - else - { + else { livePolicy = getHAPolicy(liveConf); } - return new ColocatedPolicy(pc.isRequestBackup(), - pc.getBackupRequestRetries(), - pc.getBackupRequestRetryInterval(), - pc.getMaxBackups(), - pc.getBackupPortOffset(), - pc.getExcludedConnectors(), - livePolicy, - backupPolicy); + return new ColocatedPolicy(pc.isRequestBackup(), pc.getBackupRequestRetries(), pc.getBackupRequestRetryInterval(), pc.getMaxBackups(), pc.getBackupPortOffset(), pc.getExcludedConnectors(), livePolicy, backupPolicy); } } throw ActiveMQMessageBundle.BUNDLE.unsupportedHAPolicyConfiguration(conf); } - public static ScaleDownPolicy getScaleDownPolicy(ScaleDownConfiguration scaleDownConfiguration) - { - if (scaleDownConfiguration != null) - { - if (scaleDownConfiguration.getDiscoveryGroup() != null) - { - return new ScaleDownPolicy(scaleDownConfiguration.getDiscoveryGroup(), scaleDownConfiguration.getGroupName(), - scaleDownConfiguration.getClusterName(), scaleDownConfiguration.isEnabled()); + public static ScaleDownPolicy getScaleDownPolicy(ScaleDownConfiguration scaleDownConfiguration) { + if (scaleDownConfiguration != null) { + if (scaleDownConfiguration.getDiscoveryGroup() != null) { + return new ScaleDownPolicy(scaleDownConfiguration.getDiscoveryGroup(), scaleDownConfiguration.getGroupName(), scaleDownConfiguration.getClusterName(), scaleDownConfiguration.isEnabled()); } - else - { - return new ScaleDownPolicy(scaleDownConfiguration.getConnectors(), scaleDownConfiguration.getGroupName(), - scaleDownConfiguration.getClusterName(), scaleDownConfiguration.isEnabled()); + else { + return new ScaleDownPolicy(scaleDownConfiguration.getConnectors(), scaleDownConfiguration.getGroupName(), scaleDownConfiguration.getClusterName(), scaleDownConfiguration.isEnabled()); } } return null; } // A method to check the passed Configuration object and warn users if semantically unwise parameters are present - public static void validateConfiguration(Configuration configuration) - { + public static void validateConfiguration(Configuration configuration) { // Warn if connection-ttl-override/connection-ttl == check-period compareTTLWithCheckPeriod(configuration); } - private static void compareTTLWithCheckPeriod(Configuration configuration) - { + private static void compareTTLWithCheckPeriod(Configuration configuration) { for (ClusterConnectionConfiguration c : configuration.getClusterConfigurations()) compareTTLWithCheckPeriod(c.getName(), c.getConnectionTTL(), configuration.getConnectionTTLOverride(), c.getClientFailureCheckPeriod()); @@ -161,8 +130,10 @@ public final class ConfigurationUtils compareTTLWithCheckPeriod(c.getName(), c.getConnectionTTL(), configuration.getConnectionTTLOverride(), c.getClientFailureCheckPeriod()); } - private static void compareTTLWithCheckPeriod(String name, long connectionTTL, long connectionTTLOverride, long checkPeriod) - { + private static void compareTTLWithCheckPeriod(String name, + long connectionTTL, + long connectionTTLOverride, + long checkPeriod) { if (connectionTTLOverride == checkPeriod) ActiveMQServerLogger.LOGGER.connectionTTLEqualsCheckPeriod(name, "connection-ttl-override", "check-period"); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ConnectorServiceConfiguration.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ConnectorServiceConfiguration.java index b7a9678d1e..a8b0d7c6ec 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ConnectorServiceConfiguration.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ConnectorServiceConfiguration.java @@ -19,8 +19,8 @@ package org.apache.activemq.artemis.core.config; import java.io.Serializable; import java.util.Map; -public class ConnectorServiceConfiguration implements Serializable -{ +public class ConnectorServiceConfiguration implements Serializable { + private static final long serialVersionUID = -641207073030767325L; private String name; @@ -29,51 +29,42 @@ public class ConnectorServiceConfiguration implements Serializable private Map params; - public ConnectorServiceConfiguration() - { + public ConnectorServiceConfiguration() { } - public String getConnectorName() - { + public String getConnectorName() { return name; } - public String getFactoryClassName() - { + public String getFactoryClassName() { return factoryClassName; } - public Map getParams() - { + public Map getParams() { return params; } - public String getName() - { + public String getName() { return name; } - public ConnectorServiceConfiguration setName(String name) - { + public ConnectorServiceConfiguration setName(String name) { this.name = name; return this; } - public ConnectorServiceConfiguration setFactoryClassName(String factoryClassName) - { + public ConnectorServiceConfiguration setFactoryClassName(String factoryClassName) { this.factoryClassName = factoryClassName; return this; } - public ConnectorServiceConfiguration setParams(Map params) - { + public ConnectorServiceConfiguration setParams(Map params) { this.params = params; return this; } @Override - public boolean equals(Object o) - { + public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) @@ -92,8 +83,7 @@ public class ConnectorServiceConfiguration implements Serializable } @Override - public int hashCode() - { + public int hashCode() { int result = getConnectorName() != null ? getConnectorName().hashCode() : 0; result = 31 * result + (getFactoryClassName() != null ? getFactoryClassName().hashCode() : 0); result = 31 * result + (getParams() != null ? getParams().hashCode() : 0); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/CoreQueueConfiguration.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/CoreQueueConfiguration.java index 78ca8dc186..daaca811e4 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/CoreQueueConfiguration.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/CoreQueueConfiguration.java @@ -18,8 +18,8 @@ package org.apache.activemq.artemis.core.config; import java.io.Serializable; -public class CoreQueueConfiguration implements Serializable -{ +public class CoreQueueConfiguration implements Serializable { + private static final long serialVersionUID = 650404974977490254L; private String address = null; @@ -30,35 +30,29 @@ public class CoreQueueConfiguration implements Serializable private boolean durable = true; - public CoreQueueConfiguration() - { + public CoreQueueConfiguration() { } - public String getAddress() - { + public String getAddress() { return address; } - public String getName() - { + public String getName() { return name; } - public String getFilterString() - { + public String getFilterString() { return filterString; } - public boolean isDurable() - { + public boolean isDurable() { return durable; } /** * @param address the address to set */ - public CoreQueueConfiguration setAddress(final String address) - { + public CoreQueueConfiguration setAddress(final String address) { this.address = address; return this; } @@ -66,8 +60,7 @@ public class CoreQueueConfiguration implements Serializable /** * @param name the name to set */ - public CoreQueueConfiguration setName(final String name) - { + public CoreQueueConfiguration setName(final String name) { this.name = name; return this; } @@ -75,8 +68,7 @@ public class CoreQueueConfiguration implements Serializable /** * @param filterString the filterString to set */ - public CoreQueueConfiguration setFilterString(final String filterString) - { + public CoreQueueConfiguration setFilterString(final String filterString) { this.filterString = filterString; return this; } @@ -84,15 +76,13 @@ public class CoreQueueConfiguration implements Serializable /** * @param durable the durable to set; default value is true */ - public CoreQueueConfiguration setDurable(final boolean durable) - { + public CoreQueueConfiguration setDurable(final boolean durable) { this.durable = durable; return this; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((address == null) ? 0 : address.hashCode()); @@ -103,17 +93,15 @@ public class CoreQueueConfiguration implements Serializable } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; - CoreQueueConfiguration other = (CoreQueueConfiguration)obj; - if (address == null) - { + CoreQueueConfiguration other = (CoreQueueConfiguration) obj; + if (address == null) { if (other.address != null) return false; } @@ -121,15 +109,13 @@ public class CoreQueueConfiguration implements Serializable return false; if (durable != other.durable) return false; - if (filterString == null) - { + if (filterString == null) { if (other.filterString != null) return false; } else if (!filterString.equals(other.filterString)) return false; - if (name == null) - { + if (name == null) { if (other.name != null) return false; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/DivertConfiguration.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/DivertConfiguration.java index 4f35477330..e8d77a3344 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/DivertConfiguration.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/DivertConfiguration.java @@ -21,8 +21,8 @@ import java.io.Serializable; import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration; import org.apache.activemq.artemis.utils.UUIDGenerator; -public class DivertConfiguration implements Serializable -{ +public class DivertConfiguration implements Serializable { + private static final long serialVersionUID = 6910543740464269629L; private String name = null; @@ -39,50 +39,41 @@ public class DivertConfiguration implements Serializable private String transformerClassName = null; - public DivertConfiguration() - { + public DivertConfiguration() { } - public String getName() - { + public String getName() { return name; } - public String getRoutingName() - { + public String getRoutingName() { return routingName; } - public String getAddress() - { + public String getAddress() { return address; } - public String getForwardingAddress() - { + public String getForwardingAddress() { return forwardingAddress; } - public boolean isExclusive() - { + public boolean isExclusive() { return exclusive; } - public String getFilterString() - { + public String getFilterString() { return filterString; } - public String getTransformerClassName() - { + public String getTransformerClassName() { return transformerClassName; } /** * @param name the name to set */ - public DivertConfiguration setName(final String name) - { + public DivertConfiguration setName(final String name) { this.name = name; return this; } @@ -90,14 +81,11 @@ public class DivertConfiguration implements Serializable /** * @param routingName the routingName to set */ - public DivertConfiguration setRoutingName(final String routingName) - { - if (routingName == null) - { + public DivertConfiguration setRoutingName(final String routingName) { + if (routingName == null) { this.routingName = UUIDGenerator.getInstance().generateStringUUID(); } - else - { + else { this.routingName = routingName; } return this; @@ -106,8 +94,7 @@ public class DivertConfiguration implements Serializable /** * @param address the address to set */ - public DivertConfiguration setAddress(final String address) - { + public DivertConfiguration setAddress(final String address) { this.address = address; return this; } @@ -115,8 +102,7 @@ public class DivertConfiguration implements Serializable /** * @param forwardingAddress the forwardingAddress to set */ - public DivertConfiguration setForwardingAddress(final String forwardingAddress) - { + public DivertConfiguration setForwardingAddress(final String forwardingAddress) { this.forwardingAddress = forwardingAddress; return this; } @@ -124,8 +110,7 @@ public class DivertConfiguration implements Serializable /** * @param exclusive the exclusive to set */ - public DivertConfiguration setExclusive(final boolean exclusive) - { + public DivertConfiguration setExclusive(final boolean exclusive) { this.exclusive = exclusive; return this; } @@ -133,8 +118,7 @@ public class DivertConfiguration implements Serializable /** * @param filterString the filterString to set */ - public DivertConfiguration setFilterString(final String filterString) - { + public DivertConfiguration setFilterString(final String filterString) { this.filterString = filterString; return this; } @@ -142,15 +126,13 @@ public class DivertConfiguration implements Serializable /** * @param transformerClassName the transformerClassName to set */ - public DivertConfiguration setTransformerClassName(final String transformerClassName) - { + public DivertConfiguration setTransformerClassName(final String transformerClassName) { this.transformerClassName = transformerClassName; return this; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((address == null) ? 0 : address.hashCode()); @@ -164,17 +146,15 @@ public class DivertConfiguration implements Serializable } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; - DivertConfiguration other = (DivertConfiguration)obj; - if (address == null) - { + DivertConfiguration other = (DivertConfiguration) obj; + if (address == null) { if (other.address != null) return false; } @@ -182,36 +162,31 @@ public class DivertConfiguration implements Serializable return false; if (exclusive != other.exclusive) return false; - if (filterString == null) - { + if (filterString == null) { if (other.filterString != null) return false; } else if (!filterString.equals(other.filterString)) return false; - if (forwardingAddress == null) - { + if (forwardingAddress == null) { if (other.forwardingAddress != null) return false; } else if (!forwardingAddress.equals(other.forwardingAddress)) return false; - if (name == null) - { + if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; - if (routingName == null) - { + if (routingName == null) { if (other.routingName != null) return false; } else if (!routingName.equals(other.routingName)) return false; - if (transformerClassName == null) - { + if (transformerClassName == null) { if (other.transformerClassName != null) return false; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/FileDeploymentManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/FileDeploymentManager.java index 3e2c3f6ec6..abf0170ed1 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/FileDeploymentManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/FileDeploymentManager.java @@ -35,41 +35,36 @@ import org.w3c.dom.NodeList; /** * ised to build a set of ActiveMQComponents from a set of Deployables pulled out of the configuration file */ -public class FileDeploymentManager -{ +public class FileDeploymentManager { + private static final String DEFAULT_CONFIGURATION_URL = "broker.xml"; private final String configurationUrl; LinkedHashMap deployables = new LinkedHashMap<>(); - public FileDeploymentManager() - { + public FileDeploymentManager() { this.configurationUrl = DEFAULT_CONFIGURATION_URL; } - public FileDeploymentManager(String configurationUrl) - { + public FileDeploymentManager(String configurationUrl) { this.configurationUrl = configurationUrl; } /* * parse a set of configuration with the Deployables that were given. */ - public void readConfiguration() throws Exception - { + public void readConfiguration() throws Exception { URL url; url = Thread.currentThread().getContextClassLoader().getResource(configurationUrl); - if (url == null) - { + if (url == null) { // trying a different classloader now url = getClass().getClassLoader().getResource(configurationUrl); } - if (url == null) - { + if (url == null) { // The URL is outside of the classloader. Trying a pure url now url = new URL(configurationUrl); } @@ -81,13 +76,11 @@ public class FileDeploymentManager Element e = XMLUtil.stringToElement(xml); //iterate around all the deployables - for (Deployable deployable : deployables.values()) - { + for (Deployable deployable : deployables.values()) { String root = deployable.getRootElement(); NodeList children = e.getElementsByTagName(root); //if the root element exists then parse it - if (root != null && children.getLength() > 0) - { + if (root != null && children.getLength() > 0) { Node item = children.item(0); XMLUtil.validate(item, deployable.getSchema()); deployable.parse((Element) item); @@ -98,14 +91,12 @@ public class FileDeploymentManager /* * Build a set of ActiveMQComponents from the Deployables configured */ - public Map buildService(ActiveMQSecurityManager securityManager, MBeanServer mBeanServer) throws Exception - { + public Map buildService(ActiveMQSecurityManager securityManager, + MBeanServer mBeanServer) throws Exception { Map components = new HashMap<>(); - for (Deployable deployable : deployables.values()) - { + for (Deployable deployable : deployables.values()) { // if the deployable was parsed then build the service - if (deployable.isParsed()) - { + if (deployable.isParsed()) { deployable.buildService(securityManager, mBeanServer, deployables, components); } } @@ -115,8 +106,7 @@ public class FileDeploymentManager /* * add a Deployable to be configured */ - public FileDeploymentManager addDeployable(Deployable deployable) - { + public FileDeploymentManager addDeployable(Deployable deployable) { deployables.put(deployable.getRootElement(), deployable); return this; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/HAPolicyConfiguration.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/HAPolicyConfiguration.java index 97060a6201..c1510d1b54 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/HAPolicyConfiguration.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/HAPolicyConfiguration.java @@ -18,10 +18,9 @@ package org.apache.activemq.artemis.core.config; import java.io.Serializable; -public interface HAPolicyConfiguration extends Serializable -{ - public enum TYPE - { +public interface HAPolicyConfiguration extends Serializable { + + public enum TYPE { LIVE_ONLY, REPLICATED, REPLICA, diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ScaleDownConfiguration.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ScaleDownConfiguration.java index 30570e421d..25721cad5c 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ScaleDownConfiguration.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ScaleDownConfiguration.java @@ -22,8 +22,8 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.List; -public class ScaleDownConfiguration implements Serializable -{ +public class ScaleDownConfiguration implements Serializable { + private List connectors = new ArrayList<>(); private String discoveryGroup = null; @@ -34,63 +34,52 @@ public class ScaleDownConfiguration implements Serializable private boolean enabled = ActiveMQDefaultConfiguration.isDefaultScaleDownEnabled(); - public List getConnectors() - { + public List getConnectors() { return connectors; } - public ScaleDownConfiguration setConnectors(List connectors) - { + public ScaleDownConfiguration setConnectors(List connectors) { this.connectors = connectors; return this; } - public ScaleDownConfiguration addConnector(String connector) - { + public ScaleDownConfiguration addConnector(String connector) { connectors.add(connector); return this; } - public String getDiscoveryGroup() - { + public String getDiscoveryGroup() { return discoveryGroup; } - public ScaleDownConfiguration setDiscoveryGroup(String discoveryGroup) - { + public ScaleDownConfiguration setDiscoveryGroup(String discoveryGroup) { this.discoveryGroup = discoveryGroup; return this; } - public String getGroupName() - { + public String getGroupName() { return groupName; } - public ScaleDownConfiguration setGroupName(String groupName) - { + public ScaleDownConfiguration setGroupName(String groupName) { this.groupName = groupName; return this; } - public String getClusterName() - { + public String getClusterName() { return clusterName; } - public ScaleDownConfiguration setClusterName(String clusterName) - { + public ScaleDownConfiguration setClusterName(String clusterName) { this.clusterName = clusterName; return this; } - public boolean isEnabled() - { + public boolean isEnabled() { return enabled; } - public ScaleDownConfiguration setEnabled(boolean enabled) - { + public ScaleDownConfiguration setEnabled(boolean enabled) { this.enabled = enabled; return this; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ha/ColocatedPolicyConfiguration.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ha/ColocatedPolicyConfiguration.java index d9b8f95390..1c5a903541 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ha/ColocatedPolicyConfiguration.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ha/ColocatedPolicyConfiguration.java @@ -22,8 +22,8 @@ import org.apache.activemq.artemis.core.config.HAPolicyConfiguration; import java.util.ArrayList; import java.util.List; -public class ColocatedPolicyConfiguration implements HAPolicyConfiguration -{ +public class ColocatedPolicyConfiguration implements HAPolicyConfiguration { + private boolean requestBackup = ActiveMQDefaultConfiguration.isDefaultHapolicyRequestBackup(); private int backupRequestRetries = ActiveMQDefaultConfiguration.getDefaultHapolicyBackupRequestRetries(); @@ -42,111 +42,91 @@ public class ColocatedPolicyConfiguration implements HAPolicyConfiguration private HAPolicyConfiguration backupConfig; - public ColocatedPolicyConfiguration() - { + public ColocatedPolicyConfiguration() { } @Override - public TYPE getType() - { + public TYPE getType() { return TYPE.COLOCATED; } - public boolean isRequestBackup() - { + public boolean isRequestBackup() { return requestBackup; } - public ColocatedPolicyConfiguration setRequestBackup(boolean requestBackup) - { + public ColocatedPolicyConfiguration setRequestBackup(boolean requestBackup) { this.requestBackup = requestBackup; return this; } - public int getBackupRequestRetries() - { + public int getBackupRequestRetries() { return backupRequestRetries; } - public ColocatedPolicyConfiguration setBackupRequestRetries(int backupRequestRetries) - { + public ColocatedPolicyConfiguration setBackupRequestRetries(int backupRequestRetries) { this.backupRequestRetries = backupRequestRetries; return this; } - public long getBackupRequestRetryInterval() - { + public long getBackupRequestRetryInterval() { return backupRequestRetryInterval; } - public ColocatedPolicyConfiguration setBackupRequestRetryInterval(long backupRequestRetryInterval) - { + public ColocatedPolicyConfiguration setBackupRequestRetryInterval(long backupRequestRetryInterval) { this.backupRequestRetryInterval = backupRequestRetryInterval; return this; } - public int getMaxBackups() - { + public int getMaxBackups() { return maxBackups; } - public ColocatedPolicyConfiguration setMaxBackups(int maxBackups) - { + public ColocatedPolicyConfiguration setMaxBackups(int maxBackups) { this.maxBackups = maxBackups; return this; } - public int getBackupPortOffset() - { + public int getBackupPortOffset() { return backupPortOffset; } - public ColocatedPolicyConfiguration setBackupPortOffset(int backupPortOffset) - { + public ColocatedPolicyConfiguration setBackupPortOffset(int backupPortOffset) { this.backupPortOffset = backupPortOffset; return this; } - public List getExcludedConnectors() - { + public List getExcludedConnectors() { return excludedConnectors; } - public ColocatedPolicyConfiguration setExcludedConnectors(List excludedConnectors) - { + public ColocatedPolicyConfiguration setExcludedConnectors(List excludedConnectors) { this.excludedConnectors = excludedConnectors; return this; } - public int getPortOffset() - { + public int getPortOffset() { return portOffset; } - public ColocatedPolicyConfiguration setPortOffset(int portOffset) - { + public ColocatedPolicyConfiguration setPortOffset(int portOffset) { this.portOffset = portOffset; return this; } - public HAPolicyConfiguration getLiveConfig() - { + public HAPolicyConfiguration getLiveConfig() { return liveConfig; } - public ColocatedPolicyConfiguration setLiveConfig(HAPolicyConfiguration liveConfig) - { + public ColocatedPolicyConfiguration setLiveConfig(HAPolicyConfiguration liveConfig) { this.liveConfig = liveConfig; return this; } - public HAPolicyConfiguration getBackupConfig() - { + public HAPolicyConfiguration getBackupConfig() { return backupConfig; } - public ColocatedPolicyConfiguration setBackupConfig(HAPolicyConfiguration backupConfig) - { + public ColocatedPolicyConfiguration setBackupConfig(HAPolicyConfiguration backupConfig) { this.backupConfig = backupConfig; return this; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ha/LiveOnlyPolicyConfiguration.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ha/LiveOnlyPolicyConfiguration.java index b1c33f8edf..858567bc9d 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ha/LiveOnlyPolicyConfiguration.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ha/LiveOnlyPolicyConfiguration.java @@ -19,30 +19,25 @@ package org.apache.activemq.artemis.core.config.ha; import org.apache.activemq.artemis.core.config.HAPolicyConfiguration; import org.apache.activemq.artemis.core.config.ScaleDownConfiguration; -public class LiveOnlyPolicyConfiguration implements HAPolicyConfiguration -{ - public LiveOnlyPolicyConfiguration() - { +public class LiveOnlyPolicyConfiguration implements HAPolicyConfiguration { + + public LiveOnlyPolicyConfiguration() { } - public LiveOnlyPolicyConfiguration(ScaleDownConfiguration scaleDownConfiguration) - { + public LiveOnlyPolicyConfiguration(ScaleDownConfiguration scaleDownConfiguration) { this.scaleDownConfiguration = scaleDownConfiguration; } @Override - public TYPE getType() - { + public TYPE getType() { return TYPE.LIVE_ONLY; } - public ScaleDownConfiguration getScaleDownConfiguration() - { + public ScaleDownConfiguration getScaleDownConfiguration() { return scaleDownConfiguration; } - public void setScaleDownConfiguration(ScaleDownConfiguration scaleDownConfiguration) - { + public void setScaleDownConfiguration(ScaleDownConfiguration scaleDownConfiguration) { this.scaleDownConfiguration = scaleDownConfiguration; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ha/ReplicaPolicyConfiguration.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ha/ReplicaPolicyConfiguration.java index 1f5c7b1112..9663d24458 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ha/ReplicaPolicyConfiguration.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ha/ReplicaPolicyConfiguration.java @@ -20,8 +20,8 @@ import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration; import org.apache.activemq.artemis.core.config.HAPolicyConfiguration; import org.apache.activemq.artemis.core.config.ScaleDownConfiguration; -public class ReplicaPolicyConfiguration implements HAPolicyConfiguration -{ +public class ReplicaPolicyConfiguration implements HAPolicyConfiguration { + private String clusterName = null; private int maxSavedReplicatedJournalsSize = ActiveMQDefaultConfiguration.getDefaultMaxSavedReplicatedJournalsSize(); @@ -39,90 +39,74 @@ public class ReplicaPolicyConfiguration implements HAPolicyConfiguration private long failbackDelay = ActiveMQDefaultConfiguration.getDefaultFailbackDelay(); - public ReplicaPolicyConfiguration() - { + public ReplicaPolicyConfiguration() { } @Override - public TYPE getType() - { + public TYPE getType() { return TYPE.REPLICA; } - public ScaleDownConfiguration getScaleDownConfiguration() - { + public ScaleDownConfiguration getScaleDownConfiguration() { return scaleDownConfiguration; } - public ReplicaPolicyConfiguration setScaleDownConfiguration(ScaleDownConfiguration scaleDownConfiguration) - { + public ReplicaPolicyConfiguration setScaleDownConfiguration(ScaleDownConfiguration scaleDownConfiguration) { this.scaleDownConfiguration = scaleDownConfiguration; return this; } - public String getClusterName() - { + public String getClusterName() { return clusterName; } - public ReplicaPolicyConfiguration setClusterName(String clusterName) - { + public ReplicaPolicyConfiguration setClusterName(String clusterName) { this.clusterName = clusterName; return this; } - public int getMaxSavedReplicatedJournalsSize() - { + public int getMaxSavedReplicatedJournalsSize() { return maxSavedReplicatedJournalsSize; } - public ReplicaPolicyConfiguration setMaxSavedReplicatedJournalsSize(int maxSavedReplicatedJournalsSize) - { + public ReplicaPolicyConfiguration setMaxSavedReplicatedJournalsSize(int maxSavedReplicatedJournalsSize) { this.maxSavedReplicatedJournalsSize = maxSavedReplicatedJournalsSize; return this; } - public String getGroupName() - { + public String getGroupName() { return groupName; } - public ReplicaPolicyConfiguration setGroupName(String groupName) - { + public ReplicaPolicyConfiguration setGroupName(String groupName) { this.groupName = groupName; return this; } - public boolean isRestartBackup() - { + public boolean isRestartBackup() { return restartBackup; } - public ReplicaPolicyConfiguration setRestartBackup(boolean restartBackup) - { + public ReplicaPolicyConfiguration setRestartBackup(boolean restartBackup) { this.restartBackup = restartBackup; return this; } - public boolean isAllowFailBack() - { + public boolean isAllowFailBack() { return allowFailBack; } - public ReplicaPolicyConfiguration setAllowFailBack(boolean allowFailBack) - { + public ReplicaPolicyConfiguration setAllowFailBack(boolean allowFailBack) { this.allowFailBack = allowFailBack; return this; } - public ReplicaPolicyConfiguration setFailbackDelay(long failbackDelay) - { + public ReplicaPolicyConfiguration setFailbackDelay(long failbackDelay) { this.failbackDelay = failbackDelay; return this; } - public long getFailbackDelay() - { + public long getFailbackDelay() { return failbackDelay; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ha/ReplicatedPolicyConfiguration.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ha/ReplicatedPolicyConfiguration.java index 30dc430ce7..ce6244314d 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ha/ReplicatedPolicyConfiguration.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ha/ReplicatedPolicyConfiguration.java @@ -19,53 +19,45 @@ package org.apache.activemq.artemis.core.config.ha; import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration; import org.apache.activemq.artemis.core.config.HAPolicyConfiguration; -public class ReplicatedPolicyConfiguration implements HAPolicyConfiguration -{ +public class ReplicatedPolicyConfiguration implements HAPolicyConfiguration { + private boolean checkForLiveServer = ActiveMQDefaultConfiguration.isDefaultCheckForLiveServer(); private String groupName = null; private String clusterName = null; - public ReplicatedPolicyConfiguration() - { + public ReplicatedPolicyConfiguration() { } @Override - public TYPE getType() - { + public TYPE getType() { return TYPE.REPLICATED; } - public boolean isCheckForLiveServer() - { + public boolean isCheckForLiveServer() { return checkForLiveServer; } - public ReplicatedPolicyConfiguration setCheckForLiveServer(boolean checkForLiveServer) - { + public ReplicatedPolicyConfiguration setCheckForLiveServer(boolean checkForLiveServer) { this.checkForLiveServer = checkForLiveServer; return this; } - public String getGroupName() - { + public String getGroupName() { return groupName; } - public ReplicatedPolicyConfiguration setGroupName(String groupName) - { + public ReplicatedPolicyConfiguration setGroupName(String groupName) { this.groupName = groupName; return this; } - public String getClusterName() - { + public String getClusterName() { return clusterName; } - public ReplicatedPolicyConfiguration setClusterName(String clusterName) - { + public ReplicatedPolicyConfiguration setClusterName(String clusterName) { this.clusterName = clusterName; return this; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ha/SharedStoreMasterPolicyConfiguration.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ha/SharedStoreMasterPolicyConfiguration.java index 43394e7daf..c868022998 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ha/SharedStoreMasterPolicyConfiguration.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ha/SharedStoreMasterPolicyConfiguration.java @@ -19,40 +19,34 @@ package org.apache.activemq.artemis.core.config.ha; import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration; import org.apache.activemq.artemis.core.config.HAPolicyConfiguration; -public class SharedStoreMasterPolicyConfiguration implements HAPolicyConfiguration -{ +public class SharedStoreMasterPolicyConfiguration implements HAPolicyConfiguration { + private long failbackDelay = ActiveMQDefaultConfiguration.getDefaultFailbackDelay(); private boolean failoverOnServerShutdown = ActiveMQDefaultConfiguration.isDefaultFailoverOnServerShutdown(); - public SharedStoreMasterPolicyConfiguration() - { + public SharedStoreMasterPolicyConfiguration() { } @Override - public TYPE getType() - { + public TYPE getType() { return TYPE.SHARED_STORE_MASTER; } - public long getFailbackDelay() - { + public long getFailbackDelay() { return failbackDelay; } - public SharedStoreMasterPolicyConfiguration setFailbackDelay(long failbackDelay) - { + public SharedStoreMasterPolicyConfiguration setFailbackDelay(long failbackDelay) { this.failbackDelay = failbackDelay; return this; } - public boolean isFailoverOnServerShutdown() - { + public boolean isFailoverOnServerShutdown() { return failoverOnServerShutdown; } - public SharedStoreMasterPolicyConfiguration setFailoverOnServerShutdown(boolean failoverOnServerShutdown) - { + public SharedStoreMasterPolicyConfiguration setFailoverOnServerShutdown(boolean failoverOnServerShutdown) { this.failoverOnServerShutdown = failoverOnServerShutdown; return this; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ha/SharedStoreSlavePolicyConfiguration.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ha/SharedStoreSlavePolicyConfiguration.java index 01313fc65f..8e220771c7 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ha/SharedStoreSlavePolicyConfiguration.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/ha/SharedStoreSlavePolicyConfiguration.java @@ -20,8 +20,8 @@ import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration; import org.apache.activemq.artemis.core.config.HAPolicyConfiguration; import org.apache.activemq.artemis.core.config.ScaleDownConfiguration; -public class SharedStoreSlavePolicyConfiguration implements HAPolicyConfiguration -{ +public class SharedStoreSlavePolicyConfiguration implements HAPolicyConfiguration { + private long failbackDelay = ActiveMQDefaultConfiguration.getDefaultFailbackDelay(); private boolean failoverOnServerShutdown = ActiveMQDefaultConfiguration.isDefaultFailoverOnServerShutdown(); @@ -32,67 +32,55 @@ public class SharedStoreSlavePolicyConfiguration implements HAPolicyConfiguratio private ScaleDownConfiguration scaleDownConfiguration; - public SharedStoreSlavePolicyConfiguration() - { + public SharedStoreSlavePolicyConfiguration() { } @Override - public TYPE getType() - { + public TYPE getType() { return TYPE.SHARED_STORE_SLAVE; } - public boolean isRestartBackup() - { + public boolean isRestartBackup() { return restartBackup; } - public SharedStoreSlavePolicyConfiguration setRestartBackup(boolean restartBackup) - { + public SharedStoreSlavePolicyConfiguration setRestartBackup(boolean restartBackup) { this.restartBackup = restartBackup; return this; } - public ScaleDownConfiguration getScaleDownConfiguration() - { + public ScaleDownConfiguration getScaleDownConfiguration() { return scaleDownConfiguration; } - public SharedStoreSlavePolicyConfiguration setScaleDownConfiguration(ScaleDownConfiguration scaleDownConfiguration) - { + public SharedStoreSlavePolicyConfiguration setScaleDownConfiguration(ScaleDownConfiguration scaleDownConfiguration) { this.scaleDownConfiguration = scaleDownConfiguration; return this; } - public boolean isAllowFailBack() - { + public boolean isAllowFailBack() { return allowFailBack; } - public SharedStoreSlavePolicyConfiguration setAllowFailBack(boolean allowFailBack) - { + public SharedStoreSlavePolicyConfiguration setAllowFailBack(boolean allowFailBack) { this.allowFailBack = allowFailBack; return this; } - public boolean isFailoverOnServerShutdown() - { + public boolean isFailoverOnServerShutdown() { return failoverOnServerShutdown; } - public SharedStoreSlavePolicyConfiguration setFailoverOnServerShutdown(boolean failoverOnServerShutdown) - { + public SharedStoreSlavePolicyConfiguration setFailoverOnServerShutdown(boolean failoverOnServerShutdown) { this.failoverOnServerShutdown = failoverOnServerShutdown; return this; } - public long getFailbackDelay() - { + public long getFailbackDelay() { return failbackDelay; } - public SharedStoreSlavePolicyConfiguration setFailbackDelay(long failbackDelay) - { + public SharedStoreSlavePolicyConfiguration setFailbackDelay(long failbackDelay) { this.failbackDelay = failbackDelay; return this; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/impl/ConfigurationImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/impl/ConfigurationImpl.java index c6dab0e096..75fbe597df 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/impl/ConfigurationImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/impl/ConfigurationImpl.java @@ -54,8 +54,7 @@ import org.apache.activemq.artemis.core.settings.impl.AddressSettings; import org.apache.activemq.artemis.core.settings.impl.ResourceLimitSettings; import org.apache.activemq.artemis.utils.ObjectInputStreamWithClassLoader; -public class ConfigurationImpl implements Configuration, Serializable -{ +public class ConfigurationImpl implements Configuration, Serializable { // Constants ------------------------------------------------------------------------------ public static final JournalType DEFAULT_JOURNAL_TYPE = JournalType.ASYNCIO; @@ -70,8 +69,7 @@ public class ConfigurationImpl implements Configuration, Serializable protected long fileDeploymentScanPeriod = ActiveMQDefaultConfiguration.getDefaultFileDeployerScanPeriod(); - private boolean persistDeliveryCountBeforeDelivery = - ActiveMQDefaultConfiguration.isDefaultPersistDeliveryCountBeforeDelivery(); + private boolean persistDeliveryCountBeforeDelivery = ActiveMQDefaultConfiguration.isDefaultPersistDeliveryCountBeforeDelivery(); private int scheduledThreadPoolMaxSize = ActiveMQDefaultConfiguration.getDefaultScheduledThreadPoolMaxSize(); @@ -229,29 +227,24 @@ public class ConfigurationImpl implements Configuration, Serializable // Public ------------------------------------------------------------------------- - public boolean isClustered() - { + public boolean isClustered() { return !getClusterConfigurations().isEmpty(); } - public boolean isPersistenceEnabled() - { + public boolean isPersistenceEnabled() { return persistenceEnabled; } - public ConfigurationImpl setPersistenceEnabled(final boolean enable) - { + public ConfigurationImpl setPersistenceEnabled(final boolean enable) { persistenceEnabled = enable; return this; } - public long getFileDeployerScanPeriod() - { + public long getFileDeployerScanPeriod() { return fileDeploymentScanPeriod; } - public ConfigurationImpl setFileDeployerScanPeriod(final long period) - { + public ConfigurationImpl setFileDeployerScanPeriod(final long period) { fileDeploymentScanPeriod = period; return this; } @@ -259,864 +252,710 @@ public class ConfigurationImpl implements Configuration, Serializable /** * @return the persistDeliveryCountBeforeDelivery */ - public boolean isPersistDeliveryCountBeforeDelivery() - { + public boolean isPersistDeliveryCountBeforeDelivery() { return persistDeliveryCountBeforeDelivery; } - public ConfigurationImpl setPersistDeliveryCountBeforeDelivery(final boolean persistDeliveryCountBeforeDelivery) - { + public ConfigurationImpl setPersistDeliveryCountBeforeDelivery(final boolean persistDeliveryCountBeforeDelivery) { this.persistDeliveryCountBeforeDelivery = persistDeliveryCountBeforeDelivery; return this; } - public int getScheduledThreadPoolMaxSize() - { + public int getScheduledThreadPoolMaxSize() { return scheduledThreadPoolMaxSize; } - public ConfigurationImpl setScheduledThreadPoolMaxSize(final int maxSize) - { + public ConfigurationImpl setScheduledThreadPoolMaxSize(final int maxSize) { scheduledThreadPoolMaxSize = maxSize; return this; } - public int getThreadPoolMaxSize() - { + public int getThreadPoolMaxSize() { return threadPoolMaxSize; } - public ConfigurationImpl setThreadPoolMaxSize(final int maxSize) - { + public ConfigurationImpl setThreadPoolMaxSize(final int maxSize) { threadPoolMaxSize = maxSize; return this; } - public long getSecurityInvalidationInterval() - { + public long getSecurityInvalidationInterval() { return securityInvalidationInterval; } - public ConfigurationImpl setSecurityInvalidationInterval(final long interval) - { + public ConfigurationImpl setSecurityInvalidationInterval(final long interval) { securityInvalidationInterval = interval; return this; } - public long getConnectionTTLOverride() - { + public long getConnectionTTLOverride() { return connectionTTLOverride; } - public ConfigurationImpl setConnectionTTLOverride(final long ttl) - { + public ConfigurationImpl setConnectionTTLOverride(final long ttl) { connectionTTLOverride = ttl; return this; } - public boolean isAsyncConnectionExecutionEnabled() - { + public boolean isAsyncConnectionExecutionEnabled() { return asyncConnectionExecutionEnabled; } - public ConfigurationImpl setEnabledAsyncConnectionExecution(final boolean enabled) - { + public ConfigurationImpl setEnabledAsyncConnectionExecution(final boolean enabled) { asyncConnectionExecutionEnabled = enabled; return this; } - public List getIncomingInterceptorClassNames() - { + public List getIncomingInterceptorClassNames() { return incomingInterceptorClassNames; } - public ConfigurationImpl setIncomingInterceptorClassNames(final List interceptors) - { + public ConfigurationImpl setIncomingInterceptorClassNames(final List interceptors) { incomingInterceptorClassNames = interceptors; return this; } - public List getOutgoingInterceptorClassNames() - { + public List getOutgoingInterceptorClassNames() { return outgoingInterceptorClassNames; } - public ConfigurationImpl setOutgoingInterceptorClassNames(final List interceptors) - { + public ConfigurationImpl setOutgoingInterceptorClassNames(final List interceptors) { outgoingInterceptorClassNames = interceptors; return this; } - public Set getAcceptorConfigurations() - { + public Set getAcceptorConfigurations() { return acceptorConfigs; } - public ConfigurationImpl setAcceptorConfigurations(final Set infos) - { + public ConfigurationImpl setAcceptorConfigurations(final Set infos) { acceptorConfigs = infos; return this; } - public ConfigurationImpl addAcceptorConfiguration(final TransportConfiguration infos) - { + public ConfigurationImpl addAcceptorConfiguration(final TransportConfiguration infos) { acceptorConfigs.add(infos); return this; } - public ConfigurationImpl clearAcceptorConfigurations() - { + public ConfigurationImpl clearAcceptorConfigurations() { acceptorConfigs.clear(); return this; } - public Map getConnectorConfigurations() - { + public Map getConnectorConfigurations() { return connectorConfigs; } - public ConfigurationImpl setConnectorConfigurations(final Map infos) - { + public ConfigurationImpl setConnectorConfigurations(final Map infos) { connectorConfigs = infos; return this; } - public ConfigurationImpl addConnectorConfiguration(final String key, final TransportConfiguration info) - { + public ConfigurationImpl addConnectorConfiguration(final String key, final TransportConfiguration info) { connectorConfigs.put(key, info); return this; } - public ConfigurationImpl clearConnectorConfigurations() - { + public ConfigurationImpl clearConnectorConfigurations() { connectorConfigs.clear(); return this; } - public GroupingHandlerConfiguration getGroupingHandlerConfiguration() - { + public GroupingHandlerConfiguration getGroupingHandlerConfiguration() { return groupingHandlerConfiguration; } - public ConfigurationImpl setGroupingHandlerConfiguration(final GroupingHandlerConfiguration groupingHandlerConfiguration) - { + public ConfigurationImpl setGroupingHandlerConfiguration(final GroupingHandlerConfiguration groupingHandlerConfiguration) { this.groupingHandlerConfiguration = groupingHandlerConfiguration; return this; } - public List getBridgeConfigurations() - { + public List getBridgeConfigurations() { return bridgeConfigurations; } - public ConfigurationImpl setBridgeConfigurations(final List configs) - { + public ConfigurationImpl setBridgeConfigurations(final List configs) { bridgeConfigurations = configs; return this; } - public ConfigurationImpl addBridgeConfiguration(final BridgeConfiguration config) - { + public ConfigurationImpl addBridgeConfiguration(final BridgeConfiguration config) { bridgeConfigurations.add(config); return this; } - public List getBroadcastGroupConfigurations() - { + public List getBroadcastGroupConfigurations() { return broadcastGroupConfigurations; } - public ConfigurationImpl setBroadcastGroupConfigurations(final List configs) - { + public ConfigurationImpl setBroadcastGroupConfigurations(final List configs) { broadcastGroupConfigurations = configs; return this; } - public ConfigurationImpl addBroadcastGroupConfiguration(final BroadcastGroupConfiguration config) - { + public ConfigurationImpl addBroadcastGroupConfiguration(final BroadcastGroupConfiguration config) { broadcastGroupConfigurations.add(config); return this; } - public List getClusterConfigurations() - { + public List getClusterConfigurations() { return clusterConfigurations; } - public ConfigurationImpl setClusterConfigurations(final List configs) - { + public ConfigurationImpl setClusterConfigurations(final List configs) { clusterConfigurations = configs; return this; } - public ConfigurationImpl addClusterConfiguration(final ClusterConnectionConfiguration config) - { + public ConfigurationImpl addClusterConfiguration(final ClusterConnectionConfiguration config) { clusterConfigurations.add(config); return this; } - public ConfigurationImpl clearClusterConfigurations() - { + public ConfigurationImpl clearClusterConfigurations() { clusterConfigurations.clear(); return this; } - public List getDivertConfigurations() - { + public List getDivertConfigurations() { return divertConfigurations; } - public ConfigurationImpl setDivertConfigurations(final List configs) - { + public ConfigurationImpl setDivertConfigurations(final List configs) { divertConfigurations = configs; return this; } - public ConfigurationImpl addDivertConfiguration(final DivertConfiguration config) - { + public ConfigurationImpl addDivertConfiguration(final DivertConfiguration config) { divertConfigurations.add(config); return this; } - public List getQueueConfigurations() - { + public List getQueueConfigurations() { return queueConfigurations; } - public ConfigurationImpl setQueueConfigurations(final List configs) - { + public ConfigurationImpl setQueueConfigurations(final List configs) { queueConfigurations = configs; return this; } - public ConfigurationImpl addQueueConfiguration(final CoreQueueConfiguration config) - { + public ConfigurationImpl addQueueConfiguration(final CoreQueueConfiguration config) { queueConfigurations.add(config); return this; } - public Map getDiscoveryGroupConfigurations() - { + public Map getDiscoveryGroupConfigurations() { return discoveryGroupConfigurations; } - public ConfigurationImpl setDiscoveryGroupConfigurations(final Map discoveryGroupConfigurations) - { + public ConfigurationImpl setDiscoveryGroupConfigurations(final Map discoveryGroupConfigurations) { this.discoveryGroupConfigurations = discoveryGroupConfigurations; return this; } - public ConfigurationImpl addDiscoveryGroupConfiguration(final String key, DiscoveryGroupConfiguration discoveryGroupConfiguration) - { + public ConfigurationImpl addDiscoveryGroupConfiguration(final String key, + DiscoveryGroupConfiguration discoveryGroupConfiguration) { this.discoveryGroupConfigurations.put(key, discoveryGroupConfiguration); return this; } - public int getIDCacheSize() - { + public int getIDCacheSize() { return idCacheSize; } - public ConfigurationImpl setIDCacheSize(final int idCacheSize) - { + public ConfigurationImpl setIDCacheSize(final int idCacheSize) { this.idCacheSize = idCacheSize; return this; } - public boolean isPersistIDCache() - { + public boolean isPersistIDCache() { return persistIDCache; } - public ConfigurationImpl setPersistIDCache(final boolean persist) - { + public ConfigurationImpl setPersistIDCache(final boolean persist) { persistIDCache = persist; return this; } - public File getBindingsLocation() - { + public File getBindingsLocation() { return subFolder(getBindingsDirectory()); } - public String getBindingsDirectory() - { + public String getBindingsDirectory() { return bindingsDirectory; } - public ConfigurationImpl setBindingsDirectory(final String dir) - { + public ConfigurationImpl setBindingsDirectory(final String dir) { bindingsDirectory = dir; return this; } - @Override - public int getPageMaxConcurrentIO() - { + public int getPageMaxConcurrentIO() { return maxConcurrentPageIO; } @Override - public ConfigurationImpl setPageMaxConcurrentIO(int maxIO) - { + public ConfigurationImpl setPageMaxConcurrentIO(int maxIO) { this.maxConcurrentPageIO = maxIO; return this; } - public File getJournalLocation() - { + public File getJournalLocation() { return subFolder(getJournalDirectory()); } - public String getJournalDirectory() - { + public String getJournalDirectory() { return journalDirectory; } - public ConfigurationImpl setJournalDirectory(final String dir) - { + public ConfigurationImpl setJournalDirectory(final String dir) { journalDirectory = dir; return this; } - public JournalType getJournalType() - { + public JournalType getJournalType() { return journalType; } - public ConfigurationImpl setPagingDirectory(final String dir) - { + public ConfigurationImpl setPagingDirectory(final String dir) { pagingDirectory = dir; return this; } - public File getPagingLocation() - { + public File getPagingLocation() { return subFolder(getPagingDirectory()); } - public String getPagingDirectory() - { + public String getPagingDirectory() { return pagingDirectory; } - public ConfigurationImpl setJournalType(final JournalType type) - { + public ConfigurationImpl setJournalType(final JournalType type) { journalType = type; return this; } - public boolean isJournalSyncTransactional() - { + public boolean isJournalSyncTransactional() { return journalSyncTransactional; } - public ConfigurationImpl setJournalSyncTransactional(final boolean sync) - { + public ConfigurationImpl setJournalSyncTransactional(final boolean sync) { journalSyncTransactional = sync; return this; } - public boolean isJournalSyncNonTransactional() - { + public boolean isJournalSyncNonTransactional() { return journalSyncNonTransactional; } - public ConfigurationImpl setJournalSyncNonTransactional(final boolean sync) - { + public ConfigurationImpl setJournalSyncNonTransactional(final boolean sync) { journalSyncNonTransactional = sync; return this; } - public int getJournalFileSize() - { + public int getJournalFileSize() { return journalFileSize; } - public ConfigurationImpl setJournalFileSize(final int size) - { + public ConfigurationImpl setJournalFileSize(final int size) { journalFileSize = size; return this; } - public int getJournalMinFiles() - { + public int getJournalMinFiles() { return journalMinFiles; } - public ConfigurationImpl setJournalMinFiles(final int files) - { + public ConfigurationImpl setJournalMinFiles(final int files) { journalMinFiles = files; return this; } - public boolean isLogJournalWriteRate() - { + public boolean isLogJournalWriteRate() { return logJournalWriteRate; } - public ConfigurationImpl setLogJournalWriteRate(final boolean logJournalWriteRate) - { + public ConfigurationImpl setLogJournalWriteRate(final boolean logJournalWriteRate) { this.logJournalWriteRate = logJournalWriteRate; return this; } - public int getJournalPerfBlastPages() - { + public int getJournalPerfBlastPages() { return journalPerfBlastPages; } - public ConfigurationImpl setJournalPerfBlastPages(final int journalPerfBlastPages) - { + public ConfigurationImpl setJournalPerfBlastPages(final int journalPerfBlastPages) { this.journalPerfBlastPages = journalPerfBlastPages; return this; } - public boolean isRunSyncSpeedTest() - { + public boolean isRunSyncSpeedTest() { return runSyncSpeedTest; } - public ConfigurationImpl setRunSyncSpeedTest(final boolean run) - { + public ConfigurationImpl setRunSyncSpeedTest(final boolean run) { runSyncSpeedTest = run; return this; } - public boolean isCreateBindingsDir() - { + public boolean isCreateBindingsDir() { return createBindingsDir; } - public ConfigurationImpl setCreateBindingsDir(final boolean create) - { + public ConfigurationImpl setCreateBindingsDir(final boolean create) { createBindingsDir = create; return this; } - public boolean isCreateJournalDir() - { + public boolean isCreateJournalDir() { return createJournalDir; } - public ConfigurationImpl setCreateJournalDir(final boolean create) - { + public ConfigurationImpl setCreateJournalDir(final boolean create) { createJournalDir = create; return this; } - public boolean isWildcardRoutingEnabled() - { + public boolean isWildcardRoutingEnabled() { return wildcardRoutingEnabled; } - public ConfigurationImpl setWildcardRoutingEnabled(final boolean enabled) - { + public ConfigurationImpl setWildcardRoutingEnabled(final boolean enabled) { wildcardRoutingEnabled = enabled; return this; } - public long getTransactionTimeout() - { + public long getTransactionTimeout() { return transactionTimeout; } - public ConfigurationImpl setTransactionTimeout(final long timeout) - { + public ConfigurationImpl setTransactionTimeout(final long timeout) { transactionTimeout = timeout; return this; } - public long getTransactionTimeoutScanPeriod() - { + public long getTransactionTimeoutScanPeriod() { return transactionTimeoutScanPeriod; } - public ConfigurationImpl setTransactionTimeoutScanPeriod(final long period) - { + public ConfigurationImpl setTransactionTimeoutScanPeriod(final long period) { transactionTimeoutScanPeriod = period; return this; } - public long getMessageExpiryScanPeriod() - { + public long getMessageExpiryScanPeriod() { return messageExpiryScanPeriod; } - public ConfigurationImpl setMessageExpiryScanPeriod(final long messageExpiryScanPeriod) - { + public ConfigurationImpl setMessageExpiryScanPeriod(final long messageExpiryScanPeriod) { this.messageExpiryScanPeriod = messageExpiryScanPeriod; return this; } - public int getMessageExpiryThreadPriority() - { + public int getMessageExpiryThreadPriority() { return messageExpiryThreadPriority; } - public ConfigurationImpl setMessageExpiryThreadPriority(final int messageExpiryThreadPriority) - { + public ConfigurationImpl setMessageExpiryThreadPriority(final int messageExpiryThreadPriority) { this.messageExpiryThreadPriority = messageExpiryThreadPriority; return this; } - public boolean isSecurityEnabled() - { + public boolean isSecurityEnabled() { return securityEnabled; } - public ConfigurationImpl setSecurityEnabled(final boolean enabled) - { + public ConfigurationImpl setSecurityEnabled(final boolean enabled) { securityEnabled = enabled; return this; } - public boolean isGracefulShutdownEnabled() - { + public boolean isGracefulShutdownEnabled() { return gracefulShutdownEnabled; } - public ConfigurationImpl setGracefulShutdownEnabled(final boolean enabled) - { + public ConfigurationImpl setGracefulShutdownEnabled(final boolean enabled) { gracefulShutdownEnabled = enabled; return this; } - public long getGracefulShutdownTimeout() - { + public long getGracefulShutdownTimeout() { return gracefulShutdownTimeout; } - public ConfigurationImpl setGracefulShutdownTimeout(final long timeout) - { + public ConfigurationImpl setGracefulShutdownTimeout(final long timeout) { gracefulShutdownTimeout = timeout; return this; } - public boolean isJMXManagementEnabled() - { + public boolean isJMXManagementEnabled() { return jmxManagementEnabled; } - public ConfigurationImpl setJMXManagementEnabled(final boolean enabled) - { + public ConfigurationImpl setJMXManagementEnabled(final boolean enabled) { jmxManagementEnabled = enabled; return this; } - public String getJMXDomain() - { + public String getJMXDomain() { return jmxDomain; } - public ConfigurationImpl setJMXDomain(final String domain) - { + public ConfigurationImpl setJMXDomain(final String domain) { jmxDomain = domain; return this; } - public String getLargeMessagesDirectory() - { + public String getLargeMessagesDirectory() { return largeMessagesDirectory; } - public File getLargeMessagesLocation() - { + public File getLargeMessagesLocation() { return subFolder(getLargeMessagesDirectory()); } - public ConfigurationImpl setLargeMessagesDirectory(final String directory) - { + public ConfigurationImpl setLargeMessagesDirectory(final String directory) { largeMessagesDirectory = directory; return this; } - public boolean isMessageCounterEnabled() - { + public boolean isMessageCounterEnabled() { return messageCounterEnabled; } - public ConfigurationImpl setMessageCounterEnabled(final boolean enabled) - { + public ConfigurationImpl setMessageCounterEnabled(final boolean enabled) { messageCounterEnabled = enabled; return this; } - public long getMessageCounterSamplePeriod() - { + public long getMessageCounterSamplePeriod() { return messageCounterSamplePeriod; } - public ConfigurationImpl setMessageCounterSamplePeriod(final long period) - { + public ConfigurationImpl setMessageCounterSamplePeriod(final long period) { messageCounterSamplePeriod = period; return this; } - public int getMessageCounterMaxDayHistory() - { + public int getMessageCounterMaxDayHistory() { return messageCounterMaxDayHistory; } - public ConfigurationImpl setMessageCounterMaxDayHistory(final int maxDayHistory) - { + public ConfigurationImpl setMessageCounterMaxDayHistory(final int maxDayHistory) { messageCounterMaxDayHistory = maxDayHistory; return this; } - public SimpleString getManagementAddress() - { + public SimpleString getManagementAddress() { return managementAddress; } - public ConfigurationImpl setManagementAddress(final SimpleString address) - { + public ConfigurationImpl setManagementAddress(final SimpleString address) { managementAddress = address; return this; } - public SimpleString getManagementNotificationAddress() - { + public SimpleString getManagementNotificationAddress() { return managementNotificationAddress; } - public ConfigurationImpl setManagementNotificationAddress(final SimpleString address) - { + public ConfigurationImpl setManagementNotificationAddress(final SimpleString address) { managementNotificationAddress = address; return this; } - public String getClusterUser() - { + public String getClusterUser() { return clusterUser; } - public ConfigurationImpl setClusterUser(final String user) - { + public ConfigurationImpl setClusterUser(final String user) { clusterUser = user; return this; } - public String getClusterPassword() - { + public String getClusterPassword() { return clusterPassword; } - public boolean isFailoverOnServerShutdown() - { + public boolean isFailoverOnServerShutdown() { return failoverOnServerShutdown; } - public ConfigurationImpl setFailoverOnServerShutdown(boolean failoverOnServerShutdown) - { + public ConfigurationImpl setFailoverOnServerShutdown(boolean failoverOnServerShutdown) { this.failoverOnServerShutdown = failoverOnServerShutdown; return this; } - public ConfigurationImpl setClusterPassword(final String theclusterPassword) - { + public ConfigurationImpl setClusterPassword(final String theclusterPassword) { clusterPassword = theclusterPassword; return this; } - public int getJournalCompactMinFiles() - { + public int getJournalCompactMinFiles() { return journalCompactMinFiles; } - public int getJournalCompactPercentage() - { + public int getJournalCompactPercentage() { return journalCompactPercentage; } - public ConfigurationImpl setJournalCompactMinFiles(final int minFiles) - { + public ConfigurationImpl setJournalCompactMinFiles(final int minFiles) { journalCompactMinFiles = minFiles; return this; } - public ConfigurationImpl setJournalCompactPercentage(final int percentage) - { + public ConfigurationImpl setJournalCompactPercentage(final int percentage) { journalCompactPercentage = percentage; return this; } - public long getServerDumpInterval() - { + public long getServerDumpInterval() { return serverDumpInterval; } - public ConfigurationImpl setServerDumpInterval(final long intervalInMilliseconds) - { + public ConfigurationImpl setServerDumpInterval(final long intervalInMilliseconds) { serverDumpInterval = intervalInMilliseconds; return this; } - public int getMemoryWarningThreshold() - { + public int getMemoryWarningThreshold() { return memoryWarningThreshold; } - public ConfigurationImpl setMemoryWarningThreshold(final int memoryWarningThreshold) - { + public ConfigurationImpl setMemoryWarningThreshold(final int memoryWarningThreshold) { this.memoryWarningThreshold = memoryWarningThreshold; return this; } - public long getMemoryMeasureInterval() - { + public long getMemoryMeasureInterval() { return memoryMeasureInterval; } - public ConfigurationImpl setMemoryMeasureInterval(final long memoryMeasureInterval) - { + public ConfigurationImpl setMemoryMeasureInterval(final long memoryMeasureInterval) { this.memoryMeasureInterval = memoryMeasureInterval; return this; } - public int getJournalMaxIO_AIO() - { + public int getJournalMaxIO_AIO() { return journalMaxIO_AIO; } - public ConfigurationImpl setJournalMaxIO_AIO(final int journalMaxIO) - { + public ConfigurationImpl setJournalMaxIO_AIO(final int journalMaxIO) { journalMaxIO_AIO = journalMaxIO; return this; } - public int getJournalBufferTimeout_AIO() - { + public int getJournalBufferTimeout_AIO() { return journalBufferTimeout_AIO; } - public ConfigurationImpl setJournalBufferTimeout_AIO(final int journalBufferTimeout) - { + public ConfigurationImpl setJournalBufferTimeout_AIO(final int journalBufferTimeout) { journalBufferTimeout_AIO = journalBufferTimeout; return this; } - public int getJournalBufferSize_AIO() - { + public int getJournalBufferSize_AIO() { return journalBufferSize_AIO; } - public ConfigurationImpl setJournalBufferSize_AIO(final int journalBufferSize) - { + public ConfigurationImpl setJournalBufferSize_AIO(final int journalBufferSize) { journalBufferSize_AIO = journalBufferSize; return this; } - public int getJournalMaxIO_NIO() - { + public int getJournalMaxIO_NIO() { return journalMaxIO_NIO; } - public ConfigurationImpl setJournalMaxIO_NIO(final int journalMaxIO) - { + public ConfigurationImpl setJournalMaxIO_NIO(final int journalMaxIO) { journalMaxIO_NIO = journalMaxIO; return this; } - public int getJournalBufferTimeout_NIO() - { + public int getJournalBufferTimeout_NIO() { return journalBufferTimeout_NIO; } - public ConfigurationImpl setJournalBufferTimeout_NIO(final int journalBufferTimeout) - { + public ConfigurationImpl setJournalBufferTimeout_NIO(final int journalBufferTimeout) { journalBufferTimeout_NIO = journalBufferTimeout; return this; } - public int getJournalBufferSize_NIO() - { + public int getJournalBufferSize_NIO() { return journalBufferSize_NIO; } - public ConfigurationImpl setJournalBufferSize_NIO(final int journalBufferSize) - { + public ConfigurationImpl setJournalBufferSize_NIO(final int journalBufferSize) { journalBufferSize_NIO = journalBufferSize; return this; } @Override - public Map getAddressesSettings() - { + public Map getAddressesSettings() { return addressesSettings; } @Override - public ConfigurationImpl setAddressesSettings(final Map addressesSettings) - { + public ConfigurationImpl setAddressesSettings(final Map addressesSettings) { this.addressesSettings = addressesSettings; return this; } @Override - public ConfigurationImpl addAddressesSetting(String key, AddressSettings addressesSetting) - { + public ConfigurationImpl addAddressesSetting(String key, AddressSettings addressesSetting) { this.addressesSettings.put(key, addressesSetting); return this; } @Override - public ConfigurationImpl clearAddressesSettings() - { + public ConfigurationImpl clearAddressesSettings() { this.addressesSettings.clear(); return this; } @Override - public Map getResourceLimitSettings() - { + public Map getResourceLimitSettings() { return resourceLimitSettings; } @Override - public ConfigurationImpl setResourceLimitSettings(final Map resourceLimitSettings) - { + public ConfigurationImpl setResourceLimitSettings(final Map resourceLimitSettings) { this.resourceLimitSettings = resourceLimitSettings; return this; } @Override - public ConfigurationImpl addResourceLimitSettings(ResourceLimitSettings resourceLimitSettings) - { + public ConfigurationImpl addResourceLimitSettings(ResourceLimitSettings resourceLimitSettings) { this.resourceLimitSettings.put(resourceLimitSettings.getMatch().toString(), resourceLimitSettings); return this; } @Override - public Map> getSecurityRoles() - { + public Map> getSecurityRoles() { return securitySettings; } @Override - public ConfigurationImpl setSecurityRoles(final Map> securitySettings) - { + public ConfigurationImpl setSecurityRoles(final Map> securitySettings) { this.securitySettings = securitySettings; return this; } - public List getConnectorServiceConfigurations() - { + public List getConnectorServiceConfigurations() { return this.connectorServiceConfigurations; } - public File getBrokerInstance() - { - if (artemisInstance != null) - { + public File getBrokerInstance() { + if (artemisInstance != null) { return artemisInstance; } String strartemisInstance = System.getProperty("artemis.instance"); - if (strartemisInstance == null) - { + if (strartemisInstance == null) { strartemisInstance = System.getProperty("user.dir"); } @@ -1125,36 +964,29 @@ public class ConfigurationImpl implements Configuration, Serializable return artemisInstance; } - public void setBrokerInstance(File directory) - { + public void setBrokerInstance(File directory) { this.artemisInstance = directory; } - public boolean isCheckForLiveServer() - { - if (haPolicyConfiguration instanceof ReplicaPolicyConfiguration) - { - return ((ReplicatedPolicyConfiguration)haPolicyConfiguration).isCheckForLiveServer(); + public boolean isCheckForLiveServer() { + if (haPolicyConfiguration instanceof ReplicaPolicyConfiguration) { + return ((ReplicatedPolicyConfiguration) haPolicyConfiguration).isCheckForLiveServer(); } - else - { + else { return false; } } - public ConfigurationImpl setCheckForLiveServer(boolean checkForLiveServer) - { - if (haPolicyConfiguration instanceof ReplicaPolicyConfiguration) - { - ((ReplicatedPolicyConfiguration)haPolicyConfiguration).setCheckForLiveServer(checkForLiveServer); + public ConfigurationImpl setCheckForLiveServer(boolean checkForLiveServer) { + if (haPolicyConfiguration instanceof ReplicaPolicyConfiguration) { + ((ReplicatedPolicyConfiguration) haPolicyConfiguration).setCheckForLiveServer(checkForLiveServer); } return this; } @Override - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder("Broker Configuration ("); sb.append("clustered=").append(isClustered()).append(","); sb.append("journalDirectory=").append(journalDirectory).append(","); @@ -1165,69 +997,58 @@ public class ConfigurationImpl implements Configuration, Serializable return sb.toString(); } - public ConfigurationImpl setConnectorServiceConfigurations(final List configs) - { + public ConfigurationImpl setConnectorServiceConfigurations(final List configs) { this.connectorServiceConfigurations = configs; return this; } - public ConfigurationImpl addConnectorServiceConfiguration(final ConnectorServiceConfiguration config) - { + public ConfigurationImpl addConnectorServiceConfiguration(final ConnectorServiceConfiguration config) { this.connectorServiceConfigurations.add(config); return this; } - public boolean isMaskPassword() - { + public boolean isMaskPassword() { return maskPassword; } - public ConfigurationImpl setMaskPassword(boolean maskPassword) - { + public ConfigurationImpl setMaskPassword(boolean maskPassword) { this.maskPassword = maskPassword; return this; } - public ConfigurationImpl setPasswordCodec(String codec) - { + public ConfigurationImpl setPasswordCodec(String codec) { passwordCodec = codec; return this; } - public String getPasswordCodec() - { + public String getPasswordCodec() { return passwordCodec; } @Override - public String getName() - { + public String getName() { return name; } @Override - public ConfigurationImpl setName(String name) - { + public ConfigurationImpl setName(String name) { this.name = name; return this; } @Override - public ConfigurationImpl setResolveProtocols(boolean resolveProtocols) - { + public ConfigurationImpl setResolveProtocols(boolean resolveProtocols) { this.resolveProtocols = resolveProtocols; return this; } @Override - public boolean isResolveProtocols() - { + public boolean isResolveProtocols() { return resolveProtocols; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((acceptorConfigs == null) ? 0 : acceptorConfigs.hashCode()); @@ -1239,22 +1060,18 @@ public class ConfigurationImpl implements Configuration, Serializable result = prime * result + ((clusterConfigurations == null) ? 0 : clusterConfigurations.hashCode()); result = prime * result + ((clusterPassword == null) ? 0 : clusterPassword.hashCode()); result = prime * result + ((clusterUser == null) ? 0 : clusterUser.hashCode()); - result = prime * result + (int)(connectionTTLOverride ^ (connectionTTLOverride >>> 32)); + result = prime * result + (int) (connectionTTLOverride ^ (connectionTTLOverride >>> 32)); result = prime * result + ((connectorConfigs == null) ? 0 : connectorConfigs.hashCode()); - result = - prime * result + - ((connectorServiceConfigurations == null) ? 0 : connectorServiceConfigurations.hashCode()); + result = prime * result + ((connectorServiceConfigurations == null) ? 0 : connectorServiceConfigurations.hashCode()); result = prime * result + (createBindingsDir ? 1231 : 1237); result = prime * result + (createJournalDir ? 1231 : 1237); result = prime * result + ((discoveryGroupConfigurations == null) ? 0 : discoveryGroupConfigurations.hashCode()); result = prime * result + ((divertConfigurations == null) ? 0 : divertConfigurations.hashCode()); result = prime * result + (failoverOnServerShutdown ? 1231 : 1237); - result = prime * result + (int)(fileDeploymentScanPeriod ^ (fileDeploymentScanPeriod >>> 32)); + result = prime * result + (int) (fileDeploymentScanPeriod ^ (fileDeploymentScanPeriod >>> 32)); result = prime * result + ((groupingHandlerConfiguration == null) ? 0 : groupingHandlerConfiguration.hashCode()); result = prime * result + idCacheSize; - result = - prime * result + - ((incomingInterceptorClassNames == null) ? 0 : incomingInterceptorClassNames.hashCode()); + result = prime * result + ((incomingInterceptorClassNames == null) ? 0 : incomingInterceptorClassNames.hashCode()); result = prime * result + ((jmxDomain == null) ? 0 : jmxDomain.hashCode()); result = prime * result + (jmxManagementEnabled ? 1231 : 1237); result = prime * result + journalBufferSize_AIO; @@ -1275,22 +1092,18 @@ public class ConfigurationImpl implements Configuration, Serializable result = prime * result + ((largeMessagesDirectory == null) ? 0 : largeMessagesDirectory.hashCode()); result = prime * result + (logJournalWriteRate ? 1231 : 1237); result = prime * result + ((managementAddress == null) ? 0 : managementAddress.hashCode()); - result = - prime * result + - ((managementNotificationAddress == null) ? 0 : managementNotificationAddress.hashCode()); + result = prime * result + ((managementNotificationAddress == null) ? 0 : managementNotificationAddress.hashCode()); result = prime * result + (maskPassword ? 1231 : 1237); result = prime * result + maxConcurrentPageIO; - result = prime * result + (int)(memoryMeasureInterval ^ (memoryMeasureInterval >>> 32)); + result = prime * result + (int) (memoryMeasureInterval ^ (memoryMeasureInterval >>> 32)); result = prime * result + memoryWarningThreshold; result = prime * result + (messageCounterEnabled ? 1231 : 1237); result = prime * result + messageCounterMaxDayHistory; - result = prime * result + (int)(messageCounterSamplePeriod ^ (messageCounterSamplePeriod >>> 32)); - result = prime * result + (int)(messageExpiryScanPeriod ^ (messageExpiryScanPeriod >>> 32)); + result = prime * result + (int) (messageCounterSamplePeriod ^ (messageCounterSamplePeriod >>> 32)); + result = prime * result + (int) (messageExpiryScanPeriod ^ (messageExpiryScanPeriod >>> 32)); result = prime * result + messageExpiryThreadPriority; result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = - prime * result + - ((outgoingInterceptorClassNames == null) ? 0 : outgoingInterceptorClassNames.hashCode()); + result = prime * result + ((outgoingInterceptorClassNames == null) ? 0 : outgoingInterceptorClassNames.hashCode()); result = prime * result + ((pagingDirectory == null) ? 0 : pagingDirectory.hashCode()); result = prime * result + (persistDeliveryCountBeforeDelivery ? 1231 : 1237); result = prime * result + (persistIDCache ? 1231 : 1237); @@ -1299,12 +1112,12 @@ public class ConfigurationImpl implements Configuration, Serializable result = prime * result + (runSyncSpeedTest ? 1231 : 1237); result = prime * result + scheduledThreadPoolMaxSize; result = prime * result + (securityEnabled ? 1231 : 1237); - result = prime * result + (int)(securityInvalidationInterval ^ (securityInvalidationInterval >>> 32)); + result = prime * result + (int) (securityInvalidationInterval ^ (securityInvalidationInterval >>> 32)); result = prime * result + ((securitySettings == null) ? 0 : securitySettings.hashCode()); - result = prime * result + (int)(serverDumpInterval ^ (serverDumpInterval >>> 32)); + result = prime * result + (int) (serverDumpInterval ^ (serverDumpInterval >>> 32)); result = prime * result + threadPoolMaxSize; - result = prime * result + (int)(transactionTimeout ^ (transactionTimeout >>> 32)); - result = prime * result + (int)(transactionTimeoutScanPeriod ^ (transactionTimeoutScanPeriod >>> 32)); + result = prime * result + (int) (transactionTimeout ^ (transactionTimeout >>> 32)); + result = prime * result + (int) (transactionTimeoutScanPeriod ^ (transactionTimeoutScanPeriod >>> 32)); result = prime * result + (wildcardRoutingEnabled ? 1231 : 1237); result = prime * result + (resolveProtocols ? 1231 : 1237); result = prime * result + (int) (journalLockAcquisitionTimeout ^ (journalLockAcquisitionTimeout >>> 32)); @@ -1312,24 +1125,21 @@ public class ConfigurationImpl implements Configuration, Serializable } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof ConfigurationImpl)) return false; - ConfigurationImpl other = (ConfigurationImpl)obj; - if (acceptorConfigs == null) - { + ConfigurationImpl other = (ConfigurationImpl) obj; + if (acceptorConfigs == null) { if (other.acceptorConfigs != null) return false; } else if (!acceptorConfigs.equals(other.acceptorConfigs)) return false; - if (addressesSettings == null) - { + if (addressesSettings == null) { if (other.addressesSettings != null) return false; } @@ -1338,43 +1148,37 @@ public class ConfigurationImpl implements Configuration, Serializable if (asyncConnectionExecutionEnabled != other.asyncConnectionExecutionEnabled) return false; - if (bindingsDirectory == null) - { + if (bindingsDirectory == null) { if (other.bindingsDirectory != null) return false; } else if (!bindingsDirectory.equals(other.bindingsDirectory)) return false; - if (bridgeConfigurations == null) - { + if (bridgeConfigurations == null) { if (other.bridgeConfigurations != null) return false; } else if (!bridgeConfigurations.equals(other.bridgeConfigurations)) return false; - if (broadcastGroupConfigurations == null) - { + if (broadcastGroupConfigurations == null) { if (other.broadcastGroupConfigurations != null) return false; } else if (!broadcastGroupConfigurations.equals(other.broadcastGroupConfigurations)) return false; - if (clusterConfigurations == null) - { + if (clusterConfigurations == null) { if (other.clusterConfigurations != null) return false; } else if (!clusterConfigurations.equals(other.clusterConfigurations)) return false; - if (clusterPassword == null) - { + if (clusterPassword == null) { if (other.clusterPassword != null) return false; } else if (!clusterPassword.equals(other.clusterPassword)) return false; - if (clusterUser == null) - { + if (clusterUser == null) { if (other.clusterUser != null) return false; } @@ -1382,15 +1186,13 @@ public class ConfigurationImpl implements Configuration, Serializable return false; if (connectionTTLOverride != other.connectionTTLOverride) return false; - if (connectorConfigs == null) - { + if (connectorConfigs == null) { if (other.connectorConfigs != null) return false; } else if (!connectorConfigs.equals(other.connectorConfigs)) return false; - if (connectorServiceConfigurations == null) - { + if (connectorServiceConfigurations == null) { if (other.connectorServiceConfigurations != null) return false; } @@ -1400,15 +1202,13 @@ public class ConfigurationImpl implements Configuration, Serializable return false; if (createJournalDir != other.createJournalDir) return false; - if (discoveryGroupConfigurations == null) - { + if (discoveryGroupConfigurations == null) { if (other.discoveryGroupConfigurations != null) return false; } else if (!discoveryGroupConfigurations.equals(other.discoveryGroupConfigurations)) return false; - if (divertConfigurations == null) - { + if (divertConfigurations == null) { if (other.divertConfigurations != null) return false; } @@ -1418,8 +1218,7 @@ public class ConfigurationImpl implements Configuration, Serializable return false; if (fileDeploymentScanPeriod != other.fileDeploymentScanPeriod) return false; - if (groupingHandlerConfiguration == null) - { + if (groupingHandlerConfiguration == null) { if (other.groupingHandlerConfiguration != null) return false; } @@ -1427,15 +1226,13 @@ public class ConfigurationImpl implements Configuration, Serializable return false; if (idCacheSize != other.idCacheSize) return false; - if (incomingInterceptorClassNames == null) - { + if (incomingInterceptorClassNames == null) { if (other.incomingInterceptorClassNames != null) return false; } else if (!incomingInterceptorClassNames.equals(other.incomingInterceptorClassNames)) return false; - if (jmxDomain == null) - { + if (jmxDomain == null) { if (other.jmxDomain != null) return false; } @@ -1455,8 +1252,7 @@ public class ConfigurationImpl implements Configuration, Serializable return false; if (journalCompactPercentage != other.journalCompactPercentage) return false; - if (journalDirectory == null) - { + if (journalDirectory == null) { if (other.journalDirectory != null) return false; } @@ -1478,8 +1274,7 @@ public class ConfigurationImpl implements Configuration, Serializable return false; if (journalType != other.journalType) return false; - if (largeMessagesDirectory == null) - { + if (largeMessagesDirectory == null) { if (other.largeMessagesDirectory != null) return false; } @@ -1487,15 +1282,13 @@ public class ConfigurationImpl implements Configuration, Serializable return false; if (logJournalWriteRate != other.logJournalWriteRate) return false; - if (managementAddress == null) - { + if (managementAddress == null) { if (other.managementAddress != null) return false; } else if (!managementAddress.equals(other.managementAddress)) return false; - if (managementNotificationAddress == null) - { + if (managementNotificationAddress == null) { if (other.managementNotificationAddress != null) return false; } @@ -1519,23 +1312,20 @@ public class ConfigurationImpl implements Configuration, Serializable return false; if (messageExpiryThreadPriority != other.messageExpiryThreadPriority) return false; - if (name == null) - { + if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; - if (outgoingInterceptorClassNames == null) - { + if (outgoingInterceptorClassNames == null) { if (other.outgoingInterceptorClassNames != null) return false; } else if (!outgoingInterceptorClassNames.equals(other.outgoingInterceptorClassNames)) return false; - if (pagingDirectory == null) - { + if (pagingDirectory == null) { if (other.pagingDirectory != null) return false; } @@ -1547,8 +1337,7 @@ public class ConfigurationImpl implements Configuration, Serializable return false; if (persistenceEnabled != other.persistenceEnabled) return false; - if (queueConfigurations == null) - { + if (queueConfigurations == null) { if (other.queueConfigurations != null) return false; } @@ -1562,8 +1351,7 @@ public class ConfigurationImpl implements Configuration, Serializable return false; if (securityInvalidationInterval != other.securityInvalidationInterval) return false; - if (securitySettings == null) - { + if (securitySettings == null) { if (other.securitySettings != null) return false; } @@ -1587,14 +1375,11 @@ public class ConfigurationImpl implements Configuration, Serializable } @Override - public Configuration copy() throws Exception - { + public Configuration copy() throws Exception { - return AccessController.doPrivileged(new PrivilegedExceptionAction() - { + return AccessController.doPrivileged(new PrivilegedExceptionAction() { @Override - public Configuration run() throws Exception - { + public Configuration run() throws Exception { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream os = new ObjectOutputStream(bos); os.writeObject(ConfigurationImpl.this); @@ -1614,27 +1399,23 @@ public class ConfigurationImpl implements Configuration, Serializable } @Override - public ConfigurationImpl setJournalLockAcquisitionTimeout(long journalLockAcquisitionTimeout) - { + public ConfigurationImpl setJournalLockAcquisitionTimeout(long journalLockAcquisitionTimeout) { this.journalLockAcquisitionTimeout = journalLockAcquisitionTimeout; return this; } @Override - public long getJournalLockAcquisitionTimeout() - { + public long getJournalLockAcquisitionTimeout() { return journalLockAcquisitionTimeout; } @Override - public HAPolicyConfiguration getHAPolicyConfiguration() - { + public HAPolicyConfiguration getHAPolicyConfiguration() { return haPolicyConfiguration; } @Override - public ConfigurationImpl setHAPolicyConfiguration(HAPolicyConfiguration haPolicyConfiguration) - { + public ConfigurationImpl setHAPolicyConfiguration(HAPolicyConfiguration haPolicyConfiguration) { this.haPolicyConfiguration = haPolicyConfiguration; return this; } @@ -1642,17 +1423,14 @@ public class ConfigurationImpl implements Configuration, Serializable /** * It will find the right location of a subFolder, related to artemisInstance */ - private File subFolder(String subFolder) - { - try - { + private File subFolder(String subFolder) { + try { // Resolve wont work without "/" as the last character URI artemisHome = new URI(getBrokerInstance().toURI() + "/"); URI relative = artemisHome.resolve(subFolder); return new File(relative.getPath()); } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/impl/FileConfiguration.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/impl/FileConfiguration.java index 4eb10d2a7c..e0d9d4467b 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/impl/FileConfiguration.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/impl/FileConfiguration.java @@ -30,8 +30,8 @@ import javax.management.MBeanServer; /** * A {@code FileConfiguration} reads configuration values from a file. */ -public final class FileConfiguration extends ConfigurationImpl implements Deployable -{ +public final class FileConfiguration extends ConfigurationImpl implements Deployable { + private static final long serialVersionUID = -4766689627675039596L; private static final String CONFIGURATION_SCHEMA_URL = "schema/artemis-configuration.xsd"; @@ -44,8 +44,7 @@ public final class FileConfiguration extends ConfigurationImpl implements Deploy private boolean parsed = false; @Override - public void parse(Element config) throws Exception - { + public void parse(Element config) throws Exception { FileConfigurationParser parser = new FileConfigurationParser(); // https://jira.jboss.org/browse/HORNETQ-478 - We only want to validate AIO when @@ -59,26 +58,25 @@ public final class FileConfiguration extends ConfigurationImpl implements Deploy } @Override - public boolean isParsed() - { + public boolean isParsed() { return parsed; } @Override - public String getRootElement() - { + public String getRootElement() { return CONFIGURATION_SCHEMA_ROOT_ELEMENT; } @Override - public void buildService(ActiveMQSecurityManager securityManager, MBeanServer mBeanServer, Map deployables, Map components) - { + public void buildService(ActiveMQSecurityManager securityManager, + MBeanServer mBeanServer, + Map deployables, + Map components) { components.put(getRootElement(), new ActiveMQServerImpl(this, mBeanServer, securityManager)); } @Override - public String getSchema() - { + public String getSchema() { return CONFIGURATION_SCHEMA_URL; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/impl/FileSecurityConfiguration.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/impl/FileSecurityConfiguration.java index 2808e1a866..0dce1da208 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/impl/FileSecurityConfiguration.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/impl/FileSecurityConfiguration.java @@ -24,8 +24,8 @@ import org.apache.activemq.artemis.core.server.ActiveMQServerLogger; import org.apache.activemq.artemis.utils.PasswordMaskingUtil; import org.apache.activemq.artemis.utils.SensitiveDataCodec; -public class FileSecurityConfiguration extends SecurityConfiguration -{ +public class FileSecurityConfiguration extends SecurityConfiguration { + private final String usersUrl; private final String rolesUrl; @@ -36,8 +36,11 @@ public class FileSecurityConfiguration extends SecurityConfiguration private boolean started; - public FileSecurityConfiguration(String usersUrl, String rolesUrl, String defaultUser, Boolean maskPassword, String passwordCodec) - { + public FileSecurityConfiguration(String usersUrl, + String rolesUrl, + String defaultUser, + Boolean maskPassword, + String passwordCodec) { this.usersUrl = usersUrl; this.rolesUrl = rolesUrl; this.defaultUser = defaultUser; @@ -45,8 +48,7 @@ public class FileSecurityConfiguration extends SecurityConfiguration this.passwordCodec = passwordCodec; } - public void stop() throws Exception - { + public void stop() throws Exception { users.clear(); roles.clear(); @@ -54,34 +56,26 @@ public class FileSecurityConfiguration extends SecurityConfiguration defaultUser = null; } - public boolean isStarted() - { + public boolean isStarted() { return true; } - - public synchronized void start() throws Exception - { - if (started) - { + public synchronized void start() throws Exception { + if (started) { return; } SensitiveDataCodec codec = null; - if (maskPassword) - { - if (passwordCodec != null) - { + if (maskPassword) { + if (passwordCodec != null) { codec = PasswordMaskingUtil.getDefaultCodec(); } - else - { + else { codec = PasswordMaskingUtil.getCodec(passwordCodec); } } URL theUsersUrl = getClass().getClassLoader().getResource(usersUrl); - if (theUsersUrl == null) - { + if (theUsersUrl == null) { // The URL is outside of the classloader. Trying a pure url now theUsersUrl = new URL(usersUrl); } @@ -89,8 +83,7 @@ public class FileSecurityConfiguration extends SecurityConfiguration userProps.load(theUsersUrl.openStream()); URL theRolesUrl = getClass().getClassLoader().getResource(usersUrl); - if (theRolesUrl == null) - { + if (theRolesUrl == null) { // The URL is outside of the classloader. Trying a pure url now theRolesUrl = new URL(rolesUrl); } @@ -99,28 +92,22 @@ public class FileSecurityConfiguration extends SecurityConfiguration Set keys = userProps.stringPropertyNames(); - for (String username : keys) - { + for (String username : keys) { String password = userProps.getProperty(username); - if (codec != null) - { + if (codec != null) { password = codec.decode(password); } addUser(username, password); } - for (String username : keys) - { + for (String username : keys) { String roles = roleProps.getProperty(username); - if (roles == null) - { + if (roles == null) { ActiveMQServerLogger.LOGGER.cannotFindRoleForUser(username); } - else - { + else { String[] split = roles.split(","); - for (String role : split) - { + for (String role : split) { addRole(username, role.trim()); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/impl/SecurityConfiguration.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/impl/SecurityConfiguration.java index bd80e43928..afbbe5e2ef 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/impl/SecurityConfiguration.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/impl/SecurityConfiguration.java @@ -25,8 +25,9 @@ import java.util.Iterator; import java.util.List; import java.util.Map; -public class SecurityConfiguration -{ /** +public class SecurityConfiguration { + + /** * the current valid users */ protected final Map users = new HashMap(); @@ -38,61 +39,48 @@ public class SecurityConfiguration */ protected final Map> roles = new HashMap>(); - public SecurityConfiguration() - { + public SecurityConfiguration() { } - public SecurityConfiguration(Map users, Map> roles) - { + public SecurityConfiguration(Map users, Map> roles) { Iterator> iter = users.entrySet().iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { Map.Entry entry = iter.next(); addUser(entry.getKey(), entry.getValue()); } Iterator>> iter1 = roles.entrySet().iterator(); - while (iter1.hasNext()) - { + while (iter1.hasNext()) { Map.Entry> entry = iter1.next(); - for (String role : entry.getValue()) - { + for (String role : entry.getValue()) { addRole(entry.getKey(), role); } } } - public void addUser(final String user, final String password) - { - if (user == null) - { + public void addUser(final String user, final String password) { + if (user == null) { throw ActiveMQMessageBundle.BUNDLE.nullUser(); } - if (password == null) - { + if (password == null) { throw ActiveMQMessageBundle.BUNDLE.nullPassword(); } users.put(user, new User(user, password)); } - public void removeUser(final String user) - { + public void removeUser(final String user) { users.remove(user); roles.remove(user); } - public void addRole(final String user, final String role) - { - if (roles.get(user) == null) - { + public void addRole(final String user, final String role) { + if (roles.get(user) == null) { roles.put(user, new ArrayList()); } roles.get(user).add(role); } - public void removeRole(final String user, final String role) - { - if (roles.get(user) == null) - { + public void removeRole(final String user, final String role) { + if (roles.get(user) == null) { return; } roles.get(user).remove(role); @@ -101,23 +89,19 @@ public class SecurityConfiguration /* * set the default user for null users */ - public void setDefaultUser(final String username) - { + public void setDefaultUser(final String username) { defaultUser = username; } - public String getDefaultUser() - { + public String getDefaultUser() { return defaultUser; } - public org.apache.activemq.artemis.core.security.User getUser(String username) - { + public org.apache.activemq.artemis.core.security.User getUser(String username) { return users.get(username); } - public List getRole(String username) - { + public List getRole(String username) { return roles.get(username); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/impl/Validators.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/impl/Validators.java index 97c2d4b712..72085c31b1 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/impl/Validators.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/config/impl/Validators.java @@ -25,174 +25,133 @@ import org.apache.activemq.artemis.core.settings.impl.SlowConsumerPolicy; /** * A Validators. */ -public final class Validators -{ - public interface Validator - { +public final class Validators { + + public interface Validator { + void validate(String name, Object value); } - public static final Validator NO_CHECK = new Validator() - { - public void validate(final String name, final Object value) - { + public static final Validator NO_CHECK = new Validator() { + public void validate(final String name, final Object value) { return; } }; - public static final Validator NOT_NULL_OR_EMPTY = new Validator() - { - public void validate(final String name, final Object value) - { + public static final Validator NOT_NULL_OR_EMPTY = new Validator() { + public void validate(final String name, final Object value) { String str = (String) value; - if (str == null || str.length() == 0) - { + if (str == null || str.length() == 0) { throw ActiveMQMessageBundle.BUNDLE.emptyOrNull(name); } } }; - public static final Validator GT_ZERO = new Validator() - { - public void validate(final String name, final Object value) - { + public static final Validator GT_ZERO = new Validator() { + public void validate(final String name, final Object value) { Number val = (Number) value; - if (val.doubleValue() > 0) - { + if (val.doubleValue() > 0) { // OK } - else - { + else { throw ActiveMQMessageBundle.BUNDLE.greaterThanZero(name, val); } } }; - public static final Validator PERCENTAGE = new Validator() - { - public void validate(final String name, final Object value) - { + public static final Validator PERCENTAGE = new Validator() { + public void validate(final String name, final Object value) { Number val = (Number) value; - if (val == null || (val.intValue() < 0 || val.intValue() > 100)) - { + if (val == null || (val.intValue() < 0 || val.intValue() > 100)) { throw ActiveMQMessageBundle.BUNDLE.notPercent(name, val); } } }; - public static final Validator GE_ZERO = new Validator() - { - public void validate(final String name, final Object value) - { + public static final Validator GE_ZERO = new Validator() { + public void validate(final String name, final Object value) { Number val = (Number) value; - if (val.doubleValue() >= 0) - { + if (val.doubleValue() >= 0) { // OK } - else - { + else { throw ActiveMQMessageBundle.BUNDLE.greaterThanZero(name, val); } } }; - public static final Validator MINUS_ONE_OR_GT_ZERO = new Validator() - { - public void validate(final String name, final Object value) - { + public static final Validator MINUS_ONE_OR_GT_ZERO = new Validator() { + public void validate(final String name, final Object value) { Number val = (Number) value; - if (val.doubleValue() == -1 || val.doubleValue() > 0) - { + if (val.doubleValue() == -1 || val.doubleValue() > 0) { // OK } - else - { + else { throw ActiveMQMessageBundle.BUNDLE.greaterThanMinusOne(name, val); } } }; - public static final Validator MINUS_ONE_OR_GE_ZERO = new Validator() - { - public void validate(final String name, final Object value) - { + public static final Validator MINUS_ONE_OR_GE_ZERO = new Validator() { + public void validate(final String name, final Object value) { Number val = (Number) value; - if (val.doubleValue() == -1 || val.doubleValue() >= 0) - { + if (val.doubleValue() == -1 || val.doubleValue() >= 0) { // OK } - else - { + else { throw ActiveMQMessageBundle.BUNDLE.greaterThanZeroOrMinusOne(name, val); } } }; - public static final Validator THREAD_PRIORITY_RANGE = new Validator() - { - public void validate(final String name, final Object value) - { + public static final Validator THREAD_PRIORITY_RANGE = new Validator() { + public void validate(final String name, final Object value) { Number val = (Number) value; - if (val.intValue() >= Thread.MIN_PRIORITY && val.intValue() <= Thread.MAX_PRIORITY) - { + if (val.intValue() >= Thread.MIN_PRIORITY && val.intValue() <= Thread.MAX_PRIORITY) { // OK } - else - { + else { throw ActiveMQMessageBundle.BUNDLE.mustbeBetween(name, Thread.MIN_PRIORITY, Thread.MAX_PRIORITY, value); } } }; - public static final Validator JOURNAL_TYPE = new Validator() - { - public void validate(final String name, final Object value) - { + public static final Validator JOURNAL_TYPE = new Validator() { + public void validate(final String name, final Object value) { String val = (String) value; - if (val == null || !val.equals(JournalType.NIO.toString()) && !val.equals(JournalType.ASYNCIO.toString())) - { + if (val == null || !val.equals(JournalType.NIO.toString()) && !val.equals(JournalType.ASYNCIO.toString())) { throw ActiveMQMessageBundle.BUNDLE.invalidJournalType(val); } } }; - public static final Validator ADDRESS_FULL_MESSAGE_POLICY_TYPE = new Validator() - { - public void validate(final String name, final Object value) - { + public static final Validator ADDRESS_FULL_MESSAGE_POLICY_TYPE = new Validator() { + public void validate(final String name, final Object value) { String val = (String) value; if (val == null || !val.equals(AddressFullMessagePolicy.PAGE.toString()) && - !val.equals(AddressFullMessagePolicy.DROP.toString()) && - !val.equals(AddressFullMessagePolicy.BLOCK.toString()) && - !val.equals(AddressFullMessagePolicy.FAIL.toString())) - { + !val.equals(AddressFullMessagePolicy.DROP.toString()) && + !val.equals(AddressFullMessagePolicy.BLOCK.toString()) && + !val.equals(AddressFullMessagePolicy.FAIL.toString())) { throw ActiveMQMessageBundle.BUNDLE.invalidAddressFullPolicyType(val); } } }; - public static final Validator SLOW_CONSUMER_POLICY_TYPE = new Validator() - { - public void validate(final String name, final Object value) - { + public static final Validator SLOW_CONSUMER_POLICY_TYPE = new Validator() { + public void validate(final String name, final Object value) { String val = (String) value; - if (val == null || !val.equals(SlowConsumerPolicy.KILL.toString()) && - !val.equals(SlowConsumerPolicy.NOTIFY.toString())) - { + if (val == null || !val.equals(SlowConsumerPolicy.KILL.toString()) && !val.equals(SlowConsumerPolicy.NOTIFY.toString())) { throw ActiveMQMessageBundle.BUNDLE.invalidSlowConsumerPolicyType(val); } } }; - public static final Validator MESSAGE_LOAD_BALANCING_TYPE = new Validator() - { - public void validate(final String name, final Object value) - { + public static final Validator MESSAGE_LOAD_BALANCING_TYPE = new Validator() { + public void validate(final String name, final Object value) { String val = (String) value; if (val == null || !val.equals(MessageLoadBalancingType.OFF.toString()) && - !val.equals(MessageLoadBalancingType.STRICT.toString()) && - !val.equals(MessageLoadBalancingType.ON_DEMAND.toString())) - { + !val.equals(MessageLoadBalancingType.STRICT.toString()) && + !val.equals(MessageLoadBalancingType.ON_DEMAND.toString())) { throw ActiveMQMessageBundle.BUNDLE.invalidMessageLoadBalancingType(val); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/deployers/Deployable.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/deployers/Deployable.java index cff2aa8706..7ab197e97d 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/deployers/Deployable.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/deployers/Deployable.java @@ -27,8 +27,8 @@ import java.util.Map; * A Deployable is an object that can be configured via an xml configuration element in the main configuration file "broker.xml" * It holds all the information needed by the FileDeploymentManager to parse the configuration and build the component */ -public interface Deployable -{ +public interface Deployable { + /* * parse the element from the xml configuration */ @@ -52,6 +52,9 @@ public interface Deployable /* * builds the service. The implementation should add a component to the components map passed in if it needs to. */ - void buildService(ActiveMQSecurityManager securityManager, MBeanServer mBeanServer, Map deployables, Map components) throws Exception; + void buildService(ActiveMQSecurityManager securityManager, + MBeanServer mBeanServer, + Map deployables, + Map components) throws Exception; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/deployers/impl/FileConfigurationParser.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/deployers/impl/FileConfigurationParser.java index 708b710cb8..7beeb23da6 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/deployers/impl/FileConfigurationParser.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/deployers/impl/FileConfigurationParser.java @@ -77,8 +77,8 @@ import java.util.Set; /** * Parses an XML document according to the {@literal artemis-configuration.xsd} schema. */ -public final class FileConfigurationParser extends XMLConfigurationUtil -{ +public final class FileConfigurationParser extends XMLConfigurationUtil { + // Security Parsing public static final String SECURITY_ELEMENT_NAME = "security-setting"; @@ -160,21 +160,18 @@ public final class FileConfigurationParser extends XMLConfigurationUtil /** * @return the validateAIO */ - public boolean isValidateAIO() - { + public boolean isValidateAIO() { return validateAIO; } /** * @param validateAIO the validateAIO to set */ - public void setValidateAIO(final boolean validateAIO) - { + public void setValidateAIO(final boolean validateAIO) { this.validateAIO = validateAIO; } - public Configuration parseMainConfig(final InputStream input) throws Exception - { + public Configuration parseMainConfig(final InputStream input) throws Exception { Reader reader = new InputStreamReader(input); String xml = XMLUtil.readerToString(reader); @@ -188,142 +185,93 @@ public final class FileConfigurationParser extends XMLConfigurationUtil return config; } - public void parseMainConfig(final Element e, final Configuration config) throws Exception - { + public void parseMainConfig(final Element e, final Configuration config) throws Exception { config.setName(getString(e, "name", config.getName(), Validators.NO_CHECK)); NodeList haPolicyNodes = e.getElementsByTagName("ha-policy"); - if (haPolicyNodes.getLength() > 0) - { + if (haPolicyNodes.getLength() > 0) { parseHAPolicyConfiguration((Element) haPolicyNodes.item(0), config); } //if we aren already set then set to default - if (config.getHAPolicyConfiguration() == null) - { + if (config.getHAPolicyConfiguration() == null) { config.setHAPolicyConfiguration(new LiveOnlyPolicyConfiguration()); } - config.setResolveProtocols(getBoolean(e, "resolve-protocols", config.isResolveProtocols())); - config.setPersistenceEnabled(getBoolean(e, "persistence-enabled", - config.isPersistenceEnabled())); + config.setPersistenceEnabled(getBoolean(e, "persistence-enabled", config.isPersistenceEnabled())); - config.setPersistDeliveryCountBeforeDelivery(getBoolean(e, "persist-delivery-count-before-delivery", - config.isPersistDeliveryCountBeforeDelivery())); + config.setPersistDeliveryCountBeforeDelivery(getBoolean(e, "persist-delivery-count-before-delivery", config.isPersistDeliveryCountBeforeDelivery())); - config.setScheduledThreadPoolMaxSize(getInteger(e, "scheduled-thread-pool-max-size", - config.getScheduledThreadPoolMaxSize(), Validators.GT_ZERO)); + config.setScheduledThreadPoolMaxSize(getInteger(e, "scheduled-thread-pool-max-size", config.getScheduledThreadPoolMaxSize(), Validators.GT_ZERO)); - config.setThreadPoolMaxSize(getInteger(e, "thread-pool-max-size", config.getThreadPoolMaxSize(), - Validators.MINUS_ONE_OR_GT_ZERO)); + config.setThreadPoolMaxSize(getInteger(e, "thread-pool-max-size", config.getThreadPoolMaxSize(), Validators.MINUS_ONE_OR_GT_ZERO)); config.setSecurityEnabled(getBoolean(e, "security-enabled", config.isSecurityEnabled())); config.setGracefulShutdownEnabled(getBoolean(e, "graceful-shutdown-enabled", config.isGracefulShutdownEnabled())); - config.setGracefulShutdownTimeout(getLong(e, "graceful-shutdown-timeout", - config.getGracefulShutdownTimeout(), Validators.MINUS_ONE_OR_GE_ZERO)); + config.setGracefulShutdownTimeout(getLong(e, "graceful-shutdown-timeout", config.getGracefulShutdownTimeout(), Validators.MINUS_ONE_OR_GE_ZERO)); config.setJMXManagementEnabled(getBoolean(e, "jmx-management-enabled", config.isJMXManagementEnabled())); config.setJMXDomain(getString(e, "jmx-domain", config.getJMXDomain(), Validators.NOT_NULL_OR_EMPTY)); - config.setSecurityInvalidationInterval(getLong(e, "security-invalidation-interval", - config.getSecurityInvalidationInterval(), - Validators.GT_ZERO)); + config.setSecurityInvalidationInterval(getLong(e, "security-invalidation-interval", config.getSecurityInvalidationInterval(), Validators.GT_ZERO)); - config.setConnectionTTLOverride(getLong(e, - "connection-ttl-override", - config.getConnectionTTLOverride(), - Validators.MINUS_ONE_OR_GT_ZERO)); + config.setConnectionTTLOverride(getLong(e, "connection-ttl-override", config.getConnectionTTLOverride(), Validators.MINUS_ONE_OR_GT_ZERO)); - config.setEnabledAsyncConnectionExecution(getBoolean(e, - "async-connection-execution-enabled", - config.isAsyncConnectionExecutionEnabled())); + config.setEnabledAsyncConnectionExecution(getBoolean(e, "async-connection-execution-enabled", config.isAsyncConnectionExecutionEnabled())); - config.setTransactionTimeout(getLong(e, - "transaction-timeout", - config.getTransactionTimeout(), - Validators.GT_ZERO)); + config.setTransactionTimeout(getLong(e, "transaction-timeout", config.getTransactionTimeout(), Validators.GT_ZERO)); - config.setTransactionTimeoutScanPeriod(getLong(e, - "transaction-timeout-scan-period", - config.getTransactionTimeoutScanPeriod(), - Validators.GT_ZERO)); + config.setTransactionTimeoutScanPeriod(getLong(e, "transaction-timeout-scan-period", config.getTransactionTimeoutScanPeriod(), Validators.GT_ZERO)); - config.setMessageExpiryScanPeriod(getLong(e, - "message-expiry-scan-period", - config.getMessageExpiryScanPeriod(), - Validators.MINUS_ONE_OR_GT_ZERO)); + config.setMessageExpiryScanPeriod(getLong(e, "message-expiry-scan-period", config.getMessageExpiryScanPeriod(), Validators.MINUS_ONE_OR_GT_ZERO)); - config.setMessageExpiryThreadPriority(getInteger(e, - "message-expiry-thread-priority", - config.getMessageExpiryThreadPriority(), - Validators.THREAD_PRIORITY_RANGE)); + config.setMessageExpiryThreadPriority(getInteger(e, "message-expiry-thread-priority", config.getMessageExpiryThreadPriority(), Validators.THREAD_PRIORITY_RANGE)); - config.setIDCacheSize(getInteger(e, - "id-cache-size", - config.getIDCacheSize(), - Validators.GT_ZERO)); + config.setIDCacheSize(getInteger(e, "id-cache-size", config.getIDCacheSize(), Validators.GT_ZERO)); config.setPersistIDCache(getBoolean(e, "persist-id-cache", config.isPersistIDCache())); - config.setManagementAddress(new SimpleString(getString(e, - "management-address", - config.getManagementAddress() - .toString(), - Validators.NOT_NULL_OR_EMPTY))); + config.setManagementAddress(new SimpleString(getString(e, "management-address", config.getManagementAddress().toString(), Validators.NOT_NULL_OR_EMPTY))); - config.setManagementNotificationAddress(new SimpleString(getString(e, - "management-notification-address", - config.getManagementNotificationAddress() - .toString(), - Validators.NOT_NULL_OR_EMPTY))); + config.setManagementNotificationAddress(new SimpleString(getString(e, "management-notification-address", config.getManagementNotificationAddress().toString(), Validators.NOT_NULL_OR_EMPTY))); config.setMaskPassword(getBoolean(e, "mask-password", false)); - config.setPasswordCodec(getString(e, "password-codec", DefaultSensitiveStringCodec.class.getName(), - Validators.NOT_NULL_OR_EMPTY)); + config.setPasswordCodec(getString(e, "password-codec", DefaultSensitiveStringCodec.class.getName(), Validators.NOT_NULL_OR_EMPTY)); // parsing cluster password String passwordText = getString(e, "cluster-password", null, Validators.NO_CHECK); final boolean maskText = config.isMaskPassword(); - if (passwordText != null) - { - if (maskText) - { + if (passwordText != null) { + if (maskText) { SensitiveDataCodec codec = PasswordMaskingUtil.getCodec(config.getPasswordCodec()); config.setClusterPassword(codec.decode(passwordText)); } - else - { + else { config.setClusterPassword(passwordText); } } - config.setClusterUser(getString(e, - "cluster-user", - config.getClusterUser(), - Validators.NO_CHECK)); + config.setClusterUser(getString(e, "cluster-user", config.getClusterUser(), Validators.NO_CHECK)); NodeList interceptorNodes = e.getElementsByTagName("remoting-interceptors"); ArrayList incomingInterceptorList = new ArrayList(); - if (interceptorNodes.getLength() > 0) - { + if (interceptorNodes.getLength() > 0) { NodeList interceptors = interceptorNodes.item(0).getChildNodes(); - for (int i = 0; i < interceptors.getLength(); i++) - { - if ("class-name".equalsIgnoreCase(interceptors.item(i).getNodeName())) - { + for (int i = 0; i < interceptors.getLength(); i++) { + if ("class-name".equalsIgnoreCase(interceptors.item(i).getNodeName())) { String clazz = getTrimmedTextContent(interceptors.item(i)); incomingInterceptorList.add(clazz); @@ -333,14 +281,11 @@ public final class FileConfigurationParser extends XMLConfigurationUtil NodeList incomingInterceptorNodes = e.getElementsByTagName("remoting-incoming-interceptors"); - if (incomingInterceptorNodes.getLength() > 0) - { + if (incomingInterceptorNodes.getLength() > 0) { NodeList interceptors = incomingInterceptorNodes.item(0).getChildNodes(); - for (int i = 0; i < interceptors.getLength(); i++) - { - if ("class-name".equalsIgnoreCase(interceptors.item(i).getNodeName())) - { + for (int i = 0; i < interceptors.getLength(); i++) { + if ("class-name".equalsIgnoreCase(interceptors.item(i).getNodeName())) { String clazz = getTrimmedTextContent(interceptors.item(i)); incomingInterceptorList.add(clazz); @@ -354,14 +299,11 @@ public final class FileConfigurationParser extends XMLConfigurationUtil ArrayList outgoingInterceptorList = new ArrayList(); - if (outgoingInterceptorNodes.getLength() > 0) - { + if (outgoingInterceptorNodes.getLength() > 0) { NodeList interceptors = outgoingInterceptorNodes.item(0).getChildNodes(); - for (int i = 0; i < interceptors.getLength(); i++) - { - if ("class-name".equalsIgnoreCase(interceptors.item(i).getNodeName())) - { + for (int i = 0; i < interceptors.getLength(); i++) { + if ("class-name".equalsIgnoreCase(interceptors.item(i).getNodeName())) { String clazz = interceptors.item(i).getTextContent(); outgoingInterceptorList.add(clazz); @@ -373,21 +315,18 @@ public final class FileConfigurationParser extends XMLConfigurationUtil NodeList connectorNodes = e.getElementsByTagName("connector"); - for (int i = 0; i < connectorNodes.getLength(); i++) - { + for (int i = 0; i < connectorNodes.getLength(); i++) { Element connectorNode = (Element) connectorNodes.item(i); TransportConfiguration connectorConfig = parseConnectorTransportConfiguration(connectorNode, config); - if (connectorConfig.getName() == null) - { + if (connectorConfig.getName() == null) { ActiveMQServerLogger.LOGGER.connectorWithNoName(); continue; } - if (config.getConnectorConfigurations().containsKey(connectorConfig.getName())) - { + if (config.getConnectorConfigurations().containsKey(connectorConfig.getName())) { ActiveMQServerLogger.LOGGER.connectorAlreadyDeployed(connectorConfig.getName()); continue; @@ -398,8 +337,7 @@ public final class FileConfigurationParser extends XMLConfigurationUtil NodeList acceptorNodes = e.getElementsByTagName("acceptor"); - for (int i = 0; i < acceptorNodes.getLength(); i++) - { + for (int i = 0; i < acceptorNodes.getLength(); i++) { Element acceptorNode = (Element) acceptorNodes.item(i); TransportConfiguration acceptorConfig = parseAcceptorTransportConfiguration(acceptorNode, config); @@ -409,8 +347,7 @@ public final class FileConfigurationParser extends XMLConfigurationUtil NodeList bgNodes = e.getElementsByTagName("broadcast-group"); - for (int i = 0; i < bgNodes.getLength(); i++) - { + for (int i = 0; i < bgNodes.getLength(); i++) { Element bgNode = (Element) bgNodes.item(i); parseBroadcastGroupConfiguration(bgNode, config); @@ -418,8 +355,7 @@ public final class FileConfigurationParser extends XMLConfigurationUtil NodeList dgNodes = e.getElementsByTagName("discovery-group"); - for (int i = 0; i < dgNodes.getLength(); i++) - { + for (int i = 0; i < dgNodes.getLength(); i++) { Element dgNode = (Element) dgNodes.item(i); parseDiscoveryGroupConfiguration(dgNode, config); @@ -427,8 +363,7 @@ public final class FileConfigurationParser extends XMLConfigurationUtil NodeList brNodes = e.getElementsByTagName("bridge"); - for (int i = 0; i < brNodes.getLength(); i++) - { + for (int i = 0; i < brNodes.getLength(); i++) { Element mfNode = (Element) brNodes.item(i); parseBridgeConfiguration(mfNode, config); @@ -436,8 +371,7 @@ public final class FileConfigurationParser extends XMLConfigurationUtil NodeList gaNodes = e.getElementsByTagName("grouping-handler"); - for (int i = 0; i < gaNodes.getLength(); i++) - { + for (int i = 0; i < gaNodes.getLength(); i++) { Element gaNode = (Element) gaNodes.item(i); parseGroupingHandlerConfiguration(gaNode, config); @@ -445,8 +379,7 @@ public final class FileConfigurationParser extends XMLConfigurationUtil NodeList ccNodes = e.getElementsByTagName("cluster-connection"); - for (int i = 0; i < ccNodes.getLength(); i++) - { + for (int i = 0; i < ccNodes.getLength(); i++) { Element ccNode = (Element) ccNodes.item(i); parseClusterConnectionConfiguration(ccNode, config); @@ -454,8 +387,7 @@ public final class FileConfigurationParser extends XMLConfigurationUtil NodeList dvNodes = e.getElementsByTagName("divert"); - for (int i = 0; i < dvNodes.getLength(); i++) - { + for (int i = 0; i < dvNodes.getLength(); i++) { Element dvNode = (Element) dvNodes.item(i); parseDivertConfiguration(dvNode, config); @@ -463,61 +395,37 @@ public final class FileConfigurationParser extends XMLConfigurationUtil // Persistence config - config.setLargeMessagesDirectory(getString(e, - "large-messages-directory", - config.getLargeMessagesDirectory(), - Validators.NOT_NULL_OR_EMPTY)); + config.setLargeMessagesDirectory(getString(e, "large-messages-directory", config.getLargeMessagesDirectory(), Validators.NOT_NULL_OR_EMPTY)); - config.setBindingsDirectory(getString(e, - "bindings-directory", - config.getBindingsDirectory(), - Validators.NOT_NULL_OR_EMPTY)); + config.setBindingsDirectory(getString(e, "bindings-directory", config.getBindingsDirectory(), Validators.NOT_NULL_OR_EMPTY)); - config.setCreateBindingsDir(getBoolean(e, - "create-bindings-dir", - config.isCreateBindingsDir())); + config.setCreateBindingsDir(getBoolean(e, "create-bindings-dir", config.isCreateBindingsDir())); - config.setJournalDirectory(getString(e, "journal-directory", config.getJournalDirectory(), - Validators.NOT_NULL_OR_EMPTY)); + config.setJournalDirectory(getString(e, "journal-directory", config.getJournalDirectory(), Validators.NOT_NULL_OR_EMPTY)); + config.setPageMaxConcurrentIO(getInteger(e, "page-max-concurrent-io", config.getPageMaxConcurrentIO(), Validators.MINUS_ONE_OR_GT_ZERO)); - config.setPageMaxConcurrentIO(getInteger(e, - "page-max-concurrent-io", - config.getPageMaxConcurrentIO(), - Validators.MINUS_ONE_OR_GT_ZERO)); - - config.setPagingDirectory(getString(e, - "paging-directory", - config.getPagingDirectory(), - Validators.NOT_NULL_OR_EMPTY)); + config.setPagingDirectory(getString(e, "paging-directory", config.getPagingDirectory(), Validators.NOT_NULL_OR_EMPTY)); config.setCreateJournalDir(getBoolean(e, "create-journal-dir", config.isCreateJournalDir())); - String s = getString(e, - "journal-type", - config.getJournalType().toString(), - Validators.JOURNAL_TYPE); + String s = getString(e, "journal-type", config.getJournalType().toString(), Validators.JOURNAL_TYPE); - if (s.equals(JournalType.NIO.toString())) - { + if (s.equals(JournalType.NIO.toString())) { config.setJournalType(JournalType.NIO); } - else if (s.equals(JournalType.ASYNCIO.toString())) - { + else if (s.equals(JournalType.ASYNCIO.toString())) { // https://jira.jboss.org/jira/browse/HORNETQ-295 // We do the check here to see if AIO is supported so we can use the correct defaults and/or use // correct settings in xml // If we fall back later on these settings can be ignored boolean supportsAIO = AIOSequentialFileFactory.isSupported(); - if (supportsAIO) - { + if (supportsAIO) { config.setJournalType(JournalType.ASYNCIO); } - else - { - if (validateAIO) - { + else { + if (validateAIO) { ActiveMQServerLogger.LOGGER.AIONotFound(); } @@ -525,45 +433,24 @@ public final class FileConfigurationParser extends XMLConfigurationUtil } } - config.setJournalSyncTransactional(getBoolean(e, - "journal-sync-transactional", - config.isJournalSyncTransactional())); + config.setJournalSyncTransactional(getBoolean(e, "journal-sync-transactional", config.isJournalSyncTransactional())); - config.setJournalSyncNonTransactional(getBoolean(e, - "journal-sync-non-transactional", - config.isJournalSyncNonTransactional())); + config.setJournalSyncNonTransactional(getBoolean(e, "journal-sync-non-transactional", config.isJournalSyncNonTransactional())); - config.setJournalFileSize(getInteger(e, - "journal-file-size", - config.getJournalFileSize(), - Validators.GT_ZERO)); + config.setJournalFileSize(getInteger(e, "journal-file-size", config.getJournalFileSize(), Validators.GT_ZERO)); - int journalBufferTimeout = getInteger(e, - "journal-buffer-timeout", - config.getJournalType() == JournalType.ASYNCIO ? JournalConstants.DEFAULT_JOURNAL_BUFFER_TIMEOUT_AIO - : JournalConstants.DEFAULT_JOURNAL_BUFFER_TIMEOUT_NIO, - Validators.GT_ZERO); + int journalBufferTimeout = getInteger(e, "journal-buffer-timeout", config.getJournalType() == JournalType.ASYNCIO ? JournalConstants.DEFAULT_JOURNAL_BUFFER_TIMEOUT_AIO : JournalConstants.DEFAULT_JOURNAL_BUFFER_TIMEOUT_NIO, Validators.GT_ZERO); - int journalBufferSize = getInteger(e, - "journal-buffer-size", - config.getJournalType() == JournalType.ASYNCIO ? JournalConstants.DEFAULT_JOURNAL_BUFFER_SIZE_AIO - : JournalConstants.DEFAULT_JOURNAL_BUFFER_SIZE_NIO, - Validators.GT_ZERO); + int journalBufferSize = getInteger(e, "journal-buffer-size", config.getJournalType() == JournalType.ASYNCIO ? JournalConstants.DEFAULT_JOURNAL_BUFFER_SIZE_AIO : JournalConstants.DEFAULT_JOURNAL_BUFFER_SIZE_NIO, Validators.GT_ZERO); - int journalMaxIO = getInteger(e, - "journal-max-io", - config.getJournalType() == JournalType.ASYNCIO ? ActiveMQDefaultConfiguration.getDefaultJournalMaxIoAio() - : ActiveMQDefaultConfiguration.getDefaultJournalMaxIoNio(), - Validators.GT_ZERO); + int journalMaxIO = getInteger(e, "journal-max-io", config.getJournalType() == JournalType.ASYNCIO ? ActiveMQDefaultConfiguration.getDefaultJournalMaxIoAio() : ActiveMQDefaultConfiguration.getDefaultJournalMaxIoNio(), Validators.GT_ZERO); - if (config.getJournalType() == JournalType.ASYNCIO) - { + if (config.getJournalType() == JournalType.ASYNCIO) { config.setJournalBufferTimeout_AIO(journalBufferTimeout); config.setJournalBufferSize_AIO(journalBufferSize); config.setJournalMaxIO_AIO(journalMaxIO); } - else - { + else { config.setJournalBufferTimeout_NIO(journalBufferTimeout); config.setJournalBufferSize_NIO(journalBufferSize); config.setJournalMaxIO_NIO(journalMaxIO); @@ -571,22 +458,13 @@ public final class FileConfigurationParser extends XMLConfigurationUtil config.setJournalMinFiles(getInteger(e, "journal-min-files", config.getJournalMinFiles(), Validators.GT_ZERO)); - config.setJournalCompactMinFiles(getInteger(e, "journal-compact-min-files", config.getJournalCompactMinFiles(), - Validators.GE_ZERO)); + config.setJournalCompactMinFiles(getInteger(e, "journal-compact-min-files", config.getJournalCompactMinFiles(), Validators.GE_ZERO)); - config.setJournalCompactPercentage(getInteger(e, - "journal-compact-percentage", - config.getJournalCompactPercentage(), - Validators.PERCENTAGE)); + config.setJournalCompactPercentage(getInteger(e, "journal-compact-percentage", config.getJournalCompactPercentage(), Validators.PERCENTAGE)); - config.setLogJournalWriteRate(getBoolean(e, - "log-journal-write-rate", - ActiveMQDefaultConfiguration.isDefaultJournalLogWriteRate())); + config.setLogJournalWriteRate(getBoolean(e, "log-journal-write-rate", ActiveMQDefaultConfiguration.isDefaultJournalLogWriteRate())); - config.setJournalPerfBlastPages(getInteger(e, - "perf-blast-pages", - ActiveMQDefaultConfiguration.getDefaultJournalPerfBlastPages(), - Validators.MINUS_ONE_OR_GT_ZERO)); + config.setJournalPerfBlastPages(getInteger(e, "perf-blast-pages", ActiveMQDefaultConfiguration.getDefaultJournalPerfBlastPages(), Validators.MINUS_ONE_OR_GT_ZERO)); config.setRunSyncSpeedTest(getBoolean(e, "run-sync-speed-test", config.isRunSyncSpeedTest())); @@ -594,26 +472,15 @@ public final class FileConfigurationParser extends XMLConfigurationUtil config.setMessageCounterEnabled(getBoolean(e, "message-counter-enabled", config.isMessageCounterEnabled())); - config.setMessageCounterSamplePeriod(getLong(e, "message-counter-sample-period", - config.getMessageCounterSamplePeriod(), - Validators.GT_ZERO)); + config.setMessageCounterSamplePeriod(getLong(e, "message-counter-sample-period", config.getMessageCounterSamplePeriod(), Validators.GT_ZERO)); - config.setMessageCounterMaxDayHistory(getInteger(e, "message-counter-max-day-history", - config.getMessageCounterMaxDayHistory(), - Validators.GT_ZERO)); + config.setMessageCounterMaxDayHistory(getInteger(e, "message-counter-max-day-history", config.getMessageCounterMaxDayHistory(), Validators.GT_ZERO)); - config.setServerDumpInterval(getLong(e, "server-dump-interval", config.getServerDumpInterval(), - Validators.MINUS_ONE_OR_GT_ZERO)); // in milliseconds + config.setServerDumpInterval(getLong(e, "server-dump-interval", config.getServerDumpInterval(), Validators.MINUS_ONE_OR_GT_ZERO)); // in milliseconds - config.setMemoryWarningThreshold(getInteger(e, - "memory-warning-threshold", - config.getMemoryWarningThreshold(), - Validators.PERCENTAGE)); + config.setMemoryWarningThreshold(getInteger(e, "memory-warning-threshold", config.getMemoryWarningThreshold(), Validators.PERCENTAGE)); - config.setMemoryMeasureInterval(getLong(e, - "memory-measure-interval", - config.getMemoryMeasureInterval(), - Validators.MINUS_ONE_OR_GT_ZERO)); // in + config.setMemoryMeasureInterval(getLong(e, "memory-measure-interval", config.getMemoryMeasureInterval(), Validators.MINUS_ONE_OR_GT_ZERO)); // in parseAddressSettings(e, config); @@ -627,8 +494,7 @@ public final class FileConfigurationParser extends XMLConfigurationUtil ArrayList configs = new ArrayList(); - for (int i = 0; i < connectorServiceConfigs.getLength(); i++) - { + for (int i = 0; i < connectorServiceConfigs.getLength(); i++) { Element node = (Element) connectorServiceConfigs.item(i); configs.add((parseConnectorService(node))); @@ -641,16 +507,13 @@ public final class FileConfigurationParser extends XMLConfigurationUtil * @param e * @param config */ - private void parseSecurity(final Element e, final Configuration config) - { + private void parseSecurity(final Element e, final Configuration config) { NodeList elements = e.getElementsByTagName("security-settings"); - if (elements.getLength() != 0) - { + if (elements.getLength() != 0) { Element node = (Element) elements.item(0); NodeList list = node.getElementsByTagName(SECURITY_ELEMENT_NAME); - for (int i = 0; i < list.getLength(); i++) - { + for (int i = 0; i < list.getLength(); i++) { Pair> securityItem = parseSecurityRoles(list.item(i)); config.getSecurityRoles().put(securityItem.getA(), securityItem.getB()); } @@ -661,16 +524,13 @@ public final class FileConfigurationParser extends XMLConfigurationUtil * @param e * @param config */ - private void parseQueues(final Element e, final Configuration config) - { + private void parseQueues(final Element e, final Configuration config) { NodeList elements = e.getElementsByTagName("queues"); - if (elements.getLength() != 0) - { + if (elements.getLength() != 0) { Element node = (Element) elements.item(0); NodeList list = node.getElementsByTagName("queue"); - for (int i = 0; i < list.getLength(); i++) - { + for (int i = 0; i < list.getLength(); i++) { CoreQueueConfiguration queueConfig = parseQueueConfiguration(list.item(i)); config.getQueueConfigurations().add(queueConfig); } @@ -681,16 +541,13 @@ public final class FileConfigurationParser extends XMLConfigurationUtil * @param e * @param config */ - private void parseAddressSettings(final Element e, final Configuration config) - { + private void parseAddressSettings(final Element e, final Configuration config) { NodeList elements = e.getElementsByTagName("address-settings"); - if (elements.getLength() != 0) - { + if (elements.getLength() != 0) { Element node = (Element) elements.item(0); NodeList list = node.getElementsByTagName("address-setting"); - for (int i = 0; i < list.getLength(); i++) - { + for (int i = 0; i < list.getLength(); i++) { Pair addressSettings = parseAddressSettings(list.item(i)); config.getAddressesSettings().put(addressSettings.getA(), addressSettings.getB()); } @@ -701,16 +558,13 @@ public final class FileConfigurationParser extends XMLConfigurationUtil * @param e * @param config */ - private void parseResourceLimits(final Element e, final Configuration config) - { + private void parseResourceLimits(final Element e, final Configuration config) { NodeList elements = e.getElementsByTagName("resource-limit-settings"); - if (elements.getLength() != 0) - { + if (elements.getLength() != 0) { Element node = (Element) elements.item(0); NodeList list = node.getElementsByTagName("resource-limit-setting"); - for (int i = 0; i < list.getLength(); i++) - { + for (int i = 0; i < list.getLength(); i++) { config.addResourceLimitSettings(parseResourceLimitSettings(list.item(i))); } } @@ -720,8 +574,7 @@ public final class FileConfigurationParser extends XMLConfigurationUtil * @param node * @return */ - protected Pair> parseSecurityRoles(final Node node) - { + protected Pair> parseSecurityRoles(final Node node) { final String match = node.getAttributes().getNamedItem("match").getNodeValue(); HashSet securityRoles = new HashSet(); @@ -737,59 +590,45 @@ public final class FileConfigurationParser extends XMLConfigurationUtil ArrayList manageRoles = new ArrayList(); ArrayList allRoles = new ArrayList(); NodeList children = node.getChildNodes(); - for (int i = 0; i < children.getLength(); i++) - { + for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); final String name = child.getNodeName(); - if (PERMISSION_ELEMENT_NAME.equalsIgnoreCase(name)) - { + if (PERMISSION_ELEMENT_NAME.equalsIgnoreCase(name)) { final String type = getAttributeValue(child, TYPE_ATTR_NAME); final String roleString = getAttributeValue(child, ROLES_ATTR_NAME); String[] roles = roleString.split(","); - for (String role : roles) - { - if (SEND_NAME.equals(type)) - { + for (String role : roles) { + if (SEND_NAME.equals(type)) { send.add(role.trim()); } - else if (CONSUME_NAME.equals(type)) - { + else if (CONSUME_NAME.equals(type)) { consume.add(role.trim()); } - else if (CREATEDURABLEQUEUE_NAME.equals(type)) - { + else if (CREATEDURABLEQUEUE_NAME.equals(type)) { createDurableQueue.add(role.trim()); } - else if (DELETEDURABLEQUEUE_NAME.equals(type)) - { + else if (DELETEDURABLEQUEUE_NAME.equals(type)) { deleteDurableQueue.add(role.trim()); } - else if (CREATE_NON_DURABLE_QUEUE_NAME.equals(type)) - { + else if (CREATE_NON_DURABLE_QUEUE_NAME.equals(type)) { createNonDurableQueue.add(role.trim()); } - else if (DELETE_NON_DURABLE_QUEUE_NAME.equals(type)) - { + else if (DELETE_NON_DURABLE_QUEUE_NAME.equals(type)) { deleteNonDurableQueue.add(role.trim()); } - else if (CREATETEMPQUEUE_NAME.equals(type)) - { + else if (CREATETEMPQUEUE_NAME.equals(type)) { createNonDurableQueue.add(role.trim()); } - else if (DELETETEMPQUEUE_NAME.equals(type)) - { + else if (DELETETEMPQUEUE_NAME.equals(type)) { deleteNonDurableQueue.add(role.trim()); } - else if (MANAGE_NAME.equals(type)) - { + else if (MANAGE_NAME.equals(type)) { manageRoles.add(role.trim()); } - else - { + else { ActiveMQServerLogger.LOGGER.rolePermissionConfigurationError(type); } - if (!allRoles.contains(role.trim())) - { + if (!allRoles.contains(role.trim())) { allRoles.add(role.trim()); } } @@ -797,16 +636,8 @@ public final class FileConfigurationParser extends XMLConfigurationUtil } - for (String role : allRoles) - { - securityRoles.add(new Role(role, - send.contains(role), - consume.contains(role), - createDurableQueue.contains(role), - deleteDurableQueue.contains(role), - createNonDurableQueue.contains(role), - deleteNonDurableQueue.contains(role), - manageRoles.contains(role))); + for (String role : allRoles) { + securityRoles.add(new Role(role, send.contains(role), consume.contains(role), createDurableQueue.contains(role), deleteDurableQueue.contains(role), createNonDurableQueue.contains(role), deleteNonDurableQueue.contains(role), manageRoles.contains(role))); } return securityMatch; @@ -816,8 +647,7 @@ public final class FileConfigurationParser extends XMLConfigurationUtil * @param node * @return */ - protected Pair parseAddressSettings(final Node node) - { + protected Pair parseAddressSettings(final Node node) { String match = getAttributeValue(node, "match"); NodeList children = node.getChildNodes(); @@ -826,104 +656,81 @@ public final class FileConfigurationParser extends XMLConfigurationUtil Pair setting = new Pair(match, addressSettings); - for (int i = 0; i < children.getLength(); i++) - { + for (int i = 0; i < children.getLength(); i++) { final Node child = children.item(i); final String name = child.getNodeName(); - if (DEAD_LETTER_ADDRESS_NODE_NAME.equalsIgnoreCase(name)) - { + if (DEAD_LETTER_ADDRESS_NODE_NAME.equalsIgnoreCase(name)) { SimpleString queueName = new SimpleString(getTrimmedTextContent(child)); addressSettings.setDeadLetterAddress(queueName); } - else if (EXPIRY_ADDRESS_NODE_NAME.equalsIgnoreCase(name)) - { + else if (EXPIRY_ADDRESS_NODE_NAME.equalsIgnoreCase(name)) { SimpleString queueName = new SimpleString(getTrimmedTextContent(child)); addressSettings.setExpiryAddress(queueName); } - else if (EXPIRY_DELAY_NODE_NAME.equalsIgnoreCase(name)) - { + else if (EXPIRY_DELAY_NODE_NAME.equalsIgnoreCase(name)) { addressSettings.setExpiryDelay(XMLUtil.parseLong(child)); } - else if (REDELIVERY_DELAY_NODE_NAME.equalsIgnoreCase(name)) - { + else if (REDELIVERY_DELAY_NODE_NAME.equalsIgnoreCase(name)) { addressSettings.setRedeliveryDelay(XMLUtil.parseLong(child)); } - else if (REDELIVERY_DELAY_MULTIPLIER_NODE_NAME.equalsIgnoreCase(name)) - { + else if (REDELIVERY_DELAY_MULTIPLIER_NODE_NAME.equalsIgnoreCase(name)) { addressSettings.setRedeliveryMultiplier(XMLUtil.parseDouble(child)); } - else if (MAX_REDELIVERY_DELAY_NODE_NAME.equalsIgnoreCase(name)) - { + else if (MAX_REDELIVERY_DELAY_NODE_NAME.equalsIgnoreCase(name)) { addressSettings.setMaxRedeliveryDelay(XMLUtil.parseLong(child)); } - else if (MAX_SIZE_BYTES_NODE_NAME.equalsIgnoreCase(name)) - { + else if (MAX_SIZE_BYTES_NODE_NAME.equalsIgnoreCase(name)) { addressSettings.setMaxSizeBytes(XMLUtil.parseLong(child)); } - else if (PAGE_SIZE_BYTES_NODE_NAME.equalsIgnoreCase(name)) - { + else if (PAGE_SIZE_BYTES_NODE_NAME.equalsIgnoreCase(name)) { addressSettings.setPageSizeBytes(XMLUtil.parseLong(child)); } - else if (PAGE_MAX_CACHE_SIZE_NODE_NAME.equalsIgnoreCase(name)) - { + else if (PAGE_MAX_CACHE_SIZE_NODE_NAME.equalsIgnoreCase(name)) { addressSettings.setPageCacheMaxSize(XMLUtil.parseInt(child)); } - else if (MESSAGE_COUNTER_HISTORY_DAY_LIMIT_NODE_NAME.equalsIgnoreCase(name)) - { + else if (MESSAGE_COUNTER_HISTORY_DAY_LIMIT_NODE_NAME.equalsIgnoreCase(name)) { addressSettings.setMessageCounterHistoryDayLimit(XMLUtil.parseInt(child)); } - else if (ADDRESS_FULL_MESSAGE_POLICY_NODE_NAME.equalsIgnoreCase(name)) - { + else if (ADDRESS_FULL_MESSAGE_POLICY_NODE_NAME.equalsIgnoreCase(name)) { String value = getTrimmedTextContent(child); - Validators.ADDRESS_FULL_MESSAGE_POLICY_TYPE.validate(ADDRESS_FULL_MESSAGE_POLICY_NODE_NAME, - value); + Validators.ADDRESS_FULL_MESSAGE_POLICY_TYPE.validate(ADDRESS_FULL_MESSAGE_POLICY_NODE_NAME, value); AddressFullMessagePolicy policy = Enum.valueOf(AddressFullMessagePolicy.class, value); addressSettings.setAddressFullMessagePolicy(policy); } - else if (LVQ_NODE_NAME.equalsIgnoreCase(name)) - { + else if (LVQ_NODE_NAME.equalsIgnoreCase(name)) { addressSettings.setLastValueQueue(XMLUtil.parseBoolean(child)); } - else if (MAX_DELIVERY_ATTEMPTS.equalsIgnoreCase(name)) - { + else if (MAX_DELIVERY_ATTEMPTS.equalsIgnoreCase(name)) { addressSettings.setMaxDeliveryAttempts(XMLUtil.parseInt(child)); } - else if (REDISTRIBUTION_DELAY_NODE_NAME.equalsIgnoreCase(name)) - { + else if (REDISTRIBUTION_DELAY_NODE_NAME.equalsIgnoreCase(name)) { addressSettings.setRedistributionDelay(XMLUtil.parseLong(child)); } - else if (SEND_TO_DLA_ON_NO_ROUTE.equalsIgnoreCase(name)) - { + else if (SEND_TO_DLA_ON_NO_ROUTE.equalsIgnoreCase(name)) { addressSettings.setSendToDLAOnNoRoute(XMLUtil.parseBoolean(child)); } - else if (SLOW_CONSUMER_THRESHOLD_NODE_NAME.equalsIgnoreCase(name)) - { + else if (SLOW_CONSUMER_THRESHOLD_NODE_NAME.equalsIgnoreCase(name)) { long slowConsumerThreshold = XMLUtil.parseLong(child); Validators.MINUS_ONE_OR_GT_ZERO.validate(SLOW_CONSUMER_THRESHOLD_NODE_NAME, slowConsumerThreshold); addressSettings.setSlowConsumerThreshold(slowConsumerThreshold); } - else if (SLOW_CONSUMER_CHECK_PERIOD_NODE_NAME.equalsIgnoreCase(name)) - { + else if (SLOW_CONSUMER_CHECK_PERIOD_NODE_NAME.equalsIgnoreCase(name)) { long slowConsumerCheckPeriod = XMLUtil.parseLong(child); Validators.GT_ZERO.validate(SLOW_CONSUMER_CHECK_PERIOD_NODE_NAME, slowConsumerCheckPeriod); addressSettings.setSlowConsumerCheckPeriod(slowConsumerCheckPeriod); } - else if (SLOW_CONSUMER_POLICY_NODE_NAME.equalsIgnoreCase(name)) - { + else if (SLOW_CONSUMER_POLICY_NODE_NAME.equalsIgnoreCase(name)) { String value = getTrimmedTextContent(child); - Validators.SLOW_CONSUMER_POLICY_TYPE.validate(SLOW_CONSUMER_POLICY_NODE_NAME, - value); + Validators.SLOW_CONSUMER_POLICY_TYPE.validate(SLOW_CONSUMER_POLICY_NODE_NAME, value); SlowConsumerPolicy policy = Enum.valueOf(SlowConsumerPolicy.class, value); addressSettings.setSlowConsumerPolicy(policy); } - else if (AUTO_CREATE_JMS_QUEUES.equalsIgnoreCase(name)) - { + else if (AUTO_CREATE_JMS_QUEUES.equalsIgnoreCase(name)) { addressSettings.setAutoCreateJmsQueues(XMLUtil.parseBoolean(child)); } - else if (AUTO_DELETE_JMS_QUEUES.equalsIgnoreCase(name)) - { + else if (AUTO_DELETE_JMS_QUEUES.equalsIgnoreCase(name)) { addressSettings.setAutoDeleteJmsQueues(XMLUtil.parseBoolean(child)); } } @@ -934,32 +741,27 @@ public final class FileConfigurationParser extends XMLConfigurationUtil * @param node * @return */ - protected ResourceLimitSettings parseResourceLimitSettings(final Node node) - { + protected ResourceLimitSettings parseResourceLimitSettings(final Node node) { ResourceLimitSettings resourceLimitSettings = new ResourceLimitSettings(); resourceLimitSettings.setMatch(SimpleString.toSimpleString(getAttributeValue(node, "match"))); NodeList children = node.getChildNodes(); - for (int i = 0; i < children.getLength(); i++) - { + for (int i = 0; i < children.getLength(); i++) { final Node child = children.item(i); final String name = child.getNodeName(); - if (MAX_CONNECTIONS_NODE_NAME.equalsIgnoreCase(name)) - { + if (MAX_CONNECTIONS_NODE_NAME.equalsIgnoreCase(name)) { resourceLimitSettings.setMaxConnections(XMLUtil.parseInt(child)); } - else if (MAX_QUEUES_NODE_NAME.equalsIgnoreCase(name)) - { + else if (MAX_QUEUES_NODE_NAME.equalsIgnoreCase(name)) { resourceLimitSettings.setMaxQueues(XMLUtil.parseInt(child)); } } return resourceLimitSettings; } - protected CoreQueueConfiguration parseQueueConfiguration(final Node node) - { + protected CoreQueueConfiguration parseQueueConfiguration(final Node node) { String name = getAttributeValue(node, "name"); String address = null; String filterString = null; @@ -967,33 +769,25 @@ public final class FileConfigurationParser extends XMLConfigurationUtil NodeList children = node.getChildNodes(); - for (int j = 0; j < children.getLength(); j++) - { + for (int j = 0; j < children.getLength(); j++) { Node child = children.item(j); - if (child.getNodeName().equals("address")) - { + if (child.getNodeName().equals("address")) { address = getTrimmedTextContent(child); } - else if (child.getNodeName().equals("filter")) - { + else if (child.getNodeName().equals("filter")) { filterString = getAttributeValue(child, "string"); } - else if (child.getNodeName().equals("durable")) - { + else if (child.getNodeName().equals("durable")) { durable = XMLUtil.parseBoolean(child); } } - return new CoreQueueConfiguration() - .setAddress(address) - .setName(name) - .setFilterString(filterString) - .setDurable(durable); + return new CoreQueueConfiguration().setAddress(address).setName(name).setFilterString(filterString).setDurable(durable); } - private TransportConfiguration parseAcceptorTransportConfiguration(final Element e, final Configuration mainConfig) throws Exception - { + private TransportConfiguration parseAcceptorTransportConfiguration(final Element e, + final Configuration mainConfig) throws Exception { Node nameNode = e.getAttributes().getNamedItem("name"); String name = nameNode != null ? nameNode.getNodeValue() : null; @@ -1006,12 +800,10 @@ public final class FileConfigurationParser extends XMLConfigurationUtil Map params = configurations.get(0).getParams(); - if (mainConfig.isMaskPassword()) - { + if (mainConfig.isMaskPassword()) { params.put(ActiveMQDefaultConfiguration.getPropMaskPassword(), mainConfig.isMaskPassword()); - if (mainConfig.getPasswordCodec() != null) - { + if (mainConfig.getPasswordCodec() != null) { params.put(ActiveMQDefaultConfiguration.getPropPasswordCodec(), mainConfig.getPasswordCodec()); } } @@ -1019,8 +811,8 @@ public final class FileConfigurationParser extends XMLConfigurationUtil return configurations.get(0); } - private TransportConfiguration parseConnectorTransportConfiguration(final Element e, final Configuration mainConfig) throws Exception - { + private TransportConfiguration parseConnectorTransportConfiguration(final Element e, + final Configuration mainConfig) throws Exception { Node nameNode = e.getAttributes().getNamedItem("name"); String name = nameNode != null ? nameNode.getNodeValue() : null; @@ -1033,12 +825,10 @@ public final class FileConfigurationParser extends XMLConfigurationUtil Map params = configurations.get(0).getParams(); - if (mainConfig.isMaskPassword()) - { + if (mainConfig.isMaskPassword()) { params.put(ActiveMQDefaultConfiguration.getPropMaskPassword(), mainConfig.isMaskPassword()); - if (mainConfig.getPasswordCodec() != null) - { + if (mainConfig.getPasswordCodec() != null) { params.put(ActiveMQDefaultConfiguration.getPropPasswordCodec(), mainConfig.getPasswordCodec()); } } @@ -1047,8 +837,8 @@ public final class FileConfigurationParser extends XMLConfigurationUtil } private static final ArrayList POLICY_LIST = new ArrayList<>(); - static - { + + static { POLICY_LIST.add("colocated"); POLICY_LIST.add("live-only"); POLICY_LIST.add("replicated"); @@ -1056,65 +846,55 @@ public final class FileConfigurationParser extends XMLConfigurationUtil POLICY_LIST.add("shared-store-master"); POLICY_LIST.add("shared-store-slave"); } + private static final ArrayList HA_LIST = new ArrayList<>(); - static - { + + static { HA_LIST.add("live-only"); HA_LIST.add("shared-store"); HA_LIST.add("replication"); } - private void parseHAPolicyConfiguration(final Element e, final Configuration mainConfig) - { - for (String haType : HA_LIST) - { + + private void parseHAPolicyConfiguration(final Element e, final Configuration mainConfig) { + for (String haType : HA_LIST) { NodeList haNodeList = e.getElementsByTagName(haType); - if (haNodeList.getLength() > 0) - { + if (haNodeList.getLength() > 0) { Element haNode = (Element) haNodeList.item(0); - if (haNode.getTagName().equals("replication")) - { + if (haNode.getTagName().equals("replication")) { NodeList masterNodeList = e.getElementsByTagName("master"); - if (masterNodeList.getLength() > 0) - { + if (masterNodeList.getLength() > 0) { Element masterNode = (Element) masterNodeList.item(0); mainConfig.setHAPolicyConfiguration(createReplicatedHaPolicy(masterNode)); } NodeList slaveNodeList = e.getElementsByTagName("slave"); - if (slaveNodeList.getLength() > 0) - { + if (slaveNodeList.getLength() > 0) { Element slaveNode = (Element) slaveNodeList.item(0); mainConfig.setHAPolicyConfiguration(createReplicaHaPolicy(slaveNode)); } NodeList colocatedNodeList = e.getElementsByTagName("colocated"); - if (colocatedNodeList.getLength() > 0) - { + if (colocatedNodeList.getLength() > 0) { Element colocatedNode = (Element) colocatedNodeList.item(0); mainConfig.setHAPolicyConfiguration(createColocatedHaPolicy(colocatedNode, true)); } } - else if (haNode.getTagName().equals("shared-store")) - { + else if (haNode.getTagName().equals("shared-store")) { NodeList masterNodeList = e.getElementsByTagName("master"); - if (masterNodeList.getLength() > 0) - { + if (masterNodeList.getLength() > 0) { Element masterNode = (Element) masterNodeList.item(0); mainConfig.setHAPolicyConfiguration(createSharedStoreMasterHaPolicy(masterNode)); } NodeList slaveNodeList = e.getElementsByTagName("slave"); - if (slaveNodeList.getLength() > 0) - { + if (slaveNodeList.getLength() > 0) { Element slaveNode = (Element) slaveNodeList.item(0); mainConfig.setHAPolicyConfiguration(createSharedStoreSlaveHaPolicy(slaveNode)); } NodeList colocatedNodeList = e.getElementsByTagName("colocated"); - if (colocatedNodeList.getLength() > 0) - { + if (colocatedNodeList.getLength() > 0) { Element colocatedNode = (Element) colocatedNodeList.item(0); mainConfig.setHAPolicyConfiguration(createColocatedHaPolicy(colocatedNode, false)); } } - else if (haNode.getTagName().equals("live-only")) - { + else if (haNode.getTagName().equals("live-only")) { NodeList noneNodeList = e.getElementsByTagName("live-only"); Element noneNode = (Element) noneNodeList.item(0); mainConfig.setHAPolicyConfiguration(createLiveOnlyHaPolicy(noneNode)); @@ -1123,8 +903,7 @@ public final class FileConfigurationParser extends XMLConfigurationUtil } } - private LiveOnlyPolicyConfiguration createLiveOnlyHaPolicy(Element policyNode) - { + private LiveOnlyPolicyConfiguration createLiveOnlyHaPolicy(Element policyNode) { LiveOnlyPolicyConfiguration configuration = new LiveOnlyPolicyConfiguration(); configuration.setScaleDownConfiguration(parseScaleDownConfig(policyNode)); @@ -1132,8 +911,7 @@ public final class FileConfigurationParser extends XMLConfigurationUtil return configuration; } - private ReplicatedPolicyConfiguration createReplicatedHaPolicy(Element policyNode) - { + private ReplicatedPolicyConfiguration createReplicatedHaPolicy(Element policyNode) { ReplicatedPolicyConfiguration configuration = new ReplicatedPolicyConfiguration(); configuration.setCheckForLiveServer(getBoolean(policyNode, "check-for-live-server", configuration.isCheckForLiveServer())); @@ -1145,8 +923,7 @@ public final class FileConfigurationParser extends XMLConfigurationUtil return configuration; } - private ReplicaPolicyConfiguration createReplicaHaPolicy(Element policyNode) - { + private ReplicaPolicyConfiguration createReplicaHaPolicy(Element policyNode) { ReplicaPolicyConfiguration configuration = new ReplicaPolicyConfiguration(); configuration.setRestartBackup(getBoolean(policyNode, "restart-backup", configuration.isRestartBackup())); @@ -1159,16 +936,14 @@ public final class FileConfigurationParser extends XMLConfigurationUtil configuration.setClusterName(getString(policyNode, "cluster-name", configuration.getClusterName(), Validators.NO_CHECK)); - configuration.setMaxSavedReplicatedJournalsSize(getInteger(policyNode, "max-saved-replicated-journals-size", - configuration.getMaxSavedReplicatedJournalsSize(), Validators.MINUS_ONE_OR_GE_ZERO)); + configuration.setMaxSavedReplicatedJournalsSize(getInteger(policyNode, "max-saved-replicated-journals-size", configuration.getMaxSavedReplicatedJournalsSize(), Validators.MINUS_ONE_OR_GE_ZERO)); configuration.setScaleDownConfiguration(parseScaleDownConfig(policyNode)); return configuration; } - private SharedStoreMasterPolicyConfiguration createSharedStoreMasterHaPolicy(Element policyNode) - { + private SharedStoreMasterPolicyConfiguration createSharedStoreMasterHaPolicy(Element policyNode) { SharedStoreMasterPolicyConfiguration configuration = new SharedStoreMasterPolicyConfiguration(); configuration.setFailoverOnServerShutdown(getBoolean(policyNode, "failover-on-shutdown", configuration.isFailoverOnServerShutdown())); @@ -1178,8 +953,7 @@ public final class FileConfigurationParser extends XMLConfigurationUtil return configuration; } - private SharedStoreSlavePolicyConfiguration createSharedStoreSlaveHaPolicy(Element policyNode) - { + private SharedStoreSlavePolicyConfiguration createSharedStoreSlaveHaPolicy(Element policyNode) { SharedStoreSlavePolicyConfiguration configuration = new SharedStoreSlavePolicyConfiguration(); configuration.setAllowFailBack(getBoolean(policyNode, "allow-failback", configuration.isAllowFailBack())); @@ -1195,8 +969,7 @@ public final class FileConfigurationParser extends XMLConfigurationUtil return configuration; } - private ColocatedPolicyConfiguration createColocatedHaPolicy(Element policyNode, boolean replicated) - { + private ColocatedPolicyConfiguration createColocatedHaPolicy(Element policyNode, boolean replicated) { ColocatedPolicyConfiguration configuration = new ColocatedPolicyConfiguration(); boolean requestBackup = getBoolean(policyNode, "request-backup", configuration.isRequestBackup()); @@ -1221,14 +994,11 @@ public final class FileConfigurationParser extends XMLConfigurationUtil NodeList remoteConnectorNode = policyNode.getElementsByTagName("excludes"); - if (remoteConnectorNode != null && remoteConnectorNode.getLength() > 0) - { + if (remoteConnectorNode != null && remoteConnectorNode.getLength() > 0) { NodeList remoteConnectors = remoteConnectorNode.item(0).getChildNodes(); - for (int i = 0; i < remoteConnectors.getLength(); i++) - { + for (int i = 0; i < remoteConnectors.getLength(); i++) { Node child = remoteConnectors.item(i); - if (child.getNodeName().equals("connector-ref")) - { + if (child.getNodeName().equals("connector-ref")) { String connectorName = getTrimmedTextContent(child); configuration.getExcludedConnectors().add(connectorName); } @@ -1236,26 +1006,23 @@ public final class FileConfigurationParser extends XMLConfigurationUtil } NodeList masterNodeList = policyNode.getElementsByTagName("master"); - if (masterNodeList.getLength() > 0) - { + if (masterNodeList.getLength() > 0) { Element masterNode = (Element) masterNodeList.item(0); configuration.setLiveConfig(replicated ? createReplicatedHaPolicy(masterNode) : createSharedStoreMasterHaPolicy(masterNode)); } NodeList slaveNodeList = policyNode.getElementsByTagName("slave"); - if (slaveNodeList.getLength() > 0) - { + if (slaveNodeList.getLength() > 0) { Element slaveNode = (Element) slaveNodeList.item(0); configuration.setBackupConfig(replicated ? createReplicaHaPolicy(slaveNode) : createSharedStoreSlaveHaPolicy(slaveNode)); } return configuration; } - private ScaleDownConfiguration parseScaleDownConfig(Element policyNode) - { + + private ScaleDownConfiguration parseScaleDownConfig(Element policyNode) { NodeList scaleDownNode = policyNode.getElementsByTagName("scale-down"); - if (scaleDownNode.getLength() > 0) - { + if (scaleDownNode.getLength() > 0) { ScaleDownConfiguration scaleDownConfiguration = new ScaleDownConfiguration(); Element scaleDownElement = (Element) scaleDownNode.item(0); @@ -1264,8 +1031,7 @@ public final class FileConfigurationParser extends XMLConfigurationUtil NodeList discoveryGroupRef = scaleDownElement.getElementsByTagName("discovery-group-ref"); - if (discoveryGroupRef.item(0) != null) - { + if (discoveryGroupRef.item(0) != null) { scaleDownConfiguration.setDiscoveryGroup(discoveryGroupRef.item(0).getAttributes().getNamedItem("discovery-group-name").getNodeValue()); } @@ -1275,14 +1041,11 @@ public final class FileConfigurationParser extends XMLConfigurationUtil NodeList scaleDownConnectorNode = scaleDownElement.getElementsByTagName("connectors"); - if (scaleDownConnectorNode != null && scaleDownConnectorNode.getLength() > 0) - { + if (scaleDownConnectorNode != null && scaleDownConnectorNode.getLength() > 0) { NodeList scaleDownConnectors = scaleDownConnectorNode.item(0).getChildNodes(); - for (int i = 0; i < scaleDownConnectors.getLength(); i++) - { + for (int i = 0; i < scaleDownConnectors.getLength(); i++) { Node child = scaleDownConnectors.item(i); - if (child.getNodeName().equals("connector-ref")) - { + if (child.getNodeName().equals("connector-ref")) { String connectorName = getTrimmedTextContent(child); scaleDownConfiguration.getConnectors().add(connectorName); @@ -1294,31 +1057,24 @@ public final class FileConfigurationParser extends XMLConfigurationUtil return null; } - private void parseBroadcastGroupConfiguration(final Element e, final Configuration mainConfig) - { + private void parseBroadcastGroupConfiguration(final Element e, final Configuration mainConfig) { String name = e.getAttribute("name"); List connectorNames = new ArrayList(); NodeList children = e.getChildNodes(); - for (int j = 0; j < children.getLength(); j++) - { + for (int j = 0; j < children.getLength(); j++) { Node child = children.item(j); - if (child.getNodeName().equals("connector-ref")) - { - String connectorName = getString(e, - "connector-ref", - null, - Validators.NOT_NULL_OR_EMPTY); + if (child.getNodeName().equals("connector-ref")) { + String connectorName = getString(e, "connector-ref", null, Validators.NOT_NULL_OR_EMPTY); connectorNames.add(connectorName); } } - long broadcastPeriod = - getLong(e, "broadcast-period", ActiveMQDefaultConfiguration.getDefaultBroadcastPeriod(), Validators.GT_ZERO); + long broadcastPeriod = getLong(e, "broadcast-period", ActiveMQDefaultConfiguration.getDefaultBroadcastPeriod(), Validators.GT_ZERO); String localAddress = getString(e, "local-bind-address", null, Validators.NO_CHECK); @@ -1332,46 +1088,28 @@ public final class FileConfigurationParser extends XMLConfigurationUtil String jgroupsChannel = getString(e, "jgroups-channel", null, Validators.NO_CHECK); - // TODO: validate if either jgroups or UDP is being filled BroadcastEndpointFactory endpointFactory; - if (jgroupsFile != null) - { - endpointFactory = new JGroupsFileBroadcastEndpointFactory() - .setFile(jgroupsFile) - .setChannelName(jgroupsChannel); + if (jgroupsFile != null) { + endpointFactory = new JGroupsFileBroadcastEndpointFactory().setFile(jgroupsFile).setChannelName(jgroupsChannel); } - else - { - endpointFactory = new UDPBroadcastEndpointFactory() - .setGroupAddress(groupAddress) - .setGroupPort(groupPort) - .setLocalBindAddress(localAddress) - .setLocalBindPort(localBindPort); + else { + endpointFactory = new UDPBroadcastEndpointFactory().setGroupAddress(groupAddress).setGroupPort(groupPort).setLocalBindAddress(localAddress).setLocalBindPort(localBindPort); } - BroadcastGroupConfiguration config = new BroadcastGroupConfiguration() - .setName(name) - .setBroadcastPeriod(broadcastPeriod) - .setConnectorInfos(connectorNames) - .setEndpointFactory(endpointFactory); + BroadcastGroupConfiguration config = new BroadcastGroupConfiguration().setName(name).setBroadcastPeriod(broadcastPeriod).setConnectorInfos(connectorNames).setEndpointFactory(endpointFactory); mainConfig.getBroadcastGroupConfigurations().add(config); } - private void parseDiscoveryGroupConfiguration(final Element e, final Configuration mainConfig) - { + private void parseDiscoveryGroupConfiguration(final Element e, final Configuration mainConfig) { String name = e.getAttribute("name"); - long discoveryInitialWaitTimeout = - getLong(e, "initial-wait-timeout", ActiveMQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT, - Validators.GT_ZERO); + long discoveryInitialWaitTimeout = getLong(e, "initial-wait-timeout", ActiveMQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT, Validators.GT_ZERO); - long refreshTimeout = - getLong(e, "refresh-timeout", ActiveMQDefaultConfiguration.getDefaultBroadcastRefreshTimeout(), - Validators.GT_ZERO); + long refreshTimeout = getLong(e, "refresh-timeout", ActiveMQDefaultConfiguration.getDefaultBroadcastRefreshTimeout(), Validators.GT_ZERO); String localBindAddress = getString(e, "local-bind-address", null, Validators.NO_CHECK); @@ -1387,97 +1125,63 @@ public final class FileConfigurationParser extends XMLConfigurationUtil // TODO: validate if either jgroups or UDP is being filled BroadcastEndpointFactory endpointFactory; - if (jgroupsFile != null) - { - endpointFactory = new JGroupsFileBroadcastEndpointFactory() - .setFile(jgroupsFile) - .setChannelName(jgroupsChannel); + if (jgroupsFile != null) { + endpointFactory = new JGroupsFileBroadcastEndpointFactory().setFile(jgroupsFile).setChannelName(jgroupsChannel); } - else - { - endpointFactory = new UDPBroadcastEndpointFactory() - .setGroupAddress(groupAddress) - .setGroupPort(groupPort) - .setLocalBindAddress(localBindAddress) - .setLocalBindPort(localBindPort); + else { + endpointFactory = new UDPBroadcastEndpointFactory().setGroupAddress(groupAddress).setGroupPort(groupPort).setLocalBindAddress(localBindAddress).setLocalBindPort(localBindPort); } - DiscoveryGroupConfiguration config = new DiscoveryGroupConfiguration() - .setName(name) - .setRefreshTimeout(refreshTimeout) - .setDiscoveryInitialWaitTimeout(discoveryInitialWaitTimeout) - .setBroadcastEndpointFactory(endpointFactory); + DiscoveryGroupConfiguration config = new DiscoveryGroupConfiguration().setName(name).setRefreshTimeout(refreshTimeout).setDiscoveryInitialWaitTimeout(discoveryInitialWaitTimeout).setBroadcastEndpointFactory(endpointFactory); - if (mainConfig.getDiscoveryGroupConfigurations().containsKey(name)) - { + if (mainConfig.getDiscoveryGroupConfigurations().containsKey(name)) { ActiveMQServerLogger.LOGGER.discoveryGroupAlreadyDeployed(name); return; } - else - { + else { mainConfig.getDiscoveryGroupConfigurations().put(name, config); } } - private void parseClusterConnectionConfiguration(final Element e, final Configuration mainConfig) - { + private void parseClusterConnectionConfiguration(final Element e, final Configuration mainConfig) { String name = e.getAttribute("name"); String address = getString(e, "address", null, Validators.NOT_NULL_OR_EMPTY); String connectorName = getString(e, "connector-ref", null, Validators.NOT_NULL_OR_EMPTY); - boolean duplicateDetection = - getBoolean(e, "use-duplicate-detection", ActiveMQDefaultConfiguration.isDefaultClusterDuplicateDetection()); + boolean duplicateDetection = getBoolean(e, "use-duplicate-detection", ActiveMQDefaultConfiguration.isDefaultClusterDuplicateDetection()); MessageLoadBalancingType messageLoadBalancingType; - if (parameterExists(e, "forward-when-no-consumers")) - { - boolean forwardWhenNoConsumers = getBoolean(e, "forward-when-no-consumers", - ActiveMQDefaultConfiguration.isDefaultClusterForwardWhenNoConsumers()); - if (forwardWhenNoConsumers) - { + if (parameterExists(e, "forward-when-no-consumers")) { + boolean forwardWhenNoConsumers = getBoolean(e, "forward-when-no-consumers", ActiveMQDefaultConfiguration.isDefaultClusterForwardWhenNoConsumers()); + if (forwardWhenNoConsumers) { messageLoadBalancingType = MessageLoadBalancingType.STRICT; } - else - { + else { messageLoadBalancingType = MessageLoadBalancingType.ON_DEMAND; } } - else - { + else { - messageLoadBalancingType = Enum.valueOf(MessageLoadBalancingType.class, - getString(e, "message-load-balancing", - ActiveMQDefaultConfiguration.getDefaultClusterMessageLoadBalancingType(), - Validators.MESSAGE_LOAD_BALANCING_TYPE)); + messageLoadBalancingType = Enum.valueOf(MessageLoadBalancingType.class, getString(e, "message-load-balancing", ActiveMQDefaultConfiguration.getDefaultClusterMessageLoadBalancingType(), Validators.MESSAGE_LOAD_BALANCING_TYPE)); } - int maxHops = getInteger(e, "max-hops", - ActiveMQDefaultConfiguration.getDefaultClusterMaxHops(), - Validators.GE_ZERO); + int maxHops = getInteger(e, "max-hops", ActiveMQDefaultConfiguration.getDefaultClusterMaxHops(), Validators.GE_ZERO); - long clientFailureCheckPeriod = - getLong(e, "check-period", ActiveMQDefaultConfiguration.getDefaultClusterFailureCheckPeriod(), - Validators.GT_ZERO); + long clientFailureCheckPeriod = getLong(e, "check-period", ActiveMQDefaultConfiguration.getDefaultClusterFailureCheckPeriod(), Validators.GT_ZERO); - long connectionTTL = - getLong(e, "connection-ttl", ActiveMQDefaultConfiguration.getDefaultClusterConnectionTtl(), - Validators.GT_ZERO); + long connectionTTL = getLong(e, "connection-ttl", ActiveMQDefaultConfiguration.getDefaultClusterConnectionTtl(), Validators.GT_ZERO); - - long retryInterval = - getLong(e, "retry-interval", ActiveMQDefaultConfiguration.getDefaultClusterRetryInterval(), - Validators.GT_ZERO); + long retryInterval = getLong(e, "retry-interval", ActiveMQDefaultConfiguration.getDefaultClusterRetryInterval(), Validators.GT_ZERO); long callTimeout = getLong(e, "call-timeout", ActiveMQClient.DEFAULT_CALL_TIMEOUT, Validators.GT_ZERO); long callFailoverTimeout = getLong(e, "call-failover-timeout", ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, Validators.MINUS_ONE_OR_GT_ZERO); - double retryIntervalMultiplier = getDouble(e, "retry-interval-multiplier", - ActiveMQDefaultConfiguration.getDefaultClusterRetryIntervalMultiplier(), Validators.GT_ZERO); + double retryIntervalMultiplier = getDouble(e, "retry-interval-multiplier", ActiveMQDefaultConfiguration.getDefaultClusterRetryIntervalMultiplier(), Validators.GT_ZERO); int minLargeMessageSize = getInteger(e, "min-large-message-size", ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, Validators.GT_ZERO); @@ -1487,10 +1191,7 @@ public final class FileConfigurationParser extends XMLConfigurationUtil int reconnectAttempts = getInteger(e, "reconnect-attempts", ActiveMQDefaultConfiguration.getDefaultClusterReconnectAttempts(), Validators.MINUS_ONE_OR_GE_ZERO); - - int confirmationWindowSize = - getInteger(e, "confirmation-window-size", ActiveMQDefaultConfiguration.getDefaultClusterConfirmationWindowSize(), - Validators.GT_ZERO); + int confirmationWindowSize = getInteger(e, "confirmation-window-size", ActiveMQDefaultConfiguration.getDefaultClusterConfirmationWindowSize(), Validators.GT_ZERO); long clusterNotificationInterval = getLong(e, "notification-interval", ActiveMQDefaultConfiguration.getDefaultClusterNotificationInterval(), Validators.GT_ZERO); @@ -1506,81 +1207,44 @@ public final class FileConfigurationParser extends XMLConfigurationUtil NodeList children = e.getChildNodes(); - for (int j = 0; j < children.getLength(); j++) - { + for (int j = 0; j < children.getLength(); j++) { Node child = children.item(j); - if (child.getNodeName().equals("discovery-group-ref")) - { + if (child.getNodeName().equals("discovery-group-ref")) { discoveryGroupName = child.getAttributes().getNamedItem("discovery-group-name").getNodeValue(); } - else if (child.getNodeName().equals("static-connectors")) - { + else if (child.getNodeName().equals("static-connectors")) { Node attr = child.getAttributes().getNamedItem("allow-direct-connections-only"); - if (attr != null) - { + if (attr != null) { allowDirectConnectionsOnly = "true".equalsIgnoreCase(attr.getNodeValue()) || allowDirectConnectionsOnly; } getStaticConnectors(staticConnectorNames, child); } } - ClusterConnectionConfiguration config = new ClusterConnectionConfiguration() - .setName(name) - .setAddress(address) - .setConnectorName(connectorName) - .setMinLargeMessageSize(minLargeMessageSize) - .setClientFailureCheckPeriod(clientFailureCheckPeriod) - .setConnectionTTL(connectionTTL) - .setRetryInterval(retryInterval) - .setRetryIntervalMultiplier(retryIntervalMultiplier) - .setMaxRetryInterval(maxRetryInterval) - .setInitialConnectAttempts(initialConnectAttempts) - .setReconnectAttempts(reconnectAttempts) - .setCallTimeout(callTimeout) - .setCallFailoverTimeout(callFailoverTimeout) - .setDuplicateDetection(duplicateDetection) - .setMessageLoadBalancingType(messageLoadBalancingType) - .setMaxHops(maxHops) - .setConfirmationWindowSize(confirmationWindowSize) - .setAllowDirectConnectionsOnly(allowDirectConnectionsOnly) - .setClusterNotificationInterval(clusterNotificationInterval) - .setClusterNotificationAttempts(clusterNotificationAttempts); + ClusterConnectionConfiguration config = new ClusterConnectionConfiguration().setName(name).setAddress(address).setConnectorName(connectorName).setMinLargeMessageSize(minLargeMessageSize).setClientFailureCheckPeriod(clientFailureCheckPeriod).setConnectionTTL(connectionTTL).setRetryInterval(retryInterval).setRetryIntervalMultiplier(retryIntervalMultiplier).setMaxRetryInterval(maxRetryInterval).setInitialConnectAttempts(initialConnectAttempts).setReconnectAttempts(reconnectAttempts).setCallTimeout(callTimeout).setCallFailoverTimeout(callFailoverTimeout).setDuplicateDetection(duplicateDetection).setMessageLoadBalancingType(messageLoadBalancingType).setMaxHops(maxHops).setConfirmationWindowSize(confirmationWindowSize).setAllowDirectConnectionsOnly(allowDirectConnectionsOnly).setClusterNotificationInterval(clusterNotificationInterval).setClusterNotificationAttempts(clusterNotificationAttempts); - if (discoveryGroupName == null) - { + if (discoveryGroupName == null) { config.setStaticConnectors(staticConnectorNames); } - else - { + else { config.setDiscoveryGroupName(discoveryGroupName); } mainConfig.getClusterConfigurations().add(config); } - private void parseGroupingHandlerConfiguration(final Element node, final Configuration mainConfiguration) - { + private void parseGroupingHandlerConfiguration(final Element node, final Configuration mainConfiguration) { String name = node.getAttribute("name"); String type = getString(node, "type", null, Validators.NOT_NULL_OR_EMPTY); String address = getString(node, "address", null, Validators.NOT_NULL_OR_EMPTY); Integer timeout = getInteger(node, "timeout", ActiveMQDefaultConfiguration.getDefaultGroupingHandlerTimeout(), Validators.GT_ZERO); Long groupTimeout = getLong(node, "group-timeout", ActiveMQDefaultConfiguration.getDefaultGroupingHandlerGroupTimeout(), Validators.MINUS_ONE_OR_GT_ZERO); Long reaperPeriod = getLong(node, "reaper-period", ActiveMQDefaultConfiguration.getDefaultGroupingHandlerReaperPeriod(), Validators.GT_ZERO); - mainConfiguration.setGroupingHandlerConfiguration(new GroupingHandlerConfiguration() - .setName(new SimpleString(name)) - .setType( - type.equals(GroupingHandlerConfiguration.TYPE.LOCAL.getType()) - ? GroupingHandlerConfiguration.TYPE.LOCAL - : GroupingHandlerConfiguration.TYPE.REMOTE) - .setAddress(new SimpleString(address)) - .setTimeout(timeout) - .setGroupTimeout(groupTimeout) - .setReaperPeriod(reaperPeriod)); + mainConfiguration.setGroupingHandlerConfiguration(new GroupingHandlerConfiguration().setName(new SimpleString(name)).setType(type.equals(GroupingHandlerConfiguration.TYPE.LOCAL.getType()) ? GroupingHandlerConfiguration.TYPE.LOCAL : GroupingHandlerConfiguration.TYPE.REMOTE).setAddress(new SimpleString(address)).setTimeout(timeout).setGroupTimeout(groupTimeout).setReaperPeriod(reaperPeriod)); } - private void parseBridgeConfiguration(final Element brNode, final Configuration mainConfig) throws Exception - { + private void parseBridgeConfiguration(final Element brNode, final Configuration mainConfig) throws Exception { String name = brNode.getAttribute("name"); String queueName = getString(brNode, "queue-name", null, Validators.NOT_NULL_OR_EMPTY); @@ -1590,48 +1254,29 @@ public final class FileConfigurationParser extends XMLConfigurationUtil String transformerClassName = getString(brNode, "transformer-class-name", null, Validators.NO_CHECK); // Default bridge conf - int confirmationWindowSize = - getInteger(brNode, "confirmation-window-size", ActiveMQDefaultConfiguration.getDefaultBridgeConfirmationWindowSize(), - Validators.GT_ZERO); + int confirmationWindowSize = getInteger(brNode, "confirmation-window-size", ActiveMQDefaultConfiguration.getDefaultBridgeConfirmationWindowSize(), Validators.GT_ZERO); long retryInterval = getLong(brNode, "retry-interval", ActiveMQClient.DEFAULT_RETRY_INTERVAL, Validators.GT_ZERO); - long clientFailureCheckPeriod = - getLong(brNode, "check-period", ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, Validators.GT_ZERO); + long clientFailureCheckPeriod = getLong(brNode, "check-period", ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, Validators.GT_ZERO); long connectionTTL = getLong(brNode, "connection-ttl", ActiveMQClient.DEFAULT_CONNECTION_TTL, Validators.GT_ZERO); - int minLargeMessageSize = - getInteger(brNode, "min-large-message-size", ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - Validators.GT_ZERO); + int minLargeMessageSize = getInteger(brNode, "min-large-message-size", ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, Validators.GT_ZERO); long maxRetryInterval = getLong(brNode, "max-retry-interval", ActiveMQClient.DEFAULT_MAX_RETRY_INTERVAL, Validators.GT_ZERO); + double retryIntervalMultiplier = getDouble(brNode, "retry-interval-multiplier", ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, Validators.GT_ZERO); - double retryIntervalMultiplier = - getDouble(brNode, "retry-interval-multiplier", ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, - Validators.GT_ZERO); + int initialConnectAttempts = getInteger(brNode, "initial-connect-attempts", ActiveMQDefaultConfiguration.getDefaultBridgeInitialConnectAttempts(), Validators.MINUS_ONE_OR_GE_ZERO); - int initialConnectAttempts = - getInteger(brNode, "initial-connect-attempts", ActiveMQDefaultConfiguration.getDefaultBridgeInitialConnectAttempts(), - Validators.MINUS_ONE_OR_GE_ZERO); + int reconnectAttempts = getInteger(brNode, "reconnect-attempts", ActiveMQDefaultConfiguration.getDefaultBridgeReconnectAttempts(), Validators.MINUS_ONE_OR_GE_ZERO); - int reconnectAttempts = - getInteger(brNode, "reconnect-attempts", ActiveMQDefaultConfiguration.getDefaultBridgeReconnectAttempts(), - Validators.MINUS_ONE_OR_GE_ZERO); + int reconnectAttemptsSameNode = getInteger(brNode, "reconnect-attempts-same-node", ActiveMQDefaultConfiguration.getDefaultBridgeConnectSameNode(), Validators.MINUS_ONE_OR_GE_ZERO); - int reconnectAttemptsSameNode = - getInteger(brNode, "reconnect-attempts-same-node", ActiveMQDefaultConfiguration.getDefaultBridgeConnectSameNode(), - Validators.MINUS_ONE_OR_GE_ZERO); + boolean useDuplicateDetection = getBoolean(brNode, "use-duplicate-detection", ActiveMQDefaultConfiguration.isDefaultBridgeDuplicateDetection()); - boolean useDuplicateDetection = getBoolean(brNode, - "use-duplicate-detection", - ActiveMQDefaultConfiguration.isDefaultBridgeDuplicateDetection()); - - String user = getString(brNode, - "user", - ActiveMQDefaultConfiguration.getDefaultClusterUser(), - Validators.NO_CHECK); + String user = getString(brNode, "user", ActiveMQDefaultConfiguration.getDefaultClusterUser(), Validators.NO_CHECK); NodeList clusterPassNodes = brNode.getElementsByTagName("password"); String password = null; @@ -1639,22 +1284,18 @@ public final class FileConfigurationParser extends XMLConfigurationUtil SensitiveDataCodec codec = null; - if (clusterPassNodes.getLength() > 0) - { + if (clusterPassNodes.getLength() > 0) { Node passNode = clusterPassNodes.item(0); password = passNode.getTextContent(); } - if (password != null) - { - if (maskPassword) - { + if (password != null) { + if (maskPassword) { codec = PasswordMaskingUtil.getCodec(mainConfig.getPasswordCodec()); password = codec.decode(password); } } - else - { + else { password = ActiveMQDefaultConfiguration.getDefaultClusterPassword(); } @@ -1668,64 +1309,36 @@ public final class FileConfigurationParser extends XMLConfigurationUtil NodeList children = brNode.getChildNodes(); - for (int j = 0; j < children.getLength(); j++) - { + for (int j = 0; j < children.getLength(); j++) { Node child = children.item(j); - if (child.getNodeName().equals("filter")) - { + if (child.getNodeName().equals("filter")) { filterString = child.getAttributes().getNamedItem("string").getNodeValue(); } - else if (child.getNodeName().equals("discovery-group-ref")) - { + else if (child.getNodeName().equals("discovery-group-ref")) { discoveryGroupName = child.getAttributes().getNamedItem("discovery-group-name").getNodeValue(); } - else if (child.getNodeName().equals("static-connectors")) - { + else if (child.getNodeName().equals("static-connectors")) { getStaticConnectors(staticConnectorNames, child); } } + BridgeConfiguration config = new BridgeConfiguration().setName(name).setQueueName(queueName).setForwardingAddress(forwardingAddress).setFilterString(filterString).setTransformerClassName(transformerClassName).setMinLargeMessageSize(minLargeMessageSize).setClientFailureCheckPeriod(clientFailureCheckPeriod).setConnectionTTL(connectionTTL).setRetryInterval(retryInterval).setMaxRetryInterval(maxRetryInterval).setRetryIntervalMultiplier(retryIntervalMultiplier).setInitialConnectAttempts(initialConnectAttempts).setReconnectAttempts(reconnectAttempts).setReconnectAttemptsOnSameNode(reconnectAttemptsSameNode).setUseDuplicateDetection(useDuplicateDetection).setConfirmationWindowSize(confirmationWindowSize).setHA(ha).setUser(user).setPassword(password); - BridgeConfiguration config = new BridgeConfiguration() - .setName(name) - .setQueueName(queueName) - .setForwardingAddress(forwardingAddress) - .setFilterString(filterString) - .setTransformerClassName(transformerClassName) - .setMinLargeMessageSize(minLargeMessageSize) - .setClientFailureCheckPeriod(clientFailureCheckPeriod) - .setConnectionTTL(connectionTTL) - .setRetryInterval(retryInterval) - .setMaxRetryInterval(maxRetryInterval) - .setRetryIntervalMultiplier(retryIntervalMultiplier) - .setInitialConnectAttempts(initialConnectAttempts) - .setReconnectAttempts(reconnectAttempts) - .setReconnectAttemptsOnSameNode(reconnectAttemptsSameNode) - .setUseDuplicateDetection(useDuplicateDetection) - .setConfirmationWindowSize(confirmationWindowSize) - .setHA(ha) - .setUser(user) - .setPassword(password); - - if (!staticConnectorNames.isEmpty()) - { + if (!staticConnectorNames.isEmpty()) { config.setStaticConnectors(staticConnectorNames); } - else - { + else { config.setDiscoveryGroupName(discoveryGroupName); } mainConfig.getBridgeConfigurations().add(config); } - private void getStaticConnectors(List staticConnectorNames, Node child) - { + private void getStaticConnectors(List staticConnectorNames, Node child) { NodeList children2 = ((Element) child).getElementsByTagName("connector-ref"); - for (int k = 0; k < children2.getLength(); k++) - { + for (int k = 0; k < children2.getLength(); k++) { Element child2 = (Element) children2.item(k); String connectorName = child2.getChildNodes().item(0).getNodeValue(); @@ -1734,8 +1347,7 @@ public final class FileConfigurationParser extends XMLConfigurationUtil } } - private void parseDivertConfiguration(final Element e, final Configuration mainConfig) - { + private void parseDivertConfiguration(final Element e, final Configuration mainConfig) { String name = e.getAttribute("name"); String routingName = getString(e, "routing-name", null, Validators.NO_CHECK); @@ -1752,30 +1364,20 @@ public final class FileConfigurationParser extends XMLConfigurationUtil NodeList children = e.getChildNodes(); - for (int j = 0; j < children.getLength(); j++) - { + for (int j = 0; j < children.getLength(); j++) { Node child = children.item(j); - if (child.getNodeName().equals("filter")) - { + if (child.getNodeName().equals("filter")) { filterString = getAttributeValue(child, "string"); } } - DivertConfiguration config = new DivertConfiguration() - .setName(name) - .setRoutingName(routingName) - .setAddress(address) - .setForwardingAddress(forwardingAddress) - .setExclusive(exclusive) - .setFilterString(filterString) - .setTransformerClassName(transformerClassName); + DivertConfiguration config = new DivertConfiguration().setName(name).setRoutingName(routingName).setAddress(address).setForwardingAddress(forwardingAddress).setExclusive(exclusive).setFilterString(filterString).setTransformerClassName(transformerClassName); mainConfig.getDivertConfigurations().add(config); } - private ConnectorServiceConfiguration parseConnectorService(final Element e) - { + private ConnectorServiceConfiguration parseConnectorService(final Element e) { Node nameNode = e.getAttributes().getNamedItem("name"); String name = nameNode != null ? nameNode.getNodeValue() : null; @@ -1786,8 +1388,7 @@ public final class FileConfigurationParser extends XMLConfigurationUtil NodeList paramsNodes = e.getElementsByTagName("param"); - for (int i = 0; i < paramsNodes.getLength(); i++) - { + for (int i = 0; i < paramsNodes.getLength(); i++) { Node paramNode = paramsNodes.item(i); NamedNodeMap attributes = paramNode.getAttributes(); @@ -1801,9 +1402,6 @@ public final class FileConfigurationParser extends XMLConfigurationUtil params.put(key, nValue.getTextContent()); } - return new ConnectorServiceConfiguration() - .setFactoryClassName(clazz) - .setParams(params) - .setName(name); + return new ConnectorServiceConfiguration().setFactoryClassName(clazz).setParams(params).setName(name); } } \ No newline at end of file diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/filter/Filter.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/filter/Filter.java index 1632a101ad..5dd507cab0 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/filter/Filter.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/filter/Filter.java @@ -19,8 +19,8 @@ package org.apache.activemq.artemis.core.filter; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.server.ServerMessage; -public interface Filter -{ +public interface Filter { + boolean match(ServerMessage message); SimpleString getFilterString(); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/filter/impl/FilterImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/filter/impl/FilterImpl.java index 00b414ddb2..63534f6404 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/filter/impl/FilterImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/filter/impl/FilterImpl.java @@ -29,25 +29,24 @@ import org.apache.activemq.artemis.core.server.ActiveMQMessageBundle; import org.apache.activemq.artemis.core.server.ServerMessage; /** -* This class implements an ActiveMQ Artemis filter -* -* ActiveMQ Artemis filters have the same syntax as JMS 1.1 selectors, but the identifiers are different. -* -* Valid identifiers that can be used are: -* -* AMQPriority - the priority of the message -* AMQTimestamp - the timestamp of the message -* AMQDurable - "DURABLE" or "NON_DURABLE" -* AMQExpiration - the expiration of the message -* AMQSize - the encoded size of the full message in bytes -* AMQUserID - the user specified ID string (if any) -* Any other identifiers that appear in a filter expression represent header values for the message -* -* String values must be set as SimpleString, not java.lang.String (see JBMESSAGING-1307). -* Derived from JBoss MQ version by -*/ -public class FilterImpl implements Filter -{ + * This class implements an ActiveMQ Artemis filter + * + * ActiveMQ Artemis filters have the same syntax as JMS 1.1 selectors, but the identifiers are different. + * + * Valid identifiers that can be used are: + * + * AMQPriority - the priority of the message + * AMQTimestamp - the timestamp of the message + * AMQDurable - "DURABLE" or "NON_DURABLE" + * AMQExpiration - the expiration of the message + * AMQSize - the encoded size of the full message in bytes + * AMQUserID - the user specified ID string (if any) + * Any other identifiers that appear in a filter expression represent header values for the message + * + * String values must be set as SimpleString, not java.lang.String (see JBMESSAGING-1307). + * Derived from JBoss MQ version by + */ +public class FilterImpl implements Filter { // Constants ----------------------------------------------------- @@ -61,8 +60,7 @@ public class FilterImpl implements Filter * @return null if filterStr is null or an empty String and a valid filter else * @throws ActiveMQException if the string does not correspond to a valid filter */ - public static Filter createFilter(final String filterStr) throws ActiveMQException - { + public static Filter createFilter(final String filterStr) throws ActiveMQException { return FilterImpl.createFilter(SimpleString.toSimpleString(filterStr == null ? null : filterStr.trim())); } @@ -70,20 +68,16 @@ public class FilterImpl implements Filter * @return null if filterStr is null or an empty String and a valid filter else * @throws ActiveMQException if the string does not correspond to a valid filter */ - public static Filter createFilter(final SimpleString filterStr) throws ActiveMQException - { - if (filterStr == null || filterStr.length() == 0) - { + public static Filter createFilter(final SimpleString filterStr) throws ActiveMQException { + if (filterStr == null || filterStr.length() == 0) { return null; } BooleanExpression booleanExpression; - try - { - booleanExpression = SelectorParser.parse(filterStr.toString()); + try { + booleanExpression = SelectorParser.parse(filterStr.toString()); } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQServerLogger.LOGGER.invalidFilter(e, filterStr); throw ActiveMQMessageBundle.BUNDLE.invalidFilter(e, filterStr); } @@ -92,36 +86,30 @@ public class FilterImpl implements Filter // Constructors --------------------------------------------------- - private FilterImpl(final SimpleString str, final BooleanExpression expression) - { + private FilterImpl(final SimpleString str, final BooleanExpression expression) { sfilterString = str; this.booleanExpression = expression; } // Filter implementation --------------------------------------------------------------------- - public SimpleString getFilterString() - { + public SimpleString getFilterString() { return sfilterString; } - public synchronized boolean match(final ServerMessage message) - { - try - { + public synchronized boolean match(final ServerMessage message) { + try { boolean result = booleanExpression.matches(new FilterableServerMessage(message)); return result; } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.invalidFilter(e, sfilterString); return false; } } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((sfilterString == null) ? 0 : sfilterString.hashCode()); @@ -129,17 +117,15 @@ public class FilterImpl implements Filter } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; - FilterImpl other = (FilterImpl)obj; - if (sfilterString == null) - { + FilterImpl other = (FilterImpl) obj; + if (sfilterString == null) { if (other.sfilterString != null) return false; } @@ -149,71 +135,56 @@ public class FilterImpl implements Filter } @Override - public String toString() - { + public String toString() { return "FilterImpl [sfilterString=" + sfilterString + "]"; } // Private -------------------------------------------------------------------------- - private static Object getHeaderFieldValue(final ServerMessage msg, final SimpleString fieldName) - { - if (FilterConstants.ACTIVEMQ_USERID.equals(fieldName)) - { + private static Object getHeaderFieldValue(final ServerMessage msg, final SimpleString fieldName) { + if (FilterConstants.ACTIVEMQ_USERID.equals(fieldName)) { // It's the stringified (hex) representation of a user id that can be used in a selector expression return new SimpleString("ID:" + msg.getUserID()); } - else if (FilterConstants.ACTIVEMQ_PRIORITY.equals(fieldName)) - { + else if (FilterConstants.ACTIVEMQ_PRIORITY.equals(fieldName)) { return Integer.valueOf(msg.getPriority()); } - else if (FilterConstants.ACTIVEMQ_TIMESTAMP.equals(fieldName)) - { + else if (FilterConstants.ACTIVEMQ_TIMESTAMP.equals(fieldName)) { return msg.getTimestamp(); } - else if (FilterConstants.ACTIVEMQ_DURABLE.equals(fieldName)) - { + else if (FilterConstants.ACTIVEMQ_DURABLE.equals(fieldName)) { return msg.isDurable() ? FilterConstants.DURABLE : FilterConstants.NON_DURABLE; } - else if (FilterConstants.ACTIVEMQ_EXPIRATION.equals(fieldName)) - { + else if (FilterConstants.ACTIVEMQ_EXPIRATION.equals(fieldName)) { return msg.getExpiration(); } - else if (FilterConstants.ACTIVEMQ_SIZE.equals(fieldName)) - { + else if (FilterConstants.ACTIVEMQ_SIZE.equals(fieldName)) { return msg.getEncodeSize(); } - else - { + else { return null; } } - private static class FilterableServerMessage implements Filterable - { + private static class FilterableServerMessage implements Filterable { + private final ServerMessage message; - public FilterableServerMessage(ServerMessage message) - { + public FilterableServerMessage(ServerMessage message) { this.message = message; } @Override - public Object getProperty(String id) - { + public Object getProperty(String id) { Object result = null; - if (id.startsWith(FilterConstants.ACTIVEMQ_PREFIX.toString())) - { + if (id.startsWith(FilterConstants.ACTIVEMQ_PREFIX.toString())) { result = getHeaderFieldValue(message, new SimpleString(id)); } - if (result == null) - { + if (result == null) { result = message.getObjectProperty(new SimpleString(id)); } - if (result != null) - { - if (result.getClass() == SimpleString.class) - { + if (result != null) { + if (result.getClass() == SimpleString.class) { result = result.toString(); } } @@ -221,15 +192,13 @@ public class FilterImpl implements Filter } @Override - public T getBodyAs(Class type) throws FilterException - { + public T getBodyAs(Class type) throws FilterException { // TODO: implement to support content based selection return null; } @Override - public Object getLocalConnectionId() - { + public Object getLocalConnectionId() { // Only needed if the NoLocal return null; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/AbstractControl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/AbstractControl.java index db09ba466d..8281f6b5d6 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/AbstractControl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/AbstractControl.java @@ -23,8 +23,7 @@ import javax.management.StandardMBean; import org.apache.activemq.artemis.core.persistence.StorageManager; -public abstract class AbstractControl extends StandardMBean -{ +public abstract class AbstractControl extends StandardMBean { // Constants ----------------------------------------------------- @@ -36,8 +35,7 @@ public abstract class AbstractControl extends StandardMBean // Constructors -------------------------------------------------- - public AbstractControl(final Class clazz, final StorageManager storageManager) throws NotCompliantMBeanException - { + public AbstractControl(final Class clazz, final StorageManager storageManager) throws NotCompliantMBeanException { super(clazz); this.storageManager = storageManager; } @@ -48,27 +46,21 @@ public abstract class AbstractControl extends StandardMBean // Protected ----------------------------------------------------- - protected void clearIO() - { + protected void clearIO() { // the storage manager could be null on the backup on certain components - if (storageManager != null) - { + if (storageManager != null) { storageManager.clearContext(); } } - protected void blockOnIO() - { + protected void blockOnIO() { // the storage manager could be null on the backup on certain components - if (storageManager != null) - { - try - { + if (storageManager != null) { + try { storageManager.waitOnOperations(); storageManager.clearContext(); } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } @@ -78,15 +70,9 @@ public abstract class AbstractControl extends StandardMBean protected abstract MBeanOperationInfo[] fillMBeanOperationInfo(); @Override - public MBeanInfo getMBeanInfo() - { + public MBeanInfo getMBeanInfo() { MBeanInfo info = super.getMBeanInfo(); - return new MBeanInfo(info.getClassName(), - info.getDescription(), - info.getAttributes(), - info.getConstructors(), - fillMBeanOperationInfo(), - info.getNotifications()); + return new MBeanInfo(info.getClassName(), info.getDescription(), info.getAttributes(), info.getConstructors(), fillMBeanOperationInfo(), info.getNotifications()); } // Private ------------------------------------------------------- diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/AcceptorControlImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/AcceptorControlImpl.java index 1771bfe7e5..9097cd74c0 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/AcceptorControlImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/AcceptorControlImpl.java @@ -25,8 +25,7 @@ import org.apache.activemq.artemis.api.core.management.AcceptorControl; import org.apache.activemq.artemis.core.persistence.StorageManager; import org.apache.activemq.artemis.spi.core.remoting.Acceptor; -public class AcceptorControlImpl extends AbstractControl implements AcceptorControl -{ +public class AcceptorControlImpl extends AbstractControl implements AcceptorControl { // Constants ----------------------------------------------------- @@ -42,8 +41,7 @@ public class AcceptorControlImpl extends AbstractControl implements AcceptorCont public AcceptorControlImpl(final Acceptor acceptor, final StorageManager storageManager, - final TransportConfiguration configuration) throws Exception - { + final TransportConfiguration configuration) throws Exception { super(AcceptorControl.class, storageManager); this.acceptor = acceptor; this.configuration = configuration; @@ -51,87 +49,68 @@ public class AcceptorControlImpl extends AbstractControl implements AcceptorCont // AcceptorControlMBean implementation --------------------------- - public String getFactoryClassName() - { + public String getFactoryClassName() { clearIO(); - try - { + try { return configuration.getFactoryClassName(); } - finally - { + finally { blockOnIO(); } } - public String getName() - { + public String getName() { clearIO(); - try - { + try { return configuration.getName(); } - finally - { + finally { blockOnIO(); } } - public Map getParameters() - { + public Map getParameters() { clearIO(); - try - { + try { return configuration.getParams(); } - finally - { + finally { blockOnIO(); } } - public boolean isStarted() - { + public boolean isStarted() { clearIO(); - try - { + try { return acceptor.isStarted(); } - finally - { + finally { blockOnIO(); } } - public void start() throws Exception - { + public void start() throws Exception { clearIO(); - try - { + try { acceptor.start(); } - finally - { + finally { blockOnIO(); } } - public void stop() throws Exception - { + public void stop() throws Exception { clearIO(); - try - { + try { acceptor.stop(); } - finally - { + finally { blockOnIO(); } } @Override - protected MBeanOperationInfo[] fillMBeanOperationInfo() - { + protected MBeanOperationInfo[] fillMBeanOperationInfo() { return MBeanInfoHelper.getMBeanOperationsInfo(AcceptorControl.class); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/ActiveMQServerControlImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/ActiveMQServerControlImpl.java index 7f89610a67..239c9484de 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/ActiveMQServerControlImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/ActiveMQServerControlImpl.java @@ -90,9 +90,7 @@ import org.apache.activemq.artemis.utils.TypedProperties; import org.apache.activemq.artemis.utils.json.JSONArray; import org.apache.activemq.artemis.utils.json.JSONObject; -public class ActiveMQServerControlImpl extends AbstractControl implements ActiveMQServerControl, NotificationEmitter, - org.apache.activemq.artemis.core.server.management.NotificationListener -{ +public class ActiveMQServerControlImpl extends AbstractControl implements ActiveMQServerControl, NotificationEmitter, org.apache.activemq.artemis.core.server.management.NotificationListener { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -123,8 +121,7 @@ public class ActiveMQServerControlImpl extends AbstractControl implements Active final ActiveMQServer messagingServer, final MessageCounterManager messageCounterManager, final StorageManager storageManager, - final NotificationBroadcasterSupport broadcaster) throws Exception - { + final NotificationBroadcasterSupport broadcaster) throws Exception { super(ActiveMQServerControl.class, storageManager); this.postOffice = postOffice; this.configuration = configuration; @@ -138,896 +135,715 @@ public class ActiveMQServerControlImpl extends AbstractControl implements Active // ActiveMQServerControlMBean implementation -------------------- - public boolean isStarted() - { + public boolean isStarted() { clearIO(); - try - { + try { return server.isStarted(); } - finally - { + finally { blockOnIO(); } } - public String getVersion() - { + public String getVersion() { checkStarted(); clearIO(); - try - { + try { return server.getVersion().getFullVersion(); } - finally - { + finally { blockOnIO(); } } - public boolean isBackup() - { + public boolean isBackup() { checkStarted(); clearIO(); - try - { + try { return server.getHAPolicy().isBackup(); } - finally - { + finally { blockOnIO(); } } - public boolean isSharedStore() - { + public boolean isSharedStore() { checkStarted(); clearIO(); - try - { + try { return server.getHAPolicy().isSharedStore(); } - finally - { + finally { blockOnIO(); } } - public String getBindingsDirectory() - { + public String getBindingsDirectory() { checkStarted(); clearIO(); - try - { + try { return configuration.getBindingsDirectory(); } - finally - { + finally { blockOnIO(); } } - public String[] getInterceptorClassNames() - { + public String[] getInterceptorClassNames() { checkStarted(); clearIO(); - try - { - return configuration.getIncomingInterceptorClassNames().toArray(new String[configuration.getIncomingInterceptorClassNames() - .size()]); + try { + return configuration.getIncomingInterceptorClassNames().toArray(new String[configuration.getIncomingInterceptorClassNames().size()]); } - finally - { + finally { blockOnIO(); } } - public String[] getIncomingInterceptorClassNames() - { + public String[] getIncomingInterceptorClassNames() { checkStarted(); clearIO(); - try - { - return configuration.getIncomingInterceptorClassNames().toArray(new String[configuration.getIncomingInterceptorClassNames() - .size()]); + try { + return configuration.getIncomingInterceptorClassNames().toArray(new String[configuration.getIncomingInterceptorClassNames().size()]); } - finally - { + finally { blockOnIO(); } } - public String[] getOutgoingInterceptorClassNames() - { + public String[] getOutgoingInterceptorClassNames() { checkStarted(); clearIO(); - try - { - return configuration.getOutgoingInterceptorClassNames().toArray(new String[configuration.getOutgoingInterceptorClassNames() - .size()]); + try { + return configuration.getOutgoingInterceptorClassNames().toArray(new String[configuration.getOutgoingInterceptorClassNames().size()]); } - finally - { + finally { blockOnIO(); } } - public int getJournalBufferSize() - { + public int getJournalBufferSize() { checkStarted(); clearIO(); - try - { - return configuration.getJournalType() == JournalType.ASYNCIO ? configuration.getJournalBufferSize_AIO() - : configuration.getJournalBufferSize_NIO(); + try { + return configuration.getJournalType() == JournalType.ASYNCIO ? configuration.getJournalBufferSize_AIO() : configuration.getJournalBufferSize_NIO(); } - finally - { + finally { blockOnIO(); } } - public int getJournalBufferTimeout() - { + public int getJournalBufferTimeout() { checkStarted(); clearIO(); - try - { - return configuration.getJournalType() == JournalType.ASYNCIO ? configuration.getJournalBufferTimeout_AIO() - : configuration.getJournalBufferTimeout_NIO(); + try { + return configuration.getJournalType() == JournalType.ASYNCIO ? configuration.getJournalBufferTimeout_AIO() : configuration.getJournalBufferTimeout_NIO(); } - finally - { + finally { blockOnIO(); } } - public void setFailoverOnServerShutdown(boolean failoverOnServerShutdown) - { + public void setFailoverOnServerShutdown(boolean failoverOnServerShutdown) { checkStarted(); clearIO(); - try - { + try { HAPolicy haPolicy = server.getHAPolicy(); - if (haPolicy instanceof SharedStoreSlavePolicy) - { + if (haPolicy instanceof SharedStoreSlavePolicy) { ((SharedStoreSlavePolicy) haPolicy).setFailoverOnServerShutdown(failoverOnServerShutdown); } } - finally - { + finally { blockOnIO(); } } - - public boolean isFailoverOnServerShutdown() - { + public boolean isFailoverOnServerShutdown() { checkStarted(); clearIO(); - try - { + try { HAPolicy haPolicy = server.getHAPolicy(); - if (haPolicy instanceof SharedStoreSlavePolicy) - { + if (haPolicy instanceof SharedStoreSlavePolicy) { return ((SharedStoreSlavePolicy) haPolicy).isFailoverOnServerShutdown(); } - else - { + else { return false; } } - finally - { + finally { blockOnIO(); } } - public int getJournalMaxIO() - { + public int getJournalMaxIO() { checkStarted(); clearIO(); - try - { - return configuration.getJournalType() == JournalType.ASYNCIO ? configuration.getJournalMaxIO_AIO() - : configuration.getJournalMaxIO_NIO(); + try { + return configuration.getJournalType() == JournalType.ASYNCIO ? configuration.getJournalMaxIO_AIO() : configuration.getJournalMaxIO_NIO(); } - finally - { + finally { blockOnIO(); } } - public String getJournalDirectory() - { + public String getJournalDirectory() { checkStarted(); clearIO(); - try - { + try { return configuration.getJournalDirectory(); } - finally - { + finally { blockOnIO(); } } - public int getJournalFileSize() - { + public int getJournalFileSize() { checkStarted(); clearIO(); - try - { + try { return configuration.getJournalFileSize(); } - finally - { + finally { blockOnIO(); } } - public int getJournalMinFiles() - { + public int getJournalMinFiles() { checkStarted(); clearIO(); - try - { + try { return configuration.getJournalMinFiles(); } - finally - { + finally { blockOnIO(); } } - public int getJournalCompactMinFiles() - { + public int getJournalCompactMinFiles() { checkStarted(); clearIO(); - try - { + try { return configuration.getJournalCompactMinFiles(); } - finally - { + finally { blockOnIO(); } } - public int getJournalCompactPercentage() - { + public int getJournalCompactPercentage() { checkStarted(); clearIO(); - try - { + try { return configuration.getJournalCompactPercentage(); } - finally - { + finally { blockOnIO(); } } - public boolean isPersistenceEnabled() - { + public boolean isPersistenceEnabled() { checkStarted(); clearIO(); - try - { + try { return configuration.isPersistenceEnabled(); } - finally - { + finally { blockOnIO(); } } - public String getJournalType() - { + public String getJournalType() { checkStarted(); clearIO(); - try - { + try { return configuration.getJournalType().toString(); } - finally - { + finally { blockOnIO(); } } - public String getPagingDirectory() - { + public String getPagingDirectory() { checkStarted(); clearIO(); - try - { + try { return configuration.getPagingDirectory(); } - finally - { + finally { blockOnIO(); } } - public int getScheduledThreadPoolMaxSize() - { + public int getScheduledThreadPoolMaxSize() { checkStarted(); clearIO(); - try - { + try { return configuration.getScheduledThreadPoolMaxSize(); } - finally - { + finally { blockOnIO(); } } - public int getThreadPoolMaxSize() - { + public int getThreadPoolMaxSize() { checkStarted(); clearIO(); - try - { + try { return configuration.getThreadPoolMaxSize(); } - finally - { + finally { blockOnIO(); } } - public long getSecurityInvalidationInterval() - { + public long getSecurityInvalidationInterval() { checkStarted(); clearIO(); - try - { + try { return configuration.getSecurityInvalidationInterval(); } - finally - { + finally { blockOnIO(); } } - public boolean isClustered() - { + public boolean isClustered() { checkStarted(); clearIO(); - try - { + try { return configuration.isClustered(); } - finally - { + finally { blockOnIO(); } } - public boolean isCreateBindingsDir() - { + public boolean isCreateBindingsDir() { checkStarted(); clearIO(); - try - { + try { return configuration.isCreateBindingsDir(); } - finally - { + finally { blockOnIO(); } } - public boolean isCreateJournalDir() - { + public boolean isCreateJournalDir() { checkStarted(); clearIO(); - try - { + try { return configuration.isCreateJournalDir(); } - finally - { + finally { blockOnIO(); } } - public boolean isJournalSyncNonTransactional() - { + public boolean isJournalSyncNonTransactional() { checkStarted(); clearIO(); - try - { + try { return configuration.isJournalSyncNonTransactional(); } - finally - { + finally { blockOnIO(); } } - public boolean isJournalSyncTransactional() - { + public boolean isJournalSyncTransactional() { checkStarted(); clearIO(); - try - { + try { return configuration.isJournalSyncTransactional(); } - finally - { + finally { blockOnIO(); } } - public boolean isSecurityEnabled() - { + public boolean isSecurityEnabled() { checkStarted(); clearIO(); - try - { + try { return configuration.isSecurityEnabled(); } - finally - { + finally { blockOnIO(); } } - public boolean isAsyncConnectionExecutionEnabled() - { + public boolean isAsyncConnectionExecutionEnabled() { checkStarted(); clearIO(); - try - { + try { return configuration.isAsyncConnectionExecutionEnabled(); } - finally - { + finally { blockOnIO(); } } - public void deployQueue(final String address, final String name, final String filterString) throws Exception - { + public void deployQueue(final String address, final String name, final String filterString) throws Exception { checkStarted(); clearIO(); - try - { - server.deployQueue(new SimpleString(address), - new SimpleString(name), - new SimpleString(filterString), - true, - false); + try { + server.deployQueue(new SimpleString(address), new SimpleString(name), new SimpleString(filterString), true, false); } - finally - { + finally { blockOnIO(); } } - public void deployQueue(final String address, final String name, final String filterStr, final boolean durable) throws Exception - { + public void deployQueue(final String address, + final String name, + final String filterStr, + final boolean durable) throws Exception { checkStarted(); SimpleString filter = filterStr == null ? null : new SimpleString(filterStr); clearIO(); - try - { + try { server.deployQueue(new SimpleString(address), new SimpleString(name), filter, durable, false); } - finally - { + finally { blockOnIO(); } } - public void createQueue(final String address, final String name) throws Exception - { + public void createQueue(final String address, final String name) throws Exception { checkStarted(); clearIO(); - try - { + try { server.createQueue(new SimpleString(address), new SimpleString(name), null, true, false); } - finally - { + finally { blockOnIO(); } } - public void createQueue(final String address, final String name, final boolean durable) throws Exception - { + public void createQueue(final String address, final String name, final boolean durable) throws Exception { checkStarted(); clearIO(); - try - { + try { server.createQueue(new SimpleString(address), new SimpleString(name), null, durable, false); } - finally - { + finally { blockOnIO(); } } - public void createQueue(final String address, final String name, final String filterStr, final boolean durable) throws Exception - { + public void createQueue(final String address, + final String name, + final String filterStr, + final boolean durable) throws Exception { checkStarted(); clearIO(); - try - { + try { SimpleString filter = null; - if (filterStr != null && !filterStr.trim().equals("")) - { + if (filterStr != null && !filterStr.trim().equals("")) { filter = new SimpleString(filterStr); } server.createQueue(new SimpleString(address), new SimpleString(name), filter, durable, false); } - finally - { + finally { blockOnIO(); } } - public String[] getQueueNames() - { + public String[] getQueueNames() { checkStarted(); clearIO(); - try - { + try { Object[] queues = server.getManagementService().getResources(QueueControl.class); String[] names = new String[queues.length]; - for (int i = 0; i < queues.length; i++) - { + for (int i = 0; i < queues.length; i++) { QueueControl queue = (QueueControl) queues[i]; names[i] = queue.getName(); } return names; } - finally - { + finally { blockOnIO(); } } - public String[] getAddressNames() - { + public String[] getAddressNames() { checkStarted(); clearIO(); - try - { + try { Object[] addresses = server.getManagementService().getResources(AddressControl.class); String[] names = new String[addresses.length]; - for (int i = 0; i < addresses.length; i++) - { + for (int i = 0; i < addresses.length; i++) { AddressControl address = (AddressControl) addresses[i]; names[i] = address.getAddress(); } return names; } - finally - { + finally { blockOnIO(); } } - public void destroyQueue(final String name) throws Exception - { + public void destroyQueue(final String name) throws Exception { checkStarted(); clearIO(); - try - { + try { SimpleString queueName = new SimpleString(name); server.destroyQueue(queueName, null, true); } - finally - { + finally { blockOnIO(); } } - public int getConnectionCount() - { + public int getConnectionCount() { checkStarted(); clearIO(); - try - { + try { return server.getConnectionCount(); } - finally - { + finally { blockOnIO(); } } - public void enableMessageCounters() - { + public void enableMessageCounters() { checkStarted(); clearIO(); - try - { + try { setMessageCounterEnabled(true); } - finally - { + finally { blockOnIO(); } } - public void disableMessageCounters() - { + public void disableMessageCounters() { checkStarted(); clearIO(); - try - { + try { setMessageCounterEnabled(false); } - finally - { + finally { blockOnIO(); } } - public void resetAllMessageCounters() - { + public void resetAllMessageCounters() { checkStarted(); clearIO(); - try - { + try { messageCounterManager.resetAllCounters(); } - finally - { + finally { blockOnIO(); } } - public void resetAllMessageCounterHistories() - { + public void resetAllMessageCounterHistories() { checkStarted(); clearIO(); - try - { + try { messageCounterManager.resetAllCounterHistories(); } - finally - { + finally { blockOnIO(); } } - public boolean isMessageCounterEnabled() - { + public boolean isMessageCounterEnabled() { checkStarted(); clearIO(); - try - { + try { return configuration.isMessageCounterEnabled(); } - finally - { + finally { blockOnIO(); } } - public synchronized long getMessageCounterSamplePeriod() - { + public synchronized long getMessageCounterSamplePeriod() { checkStarted(); clearIO(); - try - { + try { return messageCounterManager.getSamplePeriod(); } - finally - { + finally { blockOnIO(); } } - public synchronized void setMessageCounterSamplePeriod(final long newPeriod) - { + public synchronized void setMessageCounterSamplePeriod(final long newPeriod) { checkStarted(); checkStarted(); clearIO(); - try - { - if (newPeriod < MessageCounterManagerImpl.MIN_SAMPLE_PERIOD) - { + try { + if (newPeriod < MessageCounterManagerImpl.MIN_SAMPLE_PERIOD) { throw ActiveMQMessageBundle.BUNDLE.invalidMessageCounterPeriod(MessageCounterManagerImpl.MIN_SAMPLE_PERIOD); } - if (messageCounterManager != null && newPeriod != messageCounterManager.getSamplePeriod()) - { + if (messageCounterManager != null && newPeriod != messageCounterManager.getSamplePeriod()) { messageCounterManager.reschedule(newPeriod); } } - finally - { + finally { blockOnIO(); } } - public int getMessageCounterMaxDayCount() - { + public int getMessageCounterMaxDayCount() { checkStarted(); clearIO(); - try - { + try { return messageCounterManager.getMaxDayCount(); } - finally - { + finally { blockOnIO(); } } - public void setMessageCounterMaxDayCount(final int count) - { + public void setMessageCounterMaxDayCount(final int count) { checkStarted(); clearIO(); - try - { - if (count <= 0) - { + try { + if (count <= 0) { throw ActiveMQMessageBundle.BUNDLE.greaterThanZero(count); } messageCounterManager.setMaxDayCount(count); } - finally - { + finally { blockOnIO(); } } - public String[] listPreparedTransactions() - { + public String[] listPreparedTransactions() { checkStarted(); clearIO(); - try - { + try { DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM); Map xids = resourceManager.getPreparedTransactionsWithCreationTime(); ArrayList> xidsSortedByCreationTime = new ArrayList>(xids.entrySet()); - Collections.sort(xidsSortedByCreationTime, new Comparator>() - { - public int compare(final Entry entry1, final Entry entry2) - { + Collections.sort(xidsSortedByCreationTime, new Comparator>() { + public int compare(final Entry entry1, final Entry entry2) { // sort by creation time, oldest first return (int) (entry1.getValue() - entry2.getValue()); } }); String[] s = new String[xidsSortedByCreationTime.size()]; int i = 0; - for (Map.Entry entry : xidsSortedByCreationTime) - { + for (Map.Entry entry : xidsSortedByCreationTime) { Date creation = new Date(entry.getValue()); Xid xid = entry.getKey(); s[i++] = dateFormat.format(creation) + " base64: " + XidImpl.toBase64String(xid) + " " + xid.toString(); } return s; } - finally - { + finally { blockOnIO(); } } - public String listPreparedTransactionDetailsAsJSON() throws Exception - { + public String listPreparedTransactionDetailsAsJSON() throws Exception { checkStarted(); clearIO(); - try - { + try { Map xids = resourceManager.getPreparedTransactionsWithCreationTime(); - if (xids == null || xids.size() == 0) - { + if (xids == null || xids.size() == 0) { return ""; } ArrayList> xidsSortedByCreationTime = new ArrayList>(xids.entrySet()); - Collections.sort(xidsSortedByCreationTime, new Comparator>() - { - public int compare(final Entry entry1, final Entry entry2) - { + Collections.sort(xidsSortedByCreationTime, new Comparator>() { + public int compare(final Entry entry1, final Entry entry2) { // sort by creation time, oldest first return (int) (entry1.getValue() - entry2.getValue()); } }); JSONArray txDetailListJson = new JSONArray(); - for (Map.Entry entry : xidsSortedByCreationTime) - { + for (Map.Entry entry : xidsSortedByCreationTime) { Xid xid = entry.getKey(); - TransactionDetail detail = new CoreTransactionDetail(xid, - resourceManager.getTransaction(xid), - entry.getValue()); + TransactionDetail detail = new CoreTransactionDetail(xid, resourceManager.getTransaction(xid), entry.getValue()); txDetailListJson.put(detail.toJSON()); } return txDetailListJson.toString(); } - finally - { + finally { blockOnIO(); } } - public String listPreparedTransactionDetailsAsHTML() throws Exception - { + public String listPreparedTransactionDetailsAsHTML() throws Exception { checkStarted(); clearIO(); - try - { + try { Map xids = resourceManager.getPreparedTransactionsWithCreationTime(); - if (xids == null || xids.size() == 0) - { + if (xids == null || xids.size() == 0) { return "

    *** Prepared Transaction Details ***

    No entry.

    "; } ArrayList> xidsSortedByCreationTime = new ArrayList>(xids.entrySet()); - Collections.sort(xidsSortedByCreationTime, new Comparator>() - { - public int compare(final Entry entry1, final Entry entry2) - { + Collections.sort(xidsSortedByCreationTime, new Comparator>() { + public int compare(final Entry entry1, final Entry entry2) { // sort by creation time, oldest first return (int) (entry1.getValue() - entry2.getValue()); } @@ -1036,12 +852,9 @@ public class ActiveMQServerControlImpl extends AbstractControl implements Active StringBuilder html = new StringBuilder(); html.append("

    *** Prepared Transaction Details ***

    "); - for (Map.Entry entry : xidsSortedByCreationTime) - { + for (Map.Entry entry : xidsSortedByCreationTime) { Xid xid = entry.getKey(); - TransactionDetail detail = new CoreTransactionDetail(xid, - resourceManager.getTransaction(xid), - entry.getValue()); + TransactionDetail detail = new CoreTransactionDetail(xid, resourceManager.getTransaction(xid), entry.getValue()); JSONObject txJson = detail.toJSON(); @@ -1062,15 +875,13 @@ public class ActiveMQServerControlImpl extends AbstractControl implements Active html.append("

    "); JSONArray msgs = txJson.getJSONArray(TransactionDetail.KEY_TX_RELATED_MESSAGES); - for (int i = 0; i < msgs.length(); i++) - { + for (int i = 0; i < msgs.length(); i++) { JSONObject msgJson = msgs.getJSONObject(i); JSONObject props = msgJson.getJSONObject(TransactionDetail.KEY_MSG_PROPERTIES); StringBuilder propstr = new StringBuilder(); @SuppressWarnings("unchecked") Iterator propkeys = props.keys(); - while (propkeys.hasNext()) - { + while (propkeys.hasNext()) { String key = propkeys.next(); propstr.append(key); propstr.append("="); @@ -1091,69 +902,56 @@ public class ActiveMQServerControlImpl extends AbstractControl implements Active return html.toString(); } - finally - { + finally { blockOnIO(); } } - public String[] listHeuristicCommittedTransactions() - { + public String[] listHeuristicCommittedTransactions() { checkStarted(); clearIO(); - try - { + try { List xids = resourceManager.getHeuristicCommittedTransactions(); String[] s = new String[xids.size()]; int i = 0; - for (Xid xid : xids) - { + for (Xid xid : xids) { s[i++] = XidImpl.toBase64String(xid); } return s; } - finally - { + finally { blockOnIO(); } } - public String[] listHeuristicRolledBackTransactions() - { + public String[] listHeuristicRolledBackTransactions() { checkStarted(); clearIO(); - try - { + try { List xids = resourceManager.getHeuristicRolledbackTransactions(); String[] s = new String[xids.size()]; int i = 0; - for (Xid xid : xids) - { + for (Xid xid : xids) { s[i++] = XidImpl.toBase64String(xid); } return s; } - finally - { + finally { blockOnIO(); } } - public synchronized boolean commitPreparedTransaction(final String transactionAsBase64) throws Exception - { + public synchronized boolean commitPreparedTransaction(final String transactionAsBase64) throws Exception { checkStarted(); clearIO(); - try - { + try { List xids = resourceManager.getPreparedTransactions(); - for (Xid xid : xids) - { - if (XidImpl.toBase64String(xid).equals(transactionAsBase64)) - { + for (Xid xid : xids) { + if (XidImpl.toBase64String(xid).equals(transactionAsBase64)) { Transaction transaction = resourceManager.removeTransaction(xid); transaction.commit(false); long recordID = server.getStorageManager().storeHeuristicCompletion(xid, true); @@ -1164,26 +962,21 @@ public class ActiveMQServerControlImpl extends AbstractControl implements Active } return false; } - finally - { + finally { blockOnIO(); } } - public synchronized boolean rollbackPreparedTransaction(final String transactionAsBase64) throws Exception - { + public synchronized boolean rollbackPreparedTransaction(final String transactionAsBase64) throws Exception { checkStarted(); clearIO(); - try - { + try { List xids = resourceManager.getPreparedTransactions(); - for (Xid xid : xids) - { - if (XidImpl.toBase64String(xid).equals(transactionAsBase64)) - { + for (Xid xid : xids) { + if (XidImpl.toBase64String(xid).equals(transactionAsBase64)) { Transaction transaction = resourceManager.removeTransaction(xid); transaction.rollback(); long recordID = server.getStorageManager().storeHeuristicCompletion(xid, false); @@ -1194,76 +987,62 @@ public class ActiveMQServerControlImpl extends AbstractControl implements Active } return false; } - finally - { + finally { blockOnIO(); } } - public String[] listRemoteAddresses() - { + public String[] listRemoteAddresses() { checkStarted(); clearIO(); - try - { + try { Set connections = remotingService.getConnections(); String[] remoteAddresses = new String[connections.size()]; int i = 0; - for (RemotingConnection connection : connections) - { + for (RemotingConnection connection : connections) { remoteAddresses[i++] = connection.getRemoteAddress(); } return remoteAddresses; } - finally - { + finally { blockOnIO(); } } - public String[] listRemoteAddresses(final String ipAddress) - { + public String[] listRemoteAddresses(final String ipAddress) { checkStarted(); clearIO(); - try - { + try { Set connections = remotingService.getConnections(); List remoteConnections = new ArrayList(); - for (RemotingConnection connection : connections) - { + for (RemotingConnection connection : connections) { String remoteAddress = connection.getRemoteAddress(); - if (remoteAddress.contains(ipAddress)) - { + if (remoteAddress.contains(ipAddress)) { remoteConnections.add(connection.getRemoteAddress()); } } return remoteConnections.toArray(new String[remoteConnections.size()]); } - finally - { + finally { blockOnIO(); } } - public synchronized boolean closeConnectionsForAddress(final String ipAddress) - { + public synchronized boolean closeConnectionsForAddress(final String ipAddress) { checkStarted(); clearIO(); - try - { + try { boolean closed = false; Set connections = remotingService.getConnections(); - for (RemotingConnection connection : connections) - { + for (RemotingConnection connection : connections) { String remoteAddress = connection.getRemoteAddress(); - if (remoteAddress.contains(ipAddress)) - { + if (remoteAddress.contains(ipAddress)) { connection.fail(ActiveMQMessageBundle.BUNDLE.connectionsClosedByManagement(ipAddress)); remotingService.removeConnection(connection.getID()); closed = true; @@ -1272,43 +1051,33 @@ public class ActiveMQServerControlImpl extends AbstractControl implements Active return closed; } - finally - { + finally { blockOnIO(); } } - public synchronized boolean closeConsumerConnectionsForAddress(final String address) - { + public synchronized boolean closeConsumerConnectionsForAddress(final String address) { boolean closed = false; checkStarted(); clearIO(); - try - { - for (Binding binding : postOffice.getMatchingBindings(SimpleString.toSimpleString(address)).getBindings()) - { - if (binding instanceof LocalQueueBinding) - { + try { + for (Binding binding : postOffice.getMatchingBindings(SimpleString.toSimpleString(address)).getBindings()) { + if (binding instanceof LocalQueueBinding) { Queue queue = ((LocalQueueBinding) binding).getQueue(); - for (Consumer consumer : queue.getConsumers()) - { - if (consumer instanceof ServerConsumer) - { + for (Consumer consumer : queue.getConsumers()) { + if (consumer instanceof ServerConsumer) { ServerConsumer serverConsumer = (ServerConsumer) consumer; RemotingConnection connection = null; - for (RemotingConnection potentialConnection : remotingService.getConnections()) - { - if (potentialConnection.getID().toString().equals(serverConsumer.getConnectionID())) - { + for (RemotingConnection potentialConnection : remotingService.getConnections()) { + if (potentialConnection.getID().toString().equals(serverConsumer.getConnectionID())) { connection = potentialConnection; } } - if (connection != null) - { + if (connection != null) { remotingService.removeConnection(connection.getID()); connection.fail(ActiveMQMessageBundle.BUNDLE.consumerConnectionsClosedByManagement(address)); closed = true; @@ -1318,41 +1087,32 @@ public class ActiveMQServerControlImpl extends AbstractControl implements Active } } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.failedToCloseConsumerConnectionsForAddress(address, e); } - finally - { + finally { blockOnIO(); } return closed; } - public synchronized boolean closeConnectionsForUser(final String userName) - { + public synchronized boolean closeConnectionsForUser(final String userName) { boolean closed = false; checkStarted(); clearIO(); - try - { - for (ServerSession serverSession : server.getSessions()) - { - if (serverSession.getUsername() != null && serverSession.getUsername().equals(userName)) - { + try { + for (ServerSession serverSession : server.getSessions()) { + if (serverSession.getUsername() != null && serverSession.getUsername().equals(userName)) { RemotingConnection connection = null; - for (RemotingConnection potentialConnection : remotingService.getConnections()) - { - if (potentialConnection.getID().toString().equals(serverSession.getConnectionID().toString())) - { + for (RemotingConnection potentialConnection : remotingService.getConnections()) { + if (potentialConnection.getID().toString().equals(serverSession.getConnectionID().toString())) { connection = potentialConnection; } } - if (connection != null) - { + if (connection != null) { remotingService.removeConnection(connection.getID()); connection.fail(ActiveMQMessageBundle.BUNDLE.connectionsForUserClosedByManagement(userName)); closed = true; @@ -1360,90 +1120,72 @@ public class ActiveMQServerControlImpl extends AbstractControl implements Active } } } - finally - { + finally { blockOnIO(); } return closed; } - public String[] listConnectionIDs() - { + public String[] listConnectionIDs() { checkStarted(); clearIO(); - try - { + try { Set connections = remotingService.getConnections(); String[] connectionIDs = new String[connections.size()]; int i = 0; - for (RemotingConnection connection : connections) - { + for (RemotingConnection connection : connections) { connectionIDs[i++] = connection.getID().toString(); } return connectionIDs; } - finally - { + finally { blockOnIO(); } } - public String[] listSessions(final String connectionID) - { + public String[] listSessions(final String connectionID) { checkStarted(); clearIO(); - try - { + try { List sessions = server.getSessions(connectionID); String[] sessionIDs = new String[sessions.size()]; int i = 0; - for (ServerSession serverSession : sessions) - { + for (ServerSession serverSession : sessions) { sessionIDs[i++] = serverSession.getName(); } return sessionIDs; } - finally - { + finally { blockOnIO(); } } - /* (non-Javadoc) * @see org.apache.activemq.artemis.api.core.management.ActiveMQServerControl#listProducersInfoAsJSON() */ - public String listProducersInfoAsJSON() throws Exception - { + public String listProducersInfoAsJSON() throws Exception { JSONArray producers = new JSONArray(); - - for (ServerSession session : server.getSessions()) - { + for (ServerSession session : server.getSessions()) { session.describeProducersInfo(producers); } return producers.toString(); } - - public Object[] getConnectors() throws Exception - { + public Object[] getConnectors() throws Exception { checkStarted(); clearIO(); - try - { - Collection connectorConfigurations = configuration.getConnectorConfigurations() - .values(); + try { + Collection connectorConfigurations = configuration.getConnectorConfigurations().values(); Object[] ret = new Object[connectorConfigurations.size()]; int i = 0; - for (TransportConfiguration config : connectorConfigurations) - { + for (TransportConfiguration config : connectorConfigurations) { Object[] tc = new Object[3]; tc[0] = config.getName(); @@ -1455,30 +1197,25 @@ public class ActiveMQServerControlImpl extends AbstractControl implements Active return ret; } - finally - { + finally { blockOnIO(); } } - public String getConnectorsAsJSON() throws Exception - { + public String getConnectorsAsJSON() throws Exception { checkStarted(); clearIO(); - try - { + try { JSONArray array = new JSONArray(); - for (TransportConfiguration config : configuration.getConnectorConfigurations().values()) - { + for (TransportConfiguration config : configuration.getConnectorConfigurations().values()) { array.put(new JSONObject(config)); } return array.toString(); } - finally - { + finally { blockOnIO(); } } @@ -1490,123 +1227,86 @@ public class ActiveMQServerControlImpl extends AbstractControl implements Active final String deleteDurableQueueRoles, final String createNonDurableQueueRoles, final String deleteNonDurableQueueRoles, - final String manageRoles) throws Exception - { + final String manageRoles) throws Exception { checkStarted(); clearIO(); - try - { - Set roles = SecurityFormatter.createSecurity(sendRoles, - consumeRoles, - createDurableQueueRoles, - deleteDurableQueueRoles, - createNonDurableQueueRoles, - deleteNonDurableQueueRoles, - manageRoles); + try { + Set roles = SecurityFormatter.createSecurity(sendRoles, consumeRoles, createDurableQueueRoles, deleteDurableQueueRoles, createNonDurableQueueRoles, deleteNonDurableQueueRoles, manageRoles); server.getSecurityRepository().addMatch(addressMatch, roles); - PersistedRoles persistedRoles = new PersistedRoles(addressMatch, - sendRoles, - consumeRoles, - createDurableQueueRoles, - deleteDurableQueueRoles, - createNonDurableQueueRoles, - deleteNonDurableQueueRoles, - manageRoles); + PersistedRoles persistedRoles = new PersistedRoles(addressMatch, sendRoles, consumeRoles, createDurableQueueRoles, deleteDurableQueueRoles, createNonDurableQueueRoles, deleteNonDurableQueueRoles, manageRoles); storageManager.storeSecurityRoles(persistedRoles); } - finally - { + finally { blockOnIO(); } } - public void removeSecuritySettings(final String addressMatch) throws Exception - { + public void removeSecuritySettings(final String addressMatch) throws Exception { checkStarted(); clearIO(); - try - { + try { server.getSecurityRepository().removeMatch(addressMatch); storageManager.deleteSecurityRoles(new SimpleString(addressMatch)); } - finally - { + finally { blockOnIO(); } } - public Object[] getRoles(final String addressMatch) throws Exception - { + public Object[] getRoles(final String addressMatch) throws Exception { checkStarted(); checkStarted(); clearIO(); - try - { + try { Set roles = server.getSecurityRepository().getMatch(addressMatch); Object[] objRoles = new Object[roles.size()]; int i = 0; - for (Role role : roles) - { - objRoles[i++] = new Object[]{role.getName(), - CheckType.SEND.hasRole(role), - CheckType.CONSUME.hasRole(role), - CheckType.CREATE_DURABLE_QUEUE.hasRole(role), - CheckType.DELETE_DURABLE_QUEUE.hasRole(role), - CheckType.CREATE_NON_DURABLE_QUEUE.hasRole(role), - CheckType.DELETE_NON_DURABLE_QUEUE.hasRole(role), - CheckType.MANAGE.hasRole(role)}; + for (Role role : roles) { + objRoles[i++] = new Object[]{role.getName(), CheckType.SEND.hasRole(role), CheckType.CONSUME.hasRole(role), CheckType.CREATE_DURABLE_QUEUE.hasRole(role), CheckType.DELETE_DURABLE_QUEUE.hasRole(role), CheckType.CREATE_NON_DURABLE_QUEUE.hasRole(role), CheckType.DELETE_NON_DURABLE_QUEUE.hasRole(role), CheckType.MANAGE.hasRole(role)}; } return objRoles; } - finally - { + finally { blockOnIO(); } } - public String getRolesAsJSON(final String addressMatch) throws Exception - { + public String getRolesAsJSON(final String addressMatch) throws Exception { checkStarted(); clearIO(); - try - { + try { JSONArray json = new JSONArray(); Set roles = server.getSecurityRepository().getMatch(addressMatch); - for (Role role : roles) - { + for (Role role : roles) { json.put(new JSONObject(role)); } return json.toString(); } - finally - { + finally { blockOnIO(); } } - public String getAddressSettingsAsJSON(final String address) throws Exception - { + public String getAddressSettingsAsJSON(final String address) throws Exception { checkStarted(); AddressSettings addressSettings = server.getAddressSettingsRepository().getMatch(address); Map settings = new HashMap(); - if (addressSettings.getDeadLetterAddress() != null) - { + if (addressSettings.getDeadLetterAddress() != null) { settings.put("DLA", addressSettings.getDeadLetterAddress()); } - if (addressSettings.getExpiryAddress() != null) - { + if (addressSettings.getExpiryAddress() != null) { settings.put("expiryAddress", addressSettings.getExpiryAddress()); } settings.put("expiryDelay", addressSettings.getExpiryDelay()); @@ -1620,15 +1320,11 @@ public class ActiveMQServerControlImpl extends AbstractControl implements Active settings.put("redistributionDelay", addressSettings.getRedistributionDelay()); settings.put("lastValueQueue", addressSettings.isLastValueQueue()); settings.put("sendToDLAOnNoRoute", addressSettings.isSendToDLAOnNoRoute()); - String policy = addressSettings.getAddressFullMessagePolicy() == AddressFullMessagePolicy.PAGE ? "PAGE" - : addressSettings.getAddressFullMessagePolicy() == AddressFullMessagePolicy.BLOCK ? "BLOCK" - : addressSettings.getAddressFullMessagePolicy() == AddressFullMessagePolicy.DROP ? "DROP" - : "FAIL"; + String policy = addressSettings.getAddressFullMessagePolicy() == AddressFullMessagePolicy.PAGE ? "PAGE" : addressSettings.getAddressFullMessagePolicy() == AddressFullMessagePolicy.BLOCK ? "BLOCK" : addressSettings.getAddressFullMessagePolicy() == AddressFullMessagePolicy.DROP ? "DROP" : "FAIL"; settings.put("addressFullMessagePolicy", policy); settings.put("slowConsumerThreshold", addressSettings.getSlowConsumerThreshold()); settings.put("slowConsumerCheckPeriod", addressSettings.getSlowConsumerCheckPeriod()); - policy = addressSettings.getSlowConsumerPolicy() == SlowConsumerPolicy.NOTIFY ? "NOTIFY" - : "KILL"; + policy = addressSettings.getSlowConsumerPolicy() == SlowConsumerPolicy.NOTIFY ? "NOTIFY" : "KILL"; settings.put("slowConsumerPolicy", policy); settings.put("autoCreateJmsQueues", addressSettings.isAutoCreateJmsQueues()); settings.put("autoDeleteJmsQueues", addressSettings.isAutoDeleteJmsQueues()); @@ -1637,7 +1333,6 @@ public class ActiveMQServerControlImpl extends AbstractControl implements Active return jsonObject.toString(); } - public void addAddressSettings(final String address, final String DLA, final String expiryAddress, @@ -1657,18 +1352,15 @@ public class ActiveMQServerControlImpl extends AbstractControl implements Active final long slowConsumerCheckPeriod, final String slowConsumerPolicy, final boolean autoCreateJmsQueues, - final boolean autoDeleteJmsQueues) throws Exception - { + final boolean autoDeleteJmsQueues) throws Exception { checkStarted(); // JBPAPP-6334 requested this to be pageSizeBytes > maxSizeBytes - if (pageSizeBytes > maxSizeBytes && maxSizeBytes > 0) - { + if (pageSizeBytes > maxSizeBytes && maxSizeBytes > 0) { throw new IllegalStateException("pageSize has to be lower than maxSizeBytes. Invalid argument (" + pageSizeBytes + " < " + maxSizeBytes + ")"); } - if (maxSizeBytes < -1) - { + if (maxSizeBytes < -1) { throw new IllegalStateException("Invalid argument on maxSizeBytes"); } @@ -1686,38 +1378,30 @@ public class ActiveMQServerControlImpl extends AbstractControl implements Active addressSettings.setMaxRedeliveryDelay(maxRedeliveryDelay); addressSettings.setRedistributionDelay(redistributionDelay); addressSettings.setSendToDLAOnNoRoute(sendToDLAOnNoRoute); - if (addressFullMessagePolicy == null) - { + if (addressFullMessagePolicy == null) { addressSettings.setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE); } - else if (addressFullMessagePolicy.equalsIgnoreCase("PAGE")) - { + else if (addressFullMessagePolicy.equalsIgnoreCase("PAGE")) { addressSettings.setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE); } - else if (addressFullMessagePolicy.equalsIgnoreCase("DROP")) - { + else if (addressFullMessagePolicy.equalsIgnoreCase("DROP")) { addressSettings.setAddressFullMessagePolicy(AddressFullMessagePolicy.DROP); } - else if (addressFullMessagePolicy.equalsIgnoreCase("BLOCK")) - { + else if (addressFullMessagePolicy.equalsIgnoreCase("BLOCK")) { addressSettings.setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK); } - else if (addressFullMessagePolicy.equalsIgnoreCase("FAIL")) - { + else if (addressFullMessagePolicy.equalsIgnoreCase("FAIL")) { addressSettings.setAddressFullMessagePolicy(AddressFullMessagePolicy.FAIL); } addressSettings.setSlowConsumerThreshold(slowConsumerThreshold); addressSettings.setSlowConsumerCheckPeriod(slowConsumerCheckPeriod); - if (slowConsumerPolicy == null) - { + if (slowConsumerPolicy == null) { addressSettings.setSlowConsumerPolicy(SlowConsumerPolicy.NOTIFY); } - else if (slowConsumerPolicy.equalsIgnoreCase("NOTIFY")) - { + else if (slowConsumerPolicy.equalsIgnoreCase("NOTIFY")) { addressSettings.setSlowConsumerPolicy(SlowConsumerPolicy.NOTIFY); } - else if (slowConsumerPolicy.equalsIgnoreCase("KILL")) - { + else if (slowConsumerPolicy.equalsIgnoreCase("KILL")) { addressSettings.setSlowConsumerPolicy(SlowConsumerPolicy.KILL); } addressSettings.setAutoCreateJmsQueues(autoCreateJmsQueues); @@ -1727,56 +1411,47 @@ public class ActiveMQServerControlImpl extends AbstractControl implements Active storageManager.storeAddressSetting(new PersistedAddressSetting(new SimpleString(address), addressSettings)); } - public void removeAddressSettings(final String addressMatch) throws Exception - { + public void removeAddressSettings(final String addressMatch) throws Exception { checkStarted(); server.getAddressSettingsRepository().removeMatch(addressMatch); storageManager.deleteAddressSetting(new SimpleString(addressMatch)); } - public void sendQueueInfoToQueue(final String queueName, final String address) throws Exception - { + public void sendQueueInfoToQueue(final String queueName, final String address) throws Exception { checkStarted(); clearIO(); - try - { + try { postOffice.sendQueueInfoToQueue(new SimpleString(queueName), new SimpleString(address)); GroupingHandler handler = server.getGroupingHandler(); - if (handler != null) - { + if (handler != null) { // the group handler would miss responses if the group was requested before the reset was done // on that case we ask the groupinghandler to replay its send in case it's waiting for the information handler.resendPending(); } } - finally - { + finally { blockOnIO(); } } - public String[] getDivertNames() - { + public String[] getDivertNames() { checkStarted(); clearIO(); - try - { + try { Object[] diverts = server.getManagementService().getResources(DivertControl.class); String[] names = new String[diverts.length]; - for (int i = 0; i < diverts.length; i++) - { + for (int i = 0; i < diverts.length; i++) { DivertControl divert = (DivertControl) diverts[i]; names[i] = divert.getUniqueName(); } return names; } - finally - { + finally { blockOnIO(); } } @@ -1787,63 +1462,46 @@ public class ActiveMQServerControlImpl extends AbstractControl implements Active final String forwardingAddress, final boolean exclusive, final String filterString, - final String transformerClassName) throws Exception - { + final String transformerClassName) throws Exception { checkStarted(); clearIO(); - try - { - DivertConfiguration config = new DivertConfiguration() - .setName(name) - .setRoutingName(routingName) - .setAddress(address) - .setForwardingAddress(forwardingAddress) - .setExclusive(exclusive) - .setFilterString(filterString) - .setTransformerClassName(transformerClassName); + try { + DivertConfiguration config = new DivertConfiguration().setName(name).setRoutingName(routingName).setAddress(address).setForwardingAddress(forwardingAddress).setExclusive(exclusive).setFilterString(filterString).setTransformerClassName(transformerClassName); server.deployDivert(config); } - finally - { + finally { blockOnIO(); } } - public void destroyDivert(final String name) throws Exception - { + public void destroyDivert(final String name) throws Exception { checkStarted(); clearIO(); - try - { + try { server.destroyDivert(SimpleString.toSimpleString(name)); } - finally - { + finally { blockOnIO(); } } - public String[] getBridgeNames() - { + public String[] getBridgeNames() { checkStarted(); clearIO(); - try - { + try { Object[] bridges = server.getManagementService().getResources(BridgeControl.class); String[] names = new String[bridges.length]; - for (int i = 0; i < bridges.length; i++) - { + for (int i = 0; i < bridges.length; i++) { BridgeControl bridge = (BridgeControl) bridges[i]; names[i] = bridge.getName(); } return names; } - finally - { + finally { blockOnIO(); } } @@ -1864,66 +1522,41 @@ public class ActiveMQServerControlImpl extends AbstractControl implements Active boolean useDiscoveryGroup, final boolean ha, final String user, - final String password) throws Exception - { + final String password) throws Exception { checkStarted(); clearIO(); - try - { - BridgeConfiguration config = new BridgeConfiguration() - .setName(name) - .setQueueName(queueName) - .setForwardingAddress(forwardingAddress) - .setFilterString(filterString) - .setTransformerClassName(transformerClassName) - .setClientFailureCheckPeriod(clientFailureCheckPeriod) - .setRetryInterval(retryInterval) - .setRetryIntervalMultiplier(retryIntervalMultiplier) - .setInitialConnectAttempts(initialConnectAttempts) - .setReconnectAttempts(reconnectAttempts) - .setUseDuplicateDetection(useDuplicateDetection) - .setConfirmationWindowSize(confirmationWindowSize) - .setHA(ha) - .setUser(user) - .setPassword(password); + try { + BridgeConfiguration config = new BridgeConfiguration().setName(name).setQueueName(queueName).setForwardingAddress(forwardingAddress).setFilterString(filterString).setTransformerClassName(transformerClassName).setClientFailureCheckPeriod(clientFailureCheckPeriod).setRetryInterval(retryInterval).setRetryIntervalMultiplier(retryIntervalMultiplier).setInitialConnectAttempts(initialConnectAttempts).setReconnectAttempts(reconnectAttempts).setUseDuplicateDetection(useDuplicateDetection).setConfirmationWindowSize(confirmationWindowSize).setHA(ha).setUser(user).setPassword(password); - if (useDiscoveryGroup) - { + if (useDiscoveryGroup) { config.setDiscoveryGroupName(staticConnectorsOrDiscoveryGroup); } - else - { + else { config.setStaticConnectors(toList(staticConnectorsOrDiscoveryGroup)); } server.deployBridge(config); } - finally - { + finally { blockOnIO(); } } - - public void destroyBridge(final String name) throws Exception - { + public void destroyBridge(final String name) throws Exception { checkStarted(); clearIO(); - try - { + try { server.destroyBridge(name); } - finally - { + finally { blockOnIO(); } } - public void forceFailover() throws Exception - { + public void forceFailover() throws Exception { checkStarted(); clearIO(); @@ -1932,43 +1565,35 @@ public class ActiveMQServerControlImpl extends AbstractControl implements Active } @Override - public void updateDuplicateIdCache(String address, Object[] ids) throws Exception - { + public void updateDuplicateIdCache(String address, Object[] ids) throws Exception { clearIO(); - try - { + try { DuplicateIDCache duplicateIDCache = server.getPostOffice().getDuplicateIDCache(new SimpleString(address)); - for (Object id : ids) - { - duplicateIDCache.addToCache(((String)id).getBytes(), null); + for (Object id : ids) { + duplicateIDCache.addToCache(((String) id).getBytes(), null); } } - finally - { + finally { blockOnIO(); } } @Override - public void scaleDown(String connector) throws Exception - { + public void scaleDown(String connector) throws Exception { checkStarted(); clearIO(); HAPolicy haPolicy = server.getHAPolicy(); - if (haPolicy instanceof LiveOnlyPolicy) - { + if (haPolicy instanceof LiveOnlyPolicy) { LiveOnlyPolicy liveOnlyPolicy = (LiveOnlyPolicy) haPolicy; - if (liveOnlyPolicy.getScaleDownPolicy() == null) - { + if (liveOnlyPolicy.getScaleDownPolicy() == null) { liveOnlyPolicy.setScaleDownPolicy(new ScaleDownPolicy()); } liveOnlyPolicy.getScaleDownPolicy().setEnabled(true); - if (connector != null) - { + if (connector != null) { liveOnlyPolicy.getScaleDownPolicy().getConnectors().add(0, connector); } @@ -1981,58 +1606,45 @@ public class ActiveMQServerControlImpl extends AbstractControl implements Active public void removeNotificationListener(final NotificationListener listener, final NotificationFilter filter, - final Object handback) throws ListenerNotFoundException - { + final Object handback) throws ListenerNotFoundException { clearIO(); - try - { + try { broadcaster.removeNotificationListener(listener, filter, handback); } - finally - { + finally { blockOnIO(); } } - public void removeNotificationListener(final NotificationListener listener) throws ListenerNotFoundException - { + public void removeNotificationListener(final NotificationListener listener) throws ListenerNotFoundException { clearIO(); - try - { + try { broadcaster.removeNotificationListener(listener); } - finally - { + finally { blockOnIO(); } } public void addNotificationListener(final NotificationListener listener, final NotificationFilter filter, - final Object handback) throws IllegalArgumentException - { + final Object handback) throws IllegalArgumentException { clearIO(); - try - { + try { broadcaster.addNotificationListener(listener, filter, handback); } - finally - { + finally { blockOnIO(); } } - public MBeanNotificationInfo[] getNotificationInfo() - { + public MBeanNotificationInfo[] getNotificationInfo() { CoreNotificationType[] values = CoreNotificationType.values(); String[] names = new String[values.length]; - for (int i = 0; i < values.length; i++) - { + for (int i = 0; i < values.length; i++) { names[i] = values[i].toString(); } - return new MBeanNotificationInfo[]{new MBeanNotificationInfo(names, - this.getClass().getName(), - "Notifications emitted by a Core Server")}; + return new MBeanNotificationInfo[]{new MBeanNotificationInfo(names, this.getClass().getName(), "Notifications emitted by a Core Server")}; } // Package protected --------------------------------------------- @@ -2041,29 +1653,23 @@ public class ActiveMQServerControlImpl extends AbstractControl implements Active // Private ------------------------------------------------------- - private synchronized void setMessageCounterEnabled(final boolean enable) - { - if (isStarted()) - { - if (configuration.isMessageCounterEnabled() && !enable) - { + private synchronized void setMessageCounterEnabled(final boolean enable) { + if (isStarted()) { + if (configuration.isMessageCounterEnabled() && !enable) { stopMessageCounters(); } - else if (!configuration.isMessageCounterEnabled() && enable) - { + else if (!configuration.isMessageCounterEnabled() && enable) { startMessageCounters(); } } configuration.setMessageCounterEnabled(enable); } - private void startMessageCounters() - { + private void startMessageCounters() { messageCounterManager.start(); } - private void stopMessageCounters() - { + private void stopMessageCounters() { messageCounterManager.stop(); messageCounterManager.resetAllCounters(); @@ -2071,114 +1677,93 @@ public class ActiveMQServerControlImpl extends AbstractControl implements Active messageCounterManager.resetAllCounterHistories(); } - public long getConnectionTTLOverride() - { + public long getConnectionTTLOverride() { return configuration.getConnectionTTLOverride(); } - public int getIDCacheSize() - { + public int getIDCacheSize() { return configuration.getIDCacheSize(); } - public String getLargeMessagesDirectory() - { + public String getLargeMessagesDirectory() { return configuration.getLargeMessagesDirectory(); } - public String getManagementAddress() - { + public String getManagementAddress() { return configuration.getManagementAddress().toString(); } - public String getManagementNotificationAddress() - { + public String getManagementNotificationAddress() { return configuration.getManagementNotificationAddress().toString(); } - public long getMessageExpiryScanPeriod() - { + public long getMessageExpiryScanPeriod() { return configuration.getMessageExpiryScanPeriod(); } - public long getMessageExpiryThreadPriority() - { + public long getMessageExpiryThreadPriority() { return configuration.getMessageExpiryThreadPriority(); } - public long getTransactionTimeout() - { + public long getTransactionTimeout() { return configuration.getTransactionTimeout(); } - public long getTransactionTimeoutScanPeriod() - { + public long getTransactionTimeoutScanPeriod() { return configuration.getTransactionTimeoutScanPeriod(); } - public boolean isPersistDeliveryCountBeforeDelivery() - { + public boolean isPersistDeliveryCountBeforeDelivery() { return configuration.isPersistDeliveryCountBeforeDelivery(); } - public boolean isPersistIDCache() - { + public boolean isPersistIDCache() { return configuration.isPersistIDCache(); } - public boolean isWildcardRoutingEnabled() - { + public boolean isWildcardRoutingEnabled() { return configuration.isWildcardRoutingEnabled(); } @Override - protected MBeanOperationInfo[] fillMBeanOperationInfo() - { + protected MBeanOperationInfo[] fillMBeanOperationInfo() { return MBeanInfoHelper.getMBeanOperationsInfo(ActiveMQServerControl.class); } - private void checkStarted() - { - if (!server.isStarted()) - { + private void checkStarted() { + if (!server.isStarted()) { throw new IllegalStateException("Broker is not started. It can not be managed yet"); } } - public String[] listTargetAddresses(final String sessionID) - { + public String[] listTargetAddresses(final String sessionID) { ServerSession session = server.getSessionByID(sessionID); - if (session != null) - { + if (session != null) { return session.getTargetAddresses(); } return new String[0]; } - private static List toList(final String commaSeparatedString) - { + private static List toList(final String commaSeparatedString) { List list = new ArrayList(); - if (commaSeparatedString == null || commaSeparatedString.trim().length() == 0) - { + if (commaSeparatedString == null || commaSeparatedString.trim().length() == 0) { return list; } String[] values = commaSeparatedString.split(","); - for (String value : values) - { + for (String value : values) { list.add(value.trim()); } return list; } @Override - public void onNotification(org.apache.activemq.artemis.core.server.management.Notification notification) - { - if (!(notification.getType() instanceof CoreNotificationType)) return; + public void onNotification(org.apache.activemq.artemis.core.server.management.Notification notification) { + if (!(notification.getType() instanceof CoreNotificationType)) + return; CoreNotificationType type = (CoreNotificationType) notification.getType(); TypedProperties prop = notification.getProperties(); - this.broadcaster.sendNotification(new Notification(type.toString(), this, - notifSeq.incrementAndGet(), notification.toString())); + this.broadcaster.sendNotification(new Notification(type.toString(), this, notifSeq.incrementAndGet(), notification.toString())); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/AddressControlImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/AddressControlImpl.java index b700051c20..382adc3ef0 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/AddressControlImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/AddressControlImpl.java @@ -36,8 +36,7 @@ import org.apache.activemq.artemis.core.settings.HierarchicalRepository; import org.apache.activemq.artemis.utils.json.JSONArray; import org.apache.activemq.artemis.utils.json.JSONObject; -public class AddressControlImpl extends AbstractControl implements AddressControl -{ +public class AddressControlImpl extends AbstractControl implements AddressControl { // Constants ----------------------------------------------------- @@ -59,8 +58,7 @@ public class AddressControlImpl extends AbstractControl implements AddressContro final PostOffice postOffice, final PagingManager pagingManager, final StorageManager storageManager, - final HierarchicalRepository> securityRepository) throws Exception - { + final HierarchicalRepository> securityRepository) throws Exception { super(AddressControl.class, storageManager); this.address = address; this.postOffice = postOffice; @@ -72,203 +70,153 @@ public class AddressControlImpl extends AbstractControl implements AddressContro // AddressControlMBean implementation ---------------------------- - public String getAddress() - { + public String getAddress() { return address.toString(); } - public String[] getQueueNames() throws Exception - { + public String[] getQueueNames() throws Exception { clearIO(); - try - { + try { Bindings bindings = postOffice.getBindingsForAddress(address); List queueNames = new ArrayList(); - for (Binding binding : bindings.getBindings()) - { - if (binding instanceof QueueBinding) - { + for (Binding binding : bindings.getBindings()) { + if (binding instanceof QueueBinding) { queueNames.add(binding.getUniqueName().toString()); } } return queueNames.toArray(new String[queueNames.size()]); } - catch (Throwable t) - { + catch (Throwable t) { throw new IllegalStateException(t.getMessage()); } - finally - { + finally { blockOnIO(); } } - public String[] getBindingNames() throws Exception - { + public String[] getBindingNames() throws Exception { clearIO(); - try - { + try { Bindings bindings = postOffice.getBindingsForAddress(address); String[] bindingNames = new String[bindings.getBindings().size()]; int i = 0; - for (Binding binding : bindings.getBindings()) - { + for (Binding binding : bindings.getBindings()) { bindingNames[i++] = binding.getUniqueName().toString(); } return bindingNames; } - catch (Throwable t) - { + catch (Throwable t) { throw new IllegalStateException(t.getMessage()); } - finally - { + finally { blockOnIO(); } } - public Object[] getRoles() throws Exception - { + public Object[] getRoles() throws Exception { clearIO(); - try - { + try { Set roles = securityRepository.getMatch(address.toString()); Object[] objRoles = new Object[roles.size()]; int i = 0; - for (Role role : roles) - { - objRoles[i++] = new Object[]{ - role.getName(), - CheckType.SEND.hasRole(role), - CheckType.CONSUME.hasRole(role), - CheckType.CREATE_DURABLE_QUEUE.hasRole(role), - CheckType.DELETE_DURABLE_QUEUE.hasRole(role), - CheckType.CREATE_NON_DURABLE_QUEUE.hasRole(role), - CheckType.DELETE_NON_DURABLE_QUEUE.hasRole(role), - CheckType.MANAGE.hasRole(role)}; + for (Role role : roles) { + objRoles[i++] = new Object[]{role.getName(), CheckType.SEND.hasRole(role), CheckType.CONSUME.hasRole(role), CheckType.CREATE_DURABLE_QUEUE.hasRole(role), CheckType.DELETE_DURABLE_QUEUE.hasRole(role), CheckType.CREATE_NON_DURABLE_QUEUE.hasRole(role), CheckType.DELETE_NON_DURABLE_QUEUE.hasRole(role), CheckType.MANAGE.hasRole(role)}; } return objRoles; } - finally - { + finally { blockOnIO(); } } - public String getRolesAsJSON() throws Exception - { + public String getRolesAsJSON() throws Exception { clearIO(); - try - { + try { JSONArray json = new JSONArray(); Set roles = securityRepository.getMatch(address.toString()); - for (Role role : roles) - { + for (Role role : roles) { json.put(new JSONObject(role)); } return json.toString(); } - finally - { + finally { blockOnIO(); } } - public long getNumberOfBytesPerPage() throws Exception - { + public long getNumberOfBytesPerPage() throws Exception { clearIO(); - try - { + try { return pagingManager.getPageStore(address).getPageSizeBytes(); } - finally - { + finally { blockOnIO(); } } - public long getAddressSize() throws Exception - { + public long getAddressSize() throws Exception { clearIO(); - try - { + try { return pagingManager.getPageStore(address).getAddressSize(); } - finally - { + finally { blockOnIO(); } } - public long getNumberOfMessages() throws Exception - { + public long getNumberOfMessages() throws Exception { clearIO(); long totalMsgs = 0; - try - { + try { Bindings bindings = postOffice.getBindingsForAddress(address); List queueNames = new ArrayList(); - for (Binding binding : bindings.getBindings()) - { - if (binding instanceof QueueBinding) - { + for (Binding binding : bindings.getBindings()) { + if (binding instanceof QueueBinding) { totalMsgs += ((QueueBinding) binding).getQueue().getMessageCount(); } } return totalMsgs; } - catch (Throwable t) - { + catch (Throwable t) { throw new IllegalStateException(t.getMessage()); } - finally - { + finally { blockOnIO(); } } - - public boolean isPaging() throws Exception - { + public boolean isPaging() throws Exception { clearIO(); - try - { + try { return pagingManager.getPageStore(address).isPaging(); } - finally - { + finally { blockOnIO(); } } - public int getNumberOfPages() throws Exception - { + public int getNumberOfPages() throws Exception { clearIO(); - try - { + try { PagingStore pageStore = pagingManager.getPageStore(address); - if (!pageStore.isPaging()) - { + if (!pageStore.isPaging()) { return 0; } - else - { + else { return pagingManager.getPageStore(address).getNumberOfPages(); } } - finally - { + finally { blockOnIO(); } } @Override - protected MBeanOperationInfo[] fillMBeanOperationInfo() - { + protected MBeanOperationInfo[] fillMBeanOperationInfo() { return MBeanInfoHelper.getMBeanOperationsInfo(AddressControl.class); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/BridgeControlImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/BridgeControlImpl.java index 99d96bda09..01c37ce6f8 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/BridgeControlImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/BridgeControlImpl.java @@ -23,8 +23,7 @@ import org.apache.activemq.artemis.core.config.BridgeConfiguration; import org.apache.activemq.artemis.core.persistence.StorageManager; import org.apache.activemq.artemis.core.server.cluster.Bridge; -public class BridgeControlImpl extends AbstractControl implements BridgeControl -{ +public class BridgeControlImpl extends AbstractControl implements BridgeControl { // Constants ----------------------------------------------------- @@ -40,8 +39,7 @@ public class BridgeControlImpl extends AbstractControl implements BridgeControl public BridgeControlImpl(final Bridge bridge, final StorageManager storageManager, - final BridgeConfiguration configuration) throws Exception - { + final BridgeConfiguration configuration) throws Exception { super(BridgeControl.class, storageManager); this.bridge = bridge; this.configuration = configuration; @@ -49,205 +47,159 @@ public class BridgeControlImpl extends AbstractControl implements BridgeControl // BridgeControlMBean implementation --------------------------- - public String[] getStaticConnectors() throws Exception - { + public String[] getStaticConnectors() throws Exception { clearIO(); - try - { + try { return configuration.getStaticConnectors().toArray(new String[0]); } - finally - { + finally { blockOnIO(); } } - public String getForwardingAddress() - { + public String getForwardingAddress() { clearIO(); - try - { + try { return configuration.getForwardingAddress(); } - finally - { + finally { blockOnIO(); } } - public String getQueueName() - { + public String getQueueName() { clearIO(); - try - { + try { return configuration.getQueueName(); } - finally - { + finally { blockOnIO(); } } - public String getDiscoveryGroupName() - { + public String getDiscoveryGroupName() { clearIO(); - try - { + try { return configuration.getDiscoveryGroupName(); } - finally - { + finally { blockOnIO(); } } - public String getFilterString() - { + public String getFilterString() { clearIO(); - try - { + try { return configuration.getFilterString(); } - finally - { + finally { blockOnIO(); } } - public int getReconnectAttempts() - { + public int getReconnectAttempts() { clearIO(); - try - { + try { return configuration.getReconnectAttempts(); } - finally - { + finally { blockOnIO(); } } - public String getName() - { + public String getName() { clearIO(); - try - { + try { return configuration.getName(); } - finally - { + finally { blockOnIO(); } } - public long getRetryInterval() - { + public long getRetryInterval() { clearIO(); - try - { + try { return configuration.getRetryInterval(); } - finally - { + finally { blockOnIO(); } } - public double getRetryIntervalMultiplier() - { + public double getRetryIntervalMultiplier() { clearIO(); - try - { + try { return configuration.getRetryIntervalMultiplier(); } - finally - { + finally { blockOnIO(); } } - public String getTransformerClassName() - { + public String getTransformerClassName() { clearIO(); - try - { + try { return configuration.getTransformerClassName(); } - finally - { + finally { blockOnIO(); } } - public boolean isStarted() - { + public boolean isStarted() { clearIO(); - try - { + try { return bridge.isStarted(); } - finally - { + finally { blockOnIO(); } } - public boolean isUseDuplicateDetection() - { + public boolean isUseDuplicateDetection() { clearIO(); - try - { + try { return configuration.isUseDuplicateDetection(); } - finally - { + finally { blockOnIO(); } } - public boolean isHA() - { + public boolean isHA() { clearIO(); - try - { + try { return configuration.isHA(); } - finally - { + finally { blockOnIO(); } } - public void start() throws Exception - { + public void start() throws Exception { clearIO(); - try - { + try { bridge.start(); } - finally - { + finally { blockOnIO(); } } - public void stop() throws Exception - { + public void stop() throws Exception { clearIO(); - try - { + try { bridge.stop(); bridge.flushExecutor(); } - finally - { + finally { blockOnIO(); } } @Override - protected MBeanOperationInfo[] fillMBeanOperationInfo() - { + protected MBeanOperationInfo[] fillMBeanOperationInfo() { return MBeanInfoHelper.getMBeanOperationsInfo(BridgeControl.class); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/BroadcastGroupControlImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/BroadcastGroupControlImpl.java index 59de62577d..5e42771d86 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/BroadcastGroupControlImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/BroadcastGroupControlImpl.java @@ -25,8 +25,7 @@ import org.apache.activemq.artemis.core.persistence.StorageManager; import org.apache.activemq.artemis.core.server.cluster.BroadcastGroup; import org.apache.activemq.artemis.utils.json.JSONArray; -public class BroadcastGroupControlImpl extends AbstractControl implements BroadcastGroupControl -{ +public class BroadcastGroupControlImpl extends AbstractControl implements BroadcastGroupControl { // Constants ----------------------------------------------------- @@ -42,8 +41,7 @@ public class BroadcastGroupControlImpl extends AbstractControl implements Broadc public BroadcastGroupControlImpl(final BroadcastGroup broadcastGroup, final StorageManager storageManager, - final BroadcastGroupConfiguration configuration) throws Exception - { + final BroadcastGroupConfiguration configuration) throws Exception { super(BroadcastGroupControl.class, storageManager); this.broadcastGroup = broadcastGroup; this.configuration = configuration; @@ -51,168 +49,132 @@ public class BroadcastGroupControlImpl extends AbstractControl implements Broadc // BroadcastGroupControlMBean implementation --------------------- - public String getName() - { + public String getName() { clearIO(); - try - { + try { return configuration.getName(); } - finally - { + finally { blockOnIO(); } } - public long getBroadcastPeriod() - { + public long getBroadcastPeriod() { clearIO(); - try - { + try { return configuration.getBroadcastPeriod(); } - finally - { + finally { blockOnIO(); } } - public Object[] getConnectorPairs() - { + public Object[] getConnectorPairs() { clearIO(); - try - { + try { Object[] ret = new Object[configuration.getConnectorInfos().size()]; int i = 0; - for (String connector : configuration.getConnectorInfos()) - { + for (String connector : configuration.getConnectorInfos()) { ret[i++] = connector; } return ret; } - finally - { + finally { blockOnIO(); } } - public String getConnectorPairsAsJSON() throws Exception - { + public String getConnectorPairsAsJSON() throws Exception { clearIO(); - try - { + try { JSONArray array = new JSONArray(); - for (String connector : configuration.getConnectorInfos()) - { + for (String connector : configuration.getConnectorInfos()) { array.put(connector); } return array.toString(); } - finally - { + finally { blockOnIO(); } } //todo ghoward we should deal with this properly - public String getGroupAddress() throws Exception - { + public String getGroupAddress() throws Exception { clearIO(); - try - { - if (configuration.getEndpointFactory() instanceof UDPBroadcastEndpointFactory) - { - return ((UDPBroadcastEndpointFactory)configuration.getEndpointFactory()).getGroupAddress(); + try { + if (configuration.getEndpointFactory() instanceof UDPBroadcastEndpointFactory) { + return ((UDPBroadcastEndpointFactory) configuration.getEndpointFactory()).getGroupAddress(); } throw new Exception("Invalid request because this is not a UDP Broadcast configuration."); } - finally - { + finally { blockOnIO(); } } - public int getGroupPort() throws Exception - { + public int getGroupPort() throws Exception { clearIO(); - try - { - if (configuration.getEndpointFactory() instanceof UDPBroadcastEndpointFactory) - { - return ((UDPBroadcastEndpointFactory)configuration.getEndpointFactory()).getGroupPort(); + try { + if (configuration.getEndpointFactory() instanceof UDPBroadcastEndpointFactory) { + return ((UDPBroadcastEndpointFactory) configuration.getEndpointFactory()).getGroupPort(); } throw new Exception("Invalid request because this is not a UDP Broadcast configuration."); } - finally - { + finally { blockOnIO(); } } - public int getLocalBindPort() throws Exception - { + public int getLocalBindPort() throws Exception { clearIO(); - try - { - if (configuration.getEndpointFactory() instanceof UDPBroadcastEndpointFactory) - { - return ((UDPBroadcastEndpointFactory)configuration.getEndpointFactory()).getLocalBindPort(); + try { + if (configuration.getEndpointFactory() instanceof UDPBroadcastEndpointFactory) { + return ((UDPBroadcastEndpointFactory) configuration.getEndpointFactory()).getLocalBindPort(); } throw new Exception("Invalid request because this is not a UDP Broadcast configuration."); } - finally - { + finally { blockOnIO(); } } // MessagingComponentControlMBean implementation ----------------- - public boolean isStarted() - { + public boolean isStarted() { clearIO(); - try - { + try { return broadcastGroup.isStarted(); } - finally - { + finally { blockOnIO(); } } - public void start() throws Exception - { + public void start() throws Exception { clearIO(); - try - { + try { broadcastGroup.start(); } - finally - { + finally { blockOnIO(); } } - public void stop() throws Exception - { + public void stop() throws Exception { clearIO(); - try - { + try { broadcastGroup.stop(); } - finally - { + finally { blockOnIO(); } } @Override - protected MBeanOperationInfo[] fillMBeanOperationInfo() - { + protected MBeanOperationInfo[] fillMBeanOperationInfo() { return MBeanInfoHelper.getMBeanOperationsInfo(BroadcastGroupControl.class); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/ClusterConnectionControlImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/ClusterConnectionControlImpl.java index e08474c3a5..a89f0dffb8 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/ClusterConnectionControlImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/ClusterConnectionControlImpl.java @@ -26,8 +26,7 @@ import org.apache.activemq.artemis.core.persistence.StorageManager; import org.apache.activemq.artemis.core.server.cluster.ClusterConnection; import org.apache.activemq.artemis.utils.json.JSONArray; -public class ClusterConnectionControlImpl extends AbstractControl implements ClusterConnectionControl -{ +public class ClusterConnectionControlImpl extends AbstractControl implements ClusterConnectionControl { // Constants ----------------------------------------------------- @@ -43,8 +42,7 @@ public class ClusterConnectionControlImpl extends AbstractControl implements Clu public ClusterConnectionControlImpl(final ClusterConnection clusterConnection, final StorageManager storageManager, - final ClusterConnectionConfiguration configuration) throws Exception - { + final ClusterConnectionConfiguration configuration) throws Exception { super(ClusterConnectionControl.class, storageManager); this.clusterConnection = clusterConnection; this.configuration = configuration; @@ -52,231 +50,181 @@ public class ClusterConnectionControlImpl extends AbstractControl implements Clu // ClusterConnectionControlMBean implementation --------------------------- - public String getAddress() - { + public String getAddress() { clearIO(); - try - { + try { return configuration.getAddress(); } - finally - { + finally { blockOnIO(); } } - public String getDiscoveryGroupName() - { + public String getDiscoveryGroupName() { clearIO(); - try - { + try { return configuration.getDiscoveryGroupName(); } - finally - { + finally { blockOnIO(); } } - public int getMaxHops() - { + public int getMaxHops() { clearIO(); - try - { + try { return configuration.getMaxHops(); } - finally - { + finally { blockOnIO(); } } - public String getName() - { + public String getName() { clearIO(); - try - { + try { return configuration.getName(); } - finally - { + finally { blockOnIO(); } } - public long getRetryInterval() - { + public long getRetryInterval() { clearIO(); - try - { + try { return configuration.getRetryInterval(); } - finally - { + finally { blockOnIO(); } } - public String getNodeID() - { + public String getNodeID() { clearIO(); - try - { + try { return clusterConnection.getNodeID(); } - finally - { + finally { blockOnIO(); } } - public String[] getStaticConnectors() - { + public String[] getStaticConnectors() { clearIO(); - try - { - if (configuration.getStaticConnectors() == null) - { + try { + if (configuration.getStaticConnectors() == null) { return null; } - else - { + else { return configuration.getStaticConnectors().toArray(new String[0]); } } - finally - { + finally { blockOnIO(); } } - public String getStaticConnectorsAsJSON() throws Exception - { + public String getStaticConnectorsAsJSON() throws Exception { clearIO(); - try - { + try { List connectors = configuration.getStaticConnectors(); - if (connectors == null) - { + if (connectors == null) { return null; } JSONArray array = new JSONArray(); - for (String connector : connectors) - { + for (String connector : connectors) { array.put(connector); } return array.toString(); } - finally - { + finally { blockOnIO(); } } - public boolean isDuplicateDetection() - { + public boolean isDuplicateDetection() { clearIO(); - try - { + try { return configuration.isDuplicateDetection(); } - finally - { + finally { blockOnIO(); } } - public String getMessageLoadBalancingType() - { + public String getMessageLoadBalancingType() { clearIO(); - try - { + try { return configuration.getMessageLoadBalancingType().getType(); } - finally - { + finally { blockOnIO(); } } - public String getTopology() - { + public String getTopology() { clearIO(); - try - { + try { return clusterConnection.getTopology().describe(); } - finally - { + finally { blockOnIO(); } } - public Map getNodes() throws Exception - { + public Map getNodes() throws Exception { clearIO(); - try - { + try { return clusterConnection.getNodes(); } - finally - { + finally { blockOnIO(); } } - public boolean isStarted() - { + public boolean isStarted() { clearIO(); - try - { + try { return clusterConnection.isStarted(); } - finally - { + finally { blockOnIO(); } } - public void start() throws Exception - { + public void start() throws Exception { clearIO(); - try - { + try { clusterConnection.start(); clusterConnection.flushExecutor(); } - finally - { + finally { blockOnIO(); } } - public void stop() throws Exception - { + public void stop() throws Exception { clearIO(); - try - { + try { clusterConnection.stop(); clusterConnection.flushExecutor(); } - finally - { + finally { blockOnIO(); } } @Override - protected MBeanOperationInfo[] fillMBeanOperationInfo() - { + protected MBeanOperationInfo[] fillMBeanOperationInfo() { return MBeanInfoHelper.getMBeanOperationsInfo(ClusterConnectionControl.class); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/DivertControlImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/DivertControlImpl.java index ffb9ab6662..d7767831fc 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/DivertControlImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/DivertControlImpl.java @@ -23,8 +23,7 @@ import org.apache.activemq.artemis.core.config.DivertConfiguration; import org.apache.activemq.artemis.core.persistence.StorageManager; import org.apache.activemq.artemis.core.server.Divert; -public class DivertControlImpl extends AbstractControl implements DivertControl -{ +public class DivertControlImpl extends AbstractControl implements DivertControl { // Constants ----------------------------------------------------- @@ -42,111 +41,87 @@ public class DivertControlImpl extends AbstractControl implements DivertControl public DivertControlImpl(final Divert divert, final StorageManager storageManager, - final DivertConfiguration configuration) throws Exception - { + final DivertConfiguration configuration) throws Exception { super(DivertControl.class, storageManager); this.divert = divert; this.configuration = configuration; } - public String getAddress() - { + public String getAddress() { clearIO(); - try - { + try { return configuration.getAddress(); } - finally - { + finally { blockOnIO(); } } - public String getFilter() - { + public String getFilter() { clearIO(); - try - { + try { return configuration.getFilterString(); } - finally - { + finally { blockOnIO(); } } - public String getForwardingAddress() - { + public String getForwardingAddress() { clearIO(); - try - { + try { return configuration.getForwardingAddress(); } - finally - { + finally { blockOnIO(); } } - public String getRoutingName() - { + public String getRoutingName() { clearIO(); - try - { + try { return divert.getRoutingName().toString(); } - finally - { + finally { blockOnIO(); } } - public String getTransformerClassName() - { + public String getTransformerClassName() { clearIO(); - try - { + try { return configuration.getTransformerClassName(); } - finally - { + finally { blockOnIO(); } } - public String getUniqueName() - { + public String getUniqueName() { clearIO(); - try - { + try { return divert.getUniqueName().toString(); } - finally - { + finally { blockOnIO(); } } - public boolean isExclusive() - { + public boolean isExclusive() { clearIO(); - try - { + try { return divert.isExclusive(); } - finally - { + finally { blockOnIO(); } } @Override - protected MBeanOperationInfo[] fillMBeanOperationInfo() - { + protected MBeanOperationInfo[] fillMBeanOperationInfo() { return MBeanInfoHelper.getMBeanOperationsInfo(DivertControl.class); } - // Public -------------------------------------------------------- // Package protected --------------------------------------------- diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/MBeanInfoHelper.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/MBeanInfoHelper.java index 1ef9ff2541..c507458539 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/MBeanInfoHelper.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/MBeanInfoHelper.java @@ -27,8 +27,7 @@ import javax.management.MBeanParameterInfo; import org.apache.activemq.artemis.api.core.management.Operation; import org.apache.activemq.artemis.api.core.management.Parameter; -public class MBeanInfoHelper -{ +public class MBeanInfoHelper { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -39,15 +38,12 @@ public class MBeanInfoHelper // Public -------------------------------------------------------- - public static MBeanOperationInfo[] getMBeanOperationsInfo(final Class mbeanInterface) - { + public static MBeanOperationInfo[] getMBeanOperationsInfo(final Class mbeanInterface) { List operations = new ArrayList(); - for (Method method : mbeanInterface.getMethods()) - { + for (Method method : mbeanInterface.getMethods()) { if (!MBeanInfoHelper.isGetterMethod(method) && !MBeanInfoHelper.isSetterMethod(method) && - !MBeanInfoHelper.isIsBooleanMethod(method)) - { + !MBeanInfoHelper.isIsBooleanMethod(method)) { operations.add(MBeanInfoHelper.getOperationInfo(method)); } } @@ -61,59 +57,48 @@ public class MBeanInfoHelper // Private ------------------------------------------------------- - private static boolean isGetterMethod(final Method method) - { + private static boolean isGetterMethod(final Method method) { if (!method.getName().equals("get") && method.getName().startsWith("get") && - method.getParameterTypes().length == 0 && - !method.getReturnType().equals(void.class)) - { + method.getParameterTypes().length == 0 && + !method.getReturnType().equals(void.class)) { return true; } return false; } - private static boolean isSetterMethod(final Method method) - { + private static boolean isSetterMethod(final Method method) { if (!method.getName().equals("set") && method.getName().startsWith("set") && - method.getParameterTypes().length == 1 && - method.getReturnType().equals(void.class)) - { + method.getParameterTypes().length == 1 && + method.getReturnType().equals(void.class)) { return true; } - else - { + else { return false; } } - private static boolean isIsBooleanMethod(final Method method) - { + private static boolean isIsBooleanMethod(final Method method) { if (!method.getName().equals("is") && method.getName().startsWith("is") && - method.getParameterTypes().length == 0 && - method.getReturnType().equals(boolean.class)) - { + method.getParameterTypes().length == 0 && + method.getReturnType().equals(boolean.class)) { return true; } - else - { + else { return false; } } - private static MBeanOperationInfo getOperationInfo(final Method operation) - { + private static MBeanOperationInfo getOperationInfo(final Method operation) { MBeanOperationInfo info = null; Class returnType = operation.getReturnType(); - MBeanParameterInfo[] paramsInfo = MBeanInfoHelper.getParametersInfo(operation.getParameterAnnotations(), - operation.getParameterTypes()); + MBeanParameterInfo[] paramsInfo = MBeanInfoHelper.getParametersInfo(operation.getParameterAnnotations(), operation.getParameterTypes()); String description = operation.getName(); int impact = MBeanOperationInfo.UNKNOWN; - if (operation.getAnnotation(Operation.class) != null) - { + if (operation.getAnnotation(Operation.class) != null) { description = operation.getAnnotation(Operation.class).desc(); impact = operation.getAnnotation(Operation.class).impact(); } @@ -122,26 +107,21 @@ public class MBeanInfoHelper return info; } - private static MBeanParameterInfo[] getParametersInfo(final Annotation[][] params, final Class[] paramTypes) - { + private static MBeanParameterInfo[] getParametersInfo(final Annotation[][] params, final Class[] paramTypes) { MBeanParameterInfo[] paramsInfo = new MBeanParameterInfo[params.length]; - for (int i = 0; i < params.length; i++) - { + for (int i = 0; i < params.length; i++) { MBeanParameterInfo paramInfo = null; String type = paramTypes[i].getName(); - for (Annotation anno : params[i]) - { - if (Parameter.class.isInstance(anno)) - { + for (Annotation anno : params[i]) { + if (Parameter.class.isInstance(anno)) { String name = Parameter.class.cast(anno).name(); String description = Parameter.class.cast(anno).desc(); paramInfo = new MBeanParameterInfo(name, type, description); } } - if (paramInfo == null) - { + if (paramInfo == null) { paramInfo = new MBeanParameterInfo("p " + (i + 1), type, "parameter " + (i + 1)); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/QueueControlImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/QueueControlImpl.java index c0c7e7a3ac..7d4aaaf2fd 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/QueueControlImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/QueueControlImpl.java @@ -48,8 +48,8 @@ import org.apache.activemq.artemis.utils.json.JSONArray; import org.apache.activemq.artemis.utils.json.JSONException; import org.apache.activemq.artemis.utils.json.JSONObject; -public class QueueControlImpl extends AbstractControl implements QueueControl -{ +public class QueueControlImpl extends AbstractControl implements QueueControl { + public static final int FLUSH_LIMIT = 500; // Constants ----------------------------------------------------- @@ -67,29 +67,23 @@ public class QueueControlImpl extends AbstractControl implements QueueControl // Static -------------------------------------------------------- - private static String toJSON(final Map[] messages) - { + private static String toJSON(final Map[] messages) { JSONArray array = toJSONMsgArray(messages); return array.toString(); } - private static JSONArray toJSONMsgArray(final Map[] messages) - { + private static JSONArray toJSONMsgArray(final Map[] messages) { JSONArray array = new JSONArray(); - for (Map message : messages) - { + for (Map message : messages) { array.put(new JSONObject(message)); } return array; } - private static String toJSON(final Map[]> messages) - { - try - { + private static String toJSON(final Map[]> messages) { + try { JSONArray arrayReturn = new JSONArray(); - for (Map.Entry[]> entry : messages.entrySet()) - { + for (Map.Entry[]> entry : messages.entrySet()) { JSONObject objectItem = new JSONObject(); objectItem.put("consumerName", entry.getKey()); objectItem.put("elements", toJSONMsgArray(entry.getValue())); @@ -98,21 +92,18 @@ public class QueueControlImpl extends AbstractControl implements QueueControl return arrayReturn.toString(); } - catch (JSONException e) - { + catch (JSONException e) { return "Invalid conversion " + e.toString(); } } - // Constructors -------------------------------------------------- public QueueControlImpl(final Queue queue, final String address, final PostOffice postOffice, final StorageManager storageManager, - final HierarchicalRepository addressSettingsRepository) throws Exception - { + final HierarchicalRepository addressSettingsRepository) throws Exception { super(QueueControl.class, storageManager); this.queue = queue; this.address = address; @@ -122,257 +113,207 @@ public class QueueControlImpl extends AbstractControl implements QueueControl // Public -------------------------------------------------------- - public void setMessageCounter(final MessageCounter counter) - { + public void setMessageCounter(final MessageCounter counter) { this.counter = counter; } // QueueControlMBean implementation ------------------------------ - public String getName() - { + public String getName() { clearIO(); - try - { + try { return queue.getName().toString(); } - finally - { + finally { blockOnIO(); } } - public String getAddress() - { + public String getAddress() { checkStarted(); return address; } - public String getFilter() - { + public String getFilter() { checkStarted(); clearIO(); - try - { + try { Filter filter = queue.getFilter(); return filter != null ? filter.getFilterString().toString() : null; } - finally - { + finally { blockOnIO(); } } - public boolean isDurable() - { + public boolean isDurable() { checkStarted(); clearIO(); - try - { + try { return queue.isDurable(); } - finally - { + finally { blockOnIO(); } } - public boolean isTemporary() - { + public boolean isTemporary() { checkStarted(); clearIO(); - try - { + try { return queue.isTemporary(); } - finally - { + finally { blockOnIO(); } } - public long getMessageCount() - { + public long getMessageCount() { checkStarted(); clearIO(); - try - { + try { return queue.getMessageCount(); } - finally - { + finally { blockOnIO(); } } - public int getConsumerCount() - { + public int getConsumerCount() { checkStarted(); clearIO(); - try - { + try { return queue.getConsumerCount(); } - finally - { + finally { blockOnIO(); } } - public int getDeliveringCount() - { + public int getDeliveringCount() { checkStarted(); clearIO(); - try - { + try { return queue.getDeliveringCount(); } - finally - { + finally { blockOnIO(); } } - public long getMessagesAdded() - { + public long getMessagesAdded() { checkStarted(); clearIO(); - try - { + try { return queue.getMessagesAdded(); } - finally - { + finally { blockOnIO(); } } - public long getMessagesAcknowledged() - { + public long getMessagesAcknowledged() { checkStarted(); clearIO(); - try - { + try { return queue.getMessagesAcknowledged(); } - finally - { + finally { blockOnIO(); } } - public long getID() - { + public long getID() { checkStarted(); clearIO(); - try - { + try { return queue.getID(); } - finally - { + finally { blockOnIO(); } } - public long getScheduledCount() - { + public long getScheduledCount() { checkStarted(); clearIO(); - try - { + try { return queue.getScheduledCount(); } - finally - { + finally { blockOnIO(); } } - public String getDeadLetterAddress() - { + public String getDeadLetterAddress() { checkStarted(); clearIO(); - try - { + try { AddressSettings addressSettings = addressSettingsRepository.getMatch(address); - if (addressSettings != null && addressSettings.getDeadLetterAddress() != null) - { + if (addressSettings != null && addressSettings.getDeadLetterAddress() != null) { return addressSettings.getDeadLetterAddress().toString(); } return null; } - finally - { + finally { blockOnIO(); } } - public String getExpiryAddress() - { + public String getExpiryAddress() { checkStarted(); clearIO(); - try - { + try { AddressSettings addressSettings = addressSettingsRepository.getMatch(address); - if (addressSettings != null && addressSettings.getExpiryAddress() != null) - { + if (addressSettings != null && addressSettings.getExpiryAddress() != null) { return addressSettings.getExpiryAddress().toString(); } - else - { + else { return null; } } - finally - { + finally { blockOnIO(); } } - public Map[] listScheduledMessages() throws Exception - { + public Map[] listScheduledMessages() throws Exception { checkStarted(); clearIO(); - try - { + try { List refs = queue.getScheduledMessages(); return convertMessagesToMaps(refs); } - finally - { + finally { blockOnIO(); } } - public String listScheduledMessagesAsJSON() throws Exception - { + public String listScheduledMessagesAsJSON() throws Exception { checkStarted(); clearIO(); - try - { + try { return QueueControlImpl.toJSON(listScheduledMessages()); } - finally - { + finally { blockOnIO(); } } @@ -381,338 +322,277 @@ public class QueueControlImpl extends AbstractControl implements QueueControl * @param refs * @return */ - private Map[] convertMessagesToMaps(List refs) - { + private Map[] convertMessagesToMaps(List refs) { Map[] messages = new Map[refs.size()]; int i = 0; - for (MessageReference ref : refs) - { + for (MessageReference ref : refs) { Message message = ref.getMessage(); messages[i++] = message.toMap(); } return messages; } - - public Map[]> listDeliveringMessages() - { + public Map[]> listDeliveringMessages() { checkStarted(); clearIO(); - try - { + try { Map> msgs = queue.getDeliveringMessages(); Map[]> msgRet = new HashMap[]>(); - for (Map.Entry> entry : msgs.entrySet()) - { + for (Map.Entry> entry : msgs.entrySet()) { msgRet.put(entry.getKey(), convertMessagesToMaps(entry.getValue())); } return msgRet; } - finally - { + finally { blockOnIO(); } } - public String listDeliveringMessagesAsJSON() throws Exception - { + public String listDeliveringMessagesAsJSON() throws Exception { checkStarted(); clearIO(); - try - { + try { return QueueControlImpl.toJSON(listDeliveringMessages()); } - finally - { + finally { blockOnIO(); } } - public Map[] listMessages(final String filterStr) throws Exception - { + public Map[] listMessages(final String filterStr) throws Exception { checkStarted(); clearIO(); - try - { + try { Filter filter = FilterImpl.createFilter(filterStr); List> messages = new ArrayList>(); queue.flushExecutor(); LinkedListIterator iterator = queue.totalIterator(); - try - { - while (iterator.hasNext()) - { + try { + while (iterator.hasNext()) { MessageReference ref = iterator.next(); - if (filter == null || filter.match(ref.getMessage())) - { + if (filter == null || filter.match(ref.getMessage())) { Message message = ref.getMessage(); messages.add(message.toMap()); } } return messages.toArray(new Map[messages.size()]); } - finally - { + finally { iterator.close(); } } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw new IllegalStateException(e.getMessage()); } - finally - { + finally { blockOnIO(); } } - public String listMessagesAsJSON(final String filter) throws Exception - { + public String listMessagesAsJSON(final String filter) throws Exception { checkStarted(); clearIO(); - try - { + try { return QueueControlImpl.toJSON(listMessages(filter)); } - finally - { + finally { blockOnIO(); } } - protected Map[] getFirstMessage() throws Exception - { + protected Map[] getFirstMessage() throws Exception { checkStarted(); clearIO(); - try - { + try { List> messages = new ArrayList>(); queue.flushExecutor(); LinkedListIterator iterator = queue.totalIterator(); - try - { + try { // returns just the first, as it's the first only - if (iterator.hasNext()) - { + if (iterator.hasNext()) { MessageReference ref = iterator.next(); Message message = ref.getMessage(); messages.add(message.toMap()); } return messages.toArray(new Map[1]); } - finally - { + finally { iterator.close(); } } - finally - { + finally { blockOnIO(); } } - public String getFirstMessageAsJSON() throws Exception - { + public String getFirstMessageAsJSON() throws Exception { return toJSON(getFirstMessage()).toString(); } - public Long getFirstMessageTimestamp() throws Exception - { + public Long getFirstMessageTimestamp() throws Exception { Map[] _message = getFirstMessage(); - if (_message == null || _message.length == 0 || _message[0] == null) - { + if (_message == null || _message.length == 0 || _message[0] == null) { return null; } Map message = _message[0]; - if (!message.containsKey("timestamp")) - { + if (!message.containsKey("timestamp")) { return null; } - return (Long)message.get("timestamp"); + return (Long) message.get("timestamp"); } - public Long getFirstMessageAge() throws Exception - { + public Long getFirstMessageAge() throws Exception { Long firstMessageTimestamp = getFirstMessageTimestamp(); - if (firstMessageTimestamp == null) - { + if (firstMessageTimestamp == null) { return null; } long now = new Date().getTime(); return now - firstMessageTimestamp.longValue(); } - public long countMessages(final String filterStr) throws Exception - { + public long countMessages(final String filterStr) throws Exception { checkStarted(); clearIO(); - try - { + try { Filter filter = FilterImpl.createFilter(filterStr); - if (filter == null) - { + if (filter == null) { return getMessageCount(); } - else - { + else { LinkedListIterator iterator = queue.totalIterator(); - try - { + try { int count = 0; - while (iterator.hasNext()) - { + while (iterator.hasNext()) { MessageReference ref = iterator.next(); - if (filter.match(ref.getMessage())) - { + if (filter.match(ref.getMessage())) { count++; } } return count; } - finally - { + finally { iterator.close(); } } } - finally - { + finally { blockOnIO(); } } - public boolean removeMessage(final long messageID) throws Exception - { + public boolean removeMessage(final long messageID) throws Exception { checkStarted(); clearIO(); - try - { + try { return queue.deleteReference(messageID); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw new IllegalStateException(e.getMessage()); } - finally - { + finally { blockOnIO(); } } - public int removeMessages(final String filterStr) throws Exception - { + public int removeMessages(final String filterStr) throws Exception { return removeMessages(FLUSH_LIMIT, filterStr); } - public int removeMessages(final int flushLimit, final String filterStr) throws Exception - { + public int removeMessages(final int flushLimit, final String filterStr) throws Exception { checkStarted(); clearIO(); - try - { + try { Filter filter = FilterImpl.createFilter(filterStr); return queue.deleteMatchingReferences(flushLimit, filter); } - finally - { + finally { blockOnIO(); } } - public boolean expireMessage(final long messageID) throws Exception - { + public boolean expireMessage(final long messageID) throws Exception { checkStarted(); clearIO(); - try - { + try { return queue.expireReference(messageID); } - finally - { + finally { blockOnIO(); } } - public int expireMessages(final String filterStr) throws Exception - { + public int expireMessages(final String filterStr) throws Exception { checkStarted(); clearIO(); - try - { + try { Filter filter = FilterImpl.createFilter(filterStr); return queue.expireReferences(filter); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { throw new IllegalStateException(e.getMessage()); } - finally - { + finally { blockOnIO(); } } - public boolean moveMessage(final long messageID, final String otherQueueName) throws Exception - { + public boolean moveMessage(final long messageID, final String otherQueueName) throws Exception { return moveMessage(messageID, otherQueueName, false); } - public boolean moveMessage(final long messageID, final String otherQueueName, final boolean rejectDuplicates) throws Exception - { + public boolean moveMessage(final long messageID, + final String otherQueueName, + final boolean rejectDuplicates) throws Exception { checkStarted(); clearIO(); - try - { + try { Binding binding = postOffice.getBinding(new SimpleString(otherQueueName)); - if (binding == null) - { + if (binding == null) { throw ActiveMQMessageBundle.BUNDLE.noQueueFound(otherQueueName); } return queue.moveReference(messageID, binding.getAddress(), rejectDuplicates); } - finally - { + finally { blockOnIO(); } } - public int moveMessages(final String filterStr, final String otherQueueName) throws Exception - { + public int moveMessages(final String filterStr, final String otherQueueName) throws Exception { return moveMessages(filterStr, otherQueueName, false); } - public int moveMessages(final int flushLimit, final String filterStr, final String otherQueueName, final boolean rejectDuplicates) throws Exception - { + public int moveMessages(final int flushLimit, + final String filterStr, + final String otherQueueName, + final boolean rejectDuplicates) throws Exception { checkStarted(); clearIO(); - try - { + try { Filter filter = FilterImpl.createFilter(filterStr); Binding binding = postOffice.getBinding(new SimpleString(otherQueueName)); - if (binding == null) - { + if (binding == null) { throw ActiveMQMessageBundle.BUNDLE.noQueueFound(otherQueueName); } @@ -720,247 +600,200 @@ public class QueueControlImpl extends AbstractControl implements QueueControl return retValue; } - finally - { + finally { blockOnIO(); } } - public int moveMessages(final String filterStr, final String otherQueueName, final boolean rejectDuplicates) throws Exception - { + public int moveMessages(final String filterStr, + final String otherQueueName, + final boolean rejectDuplicates) throws Exception { return moveMessages(FLUSH_LIMIT, filterStr, otherQueueName, rejectDuplicates); } - public int sendMessagesToDeadLetterAddress(final String filterStr) throws Exception - { + public int sendMessagesToDeadLetterAddress(final String filterStr) throws Exception { checkStarted(); clearIO(); - try - { + try { Filter filter = FilterImpl.createFilter(filterStr); return queue.sendMessagesToDeadLetterAddress(filter); } - finally - { + finally { blockOnIO(); } } - public boolean sendMessageToDeadLetterAddress(final long messageID) throws Exception - { + public boolean sendMessageToDeadLetterAddress(final long messageID) throws Exception { checkStarted(); clearIO(); - try - { + try { return queue.sendMessageToDeadLetterAddress(messageID); } - finally - { + finally { blockOnIO(); } } - public int changeMessagesPriority(final String filterStr, final int newPriority) throws Exception - { + public int changeMessagesPriority(final String filterStr, final int newPriority) throws Exception { checkStarted(); clearIO(); - try - { - if (newPriority < 0 || newPriority > 9) - { + try { + if (newPriority < 0 || newPriority > 9) { throw ActiveMQMessageBundle.BUNDLE.invalidNewPriority(newPriority); } Filter filter = FilterImpl.createFilter(filterStr); return queue.changeReferencesPriority(filter, (byte) newPriority); } - finally - { + finally { blockOnIO(); } } - public boolean changeMessagePriority(final long messageID, final int newPriority) throws Exception - { + public boolean changeMessagePriority(final long messageID, final int newPriority) throws Exception { checkStarted(); clearIO(); - try - { - if (newPriority < 0 || newPriority > 9) - { + try { + if (newPriority < 0 || newPriority > 9) { throw ActiveMQMessageBundle.BUNDLE.invalidNewPriority(newPriority); } return queue.changeReferencePriority(messageID, (byte) newPriority); } - finally - { + finally { blockOnIO(); } } - public String listMessageCounter() - { + public String listMessageCounter() { checkStarted(); clearIO(); - try - { + try { return MessageCounterInfo.toJSon(counter); } - catch (Exception e) - { + catch (Exception e) { throw new IllegalStateException(e); } - finally - { + finally { blockOnIO(); } } - public void resetMessageCounter() - { + public void resetMessageCounter() { checkStarted(); clearIO(); - try - { + try { counter.resetCounter(); } - finally - { + finally { blockOnIO(); } } - public String listMessageCounterAsHTML() - { + public String listMessageCounterAsHTML() { checkStarted(); clearIO(); - try - { + try { return MessageCounterHelper.listMessageCounterAsHTML(new MessageCounter[]{counter}); } - finally - { + finally { blockOnIO(); } } - public String listMessageCounterHistory() throws Exception - { + public String listMessageCounterHistory() throws Exception { checkStarted(); clearIO(); - try - { + try { return MessageCounterHelper.listMessageCounterHistory(counter); } - finally - { + finally { blockOnIO(); } } - public String listMessageCounterHistoryAsHTML() - { + public String listMessageCounterHistoryAsHTML() { checkStarted(); clearIO(); - try - { + try { return MessageCounterHelper.listMessageCounterHistoryAsHTML(new MessageCounter[]{counter}); } - finally - { + finally { blockOnIO(); } } - public void pause() - { + public void pause() { checkStarted(); clearIO(); - try - { + try { queue.pause(); } - finally - { + finally { blockOnIO(); } } - public void resume() - { + public void resume() { checkStarted(); clearIO(); - try - { + try { queue.resume(); } - finally - { + finally { blockOnIO(); } } - public boolean isPaused() throws Exception - { + public boolean isPaused() throws Exception { checkStarted(); clearIO(); - try - { + try { return queue.isPaused(); } - finally - { + finally { blockOnIO(); } } - - public void flushExecutor() - { + public void flushExecutor() { checkStarted(); clearIO(); - try - { + try { queue.flushExecutor(); } - finally - { + finally { blockOnIO(); } } @Override - public String listConsumersAsJSON() throws Exception - { + public String listConsumersAsJSON() throws Exception { checkStarted(); clearIO(); - try - { + try { Collection consumers = queue.getConsumers(); JSONArray jsonArray = new JSONArray(); - for (Consumer consumer : consumers) - { + for (Consumer consumer : consumers) { - if (consumer instanceof ServerConsumer) - { + if (consumer instanceof ServerConsumer) { ServerConsumer serverConsumer = (ServerConsumer) consumer; JSONObject obj = new JSONObject(); @@ -977,45 +810,37 @@ public class QueueControlImpl extends AbstractControl implements QueueControl return jsonArray.toString(); } - finally - { + finally { blockOnIO(); } } @Override - protected MBeanOperationInfo[] fillMBeanOperationInfo() - { + protected MBeanOperationInfo[] fillMBeanOperationInfo() { return MBeanInfoHelper.getMBeanOperationsInfo(QueueControl.class); } - public void resetMessagesAdded() throws Exception - { + public void resetMessagesAdded() throws Exception { checkStarted(); clearIO(); - try - { + try { queue.resetMessagesAdded(); } - finally - { + finally { blockOnIO(); } } - public void resetMessagesAcknowledged() throws Exception - { + public void resetMessagesAcknowledged() throws Exception { checkStarted(); clearIO(); - try - { + try { queue.resetMessagesAcknowledged(); } - finally - { + finally { blockOnIO(); } @@ -1027,14 +852,11 @@ public class QueueControlImpl extends AbstractControl implements QueueControl // Private ------------------------------------------------------- - private void checkStarted() - { - if (!postOffice.isStarted()) - { + private void checkStarted() { + if (!postOffice.isStarted()) { throw new IllegalStateException("Broker is not started. Queue can not be managed yet"); } } - // Inner classes ------------------------------------------------- } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/messagecounter/MessageCounter.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/messagecounter/MessageCounter.java index 255fc51285..dce7e5e8e6 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/messagecounter/MessageCounter.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/messagecounter/MessageCounter.java @@ -33,8 +33,7 @@ import org.apache.activemq.artemis.core.server.Queue; * is added since that would reall slow things down, instead we *sample* the queues at * regular intervals - this means we are less intrusive on the queue */ -public class MessageCounter -{ +public class MessageCounter { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -74,20 +73,20 @@ public class MessageCounter /** * Constructor - * @param name destination name + * + * @param name destination name * @param subscription subscription name - * @param serverQueue internal queue object - * @param topic topic destination flag - * @param durable durable subscription flag - * @param daycountmax max message history day count + * @param serverQueue internal queue object + * @param topic topic destination flag + * @param durable durable subscription flag + * @param daycountmax max message history day count */ public MessageCounter(final String name, final String subscription, final Queue serverQueue, final boolean topic, final boolean durable, - final int daycountmax) - { + final int daycountmax) { // store destination related information destName = name; destSubscription = subscription; @@ -104,10 +103,8 @@ public class MessageCounter setHistoryLimit(daycountmax); } - private final Runnable onTimeExecutor = new Runnable() - { - public void run() - { + private final Runnable onTimeExecutor = new Runnable() { + public void run() { long latestMessagesAdded = serverQueue.getMessagesAdded(); long newMessagesAdded = latestMessagesAdded - lastMessagesAdded; @@ -116,8 +113,7 @@ public class MessageCounter lastMessagesAdded = latestMessagesAdded; - if (newMessagesAdded > 0) - { + if (newMessagesAdded > 0) { timeLastAdd = System.currentTimeMillis(); } @@ -135,8 +131,7 @@ public class MessageCounter /* * This method is called periodically to update statistics from the queue */ - public synchronized void onTimer() - { + public synchronized void onTimer() { // Actor approach here: Instead of having the Counter locking the queue, we will use the Queue's executor // instead of possibly making a lock on the queue. // This way the scheduled Threads will be free to keep doing their pings in case the server is busy with paging or @@ -144,23 +139,19 @@ public class MessageCounter serverQueue.getExecutor().execute(onTimeExecutor); } - public String getDestinationName() - { + public String getDestinationName() { return destName; } - public String getDestinationSubscription() - { + public String getDestinationSubscription() { return destSubscription; } - public boolean isDestinationTopic() - { + public boolean isDestinationTopic() { return destTopic; } - public boolean isDestinationDurable() - { + public boolean isDestinationDurable() { return destDurable; } @@ -168,16 +159,14 @@ public class MessageCounter * Gets the total message count since startup or * last counter reset */ - public long getCount() - { + public long getCount() { return countTotal; } /** * Gets the message count delta since last method call */ - public long getCountDelta() - { + public long getCountDelta() { long delta = countTotal - countTotalLast; countTotalLast = countTotal; @@ -189,8 +178,7 @@ public class MessageCounter * Gets the current message count of pending messages * within the destination waiting for dispatch */ - public long getMessageCount() - { + public long getMessageCount() { return serverQueue.getMessageCount(); } @@ -198,28 +186,24 @@ public class MessageCounter * Gets the message count delta of pending messages * since last method call. */ - public long getMessageCountDelta() - { + public long getMessageCountDelta() { long current = serverQueue.getMessageCount(); - int delta = (int)(current - depthLast); + int delta = (int) (current - depthLast); depthLast = current; return delta; } - public long getLastUpdate() - { + public long getLastUpdate() { return timeLastUpdate; } - public long getLastAddedMessageTime() - { + public long getLastAddedMessageTime() { return timeLastAdd; } - public void resetCounter() - { + public void resetCounter() { countTotal = 0; countTotalLast = 0; depthLast = 0; @@ -227,23 +211,19 @@ public class MessageCounter timeLastAdd = 0; } - private void setHistoryLimit(final int daycountmax) - { + private void setHistoryLimit(final int daycountmax) { boolean bInitialize = false; // store new maximum day count dayCounterMax = daycountmax; // update day counter array - synchronized (dayCounters) - { - if (dayCounterMax > 0) - { + synchronized (dayCounters) { + if (dayCounterMax > 0) { // limit day history to specified day count int delta = dayCounters.size() - dayCounterMax; - for (int i = 0; i < delta; i++) - { + for (int i = 0; i < delta; i++) { // reduce array size to requested size by dropping // oldest day counters dayCounters.remove(0); @@ -252,13 +232,11 @@ public class MessageCounter // create initial day counter when empty bInitialize = dayCounters.isEmpty(); } - else if (dayCounterMax == 0) - { + else if (dayCounterMax == 0) { // disable history dayCounters.clear(); } - else - { + else { // unlimited day history // create initial day counter when empty @@ -266,23 +244,20 @@ public class MessageCounter } // optionally initialize first day counter entry - if (bInitialize) - { + if (bInitialize) { dayCounters.add(new DayCounter(new GregorianCalendar(), true)); } } } - public void resetHistory() - { + public void resetHistory() { int max = dayCounterMax; setHistoryLimit(0); setHistoryLimit(max); } - public List getHistory() - { + public List getHistory() { updateHistory(0); return new ArrayList(dayCounters); @@ -292,30 +267,27 @@ public class MessageCounter * Get message counter history data as string in format * * "day count\n - * Date 1, hour counter 0, hour counter 1, ..., hour counter 23\n - * Date 2, hour counter 0, hour counter 1, ..., hour counter 23\n - * ..... - * ..... - * Date n, hour counter 0, hour counter 1, ..., hour counter 23\n" + * Date 1, hour counter 0, hour counter 1, ..., hour counter 23\n + * Date 2, hour counter 0, hour counter 1, ..., hour counter 23\n + * ..... + * ..... + * Date n, hour counter 0, hour counter 1, ..., hour counter 23\n" * - * @return String message history data string + * @return String message history data string */ - public String getHistoryAsString() - { + public String getHistoryAsString() { StringBuilder ret = new StringBuilder(); // ensure history counters are up to date updateHistory(0); // compile string - synchronized (dayCounters) - { + synchronized (dayCounters) { // first line: history day count ret.append(dayCounters.size() + "\n"); // following lines: day counter data - for (int i = 0; i < dayCounters.size(); i++) - { + for (int i = 0; i < dayCounters.size(); i++) { DayCounter counter = dayCounters.get(i); ret.append(counter.getDayCounterAsString() + "\n"); @@ -326,18 +298,17 @@ public class MessageCounter } @Override - public String toString() - { + public String toString() { return "MessageCounter[destName" + destName + - ", destSubscription=" + - destSubscription + - ", destTopic=" + - destTopic + - ", destDurable=" + - destDurable + - ", serverQueue =" + - serverQueue + - "]"; + ", destSubscription=" + + destSubscription + + ", destTopic=" + + destTopic + + ", destDurable=" + + destDurable + + ", serverQueue =" + + serverQueue + + "]"; } // Package protected --------------------------------------------- @@ -351,17 +322,14 @@ public class MessageCounter * * @param newMessages number of new messages to add to the latest day counter */ - private void updateHistory(final long newMessages) - { + private void updateHistory(final long newMessages) { // check history activation - if (dayCounters.isEmpty()) - { + if (dayCounters.isEmpty()) { return; } // calculate day difference between current date and date of last day counter entry - synchronized (dayCounters) - { + synchronized (dayCounters) { DayCounter counterLast = dayCounters.get(dayCounters.size() - 1); GregorianCalendar calNow = new GregorianCalendar(); @@ -385,18 +353,16 @@ public class MessageCounter long millisPerDay = 86400000; // 24 * 60 * 60 * 1000 long millisDelta = calNow.getTime().getTime() - calLast.getTime().getTime(); - int dayDelta = (int)(millisDelta / millisPerDay); + int dayDelta = (int) (millisDelta / millisPerDay); - if (dayDelta > 0) - { + if (dayDelta > 0) { // finalize last day counter counterLast.finalizeDayCounter(); // add new intermediate empty day counter entries DayCounter counterNew; - for (int i = 1; i < dayDelta; i++) - { + for (int i = 1; i < dayDelta; i++) { // increment date calLast.add(Calendar.DAY_OF_YEAR, 1); @@ -426,8 +392,8 @@ public class MessageCounter /** * Internal day counter class for one day hour based counter history */ - public static final class DayCounter - { + public static final class DayCounter { + static final int HOURS = 24; GregorianCalendar date = null; @@ -435,36 +401,30 @@ public class MessageCounter int[] counters = new int[DayCounter.HOURS]; /** - * Constructor + * Constructor * - * @param date day counter date - * @param isStartDay true first day counter - * false follow up day counter + * @param date day counter date + * @param isStartDay true first day counter + * false follow up day counter */ - DayCounter(final GregorianCalendar date, final boolean isStartDay) - { + DayCounter(final GregorianCalendar date, final boolean isStartDay) { // store internal copy of creation date - this.date = (GregorianCalendar)date.clone(); + this.date = (GregorianCalendar) date.clone(); // initialize the array with '0'- values to current hour (if it is not the // first monitored day) and the rest with default values ('-1') int hour = date.get(Calendar.HOUR_OF_DAY); - for (int i = 0; i < DayCounter.HOURS; i++) - { - if (i < hour) - { - if (isStartDay) - { + for (int i = 0; i < DayCounter.HOURS; i++) { + if (i < hour) { + if (isStartDay) { counters[i] = -1; } - else - { + else { counters[i] = 0; } } - else - { + else { counters[i] = -1; } } @@ -478,13 +438,11 @@ public class MessageCounter * * @return GregorianCalendar day counter date */ - public GregorianCalendar getDate() - { - return (GregorianCalendar)date.clone(); + public GregorianCalendar getDate() { + return (GregorianCalendar) date.clone(); } - public int[] getCounters() - { + public int[] getCounters() { return counters; } @@ -493,8 +451,7 @@ public class MessageCounter * * @param newMessages number of new messages since the counter was last updated. */ - void updateDayCounter(final long newMessages) - { + void updateDayCounter(final long newMessages) { // get the current hour of the day GregorianCalendar cal = new GregorianCalendar(); @@ -504,20 +461,16 @@ public class MessageCounter // array elements between the last index and the current index with '0' values boolean bUpdate = false; - for (int i = 0; i <= currentIndex; i++) - { - if (counters[i] > -1) - { + for (int i = 0; i <= currentIndex; i++) { + if (counters[i] > -1) { // found first initialized hour counter // -> set all following uninitialized // counter values to 0 bUpdate = true; } - if (bUpdate == true) - { - if (counters[i] == -1) - { + if (bUpdate == true) { + if (counters[i] == -1) { counters[i] = 0; } } @@ -530,26 +483,21 @@ public class MessageCounter /** * Finalize day counter hour array elements */ - private void finalizeDayCounter() - { + private void finalizeDayCounter() { // a new day has began, so fill all array elements from index to end with // '0' values boolean bFinalize = false; - for (int i = 0; i < DayCounter.HOURS; i++) - { - if (counters[i] > -1) - { + for (int i = 0; i < DayCounter.HOURS; i++) { + if (counters[i] > -1) { // found first initialized hour counter // -> finalize all following uninitialized // counter values bFinalize = true; } - if (bFinalize) - { - if (counters[i] == -1) - { + if (bFinalize) { + if (counters[i] == -1) { counters[i] = 0; } } @@ -559,18 +507,17 @@ public class MessageCounter /** * Return day counter data as string with format
    * "Date, hour counter 0, hour counter 1, ..., hour counter 23". + * * @return String day counter data */ - private String getDayCounterAsString() - { + private String getDayCounterAsString() { // first element day counter date DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT); StringBuilder strData = new StringBuilder(dateFormat.format(date.getTime())); // append 24 comma separated hour counter values - for (int i = 0; i < DayCounter.HOURS; i++) - { + for (int i = 0; i < DayCounter.HOURS; i++) { strData.append("," + counters[i]); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/messagecounter/MessageCounterManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/messagecounter/MessageCounterManager.java index f1a88fd3b1..f3053c3f3a 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/messagecounter/MessageCounterManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/messagecounter/MessageCounterManager.java @@ -16,8 +16,8 @@ */ package org.apache.activemq.artemis.core.messagecounter; -public interface MessageCounterManager -{ +public interface MessageCounterManager { + void start(); void stop(); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/messagecounter/impl/MessageCounterHelper.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/messagecounter/impl/MessageCounterHelper.java index 3503c241b9..9cf41adaee 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/messagecounter/impl/MessageCounterHelper.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/messagecounter/impl/MessageCounterHelper.java @@ -26,20 +26,17 @@ import org.apache.activemq.artemis.api.core.management.DayCounterInfo; import org.apache.activemq.artemis.core.messagecounter.MessageCounter; import org.apache.activemq.artemis.core.messagecounter.MessageCounter.DayCounter; -public class MessageCounterHelper -{ +public class MessageCounterHelper { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- // Static -------------------------------------------------------- - public static String listMessageCounterHistory(final MessageCounter counter) throws Exception - { + public static String listMessageCounterHistory(final MessageCounter counter) throws Exception { List history = counter.getHistory(); DayCounterInfo[] infos = new DayCounterInfo[history.size()]; - for (int i = 0; i < infos.length; i++) - { + for (int i = 0; i < infos.length; i++) { DayCounter dayCounter = history.get(i); int[] counters = dayCounter.getCounters(); GregorianCalendar date = dayCounter.getDate(); @@ -51,39 +48,22 @@ public class MessageCounterHelper return DayCounterInfo.toJSON(infos); } - public static String listMessageCounterAsHTML(final MessageCounter[] counters) - { - if (counters == null) - { + public static String listMessageCounterAsHTML(final MessageCounter[] counters) { + if (counters == null) { return null; } - String ret0 = - "
    \n" + "" - + "" - + "" - + "" - + "" - + "" - + "" - + "" - + "" - + "" - + "" - + "\n"; + String ret0 = "
    TypeNameSubscriptionDurableCountCountDeltaDepthDepthDeltaLast AddLast Update
    \n" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "\n"; StringBuilder ret = new StringBuilder(ret0); - for (int i = 0; i < counters.length; i++) - { + for (int i = 0; i < counters.length; i++) { MessageCounter counter = counters[i]; String type = counter.isDestinationTopic() ? "Topic" : "Queue"; String subscription = counter.getDestinationSubscription(); - if (subscription == null) - { + if (subscription == null) { subscription = "-"; } String durableStr = "-"; // makes no sense for a queue - if (counter.isDestinationTopic()) - { + if (counter.isDestinationTopic()) { durableStr = Boolean.toString(counter.isDestinationDurable()); } ret.append(""); @@ -107,17 +87,14 @@ public class MessageCounterHelper return ret.toString(); } - public static String listMessageCounterHistoryAsHTML(final MessageCounter[] counters) - { - if (counters == null) - { + public static String listMessageCounterHistoryAsHTML(final MessageCounter[] counters) { + if (counters == null) { return null; } StringBuilder ret = new StringBuilder("
      \n"); - for (MessageCounter counter : counters) - { + for (MessageCounter counter : counters) { ret.append("
    • \n"); ret.append("
        \n"); @@ -126,8 +103,7 @@ public class MessageCounterHelper ret.append((counter.isDestinationTopic() ? "Topic '" : "Queue '") + counter.getDestinationName() + "'"); ret.append("\n"); - if (counter.getDestinationSubscription() != null) - { + if (counter.getDestinationSubscription() != null) { ret.append("
      • "); ret.append("Subscription '" + counter.getDestinationSubscription() + "'"); ret.append("
      • \n"); @@ -138,8 +114,7 @@ public class MessageCounterHelper ret.append("
    TypeNameSubscriptionDurableCountCountDeltaDepthDepthDeltaLast AddLast Update
    \n"); ret.append(""); - for (int j = 0; j < 24; j++) - { + for (int j = 0; j < 24; j++) { ret.append(""); } @@ -151,8 +126,7 @@ public class MessageCounterHelper // get history day count int days = Integer.parseInt(tokens.nextToken()); - for (int j = 0; j < days; j++) - { + for (int j = 0; j < days; j++) { // next day counter row ret.append(""); @@ -162,16 +136,13 @@ public class MessageCounterHelper // 24 hour counters int total = 0; - for (int k = 0; k < 24; k++) - { + for (int k = 0; k < 24; k++) { int value = Integer.parseInt(tokens.nextToken().trim()); - if (value == -1) - { + if (value == -1) { ret.append(""); } - else - { + else { ret.append(""); total += value; @@ -191,23 +162,18 @@ public class MessageCounterHelper return ret.toString(); } - private static String prettify(final long value) - { - if (value == 0) - { + private static String prettify(final long value) { + if (value == 0) { return "-"; } return Long.toString(value); } - private static String asDate(final long time) - { - if (time > 0) - { + private static String asDate(final long time) { + if (time > 0) { return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM).format(new Date(time)); } - else - { + else { return "-"; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/messagecounter/impl/MessageCounterManagerImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/messagecounter/impl/MessageCounterManagerImpl.java index de02a09cb6..c81aa655aa 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/messagecounter/impl/MessageCounterManagerImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/messagecounter/impl/MessageCounterManagerImpl.java @@ -30,11 +30,9 @@ import org.apache.activemq.artemis.core.messagecounter.MessageCounter; import org.apache.activemq.artemis.core.messagecounter.MessageCounterManager; /** - * * A MessageCounterManager */ -public class MessageCounterManagerImpl implements MessageCounterManager -{ +public class MessageCounterManagerImpl implements MessageCounterManager { public static final long DEFAULT_SAMPLE_PERIOD = ActiveMQDefaultConfiguration.getDefaultMessageCounterSamplePeriod(); @@ -54,35 +52,27 @@ public class MessageCounterManagerImpl implements MessageCounterManager private final ScheduledExecutorService scheduledThreadPool; - public MessageCounterManagerImpl(final ScheduledExecutorService scheduledThreadPool) - { + public MessageCounterManagerImpl(final ScheduledExecutorService scheduledThreadPool) { messageCounters = new HashMap(); this.scheduledThreadPool = scheduledThreadPool; } - public synchronized void start() - { - if (started) - { + public synchronized void start() { + if (started) { return; } messageCountersPinger = new MessageCountersPinger(); - Future future = scheduledThreadPool.scheduleAtFixedRate(messageCountersPinger, - 0, - period, - TimeUnit.MILLISECONDS); + Future future = scheduledThreadPool.scheduleAtFixedRate(messageCountersPinger, 0, period, TimeUnit.MILLISECONDS); messageCountersPinger.setFuture(future); started = true; } - public synchronized void stop() - { - if (!started) - { + public synchronized void stop() { + if (!started) { return; } @@ -91,75 +81,59 @@ public class MessageCounterManagerImpl implements MessageCounterManager started = false; } - public synchronized void clear() - { + public synchronized void clear() { messageCounters.clear(); } - public synchronized void reschedule(final long newPeriod) - { + public synchronized void reschedule(final long newPeriod) { boolean wasStarted = started; - if (wasStarted) - { + if (wasStarted) { stop(); } period = newPeriod; - if (wasStarted) - { + if (wasStarted) { start(); } } - public long getSamplePeriod() - { + public long getSamplePeriod() { return period; } - public int getMaxDayCount() - { + public int getMaxDayCount() { return maxDayCount; } - public void setMaxDayCount(final int count) - { + public void setMaxDayCount(final int count) { maxDayCount = count; } - public void registerMessageCounter(final String name, final MessageCounter counter) - { - synchronized (messageCounters) - { + public void registerMessageCounter(final String name, final MessageCounter counter) { + synchronized (messageCounters) { messageCounters.put(name, counter); } } - public MessageCounter unregisterMessageCounter(final String name) - { - synchronized (messageCounters) - { + public MessageCounter unregisterMessageCounter(final String name) { + synchronized (messageCounters) { return messageCounters.remove(name); } } - public Set getMessageCounters() - { - synchronized (messageCounters) - { + public Set getMessageCounters() { + synchronized (messageCounters) { return new HashSet(messageCounters.values()); } } - public void resetAllCounters() - { - synchronized (messageCounters) - { + public void resetAllCounters() { + synchronized (messageCounters) { Iterator iter = messageCounters.values().iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { MessageCounter counter = iter.next(); counter.resetCounter(); @@ -167,14 +141,11 @@ public class MessageCounterManagerImpl implements MessageCounterManager } } - public void resetAllCounterHistories() - { - synchronized (messageCounters) - { + public void resetAllCounterHistories() { + synchronized (messageCounters) { Iterator iter = messageCounters.values().iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { MessageCounter counter = iter.next(); counter.resetHistory(); @@ -182,25 +153,21 @@ public class MessageCounterManagerImpl implements MessageCounterManager } } - private class MessageCountersPinger implements Runnable - { + private class MessageCountersPinger implements Runnable { + private boolean closed = false; private Future future; - public synchronized void run() - { - if (closed) - { + public synchronized void run() { + if (closed) { return; } - synchronized (messageCounters) - { + synchronized (messageCounters) { Iterator iter = messageCounters.values().iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { MessageCounter counter = iter.next(); counter.onTimer(); @@ -208,15 +175,12 @@ public class MessageCounterManagerImpl implements MessageCounterManager } } - public void setFuture(final Future future) - { + public void setFuture(final Future future) { this.future = future; } - synchronized void stop() - { - if (future != null) - { + synchronized void stop() { + if (future != null) { future.cancel(false); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/PageTransactionInfo.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/PageTransactionInfo.java index 39b776d6c0..ed4297331f 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/PageTransactionInfo.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/PageTransactionInfo.java @@ -23,8 +23,8 @@ import org.apache.activemq.artemis.core.paging.cursor.PageSubscription; import org.apache.activemq.artemis.core.persistence.StorageManager; import org.apache.activemq.artemis.core.transaction.Transaction; -public interface PageTransactionInfo extends EncodingSupport -{ +public interface PageTransactionInfo extends EncodingSupport { + boolean isCommit(); boolean isRollback(); @@ -45,7 +45,10 @@ public interface PageTransactionInfo extends EncodingSupport void storeUpdate(StorageManager storageManager, PagingManager pagingManager, Transaction tx) throws Exception; - void reloadUpdate(final StorageManager storageManager, final PagingManager pagingManager, final Transaction tx, final int increment) throws Exception; + void reloadUpdate(final StorageManager storageManager, + final PagingManager pagingManager, + final Transaction tx, + final int increment) throws Exception; // To be used after the update was stored or reload void onUpdate(int update, StorageManager storageManager, PagingManager pagingManager); @@ -57,6 +60,7 @@ public interface PageTransactionInfo extends EncodingSupport /** * This method will hold the position to be delivered later in case this transaction is pending. * If the tx is not pending, it will return false, so the caller can deliver it right away + * * @return true if the message will be delivered later, false if it should be delivered right away */ boolean deliverAfterCommit(PageIterator pageIterator, PageSubscription cursor, PagePosition cursorPos); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/PagedMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/PagedMessage.java index 42b63ef83b..9b1e243037 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/PagedMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/PagedMessage.java @@ -26,11 +26,13 @@ import org.apache.activemq.artemis.core.server.ServerMessage; * We can't just record the ServerMessage as we need other information (such as the TransactionID * used during paging) */ -public interface PagedMessage extends EncodingSupport -{ +public interface PagedMessage extends EncodingSupport { + ServerMessage getMessage(); - /** The queues that were routed during paging */ + /** + * The queues that were routed during paging + */ long[] getQueueIDs(); void initMessage(StorageManager storageManager); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/PagingManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/PagingManager.java index 8e06cdecf7..d55c09f8de 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/PagingManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/PagingManager.java @@ -28,18 +28,20 @@ import org.apache.activemq.artemis.core.settings.HierarchicalRepositoryChangeLis * +--------------+ 1 +----------------+ N +--------------+ N +--------+ 1 +-------------------+ * | {@link org.apache.activemq.artemis.core.postoffice.PostOffice} |-------> |{@link PagingManager}|-------> |{@link PagingStore} | ------> | {@link org.apache.activemq.artemis.core.paging.impl.Page} | ------> | {@link SequentialFile} | * +--------------+ +----------------+ +--------------+ +--------+ +-------------------+ - * | 1 ^ - * | | - * | | - * | | 1 - * | N +----------+ - * +------------> | {@link org.apache.activemq.artemis.core.postoffice.Address} | - * +----------+ + * | 1 ^ + * | | + * | | + * | | 1 + * | N +----------+ + * +------------> | {@link org.apache.activemq.artemis.core.postoffice.Address} | + * +----------+ * */ -public interface PagingManager extends ActiveMQComponent, HierarchicalRepositoryChangeListener -{ - /** Returns the PageStore associated with the address. A new page store is created if necessary. */ +public interface PagingManager extends ActiveMQComponent, HierarchicalRepositoryChangeListener { + + /** + * Returns the PageStore associated with the address. A new page store is created if necessary. + */ PagingStore getPageStore(SimpleString address) throws Exception; /** @@ -49,7 +51,7 @@ public interface PagingManager extends ActiveMQComponent, HierarchicalRepository /** * Point to inform/restoring Transactions used when the messages were added into paging - * */ + */ PageTransactionInfo getTransaction(long transactionID); /** @@ -61,6 +63,7 @@ public interface PagingManager extends ActiveMQComponent, HierarchicalRepository /** * Reload previously created PagingStores into memory + * * @throws Exception */ void reloadStores() throws Exception; @@ -82,6 +85,7 @@ public interface PagingManager extends ActiveMQComponent, HierarchicalRepository /** * Unlock the manager. + * * @see #lock() */ void unlock(); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/PagingStore.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/PagingStore.java index b0129e79bd..e831966d02 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/PagingStore.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/PagingStore.java @@ -41,8 +41,8 @@ import org.apache.activemq.artemis.core.transaction.Transaction; * * @see PagingManager */ -public interface PagingStore extends ActiveMQComponent -{ +public interface PagingStore extends ActiveMQComponent { + SimpleString getAddress(); int getNumberOfPages(); @@ -111,7 +111,6 @@ public interface PagingStore extends ActiveMQComponent */ Page depage() throws Exception; - void forceAnotherPage() throws Exception; Page getCurrentPage(); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/PagingStoreFactory.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/PagingStoreFactory.java index 08180342f6..8c2d11a811 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/PagingStoreFactory.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/PagingStoreFactory.java @@ -26,8 +26,8 @@ import org.apache.activemq.artemis.core.settings.impl.AddressSettings; /** * The integration point between the PagingManger and the File System (aka SequentialFiles) */ -public interface PagingStoreFactory -{ +public interface PagingStoreFactory { + PagingStore newStore(SimpleString address, AddressSettings addressSettings); void stop() throws InterruptedException; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/LivePageCache.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/LivePageCache.java index 59cbd8efa6..0d09bc4bd9 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/LivePageCache.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/LivePageCache.java @@ -18,8 +18,7 @@ package org.apache.activemq.artemis.core.paging.cursor; import org.apache.activemq.artemis.core.paging.PagedMessage; -public interface LivePageCache extends PageCache -{ +public interface LivePageCache extends PageCache { void addLiveMessage(PagedMessage message); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PageCache.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PageCache.java index e3ffd707cc..0c6cf9151b 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PageCache.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PageCache.java @@ -19,8 +19,8 @@ package org.apache.activemq.artemis.core.paging.cursor; import org.apache.activemq.artemis.core.paging.PagedMessage; import org.apache.activemq.artemis.utils.SoftValueHashMap; -public interface PageCache extends SoftValueHashMap.ValueCache -{ +public interface PageCache extends SoftValueHashMap.ValueCache { + long getPageId(); int getNumberOfMessages(); @@ -35,7 +35,6 @@ public interface PageCache extends SoftValueHashMap.ValueCache boolean isLive(); /** - * * @param messageNumber The order of the message on the page * @return */ diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PageCursorProvider.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PageCursorProvider.java index 3d734d4472..951b83c46c 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PageCursorProvider.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PageCursorProvider.java @@ -22,8 +22,7 @@ import org.apache.activemq.artemis.core.paging.PagedMessage; /** * The provider of Cursor for a given Address */ -public interface PageCursorProvider -{ +public interface PageCursorProvider { PageCache getPageCache(long pageNr); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PageIterator.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PageIterator.java index 46ab4521a5..af6ed4021d 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PageIterator.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PageIterator.java @@ -19,7 +19,7 @@ package org.apache.activemq.artemis.core.paging.cursor; import org.apache.activemq.artemis.utils.LinkedListIterator; -public interface PageIterator extends LinkedListIterator -{ +public interface PageIterator extends LinkedListIterator { + void redeliver(PagePosition reference); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PagePosition.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PagePosition.java index d9bbb9455a..00955b77bd 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PagePosition.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PagePosition.java @@ -16,10 +16,7 @@ */ package org.apache.activemq.artemis.core.paging.cursor; - - -public interface PagePosition extends Comparable -{ +public interface PagePosition extends Comparable { // The recordID associated during ack long getRecordID(); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PageSubscription.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PageSubscription.java index 62150031fa..df2ccc3627 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PageSubscription.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PageSubscription.java @@ -25,8 +25,7 @@ import org.apache.activemq.artemis.core.server.Queue; import org.apache.activemq.artemis.core.transaction.Transaction; import org.apache.activemq.artemis.utils.LinkedListIterator; -public interface PageSubscription -{ +public interface PageSubscription { // Cursor query operations -------------------------------------- @@ -35,7 +34,9 @@ public interface PageSubscription // To be called before the server is down void stop(); - /** This is a callback to inform the PageSubscription that something was routed, so the empty flag can be cleared */ + /** + * This is a callback to inform the PageSubscription that something was routed, so the empty flag can be cleared + */ void notEmpty(); void bookmark(PagePosition position) throws Exception; @@ -48,7 +49,9 @@ public interface PageSubscription boolean isPersistent(); - /** Used as a delegate method to {@link PagingStore#isPaging()} */ + /** + * Used as a delegate method to {@link PagingStore#isPaging()} + */ boolean isPaging(); LinkedListIterator iterator(); @@ -79,7 +82,6 @@ public interface PageSubscription void confirmPosition(Transaction tx, PagePosition position) throws Exception; /** - * * @return the first page in use or MAX_LONG if none is in use */ long getFirstPage(); @@ -106,6 +108,7 @@ public interface PageSubscription /** * To be used to avoid a redelivery of a prepared ACK after load + * * @param position */ void reloadPreparedACK(Transaction tx, PagePosition position); @@ -116,6 +119,7 @@ public interface PageSubscription /** * To be used on redeliveries + * * @param position */ void redeliver(PageIterator iterator, PagePosition position); @@ -128,7 +132,9 @@ public interface PageSubscription */ boolean isComplete(long page); - /** wait all the scheduled runnables to finish their current execution */ + /** + * wait all the scheduled runnables to finish their current execution + */ void flushExecutors(); void setQueue(Queue queue); @@ -137,6 +143,7 @@ public interface PageSubscription /** * To be used to requery the reference case the Garbage Collection removed it from the PagedReference as it's using WeakReferences + * * @param pos * @return */ diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PageSubscriptionCounter.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PageSubscriptionCounter.java index c1a2729200..343f93611c 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PageSubscriptionCounter.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PageSubscriptionCounter.java @@ -19,8 +19,7 @@ package org.apache.activemq.artemis.core.paging.cursor; import org.apache.activemq.artemis.core.paging.impl.Page; import org.apache.activemq.artemis.core.transaction.Transaction; -public interface PageSubscriptionCounter -{ +public interface PageSubscriptionCounter { long getValue(); @@ -32,11 +31,12 @@ public interface PageSubscriptionCounter void applyIncrementOnTX(Transaction tx, long recordID, int add); - /** This will process the reload */ + /** + * This will process the reload + */ void processReload(); /** - * * @param id * @param variance */ diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PagedReference.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PagedReference.java index bd9457a698..c1ff089681 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PagedReference.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PagedReference.java @@ -19,8 +19,8 @@ package org.apache.activemq.artemis.core.paging.cursor; import org.apache.activemq.artemis.core.paging.PagedMessage; import org.apache.activemq.artemis.core.server.MessageReference; -public interface PagedReference extends MessageReference -{ +public interface PagedReference extends MessageReference { + PagePosition getPosition(); PagedMessage getPagedMessage(); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PagedReferenceImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PagedReferenceImpl.java index 911e763b74..cfbe8e893d 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PagedReferenceImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/PagedReferenceImpl.java @@ -26,8 +26,8 @@ import org.apache.activemq.artemis.core.server.MessageReference; import org.apache.activemq.artemis.core.server.Queue; import org.apache.activemq.artemis.core.server.ServerMessage; -public class PagedReferenceImpl implements PagedReference -{ +public class PagedReferenceImpl implements PagedReference { + private static final boolean isTrace = ActiveMQServerLogger.LOGGER.isTraceEnabled(); private final PagePosition position; @@ -48,21 +48,18 @@ public class PagedReferenceImpl implements PagedReference private boolean alreadyAcked; - public ServerMessage getMessage() - { + public ServerMessage getMessage() { return getPagedMessage().getMessage(); } - public synchronized PagedMessage getPagedMessage() - { + public synchronized PagedMessage getPagedMessage() { PagedMessage returnMessage = message != null ? message.get() : null; // We only keep a few references on the Queue from paging... // Besides those references are SoftReferenced on page cache... // So, this will unlikely be null, // unless the Queue has stalled for some time after paging - if (returnMessage == null) - { + if (returnMessage == null) { // reference is gone, we will reconstruct it returnMessage = subscription.queryMessage(position); message = new WeakReference(returnMessage); @@ -70,74 +67,58 @@ public class PagedReferenceImpl implements PagedReference return returnMessage; } - public PagePosition getPosition() - { + public PagePosition getPosition() { return position; } public PagedReferenceImpl(final PagePosition position, final PagedMessage message, - final PageSubscription subscription) - { + final PageSubscription subscription) { this.position = position; - if (message == null) - { + if (message == null) { this.messageEstimate = -1; } - else - { + else { this.messageEstimate = message.getMessage().getMemoryEstimate(); } this.message = new WeakReference(message); this.subscription = subscription; } - public boolean isPaged() - { + public boolean isPaged() { return true; } - public void setPersistedCount(int count) - { + public void setPersistedCount(int count) { this.persistedCount = count; } - public int getPersistedCount() - { + public int getPersistedCount() { return persistedCount; } - @Override - public int getMessageMemoryEstimate() - { - if (messageEstimate < 0) - { + public int getMessageMemoryEstimate() { + if (messageEstimate < 0) { messageEstimate = getMessage().getMemoryEstimate(); } return messageEstimate; } - @Override - public MessageReference copy(final Queue queue) - { + public MessageReference copy(final Queue queue) { return new PagedReferenceImpl(this.position, this.getPagedMessage(), this.subscription); } @Override - public long getScheduledDeliveryTime() - { - if (deliveryTime == null) - { + public long getScheduledDeliveryTime() { + if (deliveryTime == null) { ServerMessage msg = getMessage(); - if (msg.containsProperty(Message.HDR_SCHEDULED_DELIVERY_TIME)) - { + if (msg.containsProperty(Message.HDR_SCHEDULED_DELIVERY_TIME)) { deliveryTime = getMessage().getLongProperty(Message.HDR_SCHEDULED_DELIVERY_TIME); } - else - { + else { deliveryTime = 0L; } } @@ -145,71 +126,59 @@ public class PagedReferenceImpl implements PagedReference } @Override - public void setScheduledDeliveryTime(final long scheduledDeliveryTime) - { + public void setScheduledDeliveryTime(final long scheduledDeliveryTime) { deliveryTime = scheduledDeliveryTime; } @Override - public int getDeliveryCount() - { + public int getDeliveryCount() { return deliveryCount.get(); } @Override - public void setDeliveryCount(final int deliveryCount) - { + public void setDeliveryCount(final int deliveryCount) { this.deliveryCount.set(deliveryCount); } @Override - public void incrementDeliveryCount() - { + public void incrementDeliveryCount() { deliveryCount.incrementAndGet(); - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("++deliveryCount = " + deliveryCount + " for " + this, new Exception("trace")); } } @Override - public void decrementDeliveryCount() - { + public void decrementDeliveryCount() { deliveryCount.decrementAndGet(); - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("--deliveryCount = " + deliveryCount + " for " + this, new Exception("trace")); } } @Override - public Queue getQueue() - { + public Queue getQueue() { return subscription.getQueue(); } @Override - public void handled() - { + public void handled() { getQueue().referenceHandled(); } @Override - public void setAlreadyAcked() - { + public void setAlreadyAcked() { alreadyAcked = true; } @Override - public boolean isAlreadyAcked() - { + public boolean isAlreadyAcked() { return alreadyAcked; } @Override - public void acknowledge() throws Exception - { + public void acknowledge() throws Exception { subscription.ack(this); } @@ -217,15 +186,12 @@ public class PagedReferenceImpl implements PagedReference * @see java.lang.Object#toString() */ @Override - public String toString() - { + public String toString() { String msgToString; - try - { + try { msgToString = getPagedMessage().toString(); } - catch (Throwable e) - { + catch (Throwable e) { // in case of an exception because of a missing page, we just want toString to return null msgToString = "error:" + e.getMessage(); } @@ -247,8 +213,7 @@ public class PagedReferenceImpl implements PagedReference * @see org.apache.activemq.artemis.core.server.MessageReference#setConsumerId(java.lang.Long) */ @Override - public void setConsumerId(Long consumerID) - { + public void setConsumerId(Long consumerID) { this.consumerId = consumerID; } @@ -256,8 +221,7 @@ public class PagedReferenceImpl implements PagedReference * @see org.apache.activemq.artemis.core.server.MessageReference#getConsumerId() */ @Override - public Long getConsumerId() - { + public Long getConsumerId() { return this.consumerId; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/LivePageCacheImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/LivePageCacheImpl.java index 1fc49d39ab..e319667b32 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/LivePageCacheImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/LivePageCacheImpl.java @@ -27,98 +27,82 @@ import org.apache.activemq.artemis.core.server.LargeServerMessage; /** * This is the same as PageCache, however this is for the page that's being currently written. */ -public class LivePageCacheImpl implements LivePageCache -{ +public class LivePageCacheImpl implements LivePageCache { + private final List messages = new LinkedList(); private final Page page; private boolean isLive = true; - public LivePageCacheImpl(final Page page) - { + public LivePageCacheImpl(final Page page) { this.page = page; } @Override - public long getPageId() - { + public long getPageId() { return page.getPageId(); } @Override - public synchronized int getNumberOfMessages() - { + public synchronized int getNumberOfMessages() { return messages.size(); } @Override - public synchronized void setMessages(PagedMessage[] messages) - { + public synchronized void setMessages(PagedMessage[] messages) { // This method shouldn't be called on liveCache, but we will provide the implementation for it anyway - for (PagedMessage msg : messages) - { + for (PagedMessage msg : messages) { addLiveMessage(msg); } } @Override - public synchronized PagedMessage getMessage(int messageNumber) - { - if (messageNumber < messages.size()) - { + public synchronized PagedMessage getMessage(int messageNumber) { + if (messageNumber < messages.size()) { return messages.get(messageNumber); } - else - { + else { return null; } } @Override - public void lock() - { + public void lock() { // nothing to be done on live cache } @Override - public void unlock() - { + public void unlock() { // nothing to be done on live cache } @Override - public synchronized boolean isLive() - { + public synchronized boolean isLive() { return isLive; } @Override - public synchronized void addLiveMessage(PagedMessage message) - { - if (message.getMessage().isLargeMessage()) - { - ((LargeServerMessage)message.getMessage()).incrementDelayDeletionCount(); + public synchronized void addLiveMessage(PagedMessage message) { + if (message.getMessage().isLargeMessage()) { + ((LargeServerMessage) message.getMessage()).incrementDelayDeletionCount(); } this.messages.add(message); } @Override - public synchronized void close() - { + public synchronized void close() { this.isLive = false; } @Override - public synchronized PagedMessage[] getMessages() - { + public synchronized PagedMessage[] getMessages() { return messages.toArray(new PagedMessage[messages.size()]); } @Override - public String toString() - { + public String toString() { return "LivePacheCacheImpl::page=" + page.getPageId() + " number of messages=" + messages.size() + " isLive = " + - isLive; + isLive; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/PageCacheImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/PageCacheImpl.java index 955a3984ee..f964d42406 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/PageCacheImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/PageCacheImpl.java @@ -26,8 +26,7 @@ import org.apache.activemq.artemis.core.paging.impl.Page; /** * The caching associated to a single page. */ -class PageCacheImpl implements PageCache -{ +class PageCacheImpl implements PageCache { // Constants ----------------------------------------------------- @@ -43,86 +42,69 @@ class PageCacheImpl implements PageCache // Constructors -------------------------------------------------- - public PageCacheImpl(final Page page) - { + public PageCacheImpl(final Page page) { this.page = page; } // Public -------------------------------------------------------- @Override - public PagedMessage getMessage(final int messageNumber) - { + public PagedMessage getMessage(final int messageNumber) { lock.readLock().lock(); - try - { - if (messageNumber < messages.length) - { + try { + if (messageNumber < messages.length) { return messages[messageNumber]; } - else - { + else { return null; } } - finally - { + finally { lock.readLock().unlock(); } } - public long getPageId() - { + public long getPageId() { return page.getPageId(); } - public void lock() - { + public void lock() { lock.writeLock().lock(); } - public void unlock() - { + public void unlock() { lock.writeLock().unlock(); } - public void setMessages(final PagedMessage[] messages) - { + public void setMessages(final PagedMessage[] messages) { this.messages = messages; } - public int getNumberOfMessages() - { + public int getNumberOfMessages() { lock.readLock().lock(); - try - { + try { return messages.length; } - finally - { + finally { lock.readLock().unlock(); } } - public void close() - { + public void close() { } @Override - public boolean isLive() - { + public boolean isLive() { return false; } @Override - public String toString() - { + public String toString() { return "PageCacheImpl::page=" + page.getPageId() + " numberOfMessages = " + messages.length; } @Override - public PagedMessage[] getMessages() - { + public PagedMessage[] getMessages() { return messages; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/PageCursorProviderImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/PageCursorProviderImpl.java index f931792cd3..437cd96b18 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/PageCursorProviderImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/PageCursorProviderImpl.java @@ -40,14 +40,14 @@ import org.apache.activemq.artemis.core.transaction.Transaction; import org.apache.activemq.artemis.core.transaction.impl.TransactionImpl; import org.apache.activemq.artemis.utils.FutureLatch; import org.apache.activemq.artemis.utils.SoftValueHashMap; + /** * A PageProviderIMpl * * TODO: this may be moved entirely into PagingStore as there's an one-to-one relationship here - * However I want to keep this isolated as much as possible during development + * However I want to keep this isolated as much as possible during development */ -public class PageCursorProviderImpl implements PageCursorProvider -{ +public class PageCursorProviderImpl implements PageCursorProvider { // Constants ----------------------------------------------------- boolean isTrace = ActiveMQServerLogger.LOGGER.isTraceEnabled(); @@ -79,8 +79,7 @@ public class PageCursorProviderImpl implements PageCursorProvider public PageCursorProviderImpl(final PagingStore pagingStore, final StorageManager storageManager, final Executor executor, - final int maxCacheSize) - { + final int maxCacheSize) { this.pagingStore = pagingStore; this.storageManager = storageManager; this.executor = executor; @@ -89,35 +88,28 @@ public class PageCursorProviderImpl implements PageCursorProvider // Public -------------------------------------------------------- - public synchronized PageSubscription createSubscription(long cursorID, Filter filter, boolean persistent) - { - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + public synchronized PageSubscription createSubscription(long cursorID, Filter filter, boolean persistent) { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace(this.pagingStore.getAddress() + " creating subscription " + cursorID + " with filter " + filter, new Exception("trace")); } - if (activeCursors.containsKey(cursorID)) - { + if (activeCursors.containsKey(cursorID)) { throw new IllegalStateException("Cursor " + cursorID + " had already been created"); } - PageSubscription activeCursor = - new PageSubscriptionImpl(this, pagingStore, storageManager, executor, filter, cursorID, persistent); + PageSubscription activeCursor = new PageSubscriptionImpl(this, pagingStore, storageManager, executor, filter, cursorID, persistent); activeCursors.put(cursorID, activeCursor); return activeCursor; } - public synchronized PageSubscription getSubscription(long cursorID) - { + public synchronized PageSubscription getSubscription(long cursorID) { return activeCursors.get(cursorID); } - public PagedMessage getMessage(final PagePosition pos) - { + public PagedMessage getMessage(final PagePosition pos) { PageCache cache = getPageCache(pos.getPageNr()); - if (cache == null || pos.getMessageNr() >= cache.getNumberOfMessages()) - { + if (cache == null || pos.getMessageNr() >= cache.getNumberOfMessages()) { // sanity check, this should never happen unless there's a bug throw new IllegalStateException("Invalid messageNumber passed = " + pos + " on " + cache); } @@ -127,29 +119,22 @@ public class PageCursorProviderImpl implements PageCursorProvider public PagedReference newReference(final PagePosition pos, final PagedMessage msg, - final PageSubscription subscription) - { + final PageSubscription subscription) { return new PagedReferenceImpl(pos, msg, subscription); } - public PageCache getPageCache(final long pageId) - { - try - { + public PageCache getPageCache(final long pageId) { + try { boolean needToRead = false; PageCache cache = null; - synchronized (softCache) - { - if (pageId > pagingStore.getCurrentWritingPage()) - { + synchronized (softCache) { + if (pageId > pagingStore.getCurrentWritingPage()) { return null; } cache = softCache.get(pageId); - if (cache == null) - { - if (!pagingStore.checkPageFileExists((int)pageId)) - { + if (cache == null) { + if (!pagingStore.checkPageFileExists((int) pageId)) { return null; } @@ -158,9 +143,8 @@ public class PageCursorProviderImpl implements PageCursorProvider // anyone reading from this cache will have to wait reading to finish first // we also want only one thread reading this cache cache.lock(); - if (isTrace) - { - ActiveMQServerLogger.LOGGER.trace("adding " + pageId + " into cursor = " + this.pagingStore.getAddress()); + if (isTrace) { + ActiveMQServerLogger.LOGGER.trace("adding " + pageId + " into cursor = " + this.pagingStore.getAddress()); } softCache.put(pageId, cache); } @@ -168,12 +152,10 @@ public class PageCursorProviderImpl implements PageCursorProvider // Reading is done outside of the synchronized block, however // the page stays locked until the entire reading is finished - if (needToRead) - { + if (needToRead) { Page page = null; - try - { - page = pagingStore.createPage((int)pageId); + try { + page = pagingStore.createPage((int) pageId); storageManager.beforePageRead(); page.open(); @@ -181,17 +163,13 @@ public class PageCursorProviderImpl implements PageCursorProvider List pgdMessages = page.read(storageManager); cache.setMessages(pgdMessages.toArray(new PagedMessage[pgdMessages.size()])); } - finally - { - try - { - if (page != null) - { + finally { + try { + if (page != null) { page.close(); } } - catch (Throwable ignored) - { + catch (Throwable ignored) { } storageManager.afterPageRead(); cache.unlock(); @@ -200,63 +178,49 @@ public class PageCursorProviderImpl implements PageCursorProvider return cache; } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException("Couldn't complete paging due to an IO Exception on Paging - " + e.getMessage(), e); } } - public void addPageCache(PageCache cache) - { - synchronized (softCache) - { + public void addPageCache(PageCache cache) { + synchronized (softCache) { softCache.put(cache.getPageId(), cache); } } - public void setCacheMaxSize(final int size) - { + public void setCacheMaxSize(final int size) { softCache.setMaxElements(size); } - public int getCacheSize() - { - synchronized (softCache) - { + public int getCacheSize() { + synchronized (softCache) { return softCache.size(); } } - public void clearCache() - { - synchronized (softCache) - { + public void clearCache() { + synchronized (softCache) { softCache.clear(); } } - public void processReload() throws Exception - { + public void processReload() throws Exception { Collection cursorList = this.activeCursors.values(); - for (PageSubscription cursor : cursorList) - { + for (PageSubscription cursor : cursorList) { cursor.processReload(); } - if (!cursorList.isEmpty()) - { + if (!cursorList.isEmpty()) { // https://issues.jboss.org/browse/JBPAPP-10338 if you ack out of order, // the min page could be beyond the first page. // we have to reload any previously acked message long cursorsMinPage = checkMinPage(cursorList); // checkMinPage will return MaxValue if there aren't any pages or any cursors - if (cursorsMinPage != Long.MAX_VALUE) - { - for (long startPage = pagingStore.getFirstPage(); startPage < cursorsMinPage; startPage++) - { - for (PageSubscription cursor : cursorList) - { + if (cursorsMinPage != Long.MAX_VALUE) { + for (long startPage = pagingStore.getFirstPage(); startPage < cursorsMinPage; startPage++) { + for (PageSubscription cursor : cursorList) { cursor.reloadPageInfo(startPage); } } @@ -267,50 +231,41 @@ public class PageCursorProviderImpl implements PageCursorProvider } - public void stop() - { - for (PageSubscription cursor : activeCursors.values()) - { + public void stop() { + for (PageSubscription cursor : activeCursors.values()) { cursor.stop(); } waitForFuture(); } - private void waitForFuture() - { + private void waitForFuture() { FutureLatch future = new FutureLatch(); executor.execute(future); - while (!future.await(10000)) - { + while (!future.await(10000)) { ActiveMQServerLogger.LOGGER.timedOutStoppingPagingCursor(future, executor); } } - public void flushExecutors() - { - for (PageSubscription cursor : activeCursors.values()) - { + public void flushExecutors() { + for (PageSubscription cursor : activeCursors.values()) { cursor.flushExecutors(); } waitForFuture(); } - public void close(PageSubscription cursor) - { + public void close(PageSubscription cursor) { activeCursors.remove(cursor.getId()); scheduleCleanup(); } @Override - public void scheduleCleanup() - { + public void scheduleCleanup() { - if (!cleanupEnabled || scheduledCleanup.intValue() > 2) - { + if (!cleanupEnabled || scheduledCleanup.intValue() > 2) { // Scheduled cleanup was already scheduled before.. never mind! // or we have cleanup disabled return; @@ -318,17 +273,13 @@ public class PageCursorProviderImpl implements PageCursorProvider scheduledCleanup.incrementAndGet(); - executor.execute(new Runnable() - { - public void run() - { + executor.execute(new Runnable() { + public void run() { storageManager.setContext(storageManager.newSingleThreadContext()); - try - { + try { cleanup(); } - finally - { + finally { storageManager.clearContext(); scheduledCleanup.decrementAndGet(); } @@ -342,74 +293,57 @@ public class PageCursorProviderImpl implements PageCursorProvider * Hence the PagingStore will be holding a write lock, meaning no messages are going to be paged at this time. * So, we shouldn't lock anything after this method, to avoid dead locks between the writeLock and any synchronization with the CursorProvider. */ - public void onPageModeCleared() - { + public void onPageModeCleared() { ArrayList subscriptions = cloneSubscriptions(); Transaction tx = new TransactionImpl(storageManager); - for (PageSubscription sub : subscriptions) - { - try - { + for (PageSubscription sub : subscriptions) { + try { sub.onPageModeCleared(tx); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.warn("Error while cleaning paging on queue " + sub.getQueue().getName(), e); } } - try - { + try { tx.commit(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.warn("Error while cleaning page, during the commit", e); } } - public void disableCleanup() - { + public void disableCleanup() { this.cleanupEnabled = false; } - public void resumeCleanup() - { + public void resumeCleanup() { this.cleanupEnabled = true; } - - public void cleanup() - { + public void cleanup() { ArrayList depagedPages = new ArrayList(); - while (true) - { - if (pagingStore.lock(100)) - { + while (true) { + if (pagingStore.lock(100)) { break; } if (!pagingStore.isStarted()) return; } - synchronized (this) - { - try - { - if (!pagingStore.isStarted()) - { + synchronized (this) { + try { + if (!pagingStore.isStarted()) { return; } - if (pagingStore.getNumberOfPages() == 0) - { + if (pagingStore.getNumberOfPages() == 0) { return; } - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Asserting cleanup for address " + this.pagingStore.getAddress()); } @@ -419,23 +353,19 @@ public class PageCursorProviderImpl implements PageCursorProvider // if the current page is being written... // on that case we need to move to verify it in a different way - if (minPage == pagingStore.getCurrentWritingPage() && pagingStore.getCurrentPage().getNumberOfMessages() > 0) - { + if (minPage == pagingStore.getCurrentWritingPage() && pagingStore.getCurrentPage().getNumberOfMessages() > 0) { boolean complete = checkPageCompletion(cursorList, minPage); - if (!pagingStore.isStarted()) - { + if (!pagingStore.isStarted()) { return; } // All the pages on the cursor are complete.. so we will cleanup everything and store a bookmark - if (complete) - { + if (complete) { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Address " + pagingStore.getAddress() + - " is leaving page mode as all messages are consumed and acknowledged from the page store"); + " is leaving page mode as all messages are consumed and acknowledged from the page store"); } pagingStore.forceAnotherPage(); @@ -448,85 +378,67 @@ public class PageCursorProviderImpl implements PageCursorProvider } } - for (long i = pagingStore.getFirstPage(); i < minPage; i++) - { - if (!checkPageCompletion(cursorList, i)) - { + for (long i = pagingStore.getFirstPage(); i < minPage; i++) { + if (!checkPageCompletion(cursorList, i)) { break; } Page page = pagingStore.depage(); - if (page == null) - { + if (page == null) { break; } depagedPages.add(page); } - if (pagingStore.getNumberOfPages() == 0 || pagingStore.getNumberOfPages() == 1 && - pagingStore.getCurrentPage().getNumberOfMessages() == 0) - { + if (pagingStore.getNumberOfPages() == 0 || pagingStore.getNumberOfPages() == 1 && pagingStore.getCurrentPage().getNumberOfMessages() == 0) { pagingStore.stopPaging(); } - else - { - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + else { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("Couldn't cleanup page on address " + this.pagingStore.getAddress() + - " as numberOfPages == " + - pagingStore.getNumberOfPages() + - " and currentPage.numberOfMessages = " + - pagingStore.getCurrentPage().getNumberOfMessages()); + " as numberOfPages == " + + pagingStore.getNumberOfPages() + + " and currentPage.numberOfMessages = " + + pagingStore.getCurrentPage().getNumberOfMessages()); } } } - catch (Exception ex) - { + catch (Exception ex) { ActiveMQServerLogger.LOGGER.problemCleaningPageAddress(ex, pagingStore.getAddress()); return; } - finally - { + finally { pagingStore.unlock(); } } - try - { - for (Page depagedPage : depagedPages) - { + try { + for (Page depagedPage : depagedPages) { PageCache cache; PagedMessage[] pgdMessages; - synchronized (softCache) - { - cache = softCache.get((long)depagedPage.getPageId()); + synchronized (softCache) { + cache = softCache.get((long) depagedPage.getPageId()); } - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Removing page " + depagedPage.getPageId() + " from page-cache"); } - if (cache == null) - { + if (cache == null) { // The page is not on cache any more // We need to read the page-file before deleting it // to make sure we remove any large-messages pending storageManager.beforePageRead(); List pgdMessagesList = null; - try - { + try { depagedPage.open(); pgdMessagesList = depagedPage.read(storageManager); } - finally - { - try - { + finally { + try { depagedPage.close(); } - catch (Exception e) - { + catch (Exception e) { } storageManager.afterPageRead(); @@ -534,69 +446,57 @@ public class PageCursorProviderImpl implements PageCursorProvider depagedPage.close(); pgdMessages = pgdMessagesList.toArray(new PagedMessage[pgdMessagesList.size()]); } - else - { + else { pgdMessages = cache.getMessages(); } depagedPage.delete(pgdMessages); onDeletePage(depagedPage); - synchronized (softCache) - { - softCache.remove((long)depagedPage.getPageId()); + synchronized (softCache) { + softCache.remove((long) depagedPage.getPageId()); } } } - catch (Exception ex) - { + catch (Exception ex) { ActiveMQServerLogger.LOGGER.problemCleaningPageAddress(ex, pagingStore.getAddress()); return; } } - - private boolean checkPageCompletion(ArrayList cursorList, long minPage) - { + private boolean checkPageCompletion(ArrayList cursorList, long minPage) { boolean complete = true; - for (PageSubscription cursor : cursorList) - { - if (!cursor.isComplete(minPage)) - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + for (PageSubscription cursor : cursorList) { + if (!cursor.isComplete(minPage)) { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Cursor " + cursor + " was considered incomplete at page " + minPage); } complete = false; break; } - else - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + else { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Cursor " + cursor + "was considered **complete** at page " + minPage); } } } return complete; } + /** * @return */ - private synchronized ArrayList cloneSubscriptions() - { + private synchronized ArrayList cloneSubscriptions() { ArrayList cursorList = new ArrayList(activeCursors.values()); return cursorList; } - protected void onDeletePage(Page deletedPage) throws Exception - { + protected void onDeletePage(Page deletedPage) throws Exception { List subscriptions = cloneSubscriptions(); - for (PageSubscription subs: subscriptions) - { + for (PageSubscription subs : subscriptions) { subs.onDeletePage(deletedPage); } } @@ -606,35 +506,27 @@ public class PageCursorProviderImpl implements PageCursorProvider * @param currentPage * @throws Exception */ - protected void storeBookmark(ArrayList cursorList, Page currentPage) throws Exception - { - try - { + protected void storeBookmark(ArrayList cursorList, Page currentPage) throws Exception { + try { // First step: Move every cursor to the next bookmarked page (that was just created) - for (PageSubscription cursor : cursorList) - { + for (PageSubscription cursor : cursorList) { cursor.confirmPosition(new PagePositionImpl(currentPage.getPageId(), -1)); } - while (!storageManager.waitOnOperations(5000)) - { + while (!storageManager.waitOnOperations(5000)) { ActiveMQServerLogger.LOGGER.problemCompletingOperations(storageManager.getContext()); } } - finally - { - for (PageSubscription cursor : cursorList) - { + finally { + for (PageSubscription cursor : cursorList) { cursor.enableAutoCleanup(); } } } - public void printDebug() - { + public void printDebug() { System.out.println("Debug information for PageCursorProviderImpl:"); - for (PageCache cache : softCache.values()) - { + for (PageCache cache : softCache.values()) { System.out.println("Cache " + cache); } } @@ -644,9 +536,8 @@ public class PageCursorProviderImpl implements PageCursorProvider // Protected ----------------------------------------------------- /* Protected as we may let test cases to instrument the test */ - protected PageCacheImpl createPageCache(final long pageId) throws Exception - { - return new PageCacheImpl(pagingStore.createPage((int)pageId)); + protected PageCacheImpl createPageCache(final long pageId) throws Exception { + return new PageCacheImpl(pagingStore.createPage((int) pageId)); } // Private ------------------------------------------------------- @@ -654,27 +545,22 @@ public class PageCursorProviderImpl implements PageCursorProvider /** * This method is synchronized because we want it to be atomic with the cursors being used */ - private long checkMinPage(Collection cursorList) - { + private long checkMinPage(Collection cursorList) { long minPage = Long.MAX_VALUE; - for (PageSubscription cursor : cursorList) - { + for (PageSubscription cursor : cursorList) { long firstPage = cursor.getFirstPage(); - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug(this.pagingStore.getAddress() + " has a cursor " + cursor + " with first page=" + firstPage); } // the cursor will return -1 if the cursor is empty - if (firstPage >= 0 && firstPage < minPage) - { + if (firstPage >= 0 && firstPage < minPage) { minPage = firstPage; } } - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug(this.pagingStore.getAddress() + " has minPage=" + minPage); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/PagePositionImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/PagePositionImpl.java index 0d150a5b0b..51dda9dd6b 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/PagePositionImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/PagePositionImpl.java @@ -18,8 +18,8 @@ package org.apache.activemq.artemis.core.paging.cursor.impl; import org.apache.activemq.artemis.core.paging.cursor.PagePosition; -public class PagePositionImpl implements PagePosition -{ +public class PagePositionImpl implements PagePosition { + private long pageNr; /** @@ -31,112 +31,98 @@ public class PagePositionImpl implements PagePosition */ private int messageNr; - /** ID used for storage */ + /** + * ID used for storage + */ private long recordID = -1; /** * @param pageNr * @param messageNr */ - public PagePositionImpl(long pageNr, int messageNr) - { + public PagePositionImpl(long pageNr, int messageNr) { this(); this.pageNr = pageNr; this.messageNr = messageNr; } - public PagePositionImpl() - { + public PagePositionImpl() { super(); } /** * @return the recordID */ - public long getRecordID() - { + public long getRecordID() { return recordID; } /** * @param recordID the recordID to set */ - public void setRecordID(long recordID) - { + public void setRecordID(long recordID) { this.recordID = recordID; } /** * @return the pageNr */ - public long getPageNr() - { + public long getPageNr() { return pageNr; } /** * @return the messageNr */ - public int getMessageNr() - { + public int getMessageNr() { return messageNr; } @Override - public int compareTo(PagePosition o) - { - if (pageNr > o.getPageNr()) - { + public int compareTo(PagePosition o) { + if (pageNr > o.getPageNr()) { return 1; } - else if (pageNr < o.getPageNr()) - { + else if (pageNr < o.getPageNr()) { return -1; } - else if (recordID > o.getRecordID()) - { + else if (recordID > o.getRecordID()) { return 1; } - else if (recordID < o.getRecordID()) - { + else if (recordID < o.getRecordID()) { return -1; } - else - { + else { return 0; } } - public PagePosition nextMessage() - { + public PagePosition nextMessage() { return new PagePositionImpl(this.pageNr, this.messageNr + 1); } - public PagePosition nextPage() - { + public PagePosition nextPage() { return new PagePositionImpl(this.pageNr + 1, 0); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + messageNr; - result = prime * result + (int)(pageNr ^ (pageNr >>> 32)); + result = prime * result + (int) (pageNr ^ (pageNr >>> 32)); return result; } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; - PagePositionImpl other = (PagePositionImpl)obj; + PagePositionImpl other = (PagePositionImpl) obj; if (messageNr != other.messageNr) return false; if (pageNr != other.pageNr) @@ -145,8 +131,7 @@ public class PagePositionImpl implements PagePosition } @Override - public String toString() - { + public String toString() { return "PagePositionImpl [pageNr=" + pageNr + ", messageNr=" + messageNr + ", recordID=" + recordID + "]"; } @@ -155,7 +140,6 @@ public class PagePositionImpl implements PagePosition * There is a rule for finalizing it where I'm establishing a counter, and that rule won't work without this method defined. * So, please don't remove it unless you had to remove that test for any weird reason.. it's here for a purpose! */ - protected void finalize() - { + protected void finalize() { } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/PageSubscriptionCounterImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/PageSubscriptionCounterImpl.java index 79f2aac466..5a0d94f7f3 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/PageSubscriptionCounterImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/PageSubscriptionCounterImpl.java @@ -39,8 +39,8 @@ import org.apache.activemq.artemis.core.transaction.impl.TransactionImpl; /** * This class will encapsulate the persistent counters for the PagingSubscription */ -public class PageSubscriptionCounterImpl implements PageSubscriptionCounter -{ +public class PageSubscriptionCounterImpl implements PageSubscriptionCounter { + private static final boolean isTrace = ActiveMQServerLogger.LOGGER.isTraceEnabled(); private static final int FLUSH_COUNTER = 1000; @@ -64,7 +64,6 @@ public class PageSubscriptionCounterImpl implements PageSubscriptionCounter private final LinkedList incrementRecords = new LinkedList(); - // We are storing pending counters for non transactional writes on page // we will recount a page case we still see pending records // as soon as we close a page we remove these records replacing by a regular page increment record @@ -73,10 +72,8 @@ public class PageSubscriptionCounterImpl implements PageSubscriptionCounter private LinkedList> loadList; - private final Runnable cleanupCheck = new Runnable() - { - public void run() - { + private final Runnable cleanupCheck = new Runnable() { + public void run() { cleanup(); } }; @@ -85,8 +82,7 @@ public class PageSubscriptionCounterImpl implements PageSubscriptionCounter final PageSubscription subscription, final Executor executor, final boolean persistent, - final long subscriptionID) - { + final long subscriptionID) { this.subscriptionID = subscriptionID; this.executor = executor; this.storage = storage; @@ -95,38 +91,33 @@ public class PageSubscriptionCounterImpl implements PageSubscriptionCounter } @Override - public long getValue() - { + public long getValue() { return value.get() + pendingValue.get(); } - /** * This is used only on non transactional paging + * * @param page * @param increment * @throws Exception */ @Override - public synchronized void pendingCounter(Page page, int increment) throws Exception - { - if (!persistent) - { + public synchronized void pendingCounter(Page page, int increment) throws Exception { + if (!persistent) { return; // nothing to be done } - Pair pendingInfo = pendingCounters.get((long)page.getPageId()); - if (pendingInfo == null) - { + Pair pendingInfo = pendingCounters.get((long) page.getPageId()); + if (pendingInfo == null) { // We have to make sure this is sync here // not syncing this to disk may cause the page files to be out of sync on pages. // we can't afford the case where a page file is written without a record here long id = storage.storePendingCounter(this.subscriptionID, page.getPageId(), increment); pendingInfo = new Pair(id, new AtomicInteger(1)); - pendingCounters.put((long)page.getPageId(), pendingInfo); + pendingCounters.put((long) page.getPageId(), pendingInfo); } - else - { + else { pendingInfo.getB().addAndGet(increment); } @@ -137,18 +128,16 @@ public class PageSubscriptionCounterImpl implements PageSubscriptionCounter /** * Cleanup temporary page counters on non transactional paged messages + * * @param pageID */ - public void cleanupNonTXCounters(final long pageID) throws Exception - { + public void cleanupNonTXCounters(final long pageID) throws Exception { Pair pendingInfo; - synchronized (this) - { + synchronized (this) { pendingInfo = pendingCounters.remove(pageID); } - if (pendingInfo != null) - { + if (pendingInfo != null) { final AtomicInteger valueCleaned = pendingInfo.getB(); Transaction tx = new TransactionImpl(storage); storage.deletePendingPageCounter(tx.getID(), pendingInfo.getA()); @@ -156,11 +145,9 @@ public class PageSubscriptionCounterImpl implements PageSubscriptionCounter // To apply the increment of the value just being cleaned increment(tx, valueCleaned.get()); - tx.addOperation(new TransactionOperationAbstract() - { + tx.addOperation(new TransactionOperationAbstract() { @Override - public void afterCommit(Transaction tx) - { + public void afterCommit(Transaction tx) { pendingValue.addAndGet(-valueCleaned.get()); } }); @@ -169,32 +156,24 @@ public class PageSubscriptionCounterImpl implements PageSubscriptionCounter } } - @Override - public void increment(Transaction tx, int add) throws Exception - { - if (tx == null) - { - if (persistent) - { + public void increment(Transaction tx, int add) throws Exception { + if (tx == null) { + if (persistent) { long id = storage.storePageCounterInc(this.subscriptionID, add); incrementProcessed(id, add); } - else - { + else { incrementProcessed(-1, add); } } - else - { - if (persistent) - { + else { + if (persistent) { tx.setContainsPersistent(); long id = storage.storePageCounterInc(tx.getID(), this.subscriptionID, add); applyIncrementOnTX(tx, id, add); } - else - { + else { applyIncrementOnTX(tx, -1, add); } } @@ -202,16 +181,15 @@ public class PageSubscriptionCounterImpl implements PageSubscriptionCounter /** * This method will install the TXs + * * @param tx * @param recordID1 * @param add */ - public void applyIncrementOnTX(Transaction tx, long recordID1, int add) - { - CounterOperations oper = (CounterOperations)tx.getProperty(TransactionPropertyIndexes.PAGE_COUNT_INC); + public void applyIncrementOnTX(Transaction tx, long recordID1, int add) { + CounterOperations oper = (CounterOperations) tx.getProperty(TransactionPropertyIndexes.PAGE_COUNT_INC); - if (oper == null) - { + if (oper == null) { oper = new CounterOperations(); tx.putProperty(TransactionPropertyIndexes.PAGE_COUNT_INC, oper); tx.addOperation(oper); @@ -220,10 +198,8 @@ public class PageSubscriptionCounterImpl implements PageSubscriptionCounter oper.operations.add(new ItemOper(this, recordID1, add)); } - public synchronized void loadValue(final long recordID1, final long value1) - { - if (this.subscription != null) - { + public synchronized void loadValue(final long recordID1, final long value1) { + if (this.subscription != null) { // it could be null on testcases... which is ok this.subscription.notEmpty(); } @@ -231,18 +207,15 @@ public class PageSubscriptionCounterImpl implements PageSubscriptionCounter this.recordID = recordID1; } - public synchronized void incrementProcessed(long id, int add) - { + public synchronized void incrementProcessed(long id, int add) { addInc(id, add); - if (incrementRecords.size() > FLUSH_COUNTER) - { + if (incrementRecords.size() > FLUSH_COUNTER) { executor.execute(cleanupCheck); } } - public void delete() throws Exception - { + public void delete() throws Exception { Transaction tx = new TransactionImpl(storage); delete(tx); @@ -250,22 +223,17 @@ public class PageSubscriptionCounterImpl implements PageSubscriptionCounter tx.commit(); } - public void delete(Transaction tx) throws Exception - { + public void delete(Transaction tx) throws Exception { // always lock the StorageManager first. storage.readLock(); - try - { - synchronized (this) - { - for (Long record : incrementRecords) - { + try { + synchronized (this) { + for (Long record : incrementRecords) { storage.deleteIncrementRecord(tx.getID(), record.longValue()); tx.setContainsPersistent(); } - if (recordID >= 0) - { + if (recordID >= 0) { storage.deletePageCounter(tx.getID(), this.recordID); tx.setContainsPersistent(); } @@ -275,34 +243,27 @@ public class PageSubscriptionCounterImpl implements PageSubscriptionCounter incrementRecords.clear(); } } - finally - { + finally { storage.readUnLock(); } } - public void loadInc(long id, int add) - { - if (loadList == null) - { + public void loadInc(long id, int add) { + if (loadList == null) { loadList = new LinkedList>(); } loadList.add(new Pair(id, add)); } - public void processReload() - { - if (loadList != null) - { - if (subscription != null) - { + public void processReload() { + if (loadList != null) { + if (subscription != null) { // it could be null on testcases subscription.notEmpty(); } - for (Pair incElement : loadList) - { + for (Pair incElement : loadList) { value.addAndGet(incElement.getB()); incrementRecords.add(incElement.getA()); } @@ -311,33 +272,30 @@ public class PageSubscriptionCounterImpl implements PageSubscriptionCounter } } - public synchronized void addInc(long id, int variance) - { + public synchronized void addInc(long id, int variance) { value.addAndGet(variance); - if (id >= 0) - { + if (id >= 0) { incrementRecords.add(id); } } - /** used on testing only */ - public void setPersistent(final boolean persistent) - { + /** + * used on testing only + */ + public void setPersistent(final boolean persistent) { this.persistent = persistent; } - - /** This method should always be called from a single threaded executor */ - protected void cleanup() - { + /** + * This method should always be called from a single threaded executor + */ + protected void cleanup() { ArrayList deleteList; long valueReplace; - synchronized (this) - { - if (incrementRecords.size() <= FLUSH_COUNTER) - { + synchronized (this) { + if (incrementRecords.size() <= FLUSH_COUNTER) { return; } valueReplace = value.get(); @@ -349,51 +307,41 @@ public class PageSubscriptionCounterImpl implements PageSubscriptionCounter long txCleanup = storage.generateID(); - try - { - for (Long value1 : deleteList) - { + try { + for (Long value1 : deleteList) { storage.deleteIncrementRecord(txCleanup, value1); } - if (recordID >= 0) - { + if (recordID >= 0) { storage.deletePageCounter(txCleanup, recordID); } newRecordID = storage.storePageCounter(txCleanup, subscriptionID, valueReplace); - if (isTrace) - { - ActiveMQServerLogger.LOGGER.trace("Replacing page-counter record = " + recordID + " by record = " + newRecordID + " on subscriptionID = " + this.subscriptionID + " for queue = " + this.subscription.getQueue().getName()); + if (isTrace) { + ActiveMQServerLogger.LOGGER.trace("Replacing page-counter record = " + recordID + " by record = " + newRecordID + " on subscriptionID = " + this.subscriptionID + " for queue = " + this.subscription.getQueue().getName()); } storage.commit(txCleanup); } - catch (Exception e) - { + catch (Exception e) { newRecordID = recordID; ActiveMQServerLogger.LOGGER.problemCleaningPagesubscriptionCounter(e); - try - { + try { storage.rollback(txCleanup); } - catch (Exception ignored) - { + catch (Exception ignored) { } } - finally - { + finally { recordID = newRecordID; } } - private static class ItemOper - { + private static class ItemOper { - public ItemOper(PageSubscriptionCounterImpl counter, long id, int add) - { + public ItemOper(PageSubscriptionCounterImpl counter, long id, int add) { this.counter = counter; this.id = id; this.amount = add; @@ -406,15 +354,13 @@ public class PageSubscriptionCounterImpl implements PageSubscriptionCounter int amount; } - private static class CounterOperations extends TransactionOperationAbstract implements TransactionOperation - { + private static class CounterOperations extends TransactionOperationAbstract implements TransactionOperation { + LinkedList operations = new LinkedList(); @Override - public void afterCommit(Transaction tx) - { - for (ItemOper oper : operations) - { + public void afterCommit(Transaction tx) { + for (ItemOper oper : operations) { oper.counter.incrementProcessed(oper.id, oper.amount); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/PageSubscriptionImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/PageSubscriptionImpl.java index e98da75183..2bb7cd9f49 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/PageSubscriptionImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/PageSubscriptionImpl.java @@ -57,8 +57,8 @@ import org.apache.activemq.artemis.core.transaction.impl.TransactionImpl; import org.apache.activemq.artemis.utils.ConcurrentHashSet; import org.apache.activemq.artemis.utils.FutureLatch; -final class PageSubscriptionImpl implements PageSubscription -{ +final class PageSubscriptionImpl implements PageSubscription { + private final boolean isTrace = ActiveMQServerLogger.LOGGER.isTraceEnabled(); private boolean empty = true; @@ -100,8 +100,7 @@ final class PageSubscriptionImpl implements PageSubscription final Executor executor, final Filter filter, final long cursorId, - final boolean persistent) - { + final boolean persistent) { this.pageStore = pageStore; this.store = store; this.cursorProvider = cursorProvider; @@ -114,76 +113,61 @@ final class PageSubscriptionImpl implements PageSubscription // Public -------------------------------------------------------- - public PagingStore getPagingStore() - { + public PagingStore getPagingStore() { return pageStore; } - public Queue getQueue() - { + public Queue getQueue() { return queue; } - public boolean isPaging() - { + public boolean isPaging() { return pageStore.isPaging(); } - public void setQueue(Queue queue) - { + public void setQueue(Queue queue) { this.queue = queue; } - public void disableAutoCleanup() - { + public void disableAutoCleanup() { autoCleanup = false; } - public void enableAutoCleanup() - { + public void enableAutoCleanup() { autoCleanup = true; } - public PageCursorProvider getProvider() - { + public PageCursorProvider getProvider() { return cursorProvider; } - public void notEmpty() - { - synchronized (consumedPages) - { + public void notEmpty() { + synchronized (consumedPages) { this.empty = false; } } - public void bookmark(PagePosition position) throws Exception - { + public void bookmark(PagePosition position) throws Exception { PageCursorInfo cursorInfo = getPageInfo(position); - if (position.getMessageNr() > 0) - { + if (position.getMessageNr() > 0) { cursorInfo.confirmed.addAndGet(position.getMessageNr()); } confirmPosition(position); } - public long getMessageCount() - { - if (empty) - { + public long getMessageCount() { + if (empty) { return 0; } - else - { + else { return counter.getValue() - deliveredCount.get(); } } - public PageSubscriptionCounter getCounter() - { + public PageSubscriptionCounter getCounter() { return counter; } @@ -194,41 +178,31 @@ final class PageSubscriptionImpl implements PageSubscription * TX) we may have big holes on the page streaming, and we will need to ignore such pages on the * cursor/subscription. */ - public void reloadPageCompletion(PagePosition position) - { + public void reloadPageCompletion(PagePosition position) { PageCursorInfo info = new PageCursorInfo(position.getPageNr(), position.getMessageNr(), null); info.setCompleteInfo(position); - synchronized (consumedPages) - { + synchronized (consumedPages) { consumedPages.put(Long.valueOf(position.getPageNr()), info); } } - public void scheduleCleanupCheck() - { - if (autoCleanup) - { - if (scheduledCleanupCount.get() > 2) - { + public void scheduleCleanupCheck() { + if (autoCleanup) { + if (scheduledCleanupCount.get() > 2) { return; } scheduledCleanupCount.incrementAndGet(); - executor.execute(new Runnable() - { + executor.execute(new Runnable() { - public void run() - { - try - { + public void run() { + try { cleanupEntries(false); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.problemCleaningCursorPages(e); } - finally - { + finally { scheduledCleanupCount.decrementAndGet(); } } @@ -236,10 +210,8 @@ final class PageSubscriptionImpl implements PageSubscription } } - public void onPageModeCleared(Transaction tx) throws Exception - { - if (counter != null) - { + public void onPageModeCleared(Transaction tx) throws Exception { + if (counter != null) { // this could be null on testcases counter.delete(tx); } @@ -249,10 +221,8 @@ final class PageSubscriptionImpl implements PageSubscription /** * It will cleanup all the records for completed pages */ - public void cleanupEntries(final boolean completeDelete) throws Exception - { - if (completeDelete) - { + public void cleanupEntries(final boolean completeDelete) throws Exception { + if (completeDelete) { counter.delete(); } Transaction tx = new TransactionImpl(store); @@ -262,30 +232,24 @@ final class PageSubscriptionImpl implements PageSubscription final ArrayList completedPages = new ArrayList(); // First get the completed pages using a lock - synchronized (consumedPages) - { + synchronized (consumedPages) { // lastAckedPosition = null means no acks were done yet, so we are not ready to cleanup - if (lastAckedPosition == null) - { + if (lastAckedPosition == null) { return; } - for (Entry entry : consumedPages.entrySet()) - { + for (Entry entry : consumedPages.entrySet()) { PageCursorInfo info = entry.getValue(); - if (info.isDone() && !info.isPendingDelete()) - { + if (info.isDone() && !info.isPendingDelete()) { Page currentPage = pageStore.getCurrentPage(); if (currentPage != null && entry.getKey() == pageStore.getCurrentPage().getPageId() && - currentPage.isLive()) - { + currentPage.isLive()) { ActiveMQServerLogger.LOGGER.trace("We can't clear page " + entry.getKey() + - " now since it's the current page"); + " now since it's the current page"); } - else - { + else { info.setPendingDelete(); completedPages.add(entry.getValue()); } @@ -293,8 +257,7 @@ final class PageSubscriptionImpl implements PageSubscription } } - for (PageCursorInfo infoPG : completedPages) - { + for (PageCursorInfo infoPG : completedPages) { // HORNETQ-1017: There are a few cases where a pending transaction might set a big hole on the page system // where we need to ignore these pages in case of a restart. // for that reason when we delete complete ACKs we store a single record per page file that will @@ -303,26 +266,21 @@ final class PageSubscriptionImpl implements PageSubscription // In case of a TX Failure (a crash on the server) this will be recovered on the next cleanup once the // server is restarted. // first will mark the page as complete - if (isPersistent()) - { + if (isPersistent()) { PagePosition completePage = new PagePositionImpl(infoPG.getPageId(), infoPG.getNumberOfMessages()); infoPG.setCompleteInfo(completePage); store.storePageCompleteTransactional(tx.getID(), this.getId(), completePage); - if (!persist) - { + if (!persist) { persist = true; tx.setContainsPersistent(); } } // it will delete the page ack records - for (PagePosition pos : infoPG.acks) - { - if (pos.getRecordID() >= 0) - { + for (PagePosition pos : infoPG.acks) { + if (pos.getRecordID() >= 0) { store.deleteCursorAcknowledgeTransactional(tx.getID(), pos.getRecordID()); - if (!persist) - { + if (!persist) { // only need to set it once tx.setContainsPersistent(); persist = true; @@ -334,19 +292,14 @@ final class PageSubscriptionImpl implements PageSubscription infoPG.removedReferences.clear(); } - tx.addOperation(new TransactionOperationAbstract() - { + tx.addOperation(new TransactionOperationAbstract() { @Override - public void afterCommit(final Transaction tx1) - { - executor.execute(new Runnable() - { + public void afterCommit(final Transaction tx1) { + executor.execute(new Runnable() { - public void run() - { - if (!completeDelete) - { + public void run() { + if (!completeDelete) { cursorProvider.scheduleCleanup(); } } @@ -359,89 +312,71 @@ final class PageSubscriptionImpl implements PageSubscription } @Override - public String toString() - { + public String toString() { return "PageSubscriptionImpl [cursorId=" + cursorId + ", queue=" + queue + ", filter = " + filter + "]"; } - private PagedReference getReference(PagePosition pos) - { + private PagedReference getReference(PagePosition pos) { return cursorProvider.newReference(pos, cursorProvider.getMessage(pos), this); } @Override - public PageIterator iterator() - { + public PageIterator iterator() { return new CursorIterator(); } - private PagedReference internalGetNext(final PagePosition pos) - { + private PagedReference internalGetNext(final PagePosition pos) { PagePosition retPos = pos.nextMessage(); PageCache cache = cursorProvider.getPageCache(pos.getPageNr()); - if (cache != null && !cache.isLive() && retPos.getMessageNr() >= cache.getNumberOfMessages()) - { + if (cache != null && !cache.isLive() && retPos.getMessageNr() >= cache.getNumberOfMessages()) { // The next message is beyond what's available at the current page, so we need to move to the next page cache = null; } // it will scan for the next available page - while ((cache == null && retPos.getPageNr() <= pageStore.getCurrentWritingPage()) || - (cache != null && retPos.getPageNr() <= pageStore.getCurrentWritingPage() && cache.getNumberOfMessages() == 0)) - { + while ((cache == null && retPos.getPageNr() <= pageStore.getCurrentWritingPage()) || (cache != null && retPos.getPageNr() <= pageStore.getCurrentWritingPage() && cache.getNumberOfMessages() == 0)) { retPos = moveNextPage(retPos); cache = cursorProvider.getPageCache(retPos.getPageNr()); } - if (cache == null) - { + if (cache == null) { // it will be null in the case of the current writing page return null; } - else - { + else { PagedMessage serverMessage = cache.getMessage(retPos.getMessageNr()); - if (serverMessage != null) - { + if (serverMessage != null) { return cursorProvider.newReference(retPos, serverMessage, this); } - else - { + else { return null; } } } - private PagePosition moveNextPage(final PagePosition pos) - { + private PagePosition moveNextPage(final PagePosition pos) { PagePosition retPos = pos; - while (true) - { + while (true) { retPos = retPos.nextPage(); - synchronized (consumedPages) - { + synchronized (consumedPages) { PageCursorInfo pageInfo = consumedPages.get(retPos.getPageNr()); // any deleted or complete page will be ignored on the moveNextPage, we will just keep going - if (pageInfo == null || (!pageInfo.isPendingDelete() && pageInfo.getCompleteInfo() == null)) - { + if (pageInfo == null || (!pageInfo.isPendingDelete() && pageInfo.getCompleteInfo() == null)) { return retPos; } } } } - private boolean routed(PagedMessage message) - { + private boolean routed(PagedMessage message) { long id = getId(); - for (long qid : message.getQueueIDs()) - { - if (qid == id) - { + for (long qid : message.getQueueIDs()) { + if (qid == id) { return true; } } @@ -451,116 +386,94 @@ final class PageSubscriptionImpl implements PageSubscription /** * */ - private synchronized PagePosition getStartPosition() - { + private synchronized PagePosition getStartPosition() { return new PagePositionImpl(pageStore.getFirstPage(), -1); } - public void confirmPosition(final Transaction tx, final PagePosition position) throws Exception - { + public void confirmPosition(final Transaction tx, final PagePosition position) throws Exception { // if the cursor is persistent - if (persistent) - { + if (persistent) { store.storeCursorAcknowledgeTransactional(tx.getID(), cursorId, position); } installTXCallback(tx, position); } - public void ackTx(final Transaction tx, final PagedReference reference) throws Exception - { + public void ackTx(final Transaction tx, final PagedReference reference) throws Exception { confirmPosition(tx, reference.getPosition()); counter.increment(tx, -1); PageTransactionInfo txInfo = getPageTransaction(reference); - if (txInfo != null) - { + if (txInfo != null) { txInfo.storeUpdate(store, pageStore.getPagingManager(), tx); } } @Override - public void ack(final PagedReference reference) throws Exception - { + public void ack(final PagedReference reference) throws Exception { // Need to do the ACK and counter atomically (inside a TX) or the counter could get out of sync Transaction tx = new TransactionImpl(this.store); ackTx(tx, reference); tx.commit(); } - public boolean contains(PagedReference ref) throws Exception - { + public boolean contains(PagedReference ref) throws Exception { // We first verify if the message was routed to this queue boolean routed = false; - for (long idRef : ref.getPagedMessage().getQueueIDs()) - { - if (idRef == this.cursorId) - { + for (long idRef : ref.getPagedMessage().getQueueIDs()) { + if (idRef == this.cursorId) { routed = true; break; } } - if (!routed) - { + if (!routed) { return false; } - else - { + else { // if it's been routed here, we have to verify if it was acked return !getPageInfo(ref.getPosition()).isAck(ref.getPosition()); } } - public void confirmPosition(final PagePosition position) throws Exception - { + public void confirmPosition(final PagePosition position) throws Exception { // if we are dealing with a persistent cursor - if (persistent) - { + if (persistent) { store.storeCursorAcknowledge(cursorId, position); } - store.afterCompleteOperations(new IOCallback() - { + store.afterCompleteOperations(new IOCallback() { volatile String error = ""; @Override - public void onError(final int errorCode, final String errorMessage) - { + public void onError(final int errorCode, final String errorMessage) { error = " errorCode=" + errorCode + ", msg=" + errorMessage; ActiveMQServerLogger.LOGGER.pageSubscriptionError(this, error); } @Override - public void done() - { + public void done() { processACK(position); } @Override - public String toString() - { + public String toString() { return IOCallback.class.getSimpleName() + "(" + PageSubscriptionImpl.class.getSimpleName() + ") " + error; } }); } @Override - public long getFirstPage() - { - synchronized (consumedPages) - { - if (empty && consumedPages.isEmpty()) - { + public long getFirstPage() { + synchronized (consumedPages) { + if (empty && consumedPages.isEmpty()) { return -1; } long lastPageSeen = 0; - for (Map.Entry info : consumedPages.entrySet()) - { + for (Map.Entry info : consumedPages.entrySet()) { lastPageSeen = info.getKey(); - if (!info.getValue().isDone() && !info.getValue().isPendingDelete()) - { + if (!info.getValue().isDone() && !info.getValue().isPendingDelete()) { return info.getKey(); } } @@ -569,39 +482,31 @@ final class PageSubscriptionImpl implements PageSubscription } - public void addPendingDelivery(final PagePosition position) - { + public void addPendingDelivery(final PagePosition position) { getPageInfo(position).incrementPendingTX(); } @Override - public void redeliver(final PageIterator iterator, final PagePosition position) - { + public void redeliver(final PageIterator iterator, final PagePosition position) { iterator.redeliver(position); - synchronized (consumedPages) - { + synchronized (consumedPages) { PageCursorInfo pageInfo = consumedPages.get(position.getPageNr()); - if (pageInfo != null) - { + if (pageInfo != null) { pageInfo.decrementPendingTX(); } - else - { + else { // this shouldn't really happen. } } } @Override - public PagedMessage queryMessage(PagePosition pos) - { - try - { + public PagedMessage queryMessage(PagePosition pos) { + try { return cursorProvider.getMessage(pos); } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } @@ -609,10 +514,8 @@ final class PageSubscriptionImpl implements PageSubscription /** * Theres no need to synchronize this method as it's only called from journal load on startup */ - public void reloadACK(final PagePosition position) - { - if (recoveredACK == null) - { + public void reloadACK(final PagePosition position) { + if (recoveredACK == null) { recoveredACK = new LinkedList(); } @@ -620,42 +523,34 @@ final class PageSubscriptionImpl implements PageSubscription } @Override - public void reloadPreparedACK(final Transaction tx, final PagePosition position) - { + public void reloadPreparedACK(final Transaction tx, final PagePosition position) { deliveredCount.incrementAndGet(); installTXCallback(tx, position); } @Override - public void positionIgnored(final PagePosition position) - { + public void positionIgnored(final PagePosition position) { processACK(position); } - public void lateDeliveryRollback(PagePosition position) - { + public void lateDeliveryRollback(PagePosition position) { PageCursorInfo cursorInfo = processACK(position); cursorInfo.decrementPendingTX(); } @Override - public boolean isComplete(long page) - { - synchronized (consumedPages) - { - if (empty && consumedPages.isEmpty()) - { + public boolean isComplete(long page) { + synchronized (consumedPages) { + if (empty && consumedPages.isEmpty()) { return true; } PageCursorInfo info = consumedPages.get(page); - if (info == null && empty) - { + if (info == null && empty) { return true; } - else - { + else { return info != null && info.isDone(); } } @@ -664,100 +559,79 @@ final class PageSubscriptionImpl implements PageSubscription /** * All the data associated with the cursor should go away here */ - public void destroy() throws Exception - { + public void destroy() throws Exception { final long tx = store.generateID(); - try - { + try { boolean isPersistent = false; - synchronized (consumedPages) - { - for (PageCursorInfo cursor : consumedPages.values()) - { - for (PagePosition info : cursor.acks) - { - if (info.getRecordID() >= 0) - { + synchronized (consumedPages) { + for (PageCursorInfo cursor : consumedPages.values()) { + for (PagePosition info : cursor.acks) { + if (info.getRecordID() >= 0) { isPersistent = true; store.deleteCursorAcknowledgeTransactional(tx, info.getRecordID()); } } PagePosition completeInfo = cursor.getCompleteInfo(); - if (completeInfo != null && completeInfo.getRecordID() >= 0) - { + if (completeInfo != null && completeInfo.getRecordID() >= 0) { store.deletePageComplete(completeInfo.getRecordID()); cursor.setCompleteInfo(null); } } } - if (isPersistent) - { + if (isPersistent) { store.commit(tx); } cursorProvider.close(this); } - catch (Exception e) - { - try - { + catch (Exception e) { + try { store.rollback(tx); } - catch (Exception ignored) - { + catch (Exception ignored) { // exception of the exception.. nothing that can be done here } } } @Override - public long getId() - { + public long getId() { return cursorId; } - public boolean isPersistent() - { + public boolean isPersistent() { return persistent; } - public void processReload() throws Exception - { - if (recoveredACK != null) - { - if (isTrace) - { + public void processReload() throws Exception { + if (recoveredACK != null) { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("********** processing reload!!!!!!!"); } Collections.sort(recoveredACK); long txDeleteCursorOnReload = -1; - for (PagePosition pos : recoveredACK) - { + for (PagePosition pos : recoveredACK) { lastAckedPosition = pos; PageCursorInfo pageInfo = getPageInfo(pos); - if (pageInfo == null) - { + if (pageInfo == null) { ActiveMQServerLogger.LOGGER.pageNotFound(pos); - if (txDeleteCursorOnReload == -1) - { + if (txDeleteCursorOnReload == -1) { txDeleteCursorOnReload = store.generateID(); } store.deleteCursorAcknowledgeTransactional(txDeleteCursorOnReload, pos.getRecordID()); } - else - { + else { pageInfo.loadACK(pos); } } - if (txDeleteCursorOnReload >= 0) - { + if (txDeleteCursorOnReload >= 0) { store.commit(txDeleteCursorOnReload); } @@ -766,68 +640,51 @@ final class PageSubscriptionImpl implements PageSubscription } } - public void flushExecutors() - { + public void flushExecutors() { FutureLatch future = new FutureLatch(); executor.execute(future); - while (!future.await(1000)) - { + while (!future.await(1000)) { ActiveMQServerLogger.LOGGER.timedOutFlushingExecutorsPagingCursor(this); } } - public void stop() - { + public void stop() { flushExecutors(); } - public void printDebug() - { + public void printDebug() { printDebug(toString()); } - public void printDebug(final String msg) - { + public void printDebug(final String msg) { System.out.println("Debug information on PageCurorImpl- " + msg); - for (PageCursorInfo info : consumedPages.values()) - { + for (PageCursorInfo info : consumedPages.values()) { System.out.println(info); } } - - public void onDeletePage(Page deletedPage) throws Exception - { + public void onDeletePage(Page deletedPage) throws Exception { PageCursorInfo info; - synchronized (consumedPages) - { + synchronized (consumedPages) { info = consumedPages.remove(Long.valueOf(deletedPage.getPageId())); } - if (info != null) - { + if (info != null) { PagePosition completeInfo = info.getCompleteInfo(); - if (completeInfo != null) - { - try - { + if (completeInfo != null) { + try { store.deletePageComplete(completeInfo.getRecordID()); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.warn("Error while deleting page-complete-record", e); } info.setCompleteInfo(null); } - for (PagePosition deleteInfo : info.acks) - { - if (deleteInfo.getRecordID() >= 0) - { - try - { + for (PagePosition deleteInfo : info.acks) { + if (deleteInfo.getRecordID() >= 0) { + try { store.deleteCursorAcknowledge(deleteInfo.getRecordID()); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.warn("Error while deleting page-complete-record", e); } } @@ -836,33 +693,25 @@ final class PageSubscriptionImpl implements PageSubscription } } - public Executor getExecutor() - { + public Executor getExecutor() { return executor; } - - public void reloadPageInfo(long pageNr) - { + public void reloadPageInfo(long pageNr) { getPageInfo(pageNr, true); } - private PageCursorInfo getPageInfo(final PagePosition pos) - { + private PageCursorInfo getPageInfo(final PagePosition pos) { return getPageInfo(pos.getPageNr(), true); } - private PageCursorInfo getPageInfo(final long pageNr, boolean create) - { - synchronized (consumedPages) - { + private PageCursorInfo getPageInfo(final long pageNr, boolean create) { + synchronized (consumedPages) { PageCursorInfo pageInfo = consumedPages.get(pageNr); - if (create && pageInfo == null) - { + if (create && pageInfo == null) { PageCache cache = cursorProvider.getPageCache(pageNr); - if (cache == null) - { + if (cache == null) { return null; } pageInfo = new PageCursorInfo(pageNr, cache.getNumberOfMessages(), cache); @@ -877,14 +726,11 @@ final class PageSubscriptionImpl implements PageSubscription // Protected ----------------------------------------------------- - private boolean match(final ServerMessage message) - { - if (filter == null) - { + private boolean match(final ServerMessage message) { + if (filter == null) { return true; } - else - { + else { return filter.match(message); } } @@ -893,24 +739,18 @@ final class PageSubscriptionImpl implements PageSubscription // To be called only after the ACK has been processed and guaranteed to be on storage // The only exception is on non storage events such as not matching messages - private PageCursorInfo processACK(final PagePosition pos) - { - if (lastAckedPosition == null || pos.compareTo(lastAckedPosition) > 0) - { - if (isTrace) - { + private PageCursorInfo processACK(final PagePosition pos) { + if (lastAckedPosition == null || pos.compareTo(lastAckedPosition) > 0) { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("a new position is being processed as ACK"); } - if (lastAckedPosition != null && lastAckedPosition.getPageNr() != pos.getPageNr()) - { - if (isTrace) - { + if (lastAckedPosition != null && lastAckedPosition.getPageNr() != pos.getPageNr()) { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Scheduling cleanup on pageSubscription for address = " + pageStore.getAddress() + " queue = " + this.getQueue().getName()); } // there's a different page being acked, we will do the check right away - if (autoCleanup) - { + if (autoCleanup) { scheduleCleanupCheck(); } } @@ -919,14 +759,12 @@ final class PageSubscriptionImpl implements PageSubscription PageCursorInfo info = getPageInfo(pos); // This could be null if the page file was removed - if (info == null) - { + if (info == null) { // This could become null if the page file was deleted, or if the queue was removed maybe? // it's better to diagnose it (based on support tickets) instead of NPE ActiveMQServerLogger.LOGGER.nullPageCursorInfo(this.getPagingStore().getAddress().toString(), pos.toString(), cursorId); } - else - { + else { info.addACK(pos); } @@ -937,10 +775,8 @@ final class PageSubscriptionImpl implements PageSubscription * @param tx * @param position */ - private void installTXCallback(final Transaction tx, final PagePosition position) - { - if (position.getRecordID() >= 0) - { + private void installTXCallback(final Transaction tx, final PagePosition position) { + if (position.getRecordID() >= 0) { // It needs to persist, otherwise the cursor will return to the fist page position tx.setContainsPersistent(); } @@ -949,8 +785,7 @@ final class PageSubscriptionImpl implements PageSubscription PageCursorTX cursorTX = (PageCursorTX) tx.getProperty(TransactionPropertyIndexes.PAGE_CURSOR_POSITIONS); - if (cursorTX == null) - { + if (cursorTX == null) { cursorTX = new PageCursorTX(); tx.putProperty(TransactionPropertyIndexes.PAGE_CURSOR_POSITIONS, cursorTX); tx.addOperation(cursorTX); @@ -960,14 +795,11 @@ final class PageSubscriptionImpl implements PageSubscription } - private PageTransactionInfo getPageTransaction(final PagedReference reference) - { - if (reference.getPagedMessage().getTransactionID() >= 0) - { + private PageTransactionInfo getPageTransaction(final PagedReference reference) { + if (reference.getPagedMessage().getTransactionID() >= 0) { return pageStore.getPagingManager().getTransaction(reference.getPagedMessage().getTransactionID()); } - else - { + else { return null; } } @@ -977,10 +809,8 @@ final class PageSubscriptionImpl implements PageSubscription * * @param info */ - private void onPageDone(final PageCursorInfo info) - { - if (autoCleanup) - { + private void onPageDone(final PageCursorInfo info) { + if (autoCleanup) { scheduleCleanupCheck(); } } @@ -993,8 +823,8 @@ final class PageSubscriptionImpl implements PageSubscription * This instance will be released as soon as the entire page is consumed, releasing the memory at * that point The ref counts are increased also when a message is ignored for any reason. */ - private final class PageCursorInfo - { + private final class PageCursorInfo { + // Number of messages existent on this page private final int numberOfMessages; @@ -1027,16 +857,12 @@ final class PageSubscriptionImpl implements PageSubscription // expressions private final AtomicInteger confirmed = new AtomicInteger(0); - - public boolean isAck(PagePosition position) - { - return completePage != null || - acks.contains(position); + public boolean isAck(PagePosition position) { + return completePage != null || acks.contains(position); } @Override - public String toString() - { + public String toString() { return "PageCursorInfo::PageID=" + pageId + " numberOfMessage = " + numberOfMessages + @@ -1046,17 +872,14 @@ final class PageSubscriptionImpl implements PageSubscription this.isDone(); } - public PageCursorInfo(final long pageId, final int numberOfMessages, final PageCache cache) - { + public PageCursorInfo(final long pageId, final int numberOfMessages, final PageCache cache) { this.pageId = pageId; this.numberOfMessages = numberOfMessages; - if (cache != null) - { + if (cache != null) { wasLive = cache.isLive(); this.cache = new WeakReference(cache); } - else - { + else { wasLive = false; } } @@ -1064,94 +887,78 @@ final class PageSubscriptionImpl implements PageSubscription /** * @param completePage */ - public void setCompleteInfo(final PagePosition completePage) - { + public void setCompleteInfo(final PagePosition completePage) { this.completePage = completePage; } - public PagePosition getCompleteInfo() - { + public PagePosition getCompleteInfo() { return completePage; } - public boolean isDone() - { + public boolean isDone() { return completePage != null || (getNumberOfMessages() == confirmed.get() && pendingTX.get() == 0); } - public boolean isPendingDelete() - { + public boolean isPendingDelete() { return pendingDelete || completePage != null; } - public void setPendingDelete() - { + public void setPendingDelete() { pendingDelete = true; } /** * @return the pageId */ - public long getPageId() - { + public long getPageId() { return pageId; } - public void incrementPendingTX() - { + public void incrementPendingTX() { pendingTX.incrementAndGet(); } - public void decrementPendingTX() - { + public void decrementPendingTX() { pendingTX.decrementAndGet(); checkDone(); } - public boolean isRemoved(final PagePosition pos) - { + public boolean isRemoved(final PagePosition pos) { return removedReferences.contains(pos); } - public void remove(final PagePosition position) - { + public void remove(final PagePosition position) { removedReferences.add(position); } - public void addACK(final PagePosition posACK) - { + public void addACK(final PagePosition posACK) { - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("numberOfMessages = " + getNumberOfMessages() + - " confirmed = " + - (confirmed.get() + 1) + - " pendingTX = " + pendingTX + - ", page = " + - pageId + " posACK = " + posACK); + " confirmed = " + + (confirmed.get() + 1) + + " pendingTX = " + pendingTX + + ", page = " + + pageId + " posACK = " + posACK); } boolean added = internalAddACK(posACK); // Negative could mean a bookmark on the first element for the page (example -1) - if (added && posACK.getMessageNr() >= 0) - { + if (added && posACK.getMessageNr() >= 0) { confirmed.incrementAndGet(); checkDone(); } } // To be called during reload - public void loadACK(final PagePosition posACK) - { - if (internalAddACK(posACK) && posACK.getMessageNr() >= 0) - { + public void loadACK(final PagePosition posACK) { + if (internalAddACK(posACK) && posACK.getMessageNr() >= 0) { confirmed.incrementAndGet(); } } - private boolean internalAddACK(final PagePosition posACK) - { + private boolean internalAddACK(final PagePosition posACK) { removedReferences.add(posACK); return acks.add(posACK); } @@ -1159,48 +966,39 @@ final class PageSubscriptionImpl implements PageSubscription /** * */ - protected void checkDone() - { - if (isDone()) - { + protected void checkDone() { + if (isDone()) { onPageDone(this); } } - private int getNumberOfMessages() - { - if (wasLive) - { + private int getNumberOfMessages() { + if (wasLive) { // if the page was live at any point, we need to // get the number of messages from the page-cache PageCache localcache = this.cache.get(); - if (localcache == null) - { + if (localcache == null) { localcache = cursorProvider.getPageCache(pageId); this.cache = new WeakReference(localcache); } return localcache.getNumberOfMessages(); } - else - { + else { return numberOfMessages; } } } - private static final class PageCursorTX extends TransactionOperationAbstract - { - private final Map> pendingPositions = - new HashMap>(); + private static final class PageCursorTX extends TransactionOperationAbstract { - private void addPositionConfirmation(final PageSubscriptionImpl cursor, final PagePosition position) - { + private final Map> pendingPositions = new HashMap>(); + + private void addPositionConfirmation(final PageSubscriptionImpl cursor, final PagePosition position) { List list = pendingPositions.get(cursor); - if (list == null) - { + if (list == null) { list = new LinkedList(); pendingPositions.put(cursor, list); } @@ -1209,16 +1007,13 @@ final class PageSubscriptionImpl implements PageSubscription } @Override - public void afterCommit(final Transaction tx) - { - for (Entry> entry : pendingPositions.entrySet()) - { + public void afterCommit(final Transaction tx) { + for (Entry> entry : pendingPositions.entrySet()) { PageSubscriptionImpl cursor = entry.getKey(); List positions = entry.getValue(); - for (PagePosition confirmed : positions) - { + for (PagePosition confirmed : positions) { cursor.processACK(confirmed); cursor.deliveredCount.decrementAndGet(); } @@ -1227,15 +1022,14 @@ final class PageSubscriptionImpl implements PageSubscription } @Override - public List getRelatedMessageReferences() - { + public List getRelatedMessageReferences() { return Collections.emptyList(); } } - private class CursorIterator implements PageIterator - { + private class CursorIterator implements PageIterator { + private PagePosition position = null; private PagePosition lastOperation = null; @@ -1255,72 +1049,56 @@ final class PageSubscriptionImpl implements PageSubscription */ private volatile PagedReference cachedNext; - public CursorIterator() - { + public CursorIterator() { } - public void redeliver(PagePosition reference) - { - synchronized (redeliveries) - { + public void redeliver(PagePosition reference) { + synchronized (redeliveries) { redeliveries.add(reference); } } - public void repeat() - { - if (isredelivery) - { - synchronized (redeliveries) - { + public void repeat() { + if (isredelivery) { + synchronized (redeliveries) { cachedNext = lastRedelivery; } } - else - { - if (lastOperation == null) - { + else { + if (lastOperation == null) { position = null; } - else - { + else { position = lastOperation; } } } @Override - public synchronized PagedReference next() - { + public synchronized PagedReference next() { - if (cachedNext != null) - { + if (cachedNext != null) { currentDelivery = cachedNext; cachedNext = null; return currentDelivery; } - try - { - if (position == null) - { + try { + if (position == null) { position = getStartPosition(); } currentDelivery = moveNext(); return currentDelivery; } - catch (RuntimeException e) - { + catch (RuntimeException e) { e.printStackTrace(); throw e; } } - private PagedReference moveNext() - { - synchronized (PageSubscriptionImpl.this) - { + private PagedReference moveNext() { + synchronized (PageSubscriptionImpl.this) { boolean match = false; PagedReference message; @@ -1328,14 +1106,11 @@ final class PageSubscriptionImpl implements PageSubscription PagePosition lastPosition = position; PagePosition tmpPosition = position; - do - { - synchronized (redeliveries) - { + do { + synchronized (redeliveries) { PagePosition redelivery = redeliveries.poll(); - if (redelivery != null) - { + if (redelivery != null) { // There's a redelivery pending, we will get it out of that pool instead isredelivery = true; PagedReference redeliveredMsg = getReference(redelivery); @@ -1343,8 +1118,7 @@ final class PageSubscriptionImpl implements PageSubscription return redeliveredMsg; } - else - { + else { lastRedelivery = null; isredelivery = false; } @@ -1352,8 +1126,7 @@ final class PageSubscriptionImpl implements PageSubscription message = internalGetNext(tmpPosition); } - if (message == null) - { + if (message == null) { break; } @@ -1367,34 +1140,26 @@ final class PageSubscriptionImpl implements PageSubscription // 1st... is it routed? valid = routed(message.getPagedMessage()); - if (!valid) - { + if (!valid) { ignored = true; } PageCursorInfo info = getPageInfo(message.getPosition().getPageNr(), false); - if (info != null && (info.isRemoved(message.getPosition()) || info.getCompleteInfo() != null)) - { + if (info != null && (info.isRemoved(message.getPosition()) || info.getCompleteInfo() != null)) { continue; } // 2nd ... if TX, is it committed? - if (valid && message.getPagedMessage().getTransactionID() >= 0) - { - PageTransactionInfo tx = pageStore.getPagingManager().getTransaction(message.getPagedMessage() - .getTransactionID()); - if (tx == null) - { - ActiveMQServerLogger.LOGGER.pageSubscriptionCouldntLoad(message.getPagedMessage().getTransactionID(), - message.getPosition(), pageStore.getAddress(), queue.getName()); + if (valid && message.getPagedMessage().getTransactionID() >= 0) { + PageTransactionInfo tx = pageStore.getPagingManager().getTransaction(message.getPagedMessage().getTransactionID()); + if (tx == null) { + ActiveMQServerLogger.LOGGER.pageSubscriptionCouldntLoad(message.getPagedMessage().getTransactionID(), message.getPosition(), pageStore.getAddress(), queue.getName()); valid = false; ignored = true; } - else - { - if (tx.deliverAfterCommit(CursorIterator.this, PageSubscriptionImpl.this, message.getPosition())) - { + else { + if (tx.deliverAfterCommit(CursorIterator.this, PageSubscriptionImpl.this, message.getPosition())) { valid = false; ignored = false; } @@ -1402,42 +1167,34 @@ final class PageSubscriptionImpl implements PageSubscription } // 3rd... was it previously removed? - if (valid) - { + if (valid) { // We don't create a PageCursorInfo unless we are doing a write operation (ack or removing) // Say you have a Browser that will only read the files... there's no need to control PageCursors is // nothing // is being changed. That's why the false is passed as a parameter here - if (info != null && info.isRemoved(message.getPosition())) - { + if (info != null && info.isRemoved(message.getPosition())) { valid = false; } } - if (!ignored) - { + if (!ignored) { position = message.getPosition(); } - if (valid) - { + if (valid) { match = match(message.getMessage()); - if (!match) - { + if (!match) { processACK(message.getPosition()); } } - else if (ignored) - { + else if (ignored) { positionIgnored(message.getPosition()); } - } - while (message != null && !match); + } while (message != null && !match); - if (message != null) - { + if (message != null) { lastOperation = lastPosition; } @@ -1449,16 +1206,13 @@ final class PageSubscriptionImpl implements PageSubscription * QueueImpl::deliver could be calling hasNext while QueueImpl.depage could be using next and hasNext as well. * It would be a rare race condition but I would prefer avoiding that scenario */ - public synchronized boolean hasNext() - { + public synchronized boolean hasNext() { // if an unbehaved program called hasNext twice before next, we only cache it once. - if (cachedNext != null) - { + if (cachedNext != null) { return true; } - if (!pageStore.isPaging()) - { + if (!pageStore.isPaging()) { return false; } @@ -1468,23 +1222,19 @@ final class PageSubscriptionImpl implements PageSubscription } @Override - public void remove() - { + public void remove() { deliveredCount.incrementAndGet(); PagedReference delivery = currentDelivery; - if (delivery != null) - { + if (delivery != null) { PageCursorInfo info = PageSubscriptionImpl.this.getPageInfo(delivery.getPosition()); - if (info != null) - { + if (info != null) { info.remove(delivery.getPosition()); } } } @Override - public void close() - { + public void close() { } } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/Page.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/Page.java index ae41bb0b1f..1bf9f2a1a7 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/Page.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/Page.java @@ -37,8 +37,8 @@ import org.apache.activemq.artemis.core.server.LargeServerMessage; import org.apache.activemq.artemis.utils.ConcurrentHashSet; import org.apache.activemq.artemis.utils.DataConstants; -public final class Page implements Comparable -{ +public final class Page implements Comparable { + // Constants ----------------------------------------------------- private static final boolean isTrace = ActiveMQServerLogger.LOGGER.isTraceEnabled(); private static final boolean isDebug = ActiveMQServerLogger.LOGGER.isDebugEnabled(); @@ -81,8 +81,7 @@ public final class Page implements Comparable final StorageManager storageManager, final SequentialFileFactory factory, final SequentialFile file, - final int pageId) throws Exception - { + final int pageId) throws Exception { this.pageId = pageId; this.file = file; fileFactory = factory; @@ -90,25 +89,20 @@ public final class Page implements Comparable this.storeName = storeName; } - public int getPageId() - { + public int getPageId() { return pageId; } - public void setLiveCache(LivePageCache pageCache) - { + public void setLiveCache(LivePageCache pageCache) { this.pageCache = pageCache; } - public synchronized List read(StorageManager storage) throws Exception - { - if (isDebug) - { + public synchronized List read(StorageManager storage) throws Exception { + if (isDebug) { ActiveMQServerLogger.LOGGER.debug("reading page " + this.pageId + " on address = " + storeName); } - if (!file.isOpen()) - { + if (!file.isOpen()) { throw ActiveMQMessageBundle.BUNDLE.invalidPageIO(); } @@ -118,8 +112,7 @@ public final class Page implements Comparable // Using direct buffer, as described on https://jira.jboss.org/browse/HORNETQ-467 ByteBuffer directBuffer = storage.allocateDirectBuffer((int) file.size()); ActiveMQBuffer fileBuffer = null; - try - { + try { file.position(0); file.read(directBuffer); @@ -129,56 +122,45 @@ public final class Page implements Comparable fileBuffer = ActiveMQBuffers.wrappedBuffer(directBuffer); fileBuffer.writerIndex(fileBuffer.capacity()); - while (fileBuffer.readable()) - { + while (fileBuffer.readable()) { final int position = fileBuffer.readerIndex(); byte byteRead = fileBuffer.readByte(); - if (byteRead == Page.START_BYTE) - { - if (fileBuffer.readerIndex() + DataConstants.SIZE_INT < fileBuffer.capacity()) - { + if (byteRead == Page.START_BYTE) { + if (fileBuffer.readerIndex() + DataConstants.SIZE_INT < fileBuffer.capacity()) { int messageSize = fileBuffer.readInt(); int oldPos = fileBuffer.readerIndex(); - if (fileBuffer.readerIndex() + messageSize < fileBuffer.capacity() && - fileBuffer.getByte(oldPos + messageSize) == Page.END_BYTE) - { + if (fileBuffer.readerIndex() + messageSize < fileBuffer.capacity() && fileBuffer.getByte(oldPos + messageSize) == Page.END_BYTE) { PagedMessage msg = new PagedMessageImpl(); msg.decode(fileBuffer); byte b = fileBuffer.readByte(); - if (b != Page.END_BYTE) - { + if (b != Page.END_BYTE) { // Sanity Check: This would only happen if there is a bug on decode or any internal code, as // this // constraint was already checked throw new IllegalStateException("Internal error, it wasn't possible to locate END_BYTE " + b); } msg.initMessage(storage); - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Reading message " + msg + " on pageId=" + this.pageId + " for address=" + storeName); } messages.add(msg); } - else - { + else { markFileAsSuspect(file.getFileName(), position, messages.size()); break; } } } - else - { + else { markFileAsSuspect(file.getFileName(), position, messages.size()); break; } } } - finally - { - if (fileBuffer != null) - { + finally { + if (fileBuffer != null) { fileBuffer.byteBuf().unwrap().release(); } storage.freeDirectBuffer(directBuffer); @@ -189,10 +171,8 @@ public final class Page implements Comparable return messages; } - public synchronized void write(final PagedMessage message) throws Exception - { - if (!file.isOpen()) - { + public synchronized void write(final PagedMessage message) throws Exception { + if (!file.isOpen()) { return; } @@ -214,8 +194,7 @@ public final class Page implements Comparable file.writeDirect(buffer, false); - if (pageCache != null) - { + if (pageCache != null) { pageCache.addLiveMessage(message); } @@ -225,29 +204,23 @@ public final class Page implements Comparable storageManager.pageWrite(message, pageId); } - public void sync() throws Exception - { + public void sync() throws Exception { file.sync(); } - public void open() throws Exception - { - if (!file.isOpen()) - { + public void open() throws Exception { + if (!file.isOpen()) { file.open(); } size.set((int) file.size()); file.position(0); } - public synchronized void close() throws Exception - { - if (storageManager != null) - { + public synchronized void close() throws Exception { + if (storageManager != null) { storageManager.pageClosed(storeName, pageId); } - if (pageCache != null) - { + if (pageCache != null) { pageCache.close(); // leave it to the soft cache to decide when to release it now pageCache = null; @@ -255,38 +228,29 @@ public final class Page implements Comparable file.close(); Set counters = getPendingCounters(); - if (counters != null) - { - for (PageSubscriptionCounter counter : counters) - { + if (counters != null) { + for (PageSubscriptionCounter counter : counters) { counter.cleanupNonTXCounters(this.getPageId()); } } } - public boolean isLive() - { + public boolean isLive() { return pageCache != null; } - public boolean delete(final PagedMessage[] messages) throws Exception - { - if (storageManager != null) - { + public boolean delete(final PagedMessage[] messages) throws Exception { + if (storageManager != null) { storageManager.pageDeleted(storeName, pageId); } - if (isDebug) - { + if (isDebug) { ActiveMQServerLogger.LOGGER.debug("Deleting pageId=" + pageId + " on store " + storeName); } - if (messages != null) - { - for (PagedMessage msg : messages) - { - if (msg.getMessage().isLargeMessage()) - { + if (messages != null) { + for (PagedMessage msg : messages) { + if (msg.getMessage().isLargeMessage()) { LargeServerMessage lmsg = (LargeServerMessage) msg.getMessage(); // Remember, cannot call delete directly here @@ -297,68 +261,54 @@ public final class Page implements Comparable } } - try - { - if (suspiciousRecords) - { + try { + if (suspiciousRecords) { ActiveMQServerLogger.LOGGER.pageInvalid(file.getFileName(), file.getFileName()); file.renameTo(file.getFileName() + ".invalidPage"); } - else - { + else { file.delete(); } return true; } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.pageDeleteError(e); return false; } } - public int getNumberOfMessages() - { + public int getNumberOfMessages() { return numberOfMessages.intValue(); } - public int getSize() - { + public int getSize() { return size.intValue(); } @Override - public String toString() - { + public String toString() { return "Page::pageID=" + this.pageId + ", file=" + this.file; } - - public int compareTo(Page otherPage) - { + public int compareTo(Page otherPage) { return otherPage.getPageId() - this.pageId; } @Override - protected void finalize() - { - try - { - if (file != null && file.isOpen()) - { + protected void finalize() { + try { + if (file != null && file.isOpen()) { file.close(); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.pageFinaliseError(e); } } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + pageId; @@ -366,8 +316,7 @@ public final class Page implements Comparable } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) @@ -384,14 +333,12 @@ public final class Page implements Comparable * @param position * @param msgNumber */ - private void markFileAsSuspect(final String fileName, final int position, final int msgNumber) - { + private void markFileAsSuspect(final String fileName, final int position, final int msgNumber) { ActiveMQServerLogger.LOGGER.pageSuspectFile(fileName, position, msgNumber); suspiciousRecords = true; } - public SequentialFile getFile() - { + public SequentialFile getFile() { return file; } @@ -400,21 +347,17 @@ public final class Page implements Comparable * * @param pageSubscriptionCounter */ - public void addPendingCounter(PageSubscriptionCounter pageSubscriptionCounter) - { + public void addPendingCounter(PageSubscriptionCounter pageSubscriptionCounter) { Set counter = getOrCreatePendingCounters(); pendingCounters.add(pageSubscriptionCounter); } - private synchronized Set getPendingCounters() - { + private synchronized Set getPendingCounters() { return pendingCounters; } - private synchronized Set getOrCreatePendingCounters() - { - if (pendingCounters == null) - { + private synchronized Set getOrCreatePendingCounters() { + if (pendingCounters == null) { pendingCounters = new ConcurrentHashSet(); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PageSyncTimer.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PageSyncTimer.java index 58052fa587..a8d24c7dfb 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PageSyncTimer.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PageSyncTimer.java @@ -28,8 +28,7 @@ import org.apache.activemq.artemis.core.persistence.OperationContext; /** * This will batch multiple calls waiting to perform a sync in a single call. */ -final class PageSyncTimer -{ +final class PageSyncTimer { // Constants ----------------------------------------------------- @@ -43,10 +42,8 @@ final class PageSyncTimer private final long timeSync; - private final Runnable runnable = new Runnable() - { - public void run() - { + private final Runnable runnable = new Runnable() { + public void run() { tick(); } }; @@ -57,8 +54,7 @@ final class PageSyncTimer // Constructors -------------------------------------------------- - PageSyncTimer(PagingStore store, ScheduledExecutorService scheduledExecutor, long timeSync) - { + PageSyncTimer(PagingStore store, ScheduledExecutorService scheduledExecutor, long timeSync) { this.store = store; this.scheduledExecutor = scheduledExecutor; this.timeSync = timeSync; @@ -66,22 +62,18 @@ final class PageSyncTimer // Public -------------------------------------------------------- - synchronized void addSync(OperationContext ctx) - { + synchronized void addSync(OperationContext ctx) { ctx.pageSyncLineUp(); - if (!pendingSync) - { + if (!pendingSync) { pendingSync = true; scheduledExecutor.schedule(runnable, timeSync, TimeUnit.NANOSECONDS); } syncOperations.add(ctx); } - private void tick() - { - OperationContext [] pendingSyncsArray; - synchronized (this) - { + private void tick() { + OperationContext[] pendingSyncsArray; + synchronized (this) { pendingSync = false; pendingSyncsArray = new OperationContext[syncOperations.size()]; @@ -89,27 +81,21 @@ final class PageSyncTimer syncOperations.clear(); } - try - { - if (pendingSyncsArray.length != 0) - { + try { + if (pendingSyncsArray.length != 0) { store.ioSync(); } } - catch (Exception e) - { - for (OperationContext ctx : pendingSyncsArray) - { + catch (Exception e) { + for (OperationContext ctx : pendingSyncsArray) { ctx.onError(ActiveMQExceptionType.IO_ERROR.getCode(), e.getMessage()); } } - finally - { + finally { // In case of failure, The context should propagate an exception to the client // We send an exception to the client even on the case of a failure // to avoid possible locks and the client not getting the exception back - for (OperationContext ctx : pendingSyncsArray) - { + for (OperationContext ctx : pendingSyncsArray) { ctx.pageSyncDone(); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PageTransactionInfoImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PageTransactionInfoImpl.java index 066c29bac7..f6990d6cbf 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PageTransactionInfoImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PageTransactionInfoImpl.java @@ -35,8 +35,7 @@ import org.apache.activemq.artemis.core.transaction.TransactionOperationAbstract import org.apache.activemq.artemis.core.transaction.TransactionPropertyIndexes; import org.apache.activemq.artemis.utils.DataConstants; -public final class PageTransactionInfoImpl implements PageTransactionInfo -{ +public final class PageTransactionInfoImpl implements PageTransactionInfo { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -61,44 +60,35 @@ public final class PageTransactionInfoImpl implements PageTransactionInfo // Constructors -------------------------------------------------- - public PageTransactionInfoImpl(final long transactionID) - { + public PageTransactionInfoImpl(final long transactionID) { this(); this.transactionID = transactionID; } - public PageTransactionInfoImpl() - { + public PageTransactionInfoImpl() { } // Public -------------------------------------------------------- - public long getRecordID() - { + public long getRecordID() { return recordID; } - public void setRecordID(final long recordID) - { + public void setRecordID(final long recordID) { this.recordID = recordID; } - public long getTransactionID() - { + public long getTransactionID() { return transactionID; } - public void onUpdate(final int update, final StorageManager storageManager, PagingManager pagingManager) - { + public void onUpdate(final int update, final StorageManager storageManager, PagingManager pagingManager) { int sizeAfterUpdate = numberOfMessages.addAndGet(-update); - if (sizeAfterUpdate == 0 && storageManager != null) - { - try - { + if (sizeAfterUpdate == 0 && storageManager != null) { + try { storageManager.deletePageTransactional(this.recordID); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.pageTxDeleteError(e, recordID); } @@ -106,45 +96,37 @@ public final class PageTransactionInfoImpl implements PageTransactionInfo } } - public void increment(final int durableSize, final int nonDurableSize) - { + public void increment(final int durableSize, final int nonDurableSize) { numberOfPersistentMessages.addAndGet(durableSize); numberOfMessages.addAndGet(durableSize + nonDurableSize); } - public int getNumberOfMessages() - { + public int getNumberOfMessages() { return numberOfMessages.get(); } // EncodingSupport implementation - public synchronized void decode(final ActiveMQBuffer buffer) - { + public synchronized void decode(final ActiveMQBuffer buffer) { transactionID = buffer.readLong(); numberOfMessages.set(buffer.readInt()); numberOfPersistentMessages.set(numberOfMessages.get()); committed = true; } - public synchronized void encode(final ActiveMQBuffer buffer) - { + public synchronized void encode(final ActiveMQBuffer buffer) { buffer.writeLong(transactionID); buffer.writeInt(numberOfPersistentMessages.get()); } - public synchronized int getEncodeSize() - { + public synchronized int getEncodeSize() { return DataConstants.SIZE_LONG + DataConstants.SIZE_INT; } - public synchronized void commit() - { - if (lateDeliveries != null) - { + public synchronized void commit() { + if (lateDeliveries != null) { // This is to make sure deliveries that were touched before the commit arrived will be delivered - for (LateDelivery pos : lateDeliveries) - { + for (LateDelivery pos : lateDeliveries) { pos.getSubscription().redeliver(pos.getIterator(), pos.getPagePosition()); } lateDeliveries.clear(); @@ -153,8 +135,9 @@ public final class PageTransactionInfoImpl implements PageTransactionInfo lateDeliveries = null; } - public void store(final StorageManager storageManager, PagingManager pagingManager, final Transaction tx) throws Exception - { + public void store(final StorageManager storageManager, + PagingManager pagingManager, + final Transaction tx) throws Exception { storageManager.storePageTransaction(tx.getID(), this); } @@ -163,13 +146,16 @@ public final class PageTransactionInfoImpl implements PageTransactionInfo * (non-Javadoc) * @see org.apache.activemq.artemis.core.paging.PageTransactionInfo#storeUpdate(org.apache.activemq.artemis.core.persistence.StorageManager, org.apache.activemq.artemis.core.transaction.Transaction, int) */ - public void storeUpdate(final StorageManager storageManager, final PagingManager pagingManager, final Transaction tx) throws Exception - { + public void storeUpdate(final StorageManager storageManager, + final PagingManager pagingManager, + final Transaction tx) throws Exception { internalUpdatePageManager(storageManager, pagingManager, tx, 1); } - public void reloadUpdate(final StorageManager storageManager, final PagingManager pagingManager, final Transaction tx, final int increment) throws Exception - { + public void reloadUpdate(final StorageManager storageManager, + final PagingManager pagingManager, + final Transaction tx, + final int increment) throws Exception { UpdatePageTXOperation updt = internalUpdatePageManager(storageManager, pagingManager, tx, increment); updt.setStored(); } @@ -182,12 +168,10 @@ public final class PageTransactionInfoImpl implements PageTransactionInfo protected UpdatePageTXOperation internalUpdatePageManager(final StorageManager storageManager, final PagingManager pagingManager, final Transaction tx, - final int increment) - { + final int increment) { UpdatePageTXOperation pgtxUpdate = (UpdatePageTXOperation) tx.getProperty(TransactionPropertyIndexes.PAGE_TRANSACTION_UPDATE); - if (pgtxUpdate == null) - { + if (pgtxUpdate == null) { pgtxUpdate = new UpdatePageTXOperation(storageManager, pagingManager); tx.putProperty(TransactionPropertyIndexes.PAGE_TRANSACTION_UPDATE, pgtxUpdate); tx.addOperation(pgtxUpdate); @@ -200,30 +184,24 @@ public final class PageTransactionInfoImpl implements PageTransactionInfo return pgtxUpdate; } - public boolean isCommit() - { + public boolean isCommit() { return committed; } - public void setCommitted(final boolean committed) - { + public void setCommitted(final boolean committed) { this.committed = committed; } - public boolean isRollback() - { + public boolean isRollback() { return rolledback; } - public synchronized void rollback() - { + public synchronized void rollback() { rolledback = true; committed = false; - if (lateDeliveries != null) - { - for (LateDelivery pos : lateDeliveries) - { + if (lateDeliveries != null) { + for (LateDelivery pos : lateDeliveries) { pos.getSubscription().lateDeliveryRollback(pos.getPagePosition()); } lateDeliveries = null; @@ -231,8 +209,7 @@ public final class PageTransactionInfoImpl implements PageTransactionInfo } @Override - public String toString() - { + public String toString() { return "PageTransactionInfoImpl(transactionID=" + transactionID + ",id=" + recordID + @@ -242,28 +219,24 @@ public final class PageTransactionInfoImpl implements PageTransactionInfo } @Override - public synchronized boolean deliverAfterCommit(PageIterator iterator, PageSubscription cursor, PagePosition cursorPos) - { - if (committed && useRedelivery) - { + public synchronized boolean deliverAfterCommit(PageIterator iterator, + PageSubscription cursor, + PagePosition cursorPos) { + if (committed && useRedelivery) { cursor.addPendingDelivery(cursorPos); cursor.redeliver(iterator, cursorPos); return true; } - else if (committed) - { + else if (committed) { return false; } - else if (rolledback) - { + else if (rolledback) { cursor.positionIgnored(cursorPos); return true; } - else - { + else { useRedelivery = true; - if (lateDeliveries == null) - { + if (lateDeliveries == null) { lateDeliveries = new LinkedList<>(); } cursor.addPendingDelivery(cursorPos); @@ -280,44 +253,40 @@ public final class PageTransactionInfoImpl implements PageTransactionInfo // Inner classes ------------------------------------------------- - /** a Message shouldn't be delivered until it's committed - * For that reason the page-reference will be written right away - * But in certain cases we can only deliver after the commit - * For that reason we will perform a late delivery - * through the method redeliver. + /** + * a Message shouldn't be delivered until it's committed + * For that reason the page-reference will be written right away + * But in certain cases we can only deliver after the commit + * For that reason we will perform a late delivery + * through the method redeliver. */ - private static class LateDelivery - { + private static class LateDelivery { + final PageSubscription subscription; final PagePosition pagePosition; final PageIterator iterator; - public LateDelivery(PageSubscription subscription, PagePosition pagePosition, PageIterator iterator) - { + public LateDelivery(PageSubscription subscription, PagePosition pagePosition, PageIterator iterator) { this.subscription = subscription; this.pagePosition = pagePosition; this.iterator = iterator; } - public PageSubscription getSubscription() - { + public PageSubscription getSubscription() { return subscription; } - public PagePosition getPagePosition() - { + public PagePosition getPagePosition() { return pagePosition; } - public PageIterator getIterator() - { + public PageIterator getIterator() { return iterator; } } + private static class UpdatePageTXOperation extends TransactionOperationAbstract { - private static class UpdatePageTXOperation extends TransactionOperationAbstract - { private final HashMap countsToUpdate = new HashMap(); private boolean stored = false; @@ -326,23 +295,19 @@ public final class PageTransactionInfoImpl implements PageTransactionInfo private final PagingManager pagingManager; - public UpdatePageTXOperation(final StorageManager storageManager, final PagingManager pagingManager) - { + public UpdatePageTXOperation(final StorageManager storageManager, final PagingManager pagingManager) { this.storageManager = storageManager; this.pagingManager = pagingManager; } - public void setStored() - { + public void setStored() { stored = true; } - public void addUpdate(final PageTransactionInfo info, final int increment) - { + public void addUpdate(final PageTransactionInfo info, final int increment) { AtomicInteger counter = countsToUpdate.get(info); - if (counter == null) - { + if (counter == null) { counter = new AtomicInteger(0); countsToUpdate.put(info, counter); } @@ -351,38 +316,30 @@ public final class PageTransactionInfoImpl implements PageTransactionInfo } @Override - public void beforePrepare(Transaction tx) throws Exception - { + public void beforePrepare(Transaction tx) throws Exception { storeUpdates(tx); } @Override - public void beforeCommit(Transaction tx) throws Exception - { + public void beforeCommit(Transaction tx) throws Exception { storeUpdates(tx); } @Override - public void afterCommit(Transaction tx) - { - for (Map.Entry entry : countsToUpdate.entrySet()) - { + public void afterCommit(Transaction tx) { + for (Map.Entry entry : countsToUpdate.entrySet()) { entry.getKey().onUpdate(entry.getValue().intValue(), storageManager, pagingManager); } } - private void storeUpdates(Transaction tx) throws Exception - { - if (!stored) - { + private void storeUpdates(Transaction tx) throws Exception { + if (!stored) { stored = true; - for (Map.Entry entry : countsToUpdate.entrySet()) - { + for (Map.Entry entry : countsToUpdate.entrySet()) { storageManager.updatePageTransaction(tx.getID(), entry.getKey(), entry.getValue().get()); } } } - } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PagedMessageImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PagedMessageImpl.java index 228e09f374..9b5b0fde66 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PagedMessageImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PagedMessageImpl.java @@ -30,8 +30,8 @@ import org.apache.activemq.artemis.utils.DataConstants; /** * This class represents a paged message */ -public class PagedMessageImpl implements PagedMessage -{ +public class PagedMessageImpl implements PagedMessage { + /** * Large messages will need to be instantiated lazily during getMessage when the StorageManager * is available @@ -44,31 +44,25 @@ public class PagedMessageImpl implements PagedMessage private long transactionID = 0; - public PagedMessageImpl(final ServerMessage message, final long[] queueIDs, final long transactionID) - { + public PagedMessageImpl(final ServerMessage message, final long[] queueIDs, final long transactionID) { this(message, queueIDs); this.transactionID = transactionID; } - public PagedMessageImpl(final ServerMessage message, final long[] queueIDs) - { + public PagedMessageImpl(final ServerMessage message, final long[] queueIDs) { this.queueIDs = queueIDs; this.message = message; } - public PagedMessageImpl() - { + public PagedMessageImpl() { } - public ServerMessage getMessage() - { + public ServerMessage getMessage() { return message; } - public void initMessage(StorageManager storage) - { - if (largeMessageLazyData != null) - { + public void initMessage(StorageManager storage) { + if (largeMessageLazyData != null) { LargeServerMessage lgMessage = storage.createLargeMessage(); ActiveMQBuffer buffer = ActiveMQBuffers.dynamicBuffer(largeMessageLazyData); lgMessage.decodeHeadersAndProperties(buffer); @@ -79,34 +73,29 @@ public class PagedMessageImpl implements PagedMessage } } - public long getTransactionID() - { + public long getTransactionID() { return transactionID; } - public long[] getQueueIDs() - { + public long[] getQueueIDs() { return queueIDs; } // EncodingSupport implementation -------------------------------- - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { transactionID = buffer.readLong(); boolean isLargeMessage = buffer.readBoolean(); - if (isLargeMessage) - { + if (isLargeMessage) { int largeMessageHeaderSize = buffer.readInt(); largeMessageLazyData = new byte[largeMessageHeaderSize]; buffer.readBytes(largeMessageLazyData); } - else - { + else { buffer.readInt(); // This value is only used on LargeMessages for now message = new ServerMessageImpl(-1, 50); @@ -118,14 +107,12 @@ public class PagedMessageImpl implements PagedMessage queueIDs = new long[queueIDsSize]; - for (int i = 0; i < queueIDsSize; i++) - { + for (int i = 0; i < queueIDsSize; i++) { queueIDs[i] = buffer.readLong(); } } - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { buffer.writeLong(transactionID); buffer.writeBoolean(message instanceof LargeServerMessage); @@ -136,21 +123,18 @@ public class PagedMessageImpl implements PagedMessage buffer.writeInt(queueIDs.length); - for (long queueID : queueIDs) - { + for (long queueID : queueIDs) { buffer.writeLong(queueID); } } - public int getEncodeSize() - { + public int getEncodeSize() { return DataConstants.SIZE_LONG + DataConstants.SIZE_BYTE + DataConstants.SIZE_INT + message.getEncodeSize() + DataConstants.SIZE_INT + queueIDs.length * DataConstants.SIZE_LONG; } @Override - public String toString() - { + public String toString() { return "PagedMessageImpl [queueIDs=" + Arrays.toString(queueIDs) + ", transactionID=" + transactionID + diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PagingManagerImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PagingManagerImpl.java index 87f151b666..15f01f696b 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PagingManagerImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PagingManagerImpl.java @@ -32,8 +32,8 @@ import org.apache.activemq.artemis.core.server.ActiveMQServerLogger; import org.apache.activemq.artemis.core.settings.HierarchicalRepository; import org.apache.activemq.artemis.core.settings.impl.AddressSettings; -public final class PagingManagerImpl implements PagingManager -{ +public final class PagingManagerImpl implements PagingManager { + private volatile boolean started = false; /** @@ -52,8 +52,7 @@ public final class PagingManagerImpl implements PagingManager private volatile boolean cleanupEnabled = true; - private final ConcurrentMap transactions = - new ConcurrentHashMap(); + private final ConcurrentMap transactions = new ConcurrentHashMap(); // Static // -------------------------------------------------------------------------------------------------------------------------- @@ -64,92 +63,73 @@ public final class PagingManagerImpl implements PagingManager // -------------------------------------------------------------------------------------------------------------------- public PagingManagerImpl(final PagingStoreFactory pagingSPI, - final HierarchicalRepository addressSettingsRepository) - { + final HierarchicalRepository addressSettingsRepository) { pagingStoreFactory = pagingSPI; this.addressSettingsRepository = addressSettingsRepository; addressSettingsRepository.registerListener(this); } @Override - public void onChange() - { + public void onChange() { reaplySettings(); } - private void reaplySettings() - { - for (PagingStore store : stores.values()) - { + private void reaplySettings() { + for (PagingStore store : stores.values()) { AddressSettings settings = this.addressSettingsRepository.getMatch(store.getAddress().toString()); store.applySetting(settings); } } - public void disableCleanup() - { - if (!cleanupEnabled) - { + public void disableCleanup() { + if (!cleanupEnabled) { return; } lock(); - try - { + try { cleanupEnabled = false; - for (PagingStore store : stores.values()) - { + for (PagingStore store : stores.values()) { store.disableCleanup(); } } - finally - { + finally { unlock(); } } - public void resumeCleanup() - { - if (cleanupEnabled) - { + public void resumeCleanup() { + if (cleanupEnabled) { return; } lock(); - try - { + try { cleanupEnabled = true; - for (PagingStore store : stores.values()) - { + for (PagingStore store : stores.values()) { store.enableCleanup(); } } - finally - { + finally { unlock(); } } - public SimpleString[] getStoreNames() - { + public SimpleString[] getStoreNames() { Set names = stores.keySet(); return names.toArray(new SimpleString[names.size()]); } - public void reloadStores() throws Exception - { + public void reloadStores() throws Exception { lock(); - try - { + try { List reloadedStores = pagingStoreFactory.reloadStores(addressSettingsRepository); - for (PagingStore store : reloadedStores) - { + for (PagingStore store : reloadedStores) { // when reloading, we need to close the previously loaded version of this // store PagingStore oldStore = stores.remove(store.getStoreName()); - if (oldStore != null) - { + if (oldStore != null) { oldStore.stop(); oldStore = null; } @@ -157,26 +137,21 @@ public final class PagingManagerImpl implements PagingManager stores.put(store.getStoreName(), store); } } - finally - { + finally { unlock(); } } - public void deletePageStore(final SimpleString storeName) throws Exception - { + public void deletePageStore(final SimpleString storeName) throws Exception { syncLock.readLock().lock(); - try - { + try { PagingStore store = stores.remove(storeName); - if (store != null) - { + if (store != null) { store.stop(); } } - finally - { + finally { syncLock.readLock().unlock(); } } @@ -184,65 +159,51 @@ public final class PagingManagerImpl implements PagingManager /** * stores is a ConcurrentHashMap, so we don't need to synchronize this method */ - public PagingStore getPageStore(final SimpleString storeName) throws Exception - { + public PagingStore getPageStore(final SimpleString storeName) throws Exception { PagingStore store = stores.get(storeName); - if (store != null) - { + if (store != null) { return store; } return newStore(storeName); } - public void addTransaction(final PageTransactionInfo pageTransaction) - { - if (isTrace) - { + public void addTransaction(final PageTransactionInfo pageTransaction) { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Adding pageTransaction " + pageTransaction.getTransactionID()); } transactions.put(pageTransaction.getTransactionID(), pageTransaction); } - public void removeTransaction(final long id) - { - if (isTrace) - { + public void removeTransaction(final long id) { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Removing pageTransaction " + id); } transactions.remove(id); } - public PageTransactionInfo getTransaction(final long id) - { - if (isTrace) - { + public PageTransactionInfo getTransaction(final long id) { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("looking up pageTX = " + id); } return transactions.get(id); } @Override - public Map getTransactions() - { + public Map getTransactions() { return transactions; } - @Override - public boolean isStarted() - { + public boolean isStarted() { return started; } @Override - public void start() throws Exception - { + public void start() throws Exception { lock(); - try - { - if (started) - { + try { + if (started) { return; } @@ -252,77 +213,61 @@ public final class PagingManagerImpl implements PagingManager started = true; } - finally - { + finally { unlock(); } } - public synchronized void stop() throws Exception - { - if (!started) - { + public synchronized void stop() throws Exception { + if (!started) { return; } started = false; lock(); - try - { + try { - for (PagingStore store : stores.values()) - { + for (PagingStore store : stores.values()) { store.stop(); } pagingStoreFactory.stop(); } - finally - { + finally { unlock(); } } - public void processReload() throws Exception - { - for (PagingStore store : stores.values()) - { + public void processReload() throws Exception { + for (PagingStore store : stores.values()) { store.processReload(); } } - - private PagingStore newStore(final SimpleString address) throws Exception - { + private PagingStore newStore(final SimpleString address) throws Exception { syncLock.readLock().lock(); - try - { + try { PagingStore store = stores.get(address); - if (store == null) - { + if (store == null) { store = pagingStoreFactory.newStore(address, addressSettingsRepository.getMatch(address.toString())); store.start(); - if (!cleanupEnabled) - { + if (!cleanupEnabled) { store.disableCleanup(); } stores.put(address, store); } return store; } - finally - { + finally { syncLock.readLock().unlock(); } } - public void unlock() - { + public void unlock() { syncLock.writeLock().unlock(); } - public void lock() - { + public void lock() { syncLock.writeLock().lock(); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PagingStoreFactoryNIO.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PagingStoreFactoryNIO.java index 63681f2f61..ce42860957 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PagingStoreFactoryNIO.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PagingStoreFactoryNIO.java @@ -43,11 +43,9 @@ import org.apache.activemq.artemis.utils.ExecutorFactory; import org.apache.activemq.artemis.utils.UUIDGenerator; /** - * * Integration point between Paging and NIO */ -public class PagingStoreFactoryNIO implements PagingStoreFactory -{ +public class PagingStoreFactoryNIO implements PagingStoreFactory { // Constants ----------------------------------------------------- @@ -71,13 +69,13 @@ public class PagingStoreFactoryNIO implements PagingStoreFactory private final IOCriticalErrorListener critialErrorListener; - public PagingStoreFactoryNIO(final StorageManager storageManager, final File directory, + public PagingStoreFactoryNIO(final StorageManager storageManager, + final File directory, final long syncTimeout, final ScheduledExecutorService scheduledExecutor, final ExecutorFactory executorFactory, final boolean syncNonTransactional, - final IOCriticalErrorListener critialErrorListener) - { + final IOCriticalErrorListener critialErrorListener) { this.storageManager = storageManager; this.directory = directory; this.executorFactory = executorFactory; @@ -89,28 +87,15 @@ public class PagingStoreFactoryNIO implements PagingStoreFactory // Public -------------------------------------------------------- - public void stop() - { + public void stop() { } - public synchronized PagingStore newStore(final SimpleString address, final AddressSettings settings) - { + public synchronized PagingStore newStore(final SimpleString address, final AddressSettings settings) { - return new PagingStoreImpl(address, - scheduledExecutor, - syncTimeout, - pagingManager, - storageManager, - null, - this, - address, - settings, - executorFactory.getExecutor(), - syncNonTransactional); + return new PagingStoreImpl(address, scheduledExecutor, syncTimeout, pagingManager, storageManager, null, this, address, settings, executorFactory.getExecutor(), syncNonTransactional); } - public synchronized SequentialFileFactory newFileFactory(final SimpleString address) throws Exception - { + public synchronized SequentialFileFactory newFileFactory(final SimpleString address) throws Exception { String guid = UUIDGenerator.getInstance().generateStringUUID(); @@ -118,52 +103,43 @@ public class PagingStoreFactoryNIO implements PagingStoreFactory factory.createDirs(); - File fileWithID = new File(directory, - guid + - File.separatorChar + - PagingStoreFactoryNIO.ADDRESS_FILE); + File fileWithID = new File(directory, guid + + File.separatorChar + + PagingStoreFactoryNIO.ADDRESS_FILE); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileWithID))); - try - { + try { writer.write(address.toString()); writer.newLine(); } - finally - { + finally { writer.close(); } return factory; } - public void setPagingManager(final PagingManager pagingManager) - { + public void setPagingManager(final PagingManager pagingManager) { this.pagingManager = pagingManager; } - public List reloadStores(final HierarchicalRepository addressSettingsRepository) throws Exception - { + public List reloadStores(final HierarchicalRepository addressSettingsRepository) throws Exception { File[] files = directory.listFiles(); - if (files == null) - { + if (files == null) { return Collections.emptyList(); } - else - { + else { ArrayList storesReturn = new ArrayList(files.length); - for (File file : files) - { + for (File file : files) { final String guid = file.getName(); final File addressFile = new File(file, PagingStoreFactoryNIO.ADDRESS_FILE); - if (!addressFile.exists()) - { + if (!addressFile.exists()) { ActiveMQServerLogger.LOGGER.pageStoreFactoryNoIdFile(file.toString(), PagingStoreFactoryNIO.ADDRESS_FILE); continue; } @@ -172,12 +148,10 @@ public class PagingStoreFactoryNIO implements PagingStoreFactory String addressString; - try - { + try { addressString = reader.readLine(); } - finally - { + finally { reader.close(); } @@ -187,17 +161,7 @@ public class PagingStoreFactoryNIO implements PagingStoreFactory AddressSettings settings = addressSettingsRepository.getMatch(address.toString()); - PagingStore store = new PagingStoreImpl(address, - scheduledExecutor, - syncTimeout, - pagingManager, - storageManager, - factory, - this, - address, - settings, - executorFactory.getExecutor(), - syncNonTransactional); + PagingStore store = new PagingStoreImpl(address, scheduledExecutor, syncTimeout, pagingManager, storageManager, factory, this, address, settings, executorFactory.getExecutor(), syncNonTransactional); storesReturn.add(store); } @@ -206,8 +170,7 @@ public class PagingStoreFactoryNIO implements PagingStoreFactory } } - private SequentialFileFactory newFileFactory(final String directoryName) - { + private SequentialFileFactory newFileFactory(final String directoryName) { return new NIOSequentialFileFactory(new File(directory, directoryName), false, critialErrorListener, 1); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PagingStoreImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PagingStoreImpl.java index 6b67f3e863..582466411d 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PagingStoreImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PagingStoreImpl.java @@ -66,8 +66,8 @@ import org.apache.activemq.artemis.utils.FutureLatch; /** * @see PagingStore */ -public class PagingStoreImpl implements PagingStore -{ +public class PagingStoreImpl implements PagingStore { + private final SimpleString address; private final StorageManager storageManager; @@ -133,10 +133,8 @@ public class PagingStoreImpl implements PagingStore final SimpleString storeName, final AddressSettings addressSettings, final Executor executor, - final boolean syncNonTransactional) - { - if (pagingManager == null) - { + final boolean syncNonTransactional) { + if (pagingManager == null) { throw new IllegalStateException("Paging Manager can't be null"); } @@ -148,14 +146,13 @@ public class PagingStoreImpl implements PagingStore applySetting(addressSettings); - if (addressFullMessagePolicy == AddressFullMessagePolicy.PAGE && maxSize != -1 && pageSize >= maxSize) - { + if (addressFullMessagePolicy == AddressFullMessagePolicy.PAGE && maxSize != -1 && pageSize >= maxSize) { throw new IllegalStateException("pageSize for address " + address + - " >= maxSize. Normally pageSize should" + - " be significantly smaller than maxSize, ms: " + - maxSize + - " ps " + - pageSize); + " >= maxSize. Normally pageSize should" + + " be significantly smaller than maxSize, ms: " + + maxSize + + " ps " + + pageSize); } this.executor = executor; @@ -168,246 +165,196 @@ public class PagingStoreImpl implements PagingStore this.syncNonTransactional = syncNonTransactional; - if (scheduledExecutor != null && syncTimeout > 0) - { + if (scheduledExecutor != null && syncTimeout > 0) { this.syncTimer = new PageSyncTimer(this, scheduledExecutor, syncTimeout); } - else - { + else { this.syncTimer = null; } - this.cursorProvider = new PageCursorProviderImpl(this, - this.storageManager, - executor, - addressSettings.getPageCacheMaxSize()); + this.cursorProvider = new PageCursorProviderImpl(this, this.storageManager, executor, addressSettings.getPageCacheMaxSize()); } /** * @param addressSettings */ - public void applySetting(final AddressSettings addressSettings) - { + public void applySetting(final AddressSettings addressSettings) { maxSize = addressSettings.getMaxSizeBytes(); pageSize = addressSettings.getPageSizeBytes(); addressFullMessagePolicy = addressSettings.getAddressFullMessagePolicy(); - if (cursorProvider != null) - { + if (cursorProvider != null) { cursorProvider.setCacheMaxSize(addressSettings.getPageCacheMaxSize()); } } @Override - public String toString() - { + public String toString() { return "PagingStoreImpl(" + this.address + ")"; } @Override - public boolean lock(long timeout) - { - if (timeout == -1) - { + public boolean lock(long timeout) { + if (timeout == -1) { lock.writeLock().lock(); return true; } - try - { + try { return lock.writeLock().tryLock(timeout, TimeUnit.MILLISECONDS); } - catch (InterruptedException e) - { + catch (InterruptedException e) { return false; } } - public void unlock() - { + public void unlock() { lock.writeLock().unlock(); } - public PageCursorProvider getCursorProvider() - { + public PageCursorProvider getCursorProvider() { return cursorProvider; } - public long getFirstPage() - { + public long getFirstPage() { return firstPageId; } - public SimpleString getAddress() - { + public SimpleString getAddress() { return address; } - public long getAddressSize() - { + public long getAddressSize() { return sizeInBytes.get(); } - public long getMaxSize() - { + public long getMaxSize() { return maxSize; } - public AddressFullMessagePolicy getAddressFullMessagePolicy() - { + public AddressFullMessagePolicy getAddressFullMessagePolicy() { return addressFullMessagePolicy; } - public long getPageSizeBytes() - { + public long getPageSizeBytes() { return pageSize; } - public File getFolder() - { + public File getFolder() { SequentialFileFactory factoryUsed = this.fileFactory; - if (factoryUsed != null) - { + if (factoryUsed != null) { return factoryUsed.getDirectory(); } - else - { + else { return null; } } - public boolean isPaging() - { + public boolean isPaging() { lock.readLock().lock(); - try - { - if (addressFullMessagePolicy == AddressFullMessagePolicy.BLOCK) - { + try { + if (addressFullMessagePolicy == AddressFullMessagePolicy.BLOCK) { return false; } - if (addressFullMessagePolicy == AddressFullMessagePolicy.FAIL) - { + if (addressFullMessagePolicy == AddressFullMessagePolicy.FAIL) { return isFull(); } - if (addressFullMessagePolicy == AddressFullMessagePolicy.DROP) - { + if (addressFullMessagePolicy == AddressFullMessagePolicy.DROP) { return isFull(); } return paging; } - finally - { + finally { lock.readLock().unlock(); } } - public int getNumberOfPages() - { + public int getNumberOfPages() { return numberOfPages; } - public int getCurrentWritingPage() - { + public int getCurrentWritingPage() { return currentPageId; } - public SimpleString getStoreName() - { + public SimpleString getStoreName() { return storeName; } - public void sync() throws Exception - { - if (syncTimer != null) - { + public void sync() throws Exception { + if (syncTimer != null) { syncTimer.addSync(storageManager.getContext()); } - else - { + else { ioSync(); } } - public void ioSync() throws Exception - { + public void ioSync() throws Exception { lock.readLock().lock(); - try - { - if (currentPage != null) - { + try { + if (currentPage != null) { currentPage.sync(); } } - finally - { + finally { lock.readLock().unlock(); } } - public void processReload() throws Exception - { + public void processReload() throws Exception { cursorProvider.processReload(); } - public PagingManager getPagingManager() - { + public PagingManager getPagingManager() { return pagingManager; } @Override - public boolean isStarted() - { + public boolean isStarted() { return running; } @Override - public synchronized void stop() throws Exception - { - if (running) - { + public synchronized void stop() throws Exception { + if (running) { cursorProvider.stop(); running = false; flushExecutors(); - if (currentPage != null) - { + if (currentPage != null) { currentPage.close(); currentPage = null; } } } - public void flushExecutors() - { + public void flushExecutors() { cursorProvider.flushExecutors(); FutureLatch future = new FutureLatch(); executor.execute(future); - if (!future.await(60000)) - { + if (!future.await(60000)) { ActiveMQServerLogger.LOGGER.pageStoreTimeout(address); } } @Override - public void start() throws Exception - { + public void start() throws Exception { lock.writeLock().lock(); - try - { + try { - if (running) - { + if (running) { // don't throw an exception. // You could have two threads adding PagingStore to a // ConcurrentHashMap, @@ -415,18 +362,15 @@ public class PagingStoreImpl implements PagingStore // need to be ignored return; } - else - { + else { running = true; firstPageId = Integer.MAX_VALUE; // There are no files yet on this Storage. We will just return it empty - if (fileFactory != null) - { + if (fileFactory != null) { currentPageId = 0; - if (currentPage != null) - { + if (currentPage != null) { currentPage.close(); } currentPage = null; @@ -435,23 +379,19 @@ public class PagingStoreImpl implements PagingStore numberOfPages = files.size(); - for (String fileName : files) - { + for (String fileName : files) { final int fileId = PagingStoreImpl.getPageIdFromFileName(fileName); - if (fileId > currentPageId) - { + if (fileId > currentPageId) { currentPageId = fileId; } - if (fileId < firstPageId) - { + if (fileId < firstPageId) { firstPageId = fileId; } } - if (currentPageId != 0) - { + if (currentPageId != 0) { currentPage = createPage(currentPageId); currentPage.open(); @@ -459,11 +399,9 @@ public class PagingStoreImpl implements PagingStore LivePageCache pageCache = new LivePageCacheImpl(currentPage); - for (PagedMessage msg : messages) - { + for (PagedMessage msg : messages) { pageCache.addLiveMessage(msg); - if (msg.getMessage().isLargeMessage()) - { + if (msg.getMessage().isLargeMessage()) { // We have to do this since addLIveMessage will increment an extra one ((LargeServerMessage) msg.getMessage()).decrementDelayDeletionCount(); } @@ -477,57 +415,47 @@ public class PagingStoreImpl implements PagingStore } // We will not mark it for paging if there's only a single empty file - if (currentPage != null && !(numberOfPages == 1 && currentPage.getSize() == 0)) - { + if (currentPage != null && !(numberOfPages == 1 && currentPage.getSize() == 0)) { startPaging(); } } } } - finally - { + finally { lock.writeLock().unlock(); } } - public void stopPaging() - { + public void stopPaging() { lock.writeLock().lock(); - try - { + try { paging = false; this.cursorProvider.onPageModeCleared(); } - finally - { + finally { lock.writeLock().unlock(); } } - public boolean startPaging() - { - if (!running) - { + public boolean startPaging() { + if (!running) { return false; } lock.readLock().lock(); - try - { + try { // I'm not calling isPaging() here because // isPaging will perform extra steps. // at this context it doesn't really matter what policy we are using // since this method is only called when paging. // Besides that isPaging() will perform lock.readLock() again which is not needed here // for that reason the attribute is used directly here. - if (paging) - { + if (paging) { return false; } } - finally - { + finally { lock.readLock().unlock(); } @@ -535,22 +463,17 @@ public class PagingStoreImpl implements PagingStore // (writeLock) this time lock.writeLock().lock(); - try - { + try { // Same notes from previous if (paging) on this method will apply here - if (paging) - { + if (paging) { return false; } - if (currentPage == null) - { - try - { + if (currentPage == null) { + try { openNewPage(); } - catch (Exception e) - { + catch (Exception e) { // If not possible to starting page due to an IO error, we will just consider it non paging. // This shouldn't happen anyway ActiveMQServerLogger.LOGGER.pageStoreStartIOError(e); @@ -562,30 +485,25 @@ public class PagingStoreImpl implements PagingStore return true; } - finally - { + finally { lock.writeLock().unlock(); } } - public Page getCurrentPage() - { + public Page getCurrentPage() { return currentPage; } - public boolean checkPageFileExists(final int pageNumber) - { + public boolean checkPageFileExists(final int pageNumber) { String fileName = createFileName(pageNumber); SequentialFile file = fileFactory.createSequentialFile(fileName); return file.exists(); } - public Page createPage(final int pageNumber) throws Exception - { + public Page createPage(final int pageNumber) throws Exception { String fileName = createFileName(pageNumber); - if (fileFactory == null) - { + if (fileFactory == null) { fileFactory = storeFactory.newFileFactory(getStoreName()); } @@ -603,8 +521,7 @@ public class PagingStoreImpl implements PagingStore return page; } - public void forceAnotherPage() throws Exception - { + public void forceAnotherPage() throws Exception { openNewPage(); } @@ -620,34 +537,27 @@ public class PagingStoreImpl implements PagingStore * externally is used only on tests, and that's why this method is part of the Testable Interface *

    */ - public Page depage() throws Exception - { + public Page depage() throws Exception { lock.writeLock().lock(); // Make sure no checks are done on currentPage while we are depaging - try - { - if (!running) - { + try { + if (!running) { return null; } - if (numberOfPages == 0) - { + if (numberOfPages == 0) { return null; } - else - { + else { numberOfPages--; final Page returnPage; // We are out of old pages, all that is left now is the current page. // On that case we need to replace it by a new empty page, and return the current page immediately - if (currentPageId == firstPageId) - { + if (currentPageId == firstPageId) { firstPageId = Integer.MAX_VALUE; - if (currentPage == null) - { + if (currentPage == null) { // sanity check... it shouldn't happen! throw new IllegalStateException("CurrentPage is null"); } @@ -657,8 +567,7 @@ public class PagingStoreImpl implements PagingStore currentPage = null; // The current page is empty... which means we reached the end of the pages - if (returnPage.getNumberOfMessages() == 0) - { + if (returnPage.getNumberOfMessages() == 0) { stopPaging(); returnPage.open(); returnPage.delete(null); @@ -667,24 +576,21 @@ public class PagingStoreImpl implements PagingStore // and this will make ActiveMQ Artemis start using the journal again return null; } - else - { + else { // We need to create a new page, as we can't lock the address until we finish depaging. openNewPage(); } return returnPage; } - else - { + else { returnPage = createPage(firstPageId++); } return returnPage; } } - finally - { + finally { lock.writeLock().unlock(); } @@ -692,14 +598,12 @@ public class PagingStoreImpl implements PagingStore private final Queue onMemoryFreedRunnables = new ConcurrentLinkedQueue(); - private class MemoryFreedRunnablesExecutor implements Runnable - { - public void run() - { + private class MemoryFreedRunnablesExecutor implements Runnable { + + public void run() { Runnable runnable; - while ((runnable = onMemoryFreedRunnables.poll()) != null) - { + while ((runnable = onMemoryFreedRunnables.poll()) != null) { runnable.run(); } } @@ -707,21 +611,18 @@ public class PagingStoreImpl implements PagingStore private final Runnable memoryFreedRunnablesExecutor = new MemoryFreedRunnablesExecutor(); - private static final class OurRunnable implements Runnable - { + private static final class OurRunnable implements Runnable { + private boolean ran; private final Runnable runnable; - private OurRunnable(final Runnable runnable) - { + private OurRunnable(final Runnable runnable) { this.runnable = runnable; } - public synchronized void run() - { - if (!ran) - { + public synchronized void run() { + if (!ran) { runnable.run(); ran = true; @@ -729,12 +630,9 @@ public class PagingStoreImpl implements PagingStore } } - public boolean checkMemory(final Runnable runWhenAvailable) - { - if (addressFullMessagePolicy == AddressFullMessagePolicy.BLOCK && maxSize != -1) - { - if (sizeInBytes.get() > maxSize) - { + public boolean checkMemory(final Runnable runWhenAvailable) { + if (addressFullMessagePolicy == AddressFullMessagePolicy.BLOCK && maxSize != -1) { + if (sizeInBytes.get() > maxSize) { OurRunnable ourRunnable = new OurRunnable(runWhenAvailable); onMemoryFreedRunnables.add(ourRunnable); @@ -743,13 +641,11 @@ public class PagingStoreImpl implements PagingStore // has been added, but the check to execute was done before the element was added // NOTE! We do not fix this race by locking the whole thing, doing this check provides // MUCH better performance in a highly concurrent environment - if (sizeInBytes.get() <= maxSize) - { + if (sizeInBytes.get() <= maxSize) { // run it now ourRunnable.run(); } - else if (!blocking.get()) - { + else if (!blocking.get()) { ActiveMQServerLogger.LOGGER.blockingMessageProduction(address, sizeInBytes.get(), maxSize); blocking.set(true); } @@ -757,10 +653,8 @@ public class PagingStoreImpl implements PagingStore return true; } } - else if (addressFullMessagePolicy == AddressFullMessagePolicy.FAIL && maxSize != -1) - { - if (sizeInBytes.get() > maxSize) - { + else if (addressFullMessagePolicy == AddressFullMessagePolicy.FAIL && maxSize != -1) { + if (sizeInBytes.get() > maxSize) { return false; } } @@ -770,21 +664,15 @@ public class PagingStoreImpl implements PagingStore return true; } - public void addSize(final int size) - { - if (addressFullMessagePolicy == AddressFullMessagePolicy.BLOCK) - { - if (maxSize != -1) - { + public void addSize(final int size) { + if (addressFullMessagePolicy == AddressFullMessagePolicy.BLOCK) { + if (maxSize != -1) { long newSize = sizeInBytes.addAndGet(size); - if (newSize <= maxSize) - { - if (!onMemoryFreedRunnables.isEmpty()) - { + if (newSize <= maxSize) { + if (!onMemoryFreedRunnables.isEmpty()) { executor.execute(memoryFreedRunnablesExecutor); - if (blocking.get()) - { + if (blocking.get()) { ActiveMQServerLogger.LOGGER.unblockingMessageProduction(address, sizeInBytes.get(), maxSize); blocking.set(false); } @@ -794,16 +682,12 @@ public class PagingStoreImpl implements PagingStore return; } - else if (addressFullMessagePolicy == AddressFullMessagePolicy.PAGE) - { + else if (addressFullMessagePolicy == AddressFullMessagePolicy.PAGE) { final long addressSize = sizeInBytes.addAndGet(size); - if (size > 0) - { - if (maxSize > 0 && addressSize > maxSize) - { - if (startPaging()) - { + if (size > 0) { + if (maxSize > 0 && addressSize > maxSize) { + if (startPaging()) { ActiveMQServerLogger.LOGGER.pageStoreStart(storeName, addressSize, maxSize); } } @@ -811,90 +695,74 @@ public class PagingStoreImpl implements PagingStore return; } - else if (addressFullMessagePolicy == AddressFullMessagePolicy.DROP || addressFullMessagePolicy == AddressFullMessagePolicy.FAIL) - { + else if (addressFullMessagePolicy == AddressFullMessagePolicy.DROP || addressFullMessagePolicy == AddressFullMessagePolicy.FAIL) { sizeInBytes.addAndGet(size); } } @Override - public boolean - page(ServerMessage message, final Transaction tx, RouteContextList listCtx, final ReadLock managerLock) throws Exception - { + public boolean page(ServerMessage message, + final Transaction tx, + RouteContextList listCtx, + final ReadLock managerLock) throws Exception { - if (!running) - { + if (!running) { throw new IllegalStateException("PagingStore(" + getStoreName() + ") not initialized"); } boolean full = isFull(); - if (addressFullMessagePolicy == AddressFullMessagePolicy.DROP || addressFullMessagePolicy == AddressFullMessagePolicy.FAIL) - { - if (full) - { - if (!printedDropMessagesWarning) - { + if (addressFullMessagePolicy == AddressFullMessagePolicy.DROP || addressFullMessagePolicy == AddressFullMessagePolicy.FAIL) { + if (full) { + if (!printedDropMessagesWarning) { printedDropMessagesWarning = true; ActiveMQServerLogger.LOGGER.pageStoreDropMessages(storeName, sizeInBytes.get(), maxSize); } - if (message.isLargeMessage()) - { - ((LargeServerMessage)message).deleteFile(); + if (message.isLargeMessage()) { + ((LargeServerMessage) message).deleteFile(); } - if (addressFullMessagePolicy == AddressFullMessagePolicy.FAIL) - { + if (addressFullMessagePolicy == AddressFullMessagePolicy.FAIL) { throw ActiveMQMessageBundle.BUNDLE.addressIsFull(address.toString()); } // Address is full, we just pretend we are paging, and drop the data return true; } - else - { + else { return false; } } - else if (addressFullMessagePolicy == AddressFullMessagePolicy.BLOCK) - { + else if (addressFullMessagePolicy == AddressFullMessagePolicy.BLOCK) { return false; } // We need to ensure a read lock, as depage could change the paging state lock.readLock().lock(); - try - { + try { // First check done concurrently, to avoid synchronization and increase throughput - if (!paging) - { + if (!paging) { return false; } } - finally - { + finally { lock.readLock().unlock(); } - managerLock.lock(); - try - { + try { lock.writeLock().lock(); - try - { - if (!paging) - { + try { + if (!paging) { return false; } - if (!message.isDurable()) - { + if (!message.isDurable()) { // The address should never be transient when paging (even for non-persistent messages when paging) // This will force everything to be persisted message.forceAddress(address); @@ -903,22 +771,19 @@ public class PagingStoreImpl implements PagingStore final long transactionID = tx == null ? -1 : tx.getID(); PagedMessage pagedMessage = new PagedMessageImpl(message, routeQueues(tx, listCtx), transactionID); - if (message.isLargeMessage()) - { + if (message.isLargeMessage()) { ((LargeServerMessage) message).setPaged(); } int bytesToWrite = pagedMessage.getEncodeSize() + Page.SIZE_RECORD; - if (currentPageSize.addAndGet(bytesToWrite) > pageSize && currentPage.getNumberOfMessages() > 0) - { + if (currentPageSize.addAndGet(bytesToWrite) > pageSize && currentPage.getNumberOfMessages() > 0) { // Make sure nothing is currently validating or using currentPage openNewPage(); currentPageSize.addAndGet(bytesToWrite); } - if (tx != null) - { + if (tx != null) { installPageTransaction(tx, listCtx); } @@ -929,26 +794,22 @@ public class PagingStoreImpl implements PagingStore currentPage.write(pagedMessage); - if (tx == null && syncNonTransactional && message.isDurable()) - { + if (tx == null && syncNonTransactional && message.isDurable()) { sync(); } - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Paging message " + pagedMessage + " on pageStore " + this.getStoreName() + - " pageId=" + currentPage.getPageId()); + " pageId=" + currentPage.getPageId()); } return true; } - finally - { + finally { lock.writeLock().unlock(); } } - finally - { + finally { managerLock.unlock(); } } @@ -956,35 +817,29 @@ public class PagingStoreImpl implements PagingStore /** * This method will disable cleanup of pages. No page will be deleted after this call. */ - public void disableCleanup() - { + public void disableCleanup() { getCursorProvider().disableCleanup(); } - /** * This method will re-enable cleanup of pages. Notice that it will also start cleanup threads. */ - public void enableCleanup() - { + public void enableCleanup() { getCursorProvider().resumeCleanup(); } - private long[] routeQueues(Transaction tx, RouteContextList ctx) throws Exception - { + private long[] routeQueues(Transaction tx, RouteContextList ctx) throws Exception { List durableQueues = ctx.getDurableQueues(); List nonDurableQueues = ctx.getNonDurableQueues(); long[] ids = new long[durableQueues.size() + nonDurableQueues.size()]; int i = 0; - for (org.apache.activemq.artemis.core.server.Queue q : durableQueues) - { + for (org.apache.activemq.artemis.core.server.Queue q : durableQueues) { q.getPageSubscription().notEmpty(); ids[i++] = q.getID(); } - for (org.apache.activemq.artemis.core.server.Queue q : nonDurableQueues) - { + for (org.apache.activemq.artemis.core.server.Queue q : nonDurableQueues) { q.getPageSubscription().getCounter().increment(tx, 1); q.getPageSubscription().notEmpty(); ids[i++] = q.getID(); @@ -994,42 +849,36 @@ public class PagingStoreImpl implements PagingStore /** * This is done to prevent non tx to get out of sync in case of failures + * * @param tx * @param page * @param ctx * @throws Exception */ - private void applyPageCounters(Transaction tx, Page page, RouteContextList ctx) throws Exception - { + private void applyPageCounters(Transaction tx, Page page, RouteContextList ctx) throws Exception { List durableQueues = ctx.getDurableQueues(); List nonDurableQueues = ctx.getNonDurableQueues(); - for (org.apache.activemq.artemis.core.server.Queue q : durableQueues) - { - if (tx == null) - { + for (org.apache.activemq.artemis.core.server.Queue q : durableQueues) { + if (tx == null) { // non transactional writes need an intermediate place // to avoid the counter getting out of sync q.getPageSubscription().getCounter().pendingCounter(page, 1); } - else - { + else { // null tx is treated through pending counters q.getPageSubscription().getCounter().increment(tx, 1); } } - for (org.apache.activemq.artemis.core.server.Queue q : nonDurableQueues) - { + for (org.apache.activemq.artemis.core.server.Queue q : nonDurableQueues) { q.getPageSubscription().getCounter().increment(tx, 1); } } - private void installPageTransaction(final Transaction tx, final RouteContextList listCtx) throws Exception - { - FinishPageMessageOperation pgOper = (FinishPageMessageOperation)tx.getProperty(TransactionPropertyIndexes.PAGE_TRANSACTION); - if (pgOper == null) - { + private void installPageTransaction(final Transaction tx, final RouteContextList listCtx) throws Exception { + FinishPageMessageOperation pgOper = (FinishPageMessageOperation) tx.getProperty(TransactionPropertyIndexes.PAGE_TRANSACTION); + if (pgOper == null) { PageTransactionInfo pgTX = new PageTransactionInfoImpl(tx.getID()); pagingManager.addTransaction(pgTX); pgOper = new FinishPageMessageOperation(pgTX, storageManager, pagingManager); @@ -1043,8 +892,8 @@ public class PagingStoreImpl implements PagingStore return; } - private static class FinishPageMessageOperation implements TransactionOperation - { + private static class FinishPageMessageOperation implements TransactionOperation { + private final PageTransactionInfo pageTransaction; private final StorageManager storageManager; private final PagingManager pagingManager; @@ -1052,46 +901,38 @@ public class PagingStoreImpl implements PagingStore private boolean stored = false; - public void addStore(PagingStore store) - { + public void addStore(PagingStore store) { this.usedStores.add(store); } public FinishPageMessageOperation(final PageTransactionInfo pageTransaction, final StorageManager storageManager, - final PagingManager pagingManager) - { + final PagingManager pagingManager) { this.pageTransaction = pageTransaction; this.storageManager = storageManager; this.pagingManager = pagingManager; } - public void afterCommit(final Transaction tx) - { + public void afterCommit(final Transaction tx) { // If part of the transaction goes to the queue, and part goes to paging, we can't let depage start for the // transaction until all the messages were added to the queue // or else we could deliver the messages out of order - if (pageTransaction != null) - { + if (pageTransaction != null) { pageTransaction.commit(); } } - public void afterPrepare(final Transaction tx) - { + public void afterPrepare(final Transaction tx) { } - public void afterRollback(final Transaction tx) - { - if (pageTransaction != null) - { + public void afterRollback(final Transaction tx) { + if (pageTransaction != null) { pageTransaction.rollback(); } } - public void beforeCommit(final Transaction tx) throws Exception - { + public void beforeCommit(final Transaction tx) throws Exception { syncStore(); storePageTX(tx); } @@ -1099,60 +940,49 @@ public class PagingStoreImpl implements PagingStore /** * @throws Exception */ - private void syncStore() throws Exception - { - for (PagingStore store : usedStores) - { + private void syncStore() throws Exception { + for (PagingStore store : usedStores) { store.sync(); } } - public void beforePrepare(final Transaction tx) throws Exception - { + public void beforePrepare(final Transaction tx) throws Exception { syncStore(); storePageTX(tx); } - private void storePageTX(final Transaction tx) throws Exception - { - if (!stored) - { + private void storePageTX(final Transaction tx) throws Exception { + if (!stored) { tx.setContainsPersistent(); pageTransaction.store(storageManager, pagingManager, tx); stored = true; } } - public void beforeRollback(final Transaction tx) throws Exception - { + public void beforeRollback(final Transaction tx) throws Exception { } @Override - public List getRelatedMessageReferences() - { + public List getRelatedMessageReferences() { return Collections.emptyList(); } @Override - public List getListOnConsumer(long consumerID) - { + public List getListOnConsumer(long consumerID) { return Collections.emptyList(); } } - private void openNewPage() throws Exception - { + private void openNewPage() throws Exception { lock.writeLock().lock(); - try - { + try { numberOfPages++; int tmpCurrentPageId = currentPageId + 1; - if (currentPage != null) - { + if (currentPage != null) { currentPage.close(); } @@ -1170,13 +1000,11 @@ public class PagingStoreImpl implements PagingStore currentPageId = tmpCurrentPageId; - if (currentPageId < firstPageId) - { + if (currentPageId < firstPageId) { firstPageId = currentPageId; } } - finally - { + finally { lock.writeLock().unlock(); } } @@ -1185,34 +1013,27 @@ public class PagingStoreImpl implements PagingStore * @param pageID * @return */ - private String createFileName(final int pageID) - { + private String createFileName(final int pageID) { /** {@link DecimalFormat} is not thread safe. */ - synchronized (format) - { + synchronized (format) { return format.format(pageID) + ".page"; } } - private static int getPageIdFromFileName(final String fileName) - { + private static int getPageIdFromFileName(final String fileName) { return Integer.parseInt(fileName.substring(0, fileName.indexOf('.'))); } // To be used on isDropMessagesWhenFull - public boolean isFull() - { + public boolean isFull() { return maxSize > 0 && getAddressSize() > maxSize; } @Override - public Collection getCurrentIds() throws Exception - { + public Collection getCurrentIds() throws Exception { List ids = new ArrayList(); - if (fileFactory != null) - { - for (String fileName : fileFactory.listFiles("page")) - { + if (fileFactory != null) { + for (String fileName : fileFactory.listFiles("page")) { ids.add(getPageIdFromFileName(fileName)); } } @@ -1220,27 +1041,21 @@ public class PagingStoreImpl implements PagingStore } @Override - public void sendPages(ReplicationManager replicator, Collection pageIds) throws Exception - { + public void sendPages(ReplicationManager replicator, Collection pageIds) throws Exception { lock.writeLock().lock(); - try - { - for (Integer id : pageIds) - { + try { + for (Integer id : pageIds) { SequentialFile sFile = fileFactory.createSequentialFile(createFileName(id)); - if (!sFile.exists()) - { + if (!sFile.exists()) { continue; } replicator.syncPages(sFile, id, getAddress()); } } - finally - { + finally { lock.writeLock().unlock(); } } - // Inner classes ------------------------------------------------- } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/GroupingInfo.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/GroupingInfo.java index 4b6a510db4..ec52ce15de 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/GroupingInfo.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/GroupingInfo.java @@ -18,8 +18,8 @@ package org.apache.activemq.artemis.core.persistence; import org.apache.activemq.artemis.api.core.SimpleString; -public interface GroupingInfo -{ +public interface GroupingInfo { + SimpleString getClusterName(); SimpleString getGroupId(); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/OperationContext.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/OperationContext.java index d13f311b28..6d64eb8f58 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/OperationContext.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/OperationContext.java @@ -24,10 +24,12 @@ import org.apache.activemq.artemis.core.journal.IOCompletion; *

    * When the entire set is done, a group of Runnables can be executed. */ -public interface OperationContext extends IOCompletion -{ - /** Execute the task when all IO operations are complete, - * Or execute it immediately if nothing is pending. */ +public interface OperationContext extends IOCompletion { + + /** + * Execute the task when all IO operations are complete, + * Or execute it immediately if nothing is pending. + */ void executeOnCompletion(IOCallback runnable); void replicationLineUp(); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/QueueBindingInfo.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/QueueBindingInfo.java index d48ae939ee..c05b86c77f 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/QueueBindingInfo.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/QueueBindingInfo.java @@ -18,8 +18,8 @@ package org.apache.activemq.artemis.core.persistence; import org.apache.activemq.artemis.api.core.SimpleString; -public interface QueueBindingInfo -{ +public interface QueueBindingInfo { + long getId(); SimpleString getAddress(); @@ -28,6 +28,7 @@ public interface QueueBindingInfo /** * used to rename the queue in case of a duplication during load time + * * @param newName */ void replaceQueueName(SimpleString newName); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/StorageManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/StorageManager.java index 7cf811249e..76cb1bcf74 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/StorageManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/StorageManager.java @@ -57,15 +57,12 @@ import org.apache.activemq.artemis.utils.IDGenerator; * * Note about IDGEnerator * - * I've changed StorageManager to extend IDGenerator, because in some places - * all we needed from the StorageManager was the idGeneration. - * I couldn't just get the IDGenerator from the inner part because the NullPersistent has its own sequence. - * So the best was to add the interface and adjust the callers for the method - * - + * I've changed StorageManager to extend IDGenerator, because in some places + * all we needed from the StorageManager was the idGeneration. + * I couldn't just get the IDGenerator from the inner part because the NullPersistent has its own sequence. + * So the best was to add the interface and adjust the callers for the method */ -public interface StorageManager extends IDGenerator, ActiveMQComponent -{ +public interface StorageManager extends IDGenerator, ActiveMQComponent { /** * Get the context associated with the thread for later reuse @@ -137,7 +134,6 @@ public interface StorageManager extends IDGenerator, ActiveMQComponent */ void afterPageRead() throws Exception; - /** * AIO has an optimized buffer which has a method to release it * instead of the way NIO will release data based on GC. @@ -219,18 +215,15 @@ public interface StorageManager extends IDGenerator, ActiveMQComponent */ LargeServerMessage createLargeMessage(long id, MessageInternal message) throws Exception; - enum LargeMessageExtension - { + enum LargeMessageExtension { DURABLE(".msg"), TEMPORARY(".tmp"), SYNC(".sync"); final String extension; - private LargeMessageExtension(String extension) - { + private LargeMessageExtension(String extension) { this.extension = extension; } - public String getExtension() - { + public String getExtension() { return extension; } } @@ -274,8 +267,7 @@ public interface StorageManager extends IDGenerator, ActiveMQComponent final Map>> duplicateIDMap, final Set> pendingLargeMessages, List pendingNonTXPageCounter, - final JournalLoader journalLoader - ) throws Exception; + final JournalLoader journalLoader) throws Exception; long storeHeuristicCompletion(Xid xid, boolean isCommit) throws Exception; @@ -287,7 +279,8 @@ public interface StorageManager extends IDGenerator, ActiveMQComponent void deleteQueueBinding(long tx, long queueBindingID) throws Exception; - JournalLoadInformation loadBindingJournal(List queueBindingInfos, List groupingInfos) throws Exception; + JournalLoadInformation loadBindingJournal(List queueBindingInfos, + List groupingInfos) throws Exception; // grouping related operations void addGrouping(GroupBinding groupBinding) throws Exception; @@ -344,7 +337,9 @@ public interface StorageManager extends IDGenerator, ActiveMQComponent /** * @see org.apache.activemq.artemis.core.persistence.impl.journal.JournalStorageManager#startReplication(org.apache.activemq.artemis.core.replication.ReplicationManager, org.apache.activemq.artemis.core.paging.PagingManager, String, boolean) */ - void startReplication(ReplicationManager replicationManager, PagingManager pagingManager, String nodeID, + void startReplication(ReplicationManager replicationManager, + PagingManager pagingManager, + String nodeID, boolean autoFailBack) throws Exception; /** @@ -384,13 +379,11 @@ public interface StorageManager extends IDGenerator, ActiveMQComponent */ void storeID(long journalID, long id) throws Exception; - /* Deletes the ID from IDManager. */ void deleteID(long journalD) throws Exception; - /** * Read lock the StorageManager. USE WITH CARE! *

    diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/config/PersistedAddressSetting.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/config/PersistedAddressSetting.java index 13e0004098..d1c5591eee 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/config/PersistedAddressSetting.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/config/PersistedAddressSetting.java @@ -21,8 +21,7 @@ import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.journal.EncodingSupport; import org.apache.activemq.artemis.core.settings.impl.AddressSettings; -public class PersistedAddressSetting implements EncodingSupport -{ +public class PersistedAddressSetting implements EncodingSupport { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -37,8 +36,7 @@ public class PersistedAddressSetting implements EncodingSupport // Constructors -------------------------------------------------- - public PersistedAddressSetting() - { + public PersistedAddressSetting() { super(); } @@ -46,22 +44,20 @@ public class PersistedAddressSetting implements EncodingSupport * @see java.lang.Object#toString() */ @Override - public String toString() - { + public String toString() { return "PersistedAddressSetting [storeId=" + storeId + - ", addressMatch=" + - addressMatch + - ", setting=" + - setting + - "]"; + ", addressMatch=" + + addressMatch + + ", setting=" + + setting + + "]"; } /** * @param addressMatch * @param setting */ - public PersistedAddressSetting(SimpleString addressMatch, AddressSettings setting) - { + public PersistedAddressSetting(SimpleString addressMatch, AddressSettings setting) { super(); this.addressMatch = addressMatch; this.setting = setting; @@ -69,35 +65,30 @@ public class PersistedAddressSetting implements EncodingSupport // Public -------------------------------------------------------- - public void setStoreId(long id) - { + public void setStoreId(long id) { this.storeId = id; } - public long getStoreId() - { + public long getStoreId() { return storeId; } /** * @return the addressMatch */ - public SimpleString getAddressMatch() - { + public SimpleString getAddressMatch() { return addressMatch; } /** * @return the setting */ - public AddressSettings getSetting() - { + public AddressSettings getSetting() { return setting; } @Override - public void decode(ActiveMQBuffer buffer) - { + public void decode(ActiveMQBuffer buffer) { addressMatch = buffer.readSimpleString(); setting = new AddressSettings(); @@ -105,16 +96,14 @@ public class PersistedAddressSetting implements EncodingSupport } @Override - public void encode(ActiveMQBuffer buffer) - { + public void encode(ActiveMQBuffer buffer) { buffer.writeSimpleString(addressMatch); setting.encode(buffer); } @Override - public int getEncodeSize() - { + public int getEncodeSize() { return addressMatch.sizeof() + setting.getEncodeSize(); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/config/PersistedRoles.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/config/PersistedRoles.java index ec5fe2bdc1..5b3c4223cc 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/config/PersistedRoles.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/config/PersistedRoles.java @@ -20,8 +20,7 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.journal.EncodingSupport; -public class PersistedRoles implements EncodingSupport -{ +public class PersistedRoles implements EncodingSupport { // Constants ----------------------------------------------------- @@ -49,8 +48,7 @@ public class PersistedRoles implements EncodingSupport // Constructors -------------------------------------------------- - public PersistedRoles() - { + public PersistedRoles() { } /** @@ -70,8 +68,7 @@ public class PersistedRoles implements EncodingSupport final String deleteDurableQueueRoles, final String createNonDurableQueueRoles, final String deleteNonDurableQueueRoles, - final String manageRoles) - { + final String manageRoles) { super(); this.addressMatch = SimpleString.toSimpleString(addressMatch); this.sendRoles = SimpleString.toSimpleString(sendRoles); @@ -85,83 +82,72 @@ public class PersistedRoles implements EncodingSupport // Public -------------------------------------------------------- - public long getStoreId() - { + public long getStoreId() { return storeId; } - public void setStoreId(final long id) - { + public void setStoreId(final long id) { storeId = id; } /** * @return the addressMatch */ - public SimpleString getAddressMatch() - { + public SimpleString getAddressMatch() { return addressMatch; } /** * @return the sendRoles */ - public String getSendRoles() - { + public String getSendRoles() { return sendRoles.toString(); } /** * @return the consumeRoles */ - public String getConsumeRoles() - { + public String getConsumeRoles() { return consumeRoles.toString(); } /** * @return the createDurableQueueRoles */ - public String getCreateDurableQueueRoles() - { + public String getCreateDurableQueueRoles() { return createDurableQueueRoles.toString(); } /** * @return the deleteDurableQueueRoles */ - public String getDeleteDurableQueueRoles() - { + public String getDeleteDurableQueueRoles() { return deleteDurableQueueRoles.toString(); } /** * @return the createNonDurableQueueRoles */ - public String getCreateNonDurableQueueRoles() - { + public String getCreateNonDurableQueueRoles() { return createNonDurableQueueRoles.toString(); } /** * @return the deleteNonDurableQueueRoles */ - public String getDeleteNonDurableQueueRoles() - { + public String getDeleteNonDurableQueueRoles() { return deleteNonDurableQueueRoles.toString(); } /** * @return the manageRoles */ - public String getManageRoles() - { + public String getManageRoles() { return manageRoles.toString(); } @Override - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { buffer.writeSimpleString(addressMatch); buffer.writeNullableSimpleString(sendRoles); buffer.writeNullableSimpleString(consumeRoles); @@ -173,21 +159,19 @@ public class PersistedRoles implements EncodingSupport } @Override - public int getEncodeSize() - { + public int getEncodeSize() { return addressMatch.sizeof() + SimpleString.sizeofNullableString(sendRoles) + - SimpleString.sizeofNullableString(consumeRoles) + - SimpleString.sizeofNullableString(createDurableQueueRoles) + - SimpleString.sizeofNullableString(deleteDurableQueueRoles) + - SimpleString.sizeofNullableString(createNonDurableQueueRoles) + - SimpleString.sizeofNullableString(deleteNonDurableQueueRoles) + - SimpleString.sizeofNullableString(manageRoles); + SimpleString.sizeofNullableString(consumeRoles) + + SimpleString.sizeofNullableString(createDurableQueueRoles) + + SimpleString.sizeofNullableString(deleteDurableQueueRoles) + + SimpleString.sizeofNullableString(createNonDurableQueueRoles) + + SimpleString.sizeofNullableString(deleteNonDurableQueueRoles) + + SimpleString.sizeofNullableString(manageRoles); } @Override - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { addressMatch = buffer.readSimpleString(); sendRoles = buffer.readNullableSimpleString(); consumeRoles = buffer.readNullableSimpleString(); @@ -202,8 +186,7 @@ public class PersistedRoles implements EncodingSupport * @see java.lang.Object#hashCode() */ @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((addressMatch == null) ? 0 : addressMatch.hashCode()); @@ -214,7 +197,7 @@ public class PersistedRoles implements EncodingSupport result = prime * result + ((deleteNonDurableQueueRoles == null) ? 0 : deleteNonDurableQueueRoles.hashCode()); result = prime * result + ((manageRoles == null) ? 0 : manageRoles.hashCode()); result = prime * result + ((sendRoles == null) ? 0 : sendRoles.hashCode()); - result = prime * result + (int)(storeId ^ (storeId >>> 32)); + result = prime * result + (int) (storeId ^ (storeId >>> 32)); return result; } @@ -222,66 +205,57 @@ public class PersistedRoles implements EncodingSupport * @see java.lang.Object#equals(java.lang.Object) */ @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; - PersistedRoles other = (PersistedRoles)obj; - if (addressMatch == null) - { + PersistedRoles other = (PersistedRoles) obj; + if (addressMatch == null) { if (other.addressMatch != null) return false; } else if (!addressMatch.equals(other.addressMatch)) return false; - if (consumeRoles == null) - { + if (consumeRoles == null) { if (other.consumeRoles != null) return false; } else if (!consumeRoles.equals(other.consumeRoles)) return false; - if (createDurableQueueRoles == null) - { + if (createDurableQueueRoles == null) { if (other.createDurableQueueRoles != null) return false; } else if (!createDurableQueueRoles.equals(other.createDurableQueueRoles)) return false; - if (createNonDurableQueueRoles == null) - { + if (createNonDurableQueueRoles == null) { if (other.createNonDurableQueueRoles != null) return false; } else if (!createNonDurableQueueRoles.equals(other.createNonDurableQueueRoles)) return false; - if (deleteDurableQueueRoles == null) - { + if (deleteDurableQueueRoles == null) { if (other.deleteDurableQueueRoles != null) return false; } else if (!deleteDurableQueueRoles.equals(other.deleteDurableQueueRoles)) return false; - if (deleteNonDurableQueueRoles == null) - { + if (deleteNonDurableQueueRoles == null) { if (other.deleteNonDurableQueueRoles != null) return false; } else if (!deleteNonDurableQueueRoles.equals(other.deleteNonDurableQueueRoles)) return false; - if (manageRoles == null) - { + if (manageRoles == null) { if (other.manageRoles != null) return false; } else if (!manageRoles.equals(other.manageRoles)) return false; - if (sendRoles == null) - { + if (sendRoles == null) { if (other.sendRoles != null) return false; } @@ -296,30 +270,27 @@ public class PersistedRoles implements EncodingSupport * @see java.lang.Object#toString() */ @Override - public String toString() - { + public String toString() { return "PersistedRoles [storeId=" + storeId + - ", addressMatch=" + - addressMatch + - ", sendRoles=" + - sendRoles + - ", consumeRoles=" + - consumeRoles + - ", createDurableQueueRoles=" + - createDurableQueueRoles + - ", deleteDurableQueueRoles=" + - deleteDurableQueueRoles + - ", createNonDurableQueueRoles=" + - createNonDurableQueueRoles + - ", deleteNonDurableQueueRoles=" + - deleteNonDurableQueueRoles + - ", manageRoles=" + - manageRoles + - "]"; + ", addressMatch=" + + addressMatch + + ", sendRoles=" + + sendRoles + + ", consumeRoles=" + + consumeRoles + + ", createDurableQueueRoles=" + + createDurableQueueRoles + + ", deleteDurableQueueRoles=" + + deleteDurableQueueRoles + + ", createNonDurableQueueRoles=" + + createNonDurableQueueRoles + + ", deleteNonDurableQueueRoles=" + + deleteNonDurableQueueRoles + + ", manageRoles=" + + manageRoles + + "]"; } - - // Package protected --------------------------------------------- // Protected ----------------------------------------------------- diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/PageCountPending.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/PageCountPending.java index be79307781..8cc412db8e 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/PageCountPending.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/PageCountPending.java @@ -16,10 +16,12 @@ */ package org.apache.activemq.artemis.core.persistence.impl; -public interface PageCountPending -{ +public interface PageCountPending { + long getID(); + long getQueueID(); + long getPageID(); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/AddMessageRecord.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/AddMessageRecord.java index ef74dd3ff2..49ac289fab 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/AddMessageRecord.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/AddMessageRecord.java @@ -18,10 +18,9 @@ package org.apache.activemq.artemis.core.persistence.impl.journal; import org.apache.activemq.artemis.core.server.ServerMessage; -public final class AddMessageRecord -{ - public AddMessageRecord(final ServerMessage message) - { +public final class AddMessageRecord { + + public AddMessageRecord(final ServerMessage message) { this.message = message; } @@ -31,18 +30,15 @@ public final class AddMessageRecord int deliveryCount; - public ServerMessage getMessage() - { + public ServerMessage getMessage() { return message; } - public long getScheduledDeliveryTime() - { + public long getScheduledDeliveryTime() { return scheduledDeliveryTime; } - public int getDeliveryCount() - { + public int getDeliveryCount() { return deliveryCount; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/BatchingIDGenerator.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/BatchingIDGenerator.java index 3a035de369..7b32c4ca4f 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/BatchingIDGenerator.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/BatchingIDGenerator.java @@ -31,10 +31,11 @@ import org.apache.activemq.artemis.utils.IDGenerator; /** * An ID generator that allocates a batch of IDs of size {@link #checkpointSize} and records the ID * in the journal only when starting a new batch. + * * @see IDGenerator */ -public final class BatchingIDGenerator implements IDGenerator -{ +public final class BatchingIDGenerator implements IDGenerator { + private final AtomicLong counter; private final long checkpointSize; @@ -45,8 +46,7 @@ public final class BatchingIDGenerator implements IDGenerator private List cleanupRecords = null; - public BatchingIDGenerator(final long start, final long checkpointSize, final StorageManager storageManager) - { + public BatchingIDGenerator(final long start, final long checkpointSize, final StorageManager storageManager) { counter = new AtomicLong(start); // as soon as you generate the first ID, the nextID should be updated @@ -57,8 +57,7 @@ public final class BatchingIDGenerator implements IDGenerator this.storageManager = storageManager; } - public void persistCurrentID() - { + public void persistCurrentID() { final long recordID = counter.incrementAndGet(); storeID(recordID, recordID); } @@ -66,16 +65,12 @@ public final class BatchingIDGenerator implements IDGenerator /** * A method to cleanup old records after started */ - public void cleanup() - { - if (cleanupRecords != null) - { + public void cleanup() { + if (cleanupRecords != null) { Iterator iterRecord = cleanupRecords.iterator(); - while (iterRecord.hasNext()) - { + while (iterRecord.hasNext()) { Long record = iterRecord.next(); - if (iterRecord.hasNext()) - { + if (iterRecord.hasNext()) { // we don't want to remove the last record deleteID(record.longValue()); } @@ -85,8 +80,7 @@ public final class BatchingIDGenerator implements IDGenerator } } - public void loadState(final long journalID, final ActiveMQBuffer buffer) - { + public void loadState(final long journalID, final ActiveMQBuffer buffer) { addCleanupRecord(journalID); IDCounterEncoding encoding = new IDCounterEncoding(); @@ -98,116 +92,93 @@ public final class BatchingIDGenerator implements IDGenerator counter.set(nextID); } - public long generateID() - { + public long generateID() { long id = counter.getAndIncrement(); - if (id >= nextID) - { + if (id >= nextID) { saveCheckPoint(id); } return id; } - public long getCurrentID() - { + public long getCurrentID() { return counter.get(); } - private synchronized void saveCheckPoint(final long id) - { - if (id >= nextID) - { + private synchronized void saveCheckPoint(final long id) { + if (id >= nextID) { nextID += checkpointSize; - if (!storageManager.isStarted()) - { + if (!storageManager.isStarted()) { // This could happen after the server is stopped // while notifications are being sent and ID gerated. // If the ID is intended to the journal you would know soon enough // so we just ignore this for now - ActiveMQServerLogger.LOGGER.debug("The journalStorageManager is not loaded. " + - "This is probably ok as long as it's a notification being sent after shutdown"); + ActiveMQServerLogger.LOGGER.debug("The journalStorageManager is not loaded. " + "This is probably ok as long as it's a notification being sent after shutdown"); } - else - { + else { storeID(counter.getAndIncrement(), nextID); } } } - private void addCleanupRecord(long id) - { - if (cleanupRecords == null) - { + private void addCleanupRecord(long id) { + if (cleanupRecords == null) { cleanupRecords = new LinkedList<>(); } cleanupRecords.add(id); } - private void storeID(final long journalID, final long id) - { - try - { + private void storeID(final long journalID, final long id) { + try { storageManager.storeID(journalID, id); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.batchingIdError(e); } } - private void deleteID(final long journalID) - { - try - { + private void deleteID(final long journalID) { + try { storageManager.deleteID(journalID); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.batchingIdError(e); } } - public static EncodingSupport createIDEncodingSupport(final long id) - { + public static EncodingSupport createIDEncodingSupport(final long id) { return new IDCounterEncoding(id); } // Inner classes ------------------------------------------------- - protected static final class IDCounterEncoding implements EncodingSupport - { + protected static final class IDCounterEncoding implements EncodingSupport { + private long id; @Override - public String toString() - { + public String toString() { return "IDCounterEncoding [id=" + id + "]"; } - private IDCounterEncoding(final long id) - { + private IDCounterEncoding(final long id) { this.id = id; } - IDCounterEncoding() - { + IDCounterEncoding() { } - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { id = buffer.readLong(); } - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { buffer.writeLong(id); } - public int getEncodeSize() - { + public int getEncodeSize() { return DataConstants.SIZE_LONG; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/DescribeJournal.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/DescribeJournal.java index 210877c9d5..d8b6fa93af 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/DescribeJournal.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/DescribeJournal.java @@ -84,30 +84,25 @@ import static org.apache.activemq.artemis.core.persistence.impl.journal.JournalR *

    * Meant to be used in debugging. */ -public final class DescribeJournal -{ +public final class DescribeJournal { private final List records; private final List preparedTransactions; - public DescribeJournal(List records, List preparedTransactions) - { + public DescribeJournal(List records, List preparedTransactions) { this.records = records; this.preparedTransactions = preparedTransactions; } - public List getRecords() - { + public List getRecords() { return records; } - public List getPreparedTransactions() - { + public List getPreparedTransactions() { return preparedTransactions; } - public static void describeBindingsJournal(final File bindingsDir) throws Exception - { + public static void describeBindingsJournal(final File bindingsDir) throws Exception { SequentialFileFactory bindingsFF = new NIOSequentialFileFactory(bindingsDir, null, 1); @@ -115,22 +110,14 @@ public final class DescribeJournal describeJournal(bindingsFF, bindings, bindingsDir); } - public static DescribeJournal describeMessagesJournal(final File messagesDir) throws Exception - { + public static DescribeJournal describeMessagesJournal(final File messagesDir) throws Exception { SequentialFileFactory messagesFF = new NIOSequentialFileFactory(messagesDir, null, 1); // Will use only default values. The load function should adapt to anything different ConfigurationImpl defaultValues = new ConfigurationImpl(); - JournalImpl messagesJournal = new JournalImpl(defaultValues.getJournalFileSize(), - defaultValues.getJournalMinFiles(), - 0, - 0, - messagesFF, - "activemq-data", - "amq", - 1); + JournalImpl messagesJournal = new JournalImpl(defaultValues.getJournalFileSize(), defaultValues.getJournalMinFiles(), 0, 0, messagesFF, "activemq-data", "amq", 1); return describeJournal(messagesFF, messagesJournal, messagesDir); } @@ -140,8 +127,9 @@ public final class DescribeJournal * @param journal * @throws Exception */ - private static DescribeJournal describeJournal(SequentialFileFactory fileFactory, JournalImpl journal, final File path) throws Exception - { + private static DescribeJournal describeJournal(SequentialFileFactory fileFactory, + JournalImpl journal, + final File path) throws Exception { List files = journal.orderFiles(); final PrintStream out = System.out; @@ -150,95 +138,79 @@ public final class DescribeJournal out.println("Journal path: " + path); - for (JournalFile file : files) - { + for (JournalFile file : files) { out.println("#" + file + " (size=" + file.getFile().size() + ")"); - JournalImpl.readJournalFile(fileFactory, file, new JournalReaderCallback() - { + JournalImpl.readJournalFile(fileFactory, file, new JournalReaderCallback() { - public void onReadUpdateRecordTX(final long transactionID, final RecordInfo recordInfo) throws Exception - { + public void onReadUpdateRecordTX(final long transactionID, final RecordInfo recordInfo) throws Exception { out.println("operation@UpdateTX;txID=" + transactionID + "," + describeRecord(recordInfo)); checkRecordCounter(recordInfo); } - public void onReadUpdateRecord(final RecordInfo recordInfo) throws Exception - { + public void onReadUpdateRecord(final RecordInfo recordInfo) throws Exception { out.println("operation@Update;" + describeRecord(recordInfo)); checkRecordCounter(recordInfo); } - public void onReadRollbackRecord(final long transactionID) throws Exception - { + public void onReadRollbackRecord(final long transactionID) throws Exception { out.println("operation@Rollback;txID=" + transactionID); } - public void onReadPrepareRecord(final long transactionID, final byte[] extraData, final int numberOfRecords) throws Exception - { + public void onReadPrepareRecord(final long transactionID, + final byte[] extraData, + final int numberOfRecords) throws Exception { out.println("operation@Prepare,txID=" + transactionID + ",numberOfRecords=" + numberOfRecords + ",extraData=" + encode(extraData) + ", xid=" + toXid(extraData)); } - public void onReadDeleteRecordTX(final long transactionID, final RecordInfo recordInfo) throws Exception - { + public void onReadDeleteRecordTX(final long transactionID, final RecordInfo recordInfo) throws Exception { out.println("operation@DeleteRecordTX;txID=" + transactionID + "," + describeRecord(recordInfo)); } - public void onReadDeleteRecord(final long recordID) throws Exception - { + public void onReadDeleteRecord(final long recordID) throws Exception { out.println("operation@DeleteRecord;recordID=" + recordID); } - public void onReadCommitRecord(final long transactionID, final int numberOfRecords) throws Exception - { + public void onReadCommitRecord(final long transactionID, final int numberOfRecords) throws Exception { out.println("operation@Commit;txID=" + transactionID + ",numberOfRecords=" + numberOfRecords); } - public void onReadAddRecordTX(final long transactionID, final RecordInfo recordInfo) throws Exception - { + public void onReadAddRecordTX(final long transactionID, final RecordInfo recordInfo) throws Exception { out.println("operation@AddRecordTX;txID=" + transactionID + "," + describeRecord(recordInfo)); } - public void onReadAddRecord(final RecordInfo recordInfo) throws Exception - { + public void onReadAddRecord(final RecordInfo recordInfo) throws Exception { out.println("operation@AddRecord;" + describeRecord(recordInfo)); } - public void markAsDataFile(final JournalFile file1) - { + public void markAsDataFile(final JournalFile file1) { } - public void checkRecordCounter(RecordInfo info) - { - if (info.getUserRecordType() == JournalRecordIds.PAGE_CURSOR_COUNTER_VALUE) - { - PageCountRecord encoding = (PageCountRecord)newObjectEncoding(info); + public void checkRecordCounter(RecordInfo info) { + if (info.getUserRecordType() == JournalRecordIds.PAGE_CURSOR_COUNTER_VALUE) { + PageCountRecord encoding = (PageCountRecord) newObjectEncoding(info); long queueIDForCounter = encoding.queueID; PageSubscriptionCounterImpl subsCounter = lookupCounter(counters, queueIDForCounter); - if (subsCounter.getValue() != 0 && subsCounter.getValue() != encoding.value) - { + if (subsCounter.getValue() != 0 && subsCounter.getValue() != encoding.value) { out.println("####### Counter replace wrongly on queue " + queueIDForCounter + " oldValue=" + subsCounter.getValue() + " newValue=" + encoding.value); } subsCounter.loadValue(info.id, encoding.value); subsCounter.processReload(); out.print("#Counter queue " + queueIDForCounter + " value=" + subsCounter.getValue() + ", result=" + subsCounter.getValue()); - if (subsCounter.getValue() < 0) - { + if (subsCounter.getValue() < 0) { out.println(" #NegativeCounter!!!!"); } - else - { + else { out.println(); } out.println(); } - else if (info.getUserRecordType() == JournalRecordIds.PAGE_CURSOR_COUNTER_INC) - { - PageCountRecordInc encoding = (PageCountRecordInc)newObjectEncoding(info); + else if (info.getUserRecordType() == JournalRecordIds.PAGE_CURSOR_COUNTER_INC) { + PageCountRecordInc encoding = (PageCountRecordInc) newObjectEncoding(info); long queueIDForCounter = encoding.queueID; PageSubscriptionCounterImpl subsCounter = lookupCounter(counters, queueIDForCounter); @@ -246,12 +218,10 @@ public final class DescribeJournal subsCounter.loadInc(info.id, encoding.value); subsCounter.processReload(); out.print("#Counter queue " + queueIDForCounter + " value=" + subsCounter.getValue() + " increased by " + encoding.value); - if (subsCounter.getValue() < 0) - { + if (subsCounter.getValue() < 0) { out.println(" #NegativeCounter!!!!"); } - else - { + else { out.println(); } out.println(); @@ -262,8 +232,7 @@ public final class DescribeJournal out.println(); - if (counters.size() != 0) - { + if (counters.size() != 0) { out.println("#Counters during initial load:"); printCounters(out, counters); } @@ -281,19 +250,17 @@ public final class DescribeJournal Map messageRefCounts = new HashMap(); int preparedMessageCount = 0; Map preparedMessageRefCount = new HashMap(); - journal.load(records, preparedTransactions, new TransactionFailureCallback() - { + journal.load(records, preparedTransactions, new TransactionFailureCallback() { - public void failedTransaction(long transactionID, List records1, List recordsToDelete) - { + public void failedTransaction(long transactionID, + List records1, + List recordsToDelete) { bufferFailingTransactions.append("Transaction " + transactionID + " failed with these records:\n"); - for (RecordInfo info : records1) - { + for (RecordInfo info : records1) { bufferFailingTransactions.append("- " + describeRecord(info) + "\n"); } - for (RecordInfo info : recordsToDelete) - { + for (RecordInfo info : recordsToDelete) { bufferFailingTransactions.append("- " + describeRecord(info) + " \n"); } @@ -302,46 +269,37 @@ public final class DescribeJournal counters.clear(); - for (RecordInfo info : records) - { + for (RecordInfo info : records) { PageSubscriptionCounterImpl subsCounter = null; long queueIDForCounter = 0; Object o = newObjectEncoding(info); - if (info.getUserRecordType() == JournalRecordIds.ADD_MESSAGE) - { + if (info.getUserRecordType() == JournalRecordIds.ADD_MESSAGE) { messageCount++; } - else if (info.getUserRecordType() == JournalRecordIds.ADD_REF) - { - ReferenceDescribe ref = (ReferenceDescribe)o; + else if (info.getUserRecordType() == JournalRecordIds.ADD_REF) { + ReferenceDescribe ref = (ReferenceDescribe) o; Integer count = messageRefCounts.get(ref.refEncoding.queueID); - if (count == null) - { + if (count == null) { count = 1; messageRefCounts.put(ref.refEncoding.queueID, count); } - else - { + else { messageRefCounts.put(ref.refEncoding.queueID, count + 1); } } - else if (info.getUserRecordType() == JournalRecordIds.ACKNOWLEDGE_REF) - { - AckDescribe ref = (AckDescribe)o; + else if (info.getUserRecordType() == JournalRecordIds.ACKNOWLEDGE_REF) { + AckDescribe ref = (AckDescribe) o; Integer count = messageRefCounts.get(ref.refEncoding.queueID); - if (count == null) - { + if (count == null) { messageRefCounts.put(ref.refEncoding.queueID, 0); } - else - { + else { messageRefCounts.put(ref.refEncoding.queueID, count - 1); } } - else if (info.getUserRecordType() == JournalRecordIds.PAGE_CURSOR_COUNTER_VALUE) - { - PageCountRecord encoding = (PageCountRecord)o; + else if (info.getUserRecordType() == JournalRecordIds.PAGE_CURSOR_COUNTER_VALUE) { + PageCountRecord encoding = (PageCountRecord) o; queueIDForCounter = encoding.queueID; subsCounter = lookupCounter(counters, queueIDForCounter); @@ -349,9 +307,8 @@ public final class DescribeJournal subsCounter.loadValue(info.id, encoding.value); subsCounter.processReload(); } - else if (info.getUserRecordType() == JournalRecordIds.PAGE_CURSOR_COUNTER_INC) - { - PageCountRecordInc encoding = (PageCountRecordInc)o; + else if (info.getUserRecordType() == JournalRecordIds.PAGE_CURSOR_COUNTER_INC) { + PageCountRecordInc encoding = (PageCountRecordInc) o; queueIDForCounter = encoding.queueID; subsCounter = lookupCounter(counters, queueIDForCounter); @@ -362,60 +319,49 @@ public final class DescribeJournal out.println(describeRecord(info, o)); - if (subsCounter != null) - { + if (subsCounter != null) { out.println("##SubsCounter for queue=" + queueIDForCounter + ", value=" + subsCounter.getValue()); out.println(); } } - if (counters.size() > 0) - { + if (counters.size() > 0) { out.println("### Page Counters"); printCounters(out, counters); } - out.println(); out.println("### Prepared TX ###"); - for (PreparedTransactionInfo tx : preparedTransactions) - { + for (PreparedTransactionInfo tx : preparedTransactions) { out.println(tx.id); - for (RecordInfo info : tx.records) - { + for (RecordInfo info : tx.records) { Object o = newObjectEncoding(info); out.println("- " + describeRecord(info, o)); - if (info.getUserRecordType() == 31) - { + if (info.getUserRecordType() == 31) { preparedMessageCount++; } - else if (info.getUserRecordType() == 32) - { - ReferenceDescribe ref = (ReferenceDescribe)o; + else if (info.getUserRecordType() == 32) { + ReferenceDescribe ref = (ReferenceDescribe) o; Integer count = preparedMessageRefCount.get(ref.refEncoding.queueID); - if (count == null) - { + if (count == null) { count = 1; preparedMessageRefCount.put(ref.refEncoding.queueID, count); } - else - { + else { preparedMessageRefCount.put(ref.refEncoding.queueID, count + 1); } } } - for (RecordInfo info : tx.recordsToDelete) - { + for (RecordInfo info : tx.recordsToDelete) { out.println("- " + describeRecord(info) + " "); } } String missingTX = bufferFailingTransactions.toString(); - if (missingTX.length() > 0) - { + if (missingTX.length() > 0) { out.println(); out.println("### Failed Transactions (Missing commit/prepare/rollback record) ###"); } @@ -425,15 +371,13 @@ public final class DescribeJournal out.println("### Message Counts ###"); out.println("message count=" + messageCount); out.println("message reference count"); - for (Map.Entry longIntegerEntry : messageRefCounts.entrySet()) - { + for (Map.Entry longIntegerEntry : messageRefCounts.entrySet()) { System.out.println("queue id " + longIntegerEntry.getKey() + ",count=" + longIntegerEntry.getValue()); } out.println("prepared message count=" + preparedMessageCount); - for (Map.Entry longIntegerEntry : preparedMessageRefCount.entrySet()) - { + for (Map.Entry longIntegerEntry : preparedMessageRefCount.entrySet()) { System.out.println("queue id " + longIntegerEntry.getKey() + ",count=" + longIntegerEntry.getValue()); } @@ -442,76 +386,61 @@ public final class DescribeJournal return new DescribeJournal(records, preparedTransactions); } - protected static void printCounters(final PrintStream out, final Map counters) - { - for (Map.Entry entry : counters.entrySet()) - { + protected static void printCounters(final PrintStream out, final Map counters) { + for (Map.Entry entry : counters.entrySet()) { out.println("Queue " + entry.getKey() + " value=" + entry.getValue().getValue()); } } protected static PageSubscriptionCounterImpl lookupCounter(Map counters, - long queueIDForCounter) - { + long queueIDForCounter) { PageSubscriptionCounterImpl subsCounter; subsCounter = counters.get(queueIDForCounter); - if (subsCounter == null) - { + if (subsCounter == null) { subsCounter = new PageSubscriptionCounterImpl(null, null, null, false, -1); counters.put(queueIDForCounter, subsCounter); } return subsCounter; } - private static String describeRecord(RecordInfo info) - { + private static String describeRecord(RecordInfo info) { return "recordID=" + info.id + ";userRecordType=" + info.userRecordType + ";isUpdate=" + info.isUpdate + ";compactCount=" + info.compactCount + ";" + newObjectEncoding(info); } - private static String describeRecord(RecordInfo info, Object o) - { + private static String describeRecord(RecordInfo info, Object o) { return "recordID=" + info.id + ";userRecordType=" + info.userRecordType + ";isUpdate=" + info.isUpdate + ";compactCount=" + info.compactCount + ";" + o; } - private static String encode(final byte[] data) - { + private static String encode(final byte[] data) { return Base64.encodeBytes(data, 0, data.length, Base64.DONT_BREAK_LINES | Base64.URL_SAFE); } - private static Xid toXid(final byte[] data) - { - try - { + private static Xid toXid(final byte[] data) { + try { return XidCodecSupport.decodeXid(ActiveMQBuffers.wrappedBuffer(data)); } - catch (Exception e) - { + catch (Exception e) { return null; } } - public static Object newObjectEncoding(RecordInfo info) - { + public static Object newObjectEncoding(RecordInfo info) { return newObjectEncoding(info, null); } - public static Object newObjectEncoding(RecordInfo info, JournalStorageManager storageManager) - { + public static Object newObjectEncoding(RecordInfo info, JournalStorageManager storageManager) { ActiveMQBuffer buffer = ActiveMQBuffers.wrappedBuffer(info.data); long id = info.id; int rec = info.getUserRecordType(); - switch (rec) - { - case ADD_LARGE_MESSAGE_PENDING: - { + switch (rec) { + case ADD_LARGE_MESSAGE_PENDING: { PendingLargeMessageEncoding lmEncoding = new PendingLargeMessageEncoding(); lmEncoding.decode(buffer); return lmEncoding; } - case ADD_LARGE_MESSAGE: - { + case ADD_LARGE_MESSAGE: { LargeServerMessage largeMessage = new LargeServerMessageImpl(storageManager); @@ -521,47 +450,40 @@ public final class DescribeJournal return new MessageDescribe(largeMessage); } - case ADD_MESSAGE: - { + case ADD_MESSAGE: { ServerMessage message = new ServerMessageImpl(rec, 50); message.decode(buffer); return new MessageDescribe(message); } - case ADD_REF: - { + case ADD_REF: { final RefEncoding encoding = new RefEncoding(); encoding.decode(buffer); return new ReferenceDescribe(encoding); } - case ACKNOWLEDGE_REF: - { + case ACKNOWLEDGE_REF: { final RefEncoding encoding = new RefEncoding(); encoding.decode(buffer); return new AckDescribe(encoding); } - case UPDATE_DELIVERY_COUNT: - { + case UPDATE_DELIVERY_COUNT: { DeliveryCountUpdateEncoding updateDeliveryCount = new DeliveryCountUpdateEncoding(); updateDeliveryCount.decode(buffer); return updateDeliveryCount; } - case PAGE_TRANSACTION: - { - if (info.isUpdate) - { + case PAGE_TRANSACTION: { + if (info.isUpdate) { PageUpdateTXEncoding pageUpdate = new PageUpdateTXEncoding(); pageUpdate.decode(buffer); return pageUpdate; } - else - { + else { PageTransactionInfoImpl pageTransactionInfo = new PageTransactionInfoImpl(); pageTransactionInfo.decode(buffer); @@ -572,40 +494,35 @@ public final class DescribeJournal } } - case SET_SCHEDULED_DELIVERY_TIME: - { + case SET_SCHEDULED_DELIVERY_TIME: { ScheduledDeliveryEncoding encoding = new ScheduledDeliveryEncoding(); encoding.decode(buffer); return encoding; } - case DUPLICATE_ID: - { + case DUPLICATE_ID: { DuplicateIDEncoding encoding = new DuplicateIDEncoding(); encoding.decode(buffer); return encoding; } - case HEURISTIC_COMPLETION: - { + case HEURISTIC_COMPLETION: { HeuristicCompletionEncoding encoding = new HeuristicCompletionEncoding(); encoding.decode(buffer); return encoding; } - case ACKNOWLEDGE_CURSOR: - { + case ACKNOWLEDGE_CURSOR: { CursorAckRecordEncoding encoding = new CursorAckRecordEncoding(); encoding.decode(buffer); return encoding; } - case PAGE_CURSOR_COUNTER_VALUE: - { + case PAGE_CURSOR_COUNTER_VALUE: { PageCountRecord encoding = new PageCountRecord(); encoding.decode(buffer); @@ -613,8 +530,7 @@ public final class DescribeJournal return encoding; } - case PAGE_CURSOR_COMPLETE: - { + case PAGE_CURSOR_COMPLETE: { CursorAckRecordEncoding encoding = new PageCompleteCursorAckRecordEncoding(); encoding.decode(buffer); @@ -622,8 +538,7 @@ public final class DescribeJournal return encoding; } - case PAGE_CURSOR_COUNTER_INC: - { + case PAGE_CURSOR_COUNTER_INC: { PageCountRecordInc encoding = new PageCountRecordInc(); encoding.decode(buffer); @@ -631,8 +546,7 @@ public final class DescribeJournal return encoding; } - case PAGE_CURSOR_PENDING_COUNTER: - { + case PAGE_CURSOR_PENDING_COUNTER: { PageCountPendingImpl encoding = new PageCountPendingImpl(); encoding.decode(buffer); encoding.setID(info.id); @@ -662,33 +576,28 @@ public final class DescribeJournal } } - private static final class PageCompleteCursorAckRecordEncoding extends CursorAckRecordEncoding - { + private static final class PageCompleteCursorAckRecordEncoding extends CursorAckRecordEncoding { @Override - public String toString() - { + public String toString() { return "PGComplete [queueID=" + queueID + ", position=" + position + "]"; } } - public static final class MessageDescribe - { - public MessageDescribe(Message msg) - { + public static final class MessageDescribe { + + public MessageDescribe(Message msg) { this.msg = msg; } Message msg; @Override - public String toString() - { + public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(msg.isLargeMessage() ? "LargeMessage(" : "Message("); buffer.append("messageID=" + msg.getMessageID()); - if (msg.getUserID() != null) - { + if (msg.getUserID() != null) { buffer.append(";userMessageID=" + msg.getUserID().toString()); } @@ -697,31 +606,27 @@ public final class DescribeJournal return buffer.toString(); } - public Message getMsg() - { + public Message getMsg() { return msg; } } - public static final class ReferenceDescribe - { + public static final class ReferenceDescribe { + public RefEncoding refEncoding; - public ReferenceDescribe(RefEncoding refEncoding) - { + public ReferenceDescribe(RefEncoding refEncoding) { this.refEncoding = refEncoding; } @Override - public String toString() - { + public String toString() { return "AddRef;" + refEncoding; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((refEncoding == null) ? 0 : refEncoding.hashCode()); @@ -729,17 +634,15 @@ public final class DescribeJournal } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof ReferenceDescribe)) return false; - ReferenceDescribe other = (ReferenceDescribe)obj; - if (refEncoding == null) - { + ReferenceDescribe other = (ReferenceDescribe) obj; + if (refEncoding == null) { if (other.refEncoding != null) return false; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/JournalRecordIds.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/JournalRecordIds.java index 1fd81d56a8..5b1234502b 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/JournalRecordIds.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/JournalRecordIds.java @@ -23,8 +23,8 @@ package org.apache.activemq.artemis.core.persistence.impl.journal; * This is where the definitions will exist and this is what these tests should be using to verify * the IDs. */ -public final class JournalRecordIds -{ +public final class JournalRecordIds { + // grouping journal record type static final byte GROUP_RECORD = 20; @@ -34,6 +34,7 @@ public final class JournalRecordIds /** * Records storing the current recordID number. + * * @see org.apache.activemq.artemis.utils.IDGenerator * @see BatchingIDGenerator */ diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/JournalStorageManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/JournalStorageManager.java index 33a1cbecd0..f1a6e38d83 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/JournalStorageManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/JournalStorageManager.java @@ -139,8 +139,8 @@ import static org.apache.activemq.artemis.core.persistence.impl.journal.JournalR * {@link #startReplication(ReplicationManager, PagingManager, String, boolean)}. *

    */ -public class JournalStorageManager implements StorageManager -{ +public class JournalStorageManager implements StorageManager { + private static final long CHECKPOINT_BATCH_SIZE = Integer.MAX_VALUE; private final Semaphore pageMaxConcurrentIO; @@ -151,19 +151,16 @@ public class JournalStorageManager implements StorageManager private ReplicationManager replicator; - public enum JournalContent - { + public enum JournalContent { BINDINGS((byte) 0), MESSAGES((byte) 1); public final byte typeByte; - JournalContent(byte b) - { + JournalContent(byte b) { typeByte = b; } - public static JournalContent getType(byte type) - { + public static JournalContent getType(byte type) { if (MESSAGES.typeByte == type) return MESSAGES; if (BINDINGS.typeByte == type) @@ -208,46 +205,32 @@ public class JournalStorageManager implements StorageManager private final Configuration config; // Persisted core configuration - private final Map mapPersistedRoles = - new ConcurrentHashMap(); + private final Map mapPersistedRoles = new ConcurrentHashMap(); - private final Map mapPersistedAddressSettings = - new ConcurrentHashMap(); + private final Map mapPersistedAddressSettings = new ConcurrentHashMap(); private final Set largeMessagesToDelete = new HashSet(); - public JournalStorageManager(final Configuration config, final ExecutorFactory executorFactory) - { + public JournalStorageManager(final Configuration config, final ExecutorFactory executorFactory) { this(config, executorFactory, null); } - public JournalStorageManager(final Configuration config, final ExecutorFactory executorFactory, - final IOCriticalErrorListener criticalErrorListener) - { + public JournalStorageManager(final Configuration config, + final ExecutorFactory executorFactory, + final IOCriticalErrorListener criticalErrorListener) { this.executorFactory = executorFactory; this.config = config; executor = executorFactory.getExecutor(); - if (config.getJournalType() != JournalType.NIO && config.getJournalType() != JournalType.ASYNCIO) - { + if (config.getJournalType() != JournalType.NIO && config.getJournalType() != JournalType.ASYNCIO) { throw ActiveMQMessageBundle.BUNDLE.invalidJournal(); } + SequentialFileFactory bindingsFF = new NIOSequentialFileFactory(config.getBindingsLocation(), criticalErrorListener, config.getJournalMaxIO_NIO()); - SequentialFileFactory bindingsFF = new NIOSequentialFileFactory(config.getBindingsLocation(), - criticalErrorListener, - config.getJournalMaxIO_NIO()); - - Journal localBindings = new JournalImpl(1024 * 1024, - 2, - config.getJournalCompactMinFiles(), - config.getJournalCompactPercentage(), - bindingsFF, - "activemq-bindings", - "bindings", - 1); + Journal localBindings = new JournalImpl(1024 * 1024, 2, config.getJournalCompactMinFiles(), config.getJournalCompactPercentage(), bindingsFF, "activemq-bindings", "bindings", 1); bindingsJournal = localBindings; originalBindingsJournal = localBindings; @@ -256,72 +239,45 @@ public class JournalStorageManager implements StorageManager syncTransactional = config.isJournalSyncTransactional(); - if (config.getJournalType() == JournalType.ASYNCIO) - { + if (config.getJournalType() == JournalType.ASYNCIO) { ActiveMQServerLogger.LOGGER.journalUseAIO(); - journalFF = new AIOSequentialFileFactory(config.getJournalLocation(), - config.getJournalBufferSize_AIO(), - config.getJournalBufferTimeout_AIO(), - config.getJournalMaxIO_AIO(), - config.isLogJournalWriteRate(), - criticalErrorListener); + journalFF = new AIOSequentialFileFactory(config.getJournalLocation(), config.getJournalBufferSize_AIO(), config.getJournalBufferTimeout_AIO(), config.getJournalMaxIO_AIO(), config.isLogJournalWriteRate(), criticalErrorListener); } - else if (config.getJournalType() == JournalType.NIO) - { + else if (config.getJournalType() == JournalType.NIO) { ActiveMQServerLogger.LOGGER.journalUseNIO(); - journalFF = new NIOSequentialFileFactory(config.getJournalLocation(), - true, - config.getJournalBufferSize_NIO(), - config.getJournalBufferTimeout_NIO(), - config.getJournalMaxIO_NIO(), - config.isLogJournalWriteRate(), - criticalErrorListener); + journalFF = new NIOSequentialFileFactory(config.getJournalLocation(), true, config.getJournalBufferSize_NIO(), config.getJournalBufferTimeout_NIO(), config.getJournalMaxIO_NIO(), config.isLogJournalWriteRate(), criticalErrorListener); } - else - { + else { throw ActiveMQMessageBundle.BUNDLE.invalidJournalType2(config.getJournalType()); } idGenerator = new BatchingIDGenerator(0, JournalStorageManager.CHECKPOINT_BATCH_SIZE, this); - Journal localMessage = new JournalImpl(config.getJournalFileSize(), - config.getJournalMinFiles(), - config.getJournalCompactMinFiles(), - config.getJournalCompactPercentage(), - journalFF, - "activemq-data", - "amq", - config.getJournalType() == JournalType.ASYNCIO ? config.getJournalMaxIO_AIO() - : config.getJournalMaxIO_NIO()); + Journal localMessage = new JournalImpl(config.getJournalFileSize(), config.getJournalMinFiles(), config.getJournalCompactMinFiles(), config.getJournalCompactPercentage(), journalFF, "activemq-data", "amq", config.getJournalType() == JournalType.ASYNCIO ? config.getJournalMaxIO_AIO() : config.getJournalMaxIO_NIO()); messageJournal = localMessage; originalMessageJournal = localMessage; largeMessagesDirectory = config.getLargeMessagesDirectory(); - largeMessagesFactory = new NIOSequentialFileFactory(config.getLargeMessagesLocation(), false, criticalErrorListener, - 1); + largeMessagesFactory = new NIOSequentialFileFactory(config.getLargeMessagesLocation(), false, criticalErrorListener, 1); perfBlastPages = config.getJournalPerfBlastPages(); - if (config.getPageMaxConcurrentIO() != 1) - { + if (config.getPageMaxConcurrentIO() != 1) { pageMaxConcurrentIO = new Semaphore(config.getPageMaxConcurrentIO()); } - else - { + else { pageMaxConcurrentIO = null; } } - public void clearContext() - { + public void clearContext() { OperationContextImpl.clearContext(); } - public boolean isReplicated() - { + public boolean isReplicated() { return replicator != null; } @@ -345,21 +301,19 @@ public class JournalStorageManager implements StorageManager * @throws ActiveMQException */ @Override - public void startReplication(ReplicationManager replicationManager, PagingManager pagingManager, String nodeID, - final boolean autoFailBack) throws Exception - { - if (!started) - { + public void startReplication(ReplicationManager replicationManager, + PagingManager pagingManager, + String nodeID, + final boolean autoFailBack) throws Exception { + if (!started) { throw new IllegalStateException("JournalStorageManager must be started..."); } assert replicationManager != null; - if (!(messageJournal instanceof JournalImpl) || !(bindingsJournal instanceof JournalImpl)) - { + if (!(messageJournal instanceof JournalImpl) || !(bindingsJournal instanceof JournalImpl)) { throw ActiveMQMessageBundle.BUNDLE.notJournalImpl(); } - // We first do a compact without any locks, to avoid copying unnecessary data over the network. // We do this without holding the storageManager lock, so the journal stays open while compact is being done originalMessageJournal.scheduleCompactAndBlock(-1); @@ -372,12 +326,10 @@ public class JournalStorageManager implements StorageManager // and we send the current messages while more state is coming Map> pendingLargeMessages = null; - try - { + try { Map> pageFilesToSync; storageManagerLock.writeLock().lock(); - try - { + try { if (isReplicated()) throw new ActiveMQIllegalStateException("already replicating"); replicator = replicationManager; @@ -386,37 +338,30 @@ public class JournalStorageManager implements StorageManager originalMessageJournal.synchronizationLock(); originalBindingsJournal.synchronizationLock(); - try - { + try { originalBindingsJournal.replicationSyncPreserveOldFiles(); originalMessageJournal.replicationSyncPreserveOldFiles(); pagingManager.lock(); - try - { + try { pagingManager.disableCleanup(); - messageFiles = - prepareJournalForCopy(originalMessageJournal, JournalContent.MESSAGES, nodeID, autoFailBack); - bindingsFiles = - prepareJournalForCopy(originalBindingsJournal, JournalContent.BINDINGS, nodeID, autoFailBack); + messageFiles = prepareJournalForCopy(originalMessageJournal, JournalContent.MESSAGES, nodeID, autoFailBack); + bindingsFiles = prepareJournalForCopy(originalBindingsJournal, JournalContent.BINDINGS, nodeID, autoFailBack); pageFilesToSync = getPageInformationForSync(pagingManager); pendingLargeMessages = recoverPendingLargeMessages(); } - finally - { + finally { pagingManager.unlock(); } } - finally - { + finally { originalMessageJournal.synchronizationUnlock(); originalBindingsJournal.synchronizationUnlock(); } bindingsJournal = new ReplicatedJournal(((byte) 0), originalBindingsJournal, replicator); messageJournal = new ReplicatedJournal((byte) 1, originalMessageJournal, replicator); } - finally - { + finally { storageManagerLock.writeLock().unlock(); } @@ -428,26 +373,21 @@ public class JournalStorageManager implements StorageManager sendPagesToBackup(pageFilesToSync, pagingManager); storageManagerLock.writeLock().lock(); - try - { - if (replicator != null) - { + try { + if (replicator != null) { replicator.sendSynchronizationDone(nodeID); performCachedLargeMessageDeletes(); } } - finally - { + finally { storageManagerLock.writeLock().unlock(); } } - catch (Exception e) - { + catch (Exception e) { stopReplication(); throw e; } - finally - { + finally { pagingManager.resumeCleanup(); // Re-enable compact and reclaim of journal files originalBindingsJournal.replicationSyncFinished(); @@ -455,17 +395,14 @@ public class JournalStorageManager implements StorageManager } } - public static String md5(File file) - { - try - { + public static String md5(File file) { + try { byte[] buffer = new byte[1 << 4]; MessageDigest md = MessageDigest.getInstance("MD5"); FileInputStream is = new FileInputStream(file); DigestInputStream is2 = new DigestInputStream(is, md); - while (is2.read(buffer) > 0) - { + while (is2.read(buffer) > 0) { continue; } byte[] digest = md.digest(); @@ -473,8 +410,7 @@ public class JournalStorageManager implements StorageManager is2.close(); return Base64.encodeBytes(digest); } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } } @@ -483,21 +419,17 @@ public class JournalStorageManager implements StorageManager * Stops replication by resetting replication-related fields to their 'unreplicated' state. */ @Override - public void stopReplication() - { + public void stopReplication() { storageManagerLock.writeLock().lock(); - try - { + try { if (replicator == null) return; bindingsJournal = originalBindingsJournal; messageJournal = originalMessageJournal; - try - { + try { replicator.stop(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorStoppingReplicationManager(e); } replicator = null; @@ -506,8 +438,7 @@ public class JournalStorageManager implements StorageManager // This method should not be called under normal circumstances performCachedLargeMessageDeletes(); } - finally - { + finally { storageManagerLock.writeLock().unlock(); } } @@ -515,21 +446,16 @@ public class JournalStorageManager implements StorageManager /** * Assumption is that this is only called with a writeLock on the StorageManager. */ - private void performCachedLargeMessageDeletes() - { - for (Long largeMsgId : largeMessagesToDelete) - { + private void performCachedLargeMessageDeletes() { + for (Long largeMsgId : largeMessagesToDelete) { SequentialFile msg = createFileForLargeMessage(largeMsgId, LargeMessageExtension.DURABLE); - try - { + try { msg.delete(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.journalErrorDeletingMessage(e, largeMsgId); } - if (replicator != null) - { + if (replicator != null) { replicator.largeMessageDelete(largeMsgId); } } @@ -540,10 +466,9 @@ public class JournalStorageManager implements StorageManager * @param pageFilesToSync * @throws Exception */ - private void sendPagesToBackup(Map> pageFilesToSync, PagingManager manager) throws Exception - { - for (Entry> entry : pageFilesToSync.entrySet()) - { + private void sendPagesToBackup(Map> pageFilesToSync, + PagingManager manager) throws Exception { + for (Entry> entry : pageFilesToSync.entrySet()) { if (!started) return; PagingStore store = manager.getPageStore(entry.getKey()); @@ -556,11 +481,9 @@ public class JournalStorageManager implements StorageManager * @return * @throws Exception */ - private Map> getPageInformationForSync(PagingManager pagingManager) throws Exception - { + private Map> getPageInformationForSync(PagingManager pagingManager) throws Exception { Map> info = new HashMap>(); - for (SimpleString storeName : pagingManager.getStoreNames()) - { + for (SimpleString storeName : pagingManager.getStoreNames()) { PagingStore store = pagingManager.getPageStore(storeName); info.put(storeName, store.getCurrentIds()); store.forceAnotherPage(); @@ -568,11 +491,9 @@ public class JournalStorageManager implements StorageManager return info; } - private void sendLargeMessageFiles(final Map> pendingLargeMessages) throws Exception - { + private void sendLargeMessageFiles(final Map> pendingLargeMessages) throws Exception { Iterator>> iter = pendingLargeMessages.entrySet().iterator(); - while (started && iter.hasNext()) - { + while (started && iter.hasNext()) { Map.Entry> entry = iter.next(); String fileName = entry.getValue().getA(); final long id = entry.getKey(); @@ -584,8 +505,7 @@ public class JournalStorageManager implements StorageManager } } - private long getLargeMessageIdFromFilename(String filename) - { + private long getLargeMessageIdFromFilename(String filename) { return Long.parseLong(filename.split("\\.")[0]); } @@ -599,19 +519,16 @@ public class JournalStorageManager implements StorageManager * * @throws Exception */ - private Map> recoverPendingLargeMessages() throws Exception - { + private Map> recoverPendingLargeMessages() throws Exception { Map> largeMessages = new HashMap>(); // only send durable messages... // listFiles append a "." to anything... List filenames = largeMessagesFactory.listFiles("msg"); List idList = new ArrayList(); - for (String filename : filenames) - { + for (String filename : filenames) { Long id = getLargeMessageIdFromFilename(filename); - if (!largeMessagesToDelete.contains(id)) - { + if (!largeMessagesToDelete.contains(id)) { idList.add(id); SequentialFile seqFile = largeMessagesFactory.createSequentialFile(filename); long size = seqFile.size(); @@ -625,31 +542,27 @@ public class JournalStorageManager implements StorageManager /** * Send an entire journal file to a replicating backup server. */ - private void sendJournalFile(JournalFile[] journalFiles, JournalContent type) throws Exception - { - for (JournalFile jf : journalFiles) - { + private void sendJournalFile(JournalFile[] journalFiles, JournalContent type) throws Exception { + for (JournalFile jf : journalFiles) { if (!started) return; replicator.syncJournalFile(jf, type); } } - private JournalFile[] prepareJournalForCopy(Journal journal, JournalContent contentType, String nodeID, - boolean autoFailBack) throws Exception - { + private JournalFile[] prepareJournalForCopy(Journal journal, + JournalContent contentType, + String nodeID, + boolean autoFailBack) throws Exception { journal.forceMoveNextFile(); JournalFile[] datafiles = journal.getDataFiles(); replicator.sendStartSyncMessage(datafiles, contentType, nodeID, autoFailBack); return datafiles; } - @Override - public final void waitOnOperations() throws Exception - { - if (!started) - { + public final void waitOnOperations() throws Exception { + if (!started) { ActiveMQServerLogger.LOGGER.serverIsStopped(); throw new IllegalStateException("Server is stopped"); } @@ -657,10 +570,8 @@ public class JournalStorageManager implements StorageManager } @Override - public final boolean waitOnOperations(final long timeout) throws Exception - { - if (!started) - { + public final boolean waitOnOperations(final long timeout) throws Exception { + if (!started) { ActiveMQServerLogger.LOGGER.serverIsStopped(); throw new IllegalStateException("Server is stopped"); } @@ -668,46 +579,36 @@ public class JournalStorageManager implements StorageManager } @Override - public void pageClosed(final SimpleString storeName, final int pageNumber) - { - if (isReplicated()) - { + public void pageClosed(final SimpleString storeName, final int pageNumber) { + if (isReplicated()) { readLock(); - try - { + try { if (isReplicated()) replicator.pageClosed(storeName, pageNumber); } - finally - { + finally { readUnLock(); } } } @Override - public void pageDeleted(final SimpleString storeName, final int pageNumber) - { - if (isReplicated()) - { + public void pageDeleted(final SimpleString storeName, final int pageNumber) { + if (isReplicated()) { readLock(); - try - { + try { if (isReplicated()) replicator.pageDeleted(storeName, pageNumber); } - finally - { + finally { readUnLock(); } } } @Override - public void pageWrite(final PagedMessage message, final int pageNumber) - { - if (isReplicated()) - { + public void pageWrite(final PagedMessage message, final int pageNumber) { + if (isReplicated()) { // Note: (https://issues.jboss.org/browse/HORNETQ-1059) // We have to replicate durable and non-durable messages on paging // since acknowledgments are written using the page-position. @@ -715,91 +616,74 @@ public class JournalStorageManager implements StorageManager // The ACKs would be done to wrong positions, and the backup would be a mess readLock(); - try - { + try { if (isReplicated()) replicator.pageWrite(message, pageNumber); } - finally - { + finally { readUnLock(); } } } - public OperationContext getContext() - { + public OperationContext getContext() { return OperationContextImpl.getContext(executorFactory); } - public void setContext(final OperationContext context) - { + public void setContext(final OperationContext context) { OperationContextImpl.setContext(context); } - public Executor getSingleThreadExecutor() - { + public Executor getSingleThreadExecutor() { return singleThreadExecutor; } - public OperationContext newSingleThreadContext() - { + public OperationContext newSingleThreadContext() { return newContext(singleThreadExecutor); } - public OperationContext newContext(final Executor executor1) - { + public OperationContext newContext(final Executor executor1) { return new OperationContextImpl(executor1); } - public void afterCompleteOperations(final IOCallback run) - { + public void afterCompleteOperations(final IOCallback run) { getContext().executeOnCompletion(run); } - public long generateID() - { + public long generateID() { return idGenerator.generateID(); } - public long getCurrentID() - { + public long getCurrentID() { return idGenerator.getCurrentID(); } - public LargeServerMessage createLargeMessage() - { + public LargeServerMessage createLargeMessage() { return new LargeServerMessageImpl(this); } public final void addBytesToLargeMessage(final SequentialFile file, - final long messageId, final byte[] bytes) throws Exception - { + final long messageId, + final byte[] bytes) throws Exception { readLock(); - try - { + try { file.position(file.size()); file.writeDirect(ByteBuffer.wrap(bytes), false); - if (isReplicated()) - { + if (isReplicated()) { replicator.largeMessageWrite(messageId, bytes); } } - finally - { + finally { readUnLock(); } } - public LargeServerMessage createLargeMessage(final long id, final MessageInternal message) throws Exception - { + public LargeServerMessage createLargeMessage(final long id, final MessageInternal message) throws Exception { readLock(); - try - { - if (isReplicated()) - { + try { + if (isReplicated()) { replicator.largeMessageBegin(id); } @@ -809,8 +693,7 @@ public class JournalStorageManager implements StorageManager largeMessage.setMessageID(id); - if (largeMessage.isDurable()) - { + if (largeMessage.isDurable()) { // We store a marker on the journal that the large file is pending long pendingRecordID = storePendingLargeMessage(id); @@ -819,46 +702,34 @@ public class JournalStorageManager implements StorageManager return largeMessage; } - finally - { + finally { readUnLock(); } } // Non transactional operations - public long storePendingLargeMessage(final long messageID) throws Exception - { + public long storePendingLargeMessage(final long messageID) throws Exception { readLock(); - try - { + try { long recordID = generateID(); - messageJournal.appendAddRecord(recordID, JournalRecordIds.ADD_LARGE_MESSAGE_PENDING, - new PendingLargeMessageEncoding(messageID), - true, - getContext(true)); + messageJournal.appendAddRecord(recordID, JournalRecordIds.ADD_LARGE_MESSAGE_PENDING, new PendingLargeMessageEncoding(messageID), true, getContext(true)); return recordID; } - finally - { + finally { readUnLock(); } } - public void confirmPendingLargeMessageTX(final Transaction tx, long messageID, long recordID) throws Exception - { + public void confirmPendingLargeMessageTX(final Transaction tx, long messageID, long recordID) throws Exception { readLock(); - try - { + try { installLargeMessageConfirmationOnTX(tx, recordID); - messageJournal.appendDeleteRecordTransactional(tx.getID(), recordID, - new DeleteEncoding(JournalRecordIds.ADD_LARGE_MESSAGE_PENDING, - messageID)); + messageJournal.appendDeleteRecordTransactional(tx.getID(), recordID, new DeleteEncoding(JournalRecordIds.ADD_LARGE_MESSAGE_PENDING, messageID)); } - finally - { + finally { readUnLock(); } } @@ -866,439 +737,315 @@ public class JournalStorageManager implements StorageManager /** * We don't need messageID now but we are likely to need it we ever decide to support a database */ - public void confirmPendingLargeMessage(long recordID) throws Exception - { + public void confirmPendingLargeMessage(long recordID) throws Exception { readLock(); - try - { + try { messageJournal.appendDeleteRecord(recordID, true, getContext()); } - finally - { + finally { readUnLock(); } } - public void storeMessage(final ServerMessage message) throws Exception - { - if (message.getMessageID() <= 0) - { + public void storeMessage(final ServerMessage message) throws Exception { + if (message.getMessageID() <= 0) { // Sanity check only... this shouldn't happen unless there is a bug throw ActiveMQMessageBundle.BUNDLE.messageIdNotAssigned(); } readLock(); - try - { + try { // Note that we don't sync, the add reference that comes immediately after will sync if // appropriate - if (message.isLargeMessage()) - { - messageJournal.appendAddRecord(message.getMessageID(), JournalRecordIds.ADD_LARGE_MESSAGE, - new LargeMessageEncoding((LargeServerMessage) message), false, - getContext(false)); + if (message.isLargeMessage()) { + messageJournal.appendAddRecord(message.getMessageID(), JournalRecordIds.ADD_LARGE_MESSAGE, new LargeMessageEncoding((LargeServerMessage) message), false, getContext(false)); } - else - { - messageJournal.appendAddRecord(message.getMessageID(), JournalRecordIds.ADD_MESSAGE, message, false, - getContext(false)); + else { + messageJournal.appendAddRecord(message.getMessageID(), JournalRecordIds.ADD_MESSAGE, message, false, getContext(false)); } } - finally - { + finally { readUnLock(); } } - public void storeReference(final long queueID, final long messageID, final boolean last) throws Exception - { + public void storeReference(final long queueID, final long messageID, final boolean last) throws Exception { readLock(); - try - { - messageJournal.appendUpdateRecord(messageID, JournalRecordIds.ADD_REF, new RefEncoding(queueID), last && - syncNonTransactional, getContext(last && syncNonTransactional)); + try { + messageJournal.appendUpdateRecord(messageID, JournalRecordIds.ADD_REF, new RefEncoding(queueID), last && syncNonTransactional, getContext(last && syncNonTransactional)); } - finally - { + finally { readUnLock(); } } @Override - public void readLock() - { + public void readLock() { storageManagerLock.readLock().lock(); } @Override - public void readUnLock() - { + public void readUnLock() { storageManagerLock.readLock().unlock(); } - public void storeAcknowledge(final long queueID, final long messageID) throws Exception - { + public void storeAcknowledge(final long queueID, final long messageID) throws Exception { readLock(); - try - { - messageJournal.appendUpdateRecord(messageID, JournalRecordIds.ACKNOWLEDGE_REF, new RefEncoding(queueID), - syncNonTransactional, getContext(syncNonTransactional)); + try { + messageJournal.appendUpdateRecord(messageID, JournalRecordIds.ACKNOWLEDGE_REF, new RefEncoding(queueID), syncNonTransactional, getContext(syncNonTransactional)); } - finally - { + finally { readUnLock(); } } - public void storeCursorAcknowledge(long queueID, PagePosition position) throws Exception - { + public void storeCursorAcknowledge(long queueID, PagePosition position) throws Exception { readLock(); - try - { + try { long ackID = idGenerator.generateID(); position.setRecordID(ackID); - messageJournal.appendAddRecord(ackID, - JournalRecordIds.ACKNOWLEDGE_CURSOR, - new CursorAckRecordEncoding(queueID, position), - syncNonTransactional, - getContext(syncNonTransactional)); + messageJournal.appendAddRecord(ackID, JournalRecordIds.ACKNOWLEDGE_CURSOR, new CursorAckRecordEncoding(queueID, position), syncNonTransactional, getContext(syncNonTransactional)); } - finally - { + finally { readUnLock(); } } - public void deleteMessage(final long messageID) throws Exception - { + public void deleteMessage(final long messageID) throws Exception { readLock(); - try - { + try { // Messages are deleted on postACK, one after another. // If these deletes are synchronized, we would build up messages on the Executor // increasing chances of losing deletes. // The StorageManager should verify messages without references messageJournal.appendDeleteRecord(messageID, false, getContext(false)); } - finally - { + finally { readUnLock(); } } - public void updateScheduledDeliveryTime(final MessageReference ref) throws Exception - { - ScheduledDeliveryEncoding encoding = new ScheduledDeliveryEncoding(ref.getScheduledDeliveryTime(), ref.getQueue() - .getID()); + public void updateScheduledDeliveryTime(final MessageReference ref) throws Exception { + ScheduledDeliveryEncoding encoding = new ScheduledDeliveryEncoding(ref.getScheduledDeliveryTime(), ref.getQueue().getID()); readLock(); - try - { - messageJournal.appendUpdateRecord(ref.getMessage().getMessageID(), - JournalRecordIds.SET_SCHEDULED_DELIVERY_TIME, - encoding, - syncNonTransactional, - getContext(syncNonTransactional)); + try { + messageJournal.appendUpdateRecord(ref.getMessage().getMessageID(), JournalRecordIds.SET_SCHEDULED_DELIVERY_TIME, encoding, syncNonTransactional, getContext(syncNonTransactional)); } - finally - { + finally { readUnLock(); } } - public void storeDuplicateID(final SimpleString address, final byte[] duplID, final long recordID) throws Exception - { + public void storeDuplicateID(final SimpleString address, final byte[] duplID, final long recordID) throws Exception { readLock(); - try - { + try { DuplicateIDEncoding encoding = new DuplicateIDEncoding(address, duplID); - messageJournal.appendAddRecord(recordID, - JournalRecordIds.DUPLICATE_ID, - encoding, - syncNonTransactional, - getContext(syncNonTransactional)); + messageJournal.appendAddRecord(recordID, JournalRecordIds.DUPLICATE_ID, encoding, syncNonTransactional, getContext(syncNonTransactional)); } - finally - { + finally { readUnLock(); } } - public void deleteDuplicateID(final long recordID) throws Exception - { + public void deleteDuplicateID(final long recordID) throws Exception { readLock(); - try - { + try { messageJournal.appendDeleteRecord(recordID, syncNonTransactional, getContext(syncNonTransactional)); } - finally - { + finally { readUnLock(); } } // Transactional operations - public void storeMessageTransactional(final long txID, final ServerMessage message) throws Exception - { - if (message.getMessageID() <= 0) - { + public void storeMessageTransactional(final long txID, final ServerMessage message) throws Exception { + if (message.getMessageID() <= 0) { throw ActiveMQMessageBundle.BUNDLE.messageIdNotAssigned(); } readLock(); - try - { - if (message.isLargeMessage()) - { - messageJournal.appendAddRecordTransactional(txID, message.getMessageID(), - JournalRecordIds.ADD_LARGE_MESSAGE, - new LargeMessageEncoding(((LargeServerMessage) message))); + try { + if (message.isLargeMessage()) { + messageJournal.appendAddRecordTransactional(txID, message.getMessageID(), JournalRecordIds.ADD_LARGE_MESSAGE, new LargeMessageEncoding(((LargeServerMessage) message))); } - else - { - messageJournal.appendAddRecordTransactional(txID, message.getMessageID(), - JournalRecordIds.ADD_MESSAGE, - message); + else { + messageJournal.appendAddRecordTransactional(txID, message.getMessageID(), JournalRecordIds.ADD_MESSAGE, message); } } - finally - { + finally { readUnLock(); } } - public void storePageTransaction(final long txID, final PageTransactionInfo pageTransaction) throws Exception - { + public void storePageTransaction(final long txID, final PageTransactionInfo pageTransaction) throws Exception { readLock(); - try - { + try { pageTransaction.setRecordID(generateID()); - messageJournal.appendAddRecordTransactional(txID, pageTransaction.getRecordID(), - JournalRecordIds.PAGE_TRANSACTION, pageTransaction); + messageJournal.appendAddRecordTransactional(txID, pageTransaction.getRecordID(), JournalRecordIds.PAGE_TRANSACTION, pageTransaction); } - finally - { + finally { readUnLock(); } } - public void updatePageTransaction(final long txID, final PageTransactionInfo pageTransaction, final int depages) throws Exception - { + public void updatePageTransaction(final long txID, + final PageTransactionInfo pageTransaction, + final int depages) throws Exception { readLock(); - try - { - messageJournal.appendUpdateRecordTransactional(txID, pageTransaction.getRecordID(), - JournalRecordIds.PAGE_TRANSACTION, - new PageUpdateTXEncoding(pageTransaction.getTransactionID(), - depages)); + try { + messageJournal.appendUpdateRecordTransactional(txID, pageTransaction.getRecordID(), JournalRecordIds.PAGE_TRANSACTION, new PageUpdateTXEncoding(pageTransaction.getTransactionID(), depages)); } - finally - { + finally { readUnLock(); } } - - public void updatePageTransaction(final PageTransactionInfo pageTransaction, final int depages) throws Exception - { + public void updatePageTransaction(final PageTransactionInfo pageTransaction, final int depages) throws Exception { readLock(); - try - { - messageJournal.appendUpdateRecord(pageTransaction.getRecordID(), JournalRecordIds.PAGE_TRANSACTION, - new PageUpdateTXEncoding(pageTransaction.getTransactionID(), depages), - syncNonTransactional, getContext(syncNonTransactional)); + try { + messageJournal.appendUpdateRecord(pageTransaction.getRecordID(), JournalRecordIds.PAGE_TRANSACTION, new PageUpdateTXEncoding(pageTransaction.getTransactionID(), depages), syncNonTransactional, getContext(syncNonTransactional)); } - finally - { + finally { readUnLock(); } } - public void storeReferenceTransactional(final long txID, final long queueID, final long messageID) throws Exception - { + public void storeReferenceTransactional(final long txID, final long queueID, final long messageID) throws Exception { readLock(); - try - { - messageJournal.appendUpdateRecordTransactional(txID, messageID, JournalRecordIds.ADD_REF, - new RefEncoding(queueID)); + try { + messageJournal.appendUpdateRecordTransactional(txID, messageID, JournalRecordIds.ADD_REF, new RefEncoding(queueID)); } - finally - { + finally { readUnLock(); } } - public void storeAcknowledgeTransactional(final long txID, final long queueID, final long messageID) throws Exception - { + public void storeAcknowledgeTransactional(final long txID, + final long queueID, + final long messageID) throws Exception { readLock(); - try - { - messageJournal.appendUpdateRecordTransactional(txID, messageID, JournalRecordIds.ACKNOWLEDGE_REF, - new RefEncoding(queueID)); + try { + messageJournal.appendUpdateRecordTransactional(txID, messageID, JournalRecordIds.ACKNOWLEDGE_REF, new RefEncoding(queueID)); } - finally - { + finally { readUnLock(); } } - public void storeCursorAcknowledgeTransactional(long txID, long queueID, PagePosition position) throws Exception - { + public void storeCursorAcknowledgeTransactional(long txID, long queueID, PagePosition position) throws Exception { readLock(); - try - { + try { long ackID = idGenerator.generateID(); position.setRecordID(ackID); - messageJournal.appendAddRecordTransactional(txID, - ackID, - JournalRecordIds.ACKNOWLEDGE_CURSOR, - new CursorAckRecordEncoding(queueID, position)); + messageJournal.appendAddRecordTransactional(txID, ackID, JournalRecordIds.ACKNOWLEDGE_CURSOR, new CursorAckRecordEncoding(queueID, position)); } - finally - { + finally { readUnLock(); } } - public void storePageCompleteTransactional(long txID, long queueID, PagePosition position) throws Exception - { + public void storePageCompleteTransactional(long txID, long queueID, PagePosition position) throws Exception { long recordID = idGenerator.generateID(); position.setRecordID(recordID); - messageJournal.appendAddRecordTransactional(txID, - recordID, - JournalRecordIds.PAGE_CURSOR_COMPLETE, - new CursorAckRecordEncoding(queueID, position)); + messageJournal.appendAddRecordTransactional(txID, recordID, JournalRecordIds.PAGE_CURSOR_COMPLETE, new CursorAckRecordEncoding(queueID, position)); } - public void deletePageComplete(long ackID) throws Exception - { + public void deletePageComplete(long ackID) throws Exception { messageJournal.appendDeleteRecord(ackID, false); } - public void deleteCursorAcknowledgeTransactional(long txID, long ackID) throws Exception - { + public void deleteCursorAcknowledgeTransactional(long txID, long ackID) throws Exception { readLock(); - try - { + try { messageJournal.appendDeleteRecordTransactional(txID, ackID); } - finally - { + finally { readUnLock(); } } - public void deleteCursorAcknowledge(long ackID) throws Exception - { + public void deleteCursorAcknowledge(long ackID) throws Exception { messageJournal.appendDeleteRecord(ackID, false); } - public long storeHeuristicCompletion(final Xid xid, final boolean isCommit) throws Exception - { + public long storeHeuristicCompletion(final Xid xid, final boolean isCommit) throws Exception { readLock(); - try - { + try { long id = generateID(); - messageJournal.appendAddRecord(id, - JournalRecordIds.HEURISTIC_COMPLETION, - new HeuristicCompletionEncoding(xid, isCommit), - true, - getContext(true)); + messageJournal.appendAddRecord(id, JournalRecordIds.HEURISTIC_COMPLETION, new HeuristicCompletionEncoding(xid, isCommit), true, getContext(true)); return id; } - finally - { + finally { readUnLock(); } } - public void deleteHeuristicCompletion(final long id) throws Exception - { + public void deleteHeuristicCompletion(final long id) throws Exception { readLock(); - try - { + try { messageJournal.appendDeleteRecord(id, true, getContext(true)); } - finally - { + finally { readUnLock(); } } - public void deletePageTransactional(final long recordID) throws Exception - { + public void deletePageTransactional(final long recordID) throws Exception { readLock(); - try - { + try { messageJournal.appendDeleteRecord(recordID, false); } - finally - { + finally { readUnLock(); } } - public void updateScheduledDeliveryTimeTransactional(final long txID, final MessageReference ref) throws Exception - { - ScheduledDeliveryEncoding encoding = new ScheduledDeliveryEncoding(ref.getScheduledDeliveryTime(), ref.getQueue() - .getID()); + public void updateScheduledDeliveryTimeTransactional(final long txID, final MessageReference ref) throws Exception { + ScheduledDeliveryEncoding encoding = new ScheduledDeliveryEncoding(ref.getScheduledDeliveryTime(), ref.getQueue().getID()); readLock(); - try - { + try { - messageJournal.appendUpdateRecordTransactional(txID, - ref.getMessage().getMessageID(), - JournalRecordIds.SET_SCHEDULED_DELIVERY_TIME, - encoding); + messageJournal.appendUpdateRecordTransactional(txID, ref.getMessage().getMessageID(), JournalRecordIds.SET_SCHEDULED_DELIVERY_TIME, encoding); } - finally - { + finally { readUnLock(); } } - public void prepare(final long txID, final Xid xid) throws Exception - { + public void prepare(final long txID, final Xid xid) throws Exception { readLock(); - try - { + try { messageJournal.appendPrepareRecord(txID, new XidEncoding(xid), syncTransactional, getContext(syncTransactional)); } - finally - { + finally { readUnLock(); } } - public void commit(final long txID) throws Exception - { + public void commit(final long txID) throws Exception { commit(txID, true); } - public void commitBindings(final long txID) throws Exception - { + public void commitBindings(final long txID) throws Exception { bindingsJournal.appendCommitRecord(txID, true); } - public void rollbackBindings(final long txID) throws Exception - { + public void rollbackBindings(final long txID) throws Exception { // no need to sync, it's going away anyways bindingsJournal.appendRollbackRecord(txID, false); } - public void commit(final long txID, final boolean lineUpContext) throws Exception - { + public void commit(final long txID, final boolean lineUpContext) throws Exception { readLock(); - try - { + try { messageJournal.appendCommitRecord(txID, syncTransactional, getContext(syncTransactional), lineUpContext); - if (!lineUpContext && !syncTransactional) - { + if (!lineUpContext && !syncTransactional) { /** * If {@code lineUpContext == false}, it means that we have previously lined up a * context somewhere else (specifically see @{link TransactionImpl#asyncAppendCommit}), @@ -1309,40 +1056,32 @@ public class JournalStorageManager implements StorageManager getContext(true).done(); } } - finally - { + finally { readUnLock(); } } - public void rollback(final long txID) throws Exception - { + public void rollback(final long txID) throws Exception { readLock(); - try - { + try { messageJournal.appendRollbackRecord(txID, syncTransactional, getContext(syncTransactional)); } - finally - { + finally { readUnLock(); } } - public void storeDuplicateIDTransactional(final long txID, final SimpleString address, final byte[] duplID, - final long recordID) throws Exception - { + final long recordID) throws Exception { DuplicateIDEncoding encoding = new DuplicateIDEncoding(address, duplID); readLock(); - try - { + try { messageJournal.appendAddRecordTransactional(txID, recordID, JournalRecordIds.DUPLICATE_ID, encoding); } - finally - { + finally { readUnLock(); } } @@ -1350,170 +1089,131 @@ public class JournalStorageManager implements StorageManager public void updateDuplicateIDTransactional(final long txID, final SimpleString address, final byte[] duplID, - final long recordID) throws Exception - { + final long recordID) throws Exception { DuplicateIDEncoding encoding = new DuplicateIDEncoding(address, duplID); readLock(); - try - { + try { messageJournal.appendUpdateRecordTransactional(txID, recordID, JournalRecordIds.DUPLICATE_ID, encoding); } - finally - { + finally { readUnLock(); } } - public void deleteDuplicateIDTransactional(final long txID, final long recordID) throws Exception - { + public void deleteDuplicateIDTransactional(final long txID, final long recordID) throws Exception { readLock(); - try - { + try { messageJournal.appendDeleteRecordTransactional(txID, recordID); } - finally - { + finally { readUnLock(); } } // Other operations - public void updateDeliveryCount(final MessageReference ref) throws Exception - { + public void updateDeliveryCount(final MessageReference ref) throws Exception { // no need to store if it's the same value // otherwise the journal will get OME in case of lots of redeliveries - if (ref.getDeliveryCount() == ref.getPersistedCount()) - { + if (ref.getDeliveryCount() == ref.getPersistedCount()) { return; } ref.setPersistedCount(ref.getDeliveryCount()); - DeliveryCountUpdateEncoding updateInfo = - new DeliveryCountUpdateEncoding(ref.getQueue().getID(), ref.getDeliveryCount()); + DeliveryCountUpdateEncoding updateInfo = new DeliveryCountUpdateEncoding(ref.getQueue().getID(), ref.getDeliveryCount()); readLock(); - try - { - messageJournal.appendUpdateRecord(ref.getMessage().getMessageID(), - JournalRecordIds.UPDATE_DELIVERY_COUNT, - updateInfo, - syncNonTransactional, getContext(syncNonTransactional)); + try { + messageJournal.appendUpdateRecord(ref.getMessage().getMessageID(), JournalRecordIds.UPDATE_DELIVERY_COUNT, updateInfo, syncNonTransactional, getContext(syncNonTransactional)); } - finally - { + finally { readUnLock(); } } - public void storeAddressSetting(PersistedAddressSetting addressSetting) throws Exception - { + public void storeAddressSetting(PersistedAddressSetting addressSetting) throws Exception { deleteAddressSetting(addressSetting.getAddressMatch()); readLock(); - try - { + try { long id = idGenerator.generateID(); addressSetting.setStoreId(id); bindingsJournal.appendAddRecord(id, JournalRecordIds.ADDRESS_SETTING_RECORD, addressSetting, true); mapPersistedAddressSettings.put(addressSetting.getAddressMatch(), addressSetting); } - finally - { + finally { readUnLock(); } } - public List recoverAddressSettings() throws Exception - { + public List recoverAddressSettings() throws Exception { ArrayList list = new ArrayList(mapPersistedAddressSettings.values()); return list; } - public List recoverPersistedRoles() throws Exception - { + public List recoverPersistedRoles() throws Exception { ArrayList list = new ArrayList(mapPersistedRoles.values()); return list; } - - public void storeSecurityRoles(PersistedRoles persistedRoles) throws Exception - { + public void storeSecurityRoles(PersistedRoles persistedRoles) throws Exception { deleteSecurityRoles(persistedRoles.getAddressMatch()); readLock(); - try - { + try { final long id = idGenerator.generateID(); persistedRoles.setStoreId(id); bindingsJournal.appendAddRecord(id, JournalRecordIds.SECURITY_RECORD, persistedRoles, true); mapPersistedRoles.put(persistedRoles.getAddressMatch(), persistedRoles); } - finally - { + finally { readUnLock(); } } @Override - public final void storeID(final long journalID, final long id) throws Exception - { + public final void storeID(final long journalID, final long id) throws Exception { readLock(); - try - { - bindingsJournal.appendAddRecord(journalID, JournalRecordIds.ID_COUNTER_RECORD, - BatchingIDGenerator.createIDEncodingSupport(id), true); + try { + bindingsJournal.appendAddRecord(journalID, JournalRecordIds.ID_COUNTER_RECORD, BatchingIDGenerator.createIDEncodingSupport(id), true); } - finally - { + finally { readUnLock(); } } @Override - public void deleteID(long journalD) throws Exception - { + public void deleteID(long journalD) throws Exception { readLock(); - try - { + try { bindingsJournal.appendDeleteRecord(journalD, false); } - finally - { + finally { readUnLock(); } } - - public void deleteAddressSetting(SimpleString addressMatch) throws Exception - { + public void deleteAddressSetting(SimpleString addressMatch) throws Exception { PersistedAddressSetting oldSetting = mapPersistedAddressSettings.remove(addressMatch); - if (oldSetting != null) - { + if (oldSetting != null) { readLock(); - try - { + try { bindingsJournal.appendDeleteRecord(oldSetting.getStoreId(), false); } - finally - { + finally { readUnLock(); } } } - public void deleteSecurityRoles(SimpleString addressMatch) throws Exception - { + public void deleteSecurityRoles(SimpleString addressMatch) throws Exception { PersistedRoles oldRoles = mapPersistedRoles.remove(addressMatch); - if (oldRoles != null) - { + if (oldRoles != null) { readLock(); - try - { + try { bindingsJournal.appendDeleteRecord(oldRoles.getStoreId(), false); } - finally - { + finally { readUnLock(); } } @@ -1527,20 +1227,16 @@ public class JournalStorageManager implements StorageManager final Map>> duplicateIDMap, final Set> pendingLargeMessages, List pendingNonTXPageCounter, - final JournalLoader journalLoader) throws Exception - { + final JournalLoader journalLoader) throws Exception { List records = new ArrayList(); List preparedTransactions = new ArrayList(); Map messages = new HashMap(); readLock(); - try - { + try { - JournalLoadInformation info = messageJournal.load(records, - preparedTransactions, - new LargeMessageTXFailureCallback(messages)); + JournalLoadInformation info = messageJournal.load(records, preparedTransactions, new LargeMessageTXFailureCallback(messages)); ArrayList largeMessages = new ArrayList(); @@ -1550,11 +1246,9 @@ public class JournalStorageManager implements StorageManager final int totalSize = records.size(); - for (int reccount = 0; reccount < totalSize; reccount++) - { + for (int reccount = 0; reccount < totalSize; reccount++) { // It will show log.info only with large journals (more than 1 million records) - if (reccount > 0 && reccount % 1000000 == 0) - { + if (reccount > 0 && reccount % 1000000 == 0) { long percent = (long) ((((double) reccount) / ((double) totalSize)) * 100f); ActiveMQServerLogger.LOGGER.percentLoaded(percent); @@ -1567,23 +1261,19 @@ public class JournalStorageManager implements StorageManager byte recordType = record.getUserRecordType(); - switch (recordType) - { - case JournalRecordIds.ADD_LARGE_MESSAGE_PENDING: - { + switch (recordType) { + case JournalRecordIds.ADD_LARGE_MESSAGE_PENDING: { PendingLargeMessageEncoding pending = new PendingLargeMessageEncoding(); pending.decode(buff); - if (pendingLargeMessages != null) - { + if (pendingLargeMessages != null) { // it could be null on tests, and we don't need anything on that case pendingLargeMessages.add(new Pair(record.id, pending.largeMessageID)); } break; } - case JournalRecordIds.ADD_LARGE_MESSAGE: - { + case JournalRecordIds.ADD_LARGE_MESSAGE: { LargeServerMessage largeMessage = parseLargeMessage(messages, buff); messages.put(record.id, largeMessage); @@ -1592,8 +1282,7 @@ public class JournalStorageManager implements StorageManager break; } - case JournalRecordIds.ADD_MESSAGE: - { + case JournalRecordIds.ADD_MESSAGE: { ServerMessage message = new ServerMessageImpl(record.id, 50); message.decode(buff); @@ -1602,8 +1291,7 @@ public class JournalStorageManager implements StorageManager break; } - case JournalRecordIds.ADD_REF: - { + case JournalRecordIds.ADD_REF: { long messageID = record.id; RefEncoding encoding = new RefEncoding(); @@ -1612,8 +1300,7 @@ public class JournalStorageManager implements StorageManager Map queueMessages = queueMap.get(encoding.queueID); - if (queueMessages == null) - { + if (queueMessages == null) { queueMessages = new LinkedHashMap(); queueMap.put(encoding.queueID, queueMessages); @@ -1621,19 +1308,16 @@ public class JournalStorageManager implements StorageManager ServerMessage message = messages.get(messageID); - if (message == null) - { + if (message == null) { ActiveMQServerLogger.LOGGER.cannotFindMessage(record.id); } - else - { + else { queueMessages.put(messageID, new AddMessageRecord(message)); } break; } - case JournalRecordIds.ACKNOWLEDGE_REF: - { + case JournalRecordIds.ACKNOWLEDGE_REF: { long messageID = record.id; RefEncoding encoding = new RefEncoding(); @@ -1642,24 +1326,20 @@ public class JournalStorageManager implements StorageManager Map queueMessages = queueMap.get(encoding.queueID); - if (queueMessages == null) - { + if (queueMessages == null) { ActiveMQServerLogger.LOGGER.journalCannotFindQueue(encoding.queueID, messageID); } - else - { + else { AddMessageRecord rec = queueMessages.remove(messageID); - if (rec == null) - { + if (rec == null) { ActiveMQServerLogger.LOGGER.cannotFindMessage(messageID); } } break; } - case JournalRecordIds.UPDATE_DELIVERY_COUNT: - { + case JournalRecordIds.UPDATE_DELIVERY_COUNT: { long messageID = record.id; DeliveryCountUpdateEncoding encoding = new DeliveryCountUpdateEncoding(); @@ -1668,30 +1348,24 @@ public class JournalStorageManager implements StorageManager Map queueMessages = queueMap.get(encoding.queueID); - if (queueMessages == null) - { + if (queueMessages == null) { ActiveMQServerLogger.LOGGER.journalCannotFindQueueDelCount(encoding.queueID); } - else - { + else { AddMessageRecord rec = queueMessages.get(messageID); - if (rec == null) - { + if (rec == null) { ActiveMQServerLogger.LOGGER.journalCannotFindMessageDelCount(messageID); } - else - { + else { rec.deliveryCount = encoding.count; } } break; } - case JournalRecordIds.PAGE_TRANSACTION: - { - if (record.isUpdate) - { + case JournalRecordIds.PAGE_TRANSACTION: { + if (record.isUpdate) { PageUpdateTXEncoding pageUpdate = new PageUpdateTXEncoding(); pageUpdate.decode(buff); @@ -1700,8 +1374,7 @@ public class JournalStorageManager implements StorageManager pageTX.onUpdate(pageUpdate.recods, null, null); } - else - { + else { PageTransactionInfoImpl pageTransactionInfo = new PageTransactionInfoImpl(); pageTransactionInfo.decode(buff); @@ -1713,8 +1386,7 @@ public class JournalStorageManager implements StorageManager break; } - case JournalRecordIds.SET_SCHEDULED_DELIVERY_TIME: - { + case JournalRecordIds.SET_SCHEDULED_DELIVERY_TIME: { long messageID = record.id; ScheduledDeliveryEncoding encoding = new ScheduledDeliveryEncoding(); @@ -1723,37 +1395,31 @@ public class JournalStorageManager implements StorageManager Map queueMessages = queueMap.get(encoding.queueID); - if (queueMessages == null) - { + if (queueMessages == null) { ActiveMQServerLogger.LOGGER.journalCannotFindQueueScheduled(encoding.queueID, messageID); } - else - { + else { AddMessageRecord rec = queueMessages.get(messageID); - if (rec == null) - { + if (rec == null) { ActiveMQServerLogger.LOGGER.cannotFindMessage(messageID); } - else - { + else { rec.scheduledDeliveryTime = encoding.scheduledDeliveryTime; } } break; } - case JournalRecordIds.DUPLICATE_ID: - { + case JournalRecordIds.DUPLICATE_ID: { DuplicateIDEncoding encoding = new DuplicateIDEncoding(); encoding.decode(buff); List> ids = duplicateIDMap.get(encoding.address); - if (ids == null) - { + if (ids == null) { ids = new ArrayList>(); duplicateIDMap.put(encoding.address, ids); @@ -1763,15 +1429,13 @@ public class JournalStorageManager implements StorageManager break; } - case JournalRecordIds.HEURISTIC_COMPLETION: - { + case JournalRecordIds.HEURISTIC_COMPLETION: { HeuristicCompletionEncoding encoding = new HeuristicCompletionEncoding(); encoding.decode(buff); resourceManager.putHeuristicCompletion(record.id, encoding.xid, encoding.isCommit); break; } - case JournalRecordIds.ACKNOWLEDGE_CURSOR: - { + case JournalRecordIds.ACKNOWLEDGE_CURSOR: { CursorAckRecordEncoding encoding = new CursorAckRecordEncoding(); encoding.decode(buff); @@ -1779,12 +1443,10 @@ public class JournalStorageManager implements StorageManager PageSubscription sub = locateSubscription(encoding.queueID, pageSubscriptions, queueInfos, pagingManager); - if (sub != null) - { + if (sub != null) { sub.reloadACK(encoding.position); } - else - { + else { ActiveMQServerLogger.LOGGER.journalCannotFindQueueReloading(encoding.queueID); messageJournal.appendDeleteRecord(record.id, false); @@ -1792,20 +1454,17 @@ public class JournalStorageManager implements StorageManager break; } - case JournalRecordIds.PAGE_CURSOR_COUNTER_VALUE: - { + case JournalRecordIds.PAGE_CURSOR_COUNTER_VALUE: { PageCountRecord encoding = new PageCountRecord(); encoding.decode(buff); PageSubscription sub = locateSubscription(encoding.queueID, pageSubscriptions, queueInfos, pagingManager); - if (sub != null) - { + if (sub != null) { sub.getCounter().loadValue(record.id, encoding.value); } - else - { + else { ActiveMQServerLogger.LOGGER.journalCannotFindQueueReloadingPage(encoding.queueID); messageJournal.appendDeleteRecord(record.id, false); } @@ -1813,20 +1472,17 @@ public class JournalStorageManager implements StorageManager break; } - case JournalRecordIds.PAGE_CURSOR_COUNTER_INC: - { + case JournalRecordIds.PAGE_CURSOR_COUNTER_INC: { PageCountRecordInc encoding = new PageCountRecordInc(); encoding.decode(buff); PageSubscription sub = locateSubscription(encoding.queueID, pageSubscriptions, queueInfos, pagingManager); - if (sub != null) - { + if (sub != null) { sub.getCounter().loadInc(record.id, encoding.value); } - else - { + else { ActiveMQServerLogger.LOGGER.journalCannotFindQueueReloadingPageCursor(encoding.queueID); messageJournal.appendDeleteRecord(record.id, false); } @@ -1834,8 +1490,7 @@ public class JournalStorageManager implements StorageManager break; } - case JournalRecordIds.PAGE_CURSOR_COMPLETE: - { + case JournalRecordIds.PAGE_CURSOR_COMPLETE: { CursorAckRecordEncoding encoding = new CursorAckRecordEncoding(); encoding.decode(buff); @@ -1843,12 +1498,10 @@ public class JournalStorageManager implements StorageManager PageSubscription sub = locateSubscription(encoding.queueID, pageSubscriptions, queueInfos, pagingManager); - if (sub != null) - { + if (sub != null) { sub.reloadPageCompletion(encoding.position); } - else - { + else { ActiveMQServerLogger.LOGGER.cantFindQueueOnPageComplete(encoding.queueID); messageJournal.appendDeleteRecord(record.id, false); } @@ -1856,24 +1509,20 @@ public class JournalStorageManager implements StorageManager break; } - case JournalRecordIds.PAGE_CURSOR_PENDING_COUNTER: - { + case JournalRecordIds.PAGE_CURSOR_PENDING_COUNTER: { PageCountPendingImpl pendingCountEncoding = new PageCountPendingImpl(); pendingCountEncoding.decode(buff); pendingCountEncoding.setID(record.id); // This can be null on testcases not interested on this outcome - if (pendingNonTXPageCounter != null) - { + if (pendingNonTXPageCounter != null) { pendingNonTXPageCounter.add(pendingCountEncoding); } break; } - - default: - { + default: { throw new IllegalStateException("Invalid record type " + recordType); } } @@ -1890,25 +1539,14 @@ public class JournalStorageManager implements StorageManager journalLoader.handleAddMessage(queueMap); - loadPreparedTransactions(postOffice, - pagingManager, - resourceManager, - queueInfos, - preparedTransactions, - duplicateIDMap, - pageSubscriptions, - pendingLargeMessages, - journalLoader); + loadPreparedTransactions(postOffice, pagingManager, resourceManager, queueInfos, preparedTransactions, duplicateIDMap, pageSubscriptions, pendingLargeMessages, journalLoader); - for (PageSubscription sub : pageSubscriptions.values()) - { + for (PageSubscription sub : pageSubscriptions.values()) { sub.getCounter().processReload(); } - for (LargeServerMessage msg : largeMessages) - { - if (msg.getRefCount() == 0) - { + for (LargeServerMessage msg : largeMessages) { + if (msg.getRefCount() == 0) { ActiveMQServerLogger.LOGGER.largeMessageWithNoRef(msg.getMessageID()); msg.decrementDelayDeletionCount(); } @@ -1917,15 +1555,13 @@ public class JournalStorageManager implements StorageManager journalLoader.handleNoMessageReferences(messages); // To recover positions on Iterators - if (pagingManager != null) - { + if (pagingManager != null) { // it could be null on certain tests that are not dealing with paging // This could also be the case in certain embedded conditions pagingManager.processReload(); } - if (perfBlastPages != -1) - { + if (perfBlastPages != -1) { messageJournal.perfBlast(perfBlastPages); } @@ -1933,8 +1569,7 @@ public class JournalStorageManager implements StorageManager journalLoaded = true; return info; } - finally - { + finally { readUnLock(); } } @@ -1948,16 +1583,13 @@ public class JournalStorageManager implements StorageManager private static PageSubscription locateSubscription(final long queueID, final Map pageSubscriptions, final Map queueInfos, - final PagingManager pagingManager) throws Exception - { + final PagingManager pagingManager) throws Exception { PageSubscription subs = pageSubscriptions.get(queueID); - if (subs == null) - { + if (subs == null) { QueueBindingInfo queueInfo = queueInfos.get(queueID); - if (queueInfo != null) - { + if (queueInfo != null) { SimpleString address = queueInfo.getAddress(); PagingStore store = pagingManager.getPageStore(address); subs = store.getCursorProvider().getSubscription(queueID); @@ -1969,135 +1601,98 @@ public class JournalStorageManager implements StorageManager } // grouping handler operations - public void addGrouping(final GroupBinding groupBinding) throws Exception - { - GroupingEncoding groupingEncoding = new GroupingEncoding(groupBinding.getId(), - groupBinding.getGroupId(), - groupBinding.getClusterName()); + public void addGrouping(final GroupBinding groupBinding) throws Exception { + GroupingEncoding groupingEncoding = new GroupingEncoding(groupBinding.getId(), groupBinding.getGroupId(), groupBinding.getClusterName()); readLock(); - try - { - bindingsJournal.appendAddRecord(groupBinding.getId(), JournalRecordIds.GROUP_RECORD, groupingEncoding, - true); + try { + bindingsJournal.appendAddRecord(groupBinding.getId(), JournalRecordIds.GROUP_RECORD, groupingEncoding, true); } - finally - { + finally { readUnLock(); } } - public void deleteGrouping(long tx, final GroupBinding groupBinding) throws Exception - { + public void deleteGrouping(long tx, final GroupBinding groupBinding) throws Exception { readLock(); - try - { + try { bindingsJournal.appendDeleteRecordTransactional(tx, groupBinding.getId()); } - finally - { + finally { readUnLock(); } } // BindingsImpl operations - public void addQueueBinding(final long tx, final Binding binding) throws Exception - { + public void addQueueBinding(final long tx, final Binding binding) throws Exception { Queue queue = (Queue) binding.getBindable(); Filter filter = queue.getFilter(); SimpleString filterString = filter == null ? null : filter.getFilterString(); - PersistentQueueBindingEncoding bindingEncoding = new PersistentQueueBindingEncoding(queue.getName(), - binding.getAddress(), - filterString, - queue.getUser(), - queue.isAutoCreated()); + PersistentQueueBindingEncoding bindingEncoding = new PersistentQueueBindingEncoding(queue.getName(), binding.getAddress(), filterString, queue.getUser(), queue.isAutoCreated()); readLock(); - try - { - bindingsJournal.appendAddRecordTransactional(tx, binding.getID(), JournalRecordIds.QUEUE_BINDING_RECORD, - bindingEncoding); + try { + bindingsJournal.appendAddRecordTransactional(tx, binding.getID(), JournalRecordIds.QUEUE_BINDING_RECORD, bindingEncoding); } - finally - { + finally { readUnLock(); } } - public void deleteQueueBinding(long tx, final long queueBindingID) throws Exception - { + public void deleteQueueBinding(long tx, final long queueBindingID) throws Exception { readLock(); - try - { + try { bindingsJournal.appendDeleteRecordTransactional(tx, queueBindingID); } - finally - { + finally { readUnLock(); } } - public long storePageCounterInc(long txID, long queueID, int value) throws Exception - { + public long storePageCounterInc(long txID, long queueID, int value) throws Exception { readLock(); - try - { + try { long recordID = idGenerator.generateID(); - messageJournal.appendAddRecordTransactional(txID, recordID, JournalRecordIds.PAGE_CURSOR_COUNTER_INC, - new PageCountRecordInc(queueID, value)); + messageJournal.appendAddRecordTransactional(txID, recordID, JournalRecordIds.PAGE_CURSOR_COUNTER_INC, new PageCountRecordInc(queueID, value)); return recordID; } - finally - { + finally { readUnLock(); } } - public long storePageCounterInc(long queueID, int value) throws Exception - { + public long storePageCounterInc(long queueID, int value) throws Exception { readLock(); - try - { + try { final long recordID = idGenerator.generateID(); - messageJournal.appendAddRecord(recordID, - JournalRecordIds.PAGE_CURSOR_COUNTER_INC, - new PageCountRecordInc(queueID, value), - true, - getContext()); + messageJournal.appendAddRecord(recordID, JournalRecordIds.PAGE_CURSOR_COUNTER_INC, new PageCountRecordInc(queueID, value), true, getContext()); return recordID; } - finally - { + finally { readUnLock(); } } @Override - public long storePageCounter(long txID, long queueID, long value) throws Exception - { + public long storePageCounter(long txID, long queueID, long value) throws Exception { readLock(); - try - { + try { final long recordID = idGenerator.generateID(); - messageJournal.appendAddRecordTransactional(txID, recordID, JournalRecordIds.PAGE_CURSOR_COUNTER_VALUE, - new PageCountRecord(queueID, value)); + messageJournal.appendAddRecordTransactional(txID, recordID, JournalRecordIds.PAGE_CURSOR_COUNTER_VALUE, new PageCountRecord(queueID, value)); return recordID; } - finally - { + finally { readUnLock(); } } @Override - public long storePendingCounter(final long queueID, final long pageID, final int inc) throws Exception - { + public long storePendingCounter(final long queueID, final long pageID, final int inc) throws Exception { readLock(); - try - { + try { final long recordID = idGenerator.generateID(); PageCountPendingImpl pendingInc = new PageCountPendingImpl(queueID, pageID, inc); // We must guarantee the record sync before we actually write on the page otherwise we may get out of sync @@ -2105,95 +1700,77 @@ public class JournalStorageManager implements StorageManager messageJournal.appendAddRecord(recordID, JournalRecordIds.PAGE_CURSOR_PENDING_COUNTER, pendingInc, true); return recordID; } - finally - { + finally { readUnLock(); } } - public void deleteIncrementRecord(long txID, long recordID) throws Exception - { + public void deleteIncrementRecord(long txID, long recordID) throws Exception { readLock(); - try - { + try { messageJournal.appendDeleteRecordTransactional(txID, recordID); } - finally - { + finally { readUnLock(); } } - public void deletePageCounter(long txID, long recordID) throws Exception - { + public void deletePageCounter(long txID, long recordID) throws Exception { readLock(); - try - { + try { messageJournal.appendDeleteRecordTransactional(txID, recordID); } - finally - { + finally { readUnLock(); } } - public void deletePendingPageCounter(long txID, long recordID) throws Exception - { + public void deletePendingPageCounter(long txID, long recordID) throws Exception { readLock(); - try - { + try { messageJournal.appendDeleteRecordTransactional(txID, recordID); } - finally - { + finally { readUnLock(); } } public JournalLoadInformation loadBindingJournal(final List queueBindingInfos, - final List groupingInfos) throws Exception - { + final List groupingInfos) throws Exception { List records = new ArrayList(); List preparedTransactions = new ArrayList(); JournalLoadInformation bindingsInfo = bindingsJournal.load(records, preparedTransactions, null); - for (RecordInfo record : records) - { + for (RecordInfo record : records) { long id = record.id; ActiveMQBuffer buffer = ActiveMQBuffers.wrappedBuffer(record.data); byte rec = record.getUserRecordType(); - if (rec == JournalRecordIds.QUEUE_BINDING_RECORD) - { + if (rec == JournalRecordIds.QUEUE_BINDING_RECORD) { PersistentQueueBindingEncoding bindingEncoding = newBindingEncoding(id, buffer); queueBindingInfos.add(bindingEncoding); } - else if (rec == JournalRecordIds.ID_COUNTER_RECORD) - { + else if (rec == JournalRecordIds.ID_COUNTER_RECORD) { idGenerator.loadState(record.id, buffer); } - else if (rec == JournalRecordIds.GROUP_RECORD) - { + else if (rec == JournalRecordIds.GROUP_RECORD) { GroupingEncoding encoding = newGroupEncoding(id, buffer); groupingInfos.add(encoding); } - else if (rec == JournalRecordIds.ADDRESS_SETTING_RECORD) - { + else if (rec == JournalRecordIds.ADDRESS_SETTING_RECORD) { PersistedAddressSetting setting = newAddressEncoding(id, buffer); mapPersistedAddressSettings.put(setting.getAddressMatch(), setting); } - else if (rec == JournalRecordIds.SECURITY_RECORD) - { + else if (rec == JournalRecordIds.SECURITY_RECORD) { PersistedRoles roles = newSecurityRecord(id, buffer); mapPersistedRoles.put(roles.getAddressMatch(), roles); } - else - { + else { throw new IllegalStateException("Invalid record type " + rec); } } @@ -2204,15 +1781,12 @@ public class JournalStorageManager implements StorageManager return bindingsInfo; } - public void lineUpContext() - { + public void lineUpContext() { readLock(); - try - { + try { messageJournal.lineUpContext(getContext()); } - finally - { + finally { readUnLock(); } } @@ -2220,10 +1794,8 @@ public class JournalStorageManager implements StorageManager // ActiveMQComponent implementation // ------------------------------------------------------ - public synchronized void start() throws Exception - { - if (started) - { + public synchronized void start() throws Exception { + if (started) { return; } @@ -2235,9 +1807,7 @@ public class JournalStorageManager implements StorageManager cleanupIncompleteFiles(); - singleThreadExecutor = Executors.newSingleThreadExecutor(new ActiveMQThreadFactory("ActiveMQ-IO-SingleThread", - true, - getThisClassLoader())); + singleThreadExecutor = Executors.newSingleThreadExecutor(new ActiveMQThreadFactory("ActiveMQ-IO-SingleThread", true, getThisClassLoader())); bindingsJournal.start(); @@ -2246,30 +1816,24 @@ public class JournalStorageManager implements StorageManager started = true; } - public void stop() throws Exception - { + public void stop() throws Exception { stop(false); } @Override - public synchronized void persistIdGenerator() - { - if (journalLoaded && idGenerator != null) - { + public synchronized void persistIdGenerator() { + if (journalLoaded && idGenerator != null) { // Must call close to make sure last id is persisted idGenerator.persistCurrentID(); } } - public synchronized void stop(boolean ioCriticalError) throws Exception - { - if (!started) - { + public synchronized void stop(boolean ioCriticalError) throws Exception { + if (!started) { return; } - if (!ioCriticalError) - { + if (!ioCriticalError) { performCachedLargeMessageDeletes(); // Must call close to make sure last id is persisted if (journalLoaded && idGenerator != null) @@ -2277,33 +1841,26 @@ public class JournalStorageManager implements StorageManager } final CountDownLatch latch = new CountDownLatch(1); - executor.execute(new Runnable() - { + executor.execute(new Runnable() { @Override - public void run() - { + public void run() { latch.countDown(); } }); latch.await(30, TimeUnit.SECONDS); - // We cache the variable as the replicator could be changed between here and the time we call stop // since sendLiveIsStoping my issue a close back from the channel // and we want to ensure a stop here just in case ReplicationManager replicatorInUse = replicator; - if (replicatorInUse != null) - { + if (replicatorInUse != null) { final OperationContext token = replicator.sendLiveIsStopping(LiveStopping.FAIL_OVER); - if (token != null) - { - try - { + if (token != null) { + try { token.waitCompletion(5000); } - catch (Exception e) - { + catch (Exception e) { // ignore it } } @@ -2320,144 +1877,113 @@ public class JournalStorageManager implements StorageManager started = false; } - public synchronized boolean isStarted() - { + public synchronized boolean isStarted() { return started; } /** * TODO: Is this still being used ? */ - public JournalLoadInformation[] loadInternalOnly() throws Exception - { + public JournalLoadInformation[] loadInternalOnly() throws Exception { readLock(); - try - { + try { JournalLoadInformation[] info = new JournalLoadInformation[2]; info[0] = bindingsJournal.loadInternalOnly(); info[1] = messageJournal.loadInternalOnly(); return info; } - finally - { + finally { readUnLock(); } } - public void beforePageRead() throws Exception - { - if (pageMaxConcurrentIO != null) - { + public void beforePageRead() throws Exception { + if (pageMaxConcurrentIO != null) { pageMaxConcurrentIO.acquire(); } } - public void afterPageRead() throws Exception - { - if (pageMaxConcurrentIO != null) - { + public void afterPageRead() throws Exception { + if (pageMaxConcurrentIO != null) { pageMaxConcurrentIO.release(); } } @Override - public ByteBuffer allocateDirectBuffer(int size) - { + public ByteBuffer allocateDirectBuffer(int size) { return journalFF.allocateDirectBuffer(size); } @Override - public void freeDirectBuffer(ByteBuffer buffer) - { + public void freeDirectBuffer(ByteBuffer buffer) { journalFF.releaseBuffer(buffer); } // Public ----------------------------------------------------------------------------------- - public Journal getMessageJournal() - { + public Journal getMessageJournal() { return messageJournal; } - public Journal getBindingsJournal() - { + public Journal getBindingsJournal() { return bindingsJournal; } // Package protected --------------------------------------------- - private void confirmLargeMessage(final LargeServerMessage largeServerMessage) - { - if (largeServerMessage.getPendingRecordID() >= 0) - { - try - { + private void confirmLargeMessage(final LargeServerMessage largeServerMessage) { + if (largeServerMessage.getPendingRecordID() >= 0) { + try { confirmPendingLargeMessage(largeServerMessage.getPendingRecordID()); largeServerMessage.setPendingRecordID(-1); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e); } } } // This should be accessed from this package only - void deleteLargeMessageFile(final LargeServerMessage largeServerMessage) throws ActiveMQException - { - if (largeServerMessage.getPendingRecordID() < 0) - { - try - { + void deleteLargeMessageFile(final LargeServerMessage largeServerMessage) throws ActiveMQException { + if (largeServerMessage.getPendingRecordID() < 0) { + try { // The delete file happens asynchronously // And the client won't be waiting for the actual file to be deleted. // We set a temporary record (short lived) on the journal // to avoid a situation where the server is restarted and pending large message stays on forever largeServerMessage.setPendingRecordID(storePendingLargeMessage(largeServerMessage.getMessageID())); } - catch (Exception e) - { + catch (Exception e) { throw new ActiveMQInternalErrorException(e.getMessage(), e); } } final SequentialFile file = largeServerMessage.getFile(); - if (file == null) - { + if (file == null) { return; } - if (largeServerMessage.isDurable() && isReplicated()) - { + if (largeServerMessage.isDurable() && isReplicated()) { readLock(); - try - { - if (isReplicated() && replicator.isSynchronizing()) - { - synchronized (largeMessagesToDelete) - { + try { + if (isReplicated() && replicator.isSynchronizing()) { + synchronized (largeMessagesToDelete) { largeMessagesToDelete.add(Long.valueOf(largeServerMessage.getMessageID())); confirmLargeMessage(largeServerMessage); } return; } } - finally - { + finally { readUnLock(); } } - Runnable deleteAction = new Runnable() - { - public void run() - { - try - { + Runnable deleteAction = new Runnable() { + public void run() { + try { readLock(); - try - { - if (replicator != null) - { + try { + if (replicator != null) { replicator.largeMessageDelete(largeServerMessage.getMessageID()); } file.delete(); @@ -2465,63 +1991,48 @@ public class JournalStorageManager implements StorageManager // The confirm could only be done after the actual delete is done confirmLargeMessage(largeServerMessage); } - finally - { + finally { readUnLock(); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.journalErrorDeletingMessage(e, largeServerMessage.getMessageID()); } } }; - if (executor == null) - { + if (executor == null) { deleteAction.run(); } - else - { + else { executor.execute(deleteAction); } } - SequentialFile createFileForLargeMessage(final long messageID, final boolean durable) - { - if (durable) - { + SequentialFile createFileForLargeMessage(final long messageID, final boolean durable) { + if (durable) { return createFileForLargeMessage(messageID, LargeMessageExtension.DURABLE); } - else - { + else { return createFileForLargeMessage(messageID, LargeMessageExtension.TEMPORARY); } } - - public SequentialFile createFileForLargeMessage(final long messageID, LargeMessageExtension extension) - { + public SequentialFile createFileForLargeMessage(final long messageID, LargeMessageExtension extension) { return largeMessagesFactory.createSequentialFile(messageID + extension.getExtension()); } - // Private ---------------------------------------------------------------------------------- - private void checkAndCreateDir(final File dir, final boolean create) - { - if (!dir.exists()) - { - if (create) - { - if (!dir.mkdirs()) - { + private void checkAndCreateDir(final File dir, final boolean create) { + if (!dir.exists()) { + if (create) { + if (!dir.mkdirs()) { throw new IllegalStateException("Failed to create directory " + dir); } } - else - { + else { throw ActiveMQMessageBundle.BUNDLE.cannotCreateDir(dir.getAbsolutePath()); } } @@ -2533,26 +2044,23 @@ public class JournalStorageManager implements StorageManager * @return * @throws Exception */ - private LargeServerMessage parseLargeMessage(final Map messages, final ActiveMQBuffer buff) throws Exception - { + private LargeServerMessage parseLargeMessage(final Map messages, + final ActiveMQBuffer buff) throws Exception { LargeServerMessage largeMessage = createLargeMessage(); LargeMessageEncoding messageEncoding = new LargeMessageEncoding(largeMessage); messageEncoding.decode(buff); - if (largeMessage.containsProperty(Message.HDR_ORIG_MESSAGE_ID)) - { + if (largeMessage.containsProperty(Message.HDR_ORIG_MESSAGE_ID)) { // for compatibility: couple with old behaviour, copying the old file to avoid message loss long originalMessageID = largeMessage.getLongProperty(Message.HDR_ORIG_MESSAGE_ID); SequentialFile currentFile = createFileForLargeMessage(largeMessage.getMessageID(), true); - if (!currentFile.exists()) - { + if (!currentFile.exists()) { SequentialFile linkedFile = createFileForLargeMessage(originalMessageID, true); - if (linkedFile.exists()) - { + if (linkedFile.exists()) { linkedFile.copyTo(currentFile); linkedFile.close(); } @@ -2571,11 +2079,10 @@ public class JournalStorageManager implements StorageManager final List preparedTransactions, final Map>> duplicateIDMap, final Map pageSubscriptions, - final Set> pendingLargeMessages, JournalLoader journalLoader) throws Exception - { + final Set> pendingLargeMessages, + JournalLoader journalLoader) throws Exception { // recover prepared transactions - for (PreparedTransactionInfo preparedTransaction : preparedTransactions) - { + for (PreparedTransactionInfo preparedTransaction : preparedTransactions) { XidEncoding encodingXid = new XidEncoding(preparedTransaction.extraData); Xid xid = encodingXid.xid; @@ -2590,24 +2097,20 @@ public class JournalStorageManager implements StorageManager // Then have reacknowledge(tx) methods on queue, which needs to add the page size // first get any sent messages for this tx and recreate - for (RecordInfo record : preparedTransaction.records) - { + for (RecordInfo record : preparedTransaction.records) { byte[] data = record.data; ActiveMQBuffer buff = ActiveMQBuffers.wrappedBuffer(data); byte recordType = record.getUserRecordType(); - switch (recordType) - { - case JournalRecordIds.ADD_LARGE_MESSAGE: - { + switch (recordType) { + case JournalRecordIds.ADD_LARGE_MESSAGE: { messages.put(record.id, parseLargeMessage(messages, buff)); break; } - case JournalRecordIds.ADD_MESSAGE: - { + case JournalRecordIds.ADD_MESSAGE: { ServerMessage message = new ServerMessageImpl(record.id, 50); message.decode(buff); @@ -2616,8 +2119,7 @@ public class JournalStorageManager implements StorageManager break; } - case JournalRecordIds.ADD_REF: - { + case JournalRecordIds.ADD_REF: { long messageID = record.id; RefEncoding encoding = new RefEncoding(); @@ -2626,8 +2128,7 @@ public class JournalStorageManager implements StorageManager ServerMessage message = messages.get(messageID); - if (message == null) - { + if (message == null) { throw new IllegalStateException("Cannot find message with id " + messageID); } @@ -2635,8 +2136,7 @@ public class JournalStorageManager implements StorageManager break; } - case JournalRecordIds.ACKNOWLEDGE_REF: - { + case JournalRecordIds.ACKNOWLEDGE_REF: { long messageID = record.id; RefEncoding encoding = new RefEncoding(); @@ -2647,20 +2147,17 @@ public class JournalStorageManager implements StorageManager break; } - case JournalRecordIds.PAGE_TRANSACTION: - { + case JournalRecordIds.PAGE_TRANSACTION: { PageTransactionInfo pageTransactionInfo = new PageTransactionInfoImpl(); pageTransactionInfo.decode(buff); - if (record.isUpdate) - { + if (record.isUpdate) { PageTransactionInfo pgTX = pagingManager.getTransaction(pageTransactionInfo.getTransactionID()); pgTX.reloadUpdate(this, pagingManager, tx, pageTransactionInfo.getNumberOfMessages()); } - else - { + else { pageTransactionInfo.setCommitted(false); tx.putProperty(TransactionPropertyIndexes.PAGE_TRANSACTION, pageTransactionInfo); @@ -2672,16 +2169,14 @@ public class JournalStorageManager implements StorageManager break; } - case SET_SCHEDULED_DELIVERY_TIME: - { + case SET_SCHEDULED_DELIVERY_TIME: { // Do nothing - for prepared txs, the set scheduled delivery time will only occur in a send in which // case the message will already have the header for the scheduled delivery time, so no need to do // anything. break; } - case DUPLICATE_ID: - { + case DUPLICATE_ID: { // We need load the duplicate ids at prepare time too DuplicateIDEncoding encoding = new DuplicateIDEncoding(); @@ -2693,83 +2188,64 @@ public class JournalStorageManager implements StorageManager break; } - case ACKNOWLEDGE_CURSOR: - { + case ACKNOWLEDGE_CURSOR: { CursorAckRecordEncoding encoding = new CursorAckRecordEncoding(); encoding.decode(buff); encoding.position.setRecordID(record.id); - PageSubscription sub = locateSubscription(encoding.queueID, - pageSubscriptions, - queueInfos, - pagingManager); + PageSubscription sub = locateSubscription(encoding.queueID, pageSubscriptions, queueInfos, pagingManager); - if (sub != null) - { + if (sub != null) { sub.reloadPreparedACK(tx, encoding.position); referencesToAck.add(new PagedReferenceImpl(encoding.position, null, sub)); } - else - { + else { ActiveMQServerLogger.LOGGER.journalCannotFindQueueReloadingACK(encoding.queueID); } break; } - case PAGE_CURSOR_COUNTER_VALUE: - { + case PAGE_CURSOR_COUNTER_VALUE: { ActiveMQServerLogger.LOGGER.journalPAGEOnPrepared(); break; } - case PAGE_CURSOR_COUNTER_INC: - { + case PAGE_CURSOR_COUNTER_INC: { PageCountRecordInc encoding = new PageCountRecordInc(); encoding.decode(buff); - PageSubscription sub = locateSubscription(encoding.queueID, - pageSubscriptions, - queueInfos, - pagingManager); + PageSubscription sub = locateSubscription(encoding.queueID, pageSubscriptions, queueInfos, pagingManager); - if (sub != null) - { + if (sub != null) { sub.getCounter().applyIncrementOnTX(tx, record.id, encoding.value); sub.notEmpty(); } - else - { + else { ActiveMQServerLogger.LOGGER.journalCannotFindQueueReloadingACK(encoding.queueID); } break; } - default: - { + default: { ActiveMQServerLogger.LOGGER.journalInvalidRecordType(recordType); } } } - for (RecordInfo recordDeleted : preparedTransaction.recordsToDelete) - { + for (RecordInfo recordDeleted : preparedTransaction.recordsToDelete) { byte[] data = recordDeleted.data; - if (data.length > 0) - { + if (data.length > 0) { ActiveMQBuffer buff = ActiveMQBuffers.wrappedBuffer(data); byte b = buff.readByte(); - switch (b) - { - case ADD_LARGE_MESSAGE_PENDING: - { + switch (b) { + case ADD_LARGE_MESSAGE_PENDING: { long messageID = buff.readLong(); - if (!pendingLargeMessages.remove(new Pair(recordDeleted.id, messageID))) - { + if (!pendingLargeMessages.remove(new Pair(recordDeleted.id, messageID))) { ActiveMQServerLogger.LOGGER.largeMessageNotFound(recordDeleted.id); } installLargeMessageConfirmationOnTX(tx, recordDeleted.id); @@ -2786,37 +2262,28 @@ public class JournalStorageManager implements StorageManager } } - private void cleanupIncompleteFiles() throws Exception - { - if (largeMessagesFactory != null) - { + private void cleanupIncompleteFiles() throws Exception { + if (largeMessagesFactory != null) { List tmpFiles = largeMessagesFactory.listFiles("tmp"); - for (String tmpFile : tmpFiles) - { + for (String tmpFile : tmpFiles) { SequentialFile file = largeMessagesFactory.createSequentialFile(tmpFile); file.delete(); } } } - private OperationContext getContext(final boolean sync) - { - if (sync) - { + private OperationContext getContext(final boolean sync) { + if (sync) { return getContext(); } - else - { + else { return DummyOperationContext.getInstance(); } } - private static ClassLoader getThisClassLoader() - { - return AccessController.doPrivileged(new PrivilegedAction() - { - public ClassLoader run() - { + private static ClassLoader getThisClassLoader() { + return AccessController.doPrivileged(new PrivilegedAction() { + public ClassLoader run() { return JournalStorageManager.class.getClassLoader(); } }); @@ -2825,199 +2292,166 @@ public class JournalStorageManager implements StorageManager // Inner Classes // ---------------------------------------------------------------------------- - private static final class DummyOperationContext implements OperationContext - { + private static final class DummyOperationContext implements OperationContext { private static DummyOperationContext instance = new DummyOperationContext(); - public static OperationContext getInstance() - { + public static OperationContext getInstance() { return DummyOperationContext.instance; } - public void executeOnCompletion(final IOCallback runnable) - { + public void executeOnCompletion(final IOCallback runnable) { // There are no executeOnCompletion calls while using the DummyOperationContext // However we keep the code here for correctness runnable.done(); } - public void replicationDone() - { + public void replicationDone() { } - public void replicationLineUp() - { + public void replicationLineUp() { } - public void storeLineUp() - { + public void storeLineUp() { } - public void done() - { + public void done() { } - public void onError(final int errorCode, final String errorMessage) - { + public void onError(final int errorCode, final String errorMessage) { } - public void waitCompletion() - { + public void waitCompletion() { } - public boolean waitCompletion(final long timeout) - { + public boolean waitCompletion(final long timeout) { return true; } - public void pageSyncLineUp() - { + public void pageSyncLineUp() { } - public void pageSyncDone() - { + public void pageSyncDone() { } } /** * It's public as other classes may want to unparse data on tools */ - public static class XidEncoding implements EncodingSupport - { + public static class XidEncoding implements EncodingSupport { + public final Xid xid; - XidEncoding(final Xid xid) - { + XidEncoding(final Xid xid) { this.xid = xid; } - XidEncoding(final byte[] data) - { + XidEncoding(final byte[] data) { xid = XidCodecSupport.decodeXid(ActiveMQBuffers.wrappedBuffer(data)); } - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { throw new IllegalStateException("Non Supported Operation"); } - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { XidCodecSupport.encodeXid(xid, buffer); } - public int getEncodeSize() - { + public int getEncodeSize() { return XidCodecSupport.getXidEncodeLength(xid); } } - protected static class HeuristicCompletionEncoding implements EncodingSupport - { + protected static class HeuristicCompletionEncoding implements EncodingSupport { + public Xid xid; public boolean isCommit; @Override - public String toString() - { + public String toString() { return "HeuristicCompletionEncoding [xid=" + xid + ", isCommit=" + isCommit + "]"; } - HeuristicCompletionEncoding(final Xid xid, final boolean isCommit) - { + HeuristicCompletionEncoding(final Xid xid, final boolean isCommit) { this.xid = xid; this.isCommit = isCommit; } - HeuristicCompletionEncoding() - { + HeuristicCompletionEncoding() { } - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { xid = XidCodecSupport.decodeXid(buffer); isCommit = buffer.readBoolean(); } - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { XidCodecSupport.encodeXid(xid, buffer); buffer.writeBoolean(isCommit); } - public int getEncodeSize() - { + public int getEncodeSize() { return XidCodecSupport.getXidEncodeLength(xid) + DataConstants.SIZE_BOOLEAN; } } - private static class GroupingEncoding implements EncodingSupport, GroupingInfo - { + private static class GroupingEncoding implements EncodingSupport, GroupingInfo { + public long id; public SimpleString groupId; public SimpleString clusterName; - public GroupingEncoding(final long id, final SimpleString groupId, final SimpleString clusterName) - { + public GroupingEncoding(final long id, final SimpleString groupId, final SimpleString clusterName) { this.id = id; this.groupId = groupId; this.clusterName = clusterName; } - public GroupingEncoding() - { + public GroupingEncoding() { } - public int getEncodeSize() - { + public int getEncodeSize() { return SimpleString.sizeofString(groupId) + SimpleString.sizeofString(clusterName); } - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { buffer.writeSimpleString(groupId); buffer.writeSimpleString(clusterName); } - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { groupId = buffer.readSimpleString(); clusterName = buffer.readSimpleString(); } - public long getId() - { + public long getId() { return id; } - public void setId(final long id) - { + public void setId(final long id) { this.id = id; } - public SimpleString getGroupId() - { + public SimpleString getGroupId() { return groupId; } - public SimpleString getClusterName() - { + public SimpleString getClusterName() { return clusterName; } @Override - public String toString() - { + public String toString() { return "GroupingEncoding [id=" + id + ", groupId=" + groupId + ", clusterName=" + clusterName + "]"; } } - public static class PersistentQueueBindingEncoding implements EncodingSupport, QueueBindingInfo - { + public static class PersistentQueueBindingEncoding implements EncodingSupport, QueueBindingInfo { + public long id; public SimpleString name; @@ -3030,13 +2464,11 @@ public class JournalStorageManager implements StorageManager public SimpleString user; - public PersistentQueueBindingEncoding() - { + public PersistentQueueBindingEncoding() { } @Override - public String toString() - { + public String toString() { return "PersistentQueueBindingEncoding [id=" + id + ", name=" + name + @@ -3055,8 +2487,7 @@ public class JournalStorageManager implements StorageManager final SimpleString address, final SimpleString filterString, final SimpleString user, - final boolean autoCreated) - { + final boolean autoCreated) { this.name = name; this.address = address; this.filterString = filterString; @@ -3064,63 +2495,50 @@ public class JournalStorageManager implements StorageManager this.autoCreated = autoCreated; } - public long getId() - { + public long getId() { return id; } - public void setId(final long id) - { + public void setId(final long id) { this.id = id; } - public SimpleString getAddress() - { + public SimpleString getAddress() { return address; } - public void replaceQueueName(SimpleString newName) - { + public void replaceQueueName(SimpleString newName) { this.name = newName; } - public SimpleString getFilterString() - { + public SimpleString getFilterString() { return filterString; } - public SimpleString getQueueName() - { + public SimpleString getQueueName() { return name; } - public SimpleString getUser() - { + public SimpleString getUser() { return user; } - public boolean isAutoCreated() - { + public boolean isAutoCreated() { return autoCreated; } - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { name = buffer.readSimpleString(); address = buffer.readSimpleString(); filterString = buffer.readNullableSimpleString(); String metadata = buffer.readNullableSimpleString().toString(); - if (metadata != null) - { + if (metadata != null) { String[] elements = metadata.split(";"); - for (String element : elements) - { + for (String element : elements) { String[] keyValuePair = element.split("="); - if (keyValuePair.length == 2) - { - if (keyValuePair[0].equals("user")) - { + if (keyValuePair.length == 2) { + if (keyValuePair[0].equals("user")) { user = SimpleString.toSimpleString(keyValuePair[1]); } } @@ -3130,8 +2548,7 @@ public class JournalStorageManager implements StorageManager autoCreated = buffer.readBoolean(); } - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { buffer.writeSimpleString(name); buffer.writeSimpleString(address); buffer.writeNullableSimpleString(filterString); @@ -3139,190 +2556,165 @@ public class JournalStorageManager implements StorageManager buffer.writeBoolean(autoCreated); } - public int getEncodeSize() - { + public int getEncodeSize() { return SimpleString.sizeofString(name) + SimpleString.sizeofString(address) + SimpleString.sizeofNullableString(filterString) + DataConstants.SIZE_BOOLEAN + SimpleString.sizeofNullableString(createMetadata()); } - private SimpleString createMetadata() - { + private SimpleString createMetadata() { StringBuilder metadata = new StringBuilder(); metadata.append("user=").append(user).append(";"); return SimpleString.toSimpleString(metadata.toString()); } } - public static class LargeMessageEncoding implements EncodingSupport - { + public static class LargeMessageEncoding implements EncodingSupport { + public final LargeServerMessage message; - public LargeMessageEncoding(final LargeServerMessage message) - { + public LargeMessageEncoding(final LargeServerMessage message) { this.message = message; } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.journal.EncodingSupport#decode(org.apache.activemq.artemis.spi.core.remoting.ActiveMQBuffer) */ - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { message.decodeHeadersAndProperties(buffer); } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.journal.EncodingSupport#encode(org.apache.activemq.artemis.spi.core.remoting.ActiveMQBuffer) */ - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { message.encode(buffer); } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.journal.EncodingSupport#getEncodeSize() */ - public int getEncodeSize() - { + public int getEncodeSize() { return message.getEncodeSize(); } } - public static class PendingLargeMessageEncoding implements EncodingSupport - { + public static class PendingLargeMessageEncoding implements EncodingSupport { + public long largeMessageID; - public PendingLargeMessageEncoding(final long pendingLargeMessageID) - { + public PendingLargeMessageEncoding(final long pendingLargeMessageID) { this.largeMessageID = pendingLargeMessageID; } - public PendingLargeMessageEncoding() - { + public PendingLargeMessageEncoding() { } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.journal.EncodingSupport#decode(org.apache.activemq.artemis.spi.core.remoting.ActiveMQBuffer) */ - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { largeMessageID = buffer.readLong(); } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.journal.EncodingSupport#encode(org.apache.activemq.artemis.spi.core.remoting.ActiveMQBuffer) */ - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { buffer.writeLong(largeMessageID); } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.journal.EncodingSupport#getEncodeSize() */ - public int getEncodeSize() - { + public int getEncodeSize() { return DataConstants.SIZE_LONG; } @Override - public String toString() - { + public String toString() { return "PendingLargeMessageEncoding::MessageID=" + largeMessageID; } } - public static class DeliveryCountUpdateEncoding implements EncodingSupport - { + public static class DeliveryCountUpdateEncoding implements EncodingSupport { + public long queueID; public int count; - public DeliveryCountUpdateEncoding() - { + public DeliveryCountUpdateEncoding() { super(); } - public DeliveryCountUpdateEncoding(final long queueID, final int count) - { + public DeliveryCountUpdateEncoding(final long queueID, final int count) { super(); this.queueID = queueID; this.count = count; } - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { queueID = buffer.readLong(); count = buffer.readInt(); } - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { buffer.writeLong(queueID); buffer.writeInt(count); } - public int getEncodeSize() - { + public int getEncodeSize() { return 8 + 4; } @Override - public String toString() - { + public String toString() { return "DeliveryCountUpdateEncoding [queueID=" + queueID + ", count=" + count + "]"; } } - public static class QueueEncoding implements EncodingSupport - { + public static class QueueEncoding implements EncodingSupport { + public long queueID; - public QueueEncoding(final long queueID) - { + public QueueEncoding(final long queueID) { super(); this.queueID = queueID; } - public QueueEncoding() - { + public QueueEncoding() { super(); } - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { queueID = buffer.readLong(); } - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { buffer.writeLong(queueID); } - public int getEncodeSize() - { + public int getEncodeSize() { return 8; } @Override - public String toString() - { + public String toString() { return "QueueEncoding [queueID=" + queueID + "]"; } } - private static class DeleteEncoding implements EncodingSupport - { + private static class DeleteEncoding implements EncodingSupport { + public byte recordType; public long id; - public DeleteEncoding(final byte recordType, final long id) - { + public DeleteEncoding(final byte recordType, final long id) { this.recordType = recordType; this.id = id; } @@ -3331,8 +2723,7 @@ public class JournalStorageManager implements StorageManager * @see org.apache.activemq.artemis.core.journal.EncodingSupport#getEncodeSize() */ @Override - public int getEncodeSize() - { + public int getEncodeSize() { return DataConstants.SIZE_BYTE + DataConstants.SIZE_LONG; } @@ -3340,8 +2731,7 @@ public class JournalStorageManager implements StorageManager * @see org.apache.activemq.artemis.core.journal.EncodingSupport#encode(org.apache.activemq.artemis.api.core.ActiveMQBuffer) */ @Override - public void encode(ActiveMQBuffer buffer) - { + public void encode(ActiveMQBuffer buffer) { buffer.writeByte(recordType); buffer.writeLong(id); } @@ -3350,134 +2740,114 @@ public class JournalStorageManager implements StorageManager * @see org.apache.activemq.artemis.core.journal.EncodingSupport#decode(org.apache.activemq.artemis.api.core.ActiveMQBuffer) */ @Override - public void decode(ActiveMQBuffer buffer) - { + public void decode(ActiveMQBuffer buffer) { recordType = buffer.readByte(); id = buffer.readLong(); } } - public static class RefEncoding extends QueueEncoding - { - public RefEncoding() - { + public static class RefEncoding extends QueueEncoding { + + public RefEncoding() { super(); } - public RefEncoding(final long queueID) - { + public RefEncoding(final long queueID) { super(queueID); } } - public static class PageUpdateTXEncoding implements EncodingSupport - { + public static class PageUpdateTXEncoding implements EncodingSupport { public long pageTX; public int recods; @Override - public String toString() - { + public String toString() { return "PageUpdateTXEncoding [pageTX=" + pageTX + ", recods=" + recods + "]"; } - public PageUpdateTXEncoding() - { + public PageUpdateTXEncoding() { } - public PageUpdateTXEncoding(final long pageTX, final int records) - { + public PageUpdateTXEncoding(final long pageTX, final int records) { this.pageTX = pageTX; this.recods = records; } - public void decode(ActiveMQBuffer buffer) - { + public void decode(ActiveMQBuffer buffer) { this.pageTX = buffer.readLong(); this.recods = buffer.readInt(); } @Override - public void encode(ActiveMQBuffer buffer) - { + public void encode(ActiveMQBuffer buffer) { buffer.writeLong(pageTX); buffer.writeInt(recods); } @Override - public int getEncodeSize() - { + public int getEncodeSize() { return DataConstants.SIZE_LONG + DataConstants.SIZE_INT; } - public List getRelatedMessageReferences() - { + public List getRelatedMessageReferences() { return null; } } - protected static class ScheduledDeliveryEncoding extends QueueEncoding - { + protected static class ScheduledDeliveryEncoding extends QueueEncoding { + long scheduledDeliveryTime; @Override - public String toString() - { + public String toString() { return "ScheduledDeliveryEncoding [scheduledDeliveryTime=" + scheduledDeliveryTime + "]"; } - private ScheduledDeliveryEncoding(final long scheduledDeliveryTime, final long queueID) - { + private ScheduledDeliveryEncoding(final long scheduledDeliveryTime, final long queueID) { super(queueID); this.scheduledDeliveryTime = scheduledDeliveryTime; } - public ScheduledDeliveryEncoding() - { + public ScheduledDeliveryEncoding() { } @Override - public int getEncodeSize() - { + public int getEncodeSize() { return super.getEncodeSize() + 8; } @Override - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { super.encode(buffer); buffer.writeLong(scheduledDeliveryTime); } @Override - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { super.decode(buffer); scheduledDeliveryTime = buffer.readLong(); } } - public static class DuplicateIDEncoding implements EncodingSupport - { + public static class DuplicateIDEncoding implements EncodingSupport { + SimpleString address; byte[] duplID; - public DuplicateIDEncoding(final SimpleString address, final byte[] duplID) - { + public DuplicateIDEncoding(final SimpleString address, final byte[] duplID) { this.address = address; this.duplID = duplID; } - public DuplicateIDEncoding() - { + public DuplicateIDEncoding() { } - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { address = buffer.readSimpleString(); int size = buffer.readInt(); @@ -3487,8 +2857,7 @@ public class JournalStorageManager implements StorageManager buffer.readBytes(duplID); } - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { buffer.writeSimpleString(address); buffer.writeInt(duplID.length); @@ -3496,14 +2865,12 @@ public class JournalStorageManager implements StorageManager buffer.writeBytes(duplID); } - public int getEncodeSize() - { + public int getEncodeSize() { return SimpleString.sizeofString(address) + DataConstants.SIZE_INT + duplID.length; } @Override - public String toString() - { + public String toString() { // this would be useful when testing. Most tests on the testsuite will use a SimpleString on the duplicate ID // and this may be useful to validate the journal on those tests // You may uncomment these two lines on that case and replcate the toString for the PrintData @@ -3515,10 +2882,8 @@ public class JournalStorageManager implements StorageManager // The bridge will generate IDs on these terms: // This will make them easier to read - if (address.toString().startsWith("BRIDGE") && duplID.length == 24) - { - try - { + if (address.toString().startsWith("BRIDGE") && duplID.length == 24) { + try { ByteBuffer buff = ByteBuffer.wrap(duplID); // 16 for UUID @@ -3531,19 +2896,16 @@ public class JournalStorageManager implements StorageManager long id = buff.getLong(); bridgeRepresentation = "nodeUUID=" + uuid.toString() + " messageID=" + id; } - catch (Throwable ignored) - { + catch (Throwable ignored) { bridgeRepresentation = null; } } - if (bridgeRepresentation != null) - { + if (bridgeRepresentation != null) { return "DuplicateIDEncoding [address=" + address + ", duplID=" + ByteUtil.bytesToHex(duplID, 2) + " / " + bridgeRepresentation + "]"; } - else - { + else { return "DuplicateIDEncoding [address=" + address + ", duplID=" + ByteUtil.bytesToHex(duplID, 2) + "]"; } } @@ -3556,52 +2918,43 @@ public class JournalStorageManager implements StorageManager * {@link org.apache.activemq.artemis.core.persistence.impl.journal.JournalStorageManager.FinishPageMessageOperation} */ // TODO: merge this class with the one on the PagingStoreImpl - private static class FinishPageMessageOperation extends TransactionOperationAbstract implements TransactionOperation - { + private static class FinishPageMessageOperation extends TransactionOperationAbstract implements TransactionOperation { @Override - public void afterCommit(final Transaction tx) - { + public void afterCommit(final Transaction tx) { // If part of the transaction goes to the queue, and part goes to paging, we can't let depage start for the // transaction until all the messages were added to the queue // or else we could deliver the messages out of order PageTransactionInfo pageTransaction = (PageTransactionInfo) tx.getProperty(TransactionPropertyIndexes.PAGE_TRANSACTION); - if (pageTransaction != null) - { + if (pageTransaction != null) { pageTransaction.commit(); } } @Override - public void afterRollback(final Transaction tx) - { + public void afterRollback(final Transaction tx) { PageTransactionInfo pageTransaction = (PageTransactionInfo) tx.getProperty(TransactionPropertyIndexes.PAGE_TRANSACTION); - if (tx.getState() == State.PREPARED && pageTransaction != null) - { + if (tx.getState() == State.PREPARED && pageTransaction != null) { pageTransaction.rollback(); } } } - protected static final class PageCountRecord implements EncodingSupport - { + protected static final class PageCountRecord implements EncodingSupport { @Override - public String toString() - { + public String toString() { return "PageCountRecord [queueID=" + queueID + ", value=" + value + "]"; } - PageCountRecord() - { + PageCountRecord() { } - PageCountRecord(long queueID, long value) - { + PageCountRecord(long queueID, long value) { this.queueID = queueID; this.value = value; } @@ -3611,43 +2964,36 @@ public class JournalStorageManager implements StorageManager long value; @Override - public int getEncodeSize() - { + public int getEncodeSize() { return DataConstants.SIZE_LONG * 2; } @Override - public void encode(ActiveMQBuffer buffer) - { + public void encode(ActiveMQBuffer buffer) { buffer.writeLong(queueID); buffer.writeLong(value); } @Override - public void decode(ActiveMQBuffer buffer) - { + public void decode(ActiveMQBuffer buffer) { queueID = buffer.readLong(); value = buffer.readLong(); } } - protected static final class PageCountPendingImpl implements EncodingSupport, PageCountPending - { + protected static final class PageCountPendingImpl implements EncodingSupport, PageCountPending { @Override - public String toString() - { + public String toString() { return "PageCountPending [queueID=" + queueID + ", pageID=" + pageID + "]"; } - PageCountPendingImpl() - { + PageCountPendingImpl() { } - PageCountPendingImpl(long queueID, long pageID, int inc) - { + PageCountPendingImpl(long queueID, long pageID, int inc) { this.queueID = queueID; this.pageID = pageID; } @@ -3658,65 +3004,53 @@ public class JournalStorageManager implements StorageManager long pageID; - - public void setID(long id) - { + public void setID(long id) { this.id = id; } - public long getID() - { + public long getID() { return id; } - public long getQueueID() - { + public long getQueueID() { return queueID; } - public long getPageID() - { + public long getPageID() { return pageID; } @Override - public int getEncodeSize() - { + public int getEncodeSize() { return DataConstants.SIZE_LONG * 2; } @Override - public void encode(ActiveMQBuffer buffer) - { + public void encode(ActiveMQBuffer buffer) { buffer.writeLong(queueID); buffer.writeLong(pageID); } @Override - public void decode(ActiveMQBuffer buffer) - { + public void decode(ActiveMQBuffer buffer) { queueID = buffer.readLong(); pageID = buffer.readLong(); } } - protected static final class PageCountRecordInc implements EncodingSupport - { + protected static final class PageCountRecordInc implements EncodingSupport { @Override - public String toString() - { + public String toString() { return "PageCountRecordInc [queueID=" + queueID + ", value=" + value + "]"; } - PageCountRecordInc() - { + PageCountRecordInc() { } - PageCountRecordInc(long queueID, int value) - { + PageCountRecordInc(long queueID, int value) { this.queueID = queueID; this.value = value; } @@ -3725,41 +3059,35 @@ public class JournalStorageManager implements StorageManager int value; - public int getEncodeSize() - { + public int getEncodeSize() { return DataConstants.SIZE_LONG + DataConstants.SIZE_INT; } - public void encode(ActiveMQBuffer buffer) - { + public void encode(ActiveMQBuffer buffer) { buffer.writeLong(queueID); buffer.writeInt(value); } - public void decode(ActiveMQBuffer buffer) - { + public void decode(ActiveMQBuffer buffer) { queueID = buffer.readLong(); value = buffer.readInt(); } } - public static class CursorAckRecordEncoding implements EncodingSupport - { - public CursorAckRecordEncoding(final long queueID, final PagePosition position) - { + public static class CursorAckRecordEncoding implements EncodingSupport { + + public CursorAckRecordEncoding(final long queueID, final PagePosition position) { this.queueID = queueID; this.position = position; } - public CursorAckRecordEncoding() - { + public CursorAckRecordEncoding() { this.position = new PagePositionImpl(); } @Override - public String toString() - { + public String toString() { return "CursorAckRecordEncoding [queueID=" + queueID + ", position=" + position + "]"; } @@ -3767,20 +3095,17 @@ public class JournalStorageManager implements StorageManager public PagePosition position; - public int getEncodeSize() - { + public int getEncodeSize() { return DataConstants.SIZE_LONG + DataConstants.SIZE_LONG + DataConstants.SIZE_INT; } - public void encode(ActiveMQBuffer buffer) - { + public void encode(ActiveMQBuffer buffer) { buffer.writeLong(queueID); buffer.writeLong(position.getPageNr()); buffer.writeInt(position.getMessageNr()); } - public void decode(ActiveMQBuffer buffer) - { + public void decode(ActiveMQBuffer buffer) { queueID = buffer.readLong(); long pageNR = buffer.readLong(); int messageNR = buffer.readInt(); @@ -3788,35 +3113,29 @@ public class JournalStorageManager implements StorageManager } } - private class LargeMessageTXFailureCallback implements TransactionFailureCallback - { + private class LargeMessageTXFailureCallback implements TransactionFailureCallback { + private final Map messages; - public LargeMessageTXFailureCallback(final Map messages) - { + public LargeMessageTXFailureCallback(final Map messages) { super(); this.messages = messages; } public void failedTransaction(final long transactionID, final List records, - final List recordsToDelete) - { - for (RecordInfo record : records) - { - if (record.userRecordType == ADD_LARGE_MESSAGE) - { + final List recordsToDelete) { + for (RecordInfo record : records) { + if (record.userRecordType == ADD_LARGE_MESSAGE) { byte[] data = record.data; ActiveMQBuffer buff = ActiveMQBuffers.wrappedBuffer(data); - try - { + try { LargeServerMessage serverMessage = parseLargeMessage(messages, buff); serverMessage.decrementDelayDeletionCount(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.journalError(e); } } @@ -3825,31 +3144,27 @@ public class JournalStorageManager implements StorageManager } - public static final class AckDescribe - { + public static final class AckDescribe { + public RefEncoding refEncoding; - public AckDescribe(RefEncoding refEncoding) - { + public AckDescribe(RefEncoding refEncoding) { this.refEncoding = refEncoding; } @Override - public String toString() - { + public String toString() { return "ACK;" + refEncoding; } } - /** * @param id * @param buffer * @return */ - protected static PersistedRoles newSecurityRecord(long id, ActiveMQBuffer buffer) - { + protected static PersistedRoles newSecurityRecord(long id, ActiveMQBuffer buffer) { PersistedRoles roles = new PersistedRoles(); roles.decode(buffer); roles.setStoreId(id); @@ -3861,8 +3176,7 @@ public class JournalStorageManager implements StorageManager * @param buffer * @return */ - static PersistedAddressSetting newAddressEncoding(long id, ActiveMQBuffer buffer) - { + static PersistedAddressSetting newAddressEncoding(long id, ActiveMQBuffer buffer) { PersistedAddressSetting setting = new PersistedAddressSetting(); setting.decode(buffer); setting.setStoreId(id); @@ -3874,8 +3188,7 @@ public class JournalStorageManager implements StorageManager * @param buffer * @return */ - static GroupingEncoding newGroupEncoding(long id, ActiveMQBuffer buffer) - { + static GroupingEncoding newGroupEncoding(long id, ActiveMQBuffer buffer) { GroupingEncoding encoding = new GroupingEncoding(); encoding.decode(buffer); encoding.setId(id); @@ -3887,8 +3200,7 @@ public class JournalStorageManager implements StorageManager * @param buffer * @return */ - protected static PersistentQueueBindingEncoding newBindingEncoding(long id, ActiveMQBuffer buffer) - { + protected static PersistentQueueBindingEncoding newBindingEncoding(long id, ActiveMQBuffer buffer) { PersistentQueueBindingEncoding bindingEncoding = new PersistentQueueBindingEncoding(); bindingEncoding.decode(buffer); @@ -3898,9 +3210,10 @@ public class JournalStorageManager implements StorageManager } @Override - public boolean - addToPage(PagingStore store, ServerMessage msg, Transaction tx, RouteContextList listCtx) throws Exception - { + public boolean addToPage(PagingStore store, + ServerMessage msg, + Transaction tx, + RouteContextList listCtx) throws Exception { /** * Exposing the read-lock here is an encapsulation violation done in order to keep the code * simpler. The alternative would be to add a second method, say 'verifyPaging', to @@ -3914,32 +3227,26 @@ public class JournalStorageManager implements StorageManager return store.page(msg, tx, listCtx, storageManagerLock.readLock()); } - private void installLargeMessageConfirmationOnTX(Transaction tx, long recordID) - { + private void installLargeMessageConfirmationOnTX(Transaction tx, long recordID) { TXLargeMessageConfirmationOperation txoper = (TXLargeMessageConfirmationOperation) tx.getProperty(TransactionPropertyIndexes.LARGE_MESSAGE_CONFIRMATIONS); - if (txoper == null) - { + if (txoper == null) { txoper = new TXLargeMessageConfirmationOperation(); tx.putProperty(TransactionPropertyIndexes.LARGE_MESSAGE_CONFIRMATIONS, txoper); } txoper.confirmedMessages.add(recordID); } - final class TXLargeMessageConfirmationOperation extends TransactionOperationAbstract - { + final class TXLargeMessageConfirmationOperation extends TransactionOperationAbstract { + public List confirmedMessages = new LinkedList(); @Override - public void afterRollback(Transaction tx) - { - for (Long msg : confirmedMessages) - { - try - { + public void afterRollback(Transaction tx) { + for (Long msg : confirmedMessages) { + try { JournalStorageManager.this.confirmPendingLargeMessage(msg); } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQServerLogger.LOGGER.journalErrorConfirmingLargeMessage(e, msg); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/LargeServerMessageImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/LargeServerMessageImpl.java index c4aa058cfe..719694d2a3 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/LargeServerMessageImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/LargeServerMessageImpl.java @@ -34,8 +34,8 @@ import org.apache.activemq.artemis.core.server.impl.ServerMessageImpl; import org.apache.activemq.artemis.utils.DataConstants; import org.apache.activemq.artemis.utils.TypedProperties; -public final class LargeServerMessageImpl extends ServerMessageImpl implements LargeServerMessage -{ +public final class LargeServerMessageImpl extends ServerMessageImpl implements LargeServerMessage { + // Constants ----------------------------------------------------- private static boolean isTrace = ActiveMQServerLogger.LOGGER.isTraceEnabled(); @@ -62,8 +62,7 @@ public final class LargeServerMessageImpl extends ServerMessageImpl implements L // Constructors -------------------------------------------------- - public LargeServerMessageImpl(final JournalStorageManager storageManager) - { + public LargeServerMessageImpl(final JournalStorageManager storageManager) { this.storageManager = storageManager; } @@ -74,8 +73,10 @@ public final class LargeServerMessageImpl extends ServerMessageImpl implements L * @param copy * @param fileCopy */ - private LargeServerMessageImpl(final LargeServerMessageImpl copy, TypedProperties properties, final SequentialFile fileCopy, final long newID) - { + private LargeServerMessageImpl(final LargeServerMessageImpl copy, + TypedProperties properties, + final SequentialFile fileCopy, + final long newID) { super(copy, properties); storageManager = copy.storageManager; file = fileCopy; @@ -88,28 +89,23 @@ public final class LargeServerMessageImpl extends ServerMessageImpl implements L /** * @param pendingRecordID */ - public void setPendingRecordID(long pendingRecordID) - { + public void setPendingRecordID(long pendingRecordID) { this.pendingRecordID = pendingRecordID; } - public long getPendingRecordID() - { + public long getPendingRecordID() { return this.pendingRecordID; } - public void setPaged() - { + public void setPaged() { paged = true; } @Override - public synchronized void addBytes(final byte[] bytes) throws Exception - { + public synchronized void addBytes(final byte[] bytes) throws Exception { validateFile(); - if (!file.isOpen()) - { + if (!file.isOpen()) { file.open(); } @@ -118,10 +114,8 @@ public final class LargeServerMessageImpl extends ServerMessageImpl implements L bodySize += bytes.length; } - public void encodeBody(final ActiveMQBuffer bufferOut, final BodyEncoder context, final int size) - { - try - { + public void encodeBody(final ActiveMQBuffer bufferOut, final BodyEncoder context, final int size) { + try { // This could maybe be optimized (maybe reading directly into bufferOut) ByteBuffer bufferRead = ByteBuffer.allocate(size); @@ -129,100 +123,82 @@ public final class LargeServerMessageImpl extends ServerMessageImpl implements L bufferRead.flip(); - if (bytesRead > 0) - { + if (bytesRead > 0) { bufferOut.writeBytes(bufferRead.array(), 0, bytesRead); } } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } @Override - public synchronized int getEncodeSize() - { + public synchronized int getEncodeSize() { return getHeadersAndPropertiesEncodeSize(); } @Override - public void encode(final ActiveMQBuffer buffer1) - { + public void encode(final ActiveMQBuffer buffer1) { super.encodeHeadersAndProperties(buffer1); } @Override - public void decode(final ActiveMQBuffer buffer1) - { + public void decode(final ActiveMQBuffer buffer1) { file = null; super.decodeHeadersAndProperties(buffer1); } - public synchronized void incrementDelayDeletionCount() - { + public synchronized void incrementDelayDeletionCount() { delayDeletionCount.incrementAndGet(); - try - { + try { incrementRefCount(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorIncrementDelayDeletionCount(e); } } - public synchronized void decrementDelayDeletionCount() throws Exception - { + public synchronized void decrementDelayDeletionCount() throws Exception { int count = delayDeletionCount.decrementAndGet(); decrementRefCount(); - if (count == 0) - { + if (count == 0) { checkDelete(); } } @Override - public BodyEncoder getBodyEncoder() throws ActiveMQException - { + public BodyEncoder getBodyEncoder() throws ActiveMQException { validateFile(); return new DecodingContext(); } - private void checkDelete() throws Exception - { - if (getRefCount() <= 0) - { - if (LargeServerMessageImpl.isTrace) - { + private void checkDelete() throws Exception { + if (getRefCount() <= 0) { + if (LargeServerMessageImpl.isTrace) { ActiveMQServerLogger.LOGGER.trace("Deleting file " + file + " as the usage was complete"); } - try - { + try { deleteFile(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.error(e.getMessage(), e); } } } @Override - public synchronized int decrementRefCount() throws Exception - { + public synchronized int decrementRefCount() throws Exception { int currentRefCount = super.decrementRefCount(); // We use <= as this could be used by load. // because of a failure, no references were loaded, so we have 0... and we still need to delete the associated // files - if (delayDeletionCount.get() <= 0) - { + if (delayDeletionCount.get() <= 0) { checkDelete(); } @@ -230,14 +206,12 @@ public final class LargeServerMessageImpl extends ServerMessageImpl implements L } @Override - public boolean isLargeMessage() - { + public boolean isLargeMessage() { return true; } @Override - public synchronized void deleteFile() throws Exception - { + public synchronized void deleteFile() throws Exception { validateFile(); releaseResources(); storageManager.deleteLargeMessageFile(this); @@ -247,84 +221,66 @@ public final class LargeServerMessageImpl extends ServerMessageImpl implements L private volatile int memoryEstimate = -1; @Override - public synchronized int getMemoryEstimate() - { - if (memoryEstimate == -1) - { + public synchronized int getMemoryEstimate() { + if (memoryEstimate == -1) { // The body won't be on memory (aways on-file), so we don't consider this for paging memoryEstimate = getHeadersAndPropertiesEncodeSize() + DataConstants.SIZE_INT + getEncodeSize() + - (16 + 4) * - 2 + + (16 + 4) * 2 + 1; } return memoryEstimate; } - public synchronized void releaseResources() - { - if (file != null && file.isOpen()) - { - try - { + public synchronized void releaseResources() { + if (file != null && file.isOpen()) { + try { file.close(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.largeMessageErrorReleasingResources(e); } } } - @Override - public void setOriginalHeaders(final ServerMessage other, final MessageReference originalReference, final boolean expiry) - { + public void setOriginalHeaders(final ServerMessage other, + final MessageReference originalReference, + final boolean expiry) { super.setOriginalHeaders(other, originalReference, expiry); LargeServerMessageImpl otherLM = (LargeServerMessageImpl) other; this.paged = otherLM.paged; - if (this.paged) - { + if (this.paged) { this.removeProperty(Message.HDR_ORIG_MESSAGE_ID); } } @Override - public synchronized ServerMessage copy() - { + public synchronized ServerMessage copy() { SequentialFile newfile = storageManager.createFileForLargeMessage(messageID, durable); - ServerMessage newMessage = new LargeServerMessageImpl(this, - properties, - newfile, - messageID); + ServerMessage newMessage = new LargeServerMessageImpl(this, properties, newfile, messageID); return newMessage; } - public void copyFrom(final SequentialFile fileSource) throws Exception - { + public void copyFrom(final SequentialFile fileSource) throws Exception { this.bodySize = -1; this.pendingCopy = fileSource; } - @Override - public void finishCopy() throws Exception - { - if (pendingCopy != null) - { + public void finishCopy() throws Exception { + if (pendingCopy != null) { SequentialFile copyTo = createFile(); - try - { + try { this.pendingRecordID = storageManager.storePendingLargeMessage(this.messageID); copyTo.open(); pendingCopy.open(); pendingCopy.copyTo(copyTo); } - finally - { + finally { copyTo.close(); pendingCopy.close(); pendingCopy = null; @@ -340,62 +296,48 @@ public final class LargeServerMessageImpl extends ServerMessageImpl implements L * The copy of the file itself will be done later by {@link LargeServerMessageImpl#finishCopy()} */ @Override - public synchronized ServerMessage copy(final long newID) - { - try - { + public synchronized ServerMessage copy(final long newID) { + try { SequentialFile newfile = storageManager.createFileForLargeMessage(newID, durable); - LargeServerMessageImpl newMessage = new LargeServerMessageImpl(this, - properties, - newfile, - newID); + LargeServerMessageImpl newMessage = new LargeServerMessageImpl(this, properties, newfile, newID); newMessage.copyFrom(createFile()); return newMessage; } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.lareMessageErrorCopying(e, this); return null; } } - public SequentialFile getFile() throws ActiveMQException - { + public SequentialFile getFile() throws ActiveMQException { validateFile(); return file; } @Override - public String toString() - { + public String toString() { return "LargeServerMessage[messageID=" + messageID + ",priority=" + this.getPriority() + ",expiration=[" + (this.getExpiration() != 0 ? new java.util.Date(this.getExpiration()) : "null") + "]" + ", durable=" + durable + ", address=" + getAddress() + ",properties=" + properties.toString() + "]@" + System.identityHashCode(this); } - // Package protected --------------------------------------------- // Protected ----------------------------------------------------- @Override - protected void finalize() throws Throwable - { + protected void finalize() throws Throwable { releaseResources(); super.finalize(); } // Private ------------------------------------------------------- - private synchronized void validateFile() throws ActiveMQException - { - try - { - if (file == null) - { - if (messageID <= 0) - { + private synchronized void validateFile() throws ActiveMQException { + try { + if (file == null) { + if (messageID <= 0) { throw new RuntimeException("MessageID not set on LargeMessage"); } @@ -406,8 +348,7 @@ public final class LargeServerMessageImpl extends ServerMessageImpl implements L bodySize = file.size(); } } - catch (Exception e) - { + catch (Exception e) { // TODO: There is an IO_ERROR on trunk now, this should be used here instead throw new ActiveMQInternalErrorException(e.getMessage(), e); } @@ -416,83 +357,65 @@ public final class LargeServerMessageImpl extends ServerMessageImpl implements L /** * */ - protected SequentialFile createFile() - { + protected SequentialFile createFile() { return storageManager.createFileForLargeMessage(getMessageID(), durable); } - protected void openFile() throws Exception - { - if (file == null) - { + protected void openFile() throws Exception { + if (file == null) { validateFile(); } - else if (!file.isOpen()) - { + else if (!file.isOpen()) { file.open(); } } - protected void closeFile() throws Exception - { - if (file != null && file.isOpen()) - { + protected void closeFile() throws Exception { + if (file != null && file.isOpen()) { file.close(); } } // Inner classes ------------------------------------------------- - class DecodingContext implements BodyEncoder - { + class DecodingContext implements BodyEncoder { + private SequentialFile cFile; - public void open() throws ActiveMQException - { - try - { - if (cFile != null && cFile.isOpen()) - { + public void open() throws ActiveMQException { + try { + if (cFile != null && cFile.isOpen()) { cFile.close(); } cFile = file.cloneFile(); cFile.open(); } - catch (Exception e) - { + catch (Exception e) { throw new ActiveMQException(ActiveMQExceptionType.INTERNAL_ERROR, e.getMessage(), e); } } - public void close() throws ActiveMQException - { - try - { - if (cFile != null) - { + public void close() throws ActiveMQException { + try { + if (cFile != null) { cFile.close(); } } - catch (Exception e) - { + catch (Exception e) { throw new ActiveMQInternalErrorException(e.getMessage(), e); } } - public int encode(final ByteBuffer bufferRead) throws ActiveMQException - { - try - { + public int encode(final ByteBuffer bufferRead) throws ActiveMQException { + try { return cFile.read(bufferRead); } - catch (Exception e) - { + catch (Exception e) { throw new ActiveMQInternalErrorException(e.getMessage(), e); } } - public int encode(final ActiveMQBuffer bufferOut, final int size) throws ActiveMQException - { + public int encode(final ActiveMQBuffer bufferOut, final int size) throws ActiveMQException { // This could maybe be optimized (maybe reading directly into bufferOut) ByteBuffer bufferRead = ByteBuffer.allocate(size); @@ -500,8 +423,7 @@ public final class LargeServerMessageImpl extends ServerMessageImpl implements L bufferRead.flip(); - if (bytesRead > 0) - { + if (bytesRead > 0) { bufferOut.writeBytes(bufferRead.array(), 0, bytesRead); } @@ -511,16 +433,12 @@ public final class LargeServerMessageImpl extends ServerMessageImpl implements L /* (non-Javadoc) * @see org.apache.activemq.artemis.core.message.BodyEncoder#getLargeBodySize() */ - public long getLargeBodySize() - { - if (bodySize < 0) - { - try - { + public long getLargeBodySize() { + if (bodySize < 0) { + try { bodySize = file.size(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/LargeServerMessageInSync.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/LargeServerMessageInSync.java index b034660424..f264415052 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/LargeServerMessageInSync.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/LargeServerMessageInSync.java @@ -27,8 +27,8 @@ import org.apache.activemq.artemis.core.replication.ReplicatedLargeMessage; import org.apache.activemq.artemis.core.server.ActiveMQServerLogger; import org.apache.activemq.artemis.core.server.LargeServerMessage; -public final class LargeServerMessageInSync implements ReplicatedLargeMessage -{ +public final class LargeServerMessageInSync implements ReplicatedLargeMessage { + private final LargeServerMessage mainLM; private final StorageManager storageManager; private SequentialFile appendFile; @@ -38,33 +38,27 @@ public final class LargeServerMessageInSync implements ReplicatedLargeMessage /** * @param storageManager */ - public LargeServerMessageInSync(StorageManager storageManager) - { + public LargeServerMessageInSync(StorageManager storageManager) { mainLM = storageManager.createLargeMessage(); this.storageManager = storageManager; } - public synchronized void joinSyncedData(ByteBuffer buffer) throws Exception - { + public synchronized void joinSyncedData(ByteBuffer buffer) throws Exception { if (deleted) return; SequentialFile mainSeqFile = mainLM.getFile(); - if (!mainSeqFile.isOpen()) - { + if (!mainSeqFile.isOpen()) { mainSeqFile.open(); } - if (appendFile != null) - { + if (appendFile != null) { appendFile.close(); appendFile.open(); - for (;;) - { + for (;;) { buffer.rewind(); int bytesRead = appendFile.read(buffer); if (bytesRead > 0) mainSeqFile.writeDirect(buffer, false); - if (bytesRead < buffer.capacity()) - { + if (bytesRead < buffer.capacity()) { break; } } @@ -73,52 +67,42 @@ public final class LargeServerMessageInSync implements ReplicatedLargeMessage syncDone = true; } - public SequentialFile getSyncFile() throws ActiveMQException - { + public SequentialFile getSyncFile() throws ActiveMQException { return mainLM.getFile(); } @Override - public Message setDurable(boolean durable) - { + public Message setDurable(boolean durable) { mainLM.setDurable(durable); return mainLM; } @Override - public synchronized Message setMessageID(long id) - { + public synchronized Message setMessageID(long id) { mainLM.setMessageID(id); return mainLM; } @Override - public synchronized void releaseResources() - { + public synchronized void releaseResources() { mainLM.releaseResources(); - if (appendFile != null && appendFile.isOpen()) - { - try - { + if (appendFile != null && appendFile.isOpen()) { + try { appendFile.close(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.largeMessageErrorReleasingResources(e); } } } @Override - public synchronized void deleteFile() throws Exception - { + public synchronized void deleteFile() throws Exception { deleted = true; - try - { + try { mainLM.deleteFile(); } - finally - { + finally { deleteAppendFile(); } } @@ -126,10 +110,8 @@ public final class LargeServerMessageInSync implements ReplicatedLargeMessage /** * @throws Exception */ - private void deleteAppendFile() throws Exception - { - if (appendFile != null) - { + private void deleteAppendFile() throws Exception { + if (appendFile != null) { if (appendFile.isOpen()) appendFile.close(); appendFile.delete(); @@ -137,23 +119,19 @@ public final class LargeServerMessageInSync implements ReplicatedLargeMessage } @Override - public synchronized void addBytes(byte[] bytes) throws Exception - { + public synchronized void addBytes(byte[] bytes) throws Exception { if (deleted) return; - if (syncDone) - { + if (syncDone) { mainLM.addBytes(bytes); return; } - if (appendFile == null) - { + if (appendFile == null) { appendFile = storageManager.createFileForLargeMessage(mainLM.getMessageID(), LargeMessageExtension.SYNC); } - if (!appendFile.isOpen()) - { + if (!appendFile.isOpen()) { appendFile.open(); } storageManager.addBytesToLargeMessage(appendFile, mainLM.getMessageID(), bytes); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/OperationContextImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/OperationContextImpl.java index a8e8e2a96b..fc49adadb9 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/OperationContextImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/OperationContextImpl.java @@ -32,7 +32,6 @@ import org.apache.activemq.artemis.core.server.ActiveMQServerLogger; import org.apache.activemq.artemis.utils.ExecutorFactory; /** - * * Each instance of OperationContextImpl is associated with an executor (usually an ordered Executor). * * Tasks are hold until the operations are complete and executed in the natural order as soon as the operations are returned @@ -42,31 +41,25 @@ import org.apache.activemq.artemis.utils.ExecutorFactory; * * So, if you are doing operations that are not dependent on IO (e.g NonPersistentMessages) you wouldn't have any context switch. */ -public class OperationContextImpl implements OperationContext -{ +public class OperationContextImpl implements OperationContext { + private static final ThreadLocal threadLocalContext = new ThreadLocal(); - public static void clearContext() - { + public static void clearContext() { OperationContextImpl.threadLocalContext.set(null); } - public static final OperationContext getContext() - { + public static final OperationContext getContext() { return getContext(null); } - public static OperationContext getContext(final ExecutorFactory executorFactory) - { + public static OperationContext getContext(final ExecutorFactory executorFactory) { OperationContext token = OperationContextImpl.threadLocalContext.get(); - if (token == null) - { - if (executorFactory == null) - { + if (token == null) { + if (executorFactory == null) { return null; } - else - { + else { token = new OperationContextImpl(executorFactory.getExecutor()); OperationContextImpl.threadLocalContext.set(token); } @@ -74,8 +67,7 @@ public class OperationContextImpl implements OperationContext return token; } - public static void setContext(final OperationContext context) - { + public static void setContext(final OperationContext context) { OperationContextImpl.threadLocalContext.set(context); } @@ -101,53 +93,43 @@ public class OperationContextImpl implements OperationContext private final AtomicInteger executorsPending = new AtomicInteger(0); - public OperationContextImpl(final Executor executor) - { + public OperationContextImpl(final Executor executor) { super(); this.executor = executor; } - public void pageSyncLineUp() - { + public void pageSyncLineUp() { pageLineUp.incrementAndGet(); } - public synchronized void pageSyncDone() - { + public synchronized void pageSyncDone() { paged++; checkTasks(); } - public void storeLineUp() - { + public void storeLineUp() { storeLineUp.incrementAndGet(); } - public void replicationLineUp() - { + public void replicationLineUp() { replicationLineUp.incrementAndGet(); } - public synchronized void replicationDone() - { + public synchronized void replicationDone() { replicated++; checkTasks(); } - public void executeOnCompletion(final IOCallback completion) - { - if (errorCode != -1) - { + public void executeOnCompletion(final IOCallback completion) { + if (errorCode != -1) { completion.onError(errorCode, errorMessage); return; } boolean executeNow = false; - synchronized (this) - { - if (tasks == null) - { + synchronized (this) { + if (tasks == null) { tasks = new LinkedList(); minimalReplicated = replicationLineUp.intValue(); minimalStore = storeLineUp.intValue(); @@ -156,59 +138,48 @@ public class OperationContextImpl implements OperationContext // On this case, we can just execute the context directly if (replicationLineUp.intValue() == replicated && storeLineUp.intValue() == stored && - pageLineUp.intValue() == paged) - { + pageLineUp.intValue() == paged) { // We want to avoid the executor if everything is complete... // However, we can't execute the context if there are executions pending // We need to use the executor on this case - if (executorsPending.get() == 0) - { + if (executorsPending.get() == 0) { // No need to use an executor here or a context switch // there are no actions pending.. hence we can just execute the task directly on the same thread executeNow = true; } - else - { + else { execute(completion); } } - else - { + else { tasks.add(new TaskHolder(completion)); } } - if (executeNow) - { + if (executeNow) { // Executing outside of any locks completion.done(); } } - public synchronized void done() - { + public synchronized void done() { stored++; checkTasks(); } - private void checkTasks() - { - if (stored >= minimalStore && replicated >= minimalReplicated && paged >= minimalPage) - { + private void checkTasks() { + if (stored >= minimalStore && replicated >= minimalReplicated && paged >= minimalPage) { Iterator iter = tasks.iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { TaskHolder holder = iter.next(); - if (stored >= holder.storeLined && replicated >= holder.replicationLined && paged >= holder.pageLined) - { + if (stored >= holder.storeLined && replicated >= holder.replicationLined && paged >= holder.pageLined) { // If set, we use an executor to avoid the server being single threaded execute(holder.task); iter.remove(); } - else - { + else { // End of list here. No other task will be completed after this break; } @@ -219,34 +190,26 @@ public class OperationContextImpl implements OperationContext /** * @param task */ - private void execute(final IOCallback task) - { + private void execute(final IOCallback task) { executorsPending.incrementAndGet(); - try - { - executor.execute(new Runnable() - { - public void run() - { - try - { + try { + executor.execute(new Runnable() { + public void run() { + try { // If any IO is done inside the callback, it needs to be done on a new context OperationContextImpl.clearContext(); task.done(); } - finally - { + finally { executorsPending.decrementAndGet(); } } }); } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQServerLogger.LOGGER.errorExecutingAIOCallback(e); executorsPending.decrementAndGet(); - task.onError(ActiveMQExceptionType.INTERNAL_ERROR.getCode(), - "It wasn't possible to complete IO operation - " + e.getMessage()); + task.onError(ActiveMQExceptionType.INTERNAL_ERROR.getCode(), "It wasn't possible to complete IO operation - " + e.getMessage()); } } @@ -254,21 +217,17 @@ public class OperationContextImpl implements OperationContext * (non-Javadoc) * @see org.apache.activemq.artemis.core.replication.ReplicationToken#complete() */ - public void complete() - { + public void complete() { } @Override - public synchronized void onError(final int errorCode, final String errorMessage) - { + public synchronized void onError(final int errorCode, final String errorMessage) { this.errorCode = errorCode; this.errorMessage = errorMessage; - if (tasks != null) - { + if (tasks != null) { Iterator iter = tasks.iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { TaskHolder holder = iter.next(); holder.task.onError(errorCode, errorMessage); iter.remove(); @@ -276,20 +235,18 @@ public class OperationContextImpl implements OperationContext } } - final class TaskHolder - { + final class TaskHolder { @Override - public String toString() - { + public String toString() { return "TaskHolder [storeLined=" + storeLined + - ", replicationLined=" + - replicationLined + - ", pageLined=" + - pageLined + - ", task=" + - task + - "]"; + ", replicationLined=" + + replicationLined + + ", pageLined=" + + pageLined + + ", task=" + + task + + "]"; } final int storeLined; @@ -298,8 +255,7 @@ public class OperationContextImpl implements OperationContext final IOCallback task; - TaskHolder(final IOCallback task) - { + TaskHolder(final IOCallback task) { storeLined = storeLineUp.intValue(); replicationLined = replicationLineUp.intValue(); pageLined = pageLineUp.intValue(); @@ -308,64 +264,57 @@ public class OperationContextImpl implements OperationContext } @Override - public void waitCompletion() throws Exception - { + public void waitCompletion() throws Exception { waitCompletion(0); } @Override - public boolean waitCompletion(final long timeout) throws InterruptedException, ActiveMQException - { + public boolean waitCompletion(final long timeout) throws InterruptedException, ActiveMQException { SimpleWaitIOCallback waitCallback = new SimpleWaitIOCallback(); executeOnCompletion(waitCallback); complete(); - if (timeout == 0) - { + if (timeout == 0) { waitCallback.waitCompletion(); return true; } - else - { + else { return waitCallback.waitCompletion(timeout); } } @Override - public String toString() - { + public String toString() { StringBuffer buffer = new StringBuffer(); - if (tasks != null) - { - for (TaskHolder hold : tasks) - { + if (tasks != null) { + for (TaskHolder hold : tasks) { buffer.append("Task = " + hold + "\n"); } } return "OperationContextImpl [" + hashCode() + "] [minimalStore=" + minimalStore + - ", storeLineUp=" + - storeLineUp + - ", stored=" + - stored + - ", minimalReplicated=" + - minimalReplicated + - ", replicationLineUp=" + - replicationLineUp + - ", replicated=" + - replicated + - ", paged=" + - paged + - ", minimalPage=" + - minimalPage + - ", pageLineUp=" + - pageLineUp + - ", errorCode=" + - errorCode + - ", errorMessage=" + - errorMessage + - ", executorsPending=" + - executorsPending + - ", executor=" + this.executor + - "]" + buffer.toString(); + ", storeLineUp=" + + storeLineUp + + ", stored=" + + stored + + ", minimalReplicated=" + + minimalReplicated + + ", replicationLineUp=" + + replicationLineUp + + ", replicated=" + + replicated + + ", paged=" + + paged + + ", minimalPage=" + + minimalPage + + ", pageLineUp=" + + pageLineUp + + ", errorCode=" + + errorCode + + ", errorMessage=" + + errorMessage + + ", executorsPending=" + + executorsPending + + ", executor=" + this.executor + + "]" + buffer.toString(); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/nullpm/NullStorageLargeServerMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/nullpm/NullStorageLargeServerMessage.java index 25cd0fc593..3eb14da561 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/nullpm/NullStorageLargeServerMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/nullpm/NullStorageLargeServerMessage.java @@ -22,29 +22,23 @@ import org.apache.activemq.artemis.core.server.LargeServerMessage; import org.apache.activemq.artemis.core.server.ServerMessage; import org.apache.activemq.artemis.core.server.impl.ServerMessageImpl; -class NullStorageLargeServerMessage extends ServerMessageImpl implements LargeServerMessage -{ +class NullStorageLargeServerMessage extends ServerMessageImpl implements LargeServerMessage { - public NullStorageLargeServerMessage() - { + public NullStorageLargeServerMessage() { super(); } - public NullStorageLargeServerMessage(NullStorageLargeServerMessage other) - { + public NullStorageLargeServerMessage(NullStorageLargeServerMessage other) { super(other); } @Override - public void releaseResources() - { + public void releaseResources() { } @Override - public synchronized void addBytes(final byte[] bytes) - { - if (buffer == null) - { + public synchronized void addBytes(final byte[] bytes) { + if (buffer == null) { buffer = ActiveMQBuffers.dynamicBuffer(bytes.length); } @@ -53,67 +47,55 @@ class NullStorageLargeServerMessage extends ServerMessageImpl implements LargeSe } @Override - public void deleteFile() throws Exception - { + public void deleteFile() throws Exception { // nothing to be done here.. we don really have a file on this Storage } @Override - public boolean isLargeMessage() - { + public boolean isLargeMessage() { return true; } @Override - public void decrementDelayDeletionCount() - { + public void decrementDelayDeletionCount() { } @Override - public void incrementDelayDeletionCount() - { + public void incrementDelayDeletionCount() { } @Override - public synchronized int getEncodeSize() - { + public synchronized int getEncodeSize() { return getHeadersAndPropertiesEncodeSize(); } @Override - public String toString() - { - return "NullStorageLargeServerMessage[messageID=" + messageID + ", durable=" + durable + ", address=" + getAddress() + ",properties=" + properties.toString() + "]"; + public String toString() { + return "NullStorageLargeServerMessage[messageID=" + messageID + ", durable=" + durable + ", address=" + getAddress() + ",properties=" + properties.toString() + "]"; } - public ServerMessage copy() - { + public ServerMessage copy() { // This is a simple copy, used only to avoid changing original properties return new NullStorageLargeServerMessage(this); } @Override - public void setPaged() - { + public void setPaged() { } @Override - public void setPendingRecordID(long pendingRecordID) - { + public void setPendingRecordID(long pendingRecordID) { } @Override - public long getPendingRecordID() - { + public long getPendingRecordID() { return -1; } - @Override - public SequentialFile getFile() - { + public SequentialFile getFile() { return null; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/nullpm/NullStorageManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/nullpm/NullStorageManager.java index d6336d299a..e6c1fe0cad 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/nullpm/NullStorageManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/nullpm/NullStorageManager.java @@ -56,202 +56,171 @@ import org.apache.activemq.artemis.core.server.impl.JournalLoader; import org.apache.activemq.artemis.core.transaction.ResourceManager; import org.apache.activemq.artemis.core.transaction.Transaction; -public class NullStorageManager implements StorageManager -{ +public class NullStorageManager implements StorageManager { + private final AtomicLong idSequence = new AtomicLong(0); private volatile boolean started; - private static final OperationContext dummyContext = new OperationContext() - { + private static final OperationContext dummyContext = new OperationContext() { @Override - public void onError(final int errorCode, final String errorMessage) - { + public void onError(final int errorCode, final String errorMessage) { } @Override - public void done() - { + public void done() { } @Override - public void storeLineUp() - { + public void storeLineUp() { } @Override - public boolean waitCompletion(final long timeout) throws Exception - { + public boolean waitCompletion(final long timeout) throws Exception { return true; } @Override - public void waitCompletion() throws Exception - { + public void waitCompletion() throws Exception { } @Override - public void replicationLineUp() - { + public void replicationLineUp() { } @Override - public void replicationDone() - { + public void replicationDone() { } @Override - public void pageSyncLineUp() - { + public void pageSyncLineUp() { } @Override - public void pageSyncDone() - { + public void pageSyncDone() { } @Override - public void executeOnCompletion(final IOCallback runnable) - { + public void executeOnCompletion(final IOCallback runnable) { runnable.done(); } }; @Override - public void deleteQueueBinding(long tx, final long queueBindingID) throws Exception - { + public void deleteQueueBinding(long tx, final long queueBindingID) throws Exception { } @Override - public void commit(final long txID) throws Exception - { + public void commit(final long txID) throws Exception { } @Override public JournalLoadInformation loadBindingJournal(final List queueBindingInfos, - final List groupingInfos) throws Exception - { + final List groupingInfos) throws Exception { return new JournalLoadInformation(); } @Override - public void prepare(final long txID, final Xid xid) throws Exception - { + public void prepare(final long txID, final Xid xid) throws Exception { } @Override - public void rollback(final long txID) throws Exception - { + public void rollback(final long txID) throws Exception { } @Override - public void rollbackBindings(final long txID) throws Exception - { + public void rollbackBindings(final long txID) throws Exception { } @Override - public void commitBindings(final long txID) throws Exception - { + public void commitBindings(final long txID) throws Exception { } @Override - public void storeReference(final long queueID, final long messageID, final boolean last) throws Exception - { + public void storeReference(final long queueID, final long messageID, final boolean last) throws Exception { } @Override - public void storeReferenceTransactional(final long txID, final long queueID, final long messageID) throws Exception - { + public void storeReferenceTransactional(final long txID, final long queueID, final long messageID) throws Exception { } @Override - public void storeAcknowledge(final long queueID, final long messageID) throws Exception - { + public void storeAcknowledge(final long queueID, final long messageID) throws Exception { } @Override - public void storeAcknowledgeTransactional(final long txID, final long queueID, final long messageiD) throws Exception - { + public void storeAcknowledgeTransactional(final long txID, + final long queueID, + final long messageiD) throws Exception { } @Override - public void deleteMessage(final long messageID) throws Exception - { + public void deleteMessage(final long messageID) throws Exception { } @Override - public void storeMessage(final ServerMessage message) throws Exception - { + public void storeMessage(final ServerMessage message) throws Exception { } @Override - public void storeMessageTransactional(final long txID, final ServerMessage message) throws Exception - { + public void storeMessageTransactional(final long txID, final ServerMessage message) throws Exception { } @Override - public void updateScheduledDeliveryTime(final MessageReference ref) throws Exception - { + public void updateScheduledDeliveryTime(final MessageReference ref) throws Exception { } @Override - public void updateScheduledDeliveryTimeTransactional(final long txID, final MessageReference ref) throws Exception - { + public void updateScheduledDeliveryTimeTransactional(final long txID, final MessageReference ref) throws Exception { } @Override - public void storePageTransaction(final long txID, final PageTransactionInfo pageTransaction) throws Exception - { + public void storePageTransaction(final long txID, final PageTransactionInfo pageTransaction) throws Exception { } @Override - public void updateDeliveryCount(final MessageReference ref) throws Exception - { + public void updateDeliveryCount(final MessageReference ref) throws Exception { } @Override - public void storeDuplicateID(final SimpleString address, final byte[] duplID, final long recordID) throws Exception - { + public void storeDuplicateID(final SimpleString address, final byte[] duplID, final long recordID) throws Exception { } @Override - public void storeDuplicateIDTransactional(final long txID, final SimpleString address, final byte[] duplID, - final long recordID) throws Exception - { + public void storeDuplicateIDTransactional(final long txID, + final SimpleString address, + final byte[] duplID, + final long recordID) throws Exception { } @Override - public void updateDuplicateIDTransactional(final long txID, final SimpleString address, final byte[] duplID, - final long recordID) throws Exception - { + public void updateDuplicateIDTransactional(final long txID, + final SimpleString address, + final byte[] duplID, + final long recordID) throws Exception { } @Override - public long storeHeuristicCompletion(final Xid xid, final boolean isCommit) throws Exception - { + public long storeHeuristicCompletion(final Xid xid, final boolean isCommit) throws Exception { return generateID(); } @Override - public void deleteHeuristicCompletion(final long txID) throws Exception - { + public void deleteHeuristicCompletion(final long txID) throws Exception { } @Override - public void addQueueBinding(final long tx, final Binding binding) throws Exception - { + public void addQueueBinding(final long tx, final Binding binding) throws Exception { } @Override - public LargeServerMessage createLargeMessage() - { + public LargeServerMessage createLargeMessage() { return new NullStorageLargeServerMessage(); } @Override - public LargeServerMessage createLargeMessage(final long id, final MessageInternal message) - { + public LargeServerMessage createLargeMessage(final long id, final MessageInternal message) { NullStorageLargeServerMessage largeMessage = new NullStorageLargeServerMessage(); largeMessage.copyHeadersAndProperties(message); @@ -262,24 +231,20 @@ public class NullStorageManager implements StorageManager } @Override - public long generateID() - { + public long generateID() { long id = idSequence.getAndIncrement(); return id; } @Override - public long getCurrentID() - { + public long getCurrentID() { return idSequence.get(); } @Override - public synchronized void start() throws Exception - { - if (started) - { + public synchronized void start() throws Exception { + if (started) { throw new IllegalStateException("Already started"); } @@ -287,10 +252,8 @@ public class NullStorageManager implements StorageManager } @Override - public synchronized void stop() throws Exception - { - if (!started) - { + public synchronized void stop() throws Exception { + if (!started) { throw new IllegalStateException("Not started"); } @@ -300,335 +263,283 @@ public class NullStorageManager implements StorageManager } @Override - public synchronized boolean isStarted() - { + public synchronized boolean isStarted() { return started; } @Override - public JournalLoadInformation loadMessageJournal(final PostOffice postOffice, final PagingManager pagingManager, + public JournalLoadInformation loadMessageJournal(final PostOffice postOffice, + final PagingManager pagingManager, final ResourceManager resourceManager, final Map queueInfos, final Map>> duplicateIDMap, final Set> pendingLargeMessages, List pendingNonTXPageCounter, - final JournalLoader journalLoader) throws Exception - { + final JournalLoader journalLoader) throws Exception { return new JournalLoadInformation(); } @Override - public void deleteDuplicateIDTransactional(final long txID, final long recordID) throws Exception - { + public void deleteDuplicateIDTransactional(final long txID, final long recordID) throws Exception { } @Override - public void deleteDuplicateID(final long recordID) throws Exception - { + public void deleteDuplicateID(final long recordID) throws Exception { } @Override - public void pageClosed(final SimpleString storeName, final int pageNumber) - { + public void pageClosed(final SimpleString storeName, final int pageNumber) { } @Override - public void pageDeleted(final SimpleString storeName, final int pageNumber) - { + public void pageDeleted(final SimpleString storeName, final int pageNumber) { } @Override - public void pageWrite(final PagedMessage message, final int pageNumber) - { + public void pageWrite(final PagedMessage message, final int pageNumber) { } @Override - public void addGrouping(final GroupBinding groupBinding) throws Exception - { + public void addGrouping(final GroupBinding groupBinding) throws Exception { } @Override - public void deleteGrouping(final long tx, final GroupBinding groupBinding) throws Exception - { + public void deleteGrouping(final long tx, final GroupBinding groupBinding) throws Exception { } @Override - public boolean waitOnOperations(final long timeout) throws Exception - { + public boolean waitOnOperations(final long timeout) throws Exception { return true; } @Override - public void afterCompleteOperations(final IOCallback run) - { + public void afterCompleteOperations(final IOCallback run) { run.done(); } @Override - public void waitOnOperations() throws Exception - { + public void waitOnOperations() throws Exception { } @Override - public OperationContext getContext() - { + public OperationContext getContext() { return NullStorageManager.dummyContext; } @Override - public OperationContext newContext(final Executor executor) - { + public OperationContext newContext(final Executor executor) { return NullStorageManager.dummyContext; } @Override - public OperationContext newSingleThreadContext() - { + public OperationContext newSingleThreadContext() { return NullStorageManager.dummyContext; } @Override - public void setContext(final OperationContext context) - { + public void setContext(final OperationContext context) { } @Override - public void clearContext() - { + public void clearContext() { } @Override - public List recoverAddressSettings() throws Exception - { + public List recoverAddressSettings() throws Exception { return Collections.emptyList(); } @Override - public void storeAddressSetting(final PersistedAddressSetting addressSetting) throws Exception - { + public void storeAddressSetting(final PersistedAddressSetting addressSetting) throws Exception { } @Override - public List recoverPersistedRoles() throws Exception - { + public List recoverPersistedRoles() throws Exception { return Collections.emptyList(); } @Override - public void storeSecurityRoles(final PersistedRoles persistedRoles) throws Exception - { + public void storeSecurityRoles(final PersistedRoles persistedRoles) throws Exception { } @Override - public void deleteAddressSetting(final SimpleString addressMatch) throws Exception - { + public void deleteAddressSetting(final SimpleString addressMatch) throws Exception { } @Override - public void deleteSecurityRoles(final SimpleString addressMatch) throws Exception - { + public void deleteSecurityRoles(final SimpleString addressMatch) throws Exception { } @Override - public void deletePageTransactional(final long recordID) throws Exception - { + public void deletePageTransactional(final long recordID) throws Exception { } @Override - public void - updatePageTransaction(final long txID, final PageTransactionInfo pageTransaction, final int depage) throws Exception - { + public void updatePageTransaction(final long txID, + final PageTransactionInfo pageTransaction, + final int depage) throws Exception { } @Override - public void storeCursorAcknowledge(final long queueID, final PagePosition position) - { + public void storeCursorAcknowledge(final long queueID, final PagePosition position) { } @Override - public void storeCursorAcknowledgeTransactional(final long txID, final long queueID, final PagePosition position) - { + public void storeCursorAcknowledgeTransactional(final long txID, final long queueID, final PagePosition position) { } @Override - public void deleteCursorAcknowledgeTransactional(final long txID, final long ackID) throws Exception - { + public void deleteCursorAcknowledgeTransactional(final long txID, final long ackID) throws Exception { } @Override - public void deleteCursorAcknowledge(long ackID) throws Exception - { + public void deleteCursorAcknowledge(long ackID) throws Exception { } - public void storePageCompleteTransactional(long txID, long queueID, PagePosition position) throws Exception - { + public void storePageCompleteTransactional(long txID, long queueID, PagePosition position) throws Exception { } - public void deletePageComplete(long ackID) throws Exception - { + public void deletePageComplete(long ackID) throws Exception { } @Override - public void updatePageTransaction(final PageTransactionInfo pageTransaction, final int depage) throws Exception - { + public void updatePageTransaction(final PageTransactionInfo pageTransaction, final int depage) throws Exception { } @Override - public long storePageCounter(final long txID, final long queueID, final long value) throws Exception - { + public long storePageCounter(final long txID, final long queueID, final long value) throws Exception { return 0; } @Override - public long storePendingCounter(long queueID, long pageID, int inc) throws Exception - { + public long storePendingCounter(long queueID, long pageID, int inc) throws Exception { return -1; } @Override - public void deleteIncrementRecord(final long txID, final long recordID) throws Exception - { + public void deleteIncrementRecord(final long txID, final long recordID) throws Exception { } @Override - public void deletePageCounter(final long txID, final long recordID) throws Exception - { + public void deletePageCounter(final long txID, final long recordID) throws Exception { } - public void deletePendingPageCounter(long txID, long recordID) throws Exception - { + public void deletePendingPageCounter(long txID, long recordID) throws Exception { } @Override - public long storePageCounterInc(final long txID, final long queueID, final int add) throws Exception - { + public long storePageCounterInc(final long txID, final long queueID, final int add) throws Exception { return 0; } @Override - public long storePageCounterInc(final long queueID, final int add) throws Exception - { + public long storePageCounterInc(final long queueID, final int add) throws Exception { return 0; } @Override - public void commit(final long txID, final boolean lineUpContext) throws Exception - { + public void commit(final long txID, final boolean lineUpContext) throws Exception { } @Override - public void lineUpContext() - { + public void lineUpContext() { } @Override - public void - confirmPendingLargeMessageTX(final Transaction transaction, final long messageID, final long recordID) throws Exception - { + public void confirmPendingLargeMessageTX(final Transaction transaction, + final long messageID, + final long recordID) throws Exception { } @Override - public void confirmPendingLargeMessage(final long recordID) throws Exception - { + public void confirmPendingLargeMessage(final long recordID) throws Exception { } @Override - public void stop(final boolean ioCriticalError) throws Exception - { + public void stop(final boolean ioCriticalError) throws Exception { } @Override - public Journal getBindingsJournal() - { + public Journal getBindingsJournal() { return null; } @Override - public Journal getMessageJournal() - { + public Journal getMessageJournal() { return null; } @Override - public void startReplication(final ReplicationManager replicationManager, final PagingManager pagingManager, - final String nodeID, final boolean autoFailBack) throws Exception - { + public void startReplication(final ReplicationManager replicationManager, + final PagingManager pagingManager, + final String nodeID, + final boolean autoFailBack) throws Exception { // no-op } @Override - public boolean addToPage(PagingStore s, ServerMessage msg, Transaction tx, RouteContextList listCtx) throws Exception - { + public boolean addToPage(PagingStore s, + ServerMessage msg, + Transaction tx, + RouteContextList listCtx) throws Exception { return false; } @Override - public void stopReplication() - { + public void stopReplication() { // no-op } @Override - public SequentialFile createFileForLargeMessage(final long messageID, final LargeMessageExtension extension) - { + public SequentialFile createFileForLargeMessage(final long messageID, final LargeMessageExtension extension) { throw new UnsupportedOperationException(); } @Override - public void addBytesToLargeMessage(SequentialFile appendFile, long messageID, byte[] bytes) throws Exception - { + public void addBytesToLargeMessage(SequentialFile appendFile, long messageID, byte[] bytes) throws Exception { // no-op } @Override - public void beforePageRead() throws Exception - { + public void beforePageRead() throws Exception { } @Override - public void afterPageRead() throws Exception - { + public void afterPageRead() throws Exception { } @Override - public ByteBuffer allocateDirectBuffer(final int size) - { + public ByteBuffer allocateDirectBuffer(final int size) { return ByteBuffer.allocateDirect(size); } @Override - public void freeDirectBuffer(final ByteBuffer buffer) - { + public void freeDirectBuffer(final ByteBuffer buffer) { // We can just have hope on GC here :-) } @Override - public void storeID(final long journalID, final long id) throws Exception - { + public void storeID(final long journalID, final long id) throws Exception { // no-op } @Override - public void readLock() - { + public void readLock() { // no-op } @Override - public void readUnLock() - { + public void readUnLock() { // no-op } @Override - public void persistIdGenerator() - { + public void persistIdGenerator() { // no-op } @Override - public void deleteID(long journalD) throws Exception - { + public void deleteID(long journalD) throws Exception { } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/Address.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/Address.java index 94c7ae33c4..8ebcab79f5 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/Address.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/Address.java @@ -23,8 +23,8 @@ import org.apache.activemq.artemis.api.core.SimpleString; /** * USed to hold a hierarchical style address, delimited by a '.'. */ -public interface Address -{ +public interface Address { + SimpleString getAddress(); SimpleString[] getAddressParts(); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/AddressManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/AddressManager.java index b4dcfe7218..efc12975ea 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/AddressManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/AddressManager.java @@ -25,12 +25,13 @@ import org.apache.activemq.artemis.core.transaction.Transaction; /** * Used to maintain addresses and BindingsImpl. */ -public interface AddressManager -{ +public interface AddressManager { + boolean addBinding(Binding binding) throws Exception; /** * This will use a Transaction as we need to confirm the queue was removed + * * @param uniqueName * @param tx * @return diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/Binding.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/Binding.java index 338329ee9a..4c6763d491 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/Binding.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/Binding.java @@ -23,8 +23,8 @@ import org.apache.activemq.artemis.core.server.RoutingContext; import org.apache.activemq.artemis.core.server.ServerMessage; import org.apache.activemq.artemis.core.server.group.UnproposalListener; -public interface Binding extends UnproposalListener -{ +public interface Binding extends UnproposalListener { + SimpleString getAddress(); Bindable getBindable(); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/BindingType.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/BindingType.java index 5b1f73ac7e..4576dea926 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/BindingType.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/BindingType.java @@ -18,8 +18,7 @@ package org.apache.activemq.artemis.core.postoffice; import org.apache.activemq.artemis.core.server.ActiveMQMessageBundle; -public enum BindingType -{ +public enum BindingType { LOCAL_QUEUE, REMOTE_QUEUE, DIVERT; public static final int LOCAL_QUEUE_INDEX = 0; @@ -28,22 +27,17 @@ public enum BindingType public static final int DIVERT_INDEX = 2; - public int toInt() - { - if (equals(BindingType.LOCAL_QUEUE)) - { + public int toInt() { + if (equals(BindingType.LOCAL_QUEUE)) { return BindingType.LOCAL_QUEUE_INDEX; } - else if (equals(BindingType.REMOTE_QUEUE)) - { + else if (equals(BindingType.REMOTE_QUEUE)) { return BindingType.REMOTE_QUEUE_INDEX; } - else if (equals(BindingType.DIVERT)) - { + else if (equals(BindingType.DIVERT)) { return BindingType.DIVERT_INDEX; } - else - { + else { throw ActiveMQMessageBundle.BUNDLE.cannotConvertToInt(); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/Bindings.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/Bindings.java index 1f6613c833..b79f1da20a 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/Bindings.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/Bindings.java @@ -24,8 +24,8 @@ import org.apache.activemq.artemis.core.server.ServerMessage; import org.apache.activemq.artemis.core.server.cluster.impl.MessageLoadBalancingType; import org.apache.activemq.artemis.core.server.group.UnproposalListener; -public interface Bindings extends UnproposalListener -{ +public interface Bindings extends UnproposalListener { + Collection getBindings(); void addBinding(Binding binding); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/BindingsFactory.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/BindingsFactory.java index 705b751633..5b4c6c9a67 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/BindingsFactory.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/BindingsFactory.java @@ -21,7 +21,7 @@ import org.apache.activemq.artemis.api.core.SimpleString; /** * A factory for creating bindings */ -public interface BindingsFactory -{ +public interface BindingsFactory { + Bindings createBindings(SimpleString address) throws Exception; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/DuplicateIDCache.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/DuplicateIDCache.java index 8d30bd9ffe..35d2f83834 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/DuplicateIDCache.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/DuplicateIDCache.java @@ -21,13 +21,13 @@ import java.util.List; import org.apache.activemq.artemis.api.core.Pair; import org.apache.activemq.artemis.core.transaction.Transaction; -public interface DuplicateIDCache -{ +public interface DuplicateIDCache { + boolean contains(byte[] duplicateID); void addToCache(byte[] duplicateID, Transaction tx) throws Exception; - void deleteFromCache(byte [] duplicateID) throws Exception; + void deleteFromCache(byte[] duplicateID) throws Exception; void load(List> theIds) throws Exception; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/PostOffice.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/PostOffice.java index f122417e02..e6bb837a83 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/PostOffice.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/PostOffice.java @@ -30,7 +30,6 @@ import org.apache.activemq.artemis.core.server.ServerMessage; import org.apache.activemq.artemis.core.transaction.Transaction; /** - * * A PostOffice instance maintains a mapping of a String address to a Queue. Multiple Queue instances can be bound * with the same String address. * @@ -41,14 +40,15 @@ import org.apache.activemq.artemis.core.transaction.Transaction; * * A Queue instance can only be bound against a single address in the post office. */ -public interface PostOffice extends ActiveMQComponent -{ +public interface PostOffice extends ActiveMQComponent { + void addBinding(Binding binding) throws Exception; Binding removeBinding(SimpleString uniqueName, Transaction tx) throws Exception; /** * It will lookup the Binding without creating an item on the Queue if non-existent + * * @param address * @throws Exception */ @@ -56,6 +56,7 @@ public interface PostOffice extends ActiveMQComponent /** * Differently to lookupBindings, this will always create a new element on the Queue if non-existent + * * @param address * @throws Exception */ @@ -71,15 +72,28 @@ public interface PostOffice extends ActiveMQComponent void route(ServerMessage message, QueueCreator queueCreator, Transaction tx, boolean direct) throws Exception; - void route(ServerMessage message, QueueCreator queueCreator, Transaction tx, boolean direct, boolean rejectDuplicates) throws Exception; + void route(ServerMessage message, + QueueCreator queueCreator, + Transaction tx, + boolean direct, + boolean rejectDuplicates) throws Exception; - void route(ServerMessage message, QueueCreator queueCreator, RoutingContext context, boolean direct) throws Exception; + void route(ServerMessage message, + QueueCreator queueCreator, + RoutingContext context, + boolean direct) throws Exception; - void route(ServerMessage message, QueueCreator queueCreator, RoutingContext context, boolean direct, boolean rejectDuplicates) throws Exception; + void route(ServerMessage message, + QueueCreator queueCreator, + RoutingContext context, + boolean direct, + boolean rejectDuplicates) throws Exception; MessageReference reroute(ServerMessage message, Queue queue, Transaction tx) throws Exception; - Pair redistribute(ServerMessage message, final Queue originatingQueue, Transaction tx) throws Exception; + Pair redistribute(ServerMessage message, + final Queue originatingQueue, + Transaction tx) throws Exception; void processRoute(final ServerMessage message, final RoutingContext context, final boolean direct) throws Exception; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/QueueBinding.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/QueueBinding.java index 44c8d61375..2cb12b83c3 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/QueueBinding.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/QueueBinding.java @@ -18,8 +18,8 @@ package org.apache.activemq.artemis.core.postoffice; import org.apache.activemq.artemis.core.server.Queue; -public interface QueueBinding extends Binding -{ +public interface QueueBinding extends Binding { + int consumerCount(); Queue getQueue(); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/QueueInfo.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/QueueInfo.java index 9162e3dc9f..a953fc2e71 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/QueueInfo.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/QueueInfo.java @@ -22,8 +22,8 @@ import java.util.List; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.server.ActiveMQMessageBundle; -public class QueueInfo implements Serializable -{ +public class QueueInfo implements Serializable { + private static final long serialVersionUID = 3451892849198803182L; private final SimpleString routingName; @@ -47,18 +47,14 @@ public class QueueInfo implements Serializable final SimpleString address, final SimpleString filterString, final long id, - final int distance) - { - if (routingName == null) - { + final int distance) { + if (routingName == null) { throw ActiveMQMessageBundle.BUNDLE.routeNameIsNull(); } - if (clusterName == null) - { + if (clusterName == null) { throw ActiveMQMessageBundle.BUNDLE.clusterNameIsNull(); } - if (address == null) - { + if (address == null) { throw ActiveMQMessageBundle.BUNDLE.addressIsNull(); } @@ -70,74 +66,59 @@ public class QueueInfo implements Serializable this.distance = distance; } - public SimpleString getRoutingName() - { + public SimpleString getRoutingName() { return routingName; } - public SimpleString getClusterName() - { + public SimpleString getClusterName() { return clusterName; } - public SimpleString getAddress() - { + public SimpleString getAddress() { return address; } - public SimpleString getFilterString() - { + public SimpleString getFilterString() { return filterString; } - public int getDistance() - { + public int getDistance() { return distance; } - public long getID() - { + public long getID() { return id; } - public List getFilterStrings() - { + public List getFilterStrings() { return filterStrings; } - public void setFilterStrings(final List filterStrings) - { + public void setFilterStrings(final List filterStrings) { this.filterStrings = filterStrings; } - public int getNumberOfConsumers() - { + public int getNumberOfConsumers() { return numberOfConsumers; } - public void incrementConsumers() - { + public void incrementConsumers() { numberOfConsumers++; } - public void decrementConsumers() - { + public void decrementConsumers() { numberOfConsumers--; } - public boolean matchesAddress(SimpleString address) - { + public boolean matchesAddress(SimpleString address) { boolean containsAddress = false; - if (address != null) - { + if (address != null) { SimpleString[] split = address.split(','); - for (SimpleString addressPart : split) - { + for (SimpleString addressPart : split) { containsAddress = address.startsWith(addressPart); - if (containsAddress) - { + if (containsAddress) { break; } } @@ -150,23 +131,22 @@ public class QueueInfo implements Serializable * @see java.lang.Object#toString() */ @Override - public String toString() - { + public String toString() { return "QueueInfo [routingName=" + routingName + - ", clusterName=" + - clusterName + - ", address=" + - address + - ", filterString=" + - filterString + - ", id=" + - id + - ", filterStrings=" + - filterStrings + - ", numberOfConsumers=" + - numberOfConsumers + - ", distance=" + - distance + - "]"; + ", clusterName=" + + clusterName + + ", address=" + + address + + ", filterString=" + + filterString + + ", id=" + + id + + ", filterStrings=" + + filterStrings + + ", numberOfConsumers=" + + numberOfConsumers + + ", distance=" + + distance + + "]"; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/AddressImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/AddressImpl.java index f91c76183e..bfa8527b49 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/AddressImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/AddressImpl.java @@ -25,8 +25,8 @@ import org.apache.activemq.artemis.core.postoffice.Address; /** * splits an address string into its hierarchical parts split by '.' */ -public class AddressImpl implements Address -{ +public class AddressImpl implements Address { + private final SimpleString address; private final SimpleString[] addressParts; @@ -35,110 +35,87 @@ public class AddressImpl implements Address private final List

    linkedAddresses = new ArrayList
    (); - public AddressImpl(final SimpleString address) - { + public AddressImpl(final SimpleString address) { this.address = address; addressParts = address.split(WildcardAddressManager.DELIM); containsWildCard = address.contains(WildcardAddressManager.SINGLE_WORD) || address.contains(WildcardAddressManager.ANY_WORDS); } - public SimpleString getAddress() - { + public SimpleString getAddress() { return address; } - public SimpleString[] getAddressParts() - { + public SimpleString[] getAddressParts() { return addressParts; } - public boolean containsWildCard() - { + public boolean containsWildCard() { return containsWildCard; } - public List
    getLinkedAddresses() - { + public List
    getLinkedAddresses() { return linkedAddresses; } - public void addLinkedAddress(final Address address) - { - if (!linkedAddresses.contains(address)) - { + public void addLinkedAddress(final Address address) { + if (!linkedAddresses.contains(address)) { linkedAddresses.add(address); } } - public void removeLinkedAddress(final Address actualAddress) - { + public void removeLinkedAddress(final Address actualAddress) { linkedAddresses.remove(actualAddress); } - public boolean matches(final Address add) - { - if (containsWildCard == add.containsWildCard()) - { + public boolean matches(final Address add) { + if (containsWildCard == add.containsWildCard()) { return address.equals(add.getAddress()); } int pos = 0; int matchPos = 0; SimpleString nextToMatch; - for (; matchPos < add.getAddressParts().length; ) - { - if (pos >= addressParts.length) - { + for (; matchPos < add.getAddressParts().length; ) { + if (pos >= addressParts.length) { // test for # as last address part return pos + 1 == add.getAddressParts().length && add.getAddressParts()[pos].equals(WildcardAddressManager.ANY_WORDS_SIMPLESTRING); } SimpleString curr = addressParts[pos]; SimpleString next = addressParts.length > pos + 1 ? addressParts[pos + 1] : null; SimpleString currMatch = add.getAddressParts()[matchPos]; - if (currMatch.equals(WildcardAddressManager.SINGLE_WORD_SIMPLESTRING)) - { + if (currMatch.equals(WildcardAddressManager.SINGLE_WORD_SIMPLESTRING)) { pos++; matchPos++; } - else if (currMatch.equals(WildcardAddressManager.ANY_WORDS_SIMPLESTRING)) - { - if (matchPos == addressParts.length - 1) - { + else if (currMatch.equals(WildcardAddressManager.ANY_WORDS_SIMPLESTRING)) { + if (matchPos == addressParts.length - 1) { pos++; matchPos++; } - else if (next == null) - { + else if (next == null) { return false; } - else if (matchPos == add.getAddressParts().length - 1) - { + else if (matchPos == add.getAddressParts().length - 1) { return true; } - else - { + else { nextToMatch = add.getAddressParts()[matchPos + 1]; - while (curr != null) - { - if (curr.equals(nextToMatch)) - { + while (curr != null) { + if (curr.equals(nextToMatch)) { break; } pos++; curr = next; next = addressParts.length > pos + 1 ? addressParts[pos + 1] : null; } - if (curr == null) - { + if (curr == null) { return false; } matchPos++; } } - else - { - if (!curr.equals(currMatch)) - { + else { + if (!curr.equals(currMatch)) { return false; } pos++; @@ -149,21 +126,17 @@ public class AddressImpl implements Address } @Override - public boolean equals(final Object o) - { - if (this == o) - { + public boolean equals(final Object o) { + if (this == o) { return true; } - if (o == null || getClass() != o.getClass()) - { + if (o == null || getClass() != o.getClass()) { return false; } AddressImpl address1 = (AddressImpl) o; - if (!address.equals(address1.address)) - { + if (!address.equals(address1.address)) { return false; } @@ -171,8 +144,7 @@ public class AddressImpl implements Address } @Override - public int hashCode() - { + public int hashCode() { return address.hashCode(); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/BindingsImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/BindingsImpl.java index 927d049b70..8b21396376 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/BindingsImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/BindingsImpl.java @@ -44,8 +44,8 @@ import org.apache.activemq.artemis.core.server.group.GroupingHandler; import org.apache.activemq.artemis.core.server.group.impl.Proposal; import org.apache.activemq.artemis.core.server.group.impl.Response; -public final class BindingsImpl implements Bindings -{ +public final class BindingsImpl implements Bindings { + // This is public as we use on test assertions public static final int MAX_GROUP_RETRY = 10; @@ -67,55 +67,44 @@ public final class BindingsImpl implements Bindings private final SimpleString name; - public BindingsImpl(final SimpleString name, final GroupingHandler groupingHandler, final PagingStore pageStore) - { + public BindingsImpl(final SimpleString name, final GroupingHandler groupingHandler, final PagingStore pageStore) { this.groupingHandler = groupingHandler; this.pageStore = pageStore; this.name = name; } - public void setMessageLoadBalancingType(final MessageLoadBalancingType messageLoadBalancingType) - { + public void setMessageLoadBalancingType(final MessageLoadBalancingType messageLoadBalancingType) { this.messageLoadBalancingType = messageLoadBalancingType; } - public Collection getBindings() - { + public Collection getBindings() { return bindingsMap.values(); } - public void unproposed(SimpleString groupID) - { - for (Binding binding : bindingsMap.values()) - { + public void unproposed(SimpleString groupID) { + for (Binding binding : bindingsMap.values()) { binding.unproposed(groupID); } } - public void addBinding(final Binding binding) - { - if (isTrace) - { + public void addBinding(final Binding binding) { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("addBinding(" + binding + ") being called"); } - if (binding.isExclusive()) - { + if (binding.isExclusive()) { exclusiveBindings.add(binding); } - else - { + else { SimpleString routingName = binding.getRoutingName(); List bindings = routingNameBindingMap.get(routingName); - if (bindings == null) - { + if (bindings == null) { bindings = new CopyOnWriteArrayList(); List oldBindings = routingNameBindingMap.putIfAbsent(routingName, bindings); - if (oldBindings != null) - { + if (oldBindings != null) { bindings = oldBindings; } } @@ -125,31 +114,25 @@ public final class BindingsImpl implements Bindings bindingsMap.put(binding.getID(), binding); - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Adding binding " + binding + " into " + this + " bindingTable: " + debugBindings()); } } - public void removeBinding(final Binding binding) - { - if (binding.isExclusive()) - { + public void removeBinding(final Binding binding) { + if (binding.isExclusive()) { exclusiveBindings.remove(binding); } - else - { + else { SimpleString routingName = binding.getRoutingName(); List bindings = routingNameBindingMap.get(routingName); - if (bindings != null) - { + if (bindings != null) { bindings.remove(binding); - if (bindings.isEmpty()) - { + if (bindings.isEmpty()) { routingNameBindingMap.remove(routingName); } } @@ -157,21 +140,19 @@ public final class BindingsImpl implements Bindings bindingsMap.remove(binding.getID()); - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Removing binding " + binding + " into " + this + " bindingTable: " + debugBindings()); } } - public boolean redistribute(final ServerMessage message, final Queue originatingQueue, final RoutingContext context) throws Exception - { - if (messageLoadBalancingType.equals(MessageLoadBalancingType.STRICT) || messageLoadBalancingType.equals(MessageLoadBalancingType.OFF)) - { + public boolean redistribute(final ServerMessage message, + final Queue originatingQueue, + final RoutingContext context) throws Exception { + if (messageLoadBalancingType.equals(MessageLoadBalancingType.STRICT) || messageLoadBalancingType.equals(MessageLoadBalancingType.OFF)) { return false; } - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Redistributing message " + message); } @@ -179,8 +160,7 @@ public final class BindingsImpl implements Bindings List bindings = routingNameBindingMap.get(routingName); - if (bindings == null) - { + if (bindings == null) { // The value can become null if it's concurrently removed while we're iterating - this is expected // ConcurrentHashMap behaviour! return false; @@ -197,26 +177,21 @@ public final class BindingsImpl implements Bindings Binding theBinding = null; // TODO - combine this with similar logic in route() - while (true) - { + while (true) { Binding binding; - try - { + try { binding = bindings.get(pos); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { // This can occur if binding is removed while in route - if (!bindings.isEmpty()) - { + if (!bindings.isEmpty()) { pos = 0; startPos = 0; length = bindings.size(); continue; } - else - { + else { break; } } @@ -227,60 +202,50 @@ public final class BindingsImpl implements Bindings boolean highPrior = binding.isHighAcceptPriority(message); - if (highPrior && binding.getBindable() != originatingQueue && (filter == null || filter.match(message))) - { + if (highPrior && binding.getBindable() != originatingQueue && (filter == null || filter.match(message))) { theBinding = binding; break; } - if (pos == startPos) - { + if (pos == startPos) { break; } } routingNamePositions.put(routingName, pos); - if (theBinding != null) - { + if (theBinding != null) { theBinding.route(message, context); return true; } - else - { + else { return false; } } - public void route(final ServerMessage message, final RoutingContext context) throws Exception - { + public void route(final ServerMessage message, final RoutingContext context) throws Exception { route(message, context, true); } - private void route(final ServerMessage message, final RoutingContext context, final boolean groupRouting) throws Exception - { + private void route(final ServerMessage message, + final RoutingContext context, + final boolean groupRouting) throws Exception { /* This is a special treatment for scaled-down messages involving SnF queues. * See org.apache.activemq.artemis.core.server.impl.ScaleDownHandler.scaleDownMessages() for the logic that sends messages with this property */ - if (message.containsProperty(MessageImpl.HDR_SCALEDOWN_TO_IDS)) - { + if (message.containsProperty(MessageImpl.HDR_SCALEDOWN_TO_IDS)) { byte[] ids = (byte[]) message.removeProperty(MessageImpl.HDR_SCALEDOWN_TO_IDS); - if (ids != null) - { + if (ids != null) { ByteBuffer buffer = ByteBuffer.wrap(ids); - while (buffer.hasRemaining()) - { + while (buffer.hasRemaining()) { long id = buffer.getLong(); - for (Map.Entry entry : bindingsMap.entrySet()) - { - if (entry.getValue() instanceof RemoteQueueBinding) - { + for (Map.Entry entry : bindingsMap.entrySet()) { + if (entry.getValue() instanceof RemoteQueueBinding) { RemoteQueueBinding remoteQueueBinding = (RemoteQueueBinding) entry.getValue(); - if (remoteQueueBinding.getRemoteQueueID() == id) - { + if (remoteQueueBinding.getRemoteQueueID() == id) { message.putBytesProperty(MessageImpl.HDR_ROUTE_TO_IDS, ByteBuffer.allocate(8).putLong(remoteQueueBinding.getID()).array()); } } @@ -291,12 +256,9 @@ public final class BindingsImpl implements Bindings boolean routed = false; - if (!exclusiveBindings.isEmpty()) - { - for (Binding binding : exclusiveBindings) - { - if (binding.getFilter() == null || binding.getFilter().match(message)) - { + if (!exclusiveBindings.isEmpty()) { + for (Binding binding : exclusiveBindings) { + if (binding.getFilter() == null || binding.getFilter().match(message)) { binding.getBindable().route(message, context); routed = true; @@ -304,36 +266,29 @@ public final class BindingsImpl implements Bindings } } - if (!routed) - { + if (!routed) { // Remove the ids now, in order to avoid double check byte[] ids = (byte[]) message.removeProperty(MessageImpl.HDR_ROUTE_TO_IDS); // Fetch the groupId now, in order to avoid double checking SimpleString groupId = message.getSimpleStringProperty(Message.HDR_GROUP_ID); - if (ids != null) - { + if (ids != null) { routeFromCluster(message, context, ids); } - else if (groupingHandler != null && groupRouting && groupId != null) - { + else if (groupingHandler != null && groupRouting && groupId != null) { routeUsingStrictOrdering(message, context, groupingHandler, groupId, 0); } - else - { - if (isTrace) - { + else { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Routing message " + message + " on binding=" + this); } - for (Map.Entry> entry : routingNameBindingMap.entrySet()) - { + for (Map.Entry> entry : routingNameBindingMap.entrySet()) { SimpleString routingName = entry.getKey(); List bindings = entry.getValue(); - if (bindings == null) - { + if (bindings == null) { // The value can become null if it's concurrently removed while we're iterating - this is expected // ConcurrentHashMap behaviour! continue; @@ -341,8 +296,7 @@ public final class BindingsImpl implements Bindings Binding theBinding = getNextBinding(message, routingName, bindings); - if (theBinding != null) - { + if (theBinding != null) { theBinding.route(message, context); } } @@ -351,8 +305,7 @@ public final class BindingsImpl implements Bindings } @Override - public String toString() - { + public String toString() { return "BindingsImpl [name=" + name + "]"; } @@ -366,8 +319,7 @@ public final class BindingsImpl implements Bindings */ private Binding getNextBinding(final ServerMessage message, final SimpleString routingName, - final List bindings) - { + final List bindings) { Integer ipos = routingNamePositions.get(routingName); int pos = ipos != null ? ipos : 0; @@ -380,50 +332,41 @@ public final class BindingsImpl implements Bindings int lastLowPriorityBinding = -1; - while (true) - { + while (true) { Binding binding; - try - { + try { binding = bindings.get(pos); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { // This can occur if binding is removed while in route - if (!bindings.isEmpty()) - { + if (!bindings.isEmpty()) { pos = 0; startPos = 0; length = bindings.size(); continue; } - else - { + else { break; } } Filter filter = binding.getFilter(); - if (filter == null || filter.match(message)) - { + if (filter == null || filter.match(message)) { // bindings.length == 1 ==> only a local queue so we don't check for matching consumers (it's an // unnecessary overhead) - if (length == 1 || (binding.isConnected() && (messageLoadBalancingType.equals(MessageLoadBalancingType.STRICT) || binding.isHighAcceptPriority(message)))) - { + if (length == 1 || (binding.isConnected() && (messageLoadBalancingType.equals(MessageLoadBalancingType.STRICT) || binding.isHighAcceptPriority(message)))) { theBinding = binding; pos = incrementPos(pos, length); break; } - else - { + else { //https://issues.jboss.org/browse/HORNETQ-1254 When !routeWhenNoConsumers, // the localQueue should always have the priority over the secondary bindings - if (lastLowPriorityBinding == -1 || messageLoadBalancingType.equals(MessageLoadBalancingType.ON_DEMAND) && binding instanceof LocalQueueBinding) - { + if (lastLowPriorityBinding == -1 || messageLoadBalancingType.equals(MessageLoadBalancingType.ON_DEMAND) && binding instanceof LocalQueueBinding) { lastLowPriorityBinding = pos; } } @@ -431,29 +374,23 @@ public final class BindingsImpl implements Bindings pos = incrementPos(pos, length); - if (pos == startPos) - { + if (pos == startPos) { // if no bindings were found, we will apply a secondary level on the routing logic - if (lastLowPriorityBinding != -1) - { - try - { + if (lastLowPriorityBinding != -1) { + try { theBinding = bindings.get(lastLowPriorityBinding); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { // This can occur if binding is removed while in route - if (!bindings.isEmpty()) - { + if (!bindings.isEmpty()) { pos = 0; lastLowPriorityBinding = -1; continue; } - else - { + else { break; } } @@ -463,13 +400,11 @@ public final class BindingsImpl implements Bindings break; } } - if (pos != startPos) - { + if (pos != startPos) { routingNamePositions.put(routingName, pos); } - if (messageLoadBalancingType.equals(MessageLoadBalancingType.OFF) && theBinding instanceof RemoteQueueBinding) - { + if (messageLoadBalancingType.equals(MessageLoadBalancingType.OFF) && theBinding instanceof RemoteQueueBinding) { theBinding = getNextBinding(message, routingName, bindings); } return theBinding; @@ -479,16 +414,13 @@ public final class BindingsImpl implements Bindings final RoutingContext context, final GroupingHandler groupingGroupingHandler, final SimpleString groupId, - final int tries) throws Exception - { - for (Map.Entry> entry : routingNameBindingMap.entrySet()) - { + final int tries) throws Exception { + for (Map.Entry> entry : routingNameBindingMap.entrySet()) { SimpleString routingName = entry.getKey(); List bindings = entry.getValue(); - if (bindings == null) - { + if (bindings == null) { // The value can become null if it's concurrently removed while we're iterating - this is expected // ConcurrentHashMap behaviour! continue; @@ -502,19 +434,16 @@ public final class BindingsImpl implements Bindings // see if there is already a response Response resp = groupingGroupingHandler.getProposal(fullID, true); - if (resp == null) - { + if (resp == null) { // ok let's find the next binding to propose Binding theBinding = getNextBinding(message, routingName, bindings); - if (theBinding == null) - { + if (theBinding == null) { continue; } resp = groupingGroupingHandler.propose(new Proposal(fullID, theBinding.getClusterName())); - if (resp == null) - { + if (resp == null) { ActiveMQServerLogger.LOGGER.debug("it got a timeout on propose, trying again, number of retries: " + tries); // it timed out, so we will check it through routeAndcheckNull theBinding = null; @@ -523,15 +452,13 @@ public final class BindingsImpl implements Bindings // alternativeClusterName will be != null when by the time we looked at the cachedProposed, // another thread already set the proposal, so we use the new alternativeclusterName that's set there // if our proposal was declined find the correct binding to use - if (resp != null && resp.getAlternativeClusterName() != null) - { + if (resp != null && resp.getAlternativeClusterName() != null) { theBinding = locateBinding(resp.getAlternativeClusterName(), bindings); } routeAndCheckNull(message, context, resp, theBinding, groupId, tries); } - else - { + else { // ok, we need to find the binding and route it Binding chosen = locateBinding(resp.getChosenClusterName(), bindings); @@ -540,12 +467,9 @@ public final class BindingsImpl implements Bindings } } - private Binding locateBinding(SimpleString clusterName, List bindings) - { - for (Binding binding : bindings) - { - if (binding.getClusterName().equals(clusterName)) - { + private Binding locateBinding(SimpleString clusterName, List bindings) { + for (Binding binding : bindings) { + if (binding.getClusterName().equals(clusterName)) { return binding; } } @@ -553,37 +477,34 @@ public final class BindingsImpl implements Bindings return null; } - private void routeAndCheckNull(ServerMessage message, RoutingContext context, Response resp, Binding theBinding, SimpleString groupId, int tries) throws Exception - { + private void routeAndCheckNull(ServerMessage message, + RoutingContext context, + Response resp, + Binding theBinding, + SimpleString groupId, + int tries) throws Exception { // and let's route it - if (theBinding != null) - { + if (theBinding != null) { theBinding.route(message, context); } - else - { - if (resp != null) - { + else { + if (resp != null) { groupingHandler.forceRemove(resp.getGroupId(), resp.getClusterName()); } //there may be a chance that the binding has been removed from the post office before it is removed from the grouping handler. //in this case all we can do is remove it and try again. - if (tries < MAX_GROUP_RETRY) - { + if (tries < MAX_GROUP_RETRY) { routeUsingStrictOrdering(message, context, groupingHandler, groupId, tries + 1); } - else - { + else { ActiveMQServerLogger.LOGGER.impossibleToRouteGrouped(); route(message, context, false); } } } - - private String debugBindings() - { + private String debugBindings() { StringWriter writer = new StringWriter(); PrintWriter out = new PrintWriter(writer); @@ -591,29 +512,25 @@ public final class BindingsImpl implements Bindings out.println("\n***************************************"); out.println("routingNameBindingMap:"); - if (routingNameBindingMap.isEmpty()) - { + if (routingNameBindingMap.isEmpty()) { out.println("EMPTY!"); } - for (Map.Entry> entry : routingNameBindingMap.entrySet()) - { + for (Map.Entry> entry : routingNameBindingMap.entrySet()) { out.print("key=" + entry.getKey() + ", value=" + entry.getValue()); -// for (Binding bind : entry.getValue()) -// { -// out.print(bind + ","); -// } + // for (Binding bind : entry.getValue()) + // { + // out.print(bind + ","); + // } out.println(); } out.println(); out.println("RoutingNamePositions:"); - if (routingNamePositions.isEmpty()) - { + if (routingNamePositions.isEmpty()) { out.println("EMPTY!"); } - for (Map.Entry entry : routingNamePositions.entrySet()) - { + for (Map.Entry entry : routingNamePositions.entrySet()) { out.println("key=" + entry.getKey() + ", value=" + entry.getValue()); } @@ -621,46 +538,39 @@ public final class BindingsImpl implements Bindings out.println("BindingsMap:"); - if (bindingsMap.isEmpty()) - { + if (bindingsMap.isEmpty()) { out.println("EMPTY!"); } - for (Map.Entry entry : bindingsMap.entrySet()) - { + for (Map.Entry entry : bindingsMap.entrySet()) { out.println("Key=" + entry.getKey() + ", value=" + entry.getValue()); } out.println(); out.println("ExclusiveBindings:"); - if (exclusiveBindings.isEmpty()) - { + if (exclusiveBindings.isEmpty()) { out.println("EMPTY!"); } - for (Binding binding : exclusiveBindings) - { + for (Binding binding : exclusiveBindings) { out.println(binding); } out.println("#####################################################"); - return writer.toString(); } - - private void routeFromCluster(final ServerMessage message, final RoutingContext context, final byte[] ids) throws Exception - { + private void routeFromCluster(final ServerMessage message, + final RoutingContext context, + final byte[] ids) throws Exception { byte[] idsToAck = (byte[]) message.removeProperty(MessageImpl.HDR_ROUTE_TO_ACK_IDS); List idsToAckList = new ArrayList<>(); - if (idsToAck != null) - { + if (idsToAck != null) { ByteBuffer buff = ByteBuffer.wrap(idsToAck); - while (buff.hasRemaining()) - { + while (buff.hasRemaining()) { long bindingID = buff.getLong(); idsToAckList.add(bindingID); } @@ -668,35 +578,28 @@ public final class BindingsImpl implements Bindings ByteBuffer buff = ByteBuffer.wrap(ids); - while (buff.hasRemaining()) - { + while (buff.hasRemaining()) { long bindingID = buff.getLong(); Binding binding = bindingsMap.get(bindingID); - if (binding != null) - { - if (idsToAckList.contains(bindingID)) - { + if (binding != null) { + if (idsToAckList.contains(bindingID)) { binding.routeWithAck(message, context); } - else - { + else { binding.route(message, context); } } - else - { + else { ActiveMQServerLogger.LOGGER.bindingNotFound(bindingID, message.toString(), this.toString()); } } } - private int incrementPos(int pos, final int length) - { + private int incrementPos(int pos, final int length) { pos++; - if (pos == length) - { + if (pos == length) { pos = 0; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/DivertBinding.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/DivertBinding.java index 1330ed07f2..303b0fe028 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/DivertBinding.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/DivertBinding.java @@ -25,8 +25,8 @@ import org.apache.activemq.artemis.core.server.Divert; import org.apache.activemq.artemis.core.server.RoutingContext; import org.apache.activemq.artemis.core.server.ServerMessage; -public class DivertBinding implements Binding -{ +public class DivertBinding implements Binding { + private final SimpleString address; private final Divert divert; @@ -41,8 +41,7 @@ public class DivertBinding implements Binding private final long id; - public DivertBinding(final long id, final SimpleString address, final Divert divert) - { + public DivertBinding(final long id, final SimpleString address, final Divert divert) { this.id = id; this.address = address; @@ -58,114 +57,95 @@ public class DivertBinding implements Binding exclusive = divert.isExclusive(); } - public long getID() - { + public long getID() { return id; } - public Filter getFilter() - { + public Filter getFilter() { return filter; } - public SimpleString getAddress() - { + public SimpleString getAddress() { return address; } - public Bindable getBindable() - { + public Bindable getBindable() { return divert; } - public SimpleString getRoutingName() - { + public SimpleString getRoutingName() { return routingName; } - public SimpleString getUniqueName() - { + public SimpleString getUniqueName() { return uniqueName; } - public SimpleString getClusterName() - { + public SimpleString getClusterName() { return uniqueName; } - public boolean isExclusive() - { + public boolean isExclusive() { return exclusive; } - public boolean isHighAcceptPriority(final ServerMessage message) - { + public boolean isHighAcceptPriority(final ServerMessage message) { return true; } - public void route(final ServerMessage message, final RoutingContext context) throws Exception - { + public void route(final ServerMessage message, final RoutingContext context) throws Exception { divert.route(message, context); } - public int getDistance() - { + public int getDistance() { return 0; } - public BindingType getType() - { + public BindingType getType() { return BindingType.DIVERT; } @Override - public void unproposed(SimpleString groupID) - { + public void unproposed(SimpleString groupID) { } @Override - public String toString() - { + public String toString() { return "DivertBinding [id=" + id + - ", address=" + - address + - ", divert=" + - divert + - ", filter=" + - filter + - ", uniqueName=" + - uniqueName + - ", routingName=" + - routingName + - ", exclusive=" + - exclusive + - "]"; + ", address=" + + address + + ", divert=" + + divert + + ", filter=" + + filter + + ", uniqueName=" + + uniqueName + + ", routingName=" + + routingName + + ", exclusive=" + + exclusive + + "]"; } @Override - public String toManagementString() - { + public String toManagementString() { return this.getClass().getSimpleName() + " [id=" + id + "]"; } @Override - public boolean isConnected() - { + public boolean isConnected() { return true; } @Override - public void routeWithAck(ServerMessage message, RoutingContext context) - { - //noop + public void routeWithAck(ServerMessage message, RoutingContext context) { + //noop } - public void close() throws Exception - { + public void close() throws Exception { } - public Divert getDivert() - { + public Divert getDivert() { return divert; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/DuplicateIDCacheImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/DuplicateIDCacheImpl.java index f09003caf3..d75dad6257 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/DuplicateIDCacheImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/DuplicateIDCacheImpl.java @@ -35,8 +35,8 @@ import org.apache.activemq.artemis.core.transaction.TransactionOperationAbstract * * A fixed size rotating cache of last X duplicate ids. */ -public class DuplicateIDCacheImpl implements DuplicateIDCache -{ +public class DuplicateIDCacheImpl implements DuplicateIDCache { + // ByteHolder, position private final Map cache = new ConcurrentHashMap(); @@ -57,8 +57,7 @@ public class DuplicateIDCacheImpl implements DuplicateIDCache public DuplicateIDCacheImpl(final SimpleString address, final int size, final StorageManager storageManager, - final boolean persist) - { + final boolean persist) { this.address = address; cacheSize = size; @@ -70,16 +69,13 @@ public class DuplicateIDCacheImpl implements DuplicateIDCache this.persist = persist; } - public void load(final List> theIds) throws Exception - { + public void load(final List> theIds) throws Exception { int count = 0; long txID = -1; - for (Pair id : theIds) - { - if (count < cacheSize) - { + for (Pair id : theIds) { + if (count < cacheSize) { ByteArrayHolder bah = new ByteArrayHolder(id.getA()); Pair pair = new Pair(bah, id.getB()); @@ -88,11 +84,9 @@ public class DuplicateIDCacheImpl implements DuplicateIDCache ids.add(pair); } - else - { + else { // cache size has been reduced in config - delete the extra records - if (txID == -1) - { + if (txID == -1) { txID = storageManager.generateID(); } @@ -102,37 +96,30 @@ public class DuplicateIDCacheImpl implements DuplicateIDCache count++; } - if (txID != -1) - { + if (txID != -1) { storageManager.commit(txID); } pos = ids.size(); - if (pos == cacheSize) - { + if (pos == cacheSize) { pos = 0; } } - - public void deleteFromCache(byte[] duplicateID) throws Exception - { + public void deleteFromCache(byte[] duplicateID) throws Exception { ByteArrayHolder bah = new ByteArrayHolder(duplicateID); Integer posUsed = cache.remove(bah); - if (posUsed != null) - { + if (posUsed != null) { Pair id; - synchronized (this) - { + synchronized (this) { id = ids.get(posUsed.intValue()); - if (id.getA().equals(bah)) - { + if (id.getA().equals(bah)) { id.setA(null); storageManager.deleteDuplicateID(id.getB()); id.setB(null); @@ -142,30 +129,23 @@ public class DuplicateIDCacheImpl implements DuplicateIDCache } - - public boolean contains(final byte[] duplID) - { + public boolean contains(final byte[] duplID) { return cache.get(new ByteArrayHolder(duplID)) != null; } - public synchronized void addToCache(final byte[] duplID, final Transaction tx) throws Exception - { + public synchronized void addToCache(final byte[] duplID, final Transaction tx) throws Exception { long recordID = -1; - if (tx == null) - { - if (persist) - { + if (tx == null) { + if (persist) { recordID = storageManager.generateID(); storageManager.storeDuplicateID(address, duplID, recordID); } addToCacheInMemory(duplID, recordID); } - else - { - if (persist) - { + else { + if (persist) { recordID = storageManager.generateID(); storageManager.storeDuplicateIDTransactional(tx.getID(), address, duplID, recordID); @@ -178,41 +158,34 @@ public class DuplicateIDCacheImpl implements DuplicateIDCache } } - public void load(final Transaction tx, final byte[] duplID) - { + public void load(final Transaction tx, final byte[] duplID) { tx.addOperation(new AddDuplicateIDOperation(duplID, tx.getID())); } - private synchronized void addToCacheInMemory(final byte[] duplID, final long recordID) - { + private synchronized void addToCacheInMemory(final byte[] duplID, final long recordID) { ByteArrayHolder holder = new ByteArrayHolder(duplID); cache.put(holder, pos); Pair id; - if (pos < ids.size()) - { + if (pos < ids.size()) { // Need fast array style access here -hence ArrayList typing id = ids.get(pos); // The id here might be null if it was explicit deleted - if (id.getA() != null) - { + if (id.getA() != null) { cache.remove(id.getA()); // Record already exists - we delete the old one and add the new one // Note we can't use update since journal update doesn't let older records get // reclaimed - if (id.getB() != null) - { - try - { + if (id.getB() != null) { + try { storageManager.deleteDuplicateID(id.getB()); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorDeletingDuplicateCache(e); } } @@ -226,8 +199,7 @@ public class DuplicateIDCacheImpl implements DuplicateIDCache holder.pos = pos; } - else - { + else { id = new Pair(holder, recordID >= 0 ? recordID : null); ids.add(id); @@ -235,21 +207,16 @@ public class DuplicateIDCacheImpl implements DuplicateIDCache holder.pos = pos; } - if (pos++ == cacheSize - 1) - { + if (pos++ == cacheSize - 1) { pos = 0; } } - public void clear() throws Exception - { - synchronized (this) - { - if (ids.size() > 0) - { + public void clear() throws Exception { + synchronized (this) { + if (ids.size() > 0) { long tx = storageManager.generateID(); - for (Pair id : ids) - { + for (Pair id : ids) { storageManager.deleteDuplicateIDTransactional(tx, id.getB()); } storageManager.commit(tx); @@ -262,34 +229,29 @@ public class DuplicateIDCacheImpl implements DuplicateIDCache } @Override - public List> getMap() - { + public List> getMap() { List> list = new ArrayList<>(); - for (Pair id : ids) - { + for (Pair id : ids) { list.add(new Pair<>(id.getA().bytes, id.getB())); } return list; } - private final class AddDuplicateIDOperation extends TransactionOperationAbstract - { + private final class AddDuplicateIDOperation extends TransactionOperationAbstract { + final byte[] duplID; final long recordID; volatile boolean done; - AddDuplicateIDOperation(final byte[] duplID, final long recordID) - { + AddDuplicateIDOperation(final byte[] duplID, final long recordID) { this.duplID = duplID; this.recordID = recordID; } - private void process() - { - if (!done) - { + private void process() { + if (!done) { addToCacheInMemory(duplID, recordID); done = true; @@ -297,22 +259,19 @@ public class DuplicateIDCacheImpl implements DuplicateIDCache } @Override - public void afterCommit(final Transaction tx) - { + public void afterCommit(final Transaction tx) { process(); } @Override - public List getRelatedMessageReferences() - { + public List getRelatedMessageReferences() { return null; } } - private static final class ByteArrayHolder - { - ByteArrayHolder(final byte[] bytes) - { + private static final class ByteArrayHolder { + + ByteArrayHolder(final byte[] bytes) { this.bytes = bytes; } @@ -323,40 +282,31 @@ public class DuplicateIDCacheImpl implements DuplicateIDCache int pos; @Override - public boolean equals(final Object other) - { - if (other instanceof ByteArrayHolder) - { + public boolean equals(final Object other) { + if (other instanceof ByteArrayHolder) { ByteArrayHolder s = (ByteArrayHolder) other; - if (bytes.length != s.bytes.length) - { + if (bytes.length != s.bytes.length) { return false; } - for (int i = 0; i < bytes.length; i++) - { - if (bytes[i] != s.bytes[i]) - { + for (int i = 0; i < bytes.length; i++) { + if (bytes[i] != s.bytes[i]) { return false; } } return true; } - else - { + else { return false; } } @Override - public int hashCode() - { - if (hash == 0) - { - for (byte b : bytes) - { + public int hashCode() { + if (hash == 0) { + for (byte b : bytes) { hash = 31 * hash + b; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/LocalQueueBinding.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/LocalQueueBinding.java index 78e7246a61..cffd0c3a6e 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/LocalQueueBinding.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/LocalQueueBinding.java @@ -25,8 +25,8 @@ import org.apache.activemq.artemis.core.server.Queue; import org.apache.activemq.artemis.core.server.RoutingContext; import org.apache.activemq.artemis.core.server.ServerMessage; -public class LocalQueueBinding implements QueueBinding -{ +public class LocalQueueBinding implements QueueBinding { + private final SimpleString address; private final Queue queue; @@ -37,8 +37,7 @@ public class LocalQueueBinding implements QueueBinding private final SimpleString clusterName; - public LocalQueueBinding(final SimpleString address, final Queue queue, final SimpleString nodeID) - { + public LocalQueueBinding(final SimpleString address, final Queue queue, final SimpleString nodeID) { this.address = address; this.queue = queue; @@ -50,122 +49,102 @@ public class LocalQueueBinding implements QueueBinding clusterName = name.concat(nodeID); } - public long getID() - { + public long getID() { return queue.getID(); } - public Filter getFilter() - { + public Filter getFilter() { return filter; } - public SimpleString getAddress() - { + public SimpleString getAddress() { return address; } - public Bindable getBindable() - { + public Bindable getBindable() { return queue; } - public Queue getQueue() - { + public Queue getQueue() { return queue; } - public SimpleString getRoutingName() - { + public SimpleString getRoutingName() { return name; } - public SimpleString getUniqueName() - { + public SimpleString getUniqueName() { return name; } - public SimpleString getClusterName() - { + public SimpleString getClusterName() { return clusterName; } - public boolean isExclusive() - { + public boolean isExclusive() { return false; } - public int getDistance() - { + public int getDistance() { return 0; } - public boolean isHighAcceptPriority(final ServerMessage message) - { + public boolean isHighAcceptPriority(final ServerMessage message) { // It's a high accept priority if the queue has at least one matching consumer return queue.hasMatchingConsumer(message); } @Override - public void unproposed(SimpleString groupID) - { + public void unproposed(SimpleString groupID) { queue.unproposed(groupID); } - public void route(final ServerMessage message, final RoutingContext context) throws Exception - { + public void route(final ServerMessage message, final RoutingContext context) throws Exception { queue.route(message, context); } - public void routeWithAck(ServerMessage message, RoutingContext context) throws Exception - { + public void routeWithAck(ServerMessage message, RoutingContext context) throws Exception { queue.routeWithAck(message, context); } - public boolean isQueueBinding() - { + public boolean isQueueBinding() { return true; } - public int consumerCount() - { + public int consumerCount() { return queue.getConsumerCount(); } - public BindingType getType() - { + public BindingType getType() { return BindingType.LOCAL_QUEUE; } - public void close() throws Exception - { + public void close() throws Exception { queue.close(); } @Override - public String toString() - { + public String toString() { return "LocalQueueBinding [address=" + address + - ", queue=" + - queue + - ", filter=" + - filter + - ", name=" + - name + - ", clusterName=" + - clusterName + - "]"; + ", queue=" + + queue + + ", filter=" + + filter + + ", name=" + + name + + ", clusterName=" + + clusterName + + "]"; } @Override - public String toManagementString() - { + public String toManagementString() { return this.getClass().getSimpleName() + " [address=" + address + ", queue=" + queue + "]"; } + @Override - public boolean isConnected() - { + public boolean isConnected() { return true; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/PostOfficeImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/PostOfficeImpl.java index 71a2458ae7..85ac2ef20e 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/PostOfficeImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/PostOfficeImpl.java @@ -86,8 +86,8 @@ import org.apache.activemq.artemis.utils.UUIDGenerator; * This is the class that will make the routing to Queues and decide which consumer will get the messages * It's the queue component on distributing the messages * * */ -public class PostOfficeImpl implements PostOffice, NotificationListener, BindingsFactory -{ +public class PostOfficeImpl implements PostOffice, NotificationListener, BindingsFactory { + private static final boolean isTrace = ActiveMQServerLogger.LOGGER.isTraceEnabled(); public static final SimpleString HDR_RESET_QUEUE_DATA = new SimpleString("_AMQ_RESET_QUEUE_DATA"); @@ -140,9 +140,7 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding final boolean enableWildCardRouting, final int idCacheSize, final boolean persistIDCache, - final HierarchicalRepository addressSettingsRepository) - - { + final HierarchicalRepository addressSettingsRepository) { this.storageManager = storageManager; queueFactory = bindableFactory; @@ -155,12 +153,10 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding this.reaperPriority = reaperPriority; - if (enableWildCardRouting) - { + if (enableWildCardRouting) { addressManager = new WildcardAddressManager(this); } - else - { + else { addressManager = new SimpleAddressManager(this); } @@ -175,8 +171,7 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding // ActiveMQComponent implementation --------------------------------------- - public synchronized void start() throws Exception - { + public synchronized void start() throws Exception { if (started) return; @@ -191,8 +186,7 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding started = true; } - public synchronized void stop() throws Exception - { + public synchronized void stop() throws Exception { started = false; managementService.removeNotificationListener(this); @@ -200,8 +194,7 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding if (reaperRunnable != null) reaperRunnable.stop(); - if (reaperThread != null) - { + if (reaperThread != null) { reaperThread.join(); reaperThread = null; @@ -212,40 +205,33 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding queueInfos.clear(); } - public boolean isStarted() - { + public boolean isStarted() { return started; } // NotificationListener implementation ------------------------------------- - public void onNotification(final Notification notification) - { - if (!(notification.getType() instanceof CoreNotificationType)) return; + public void onNotification(final Notification notification) { + if (!(notification.getType() instanceof CoreNotificationType)) + return; - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Receiving notification : " + notification + " on server " + this.server); } - synchronized (notificationLock) - { + synchronized (notificationLock) { CoreNotificationType type = (CoreNotificationType) notification.getType(); - switch (type) - { - case BINDING_ADDED: - { + switch (type) { + case BINDING_ADDED: { TypedProperties props = notification.getProperties(); - if (!props.containsProperty(ManagementHelper.HDR_BINDING_TYPE)) - { + if (!props.containsProperty(ManagementHelper.HDR_BINDING_TYPE)) { throw ActiveMQMessageBundle.BUNDLE.bindingTypeNotSpecified(); } Integer bindingType = props.getIntProperty(ManagementHelper.HDR_BINDING_TYPE); - if (bindingType == BindingType.DIVERT_INDEX) - { + if (bindingType == BindingType.DIVERT_INDEX) { // We don't propagate diverts return; } @@ -256,8 +242,7 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding SimpleString address = props.getSimpleStringProperty(ManagementHelper.HDR_ADDRESS); - if (!props.containsProperty(ManagementHelper.HDR_BINDING_ID)) - { + if (!props.containsProperty(ManagementHelper.HDR_BINDING_ID)) { throw ActiveMQMessageBundle.BUNDLE.bindingIdNotSpecified(); } @@ -265,8 +250,7 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding SimpleString filterString = props.getSimpleStringProperty(ManagementHelper.HDR_FILTERSTRING); - if (!props.containsProperty(ManagementHelper.HDR_DISTANCE)) - { + if (!props.containsProperty(ManagementHelper.HDR_DISTANCE)) { throw ActiveMQMessageBundle.BUNDLE.distancenotSpecified(); } @@ -278,12 +262,10 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding break; } - case BINDING_REMOVED: - { + case BINDING_REMOVED: { TypedProperties props = notification.getProperties(); - if (!props.containsProperty(ManagementHelper.HDR_CLUSTER_NAME)) - { + if (!props.containsProperty(ManagementHelper.HDR_CLUSTER_NAME)) { throw new IllegalStateException("No cluster name"); } @@ -291,19 +273,16 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding QueueInfo info = queueInfos.remove(clusterName); - if (info == null) - { + if (info == null) { throw new IllegalStateException("Cannot find queue info for queue " + clusterName); } break; } - case CONSUMER_CREATED: - { + case CONSUMER_CREATED: { TypedProperties props = notification.getProperties(); - if (!props.containsProperty(ManagementHelper.HDR_CLUSTER_NAME)) - { + if (!props.containsProperty(ManagementHelper.HDR_CLUSTER_NAME)) { throw new IllegalStateException("No cluster name"); } @@ -313,19 +292,16 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding QueueInfo info = queueInfos.get(clusterName); - if (info == null) - { + if (info == null) { throw new IllegalStateException("Cannot find queue info for queue " + clusterName); } info.incrementConsumers(); - if (filterString != null) - { + if (filterString != null) { List filterStrings = info.getFilterStrings(); - if (filterStrings == null) - { + if (filterStrings == null) { filterStrings = new ArrayList(); info.setFilterStrings(filterStrings); @@ -334,36 +310,30 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding filterStrings.add(filterString); } - if (!props.containsProperty(ManagementHelper.HDR_DISTANCE)) - { + if (!props.containsProperty(ManagementHelper.HDR_DISTANCE)) { throw new IllegalStateException("No distance"); } int distance = props.getIntProperty(ManagementHelper.HDR_DISTANCE); - if (distance > 0) - { + if (distance > 0) { SimpleString queueName = props.getSimpleStringProperty(ManagementHelper.HDR_ROUTING_NAME); - if (queueName == null) - { + if (queueName == null) { throw new IllegalStateException("No queue name"); } Binding binding = getBinding(queueName); - if (binding != null) - { + if (binding != null) { // We have a local queue Queue queue = (Queue) binding.getBindable(); - AddressSettings addressSettings = addressSettingsRepository.getMatch(binding.getAddress() - .toString()); + AddressSettings addressSettings = addressSettingsRepository.getMatch(binding.getAddress().toString()); long redistributionDelay = addressSettings.getRedistributionDelay(); - if (redistributionDelay != -1) - { + if (redistributionDelay != -1) { queue.addRedistributor(redistributionDelay); } } @@ -371,14 +341,12 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding break; } - case CONSUMER_CLOSED: - { + case CONSUMER_CLOSED: { TypedProperties props = notification.getProperties(); SimpleString clusterName = props.getSimpleStringProperty(ManagementHelper.HDR_CLUSTER_NAME); - if (clusterName == null) - { + if (clusterName == null) { throw new IllegalStateException("No cluster name"); } @@ -386,54 +354,45 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding QueueInfo info = queueInfos.get(clusterName); - if (info == null) - { + if (info == null) { return; } info.decrementConsumers(); - if (filterString != null) - { + if (filterString != null) { List filterStrings = info.getFilterStrings(); filterStrings.remove(filterString); } - if (info.getNumberOfConsumers() == 0) - { - if (!props.containsProperty(ManagementHelper.HDR_DISTANCE)) - { + if (info.getNumberOfConsumers() == 0) { + if (!props.containsProperty(ManagementHelper.HDR_DISTANCE)) { throw new IllegalStateException("No cluster name"); } int distance = props.getIntProperty(ManagementHelper.HDR_DISTANCE); - if (distance == 0) - { + if (distance == 0) { SimpleString queueName = props.getSimpleStringProperty(ManagementHelper.HDR_ROUTING_NAME); - if (queueName == null) - { + if (queueName == null) { throw new IllegalStateException("No queue name"); } Binding binding = getBinding(queueName); - if (binding == null) - { + if (binding == null) { throw new IllegalStateException("No queue " + queueName); } Queue queue = (Queue) binding.getBindable(); - AddressSettings addressSettings = addressSettingsRepository.getMatch(binding.getAddress() - .toString()); + AddressSettings addressSettings = addressSettingsRepository.getMatch(binding.getAddress().toString()); long redistributionDelay = addressSettings.getRedistributionDelay(); - if (redistributionDelay != -1) - { + if (redistributionDelay != -1) { queue.addRedistributor(redistributionDelay); } } @@ -441,8 +400,7 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding break; } - default: - { + default: { break; } } @@ -456,8 +414,7 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding // Otherwise can have situation where createQueue comes in before failover, then failover occurs // and post office is activated but queue remains unactivated after failover so delivery never occurs // even though failover is complete - public synchronized void addBinding(final Binding binding) throws Exception - { + public synchronized void addBinding(final Binding binding) throws Exception { addressManager.addBinding(binding); TypedProperties props = new TypedProperties(); @@ -476,35 +433,30 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding Filter filter = binding.getFilter(); - if (filter != null) - { + if (filter != null) { props.putSimpleStringProperty(ManagementHelper.HDR_FILTERSTRING, filter.getFilterString()); } String uid = UUIDGenerator.getInstance().generateStringUUID(); - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("ClusterCommunication::Sending notification for addBinding " + binding + " from server " + server); } managementService.sendNotification(new Notification(uid, CoreNotificationType.BINDING_ADDED, props)); } - public synchronized Binding removeBinding(final SimpleString uniqueName, Transaction tx) throws Exception - { + public synchronized Binding removeBinding(final SimpleString uniqueName, Transaction tx) throws Exception { addressSettingsRepository.clearCache(); Binding binding = addressManager.removeBinding(uniqueName, tx); - if (binding == null) - { + if (binding == null) { throw new ActiveMQNonExistentQueueException(); } - if (addressManager.getBindingsForRoutingAddress(binding.getAddress()) == null) - { + if (addressManager.getBindingsForRoutingAddress(binding.getAddress()) == null) { pagingManager.deletePageStore(binding.getAddress()); managementService.unregisterAddress(binding.getAddress()); @@ -512,17 +464,14 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding deleteDuplicateCache(binding.getAddress()); } - if (binding.getType() == BindingType.LOCAL_QUEUE) - { + if (binding.getType() == BindingType.LOCAL_QUEUE) { managementService.unregisterQueue(uniqueName, binding.getAddress()); } - else if (binding.getType() == BindingType.DIVERT) - { + else if (binding.getType() == BindingType.DIVERT) { managementService.unregisterDivert(uniqueName); } - if (binding.getType() != BindingType.DIVERT) - { + if (binding.getType() != BindingType.DIVERT) { TypedProperties props = new TypedProperties(); props.putSimpleStringProperty(ManagementHelper.HDR_ADDRESS, binding.getAddress()); @@ -535,12 +484,10 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding props.putLongProperty(ManagementHelper.HDR_BINDING_ID, binding.getID()); - if (binding.getFilter() == null) - { + if (binding.getFilter() == null) { props.putSimpleStringProperty(ManagementHelper.HDR_FILTERSTRING, null); } - else - { + else { props.putSimpleStringProperty(ManagementHelper.HDR_FILTERSTRING, binding.getFilter().getFilterString()); } @@ -552,71 +499,60 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding return binding; } - private void deleteDuplicateCache(SimpleString address) throws Exception - { + private void deleteDuplicateCache(SimpleString address) throws Exception { DuplicateIDCache cache = duplicateIDCaches.remove(address); - if (cache != null) - { + if (cache != null) { cache.clear(); } cache = duplicateIDCaches.remove(BRIDGE_CACHE_STR.concat(address)); - if (cache != null) - { + if (cache != null) { cache.clear(); } } @Override - public boolean isAddressBound(final SimpleString address) throws Exception - { + public boolean isAddressBound(final SimpleString address) throws Exception { Bindings bindings = getBindingsForAddress(address); return bindings != null && !bindings.getBindings().isEmpty(); } - - public Bindings getBindingsForAddress(final SimpleString address) throws Exception - { + public Bindings getBindingsForAddress(final SimpleString address) throws Exception { Bindings bindings = addressManager.getBindingsForRoutingAddress(address); - if (bindings == null) - { + if (bindings == null) { bindings = createBindings(address); } return bindings; } - - public Bindings lookupBindingsForAddress(final SimpleString address) throws Exception - { + public Bindings lookupBindingsForAddress(final SimpleString address) throws Exception { return addressManager.getBindingsForRoutingAddress(address); } - public Binding getBinding(final SimpleString name) - { + public Binding getBinding(final SimpleString name) { return addressManager.getBinding(name); } - public Bindings getMatchingBindings(final SimpleString address) throws Exception - { + public Bindings getMatchingBindings(final SimpleString address) throws Exception { return addressManager.getMatchingBindings(address); } - public Map getAllBindings() - { + public Map getAllBindings() { return addressManager.getBindings(); } - public void route(final ServerMessage message, QueueCreator queueCreator, final boolean direct) throws Exception - { + public void route(final ServerMessage message, QueueCreator queueCreator, final boolean direct) throws Exception { route(message, queueCreator, (Transaction) null, direct); } - public void route(final ServerMessage message, QueueCreator queueCreator, final Transaction tx, final boolean direct) throws Exception - { + public void route(final ServerMessage message, + QueueCreator queueCreator, + final Transaction tx, + final boolean direct) throws Exception { route(message, queueCreator, new RoutingContextImpl(tx), direct); } @@ -624,13 +560,14 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding final QueueCreator queueCreator, final Transaction tx, final boolean direct, - final boolean rejectDuplicates) throws Exception - { + final boolean rejectDuplicates) throws Exception { route(message, queueCreator, new RoutingContextImpl(tx), direct, rejectDuplicates); } - public void route(final ServerMessage message, final QueueCreator queueCreator, final RoutingContext context, final boolean direct) throws Exception - { + public void route(final ServerMessage message, + final QueueCreator queueCreator, + final RoutingContext context, + final boolean direct) throws Exception { route(message, queueCreator, context, direct, true); } @@ -638,11 +575,9 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding final QueueCreator queueCreator, final RoutingContext context, final boolean direct, - boolean rejectDuplicates) throws Exception - { + boolean rejectDuplicates) throws Exception { // Sanity check - if (message.getRefCount() > 0) - { + if (message.getRefCount() > 0) { throw new IllegalStateException("Message cannot be routed more than once"); } @@ -654,13 +589,11 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding applyExpiryDelay(message, address); - if (!checkDuplicateID(message, context, rejectDuplicates, startedTX)) - { + if (!checkDuplicateID(message, context, rejectDuplicates, startedTX)) { return; } - if (message.hasInternalProperties()) - { + if (message.hasInternalProperties()) { // We need to perform some cleanup on internal properties, // but we don't do it every time, otherwise it wouldn't be optimal cleanupInternalPropertiesBeforeRouting(message); @@ -669,60 +602,49 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding Bindings bindings = addressManager.getBindingsForRoutingAddress(address); // first check for the auto-queue creation thing - if (bindings == null && queueCreator != null) - { + if (bindings == null && queueCreator != null) { // There is no queue with this address, we will check if it needs to be created - if (queueCreator.create(address)) - { + if (queueCreator.create(address)) { // TODO: this is not working!!!! // reassign bindings if it was created bindings = addressManager.getBindingsForRoutingAddress(address); } } - if (bindings != null) - { + if (bindings != null) { bindings.route(message, context); } - else - { + else { // this is a debug and not warn because this could be a regular scenario on publish-subscribe queues (or topic subscriptions on JMS) - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Couldn't find any bindings for address=" + address + " on message=" + message); } } - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("Message after routed=" + message); } - if (context.getQueueCount() == 0) - { + if (context.getQueueCount() == 0) { // Send to DLA if appropriate AddressSettings addressSettings = addressSettingsRepository.getMatch(address.toString()); boolean sendToDLA = addressSettings.isSendToDLAOnNoRoute(); - if (sendToDLA) - { + if (sendToDLA) { // Send to the DLA for the address SimpleString dlaAddress = addressSettings.getDeadLetterAddress(); - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("sending message to dla address = " + dlaAddress + ", message=" + message); } - if (dlaAddress == null) - { + if (dlaAddress == null) { ActiveMQServerLogger.LOGGER.noDLA(address); } - else - { + else { message.setOriginalHeaders(message, null, false); message.setAddress(dlaAddress); @@ -730,69 +652,57 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding route(message, null, context.getTransaction(), false); } } - else - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + else { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Message " + message + " is not going anywhere as it didn't have a binding on address:" + address); } - if (message.isLargeMessage()) - { + if (message.isLargeMessage()) { ((LargeServerMessage) message).deleteFile(); } } } - else - { - try - { + else { + try { processRoute(message, context, direct); } - catch (ActiveMQAddressFullException e) - { - if (startedTX.get()) - { + catch (ActiveMQAddressFullException e) { + if (startedTX.get()) { context.getTransaction().rollback(); } - else if (context.getTransaction() != null) - { + else if (context.getTransaction() != null) { context.getTransaction().markAsRollbackOnly(e); } throw e; } } - if (startedTX.get()) - { + if (startedTX.get()) { context.getTransaction().commit(); } } // HORNETQ-1029 - private void applyExpiryDelay(ServerMessage message, SimpleString address) - { + private void applyExpiryDelay(ServerMessage message, SimpleString address) { long expirationOverride = addressSettingsRepository.getMatch(address.toString()).getExpiryDelay(); // A -1 means don't do anything - if (expirationOverride >= 0) - { + if (expirationOverride >= 0) { // only override the exiration on messages where the expiration hasn't been set by the user - if (message.getExpiration() == 0) - { + if (message.getExpiration() == 0) { message.setExpiration(System.currentTimeMillis() + expirationOverride); } } } - public MessageReference reroute(final ServerMessage message, final Queue queue, final Transaction tx) throws Exception - { + public MessageReference reroute(final ServerMessage message, + final Queue queue, + final Transaction tx) throws Exception { setPagingStore(message); MessageReference reference = message.createReference(queue); - if (message.containsProperty(Message.HDR_SCHEDULED_DELIVERY_TIME)) - { + if (message.containsProperty(Message.HDR_SCHEDULED_DELIVERY_TIME)) { Long scheduledDeliveryTime = message.getLongProperty(Message.HDR_SCHEDULED_DELIVERY_TIME); reference.setScheduledDeliveryTime(scheduledDeliveryTime); } @@ -801,12 +711,10 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding message.incrementRefCount(); - if (tx == null) - { + if (tx == null) { queue.reload(reference); } - else - { + else { List refs = new ArrayList(1); refs.add(reference); @@ -820,8 +728,9 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding /** * The redistribution can't process the route right away as we may be dealing with a large message which will need to be processed on a different thread */ - public Pair redistribute(final ServerMessage message, final Queue originatingQueue, final Transaction tx) throws Exception - { + public Pair redistribute(final ServerMessage message, + final Queue originatingQueue, + final Transaction tx) throws Exception { // We have to copy the message and store it separately, otherwise we may lose remote bindings in case of restart before the message // arrived the target node // as described on https://issues.jboss.org/browse/JBPAPP-6130 @@ -829,14 +738,12 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding Bindings bindings = addressManager.getBindingsForRoutingAddress(message.getAddress()); - if (bindings != null) - { + if (bindings != null) { RoutingContext context = new RoutingContextImpl(tx); boolean routed = bindings.redistribute(copyRedistribute, originatingQueue, context); - if (routed) - { + if (routed) { return new Pair(context, copyRedistribute); } } @@ -844,18 +751,15 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding return null; } - public DuplicateIDCache getDuplicateIDCache(final SimpleString address) - { + public DuplicateIDCache getDuplicateIDCache(final SimpleString address) { DuplicateIDCache cache = duplicateIDCaches.get(address); - if (cache == null) - { + if (cache == null) { cache = new DuplicateIDCacheImpl(address, idCacheSize, storageManager, persistIDCache); DuplicateIDCache oldCache = duplicateIDCaches.putIfAbsent(address, cache); - if (oldCache != null) - { + if (oldCache != null) { cache = oldCache; } } @@ -863,43 +767,36 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding return cache; } - public ConcurrentMap getDuplicateIDCaches() - { + public ConcurrentMap getDuplicateIDCaches() { return duplicateIDCaches; } - public Object getNotificationLock() - { + public Object getNotificationLock() { return notificationLock; } - public Set getAddresses() - { + public Set getAddresses() { return addressManager.getAddresses(); } - public void sendQueueInfoToQueue(final SimpleString queueName, final SimpleString address) throws Exception - { + public void sendQueueInfoToQueue(final SimpleString queueName, final SimpleString address) throws Exception { // We send direct to the queue so we can send it to the same queue that is bound to the notifications address - // this is crucial for ensuring // that queue infos and notifications are received in a contiguous consistent stream Binding binding = addressManager.getBinding(queueName); - if (binding == null) - { + if (binding == null) { throw new IllegalStateException("Cannot find queue " + queueName); } - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("PostOffice.sendQueueInfoToQueue on server=" + this.server + ", queueName=" + queueName + " and address=" + address); } Queue queue = (Queue) binding.getBindable(); // Need to lock to make sure all queue info and notifications are in the correct order with no gaps - synchronized (notificationLock) - { + synchronized (notificationLock) { // First send a reset message ServerMessage message = new ServerMessageImpl(storageManager.generateID(), 50); @@ -908,14 +805,11 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding message.putBooleanProperty(PostOfficeImpl.HDR_RESET_QUEUE_DATA, true); routeQueueInfo(message, queue, false); - for (QueueInfo info : queueInfos.values()) - { - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + for (QueueInfo info : queueInfos.values()) { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("QueueInfo on sendQueueInfoToQueue = " + info); } - if (info.matchesAddress(address)) - { + if (info.matchesAddress(address)) { message = createQueueInfoMessage(CoreNotificationType.BINDING_ADDED, queueName); message.putStringProperty(ManagementHelper.HDR_ADDRESS, info.getAddress()); @@ -929,8 +823,7 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding int consumersWithFilters = info.getFilterStrings() != null ? info.getFilterStrings().size() : 0; - for (int i = 0; i < info.getNumberOfConsumers() - consumersWithFilters; i++) - { + for (int i = 0; i < info.getNumberOfConsumers() - consumersWithFilters; i++) { message = createQueueInfoMessage(CoreNotificationType.CONSUMER_CREATED, queueName); message.putStringProperty(ManagementHelper.HDR_ADDRESS, info.getAddress()); @@ -941,10 +834,8 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding routeQueueInfo(message, queue, true); } - if (info.getFilterStrings() != null) - { - for (SimpleString filterString : info.getFilterStrings()) - { + if (info.getFilterStrings() != null) { + for (SimpleString filterString : info.getFilterStrings()) { message = createQueueInfoMessage(CoreNotificationType.CONSUMER_CREATED, queueName); message.putStringProperty(ManagementHelper.HDR_ADDRESS, info.getAddress()); @@ -971,8 +862,7 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding * @see java.lang.Object#toString() */ @Override - public String toString() - { + public String toString() { return "PostOfficeImpl [server=" + server + "]"; } @@ -981,47 +871,37 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding /** * @param message */ - protected void cleanupInternalPropertiesBeforeRouting(final ServerMessage message) - { + protected void cleanupInternalPropertiesBeforeRouting(final ServerMessage message) { LinkedList valuesToRemove = null; - - for (SimpleString name : message.getPropertyNames()) - { + for (SimpleString name : message.getPropertyNames()) { // We use properties to establish routing context on clustering. // However if the client resends the message after receiving, it needs to be removed - if ((name.startsWith(MessageImpl.HDR_ROUTE_TO_IDS) && !name.equals(MessageImpl.HDR_ROUTE_TO_IDS)) || - (name.startsWith(MessageImpl.HDR_ROUTE_TO_ACK_IDS) && !name.equals(MessageImpl.HDR_ROUTE_TO_ACK_IDS))) - { - if (valuesToRemove == null) - { + if ((name.startsWith(MessageImpl.HDR_ROUTE_TO_IDS) && !name.equals(MessageImpl.HDR_ROUTE_TO_IDS)) || (name.startsWith(MessageImpl.HDR_ROUTE_TO_ACK_IDS) && !name.equals(MessageImpl.HDR_ROUTE_TO_ACK_IDS))) { + if (valuesToRemove == null) { valuesToRemove = new LinkedList(); } valuesToRemove.add(name); } } - if (valuesToRemove != null) - { - for (SimpleString removal : valuesToRemove) - { + if (valuesToRemove != null) { + for (SimpleString removal : valuesToRemove) { message.removeProperty(removal); } } } - - private void setPagingStore(final ServerMessage message) throws Exception - { + private void setPagingStore(final ServerMessage message) throws Exception { PagingStore store = pagingManager.getPageStore(message.getAddress()); message.setPagingStore(store); } - private void routeQueueInfo(final ServerMessage message, final Queue queue, final boolean applyFilters) throws Exception - { - if (!applyFilters || queue.getFilter() == null || queue.getFilter().match(message)) - { + private void routeQueueInfo(final ServerMessage message, + final Queue queue, + final boolean applyFilters) throws Exception { + if (!applyFilters || queue.getFilter() == null || queue.getFilter().match(message)) { RoutingContext context = new RoutingContextImpl(null); queue.route(message, context); @@ -1030,49 +910,43 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding } } - private static class PageDelivery extends TransactionOperationAbstract - { + private static class PageDelivery extends TransactionOperationAbstract { + private final Set queues = new HashSet(); - public void addQueues(List queueList) - { + public void addQueues(List queueList) { queues.addAll(queueList); } @Override - public void afterCommit(Transaction tx) - { + public void afterCommit(Transaction tx) { // We need to try delivering async after paging, or nothing may start a delivery after paging since nothing is // going towards the queues // The queue will try to depage case it's empty - for (Queue queue : queues) - { + for (Queue queue : queues) { queue.deliverAsync(); } } @Override - public List getRelatedMessageReferences() - { + public List getRelatedMessageReferences() { return Collections.emptyList(); } } - public void processRoute(final ServerMessage message, final RoutingContext context, final boolean direct) throws Exception - { + public void processRoute(final ServerMessage message, + final RoutingContext context, + final boolean direct) throws Exception { final List refs = new ArrayList(); Transaction tx = context.getTransaction(); - for (Map.Entry entry : context.getContexListing().entrySet()) - { + for (Map.Entry entry : context.getContexListing().entrySet()) { PagingStore store = pagingManager.getPageStore(entry.getKey()); - if (storageManager.addToPage(store, message, context.getTransaction(), entry.getValue())) - { - if (message.isLargeMessage()) - { + if (storageManager.addToPage(store, message, context.getTransaction(), entry.getValue())) { + if (message.isLargeMessage()) { confirmLargeMessageSend(tx, message); } @@ -1081,13 +955,11 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding continue; } - for (Queue queue : entry.getValue().getNonDurableQueues()) - { + for (Queue queue : entry.getValue().getNonDurableQueues()) { MessageReference reference = message.createReference(queue); refs.add(reference); - if (message.containsProperty(Message.HDR_SCHEDULED_DELIVERY_TIME)) - { + if (message.containsProperty(Message.HDR_SCHEDULED_DELIVERY_TIME)) { Long scheduledDeliveryTime = message.getLongProperty(Message.HDR_SCHEDULED_DELIVERY_TIME); reference.setScheduledDeliveryTime(scheduledDeliveryTime); @@ -1098,70 +970,56 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding Iterator iter = entry.getValue().getDurableQueues().iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { Queue queue = iter.next(); MessageReference reference = message.createReference(queue); - if (context.isAlreadyAcked(message.getAddress(), queue)) - { + if (context.isAlreadyAcked(message.getAddress(), queue)) { reference.setAlreadyAcked(); - if (tx != null) - { + if (tx != null) { queue.acknowledge(tx, reference); } } refs.add(reference); - if (message.containsProperty(Message.HDR_SCHEDULED_DELIVERY_TIME)) - { + if (message.containsProperty(Message.HDR_SCHEDULED_DELIVERY_TIME)) { Long scheduledDeliveryTime = message.getLongProperty(Message.HDR_SCHEDULED_DELIVERY_TIME); reference.setScheduledDeliveryTime(scheduledDeliveryTime); } - if (message.isDurable()) - { + if (message.isDurable()) { int durableRefCount = message.incrementDurableRefCount(); - if (durableRefCount == 1) - { - if (tx != null) - { + if (durableRefCount == 1) { + if (tx != null) { storageManager.storeMessageTransactional(tx.getID(), message); } - else - { + else { storageManager.storeMessage(message); } - if (message.isLargeMessage()) - { + if (message.isLargeMessage()) { confirmLargeMessageSend(tx, message); } } - if (tx != null) - { + if (tx != null) { storageManager.storeReferenceTransactional(tx.getID(), queue.getID(), message.getMessageID()); tx.setContainsPersistent(); } - else - { + else { storageManager.storeReference(queue.getID(), message.getMessageID(), !iter.hasNext()); } - if (message.containsProperty(Message.HDR_SCHEDULED_DELIVERY_TIME)) - { - if (tx != null) - { + if (message.containsProperty(Message.HDR_SCHEDULED_DELIVERY_TIME)) { + if (tx != null) { storageManager.updateScheduledDeliveryTimeTransactional(tx.getID(), reference); } - else - { + else { storageManager.updateScheduledDeliveryTime(reference); } } @@ -1171,23 +1029,18 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding } } - if (tx != null) - { + if (tx != null) { tx.addOperation(new AddOperation(refs)); } - else - { + else { // This will use the same thread if there are no pending operations // avoiding a context switch on this case - storageManager.afterCompleteOperations(new IOCallback() - { - public void onError(final int errorCode, final String errorMessage) - { + storageManager.afterCompleteOperations(new IOCallback() { + public void onError(final int errorCode, final String errorMessage) { ActiveMQServerLogger.LOGGER.ioErrorAddingReferences(errorCode, errorMessage); } - public void done() - { + public void done() { addReferences(refs, direct); } }); @@ -1199,19 +1052,14 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding * @param message * @throws Exception */ - private void confirmLargeMessageSend(Transaction tx, final ServerMessage message) throws Exception - { + private void confirmLargeMessageSend(Transaction tx, final ServerMessage message) throws Exception { LargeServerMessage largeServerMessage = (LargeServerMessage) message; - if (largeServerMessage.getPendingRecordID() >= 0) - { - if (tx == null) - { + if (largeServerMessage.getPendingRecordID() >= 0) { + if (tx == null) { storageManager.confirmPendingLargeMessage(largeServerMessage.getPendingRecordID()); } - else - { - storageManager.confirmPendingLargeMessageTX(tx, largeServerMessage.getMessageID(), - largeServerMessage.getPendingRecordID()); + else { + storageManager.confirmPendingLargeMessageTX(tx, largeServerMessage.getMessageID(), largeServerMessage.getPendingRecordID()); } largeServerMessage.setPendingRecordID(-1); } @@ -1223,13 +1071,10 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding * @param tx * @param entry */ - private void schedulePageDelivery(Transaction tx, Map.Entry entry) - { - if (tx != null) - { + private void schedulePageDelivery(Transaction tx, Map.Entry entry) { + if (tx != null) { PageDelivery delivery = (PageDelivery) tx.getProperty(TransactionPropertyIndexes.PAGE_DELIVERY); - if (delivery == null) - { + if (delivery == null) { delivery = new PageDelivery(); tx.putProperty(TransactionPropertyIndexes.PAGE_DELIVERY, delivery); tx.addOperation(delivery); @@ -1238,8 +1083,7 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding delivery.addQueues(entry.getValue().getDurableQueues()); delivery.addQueues(entry.getValue().getNonDurableQueues()); } - else - { + else { List durableQueues = entry.getValue().getDurableQueues(); List nonDurableQueues = entry.getValue().getNonDurableQueues(); @@ -1249,17 +1093,13 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding queues.addAll(durableQueues); queues.addAll(nonDurableQueues); - storageManager.afterCompleteOperations(new IOCallback() - { + storageManager.afterCompleteOperations(new IOCallback() { - public void onError(int errorCode, String errorMessage) - { + public void onError(int errorCode, String errorMessage) { } - public void done() - { - for (Queue queue : queues) - { + public void done() { + for (Queue queue : queues) { // in case of paging, we need to kick asynchronous delivery to try delivering queue.deliverAsync(); } @@ -1271,24 +1111,20 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding private boolean checkDuplicateID(final ServerMessage message, final RoutingContext context, boolean rejectDuplicates, - AtomicBoolean startedTX) throws Exception - { + AtomicBoolean startedTX) throws Exception { // Check the DuplicateCache for the Bridge first Object bridgeDup = message.getObjectProperty(MessageImpl.HDR_BRIDGE_DUPLICATE_ID); - if (bridgeDup != null) - { + if (bridgeDup != null) { // if the message is being sent from the bridge, we just ignore the duplicate id, and use the internal one byte[] bridgeDupBytes = (byte[]) bridgeDup; DuplicateIDCache cacheBridge = getDuplicateIDCache(BRIDGE_CACHE_STR.concat(message.getAddress())); - if (cacheBridge.contains(bridgeDupBytes)) - { + if (cacheBridge.contains(bridgeDupBytes)) { ActiveMQServerLogger.LOGGER.duplicateMessageDetectedThruBridge(message); - if (context.getTransaction() != null) - { + if (context.getTransaction() != null) { context.getTransaction().markAsRollbackOnly(new ActiveMQDuplicateIdException()); } @@ -1296,10 +1132,8 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding return false; } - else - { - if (context.getTransaction() == null) - { + else { + if (context.getTransaction() == null) { context.setTransaction(new TransactionImpl(storageManager)); startedTX.set(true); } @@ -1310,8 +1144,7 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding message.removeProperty(MessageImpl.HDR_BRIDGE_DUPLICATE_ID); } - else - { + else { // if used BridgeDuplicate, it's not going to use the regular duplicate // since this will would break redistribution (re-setting the duplicateId) byte[] duplicateIDBytes = message.getDuplicateIDBytes(); @@ -1320,20 +1153,17 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding boolean isDuplicate = false; - if (duplicateIDBytes != null) - { + if (duplicateIDBytes != null) { cache = getDuplicateIDCache(message.getAddress()); isDuplicate = cache.contains(duplicateIDBytes); - if (rejectDuplicates && isDuplicate) - { + if (rejectDuplicates && isDuplicate) { ActiveMQServerLogger.LOGGER.duplicateMessageDetected(message); String warnMessage = "Duplicate message detected - message will not be routed. Message information:" + message.toString(); - if (context.getTransaction() != null) - { + if (context.getTransaction() != null) { context.getTransaction().markAsRollbackOnly(new ActiveMQDuplicateIdException(warnMessage)); } @@ -1343,10 +1173,8 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding } } - if (cache != null && !isDuplicate) - { - if (context.getTransaction() == null) - { + if (cache != null && !isDuplicate) { + if (context.getTransaction() == null) { // We need to store the duplicate id atomically with the message storage, so we need to create a tx for this context.setTransaction(new TransactionImpl(storageManager)); @@ -1363,10 +1191,8 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding /** * @param refs */ - private void addReferences(final List refs, final boolean direct) - { - for (MessageReference ref : refs) - { + private void addReferences(final List refs, final boolean direct) { + for (MessageReference ref : refs) { ref.getQueue().addTail(ref, direct); } } @@ -1374,10 +1200,8 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding /** * The expiry scanner can't be started until the whole server has been started other wise you may get races */ - public synchronized void startExpiryScanner() - { - if (reaperPeriod > 0) - { + public synchronized void startExpiryScanner() { + if (reaperPeriod > 0) { if (reaperRunnable != null) reaperRunnable.stop(); reaperRunnable = new Reaper(); @@ -1389,8 +1213,7 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding } } - private ServerMessage createQueueInfoMessage(final NotificationType type, final SimpleString queueName) - { + private ServerMessage createQueueInfoMessage(final NotificationType type, final SimpleString queueName) { ServerMessage message = new ServerMessageImpl(storageManager.generateID(), 50); message.setAddress(queueName); @@ -1405,28 +1228,23 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding return message; } - private final class Reaper implements Runnable - { + private final class Reaper implements Runnable { + private final CountDownLatch latch = new CountDownLatch(1); - public void stop() - { + public void stop() { latch.countDown(); } - public void run() - { + public void run() { // The reaper thread should be finished case the PostOffice is gone // This is to avoid leaks on PostOffice between stops and starts - while (isStarted()) - { - try - { + while (isStarted()) { + try { if (latch.await(reaperPeriod, TimeUnit.MILLISECONDS)) return; } - catch (InterruptedException e1) - { + catch (InterruptedException e1) { throw new ActiveMQInterruptedException(e1); } if (!isStarted()) @@ -1436,24 +1254,19 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding List queues = new ArrayList(); - for (Binding binding : nameMap.values()) - { - if (binding.getType() == BindingType.LOCAL_QUEUE) - { + for (Binding binding : nameMap.values()) { + if (binding.getType() == BindingType.LOCAL_QUEUE) { Queue queue = (Queue) binding.getBindable(); queues.add(queue); } } - for (Queue queue : queues) - { - try - { + for (Queue queue : queues) { + try { queue.expireReferences(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorExpiringMessages(e); } } @@ -1461,60 +1274,47 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding } } - public static final class AddOperation implements TransactionOperation - { + public static final class AddOperation implements TransactionOperation { + private final List refs; - AddOperation(final List refs) - { + AddOperation(final List refs) { this.refs = refs; } - public void afterCommit(final Transaction tx) - { - for (MessageReference ref : refs) - { - if (!ref.isAlreadyAcked()) - { + public void afterCommit(final Transaction tx) { + for (MessageReference ref : refs) { + if (!ref.isAlreadyAcked()) { ref.getQueue().addTail(ref, false); } } } - public void afterPrepare(final Transaction tx) - { - for (MessageReference ref : refs) - { - if (ref.isAlreadyAcked()) - { + public void afterPrepare(final Transaction tx) { + for (MessageReference ref : refs) { + if (ref.isAlreadyAcked()) { ref.getQueue().referenceHandled(); ref.getQueue().incrementMesssagesAdded(); } } } - public void afterRollback(final Transaction tx) - { + public void afterRollback(final Transaction tx) { } - public void beforeCommit(final Transaction tx) throws Exception - { + public void beforeCommit(final Transaction tx) throws Exception { } - public void beforePrepare(final Transaction tx) throws Exception - { + public void beforePrepare(final Transaction tx) throws Exception { } - public void beforeRollback(final Transaction tx) throws Exception - { + public void beforeRollback(final Transaction tx) throws Exception { // Reverse the ref counts, and paging sizes - for (MessageReference ref : refs) - { + for (MessageReference ref : refs) { ServerMessage message = ref.getMessage(); - if (message.isDurable() && ref.getQueue().isDurable()) - { + if (message.isDurable() && ref.getQueue().isDurable()) { message.decrementDurableRefCount(); } @@ -1522,37 +1322,31 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding } } - public List getRelatedMessageReferences() - { + public List getRelatedMessageReferences() { return refs; } @Override - public List getListOnConsumer(long consumerID) - { + public List getListOnConsumer(long consumerID) { return Collections.emptyList(); } } - public Bindings createBindings(final SimpleString address) throws Exception - { + public Bindings createBindings(final SimpleString address) throws Exception { GroupingHandler groupingHandler = server.getGroupingHandler(); BindingsImpl bindings = new BindingsImpl(address, groupingHandler, pagingManager.getPageStore(address)); - if (groupingHandler != null) - { + if (groupingHandler != null) { groupingHandler.addListener(bindings); } return bindings; } // For tests only - public AddressManager getAddressManager() - { + public AddressManager getAddressManager() { return addressManager; } - public ActiveMQServer getServer() - { + public ActiveMQServer getServer() { return server; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/SimpleAddressManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/SimpleAddressManager.java index a3cfec4868..c40182534e 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/SimpleAddressManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/SimpleAddressManager.java @@ -37,8 +37,8 @@ import org.apache.activemq.artemis.utils.ConcurrentHashSet; /** * A simple address manager that maintains the addresses and bindings. */ -public class SimpleAddressManager implements AddressManager -{ +public class SimpleAddressManager implements AddressManager { + /** * HashMap */ @@ -53,50 +53,40 @@ public class SimpleAddressManager implements AddressManager private final BindingsFactory bindingsFactory; - public SimpleAddressManager(final BindingsFactory bindingsFactory) - { + public SimpleAddressManager(final BindingsFactory bindingsFactory) { this.bindingsFactory = bindingsFactory; } - public boolean addBinding(final Binding binding) throws Exception - { - if (nameMap.putIfAbsent(binding.getUniqueName(), binding) != null || pendingDeletes.contains(binding.getUniqueName())) - { + public boolean addBinding(final Binding binding) throws Exception { + if (nameMap.putIfAbsent(binding.getUniqueName(), binding) != null || pendingDeletes.contains(binding.getUniqueName())) { throw ActiveMQMessageBundle.BUNDLE.bindingAlreadyExists(binding); } - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("Adding binding " + binding + " with address = " + binding.getUniqueName(), new Exception("trace")); } return addMappingInternal(binding.getAddress(), binding); } - public Binding removeBinding(final SimpleString uniqueName, Transaction tx) throws Exception - { + public Binding removeBinding(final SimpleString uniqueName, Transaction tx) throws Exception { final Binding binding = nameMap.remove(uniqueName); - if (binding == null) - { + if (binding == null) { return null; } - if (tx != null) - { + if (tx != null) { pendingDeletes.add(uniqueName); - tx.addOperation(new TransactionOperationAbstract() - { + tx.addOperation(new TransactionOperationAbstract() { @Override - public void afterCommit(Transaction tx) - { + public void afterCommit(Transaction tx) { pendingDeletes.remove(uniqueName); } @Override - public void afterRollback(Transaction tx) - { + public void afterRollback(Transaction tx) { nameMap.put(uniqueName, binding); pendingDeletes.remove(uniqueName); } @@ -109,33 +99,27 @@ public class SimpleAddressManager implements AddressManager return binding; } - public Bindings getBindingsForRoutingAddress(final SimpleString address) throws Exception - { + public Bindings getBindingsForRoutingAddress(final SimpleString address) throws Exception { return mappings.get(address); } - public Binding getBinding(final SimpleString bindableName) - { + public Binding getBinding(final SimpleString bindableName) { return nameMap.get(bindableName); } - public Map getBindings() - { + public Map getBindings() { return nameMap; } - public Bindings getMatchingBindings(final SimpleString address) throws Exception - { + public Bindings getMatchingBindings(final SimpleString address) throws Exception { Address add = new AddressImpl(address); Bindings bindings = bindingsFactory.createBindings(address); - for (Binding binding : nameMap.values()) - { + for (Binding binding : nameMap.values()) { Address addCheck = new AddressImpl(binding.getAddress()); - if (addCheck.matches(add)) - { + if (addCheck.matches(add)) { bindings.addBinding(binding); } } @@ -143,52 +127,42 @@ public class SimpleAddressManager implements AddressManager return bindings; } - public void clear() - { + public void clear() { nameMap.clear(); mappings.clear(); } - @Override - public Set getAddresses() - { + public Set getAddresses() { Set addresses = new HashSet<>(); addresses.addAll(mappings.keySet()); return addresses; } - protected void removeBindingInternal(final SimpleString address, final SimpleString bindableName) - { + protected void removeBindingInternal(final SimpleString address, final SimpleString bindableName) { Bindings bindings = mappings.get(address); - if (bindings != null) - { + if (bindings != null) { removeMapping(bindableName, bindings); - if (bindings.getBindings().isEmpty()) - { + if (bindings.getBindings().isEmpty()) { mappings.remove(address); } } } - protected Binding removeMapping(final SimpleString bindableName, final Bindings bindings) - { + protected Binding removeMapping(final SimpleString bindableName, final Bindings bindings) { Binding theBinding = null; - for (Binding binding : bindings.getBindings()) - { - if (binding.getUniqueName().equals(bindableName)) - { + for (Binding binding : bindings.getBindings()) { + if (binding.getUniqueName().equals(bindableName)) { theBinding = binding; break; } } - if (theBinding == null) - { + if (theBinding == null) { throw new IllegalStateException("Cannot find binding " + bindableName); } @@ -197,20 +171,17 @@ public class SimpleAddressManager implements AddressManager return theBinding; } - protected boolean addMappingInternal(final SimpleString address, final Binding binding) throws Exception - { + protected boolean addMappingInternal(final SimpleString address, final Binding binding) throws Exception { Bindings bindings = mappings.get(address); Bindings prevBindings = null; - if (bindings == null) - { + if (bindings == null) { bindings = bindingsFactory.createBindings(address); prevBindings = mappings.putIfAbsent(address, bindings); - if (prevBindings != null) - { + if (prevBindings != null) { bindings = prevBindings; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/WildcardAddressManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/WildcardAddressManager.java index 86caa928d5..7020e5d099 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/WildcardAddressManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/impl/WildcardAddressManager.java @@ -31,8 +31,8 @@ import org.apache.activemq.artemis.core.transaction.Transaction; /** * extends the simple manager to allow wildcard addresses to be used. */ -public class WildcardAddressManager extends SimpleAddressManager -{ +public class WildcardAddressManager extends SimpleAddressManager { + static final char SINGLE_WORD = '*'; static final char ANY_WORDS = '#'; @@ -51,30 +51,23 @@ public class WildcardAddressManager extends SimpleAddressManager private final Map wildCardAddresses = new ConcurrentHashMap(); - public WildcardAddressManager(final BindingsFactory bindingsFactory) - { + public WildcardAddressManager(final BindingsFactory bindingsFactory) { super(bindingsFactory); } @Override - public Bindings getBindingsForRoutingAddress(final SimpleString address) throws Exception - { + public Bindings getBindingsForRoutingAddress(final SimpleString address) throws Exception { Bindings bindings = super.getBindingsForRoutingAddress(address); // this should only happen if we're routing to an address that has no mappings when we're running checkAllowable - if (bindings == null && !wildCardAddresses.isEmpty()) - { + if (bindings == null && !wildCardAddresses.isEmpty()) { Address add = addAndUpdateAddressMap(address); - if (!add.containsWildCard()) - { - for (Address destAdd : add.getLinkedAddresses()) - { + if (!add.containsWildCard()) { + for (Address destAdd : add.getLinkedAddresses()) { Bindings b = super.getBindingsForRoutingAddress(destAdd.getAddress()); - if (b != null) - { + if (b != null) { Collection theBindings = b.getBindings(); - for (Binding theBinding : theBindings) - { + for (Binding theBinding : theBindings) { super.addMappingInternal(address, theBinding); } } @@ -93,26 +86,19 @@ public class WildcardAddressManager extends SimpleAddressManager * @return true if the address was a new mapping */ @Override - public boolean addBinding(final Binding binding) throws Exception - { + public boolean addBinding(final Binding binding) throws Exception { boolean exists = super.addBinding(binding); - if (!exists) - { + if (!exists) { Address add = addAndUpdateAddressMap(binding.getAddress()); - if (add.containsWildCard()) - { - for (Address destAdd : add.getLinkedAddresses()) - { + if (add.containsWildCard()) { + for (Address destAdd : add.getLinkedAddresses()) { super.addMappingInternal(destAdd.getAddress(), binding); } } - else - { - for (Address destAdd : add.getLinkedAddresses()) - { + else { + for (Address destAdd : add.getLinkedAddresses()) { Bindings bindings = super.getBindingsForRoutingAddress(destAdd.getAddress()); - for (Binding b : bindings.getBindings()) - { + for (Binding b : bindings.getBindings()) { super.addMappingInternal(binding.getAddress(), b); } } @@ -129,16 +115,12 @@ public class WildcardAddressManager extends SimpleAddressManager * @return true if this was the last mapping for a specific address */ @Override - public Binding removeBinding(final SimpleString uniqueName, Transaction tx) throws Exception - { + public Binding removeBinding(final SimpleString uniqueName, Transaction tx) throws Exception { Binding binding = super.removeBinding(uniqueName, tx); - if (binding != null) - { + if (binding != null) { Address add = getAddress(binding.getAddress()); - if (add.containsWildCard()) - { - for (Address theAddress : add.getLinkedAddresses()) - { + if (add.containsWildCard()) { + for (Address theAddress : add.getLinkedAddresses()) { super.removeBindingInternal(theAddress.getAddress(), uniqueName); } } @@ -148,62 +130,48 @@ public class WildcardAddressManager extends SimpleAddressManager } @Override - public void clear() - { + public void clear() { super.clear(); addresses.clear(); wildCardAddresses.clear(); } - private Address getAddress(final SimpleString address) - { + private Address getAddress(final SimpleString address) { Address add = new AddressImpl(address); Address actualAddress; - if (add.containsWildCard()) - { + if (add.containsWildCard()) { actualAddress = wildCardAddresses.get(address); } - else - { + else { actualAddress = addresses.get(address); } return actualAddress != null ? actualAddress : add; } - private synchronized Address addAndUpdateAddressMap(final SimpleString address) - { + private synchronized Address addAndUpdateAddressMap(final SimpleString address) { Address add = new AddressImpl(address); Address actualAddress; - if (add.containsWildCard()) - { + if (add.containsWildCard()) { actualAddress = wildCardAddresses.get(address); } - else - { + else { actualAddress = addresses.get(address); } - if (actualAddress == null) - { + if (actualAddress == null) { actualAddress = add; addAddress(address, actualAddress); } - if (actualAddress.containsWildCard()) - { - for (Address destAdd : addresses.values()) - { - if (destAdd.matches(actualAddress)) - { + if (actualAddress.containsWildCard()) { + for (Address destAdd : addresses.values()) { + if (destAdd.matches(actualAddress)) { destAdd.addLinkedAddress(actualAddress); actualAddress.addLinkedAddress(destAdd); } } } - else - { - for (Address destAdd : wildCardAddresses.values()) - { - if (actualAddress.matches(destAdd)) - { + else { + for (Address destAdd : wildCardAddresses.values()) { + if (actualAddress.matches(destAdd)) { destAdd.addLinkedAddress(actualAddress); actualAddress.addLinkedAddress(destAdd); @@ -213,31 +181,24 @@ public class WildcardAddressManager extends SimpleAddressManager return actualAddress; } - private void addAddress(final SimpleString address, final Address actualAddress) - { - if (actualAddress.containsWildCard()) - { + private void addAddress(final SimpleString address, final Address actualAddress) { + if (actualAddress.containsWildCard()) { wildCardAddresses.put(address, actualAddress); } - else - { + else { addresses.put(address, actualAddress); } } - private synchronized void removeAndUpdateAddressMap(final Address address) throws Exception - { + private synchronized void removeAndUpdateAddressMap(final Address address) throws Exception { // we only remove if there are no bindings left Bindings bindings = super.getBindingsForRoutingAddress(address.getAddress()); - if (bindings == null || bindings.getBindings().size() == 0) - { + if (bindings == null || bindings.getBindings().size() == 0) { List
    addresses = address.getLinkedAddresses(); - for (Address address1 : addresses) - { + for (Address address1 : addresses) { address1.removeLinkedAddress(address); Bindings linkedBindings = super.getBindingsForRoutingAddress(address1.getAddress()); - if (linkedBindings == null || linkedBindings.getBindings().size() == 0) - { + if (linkedBindings == null || linkedBindings.getBindings().size() == 0) { removeAddress(address1); } } @@ -245,14 +206,11 @@ public class WildcardAddressManager extends SimpleAddressManager } } - private void removeAddress(final Address add) - { - if (add.containsWildCard()) - { + private void removeAddress(final Address add) { + if (add.containsWildCard()) { wildCardAddresses.remove(add.getAddress()); } - else - { + else { addresses.remove(add.getAddress()); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/ProtocolHandler.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/ProtocolHandler.java index 5e0513cc46..e33288790a 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/ProtocolHandler.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/ProtocolHandler.java @@ -51,8 +51,8 @@ import org.apache.activemq.artemis.utils.ConfigurationHelper; import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; -public class ProtocolHandler -{ +public class ProtocolHandler { + private Map protocolMap; private NettyAcceptor nettyAcceptor; @@ -66,49 +66,41 @@ public class ProtocolHandler public ProtocolHandler(Map protocolMap, NettyAcceptor nettyAcceptor, final Map configuration, - ScheduledExecutorService scheduledThreadPool) - { + ScheduledExecutorService scheduledThreadPool) { this.protocolMap = protocolMap; this.nettyAcceptor = nettyAcceptor; this.configuration = configuration; this.scheduledThreadPool = scheduledThreadPool; } - public ChannelHandler getProtocolDecoder() - { + public ChannelHandler getProtocolDecoder() { return new ProtocolDecoder(true, false); } - public void close() - { - if (httpKeepAliveRunnable != null) - { + public void close() { + if (httpKeepAliveRunnable != null) { httpKeepAliveRunnable.close(); } } - class ProtocolDecoder extends ByteToMessageDecoder - { + class ProtocolDecoder extends ByteToMessageDecoder { + private final boolean http; private final boolean httpEnabled; - public ProtocolDecoder(boolean http, boolean httpEnabled) - { + public ProtocolDecoder(boolean http, boolean httpEnabled) { this.http = http; this.httpEnabled = httpEnabled; } @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception - { - if (msg instanceof FullHttpRequest) - { + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + if (msg instanceof FullHttpRequest) { FullHttpRequest request = (FullHttpRequest) msg; HttpHeaders headers = request.headers(); String upgrade = headers.get("upgrade"); - if (upgrade != null && upgrade.equalsIgnoreCase("websocket")) - { + if (upgrade != null && upgrade.equalsIgnoreCase("websocket")) { ctx.pipeline().addLast("websocket-handler", new WebSocketServerHandler()); ctx.pipeline().addLast(new ProtocolDecoder(false, false)); ctx.pipeline().remove(this); @@ -116,53 +108,44 @@ public class ProtocolHandler ctx.fireChannelRead(msg); } // HORNETQ-1391 - else if (upgrade != null && upgrade.equalsIgnoreCase(NettyConnector.ACTIVEMQ_REMOTING)) - { + else if (upgrade != null && upgrade.equalsIgnoreCase(NettyConnector.ACTIVEMQ_REMOTING)) { // Send the response and close the connection if necessary. ctx.writeAndFlush(new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)).addListener(ChannelFutureListener.CLOSE); } } - else - { + else { super.channelRead(ctx, msg); } } @Override - protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception - { - if (ctx.isRemoved()) - { + protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception { + if (ctx.isRemoved()) { return; } // Will use the first five bytes to detect a protocol. - if (in.readableBytes() < 8) - { + if (in.readableBytes() < 8) { return; } final int magic1 = in.getUnsignedByte(in.readerIndex()); final int magic2 = in.getUnsignedByte(in.readerIndex() + 1); - if (http && isHttp(magic1, magic2)) - { + if (http && isHttp(magic1, magic2)) { switchToHttp(ctx); return; } String protocolToUse = null; Set protocolSet = protocolMap.keySet(); - if (!protocolSet.isEmpty()) - { + if (!protocolSet.isEmpty()) { // Use getBytes(...) as this works with direct and heap buffers. // See https://issues.jboss.org/browse/HORNETQ-1406 byte[] bytes = new byte[8]; in.getBytes(0, bytes); - for (String protocol : protocolSet) - { + for (String protocol : protocolSet) { ProtocolManager protocolManager = protocolMap.get(protocol); - if (protocolManager.isProtocol(bytes)) - { + if (protocolManager.isProtocol(bytes)) { protocolToUse = protocol; break; } @@ -170,8 +153,7 @@ public class ProtocolHandler } //if we get here we assume we use the core protocol as we match nothing else - if (protocolToUse == null) - { + if (protocolToUse == null) { protocolToUse = ActiveMQClient.DEFAULT_CORE_PROTOCOL; } ProtocolManager protocolManagerToUse = protocolMap.get(protocolToUse); @@ -185,42 +167,31 @@ public class ProtocolHandler ctx.flush(); } - private boolean isHttp(int magic1, int magic2) - { - return - magic1 == 'G' && magic2 == 'E' || // GET - magic1 == 'P' && magic2 == 'O' || // POST - magic1 == 'P' && magic2 == 'U' || // PUT - magic1 == 'H' && magic2 == 'E' || // HEAD - magic1 == 'O' && magic2 == 'P' || // OPTIONS - magic1 == 'P' && magic2 == 'A' || // PATCH - magic1 == 'D' && magic2 == 'E' || // DELETE - magic1 == 'T' && magic2 == 'R'; // TRACE + private boolean isHttp(int magic1, int magic2) { + return magic1 == 'G' && magic2 == 'E' || // GET + magic1 == 'P' && magic2 == 'O' || // POST + magic1 == 'P' && magic2 == 'U' || // PUT + magic1 == 'H' && magic2 == 'E' || // HEAD + magic1 == 'O' && magic2 == 'P' || // OPTIONS + magic1 == 'P' && magic2 == 'A' || // PATCH + magic1 == 'D' && magic2 == 'E' || // DELETE + magic1 == 'T' && magic2 == 'R'; // TRACE //magic1 == 'C' && magic2 == 'O'; // CONNECT } - private void switchToHttp(ChannelHandlerContext ctx) - { + private void switchToHttp(ChannelHandlerContext ctx) { ChannelPipeline p = ctx.pipeline(); p.addLast("http-decoder", new HttpRequestDecoder()); p.addLast("http-aggregator", new HttpObjectAggregator(Integer.MAX_VALUE)); p.addLast("http-encoder", new HttpResponseEncoder()); //create it lazily if and when we need it - if (httpKeepAliveRunnable == null) - { - long httpServerScanPeriod = ConfigurationHelper.getLongProperty(TransportConstants.HTTP_SERVER_SCAN_PERIOD_PROP_NAME, - TransportConstants.DEFAULT_HTTP_SERVER_SCAN_PERIOD, - configuration); + if (httpKeepAliveRunnable == null) { + long httpServerScanPeriod = ConfigurationHelper.getLongProperty(TransportConstants.HTTP_SERVER_SCAN_PERIOD_PROP_NAME, TransportConstants.DEFAULT_HTTP_SERVER_SCAN_PERIOD, configuration); httpKeepAliveRunnable = new HttpKeepAliveRunnable(); - Future future = scheduledThreadPool.scheduleAtFixedRate(httpKeepAliveRunnable, - httpServerScanPeriod, - httpServerScanPeriod, - TimeUnit.MILLISECONDS); + Future future = scheduledThreadPool.scheduleAtFixedRate(httpKeepAliveRunnable, httpServerScanPeriod, httpServerScanPeriod, TimeUnit.MILLISECONDS); httpKeepAliveRunnable.setFuture(future); } - long httpResponseTime = ConfigurationHelper.getLongProperty(TransportConstants.HTTP_RESPONSE_TIME_PROP_NAME, - TransportConstants.DEFAULT_HTTP_RESPONSE_TIME, - configuration); + long httpResponseTime = ConfigurationHelper.getLongProperty(TransportConstants.HTTP_RESPONSE_TIME_PROP_NAME, TransportConstants.DEFAULT_HTTP_RESPONSE_TIME, configuration); HttpAcceptorHandler httpHandler = new HttpAcceptorHandler(httpKeepAliveRunnable, httpResponseTime, ctx.channel()); ctx.pipeline().addLast("http-handler", httpHandler); p.addLast(new ProtocolDecoder(false, true)); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/ServerPacketDecoder.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/ServerPacketDecoder.java index 973f10ca99..796fb60cc2 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/ServerPacketDecoder.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/ServerPacketDecoder.java @@ -71,158 +71,128 @@ import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionSen import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionSendMessage; import org.apache.activemq.artemis.core.server.impl.ServerMessageImpl; -public class ServerPacketDecoder extends ClientPacketDecoder -{ +public class ServerPacketDecoder extends ClientPacketDecoder { + private static final long serialVersionUID = 3348673114388400766L; public static final ServerPacketDecoder INSTANCE = new ServerPacketDecoder(); @Override - public Packet decode(final ActiveMQBuffer in) - { + public Packet decode(final ActiveMQBuffer in) { final byte packetType = in.readByte(); Packet packet; - switch (packetType) - { + switch (packetType) { - case SESS_SEND: - { + case SESS_SEND: { packet = new SessionSendMessage(new ServerMessageImpl()); break; } - case SESS_SEND_LARGE: - { + case SESS_SEND_LARGE: { packet = new SessionSendLargeMessage(new ServerMessageImpl()); break; } - case REPLICATION_APPEND: - { + case REPLICATION_APPEND: { packet = new ReplicationAddMessage(); break; } - case REPLICATION_APPEND_TX: - { + case REPLICATION_APPEND_TX: { packet = new ReplicationAddTXMessage(); break; } - case REPLICATION_DELETE: - { + case REPLICATION_DELETE: { packet = new ReplicationDeleteMessage(); break; } - case REPLICATION_DELETE_TX: - { + case REPLICATION_DELETE_TX: { packet = new ReplicationDeleteTXMessage(); break; } - case REPLICATION_PREPARE: - { + case REPLICATION_PREPARE: { packet = new ReplicationPrepareMessage(); break; } - case REPLICATION_COMMIT_ROLLBACK: - { + case REPLICATION_COMMIT_ROLLBACK: { packet = new ReplicationCommitMessage(); break; } - case REPLICATION_RESPONSE: - { + case REPLICATION_RESPONSE: { packet = new ReplicationResponseMessage(); break; } - case REPLICATION_PAGE_WRITE: - { + case REPLICATION_PAGE_WRITE: { packet = new ReplicationPageWriteMessage(); break; } - case REPLICATION_PAGE_EVENT: - { + case REPLICATION_PAGE_EVENT: { packet = new ReplicationPageEventMessage(); break; } - case REPLICATION_LARGE_MESSAGE_BEGIN: - { + case REPLICATION_LARGE_MESSAGE_BEGIN: { packet = new ReplicationLargeMessageBeginMessage(); break; } - case REPLICATION_LARGE_MESSAGE_END: - { + case REPLICATION_LARGE_MESSAGE_END: { packet = new ReplicationLargeMessageEndMessage(); break; } - case REPLICATION_LARGE_MESSAGE_WRITE: - { + case REPLICATION_LARGE_MESSAGE_WRITE: { packet = new ReplicationLargeMessageWriteMessage(); break; } - case PacketImpl.BACKUP_REGISTRATION: - { + case PacketImpl.BACKUP_REGISTRATION: { packet = new BackupRegistrationMessage(); break; } - case PacketImpl.BACKUP_REGISTRATION_FAILED: - { + case PacketImpl.BACKUP_REGISTRATION_FAILED: { packet = new BackupReplicationStartFailedMessage(); break; } - case PacketImpl.REPLICATION_START_FINISH_SYNC: - { + case PacketImpl.REPLICATION_START_FINISH_SYNC: { packet = new ReplicationStartSyncMessage(); break; } - case PacketImpl.REPLICATION_SYNC_FILE: - { + case PacketImpl.REPLICATION_SYNC_FILE: { packet = new ReplicationSyncFileMessage(); break; } - case PacketImpl.REPLICATION_SCHEDULED_FAILOVER: - { + case PacketImpl.REPLICATION_SCHEDULED_FAILOVER: { packet = new ReplicationLiveIsStoppingMessage(); break; } - case CLUSTER_CONNECT: - { + case CLUSTER_CONNECT: { packet = new ClusterConnectMessage(); break; } - case CLUSTER_CONNECT_REPLY: - { + case CLUSTER_CONNECT_REPLY: { packet = new ClusterConnectReplyMessage(); break; } - case NODE_ANNOUNCE: - { + case NODE_ANNOUNCE: { packet = new NodeAnnounceMessage(); break; } - case BACKUP_REQUEST: - { + case BACKUP_REQUEST: { packet = new BackupRequestMessage(); break; } - case BACKUP_REQUEST_RESPONSE: - { + case BACKUP_REQUEST_RESPONSE: { packet = new BackupResponseMessage(); break; } - case QUORUM_VOTE: - { + case QUORUM_VOTE: { packet = new QuorumVoteMessage(); break; } - case QUORUM_VOTE_REPLY: - { + case QUORUM_VOTE_REPLY: { packet = new QuorumVoteReplyMessage(); break; } - case SCALEDOWN_ANNOUNCEMENT: - { + case SCALEDOWN_ANNOUNCEMENT: { packet = new ScaleDownAnnounceMessage(); break; } - default: - { + default: { packet = super.decode(packetType); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/ServerSessionPacketHandler.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/ServerSessionPacketHandler.java index a39950edea..0cd4472513 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/ServerSessionPacketHandler.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/ServerSessionPacketHandler.java @@ -113,8 +113,8 @@ import org.apache.activemq.artemis.core.server.ServerMessage; import org.apache.activemq.artemis.core.server.ServerSession; import org.apache.activemq.artemis.spi.core.remoting.Connection; -public class ServerSessionPacketHandler implements ChannelHandler -{ +public class ServerSessionPacketHandler implements ChannelHandler { + private final ServerSession session; private final StorageManager storageManager; @@ -127,8 +127,7 @@ public class ServerSessionPacketHandler implements ChannelHandler public ServerSessionPacketHandler(final ServerSession session, final StorageManager storageManager, - final Channel channel) - { + final Channel channel) { this.session = session; this.storageManager = storageManager; @@ -140,63 +139,51 @@ public class ServerSessionPacketHandler implements ChannelHandler //TODO think of a better way of doing this Connection conn = remotingConnection.getTransportConnection(); - if (conn instanceof NettyConnection) - { - direct = ((NettyConnection)conn).isDirectDeliver(); + if (conn instanceof NettyConnection) { + direct = ((NettyConnection) conn).isDirectDeliver(); } - else - { + else { direct = false; } } - public ServerSession getSession() - { + public ServerSession getSession() { return session; } - public long getID() - { + public long getID() { return channel.getID(); } - public void connectionFailed(final ActiveMQException exception, boolean failedOver) - { + public void connectionFailed(final ActiveMQException exception, boolean failedOver) { ActiveMQServerLogger.LOGGER.clientConnectionFailed(session.getName()); - try - { + try { session.close(true); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorClosingSession(e); } ActiveMQServerLogger.LOGGER.clearingUpSession(session.getName()); } - public void close() - { + public void close() { channel.flushConfirmations(); - try - { + try { session.close(false); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorClosingSession(e); } } - public Channel getChannel() - { + public Channel getChannel() { return channel; } - public void handlePacket(final Packet packet) - { + public void handlePacket(final Packet packet) { byte type = packet.getType(); storageManager.setContext(session.getSessionContext()); @@ -206,405 +193,327 @@ public class ServerSessionPacketHandler implements ChannelHandler boolean closeChannel = false; boolean requiresResponse = false; - try - { - try - { - switch (type) - { - case SESS_CREATECONSUMER: - { - SessionCreateConsumerMessage request = (SessionCreateConsumerMessage)packet; + try { + try { + switch (type) { + case SESS_CREATECONSUMER: { + SessionCreateConsumerMessage request = (SessionCreateConsumerMessage) packet; requiresResponse = request.isRequiresResponse(); - session.createConsumer(request.getID(), - request.getQueueName(), - request.getFilterString(), - request.isBrowseOnly()); - if (requiresResponse) - { + session.createConsumer(request.getID(), request.getQueueName(), request.getFilterString(), request.isBrowseOnly()); + if (requiresResponse) { // We send back queue information on the queue as a response- this allows the queue to // be automatically recreated on failover QueueQueryResult queueQueryResult = session.executeQueueQuery(request.getQueueName()); - if (channel.supports(PacketImpl.SESS_QUEUEQUERY_RESP_V2)) - { + if (channel.supports(PacketImpl.SESS_QUEUEQUERY_RESP_V2)) { response = new SessionQueueQueryResponseMessage_V2(queueQueryResult); } - else - { + else { response = new SessionQueueQueryResponseMessage(queueQueryResult); } } break; } - case CREATE_QUEUE: - { - CreateQueueMessage request = (CreateQueueMessage)packet; + case CREATE_QUEUE: { + CreateQueueMessage request = (CreateQueueMessage) packet; requiresResponse = request.isRequiresResponse(); - session.createQueue(request.getAddress(), - request.getQueueName(), - request.getFilterString(), - request.isTemporary(), - request.isDurable()); - if (requiresResponse) - { + session.createQueue(request.getAddress(), request.getQueueName(), request.getFilterString(), request.isTemporary(), request.isDurable()); + if (requiresResponse) { response = new NullResponseMessage(); } break; } - case CREATE_SHARED_QUEUE: - { - CreateSharedQueueMessage request = (CreateSharedQueueMessage)packet; + case CREATE_SHARED_QUEUE: { + CreateSharedQueueMessage request = (CreateSharedQueueMessage) packet; requiresResponse = request.isRequiresResponse(); - session.createSharedQueue(request.getAddress(), - request.getQueueName(), - request.isDurable(), - request.getFilterString()); - if (requiresResponse) - { + session.createSharedQueue(request.getAddress(), request.getQueueName(), request.isDurable(), request.getFilterString()); + if (requiresResponse) { response = new NullResponseMessage(); } break; } - case DELETE_QUEUE: - { + case DELETE_QUEUE: { requiresResponse = true; - SessionDeleteQueueMessage request = (SessionDeleteQueueMessage)packet; + SessionDeleteQueueMessage request = (SessionDeleteQueueMessage) packet; session.deleteQueue(request.getQueueName()); response = new NullResponseMessage(); break; } - case SESS_QUEUEQUERY: - { + case SESS_QUEUEQUERY: { requiresResponse = true; - SessionQueueQueryMessage request = (SessionQueueQueryMessage)packet; + SessionQueueQueryMessage request = (SessionQueueQueryMessage) packet; QueueQueryResult result = session.executeQueueQuery(request.getQueueName()); - if (channel.supports(PacketImpl.SESS_QUEUEQUERY_RESP_V2)) - { + if (channel.supports(PacketImpl.SESS_QUEUEQUERY_RESP_V2)) { response = new SessionQueueQueryResponseMessage_V2(result); } - else - { + else { response = new SessionQueueQueryResponseMessage(result); } break; } - case SESS_BINDINGQUERY: - { + case SESS_BINDINGQUERY: { requiresResponse = true; - SessionBindingQueryMessage request = (SessionBindingQueryMessage)packet; + SessionBindingQueryMessage request = (SessionBindingQueryMessage) packet; BindingQueryResult result = session.executeBindingQuery(request.getAddress()); - if (channel.supports(PacketImpl.SESS_BINDINGQUERY_RESP_V2)) - { + if (channel.supports(PacketImpl.SESS_BINDINGQUERY_RESP_V2)) { response = new SessionBindingQueryResponseMessage_V2(result.isExists(), result.getQueueNames(), result.isAutoCreateJmsQueues()); } - else - { + else { response = new SessionBindingQueryResponseMessage(result.isExists(), result.getQueueNames()); } break; } - case SESS_ACKNOWLEDGE: - { - SessionAcknowledgeMessage message = (SessionAcknowledgeMessage)packet; + case SESS_ACKNOWLEDGE: { + SessionAcknowledgeMessage message = (SessionAcknowledgeMessage) packet; requiresResponse = message.isRequiresResponse(); session.acknowledge(message.getConsumerID(), message.getMessageID()); - if (requiresResponse) - { + if (requiresResponse) { response = new NullResponseMessage(); } break; } - case SESS_EXPIRED: - { - SessionExpireMessage message = (SessionExpireMessage)packet; + case SESS_EXPIRED: { + SessionExpireMessage message = (SessionExpireMessage) packet; session.expire(message.getConsumerID(), message.getMessageID()); break; } - case SESS_COMMIT: - { + case SESS_COMMIT: { requiresResponse = true; session.commit(); response = new NullResponseMessage(); break; } - case SESS_ROLLBACK: - { + case SESS_ROLLBACK: { requiresResponse = true; session.rollback(((RollbackMessage) packet).isConsiderLastMessageAsDelivered()); response = new NullResponseMessage(); break; } - case SESS_XA_COMMIT: - { + case SESS_XA_COMMIT: { requiresResponse = true; - SessionXACommitMessage message = (SessionXACommitMessage)packet; + SessionXACommitMessage message = (SessionXACommitMessage) packet; session.xaCommit(message.getXid(), message.isOnePhase()); response = new SessionXAResponseMessage(false, XAResource.XA_OK, null); break; } - case SESS_XA_END: - { + case SESS_XA_END: { requiresResponse = true; - SessionXAEndMessage message = (SessionXAEndMessage)packet; + SessionXAEndMessage message = (SessionXAEndMessage) packet; session.xaEnd(message.getXid()); response = new SessionXAResponseMessage(false, XAResource.XA_OK, null); break; } - case SESS_XA_FORGET: - { + case SESS_XA_FORGET: { requiresResponse = true; - SessionXAForgetMessage message = (SessionXAForgetMessage)packet; + SessionXAForgetMessage message = (SessionXAForgetMessage) packet; session.xaForget(message.getXid()); response = new SessionXAResponseMessage(false, XAResource.XA_OK, null); break; } - case SESS_XA_JOIN: - { + case SESS_XA_JOIN: { requiresResponse = true; - SessionXAJoinMessage message = (SessionXAJoinMessage)packet; + SessionXAJoinMessage message = (SessionXAJoinMessage) packet; session.xaJoin(message.getXid()); response = new SessionXAResponseMessage(false, XAResource.XA_OK, null); break; } - case SESS_XA_RESUME: - { + case SESS_XA_RESUME: { requiresResponse = true; - SessionXAResumeMessage message = (SessionXAResumeMessage)packet; + SessionXAResumeMessage message = (SessionXAResumeMessage) packet; session.xaResume(message.getXid()); response = new SessionXAResponseMessage(false, XAResource.XA_OK, null); break; } - case SESS_XA_ROLLBACK: - { + case SESS_XA_ROLLBACK: { requiresResponse = true; - SessionXARollbackMessage message = (SessionXARollbackMessage)packet; + SessionXARollbackMessage message = (SessionXARollbackMessage) packet; session.xaRollback(message.getXid()); response = new SessionXAResponseMessage(false, XAResource.XA_OK, null); break; } - case SESS_XA_START: - { + case SESS_XA_START: { requiresResponse = true; - SessionXAStartMessage message = (SessionXAStartMessage)packet; + SessionXAStartMessage message = (SessionXAStartMessage) packet; session.xaStart(message.getXid()); response = new SessionXAResponseMessage(false, XAResource.XA_OK, null); break; } - case SESS_XA_FAILED: - { + case SESS_XA_FAILED: { requiresResponse = true; - SessionXAAfterFailedMessage message = (SessionXAAfterFailedMessage)packet; + SessionXAAfterFailedMessage message = (SessionXAAfterFailedMessage) packet; session.xaFailed(message.getXid()); // no response on this case break; } - case SESS_XA_SUSPEND: - { + case SESS_XA_SUSPEND: { requiresResponse = true; session.xaSuspend(); response = new SessionXAResponseMessage(false, XAResource.XA_OK, null); break; } - case SESS_XA_PREPARE: - { + case SESS_XA_PREPARE: { requiresResponse = true; - SessionXAPrepareMessage message = (SessionXAPrepareMessage)packet; + SessionXAPrepareMessage message = (SessionXAPrepareMessage) packet; session.xaPrepare(message.getXid()); response = new SessionXAResponseMessage(false, XAResource.XA_OK, null); break; } - case SESS_XA_INDOUBT_XIDS: - { + case SESS_XA_INDOUBT_XIDS: { requiresResponse = true; List xids = session.xaGetInDoubtXids(); response = new SessionXAGetInDoubtXidsResponseMessage(xids); break; } - case SESS_XA_GET_TIMEOUT: - { + case SESS_XA_GET_TIMEOUT: { requiresResponse = true; int timeout = session.xaGetTimeout(); response = new SessionXAGetTimeoutResponseMessage(timeout); break; } - case SESS_XA_SET_TIMEOUT: - { + case SESS_XA_SET_TIMEOUT: { requiresResponse = true; - SessionXASetTimeoutMessage message = (SessionXASetTimeoutMessage)packet; + SessionXASetTimeoutMessage message = (SessionXASetTimeoutMessage) packet; session.xaSetTimeout(message.getTimeoutSeconds()); response = new SessionXASetTimeoutResponseMessage(true); break; } - case SESS_START: - { + case SESS_START: { session.start(); break; } - case SESS_STOP: - { + case SESS_STOP: { requiresResponse = true; session.stop(); response = new NullResponseMessage(); break; } - case SESS_CLOSE: - { + case SESS_CLOSE: { requiresResponse = true; session.close(false); - // removeConnectionListeners(); + // removeConnectionListeners(); response = new NullResponseMessage(); flush = true; closeChannel = true; break; } - case SESS_INDIVIDUAL_ACKNOWLEDGE: - { - SessionIndividualAcknowledgeMessage message = (SessionIndividualAcknowledgeMessage)packet; + case SESS_INDIVIDUAL_ACKNOWLEDGE: { + SessionIndividualAcknowledgeMessage message = (SessionIndividualAcknowledgeMessage) packet; requiresResponse = message.isRequiresResponse(); session.individualAcknowledge(message.getConsumerID(), message.getMessageID()); - if (requiresResponse) - { + if (requiresResponse) { response = new NullResponseMessage(); } break; } - case SESS_CONSUMER_CLOSE: - { + case SESS_CONSUMER_CLOSE: { requiresResponse = true; - SessionConsumerCloseMessage message = (SessionConsumerCloseMessage)packet; + SessionConsumerCloseMessage message = (SessionConsumerCloseMessage) packet; session.closeConsumer(message.getConsumerID()); response = new NullResponseMessage(); break; } - case SESS_FLOWTOKEN: - { - SessionConsumerFlowCreditMessage message = (SessionConsumerFlowCreditMessage)packet; + case SESS_FLOWTOKEN: { + SessionConsumerFlowCreditMessage message = (SessionConsumerFlowCreditMessage) packet; session.receiveConsumerCredits(message.getConsumerID(), message.getCredits()); break; } - case SESS_SEND: - { - SessionSendMessage message = (SessionSendMessage)packet; + case SESS_SEND: { + SessionSendMessage message = (SessionSendMessage) packet; requiresResponse = message.isRequiresResponse(); - session.send((ServerMessage)message.getMessage(), direct); - if (requiresResponse) - { + session.send((ServerMessage) message.getMessage(), direct); + if (requiresResponse) { response = new NullResponseMessage(); } break; } - case SESS_SEND_LARGE: - { - SessionSendLargeMessage message = (SessionSendLargeMessage)packet; + case SESS_SEND_LARGE: { + SessionSendLargeMessage message = (SessionSendLargeMessage) packet; session.sendLarge(message.getLargeMessage()); break; } - case SESS_SEND_CONTINUATION: - { - SessionSendContinuationMessage message = (SessionSendContinuationMessage)packet; + case SESS_SEND_CONTINUATION: { + SessionSendContinuationMessage message = (SessionSendContinuationMessage) packet; requiresResponse = message.isRequiresResponse(); session.sendContinuations(message.getPacketSize(), message.getMessageBodySize(), message.getBody(), message.isContinues()); - if (requiresResponse) - { + if (requiresResponse) { response = new NullResponseMessage(); } break; } - case SESS_FORCE_CONSUMER_DELIVERY: - { - SessionForceConsumerDelivery message = (SessionForceConsumerDelivery)packet; + case SESS_FORCE_CONSUMER_DELIVERY: { + SessionForceConsumerDelivery message = (SessionForceConsumerDelivery) packet; session.forceConsumerDelivery(message.getConsumerID(), message.getSequence()); break; } - case PacketImpl.SESS_PRODUCER_REQUEST_CREDITS: - { - SessionRequestProducerCreditsMessage message = (SessionRequestProducerCreditsMessage)packet; + case PacketImpl.SESS_PRODUCER_REQUEST_CREDITS: { + SessionRequestProducerCreditsMessage message = (SessionRequestProducerCreditsMessage) packet; session.requestProducerCredits(message.getAddress(), message.getCredits()); break; } - case PacketImpl.SESS_ADD_METADATA: - { + case PacketImpl.SESS_ADD_METADATA: { response = new NullResponseMessage(); - SessionAddMetaDataMessage message = (SessionAddMetaDataMessage)packet; + SessionAddMetaDataMessage message = (SessionAddMetaDataMessage) packet; session.addMetaData(message.getKey(), message.getData()); break; } - case PacketImpl.SESS_ADD_METADATA2: - { - SessionAddMetaDataMessageV2 message = (SessionAddMetaDataMessageV2)packet; - if (message.isRequiresConfirmations()) - { + case PacketImpl.SESS_ADD_METADATA2: { + SessionAddMetaDataMessageV2 message = (SessionAddMetaDataMessageV2) packet; + if (message.isRequiresConfirmations()) { response = new NullResponseMessage(); } session.addMetaData(message.getKey(), message.getData()); break; } - case PacketImpl.SESS_UNIQUE_ADD_METADATA: - { - SessionUniqueAddMetaDataMessage message = (SessionUniqueAddMetaDataMessage)packet; - if (session.addUniqueMetaData(message.getKey(), message.getData())) - { + case PacketImpl.SESS_UNIQUE_ADD_METADATA: { + SessionUniqueAddMetaDataMessage message = (SessionUniqueAddMetaDataMessage) packet; + if (session.addUniqueMetaData(message.getKey(), message.getData())) { response = new NullResponseMessage(); } - else - { + else { response = new ActiveMQExceptionMessage(ActiveMQMessageBundle.BUNDLE.duplicateMetadata(message.getKey(), message.getData())); } break; } } } - catch (ActiveMQXAException e) - { - if (requiresResponse) - { + catch (ActiveMQXAException e) { + if (requiresResponse) { ActiveMQServerLogger.LOGGER.debug("Sending exception to client", e); response = new SessionXAResponseMessage(true, e.errorCode, e.getMessage()); } - else - { + else { ActiveMQServerLogger.LOGGER.caughtXaException(e); } } - catch (ActiveMQException e) - { - if (requiresResponse) - { + catch (ActiveMQException e) { + if (requiresResponse) { ActiveMQServerLogger.LOGGER.debug("Sending exception to client", e); response = new ActiveMQExceptionMessage(e); } - else - { - if (e.getType() == ActiveMQExceptionType.QUEUE_EXISTS) - { + else { + if (e.getType() == ActiveMQExceptionType.QUEUE_EXISTS) { ActiveMQServerLogger.LOGGER.debug("Caught exception", e); } - else - { + else { ActiveMQServerLogger.LOGGER.caughtException(e); } } } - catch (Throwable t) - { - if (requiresResponse) - { + catch (Throwable t) { + if (requiresResponse) { ActiveMQServerLogger.LOGGER.warn("Sending unexpected exception to the client", t); ActiveMQException activeMQInternalErrorException = new ActiveMQInternalErrorException(); activeMQInternalErrorException.initCause(t); response = new ActiveMQExceptionMessage(activeMQInternalErrorException); } - else - { + else { ActiveMQServerLogger.LOGGER.caughtException(t); } } sendResponse(packet, response, flush, closeChannel); } - finally - { + finally { storageManager.clearContext(); } } @@ -612,21 +521,17 @@ public class ServerSessionPacketHandler implements ChannelHandler private void sendResponse(final Packet confirmPacket, final Packet response, final boolean flush, - final boolean closeChannel) - { - storageManager.afterCompleteOperations(new IOCallback() - { - public void onError(final int errorCode, final String errorMessage) - { + final boolean closeChannel) { + storageManager.afterCompleteOperations(new IOCallback() { + public void onError(final int errorCode, final String errorMessage) { ActiveMQServerLogger.LOGGER.errorProcessingIOCallback(errorCode, errorMessage); - ActiveMQExceptionMessage exceptionMessage = new ActiveMQExceptionMessage( ActiveMQExceptionType.createException(errorCode, errorMessage)); + ActiveMQExceptionMessage exceptionMessage = new ActiveMQExceptionMessage(ActiveMQExceptionType.createException(errorCode, errorMessage)); doConfirmAndResponse(confirmPacket, exceptionMessage, flush, closeChannel); } - public void done() - { + public void done() { doConfirmAndResponse(confirmPacket, response, flush, closeChannel); } }); @@ -635,45 +540,36 @@ public class ServerSessionPacketHandler implements ChannelHandler private void doConfirmAndResponse(final Packet confirmPacket, final Packet response, final boolean flush, - final boolean closeChannel) - { - if (confirmPacket != null) - { + final boolean closeChannel) { + if (confirmPacket != null) { channel.confirm(confirmPacket); - if (flush) - { + if (flush) { channel.flushConfirmations(); } } - if (response != null) - { + if (response != null) { channel.send(response); } - if (closeChannel) - { + if (closeChannel) { channel.close(); } } - public void closeListeners() - { + public void closeListeners() { List listeners = remotingConnection.removeCloseListeners(); - for (CloseListener closeListener: listeners) - { + for (CloseListener closeListener : listeners) { closeListener.connectionClosed(); - if (closeListener instanceof FailureListener) - { - remotingConnection.removeFailureListener((FailureListener)closeListener); + if (closeListener instanceof FailureListener) { + remotingConnection.removeFailureListener((FailureListener) closeListener); } } } - public int transferConnection(final CoreRemotingConnection newConnection, final int lastReceivedCommandID) - { + public int transferConnection(final CoreRemotingConnection newConnection, final int lastReceivedCommandID) { // We need to disable delivery on all the consumers while the transfer is occurring- otherwise packets might get // delivered // after the channel has transferred but *before* packets have been replayed - this will give the client the wrong diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQPacketHandler.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQPacketHandler.java index 91a8147aeb..665ea66064 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQPacketHandler.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQPacketHandler.java @@ -43,8 +43,8 @@ import org.apache.activemq.artemis.core.version.Version; /** * A packet handler for all packets that need to be handled at the server level */ -public class ActiveMQPacketHandler implements ChannelHandler -{ +public class ActiveMQPacketHandler implements ChannelHandler { + private final ActiveMQServer server; private final Channel channel1; @@ -56,8 +56,7 @@ public class ActiveMQPacketHandler implements ChannelHandler public ActiveMQPacketHandler(final CoreProtocolManager protocolManager, final ActiveMQServer server, final Channel channel1, - final CoreRemotingConnection connection) - { + final CoreRemotingConnection connection) { this.protocolManager = protocolManager; this.server = server; @@ -67,38 +66,32 @@ public class ActiveMQPacketHandler implements ChannelHandler this.connection = connection; } - public void handlePacket(final Packet packet) - { + public void handlePacket(final Packet packet) { byte type = packet.getType(); - switch (type) - { - case PacketImpl.CREATESESSION: - { + switch (type) { + case PacketImpl.CREATESESSION: { CreateSessionMessage request = (CreateSessionMessage) packet; handleCreateSession(request); break; } - case PacketImpl.CHECK_FOR_FAILOVER: - { + case PacketImpl.CHECK_FOR_FAILOVER: { CheckFailoverMessage request = (CheckFailoverMessage) packet; handleCheckForFailover(request); break; } - case PacketImpl.REATTACH_SESSION: - { + case PacketImpl.REATTACH_SESSION: { ReattachSessionMessage request = (ReattachSessionMessage) packet; handleReattachSession(request); break; } - case PacketImpl.CREATE_QUEUE: - { + case PacketImpl.CREATE_QUEUE: { // Create queue can also be fielded here in the case of a replicated store and forward queue creation CreateQueueMessage request = (CreateQueueMessage) packet; @@ -107,35 +100,28 @@ public class ActiveMQPacketHandler implements ChannelHandler break; } - default: - { + default: { ActiveMQServerLogger.LOGGER.invalidPacket(packet); } } } - private void handleCheckForFailover(CheckFailoverMessage failoverMessage) - { + private void handleCheckForFailover(CheckFailoverMessage failoverMessage) { String nodeID = failoverMessage.getNodeID(); - boolean okToFailover = nodeID == null || - !(server.getHAPolicy().canScaleDown() && !server.hasScaledDown(new SimpleString(nodeID))); + boolean okToFailover = nodeID == null || !(server.getHAPolicy().canScaleDown() && !server.hasScaledDown(new SimpleString(nodeID))); channel1.send(new CheckFailoverReplyMessage(okToFailover)); } - private void handleCreateSession(final CreateSessionMessage request) - { + private void handleCreateSession(final CreateSessionMessage request) { boolean incompatibleVersion = false; Packet response; - try - { + try { Version version = server.getVersion(); - if (!version.isCompatible(request.getVersion())) - { + if (!version.isCompatible(request.getVersion())) { throw ActiveMQMessageBundle.BUNDLE.incompatibleClientServer(); } - if (!server.isStarted()) - { + if (!server.isStarted()) { throw ActiveMQMessageBundle.BUNDLE.serverNotStarted(); } @@ -146,13 +132,10 @@ public class ActiveMQPacketHandler implements ChannelHandler "Server will not accept create session requests"); }*/ - - if (connection.getClientVersion() == 0) - { + if (connection.getClientVersion() == 0) { connection.setClientVersion(request.getVersion()); } - else if (connection.getClientVersion() != request.getVersion()) - { + else if (connection.getClientVersion() != request.getVersion()) { ActiveMQServerLogger.LOGGER.incompatibleVersionAfterConnect(request.getVersion(), connection.getClientVersion()); } @@ -160,28 +143,13 @@ public class ActiveMQPacketHandler implements ChannelHandler ActiveMQPrincipal activeMQPrincipal = null; - if (request.getUsername() == null) - { + if (request.getUsername() == null) { activeMQPrincipal = connection.getDefaultActiveMQPrincipal(); } - ServerSession session = server.createSession(request.getName(), - activeMQPrincipal == null ? request.getUsername() : activeMQPrincipal.getUserName(), - activeMQPrincipal == null ? request.getPassword() : activeMQPrincipal.getPassword(), - request.getMinLargeMessageSize(), - connection, - request.isAutoCommitSends(), - request.isAutoCommitAcks(), - request.isPreAcknowledge(), - request.isXA(), - request.getDefaultAddress(), - new CoreSessionCallback(request.getName(), - protocolManager, - channel), null, true); + ServerSession session = server.createSession(request.getName(), activeMQPrincipal == null ? request.getUsername() : activeMQPrincipal.getUserName(), activeMQPrincipal == null ? request.getPassword() : activeMQPrincipal.getPassword(), request.getMinLargeMessageSize(), connection, request.isAutoCommitSends(), request.isAutoCommitAcks(), request.isPreAcknowledge(), request.isXA(), request.getDefaultAddress(), new CoreSessionCallback(request.getName(), protocolManager, channel), null, true); - ServerSessionPacketHandler handler = new ServerSessionPacketHandler(session, - server.getStorageManager(), - channel); + ServerSessionPacketHandler handler = new ServerSessionPacketHandler(session, server.getStorageManager(), channel); channel.setHandler(handler); // TODO - where is this removed? @@ -189,22 +157,18 @@ public class ActiveMQPacketHandler implements ChannelHandler response = new CreateSessionResponseMessage(server.getVersion().getIncrementingVersion()); } - catch (ActiveMQException e) - { - if (e.getType() == ActiveMQExceptionType.INCOMPATIBLE_CLIENT_SERVER_VERSIONS) - { + catch (ActiveMQException e) { + if (e.getType() == ActiveMQExceptionType.INCOMPATIBLE_CLIENT_SERVER_VERSIONS) { incompatibleVersion = true; ActiveMQServerLogger.LOGGER.debug("Sending ActiveMQException after Incompatible client", e); } - else - { + else { ActiveMQServerLogger.LOGGER.failedToCreateSession(e); } response = new ActiveMQExceptionMessage(e); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.failedToCreateSession(e); response = new ActiveMQExceptionMessage(new ActiveMQInternalErrorException()); @@ -213,42 +177,33 @@ public class ActiveMQPacketHandler implements ChannelHandler // send the exception to the client and destroy // the connection if the client and server versions // are not compatible - if (incompatibleVersion) - { + if (incompatibleVersion) { channel1.sendAndFlush(response); } - else - { + else { channel1.send(response); } } - private void handleReattachSession(final ReattachSessionMessage request) - { + private void handleReattachSession(final ReattachSessionMessage request) { Packet response = null; - try - { + try { - if (!server.isStarted()) - { + if (!server.isStarted()) { response = new ReattachSessionResponseMessage(-1, false); } ActiveMQServerLogger.LOGGER.debug("Reattaching request from " + connection.getRemoteAddress()); - ServerSessionPacketHandler sessionHandler = protocolManager.getSessionHandler(request.getName()); // HORNETQ-720 XXX ataylor? - if (/*!server.checkActivate() || */ sessionHandler == null) - { + if (/*!server.checkActivate() || */ sessionHandler == null) { response = new ReattachSessionResponseMessage(-1, false); } - else - { - if (sessionHandler.getChannel().getConfirmationWindowSize() == -1) - { + else { + if (sessionHandler.getChannel().getConfirmationWindowSize() == -1) { // Even though session exists, we can't reattach since confi window size == -1, // i.e. we don't have a resend cache for commands, so we just close the old session // and let the client recreate @@ -260,18 +215,15 @@ public class ActiveMQPacketHandler implements ChannelHandler response = new ReattachSessionResponseMessage(-1, false); } - else - { + else { // Reconnect the channel to the new connection - int serverLastConfirmedCommandID = sessionHandler.transferConnection(connection, - request.getLastConfirmedCommandID()); + int serverLastConfirmedCommandID = sessionHandler.transferConnection(connection, request.getLastConfirmedCommandID()); response = new ReattachSessionResponseMessage(serverLastConfirmedCommandID, true); } } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.failedToReattachSession(e); response = new ActiveMQExceptionMessage(new ActiveMQInternalErrorException()); @@ -280,18 +232,11 @@ public class ActiveMQPacketHandler implements ChannelHandler channel1.send(response); } - private void handleCreateQueue(final CreateQueueMessage request) - { - try - { - server.createQueue(request.getAddress(), - request.getQueueName(), - request.getFilterString(), - request.isDurable(), - request.isTemporary()); + private void handleCreateQueue(final CreateQueueMessage request) { + try { + server.createQueue(request.getAddress(), request.getQueueName(), request.getFilterString(), request.isDurable(), request.isTemporary()); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.failedToHandleCreateQueue(e); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/CoreProtocolManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/CoreProtocolManager.java index a3abfe0b98..da6e5b13bb 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/CoreProtocolManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/CoreProtocolManager.java @@ -59,8 +59,8 @@ import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; import org.apache.activemq.artemis.spi.core.remoting.Acceptor; import org.apache.activemq.artemis.spi.core.remoting.Connection; -public class CoreProtocolManager implements ProtocolManager -{ +public class CoreProtocolManager implements ProtocolManager { + private static final boolean isTrace = ActiveMQServerLogger.LOGGER.isTraceEnabled(); private final ActiveMQServer server; @@ -71,8 +71,10 @@ public class CoreProtocolManager implements ProtocolManager private final CoreProtocolManagerFactory protocolManagerFactory; - public CoreProtocolManager(final CoreProtocolManagerFactory factory, final ActiveMQServer server, final List incomingInterceptors, List outgoingInterceptors) - { + public CoreProtocolManager(final CoreProtocolManagerFactory factory, + final ActiveMQServer server, + final List incomingInterceptors, + List outgoingInterceptors) { this.protocolManagerFactory = factory; this.server = server; @@ -82,16 +84,13 @@ public class CoreProtocolManager implements ProtocolManager this.outgoingInterceptors = outgoingInterceptors; } - @Override - public ProtocolManagerFactory getFactory() - { + public ProtocolManagerFactory getFactory() { return protocolManagerFactory; } @Override - public void updateInterceptors(List incoming, List outgoing) - { + public void updateInterceptors(List incoming, List outgoing) { this.incomingInterceptors.clear(); this.incomingInterceptors.addAll(getFactory().filterInterceptors(incoming)); @@ -105,23 +104,16 @@ public class CoreProtocolManager implements ProtocolManager * @return */ @Override - public MessageConverter getConverter() - { + public MessageConverter getConverter() { return null; } - public ConnectionEntry createConnectionEntry(final Acceptor acceptorUsed, final Connection connection) - { + public ConnectionEntry createConnectionEntry(final Acceptor acceptorUsed, final Connection connection) { final Configuration config = server.getConfiguration(); Executor connectionExecutor = server.getExecutorFactory().getExecutor(); - final CoreRemotingConnection rc = new RemotingConnectionImpl(ServerPacketDecoder.INSTANCE, - connection, - incomingInterceptors, - outgoingInterceptors, - config.isAsyncConnectionExecutionEnabled() ? connectionExecutor : null, - server.getNodeID()); + final CoreRemotingConnection rc = new RemotingConnectionImpl(ServerPacketDecoder.INSTANCE, connection, incomingInterceptors, outgoingInterceptors, config.isAsyncConnectionExecutionEnabled() ? connectionExecutor : null, server.getNodeID()); Channel channel1 = rc.getChannel(CHANNEL_ID.SESSION.id, -1); @@ -131,8 +123,7 @@ public class CoreProtocolManager implements ProtocolManager long ttl = ActiveMQClient.DEFAULT_CONNECTION_TTL; - if (config.getConnectionTTLOverride() != -1) - { + if (config.getConnectionTTLOverride() != -1) { ttl = config.getConnectionTTLOverride(); } @@ -149,41 +140,34 @@ public class CoreProtocolManager implements ProtocolManager private final Map sessionHandlers = new ConcurrentHashMap(); - ServerSessionPacketHandler getSessionHandler(final String sessionName) - { + ServerSessionPacketHandler getSessionHandler(final String sessionName) { return sessionHandlers.get(sessionName); } - void addSessionHandler(final String name, final ServerSessionPacketHandler handler) - { + void addSessionHandler(final String name, final ServerSessionPacketHandler handler) { sessionHandlers.put(name, handler); } - public void removeHandler(final String name) - { + public void removeHandler(final String name) { sessionHandlers.remove(name); } - public void handleBuffer(RemotingConnection connection, ActiveMQBuffer buffer) - { + public void handleBuffer(RemotingConnection connection, ActiveMQBuffer buffer) { } @Override - public void addChannelHandlers(ChannelPipeline pipeline) - { + public void addChannelHandlers(ChannelPipeline pipeline) { pipeline.addLast("activemq-decoder", new ActiveMQFrameDecoder2()); } @Override - public boolean isProtocol(byte[] array) - { + public boolean isProtocol(byte[] array) { String frameStart = new String(array, StandardCharsets.US_ASCII); return frameStart.startsWith("ACTIVEMQ"); } @Override - public void handshake(NettyServerConnection connection, ActiveMQBuffer buffer) - { + public void handshake(NettyServerConnection connection, ActiveMQBuffer buffer) { //if we are not an old client then handshake if (buffer.getByte(0) == 'A' && buffer.getByte(1) == 'R' && @@ -191,30 +175,30 @@ public class CoreProtocolManager implements ProtocolManager buffer.getByte(3) == 'E' && buffer.getByte(4) == 'M' && buffer.getByte(5) == 'I' && - buffer.getByte(6) == 'S') - { + buffer.getByte(6) == 'S') { //todo add some handshaking buffer.readBytes(7); } } @Override - public String toString() - { + public String toString() { return "CoreProtocolManager(server=" + server + ")"; } - private class LocalChannelHandler implements ChannelHandler - { + private class LocalChannelHandler implements ChannelHandler { + private final Configuration config; private final ConnectionEntry entry; private final Channel channel0; private final Acceptor acceptorUsed; private final CoreRemotingConnection rc; - public LocalChannelHandler(final Configuration config, final ConnectionEntry entry, - final Channel channel0, final Acceptor acceptorUsed, final CoreRemotingConnection rc) - { + public LocalChannelHandler(final Configuration config, + final ConnectionEntry entry, + final Channel channel0, + final Acceptor acceptorUsed, + final CoreRemotingConnection rc) { this.config = config; this.entry = entry; this.channel0 = channel0; @@ -222,14 +206,11 @@ public class CoreProtocolManager implements ProtocolManager this.rc = rc; } - public void handlePacket(final Packet packet) - { - if (packet.getType() == PacketImpl.PING) - { - Ping ping = (Ping)packet; + public void handlePacket(final Packet packet) { + if (packet.getType() == PacketImpl.PING) { + Ping ping = (Ping) packet; - if (config.getConnectionTTLOverride() == -1) - { + if (config.getConnectionTTLOverride() == -1) { // Allow clients to specify connection ttl entry.ttl = ping.getConnectionTTL(); } @@ -237,55 +218,38 @@ public class CoreProtocolManager implements ProtocolManager // Just send a ping back channel0.send(packet); } - else if (packet.getType() == PacketImpl.SUBSCRIBE_TOPOLOGY || packet.getType() == PacketImpl.SUBSCRIBE_TOPOLOGY_V2) - { - SubscribeClusterTopologyUpdatesMessage msg = (SubscribeClusterTopologyUpdatesMessage)packet; + else if (packet.getType() == PacketImpl.SUBSCRIBE_TOPOLOGY || packet.getType() == PacketImpl.SUBSCRIBE_TOPOLOGY_V2) { + SubscribeClusterTopologyUpdatesMessage msg = (SubscribeClusterTopologyUpdatesMessage) packet; - if (packet.getType() == PacketImpl.SUBSCRIBE_TOPOLOGY_V2) - { - channel0.getConnection().setClientVersion(((SubscribeClusterTopologyUpdatesMessageV2)msg).getClientVersion()); + if (packet.getType() == PacketImpl.SUBSCRIBE_TOPOLOGY_V2) { + channel0.getConnection().setClientVersion(((SubscribeClusterTopologyUpdatesMessageV2) msg).getClientVersion()); } - final ClusterTopologyListener listener = new ClusterTopologyListener() - { + final ClusterTopologyListener listener = new ClusterTopologyListener() { @Override - public void nodeUP(final TopologyMember topologyMember, final boolean last) - { - try - { - final Pair connectorPair = BackwardsCompatibilityUtils - .getTCPair(channel0.getConnection().getClientVersion(), topologyMember); + public void nodeUP(final TopologyMember topologyMember, final boolean last) { + try { + final Pair connectorPair = BackwardsCompatibilityUtils.getTCPair(channel0.getConnection().getClientVersion(), topologyMember); final String nodeID = topologyMember.getNodeId(); // Using an executor as most of the notifications on the Topology // may come from a channel itself // What could cause deadlocks - entry.connectionExecutor.execute(new Runnable() - { - public void run() - { - if (channel0.supports(PacketImpl.CLUSTER_TOPOLOGY_V3)) - { - channel0.send(new ClusterTopologyChangeMessage_V3(topologyMember.getUniqueEventID(), - nodeID, topologyMember.getBackupGroupName(), - topologyMember.getScaleDownGroupName(), - connectorPair, last)); + entry.connectionExecutor.execute(new Runnable() { + public void run() { + if (channel0.supports(PacketImpl.CLUSTER_TOPOLOGY_V3)) { + channel0.send(new ClusterTopologyChangeMessage_V3(topologyMember.getUniqueEventID(), nodeID, topologyMember.getBackupGroupName(), topologyMember.getScaleDownGroupName(), connectorPair, last)); } - else if (channel0.supports(PacketImpl.CLUSTER_TOPOLOGY_V2)) - { - channel0.send(new ClusterTopologyChangeMessage_V2(topologyMember.getUniqueEventID(), - nodeID, topologyMember.getBackupGroupName(), - connectorPair, last)); + else if (channel0.supports(PacketImpl.CLUSTER_TOPOLOGY_V2)) { + channel0.send(new ClusterTopologyChangeMessage_V2(topologyMember.getUniqueEventID(), nodeID, topologyMember.getBackupGroupName(), connectorPair, last)); } - else - { + else { channel0.send(new ClusterTopologyChangeMessage(nodeID, connectorPair, last)); } } }); } - catch (RejectedExecutionException ignored) - { + catch (RejectedExecutionException ignored) { // this could happen during a shutdown and we don't care, if we lost a nodeDown during a shutdown // what can we do anyways? } @@ -293,70 +257,54 @@ public class CoreProtocolManager implements ProtocolManager } @Override - public void nodeDown(final long uniqueEventID, final String nodeID) - { + public void nodeDown(final long uniqueEventID, final String nodeID) { // Using an executor as most of the notifications on the Topology // may come from a channel itself // What could cause deadlocks - try - { - entry.connectionExecutor.execute(new Runnable() - { - public void run() - { - if (channel0.supports(PacketImpl.CLUSTER_TOPOLOGY_V2)) - { + try { + entry.connectionExecutor.execute(new Runnable() { + public void run() { + if (channel0.supports(PacketImpl.CLUSTER_TOPOLOGY_V2)) { channel0.send(new ClusterTopologyChangeMessage_V2(uniqueEventID, nodeID)); } - else - { + else { channel0.send(new ClusterTopologyChangeMessage(nodeID)); } } }); } - catch (RejectedExecutionException ignored) - { + catch (RejectedExecutionException ignored) { // this could happen during a shutdown and we don't care, if we lost a nodeDown during a shutdown // what can we do anyways? } } @Override - public String toString() - { + public String toString() { return "Remote Proxy on channel " + Integer.toHexString(System.identityHashCode(this)); } }; - if (acceptorUsed.getClusterConnection() != null) - { + if (acceptorUsed.getClusterConnection() != null) { acceptorUsed.getClusterConnection().addClusterTopologyListener(listener); - rc.addCloseListener(new CloseListener() - { - public void connectionClosed() - { + rc.addCloseListener(new CloseListener() { + public void connectionClosed() { acceptorUsed.getClusterConnection().removeClusterTopologyListener(listener); } }); } - else - { + else { // if not clustered, we send a single notification to the client containing the node-id where the server is connected to // This is done this way so Recovery discovery could also use the node-id for non-clustered setups - entry.connectionExecutor.execute(new Runnable() - { - public void run() - { + entry.connectionExecutor.execute(new Runnable() { + public void run() { String nodeId = server.getNodeID().toString(); Pair emptyConfig = new Pair(null, null); - if (channel0.supports(PacketImpl.CLUSTER_TOPOLOGY_V2)) - { + if (channel0.supports(PacketImpl.CLUSTER_TOPOLOGY_V2)) { channel0.send(new ClusterTopologyChangeMessage_V2(System.currentTimeMillis(), nodeId, null, emptyConfig, true)); } - else - { + else { channel0.send(new ClusterTopologyChangeMessage(nodeId, emptyConfig, true)); } } @@ -366,10 +314,8 @@ public class CoreProtocolManager implements ProtocolManager } private Pair getPair(TransportConfiguration conn, - boolean isBackup) - { - if (isBackup) - { + boolean isBackup) { + if (isBackup) { return new Pair(null, conn); } return new Pair(conn, null); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/CoreProtocolManagerFactory.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/CoreProtocolManagerFactory.java index 1a357327ef..bc656f4dd2 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/CoreProtocolManagerFactory.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/CoreProtocolManagerFactory.java @@ -25,27 +25,28 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.spi.core.protocol.AbstractProtocolManagerFactory; import org.apache.activemq.artemis.spi.core.protocol.ProtocolManager; -public class CoreProtocolManagerFactory extends AbstractProtocolManagerFactory -{ +public class CoreProtocolManagerFactory extends AbstractProtocolManagerFactory { + private static String[] SUPPORTED_PROTOCOLS = {ActiveMQClient.DEFAULT_CORE_PROTOCOL}; private static final String MODULE_NAME = "artemis-server"; /** * {@inheritDoc} * + * * @param server * @param incomingInterceptors * @param outgoingInterceptors * @return */ - public ProtocolManager createProtocolManager(final ActiveMQServer server, final List incomingInterceptors, List outgoingInterceptors) - { + public ProtocolManager createProtocolManager(final ActiveMQServer server, + final List incomingInterceptors, + List outgoingInterceptors) { return new CoreProtocolManager(this, server, incomingInterceptors, outgoingInterceptors); } @Override - public List filterInterceptors(List interceptors) - { + public List filterInterceptors(List interceptors) { // This is using this tool method // it wouldn't be possible to write a generic method without this class parameter // and I didn't want to bloat the cllaers for this @@ -53,14 +54,12 @@ public class CoreProtocolManagerFactory extends AbstractProtocolManagerFactory TYPE_MAP; final int code; - private BackupRegistrationProblem(int code) - { + private BackupRegistrationProblem(int code) { this.code = code; } - static - { + static { HashMap map = new HashMap(); - for (BackupRegistrationProblem type : EnumSet.allOf(BackupRegistrationProblem.class)) - { + for (BackupRegistrationProblem type : EnumSet.allOf(BackupRegistrationProblem.class)) { map.put(type.code, type); } TYPE_MAP = Collections.unmodifiableMap(map); @@ -56,64 +51,59 @@ public final class BackupReplicationStartFailedMessage extends PacketImpl private BackupRegistrationProblem problem; - private static BackupRegistrationProblem getType(int type) - { + private static BackupRegistrationProblem getType(int type) { return BackupRegistrationProblem.TYPE_MAP.get(type); } - public BackupReplicationStartFailedMessage(BackupRegistrationProblem registrationProblem) - { + public BackupReplicationStartFailedMessage(BackupRegistrationProblem registrationProblem) { super(BACKUP_REGISTRATION_FAILED); problem = registrationProblem; } - public BackupReplicationStartFailedMessage() - { + public BackupReplicationStartFailedMessage() { super(BACKUP_REGISTRATION_FAILED); } - public BackupRegistrationProblem getRegistrationProblem() - { + public BackupRegistrationProblem getRegistrationProblem() { return problem; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeInt(problem.code); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { problem = getType(buffer.readInt()); } @Override - public boolean equals(Object o) - { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - if (!super.equals(o)) return false; + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + if (!super.equals(o)) + return false; BackupReplicationStartFailedMessage that = (BackupReplicationStartFailedMessage) o; - if (problem != that.problem) return false; + if (problem != that.problem) + return false; return true; } @Override - public int hashCode() - { + public int hashCode() { int result = super.hashCode(); result = 31 * result + (problem != null ? problem.hashCode() : 0); return result; } @Override - public String toString() - { + public String toString() { return getParentString() + ", problem=" + problem.name() + "]"; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/BackupRequestMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/BackupRequestMessage.java index a13f1a5fee..5300778834 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/BackupRequestMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/BackupRequestMessage.java @@ -20,8 +20,8 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class BackupRequestMessage extends PacketImpl -{ +public class BackupRequestMessage extends PacketImpl { + private int backupSize; private SimpleString nodeID; private String journalDirectory; @@ -29,14 +29,15 @@ public class BackupRequestMessage extends PacketImpl private String largeMessagesDirectory; private String pagingDirectory; - - public BackupRequestMessage() - { + public BackupRequestMessage() { super(BACKUP_REQUEST); } - public BackupRequestMessage(int backupSize, String journalDirectory, String bindingsDirectory, String largeMessagesDirectory, String pagingDirectory) - { + public BackupRequestMessage(int backupSize, + String journalDirectory, + String bindingsDirectory, + String largeMessagesDirectory, + String pagingDirectory) { super(BACKUP_REQUEST); this.backupSize = backupSize; this.journalDirectory = journalDirectory; @@ -45,16 +46,14 @@ public class BackupRequestMessage extends PacketImpl this.pagingDirectory = pagingDirectory; } - public BackupRequestMessage(int backupSize, SimpleString nodeID) - { + public BackupRequestMessage(int backupSize, SimpleString nodeID) { super(BACKUP_REQUEST); this.backupSize = backupSize; this.nodeID = nodeID; } @Override - public void encodeRest(ActiveMQBuffer buffer) - { + public void encodeRest(ActiveMQBuffer buffer) { super.encodeRest(buffer); buffer.writeInt(backupSize); buffer.writeNullableString(journalDirectory); @@ -65,8 +64,7 @@ public class BackupRequestMessage extends PacketImpl } @Override - public void decodeRest(ActiveMQBuffer buffer) - { + public void decodeRest(ActiveMQBuffer buffer) { super.decodeRest(buffer); backupSize = buffer.readInt(); journalDirectory = buffer.readNullableString(); @@ -76,33 +74,27 @@ public class BackupRequestMessage extends PacketImpl nodeID = buffer.readNullableSimpleString(); } - public int getBackupSize() - { + public int getBackupSize() { return backupSize; } - public SimpleString getNodeID() - { + public SimpleString getNodeID() { return nodeID; } - public String getJournalDirectory() - { + public String getJournalDirectory() { return journalDirectory; } - public String getBindingsDirectory() - { + public String getBindingsDirectory() { return bindingsDirectory; } - public String getLargeMessagesDirectory() - { + public String getLargeMessagesDirectory() { return largeMessagesDirectory; } - public String getPagingDirectory() - { + public String getPagingDirectory() { return pagingDirectory; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/BackupResponseMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/BackupResponseMessage.java index 3c0b88b506..5a9f685c49 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/BackupResponseMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/BackupResponseMessage.java @@ -16,52 +16,44 @@ */ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; - import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class BackupResponseMessage extends PacketImpl -{ +public class BackupResponseMessage extends PacketImpl { + boolean backupStarted; - public BackupResponseMessage() - { + public BackupResponseMessage() { super(PacketImpl.BACKUP_REQUEST_RESPONSE); } - public BackupResponseMessage(boolean backupStarted) - { + public BackupResponseMessage(boolean backupStarted) { super(PacketImpl.BACKUP_REQUEST_RESPONSE); this.backupStarted = backupStarted; } @Override - public void encodeRest(ActiveMQBuffer buffer) - { + public void encodeRest(ActiveMQBuffer buffer) { super.encodeRest(buffer); buffer.writeBoolean(backupStarted); } @Override - public void decodeRest(ActiveMQBuffer buffer) - { + public void decodeRest(ActiveMQBuffer buffer) { super.decodeRest(buffer); backupStarted = buffer.readBoolean(); } @Override - public boolean isResponse() - { + public boolean isResponse() { return true; } - public boolean isBackupStarted() - { + public boolean isBackupStarted() { return backupStarted; } - public void setBackupStarted(boolean backupStarted) - { + public void setBackupStarted(boolean backupStarted) { this.backupStarted = backupStarted; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ClusterConnectMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ClusterConnectMessage.java index 090315338d..15780929a1 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ClusterConnectMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ClusterConnectMessage.java @@ -19,46 +19,38 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class ClusterConnectMessage extends PacketImpl -{ +public class ClusterConnectMessage extends PacketImpl { + private String clusterUser; private String clusterPassword; - public ClusterConnectMessage() - { + public ClusterConnectMessage() { super(CLUSTER_CONNECT); } - public ClusterConnectMessage(String clusterUser, String clusterPassword) - { + public ClusterConnectMessage(String clusterUser, String clusterPassword) { super(CLUSTER_CONNECT); this.clusterUser = clusterUser; this.clusterPassword = clusterPassword; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeString(clusterUser); buffer.writeString(clusterPassword); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { clusterUser = buffer.readString(); clusterPassword = buffer.readString(); } - - - public String getClusterUser() - { + public String getClusterUser() { return clusterUser; } - public String getClusterPassword() - { + public String getClusterPassword() { return clusterPassword; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ClusterConnectReplyMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ClusterConnectReplyMessage.java index 2382ec7aa4..d4d877a7e0 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ClusterConnectReplyMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ClusterConnectReplyMessage.java @@ -16,52 +16,44 @@ */ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; - import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class ClusterConnectReplyMessage extends PacketImpl -{ +public class ClusterConnectReplyMessage extends PacketImpl { + private boolean authorized; - public ClusterConnectReplyMessage() - { + public ClusterConnectReplyMessage() { super(CLUSTER_CONNECT_REPLY); } - public ClusterConnectReplyMessage(boolean authorized) - { + public ClusterConnectReplyMessage(boolean authorized) { super(CLUSTER_CONNECT_REPLY); this.authorized = authorized; } @Override - public boolean isResponse() - { + public boolean isResponse() { return true; } @Override - public void encodeRest(ActiveMQBuffer buffer) - { + public void encodeRest(ActiveMQBuffer buffer) { super.encodeRest(buffer); buffer.writeBoolean(authorized); } @Override - public void decodeRest(ActiveMQBuffer buffer) - { + public void decodeRest(ActiveMQBuffer buffer) { super.decodeRest(buffer); authorized = buffer.readBoolean(); } - public boolean isAuthorized() - { + public boolean isAuthorized() { return authorized; } - public void setAuthorized(boolean authorized) - { + public void setAuthorized(boolean authorized) { this.authorized = authorized; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/NodeAnnounceMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/NodeAnnounceMessage.java index aa9b855b5b..714c21fe29 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/NodeAnnounceMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/NodeAnnounceMessage.java @@ -20,8 +20,8 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class NodeAnnounceMessage extends PacketImpl -{ +public class NodeAnnounceMessage extends PacketImpl { + protected String nodeID; protected String backupGroupName; @@ -40,8 +40,13 @@ public class NodeAnnounceMessage extends PacketImpl // Constructors -------------------------------------------------- - public NodeAnnounceMessage(final long currentEventID, final String nodeID, final String backupGroupName, final String scaleDownGroupName, final boolean backup, final TransportConfiguration tc, final TransportConfiguration backupConnector) - { + public NodeAnnounceMessage(final long currentEventID, + final String nodeID, + final String backupGroupName, + final String scaleDownGroupName, + final boolean backup, + final TransportConfiguration tc, + final TransportConfiguration backupConnector) { super(NODE_ANNOUNCE); this.currentEventID = currentEventID; @@ -59,99 +64,81 @@ public class NodeAnnounceMessage extends PacketImpl this.scaleDownGroupName = scaleDownGroupName; } - public NodeAnnounceMessage() - { + public NodeAnnounceMessage() { super(NODE_ANNOUNCE); } - public NodeAnnounceMessage(byte nodeAnnounceMessage_V2) - { + public NodeAnnounceMessage(byte nodeAnnounceMessage_V2) { super(nodeAnnounceMessage_V2); } // Public -------------------------------------------------------- - - public String getNodeID() - { + public String getNodeID() { return nodeID; } - public String getBackupGroupName() - { + public String getBackupGroupName() { return backupGroupName; } - public boolean isBackup() - { + public boolean isBackup() { return backup; } - public TransportConfiguration getConnector() - { + public TransportConfiguration getConnector() { return connector; } - public TransportConfiguration getBackupConnector() - { + public TransportConfiguration getBackupConnector() { return backupConnector; } - public String getScaleDownGroupName() - { + public String getScaleDownGroupName() { return scaleDownGroupName; } /** * @return the currentEventID */ - public long getCurrentEventID() - { + public long getCurrentEventID() { return currentEventID; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeString(nodeID); buffer.writeNullableString(backupGroupName); buffer.writeBoolean(backup); buffer.writeLong(currentEventID); - if (connector != null) - { + if (connector != null) { buffer.writeBoolean(true); connector.encode(buffer); } - else - { + else { buffer.writeBoolean(false); } - if (backupConnector != null) - { + if (backupConnector != null) { buffer.writeBoolean(true); backupConnector.encode(buffer); } - else - { + else { buffer.writeBoolean(false); } buffer.writeNullableString(scaleDownGroupName); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { this.nodeID = buffer.readString(); this.backupGroupName = buffer.readNullableString(); this.backup = buffer.readBoolean(); this.currentEventID = buffer.readLong(); - if (buffer.readBoolean()) - { + if (buffer.readBoolean()) { connector = new TransportConfiguration(); connector.decode(buffer); } - if (buffer.readBoolean()) - { + if (buffer.readBoolean()) { backupConnector = new TransportConfiguration(); backupConnector.decode(buffer); } @@ -159,91 +146,73 @@ public class NodeAnnounceMessage extends PacketImpl } @Override - public String toString() - { + public String toString() { return "NodeAnnounceMessage [backup=" + backup + - ", connector=" + - connector + - ", nodeID=" + - nodeID + - ", toString()=" + - super.toString() + - "]"; + ", connector=" + + connector + + ", nodeID=" + + nodeID + + ", toString()=" + + super.toString() + + "]"; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (backup ? 1231 : 1237); result = prime * result + ((backupConnector == null) ? 0 : backupConnector.hashCode()); result = prime * result + ((connector == null) ? 0 : connector.hashCode()); - result = prime * result + (int)(currentEventID ^ (currentEventID >>> 32)); + result = prime * result + (int) (currentEventID ^ (currentEventID >>> 32)); result = prime * result + ((nodeID == null) ? 0 : nodeID.hashCode()); result = prime * result + ((scaleDownGroupName == null) ? 0 : scaleDownGroupName.hashCode()); return result; } @Override - public boolean equals(Object obj) - { - if (this == obj) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if (!super.equals(obj)) - { + if (!super.equals(obj)) { return false; } - if (!(obj instanceof NodeAnnounceMessage)) - { + if (!(obj instanceof NodeAnnounceMessage)) { return false; } - NodeAnnounceMessage other = (NodeAnnounceMessage)obj; - if (backup != other.backup) - { + NodeAnnounceMessage other = (NodeAnnounceMessage) obj; + if (backup != other.backup) { return false; } - if (backupConnector == null) - { - if (other.backupConnector != null) - { + if (backupConnector == null) { + if (other.backupConnector != null) { return false; } } - else if (!backupConnector.equals(other.backupConnector)) - { + else if (!backupConnector.equals(other.backupConnector)) { return false; } - if (connector == null) - { - if (other.connector != null) - { + if (connector == null) { + if (other.connector != null) { return false; } } - else if (!connector.equals(other.connector)) - { + else if (!connector.equals(other.connector)) { return false; } - if (currentEventID != other.currentEventID) - { + if (currentEventID != other.currentEventID) { return false; } - if (nodeID == null) - { - if (other.nodeID != null) - { + if (nodeID == null) { + if (other.nodeID != null) { return false; } } - else if (!nodeID.equals(other.nodeID)) - { + else if (!nodeID.equals(other.nodeID)) { return false; } - else if (!scaleDownGroupName.equals(other.scaleDownGroupName)) - { + else if (!scaleDownGroupName.equals(other.scaleDownGroupName)) { return false; } return true; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/QuorumVoteMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/QuorumVoteMessage.java index 476e2bf13d..f80834918d 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/QuorumVoteMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/QuorumVoteMessage.java @@ -22,54 +22,47 @@ import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; import org.apache.activemq.artemis.core.server.cluster.qourum.QuorumVoteHandler; import org.apache.activemq.artemis.core.server.cluster.qourum.Vote; -public class QuorumVoteMessage extends PacketImpl -{ +public class QuorumVoteMessage extends PacketImpl { + private SimpleString handler; private Vote vote; private ActiveMQBuffer voteBuffer; - public QuorumVoteMessage() - { + public QuorumVoteMessage() { super(QUORUM_VOTE); } - public QuorumVoteMessage(SimpleString handler, Vote vote) - { + public QuorumVoteMessage(SimpleString handler, Vote vote) { super(QUORUM_VOTE); this.handler = handler; this.vote = vote; } @Override - public void encodeRest(ActiveMQBuffer buffer) - { + public void encodeRest(ActiveMQBuffer buffer) { super.encodeRest(buffer); buffer.writeSimpleString(handler); vote.encode(buffer); } @Override - public void decodeRest(ActiveMQBuffer buffer) - { + public void decodeRest(ActiveMQBuffer buffer) { super.decodeRest(buffer); handler = buffer.readSimpleString(); voteBuffer = buffer.readSlice(buffer.readableBytes()); } - public SimpleString getHandler() - { + public SimpleString getHandler() { return handler; } - public Vote getVote() - { + public Vote getVote() { return vote; } - public void decode(QuorumVoteHandler voteHandler) - { + public void decode(QuorumVoteHandler voteHandler) { vote = voteHandler.decode(voteBuffer); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/QuorumVoteReplyMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/QuorumVoteReplyMessage.java index bdadf13dde..ff0609cfbc 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/QuorumVoteReplyMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/QuorumVoteReplyMessage.java @@ -22,58 +22,50 @@ import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; import org.apache.activemq.artemis.core.server.cluster.qourum.QuorumVoteHandler; import org.apache.activemq.artemis.core.server.cluster.qourum.Vote; -public class QuorumVoteReplyMessage extends PacketImpl -{ +public class QuorumVoteReplyMessage extends PacketImpl { + private SimpleString handler; private Vote vote; private ActiveMQBuffer voteBuffer; - public QuorumVoteReplyMessage(SimpleString handler, Vote vote) - { + public QuorumVoteReplyMessage(SimpleString handler, Vote vote) { super(QUORUM_VOTE_REPLY); this.handler = handler; this.vote = vote; } - public QuorumVoteReplyMessage() - { + public QuorumVoteReplyMessage() { super(QUORUM_VOTE_REPLY); } - public Vote getVote() - { + public Vote getVote() { return vote; } - public SimpleString getHandler() - { + public SimpleString getHandler() { return handler; } @Override - public boolean isResponse() - { + public boolean isResponse() { return true; } @Override - public void encodeRest(ActiveMQBuffer buffer) - { + public void encodeRest(ActiveMQBuffer buffer) { super.encodeRest(buffer); buffer.writeSimpleString(handler); vote.encode(buffer); } @Override - public void decodeRest(ActiveMQBuffer buffer) - { + public void decodeRest(ActiveMQBuffer buffer) { super.decodeRest(buffer); handler = buffer.readSimpleString(); voteBuffer = buffer.readSlice(buffer.readableBytes()); } - public void decodeRest(QuorumVoteHandler voteHandler) - { + public void decodeRest(QuorumVoteHandler voteHandler) { vote = voteHandler.decode(voteBuffer); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationAddMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationAddMessage.java index 69bbad635c..eebc29aed5 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationAddMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationAddMessage.java @@ -23,11 +23,13 @@ import org.apache.activemq.artemis.core.journal.EncodingSupport; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; import org.apache.activemq.artemis.core.replication.ReplicationManager.ADD_OPERATION_TYPE; -public final class ReplicationAddMessage extends PacketImpl -{ +public final class ReplicationAddMessage extends PacketImpl { + private long id; - /** 0 - BindingsImpl, 1 - MessagesJournal */ + /** + * 0 - BindingsImpl, 1 - MessagesJournal + */ private byte journalID; private ADD_OPERATION_TYPE operation; @@ -38,14 +40,15 @@ public final class ReplicationAddMessage extends PacketImpl private byte[] recordData; - public ReplicationAddMessage() - { + public ReplicationAddMessage() { super(PacketImpl.REPLICATION_APPEND); } - public ReplicationAddMessage(final byte journalID, final ADD_OPERATION_TYPE operation, final long id, - final byte journalRecordType, final EncodingSupport encodingData) - { + public ReplicationAddMessage(final byte journalID, + final ADD_OPERATION_TYPE operation, + final long id, + final byte journalRecordType, + final EncodingSupport encodingData) { this(); this.journalID = journalID; this.operation = operation; @@ -57,8 +60,7 @@ public final class ReplicationAddMessage extends PacketImpl // Public -------------------------------------------------------- @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeByte(journalID); buffer.writeBoolean(operation.toBoolean()); @@ -69,8 +71,7 @@ public final class ReplicationAddMessage extends PacketImpl } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { journalID = buffer.readByte(); operation = ADD_OPERATION_TYPE.toOperation(buffer.readBoolean()); id = buffer.readLong(); @@ -83,47 +84,41 @@ public final class ReplicationAddMessage extends PacketImpl /** * @return the id */ - public long getId() - { + public long getId() { return id; } /** * @return the journalID */ - public byte getJournalID() - { + public byte getJournalID() { return journalID; } - public ADD_OPERATION_TYPE getRecord() - { + public ADD_OPERATION_TYPE getRecord() { return operation; } /** * @return the recordType */ - public byte getJournalRecordType() - { + public byte getJournalRecordType() { return journalRecordType; } /** * @return the recordData */ - public byte[] getRecordData() - { + public byte[] getRecordData() { return recordData; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((encodingData == null) ? 0 : encodingData.hashCode()); - result = prime * result + (int)(id ^ (id >>> 32)); + result = prime * result + (int) (id ^ (id >>> 32)); result = prime * result + journalID; result = prime * result + journalRecordType; result = prime * result + ((operation == null) ? 0 : operation.hashCode()); @@ -132,17 +127,15 @@ public final class ReplicationAddMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof ReplicationAddMessage)) return false; - ReplicationAddMessage other = (ReplicationAddMessage)obj; - if (encodingData == null) - { + ReplicationAddMessage other = (ReplicationAddMessage) obj; + if (encodingData == null) { if (other.encodingData != null) return false; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationAddTXMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationAddTXMessage.java index 9e719ac811..c4d7e79e2f 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationAddTXMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationAddTXMessage.java @@ -23,14 +23,15 @@ import org.apache.activemq.artemis.core.journal.EncodingSupport; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; import org.apache.activemq.artemis.core.replication.ReplicationManager.ADD_OPERATION_TYPE; -public class ReplicationAddTXMessage extends PacketImpl -{ +public class ReplicationAddTXMessage extends PacketImpl { private long txId; private long id; - /** 0 - BindingsImpl, 1 - MessagesJournal */ + /** + * 0 - BindingsImpl, 1 - MessagesJournal + */ private byte journalID; private byte recordType; @@ -41,17 +42,16 @@ public class ReplicationAddTXMessage extends PacketImpl private ADD_OPERATION_TYPE operation; - public ReplicationAddTXMessage() - { + public ReplicationAddTXMessage() { super(PacketImpl.REPLICATION_APPEND_TX); } - public ReplicationAddTXMessage(final byte journalID, final ADD_OPERATION_TYPE operation, + public ReplicationAddTXMessage(final byte journalID, + final ADD_OPERATION_TYPE operation, final long txId, final long id, final byte recordType, - final EncodingSupport encodingData) - { + final EncodingSupport encodingData) { this(); this.journalID = journalID; this.operation = operation; @@ -64,8 +64,7 @@ public class ReplicationAddTXMessage extends PacketImpl // Public -------------------------------------------------------- @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeByte(journalID); buffer.writeBoolean(operation.toBoolean()); buffer.writeLong(txId); @@ -76,8 +75,7 @@ public class ReplicationAddTXMessage extends PacketImpl } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { journalID = buffer.readByte(); operation = ADD_OPERATION_TYPE.toOperation(buffer.readBoolean()); txId = buffer.readLong(); @@ -91,72 +89,63 @@ public class ReplicationAddTXMessage extends PacketImpl /** * @return the id */ - public long getId() - { + public long getId() { return id; } - public long getTxId() - { + public long getTxId() { return txId; } /** * @return the journalID */ - public byte getJournalID() - { + public byte getJournalID() { return journalID; } - public ADD_OPERATION_TYPE getOperation() - { + public ADD_OPERATION_TYPE getOperation() { return operation; } /** * @return the recordType */ - public byte getRecordType() - { + public byte getRecordType() { return recordType; } /** * @return the recordData */ - public byte[] getRecordData() - { + public byte[] getRecordData() { return recordData; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((encodingData == null) ? 0 : encodingData.hashCode()); - result = prime * result + (int)(id ^ (id >>> 32)); + result = prime * result + (int) (id ^ (id >>> 32)); result = prime * result + journalID; result = prime * result + ((operation == null) ? 0 : operation.hashCode()); result = prime * result + Arrays.hashCode(recordData); result = prime * result + recordType; - result = prime * result + (int)(txId ^ (txId >>> 32)); + result = prime * result + (int) (txId ^ (txId >>> 32)); return result; } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof ReplicationAddTXMessage)) return false; - ReplicationAddTXMessage other = (ReplicationAddTXMessage)obj; - if (encodingData == null) - { + ReplicationAddTXMessage other = (ReplicationAddTXMessage) obj; + if (encodingData == null) { if (other.encodingData != null) return false; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationCommitMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationCommitMessage.java index 864649f242..1987b3db1b 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationCommitMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationCommitMessage.java @@ -19,24 +19,22 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public final class ReplicationCommitMessage extends PacketImpl -{ +public final class ReplicationCommitMessage extends PacketImpl { - /** 0 - BindingsImpl, 1 - MessagesJournal */ + /** + * 0 - BindingsImpl, 1 - MessagesJournal + */ private byte journalID; private boolean rollback; private long txId; - - public ReplicationCommitMessage() - { + public ReplicationCommitMessage() { super(PacketImpl.REPLICATION_COMMIT_ROLLBACK); } - public ReplicationCommitMessage(final byte journalID, final boolean rollback, final long txId) - { + public ReplicationCommitMessage(final byte journalID, final boolean rollback, final long txId) { this(); this.journalID = journalID; this.rollback = rollback; @@ -44,60 +42,53 @@ public final class ReplicationCommitMessage extends PacketImpl } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeByte(journalID); buffer.writeBoolean(rollback); buffer.writeLong(txId); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { journalID = buffer.readByte(); rollback = buffer.readBoolean(); txId = buffer.readLong(); } - public boolean isRollback() - { + public boolean isRollback() { return rollback; } - public long getTxId() - { + public long getTxId() { return txId; } /** * @return the journalID */ - public byte getJournalID() - { + public byte getJournalID() { return journalID; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + journalID; result = prime * result + (rollback ? 1231 : 1237); - result = prime * result + (int)(txId ^ (txId >>> 32)); + result = prime * result + (int) (txId ^ (txId >>> 32)); return result; } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof ReplicationCommitMessage)) return false; - ReplicationCommitMessage other = (ReplicationCommitMessage)obj; + ReplicationCommitMessage other = (ReplicationCommitMessage) obj; if (journalID != other.journalID) return false; if (rollback != other.rollback) @@ -108,10 +99,9 @@ public final class ReplicationCommitMessage extends PacketImpl } @Override - public String toString() - { + public String toString() { String txOperation = rollback ? "rollback" : "commmit"; return ReplicationCommitMessage.class.getSimpleName() + "[type=" + getType() + ", channel=" + getChannelID() + - ", journalID=" + journalID + ", txAction='" + txOperation + "']"; + ", journalID=" + journalID + ", txAction='" + txOperation + "']"; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationDeleteMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationDeleteMessage.java index 8cfffc8860..ab97b18579 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationDeleteMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationDeleteMessage.java @@ -19,35 +19,33 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public final class ReplicationDeleteMessage extends PacketImpl -{ +public final class ReplicationDeleteMessage extends PacketImpl { + private long id; - /** 0 - BindingsImpl, 1 - MessagesJournal */ + /** + * 0 - BindingsImpl, 1 - MessagesJournal + */ private byte journalID; - public ReplicationDeleteMessage() - { + public ReplicationDeleteMessage() { super(PacketImpl.REPLICATION_DELETE); } - public ReplicationDeleteMessage(final byte journalID, final long id) - { + public ReplicationDeleteMessage(final byte journalID, final long id) { this(); this.journalID = journalID; this.id = id; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeByte(journalID); buffer.writeLong(id); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { journalID = buffer.readByte(); id = buffer.readLong(); } @@ -55,39 +53,35 @@ public final class ReplicationDeleteMessage extends PacketImpl /** * @return the id */ - public long getId() - { + public long getId() { return id; } /** * @return the journalID */ - public byte getJournalID() - { + public byte getJournalID() { return journalID; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); - result = prime * result + (int)(id ^ (id >>> 32)); + result = prime * result + (int) (id ^ (id >>> 32)); result = prime * result + journalID; return result; } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof ReplicationDeleteMessage)) return false; - ReplicationDeleteMessage other = (ReplicationDeleteMessage)obj; + ReplicationDeleteMessage other = (ReplicationDeleteMessage) obj; if (id != other.id) return false; if (journalID != other.journalID) diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationDeleteTXMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationDeleteTXMessage.java index e3fff6942b..82f652514d 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationDeleteTXMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationDeleteTXMessage.java @@ -22,30 +22,29 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.journal.EncodingSupport; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class ReplicationDeleteTXMessage extends PacketImpl -{ +public class ReplicationDeleteTXMessage extends PacketImpl { private long txId; private long id; - /** 0 - BindingsImpl, 1 - MessagesJournal */ + /** + * 0 - BindingsImpl, 1 - MessagesJournal + */ private byte journalID; private EncodingSupport encodingData; private byte[] recordData; - public ReplicationDeleteTXMessage() - { + public ReplicationDeleteTXMessage() { super(PacketImpl.REPLICATION_DELETE_TX); } public ReplicationDeleteTXMessage(final byte journalID, final long txId, final long id, - final EncodingSupport encodingData) - { + final EncodingSupport encodingData) { this(); this.journalID = journalID; this.txId = txId; @@ -54,8 +53,7 @@ public class ReplicationDeleteTXMessage extends PacketImpl } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeByte(journalID); buffer.writeLong(txId); buffer.writeLong(id); @@ -64,8 +62,7 @@ public class ReplicationDeleteTXMessage extends PacketImpl } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { journalID = buffer.readByte(); txId = buffer.readLong(); id = buffer.readLong(); @@ -77,57 +74,50 @@ public class ReplicationDeleteTXMessage extends PacketImpl /** * @return the id */ - public long getId() - { + public long getId() { return id; } - public long getTxId() - { + public long getTxId() { return txId; } /** * @return the journalID */ - public byte getJournalID() - { + public byte getJournalID() { return journalID; } /** * @return the recordData */ - public byte[] getRecordData() - { + public byte[] getRecordData() { return recordData; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((encodingData == null) ? 0 : encodingData.hashCode()); - result = prime * result + (int)(id ^ (id >>> 32)); + result = prime * result + (int) (id ^ (id >>> 32)); result = prime * result + journalID; result = prime * result + Arrays.hashCode(recordData); - result = prime * result + (int)(txId ^ (txId >>> 32)); + result = prime * result + (int) (txId ^ (txId >>> 32)); return result; } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; - ReplicationDeleteTXMessage other = (ReplicationDeleteTXMessage)obj; - if (encodingData == null) - { + ReplicationDeleteTXMessage other = (ReplicationDeleteTXMessage) obj; + if (encodingData == null) { if (other.encodingData != null) return false; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationLargeMessageBeginMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationLargeMessageBeginMessage.java index 62515e5091..0a36a56471 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationLargeMessageBeginMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationLargeMessageBeginMessage.java @@ -19,61 +19,53 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class ReplicationLargeMessageBeginMessage extends PacketImpl -{ +public class ReplicationLargeMessageBeginMessage extends PacketImpl { long messageId; - public ReplicationLargeMessageBeginMessage(final long messageId) - { + public ReplicationLargeMessageBeginMessage(final long messageId) { this(); this.messageId = messageId; } - public ReplicationLargeMessageBeginMessage() - { + public ReplicationLargeMessageBeginMessage() { super(PacketImpl.REPLICATION_LARGE_MESSAGE_BEGIN); } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeLong(messageId); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { messageId = buffer.readLong(); } /** * @return the messageId */ - public long getMessageId() - { + public long getMessageId() { return messageId; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); - result = prime * result + (int)(messageId ^ (messageId >>> 32)); + result = prime * result + (int) (messageId ^ (messageId >>> 32)); return result; } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; - ReplicationLargeMessageBeginMessage other = (ReplicationLargeMessageBeginMessage)obj; + ReplicationLargeMessageBeginMessage other = (ReplicationLargeMessageBeginMessage) obj; if (messageId != other.messageId) return false; return true; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationLargeMessageEndMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationLargeMessageEndMessage.java index 516e6b7c74..eea788a0d3 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationLargeMessageEndMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationLargeMessageEndMessage.java @@ -19,61 +19,53 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class ReplicationLargeMessageEndMessage extends PacketImpl -{ +public class ReplicationLargeMessageEndMessage extends PacketImpl { long messageId; - public ReplicationLargeMessageEndMessage() - { + public ReplicationLargeMessageEndMessage() { super(PacketImpl.REPLICATION_LARGE_MESSAGE_END); } - public ReplicationLargeMessageEndMessage(final long messageId) - { + public ReplicationLargeMessageEndMessage(final long messageId) { this(); this.messageId = messageId; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeLong(messageId); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { messageId = buffer.readLong(); } /** * @return the messageId */ - public long getMessageId() - { + public long getMessageId() { return messageId; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); - result = prime * result + (int)(messageId ^ (messageId >>> 32)); + result = prime * result + (int) (messageId ^ (messageId >>> 32)); return result; } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; - ReplicationLargeMessageEndMessage other = (ReplicationLargeMessageEndMessage)obj; + ReplicationLargeMessageEndMessage other = (ReplicationLargeMessageEndMessage) obj; if (messageId != other.messageId) return false; return true; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationLargeMessageWriteMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationLargeMessageWriteMessage.java index df1f277936..0970f0594a 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationLargeMessageWriteMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationLargeMessageWriteMessage.java @@ -21,15 +21,13 @@ import java.util.Arrays; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public final class ReplicationLargeMessageWriteMessage extends PacketImpl -{ +public final class ReplicationLargeMessageWriteMessage extends PacketImpl { private long messageId; private byte[] body; - public ReplicationLargeMessageWriteMessage() - { + public ReplicationLargeMessageWriteMessage() { super(PacketImpl.REPLICATION_LARGE_MESSAGE_WRITE); } @@ -37,8 +35,7 @@ public final class ReplicationLargeMessageWriteMessage extends PacketImpl * @param messageId * @param body */ - public ReplicationLargeMessageWriteMessage(final long messageId, final byte[] body) - { + public ReplicationLargeMessageWriteMessage(final long messageId, final byte[] body) { this(); this.messageId = messageId; @@ -46,16 +43,14 @@ public final class ReplicationLargeMessageWriteMessage extends PacketImpl } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeLong(messageId); buffer.writeInt(body.length); buffer.writeBytes(body); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { messageId = buffer.readLong(); int size = buffer.readInt(); body = new byte[size]; @@ -65,22 +60,19 @@ public final class ReplicationLargeMessageWriteMessage extends PacketImpl /** * @return the messageId */ - public long getMessageId() - { + public long getMessageId() { return messageId; } /** * @return the body */ - public byte[] getBody() - { + public byte[] getBody() { return body; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + Arrays.hashCode(body); @@ -89,8 +81,7 @@ public final class ReplicationLargeMessageWriteMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationLiveIsStoppingMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationLiveIsStoppingMessage.java index 36141729d8..28e03cf663 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationLiveIsStoppingMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationLiveIsStoppingMessage.java @@ -24,11 +24,9 @@ import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; *

    * The backup starts the fail-over immediately after receiving this. */ -public final class ReplicationLiveIsStoppingMessage extends PacketImpl -{ +public final class ReplicationLiveIsStoppingMessage extends PacketImpl { - public enum LiveStopping - { + public enum LiveStopping { /** * Notifies the backup that its live is going to stop. The backup will then NOT fail-over if * it gets signals from the cluster that its live sent a disconnect. @@ -41,8 +39,7 @@ public final class ReplicationLiveIsStoppingMessage extends PacketImpl FAIL_OVER(1); private final int code; - private LiveStopping(int code) - { + private LiveStopping(int code) { this.code = code; } } @@ -50,45 +47,40 @@ public final class ReplicationLiveIsStoppingMessage extends PacketImpl private int finalMessage; private LiveStopping liveStopping; - public ReplicationLiveIsStoppingMessage() - { + public ReplicationLiveIsStoppingMessage() { super(PacketImpl.REPLICATION_SCHEDULED_FAILOVER); } /** * @param b */ - public ReplicationLiveIsStoppingMessage(LiveStopping b) - { + public ReplicationLiveIsStoppingMessage(LiveStopping b) { this(); this.liveStopping = b; } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeInt(liveStopping.code); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { liveStopping = buffer.readInt() == 0 ? LiveStopping.STOP_CALLED : LiveStopping.FAIL_OVER; } /** * The first message is sent to turn-off the quorumManager, which in some cases would trigger a * faster fail-over than what would be correct. + * * @return */ - public LiveStopping isFinalMessage() - { + public LiveStopping isFinalMessage() { return liveStopping; } @Override - public String toString() - { + public String toString() { return super.toString() + ":" + liveStopping; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationPageEventMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationPageEventMessage.java index 0ebedd00a9..78555dbc6d 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationPageEventMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationPageEventMessage.java @@ -20,8 +20,7 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class ReplicationPageEventMessage extends PacketImpl -{ +public class ReplicationPageEventMessage extends PacketImpl { private int pageNumber; @@ -32,13 +31,11 @@ public class ReplicationPageEventMessage extends PacketImpl */ private boolean isDelete; - public ReplicationPageEventMessage() - { + public ReplicationPageEventMessage() { super(PacketImpl.REPLICATION_PAGE_EVENT); } - public ReplicationPageEventMessage(final SimpleString storeName, final int pageNumber, final boolean isDelete) - { + public ReplicationPageEventMessage(final SimpleString storeName, final int pageNumber, final boolean isDelete) { this(); this.pageNumber = pageNumber; this.isDelete = isDelete; @@ -46,16 +43,14 @@ public class ReplicationPageEventMessage extends PacketImpl } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeSimpleString(storeName); buffer.writeInt(pageNumber); buffer.writeBoolean(isDelete); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { storeName = buffer.readSimpleString(); pageNumber = buffer.readInt(); isDelete = buffer.readBoolean(); @@ -64,37 +59,32 @@ public class ReplicationPageEventMessage extends PacketImpl /** * @return the pageNumber */ - public int getPageNumber() - { + public int getPageNumber() { return pageNumber; } /** * @return the storeName */ - public SimpleString getStoreName() - { + public SimpleString getStoreName() { return storeName; } /** * @return the isDelete */ - public boolean isDelete() - { + public boolean isDelete() { return isDelete; } @Override - public String toString() - { + public String toString() { return ReplicationPageEventMessage.class.getSimpleName() + "(channel=" + channelID + ", isDelete=" + isDelete + - ", storeName=" + storeName + ", pageNumber=" + pageNumber + ")"; + ", storeName=" + storeName + ", pageNumber=" + pageNumber + ")"; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (isDelete ? 1231 : 1237); @@ -104,21 +94,19 @@ public class ReplicationPageEventMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; - ReplicationPageEventMessage other = (ReplicationPageEventMessage)obj; + ReplicationPageEventMessage other = (ReplicationPageEventMessage) obj; if (isDelete != other.isDelete) return false; if (pageNumber != other.pageNumber) return false; - if (storeName == null) - { + if (storeName == null) { if (other.storeName != null) return false; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationPageWriteMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationPageWriteMessage.java index 3669651c83..4199cb088f 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationPageWriteMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationPageWriteMessage.java @@ -21,21 +21,17 @@ import org.apache.activemq.artemis.core.paging.PagedMessage; import org.apache.activemq.artemis.core.paging.impl.PagedMessageImpl; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class ReplicationPageWriteMessage extends PacketImpl -{ +public class ReplicationPageWriteMessage extends PacketImpl { private int pageNumber; private PagedMessage pagedMessage; - - public ReplicationPageWriteMessage() - { + public ReplicationPageWriteMessage() { super(PacketImpl.REPLICATION_PAGE_WRITE); } - public ReplicationPageWriteMessage(final PagedMessage pagedMessage, final int pageNumber) - { + public ReplicationPageWriteMessage(final PagedMessage pagedMessage, final int pageNumber) { this(); this.pageNumber = pageNumber; this.pagedMessage = pagedMessage; @@ -44,15 +40,13 @@ public class ReplicationPageWriteMessage extends PacketImpl // Public -------------------------------------------------------- @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeInt(pageNumber); pagedMessage.encode(buffer); } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { pageNumber = buffer.readInt(); pagedMessage = new PagedMessageImpl(); pagedMessage.decode(buffer); @@ -61,22 +55,19 @@ public class ReplicationPageWriteMessage extends PacketImpl /** * @return the pageNumber */ - public int getPageNumber() - { + public int getPageNumber() { return pageNumber; } /** * @return the pagedMessage */ - public PagedMessage getPagedMessage() - { + public PagedMessage getPagedMessage() { return pagedMessage; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + pageNumber; @@ -85,19 +76,17 @@ public class ReplicationPageWriteMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; - ReplicationPageWriteMessage other = (ReplicationPageWriteMessage)obj; + ReplicationPageWriteMessage other = (ReplicationPageWriteMessage) obj; if (pageNumber != other.pageNumber) return false; - if (pagedMessage == null) - { + if (pagedMessage == null) { if (other.pagedMessage != null) return false; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationPrepareMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationPrepareMessage.java index e9f31eb123..cf8c413f84 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationPrepareMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationPrepareMessage.java @@ -22,8 +22,8 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.journal.EncodingSupport; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public final class ReplicationPrepareMessage extends PacketImpl -{ +public final class ReplicationPrepareMessage extends PacketImpl { + private long txId; /** @@ -35,13 +35,11 @@ public final class ReplicationPrepareMessage extends PacketImpl private byte[] recordData; - public ReplicationPrepareMessage() - { + public ReplicationPrepareMessage() { super(PacketImpl.REPLICATION_PREPARE); } - public ReplicationPrepareMessage(final byte journalID, final long txId, final EncodingSupport encodingData) - { + public ReplicationPrepareMessage(final byte journalID, final long txId, final EncodingSupport encodingData) { this(); this.journalID = journalID; this.txId = txId; @@ -51,8 +49,7 @@ public final class ReplicationPrepareMessage extends PacketImpl // Public -------------------------------------------------------- @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeByte(journalID); buffer.writeLong(txId); buffer.writeInt(encodingData.getEncodeSize()); @@ -60,8 +57,7 @@ public final class ReplicationPrepareMessage extends PacketImpl } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { journalID = buffer.readByte(); txId = buffer.readLong(); int size = buffer.readInt(); @@ -69,30 +65,26 @@ public final class ReplicationPrepareMessage extends PacketImpl buffer.readBytes(recordData); } - public long getTxId() - { + public long getTxId() { return txId; } /** * @return the journalID */ - public byte getJournalID() - { + public byte getJournalID() { return journalID; } /** * @return the recordData */ - public byte[] getRecordData() - { + public byte[] getRecordData() { return recordData; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((encodingData == null) ? 0 : encodingData.hashCode()); @@ -103,42 +95,32 @@ public final class ReplicationPrepareMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { - if (this == obj) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if (!super.equals(obj)) - { + if (!super.equals(obj)) { return false; } - if (!(obj instanceof ReplicationPrepareMessage)) - { + if (!(obj instanceof ReplicationPrepareMessage)) { return false; } ReplicationPrepareMessage other = (ReplicationPrepareMessage) obj; - if (encodingData == null) - { - if (other.encodingData != null) - { + if (encodingData == null) { + if (other.encodingData != null) { return false; } } - else if (!encodingData.equals(other.encodingData)) - { + else if (!encodingData.equals(other.encodingData)) { return false; } - if (journalID != other.journalID) - { + if (journalID != other.journalID) { return false; } - if (!Arrays.equals(recordData, other.recordData)) - { + if (!Arrays.equals(recordData, other.recordData)) { return false; } - if (txId != other.txId) - { + if (txId != other.txId) { return false; } return true; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationResponseMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationResponseMessage.java index 1a15642c85..ac06997918 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationResponseMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationResponseMessage.java @@ -18,11 +18,9 @@ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public final class ReplicationResponseMessage extends PacketImpl -{ +public final class ReplicationResponseMessage extends PacketImpl { - public ReplicationResponseMessage() - { + public ReplicationResponseMessage() { super(PacketImpl.REPLICATION_RESPONSE); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationStartSyncMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationStartSyncMessage.java index c94c2169aa..d6d6753d69 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationStartSyncMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationStartSyncMessage.java @@ -31,34 +31,30 @@ import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; * At start, it sends all fileIDs used in a given journal live server to the backup, so the backup * can reserve those IDs. */ -public class ReplicationStartSyncMessage extends PacketImpl -{ +public class ReplicationStartSyncMessage extends PacketImpl { + private long[] ids; private SyncDataType dataType; private boolean synchronizationIsFinished; private String nodeID; private boolean allowsAutoFailBack; - public enum SyncDataType - { + public enum SyncDataType { JournalBindings(JournalContent.BINDINGS.typeByte), JournalMessages(JournalContent.MESSAGES.typeByte), - LargeMessages((byte)2); + LargeMessages((byte) 2); private byte code; - private SyncDataType(byte code) - { + private SyncDataType(byte code) { this.code = code; } - public static JournalContent getJournalContentType(SyncDataType dataType) - { + public static JournalContent getJournalContentType(SyncDataType dataType) { return JournalContent.getType(dataType.code); } - public static SyncDataType getDataType(byte code) - { + public static SyncDataType getDataType(byte code) { if (code == JournalBindings.code) return JournalBindings; if (code == JournalMessages.code) @@ -69,44 +65,39 @@ public class ReplicationStartSyncMessage extends PacketImpl } } - public ReplicationStartSyncMessage() - { + public ReplicationStartSyncMessage() { super(REPLICATION_START_FINISH_SYNC); } - public ReplicationStartSyncMessage(List filenames) - { + public ReplicationStartSyncMessage(List filenames) { this(); ids = new long[filenames.size()]; - for (int i = 0; i < filenames.size(); i++) - { + for (int i = 0; i < filenames.size(); i++) { ids[i] = filenames.get(i); } dataType = SyncDataType.LargeMessages; nodeID = ""; // this value will be ignored } - public ReplicationStartSyncMessage(String nodeID) - { + public ReplicationStartSyncMessage(String nodeID) { this(); synchronizationIsFinished = true; this.nodeID = nodeID; } - public ReplicationStartSyncMessage(JournalFile[] datafiles, JournalContent contentType, String nodeID, - boolean allowsAutoFailBack) - { + public ReplicationStartSyncMessage(JournalFile[] datafiles, + JournalContent contentType, + String nodeID, + boolean allowsAutoFailBack) { this(); this.nodeID = nodeID; this.allowsAutoFailBack = allowsAutoFailBack; synchronizationIsFinished = false; ids = new long[datafiles.length]; - for (int i = 0; i < datafiles.length; i++) - { + for (int i = 0; i < datafiles.length; i++) { ids[i] = datafiles[i].getFileID(); } - switch (contentType) - { + switch (contentType) { case MESSAGES: dataType = SyncDataType.JournalMessages; break; @@ -119,8 +110,7 @@ public class ReplicationStartSyncMessage extends PacketImpl } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeBoolean(synchronizationIsFinished); buffer.writeBoolean(allowsAutoFailBack); buffer.writeString(nodeID); @@ -128,27 +118,23 @@ public class ReplicationStartSyncMessage extends PacketImpl return; buffer.writeByte(dataType.code); buffer.writeInt(ids.length); - for (long id : ids) - { + for (long id : ids) { buffer.writeLong(id); } } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { synchronizationIsFinished = buffer.readBoolean(); allowsAutoFailBack = buffer.readBoolean(); nodeID = buffer.readString(); - if (synchronizationIsFinished) - { + if (synchronizationIsFinished) { return; } dataType = SyncDataType.getDataType(buffer.readByte()); int length = buffer.readInt(); ids = new long[length]; - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { ids[i] = buffer.readLong(); } } @@ -156,37 +142,32 @@ public class ReplicationStartSyncMessage extends PacketImpl /** * @return whether the server is configured to allow for fail-back */ - public boolean isServerToFailBack() - { + public boolean isServerToFailBack() { return allowsAutoFailBack; } + /** * @return {@code true} if the live has finished synchronizing its data and the backup is - * therefore up-to-date, {@code false} otherwise. + * therefore up-to-date, {@code false} otherwise. */ - public boolean isSynchronizationFinished() - { + public boolean isSynchronizationFinished() { return synchronizationIsFinished; } - public SyncDataType getDataType() - { + public SyncDataType getDataType() { return dataType; } - public long[] getFileIds() - { + public long[] getFileIds() { return ids; } - public String getNodeID() - { + public String getNodeID() { return nodeID; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (allowsAutoFailBack ? 1231 : 1237); @@ -198,23 +179,21 @@ public class ReplicationStartSyncMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof ReplicationStartSyncMessage)) return false; - ReplicationStartSyncMessage other = (ReplicationStartSyncMessage)obj; + ReplicationStartSyncMessage other = (ReplicationStartSyncMessage) obj; if (allowsAutoFailBack != other.allowsAutoFailBack) return false; if (dataType != other.dataType) return false; if (!Arrays.equals(ids, other.ids)) return false; - if (nodeID == null) - { + if (nodeID == null) { if (other.nodeID != null) return false; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationSyncFileMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationSyncFileMessage.java index 35f5a1052f..6c3007ce77 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationSyncFileMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ReplicationSyncFileMessage.java @@ -30,8 +30,7 @@ import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; * Message is used to sync {@link org.apache.activemq.artemis.core.journal.SequentialFile}s to a backup server. The {@link FileType} controls * which extra information is sent. */ -public final class ReplicationSyncFileMessage extends PacketImpl -{ +public final class ReplicationSyncFileMessage extends PacketImpl { /** * The JournalType or {@code null} if sync'ing large-messages. @@ -47,26 +46,23 @@ public final class ReplicationSyncFileMessage extends PacketImpl private byte[] byteArray; private SimpleString pageStoreName; private FileType fileType; - public enum FileType - { + + public enum FileType { JOURNAL(0), PAGE(1), LARGE_MESSAGE(2); private byte code; private static final Set ALL_OF = EnumSet.allOf(FileType.class); - private FileType(int code) - { - this.code = (byte)code; + private FileType(int code) { + this.code = (byte) code; } /** * @param readByte * @return {@link FileType} corresponding to the byte code. */ - public static FileType getFileType(byte readByte) - { - for (FileType type : ALL_OF) - { + public static FileType getFileType(byte readByte) { + for (FileType type : ALL_OF) { if (type.code == readByte) return type; } @@ -74,14 +70,15 @@ public final class ReplicationSyncFileMessage extends PacketImpl } } - public ReplicationSyncFileMessage() - { + public ReplicationSyncFileMessage() { super(REPLICATION_SYNC_FILE); } - public ReplicationSyncFileMessage(JournalContent content, SimpleString storeName, long id, int size, - ByteBuffer buffer) - { + public ReplicationSyncFileMessage(JournalContent content, + SimpleString storeName, + long id, + int size, + ByteBuffer buffer) { this(); this.byteBuffer = buffer; this.pageStoreName = storeName; @@ -91,38 +88,30 @@ public final class ReplicationSyncFileMessage extends PacketImpl determineType(); } - private void determineType() - { - if (journalType != null) - { + private void determineType() { + if (journalType != null) { fileType = FileType.JOURNAL; } - else if (pageStoreName != null) - { + else if (pageStoreName != null) { fileType = FileType.PAGE; } - else - { + else { fileType = FileType.LARGE_MESSAGE; } } @Override - public void encodeRest(final ActiveMQBuffer buffer) - { + public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeLong(fileId); if (fileId == -1) return; buffer.writeByte(fileType.code); - switch (fileType) - { - case JOURNAL: - { + switch (fileType) { + case JOURNAL: { buffer.writeByte(journalType.typeByte); break; } - case PAGE: - { + case PAGE: { buffer.writeSimpleString(pageStoreName); break; } @@ -136,78 +125,65 @@ public final class ReplicationSyncFileMessage extends PacketImpl * sending -1 will close the file in case of a journal, but not in case of a largeMessage * (which might receive appends) */ - if (dataSize > 0) - { + if (dataSize > 0) { buffer.writeBytes(byteBuffer); } } @Override - public void decodeRest(final ActiveMQBuffer buffer) - { + public void decodeRest(final ActiveMQBuffer buffer) { fileId = buffer.readLong(); - switch (FileType.getFileType(buffer.readByte())) - { - case JOURNAL: - { + switch (FileType.getFileType(buffer.readByte())) { + case JOURNAL: { journalType = JournalContent.getType(buffer.readByte()); fileType = FileType.JOURNAL; break; } - case PAGE: - { + case PAGE: { pageStoreName = buffer.readSimpleString(); fileType = FileType.PAGE; break; } - case LARGE_MESSAGE: - { + case LARGE_MESSAGE: { fileType = FileType.LARGE_MESSAGE; break; } } int size = buffer.readInt(); - if (size > 0) - { + if (size > 0) { byteArray = new byte[size]; buffer.readBytes(byteArray); } } - public long getId() - { + public long getId() { return fileId; } - public JournalContent getJournalContent() - { + public JournalContent getJournalContent() { return journalType; } - public byte[] getData() - { + public byte[] getData() { return byteArray; } - public FileType getFileType() - { + public FileType getFileType() { return fileType; } - public SimpleString getPageStore() - { + public SimpleString getPageStore() { return pageStoreName; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + Arrays.hashCode(byteArray); result = prime * result + ((byteBuffer == null) ? 0 : byteBuffer.hashCode()); result = prime * result + dataSize; - result = prime * result + (int)(fileId ^ (fileId >>> 32)); + result = prime * result + (int) (fileId ^ (fileId >>> 32)); result = prime * result + ((fileType == null) ? 0 : fileType.hashCode()); result = prime * result + ((journalType == null) ? 0 : journalType.hashCode()); result = prime * result + ((pageStoreName == null) ? 0 : pageStoreName.hashCode()); @@ -215,70 +191,54 @@ public final class ReplicationSyncFileMessage extends PacketImpl } @Override - public boolean equals(Object obj) - { - if (this == obj) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if (!super.equals(obj)) - { + if (!super.equals(obj)) { return false; } - if (!(obj instanceof ReplicationSyncFileMessage)) - { + if (!(obj instanceof ReplicationSyncFileMessage)) { return false; } - ReplicationSyncFileMessage other = (ReplicationSyncFileMessage)obj; - if (!Arrays.equals(byteArray, other.byteArray)) - { + ReplicationSyncFileMessage other = (ReplicationSyncFileMessage) obj; + if (!Arrays.equals(byteArray, other.byteArray)) { return false; } - if (byteBuffer == null) - { - if (other.byteBuffer != null) - { + if (byteBuffer == null) { + if (other.byteBuffer != null) { return false; } } - else if (!byteBuffer.equals(other.byteBuffer)) - { + else if (!byteBuffer.equals(other.byteBuffer)) { return false; } - if (dataSize != other.dataSize) - { + if (dataSize != other.dataSize) { return false; } - if (fileId != other.fileId) - { + if (fileId != other.fileId) { return false; } - if (fileType != other.fileType) - { + if (fileType != other.fileType) { return false; } - if (journalType != other.journalType) - { + if (journalType != other.journalType) { return false; } - if (pageStoreName == null) - { - if (other.pageStoreName != null) - { + if (pageStoreName == null) { + if (other.pageStoreName != null) { return false; } } - else if (!pageStoreName.equals(other.pageStoreName)) - { + else if (!pageStoreName.equals(other.pageStoreName)) { return false; } return true; } @Override - public String toString() - { + public String toString() { return ReplicationSyncFileMessage.class.getSimpleName() + "(" + fileType + - (journalType != null ? ", " + journalType : "") + ", id=" + fileId + ")"; + (journalType != null ? ", " + journalType : "") + ", id=" + fileId + ")"; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ScaleDownAnnounceMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ScaleDownAnnounceMessage.java index 81de3c19c4..7a6f147e3e 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ScaleDownAnnounceMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ScaleDownAnnounceMessage.java @@ -20,44 +20,38 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; -public class ScaleDownAnnounceMessage extends PacketImpl -{ +public class ScaleDownAnnounceMessage extends PacketImpl { + private SimpleString targetNodeId; private SimpleString scaledDownNodeId; - public ScaleDownAnnounceMessage() - { + public ScaleDownAnnounceMessage() { super(SCALEDOWN_ANNOUNCEMENT); } - public ScaleDownAnnounceMessage(SimpleString targetNodeId, SimpleString scaledDownNodeId) - { + public ScaleDownAnnounceMessage(SimpleString targetNodeId, SimpleString scaledDownNodeId) { super(SCALEDOWN_ANNOUNCEMENT); this.targetNodeId = targetNodeId; this.scaledDownNodeId = scaledDownNodeId; } @Override - public void encodeRest(ActiveMQBuffer buffer) - { + public void encodeRest(ActiveMQBuffer buffer) { buffer.writeSimpleString(targetNodeId); buffer.writeSimpleString(scaledDownNodeId); } @Override - public void decodeRest(ActiveMQBuffer buffer) - { + public void decodeRest(ActiveMQBuffer buffer) { targetNodeId = buffer.readSimpleString(); scaledDownNodeId = buffer.readSimpleString(); } - public SimpleString getTargetNodeId() - { + public SimpleString getTargetNodeId() { return targetNodeId; } - public SimpleString getScaledDownNodeId() - { + public SimpleString getScaledDownNodeId() { return scaledDownNodeId; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/WebSocketServerHandler.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/WebSocketServerHandler.java index 8f9764efec..92493feabe 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/WebSocketServerHandler.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/WebSocketServerHandler.java @@ -45,65 +45,52 @@ import static io.netty.handler.codec.http.HttpMethod.GET; import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; -public class WebSocketServerHandler extends SimpleChannelInboundHandler -{ +public class WebSocketServerHandler extends SimpleChannelInboundHandler { + private static final String WEBSOCKET_PATH = "/stomp"; private WebSocketServerHandshaker handshaker; private static final BinaryWebSocketEncoder BINARY_WEBSOCKET_ENCODER = new BinaryWebSocketEncoder(); @Override - public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception - { - if (msg instanceof FullHttpRequest) - { + public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { + if (msg instanceof FullHttpRequest) { handleHttpRequest(ctx, (FullHttpRequest) msg); } - else if (msg instanceof WebSocketFrame) - { + else if (msg instanceof WebSocketFrame) { WebSocketFrame frame = (WebSocketFrame) msg; boolean handle = handleWebSocketFrame(ctx, frame); - if (handle) - { + if (handle) { ctx.fireChannelRead(frame.content().retain()); } } } - private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception - { + private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { // Allow only GET methods. - if (req.getMethod() != GET) - { + if (req.getMethod() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } // Handshake - WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( - this.getWebSocketLocation(req), "v10.stomp,v11.stomp", false); + WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(this.getWebSocketLocation(req), "v10.stomp,v11.stomp", false); this.handshaker = wsFactory.newHandshaker(req); - if (this.handshaker == null) - { + if (this.handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel()); } - else - { + else { ChannelFuture handshake = this.handshaker.handshake(ctx.channel(), req); - handshake.addListener(new ChannelFutureListener() - { + handshake.addListener(new ChannelFutureListener() { @Override - public void operationComplete(ChannelFuture future) throws Exception - { - if (future.isSuccess()) - { + public void operationComplete(ChannelFuture future) throws Exception { + if (future.isSuccess()) { // we need to insert an encoder that takes the underlying ChannelBuffer of a StompFrame.toActiveMQBuffer and // wrap it in a binary web socket frame before letting the wsencoder send it on the wire future.channel().pipeline().addAfter("wsencoder", "binary-websocket-encoder", BINARY_WEBSOCKET_ENCODER); } - else - { + else { // Handshake failed, fire an exceptionCaught event future.channel().pipeline().fireExceptionCaught(future.cause()); } @@ -112,66 +99,53 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler } } - private boolean handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) - { + private boolean handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // Check for closing frame - if (frame instanceof CloseWebSocketFrame) - { + if (frame instanceof CloseWebSocketFrame) { this.handshaker.close(ctx.channel(), ((CloseWebSocketFrame) frame).retain()); return false; } - else if (frame instanceof PingWebSocketFrame) - { + else if (frame instanceof PingWebSocketFrame) { ctx.writeAndFlush(new PongWebSocketFrame(frame.content().retain())); return false; } - else if (!(frame instanceof TextWebSocketFrame)) - { - throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass() - .getName())); + else if (!(frame instanceof TextWebSocketFrame)) { + throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName())); } return true; } - private void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, FullHttpResponse res) - { + private void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, FullHttpResponse res) { // Generate an error page if response status code is not OK (200). - if (res.getStatus().code() != 200) - { + if (res.getStatus().code() != 200) { res.content().writeBytes(res.getStatus().toString().getBytes(StandardCharsets.UTF_8)); setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.writeAndFlush(res); - if (!isKeepAlive(req) || res.getStatus().code() != 200) - { + if (!isKeepAlive(req) || res.getStatus().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } } @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception - { + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } - private String getWebSocketLocation(HttpRequest req) - { + private String getWebSocketLocation(HttpRequest req) { return "ws://" + req.headers().get(HttpHeaders.Names.HOST) + WEBSOCKET_PATH; } @Sharable - private static final class BinaryWebSocketEncoder extends ChannelOutboundHandlerAdapter - { + private static final class BinaryWebSocketEncoder extends ChannelOutboundHandlerAdapter { @Override - public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception - { - if (msg instanceof ByteBuf) - { + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + if (msg instanceof ByteBuf) { msg = new BinaryWebSocketFrame((ByteBuf) msg); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/registry/JndiBindingRegistry.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/registry/JndiBindingRegistry.java index 81426aebbd..f81c4bd879 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/registry/JndiBindingRegistry.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/registry/JndiBindingRegistry.java @@ -23,105 +23,80 @@ import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; -public class JndiBindingRegistry implements BindingRegistry -{ +public class JndiBindingRegistry implements BindingRegistry { + private Context context; - public JndiBindingRegistry(Context context) - { + public JndiBindingRegistry(Context context) { this.context = context; } - public JndiBindingRegistry() throws Exception - { + public JndiBindingRegistry() throws Exception { this.context = new InitialContext(); } - public Object lookup(String name) - { - try - { - if (context == null) - { + public Object lookup(String name) { + try { + if (context == null) { return null; } - else - { + else { return context.lookup(name); } } - catch (NamingException e) - { + catch (NamingException e) { return null; } } - public boolean bind(String name, Object obj) - { - try - { + public boolean bind(String name, Object obj) { + try { return bindToJndi(name, obj); } - catch (NamingException e) - { + catch (NamingException e) { throw new RuntimeException(e); } } - public void unbind(String name) - { - try - { - if (context != null) - { + public void unbind(String name) { + try { + if (context != null) { context.unbind(name); } } - catch (NamingException e) - { + catch (NamingException e) { } } - public void close() - { - try - { - if (context != null) - { + public void close() { + try { + if (context != null) { context.close(); } } - catch (NamingException e) - { + catch (NamingException e) { } } - - private boolean bindToJndi(final String jndiName, final Object objectToBind) throws NamingException - { - if (context != null) - { + private boolean bindToJndi(final String jndiName, final Object objectToBind) throws NamingException { + if (context != null) { String parentContext; String jndiNameInContext; int sepIndex = jndiName.lastIndexOf('/'); - if (sepIndex == -1) - { + if (sepIndex == -1) { parentContext = ""; } - else - { + else { parentContext = jndiName.substring(0, sepIndex); } jndiNameInContext = jndiName.substring(sepIndex + 1); - try - { + try { context.lookup(jndiName); //JMSServerManagerImpl.log.warn("Binding for " + jndiName + " already exists"); return false; } - catch (Throwable e) - { + catch (Throwable e) { // OK } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/registry/MapBindingRegistry.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/registry/MapBindingRegistry.java index cfbe491f51..d06d267e87 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/registry/MapBindingRegistry.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/registry/MapBindingRegistry.java @@ -21,26 +21,22 @@ import java.util.concurrent.ConcurrentMap; import org.apache.activemq.artemis.spi.core.naming.BindingRegistry; -public class MapBindingRegistry implements BindingRegistry -{ +public class MapBindingRegistry implements BindingRegistry { + protected ConcurrentMap registry = new ConcurrentHashMap(); - public Object lookup(String name) - { + public Object lookup(String name) { return registry.get(name); } - public boolean bind(String name, Object obj) - { + public boolean bind(String name, Object obj) { return registry.putIfAbsent(name, obj) == null; } - public void unbind(String name) - { + public void unbind(String name) { registry.remove(name); } - public void close() - { + public void close() { } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/InVMAcceptor.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/InVMAcceptor.java index 807a0adf28..a6033653e8 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/InVMAcceptor.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/InVMAcceptor.java @@ -40,8 +40,8 @@ import org.apache.activemq.artemis.utils.ExecutorFactory; import org.apache.activemq.artemis.utils.OrderedExecutorFactory; import org.apache.activemq.artemis.utils.TypedProperties; -public final class InVMAcceptor implements Acceptor -{ +public final class InVMAcceptor implements Acceptor { + private final int id; private final BufferHandler handler; @@ -70,8 +70,7 @@ public final class InVMAcceptor implements Acceptor final Map configuration, final BufferHandler handler, final ConnectionLifeCycleListener listener, - final Executor threadPool) - { + final Executor threadPool) { this.clusterConnection = clusterConnection; this.configuration = configuration; @@ -84,45 +83,35 @@ public final class InVMAcceptor implements Acceptor executorFactory = new OrderedExecutorFactory(threadPool); - connectionsAllowed = ConfigurationHelper.getLongProperty(TransportConstants.CONNECTIONS_ALLOWED, - TransportConstants.DEFAULT_CONNECTIONS_ALLOWED, - configuration); + connectionsAllowed = ConfigurationHelper.getLongProperty(TransportConstants.CONNECTIONS_ALLOWED, TransportConstants.DEFAULT_CONNECTIONS_ALLOWED, configuration); } - public Map getConfiguration() - { + public Map getConfiguration() { return configuration; } - public ClusterConnection getClusterConnection() - { + public ClusterConnection getClusterConnection() { return clusterConnection; } - public long getConnectionsAllowed() - { + public long getConnectionsAllowed() { return connectionsAllowed; } - public int getConnectionCount() - { + public int getConnectionCount() { return connections.size(); } - public synchronized void start() throws Exception - { - if (started) - { + public synchronized void start() throws Exception { + if (started) { return; } InVMRegistry.instance.registerAcceptor(id, this); - if (notificationService != null) - { + if (notificationService != null) { TypedProperties props = new TypedProperties(); - props.putSimpleStringProperty(new SimpleString("factory"), - new SimpleString(InVMAcceptorFactory.class.getName())); + props.putSimpleStringProperty(new SimpleString("factory"), new SimpleString(InVMAcceptorFactory.class.getName())); props.putIntProperty(new SimpleString("id"), id); Notification notification = new Notification(null, CoreNotificationType.ACCEPTOR_STARTED, props); notificationService.sendNotification(notification); @@ -133,38 +122,30 @@ public final class InVMAcceptor implements Acceptor paused = false; } - public synchronized void stop() - { - if (!started) - { + public synchronized void stop() { + if (!started) { return; } - if (!paused) - { + if (!paused) { InVMRegistry.instance.unregisterAcceptor(id); } - for (Connection connection : connections.values()) - { + for (Connection connection : connections.values()) { listener.connectionDestroyed(connection.getID()); } connections.clear(); - if (notificationService != null) - { + if (notificationService != null) { TypedProperties props = new TypedProperties(); - props.putSimpleStringProperty(new SimpleString("factory"), - new SimpleString(InVMAcceptorFactory.class.getName())); + props.putSimpleStringProperty(new SimpleString("factory"), new SimpleString(InVMAcceptorFactory.class.getName())); props.putIntProperty(new SimpleString("id"), id); Notification notification = new Notification(null, CoreNotificationType.ACCEPTOR_STOPPED, props); - try - { + try { notificationService.sendNotification(notification); } - catch (Exception e) - { + catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } @@ -175,18 +156,15 @@ public final class InVMAcceptor implements Acceptor paused = false; } - public synchronized boolean isStarted() - { + public synchronized boolean isStarted() { return started; } /* * Stop accepting new connections */ - public synchronized void pause() - { - if (!started || paused) - { + public synchronized void pause() { + if (!started || paused) { return; } @@ -195,33 +173,27 @@ public final class InVMAcceptor implements Acceptor paused = true; } - public synchronized void setNotificationService(final NotificationService notificationService) - { + public synchronized void setNotificationService(final NotificationService notificationService) { this.notificationService = notificationService; } - public BufferHandler getHandler() - { - if (!started) - { + public BufferHandler getHandler() { + if (!started) { throw new IllegalStateException("Acceptor is not started"); } return handler; } - public ExecutorFactory getExecutorFactory() - { + public ExecutorFactory getExecutorFactory() { return executorFactory; } public void connect(final String connectionID, final BufferHandler remoteHandler, final InVMConnector connector, - final Executor clientExecutor) - { - if (!started) - { + final Executor clientExecutor) { + if (!started) { throw new IllegalStateException("Acceptor is not started"); } @@ -232,17 +204,14 @@ public final class InVMAcceptor implements Acceptor connectionListener.connectionCreated(this, inVMConnection, ActiveMQClient.DEFAULT_CORE_PROTOCOL); } - public void disconnect(final String connectionID) - { - if (!started) - { + public void disconnect(final String connectionID) { + if (!started) { return; } Connection conn = connections.get(connectionID); - if (conn != null) - { + if (conn != null) { conn.close(); } } @@ -252,51 +221,43 @@ public final class InVMAcceptor implements Acceptor * * @return true */ - public boolean isUnsecurable() - { + public boolean isUnsecurable() { return true; } - public void setDefaultActiveMQPrincipal(ActiveMQPrincipal defaultActiveMQPrincipal) - { + public void setDefaultActiveMQPrincipal(ActiveMQPrincipal defaultActiveMQPrincipal) { this.defaultActiveMQPrincipal = defaultActiveMQPrincipal; } - private class Listener implements ConnectionLifeCycleListener - { + private class Listener implements ConnectionLifeCycleListener { //private static Listener instance = new Listener(); private final InVMConnector connector; - Listener(final InVMConnector connector) - { + Listener(final InVMConnector connector) { this.connector = connector; } - public void connectionCreated(final ActiveMQComponent component, final Connection connection, final String protocol) - { - if (connections.putIfAbsent((String) connection.getID(), connection) != null) - { + public void connectionCreated(final ActiveMQComponent component, + final Connection connection, + final String protocol) { + if (connections.putIfAbsent((String) connection.getID(), connection) != null) { throw ActiveMQMessageBundle.BUNDLE.connectionExists(connection.getID()); } listener.connectionCreated(component, connection, protocol); } - public void connectionDestroyed(final Object connectionID) - { + public void connectionDestroyed(final Object connectionID) { InVMConnection connection = (InVMConnection) connections.remove(connectionID); - if (connection != null) - { + if (connection != null) { listener.connectionDestroyed(connectionID); // Execute on different thread after all the packets are sent, to avoid deadlocks - connection.getExecutor().execute(new Runnable() - { - public void run() - { + connection.getExecutor().execute(new Runnable() { + public void run() { // Remove on the other side too connector.disconnect((String) connectionID); } @@ -304,13 +265,11 @@ public final class InVMAcceptor implements Acceptor } } - public void connectionException(final Object connectionID, final ActiveMQException me) - { + public void connectionException(final Object connectionID, final ActiveMQException me) { listener.connectionException(connectionID, me); } - public void connectionReadyForWrites(Object connectionID, boolean ready) - { + public void connectionReadyForWrites(Object connectionID, boolean ready) { } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/InVMAcceptorFactory.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/InVMAcceptorFactory.java index 3a4f99da60..e227bcea9d 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/InVMAcceptorFactory.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/InVMAcceptorFactory.java @@ -27,8 +27,8 @@ import org.apache.activemq.artemis.spi.core.remoting.AcceptorFactory; import org.apache.activemq.artemis.spi.core.remoting.BufferHandler; import org.apache.activemq.artemis.spi.core.remoting.ConnectionLifeCycleListener; -public class InVMAcceptorFactory implements AcceptorFactory -{ +public class InVMAcceptorFactory implements AcceptorFactory { + public Acceptor createAcceptor(final String name, final ClusterConnection clusterConnection, final Map configuration, @@ -36,8 +36,7 @@ public class InVMAcceptorFactory implements AcceptorFactory final ConnectionLifeCycleListener listener, final Executor threadPool, final ScheduledExecutorService scheduledThreadPool, - final Map protocolHandler) - { + final Map protocolHandler) { return new InVMAcceptor(clusterConnection, configuration, handler, listener, threadPool); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/InVMConnection.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/InVMConnection.java index 893acb87fe..0205141ca7 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/InVMConnection.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/InVMConnection.java @@ -37,8 +37,8 @@ import org.apache.activemq.artemis.spi.core.remoting.ConnectionLifeCycleListener import org.apache.activemq.artemis.spi.core.remoting.ReadyListener; import org.apache.activemq.artemis.utils.UUIDGenerator; -public class InVMConnection implements Connection -{ +public class InVMConnection implements Connection { + private static final boolean isTrace = ActiveMQServerLogger.LOGGER.isTraceEnabled(); private final BufferHandler handler; @@ -65,8 +65,7 @@ public class InVMConnection implements Connection public InVMConnection(final int serverID, final BufferHandler handler, final ConnectionLifeCycleListener listener, - final Executor executor) - { + final Executor executor) { this(serverID, UUIDGenerator.getInstance().generateSimpleStringUUID().toString(), handler, listener, executor); } @@ -74,8 +73,7 @@ public class InVMConnection implements Connection final String id, final BufferHandler handler, final ConnectionLifeCycleListener listener, - final Executor executor) - { + final Executor executor) { this(serverID, id, handler, listener, executor, null); } @@ -84,8 +82,7 @@ public class InVMConnection implements Connection final BufferHandler handler, final ConnectionLifeCycleListener listener, final Executor executor, - final ActiveMQPrincipal defaultActiveMQPrincipal) - { + final ActiveMQPrincipal defaultActiveMQPrincipal) { this.serverID = serverID; this.handler = handler; @@ -99,37 +96,27 @@ public class InVMConnection implements Connection this.defaultActiveMQPrincipal = defaultActiveMQPrincipal; } - - public void forceClose() - { + public void forceClose() { // no op } - public RemotingConnection getProtocolConnection() - { + public RemotingConnection getProtocolConnection() { return this.protocolConnection; } - public void setProtocolConnection(RemotingConnection connection) - { + public void setProtocolConnection(RemotingConnection connection) { this.protocolConnection = connection; } - - - public void close() - { - if (closing) - { + public void close() { + if (closing) { return; } closing = true; - synchronized (this) - { - if (!closed) - { + synchronized (this) { + if (!closed) { listener.connectionDestroyed(id); closed = true; @@ -137,149 +124,119 @@ public class InVMConnection implements Connection } } - public ActiveMQBuffer createTransportBuffer(final int size) - { + public ActiveMQBuffer createTransportBuffer(final int size) { return ActiveMQBuffers.dynamicBuffer(size); } - public Object getID() - { + public Object getID() { return id; } - public void checkFlushBatchBuffer() - { + public void checkFlushBatchBuffer() { } - public void write(final ActiveMQBuffer buffer) - { + public void write(final ActiveMQBuffer buffer) { write(buffer, false, false, null); } - public void write(final ActiveMQBuffer buffer, final boolean flush, final boolean batch) - { + public void write(final ActiveMQBuffer buffer, final boolean flush, final boolean batch) { write(buffer, flush, batch, null); } - public void write(final ActiveMQBuffer buffer, final boolean flush, final boolean batch, final ChannelFutureListener futureListener) - { + public void write(final ActiveMQBuffer buffer, + final boolean flush, + final boolean batch, + final ChannelFutureListener futureListener) { final ActiveMQBuffer copied = buffer.copy(0, buffer.capacity()); copied.setIndex(buffer.readerIndex(), buffer.writerIndex()); - try - { - executor.execute(new Runnable() - { - public void run() - { - try - { - if (!closed) - { + try { + executor.execute(new Runnable() { + public void run() { + try { + if (!closed) { copied.readInt(); // read and discard - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace(InVMConnection.this + "::Sending inVM packet"); } handler.bufferReceived(id, copied); - if (futureListener != null) - { - // TODO BEFORE MERGE: (is null a good option here?) + if (futureListener != null) { + // TODO BEFORE MERGE: (is null a good option here?) futureListener.operationComplete(null); } } } - catch (Exception e) - { + catch (Exception e) { final String msg = "Failed to write to handler on connector " + this; ActiveMQServerLogger.LOGGER.errorWritingToInvmConnector(e, this); throw new IllegalStateException(msg, e); } - finally - { - if (isTrace) - { + finally { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace(InVMConnection.this + "::packet sent done"); } } } }); - if (flush && flushEnabled) - { + if (flush && flushEnabled) { final CountDownLatch latch = new CountDownLatch(1); - executor.execute(new Runnable() - { - public void run() - { + executor.execute(new Runnable() { + public void run() { latch.countDown(); } }); - try - { - if (!latch.await(10, TimeUnit.SECONDS)) - { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { ActiveMQServerLogger.LOGGER.timedOutFlushingInvmChannel(); } } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } } } - catch (RejectedExecutionException e) - { + catch (RejectedExecutionException e) { // Ignore - this can happen if server/client is shutdown and another request comes in } } - public String getRemoteAddress() - { + public String getRemoteAddress() { return "invm:" + serverID; } - public int getBatchingBufferSize() - { + public int getBatchingBufferSize() { return -1; } - public void addReadyListener(ReadyListener listener) - { + public void addReadyListener(ReadyListener listener) { } - public void removeReadyListener(ReadyListener listener) - { + public void removeReadyListener(ReadyListener listener) { } @Override - public boolean isUsingProtocolHandling() - { + public boolean isUsingProtocolHandling() { return false; } - public ActiveMQPrincipal getDefaultActiveMQPrincipal() - { + public ActiveMQPrincipal getDefaultActiveMQPrincipal() { return defaultActiveMQPrincipal; } - public static void setFlushEnabled(boolean enable) - { + public static void setFlushEnabled(boolean enable) { flushEnabled = enable; } - public Executor getExecutor() - { + public Executor getExecutor() { return executor; } - @Override - public TransportConfiguration getConnectorConfig() - { + public TransportConfiguration getConnectorConfig() { Map params = new HashMap(); params.put(org.apache.activemq.artemis.core.remoting.impl.invm.TransportConstants.SERVER_ID_PROP_NAME, serverID); @@ -288,10 +245,8 @@ public class InVMConnection implements Connection } @Override - public String toString() - { + public String toString() { return "InVMConnection [serverID=" + serverID + ", id=" + id + "]"; } - } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/InVMConnector.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/InVMConnector.java index 3625ffe76d..a6b819adcb 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/InVMConnector.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/InVMConnector.java @@ -36,13 +36,12 @@ import org.apache.activemq.artemis.spi.core.remoting.ConnectionLifeCycleListener import org.apache.activemq.artemis.utils.ConfigurationHelper; import org.apache.activemq.artemis.utils.OrderedExecutorFactory; -public class InVMConnector extends AbstractConnector -{ +public class InVMConnector extends AbstractConnector { + public static final Map DEFAULT_CONFIG; - static - { - Map config = new HashMap(); + static { + Map config = new HashMap(); config.put(TransportConstants.SERVER_ID_PROP_NAME, TransportConstants.DEFAULT_SERVER_ID); DEFAULT_CONFIG = Collections.unmodifiableMap(config); } @@ -54,18 +53,15 @@ public class InVMConnector extends AbstractConnector private static volatile int failures; - public static synchronized void resetFailures() - { + public static synchronized void resetFailures() { InVMConnector.failures = 0; InVMConnector.failOnCreateConnection = false; InVMConnector.numberOfFailures = -1; } - private static synchronized void incFailures() - { + private static synchronized void incFailures() { InVMConnector.failures++; - if (InVMConnector.failures == InVMConnector.numberOfFailures) - { + if (InVMConnector.failures == InVMConnector.numberOfFailures) { InVMConnector.resetFailures(); } } @@ -93,8 +89,7 @@ public class InVMConnector extends AbstractConnector final ConnectionLifeCycleListener listener, final Executor closeExecutor, final Executor threadPool, - ClientProtocolManager protocolManager) - { + ClientProtocolManager protocolManager) { super(configuration); this.listener = listener; @@ -113,35 +108,28 @@ public class InVMConnector extends AbstractConnector this.protocolManager = protocolManager; } - public Acceptor getAcceptor() - { + public Acceptor getAcceptor() { return acceptor; } - public synchronized void close() - { - if (!started) - { + public synchronized void close() { + if (!started) { return; } - for (Connection connection : connections.values()) - { + for (Connection connection : connections.values()) { listener.connectionDestroyed(connection.getID()); } started = false; } - public boolean isStarted() - { + public boolean isStarted() { return started; } - public Connection createConnection() - { - if (InVMConnector.failOnCreateConnection) - { + public Connection createConnection() { + if (InVMConnector.failOnCreateConnection) { InVMConnector.incFailures(); ActiveMQServerLogger.LOGGER.debug("Returning null on InVMConnector for tests"); @@ -149,49 +137,40 @@ public class InVMConnector extends AbstractConnector return null; } - if (acceptor == null) - { + if (acceptor == null) { return null; } - if (acceptor.getConnectionsAllowed() == -1 || acceptor.getConnectionCount() < acceptor.getConnectionsAllowed()) - { + if (acceptor.getConnectionsAllowed() == -1 || acceptor.getConnectionCount() < acceptor.getConnectionsAllowed()) { Connection conn = internalCreateConnection(acceptor.getHandler(), new Listener(), acceptor.getExecutorFactory().getExecutor()); acceptor.connect((String) conn.getID(), handler, this, executorFactory.getExecutor()); return conn; } - else - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + else { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug(new StringBuilder().append("Connection limit of ").append(acceptor.getConnectionsAllowed()).append(" reached. Refusing connection.")); } return null; } } - public synchronized void start() - { + public synchronized void start() { started = true; } - public BufferHandler getHandler() - { + public BufferHandler getHandler() { return handler; } - public void disconnect(final String connectionID) - { - if (!started) - { + public void disconnect(final String connectionID) { + if (!started) { return; } Connection conn = connections.get(connectionID); - if (conn != null) - { + if (conn != null) { conn.close(); } } @@ -199,66 +178,54 @@ public class InVMConnector extends AbstractConnector // This may be an injection point for mocks on tests protected Connection internalCreateConnection(final BufferHandler handler, final ConnectionLifeCycleListener listener, - final Executor serverExecutor) - { + final Executor serverExecutor) { // No acceptor on a client connection InVMConnection inVMConnection = new InVMConnection(id, handler, listener, serverExecutor); listener.connectionCreated(null, inVMConnection, protocolManager.getName()); return inVMConnection; } - public boolean isEquivalent(Map configuration) - { - int serverId = ConfigurationHelper.getIntProperty(TransportConstants.SERVER_ID_PROP_NAME, - 0, - configuration); + public boolean isEquivalent(Map configuration) { + int serverId = ConfigurationHelper.getIntProperty(TransportConstants.SERVER_ID_PROP_NAME, 0, configuration); return id == serverId; } - private class Listener implements ConnectionLifeCycleListener - { - public void connectionCreated(final ActiveMQComponent component, final Connection connection, final String protocol) - { - if (connections.putIfAbsent((String)connection.getID(), connection) != null) - { + private class Listener implements ConnectionLifeCycleListener { + + public void connectionCreated(final ActiveMQComponent component, + final Connection connection, + final String protocol) { + if (connections.putIfAbsent((String) connection.getID(), connection) != null) { throw ActiveMQMessageBundle.BUNDLE.connectionExists(connection.getID()); } listener.connectionCreated(component, connection, protocol); } - public void connectionDestroyed(final Object connectionID) - { - if (connections.remove(connectionID) != null) - { + public void connectionDestroyed(final Object connectionID) { + if (connections.remove(connectionID) != null) { // Close the corresponding connection on the other side - acceptor.disconnect((String)connectionID); + acceptor.disconnect((String) connectionID); // Execute on different thread to avoid deadlocks - closeExecutor.execute(new Runnable() - { - public void run() - { + closeExecutor.execute(new Runnable() { + public void run() { listener.connectionDestroyed(connectionID); } }); } } - public void connectionException(final Object connectionID, final ActiveMQException me) - { + public void connectionException(final Object connectionID, final ActiveMQException me) { // Execute on different thread to avoid deadlocks - closeExecutor.execute(new Runnable() - { - public void run() - { + closeExecutor.execute(new Runnable() { + public void run() { listener.connectionException(connectionID, me); } }); } - public void connectionReadyForWrites(Object connectionID, boolean ready) - { + public void connectionReadyForWrites(Object connectionID, boolean ready) { } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/InVMConnectorFactory.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/InVMConnectorFactory.java index e261aeff5c..c22e2a6062 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/InVMConnectorFactory.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/InVMConnectorFactory.java @@ -26,30 +26,27 @@ import org.apache.activemq.artemis.spi.core.remoting.ConnectionLifeCycleListener import org.apache.activemq.artemis.spi.core.remoting.Connector; import org.apache.activemq.artemis.spi.core.remoting.ConnectorFactory; -public class InVMConnectorFactory implements ConnectorFactory -{ +public class InVMConnectorFactory implements ConnectorFactory { + public Connector createConnector(final Map configuration, final BufferHandler handler, final ConnectionLifeCycleListener listener, final Executor closeExecutor, final Executor threadPool, final ScheduledExecutorService scheduledThreadPool, - final ClientProtocolManager protocolManager) - { + final ClientProtocolManager protocolManager) { InVMConnector connector = new InVMConnector(configuration, handler, listener, closeExecutor, threadPool, protocolManager); return connector; } @Override - public boolean isReliable() - { + public boolean isReliable() { return true; } @Override - public Map getDefaults() - { + public Map getDefaults() { return InVMConnector.DEFAULT_CONFIG; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/InVMRegistry.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/InVMRegistry.java index 12705e635d..cdb0ee3932 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/InVMRegistry.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/InVMRegistry.java @@ -21,40 +21,33 @@ import org.apache.activemq.artemis.core.server.ActiveMQMessageBundle; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -public final class InVMRegistry -{ +public final class InVMRegistry { + public static final InVMRegistry instance = new InVMRegistry(); private final ConcurrentMap acceptors = new ConcurrentHashMap(); - public void registerAcceptor(final int id, final InVMAcceptor acceptor) - { - if (acceptors.putIfAbsent(id, acceptor) != null) - { + public void registerAcceptor(final int id, final InVMAcceptor acceptor) { + if (acceptors.putIfAbsent(id, acceptor) != null) { throw ActiveMQMessageBundle.BUNDLE.acceptorExists(id); } } - public void unregisterAcceptor(final int id) - { - if (acceptors.remove(id) == null) - { + public void unregisterAcceptor(final int id) { + if (acceptors.remove(id) == null) { throw ActiveMQMessageBundle.BUNDLE.acceptorNotExists(id); } } - public InVMAcceptor getAcceptor(final int id) - { + public InVMAcceptor getAcceptor(final int id) { return acceptors.get(id); } - public void clear() - { + public void clear() { acceptors.clear(); } - public int size() - { + public int size() { return acceptors.size(); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/TransportConstants.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/TransportConstants.java index 0447206997..f8a5117f5b 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/TransportConstants.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/invm/TransportConstants.java @@ -16,9 +16,8 @@ */ package org.apache.activemq.artemis.core.remoting.impl.invm; +public final class TransportConstants { -public final class TransportConstants -{ public static final String SERVER_ID_PROP_NAME = "serverId"; public static final int DEFAULT_SERVER_ID = 0; @@ -27,8 +26,7 @@ public final class TransportConstants public static final long DEFAULT_CONNECTIONS_ALLOWED = -1L; - private TransportConstants() - { + private TransportConstants() { // Utility class } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/ConnectionCreator.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/ConnectionCreator.java index 83178fbe49..6df028c9d1 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/ConnectionCreator.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/ConnectionCreator.java @@ -19,7 +19,9 @@ package org.apache.activemq.artemis.core.remoting.impl.netty; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; -public interface ConnectionCreator extends ChannelHandler -{ - NettyServerConnection createConnection(final ChannelHandlerContext ctx, String protocol, boolean httpEnabled) throws Exception; +public interface ConnectionCreator extends ChannelHandler { + + NettyServerConnection createConnection(final ChannelHandlerContext ctx, + String protocol, + boolean httpEnabled) throws Exception; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/HttpAcceptorHandler.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/HttpAcceptorHandler.java index ee05c7c43f..6e41505318 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/HttpAcceptorHandler.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/HttpAcceptorHandler.java @@ -41,8 +41,8 @@ import io.netty.util.ReferenceCountUtil; * Ensures that every request has a response and also that any uninitiated responses always wait for * a response. */ -public class HttpAcceptorHandler extends ChannelDuplexHandler -{ +public class HttpAcceptorHandler extends ChannelDuplexHandler { + private final BlockingQueue responses = new LinkedBlockingQueue(); private final BlockingQueue delayedResponses = new LinkedBlockingQueue(); @@ -55,8 +55,7 @@ public class HttpAcceptorHandler extends ChannelDuplexHandler private Channel channel; - public HttpAcceptorHandler(final HttpKeepAliveRunnable httpKeepAliveTask, final long responseTime, Channel channel) - { + public HttpAcceptorHandler(final HttpKeepAliveRunnable httpKeepAliveTask, final long responseTime, Channel channel) { super(); this.responseTime = responseTime; this.httpKeepAliveTask = httpKeepAliveTask; @@ -65,25 +64,21 @@ public class HttpAcceptorHandler extends ChannelDuplexHandler } @Override - public void channelInactive(final ChannelHandlerContext ctx) throws Exception - { + public void channelInactive(final ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); httpKeepAliveTask.unregisterKeepAliveHandler(this); channel = null; } @Override - public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception - { + public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception { FullHttpRequest request = (FullHttpRequest) msg; HttpMethod method = request.getMethod(); // if we are a post then we send upstream, otherwise we are just being prompted for a response. - if (method.equals(HttpMethod.POST ) ) - { + if (method.equals(HttpMethod.POST)) { ctx.fireChannelRead(ReferenceCountUtil.retain(((FullHttpRequest) msg).content())); // add a new response - responses.put(new ResponseHolder(System.currentTimeMillis() + responseTime, - new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK))); + responses.put(new ResponseHolder(System.currentTimeMillis() + responseTime, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK))); ReferenceCountUtil.release(msg); return; } @@ -91,36 +86,28 @@ public class HttpAcceptorHandler extends ChannelDuplexHandler } @Override - public void write(final ChannelHandlerContext ctx, final Object msg, ChannelPromise promise) throws Exception - { + public void write(final ChannelHandlerContext ctx, final Object msg, ChannelPromise promise) throws Exception { // we are either a channel buffer, which gets delayed until a response is available, or we are the actual response - if (msg instanceof ByteBuf) - { + if (msg instanceof ByteBuf) { executor.execute(new ResponseRunner((ByteBuf) msg, promise)); } - else - { + else { ctx.write(msg, promise); } } - public void keepAlive(final long time) - { + public void keepAlive(final long time) { // send some responses to catch up thus avoiding any timeout. int lateResponses = 0; - for (ResponseHolder response : responses) - { - if (response.timeReceived < time) - { + for (ResponseHolder response : responses) { + if (response.timeReceived < time) { lateResponses++; } - else - { + else { break; } } - for (int i = 0; i < lateResponses; i++) - { + for (int i = 0; i < lateResponses; i++) { executor.execute(new ResponseRunner()); } } @@ -128,54 +115,44 @@ public class HttpAcceptorHandler extends ChannelDuplexHandler /** * this is prompted to delivery when a response is available in the response queue. */ - final class ResponseRunner implements Runnable - { + final class ResponseRunner implements Runnable { + private final ByteBuf buffer; private final boolean bogusResponse; private final ChannelPromise promise; - public ResponseRunner(final ByteBuf buffer, ChannelPromise promise) - { + public ResponseRunner(final ByteBuf buffer, ChannelPromise promise) { this.buffer = buffer; bogusResponse = false; this.promise = promise; } - public ResponseRunner() - { + public ResponseRunner() { bogusResponse = true; buffer = Unpooled.buffer(0); promise = channel.newPromise(); } - public void run() - { + public void run() { ResponseHolder responseHolder = null; - do - { - try - { + do { + try { responseHolder = responses.take(); } - catch (InterruptedException e) - { + catch (InterruptedException e) { if (executor.isShutdown()) return; // otherwise ignore, we'll just try again } - } - while (responseHolder == null); - if (!bogusResponse) - { + } while (responseHolder == null); + if (!bogusResponse) { piggyBackResponses(responseHolder.response.content()); - responseHolder.response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, - String.valueOf(responseHolder.response.content().readableBytes())); + responseHolder.response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(responseHolder.response.content().readableBytes())); channel.writeAndFlush(responseHolder.response, promise); } - else - { + else { responseHolder.response.content().writeBytes(buffer); responseHolder.response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(responseHolder.response.content().readableBytes())); channel.writeAndFlush(responseHolder.response, promise); @@ -186,30 +163,23 @@ public class HttpAcceptorHandler extends ChannelDuplexHandler } // TODO: This can be optimized a lot - private void piggyBackResponses(ByteBuf buf) - { + private void piggyBackResponses(ByteBuf buf) { // if we are the last available response then we have to piggy back any remaining responses - if (responses.isEmpty()) - { + if (responses.isEmpty()) { buf.writeBytes(buffer); - do - { - try - { - ResponseRunner responseRunner = (ResponseRunner)delayedResponses.poll(0, TimeUnit.MILLISECONDS); - if (responseRunner == null) - { + do { + try { + ResponseRunner responseRunner = (ResponseRunner) delayedResponses.poll(0, TimeUnit.MILLISECONDS); + if (responseRunner == null) { break; } buf.writeBytes(responseRunner.buffer); responseRunner.buffer.release(); } - catch (InterruptedException e) - { + catch (InterruptedException e) { break; } - } - while (responses.isEmpty()); + } while (responses.isEmpty()); return; } buf.writeBytes(buffer); @@ -217,20 +187,15 @@ public class HttpAcceptorHandler extends ChannelDuplexHandler } - - public void shutdown() - { + public void shutdown() { executor.shutdown(); - try - { + try { executor.awaitTermination(10, TimeUnit.SECONDS); } - catch (InterruptedException e) - { + catch (InterruptedException e) { // no-op } - finally - { + finally { executor.shutdownNow(); } responses.clear(); @@ -239,14 +204,13 @@ public class HttpAcceptorHandler extends ChannelDuplexHandler /** * a holder class so we know what time the request first arrived */ - private static final class ResponseHolder - { + private static final class ResponseHolder { + final FullHttpResponse response; final long timeReceived; - public ResponseHolder(final long timeReceived, final FullHttpResponse response) - { + public ResponseHolder(final long timeReceived, final FullHttpResponse response) { this.timeReceived = timeReceived; this.response = response; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/HttpKeepAliveRunnable.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/HttpKeepAliveRunnable.java index 91aee1b947..712aa0e519 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/HttpKeepAliveRunnable.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/HttpKeepAliveRunnable.java @@ -23,55 +23,46 @@ import java.util.concurrent.Future; /** * A simple Runnable to allow {@link HttpAcceptorHandler}s to be called intermittently. */ -public class HttpKeepAliveRunnable implements Runnable -{ +public class HttpKeepAliveRunnable implements Runnable { + private final List handlers = new ArrayList(); private boolean closed = false; private Future future; - public synchronized void run() - { - if (closed) - { + public synchronized void run() { + if (closed) { return; } long time = System.currentTimeMillis(); - for (HttpAcceptorHandler handler : handlers) - { + for (HttpAcceptorHandler handler : handlers) { handler.keepAlive(time); } } - public synchronized void registerKeepAliveHandler(final HttpAcceptorHandler httpAcceptorHandler) - { + public synchronized void registerKeepAliveHandler(final HttpAcceptorHandler httpAcceptorHandler) { handlers.add(httpAcceptorHandler); } - public synchronized void unregisterKeepAliveHandler(final HttpAcceptorHandler httpAcceptorHandler) - { + public synchronized void unregisterKeepAliveHandler(final HttpAcceptorHandler httpAcceptorHandler) { handlers.remove(httpAcceptorHandler); httpAcceptorHandler.shutdown(); } - public void close() - { - for (HttpAcceptorHandler handler : handlers) - { + public void close() { + for (HttpAcceptorHandler handler : handlers) { handler.shutdown(); } - if (future != null) - { + if (future != null) { future.cancel(true); } closed = true; } - public synchronized void setFuture(final Future future) - { + public synchronized void setFuture(final Future future) { this.future = future; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/NettyAcceptor.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/NettyAcceptor.java index 0541ba07ea..f0fafaf59e 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/NettyAcceptor.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/NettyAcceptor.java @@ -82,14 +82,13 @@ import org.apache.activemq.artemis.utils.TypedProperties; /** * A Netty TCP Acceptor that supports SSL */ -public class NettyAcceptor implements Acceptor -{ +public class NettyAcceptor implements Acceptor { - static - { + static { // Disable resource leak detection for performance reasons by default ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.DISABLED); } + //just for debug private final String protocolsString; @@ -176,8 +175,7 @@ public class NettyAcceptor implements Acceptor final BufferHandler handler, final ConnectionLifeCycleListener listener, final ScheduledExecutorService scheduledThreadPool, - final Map protocolMap) - { + final Map protocolMap) { this.name = name; this.clusterConnection = clusterConnection; @@ -188,74 +186,38 @@ public class NettyAcceptor implements Acceptor this.listener = listener; - sslEnabled = ConfigurationHelper.getBooleanProperty(TransportConstants.SSL_ENABLED_PROP_NAME, - TransportConstants.DEFAULT_SSL_ENABLED, - configuration); + sslEnabled = ConfigurationHelper.getBooleanProperty(TransportConstants.SSL_ENABLED_PROP_NAME, TransportConstants.DEFAULT_SSL_ENABLED, configuration); - nioRemotingThreads = ConfigurationHelper.getIntProperty(TransportConstants.NIO_REMOTING_THREADS_PROPNAME, - -1, - configuration); - backlog = ConfigurationHelper.getIntProperty(TransportConstants.BACKLOG_PROP_NAME, - -1, - configuration); - useInvm = ConfigurationHelper.getBooleanProperty(TransportConstants.USE_INVM_PROP_NAME, - TransportConstants.DEFAULT_USE_INVM, - configuration); + nioRemotingThreads = ConfigurationHelper.getIntProperty(TransportConstants.NIO_REMOTING_THREADS_PROPNAME, -1, configuration); + backlog = ConfigurationHelper.getIntProperty(TransportConstants.BACKLOG_PROP_NAME, -1, configuration); + useInvm = ConfigurationHelper.getBooleanProperty(TransportConstants.USE_INVM_PROP_NAME, TransportConstants.DEFAULT_USE_INVM, configuration); this.protocolHandler = new ProtocolHandler(protocolMap, this, configuration, scheduledThreadPool); this.protocolsString = getProtocols(protocolMap); - host = ConfigurationHelper.getStringProperty(TransportConstants.HOST_PROP_NAME, - TransportConstants.DEFAULT_HOST, - configuration); - port = ConfigurationHelper.getIntProperty(TransportConstants.PORT_PROP_NAME, - TransportConstants.DEFAULT_PORT, - configuration); - if (sslEnabled) - { - keyStoreProvider = ConfigurationHelper.getStringProperty(TransportConstants.KEYSTORE_PROVIDER_PROP_NAME, - TransportConstants.DEFAULT_KEYSTORE_PROVIDER, - configuration); + host = ConfigurationHelper.getStringProperty(TransportConstants.HOST_PROP_NAME, TransportConstants.DEFAULT_HOST, configuration); + port = ConfigurationHelper.getIntProperty(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_PORT, configuration); + if (sslEnabled) { + keyStoreProvider = ConfigurationHelper.getStringProperty(TransportConstants.KEYSTORE_PROVIDER_PROP_NAME, TransportConstants.DEFAULT_KEYSTORE_PROVIDER, configuration); - keyStorePath = ConfigurationHelper.getStringProperty(TransportConstants.KEYSTORE_PATH_PROP_NAME, - TransportConstants.DEFAULT_KEYSTORE_PATH, - configuration); + keyStorePath = ConfigurationHelper.getStringProperty(TransportConstants.KEYSTORE_PATH_PROP_NAME, TransportConstants.DEFAULT_KEYSTORE_PATH, configuration); - keyStorePassword = ConfigurationHelper.getPasswordProperty(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, - TransportConstants.DEFAULT_KEYSTORE_PASSWORD, - configuration, - ActiveMQDefaultConfiguration.getPropMaskPassword(), - ActiveMQDefaultConfiguration.getPropMaskPassword()); + keyStorePassword = ConfigurationHelper.getPasswordProperty(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, TransportConstants.DEFAULT_KEYSTORE_PASSWORD, configuration, ActiveMQDefaultConfiguration.getPropMaskPassword(), ActiveMQDefaultConfiguration.getPropMaskPassword()); - trustStoreProvider = ConfigurationHelper.getStringProperty(TransportConstants.TRUSTSTORE_PROVIDER_PROP_NAME, - TransportConstants.DEFAULT_TRUSTSTORE_PROVIDER, - configuration); + trustStoreProvider = ConfigurationHelper.getStringProperty(TransportConstants.TRUSTSTORE_PROVIDER_PROP_NAME, TransportConstants.DEFAULT_TRUSTSTORE_PROVIDER, configuration); - trustStorePath = ConfigurationHelper.getStringProperty(TransportConstants.TRUSTSTORE_PATH_PROP_NAME, - TransportConstants.DEFAULT_TRUSTSTORE_PATH, - configuration); + trustStorePath = ConfigurationHelper.getStringProperty(TransportConstants.TRUSTSTORE_PATH_PROP_NAME, TransportConstants.DEFAULT_TRUSTSTORE_PATH, configuration); - trustStorePassword = ConfigurationHelper.getPasswordProperty(TransportConstants.TRUSTSTORE_PASSWORD_PROP_NAME, - TransportConstants.DEFAULT_TRUSTSTORE_PASSWORD, - configuration, - ActiveMQDefaultConfiguration.getPropMaskPassword(), - ActiveMQDefaultConfiguration.getPropMaskPassword()); + trustStorePassword = ConfigurationHelper.getPasswordProperty(TransportConstants.TRUSTSTORE_PASSWORD_PROP_NAME, TransportConstants.DEFAULT_TRUSTSTORE_PASSWORD, configuration, ActiveMQDefaultConfiguration.getPropMaskPassword(), ActiveMQDefaultConfiguration.getPropMaskPassword()); - enabledCipherSuites = ConfigurationHelper.getStringProperty(TransportConstants.ENABLED_CIPHER_SUITES_PROP_NAME, - TransportConstants.DEFAULT_ENABLED_CIPHER_SUITES, - configuration); + enabledCipherSuites = ConfigurationHelper.getStringProperty(TransportConstants.ENABLED_CIPHER_SUITES_PROP_NAME, TransportConstants.DEFAULT_ENABLED_CIPHER_SUITES, configuration); - enabledProtocols = ConfigurationHelper.getStringProperty(TransportConstants.ENABLED_PROTOCOLS_PROP_NAME, - TransportConstants.DEFAULT_ENABLED_PROTOCOLS, - configuration); + enabledProtocols = ConfigurationHelper.getStringProperty(TransportConstants.ENABLED_PROTOCOLS_PROP_NAME, TransportConstants.DEFAULT_ENABLED_PROTOCOLS, configuration); - needClientAuth = ConfigurationHelper.getBooleanProperty(TransportConstants.NEED_CLIENT_AUTH_PROP_NAME, - TransportConstants.DEFAULT_NEED_CLIENT_AUTH, - configuration); + needClientAuth = ConfigurationHelper.getBooleanProperty(TransportConstants.NEED_CLIENT_AUTH_PROP_NAME, TransportConstants.DEFAULT_NEED_CLIENT_AUTH, configuration); } - else - { + else { keyStoreProvider = TransportConstants.DEFAULT_KEYSTORE_PROVIDER; keyStorePath = TransportConstants.DEFAULT_KEYSTORE_PATH; keyStorePassword = TransportConstants.DEFAULT_KEYSTORE_PASSWORD; @@ -267,60 +229,40 @@ public class NettyAcceptor implements Acceptor needClientAuth = TransportConstants.DEFAULT_NEED_CLIENT_AUTH; } - tcpNoDelay = ConfigurationHelper.getBooleanProperty(TransportConstants.TCP_NODELAY_PROPNAME, - TransportConstants.DEFAULT_TCP_NODELAY, - configuration); - tcpSendBufferSize = ConfigurationHelper.getIntProperty(TransportConstants.TCP_SENDBUFFER_SIZE_PROPNAME, - TransportConstants.DEFAULT_TCP_SENDBUFFER_SIZE, - configuration); - tcpReceiveBufferSize = ConfigurationHelper.getIntProperty(TransportConstants.TCP_RECEIVEBUFFER_SIZE_PROPNAME, - TransportConstants.DEFAULT_TCP_RECEIVEBUFFER_SIZE, - configuration); + tcpNoDelay = ConfigurationHelper.getBooleanProperty(TransportConstants.TCP_NODELAY_PROPNAME, TransportConstants.DEFAULT_TCP_NODELAY, configuration); + tcpSendBufferSize = ConfigurationHelper.getIntProperty(TransportConstants.TCP_SENDBUFFER_SIZE_PROPNAME, TransportConstants.DEFAULT_TCP_SENDBUFFER_SIZE, configuration); + tcpReceiveBufferSize = ConfigurationHelper.getIntProperty(TransportConstants.TCP_RECEIVEBUFFER_SIZE_PROPNAME, TransportConstants.DEFAULT_TCP_RECEIVEBUFFER_SIZE, configuration); this.scheduledThreadPool = scheduledThreadPool; - batchDelay = ConfigurationHelper.getLongProperty(TransportConstants.BATCH_DELAY, - TransportConstants.DEFAULT_BATCH_DELAY, - configuration); + batchDelay = ConfigurationHelper.getLongProperty(TransportConstants.BATCH_DELAY, TransportConstants.DEFAULT_BATCH_DELAY, configuration); - directDeliver = ConfigurationHelper.getBooleanProperty(TransportConstants.DIRECT_DELIVER, - TransportConstants.DEFAULT_DIRECT_DELIVER, - configuration); + directDeliver = ConfigurationHelper.getBooleanProperty(TransportConstants.DIRECT_DELIVER, TransportConstants.DEFAULT_DIRECT_DELIVER, configuration); - httpUpgradeEnabled = ConfigurationHelper.getBooleanProperty(TransportConstants.HTTP_UPGRADE_ENABLED_PROP_NAME, - TransportConstants.DEFAULT_HTTP_UPGRADE_ENABLED, - configuration); + httpUpgradeEnabled = ConfigurationHelper.getBooleanProperty(TransportConstants.HTTP_UPGRADE_ENABLED_PROP_NAME, TransportConstants.DEFAULT_HTTP_UPGRADE_ENABLED, configuration); - connectionsAllowed = ConfigurationHelper.getLongProperty(TransportConstants.CONNECTIONS_ALLOWED, - TransportConstants.DEFAULT_CONNECTIONS_ALLOWED, - configuration); + connectionsAllowed = ConfigurationHelper.getLongProperty(TransportConstants.CONNECTIONS_ALLOWED, TransportConstants.DEFAULT_CONNECTIONS_ALLOWED, configuration); } - public synchronized void start() throws Exception - { - if (channelClazz != null) - { + public synchronized void start() throws Exception { + if (channelClazz != null) { // Already started return; } - if (useInvm) - { + if (useInvm) { channelClazz = LocalServerChannel.class; eventLoopGroup = new LocalEventLoopGroup(); } - else - { + else { int threadsToUse; - if (nioRemotingThreads == -1) - { + if (nioRemotingThreads == -1) { // Default to number of cores * 3 threadsToUse = Runtime.getRuntime().availableProcessors() * 3; } - else - { + else { threadsToUse = this.nioRemotingThreads; } channelClazz = NioServerSocketChannel.class; @@ -331,39 +273,32 @@ public class NettyAcceptor implements Acceptor bootstrap.group(eventLoopGroup); bootstrap.channel(channelClazz); final SSLContext context; - if (sslEnabled) - { - try - { + if (sslEnabled) { + try { if (keyStorePath == null && TransportConstants.DEFAULT_TRUSTSTORE_PROVIDER.equals(keyStoreProvider)) throw new IllegalArgumentException("If \"" + TransportConstants.SSL_ENABLED_PROP_NAME + "\" is true then \"" + TransportConstants.KEYSTORE_PATH_PROP_NAME + "\" must be non-null " + "unless an alternative \"" + TransportConstants.KEYSTORE_PROVIDER_PROP_NAME + "\" has been specified."); context = SSLSupport.createContext(keyStoreProvider, keyStorePath, keyStorePassword, trustStoreProvider, trustStorePath, trustStorePassword); } - catch (Exception e) - { + catch (Exception e) { IllegalStateException ise = new IllegalStateException("Unable to create NettyAcceptor for " + host + ":" + port); ise.initCause(e); throw ise; } } - else - { + else { context = null; // Unused } final AtomicBoolean warningPrinted = new AtomicBoolean(false); - ChannelInitializer factory = new ChannelInitializer() - { + ChannelInitializer factory = new ChannelInitializer() { @Override - public void initChannel(Channel channel) throws Exception - { + public void initChannel(Channel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); - if (sslEnabled) - { + if (sslEnabled) { SSLEngine engine = context.createSSLEngine(); engine.setUseClientMode(false); @@ -376,33 +311,26 @@ public class NettyAcceptor implements Acceptor // we can reset the enabled protocols if a customer protocol isn't specified String[] originalProtocols = engine.getEnabledProtocols(); - if (enabledCipherSuites != null) - { - try - { + if (enabledCipherSuites != null) { + try { engine.setEnabledCipherSuites(SSLSupport.parseCommaSeparatedListIntoArray(enabledCipherSuites)); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { ActiveMQServerLogger.LOGGER.invalidCipherSuite(SSLSupport.parseArrayIntoCommandSeparatedList(engine.getSupportedCipherSuites())); throw e; } } - if (enabledProtocols != null) - { - try - { + if (enabledProtocols != null) { + try { engine.setEnabledProtocols(SSLSupport.parseCommaSeparatedListIntoArray(enabledProtocols)); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { ActiveMQServerLogger.LOGGER.invalidProtocol(SSLSupport.parseArrayIntoCommandSeparatedList(engine.getSupportedProtocols())); throw e; } } - else - { + else { engine.setEnabledProtocols(originalProtocols); } @@ -410,12 +338,9 @@ public class NettyAcceptor implements Acceptor // This recommendation came from http://www.oracle.com/technetwork/java/javase/documentation/cve-2014-3566-2342133.html String[] protocols = engine.getEnabledProtocols(); Set set = new HashSet<>(); - for (String s : protocols) - { - if (s.equals("SSLv3") || s.equals("SSLv2Hello")) - { - if (!warningPrinted.get()) - { + for (String s : protocols) { + if (s.equals("SSLv3") || s.equals("SSLv2Hello")) { + if (!warningPrinted.get()) { ActiveMQServerLogger.LOGGER.disallowedProtocol(s); } continue; @@ -436,16 +361,13 @@ public class NettyAcceptor implements Acceptor // Bind bootstrap.childOption(ChannelOption.TCP_NODELAY, tcpNoDelay); - if (tcpReceiveBufferSize != -1) - { + if (tcpReceiveBufferSize != -1) { bootstrap.childOption(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize); } - if (tcpSendBufferSize != -1) - { + if (tcpSendBufferSize != -1) { bootstrap.childOption(ChannelOption.SO_SNDBUF, tcpSendBufferSize); } - if (backlog != -1) - { + if (backlog != -1) { bootstrap.option(ChannelOption.SO_BACKLOG, backlog); } bootstrap.option(ChannelOption.SO_REUSEADDR, true); @@ -456,36 +378,28 @@ public class NettyAcceptor implements Acceptor serverChannelGroup = new DefaultChannelGroup("activemq-acceptor-channels", GlobalEventExecutor.INSTANCE); - if (httpUpgradeEnabled) - { + if (httpUpgradeEnabled) { // the channel will be bound by the Web container and hand over after the HTTP Upgrade // handshake is successful } - else - { + else { startServerChannels(); paused = false; - if (notificationService != null) - { + if (notificationService != null) { TypedProperties props = new TypedProperties(); - props.putSimpleStringProperty(new SimpleString("factory"), - new SimpleString(NettyAcceptorFactory.class.getName())); + props.putSimpleStringProperty(new SimpleString("factory"), new SimpleString(NettyAcceptorFactory.class.getName())); props.putSimpleStringProperty(new SimpleString("host"), new SimpleString(host)); props.putIntProperty(new SimpleString("port"), port); Notification notification = new Notification(null, CoreNotificationType.ACCEPTOR_STARTED, props); notificationService.sendNotification(notification); } - if (batchDelay > 0) - { + if (batchDelay > 0) { flusher = new BatchFlusher(); - batchFlusherFuture = scheduledThreadPool.scheduleWithFixedDelay(flusher, - batchDelay, - batchDelay, - TimeUnit.MILLISECONDS); + batchFlusherFuture = scheduledThreadPool.scheduleWithFixedDelay(flusher, batchDelay, batchDelay, TimeUnit.MILLISECONDS); } ActiveMQServerLogger.LOGGER.startedAcceptor(host, port, protocolsString); @@ -498,23 +412,18 @@ public class NettyAcceptor implements Acceptor * * @param channel A Netty channel created outside this NettyAcceptor. */ - public void transfer(Channel channel) - { + public void transfer(Channel channel) { channel.pipeline().addLast(protocolHandler.getProtocolDecoder()); } - private void startServerChannels() - { + private void startServerChannels() { String[] hosts = TransportConfiguration.splitHosts(host); - for (String h : hosts) - { + for (String h : hosts) { SocketAddress address; - if (useInvm) - { + if (useInvm) { address = new LocalAddress(h); } - else - { + else { address = new InetSocketAddress(h, port); } Channel serverChannel = bootstrap.bind(address).syncUninterruptibly().channel(); @@ -522,25 +431,20 @@ public class NettyAcceptor implements Acceptor } } - public Map getConfiguration() - { + public Map getConfiguration() { return this.configuration; } - public synchronized void stop() - { - if (channelClazz == null) - { + public synchronized void stop() { + if (channelClazz == null) { return; } - if (protocolHandler != null) - { + if (protocolHandler != null) { protocolHandler.close(); } - if (batchFlusherFuture != null) - { + if (batchFlusherFuture != null) { batchFlusherFuture.cancel(false); flusher.cancel(); @@ -550,26 +454,20 @@ public class NettyAcceptor implements Acceptor batchFlusherFuture = null; } - // serverChannelGroup has been unbound in pause() - if (serverChannelGroup != null) - { + if (serverChannelGroup != null) { serverChannelGroup.close().awaitUninterruptibly(); } - if (channelGroup != null) - { + if (channelGroup != null) { ChannelGroupFuture future = channelGroup.close().awaitUninterruptibly(); - if (!future.isSuccess()) - { + if (!future.isSuccess()) { ActiveMQServerLogger.LOGGER.nettyChannelGroupError(); Iterator iterator = future.group().iterator(); - while (iterator.hasNext()) - { + while (iterator.hasNext()) { Channel channel = iterator.next(); - if (channel.isActive()) - { + if (channel.isActive()) { ActiveMQServerLogger.LOGGER.nettyChannelStillOpen(channel, channel.remoteAddress()); } } @@ -583,27 +481,22 @@ public class NettyAcceptor implements Acceptor channelClazz = null; - for (Connection connection : connections.values()) - { + for (Connection connection : connections.values()) { listener.connectionDestroyed(connection.getID()); } connections.clear(); - if (notificationService != null) - { + if (notificationService != null) { TypedProperties props = new TypedProperties(); - props.putSimpleStringProperty(new SimpleString("factory"), - new SimpleString(NettyAcceptorFactory.class.getName())); + props.putSimpleStringProperty(new SimpleString("factory"), new SimpleString(NettyAcceptorFactory.class.getName())); props.putSimpleStringProperty(new SimpleString("host"), new SimpleString(host)); props.putIntProperty(new SimpleString("port"), port); Notification notification = new Notification(null, CoreNotificationType.ACCEPTOR_STOPPED, props); - try - { + try { notificationService.sendNotification(notification); } - catch (Exception e) - { + catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } @@ -612,36 +505,28 @@ public class NettyAcceptor implements Acceptor paused = false; } - public boolean isStarted() - { + public boolean isStarted() { return channelClazz != null; } - public synchronized void pause() - { - if (paused) - { + public synchronized void pause() { + if (paused) { return; } - if (channelClazz == null) - { + if (channelClazz == null) { return; } // We *pause* the acceptor so no new connections are made - if (serverChannelGroup != null) - { + if (serverChannelGroup != null) { ChannelGroupFuture future = serverChannelGroup.close().awaitUninterruptibly(); - if (!future.isSuccess()) - { + if (!future.isSuccess()) { ActiveMQServerLogger.LOGGER.nettyChannelGroupBindError(); Iterator iterator = future.group().iterator(); - while (iterator.hasNext()) - { + while (iterator.hasNext()) { Channel channel = iterator.next(); - if (channel.isActive()) - { + if (channel.isActive()) { ActiveMQServerLogger.LOGGER.nettyChannelStillBound(channel, channel.remoteAddress()); } } @@ -650,8 +535,7 @@ public class NettyAcceptor implements Acceptor paused = true; } - public void setNotificationService(final NotificationService notificationService) - { + public void setNotificationService(final NotificationService notificationService) { this.notificationService = notificationService; } @@ -660,8 +544,7 @@ public class NettyAcceptor implements Acceptor * * @param defaultActiveMQPrincipal */ - public void setDefaultActiveMQPrincipal(ActiveMQPrincipal defaultActiveMQPrincipal) - { + public void setDefaultActiveMQPrincipal(ActiveMQPrincipal defaultActiveMQPrincipal) { throw new IllegalStateException("unsecure connections not allowed"); } @@ -670,32 +553,25 @@ public class NettyAcceptor implements Acceptor * * @return */ - public boolean isUnsecurable() - { + public boolean isUnsecurable() { return false; } @Override - public ClusterConnection getClusterConnection() - { + public ClusterConnection getClusterConnection() { return clusterConnection; } - public ConnectionCreator createConnectionCreator() - { + public ConnectionCreator createConnectionCreator() { return new ActiveMQServerChannelHandler(channelGroup, handler, new Listener()); } - private static String getProtocols(Map protocolManager) - { + private static String getProtocols(Map protocolManager) { StringBuilder sb = new StringBuilder(); - if (protocolManager != null) - { + if (protocolManager != null) { Set strings = protocolManager.keySet(); - for (String string : strings) - { - if (sb.length() > 0) - { + for (String string : strings) { + if (sb.length() > 0) { sb.append(","); } sb.append(string); @@ -705,20 +581,18 @@ public class NettyAcceptor implements Acceptor } // Inner classes ----------------------------------------------------------------------------- - private final class ActiveMQServerChannelHandler extends ActiveMQChannelHandler implements ConnectionCreator - { + private final class ActiveMQServerChannelHandler extends ActiveMQChannelHandler implements ConnectionCreator { ActiveMQServerChannelHandler(final ChannelGroup group, final BufferHandler handler, - final ConnectionLifeCycleListener listener) - { + final ConnectionLifeCycleListener listener) { super(group, handler, listener); } - public NettyServerConnection createConnection(final ChannelHandlerContext ctx, String protocol, boolean httpEnabled) throws Exception - { - if (connectionsAllowed == -1 || connections.size() < connectionsAllowed) - { + public NettyServerConnection createConnection(final ChannelHandlerContext ctx, + String protocol, + boolean httpEnabled) throws Exception { + if (connectionsAllowed == -1 || connections.size() < connectionsAllowed) { super.channelActive(ctx); Listener connectionListener = new Listener(); @@ -727,33 +601,25 @@ public class NettyAcceptor implements Acceptor connectionListener.connectionCreated(NettyAcceptor.this, nc, protocol); SslHandler sslHandler = ctx.pipeline().get(SslHandler.class); - if (sslHandler != null) - { - sslHandler.handshakeFuture().addListener(new GenericFutureListener>() - { - public void operationComplete(final io.netty.util.concurrent.Future future) throws Exception - { - if (future.isSuccess()) - { + if (sslHandler != null) { + sslHandler.handshakeFuture().addListener(new GenericFutureListener>() { + public void operationComplete(final io.netty.util.concurrent.Future future) throws Exception { + if (future.isSuccess()) { active = true; } - else - { + else { future.getNow().close(); } } }); } - else - { + else { active = true; } return nc; } - else - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + else { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug(new StringBuilder().append("Connection limit of ").append(connectionsAllowed).append(" reached. Refusing connection from ").append(ctx.channel().remoteAddress())); } throw new Exception(); @@ -761,78 +627,64 @@ public class NettyAcceptor implements Acceptor } } - private class Listener implements ConnectionLifeCycleListener - { - public void connectionCreated(final ActiveMQComponent component, final Connection connection, final String protocol) - { - if (connections.putIfAbsent(connection.getID(), (NettyServerConnection) connection) != null) - { + private class Listener implements ConnectionLifeCycleListener { + + public void connectionCreated(final ActiveMQComponent component, + final Connection connection, + final String protocol) { + if (connections.putIfAbsent(connection.getID(), (NettyServerConnection) connection) != null) { throw ActiveMQMessageBundle.BUNDLE.connectionExists(connection.getID()); } listener.connectionCreated(component, connection, protocol); } - public void connectionDestroyed(final Object connectionID) - { - if (connections.remove(connectionID) != null) - { + public void connectionDestroyed(final Object connectionID) { + if (connections.remove(connectionID) != null) { listener.connectionDestroyed(connectionID); } } - public void connectionException(final Object connectionID, final ActiveMQException me) - { + public void connectionException(final Object connectionID, final ActiveMQException me) { // Execute on different thread to avoid deadlocks - new Thread() - { + new Thread() { @Override - public void run() - { + public void run() { listener.connectionException(connectionID, me); } }.start(); } - public void connectionReadyForWrites(final Object connectionID, boolean ready) - { + public void connectionReadyForWrites(final Object connectionID, boolean ready) { NettyServerConnection conn = connections.get(connectionID); - if (conn != null) - { + if (conn != null) { conn.fireReady(ready); } } } - private class BatchFlusher implements Runnable - { + private class BatchFlusher implements Runnable { + private boolean cancelled; - public synchronized void run() - { - if (!cancelled) - { - for (Connection connection : connections.values()) - { + public synchronized void run() { + if (!cancelled) { + for (Connection connection : connections.values()) { connection.checkFlushBatchBuffer(); } } } - public synchronized void cancel() - { + public synchronized void cancel() { cancelled = true; } } - private static ClassLoader getThisClassLoader() - { - return AccessController.doPrivileged(new PrivilegedAction() - { - public ClassLoader run() - { + private static ClassLoader getThisClassLoader() { + return AccessController.doPrivileged(new PrivilegedAction() { + public ClassLoader run() { return ClientSessionFactoryImpl.class.getClassLoader(); } }); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/NettyAcceptorFactory.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/NettyAcceptorFactory.java index dc9faf3b4e..92b79f858a 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/NettyAcceptorFactory.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/NettyAcceptorFactory.java @@ -27,8 +27,8 @@ import org.apache.activemq.artemis.spi.core.remoting.AcceptorFactory; import org.apache.activemq.artemis.spi.core.remoting.BufferHandler; import org.apache.activemq.artemis.spi.core.remoting.ConnectionLifeCycleListener; -public class NettyAcceptorFactory implements AcceptorFactory -{ +public class NettyAcceptorFactory implements AcceptorFactory { + public Acceptor createAcceptor(final String name, final ClusterConnection connection, final Map configuration, @@ -36,8 +36,7 @@ public class NettyAcceptorFactory implements AcceptorFactory final ConnectionLifeCycleListener listener, final Executor threadPool, final ScheduledExecutorService scheduledThreadPool, - final Map protocolMap) - { + final Map protocolMap) { return new NettyAcceptor(name, connection, configuration, handler, listener, scheduledThreadPool, protocolMap); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/NettyServerConnection.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/NettyServerConnection.java index 5f99674caa..31957c41b5 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/NettyServerConnection.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/NettyServerConnection.java @@ -23,16 +23,18 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.core.buffers.impl.ChannelBufferWrapper; import org.apache.activemq.artemis.spi.core.remoting.ConnectionLifeCycleListener; -public class NettyServerConnection extends NettyConnection -{ - public NettyServerConnection(Map configuration, Channel channel, ConnectionLifeCycleListener listener, boolean batchingEnabled, boolean directDeliver) - { +public class NettyServerConnection extends NettyConnection { + + public NettyServerConnection(Map configuration, + Channel channel, + ConnectionLifeCycleListener listener, + boolean batchingEnabled, + boolean directDeliver) { super(configuration, channel, listener, batchingEnabled, directDeliver); } @Override - public ActiveMQBuffer createTransportBuffer(int size) - { + public ActiveMQBuffer createTransportBuffer(int size) { return new ChannelBufferWrapper(channel.alloc().directBuffer(size), true); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/server/RemotingService.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/server/RemotingService.java index 72d61fe081..e940c02f83 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/server/RemotingService.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/server/RemotingService.java @@ -27,8 +27,8 @@ import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; import org.apache.activemq.artemis.spi.core.remoting.Acceptor; import org.apache.activemq.artemis.utils.ReusableLatch; -public interface RemotingService -{ +public interface RemotingService { + /** * Remove a connection from the connections held by the remoting service. * This method must be used only from the management API. diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/server/impl/RemotingServiceImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/server/impl/RemotingServiceImpl.java index 1b43e2104f..5401c8a001 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/server/impl/RemotingServiceImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/remoting/server/impl/RemotingServiceImpl.java @@ -71,8 +71,7 @@ import org.apache.activemq.artemis.utils.ActiveMQThreadFactory; import org.apache.activemq.artemis.utils.ConfigurationHelper; import org.apache.activemq.artemis.utils.ReusableLatch; -public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycleListener -{ +public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycleListener { // Constants ----------------------------------------------------- private static final boolean isTrace = ActiveMQServerLogger.LOGGER.isTraceEnabled(); @@ -126,8 +125,7 @@ public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycle final ScheduledExecutorService scheduledThreadPool, List protocolManagerFactories, final Executor flushExecutor, - final ServiceRegistry serviceRegistry) - { + final ServiceRegistry serviceRegistry) { this.serviceRegistry = serviceRegistry; acceptorsConfig = config.getAcceptorConfigurations(); @@ -147,35 +145,25 @@ public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycle this.flushExecutor = flushExecutor; ActiveMQServerLogger.LOGGER.addingProtocolSupport(coreProtocolManagerFactory.getProtocols()[0], coreProtocolManagerFactory.getModuleName()); - this.protocolMap.put(coreProtocolManagerFactory.getProtocols()[0], - coreProtocolManagerFactory.createProtocolManager(server, coreProtocolManagerFactory.filterInterceptors(incomingInterceptors), - coreProtocolManagerFactory.filterInterceptors(outgoingInterceptors))); + this.protocolMap.put(coreProtocolManagerFactory.getProtocols()[0], coreProtocolManagerFactory.createProtocolManager(server, coreProtocolManagerFactory.filterInterceptors(incomingInterceptors), coreProtocolManagerFactory.filterInterceptors(outgoingInterceptors))); - if (config.isResolveProtocols()) - { + if (config.isResolveProtocols()) { ServiceLoader serviceLoader = ServiceLoader.load(ProtocolManagerFactory.class, this.getClass().getClassLoader()); - if (serviceLoader != null) - { - for (ProtocolManagerFactory next : serviceLoader) - { + if (serviceLoader != null) { + for (ProtocolManagerFactory next : serviceLoader) { String[] protocols = next.getProtocols(); - for (String protocol : protocols) - { + for (String protocol : protocols) { ActiveMQServerLogger.LOGGER.addingProtocolSupport(protocol, next.getModuleName()); - protocolMap.put(protocol, next.createProtocolManager(server, next.filterInterceptors(incomingInterceptors), - next.filterInterceptors(outgoingInterceptors))); + protocolMap.put(protocol, next.createProtocolManager(server, next.filterInterceptors(incomingInterceptors), next.filterInterceptors(outgoingInterceptors))); } } } } - if (protocolManagerFactories != null) - { - for (ProtocolManagerFactory protocolManagerFactory : protocolManagerFactories) - { + if (protocolManagerFactories != null) { + for (ProtocolManagerFactory protocolManagerFactory : protocolManagerFactories) { String[] protocols = protocolManagerFactory.getProtocols(); - for (String protocol : protocols) - { + for (String protocol : protocols) { ActiveMQServerLogger.LOGGER.addingProtocolSupport(protocol, protocolManagerFactory.getModuleName()); protocolMap.put(protocol, protocolManagerFactory.createProtocolManager(server, incomingInterceptors, outgoingInterceptors)); } @@ -185,23 +173,18 @@ public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycle // RemotingService implementation ------------------------------- - private void setInterceptors(Configuration configuration) - { + private void setInterceptors(Configuration configuration) { incomingInterceptors.addAll(serviceRegistry.getIncomingInterceptors(configuration.getIncomingInterceptorClassNames())); outgoingInterceptors.addAll(serviceRegistry.getOutgoingInterceptors(configuration.getOutgoingInterceptorClassNames())); } - public synchronized void start() throws Exception - { - if (started) - { + public synchronized void start() throws Exception { + if (started) { return; } - ClassLoader tccl = AccessController.doPrivileged(new PrivilegedAction() - { - public ClassLoader run() - { + ClassLoader tccl = AccessController.doPrivileged(new PrivilegedAction() { + public ClassLoader run() { return Thread.currentThread().getContextClassLoader(); } }); @@ -218,51 +201,39 @@ public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycle threadPool = Executors.newCachedThreadPool(tFactory); - for (TransportConfiguration info : acceptorsConfig) - { - try - { + for (TransportConfiguration info : acceptorsConfig) { + try { AcceptorFactory factory = server.getServiceRegistry().getAcceptorFactory(info.getName(), info.getFactoryClassName()); Map supportedProtocols = new ConcurrentHashMap(); - String protocol = ConfigurationHelper.getStringProperty(TransportConstants.PROTOCOL_PROP_NAME, null, - info.getParams()); + String protocol = ConfigurationHelper.getStringProperty(TransportConstants.PROTOCOL_PROP_NAME, null, info.getParams()); - if (protocol != null) - { + if (protocol != null) { ActiveMQServerLogger.LOGGER.warnDeprecatedProtocol(); ProtocolManager protocolManager = protocolMap.get(protocol); - if (protocolManager == null) - { + if (protocolManager == null) { throw ActiveMQMessageBundle.BUNDLE.noProtocolManagerFound(protocol); } - else - { + else { supportedProtocols.put(protocol, protocolManager); } } - String protocols = ConfigurationHelper.getStringProperty(TransportConstants.PROTOCOLS_PROP_NAME, null, - info.getParams()); + String protocols = ConfigurationHelper.getStringProperty(TransportConstants.PROTOCOLS_PROP_NAME, null, info.getParams()); - if (protocols != null) - { + if (protocols != null) { String[] actualProtocols = protocols.split(","); - if (actualProtocols != null) - { - for (String actualProtocol : actualProtocols) - { + if (actualProtocols != null) { + for (String actualProtocol : actualProtocols) { ProtocolManager protocolManager = protocolMap.get(actualProtocol); - if (protocolManager == null) - { + if (protocolManager == null) { throw ActiveMQMessageBundle.BUNDLE.noProtocolManagerFound(actualProtocol); } - else - { + else { supportedProtocols.put(actualProtocol, protocolManager); } } @@ -271,31 +242,21 @@ public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycle ClusterConnection clusterConnection = lookupClusterConnection(info); - Acceptor acceptor = factory.createAcceptor(info.getName(), - clusterConnection, - info.getParams(), - new DelegatingBufferHandler(), - this, - threadPool, - scheduledThreadPool, - supportedProtocols.isEmpty() ? protocolMap : supportedProtocols); + Acceptor acceptor = factory.createAcceptor(info.getName(), clusterConnection, info.getParams(), new DelegatingBufferHandler(), this, threadPool, scheduledThreadPool, supportedProtocols.isEmpty() ? protocolMap : supportedProtocols); - if (defaultInvmSecurityPrincipal != null && acceptor.isUnsecurable()) - { + if (defaultInvmSecurityPrincipal != null && acceptor.isUnsecurable()) { acceptor.setDefaultActiveMQPrincipal(defaultInvmSecurityPrincipal); } acceptors.put(info.getName(), acceptor); - if (managementService != null) - { + if (managementService != null) { acceptor.setNotificationService(managementService); managementService.registerAcceptor(acceptor, info); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorCreatingAcceptor(e, info.getFactoryClassName()); } } @@ -313,49 +274,38 @@ public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycle started = true; } - public synchronized void startAcceptors() throws Exception - { - if (isStarted()) - { - for (Acceptor a : acceptors.values()) - { + public synchronized void startAcceptors() throws Exception { + if (isStarted()) { + for (Acceptor a : acceptors.values()) { a.start(); } } } - public synchronized void allowInvmSecurityOverride(ActiveMQPrincipal principal) - { + public synchronized void allowInvmSecurityOverride(ActiveMQPrincipal principal) { defaultInvmSecurityPrincipal = principal; - for (Acceptor acceptor : acceptors.values()) - { - if (acceptor.isUnsecurable()) - { + for (Acceptor acceptor : acceptors.values()) { + if (acceptor.isUnsecurable()) { acceptor.setDefaultActiveMQPrincipal(principal); } } } - public synchronized void pauseAcceptors() - { + public synchronized void pauseAcceptors() { if (!started) return; - for (Acceptor acceptor : acceptors.values()) - { - try - { + for (Acceptor acceptor : acceptors.values()) { + try { acceptor.pause(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorStoppingAcceptor(); } } } - public synchronized void freeze(final String scaleDownNodeID, final CoreRemotingConnection connectionToKeepOpen) - { + public synchronized void freeze(final String scaleDownNodeID, final CoreRemotingConnection connectionToKeepOpen) { if (!started) return; failureCheckAndFlushThread.close(false); @@ -363,47 +313,39 @@ public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycle // Now we ensure that no connections will process any more packets after this method is // complete then send a disconnect packet - for (Entry entry : connectionEntries.entrySet()) - { + for (Entry entry : connectionEntries.entrySet()) { RemotingConnection conn = entry.getValue().connection; if (conn.equals(connectionToKeepOpen)) continue; - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("Sending connection.disconnection packet to " + conn); } - if (!conn.isClient()) - { + if (!conn.isClient()) { conn.disconnect(scaleDownNodeID, false); removeConnection(entry.getKey()); } } } - public void stop(final boolean criticalError) throws Exception - { - if (!started) - { + public void stop(final boolean criticalError) throws Exception { + if (!started) { return; } failureCheckAndFlushThread.close(criticalError); // We need to stop them accepting first so no new connections are accepted after we send the disconnect message - for (Acceptor acceptor : acceptors.values()) - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + for (Acceptor acceptor : acceptors.values()) { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Pausing acceptor " + acceptor); } acceptor.pause(); } - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Sending disconnect on live connections"); } @@ -411,20 +353,17 @@ public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycle // Now we ensure that no connections will process any more packets after this method is complete // then send a disconnect packet - for (ConnectionEntry entry : connectionEntries) - { + for (ConnectionEntry entry : connectionEntries) { RemotingConnection conn = entry.connection; - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("Sending connection.disconnection packet to " + conn); } conn.disconnect(criticalError); } - for (Acceptor acceptor : acceptors.values()) - { + for (Acceptor acceptor : acceptors.values()) { acceptor.stop(); } @@ -433,19 +372,16 @@ public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycle connections.clear(); connectionCountLatch.setCount(0); - if (managementService != null) - { + if (managementService != null) { managementService.unregisterAcceptors(); } threadPool.shutdown(); - if (!criticalError) - { + if (!criticalError) { boolean ok = threadPool.awaitTermination(10000, TimeUnit.MILLISECONDS); - if (!ok) - { + if (!ok) { ActiveMQServerLogger.LOGGER.timeoutRemotingThreadPool(); } } @@ -455,92 +391,77 @@ public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycle } @Override - public Acceptor getAcceptor(String name) - { + public Acceptor getAcceptor(String name) { return acceptors.get(name); } - public boolean isStarted() - { + public boolean isStarted() { return started; } - - private RemotingConnection getConnection(final Object remotingConnectionID) - { + private RemotingConnection getConnection(final Object remotingConnectionID) { ConnectionEntry entry = connections.get(remotingConnectionID); - if (entry != null) - { + if (entry != null) { return entry.connection; } - else - { + else { ActiveMQServerLogger.LOGGER.errorRemovingConnection(); return null; } } - public RemotingConnection removeConnection(final Object remotingConnectionID) - { + public RemotingConnection removeConnection(final Object remotingConnectionID) { ConnectionEntry entry = connections.remove(remotingConnectionID); - if (entry != null) - { + if (entry != null) { connectionCountLatch.countDown(); return entry.connection; } - else - { + else { ActiveMQServerLogger.LOGGER.errorRemovingConnection(); return null; } } - public synchronized Set getConnections() - { + public synchronized Set getConnections() { Set conns = new HashSet(connections.size()); - for (ConnectionEntry entry : connections.values()) - { + for (ConnectionEntry entry : connections.values()) { conns.add(entry.connection); } return conns; } - public synchronized ReusableLatch getConnectionCountLatch() - { + public synchronized ReusableLatch getConnectionCountLatch() { return connectionCountLatch; } // ConnectionLifeCycleListener implementation ----------------------------------- - private ProtocolManager getProtocolManager(String protocol) - { + private ProtocolManager getProtocolManager(String protocol) { return protocolMap.get(protocol); } - public void connectionCreated(final ActiveMQComponent component, final Connection connection, final String protocol) - { - if (server == null) - { + public void connectionCreated(final ActiveMQComponent component, + final Connection connection, + final String protocol) { + if (server == null) { throw new IllegalStateException("Unable to create connection, server hasn't finished starting up"); } ProtocolManager pmgr = this.getProtocolManager(protocol.toString()); - if (pmgr == null) - { + if (pmgr == null) { throw ActiveMQMessageBundle.BUNDLE.unknownProtocol(protocol); } ConnectionEntry entry = pmgr.createConnectionEntry((Acceptor) component, connection); - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Connection created " + connection); } @@ -548,28 +469,23 @@ public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycle connectionCountLatch.countUp(); } - public void connectionDestroyed(final Object connectionID) - { + public void connectionDestroyed(final Object connectionID) { - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Connection removed " + connectionID + " from server " + this.server, new Exception("trace")); } ConnectionEntry conn = connections.get(connectionID); - if (conn != null) - { + if (conn != null) { // Bit of a hack - find a better way to do this List failureListeners = conn.connection.getFailureListeners(); boolean empty = true; - for (FailureListener listener : failureListeners) - { - if (listener instanceof ServerSessionImpl) - { + for (FailureListener listener : failureListeners) { + if (listener instanceof ServerSessionImpl) { empty = false; break; @@ -579,8 +495,7 @@ public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycle // We only destroy the connection if the connection has no sessions attached to it // Otherwise it means the connection has died without the sessions being closed first // so we need to keep them for ttl, in case re-attachment occurs - if (empty) - { + if (empty) { removeConnection(connectionID); conn.connection.destroy(); @@ -588,8 +503,7 @@ public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycle } } - public void connectionException(final Object connectionID, final ActiveMQException me) - { + public void connectionException(final Object connectionID, final ActiveMQException me) { // We DO NOT call fail on connection exception, otherwise in event of real connection failure, the // connection will be failed, the session will be closed and won't be able to reconnect @@ -600,78 +514,64 @@ public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycle // Connections should only fail when TTL is exceeded } - public void connectionReadyForWrites(final Object connectionID, final boolean ready) - { + public void connectionReadyForWrites(final Object connectionID, final boolean ready) { } @Override - public void addIncomingInterceptor(final Interceptor interceptor) - { + public void addIncomingInterceptor(final Interceptor interceptor) { incomingInterceptors.add(interceptor); updateProtocols(); } @Override - public List getIncomingInterceptors() - { + public List getIncomingInterceptors() { return Collections.unmodifiableList(incomingInterceptors); } @Override - public boolean removeIncomingInterceptor(final Interceptor interceptor) - { - if (incomingInterceptors.remove(interceptor)) - { + public boolean removeIncomingInterceptor(final Interceptor interceptor) { + if (incomingInterceptors.remove(interceptor)) { updateProtocols(); return true; } - else - { + else { return false; } } @Override - public void addOutgoingInterceptor(final Interceptor interceptor) - { + public void addOutgoingInterceptor(final Interceptor interceptor) { outgoingInterceptors.add(interceptor); updateProtocols(); } @Override - public List getOutgoinInterceptors() - { + public List getOutgoinInterceptors() { return Collections.unmodifiableList(outgoingInterceptors); } @Override - public boolean removeOutgoingInterceptor(final Interceptor interceptor) - { - if (outgoingInterceptors.remove(interceptor)) - { + public boolean removeOutgoingInterceptor(final Interceptor interceptor) { + if (outgoingInterceptors.remove(interceptor)) { updateProtocols(); return true; } - else - { + else { return false; } } - private ClusterConnection lookupClusterConnection(TransportConfiguration acceptorConfig) - { + private ClusterConnection lookupClusterConnection(TransportConfiguration acceptorConfig) { String clusterConnectionName = (String) acceptorConfig.getParams().get(org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.CLUSTER_CONNECTION); ClusterConnection clusterConnection = null; - if (clusterConnectionName != null) - { + if (clusterConnectionName != null) { clusterConnection = clusterManager.getClusterConnection(clusterConnectionName); } // if not found we will still use the default name, even if a name was provided - if (clusterConnection == null) - { + if (clusterConnection == null) { clusterConnection = clusterManager.getDefaultConnection(acceptorConfig); } @@ -680,108 +580,86 @@ public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycle // Inner classes ------------------------------------------------- - private final class DelegatingBufferHandler implements BufferHandler - { - public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) - { + private final class DelegatingBufferHandler implements BufferHandler { + + public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) { ConnectionEntry conn = connections.get(connectionID); - if (conn != null) - { + if (conn != null) { conn.connection.bufferReceived(connectionID, buffer); } - else - { - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + else { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("ConnectionID = " + connectionID + " was already closed, so ignoring packet"); } } } } - private final class FailureCheckAndFlushThread extends Thread - { + private final class FailureCheckAndFlushThread extends Thread { + private final long pauseInterval; private volatile boolean closed; private final CountDownLatch latch = new CountDownLatch(1); - FailureCheckAndFlushThread(final long pauseInterval) - { + FailureCheckAndFlushThread(final long pauseInterval) { super("activemq-failure-check-thread"); this.pauseInterval = pauseInterval; } - public void close(final boolean criticalError) - { + public void close(final boolean criticalError) { closed = true; latch.countDown(); - if (!criticalError) - { - try - { + if (!criticalError) { + try { join(); } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } } } @Override - public void run() - { - while (!closed) - { - try - { + public void run() { + while (!closed) { + try { long now = System.currentTimeMillis(); Set idsToRemove = new HashSet(); - for (ConnectionEntry entry : connections.values()) - { + for (ConnectionEntry entry : connections.values()) { final RemotingConnection conn = entry.connection; boolean flush = true; - if (entry.ttl != -1) - { - if (!conn.checkDataReceived()) - { - if (now >= entry.lastCheck + entry.ttl) - { + if (entry.ttl != -1) { + if (!conn.checkDataReceived()) { + if (now >= entry.lastCheck + entry.ttl) { idsToRemove.add(conn.getID()); flush = false; } } - else - { + else { entry.lastCheck = now; } } - if (flush) - { - flushExecutor.execute(new Runnable() - { - public void run() - { - try - { + if (flush) { + flushExecutor.execute(new Runnable() { + public void run() { + try { // this is using a different thread // as if anything wrong happens on flush // failure detection could be affected conn.flush(); } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e); } @@ -790,11 +668,9 @@ public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycle } } - for (Object id : idsToRemove) - { + for (Object id : idsToRemove) { RemotingConnection conn = getConnection(id); - if (conn != null) - { + if (conn != null) { conn.fail(ActiveMQMessageBundle.BUNDLE.clientExited(conn.getRemoteAddress())); removeConnection(id); } @@ -803,18 +679,15 @@ public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycle if (latch.await(pauseInterval, TimeUnit.MILLISECONDS)) return; } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQServerLogger.LOGGER.errorOnFailureCheck(e); } } } } - protected void updateProtocols() - { - for (ProtocolManager protocolManager : this.protocolMap.values()) - { + protected void updateProtocols() { + for (ProtocolManager protocolManager : this.protocolMap.values()) { protocolManager.updateInterceptors(incomingInterceptors, outgoingInterceptors); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/replication/ReplicatedJournal.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/replication/ReplicatedJournal.java index d96dbe187e..ab33e19238 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/replication/ReplicatedJournal.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/replication/ReplicatedJournal.java @@ -41,13 +41,11 @@ import org.apache.activemq.artemis.core.replication.ReplicationManager.ADD_OPERA * * @see org.apache.activemq.artemis.core.persistence.impl.journal.JournalStorageManager */ -public class ReplicatedJournal implements Journal -{ +public class ReplicatedJournal implements Journal { private static final boolean trace = false; - private static void trace(final String message) - { + private static void trace(final String message) { System.out.println("ReplicatedJournal::" + message); } @@ -57,9 +55,9 @@ public class ReplicatedJournal implements Journal private final byte journalID; - public ReplicatedJournal(final byte journalID, final Journal localJournal, - final ReplicationManager replicationManager) - { + public ReplicatedJournal(final byte journalID, + final Journal localJournal, + final ReplicationManager replicationManager) { super(); this.journalID = journalID; this.localJournal = localJournal; @@ -74,15 +72,18 @@ public class ReplicatedJournal implements Journal * @throws Exception * @see org.apache.activemq.artemis.core.journal.Journal#appendAddRecord(long, byte, byte[], boolean) */ - public void appendAddRecord(final long id, final byte recordType, final byte[] record, final boolean sync) throws Exception - { + public void appendAddRecord(final long id, + final byte recordType, + final byte[] record, + final boolean sync) throws Exception { this.appendAddRecord(id, recordType, new ByteArrayEncoding(record), sync); } - public void appendAddRecord(final long id, final byte recordType, final EncodingSupport record, final boolean sync) throws Exception - { - if (ReplicatedJournal.trace) - { + public void appendAddRecord(final long id, + final byte recordType, + final EncodingSupport record, + final boolean sync) throws Exception { + if (ReplicatedJournal.trace) { ReplicatedJournal.trace("Append record id = " + id + " recordType = " + recordType); } replicationManager.appendUpdateRecord(journalID, ADD_OPERATION_TYPE.ADD, id, recordType, record); @@ -101,10 +102,8 @@ public class ReplicatedJournal implements Journal final byte recordType, final EncodingSupport record, final boolean sync, - final IOCompletion completionCallback) throws Exception - { - if (ReplicatedJournal.trace) - { + final IOCompletion completionCallback) throws Exception { + if (ReplicatedJournal.trace) { ReplicatedJournal.trace("Append record id = " + id + " recordType = " + recordType); } replicationManager.appendUpdateRecord(journalID, ADD_OPERATION_TYPE.ADD, id, recordType, record); @@ -119,8 +118,10 @@ public class ReplicatedJournal implements Journal * @throws Exception * @see org.apache.activemq.artemis.core.journal.Journal#appendAddRecordTransactional(long, long, byte, byte[]) */ - public void appendAddRecordTransactional(final long txID, final long id, final byte recordType, final byte[] record) throws Exception - { + public void appendAddRecordTransactional(final long txID, + final long id, + final byte recordType, + final byte[] record) throws Exception { this.appendAddRecordTransactional(txID, id, recordType, new ByteArrayEncoding(record)); } @@ -135,10 +136,8 @@ public class ReplicatedJournal implements Journal public void appendAddRecordTransactional(final long txID, final long id, final byte recordType, - final EncodingSupport record) throws Exception - { - if (ReplicatedJournal.trace) - { + final EncodingSupport record) throws Exception { + if (ReplicatedJournal.trace) { ReplicatedJournal.trace("Append record TXid = " + id + " recordType = " + recordType); } replicationManager.appendAddRecordTransactional(journalID, ADD_OPERATION_TYPE.ADD, txID, id, recordType, record); @@ -151,37 +150,33 @@ public class ReplicatedJournal implements Journal * @throws Exception * @see org.apache.activemq.artemis.core.journal.Journal#appendCommitRecord(long, boolean) */ - public void appendCommitRecord(final long txID, final boolean sync) throws Exception - { - if (ReplicatedJournal.trace) - { + public void appendCommitRecord(final long txID, final boolean sync) throws Exception { + if (ReplicatedJournal.trace) { ReplicatedJournal.trace("AppendCommit " + txID); } replicationManager.appendCommitRecord(journalID, txID, sync, true); localJournal.appendCommitRecord(txID, sync); } - public void appendCommitRecord(final long txID, final boolean sync, final IOCompletion callback) throws Exception - { - if (ReplicatedJournal.trace) - { + public void appendCommitRecord(final long txID, final boolean sync, final IOCompletion callback) throws Exception { + if (ReplicatedJournal.trace) { ReplicatedJournal.trace("AppendCommit " + txID); } replicationManager.appendCommitRecord(journalID, txID, sync, true); localJournal.appendCommitRecord(txID, sync, callback); } - public void appendCommitRecord(long txID, boolean sync, IOCompletion callback, boolean lineUpContext) throws Exception - { - if (ReplicatedJournal.trace) - { + public void appendCommitRecord(long txID, + boolean sync, + IOCompletion callback, + boolean lineUpContext) throws Exception { + if (ReplicatedJournal.trace) { ReplicatedJournal.trace("AppendCommit " + txID); } replicationManager.appendCommitRecord(journalID, txID, sync, lineUpContext); localJournal.appendCommitRecord(txID, sync, callback, lineUpContext); } - /** * @param id * @param sync @@ -189,10 +184,8 @@ public class ReplicatedJournal implements Journal * @see org.apache.activemq.artemis.core.journal.Journal#appendDeleteRecord(long, boolean) */ @Override - public void appendDeleteRecord(final long id, final boolean sync) throws Exception - { - if (ReplicatedJournal.trace) - { + public void appendDeleteRecord(final long id, final boolean sync) throws Exception { + if (ReplicatedJournal.trace) { ReplicatedJournal.trace("AppendDelete " + id); } replicationManager.appendDeleteRecord(journalID, id); @@ -200,10 +193,10 @@ public class ReplicatedJournal implements Journal } @Override - public void appendDeleteRecord(final long id, final boolean sync, final IOCompletion completionCallback) throws Exception - { - if (ReplicatedJournal.trace) - { + public void appendDeleteRecord(final long id, + final boolean sync, + final IOCompletion completionCallback) throws Exception { + if (ReplicatedJournal.trace) { ReplicatedJournal.trace("AppendDelete " + id); } replicationManager.appendDeleteRecord(journalID, id); @@ -217,8 +210,7 @@ public class ReplicatedJournal implements Journal * @throws Exception * @see org.apache.activemq.artemis.core.journal.Journal#appendDeleteRecordTransactional(long, long, byte[]) */ - public void appendDeleteRecordTransactional(final long txID, final long id, final byte[] record) throws Exception - { + public void appendDeleteRecordTransactional(final long txID, final long id, final byte[] record) throws Exception { this.appendDeleteRecordTransactional(txID, id, new ByteArrayEncoding(record)); } @@ -229,10 +221,10 @@ public class ReplicatedJournal implements Journal * @throws Exception * @see org.apache.activemq.artemis.core.journal.Journal#appendDeleteRecordTransactional(long, long, org.apache.activemq.artemis.core.journal.EncodingSupport) */ - public void appendDeleteRecordTransactional(final long txID, final long id, final EncodingSupport record) throws Exception - { - if (ReplicatedJournal.trace) - { + public void appendDeleteRecordTransactional(final long txID, + final long id, + final EncodingSupport record) throws Exception { + if (ReplicatedJournal.trace) { ReplicatedJournal.trace("AppendDelete txID=" + txID + " id=" + id); } replicationManager.appendDeleteRecordTransactional(journalID, txID, id, record); @@ -245,10 +237,8 @@ public class ReplicatedJournal implements Journal * @throws Exception * @see org.apache.activemq.artemis.core.journal.Journal#appendDeleteRecordTransactional(long, long) */ - public void appendDeleteRecordTransactional(final long txID, final long id) throws Exception - { - if (ReplicatedJournal.trace) - { + public void appendDeleteRecordTransactional(final long txID, final long id) throws Exception { + if (ReplicatedJournal.trace) { ReplicatedJournal.trace("AppendDelete (noencoding) txID=" + txID + " id=" + id); } replicationManager.appendDeleteRecordTransactional(journalID, txID, id); @@ -262,8 +252,7 @@ public class ReplicatedJournal implements Journal * @throws Exception * @see org.apache.activemq.artemis.core.journal.Journal#appendPrepareRecord(long, byte[], boolean) */ - public void appendPrepareRecord(final long txID, final byte[] transactionData, final boolean sync) throws Exception - { + public void appendPrepareRecord(final long txID, final byte[] transactionData, final boolean sync) throws Exception { this.appendPrepareRecord(txID, new ByteArrayEncoding(transactionData), sync); } @@ -274,10 +263,10 @@ public class ReplicatedJournal implements Journal * @throws Exception * @see org.apache.activemq.artemis.core.journal.Journal#appendPrepareRecord(long, org.apache.activemq.artemis.core.journal.EncodingSupport, boolean) */ - public void appendPrepareRecord(final long txID, final EncodingSupport transactionData, final boolean sync) throws Exception - { - if (ReplicatedJournal.trace) - { + public void appendPrepareRecord(final long txID, + final EncodingSupport transactionData, + final boolean sync) throws Exception { + if (ReplicatedJournal.trace) { ReplicatedJournal.trace("AppendPrepare txID=" + txID); } replicationManager.appendPrepareRecord(journalID, txID, transactionData); @@ -288,10 +277,8 @@ public class ReplicatedJournal implements Journal public void appendPrepareRecord(final long txID, final EncodingSupport transactionData, final boolean sync, - final IOCompletion callback) throws Exception - { - if (ReplicatedJournal.trace) - { + final IOCompletion callback) throws Exception { + if (ReplicatedJournal.trace) { ReplicatedJournal.trace("AppendPrepare txID=" + txID); } replicationManager.appendPrepareRecord(journalID, txID, transactionData); @@ -304,20 +291,16 @@ public class ReplicatedJournal implements Journal * @throws Exception * @see org.apache.activemq.artemis.core.journal.Journal#appendRollbackRecord(long, boolean) */ - public void appendRollbackRecord(final long txID, final boolean sync) throws Exception - { - if (ReplicatedJournal.trace) - { + public void appendRollbackRecord(final long txID, final boolean sync) throws Exception { + if (ReplicatedJournal.trace) { ReplicatedJournal.trace("AppendRollback " + txID); } replicationManager.appendRollbackRecord(journalID, txID); localJournal.appendRollbackRecord(txID, sync); } - public void appendRollbackRecord(final long txID, final boolean sync, final IOCompletion callback) throws Exception - { - if (ReplicatedJournal.trace) - { + public void appendRollbackRecord(final long txID, final boolean sync, final IOCompletion callback) throws Exception { + if (ReplicatedJournal.trace) { ReplicatedJournal.trace("AppendRollback " + txID); } replicationManager.appendRollbackRecord(journalID, txID); @@ -332,8 +315,10 @@ public class ReplicatedJournal implements Journal * @throws Exception * @see org.apache.activemq.artemis.core.journal.Journal#appendUpdateRecord(long, byte, byte[], boolean) */ - public void appendUpdateRecord(final long id, final byte recordType, final byte[] record, final boolean sync) throws Exception - { + public void appendUpdateRecord(final long id, + final byte recordType, + final byte[] record, + final boolean sync) throws Exception { this.appendUpdateRecord(id, recordType, new ByteArrayEncoding(record), sync); } @@ -346,10 +331,11 @@ public class ReplicatedJournal implements Journal * @see org.apache.activemq.artemis.core.journal.Journal#appendUpdateRecord(long, byte, org.apache.activemq.artemis.core.journal.EncodingSupport, boolean) */ @Override - public void appendUpdateRecord(final long id, final byte recordType, final EncodingSupport record, final boolean sync) throws Exception - { - if (ReplicatedJournal.trace) - { + public void appendUpdateRecord(final long id, + final byte recordType, + final EncodingSupport record, + final boolean sync) throws Exception { + if (ReplicatedJournal.trace) { ReplicatedJournal.trace("AppendUpdateRecord id = " + id + " , recordType = " + recordType); } replicationManager.appendUpdateRecord(journalID, ADD_OPERATION_TYPE.UPDATE, id, recordType, record); @@ -361,10 +347,8 @@ public class ReplicatedJournal implements Journal final byte journalRecordType, final EncodingSupport record, final boolean sync, - final IOCompletion completionCallback) throws Exception - { - if (ReplicatedJournal.trace) - { + final IOCompletion completionCallback) throws Exception { + if (ReplicatedJournal.trace) { ReplicatedJournal.trace("AppendUpdateRecord id = " + id + " , recordType = " + journalRecordType); } replicationManager.appendUpdateRecord(journalID, ADD_OPERATION_TYPE.UPDATE, id, journalRecordType, record); @@ -379,9 +363,10 @@ public class ReplicatedJournal implements Journal * @throws Exception * @see org.apache.activemq.artemis.core.journal.Journal#appendUpdateRecordTransactional(long, long, byte, byte[]) */ - public void appendUpdateRecordTransactional(final long txID, final long id, final byte recordType, - final byte[] record) throws Exception - { + public void appendUpdateRecordTransactional(final long txID, + final long id, + final byte recordType, + final byte[] record) throws Exception { this.appendUpdateRecordTransactional(txID, id, recordType, new ByteArrayEncoding(record)); } @@ -393,15 +378,14 @@ public class ReplicatedJournal implements Journal * @throws Exception * @see org.apache.activemq.artemis.core.journal.Journal#appendUpdateRecordTransactional(long, long, byte, org.apache.activemq.artemis.core.journal.EncodingSupport) */ - public void appendUpdateRecordTransactional(final long txID, final long id, final byte recordType, - final EncodingSupport record) throws Exception - { - if (ReplicatedJournal.trace) - { + public void appendUpdateRecordTransactional(final long txID, + final long id, + final byte recordType, + final EncodingSupport record) throws Exception { + if (ReplicatedJournal.trace) { ReplicatedJournal.trace("AppendUpdateRecord txid=" + txID + " id = " + id + " , recordType = " + recordType); } - replicationManager.appendAddRecordTransactional(journalID, ADD_OPERATION_TYPE.UPDATE, txID, id, recordType, - record); + replicationManager.appendAddRecordTransactional(journalID, ADD_OPERATION_TYPE.UPDATE, txID, id, recordType, record); localJournal.appendUpdateRecordTransactional(txID, id, recordType, record); } @@ -409,25 +393,21 @@ public class ReplicatedJournal implements Journal * @param committedRecords * @param preparedTransactions * @param transactionFailure - * * @throws Exception * @see org.apache.activemq.artemis.core.journal.Journal#load(java.util.List, java.util.List, org.apache.activemq.artemis.core.journal.TransactionFailureCallback) */ public JournalLoadInformation load(final List committedRecords, final List preparedTransactions, - final TransactionFailureCallback transactionFailure) throws Exception - { + final TransactionFailureCallback transactionFailure) throws Exception { return localJournal.load(committedRecords, preparedTransactions, transactionFailure); } /** * @param reloadManager - * * @throws Exception * @see org.apache.activemq.artemis.core.journal.Journal#load(org.apache.activemq.artemis.core.journal.LoaderCallback) */ - public JournalLoadInformation load(final LoaderCallback reloadManager) throws Exception - { + public JournalLoadInformation load(final LoaderCallback reloadManager) throws Exception { return localJournal.load(reloadManager); } @@ -435,8 +415,7 @@ public class ReplicatedJournal implements Journal * @param pages * @see org.apache.activemq.artemis.core.journal.Journal#perfBlast(int) */ - public void perfBlast(final int pages) - { + public void perfBlast(final int pages) { localJournal.perfBlast(pages); } @@ -444,8 +423,7 @@ public class ReplicatedJournal implements Journal * @throws Exception * @see org.apache.activemq.artemis.core.server.ActiveMQComponent#start() */ - public void start() throws Exception - { + public void start() throws Exception { localJournal.start(); } @@ -453,110 +431,91 @@ public class ReplicatedJournal implements Journal * @throws Exception * @see org.apache.activemq.artemis.core.server.ActiveMQComponent#stop() */ - public void stop() throws Exception - { + public void stop() throws Exception { localJournal.stop(); } - public int getAlignment() throws Exception - { + public int getAlignment() throws Exception { return localJournal.getAlignment(); } - public boolean isStarted() - { + public boolean isStarted() { return localJournal.isStarted(); } @Override - public JournalLoadInformation loadInternalOnly() throws Exception - { + public JournalLoadInformation loadInternalOnly() throws Exception { return localJournal.loadInternalOnly(); } - public int getNumberOfRecords() - { + public int getNumberOfRecords() { return localJournal.getNumberOfRecords(); } - public void runDirectJournalBlast() throws Exception - { + public void runDirectJournalBlast() throws Exception { localJournal.runDirectJournalBlast(); } - public int getUserVersion() - { + public int getUserVersion() { return localJournal.getUserVersion(); } - public void lineUpContext(IOCompletion callback) - { - ((OperationContext)callback).replicationLineUp(); + public void lineUpContext(IOCompletion callback) { + ((OperationContext) callback).replicationLineUp(); localJournal.lineUpContext(callback); } @Override - public JournalLoadInformation loadSyncOnly(JournalState state) throws Exception - { + public JournalLoadInformation loadSyncOnly(JournalState state) throws Exception { return localJournal.loadSyncOnly(state); } @Override - public Map createFilesForBackupSync(long[] fileIds) throws Exception - { + public Map createFilesForBackupSync(long[] fileIds) throws Exception { throw new UnsupportedOperationException("This method should only be called at a replicating backup"); } @Override - public void synchronizationLock() - { + public void synchronizationLock() { throw new UnsupportedOperationException(); } @Override - public void synchronizationUnlock() - { + public void synchronizationUnlock() { throw new UnsupportedOperationException(); } @Override - public void forceMoveNextFile() - { + public void forceMoveNextFile() { throw new UnsupportedOperationException(); } @Override - public JournalFile[] getDataFiles() - { + public JournalFile[] getDataFiles() { throw new UnsupportedOperationException(); } @Override - public SequentialFileFactory getFileFactory() - { + public SequentialFileFactory getFileFactory() { throw new UnsupportedOperationException(); } - public int getFileSize() - { + public int getFileSize() { return localJournal.getFileSize(); } @Override - public void scheduleCompactAndBlock(int timeout) throws Exception - { + public void scheduleCompactAndBlock(int timeout) throws Exception { localJournal.scheduleCompactAndBlock(timeout); } @Override - public void replicationSyncPreserveOldFiles() - { + public void replicationSyncPreserveOldFiles() { throw new UnsupportedOperationException("should never get called"); } @Override - public void replicationSyncFinished() - { + public void replicationSyncFinished() { throw new UnsupportedOperationException("should never get called"); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/replication/ReplicatedLargeMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/replication/ReplicatedLargeMessage.java index 47768dee17..3b6327a89e 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/replication/ReplicatedLargeMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/replication/ReplicatedLargeMessage.java @@ -25,8 +25,8 @@ import org.apache.activemq.artemis.api.core.Message; * * @see org.apache.activemq.artemis.core.persistence.impl.journal.LargeServerMessageInSync */ -public interface ReplicatedLargeMessage -{ +public interface ReplicatedLargeMessage { + /** * @see org.apache.activemq.artemis.core.server.LargeServerMessage#setDurable(boolean) */ diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/replication/ReplicationEndpoint.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/replication/ReplicationEndpoint.java index afb1e77f97..c96a10f6e3 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/replication/ReplicationEndpoint.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/replication/ReplicationEndpoint.java @@ -84,8 +84,8 @@ import org.apache.activemq.artemis.core.server.impl.SharedNothingBackupActivatio * Handles all the synchronization necessary for replication on the backup side (that is the * backup's side of the "remote backup" use case). */ -public final class ReplicationEndpoint implements ChannelHandler, ActiveMQComponent -{ +public final class ReplicationEndpoint implements ChannelHandler, ActiveMQComponent { + private static final boolean trace = ActiveMQServerLogger.LOGGER.isTraceEnabled(); private final IOCriticalErrorListener criticalErrorListener; @@ -101,8 +101,7 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon /** * Files reserved in each journal for synchronization of existing data from the 'live' server. */ - private final Map> filesReservedForSync = - new HashMap>(); + private final Map> filesReservedForSync = new HashMap>(); /** * Used to hold the real Journals before the backup is synchronized. This field should be @@ -114,10 +113,8 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon private PagingManager pageManager; - private final ConcurrentMap> pageIndex = - new ConcurrentHashMap>(); - private final ConcurrentMap largeMessages = - new ConcurrentHashMap(); + private final ConcurrentMap> pageIndex = new ConcurrentHashMap>(); + private final ConcurrentMap largeMessages = new ConcurrentHashMap(); // Used on tests, to simulate failures on delete pages private boolean deletePages = true; @@ -128,9 +125,10 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon private Executor executor; // Constructors -------------------------------------------------- - public ReplicationEndpoint(final ActiveMQServerImpl server, IOCriticalErrorListener criticalErrorListener, - boolean wantedFailBack, SharedNothingBackupActivation activation) - { + public ReplicationEndpoint(final ActiveMQServerImpl server, + IOCriticalErrorListener criticalErrorListener, + boolean wantedFailBack, + SharedNothingBackupActivation activation) { this.server = server; this.criticalErrorListener = criticalErrorListener; this.wantedFailBack = wantedFailBack; @@ -139,17 +137,13 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon // Public -------------------------------------------------------- - public synchronized void registerJournal(final byte id, final Journal journal) - { - if (journals == null || id >= journals.length) - { + public synchronized void registerJournal(final byte id, final Journal journal) { + if (journals == null || id >= journals.length) { Journal[] oldJournals = journals; journals = new Journal[id + 1]; - if (oldJournals != null) - { - for (int i = 0; i < oldJournals.length; i++) - { + if (oldJournals != null) { + for (int i = 0; i < oldJournals.length; i++) { journals[i] = oldJournals[i]; } } @@ -159,93 +153,71 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon } @Override - public void handlePacket(final Packet packet) - { + public void handlePacket(final Packet packet) { PacketImpl response = new ReplicationResponseMessage(); final byte type = packet.getType(); - try - { - if (!started) - { + try { + if (!started) { return; } - if (type == PacketImpl.REPLICATION_APPEND) - { + if (type == PacketImpl.REPLICATION_APPEND) { handleAppendAddRecord((ReplicationAddMessage) packet); } - else if (type == PacketImpl.REPLICATION_APPEND_TX) - { + else if (type == PacketImpl.REPLICATION_APPEND_TX) { handleAppendAddTXRecord((ReplicationAddTXMessage) packet); } - else if (type == PacketImpl.REPLICATION_DELETE) - { + else if (type == PacketImpl.REPLICATION_DELETE) { handleAppendDelete((ReplicationDeleteMessage) packet); } - else if (type == PacketImpl.REPLICATION_DELETE_TX) - { + else if (type == PacketImpl.REPLICATION_DELETE_TX) { handleAppendDeleteTX((ReplicationDeleteTXMessage) packet); } - else if (type == PacketImpl.REPLICATION_PREPARE) - { + else if (type == PacketImpl.REPLICATION_PREPARE) { handlePrepare((ReplicationPrepareMessage) packet); } - else if (type == PacketImpl.REPLICATION_COMMIT_ROLLBACK) - { + else if (type == PacketImpl.REPLICATION_COMMIT_ROLLBACK) { handleCommitRollback((ReplicationCommitMessage) packet); } - else if (type == PacketImpl.REPLICATION_PAGE_WRITE) - { + else if (type == PacketImpl.REPLICATION_PAGE_WRITE) { handlePageWrite((ReplicationPageWriteMessage) packet); } - else if (type == PacketImpl.REPLICATION_PAGE_EVENT) - { + else if (type == PacketImpl.REPLICATION_PAGE_EVENT) { handlePageEvent((ReplicationPageEventMessage) packet); } - else if (type == PacketImpl.REPLICATION_LARGE_MESSAGE_BEGIN) - { + else if (type == PacketImpl.REPLICATION_LARGE_MESSAGE_BEGIN) { handleLargeMessageBegin((ReplicationLargeMessageBeginMessage) packet); } - else if (type == PacketImpl.REPLICATION_LARGE_MESSAGE_WRITE) - { + else if (type == PacketImpl.REPLICATION_LARGE_MESSAGE_WRITE) { handleLargeMessageWrite((ReplicationLargeMessageWriteMessage) packet); } - else if (type == PacketImpl.REPLICATION_LARGE_MESSAGE_END) - { + else if (type == PacketImpl.REPLICATION_LARGE_MESSAGE_END) { handleLargeMessageEnd((ReplicationLargeMessageEndMessage) packet); } - else if (type == PacketImpl.REPLICATION_START_FINISH_SYNC) - { + else if (type == PacketImpl.REPLICATION_START_FINISH_SYNC) { handleStartReplicationSynchronization((ReplicationStartSyncMessage) packet); } - else if (type == PacketImpl.REPLICATION_SYNC_FILE) - { + else if (type == PacketImpl.REPLICATION_SYNC_FILE) { handleReplicationSynchronization((ReplicationSyncFileMessage) packet); } - else if (type == PacketImpl.REPLICATION_SCHEDULED_FAILOVER) - { + else if (type == PacketImpl.REPLICATION_SCHEDULED_FAILOVER) { handleLiveStopping((ReplicationLiveIsStoppingMessage) packet); } - else if (type == PacketImpl.BACKUP_REGISTRATION_FAILED) - { + else if (type == PacketImpl.BACKUP_REGISTRATION_FAILED) { handleFatalError((BackupReplicationStartFailedMessage) packet); } - else - { + else { ActiveMQServerLogger.LOGGER.invalidPacketForReplication(packet); } } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { ActiveMQServerLogger.LOGGER.errorHandlingReplicationPacket(e, packet); response = new ActiveMQExceptionMessage(e); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorHandlingReplicationPacket(e, packet); - response = - new ActiveMQExceptionMessage(ActiveMQMessageBundle.BUNDLE.replicationUnhandledError(e)); + response = new ActiveMQExceptionMessage(ActiveMQMessageBundle.BUNDLE.replicationUnhandledError(e)); } channel.send(response); } @@ -253,8 +225,7 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon /** * @param packet */ - private void handleFatalError(BackupReplicationStartFailedMessage packet) - { + private void handleFatalError(BackupReplicationStartFailedMessage packet) { ActiveMQServerLogger.LOGGER.errorStartingReplication(packet.getRegistrationProblem()); server.stopTheServer(false); } @@ -263,21 +234,17 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon * @param packet * @throws ActiveMQException */ - private void handleLiveStopping(ReplicationLiveIsStoppingMessage packet) throws ActiveMQException - { + private void handleLiveStopping(ReplicationLiveIsStoppingMessage packet) throws ActiveMQException { activation.remoteFailOver(packet.isFinalMessage()); } - public boolean isStarted() - { + public boolean isStarted() { return started; } - public synchronized void start() throws Exception - { + public synchronized void start() throws Exception { Configuration config = server.getConfiguration(); - try - { + try { storageManager = server.getStorageManager(); storageManager.start(); @@ -286,81 +253,60 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon journalsHolder.put(JournalContent.BINDINGS, storageManager.getBindingsJournal()); journalsHolder.put(JournalContent.MESSAGES, storageManager.getMessageJournal()); - for (JournalContent jc : EnumSet.allOf(JournalContent.class)) - { + for (JournalContent jc : EnumSet.allOf(JournalContent.class)) { filesReservedForSync.put(jc, new HashMap()); // We only need to load internal structures on the backup... journalLoadInformation[jc.typeByte] = journalsHolder.get(jc).loadSyncOnly(JournalState.SYNCING); } - pageManager = - new PagingManagerImpl(new PagingStoreFactoryNIO(storageManager, config.getPagingLocation(), - config.getJournalBufferSize_NIO(), - server.getScheduledPool(), - server.getExecutorFactory(), - config.isJournalSyncNonTransactional(), criticalErrorListener), - server.getAddressSettingsRepository()); + pageManager = new PagingManagerImpl(new PagingStoreFactoryNIO(storageManager, config.getPagingLocation(), config.getJournalBufferSize_NIO(), server.getScheduledPool(), server.getExecutorFactory(), config.isJournalSyncNonTransactional(), criticalErrorListener), server.getAddressSettingsRepository()); pageManager.start(); started = true; } - catch (Exception e) - { + catch (Exception e) { if (server.isStarted()) throw e; } } - public synchronized void stop() throws Exception - { - if (!started) - { + public synchronized void stop() throws Exception { + if (!started) { return; } // Channel may be null if there isn't a connection to a live server - if (channel != null) - { + if (channel != null) { channel.close(); } - for (ReplicatedLargeMessage largeMessage : largeMessages.values()) - { + for (ReplicatedLargeMessage largeMessage : largeMessages.values()) { largeMessage.releaseResources(); } largeMessages.clear(); - for (Entry> entry : filesReservedForSync - .entrySet()) - { - for (JournalSyncFile filesReserved : entry.getValue().values()) - { + for (Entry> entry : filesReservedForSync.entrySet()) { + for (JournalSyncFile filesReserved : entry.getValue().values()) { filesReserved.close(); } } filesReservedForSync.clear(); - if (journals != null) - { - for (Journal j : journals) - { + if (journals != null) { + for (Journal j : journals) { if (j instanceof FileWrapperJournal) j.stop(); } } - for (ConcurrentMap map : pageIndex.values()) - { - for (Page page : map.values()) - { - try - { + for (ConcurrentMap map : pageIndex.values()) { + for (Page page : map.values()) { + try { page.sync(); page.close(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorClosingPageOnReplication(e); } } @@ -369,12 +315,10 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon pageIndex.clear(); final CountDownLatch latch = new CountDownLatch(1); - executor.execute(new Runnable() - { + executor.execute(new Runnable() { @Override - public void run() - { + public void run() { latch.countDown(); } }); @@ -386,33 +330,25 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon started = false; } - - public Channel getChannel() - { + public Channel getChannel() { return channel; } - public void setChannel(final Channel channel) - { + public void setChannel(final Channel channel) { this.channel = channel; } - public void compareJournalInformation(final JournalLoadInformation[] journalInformation) throws ActiveMQException - { - if (!activation.isRemoteBackupUpToDate()) - { + public void compareJournalInformation(final JournalLoadInformation[] journalInformation) throws ActiveMQException { + if (!activation.isRemoteBackupUpToDate()) { throw ActiveMQMessageBundle.BUNDLE.journalsNotInSync(); } - if (journalLoadInformation == null || journalLoadInformation.length != journalInformation.length) - { + if (journalLoadInformation == null || journalLoadInformation.length != journalInformation.length) { throw ActiveMQMessageBundle.BUNDLE.replicationTooManyJournals(); } - for (int i = 0; i < journalInformation.length; i++) - { - if (!journalInformation[i].equals(journalLoadInformation[i])) - { + for (int i = 0; i < journalInformation.length; i++) { + if (!journalInformation[i].equals(journalLoadInformation[i])) { ActiveMQServerLogger.LOGGER.journalcomparisonMismatch(journalParametersToString(journalInformation)); throw ActiveMQMessageBundle.BUNDLE.replicationTooManyJournals(); } @@ -423,16 +359,14 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon /** * Used on tests only. To simulate missing page deletes */ - public void setDeletePages(final boolean deletePages) - { + public void setDeletePages(final boolean deletePages) { this.deletePages = deletePages; } /** * @param journalInformation */ - private String journalParametersToString(final JournalLoadInformation[] journalInformation) - { + private String journalParametersToString(final JournalLoadInformation[] journalInformation) { return "**********************************************************\n" + "parameters:\n" + "BindingsImpl = " + journalInformation[0] + @@ -453,14 +387,11 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon "**********************************************************"; } - private void finishSynchronization(String liveID) throws Exception - { - for (JournalContent jc : EnumSet.allOf(JournalContent.class)) - { + private void finishSynchronization(String liveID) throws Exception { + for (JournalContent jc : EnumSet.allOf(JournalContent.class)) { Journal journal = journalsHolder.remove(jc); journal.synchronizationLock(); - try - { + try { // files should be already in place. filesReservedForSync.remove(jc); registerJournal(jc.typeByte, journal); @@ -468,17 +399,14 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon journal.start(); journal.loadSyncOnly(JournalState.SYNCING_UP_TO_DATE); } - finally - { + finally { journal.synchronizationUnlock(); } } ByteBuffer buffer = ByteBuffer.allocate(4 * 1024); - for (Entry entry : largeMessages.entrySet()) - { + for (Entry entry : largeMessages.entrySet()) { ReplicatedLargeMessage lm = entry.getValue(); - if (lm instanceof LargeServerMessageInSync) - { + if (lm instanceof LargeServerMessageInSync) { LargeServerMessageInSync lmSync = (LargeServerMessageInSync) lm; lmSync.joinSyncedData(buffer); } @@ -497,18 +425,14 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon * @param msg * @throws Exception */ - private synchronized void handleReplicationSynchronization(ReplicationSyncFileMessage msg) throws Exception - { + private synchronized void handleReplicationSynchronization(ReplicationSyncFileMessage msg) throws Exception { Long id = Long.valueOf(msg.getId()); byte[] data = msg.getData(); SequentialFile channel1; - switch (msg.getFileType()) - { - case LARGE_MESSAGE: - { + switch (msg.getFileType()) { + case LARGE_MESSAGE: { ReplicatedLargeMessage largeMessage = lookupLargeMessage(id, false); - if (!(largeMessage instanceof LargeServerMessageInSync)) - { + if (!(largeMessage instanceof LargeServerMessageInSync)) { ActiveMQServerLogger.LOGGER.largeMessageIncompatible(); return; } @@ -516,18 +440,15 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon channel1 = largeMessageInSync.getSyncFile(); break; } - case PAGE: - { + case PAGE: { Page page = getPage(msg.getPageStore(), (int) msg.getId()); channel1 = page.getFile(); break; } - case JOURNAL: - { + case JOURNAL: { JournalSyncFile journalSyncFile = filesReservedForSync.get(msg.getJournalContent()).get(id); FileChannel channel2 = journalSyncFile.getChannel(); - if (data == null) - { + if (data == null) { channel2.close(); return; } @@ -538,14 +459,12 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon throw ActiveMQMessageBundle.BUNDLE.replicationUnhandledFileType(msg.getFileType()); } - if (data == null) - { + if (data == null) { channel1.close(); return; } - if (!channel1.isOpen()) - { + if (!channel1.isOpen()) { channel1.open(); } channel1.writeDirect(ByteBuffer.wrap(data), true); @@ -558,53 +477,43 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon * @param packet * @throws Exception */ - private void handleStartReplicationSynchronization(final ReplicationStartSyncMessage packet) throws Exception - { - if (activation.isRemoteBackupUpToDate()) - { + private void handleStartReplicationSynchronization(final ReplicationStartSyncMessage packet) throws Exception { + if (activation.isRemoteBackupUpToDate()) { throw ActiveMQMessageBundle.BUNDLE.replicationBackupUpToDate(); } - - synchronized (this) - { + synchronized (this) { if (!started) return; - if (packet.isSynchronizationFinished()) - { + if (packet.isSynchronizationFinished()) { finishSynchronization(packet.getNodeID()); return; } - switch (packet.getDataType()) - { + switch (packet.getDataType()) { case LargeMessages: - for (long msgID : packet.getFileIds()) - { + for (long msgID : packet.getFileIds()) { createLargeMessage(msgID, true); } break; case JournalBindings: case JournalMessages: - if (wantedFailBack && !packet.isServerToFailBack()) - { + if (wantedFailBack && !packet.isServerToFailBack()) { ActiveMQServerLogger.LOGGER.autoFailBackDenied(); } final JournalContent journalContent = SyncDataType.getJournalContentType(packet.getDataType()); final Journal journal = journalsHolder.get(journalContent); - if (packet.getNodeID() != null) - { + if (packet.getNodeID() != null) { // At the start of replication, we still do not know which is the nodeID that the live uses. // This is the point where the backup gets this information. backupQuorum.liveIDSet(packet.getNodeID()); } Map mapToFill = filesReservedForSync.get(journalContent); - for (Entry entry : journal.createFilesForBackupSync(packet.getFileIds()).entrySet()) - { + for (Entry entry : journal.createFilesForBackupSync(packet.getFileIds()).entrySet()) { mapToFill.put(entry.getKey(), new JournalSyncFile(entry.getValue())); } FileWrapperJournal syncJournal = new FileWrapperJournal(journal); @@ -616,22 +525,16 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon } } - private void handleLargeMessageEnd(final ReplicationLargeMessageEndMessage packet) - { + private void handleLargeMessageEnd(final ReplicationLargeMessageEndMessage packet) { final ReplicatedLargeMessage message = lookupLargeMessage(packet.getMessageId(), true); - if (message != null) - { - executor.execute(new Runnable() - { + if (message != null) { + executor.execute(new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { message.deleteFile(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorDeletingLargeMessage(e, packet.getMessageId()); } } @@ -642,34 +545,27 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon /** * @param packet */ - private void handleLargeMessageWrite(final ReplicationLargeMessageWriteMessage packet) throws Exception - { + private void handleLargeMessageWrite(final ReplicationLargeMessageWriteMessage packet) throws Exception { ReplicatedLargeMessage message = lookupLargeMessage(packet.getMessageId(), false); - if (message != null) - { + if (message != null) { message.addBytes(packet.getBody()); } } - private ReplicatedLargeMessage lookupLargeMessage(final long messageId, final boolean delete) - { + private ReplicatedLargeMessage lookupLargeMessage(final long messageId, final boolean delete) { ReplicatedLargeMessage message; - if (delete) - { + if (delete) { message = largeMessages.remove(messageId); } - else - { + else { message = largeMessages.get(messageId); - if (message == null) - { + if (message == null) { // No warnings if it's a delete, as duplicate deletes may be sent repeatedly. ActiveMQServerLogger.LOGGER.largeMessageNotAvailable(messageId); } } - return message; } @@ -677,22 +573,18 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon /** * @param packet */ - private void handleLargeMessageBegin(final ReplicationLargeMessageBeginMessage packet) - { + private void handleLargeMessageBegin(final ReplicationLargeMessageBeginMessage packet) { final long id = packet.getMessageId(); createLargeMessage(id, false); ActiveMQServerLogger.LOGGER.trace("Receiving Large Message " + id + " on backup"); } - private void createLargeMessage(final long id, boolean liveToBackupSync) - { + private void createLargeMessage(final long id, boolean liveToBackupSync) { ReplicatedLargeMessage msg; - if (liveToBackupSync) - { + if (liveToBackupSync) { msg = new LargeServerMessageInSync(storageManager); } - else - { + else { msg = storageManager.createLargeMessage(); } @@ -704,15 +596,12 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon /** * @param packet */ - private void handleCommitRollback(final ReplicationCommitMessage packet) throws Exception - { + private void handleCommitRollback(final ReplicationCommitMessage packet) throws Exception { Journal journalToUse = getJournal(packet.getJournalID()); - if (packet.isRollback()) - { + if (packet.isRollback()) { journalToUse.appendRollbackRecord(packet.getTxId(), noSync); } - else - { + else { journalToUse.appendCommitRecord(packet.getTxId(), noSync); } } @@ -720,8 +609,7 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon /** * @param packet */ - private void handlePrepare(final ReplicationPrepareMessage packet) throws Exception - { + private void handlePrepare(final ReplicationPrepareMessage packet) throws Exception { Journal journalToUse = getJournal(packet.getJournalID()); journalToUse.appendPrepareRecord(packet.getTxId(), packet.getRecordData(), noSync); } @@ -729,8 +617,7 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon /** * @param packet */ - private void handleAppendDeleteTX(final ReplicationDeleteTXMessage packet) throws Exception - { + private void handleAppendDeleteTX(final ReplicationDeleteTXMessage packet) throws Exception { Journal journalToUse = getJournal(packet.getJournalID()); journalToUse.appendDeleteRecordTransactional(packet.getTxId(), packet.getId(), packet.getRecordData()); @@ -739,8 +626,7 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon /** * @param packet */ - private void handleAppendDelete(final ReplicationDeleteMessage packet) throws Exception - { + private void handleAppendDelete(final ReplicationDeleteMessage packet) throws Exception { Journal journalToUse = getJournal(packet.getJournalID()); journalToUse.appendDeleteRecord(packet.getId(), noSync); } @@ -748,23 +634,14 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon /** * @param packet */ - private void handleAppendAddTXRecord(final ReplicationAddTXMessage packet) throws Exception - { + private void handleAppendAddTXRecord(final ReplicationAddTXMessage packet) throws Exception { Journal journalToUse = getJournal(packet.getJournalID()); - if (packet.getOperation() == ADD_OPERATION_TYPE.UPDATE) - { - journalToUse.appendUpdateRecordTransactional(packet.getTxId(), - packet.getId(), - packet.getRecordType(), - packet.getRecordData()); + if (packet.getOperation() == ADD_OPERATION_TYPE.UPDATE) { + journalToUse.appendUpdateRecordTransactional(packet.getTxId(), packet.getId(), packet.getRecordType(), packet.getRecordData()); } - else - { - journalToUse.appendAddRecordTransactional(packet.getTxId(), - packet.getId(), - packet.getRecordType(), - packet.getRecordData()); + else { + journalToUse.appendAddRecordTransactional(packet.getTxId(), packet.getId(), packet.getRecordType(), packet.getRecordData()); } } @@ -772,21 +649,16 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon * @param packet * @throws Exception */ - private void handleAppendAddRecord(final ReplicationAddMessage packet) throws Exception - { + private void handleAppendAddRecord(final ReplicationAddMessage packet) throws Exception { Journal journalToUse = getJournal(packet.getJournalID()); - if (packet.getRecord() == ADD_OPERATION_TYPE.UPDATE) - { - if (ReplicationEndpoint.trace) - { + if (packet.getRecord() == ADD_OPERATION_TYPE.UPDATE) { + if (ReplicationEndpoint.trace) { ActiveMQServerLogger.LOGGER.trace("Endpoint appendUpdate id = " + packet.getId()); } journalToUse.appendUpdateRecord(packet.getId(), packet.getJournalRecordType(), packet.getRecordData(), noSync); } - else - { - if (ReplicationEndpoint.trace) - { + else { + if (ReplicationEndpoint.trace) { ActiveMQServerLogger.LOGGER.trace("Endpoint append id = " + packet.getId()); } journalToUse.appendAddRecord(packet.getId(), packet.getJournalRecordType(), packet.getRecordData(), noSync); @@ -796,28 +668,22 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon /** * @param packet */ - private void handlePageEvent(final ReplicationPageEventMessage packet) throws Exception - { + private void handlePageEvent(final ReplicationPageEventMessage packet) throws Exception { ConcurrentMap pages = getPageMap(packet.getStoreName()); Page page = pages.remove(packet.getPageNumber()); - if (page == null) - { + if (page == null) { page = getPage(packet.getStoreName(), packet.getPageNumber()); } - if (page != null) - { - if (packet.isDelete()) - { - if (deletePages) - { + if (page != null) { + if (packet.isDelete()) { + if (deletePages) { page.delete(null); } } - else - { + else { page.close(); } } @@ -827,8 +693,7 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon /** * @param packet */ - private void handlePageWrite(final ReplicationPageWriteMessage packet) throws Exception - { + private void handlePageWrite(final ReplicationPageWriteMessage packet) throws Exception { PagedMessage pgdMessage = packet.getPagedMessage(); pgdMessage.initMessage(storageManager); ServerMessage msg = pgdMessage.getMessage(); @@ -836,16 +701,13 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon page.write(pgdMessage); } - private ConcurrentMap getPageMap(final SimpleString storeName) - { + private ConcurrentMap getPageMap(final SimpleString storeName) { ConcurrentMap resultIndex = pageIndex.get(storeName); - if (resultIndex == null) - { + if (resultIndex == null) { resultIndex = new ConcurrentHashMap(); ConcurrentMap mapResult = pageIndex.putIfAbsent(storeName, resultIndex); - if (mapResult != null) - { + if (mapResult != null) { resultIndex = mapResult; } } @@ -853,14 +715,12 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon return resultIndex; } - private Page getPage(final SimpleString storeName, final int pageId) throws Exception - { + private Page getPage(final SimpleString storeName, final int pageId) throws Exception { ConcurrentMap map = getPageMap(storeName); Page page = map.get(pageId); - if (page == null) - { + if (page == null) { page = newPage(pageId, storeName, map); } @@ -874,12 +734,10 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon */ private synchronized Page newPage(final int pageId, final SimpleString storeName, - final ConcurrentMap map) throws Exception - { + final ConcurrentMap map) throws Exception { Page page = map.get(pageId); - if (page == null) - { + if (page == null) { page = pageManager.getPageStore(storeName).createPage(pageId); page.open(); map.put(pageId, page); @@ -892,36 +750,31 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon * @param journalID * @return */ - private Journal getJournal(final byte journalID) - { + private Journal getJournal(final byte journalID) { return journals[journalID]; } - public static final class JournalSyncFile - { + public static final class JournalSyncFile { + private FileChannel channel; private final File file; private FileOutputStream fos; - public JournalSyncFile(JournalFile jFile) throws Exception - { + public JournalSyncFile(JournalFile jFile) throws Exception { SequentialFile seqFile = jFile.getFile(); file = seqFile.getJavaFile(); seqFile.close(); } - synchronized FileChannel getChannel() throws Exception - { - if (channel == null) - { + synchronized FileChannel getChannel() throws Exception { + if (channel == null) { fos = new FileOutputStream(file); channel = fos.getChannel(); } return channel; } - synchronized void close() throws IOException - { + synchronized void close() throws IOException { if (fos != null) fos.close(); if (channel != null) @@ -929,8 +782,7 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon } @Override - public String toString() - { + public String toString() { return "JournalSyncFile(file=" + file.getAbsolutePath() + ")"; } } @@ -941,16 +793,14 @@ public final class ReplicationEndpoint implements ChannelHandler, ActiveMQCompon * * @param backupQuorum */ - public synchronized void setBackupQuorum(SharedNothingBackupQuorum backupQuorum) - { + public synchronized void setBackupQuorum(SharedNothingBackupQuorum backupQuorum) { this.backupQuorum = backupQuorum; } /** * @param executor2 */ - public void setExecutor(Executor executor2) - { + public void setExecutor(Executor executor2) { this.executor = executor2; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/replication/ReplicationManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/replication/ReplicationManager.java index 905d7a57d3..fa2b72c8d8 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/replication/ReplicationManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/replication/ReplicationManager.java @@ -73,31 +73,25 @@ import org.apache.activemq.artemis.utils.ExecutorFactory; * * @see ReplicationEndpoint */ -public final class ReplicationManager implements ActiveMQComponent -{ - public enum ADD_OPERATION_TYPE - { - UPDATE - { +public final class ReplicationManager implements ActiveMQComponent { + + public enum ADD_OPERATION_TYPE { + UPDATE { @Override - public boolean toBoolean() - { + public boolean toBoolean() { return true; } }, - ADD - { + ADD { @Override - public boolean toBoolean() - { + public boolean toBoolean() { return false; } }; public abstract boolean toBoolean(); - public static ADD_OPERATION_TYPE toOperation(boolean isUpdate) - { + public static ADD_OPERATION_TYPE toOperation(boolean isUpdate) { return isUpdate ? UPDATE : ADD; } } @@ -125,47 +119,44 @@ public final class ReplicationManager implements ActiveMQComponent /** * @param remotingConnection */ - public ReplicationManager(CoreRemotingConnection remotingConnection, final ExecutorFactory executorFactory) - { + public ReplicationManager(CoreRemotingConnection remotingConnection, final ExecutorFactory executorFactory) { this.executorFactory = executorFactory; this.replicatingChannel = remotingConnection.getChannel(CHANNEL_ID.REPLICATION.id, -1); this.remotingConnection = remotingConnection; } - public void appendUpdateRecord(final byte journalID, final ADD_OPERATION_TYPE operation, final long id, + public void appendUpdateRecord(final byte journalID, + final ADD_OPERATION_TYPE operation, + final long id, final byte recordType, - final EncodingSupport record) throws Exception - { - if (enabled) - { + final EncodingSupport record) throws Exception { + if (enabled) { sendReplicatePacket(new ReplicationAddMessage(journalID, operation, id, recordType, record)); } } - public void appendDeleteRecord(final byte journalID, final long id) throws Exception - { - if (enabled) - { + public void appendDeleteRecord(final byte journalID, final long id) throws Exception { + if (enabled) { sendReplicatePacket(new ReplicationDeleteMessage(journalID, id)); } } - public void - appendAddRecordTransactional(final byte journalID, final ADD_OPERATION_TYPE operation, final long txID, - final long id, - final byte recordType, - final EncodingSupport record) throws Exception - { - if (enabled) - { + public void appendAddRecordTransactional(final byte journalID, + final ADD_OPERATION_TYPE operation, + final long txID, + final long id, + final byte recordType, + final EncodingSupport record) throws Exception { + if (enabled) { sendReplicatePacket(new ReplicationAddTXMessage(journalID, operation, txID, id, recordType, record)); } } - public void appendCommitRecord(final byte journalID, final long txID, boolean sync, final boolean lineUp) throws Exception - { - if (enabled) - { + public void appendCommitRecord(final byte journalID, + final long txID, + boolean sync, + final boolean lineUp) throws Exception { + if (enabled) { sendReplicatePacket(new ReplicationCommitMessage(journalID, false, txID), lineUp); } } @@ -173,35 +164,28 @@ public final class ReplicationManager implements ActiveMQComponent public void appendDeleteRecordTransactional(final byte journalID, final long txID, final long id, - final EncodingSupport record) throws Exception - { - if (enabled) - { + final EncodingSupport record) throws Exception { + if (enabled) { sendReplicatePacket(new ReplicationDeleteTXMessage(journalID, txID, id, record)); } } - public void appendDeleteRecordTransactional(final byte journalID, final long txID, final long id) throws Exception - { - if (enabled) - { + public void appendDeleteRecordTransactional(final byte journalID, final long txID, final long id) throws Exception { + if (enabled) { sendReplicatePacket(new ReplicationDeleteTXMessage(journalID, txID, id, NullEncoding.instance)); } } - public void - appendPrepareRecord(final byte journalID, final long txID, final EncodingSupport transactionData) throws Exception - { - if (enabled) - { + public void appendPrepareRecord(final byte journalID, + final long txID, + final EncodingSupport transactionData) throws Exception { + if (enabled) { sendReplicatePacket(new ReplicationPrepareMessage(journalID, txID, transactionData)); } } - public void appendRollbackRecord(final byte journalID, final long txID) throws Exception - { - if (enabled) - { + public void appendRollbackRecord(final byte journalID, final long txID) throws Exception { + if (enabled) { sendReplicatePacket(new ReplicationCommitMessage(journalID, true, txID)); } } @@ -210,65 +194,50 @@ public final class ReplicationManager implements ActiveMQComponent * @param storeName * @param pageNumber */ - public void pageClosed(final SimpleString storeName, final int pageNumber) - { - if (enabled) - { + public void pageClosed(final SimpleString storeName, final int pageNumber) { + if (enabled) { sendReplicatePacket(new ReplicationPageEventMessage(storeName, pageNumber, false)); } } - public void pageDeleted(final SimpleString storeName, final int pageNumber) - { - if (enabled) - { + public void pageDeleted(final SimpleString storeName, final int pageNumber) { + if (enabled) { sendReplicatePacket(new ReplicationPageEventMessage(storeName, pageNumber, true)); } } - public void pageWrite(final PagedMessage message, final int pageNumber) - { - if (enabled) - { + public void pageWrite(final PagedMessage message, final int pageNumber) { + if (enabled) { sendReplicatePacket(new ReplicationPageWriteMessage(message, pageNumber)); } } - public void largeMessageBegin(final long messageId) - { - if (enabled) - { + public void largeMessageBegin(final long messageId) { + if (enabled) { sendReplicatePacket(new ReplicationLargeMessageBeginMessage(messageId)); } } - public void largeMessageDelete(final Long messageId) - { - if (enabled) - { + public void largeMessageDelete(final Long messageId) { + if (enabled) { sendReplicatePacket(new ReplicationLargeMessageEndMessage(messageId)); } } - public void largeMessageWrite(final long messageId, final byte[] body) - { - if (enabled) - { + public void largeMessageWrite(final long messageId, final byte[] body) { + if (enabled) { sendReplicatePacket(new ReplicationLargeMessageWriteMessage(messageId, body)); } } @Override - public synchronized boolean isStarted() - { + public synchronized boolean isStarted() { return started; } @Override - public synchronized void start() throws ActiveMQException - { - if (started) - { + public synchronized void start() throws ActiveMQException { + if (started) { throw new IllegalStateException("ReplicationManager is already started"); } @@ -281,26 +250,21 @@ public final class ReplicationManager implements ActiveMQComponent enabled = true; } - public synchronized void stop() throws Exception - { - if (!started) - { + public synchronized void stop() throws Exception { + if (!started) { return; } - synchronized (replicationLock) - { + synchronized (replicationLock) { enabled = false; - if (replicatingChannel != null) - { + if (replicatingChannel != null) { replicatingChannel.close(); } clearReplicationTokens(); } RemotingConnection toStop = remotingConnection; - if (toStop != null) - { + if (toStop != null) { toStop.removeFailureListener(failureListener); } remotingConnection = null; @@ -313,19 +277,14 @@ public final class ReplicationManager implements ActiveMQComponent * This can be necessary in case the live loses connection to the backup (network failure, or * backup crashing). */ - public void clearReplicationTokens() - { - synchronized (replicationLock) - { - while (!pendingTokens.isEmpty()) - { + public void clearReplicationTokens() { + synchronized (replicationLock) { + while (!pendingTokens.isEmpty()) { OperationContext ctx = pendingTokens.poll(); - try - { + try { ctx.replicationDone(); } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQServerLogger.LOGGER.errorCompletingCallbackOnReplicationManager(e); } } @@ -335,16 +294,14 @@ public final class ReplicationManager implements ActiveMQComponent /** * A list of tokens that are still waiting for replications to be completed */ - public Set getActiveTokens() - { + public Set getActiveTokens() { LinkedHashSet activeContexts = new LinkedHashSet(); // The same context will be replicated on the pending tokens... // as the multiple operations will be replicated on the same context - for (OperationContext ctx : pendingTokens) - { + for (OperationContext ctx : pendingTokens) { activeContexts.add(ctx); } @@ -352,32 +309,26 @@ public final class ReplicationManager implements ActiveMQComponent } - private OperationContext sendReplicatePacket(final Packet packet) - { + private OperationContext sendReplicatePacket(final Packet packet) { return sendReplicatePacket(packet, true); } - private OperationContext sendReplicatePacket(final Packet packet, boolean lineUp) - { + private OperationContext sendReplicatePacket(final Packet packet, boolean lineUp) { if (!enabled) return null; boolean runItNow = false; OperationContext repliToken = OperationContextImpl.getContext(executorFactory); - if (lineUp) - { + if (lineUp) { repliToken.replicationLineUp(); } - synchronized (replicationLock) - { - if (enabled) - { + synchronized (replicationLock) { + if (enabled) { pendingTokens.add(repliToken); replicatingChannel.send(packet); } - else - { + else { // Already replicating channel failed, so just play the action now runItNow = true; } @@ -385,8 +336,7 @@ public final class ReplicationManager implements ActiveMQComponent // Execute outside lock - if (runItNow) - { + if (runItNow) { repliToken.replicationDone(); } @@ -398,12 +348,10 @@ public final class ReplicationManager implements ActiveMQComponent * response. If your packets are triggering this exception, it may be because the * packets were not sent with {@link #sendReplicatePacket(Packet)}. */ - private void replicated() - { + private void replicated() { OperationContext ctx = pendingTokens.poll(); - if (ctx == null) - { + if (ctx == null) { throw new IllegalStateException("Missing replication token on the queue."); } @@ -412,68 +360,56 @@ public final class ReplicationManager implements ActiveMQComponent // Inner classes ------------------------------------------------- - private final class ReplicatedSessionFailureListener implements SessionFailureListener - { + private final class ReplicatedSessionFailureListener implements SessionFailureListener { + @Override - public void connectionFailed(final ActiveMQException me, boolean failedOver) - { - if (me.getType() == ActiveMQExceptionType.DISCONNECTED) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver) { + if (me.getType() == ActiveMQExceptionType.DISCONNECTED) { // Backup has shut down - no need to log a stack trace ActiveMQServerLogger.LOGGER.replicationStopOnBackupShutdown(); } - else - { + else { ActiveMQServerLogger.LOGGER.replicationStopOnBackupFail(me); } - try - { + try { stop(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorStoppingReplication(e); } } @Override - public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) { connectionFailed(me, failedOver); } - public void beforeReconnect(final ActiveMQException me) - { + public void beforeReconnect(final ActiveMQException me) { } } - private final class ResponseHandler implements ChannelHandler - { - public void handlePacket(final Packet packet) - { - if (packet.getType() == PacketImpl.REPLICATION_RESPONSE) - { + private final class ResponseHandler implements ChannelHandler { + + public void handlePacket(final Packet packet) { + if (packet.getType() == PacketImpl.REPLICATION_RESPONSE) { replicated(); } } } - private static final class NullEncoding implements EncodingSupport - { + private static final class NullEncoding implements EncodingSupport { + static final NullEncoding instance = new NullEncoding(); - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { } - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { } - public int getEncodeSize() - { + public int getEncodeSize() { return 0; } } @@ -484,35 +420,28 @@ public final class ReplicationManager implements ActiveMQComponent * @throws ActiveMQException * @throws Exception */ - public void syncJournalFile(JournalFile jf, JournalContent content) throws Exception - { - if (!enabled) - { + public void syncJournalFile(JournalFile jf, JournalContent content) throws Exception { + if (!enabled) { return; } SequentialFile file = jf.getFile().cloneFile(); - try - { + try { ActiveMQServerLogger.LOGGER.journalSynch(jf, file.size(), file); sendLargeFile(content, null, jf.getFileID(), file, Long.MAX_VALUE); } - finally - { + finally { if (file.isOpen()) file.close(); } } - public void syncLargeMessageFile(SequentialFile file, long size, long id) throws Exception - { - if (enabled) - { + public void syncLargeMessageFile(SequentialFile file, long size, long id) throws Exception { + if (enabled) { sendLargeFile(null, null, id, file, size); } } - public void syncPages(SequentialFile file, long id, SimpleString queueName) throws Exception - { + public void syncPages(SequentialFile file, long id, SimpleString queueName) throws Exception { if (enabled) sendLargeFile(null, queueName, id, file, Long.MAX_VALUE); } @@ -527,41 +456,35 @@ public final class ReplicationManager implements ActiveMQComponent * @param maxBytesToSend maximum number of bytes to read and send from the file * @throws Exception */ - private void sendLargeFile(JournalContent content, SimpleString pageStore, final long id, SequentialFile file, - long maxBytesToSend) throws Exception - { + private void sendLargeFile(JournalContent content, + SimpleString pageStore, + final long id, + SequentialFile file, + long maxBytesToSend) throws Exception { if (!enabled) return; - if (!file.isOpen()) - { + if (!file.isOpen()) { file.open(); } - try - { + try { final FileInputStream fis = new FileInputStream(file.getJavaFile()); - try - { + try { final FileChannel channel = fis.getChannel(); - try - { + try { // We can afford having a single buffer here for this entire loop // because sendReplicatePacket will encode the packet as a NettyBuffer // through ActiveMQBuffer class leaving this buffer free to be reused on the next copy final ByteBuffer buffer = ByteBuffer.allocate(1 << 17); // 1 << 17 == 131072 == 128 * 1024 - while (true) - { + while (true) { buffer.clear(); final int bytesRead = channel.read(buffer); int toSend = bytesRead; - if (bytesRead > 0) - { - if (bytesRead >= maxBytesToSend) - { + if (bytesRead > 0) { + if (bytesRead >= maxBytesToSend) { toSend = (int) maxBytesToSend; maxBytesToSend = 0; } - else - { + else { maxBytesToSend = maxBytesToSend - bytesRead; } buffer.limit(toSend); @@ -574,18 +497,15 @@ public final class ReplicationManager implements ActiveMQComponent break; } } - finally - { + finally { channel.close(); } } - finally - { + finally { fis.close(); } } - finally - { + finally { if (file.isOpen()) file.close(); } @@ -598,9 +518,10 @@ public final class ReplicationManager implements ActiveMQComponent * @param contentType * @throws ActiveMQException */ - public void sendStartSyncMessage(JournalFile[] datafiles, JournalContent contentType, String nodeID, - boolean allowsAutoFailBack) throws ActiveMQException - { + public void sendStartSyncMessage(JournalFile[] datafiles, + JournalContent contentType, + String nodeID, + boolean allowsAutoFailBack) throws ActiveMQException { if (enabled) sendReplicatePacket(new ReplicationStartSyncMessage(datafiles, contentType, nodeID, allowsAutoFailBack)); } @@ -613,10 +534,8 @@ public final class ReplicationManager implements ActiveMQComponent * * @param nodeID */ - public void sendSynchronizationDone(String nodeID) - { - if (enabled) - { + public void sendSynchronizationDone(String nodeID) { + if (enabled) { sendReplicatePacket(new ReplicationStartSyncMessage(nodeID)); inSync = false; } @@ -630,8 +549,7 @@ public final class ReplicationManager implements ActiveMQComponent * * @param largeMessages */ - public void sendLargeMessageIdListMessage(Map> largeMessages) - { + public void sendLargeMessageIdListMessage(Map> largeMessages) { ArrayList idsToSend; idsToSend = new ArrayList(largeMessages.keySet()); @@ -647,11 +565,9 @@ public final class ReplicationManager implements ActiveMQComponent * * @return */ - public OperationContext sendLiveIsStopping(final LiveStopping finalMessage) - { + public OperationContext sendLiveIsStopping(final LiveStopping finalMessage) { ActiveMQServerLogger.LOGGER.debug("LIVE IS STOPPING?!? message=" + finalMessage + " enabled=" + enabled); - if (enabled) - { + if (enabled) { ActiveMQServerLogger.LOGGER.debug("LIVE IS STOPPING?!? message=" + finalMessage + " " + enabled); return sendReplicatePacket(new ReplicationLiveIsStoppingMessage(finalMessage)); } @@ -663,16 +579,14 @@ public final class ReplicationManager implements ActiveMQComponent * * @return remoting connection with the backup */ - public CoreRemotingConnection getBackupTransportConnection() - { + public CoreRemotingConnection getBackupTransportConnection() { return remotingConnection; } /** * @return */ - public boolean isSynchronizing() - { + public boolean isSynchronizing() { return inSync; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/security/CheckType.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/security/CheckType.java index 62ea99edcb..6a8f01c7fe 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/security/CheckType.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/security/CheckType.java @@ -16,61 +16,46 @@ */ package org.apache.activemq.artemis.core.security; -public enum CheckType -{ - SEND - { +public enum CheckType { + SEND { @Override - public boolean hasRole(final Role role) - { + public boolean hasRole(final Role role) { return role.isSend(); } }, - CONSUME - { + CONSUME { @Override - public boolean hasRole(final Role role) - { + public boolean hasRole(final Role role) { return role.isConsume(); } }, - CREATE_DURABLE_QUEUE - { + CREATE_DURABLE_QUEUE { @Override - public boolean hasRole(final Role role) - { + public boolean hasRole(final Role role) { return role.isCreateDurableQueue(); } }, - DELETE_DURABLE_QUEUE - { + DELETE_DURABLE_QUEUE { @Override - public boolean hasRole(final Role role) - { + public boolean hasRole(final Role role) { return role.isDeleteDurableQueue(); } }, - CREATE_NON_DURABLE_QUEUE - { + CREATE_NON_DURABLE_QUEUE { @Override - public boolean hasRole(final Role role) - { + public boolean hasRole(final Role role) { return role.isCreateNonDurableQueue(); } }, - DELETE_NON_DURABLE_QUEUE - { + DELETE_NON_DURABLE_QUEUE { @Override - public boolean hasRole(final Role role) - { + public boolean hasRole(final Role role) { return role.isDeleteNonDurableQueue(); } }, - MANAGE - { + MANAGE { @Override - public boolean hasRole(final Role role) - { + public boolean hasRole(final Role role) { return role.isManage(); } }; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/security/SecurityStore.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/security/SecurityStore.java index 9bf8d9da38..1456f7c221 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/security/SecurityStore.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/security/SecurityStore.java @@ -19,8 +19,8 @@ package org.apache.activemq.artemis.core.security; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.server.ServerSession; -public interface SecurityStore -{ +public interface SecurityStore { + void authenticate(String user, String password) throws Exception; void check(SimpleString address, CheckType checkType, ServerSession session) throws Exception; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/security/User.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/security/User.java index 66b1affe9b..9e6bacb129 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/security/User.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/security/User.java @@ -16,34 +16,29 @@ */ package org.apache.activemq.artemis.core.security; -public class User -{ +public class User { + final String user; final String password; - public User(final String user, final String password) - { + public User(final String user, final String password) { this.user = user; this.password = password; } @Override - public boolean equals(final Object o) - { - if (this == o) - { + public boolean equals(final Object o) { + if (this == o) { return true; } - if (o == null || getClass() != o.getClass()) - { + if (o == null || getClass() != o.getClass()) { return false; } - User user1 = (User)o; + User user1 = (User) o; - if (!user.equals(user1.user)) - { + if (!user.equals(user1.user)) { return false; } @@ -51,27 +46,22 @@ public class User } @Override - public int hashCode() - { + public int hashCode() { return user.hashCode(); } - public boolean isValid(final String user, final String password) - { - if (user == null) - { + public boolean isValid(final String user, final String password) { + if (user == null) { return false; } return this.user.equals(user) && this.password.equals(password); } - public String getUser() - { + public String getUser() { return user; } - public String getPassword() - { + public String getPassword() { return password; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/security/impl/SecurityStoreImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/security/impl/SecurityStoreImpl.java index 25da5cc6a8..143cf05ea2 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/security/impl/SecurityStoreImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/security/impl/SecurityStoreImpl.java @@ -40,8 +40,7 @@ import org.apache.activemq.artemis.utils.TypedProperties; /** * The ActiveMQ Artemis SecurityStore implementation */ -public class SecurityStoreImpl implements SecurityStore, HierarchicalRepositoryChangeListener -{ +public class SecurityStoreImpl implements SecurityStore, HierarchicalRepositoryChangeListener { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -79,8 +78,7 @@ public class SecurityStoreImpl implements SecurityStore, HierarchicalRepositoryC final boolean securityEnabled, final String managementClusterUser, final String managementClusterPassword, - final NotificationService notificationService) - { + final NotificationService notificationService) { this.securityRepository = securityRepository; this.securityManager = securityManager; this.invalidationInterval = invalidationInterval; @@ -94,25 +92,19 @@ public class SecurityStoreImpl implements SecurityStore, HierarchicalRepositoryC // SecurityManager implementation -------------------------------- @Override - public boolean isSecurityEnabled() - { + public boolean isSecurityEnabled() { return securityEnabled; } - public void stop() - { + public void stop() { securityRepository.unRegisterListener(this); } - public void authenticate(final String user, final String password) throws Exception - { - if (securityEnabled) - { + public void authenticate(final String user, final String password) throws Exception { + if (securityEnabled) { - if (managementClusterUser.equals(user)) - { - if (trace) - { + if (managementClusterUser.equals(user)) { + if (trace) { ActiveMQServerLogger.LOGGER.trace("Authenticating cluster admin user"); } @@ -120,20 +112,16 @@ public class SecurityStoreImpl implements SecurityStore, HierarchicalRepositoryC * The special user cluster user is used for creating sessions that replicate management * operation between nodes */ - if (!managementClusterPassword.equals(password)) - { + if (!managementClusterPassword.equals(password)) { throw ActiveMQMessageBundle.BUNDLE.unableToValidateClusterUser(user); } - else - { + else { return; } } - if (!securityManager.validateUser(user, password)) - { - if (notificationService != null) - { + if (!securityManager.validateUser(user, password)) { + if (notificationService != null) { TypedProperties props = new TypedProperties(); props.putSimpleStringProperty(ManagementHelper.HDR_USER, SimpleString.toSimpleString(user)); @@ -148,18 +136,16 @@ public class SecurityStoreImpl implements SecurityStore, HierarchicalRepositoryC } } - public void check(final SimpleString address, final CheckType checkType, final ServerSession session) throws Exception - { - if (securityEnabled) - { - if (trace) - { + public void check(final SimpleString address, + final CheckType checkType, + final ServerSession session) throws Exception { + if (securityEnabled) { + if (trace) { ActiveMQServerLogger.LOGGER.trace("checking access permissions to " + address); } String user = session.getUsername(); - if (checkCached(address, user, checkType)) - { + if (checkCached(address, user, checkType)) { // OK return; } @@ -169,15 +155,12 @@ public class SecurityStoreImpl implements SecurityStore, HierarchicalRepositoryC Set roles = securityRepository.getMatch(saddress); // bypass permission checks for management cluster user - if (managementClusterUser.equals(user) && session.getPassword().equals(managementClusterPassword)) - { + if (managementClusterUser.equals(user) && session.getPassword().equals(managementClusterPassword)) { return; } - if (!securityManager.validateUserAndRole(user, session.getPassword(), roles, checkType)) - { - if (notificationService != null) - { + if (!securityManager.validateUserAndRole(user, session.getPassword(), roles, checkType)) { + if (notificationService != null) { TypedProperties props = new TypedProperties(); props.putSimpleStringProperty(ManagementHelper.HDR_ADDRESS, address); @@ -194,8 +177,7 @@ public class SecurityStoreImpl implements SecurityStore, HierarchicalRepositoryC // if we get here we're granted, add to the cache ConcurrentHashSet set = new ConcurrentHashSet(); ConcurrentHashSet act = cache.putIfAbsent(user + "." + checkType.name(), set); - if (act != null) - { + if (act != null) { set = act; } set.add(address); @@ -203,8 +185,7 @@ public class SecurityStoreImpl implements SecurityStore, HierarchicalRepositoryC } } - public void onChange() - { + public void onChange() { invalidateCache(); } @@ -215,28 +196,23 @@ public class SecurityStoreImpl implements SecurityStore, HierarchicalRepositoryC // Package Private ----------------------------------------------- // Private ------------------------------------------------------- - private void invalidateCache() - { + private void invalidateCache() { cache.clear(); } - private boolean checkCached(final SimpleString dest, final String user, final CheckType checkType) - { + private boolean checkCached(final SimpleString dest, final String user, final CheckType checkType) { long now = System.currentTimeMillis(); boolean granted = false; - if (now - lastCheck > invalidationInterval) - { + if (now - lastCheck > invalidationInterval) { invalidateCache(); lastCheck = now; } - else - { + else { ConcurrentHashSet act = cache.get(user + "." + checkType.name()); - if (act != null) - { + if (act != null) { granted = act.contains(dest); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActivateCallback.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActivateCallback.java index 61ae20c90c..9841d67a01 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActivateCallback.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActivateCallback.java @@ -16,8 +16,8 @@ */ package org.apache.activemq.artemis.core.server; -public interface ActivateCallback -{ +public interface ActivateCallback { + /* * this is called before any services are started when the server first initialised */ diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActivationParams.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActivationParams.java index b4c48040e3..efb827ea94 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActivationParams.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActivationParams.java @@ -16,7 +16,7 @@ */ package org.apache.activemq.artemis.core.server; -public class ActivationParams -{ +public class ActivationParams { + public static final String REPLICATION_ENDPOINT = "REPLICATION_ENDPOINT"; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQMessageBundle.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQMessageBundle.java index ad8220e95a..b8c637d604 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQMessageBundle.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQMessageBundle.java @@ -53,8 +53,8 @@ import java.io.File; * articles. Unused methods should be marked as deprecated. */ @MessageBundle(projectCode = "AMQ") -public interface ActiveMQMessageBundle -{ +public interface ActiveMQMessageBundle { + ActiveMQMessageBundle BUNDLE = Messages.getBundle(ActiveMQMessageBundle.class); @Message(id = 119000, value = "Activation for server {0}", format = Message.Format.MESSAGE_FORMAT) @@ -100,12 +100,11 @@ public interface ActiveMQMessageBundle ActiveMQInternalErrorException bindingNotDivert(SimpleString name); @Message(id = 119014, - value = "Did not receive data from {0}. It is likely the client has exited or crashed without " - + - "closing its connection, or the network between the server and client has failed. " + - "You also might have configured connection-ttl and client-failure-check-period incorrectly. " + - "Please check user manual for more information." + - " The connection will now be closed.", format = Message.Format.MESSAGE_FORMAT) + value = "Did not receive data from {0}. It is likely the client has exited or crashed without " + + "closing its connection, or the network between the server and client has failed. " + + "You also might have configured connection-ttl and client-failure-check-period incorrectly. " + + "Please check user manual for more information." + + " The connection will now be closed.", format = Message.Format.MESSAGE_FORMAT) ActiveMQConnectionTimedOutException clientExited(String remoteAddress); @Message(id = 119017, value = "Queue {0} does not exist", format = Message.Format.MESSAGE_FORMAT) @@ -316,21 +315,20 @@ public interface ActiveMQMessageBundle ActiveMQInvalidTransientQueueUseException queueSubscriptionBelongsToDifferentFilter(SimpleString queueName); @Message(id = 119085, value = "Classpath lacks a protocol-manager for protocol {0}", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) ActiveMQException noProtocolManagerFound(String protocol); // this code has to match with version 2.3.x as it's used on integration tests at Wildfly and JBoss EAP @Message(id = 119099, value = "Unable to authenticate cluster user: {0}", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) ActiveMQClusterSecurityException unableToValidateClusterUser(String user); - @Message(id = 119100, value = "Trying to move a journal file that refers to a file instead of a directory: {0}", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) IllegalStateException journalDirIsFile(File fDir); @Message(id = 119101, value = "error trying to backup journal files at directory: {0}", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) IllegalStateException couldNotMoveJournal(File dir); @Message(id = 119102, value = "Address \"{0}\" is full.", format = Message.Format.MESSAGE_FORMAT) diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQServer.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQServer.java index 1de2ee6962..f1811baf92 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQServer.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQServer.java @@ -56,8 +56,7 @@ import org.apache.activemq.artemis.utils.ExecutorFactory; *

    * This is not part of our public API. */ -public interface ActiveMQServer extends ActiveMQComponent -{ +public interface ActiveMQServer extends ActiveMQComponent { /** * Sets the server identity. @@ -96,6 +95,7 @@ public interface ActiveMQServer extends ActiveMQComponent /** * Returns the resource to manage this ActiveMQ Artemis server. + * * @throws IllegalStateException if the server is not properly started. */ ActiveMQServerControlImpl getActiveMQServerControl(); @@ -138,7 +138,9 @@ public interface ActiveMQServer extends ActiveMQComponent List getSessions(String connectionID); - /** @return a session containing the meta-key and meata-value */ + /** + * @return a session containing the meta-key and meata-value + */ ServerSession lookupSession(String metakey, String metavalue); ClusterManager getClusterManager(); @@ -149,6 +151,7 @@ public interface ActiveMQServer extends ActiveMQComponent /** * This is the queue creator responsible for JMS Queue creations* + * * @param queueCreator */ void setJMSQueueCreator(QueueCreator queueCreator); @@ -160,12 +163,12 @@ public interface ActiveMQServer extends ActiveMQComponent /** * Wait for server initialization. + * * @param timeout * @param unit * @return {@code true} if the server was already initialized or if it was initialized within the - * timeout period, {@code false} otherwise. + * timeout period, {@code false} otherwise. * @throws InterruptedException - * @see java.util.concurrent.CountDownLatch#await(long, java.util.concurrent.TimeUnit) */ boolean waitForActivation(long timeout, TimeUnit unit) throws InterruptedException; @@ -182,10 +185,10 @@ public interface ActiveMQServer extends ActiveMQComponent * @throws Exception */ void createSharedQueue(final SimpleString address, - final SimpleString name, - final SimpleString filterString, - final SimpleString user, - boolean durable) throws Exception; + final SimpleString name, + final SimpleString filterString, + final SimpleString user, + boolean durable) throws Exception; Queue createQueue(SimpleString address, SimpleString queueName, @@ -222,7 +225,10 @@ public interface ActiveMQServer extends ActiveMQComponent void destroyQueue(SimpleString queueName, ServerSession session, boolean checkConsumerCount) throws Exception; - void destroyQueue(SimpleString queueName, ServerSession session, boolean checkConsumerCount, boolean removeConsumers) throws Exception; + void destroyQueue(SimpleString queueName, + ServerSession session, + boolean checkConsumerCount, + boolean removeConsumers) throws Exception; String destroyConnectionWithSessionMetadata(String metaKey, String metaValue) throws Exception; @@ -252,6 +258,7 @@ public interface ActiveMQServer extends ActiveMQComponent /** * return true if there is a binding for this address (i.e. if there is a created queue) + * * @param address * @return */ diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQServerLogger.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQServerLogger.java index 69b34e8b8a..aa5a406577 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQServerLogger.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQServerLogger.java @@ -69,8 +69,8 @@ import org.jboss.logging.annotations.MessageLogger; import org.w3c.dom.Node; @MessageLogger(projectCode = "AMQ") -public interface ActiveMQServerLogger extends BasicLogger -{ +public interface ActiveMQServerLogger extends BasicLogger { + /** * The default logger. */ @@ -98,7 +98,7 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.INFO) @Message(id = 221005, value = "Deleting pending large message as it was not completed: {0}", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void deletingPendingMessage(Pair msgToDelete); @LogMessage(level = Logger.Level.INFO) @@ -115,7 +115,7 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.INFO) @Message(id = 221109, value = "Apache ActiveMQ Artemis Backup Server version {0} [{1}] started, waiting live to fail before it gets active", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void backupServerStarted(String version, SimpleString nodeID); @LogMessage(level = Logger.Level.INFO) @@ -140,23 +140,23 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.INFO) @Message(id = 221015, value = "Can not find queue {0} while reloading ACKNOWLEDGE_CURSOR, deleting record now", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void journalCannotFindQueueReloading(Long queueID); @LogMessage(level = Logger.Level.INFO) @Message(id = 221016, - value = "Can not find queue {0} while reloading PAGE_CURSOR_COUNTER_VALUE, deleting record now", - format = Message.Format.MESSAGE_FORMAT) + value = "Can not find queue {0} while reloading PAGE_CURSOR_COUNTER_VALUE, deleting record now", + format = Message.Format.MESSAGE_FORMAT) void journalCannotFindQueueReloadingPage(Long queueID); @LogMessage(level = Logger.Level.INFO) @Message(id = 221017, value = "Can not find queue {0} while reloading PAGE_CURSOR_COUNTER_INC, deleting record now", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void journalCannotFindQueueReloadingPageCursor(Long queueID); @LogMessage(level = Logger.Level.INFO) @Message(id = 221018, value = "Large message: {0} did not have any associated reference, file will be deleted", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void largeMessageWithNoRef(Long messageID); @LogMessage(level = Logger.Level.INFO) @@ -232,8 +232,11 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.INFO) @Message(id = 221036, value = "Message with duplicate ID {0} was already set at {1}. Move from {2} being ignored and message removed from {3}", - format = Message.Format.MESSAGE_FORMAT) - void messageWithDuplicateID(Object duplicateProperty, SimpleString toAddress, SimpleString address, SimpleString simpleString); + format = Message.Format.MESSAGE_FORMAT) + void messageWithDuplicateID(Object duplicateProperty, + SimpleString toAddress, + SimpleString address, + SimpleString simpleString); @LogMessage(level = Logger.Level.INFO) @Message(id = 221037, value = "{0} to become ''live''", format = Message.Format.MESSAGE_FORMAT) @@ -241,27 +244,27 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.INFO) @Message(id = 221038, value = "Configuration option ''{0}'' is deprecated. Consult the manual for details.", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void deprecatedConfigurationOption(String deprecatedOption); @LogMessage(level = Logger.Level.INFO) @Message(id = 221039, value = "Restarting as Replicating backup server after live restart", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void restartingReplicatedBackupAfterFailback(); @LogMessage(level = Logger.Level.INFO) - @Message(id = 221040, value = "Remote group coordinators did not start yet", format = Message.Format.MESSAGE_FORMAT) + @Message(id = 221040, value = "Remote group coordinators did not start yet", format = Message.Format.MESSAGE_FORMAT) void remoteGroupCoordinatorsNotStarted(); @LogMessage(level = Logger.Level.INFO) @Message(id = 221041, value = "Cannot find queue {0} while reloading PAGE_CURSOR_COMPLETE, deleting record now", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void cantFindQueueOnPageComplete(long queueID); @LogMessage(level = Logger.Level.INFO) @Message(id = 221042, - value = "Bridge {0} timed out waiting for the completion of {1} messages, we will just shutdown the bridge after 10 seconds wait", - format = Message.Format.MESSAGE_FORMAT) + value = "Bridge {0} timed out waiting for the completion of {1} messages, we will just shutdown the bridge after 10 seconds wait", + format = Message.Format.MESSAGE_FORMAT) void timedOutWaitingCompletions(String bridgeName, long numberOfMessages); @LogMessage(level = Logger.Level.INFO) @@ -282,7 +285,12 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.INFO) @Message(id = 221048, value = "Consumer {0}:{1} attached to queue ''{2}'' from {3} identified as ''slow.'' Expected consumption rate: {4} msgs/second; actual consumption rate: {5} msgs/second.", format = Message.Format.MESSAGE_FORMAT) - void slowConsumerDetected(String sessionID, long consumerID, String queueName, String remoteAddress, float slowConsumerThreshold, float consumerRate); + void slowConsumerDetected(String sessionID, + long consumerID, + String queueName, + String remoteAddress, + float slowConsumerThreshold, + float consumerRate); @LogMessage(level = Logger.Level.INFO) @Message(id = 221049, value = "Activating Replica for node: {0}", format = Message.Format.MESSAGE_FORMAT) @@ -294,7 +302,7 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 222000, value = "ActiveMQServer is being finalized and has not been stopped. Please remember to stop the server before letting it go out of scope", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void serverFinalisedWIthoutBeingSTopped(); @LogMessage(level = Logger.Level.WARN) @@ -393,7 +401,7 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 222024, value = "Could not complete operations on IO context {0}", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void problemCompletingOperations(OperationContext e); @LogMessage(level = Logger.Level.WARN) @@ -410,13 +418,13 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 222028, value = "Could not find page cache for page {0} removing it from the journal", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void pageNotFound(PagePosition pos); @LogMessage(level = Logger.Level.WARN) @Message(id = 222029, - value = "Could not locate page transaction {0}, ignoring message on position {1} on address={2} queue={3}", - format = Message.Format.MESSAGE_FORMAT) + value = "Could not locate page transaction {0}, ignoring message on position {1} on address={2} queue={3}", + format = Message.Format.MESSAGE_FORMAT) void pageSubscriptionCouldntLoad(long transactionID, PagePosition position, SimpleString address, SimpleString name); @LogMessage(level = Logger.Level.WARN) @@ -441,7 +449,7 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 222035, value = "Directory {0} did not have an identification file {1}", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void pageStoreFactoryNoIdFile(String s, String addressFile); @LogMessage(level = Logger.Level.WARN) @@ -490,7 +498,7 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 222047, value = "Can not find queue {0} while reloading ACKNOWLEDGE_CURSOR", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void journalCannotFindQueueReloadingACK(Long queueID); @LogMessage(level = Logger.Level.WARN) @@ -506,7 +514,7 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 222050, value = "Can not locate recordType={0} on loadPreparedTransaction//deleteRecords", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void journalInvalidRecordTypeOnPreparedTX(Byte recordType); @LogMessage(level = Logger.Level.WARN) @@ -531,12 +539,12 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 222056, value = "Did not route to any bindings for address {0} and sendToDLAOnNoRoute is true but there is no DLA configured for the address, the message will be ignored.", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void noDLA(SimpleString address); @LogMessage(level = Logger.Level.WARN) @Message(id = 222057, value = "It was not possible to add references due to an IO error code {0} message = {1}", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void ioErrorAddingReferences(Integer errorCode, String errorMessage); @LogMessage(level = Logger.Level.WARN) @@ -613,7 +621,7 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 222079, value = "The following keys are invalid for configuring the acceptor: {0} the acceptor will not be started.", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void invalidAcceptorKeys(String s); @LogMessage(level = Logger.Level.WARN) @@ -630,17 +638,17 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 222083, value = "The following keys are invalid for configuring the connector service: {0} the connector will not be started.", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void connectorKeysInvalid(String s); @LogMessage(level = Logger.Level.WARN) @Message(id = 222084, value = "The following keys are required for configuring the connector service: {0} the connector will not be started.", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void connectorKeysMissing(String s); @LogMessage(level = Logger.Level.WARN) @Message(id = 222085, value = "Packet {0} can not be processed by the ReplicationEndpoint", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void invalidPacketForReplication(Packet packet); @LogMessage(level = Logger.Level.WARN) @@ -689,7 +697,7 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 222097, value = "Address {0} does not have any bindings yet, retry #({1})", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void errorQueryingBridge(SimpleString address, Integer retryCount); @LogMessage(level = Logger.Level.WARN) @@ -702,7 +710,7 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 222100, value = "ServerLocator was shutdown, can not retry on opening connection for bridge", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void bridgeLocatorShutdown(); @LogMessage(level = Logger.Level.WARN) @@ -723,7 +731,7 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 222105, value = "Could not finish context execution in 10 seconds", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void errorCompletingContext(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @@ -736,7 +744,7 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 222108, value = "unable to send notification when broadcast group is stopped", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void broadcastGroupClosed(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @@ -745,32 +753,32 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 222110, value = "no queue IDs defined!, originalMessage = {0}, copiedMessage = {1}, props={2}", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void noQueueIdDefined(ServerMessage message, ServerMessage messageCopy, SimpleString idsHeaderName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222111, value = "exception while invoking {0} on {1}", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void managementOperationError(@Cause Exception e, String op, String resourceName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222112, value = "exception while retrieving attribute {0} on {1}", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void managementAttributeError(@Cause Exception e, String att, String resourceName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222113, value = "On ManagementService stop, there are {0} unexpected registered MBeans: {1}", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void managementStopError(Integer size, List unexpectedResourceNames); @LogMessage(level = Logger.Level.WARN) @Message(id = 222114, value = "Unable to delete group binding info {0}", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void unableToDeleteGroupBindings(@Cause Exception e, SimpleString groupId); @LogMessage(level = Logger.Level.WARN) @Message(id = 222115, value = "Error closing serverLocator={0}", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void errorClosingServerLocator(@Cause Exception e, ServerLocatorInternal clusterLocator); @LogMessage(level = Logger.Level.WARN) @@ -787,7 +795,7 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 222119, value = "No connector with name {0}. backup cannot be announced.", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void announceBackupNoConnector(String connectorName); @LogMessage(level = Logger.Level.WARN) @@ -828,18 +836,18 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 222129, value = "No connector with name {0}. The cluster connection will not be deployed.", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void clusterConnectionNoConnector(String connectorName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222130, - value = "Cluster Configuration {0} already exists. The cluster connection will not be deployed.", - format = Message.Format.MESSAGE_FORMAT) + value = "Cluster Configuration {0} already exists. The cluster connection will not be deployed.", + format = Message.Format.MESSAGE_FORMAT) void clusterConnectionAlreadyExists(String connectorName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222131, value = "No discovery group with name {0}. The cluster connection will not be deployed.", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void clusterConnectionNoDiscoveryGroup(String discoveryGroupName); @LogMessage(level = Logger.Level.WARN) @@ -855,7 +863,7 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 222134, value = "No connector defined with name {0}. The bridge will not be deployed.", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void bridgeNoConnector(String name); @LogMessage(level = Logger.Level.WARN) @@ -876,7 +884,7 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 222139, value = "{0}::Remote queue binding {1} has already been bound in the post office. Most likely cause for this is you have a loop in your cluster due to cluster max-hops being too large or you have multiple cluster connections to the same nodes using overlapping addresses", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void remoteQueueAlreadyBoundOnClusterConnection(Object messageFlowRecord, SimpleString clusterName); @LogMessage(level = Logger.Level.WARN) @@ -893,7 +901,7 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 222144, value = "Queue could not finish waiting executors. Try increasing the thread pool size", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void errorFlushingExecutorsOnQueue(); @LogMessage(level = Logger.Level.WARN) @@ -910,52 +918,52 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 222148, value = "Message {0} has exceeded max delivery attempts. No bindings for Dead Letter Address {1} so dropping it", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void messageExceededMaxDelivery(MessageReference ref, SimpleString name); @LogMessage(level = Logger.Level.WARN) @Message(id = 222149, value = "Message {0} has reached maximum delivery attempts, sending it to Dead Letter Address {1} from {2}", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void messageExceededMaxDeliverySendtoDLA(MessageReference ref, SimpleString name, SimpleString simpleString); @LogMessage(level = Logger.Level.WARN) @Message(id = 222150, value = "Message has exceeded max delivery attempts. No Dead Letter Address configured for queue {0} so dropping it", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void messageExceededMaxDeliveryNoDLA(SimpleString name); @LogMessage(level = Logger.Level.WARN) @Message(id = 222151, value = "removing consumer which did not handle a message, consumer={0}, message={1}", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void removingBadConsumer(@Cause Throwable e, Consumer consumer, MessageReference reference); @LogMessage(level = Logger.Level.WARN) @Message(id = 222152, value = "Unable to decrement reference counting on queue", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void errorDecrementingRefCount(@Cause Throwable e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222153, value = "Unable to remove message id = {0} please remove manually", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void errorRemovingMessage(@Cause Throwable e, Long messageID); @LogMessage(level = Logger.Level.WARN) @Message(id = 222154, value = "Error checking DLQ", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void errorCheckingDLQ(@Cause Throwable e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222155, value = "Failed to register as backup. Stopping the server.", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void errorRegisteringBackup(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222156, value = "Less than {0}%\n{1}\nYou are in danger of running out of RAM. Have you set paging parameters on your addresses? (See user manual \"Paging\" chapter)", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void memoryError(Integer memoryWarningThreshold, String info); @LogMessage(level = Logger.Level.WARN) @Message(id = 222157, value = "Error completing callback on replication manager", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void errorCompletingCallbackOnReplicationManager(@Cause Throwable e); @LogMessage(level = Logger.Level.WARN) @@ -980,7 +988,7 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 222163, value = "Server is being completely stopped, since this was a replicated backup there may be journal files that need cleaning up. The Apache ActiveMQ Artemis broker will have to be manually restarted.", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void stopReplicatedBackupAfterFailback(); @LogMessage(level = Logger.Level.WARN) @@ -989,32 +997,32 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 222167, value = "Group Binding not available so deleting {0} groups from {1}, groups will be bound to another node", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void groupingQueueRemoved(int size, SimpleString clusterName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222168, value = "The ''protocol'' property is deprecated, if you want this Acceptor to support multiple protocols use the ''protocols'' property, i.e. ''CORE,AMQP,STOMP''", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void warnDeprecatedProtocol(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222169, value = "You have old legacy clients connected to the queue {0} and we can''t disconnect them, these clients may just hang", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void warnDisconnectOldClient(String queueName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222170, value = "Bridge {0} forwarding address {1} has confirmation-window-size ({2}) greater than address'' max-size-bytes'' ({3})", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void bridgeConfirmationWindowTooSmall(String bridgeName, String address, int windowConfirmation, long maxSizeBytes); @LogMessage(level = Logger.Level.WARN) @Message(id = 222171, value = "Bridge {0} forwarding address {1} could not be resolved on address-settings configuration", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void bridgeCantFindAddressConfig(String bridgeName, String forwardingAddress); @LogMessage(level = Logger.Level.WARN) @Message(id = 222172, value = "Queue {0} was busy for more than {1} milliseconds. There are possibly consumers hanging on a network operation", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void queueBusy(String name, long timeout); @LogMessage(level = Logger.Level.WARN) @@ -1031,19 +1039,18 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 222176, - value = "A session that was already doing XA work on {0} is replacing the xid by {1} " + - ". This was most likely caused from a previous communication timeout", - format = Message.Format.MESSAGE_FORMAT) + value = "A session that was already doing XA work on {0} is replacing the xid by {1} " + ". This was most likely caused from a previous communication timeout", + format = Message.Format.MESSAGE_FORMAT) void xidReplacedOnXStart(String xidOriginalToString, String xidReplacedToString); @LogMessage(level = Logger.Level.WARN) @Message(id = 222177, value = "Wrong configuration for role, {0} is not a valid permission", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void rolePermissionConfigurationError(String permission); @LogMessage(level = Logger.Level.WARN) @Message(id = 222178, value = "Error during recovery of page counters", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void errorRecoveringPageCounter(@Cause Throwable error); @LogMessage(level = Logger.Level.WARN) @@ -1060,44 +1067,44 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 222184, - value = "Unable to recover group bindings in SCALE_DOWN mode, only FULL backup server can do this", - format = Message.Format.MESSAGE_FORMAT) + value = "Unable to recover group bindings in SCALE_DOWN mode, only FULL backup server can do this", + format = Message.Format.MESSAGE_FORMAT) void groupBindingsOnRecovery(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222185, - value = "no cluster connection for specified replication cluster", - format = Message.Format.MESSAGE_FORMAT) + value = "no cluster connection for specified replication cluster", + format = Message.Format.MESSAGE_FORMAT) void noClusterConnectionForReplicationCluster(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222186, - value = "unable to authorise cluster control", - format = Message.Format.MESSAGE_FORMAT) + value = "unable to authorise cluster control", + format = Message.Format.MESSAGE_FORMAT) void clusterControlAuthfailure(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222187, - value = "Failed to activate replicata", - format = Message.Format.MESSAGE_FORMAT) + value = "Failed to activate replicata", + format = Message.Format.MESSAGE_FORMAT) void activateReplicatedBackupFailed(@Cause Throwable e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222188, - value = "Unable to find target queue for node {0}", - format = Message.Format.MESSAGE_FORMAT) + value = "Unable to find target queue for node {0}", + format = Message.Format.MESSAGE_FORMAT) void unableToFindTargetQueue(String targetNodeID); @LogMessage(level = Logger.Level.WARN) @Message(id = 222189, - value = "Failed to activate shared store slave", - format = Message.Format.MESSAGE_FORMAT) + value = "Failed to activate shared store slave", + format = Message.Format.MESSAGE_FORMAT) void activateSharedStoreSlaveFailed(@Cause Throwable e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222190, - value = "Disallowing use of vulnerable protocol: {0}. See http://www.oracle.com/technetwork/topics/security/poodlecve-2014-3566-2339408.html for more details.", - format = Message.Format.MESSAGE_FORMAT) + value = "Disallowing use of vulnerable protocol: {0}. See http://www.oracle.com/technetwork/topics/security/poodlecve-2014-3566-2339408.html for more details.", + format = Message.Format.MESSAGE_FORMAT) void disallowedProtocol(String protocol); @LogMessage(level = Logger.Level.WARN) @@ -1108,62 +1115,62 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 222192, - value = "Could not delete: {0}", - format = Message.Format.MESSAGE_FORMAT) + value = "Could not delete: {0}", + format = Message.Format.MESSAGE_FORMAT) void couldNotDeleteTempFile(String tempFileName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222193, - value = "Memory Limit reached. Producer ({0}) stopped to prevent flooding {1} (blocking for {2}s). See http://activemq.apache.org/producer-flow-control.html for more info.", - format = Message.Format.MESSAGE_FORMAT) + value = "Memory Limit reached. Producer ({0}) stopped to prevent flooding {1} (blocking for {2}s). See http://activemq.apache.org/producer-flow-control.html for more info.", + format = Message.Format.MESSAGE_FORMAT) void memoryLimitReached(String producerID, String address, long duration); @LogMessage(level = Logger.Level.WARN) @Message(id = 222194, - value = "PageCursorInfo == null on address {0}, pos = {1}, queue = {2}.", - format = Message.Format.MESSAGE_FORMAT) + value = "PageCursorInfo == null on address {0}, pos = {1}, queue = {2}.", + format = Message.Format.MESSAGE_FORMAT) void nullPageCursorInfo(String address, String position, long id); @LogMessage(level = Logger.Level.WARN) @Message(id = 222195, - value = "Large message {0} wasn't found when dealing with add pending large message", - format = Message.Format.MESSAGE_FORMAT) + value = "Large message {0} wasn't found when dealing with add pending large message", + format = Message.Format.MESSAGE_FORMAT) void largeMessageNotFound(long id); @LogMessage(level = Logger.Level.WARN) @Message(id = 222196, - value = "Couldn't find binding with id={0} on routeFromCluster for message={1} binding = {2}", - format = Message.Format.MESSAGE_FORMAT) + value = "Couldn't find binding with id={0} on routeFromCluster for message={1} binding = {2}", + format = Message.Format.MESSAGE_FORMAT) void bindingNotFound(long id, String message, String binding); @LogMessage(level = Logger.Level.WARN) @Message(id = 222197, - value = "Internal error! Delivery logic has identified a non delivery and still handled a consumer!", - format = Message.Format.MESSAGE_FORMAT) + value = "Internal error! Delivery logic has identified a non delivery and still handled a consumer!", + format = Message.Format.MESSAGE_FORMAT) void nonDeliveryHandled(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222198, - value = "Couldn't flush ClusterManager executor ({0}) in 10 seconds, verify your thread pool size", - format = Message.Format.MESSAGE_FORMAT) + value = "Couldn't flush ClusterManager executor ({0}) in 10 seconds, verify your thread pool size", + format = Message.Format.MESSAGE_FORMAT) void couldNotFlushClusterManager(String manager); @LogMessage(level = Logger.Level.WARN) @Message(id = 222199, - value = "Thread dump: {0}", - format = Message.Format.MESSAGE_FORMAT) + value = "Thread dump: {0}", + format = Message.Format.MESSAGE_FORMAT) void threadDump(String manager); @LogMessage(level = Logger.Level.WARN) @Message(id = 222200, - value = "Couldn't finish executor on {0}", - format = Message.Format.MESSAGE_FORMAT) + value = "Couldn't finish executor on {0}", + format = Message.Format.MESSAGE_FORMAT) void couldNotFinishExecutor(String clusterConnection); @LogMessage(level = Logger.Level.WARN) @Message(id = 222201, - value = "Timed out waiting for backup activation to exit", - format = Message.Format.MESSAGE_FORMAT) + value = "Timed out waiting for backup activation to exit", + format = Message.Format.MESSAGE_FORMAT) void backupActivationTimeout(); @LogMessage(level = Logger.Level.WARN) @@ -1388,12 +1395,12 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.ERROR) @Message(id = 224057, value = "Backup server that requested fail-back was not announced. Server will not stop for fail-back.", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void failbackMissedBackupAnnouncement(); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224058, value = "Stopping ClusterManager. As it failed to authenticate with the cluster: {0}", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void clusterManagerAuthenticationError(String msg); @LogMessage(level = Logger.Level.ERROR) @@ -1406,7 +1413,7 @@ public interface ActiveMQServerLogger extends BasicLogger @LogMessage(level = Logger.Level.WARN) @Message(id = 224069, value = "Could not contact group handler coordinator after 10 retries, message being routed without grouping information", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void impossibleToRouteGrouped(); @LogMessage(level = Logger.Level.ERROR) diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQServers.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQServers.java index 79cd370622..1f14833ea8 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQServers.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQServers.java @@ -31,35 +31,27 @@ import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManagerImpl * This class should be used when you want to instantiate an ActiveMQServer instance for embedding in * your own application, as opposed to directly instantiating an implementing instance. */ -public final class ActiveMQServers -{ +public final class ActiveMQServers { - private ActiveMQServers() - { + private ActiveMQServers() { // Utility class } - public static ActiveMQServer newActiveMQServer(final Configuration config, final boolean enablePersistence) - { + public static ActiveMQServer newActiveMQServer(final Configuration config, final boolean enablePersistence) { ActiveMQSecurityManager securityManager = new ActiveMQSecurityManagerImpl(); - ActiveMQServer server = ActiveMQServers.newActiveMQServer(config, - ManagementFactory.getPlatformMBeanServer(), - securityManager, - enablePersistence); + ActiveMQServer server = ActiveMQServers.newActiveMQServer(config, ManagementFactory.getPlatformMBeanServer(), securityManager, enablePersistence); return server; } - public static ActiveMQServer newActiveMQServer(final Configuration config) - { + public static ActiveMQServer newActiveMQServer(final Configuration config) { return ActiveMQServers.newActiveMQServer(config, config.isPersistenceEnabled()); } public static ActiveMQServer newActiveMQServer(final Configuration config, final MBeanServer mbeanServer, - final boolean enablePersistence) - { + final boolean enablePersistence) { ActiveMQSecurityManager securityManager = new ActiveMQSecurityManagerImpl(); ActiveMQServer server = ActiveMQServers.newActiveMQServer(config, mbeanServer, securityManager, enablePersistence); @@ -67,15 +59,13 @@ public final class ActiveMQServers return server; } - public static ActiveMQServer newActiveMQServer(final Configuration config, final MBeanServer mbeanServer) - { + public static ActiveMQServer newActiveMQServer(final Configuration config, final MBeanServer mbeanServer) { return ActiveMQServers.newActiveMQServer(config, mbeanServer, true); } public static ActiveMQServer newActiveMQServer(final Configuration config, final MBeanServer mbeanServer, - final ActiveMQSecurityManager securityManager) - { + final ActiveMQSecurityManager securityManager) { ActiveMQServer server = ActiveMQServers.newActiveMQServer(config, mbeanServer, securityManager, true); return server; @@ -84,8 +74,7 @@ public final class ActiveMQServers public static ActiveMQServer newActiveMQServer(final Configuration config, final MBeanServer mbeanServer, final ActiveMQSecurityManager securityManager, - final boolean enablePersistence) - { + final boolean enablePersistence) { config.setPersistenceEnabled(enablePersistence); ActiveMQServer server = new ActiveMQServerImpl(config, mbeanServer, securityManager); @@ -93,17 +82,12 @@ public final class ActiveMQServers return server; } - public static ActiveMQServer newActiveMQServer(Configuration config, - String defUser, String defPass) - { + public static ActiveMQServer newActiveMQServer(Configuration config, String defUser, String defPass) { ActiveMQSecurityManagerImpl securityManager = new ActiveMQSecurityManagerImpl(); securityManager.getConfiguration().addUser(defUser, defPass); - ActiveMQServer server = ActiveMQServers.newActiveMQServer(config, - ManagementFactory.getPlatformMBeanServer(), - securityManager, - config.isPersistenceEnabled()); + ActiveMQServer server = ActiveMQServers.newActiveMQServer(config, ManagementFactory.getPlatformMBeanServer(), securityManager, config.isPersistenceEnabled()); return server; } @@ -112,8 +96,7 @@ public final class ActiveMQServers final MBeanServer mbeanServer, final boolean enablePersistence, String user, - String password) - { + String password) { ActiveMQSecurityManagerImpl securityManager = new ActiveMQSecurityManagerImpl(); securityManager.getConfiguration().addUser(user, password); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/AutoCreatedQueueManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/AutoCreatedQueueManager.java index ab4291f9b0..5af5c0e7da 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/AutoCreatedQueueManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/AutoCreatedQueueManager.java @@ -19,7 +19,7 @@ package org.apache.activemq.artemis.core.server; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.utils.ReferenceCounter; -public interface AutoCreatedQueueManager extends ReferenceCounter -{ +public interface AutoCreatedQueueManager extends ReferenceCounter { + SimpleString getQueueName(); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/Bindable.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/Bindable.java index 81a5969568..0e3863421f 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/Bindable.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/Bindable.java @@ -16,8 +16,8 @@ */ package org.apache.activemq.artemis.core.server; -public interface Bindable -{ +public interface Bindable { + void route(ServerMessage message, RoutingContext context) throws Exception; void routeWithAck(ServerMessage message, RoutingContext context) throws Exception; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/BindingQueryResult.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/BindingQueryResult.java index cf1547c0a9..ba1c83661c 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/BindingQueryResult.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/BindingQueryResult.java @@ -20,16 +20,17 @@ import java.util.List; import org.apache.activemq.artemis.api.core.SimpleString; -public class BindingQueryResult -{ +public class BindingQueryResult { + private boolean exists; private List queueNames; private boolean autoCreateJmsQueues; - public BindingQueryResult(final boolean exists, final List queueNames, final boolean autoCreateJmsQueues) - { + public BindingQueryResult(final boolean exists, + final List queueNames, + final boolean autoCreateJmsQueues) { this.exists = exists; this.queueNames = queueNames; @@ -37,18 +38,15 @@ public class BindingQueryResult this.autoCreateJmsQueues = autoCreateJmsQueues; } - public boolean isExists() - { + public boolean isExists() { return exists; } - public boolean isAutoCreateJmsQueues() - { + public boolean isAutoCreateJmsQueues() { return autoCreateJmsQueues; } - public List getQueueNames() - { + public List getQueueNames() { return queueNames; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ConnectorService.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ConnectorService.java index 3cb1d74a4c..a3d9866640 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ConnectorService.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ConnectorService.java @@ -16,7 +16,7 @@ */ package org.apache.activemq.artemis.core.server; -public interface ConnectorService extends ActiveMQComponent -{ +public interface ConnectorService extends ActiveMQComponent { + String getName(); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ConnectorServiceFactory.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ConnectorServiceFactory.java index 47ac73f343..0c37ade294 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ConnectorServiceFactory.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ConnectorServiceFactory.java @@ -23,9 +23,10 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.ScheduledExecutorService; -public interface ConnectorServiceFactory -{ - ConnectorService createConnectorService(String connectorName, Map configuration, +public interface ConnectorServiceFactory { + + ConnectorService createConnectorService(String connectorName, + Map configuration, StorageManager storageManager, PostOffice postOffice, ScheduledExecutorService scheduledThreadPool); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/Consumer.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/Consumer.java index 5cb06d2415..58c7d81cec 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/Consumer.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/Consumer.java @@ -20,8 +20,8 @@ import java.util.List; import org.apache.activemq.artemis.core.filter.Filter; -public interface Consumer -{ +public interface Consumer { + /** * There was a change on semantic during 2.3 here.
    * We now first accept the message, and the actual deliver is done as part of @@ -30,6 +30,7 @@ public interface Consumer * consumers. *

    * This should return busy if handle is called before proceed deliver is called + * * @param reference * @return * @throws Exception @@ -41,6 +42,7 @@ public interface Consumer * Notice that handle should hold a readLock and proceedDelivery should release the readLock * any lock operation on Consumer should also get a writeLock on the readWriteLock * to guarantee there are no pending deliveries + * * @throws Exception */ void proceedDeliver(MessageReference reference) throws Exception; @@ -50,20 +52,20 @@ public interface Consumer /** * @return the list of messages being delivered */ - List getDeliveringMessages(); + List getDeliveringMessages(); String debug(); - /** * This method will create a string representation meant for management operations. * This is different from the toString method that's meant for debugging and will contain information that regular users won't understand well + * * @return */ String toManagementString(); - /** - * disconnect the consumer - */ + /** + * disconnect the consumer + */ void disconnect(); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/Divert.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/Divert.java index 9ae98c79b1..e42bd11eed 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/Divert.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/Divert.java @@ -20,8 +20,8 @@ import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.filter.Filter; import org.apache.activemq.artemis.core.server.cluster.Transformer; -public interface Divert extends Bindable -{ +public interface Divert extends Bindable { + Filter getFilter(); boolean isExclusive(); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/HandleStatus.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/HandleStatus.java index 16fcf6331a..c5968f1872 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/HandleStatus.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/HandleStatus.java @@ -17,7 +17,6 @@ package org.apache.activemq.artemis.core.server; /** - * * A HandleStatus * * HANDLED means the MessageReference was handled @@ -26,7 +25,6 @@ package org.apache.activemq.artemis.core.server; * * BUSY means the MessageReference was rejected since the ClientConsumer was busy */ -public enum HandleStatus -{ +public enum HandleStatus { HANDLED, NO_MATCH, BUSY; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/JournalType.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/JournalType.java index 166894f495..ec5a9641f9 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/JournalType.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/JournalType.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.core.server; -public enum JournalType -{ +public enum JournalType { NIO, ASYNCIO; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/LargeServerMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/LargeServerMessage.java index e22a172dc9..e6e1ee952e 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/LargeServerMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/LargeServerMessage.java @@ -20,9 +20,8 @@ import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.core.io.SequentialFile; import org.apache.activemq.artemis.core.replication.ReplicatedLargeMessage; +public interface LargeServerMessage extends ServerMessage, ReplicatedLargeMessage { -public interface LargeServerMessage extends ServerMessage, ReplicatedLargeMessage -{ void addBytes(byte[] bytes) throws Exception; void setPendingRecordID(long pendingRecordID); @@ -35,7 +34,9 @@ public interface LargeServerMessage extends ServerMessage, ReplicatedLargeMessag */ void setPaged(); - /** Close the files if opened */ + /** + * Close the files if opened + */ void releaseResources(); void deleteFile() throws Exception; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/LiveNodeLocator.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/LiveNodeLocator.java index 5d6e3e1c80..88a85dae50 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/LiveNodeLocator.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/LiveNodeLocator.java @@ -29,20 +29,18 @@ import org.apache.activemq.artemis.core.server.cluster.qourum.SharedNothingBacku * * This is used for replication (which needs a QuorumManager) and scaling-down (which does not need a QuorumManager). */ -public abstract class LiveNodeLocator implements ClusterTopologyListener -{ +public abstract class LiveNodeLocator implements ClusterTopologyListener { + private SharedNothingBackupQuorum backupQuorum; - public LiveNodeLocator(SharedNothingBackupQuorum backupQuorum) - { + public LiveNodeLocator(SharedNothingBackupQuorum backupQuorum) { this.backupQuorum = backupQuorum; } /** * Use this constructor when the LiveNodeLocator is used for scaling down rather than replicating */ - public LiveNodeLocator() - { + public LiveNodeLocator() { } /** @@ -68,16 +66,12 @@ public abstract class LiveNodeLocator implements ClusterTopologyListener /** * tells the locator the the current connector has failed. */ - public void notifyRegistrationFailed(boolean alreadyReplicating) - { - if (backupQuorum != null) - { - if (alreadyReplicating) - { + public void notifyRegistrationFailed(boolean alreadyReplicating) { + if (backupQuorum != null) { + if (alreadyReplicating) { backupQuorum.notifyAlreadyReplicating(); } - else - { + else { backupQuorum.notifyRegistrationFailed(); } } @@ -86,8 +80,7 @@ public abstract class LiveNodeLocator implements ClusterTopologyListener /** * connects to the cluster */ - public void connectToCluster(ServerLocatorInternal serverLocator) throws ActiveMQException - { + public void connectToCluster(ServerLocatorInternal serverLocator) throws ActiveMQException { serverLocator.connect(); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/MemoryManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/MemoryManager.java index 27ec0cacb1..7eed4998b2 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/MemoryManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/MemoryManager.java @@ -24,8 +24,8 @@ import org.apache.activemq.artemis.utils.SizeFormatterUtil; * This class will run a thread monitoring memory usage and log warnings in case we are low on * memory. */ -public class MemoryManager implements ActiveMQComponent -{ +public class MemoryManager implements ActiveMQComponent { + private final Runtime runtime; private final long measureInterval; @@ -38,8 +38,7 @@ public class MemoryManager implements ActiveMQComponent private volatile boolean low; - public MemoryManager(final int memoryWarningThreshold, final long measureInterval) - { + public MemoryManager(final int memoryWarningThreshold, final long measureInterval) { runtime = Runtime.getRuntime(); this.measureInterval = measureInterval; @@ -47,24 +46,20 @@ public class MemoryManager implements ActiveMQComponent this.memoryWarningThreshold = memoryWarningThreshold; } - public boolean isMemoryLow() - { + public boolean isMemoryLow() { return low; } - public synchronized boolean isStarted() - { + public synchronized boolean isStarted() { return started; } - public synchronized void start() - { + public synchronized void start() { ActiveMQServerLogger.LOGGER.debug("Starting MemoryManager with MEASURE_INTERVAL: " + measureInterval + - " FREE_MEMORY_PERCENT: " + - memoryWarningThreshold); + " FREE_MEMORY_PERCENT: " + + memoryWarningThreshold); - if (started) - { + if (started) { // Already started return; } @@ -78,10 +73,8 @@ public class MemoryManager implements ActiveMQComponent thread.start(); } - public synchronized void stop() - { - if (!started) - { + public synchronized void stop() { + if (!started) { // Already stopped return; } @@ -90,34 +83,26 @@ public class MemoryManager implements ActiveMQComponent thread.interrupt(); - try - { + try { thread.join(); } - catch (InterruptedException ignore) - { + catch (InterruptedException ignore) { } } - private class MemoryRunnable implements Runnable - { - public void run() - { - while (true) - { - try - { - if (thread.isInterrupted() && !started) - { + private class MemoryRunnable implements Runnable { + + public void run() { + while (true) { + try { + if (thread.isInterrupted() && !started) { break; } Thread.sleep(measureInterval); } - catch (InterruptedException ignore) - { - if (!started) - { + catch (InterruptedException ignore) { + if (!started) { return; } } @@ -138,19 +123,16 @@ public class MemoryManager implements ActiveMQComponent info.append(String.format("total memory: %s%n", SizeFormatterUtil.sizeof(totalMemory))); info.append(String.format("available memory: %.2f%%%n", availableMemoryPercent)); - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug(info); } - if (availableMemoryPercent <= memoryWarningThreshold) - { + if (availableMemoryPercent <= memoryWarningThreshold) { ActiveMQServerLogger.LOGGER.memoryError(memoryWarningThreshold, info.toString()); low = true; } - else - { + else { low = false; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/MessageReference.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/MessageReference.java index 0a5f51a359..0ff55ac1b8 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/MessageReference.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/MessageReference.java @@ -16,14 +16,12 @@ */ package org.apache.activemq.artemis.core.server; - /** * A reference to a message. * * Channels store message references rather than the messages themselves. */ -public interface MessageReference -{ +public interface MessageReference { boolean isPaged(); @@ -32,6 +30,7 @@ public interface MessageReference /** * We define this method aggregation here because on paging we need to hold the original estimate, * so we need to perform some extra steps on paging. + * * @return */ int getMessageMemoryEstimate(); @@ -39,7 +38,6 @@ public interface MessageReference MessageReference copy(Queue queue); /** - * * @return The time in the future that delivery will be delayed until, or zero if * no scheduled delivery will occur */ diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/NodeManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/NodeManager.java index 82b6398098..421daaa21f 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/NodeManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/NodeManager.java @@ -27,8 +27,8 @@ import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.utils.UUID; import org.apache.activemq.artemis.utils.UUIDGenerator; -public abstract class NodeManager implements ActiveMQComponent -{ +public abstract class NodeManager implements ActiveMQComponent { + protected static final byte FIRST_TIME_START = '0'; private static final String SERVER_LOCK_NAME = "server.lock"; private static final String ACCESS_MODE = "rw"; @@ -42,8 +42,7 @@ public abstract class NodeManager implements ActiveMQComponent protected FileChannel channel; - public NodeManager(final boolean replicatedBackup, final File directory) - { + public NodeManager(final boolean replicatedBackup, final File directory) { this.directory = directory; this.replicatedBackup = replicatedBackup; } @@ -64,30 +63,24 @@ public abstract class NodeManager implements ActiveMQComponent // -------------------------------------------------------------------- - public synchronized void start() throws Exception - { + public synchronized void start() throws Exception { isStarted = true; } - public boolean isStarted() - { + public boolean isStarted() { return isStarted; } - public SimpleString getNodeId() - { - synchronized (nodeIDGuard) - { + public SimpleString getNodeId() { + synchronized (nodeIDGuard) { return nodeID; } } public abstract SimpleString readNodeId() throws ActiveMQIllegalStateException, IOException; - public UUID getUUID() - { - synchronized (nodeIDGuard) - { + public UUID getUUID() { + synchronized (nodeIDGuard) { return uuid; } } @@ -99,10 +92,8 @@ public abstract class NodeManager implements ActiveMQComponent * * @param nodeID */ - public void setNodeID(String nodeID) - { - synchronized (nodeIDGuard) - { + public void setNodeID(String nodeID) { + synchronized (nodeIDGuard) { this.nodeID = new SimpleString(nodeID); this.uuid = new UUID(UUID.TYPE_TIME_BASED, UUID.stringToBytes(nodeID)); } @@ -111,10 +102,8 @@ public abstract class NodeManager implements ActiveMQComponent /** * @param generateUUID */ - protected void setUUID(UUID generateUUID) - { - synchronized (nodeIDGuard) - { + protected void setUUID(UUID generateUUID) { + synchronized (nodeIDGuard) { uuid = generateUUID; nodeID = new SimpleString(uuid.toString()); } @@ -127,18 +116,15 @@ public abstract class NodeManager implements ActiveMQComponent public abstract void interrupt(); @Override - public synchronized void stop() throws Exception - { + public synchronized void stop() throws Exception { FileChannel channelCopy = channel; if (channelCopy != null) channelCopy.close(); isStarted = false; } - public final void stopBackup() throws Exception - { - if (replicatedBackup && getNodeId() != null) - { + public final void stopBackup() throws Exception { + if (replicatedBackup && getNodeId() != null) { setUpServerLockFile(); } releaseBackup(); @@ -156,37 +142,29 @@ public abstract class NodeManager implements ActiveMQComponent * the *current* nodeID * */ - protected final synchronized void setUpServerLockFile() throws IOException - { + protected final synchronized void setUpServerLockFile() throws IOException { File serverLockFile = newFile(SERVER_LOCK_NAME); boolean fileCreated = false; int count = 0; - while (!serverLockFile.exists()) - { - try - { + while (!serverLockFile.exists()) { + try { fileCreated = serverLockFile.createNewFile(); } - catch (RuntimeException e) - { + catch (RuntimeException e) { ActiveMQServerLogger.LOGGER.nodeManagerCantOpenFile(e, serverLockFile); throw e; } - catch (IOException e) - { + catch (IOException e) { /* * on some OS's this may fail weirdly even tho the parent dir exists, retrying will work, some weird timing issue i think * */ - if (count < 5) - { - try - { + if (count < 5) { + try { Thread.sleep(100); } - catch (InterruptedException e1) - { + catch (InterruptedException e1) { } count++; continue; @@ -194,8 +172,7 @@ public abstract class NodeManager implements ActiveMQComponent ActiveMQServerLogger.LOGGER.nodeManagerCantOpenFile(e, serverLockFile); throw e; } - if (!fileCreated) - { + if (!fileCreated) { throw new IllegalStateException("Unable to create server lock file"); } } @@ -205,8 +182,7 @@ public abstract class NodeManager implements ActiveMQComponent channel = raFile.getChannel(); - if (fileCreated) - { + if (fileCreated) { ByteBuffer id = ByteBuffer.allocateDirect(3); byte[] bytes = new byte[3]; bytes[0] = FIRST_TIME_START; @@ -224,36 +200,30 @@ public abstract class NodeManager implements ActiveMQComponent /** * @return */ - protected final File newFile(final String fileName) - { + protected final File newFile(final String fileName) { File file = new File(directory, fileName); return file; } - protected final synchronized void createNodeId() throws IOException - { - synchronized (nodeIDGuard) - { + protected final synchronized void createNodeId() throws IOException { + synchronized (nodeIDGuard) { ByteBuffer id = ByteBuffer.allocateDirect(16); int read = channel.read(id, 3); - if (replicatedBackup) - { + if (replicatedBackup) { id.position(0); id.put(getUUID().asBytes(), 0, 16); id.position(0); channel.write(id, 3); channel.force(true); } - else if (read != 16) - { + else if (read != 16) { setUUID(UUIDGenerator.getInstance().generateUUID()); id.put(getUUID().asBytes(), 0, 16); id.position(0); channel.write(id, 3); channel.force(true); } - else - { + else { byte[] bytes = new byte[16]; id.position(0); id.get(bytes); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/Queue.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/Queue.java index bfc8806e35..ba12a55757 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/Queue.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/Queue.java @@ -28,8 +28,8 @@ import org.apache.activemq.artemis.core.transaction.Transaction; import org.apache.activemq.artemis.utils.LinkedListIterator; import org.apache.activemq.artemis.utils.ReferenceCounter; -public interface Queue extends Bindable -{ +public interface Queue extends Bindable { + SimpleString getName(); long getID(); @@ -159,7 +159,10 @@ public interface Queue extends Bindable int moveReferences(Filter filter, SimpleString toAddress) throws Exception; - int moveReferences(final int flushLimit, Filter filter, SimpleString toAddress, boolean rejectDuplicates) throws Exception; + int moveReferences(final int flushLimit, + Filter filter, + SimpleString toAddress, + boolean rejectDuplicates) throws Exception; void addRedistributor(long delay); @@ -173,6 +176,7 @@ public interface Queue extends Bindable /** * It will iterate thorugh memory only (not paging) + * * @return */ LinkedListIterator iterator(); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/QueueCreator.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/QueueCreator.java index 99a2d87995..f89a2b0210 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/QueueCreator.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/QueueCreator.java @@ -19,13 +19,13 @@ package org.apache.activemq.artemis.core.server; import org.apache.activemq.artemis.api.core.SimpleString; -public interface QueueCreator -{ +public interface QueueCreator { + /** - * * You should return true if you even tried to create the queue and the queue was already there. * As the callers of this method will use that as an indicator that they should re-route the messages. * * + * * @return True if a queue was created. */ boolean create(SimpleString address) throws Exception; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/QueueFactory.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/QueueFactory.java index b82e694b41..5e9f9f12ad 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/QueueFactory.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/QueueFactory.java @@ -22,14 +22,13 @@ import org.apache.activemq.artemis.core.paging.cursor.PageSubscription; import org.apache.activemq.artemis.core.postoffice.PostOffice; /** - * * A QueueFactory * * Implementations of this class know how to create queues with the correct attribute values * based on default and overrides */ -public interface QueueFactory -{ +public interface QueueFactory { + Queue createQueue(long persistenceID, final SimpleString address, SimpleString name, @@ -42,6 +41,7 @@ public interface QueueFactory /** * This is required for delete-all-reference to work correctly with paging + * * @param postOffice */ void setPostOffice(PostOffice postOffice); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/RouteContextList.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/RouteContextList.java index 89bbeaa817..b4f9bd761f 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/RouteContextList.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/RouteContextList.java @@ -21,8 +21,7 @@ import java.util.List; /** * This is a simple datatype containing the list of a routing context */ -public interface RouteContextList -{ +public interface RouteContextList { int getNumberOfNonDurableQueues(); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/RoutingContext.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/RoutingContext.java index 9ff18c9d01..32baee1b10 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/RoutingContext.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/RoutingContext.java @@ -22,8 +22,8 @@ import java.util.Map; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.transaction.Transaction; -public interface RoutingContext -{ +public interface RoutingContext { + Transaction getTransaction(); void setTransaction(Transaction transaction); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ScheduledDeliveryHandler.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ScheduledDeliveryHandler.java index 12267c2636..5afb0524a6 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ScheduledDeliveryHandler.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ScheduledDeliveryHandler.java @@ -20,8 +20,8 @@ import org.apache.activemq.artemis.core.filter.Filter; import java.util.List; -public interface ScheduledDeliveryHandler -{ +public interface ScheduledDeliveryHandler { + boolean checkAndSchedule(MessageReference ref, final boolean tail); int getScheduledCount(); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ServerConsumer.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ServerConsumer.java index dd91832ebe..6045e2c453 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ServerConsumer.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ServerConsumer.java @@ -21,14 +21,13 @@ import java.util.List; import org.apache.activemq.artemis.core.transaction.Transaction; /** - * * A ServerConsumer */ -public interface ServerConsumer extends Consumer -{ +public interface ServerConsumer extends Consumer { + /** - * @see #getProtocolContext() * @param protocolContext + * @see #getProtocolContext() */ void setProtocolContext(Object protocolContext); @@ -48,6 +47,7 @@ public interface ServerConsumer extends Consumer * This method is just to remove itself from Queues. * If for any reason during a close an exception occurred, the exception treatment * will call removeItself what should take the consumer out of any queues. + * * @throws Exception */ void removeItself() throws Exception; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ServerMessage.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ServerMessage.java index b70ed552d3..73a4df5f43 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ServerMessage.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ServerMessage.java @@ -22,11 +22,10 @@ import org.apache.activemq.artemis.core.message.impl.MessageInternal; import org.apache.activemq.artemis.core.paging.PagingStore; /** - * * A ServerMessage */ -public interface ServerMessage extends MessageInternal, EncodingSupport -{ +public interface ServerMessage extends MessageInternal, EncodingSupport { + ServerMessage setMessageID(long id); MessageReference createReference(Queue queue); @@ -34,6 +33,7 @@ public interface ServerMessage extends MessageInternal, EncodingSupport /** * This will force encoding of the address, and will re-check the buffer * This is to avoid setMessageTransient which set the address without changing the buffer + * * @param address */ void forceAddress(SimpleString address); @@ -56,7 +56,10 @@ public interface ServerMessage extends MessageInternal, EncodingSupport int getRefCount(); - ServerMessage makeCopyForExpiryOrDLA(long newID, MessageReference originalReference, boolean expiry, boolean copyOriginalHeaders) throws Exception; + ServerMessage makeCopyForExpiryOrDLA(long newID, + MessageReference originalReference, + boolean expiry, + boolean copyOriginalHeaders) throws Exception; void setOriginalHeaders(ServerMessage other, MessageReference originalReference, boolean expiry); @@ -71,7 +74,7 @@ public interface ServerMessage extends MessageInternal, EncodingSupport void encodeMessageIDToBuffer(); - byte [] getDuplicateIDBytes(); + byte[] getDuplicateIDBytes(); Object getDuplicateProperty(); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ServerSession.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ServerSession.java index 7623781a3f..66ebf93306 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ServerSession.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ServerSession.java @@ -27,8 +27,8 @@ import org.apache.activemq.artemis.core.transaction.Transaction; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; import org.apache.activemq.artemis.utils.json.JSONArray; -public interface ServerSession -{ +public interface ServerSession { + String getName(); String getUsername(); @@ -88,14 +88,17 @@ public interface ServerSession void stop(); Queue createQueue(SimpleString address, - SimpleString name, - SimpleString filterString, - boolean temporary, - boolean durable) throws Exception; + SimpleString name, + SimpleString filterString, + boolean temporary, + boolean durable) throws Exception; void deleteQueue(SimpleString name) throws Exception; - ServerConsumer createConsumer(long consumerID, SimpleString queueName, SimpleString filterString, boolean browseOnly) throws Exception; + ServerConsumer createConsumer(long consumerID, + SimpleString queueName, + SimpleString filterString, + boolean browseOnly) throws Exception; QueueQueryResult executeQueueQuery(SimpleString name) throws Exception; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ServerSessionFactory.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ServerSessionFactory.java index 66c54ca7ca..6447daa316 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ServerSessionFactory.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ServerSessionFactory.java @@ -28,18 +28,28 @@ import org.apache.activemq.artemis.core.transaction.ResourceManager; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; import org.apache.activemq.artemis.spi.core.protocol.SessionCallback; -public interface ServerSessionFactory -{ +public interface ServerSessionFactory { - ServerSessionImpl createCoreSession(String name, String username, String password, - int minLargeMessageSize, boolean autoCommitSends, - boolean autoCommitAcks, boolean preAcknowledge, - boolean persistDeliveryCountBeforeDelivery, boolean xa, - RemotingConnection connection, StorageManager storageManager, - PostOffice postOffice, ResourceManager resourceManager, - SecurityStore securityStore, ManagementService managementService, - ActiveMQServerImpl activeMQServerImpl, SimpleString managementAddress, - SimpleString simpleString, SessionCallback callback, - QueueCreator queueCreator, OperationContext context) throws Exception; + ServerSessionImpl createCoreSession(String name, + String username, + String password, + int minLargeMessageSize, + boolean autoCommitSends, + boolean autoCommitAcks, + boolean preAcknowledge, + boolean persistDeliveryCountBeforeDelivery, + boolean xa, + RemotingConnection connection, + StorageManager storageManager, + PostOffice postOffice, + ResourceManager resourceManager, + SecurityStore securityStore, + ManagementService managementService, + ActiveMQServerImpl activeMQServerImpl, + SimpleString managementAddress, + SimpleString simpleString, + SessionCallback callback, + QueueCreator queueCreator, + OperationContext context) throws Exception; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ServiceRegistry.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ServiceRegistry.java index 1ca8c9eedb..9cb1df1f45 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ServiceRegistry.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ServiceRegistry.java @@ -31,8 +31,8 @@ import java.util.concurrent.ScheduledExecutorService; /** * A holder for common services leveraged by the broker. */ -public interface ServiceRegistry -{ +public interface ServiceRegistry { + ExecutorService getExecutorService(); void setExecutorService(ExecutorService executorService); @@ -41,7 +41,8 @@ public interface ServiceRegistry void setScheduledExecutorService(ScheduledExecutorService scheduledExecutorService); - void addConnectorService(ConnectorServiceFactory connectorServiceFactory, ConnectorServiceConfiguration configuration); + void addConnectorService(ConnectorServiceFactory connectorServiceFactory, + ConnectorServiceConfiguration configuration); void removeConnectorService(ConnectorServiceConfiguration configuration); @@ -77,7 +78,7 @@ public interface ServiceRegistry /** * Get an instance of org.apache.activemq.artemis.core.server.cluster.Transformer for a divert * - * @param name the name of divert for which the transformer will be used + * @param name the name of divert for which the transformer will be used * @param className the fully qualified name of the transformer implementation (can be null) * @return */ @@ -88,7 +89,7 @@ public interface ServiceRegistry /** * Get an instance of org.apache.activemq.artemis.core.server.cluster.Transformer for a bridge * - * @param name the name of bridge for which the transformer will be used + * @param name the name of bridge for which the transformer will be used * @param className the fully qualified name of the transformer implementation (can be null) * @return */ @@ -99,7 +100,7 @@ public interface ServiceRegistry /** * Get an instance of org.apache.activemq.artemis.spi.core.remoting.AcceptorFactory * - * @param name the name of acceptor for which the factory will be used + * @param name the name of acceptor for which the factory will be used * @param className the fully qualified name of the factory implementation (can be null) * @return */ diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/TransientQueueManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/TransientQueueManager.java index c7412decb3..6a2aef88a5 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/TransientQueueManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/TransientQueueManager.java @@ -19,7 +19,7 @@ package org.apache.activemq.artemis.core.server; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.utils.ReferenceCounter; -public interface TransientQueueManager extends ReferenceCounter -{ +public interface TransientQueueManager extends ReferenceCounter { + SimpleString getQueueName(); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ActiveMQServerSideProtocolManagerFactory.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ActiveMQServerSideProtocolManagerFactory.java index 576a55b39a..d5c0d3818a 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ActiveMQServerSideProtocolManagerFactory.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ActiveMQServerSideProtocolManagerFactory.java @@ -25,32 +25,28 @@ import org.apache.activemq.artemis.spi.core.remoting.ClientProtocolManagerFactor /** * A protocol manager that will replace the packet manager for inter-server communications */ -public class ActiveMQServerSideProtocolManagerFactory implements ClientProtocolManagerFactory -{ +public class ActiveMQServerSideProtocolManagerFactory implements ClientProtocolManagerFactory { + private static final ActiveMQServerSideProtocolManagerFactory INSTANCE = new ActiveMQServerSideProtocolManagerFactory(); - public static ActiveMQServerSideProtocolManagerFactory getInstance() - { + public static ActiveMQServerSideProtocolManagerFactory getInstance() { return INSTANCE; } - private ActiveMQServerSideProtocolManagerFactory() - { + private ActiveMQServerSideProtocolManagerFactory() { } private static final long serialVersionUID = 1; @Override - public ClientProtocolManager newProtocolManager() - { + public ClientProtocolManager newProtocolManager() { return new ActiveMQReplicationProtocolManager(); } - class ActiveMQReplicationProtocolManager extends ActiveMQClientProtocolManager - { + class ActiveMQReplicationProtocolManager extends ActiveMQClientProtocolManager { + @Override - protected PacketDecoder getPacketDecoder() - { + protected PacketDecoder getPacketDecoder() { return ServerPacketDecoder.INSTANCE; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/BackupManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/BackupManager.java index 36d047e71a..44d28c0658 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/BackupManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/BackupManager.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.core.server.cluster; - import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -42,8 +41,8 @@ import org.apache.activemq.artemis.utils.ExecutorFactory; /* * takes care of updating the cluster with a backups transport configuration which is based on each cluster connection. * */ -public class BackupManager implements ActiveMQComponent -{ +public class BackupManager implements ActiveMQComponent { + private ActiveMQServer server; private Executor executor; private ScheduledExecutorService scheduledExecutor; @@ -55,9 +54,12 @@ public class BackupManager implements ActiveMQComponent private boolean started; - public BackupManager(ActiveMQServer server, ExecutorFactory executorFactory, ScheduledExecutorService scheduledExecutor, NodeManager nodeManager, - Configuration configuration, ClusterManager clusterManager) - { + public BackupManager(ActiveMQServer server, + ExecutorFactory executorFactory, + ScheduledExecutorService scheduledExecutor, + NodeManager nodeManager, + Configuration configuration, + ClusterManager clusterManager) { this.server = server; this.executor = executorFactory.getExecutor(); this.scheduledExecutor = scheduledExecutor; @@ -70,21 +72,18 @@ public class BackupManager implements ActiveMQComponent * Start the backup manager if not already started. This entails deploying a backup connector based on a cluster * configuration, informing the cluster manager so that it can add it to its topology and announce itself to the cluster. * */ - public synchronized void start() - { - if (started) return; + public synchronized void start() { + if (started) + return; //deploy the backup connectors using the cluster configuration - for (ClusterConnectionConfiguration config : configuration.getClusterConfigurations()) - { + for (ClusterConnectionConfiguration config : configuration.getClusterConfigurations()) { deployBackupConnector(config); } //start each connector and if we are backup and shared store announce ourselves. NB with replication we dont do this //as we wait for replication to start and be notififed by the replication manager. - for (BackupConnector conn : backupConnectors) - { + for (BackupConnector conn : backupConnectors) { conn.start(); - if (server.getHAPolicy().isBackup() && server.getHAPolicy().isSharedStore()) - { + if (server.getHAPolicy().isBackup() && server.getHAPolicy().isSharedStore()) { conn.informTopology(); conn.announceBackup(); } @@ -95,11 +94,10 @@ public class BackupManager implements ActiveMQComponent /* * stop all the connectors * */ - public synchronized void stop() - { - if (!started) return; - for (BackupConnector backupConnector : backupConnectors) - { + public synchronized void stop() { + if (!started) + return; + for (BackupConnector backupConnector : backupConnectors) { backupConnector.close(); } started = false; @@ -108,10 +106,8 @@ public class BackupManager implements ActiveMQComponent /* * announce the fact that we are a backup server ready to fail over if required. */ - public void announceBackup() - { - for (BackupConnector backupConnector : backupConnectors) - { + public void announceBackup() { + for (BackupConnector backupConnector : backupConnectors) { backupConnector.announceBackup(); } } @@ -119,30 +115,26 @@ public class BackupManager implements ActiveMQComponent /* * create the connectors using the cluster configurations * */ - private void deployBackupConnector(final ClusterConnectionConfiguration config) - { + private void deployBackupConnector(final ClusterConnectionConfiguration config) { TransportConfiguration connector = ClusterConfigurationUtil.getTransportConfiguration(config, configuration); - if (connector == null) return; + if (connector == null) + return; - if (config.getDiscoveryGroupName() != null) - { + if (config.getDiscoveryGroupName() != null) { DiscoveryGroupConfiguration dg = ClusterConfigurationUtil.getDiscoveryGroupConfiguration(config, configuration); - if (dg == null) return; + if (dg == null) + return; - - DiscoveryBackupConnector backupConnector = new DiscoveryBackupConnector(dg, config.getName(), connector, - config.getRetryInterval(), clusterManager); + DiscoveryBackupConnector backupConnector = new DiscoveryBackupConnector(dg, config.getName(), connector, config.getRetryInterval(), clusterManager); backupConnectors.add(backupConnector); } - else - { + else { TransportConfiguration[] tcConfigs = ClusterConfigurationUtil.getTransportConfigurations(config, configuration); - StaticBackupConnector backupConnector = new StaticBackupConnector(tcConfigs, config.getName(), connector, - config.getRetryInterval(), clusterManager); + StaticBackupConnector backupConnector = new StaticBackupConnector(tcConfigs, config.getName(), connector, config.getRetryInterval(), clusterManager); backupConnectors.add(backupConnector); } @@ -151,26 +143,20 @@ public class BackupManager implements ActiveMQComponent /* * called to notify us that we have been activated as a live server so the connectors are no longer needed. * */ - public void activated() - { - for (BackupConnector backupConnector : backupConnectors) - { + public void activated() { + for (BackupConnector backupConnector : backupConnectors) { backupConnector.close(); } } @Override - public boolean isStarted() - { + public boolean isStarted() { return started; } - public boolean isBackupAnnounced() - { - for (BackupConnector backupConnector : backupConnectors) - { - if (!backupConnector.isBackupAnnounced()) - { + public boolean isBackupAnnounced() { + for (BackupConnector backupConnector : backupConnectors) { + if (!backupConnector.isBackupAnnounced()) { return false; } } @@ -180,8 +166,8 @@ public class BackupManager implements ActiveMQComponent /* * A backup connector will connect to the cluster and announce that we are a backup server ready to fail over. * */ - private abstract class BackupConnector - { + private abstract class BackupConnector { + private volatile ServerLocatorInternal backupServerLocator; private String name; private TransportConfiguration connector; @@ -191,9 +177,10 @@ public class BackupManager implements ActiveMQComponent private boolean announcingBackup; private boolean backupAnnounced = false; - public BackupConnector(String name, TransportConfiguration connector, long retryInterval, - ClusterManager clusterManager) - { + public BackupConnector(String name, + TransportConfiguration connector, + long retryInterval, + ClusterManager clusterManager) { this.name = name; this.connector = connector; this.retryInterval = retryInterval; @@ -208,8 +195,7 @@ public class BackupManager implements ActiveMQComponent /* * start the connector by creating the server locator to use. * */ - void start() - { + void start() { stopping = false; backupAnnounced = false; @@ -217,8 +203,7 @@ public class BackupManager implements ActiveMQComponent //NB we use the same topology as the sister cluster connection so it knows when started about all the nodes to bridge to backupServerLocator = createServerLocator(clusterConnection.getTopology()); - if (backupServerLocator != null) - { + if (backupServerLocator != null) { backupServerLocator.setIdentity("backupLocatorFor='" + server + "'"); backupServerLocator.setReconnectAttempts(-1); backupServerLocator.setInitialConnectAttempts(-1); @@ -229,72 +214,54 @@ public class BackupManager implements ActiveMQComponent /* * this connects to the cluster and announces that we are a backup * */ - public void announceBackup() - { + public void announceBackup() { //this has to be done in a separate thread - executor.execute(new Runnable() - { + executor.execute(new Runnable() { - public void run() - { + public void run() { if (stopping) return; - try - { + try { //make a copy to avoid npe if we are nulled on close ServerLocatorInternal localBackupLocator = backupServerLocator; - if (localBackupLocator == null) - { + if (localBackupLocator == null) { if (!stopping) ActiveMQServerLogger.LOGGER.error("Error announcing backup: backupServerLocator is null. " + this); return; } - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug(BackupConnector.this + ":: announcing " + connector + " to " + backupServerLocator); } announcingBackup = true; //connect to the cluster ClientSessionFactoryInternal backupSessionFactory = localBackupLocator.connect(); //send the announce message - if (backupSessionFactory != null) - { + if (backupSessionFactory != null) { ClusterControl clusterControl = clusterManager.getClusterController().connectToNodeInCluster(backupSessionFactory); clusterControl.authorize(); - clusterControl.sendNodeAnnounce(System.currentTimeMillis(), - nodeManager.getNodeId().toString(), - server.getHAPolicy().getBackupGroupName(), - server.getHAPolicy().getScaleDownClustername(), - true, - connector, - null); + clusterControl.sendNodeAnnounce(System.currentTimeMillis(), nodeManager.getNodeId().toString(), server.getHAPolicy().getBackupGroupName(), server.getHAPolicy().getScaleDownClustername(), true, connector, null); ActiveMQServerLogger.LOGGER.backupAnnounced(); backupAnnounced = true; } } - catch (RejectedExecutionException e) - { + catch (RejectedExecutionException e) { // assumption is that the whole server is being stopped. So the exception is ignored. } - catch (Exception e) - { + catch (Exception e) { if (scheduledExecutor.isShutdown()) return; if (stopping) return; ActiveMQServerLogger.LOGGER.errorAnnouncingBackup(); - scheduledExecutor.schedule(new Runnable() - { - public void run() - { + scheduledExecutor.schedule(new Runnable() { + public void run() { announceBackup(); } }, retryInterval, TimeUnit.MILLISECONDS); } - finally - { + finally { announcingBackup = false; } } @@ -304,31 +271,25 @@ public class BackupManager implements ActiveMQComponent /* * called to notify the cluster manager about the backup * */ - public void informTopology() - { + public void informTopology() { clusterManager.informClusterOfBackup(name); } /* * close everything * */ - public void close() - { + public void close() { stopping = true; - if (announcingBackup) - { + if (announcingBackup) { /* * The executor used is ordered so if we are announcing the backup, scheduling the following * Runnable would never execute. */ closeLocator(backupServerLocator); } - executor.execute(new Runnable() - { - public void run() - { - synchronized (BackupConnector.this) - { + executor.execute(new Runnable() { + public void run() { + synchronized (BackupConnector.this) { closeLocator(backupServerLocator); backupServerLocator = null; } @@ -337,15 +298,12 @@ public class BackupManager implements ActiveMQComponent }); } - public boolean isBackupAnnounced() - { + public boolean isBackupAnnounced() { return backupAnnounced; } - private void closeLocator(ServerLocatorInternal backupServerLocator) - { - if (backupServerLocator != null) - { + private void closeLocator(ServerLocatorInternal backupServerLocator) { + if (backupServerLocator != null) { backupServerLocator.close(); } } @@ -354,23 +312,22 @@ public class BackupManager implements ActiveMQComponent /* * backup connector using static connectors * */ - private final class StaticBackupConnector extends BackupConnector - { + private final class StaticBackupConnector extends BackupConnector { + private final TransportConfiguration[] tcConfigs; - public StaticBackupConnector(TransportConfiguration[] tcConfigs, String name, TransportConfiguration connector, long retryInterval, - ClusterManager clusterManager) - { + public StaticBackupConnector(TransportConfiguration[] tcConfigs, + String name, + TransportConfiguration connector, + long retryInterval, + ClusterManager clusterManager) { super(name, connector, retryInterval, clusterManager); this.tcConfigs = tcConfigs; } - public ServerLocatorInternal createServerLocator(Topology topology) - { - if (tcConfigs != null && tcConfigs.length > 0) - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + public ServerLocatorInternal createServerLocator(Topology topology) { + if (tcConfigs != null && tcConfigs.length > 0) { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug(BackupManager.this + "Creating a serverLocator for " + Arrays.toString(tcConfigs)); } ServerLocatorImpl locator = new ServerLocatorImpl(topology, true, tcConfigs); @@ -382,8 +339,7 @@ public class BackupManager implements ActiveMQComponent } @Override - public String toString() - { + public String toString() { return "StaticBackupConnector [tcConfigs=" + Arrays.toString(tcConfigs) + "]"; } @@ -392,26 +348,25 @@ public class BackupManager implements ActiveMQComponent /* * backup connector using discovery * */ - private final class DiscoveryBackupConnector extends BackupConnector - { + private final class DiscoveryBackupConnector extends BackupConnector { private final DiscoveryGroupConfiguration discoveryGroupConfiguration; - public DiscoveryBackupConnector(DiscoveryGroupConfiguration discoveryGroupConfiguration, String name, TransportConfiguration connector, long retryInterval, - ClusterManager clusterManager) - { + public DiscoveryBackupConnector(DiscoveryGroupConfiguration discoveryGroupConfiguration, + String name, + TransportConfiguration connector, + long retryInterval, + ClusterManager clusterManager) { super(name, connector, retryInterval, clusterManager); this.discoveryGroupConfiguration = discoveryGroupConfiguration; } - public ServerLocatorInternal createServerLocator(Topology topology) - { + public ServerLocatorInternal createServerLocator(Topology topology) { return new ServerLocatorImpl(topology, true, discoveryGroupConfiguration); } @Override - public String toString() - { + public String toString() { return "DiscoveryBackupConnector [group=" + discoveryGroupConfiguration + "]"; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/Bridge.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/Bridge.java index 81607880ed..65d19d6136 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/Bridge.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/Bridge.java @@ -26,8 +26,8 @@ import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; /** * A Core Bridge */ -public interface Bridge extends Consumer, ActiveMQComponent -{ +public interface Bridge extends Consumer, ActiveMQComponent { + SimpleString getName(); Queue getQueue(); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/BroadcastGroup.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/BroadcastGroup.java index 57478187ec..9bb410c329 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/BroadcastGroup.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/BroadcastGroup.java @@ -20,8 +20,8 @@ import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.core.server.ActiveMQComponent; import org.apache.activemq.artemis.core.server.management.NotificationService; -public interface BroadcastGroup extends ActiveMQComponent -{ +public interface BroadcastGroup extends ActiveMQComponent { + void setNotificationService(NotificationService notificationService); String getName(); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterConfigurationUtil.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterConfigurationUtil.java index c6a7a94f58..0d6b761a43 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterConfigurationUtil.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterConfigurationUtil.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.core.server.cluster; - import org.apache.activemq.artemis.api.core.DiscoveryGroupConfiguration; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.core.config.ClusterConnectionConfiguration; @@ -26,19 +25,17 @@ import org.apache.activemq.artemis.core.server.ActiveMQServerLogger; import java.lang.reflect.Array; import java.util.List; -public class ClusterConfigurationUtil -{ - public static TransportConfiguration getTransportConfiguration(ClusterConnectionConfiguration config, Configuration configuration) - { - if (config.getName() == null) - { +public class ClusterConfigurationUtil { + + public static TransportConfiguration getTransportConfiguration(ClusterConnectionConfiguration config, + Configuration configuration) { + if (config.getName() == null) { ActiveMQServerLogger.LOGGER.clusterConnectionNotUnique(); return null; } - if (config.getAddress() == null) - { + if (config.getAddress() == null) { ActiveMQServerLogger.LOGGER.clusterConnectionNoForwardAddress(); return null; @@ -46,44 +43,37 @@ public class ClusterConfigurationUtil TransportConfiguration connector = configuration.getConnectorConfigurations().get(config.getConnectorName()); - if (connector == null) - { + if (connector == null) { ActiveMQServerLogger.LOGGER.clusterConnectionNoConnector(config.getConnectorName()); return null; } return connector; } - public static DiscoveryGroupConfiguration getDiscoveryGroupConfiguration(ClusterConnectionConfiguration config, Configuration configuration) - { - DiscoveryGroupConfiguration dg = configuration.getDiscoveryGroupConfigurations() - .get(config.getDiscoveryGroupName()); + public static DiscoveryGroupConfiguration getDiscoveryGroupConfiguration(ClusterConnectionConfiguration config, + Configuration configuration) { + DiscoveryGroupConfiguration dg = configuration.getDiscoveryGroupConfigurations().get(config.getDiscoveryGroupName()); - if (dg == null) - { + if (dg == null) { ActiveMQServerLogger.LOGGER.clusterConnectionNoDiscoveryGroup(config.getDiscoveryGroupName()); return null; } return dg; } - public static TransportConfiguration[] getTransportConfigurations(ClusterConnectionConfiguration config, Configuration configuration) - { - return config.getStaticConnectors() != null ? connectorNameListToArray(config.getStaticConnectors(), configuration) - : null; + public static TransportConfiguration[] getTransportConfigurations(ClusterConnectionConfiguration config, + Configuration configuration) { + return config.getStaticConnectors() != null ? connectorNameListToArray(config.getStaticConnectors(), configuration) : null; } - public static TransportConfiguration[] connectorNameListToArray(final List connectorNames, Configuration configuration) - { - TransportConfiguration[] tcConfigs = (TransportConfiguration[]) Array.newInstance(TransportConfiguration.class, - connectorNames.size()); + public static TransportConfiguration[] connectorNameListToArray(final List connectorNames, + Configuration configuration) { + TransportConfiguration[] tcConfigs = (TransportConfiguration[]) Array.newInstance(TransportConfiguration.class, connectorNames.size()); int count = 0; - for (String connectorName : connectorNames) - { + for (String connectorName : connectorNames) { TransportConfiguration connector = configuration.getConnectorConfigurations().get(connectorName); - if (connector == null) - { + if (connector == null) { ActiveMQServerLogger.LOGGER.bridgeNoConnector(connectorName); return null; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterConnection.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterConnection.java index 8b93fdb830..7134bd3e8e 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterConnection.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterConnection.java @@ -26,15 +26,20 @@ import org.apache.activemq.artemis.core.client.impl.Topology; import org.apache.activemq.artemis.core.server.ActiveMQComponent; import org.apache.activemq.artemis.core.server.ActiveMQServer; -public interface ClusterConnection extends ActiveMQComponent, ClusterTopologyListener -{ +public interface ClusterConnection extends ActiveMQComponent, ClusterTopologyListener { + SimpleString getName(); String getNodeID(); ActiveMQServer getServer(); - void nodeAnnounced(long eventUID, String nodeID, String backupGroupName, String scaleDownGroupName, Pair connectorPair, boolean backup); + void nodeAnnounced(long eventUID, + String nodeID, + String backupGroupName, + String scaleDownGroupName, + Pair connectorPair, + boolean backup); void addClusterTopologyListener(ClusterTopologyListener listener); @@ -42,6 +47,7 @@ public interface ClusterConnection extends ActiveMQComponent, ClusterTopologyLis /** * Only used for tests? + * * @return a Map of node ID and addresses */ Map getNodes(); @@ -61,6 +67,7 @@ public interface ClusterConnection extends ActiveMQComponent, ClusterTopologyLis /** * Verifies whether user and password match the ones configured for this ClusterConnection. + * * @param clusterUser * @param clusterPassword * @return {@code true} if username and password match, {@code false} otherwise. diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterControl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterControl.java index 392b095e38..bfcff92bea 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterControl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterControl.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.core.server.cluster; - import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.TransportConfiguration; @@ -46,8 +45,8 @@ import org.apache.activemq.artemis.core.server.cluster.qourum.Vote; * handles the communication between a cluster node and the cluster, either the whole cluster or a specific node in the * cluster such as a replicating node. */ -public class ClusterControl implements AutoCloseable -{ +public class ClusterControl implements AutoCloseable { + private Channel clusterChannel; private final ClientSessionFactoryInternal sessionFactory; @@ -58,8 +57,7 @@ public class ClusterControl implements AutoCloseable private final String clusterPassword; - public ClusterControl(ClientSessionFactoryInternal sessionFactory, ActiveMQServer server) - { + public ClusterControl(ClientSessionFactoryInternal sessionFactory, ActiveMQServer server) { this.sessionFactory = sessionFactory; this.server = server; this.clusterUser = server.getConfiguration().getClusterUser(); @@ -72,17 +70,14 @@ public class ClusterControl implements AutoCloseable * * @throws ActiveMQException if authorisation wasn't successful. */ - public void authorize() throws ActiveMQException - { - CoreRemotingConnection connection = (CoreRemotingConnection)sessionFactory.getConnection(); + public void authorize() throws ActiveMQException { + CoreRemotingConnection connection = (CoreRemotingConnection) sessionFactory.getConnection(); clusterChannel = connection.getChannel(ChannelImpl.CHANNEL_ID.CLUSTER.id, -1); - ClusterConnectReplyMessage packet = - (ClusterConnectReplyMessage) clusterChannel.sendBlocking(new ClusterConnectMessage(clusterUser, clusterPassword), PacketImpl.CLUSTER_CONNECT_REPLY); + ClusterConnectReplyMessage packet = (ClusterConnectReplyMessage) clusterChannel.sendBlocking(new ClusterConnectMessage(clusterUser, clusterPassword), PacketImpl.CLUSTER_CONNECT_REPLY); - if (!packet.isAuthorized()) - { + if (!packet.isAuthorized()) { throw ActiveMQMessageBundle.BUNDLE.unableToValidateClusterUser(clusterUser); } } @@ -95,20 +90,18 @@ public class ClusterControl implements AutoCloseable * server. * @throws ActiveMQException */ - public void announceReplicatingBackupToLive(final boolean attemptingFailBack, String replicationClusterName) throws ActiveMQException - { + public void announceReplicatingBackupToLive(final boolean attemptingFailBack, + String replicationClusterName) throws ActiveMQException { ClusterConnectionConfiguration config = ConfigurationUtils.getReplicationClusterConfiguration(server.getConfiguration(), replicationClusterName); - if (config == null) - { + if (config == null) { ActiveMQServerLogger.LOGGER.announceBackupNoClusterConnections(); throw new ActiveMQException("lacking cluster connection"); } TransportConfiguration connector = server.getConfiguration().getConnectorConfigurations().get(config.getConnectorName()); - if (connector == null) - { + if (connector == null) { ActiveMQServerLogger.LOGGER.announceBackupNoConnector(config.getConnectorName()); throw new ActiveMQException("lacking cluster connection"); } @@ -119,13 +112,13 @@ public class ClusterControl implements AutoCloseable /** * announce this node to the cluster. * - * @param currentEventID used if multiple announcements about this node are made. - * @param nodeID the node id if the announcing node - * @param backupGroupName the backup group name. + * @param currentEventID used if multiple announcements about this node are made. + * @param nodeID the node id if the announcing node + * @param backupGroupName the backup group name. * @param scaleDownGroupName the scaledown group name - * @param isBackup are we a backup - * @param config the transports config - * @param backupConfig the transports backup config + * @param isBackup are we a backup + * @param config the transports config + * @param backupConfig the transports backup config */ public void sendNodeAnnounce(final long currentEventID, String nodeID, @@ -133,8 +126,7 @@ public class ClusterControl implements AutoCloseable String scaleDownGroupName, boolean isBackup, TransportConfiguration config, - TransportConfiguration backupConfig) - { + TransportConfiguration backupConfig) { clusterChannel.send(new NodeAnnounceMessage(currentEventID, nodeID, backupGroupName, scaleDownGroupName, isBackup, config, backupConfig)); } @@ -143,9 +135,8 @@ public class ClusterControl implements AutoCloseable * * @return the replication channel */ - public Channel createReplicationChannel() - { - CoreRemotingConnection connection = (CoreRemotingConnection)sessionFactory.getConnection(); + public Channel createReplicationChannel() { + CoreRemotingConnection connection = (CoreRemotingConnection) sessionFactory.getConnection(); return connection.getChannel(ChannelImpl.CHANNEL_ID.REPLICATION.id, -1); } @@ -154,63 +145,55 @@ public class ClusterControl implements AutoCloseable * * @return the session factory */ - public ClientSessionFactoryInternal getSessionFactory() - { + public ClientSessionFactoryInternal getSessionFactory() { return sessionFactory; } /** * close this cluster control and its resources */ - public void close() - { + public void close() { sessionFactory.close(); } - public Vote sendQuorumVote(SimpleString handler, Vote vote) - { - try - { - QuorumVoteReplyMessage replyMessage = (QuorumVoteReplyMessage) - clusterChannel.sendBlocking(new QuorumVoteMessage(handler, vote), PacketImpl.QUORUM_VOTE_REPLY); + public Vote sendQuorumVote(SimpleString handler, Vote vote) { + try { + QuorumVoteReplyMessage replyMessage = (QuorumVoteReplyMessage) clusterChannel.sendBlocking(new QuorumVoteMessage(handler, vote), PacketImpl.QUORUM_VOTE_REPLY); QuorumVoteHandler voteHandler = server.getClusterManager().getQuorumManager().getVoteHandler(replyMessage.getHandler()); replyMessage.decodeRest(voteHandler); return replyMessage.getVote(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { return null; } } - public boolean requestReplicatedBackup(int backupSize, SimpleString nodeID) - { + public boolean requestReplicatedBackup(int backupSize, SimpleString nodeID) { BackupRequestMessage backupRequestMessage = new BackupRequestMessage(backupSize, nodeID); return requestBackup(backupRequestMessage); } - private boolean requestBackup(BackupRequestMessage backupRequestMessage) - { + private boolean requestBackup(BackupRequestMessage backupRequestMessage) { BackupResponseMessage packet; - try - { + try { packet = (BackupResponseMessage) clusterChannel.sendBlocking(backupRequestMessage, PacketImpl.BACKUP_REQUEST_RESPONSE); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { return false; } return packet.isBackupStarted(); } - public boolean requestSharedStoreBackup(int backupSize, String journalDirectory, String bindingsDirectory, String largeMessagesDirectory, String pagingDirectory) - { + public boolean requestSharedStoreBackup(int backupSize, + String journalDirectory, + String bindingsDirectory, + String largeMessagesDirectory, + String pagingDirectory) { BackupRequestMessage backupRequestMessage = new BackupRequestMessage(backupSize, journalDirectory, bindingsDirectory, largeMessagesDirectory, pagingDirectory); return requestBackup(backupRequestMessage); } - public void announceScaleDown(SimpleString targetNodeId, SimpleString scaledDownNodeId) - { + public void announceScaleDown(SimpleString targetNodeId, SimpleString scaledDownNodeId) { ScaleDownAnnounceMessage announceMessage = new ScaleDownAnnounceMessage(targetNodeId, scaledDownNodeId); clusterChannel.send(announceMessage); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterController.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterController.java index a3a4f64c3c..1a115cfb24 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterController.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterController.java @@ -60,8 +60,8 @@ import org.apache.activemq.artemis.spi.core.remoting.Acceptor; /** * used for creating and managing cluster control connections for each cluster connection and the replication connection */ -public class ClusterController implements ActiveMQComponent -{ +public class ClusterController implements ActiveMQComponent { + private static final boolean isTrace = ActiveMQServerLogger.LOGGER.isTraceEnabled(); private final QuorumManager quorumManager; @@ -83,32 +83,27 @@ public class ClusterController implements ActiveMQComponent private boolean started; private SimpleString replicatedClusterName; - public ClusterController(ActiveMQServer server, ScheduledExecutorService scheduledExecutor) - { + public ClusterController(ActiveMQServer server, ScheduledExecutorService scheduledExecutor) { this.server = server; executor = server.getExecutorFactory().getExecutor(); quorumManager = new QuorumManager(scheduledExecutor, this); } @Override - public void start() throws Exception - { + public void start() throws Exception { if (started) return; //set the default locator that will be used to connecting to the default cluster. defaultLocator = locators.get(defaultClusterConnectionName); //create a locator for replication, either the default or the specified if not set - if (replicatedClusterName != null && !replicatedClusterName.equals(defaultClusterConnectionName)) - { + if (replicatedClusterName != null && !replicatedClusterName.equals(defaultClusterConnectionName)) { replicationLocator = locators.get(replicatedClusterName); - if (replicationLocator == null) - { + if (replicationLocator == null) { ActiveMQServerLogger.LOGGER.noClusterConnectionForReplicationCluster(); replicationLocator = defaultLocator; } } - else - { + else { replicationLocator = defaultLocator; } //latch so we know once we are connected @@ -119,21 +114,17 @@ public class ClusterController implements ActiveMQComponent quorumManager.start(); started = true; //connect all the locators in a separate thread - for (ServerLocatorInternal serverLocatorInternal : locators.values()) - { - if (serverLocatorInternal.isConnectable()) - { + for (ServerLocatorInternal serverLocatorInternal : locators.values()) { + if (serverLocatorInternal.isConnectable()) { executor.execute(new ConnectRunnable(serverLocatorInternal)); } } } @Override - public void stop() throws Exception - { + public void stop() throws Exception { //close all the locators - for (ServerLocatorInternal serverLocatorInternal : locators.values()) - { + for (ServerLocatorInternal serverLocatorInternal : locators.values()) { serverLocatorInternal.close(); } //stop the quorum manager @@ -142,31 +133,29 @@ public class ClusterController implements ActiveMQComponent } @Override - public boolean isStarted() - { + public boolean isStarted() { return started; } - public QuorumManager getQuorumManager() - { + public QuorumManager getQuorumManager() { return quorumManager; } //set the default cluster connections name - public void setDefaultClusterConnectionName(SimpleString defaultClusterConnection) - { + public void setDefaultClusterConnectionName(SimpleString defaultClusterConnection) { this.defaultClusterConnectionName = defaultClusterConnection; } /** * add a locator for a cluster connection. * - * @param name the cluster connection name - * @param dg the discovery group to use + * @param name the cluster connection name + * @param dg the discovery group to use * @param config the cluster connection config */ - public void addClusterConnection(SimpleString name, DiscoveryGroupConfiguration dg, ClusterConnectionConfiguration config) - { + public void addClusterConnection(SimpleString name, + DiscoveryGroupConfiguration dg, + ClusterConnectionConfiguration config) { ServerLocatorImpl serverLocator = (ServerLocatorImpl) ActiveMQClient.createServerLocatorWithHA(dg); configAndAdd(name, serverLocator, config); } @@ -174,17 +163,19 @@ public class ClusterController implements ActiveMQComponent /** * add a locator for a cluster connection. * - * @param name the cluster connection name + * @param name the cluster connection name * @param tcConfigs the transport configurations to use */ - public void addClusterConnection(SimpleString name, TransportConfiguration[] tcConfigs, ClusterConnectionConfiguration config) - { + public void addClusterConnection(SimpleString name, + TransportConfiguration[] tcConfigs, + ClusterConnectionConfiguration config) { ServerLocatorImpl serverLocator = (ServerLocatorImpl) ActiveMQClient.createServerLocatorWithHA(tcConfigs); configAndAdd(name, serverLocator, config); } - private void configAndAdd(SimpleString name, ServerLocatorInternal serverLocator, ClusterConnectionConfiguration config) - { + private void configAndAdd(SimpleString name, + ServerLocatorInternal serverLocator, + ClusterConnectionConfiguration config) { serverLocator.setConnectionTTL(config.getConnectionTTL()); serverLocator.setClientFailureCheckPeriod(config.getClientFailureCheckPeriod()); //if the cluster isn't available we want to hang around until it is @@ -200,8 +191,7 @@ public class ClusterController implements ActiveMQComponent * * @param listener */ - public void addClusterTopologyListenerForReplication(ClusterTopologyListener listener) - { + public void addClusterTopologyListenerForReplication(ClusterTopologyListener listener) { replicationLocator.addClusterTopologyListener(listener); } @@ -210,22 +200,18 @@ public class ClusterController implements ActiveMQComponent * * @param interceptor */ - public void addIncomingInterceptorForReplication(Interceptor interceptor) - { + public void addIncomingInterceptorForReplication(Interceptor interceptor) { replicationLocator.addIncomingInterceptor(interceptor); } - /** * connect to a specific node in the cluster used for replication * * @param transportConfiguration the configuration of the node to connect to. - * * @return the Cluster Control * @throws Exception */ - public ClusterControl connectToNode(TransportConfiguration transportConfiguration) throws Exception - { + public ClusterControl connectToNode(TransportConfiguration transportConfiguration) throws Exception { ClientSessionFactoryInternal sessionFactory = (ClientSessionFactoryInternal) defaultLocator.createSessionFactory(transportConfiguration, 0, false); return connectToNodeInCluster(sessionFactory); @@ -235,12 +221,10 @@ public class ClusterController implements ActiveMQComponent * connect to a specific node in the cluster used for replication * * @param transportConfiguration the configuration of the node to connect to. - * * @return the Cluster Control * @throws Exception */ - public ClusterControl connectToNodeInReplicatedCluster(TransportConfiguration transportConfiguration) throws Exception - { + public ClusterControl connectToNodeInReplicatedCluster(TransportConfiguration transportConfiguration) throws Exception { ClientSessionFactoryInternal sessionFactory = (ClientSessionFactoryInternal) replicationLocator.createSessionFactory(transportConfiguration, 0, false); return connectToNodeInCluster(sessionFactory); @@ -250,11 +234,9 @@ public class ClusterController implements ActiveMQComponent * connect to an already defined node in the cluster * * @param sf the session factory - * - * @return the Cluster Control + * @return the Cluster Control */ - public ClusterControl connectToNodeInCluster(ClientSessionFactoryInternal sf) - { + public ClusterControl connectToNodeInCluster(ClientSessionFactoryInternal sf) { sf.getServerLocator().setProtocolManagerFactory(ActiveMQServerSideProtocolManagerFactory.getInstance()); return new ClusterControl(sf, server); } @@ -264,72 +246,69 @@ public class ClusterController implements ActiveMQComponent * * @return the retry interval */ - public long getRetryIntervalForReplicatedCluster() - { + public long getRetryIntervalForReplicatedCluster() { return replicationLocator.getRetryInterval(); } - /** * wait until we have connected to the cluster. * * @throws InterruptedException */ - public void awaitConnectionToReplicationCluster() throws InterruptedException - { + public void awaitConnectionToReplicationCluster() throws InterruptedException { replicationClusterConnectedLatch.await(); } /** * used to set a channel handler on the connection that can be used by the cluster control - * @param channel the channel to set the handler - * @param acceptorUsed the acceptor used for connection + * + * @param channel the channel to set the handler + * @param acceptorUsed the acceptor used for connection * @param remotingConnection the connection itself * @param activation */ - public void addClusterChannelHandler(Channel channel, Acceptor acceptorUsed, CoreRemotingConnection remotingConnection, Activation activation) - { + public void addClusterChannelHandler(Channel channel, + Acceptor acceptorUsed, + CoreRemotingConnection remotingConnection, + Activation activation) { channel.setHandler(new ClusterControllerChannelHandler(channel, acceptorUsed, remotingConnection, activation.getActivationChannelHandler(channel, acceptorUsed))); } - public int getDefaultClusterSize() - { + public int getDefaultClusterSize() { return defaultLocator.getTopology().getMembers().size(); } - public Topology getDefaultClusterTopology() - { + public Topology getDefaultClusterTopology() { return defaultLocator.getTopology(); } - public SimpleString getNodeID() - { + public SimpleString getNodeID() { return server.getNodeID(); } - public String getIdentity() - { + public String getIdentity() { return server.getIdentity(); } - public void setReplicatedClusterName(String replicatedClusterName) - { + public void setReplicatedClusterName(String replicatedClusterName) { this.replicatedClusterName = new SimpleString(replicatedClusterName); } /** * a handler for handling packets sent between the cluster. */ - private final class ClusterControllerChannelHandler implements ChannelHandler - { + private final class ClusterControllerChannelHandler implements ChannelHandler { + private final Channel clusterChannel; private final Acceptor acceptorUsed; private final CoreRemotingConnection remotingConnection; private final ChannelHandler channelHandler; boolean authorized = false; - public ClusterControllerChannelHandler(Channel clusterChannel, Acceptor acceptorUsed, CoreRemotingConnection remotingConnection, ChannelHandler channelHandler) - { + public ClusterControllerChannelHandler(Channel clusterChannel, + Acceptor acceptorUsed, + CoreRemotingConnection remotingConnection, + ChannelHandler channelHandler) { this.clusterChannel = clusterChannel; this.acceptorUsed = acceptorUsed; this.remotingConnection = remotingConnection; @@ -337,90 +316,71 @@ public class ClusterController implements ActiveMQComponent } @Override - public void handlePacket(Packet packet) - { - if (!authorized) - { - if (packet.getType() == PacketImpl.CLUSTER_CONNECT ) - { + public void handlePacket(Packet packet) { + if (!authorized) { + if (packet.getType() == PacketImpl.CLUSTER_CONNECT) { ClusterConnection clusterConnection = acceptorUsed.getClusterConnection(); //if this acceptor isnt associated with a cluster connection use the default - if (clusterConnection == null) - { + if (clusterConnection == null) { clusterConnection = server.getClusterManager().getDefaultConnection(null); } ClusterConnectMessage msg = (ClusterConnectMessage) packet; - if (server.getConfiguration().isSecurityEnabled() && !clusterConnection.verify(msg.getClusterUser(), msg.getClusterPassword())) - { + if (server.getConfiguration().isSecurityEnabled() && !clusterConnection.verify(msg.getClusterUser(), msg.getClusterPassword())) { clusterChannel.send(new ClusterConnectReplyMessage(false)); } - else - { + else { authorized = true; clusterChannel.send(new ClusterConnectReplyMessage(true)); } } } - else - { - if (packet.getType() == PacketImpl.NODE_ANNOUNCE) - { - NodeAnnounceMessage msg = (NodeAnnounceMessage)packet; + else { + if (packet.getType() == PacketImpl.NODE_ANNOUNCE) { + NodeAnnounceMessage msg = (NodeAnnounceMessage) packet; Pair pair; - if (msg.isBackup()) - { + if (msg.isBackup()) { pair = new Pair<>(null, msg.getConnector()); } - else - { + else { pair = new Pair<>(msg.getConnector(), msg.getBackupConnector()); } - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Server " + server + " receiving nodeUp from NodeID=" + msg.getNodeID() + ", pair=" + pair); } - if (acceptorUsed != null) - { + if (acceptorUsed != null) { ClusterConnection clusterConn = acceptorUsed.getClusterConnection(); - if (clusterConn != null) - { + if (clusterConn != null) { String scaleDownGroupName = msg.getScaleDownGroupName(); clusterConn.nodeAnnounced(msg.getCurrentEventID(), msg.getNodeID(), msg.getBackupGroupName(), scaleDownGroupName, pair, msg.isBackup()); } - else - { + else { ActiveMQServerLogger.LOGGER.debug("Cluster connection is null on acceptor = " + acceptorUsed); } } - else - { + else { ActiveMQServerLogger.LOGGER.debug("there is no acceptor used configured at the CoreProtocolManager " + this); } } - else if (packet.getType() == PacketImpl.QUORUM_VOTE) - { + else if (packet.getType() == PacketImpl.QUORUM_VOTE) { QuorumVoteMessage quorumVoteMessage = (QuorumVoteMessage) packet; QuorumVoteHandler voteHandler = quorumManager.getVoteHandler(quorumVoteMessage.getHandler()); quorumVoteMessage.decode(voteHandler); Vote vote = quorumManager.vote(quorumVoteMessage.getHandler(), quorumVoteMessage.getVote()); clusterChannel.send(new QuorumVoteReplyMessage(quorumVoteMessage.getHandler(), vote)); } - else if (packet.getType() == PacketImpl.SCALEDOWN_ANNOUNCEMENT) - { + else if (packet.getType() == PacketImpl.SCALEDOWN_ANNOUNCEMENT) { ScaleDownAnnounceMessage message = (ScaleDownAnnounceMessage) packet; //we don't really need to check as it should always be true - if (server.getNodeID().equals(message.getTargetNodeId())) - { + if (server.getNodeID().equals(message.getTargetNodeId())) { server.addScaledDownNode(message.getScaledDownNodeId()); } } - else if (channelHandler != null) - { + else if (channelHandler != null) { channelHandler.handlePacket(packet); } } @@ -431,28 +391,23 @@ public class ClusterController implements ActiveMQComponent /** * used for making the initial connection in the cluster */ - private final class ConnectRunnable implements Runnable - { + private final class ConnectRunnable implements Runnable { + private ServerLocatorInternal serverLocator; - public ConnectRunnable(ServerLocatorInternal serverLocator) - { + public ConnectRunnable(ServerLocatorInternal serverLocator) { this.serverLocator = serverLocator; } @Override - public void run() - { - try - { + public void run() { + try { serverLocator.connect(); - if (serverLocator == replicationLocator) - { + if (serverLocator == replicationLocator) { replicationClusterConnectedLatch.countDown(); } } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { if (!started) return; server.getScheduledPool().schedule(this, serverLocator.getRetryInterval(), TimeUnit.MILLISECONDS); @@ -460,8 +415,7 @@ public class ClusterController implements ActiveMQComponent } } - public ServerLocator getReplicationLocator() - { + public ServerLocator getReplicationLocator() { return this.replicationLocator; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterManager.java index 4640f81b72..e23e18a088 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterManager.java @@ -73,8 +73,8 @@ import java.util.concurrent.ScheduledExecutorService; * {@link ClusterConnectionImpl}. As a node is discovered a new {@link org.apache.activemq.artemis.core.server.cluster.impl.ClusterConnectionBridge} is * deployed. */ -public final class ClusterManager implements ActiveMQComponent -{ +public final class ClusterManager implements ActiveMQComponent { + private ClusterController clusterController; private HAManager haManager; @@ -97,28 +97,26 @@ public final class ClusterManager implements ActiveMQComponent private final Configuration configuration; - public QuorumManager getQuorumManager() - { + public QuorumManager getQuorumManager() { return clusterController.getQuorumManager(); } - public ClusterController getClusterController() - { + public ClusterController getClusterController() { return clusterController; } - public HAManager getHAManager() - { + public HAManager getHAManager() { return haManager; } - public void addClusterChannelHandler(Channel channel, Acceptor acceptorUsed, CoreRemotingConnection remotingConnection, Activation activation) - { + public void addClusterChannelHandler(Channel channel, + Acceptor acceptorUsed, + CoreRemotingConnection remotingConnection, + Activation activation) { clusterController.addClusterChannelHandler(channel, acceptorUsed, remotingConnection, activation); } - enum State - { + enum State { STOPPED, /** * Used because {@link ClusterManager#stop()} method is not completely synchronized @@ -152,8 +150,7 @@ public final class ClusterManager implements ActiveMQComponent final ManagementService managementService, final Configuration configuration, final NodeManager nodeManager, - final boolean backup) - { + final boolean backup) { this.executorFactory = executorFactory; executor = executorFactory.getExecutor(); @@ -175,16 +172,14 @@ public final class ClusterManager implements ActiveMQComponent haManager = server.getActivation().getHAManager(); } - public String describe() - { + public String describe() { StringWriter str = new StringWriter(); PrintWriter out = new PrintWriter(str); out.println("Information on " + this); out.println("*******************************************************"); - for (ClusterConnection conn : cloneClusterConnections()) - { + for (ClusterConnection conn : cloneClusterConnections()) { out.println(conn.describe()); } @@ -198,23 +193,17 @@ public final class ClusterManager implements ActiveMQComponent * * @return default connection */ - public ClusterConnection getDefaultConnection(TransportConfiguration acceptorConfig) - { - if (acceptorConfig == null) - { + public ClusterConnection getDefaultConnection(TransportConfiguration acceptorConfig) { + if (acceptorConfig == null) { // if the parameter is null, we just return whatever is defined on defaultClusterConnection return defaultClusterConnection; } - else if (defaultClusterConnection != null && defaultClusterConnection.getConnector().isEquivalent(acceptorConfig)) - { + else if (defaultClusterConnection != null && defaultClusterConnection.getConnector().isEquivalent(acceptorConfig)) { return defaultClusterConnection; } - else - { - for (ClusterConnection conn : cloneClusterConnections()) - { - if (conn.getConnector().isEquivalent(acceptorConfig)) - { + else { + for (ClusterConnection conn : cloneClusterConnections()) { + if (conn.getConnector().isEquivalent(acceptorConfig)) { return conn; } } @@ -223,97 +212,76 @@ public final class ClusterManager implements ActiveMQComponent } @Override - public String toString() - { + public String toString() { return "ClusterManagerImpl[server=" + server + "]@" + System.identityHashCode(this); } - public String getNodeId() - { + public String getNodeId() { return nodeManager.getNodeId().toString(); } - public String getBackupGroupName() - { + public String getBackupGroupName() { return server.getHAPolicy().getBackupGroupName(); } - public String getScaleDownGroupName() - { + public String getScaleDownGroupName() { return server.getHAPolicy().getScaleDownGroupName(); } - public synchronized void deploy() throws Exception - { - if (state == State.STOPPED) - { + public synchronized void deploy() throws Exception { + if (state == State.STOPPED) { state = State.DEPLOYED; } - else - { + else { throw new IllegalStateException(); } - for (BroadcastGroupConfiguration config : configuration.getBroadcastGroupConfigurations()) - { + for (BroadcastGroupConfiguration config : configuration.getBroadcastGroupConfigurations()) { deployBroadcastGroup(config); } - for (ClusterConnectionConfiguration config : configuration.getClusterConfigurations()) - { + for (ClusterConnectionConfiguration config : configuration.getClusterConfigurations()) { deployClusterConnection(config); } /* * only start if we are actually in a cluster * */ - if (clusterConnections.size() > 0) - { + if (clusterConnections.size() > 0) { clusterController.start(); } } - public synchronized void start() throws Exception - { - if (state == State.STARTED) - { + public synchronized void start() throws Exception { + if (state == State.STARTED) { return; } - for (BroadcastGroup group : broadcastGroups.values()) - { - try - { + for (BroadcastGroup group : broadcastGroups.values()) { + try { group.start(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.unableToStartBroadcastGroup(e, group.getName()); } } - for (ClusterConnection conn : clusterConnections.values()) - { - try - { + for (ClusterConnection conn : clusterConnections.values()) { + try { conn.start(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.unableToStartClusterConnection(e, conn.getName()); } } deployConfiguredBridges(); - for (Bridge bridge : bridges.values()) - { - try - { + for (Bridge bridge : bridges.values()) { + try { bridge.start(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.unableToStartBridge(e, bridge.getName()); } } @@ -324,43 +292,35 @@ public final class ClusterManager implements ActiveMQComponent state = State.STARTED; } - private void deployConfiguredBridges() throws Exception - { - for (BridgeConfiguration config : configuration.getBridgeConfigurations()) - { + private void deployConfiguredBridges() throws Exception { + for (BridgeConfiguration config : configuration.getBridgeConfigurations()) { deployBridge(config); } } - public void stop() throws Exception - { + public void stop() throws Exception { haManager.stop(); - synchronized (this) - { - if (state == State.STOPPED || state == State.STOPPING) - { + synchronized (this) { + if (state == State.STOPPED || state == State.STOPPING) { return; } state = State.STOPPING; clusterController.stop(); - for (BroadcastGroup group : broadcastGroups.values()) - { + for (BroadcastGroup group : broadcastGroups.values()) { group.stop(); managementService.unregisterBroadcastGroup(group.getName()); } broadcastGroups.clear(); - for (ClusterConnection clusterConnection : clusterConnections.values()) - { + for (ClusterConnection clusterConnection : clusterConnections.values()) { clusterConnection.stop(); managementService.unregisterCluster(clusterConnection.getName().toString()); } - for (Bridge bridge : bridges.values()) - { + for (Bridge bridge : bridges.values()) { bridge.stop(); managementService.unregisterBridge(bridge.getName().toString()); } @@ -368,14 +328,11 @@ public final class ClusterManager implements ActiveMQComponent bridges.clear(); } - for (ServerLocatorInternal clusterLocator : clusterLocators) - { - try - { + for (ServerLocatorInternal clusterLocator : clusterLocators) { + try { clusterLocator.close(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorClosingServerLocator(e, clusterLocator); } } @@ -385,73 +342,57 @@ public final class ClusterManager implements ActiveMQComponent clearClusterConnections(); } - public void flushExecutor() - { + public void flushExecutor() { FutureLatch future = new FutureLatch(); executor.execute(future); - if (!future.await(10000)) - { + if (!future.await(10000)) { ActiveMQServerLogger.LOGGER.couldNotFlushClusterManager(this.toString()); server.threadDump(); } } - public boolean isStarted() - { + public boolean isStarted() { return state == State.STARTED; } - public Map getBridges() - { + public Map getBridges() { return new HashMap(bridges); } - public Set getClusterConnections() - { + public Set getClusterConnections() { return new HashSet(clusterConnections.values()); } - public Set getBroadcastGroups() - { + public Set getBroadcastGroups() { return new HashSet(broadcastGroups.values()); } - public ClusterConnection getClusterConnection(final String name) - { + public ClusterConnection getClusterConnection(final String name) { return clusterConnections.get(name); } - - - - public void removeClusterLocator(final ServerLocatorInternal serverLocator) - { + public void removeClusterLocator(final ServerLocatorInternal serverLocator) { this.clusterLocators.remove(serverLocator); } - public synchronized void deployBridge(final BridgeConfiguration config) throws Exception - { - if (config.getName() == null) - { + public synchronized void deployBridge(final BridgeConfiguration config) throws Exception { + if (config.getName() == null) { ActiveMQServerLogger.LOGGER.bridgeNotUnique(); return; } - if (config.getQueueName() == null) - { + if (config.getQueueName() == null) { ActiveMQServerLogger.LOGGER.bridgeNoQueue(config.getName()); return; } - if (config.getForwardingAddress() == null) - { + if (config.getForwardingAddress() == null) { ActiveMQServerLogger.LOGGER.bridgeNoForwardAddress(config.getName()); } - if (bridges.containsKey(config.getName())) - { + if (bridges.containsKey(config.getName())) { ActiveMQServerLogger.LOGGER.bridgeAlreadyDeployed(config.getName()); return; @@ -461,8 +402,7 @@ public final class ClusterManager implements ActiveMQComponent Binding binding = postOffice.getBinding(new SimpleString(config.getQueueName())); - if (binding == null) - { + if (binding == null) { ActiveMQServerLogger.LOGGER.bridgeQueueNotFound(config.getQueueName(), config.getName()); return; @@ -472,43 +412,34 @@ public final class ClusterManager implements ActiveMQComponent ServerLocatorInternal serverLocator; - if (config.getDiscoveryGroupName() != null) - { - DiscoveryGroupConfiguration discoveryGroupConfiguration = configuration.getDiscoveryGroupConfigurations() - .get(config.getDiscoveryGroupName()); - if (discoveryGroupConfiguration == null) - { + if (config.getDiscoveryGroupName() != null) { + DiscoveryGroupConfiguration discoveryGroupConfiguration = configuration.getDiscoveryGroupConfigurations().get(config.getDiscoveryGroupName()); + if (discoveryGroupConfiguration == null) { ActiveMQServerLogger.LOGGER.bridgeNoDiscoveryGroup(config.getDiscoveryGroupName()); return; } - if (config.isHA()) - { + if (config.isHA()) { serverLocator = (ServerLocatorInternal) ActiveMQClient.createServerLocatorWithHA(discoveryGroupConfiguration); } - else - { + else { serverLocator = (ServerLocatorInternal) ActiveMQClient.createServerLocatorWithoutHA(discoveryGroupConfiguration); } } - else - { + else { TransportConfiguration[] tcConfigs = ClusterConfigurationUtil.connectorNameListToArray(config.getStaticConnectors(), configuration); - if (tcConfigs == null) - { + if (tcConfigs == null) { ActiveMQServerLogger.LOGGER.bridgeCantFindConnectors(config.getName()); return; } - if (config.isHA()) - { + if (config.isHA()) { serverLocator = (ServerLocatorInternal) ActiveMQClient.createServerLocatorWithHA(tcConfigs); } - else - { + else { serverLocator = (ServerLocatorInternal) ActiveMQClient.createServerLocatorWithoutHA(tcConfigs); } @@ -539,33 +470,14 @@ public final class ClusterManager implements ActiveMQComponent serverLocator.addIncomingInterceptor(new IncomingInterceptorLookingForExceptionMessage(this, executor)); - if (!config.isUseDuplicateDetection()) - { + if (!config.isUseDuplicateDetection()) { ActiveMQServerLogger.LOGGER.debug("Bridge " + config.getName() + - " is configured to not use duplicate detecion, it will send messages synchronously"); + " is configured to not use duplicate detecion, it will send messages synchronously"); } clusterLocators.add(serverLocator); - Bridge bridge = new BridgeImpl(serverLocator, - config.getInitialConnectAttempts(), - config.getReconnectAttempts(), - config.getReconnectAttemptsOnSameNode(), - config.getRetryInterval(), - config.getRetryIntervalMultiplier(), - config.getMaxRetryInterval(), - nodeManager.getUUID(), - new SimpleString(config.getName()), - queue, - executorFactory.getExecutor(), - FilterImpl.createFilter(config.getFilterString()), - SimpleString.toSimpleString(config.getForwardingAddress()), - scheduledExecutor, - transformer, - config.isUseDuplicateDetection(), - config.getUser(), - config.getPassword(), - server.getStorageManager()); + Bridge bridge = new BridgeImpl(serverLocator, config.getInitialConnectAttempts(), config.getReconnectAttempts(), config.getReconnectAttemptsOnSameNode(), config.getRetryInterval(), config.getRetryIntervalMultiplier(), config.getMaxRetryInterval(), nodeManager.getUUID(), new SimpleString(config.getName()), queue, executorFactory.getExecutor(), FilterImpl.createFilter(config.getFilterString()), SimpleString.toSimpleString(config.getForwardingAddress()), scheduledExecutor, transformer, config.isUseDuplicateDetection(), config.getUser(), config.getPassword(), server.getStorageManager()); bridges.put(config.getName(), bridge); @@ -575,8 +487,8 @@ public final class ClusterManager implements ActiveMQComponent } - public static class IncomingInterceptorLookingForExceptionMessage implements Interceptor - { + public static class IncomingInterceptorLookingForExceptionMessage implements Interceptor { + private final ClusterManager manager; private final Executor executor; @@ -584,33 +496,25 @@ public final class ClusterManager implements ActiveMQComponent * @param manager * @param executor */ - public IncomingInterceptorLookingForExceptionMessage(ClusterManager manager, Executor executor) - { + public IncomingInterceptorLookingForExceptionMessage(ClusterManager manager, Executor executor) { this.manager = manager; this.executor = executor; } @Override - public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException - { - if (packet.getType() == PacketImpl.EXCEPTION) - { + public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException { + if (packet.getType() == PacketImpl.EXCEPTION) { ActiveMQExceptionMessage msg = (ActiveMQExceptionMessage) packet; final ActiveMQException exception = msg.getException(); - if (exception.getType() == ActiveMQExceptionType.CLUSTER_SECURITY_EXCEPTION) - { + if (exception.getType() == ActiveMQExceptionType.CLUSTER_SECURITY_EXCEPTION) { ActiveMQServerLogger.LOGGER.clusterManagerAuthenticationError(exception.getMessage()); - executor.execute(new Runnable() - { + executor.execute(new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { manager.stop(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -622,180 +526,100 @@ public final class ClusterManager implements ActiveMQComponent } } - public void destroyBridge(final String name) throws Exception - { + public void destroyBridge(final String name) throws Exception { Bridge bridge; - synchronized (this) - { + synchronized (this) { bridge = bridges.remove(name); - if (bridge != null) - { + if (bridge != null) { bridge.stop(); managementService.unregisterBridge(name); } } - if (bridge != null) - { + if (bridge != null) { bridge.flushExecutor(); } } // for testing - public void clear() - { - for (Bridge bridge : bridges.values()) - { - try - { + public void clear() { + for (Bridge bridge : bridges.values()) { + try { bridge.stop(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e); } } bridges.clear(); - for (ClusterConnection clusterConnection : clusterConnections.values()) - { - try - { + for (ClusterConnection clusterConnection : clusterConnections.values()) { + try { clusterConnection.stop(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } clearClusterConnections(); } - public void informClusterOfBackup(String name) - { + public void informClusterOfBackup(String name) { ClusterConnection clusterConnection = clusterConnections.get(name); - if (clusterConnection != null) - { + if (clusterConnection != null) { clusterConnection.informClusterOfBackup(); } } // Private methods ---------------------------------------------------------------------------------------------------- - - private void clearClusterConnections() - { + private void clearClusterConnections() { clusterConnections.clear(); this.defaultClusterConnection = null; } - private void deployClusterConnection(final ClusterConnectionConfiguration config) throws Exception - { + private void deployClusterConnection(final ClusterConnectionConfiguration config) throws Exception { TransportConfiguration connector = ClusterConfigurationUtil.getTransportConfiguration(config, configuration); - if (connector == null) return; + if (connector == null) + return; - if (clusterConnections.containsKey(config.getName())) - { + if (clusterConnections.containsKey(config.getName())) { ActiveMQServerLogger.LOGGER.clusterConnectionAlreadyExists(config.getConnectorName()); return; } ClusterConnectionImpl clusterConnection; - if (config.getDiscoveryGroupName() != null) - { + if (config.getDiscoveryGroupName() != null) { DiscoveryGroupConfiguration dg = ClusterConfigurationUtil.getDiscoveryGroupConfiguration(config, configuration); - if (dg == null) return; + if (dg == null) + return; - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug(this + " Starting a Discovery Group Cluster Connection, name=" + - config.getDiscoveryGroupName() + - ", dg=" + - dg); + config.getDiscoveryGroupName() + + ", dg=" + + dg); } - clusterConnection = new ClusterConnectionImpl(this, - dg, - connector, - new SimpleString(config.getName()), - new SimpleString(config.getAddress()), - config.getMinLargeMessageSize(), - config.getClientFailureCheckPeriod(), - config.getConnectionTTL(), - config.getRetryInterval(), - config.getRetryIntervalMultiplier(), - config.getMaxRetryInterval(), - config.getInitialConnectAttempts(), - config.getReconnectAttempts(), - config.getCallTimeout(), - config.getCallFailoverTimeout(), - config.isDuplicateDetection(), - config.getMessageLoadBalancingType(), - config.getConfirmationWindowSize(), - executorFactory, - server, - postOffice, - managementService, - scheduledExecutor, - config.getMaxHops(), - nodeManager, - server.getConfiguration().getClusterUser(), - server.getConfiguration().getClusterPassword(), - config.isAllowDirectConnectionsOnly(), - config.getClusterNotificationInterval(), - config.getClusterNotificationAttempts()); + clusterConnection = new ClusterConnectionImpl(this, dg, connector, new SimpleString(config.getName()), new SimpleString(config.getAddress()), config.getMinLargeMessageSize(), config.getClientFailureCheckPeriod(), config.getConnectionTTL(), config.getRetryInterval(), config.getRetryIntervalMultiplier(), config.getMaxRetryInterval(), config.getInitialConnectAttempts(), config.getReconnectAttempts(), config.getCallTimeout(), config.getCallFailoverTimeout(), config.isDuplicateDetection(), config.getMessageLoadBalancingType(), config.getConfirmationWindowSize(), executorFactory, server, postOffice, managementService, scheduledExecutor, config.getMaxHops(), nodeManager, server.getConfiguration().getClusterUser(), server.getConfiguration().getClusterPassword(), config.isAllowDirectConnectionsOnly(), config.getClusterNotificationInterval(), config.getClusterNotificationAttempts()); clusterController.addClusterConnection(clusterConnection.getName(), dg, config); } - else - { + else { TransportConfiguration[] tcConfigs = ClusterConfigurationUtil.getTransportConfigurations(config, configuration); - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug(this + " defining cluster connection towards " + Arrays.toString(tcConfigs)); } - clusterConnection = new ClusterConnectionImpl(this, - tcConfigs, - connector, - new SimpleString(config.getName()), - new SimpleString(config.getAddress()), - config.getMinLargeMessageSize(), - config.getClientFailureCheckPeriod(), - config.getConnectionTTL(), - config.getRetryInterval(), - config.getRetryIntervalMultiplier(), - config.getMaxRetryInterval(), - config.getInitialConnectAttempts(), - config.getReconnectAttempts(), - config.getCallTimeout(), - config.getCallFailoverTimeout(), - config.isDuplicateDetection(), - config.getMessageLoadBalancingType(), - config.getConfirmationWindowSize(), - executorFactory, - server, - postOffice, - managementService, - scheduledExecutor, - config.getMaxHops(), - nodeManager, - server.getConfiguration().getClusterUser(), - server.getConfiguration().getClusterPassword(), - config.isAllowDirectConnectionsOnly(), - config.getClusterNotificationInterval(), - config.getClusterNotificationAttempts()); - + clusterConnection = new ClusterConnectionImpl(this, tcConfigs, connector, new SimpleString(config.getName()), new SimpleString(config.getAddress()), config.getMinLargeMessageSize(), config.getClientFailureCheckPeriod(), config.getConnectionTTL(), config.getRetryInterval(), config.getRetryIntervalMultiplier(), config.getMaxRetryInterval(), config.getInitialConnectAttempts(), config.getReconnectAttempts(), config.getCallTimeout(), config.getCallFailoverTimeout(), config.isDuplicateDetection(), config.getMessageLoadBalancingType(), config.getConfirmationWindowSize(), executorFactory, server, postOffice, managementService, scheduledExecutor, config.getMaxHops(), nodeManager, server.getConfiguration().getClusterUser(), server.getConfiguration().getClusterPassword(), config.isAllowDirectConnectionsOnly(), config.getClusterNotificationInterval(), config.getClusterNotificationAttempts()); clusterController.addClusterConnection(clusterConnection.getName(), tcConfigs, config); } - - if (defaultClusterConnection == null) - { + if (defaultClusterConnection == null) { defaultClusterConnection = clusterConnection; clusterController.setDefaultClusterConnectionName(defaultClusterConnection.getName()); } @@ -804,17 +628,13 @@ public final class ClusterManager implements ActiveMQComponent clusterConnections.put(config.getName(), clusterConnection); - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("ClusterConnection.start at " + clusterConnection, new Exception("trace")); } } - - private synchronized void deployBroadcastGroup(final BroadcastGroupConfiguration config) throws Exception - { - if (broadcastGroups.containsKey(config.getName())) - { + private synchronized void deployBroadcastGroup(final BroadcastGroupConfiguration config) throws Exception { + if (broadcastGroups.containsKey(config.getName())) { ActiveMQServerLogger.LOGGER.broadcastGroupAlreadyExists(config.getName()); return; @@ -825,21 +645,16 @@ public final class ClusterManager implements ActiveMQComponent managementService.registerBroadcastGroup(group, config); } - private BroadcastGroup createBroadcastGroup(BroadcastGroupConfiguration config) throws Exception - { + private BroadcastGroup createBroadcastGroup(BroadcastGroupConfiguration config) throws Exception { BroadcastGroup group = broadcastGroups.get(config.getName()); - if (group == null) - { - group = new BroadcastGroupImpl(nodeManager, config.getName(), - config.getBroadcastPeriod(), scheduledExecutor, config.getEndpointFactory()); + if (group == null) { + group = new BroadcastGroupImpl(nodeManager, config.getName(), config.getBroadcastPeriod(), scheduledExecutor, config.getEndpointFactory()); - for (String connectorInfo : config.getConnectorInfos()) - { + for (String connectorInfo : config.getConnectorInfos()) { TransportConfiguration connector = configuration.getConnectorConfigurations().get(connectorInfo); - if (connector == null) - { + if (connector == null) { logWarnNoConnector(connectorInfo, config.getName()); return null; @@ -849,8 +664,7 @@ public final class ClusterManager implements ActiveMQComponent } } - if (group.size() == 0) - { + if (group.size() == 0) { logWarnNoConnector(config.getConnectorInfos().toString(), group.getName()); return null; } @@ -860,16 +674,13 @@ public final class ClusterManager implements ActiveMQComponent return group; } - private void logWarnNoConnector(final String connectorName, final String bgName) - { + private void logWarnNoConnector(final String connectorName, final String bgName) { ActiveMQServerLogger.LOGGER.broadcastGroupNoConnector(connectorName, bgName); } - private synchronized Collection cloneClusterConnections() - { + private synchronized Collection cloneClusterConnections() { ArrayList list = new ArrayList(clusterConnections.values()); return list; } - } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/MessageFlowRecord.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/MessageFlowRecord.java index b50c237781..1982f4ee4a 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/MessageFlowRecord.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/MessageFlowRecord.java @@ -18,8 +18,8 @@ package org.apache.activemq.artemis.core.server.cluster; import org.apache.activemq.artemis.api.core.client.MessageHandler; -public interface MessageFlowRecord extends MessageHandler -{ +public interface MessageFlowRecord extends MessageHandler { + String getAddress(); int getMaxHops(); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/RemoteQueueBinding.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/RemoteQueueBinding.java index b4fc259730..aad320d8ff 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/RemoteQueueBinding.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/RemoteQueueBinding.java @@ -19,8 +19,8 @@ package org.apache.activemq.artemis.core.server.cluster; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.postoffice.QueueBinding; -public interface RemoteQueueBinding extends QueueBinding -{ +public interface RemoteQueueBinding extends QueueBinding { + void addConsumer(SimpleString filterString) throws Exception; void removeConsumer(SimpleString filterString) throws Exception; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/Transformer.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/Transformer.java index 577ae3d533..1583f2cd35 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/Transformer.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/Transformer.java @@ -18,7 +18,7 @@ package org.apache.activemq.artemis.core.server.cluster; import org.apache.activemq.artemis.core.server.ServerMessage; -public interface Transformer -{ +public interface Transformer { + ServerMessage transform(ServerMessage message); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/BackupPolicy.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/BackupPolicy.java index cada456080..51f5c050fb 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/BackupPolicy.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/BackupPolicy.java @@ -19,47 +19,39 @@ package org.apache.activemq.artemis.core.server.cluster.ha; import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration; import org.apache.activemq.artemis.core.server.impl.Activation; -public abstract class BackupPolicy implements HAPolicy -{ +public abstract class BackupPolicy implements HAPolicy { + protected ScaleDownPolicy scaleDownPolicy; protected boolean restartBackup = ActiveMQDefaultConfiguration.isDefaultRestartBackup(); - public ScaleDownPolicy getScaleDownPolicy() - { + public ScaleDownPolicy getScaleDownPolicy() { return scaleDownPolicy; } - public void setScaleDownPolicy(ScaleDownPolicy scaleDownPolicy) - { + public void setScaleDownPolicy(ScaleDownPolicy scaleDownPolicy) { this.scaleDownPolicy = scaleDownPolicy; } - @Override - public boolean isBackup() - { + public boolean isBackup() { return true; } @Override - public String getScaleDownClustername() - { + public String getScaleDownClustername() { return null; } @Override - public String getScaleDownGroupName() - { + public String getScaleDownGroupName() { return getScaleDownPolicy() != null ? getScaleDownPolicy().getGroupName() : null; } - public boolean isRestartBackup() - { + public boolean isRestartBackup() { return restartBackup; } - public void setRestartBackup(boolean restartBackup) - { + public void setRestartBackup(boolean restartBackup) { this.restartBackup = restartBackup; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/ColocatedHAManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/ColocatedHAManager.java index 4be3cf4b80..4758a114c9 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/ColocatedHAManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/ColocatedHAManager.java @@ -32,8 +32,7 @@ import java.util.List; import java.util.Map; import java.util.Set; -public class ColocatedHAManager implements HAManager -{ +public class ColocatedHAManager implements HAManager { private final ColocatedPolicy haPolicy; @@ -43,8 +42,7 @@ public class ColocatedHAManager implements HAManager private boolean started; - public ColocatedHAManager(ColocatedPolicy haPolicy, ActiveMQServer activeMQServer) - { + public ColocatedHAManager(ColocatedPolicy haPolicy, ActiveMQServer activeMQServer) { this.haPolicy = haPolicy; server = activeMQServer; } @@ -52,8 +50,7 @@ public class ColocatedHAManager implements HAManager /** * starts the HA manager. */ - public void start() - { + public void start() { if (started) return; @@ -65,16 +62,12 @@ public class ColocatedHAManager implements HAManager /** * stop any backups */ - public void stop() - { - for (ActiveMQServer activeMQServer : backupServers.values()) - { - try - { + public void stop() { + for (ActiveMQServer activeMQServer : backupServers.values()) { + try { activeMQServer.stop(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); //todo } @@ -84,35 +77,33 @@ public class ColocatedHAManager implements HAManager } @Override - public boolean isStarted() - { + public boolean isStarted() { return started; } - public synchronized boolean activateBackup(int backupSize, String journalDirectory, String bindingsDirectory, String largeMessagesDirectory, String pagingDirectory, SimpleString nodeID) throws Exception - { - if (backupServers.size() >= haPolicy.getMaxBackups() || backupSize != backupServers.size()) - { + public synchronized boolean activateBackup(int backupSize, + String journalDirectory, + String bindingsDirectory, + String largeMessagesDirectory, + String pagingDirectory, + SimpleString nodeID) throws Exception { + if (backupServers.size() >= haPolicy.getMaxBackups() || backupSize != backupServers.size()) { return false; } - if (haPolicy.getBackupPolicy().isSharedStore()) - { + if (haPolicy.getBackupPolicy().isSharedStore()) { return activateSharedStoreBackup(journalDirectory, bindingsDirectory, largeMessagesDirectory, pagingDirectory); } - else - { + else { return activateReplicatedBackup(nodeID); } } - /** * return the current backup servers * * @return the backups */ - public Map getBackupServers() - { + public Map getBackupServers() { return backupServers; } @@ -120,42 +111,37 @@ public class ColocatedHAManager implements HAManager * send a request to a live server to start a backup for us * * @param connectorPair the connector for the node to request a backup from - * @param backupSize the current size of the requested nodes backups + * @param backupSize the current size of the requested nodes backups * @param replicated * @return true if the request wa successful. * @throws Exception */ - public boolean requestBackup(Pair connectorPair, int backupSize, boolean replicated) throws Exception - { + public boolean requestBackup(Pair connectorPair, + int backupSize, + boolean replicated) throws Exception { ClusterController clusterController = server.getClusterManager().getClusterController(); try - ( - ClusterControl clusterControl = clusterController.connectToNode(connectorPair.getA()); - ) - { + ( + ClusterControl clusterControl = clusterController.connectToNode(connectorPair.getA()); + ) { clusterControl.authorize(); - if (replicated) - { + if (replicated) { return clusterControl.requestReplicatedBackup(backupSize, server.getNodeID()); } - else - { - return clusterControl.requestSharedStoreBackup(backupSize, - server.getConfiguration().getJournalDirectory(), - server.getConfiguration().getBindingsDirectory(), - server.getConfiguration().getLargeMessagesDirectory(), - server.getConfiguration().getPagingDirectory()); + else { + return clusterControl.requestSharedStoreBackup(backupSize, server.getConfiguration().getJournalDirectory(), server.getConfiguration().getBindingsDirectory(), server.getConfiguration().getLargeMessagesDirectory(), server.getConfiguration().getPagingDirectory()); } } } - private synchronized boolean activateSharedStoreBackup(String journalDirectory, String bindingsDirectory, String largeMessagesDirectory, String pagingDirectory) throws Exception - { + private synchronized boolean activateSharedStoreBackup(String journalDirectory, + String bindingsDirectory, + String largeMessagesDirectory, + String pagingDirectory) throws Exception { Configuration configuration = server.getConfiguration().copy(); ActiveMQServer backup = server.createBackupServer(configuration); - try - { + try { int portOffset = haPolicy.getBackupPortOffset() * (backupServers.size() + 1); String name = "colocated_backup_" + backupServers.size() + 1; //make sure we don't restart as we are colocated @@ -167,8 +153,7 @@ public class ColocatedHAManager implements HAManager backupServers.put(configuration.getName(), backup); backup.start(); } - catch (Exception e) - { + catch (Exception e) { backup.stop(); ActiveMQServerLogger.LOGGER.activateSharedStoreSlaveFailed(e); return false; @@ -181,16 +166,15 @@ public class ColocatedHAManager implements HAManager * activate a backup server replicating from a specified node. * * decline and the requesting server can cast a re vote + * * @param nodeID the id of the node to replicate from * @return true if the server was created and started * @throws Exception */ - private synchronized boolean activateReplicatedBackup(SimpleString nodeID) throws Exception - { + private synchronized boolean activateReplicatedBackup(SimpleString nodeID) throws Exception { Configuration configuration = server.getConfiguration().copy(); ActiveMQServer backup = server.createBackupServer(configuration); - try - { + try { TopologyMember member = server.getClusterManager().getDefaultConnection(null).getTopology().getMember(nodeID.toString()); int portOffset = haPolicy.getBackupPortOffset() * (backupServers.size() + 1); String name = "colocated_backup_" + backupServers.size() + 1; @@ -203,8 +187,7 @@ public class ColocatedHAManager implements HAManager backupServers.put(configuration.getName(), backup); backup.start(); } - catch (Exception e) - { + catch (Exception e) { backup.stop(); ActiveMQServerLogger.LOGGER.activateReplicatedBackupFailed(e); return false; @@ -215,10 +198,11 @@ public class ColocatedHAManager implements HAManager /** * update the backups configuration - * @param backupConfiguration the configuration to update - * @param name the new name of the backup - * @param portOffset the offset for the acceptors and any connectors that need changing - * @param remoteConnectors the connectors that don't need off setting, typically remote + * + * @param backupConfiguration the configuration to update + * @param name the new name of the backup + * @param portOffset the offset for the acceptors and any connectors that need changing + * @param remoteConnectors the connectors that don't need off setting, typically remote * @param journalDirectory * @param bindingsDirectory * @param largeMessagesDirectory @@ -233,8 +217,7 @@ public class ColocatedHAManager implements HAManager String bindingsDirectory, String largeMessagesDirectory, String pagingDirectory, - boolean fullServer) - { + boolean fullServer) { backupConfiguration.setName(name); backupConfiguration.setJournalDirectory(journalDirectory); backupConfiguration.setBindingsDirectory(bindingsDirectory); @@ -247,16 +230,15 @@ public class ColocatedHAManager implements HAManager * update the backups configuration * * @param backupConfiguration the configuration to update - * @param name the new name of the backup - * @param portOffset the offset for the acceptors and any connectors that need changing - * @param remoteConnectors the connectors that don't need off setting, typically remote + * @param name the new name of the backup + * @param portOffset the offset for the acceptors and any connectors that need changing + * @param remoteConnectors the connectors that don't need off setting, typically remote */ private static void updateReplicatedConfiguration(Configuration backupConfiguration, String name, int portOffset, List remoteConnectors, - boolean fullServer) - { + boolean fullServer) { backupConfiguration.setName(name); backupConfiguration.setJournalDirectory(backupConfiguration.getJournalDirectory() + name); backupConfiguration.setPagingDirectory(backupConfiguration.getPagingDirectory() + name); @@ -268,48 +250,38 @@ public class ColocatedHAManager implements HAManager private static void updateAcceptorsAndConnectors(Configuration backupConfiguration, int portOffset, List remoteConnectors, - boolean fullServer) - { + boolean fullServer) { //we only do this if we are a full server, if scale down then our acceptors wont be needed and our connectors will // be the same as the parent server - if (fullServer) - { + if (fullServer) { Set acceptors = backupConfiguration.getAcceptorConfigurations(); - for (TransportConfiguration acceptor : acceptors) - { + for (TransportConfiguration acceptor : acceptors) { updatebackupParams(backupConfiguration.getName(), portOffset, acceptor.getParams()); } Map connectorConfigurations = backupConfiguration.getConnectorConfigurations(); - for (Map.Entry entry : connectorConfigurations.entrySet()) - { + for (Map.Entry entry : connectorConfigurations.entrySet()) { //check to make sure we aren't a remote connector as this shouldn't be changed - if (!remoteConnectors.contains(entry.getValue().getName())) - { + if (!remoteConnectors.contains(entry.getValue().getName())) { updatebackupParams(backupConfiguration.getName(), portOffset, entry.getValue().getParams()); } } } - else - { + else { //if we are scaling down then we wont need any acceptors but clear anyway for belts and braces backupConfiguration.getAcceptorConfigurations().clear(); } } - private static void updatebackupParams(String name, int portOffset, Map params) - { - if (params != null) - { + private static void updatebackupParams(String name, int portOffset, Map params) { + if (params != null) { Object port = params.get("port"); - if (port != null) - { + if (port != null) { Integer integer = Integer.valueOf(port.toString()); integer += portOffset; params.put("port", integer.toString()); } Object serverId = params.get("server-id"); - if (serverId != null) - { + if (serverId != null) { params.put("server-id", serverId.toString() + "(" + name + ")"); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/ColocatedPolicy.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/ColocatedPolicy.java index 1302006a58..e507356b50 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/ColocatedPolicy.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/ColocatedPolicy.java @@ -25,8 +25,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -public class ColocatedPolicy implements HAPolicy -{ +public class ColocatedPolicy implements HAPolicy { /*live stuff*/ private boolean requestBackup = ActiveMQDefaultConfiguration.isDefaultHapolicyRequestBackup(); @@ -53,8 +52,7 @@ public class ColocatedPolicy implements HAPolicy int backupPortOffset, List excludedConnectors, HAPolicy livePolicy, - BackupPolicy backupPolicy) - { + BackupPolicy backupPolicy) { this.requestBackup = requestBackup; this.backupRequestRetries = backupRequestRetries; this.backupRequestRetryInterval = backupRequestRetryInterval; @@ -66,126 +64,104 @@ public class ColocatedPolicy implements HAPolicy } @Override - public String getBackupGroupName() - { + public String getBackupGroupName() { return null; } @Override - public String getScaleDownGroupName() - { + public String getScaleDownGroupName() { return null; } @Override - public boolean isSharedStore() - { + public boolean isSharedStore() { return backupPolicy.isSharedStore(); } @Override - public boolean isBackup() - { + public boolean isBackup() { return false; } @Override - public LiveActivation createActivation(ActiveMQServerImpl server, boolean wasLive, Map activationParams, ActiveMQServerImpl.ShutdownOnCriticalErrorListener shutdownOnCriticalIO) throws Exception - { + public LiveActivation createActivation(ActiveMQServerImpl server, + boolean wasLive, + Map activationParams, + ActiveMQServerImpl.ShutdownOnCriticalErrorListener shutdownOnCriticalIO) throws Exception { return new ColocatedActivation(server, this, livePolicy.createActivation(server, wasLive, activationParams, shutdownOnCriticalIO)); } @Override - public boolean canScaleDown() - { + public boolean canScaleDown() { return false; } @Override - public String getScaleDownClustername() - { + public String getScaleDownClustername() { return null; } - - - public boolean isRequestBackup() - { + public boolean isRequestBackup() { return requestBackup; } - public void setRequestBackup(boolean requestBackup) - { + public void setRequestBackup(boolean requestBackup) { this.requestBackup = requestBackup; } - public int getBackupRequestRetries() - { + public int getBackupRequestRetries() { return backupRequestRetries; } - public void setBackupRequestRetries(int backupRequestRetries) - { + public void setBackupRequestRetries(int backupRequestRetries) { this.backupRequestRetries = backupRequestRetries; } - public long getBackupRequestRetryInterval() - { + public long getBackupRequestRetryInterval() { return backupRequestRetryInterval; } - public void setBackupRequestRetryInterval(long backupRequestRetryInterval) - { + public void setBackupRequestRetryInterval(long backupRequestRetryInterval) { this.backupRequestRetryInterval = backupRequestRetryInterval; } - public int getMaxBackups() - { + public int getMaxBackups() { return maxBackups; } - public void setMaxBackups(int maxBackups) - { + public void setMaxBackups(int maxBackups) { this.maxBackups = maxBackups; } - public int getBackupPortOffset() - { + public int getBackupPortOffset() { return backupPortOffset; } - public void setBackupPortOffset(int backupPortOffset) - { + public void setBackupPortOffset(int backupPortOffset) { this.backupPortOffset = backupPortOffset; } - public List getExcludedConnectors() - { + public List getExcludedConnectors() { return excludedConnectors; } - public void setExcludedConnectors(List excludedConnectors) - { + public void setExcludedConnectors(List excludedConnectors) { this.excludedConnectors = excludedConnectors; } - public HAPolicy getLivePolicy() - { + public HAPolicy getLivePolicy() { return livePolicy; } - public void setLivePolicy(HAPolicy livePolicy) - { + public void setLivePolicy(HAPolicy livePolicy) { this.livePolicy = livePolicy; } - public BackupPolicy getBackupPolicy() - { + public BackupPolicy getBackupPolicy() { return backupPolicy; } - public void setBackupPolicy(BackupPolicy backupPolicy) - { + public void setBackupPolicy(BackupPolicy backupPolicy) { this.backupPolicy = backupPolicy; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/HAManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/HAManager.java index ad9b678374..74107fc443 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/HAManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/HAManager.java @@ -24,8 +24,8 @@ import java.util.Map; /* * An HAManager takes care of any colocated backups in a VM. * */ -public interface HAManager extends ActiveMQComponent -{ +public interface HAManager extends ActiveMQComponent { + /** * return the current backup servers * diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/HAPolicy.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/HAPolicy.java index 37e588cb0d..006ba1b929 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/HAPolicy.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/HAPolicy.java @@ -25,12 +25,15 @@ import org.apache.activemq.artemis.core.server.impl.ActiveMQServerImpl; * Every live server will have an HAPolicy that configures the type of server that it should be either live, backup or * colocated (both). It also configures how, if colocated, it should react to sending and receiving requests for backups. */ -public interface HAPolicy -{ +public interface HAPolicy { + /* * created the Activation associated with this policy. * */ - T createActivation(ActiveMQServerImpl server, boolean wasLive, Map activationParams, ActiveMQServerImpl.ShutdownOnCriticalErrorListener shutdownOnCriticalIO) throws Exception; + T createActivation(ActiveMQServerImpl server, + boolean wasLive, + Map activationParams, + ActiveMQServerImpl.ShutdownOnCriticalErrorListener shutdownOnCriticalIO) throws Exception; boolean isSharedStore(); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/LiveOnlyPolicy.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/LiveOnlyPolicy.java index ad1e4707bc..9161e06433 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/LiveOnlyPolicy.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/LiveOnlyPolicy.java @@ -22,68 +22,60 @@ import org.apache.activemq.artemis.core.server.impl.LiveOnlyActivation; import java.util.Map; -public class LiveOnlyPolicy implements HAPolicy -{ +public class LiveOnlyPolicy implements HAPolicy { + private ScaleDownPolicy scaleDownPolicy; - public LiveOnlyPolicy() - { + public LiveOnlyPolicy() { } - public LiveOnlyPolicy(ScaleDownPolicy scaleDownPolicy) - { + public LiveOnlyPolicy(ScaleDownPolicy scaleDownPolicy) { this.scaleDownPolicy = scaleDownPolicy; } @Override - public Activation createActivation(ActiveMQServerImpl server, boolean wasLive, Map activationParams, ActiveMQServerImpl.ShutdownOnCriticalErrorListener shutdownOnCriticalIO) - { + public Activation createActivation(ActiveMQServerImpl server, + boolean wasLive, + Map activationParams, + ActiveMQServerImpl.ShutdownOnCriticalErrorListener shutdownOnCriticalIO) { return new LiveOnlyActivation(server, this); } @Override - public String getBackupGroupName() - { + public String getBackupGroupName() { return null; } @Override - public String getScaleDownGroupName() - { + public String getScaleDownGroupName() { return scaleDownPolicy == null ? null : scaleDownPolicy.getGroupName(); } @Override - public String getScaleDownClustername() - { + public String getScaleDownClustername() { return null; } @Override - public boolean isSharedStore() - { + public boolean isSharedStore() { return false; } @Override - public boolean isBackup() - { + public boolean isBackup() { return false; } @Override - public boolean canScaleDown() - { + public boolean canScaleDown() { return scaleDownPolicy != null; } - public ScaleDownPolicy getScaleDownPolicy() - { + public ScaleDownPolicy getScaleDownPolicy() { return scaleDownPolicy; } - public void setScaleDownPolicy(ScaleDownPolicy scaleDownPolicy) - { + public void setScaleDownPolicy(ScaleDownPolicy scaleDownPolicy) { this.scaleDownPolicy = scaleDownPolicy; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/ReplicaPolicy.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/ReplicaPolicy.java index d03e75cb5d..2858d931da 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/ReplicaPolicy.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/ReplicaPolicy.java @@ -23,8 +23,8 @@ import org.apache.activemq.artemis.core.server.impl.SharedNothingBackupActivatio import java.util.Map; -public class ReplicaPolicy extends BackupPolicy -{ +public class ReplicaPolicy extends BackupPolicy { + private String clusterName; private int maxSavedReplicatedJournalsSize = ActiveMQDefaultConfiguration.getDefaultMaxSavedReplicatedJournalsSize(); @@ -35,12 +35,16 @@ public class ReplicaPolicy extends BackupPolicy private ReplicatedPolicy replicatedPolicy; - public ReplicaPolicy() - { + public ReplicaPolicy() { } - public ReplicaPolicy(String clusterName, int maxSavedReplicatedJournalsSize, String groupName, boolean restartBackup, boolean allowFailback, long failbackDelay, ScaleDownPolicy scaleDownPolicy) - { + public ReplicaPolicy(String clusterName, + int maxSavedReplicatedJournalsSize, + String groupName, + boolean restartBackup, + boolean allowFailback, + long failbackDelay, + ScaleDownPolicy scaleDownPolicy) { this.clusterName = clusterName; this.maxSavedReplicatedJournalsSize = maxSavedReplicatedJournalsSize; this.groupName = groupName; @@ -50,89 +54,78 @@ public class ReplicaPolicy extends BackupPolicy replicatedPolicy = new ReplicatedPolicy(false, allowFailback, failbackDelay, groupName, clusterName, this); } - public ReplicaPolicy(String clusterName, int maxSavedReplicatedJournalsSize, String groupName, ReplicatedPolicy replicatedPolicy) - { + public ReplicaPolicy(String clusterName, + int maxSavedReplicatedJournalsSize, + String groupName, + ReplicatedPolicy replicatedPolicy) { this.clusterName = clusterName; this.maxSavedReplicatedJournalsSize = maxSavedReplicatedJournalsSize; this.groupName = groupName; this.replicatedPolicy = replicatedPolicy; } - public String getClusterName() - { + public String getClusterName() { return clusterName; } - public void setClusterName(String clusterName) - { + public void setClusterName(String clusterName) { this.clusterName = clusterName; } - public int getMaxSavedReplicatedJournalsSize() - { + public int getMaxSavedReplicatedJournalsSize() { return maxSavedReplicatedJournalsSize; } - public void setMaxSavedReplicatedJournalsSize(int maxSavedReplicatedJournalsSize) - { + public void setMaxSavedReplicatedJournalsSize(int maxSavedReplicatedJournalsSize) { this.maxSavedReplicatedJournalsSize = maxSavedReplicatedJournalsSize; } - public ReplicatedPolicy getReplicatedPolicy() - { + public ReplicatedPolicy getReplicatedPolicy() { return replicatedPolicy; } - public void setReplicatedPolicy(ReplicatedPolicy replicatedPolicy) - { + public void setReplicatedPolicy(ReplicatedPolicy replicatedPolicy) { this.replicatedPolicy = replicatedPolicy; } /* * these 2 methods are the same, leaving both as the second is correct but the first is needed until more refactoring is done * */ - public String getBackupGroupName() - { + public String getBackupGroupName() { return groupName; } - public String getGroupName() - { + public String getGroupName() { return groupName; } - public void setGroupName(String groupName) - { + public void setGroupName(String groupName) { this.groupName = groupName; } - public boolean isRestartBackup() - { + public boolean isRestartBackup() { return restartBackup; } - public void setRestartBackup(boolean restartBackup) - { + public void setRestartBackup(boolean restartBackup) { this.restartBackup = restartBackup; } @Override - public boolean isSharedStore() - { + public boolean isSharedStore() { return false; } @Override - public boolean canScaleDown() - { + public boolean canScaleDown() { return scaleDownPolicy != null; } @Override - public Activation createActivation(ActiveMQServerImpl server, boolean wasLive, + public Activation createActivation(ActiveMQServerImpl server, + boolean wasLive, Map activationParams, - ActiveMQServerImpl.ShutdownOnCriticalErrorListener shutdownOnCriticalIO) throws Exception - { + ActiveMQServerImpl.ShutdownOnCriticalErrorListener shutdownOnCriticalIO) throws Exception { SharedNothingBackupActivation backupActivation = new SharedNothingBackupActivation(server, wasLive, activationParams, shutdownOnCriticalIO, this); backupActivation.init(); return backupActivation; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/ReplicatedPolicy.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/ReplicatedPolicy.java index cc1fcdd4aa..4cd3e81ac6 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/ReplicatedPolicy.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/ReplicatedPolicy.java @@ -23,8 +23,8 @@ import org.apache.activemq.artemis.core.server.impl.SharedNothingLiveActivation; import java.util.Map; -public class ReplicatedPolicy implements HAPolicy -{ +public class ReplicatedPolicy implements HAPolicy { + private boolean checkForLiveServer = ActiveMQDefaultConfiguration.isDefaultCheckForLiveServer(); private String groupName = null; @@ -44,13 +44,10 @@ public class ReplicatedPolicy implements HAPolicy * */ private ReplicaPolicy replicaPolicy; - - public ReplicatedPolicy() - { + public ReplicatedPolicy() { } - public ReplicatedPolicy(boolean checkForLiveServer, String groupName, String clusterName) - { + public ReplicatedPolicy(boolean checkForLiveServer, String groupName, String clusterName) { this.checkForLiveServer = checkForLiveServer; this.groupName = groupName; this.clusterName = clusterName; @@ -60,8 +57,12 @@ public class ReplicatedPolicy implements HAPolicy replicaPolicy = new ReplicaPolicy(clusterName, -1, groupName, this); } - public ReplicatedPolicy(boolean checkForLiveServer, boolean allowAutoFailBack, long failbackDelay, String groupName, String clusterName, ReplicaPolicy replicaPolicy) - { + public ReplicatedPolicy(boolean checkForLiveServer, + boolean allowAutoFailBack, + long failbackDelay, + String groupName, + String clusterName, + ReplicaPolicy replicaPolicy) { this.checkForLiveServer = checkForLiveServer; this.clusterName = clusterName; this.groupName = groupName; @@ -70,102 +71,87 @@ public class ReplicatedPolicy implements HAPolicy this.replicaPolicy = replicaPolicy; } - public boolean isCheckForLiveServer() - { + public boolean isCheckForLiveServer() { return checkForLiveServer; } - public void setCheckForLiveServer(boolean checkForLiveServer) - { + public void setCheckForLiveServer(boolean checkForLiveServer) { this.checkForLiveServer = checkForLiveServer; } - public boolean isAllowAutoFailBack() - { + public boolean isAllowAutoFailBack() { return allowAutoFailBack; } - public long getFailbackDelay() - { + public long getFailbackDelay() { return failbackDelay; } - public void setFailbackDelay(long failbackDelay) - { + public void setFailbackDelay(long failbackDelay) { this.failbackDelay = failbackDelay; } - public String getClusterName() - { + public String getClusterName() { return clusterName; } - public void setClusterName(String clusterName) - { + public void setClusterName(String clusterName) { this.clusterName = clusterName; } - public ReplicaPolicy getReplicaPolicy() - { + public ReplicaPolicy getReplicaPolicy() { return replicaPolicy; } - public void setReplicaPolicy(ReplicaPolicy replicaPolicy) - { + public void setReplicaPolicy(ReplicaPolicy replicaPolicy) { this.replicaPolicy = replicaPolicy; } /* * these 2 methods are the same, leaving both as the second is correct but the first is needed until more refactoring is done * */ - public String getBackupGroupName() - { + public String getBackupGroupName() { return groupName; } - public String getGroupName() - { + public String getGroupName() { return groupName; } @Override - public String getScaleDownGroupName() - { + public String getScaleDownGroupName() { return null; } - public void setGroupName(String groupName) - { + public void setGroupName(String groupName) { this.groupName = groupName; } @Override - public boolean isSharedStore() - { + public boolean isSharedStore() { return false; } @Override - public boolean isBackup() - { + public boolean isBackup() { return false; } @Override - public boolean canScaleDown() - { + public boolean canScaleDown() { return false; } @Override - public String getScaleDownClustername() - { + public String getScaleDownClustername() { return null; } @Override - public LiveActivation createActivation(ActiveMQServerImpl server, boolean wasLive, Map activationParams, ActiveMQServerImpl.ShutdownOnCriticalErrorListener shutdownOnCriticalIO) - { + public LiveActivation createActivation(ActiveMQServerImpl server, + boolean wasLive, + Map activationParams, + ActiveMQServerImpl.ShutdownOnCriticalErrorListener shutdownOnCriticalIO) { return new SharedNothingLiveActivation(server, this); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/ScaleDownPolicy.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/ScaleDownPolicy.java index 2cd36b5904..17777d431b 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/ScaleDownPolicy.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/ScaleDownPolicy.java @@ -31,8 +31,8 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -public class ScaleDownPolicy -{ +public class ScaleDownPolicy { + private List connectors = new ArrayList<>(); private String discoveryGroup = null; @@ -43,100 +43,80 @@ public class ScaleDownPolicy private boolean enabled; - public ScaleDownPolicy() - { + public ScaleDownPolicy() { } - public ScaleDownPolicy(List connectors, String groupName, String clusterName, boolean enabled) - { + public ScaleDownPolicy(List connectors, String groupName, String clusterName, boolean enabled) { this.connectors = connectors; this.groupName = groupName; this.clusterName = clusterName; this.enabled = enabled; } - public ScaleDownPolicy(String discoveryGroup, String groupName, String clusterName, boolean enabled) - { + public ScaleDownPolicy(String discoveryGroup, String groupName, String clusterName, boolean enabled) { this.discoveryGroup = discoveryGroup; this.groupName = groupName; this.clusterName = clusterName; this.enabled = enabled; } - - public List getConnectors() - { + public List getConnectors() { return connectors; } - public void setConnectors(List connectors) - { + public void setConnectors(List connectors) { this.connectors = connectors; } - public String getDiscoveryGroup() - { + public String getDiscoveryGroup() { return discoveryGroup; } - public void setDiscoveryGroup(String discoveryGroup) - { + public void setDiscoveryGroup(String discoveryGroup) { this.discoveryGroup = discoveryGroup; } - public String getGroupName() - { + public String getGroupName() { return groupName; } - public void setGroupName(String groupName) - { + public void setGroupName(String groupName) { this.groupName = groupName; } - public String getClusterName() - { + public String getClusterName() { return clusterName; } - public void setClusterName(String clusterName) - { + public void setClusterName(String clusterName) { this.clusterName = clusterName; } - public boolean isEnabled() - { + public boolean isEnabled() { return enabled; } - public void setEnabled(boolean enabled) - { + public void setEnabled(boolean enabled) { this.enabled = enabled; } - public static ServerLocatorInternal getScaleDownConnector(ScaleDownPolicy scaleDownPolicy, ActiveMQServer activeMQServer) throws ActiveMQException - { - if (!scaleDownPolicy.getConnectors().isEmpty()) - { + public static ServerLocatorInternal getScaleDownConnector(ScaleDownPolicy scaleDownPolicy, + ActiveMQServer activeMQServer) throws ActiveMQException { + if (!scaleDownPolicy.getConnectors().isEmpty()) { return (ServerLocatorInternal) ActiveMQClient.createServerLocatorWithHA(connectorNameListToArray(scaleDownPolicy.getConnectors(), activeMQServer)); } - else if (scaleDownPolicy.getDiscoveryGroup() != null) - { + else if (scaleDownPolicy.getDiscoveryGroup() != null) { DiscoveryGroupConfiguration dg = activeMQServer.getConfiguration().getDiscoveryGroupConfigurations().get(scaleDownPolicy.getDiscoveryGroup()); - if (dg == null) - { + if (dg == null) { throw ActiveMQMessageBundle.BUNDLE.noDiscoveryGroupFound(dg); } - return (ServerLocatorInternal) ActiveMQClient.createServerLocatorWithHA(dg); + return (ServerLocatorInternal) ActiveMQClient.createServerLocatorWithHA(dg); } - else - { + else { Map connectorConfigurations = activeMQServer.getConfiguration().getConnectorConfigurations(); - for (TransportConfiguration transportConfiguration : connectorConfigurations.values()) - { - if (transportConfiguration.getFactoryClassName().equals(InVMConnectorFactory.class.getName())) - { + for (TransportConfiguration transportConfiguration : connectorConfigurations.values()) { + if (transportConfiguration.getFactoryClassName().equals(InVMConnectorFactory.class.getName())) { return (ServerLocatorInternal) ActiveMQClient.createServerLocatorWithHA(transportConfiguration); } } @@ -144,17 +124,14 @@ public class ScaleDownPolicy throw ActiveMQMessageBundle.BUNDLE.noConfigurationFoundForScaleDown(); } - private static TransportConfiguration[] connectorNameListToArray(final List connectorNames, ActiveMQServer activeMQServer) - { - TransportConfiguration[] tcConfigs = (TransportConfiguration[]) Array.newInstance(TransportConfiguration.class, - connectorNames.size()); + private static TransportConfiguration[] connectorNameListToArray(final List connectorNames, + ActiveMQServer activeMQServer) { + TransportConfiguration[] tcConfigs = (TransportConfiguration[]) Array.newInstance(TransportConfiguration.class, connectorNames.size()); int count = 0; - for (String connectorName : connectorNames) - { + for (String connectorName : connectorNames) { TransportConfiguration connector = activeMQServer.getConfiguration().getConnectorConfigurations().get(connectorName); - if (connector == null) - { + if (connector == null) { ActiveMQServerLogger.LOGGER.bridgeNoConnector(connectorName); return null; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/SharedStoreMasterPolicy.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/SharedStoreMasterPolicy.java index ab7e55f691..653cd93e97 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/SharedStoreMasterPolicy.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/SharedStoreMasterPolicy.java @@ -23,93 +23,81 @@ import org.apache.activemq.artemis.core.server.impl.SharedStoreLiveActivation; import java.util.Map; -public class SharedStoreMasterPolicy implements HAPolicy -{ +public class SharedStoreMasterPolicy implements HAPolicy { + private long failbackDelay = ActiveMQDefaultConfiguration.getDefaultFailbackDelay(); private boolean failoverOnServerShutdown = ActiveMQDefaultConfiguration.isDefaultFailoverOnServerShutdown(); private SharedStoreSlavePolicy sharedStoreSlavePolicy; - public SharedStoreMasterPolicy() - { + public SharedStoreMasterPolicy() { } - public SharedStoreMasterPolicy(long failbackDelay, boolean failoverOnServerShutdown) - { + public SharedStoreMasterPolicy(long failbackDelay, boolean failoverOnServerShutdown) { this.failbackDelay = failbackDelay; this.failoverOnServerShutdown = failoverOnServerShutdown; } - public long getFailbackDelay() - { + public long getFailbackDelay() { return failbackDelay; } - public void setFailbackDelay(long failbackDelay) - { + public void setFailbackDelay(long failbackDelay) { this.failbackDelay = failbackDelay; } - public boolean isFailoverOnServerShutdown() - { + public boolean isFailoverOnServerShutdown() { return failoverOnServerShutdown; } - public void setFailoverOnServerShutdown(boolean failoverOnServerShutdown) - { + public void setFailoverOnServerShutdown(boolean failoverOnServerShutdown) { this.failoverOnServerShutdown = failoverOnServerShutdown; } - public SharedStoreSlavePolicy getSharedStoreSlavePolicy() - { + public SharedStoreSlavePolicy getSharedStoreSlavePolicy() { return sharedStoreSlavePolicy; } - public void setSharedStoreSlavePolicy(SharedStoreSlavePolicy sharedStoreSlavePolicy) - { + public void setSharedStoreSlavePolicy(SharedStoreSlavePolicy sharedStoreSlavePolicy) { this.sharedStoreSlavePolicy = sharedStoreSlavePolicy; } @Override - public boolean isSharedStore() - { + public boolean isSharedStore() { return true; } @Override - public boolean isBackup() - { + public boolean isBackup() { return false; } @Override - public boolean canScaleDown() - { + public boolean canScaleDown() { return false; } @Override - public LiveActivation createActivation(ActiveMQServerImpl server, boolean wasLive, Map activationParams, ActiveMQServerImpl.ShutdownOnCriticalErrorListener shutdownOnCriticalIO) - { - return new SharedStoreLiveActivation(server, this); + public LiveActivation createActivation(ActiveMQServerImpl server, + boolean wasLive, + Map activationParams, + ActiveMQServerImpl.ShutdownOnCriticalErrorListener shutdownOnCriticalIO) { + return new SharedStoreLiveActivation(server, this); } @Override - public String getBackupGroupName() - { + public String getBackupGroupName() { return null; } @Override - public String getScaleDownGroupName() - { + public String getScaleDownGroupName() { return null; } @Override - public String getScaleDownClustername() - { + public String getScaleDownClustername() { return null; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/SharedStoreSlavePolicy.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/SharedStoreSlavePolicy.java index d5f34ddff4..259d38a459 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/SharedStoreSlavePolicy.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/SharedStoreSlavePolicy.java @@ -23,8 +23,8 @@ import org.apache.activemq.artemis.core.server.impl.SharedStoreBackupActivation; import java.util.Map; -public class SharedStoreSlavePolicy extends BackupPolicy -{ +public class SharedStoreSlavePolicy extends BackupPolicy { + private long failbackDelay = ActiveMQDefaultConfiguration.getDefaultFailbackDelay(); private boolean failoverOnServerShutdown = ActiveMQDefaultConfiguration.isDefaultFailoverOnServerShutdown(); @@ -34,12 +34,14 @@ public class SharedStoreSlavePolicy extends BackupPolicy //this is how we act once we have failed over private SharedStoreMasterPolicy sharedStoreMasterPolicy; - public SharedStoreSlavePolicy() - { + public SharedStoreSlavePolicy() { } - public SharedStoreSlavePolicy(long failbackDelay, boolean failoverOnServerShutdown, boolean restartBackup, boolean allowAutoFailBack, ScaleDownPolicy scaleDownPolicy) - { + public SharedStoreSlavePolicy(long failbackDelay, + boolean failoverOnServerShutdown, + boolean restartBackup, + boolean allowAutoFailBack, + ScaleDownPolicy scaleDownPolicy) { this.failbackDelay = failbackDelay; this.failoverOnServerShutdown = failoverOnServerShutdown; this.restartBackup = restartBackup; @@ -48,67 +50,58 @@ public class SharedStoreSlavePolicy extends BackupPolicy sharedStoreMasterPolicy = new SharedStoreMasterPolicy(failbackDelay, failoverOnServerShutdown); } - public long getFailbackDelay() - { + public long getFailbackDelay() { return failbackDelay; } - public void setFailbackDelay(long failbackDelay) - { + public void setFailbackDelay(long failbackDelay) { this.failbackDelay = failbackDelay; } - public boolean isFailoverOnServerShutdown() - { + public boolean isFailoverOnServerShutdown() { return failoverOnServerShutdown; } - public void setFailoverOnServerShutdown(boolean failoverOnServerShutdown) - { + public void setFailoverOnServerShutdown(boolean failoverOnServerShutdown) { this.failoverOnServerShutdown = failoverOnServerShutdown; } - public SharedStoreMasterPolicy getSharedStoreMasterPolicy() - { + public SharedStoreMasterPolicy getSharedStoreMasterPolicy() { return sharedStoreMasterPolicy; } - public void setSharedStoreMasterPolicy(SharedStoreMasterPolicy sharedStoreMasterPolicy) - { + public void setSharedStoreMasterPolicy(SharedStoreMasterPolicy sharedStoreMasterPolicy) { this.sharedStoreMasterPolicy = sharedStoreMasterPolicy; } @Override - public boolean isSharedStore() - { + public boolean isSharedStore() { return true; } @Override - public boolean canScaleDown() - { + public boolean canScaleDown() { return scaleDownPolicy != null; } - public boolean isAllowAutoFailBack() - { + public boolean isAllowAutoFailBack() { return allowAutoFailBack; } - public void setAllowAutoFailBack(boolean allowAutoFailBack) - { + public void setAllowAutoFailBack(boolean allowAutoFailBack) { this.allowAutoFailBack = allowAutoFailBack; } @Override - public Activation createActivation(ActiveMQServerImpl server, boolean wasLive, Map activationParams, ActiveMQServerImpl.ShutdownOnCriticalErrorListener shutdownOnCriticalIO) - { + public Activation createActivation(ActiveMQServerImpl server, + boolean wasLive, + Map activationParams, + ActiveMQServerImpl.ShutdownOnCriticalErrorListener shutdownOnCriticalIO) { return new SharedStoreBackupActivation(server, this); } @Override - public String getBackupGroupName() - { + public String getBackupGroupName() { return null; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/StandaloneHAManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/StandaloneHAManager.java index 40f7769d71..3b0b9083b1 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/StandaloneHAManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/StandaloneHAManager.java @@ -24,37 +24,33 @@ import java.util.Map; /* * this implementation doesn't really do anything at the minute but this may change so Im leaving it here, Andy... * */ -public class StandaloneHAManager implements HAManager -{ +public class StandaloneHAManager implements HAManager { + Map servers = new HashMap<>(); boolean isStarted = false; @Override - public Map getBackupServers() - { + public Map getBackupServers() { return servers; } @Override - public void start() throws Exception - { + public void start() throws Exception { if (isStarted) return; isStarted = true; } @Override - public void stop() throws Exception - { + public void stop() throws Exception { if (!isStarted) return; isStarted = false; } @Override - public boolean isStarted() - { + public boolean isStarted() { return isStarted; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/BridgeImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/BridgeImpl.java index 243bc71207..9853455b36 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/BridgeImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/BridgeImpl.java @@ -66,8 +66,7 @@ import org.apache.activemq.artemis.utils.UUID; * A Core BridgeImpl */ -public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowledgementHandler -{ +public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowledgementHandler { // Constants ----------------------------------------------------- private static final boolean isTrace = ActiveMQServerLogger.LOGGER.isTraceEnabled(); @@ -167,8 +166,7 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled final boolean useDuplicateDetection, final String user, final String password, - final StorageManager storageManager) - { + final StorageManager storageManager) { this.reconnectAttempts = reconnectAttempts; @@ -207,8 +205,7 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled this.password = password; } - public static final byte[] getDuplicateBytes(final UUID nodeUUID, final long messageID) - { + public static final byte[] getDuplicateBytes(final UUID nodeUUID, final long messageID) { byte[] bytes = new byte[24]; ByteBuffer bb = ByteBuffer.wrap(bytes); @@ -224,29 +221,23 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled * @see org.apache.activemq.artemis.core.server.Consumer#getDeliveringMessages() */ @Override - public List getDeliveringMessages() - { - synchronized (this) - { + public List getDeliveringMessages() { + synchronized (this) { return new ArrayList(refs); } } - private static void cleanUpSessionFactory(ClientSessionFactoryInternal factory) - { + private static void cleanUpSessionFactory(ClientSessionFactoryInternal factory) { if (factory != null) factory.cleanup(); } - public void setNotificationService(final NotificationService notificationService) - { + public void setNotificationService(final NotificationService notificationService) { this.notificationService = notificationService; } - public synchronized void start() throws Exception - { - if (started) - { + public synchronized void start() throws Exception { + if (started) { return; } @@ -256,8 +247,7 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled activate(); - if (notificationService != null) - { + if (notificationService != null) { TypedProperties props = new TypedProperties(); props.putSimpleStringProperty(new SimpleString("name"), name); Notification notification = new Notification(nodeUUID.toString(), CoreNotificationType.BRIDGE_STARTED, props); @@ -265,28 +255,23 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled } } - public String debug() - { + public String debug() { return toString(); } - private void cancelRefs() - { + private void cancelRefs() { MessageReference ref; LinkedList list = new LinkedList(); - while ((ref = refs.poll()) != null) - { - if (isTrace) - { + while ((ref = refs.poll()) != null) { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Cancelling reference " + ref + " on bridge " + this); } list.addFirst(ref); } - if (isTrace && list.isEmpty()) - { + if (isTrace && list.isEmpty()) { ActiveMQServerLogger.LOGGER.trace("didn't have any references to cancel on bridge " + this); } @@ -294,24 +279,20 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled long timeBase = System.currentTimeMillis(); - for (MessageReference ref2 : list) - { + for (MessageReference ref2 : list) { refqueue = ref2.getQueue(); - try - { + try { refqueue.cancel(ref2, timeBase); } - catch (Exception e) - { + catch (Exception e) { // There isn't much we can do besides log an error ActiveMQServerLogger.LOGGER.errorCancellingRefOnBridge(e, ref2); } } } - public void flushExecutor() - { + public void flushExecutor() { // Wait for any create objects runnable to complete FutureLatch future = new FutureLatch(); @@ -319,26 +300,19 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled boolean ok = future.await(10000); - if (!ok) - { + if (!ok) { ActiveMQServerLogger.LOGGER.timedOutWaitingToStopBridge(); } } - public void disconnect() - { - executor.execute(new Runnable() - { - public void run() - { - if (session != null) - { - try - { + public void disconnect() { + executor.execute(new Runnable() { + public void run() { + if (session != null) { + try { session.cleanUp(false); } - catch (Exception dontcare) - { + catch (Exception dontcare) { ActiveMQServerLogger.LOGGER.debug(dontcare.getMessage(), dontcare); } session = null; @@ -347,8 +321,7 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled }); } - public boolean isConnected() - { + public boolean isConnected() { return session != null; } @@ -356,214 +329,170 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled * The cluster manager needs to use the same executor to close the serverLocator, otherwise the stop will break. * This method is intended to expose this executor to the ClusterManager */ - public Executor getExecutor() - { + public Executor getExecutor() { return executor; } - public void stop() throws Exception - { - if (stopping) - { + public void stop() throws Exception { + if (stopping) { return; } stopping = true; - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Bridge " + this.name + " being stopped"); } - if (futureScheduledReconnection != null) - { + if (futureScheduledReconnection != null) { futureScheduledReconnection.cancel(true); } executor.execute(new StopRunnable()); - if (notificationService != null) - { + if (notificationService != null) { TypedProperties props = new TypedProperties(); props.putSimpleStringProperty(new SimpleString("name"), name); Notification notification = new Notification(nodeUUID.toString(), CoreNotificationType.BRIDGE_STOPPED, props); - try - { + try { notificationService.sendNotification(notification); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.broadcastBridgeStoppedError(e); } } } - public void pause() throws Exception - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + public void pause() throws Exception { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Bridge " + this.name + " being paused"); } executor.execute(new PauseRunnable()); - if (notificationService != null) - { + if (notificationService != null) { TypedProperties props = new TypedProperties(); props.putSimpleStringProperty(new SimpleString("name"), name); Notification notification = new Notification(nodeUUID.toString(), CoreNotificationType.BRIDGE_STOPPED, props); - try - { + try { notificationService.sendNotification(notification); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.notificationBridgeStoppedError(e); } } } - public void resume() throws Exception - { + public void resume() throws Exception { queue.addConsumer(BridgeImpl.this); queue.deliverAsync(); } - public boolean isStarted() - { + public boolean isStarted() { return started; } - public synchronized void activate() - { + public synchronized void activate() { executor.execute(new ConnectRunnable(this)); } - public SimpleString getName() - { + public SimpleString getName() { return name; } - public Queue getQueue() - { + public Queue getQueue() { return queue; } - public Filter getFilter() - { + public Filter getFilter() { return filter; } // SendAcknowledgementHandler implementation --------------------- - public SimpleString getForwardingAddress() - { + public SimpleString getForwardingAddress() { return forwardingAddress; } // For testing only - public RemotingConnection getForwardingConnection() - { - if (session == null) - { + public RemotingConnection getForwardingConnection() { + if (session == null) { return null; } - else - { + else { return session.getConnection(); } } - // Consumer implementation --------------------------------------- - public void sendAcknowledged(final Message message) - { - if (active) - { - try - { + public void sendAcknowledged(final Message message) { + if (active) { + try { final MessageReference ref = refs.poll(); - if (ref != null) - { - if (isTrace) - { + if (ref != null) { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace(this + " Acking " + ref + " on queue " + ref.getQueue()); } ref.getQueue().acknowledge(ref); pendingAcks.countDown(); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.bridgeFailedToAck(e); } } } - protected boolean isPlainCoreBridge() - { + protected boolean isPlainCoreBridge() { return true; } /* Hook for processing message before forwarding */ - protected ServerMessage beforeForward(final ServerMessage message) - { - if (useDuplicateDetection) - { + protected ServerMessage beforeForward(final ServerMessage message) { + if (useDuplicateDetection) { // We keep our own DuplicateID for the Bridge, so bouncing back and forths will work fine byte[] bytes = getDuplicateBytes(nodeUUID, message.getMessageID()); message.putBytesProperty(MessageImpl.HDR_BRIDGE_DUPLICATE_ID, bytes); } - if (transformer != null) - { + if (transformer != null) { final ServerMessage transformedMessage = transformer.transform(message); - if (transformedMessage != message) - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (transformedMessage != message) { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("The transformer " + transformer + - " made a copy of the message " + - message + - " as transformedMessage"); + " made a copy of the message " + + message + + " as transformedMessage"); } } return transformedMessage; } - else - { + else { return message; } } - public HandleStatus handle(final MessageReference ref) throws Exception - { - if (filter != null && !filter.match(ref.getMessage())) - { + public HandleStatus handle(final MessageReference ref) throws Exception { + if (filter != null && !filter.match(ref.getMessage())) { return HandleStatus.NO_MATCH; } - synchronized (this) - { - if (!active) - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + synchronized (this) { + if (!active) { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug(this + "::Ignoring reference on bridge as it is set to inactive ref=" + ref); } return HandleStatus.BUSY; } - if (deliveringLargeMessage) - { + if (deliveringLargeMessage) { return HandleStatus.BUSY; } - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Bridge " + this + " is handling reference=" + ref); } @@ -575,33 +504,27 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled final SimpleString dest; - if (forwardingAddress != null) - { + if (forwardingAddress != null) { dest = forwardingAddress; } - else - { + else { // Preserve the original address dest = message.getAddress(); } pendingAcks.countUp(); - try - { - if (message.isLargeMessage()) - { + try { + if (message.isLargeMessage()) { deliveringLargeMessage = true; deliverLargeMessage(dest, ref, (LargeServerMessage) message); return HandleStatus.HANDLED; } - else - { + else { return deliverStandardMessage(dest, ref, message); } } - catch (Exception e) - { + catch (Exception e) { // If an exception happened, we must count down immediately pendingAcks.countDown(); throw e; @@ -609,75 +532,59 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled } } - // FailureListener implementation -------------------------------- - public void proceedDeliver(MessageReference ref) - { + public void proceedDeliver(MessageReference ref) { // no op } - public void connectionFailed(final ActiveMQException me, boolean failedOver) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver) { connectionFailed(me, failedOver, null); } - public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) { ActiveMQServerLogger.LOGGER.bridgeConnectionFailed(me, failedOver); - synchronized (connectionGuard) - { + synchronized (connectionGuard) { keepConnecting = true; } - try - { - if (producer != null) - { + try { + if (producer != null) { producer.close(); } cleanUpSessionFactory(csf); } - catch (Throwable dontCare) - { + catch (Throwable dontCare) { } - try - { + try { session.cleanUp(false); } - catch (Throwable dontCare) - { + catch (Throwable dontCare) { } - if (scaleDownTargetNodeID != null && !scaleDownTargetNodeID.equals(nodeUUID)) - { - synchronized (this) - { - try - { + if (scaleDownTargetNodeID != null && !scaleDownTargetNodeID.equals(nodeUUID)) { + synchronized (this) { + try { ActiveMQServerLogger.LOGGER.debug("Moving " + queue.getMessageCount() + " messages from " + queue.getName() + " to " + scaleDownTargetNodeID); - ((QueueImpl)queue).moveReferencesBetweenSnFQueues(SimpleString.toSimpleString(scaleDownTargetNodeID)); + ((QueueImpl) queue).moveReferencesBetweenSnFQueues(SimpleString.toSimpleString(scaleDownTargetNodeID)); // stop the bridge from trying to reconnect and clean up all the bindings fail(true); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e); } } } - else if (scaleDownTargetNodeID != null) - { + else if (scaleDownTargetNodeID != null) { // the disconnected node is scaling down to me, no need to reconnect to it ActiveMQServerLogger.LOGGER.debug("Received scaleDownTargetNodeID: " + scaleDownTargetNodeID + "; cancelling reconnect."); fail(true); } - else - { + else { ActiveMQServerLogger.LOGGER.debug("Received invalid scaleDownTargetNodeID: " + scaleDownTargetNodeID); //we never fail permanently here, this only happens once all reconnect tries have happened @@ -687,27 +594,21 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled tryScheduleRetryReconnect(me.getType()); } - protected void tryScheduleRetryReconnect(final ActiveMQExceptionType type) - { + protected void tryScheduleRetryReconnect(final ActiveMQExceptionType type) { scheduleRetryConnect(); } - public void beforeReconnect(final ActiveMQException exception) - { + public void beforeReconnect(final ActiveMQException exception) { // log.warn(name + "::Connection failed before reconnect ", exception); // fail(false); } private void deliverLargeMessage(final SimpleString dest, final MessageReference ref, - final LargeServerMessage message) - { - executor.execute(new Runnable() - { - public void run() - { - try - { + final LargeServerMessage message) { + executor.execute(new Runnable() { + public void run() { + try { producer.send(dest, message); // as soon as we are done sending the large message @@ -715,13 +616,11 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled // so the bridge will be able to resume work unsetLargeMessageDelivery(); - if (queue != null) - { + if (queue != null) { queue.deliverAsync(); } } - catch (final ActiveMQException e) - { + catch (final ActiveMQException e) { unsetLargeMessageDelivery(); ActiveMQServerLogger.LOGGER.bridgeUnableToSendMessage(e, ref); @@ -736,24 +635,20 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled * @param message * @return */ - private HandleStatus deliverStandardMessage(SimpleString dest, final MessageReference ref, ServerMessage message) - { + private HandleStatus deliverStandardMessage(SimpleString dest, final MessageReference ref, ServerMessage message) { // if we failover during send then there is a chance that the // that this will throw a disconnect, we need to remove the message // from the acks so it will get resent, duplicate detection will cope // with any messages resent - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("going to send message: " + message + " from " + this.getQueue()); } - try - { + try { producer.send(dest, message); } - catch (final ActiveMQException e) - { + catch (final ActiveMQException e) { ActiveMQServerLogger.LOGGER.bridgeUnableToSendMessage(e, ref); // We remove this reference as we are returning busy which means the reference will never leave the Queue. @@ -773,14 +668,12 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled * * @return */ - public TopologyMember getTargetNodeFromTopology() - { + public TopologyMember getTargetNodeFromTopology() { return this.targetNode; } @Override - public String toString() - { + public String toString() { return this.getClass().getSimpleName() + "@" + Integer.toHexString(System.identityHashCode(this)) + " [name=" + @@ -793,8 +686,7 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled } @Override - public String toManagementString() - { + public String toManagementString() { return this.getClass().getSimpleName() + " [name=" + name + @@ -802,96 +694,78 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled queue.getName() + "/" + queue.getID() + "]"; } - public ClientSessionFactoryImpl getCSF() - { + public ClientSessionFactoryImpl getCSF() { return (ClientSessionFactoryImpl) csf; } - public Transformer getTransformer() - { + public Transformer getTransformer() { return transformer; } - protected void fail(final boolean permanently) - { + + protected void fail(final boolean permanently) { ActiveMQServerLogger.LOGGER.debug(this + "\n\t::fail being called, permanently=" + permanently); - if (queue != null) - { - try - { - if (isTrace) - { + if (queue != null) { + try { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Removing consumer on fail " + this + " from queue " + queue); } queue.removeConsumer(this); } - catch (Exception dontcare) - { + catch (Exception dontcare) { ActiveMQServerLogger.LOGGER.debug(dontcare); } } cancelRefs(); - if (queue != null) - { + if (queue != null) { queue.deliverAsync(); } } /* Hook for doing extra stuff after connection */ - protected void afterConnect() throws Exception - { + protected void afterConnect() throws Exception { retryCount = 0; reconnectAttemptsInUse = reconnectAttempts; - if (futureScheduledReconnection != null) - { + if (futureScheduledReconnection != null) { futureScheduledReconnection.cancel(true); futureScheduledReconnection = null; } } /* Hook for creating session factory */ - protected ClientSessionFactoryInternal createSessionFactory() throws Exception - { - if (targetNodeID != null && (this.reconnectAttemptsSameNode < 0 || retryCount <= this.reconnectAttemptsSameNode)) - { + protected ClientSessionFactoryInternal createSessionFactory() throws Exception { + if (targetNodeID != null && (this.reconnectAttemptsSameNode < 0 || retryCount <= this.reconnectAttemptsSameNode)) { csf = reconnectOnOriginalNode(); } - else - { + else { serverLocator.resetToInitialConnectors(); csf = (ClientSessionFactoryInternal) serverLocator.createSessionFactory(); } // null here means the targetNodeIS is not available yet - if (csf != null) - { + if (csf != null) { csf.setReconnectAttempts(0); } return csf; } - private ClientSessionFactoryInternal reconnectOnOriginalNode() throws Exception - { + private ClientSessionFactoryInternal reconnectOnOriginalNode() throws Exception { String targetNodeIdUse = targetNodeID; TopologyMember nodeUse = targetNode; - if (targetNodeIdUse != null && nodeUse != null) - { + if (targetNodeIdUse != null && nodeUse != null) { TransportConfiguration[] configs = new TransportConfiguration[2]; // live and backup int numberOfConfigs = 0; - if (nodeUse.getLive() != null) - { + if (nodeUse.getLive() != null) { configs[numberOfConfigs++] = nodeUse.getLive(); } - if (nodeUse.getBackup() != null) - { + if (nodeUse.getBackup() != null) { configs[numberOfConfigs++] = nodeUse.getBackup(); } - if (numberOfConfigs > 0) - { + if (numberOfConfigs > 0) { // It will bounce between all the available configs int nodeTry = (retryCount - 1) % numberOfConfigs; @@ -902,36 +776,29 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled return null; } - - protected void setSessionFactory(ClientSessionFactoryInternal sfi) - { + protected void setSessionFactory(ClientSessionFactoryInternal sfi) { csf = sfi; } /* This is called only when the bridge is activated */ - protected void connect() - { + protected void connect() { if (stopping) return; - - synchronized (connectionGuard) - { - if (!keepConnecting) return; + synchronized (connectionGuard) { + if (!keepConnecting) + return; ActiveMQServerLogger.LOGGER.debug("Connecting " + this + " to its destination [" + nodeUUID.toString() + "], csf=" + this.csf); retryCount++; - try - { - if (csf == null || csf.isClosed()) - { + try { + if (csf == null || csf.isClosed()) { if (stopping) return; csf = createSessionFactory(); - if (csf == null) - { + if (csf == null) { // Retrying. This probably means the node is not available (for the cluster connection case) scheduleRetryConnect(); return; @@ -940,16 +807,13 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled session = (ClientSessionInternal) csf.createSession(user, password, false, true, true, true, 1); } - if (forwardingAddress != null) - { + if (forwardingAddress != null) { ClientSession.AddressQuery query = null; - try - { + try { query = session.addressQuery(forwardingAddress); } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQServerLogger.LOGGER.errorQueryingBridge(e, name); // This was an issue during startup, we will not count this retry retryCount--; @@ -958,19 +822,15 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled return; } - if (forwardingAddress.startsWith(BridgeImpl.JMS_QUEUE_ADDRESS_PREFIX) || forwardingAddress.startsWith(BridgeImpl.JMS_TOPIC_ADDRESS_PREFIX)) - { - if (!query.isExists()) - { + if (forwardingAddress.startsWith(BridgeImpl.JMS_QUEUE_ADDRESS_PREFIX) || forwardingAddress.startsWith(BridgeImpl.JMS_TOPIC_ADDRESS_PREFIX)) { + if (!query.isExists()) { ActiveMQServerLogger.LOGGER.errorQueryingBridge(forwardingAddress, retryCount); scheduleRetryConnect(); return; } } - else - { - if (!query.isExists()) - { + else { + if (!query.isExists()) { ActiveMQServerLogger.LOGGER.bridgeNoBindings(getName(), getForwardingAddress(), getForwardingAddress()); } } @@ -991,19 +851,16 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled ActiveMQServerLogger.LOGGER.bridgeConnected(this); // We only do this on plain core bridges - if (isPlainCoreBridge()) - { + if (isPlainCoreBridge()) { serverLocator.addClusterTopologyListener(new TopologyListener()); } keepConnecting = false; return; } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { // the session was created while its server was starting, retry it: - if (e.getType() == ActiveMQExceptionType.SESSION_CREATION_REJECTED) - { + if (e.getType() == ActiveMQExceptionType.SESSION_CREATION_REJECTED) { ActiveMQServerLogger.LOGGER.errorStartingBridge(name); // We are not going to count this one as a retry @@ -1012,98 +869,79 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled scheduleRetryConnectFixedTimeout(this.retryInterval); return; } - else - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + else { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Bridge " + this + " is unable to connect to destination. Retrying", e); } scheduleRetryConnect(); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorConnectingBridge(e, this); } } } - protected void scheduleRetryConnect() - { - if (serverLocator.isClosed()) - { + protected void scheduleRetryConnect() { + if (serverLocator.isClosed()) { ActiveMQServerLogger.LOGGER.bridgeLocatorShutdown(); return; } - if (stopping) - { + if (stopping) { ActiveMQServerLogger.LOGGER.bridgeStopping(); return; } - if (reconnectAttemptsInUse >= 0 && retryCount > reconnectAttemptsInUse) - { + if (reconnectAttemptsInUse >= 0 && retryCount > reconnectAttemptsInUse) { ActiveMQServerLogger.LOGGER.bridgeAbortStart(name, retryCount, reconnectAttempts); fail(true); return; } long timeout = (long) (this.retryInterval * Math.pow(this.retryMultiplier, retryCount)); - if (timeout == 0) - { + if (timeout == 0) { timeout = this.retryInterval; } - if (timeout > maxRetryInterval) - { + if (timeout > maxRetryInterval) { timeout = maxRetryInterval; } ActiveMQServerLogger.LOGGER.debug("Bridge " + this + - " retrying connection #" + - retryCount + - ", maxRetry=" + - reconnectAttemptsInUse + - ", timeout=" + - timeout); + " retrying connection #" + + retryCount + + ", maxRetry=" + + reconnectAttemptsInUse + + ", timeout=" + + timeout); scheduleRetryConnectFixedTimeout(timeout); } // Inner classes ------------------------------------------------- - protected void scheduleRetryConnectFixedTimeout(final long milliseconds) - { - try - { + protected void scheduleRetryConnectFixedTimeout(final long milliseconds) { + try { cleanUpSessionFactory(csf); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } - if (stopping) return; - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Scheduling retry for bridge " + this.name + " in " + milliseconds + " milliseconds"); } - futureScheduledReconnection = - scheduledExecutor.schedule(new FutureConnectRunnable(executor, this), - milliseconds, - TimeUnit.MILLISECONDS); + futureScheduledReconnection = scheduledExecutor.schedule(new FutureConnectRunnable(executor, this), milliseconds, TimeUnit.MILLISECONDS); } - private void internalCancelReferences() - { + private void internalCancelReferences() { cancelRefs(); - if (queue != null) - { + if (queue != null) { queue.deliverAsync(); } } @@ -1111,63 +949,53 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled /** * just set deliveringLargeMessage to false */ - private synchronized void unsetLargeMessageDelivery() - { + private synchronized void unsetLargeMessageDelivery() { deliveringLargeMessage = false; } // The scheduling will still use the main executor here - private static class FutureConnectRunnable implements Runnable - { + private static class FutureConnectRunnable implements Runnable { + private final BridgeImpl bridge; private final Executor executor; - public FutureConnectRunnable(Executor exe, BridgeImpl bridge) - { + public FutureConnectRunnable(Executor exe, BridgeImpl bridge) { executor = exe; this.bridge = bridge; } - public void run() - { + public void run() { if (bridge.isStarted()) executor.execute(new ConnectRunnable(bridge)); } } - private static final class ConnectRunnable implements Runnable - { + private static final class ConnectRunnable implements Runnable { + private final BridgeImpl bridge; - public ConnectRunnable(BridgeImpl bridge2) - { + public ConnectRunnable(BridgeImpl bridge2) { bridge = bridge2; } - public void run() - { + public void run() { bridge.connect(); } } - private class StopRunnable implements Runnable - { - public void run() - { - try - { + private class StopRunnable implements Runnable { + + public void run() { + try { ActiveMQServerLogger.LOGGER.debug("stopping bridge " + BridgeImpl.this); queue.removeConsumer(BridgeImpl.this); - if (!pendingAcks.await(10, TimeUnit.SECONDS)) - { - ActiveMQServerLogger.LOGGER.timedOutWaitingCompletions(BridgeImpl.this.toString(), - pendingAcks.getCount()); + if (!pendingAcks.await(10, TimeUnit.SECONDS)) { + ActiveMQServerLogger.LOGGER.timedOutWaitingCompletions(BridgeImpl.this.toString(), pendingAcks.getCount()); } - synchronized (BridgeImpl.this) - { + synchronized (BridgeImpl.this) { ActiveMQServerLogger.LOGGER.debug("Closing Session for bridge " + BridgeImpl.this.name); started = false; @@ -1176,66 +1004,52 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled } - internalCancelReferences(); - if (session != null) - { + if (session != null) { ActiveMQServerLogger.LOGGER.debug("Cleaning up session " + session); session.removeFailureListener(BridgeImpl.this); - try - { + try { session.close(); session = null; } - catch (ActiveMQException dontcare) - { + catch (ActiveMQException dontcare) { } } - if (csf != null) - { + if (csf != null) { csf.cleanup(); } - synchronized (connectionGuard) - { + synchronized (connectionGuard) { keepConnecting = true; } - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Removing consumer on stopRunnable " + this + " from queue " + queue); } ActiveMQServerLogger.LOGGER.bridgeStopped(name); } - catch (RuntimeException e) - { + catch (RuntimeException e) { ActiveMQServerLogger.LOGGER.error("Failed to stop bridge", e); } - catch (InterruptedException e) - { + catch (InterruptedException e) { ActiveMQServerLogger.LOGGER.error("Failed to stop bridge", e); } } } - private class PauseRunnable implements Runnable - { - public void run() - { - try - { + private class PauseRunnable implements Runnable { + + public void run() { + try { queue.removeConsumer(BridgeImpl.this); - if (!pendingAcks.await(60, TimeUnit.SECONDS)) - { - ActiveMQServerLogger.LOGGER.timedOutWaitingCompletions(BridgeImpl.this.toString(), - pendingAcks.getCount()); + if (!pendingAcks.await(60, TimeUnit.SECONDS)) { + ActiveMQServerLogger.LOGGER.timedOutWaitingCompletions(BridgeImpl.this.toString(), pendingAcks.getCount()); } - synchronized (BridgeImpl.this) - { + synchronized (BridgeImpl.this) { started = false; active = false; } @@ -1244,34 +1058,28 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled ActiveMQServerLogger.LOGGER.bridgePaused(name); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorPausingBridge(e); } } } - private class TopologyListener implements ClusterTopologyListener - { + private class TopologyListener implements ClusterTopologyListener { // ClusterListener @Override - public void nodeUP(TopologyMember member, boolean last) - { + public void nodeUP(TopologyMember member, boolean last) { ClientSessionInternal sessionToUse = session; RemotingConnection connectionToUse = sessionToUse != null ? sessionToUse.getConnection() : null; - if (member != null && BridgeImpl.this.targetNodeID != null && BridgeImpl.this.targetNodeID.equals(member.getNodeId())) - { + if (member != null && BridgeImpl.this.targetNodeID != null && BridgeImpl.this.targetNodeID.equals(member.getNodeId())) { // this could be an update of the topology say after a backup started BridgeImpl.this.targetNode = member; } - else - { + else { // we don't need synchronization here, but we need to make sure we won't get a NPE on races - if (connectionToUse != null && member.isMember(connectionToUse)) - { + if (connectionToUse != null && member.isMember(connectionToUse)) { BridgeImpl.this.targetNode = member; BridgeImpl.this.targetNodeID = member.getNodeId(); } @@ -1280,8 +1088,7 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled } @Override - public void nodeDown(long eventUID, String nodeID) - { + public void nodeDown(long eventUID, String nodeID) { } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/BroadcastGroupImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/BroadcastGroupImpl.java index 4720fc77c2..d69355ce5b 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/BroadcastGroupImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/BroadcastGroupImpl.java @@ -39,13 +39,13 @@ import org.apache.activemq.artemis.utils.UUIDGenerator; /** *

    This class will use the {@link BroadcastEndpoint} to send periodical updates on the list for connections - * used by this server.

    + * used by this server.

    * *

    This is totally generic to the mechanism used on the transmission. It originally only had UDP but this got refactored * into sub classes of {@link BroadcastEndpoint}

    */ -public class BroadcastGroupImpl implements BroadcastGroup, Runnable -{ +public class BroadcastGroupImpl implements BroadcastGroup, Runnable { + private final NodeManager nodeManager; private final String name; @@ -70,13 +70,11 @@ public class BroadcastGroupImpl implements BroadcastGroup, Runnable private BroadcastEndpoint endpoint; - public BroadcastGroupImpl(final NodeManager nodeManager, - final String name, - final long broadCastPeriod, - final ScheduledExecutorService scheduledExecutor, - final BroadcastEndpointFactory endpointFactory) throws Exception - { + final String name, + final long broadCastPeriod, + final ScheduledExecutorService scheduledExecutor, + final BroadcastEndpointFactory endpointFactory) throws Exception { this.nodeManager = nodeManager; this.name = name; @@ -90,15 +88,12 @@ public class BroadcastGroupImpl implements BroadcastGroup, Runnable uniqueID = UUIDGenerator.getInstance().generateStringUUID(); } - public void setNotificationService(final NotificationService notificationService) - { + public void setNotificationService(final NotificationService notificationService) { this.notificationService = notificationService; } - public synchronized void start() throws Exception - { - if (started) - { + public synchronized void start() throws Exception { + if (started) { return; } @@ -106,8 +101,7 @@ public class BroadcastGroupImpl implements BroadcastGroup, Runnable started = true; - if (notificationService != null) - { + if (notificationService != null) { TypedProperties props = new TypedProperties(); props.putSimpleStringProperty(new SimpleString("name"), new SimpleString(name)); Notification notification = new Notification(nodeManager.getNodeId().toString(), CoreNotificationType.BROADCAST_GROUP_STARTED, props); @@ -117,84 +111,65 @@ public class BroadcastGroupImpl implements BroadcastGroup, Runnable activate(); } - public synchronized void stop() - { - if (!started) - { + public synchronized void stop() { + if (!started) { return; } - if (future != null) - { + if (future != null) { future.cancel(false); } - try - { + try { endpoint.close(true); } - catch (Exception e1) - { + catch (Exception e1) { ActiveMQServerLogger.LOGGER.broadcastGroupClosed(e1); } started = false; - if (notificationService != null) - { + if (notificationService != null) { TypedProperties props = new TypedProperties(); props.putSimpleStringProperty(new SimpleString("name"), new SimpleString(name)); Notification notification = new Notification(nodeManager.getNodeId().toString(), CoreNotificationType.BROADCAST_GROUP_STOPPED, props); - try - { + try { notificationService.sendNotification(notification); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.broadcastGroupClosed(e); } } } - public synchronized boolean isStarted() - { + public synchronized boolean isStarted() { return started; } - public String getName() - { + public String getName() { return name; } - public synchronized void addConnector(final TransportConfiguration tcConfig) - { + public synchronized void addConnector(final TransportConfiguration tcConfig) { connectors.add(tcConfig); } - public synchronized void removeConnector(final TransportConfiguration tcConfig) - { + public synchronized void removeConnector(final TransportConfiguration tcConfig) { connectors.remove(tcConfig); } - public synchronized int size() - { + public synchronized int size() { return connectors.size(); } - private synchronized void activate() - { - if (scheduledExecutor != null) - { - future = scheduledExecutor.scheduleWithFixedDelay(this, - 0L, - broadCastPeriod, - TimeUnit.MILLISECONDS); + private synchronized void activate() { + if (scheduledExecutor != null) { + future = scheduledExecutor.scheduleWithFixedDelay(this, 0L, broadCastPeriod, TimeUnit.MILLISECONDS); } } - public synchronized void broadcastConnectors() throws Exception - { + public synchronized void broadcastConnectors() throws Exception { ActiveMQBuffer buff = ActiveMQBuffers.dynamicBuffer(4096); buff.writeString(nodeManager.getNodeId().toString()); @@ -203,8 +178,7 @@ public class BroadcastGroupImpl implements BroadcastGroup, Runnable buff.writeInt(connectors.size()); - for (TransportConfiguration tcConfig : connectors) - { + for (TransportConfiguration tcConfig : connectors) { tcConfig.encode(buff); } @@ -213,28 +187,22 @@ public class BroadcastGroupImpl implements BroadcastGroup, Runnable endpoint.broadcast(data); } - public void run() - { - if (!started) - { + public void run() { + if (!started) { return; } - try - { + try { broadcastConnectors(); loggedBroadcastException = false; } - catch (Exception e) - { + catch (Exception e) { // only log the exception at ERROR level once, even if it fails multiple times in a row - HORNETQ-919 - if (!loggedBroadcastException) - { + if (!loggedBroadcastException) { ActiveMQServerLogger.LOGGER.errorBroadcastingConnectorConfigs(e); loggedBroadcastException = true; } - else - { + else { ActiveMQServerLogger.LOGGER.debug("Failed to broadcast connector configs...again", e); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/ClusterConnectionBridge.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/ClusterConnectionBridge.java index 357c22b0c3..c7e70c084d 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/ClusterConnectionBridge.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/ClusterConnectionBridge.java @@ -55,8 +55,8 @@ import org.apache.activemq.artemis.utils.UUIDGenerator; *

    * Such as such adding extra properties and setting up notifications between the nodes. */ -public class ClusterConnectionBridge extends BridgeImpl -{ +public class ClusterConnectionBridge extends BridgeImpl { + private final ClusterConnection clusterConnection; private final ClusterManager clusterManager; @@ -75,7 +75,8 @@ public class ClusterConnectionBridge extends BridgeImpl private final ServerLocatorInternal discoveryLocator; - public ClusterConnectionBridge(final ClusterConnection clusterConnection, final ClusterManager clusterManager, + public ClusterConnectionBridge(final ClusterConnection clusterConnection, + final ClusterManager clusterManager, final ServerLocatorInternal targetLocator, final ServerLocatorInternal discoveryLocator, final int initialConnectAttempts, @@ -100,27 +101,9 @@ public class ClusterConnectionBridge extends BridgeImpl final SimpleString managementAddress, final SimpleString managementNotificationAddress, final MessageFlowRecord flowRecord, - final TransportConfiguration connector) - { - super(targetLocator, - initialConnectAttempts, - reconnectAttempts, - 0, // reconnectAttemptsOnSameNode means nothing on the clustering bridge since we always try the same - retryInterval, - retryMultiplier, - maxRetryInterval, - nodeUUID, - name, - queue, - executor, - filterString, - forwardingAddress, - scheduledExecutor, - transformer, - useDuplicateDetection, - user, - password, - storageManager); + final TransportConfiguration connector) { + super(targetLocator, initialConnectAttempts, reconnectAttempts, 0, // reconnectAttemptsOnSameNode means nothing on the clustering bridge since we always try the same + retryInterval, retryMultiplier, maxRetryInterval, nodeUUID, name, queue, executor, filterString, forwardingAddress, scheduledExecutor, transformer, useDuplicateDetection, user, password, storageManager); this.discoveryLocator = discoveryLocator; @@ -139,22 +122,18 @@ public class ClusterConnectionBridge extends BridgeImpl // we need to disable DLQ check on the clustered bridges queue.setInternalQueue(true); - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { - ActiveMQServerLogger.LOGGER.trace("Setting up bridge between " + clusterConnection.getConnector() + " and " + targetLocator, - new Exception("trace")); + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { + ActiveMQServerLogger.LOGGER.trace("Setting up bridge between " + clusterConnection.getConnector() + " and " + targetLocator, new Exception("trace")); } } @Override - protected ClientSessionFactoryInternal createSessionFactory() throws Exception - { + protected ClientSessionFactoryInternal createSessionFactory() throws Exception { serverLocator.setProtocolManagerFactory(ActiveMQServerSideProtocolManagerFactory.getInstance()); ClientSessionFactoryInternal factory = (ClientSessionFactoryInternal) serverLocator.createSessionFactory(targetNodeID); setSessionFactory(factory); - if (factory == null) - { + if (factory == null) { return null; } factory.setReconnectAttempts(0); @@ -163,8 +142,7 @@ public class ClusterConnectionBridge extends BridgeImpl } @Override - protected ServerMessage beforeForward(final ServerMessage message) - { + protected ServerMessage beforeForward(final ServerMessage message) { // We make a copy of the message, then we strip out the unwanted routing id headers and leave // only // the one pertinent for the address node - this is important since different queues on different @@ -172,8 +150,7 @@ public class ClusterConnectionBridge extends BridgeImpl // Note we must copy since same message may get routed to other nodes which require different headers ServerMessage messageCopy = message.copy(); - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("Clustered bridge copied message " + message + " as " + messageCopy + " before delivery"); } @@ -183,17 +160,14 @@ public class ClusterConnectionBridge extends BridgeImpl byte[] queueIds = message.getBytesProperty(idsHeaderName); - if (queueIds == null) - { + if (queueIds == null) { // Sanity check only ActiveMQServerLogger.LOGGER.noQueueIdDefined(message, messageCopy, idsHeaderName); throw new IllegalStateException("no queueIDs defined"); } - for (SimpleString propName : propNames) - { - if (propName.startsWith(MessageImpl.HDR_ROUTE_TO_IDS)) - { + for (SimpleString propName : propNames) { + if (propName.startsWith(MessageImpl.HDR_ROUTE_TO_IDS)) { messageCopy.removeProperty(propName); } } @@ -205,35 +179,29 @@ public class ClusterConnectionBridge extends BridgeImpl return messageCopy; } - private void setupNotificationConsumer() throws Exception - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + private void setupNotificationConsumer() throws Exception { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Setting up notificationConsumer between " + this.clusterConnection.getConnector() + - " and " + - flowRecord.getBridge().getForwardingConnection() + - " clusterConnection = " + - this.clusterConnection.getName() + - " on server " + - clusterConnection.getServer()); + " and " + + flowRecord.getBridge().getForwardingConnection() + + " clusterConnection = " + + this.clusterConnection.getName() + + " on server " + + clusterConnection.getServer()); } - if (flowRecord != null) - { + if (flowRecord != null) { flowRecord.reset(); - if (notifConsumer != null) - { - try - { + if (notifConsumer != null) { + try { ActiveMQServerLogger.LOGGER.debug("Closing notification Consumer for reopening " + notifConsumer + - " on bridge " + - this.getName()); + " on bridge " + + this.getName()); notifConsumer.close(); notifConsumer = null; } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { ActiveMQServerLogger.LOGGER.errorClosingConsumer(e); } } @@ -281,20 +249,14 @@ public class ClusterConnectionBridge extends BridgeImpl session.start(); ClientMessage message = session.createMessage(false); - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("Requesting sendQueueInfoToQueue through " + this, new Exception("trace")); } - ManagementHelper.putOperationInvocation(message, - ResourceNames.CORE_SERVER, - "sendQueueInfoToQueue", - notifQueueName.toString(), - flowRecord.getAddress()); + ManagementHelper.putOperationInvocation(message, ResourceNames.CORE_SERVER, "sendQueueInfoToQueue", notifQueueName.toString(), flowRecord.getAddress()); ClientProducer prod = session.createProducer(managementAddress); - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Cluster connetion bridge on " + clusterConnection + " requesting information on queues"); } @@ -305,22 +267,19 @@ public class ClusterConnectionBridge extends BridgeImpl /** * Takes in a string of an address filter or comma separated list and generates an appropriate JMS selector for * filtering queues. + * * @param address */ - public static String createSelectorFromAddress(String address) - { + public static String createSelectorFromAddress(String address) { StringBuilder stringBuilder = new StringBuilder(); // Support standard address (not a list) case. - if (!address.contains(",")) - { - if (address.startsWith("!")) - { + if (!address.contains(",")) { + if (address.startsWith("!")) { stringBuilder.append(ManagementHelper.HDR_ADDRESS + " NOT LIKE '" + address.substring(1, address.length()) + "%'"); } - else - { - stringBuilder.append(ManagementHelper.HDR_ADDRESS + " LIKE '" + address + "%'"); + else { + stringBuilder.append(ManagementHelper.HDR_ADDRESS + " LIKE '" + address + "%'"); } return stringBuilder.toString(); } @@ -329,84 +288,76 @@ public class ClusterConnectionBridge extends BridgeImpl return buildSelectorFromArray(address.split(",")); } - public static String buildSelectorFromArray(String[] list) - { + public static String buildSelectorFromArray(String[] list) { List includes = new ArrayList(); List excludes = new ArrayList(); // Split the list into addresses to match and addresses to exclude. - for (int i = 0; i < list.length; i++) - { - if (list[i].startsWith("!")) - { + for (int i = 0; i < list.length; i++) { + if (list[i].startsWith("!")) { excludes.add(list[i].substring(1, list[i].length())); } - else - { + else { includes.add(list[i]); } } // Build the address matching part of the selector StringBuilder builder = new StringBuilder("("); - if (includes.size() > 0) - { - if (excludes.size() > 0) builder.append("("); - for (int i = 0; i < includes.size(); i++) - { + if (includes.size() > 0) { + if (excludes.size() > 0) + builder.append("("); + for (int i = 0; i < includes.size(); i++) { builder.append("(" + ManagementHelper.HDR_ADDRESS + " LIKE '" + includes.get(i) + "%')"); - if (i < includes.size() - 1) builder.append(" OR "); + if (i < includes.size() - 1) + builder.append(" OR "); } - if (excludes.size() > 0) builder.append(")"); + if (excludes.size() > 0) + builder.append(")"); } // Build the address exclusion part of the selector - if (excludes.size() > 0) - { - if (includes.size() > 0) builder.append(" AND ("); - for (int i = 0; i < excludes.size(); i++) - { + if (excludes.size() > 0) { + if (includes.size() > 0) + builder.append(" AND ("); + for (int i = 0; i < excludes.size(); i++) { builder.append("(" + ManagementHelper.HDR_ADDRESS + " NOT LIKE '" + excludes.get(i) + "%')"); - if (i < excludes.size() - 1) builder.append(" AND "); + if (i < excludes.size() - 1) + builder.append(" AND "); } - if (includes.size() > 0) builder.append(")"); + if (includes.size() > 0) + builder.append(")"); } builder.append(")"); return builder.toString(); } @Override - protected void afterConnect() throws Exception - { + protected void afterConnect() throws Exception { super.afterConnect(); setupNotificationConsumer(); } @Override - protected void tryScheduleRetryReconnect(final ActiveMQExceptionType type) - { + protected void tryScheduleRetryReconnect(final ActiveMQExceptionType type) { scheduleRetryConnect(); } @Override - protected void fail(final boolean permanently) - { + protected void fail(final boolean permanently) { ActiveMQServerLogger.LOGGER.debug("Cluster Bridge " + this.getName() + " failed, permanently=" + permanently); super.fail(permanently); - if (permanently) - { + if (permanently) { ActiveMQServerLogger.LOGGER.debug("cluster node for bridge " + this.getName() + " is permanently down"); clusterConnection.removeRecord(targetNodeID); } - else - { + else { clusterConnection.disconnectRecord(targetNodeID); } } - protected boolean isPlainCoreBridge() - { + protected boolean isPlainCoreBridge() { return false; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/ClusterConnectionImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/ClusterConnectionImpl.java index 7a0d780e0a..c4666b9f58 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/ClusterConnectionImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/ClusterConnectionImpl.java @@ -71,8 +71,8 @@ import org.apache.activemq.artemis.utils.ExecutorFactory; import org.apache.activemq.artemis.utils.FutureLatch; import org.apache.activemq.artemis.utils.TypedProperties; -public final class ClusterConnectionImpl implements ClusterConnection, AfterConnectInternalListener -{ +public final class ClusterConnectionImpl implements ClusterConnection, AfterConnectInternalListener { + private static final boolean isTrace = ActiveMQServerLogger.LOGGER.isTraceEnabled(); private final ExecutorFactory executorFactory; @@ -148,7 +148,6 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn private final int minLargeMessageSize; - // Stuff that used to be on the ClusterManager private final Topology topology; @@ -190,8 +189,7 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn final String clusterPassword, final boolean allowDirectConnectionsOnly, final long clusterNotificationInterval, - final int clusterNotificationAttempts) throws Exception - { + final int clusterNotificationAttempts) throws Exception { this.nodeManager = nodeManager; this.connector = connector; @@ -256,12 +254,10 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn clusterConnector = new StaticClusterConnector(staticTranspConfigs); - if (staticTranspConfigs != null && staticTranspConfigs.length > 0) - { + if (staticTranspConfigs != null && staticTranspConfigs.length > 0) { // a cluster connection will connect to other nodes only if they are directly connected // through a static list of connectors or broadcasting using UDP. - if (allowDirectConnectionsOnly) - { + if (allowDirectConnectionsOnly) { allowableConnections.addAll(Arrays.asList(staticTranspConfigs)); } } @@ -297,8 +293,7 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn final String clusterPassword, final boolean allowDirectConnectionsOnly, final long clusterNotificationInterval, - final int clusterNotificationAttempts) throws Exception - { + final int clusterNotificationAttempts) throws Exception { this.nodeManager = nodeManager; this.connector = connector; @@ -364,12 +359,9 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn this.manager = manager; } - public void start() throws Exception - { - synchronized (this) - { - if (started) - { + public void start() throws Exception { + synchronized (this) { + if (started) { return; } @@ -380,69 +372,53 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn } - public void flushExecutor() - { + public void flushExecutor() { FutureLatch future = new FutureLatch(); executor.execute(future); - if (!future.await(10000)) - { + if (!future.await(10000)) { ActiveMQServerLogger.LOGGER.couldNotFinishExecutor(this.toString()); server.threadDump(); } } - public void stop() throws Exception - { - if (!started) - { + public void stop() throws Exception { + if (!started) { return; } stopping = true; - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug(this + "::stopping ClusterConnection"); } - if (serverLocator != null) - { + if (serverLocator != null) { serverLocator.removeClusterTopologyListener(this); } ActiveMQServerLogger.LOGGER.debug("Cluster connection being stopped for node" + nodeManager.getNodeId() + - ", server = " + - this.server + - " serverLocator = " + - serverLocator); + ", server = " + + this.server + + " serverLocator = " + + serverLocator); - synchronized (this) - { - for (MessageFlowRecord record : records.values()) - { - try - { + synchronized (this) { + for (MessageFlowRecord record : records.values()) { + try { record.close(); } - catch (Exception ignore) - { + catch (Exception ignore) { } } } - if (managementService != null) - { + if (managementService != null) { TypedProperties props = new TypedProperties(); props.putSimpleStringProperty(new SimpleString("name"), name); - Notification notification = new Notification(nodeManager.getNodeId().toString(), - CoreNotificationType.CLUSTER_CONNECTION_STOPPED, - props); + Notification notification = new Notification(nodeManager.getNodeId().toString(), CoreNotificationType.CLUSTER_CONNECTION_STOPPED, props); managementService.sendNotification(notification); } - executor.execute(new Runnable() - { - public void run() - { - synchronized (ClusterConnectionImpl.this) - { + executor.execute(new Runnable() { + public void run() { + synchronized (ClusterConnectionImpl.this) { closeLocator(serverLocator); serverLocator = null; } @@ -456,29 +432,24 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn /** * @param locator */ - private void closeLocator(final ServerLocatorInternal locator) - { + private void closeLocator(final ServerLocatorInternal locator) { if (locator != null) locator.close(); } - private TopologyMember getLocalMember() - { + private TopologyMember getLocalMember() { return topology.getMember(manager.getNodeId()); } - public void addClusterTopologyListener(final ClusterTopologyListener listener) - { + public void addClusterTopologyListener(final ClusterTopologyListener listener) { topology.addClusterTopologyListener(listener); } - public void removeClusterTopologyListener(final ClusterTopologyListener listener) - { + public void removeClusterTopologyListener(final ClusterTopologyListener listener) { topology.removeClusterTopologyListener(listener); } - public Topology getTopology() - { + public Topology getTopology() { return topology; } @@ -487,10 +458,8 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn final String backupGroupName, final String scaleDownGroupName, final Pair connectorPair, - final boolean backup) - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + final boolean backup) { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug(this + "::NodeAnnounced, backup=" + backup + nodeID + connectorPair); } @@ -498,40 +467,28 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn TransportConfiguration backupTC = connectorPair.getB(); TopologyMemberImpl newMember = new TopologyMemberImpl(nodeID, backupGroupName, scaleDownGroupName, live, backupTC); newMember.setUniqueEventID(uniqueEventID); - if (backup) - { + if (backup) { topology.updateBackup(new TopologyMemberImpl(nodeID, backupGroupName, scaleDownGroupName, live, backupTC)); } - else - { + else { topology.updateMember(uniqueEventID, nodeID, newMember); } } @Override - public void onConnection(ClientSessionFactoryInternal sf) - { + public void onConnection(ClientSessionFactoryInternal sf) { TopologyMember localMember = getLocalMember(); - if (localMember != null) - { + if (localMember != null) { ClusterControl clusterControl = manager.getClusterController().connectToNodeInCluster(sf); - try - { + try { clusterControl.authorize(); - clusterControl.sendNodeAnnounce(localMember.getUniqueEventID(), - manager.getNodeId(), - manager.getBackupGroupName(), - manager.getScaleDownGroupName(), - false, - localMember.getLive(), localMember.getBackup()); + clusterControl.sendNodeAnnounce(localMember.getUniqueEventID(), manager.getNodeId(), manager.getBackupGroupName(), manager.getScaleDownGroupName(), false, localMember.getLive(), localMember.getBackup()); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { ActiveMQServerLogger.LOGGER.clusterControlAuthfailure(); } } - else - { + else { ActiveMQServerLogger.LOGGER.noLocalMemborOnClusterConnection(this); } @@ -543,46 +500,36 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn // localMember.getConnector().b); } - public boolean isStarted() - { + public boolean isStarted() { return started; } - public SimpleString getName() - { + public SimpleString getName() { return name; } - public String getNodeID() - { + public String getNodeID() { return nodeManager.getNodeId().toString(); } - public ActiveMQServer getServer() - { + public ActiveMQServer getServer() { return server; } - public boolean isNodeActive(String nodeId) - { + public boolean isNodeActive(String nodeId) { MessageFlowRecord rec = records.get(nodeId); - if (rec == null) - { + if (rec == null) { return false; } return rec.getBridge().isConnected(); } - public Map getNodes() - { - synchronized (recordsGuard) - { + public Map getNodes() { + synchronized (recordsGuard) { Map nodes = new HashMap(); - for (Entry entry : records.entrySet()) - { + for (Entry entry : records.entrySet()) { RemotingConnection fwdConnection = entry.getValue().getBridge().getForwardingConnection(); - if (fwdConnection != null) - { + if (fwdConnection != null) { nodes.put(entry.getKey(), fwdConnection.getRemoteAddress()); } } @@ -590,15 +537,12 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn } } - private synchronized void activate() throws Exception - { - if (!started) - { + private synchronized void activate() throws Exception { + if (!started) { return; } - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Activating cluster connection nodeID=" + nodeManager.getNodeId() + " for server=" + this.server); } @@ -608,18 +552,15 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn serverLocator = clusterConnector.createServerLocator(); - if (serverLocator != null) - { + if (serverLocator != null) { - if (!useDuplicateDetection) - { + if (!useDuplicateDetection) { ActiveMQServerLogger.LOGGER.debug("DuplicateDetection is disabled, sending clustered messages blocked"); } final TopologyMember currentMember = topology.getMember(manager.getNodeId()); - if (currentMember == null) - { + if (currentMember == null) { // sanity check only throw new IllegalStateException("InternalError! The ClusterConnection doesn't know about its own node = " + this); } @@ -641,8 +582,7 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn // No producer flow control on the bridges, as we don't want to lock the queues serverLocator.setProducerWindowSize(-1); - if (retryInterval > 0) - { + if (retryInterval > 0) { this.serverLocator.setRetryInterval(retryInterval); } @@ -653,13 +593,10 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn serverLocator.start(server.getExecutorFactory().getExecutor()); } - if (managementService != null) - { + if (managementService != null) { TypedProperties props = new TypedProperties(); props.putSimpleStringProperty(new SimpleString("name"), name); - Notification notification = new Notification(nodeManager.getNodeId().toString(), - CoreNotificationType.CLUSTER_CONNECTION_STARTED, - props); + Notification notification = new Notification(nodeManager.getNodeId().toString(), CoreNotificationType.CLUSTER_CONNECTION_STARTED, props); ActiveMQServerLogger.LOGGER.debug("sending notification: " + notification); managementService.sendNotification(notification); } @@ -667,15 +604,13 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn addClusterTopologyListener(this); } - public TransportConfiguration getConnector() - { + public TransportConfiguration getConnector() { return connector; } // ClusterTopologyListener implementation ------------------------------------------------------------------ - public void nodeDown(final long eventUID, final String nodeID) - { + public void nodeDown(final long eventUID, final String nodeID) { /* * we dont do anything when a node down is received. The bridges will take care themselves when they should disconnect * and/or clear their bindings. This is to avoid closing a record when we don't want to. @@ -683,65 +618,52 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn } @Override - public void nodeUP(final TopologyMember topologyMember, final boolean last) - { - if (stopping) - { + public void nodeUP(final TopologyMember topologyMember, final boolean last) { + if (stopping) { return; } final String nodeID = topologyMember.getNodeId(); - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { String ClusterTestBase = "receiving nodeUP for nodeID="; ActiveMQServerLogger.LOGGER.debug(this + ClusterTestBase + nodeID + " connectionPair=" + topologyMember); } // discard notifications about ourselves unless its from our backup - if (nodeID.equals(nodeManager.getNodeId().toString())) - { - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + if (nodeID.equals(nodeManager.getNodeId().toString())) { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace(this + "::informing about backup to itself, nodeUUID=" + - nodeManager.getNodeId() + ", connectorPair=" + topologyMember + ", this = " + this); + nodeManager.getNodeId() + ", connectorPair=" + topologyMember + ", this = " + this); } return; } // if the node is more than 1 hop away, we do not create a bridge for direct cluster connection - if (allowDirectConnectionsOnly && !allowableConnections.contains(topologyMember.getLive())) - { + if (allowDirectConnectionsOnly && !allowableConnections.contains(topologyMember.getLive())) { return; } // FIXME required to prevent cluster connections w/o discovery group // and empty static connectors to create bridges... ulgy! - if (serverLocator == null) - { + if (serverLocator == null) { return; } /*we don't create bridges to backups*/ - if (topologyMember.getLive() == null) - { - if (isTrace) - { + if (topologyMember.getLive() == null) { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace(this + " ignoring call with nodeID=" + nodeID + ", topologyMember=" + - topologyMember + ", last=" + last); + topologyMember + ", last=" + last); } return; } - synchronized (recordsGuard) - { - try - { + synchronized (recordsGuard) { + try { MessageFlowRecord record = records.get(nodeID); - if (record == null) - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (record == null) { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug(this + "::Creating record for nodeID=" + nodeID + ", topologyMember=" + - topologyMember); + topologyMember); } // New node - create a new flow record @@ -752,12 +674,10 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn Queue queue; - if (queueBinding != null) - { + if (queueBinding != null) { queue = (Queue) queueBinding.getBindable(); } - else - { + else { // Add binding in storage so the queue will get reloaded on startup and we can find it - it's never // actually routed to at that address though queue = server.createQueue(queueName, queueName, null, true, false); @@ -769,24 +689,20 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn createNewRecord(topologyMember.getUniqueEventID(), nodeID, topologyMember.getLive(), queueName, queue, true); } - else - { - if (isTrace) - { + else { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace(this + " ignored nodeUp record for " + topologyMember + " on nodeID=" + - nodeID + " as the record already existed"); + nodeID + " as the record already existed"); } } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorUpdatingTopology(e); } } } - public synchronized void informClusterOfBackup() - { + public synchronized void informClusterOfBackup() { String nodeID = server.getNodeID().toString(); TopologyMemberImpl localMember = new TopologyMemberImpl(nodeID, null, null, null, connector); @@ -799,19 +715,15 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn final TransportConfiguration connector, final SimpleString queueName, final Queue queue, - final boolean start) throws Exception - { + final boolean start) throws Exception { String nodeId; - synchronized (this) - { - if (!started) - { + synchronized (this) { + if (!started) { return; } - if (serverLocator == null) - { + if (serverLocator == null) { return; } @@ -847,53 +759,19 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn targetLocator.setClusterTransportConfiguration(serverLocator.getClusterTransportConfiguration()); - if (retryInterval > 0) - { + if (retryInterval > 0) { targetLocator.setRetryInterval(retryInterval); } targetLocator.disableFinalizeCheck(); - targetLocator.addIncomingInterceptor(new IncomingInterceptorLookingForExceptionMessage(manager, - executorFactory.getExecutor())); - MessageFlowRecordImpl record = new MessageFlowRecordImpl(targetLocator, - eventUID, - targetNodeID, - connector, - queueName, - queue); + targetLocator.addIncomingInterceptor(new IncomingInterceptorLookingForExceptionMessage(manager, executorFactory.getExecutor())); + MessageFlowRecordImpl record = new MessageFlowRecordImpl(targetLocator, eventUID, targetNodeID, connector, queueName, queue); - ClusterConnectionBridge bridge = new ClusterConnectionBridge(this, - manager, - targetLocator, - serverLocator, - initialConnectAttempts, - reconnectAttempts, - retryInterval, - retryIntervalMultiplier, - maxRetryInterval, - nodeManager.getUUID(), - record.getEventUID(), - record.getTargetNodeID(), - record.getQueueName(), - record.getQueue(), - executorFactory.getExecutor(), - null, - null, - scheduledExecutor, - null, - useDuplicateDetection, - clusterUser, - clusterPassword, - server.getStorageManager(), - managementService.getManagementAddress(), - managementService.getManagementNotificationAddress(), - record, - record.getConnector()); + ClusterConnectionBridge bridge = new ClusterConnectionBridge(this, manager, targetLocator, serverLocator, initialConnectAttempts, reconnectAttempts, retryInterval, retryIntervalMultiplier, maxRetryInterval, nodeManager.getUUID(), record.getEventUID(), record.getTargetNodeID(), record.getQueueName(), record.getQueue(), executorFactory.getExecutor(), null, null, scheduledExecutor, null, useDuplicateDetection, clusterUser, clusterPassword, server.getStorageManager(), managementService.getManagementAddress(), managementService.getManagementNotificationAddress(), record, record.getConnector()); targetLocator.setIdentity("(Cluster-connection-bridge::" + bridge.toString() + "::" + this.toString() + ")"); - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("creating record between " + this.connector + " and " + connector + bridge); } @@ -901,16 +779,15 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn records.put(targetNodeID, record); - if (start) - { + if (start) { bridge.start(); } } // Inner classes ----------------------------------------------------------------------------------- - private class MessageFlowRecordImpl implements MessageFlowRecord - { + private class MessageFlowRecordImpl implements MessageFlowRecord { + private BridgeImpl bridge; private final long eventUID; @@ -938,8 +815,7 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn final String targetNodeID, final TransportConfiguration connector, final SimpleString queueName, - final Queue queue) - { + final Queue queue) { this.targetLocator = targetLocator; this.queue = queue; this.targetNodeID = targetNodeID; @@ -952,8 +828,7 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn * @see java.lang.Object#toString() */ @Override - public String toString() - { + public String toString() { return "MessageFlowRecordImpl [nodeID=" + targetNodeID + ", connector=" + connector + @@ -968,58 +843,50 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn "]"; } - public void serverDisconnected() - { + public void serverDisconnected() { this.disconnected = true; } - public String getAddress() - { + public String getAddress() { return address.toString(); } /** * @return the eventUID */ - public long getEventUID() - { + public long getEventUID() { return eventUID; } /** * @return the nodeID */ - public String getTargetNodeID() - { + public String getTargetNodeID() { return targetNodeID; } /** * @return the connector */ - public TransportConfiguration getConnector() - { + public TransportConfiguration getConnector() { return connector; } /** * @return the queueName */ - public SimpleString getQueueName() - { + public SimpleString getQueueName() { return queueName; } /** * @return the queue */ - public Queue getQueue() - { + public Queue getQueue() { return queue; } - public int getMaxHops() - { + public int getMaxHops() { return maxHops; } @@ -1027,10 +894,8 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn * we should only ever close a record when the node itself has gone down or in the case of scale down where we know * the node is being completely destroyed and in this case we will migrate to another server/Bridge. * */ - public void close() throws Exception - { - if (isTrace) - { + public void close() throws Exception { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Stopping bridge " + bridge); } @@ -1038,143 +903,115 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn clearBindings(); - if (disconnected) - { + if (disconnected) { bridge.disconnect(); } bridge.stop(); - bridge.getExecutor().execute(new Runnable() - { - public void run() - { - try - { - if (disconnected) - { + bridge.getExecutor().execute(new Runnable() { + public void run() { + try { + if (disconnected) { targetLocator.cleanup(); } - else - { + else { targetLocator.close(); } } - catch (Exception ignored) - { + catch (Exception ignored) { ActiveMQServerLogger.LOGGER.debug(ignored.getMessage(), ignored); } } }); } - public boolean isClosed() - { + public boolean isClosed() { return isClosed; } - public void reset() throws Exception - { + public void reset() throws Exception { resetBindings(); } - public void setBridge(final BridgeImpl bridge) - { + public void setBridge(final BridgeImpl bridge) { this.bridge = bridge; } - public Bridge getBridge() - { + public Bridge getBridge() { return bridge; } - public synchronized void onMessage(final ClientMessage message) - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + public synchronized void onMessage(final ClientMessage message) { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("ClusterCommunication::Flow record on " + clusterConnector + " Receiving message " + message); } - try - { + try { // Reset the bindings - if (message.containsProperty(PostOfficeImpl.HDR_RESET_QUEUE_DATA)) - { + if (message.containsProperty(PostOfficeImpl.HDR_RESET_QUEUE_DATA)) { reset = true; return; } - else if (message.containsProperty(PostOfficeImpl.HDR_RESET_QUEUE_DATA_COMPLETE)) - { + else if (message.containsProperty(PostOfficeImpl.HDR_RESET_QUEUE_DATA_COMPLETE)) { clearDisconnectedBindings(); return; } - if (!reset) - { + if (!reset) { ActiveMQServerLogger.LOGGER.debug("Notification being ignored since first reset wasn't received yet: " + message); return; } handleNotificationMessage(message); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorHandlingMessage(e); } } - private void handleNotificationMessage(ClientMessage message) throws Exception - { + private void handleNotificationMessage(ClientMessage message) throws Exception { // TODO - optimised this by just passing int in header - but filter needs to be extended to support IN with // a list of integers SimpleString type = message.getSimpleStringProperty(ManagementHelper.HDR_NOTIFICATION_TYPE); CoreNotificationType ntype = CoreNotificationType.valueOf(type.toString()); - switch (ntype) - { - case BINDING_ADDED: - { + switch (ntype) { + case BINDING_ADDED: { doBindingAdded(message); break; } - case BINDING_REMOVED: - { + case BINDING_REMOVED: { doBindingRemoved(message); break; } - case CONSUMER_CREATED: - { + case CONSUMER_CREATED: { doConsumerCreated(message); break; } - case CONSUMER_CLOSED: - { + case CONSUMER_CLOSED: { doConsumerClosed(message); break; } - case PROPOSAL: - { + case PROPOSAL: { doProposalReceived(message); break; } - case PROPOSAL_RESPONSE: - { + case PROPOSAL_RESPONSE: { doProposalResponseReceived(message); break; } - case UNPROPOSAL: - { + case UNPROPOSAL: { doUnProposalReceived(message); break; } - default: - { + default: { throw ActiveMQMessageBundle.BUNDLE.invalidType(ntype); } } @@ -1183,10 +1020,8 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn /* * Inform the grouping handler of a proposal * */ - private synchronized void doProposalReceived(final ClientMessage message) throws Exception - { - if (!message.containsProperty(ManagementHelper.HDR_PROPOSAL_GROUP_ID)) - { + private synchronized void doProposalReceived(final ClientMessage message) throws Exception { + if (!message.containsProperty(ManagementHelper.HDR_PROPOSAL_GROUP_ID)) { throw new IllegalStateException("proposal type is null"); } @@ -1196,15 +1031,13 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn Integer hops = message.getIntProperty(ManagementHelper.HDR_DISTANCE); - if (server.getGroupingHandler() == null) - { + if (server.getGroupingHandler() == null) { throw new IllegalStateException("grouping handler is null"); } Response response = server.getGroupingHandler().receive(new Proposal(type, val), hops + 1); - if (response != null) - { + if (response != null) { server.getGroupingHandler().sendProposalResponse(response, 0); } } @@ -1212,10 +1045,8 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn /* * Inform the grouping handler of a proposal(groupid) being removed * */ - private synchronized void doUnProposalReceived(final ClientMessage message) throws Exception - { - if (!message.containsProperty(ManagementHelper.HDR_PROPOSAL_GROUP_ID)) - { + private synchronized void doUnProposalReceived(final ClientMessage message) throws Exception { + if (!message.containsProperty(ManagementHelper.HDR_PROPOSAL_GROUP_ID)) { throw new IllegalStateException("proposal type is null"); } @@ -1225,8 +1056,7 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn Integer hops = message.getIntProperty(ManagementHelper.HDR_DISTANCE); - if (server.getGroupingHandler() == null) - { + if (server.getGroupingHandler() == null) { throw new IllegalStateException("grouping handler is null"); } @@ -1238,10 +1068,8 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn * Inform the grouping handler of a response from a proposal * * */ - private synchronized void doProposalResponseReceived(final ClientMessage message) throws Exception - { - if (!message.containsProperty(ManagementHelper.HDR_PROPOSAL_GROUP_ID)) - { + private synchronized void doProposalResponseReceived(final ClientMessage message) throws Exception { + if (!message.containsProperty(ManagementHelper.HDR_PROPOSAL_GROUP_ID)) { throw new IllegalStateException("proposal type is null"); } @@ -1251,8 +1079,7 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn Integer hops = message.getIntProperty(ManagementHelper.HDR_DISTANCE); Response response = new Response(type, val, alt); - if (server.getGroupingHandler() == null) - { + if (server.getGroupingHandler() == null) { throw new IllegalStateException("grouping handler is null while sending response " + response); } @@ -1260,75 +1087,58 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn server.getGroupingHandler().sendProposalResponse(response, hops + 1); } - private synchronized void clearBindings() throws Exception - { + private synchronized void clearBindings() throws Exception { ActiveMQServerLogger.LOGGER.debug(ClusterConnectionImpl.this + " clearing bindings"); - for (RemoteQueueBinding binding : new HashSet(bindings.values())) - { + for (RemoteQueueBinding binding : new HashSet(bindings.values())) { removeBinding(binding.getClusterName()); } } - private synchronized void resetBindings() throws Exception - { + private synchronized void resetBindings() throws Exception { ActiveMQServerLogger.LOGGER.debug(ClusterConnectionImpl.this + " reset bindings"); - for (RemoteQueueBinding binding : new HashSet<>(bindings.values())) - { + for (RemoteQueueBinding binding : new HashSet<>(bindings.values())) { resetBinding(binding.getClusterName()); } } - private synchronized void clearDisconnectedBindings() throws Exception - { + private synchronized void clearDisconnectedBindings() throws Exception { ActiveMQServerLogger.LOGGER.debug(ClusterConnectionImpl.this + " reset bindings"); - for (RemoteQueueBinding binding : new HashSet<>(bindings.values())) - { - if (!binding.isConnected()) - { + for (RemoteQueueBinding binding : new HashSet<>(bindings.values())) { + if (!binding.isConnected()) { removeBinding(binding.getClusterName()); } } } - - public synchronized void disconnectBindings() throws Exception - { + public synchronized void disconnectBindings() throws Exception { ActiveMQServerLogger.LOGGER.debug(ClusterConnectionImpl.this + " disconnect bindings"); reset = false; - for (RemoteQueueBinding binding : new HashSet<>(bindings.values())) - { + for (RemoteQueueBinding binding : new HashSet<>(bindings.values())) { disconnectBinding(binding.getClusterName()); } } - private synchronized void doBindingAdded(final ClientMessage message) throws Exception - { - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + private synchronized void doBindingAdded(final ClientMessage message) throws Exception { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace(ClusterConnectionImpl.this + " Adding binding " + message); } - if (!message.containsProperty(ManagementHelper.HDR_DISTANCE)) - { + if (!message.containsProperty(ManagementHelper.HDR_DISTANCE)) { throw new IllegalStateException("distance is null"); } - if (!message.containsProperty(ManagementHelper.HDR_ADDRESS)) - { + if (!message.containsProperty(ManagementHelper.HDR_ADDRESS)) { throw new IllegalStateException("queueAddress is null"); } - if (!message.containsProperty(ManagementHelper.HDR_CLUSTER_NAME)) - { + if (!message.containsProperty(ManagementHelper.HDR_CLUSTER_NAME)) { throw new IllegalStateException("clusterName is null"); } - if (!message.containsProperty(ManagementHelper.HDR_ROUTING_NAME)) - { + if (!message.containsProperty(ManagementHelper.HDR_ROUTING_NAME)) { throw new IllegalStateException("routingName is null"); } - if (!message.containsProperty(ManagementHelper.HDR_BINDING_ID)) - { + if (!message.containsProperty(ManagementHelper.HDR_BINDING_ID)) { throw new IllegalStateException("queueID is null"); } @@ -1346,10 +1156,8 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn RemoteQueueBinding existingBinding = (RemoteQueueBinding) postOffice.getBinding(clusterName); - if (existingBinding != null) - { - if (!existingBinding.isConnected()) - { + if (existingBinding != null) { + if (!existingBinding.isConnected()) { existingBinding.connect(); return; } @@ -1362,29 +1170,18 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn return; } - RemoteQueueBinding binding = new RemoteQueueBindingImpl(server.getStorageManager().generateID(), - queueAddress, - clusterName, - routingName, - queueID, - filterString, - queue, - bridge.getName(), - distance + 1); + RemoteQueueBinding binding = new RemoteQueueBindingImpl(server.getStorageManager().generateID(), queueAddress, clusterName, routingName, queueID, filterString, queue, bridge.getName(), distance + 1); - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Adding binding " + clusterName + " into " + ClusterConnectionImpl.this); } bindings.put(clusterName, binding); - try - { + try { postOffice.addBinding(binding); } - catch (Exception ignore) - { + catch (Exception ignore) { } Bindings theBindings = postOffice.getBindingsForAddress(queueAddress); @@ -1393,14 +1190,11 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn } - private void doBindingRemoved(final ClientMessage message) throws Exception - { - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + private void doBindingRemoved(final ClientMessage message) throws Exception { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace(ClusterConnectionImpl.this + " Removing binding " + message); } - if (!message.containsProperty(ManagementHelper.HDR_CLUSTER_NAME)) - { + if (!message.containsProperty(ManagementHelper.HDR_CLUSTER_NAME)) { throw new IllegalStateException("clusterName is null"); } @@ -1409,54 +1203,43 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn removeBinding(clusterName); } - private synchronized void removeBinding(final SimpleString clusterName) throws Exception - { + private synchronized void removeBinding(final SimpleString clusterName) throws Exception { RemoteQueueBinding binding = bindings.remove(clusterName); - if (binding == null) - { + if (binding == null) { throw new IllegalStateException("Cannot find binding for queue " + clusterName); } postOffice.removeBinding(binding.getUniqueName(), null); } - private synchronized void resetBinding(final SimpleString clusterName) throws Exception - { + private synchronized void resetBinding(final SimpleString clusterName) throws Exception { RemoteQueueBinding binding = bindings.get(clusterName); - if (binding == null) - { + if (binding == null) { throw new IllegalStateException("Cannot find binding for queue " + clusterName); } binding.reset(); } - - private synchronized void disconnectBinding(final SimpleString clusterName) throws Exception - { + private synchronized void disconnectBinding(final SimpleString clusterName) throws Exception { RemoteQueueBinding binding = bindings.get(clusterName); - if (binding == null) - { + if (binding == null) { throw new IllegalStateException("Cannot find binding for queue " + clusterName); } binding.disconnect(); } - private synchronized void doConsumerCreated(final ClientMessage message) throws Exception - { - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + private synchronized void doConsumerCreated(final ClientMessage message) throws Exception { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace(ClusterConnectionImpl.this + " Consumer created " + message); } - if (!message.containsProperty(ManagementHelper.HDR_DISTANCE)) - { + if (!message.containsProperty(ManagementHelper.HDR_DISTANCE)) { throw new IllegalStateException("distance is null"); } - if (!message.containsProperty(ManagementHelper.HDR_CLUSTER_NAME)) - { + if (!message.containsProperty(ManagementHelper.HDR_CLUSTER_NAME)) { throw new IllegalStateException("clusterName is null"); } @@ -1470,8 +1253,7 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn RemoteQueueBinding binding = bindings.get(clusterName); - if (binding == null) - { + if (binding == null) { throw new IllegalStateException("Cannot find binding for " + clusterName + " on " + ClusterConnectionImpl.this); @@ -1494,8 +1276,7 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn props.putIntProperty(ManagementHelper.HDR_CONSUMER_COUNT, theQueue.getConsumerCount()); - if (filterString != null) - { + if (filterString != null) { props.putSimpleStringProperty(ManagementHelper.HDR_FILTERSTRING, filterString); } @@ -1504,19 +1285,15 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn managementService.sendNotification(notification); } - private synchronized void doConsumerClosed(final ClientMessage message) throws Exception - { - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + private synchronized void doConsumerClosed(final ClientMessage message) throws Exception { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace(ClusterConnectionImpl.this + " Consumer closed " + message); } - if (!message.containsProperty(ManagementHelper.HDR_DISTANCE)) - { + if (!message.containsProperty(ManagementHelper.HDR_DISTANCE)) { throw new IllegalStateException("distance is null"); } - if (!message.containsProperty(ManagementHelper.HDR_CLUSTER_NAME)) - { + if (!message.containsProperty(ManagementHelper.HDR_CLUSTER_NAME)) { throw new IllegalStateException("clusterName is null"); } @@ -1530,8 +1307,7 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn RemoteQueueBinding binding = bindings.get(clusterName); - if (binding == null) - { + if (binding == null) { throw new IllegalStateException("Cannot find binding for " + clusterName); } @@ -1552,8 +1328,7 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn props.putIntProperty(ManagementHelper.HDR_CONSUMER_COUNT, theQueue.getConsumerCount()); - if (filterString != null) - { + if (filterString != null) { props.putSimpleStringProperty(ManagementHelper.HDR_FILTERSTRING, filterString); } Notification notification = new Notification(null, CoreNotificationType.CONSUMER_CLOSED, props); @@ -1564,14 +1339,12 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn } // for testing only - public Map getRecords() - { + public Map getRecords() { return records; } @Override - public String toString() - { + public String toString() { return "ClusterConnectionImpl@" + System.identityHashCode(this) + "[nodeUUID=" + nodeManager.getNodeId() + @@ -1584,16 +1357,14 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn "]"; } - public String describe() - { + public String describe() { StringWriter str = new StringWriter(); PrintWriter out = new PrintWriter(str); out.println(this); out.println("***************************************"); out.println(name + " connected to"); - for (MessageFlowRecord messageFlow : records.values()) - { + for (MessageFlowRecord messageFlow : records.values()) { out.println("\t Bridge = " + messageFlow.getBridge()); out.println("\t Flow Record = " + messageFlow); } @@ -1602,26 +1373,22 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn return str.toString(); } - private interface ClusterConnector - { + private interface ClusterConnector { + ServerLocatorInternal createServerLocator(); } - private final class StaticClusterConnector implements ClusterConnector - { + private final class StaticClusterConnector implements ClusterConnector { + private final TransportConfiguration[] tcConfigs; - public StaticClusterConnector(TransportConfiguration[] tcConfigs) - { + public StaticClusterConnector(TransportConfiguration[] tcConfigs) { this.tcConfigs = tcConfigs; } - public ServerLocatorInternal createServerLocator() - { - if (tcConfigs != null && tcConfigs.length > 0) - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + public ServerLocatorInternal createServerLocator() { + if (tcConfigs != null && tcConfigs.length > 0) { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug(ClusterConnectionImpl.this + "Creating a serverLocator for " + Arrays.toString(tcConfigs)); } ServerLocatorImpl locator = new ServerLocatorImpl(topology, true, tcConfigs); @@ -1632,104 +1399,81 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn } @Override - public String toString() - { + public String toString() { return "StaticClusterConnector [tcConfigs=" + Arrays.toString(tcConfigs) + "]"; } } - private final class DiscoveryClusterConnector implements ClusterConnector - { + private final class DiscoveryClusterConnector implements ClusterConnector { + private final DiscoveryGroupConfiguration dg; - public DiscoveryClusterConnector(DiscoveryGroupConfiguration dg) - { + public DiscoveryClusterConnector(DiscoveryGroupConfiguration dg) { this.dg = dg; } - public ServerLocatorInternal createServerLocator() - { + public ServerLocatorInternal createServerLocator() { return new ServerLocatorImpl(topology, true, dg); } } @Override - public boolean verify(String clusterUser0, String clusterPassword0) - { + public boolean verify(String clusterUser0, String clusterPassword0) { return clusterUser.equals(clusterUser0) && clusterPassword.equals(clusterPassword0); } @Override - public void removeRecord(String targetNodeID) - { + public void removeRecord(String targetNodeID) { ActiveMQServerLogger.LOGGER.debug("Removing record for: " + targetNodeID); MessageFlowRecord record = records.remove(targetNodeID); - try - { + try { record.close(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @Override - public void disconnectRecord(String targetNodeID) - { + public void disconnectRecord(String targetNodeID) { ActiveMQServerLogger.LOGGER.debug("Disconnecting record for: " + targetNodeID); MessageFlowRecord record = records.get(targetNodeID); - try - { - if (record != null) - { + try { + if (record != null) { record.disconnectBindings(); } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } - private final class LiveNotifier implements Runnable - { + private final class LiveNotifier implements Runnable { + int notificationsSent = 0; - @Override - public void run() - { + public void run() { resendLive(); schedule(); } - public void schedule() - { - if (started && !stopping && notificationsSent++ < clusterNotificationAttempts) - { + public void schedule() { + if (started && !stopping && notificationsSent++ < clusterNotificationAttempts) { scheduledExecutor.schedule(this, clusterNotificationInterval, TimeUnit.MILLISECONDS); } } - public void updateAsLive() - { - if (!stopping && started) - { - topology.updateAsLive(manager.getNodeId(), new TopologyMemberImpl(manager.getNodeId(), - manager.getBackupGroupName(), - manager.getScaleDownGroupName(), - connector, - null)); + public void updateAsLive() { + if (!stopping && started) { + topology.updateAsLive(manager.getNodeId(), new TopologyMemberImpl(manager.getNodeId(), manager.getBackupGroupName(), manager.getScaleDownGroupName(), connector, null)); } } - public void resendLive() - { - if (!stopping && started) - { + public void resendLive() { + if (!stopping && started) { topology.resendNode(manager.getNodeId()); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/MessageLoadBalancingType.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/MessageLoadBalancingType.java index 61d06f1e51..9c578cfc91 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/MessageLoadBalancingType.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/MessageLoadBalancingType.java @@ -16,19 +16,16 @@ */ package org.apache.activemq.artemis.core.server.cluster.impl; -public enum MessageLoadBalancingType -{ +public enum MessageLoadBalancingType { OFF("OFF"), STRICT("STRICT"), ON_DEMAND("ON_DEMAND"); private String type; - MessageLoadBalancingType(final String type) - { + MessageLoadBalancingType(final String type) { this.type = type; } - public String getType() - { + public String getType() { return type; } } \ No newline at end of file diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/Redistributor.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/Redistributor.java index 106158cb10..d6abf2206c 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/Redistributor.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/Redistributor.java @@ -37,8 +37,8 @@ import org.apache.activemq.artemis.core.transaction.Transaction; import org.apache.activemq.artemis.core.transaction.impl.TransactionImpl; import org.apache.activemq.artemis.utils.ReusableLatch; -public class Redistributor implements Consumer -{ +public class Redistributor implements Consumer { + private boolean active; private final StorageManager storageManager; @@ -62,8 +62,7 @@ public class Redistributor implements Consumer final StorageManager storageManager, final PostOffice postOffice, final Executor executor, - final int batchSize) - { + final int batchSize) { this.queue = queue; this.storageManager = storageManager; @@ -75,79 +74,64 @@ public class Redistributor implements Consumer this.batchSize = batchSize; } - public Filter getFilter() - { + public Filter getFilter() { return null; } - public String debug() - { + public String debug() { return toString(); } - public String toManagementString() - { + public String toManagementString() { return "Redistributor[" + queue.getName() + "/" + queue.getID() + "]"; } @Override - public void disconnect() - { + public void disconnect() { //noop } - public synchronized void start() - { + public synchronized void start() { active = true; } - public synchronized void stop() throws Exception - { + public synchronized void stop() throws Exception { active = false; boolean ok = flushExecutor(); - if (!ok) - { + if (!ok) { ActiveMQServerLogger.LOGGER.errorStoppingRedistributor(); } } - public synchronized void close() - { + public synchronized void close() { boolean ok = flushExecutor(); - if (!ok) - { + if (!ok) { throw new IllegalStateException("Timed out waiting for executor to complete"); } active = false; } - private boolean flushExecutor() - { - try - { + private boolean flushExecutor() { + try { boolean ok = pendingRuns.await(10000); return ok; } - catch (InterruptedException e) - { + catch (InterruptedException e) { ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e); return false; } } - public synchronized HandleStatus handle(final MessageReference reference) throws Exception - { - if (!active) - { + public synchronized HandleStatus handle(final MessageReference reference) throws Exception { + if (!active) { return HandleStatus.BUSY; } //we shouldn't redistribute with message groups return NO_MATCH so other messages can be delivered - else if (reference.getMessage().getSimpleStringProperty(Message.HDR_GROUP_ID) != null) - { + else if (reference.getMessage().getSimpleStringProperty(Message.HDR_GROUP_ID) != null) { return HandleStatus.NO_MATCH; } @@ -155,36 +139,29 @@ public class Redistributor implements Consumer final Pair routingInfo = postOffice.redistribute(reference.getMessage(), queue, tx); - if (routingInfo == null) - { + if (routingInfo == null) { return HandleStatus.BUSY; } - if (!reference.getMessage().isLargeMessage()) - { + if (!reference.getMessage().isLargeMessage()) { routingInfo.getB().finishCopy(); postOffice.processRoute(routingInfo.getB(), routingInfo.getA(), false); ackRedistribution(reference, tx); } - else - { + else { active = false; - executor.execute(new Runnable() - { - public void run() - { - try - { + executor.execute(new Runnable() { + public void run() { + try { routingInfo.getB().finishCopy(); postOffice.processRoute(routingInfo.getB(), routingInfo.getA(), false); ackRedistribution(reference, tx); - synchronized (Redistributor.this) - { + synchronized (Redistributor.this) { active = true; count++; @@ -192,14 +169,11 @@ public class Redistributor implements Consumer queue.deliverAsync(); } } - catch (Exception e) - { - try - { + catch (Exception e) { + try { tx.rollback(); } - catch (Exception e2) - { + catch (Exception e2) { // Nothing much we can do now // TODO log @@ -213,63 +187,49 @@ public class Redistributor implements Consumer return HandleStatus.HANDLED; } - public void proceedDeliver(MessageReference ref) - { + public void proceedDeliver(MessageReference ref) { // no op } - - private void internalExecute(final Runnable runnable) - { + private void internalExecute(final Runnable runnable) { pendingRuns.countUp(); - executor.execute(new Runnable() - { - public void run() - { - try - { + executor.execute(new Runnable() { + public void run() { + try { runnable.run(); } - finally - { + finally { pendingRuns.countDown(); } } }); } - - private void ackRedistribution(final MessageReference reference, final Transaction tx) throws Exception - { + private void ackRedistribution(final MessageReference reference, final Transaction tx) throws Exception { reference.handled(); queue.acknowledge(tx, reference); tx.commit(); - storageManager.afterCompleteOperations(new IOCallback() - { + storageManager.afterCompleteOperations(new IOCallback() { - public void onError(final int errorCode, final String errorMessage) - { + public void onError(final int errorCode, final String errorMessage) { ActiveMQServerLogger.LOGGER.ioErrorRedistributing(errorCode, errorMessage); } - public void done() - { + public void done() { execPrompter(); } }); } - private void execPrompter() - { + private void execPrompter() { count++; // We use >= as the large message redistribution will set count to max_int // so we are use the prompter will get called - if (count >= batchSize) - { + if (count >= batchSize) { // We continue the next batch on a different thread, so as not to keep the delivery thread busy for a very // long time in the case there are many messages in the queue active = false; @@ -281,12 +241,10 @@ public class Redistributor implements Consumer } - private class Prompter implements Runnable - { - public void run() - { - synchronized (Redistributor.this) - { + private class Prompter implements Runnable { + + public void run() { + synchronized (Redistributor.this) { active = true; queue.deliverAsync(); @@ -298,8 +256,7 @@ public class Redistributor implements Consumer * @see org.apache.activemq.artemis.core.server.Consumer#getDeliveringMessages() */ @Override - public List getDeliveringMessages() - { + public List getDeliveringMessages() { return Collections.emptyList(); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/RemoteQueueBindingImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/RemoteQueueBindingImpl.java index b0af90eb02..0a0030f133 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/RemoteQueueBindingImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/RemoteQueueBindingImpl.java @@ -35,8 +35,8 @@ import org.apache.activemq.artemis.core.server.RoutingContext; import org.apache.activemq.artemis.core.server.ServerMessage; import org.apache.activemq.artemis.core.server.cluster.RemoteQueueBinding; -public class RemoteQueueBindingImpl implements RemoteQueueBinding -{ +public class RemoteQueueBindingImpl implements RemoteQueueBinding { + private final SimpleString address; private final Queue storeAndForwardQueue; @@ -71,8 +71,7 @@ public class RemoteQueueBindingImpl implements RemoteQueueBinding final SimpleString filterString, final Queue storeAndForwardQueue, final SimpleString bridgeName, - final int distance) throws Exception - { + final int distance) throws Exception { this.id = id; this.address = address; @@ -92,78 +91,61 @@ public class RemoteQueueBindingImpl implements RemoteQueueBinding this.distance = distance; } - public long getID() - { + public long getID() { return id; } - public SimpleString getAddress() - { + public SimpleString getAddress() { return address; } - public Bindable getBindable() - { + public Bindable getBindable() { return storeAndForwardQueue; } - public Queue getQueue() - { + public Queue getQueue() { return storeAndForwardQueue; } - public SimpleString getRoutingName() - { + public SimpleString getRoutingName() { return routingName; } - public SimpleString getUniqueName() - { + public SimpleString getUniqueName() { return uniqueName; } - public SimpleString getClusterName() - { + public SimpleString getClusterName() { return uniqueName; } - public boolean isExclusive() - { + public boolean isExclusive() { return false; } - public BindingType getType() - { + public BindingType getType() { return BindingType.REMOTE_QUEUE; } - public Filter getFilter() - { + public Filter getFilter() { return queueFilter; } - public int getDistance() - { + public int getDistance() { return distance; } - public synchronized boolean isHighAcceptPriority(final ServerMessage message) - { - if (consumerCount == 0) - { + public synchronized boolean isHighAcceptPriority(final ServerMessage message) { + if (consumerCount == 0) { return false; } - if (filters.isEmpty()) - { + if (filters.isEmpty()) { return true; } - else - { - for (Filter filter : filters) - { - if (filter.match(message)) - { + else { + for (Filter filter : filters) { + if (filter.match(message)) { return true; } } @@ -172,20 +154,16 @@ public class RemoteQueueBindingImpl implements RemoteQueueBinding return false; } - @Override - public void unproposed(SimpleString groupID) - { + public void unproposed(SimpleString groupID) { } - public void route(final ServerMessage message, final RoutingContext context) - { + public void route(final ServerMessage message, final RoutingContext context) { addRouteContextToMessage(message); List durableQueuesOnContext = context.getDurableQueues(storeAndForwardQueue.getAddress()); - if (!durableQueuesOnContext.contains(storeAndForwardQueue)) - { + if (!durableQueuesOnContext.contains(storeAndForwardQueue)) { // There can be many remote bindings for the same node, we only want to add the message once to // the s & f queue for that node context.addQueue(storeAndForwardQueue.getAddress(), storeAndForwardQueue); @@ -193,37 +171,31 @@ public class RemoteQueueBindingImpl implements RemoteQueueBinding } @Override - public void routeWithAck(ServerMessage message, RoutingContext context) - { + public void routeWithAck(ServerMessage message, RoutingContext context) { addRouteContextToMessage(message); List durableQueuesOnContext = context.getDurableQueues(storeAndForwardQueue.getAddress()); - if (!durableQueuesOnContext.contains(storeAndForwardQueue)) - { + if (!durableQueuesOnContext.contains(storeAndForwardQueue)) { // There can be many remote bindings for the same node, we only want to add the message once to // the s & f queue for that node context.addQueueWithAck(storeAndForwardQueue.getAddress(), storeAndForwardQueue); } } - public synchronized void addConsumer(final SimpleString filterString) throws Exception - { - if (filterString != null) - { + public synchronized void addConsumer(final SimpleString filterString) throws Exception { + if (filterString != null) { // There can actually be many consumers on the same queue with the same filter, so we need to maintain a ref // count Integer i = filterCounts.get(filterString); - if (i == null) - { + if (i == null) { filterCounts.put(filterString, 1); filters.add(FilterImpl.createFilter(filterString)); } - else - { + else { filterCounts.put(filterString, i + 1); } } @@ -231,24 +203,19 @@ public class RemoteQueueBindingImpl implements RemoteQueueBinding consumerCount++; } - public synchronized void removeConsumer(final SimpleString filterString) throws Exception - { - if (filterString != null) - { + public synchronized void removeConsumer(final SimpleString filterString) throws Exception { + if (filterString != null) { Integer i = filterCounts.get(filterString); - if (i != null) - { + if (i != null) { int ii = i - 1; - if (ii == 0) - { + if (ii == 0) { filterCounts.remove(filterString); filters.remove(FilterImpl.createFilter(filterString)); } - else - { + else { filterCounts.put(filterString, ii); } } @@ -258,50 +225,45 @@ public class RemoteQueueBindingImpl implements RemoteQueueBinding } @Override - public void reset() - { + public void reset() { consumerCount = 0; filterCounts.clear(); filters.clear(); } - public synchronized int consumerCount() - { + public synchronized int consumerCount() { return consumerCount; } @Override - public String toString() - { + public String toString() { return "RemoteQueueBindingImpl(" + - (connected ? "connected" : "disconnected") - + ")[address=" + address + - ", consumerCount=" + - consumerCount + - ", distance=" + - distance + - ", filters=" + - filters + - ", id=" + - id + - ", idsHeaderName=" + - idsHeaderName + - ", queueFilter=" + - queueFilter + - ", remoteQueueID=" + - remoteQueueID + - ", routingName=" + - routingName + - ", storeAndForwardQueue=" + - storeAndForwardQueue + - ", uniqueName=" + - uniqueName + - "]"; + (connected ? "connected" : "disconnected") + ")[address=" + address + + ", consumerCount=" + + consumerCount + + ", distance=" + + distance + + ", filters=" + + filters + + ", id=" + + id + + ", idsHeaderName=" + + idsHeaderName + + ", queueFilter=" + + queueFilter + + ", remoteQueueID=" + + remoteQueueID + + ", routingName=" + + routingName + + ", storeAndForwardQueue=" + + storeAndForwardQueue + + ", uniqueName=" + + uniqueName + + "]"; } @Override - public String toManagementString() - { + public String toManagementString() { return "RemoteQueueBindingImpl [address=" + address + ", storeAndForwardQueue=" + storeAndForwardQueue.getName() + ", remoteQueueID=" + @@ -309,49 +271,41 @@ public class RemoteQueueBindingImpl implements RemoteQueueBinding } @Override - public void disconnect() - { + public void disconnect() { connected = false; } @Override - public boolean isConnected() - { + public boolean isConnected() { return connected; } @Override - public void connect() - { + public void connect() { connected = true; } - - public Set getFilters() - { + public Set getFilters() { return filters; } - public void close() throws Exception - { + public void close() throws Exception { storeAndForwardQueue.close(); } /** * This will add routing information to the message. * This will be later processed during the delivery between the nodes. Because of that this has to be persisted as a property on the message. + * * @param message */ - private void addRouteContextToMessage(final ServerMessage message) - { + private void addRouteContextToMessage(final ServerMessage message) { byte[] ids = message.getBytesProperty(idsHeaderName); - if (ids == null) - { + if (ids == null) { ids = new byte[8]; } - else - { + else { byte[] newIds = new byte[ids.length + 8]; System.arraycopy(ids, 0, newIds, 8, ids.length); @@ -365,14 +319,12 @@ public class RemoteQueueBindingImpl implements RemoteQueueBinding message.putBytesProperty(idsHeaderName, ids); - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("Adding remoteQueue ID = " + remoteQueueID + " into message=" + message + " store-forward-queue=" + storeAndForwardQueue); } } - public long getRemoteQueueID() - { - return remoteQueueID; + public long getRemoteQueueID() { + return remoteQueueID; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/BooleanVote.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/BooleanVote.java index da1b6d1cd2..553f4ce781 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/BooleanVote.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/BooleanVote.java @@ -23,41 +23,35 @@ import java.util.Map; /** * a simple yes.no vote */ -public final class BooleanVote extends Vote -{ +public final class BooleanVote extends Vote { + private boolean vote; - public BooleanVote(boolean vote) - { + public BooleanVote(boolean vote) { this.vote = vote; } @Override - public boolean isRequestServerVote() - { + public boolean isRequestServerVote() { return false; } - public Boolean getVote() - { + public Boolean getVote() { return vote; } @Override - public Map getVoteMap() - { + public Map getVoteMap() { return null; } @Override - public void encode(ActiveMQBuffer buff) - { + public void encode(ActiveMQBuffer buff) { buff.writeBoolean(vote); } @Override - public void decode(ActiveMQBuffer buff) - { + public void decode(ActiveMQBuffer buff) { vote = buff.readBoolean(); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/Quorum.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/Quorum.java index b57418443d..d3db6e70c4 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/Quorum.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/Quorum.java @@ -21,27 +21,27 @@ import org.apache.activemq.artemis.core.client.impl.Topology; /** * A quorum can be registered with the {@link QuorumManager} to receive notifications about the state of a cluster. * It can then use the {@link QuorumManager} for the quorum within a cluster to vote on a specific outcome. - * */ -public interface Quorum -{ + */ +public interface Quorum { + /** - * the name of the Quorum. this should be unique and is used to locate the correct quorum to use for voting - * */ + * the name of the Quorum. this should be unique and is used to locate the correct quorum to use for voting + */ String getName(); /** - * called by the quorum manager when a quorum is registered - * */ + * called by the quorum manager when a quorum is registered + */ void setQuorumManager(QuorumManager quorumManager); /** - * called by the quorum when a node in the quorum goes down - * */ + * called by the quorum when a node in the quorum goes down + */ void nodeDown(Topology topology, long eventUID, String nodeID); - /** - * called by the quorum when a node in the quorum goes up - * */ + /** + * called by the quorum when a node in the quorum goes up + */ void nodeUp(Topology topology); /** diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/QuorumManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/QuorumManager.java index 3cb048dfe2..d510b41e0a 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/QuorumManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/QuorumManager.java @@ -21,6 +21,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; + import org.apache.activemq.artemis.api.core.Pair; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.TransportConfiguration; @@ -36,8 +37,8 @@ import org.apache.activemq.artemis.core.server.cluster.ClusterController; * about changes to the cluster. A {@link org.apache.activemq.artemis.core.server.cluster.qourum.Quorum} can then issue a vote to the * remaining nodes in a cluster for a specific outcome */ -public final class QuorumManager implements ClusterTopologyListener, ActiveMQComponent -{ +public final class QuorumManager implements ClusterTopologyListener, ActiveMQComponent { + private final ExecutorService executor; private final ClusterController clusterController; @@ -61,19 +62,18 @@ public final class QuorumManager implements ClusterTopologyListener, ActiveMQCom */ private int maxClusterSize = 0; - public QuorumManager(ExecutorService threadPool, ClusterController clusterController) - { + public QuorumManager(ExecutorService threadPool, ClusterController clusterController) { this.clusterController = clusterController; this.executor = threadPool; } /** * we start by simply creating the server locator and connecting in a separate thread + * * @throws Exception */ @Override - public void start() throws Exception - { + public void start() throws Exception { if (started) return; started = true; @@ -81,57 +81,53 @@ public final class QuorumManager implements ClusterTopologyListener, ActiveMQCom /** * stops the server locator + * * @throws Exception */ @Override - public void stop() throws Exception - { + public void stop() throws Exception { if (!started) return; - synchronized (voteRunnables) - { + synchronized (voteRunnables) { started = false; - for (VoteRunnableHolder voteRunnableHolder : voteRunnables.values()) - { - for (VoteRunnable runnable : voteRunnableHolder.runnables) - { + for (VoteRunnableHolder voteRunnableHolder : voteRunnables.values()) { + for (VoteRunnable runnable : voteRunnableHolder.runnables) { runnable.close(); } } } quorums.clear(); - for (Quorum quorum : quorums.values()) - { + for (Quorum quorum : quorums.values()) { quorum.close(); } } /** * are we started + * * @return */ @Override - public boolean isStarted() - { + public boolean isStarted() { return started; } /** * registers a {@link org.apache.activemq.artemis.core.server.cluster.qourum.Quorum} so that it can be notified of changes in the cluster. + * * @param quorum */ - public void registerQuorum(Quorum quorum) - { + public void registerQuorum(Quorum quorum) { quorums.put(quorum.getName(), quorum); quorum.setQuorumManager(this); } /** * unregisters a {@link org.apache.activemq.artemis.core.server.cluster.qourum.Quorum}. + * * @param quorum */ - public void unRegisterQuorum(Quorum quorum) - { + public void unRegisterQuorum(Quorum quorum) { quorums.remove(quorum.getName()); } @@ -140,40 +136,37 @@ public final class QuorumManager implements ClusterTopologyListener, ActiveMQCom * {@code maxClusterSize} if needed and inform the {@link org.apache.activemq.artemis.core.server.cluster.qourum.Quorum}'s. * * @param topologyMember the topolgy changed - * @param last if the whole cluster topology is being transmitted (after adding the listener to - * the cluster connection) this parameter will be {@code true} for the last topology + * @param last if the whole cluster topology is being transmitted (after adding the listener to + * the cluster connection) this parameter will be {@code true} for the last topology */ @Override - public void nodeUP(TopologyMember topologyMember, boolean last) - { + public void nodeUP(TopologyMember topologyMember, boolean last) { final int newClusterSize = clusterController.getDefaultClusterSize(); maxClusterSize = newClusterSize > maxClusterSize ? newClusterSize : maxClusterSize; - for (Quorum quorum : quorums.values()) - { + for (Quorum quorum : quorums.values()) { quorum.nodeUp(clusterController.getDefaultClusterTopology()); } } /** * notify the {@link org.apache.activemq.artemis.core.server.cluster.qourum.Quorum} of a topology change. + * * @param eventUID - * @param nodeID the id of the node leaving the cluster + * @param nodeID the id of the node leaving the cluster */ @Override - public void nodeDown(long eventUID, String nodeID) - { - for (Quorum quorum : quorums.values()) - { + public void nodeDown(long eventUID, String nodeID) { + for (Quorum quorum : quorums.values()) { quorum.nodeDown(clusterController.getDefaultClusterTopology(), eventUID, nodeID); } } /** * returns the maximum size this cluster has been. + * * @return max size */ - public int getMaxClusterSize() - { + public int getMaxClusterSize() { return maxClusterSize; } @@ -182,19 +175,15 @@ public final class QuorumManager implements ClusterTopologyListener, ActiveMQCom * * @param quorumVote the vote to acquire */ - public void vote(final QuorumVote quorumVote) - { + public void vote(final QuorumVote quorumVote) { List runnables = new ArrayList<>(); - synchronized (voteRunnables) - { + synchronized (voteRunnables) { if (!started) return; //send a vote to each node - for (TopologyMemberImpl tm : clusterController.getDefaultClusterTopology().getMembers()) - { + for (TopologyMemberImpl tm : clusterController.getDefaultClusterTopology().getMembers()) { //but not ourselves - if (!tm.getNodeId().equals(clusterController.getNodeID().toString())) - { + if (!tm.getNodeId().equals(clusterController.getNodeID().toString())) { Pair pair = tm.getConnector(); final TransportConfiguration serverTC = pair.getA(); @@ -204,17 +193,14 @@ public final class QuorumManager implements ClusterTopologyListener, ActiveMQCom runnables.add(voteRunnable); } } - if (runnables.size() > 0) - { + if (runnables.size() > 0) { voteRunnables.put(quorumVote, new VoteRunnableHolder(quorumVote, runnables, runnables.size())); - for (VoteRunnable runnable : runnables) - { + for (VoteRunnable runnable : runnables) { executor.submit(runnable); } } - else - { + else { quorumVote.allVotesCast(clusterController.getDefaultClusterTopology()); } } @@ -224,11 +210,10 @@ public final class QuorumManager implements ClusterTopologyListener, ActiveMQCom * handle a vote received on the quorum * * @param handler the name of the handler to use for the vote - * @param vote the vote + * @param vote the vote * @return the updated vote */ - public Vote vote(SimpleString handler, Vote vote) - { + public Vote vote(SimpleString handler, Vote vote) { QuorumVoteHandler quorumVoteHandler = handlers.get(handler); return quorumVoteHandler.vote(vote); } @@ -239,13 +224,10 @@ public final class QuorumManager implements ClusterTopologyListener, ActiveMQCom * * @param quorumVote the vote */ - public void voteComplete(QuorumVoteServerConnect quorumVote) - { + public void voteComplete(QuorumVoteServerConnect quorumVote) { VoteRunnableHolder holder = voteRunnables.remove(quorumVote); - if (holder != null) - { - for (VoteRunnable runnable : holder.runnables) - { + if (holder != null) { + for (VoteRunnable runnable : holder.runnables) { runnable.close(); } } @@ -253,68 +235,61 @@ public final class QuorumManager implements ClusterTopologyListener, ActiveMQCom /** * called to register vote handlers on the quorum + * * @param quorumVoteHandler the vote handler */ - public void registerQuorumHandler(QuorumVoteHandler quorumVoteHandler) - { + public void registerQuorumHandler(QuorumVoteHandler quorumVoteHandler) { handlers.put(quorumVoteHandler.getQuorumName(), quorumVoteHandler); } @Override - public String toString() - { + public String toString() { return QuorumManager.class.getSimpleName() + "(server=" + clusterController.getIdentity() + ")"; } - public QuorumVoteHandler getVoteHandler(SimpleString handler) - { + public QuorumVoteHandler getVoteHandler(SimpleString handler) { return handlers.get(handler); } - private final class VoteRunnableHolder - { + private final class VoteRunnableHolder { + private QuorumVote quorumVote; private final List runnables; private int size; - public VoteRunnableHolder(QuorumVote quorumVote, List runnables, int size) - { + public VoteRunnableHolder(QuorumVote quorumVote, List runnables, int size) { this.quorumVote = quorumVote; this.runnables = runnables; this.size = size; } - public synchronized void voteComplete() - { + public synchronized void voteComplete() { size--; - if (size <= 0) - { + if (size <= 0) { quorumVote.allVotesCast(clusterController.getDefaultClusterTopology()); } } } + /** * this will connect to a node and then cast a vote. whether or not this vote is asked of the target node is dependent * on {@link org.apache.activemq.artemis.core.server.cluster.qourum.Vote#isRequestServerVote()} */ - private final class VoteRunnable implements Runnable - { + private final class VoteRunnable implements Runnable { + private final TransportConfiguration serverTC; private final QuorumVote quorumVote; private ClusterControl clusterControl; - public VoteRunnable(TransportConfiguration serverTC, QuorumVote quorumVote) - { + public VoteRunnable(TransportConfiguration serverTC, QuorumVote quorumVote) { this.serverTC = serverTC; this.quorumVote = quorumVote; } @Override - public void run() - { - try - { + public void run() { + try { Vote vote; if (!started) return; @@ -324,52 +299,41 @@ public final class QuorumManager implements ClusterTopologyListener, ActiveMQCom //if we are successful get the vote and check whether we need to send it to the target server, //just connecting may be enough vote = quorumVote.connected(); - if (vote.isRequestServerVote()) - { + if (vote.isRequestServerVote()) { vote = clusterControl.sendQuorumVote(quorumVote.getName(), vote); quorumVote.vote(vote); } - else - { + else { quorumVote.vote(vote); } } - catch (Exception e) - { + catch (Exception e) { Vote vote = quorumVote.notConnected(); quorumVote.vote(vote); } - finally - { - try - { - if (clusterControl != null) - { + finally { + try { + if (clusterControl != null) { clusterControl.close(); } } - catch (Exception e) - { + catch (Exception e) { //ignore } QuorumManager.this.votingComplete(quorumVote); } } - public void close() - { - if (clusterControl != null) - { + public void close() { + if (clusterControl != null) { clusterControl.close(); } } } - private void votingComplete(QuorumVote quorumVote) - { + private void votingComplete(QuorumVote quorumVote) { VoteRunnableHolder voteRunnableHolder = voteRunnables.get(quorumVote); - if (voteRunnableHolder != null) - { + if (voteRunnableHolder != null) { voteRunnableHolder.voteComplete(); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/QuorumVote.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/QuorumVote.java index 7ad4aa510d..896c9ac88f 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/QuorumVote.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/QuorumVote.java @@ -22,12 +22,11 @@ import org.apache.activemq.artemis.core.client.impl.Topology; /** * the vote itself. the vote can be decided by the enquirer or sent out to each node in the quorum. */ -public abstract class QuorumVote -{ +public abstract class QuorumVote { + private SimpleString name; - public QuorumVote(SimpleString name) - { + public QuorumVote(SimpleString name) { this.name = name; } @@ -43,6 +42,7 @@ public abstract class QuorumVote * called by the {@link org.apache.activemq.artemis.core.server.cluster.qourum.QuorumManager} fails to connect to a node in the quorum. * The QuorumVote can then decide whether or not a decision can be made with just that information however the node * cannot cannot be asked. + * * @return the vote to use */ public abstract Vote notConnected(); @@ -74,8 +74,7 @@ public abstract class QuorumVote * * @return the name of the wuorum vote */ - public SimpleString getName() - { + public SimpleString getName() { return name; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/QuorumVoteHandler.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/QuorumVoteHandler.java index d4604ce7ae..3bac81f3a3 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/QuorumVoteHandler.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/QuorumVoteHandler.java @@ -22,8 +22,8 @@ import org.apache.activemq.artemis.api.core.SimpleString; /** * used to handle votes received by a quorum from a particular node */ -public interface QuorumVoteHandler -{ +public interface QuorumVoteHandler { + /** * @param vote * @return diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/QuorumVoteServerConnect.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/QuorumVoteServerConnect.java index 0793d117f7..79e41ee384 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/QuorumVoteServerConnect.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/QuorumVoteServerConnect.java @@ -26,8 +26,8 @@ import java.util.concurrent.TimeUnit; /** * A Qourum Vote for deciding if a replicated backup should become live. */ -public class QuorumVoteServerConnect extends QuorumVote -{ +public class QuorumVoteServerConnect extends QuorumVote { + private static final SimpleString LIVE_FAILOVER_VOTE = new SimpleString("LIVE_FAILOVER)VOTE"); private final CountDownLatch latch; @@ -45,26 +45,22 @@ public class QuorumVoteServerConnect extends QuorumVote * 4 remaining nodes would be 3/2 = 2 vote needed * 5 remaining nodes would be 4/2 = 3 vote needed * 6 remaining nodes would be 5/2 = 3 vote needed - * */ - public QuorumVoteServerConnect(int size, StorageManager storageManager) - { + */ + public QuorumVoteServerConnect(int size, StorageManager storageManager) { super(LIVE_FAILOVER_VOTE); //we don't count ourself int actualSize = size - 1; - if (actualSize <= 2) - { + if (actualSize <= 2) { votesNeeded = actualSize / 2; } - else - { + else { //even votesNeeded = actualSize / 2 + 1; } //votes needed could be say 2.5 so we add 1 in this case int latchSize = votesNeeded > (int) votesNeeded ? (int) votesNeeded + 1 : (int) votesNeeded; latch = new CountDownLatch(latchSize); - if (votesNeeded == 0) - { + if (votesNeeded == 0) { decision = true; } } @@ -75,18 +71,17 @@ public class QuorumVoteServerConnect extends QuorumVote * @return */ @Override - public Vote connected() - { + public Vote connected() { return new BooleanVote(true); } /** * if we cant connect to the node + * * @return */ @Override - public Vote notConnected() - { + public Vote notConnected() { return new BooleanVote(false); } @@ -98,18 +93,16 @@ public class QuorumVoteServerConnect extends QuorumVote * 4 remaining nodes would be 3/2 = 2 vote needed * 5 remaining nodes would be 4/2 = 3 vote needed * 6 remaining nodes would be 5/2 = 3 vote needed + * * @param vote the vote to make. */ @Override - public synchronized void vote(BooleanVote vote) - { + public synchronized void vote(BooleanVote vote) { if (decision) return; - if (vote.getVote()) - { + if (vote.getVote()) { total++; - if (total >= votesNeeded) - { + if (total >= votesNeeded) { decision = true; latch.countDown(); } @@ -117,25 +110,21 @@ public class QuorumVoteServerConnect extends QuorumVote } @Override - public void allVotesCast(Topology voteTopology) - { + public void allVotesCast(Topology voteTopology) { } @Override - public Boolean getDecision() - { + public Boolean getDecision() { return decision; } @Override - public SimpleString getName() - { + public SimpleString getName() { return null; } - public void await(int latchTimeout, TimeUnit unit) throws InterruptedException - { + public void await(int latchTimeout, TimeUnit unit) throws InterruptedException { latch.await(latchTimeout, unit); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/SharedNothingBackupQuorum.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/SharedNothingBackupQuorum.java index 716e51f3a1..c1bf6a860f 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/SharedNothingBackupQuorum.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/SharedNothingBackupQuorum.java @@ -31,11 +31,9 @@ import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.Replicatio import org.apache.activemq.artemis.core.server.ActiveMQServerLogger; import org.apache.activemq.artemis.core.server.NodeManager; -public class SharedNothingBackupQuorum implements Quorum, SessionFailureListener -{ +public class SharedNothingBackupQuorum implements Quorum, SessionFailureListener { - public enum BACKUP_ACTIVATION - { + public enum BACKUP_ACTIVATION { FAIL_OVER, FAILURE_REPLICATING, ALREADY_REPLICATING, STOP; } @@ -63,8 +61,9 @@ public class SharedNothingBackupQuorum implements Quorum, SessionFailureListener */ public static final int WAIT_TIME_AFTER_FIRST_LIVE_STOPPING_MSG = 60; - public SharedNothingBackupQuorum(StorageManager storageManager, NodeManager nodeManager, ScheduledExecutorService scheduledPool) - { + public SharedNothingBackupQuorum(StorageManager storageManager, + NodeManager nodeManager, + ScheduledExecutorService scheduledPool) { this.storageManager = storageManager; this.scheduledPool = scheduledPool; this.latch = new CountDownLatch(1); @@ -83,30 +82,23 @@ public class SharedNothingBackupQuorum implements Quorum, SessionFailureListener private final Object decisionGuard = new Object(); @Override - public String getName() - { + public String getName() { return "SharedNothingBackupQuorum"; } - public void decideOnAction(Topology topology) - { + public void decideOnAction(Topology topology) { //we may get called via multiple paths so need to guard - synchronized (decisionGuard) - { - if (signal == BACKUP_ACTIVATION.FAIL_OVER) - { + synchronized (decisionGuard) { + if (signal == BACKUP_ACTIVATION.FAIL_OVER) { return; } - if (!isLiveDown()) - { - try - { + if (!isLiveDown()) { + try { // no point in repeating all the reconnection logic sessionFactory.connect(RECONNECT_ATTEMPTS, false); return; } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { if (e.getType() != ActiveMQExceptionType.NOT_CONNECTED) ActiveMQServerLogger.LOGGER.errorReConnecting(e); } @@ -117,17 +109,15 @@ public class SharedNothingBackupQuorum implements Quorum, SessionFailureListener latch.countDown(); } - public void liveIDSet(String liveID) - { + public void liveIDSet(String liveID) { targetServerID = liveID; nodeManager.setNodeID(liveID); //now we are replicating we can start waiting for disconnect notifications so we can fail over - // sessionFactory.addFailureListener(this); + // sessionFactory.addFailureListener(this); } @Override - public void setQuorumManager(QuorumManager quorumManager) - { + public void setQuorumManager(QuorumManager quorumManager) { this.quorumManager = quorumManager; } @@ -139,17 +129,14 @@ public class SharedNothingBackupQuorum implements Quorum, SessionFailureListener * @param nodeID */ @Override - public void nodeDown(Topology topology, long eventUID, String nodeID) - { - if (targetServerID.equals(nodeID)) - { + public void nodeDown(Topology topology, long eventUID, String nodeID) { + if (targetServerID.equals(nodeID)) { decideOnAction(topology); } } @Override - public void nodeUp(Topology topology) - { + public void nodeUp(Topology topology) { //noop } @@ -157,38 +144,31 @@ public class SharedNothingBackupQuorum implements Quorum, SessionFailureListener * if the connection to our replicated live goes down then decide on an action */ @Override - public void connectionFailed(ActiveMQException exception, boolean failedOver) - { + public void connectionFailed(ActiveMQException exception, boolean failedOver) { decideOnAction(sessionFactory.getServerLocator().getTopology()); } @Override - public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) { connectionFailed(me, failedOver); } - @Override - public void beforeReconnect(ActiveMQException exception) - { + public void beforeReconnect(ActiveMQException exception) { //noop } @Override - public void close() - { + public void close() { causeExit(BACKUP_ACTIVATION.STOP); } - /** * @param sessionFactory the session factory used to connect to the live server */ - public void setSessionFactory(final ClientSessionFactoryInternal sessionFactory) - { + public void setSessionFactory(final ClientSessionFactoryInternal sessionFactory) { this.sessionFactory = sessionFactory; - this.connection = (CoreRemotingConnection)sessionFactory.getConnection(); + this.connection = (CoreRemotingConnection) sessionFactory.getConnection(); connection.addFailureListener(this); //belts and braces, there are circumstances where the connection listener doesn't get called but the session does. sessionFactory.addFailureListener(this); @@ -200,22 +180,17 @@ public class SharedNothingBackupQuorum implements Quorum, SessionFailureListener * The use case is for when the 'live' has an orderly shutdown, in which case it informs the * backup that it should fail-over. */ - public synchronized void failOver(ReplicationLiveIsStoppingMessage.LiveStopping finalMessage) - { + public synchronized void failOver(ReplicationLiveIsStoppingMessage.LiveStopping finalMessage) { removeListener(); signal = BACKUP_ACTIVATION.FAIL_OVER; - if (finalMessage == ReplicationLiveIsStoppingMessage.LiveStopping.FAIL_OVER) - { + if (finalMessage == ReplicationLiveIsStoppingMessage.LiveStopping.FAIL_OVER) { latch.countDown(); } - if (finalMessage == ReplicationLiveIsStoppingMessage.LiveStopping.STOP_CALLED) - { + if (finalMessage == ReplicationLiveIsStoppingMessage.LiveStopping.STOP_CALLED) { final CountDownLatch localLatch = latch; - scheduledPool.schedule(new Runnable() - { + scheduledPool.schedule(new Runnable() { @Override - public void run() - { + public void run() { localLatch.countDown(); } @@ -223,22 +198,18 @@ public class SharedNothingBackupQuorum implements Quorum, SessionFailureListener } } - public void notifyRegistrationFailed() - { + public void notifyRegistrationFailed() { signal = BACKUP_ACTIVATION.FAILURE_REPLICATING; latch.countDown(); } - public void notifyAlreadyReplicating() - { + public void notifyAlreadyReplicating() { signal = BACKUP_ACTIVATION.ALREADY_REPLICATING; latch.countDown(); } - private void removeListener() - { - if (connection != null) - { + private void removeListener() { + if (connection != null) { connection.removeFailureListener(this); } } @@ -249,34 +220,28 @@ public class SharedNothingBackupQuorum implements Quorum, SessionFailureListener * * @return signal, indicating whether to stop or to fail-over */ - public BACKUP_ACTIVATION waitForStatusChange() - { - try - { + public BACKUP_ACTIVATION waitForStatusChange() { + try { latch.await(); } - catch (InterruptedException e) - { + catch (InterruptedException e) { return BACKUP_ACTIVATION.STOP; } return signal; } - /** * Cause the Activation thread to exit and the server to be stopped. * * @param explicitSignal the state we want to set the quorum manager to return */ - public synchronized void causeExit(BACKUP_ACTIVATION explicitSignal) - { + public synchronized void causeExit(BACKUP_ACTIVATION explicitSignal) { removeListener(); this.signal = explicitSignal; latch.countDown(); } - public synchronized void reset() - { + public synchronized void reset() { latch = new CountDownLatch(1); } @@ -285,8 +250,7 @@ public class SharedNothingBackupQuorum implements Quorum, SessionFailureListener * * @return the voting decision */ - private boolean isLiveDown() - { + private boolean isLiveDown() { // we use 1 less than the max cluste size as we arent bothered about the replicated live node int size = quorumManager.getMaxClusterSize() - 1; @@ -294,12 +258,10 @@ public class SharedNothingBackupQuorum implements Quorum, SessionFailureListener quorumManager.vote(quorumVote); - try - { + try { quorumVote.await(LATCH_TIMEOUT, TimeUnit.SECONDS); } - catch (InterruptedException interruption) - { + catch (InterruptedException interruption) { // No-op. The best the quorum can do now is to return the latest number it has } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/Vote.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/Vote.java index 23739caced..5ceb0b2351 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/Vote.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/qourum/Vote.java @@ -24,19 +24,17 @@ import java.util.Map; /** * the vote itself */ -public abstract class Vote -{ +public abstract class Vote { - public Map getVoteMap() - { + public Map getVoteMap() { HashMap map = new HashMap<>(); return map; } - public abstract void encode(final ActiveMQBuffer buff); public abstract void decode(final ActiveMQBuffer buff); + //whether or note we should ask the target server for an answer or decide ourselves, for instance if we couldn't //connect to the node in the first place. public abstract boolean isRequestServerVote(); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/embedded/EmbeddedActiveMQ.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/embedded/EmbeddedActiveMQ.java index 9892abbaef..86bbe91896 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/embedded/EmbeddedActiveMQ.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/embedded/EmbeddedActiveMQ.java @@ -29,8 +29,8 @@ import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManagerImpl /** * Helper class to simplify bootstrap of ActiveMQ Artemis server. Bootstraps from classpath-based config files. */ -public class EmbeddedActiveMQ -{ +public class EmbeddedActiveMQ { + protected ActiveMQSecurityManager securityManager; protected String configResourcePath = null; protected Configuration configuration; @@ -42,8 +42,7 @@ public class EmbeddedActiveMQ * * @param filename */ - public void setConfigResourcePath(String filename) - { + public void setConfigResourcePath(String filename) { configResourcePath = filename; } @@ -52,8 +51,7 @@ public class EmbeddedActiveMQ * * @param securityManager */ - public void setSecurityManager(ActiveMQSecurityManager securityManager) - { + public void setSecurityManager(ActiveMQSecurityManager securityManager) { this.securityManager = securityManager; } @@ -62,8 +60,7 @@ public class EmbeddedActiveMQ * * @param mbeanServer */ - public void setMbeanServer(MBeanServer mbeanServer) - { + public void setMbeanServer(MBeanServer mbeanServer) { this.mbeanServer = mbeanServer; } @@ -73,50 +70,42 @@ public class EmbeddedActiveMQ * * @param configuration */ - public void setConfiguration(Configuration configuration) - { + public void setConfiguration(Configuration configuration) { this.configuration = configuration; } - public ActiveMQServer getActiveMQServer() - { + public ActiveMQServer getActiveMQServer() { return activeMQServer; } - public void start() throws Exception - { + public void start() throws Exception { initStart(); activeMQServer.start(); } - protected void initStart() throws Exception - { - if (configuration == null) - { - if (configResourcePath == null) configResourcePath = "broker.xml"; + protected void initStart() throws Exception { + if (configuration == null) { + if (configResourcePath == null) + configResourcePath = "broker.xml"; FileDeploymentManager deploymentManager = new FileDeploymentManager(configResourcePath); FileConfiguration config = new FileConfiguration(); deploymentManager.addDeployable(config); deploymentManager.readConfiguration(); configuration = config; } - if (securityManager == null) - { + if (securityManager == null) { securityManager = new ActiveMQSecurityManagerImpl(); } - if (mbeanServer == null) - { + if (mbeanServer == null) { activeMQServer = new ActiveMQServerImpl(configuration, securityManager); } - else - { + else { activeMQServer = new ActiveMQServerImpl(configuration, mbeanServer, securityManager); } } - public void stop() throws Exception - { + public void stop() throws Exception { activeMQServer.stop(); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/GroupingHandler.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/GroupingHandler.java index 57649bc778..0ebb80ff20 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/GroupingHandler.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/GroupingHandler.java @@ -23,8 +23,8 @@ import org.apache.activemq.artemis.core.server.group.impl.Proposal; import org.apache.activemq.artemis.core.server.group.impl.Response; import org.apache.activemq.artemis.core.server.management.NotificationListener; -public interface GroupingHandler extends NotificationListener, ActiveMQComponent -{ +public interface GroupingHandler extends NotificationListener, ActiveMQComponent { + // this method should maintain a WeakHash list, no need to remove the elements void addListener(UnproposalListener listener); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/UnproposalListener.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/UnproposalListener.java index 40013e9302..d083b894cc 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/UnproposalListener.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/UnproposalListener.java @@ -18,7 +18,7 @@ package org.apache.activemq.artemis.core.server.group; import org.apache.activemq.artemis.api.core.SimpleString; -public interface UnproposalListener -{ +public interface UnproposalListener { + void unproposed(SimpleString groupID); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/GroupBinding.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/GroupBinding.java index 7bdc46c9f1..d65c954a5d 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/GroupBinding.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/GroupBinding.java @@ -21,8 +21,8 @@ import org.apache.activemq.artemis.api.core.SimpleString; /** * A group binding */ -public class GroupBinding -{ +public class GroupBinding { + private long id; private final SimpleString groupId; @@ -31,54 +31,45 @@ public class GroupBinding volatile long timeUsed; - public GroupBinding(final SimpleString groupId, final SimpleString clusterName) - { + public GroupBinding(final SimpleString groupId, final SimpleString clusterName) { this.groupId = groupId; this.clusterName = clusterName; use(); } - public GroupBinding(final long id, final SimpleString groupId, final SimpleString clusterName) - { + public GroupBinding(final long id, final SimpleString groupId, final SimpleString clusterName) { this.id = id; this.groupId = groupId; this.clusterName = clusterName; use(); } - public long getId() - { + public long getId() { return id; } - public void setId(final long id) - { + public void setId(final long id) { this.id = id; } - public SimpleString getGroupId() - { + public SimpleString getGroupId() { return groupId; } - public SimpleString getClusterName() - { + public SimpleString getClusterName() { return clusterName; } - public long getTimeUsed() - { + public long getTimeUsed() { return timeUsed; } - public void use() - { + public void use() { timeUsed = System.currentTimeMillis(); } @Override - public String toString() - { + public String toString() { return id + ":" + groupId + ":" + clusterName; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/GroupHandlingAbstract.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/GroupHandlingAbstract.java index a252193731..c3165c6ae2 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/GroupHandlingAbstract.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/GroupHandlingAbstract.java @@ -32,8 +32,8 @@ import org.apache.activemq.artemis.core.server.management.ManagementService; import org.apache.activemq.artemis.core.server.management.Notification; import org.apache.activemq.artemis.utils.TypedProperties; -public abstract class GroupHandlingAbstract implements GroupingHandler -{ +public abstract class GroupHandlingAbstract implements GroupingHandler { + protected final Executor executor; protected final ManagementService managementService; @@ -45,64 +45,49 @@ public abstract class GroupHandlingAbstract implements GroupingHandler public GroupHandlingAbstract(final Executor executor, final ManagementService managementService, - final SimpleString address) - { + final SimpleString address) { this.executor = executor; this.managementService = managementService; this.address = address; } - public void addListener(final UnproposalListener listener) - { - if (executor == null) - { + public void addListener(final UnproposalListener listener) { + if (executor == null) { listeners.add(listener); } - else - { - executor.execute(new Runnable() - { - public void run() - { + else { + executor.execute(new Runnable() { + public void run() { listeners.add(listener); } }); } } - protected void fireUnproposed(final SimpleString groupID) - { + protected void fireUnproposed(final SimpleString groupID) { - Runnable runnable = new Runnable() - { - public void run() - { - for (UnproposalListener listener : listeners) - { + Runnable runnable = new Runnable() { + public void run() { + for (UnproposalListener listener : listeners) { listener.unproposed(groupID); } } }; - if (executor != null) - { + if (executor != null) { executor.execute(runnable); } - else - { + else { // for tests only, where we don't need an executor runnable.run(); } } - public void forceRemove(SimpleString groupid, SimpleString clusterName) throws Exception - { + public void forceRemove(SimpleString groupid, SimpleString clusterName) throws Exception { remove(groupid, clusterName); sendUnproposal(groupid, clusterName, 0); } - - protected void sendUnproposal(SimpleString groupid, SimpleString clusterName, int distance) - { + protected void sendUnproposal(SimpleString groupid, SimpleString clusterName, int distance) { TypedProperties props = new TypedProperties(); props.putSimpleStringProperty(ManagementHelper.HDR_PROPOSAL_GROUP_ID, groupid); props.putSimpleStringProperty(ManagementHelper.HDR_PROPOSAL_VALUE, clusterName); @@ -110,15 +95,12 @@ public abstract class GroupHandlingAbstract implements GroupingHandler props.putSimpleStringProperty(ManagementHelper.HDR_ADDRESS, address); props.putIntProperty(ManagementHelper.HDR_DISTANCE, distance); Notification notification = new Notification(null, CoreNotificationType.UNPROPOSAL, props); - try - { + try { managementService.sendNotification(notification); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorHandlingMessage(e); } } - } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/GroupingHandlerConfiguration.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/GroupingHandlerConfiguration.java index 08fb50f11e..f6b7fccf02 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/GroupingHandlerConfiguration.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/GroupingHandlerConfiguration.java @@ -24,8 +24,8 @@ import org.apache.activemq.artemis.api.core.SimpleString; /** * A remote Grouping handler configuration */ -public final class GroupingHandlerConfiguration implements Serializable -{ +public final class GroupingHandlerConfiguration implements Serializable { + public static final long serialVersionUID = -4600283023652477326L; public static final String GROUP_TIMEOUT_PROP_NAME = "org.apache.activemq.GroupingHandlerConfiguration.groupTimeout"; @@ -44,96 +44,79 @@ public final class GroupingHandlerConfiguration implements Serializable private long reaperPeriod = ActiveMQDefaultConfiguration.getDefaultGroupingHandlerReaperPeriod(); - public GroupingHandlerConfiguration() - { + public GroupingHandlerConfiguration() { } - public SimpleString getName() - { + public SimpleString getName() { return name; } - public TYPE getType() - { + public TYPE getType() { return type; } - public SimpleString getAddress() - { + public SimpleString getAddress() { return address; } - public long getTimeout() - { + public long getTimeout() { return timeout; } - public long getGroupTimeout() - { + public long getGroupTimeout() { return groupTimeout; } - public long getReaperPeriod() - { + public long getReaperPeriod() { return reaperPeriod; } - public GroupingHandlerConfiguration setName(SimpleString name) - { + public GroupingHandlerConfiguration setName(SimpleString name) { this.name = name; return this; } - public GroupingHandlerConfiguration setType(TYPE type) - { + public GroupingHandlerConfiguration setType(TYPE type) { this.type = type; return this; } - public GroupingHandlerConfiguration setAddress(SimpleString address) - { + public GroupingHandlerConfiguration setAddress(SimpleString address) { this.address = address; return this; } - public GroupingHandlerConfiguration setTimeout(long timeout) - { + public GroupingHandlerConfiguration setTimeout(long timeout) { this.timeout = timeout; return this; } - public GroupingHandlerConfiguration setGroupTimeout(long groupTimeout) - { + public GroupingHandlerConfiguration setGroupTimeout(long groupTimeout) { this.groupTimeout = groupTimeout; return this; } - public GroupingHandlerConfiguration setReaperPeriod(long reaperPeriod) - { + public GroupingHandlerConfiguration setReaperPeriod(long reaperPeriod) { this.reaperPeriod = reaperPeriod; return this; } - public enum TYPE - { + public enum TYPE { LOCAL("LOCAL"), REMOTE("REMOTE"); private String type; - TYPE(final String type) - { + TYPE(final String type) { this.type = type; } - public String getType() - { + public String getType() { return type; } } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((address == null) ? 0 : address.hashCode()); @@ -144,24 +127,21 @@ public final class GroupingHandlerConfiguration implements Serializable } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; - GroupingHandlerConfiguration other = (GroupingHandlerConfiguration)obj; - if (address == null) - { + GroupingHandlerConfiguration other = (GroupingHandlerConfiguration) obj; + if (address == null) { if (other.address != null) return false; } else if (!address.equals(other.address)) return false; - if (name == null) - { + if (name == null) { if (other.name != null) return false; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/LocalGroupingHandler.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/LocalGroupingHandler.java index d09d5f50d8..41627767fc 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/LocalGroupingHandler.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/LocalGroupingHandler.java @@ -44,8 +44,8 @@ import org.apache.activemq.artemis.utils.TypedProperties; /** * A Local Grouping handler. All the Remote handlers will talk with us */ -public final class LocalGroupingHandler extends GroupHandlingAbstract -{ +public final class LocalGroupingHandler extends GroupHandlingAbstract { + private final ConcurrentMap map = new ConcurrentHashMap(); private final ConcurrentMap> groupMap = new ConcurrentHashMap>(); @@ -87,8 +87,7 @@ public final class LocalGroupingHandler extends GroupHandlingAbstract final StorageManager storageManager, final long timeout, final long groupTimeout, - long reaperPeriod) - { + long reaperPeriod) { super(executorFactory.getExecutor(), managementService, address); this.reaperPeriod = reaperPeriod; this.scheduledExecutor = scheduledExecutor; @@ -98,30 +97,24 @@ public final class LocalGroupingHandler extends GroupHandlingAbstract this.groupTimeout = groupTimeout; } - public SimpleString getName() - { + public SimpleString getName() { return name; } - public Response propose(final Proposal proposal) throws Exception - { + public Response propose(final Proposal proposal) throws Exception { OperationContext originalCtx = storageManager.getContext(); - try - { + try { // the waitCompletion cannot be done inside an ordered executor or we would starve when the thread pool is full storageManager.setContext(storageManager.newSingleThreadContext()); - if (proposal.getClusterName() == null) - { + if (proposal.getClusterName() == null) { GroupBinding original = map.get(proposal.getGroupId()); - if (original != null) - { + if (original != null) { original.use(); return new Response(proposal.getGroupId(), original.getClusterName()); } - else - { + else { return null; } } @@ -130,65 +123,54 @@ public final class LocalGroupingHandler extends GroupHandlingAbstract GroupBinding groupBinding = null; lock.lock(); - try - { + try { groupBinding = map.get(proposal.getGroupId()); - if (groupBinding != null) - { + if (groupBinding != null) { groupBinding.use(); // Returning with an alternate cluster name, as it's been already grouped return new Response(groupBinding.getGroupId(), proposal.getClusterName(), groupBinding.getClusterName()); } - else - { + else { addRecord = true; groupBinding = new GroupBinding(proposal.getGroupId(), proposal.getClusterName()); groupBinding.setId(storageManager.generateID()); List newList = new ArrayList(); List oldList = groupMap.putIfAbsent(groupBinding.getClusterName(), newList); - if (oldList != null) - { + if (oldList != null) { newList = oldList; } newList.add(groupBinding); map.put(groupBinding.getGroupId(), groupBinding); } } - finally - { + finally { lock.unlock(); } // Storing the record outside of any locks - if (addRecord) - { + if (addRecord) { storageManager.addGrouping(groupBinding); } return new Response(groupBinding.getGroupId(), groupBinding.getClusterName()); } - finally - { + finally { storageManager.setContext(originalCtx); } } - public void resendPending() throws Exception - { + public void resendPending() throws Exception { // this only make sense on RemoteGroupingHandler. // this is a no-op on the local one } - public void proposed(final Response response) throws Exception - { + public void proposed(final Response response) throws Exception { } @Override - public void remove(SimpleString groupid, SimpleString clusterName, int distance) throws Exception - { + public void remove(SimpleString groupid, SimpleString clusterName, int distance) throws Exception { remove(groupid, clusterName); } - public void sendProposalResponse(final Response response, final int distance) throws Exception - { + public void sendProposalResponse(final Response response, final int distance) throws Exception { TypedProperties props = new TypedProperties(); props.putSimpleStringProperty(ManagementHelper.HDR_PROPOSAL_GROUP_ID, response.getGroupId()); props.putSimpleStringProperty(ManagementHelper.HDR_PROPOSAL_VALUE, response.getClusterName()); @@ -200,58 +182,47 @@ public final class LocalGroupingHandler extends GroupHandlingAbstract managementService.sendNotification(notification); } - public Response receive(final Proposal proposal, final int distance) throws Exception - { + public Response receive(final Proposal proposal, final int distance) throws Exception { ActiveMQServerLogger.LOGGER.trace("received proposal " + proposal); return propose(proposal); } - public void addGroupBinding(final GroupBinding groupBinding) - { + public void addGroupBinding(final GroupBinding groupBinding) { map.put(groupBinding.getGroupId(), groupBinding); List newList = new ArrayList(); List oldList = groupMap.putIfAbsent(groupBinding.getClusterName(), newList); - if (oldList != null) - { + if (oldList != null) { newList = oldList; } newList.add(groupBinding); } - public Response getProposal(final SimpleString fullID, final boolean touchTime) - { + public Response getProposal(final SimpleString fullID, final boolean touchTime) { GroupBinding original = map.get(fullID); - if (original != null) - { - if (touchTime) - { + if (original != null) { + if (touchTime) { original.use(); } return new Response(fullID, original.getClusterName()); } - else - { + else { return null; } } @Override - public void remove(SimpleString groupid, SimpleString clusterName) - { + public void remove(SimpleString groupid, SimpleString clusterName) { GroupBinding groupBinding = map.remove(groupid); List groupBindings = groupMap.get(clusterName); - if (groupBindings != null && groupBinding != null) - { + if (groupBindings != null && groupBinding != null) { groupBindings.remove(groupBinding); - try - { + try { long tx = storageManager.generateID(); storageManager.deleteGrouping(tx, groupBinding); storageManager.commitBindings(tx); } - catch (Exception e) - { + catch (Exception e) { // nothing we can do being log ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e); } @@ -259,24 +230,19 @@ public final class LocalGroupingHandler extends GroupHandlingAbstract } @Override - public void awaitBindings() throws Exception - { + public void awaitBindings() throws Exception { lock.lock(); - try - { - if (groupMap.size() > 0) - { + try { + if (groupMap.size() > 0) { waitingForBindings = true; //make a copy of the bindings added so far from the cluster via onNotification() List bindingsAlreadyAdded; - if (expectedBindings == null) - { + if (expectedBindings == null) { bindingsAlreadyAdded = Collections.emptyList(); expectedBindings = new LinkedList(); } - else - { + else { bindingsAlreadyAdded = new ArrayList(expectedBindings); //clear the bindings expectedBindings.clear(); @@ -287,170 +253,132 @@ public final class LocalGroupingHandler extends GroupHandlingAbstract //received via onNotification expectedBindings.removeAll(bindingsAlreadyAdded); - if (expectedBindings.size() > 0) - { + if (expectedBindings.size() > 0) { ActiveMQServerLogger.LOGGER.debug("Waiting remote group bindings to arrive before starting the server. timeout=" + timeout + " milliseconds"); //now we wait here for the rest to be received in onNotification, it will signal once all have been received. //if we arent signaled then bindingsAdded still has some groupids we need to remove. - if (!awaitCondition.await(timeout, TimeUnit.MILLISECONDS)) - { + if (!awaitCondition.await(timeout, TimeUnit.MILLISECONDS)) { ActiveMQServerLogger.LOGGER.remoteGroupCoordinatorsNotStarted(); } } } } - finally - { + finally { expectedBindings = null; waitingForBindings = false; lock.unlock(); } } - public void onNotification(final Notification notification) - { - if (!(notification.getType() instanceof CoreNotificationType)) return; + public void onNotification(final Notification notification) { + if (!(notification.getType() instanceof CoreNotificationType)) + return; - if (notification.getType() == CoreNotificationType.BINDING_REMOVED) - { - SimpleString clusterName = notification.getProperties() - .getSimpleStringProperty(ManagementHelper.HDR_CLUSTER_NAME); + if (notification.getType() == CoreNotificationType.BINDING_REMOVED) { + SimpleString clusterName = notification.getProperties().getSimpleStringProperty(ManagementHelper.HDR_CLUSTER_NAME); removeGrouping(clusterName); } - else if (notification.getType() == CoreNotificationType.BINDING_ADDED) - { - SimpleString clusterName = notification.getProperties() - .getSimpleStringProperty(ManagementHelper.HDR_CLUSTER_NAME); - try - { + else if (notification.getType() == CoreNotificationType.BINDING_ADDED) { + SimpleString clusterName = notification.getProperties().getSimpleStringProperty(ManagementHelper.HDR_CLUSTER_NAME); + try { lock.lock(); - if (expectedBindings != null) - { - if (waitingForBindings) - { - if (expectedBindings.remove(clusterName)) - { + if (expectedBindings != null) { + if (waitingForBindings) { + if (expectedBindings.remove(clusterName)) { ActiveMQServerLogger.LOGGER.debug("OnNotification for waitForbindings::Removed clusterName=" + clusterName + " from lis succesffully"); } - else - { + else { ActiveMQServerLogger.LOGGER.debug("OnNotification for waitForbindings::Couldn't remove clusterName=" + clusterName + " as it wasn't on the original list"); } } - else - { + else { expectedBindings.add(clusterName); ActiveMQServerLogger.LOGGER.debug("Notification for waitForbindings::Adding previously known item clusterName=" + clusterName); } - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { - for (SimpleString stillWaiting : expectedBindings) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { + for (SimpleString stillWaiting : expectedBindings) { ActiveMQServerLogger.LOGGER.debug("Notification for waitForbindings::Still waiting for clusterName=" + stillWaiting); } } - if (expectedBindings.size() == 0) - { + if (expectedBindings.size() == 0) { awaitCondition.signal(); } } } - finally - { + finally { lock.unlock(); } } } - public synchronized void start() throws Exception - { + public synchronized void start() throws Exception { if (started) return; - if (expectedBindings == null) - { + if (expectedBindings == null) { // just in case the component is restarted expectedBindings = new LinkedList(); } - if (reaperPeriod > 0 && groupTimeout > 0) - { - if (reaperFuture != null) - { + if (reaperPeriod > 0 && groupTimeout > 0) { + if (reaperFuture != null) { reaperFuture.cancel(true); reaperFuture = null; } - reaperFuture = scheduledExecutor.scheduleAtFixedRate(new GroupReaperScheduler(), reaperPeriod, - reaperPeriod, TimeUnit.MILLISECONDS); + reaperFuture = scheduledExecutor.scheduleAtFixedRate(new GroupReaperScheduler(), reaperPeriod, reaperPeriod, TimeUnit.MILLISECONDS); } started = true; } - public synchronized void stop() throws Exception - { + public synchronized void stop() throws Exception { started = false; - if (reaperFuture != null) - { + if (reaperFuture != null) { reaperFuture.cancel(true); reaperFuture = null; } } - public boolean isStarted() - { + public boolean isStarted() { return started; } - private void removeGrouping(final SimpleString clusterName) - { + private void removeGrouping(final SimpleString clusterName) { final List list = groupMap.remove(clusterName); - if (list != null) - { - executor.execute(new Runnable() - { + if (list != null) { + executor.execute(new Runnable() { @Override - public void run() - { + public void run() { long txID = -1; - for (GroupBinding val : list) - { - if (val != null) - { + for (GroupBinding val : list) { + if (val != null) { fireUnproposed(val.getGroupId()); map.remove(val.getGroupId()); sendUnproposal(val.getGroupId(), clusterName, 0); - try - { - if (txID < 0) - { + try { + if (txID < 0) { txID = storageManager.generateID(); } storageManager.deleteGrouping(txID, val); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.unableToDeleteGroupBindings(e, val.getGroupId()); } } } - - if (txID >= 0) - { - try - { + if (txID >= 0) { + try { storageManager.commitBindings(txID); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.unableToDeleteGroupBindings(e, SimpleString.toSimpleString("TX:" + txID)); } } @@ -460,33 +388,28 @@ public final class LocalGroupingHandler extends GroupHandlingAbstract } } - private final class GroupReaperScheduler implements Runnable - { + private final class GroupReaperScheduler implements Runnable { + final GroupIdReaper reaper = new GroupIdReaper(); - public void run() - { + public void run() { executor.execute(reaper); } } - private final class GroupIdReaper implements Runnable - { - public void run() - { + private final class GroupIdReaper implements Runnable { + + public void run() { // The reaper thread should be finished case the PostOffice is gone // This is to avoid leaks on PostOffice between stops and starts - if (isStarted()) - { + if (isStarted()) { long txID = -1; int expiredGroups = 0; - for (GroupBinding groupBinding : map.values()) - { - if ((groupBinding.getTimeUsed() + groupTimeout) < System.currentTimeMillis()) - { + for (GroupBinding groupBinding : map.values()) { + if ((groupBinding.getTimeUsed() + groupTimeout) < System.currentTimeMillis()) { map.remove(groupBinding.getGroupId()); List groupBindings = groupMap.get(groupBinding.getClusterName()); @@ -497,36 +420,29 @@ public final class LocalGroupingHandler extends GroupHandlingAbstract sendUnproposal(groupBinding.getGroupId(), groupBinding.getClusterName(), 0); expiredGroups++; - try - { - if (txID < 0) - { + try { + if (txID < 0) { txID = storageManager.generateID(); } storageManager.deleteGrouping(txID, groupBinding); - if (expiredGroups >= 1000 && txID >= 0) - { + if (expiredGroups >= 1000 && txID >= 0) { expiredGroups = 0; txID = -1; storageManager.commitBindings(txID); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.unableToDeleteGroupBindings(e, groupBinding.getGroupId()); } } } - if (txID >= 0) - { - try - { + if (txID >= 0) { + try { storageManager.commitBindings(txID); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.unableToDeleteGroupBindings(e, SimpleString.toSimpleString("TX:" + txID)); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/Proposal.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/Proposal.java index a287ff10f9..492866dfff 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/Proposal.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/Proposal.java @@ -21,31 +21,27 @@ import org.apache.activemq.artemis.api.core.SimpleString; /** * A proposal to select a group id */ -public class Proposal -{ +public class Proposal { + private final SimpleString groupId; private final SimpleString clusterName; - public Proposal(final SimpleString groupId, final SimpleString clusterName) - { + public Proposal(final SimpleString groupId, final SimpleString clusterName) { this.clusterName = clusterName; this.groupId = groupId; } - public SimpleString getGroupId() - { + public SimpleString getGroupId() { return groupId; } - public SimpleString getClusterName() - { + public SimpleString getClusterName() { return clusterName; } @Override - public String toString() - { + public String toString() { return "Proposal:" + getGroupId() + ":" + clusterName; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/RemoteGroupingHandler.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/RemoteGroupingHandler.java index c33a4f8cc7..5545aff511 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/RemoteGroupingHandler.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/RemoteGroupingHandler.java @@ -44,8 +44,8 @@ import org.apache.activemq.artemis.utils.TypedProperties; * This will use management notifications to communicate with the node that has the Local Grouping * handler to make proposals. */ -public final class RemoteGroupingHandler extends GroupHandlingAbstract -{ +public final class RemoteGroupingHandler extends GroupHandlingAbstract { + private final SimpleString name; private final Map responses = new ConcurrentHashMap(); @@ -69,8 +69,7 @@ public final class RemoteGroupingHandler extends GroupHandlingAbstract final SimpleString name, final SimpleString address, final long timeout, - final long groupTimeout) - { + final long groupTimeout) { super(executorFactory != null ? executorFactory.getExecutor() : null, managementService, address); this.name = name; this.timeout = timeout; @@ -81,74 +80,61 @@ public final class RemoteGroupingHandler extends GroupHandlingAbstract final SimpleString name, final SimpleString address, final long timeout, - final long groupTimeout) - { + final long groupTimeout) { this(null, managementService, name, address, timeout, groupTimeout); } - public SimpleString getName() - { + public SimpleString getName() { return name; } @Override - public void start() throws Exception - { + public void start() throws Exception { if (started) return; started = true; } @Override - public void stop() throws Exception - { + public void stop() throws Exception { started = false; } @Override - public boolean isStarted() - { + public boolean isStarted() { return started; } - public void resendPending() throws Exception - { + public void resendPending() throws Exception { // In case the RESET wasn't sent yet to the remote node, we may eventually miss a node send, // on that case the cluster-reset information will ask the group to resend any pending information - try - { + try { lock.lock(); - for (Notification notification : pendingNotifications) - { + for (Notification notification : pendingNotifications) { managementService.sendNotification(notification); } } - finally - { + finally { lock.unlock(); } } - public Response propose(final Proposal proposal) throws Exception - { + public Response propose(final Proposal proposal) throws Exception { // return it from the cache first Response response = responses.get(proposal.getGroupId()); - if (response != null) - { + if (response != null) { checkTimeout(response); return response; } - if (!started) - { + if (!started) { throw ActiveMQMessageBundle.BUNDLE.groupWhileStopping(); } Notification notification = null; - try - { + try { lock.lock(); @@ -158,67 +144,52 @@ public final class RemoteGroupingHandler extends GroupHandlingAbstract managementService.sendNotification(notification); - long timeLimit = System.currentTimeMillis() + timeout; - do - { + do { sendCondition.await(timeout, TimeUnit.MILLISECONDS); response = responses.get(proposal.getGroupId()); // You could have this response being null if you had multiple threads calling propose - if (response != null) - { + if (response != null) { break; } - } - while (timeLimit > System.currentTimeMillis()); + } while (timeLimit > System.currentTimeMillis()); } - finally - { - if (notification != null) - { + finally { + if (notification != null) { pendingNotifications.remove(notification); } lock.unlock(); } - if (response == null) - { + if (response == null) { ActiveMQServerLogger.LOGGER.groupHandlerSendTimeout(); } return response; } @Override - public void awaitBindings() - { + public void awaitBindings() { // NO-OP } - - private void checkTimeout(Response response) - { - if (response != null) - { - if (groupTimeout > 0 && ((response.getTimeUsed() + groupTimeout) < System.currentTimeMillis())) - { + private void checkTimeout(Response response) { + if (response != null) { + if (groupTimeout > 0 && ((response.getTimeUsed() + groupTimeout) < System.currentTimeMillis())) { // We just touch the group on the local server at the half of the timeout // to avoid the group from expiring response.use(); - try - { + try { managementService.sendNotification(createProposalNotification(response.getGroupId(), response.getClusterName())); } - catch (Exception ignored) - { + catch (Exception ignored) { } } } } - private Notification createProposalNotification(SimpleString groupId, SimpleString clusterName) - { + private Notification createProposalNotification(SimpleString groupId, SimpleString clusterName) { TypedProperties props = new TypedProperties(); props.putSimpleStringProperty(ManagementHelper.HDR_PROPOSAL_GROUP_ID, groupId); @@ -234,23 +205,19 @@ public final class RemoteGroupingHandler extends GroupHandlingAbstract return new Notification(null, CoreNotificationType.PROPOSAL, props); } - public Response getProposal(final SimpleString fullID, boolean touchTime) - { + public Response getProposal(final SimpleString fullID, boolean touchTime) { Response response = responses.get(fullID); - if (touchTime) - { + if (touchTime) { checkTimeout(response); } return response; } @Override - public void remove(SimpleString groupid, SimpleString clusterName) throws Exception - { + public void remove(SimpleString groupid, SimpleString clusterName) throws Exception { List groups = groupMap.get(clusterName); - if (groups != null) - { + if (groups != null) { groups.remove(groupid); } responses.remove(groupid); @@ -258,23 +225,19 @@ public final class RemoteGroupingHandler extends GroupHandlingAbstract } @Override - public void remove(SimpleString groupid, SimpleString clusterName, int distance) throws Exception - { + public void remove(SimpleString groupid, SimpleString clusterName, int distance) throws Exception { remove(groupid, clusterName); sendUnproposal(groupid, clusterName, distance); } - public void proposed(final Response response) throws Exception - { - try - { + public void proposed(final Response response) throws Exception { + try { lock.lock(); responses.put(response.getGroupId(), response); List newList = new ArrayList(); List oldList = groupMap.putIfAbsent(response.getChosenClusterName(), newList); - if (oldList != null) - { + if (oldList != null) { newList = oldList; } newList.add(response.getGroupId()); @@ -282,14 +245,12 @@ public final class RemoteGroupingHandler extends GroupHandlingAbstract // using different groups sendCondition.signalAll(); } - finally - { + finally { lock.unlock(); } } - public Response receive(final Proposal proposal, final int distance) throws Exception - { + public Response receive(final Proposal proposal, final int distance) throws Exception { TypedProperties props = new TypedProperties(); props.putSimpleStringProperty(ManagementHelper.HDR_PROPOSAL_GROUP_ID, proposal.getGroupId()); props.putSimpleStringProperty(ManagementHelper.HDR_PROPOSAL_VALUE, proposal.getClusterName()); @@ -301,31 +262,24 @@ public final class RemoteGroupingHandler extends GroupHandlingAbstract return null; } - public void sendProposalResponse(final Response response, final int distance) throws Exception - { + public void sendProposalResponse(final Response response, final int distance) throws Exception { // NO-OP } - public void addGroupBinding(final GroupBinding groupBinding) - { + public void addGroupBinding(final GroupBinding groupBinding) { // NO-OP } - public void onNotification(final Notification notification) - { - if (!(notification.getType() instanceof CoreNotificationType)) return; + public void onNotification(final Notification notification) { + if (!(notification.getType() instanceof CoreNotificationType)) + return; // removing the groupid if the binding has been removed - if (notification.getType() == CoreNotificationType.BINDING_REMOVED) - { - SimpleString clusterName = notification.getProperties() - .getSimpleStringProperty(ManagementHelper.HDR_CLUSTER_NAME); + if (notification.getType() == CoreNotificationType.BINDING_REMOVED) { + SimpleString clusterName = notification.getProperties().getSimpleStringProperty(ManagementHelper.HDR_CLUSTER_NAME); List list = groupMap.remove(clusterName); - if (list != null) - { - for (SimpleString val : list) - { - if (val != null) - { + if (list != null) { + for (SimpleString val : list) { + if (val != null) { responses.remove(val); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/Response.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/Response.java index 0a0ead0858..5b4472e221 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/Response.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/group/impl/Response.java @@ -21,8 +21,8 @@ import org.apache.activemq.artemis.api.core.SimpleString; /** * A response to a proposal */ -public class Response -{ +public class Response { + private final boolean accepted; private final SimpleString clusterName; @@ -33,13 +33,13 @@ public class Response private volatile long timeUsed; - public Response(final SimpleString groupId, final SimpleString clusterName) - { + public Response(final SimpleString groupId, final SimpleString clusterName) { this(groupId, clusterName, null); } - public Response(final SimpleString groupId, final SimpleString clusterName, final SimpleString alternativeClusterName) - { + public Response(final SimpleString groupId, + final SimpleString clusterName, + final SimpleString alternativeClusterName) { this.groupId = groupId; accepted = alternativeClusterName == null; this.clusterName = clusterName; @@ -47,49 +47,41 @@ public class Response use(); } - public void use() - { + public void use() { timeUsed = System.currentTimeMillis(); } - public long getTimeUsed() - { + public long getTimeUsed() { return timeUsed; } - public boolean isAccepted() - { + public boolean isAccepted() { return accepted; } - public SimpleString getClusterName() - { + public SimpleString getClusterName() { return clusterName; } - public SimpleString getAlternativeClusterName() - { + public SimpleString getAlternativeClusterName() { return alternativeClusterName; } - public SimpleString getChosenClusterName() - { + public SimpleString getChosenClusterName() { return alternativeClusterName != null ? alternativeClusterName : clusterName; } @Override - public String toString() - { + public String toString() { return "accepted = " + accepted + - " groupid = " + groupId + - " clusterName = " + - clusterName + - " alternativeClusterName = " + - alternativeClusterName; + " groupid = " + groupId + + " clusterName = " + + clusterName + + " alternativeClusterName = " + + alternativeClusterName; } - public SimpleString getGroupId() - { + public SimpleString getGroupId() { return groupId; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/AIOFileLockNodeManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/AIOFileLockNodeManager.java index 2d0f3c0d0e..471b7c125d 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/AIOFileLockNodeManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/AIOFileLockNodeManager.java @@ -33,34 +33,29 @@ import org.apache.activemq.artemis.jlibaio.LibaioFile; *

    * https://bugzilla.redhat.com/show_bug.cgi?id=678585 */ -public final class AIOFileLockNodeManager extends FileLockNodeManager -{ +public final class AIOFileLockNodeManager extends FileLockNodeManager { /** * @param directory * @param replicatingBackup */ - public AIOFileLockNodeManager(final File directory, boolean replicatingBackup) - { + public AIOFileLockNodeManager(final File directory, boolean replicatingBackup) { super(directory, replicatingBackup); } - public AIOFileLockNodeManager(final File directory, boolean replicatingBackup, long lockAcquisitionTimeout) - { + public AIOFileLockNodeManager(final File directory, boolean replicatingBackup, long lockAcquisitionTimeout) { super(directory, replicatingBackup); this.lockAcquisitionTimeout = lockAcquisitionTimeout; } @Override - protected FileLock tryLock(final int lockPos) throws Exception - { + protected FileLock tryLock(final int lockPos) throws Exception { File file = newFileForRegionLock(lockPos); LibaioFile fileControl = LibaioContext.openControlFile(file.getAbsolutePath(), false); - if (!fileControl.lock()) - { + if (!fileControl.lock()) { fileControl.close(); return null; } @@ -72,32 +67,25 @@ public final class AIOFileLockNodeManager extends FileLockNodeManager } @Override - protected FileLock lock(final int liveLockPos) throws Exception - { + protected FileLock lock(final int liveLockPos) throws Exception { long start = System.currentTimeMillis(); File file = newFileForRegionLock(liveLockPos); - while (!interrupted) - { + while (!interrupted) { FileLock lockFile = tryLock(liveLockPos); - if (lockFile != null) - { + if (lockFile != null) { return lockFile; } - else - { - try - { + else { + try { Thread.sleep(500); } - catch (InterruptedException e) - { + catch (InterruptedException e) { return null; } - if (lockAcquisitionTimeout != -1 && (System.currentTimeMillis() - start) > lockAcquisitionTimeout) - { + if (lockAcquisitionTimeout != -1 && (System.currentTimeMillis() - start) > lockAcquisitionTimeout) { throw new Exception("timed out waiting for lock"); } } @@ -110,8 +98,7 @@ public final class AIOFileLockNodeManager extends FileLockNodeManager * @param liveLockPos * @return */ - protected File newFileForRegionLock(final int liveLockPos) - { + protected File newFileForRegionLock(final int liveLockPos) { File file = newFile("server." + liveLockPos + ".lock"); return file; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/Activation.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/Activation.java index 08c0fab4c9..8d7d8324c8 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/Activation.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/Activation.java @@ -35,19 +35,17 @@ import org.apache.activemq.artemis.core.server.management.ManagementService; import org.apache.activemq.artemis.spi.core.remoting.Acceptor; /** -* An activation controls the lifecycle of the server and any components specific to the Activation itself. -*/ -public abstract class Activation implements Runnable -{ + * An activation controls the lifecycle of the server and any components specific to the Activation itself. + */ +public abstract class Activation implements Runnable { + public abstract void close(boolean permanently, boolean restarting) throws Exception; /* * freeze the connection but allow the Activation to over ride this and decide if any connections should be left open. * */ - public void freezeConnections(RemotingService remotingService) - { - if (remotingService != null) - { + public void freezeConnections(RemotingService remotingService) { + if (remotingService != null) { remotingService.freeze(null, null); } } @@ -56,67 +54,60 @@ public abstract class Activation implements Runnable * allow the activation t ooverride this if it needs to tidy up after freezing the connection. its a different method as * its called outside of the lock that the previous method is. * */ - public void postConnectionFreeze() - { + public void postConnectionFreeze() { } /* * called before the server is closing the journals so the activation can tidy up stuff * */ - public void preStorageClose() throws Exception - { + public void preStorageClose() throws Exception { } /* * called by the server to notify the Activation that the server is stopping * */ - public void sendLiveIsStopping() - { + public void sendLiveIsStopping() { } /* * called by the ha manager to notify the Activation that HA is now active * */ - public void haStarted() - { + public void haStarted() { } /* * allows the Activation to register a channel handler so it can handle any packets that are unique to the Activation * */ - public ChannelHandler getActivationChannelHandler(Channel channel, Acceptor acceptorUsed) - { + public ChannelHandler getActivationChannelHandler(Channel channel, Acceptor acceptorUsed) { return null; } /* * returns the HA manager used for this Activation * */ - public HAManager getHAManager() - { + public HAManager getHAManager() { return new StandaloneHAManager(); } /* * create the Journal loader needed for this Activation. * */ - public JournalLoader createJournalLoader(PostOffice postOffice, PagingManager pagingManager, StorageManager storageManager, QueueFactory queueFactory, NodeManager nodeManager, ManagementService managementService, GroupingHandler groupingHandler, Configuration configuration, ActiveMQServer parentServer) throws ActiveMQException - { - return new PostOfficeJournalLoader(postOffice, - pagingManager, - storageManager, - queueFactory, - nodeManager, - managementService, - groupingHandler, - configuration); + public JournalLoader createJournalLoader(PostOffice postOffice, + PagingManager pagingManager, + StorageManager storageManager, + QueueFactory queueFactory, + NodeManager nodeManager, + ManagementService managementService, + GroupingHandler groupingHandler, + Configuration configuration, + ActiveMQServer parentServer) throws ActiveMQException { + return new PostOfficeJournalLoader(postOffice, pagingManager, storageManager, queueFactory, nodeManager, managementService, groupingHandler, configuration); } /* * todo, remove this, its only needed for JMSServerManagerImpl, it should be sought elsewhere * */ - public ReplicationManager getReplicationManager() - { + public ReplicationManager getReplicationManager() { return null; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ActiveMQServerImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ActiveMQServerImpl.java index e33286c9f3..885315423e 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ActiveMQServerImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ActiveMQServerImpl.java @@ -134,8 +134,8 @@ import java.util.concurrent.TimeUnit; /** * The ActiveMQ Artemis server implementation */ -public class ActiveMQServerImpl implements ActiveMQServer -{ +public class ActiveMQServerImpl implements ActiveMQServer { + /** * JMS Topics (which are outside of the scope of the core API) will require a dumb subscription * with a dummy-filter at this current version as a way to keep its existence valid and TCK @@ -148,8 +148,7 @@ public class ActiveMQServerImpl implements ActiveMQServer private HAPolicy haPolicy; - enum SERVER_STATE - { + enum SERVER_STATE { /** * start() has been called but components are not initialized. The whole point of this state, * is to be in a state which is different from {@link SERVER_STATE#STARTED} and @@ -266,43 +265,36 @@ public class ActiveMQServerImpl implements ActiveMQServer // Constructors // --------------------------------------------------------------------------------- - public ActiveMQServerImpl() - { + public ActiveMQServerImpl() { this(null, null, null); } - public ActiveMQServerImpl(final Configuration configuration) - { + public ActiveMQServerImpl(final Configuration configuration) { this(configuration, null, null); } - public ActiveMQServerImpl(final Configuration configuration, ActiveMQServer parentServer) - { + public ActiveMQServerImpl(final Configuration configuration, ActiveMQServer parentServer) { this(configuration, null, null, parentServer); } - public ActiveMQServerImpl(final Configuration configuration, final MBeanServer mbeanServer) - { + public ActiveMQServerImpl(final Configuration configuration, final MBeanServer mbeanServer) { this(configuration, mbeanServer, null); } - public ActiveMQServerImpl(final Configuration configuration, final ActiveMQSecurityManager securityManager) - { + public ActiveMQServerImpl(final Configuration configuration, final ActiveMQSecurityManager securityManager) { this(configuration, null, securityManager); } public ActiveMQServerImpl(Configuration configuration, MBeanServer mbeanServer, - final ActiveMQSecurityManager securityManager) - { + final ActiveMQSecurityManager securityManager) { this(configuration, mbeanServer, securityManager, null); } public ActiveMQServerImpl(Configuration configuration, MBeanServer mbeanServer, final ActiveMQSecurityManager securityManager, - final ActiveMQServer parentServer) - { + final ActiveMQServer parentServer) { this(configuration, mbeanServer, securityManager, parentServer, null); } @@ -310,19 +302,15 @@ public class ActiveMQServerImpl implements ActiveMQServer MBeanServer mbeanServer, final ActiveMQSecurityManager securityManager, final ActiveMQServer parentServer, - final ServiceRegistry serviceRegistry) - { - if (configuration == null) - { + final ServiceRegistry serviceRegistry) { + if (configuration == null) { configuration = new ConfigurationImpl(); } - else - { + else { ConfigurationUtils.validateConfiguration(configuration); } - if (mbeanServer == null) - { + if (mbeanServer == null) { // Just use JVM mbean server mbeanServer = ManagementFactory.getPlatformMBeanServer(); } @@ -347,7 +335,7 @@ public class ActiveMQServerImpl implements ActiveMQServer this.parentServer = parentServer; - this.serviceRegistry = serviceRegistry == null ? new ServiceRegistryImpl() : serviceRegistry; + this.serviceRegistry = serviceRegistry == null ? new ServiceRegistryImpl() : serviceRegistry; } // life-cycle methods @@ -356,36 +344,29 @@ public class ActiveMQServerImpl implements ActiveMQServer /* * Can be overridden for tests */ - protected NodeManager createNodeManager(final File directory, boolean replicatingBackup) - { + protected NodeManager createNodeManager(final File directory, boolean replicatingBackup) { NodeManager manager; - if (!configuration.isPersistenceEnabled()) - { + if (!configuration.isPersistenceEnabled()) { manager = new InVMNodeManager(replicatingBackup); } - else if (configuration.getJournalType() == JournalType.ASYNCIO && LibaioContext.isLoaded()) - { + else if (configuration.getJournalType() == JournalType.ASYNCIO && LibaioContext.isLoaded()) { manager = new AIOFileLockNodeManager(directory, replicatingBackup, configuration.getJournalLockAcquisitionTimeout()); } - else - { + else { manager = new FileLockNodeManager(directory, replicatingBackup, configuration.getJournalLockAcquisitionTimeout()); } return manager; } - public final synchronized void start() throws Exception - { - if (state != SERVER_STATE.STOPPED) - { + public final synchronized void start() throws Exception { + if (state != SERVER_STATE.STOPPED) { ActiveMQServerLogger.LOGGER.debug("Server already started!"); return; } state = SERVER_STATE.STARTING; - if (haPolicy == null) - { + if (haPolicy == null) { haPolicy = ConfigurationUtils.getHAPolicy(configuration.getHAPolicyConfiguration()); } @@ -395,8 +376,7 @@ public class ActiveMQServerImpl implements ActiveMQServer OperationContextImpl.clearContext(); - try - { + try { checkJournalDirectory(); nodeManager = createNodeManager(configuration.getJournalLocation(), false); @@ -406,49 +386,40 @@ public class ActiveMQServerImpl implements ActiveMQServer ActiveMQServerLogger.LOGGER.serverStarting((haPolicy.isBackup() ? "backup" : "live"), configuration); final boolean wasLive = !haPolicy.isBackup(); - if (!haPolicy.isBackup()) - { + if (!haPolicy.isBackup()) { activation = haPolicy.createActivation(this, false, activationParams, shutdownOnCriticalIO); activation.run(); } // The activation on fail-back may change the value of isBackup, for that reason we are // checking again here - if (haPolicy.isBackup()) - { - if (haPolicy.isSharedStore()) - { + if (haPolicy.isBackup()) { + if (haPolicy.isSharedStore()) { activation = haPolicy.createActivation(this, false, activationParams, shutdownOnCriticalIO); } - else - { + else { activation = haPolicy.createActivation(this, wasLive, activationParams, shutdownOnCriticalIO); } backupActivationThread = new Thread(activation, ActiveMQMessageBundle.BUNDLE.activationForServer(this)); backupActivationThread.start(); } - else - { - ActiveMQServerLogger.LOGGER.serverStarted(getVersion().getFullVersion(), nodeManager.getNodeId(), - identity != null ? identity : ""); + else { + ActiveMQServerLogger.LOGGER.serverStarted(getVersion().getFullVersion(), nodeManager.getNodeId(), identity != null ? identity : ""); } // start connector service connectorsService = new ConnectorsService(configuration, storageManager, scheduledPool, postOffice, serviceRegistry); connectorsService.start(); } - finally - { + finally { // this avoids embedded applications using dirty contexts from startup OperationContextImpl.clearContext(); } } @Override - protected final void finalize() throws Throwable - { - if (state != SERVER_STATE.STOPPED) - { + protected final void finalize() throws Throwable { + if (state != SERVER_STATE.STOPPED) { ActiveMQServerLogger.LOGGER.serverFinalisedWIthoutBeingSTopped(); stop(); @@ -457,26 +428,21 @@ public class ActiveMQServerImpl implements ActiveMQServer super.finalize(); } - public void setState(SERVER_STATE state) - { + public void setState(SERVER_STATE state) { this.state = state; } - public SERVER_STATE getState() - { + public SERVER_STATE getState() { return state; } - public void interrupBackupThread(NodeManager nodeManagerInUse) throws InterruptedException - { + public void interrupBackupThread(NodeManager nodeManagerInUse) throws InterruptedException { long timeout = 30000; long start = System.currentTimeMillis(); - while (backupActivationThread.isAlive() && System.currentTimeMillis() - start < timeout) - { - if (nodeManagerInUse != null) - { + while (backupActivationThread.isAlive() && System.currentTimeMillis() - start < timeout) { + if (nodeManagerInUse != null) { nodeManagerInUse.interrupt(); } @@ -486,96 +452,79 @@ public class ActiveMQServerImpl implements ActiveMQServer } - if (System.currentTimeMillis() - start >= timeout) - { + if (System.currentTimeMillis() - start >= timeout) { ActiveMQServerLogger.LOGGER.backupActivationTimeout(); threadDump(); } } - public void resetNodeManager() throws Exception - { + public void resetNodeManager() throws Exception { nodeManager.stop(); - nodeManager = - createNodeManager(configuration.getJournalLocation(), true); + nodeManager = createNodeManager(configuration.getJournalLocation(), true); } - public Activation getActivation() - { + public Activation getActivation() { return activation; } @Override - public HAPolicy getHAPolicy() - { + public HAPolicy getHAPolicy() { return haPolicy; } @Override - public void setHAPolicy(HAPolicy haPolicy) - { + public void setHAPolicy(HAPolicy haPolicy) { this.haPolicy = haPolicy; } @Override - public void setMBeanServer(MBeanServer mbeanServer) - { - if (state == SERVER_STATE.STARTING || state == SERVER_STATE.STARTED) - { + public void setMBeanServer(MBeanServer mbeanServer) { + if (state == SERVER_STATE.STARTING || state == SERVER_STATE.STARTED) { throw ActiveMQMessageBundle.BUNDLE.cannotSetMBeanserver(); } this.mbeanServer = mbeanServer; } - public ExecutorService getThreadPool() - { + public ExecutorService getThreadPool() { return threadPool; } - public void setActivation(SharedNothingLiveActivation activation) - { + public void setActivation(SharedNothingLiveActivation activation) { this.activation = activation; } + /** * Stops the server in a different thread. */ - public final void stopTheServer(final boolean criticalIOError) - { + public final void stopTheServer(final boolean criticalIOError) { ExecutorService executor = Executors.newSingleThreadExecutor(); - executor.submit(new Runnable() - { + executor.submit(new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { stop(false, criticalIOError, false); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorStoppingServer(e); } } }); } - public final void stop() throws Exception - { + public final void stop() throws Exception { stop(false); } - public void addActivationParam(String key, Object val) - { + public void addActivationParam(String key, Object val) { activationParams.put(key, val); } + @Override - public boolean isAddressBound(String address) throws Exception - { + public boolean isAddressBound(String address) throws Exception { return postOffice.isAddressBound(SimpleString.toSimpleString(address)); } - public void threadDump() - { + public void threadDump() { StringWriter str = new StringWriter(); PrintWriter out = new PrintWriter(str); @@ -584,13 +533,11 @@ public class ActiveMQServerImpl implements ActiveMQServer out.println(ActiveMQMessageBundle.BUNDLE.generatingThreadDump()); out.println("*******************************************************************************"); - for (Map.Entry el : stackTrace.entrySet()) - { + for (Map.Entry el : stackTrace.entrySet()) { out.println("==============================================================================="); out.println(ActiveMQMessageBundle.BUNDLE.threadDump(el.getKey(), el.getKey().getName(), el.getKey().getId(), el.getKey().getThreadGroup())); out.println(); - for (StackTraceElement traceEl : el.getValue()) - { + for (StackTraceElement traceEl : el.getValue()) { out.println(traceEl); } } @@ -602,33 +549,28 @@ public class ActiveMQServerImpl implements ActiveMQServer ActiveMQServerLogger.LOGGER.threadDump(str.toString()); } - public final void stop(boolean failoverOnServerShutdown) throws Exception - { + public final void stop(boolean failoverOnServerShutdown) throws Exception { stop(failoverOnServerShutdown, false, false); } @Override - public QueueCreator getJMSQueueCreator() - { + public QueueCreator getJMSQueueCreator() { return jmsQueueCreator; } @Override - public void setJMSQueueCreator(QueueCreator jmsQueueCreator) - { + public void setJMSQueueCreator(QueueCreator jmsQueueCreator) { this.jmsQueueCreator = jmsQueueCreator; } /** * Stops the server - * @param criticalIOError whether we have encountered an IO error with the journal etc + * + * @param criticalIOError whether we have encountered an IO error with the journal etc */ - void stop(boolean failoverOnServerShutdown, final boolean criticalIOError, boolean restarting) throws Exception - { - synchronized (this) - { - if (state == SERVER_STATE.STOPPED || state == SERVER_STATE.STOPPING) - { + void stop(boolean failoverOnServerShutdown, final boolean criticalIOError, boolean restarting) throws Exception { + synchronized (this) { + if (state == SERVER_STATE.STOPPED || state == SERVER_STATE.STOPPING) { return; } state = SERVER_STATE.STOPPING; @@ -639,28 +581,23 @@ public class ActiveMQServerImpl implements ActiveMQServer // we stop the groupingHandler before we stop the cluster manager so binding mappings // aren't removed in case of failover - if (groupingHandler != null) - { + if (groupingHandler != null) { managementService.removeNotificationListener(groupingHandler); groupingHandler.stop(); } stopComponent(clusterManager); - if (remotingService != null) - { + if (remotingService != null) { remotingService.pauseAcceptors(); } // allows for graceful shutdown - if (remotingService != null && configuration.isGracefulShutdownEnabled()) - { + if (remotingService != null && configuration.isGracefulShutdownEnabled()) { long timeout = configuration.getGracefulShutdownTimeout(); - if (timeout == -1) - { + if (timeout == -1) { remotingService.getConnectionCountLatch().await(); } - else - { + else { remotingService.getConnectionCountLatch().await(timeout); } } @@ -708,36 +645,32 @@ public class ActiveMQServerImpl implements ActiveMQServer stopComponent(postOffice); - if (scheduledPool != null && !scheduledPoolSupplied) - { + if (scheduledPool != null && !scheduledPoolSupplied) { // we just interrupt all running tasks, these are supposed to be pings and the like. scheduledPool.shutdownNow(); } stopComponent(memoryManager); - if (threadPool != null && !threadPoolSupplied) - { + if (threadPool != null && !threadPoolSupplied) { threadPool.shutdown(); - try - { - if (!threadPool.awaitTermination(10, TimeUnit.SECONDS)) - { + try { + if (!threadPool.awaitTermination(10, TimeUnit.SECONDS)) { ActiveMQServerLogger.LOGGER.timedOutStoppingThreadpool(threadPool); - for (Runnable r : threadPool.shutdownNow()) - { + for (Runnable r : threadPool.shutdownNow()) { ActiveMQServerLogger.LOGGER.debug("Cancelled the execution of " + r); } } } - catch (InterruptedException e) - { + catch (InterruptedException e) { // Ignore } } - if (!threadPoolSupplied) threadPool = null; - if (!scheduledPoolSupplied) scheduledPool = null; + if (!threadPoolSupplied) + threadPool = null; + if (!scheduledPoolSupplied) + scheduledPool = null; if (securityStore != null) securityStore.stop(); @@ -761,16 +694,13 @@ public class ActiveMQServerImpl implements ActiveMQServer // to display in the log message SimpleString tempNodeID = getNodeID(); - if (activation != null) - { + if (activation != null) { activation.close(failoverOnServerShutdown, restarting); } - if (backupActivationThread != null) - { + if (backupActivationThread != null) { backupActivationThread.join(30000); - if (backupActivationThread.isAlive()) - { + if (backupActivationThread.isAlive()) { ActiveMQServerLogger.LOGGER.backupActivationDidntFinish(this); backupActivationThread.interrupt(); } @@ -786,27 +716,19 @@ public class ActiveMQServerImpl implements ActiveMQServer scaledDownNodeIDs.clear(); - if (identity != null) - { - ActiveMQServerLogger.LOGGER.serverStopped("identity=" + identity + ",version=" + getVersion().getFullVersion(), - tempNodeID); + if (identity != null) { + ActiveMQServerLogger.LOGGER.serverStopped("identity=" + identity + ",version=" + getVersion().getFullVersion(), tempNodeID); } - else - { + else { ActiveMQServerLogger.LOGGER.serverStopped(getVersion().getFullVersion(), tempNodeID); } } - - - public boolean checkLiveIsNotColocated(String nodeId) - { - if (parentServer == null) - { + public boolean checkLiveIsNotColocated(String nodeId) { + if (parentServer == null) { return true; } - else - { + else { return !parentServer.getNodeID().toString().equals(nodeId); } } @@ -817,19 +739,15 @@ public class ActiveMQServerImpl implements ActiveMQServer * If replicating, avoid freezing the replication connection. Helper method for * {@link #stop(boolean, boolean, boolean)}. */ - private void freezeConnections() - { + private void freezeConnections() { activation.freezeConnections(remotingService); // after disconnecting all the clients close all the server sessions so any messages in delivery will be cancelled back to the queue - for (ServerSession serverSession : sessions.values()) - { - try - { + for (ServerSession serverSession : sessions.values()) { + try { serverSession.close(true); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -841,35 +759,26 @@ public class ActiveMQServerImpl implements ActiveMQServer * possible to have this scenario on a real failure (without the use of XA) But at least we will * do our best to avoid it on regular shutdowns */ - private void closeAllServerSessions(final boolean criticalIOError) - { - if (state != SERVER_STATE.STOPPING) - { + private void closeAllServerSessions(final boolean criticalIOError) { + if (state != SERVER_STATE.STOPPING) { return; } - for (ServerSession session : sessions.values()) - { - try - { + for (ServerSession session : sessions.values()) { + try { session.close(true); } - catch (Exception e) - { + catch (Exception e) { // If anything went wrong with closing sessions.. we should ignore it // such as transactions.. etc. ActiveMQServerLogger.LOGGER.errorClosingSessionsWhileStoppingServer(e); } } - if (!criticalIOError) - { - for (ServerSession session : sessions.values()) - { - try - { + if (!criticalIOError) { + for (ServerSession session : sessions.values()) { + try { session.waitContextCompletion(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorClosingSessionsWhileStoppingServer(e); } } @@ -877,8 +786,7 @@ public class ActiveMQServerImpl implements ActiveMQServer } - static void stopComponent(ActiveMQComponent component) throws Exception - { + static void stopComponent(ActiveMQComponent component) throws Exception { if (component != null) component.stop(); } @@ -886,8 +794,7 @@ public class ActiveMQServerImpl implements ActiveMQServer // ActiveMQServer implementation // ----------------------------------------------------------- - public String describe() - { + public String describe() { StringWriter str = new StringWriter(); PrintWriter out = new PrintWriter(str); @@ -896,44 +803,36 @@ public class ActiveMQServerImpl implements ActiveMQServer return str.toString(); } - public String destroyConnectionWithSessionMetadata(String metaKey, String parameterValue) throws Exception - { + public String destroyConnectionWithSessionMetadata(String metaKey, String parameterValue) throws Exception { StringBuffer operationsExecuted = new StringBuffer(); - try - { + try { operationsExecuted.append("**************************************************************************************************\n"); operationsExecuted.append(ActiveMQMessageBundle.BUNDLE.destroyConnectionWithSessionMetadataHeader(metaKey, parameterValue) + "\n"); Set allSessions = getSessions(); ServerSession sessionFound = null; - for (ServerSession session : allSessions) - { - try - { + for (ServerSession session : allSessions) { + try { String value = session.getMetaData(metaKey); - if (value != null && value.equals(parameterValue)) - { + if (value != null && value.equals(parameterValue)) { sessionFound = session; operationsExecuted.append(ActiveMQMessageBundle.BUNDLE.destroyConnectionWithSessionMetadataClosingConnection(sessionFound.toString()) + "\n"); RemotingConnection conn = session.getRemotingConnection(); - if (conn != null) - { + if (conn != null) { conn.fail(ActiveMQMessageBundle.BUNDLE.destroyConnectionWithSessionMetadataSendException(metaKey, parameterValue)); } session.close(true); sessions.remove(session.getName()); } } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e); } } - if (sessionFound == null) - { + if (sessionFound == null) { operationsExecuted.append(ActiveMQMessageBundle.BUNDLE.destroyConnectionWithSessionMetadataNoSessionFound(metaKey, parameterValue) + "\n"); } @@ -941,96 +840,78 @@ public class ActiveMQServerImpl implements ActiveMQServer return operationsExecuted.toString(); } - finally - { + finally { // This operation is critical for the knowledge of the admin, so we need to add info logs for later knowledge ActiveMQServerLogger.LOGGER.info(operationsExecuted.toString()); } } - public void setIdentity(String identity) - { + public void setIdentity(String identity) { this.identity = identity; } - public String getIdentity() - { + public String getIdentity() { return identity; } - public ScheduledExecutorService getScheduledPool() - { + public ScheduledExecutorService getScheduledPool() { return scheduledPool; } - public Configuration getConfiguration() - { + public Configuration getConfiguration() { return configuration; } - public PagingManager getPagingManager() - { + public PagingManager getPagingManager() { return pagingManager; } - public RemotingService getRemotingService() - { + public RemotingService getRemotingService() { return remotingService; } - public StorageManager getStorageManager() - { + public StorageManager getStorageManager() { return storageManager; } - public ActiveMQSecurityManager getSecurityManager() - { + public ActiveMQSecurityManager getSecurityManager() { return securityManager; } - public ManagementService getManagementService() - { + public ManagementService getManagementService() { return managementService; } - public HierarchicalRepository> getSecurityRepository() - { + public HierarchicalRepository> getSecurityRepository() { return securityRepository; } - public NodeManager getNodeManager() - { + public NodeManager getNodeManager() { return nodeManager; } - public HierarchicalRepository getAddressSettingsRepository() - { + public HierarchicalRepository getAddressSettingsRepository() { return addressSettingsRepository; } - public ResourceManager getResourceManager() - { + public ResourceManager getResourceManager() { return resourceManager; } - public Version getVersion() - { + public Version getVersion() { return version; } - public boolean isStarted() - { + public boolean isStarted() { return state == SERVER_STATE.STARTED; } - public ClusterManager getClusterManager() - { + public ClusterManager getClusterManager() { return clusterManager; } - public BackupManager getBackupManager() - { + public BackupManager getBackupManager() { return backupManager; } @@ -1047,51 +928,40 @@ public class ActiveMQServerImpl implements ActiveMQServer final String defaultAddress, final SessionCallback callback, final ServerSessionFactory sessionFactory, - final boolean autoCreateQueues) throws Exception - { + final boolean autoCreateQueues) throws Exception { - if (securityStore != null) - { + if (securityStore != null) { securityStore.authenticate(username, password); } checkSessionLimit(username); final OperationContext context = storageManager.newContext(getExecutorFactory().getExecutor()); - final ServerSessionImpl session = internalCreateSession(name, username, password, minLargeMessageSize, - connection, autoCommitSends, autoCommitAcks, preAcknowledge, - xa, defaultAddress, callback, context, sessionFactory, autoCreateQueues); + final ServerSessionImpl session = internalCreateSession(name, username, password, minLargeMessageSize, connection, autoCommitSends, autoCommitAcks, preAcknowledge, xa, defaultAddress, callback, context, sessionFactory, autoCreateQueues); sessions.put(name, session); return session; } - private void checkSessionLimit(String username) throws Exception - { - if (configuration.getResourceLimitSettings() != null && configuration.getResourceLimitSettings().containsKey(username)) - { + private void checkSessionLimit(String username) throws Exception { + if (configuration.getResourceLimitSettings() != null && configuration.getResourceLimitSettings().containsKey(username)) { ResourceLimitSettings limits = configuration.getResourceLimitSettings().get(username); - if (limits.getMaxConnections() == -1) - { + if (limits.getMaxConnections() == -1) { return; } - else if (limits.getMaxConnections() == 0 || getSessionCountForUser(username) >= limits.getMaxConnections()) - { + else if (limits.getMaxConnections() == 0 || getSessionCountForUser(username) >= limits.getMaxConnections()) { throw ActiveMQMessageBundle.BUNDLE.sessionLimitReached(username, limits.getMaxConnections()); } } } - private int getSessionCountForUser(String username) - { + private int getSessionCountForUser(String username) { int sessionCount = 0; - for (Entry sessionEntry : sessions.entrySet()) - { - if (sessionEntry.getValue().getUsername().toString().equals(username)) - { + for (Entry sessionEntry : sessions.entrySet()) { + if (sessionEntry.getValue().getUsername().toString().equals(username)) { sessionCount++; } } @@ -1099,33 +969,26 @@ public class ActiveMQServerImpl implements ActiveMQServer return sessionCount; } - public void checkQueueCreationLimit(String username) throws Exception - { - if (configuration.getResourceLimitSettings() != null && configuration.getResourceLimitSettings().containsKey(username)) - { + public void checkQueueCreationLimit(String username) throws Exception { + if (configuration.getResourceLimitSettings() != null && configuration.getResourceLimitSettings().containsKey(username)) { ResourceLimitSettings limits = configuration.getResourceLimitSettings().get(username); - if (limits.getMaxQueues() == -1) - { + if (limits.getMaxQueues() == -1) { return; } - else if (limits.getMaxQueues() == 0 || getQueueCountForUser(username) >= limits.getMaxQueues()) - { + else if (limits.getMaxQueues() == 0 || getQueueCountForUser(username) >= limits.getMaxQueues()) { throw ActiveMQMessageBundle.BUNDLE.queueLimitReached(username, limits.getMaxConnections()); } } } - public int getQueueCountForUser(String username) throws Exception - { + public int getQueueCountForUser(String username) throws Exception { Map bindings = postOffice.getAllBindings(); int queuesForUser = 0; - for (Binding binding : bindings.values()) - { - if (binding instanceof LocalQueueBinding && ((LocalQueueBinding) binding).getQueue().getUser().equals(SimpleString.toSimpleString(username))) - { + for (Binding binding : bindings.values()) { + if (binding instanceof LocalQueueBinding && ((LocalQueueBinding) binding).getQueue().getUser().equals(SimpleString.toSimpleString(username))) { queuesForUser++; } } @@ -1134,87 +997,44 @@ public class ActiveMQServerImpl implements ActiveMQServer } - protected ServerSessionImpl internalCreateSession(String name, String username, - String password, int minLargeMessageSize, - RemotingConnection connection, boolean autoCommitSends, - boolean autoCommitAcks, boolean preAcknowledge, boolean xa, - String defaultAddress, SessionCallback callback, - OperationContext context, ServerSessionFactory sessionFactory, - boolean autoCreateJMSQueues) throws Exception - { - if (sessionFactory == null) - { - return new ServerSessionImpl(name, - username, - password, - minLargeMessageSize, - autoCommitSends, - autoCommitAcks, - preAcknowledge, - configuration.isPersistDeliveryCountBeforeDelivery(), - xa, - connection, - storageManager, - postOffice, - resourceManager, - securityStore, - managementService, - this, - configuration.getManagementAddress(), - defaultAddress == null ? null - : new SimpleString(defaultAddress), - callback, - context, - autoCreateJMSQueues ? jmsQueueCreator : null); + protected ServerSessionImpl internalCreateSession(String name, + String username, + String password, + int minLargeMessageSize, + RemotingConnection connection, + boolean autoCommitSends, + boolean autoCommitAcks, + boolean preAcknowledge, + boolean xa, + String defaultAddress, + SessionCallback callback, + OperationContext context, + ServerSessionFactory sessionFactory, + boolean autoCreateJMSQueues) throws Exception { + if (sessionFactory == null) { + return new ServerSessionImpl(name, username, password, minLargeMessageSize, autoCommitSends, autoCommitAcks, preAcknowledge, configuration.isPersistDeliveryCountBeforeDelivery(), xa, connection, storageManager, postOffice, resourceManager, securityStore, managementService, this, configuration.getManagementAddress(), defaultAddress == null ? null : new SimpleString(defaultAddress), callback, context, autoCreateJMSQueues ? jmsQueueCreator : null); } - else - { - return sessionFactory.createCoreSession(name, - username, - password, - minLargeMessageSize, - autoCommitSends, - autoCommitAcks, - preAcknowledge, - configuration.isPersistDeliveryCountBeforeDelivery(), - xa, - connection, - storageManager, - postOffice, - resourceManager, - securityStore, - managementService, - this, - configuration.getManagementAddress(), - defaultAddress == null ? null - : new SimpleString(defaultAddress), - callback, - jmsQueueCreator, - context); + else { + return sessionFactory.createCoreSession(name, username, password, minLargeMessageSize, autoCommitSends, autoCommitAcks, preAcknowledge, configuration.isPersistDeliveryCountBeforeDelivery(), xa, connection, storageManager, postOffice, resourceManager, securityStore, managementService, this, configuration.getManagementAddress(), defaultAddress == null ? null : new SimpleString(defaultAddress), callback, jmsQueueCreator, context); } } @Override - public SecurityStore getSecurityStore() - { + public SecurityStore getSecurityStore() { return securityStore; } - public void removeSession(final String name) throws Exception - { + public void removeSession(final String name) throws Exception { sessions.remove(name); } - public ServerSession lookupSession(String key, String value) - { + public ServerSession lookupSession(String key, String value) { // getSessions is called here in a try to minimize locking the Server while this check is being done Set allSessions = getSessions(); - for (ServerSession session : allSessions) - { + for (ServerSession session : allSessions) { String metaValue = session.getMetaData(key); - if (metaValue != null && metaValue.equals(value)) - { + if (metaValue != null && metaValue.equals(value)) { return session; } } @@ -1222,61 +1042,49 @@ public class ActiveMQServerImpl implements ActiveMQServer return null; } - public synchronized List getSessions(final String connectionID) - { + public synchronized List getSessions(final String connectionID) { Set> sessionEntries = sessions.entrySet(); List matchingSessions = new ArrayList(); - for (Entry sessionEntry : sessionEntries) - { + for (Entry sessionEntry : sessionEntries) { ServerSession serverSession = sessionEntry.getValue(); - if (serverSession.getConnectionID().toString().equals(connectionID)) - { + if (serverSession.getConnectionID().toString().equals(connectionID)) { matchingSessions.add(serverSession); } } return matchingSessions; } - public synchronized Set getSessions() - { + public synchronized Set getSessions() { return new HashSet(sessions.values()); } @Override - public boolean isActive() - { + public boolean isActive() { return activationLatch.getCount() < 1; } @Override - public boolean waitForActivation(long timeout, TimeUnit unit) throws InterruptedException - { + public boolean waitForActivation(long timeout, TimeUnit unit) throws InterruptedException { return activationLatch.await(timeout, unit); } - - public ActiveMQServerControlImpl getActiveMQServerControl() - { + public ActiveMQServerControlImpl getActiveMQServerControl() { return messagingServerControl; } - public int getConnectionCount() - { + public int getConnectionCount() { return remotingService.getConnections().size(); } - public PostOffice getPostOffice() - { + public PostOffice getPostOffice() { return postOffice; } - public QueueFactory getQueueFactory() - { + public QueueFactory getQueueFactory() { return queueFactory; } - public SimpleString getNodeID() - { + public SimpleString getNodeID() { return nodeManager == null ? null : nodeManager.getNodeId(); } @@ -1284,8 +1092,7 @@ public class ActiveMQServerImpl implements ActiveMQServer final SimpleString queueName, final SimpleString filterString, final boolean durable, - final boolean temporary) throws Exception - { + final boolean temporary) throws Exception { return createQueue(address, queueName, filterString, null, durable, temporary, false, false, false); } @@ -1294,8 +1101,7 @@ public class ActiveMQServerImpl implements ActiveMQServer final SimpleString filterString, final SimpleString user, final boolean durable, - final boolean temporary) throws Exception - { + final boolean temporary) throws Exception { return createQueue(address, queueName, filterString, user, durable, temporary, false, false, false); } @@ -1305,8 +1111,7 @@ public class ActiveMQServerImpl implements ActiveMQServer final SimpleString user, final boolean durable, final boolean temporary, - final boolean autoCreated) throws Exception - { + final boolean autoCreated) throws Exception { return createQueue(address, queueName, filterString, user, durable, temporary, false, false, autoCreated); } @@ -1326,43 +1131,34 @@ public class ActiveMQServerImpl implements ActiveMQServer final SimpleString name, final SimpleString filterString, final SimpleString user, - boolean durable) throws Exception - { + boolean durable) throws Exception { Queue queue = createQueue(address, name, filterString, user, durable, !durable, true, !durable, false); - if (!queue.getAddress().equals(address)) - { + if (!queue.getAddress().equals(address)) { throw ActiveMQMessageBundle.BUNDLE.queueSubscriptionBelongsToDifferentAddress(name); } - if (filterString != null && (queue.getFilter() == null || !queue.getFilter().getFilterString().equals(filterString)) || - filterString == null && queue.getFilter() != null) - { + if (filterString != null && (queue.getFilter() == null || !queue.getFilter().getFilterString().equals(filterString)) || filterString == null && queue.getFilter() != null) { throw ActiveMQMessageBundle.BUNDLE.queueSubscriptionBelongsToDifferentFilter(name); } - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Transient Queue " + name + " created on address " + name + - " with filter=" + filterString); + " with filter=" + filterString); } } - - public Queue locateQueue(SimpleString queueName) - { + public Queue locateQueue(SimpleString queueName) { Binding binding = postOffice.getBinding(queueName); - if (binding == null) - { + if (binding == null) { return null; } Bindable queue = binding.getBindable(); - if (!(queue instanceof Queue)) - { + if (!(queue instanceof Queue)) { throw new IllegalStateException("locateQueue should only be used to locate queues"); } @@ -1373,60 +1169,55 @@ public class ActiveMQServerImpl implements ActiveMQServer final SimpleString queueName, final SimpleString filterString, final boolean durable, - final boolean temporary) throws Exception - { + final boolean temporary) throws Exception { ActiveMQServerLogger.LOGGER.deployQueue(queueName); return createQueue(address, queueName, filterString, null, durable, temporary, true, false, false); } - public void destroyQueue(final SimpleString queueName) throws Exception - { + public void destroyQueue(final SimpleString queueName) throws Exception { // The session is passed as an argument to verify if the user has authorization to delete the queue // in some cases (such as temporary queues) this should happen regardless of the authorization // since that will only happen during a session close, which will be used to cleanup on temporary queues destroyQueue(queueName, null, true); } - public void destroyQueue(final SimpleString queueName, final ServerSession session) throws Exception - { + public void destroyQueue(final SimpleString queueName, final ServerSession session) throws Exception { destroyQueue(queueName, session, true); } - public void destroyQueue(final SimpleString queueName, final ServerSession session, final boolean checkConsumerCount) throws Exception - { + public void destroyQueue(final SimpleString queueName, + final ServerSession session, + final boolean checkConsumerCount) throws Exception { destroyQueue(queueName, session, checkConsumerCount, false); } - public void destroyQueue(final SimpleString queueName, final ServerSession session, final boolean checkConsumerCount, final boolean removeConsumers) throws Exception - { + public void destroyQueue(final SimpleString queueName, + final ServerSession session, + final boolean checkConsumerCount, + final boolean removeConsumers) throws Exception { addressSettingsRepository.clearCache(); Binding binding = postOffice.getBinding(queueName); - if (binding == null) - { + if (binding == null) { throw ActiveMQMessageBundle.BUNDLE.noSuchQueue(queueName); } Queue queue = (Queue) binding.getBindable(); // This check is only valid if checkConsumerCount == true - if (checkConsumerCount && queue.getConsumerCount() != 0) - { + if (checkConsumerCount && queue.getConsumerCount() != 0) { throw ActiveMQMessageBundle.BUNDLE.cannotDeleteQueue(queue.getName(), queueName, binding.getClass().getName()); } - if (session != null) - { + if (session != null) { - if (queue.isDurable()) - { + if (queue.isDurable()) { // make sure the user has privileges to delete this queue securityStore.check(binding.getAddress(), CheckType.DELETE_DURABLE_QUEUE, session); } - else - { + else { securityStore.check(binding.getAddress(), CheckType.DELETE_NON_DURABLE_QUEUE, session); } } @@ -1434,70 +1225,56 @@ public class ActiveMQServerImpl implements ActiveMQServer queue.deleteQueue(removeConsumers); } - - public void registerActivateCallback(final ActivateCallback callback) - { + public void registerActivateCallback(final ActivateCallback callback) { activateCallbacks.add(callback); } - public void unregisterActivateCallback(final ActivateCallback callback) - { + public void unregisterActivateCallback(final ActivateCallback callback) { activateCallbacks.remove(callback); } - public ExecutorFactory getExecutorFactory() - { + public ExecutorFactory getExecutorFactory() { return executorFactory; } - public void setGroupingHandler(final GroupingHandler groupingHandler) - { - if (this.groupingHandler != null && managementService != null) - { + public void setGroupingHandler(final GroupingHandler groupingHandler) { + if (this.groupingHandler != null && managementService != null) { // Removing old groupNotification managementService.removeNotificationListener(this.groupingHandler); } this.groupingHandler = groupingHandler; - if (managementService != null) - { + if (managementService != null) { managementService.addNotificationListener(this.groupingHandler); } } - public GroupingHandler getGroupingHandler() - { + public GroupingHandler getGroupingHandler() { return groupingHandler; } - public ReplicationManager getReplicationManager() - { + public ReplicationManager getReplicationManager() { return activation.getReplicationManager(); } - public ConnectorsService getConnectorsService() - { + public ConnectorsService getConnectorsService() { return connectorsService; } - public void deployDivert(DivertConfiguration config) throws Exception - { - if (config.getName() == null) - { + public void deployDivert(DivertConfiguration config) throws Exception { + if (config.getName() == null) { ActiveMQServerLogger.LOGGER.divertWithNoName(); return; } - if (config.getAddress() == null) - { + if (config.getAddress() == null) { ActiveMQServerLogger.LOGGER.divertWithNoAddress(); return; } - if (config.getForwardingAddress() == null) - { + if (config.getForwardingAddress() == null) { ActiveMQServerLogger.LOGGER.divertWithNoForwardingAddress(); return; @@ -1505,8 +1282,7 @@ public class ActiveMQServerImpl implements ActiveMQServer SimpleString sName = new SimpleString(config.getName()); - if (postOffice.getBinding(sName) != null) - { + if (postOffice.getBinding(sName) != null) { ActiveMQServerLogger.LOGGER.divertBindingNotExists(sName); return; @@ -1518,14 +1294,7 @@ public class ActiveMQServerImpl implements ActiveMQServer Filter filter = FilterImpl.createFilter(config.getFilterString()); - Divert divert = new DivertImpl(new SimpleString(config.getForwardingAddress()), - sName, - new SimpleString(config.getRoutingName()), - config.isExclusive(), - filter, - transformer, - postOffice, - storageManager); + Divert divert = new DivertImpl(new SimpleString(config.getForwardingAddress()), sName, new SimpleString(config.getRoutingName()), config.isExclusive(), filter, transformer, postOffice, storageManager); Binding binding = new DivertBinding(storageManager.generateID(), sAddress, divert); @@ -1534,49 +1303,39 @@ public class ActiveMQServerImpl implements ActiveMQServer managementService.registerDivert(divert, config); } - public void destroyDivert(SimpleString name) throws Exception - { + public void destroyDivert(SimpleString name) throws Exception { Binding binding = postOffice.getBinding(name); - if (binding == null) - { + if (binding == null) { throw ActiveMQMessageBundle.BUNDLE.noBindingForDivert(name); } - if (!(binding instanceof DivertBinding)) - { + if (!(binding instanceof DivertBinding)) { throw ActiveMQMessageBundle.BUNDLE.bindingNotDivert(name); } postOffice.removeBinding(name, null); } - public void deployBridge(BridgeConfiguration config) throws Exception - { - if (clusterManager != null) - { + public void deployBridge(BridgeConfiguration config) throws Exception { + if (clusterManager != null) { clusterManager.deployBridge(config); } } - public void destroyBridge(String name) throws Exception - { - if (clusterManager != null) - { + public void destroyBridge(String name) throws Exception { + if (clusterManager != null) { clusterManager.destroyBridge(name); } } - public ServerSession getSessionByID(String sessionName) - { + public ServerSession getSessionByID(String sessionName) { return sessions.get(sessionName); } // PUBLIC ------- @Override - public String toString() - { - if (identity != null) - { + public String toString() { + if (identity != null) { return "ActiveMQServerImpl::" + identity; } return "ActiveMQServerImpl::" + (nodeManager != null ? "serverUUID=" + nodeManager.getUUID() : ""); @@ -1587,62 +1346,43 @@ public class ActiveMQServerImpl implements ActiveMQServer * * @param factory */ - public void replaceQueueFactory(QueueFactory factory) - { + public void replaceQueueFactory(QueueFactory factory) { this.queueFactory = factory; } + private PagingManager createPagingManager() { - private PagingManager createPagingManager() - { - - return new PagingManagerImpl(new PagingStoreFactoryNIO(storageManager, configuration.getPagingLocation(), - configuration.getJournalBufferTimeout_NIO(), - scheduledPool, - executorFactory, - configuration.isJournalSyncNonTransactional(), - shutdownOnCriticalIO), - addressSettingsRepository); + return new PagingManagerImpl(new PagingStoreFactoryNIO(storageManager, configuration.getPagingLocation(), configuration.getJournalBufferTimeout_NIO(), scheduledPool, executorFactory, configuration.isJournalSyncNonTransactional(), shutdownOnCriticalIO), addressSettingsRepository); } /** * This method is protected as it may be used as a hook for creating a custom storage manager (on tests for instance) */ - private StorageManager createStorageManager() - { - if (configuration.isPersistenceEnabled()) - { + private StorageManager createStorageManager() { + if (configuration.isPersistenceEnabled()) { return new JournalStorageManager(configuration, executorFactory, shutdownOnCriticalIO); } return new NullStorageManager(); } - private void callActivateCallbacks() - { - for (ActivateCallback callback : activateCallbacks) - { + private void callActivateCallbacks() { + for (ActivateCallback callback : activateCallbacks) { callback.activated(); } } - private void callPreActiveCallbacks() - { - for (ActivateCallback callback : activateCallbacks) - { + private void callPreActiveCallbacks() { + for (ActivateCallback callback : activateCallbacks) { callback.preActivate(); } } - private void callDeActiveCallbacks() - { - for (ActivateCallback callback : activateCallbacks) - { - try - { + private void callDeActiveCallbacks() { + for (ActivateCallback callback : activateCallbacks) { + try { callback.deActivate(); } - catch (Throwable e) - { + catch (Throwable e) { // https://bugzilla.redhat.com/show_bug.cgi?id=1009530: // we won't interrupt the shutdown sequence because of a failed callback here ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e); @@ -1650,10 +1390,8 @@ public class ActiveMQServerImpl implements ActiveMQServer } } - private void callActivationCompleteCallbacks() - { - for (ActivateCallback callback : activateCallbacks) - { + private void callActivationCompleteCallbacks() { + for (ActivateCallback callback : activateCallbacks) { callback.activationComplete(); } } @@ -1661,25 +1399,20 @@ public class ActiveMQServerImpl implements ActiveMQServer /** * Sets up ActiveMQ Artemis Executor Services. */ - private void initializeExecutorServices() - { + private void initializeExecutorServices() { /* We check to see if a Thread Pool is supplied in the InjectedObjectRegistry. If so we created a new Ordered * Executor based on the provided Thread pool. Otherwise we create a new ThreadPool. */ - if (serviceRegistry.getExecutorService() == null) - { + if (serviceRegistry.getExecutorService() == null) { ThreadFactory tFactory = new ActiveMQThreadFactory("ActiveMQ-server-" + this.toString(), false, getThisClassLoader()); - if (configuration.getThreadPoolMaxSize() == -1) - { + if (configuration.getThreadPoolMaxSize() == -1) { threadPool = Executors.newCachedThreadPool(tFactory); } - else - { + else { threadPool = Executors.newFixedThreadPool(configuration.getThreadPoolMaxSize(), tFactory); } } - else - { + else { threadPool = serviceRegistry.getExecutorService(); this.threadPoolSupplied = true; } @@ -1688,20 +1421,17 @@ public class ActiveMQServerImpl implements ActiveMQServer /* We check to see if a Scheduled Executor Service is provided in the InjectedObjectRegistry. If so we use this * Scheduled ExecutorService otherwise we create a new one. */ - if (serviceRegistry.getScheduledExecutorService() == null) - { + if (serviceRegistry.getScheduledExecutorService() == null) { ThreadFactory tFactory = new ActiveMQThreadFactory("ActiveMQ-scheduled-threads", false, getThisClassLoader()); scheduledPool = new ScheduledThreadPoolExecutor(configuration.getScheduledThreadPoolMaxSize(), tFactory); } - else - { + else { this.scheduledPoolSupplied = true; this.scheduledPool = serviceRegistry.getScheduledExecutorService(); } } - public ServiceRegistry getServiceRegistry() - { + public ServiceRegistry getServiceRegistry() { return serviceRegistry; } @@ -1710,28 +1440,25 @@ public class ActiveMQServerImpl implements ActiveMQServer *

    * After optional intermediary steps, Part 1 is meant to be followed by part 2 * {@link #initialisePart2(boolean)}. + * * @param scalingDown */ - synchronized boolean initialisePart1(boolean scalingDown) throws Exception - { + synchronized boolean initialisePart1(boolean scalingDown) throws Exception { if (state == SERVER_STATE.STOPPED) return false; // Create the pools - we have two pools - one for non scheduled - and another for scheduled initializeExecutorServices(); - if (configuration.getJournalType() == JournalType.ASYNCIO && !AIOSequentialFileFactory.isSupported()) - { + if (configuration.getJournalType() == JournalType.ASYNCIO && !AIOSequentialFileFactory.isSupported()) { ActiveMQServerLogger.LOGGER.switchingNIO(); configuration.setJournalType(JournalType.NIO); } managementService = new ManagementServiceImpl(mbeanServer, configuration); - if (configuration.getMemoryMeasureInterval() != -1) - { - memoryManager = new MemoryManager(configuration.getMemoryWarningThreshold(), - configuration.getMemoryMeasureInterval()); + if (configuration.getMemoryMeasureInterval() != -1) { + memoryManager = new MemoryManager(configuration.getMemoryWarningThreshold(), configuration.getMemoryMeasureInterval()); memoryManager.start(); } @@ -1744,75 +1471,34 @@ public class ActiveMQServerImpl implements ActiveMQServer storageManager = createStorageManager(); - if (configuration.getClusterConfigurations().size() > 0 && - ActiveMQDefaultConfiguration.getDefaultClusterUser().equals(configuration.getClusterUser()) && ActiveMQDefaultConfiguration.getDefaultClusterPassword().equals(configuration.getClusterPassword())) - { + ActiveMQDefaultConfiguration.getDefaultClusterUser().equals(configuration.getClusterUser()) && ActiveMQDefaultConfiguration.getDefaultClusterPassword().equals(configuration.getClusterPassword())) { ActiveMQServerLogger.LOGGER.clusterSecurityRisk(); } - securityStore = new SecurityStoreImpl(securityRepository, - securityManager, - configuration.getSecurityInvalidationInterval(), - configuration.isSecurityEnabled(), - configuration.getClusterUser(), - configuration.getClusterPassword(), - managementService); + securityStore = new SecurityStoreImpl(securityRepository, securityManager, configuration.getSecurityInvalidationInterval(), configuration.isSecurityEnabled(), configuration.getClusterUser(), configuration.getClusterPassword(), managementService); queueFactory = new QueueFactoryImpl(executorFactory, scheduledPool, addressSettingsRepository, storageManager); pagingManager = createPagingManager(); - resourceManager = new ResourceManagerImpl((int) (configuration.getTransactionTimeout() / 1000), - configuration.getTransactionTimeoutScanPeriod(), - scheduledPool); - postOffice = new PostOfficeImpl(this, - storageManager, - pagingManager, - queueFactory, - managementService, - configuration.getMessageExpiryScanPeriod(), - configuration.getMessageExpiryThreadPriority(), - configuration.isWildcardRoutingEnabled(), - configuration.getIDCacheSize(), - configuration.isPersistIDCache(), - addressSettingsRepository); + resourceManager = new ResourceManagerImpl((int) (configuration.getTransactionTimeout() / 1000), configuration.getTransactionTimeoutScanPeriod(), scheduledPool); + postOffice = new PostOfficeImpl(this, storageManager, pagingManager, queueFactory, managementService, configuration.getMessageExpiryScanPeriod(), configuration.getMessageExpiryThreadPriority(), configuration.isWildcardRoutingEnabled(), configuration.getIDCacheSize(), configuration.isPersistIDCache(), addressSettingsRepository); // This can't be created until node id is set - clusterManager = - new ClusterManager(executorFactory, this, postOffice, scheduledPool, managementService, configuration, - nodeManager, haPolicy.isBackup()); + clusterManager = new ClusterManager(executorFactory, this, postOffice, scheduledPool, managementService, configuration, nodeManager, haPolicy.isBackup()); backupManager = new BackupManager(this, executorFactory, scheduledPool, nodeManager, configuration, clusterManager); clusterManager.deploy(); - remotingService = new RemotingServiceImpl(clusterManager, - configuration, - this, - managementService, - scheduledPool, - protocolManagerFactories, - executorFactory.getExecutor(), - serviceRegistry); + remotingService = new RemotingServiceImpl(clusterManager, configuration, this, managementService, scheduledPool, protocolManagerFactories, executorFactory.getExecutor(), serviceRegistry); - messagingServerControl = managementService.registerServer(postOffice, - storageManager, - configuration, - addressSettingsRepository, - securityRepository, - resourceManager, - remotingService, - this, - queueFactory, - scheduledPool, - pagingManager, - haPolicy.isBackup()); + messagingServerControl = managementService.registerServer(postOffice, storageManager, configuration, addressSettingsRepository, securityRepository, resourceManager, remotingService, this, queueFactory, scheduledPool, pagingManager, haPolicy.isBackup()); // Address settings need to deployed initially, since they're require on paging manager.start() - if (!scalingDown) - { + if (!scalingDown) { deployAddressSettingsFromConfiguration(); } @@ -1836,12 +1522,10 @@ public class ActiveMQServerImpl implements ActiveMQServer /* * Load the data, and start remoting service so clients can connect */ - synchronized void initialisePart2(boolean scalingDown) throws Exception - { + synchronized void initialisePart2(boolean scalingDown) throws Exception { // Load the journal and populate queues, transactions and caches in memory - if (state == SERVER_STATE.STOPPED || state == SERVER_STATE.STOPPING) - { + if (state == SERVER_STATE.STOPPED || state == SERVER_STATE.STOPPING) { return; } @@ -1849,17 +1533,13 @@ public class ActiveMQServerImpl implements ActiveMQServer JournalLoadInformation[] journalInfo = loadJournals(); - final ServerInfo dumper = new ServerInfo(this, pagingManager); long dumpInfoInterval = configuration.getServerDumpInterval(); - if (dumpInfoInterval > 0) - { - scheduledPool.scheduleWithFixedDelay(new Runnable() - { - public void run() - { + if (dumpInfoInterval > 0) { + scheduledPool.scheduleWithFixedDelay(new Runnable() { + public void run() { ActiveMQServerLogger.LOGGER.dumpServerInfo(dumper.dump()); } }, 0, dumpInfoInterval, TimeUnit.MILLISECONDS); @@ -1870,41 +1550,35 @@ public class ActiveMQServerImpl implements ActiveMQServer // Deploy any predefined queues deployQueuesFromConfiguration(); - // We need to call this here, this gives any dependent server a chance to deploy its own addresses // this needs to be done before clustering is fully activated callActivateCallbacks(); - if (!scalingDown) - { + if (!scalingDown) { // Deploy any pre-defined diverts deployDiverts(); - if (groupingHandler != null) - { + if (groupingHandler != null) { groupingHandler.start(); } - // We do this at the end - we don't want things like MDBs or other connections connecting to a backup server until - // it is activated + // We do this at the end - we don't want things like MDBs or other connections connecting to a backup server until + // it is activated - if (groupingHandler != null && groupingHandler instanceof LocalGroupingHandler) - { + if (groupingHandler != null && groupingHandler instanceof LocalGroupingHandler) { clusterManager.start(); groupingHandler.awaitBindings(); remotingService.start(); } - else - { + else { remotingService.start(); clusterManager.start(); } - if (nodeManager.getNodeId() == null) - { + if (nodeManager.getNodeId() == null) { throw ActiveMQMessageBundle.BUNDLE.nodeIdNull(); } @@ -1913,53 +1587,33 @@ public class ActiveMQServerImpl implements ActiveMQServer } } - public void completeActivation() throws Exception - { + public void completeActivation() throws Exception { setState(ActiveMQServerImpl.SERVER_STATE.STARTED); getRemotingService().startAcceptors(); activationLatch.countDown(); callActivationCompleteCallbacks(); } - private void deploySecurityFromConfiguration() - { - for (Map.Entry> entry : configuration.getSecurityRoles().entrySet()) - { + private void deploySecurityFromConfiguration() { + for (Map.Entry> entry : configuration.getSecurityRoles().entrySet()) { securityRepository.addMatch(entry.getKey(), entry.getValue(), true); } } - private void deployQueuesFromConfiguration() throws Exception - { - for (CoreQueueConfiguration config : configuration.getQueueConfigurations()) - { - deployQueue(SimpleString.toSimpleString(config.getAddress()), - SimpleString.toSimpleString(config.getName()), - SimpleString.toSimpleString(config.getFilterString()), - config.isDurable(), - false); + private void deployQueuesFromConfiguration() throws Exception { + for (CoreQueueConfiguration config : configuration.getQueueConfigurations()) { + deployQueue(SimpleString.toSimpleString(config.getAddress()), SimpleString.toSimpleString(config.getName()), SimpleString.toSimpleString(config.getFilterString()), config.isDurable(), false); } } - private void deployAddressSettingsFromConfiguration() - { - for (Map.Entry entry : configuration.getAddressesSettings().entrySet()) - { + private void deployAddressSettingsFromConfiguration() { + for (Map.Entry entry : configuration.getAddressesSettings().entrySet()) { addressSettingsRepository.addMatch(entry.getKey(), entry.getValue(), true); } } - private JournalLoadInformation[] loadJournals() throws Exception - { - JournalLoader journalLoader = activation.createJournalLoader(postOffice, - pagingManager, - storageManager, - queueFactory, - nodeManager, - managementService, - groupingHandler, - configuration, - parentServer); + private JournalLoadInformation[] loadJournals() throws Exception { + JournalLoader journalLoader = activation.createJournalLoader(postOffice, pagingManager, storageManager, queueFactory, nodeManager, managementService, groupingHandler, configuration, parentServer); JournalLoadInformation[] journalInfo = new JournalLoadInformation[2]; @@ -1973,7 +1627,6 @@ public class ActiveMQServerImpl implements ActiveMQServer Map queueBindingInfosMap = new HashMap(); - journalLoader.initQueues(queueBindingInfosMap, queueBindingInfos); journalLoader.handleGroupingBindings(groupingInfos); @@ -1984,19 +1637,11 @@ public class ActiveMQServerImpl implements ActiveMQServer List pendingNonTXPageCounter = new LinkedList(); - journalInfo[1] = storageManager.loadMessageJournal(postOffice, - pagingManager, - resourceManager, - queueBindingInfosMap, - duplicateIDMap, - pendingLargeMessages, - pendingNonTXPageCounter, - journalLoader); + journalInfo[1] = storageManager.loadMessageJournal(postOffice, pagingManager, resourceManager, queueBindingInfosMap, duplicateIDMap, pendingLargeMessages, pendingNonTXPageCounter, journalLoader); journalLoader.handleDuplicateIds(duplicateIDMap); - for (Pair msgToDelete : pendingLargeMessages) - { + for (Pair msgToDelete : pendingLargeMessages) { ActiveMQServerLogger.LOGGER.deletingPendingMessage(msgToDelete); LargeServerMessage msg = storageManager.createLargeMessage(); msg.setMessageID(msgToDelete.getB()); @@ -2005,14 +1650,11 @@ public class ActiveMQServerImpl implements ActiveMQServer msg.deleteFile(); } - if (pendingNonTXPageCounter.size() != 0) - { - try - { + if (pendingNonTXPageCounter.size() != 0) { + try { journalLoader.recoverPendingPageCounters(pendingNonTXPageCounter); } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQServerLogger.LOGGER.errorRecoveringPageCounter(e); } } @@ -2022,29 +1664,19 @@ public class ActiveMQServerImpl implements ActiveMQServer return journalInfo; } - /** * @throws Exception */ - private void recoverStoredConfigs() throws Exception - { + private void recoverStoredConfigs() throws Exception { List adsettings = storageManager.recoverAddressSettings(); - for (PersistedAddressSetting set : adsettings) - { + for (PersistedAddressSetting set : adsettings) { addressSettingsRepository.addMatch(set.getAddressMatch().toString(), set.getSetting()); } List roles = storageManager.recoverPersistedRoles(); - for (PersistedRoles roleItem : roles) - { - Set setRoles = SecurityFormatter.createSecurity(roleItem.getSendRoles(), - roleItem.getConsumeRoles(), - roleItem.getCreateDurableQueueRoles(), - roleItem.getDeleteDurableQueueRoles(), - roleItem.getCreateNonDurableQueueRoles(), - roleItem.getDeleteNonDurableQueueRoles(), - roleItem.getManageRoles()); + for (PersistedRoles roleItem : roles) { + Set setRoles = SecurityFormatter.createSecurity(roleItem.getSendRoles(), roleItem.getConsumeRoles(), roleItem.getCreateDurableQueueRoles(), roleItem.getDeleteDurableQueueRoles(), roleItem.getCreateNonDurableQueueRoles(), roleItem.getDeleteNonDurableQueueRoles(), roleItem.getManageRoles()); securityRepository.addMatch(roleItem.getAddressMatch().toString(), setRoles); } @@ -2058,18 +1690,14 @@ public class ActiveMQServerImpl implements ActiveMQServer final boolean temporary, final boolean ignoreIfExists, final boolean transientQueue, - final boolean autoCreated) throws Exception - { + final boolean autoCreated) throws Exception { QueueBinding binding = (QueueBinding) postOffice.getBinding(queueName); - if (binding != null) - { - if (ignoreIfExists) - { + if (binding != null) { + if (ignoreIfExists) { return binding.getQueue(); } - else - { + else { throw ActiveMQMessageBundle.BUNDLE.queueAlreadyExists(queueName); } } @@ -2081,116 +1709,72 @@ public class ActiveMQServerImpl implements ActiveMQServer PageSubscription pageSubscription; - if (filterString != null && filterString.toString().equals(GENERIC_IGNORED_FILTER)) - { + if (filterString != null && filterString.toString().equals(GENERIC_IGNORED_FILTER)) { pageSubscription = null; } - else - { - pageSubscription = pagingManager.getPageStore(address) - .getCursorProvider() - .createSubscription(queueID, filter, durable); + else { + pageSubscription = pagingManager.getPageStore(address).getCursorProvider().createSubscription(queueID, filter, durable); } - final Queue queue = queueFactory.createQueue(queueID, - address, - queueName, - filter, - pageSubscription, - user, - durable, - temporary, - autoCreated); + final Queue queue = queueFactory.createQueue(queueID, address, queueName, filter, pageSubscription, user, durable, temporary, autoCreated); - if (transientQueue) - { + if (transientQueue) { queue.setConsumersRefCount(new TransientQueueManagerImpl(this, queueName)); } - else if (autoCreated) - { + else if (autoCreated) { queue.setConsumersRefCount(new AutoCreatedQueueManagerImpl(this, queueName)); } binding = new LocalQueueBinding(address, queue, nodeManager.getNodeId()); - if (durable) - { + if (durable) { storageManager.addQueueBinding(txID, binding); } - try - { + try { postOffice.addBinding(binding); - if (durable) - { + if (durable) { storageManager.commitBindings(txID); } } - catch (Exception e) - { - try - { - if (durable) - { + catch (Exception e) { + try { + if (durable) { storageManager.rollbackBindings(txID); } - if (queue != null) - { + if (queue != null) { queue.close(); } - if (pageSubscription != null) - { + if (pageSubscription != null) { pageSubscription.destroy(); } } - catch (Throwable ignored) - { + catch (Throwable ignored) { ActiveMQServerLogger.LOGGER.debug(ignored.getMessage(), ignored); } throw e; } - managementService.registerAddress(address); managementService.registerQueue(queue, address, storageManager); return queue; } - private void deployDiverts() throws Exception - { - for (DivertConfiguration config : configuration.getDivertConfigurations()) - { + private void deployDiverts() throws Exception { + for (DivertConfiguration config : configuration.getDivertConfigurations()) { deployDivert(config); } } - private void deployGroupingHandlerConfiguration(final GroupingHandlerConfiguration config) throws Exception - { - if (config != null) - { + private void deployGroupingHandlerConfiguration(final GroupingHandlerConfiguration config) throws Exception { + if (config != null) { GroupingHandler groupingHandler1; - if (config.getType() == GroupingHandlerConfiguration.TYPE.LOCAL) - { - groupingHandler1 = - new LocalGroupingHandler(executorFactory, - scheduledPool, - managementService, - config.getName(), - config.getAddress(), - getStorageManager(), - config.getTimeout(), - config.getGroupTimeout(), - config.getReaperPeriod()); + if (config.getType() == GroupingHandlerConfiguration.TYPE.LOCAL) { + groupingHandler1 = new LocalGroupingHandler(executorFactory, scheduledPool, managementService, config.getName(), config.getAddress(), getStorageManager(), config.getTimeout(), config.getGroupTimeout(), config.getReaperPeriod()); } - else - { - groupingHandler1 = - new RemoteGroupingHandler(executorFactory, managementService, - config.getName(), - config.getAddress(), - config.getTimeout(), - config.getGroupTimeout()); + else { + groupingHandler1 = new RemoteGroupingHandler(executorFactory, managementService, config.getName(), config.getAddress(), config.getTimeout(), config.getGroupTimeout()); } this.groupingHandler = groupingHandler1; @@ -2199,12 +1783,9 @@ public class ActiveMQServerImpl implements ActiveMQServer } } - private static ClassLoader getThisClassLoader() - { - return AccessController.doPrivileged(new PrivilegedAction() - { - public ClassLoader run() - { + private static ClassLoader getThisClassLoader() { + return AccessController.doPrivileged(new PrivilegedAction() { + public ClassLoader run() { return ClientSessionFactoryImpl.class.getClassLoader(); } }); @@ -2214,37 +1795,28 @@ public class ActiveMQServerImpl implements ActiveMQServer /** * Check if journal directory exists or create it (if configured to do so) */ - void checkJournalDirectory() - { + void checkJournalDirectory() { File journalDir = configuration.getJournalLocation(); - if (!journalDir.exists() && configuration.isPersistenceEnabled()) - { - if (configuration.isCreateJournalDir()) - { + if (!journalDir.exists() && configuration.isPersistenceEnabled()) { + if (configuration.isCreateJournalDir()) { journalDir.mkdirs(); } - else - { + else { throw ActiveMQMessageBundle.BUNDLE.cannotCreateDir(journalDir.getAbsolutePath()); } } } - // Inner classes // -------------------------------------------------------------------------------- + public final class ShutdownOnCriticalErrorListener implements IOCriticalErrorListener { - - public final class ShutdownOnCriticalErrorListener implements IOCriticalErrorListener - { boolean failedAlready = false; - public synchronized void onIOException(Exception cause, String message, SequentialFile file) - { - if (!failedAlready) - { + public synchronized void onIOException(Exception cause, String message, SequentialFile file) { + if (!failedAlready) { failedAlready = true; ActiveMQServerLogger.LOGGER.ioCriticalIOError(message, file.toString(), cause); @@ -2254,57 +1826,45 @@ public class ActiveMQServerImpl implements ActiveMQServer } } - public void addProtocolManagerFactory(ProtocolManagerFactory factory) - { + public void addProtocolManagerFactory(ProtocolManagerFactory factory) { protocolManagerFactories.add(factory); } - public void removeProtocolManagerFactory(ProtocolManagerFactory factory) - { + public void removeProtocolManagerFactory(ProtocolManagerFactory factory) { protocolManagerFactories.remove(factory); } @Override - public ActiveMQServer createBackupServer(Configuration configuration) - { + public ActiveMQServer createBackupServer(Configuration configuration) { return new ActiveMQServerImpl(configuration, null, securityManager, this); } @Override - public void addScaledDownNode(SimpleString scaledDownNodeId) - { - synchronized (scaledDownNodeIDs) - { + public void addScaledDownNode(SimpleString scaledDownNodeId) { + synchronized (scaledDownNodeIDs) { scaledDownNodeIDs.add(scaledDownNodeId); - if (scaledDownNodeIDs.size() > 10) - { + if (scaledDownNodeIDs.size() > 10) { scaledDownNodeIDs.remove(10); } } } @Override - public boolean hasScaledDown(SimpleString scaledDownNodeId) - { + public boolean hasScaledDown(SimpleString scaledDownNodeId) { return scaledDownNodeIDs.contains(scaledDownNodeId); } - - int countNumberOfCopiedJournals() - { + int countNumberOfCopiedJournals() { //will use the main journal to check for how many backups have been kept File journalDir = new File(configuration.getJournalDirectory()); final String fileName = journalDir.getName(); int numberOfbackupsSaved = 0; //fine if it doesn't exist, we aren't using file based persistence so it's no issue - if (journalDir.exists()) - { + if (journalDir.exists()) { File parentFile = new File(journalDir.getParent()); - String[] backupJournals = parentFile.list(new FilenameFilter() - { + String[] backupJournals = parentFile.list(new FilenameFilter() { @Override - public boolean accept(File dir, String name) - { + public boolean accept(File dir, String name) { return name.startsWith(fileName) && !name.matches(fileName); } }); @@ -2319,27 +1879,18 @@ public class ActiveMQServerImpl implements ActiveMQServer * Use case is a server, upon restarting, finding a former backup running in its place. It will * move any older data away and log a warning about it. */ - void moveServerData() - { - String[] dataDirs = - new String[]{configuration.getBindingsDirectory(), - configuration.getJournalDirectory(), - configuration.getPagingDirectory(), - configuration.getLargeMessagesDirectory()}; + void moveServerData() { + String[] dataDirs = new String[]{configuration.getBindingsDirectory(), configuration.getJournalDirectory(), configuration.getPagingDirectory(), configuration.getLargeMessagesDirectory()}; boolean allEmpty = true; int lowestSuffixForMovedData = 1; boolean redo = true; - while (redo) - { + while (redo) { redo = false; - for (String dir : dataDirs) - { + for (String dir : dataDirs) { File fDir = new File(dir); - if (fDir.exists()) - { - if (!fDir.isDirectory()) - { + if (fDir.exists()) { + if (!fDir.isDirectory()) { throw ActiveMQMessageBundle.BUNDLE.journalDirIsFile(fDir); } @@ -2348,8 +1899,7 @@ public class ActiveMQServerImpl implements ActiveMQServer } String sanitizedPath = fDir.getPath(); - while (new File(sanitizedPath + lowestSuffixForMovedData).exists()) - { + while (new File(sanitizedPath + lowestSuffixForMovedData).exists()) { lowestSuffixForMovedData++; redo = true; } @@ -2358,14 +1908,11 @@ public class ActiveMQServerImpl implements ActiveMQServer if (allEmpty) return; - for (String dir0 : dataDirs) - { + for (String dir0 : dataDirs) { File dir = new File(dir0); File newPath = new File(dir.getPath() + lowestSuffixForMovedData); - if (dir.exists()) - { - if (!dir.renameTo(newPath)) - { + if (dir.exists()) { + if (!dir.renameTo(newPath)) { throw ActiveMQMessageBundle.BUNDLE.couldNotMoveJournal(dir); } @@ -2378,18 +1925,14 @@ public class ActiveMQServerImpl implements ActiveMQServer File dirToRecreate = new File(dir0); int count = 0; - while (!dirToRecreate.exists() && !dirToRecreate.mkdir()) - { - try - { + while (!dirToRecreate.exists() && !dirToRecreate.mkdir()) { + try { Thread.sleep(1000); } - catch (InterruptedException e) - { + catch (InterruptedException e) { } count++; - if (count == 5) - { + if (count == 5) { throw ActiveMQMessageBundle.BUNDLE.cannotCreateDir(dir.getPath()); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/AnyLiveNodeLocatorForReplication.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/AnyLiveNodeLocatorForReplication.java index 6983427375..6d2923a064 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/AnyLiveNodeLocatorForReplication.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/AnyLiveNodeLocatorForReplication.java @@ -35,8 +35,8 @@ import org.apache.activemq.artemis.core.server.cluster.qourum.SharedNothingBacku * This implementation looks for any available live node, once tried with no success it is marked as * tried and the next available is used. */ -public class AnyLiveNodeLocatorForReplication extends LiveNodeLocator -{ +public class AnyLiveNodeLocatorForReplication extends LiveNodeLocator { + private final Lock lock = new ReentrantLock(); private final Condition condition = lock.newCondition(); private final ActiveMQServerImpl server; @@ -45,67 +45,52 @@ public class AnyLiveNodeLocatorForReplication extends LiveNodeLocator private String nodeID; - public AnyLiveNodeLocatorForReplication(SharedNothingBackupQuorum backupQuorum, ActiveMQServerImpl server) - { + public AnyLiveNodeLocatorForReplication(SharedNothingBackupQuorum backupQuorum, ActiveMQServerImpl server) { super(backupQuorum); this.server = server; } @Override - public void locateNode() throws ActiveMQException - { + public void locateNode() throws ActiveMQException { locateNode(-1L); } @Override - public void locateNode(long timeout) throws ActiveMQException - { + public void locateNode(long timeout) throws ActiveMQException { //first time - try - { + try { lock.lock(); - if (untriedConnectors.isEmpty()) - { - try - { - if (timeout != -1L) - { + if (untriedConnectors.isEmpty()) { + try { + if (timeout != -1L) { condition.await(timeout, TimeUnit.MILLISECONDS); } - else - { + else { condition.await(); } } - catch (InterruptedException e) - { + catch (InterruptedException e) { } } } - finally - { + finally { lock.unlock(); } } @Override - public void nodeUP(TopologyMember topologyMember, boolean last) - { - try - { + public void nodeUP(TopologyMember topologyMember, boolean last) { + try { lock.lock(); - Pair connector = - new Pair(topologyMember.getLive(), topologyMember.getBackup()); + Pair connector = new Pair(topologyMember.getLive(), topologyMember.getBackup()); - if (server.checkLiveIsNotColocated(topologyMember.getNodeId())) - { + if (server.checkLiveIsNotColocated(topologyMember.getNodeId())) { untriedConnectors.put(topologyMember.getNodeId(), connector); condition.signal(); } } - finally - { + finally { lock.unlock(); } } @@ -117,65 +102,52 @@ public class AnyLiveNodeLocatorForReplication extends LiveNodeLocator * TODO: there will be a better way to do this by finding which nodes backup has gone down. */ @Override - public void nodeDown(long eventUID, String nodeID) - { - try - { + public void nodeDown(long eventUID, String nodeID) { + try { lock.lock(); untriedConnectors.putAll(triedConnectors); triedConnectors.clear(); - if (untriedConnectors.size() > 0) - { + if (untriedConnectors.size() > 0) { condition.signal(); } } - finally - { + finally { lock.unlock(); } } @Override - public String getNodeID() - { + public String getNodeID() { return nodeID; } @Override - public Pair getLiveConfiguration() - { - try - { + public Pair getLiveConfiguration() { + try { lock.lock(); Iterator iterator = untriedConnectors.keySet().iterator(); //sanity check but this should never happen - if (iterator.hasNext()) - { + if (iterator.hasNext()) { nodeID = iterator.next(); } return untriedConnectors.get(nodeID); } - finally - { + finally { lock.unlock(); } } @Override - public void notifyRegistrationFailed(boolean alreadyReplicating) - { - try - { + public void notifyRegistrationFailed(boolean alreadyReplicating) { + try { lock.lock(); Pair tc = untriedConnectors.remove(nodeID); //it may have been removed - if (tc != null) - { + if (tc != null) { triedConnectors.put(nodeID, tc); } } - finally - { + finally { lock.unlock(); } super.notifyRegistrationFailed(alreadyReplicating); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/AnyLiveNodeLocatorForScaleDown.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/AnyLiveNodeLocatorForScaleDown.java index c2f63dce04..5f630a66cc 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/AnyLiveNodeLocatorForScaleDown.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/AnyLiveNodeLocatorForScaleDown.java @@ -35,8 +35,8 @@ import org.apache.activemq.artemis.core.server.LiveNodeLocator; * This implementation looks for any available live node, once tried with no success it is marked as * tried and the next available is used. */ -public class AnyLiveNodeLocatorForScaleDown extends LiveNodeLocator -{ +public class AnyLiveNodeLocatorForScaleDown extends LiveNodeLocator { + private final Lock lock = new ReentrantLock(); private final Condition condition = lock.newCondition(); private final ActiveMQServerImpl server; @@ -45,137 +45,108 @@ public class AnyLiveNodeLocatorForScaleDown extends LiveNodeLocator private String nodeID; private String myNodeID; - public AnyLiveNodeLocatorForScaleDown(ActiveMQServerImpl server) - { + public AnyLiveNodeLocatorForScaleDown(ActiveMQServerImpl server) { super(); this.server = server; this.myNodeID = server.getNodeID().toString(); } @Override - public void locateNode() throws ActiveMQException - { + public void locateNode() throws ActiveMQException { locateNode(-1L); } @Override - public void locateNode(long timeout) throws ActiveMQException - { - try - { + public void locateNode(long timeout) throws ActiveMQException { + try { lock.lock(); - if (connectors.isEmpty()) - { - try - { - if (timeout != -1L) - { - if (!condition.await(timeout, TimeUnit.MILLISECONDS)) - { + if (connectors.isEmpty()) { + try { + if (timeout != -1L) { + if (!condition.await(timeout, TimeUnit.MILLISECONDS)) { throw new ActiveMQException("Timeout elapsed while waiting for cluster node"); } } - else - { + else { condition.await(); } } - catch (InterruptedException e) - { + catch (InterruptedException e) { } } } - finally - { + finally { lock.unlock(); } } @Override - public void nodeUP(TopologyMember topologyMember, boolean last) - { - try - { + public void nodeUP(TopologyMember topologyMember, boolean last) { + try { lock.lock(); Pair connector = new Pair<>(topologyMember.getLive(), topologyMember.getBackup()); - if (topologyMember.getNodeId().equals(myNodeID)) - { - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + if (topologyMember.getNodeId().equals(myNodeID)) { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace(this + "::informing node about itself, nodeUUID=" + - server.getNodeID() + ", connectorPair=" + topologyMember + ", this = " + this); + server.getNodeID() + ", connectorPair=" + topologyMember + ", this = " + this); } return; } - if (server.checkLiveIsNotColocated(topologyMember.getNodeId())) - { + if (server.checkLiveIsNotColocated(topologyMember.getNodeId())) { connectors.put(topologyMember.getNodeId(), connector); condition.signal(); } } - finally - { + finally { lock.unlock(); } } @Override - public void nodeDown(long eventUID, String nodeID) - { - try - { + public void nodeDown(long eventUID, String nodeID) { + try { lock.lock(); connectors.remove(nodeID); - if (connectors.size() > 0) - { + if (connectors.size() > 0) { condition.signal(); } } - finally - { + finally { lock.unlock(); } } @Override - public String getNodeID() - { + public String getNodeID() { return nodeID; } @Override - public Pair getLiveConfiguration() - { - try - { + public Pair getLiveConfiguration() { + try { lock.lock(); Iterator iterator = connectors.keySet().iterator(); //sanity check but this should never happen - if (iterator.hasNext()) - { + if (iterator.hasNext()) { nodeID = iterator.next(); } return connectors.get(nodeID); } - finally - { + finally { lock.unlock(); } } @Override - public void notifyRegistrationFailed(boolean alreadyReplicating) - { - try - { + public void notifyRegistrationFailed(boolean alreadyReplicating) { + try { lock.lock(); connectors.remove(nodeID); } - finally - { + finally { lock.unlock(); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/AutoCreatedQueueManagerImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/AutoCreatedQueueManagerImpl.java index 294298e8b1..f8fa60f742 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/AutoCreatedQueueManagerImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/AutoCreatedQueueManagerImpl.java @@ -23,38 +23,31 @@ import org.apache.activemq.artemis.core.server.AutoCreatedQueueManager; import org.apache.activemq.artemis.core.server.Queue; import org.apache.activemq.artemis.utils.ReferenceCounterUtil; -public class AutoCreatedQueueManagerImpl implements AutoCreatedQueueManager -{ +public class AutoCreatedQueueManagerImpl implements AutoCreatedQueueManager { + private final SimpleString queueName; private final ActiveMQServer server; - private final Runnable runnable = new Runnable() - { - public void run() - { - try - { + private final Runnable runnable = new Runnable() { + public void run() { + try { Queue queue = server.locateQueue(queueName); long consumerCount = queue.getConsumerCount(); long messageCount = queue.getMessageCount(); - if (server.locateQueue(queueName).getMessageCount() == 0) - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (server.locateQueue(queueName).getMessageCount() == 0) { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("deleting auto-created queue \"" + queueName + "\" because consumerCount = " + consumerCount + " and messageCount = " + messageCount); } server.destroyQueue(queueName, null, false); } - else if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + else if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("NOT deleting auto-created queue \"" + queueName + "\" because consumerCount = " + consumerCount + " and messageCount = " + messageCount); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorRemovingAutoCreatedQueue(e, queueName); } } @@ -62,28 +55,24 @@ public class AutoCreatedQueueManagerImpl implements AutoCreatedQueueManager private final ReferenceCounterUtil referenceCounterUtil = new ReferenceCounterUtil(runnable); - public AutoCreatedQueueManagerImpl(ActiveMQServer server, SimpleString queueName) - { + public AutoCreatedQueueManagerImpl(ActiveMQServer server, SimpleString queueName) { this.server = server; this.queueName = queueName; } @Override - public int increment() - { + public int increment() { return referenceCounterUtil.increment(); } @Override - public int decrement() - { + public int decrement() { return referenceCounterUtil.decrement(); } @Override - public SimpleString getQueueName() - { + public SimpleString getQueueName() { return queueName; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/BackupRecoveryJournalLoader.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/BackupRecoveryJournalLoader.java index 33f23c726d..77894bfaa1 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/BackupRecoveryJournalLoader.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/BackupRecoveryJournalLoader.java @@ -44,8 +44,8 @@ import java.util.Map; * Instead of loading into its own post office this will use its parent server (the actual live server) and load into that. * Since the server is already running we have to make sure we don't route any message that may subsequently get deleted or acked. * */ -public class BackupRecoveryJournalLoader extends PostOfficeJournalLoader -{ +public class BackupRecoveryJournalLoader extends PostOfficeJournalLoader { + private ActiveMQServer parentServer; private ServerLocator locator; private final ClusterController clusterController; @@ -60,8 +60,7 @@ public class BackupRecoveryJournalLoader extends PostOfficeJournalLoader Configuration configuration, ActiveMQServer parentServer, ServerLocatorInternal locator, - ClusterController clusterController) - { + ClusterController clusterController) { super(postOffice, pagingManager, storageManager, queueFactory, nodeManager, managementService, groupingHandler, configuration); this.parentServer = parentServer; @@ -70,38 +69,34 @@ public class BackupRecoveryJournalLoader extends PostOfficeJournalLoader } @Override - public void handleGroupingBindings(List< GroupingInfo > groupingInfos) - { + public void handleGroupingBindings(List groupingInfos) { //currently only the node that is configured with the local group handler can recover these as all other nodes are //remote handlers, this means that you can only use FULL backup server when using group handlers. //todo maybe in the future we can restart the handler on the live server as a local handler and redistribute the state - if (groupingInfos != null && groupingInfos.size() > 0) - { + if (groupingInfos != null && groupingInfos.size() > 0) { ActiveMQServerLogger.LOGGER.groupBindingsOnRecovery(); } } @Override - public void handleDuplicateIds(Map>> duplicateIDMap) throws Exception - { + public void handleDuplicateIds(Map>> duplicateIDMap) throws Exception { //nothing to do here so override so we dont bother creating the caches } @Override - public void postLoad(Journal messageJournal, ResourceManager resourceManager, Map>> duplicateIDMap) throws Exception - { + public void postLoad(Journal messageJournal, + ResourceManager resourceManager, + Map>> duplicateIDMap) throws Exception { ScaleDownHandler scaleDownHandler = new ScaleDownHandler(pagingManager, postOffice, nodeManager, clusterController, parentServer.getStorageManager()); locator.setProtocolManagerFactory(ActiveMQServerSideProtocolManagerFactory.getInstance()); - try (ClientSessionFactory sessionFactory = locator.createSessionFactory()) - { + try (ClientSessionFactory sessionFactory = locator.createSessionFactory()) { scaleDownHandler.scaleDown(sessionFactory, resourceManager, duplicateIDMap, parentServer.getConfiguration().getManagementAddress(), parentServer.getNodeID()); } } @Override - public void cleanUp() - { + public void cleanUp() { super.cleanUp(); locator.close(); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/BackupTopologyListener.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/BackupTopologyListener.java index f9fdff3eb0..615279d7e8 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/BackupTopologyListener.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/BackupTopologyListener.java @@ -22,21 +22,18 @@ import java.util.concurrent.TimeUnit; import org.apache.activemq.artemis.api.core.client.ClusterTopologyListener; import org.apache.activemq.artemis.api.core.client.TopologyMember; -final class BackupTopologyListener implements ClusterTopologyListener -{ +final class BackupTopologyListener implements ClusterTopologyListener { private final CountDownLatch latch = new CountDownLatch(1); private final String ownId; private static final int WAIT_TIMEOUT = 60; - public BackupTopologyListener(String ownId) - { + public BackupTopologyListener(String ownId) { this.ownId = ownId; } @Override - public void nodeUP(TopologyMember topologyMember, boolean last) - { + public void nodeUP(TopologyMember topologyMember, boolean last) { final String nodeID = topologyMember.getNodeId(); if (ownId.equals(nodeID) && topologyMember.getBackup() != null) @@ -44,19 +41,15 @@ final class BackupTopologyListener implements ClusterTopologyListener } @Override - public void nodeDown(long eventUID, String nodeID) - { + public void nodeDown(long eventUID, String nodeID) { // no-op } - boolean waitForBackup() - { - try - { + boolean waitForBackup() { + try { return latch.await(WAIT_TIMEOUT, TimeUnit.SECONDS); } - catch (InterruptedException e) - { + catch (InterruptedException e) { return false; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ColocatedActivation.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ColocatedActivation.java index 141882fc5e..4428136d6d 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ColocatedActivation.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ColocatedActivation.java @@ -43,8 +43,8 @@ import java.util.Comparator; import java.util.List; import java.util.concurrent.TimeUnit; -public class ColocatedActivation extends LiveActivation -{ +public class ColocatedActivation extends LiveActivation { + private static final SimpleString REQUEST_BACKUP_QUORUM_VOTE = new SimpleString("RequestBackupQuorumVote"); private final ColocatedHAManager colocatedHAManager; @@ -55,104 +55,82 @@ public class ColocatedActivation extends LiveActivation private final ActiveMQServerImpl server; - public ColocatedActivation(ActiveMQServerImpl activeMQServer, ColocatedPolicy colocatedPolicy, LiveActivation liveActivation) - { + public ColocatedActivation(ActiveMQServerImpl activeMQServer, + ColocatedPolicy colocatedPolicy, + LiveActivation liveActivation) { server = activeMQServer; this.colocatedPolicy = colocatedPolicy; this.liveActivation = liveActivation; colocatedHAManager = new ColocatedHAManager(colocatedPolicy, server); } - @Override - public void haStarted() - { + public void haStarted() { server.getClusterManager().getQuorumManager().registerQuorumHandler(new RequestBackupQuorumVoteHandler()); //vote for a backup if required - if (colocatedPolicy.isRequestBackup()) - { + if (colocatedPolicy.isRequestBackup()) { server.getClusterManager().getQuorumManager().vote(new RequestBackupQuorumVote()); } } @Override - public void freezeConnections(RemotingService remotingService) - { + public void freezeConnections(RemotingService remotingService) { liveActivation.freezeConnections(remotingService); } @Override - public void postConnectionFreeze() - { + public void postConnectionFreeze() { liveActivation.postConnectionFreeze(); } @Override - public void preStorageClose() throws Exception - { + public void preStorageClose() throws Exception { liveActivation.preStorageClose(); } @Override - public void sendLiveIsStopping() - { + public void sendLiveIsStopping() { liveActivation.sendLiveIsStopping(); } @Override - public ReplicationManager getReplicationManager() - { + public ReplicationManager getReplicationManager() { return liveActivation.getReplicationManager(); } @Override - public HAManager getHAManager() - { + public HAManager getHAManager() { return colocatedHAManager; } @Override - public void run() - { + public void run() { liveActivation.run(); } @Override - public void close(boolean permanently, boolean restarting) throws Exception - { + public void close(boolean permanently, boolean restarting) throws Exception { liveActivation.close(permanently, restarting); } @Override - public ChannelHandler getActivationChannelHandler(final Channel channel, final Acceptor acceptorUsed) - { + public ChannelHandler getActivationChannelHandler(final Channel channel, final Acceptor acceptorUsed) { final ChannelHandler activationChannelHandler = liveActivation.getActivationChannelHandler(channel, acceptorUsed); - return new ChannelHandler() - { + return new ChannelHandler() { @Override - public void handlePacket(Packet packet) - { - if (packet.getType() == PacketImpl.BACKUP_REQUEST) - { + public void handlePacket(Packet packet) { + if (packet.getType() == PacketImpl.BACKUP_REQUEST) { BackupRequestMessage backupRequestMessage = (BackupRequestMessage) packet; boolean started = false; - try - { - started = colocatedHAManager.activateBackup(backupRequestMessage.getBackupSize(), - backupRequestMessage.getJournalDirectory(), - backupRequestMessage.getBindingsDirectory(), - backupRequestMessage.getLargeMessagesDirectory(), - backupRequestMessage.getPagingDirectory(), - backupRequestMessage.getNodeID()); + try { + started = colocatedHAManager.activateBackup(backupRequestMessage.getBackupSize(), backupRequestMessage.getJournalDirectory(), backupRequestMessage.getBindingsDirectory(), backupRequestMessage.getLargeMessagesDirectory(), backupRequestMessage.getPagingDirectory(), backupRequestMessage.getNodeID()); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } channel.send(new BackupResponseMessage(started)); } - else if (activationChannelHandler != null) - { + else if (activationChannelHandler != null) { activationChannelHandler.handlePacket(packet); } } @@ -162,73 +140,63 @@ public class ColocatedActivation extends LiveActivation /** * A vote handler for incoming backup request votes */ - private final class RequestBackupQuorumVoteHandler implements QuorumVoteHandler - { + private final class RequestBackupQuorumVoteHandler implements QuorumVoteHandler { + @Override - public Vote vote(Vote vote) - { + public Vote vote(Vote vote) { int size = colocatedHAManager.getBackupServers().size(); return new RequestBackupVote(size, server.getNodeID().toString(), size < colocatedPolicy.getMaxBackups()); } @Override - public SimpleString getQuorumName() - { + public SimpleString getQuorumName() { return REQUEST_BACKUP_QUORUM_VOTE; } @Override - public Vote decode(ActiveMQBuffer voteBuffer) - { + public Vote decode(ActiveMQBuffer voteBuffer) { RequestBackupVote requestBackupVote = new RequestBackupVote(); requestBackupVote.decode(voteBuffer); return requestBackupVote; } } + /** * a quorum vote for backup requests */ - private final class RequestBackupQuorumVote extends QuorumVote> - { + private final class RequestBackupQuorumVote extends QuorumVote> { + //the available nodes that we can request private final List> nodes = new ArrayList<>(); - public RequestBackupQuorumVote() - { + public RequestBackupQuorumVote() { super(REQUEST_BACKUP_QUORUM_VOTE); } @Override - public Vote connected() - { + public Vote connected() { return new RequestBackupVote(); } @Override - public Vote notConnected() - { + public Vote notConnected() { return new RequestBackupVote(); } @Override - public void vote(RequestBackupVote vote) - { + public void vote(RequestBackupVote vote) { //if the returned vote is available add it to the nodes we can request - if (vote.backupAvailable) - { + if (vote.backupAvailable) { nodes.add(vote.getVote()); } } @Override - public Pair getDecision() - { + public Pair getDecision() { //sort the nodes by how many backups they have and choose the first - Collections.sort(nodes, new Comparator>() - { + Collections.sort(nodes, new Comparator>() { @Override - public int compare(Pair o1, Pair o2) - { + public int compare(Pair o1, Pair o2) { return o1.getB().compareTo(o2.getB()); } }); @@ -236,43 +204,33 @@ public class ColocatedActivation extends LiveActivation } @Override - public void allVotesCast(Topology voteTopology) - { + public void allVotesCast(Topology voteTopology) { //if we have any nodes that we can request then send a request - if (nodes.size() > 0) - { + if (nodes.size() > 0) { Pair decision = getDecision(); TopologyMemberImpl member = voteTopology.getMember(decision.getA()); - try - { + try { boolean backupStarted = colocatedHAManager.requestBackup(member.getConnector(), decision.getB().intValue(), !colocatedPolicy.isSharedStore()); - if (!backupStarted) - { + if (!backupStarted) { nodes.clear(); - server.getScheduledPool().schedule(new Runnable() - { + server.getScheduledPool().schedule(new Runnable() { @Override - public void run() - { + public void run() { server.getClusterManager().getQuorumManager().vote(new RequestBackupQuorumVote()); } }, colocatedPolicy.getBackupRequestRetryInterval(), TimeUnit.MILLISECONDS); } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); //todo } } - else - { + else { nodes.clear(); - server.getScheduledPool().schedule(new Runnable() - { + server.getScheduledPool().schedule(new Runnable() { @Override - public void run() - { + public void run() { server.getClusterManager().getQuorumManager().vote(RequestBackupQuorumVote.this); } }, colocatedPolicy.getBackupRequestRetryInterval(), TimeUnit.MILLISECONDS); @@ -280,55 +238,48 @@ public class ColocatedActivation extends LiveActivation } @Override - public SimpleString getName() - { + public SimpleString getName() { return REQUEST_BACKUP_QUORUM_VOTE; } } - class RequestBackupVote extends Vote> - { + class RequestBackupVote extends Vote> { + private int backupsSize; private String nodeID; private boolean backupAvailable; - public RequestBackupVote() - { + public RequestBackupVote() { backupsSize = -1; } - public RequestBackupVote(int backupsSize, String nodeID, boolean backupAvailable) - { + public RequestBackupVote(int backupsSize, String nodeID, boolean backupAvailable) { this.backupsSize = backupsSize; this.nodeID = nodeID; this.backupAvailable = backupAvailable; } @Override - public void encode(ActiveMQBuffer buff) - { + public void encode(ActiveMQBuffer buff) { buff.writeInt(backupsSize); buff.writeNullableString(nodeID); buff.writeBoolean(backupAvailable); } @Override - public void decode(ActiveMQBuffer buff) - { + public void decode(ActiveMQBuffer buff) { backupsSize = buff.readInt(); nodeID = buff.readNullableString(); backupAvailable = buff.readBoolean(); } @Override - public boolean isRequestServerVote() - { + public boolean isRequestServerVote() { return true; } @Override - public Pair getVote() - { + public Pair getVote() { return new Pair<>(nodeID, backupsSize); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ConnectorsService.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ConnectorsService.java index 52a77b7e65..ea4768d14c 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ConnectorsService.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ConnectorsService.java @@ -40,8 +40,8 @@ import java.util.concurrent.ScheduledExecutorService; * It may also listen to a queue, and forward them (e.g. messages arriving at the queue are picked * and tweeted to some Twitter account). */ -public final class ConnectorsService implements ActiveMQComponent -{ +public final class ConnectorsService implements ActiveMQComponent { + private final StorageManager storageManager; private final PostOffice postOffice; @@ -60,8 +60,7 @@ public final class ConnectorsService implements ActiveMQComponent final StorageManager storageManager, final ScheduledExecutorService scheduledPool, final PostOffice postOffice, - final ServiceRegistry serviceRegistry) - { + final ServiceRegistry serviceRegistry) { this.configuration = configuration; this.storageManager = storageManager; this.scheduledPool = scheduledPool; @@ -69,44 +68,35 @@ public final class ConnectorsService implements ActiveMQComponent this.serviceRegistry = serviceRegistry; } - public void start() throws Exception - { + public void start() throws Exception { Collection> connectorServiceFactories = serviceRegistry.getConnectorServices(configuration.getConnectorServiceConfigurations()); - for (Pair pair : connectorServiceFactories) - { + for (Pair pair : connectorServiceFactories) { createService(pair.getB(), pair.getA()); } - for (ConnectorService connector : connectors) - { - try - { + for (ConnectorService connector : connectors) { + try { connector.start(); } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQServerLogger.LOGGER.errorStartingConnectorService(e, connector.getName()); } } isStarted = true; } - public void createService(ConnectorServiceConfiguration info, ConnectorServiceFactory factory) - { - if (info.getParams() != null) - { + public void createService(ConnectorServiceConfiguration info, ConnectorServiceFactory factory) { + if (info.getParams() != null) { Set invalid = ConfigurationHelper.checkKeys(factory.getAllowableProperties(), info.getParams().keySet()); - if (!invalid.isEmpty()) - { + if (!invalid.isEmpty()) { ActiveMQServerLogger.LOGGER.connectorKeysInvalid(ConfigurationHelper.stringSetToCommaListString(invalid)); return; } } Set invalid = ConfigurationHelper.checkKeysExist(factory.getRequiredProperties(), info.getParams().keySet()); - if (!invalid.isEmpty()) - { + if (!invalid.isEmpty()) { ActiveMQServerLogger.LOGGER.connectorKeysMissing(ConfigurationHelper.stringSetToCommaListString(invalid)); return; } @@ -114,20 +104,15 @@ public final class ConnectorsService implements ActiveMQComponent connectors.add(connectorService); } - public void stop() throws Exception - { - if (!isStarted) - { + public void stop() throws Exception { + if (!isStarted) { return; } - for (ConnectorService connector : connectors) - { - try - { + for (ConnectorService connector : connectors) { + try { connector.stop(); } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQServerLogger.LOGGER.errorStoppingConnectorService(e, connector.getName()); } } @@ -135,13 +120,11 @@ public final class ConnectorsService implements ActiveMQComponent isStarted = false; } - public boolean isStarted() - { + public boolean isStarted() { return isStarted; } - public Set getConnectors() - { + public Set getConnectors() { return connectors; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/DivertImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/DivertImpl.java index c6db703d21..ee6d0feba1 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/DivertImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/DivertImpl.java @@ -29,8 +29,8 @@ import org.apache.activemq.artemis.core.server.cluster.Transformer; /** * A DivertImpl simply diverts a message to a different forwardAddress */ -public class DivertImpl implements Divert -{ +public class DivertImpl implements Divert { + private final PostOffice postOffice; private final SimpleString forwardAddress; @@ -54,8 +54,7 @@ public class DivertImpl implements Divert final Filter filter, final Transformer transformer, final PostOffice postOffice, - final StorageManager storageManager) - { + final StorageManager storageManager) { this.forwardAddress = forwardAddress; this.uniqueName = uniqueName; @@ -73,13 +72,11 @@ public class DivertImpl implements Divert this.storageManager = storageManager; } - public void route(final ServerMessage message, final RoutingContext context) throws Exception - { + public void route(final ServerMessage message, final RoutingContext context) throws Exception { // We must make a copy of the message, otherwise things like returning credits to the page won't work // properly on ack, since the original address will be overwritten - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("Diverting message " + message + " into " + this); } @@ -88,8 +85,7 @@ public class DivertImpl implements Divert ServerMessage copy = null; // Shouldn't copy if it's not routed anywhere else - if (!forwardAddress.equals(message.getAddress())) - { + if (!forwardAddress.equals(message.getAddress())) { copy = message.copy(id); copy.finishCopy(); @@ -100,13 +96,11 @@ public class DivertImpl implements Divert copy.setExpiration(message.getExpiration()); - if (transformer != null) - { + if (transformer != null) { copy = transformer.transform(copy); } } - else - { + else { copy = message; } @@ -114,34 +108,27 @@ public class DivertImpl implements Divert } @Override - public void routeWithAck(ServerMessage message, RoutingContext context) throws Exception - { + public void routeWithAck(ServerMessage message, RoutingContext context) throws Exception { route(message, context); } - - public SimpleString getRoutingName() - { + public SimpleString getRoutingName() { return routingName; } - public SimpleString getUniqueName() - { + public SimpleString getUniqueName() { return uniqueName; } - public boolean isExclusive() - { + public boolean isExclusive() { return exclusive; } - public Filter getFilter() - { + public Filter getFilter() { return filter; } - public Transformer getTransformer() - { + public Transformer getTransformer() { return transformer; } @@ -149,20 +136,19 @@ public class DivertImpl implements Divert * @see java.lang.Object#toString() */ @Override - public String toString() - { + public String toString() { return "DivertImpl [routingName=" + routingName + - ", uniqueName=" + - uniqueName + - ", forwardAddress=" + - forwardAddress + - ", exclusive=" + - exclusive + - ", filter=" + - filter + - ", transformer=" + - transformer + - "]"; + ", uniqueName=" + + uniqueName + + ", forwardAddress=" + + forwardAddress + + ", exclusive=" + + exclusive + + ", filter=" + + filter + + ", transformer=" + + transformer + + "]"; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/FileLockNodeManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/FileLockNodeManager.java index 62902c9157..acb431d388 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/FileLockNodeManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/FileLockNodeManager.java @@ -27,8 +27,8 @@ import org.apache.activemq.artemis.core.server.ActiveMQServerLogger; import org.apache.activemq.artemis.core.server.NodeManager; import org.apache.activemq.artemis.utils.UUID; -public class FileLockNodeManager extends NodeManager -{ +public class FileLockNodeManager extends NodeManager { + private static final int LIVE_LOCK_POS = 1; private static final int BACKUP_LOCK_POS = 2; @@ -51,27 +51,22 @@ public class FileLockNodeManager extends NodeManager protected boolean interrupted = false; - public FileLockNodeManager(final File directory, boolean replicatedBackup) - { + public FileLockNodeManager(final File directory, boolean replicatedBackup) { super(replicatedBackup, directory); } - public FileLockNodeManager(final File directory, boolean replicatedBackup, long lockAcquisitionTimeout) - { + public FileLockNodeManager(final File directory, boolean replicatedBackup, long lockAcquisitionTimeout) { super(replicatedBackup, directory); this.lockAcquisitionTimeout = lockAcquisitionTimeout; } @Override - public synchronized void start() throws Exception - { - if (isStarted()) - { + public synchronized void start() throws Exception { + if (isStarted()) { return; } - if (!replicatedBackup) - { + if (!replicatedBackup) { setUpServerLockFile(); } @@ -79,93 +74,75 @@ public class FileLockNodeManager extends NodeManager } @Override - public boolean isAwaitingFailback() throws Exception - { + public boolean isAwaitingFailback() throws Exception { return getState() == FileLockNodeManager.FAILINGBACK; } @Override - public boolean isBackupLive() throws Exception - { + public boolean isBackupLive() throws Exception { FileLock liveAttemptLock; liveAttemptLock = tryLock(FileLockNodeManager.LIVE_LOCK_POS); - if (liveAttemptLock == null) - { + if (liveAttemptLock == null) { return true; } - else - { + else { liveAttemptLock.release(); return false; } } - public boolean isLiveLocked() - { + public boolean isLiveLocked() { return liveLock != null; } - @Override - public void interrupt() - { + public void interrupt() { interrupted = true; } @Override - public final void releaseBackup() throws Exception - { - if (backupLock != null) - { + public final void releaseBackup() throws Exception { + if (backupLock != null) { backupLock.release(); backupLock = null; } } @Override - public void awaitLiveNode() throws Exception - { - do - { + public void awaitLiveNode() throws Exception { + do { byte state = getState(); - while (state == FileLockNodeManager.NOT_STARTED || state == FIRST_TIME_START) - { + while (state == FileLockNodeManager.NOT_STARTED || state == FIRST_TIME_START) { ActiveMQServerLogger.LOGGER.debug("awaiting live node startup state='" + state + "'"); Thread.sleep(2000); state = getState(); } liveLock = lock(FileLockNodeManager.LIVE_LOCK_POS); - if (interrupted) - { + if (interrupted) { interrupted = false; throw new InterruptedException("Lock was interrupted"); } state = getState(); - if (state == FileLockNodeManager.PAUSED) - { + if (state == FileLockNodeManager.PAUSED) { liveLock.release(); ActiveMQServerLogger.LOGGER.debug("awaiting live node restarting"); Thread.sleep(2000); } - else if (state == FileLockNodeManager.FAILINGBACK) - { + else if (state == FileLockNodeManager.FAILINGBACK) { liveLock.release(); ActiveMQServerLogger.LOGGER.debug("awaiting live node failing back"); Thread.sleep(2000); } - else if (state == FileLockNodeManager.LIVE) - { + else if (state == FileLockNodeManager.LIVE) { ActiveMQServerLogger.LOGGER.debug("acquired live node lock state = " + (char) state); break; } - } - while (true); + } while (true); } @Override - public void startBackup() throws Exception - { + public void startBackup() throws Exception { assert !replicatedBackup; // should not be called if this is a replicating backup ActiveMQServerLogger.LOGGER.waitingToBecomeBackup(); @@ -176,8 +153,7 @@ public class FileLockNodeManager extends NodeManager } @Override - public void startLiveNode() throws Exception - { + public void startLiveNode() throws Exception { setFailingBack(); String timeoutMessage = lockAcquisitionTimeout == -1 ? "indefinitely" : lockAcquisitionTimeout + " milliseconds"; @@ -192,37 +168,30 @@ public class FileLockNodeManager extends NodeManager } @Override - public void pauseLiveServer() throws Exception - { + public void pauseLiveServer() throws Exception { setPaused(); - if (liveLock != null) - { + if (liveLock != null) { liveLock.release(); } } @Override - public void crashLiveServer() throws Exception - { - if (liveLock != null) - { + public void crashLiveServer() throws Exception { + if (liveLock != null) { liveLock.release(); liveLock = null; } } - private void setLive() throws Exception - { + private void setLive() throws Exception { writeFileLockStatus(FileLockNodeManager.LIVE); } - private void setFailingBack() throws Exception - { + private void setFailingBack() throws Exception { writeFileLockStatus(FAILINGBACK); } - private void setPaused() throws Exception - { + private void setPaused() throws Exception { writeFileLockStatus(PAUSED); } @@ -230,8 +199,7 @@ public class FileLockNodeManager extends NodeManager * @param status * @throws IOException */ - private void writeFileLockStatus(byte status) throws IOException - { + private void writeFileLockStatus(byte status) throws IOException { if (replicatedBackup && channel == null) return; ByteBuffer bb = ByteBuffer.allocateDirect(1); @@ -241,28 +209,23 @@ public class FileLockNodeManager extends NodeManager channel.force(true); } - private byte getState() throws Exception - { + private byte getState() throws Exception { ByteBuffer bb = ByteBuffer.allocateDirect(1); int read; read = channel.read(bb, 0); - if (read <= 0) - { + if (read <= 0) { return FileLockNodeManager.NOT_STARTED; } - else - { + else { return bb.get(0); } } @Override - public final SimpleString readNodeId() throws ActiveMQIllegalStateException, IOException - { + public final SimpleString readNodeId() throws ActiveMQIllegalStateException, IOException { ByteBuffer id = ByteBuffer.allocateDirect(16); int read = channel.read(id, 3); - if (read != 16) - { + if (read != 16) { throw new ActiveMQIllegalStateException("live server did not write id to file"); } byte[] bytes = new byte[16]; @@ -272,53 +235,41 @@ public class FileLockNodeManager extends NodeManager return getNodeId(); } - protected FileLock tryLock(final int lockPos) throws Exception - { - try - { + protected FileLock tryLock(final int lockPos) throws Exception { + try { return channel.tryLock(lockPos, LOCK_LENGTH, false); } - catch (java.nio.channels.OverlappingFileLockException ex) - { + catch (java.nio.channels.OverlappingFileLockException ex) { // This just means that another object on the same JVM is holding the lock return null; } } - protected FileLock lock(final int liveLockPos) throws Exception - { + protected FileLock lock(final int liveLockPos) throws Exception { long start = System.currentTimeMillis(); - while (!interrupted) - { + while (!interrupted) { FileLock lock = null; - try - { + try { lock = channel.tryLock(liveLockPos, 1, false); } - catch (java.nio.channels.OverlappingFileLockException ex) - { + catch (java.nio.channels.OverlappingFileLockException ex) { // This just means that another object on the same JVM is holding the lock } - if (lock == null) - { - try - { + if (lock == null) { + try { Thread.sleep(500); } - catch (InterruptedException e) - { + catch (InterruptedException e) { return null; } - if (lockAcquisitionTimeout != -1 && (System.currentTimeMillis() - start) > lockAcquisitionTimeout) - { + if (lockAcquisitionTimeout != -1 && (System.currentTimeMillis() - start) > lockAcquisitionTimeout) { throw new Exception("timed out waiting for lock"); } } - else - { + else { return lock; } } @@ -326,27 +277,21 @@ public class FileLockNodeManager extends NodeManager // todo this is here because sometimes channel.lock throws a resource deadlock exception but trylock works, // need to investigate further and review FileLock lock; - do - { + do { lock = channel.tryLock(liveLockPos, 1, false); - if (lock == null) - { - try - { + if (lock == null) { + try { Thread.sleep(500); } - catch (InterruptedException e1) - { + catch (InterruptedException e1) { // } } - if (interrupted) - { + if (interrupted) { interrupted = false; throw new IOException("Lock was interrupted"); } - } - while (lock == null); + } while (lock == null); return lock; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/InVMNodeManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/InVMNodeManager.java index dfd74a4e55..726cb50003 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/InVMNodeManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/InVMNodeManager.java @@ -37,15 +37,13 @@ import static org.apache.activemq.artemis.core.server.impl.InVMNodeManager.State * multiple servers are run inside the same VM and File Locks can not be shared in the * same VM (it would cause a shared lock violation). */ -public final class InVMNodeManager extends NodeManager -{ +public final class InVMNodeManager extends NodeManager { private final Semaphore liveLock; private final Semaphore backupLock; - public enum State - { + public enum State { LIVE, PAUSED, FAILING_BACK, NOT_STARTED } @@ -53,15 +51,13 @@ public final class InVMNodeManager extends NodeManager public long failoverPause = 0L; - public InVMNodeManager(boolean replicatedBackup) - { + public InVMNodeManager(boolean replicatedBackup) { this(replicatedBackup, null); if (replicatedBackup) throw new RuntimeException("if replicated-backup, we need its journal directory"); } - public InVMNodeManager(boolean replicatedBackup, File directory) - { + public InVMNodeManager(boolean replicatedBackup, File directory) { super(replicatedBackup, directory); liveLock = new Semaphore(1); backupLock = new Semaphore(1); @@ -69,98 +65,80 @@ public final class InVMNodeManager extends NodeManager } @Override - public void awaitLiveNode() throws Exception - { - do - { - while (state == NOT_STARTED) - { + public void awaitLiveNode() throws Exception { + do { + while (state == NOT_STARTED) { Thread.sleep(2000); } liveLock.acquire(); - if (state == PAUSED) - { + if (state == PAUSED) { liveLock.release(); Thread.sleep(2000); } - else if (state == FAILING_BACK) - { + else if (state == FAILING_BACK) { liveLock.release(); Thread.sleep(2000); } - else if (state == LIVE) - { + else if (state == LIVE) { break; } - } - while (true); - if (failoverPause > 0L) - { + } while (true); + if (failoverPause > 0L) { Thread.sleep(failoverPause); } } @Override - public void startBackup() throws Exception - { + public void startBackup() throws Exception { backupLock.acquire(); } @Override - public void startLiveNode() throws Exception - { + public void startLiveNode() throws Exception { state = FAILING_BACK; liveLock.acquire(); state = LIVE; } @Override - public void pauseLiveServer() throws Exception - { + public void pauseLiveServer() throws Exception { state = PAUSED; liveLock.release(); } @Override - public void crashLiveServer() throws Exception - { + public void crashLiveServer() throws Exception { //overkill as already set to live state = LIVE; liveLock.release(); } @Override - public boolean isAwaitingFailback() throws Exception - { + public boolean isAwaitingFailback() throws Exception { return state == FAILING_BACK; } @Override - public boolean isBackupLive() throws Exception - { + public boolean isBackupLive() throws Exception { return liveLock.availablePermits() == 0; } @Override - public void interrupt() - { + public void interrupt() { // } @Override - public void releaseBackup() - { - if (backupLock != null) - { + public void releaseBackup() { + if (backupLock != null) { backupLock.release(); } } @Override - public SimpleString readNodeId() throws ActiveMQIllegalStateException, IOException - { + public SimpleString readNodeId() throws ActiveMQIllegalStateException, IOException { return getNodeId(); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/JournalLoader.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/JournalLoader.java index 8690d9785c..6f36ff54ca 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/JournalLoader.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/JournalLoader.java @@ -32,9 +32,10 @@ import org.apache.activemq.artemis.core.server.ServerMessage; import org.apache.activemq.artemis.core.transaction.ResourceManager; import org.apache.activemq.artemis.core.transaction.Transaction; -public interface JournalLoader -{ - void initQueues(Map queueBindingInfosMap, List queueBindingInfos) throws Exception; +public interface JournalLoader { + + void initQueues(Map queueBindingInfosMap, + List queueBindingInfos) throws Exception; void handleAddMessage(Map> queueMap) throws Exception; @@ -44,13 +45,20 @@ public interface JournalLoader void handleDuplicateIds(Map>> duplicateIDMap) throws Exception; - void postLoad(Journal messageJournal, ResourceManager resourceManager, Map>> duplicateIDMap) throws Exception; + void postLoad(Journal messageJournal, + ResourceManager resourceManager, + Map>> duplicateIDMap) throws Exception; void handlePreparedSendMessage(ServerMessage message, Transaction tx, long queueID) throws Exception; - void handlePreparedAcknowledge(long messageID, List referencesToAck, long queueID) throws Exception; + void handlePreparedAcknowledge(long messageID, + List referencesToAck, + long queueID) throws Exception; - void handlePreparedTransaction(Transaction tx, List referencesToAck, Xid xid, ResourceManager resourceManager) throws Exception; + void handlePreparedTransaction(Transaction tx, + List referencesToAck, + Xid xid, + ResourceManager resourceManager) throws Exception; void recoverPendingPageCounters(List pendingNonTXPageCounter) throws Exception; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/LastValueQueue.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/LastValueQueue.java index ef4fa10d23..39becf0452 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/LastValueQueue.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/LastValueQueue.java @@ -42,8 +42,8 @@ import org.apache.activemq.artemis.core.settings.impl.AddressSettings; * This is useful for example, for stock prices, where you're only interested in the latest value * for a particular stock */ -public class LastValueQueue extends QueueImpl -{ +public class LastValueQueue extends QueueImpl { + private final Map map = new ConcurrentHashMap(); public LastValueQueue(final long persistenceID, @@ -59,56 +59,36 @@ public class LastValueQueue extends QueueImpl final PostOffice postOffice, final StorageManager storageManager, final HierarchicalRepository addressSettingsRepository, - final Executor executor) - { - super(persistenceID, - address, - name, - filter, - pageSubscription, - user, - durable, - temporary, - autoCreated, - scheduledExecutor, - postOffice, - storageManager, - addressSettingsRepository, - executor); - new Exception("LastValueQeue " + this ).toString(); + final Executor executor) { + super(persistenceID, address, name, filter, pageSubscription, user, durable, temporary, autoCreated, scheduledExecutor, postOffice, storageManager, addressSettingsRepository, executor); + new Exception("LastValueQeue " + this).toString(); } @Override - public synchronized void addTail(final MessageReference ref, final boolean direct) - { + public synchronized void addTail(final MessageReference ref, final boolean direct) { SimpleString prop = ref.getMessage().getSimpleStringProperty(Message.HDR_LAST_VALUE_NAME); - if (prop != null) - { + if (prop != null) { HolderReference hr = map.get(prop); - if (hr != null) - { + if (hr != null) { // We need to overwrite the old ref with the new one and ack the old one MessageReference oldRef = hr.getReference(); referenceHandled(); - try - { + try { oldRef.acknowledge(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorAckingOldReference(e); } hr.setReference(ref); } - else - { + else { hr = new HolderReference(prop, ref); map.put(prop, hr); @@ -116,59 +96,47 @@ public class LastValueQueue extends QueueImpl super.addTail(hr, direct); } } - else - { + else { super.addTail(ref, direct); } } @Override - public synchronized void addHead(final MessageReference ref) - { + public synchronized void addHead(final MessageReference ref) { SimpleString prop = ref.getMessage().getSimpleStringProperty(Message.HDR_LAST_VALUE_NAME); - if (prop != null) - { + if (prop != null) { HolderReference hr = map.get(prop); - if (hr != null) - { + if (hr != null) { // We keep the current ref and ack the one we are returning super.referenceHandled(); - try - { + try { super.acknowledge(ref); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorAckingOldReference(e); } } - else - { - map.put(prop, (HolderReference)ref); + else { + map.put(prop, (HolderReference) ref); super.addHead(ref); } } - else - { + else { super.addHead(ref); } } - @Override - protected void refRemoved(MessageReference ref) - { - synchronized (this) - { + protected void refRemoved(MessageReference ref) { + synchronized (this) { SimpleString prop = ref.getMessage().getSimpleStringProperty(Message.HDR_LAST_VALUE_NAME); - if (prop != null) - { + if (prop != null) { map.remove(prop); } } @@ -176,107 +144,89 @@ public class LastValueQueue extends QueueImpl super.refRemoved(ref); } - private class HolderReference implements MessageReference - { + private class HolderReference implements MessageReference { + private final SimpleString prop; private volatile MessageReference ref; private Long consumerId; - HolderReference(final SimpleString prop, final MessageReference ref) - { + HolderReference(final SimpleString prop, final MessageReference ref) { this.prop = prop; this.ref = ref; } - MessageReference getReference() - { + MessageReference getReference() { return ref; } - public void handled() - { + public void handled() { ref.handled(); // We need to remove the entry from the map just before it gets delivered map.remove(prop); } @Override - public void setAlreadyAcked() - { + public void setAlreadyAcked() { ref.setAlreadyAcked(); } @Override - public boolean isAlreadyAcked() - { + public boolean isAlreadyAcked() { return ref.isAlreadyAcked(); } - void setReference(final MessageReference ref) - { + void setReference(final MessageReference ref) { this.ref = ref; } - public MessageReference copy(final Queue queue) - { + public MessageReference copy(final Queue queue) { return ref.copy(queue); } - public void decrementDeliveryCount() - { + public void decrementDeliveryCount() { ref.decrementDeliveryCount(); } - public int getDeliveryCount() - { + public int getDeliveryCount() { return ref.getDeliveryCount(); } - public ServerMessage getMessage() - { + public ServerMessage getMessage() { return ref.getMessage(); } - public Queue getQueue() - { + public Queue getQueue() { return ref.getQueue(); } - public long getScheduledDeliveryTime() - { + public long getScheduledDeliveryTime() { return ref.getScheduledDeliveryTime(); } - public void incrementDeliveryCount() - { + public void incrementDeliveryCount() { ref.incrementDeliveryCount(); } - public void setDeliveryCount(final int deliveryCount) - { + public void setDeliveryCount(final int deliveryCount) { ref.setDeliveryCount(deliveryCount); } - public void setScheduledDeliveryTime(final long scheduledDeliveryTime) - { + public void setScheduledDeliveryTime(final long scheduledDeliveryTime) { ref.setScheduledDeliveryTime(scheduledDeliveryTime); } - public void setPersistedCount(int count) - { + public void setPersistedCount(int count) { ref.setPersistedCount(count); } - public int getPersistedCount() - { + public int getPersistedCount() { return ref.getPersistedCount(); } - public boolean isPaged() - { + public boolean isPaged() { return false; } @@ -284,16 +234,14 @@ public class LastValueQueue extends QueueImpl * @see org.apache.activemq.artemis.core.server.MessageReference#acknowledge(org.apache.activemq.artemis.core.server.MessageReference) */ @Override - public void acknowledge() throws Exception - { + public void acknowledge() throws Exception { ref.getQueue().acknowledge(this); } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.server.MessageReference#getMessageMemoryEstimate() */ - public int getMessageMemoryEstimate() - { + public int getMessageMemoryEstimate() { return ref.getMessage().getMemoryEstimate(); } @@ -301,8 +249,7 @@ public class LastValueQueue extends QueueImpl * @see org.apache.activemq.artemis.core.server.MessageReference#setConsumerId(java.lang.Long) */ @Override - public void setConsumerId(Long consumerID) - { + public void setConsumerId(Long consumerID) { this.consumerId = consumerID; } @@ -310,15 +257,13 @@ public class LastValueQueue extends QueueImpl * @see org.apache.activemq.artemis.core.server.MessageReference#getConsumerId() */ @Override - public Long getConsumerId() - { + public Long getConsumerId() { return this.consumerId; } } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((map == null) ? 0 : map.hashCode()); @@ -326,30 +271,23 @@ public class LastValueQueue extends QueueImpl } @Override - public boolean equals(Object obj) - { - if (this == obj) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if (!super.equals(obj)) - { + if (!super.equals(obj)) { return false; } - if (!(obj instanceof LastValueQueue)) - { + if (!(obj instanceof LastValueQueue)) { return false; } - LastValueQueue other = (LastValueQueue)obj; - if (map == null) - { - if (other.map != null) - { + LastValueQueue other = (LastValueQueue) obj; + if (map == null) { + if (other.map != null) { return false; } } - else if (!map.equals(other.map)) - { + else if (!map.equals(other.map)) { return false; } return true; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/LiveActivation.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/LiveActivation.java index 01081c692b..37553a2668 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/LiveActivation.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/LiveActivation.java @@ -16,6 +16,6 @@ */ package org.apache.activemq.artemis.core.server.impl; -public abstract class LiveActivation extends Activation -{ +public abstract class LiveActivation extends Activation { + } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/LiveOnlyActivation.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/LiveOnlyActivation.java index 55d3c053fd..1c82bbf7b8 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/LiveOnlyActivation.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/LiveOnlyActivation.java @@ -37,8 +37,8 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentMap; -public class LiveOnlyActivation extends Activation -{ +public class LiveOnlyActivation extends Activation { + //this is how we act when we initially start as live private LiveOnlyPolicy liveOnlyPolicy; @@ -48,97 +48,75 @@ public class LiveOnlyActivation extends Activation private ClientSessionFactoryInternal scaleDownClientSessionFactory; - public LiveOnlyActivation(ActiveMQServerImpl server, LiveOnlyPolicy liveOnlyPolicy) - { + public LiveOnlyActivation(ActiveMQServerImpl server, LiveOnlyPolicy liveOnlyPolicy) { this.activeMQServer = server; this.liveOnlyPolicy = liveOnlyPolicy; } - public void run() - { - try - { + public void run() { + try { activeMQServer.initialisePart1(false); activeMQServer.initialisePart2(false); activeMQServer.completeActivation(); - if (activeMQServer.getIdentity() != null) - { + if (activeMQServer.getIdentity() != null) { ActiveMQServerLogger.LOGGER.serverIsLive(activeMQServer.getIdentity()); } - else - { + else { ActiveMQServerLogger.LOGGER.serverIsLive(); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.initializationError(e); } } @Override - public void close(boolean permanently, boolean restarting) throws Exception - { - if (scaleDownServerLocator != null) - { + public void close(boolean permanently, boolean restarting) throws Exception { + if (scaleDownServerLocator != null) { scaleDownServerLocator.close(); scaleDownServerLocator = null; } } - public void freezeConnections(RemotingService remotingService) - { + public void freezeConnections(RemotingService remotingService) { // connect to the scale-down target first so that when we freeze/disconnect the clients we can tell them where // we're sending the messages - if (liveOnlyPolicy.getScaleDownPolicy() != null && liveOnlyPolicy.getScaleDownPolicy().isEnabled()) - { + if (liveOnlyPolicy.getScaleDownPolicy() != null && liveOnlyPolicy.getScaleDownPolicy().isEnabled()) { connectToScaleDownTarget(liveOnlyPolicy.getScaleDownPolicy()); } TransportConfiguration tc = scaleDownClientSessionFactory == null ? null : scaleDownClientSessionFactory.getConnectorConfiguration(); String nodeID = tc == null ? null : scaleDownClientSessionFactory.getServerLocator().getTopology().getMember(tc).getNodeId(); - if (remotingService != null) - { + if (remotingService != null) { remotingService.freeze(nodeID, null); } } @Override - public void postConnectionFreeze() - { - if (liveOnlyPolicy.getScaleDownPolicy() != null - && liveOnlyPolicy.getScaleDownPolicy().isEnabled() - && scaleDownClientSessionFactory != null) - { - try - { + public void postConnectionFreeze() { + if (liveOnlyPolicy.getScaleDownPolicy() != null && liveOnlyPolicy.getScaleDownPolicy().isEnabled() && scaleDownClientSessionFactory != null) { + try { scaleDown(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.failedToScaleDown(e); } - finally - { + finally { scaleDownClientSessionFactory.close(); scaleDownServerLocator.close(); } } } - public void connectToScaleDownTarget(ScaleDownPolicy scaleDownPolicy) - { - try - { + public void connectToScaleDownTarget(ScaleDownPolicy scaleDownPolicy) { + try { scaleDownServerLocator = ScaleDownPolicy.getScaleDownConnector(scaleDownPolicy, activeMQServer); //use a Node Locator to connect to the cluster scaleDownServerLocator.setProtocolManagerFactory(ActiveMQServerSideProtocolManagerFactory.getInstance()); - LiveNodeLocator nodeLocator = scaleDownPolicy.getGroupName() == null ? - new AnyLiveNodeLocatorForScaleDown(activeMQServer) : - new NamedLiveNodeLocatorForScaleDown(scaleDownPolicy.getGroupName(), activeMQServer); + LiveNodeLocator nodeLocator = scaleDownPolicy.getGroupName() == null ? new AnyLiveNodeLocatorForScaleDown(activeMQServer) : new NamedLiveNodeLocatorForScaleDown(scaleDownPolicy.getGroupName(), activeMQServer); scaleDownServerLocator.addClusterTopologyListener(nodeLocator); nodeLocator.connectToCluster(scaleDownServerLocator); @@ -146,59 +124,44 @@ public class LiveOnlyActivation extends Activation // should the timeout be configurable? nodeLocator.locateNode(ActiveMQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT); ClientSessionFactoryInternal clientSessionFactory = null; - while (clientSessionFactory == null) - { + while (clientSessionFactory == null) { Pair possibleLive = null; - try - { + try { possibleLive = nodeLocator.getLiveConfiguration(); if (possibleLive == null) // we've tried every connector break; clientSessionFactory = (ClientSessionFactoryInternal) scaleDownServerLocator.createSessionFactory(possibleLive.getA(), 0, false); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.trace("Failed to connect to " + possibleLive.getA()); nodeLocator.notifyRegistrationFailed(false); - if (clientSessionFactory != null) - { + if (clientSessionFactory != null) { clientSessionFactory.close(); } clientSessionFactory = null; // should I try the backup (i.e. getB()) from possibleLive? } } - if (clientSessionFactory != null) - { + if (clientSessionFactory != null) { scaleDownClientSessionFactory = clientSessionFactory; } - else - { + else { throw new ActiveMQException("Unable to connect to server for scale-down"); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.failedToScaleDown(e); } } - - public long scaleDown() throws Exception - { - ScaleDownHandler scaleDownHandler = new ScaleDownHandler(activeMQServer.getPagingManager(), - activeMQServer.getPostOffice(), - activeMQServer.getNodeManager(), - activeMQServer.getClusterManager().getClusterController(), - activeMQServer.getStorageManager()); + public long scaleDown() throws Exception { + ScaleDownHandler scaleDownHandler = new ScaleDownHandler(activeMQServer.getPagingManager(), activeMQServer.getPostOffice(), activeMQServer.getNodeManager(), activeMQServer.getClusterManager().getClusterController(), activeMQServer.getStorageManager()); ConcurrentMap duplicateIDCaches = ((PostOfficeImpl) activeMQServer.getPostOffice()).getDuplicateIDCaches(); Map>> duplicateIDMap = new HashMap<>(); - for (SimpleString address : duplicateIDCaches.keySet()) - { + for (SimpleString address : duplicateIDCaches.keySet()) { DuplicateIDCache duplicateIDCache = activeMQServer.getPostOffice().getDuplicateIDCache(address); duplicateIDMap.put(address, duplicateIDCache.getMap()); } - return scaleDownHandler.scaleDown(scaleDownClientSessionFactory, activeMQServer.getResourceManager(), duplicateIDMap, - activeMQServer.getManagementService().getManagementAddress(), null); + return scaleDownHandler.scaleDown(scaleDownClientSessionFactory, activeMQServer.getResourceManager(), duplicateIDMap, activeMQServer.getManagementService().getManagementAddress(), null); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/MessageReferenceImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/MessageReferenceImpl.java index a787c891e8..ca1c0a2521 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/MessageReferenceImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/MessageReferenceImpl.java @@ -26,8 +26,8 @@ import org.apache.activemq.artemis.utils.MemorySize; /** * Implementation of a MessageReference */ -public class MessageReferenceImpl implements MessageReference -{ +public class MessageReferenceImpl implements MessageReference { + private final AtomicInteger deliveryCount = new AtomicInteger(); private volatile int persistedCount; @@ -42,39 +42,33 @@ public class MessageReferenceImpl implements MessageReference private boolean alreadyAcked; - // Static -------------------------------------------------------- private static final int memoryOffset; - static - { + static { // This is an estimate of how much memory a ServerMessageImpl takes up, exclusing body and properties // Note, it is only an estimate, it's not possible to be entirely sure with Java // This figure is calculated using the test utilities in org.apache.activemq.tests.unit.util.sizeof // The value is somewhat higher on 64 bit architectures, probably due to different alignment - if (MemorySize.is64bitArch()) - { + if (MemorySize.is64bitArch()) { memoryOffset = 48; } - else - { + else { memoryOffset = 32; } } // Constructors -------------------------------------------------- - public MessageReferenceImpl() - { + public MessageReferenceImpl() { queue = null; message = null; } - public MessageReferenceImpl(final MessageReferenceImpl other, final Queue queue) - { + public MessageReferenceImpl(final MessageReferenceImpl other, final Queue queue) { deliveryCount.set(other.deliveryCount.get()); scheduledDeliveryTime = other.scheduledDeliveryTime; @@ -84,8 +78,7 @@ public class MessageReferenceImpl implements MessageReference this.queue = queue; } - protected MessageReferenceImpl(final ServerMessage message, final Queue queue) - { + protected MessageReferenceImpl(final ServerMessage message, final Queue queue) { this.message = message; this.queue = queue; @@ -96,117 +89,96 @@ public class MessageReferenceImpl implements MessageReference /** * @return the persistedCount */ - public int getPersistedCount() - { + public int getPersistedCount() { return persistedCount; } /** * @param persistedCount the persistedCount to set */ - public void setPersistedCount(int persistedCount) - { + public void setPersistedCount(int persistedCount) { this.persistedCount = persistedCount; } - public MessageReference copy(final Queue queue) - { + public MessageReference copy(final Queue queue) { return new MessageReferenceImpl(this, queue); } - public static int getMemoryEstimate() - { + public static int getMemoryEstimate() { return MessageReferenceImpl.memoryOffset; } - public int getDeliveryCount() - { + public int getDeliveryCount() { return deliveryCount.get(); } - public void setDeliveryCount(final int deliveryCount) - { + public void setDeliveryCount(final int deliveryCount) { this.deliveryCount.set(deliveryCount); this.persistedCount = this.deliveryCount.get(); } - public void incrementDeliveryCount() - { + public void incrementDeliveryCount() { deliveryCount.incrementAndGet(); } - public void decrementDeliveryCount() - { + public void decrementDeliveryCount() { deliveryCount.decrementAndGet(); } - public long getScheduledDeliveryTime() - { + public long getScheduledDeliveryTime() { return scheduledDeliveryTime; } - public void setScheduledDeliveryTime(final long scheduledDeliveryTime) - { + public void setScheduledDeliveryTime(final long scheduledDeliveryTime) { this.scheduledDeliveryTime = scheduledDeliveryTime; } - public ServerMessage getMessage() - { + public ServerMessage getMessage() { return message; } - public Queue getQueue() - { + public Queue getQueue() { return queue; } - public void handled() - { + public void handled() { queue.referenceHandled(); } @Override - public void setAlreadyAcked() - { + public void setAlreadyAcked() { alreadyAcked = true; } @Override - public boolean isAlreadyAcked() - { + public boolean isAlreadyAcked() { return alreadyAcked; } - public boolean isPaged() - { + public boolean isPaged() { return false; } - public void acknowledge() throws Exception - { + public void acknowledge() throws Exception { queue.acknowledge(this); } @Override - public void setConsumerId(Long consumerID) - { + public void setConsumerId(Long consumerID) { this.consumerID = consumerID; } @Override - public Long getConsumerId() - { + public Long getConsumerId() { return this.consumerID; } - public int getMessageMemoryEstimate() - { + public int getMessageMemoryEstimate() { return message.getMemoryEstimate(); } @Override - public String toString() - { + public String toString() { return "Reference[" + getMessage().getMessageID() + "]:" + (getMessage().isDurable() ? "RELIABLE" : "NON-RELIABLE") + @@ -215,15 +187,12 @@ public class MessageReferenceImpl implements MessageReference } @Override - public boolean equals(Object other) - { - if (this == other) - { + public boolean equals(Object other) { + if (this == other) { return true; } - if (other instanceof MessageReferenceImpl) - { + if (other instanceof MessageReferenceImpl) { MessageReference reference = (MessageReferenceImpl) other; if (this.getMessage().equals(reference.getMessage())) @@ -234,8 +203,7 @@ public class MessageReferenceImpl implements MessageReference } @Override - public int hashCode() - { + public int hashCode() { return this.getMessage().hashCode(); } } \ No newline at end of file diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/NamedLiveNodeLocatorForReplication.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/NamedLiveNodeLocatorForReplication.java index 3d7a370eb6..38bbc54454 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/NamedLiveNodeLocatorForReplication.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/NamedLiveNodeLocatorForReplication.java @@ -33,8 +33,8 @@ import org.apache.activemq.artemis.core.server.cluster.qourum.SharedNothingBacku * * @see org.apache.activemq.artemis.core.server.cluster.ha.HAPolicy#getScaleDownGroupName() */ -public class NamedLiveNodeLocatorForReplication extends LiveNodeLocator -{ +public class NamedLiveNodeLocatorForReplication extends LiveNodeLocator { + private final Lock lock = new ReentrantLock(); private final Condition condition = lock.newCondition(); private final String backupGroupName; @@ -42,99 +42,77 @@ public class NamedLiveNodeLocatorForReplication extends LiveNodeLocator private String nodeID; - public NamedLiveNodeLocatorForReplication(String backupGroupName, SharedNothingBackupQuorum quorumManager) - { + public NamedLiveNodeLocatorForReplication(String backupGroupName, SharedNothingBackupQuorum quorumManager) { super(quorumManager); this.backupGroupName = backupGroupName; } @Override - public void locateNode() throws ActiveMQException - { + public void locateNode() throws ActiveMQException { locateNode(-1L); } @Override - public void locateNode(long timeout) throws ActiveMQException - { - try - { + public void locateNode(long timeout) throws ActiveMQException { + try { lock.lock(); - if (liveConfiguration == null) - { - try - { - if (timeout != -1L) - { + if (liveConfiguration == null) { + try { + if (timeout != -1L) { condition.await(timeout, TimeUnit.MILLISECONDS); } - else - { + else { condition.await(); } } - catch (InterruptedException e) - { + catch (InterruptedException e) { //ignore } } } - finally - { + finally { lock.unlock(); } } @Override - public void nodeUP(TopologyMember topologyMember, boolean last) - { - try - { + public void nodeUP(TopologyMember topologyMember, boolean last) { + try { lock.lock(); - if (backupGroupName.equals(topologyMember.getBackupGroupName()) && topologyMember.getLive() != null) - { - liveConfiguration = - new Pair(topologyMember.getLive(), - topologyMember.getBackup()); + if (backupGroupName.equals(topologyMember.getBackupGroupName()) && topologyMember.getLive() != null) { + liveConfiguration = new Pair(topologyMember.getLive(), topologyMember.getBackup()); nodeID = topologyMember.getNodeId(); condition.signal(); } } - finally - { + finally { lock.unlock(); } } @Override - public void nodeDown(long eventUID, String nodeID) - { + public void nodeDown(long eventUID, String nodeID) { //no op } @Override - public String getNodeID() - { + public String getNodeID() { return nodeID; } @Override - public Pair getLiveConfiguration() - { + public Pair getLiveConfiguration() { return liveConfiguration; } @Override - public void notifyRegistrationFailed(boolean alreadyReplicating) - { - try - { + public void notifyRegistrationFailed(boolean alreadyReplicating) { + try { lock.lock(); liveConfiguration = null; super.notifyRegistrationFailed(alreadyReplicating); } - finally - { + finally { lock.unlock(); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/NamedLiveNodeLocatorForScaleDown.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/NamedLiveNodeLocatorForScaleDown.java index 2c1efe66a2..6b6c25b286 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/NamedLiveNodeLocatorForScaleDown.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/NamedLiveNodeLocatorForScaleDown.java @@ -34,8 +34,8 @@ import org.apache.activemq.artemis.core.server.LiveNodeLocator; /** * NamedLiveNodeLocatorForScaleDown looks for a live server in the cluster with a specific scaleDownGroupName */ -public class NamedLiveNodeLocatorForScaleDown extends LiveNodeLocator -{ +public class NamedLiveNodeLocatorForScaleDown extends LiveNodeLocator { + private final Lock lock = new ReentrantLock(); private final Condition condition = lock.newCondition(); private final String scaleDownGroupName; @@ -45,8 +45,7 @@ public class NamedLiveNodeLocatorForScaleDown extends LiveNodeLocator private String nodeID; private String myNodeID; - public NamedLiveNodeLocatorForScaleDown(String scaleDownGroupName, ActiveMQServerImpl server) - { + public NamedLiveNodeLocatorForScaleDown(String scaleDownGroupName, ActiveMQServerImpl server) { super(); this.server = server; this.scaleDownGroupName = scaleDownGroupName; @@ -54,131 +53,102 @@ public class NamedLiveNodeLocatorForScaleDown extends LiveNodeLocator } @Override - public void locateNode() throws ActiveMQException - { + public void locateNode() throws ActiveMQException { locateNode(-1L); } @Override - public void locateNode(long timeout) throws ActiveMQException - { - try - { + public void locateNode(long timeout) throws ActiveMQException { + try { lock.lock(); - if (connectors.isEmpty()) - { - try - { - if (timeout != -1L) - { - if (!condition.await(timeout, TimeUnit.MILLISECONDS)) - { + if (connectors.isEmpty()) { + try { + if (timeout != -1L) { + if (!condition.await(timeout, TimeUnit.MILLISECONDS)) { throw new ActiveMQException("Timeout elapsed while waiting for cluster node"); } } - else - { + else { condition.await(); } } - catch (InterruptedException e) - { + catch (InterruptedException e) { //ignore } } } - finally - { + finally { lock.unlock(); } } @Override - public void nodeUP(TopologyMember topologyMember, boolean last) - { - try - { + public void nodeUP(TopologyMember topologyMember, boolean last) { + try { lock.lock(); - Pair connector = - new Pair(topologyMember.getLive(), topologyMember.getBackup()); + Pair connector = new Pair(topologyMember.getLive(), topologyMember.getBackup()); - if (topologyMember.getNodeId().equals(myNodeID)) - { - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + if (topologyMember.getNodeId().equals(myNodeID)) { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace(this + "::informing node about itself, nodeUUID=" + - server.getNodeID() + ", connectorPair=" + topologyMember + ", this = " + this); + server.getNodeID() + ", connectorPair=" + topologyMember + ", this = " + this); } return; } if (scaleDownGroupName.equals(topologyMember.getScaleDownGroupName()) && topologyMember.getLive() != null && - server.checkLiveIsNotColocated(topologyMember.getNodeId())) - { + server.checkLiveIsNotColocated(topologyMember.getNodeId())) { connectors.put(topologyMember.getNodeId(), connector); condition.signal(); } } - finally - { + finally { lock.unlock(); } } @Override - public void nodeDown(long eventUID, String nodeID) - { - try - { + public void nodeDown(long eventUID, String nodeID) { + try { lock.lock(); connectors.remove(nodeID); - if (connectors.size() > 0) - { + if (connectors.size() > 0) { condition.signal(); } } - finally - { + finally { lock.unlock(); } } @Override - public String getNodeID() - { + public String getNodeID() { return nodeID; } @Override - public Pair getLiveConfiguration() - { - try - { + public Pair getLiveConfiguration() { + try { lock.lock(); Iterator iterator = connectors.keySet().iterator(); //sanity check but this should never happen - if (iterator.hasNext()) - { + if (iterator.hasNext()) { nodeID = iterator.next(); } return connectors.get(nodeID); } - finally - { + finally { lock.unlock(); } } @Override - public void notifyRegistrationFailed(boolean alreadyReplicating) - { - try - { + public void notifyRegistrationFailed(boolean alreadyReplicating) { + try { lock.lock(); connectors.remove(nodeID); } - finally - { + finally { lock.unlock(); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/NamedNodeIdNodeLocator.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/NamedNodeIdNodeLocator.java index 22463247cb..a204faffb0 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/NamedNodeIdNodeLocator.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/NamedNodeIdNodeLocator.java @@ -16,59 +16,51 @@ */ package org.apache.activemq.artemis.core.server.impl; - import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.api.core.Pair; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.api.core.client.TopologyMember; import org.apache.activemq.artemis.core.server.LiveNodeLocator; -public class NamedNodeIdNodeLocator extends LiveNodeLocator -{ +public class NamedNodeIdNodeLocator extends LiveNodeLocator { + private final String nodeID; private final Pair liveConfiguration; - public NamedNodeIdNodeLocator(String nodeID, Pair liveConfiguration) - { + public NamedNodeIdNodeLocator(String nodeID, + Pair liveConfiguration) { this.nodeID = nodeID; this.liveConfiguration = liveConfiguration; } - @Override - public void locateNode(long timeout) throws ActiveMQException - { + public void locateNode(long timeout) throws ActiveMQException { //noop } @Override - public void locateNode() throws ActiveMQException - { + public void locateNode() throws ActiveMQException { //noop } @Override - public Pair getLiveConfiguration() - { + public Pair getLiveConfiguration() { return liveConfiguration; } @Override - public String getNodeID() - { + public String getNodeID() { return nodeID; } @Override - public void nodeUP(TopologyMember member, boolean last) - { + public void nodeUP(TopologyMember member, boolean last) { } @Override - public void nodeDown(long eventUID, String nodeID) - { + public void nodeDown(long eventUID, String nodeID) { } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/PostOfficeJournalLoader.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/PostOfficeJournalLoader.java index ea0c8da082..47793c1439 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/PostOfficeJournalLoader.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/PostOfficeJournalLoader.java @@ -60,8 +60,8 @@ import org.apache.activemq.artemis.core.transaction.ResourceManager; import org.apache.activemq.artemis.core.transaction.Transaction; import org.apache.activemq.artemis.core.transaction.impl.TransactionImpl; -public class PostOfficeJournalLoader implements JournalLoader -{ +public class PostOfficeJournalLoader implements JournalLoader { + protected final PostOffice postOffice; protected final PagingManager pagingManager; private StorageManager storageManager; @@ -79,8 +79,7 @@ public class PostOfficeJournalLoader implements JournalLoader NodeManager nodeManager, ManagementService managementService, GroupingHandler groupingHandler, - Configuration configuration) - { + Configuration configuration) { this.postOffice = postOffice; this.pagingManager = pagingManager; @@ -101,39 +100,33 @@ public class PostOfficeJournalLoader implements JournalLoader ManagementService managementService, GroupingHandler groupingHandler, Configuration configuration, - Map queues) - { + Map queues) { this(postOffice, pagingManager, storageManager, queueFactory, nodeManager, managementService, groupingHandler, configuration); this.queues = queues; } @Override - public void initQueues(Map queueBindingInfosMap, List queueBindingInfos) throws Exception - { + public void initQueues(Map queueBindingInfosMap, + List queueBindingInfos) throws Exception { int duplicateID = 0; - for (QueueBindingInfo queueBindingInfo : queueBindingInfos) - { + for (QueueBindingInfo queueBindingInfo : queueBindingInfos) { queueBindingInfosMap.put(queueBindingInfo.getId(), queueBindingInfo); Filter filter = FilterImpl.createFilter(queueBindingInfo.getFilterString()); - boolean isTopicIdentification = - filter != null && filter.getFilterString() != null && - filter.getFilterString().toString().equals(ActiveMQServerImpl.GENERIC_IGNORED_FILTER); + boolean isTopicIdentification = filter != null && filter.getFilterString() != null && + filter.getFilterString().toString().equals(ActiveMQServerImpl.GENERIC_IGNORED_FILTER); - if (postOffice.getBinding(queueBindingInfo.getQueueName()) != null) - { + if (postOffice.getBinding(queueBindingInfo.getQueueName()) != null) { - if (isTopicIdentification) - { + if (isTopicIdentification) { long tx = storageManager.generateID(); storageManager.deleteQueueBinding(tx, queueBindingInfo.getId()); storageManager.commitBindings(tx); continue; } - else - { + else { SimpleString newName = queueBindingInfo.getQueueName().concat("-" + (duplicateID++)); ActiveMQServerLogger.LOGGER.queueDuplicatedRenaming(queueBindingInfo.getQueueName().toString(), newName.toString()); @@ -143,26 +136,14 @@ public class PostOfficeJournalLoader implements JournalLoader PageSubscription subscription = null; - if (!isTopicIdentification) - { - subscription = pagingManager.getPageStore(queueBindingInfo.getAddress()) - .getCursorProvider() - .createSubscription(queueBindingInfo.getId(), filter, true); + if (!isTopicIdentification) { + subscription = pagingManager.getPageStore(queueBindingInfo.getAddress()).getCursorProvider().createSubscription(queueBindingInfo.getId(), filter, true); } - Queue queue = queueFactory.createQueue(queueBindingInfo.getId(), - queueBindingInfo.getAddress(), - queueBindingInfo.getQueueName(), - filter, - subscription, - queueBindingInfo.getUser(), - true, - false, - queueBindingInfo.isAutoCreated()); + Queue queue = queueFactory.createQueue(queueBindingInfo.getId(), queueBindingInfo.getAddress(), queueBindingInfo.getQueueName(), filter, subscription, queueBindingInfo.getUser(), true, false, queueBindingInfo.isAutoCreated()); - if (queueBindingInfo.isAutoCreated()) - { - queue.setConsumersRefCount(new AutoCreatedQueueManagerImpl(((PostOfficeImpl)postOffice).getServer(), queueBindingInfo.getQueueName())); + if (queueBindingInfo.isAutoCreated()) { + queue.setConsumersRefCount(new AutoCreatedQueueManagerImpl(((PostOfficeImpl) postOffice).getServer(), queueBindingInfo.getQueueName())); } Binding binding = new LocalQueueBinding(queueBindingInfo.getAddress(), queue, nodeManager.getNodeId()); @@ -177,20 +158,16 @@ public class PostOfficeJournalLoader implements JournalLoader } } - public void handleAddMessage(Map> queueMap) throws Exception - { - for (Map.Entry> entry : queueMap.entrySet()) - { + public void handleAddMessage(Map> queueMap) throws Exception { + for (Map.Entry> entry : queueMap.entrySet()) { long queueID = entry.getKey(); Map queueRecords = entry.getValue(); Queue queue = this.queues.get(queueID); - if (queue == null) - { - if (queueRecords.values().size() != 0) - { + if (queue == null) { + if (queueRecords.values().size() != 0) { ActiveMQServerLogger.LOGGER.journalCannotFindQueueForMessage(queueID); } @@ -206,18 +183,15 @@ public class PostOfficeJournalLoader implements JournalLoader long currentTime = System.currentTimeMillis(); - for (AddMessageRecord record : valueRecords) - { + for (AddMessageRecord record : valueRecords) { long scheduledDeliveryTime = record.getScheduledDeliveryTime(); - if (scheduledDeliveryTime != 0 && scheduledDeliveryTime <= currentTime) - { + if (scheduledDeliveryTime != 0 && scheduledDeliveryTime <= currentTime) { scheduledDeliveryTime = 0; record.getMessage().removeProperty(Message.HDR_SCHEDULED_DELIVERY_TIME); } - if (scheduledDeliveryTime != 0) - { + if (scheduledDeliveryTime != 0) { record.getMessage().putLongProperty(Message.HDR_SCHEDULED_DELIVERY_TIME, scheduledDeliveryTime); } @@ -225,27 +199,21 @@ public class PostOfficeJournalLoader implements JournalLoader ref.setDeliveryCount(record.getDeliveryCount()); - if (scheduledDeliveryTime != 0) - { + if (scheduledDeliveryTime != 0) { record.getMessage().removeProperty(Message.HDR_SCHEDULED_DELIVERY_TIME); } } } } - public void handleNoMessageReferences(Map messages) - { - for (ServerMessage msg : messages.values()) - { - if (msg.getRefCount() == 0) - { + public void handleNoMessageReferences(Map messages) { + for (ServerMessage msg : messages.values()) { + if (msg.getRefCount() == 0) { ActiveMQServerLogger.LOGGER.journalUnreferencedMessage(msg.getMessageID()); - try - { + try { storageManager.deleteMessage(msg.getMessageID()); } - catch (Exception ignored) - { + catch (Exception ignored) { ActiveMQServerLogger.LOGGER.journalErrorDeletingMessage(ignored, msg.getMessageID()); } } @@ -253,56 +221,45 @@ public class PostOfficeJournalLoader implements JournalLoader } @Override - public void handleGroupingBindings(List groupingInfos) - { - for (GroupingInfo groupingInfo : groupingInfos) - { - if (groupingHandler != null) - { - groupingHandler.addGroupBinding(new GroupBinding(groupingInfo.getId(), - groupingInfo.getGroupId(), - groupingInfo.getClusterName())); + public void handleGroupingBindings(List groupingInfos) { + for (GroupingInfo groupingInfo : groupingInfos) { + if (groupingHandler != null) { + groupingHandler.addGroupBinding(new GroupBinding(groupingInfo.getId(), groupingInfo.getGroupId(), groupingInfo.getClusterName())); } } } @Override - public void handleDuplicateIds(Map>> duplicateIDMap) throws Exception - { - for (Map.Entry>> entry : duplicateIDMap.entrySet()) - { + public void handleDuplicateIds(Map>> duplicateIDMap) throws Exception { + for (Map.Entry>> entry : duplicateIDMap.entrySet()) { SimpleString address = entry.getKey(); DuplicateIDCache cache = postOffice.getDuplicateIDCache(address); - if (configuration.isPersistIDCache()) - { + if (configuration.isPersistIDCache()) { cache.load(entry.getValue()); } } } @Override - public void postLoad(Journal messageJournal, ResourceManager resourceManager, Map>> duplicateIDMap) throws Exception - { - for (Queue queue : queues.values()) - { + public void postLoad(Journal messageJournal, + ResourceManager resourceManager, + Map>> duplicateIDMap) throws Exception { + for (Queue queue : queues.values()) { queue.resume(); } - if (System.getProperty("org.apache.activemq.opt.directblast") != null) - { + if (System.getProperty("org.apache.activemq.opt.directblast") != null) { messageJournal.runDirectJournalBlast(); } } @Override - public void handlePreparedSendMessage(ServerMessage message, Transaction tx, long queueID) throws Exception - { + public void handlePreparedSendMessage(ServerMessage message, Transaction tx, long queueID) throws Exception { Queue queue = queues.get(queueID); - if (queue == null) - { + if (queue == null) { ActiveMQServerLogger.LOGGER.journalMessageInPreparedTX(queueID); return; } @@ -310,32 +267,31 @@ public class PostOfficeJournalLoader implements JournalLoader } @Override - public void handlePreparedAcknowledge(long messageID, List referencesToAck, long queueID) throws Exception - { + public void handlePreparedAcknowledge(long messageID, + List referencesToAck, + long queueID) throws Exception { Queue queue = queues.get(queueID); - if (queue == null) - { + if (queue == null) { throw new IllegalStateException("Cannot find queue with id " + queueID); } MessageReference removed = queue.removeReferenceWithID(messageID); - if (removed == null) - { + if (removed == null) { ActiveMQServerLogger.LOGGER.journalErrorRemovingRef(messageID); } - else - { + else { referencesToAck.add(removed); } } @Override - public void handlePreparedTransaction(Transaction tx, List referencesToAck, Xid xid, ResourceManager resourceManager) throws Exception - { - for (MessageReference ack : referencesToAck) - { + public void handlePreparedTransaction(Transaction tx, + List referencesToAck, + Xid xid, + ResourceManager resourceManager) throws Exception { + for (MessageReference ack : referencesToAck) { ack.getQueue().reacknowledge(tx, ack); } @@ -350,8 +306,7 @@ public class PostOfficeJournalLoader implements JournalLoader * @param pendingNonTXPageCounter * @throws Exception */ - public void recoverPendingPageCounters(List pendingNonTXPageCounter) throws Exception - { + public void recoverPendingPageCounters(List pendingNonTXPageCounter) throws Exception { // We need a structure of the following // Address -> PageID -> QueueID -> List // The following loop will sort the records according to the hierarchy we need @@ -360,23 +315,20 @@ public class PostOfficeJournalLoader implements JournalLoader Map>>> perAddressMap = generateMapsOnPendingCount(queues, pendingNonTXPageCounter, txRecoverCounter); - for (SimpleString address : perAddressMap.keySet()) - { + for (SimpleString address : perAddressMap.keySet()) { PagingStore store = pagingManager.getPageStore(address); Map>> perPageMap = perAddressMap.get(address); // We have already generated this before, so it can't be null assert (perPageMap != null); - for (Long pageId : perPageMap.keySet()) - { + for (Long pageId : perPageMap.keySet()) { Map> perQueue = perPageMap.get(pageId); // This can't be true! assert (perQueue != null); - if (store.checkPageFileExists(pageId.intValue())) - { + if (store.checkPageFileExists(pageId.intValue())) { // on this case we need to recalculate the records Page pg = store.createPage(pageId.intValue()); pg.open(); @@ -384,15 +336,11 @@ public class PostOfficeJournalLoader implements JournalLoader List pgMessages = pg.read(storageManager); Map countsPerQueueOnPage = new HashMap(); - for (PagedMessage pgd : pgMessages) - { - if (pgd.getTransactionID() <= 0) - { - for (long q : pgd.getQueueIDs()) - { + for (PagedMessage pgd : pgMessages) { + if (pgd.getTransactionID() <= 0) { + for (long q : pgd.getQueueIDs()) { AtomicInteger countQ = countsPerQueueOnPage.get(q); - if (countQ == null) - { + if (countQ == null) { countQ = new AtomicInteger(0); countsPerQueueOnPage.put(q, countQ); } @@ -401,10 +349,8 @@ public class PostOfficeJournalLoader implements JournalLoader } } - for (Map.Entry> entry : perQueue.entrySet()) - { - for (PageCountPending record : entry.getValue()) - { + for (Map.Entry> entry : perQueue.entrySet()) { + for (PageCountPending record : entry.getValue()) { ActiveMQServerLogger.LOGGER.debug("Deleting pg tempCount " + record.getID()); storageManager.deletePendingPageCounter(txRecoverCounter.getID(), record.getID()); } @@ -413,25 +359,20 @@ public class PostOfficeJournalLoader implements JournalLoader AtomicInteger value = countsPerQueueOnPage.get(entry.getKey()); - if (value == null) - { + if (value == null) { ActiveMQServerLogger.LOGGER.debug("Page " + entry.getKey() + " wasn't open, so we will just ignore"); } - else - { + else { ActiveMQServerLogger.LOGGER.debug("Replacing counter " + value.get()); counter.increment(txRecoverCounter, value.get()); } } } - else - { + else { // on this case the page file didn't exist, we just remove all the records since the page is already gone ActiveMQServerLogger.LOGGER.debug("Page " + pageId + " didn't exist on address " + address + ", so we are just removing records"); - for (List records : perQueue.values()) - { - for (PageCountPending record : records) - { + for (List records : perQueue.values()) { + for (PageCountPending record : records) { ActiveMQServerLogger.LOGGER.debug("Removing pending page counter " + record.getID()); storageManager.deletePendingPageCounter(txRecoverCounter.getID(), record.getID()); txRecoverCounter.setContainsPersistent(); @@ -445,8 +386,7 @@ public class PostOfficeJournalLoader implements JournalLoader } @Override - public void cleanUp() - { + public void cleanUp() { queues.clear(); } @@ -459,21 +399,18 @@ public class PostOfficeJournalLoader implements JournalLoader * @return * @throws Exception */ - private Map>>> - generateMapsOnPendingCount(Map queues, List - pendingNonTXPageCounter, Transaction txRecoverCounter) throws Exception - { + private Map>>> generateMapsOnPendingCount(Map queues, + List pendingNonTXPageCounter, + Transaction txRecoverCounter) throws Exception { Map>>> perAddressMap = new HashMap>>>(); - for (PageCountPending pgCount : pendingNonTXPageCounter) - { + for (PageCountPending pgCount : pendingNonTXPageCounter) { long queueID = pgCount.getQueueID(); long pageID = pgCount.getPageID(); // We first figure what Queue is based on the queue id Queue queue = queues.get(queueID); - if (queue == null) - { + if (queue == null) { ActiveMQServerLogger.LOGGER.debug("removing pending page counter id = " + pgCount.getID() + " as queueID=" + pgCount.getID() + " no longer exists"); // this means the queue doesn't exist any longer, we will remove it from the storage storageManager.deletePendingPageCounter(txRecoverCounter.getID(), pgCount.getID()); @@ -486,25 +423,21 @@ public class PostOfficeJournalLoader implements JournalLoader Map>> perPageMap = perAddressMap.get(address); - if (perPageMap == null) - { + if (perPageMap == null) { perPageMap = new HashMap(); perAddressMap.put(address, perPageMap); } - Map> perQueueMap = perPageMap.get(pageID); - if (perQueueMap == null) - { + if (perQueueMap == null) { perQueueMap = new HashMap(); perPageMap.put(pageID, perQueueMap); } List pendingCounters = perQueueMap.get(queueID); - if (pendingCounters == null) - { + if (pendingCounters == null) { pendingCounters = new LinkedList(); perQueueMap.put(queueID, pendingCounters); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/QueueFactoryImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/QueueFactoryImpl.java index 57826e6670..d3089af73c 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/QueueFactoryImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/QueueFactoryImpl.java @@ -30,16 +30,17 @@ import org.apache.activemq.artemis.core.settings.impl.AddressSettings; import org.apache.activemq.artemis.utils.ExecutorFactory; /** - * * A QueueFactoryImpl */ -public class QueueFactoryImpl implements QueueFactory -{ +public class QueueFactoryImpl implements QueueFactory { + protected final HierarchicalRepository addressSettingsRepository; protected final ScheduledExecutorService scheduledExecutor; - /** This is required for delete-all-reference to work correctly with paging, and controlling global-size */ + /** + * This is required for delete-all-reference to work correctly with paging, and controlling global-size + */ protected PostOffice postOffice; protected final StorageManager storageManager; @@ -49,8 +50,7 @@ public class QueueFactoryImpl implements QueueFactory public QueueFactoryImpl(final ExecutorFactory executorFactory, final ScheduledExecutorService scheduledExecutor, final HierarchicalRepository addressSettingsRepository, - final StorageManager storageManager) - { + final StorageManager storageManager) { this.addressSettingsRepository = addressSettingsRepository; this.scheduledExecutor = scheduledExecutor; @@ -60,8 +60,7 @@ public class QueueFactoryImpl implements QueueFactory this.executorFactory = executorFactory; } - public void setPostOffice(final PostOffice postOffice) - { + public void setPostOffice(final PostOffice postOffice) { this.postOffice = postOffice; } @@ -73,44 +72,15 @@ public class QueueFactoryImpl implements QueueFactory final SimpleString user, final boolean durable, final boolean temporary, - final boolean autoCreated) - { + final boolean autoCreated) { AddressSettings addressSettings = addressSettingsRepository.getMatch(address.toString()); Queue queue; - if (addressSettings.isLastValueQueue()) - { - queue = new LastValueQueue(persistenceID, - address, - name, - filter, - pageSubscription, - user, - durable, - temporary, - autoCreated, - scheduledExecutor, - postOffice, - storageManager, - addressSettingsRepository, - executorFactory.getExecutor()); + if (addressSettings.isLastValueQueue()) { + queue = new LastValueQueue(persistenceID, address, name, filter, pageSubscription, user, durable, temporary, autoCreated, scheduledExecutor, postOffice, storageManager, addressSettingsRepository, executorFactory.getExecutor()); } - else - { - queue = new QueueImpl(persistenceID, - address, - name, - filter, - pageSubscription, - user, - durable, - temporary, - autoCreated, - scheduledExecutor, - postOffice, - storageManager, - addressSettingsRepository, - executorFactory.getExecutor()); + else { + queue = new QueueImpl(persistenceID, address, name, filter, pageSubscription, user, durable, temporary, autoCreated, scheduledExecutor, postOffice, storageManager, addressSettingsRepository, executorFactory.getExecutor()); } return queue; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/QueueImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/QueueImpl.java index 92cdbf9e3d..2ac5c8aa41 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/QueueImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/QueueImpl.java @@ -93,8 +93,8 @@ import org.apache.activemq.artemis.utils.TypedProperties; *

    * Completely non blocking between adding to queue and delivering to consumers. */ -public class QueueImpl implements Queue -{ +public class QueueImpl implements Queue { + private static final boolean isTrace = ActiveMQServerLogger.LOGGER.isTraceEnabled(); public static final int REDISTRIBUTOR_BATCH_SIZE = 100; @@ -236,72 +236,58 @@ public class QueueImpl implements Queue /** * For testing only */ - public List getGroupsUsed() - { + public List getGroupsUsed() { final CountDownLatch flush = new CountDownLatch(1); - executor.execute(new Runnable() - { - public void run() - { + executor.execute(new Runnable() { + public void run() { flush.countDown(); } }); - try - { + try { flush.await(10, TimeUnit.SECONDS); } - catch (Exception ignored) - { + catch (Exception ignored) { } - synchronized (this) - { + synchronized (this) { ArrayList groupsUsed = new ArrayList(); groupsUsed.addAll(groups.keySet()); return groupsUsed; } } - public String debug() - { + public String debug() { StringWriter str = new StringWriter(); PrintWriter out = new PrintWriter(str); out.println("queueMemorySize=" + queueMemorySize); - for (ConsumerHolder holder : consumerList) - { + for (ConsumerHolder holder : consumerList) { out.println("consumer: " + holder.consumer.debug()); } - for (MessageReference reference : intermediateMessageReferences) - { + for (MessageReference reference : intermediateMessageReferences) { out.print("Intermediate reference:" + reference); } - if (intermediateMessageReferences.isEmpty()) - { + if (intermediateMessageReferences.isEmpty()) { out.println("No intermediate references"); } boolean foundRef = false; - synchronized (this) - { + synchronized (this) { Iterator iter = messageReferences.iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { foundRef = true; out.println("reference = " + iter.next()); } } - if (!foundRef) - { + if (!foundRef) { out.println("No permanent references on queue"); } - System.out.println(str.toString()); return str.toString(); @@ -319,22 +305,8 @@ public class QueueImpl implements Queue final PostOffice postOffice, final StorageManager storageManager, final HierarchicalRepository addressSettingsRepository, - final Executor executor) - { - this(id, - address, - name, - filter, - null, - user, - durable, - temporary, - autoCreated, - scheduledExecutor, - postOffice, - storageManager, - addressSettingsRepository, - executor); + final Executor executor) { + this(id, address, name, filter, null, user, durable, temporary, autoCreated, scheduledExecutor, postOffice, storageManager, addressSettingsRepository, executor); } public QueueImpl(final long id, @@ -350,8 +322,7 @@ public class QueueImpl implements Queue final PostOffice postOffice, final StorageManager storageManager, final HierarchicalRepository addressSettingsRepository, - final Executor executor) - { + final Executor executor) { this.id = id; this.address = address; @@ -378,23 +349,19 @@ public class QueueImpl implements Queue scheduledDeliveryHandler = new ScheduledDeliveryHandlerImpl(scheduledExecutor); - if (addressSettingsRepository != null) - { + if (addressSettingsRepository != null) { addressSettingsRepositoryListener = new AddressSettingsRepositoryListener(); addressSettingsRepository.registerListener(addressSettingsRepositoryListener); } - else - { + else { expiryAddress = null; } - if (pageSubscription != null) - { + if (pageSubscription != null) { pageSubscription.setQueue(this); this.pageIterator = pageSubscription.iterator(); } - else - { + else { this.pageIterator = null; } @@ -405,96 +372,76 @@ public class QueueImpl implements Queue // Bindable implementation ------------------------------------------------------------------------------------- - public SimpleString getRoutingName() - { + public SimpleString getRoutingName() { return name; } - public SimpleString getUniqueName() - { + public SimpleString getUniqueName() { return name; } - public SimpleString getUser() - { + public SimpleString getUser() { return user; } - public boolean isExclusive() - { + public boolean isExclusive() { return false; } - public void route(final ServerMessage message, final RoutingContext context) throws Exception - { + public void route(final ServerMessage message, final RoutingContext context) throws Exception { context.addQueue(address, this); } @Override - public void routeWithAck(ServerMessage message, RoutingContext context) - { + public void routeWithAck(ServerMessage message, RoutingContext context) { context.addQueueWithAck(address, this); } // Queue implementation ---------------------------------------------------------------------------------------- - public synchronized void setConsumersRefCount(final ReferenceCounter referenceCounter) - { - if (refCountForConsumers == null) - { + public synchronized void setConsumersRefCount(final ReferenceCounter referenceCounter) { + if (refCountForConsumers == null) { this.refCountForConsumers = referenceCounter; } } - public ReferenceCounter getConsumersRefCount() - { + public ReferenceCounter getConsumersRefCount() { return refCountForConsumers; } - - public boolean isDurable() - { + public boolean isDurable() { return durable; } - public boolean isTemporary() - { + public boolean isTemporary() { return temporary; } - public boolean isAutoCreated() - { + public boolean isAutoCreated() { return autoCreated; } - public SimpleString getName() - { + public SimpleString getName() { return name; } - public SimpleString getAddress() - { + public SimpleString getAddress() { return address; } - public long getID() - { + public long getID() { return id; } - public PageSubscription getPageSubscription() - { + public PageSubscription getPageSubscription() { return pageSubscription; } - public Filter getFilter() - { + public Filter getFilter() { return filter; } - public void unproposed(final SimpleString groupID) - { - if (groupID.toString().endsWith("." + this.getName())) - { + public void unproposed(final SimpleString groupID) { + if (groupID.toString().endsWith("." + this.getName())) { // this means this unproposed belongs to this routing, so we will // remove this group @@ -502,18 +449,13 @@ public class QueueImpl implements Queue // this is because a groupID is stored per queue, and only this queue is expiring at this point final SimpleString groupIDToRemove = (SimpleString) groupID.subSequence(0, groupID.length() - getName().length() - 1); // using an executor so we don't want to hold anyone just because of this - getExecutor().execute(new Runnable() - { - public void run() - { - synchronized (QueueImpl.this) - { - if (groups.remove(groupIDToRemove) != null) - { + getExecutor().execute(new Runnable() { + public void run() { + synchronized (QueueImpl.this) { + if (groups.remove(groupIDToRemove) != null) { ActiveMQServerLogger.LOGGER.debug("Removing group after unproposal " + groupID + " from queue " + QueueImpl.this); } - else - { + else { ActiveMQServerLogger.LOGGER.debug("Couldn't remove Removing group " + groupIDToRemove + " after unproposal on queue " + QueueImpl.this); } } @@ -523,11 +465,9 @@ public class QueueImpl implements Queue } /* Called when a message is cancelled back into the queue */ - public synchronized void addHead(final MessageReference ref) - { + public synchronized void addHead(final MessageReference ref) { flushDeliveriesInTransit(); - if (scheduledDeliveryHandler.checkAndSchedule(ref, false)) - { + if (scheduledDeliveryHandler.checkAndSchedule(ref, false)) { return; } @@ -537,11 +477,9 @@ public class QueueImpl implements Queue } /* Called when a message is cancelled back into the queue */ - public synchronized void addHead(final List refs) - { + public synchronized void addHead(final List refs) { flushDeliveriesInTransit(); - for (MessageReference ref : refs) - { + for (MessageReference ref : refs) { addHead(ref); } @@ -550,11 +488,9 @@ public class QueueImpl implements Queue deliverAsync(); } - public synchronized void reload(final MessageReference ref) - { + public synchronized void reload(final MessageReference ref) { queueMemorySize.addAndGet(ref.getMessageMemoryEstimate()); - if (!scheduledDeliveryHandler.checkAndSchedule(ref, true)) - { + if (!scheduledDeliveryHandler.checkAndSchedule(ref, true)) { internalAddTail(ref); } @@ -563,43 +499,35 @@ public class QueueImpl implements Queue messagesAdded++; } - public void addTail(final MessageReference ref) - { + public void addTail(final MessageReference ref) { addTail(ref, false); } - public void addTail(final MessageReference ref, final boolean direct) - { - if (scheduledDeliveryHandler.checkAndSchedule(ref, true)) - { - synchronized (this) - { + public void addTail(final MessageReference ref, final boolean direct) { + if (scheduledDeliveryHandler.checkAndSchedule(ref, true)) { + synchronized (this) { messagesAdded++; } return; } - synchronized (directDeliveryGuard) - { + synchronized (directDeliveryGuard) { // The checkDirect flag is periodically set to true, if the delivery is specified as direct then this causes the // directDeliver flag to be re-computed resulting in direct delivery if the queue is empty // We don't recompute it on every delivery since executing isEmpty is expensive for a ConcurrentQueue if (!directDeliver && direct && - System.currentTimeMillis() - lastDirectDeliveryCheck > CHECK_QUEUE_SIZE_PERIOD) - { + System.currentTimeMillis() - lastDirectDeliveryCheck > CHECK_QUEUE_SIZE_PERIOD) { lastDirectDeliveryCheck = System.currentTimeMillis(); if (intermediateMessageReferences.isEmpty() && messageReferences.isEmpty() && !pageIterator.hasNext() && - !pageSubscription.isPaging()) - { + !pageSubscription.isPaging()) { // We must block on the executor to ensure any async deliveries have completed or we might get out of order // deliveries - if (flushExecutor() && flushDeliveriesInTransit()) - { + if (flushExecutor() && flushDeliveriesInTransit()) { // Go into direct delivery mode directDeliver = true; } @@ -607,8 +535,7 @@ public class QueueImpl implements Queue } } - if (direct && directDeliver && deliveriesInTransit.getCount() == 0 && deliverDirect(ref)) - { + if (direct && directDeliver && deliveriesInTransit.getCount() == 0 && deliverDirect(ref)) { return; } @@ -626,58 +553,45 @@ public class QueueImpl implements Queue /** * This will wait for any pending deliveries to finish */ - private boolean flushDeliveriesInTransit() - { - try - { + private boolean flushDeliveriesInTransit() { + try { - if (deliveriesInTransit.await(DELIVERY_TIMEOUT)) - { + if (deliveriesInTransit.await(DELIVERY_TIMEOUT)) { return true; } - else - { + else { ActiveMQServerLogger.LOGGER.timeoutFlushInTransit(getName().toString(), getAddress().toString()); return false; } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e); return false; } } - public void forceDelivery() - { - if (pageSubscription != null && pageSubscription.isPaging()) - { - if (isTrace) - { + public void forceDelivery() { + if (pageSubscription != null && pageSubscription.isPaging()) { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Force delivery scheduling depage"); } scheduleDepage(false); } - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Force delivery deliverying async"); } deliverAsync(); } - public void deliverAsync() - { - if (scheduledRunners.get() < MAX_SCHEDULED_RUNNERS) - { + public void deliverAsync() { + if (scheduledRunners.get() < MAX_SCHEDULED_RUNNERS) { scheduledRunners.incrementAndGet(); - try - { + try { getExecutor().execute(deliverRunner); } - catch (RejectedExecutionException ignored) - { + catch (RejectedExecutionException ignored) { // no-op scheduledRunners.decrementAndGet(); } @@ -687,92 +601,74 @@ public class QueueImpl implements Queue } - public void close() throws Exception - { - if (checkQueueSizeFuture != null) - { + public void close() throws Exception { + if (checkQueueSizeFuture != null) { checkQueueSizeFuture.cancel(false); } - getExecutor().execute(new Runnable() - { - public void run() - { - try - { + getExecutor().execute(new Runnable() { + public void run() { + try { cancelRedistributor(); } - catch (Exception e) - { + catch (Exception e) { // nothing that could be done anyway.. just logging ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e); } } }); - if (addressSettingsRepository != null) - { + if (addressSettingsRepository != null) { addressSettingsRepository.unRegisterListener(addressSettingsRepositoryListener); } } - public Executor getExecutor() - { - if (pageSubscription != null && pageSubscription.isPaging()) - { + public Executor getExecutor() { + if (pageSubscription != null && pageSubscription.isPaging()) { // When in page mode, we don't want to have concurrent IO on the same PageStore return pageSubscription.getExecutor(); } - else - { + else { return executor; } } /* Only used on tests */ - public void deliverNow() - { + public void deliverNow() { deliverAsync(); flushExecutor(); } - public boolean flushExecutor() - { + public boolean flushExecutor() { boolean ok = internalFlushExecutor(10000); - if (!ok) - { + if (!ok) { ActiveMQServerLogger.LOGGER.errorFlushingExecutorsOnQueue(); } return ok; } - private boolean internalFlushExecutor(long timeout) - { + private boolean internalFlushExecutor(long timeout) { FutureLatch future = new FutureLatch(); getExecutor().execute(future); boolean result = future.await(timeout); - if (!result) - { + if (!result) { ActiveMQServerLogger.LOGGER.queueBusy(this.name.toString(), timeout); } return result; } - public void addConsumer(final Consumer consumer) throws Exception - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + public void addConsumer(final Consumer consumer) throws Exception { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug(this + " adding consumer " + consumer); } - synchronized (this) - { + synchronized (this) { flushDeliveriesInTransit(); consumersChanged = true; @@ -783,26 +679,20 @@ public class QueueImpl implements Queue consumerSet.add(consumer); - if (refCountForConsumers != null) - { + if (refCountForConsumers != null) { refCountForConsumers.increment(); } } } - public void removeConsumer(final Consumer consumer) - { - synchronized (this) - { + public void removeConsumer(final Consumer consumer) { + synchronized (this) { consumersChanged = true; - for (ConsumerHolder holder : consumerList) - { - if (holder.consumer == consumer) - { - if (holder.iter != null) - { + for (ConsumerHolder holder : consumerList) { + if (holder.consumer == consumer) { + if (holder.iter != null) { holder.iter.close(); } consumerList.remove(holder); @@ -810,8 +700,7 @@ public class QueueImpl implements Queue } } - if (pos > 0 && pos >= consumerList.size()) - { + if (pos > 0 && pos >= consumerList.size()) { pos = consumerList.size() - 1; } @@ -819,12 +708,9 @@ public class QueueImpl implements Queue LinkedList groupsToRemove = null; - for (SimpleString groupID : groups.keySet()) - { - if (consumer == groups.get(groupID)) - { - if (groupsToRemove == null) - { + for (SimpleString groupID : groups.keySet()) { + if (consumer == groups.get(groupID)) { + if (groupsToRemove == null) { groupsToRemove = new LinkedList(); } groupsToRemove.add(groupID); @@ -834,40 +720,32 @@ public class QueueImpl implements Queue // We use an auxiliary List here to avoid concurrent modification exceptions on the keySet // while the iteration is being done. // Since that's a simple HashMap there's no Iterator's support with a remove operation - if (groupsToRemove != null) - { - for (SimpleString groupID : groupsToRemove) - { + if (groupsToRemove != null) { + for (SimpleString groupID : groupsToRemove) { groups.remove(groupID); } } - if (refCountForConsumers != null) - { + if (refCountForConsumers != null) { refCountForConsumers.decrement(); } } } - public synchronized void addRedistributor(final long delay) - { - if (redistributorFuture != null) - { + public synchronized void addRedistributor(final long delay) { + if (redistributorFuture != null) { redistributorFuture.cancel(false); futures.remove(redistributorFuture); } - if (redistributor != null) - { + if (redistributor != null) { // Just prompt delivery deliverAsync(); } - if (delay > 0) - { - if (consumerSet.isEmpty()) - { + if (delay > 0) { + if (consumerSet.isEmpty()) { DelayedAddRedistributor dar = new DelayedAddRedistributor(executor); redistributorFuture = scheduledExecutor.schedule(dar, delay, TimeUnit.MILLISECONDS); @@ -875,16 +753,13 @@ public class QueueImpl implements Queue futures.add(redistributorFuture); } } - else - { + else { internalAddRedistributor(executor); } } - public synchronized void cancelRedistributor() throws Exception - { - if (redistributor != null) - { + public synchronized void cancelRedistributor() throws Exception { + if (redistributor != null) { redistributor.stop(); Redistributor redistributorToRemove = redistributor; redistributor = null; @@ -892,8 +767,7 @@ public class QueueImpl implements Queue removeConsumer(redistributorToRemove); } - if (redistributorFuture != null) - { + if (redistributorFuture != null) { redistributorFuture.cancel(false); redistributorFuture = null; @@ -901,10 +775,8 @@ public class QueueImpl implements Queue } @Override - protected void finalize() throws Throwable - { - if (checkQueueSizeFuture != null) - { + protected void finalize() throws Throwable { + if (checkQueueSizeFuture != null) { checkQueueSizeFuture.cancel(false); } @@ -913,37 +785,29 @@ public class QueueImpl implements Queue super.finalize(); } - public synchronized int getConsumerCount() - { + public synchronized int getConsumerCount() { return consumerSet.size(); } - public synchronized Set getConsumers() - { + public synchronized Set getConsumers() { return consumerSet; } - public boolean hasMatchingConsumer(final ServerMessage message) - { - for (ConsumerHolder holder : consumerList) - { + public boolean hasMatchingConsumer(final ServerMessage message) { + for (ConsumerHolder holder : consumerList) { Consumer consumer = holder.consumer; - if (consumer instanceof Redistributor) - { + if (consumer instanceof Redistributor) { continue; } Filter filter1 = consumer.getFilter(); - if (filter1 == null) - { + if (filter1 == null) { return true; } - else - { - if (filter1.match(message)) - { + else { + if (filter1.match(message)) { return true; } } @@ -951,31 +815,25 @@ public class QueueImpl implements Queue return false; } - public LinkedListIterator iterator() - { + public LinkedListIterator iterator() { return new SynchronizedIterator(messageReferences.iterator()); } - public TotalQueueIterator totalIterator() - { + public TotalQueueIterator totalIterator() { return new TotalQueueIterator(); } - public synchronized MessageReference removeReferenceWithID(final long id1) throws Exception - { + public synchronized MessageReference removeReferenceWithID(final long id1) throws Exception { LinkedListIterator iterator = iterator(); - try - { + try { MessageReference removed = null; - while (iterator.hasNext()) - { + while (iterator.hasNext()) { MessageReference ref = iterator.next(); - if (ref.getMessage().getMessageID() == id1) - { + if (ref.getMessage().getMessageID() == id1) { iterator.remove(); refRemoved(ref); @@ -985,86 +843,70 @@ public class QueueImpl implements Queue } } - if (removed == null) - { + if (removed == null) { // Look in scheduled deliveries removed = scheduledDeliveryHandler.removeReferenceWithID(id1); } return removed; } - finally - { + finally { iterator.close(); } } - public synchronized MessageReference getReference(final long id1) - { + public synchronized MessageReference getReference(final long id1) { LinkedListIterator iterator = iterator(); - try - { + try { - while (iterator.hasNext()) - { + while (iterator.hasNext()) { MessageReference ref = iterator.next(); - if (ref.getMessage().getMessageID() == id1) - { + if (ref.getMessage().getMessageID() == id1) { return ref; } } return null; } - finally - { + finally { iterator.close(); } } - public long getMessageCount() - { - synchronized (this) - { - if (pageSubscription != null) - { + public long getMessageCount() { + synchronized (this) { + if (pageSubscription != null) { // messageReferences will have depaged messages which we need to discount from the counter as they are // counted on the pageSubscription as well return messageReferences.size() + getScheduledCount() + deliveringCount.get() + pageSubscription.getMessageCount(); } - else - { + else { return messageReferences.size() + getScheduledCount() + deliveringCount.get(); } } } - public synchronized int getScheduledCount() - { + public synchronized int getScheduledCount() { return scheduledDeliveryHandler.getScheduledCount(); } - public synchronized List getScheduledMessages() - { + public synchronized List getScheduledMessages() { return scheduledDeliveryHandler.getScheduledReferences(); } - public Map> getDeliveringMessages() - { + public Map> getDeliveringMessages() { List consumerListClone = cloneConsumersList(); Map> mapReturn = new HashMap>(); - for (ConsumerHolder holder : consumerListClone) - { + for (ConsumerHolder holder : consumerListClone) { List msgs = holder.consumer.getDeliveringMessages(); - if (msgs != null && msgs.size() > 0) - { + if (msgs != null && msgs.size() > 0) { mapReturn.put(holder.consumer.toManagementString(), msgs); } } @@ -1072,26 +914,21 @@ public class QueueImpl implements Queue return mapReturn; } - public int getDeliveringCount() - { + public int getDeliveringCount() { return deliveringCount.get(); } - public void acknowledge(final MessageReference ref) throws Exception - { - if (ref.isPaged()) - { + public void acknowledge(final MessageReference ref) throws Exception { + if (ref.isPaged()) { pageSubscription.ack((PagedReference) ref); postAcknowledge(ref); } - else - { + else { ServerMessage message = ref.getMessage(); boolean durableRef = message.isDurable() && durable; - if (durableRef) - { + if (durableRef) { storageManager.storeAcknowledge(id, message.getMessageID()); } postAcknowledge(ref); @@ -1101,22 +938,18 @@ public class QueueImpl implements Queue } - public void acknowledge(final Transaction tx, final MessageReference ref) throws Exception - { - if (ref.isPaged()) - { + public void acknowledge(final Transaction tx, final MessageReference ref) throws Exception { + if (ref.isPaged()) { pageSubscription.ackTx(tx, (PagedReference) ref); getRefsOperation(tx).addAck(ref); } - else - { + else { ServerMessage message = ref.getMessage(); boolean durableRef = message.isDurable() && durable; - if (durableRef) - { + if (durableRef) { storageManager.storeAcknowledgeTransactional(tx.getID(), id, message.getMessageID()); tx.setContainsPersistent(); @@ -1128,12 +961,10 @@ public class QueueImpl implements Queue messagesAcknowledged++; } - public void reacknowledge(final Transaction tx, final MessageReference ref) throws Exception - { + public void reacknowledge(final Transaction tx, final MessageReference ref) throws Exception { ServerMessage message = ref.getMessage(); - if (message.isDurable() && durable) - { + if (message.isDurable() && durable) { tx.setContainsPersistent(); } @@ -1145,19 +976,15 @@ public class QueueImpl implements Queue messagesAcknowledged++; } - private RefsOperation getRefsOperation(final Transaction tx) - { + private RefsOperation getRefsOperation(final Transaction tx) { return getRefsOperation(tx, false); } - private RefsOperation getRefsOperation(final Transaction tx, boolean ignoreRedlieveryCheck) - { - synchronized (tx) - { + private RefsOperation getRefsOperation(final Transaction tx, boolean ignoreRedlieveryCheck) { + synchronized (tx) { RefsOperation oper = (RefsOperation) tx.getProperty(TransactionPropertyIndexes.REFS_OPERATION); - if (oper == null) - { + if (oper == null) { oper = tx.createRefsOperation(this); tx.putProperty(TransactionPropertyIndexes.REFS_OPERATION, oper); @@ -1165,8 +992,7 @@ public class QueueImpl implements Queue tx.addOperation(oper); } - if (ignoreRedlieveryCheck) - { + if (ignoreRedlieveryCheck) { oper.setIgnoreRedeliveryCheck(); } @@ -1174,76 +1000,59 @@ public class QueueImpl implements Queue } } - public void cancel(final Transaction tx, final MessageReference reference) - { + public void cancel(final Transaction tx, final MessageReference reference) { cancel(tx, reference, false); } - public void cancel(final Transaction tx, final MessageReference reference, boolean ignoreRedeliveryCheck) - { + public void cancel(final Transaction tx, final MessageReference reference, boolean ignoreRedeliveryCheck) { getRefsOperation(tx, ignoreRedeliveryCheck).addAck(reference); } - public synchronized void cancel(final MessageReference reference, final long timeBase) throws Exception - { - if (checkRedelivery(reference, timeBase, false)) - { - if (!scheduledDeliveryHandler.checkAndSchedule(reference, false)) - { + public synchronized void cancel(final MessageReference reference, final long timeBase) throws Exception { + if (checkRedelivery(reference, timeBase, false)) { + if (!scheduledDeliveryHandler.checkAndSchedule(reference, false)) { internalAddHead(reference); } resetAllIterators(); } - else - { + else { decDelivering(); } } - public void expire(final MessageReference ref) throws Exception - { - if (expiryAddress != null) - { - if (isTrace) - { + public void expire(final MessageReference ref) throws Exception { + if (expiryAddress != null) { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("moving expired reference " + ref + " to address = " + expiryAddress + " from queue=" + this.getName()); } move(expiryAddress, ref, true, false); } - else - { - if (isTrace) - { + else { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("expiry is null, just acking expired message for reference " + ref + " from queue=" + this.getName()); } acknowledge(ref); } } - public SimpleString getExpiryAddress() - { + public SimpleString getExpiryAddress() { return this.expiryAddress; } - public void referenceHandled() - { + public void referenceHandled() { incDelivering(); } - public void incrementMesssagesAdded() - { + public void incrementMesssagesAdded() { messagesAdded++; } @Override - public void deliverScheduledMessages() - { - List scheduledMessages = scheduledDeliveryHandler.cancel(null); - if (scheduledMessages != null && scheduledMessages.size() > 0) - { - for (MessageReference ref : scheduledMessages) - { + public void deliverScheduledMessages() { + List scheduledMessages = scheduledDeliveryHandler.cancel(null); + if (scheduledMessages != null && scheduledMessages.size() > 0) { + for (MessageReference ref : scheduledMessages) { ref.getMessage().putLongProperty(MessageImpl.HDR_SCHEDULED_DELIVERY_TIME, ref.getScheduledDeliveryTime()); ref.setScheduledDeliveryTime(0); } @@ -1251,46 +1060,35 @@ public class QueueImpl implements Queue } } - public long getMessagesAdded() - { - if (pageSubscription != null) - { + public long getMessagesAdded() { + if (pageSubscription != null) { return messagesAdded + pageSubscription.getCounter().getValue() - pagedReferences.get(); } - else - { + else { return messagesAdded; } } - public long getMessagesAcknowledged() - { + public long getMessagesAcknowledged() { return messagesAcknowledged; } - public int deleteAllReferences() throws Exception - { + public int deleteAllReferences() throws Exception { return deleteAllReferences(DEFAULT_FLUSH_LIMIT); } - public int deleteAllReferences(final int flushLimit) throws Exception - { + public int deleteAllReferences(final int flushLimit) throws Exception { return deleteMatchingReferences(flushLimit, null); } - public int deleteMatchingReferences(Filter filter) throws Exception - { + public int deleteMatchingReferences(Filter filter) throws Exception { return deleteMatchingReferences(DEFAULT_FLUSH_LIMIT, filter); } - - public synchronized int deleteMatchingReferences(final int flushLimit, final Filter filter1) throws Exception - { - return iterQueue(flushLimit, filter1, new QueueIterateAction() - { + public synchronized int deleteMatchingReferences(final int flushLimit, final Filter filter1) throws Exception { + return iterQueue(flushLimit, filter1, new QueueIterateAction() { @Override - public void actMessage(Transaction tx, MessageReference ref) throws Exception - { + public void actMessage(Transaction tx, MessageReference ref) throws Exception { incDelivering(); acknowledge(tx, ref); refRemoved(ref); @@ -1298,7 +1096,6 @@ public class QueueImpl implements Queue }); } - /** * This is a generic method for any method interacting on the Queue to move or delete messages * Instead of duplicate the feature we created an abstract class where you pass the logic for @@ -1309,31 +1106,28 @@ public class QueueImpl implements Queue * @return * @throws Exception */ - private synchronized int iterQueue(final int flushLimit, final Filter filter1, QueueIterateAction messageAction) throws Exception - { + private synchronized int iterQueue(final int flushLimit, + final Filter filter1, + QueueIterateAction messageAction) throws Exception { int count = 0; int txCount = 0; Transaction tx = new TransactionImpl(storageManager); LinkedListIterator iter = iterator(); - try - { + try { - while (iter.hasNext()) - { + while (iter.hasNext()) { MessageReference ref = iter.next(); - if (ref.isPaged() && queueDestroyed) - { + if (ref.isPaged() && queueDestroyed) { // this means the queue is being removed // hence paged references are just going away through // page cleanup continue; } - if (filter1 == null || filter1.match(ref.getMessage())) - { + if (filter1 == null || filter1.match(ref.getMessage())) { messageAction.actMessage(tx, ref); iter.remove(); txCount++; @@ -1341,8 +1135,7 @@ public class QueueImpl implements Queue } } - if (txCount > 0) - { + if (txCount > 0) { tx.commit(); tx = new TransactionImpl(storageManager); @@ -1351,41 +1144,33 @@ public class QueueImpl implements Queue } List cancelled = scheduledDeliveryHandler.cancel(filter1); - for (MessageReference messageReference : cancelled) - { + for (MessageReference messageReference : cancelled) { messageAction.actMessage(tx, messageReference); count++; txCount++; } - if (txCount > 0) - { + if (txCount > 0) { tx.commit(); tx = new TransactionImpl(storageManager); txCount = 0; } - - if (pageIterator != null && !queueDestroyed) - { - while (pageIterator.hasNext()) - { + if (pageIterator != null && !queueDestroyed) { + while (pageIterator.hasNext()) { PagedReference reference = pageIterator.next(); pageIterator.remove(); - if (filter1 == null || filter1.match(reference.getMessage())) - { + if (filter1 == null || filter1.match(reference.getMessage())) { count++; txCount++; messageAction.actMessage(tx, reference); } - else - { + else { addTail(reference, false); } - if (txCount > 0 && txCount % flushLimit == 0) - { + if (txCount > 0 && txCount % flushLimit == 0) { tx.commit(); tx = new TransactionImpl(storageManager); txCount = 0; @@ -1393,51 +1178,41 @@ public class QueueImpl implements Queue } } - if (txCount > 0) - { + if (txCount > 0) { tx.commit(); tx = null; } - - if (filter != null && !queueDestroyed && pageSubscription != null) - { + if (filter != null && !queueDestroyed && pageSubscription != null) { scheduleDepage(false); } return count; } - finally - { + finally { iter.close(); } } - public void destroyPaging() throws Exception - { + public void destroyPaging() throws Exception { // it could be null on embedded or certain unit tests - if (pageSubscription != null) - { + if (pageSubscription != null) { pageSubscription.destroy(); pageSubscription.cleanupEntries(true); } } - public synchronized boolean deleteReference(final long messageID) throws Exception - { + public synchronized boolean deleteReference(final long messageID) throws Exception { boolean deleted = false; Transaction tx = new TransactionImpl(storageManager); LinkedListIterator iter = iterator(); - try - { + try { - while (iter.hasNext()) - { + while (iter.hasNext()) { MessageReference ref = iter.next(); - if (ref.getMessage().getMessageID() == messageID) - { + if (ref.getMessage().getMessageID() == messageID) { incDelivering(); acknowledge(tx, ref); iter.remove(); @@ -1447,8 +1222,7 @@ public class QueueImpl implements Queue } } - if (!deleted) - { + if (!deleted) { // Look in scheduled deliveries deleted = scheduledDeliveryHandler.removeReferenceWithID(messageID) != null ? true : false; } @@ -1457,67 +1231,55 @@ public class QueueImpl implements Queue return deleted; } - finally - { + finally { iter.close(); } } - public void deleteQueue() throws Exception - { + public void deleteQueue() throws Exception { deleteQueue(false); } - public void deleteQueue(boolean removeConsumers) throws Exception - { - synchronized (this) - { + public void deleteQueue(boolean removeConsumers) throws Exception { + synchronized (this) { this.queueDestroyed = true; } Transaction tx = new BindingsTransactionImpl(storageManager); - try - { + try { postOffice.removeBinding(name, tx); deleteAllReferences(); destroyPaging(); - if (removeConsumers) - { - for (ConsumerHolder consumerHolder : consumerList) - { + if (removeConsumers) { + for (ConsumerHolder consumerHolder : consumerList) { consumerHolder.consumer.disconnect(); } } - if (isDurable()) - { + if (isDurable()) { storageManager.deleteQueueBinding(tx.getID(), getID()); tx.setContainsPersistent(); } - if (slowConsumerReaperFuture != null) - { + if (slowConsumerReaperFuture != null) { slowConsumerReaperFuture.cancel(false); } tx.commit(); } - catch (Exception e) - { + catch (Exception e) { tx.rollback(); throw e; } } - public synchronized boolean expireReference(final long messageID) throws Exception - { - if (expiryAddress != null && expiryAddress.equals(this.address)) - { + public synchronized boolean expireReference(final long messageID) throws Exception { + if (expiryAddress != null && expiryAddress.equals(this.address)) { // check expire with itself would be silly (waste of time) if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) ActiveMQServerLogger.LOGGER.debug("Cannot expire from " + address + " into " + expiryAddress); @@ -1525,14 +1287,11 @@ public class QueueImpl implements Queue } LinkedListIterator iter = iterator(); - try - { + try { - while (iter.hasNext()) - { + while (iter.hasNext()) { MessageReference ref = iter.next(); - if (ref.getMessage().getMessageID() == messageID) - { + if (ref.getMessage().getMessageID() == messageID) { incDelivering(); expire(ref); iter.remove(); @@ -1542,16 +1301,13 @@ public class QueueImpl implements Queue } return false; } - finally - { + finally { iter.close(); } } - public synchronized int expireReferences(final Filter filter) throws Exception - { - if (expiryAddress != null && expiryAddress.equals(this.address)) - { + public synchronized int expireReferences(final Filter filter) throws Exception { + if (expiryAddress != null && expiryAddress.equals(this.address)) { // check expire with itself would be silly (waste of time) if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) ActiveMQServerLogger.LOGGER.debug("Cannot expire from " + address + " into " + expiryAddress); @@ -1563,14 +1319,11 @@ public class QueueImpl implements Queue int count = 0; LinkedListIterator iter = iterator(); - try - { + try { - while (iter.hasNext()) - { + while (iter.hasNext()) { MessageReference ref = iter.next(); - if (filter == null || filter.match(ref.getMessage())) - { + if (filter == null || filter.match(ref.getMessage())) { incDelivering(); expire(tx, ref); iter.remove(); @@ -1583,56 +1336,45 @@ public class QueueImpl implements Queue return count; } - finally - { + finally { iter.close(); } } - public void expireReferences() - { - if (expiryAddress != null && expiryAddress.equals(this.address)) - { + public void expireReferences() { + if (expiryAddress != null && expiryAddress.equals(this.address)) { // check expire with itself would be silly (waste of time) if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) ActiveMQServerLogger.LOGGER.debug("Cannot expire from " + address + " into " + expiryAddress); return; } - if (!queueDestroyed && expiryScanner.scannerRunning.get() == 0) - { + if (!queueDestroyed && expiryScanner.scannerRunning.get() == 0) { expiryScanner.scannerRunning.incrementAndGet(); getExecutor().execute(expiryScanner); } } - class ExpiryScanner implements Runnable - { + class ExpiryScanner implements Runnable { + public AtomicInteger scannerRunning = new AtomicInteger(0); - public void run() - { - synchronized (QueueImpl.this) - { - if (queueDestroyed) - { + public void run() { + synchronized (QueueImpl.this) { + if (queueDestroyed) { return; } LinkedListIterator iter = iterator(); - try - { + try { boolean expired = false; boolean hasElements = false; - while (postOffice.isStarted() && iter.hasNext()) - { + while (postOffice.isStarted() && iter.hasNext()) { hasElements = true; MessageReference ref = iter.next(); - try - { - if (ref.getMessage().isExpired()) - { + try { + if (ref.getMessage().isExpired()) { incDelivering(); expired = true; expire(ref); @@ -1640,27 +1382,22 @@ public class QueueImpl implements Queue refRemoved(ref); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorExpiringReferencesOnQueue(e, ref); } } // If empty we need to schedule depaging to make sure we would depage expired messages as well - if ((!hasElements || expired) && pageIterator != null && pageIterator.hasNext()) - { + if ((!hasElements || expired) && pageIterator != null && pageIterator.hasNext()) { scheduleDepage(true); } } - finally - { - try - { + finally { + try { iter.close(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } scannerRunning.decrementAndGet(); } @@ -1668,17 +1405,13 @@ public class QueueImpl implements Queue } } - public synchronized boolean sendMessageToDeadLetterAddress(final long messageID) throws Exception - { + public synchronized boolean sendMessageToDeadLetterAddress(final long messageID) throws Exception { LinkedListIterator iter = iterator(); - try - { - while (iter.hasNext()) - { + try { + while (iter.hasNext()) { MessageReference ref = iter.next(); - if (ref.getMessage().getMessageID() == messageID) - { + if (ref.getMessage().getMessageID() == messageID) { incDelivering(); sendToDeadLetterAddress(ref); iter.remove(); @@ -1688,24 +1421,19 @@ public class QueueImpl implements Queue } return false; } - finally - { + finally { iter.close(); } } - public synchronized int sendMessagesToDeadLetterAddress(Filter filter) throws Exception - { + public synchronized int sendMessagesToDeadLetterAddress(Filter filter) throws Exception { int count = 0; LinkedListIterator iter = iterator(); - try - { - while (iter.hasNext()) - { + try { + while (iter.hasNext()) { MessageReference ref = iter.next(); - if (filter == null || filter.match(ref.getMessage())) - { + if (filter == null || filter.match(ref.getMessage())) { incDelivering(); sendToDeadLetterAddress(ref); iter.remove(); @@ -1715,39 +1443,31 @@ public class QueueImpl implements Queue } return count; } - finally - { + finally { iter.close(); } } - public boolean moveReference(final long messageID, final SimpleString toAddress) throws Exception - { + public boolean moveReference(final long messageID, final SimpleString toAddress) throws Exception { return moveReference(messageID, toAddress, false); } public synchronized boolean moveReference(final long messageID, final SimpleString toAddress, - final boolean rejectDuplicate) throws Exception - { + final boolean rejectDuplicate) throws Exception { LinkedListIterator iter = iterator(); - try - { - while (iter.hasNext()) - { + try { + while (iter.hasNext()) { MessageReference ref = iter.next(); - if (ref.getMessage().getMessageID() == messageID) - { + if (ref.getMessage().getMessageID() == messageID) { iter.remove(); refRemoved(ref); incDelivering(); - try - { + try { move(toAddress, ref, false, rejectDuplicate); } - catch (Exception e) - { + catch (Exception e) { decDelivering(); throw e; } @@ -1756,40 +1476,32 @@ public class QueueImpl implements Queue } return false; } - finally - { + finally { iter.close(); } } - public int moveReferences(final Filter filter, final SimpleString toAddress) throws Exception - { + public int moveReferences(final Filter filter, final SimpleString toAddress) throws Exception { return moveReferences(DEFAULT_FLUSH_LIMIT, filter, toAddress, false); } public synchronized int moveReferences(final int flushLimit, final Filter filter, final SimpleString toAddress, - final boolean rejectDuplicates) throws Exception - { + final boolean rejectDuplicates) throws Exception { final DuplicateIDCache targetDuplicateCache = postOffice.getDuplicateIDCache(toAddress); - return iterQueue(flushLimit, filter, new QueueIterateAction() - { + return iterQueue(flushLimit, filter, new QueueIterateAction() { @Override - public void actMessage(Transaction tx, MessageReference ref) throws Exception - { + public void actMessage(Transaction tx, MessageReference ref) throws Exception { boolean ignored = false; incDelivering(); - if (rejectDuplicates) - { + if (rejectDuplicates) { byte[] duplicateBytes = ref.getMessage().getDuplicateIDBytes(); - if (duplicateBytes != null) - { - if (targetDuplicateCache.contains(duplicateBytes)) - { + if (duplicateBytes != null) { + if (targetDuplicateCache.contains(duplicateBytes)) { ActiveMQServerLogger.LOGGER.messageWithDuplicateID(ref.getMessage().getDuplicateProperty(), toAddress, address, address); acknowledge(tx, ref); ignored = true; @@ -1797,38 +1509,30 @@ public class QueueImpl implements Queue } } - if (!ignored) - { + if (!ignored) { move(toAddress, tx, ref, false, rejectDuplicates); } } }); } - public synchronized int moveReferencesBetweenSnFQueues(final SimpleString queueSuffix) throws Exception - { - return iterQueue(DEFAULT_FLUSH_LIMIT, null, new QueueIterateAction() - { + public synchronized int moveReferencesBetweenSnFQueues(final SimpleString queueSuffix) throws Exception { + return iterQueue(DEFAULT_FLUSH_LIMIT, null, new QueueIterateAction() { @Override - public void actMessage(Transaction tx, MessageReference ref) throws Exception - { + public void actMessage(Transaction tx, MessageReference ref) throws Exception { moveBetweenSnFQueues(queueSuffix, tx, ref); } }); } - public synchronized boolean changeReferencePriority(final long messageID, final byte newPriority) throws Exception - { + public synchronized boolean changeReferencePriority(final long messageID, final byte newPriority) throws Exception { LinkedListIterator iter = iterator(); - try - { + try { - while (iter.hasNext()) - { + while (iter.hasNext()) { MessageReference ref = iter.next(); - if (ref.getMessage().getMessageID() == messageID) - { + if (ref.getMessage().getMessageID() == messageID) { iter.remove(); refRemoved(ref); ref.getMessage().setPriority(newPriority); @@ -1839,24 +1543,19 @@ public class QueueImpl implements Queue return false; } - finally - { + finally { iter.close(); } } - public synchronized int changeReferencesPriority(final Filter filter, final byte newPriority) throws Exception - { + public synchronized int changeReferencesPriority(final Filter filter, final byte newPriority) throws Exception { LinkedListIterator iter = iterator(); - try - { + try { int count = 0; - while (iter.hasNext()) - { + while (iter.hasNext()) { MessageReference ref = iter.next(); - if (filter == null || filter.match(ref.getMessage())) - { + if (filter == null || filter.match(ref.getMessage())) { count++; iter.remove(); refRemoved(ref); @@ -1866,67 +1565,55 @@ public class QueueImpl implements Queue } return count; } - finally - { + finally { iter.close(); } } - public synchronized void resetAllIterators() - { - for (ConsumerHolder holder : this.consumerList) - { - if (holder.iter != null) - { + public synchronized void resetAllIterators() { + for (ConsumerHolder holder : this.consumerList) { + if (holder.iter != null) { holder.iter.close(); } holder.iter = null; } } - public synchronized void pause() - { - try - { + public synchronized void pause() { + try { this.flushDeliveriesInTransit(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e); } paused = true; } - public synchronized void resume() - { + public synchronized void resume() { paused = false; deliverAsync(); } - public synchronized boolean isPaused() - { + public synchronized boolean isPaused() { return paused; } - public boolean isDirectDeliver() - { + public boolean isDirectDeliver() { return directDeliver; } /** * @return the internalQueue */ - public boolean isInternalQueue() - { + public boolean isInternalQueue() { return internalQueue; } /** * @param internalQueue the internalQueue to set */ - public void setInternalQueue(boolean internalQueue) - { + public void setInternalQueue(boolean internalQueue) { this.internalQueue = internalQueue; } @@ -1934,13 +1621,12 @@ public class QueueImpl implements Queue // ----------------------------------------------------------------------------- @Override - public boolean equals(final Object other) - { - if (this == other) - { + public boolean equals(final Object other) { + if (this == other) { return true; } - if (!(other instanceof QueueImpl)) return false; + if (!(other instanceof QueueImpl)) + return false; QueueImpl qother = (QueueImpl) other; @@ -1948,19 +1634,16 @@ public class QueueImpl implements Queue } @Override - public int hashCode() - { + public int hashCode() { return name.hashCode(); } @Override - public String toString() - { + public String toString() { return "QueueImpl[name=" + name.toString() + ", postOffice=" + this.postOffice + "]@" + Integer.toHexString(System.identityHashCode(this)); } - private synchronized void internalAddTail(final MessageReference ref) - { + private synchronized void internalAddTail(final MessageReference ref) { refAdded(ref); messageReferences.addTail(ref, ref.getMessage().getPriority()); } @@ -1972,26 +1655,22 @@ public class QueueImpl implements Queue * * @param ref */ - private void internalAddHead(final MessageReference ref) - { + private void internalAddHead(final MessageReference ref) { queueMemorySize.addAndGet(ref.getMessageMemoryEstimate()); refAdded(ref); messageReferences.addHead(ref, ref.getMessage().getPriority()); } - private synchronized void doInternalPoll() - { + private synchronized void doInternalPoll() { int added = 0; MessageReference ref; - while ((ref = intermediateMessageReferences.poll()) != null) - { + while ((ref = intermediateMessageReferences.poll()) != null) { internalAddTail(ref); messagesAdded++; - if (added++ > MAX_DELIVERIES_IN_LOOP) - { + if (added++ > MAX_DELIVERIES_IN_LOOP) { // if we just keep polling from the intermediate we could starve in case there's a sustained load deliverAsync(); return; @@ -2003,10 +1682,8 @@ public class QueueImpl implements Queue * This method will deliver as many messages as possible until all consumers are busy or there * are no more matching or available messages. */ - private void deliver() - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + private void deliver() { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug(this + " doing deliver. messageReferences=" + messageReferences.size()); } @@ -2023,10 +1700,8 @@ public class QueueImpl implements Queue long timeout = System.currentTimeMillis() + DELIVERY_TIMEOUT; - while (true) - { - if (handled == MAX_DELIVERIES_IN_LOOP) - { + while (true) { + if (handled == MAX_DELIVERIES_IN_LOOP) { // Schedule another one - we do this to prevent a single thread getting caught up in this loop for too // long @@ -2035,10 +1710,8 @@ public class QueueImpl implements Queue return; } - if (System.currentTimeMillis() > timeout) - { - if (isTrace) - { + if (System.currentTimeMillis() > timeout) { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("delivery has been running for too long. Scheduling another delivery task now"); } @@ -2047,35 +1720,29 @@ public class QueueImpl implements Queue return; } - MessageReference ref; Consumer handledconsumer = null; - synchronized (this) - { + synchronized (this) { // Need to do these checks inside the synchronized - if (paused || consumerList.isEmpty()) - { + if (paused || consumerList.isEmpty()) { return; } - if (messageReferences.size() == 0) - { + if (messageReferences.size() == 0) { break; } - if (endPos < 0 || consumersChanged) - { + if (endPos < 0 || consumersChanged) { consumersChanged = false; size = consumerList.size(); endPos = pos - 1; - if (endPos < 0) - { + if (endPos < 0) { endPos = size - 1; noDelivery = 0; } @@ -2086,29 +1753,22 @@ public class QueueImpl implements Queue Consumer consumer = holder.consumer; Consumer groupConsumer = null; - if (holder.iter == null) - { + if (holder.iter == null) { holder.iter = messageReferences.iterator(); } - if (holder.iter.hasNext()) - { + if (holder.iter.hasNext()) { ref = holder.iter.next(); } - else - { + else { ref = null; } - if (ref == null) - { + if (ref == null) { noDelivery++; } - else - { - if (checkExpired(ref)) - { - if (isTrace) - { + else { + if (checkExpired(ref)) { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Reference " + ref + " being expired"); } holder.iter.remove(); @@ -2120,9 +1780,7 @@ public class QueueImpl implements Queue continue; } - - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Queue " + this.getName() + " is delivering reference " + ref); } @@ -2130,20 +1788,17 @@ public class QueueImpl implements Queue SimpleString groupID = extractGroupID(ref); - if (groupID != null) - { + if (groupID != null) { groupConsumer = groups.get(groupID); - if (groupConsumer != null) - { + if (groupConsumer != null) { consumer = groupConsumer; } } HandleStatus status = handle(ref, consumer); - if (status == HandleStatus.HANDLED) - { + if (status == HandleStatus.HANDLED) { deliveriesInTransit.countUp(); @@ -2153,41 +1808,33 @@ public class QueueImpl implements Queue refRemoved(ref); - if (groupID != null && groupConsumer == null) - { + if (groupID != null && groupConsumer == null) { groups.put(groupID, consumer); } handled++; } - else if (status == HandleStatus.BUSY) - { + else if (status == HandleStatus.BUSY) { holder.iter.repeat(); noDelivery++; } - else if (status == HandleStatus.NO_MATCH) - { + else if (status == HandleStatus.NO_MATCH) { // nothing to be done on this case, the iterators will just jump next } } - if (pos == endPos) - { + if (pos == endPos) { // Round robin'd all - if (noDelivery == size) - { - if (handledconsumer != null) - { + if (noDelivery == size) { + if (handledconsumer != null) { // this shouldn't really happen, // however I'm keeping this as an assertion case future developers ever change the logic here on this class ActiveMQServerLogger.LOGGER.nonDeliveryHandled(); } - else - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + else { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug(this + "::All the consumers were busy, giving up now"); } break; @@ -2199,19 +1846,16 @@ public class QueueImpl implements Queue // Only move onto the next position if the consumer on the current position was used. // When using group we don't need to load balance to the next position - if (groupConsumer == null) - { + if (groupConsumer == null) { pos++; } - if (pos >= size) - { + if (pos >= size) { pos = 0; } } - if (handledconsumer != null) - { + if (handledconsumer != null) { proceedDeliver(handledconsumer, ref); } } @@ -2219,37 +1863,29 @@ public class QueueImpl implements Queue checkDepage(); } - private void checkDepage() - { - if (pageIterator != null && pageSubscription.isPaging() && !depagePending && needsDepage() && pageIterator.hasNext()) - { + private void checkDepage() { + if (pageIterator != null && pageSubscription.isPaging() && !depagePending && needsDepage() && pageIterator.hasNext()) { scheduleDepage(false); } } - /** * This is a common check we do before scheduling depaging.. or while depaging. * Before scheduling a depage runnable we verify if it fits / needs depaging. * We also check for while needsDepage While depaging. * This is just to avoid a copy & paste dependency + * * @return */ - private boolean needsDepage() - { + private boolean needsDepage() { return queueMemorySize.get() < pageSubscription.getPagingStore().getMaxSize(); } - - - private SimpleString extractGroupID(MessageReference ref) - { - if (internalQueue) - { + private SimpleString extractGroupID(MessageReference ref) { + if (internalQueue) { return null; } - else - { + else { // But we don't use the groupID on internal queues (clustered queues) otherwise the group map would leak forever return ref.getMessage().getSimpleStringProperty(Message.HDR_GROUP_ID); } @@ -2258,11 +1894,9 @@ public class QueueImpl implements Queue /** * @param ref */ - protected void refRemoved(MessageReference ref) - { + protected void refRemoved(MessageReference ref) { queueMemorySize.addAndGet(-ref.getMessageMemoryEstimate()); - if (ref.isPaged()) - { + if (ref.isPaged()) { pagedReferences.decrementAndGet(); } } @@ -2270,20 +1904,15 @@ public class QueueImpl implements Queue /** * @param ref */ - protected void refAdded(final MessageReference ref) - { - if (ref.isPaged()) - { + protected void refAdded(final MessageReference ref) { + if (ref.isPaged()) { pagedReferences.incrementAndGet(); } } - private void scheduleDepage(final boolean scheduleExpiry) - { - if (!depagePending) - { - if (isTrace) - { + private void scheduleDepage(final boolean scheduleExpiry) { + if (!depagePending) { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Scheduling depage for queue " + this.getName()); } depagePending = true; @@ -2291,84 +1920,67 @@ public class QueueImpl implements Queue } } - private void depage(final boolean scheduleExpiry) - { + private void depage(final boolean scheduleExpiry) { depagePending = false; - synchronized (this) - { - if (paused || pageIterator == null) - { + synchronized (this) { + if (paused || pageIterator == null) { return; } } long maxSize = pageSubscription.getPagingStore().getPageSizeBytes(); - long timeout = System.currentTimeMillis() + DELIVERY_TIMEOUT; - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("QueueMemorySize before depage on queue=" + this.getName() + " is " + queueMemorySize.get()); } this.directDeliver = false; int depaged = 0; - while (timeout > System.currentTimeMillis() && needsDepage() && pageIterator.hasNext()) - { + while (timeout > System.currentTimeMillis() && needsDepage() && pageIterator.hasNext()) { depaged++; PagedReference reference = pageIterator.next(); - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Depaging reference " + reference + " on queue " + this.getName()); } addTail(reference, false); pageIterator.remove(); } - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { - if (depaged == 0 && queueMemorySize.get() >= maxSize) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { + if (depaged == 0 && queueMemorySize.get() >= maxSize) { ActiveMQServerLogger.LOGGER.debug("Couldn't depage any message as the maxSize on the queue was achieved. " + "There are too many pending messages to be acked in reference to the page configuration"); } - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Queue Memory Size after depage on queue=" + this.getName() + - " is " + - queueMemorySize.get() + - " with maxSize = " + - maxSize + - ". Depaged " + - depaged + - " messages, pendingDelivery=" + messageReferences.size() + ", intermediateMessageReferences= " + intermediateMessageReferences.size() + - ", queueDelivering=" + deliveringCount.get()); + " is " + + queueMemorySize.get() + + " with maxSize = " + + maxSize + + ". Depaged " + + depaged + + " messages, pendingDelivery=" + messageReferences.size() + ", intermediateMessageReferences= " + intermediateMessageReferences.size() + + ", queueDelivering=" + deliveringCount.get()); } } deliverAsync(); - if (depaged > 0 && scheduleExpiry) - { + if (depaged > 0 && scheduleExpiry) { // This will just call an executor expireReferences(); } } - private void internalAddRedistributor(final Executor executor) - { + private void internalAddRedistributor(final Executor executor) { // create the redistributor only once if there are no local consumers - if (consumerSet.isEmpty() && redistributor == null) - { - redistributor = new Redistributor(this, - storageManager, - postOffice, - executor, - QueueImpl.REDISTRIBUTOR_BATCH_SIZE); + if (consumerSet.isEmpty() && redistributor == null) { + redistributor = new Redistributor(this, storageManager, postOffice, executor, QueueImpl.REDISTRIBUTOR_BATCH_SIZE); consumerList.add(new ConsumerHolder(redistributor)); @@ -2380,22 +1992,20 @@ public class QueueImpl implements Queue } } - public boolean checkRedelivery(final MessageReference reference, final long timeBase, final boolean ignoreRedeliveryDelay) throws Exception - { + public boolean checkRedelivery(final MessageReference reference, + final long timeBase, + final boolean ignoreRedeliveryDelay) throws Exception { ServerMessage message = reference.getMessage(); - if (internalQueue) - { - if (isTrace) - { + if (internalQueue) { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Queue " + this.getName() + " is an internal queue, no checkRedelivery"); } // no DLQ check on internal queues return true; } - if (!internalQueue && message.isDurable() && durable && !reference.isPaged()) - { + if (!internalQueue && message.isDurable() && durable && !reference.isPaged()) { storageManager.updateDeliveryCount(reference); } @@ -2406,32 +2016,26 @@ public class QueueImpl implements Queue int deliveryCount = reference.getDeliveryCount(); // First check DLA - if (maxDeliveries > 0 && deliveryCount >= maxDeliveries) - { - if (isTrace) - { + if (maxDeliveries > 0 && deliveryCount >= maxDeliveries) { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Sending reference " + reference + " to DLA = " + addressSettings.getDeadLetterAddress() + " since ref.getDeliveryCount=" + reference.getDeliveryCount() + "and maxDeliveries=" + maxDeliveries + " from queue=" + this.getName()); } sendToDeadLetterAddress(reference, addressSettings.getDeadLetterAddress()); return false; } - else - { + else { // Second check Redelivery Delay - if (!ignoreRedeliveryDelay && redeliveryDelay > 0) - { + if (!ignoreRedeliveryDelay && redeliveryDelay > 0) { redeliveryDelay = calculateRedeliveryDelay(addressSettings, deliveryCount); - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Setting redeliveryDelay=" + redeliveryDelay + " on reference=" + reference); } reference.setScheduledDeliveryTime(timeBase + redeliveryDelay); - if (!reference.isPaged() && message.isDurable() && durable) - { + if (!reference.isPaged() && message.isDurable() && durable) { storageManager.updateScheduledDeliveryTime(reference); } } @@ -2445,8 +2049,7 @@ public class QueueImpl implements Queue /** * Used on testing only * */ - public int getNumberOfReferences() - { + public int getNumberOfReferences() { return messageReferences.size(); } @@ -2454,8 +2057,7 @@ public class QueueImpl implements Queue final Transaction tx, final MessageReference ref, final boolean expiry, - final boolean rejectDuplicate) throws Exception - { + final boolean rejectDuplicate) throws Exception { ServerMessage copyMessage = makeCopy(ref, expiry); copyMessage.setAddress(toAddress); @@ -2468,8 +2070,7 @@ public class QueueImpl implements Queue @SuppressWarnings({"ArrayToString", "ArrayToStringConcatentation"}) private void moveBetweenSnFQueues(final SimpleString queueSuffix, final Transaction tx, - final MessageReference ref) throws Exception - { + final MessageReference ref) throws Exception { ServerMessage copyMessage = makeCopy(ref, false, false); byte[] oldRouteToIDs = null; @@ -2477,10 +2078,8 @@ public class QueueImpl implements Queue Binding targetBinding; // remove the old route - for (SimpleString propName : copyMessage.getPropertyNames()) - { - if (propName.startsWith(MessageImpl.HDR_ROUTE_TO_IDS)) - { + for (SimpleString propName : copyMessage.getPropertyNames()) { + if (propName.startsWith(MessageImpl.HDR_ROUTE_TO_IDS)) { oldRouteToIDs = (byte[]) copyMessage.removeProperty(propName); final String hashcodeToString = oldRouteToIDs.toString(); // don't use Arrays.toString(..) here ActiveMQServerLogger.LOGGER.debug("Removed property from message: " + propName + " = " + hashcodeToString + " (" + ByteBuffer.wrap(oldRouteToIDs).getLong() + ")"); @@ -2497,8 +2096,7 @@ public class QueueImpl implements Queue /* this algorithm will look at the old route and find the new remote queue bindings where the messages should go * and route them there directly */ - while (oldBuffer.hasRemaining()) - { + while (oldBuffer.hasRemaining()) { long oldQueueID = oldBuffer.getLong(); // look at all the bindings @@ -2506,12 +2104,10 @@ public class QueueImpl implements Queue targetBinding = result.getB(); targetNodeID = result.getA(); - if (targetBinding == null) - { + if (targetBinding == null) { ActiveMQServerLogger.LOGGER.unableToFindTargetQueue(targetNodeID); } - else - { + else { ActiveMQServerLogger.LOGGER.debug("Routing on binding: " + targetBinding); targetBinding.route(copyMessage, routingContext); } @@ -2524,39 +2120,33 @@ public class QueueImpl implements Queue acknowledge(tx, ref); - storageManager.afterCompleteOperations(new IOCallback() - { + storageManager.afterCompleteOperations(new IOCallback() { - public void onError(final int errorCode, final String errorMessage) - { + public void onError(final int errorCode, final String errorMessage) { ActiveMQServerLogger.LOGGER.ioErrorRedistributing(errorCode, errorMessage); } - public void done() - { + public void done() { deliverAsync(); } }); } - - private Pair locateTargetBinding(SimpleString queueSuffix, ServerMessage copyMessage, long oldQueueID) - { + private Pair locateTargetBinding(SimpleString queueSuffix, + ServerMessage copyMessage, + long oldQueueID) { String targetNodeID = null; Binding targetBinding = null; - for (Map.Entry entry : postOffice.getAllBindings().entrySet()) - { + for (Map.Entry entry : postOffice.getAllBindings().entrySet()) { Binding binding = entry.getValue(); // we only care about the remote queue bindings - if (binding instanceof RemoteQueueBinding) - { + if (binding instanceof RemoteQueueBinding) { RemoteQueueBinding remoteQueueBinding = (RemoteQueueBinding) binding; // does this remote queue binding point to the same queue as the message? - if (oldQueueID == remoteQueueBinding.getRemoteQueueID()) - { + if (oldQueueID == remoteQueueBinding.getRemoteQueueID()) { // get the name of this queue so we can find the corresponding remote queue binding pointing to the scale down target node SimpleString oldQueueName = remoteQueueBinding.getRoutingName(); @@ -2566,27 +2156,22 @@ public class QueueImpl implements Queue ActiveMQServerLogger.LOGGER.debug("Message formerly destined for " + oldQueueName + " with ID: " + oldQueueID + " on address " + copyMessage.getAddress() + " on node " + targetNodeID); // now that we have the name of the queue we need to look through all the bindings again to find the new remote queue binding - for (Map.Entry entry2 : postOffice.getAllBindings().entrySet()) - { + for (Map.Entry entry2 : postOffice.getAllBindings().entrySet()) { binding = entry2.getValue(); // again, we only care about the remote queue bindings - if (binding instanceof RemoteQueueBinding) - { + if (binding instanceof RemoteQueueBinding) { remoteQueueBinding = (RemoteQueueBinding) binding; temp = remoteQueueBinding.getQueue().getName().toString(); targetNodeID = temp.substring(temp.lastIndexOf(".") + 1); - if (oldQueueName.equals(remoteQueueBinding.getRoutingName()) && targetNodeID.equals(queueSuffix.toString())) - { + if (oldQueueName.equals(remoteQueueBinding.getRoutingName()) && targetNodeID.equals(queueSuffix.toString())) { targetBinding = remoteQueueBinding; - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Message now destined for " + remoteQueueBinding.getRoutingName() + " with ID: " + remoteQueueBinding.getRemoteQueueID() + " on address " + copyMessage.getAddress() + " on node " + targetNodeID); } break; } - else - { + else { ActiveMQServerLogger.LOGGER.debug("Failed to match: " + remoteQueueBinding); } } @@ -2597,14 +2182,13 @@ public class QueueImpl implements Queue return new Pair<>(targetNodeID, targetBinding); } - - private ServerMessage makeCopy(final MessageReference ref, final boolean expiry) throws Exception - { + private ServerMessage makeCopy(final MessageReference ref, final boolean expiry) throws Exception { return makeCopy(ref, expiry, true); } - private ServerMessage makeCopy(final MessageReference ref, final boolean expiry, final boolean copyOriginalHeaders) throws Exception - { + private ServerMessage makeCopy(final MessageReference ref, + final boolean expiry, + final boolean copyOriginalHeaders) throws Exception { ServerMessage message = ref.getMessage(); /* We copy the message and send that to the dla/expiry queue - this is @@ -2622,64 +2206,55 @@ public class QueueImpl implements Queue return copy; } - private void expire(final Transaction tx, final MessageReference ref) throws Exception - { + private void expire(final Transaction tx, final MessageReference ref) throws Exception { SimpleString expiryAddress = addressSettingsRepository.getMatch(address.toString()).getExpiryAddress(); - if (expiryAddress != null) - { + if (expiryAddress != null) { Bindings bindingList = postOffice.getBindingsForAddress(expiryAddress); - if (bindingList.getBindings().isEmpty()) - { + if (bindingList.getBindings().isEmpty()) { ActiveMQServerLogger.LOGGER.errorExpiringReferencesNoBindings(expiryAddress); } - else - { + else { move(expiryAddress, tx, ref, true, true); } } - else - { + else { ActiveMQServerLogger.LOGGER.errorExpiringReferencesNoQueue(name); acknowledge(tx, ref); } } - - public void sendToDeadLetterAddress(final MessageReference ref) throws Exception - { + public void sendToDeadLetterAddress(final MessageReference ref) throws Exception { sendToDeadLetterAddress(ref, addressSettingsRepository.getMatch(address.toString()).getDeadLetterAddress()); } - private void sendToDeadLetterAddress(final MessageReference ref, final SimpleString deadLetterAddress) throws Exception - { - if (deadLetterAddress != null) - { + private void sendToDeadLetterAddress(final MessageReference ref, + final SimpleString deadLetterAddress) throws Exception { + if (deadLetterAddress != null) { Bindings bindingList = postOffice.getBindingsForAddress(deadLetterAddress); - if (bindingList.getBindings().isEmpty()) - { + if (bindingList.getBindings().isEmpty()) { ActiveMQServerLogger.LOGGER.messageExceededMaxDelivery(ref, deadLetterAddress); acknowledge(ref); } - else - { + else { ActiveMQServerLogger.LOGGER.messageExceededMaxDeliverySendtoDLA(ref, deadLetterAddress, name); move(deadLetterAddress, ref, false, false); } } - else - { + else { ActiveMQServerLogger.LOGGER.messageExceededMaxDeliveryNoDLA(name); acknowledge(ref); } } - private void move(final SimpleString address, final MessageReference ref, final boolean expiry, final boolean rejectDuplicate) throws Exception - { + private void move(final SimpleString address, + final MessageReference ref, + final boolean expiry, + final boolean rejectDuplicate) throws Exception { Transaction tx = new TransactionImpl(storageManager); ServerMessage copyMessage = makeCopy(ref, expiry); @@ -2696,17 +2271,13 @@ public class QueueImpl implements Queue /* * This method delivers the reference on the callers thread - this can give us better latency in the case there is nothing in the queue */ - private boolean deliverDirect(final MessageReference ref) - { - synchronized (this) - { - if (paused || consumerList.isEmpty()) - { + private boolean deliverDirect(final MessageReference ref) { + synchronized (this) { + if (paused || consumerList.isEmpty()) { return false; } - if (checkExpired(ref)) - { + if (checkExpired(ref)) { return true; } @@ -2714,8 +2285,7 @@ public class QueueImpl implements Queue int size = consumerList.size(); - while (true) - { + while (true) { ConsumerHolder holder = consumerList.get(pos); Consumer consumer = holder.consumer; @@ -2726,33 +2296,27 @@ public class QueueImpl implements Queue SimpleString groupID = extractGroupID(ref); - if (groupID != null) - { + if (groupID != null) { groupConsumer = groups.get(groupID); - if (groupConsumer != null) - { + if (groupConsumer != null) { consumer = groupConsumer; } } // Only move onto the next position if the consumer on the current position was used. - if (groupConsumer == null) - { + if (groupConsumer == null) { pos++; } - if (pos == size) - { + if (pos == size) { pos = 0; } HandleStatus status = handle(ref, consumer); - if (status == HandleStatus.HANDLED) - { - if (groupID != null && groupConsumer == null) - { + if (status == HandleStatus.HANDLED) { + if (groupID != null && groupConsumer == null) { groups.put(groupID, consumer); } @@ -2763,8 +2327,7 @@ public class QueueImpl implements Queue return true; } - if (pos == startPos) - { + if (pos == startPos) { // Tried them all break; } @@ -2773,25 +2336,19 @@ public class QueueImpl implements Queue } } - private void proceedDeliver(Consumer consumer, MessageReference reference) - { - try - { + private void proceedDeliver(Consumer consumer, MessageReference reference) { + try { consumer.proceedDeliver(reference); } - catch (Throwable t) - { + catch (Throwable t) { ActiveMQServerLogger.LOGGER.removingBadConsumer(t, consumer, reference); - synchronized (this) - { + synchronized (this) { // If the consumer throws an exception we remove the consumer - try - { + try { removeConsumer(consumer); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorRemovingConsumer(e); } @@ -2799,89 +2356,72 @@ public class QueueImpl implements Queue addHead(reference); } } - finally - { + finally { deliveriesInTransit.countDown(); } } - private boolean checkExpired(final MessageReference reference) - { - if (reference.getMessage().isExpired()) - { - if (isTrace) - { + private boolean checkExpired(final MessageReference reference) { + if (reference.getMessage().isExpired()) { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Reference " + reference + " is expired"); } reference.handled(); - try - { + try { expire(reference); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorExpiringRef(e); } return true; } - else - { + else { return false; } } - private synchronized HandleStatus handle(final MessageReference reference, final Consumer consumer) - { + private synchronized HandleStatus handle(final MessageReference reference, final Consumer consumer) { HandleStatus status; - try - { + try { status = consumer.handle(reference); } - catch (Throwable t) - { + catch (Throwable t) { ActiveMQServerLogger.LOGGER.removingBadConsumer(t, consumer, reference); // If the consumer throws an exception we remove the consumer - try - { + try { removeConsumer(consumer); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorRemovingConsumer(e); } return HandleStatus.BUSY; } - if (status == null) - { + if (status == null) { throw new IllegalStateException("ClientConsumer.handle() should never return null"); } return status; } - private List cloneConsumersList() - { + private List cloneConsumersList() { List consumerListClone; - synchronized (this) - { + synchronized (this) { consumerListClone = new ArrayList(consumerList); } return consumerListClone; } - public void postAcknowledge(final MessageReference ref) - { + public void postAcknowledge(final MessageReference ref) { QueueImpl queue = (QueueImpl) ref.getQueue(); queue.decDelivering(); - if (ref.isPaged()) - { + if (ref.isPaged()) { // nothing to be done return; } @@ -2890,21 +2430,17 @@ public class QueueImpl implements Queue boolean durableRef = message.isDurable() && queue.durable; - try - { + try { message.decrementRefCount(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorDecrementingRefCount(e); } - if (durableRef) - { + if (durableRef) { int count = message.decrementDurableRefCount(); - if (count == 0) - { + if (count == 0) { // Note - we MUST store the delete after the preceding ack has been committed to storage, we cannot combine // the last ack and delete into a single delete. // This is because otherwise we could have a situation where the same message is being acked concurrently @@ -2919,25 +2455,21 @@ public class QueueImpl implements Queue // Also note that this delete shouldn't sync to disk, or else we would build up the executor's queue // as we can't delete each messaging with sync=true while adding messages transactionally. // There is a startup check to remove non referenced messages case these deletes fail - try - { + try { storageManager.deleteMessage(message.getMessageID()); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorRemovingMessage(e, message.getMessageID()); } } } } - void postRollback(final LinkedList refs) - { + void postRollback(final LinkedList refs) { addHead(refs); } - private long calculateRedeliveryDelay(final AddressSettings addressSettings, final int deliveryCount) - { + private long calculateRedeliveryDelay(final AddressSettings addressSettings, final int deliveryCount) { long redeliveryDelay = addressSettings.getRedeliveryDelay(); long maxRedeliveryDelay = addressSettings.getMaxRedeliveryDelay(); double redeliveryMultiplier = addressSettings.getRedeliveryMultiplier(); @@ -2945,29 +2477,24 @@ public class QueueImpl implements Queue int tmpDeliveryCount = deliveryCount > 0 ? deliveryCount - 1 : 0; long delay = (long) (redeliveryDelay * (Math.pow(redeliveryMultiplier, tmpDeliveryCount))); - if (delay > maxRedeliveryDelay) - { + if (delay > maxRedeliveryDelay) { delay = maxRedeliveryDelay; } return delay; } - public synchronized void resetMessagesAdded() - { + public synchronized void resetMessagesAdded() { messagesAdded = 0; } - public synchronized void resetMessagesAcknowledged() - { + public synchronized void resetMessagesAcknowledged() { messagesAcknowledged = 0; } - public float getRate() - { + public float getRate() { float timeSlice = ((System.currentTimeMillis() - queueRateCheckTime.getAndSet(System.currentTimeMillis())) / 1000.0f); - if (timeSlice == 0) - { + if (timeSlice == 0) { messagesAddedSnapshot.getAndSet(messagesAdded); return 0.0f; } @@ -2977,10 +2504,9 @@ public class QueueImpl implements Queue // Inner classes // -------------------------------------------------------------------------- - private static class ConsumerHolder - { - ConsumerHolder(final Consumer consumer) - { + private static class ConsumerHolder { + + ConsumerHolder(final Consumer consumer) { this.consumer = consumer; } @@ -2990,19 +2516,16 @@ public class QueueImpl implements Queue } - private class DelayedAddRedistributor implements Runnable - { + private class DelayedAddRedistributor implements Runnable { + private final Executor executor1; - DelayedAddRedistributor(final Executor executor) - { + DelayedAddRedistributor(final Executor executor) { this.executor1 = executor; } - public void run() - { - synchronized (QueueImpl.this) - { + public void run() { + synchronized (QueueImpl.this) { internalAddRedistributor(executor1); futures.remove(this); @@ -3015,50 +2538,41 @@ public class QueueImpl implements Queue * previous versions of this class were using a synchronized object. The current version is using the deliverRunner * instance, and to avoid confusion on the implementation I'm requesting to keep this single instanced per QueueImpl. */ - private final class DeliverRunner implements Runnable - { - public void run() - { - try - { + private final class DeliverRunner implements Runnable { + + public void run() { + try { // during the transition between paging and nonpaging, we could have this using a different executor // and at this short period we could have more than one delivery thread running in async mode // this will avoid that possibility // We will be using the deliverRunner instance as the guard object to avoid multiple threads executing // an asynchronous delivery - synchronized (QueueImpl.this.deliverRunner) - { + synchronized (QueueImpl.this.deliverRunner) { deliver(); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorDelivering(e); } - finally - { + finally { scheduledRunners.decrementAndGet(); } } } - private final class DepageRunner implements Runnable - { + private final class DepageRunner implements Runnable { + final boolean scheduleExpiry; - public DepageRunner(boolean scheduleExpiry) - { + public DepageRunner(boolean scheduleExpiry) { this.scheduleExpiry = scheduleExpiry; } - public void run() - { - try - { + public void run() { + try { depage(scheduleExpiry); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorDelivering(e); } } @@ -3067,57 +2581,46 @@ public class QueueImpl implements Queue /** * This will determine the actions that could be done while iterate the queue through iterQueue */ - abstract class QueueIterateAction - { + abstract class QueueIterateAction { + public abstract void actMessage(Transaction tx, MessageReference ref) throws Exception; } /* For external use we need to use a synchronized version since the list is not thread safe */ - private class SynchronizedIterator implements LinkedListIterator - { + private class SynchronizedIterator implements LinkedListIterator { + private final LinkedListIterator iter; - SynchronizedIterator(LinkedListIterator iter) - { + SynchronizedIterator(LinkedListIterator iter) { this.iter = iter; } - public void close() - { - synchronized (QueueImpl.this) - { + public void close() { + synchronized (QueueImpl.this) { iter.close(); } } - public void repeat() - { - synchronized (QueueImpl.this) - { + public void repeat() { + synchronized (QueueImpl.this) { iter.repeat(); } } - public boolean hasNext() - { - synchronized (QueueImpl.this) - { + public boolean hasNext() { + synchronized (QueueImpl.this) { return iter.hasNext(); } } - public MessageReference next() - { - synchronized (QueueImpl.this) - { + public MessageReference next() { + synchronized (QueueImpl.this) { return iter.next(); } } - public void remove() - { - synchronized (QueueImpl.this) - { + public void remove() { + synchronized (QueueImpl.this) { iter.remove(); } } @@ -3125,34 +2628,28 @@ public class QueueImpl implements Queue //Readonly (no remove) iterator over the messages in the queue, in order of //paging store, intermediateMessageReferences and MessageReferences - private class TotalQueueIterator implements LinkedListIterator - { + private class TotalQueueIterator implements LinkedListIterator { + LinkedListIterator pageIter = null; LinkedListIterator messagesIterator = null; Iterator lastIterator = null; - public TotalQueueIterator() - { - if (pageSubscription != null) - { + public TotalQueueIterator() { + if (pageSubscription != null) { pageIter = pageSubscription.iterator(); } messagesIterator = new SynchronizedIterator(messageReferences.iterator()); } @Override - public boolean hasNext() - { - if (messagesIterator != null && messagesIterator.hasNext()) - { + public boolean hasNext() { + if (messagesIterator != null && messagesIterator.hasNext()) { lastIterator = messagesIterator; return true; } - if (pageIter != null) - { - if (pageIter.hasNext()) - { + if (pageIter != null) { + if (pageIter.hasNext()) { lastIterator = pageIter; return true; } @@ -3162,17 +2659,13 @@ public class QueueImpl implements Queue } @Override - public MessageReference next() - { - if (messagesIterator != null && messagesIterator.hasNext()) - { + public MessageReference next() { + if (messagesIterator != null && messagesIterator.hasNext()) { MessageReference msg = messagesIterator.next(); return msg; } - if (pageIter != null) - { - if (pageIter.hasNext()) - { + if (pageIter != null) { + if (pageIter.hasNext()) { lastIterator = pageIter; return pageIter.next(); } @@ -3182,179 +2675,140 @@ public class QueueImpl implements Queue } @Override - public void remove() - { - if (lastIterator != null) - { + public void remove() { + if (lastIterator != null) { lastIterator.remove(); } } @Override - public void repeat() - { + public void repeat() { } @Override - public void close() - { - if (pageIter != null) - { + public void close() { + if (pageIter != null) { pageIter.close(); } - if (messagesIterator != null) - { + if (messagesIterator != null) { messagesIterator.close(); } } } - private int incDelivering() - { + private int incDelivering() { return deliveringCount.incrementAndGet(); } - public void decDelivering() - { + public void decDelivering() { deliveringCount.decrementAndGet(); } - private void configureExpiry(final AddressSettings settings) - { + private void configureExpiry(final AddressSettings settings) { this.expiryAddress = settings == null ? null : settings.getExpiryAddress(); } - private void configureSlowConsumerReaper(final AddressSettings settings) - { - if (settings == null || settings.getSlowConsumerThreshold() == AddressSettings.DEFAULT_SLOW_CONSUMER_THRESHOLD) - { - if (slowConsumerReaperFuture != null) - { + private void configureSlowConsumerReaper(final AddressSettings settings) { + if (settings == null || settings.getSlowConsumerThreshold() == AddressSettings.DEFAULT_SLOW_CONSUMER_THRESHOLD) { + if (slowConsumerReaperFuture != null) { slowConsumerReaperFuture.cancel(false); slowConsumerReaperFuture = null; slowConsumerReaperRunnable = null; - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Cancelled slow-consumer-reaper thread for queue \"" + getName() + "\""); } } } - else - { - if (slowConsumerReaperRunnable == null) - { + else { + if (slowConsumerReaperRunnable == null) { scheduleSlowConsumerReaper(settings); } else if (slowConsumerReaperRunnable.checkPeriod != settings.getSlowConsumerCheckPeriod() || slowConsumerReaperRunnable.threshold != settings.getSlowConsumerThreshold() || - !slowConsumerReaperRunnable.policy.equals(settings.getSlowConsumerPolicy())) - { + !slowConsumerReaperRunnable.policy.equals(settings.getSlowConsumerPolicy())) { slowConsumerReaperFuture.cancel(false); scheduleSlowConsumerReaper(settings); } } } - void scheduleSlowConsumerReaper(AddressSettings settings) - { - slowConsumerReaperRunnable = new SlowConsumerReaperRunnable(settings.getSlowConsumerCheckPeriod(), - settings.getSlowConsumerThreshold(), - settings.getSlowConsumerPolicy()); + void scheduleSlowConsumerReaper(AddressSettings settings) { + slowConsumerReaperRunnable = new SlowConsumerReaperRunnable(settings.getSlowConsumerCheckPeriod(), settings.getSlowConsumerThreshold(), settings.getSlowConsumerPolicy()); - slowConsumerReaperFuture = scheduledExecutor.scheduleWithFixedDelay(slowConsumerReaperRunnable, - settings.getSlowConsumerCheckPeriod(), - settings.getSlowConsumerCheckPeriod(), - TimeUnit.SECONDS); + slowConsumerReaperFuture = scheduledExecutor.scheduleWithFixedDelay(slowConsumerReaperRunnable, settings.getSlowConsumerCheckPeriod(), settings.getSlowConsumerCheckPeriod(), TimeUnit.SECONDS); - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Scheduled slow-consumer-reaper thread for queue \"" + getName() + - "\"; slow-consumer-check-period=" + settings.getSlowConsumerCheckPeriod() + - ", slow-consumer-threshold=" + settings.getSlowConsumerThreshold() + - ", slow-consumer-policy=" + settings.getSlowConsumerPolicy()); + "\"; slow-consumer-check-period=" + settings.getSlowConsumerCheckPeriod() + + ", slow-consumer-threshold=" + settings.getSlowConsumerThreshold() + + ", slow-consumer-policy=" + settings.getSlowConsumerPolicy()); } } - private class AddressSettingsRepositoryListener implements HierarchicalRepositoryChangeListener - { + private class AddressSettingsRepositoryListener implements HierarchicalRepositoryChangeListener { + @Override - public void onChange() - { + public void onChange() { AddressSettings settings = addressSettingsRepository.getMatch(address.toString()); configureExpiry(settings); configureSlowConsumerReaper(settings); } } - private final class SlowConsumerReaperRunnable implements Runnable - { + private final class SlowConsumerReaperRunnable implements Runnable { + private SlowConsumerPolicy policy; private float threshold; private long checkPeriod; - public SlowConsumerReaperRunnable(long checkPeriod, float threshold, SlowConsumerPolicy policy) - { + public SlowConsumerReaperRunnable(long checkPeriod, float threshold, SlowConsumerPolicy policy) { this.checkPeriod = checkPeriod; this.policy = policy; this.threshold = threshold; } @Override - public void run() - { + public void run() { float queueRate = getRate(); - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug(getAddress() + ":" + getName() + " has " + getConsumerCount() + " consumer(s) and is receiving messages at a rate of " + queueRate + " msgs/second."); } - for (Consumer consumer : getConsumers()) - { - if (consumer instanceof ServerConsumerImpl) - { + for (Consumer consumer : getConsumers()) { + if (consumer instanceof ServerConsumerImpl) { ServerConsumerImpl serverConsumer = (ServerConsumerImpl) consumer; float consumerRate = serverConsumer.getRate(); - if (queueRate < threshold) - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (queueRate < threshold) { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Insufficient messages received on queue \"" + getName() + "\" to satisfy slow-consumer-threshold. Skipping inspection of consumer."); } } - else if (consumerRate < threshold) - { + else if (consumerRate < threshold) { RemotingConnection connection = null; RemotingService remotingService = ((PostOfficeImpl) postOffice).getServer().getRemotingService(); - for (RemotingConnection potentialConnection : remotingService.getConnections()) - { - if (potentialConnection.getID().toString().equals(serverConsumer.getConnectionID())) - { + for (RemotingConnection potentialConnection : remotingService.getConnections()) { + if (potentialConnection.getID().toString().equals(serverConsumer.getConnectionID())) { connection = potentialConnection; } } - if (connection != null) - { + if (connection != null) { ActiveMQServerLogger.LOGGER.slowConsumerDetected(serverConsumer.getSessionID(), serverConsumer.getID(), getName().toString(), connection.getRemoteAddress(), threshold, consumerRate); - if (policy.equals(SlowConsumerPolicy.KILL)) - { + if (policy.equals(SlowConsumerPolicy.KILL)) { remotingService.removeConnection(connection.getID()); connection.fail(ActiveMQMessageBundle.BUNDLE.connectionsClosedByManagement(connection.getRemoteAddress())); } - else if (policy.equals(SlowConsumerPolicy.NOTIFY)) - { + else if (policy.equals(SlowConsumerPolicy.NOTIFY)) { TypedProperties props = new TypedProperties(); props.putIntProperty(ManagementHelper.HDR_CONSUMER_COUNT, getConsumerCount()); props.putSimpleStringProperty(ManagementHelper.HDR_ADDRESS, address); - if (connection != null) - { + if (connection != null) { props.putSimpleStringProperty(ManagementHelper.HDR_REMOTE_ADDRESS, SimpleString.toSimpleString(connection.getRemoteAddress())); - if (connection.getID() != null) - { + if (connection.getID() != null) { props.putSimpleStringProperty(ManagementHelper.HDR_CONNECTION_NAME, SimpleString.toSimpleString(connection.getID().toString())); } } @@ -3366,12 +2820,10 @@ public class QueueImpl implements Queue Notification notification = new Notification(null, CoreNotificationType.CONSUMER_SLOW, props); ManagementService managementService = ((PostOfficeImpl) postOffice).getServer().getManagementService(); - try - { + try { managementService.sendNotification(notification); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.failedToSendSlowConsumerNotification(notification, e); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/RefsOperation.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/RefsOperation.java index b98015c931..e11af87809 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/RefsOperation.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/RefsOperation.java @@ -31,8 +31,8 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; -public class RefsOperation extends TransactionOperationAbstract -{ +public class RefsOperation extends TransactionOperationAbstract { + private final StorageManager storageManager; private Queue queue; List refsToAck = new ArrayList(); @@ -45,25 +45,20 @@ public class RefsOperation extends TransactionOperationAbstract */ protected boolean ignoreRedeliveryCheck = false; - public RefsOperation(Queue queue, StorageManager storageManager) - { + public RefsOperation(Queue queue, StorageManager storageManager) { this.queue = queue; this.storageManager = storageManager; } // once turned on, we shouldn't turn it off, that's why no parameters - public void setIgnoreRedeliveryCheck() - { + public void setIgnoreRedeliveryCheck() { ignoreRedeliveryCheck = true; } - synchronized void addAck(final MessageReference ref) - { + synchronized void addAck(final MessageReference ref) { refsToAck.add(ref); - if (ref.isPaged()) - { - if (pagedMessagesToPostACK == null) - { + if (ref.isPaged()) { + if (pagedMessagesToPostACK == null) { pagedMessagesToPostACK = new ArrayList(); } pagedMessagesToPostACK.add(ref.getMessage()); @@ -71,8 +66,7 @@ public class RefsOperation extends TransactionOperationAbstract } @Override - public void afterRollback(final Transaction tx) - { + public void afterRollback(final Transaction tx) { Map> queueMap = new HashMap>(); long timeBase = System.currentTimeMillis(); @@ -81,27 +75,21 @@ public class RefsOperation extends TransactionOperationAbstract // previous state persisted. List ackedRefs = new ArrayList<>(); - for (MessageReference ref : refsToAck) - { + for (MessageReference ref : refsToAck) { ref.setConsumerId(null); - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("rolling back " + ref); } - try - { - if (ref.isAlreadyAcked()) - { + try { + if (ref.isAlreadyAcked()) { ackedRefs.add(ref); } // if ignore redelivery check, we just perform redelivery straight - if (ref.getQueue().checkRedelivery(ref, timeBase, ignoreRedeliveryCheck)) - { + if (ref.getQueue().checkRedelivery(ref, timeBase, ignoreRedeliveryCheck)) { LinkedList toCancel = queueMap.get(ref.getQueue()); - if (toCancel == null) - { + if (toCancel == null) { toCancel = new LinkedList(); queueMap.put((QueueImpl) ref.getQueue(), toCancel); @@ -110,40 +98,32 @@ public class RefsOperation extends TransactionOperationAbstract toCancel.addFirst(ref); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorCheckingDLQ(e); } } - for (Map.Entry> entry : queueMap.entrySet()) - { + for (Map.Entry> entry : queueMap.entrySet()) { LinkedList refs = entry.getValue(); QueueImpl queue = entry.getKey(); - synchronized (queue) - { + synchronized (queue) { queue.postRollback(refs); } } - if (!ackedRefs.isEmpty()) - { + if (!ackedRefs.isEmpty()) { //since pre acked refs have no previous state we need to actually create this by storing the message and the //message references - try - { + try { Transaction ackedTX = new TransactionImpl(storageManager); - for (MessageReference ref : ackedRefs) - { + for (MessageReference ref : ackedRefs) { ServerMessage message = ref.getMessage(); - if (message.isDurable()) - { + if (message.isDurable()) { int durableRefCount = message.incrementDurableRefCount(); - if (durableRefCount == 1) - { + if (durableRefCount == 1) { storageManager.storeMessageTransactional(ackedTX.getID(), message); } Queue queue = ref.getQueue(); @@ -157,34 +137,26 @@ public class RefsOperation extends TransactionOperationAbstract } ackedTX.commit(true); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } } @Override - public void afterCommit(final Transaction tx) - { - for (MessageReference ref : refsToAck) - { - synchronized (ref.getQueue()) - { + public void afterCommit(final Transaction tx) { + for (MessageReference ref : refsToAck) { + synchronized (ref.getQueue()) { queue.postAcknowledge(ref); } } - if (pagedMessagesToPostACK != null) - { - for (ServerMessage msg : pagedMessagesToPostACK) - { - try - { + if (pagedMessagesToPostACK != null) { + for (ServerMessage msg : pagedMessagesToPostACK) { + try { msg.decrementRefCount(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e); } } @@ -192,21 +164,17 @@ public class RefsOperation extends TransactionOperationAbstract } @Override - public synchronized List getRelatedMessageReferences() - { + public synchronized List getRelatedMessageReferences() { List listRet = new LinkedList(); listRet.addAll(listRet); return listRet; } @Override - public synchronized List getListOnConsumer(long consumerID) - { + public synchronized List getListOnConsumer(long consumerID) { List list = new LinkedList(); - for (MessageReference ref : refsToAck) - { - if (ref.getConsumerId() != null && ref.getConsumerId().equals(consumerID)) - { + for (MessageReference ref : refsToAck) { + if (ref.getConsumerId() != null && ref.getConsumerId().equals(consumerID)) { list.add(ref); } } @@ -214,8 +182,7 @@ public class RefsOperation extends TransactionOperationAbstract return list; } - public List getReferencesToAcknowledge() - { + public List getReferencesToAcknowledge() { return refsToAck; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ReplicationError.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ReplicationError.java index 546284f11c..63af112bbf 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ReplicationError.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ReplicationError.java @@ -34,25 +34,22 @@ import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; * handler at {@link org.apache.activemq.artemis.core.protocol.core.impl.ActiveMQClientProtocolManager.Channel0Handler}. As {@link org.apache.activemq.artemis.core.protocol.core.impl.ActiveMQClientProtocolManager} * is also shipped in the activemq-core-client JAR (which does not include {@link org.apache.activemq.artemis.core.server.ActiveMQServer}). */ -final class ReplicationError implements Interceptor -{ +final class ReplicationError implements Interceptor { + private final ActiveMQServer server; private LiveNodeLocator nodeLocator; - public ReplicationError(ActiveMQServer server, LiveNodeLocator nodeLocator) - { + public ReplicationError(ActiveMQServer server, LiveNodeLocator nodeLocator) { this.server = server; this.nodeLocator = nodeLocator; } @Override - public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException - { + public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException { if (packet.getType() != PacketImpl.BACKUP_REGISTRATION_FAILED) return true; BackupReplicationStartFailedMessage message = (BackupReplicationStartFailedMessage) packet; - switch (message.getRegistrationProblem()) - { + switch (message.getRegistrationProblem()) { case ALREADY_REPLICATING: tryNext(); break; @@ -69,14 +66,12 @@ final class ReplicationError implements Interceptor return false; } - private void failed() throws ActiveMQInternalErrorException - { + private void failed() throws ActiveMQInternalErrorException { ActiveMQServerLogger.LOGGER.errorRegisteringBackup(); nodeLocator.notifyRegistrationFailed(false); } - private void tryNext() - { + private void tryNext() { nodeLocator.notifyRegistrationFailed(true); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/RoutingContextImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/RoutingContextImpl.java index 4de0c3ce18..cbd3236f23 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/RoutingContextImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/RoutingContextImpl.java @@ -27,8 +27,7 @@ import org.apache.activemq.artemis.core.server.RouteContextList; import org.apache.activemq.artemis.core.server.RoutingContext; import org.apache.activemq.artemis.core.transaction.Transaction; -public final class RoutingContextImpl implements RoutingContext -{ +public final class RoutingContextImpl implements RoutingContext { // The pair here is Durable and NonDurable private final Map map = new HashMap(); @@ -37,13 +36,11 @@ public final class RoutingContextImpl implements RoutingContext private int queueCount; - public RoutingContextImpl(final Transaction transaction) - { + public RoutingContextImpl(final Transaction transaction) { this.transaction = transaction; } - public void clear() - { + public void clear() { transaction = null; map.clear(); @@ -51,17 +48,14 @@ public final class RoutingContextImpl implements RoutingContext queueCount = 0; } - public void addQueue(final SimpleString address, final Queue queue) - { + public void addQueue(final SimpleString address, final Queue queue) { RouteContextList listing = getContextListing(address); - if (queue.isDurable()) - { + if (queue.isDurable()) { listing.getDurableQueues().add(queue); } - else - { + else { listing.getNonDurableQueues().add(queue); } @@ -69,101 +63,84 @@ public final class RoutingContextImpl implements RoutingContext } @Override - public void addQueueWithAck(SimpleString address, Queue queue) - { + public void addQueueWithAck(SimpleString address, Queue queue) { addQueue(address, queue); RouteContextList listing = getContextListing(address); listing.addAckedQueue(queue); } @Override - public boolean isAlreadyAcked(SimpleString address, Queue queue) - { + public boolean isAlreadyAcked(SimpleString address, Queue queue) { RouteContextList listing = map.get(address); return listing == null ? false : listing.isAlreadyAcked(queue); } - public RouteContextList getContextListing(SimpleString address) - { + public RouteContextList getContextListing(SimpleString address) { RouteContextList listing = map.get(address); - if (listing == null) - { + if (listing == null) { listing = new ContextListing(); map.put(address, listing); } return listing; } - public Transaction getTransaction() - { + public Transaction getTransaction() { return transaction; } - public void setTransaction(final Transaction tx) - { + public void setTransaction(final Transaction tx) { transaction = tx; } - public List getNonDurableQueues(SimpleString address) - { + public List getNonDurableQueues(SimpleString address) { return getContextListing(address).getNonDurableQueues(); } - public List getDurableQueues(SimpleString address) - { + public List getDurableQueues(SimpleString address) { return getContextListing(address).getDurableQueues(); } - public int getQueueCount() - { + public int getQueueCount() { return queueCount; } - public Map getContexListing() - { + public Map getContexListing() { return this.map; } + private static class ContextListing implements RouteContextList { - private static class ContextListing implements RouteContextList - { private final List durableQueue = new ArrayList(1); private final List nonDurableQueue = new ArrayList(1); private final List ackedQueues = new ArrayList<>(); - public int getNumberOfDurableQueues() - { + public int getNumberOfDurableQueues() { return durableQueue.size(); } - public int getNumberOfNonDurableQueues() - { + public int getNumberOfNonDurableQueues() { return nonDurableQueue.size(); } @Override - public List getDurableQueues() - { + public List getDurableQueues() { return durableQueue; } @Override - public List getNonDurableQueues() - { + public List getNonDurableQueues() { return nonDurableQueue; } @Override - public void addAckedQueue(Queue queue) - { + public void addAckedQueue(Queue queue) { ackedQueues.add(queue); } @Override - public boolean isAlreadyAcked(Queue queue) - { + public boolean isAlreadyAcked(Queue queue) { return ackedQueues.contains(queue); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ScaleDownHandler.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ScaleDownHandler.java index 6f0dc53c1f..e335c50d00 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ScaleDownHandler.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ScaleDownHandler.java @@ -63,8 +63,8 @@ import org.apache.activemq.artemis.core.transaction.TransactionOperation; import org.apache.activemq.artemis.core.transaction.impl.TransactionImpl; import org.apache.activemq.artemis.utils.LinkedListIterator; -public class ScaleDownHandler -{ +public class ScaleDownHandler { + final PagingManager pagingManager; final PostOffice postOffice; private NodeManager nodeManager; @@ -72,8 +72,11 @@ public class ScaleDownHandler private final StorageManager storageManager; private String targetNodeId; - public ScaleDownHandler(PagingManager pagingManager, PostOffice postOffice, NodeManager nodeManager, ClusterController clusterController, StorageManager storageManager) - { + public ScaleDownHandler(PagingManager pagingManager, + PostOffice postOffice, + NodeManager nodeManager, + ClusterController clusterController, + StorageManager storageManager) { this.pagingManager = pagingManager; this.postOffice = postOffice; this.nodeManager = nodeManager; @@ -83,11 +86,9 @@ public class ScaleDownHandler public long scaleDown(ClientSessionFactory sessionFactory, ResourceManager resourceManager, - Map>> duplicateIDMap, + Map>> duplicateIDMap, SimpleString managementAddress, - SimpleString targetNodeId) throws Exception - { + SimpleString targetNodeId) throws Exception { ClusterControl clusterControl = clusterController.connectToNodeInCluster((ClientSessionFactoryInternal) sessionFactory); clusterControl.authorize(); long num = scaleDownMessages(sessionFactory, targetNodeId); @@ -98,27 +99,22 @@ public class ScaleDownHandler return num; } - public long scaleDownMessages(ClientSessionFactory sessionFactory, SimpleString nodeId) throws Exception - { + public long scaleDownMessages(ClientSessionFactory sessionFactory, SimpleString nodeId) throws Exception { long messageCount = 0; targetNodeId = nodeId != null ? nodeId.toString() : getTargetNodeId(sessionFactory); - try (ClientSession session = sessionFactory.createSession(false, true, true)) - { + try (ClientSession session = sessionFactory.createSession(false, true, true)) { ClientProducer producer = session.createProducer(); // perform a loop per address - for (SimpleString address : postOffice.getAddresses()) - { + for (SimpleString address : postOffice.getAddresses()) { ActiveMQServerLogger.LOGGER.debug("Scaling down address " + address); Bindings bindings = postOffice.getBindingsForAddress(address); // It will get a list of queues on this address, ordered by the number of messages Set queues = new TreeSet<>(new OrderQueueByNumberOfReferencesComparator()); - for (Binding binding : bindings.getBindings()) - { - if (binding instanceof LocalQueueBinding) - { + for (Binding binding : bindings.getBindings()) { + if (binding instanceof LocalQueueBinding) { Queue queue = ((LocalQueueBinding) binding).getQueue(); // as part of scale down we will cancel any scheduled message and pass it to theWhile we scan for the queues we will also cancel any scheduled messages and deliver them right away queue.deliverScheduledMessages(); @@ -126,13 +122,10 @@ public class ScaleDownHandler } } - - if (address.toString().startsWith("sf.")) - { + if (address.toString().startsWith("sf.")) { messageCount += scaleDownSNF(address, queues, producer); } - else - { + else { messageCount += scaleDownRegularMessages(address, queues, session, producer); } @@ -142,8 +135,10 @@ public class ScaleDownHandler return messageCount; } - public long scaleDownRegularMessages(final SimpleString address, final Set queues, final ClientSession clientSession, final ClientProducer producer) throws Exception - { + public long scaleDownRegularMessages(final SimpleString address, + final Set queues, + final ClientSession clientSession, + final ClientProducer producer) throws Exception { ActiveMQServerLogger.LOGGER.debug("Scaling down messages on address " + address); long messageCount = 0; @@ -155,39 +150,31 @@ public class ScaleDownHandler pageStore.disableCleanup(); - try - { + try { - for (Queue queue : queues) - { + for (Queue queue : queues) { controls.put(queue, new QueuesXRefInnerManager(clientSession, queue, pageStore)); } // compile a list of all the relevant queues and queue iterators for this address - for (Queue loopQueue : queues) - { + for (Queue loopQueue : queues) { ActiveMQServerLogger.LOGGER.debug("Scaling down messages on address " + address + " / performing loop on queue " + loopQueue); - try (LinkedListIterator messagesIterator = loopQueue.totalIterator()) - { + try (LinkedListIterator messagesIterator = loopQueue.totalIterator()) { - while (messagesIterator.hasNext()) - { + while (messagesIterator.hasNext()) { MessageReference messageReference = messagesIterator.next(); Message message = messageReference.getMessage().copy(); ActiveMQServerLogger.LOGGER.debug("Reading message " + message + " from queue " + loopQueue); Set queuesFound = new HashSet<>(); - for (Map.Entry controlEntry : controls.entrySet()) - { - if (controlEntry.getKey() == loopQueue) - { + for (Map.Entry controlEntry : controls.entrySet()) { + if (controlEntry.getKey() == loopQueue) { // no need to lookup on itself, we just add it queuesFound.add(controlEntry.getValue()); } - else if (controlEntry.getValue().lookup(messageReference)) - { + else if (controlEntry.getValue().lookup(messageReference)) { ActiveMQServerLogger.LOGGER.debug("Message existed on queue " + controlEntry.getKey().getID() + " removeID=" + controlEntry.getValue().getQueueID()); queuesFound.add(controlEntry.getValue()); } @@ -196,24 +183,18 @@ public class ScaleDownHandler // get the ID for every queue that contains the message ByteBuffer buffer = ByteBuffer.allocate(queuesFound.size() * 8); - - for (QueuesXRefInnerManager control : queuesFound) - { + for (QueuesXRefInnerManager control : queuesFound) { long queueID = control.getQueueID(); buffer.putLong(queueID); } - message.putBytesProperty(MessageImpl.HDR_ROUTE_TO_IDS, buffer.array()); - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { - if (messageReference.isPaged()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { + if (messageReference.isPaged()) { ActiveMQServerLogger.LOGGER.debug("*********************<<<<< Scaling down pdgmessage " + message); } - else - { + else { ActiveMQServerLogger.LOGGER.debug("*********************<<<<< Scaling down message " + message); } } @@ -224,8 +205,7 @@ public class ScaleDownHandler messagesIterator.remove(); // We need to perform the ack / removal after sending, otherwise the message could been removed before the send is finished - for (QueuesXRefInnerManager queueFound : queuesFound) - { + for (QueuesXRefInnerManager queueFound : queuesFound) { ackMessageOnQueue(tx, queueFound.getQueue(), messageReference); } @@ -235,23 +215,21 @@ public class ScaleDownHandler tx.commit(); - - for (QueuesXRefInnerManager controlRemoved : controls.values()) - { + for (QueuesXRefInnerManager controlRemoved : controls.values()) { controlRemoved.close(); } return messageCount; } - finally - { + finally { pageStore.enableCleanup(); pageStore.getCursorProvider().scheduleCleanup(); } } - private long scaleDownSNF(final SimpleString address, final Set queues, final ClientProducer producer) throws Exception - { + private long scaleDownSNF(final SimpleString address, + final Set queues, + final ClientProducer producer) throws Exception { long messageCount = 0; final String propertyEnd; @@ -259,25 +237,20 @@ public class ScaleDownHandler // If this SNF is towards our targetNodeId boolean queueOnTarget = address.toString().endsWith(targetNodeId); - if (queueOnTarget) - { + if (queueOnTarget) { propertyEnd = targetNodeId; } - else - { + else { propertyEnd = address.toString().substring(address.toString().lastIndexOf(".")); } Transaction tx = new TransactionImpl(storageManager); - for (Queue queue : queues) - { + for (Queue queue : queues) { // using auto-closeable - try (LinkedListIterator messagesIterator = queue.totalIterator()) - { + try (LinkedListIterator messagesIterator = queue.totalIterator()) { // loop through every message of this queue - while (messagesIterator.hasNext()) - { + while (messagesIterator.hasNext()) { MessageReference messageRef = messagesIterator.next(); Message message = messageRef.getMessage().copy(); @@ -290,12 +263,9 @@ public class ScaleDownHandler List propertiesToRemove = new ArrayList<>(); message.removeProperty(MessageImpl.HDR_ROUTE_TO_IDS); - for (SimpleString propName : message.getPropertyNames()) - { - if (propName.startsWith(MessageImpl.HDR_ROUTE_TO_IDS)) - { - if (propName.toString().endsWith(propertyEnd)) - { + for (SimpleString propName : message.getPropertyNames()) { + if (propName.startsWith(MessageImpl.HDR_ROUTE_TO_IDS)) { + if (propName.toString().endsWith(propertyEnd)) { oldRouteToIDs = message.getBytesProperty(propName); } propertiesToRemove.add(propName); @@ -304,17 +274,14 @@ public class ScaleDownHandler // TODO: what if oldRouteToIDs == null ?? - for (SimpleString propertyToRemove : propertiesToRemove) - { + for (SimpleString propertyToRemove : propertiesToRemove) { message.removeProperty(propertyToRemove); } - if (queueOnTarget) - { + if (queueOnTarget) { message.putBytesProperty(MessageImpl.HDR_ROUTE_TO_IDS, oldRouteToIDs); } - else - { + else { message.putBytesProperty(MessageImpl.HDR_SCALEDOWN_TO_IDS, oldRouteToIDs); } @@ -335,19 +302,17 @@ public class ScaleDownHandler return messageCount; } - private String getTargetNodeId(ClientSessionFactory sessionFactory) - { + private String getTargetNodeId(ClientSessionFactory sessionFactory) { return sessionFactory.getServerLocator().getTopology().getMember(sessionFactory.getConnectorConfiguration()).getNodeId(); } - public void scaleDownTransactions(ClientSessionFactory sessionFactory, ResourceManager resourceManager) throws Exception - { + public void scaleDownTransactions(ClientSessionFactory sessionFactory, + ResourceManager resourceManager) throws Exception { ClientSession session = sessionFactory.createSession(true, false, false); ClientSession queueCreateSession = sessionFactory.createSession(false, true, true); List preparedTransactions = resourceManager.getPreparedTransactions(); Map queueIDs = new HashMap<>(); - for (Xid xid : preparedTransactions) - { + for (Xid xid : preparedTransactions) { ActiveMQServerLogger.LOGGER.debug("Scaling down transaction: " + xid); Transaction transaction = resourceManager.getTransaction(xid); session.start(xid, XAResource.TMNOFLAGS); @@ -355,60 +320,49 @@ public class ScaleDownHandler // Get the information of the Prepared TXs so it could replay the TXs Map, List>> queuesToSendTo = new HashMap<>(); - for (TransactionOperation operation : allOperations) - { - if (operation instanceof PostOfficeImpl.AddOperation) - { + for (TransactionOperation operation : allOperations) { + if (operation instanceof PostOfficeImpl.AddOperation) { PostOfficeImpl.AddOperation addOperation = (PostOfficeImpl.AddOperation) operation; List refs = addOperation.getRelatedMessageReferences(); - for (MessageReference ref : refs) - { + for (MessageReference ref : refs) { ServerMessage message = ref.getMessage(); Queue queue = ref.getQueue(); long queueID; String queueName = queue.getName().toString(); - if (queueIDs.containsKey(queueName)) - { + if (queueIDs.containsKey(queueName)) { queueID = queueIDs.get(queueName); } - else - { + else { queueID = createQueueIfNecessaryAndGetID(queueCreateSession, queue, message.getAddress()); queueIDs.put(queueName, queueID); // store it so we don't have to look it up every time } Pair, List> queueIds = queuesToSendTo.get(message); - if (queueIds == null) - { + if (queueIds == null) { queueIds = new Pair, List>(new ArrayList(), new ArrayList()); queuesToSendTo.put(message, queueIds); } queueIds.getA().add(queueID); } } - else if (operation instanceof RefsOperation) - { + else if (operation instanceof RefsOperation) { RefsOperation refsOperation = (RefsOperation) operation; List refs = refsOperation.getReferencesToAcknowledge(); - for (MessageReference ref : refs) - { + for (MessageReference ref : refs) { ServerMessage message = ref.getMessage(); Queue queue = ref.getQueue(); long queueID; String queueName = queue.getName().toString(); - if (queueIDs.containsKey(queueName)) - { + if (queueIDs.containsKey(queueName)) { queueID = queueIDs.get(queueName); } - else - { + else { queueID = createQueueIfNecessaryAndGetID(queueCreateSession, queue, message.getAddress()); queueIDs.put(queueName, queueID); // store it so we don't have to look it up every time } Pair, List> queueIds = queuesToSendTo.get(message); - if (queueIds == null) - { + if (queueIds == null) { queueIds = new Pair, List>(new ArrayList(), new ArrayList()); queuesToSendTo.put(message, queueIds); } @@ -419,22 +373,18 @@ public class ScaleDownHandler } ClientProducer producer = session.createProducer(); - for (Map.Entry, List>> entry : queuesToSendTo.entrySet()) - { + for (Map.Entry, List>> entry : queuesToSendTo.entrySet()) { List ids = entry.getValue().getA(); ByteBuffer buffer = ByteBuffer.allocate(ids.size() * 8); - for (Long id : ids) - { + for (Long id : ids) { buffer.putLong(id); } ServerMessage message = entry.getKey(); message.putBytesProperty(MessageImpl.HDR_ROUTE_TO_IDS, buffer.array()); ids = entry.getValue().getB(); - if (ids.size() > 0) - { + if (ids.size() > 0) { buffer = ByteBuffer.allocate(ids.size() * 8); - for (Long id : ids) - { + for (Long id : ids) { buffer.putLong(id); } message.putBytesProperty(MessageImpl.HDR_ROUTE_TO_ACK_IDS, buffer.array()); @@ -446,19 +396,17 @@ public class ScaleDownHandler } } - - public void scaleDownDuplicateIDs(Map>> duplicateIDMap, ClientSessionFactory sessionFactory, SimpleString managementAddress) throws Exception - { + public void scaleDownDuplicateIDs(Map>> duplicateIDMap, + ClientSessionFactory sessionFactory, + SimpleString managementAddress) throws Exception { ClientSession session = sessionFactory.createSession(true, false, false); ClientProducer producer = session.createProducer(managementAddress); //todo - https://issues.jboss.org/browse/HORNETQ-1336 - for (SimpleString address : duplicateIDMap.keySet()) - { + for (SimpleString address : duplicateIDMap.keySet()) { ClientMessage message = session.createMessage(false); List> list = duplicateIDMap.get(address); String[] array = new String[list.size()]; - for (int i = 0; i < list.size(); i++) - { + for (int i = 0; i < list.size(); i++) { Pair pair = list.get(i); array[i] = new String(pair.getA()); } @@ -467,16 +415,17 @@ public class ScaleDownHandler } session.close(); } + /** * Get the ID of the queues involved so the message can be routed properly. This is done because we cannot * send directly to a queue, we have to send to an address instead but not all the queues related to the * address may need the message */ - private long createQueueIfNecessaryAndGetID(ClientSession session, Queue queue, SimpleString addressName) throws Exception - { + private long createQueueIfNecessaryAndGetID(ClientSession session, + Queue queue, + SimpleString addressName) throws Exception { long queueID = getQueueID(session, queue.getName()); - if (queueID == -1) - { + if (queueID == -1) { session.createQueue(addressName, queue.getName(), queue.getFilter() == null ? null : queue.getFilter().getFilterString(), queue.isDurable()); ActiveMQServerLogger.LOGGER.debug("Failed to get queue ID, creating queue [addressName=" + addressName + ", queueName=" + queue.getName() + ", filter=" + (queue.getFilter() == null ? "" : queue.getFilter().getFilterString()) + ", durable=" + queue.isDurable() + "]"); queueID = getQueueID(session, queue.getName()); @@ -486,8 +435,7 @@ public class ScaleDownHandler return queueID; } - private Integer getQueueID(ClientSession session, SimpleString queueName) throws Exception - { + private Integer getQueueID(ClientSession session, SimpleString queueName) throws Exception { Integer queueID = -1; ClientRequestor requestor = new ClientRequestor(session, "jms.queue.activemq.management"); ClientMessage managementMessage = session.createMessage(false); @@ -496,47 +444,48 @@ public class ScaleDownHandler ActiveMQServerLogger.LOGGER.debug("Requesting ID for: " + queueName); ClientMessage reply = requestor.request(managementMessage); Object result = ManagementHelper.getResult(reply); - if (result != null && result instanceof Integer) - { + if (result != null && result instanceof Integer) { queueID = (Integer) result; } requestor.close(); return queueID; } - public static class OrderQueueByNumberOfReferencesComparator implements Comparator - { + public static class OrderQueueByNumberOfReferencesComparator implements Comparator { + @Override - public int compare(Queue queue1, Queue queue2) - { + public int compare(Queue queue1, Queue queue2) { final int BEFORE = -1; final int EQUAL = 0; final int AFTER = 1; int result = 0; - if (queue1 == queue2) return EQUAL; + if (queue1 == queue2) + return EQUAL; - if (queue1.getMessageCount() == queue2.getMessageCount()) - { + if (queue1.getMessageCount() == queue2.getMessageCount()) { // if it's the same count we will use the ID as a tie breaker: long tieBreak = queue2.getID() - queue1.getID(); - if (tieBreak > 0) return AFTER; - else if (tieBreak < 0) return BEFORE; - else return EQUAL; // EQUAL here shouldn't really happen... but lets do the check anyways + if (tieBreak > 0) + return AFTER; + else if (tieBreak < 0) + return BEFORE; + else + return EQUAL; // EQUAL here shouldn't really happen... but lets do the check anyways } - if (queue1.getMessageCount() > queue2.getMessageCount()) return BEFORE; - if (queue1.getMessageCount() < queue2.getMessageCount()) return AFTER; + if (queue1.getMessageCount() > queue2.getMessageCount()) + return BEFORE; + if (queue1.getMessageCount() < queue2.getMessageCount()) + return AFTER; return result; } } - - private void ackMessageOnQueue(Transaction tx, Queue queue, MessageReference messageRef) throws Exception - { + private void ackMessageOnQueue(Transaction tx, Queue queue, MessageReference messageRef) throws Exception { queue.acknowledge(tx, messageRef); } @@ -544,8 +493,8 @@ public class ScaleDownHandler * this class will control iterations while * looking over for messages relations */ - private class QueuesXRefInnerManager - { + private class QueuesXRefInnerManager { + private final Queue queue; private LinkedListIterator memoryIterator; private MessageReference lastRef = null; @@ -558,53 +507,41 @@ public class ScaleDownHandler private long targetQueueID = -1; - - QueuesXRefInnerManager(final ClientSession clientSession, final Queue queue, final PagingStore store) - { + QueuesXRefInnerManager(final ClientSession clientSession, final Queue queue, final PagingStore store) { this.queue = queue; this.store = store; this.clientSession = clientSession; } - public Queue getQueue() - { + public Queue getQueue() { return queue; } - public long getQueueID() throws Exception - { + public long getQueueID() throws Exception { - if (targetQueueID < 0) - { + if (targetQueueID < 0) { targetQueueID = createQueueIfNecessaryAndGetID(clientSession, queue, queue.getAddress()); } return targetQueueID; } - public void close() - { - if (memoryIterator != null) - { + public void close() { + if (memoryIterator != null) { memoryIterator.close(); } } - public boolean lookup(MessageReference reference) throws Exception - { + public boolean lookup(MessageReference reference) throws Exception { - if (reference.isPaged()) - { + if (reference.isPaged()) { PageSubscription subscription = store.getCursorProvider().getSubscription(queue.getID()); - if (subscription.contains((PagedReference) reference)) - { + if (subscription.contains((PagedReference) reference)) { return true; } } - else - { + else { - if (lastRef != null && lastRef.getMessage().equals(reference.getMessage())) - { + if (lastRef != null && lastRef.getMessage().equals(reference.getMessage())) { lastRef = null; memoryIterator.remove(); return true; @@ -612,41 +549,33 @@ public class ScaleDownHandler int numberOfScans = 2; - if (memoryIterator == null) - { + if (memoryIterator == null) { // If we have a brand new iterator, and we can't find something numberOfScans = 1; } MessageReference initialRef = null; - for (int i = 0; i < numberOfScans; i++) - { + for (int i = 0; i < numberOfScans; i++) { ActiveMQServerLogger.LOGGER.debug("iterating on queue " + queue + " while looking for reference " + reference); memoryIterator = queue.iterator(); - while (memoryIterator.hasNext()) - { + while (memoryIterator.hasNext()) { lastRef = memoryIterator.next(); ActiveMQServerLogger.LOGGER.debug("Iterating on message " + lastRef); - if (lastRef.getMessage().equals(reference.getMessage())) - { + if (lastRef.getMessage().equals(reference.getMessage())) { memoryIterator.remove(); lastRef = null; return true; } - if (initialRef == null) - { + if (initialRef == null) { lastRef = initialRef; } - else - { - if (initialRef.equals(lastRef)) - { - if (!memoryIterator.hasNext()) - { + else { + if (initialRef.equals(lastRef)) { + if (!memoryIterator.hasNext()) { // if by coincidence we are at the end of the iterator, we just reset the iterator lastRef = null; memoryIterator.close(); @@ -670,5 +599,4 @@ public class ScaleDownHandler } - } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ScheduledDeliveryHandlerImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ScheduledDeliveryHandlerImpl.java index 4b6bb62b55..97ce13e058 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ScheduledDeliveryHandlerImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ScheduledDeliveryHandlerImpl.java @@ -37,32 +37,27 @@ import org.apache.activemq.artemis.core.server.ScheduledDeliveryHandler; /** * Handles scheduling deliveries to a queue at the correct time. */ -public class ScheduledDeliveryHandlerImpl implements ScheduledDeliveryHandler -{ +public class ScheduledDeliveryHandlerImpl implements ScheduledDeliveryHandler { + private static final boolean trace = ActiveMQServerLogger.LOGGER.isTraceEnabled(); private final ScheduledExecutorService scheduledExecutor; - private final Map runnables = new ConcurrentHashMap<>(); // This contains RefSchedules which are delegates to the real references // just adding some information to keep it in order accordingly to the initial operations private final TreeSet scheduledReferences = new TreeSet<>(new MessageReferenceComparator()); - public ScheduledDeliveryHandlerImpl(final ScheduledExecutorService scheduledExecutor) - { + public ScheduledDeliveryHandlerImpl(final ScheduledExecutorService scheduledExecutor) { this.scheduledExecutor = scheduledExecutor; } - public boolean checkAndSchedule(final MessageReference ref, final boolean tail) - { + public boolean checkAndSchedule(final MessageReference ref, final boolean tail) { long deliveryTime = ref.getScheduledDeliveryTime(); - if (deliveryTime > 0 && scheduledExecutor != null) - { - if (ScheduledDeliveryHandlerImpl.trace) - { + if (deliveryTime > 0 && scheduledExecutor != null) { + if (ScheduledDeliveryHandlerImpl.trace) { ActiveMQServerLogger.LOGGER.trace("Scheduling delivery for " + ref + " to occur at " + deliveryTime); } @@ -75,50 +70,38 @@ public class ScheduledDeliveryHandlerImpl implements ScheduledDeliveryHandler return false; } - - public void addInPlace(final long deliveryTime, final MessageReference ref, final boolean tail) - { - synchronized (scheduledReferences) - { + public void addInPlace(final long deliveryTime, final MessageReference ref, final boolean tail) { + synchronized (scheduledReferences) { scheduledReferences.add(new RefScheduled(ref, tail)); } } - public int getScheduledCount() - { - synchronized (scheduledReferences) - { + public int getScheduledCount() { + synchronized (scheduledReferences) { return scheduledReferences.size(); } } - public List getScheduledReferences() - { + public List getScheduledReferences() { List refs = new LinkedList(); - synchronized (scheduledReferences) - { - for (RefScheduled ref : scheduledReferences) - { + synchronized (scheduledReferences) { + for (RefScheduled ref : scheduledReferences) { refs.add(ref.getRef()); } } return refs; } - public List cancel(final Filter filter) - { + public List cancel(final Filter filter) { List refs = new ArrayList(); - synchronized (scheduledReferences) - { + synchronized (scheduledReferences) { Iterator iter = scheduledReferences.iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { MessageReference ref = iter.next().getRef(); - if (filter == null || filter.match(ref.getMessage())) - { + if (filter == null || filter.match(ref.getMessage())) { iter.remove(); refs.add(ref); } @@ -127,16 +110,12 @@ public class ScheduledDeliveryHandlerImpl implements ScheduledDeliveryHandler return refs; } - public MessageReference removeReferenceWithID(final long id) - { - synchronized (scheduledReferences) - { + public MessageReference removeReferenceWithID(final long id) { + synchronized (scheduledReferences) { Iterator iter = scheduledReferences.iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { MessageReference ref = iter.next().getRef(); - if (ref.getMessage().getMessageID() == id) - { + if (ref.getMessage().getMessageID() == id) { iter.remove(); return ref; } @@ -146,91 +125,76 @@ public class ScheduledDeliveryHandlerImpl implements ScheduledDeliveryHandler return null; } - private void scheduleDelivery(final long deliveryTime) - { + private void scheduleDelivery(final long deliveryTime) { final long now = System.currentTimeMillis(); final long delay = deliveryTime - now; - if (delay < 0) - { - if (ScheduledDeliveryHandlerImpl.trace) - { + if (delay < 0) { + if (ScheduledDeliveryHandlerImpl.trace) { ActiveMQServerLogger.LOGGER.trace("calling another scheduler now as deliverTime " + deliveryTime + " < now=" + now); } // if delay == 0 we will avoid races between adding the scheduler and finishing it ScheduledDeliveryRunnable runnable = new ScheduledDeliveryRunnable(deliveryTime); scheduledExecutor.schedule(runnable, 0, TimeUnit.MILLISECONDS); } - else if (!runnables.containsKey(deliveryTime)) - { + else if (!runnables.containsKey(deliveryTime)) { ScheduledDeliveryRunnable runnable = new ScheduledDeliveryRunnable(deliveryTime); - if (ScheduledDeliveryHandlerImpl.trace) - { + if (ScheduledDeliveryHandlerImpl.trace) { ActiveMQServerLogger.LOGGER.trace("Setting up scheduler for " + deliveryTime + " with a delay of " + delay + " as now=" + now); } runnables.put(deliveryTime, runnable); scheduledExecutor.schedule(runnable, delay, TimeUnit.MILLISECONDS); } - else - { - if (ScheduledDeliveryHandlerImpl.trace) - { + else { + if (ScheduledDeliveryHandlerImpl.trace) { ActiveMQServerLogger.LOGGER.trace("Couldn't make another scheduler as " + deliveryTime + " is already set, now is " + now); } } } - private class ScheduledDeliveryRunnable implements Runnable - { + private class ScheduledDeliveryRunnable implements Runnable { + long deliveryTime; - public ScheduledDeliveryRunnable(final long deliveryTime) - { + public ScheduledDeliveryRunnable(final long deliveryTime) { this.deliveryTime = deliveryTime; } - public void run() - { + public void run() { HashMap> refs = new HashMap>(); runnables.remove(deliveryTime); final long now = System.currentTimeMillis(); - if (now < deliveryTime) - { + if (now < deliveryTime) { // Ohhhh... blame it on the OS // on some OSes (so far Windows only) the precision of the scheduled executor could eventually give // an executor call earlier than it was supposed... // for that reason we will schedule it again so no messages are lost! // we can't just assume deliveryTime here as we could deliver earlier than what we are supposed to // this is basically a hack to work around an OS or JDK bug! - if (trace) - { + if (trace) { ActiveMQServerLogger.LOGGER.trace("Scheduler is working around OS imprecisions on " + - "timing and re-scheduling an executor. now=" + now + - " and deliveryTime=" + deliveryTime); + "timing and re-scheduling an executor. now=" + now + + " and deliveryTime=" + deliveryTime); } ScheduledDeliveryHandlerImpl.this.scheduleDelivery(deliveryTime); } - if (ScheduledDeliveryHandlerImpl.trace) - { + if (ScheduledDeliveryHandlerImpl.trace) { ActiveMQServerLogger.LOGGER.trace("Is it " + System.currentTimeMillis() + " now and we are running deliveryTime = " + deliveryTime); } - synchronized (scheduledReferences) - { + synchronized (scheduledReferences) { Iterator iter = scheduledReferences.iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { MessageReference reference = iter.next().getRef(); - if (reference.getScheduledDeliveryTime() > now) - { + if (reference.getScheduledDeliveryTime() > now) { // We will delivery as long as there are messages to be delivered break; } @@ -241,32 +205,27 @@ public class ScheduledDeliveryHandlerImpl implements ScheduledDeliveryHandler LinkedList references = refs.get(reference.getQueue()); - if (references == null) - { + if (references == null) { references = new LinkedList(); refs.put(reference.getQueue(), references); } - if (ScheduledDeliveryHandlerImpl.trace) - { + if (ScheduledDeliveryHandlerImpl.trace) { ActiveMQServerLogger.LOGGER.trace("sending message " + reference + " to delivery, deliveryTime = " + deliveryTime); } references.addFirst(reference); } - if (ScheduledDeliveryHandlerImpl.trace) - { + if (ScheduledDeliveryHandlerImpl.trace) { ActiveMQServerLogger.LOGGER.trace("Finished loop on deliveryTime = " + deliveryTime); } } - for (Map.Entry> entry : refs.entrySet()) - { + for (Map.Entry> entry : refs.entrySet()) { Queue queue = entry.getKey(); LinkedList list = entry.getValue(); - if (trace) - { + if (trace) { ActiveMQServerLogger.LOGGER.trace("Delivering " + list.size() + " elements on list to queue " + queue); } queue.addHead(list); @@ -277,70 +236,56 @@ public class ScheduledDeliveryHandlerImpl implements ScheduledDeliveryHandler } } - // We need a treeset ordered, but we need to order tail operations as well. // So, this will serve as a delegate to the object - class RefScheduled - { + class RefScheduled { + private final MessageReference ref; private final boolean tail; - RefScheduled(MessageReference ref, boolean tail) - { + RefScheduled(MessageReference ref, boolean tail) { this.ref = ref; this.tail = tail; } - public MessageReference getRef() - { + public MessageReference getRef() { return ref; } - public boolean isTail() - { + public boolean isTail() { return tail; } } - static class MessageReferenceComparator implements Comparator - { - public int compare(RefScheduled ref1, RefScheduled ref2) - { + static class MessageReferenceComparator implements Comparator { + + public int compare(RefScheduled ref1, RefScheduled ref2) { long diff = ref1.getRef().getScheduledDeliveryTime() - ref2.getRef().getScheduledDeliveryTime(); - if (diff < 0L) - { + if (diff < 0L) { return -1; } - if (diff > 0L) - { + if (diff > 0L) { return 1; } - // Even if ref1 and ref2 have the same delivery time, we only want to return 0 if they are identical - if (ref1 == ref2) - { + if (ref1 == ref2) { return 0; } - else - { + else { - if (ref1.isTail() && !ref2.isTail()) - { + if (ref1.isTail() && !ref2.isTail()) { return 1; } - else if (!ref1.isTail() && ref2.isTail()) - { + else if (!ref1.isTail() && ref2.isTail()) { return -1; } - if (!ref1.isTail() && !ref2.isTail()) - { + if (!ref1.isTail() && !ref2.isTail()) { return -1; } - else - { + else { return 1; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ServerConsumerImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ServerConsumerImpl.java index cd4a59ff11..741c32be0c 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ServerConsumerImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ServerConsumerImpl.java @@ -62,8 +62,7 @@ import org.apache.activemq.artemis.utils.TypedProperties; /** * Concrete implementation of a ClientConsumer. */ -public class ServerConsumerImpl implements ServerConsumer, ReadyListener -{ +public class ServerConsumerImpl implements ServerConsumer, ReadyListener { // Constants ------------------------------------------------------------------------------------ private static boolean isTrace = ActiveMQServerLogger.LOGGER.isTraceEnabled(); @@ -101,8 +100,7 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener private volatile LargeMessageDeliverer largeMessageDeliverer = null; - public String debug() - { + public String debug() { return toString() + "::Delivering " + this.deliveringRefs.size(); } @@ -156,10 +154,8 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener final SessionCallback callback, final boolean preAcknowledge, final boolean strictUpdateDeliveryCount, - final ManagementService managementService) throws Exception - { - this(id, session, binding, filter, started, browseOnly, storageManager, callback, - preAcknowledge, strictUpdateDeliveryCount, managementService, true, null); + final ManagementService managementService) throws Exception { + this(id, session, binding, filter, started, browseOnly, storageManager, callback, preAcknowledge, strictUpdateDeliveryCount, managementService, true, null); } public ServerConsumerImpl(final long id, @@ -174,8 +170,7 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener final boolean strictUpdateDeliveryCount, final ManagementService managementService, final boolean supportLargeMessage, - final Integer credits) throws Exception - { + final Integer credits) throws Exception { this.id = id; this.filter = filter; @@ -206,24 +201,19 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener this.creationTime = System.currentTimeMillis(); - if (browseOnly) - { + if (browseOnly) { browserDeliverer = new BrowserDeliverer(messageQueue.totalIterator()); } - else - { + else { messageQueue.addConsumer(this); } this.supportLargeMessage = supportLargeMessage; - if (credits != null) - { - if (credits == -1) - { + if (credits != null) { + if (credits == -1) { availableCredits = null; } - else - { + else { availableCredits.set(credits); } } @@ -232,49 +222,39 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener // ServerConsumer implementation // ---------------------------------------------------------------------- - public Object getProtocolContext() - { + public Object getProtocolContext() { return protocolContext; } - public void setProtocolContext(Object protocolContext) - { + public void setProtocolContext(Object protocolContext) { this.protocolContext = protocolContext; } - public long getID() - { + public long getID() { return id; } - public boolean isBrowseOnly() - { + public boolean isBrowseOnly() { return browseOnly; } - public long getCreationTime() - { + public long getCreationTime() { return creationTime; } - public String getConnectionID() - { + public String getConnectionID() { return this.session.getConnectionID().toString(); } - public String getSessionID() - { + public String getSessionID() { return this.session.getName(); } - public List getDeliveringMessages() - { + public List getDeliveringMessages() { List refs = new LinkedList(); - synchronized (lock) - { + synchronized (lock) { List refsOnConsumer = session.getInTXMessagesForConsumer(this.id); - if (refsOnConsumer != null) - { + if (refsOnConsumer != null) { refs.addAll(refsOnConsumer); } refs.addAll(deliveringRefs); @@ -283,16 +263,13 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener return refs; } - public HandleStatus handle(final MessageReference ref) throws Exception - { - if (callback != null && !callback.hasCredits(this) || availableCredits != null && availableCredits.get() <= 0) - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + public HandleStatus handle(final MessageReference ref) throws Exception { + if (callback != null && !callback.hasCredits(this) || availableCredits != null && availableCredits.get() <= 0) { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug(this + " is busy for the lack of credits. Current credits = " + - availableCredits + - " Can't receive reference " + - ref); + availableCredits + + " Can't receive reference " + + ref); } return HandleStatus.BUSY; @@ -304,48 +281,39 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener // return HandleStatus.BUSY; // } - synchronized (lock) - { + synchronized (lock) { // If the consumer is stopped then we don't accept the message, it // should go back into the // queue for delivery later. - if (!started || transferring) - { + if (!started || transferring) { return HandleStatus.BUSY; } // If there is a pendingLargeMessage we can't take another message // This has to be checked inside the lock as the set to null is done inside the lock - if (largeMessageDeliverer != null) - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (largeMessageDeliverer != null) { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug(this + " is busy delivering large message " + - largeMessageDeliverer + - ", can't deliver reference " + - ref); + largeMessageDeliverer + + ", can't deliver reference " + + ref); } return HandleStatus.BUSY; } final ServerMessage message = ref.getMessage(); - if (filter != null && !filter.match(message)) - { - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + if (filter != null && !filter.match(message)) { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("Reference " + ref + " is a noMatch on consumer " + this); } return HandleStatus.NO_MATCH; } - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("Handling reference " + ref); } - if (!browseOnly) - { - if (!preAcknowledge) - { + if (!browseOnly) { + if (!preAcknowledge) { deliveringRefs.add(ref); } @@ -357,20 +325,16 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener // If updateDeliveries = false (set by strict-update), // the updateDeliveryCount would still be updated after c - if (strictUpdateDeliveryCount && !ref.isPaged()) - { + if (strictUpdateDeliveryCount && !ref.isPaged()) { if (ref.getMessage().isDurable() && ref.getQueue().isDurable() && !ref.getQueue().isInternalQueue() && - !ref.isPaged()) - { + !ref.isPaged()) { storageManager.updateDeliveryCount(ref); } } - if (preAcknowledge) - { - if (message.isLargeMessage()) - { + if (preAcknowledge) { + if (message.isLargeMessage()) { // we must hold one reference, or the file will be deleted before it could be delivered ((LargeServerMessage) message).incrementDelayDeletionCount(); } @@ -381,8 +345,7 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener } - if (message.isLargeMessage() && this.supportLargeMessage) - { + if (message.isLargeMessage() && this.supportLargeMessage) { largeMessageDeliverer = new LargeMessageDeliverer((LargeServerMessage) message, ref); } @@ -392,16 +355,12 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener } } - public void proceedDeliver(MessageReference reference) throws Exception - { - try - { + public void proceedDeliver(MessageReference reference) throws Exception { + try { ServerMessage message = reference.getMessage(); - if (message.isLargeMessage() && supportLargeMessage) - { - if (largeMessageDeliverer == null) - { + if (message.isLargeMessage() && supportLargeMessage) { + if (largeMessageDeliverer == null) { // This can't really happen as handle had already crated the deliverer // instead of throwing an exception in weird cases there is no problem on just go ahead and create it // again here @@ -411,33 +370,28 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener // as it would return busy if there is anything pending largeMessageDeliverer.deliver(); } - else - { + else { deliverStandardMessage(reference, message); } } - finally - { + finally { lockDelivery.readLock().unlock(); } } - public Filter getFilter() - { + public Filter getFilter() { return filter; } @Override - public void close(final boolean failed) throws Exception - { + public void close(final boolean failed) throws Exception { callback.removeReadyListener(this); setStarted(false); LargeMessageDeliverer del = largeMessageDeliverer; - if (del != null) - { + if (del != null) { del.finish(); } @@ -449,8 +403,7 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener Transaction tx = new TransactionImpl(storageManager); - while (iter.hasNext()) - { + while (iter.hasNext()) { MessageReference ref = iter.next(); ref.getQueue().cancel(tx, ref, true); @@ -458,8 +411,7 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener tx.rollback(); - if (!browseOnly) - { + if (!browseOnly) { TypedProperties props = new TypedProperties(); props.putSimpleStringProperty(ManagementHelper.HDR_ADDRESS, binding.getAddress()); @@ -468,14 +420,12 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener props.putSimpleStringProperty(ManagementHelper.HDR_ROUTING_NAME, binding.getRoutingName()); - props.putSimpleStringProperty(ManagementHelper.HDR_FILTERSTRING, - filter == null ? null : filter.getFilterString()); + props.putSimpleStringProperty(ManagementHelper.HDR_FILTERSTRING, filter == null ? null : filter.getFilterString()); props.putIntProperty(ManagementHelper.HDR_DISTANCE, binding.getDistance()); props.putIntProperty(ManagementHelper.HDR_CONSUMER_COUNT, messageQueue.getConsumerCount()); - // HORNETQ-946 props.putSimpleStringProperty(ManagementHelper.HDR_USER, SimpleString.toSimpleString(session.getUsername())); @@ -490,14 +440,11 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener } @Override - public void removeItself() throws Exception - { - if (browseOnly) - { + public void removeItself() throws Exception { + if (browseOnly) { browserDeliverer.close(); } - else - { + else { messageQueue.removeConsumer(this); } @@ -510,35 +457,26 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener * When the consumer receives such a "forced delivery" message, it discards it and knows that * there are no other messages to be delivered. */ - public synchronized void forceDelivery(final long sequence) - { + public synchronized void forceDelivery(final long sequence) { promptDelivery(); // JBPAPP-6030 - Using the executor to avoid distributed dead locks - messageQueue.getExecutor().execute(new Runnable() - { - public void run() - { - try - { + messageQueue.getExecutor().execute(new Runnable() { + public void run() { + try { // We execute this on the same executor to make sure the force delivery message is written after // any delivery is completed - synchronized (lock) - { - if (transferring) - { + synchronized (lock) { + if (transferring) { // Case it's transferring (reattach), we will retry later - messageQueue.getExecutor().execute(new Runnable() - { - public void run() - { + messageQueue.getExecutor().execute(new Runnable() { + public void run() { forceDelivery(sequence); } }); } - else - { + else { ServerMessage forcedDeliveryMessage = new ServerMessageImpl(storageManager.generateID(), 50); forcedDeliveryMessage.putLongProperty(ClientConsumerImpl.FORCED_DELIVERY_MESSAGE, sequence); @@ -548,8 +486,7 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener } } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorSendingForcedDelivery(e); } } @@ -559,46 +496,35 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener public LinkedList cancelRefs(final boolean failed, final boolean lastConsumedAsDelivered, - final Transaction tx) throws Exception - { + final Transaction tx) throws Exception { boolean performACK = lastConsumedAsDelivered; - try - { - if (largeMessageDeliverer != null) - { + try { + if (largeMessageDeliverer != null) { largeMessageDeliverer.finish(); } } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQServerLogger.LOGGER.errorResttingLargeMessage(e, largeMessageDeliverer); } - finally - { + finally { largeMessageDeliverer = null; } LinkedList refs = new LinkedList(); - if (!deliveringRefs.isEmpty()) - { - for (MessageReference ref : deliveringRefs) - { - if (isTrace) - { + if (!deliveringRefs.isEmpty()) { + for (MessageReference ref : deliveringRefs) { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Cancelling reference for messageID = " + ref.getMessage().getMessageID() + ", ref = " + ref); } - if (performACK) - { + if (performACK) { acknowledge(tx, ref.getMessage().getMessageID()); performACK = false; } - else - { - if (!failed) - { + else { + if (!failed) { // We don't decrement delivery count if the client failed, since there's a possibility that refs // were actually delivered but we just didn't get any acks for them // before failure @@ -615,50 +541,40 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener return refs; } - public void setStarted(final boolean started) - { - synchronized (lock) - { + public void setStarted(final boolean started) { + synchronized (lock) { // This is to make sure that the delivery process has finished any pending delivery // otherwise a message may sneak in on the client while we are trying to stop the consumer lockDelivery.writeLock().lock(); - try - { + try { this.started = browseOnly || started; } - finally - { + finally { lockDelivery.writeLock().unlock(); } } // Outside the lock - if (started) - { + if (started) { promptDelivery(); } } - public void setTransferring(final boolean transferring) - { - synchronized (lock) - { + public void setTransferring(final boolean transferring) { + synchronized (lock) { // This is to make sure that the delivery process has finished any pending delivery // otherwise a message may sneak in on the client while we are trying to stop the consumer lockDelivery.writeLock().lock(); - try - { + try { this.transferring = transferring; } - finally - { + finally { lockDelivery.writeLock().unlock(); } } // Outside the lock - if (transferring) - { + if (transferring) { // And we must wait for any force delivery to be executed - this is executed async so we add a future to the // executor and // wait for it to complete @@ -669,24 +585,19 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener boolean ok = future.await(10000); - if (!ok) - { + if (!ok) { ActiveMQServerLogger.LOGGER.errorTransferringConsumer(); } } - if (!transferring) - { + if (!transferring) { promptDelivery(); } } - public void receiveCredits(final int credits) - { - if (credits == -1) - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + public void receiveCredits(final int credits) { + if (credits == -1) { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug(this + ":: FlowControl::Received disable flow control message"); } // No flow control @@ -695,30 +606,25 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener // There may be messages already in the queue promptDelivery(); } - else if (credits == 0) - { + else if (credits == 0) { // reset, used on slow consumers ActiveMQServerLogger.LOGGER.debug(this + ":: FlowControl::Received reset flow control message"); availableCredits.set(0); } - else - { + else { int previous = availableCredits.getAndAdd(credits); - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug(this + "::FlowControl::Received " + - credits + - " credits, previous value = " + - previous + - " currentValue = " + - availableCredits.get()); + credits + + " credits, previous value = " + + previous + + " currentValue = " + + availableCredits.get()); } - if (previous <= 0 && previous + credits > 0) - { - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + if (previous <= 0 && previous + credits > 0) { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace(this + "::calling promptDelivery from receiving credits"); } promptDelivery(); @@ -726,15 +632,12 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener } } - public Queue getQueue() - { + public Queue getQueue() { return messageQueue; } - public void acknowledge(Transaction tx, final long messageID) throws Exception - { - if (browseOnly) - { + public void acknowledge(Transaction tx, final long messageID) throws Exception { + if (browseOnly) { return; } @@ -746,119 +649,95 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener boolean startedTransaction = false; - if (tx == null) - { + if (tx == null) { startedTransaction = true; tx = new TransactionImpl(storageManager); } - try - { + try { MessageReference ref; - do - { + do { ref = deliveringRefs.poll(); - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("ACKing ref " + ref + " on tx= " + tx + ", consumer=" + this); } - if (ref == null) - { + if (ref == null) { throw ActiveMQMessageBundle.BUNDLE.consumerNoReference(id, messageID, messageQueue.getName()); } ref.getQueue().acknowledge(tx, ref); acks++; - } - while (ref.getMessage().getMessageID() != messageID); + } while (ref.getMessage().getMessageID() != messageID); - if (startedTransaction) - { + if (startedTransaction) { tx.commit(); } } - catch (ActiveMQException e) - { - if (startedTransaction) - { + catch (ActiveMQException e) { + if (startedTransaction) { tx.rollback(); } - else - { + else { tx.markAsRollbackOnly(e); } throw e; } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQServerLogger.LOGGER.errorAckingMessage((Exception) e); ActiveMQException activeMQIllegalStateException = new ActiveMQIllegalStateException(e.getMessage()); - if (startedTransaction) - { + if (startedTransaction) { tx.rollback(); } - else - { + else { tx.markAsRollbackOnly(activeMQIllegalStateException); } throw activeMQIllegalStateException; } } - public void individualAcknowledge(final Transaction tx, final long messageID) throws Exception - { - if (browseOnly) - { + public void individualAcknowledge(final Transaction tx, final long messageID) throws Exception { + if (browseOnly) { return; } MessageReference ref = removeReferenceByID(messageID); - if (ref == null) - { + if (ref == null) { throw new IllegalStateException("Cannot find ref to ack " + messageID); } - if (tx == null) - { + if (tx == null) { ref.getQueue().acknowledge(ref); } - else - { + else { ref.getQueue().acknowledge(tx, ref); } acks++; } - public void individualCancel(final long messageID, boolean failed) throws Exception - { - if (browseOnly) - { + public void individualCancel(final long messageID, boolean failed) throws Exception { + if (browseOnly) { return; } MessageReference ref = removeReferenceByID(messageID); - if (ref == null) - { + if (ref == null) { throw new IllegalStateException("Cannot find ref to ack " + messageID); } - if (!failed) - { + if (!failed) { ref.decrementDeliveryCount(); } ref.getQueue().cancel(ref, System.currentTimeMillis()); } - public MessageReference removeReferenceByID(final long messageID) throws Exception - { - if (browseOnly) - { + public MessageReference removeReferenceByID(final long messageID) throws Exception { + if (browseOnly) { return null; } @@ -868,12 +747,10 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener MessageReference ref = null; - while (iter.hasNext()) - { + while (iter.hasNext()) { MessageReference theRef = iter.next(); - if (theRef.getMessage().getMessageID() == messageID) - { + if (theRef.getMessage().getMessageID() == messageID) { iter.remove(); ref = theRef; @@ -885,16 +762,13 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener return ref; } - public void readyForWriting(final boolean ready) - { - if (ready) - { + public void readyForWriting(final boolean ready) { + if (ready) { writeReady.set(true); promptDelivery(); } - else - { + else { writeReady.set(false); } } @@ -902,8 +776,7 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener /** * To be used on tests only */ - public AtomicInteger getAvailableCredits() - { + public AtomicInteger getAvailableCredits() { return availableCredits; } @@ -911,27 +784,22 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener * @see java.lang.Object#toString() */ @Override - public String toString() - { + public String toString() { return "ServerConsumerImpl [id=" + id + ", filter=" + filter + ", binding=" + binding + "]"; } - public String toManagementString() - { + public String toManagementString() { return "ServerConsumer [id=" + getConnectionID() + ":" + getSessionID() + ":" + id + ", filter=" + filter + ", binding=" + binding.toManagementString() + "]"; } @Override - public void disconnect() - { + public void disconnect() { callback.disconnect(this, getQueue().getName().toString()); } - public float getRate() - { + public float getRate() { float timeSlice = ((System.currentTimeMillis() - consumerRateCheckTime.getAndSet(System.currentTimeMillis())) / 1000.0f); - if (timeSlice == 0) - { + if (timeSlice == 0) { messageConsumedSnapshot.getAndSet(acks); return 0.0f; } @@ -940,34 +808,27 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener // Private -------------------------------------------------------------------------------------- - public void promptDelivery() - { + public void promptDelivery() { // largeMessageDeliverer is always set inside a lock // if we don't acquire a lock, we will have NPE eventually - if (largeMessageDeliverer != null) - { + if (largeMessageDeliverer != null) { resumeLargeMessage(); } - else - { + else { forceDelivery(); } } - private void forceDelivery() - { - if (browseOnly) - { + private void forceDelivery() { + if (browseOnly) { messageQueue.getExecutor().execute(browserDeliverer); } - else - { + else { messageQueue.deliverAsync(); } } - private void resumeLargeMessage() - { + private void resumeLargeMessage() { messageQueue.getExecutor().execute(resumeLargeMessageRunnable); } @@ -975,20 +836,17 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener * @param ref * @param message */ - private void deliverStandardMessage(final MessageReference ref, final ServerMessage message) - { + private void deliverStandardMessage(final MessageReference ref, final ServerMessage message) { int packetSize = callback.sendMessage(message, ServerConsumerImpl.this, ref.getDeliveryCount()); - if (availableCredits != null) - { + if (availableCredits != null) { availableCredits.addAndGet(-packetSize); - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace(this + "::FlowControl::delivery standard taking " + - packetSize + - " from credits, available now is " + - availableCredits); + packetSize + + " from credits, available now is " + + availableCredits); } } } @@ -996,21 +854,15 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener // Inner classes // ------------------------------------------------------------------------ - private final Runnable resumeLargeMessageRunnable = new Runnable() - { - public void run() - { - synchronized (lock) - { - try - { - if (largeMessageDeliverer == null || largeMessageDeliverer.deliver()) - { + private final Runnable resumeLargeMessageRunnable = new Runnable() { + public void run() { + synchronized (lock) { + try { + if (largeMessageDeliverer == null || largeMessageDeliverer.deliver()) { forceDelivery(); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorRunningLargeMessageDeliverer(e); } } @@ -1021,8 +873,8 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener * Internal encapsulation of the logic on sending LargeMessages. * This Inner class was created to avoid a bunch of loose properties about the current LargeMessage being sent */ - private final class LargeMessageDeliverer - { + private final class LargeMessageDeliverer { + private long sizePendingLargeMessage; private LargeServerMessage largeMessage; @@ -1038,8 +890,7 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener private BodyEncoder context; - public LargeMessageDeliverer(final LargeServerMessage message, final MessageReference ref) throws Exception - { + public LargeMessageDeliverer(final LargeServerMessage message, final MessageReference ref) throws Exception { largeMessage = message; largeMessage.incrementDelayDeletionCount(); @@ -1047,29 +898,23 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener this.ref = ref; } - public boolean deliver() throws Exception - { + public boolean deliver() throws Exception { lockDelivery.readLock().lock(); - try - { - if (largeMessage == null) - { + try { + if (largeMessage == null) { return true; } - if (availableCredits != null && availableCredits.get() <= 0) - { - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + if (availableCredits != null && availableCredits.get() <= 0) { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace(this + "::FlowControl::delivery largeMessage interrupting as there are no more credits, available=" + - availableCredits); + availableCredits); } return false; } - if (!sentInitialPacket) - { + if (!sentInitialPacket) { context = largeMessage.getBodyEncoder(); sizePendingLargeMessage = context.getLargeBodySize(); @@ -1078,22 +923,17 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener sentInitialPacket = true; - int packetSize = callback.sendLargeMessage(largeMessage, - ServerConsumerImpl.this, - context.getLargeBodySize(), - ref.getDeliveryCount()); + int packetSize = callback.sendLargeMessage(largeMessage, ServerConsumerImpl.this, context.getLargeBodySize(), ref.getDeliveryCount()); - if (availableCredits != null) - { + if (availableCredits != null) { availableCredits.addAndGet(-packetSize); - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace(this + "::FlowControl::" + - " deliver initialpackage with " + - packetSize + - " delivered, available now = " + - availableCredits); + " deliver initialpackage with " + + packetSize + + " delivered, available now = " + + availableCredits); } } @@ -1104,14 +944,11 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener return false; } - else - { - if (availableCredits != null && availableCredits.get() <= 0) - { - if (ServerConsumerImpl.isTrace) - { + else { + if (availableCredits != null && availableCredits.get() <= 0) { + if (ServerConsumerImpl.isTrace) { ActiveMQServerLogger.LOGGER.trace(this + "::FlowControl::deliverLargeMessage Leaving loop of send LargeMessage because of credits, available=" + - availableCredits); + availableCredits); } return false; @@ -1127,38 +964,31 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener byte[] body = bodyBuffer.toByteBuffer().array(); - int packetSize = callback.sendLargeMessageContinuation(ServerConsumerImpl.this, - body, - positionPendingLargeMessage + localChunkLen < sizePendingLargeMessage, - false); + int packetSize = callback.sendLargeMessageContinuation(ServerConsumerImpl.this, body, positionPendingLargeMessage + localChunkLen < sizePendingLargeMessage, false); int chunkLen = body.length; - if (availableCredits != null) - { + if (availableCredits != null) { availableCredits.addAndGet(-packetSize); - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace(this + "::FlowControl::largeMessage deliver continuation, packetSize=" + - packetSize + - " available now=" + - availableCredits); + packetSize + + " available now=" + + availableCredits); } } positionPendingLargeMessage += chunkLen; - if (positionPendingLargeMessage < sizePendingLargeMessage) - { + if (positionPendingLargeMessage < sizePendingLargeMessage) { resumeLargeMessage(); return false; } } - if (ServerConsumerImpl.isTrace) - { + if (ServerConsumerImpl.isTrace) { ActiveMQServerLogger.LOGGER.trace("Finished deliverLargeMessage"); } @@ -1166,25 +996,20 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener return true; } - finally - { + finally { lockDelivery.readLock().unlock(); } } - public void finish() throws Exception - { - synchronized (lock) - { - if (largeMessage == null) - { + public void finish() throws Exception { + synchronized (lock) { + if (largeMessage == null) { // handleClose could be calling close while handle is also calling finish. // As a result one of them could get here after the largeMessage is already gone. // On that case we just ignore this call return; } - if (context != null) - { + if (context != null) { context.close(); } @@ -1192,8 +1017,7 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener largeMessage.decrementDelayDeletionCount(); - if (preAcknowledge && !browseOnly) - { + if (preAcknowledge && !browseOnly) { // PreAck will have an extra reference largeMessage.decrementDelayDeletionCount(); } @@ -1205,45 +1029,37 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener } } - protected class BrowserDeliverer implements Runnable - { + protected class BrowserDeliverer implements Runnable { + protected MessageReference current = null; - public BrowserDeliverer(final LinkedListIterator iterator) - { + public BrowserDeliverer(final LinkedListIterator iterator) { this.iterator = iterator; } public final LinkedListIterator iterator; - public synchronized void close() - { + public synchronized void close() { iterator.close(); } - public synchronized void run() - { + public synchronized void run() { // if the reference was busy during the previous iteration, handle it now - if (current != null) - { - try - { + if (current != null) { + try { HandleStatus status = handle(current); - if (status == HandleStatus.BUSY) - { + if (status == HandleStatus.BUSY) { return; } - if (status == HandleStatus.HANDLED) - { + if (status == HandleStatus.HANDLED) { proceedDeliver(current); } current = null; } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorBrowserHandlingMessage(e, current); return; } @@ -1252,15 +1068,11 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener MessageReference ref = null; HandleStatus status; - while (true) - { - try - { + while (true) { + try { ref = null; - synchronized (messageQueue) - { - if (!iterator.hasNext()) - { + synchronized (messageQueue) { + if (!iterator.hasNext()) { break; } @@ -1269,28 +1081,24 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener status = handle(ref); } - if (status == HandleStatus.HANDLED) - { + if (status == HandleStatus.HANDLED) { proceedDeliver(ref); } - else if (status == HandleStatus.BUSY) - { + else if (status == HandleStatus.BUSY) { // keep a reference on the current message reference // to handle it next time the browser deliverer is executed current = ref; break; } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorBrowserHandlingMessage(e, ref); break; } } } - public boolean isBrowsed() - { + public boolean isBrowsed() { messageQueue.deliverAsync(); boolean b = !iterator.hasNext(); return b; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ServerInfo.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ServerInfo.java index 850c16f0fb..fce327e227 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ServerInfo.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ServerInfo.java @@ -26,22 +26,20 @@ import org.apache.activemq.artemis.core.paging.PagingStore; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.utils.SizeFormatterUtil; -public class ServerInfo -{ +public class ServerInfo { + private final ActiveMQServer server; private final PagingManager pagingManager; - public ServerInfo(final ActiveMQServer server, final PagingManager pagingManager) - { + public ServerInfo(final ActiveMQServer server, final PagingManager pagingManager) { this.server = server; this.pagingManager = pagingManager; } // Public -------------------------------------------------------- - public String dump() - { + public String dump() { long maxMemory = Runtime.getRuntime().maxMemory(); long totalMemory = Runtime.getRuntime().totalMemory(); long freeMemory = Runtime.getRuntime().freeMemory(); @@ -62,23 +60,16 @@ public class ServerInfo return info.toString(); } - private String appendPagingInfos() - { + private String appendPagingInfos() { StringBuilder info = new StringBuilder(); - for (SimpleString storeName : pagingManager.getStoreNames()) - { + for (SimpleString storeName : pagingManager.getStoreNames()) { PagingStore pageStore; - try - { + try { pageStore = pagingManager.getPageStore(storeName); - info.append(String.format("\t%s: %s%n", - storeName, - SizeFormatterUtil.sizeof(pageStore.getPageSizeBytes() * - pageStore.getNumberOfPages()))); + info.append(String.format("\t%s: %s%n", storeName, SizeFormatterUtil.sizeof(pageStore.getPageSizeBytes() * pageStore.getNumberOfPages()))); } - catch (Exception e) - { + catch (Exception e) { info.append(String.format("\t%s: %s%n", storeName, e.getMessage())); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ServerMessageImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ServerMessageImpl.java index e6c2efb203..8485b51b6c 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ServerMessageImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ServerMessageImpl.java @@ -30,8 +30,7 @@ import org.apache.activemq.artemis.utils.DataConstants; import org.apache.activemq.artemis.utils.MemorySize; import org.apache.activemq.artemis.utils.TypedProperties; -public class ServerMessageImpl extends MessageImpl implements ServerMessage -{ +public class ServerMessageImpl extends MessageImpl implements ServerMessage { private final AtomicInteger durableRefCount = new AtomicInteger(); @@ -43,20 +42,16 @@ public class ServerMessageImpl extends MessageImpl implements ServerMessage private boolean persisted = false; - - static - { + static { // This is an estimate of how much memory a ServerMessageImpl takes up, exclusing body and properties // Note, it is only an estimate, it's not possible to be entirely sure with Java // This figure is calculated using the test utilities in org.apache.activemq.tests.unit.util.sizeof // The value is somewhat higher on 64 bit architectures, probably due to different alignment - if (MemorySize.is64bitArch()) - { + if (MemorySize.is64bitArch()) { memoryOffset = 352; } - else - { + else { memoryOffset = 232; } } @@ -64,15 +59,13 @@ public class ServerMessageImpl extends MessageImpl implements ServerMessage /* * Constructor for when reading from network */ - public ServerMessageImpl() - { + public ServerMessageImpl() { } /* * Construct a MessageImpl from storage, or notification, or before routing */ - public ServerMessageImpl(final long messageID, final int initialMessageBufferSize) - { + public ServerMessageImpl(final long messageID, final int initialMessageBufferSize) { super(initialMessageBufferSize); this.messageID = messageID; @@ -81,55 +74,44 @@ public class ServerMessageImpl extends MessageImpl implements ServerMessage /* * Copy constructor */ - protected ServerMessageImpl(final ServerMessageImpl other) - { + protected ServerMessageImpl(final ServerMessageImpl other) { super(other); } /* * Copy constructor */ - protected ServerMessageImpl(final ServerMessageImpl other, TypedProperties properties) - { + protected ServerMessageImpl(final ServerMessageImpl other, TypedProperties properties) { super(other, properties); } - public boolean isServerMessage() - { + public boolean isServerMessage() { return true; } - public ServerMessageImpl setMessageID(final long id) - { + public ServerMessageImpl setMessageID(final long id) { messageID = id; return this; } - public MessageReference createReference(final Queue queue) - { + public MessageReference createReference(final Queue queue) { MessageReference ref = new MessageReferenceImpl(this, queue); return ref; } - - public boolean hasInternalProperties() - { + public boolean hasInternalProperties() { return properties.hasInternalProperties(); } - public int incrementRefCount() throws Exception - { + public int incrementRefCount() throws Exception { int count = refCount.incrementAndGet(); - if (pagingStore != null) - { - if (count == 1) - { + if (pagingStore != null) { + if (count == 1) { pagingStore.addSize(getMemoryEstimate() + MessageReferenceImpl.getMemoryEstimate()); } - else - { + else { pagingStore.addSize(MessageReferenceImpl.getMemoryEstimate()); } } @@ -137,24 +119,19 @@ public class ServerMessageImpl extends MessageImpl implements ServerMessage return count; } - public int decrementRefCount() throws Exception - { + public int decrementRefCount() throws Exception { int count = refCount.decrementAndGet(); - if (pagingStore != null) - { - if (count == 0) - { + if (pagingStore != null) { + if (count == 0) { pagingStore.addSize(-getMemoryEstimate() - MessageReferenceImpl.getMemoryEstimate()); - if (buffer != null) - { + if (buffer != null) { // release the buffer now buffer.byteBuf().release(); } } - else - { + else { pagingStore.addSize(-MessageReferenceImpl.getMemoryEstimate()); } } @@ -162,40 +139,33 @@ public class ServerMessageImpl extends MessageImpl implements ServerMessage return count; } - public int incrementDurableRefCount() - { + public int incrementDurableRefCount() { return durableRefCount.incrementAndGet(); } - public int decrementDurableRefCount() - { + public int decrementDurableRefCount() { return durableRefCount.decrementAndGet(); } - public int getRefCount() - { + public int getRefCount() { return refCount.get(); } - public boolean isLargeMessage() - { + public boolean isLargeMessage() { return false; } private volatile int memoryEstimate = -1; - public int getMemoryEstimate() - { - if (memoryEstimate == -1) - { + public int getMemoryEstimate() { + if (memoryEstimate == -1) { memoryEstimate = ServerMessageImpl.memoryOffset + buffer.capacity() + properties.getMemoryOffset(); } return memoryEstimate; } - public ServerMessage copy(final long newID) - { + public ServerMessage copy(final long newID) { ServerMessage m = new ServerMessageImpl(this); m.setMessageID(newID); @@ -203,25 +173,24 @@ public class ServerMessageImpl extends MessageImpl implements ServerMessage return m; } - public void finishCopy() throws Exception - { + public void finishCopy() throws Exception { } - public ServerMessage copy() - { + public ServerMessage copy() { // This is a simple copy, used only to avoid changing original properties return new ServerMessageImpl(this); } - public ServerMessage makeCopyForExpiryOrDLA(final long newID, MessageReference originalReference, - final boolean expiry) throws Exception - { + public ServerMessage makeCopyForExpiryOrDLA(final long newID, + MessageReference originalReference, + final boolean expiry) throws Exception { return makeCopyForExpiryOrDLA(newID, originalReference, expiry, true); } - public ServerMessage makeCopyForExpiryOrDLA(final long newID, MessageReference originalReference, - final boolean expiry, final boolean copyOriginalHeaders) throws Exception - { + public ServerMessage makeCopyForExpiryOrDLA(final long newID, + MessageReference originalReference, + final boolean expiry, + final boolean copyOriginalHeaders) throws Exception { /* We copy the message and send that to the dla/expiry queue - this is because otherwise we may end up with a ref with the same message id in the @@ -234,8 +203,7 @@ public class ServerMessageImpl extends MessageImpl implements ServerMessage ServerMessage copy = copy(newID); copy.finishCopy(); - if (copyOriginalHeaders) - { + if (copyOriginalHeaders) { copy.setOriginalHeaders(this, originalReference, expiry); } @@ -243,38 +211,33 @@ public class ServerMessageImpl extends MessageImpl implements ServerMessage } @Override - public void setOriginalHeaders(final ServerMessage other, final MessageReference originalReference, final boolean expiry) - { + public void setOriginalHeaders(final ServerMessage other, + final MessageReference originalReference, + final boolean expiry) { SimpleString originalQueue = other.getSimpleStringProperty(Message.HDR_ORIGINAL_QUEUE); - if (originalQueue != null) - { + if (originalQueue != null) { putStringProperty(Message.HDR_ORIGINAL_QUEUE, originalQueue); } - else if (originalReference != null) - { + else if (originalReference != null) { putStringProperty(Message.HDR_ORIGINAL_QUEUE, originalReference.getQueue().getName()); } - if (other.containsProperty(Message.HDR_ORIG_MESSAGE_ID)) - { + if (other.containsProperty(Message.HDR_ORIG_MESSAGE_ID)) { putStringProperty(Message.HDR_ORIGINAL_ADDRESS, other.getSimpleStringProperty(Message.HDR_ORIGINAL_ADDRESS)); putLongProperty(Message.HDR_ORIG_MESSAGE_ID, other.getLongProperty(Message.HDR_ORIG_MESSAGE_ID)); } - else - { + else { putStringProperty(Message.HDR_ORIGINAL_ADDRESS, other.getAddress()); - putLongProperty(Message.HDR_ORIG_MESSAGE_ID, other.getMessageID()); } // reset expiry setExpiration(0); - if (expiry) - { + if (expiry) { long actualExpiryTime = System.currentTimeMillis(); putLongProperty(Message.HDR_ACTUAL_EXPIRY_TIME, actualExpiryTime); @@ -283,8 +246,7 @@ public class ServerMessageImpl extends MessageImpl implements ServerMessage bufferValid = false; } - public void setPagingStore(final PagingStore pagingStore) - { + public void setPagingStore(final PagingStore pagingStore) { this.pagingStore = pagingStore; // On the server side, we reset the address to point to the instance of address in the paging store @@ -292,88 +254,71 @@ public class ServerMessageImpl extends MessageImpl implements ServerMessage address = pagingStore.getAddress(); } - public synchronized void forceAddress(final SimpleString address) - { + public synchronized void forceAddress(final SimpleString address) { this.address = address; bufferValid = false; } - public PagingStore getPagingStore() - { + public PagingStore getPagingStore() { return pagingStore; } - public boolean storeIsPaging() - { - if (pagingStore != null) - { + public boolean storeIsPaging() { + if (pagingStore != null) { return pagingStore.isPaging(); } - else - { + else { return false; } } @Override - public String toString() - { + public String toString() { return "ServerMessage[messageID=" + messageID + ",durable=" + isDurable() + ",userID=" + getUserID() + ",priority=" + this.getPriority() + ", bodySize=" + this.getBodyBufferCopy().capacity() + ", timestamp=" + toDate(getTimestamp()) + ",expiration=" + toDate(getExpiration()) + ", durable=" + durable + ", address=" + getAddress() + ",properties=" + properties.toString() + "]@" + System.identityHashCode(this); } - private static String toDate(long timestamp) - { - if (timestamp == 0) - { + private static String toDate(long timestamp) { + if (timestamp == 0) { return "0"; } - else - { + else { return new java.util.Date(timestamp).toString(); } } - public InputStream getBodyInputStream() - { + public InputStream getBodyInputStream() { return null; } // Encoding stuff - public void encodeMessageIDToBuffer() - { + public void encodeMessageIDToBuffer() { // We first set the message id - this needs to be set on the buffer since this buffer will be re-used buffer.setLong(buffer.getInt(MessageImpl.BUFFER_HEADER_SPACE) + DataConstants.SIZE_INT, messageID); } @Override - public byte[] getDuplicateIDBytes() - { + public byte[] getDuplicateIDBytes() { Object duplicateID = getDuplicateProperty(); - if (duplicateID == null) - { + if (duplicateID == null) { return null; } - else - { - if (duplicateID instanceof SimpleString) - { + else { + if (duplicateID instanceof SimpleString) { return ((SimpleString) duplicateID).getData(); } - else - { + else { return (byte[]) duplicateID; } } } - public Object getDuplicateProperty() - { + public Object getDuplicateProperty() { return getObjectProperty(Message.HDR_DUPLICATE_DETECTION_ID); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ServerSessionImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ServerSessionImpl.java index 118b7dffb6..d9f65a91f2 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ServerSessionImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ServerSessionImpl.java @@ -89,8 +89,7 @@ import org.apache.activemq.artemis.utils.json.JSONObject; /** * Server side Session implementation */ -public class ServerSessionImpl implements ServerSession, FailureListener -{ +public class ServerSessionImpl implements ServerSession, FailureListener { // Constants ----------------------------------------------------------------------------- private static final boolean isTrace = ActiveMQServerLogger.LOGGER.isTraceEnabled(); @@ -175,8 +174,7 @@ public class ServerSessionImpl implements ServerSession, FailureListener //create an 'empty' session. Only used by AMQServerSession //in order to check username and password - protected ServerSessionImpl(String username, String password) - { + protected ServerSessionImpl(String username, String password) { this.username = username; this.password = password; @@ -218,14 +216,8 @@ public class ServerSessionImpl implements ServerSession, FailureListener final SimpleString defaultAddress, final SessionCallback callback, final OperationContext context, - final QueueCreator queueCreator) throws Exception - { - this(name, username, password, minLargeMessageSize, - autoCommitSends, autoCommitAcks, preAcknowledge, - strictUpdateDeliveryCount, xa, remotingConnection, - storageManager, postOffice, resourceManager, securityStore, - managementService, server, managementAddress, defaultAddress, - callback, context, null, queueCreator); + final QueueCreator queueCreator) throws Exception { + this(name, username, password, minLargeMessageSize, autoCommitSends, autoCommitAcks, preAcknowledge, strictUpdateDeliveryCount, xa, remotingConnection, storageManager, postOffice, resourceManager, securityStore, managementService, server, managementAddress, defaultAddress, callback, context, null, queueCreator); } public ServerSessionImpl(final String name, @@ -249,8 +241,7 @@ public class ServerSessionImpl implements ServerSession, FailureListener final SessionCallback callback, final OperationContext context, TransactionFactory transactionFactory, - final QueueCreator queueCreator) throws Exception - { + final QueueCreator queueCreator) throws Exception { this.username = username; this.password = password; @@ -295,17 +286,14 @@ public class ServerSessionImpl implements ServerSession, FailureListener this.queueCreator = queueCreator; - if (transactionFactory == null) - { + if (transactionFactory == null) { this.transactionFactory = new DefaultTransactionFactory(); } - else - { + else { this.transactionFactory = transactionFactory; } - if (!xa) - { + if (!xa) { tx = newTransaction(); } } @@ -315,63 +303,51 @@ public class ServerSessionImpl implements ServerSession, FailureListener /** * @return the sessionContext */ - public OperationContext getSessionContext() - { + public OperationContext getSessionContext() { return context; } - public String getUsername() - { + public String getUsername() { return username; } - public String getPassword() - { + public String getPassword() { return password; } - public int getMinLargeMessageSize() - { + public int getMinLargeMessageSize() { return minLargeMessageSize; } - public String getName() - { + public String getName() { return name; } - public Object getConnectionID() - { + public Object getConnectionID() { return remotingConnection.getID(); } - public Set getServerConsumers() - { + public Set getServerConsumers() { Set consumersClone = new HashSet(consumers.values()); return Collections.unmodifiableSet(consumersClone); } - public boolean removeConsumer(final long consumerID) throws Exception - { + public boolean removeConsumer(final long consumerID) throws Exception { return consumers.remove(consumerID) != null; } - protected void doClose(final boolean failed) throws Exception - { - synchronized (this) - { - if (closed) return; + protected void doClose(final boolean failed) throws Exception { + synchronized (this) { + if (closed) + return; - if (tx != null && tx.getXid() == null) - { + if (tx != null && tx.getXid() == null) { // We only rollback local txs on close, not XA tx branches - try - { + try { rollback(failed, false); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e); } } @@ -381,21 +357,16 @@ public class ServerSessionImpl implements ServerSession, FailureListener //https://issues.jboss.org/browse/HORNETQ-1141 Set consumersClone = new HashSet(consumers.values()); - for (ServerConsumer consumer : consumersClone) - { - try - { + for (ServerConsumer consumer : consumersClone) { + try { consumer.close(failed); } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e); - try - { + try { consumer.removeItself(); } - catch (Throwable e2) - { + catch (Throwable e2) { ActiveMQServerLogger.LOGGER.warn(e2.getMessage(), e2); } } @@ -403,21 +374,16 @@ public class ServerSessionImpl implements ServerSession, FailureListener consumers.clear(); - if (currentLargeMessage != null) - { - try - { + if (currentLargeMessage != null) { + try { currentLargeMessage.deleteFile(); } - catch (Throwable error) - { + catch (Throwable error) { ActiveMQServerLogger.LOGGER.errorDeletingLargeMessageFile(error); } } - - synchronized (this) - { + synchronized (this) { server.removeSession(name); remotingConnection.removeFailureListener(this); @@ -428,18 +394,14 @@ public class ServerSessionImpl implements ServerSession, FailureListener } } - - - public QueueCreator getQueueCreator() - { + public QueueCreator getQueueCreator() { return queueCreator; } public ServerConsumer createConsumer(final long consumerID, final SimpleString queueName, final SimpleString filterString, - final boolean browseOnly) throws Exception - { + final boolean browseOnly) throws Exception { return this.createConsumer(consumerID, queueName, filterString, browseOnly, true, null); } @@ -448,12 +410,10 @@ public class ServerSessionImpl implements ServerSession, FailureListener final SimpleString filterString, final boolean browseOnly, final boolean supportLargeMessage, - final Integer credits) throws Exception - { + final Integer credits) throws Exception { Binding binding = postOffice.getBinding(queueName); - if (binding == null || binding.getType() != BindingType.LOCAL_QUEUE) - { + if (binding == null || binding.getType() != BindingType.LOCAL_QUEUE) { throw ActiveMQMessageBundle.BUNDLE.noSuchQueue(queueName); } @@ -461,23 +421,10 @@ public class ServerSessionImpl implements ServerSession, FailureListener Filter filter = FilterImpl.createFilter(filterString); - ServerConsumer consumer = newConsumer(consumerID, - this, - (QueueBinding) binding, - filter, - started, - browseOnly, - storageManager, - callback, - preAcknowledge, - strictUpdateDeliveryCount, - managementService, - supportLargeMessage, - credits); + ServerConsumer consumer = newConsumer(consumerID, this, (QueueBinding) binding, filter, started, browseOnly, storageManager, callback, preAcknowledge, strictUpdateDeliveryCount, managementService, supportLargeMessage, credits); consumers.put(consumer.getID(), consumer); - if (!browseOnly) - { + if (!browseOnly) { TypedProperties props = new TypedProperties(); props.putSimpleStringProperty(ManagementHelper.HDR_ADDRESS, binding.getAddress()); @@ -499,19 +446,17 @@ public class ServerSessionImpl implements ServerSession, FailureListener props.putSimpleStringProperty(ManagementHelper.HDR_SESSION_NAME, SimpleString.toSimpleString(name)); - if (filterString != null) - { + if (filterString != null) { props.putSimpleStringProperty(ManagementHelper.HDR_FILTERSTRING, filterString); } Notification notification = new Notification(null, CoreNotificationType.CONSUMER_CREATED, props); - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Session with user=" + username + - ", connection=" + this.remotingConnection + - " created a consumer on queue " + queueName + - ", filter = " + filterString); + ", connection=" + this.remotingConnection + + " created a consumer on queue " + queueName + + ", filter = " + filterString); } managementService.sendNotification(notification); @@ -521,60 +466,47 @@ public class ServerSessionImpl implements ServerSession, FailureListener } protected ServerConsumer newConsumer(long consumerID, - ServerSessionImpl serverSessionImpl, QueueBinding binding, - Filter filter, boolean started2, boolean browseOnly, - StorageManager storageManager2, SessionCallback callback2, - boolean preAcknowledge2, boolean strictUpdateDeliveryCount2, - ManagementService managementService2, boolean supportLargeMessage, - Integer credits) throws Exception - { - return new ServerConsumerImpl(consumerID, - this, - (QueueBinding) binding, - filter, - started, - browseOnly, - storageManager, - callback, - preAcknowledge, - strictUpdateDeliveryCount, - managementService, - supportLargeMessage, - credits); + ServerSessionImpl serverSessionImpl, + QueueBinding binding, + Filter filter, + boolean started2, + boolean browseOnly, + StorageManager storageManager2, + SessionCallback callback2, + boolean preAcknowledge2, + boolean strictUpdateDeliveryCount2, + ManagementService managementService2, + boolean supportLargeMessage, + Integer credits) throws Exception { + return new ServerConsumerImpl(consumerID, this, (QueueBinding) binding, filter, started, browseOnly, storageManager, callback, preAcknowledge, strictUpdateDeliveryCount, managementService, supportLargeMessage, credits); } public Queue createQueue(final SimpleString address, - final SimpleString name, - final SimpleString filterString, - final boolean temporary, - final boolean durable) throws Exception - { - if (durable) - { + final SimpleString name, + final SimpleString filterString, + final boolean temporary, + final boolean durable) throws Exception { + if (durable) { // make sure the user has privileges to create this queue securityStore.check(address, CheckType.CREATE_DURABLE_QUEUE, this); } - else - { + else { securityStore.check(address, CheckType.CREATE_NON_DURABLE_QUEUE, this); } - ((ActiveMQServerImpl)server).checkQueueCreationLimit(getUsername()); + ((ActiveMQServerImpl) server).checkQueueCreationLimit(getUsername()); Queue queue; // any non-temporary JMS queue created via this method should be marked as auto-created - if (!temporary && address.toString().startsWith(ResourceNames.JMS_QUEUE) && address.equals(name)) - { + if (!temporary && address.toString().startsWith(ResourceNames.JMS_QUEUE) && address.equals(name)) { queue = server.createQueue(address, name, filterString, SimpleString.toSimpleString(getUsername()), durable, temporary, true); } - else - { + else { queue = server.createQueue(address, name, filterString, SimpleString.toSimpleString(getUsername()), durable, temporary); } - if (temporary) - { + if (temporary) { // Temporary queue in core simply means the queue will be deleted if // the remoting connection // dies. It does not mean it will get deleted automatically when the @@ -589,11 +521,10 @@ public class ServerSessionImpl implements ServerSession, FailureListener tempQueueCleannerUppers.put(name, cleaner); } - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Queue " + name + " created on address " + address + - " with filter=" + filterString + " temporary = " + - temporary + " durable=" + durable + " on session user=" + this.username + ", connection=" + this.remotingConnection); + " with filter=" + filterString + " temporary = " + + temporary + " durable=" + durable + " on session user=" + this.username + ", connection=" + this.remotingConnection); } return queue; @@ -604,87 +535,72 @@ public class ServerSessionImpl implements ServerSession, FailureListener public void createSharedQueue(final SimpleString address, final SimpleString name, boolean durable, - final SimpleString filterString) throws Exception - { + final SimpleString filterString) throws Exception { securityStore.check(address, CheckType.CREATE_NON_DURABLE_QUEUE, this); - ((ActiveMQServerImpl)server).checkQueueCreationLimit(getUsername()); + ((ActiveMQServerImpl) server).checkQueueCreationLimit(getUsername()); server.createSharedQueue(address, name, filterString, SimpleString.toSimpleString(getUsername()), durable); } - public RemotingConnection getRemotingConnection() - { + public RemotingConnection getRemotingConnection() { return remotingConnection; } - public static class TempQueueCleanerUpper implements CloseListener, FailureListener - { + public static class TempQueueCleanerUpper implements CloseListener, FailureListener { + private final SimpleString bindingName; private final ActiveMQServer server; - public TempQueueCleanerUpper(final ActiveMQServer server, final SimpleString bindingName) - { + public TempQueueCleanerUpper(final ActiveMQServer server, final SimpleString bindingName) { this.server = server; this.bindingName = bindingName; } - private void run() - { - try - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + private void run() { + try { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("deleting temporary queue " + bindingName); } - try - { + try { server.destroyQueue(bindingName, null, false); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { // that's fine.. it can happen due to queue already been deleted ActiveMQServerLogger.LOGGER.debug(e.getMessage(), e); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorRemovingTempQueue(e, bindingName); } } - public void connectionFailed(ActiveMQException exception, boolean failedOver) - { + public void connectionFailed(ActiveMQException exception, boolean failedOver) { run(); } @Override - public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) { connectionFailed(me, failedOver); } - public void connectionClosed() - { + public void connectionClosed() { run(); } @Override - public String toString() - { + public String toString() { return "Temporary Cleaner for queue " + bindingName; } } - public void deleteQueue(final SimpleString queueToDelete) throws Exception - { + public void deleteQueue(final SimpleString queueToDelete) throws Exception { Binding binding = postOffice.getBinding(queueToDelete); - if (binding == null || binding.getType() != BindingType.LOCAL_QUEUE) - { + if (binding == null || binding.getType() != BindingType.LOCAL_QUEUE) { throw new ActiveMQNonExistentQueueException(); } @@ -692,20 +608,17 @@ public class ServerSessionImpl implements ServerSession, FailureListener TempQueueCleanerUpper cleaner = this.tempQueueCleannerUppers.remove(queueToDelete); - if (cleaner != null) - { + if (cleaner != null) { remotingConnection.removeCloseListener(cleaner); remotingConnection.removeFailureListener(cleaner); } } - public QueueQueryResult executeQueueQuery(final SimpleString name) throws Exception - { + public QueueQueryResult executeQueueQuery(final SimpleString name) throws Exception { boolean autoCreateJmsQueues = name.toString().startsWith(ResourceNames.JMS_QUEUE) && server.getAddressSettingsRepository().getMatch(name.toString()).isAutoCreateJmsQueues(); - if (name == null) - { + if (name == null) { throw ActiveMQMessageBundle.BUNDLE.queueNameIsNull(); } @@ -713,63 +626,47 @@ public class ServerSessionImpl implements ServerSession, FailureListener Binding binding = postOffice.getBinding(name); - if (binding != null && binding.getType() == BindingType.LOCAL_QUEUE) - { + if (binding != null && binding.getType() == BindingType.LOCAL_QUEUE) { Queue queue = (Queue) binding.getBindable(); Filter filter = queue.getFilter(); SimpleString filterString = filter == null ? null : filter.getFilterString(); - response = new QueueQueryResult(name, - binding.getAddress(), - queue.isDurable(), - queue.isTemporary(), - filterString, - queue.getConsumerCount(), - queue.getMessageCount(), - autoCreateJmsQueues); + response = new QueueQueryResult(name, binding.getAddress(), queue.isDurable(), queue.isTemporary(), filterString, queue.getConsumerCount(), queue.getMessageCount(), autoCreateJmsQueues); } // make an exception for the management address (see HORNETQ-29) - else if (name.equals(managementAddress)) - { + else if (name.equals(managementAddress)) { response = new QueueQueryResult(name, managementAddress, true, false, null, -1, -1, autoCreateJmsQueues); } - else if (autoCreateJmsQueues) - { + else if (autoCreateJmsQueues) { response = new QueueQueryResult(name, name, true, false, null, 0, 0, true, false); } - else - { + else { response = new QueueQueryResult(null, null, false, false, null, 0, 0, false, false); } return response; } - public BindingQueryResult executeBindingQuery(final SimpleString address) throws Exception - { + public BindingQueryResult executeBindingQuery(final SimpleString address) throws Exception { boolean autoCreateJmsQueues = address.toString().startsWith(ResourceNames.JMS_QUEUE) && server.getAddressSettingsRepository().getMatch(address.toString()).isAutoCreateJmsQueues(); - if (address == null) - { + if (address == null) { throw ActiveMQMessageBundle.BUNDLE.addressIsNull(); } List names = new ArrayList(); // make an exception for the management address (see HORNETQ-29) - if (address.equals(managementAddress)) - { + if (address.equals(managementAddress)) { return new BindingQueryResult(true, names, autoCreateJmsQueues); } Bindings bindings = postOffice.getMatchingBindings(address); - for (Binding binding : bindings.getBindings()) - { - if (binding.getType() == BindingType.LOCAL_QUEUE || binding.getType() == BindingType.REMOTE_QUEUE) - { + for (Binding binding : bindings.getBindings()) { + if (binding.getType() == BindingType.LOCAL_QUEUE || binding.getType() == BindingType.REMOTE_QUEUE) { names.add(binding.getUniqueName()); } } @@ -777,40 +674,32 @@ public class ServerSessionImpl implements ServerSession, FailureListener return new BindingQueryResult(!names.isEmpty(), names, autoCreateJmsQueues); } - public void forceConsumerDelivery(final long consumerID, final long sequence) throws Exception - { + public void forceConsumerDelivery(final long consumerID, final long sequence) throws Exception { ServerConsumer consumer = consumers.get(consumerID); // this would be possible if the server consumer was closed by pings/pongs.. etc - if (consumer != null) - { + if (consumer != null) { consumer.forceDelivery(sequence); } } - - public void promptDelivery(long consumerID) - { + public void promptDelivery(long consumerID) { ServerConsumer consumer = consumers.get(consumerID); // this would be possible if the server consumer was closed by pings/pongs.. etc - if (consumer != null) - { + if (consumer != null) { consumer.promptDelivery(); } } - public void acknowledge(final long consumerID, final long messageID) throws Exception - { + public void acknowledge(final long consumerID, final long messageID) throws Exception { ServerConsumer consumer = consumers.get(consumerID); - if (consumer == null) - { + if (consumer == null) { throw ActiveMQMessageBundle.BUNDLE.consumerDoesntExist(consumerID); } - if (tx != null && tx.getState() == State.ROLLEDBACK) - { + if (tx != null && tx.getState() == State.ROLLEDBACK) { // JBPAPP-8845 - if we let stuff to be acked on a rolled back TX, we will just // have these messages to be stuck on the limbo until the server is restarted // The tx has already timed out, so we need to ack and rollback immediately @@ -818,18 +707,15 @@ public class ServerSessionImpl implements ServerSession, FailureListener consumer.acknowledge(newTX, messageID); newTX.rollback(); } - else - { + else { consumer.acknowledge(autoCommitAcks ? null : tx, messageID); } } - public void individualAcknowledge(final long consumerID, final long messageID) throws Exception - { + public void individualAcknowledge(final long consumerID, final long messageID) throws Exception { ServerConsumer consumer = consumers.get(consumerID); - if (tx != null && tx.getState() == State.ROLLEDBACK) - { + if (tx != null && tx.getState() == State.ROLLEDBACK) { // JBPAPP-8845 - if we let stuff to be acked on a rolled back TX, we will just // have these messages to be stuck on the limbo until the server is restarted // The tx has already timed out, so we need to ack and rollback immediately @@ -837,63 +723,49 @@ public class ServerSessionImpl implements ServerSession, FailureListener consumer.individualAcknowledge(tx, messageID); newTX.rollback(); } - else - { + else { consumer.individualAcknowledge(autoCommitAcks ? null : tx, messageID); } } - public void individualCancel(final long consumerID, final long messageID, boolean failed) throws Exception - { + public void individualCancel(final long consumerID, final long messageID, boolean failed) throws Exception { ServerConsumer consumer = consumers.get(consumerID); - if (consumer != null) - { + if (consumer != null) { consumer.individualCancel(messageID, failed); } } - - public void expire(final long consumerID, final long messageID) throws Exception - { + public void expire(final long consumerID, final long messageID) throws Exception { MessageReference ref = consumers.get(consumerID).removeReferenceByID(messageID); - if (ref != null) - { + if (ref != null) { ref.getQueue().expire(ref); } } - public synchronized void commit() throws Exception - { - if (isTrace) - { + public synchronized void commit() throws Exception { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Calling commit"); } - try - { - if (tx != null) - { + try { + if (tx != null) { tx.commit(); } } - finally - { - if (xa) - { + finally { + if (xa) { tx = null; } - else - { + else { tx = newTransaction(); } } } - public void rollback(final boolean considerLastMessageAsDelivered) throws Exception - { + public void rollback(final boolean considerLastMessageAsDelivered) throws Exception { rollback(false, considerLastMessageAsDelivered); } @@ -902,10 +774,9 @@ public class ServerSessionImpl implements ServerSession, FailureListener * @param considerLastMessageAsDelivered * @throws Exception */ - private synchronized void rollback(final boolean clientFailed, final boolean considerLastMessageAsDelivered) throws Exception - { - if (tx == null) - { + private synchronized void rollback(final boolean clientFailed, + final boolean considerLastMessageAsDelivered) throws Exception { + if (tx == null) { // Might be null if XA tx = newTransaction(); @@ -913,12 +784,10 @@ public class ServerSessionImpl implements ServerSession, FailureListener doRollback(clientFailed, considerLastMessageAsDelivered, tx); - if (xa) - { + if (xa) { tx = null; } - else - { + else { tx = newTransaction(); } } @@ -926,8 +795,7 @@ public class ServerSessionImpl implements ServerSession, FailureListener /** * @return */ - protected Transaction newTransaction() - { + protected Transaction newTransaction() { return transactionFactory.newTransaction(null, storageManager, timeoutSeconds); } @@ -935,197 +803,153 @@ public class ServerSessionImpl implements ServerSession, FailureListener * @param xid * @return */ - private Transaction newTransaction(final Xid xid) - { + private Transaction newTransaction(final Xid xid) { return transactionFactory.newTransaction(xid, storageManager, timeoutSeconds); } - public synchronized void xaCommit(final Xid xid, final boolean onePhase) throws Exception - { + public synchronized void xaCommit(final Xid xid, final boolean onePhase) throws Exception { - if (tx != null && tx.getXid().equals(xid)) - { + if (tx != null && tx.getXid().equals(xid)) { final String msg = "Cannot commit, session is currently doing work in transaction " + tx.getXid(); throw new ActiveMQXAException(XAException.XAER_PROTO, msg); } - else - { + else { Transaction theTx = resourceManager.removeTransaction(xid); - - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("XAcommit into " + theTx + ", xid=" + xid); } - if (theTx == null) - { + if (theTx == null) { // checked heuristic committed transactions - if (resourceManager.getHeuristicCommittedTransactions().contains(xid)) - { - throw new ActiveMQXAException(XAException.XA_HEURCOM, - "transaction has been heuristically committed: " + xid); + if (resourceManager.getHeuristicCommittedTransactions().contains(xid)) { + throw new ActiveMQXAException(XAException.XA_HEURCOM, "transaction has been heuristically committed: " + xid); } // checked heuristic rolled back transactions - else if (resourceManager.getHeuristicRolledbackTransactions().contains(xid)) - { - throw new ActiveMQXAException(XAException.XA_HEURRB, - "transaction has been heuristically rolled back: " + xid); + else if (resourceManager.getHeuristicRolledbackTransactions().contains(xid)) { + throw new ActiveMQXAException(XAException.XA_HEURRB, "transaction has been heuristically rolled back: " + xid); } - else - { - if (isTrace) - { + else { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("XAcommit into " + theTx + ", xid=" + xid + " cannot find it"); } throw new ActiveMQXAException(XAException.XAER_NOTA, "Cannot find xid in resource manager: " + xid); } } - else - { - if (theTx.getState() == Transaction.State.SUSPENDED) - { + else { + if (theTx.getState() == Transaction.State.SUSPENDED) { // Put it back resourceManager.putTransaction(xid, theTx); throw new ActiveMQXAException(XAException.XAER_PROTO, "Cannot commit transaction, it is suspended " + xid); } - else - { + else { theTx.commit(onePhase); } } } } - public synchronized void xaEnd(final Xid xid) throws Exception - { - if (tx != null && tx.getXid().equals(xid)) - { - if (tx.getState() == Transaction.State.SUSPENDED) - { + public synchronized void xaEnd(final Xid xid) throws Exception { + if (tx != null && tx.getXid().equals(xid)) { + if (tx.getState() == Transaction.State.SUSPENDED) { final String msg = "Cannot end, transaction is suspended"; throw new ActiveMQXAException(XAException.XAER_PROTO, msg); } - else if (tx.getState() == Transaction.State.ROLLEDBACK) - { + else if (tx.getState() == Transaction.State.ROLLEDBACK) { final String msg = "Cannot end, transaction is rolled back"; tx = null; throw new ActiveMQXAException(XAException.XAER_PROTO, msg); } - else - { + else { tx = null; } } - else - { + else { // It's also legal for the TM to call end for a Xid in the suspended // state // See JTA 1.1 spec 3.4.4 - state diagram // Although in practice TMs rarely do this. Transaction theTx = resourceManager.getTransaction(xid); - if (theTx == null) - { + if (theTx == null) { final String msg = "Cannot find suspended transaction to end " + xid; throw new ActiveMQXAException(XAException.XAER_NOTA, msg); } - else - { - if (theTx.getState() != Transaction.State.SUSPENDED) - { + else { + if (theTx.getState() != Transaction.State.SUSPENDED) { final String msg = "Transaction is not suspended " + xid; throw new ActiveMQXAException(XAException.XAER_PROTO, msg); } - else - { + else { theTx.resume(); } } } } - public synchronized void xaForget(final Xid xid) throws Exception - { + public synchronized void xaForget(final Xid xid) throws Exception { long id = resourceManager.removeHeuristicCompletion(xid); - if (id != -1) - { - try - { + if (id != -1) { + try { storageManager.deleteHeuristicCompletion(id); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); throw new ActiveMQXAException(XAException.XAER_RMFAIL); } } - else - { + else { throw new ActiveMQXAException(XAException.XAER_NOTA); } } - public synchronized void xaJoin(final Xid xid) throws Exception - { + public synchronized void xaJoin(final Xid xid) throws Exception { Transaction theTx = resourceManager.getTransaction(xid); - if (theTx == null) - { + if (theTx == null) { final String msg = "Cannot find xid in resource manager: " + xid; throw new ActiveMQXAException(XAException.XAER_NOTA, msg); } - else - { - if (theTx.getState() == Transaction.State.SUSPENDED) - { + else { + if (theTx.getState() == Transaction.State.SUSPENDED) { throw new ActiveMQXAException(XAException.XAER_PROTO, "Cannot join tx, it is suspended " + xid); } - else - { + else { tx = theTx; } } } - public synchronized void xaResume(final Xid xid) throws Exception - { - if (tx != null) - { + public synchronized void xaResume(final Xid xid) throws Exception { + if (tx != null) { final String msg = "Cannot resume, session is currently doing work in a transaction " + tx.getXid(); throw new ActiveMQXAException(XAException.XAER_PROTO, msg); } - else - { + else { Transaction theTx = resourceManager.getTransaction(xid); - if (theTx == null) - { + if (theTx == null) { final String msg = "Cannot find xid in resource manager: " + xid; throw new ActiveMQXAException(XAException.XAER_NOTA, msg); } - else - { - if (theTx.getState() != Transaction.State.SUSPENDED) - { - throw new ActiveMQXAException(XAException.XAER_PROTO, - "Cannot resume transaction, it is not suspended " + xid); + else { + if (theTx.getState() != Transaction.State.SUSPENDED) { + throw new ActiveMQXAException(XAException.XAER_PROTO, "Cannot resume transaction, it is not suspended " + xid); } - else - { + else { tx = theTx; tx.resume(); @@ -1134,146 +958,114 @@ public class ServerSessionImpl implements ServerSession, FailureListener } } - public synchronized void xaRollback(final Xid xid) throws Exception - { - if (tx != null && tx.getXid().equals(xid)) - { + public synchronized void xaRollback(final Xid xid) throws Exception { + if (tx != null && tx.getXid().equals(xid)) { final String msg = "Cannot roll back, session is currently doing work in a transaction " + tx.getXid(); throw new ActiveMQXAException(XAException.XAER_PROTO, msg); } - else - { + else { Transaction theTx = resourceManager.removeTransaction(xid); - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("xarollback into " + theTx); } - if (theTx == null) - { + if (theTx == null) { // checked heuristic committed transactions - if (resourceManager.getHeuristicCommittedTransactions().contains(xid)) - { - throw new ActiveMQXAException(XAException.XA_HEURCOM, - "transaction has ben heuristically committed: " + xid); + if (resourceManager.getHeuristicCommittedTransactions().contains(xid)) { + throw new ActiveMQXAException(XAException.XA_HEURCOM, "transaction has ben heuristically committed: " + xid); } // checked heuristic rolled back transactions - else if (resourceManager.getHeuristicRolledbackTransactions().contains(xid)) - { - throw new ActiveMQXAException(XAException.XA_HEURRB, - "transaction has ben heuristically rolled back: " + xid); + else if (resourceManager.getHeuristicRolledbackTransactions().contains(xid)) { + throw new ActiveMQXAException(XAException.XA_HEURRB, "transaction has ben heuristically rolled back: " + xid); } - else - { - if (isTrace) - { + else { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("xarollback into " + theTx + ", xid=" + xid + " forcing a rollback regular"); } - try - { + try { // jbpapp-8845 // This could have happened because the TX timed out, // at this point we would be better on rolling back this session as a way to prevent consumers from holding their messages this.rollback(false); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e); } throw new ActiveMQXAException(XAException.XAER_NOTA, "Cannot find xid in resource manager: " + xid); } } - else - { - if (theTx.getState() == Transaction.State.SUSPENDED) - { - if (isTrace) - { + else { + if (theTx.getState() == Transaction.State.SUSPENDED) { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("xarollback into " + theTx + " sending tx back as it was suspended"); } - // Put it back resourceManager.putTransaction(xid, tx); - throw new ActiveMQXAException(XAException.XAER_PROTO, - "Cannot rollback transaction, it is suspended " + xid); + throw new ActiveMQXAException(XAException.XAER_PROTO, "Cannot rollback transaction, it is suspended " + xid); } - else - { + else { doRollback(false, false, theTx); } } } } - public synchronized void xaStart(final Xid xid) throws Exception - { - if (tx != null) - { + public synchronized void xaStart(final Xid xid) throws Exception { + if (tx != null) { ActiveMQServerLogger.LOGGER.xidReplacedOnXStart(tx.getXid().toString(), xid.toString()); - try - { - if (tx.getState() != Transaction.State.PREPARED) - { + try { + if (tx.getState() != Transaction.State.PREPARED) { // we don't want to rollback anything prepared here - if (tx.getXid() != null) - { + if (tx.getXid() != null) { resourceManager.removeTransaction(tx.getXid()); } tx.rollback(); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.debug("An exception happened while we tried to debug the previous tx, we can ignore this exception", e); } } tx = newTransaction(xid); - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("xastart into tx= " + tx); } boolean added = resourceManager.putTransaction(xid, tx); - if (!added) - { + if (!added) { final String msg = "Cannot start, there is already a xid " + tx.getXid(); throw new ActiveMQXAException(XAException.XAER_DUPID, msg); } } - public synchronized void xaFailed(final Xid xid) throws Exception - { - if (tx != null) - { + public synchronized void xaFailed(final Xid xid) throws Exception { + if (tx != null) { final String msg = "Cannot start, session is already doing work in a transaction " + tx.getXid(); throw new ActiveMQXAException(XAException.XAER_PROTO, msg); } - else - { + else { tx = newTransaction(xid); tx.markAsRollbackOnly(new ActiveMQException("Can't commit as a Failover happened during the operation")); - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("xastart into tx= " + tx); } boolean added = resourceManager.putTransaction(xid, tx); - if (!added) - { + if (!added) { final String msg = "Cannot start, there is already a xid " + tx.getXid(); throw new ActiveMQXAException(XAException.XAER_DUPID, msg); @@ -1281,30 +1073,24 @@ public class ServerSessionImpl implements ServerSession, FailureListener } } - public synchronized void xaSuspend() throws Exception - { + public synchronized void xaSuspend() throws Exception { - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("xasuspend on " + this.tx); } - if (tx == null) - { + if (tx == null) { final String msg = "Cannot suspend, session is not doing work in a transaction "; throw new ActiveMQXAException(XAException.XAER_PROTO, msg); } - else - { - if (tx.getState() == Transaction.State.SUSPENDED) - { + else { + if (tx.getState() == Transaction.State.SUSPENDED) { final String msg = "Cannot suspend, transaction is already suspended " + tx.getXid(); throw new ActiveMQXAException(XAException.XAER_PROTO, msg); } - else - { + else { tx.suspend(); tx = null; @@ -1312,50 +1098,39 @@ public class ServerSessionImpl implements ServerSession, FailureListener } } - public synchronized void xaPrepare(final Xid xid) throws Exception - { - if (tx != null && tx.getXid().equals(xid)) - { + public synchronized void xaPrepare(final Xid xid) throws Exception { + if (tx != null && tx.getXid().equals(xid)) { final String msg = "Cannot commit, session is currently doing work in a transaction " + tx.getXid(); throw new ActiveMQXAException(XAException.XAER_PROTO, msg); } - else - { + else { Transaction theTx = resourceManager.getTransaction(xid); - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("xaprepare into " + ", xid=" + xid + ", tx= " + tx); } - if (theTx == null) - { + if (theTx == null) { final String msg = "Cannot find xid in resource manager: " + xid; throw new ActiveMQXAException(XAException.XAER_NOTA, msg); } - else - { - if (theTx.getState() == Transaction.State.SUSPENDED) - { - throw new ActiveMQXAException(XAException.XAER_PROTO, - "Cannot prepare transaction, it is suspended " + xid); + else { + if (theTx.getState() == Transaction.State.SUSPENDED) { + throw new ActiveMQXAException(XAException.XAER_PROTO, "Cannot prepare transaction, it is suspended " + xid); } - else if (theTx.getState() == Transaction.State.PREPARED) - { + else if (theTx.getState() == Transaction.State.PREPARED) { ActiveMQServerLogger.LOGGER.info("ignoring prepare on xid as already called :" + xid); } - else - { + else { theTx.prepare(); } } } } - public List xaGetInDoubtXids() - { + public List xaGetInDoubtXids() { List xids = new ArrayList(); xids.addAll(resourceManager.getPreparedTransactions()); @@ -1365,88 +1140,69 @@ public class ServerSessionImpl implements ServerSession, FailureListener return xids; } - public int xaGetTimeout() - { + public int xaGetTimeout() { return resourceManager.getTimeoutSeconds(); } - public void xaSetTimeout(final int timeout) - { + public void xaSetTimeout(final int timeout) { timeoutSeconds = timeout; - if (tx != null) - { + if (tx != null) { tx.setTimeout(timeout); } } - public void start() - { + public void start() { setStarted(true); } - public void stop() - { + public void stop() { setStarted(false); } - public void waitContextCompletion() - { - try - { - if (!context.waitCompletion(10000)) - { + public void waitContextCompletion() { + try { + if (!context.waitCompletion(10000)) { ActiveMQServerLogger.LOGGER.errorCompletingContext(new Exception("warning")); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e); } } - public void close(final boolean failed) - { - if (closed) return; - context.executeOnCompletion(new IOCallback() - { - public void onError(int errorCode, String errorMessage) - { + public void close(final boolean failed) { + if (closed) + return; + context.executeOnCompletion(new IOCallback() { + public void onError(int errorCode, String errorMessage) { } - public void done() - { - try - { + public void done() { + try { doClose(failed); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorClosingSession(e); } } }); } - public void closeConsumer(final long consumerID) throws Exception - { + public void closeConsumer(final long consumerID) throws Exception { final ServerConsumer consumer = consumers.get(consumerID); - if (consumer != null) - { + if (consumer != null) { consumer.close(false); } - else - { + else { ActiveMQServerLogger.LOGGER.cannotFindConsumer(consumerID); } } - public void receiveConsumerCredits(final long consumerID, final int credits) throws Exception - { + public void receiveConsumerCredits(final long consumerID, final int credits) throws Exception { ServerConsumer consumer = consumers.get(consumerID); - if (consumer == null) - { + if (consumer == null) { ActiveMQServerLogger.LOGGER.debug("There is no consumer with id " + consumerID); return; @@ -1456,41 +1212,34 @@ public class ServerSessionImpl implements ServerSession, FailureListener } @Override - public Transaction getCurrentTransaction() - { - if (tx == null) - { + public Transaction getCurrentTransaction() { + if (tx == null) { tx = newTransaction(); } return tx; } - public void sendLarge(final MessageInternal message) throws Exception - { + public void sendLarge(final MessageInternal message) throws Exception { // need to create the LargeMessage before continue long id = storageManager.generateID(); LargeServerMessage largeMsg = storageManager.createLargeMessage(id, message); - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("sendLarge::" + largeMsg); } - if (currentLargeMessage != null) - { + if (currentLargeMessage != null) { ActiveMQServerLogger.LOGGER.replacingIncompleteLargeMessage(currentLargeMessage.getMessageID()); } currentLargeMessage = largeMsg; } - public void send(final ServerMessage message, final boolean direct) throws Exception - { + public void send(final ServerMessage message, final boolean direct) throws Exception { //large message may come from StompSession directly, in which //case the id header already generated. - if (!message.isLargeMessage()) - { + if (!message.isLargeMessage()) { long id = storageManager.generateID(); message.setMessageID(id); @@ -1499,45 +1248,37 @@ public class ServerSessionImpl implements ServerSession, FailureListener SimpleString address = message.getAddress(); - if (defaultAddress == null && address != null) - { + if (defaultAddress == null && address != null) { defaultAddress = address; } - if (address == null) - { - if (message.isDurable()) - { + if (address == null) { + if (message.isDurable()) { // We need to force a re-encode when the message gets persisted or when it gets reloaded // it will have no address message.setAddress(defaultAddress); } - else - { + else { // We don't want to force a re-encode when the message gets sent to the consumer message.setAddressTransient(defaultAddress); } } - if (isTrace) - { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("send(message=" + message + ", direct=" + direct + ") being called"); } - if (message.getAddress() == null) - { + if (message.getAddress() == null) { // This could happen with some tests that are ignoring messages throw ActiveMQMessageBundle.BUNDLE.noAddress(); } - if (message.getAddress().equals(managementAddress)) - { + if (message.getAddress().equals(managementAddress)) { // It's a management message handleManagementMessage(message, direct); } - else - { + else { doSend(message, direct); } } @@ -1545,10 +1286,8 @@ public class ServerSessionImpl implements ServerSession, FailureListener public void sendContinuations(final int packetSize, final long messageBodySize, final byte[] body, - final boolean continues) throws Exception - { - if (currentLargeMessage == null) - { + final boolean continues) throws Exception { + if (currentLargeMessage == null) { throw ActiveMQMessageBundle.BUNDLE.largeMessageNotInitialised(); } @@ -1557,12 +1296,10 @@ public class ServerSessionImpl implements ServerSession, FailureListener currentLargeMessage.addBytes(body); - if (!continues) - { + if (!continues) { currentLargeMessage.releaseResources(); - if (messageBodySize >= 0) - { + if (messageBodySize >= 0) { currentLargeMessage.putLongProperty(Message.HDR_LARGE_BODY_SIZE, messageBodySize); } @@ -1572,118 +1309,94 @@ public class ServerSessionImpl implements ServerSession, FailureListener } } - public void requestProducerCredits(final SimpleString address, final int credits) throws Exception - { + public void requestProducerCredits(final SimpleString address, final int credits) throws Exception { PagingStore store = server.getPagingManager().getPageStore(address); - if (!store.checkMemory(new Runnable() - { - public void run() - { + if (!store.checkMemory(new Runnable() { + public void run() { callback.sendProducerCreditsMessage(credits, address); } - })) - { + })) { callback.sendProducerCreditsFailMessage(credits, address); } } - public void setTransferring(final boolean transferring) - { + public void setTransferring(final boolean transferring) { Set consumersClone = new HashSet(consumers.values()); - for (ServerConsumer consumer : consumersClone) - { + for (ServerConsumer consumer : consumersClone) { consumer.setTransferring(transferring); } } - public void addMetaData(String key, String data) - { - if (metaData == null) - { + public void addMetaData(String key, String data) { + if (metaData == null) { metaData = new HashMap(); } metaData.put(key, data); } - - public boolean addUniqueMetaData(String key, String data) - { + public boolean addUniqueMetaData(String key, String data) { ServerSession sessionWithMetaData = server.lookupSession(key, data); - if (sessionWithMetaData != null && sessionWithMetaData != this) - { + if (sessionWithMetaData != null && sessionWithMetaData != this) { // There is a duplication of this property return false; } - else - { + else { addMetaData(key, data); return true; } } - public String getMetaData(String key) - { + public String getMetaData(String key) { String data = null; - if (metaData != null) - { + if (metaData != null) { data = metaData.get(key); } - if (key.equals(ClientSession.JMS_SESSION_CLIENT_ID_PROPERTY)) - { + if (key.equals(ClientSession.JMS_SESSION_CLIENT_ID_PROPERTY)) { // we know it's a JMS Session, we now install JMS Hooks of any kind installJMSHooks(); } return data; } - public String[] getTargetAddresses() - { + public String[] getTargetAddresses() { Map> copy = cloneTargetAddresses(); Iterator iter = copy.keySet().iterator(); int num = copy.keySet().size(); String[] addresses = new String[num]; int i = 0; - while (iter.hasNext()) - { + while (iter.hasNext()) { addresses[i] = iter.next().toString(); i++; } return addresses; } - public String getLastSentMessageID(String address) - { + public String getLastSentMessageID(String address) { Pair value = targetAddressInfos.get(SimpleString.toSimpleString(address)); - if (value != null) - { + if (value != null) { return value.getA().toString(); } - else - { + else { return null; } } - public long getCreationTime() - { + public long getCreationTime() { return this.creationTime; } - public StorageManager getStorageManager() - { + public StorageManager getStorageManager() { return this.storageManager; } @Override - public void describeProducersInfo(JSONArray array) throws Exception - { + public void describeProducersInfo(JSONArray array) throws Exception { Map> targetCopy = cloneTargetAddresses(); - for (Map.Entry> entry : targetCopy.entrySet()) - { + for (Map.Entry> entry : targetCopy.entrySet()) { JSONObject producerInfo = new JSONObject(); producerInfo.put("connectionID", this.getConnectionID().toString()); producerInfo.put("sessionID", this.getName()); @@ -1695,24 +1408,18 @@ public class ServerSessionImpl implements ServerSession, FailureListener } @Override - public String toString() - { + public String toString() { StringBuffer buffer = new StringBuffer(); - if (this.metaData != null) - { - for (Map.Entry value : metaData.entrySet()) - { - if (buffer.length() != 0) - { + if (this.metaData != null) { + for (Map.Entry value : metaData.entrySet()) { + if (buffer.length() != 0) { buffer.append(","); } Object tmpValue = value.getValue(); - if (tmpValue == null || tmpValue.toString().isEmpty()) - { + if (tmpValue == null || tmpValue.toString().isEmpty()) { buffer.append(value.getKey() + "=*N/A*"); } - else - { + else { buffer.append(value.getKey() + "=" + tmpValue); } } @@ -1727,68 +1434,52 @@ public class ServerSessionImpl implements ServerSession, FailureListener // -------------------------------------------------------------------- @Override - public void connectionFailed(final ActiveMQException me, boolean failedOver) - { - try - { + public void connectionFailed(final ActiveMQException me, boolean failedOver) { + try { ActiveMQServerLogger.LOGGER.clientConnectionFailed(name); close(true); ActiveMQServerLogger.LOGGER.clientConnectionFailedClearingSession(name); } - catch (Throwable t) - { + catch (Throwable t) { ActiveMQServerLogger.LOGGER.errorClosingConnection(this); } } @Override - public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) { connectionFailed(me, failedOver); } - public void clearLargeMessage() - { + public void clearLargeMessage() { currentLargeMessage = null; } - - - private void installJMSHooks() - { + private void installJMSHooks() { this.queueCreator = server.getJMSQueueCreator(); } - - private Map> cloneTargetAddresses() - { + private Map> cloneTargetAddresses() { return new HashMap>(targetAddressInfos); } - private void setStarted(final boolean s) - { + private void setStarted(final boolean s) { Set consumersClone = new HashSet(consumers.values()); - for (ServerConsumer consumer : consumersClone) - { + for (ServerConsumer consumer : consumersClone) { consumer.setStarted(s); } started = s; } - private void handleManagementMessage(final ServerMessage message, final boolean direct) throws Exception - { - try - { + private void handleManagementMessage(final ServerMessage message, final boolean direct) throws Exception { + try { securityStore.check(message.getAddress(), CheckType.MANAGE, this); } - catch (ActiveMQException e) - { - if (!autoCommitSends) - { + catch (ActiveMQException e) { + if (!autoCommitSends) { tx.markAsRollbackOnly(e); } throw e; @@ -1798,24 +1489,22 @@ public class ServerSessionImpl implements ServerSession, FailureListener SimpleString replyTo = message.getSimpleStringProperty(ClientMessageImpl.REPLYTO_HEADER_NAME); - if (replyTo != null) - { + if (replyTo != null) { reply.setAddress(replyTo); doSend(reply, direct); } } - private void doRollback(final boolean clientFailed, final boolean lastMessageAsDelived, final Transaction theTx) throws Exception - { + private void doRollback(final boolean clientFailed, + final boolean lastMessageAsDelived, + final Transaction theTx) throws Exception { boolean wasStarted = started; List toCancel = new ArrayList(); - for (ServerConsumer consumer : consumers.values()) - { - if (wasStarted) - { + for (ServerConsumer consumer : consumers.values()) { + if (wasStarted) { consumer.setStarted(false); } @@ -1826,8 +1515,7 @@ public class ServerSessionImpl implements ServerSession, FailureListener //after the last tx was rolled back so we should handle them separately. if not they //will end up added to the tx but never ever handled even tho they were removed from the consumers delivering refs. //we add them to a new tx and roll them back as the calling client will assume that this has happened. - if (theTx.getState() == State.ROLLEDBACK) - { + if (theTx.getState() == State.ROLLEDBACK) { Transaction newTX = newTransaction(); cancelAndRollback(clientFailed, newTX, wasStarted, toCancel); throw new IllegalStateException("Transaction has already been rolled back"); @@ -1835,23 +1523,20 @@ public class ServerSessionImpl implements ServerSession, FailureListener cancelAndRollback(clientFailed, theTx, wasStarted, toCancel); } - private void cancelAndRollback(boolean clientFailed, Transaction theTx, boolean wasStarted, List toCancel) throws Exception - { - for (MessageReference ref : toCancel) - { + private void cancelAndRollback(boolean clientFailed, + Transaction theTx, + boolean wasStarted, + List toCancel) throws Exception { + for (MessageReference ref : toCancel) { ref.getQueue().cancel(theTx, ref); } //if we failed don't restart as an attempt to deliver messages may be made before we actually close the consumer - if (wasStarted && !clientFailed) - { - theTx.addOperation(new TransactionOperationAbstract() - { + if (wasStarted && !clientFailed) { + theTx.addOperation(new TransactionOperationAbstract() { @Override - public void afterRollback(Transaction tx) - { - for (ServerConsumer consumer : consumers.values()) - { + public void afterRollback(Transaction tx) { + for (ServerConsumer consumer : consumers.values()) { consumer.setStarted(true); } } @@ -1862,80 +1547,63 @@ public class ServerSessionImpl implements ServerSession, FailureListener theTx.rollback(); } - protected void doSend(final ServerMessage msg, final boolean direct) throws Exception - { + protected void doSend(final ServerMessage msg, final boolean direct) throws Exception { // check the user has write access to this address. - try - { + try { securityStore.check(msg.getAddress(), CheckType.SEND, this); } - catch (ActiveMQException e) - { - if (!autoCommitSends && tx != null) - { + catch (ActiveMQException e) { + if (!autoCommitSends && tx != null) { tx.markAsRollbackOnly(e); } throw e; } - if (tx == null || autoCommitSends) - { + if (tx == null || autoCommitSends) { } - else - { + else { routingContext.setTransaction(tx); } - try - { + try { postOffice.route(msg, queueCreator, routingContext, direct); Pair value = targetAddressInfos.get(msg.getAddress()); - if (value == null) - { + if (value == null) { targetAddressInfos.put(msg.getAddress(), new Pair(msg.getUserID(), new AtomicLong(1))); } - else - { + else { value.setA(msg.getUserID()); value.getB().incrementAndGet(); } } - finally - { + finally { routingContext.clear(); } } - @Override - public List getInTXMessagesForConsumer(long consumerId) - { - if (this.tx != null) - { + public List getInTXMessagesForConsumer(long consumerId) { + if (this.tx != null) { RefsOperation oper = (RefsOperation) tx.getProperty(TransactionPropertyIndexes.REFS_OPERATION); - if (oper == null) - { + if (oper == null) { return Collections.emptyList(); } - else - { + else { return oper.getListOnConsumer(consumerId); } } - else - { + else { return Collections.emptyList(); } } - private static class DefaultTransactionFactory implements TransactionFactory - { + private static class DefaultTransactionFactory implements TransactionFactory { + @Override - public Transaction newTransaction(Xid xid, StorageManager storageManager, int timeoutSeconds) - { + public Transaction newTransaction(Xid xid, StorageManager storageManager, int timeoutSeconds) { return new TransactionImpl(xid, storageManager, timeoutSeconds); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ServiceRegistryImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ServiceRegistryImpl.java index f8849ed954..715d92fde2 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ServiceRegistryImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ServiceRegistryImpl.java @@ -38,8 +38,8 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; -public class ServiceRegistryImpl implements ServiceRegistry -{ +public class ServiceRegistryImpl implements ServiceRegistry { + private ExecutorService executorService; private ScheduledExecutorService scheduledExecutorService; @@ -59,8 +59,7 @@ public class ServiceRegistryImpl implements ServiceRegistry private Map> connectorServices; - public ServiceRegistryImpl() - { + public ServiceRegistryImpl() { this.incomingInterceptors = Collections.synchronizedList(new ArrayList()); this.outgoingInterceptors = Collections.synchronizedList(new ArrayList()); this.connectorServices = new ConcurrentHashMap<>(); @@ -70,54 +69,43 @@ public class ServiceRegistryImpl implements ServiceRegistry } @Override - public ExecutorService getExecutorService() - { + public ExecutorService getExecutorService() { return executorService; } @Override - public void setExecutorService(ExecutorService executorService) - { + public void setExecutorService(ExecutorService executorService) { this.executorService = executorService; } @Override - public ScheduledExecutorService getScheduledExecutorService() - { + public ScheduledExecutorService getScheduledExecutorService() { return scheduledExecutorService; } @Override - public void setScheduledExecutorService(ScheduledExecutorService scheduledExecutorService) - { + public void setScheduledExecutorService(ScheduledExecutorService scheduledExecutorService) { this.scheduledExecutorService = scheduledExecutorService; } @Override - public void addConnectorService(ConnectorServiceFactory connectorServiceFactory, ConnectorServiceConfiguration configuration) - { + public void addConnectorService(ConnectorServiceFactory connectorServiceFactory, + ConnectorServiceConfiguration configuration) { connectorServices.put(configuration.getConnectorName(), new Pair<>(connectorServiceFactory, configuration)); } @Override - public void removeConnectorService(ConnectorServiceConfiguration configuration) - { + public void removeConnectorService(ConnectorServiceConfiguration configuration) { connectorServices.remove(configuration.getConnectorName()); } @Override - public Collection> getConnectorServices(List configs) - { - if (configs != null) - { - for (final ConnectorServiceConfiguration config : configs) - { - if (connectorServices.get(config.getConnectorName()) == null) - { - ConnectorServiceFactory factory = AccessController.doPrivileged(new PrivilegedAction() - { - public ConnectorServiceFactory run() - { + public Collection> getConnectorServices(List configs) { + if (configs != null) { + for (final ConnectorServiceConfiguration config : configs) { + if (connectorServices.get(config.getConnectorName()) == null) { + ConnectorServiceFactory factory = AccessController.doPrivileged(new PrivilegedAction() { + public ConnectorServiceFactory run() { return (ConnectorServiceFactory) ClassloadingUtil.newInstanceFromClassLoader(config.getFactoryClassName()); } }); @@ -130,14 +118,12 @@ public class ServiceRegistryImpl implements ServiceRegistry } @Override - public void addIncomingInterceptor(Interceptor interceptor) - { + public void addIncomingInterceptor(Interceptor interceptor) { incomingInterceptors.add(interceptor); } @Override - public List getIncomingInterceptors(List classNames) - { + public List getIncomingInterceptors(List classNames) { List interceptors = new ArrayList<>(incomingInterceptors); instantiateInterceptors(classNames, interceptors); @@ -146,14 +132,12 @@ public class ServiceRegistryImpl implements ServiceRegistry } @Override - public void addOutgoingInterceptor(Interceptor interceptor) - { + public void addOutgoingInterceptor(Interceptor interceptor) { outgoingInterceptors.add(interceptor); } @Override - public List getOutgoingInterceptors(List classNames) - { + public List getOutgoingInterceptors(List classNames) { List interceptors = new ArrayList<>(outgoingInterceptors); instantiateInterceptors(classNames, interceptors); @@ -162,18 +146,15 @@ public class ServiceRegistryImpl implements ServiceRegistry } @Override - public void addDivertTransformer(String name, Transformer transformer) - { + public void addDivertTransformer(String name, Transformer transformer) { divertTransformers.put(name, transformer); } @Override - public Transformer getDivertTransformer(String name, String className) - { + public Transformer getDivertTransformer(String name, String className) { Transformer transformer = divertTransformers.get(name); - if (transformer == null && className != null) - { + if (transformer == null && className != null) { transformer = instantiateTransformer(className); addDivertTransformer(name, transformer); } @@ -182,18 +163,15 @@ public class ServiceRegistryImpl implements ServiceRegistry } @Override - public void addBridgeTransformer(String name, Transformer transformer) - { + public void addBridgeTransformer(String name, Transformer transformer) { bridgeTransformers.put(name, transformer); } @Override - public Transformer getBridgeTransformer(String name, String className) - { + public Transformer getBridgeTransformer(String name, String className) { Transformer transformer = bridgeTransformers.get(name); - if (transformer == null && className != null) - { + if (transformer == null && className != null) { transformer = instantiateTransformer(className); addBridgeTransformer(name, transformer); } @@ -202,16 +180,12 @@ public class ServiceRegistryImpl implements ServiceRegistry } @Override - public AcceptorFactory getAcceptorFactory(String name, final String className) - { + public AcceptorFactory getAcceptorFactory(String name, final String className) { AcceptorFactory factory = acceptorFactories.get(name); - if (factory == null && className != null) - { - factory = AccessController.doPrivileged(new PrivilegedAction() - { - public AcceptorFactory run() - { + if (factory == null && className != null) { + factory = AccessController.doPrivileged(new PrivilegedAction() { + public AcceptorFactory run() { return (AcceptorFactory) ClassloadingUtil.newInstanceFromClassLoader(className); } }); @@ -223,45 +197,33 @@ public class ServiceRegistryImpl implements ServiceRegistry } @Override - public void addAcceptorFactory(String name, AcceptorFactory acceptorFactory) - { + public void addAcceptorFactory(String name, AcceptorFactory acceptorFactory) { acceptorFactories.put(name, acceptorFactory); } - private Transformer instantiateTransformer(final String className) - { + private Transformer instantiateTransformer(final String className) { Transformer transformer = null; - if (className != null) - { - try - { - transformer = AccessController.doPrivileged(new PrivilegedAction() - { - public Transformer run() - { + if (className != null) { + try { + transformer = AccessController.doPrivileged(new PrivilegedAction() { + public Transformer run() { return (Transformer) ClassloadingUtil.newInstanceFromClassLoader(className); } }); } - catch (Exception e) - { + catch (Exception e) { throw ActiveMQMessageBundle.BUNDLE.errorCreatingTransformerClass(e, className); } } return transformer; } - private void instantiateInterceptors(List classNames, List interceptors) - { - if (classNames != null) - { - for (final String className : classNames) - { - BaseInterceptor interceptor = AccessController.doPrivileged(new PrivilegedAction() - { - public BaseInterceptor run() - { + private void instantiateInterceptors(List classNames, List interceptors) { + if (classNames != null) { + for (final String className : classNames) { + BaseInterceptor interceptor = AccessController.doPrivileged(new PrivilegedAction() { + public BaseInterceptor run() { return (BaseInterceptor) ClassloadingUtil.newInstanceFromClassLoader(className); } }); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/SharedNothingBackupActivation.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/SharedNothingBackupActivation.java index b9c37b4667..fa8be061be 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/SharedNothingBackupActivation.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/SharedNothingBackupActivation.java @@ -51,8 +51,8 @@ import static org.apache.activemq.artemis.core.server.cluster.qourum.SharedNothi import static org.apache.activemq.artemis.core.server.cluster.qourum.SharedNothingBackupQuorum.BACKUP_ACTIVATION.FAIL_OVER; import static org.apache.activemq.artemis.core.server.cluster.qourum.SharedNothingBackupQuorum.BACKUP_ACTIVATION.STOP; -public final class SharedNothingBackupActivation extends Activation -{ +public final class SharedNothingBackupActivation extends Activation { + //this is how we act when we start as a backup private ReplicaPolicy replicaPolicy; @@ -75,8 +75,7 @@ public final class SharedNothingBackupActivation extends Activation boolean attemptFailBack, Map activationParams, ActiveMQServerImpl.ShutdownOnCriticalErrorListener shutdownOnCriticalIO, - ReplicaPolicy replicaPolicy) - { + ReplicaPolicy replicaPolicy) { this.activeMQServer = activeMQServer; this.attemptFailBack = attemptFailBack; this.activationParams = activationParams; @@ -85,28 +84,23 @@ public final class SharedNothingBackupActivation extends Activation backupSyncLatch.setCount(1); } - public void init() throws Exception - { + public void init() throws Exception { assert replicationEndpoint == null; activeMQServer.resetNodeManager(); backupUpToDate = false; replicationEndpoint = new ReplicationEndpoint(activeMQServer, shutdownOnCriticalIO, attemptFailBack, this); } - public void run() - { - try - { - synchronized (activeMQServer) - { + public void run() { + try { + synchronized (activeMQServer) { activeMQServer.setState(ActiveMQServerImpl.SERVER_STATE.STARTED); } // move all data away: activeMQServer.getNodeManager().stop(); activeMQServer.moveServerData(); activeMQServer.getNodeManager().start(); - synchronized (this) - { + synchronized (this) { if (closed) return; } @@ -116,8 +110,7 @@ public final class SharedNothingBackupActivation extends Activation if (!activeMQServer.initialisePart1(scalingDown)) return; - synchronized (this) - { + synchronized (this) { if (closed) return; backupQuorum = new SharedNothingBackupQuorum(activeMQServer.getStorageManager(), activeMQServer.getNodeManager(), activeMQServer.getScheduledPool()); @@ -126,16 +119,12 @@ public final class SharedNothingBackupActivation extends Activation //use a Node Locator to connect to the cluster LiveNodeLocator nodeLocator; - if (activationParams.get(ActivationParams.REPLICATION_ENDPOINT) != null) - { + if (activationParams.get(ActivationParams.REPLICATION_ENDPOINT) != null) { TopologyMember member = (TopologyMember) activationParams.get(ActivationParams.REPLICATION_ENDPOINT); nodeLocator = new NamedNodeIdNodeLocator(member.getNodeId(), new Pair<>(member.getLive(), member.getBackup())); } - else - { - nodeLocator = replicaPolicy.getGroupName() == null ? - new AnyLiveNodeLocatorForReplication(backupQuorum, activeMQServer) : - new NamedLiveNodeLocatorForReplication(replicaPolicy.getGroupName(), backupQuorum); + else { + nodeLocator = replicaPolicy.getGroupName() == null ? new AnyLiveNodeLocatorForReplication(backupQuorum, activeMQServer) : new NamedLiveNodeLocatorForReplication(replicaPolicy.getGroupName(), backupQuorum); } ClusterController clusterController = activeMQServer.getClusterManager().getClusterController(); clusterController.addClusterTopologyListenerForReplication(nodeLocator); @@ -156,45 +145,36 @@ public final class SharedNothingBackupActivation extends Activation activeMQServer.setState(ActiveMQServerImpl.SERVER_STATE.STARTED); SharedNothingBackupQuorum.BACKUP_ACTIVATION signal; - do - { + do { //locate the first live server to try to replicate nodeLocator.locateNode(); - if (closed) - { + if (closed) { return; } Pair possibleLive = nodeLocator.getLiveConfiguration(); nodeID = nodeLocator.getNodeID(); //in a normal (non failback) scenario if we couldn't find our live server we should fail - if (!attemptFailBack) - { + if (!attemptFailBack) { //this shouldn't happen if (nodeID == null) throw new RuntimeException("Could not establish the connection"); activeMQServer.getNodeManager().setNodeID(nodeID); } - try - { - clusterControl = clusterController.connectToNodeInReplicatedCluster(possibleLive.getA()); + try { + clusterControl = clusterController.connectToNodeInReplicatedCluster(possibleLive.getA()); } - catch (Exception e) - { - if (possibleLive.getB() != null) - { - try - { + catch (Exception e) { + if (possibleLive.getB() != null) { + try { clusterControl = clusterController.connectToNodeInReplicatedCluster(possibleLive.getB()); } - catch (Exception e1) - { + catch (Exception e1) { clusterControl = null; } } } - if (clusterControl == null) - { + if (clusterControl == null) { //its ok to retry here since we haven't started replication yet //it may just be the server has gone since discovery Thread.sleep(clusterController.getRetryIntervalForReplicatedCluster()); @@ -221,19 +201,14 @@ public final class SharedNothingBackupActivation extends Activation else if (signal == FAIL_OVER) break; // something has gone badly run restart from scratch - else if (signal == SharedNothingBackupQuorum.BACKUP_ACTIVATION.FAILURE_REPLICATING) - { - Thread startThread = new Thread(new Runnable() - { + else if (signal == SharedNothingBackupQuorum.BACKUP_ACTIVATION.FAILURE_REPLICATING) { + Thread startThread = new Thread(new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { activeMQServer.stop(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorRestartingBackupServer(e, activeMQServer); } } @@ -245,46 +220,38 @@ public final class SharedNothingBackupActivation extends Activation //close this session factory, we're done with it clusterControl.close(); backupQuorum.reset(); - if (replicationEndpoint.getChannel() != null) - { + if (replicationEndpoint.getChannel() != null) { replicationEndpoint.getChannel().close(); replicationEndpoint.setChannel(null); } - } - while (signal == SharedNothingBackupQuorum.BACKUP_ACTIVATION.ALREADY_REPLICATING); + } while (signal == SharedNothingBackupQuorum.BACKUP_ACTIVATION.ALREADY_REPLICATING); activeMQServer.getClusterManager().getQuorumManager().unRegisterQuorum(backupQuorum); - if (!isRemoteBackupUpToDate()) - { + if (!isRemoteBackupUpToDate()) { throw ActiveMQMessageBundle.BUNDLE.backupServerNotInSync(); } replicaPolicy.getReplicatedPolicy().setReplicaPolicy(replicaPolicy); activeMQServer.setHAPolicy(replicaPolicy.getReplicatedPolicy()); - synchronized (activeMQServer) - { + synchronized (activeMQServer) { if (!activeMQServer.isStarted()) return; ActiveMQServerLogger.LOGGER.becomingLive(activeMQServer); activeMQServer.getNodeManager().stopBackup(); activeMQServer.getStorageManager().start(); activeMQServer.getBackupManager().activated(); - if (scalingDown) - { + if (scalingDown) { activeMQServer.initialisePart2(true); } - else - { + else { activeMQServer.setActivation(new SharedNothingLiveActivation(activeMQServer, replicaPolicy.getReplicatedPolicy())); activeMQServer.initialisePart2(false); - if (activeMQServer.getIdentity() != null) - { + if (activeMQServer.getIdentity() != null) { ActiveMQServerLogger.LOGGER.serverIsLive(activeMQServer.getIdentity()); } - else - { + else { ActiveMQServerLogger.LOGGER.serverIsLive(); } @@ -293,8 +260,7 @@ public final class SharedNothingBackupActivation extends Activation activeMQServer.completeActivation(); } } - catch (Exception e) - { + catch (Exception e) { if ((e instanceof InterruptedException || e instanceof IllegalStateException) && !activeMQServer.isStarted()) // do not log these errors if the server is being stopped. return; @@ -303,112 +269,86 @@ public final class SharedNothingBackupActivation extends Activation } } - public void close(final boolean permanently, boolean restarting) throws Exception - { - synchronized (this) - { + public void close(final boolean permanently, boolean restarting) throws Exception { + synchronized (this) { if (backupQuorum != null) backupQuorum.causeExit(STOP); replicationEndpoint = null; closed = true; } //we have to check as the server policy may have changed - if (activeMQServer.getHAPolicy().isBackup()) - { + if (activeMQServer.getHAPolicy().isBackup()) { // To avoid a NPE cause by the stop NodeManager nodeManagerInUse = activeMQServer.getNodeManager(); activeMQServer.interrupBackupThread(nodeManagerInUse); - if (nodeManagerInUse != null) - { + if (nodeManagerInUse != null) { nodeManagerInUse.stopBackup(); } } } @Override - public void preStorageClose() throws Exception - { - if (replicationEndpoint != null) - { + public void preStorageClose() throws Exception { + if (replicationEndpoint != null) { replicationEndpoint.stop(); } } @Override - public JournalLoader createJournalLoader(PostOffice postOffice, PagingManager pagingManager, StorageManager storageManager, QueueFactory queueFactory, NodeManager nodeManager, ManagementService managementService, GroupingHandler groupingHandler, Configuration configuration, ActiveMQServer parentServer) throws ActiveMQException - { - if (replicaPolicy.getScaleDownPolicy() != null && replicaPolicy.getScaleDownPolicy().isEnabled()) - { - return new BackupRecoveryJournalLoader(postOffice, - pagingManager, - storageManager, - queueFactory, - nodeManager, - managementService, - groupingHandler, - configuration, - parentServer, - ScaleDownPolicy.getScaleDownConnector(replicaPolicy.getScaleDownPolicy(), activeMQServer), - activeMQServer.getClusterManager().getClusterController()); + public JournalLoader createJournalLoader(PostOffice postOffice, + PagingManager pagingManager, + StorageManager storageManager, + QueueFactory queueFactory, + NodeManager nodeManager, + ManagementService managementService, + GroupingHandler groupingHandler, + Configuration configuration, + ActiveMQServer parentServer) throws ActiveMQException { + if (replicaPolicy.getScaleDownPolicy() != null && replicaPolicy.getScaleDownPolicy().isEnabled()) { + return new BackupRecoveryJournalLoader(postOffice, pagingManager, storageManager, queueFactory, nodeManager, managementService, groupingHandler, configuration, parentServer, ScaleDownPolicy.getScaleDownConnector(replicaPolicy.getScaleDownPolicy(), activeMQServer), activeMQServer.getClusterManager().getClusterController()); } - else - { - return super.createJournalLoader(postOffice, - pagingManager, - storageManager, - queueFactory, - nodeManager, - managementService, - groupingHandler, - configuration, - parentServer); + else { + return super.createJournalLoader(postOffice, pagingManager, storageManager, queueFactory, nodeManager, managementService, groupingHandler, configuration, parentServer); } } @Override - public void haStarted() - { + public void haStarted() { activeMQServer.getClusterManager().getClusterController().setReplicatedClusterName(replicaPolicy.getClusterName()); } - /** * Wait for backup synchronization when using synchronization + * * @param timeout * @param unit - * @see java.util.concurrent.CountDownLatch#await(long, TimeUnit) * @return {@code true} if the server was already initialized or if it was initialized within the - * timeout period, {@code false} otherwise. + * timeout period, {@code false} otherwise. * @throws InterruptedException + * @see java.util.concurrent.CountDownLatch#await(long, TimeUnit) */ - public boolean waitForBackupSync(long timeout, TimeUnit unit) throws InterruptedException - { + public boolean waitForBackupSync(long timeout, TimeUnit unit) throws InterruptedException { return backupSyncLatch.await(timeout, unit); } /** * Live has notified this server that it is going to stop. */ - public void failOver(final ReplicationLiveIsStoppingMessage.LiveStopping finalMessage) - { - if (finalMessage == null) - { + public void failOver(final ReplicationLiveIsStoppingMessage.LiveStopping finalMessage) { + if (finalMessage == null) { backupQuorum.causeExit(FAILURE_REPLICATING); } - else - { + else { backupQuorum.failOver(finalMessage); } } - public ReplicationEndpoint getReplicationEndpoint() - { + public ReplicationEndpoint getReplicationEndpoint() { return replicationEndpoint; } - /** * Whether a remote backup server was in sync with its live server. If it was not in sync, it may * not take over the live's functions. @@ -418,13 +358,11 @@ public final class SharedNothingBackupActivation extends Activation * @return whether the backup is up-to-date, if the server is not a backup it always returns * {@code true}. */ - public boolean isRemoteBackupUpToDate() - { + public boolean isRemoteBackupUpToDate() { return backupUpToDate; } - public void setRemoteBackupUpToDate() - { + public void setRemoteBackupUpToDate() { activeMQServer.getBackupManager().announceBackup(); backupUpToDate = true; backupSyncLatch.countDown(); @@ -433,34 +371,26 @@ public final class SharedNothingBackupActivation extends Activation /** * @throws ActiveMQException */ - public void remoteFailOver(ReplicationLiveIsStoppingMessage.LiveStopping finalMessage) throws ActiveMQException - { + public void remoteFailOver(ReplicationLiveIsStoppingMessage.LiveStopping finalMessage) throws ActiveMQException { ActiveMQServerLogger.LOGGER.trace("Remote fail-over, got message=" + finalMessage + ", backupUpToDate=" + - backupUpToDate); - if (!activeMQServer.getHAPolicy().isBackup() || activeMQServer.getHAPolicy().isSharedStore()) - { + backupUpToDate); + if (!activeMQServer.getHAPolicy().isBackup() || activeMQServer.getHAPolicy().isSharedStore()) { throw new ActiveMQInternalErrorException(); } - if (!backupUpToDate) - { + if (!backupUpToDate) { failOver(null); } - else - { + else { failOver(finalMessage); } } + private class EndpointConnector implements Runnable { - - private class EndpointConnector implements Runnable - { @Override - public void run() - { - try - { + public void run() { + try { //we should only try once, if its not there we should move on. clusterControl.getSessionFactory().setReconnectAttempts(1); backupQuorum.setSessionFactory(clusterControl.getSessionFactory()); @@ -470,20 +400,17 @@ public final class SharedNothingBackupActivation extends Activation replicationEndpoint.start(); clusterControl.announceReplicatingBackupToLive(attemptFailBack, replicaPolicy.getClusterName()); } - catch (Exception e) - { + catch (Exception e) { //we shouldn't stop the server just mark the connector as tried and unavailable ActiveMQServerLogger.LOGGER.replicationStartProblem(e); backupQuorum.causeExit(FAILURE_REPLICATING); } } - private synchronized ReplicationEndpoint connectToReplicationEndpoint(final ClusterControl control) throws Exception - { + private synchronized ReplicationEndpoint connectToReplicationEndpoint(final ClusterControl control) throws Exception { if (!activeMQServer.isStarted()) return null; - if (!activeMQServer.getHAPolicy().isBackup()) - { + if (!activeMQServer.getHAPolicy().isBackup()) { throw ActiveMQMessageBundle.BUNDLE.serverNotBackupServer(); } @@ -491,8 +418,7 @@ public final class SharedNothingBackupActivation extends Activation replicationChannel.setHandler(replicationEndpoint); - if (replicationEndpoint.getChannel() != null) - { + if (replicationEndpoint.getChannel() != null) { throw ActiveMQMessageBundle.BUNDLE.alreadyHaveReplicationServer(); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/SharedNothingLiveActivation.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/SharedNothingLiveActivation.java index 601927cf50..50c45e66f2 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/SharedNothingLiveActivation.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/SharedNothingLiveActivation.java @@ -54,8 +54,8 @@ import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -public class SharedNothingLiveActivation extends LiveActivation -{ +public class SharedNothingLiveActivation extends LiveActivation { + //this is how we act when we initially start as a live private ReplicatedPolicy replicatedPolicy; @@ -65,34 +65,26 @@ public class SharedNothingLiveActivation extends LiveActivation private final Object replicationLock = new Object(); - public SharedNothingLiveActivation(ActiveMQServerImpl activeMQServer, - ReplicatedPolicy replicatedPolicy) - { + public SharedNothingLiveActivation(ActiveMQServerImpl activeMQServer, ReplicatedPolicy replicatedPolicy) { this.activeMQServer = activeMQServer; this.replicatedPolicy = replicatedPolicy; } @Override - public void freezeConnections(RemotingService remotingService) - { + public void freezeConnections(RemotingService remotingService) { ReplicationManager localReplicationManager = replicationManager; - if (remotingService != null && localReplicationManager != null) - { + if (remotingService != null && localReplicationManager != null) { remotingService.freeze(null, localReplicationManager.getBackupTransportConnection()); } - else if (remotingService != null) - { + else if (remotingService != null) { remotingService.freeze(null, null); } } - public void run() - { - try - { - if (replicatedPolicy.isCheckForLiveServer() && isNodeIdUsed()) - { + public void run() { + try { + if (replicatedPolicy.isCheckForLiveServer() && isNodeIdUsed()) { //set for when we failback replicatedPolicy.getReplicaPolicy().setReplicatedPolicy(replicatedPolicy); activeMQServer.setHAPolicy(replicatedPolicy.getReplicaPolicy()); @@ -105,44 +97,33 @@ public class SharedNothingLiveActivation extends LiveActivation activeMQServer.completeActivation(); - if (activeMQServer.getIdentity() != null) - { + if (activeMQServer.getIdentity() != null) { ActiveMQServerLogger.LOGGER.serverIsLive(activeMQServer.getIdentity()); } - else - { + else { ActiveMQServerLogger.LOGGER.serverIsLive(); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.initializationError(e); } } @Override - public ChannelHandler getActivationChannelHandler(final Channel channel, final Acceptor acceptorUsed) - { - return new ChannelHandler() - { + public ChannelHandler getActivationChannelHandler(final Channel channel, final Acceptor acceptorUsed) { + return new ChannelHandler() { @Override - public void handlePacket(Packet packet) - { - if (packet.getType() == PacketImpl.BACKUP_REGISTRATION) - { - BackupRegistrationMessage msg = (BackupRegistrationMessage)packet; + public void handlePacket(Packet packet) { + if (packet.getType() == PacketImpl.BACKUP_REGISTRATION) { + BackupRegistrationMessage msg = (BackupRegistrationMessage) packet; ClusterConnection clusterConnection = acceptorUsed.getClusterConnection(); - try - { - startReplication(channel.getConnection(), clusterConnection, getPair(msg.getConnector(), true), - msg.isFailBackRequest()); + try { + startReplication(channel.getConnection(), clusterConnection, getPair(msg.getConnector(), true), msg.isFailBackRequest()); } - catch (ActiveMQAlreadyReplicatingException are) - { + catch (ActiveMQAlreadyReplicatingException are) { channel.send(new BackupReplicationStartFailedMessage(BackupReplicationStartFailedMessage.BackupRegistrationProblem.ALREADY_REPLICATING)); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { ActiveMQServerLogger.LOGGER.debug("Failed to process backup registration packet", e); channel.send(new BackupReplicationStartFailedMessage(BackupReplicationStartFailedMessage.BackupRegistrationProblem.EXCEPTION)); } @@ -151,24 +132,21 @@ public class SharedNothingLiveActivation extends LiveActivation }; } - public void startReplication(CoreRemotingConnection rc, final ClusterConnection clusterConnection, - final Pair pair, final boolean isFailBackRequest) throws ActiveMQException - { - if (replicationManager != null) - { + public void startReplication(CoreRemotingConnection rc, + final ClusterConnection clusterConnection, + final Pair pair, + final boolean isFailBackRequest) throws ActiveMQException { + if (replicationManager != null) { throw new ActiveMQAlreadyReplicatingException(); } - if (!activeMQServer.isStarted()) - { + if (!activeMQServer.isStarted()) { throw new ActiveMQIllegalStateException(); } - synchronized (replicationLock) - { + synchronized (replicationLock) { - if (replicationManager != null) - { + if (replicationManager != null) { throw new ActiveMQAlreadyReplicatingException(); } ReplicationFailureListener listener = new ReplicationFailureListener(); @@ -176,58 +154,45 @@ public class SharedNothingLiveActivation extends LiveActivation rc.addFailureListener(listener); replicationManager = new ReplicationManager(rc, activeMQServer.getExecutorFactory()); replicationManager.start(); - Thread t = new Thread(new Runnable() - { - public void run() - { - try - { - activeMQServer.getStorageManager().startReplication(replicationManager, activeMQServer.getPagingManager(), activeMQServer.getNodeID().toString(), - isFailBackRequest && replicatedPolicy.isAllowAutoFailBack()); + Thread t = new Thread(new Runnable() { + public void run() { + try { + activeMQServer.getStorageManager().startReplication(replicationManager, activeMQServer.getPagingManager(), activeMQServer.getNodeID().toString(), isFailBackRequest && replicatedPolicy.isAllowAutoFailBack()); clusterConnection.nodeAnnounced(System.currentTimeMillis(), activeMQServer.getNodeID().toString(), replicatedPolicy.getGroupName(), replicatedPolicy.getScaleDownGroupName(), pair, true); //todo, check why this was set here //backupUpToDate = false; - if (isFailBackRequest && replicatedPolicy.isAllowAutoFailBack()) - { + if (isFailBackRequest && replicatedPolicy.isAllowAutoFailBack()) { BackupTopologyListener listener1 = new BackupTopologyListener(activeMQServer.getNodeID().toString()); clusterConnection.addClusterTopologyListener(listener1); - if (listener1.waitForBackup()) - { - try - { + if (listener1.waitForBackup()) { + try { Thread.sleep(replicatedPolicy.getFailbackDelay()); } - catch (InterruptedException e) - { + catch (InterruptedException e) { // } //if we have to many backups kept or arent configured to restart just stop, otherwise restart as a backup - if (!replicatedPolicy.getReplicaPolicy().isRestartBackup() && activeMQServer.countNumberOfCopiedJournals() >= replicatedPolicy.getReplicaPolicy().getMaxSavedReplicatedJournalsSize() && replicatedPolicy.getReplicaPolicy().getMaxSavedReplicatedJournalsSize() >= 0) - { + if (!replicatedPolicy.getReplicaPolicy().isRestartBackup() && activeMQServer.countNumberOfCopiedJournals() >= replicatedPolicy.getReplicaPolicy().getMaxSavedReplicatedJournalsSize() && replicatedPolicy.getReplicaPolicy().getMaxSavedReplicatedJournalsSize() >= 0) { activeMQServer.stop(true); ActiveMQServerLogger.LOGGER.stopReplicatedBackupAfterFailback(); } - else - { + else { activeMQServer.stop(true); ActiveMQServerLogger.LOGGER.restartingReplicatedBackupAfterFailback(); activeMQServer.setHAPolicy(replicatedPolicy.getReplicaPolicy()); activeMQServer.start(); } } - else - { + else { ActiveMQServerLogger.LOGGER.failbackMissedBackupAnnouncement(); } } } - catch (Exception e) - { - if (activeMQServer.getState() == ActiveMQServerImpl.SERVER_STATE.STARTED) - { + catch (Exception e) { + if (activeMQServer.getState() == ActiveMQServerImpl.SERVER_STATE.STARTED) { /* * The reasoning here is that the exception was either caused by (1) the * (interaction with) the backup, or (2) by an IO Error at the storage. If (1), we @@ -236,18 +201,14 @@ public class SharedNothingLiveActivation extends LiveActivation */ ActiveMQServerLogger.LOGGER.errorStartingReplication(e); } - try - { + try { ActiveMQServerImpl.stopComponent(replicationManager); } - catch (Exception amqe) - { + catch (Exception amqe) { ActiveMQServerLogger.LOGGER.errorStoppingReplication(amqe); } - finally - { - synchronized (replicationLock) - { + finally { + synchronized (replicationLock) { replicationManager = null; } } @@ -259,32 +220,24 @@ public class SharedNothingLiveActivation extends LiveActivation } } - private final class ReplicationFailureListener implements FailureListener, CloseListener - { + private final class ReplicationFailureListener implements FailureListener, CloseListener { @Override - public void connectionFailed(ActiveMQException exception, boolean failedOver) - { + public void connectionFailed(ActiveMQException exception, boolean failedOver) { connectionClosed(); } @Override - public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) { connectionFailed(me, failedOver); } @Override - public void connectionClosed() - { - activeMQServer.getThreadPool().execute(new Runnable() - { - public void run() - { - synchronized (replicationLock) - { - if (replicationManager != null) - { + public void connectionClosed() { + activeMQServer.getThreadPool().execute(new Runnable() { + public void run() { + synchronized (replicationLock) { + if (replicationManager != null) { activeMQServer.getStorageManager().stopReplication(); replicationManager = null; } @@ -294,15 +247,13 @@ public class SharedNothingLiveActivation extends LiveActivation } } - private Pair getPair(TransportConfiguration conn, - boolean isBackup) - { - if (isBackup) - { + private Pair getPair(TransportConfiguration conn, boolean isBackup) { + if (isBackup) { return new Pair<>(null, conn); } return new Pair<>(conn, null); } + /** * Determines whether there is another server already running with this server's nodeID. *

    @@ -311,17 +262,14 @@ public class SharedNothingLiveActivation extends LiveActivation * * @throws Exception */ - private boolean isNodeIdUsed() throws Exception - { + private boolean isNodeIdUsed() throws Exception { if (activeMQServer.getConfiguration().getClusterConfigurations().isEmpty()) return false; SimpleString nodeId0; - try - { + try { nodeId0 = activeMQServer.getNodeManager().readNodeId(); } - catch (ActiveMQIllegalStateException e) - { + catch (ActiveMQIllegalStateException e) { nodeId0 = null; } @@ -336,16 +284,13 @@ public class SharedNothingLiveActivation extends LiveActivation NodeIdListener listener = new NodeIdListener(nodeId0); locator.addClusterTopologyListener(listener); - try - { + try { locator.setReconnectAttempts(0); - try - { + try { locator.addClusterTopologyListener(listener); factory = locator.connectNoWarnings(); } - catch (Exception notConnected) - { + catch (Exception notConnected) { return false; } @@ -353,8 +298,7 @@ public class SharedNothingLiveActivation extends LiveActivation return listener.isNodePresent; } - finally - { + finally { if (factory != null) factory.close(); if (locator != null) @@ -362,124 +306,99 @@ public class SharedNothingLiveActivation extends LiveActivation } } - public void close(boolean permanently, boolean restarting) throws Exception - { + public void close(boolean permanently, boolean restarting) throws Exception { replicationManager = null; // To avoid a NPE cause by the stop NodeManager nodeManagerInUse = activeMQServer.getNodeManager(); - if (nodeManagerInUse != null) - { + if (nodeManagerInUse != null) { //todo does this actually make any difference, we only set a different flag in the lock file which replication doesnt use - if (permanently) - { + if (permanently) { nodeManagerInUse.crashLiveServer(); } - else - { + else { nodeManagerInUse.pauseLiveServer(); } } } @Override - public void sendLiveIsStopping() - { + public void sendLiveIsStopping() { final ReplicationManager localReplicationManager = replicationManager; - if (localReplicationManager != null) - { + if (localReplicationManager != null) { localReplicationManager.sendLiveIsStopping(ReplicationLiveIsStoppingMessage.LiveStopping.STOP_CALLED); // Schedule for 10 seconds // this pool gets a 'hard' shutdown, no need to manage the Future of this Runnable. - activeMQServer.getScheduledPool().schedule(new Runnable() - { + activeMQServer.getScheduledPool().schedule(new Runnable() { @Override - public void run() - { + public void run() { localReplicationManager.clearReplicationTokens(); } }, 30, TimeUnit.SECONDS); } } - public ReplicationManager getReplicationManager() - { - synchronized (replicationLock) - { + public ReplicationManager getReplicationManager() { + synchronized (replicationLock) { return replicationManager; } } - private ServerLocatorInternal getLocator(ClusterConnectionConfiguration config) throws ActiveMQException - { + private ServerLocatorInternal getLocator(ClusterConnectionConfiguration config) throws ActiveMQException { ServerLocatorInternal locator; - if (config.getDiscoveryGroupName() != null) - { + if (config.getDiscoveryGroupName() != null) { DiscoveryGroupConfiguration dg = activeMQServer.getConfiguration().getDiscoveryGroupConfigurations().get(config.getDiscoveryGroupName()); - if (dg == null) - { + if (dg == null) { throw ActiveMQMessageBundle.BUNDLE.noDiscoveryGroupFound(dg); } locator = (ServerLocatorInternal) ActiveMQClient.createServerLocatorWithHA(dg); } - else - { - TransportConfiguration[] tcConfigs = config.getStaticConnectors() != null ? connectorNameListToArray(config.getStaticConnectors()) - : null; + else { + TransportConfiguration[] tcConfigs = config.getStaticConnectors() != null ? connectorNameListToArray(config.getStaticConnectors()) : null; locator = (ServerLocatorInternal) ActiveMQClient.createServerLocatorWithHA(tcConfigs); } return locator; } + static final class NodeIdListener implements ClusterTopologyListener { - static final class NodeIdListener implements ClusterTopologyListener - { volatile boolean isNodePresent = false; private final SimpleString nodeId; private final CountDownLatch latch = new CountDownLatch(1); - public NodeIdListener(SimpleString nodeId) - { + public NodeIdListener(SimpleString nodeId) { this.nodeId = nodeId; } @Override - public void nodeUP(TopologyMember topologyMember, boolean last) - { + public void nodeUP(TopologyMember topologyMember, boolean last) { boolean isOurNodeId = nodeId != null && nodeId.toString().equals(topologyMember.getNodeId()); - if (isOurNodeId) - { + if (isOurNodeId) { isNodePresent = true; } - if (isOurNodeId || last) - { + if (isOurNodeId || last) { latch.countDown(); } } @Override - public void nodeDown(long eventUID, String nodeID) - { + public void nodeDown(long eventUID, String nodeID) { // no-op } } - private TransportConfiguration[] connectorNameListToArray(final List connectorNames) - { - TransportConfiguration[] tcConfigs = (TransportConfiguration[]) Array.newInstance(TransportConfiguration.class, - connectorNames.size()); + private TransportConfiguration[] connectorNameListToArray(final List connectorNames) { + TransportConfiguration[] tcConfigs = (TransportConfiguration[]) Array.newInstance(TransportConfiguration.class, connectorNames.size()); int count = 0; - for (String connectorName : connectorNames) - { + for (String connectorName : connectorNames) { TransportConfiguration connector = activeMQServer.getConfiguration().getConnectorConfigurations().get(connectorName); - if (connector == null) - { + if (connector == null) { ActiveMQServerLogger.LOGGER.bridgeNoConnector(connectorName); return null; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/SharedStoreBackupActivation.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/SharedStoreBackupActivation.java index 18692d2f8e..e556b5d05c 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/SharedStoreBackupActivation.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/SharedStoreBackupActivation.java @@ -33,8 +33,8 @@ import org.apache.activemq.artemis.core.server.management.ManagementService; import java.nio.channels.ClosedChannelException; import java.util.concurrent.TimeUnit; -public final class SharedStoreBackupActivation extends Activation -{ +public final class SharedStoreBackupActivation extends Activation { + //this is how we act as a backup private SharedStoreSlavePolicy sharedStoreSlavePolicy; @@ -44,20 +44,16 @@ public final class SharedStoreBackupActivation extends Activation private boolean cancelFailBackChecker; - public SharedStoreBackupActivation(ActiveMQServerImpl server, SharedStoreSlavePolicy sharedStoreSlavePolicy) - { + public SharedStoreBackupActivation(ActiveMQServerImpl server, SharedStoreSlavePolicy sharedStoreSlavePolicy) { this.activeMQServer = server; this.sharedStoreSlavePolicy = sharedStoreSlavePolicy; - synchronized (failbackCheckerGuard) - { + synchronized (failbackCheckerGuard) { cancelFailBackChecker = false; } } - public void run() - { - try - { + public void run() { + try { activeMQServer.getNodeManager().startBackup(); ScaleDownPolicy scaleDownPolicy = sharedStoreSlavePolicy.getScaleDownPolicy(); @@ -82,8 +78,7 @@ public final class SharedStoreBackupActivation extends Activation //activeMQServer.configuration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE); activeMQServer.getBackupManager().activated(); - if (activeMQServer.getState() != ActiveMQServerImpl.SERVER_STATE.STARTED) - { + if (activeMQServer.getState() != ActiveMQServerImpl.SERVER_STATE.STARTED) { return; } @@ -91,25 +86,19 @@ public final class SharedStoreBackupActivation extends Activation activeMQServer.completeActivation(); - if (scalingDown) - { + if (scalingDown) { ActiveMQServerLogger.LOGGER.backupServerScaledDown(); - Thread t = new Thread(new Runnable() - { + Thread t = new Thread(new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { activeMQServer.stop(); //we are shared store but if we were started by a parent server then we shouldn't restart - if (sharedStoreSlavePolicy.isRestartBackup()) - { + if (sharedStoreSlavePolicy.isRestartBackup()) { activeMQServer.start(); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.serverRestartWarning(); } } @@ -117,44 +106,34 @@ public final class SharedStoreBackupActivation extends Activation t.start(); return; } - else - { + else { ActiveMQServerLogger.LOGGER.backupServerIsLive(); activeMQServer.getNodeManager().releaseBackup(); } - if (sharedStoreSlavePolicy.isAllowAutoFailBack()) - { + if (sharedStoreSlavePolicy.isAllowAutoFailBack()) { startFailbackChecker(); } } - catch (InterruptedException e) - { + catch (InterruptedException e) { // this is ok, we are being stopped } - catch (ClosedChannelException e) - { + catch (ClosedChannelException e) { // this is ok too, we are being stopped } - catch (Exception e) - { - if (!(e.getCause() instanceof InterruptedException)) - { + catch (Exception e) { + if (!(e.getCause() instanceof InterruptedException)) { ActiveMQServerLogger.LOGGER.initializationError(e); } } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQServerLogger.LOGGER.initializationError(e); } } - public void close(boolean permanently, boolean restarting) throws Exception - { - if (!restarting) - { - synchronized (failbackCheckerGuard) - { + public void close(boolean permanently, boolean restarting) throws Exception { + if (!restarting) { + synchronized (failbackCheckerGuard) { cancelFailBackChecker = true; } } @@ -162,31 +141,24 @@ public final class SharedStoreBackupActivation extends Activation NodeManager nodeManagerInUse = activeMQServer.getNodeManager(); //we need to check as the servers policy may have changed - if (activeMQServer.getHAPolicy().isBackup()) - { + if (activeMQServer.getHAPolicy().isBackup()) { activeMQServer.interrupBackupThread(nodeManagerInUse); - - if (nodeManagerInUse != null) - { + if (nodeManagerInUse != null) { nodeManagerInUse.stopBackup(); } } - else - { + else { - if (nodeManagerInUse != null) - { + if (nodeManagerInUse != null) { // if we are now live, behave as live // We need to delete the file too, otherwise the backup will failover when we shutdown or if the backup is // started before the live - if (sharedStoreSlavePolicy.isFailoverOnServerShutdown() || permanently) - { + if (sharedStoreSlavePolicy.isFailoverOnServerShutdown() || permanently) { nodeManagerInUse.crashLiveServer(); } - else - { + else { nodeManagerInUse.pauseLiveServer(); } } @@ -194,80 +166,58 @@ public final class SharedStoreBackupActivation extends Activation } @Override - public JournalLoader createJournalLoader(PostOffice postOffice, PagingManager pagingManager, StorageManager storageManager, QueueFactory queueFactory, NodeManager nodeManager, ManagementService managementService, GroupingHandler groupingHandler, Configuration configuration, ActiveMQServer parentServer) throws ActiveMQException - { - if (sharedStoreSlavePolicy.getScaleDownPolicy() != null && sharedStoreSlavePolicy.getScaleDownPolicy().isEnabled()) - { - return new BackupRecoveryJournalLoader(postOffice, - pagingManager, - storageManager, - queueFactory, - nodeManager, - managementService, - groupingHandler, - configuration, - parentServer, - ScaleDownPolicy.getScaleDownConnector(sharedStoreSlavePolicy.getScaleDownPolicy(), activeMQServer), - activeMQServer.getClusterManager().getClusterController()); + public JournalLoader createJournalLoader(PostOffice postOffice, + PagingManager pagingManager, + StorageManager storageManager, + QueueFactory queueFactory, + NodeManager nodeManager, + ManagementService managementService, + GroupingHandler groupingHandler, + Configuration configuration, + ActiveMQServer parentServer) throws ActiveMQException { + if (sharedStoreSlavePolicy.getScaleDownPolicy() != null && sharedStoreSlavePolicy.getScaleDownPolicy().isEnabled()) { + return new BackupRecoveryJournalLoader(postOffice, pagingManager, storageManager, queueFactory, nodeManager, managementService, groupingHandler, configuration, parentServer, ScaleDownPolicy.getScaleDownConnector(sharedStoreSlavePolicy.getScaleDownPolicy(), activeMQServer), activeMQServer.getClusterManager().getClusterController()); } - else - { - return super.createJournalLoader(postOffice, - pagingManager, - storageManager, - queueFactory, - nodeManager, - managementService, - groupingHandler, - configuration, - parentServer); + else { + return super.createJournalLoader(postOffice, pagingManager, storageManager, queueFactory, nodeManager, managementService, groupingHandler, configuration, parentServer); } } /** * To be called by backup trying to fail back the server */ - private void startFailbackChecker() - { + private void startFailbackChecker() { activeMQServer.getScheduledPool().scheduleAtFixedRate(new FailbackChecker(), 1000L, 1000L, TimeUnit.MILLISECONDS); } - private class FailbackChecker implements Runnable - { + + private class FailbackChecker implements Runnable { + private boolean restarting = false; - public void run() - { - try - { - if (!restarting && activeMQServer.getNodeManager().isAwaitingFailback()) - { + public void run() { + try { + if (!restarting && activeMQServer.getNodeManager().isAwaitingFailback()) { ActiveMQServerLogger.LOGGER.awaitFailBack(); restarting = true; - Thread t = new Thread(new Runnable() - { - public void run() - { - try - { + Thread t = new Thread(new Runnable() { + public void run() { + try { ActiveMQServerLogger.LOGGER.debug(activeMQServer + "::Stopping live node in favor of failback"); activeMQServer.stop(true, false, true); // We need to wait some time before we start the backup again // otherwise we may eventually start before the live had a chance to get it Thread.sleep(sharedStoreSlavePolicy.getFailbackDelay()); - synchronized (failbackCheckerGuard) - { + synchronized (failbackCheckerGuard) { if (cancelFailBackChecker || !sharedStoreSlavePolicy.isRestartBackup()) return; activeMQServer.setHAPolicy(sharedStoreSlavePolicy); - ActiveMQServerLogger.LOGGER.debug(activeMQServer + - "::Starting backup node now after failback"); + ActiveMQServerLogger.LOGGER.debug(activeMQServer + "::Starting backup node now after failback"); activeMQServer.start(); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.serverRestartWarning(); } } @@ -275,8 +225,7 @@ public final class SharedStoreBackupActivation extends Activation t.start(); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.serverRestartWarning(e); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/SharedStoreLiveActivation.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/SharedStoreLiveActivation.java index e9b67b8c81..95c24ab7db 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/SharedStoreLiveActivation.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/SharedStoreLiveActivation.java @@ -20,43 +20,37 @@ import org.apache.activemq.artemis.core.server.ActiveMQServerLogger; import org.apache.activemq.artemis.core.server.NodeManager; import org.apache.activemq.artemis.core.server.cluster.ha.SharedStoreMasterPolicy; -public final class SharedStoreLiveActivation extends LiveActivation -{ +public final class SharedStoreLiveActivation extends LiveActivation { + //this is how we act when we initially start as live private SharedStoreMasterPolicy sharedStoreMasterPolicy; private ActiveMQServerImpl activeMQServer; - public SharedStoreLiveActivation(ActiveMQServerImpl server, SharedStoreMasterPolicy sharedStoreMasterPolicy) - { + public SharedStoreLiveActivation(ActiveMQServerImpl server, SharedStoreMasterPolicy sharedStoreMasterPolicy) { this.activeMQServer = server; this.sharedStoreMasterPolicy = sharedStoreMasterPolicy; } - public void run() - { - try - { + public void run() { + try { ActiveMQServerLogger.LOGGER.awaitingLiveLock(); activeMQServer.checkJournalDirectory(); - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("First part initialization on " + this); } if (!activeMQServer.initialisePart1(false)) return; - if (activeMQServer.getNodeManager().isBackupLive()) - { + if (activeMQServer.getNodeManager().isBackupLive()) { /* * looks like we've failed over at some point need to inform that we are the backup * so when the current live goes down they failover to us */ - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("announcing backup to the former live" + this); } activeMQServer.getBackupManager().start(); @@ -66,8 +60,7 @@ public final class SharedStoreLiveActivation extends LiveActivation activeMQServer.getNodeManager().startLiveNode(); - if (activeMQServer.getState() == ActiveMQServerImpl.SERVER_STATE.STOPPED || activeMQServer.getState() == ActiveMQServerImpl.SERVER_STATE.STOPPING) - { + if (activeMQServer.getState() == ActiveMQServerImpl.SERVER_STATE.STOPPED || activeMQServer.getState() == ActiveMQServerImpl.SERVER_STATE.STOPPING) { return; } @@ -77,25 +70,20 @@ public final class SharedStoreLiveActivation extends LiveActivation ActiveMQServerLogger.LOGGER.serverIsLive(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.initializationError(e); } } - public void close(boolean permanently, boolean restarting) throws Exception - { + public void close(boolean permanently, boolean restarting) throws Exception { // TO avoid a NPE from stop NodeManager nodeManagerInUse = activeMQServer.getNodeManager(); - if (nodeManagerInUse != null) - { - if (sharedStoreMasterPolicy.isFailoverOnServerShutdown() || permanently) - { + if (nodeManagerInUse != null) { + if (sharedStoreMasterPolicy.isFailoverOnServerShutdown() || permanently) { nodeManagerInUse.crashLiveServer(); } - else - { + else { nodeManagerInUse.pauseLiveServer(); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/TransientQueueManagerImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/TransientQueueManagerImpl.java index 7af64f6ef1..cec94bd0c5 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/TransientQueueManagerImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/TransientQueueManagerImpl.java @@ -23,34 +23,27 @@ import org.apache.activemq.artemis.core.server.ActiveMQServerLogger; import org.apache.activemq.artemis.core.server.TransientQueueManager; import org.apache.activemq.artemis.utils.ReferenceCounterUtil; -public class TransientQueueManagerImpl implements TransientQueueManager -{ +public class TransientQueueManagerImpl implements TransientQueueManager { + private final SimpleString queueName; private final ActiveMQServer server; - private final Runnable runnable = new Runnable() - { - public void run() - { - try - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + private final Runnable runnable = new Runnable() { + public void run() { + try { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("deleting temporary queue " + queueName); } - try - { + try { server.destroyQueue(queueName, null, false); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { ActiveMQServerLogger.LOGGER.warn("Error on deleting queue " + queueName + ", " + e.getMessage(), e); } } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorRemovingTempQueue(e, queueName); } } @@ -58,28 +51,24 @@ public class TransientQueueManagerImpl implements TransientQueueManager private final ReferenceCounterUtil referenceCounterUtil = new ReferenceCounterUtil(runnable); - public TransientQueueManagerImpl(ActiveMQServer server, SimpleString queueName) - { + public TransientQueueManagerImpl(ActiveMQServer server, SimpleString queueName) { this.server = server; this.queueName = queueName; } @Override - public int increment() - { + public int increment() { return referenceCounterUtil.increment(); } @Override - public int decrement() - { + public int decrement() { return referenceCounterUtil.decrement(); } @Override - public SimpleString getQueueName() - { + public SimpleString getQueueName() { return queueName; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/management/ManagementService.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/management/ManagementService.java index e13fe812ac..3e77d152b7 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/management/ManagementService.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/management/ManagementService.java @@ -50,8 +50,7 @@ import org.apache.activemq.artemis.core.settings.impl.AddressSettings; import org.apache.activemq.artemis.core.transaction.ResourceManager; import org.apache.activemq.artemis.spi.core.remoting.Acceptor; -public interface ManagementService extends NotificationService, ActiveMQComponent -{ +public interface ManagementService extends NotificationService, ActiveMQComponent { // Configuration MessageCounterManager getMessageCounterManager(); @@ -67,17 +66,17 @@ public interface ManagementService extends NotificationService, ActiveMQComponen void setStorageManager(StorageManager storageManager); ActiveMQServerControlImpl registerServer(final PostOffice postOffice, - final StorageManager storageManager, - final Configuration configuration, - final HierarchicalRepository addressSettingsRepository, - final HierarchicalRepository> securityRepository, - final ResourceManager resourceManager, - final RemotingService remotingService, - final ActiveMQServer messagingServer, - final QueueFactory queueFactory, - final ScheduledExecutorService scheduledThreadPool, - final PagingManager pagingManager, - final boolean backup) throws Exception; + final StorageManager storageManager, + final Configuration configuration, + final HierarchicalRepository addressSettingsRepository, + final HierarchicalRepository> securityRepository, + final ResourceManager resourceManager, + final RemotingService remotingService, + final ActiveMQServer messagingServer, + final QueueFactory queueFactory, + final ScheduledExecutorService scheduledThreadPool, + final PagingManager pagingManager, + final boolean backup) throws Exception; void unregisterServer() throws Exception; @@ -105,11 +104,12 @@ public interface ManagementService extends NotificationService, ActiveMQComponen void unregisterDivert(SimpleString name) throws Exception; - void registerBroadcastGroup(BroadcastGroup broadcastGroup, BroadcastGroupConfiguration configuration) throws Exception; + void registerBroadcastGroup(BroadcastGroup broadcastGroup, + BroadcastGroupConfiguration configuration) throws Exception; void unregisterBroadcastGroup(String name) throws Exception; - // void registerDiscoveryGroup(DiscoveryGroup discoveryGroup, DiscoveryGroupConfiguration configuration) throws Exception; + // void registerDiscoveryGroup(DiscoveryGroup discoveryGroup, DiscoveryGroupConfiguration configuration) throws Exception; //void unregisterDiscoveryGroup(String name) throws Exception; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/management/impl/ManagementServiceImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/management/impl/ManagementServiceImpl.java index 1b10a5220c..e95258c8ec 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/management/impl/ManagementServiceImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/management/impl/ManagementServiceImpl.java @@ -85,8 +85,7 @@ import org.apache.activemq.artemis.spi.core.remoting.Acceptor; import org.apache.activemq.artemis.utils.ConcurrentHashSet; import org.apache.activemq.artemis.utils.TypedProperties; -public class ManagementServiceImpl implements ManagementService -{ +public class ManagementServiceImpl implements ManagementService { // Constants ----------------------------------------------------- private static final boolean isTrace = ActiveMQServerLogger.LOGGER.isTraceEnabled(); @@ -133,8 +132,7 @@ public class ManagementServiceImpl implements ManagementService // Constructor ---------------------------------------------------- - public ManagementServiceImpl(final MBeanServer mbeanServer, final Configuration configuration) - { + public ManagementServiceImpl(final MBeanServer mbeanServer, final Configuration configuration) { this.mbeanServer = mbeanServer; jmxManagementEnabled = configuration.isJMXManagementEnabled(); messageCounterEnabled = configuration.isMessageCounterEnabled(); @@ -151,34 +149,30 @@ public class ManagementServiceImpl implements ManagementService // ManagementService implementation ------------------------- - public ObjectNameBuilder getObjectNameBuilder() - { + public ObjectNameBuilder getObjectNameBuilder() { return objectNameBuilder; } - public MessageCounterManager getMessageCounterManager() - { + public MessageCounterManager getMessageCounterManager() { return messageCounterManager; } - public void setStorageManager(final StorageManager storageManager) - { + public void setStorageManager(final StorageManager storageManager) { this.storageManager = storageManager; } public ActiveMQServerControlImpl registerServer(final PostOffice postOffice, - final StorageManager storageManager1, - final Configuration configuration, - final HierarchicalRepository addressSettingsRepository, - final HierarchicalRepository> securityRepository, - final ResourceManager resourceManager, - final RemotingService remotingService, - final ActiveMQServer messagingServer, - final QueueFactory queueFactory, - final ScheduledExecutorService scheduledThreadPool, - final PagingManager pagingManager, - final boolean backup) throws Exception - { + final StorageManager storageManager1, + final Configuration configuration, + final HierarchicalRepository addressSettingsRepository, + final HierarchicalRepository> securityRepository, + final ResourceManager resourceManager, + final RemotingService remotingService, + final ActiveMQServer messagingServer, + final QueueFactory queueFactory, + final ScheduledExecutorService scheduledThreadPool, + final PagingManager pagingManager, + final boolean backup) throws Exception { this.postOffice = postOffice; this.addressSettingsRepository = addressSettingsRepository; this.securityRepository = securityRepository; @@ -190,14 +184,7 @@ public class ManagementServiceImpl implements ManagementService messageCounterManager.setMaxDayCount(configuration.getMessageCounterMaxDayHistory()); messageCounterManager.reschedule(configuration.getMessageCounterSamplePeriod()); - messagingServerControl = new ActiveMQServerControlImpl(postOffice, - configuration, - resourceManager, - remotingService, - messagingServer, - messageCounterManager, - storageManager1, - broadcaster); + messagingServerControl = new ActiveMQServerControlImpl(postOffice, configuration, resourceManager, remotingService, messagingServer, messageCounterManager, storageManager1, broadcaster); ObjectName objectName = objectNameBuilder.getActiveMQServerObjectName(); registerInJMX(objectName, messagingServerControl); registerInRegistry(ResourceNames.CORE_SERVER, messagingServerControl); @@ -205,34 +192,26 @@ public class ManagementServiceImpl implements ManagementService return messagingServerControl; } - public synchronized void unregisterServer() throws Exception - { + public synchronized void unregisterServer() throws Exception { ObjectName objectName = objectNameBuilder.getActiveMQServerObjectName(); unregisterFromJMX(objectName); unregisterFromRegistry(ResourceNames.CORE_SERVER); } - public synchronized void registerAddress(final SimpleString address) throws Exception - { + public synchronized void registerAddress(final SimpleString address) throws Exception { ObjectName objectName = objectNameBuilder.getAddressObjectName(address); - AddressControlImpl addressControl = new AddressControlImpl(address, - postOffice, - pagingManager, - storageManager, - securityRepository); + AddressControlImpl addressControl = new AddressControlImpl(address, postOffice, pagingManager, storageManager, securityRepository); registerInJMX(objectName, addressControl); registerInRegistry(ResourceNames.CORE_ADDRESS + address, addressControl); - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("registered address " + objectName); } } - public synchronized void unregisterAddress(final SimpleString address) throws Exception - { + public synchronized void unregisterAddress(final SimpleString address) throws Exception { ObjectName objectName = objectNameBuilder.getAddressObjectName(address); unregisterFromJMX(objectName); @@ -241,21 +220,10 @@ public class ManagementServiceImpl implements ManagementService public synchronized void registerQueue(final Queue queue, final SimpleString address, - final StorageManager storageManager) throws Exception - { - QueueControlImpl queueControl = new QueueControlImpl(queue, - address.toString(), - postOffice, - storageManager, - addressSettingsRepository); - if (messageCounterManager != null) - { - MessageCounter counter = new MessageCounter(queue.getName().toString(), - null, - queue, - false, - queue.isDurable(), - messageCounterManager.getMaxDayCount()); + final StorageManager storageManager) throws Exception { + QueueControlImpl queueControl = new QueueControlImpl(queue, address.toString(), postOffice, storageManager, addressSettingsRepository); + if (messageCounterManager != null) { + MessageCounter counter = new MessageCounter(queue.getName().toString(), null, queue, false, queue.isDurable(), messageCounterManager.getMaxDayCount()); queueControl.setMessageCounter(counter); messageCounterManager.registerMessageCounter(queue.getName().toString(), counter); } @@ -263,86 +231,72 @@ public class ManagementServiceImpl implements ManagementService registerInJMX(objectName, queueControl); registerInRegistry(ResourceNames.CORE_QUEUE + queue.getName(), queueControl); - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("registered queue " + objectName); } } - public synchronized void unregisterQueue(final SimpleString name, final SimpleString address) throws Exception - { + public synchronized void unregisterQueue(final SimpleString name, final SimpleString address) throws Exception { ObjectName objectName = objectNameBuilder.getQueueObjectName(address, name); unregisterFromJMX(objectName); unregisterFromRegistry(ResourceNames.CORE_QUEUE + name); messageCounterManager.unregisterMessageCounter(name.toString()); } - public synchronized void registerDivert(final Divert divert, final DivertConfiguration config) throws Exception - { + public synchronized void registerDivert(final Divert divert, final DivertConfiguration config) throws Exception { ObjectName objectName = objectNameBuilder.getDivertObjectName(divert.getUniqueName().toString()); DivertControl divertControl = new DivertControlImpl(divert, storageManager, config); registerInJMX(objectName, new StandardMBean(divertControl, DivertControl.class)); registerInRegistry(ResourceNames.CORE_DIVERT + config.getName(), divertControl); - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("registered divert " + objectName); } } - public synchronized void unregisterDivert(final SimpleString name) throws Exception - { + public synchronized void unregisterDivert(final SimpleString name) throws Exception { ObjectName objectName = objectNameBuilder.getDivertObjectName(name.toString()); unregisterFromJMX(objectName); unregisterFromRegistry(ResourceNames.CORE_DIVERT + name); } - public synchronized void registerAcceptor(final Acceptor acceptor, final TransportConfiguration configuration) throws Exception - { + public synchronized void registerAcceptor(final Acceptor acceptor, + final TransportConfiguration configuration) throws Exception { ObjectName objectName = objectNameBuilder.getAcceptorObjectName(configuration.getName()); AcceptorControl control = new AcceptorControlImpl(acceptor, storageManager, configuration); registerInJMX(objectName, new StandardMBean(control, AcceptorControl.class)); registerInRegistry(ResourceNames.CORE_ACCEPTOR + configuration.getName(), control); } - public void unregisterAcceptors() - { + public void unregisterAcceptors() { List acceptors = new ArrayList(); - synchronized (this) - { - for (String resourceName : registry.keySet()) - { - if (resourceName.startsWith(ResourceNames.CORE_ACCEPTOR)) - { + synchronized (this) { + for (String resourceName : registry.keySet()) { + if (resourceName.startsWith(ResourceNames.CORE_ACCEPTOR)) { acceptors.add(resourceName); } } } - for (String acceptor : acceptors) - { + for (String acceptor : acceptors) { String name = acceptor.substring(ResourceNames.CORE_ACCEPTOR.length()); - try - { + try { unregisterAcceptor(name); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } } - public synchronized void unregisterAcceptor(final String name) throws Exception - { + public synchronized void unregisterAcceptor(final String name) throws Exception { ObjectName objectName = objectNameBuilder.getAcceptorObjectName(name); unregisterFromJMX(objectName); unregisterFromRegistry(ResourceNames.CORE_ACCEPTOR + name); } public synchronized void registerBroadcastGroup(final BroadcastGroup broadcastGroup, - final BroadcastGroupConfiguration configuration) throws Exception - { + final BroadcastGroupConfiguration configuration) throws Exception { broadcastGroup.setNotificationService(this); ObjectName objectName = objectNameBuilder.getBroadcastGroupObjectName(configuration.getName()); BroadcastGroupControl control = new BroadcastGroupControlImpl(broadcastGroup, storageManager, configuration); @@ -350,15 +304,14 @@ public class ManagementServiceImpl implements ManagementService registerInRegistry(ResourceNames.CORE_BROADCAST_GROUP + configuration.getName(), control); } - public synchronized void unregisterBroadcastGroup(final String name) throws Exception - { + public synchronized void unregisterBroadcastGroup(final String name) throws Exception { ObjectName objectName = objectNameBuilder.getBroadcastGroupObjectName(name); unregisterFromJMX(objectName); unregisterFromRegistry(ResourceNames.CORE_BROADCAST_GROUP + name); } - public synchronized void registerBridge(final Bridge bridge, final BridgeConfiguration configuration) throws Exception - { + public synchronized void registerBridge(final Bridge bridge, + final BridgeConfiguration configuration) throws Exception { bridge.setNotificationService(this); ObjectName objectName = objectNameBuilder.getBridgeObjectName(configuration.getName()); BridgeControl control = new BridgeControlImpl(bridge, storageManager, configuration); @@ -366,99 +319,82 @@ public class ManagementServiceImpl implements ManagementService registerInRegistry(ResourceNames.CORE_BRIDGE + configuration.getName(), control); } - public synchronized void unregisterBridge(final String name) throws Exception - { + public synchronized void unregisterBridge(final String name) throws Exception { ObjectName objectName = objectNameBuilder.getBridgeObjectName(name); unregisterFromJMX(objectName); unregisterFromRegistry(ResourceNames.CORE_BRIDGE + name); } public synchronized void registerCluster(final ClusterConnection cluster, - final ClusterConnectionConfiguration configuration) throws Exception - { + final ClusterConnectionConfiguration configuration) throws Exception { ObjectName objectName = objectNameBuilder.getClusterConnectionObjectName(configuration.getName()); ClusterConnectionControl control = new ClusterConnectionControlImpl(cluster, storageManager, configuration); registerInJMX(objectName, new StandardMBean(control, ClusterConnectionControl.class)); registerInRegistry(ResourceNames.CORE_CLUSTER_CONNECTION + configuration.getName(), control); } - public synchronized void unregisterCluster(final String name) throws Exception - { + public synchronized void unregisterCluster(final String name) throws Exception { ObjectName objectName = objectNameBuilder.getClusterConnectionObjectName(name); unregisterFromJMX(objectName); unregisterFromRegistry(ResourceNames.CORE_CLUSTER_CONNECTION + name); } - public ServerMessage handleMessage(final ServerMessage message) throws Exception - { + public ServerMessage handleMessage(final ServerMessage message) throws Exception { // a reply message is sent with the result stored in the message body. ServerMessage reply = new ServerMessageImpl(storageManager.generateID(), 512); String resourceName = message.getStringProperty(ManagementHelper.HDR_RESOURCE_NAME); - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("handling management message for " + resourceName); } String operation = message.getStringProperty(ManagementHelper.HDR_OPERATION_NAME); - if (operation != null) - { + if (operation != null) { Object[] params = ManagementHelper.retrieveOperationParameters(message); - if (params == null) - { + if (params == null) { params = new Object[0]; } - try - { + try { Object result = invokeOperation(resourceName, operation, params); ManagementHelper.storeResult(reply, result); reply.putBooleanProperty(ManagementHelper.HDR_OPERATION_SUCCEEDED, true); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.managementOperationError(e, operation, resourceName); reply.putBooleanProperty(ManagementHelper.HDR_OPERATION_SUCCEEDED, false); String exceptionMessage = e.getMessage(); - if (e instanceof InvocationTargetException) - { + if (e instanceof InvocationTargetException) { exceptionMessage = ((InvocationTargetException) e).getTargetException().getMessage(); } - if (e != null) - { + if (e != null) { ManagementHelper.storeResult(reply, exceptionMessage); } } } - else - { + else { String attribute = message.getStringProperty(ManagementHelper.HDR_ATTRIBUTE); - if (attribute != null) - { - try - { + if (attribute != null) { + try { Object result = getAttribute(resourceName, attribute); ManagementHelper.storeResult(reply, result); reply.putBooleanProperty(ManagementHelper.HDR_OPERATION_SUCCEEDED, true); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.managementAttributeError(e, attribute, resourceName); reply.putBooleanProperty(ManagementHelper.HDR_OPERATION_SUCCEEDED, false); String exceptionMessage = e.getMessage(); - if (e instanceof InvocationTargetException) - { + if (e instanceof InvocationTargetException) { exceptionMessage = ((InvocationTargetException) e).getTargetException().getMessage(); } - if (e != null) - { + if (e != null) { ManagementHelper.storeResult(reply, exceptionMessage); } } @@ -468,19 +404,15 @@ public class ManagementServiceImpl implements ManagementService return reply; } - public synchronized Object getResource(final String resourceName) - { + public synchronized Object getResource(final String resourceName) { return registry.get(resourceName); } - public synchronized Object[] getResources(final Class resourceType) - { + public synchronized Object[] getResources(final Class resourceType) { List resources = new ArrayList(); Collection clone = new ArrayList(registry.values()); - for (Object entry : clone) - { - if (resourceType.isAssignableFrom(entry.getClass())) - { + for (Object entry : clone) { + if (resourceType.isAssignableFrom(entry.getClass())) { resources.add(entry); } } @@ -489,15 +421,12 @@ public class ManagementServiceImpl implements ManagementService private final Set registeredNames = new HashSet(); - public void registerInJMX(final ObjectName objectName, final Object managedResource) throws Exception - { - if (!jmxManagementEnabled) - { + public void registerInJMX(final ObjectName objectName, final Object managedResource) throws Exception { + if (!jmxManagementEnabled) { return; } - synchronized (mbeanServer) - { + synchronized (mbeanServer) { unregisterFromJMX(objectName); mbeanServer.registerMBean(managedResource, objectName); @@ -506,33 +435,26 @@ public class ManagementServiceImpl implements ManagementService } } - public synchronized void registerInRegistry(final String resourceName, final Object managedResource) - { + public synchronized void registerInRegistry(final String resourceName, final Object managedResource) { unregisterFromRegistry(resourceName); registry.put(resourceName, managedResource); } - public synchronized void unregisterFromRegistry(final String resourceName) - { + public synchronized void unregisterFromRegistry(final String resourceName) { registry.remove(resourceName); } // the JMX unregistration is synchronized to avoid race conditions if 2 clients tries to // unregister the same resource (e.g. a queue) at the same time since unregisterMBean() // will throw an exception if the MBean has already been unregistered - public void unregisterFromJMX(final ObjectName objectName) throws MBeanRegistrationException, - InstanceNotFoundException - { - if (!jmxManagementEnabled) - { + public void unregisterFromJMX(final ObjectName objectName) throws MBeanRegistrationException, InstanceNotFoundException { + if (!jmxManagementEnabled) { return; } - synchronized (mbeanServer) - { - if (mbeanServer.isRegistered(objectName)) - { + synchronized (mbeanServer) { + if (mbeanServer.isRegistered(objectName)) { mbeanServer.unregisterMBean(objectName); registeredNames.remove(objectName); @@ -540,80 +462,63 @@ public class ManagementServiceImpl implements ManagementService } } - public void addNotificationListener(final NotificationListener listener) - { + public void addNotificationListener(final NotificationListener listener) { listeners.add(listener); } - public void removeNotificationListener(final NotificationListener listener) - { + public void removeNotificationListener(final NotificationListener listener) { listeners.remove(listener); } - public SimpleString getManagementAddress() - { + public SimpleString getManagementAddress() { return managementAddress; } - public SimpleString getManagementNotificationAddress() - { + public SimpleString getManagementNotificationAddress() { return managementNotificationAddress; } // ActiveMQComponent implementation ----------------------------- - public void start() throws Exception - { - if (messageCounterEnabled) - { + public void start() throws Exception { + if (messageCounterEnabled) { messageCounterManager.start(); } started = true; } - public synchronized void stop() throws Exception - { + public synchronized void stop() throws Exception { Set resourceNames = new HashSet(registry.keySet()); - for (String resourceName : resourceNames) - { + for (String resourceName : resourceNames) { unregisterFromRegistry(resourceName); } - if (jmxManagementEnabled) - { - if (!registeredNames.isEmpty()) - { + if (jmxManagementEnabled) { + if (!registeredNames.isEmpty()) { List unexpectedResourceNames = new ArrayList(); - for (String name : resourceNames) - { + for (String name : resourceNames) { // only addresses and queues should still be registered - if (!(name.startsWith(ResourceNames.CORE_ADDRESS) || name.startsWith(ResourceNames.CORE_QUEUE))) - { + if (!(name.startsWith(ResourceNames.CORE_ADDRESS) || name.startsWith(ResourceNames.CORE_QUEUE))) { unexpectedResourceNames.add(name); } } - if (!unexpectedResourceNames.isEmpty()) - { + if (!unexpectedResourceNames.isEmpty()) { ActiveMQServerLogger.LOGGER.managementStopError(unexpectedResourceNames.size(), unexpectedResourceNames); } - for (ObjectName on : registeredNames) - { - try - { + for (ObjectName on : registeredNames) { + try { mbeanServer.unregisterMBean(on); } - catch (Exception ignore) - { + catch (Exception ignore) { } } } } - if (messageCounterManager != null) - { + if (messageCounterManager != null) { messageCounterManager.stop(); messageCounterManager.resetAllCounters(); @@ -650,39 +555,30 @@ public class ManagementServiceImpl implements ManagementService started = false; } - public boolean isStarted() - { + public boolean isStarted() { return started; } - public void sendNotification(final Notification notification) throws Exception - { - if (isTrace) - { + public void sendNotification(final Notification notification) throws Exception { + if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Sending Notification = " + notification + - ", notificationEnabled=" + notificationsEnabled + - " messagingServerControl=" + messagingServerControl); + ", notificationEnabled=" + notificationsEnabled + + " messagingServerControl=" + messagingServerControl); } // This needs to be synchronized since we need to ensure notifications are processed in strict sequence - synchronized (this) - { - if (messagingServerControl != null && notificationsEnabled) - { + synchronized (this) { + if (messagingServerControl != null && notificationsEnabled) { // We also need to synchronize on the post office notification lock // otherwise we can get notifications arriving in wrong order / missing // if a notification occurs at same time as sendQueueInfoToQueue is processed - synchronized (postOffice.getNotificationLock()) - { + synchronized (postOffice.getNotificationLock()) { // First send to any local listeners - for (NotificationListener listener : listeners) - { - try - { + for (NotificationListener listener : listeners) { + try { listener.onNotification(notification); } - catch (Exception e) - { + catch (Exception e) { // Exception thrown from one listener should not stop execution of others ActiveMQServerLogger.LOGGER.errorCallingNotifListener(e); } @@ -691,10 +587,8 @@ public class ManagementServiceImpl implements ManagementService // start sending notification *messages* only when server has initialised // Note at backup initialisation we don't want to send notifications either // https://jira.jboss.org/jira/browse/HORNETQ-317 - if (messagingServer == null || !messagingServer.isActive()) - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + if (messagingServer == null || !messagingServer.isActive()) { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("ignoring message " + notification + " as the server is not initialized"); } return; @@ -709,24 +603,19 @@ public class ManagementServiceImpl implements ManagementService notificationMessage.setDurable(true); notificationMessage.setAddress(managementNotificationAddress); - if (notification.getProperties() != null) - { + if (notification.getProperties() != null) { TypedProperties props = notification.getProperties(); - for (SimpleString name : notification.getProperties().getPropertyNames()) - { + for (SimpleString name : notification.getProperties().getPropertyNames()) { notificationMessage.putObjectProperty(name, props.getProperty(name)); } } - notificationMessage.putStringProperty(ManagementHelper.HDR_NOTIFICATION_TYPE, - new SimpleString(notification.getType().toString())); + notificationMessage.putStringProperty(ManagementHelper.HDR_NOTIFICATION_TYPE, new SimpleString(notification.getType().toString())); notificationMessage.putLongProperty(ManagementHelper.HDR_NOTIFICATION_TIMESTAMP, System.currentTimeMillis()); - if (notification.getUID() != null) - { - notificationMessage.putStringProperty(new SimpleString("foobar"), - new SimpleString(notification.getUID())); + if (notification.getUID() != null) { + notificationMessage.putStringProperty(new SimpleString("foobar"), new SimpleString(notification.getUID())); } postOffice.route(notificationMessage, null, false); @@ -735,106 +624,83 @@ public class ManagementServiceImpl implements ManagementService } } - public void enableNotifications(final boolean enabled) - { + public void enableNotifications(final boolean enabled) { notificationsEnabled = enabled; } - public Object getAttribute(final String resourceName, final String attribute) - { - try - { + public Object getAttribute(final String resourceName, final String attribute) { + try { Object resource = registry.get(resourceName); - if (resource == null) - { + if (resource == null) { throw ActiveMQMessageBundle.BUNDLE.cannotFindResource(resourceName); } Method method = null; String upperCaseAttribute = attribute.substring(0, 1).toUpperCase() + attribute.substring(1); - try - { + try { method = resource.getClass().getMethod("get" + upperCaseAttribute, new Class[0]); } - catch (NoSuchMethodException nsme) - { - try - { + catch (NoSuchMethodException nsme) { + try { method = resource.getClass().getMethod("is" + upperCaseAttribute, new Class[0]); } - catch (NoSuchMethodException nsme2) - { + catch (NoSuchMethodException nsme2) { throw ActiveMQMessageBundle.BUNDLE.noGetterMethod(attribute); } } return method.invoke(resource, new Object[0]); } - catch (Throwable t) - { + catch (Throwable t) { throw new IllegalStateException("Problem while retrieving attribute " + attribute, t); } } - private Object invokeOperation(final String resourceName, final String operation, final Object[] params) throws Exception - { + private Object invokeOperation(final String resourceName, + final String operation, + final Object[] params) throws Exception { Object resource = registry.get(resourceName); - if (resource == null) - { + if (resource == null) { throw ActiveMQMessageBundle.BUNDLE.cannotFindResource(resourceName); } Method method = null; Method[] methods = resource.getClass().getMethods(); - for (Method m : methods) - { - if (m.getName().equals(operation) && m.getParameterTypes().length == params.length) - { + for (Method m : methods) { + if (m.getName().equals(operation) && m.getParameterTypes().length == params.length) { boolean match = true; Class[] paramTypes = m.getParameterTypes(); - for (int i = 0; i < paramTypes.length; i++) - { - if (params[i] == null) - { + for (int i = 0; i < paramTypes.length; i++) { + if (params[i] == null) { continue; } - if (paramTypes[i].isAssignableFrom(params[i].getClass()) || paramTypes[i] == Long.TYPE && - params[i].getClass() == Integer.class || - paramTypes[i] == Double.TYPE && - params[i].getClass() == Integer.class || - paramTypes[i] == Long.TYPE && - params[i].getClass() == Long.class || - paramTypes[i] == Double.TYPE && - params[i].getClass() == Double.class || - paramTypes[i] == Integer.TYPE && - params[i].getClass() == Integer.class || - paramTypes[i] == Boolean.TYPE && - params[i].getClass() == Boolean.class) - { + if (paramTypes[i].isAssignableFrom(params[i].getClass()) || paramTypes[i] == Long.TYPE && params[i].getClass() == Integer.class || + paramTypes[i] == Double.TYPE && params[i].getClass() == Integer.class || + paramTypes[i] == Long.TYPE && params[i].getClass() == Long.class || + paramTypes[i] == Double.TYPE && params[i].getClass() == Double.class || + paramTypes[i] == Integer.TYPE && params[i].getClass() == Integer.class || + paramTypes[i] == Boolean.TYPE && params[i].getClass() == Boolean.class) { // parameter match } - else - { + else { match = false; break; // parameter check loop } } - if (match) - { + if (match) { method = m; break; // method match loop } } } - if (method == null) - { + if (method == null) { throw ActiveMQMessageBundle.BUNDLE.noOperation(operation, params.length); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/HierarchicalRepository.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/HierarchicalRepository.java index 111f38b612..6e2ba77f32 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/HierarchicalRepository.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/HierarchicalRepository.java @@ -21,14 +21,15 @@ import java.util.List; /** * allows objects to be mapped against a regex pattern and held in order in a list */ -public interface HierarchicalRepository -{ +public interface HierarchicalRepository { void disableListeners(); void enableListeners(); + /** * Add a new match to the repository + * * @param match The regex to use to match against * @param value the value to hold against the match */ @@ -38,6 +39,7 @@ public interface HierarchicalRepository /** * return the value held against the nearest match + * * @param match the match to look for * @return the value */ @@ -45,30 +47,35 @@ public interface HierarchicalRepository /** * Return a list of Values being added + * * @return */ List values(); /** * set the default value to fallback to if none found + * * @param defaultValue the value */ void setDefault(T defaultValue); /** * remove a match from the repository + * * @param match the match to remove */ void removeMatch(String match); /** * register a listener to listen for changes in the repository + * * @param listener */ void registerListener(HierarchicalRepositoryChangeListener listener); /** * unregister a listener + * * @param listener */ void unRegisterListener(HierarchicalRepositoryChangeListener listener); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/HierarchicalRepositoryChangeListener.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/HierarchicalRepositoryChangeListener.java index 5382a97ff3..94d4aa269d 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/HierarchicalRepositoryChangeListener.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/HierarchicalRepositoryChangeListener.java @@ -16,7 +16,7 @@ */ package org.apache.activemq.artemis.core.settings; -public interface HierarchicalRepositoryChangeListener -{ +public interface HierarchicalRepositoryChangeListener { + void onChange(); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/Mergeable.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/Mergeable.java index aed835dec5..0cfb344fad 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/Mergeable.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/Mergeable.java @@ -19,7 +19,7 @@ package org.apache.activemq.artemis.core.settings; /** * Used when merging objects together. */ -public interface Mergeable -{ +public interface Mergeable { + void merge(T merged); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/impl/AddressSettings.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/impl/AddressSettings.java index aad691b591..b0bfbf4dee 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/impl/AddressSettings.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/impl/AddressSettings.java @@ -27,10 +27,9 @@ import org.apache.activemq.artemis.utils.BufferHelper; /** * Configuration settings that are applied on the address level */ -public class AddressSettings implements Mergeable, Serializable, EncodingSupport -{ - private static final long serialVersionUID = 1607502280582336366L; +public class AddressSettings implements Mergeable, Serializable, EncodingSupport { + private static final long serialVersionUID = 1607502280582336366L; /** * defaults used if null, this allows merging @@ -111,8 +110,7 @@ public class AddressSettings implements Mergeable, Serializable private Boolean autoDeleteJmsQueues = null; - public AddressSettings(AddressSettings other) - { + public AddressSettings(AddressSettings other) { this.addressFullMessagePolicy = other.addressFullMessagePolicy; this.maxSizeBytes = other.maxSizeBytes; this.pageSizeBytes = other.pageSizeBytes; @@ -136,232 +134,187 @@ public class AddressSettings implements Mergeable, Serializable this.autoDeleteJmsQueues = other.autoDeleteJmsQueues; } - public AddressSettings() - { + public AddressSettings() { } - - public boolean isAutoCreateJmsQueues() - { + public boolean isAutoCreateJmsQueues() { return autoCreateJmsQueues != null ? autoCreateJmsQueues : AddressSettings.DEFAULT_AUTO_CREATE_QUEUES; } - public AddressSettings setAutoCreateJmsQueues(final boolean autoCreateJmsQueues) - { + public AddressSettings setAutoCreateJmsQueues(final boolean autoCreateJmsQueues) { this.autoCreateJmsQueues = autoCreateJmsQueues; return this; } - public boolean isAutoDeleteJmsQueues() - { + public boolean isAutoDeleteJmsQueues() { return autoDeleteJmsQueues != null ? autoDeleteJmsQueues : AddressSettings.DEFAULT_AUTO_DELETE_QUEUES; } - public AddressSettings setAutoDeleteJmsQueues(final boolean autoDeleteJmsQueues) - { + public AddressSettings setAutoDeleteJmsQueues(final boolean autoDeleteJmsQueues) { this.autoDeleteJmsQueues = autoDeleteJmsQueues; return this; } - public boolean isLastValueQueue() - { + public boolean isLastValueQueue() { return lastValueQueue != null ? lastValueQueue : AddressSettings.DEFAULT_LAST_VALUE_QUEUE; } - public AddressSettings setLastValueQueue(final boolean lastValueQueue) - { + public AddressSettings setLastValueQueue(final boolean lastValueQueue) { this.lastValueQueue = lastValueQueue; return this; } - public AddressFullMessagePolicy getAddressFullMessagePolicy() - { - return addressFullMessagePolicy != null ? addressFullMessagePolicy - : AddressSettings.DEFAULT_ADDRESS_FULL_MESSAGE_POLICY; + public AddressFullMessagePolicy getAddressFullMessagePolicy() { + return addressFullMessagePolicy != null ? addressFullMessagePolicy : AddressSettings.DEFAULT_ADDRESS_FULL_MESSAGE_POLICY; } - public AddressSettings setAddressFullMessagePolicy(final AddressFullMessagePolicy addressFullMessagePolicy) - { + public AddressSettings setAddressFullMessagePolicy(final AddressFullMessagePolicy addressFullMessagePolicy) { this.addressFullMessagePolicy = addressFullMessagePolicy; return this; } - public long getPageSizeBytes() - { + public long getPageSizeBytes() { return pageSizeBytes != null ? pageSizeBytes : AddressSettings.DEFAULT_PAGE_SIZE; } - public AddressSettings setPageSizeBytes(final long pageSize) - { + public AddressSettings setPageSizeBytes(final long pageSize) { pageSizeBytes = pageSize; return this; } - public int getPageCacheMaxSize() - { + public int getPageCacheMaxSize() { return pageMaxCache != null ? pageMaxCache : AddressSettings.DEFAULT_PAGE_MAX_CACHE; } - public AddressSettings setPageCacheMaxSize(final int pageMaxCache) - { + public AddressSettings setPageCacheMaxSize(final int pageMaxCache) { this.pageMaxCache = pageMaxCache; return this; } - public long getMaxSizeBytes() - { + public long getMaxSizeBytes() { return maxSizeBytes != null ? maxSizeBytes : AddressSettings.DEFAULT_MAX_SIZE_BYTES; } - public AddressSettings setMaxSizeBytes(final long maxSizeBytes) - { + public AddressSettings setMaxSizeBytes(final long maxSizeBytes) { this.maxSizeBytes = maxSizeBytes; return this; } - public int getMaxDeliveryAttempts() - { + public int getMaxDeliveryAttempts() { return maxDeliveryAttempts != null ? maxDeliveryAttempts : AddressSettings.DEFAULT_MAX_DELIVERY_ATTEMPTS; } - public AddressSettings setMaxDeliveryAttempts(final int maxDeliveryAttempts) - { + public AddressSettings setMaxDeliveryAttempts(final int maxDeliveryAttempts) { this.maxDeliveryAttempts = maxDeliveryAttempts; return this; } - public int getMessageCounterHistoryDayLimit() - { - return messageCounterHistoryDayLimit != null ? messageCounterHistoryDayLimit - : AddressSettings.DEFAULT_MESSAGE_COUNTER_HISTORY_DAY_LIMIT; + public int getMessageCounterHistoryDayLimit() { + return messageCounterHistoryDayLimit != null ? messageCounterHistoryDayLimit : AddressSettings.DEFAULT_MESSAGE_COUNTER_HISTORY_DAY_LIMIT; } - public AddressSettings setMessageCounterHistoryDayLimit(final int messageCounterHistoryDayLimit) - { + public AddressSettings setMessageCounterHistoryDayLimit(final int messageCounterHistoryDayLimit) { this.messageCounterHistoryDayLimit = messageCounterHistoryDayLimit; return this; } - public long getRedeliveryDelay() - { + public long getRedeliveryDelay() { return redeliveryDelay != null ? redeliveryDelay : AddressSettings.DEFAULT_REDELIVER_DELAY; } - public AddressSettings setRedeliveryDelay(final long redeliveryDelay) - { + public AddressSettings setRedeliveryDelay(final long redeliveryDelay) { this.redeliveryDelay = redeliveryDelay; return this; } - public double getRedeliveryMultiplier() - { + public double getRedeliveryMultiplier() { return redeliveryMultiplier != null ? redeliveryMultiplier : AddressSettings.DEFAULT_REDELIVER_MULTIPLIER; } - public AddressSettings setRedeliveryMultiplier(final double redeliveryMultiplier) - { + public AddressSettings setRedeliveryMultiplier(final double redeliveryMultiplier) { this.redeliveryMultiplier = redeliveryMultiplier; return this; } - public long getMaxRedeliveryDelay() - { + public long getMaxRedeliveryDelay() { // default is redelivery-delay * 10 as specified on the docs and at this JIRA: // https://issues.jboss.org/browse/HORNETQ-1263 return maxRedeliveryDelay != null ? maxRedeliveryDelay : (getRedeliveryDelay() * 10); } - public AddressSettings setMaxRedeliveryDelay(final long maxRedeliveryDelay) - { + public AddressSettings setMaxRedeliveryDelay(final long maxRedeliveryDelay) { this.maxRedeliveryDelay = maxRedeliveryDelay; return this; } - public SimpleString getDeadLetterAddress() - { + public SimpleString getDeadLetterAddress() { return deadLetterAddress; } - public AddressSettings setDeadLetterAddress(final SimpleString deadLetterAddress) - { + public AddressSettings setDeadLetterAddress(final SimpleString deadLetterAddress) { this.deadLetterAddress = deadLetterAddress; return this; } - public SimpleString getExpiryAddress() - { + public SimpleString getExpiryAddress() { return expiryAddress; } - public AddressSettings setExpiryAddress(final SimpleString expiryAddress) - { + public AddressSettings setExpiryAddress(final SimpleString expiryAddress) { this.expiryAddress = expiryAddress; return this; } - public Long getExpiryDelay() - { + public Long getExpiryDelay() { return expiryDelay; } - public AddressSettings setExpiryDelay(final Long expiryDelay) - { + public AddressSettings setExpiryDelay(final Long expiryDelay) { this.expiryDelay = expiryDelay; return this; } - public boolean isSendToDLAOnNoRoute() - { + public boolean isSendToDLAOnNoRoute() { return sendToDLAOnNoRoute != null ? sendToDLAOnNoRoute : AddressSettings.DEFAULT_SEND_TO_DLA_ON_NO_ROUTE; } - public AddressSettings setSendToDLAOnNoRoute(final boolean value) - { + public AddressSettings setSendToDLAOnNoRoute(final boolean value) { sendToDLAOnNoRoute = value; return this; } - public long getRedistributionDelay() - { + public long getRedistributionDelay() { return redistributionDelay != null ? redistributionDelay : AddressSettings.DEFAULT_REDISTRIBUTION_DELAY; } - public AddressSettings setRedistributionDelay(final long redistributionDelay) - { + public AddressSettings setRedistributionDelay(final long redistributionDelay) { this.redistributionDelay = redistributionDelay; return this; } - public long getSlowConsumerThreshold() - { + public long getSlowConsumerThreshold() { return slowConsumerThreshold != null ? slowConsumerThreshold : AddressSettings.DEFAULT_SLOW_CONSUMER_THRESHOLD; } - public AddressSettings setSlowConsumerThreshold(final long slowConsumerThreshold) - { + public AddressSettings setSlowConsumerThreshold(final long slowConsumerThreshold) { this.slowConsumerThreshold = slowConsumerThreshold; return this; } - public long getSlowConsumerCheckPeriod() - { + public long getSlowConsumerCheckPeriod() { return slowConsumerCheckPeriod != null ? slowConsumerCheckPeriod : AddressSettings.DEFAULT_SLOW_CONSUMER_CHECK_PERIOD; } - public AddressSettings setSlowConsumerCheckPeriod(final long slowConsumerCheckPeriod) - { + public AddressSettings setSlowConsumerCheckPeriod(final long slowConsumerCheckPeriod) { this.slowConsumerCheckPeriod = slowConsumerCheckPeriod; return this; } - public SlowConsumerPolicy getSlowConsumerPolicy() - { - return slowConsumerPolicy != null ? slowConsumerPolicy - : AddressSettings.DEFAULT_SLOW_CONSUMER_POLICY; + public SlowConsumerPolicy getSlowConsumerPolicy() { + return slowConsumerPolicy != null ? slowConsumerPolicy : AddressSettings.DEFAULT_SLOW_CONSUMER_POLICY; } - public AddressSettings setSlowConsumerPolicy(final SlowConsumerPolicy slowConsumerPolicy) - { + public AddressSettings setSlowConsumerPolicy(final SlowConsumerPolicy slowConsumerPolicy) { this.slowConsumerPolicy = slowConsumerPolicy; return this; } @@ -371,101 +324,77 @@ public class AddressSettings implements Mergeable, Serializable * * @param merged */ - public void merge(final AddressSettings merged) - { - if (maxDeliveryAttempts == null) - { + public void merge(final AddressSettings merged) { + if (maxDeliveryAttempts == null) { maxDeliveryAttempts = merged.maxDeliveryAttempts; } - if (dropMessagesWhenFull == null) - { + if (dropMessagesWhenFull == null) { dropMessagesWhenFull = merged.dropMessagesWhenFull; } - if (maxSizeBytes == null) - { + if (maxSizeBytes == null) { maxSizeBytes = merged.maxSizeBytes; } - if (pageMaxCache == null) - { + if (pageMaxCache == null) { pageMaxCache = merged.pageMaxCache; } - if (pageSizeBytes == null) - { + if (pageSizeBytes == null) { pageSizeBytes = merged.getPageSizeBytes(); } - if (messageCounterHistoryDayLimit == null) - { + if (messageCounterHistoryDayLimit == null) { messageCounterHistoryDayLimit = merged.messageCounterHistoryDayLimit; } - if (redeliveryDelay == null) - { + if (redeliveryDelay == null) { redeliveryDelay = merged.redeliveryDelay; } - if (redeliveryMultiplier == null) - { + if (redeliveryMultiplier == null) { redeliveryMultiplier = merged.redeliveryMultiplier; } - if (maxRedeliveryDelay == null) - { + if (maxRedeliveryDelay == null) { maxRedeliveryDelay = merged.maxRedeliveryDelay; } - if (deadLetterAddress == null) - { + if (deadLetterAddress == null) { deadLetterAddress = merged.deadLetterAddress; } - if (expiryAddress == null) - { + if (expiryAddress == null) { expiryAddress = merged.expiryAddress; } - if (expiryDelay == null) - { + if (expiryDelay == null) { expiryDelay = merged.expiryDelay; } - if (redistributionDelay == null) - { + if (redistributionDelay == null) { redistributionDelay = merged.redistributionDelay; } - if (sendToDLAOnNoRoute == null) - { + if (sendToDLAOnNoRoute == null) { sendToDLAOnNoRoute = merged.sendToDLAOnNoRoute; } - if (addressFullMessagePolicy == null) - { + if (addressFullMessagePolicy == null) { addressFullMessagePolicy = merged.addressFullMessagePolicy; } - if (slowConsumerThreshold == null) - { + if (slowConsumerThreshold == null) { slowConsumerThreshold = merged.slowConsumerThreshold; } - if (slowConsumerCheckPeriod == null) - { + if (slowConsumerCheckPeriod == null) { slowConsumerCheckPeriod = merged.slowConsumerCheckPeriod; } - if (slowConsumerPolicy == null) - { + if (slowConsumerPolicy == null) { slowConsumerPolicy = merged.slowConsumerPolicy; } - if (autoCreateJmsQueues == null) - { + if (autoCreateJmsQueues == null) { autoCreateJmsQueues = merged.autoCreateJmsQueues; } - if (autoDeleteJmsQueues == null) - { + if (autoDeleteJmsQueues == null) { autoDeleteJmsQueues = merged.autoDeleteJmsQueues; } } @Override - public void decode(ActiveMQBuffer buffer) - { + public void decode(ActiveMQBuffer buffer) { SimpleString policyStr = buffer.readNullableSimpleString(); - if (policyStr != null) - { + if (policyStr != null) { addressFullMessagePolicy = AddressFullMessagePolicy.valueOf(policyStr.toString()); } - else - { + else { addressFullMessagePolicy = null; } @@ -505,12 +434,10 @@ public class AddressSettings implements Mergeable, Serializable policyStr = buffer.readNullableSimpleString(); - if (policyStr != null) - { + if (policyStr != null) { slowConsumerPolicy = SlowConsumerPolicy.valueOf(policyStr.toString()); } - else - { + else { slowConsumerPolicy = null; } @@ -520,8 +447,7 @@ public class AddressSettings implements Mergeable, Serializable } @Override - public int getEncodeSize() - { + public int getEncodeSize() { return BufferHelper.sizeOfNullableSimpleString(addressFullMessagePolicy != null ? addressFullMessagePolicy.toString() : null) + BufferHelper.sizeOfNullableLong(maxSizeBytes) + @@ -547,10 +473,8 @@ public class AddressSettings implements Mergeable, Serializable } @Override - public void encode(ActiveMQBuffer buffer) - { - buffer.writeNullableSimpleString(addressFullMessagePolicy != null ? new SimpleString(addressFullMessagePolicy.toString()) - : null); + public void encode(ActiveMQBuffer buffer) { + buffer.writeNullableSimpleString(addressFullMessagePolicy != null ? new SimpleString(addressFullMessagePolicy.toString()) : null); BufferHelper.writeNullableLong(buffer, maxSizeBytes); @@ -597,8 +521,7 @@ public class AddressSettings implements Mergeable, Serializable * @see java.lang.Object#hashCode() */ @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((addressFullMessagePolicy == null) ? 0 : addressFullMessagePolicy.hashCode()); @@ -609,8 +532,7 @@ public class AddressSettings implements Mergeable, Serializable result = prime * result + ((lastValueQueue == null) ? 0 : lastValueQueue.hashCode()); result = prime * result + ((maxDeliveryAttempts == null) ? 0 : maxDeliveryAttempts.hashCode()); result = prime * result + ((maxSizeBytes == null) ? 0 : maxSizeBytes.hashCode()); - result = prime * result + - ((messageCounterHistoryDayLimit == null) ? 0 : messageCounterHistoryDayLimit.hashCode()); + result = prime * result + ((messageCounterHistoryDayLimit == null) ? 0 : messageCounterHistoryDayLimit.hashCode()); result = prime * result + ((pageSizeBytes == null) ? 0 : pageSizeBytes.hashCode()); result = prime * result + ((pageMaxCache == null) ? 0 : pageMaxCache.hashCode()); result = prime * result + ((redeliveryDelay == null) ? 0 : redeliveryDelay.hashCode()); @@ -630,8 +552,7 @@ public class AddressSettings implements Mergeable, Serializable * @see java.lang.Object#equals(java.lang.Object) */ @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) @@ -639,148 +560,127 @@ public class AddressSettings implements Mergeable, Serializable if (getClass() != obj.getClass()) return false; AddressSettings other = (AddressSettings) obj; - if (addressFullMessagePolicy == null) - { + if (addressFullMessagePolicy == null) { if (other.addressFullMessagePolicy != null) return false; } else if (!addressFullMessagePolicy.equals(other.addressFullMessagePolicy)) return false; - if (deadLetterAddress == null) - { + if (deadLetterAddress == null) { if (other.deadLetterAddress != null) return false; } else if (!deadLetterAddress.equals(other.deadLetterAddress)) return false; - if (dropMessagesWhenFull == null) - { + if (dropMessagesWhenFull == null) { if (other.dropMessagesWhenFull != null) return false; } else if (!dropMessagesWhenFull.equals(other.dropMessagesWhenFull)) return false; - if (expiryAddress == null) - { + if (expiryAddress == null) { if (other.expiryAddress != null) return false; } else if (!expiryAddress.equals(other.expiryAddress)) return false; - if (expiryDelay == null) - { + if (expiryDelay == null) { if (other.expiryDelay != null) return false; } else if (!expiryDelay.equals(other.expiryDelay)) return false; - if (lastValueQueue == null) - { + if (lastValueQueue == null) { if (other.lastValueQueue != null) return false; } else if (!lastValueQueue.equals(other.lastValueQueue)) return false; - if (maxDeliveryAttempts == null) - { + if (maxDeliveryAttempts == null) { if (other.maxDeliveryAttempts != null) return false; } else if (!maxDeliveryAttempts.equals(other.maxDeliveryAttempts)) return false; - if (maxSizeBytes == null) - { + if (maxSizeBytes == null) { if (other.maxSizeBytes != null) return false; } else if (!maxSizeBytes.equals(other.maxSizeBytes)) return false; - if (messageCounterHistoryDayLimit == null) - { + if (messageCounterHistoryDayLimit == null) { if (other.messageCounterHistoryDayLimit != null) return false; } else if (!messageCounterHistoryDayLimit.equals(other.messageCounterHistoryDayLimit)) return false; - if (pageSizeBytes == null) - { + if (pageSizeBytes == null) { if (other.pageSizeBytes != null) return false; } else if (!pageSizeBytes.equals(other.pageSizeBytes)) return false; - if (pageMaxCache == null) - { + if (pageMaxCache == null) { if (other.pageMaxCache != null) return false; } else if (!pageMaxCache.equals(other.pageMaxCache)) return false; - if (redeliveryDelay == null) - { + if (redeliveryDelay == null) { if (other.redeliveryDelay != null) return false; } else if (!redeliveryDelay.equals(other.redeliveryDelay)) return false; - if (redeliveryMultiplier == null) - { + if (redeliveryMultiplier == null) { if (other.redeliveryMultiplier != null) return false; } else if (!redeliveryMultiplier.equals(other.redeliveryMultiplier)) return false; - if (maxRedeliveryDelay == null) - { + if (maxRedeliveryDelay == null) { if (other.maxRedeliveryDelay != null) return false; } else if (!maxRedeliveryDelay.equals(other.maxRedeliveryDelay)) return false; - if (redistributionDelay == null) - { + if (redistributionDelay == null) { if (other.redistributionDelay != null) return false; } else if (!redistributionDelay.equals(other.redistributionDelay)) return false; - if (sendToDLAOnNoRoute == null) - { + if (sendToDLAOnNoRoute == null) { if (other.sendToDLAOnNoRoute != null) return false; } else if (!sendToDLAOnNoRoute.equals(other.sendToDLAOnNoRoute)) return false; - if (slowConsumerThreshold == null) - { + if (slowConsumerThreshold == null) { if (other.slowConsumerThreshold != null) return false; } else if (!slowConsumerThreshold.equals(other.slowConsumerThreshold)) return false; - if (slowConsumerCheckPeriod == null) - { + if (slowConsumerCheckPeriod == null) { if (other.slowConsumerCheckPeriod != null) return false; } else if (!slowConsumerCheckPeriod.equals(other.slowConsumerCheckPeriod)) return false; - if (slowConsumerPolicy == null) - { + if (slowConsumerPolicy == null) { if (other.slowConsumerPolicy != null) return false; } else if (!slowConsumerPolicy.equals(other.slowConsumerPolicy)) return false; - if (autoCreateJmsQueues == null) - { + if (autoCreateJmsQueues == null) { if (other.autoCreateJmsQueues != null) return false; } else if (!autoCreateJmsQueues.equals(other.autoCreateJmsQueues)) return false; - if (autoDeleteJmsQueues == null) - { + if (autoDeleteJmsQueues == null) { if (other.autoDeleteJmsQueues != null) return false; } @@ -793,8 +693,7 @@ public class AddressSettings implements Mergeable, Serializable * @see java.lang.Object#toString() */ @Override - public String toString() - { + public String toString() { return "AddressSettings [addressFullMessagePolicy=" + addressFullMessagePolicy + ", deadLetterAddress=" + deadLetterAddress + diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/impl/HierarchicalObjectRepository.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/impl/HierarchicalObjectRepository.java index 0ebcf48018..80bba6be22 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/impl/HierarchicalObjectRepository.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/impl/HierarchicalObjectRepository.java @@ -38,8 +38,7 @@ import org.apache.activemq.artemis.core.settings.Mergeable; /** * allows objects to be mapped against a regex pattern and held in order in a list */ -public class HierarchicalObjectRepository implements HierarchicalRepository -{ +public class HierarchicalObjectRepository implements HierarchicalRepository { private boolean listenersEnabled = true; /** @@ -76,7 +75,7 @@ public class HierarchicalObjectRepository implements HierarchicalRepository * We could have a race between the state of {@link #matches} and {@link #cache}: *

    - * Thread1: calls {@link #addMatch(String , T)}: i. cleans cache; ii. adds match to Map.
    + * Thread1: calls {@link #addMatch(String, T)}: i. cleans cache; ii. adds match to Map.
    * Thread2: could add an (out-dated) entry to the cache between 'i. clean cache' and 'ii. add * match to Map'. *

    @@ -92,77 +91,61 @@ public class HierarchicalObjectRepository implements HierarchicalRepository listeners = new ArrayList(); - @Override - public void disableListeners() - { + public void disableListeners() { lock.writeLock().lock(); - try - { + try { this.listenersEnabled = false; } - finally - { + finally { lock.writeLock().unlock(); } } @Override - public void enableListeners() - { + public void enableListeners() { lock.writeLock().lock(); - try - { + try { this.listenersEnabled = true; } - finally - { + finally { lock.writeLock().unlock(); } onChange(); } - public void addMatch(final String match, final T value) - { + public void addMatch(final String match, final T value) { addMatch(match, value, false); } - public List values() - { + public List values() { lock.readLock().lock(); - try - { + try { ArrayList values = new ArrayList(matches.size()); - for (Match matchValue : matches.values()) - { + for (Match matchValue : matches.values()) { values.add(matchValue.getValue()); } return values; } - finally - { + finally { lock.readLock().unlock(); } } - /** * Add a new match to the repository * * @param match The regex to use to match against * @param value the value to hold against the match */ - public void addMatch(final String match, final T value, final boolean immutableMatch) - { + public void addMatch(final String match, final T value, final boolean immutableMatch) { lock.writeLock().lock(); - try - { + try { clearCache(); - if (immutableMatch) - { + if (immutableMatch) { immutables.add(match); } Match.verify(match); @@ -170,8 +153,7 @@ public class HierarchicalObjectRepository implements HierarchicalRepository implements HierarchicalRepository implements HierarchicalRepository> possibleMatches = getPossibleMatches(match); Collection> orderedMatches = sort(possibleMatches); actualMatch = merge(orderedMatches); T value = actualMatch != null ? actualMatch : defaultmatch; - if (value != null) - { + if (value != null) { cache.put(match, value); } return value; } - finally - { + finally { lock.readLock().unlock(); } } /** * merge all the possible matches, if the values implement Mergeable then a full merge is done + * * @param orderedMatches * @return */ - private T merge(final Collection> orderedMatches) - { + private T merge(final Collection> orderedMatches) { T actualMatch = null; - for (Match match : orderedMatches) - { - if (actualMatch == null || !Mergeable.class.isAssignableFrom(actualMatch.getClass())) - { + for (Match match : orderedMatches) { + if (actualMatch == null || !Mergeable.class.isAssignableFrom(actualMatch.getClass())) { actualMatch = match.getValue(); - if (!Mergeable.class.isAssignableFrom(actualMatch.getClass())) - { + if (!Mergeable.class.isAssignableFrom(actualMatch.getClass())) { break; } } - else - { - ((Mergeable)actualMatch).merge(match.getValue()); + else { + ((Mergeable) actualMatch).merge(match.getValue()); } } return actualMatch; @@ -246,16 +218,15 @@ public class HierarchicalObjectRepository implements HierarchicalRepository> sort(final Map> possibleMatches) - { + private List> sort(final Map> possibleMatches) { List keys = new ArrayList(possibleMatches.keySet()); Collections.sort(keys, matchComparator); List> matches1 = new ArrayList>(possibleMatches.size()); - for (String key : keys) - { + for (String key : keys) { matches1.add(possibleMatches.get(key)); } return matches1; @@ -266,18 +237,14 @@ public class HierarchicalObjectRepository implements HierarchicalRepository implements HierarchicalRepository implements HierarchicalRepository> getPossibleMatches(final String match) - { + private Map> getPossibleMatches(final String match) { HashMap> possibleMatches = new HashMap>(); - for (Entry> entry : matches.entrySet()) - { + for (Entry> entry : matches.entrySet()) { Match entryMatch = entry.getValue(); - if (entryMatch.getPattern().matcher(match).matches()) - { + if (entryMatch.getPattern().matcher(match).matches()) { possibleMatches.put(entry.getKey(), entryMatch); } } @@ -408,47 +352,36 @@ public class HierarchicalObjectRepository implements HierarchicalRepository, Serializable - { + private static final class MatchComparator implements Comparator, Serializable { + private static final long serialVersionUID = -6182535107518999740L; - public int compare(final String o1, final String o2) - { - if (o1.contains(Match.WILDCARD) && !o2.contains(Match.WILDCARD)) - { + public int compare(final String o1, final String o2) { + if (o1.contains(Match.WILDCARD) && !o2.contains(Match.WILDCARD)) { return +1; } - else if (!o1.contains(Match.WILDCARD) && o2.contains(Match.WILDCARD)) - { + else if (!o1.contains(Match.WILDCARD) && o2.contains(Match.WILDCARD)) { return -1; } - else if (o1.contains(Match.WILDCARD) && o2.contains(Match.WILDCARD)) - { + else if (o1.contains(Match.WILDCARD) && o2.contains(Match.WILDCARD)) { return o2.length() - o1.length(); } - else if (o1.contains(Match.WORD_WILDCARD) && !o2.contains(Match.WORD_WILDCARD)) - { + else if (o1.contains(Match.WORD_WILDCARD) && !o2.contains(Match.WORD_WILDCARD)) { return +1; } - else if (!o1.contains(Match.WORD_WILDCARD) && o2.contains(Match.WORD_WILDCARD)) - { + else if (!o1.contains(Match.WORD_WILDCARD) && o2.contains(Match.WORD_WILDCARD)) { return -1; } - else if (o1.contains(Match.WORD_WILDCARD) && o2.contains(Match.WORD_WILDCARD)) - { + else if (o1.contains(Match.WORD_WILDCARD) && o2.contains(Match.WORD_WILDCARD)) { String[] leftSplits = o1.split("\\."); String[] rightSplits = o2.split("\\."); - for (int i = 0; i < leftSplits.length; i++) - { + for (int i = 0; i < leftSplits.length; i++) { String left = leftSplits[i]; - if (left.equals(Match.WORD_WILDCARD)) - { - if (rightSplits.length < i || !rightSplits[i].equals(Match.WORD_WILDCARD)) - { + if (left.equals(Match.WORD_WILDCARD)) { + if (rightSplits.length < i || !rightSplits[i].equals(Match.WORD_WILDCARD)) { return -1; } - else - { + else { return +1; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/impl/Match.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/impl/Match.java index d4d3f2d3a7..d7d6b4c50b 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/impl/Match.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/impl/Match.java @@ -21,10 +21,10 @@ import java.util.regex.Pattern; import org.apache.activemq.artemis.core.server.ActiveMQMessageBundle; /** - a Match is the holder for the match string and the object to hold against it. + * a Match is the holder for the match string and the object to hold against it. */ -public class Match -{ +public class Match { + public static final String WORD_WILDCARD = "*"; private static final String WORD_WILDCARD_REPLACEMENT = "[^.]+"; @@ -45,17 +45,14 @@ public class Match private T value; - public Match(final String match) - { + public Match(final String match) { this.match = match; String actMatch = match; // replace any regex characters - if (Match.WILDCARD.equals(match)) - { + if (Match.WILDCARD.equals(match)) { actMatch = Match.WILDCARD_REPLACEMENT; } - else - { + else { // this is to match with what's documented actMatch = actMatch.replace(DOT_WILDCARD, WILDCARD); @@ -69,69 +66,58 @@ public class Match } - public String getMatch() - { + public String getMatch() { return match; } - public void setMatch(final String match) - { + public void setMatch(final String match) { this.match = match; } - public Pattern getPattern() - { + public Pattern getPattern() { return pattern; } - public T getValue() - { + public T getValue() { return value; } - public void setValue(final T value) - { + public void setValue(final T value) { this.value = value; } @Override - public boolean equals(final Object o) - { - if (this == o) - { + public boolean equals(final Object o) { + if (this == o) { return true; } - if (o == null || getClass() != o.getClass()) - { + if (o == null || getClass() != o.getClass()) { return false; } @SuppressWarnings("rawtypes") - Match that = (Match)o; + Match that = (Match) o; return !(match != null ? !match.equals(that.match) : that.match != null); } @Override - public int hashCode() - { + public int hashCode() { return match != null ? match.hashCode() : 0; } /** * utility method to verify consistency of match + * * @param match the match to validate * @throws IllegalArgumentException if a match isn't valid */ - public static void verify(final String match) throws IllegalArgumentException - { - if (match == null) - { + public static void verify(final String match) throws IllegalArgumentException { + if (match == null) { throw ActiveMQMessageBundle.BUNDLE.nullMatch(); } - if (match.contains("#") && match.indexOf("#") < match.length() - 1) - { + if (match.contains("#") && match.indexOf("#") < match.length() - 1) { throw ActiveMQMessageBundle.BUNDLE.invalidMatch(); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/impl/ResourceLimitSettings.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/impl/ResourceLimitSettings.java index 94b9092f60..843e09006f 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/impl/ResourceLimitSettings.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/impl/ResourceLimitSettings.java @@ -24,8 +24,8 @@ import org.apache.activemq.artemis.utils.BufferHelper; import java.io.Serializable; -public class ResourceLimitSettings implements Serializable, EncodingSupport -{ +public class ResourceLimitSettings implements Serializable, EncodingSupport { + private static final long serialVersionUID = -110638321333856932L; public static final SimpleString DEFAULT_MATCH = null; @@ -34,9 +34,9 @@ public class ResourceLimitSettings implements Serializable, EncodingSupport public static final Integer DEFAULT_MAX_QUEUES = -1; -// public static final Long DEFAULT_MAX_QUEUE_SIZE_BYTES = -1L; + // public static final Long DEFAULT_MAX_QUEUE_SIZE_BYTES = -1L; -// public static final SimpleString DEFAULT_QUEUE_NAME_REGEX = new SimpleString(".+"); + // public static final SimpleString DEFAULT_QUEUE_NAME_REGEX = new SimpleString(".+"); SimpleString match = null; @@ -44,112 +44,101 @@ public class ResourceLimitSettings implements Serializable, EncodingSupport Integer maxQueues = null; -// Long maxQueueSizeBytes = null; + // Long maxQueueSizeBytes = null; -// SimpleString queueNameRegex = null; + // SimpleString queueNameRegex = null; - public SimpleString getMatch() - { + public SimpleString getMatch() { return match != null ? match : DEFAULT_MATCH; } - public int getMaxConnections() - { + public int getMaxConnections() { return maxConnections != null ? maxConnections : DEFAULT_MAX_CONNECTIONS; } - public int getMaxQueues() - { + public int getMaxQueues() { return maxQueues != null ? maxQueues : DEFAULT_MAX_QUEUES; } -// public long getMaxQueueSizeBytes() -// { -// return maxQueueSizeBytes != null ? maxQueueSizeBytes : DEFAULT_MAX_QUEUE_SIZE_BYTES; -// } -// -// public SimpleString getQueueNameRegex() -// { -// return queueNameRegex != null ? queueNameRegex : DEFAULT_QUEUE_NAME_REGEX; -// } + // public long getMaxQueueSizeBytes() + // { + // return maxQueueSizeBytes != null ? maxQueueSizeBytes : DEFAULT_MAX_QUEUE_SIZE_BYTES; + // } + // + // public SimpleString getQueueNameRegex() + // { + // return queueNameRegex != null ? queueNameRegex : DEFAULT_QUEUE_NAME_REGEX; + // } - public void setMatch(SimpleString match) - { + public void setMatch(SimpleString match) { this.match = match; } - public void setMaxConnections(int maxConnections) - { + public void setMaxConnections(int maxConnections) { this.maxConnections = maxConnections; } - public void setMaxQueues(int maxQueues) - { + public void setMaxQueues(int maxQueues) { this.maxQueues = maxQueues; } -// public void setMaxQueueSizeBytes(long maxQueueSizeBytes) -// { -// this.maxQueueSizeBytes = maxQueueSizeBytes; -// } -// -// public void setQueueNameRegex(SimpleString queueNameRegex) -// { -// this.queueNameRegex = queueNameRegex; -// } + // public void setMaxQueueSizeBytes(long maxQueueSizeBytes) + // { + // this.maxQueueSizeBytes = maxQueueSizeBytes; + // } + // + // public void setQueueNameRegex(SimpleString queueNameRegex) + // { + // this.queueNameRegex = queueNameRegex; + // } @Override - public int getEncodeSize() - { + public int getEncodeSize() { return SimpleString.sizeofNullableString(match) + - BufferHelper.sizeOfNullableInteger(maxConnections) + - BufferHelper.sizeOfNullableInteger(maxQueues); -// BufferHelper.sizeOfNullableLong(maxQueueSizeBytes) + -// SimpleString.sizeofNullableString(queueNameRegex); + BufferHelper.sizeOfNullableInteger(maxConnections) + + BufferHelper.sizeOfNullableInteger(maxQueues); + // BufferHelper.sizeOfNullableLong(maxQueueSizeBytes) + + // SimpleString.sizeofNullableString(queueNameRegex); } @Override - public void encode(ActiveMQBuffer buffer) - { + public void encode(ActiveMQBuffer buffer) { buffer.writeNullableSimpleString(match); BufferHelper.writeNullableInteger(buffer, maxConnections); BufferHelper.writeNullableInteger(buffer, maxQueues); -// BufferHelper.writeNullableLong(buffer, maxQueueSizeBytes); + // BufferHelper.writeNullableLong(buffer, maxQueueSizeBytes); -// buffer.writeNullableSimpleString(queueNameRegex); + // buffer.writeNullableSimpleString(queueNameRegex); } @Override - public void decode(ActiveMQBuffer buffer) - { + public void decode(ActiveMQBuffer buffer) { match = buffer.readNullableSimpleString(); maxConnections = BufferHelper.readNullableInteger(buffer); maxQueues = BufferHelper.readNullableInteger(buffer); -// maxQueueSizeBytes = BufferHelper.readNullableLong(buffer); + // maxQueueSizeBytes = BufferHelper.readNullableLong(buffer); -// queueNameRegex = buffer.readNullableSimpleString(); + // queueNameRegex = buffer.readNullableSimpleString(); } - /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((match == null) ? 0 : match.hashCode()); result = prime * result + ((maxConnections == null) ? 0 : maxConnections.hashCode()); result = prime * result + ((maxQueues == null) ? 0 : maxQueues.hashCode()); -// result = prime * result + ((maxQueueSizeBytes == null) ? 0 : maxQueueSizeBytes.hashCode()); -// result = prime * result + ((queueNameRegex == null) ? 0 : queueNameRegex.hashCode()); + // result = prime * result + ((maxQueueSizeBytes == null) ? 0 : maxQueueSizeBytes.hashCode()); + // result = prime * result + ((queueNameRegex == null) ? 0 : queueNameRegex.hashCode()); return result; } @@ -157,17 +146,16 @@ public class ResourceLimitSettings implements Serializable, EncodingSupport * @see java.lang.Object#toString() */ @Override - public String toString() - { + public String toString() { return "ResourceLimitSettings [match=" + match + - ", maxConnections=" + - maxConnections + - ", maxQueues=" + - maxQueues + -// ", maxQueueSizeBytes=" + -// maxQueueSizeBytes + -// ", queueNameRegex=" + -// queueNameRegex + - "]"; + ", maxConnections=" + + maxConnections + + ", maxQueues=" + + maxQueues + + // ", maxQueueSizeBytes=" + + // maxQueueSizeBytes + + // ", queueNameRegex=" + + // queueNameRegex + + "]"; } } \ No newline at end of file diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/impl/SlowConsumerPolicy.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/impl/SlowConsumerPolicy.java index 09c99f7292..3f009d63bd 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/impl/SlowConsumerPolicy.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/settings/impl/SlowConsumerPolicy.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.core.settings.impl; -public enum SlowConsumerPolicy -{ +public enum SlowConsumerPolicy { KILL, NOTIFY; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/ResourceManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/ResourceManager.java index 3f1d4c435c..c417a4a9bf 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/ResourceManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/ResourceManager.java @@ -23,8 +23,8 @@ import javax.transaction.xa.Xid; import org.apache.activemq.artemis.core.server.ActiveMQComponent; -public interface ResourceManager extends ActiveMQComponent -{ +public interface ResourceManager extends ActiveMQComponent { + boolean putTransaction(Xid xid, Transaction tx); Transaction getTransaction(Xid xid); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/Transaction.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/Transaction.java index c548cd9391..7d6151af1a 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/Transaction.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/Transaction.java @@ -27,10 +27,9 @@ import org.apache.activemq.artemis.core.server.impl.RefsOperation; /** * An ActiveMQ Artemis internal transaction */ -public interface Transaction -{ - static enum State - { +public interface Transaction { + + static enum State { ACTIVE, PREPARED, COMMITTED, ROLLEDBACK, SUSPENDED, ROLLBACK_ONLY } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/TransactionDetail.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/TransactionDetail.java index ba6c929964..751f35ff90 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/TransactionDetail.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/TransactionDetail.java @@ -29,8 +29,8 @@ import org.apache.activemq.artemis.core.transaction.impl.XidImpl; import org.apache.activemq.artemis.utils.json.JSONArray; import org.apache.activemq.artemis.utils.json.JSONObject; -public abstract class TransactionDetail -{ +public abstract class TransactionDetail { + public static final String KEY_CREATION_TIME = "creation_time"; public static final String KEY_XID_AS_BASE64 = "xid_as_base64"; @@ -55,15 +55,13 @@ public abstract class TransactionDetail private final Transaction transaction; private final Long creationTime; - public TransactionDetail(Xid xid, Transaction tx, Long creation) - { + public TransactionDetail(Xid xid, Transaction tx, Long creation) { this.xid = xid; this.transaction = tx; this.creationTime = creation; } - public JSONObject toJSON() throws Exception - { + public JSONObject toJSON() throws Exception { DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM); JSONObject detailJson = new JSONObject(); @@ -76,32 +74,26 @@ public abstract class TransactionDetail JSONArray msgsJson = new JSONArray(); List txops = this.transaction.getAllOperations(); detailJson.put(KEY_TX_RELATED_MESSAGES, msgsJson); - if (txops == null) - { + if (txops == null) { return detailJson; } - for (TransactionOperation op : txops) - { + for (TransactionOperation op : txops) { String opClassName = op.getClass().getName(); String opType = null; - if (opClassName.equals("org.apache.activemq.artemis.core.postoffice.impl.PostOfficeImpl$AddOperation")) - { + if (opClassName.equals("org.apache.activemq.artemis.core.postoffice.impl.PostOfficeImpl$AddOperation")) { opType = "(+) send"; } - else if (opClassName.equals("org.apache.activemq.artemis.core.server.impl.QueueImpl$RefsOperation")) - { + else if (opClassName.equals("org.apache.activemq.artemis.core.server.impl.QueueImpl$RefsOperation")) { opType = "(-) receive"; } List msgs = op.getRelatedMessageReferences(); - if (msgs == null) - { + if (msgs == null) { continue; } - for (MessageReference ref : msgs) - { + for (MessageReference ref : msgs) { JSONObject msgJson = new JSONObject(); msgsJson.put(msgJson); @@ -118,5 +110,5 @@ public abstract class TransactionDetail public abstract String decodeMessageType(ServerMessage msg); - public abstract Map decodeMessageProperties(ServerMessage msg); + public abstract Map decodeMessageProperties(ServerMessage msg); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/TransactionFactory.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/TransactionFactory.java index 976543947e..5e97826eb8 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/TransactionFactory.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/TransactionFactory.java @@ -20,7 +20,7 @@ import org.apache.activemq.artemis.core.persistence.StorageManager; import javax.transaction.xa.Xid; -public interface TransactionFactory -{ +public interface TransactionFactory { + Transaction newTransaction(Xid xid, StorageManager storageManager, int timeoutSeconds); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/TransactionOperation.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/TransactionOperation.java index 0b2bbe6bf5..5da1d97d92 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/TransactionOperation.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/TransactionOperation.java @@ -21,11 +21,10 @@ import java.util.List; import org.apache.activemq.artemis.core.server.MessageReference; /** - * * A TransactionOperation */ -public interface TransactionOperation -{ +public interface TransactionOperation { + void beforePrepare(Transaction tx) throws Exception; /** diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/TransactionOperationAbstract.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/TransactionOperationAbstract.java index ee9a70aafc..476cb3761d 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/TransactionOperationAbstract.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/TransactionOperationAbstract.java @@ -24,10 +24,9 @@ import org.apache.activemq.artemis.core.server.MessageReference; /** * Just a helper, when you don't want to implement all the methods on a transaction operation. */ -public abstract class TransactionOperationAbstract implements TransactionOperation -{ - public void beforePrepare(Transaction tx) throws Exception - { +public abstract class TransactionOperationAbstract implements TransactionOperation { + + public void beforePrepare(Transaction tx) throws Exception { } @@ -36,13 +35,11 @@ public abstract class TransactionOperationAbstract implements TransactionOperati *

    * Any verification has to be done on before prepare */ - public void afterPrepare(Transaction tx) - { + public void afterPrepare(Transaction tx) { } - public void beforeCommit(Transaction tx) throws Exception - { + public void beforeCommit(Transaction tx) throws Exception { } /** @@ -50,12 +47,10 @@ public abstract class TransactionOperationAbstract implements TransactionOperati *

    * Any verification has to be done on before commit */ - public void afterCommit(Transaction tx) - { + public void afterCommit(Transaction tx) { } - public void beforeRollback(Transaction tx) throws Exception - { + public void beforeRollback(Transaction tx) throws Exception { } /** @@ -63,13 +58,11 @@ public abstract class TransactionOperationAbstract implements TransactionOperati *

    * Any verification has to be done on before rollback */ - public void afterRollback(Transaction tx) - { + public void afterRollback(Transaction tx) { } @Override - public List getRelatedMessageReferences() - { + public List getRelatedMessageReferences() { return Collections.emptyList(); } @@ -77,10 +70,8 @@ public abstract class TransactionOperationAbstract implements TransactionOperati * @see org.apache.activemq.artemis.core.transaction.TransactionOperation#getListOnConsumer(long) */ @Override - public List getListOnConsumer(long consumerID) - { + public List getListOnConsumer(long consumerID) { return Collections.emptyList(); } - } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/TransactionPropertyIndexes.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/TransactionPropertyIndexes.java index e83324d116..19ae77775c 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/TransactionPropertyIndexes.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/TransactionPropertyIndexes.java @@ -16,8 +16,7 @@ */ package org.apache.activemq.artemis.core.transaction; -public class TransactionPropertyIndexes -{ +public class TransactionPropertyIndexes { public static final int LARGE_MESSAGE_CONFIRMATIONS = 1; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/impl/BindingsTransactionImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/impl/BindingsTransactionImpl.java index 00df53ba10..f72beb18e8 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/impl/BindingsTransactionImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/impl/BindingsTransactionImpl.java @@ -20,38 +20,31 @@ import org.apache.activemq.artemis.core.persistence.StorageManager; import org.apache.activemq.artemis.core.server.Queue; import org.apache.activemq.artemis.core.server.impl.RefsOperation; -public class BindingsTransactionImpl extends TransactionImpl -{ +public class BindingsTransactionImpl extends TransactionImpl { - public BindingsTransactionImpl(StorageManager storage) - { + public BindingsTransactionImpl(StorageManager storage) { super(storage, 0); } /** * @throws Exception */ - protected void doCommit() throws Exception - { - if (isContainsPersistent()) - { + protected void doCommit() throws Exception { + if (isContainsPersistent()) { storageManager.commitBindings(getID()); setState(State.COMMITTED); } } - protected void doRollback() throws Exception - { - if (isContainsPersistent()) - { + protected void doRollback() throws Exception { + if (isContainsPersistent()) { storageManager.rollbackBindings(getID()); setState(State.ROLLEDBACK); } } @Override - public RefsOperation createRefsOperation(Queue queue) - { + public RefsOperation createRefsOperation(Queue queue) { return null; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/impl/CoreTransactionDetail.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/impl/CoreTransactionDetail.java index 1f4f58aea5..6683882aca 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/impl/CoreTransactionDetail.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/impl/CoreTransactionDetail.java @@ -25,19 +25,16 @@ import org.apache.activemq.artemis.core.server.ServerMessage; import org.apache.activemq.artemis.core.transaction.Transaction; import org.apache.activemq.artemis.core.transaction.TransactionDetail; -public class CoreTransactionDetail extends TransactionDetail -{ - public CoreTransactionDetail(Xid xid, Transaction tx, Long creation) throws Exception - { - super(xid,tx,creation); +public class CoreTransactionDetail extends TransactionDetail { + + public CoreTransactionDetail(Xid xid, Transaction tx, Long creation) throws Exception { + super(xid, tx, creation); } @Override - public String decodeMessageType(ServerMessage msg) - { + public String decodeMessageType(ServerMessage msg) { int type = msg.getType(); - switch (type) - { + switch (type) { case Message.DEFAULT_TYPE: // 0 return "Default"; case Message.OBJECT_TYPE: // 2 @@ -56,8 +53,7 @@ public class CoreTransactionDetail extends TransactionDetail } @Override - public Map decodeMessageProperties(ServerMessage msg) - { + public Map decodeMessageProperties(ServerMessage msg) { return msg.toMap(); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/impl/ResourceManagerImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/impl/ResourceManagerImpl.java index 06c74eeb04..31160aca74 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/impl/ResourceManagerImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/impl/ResourceManagerImpl.java @@ -35,8 +35,8 @@ import org.apache.activemq.artemis.core.server.ActiveMQServerLogger; import org.apache.activemq.artemis.core.transaction.ResourceManager; import org.apache.activemq.artemis.core.transaction.Transaction; -public class ResourceManagerImpl implements ResourceManager -{ +public class ResourceManagerImpl implements ResourceManager { + private final ConcurrentMap transactions = new ConcurrentHashMap(); private final List heuristicCompletions = new ArrayList(); @@ -53,8 +53,7 @@ public class ResourceManagerImpl implements ResourceManager public ResourceManagerImpl(final int defaultTimeoutSeconds, final long txTimeoutScanPeriod, - final ScheduledExecutorService scheduledThreadPool) - { + final ScheduledExecutorService scheduledThreadPool) { this.defaultTimeoutSeconds = defaultTimeoutSeconds; this.txTimeoutScanPeriod = txTimeoutScanPeriod; this.scheduledThreadPool = scheduledThreadPool; @@ -63,31 +62,23 @@ public class ResourceManagerImpl implements ResourceManager // ActiveMQComponent implementation @Override - public void start() throws Exception - { - if (started) - { + public void start() throws Exception { + if (started) { return; } task = new TxTimeoutHandler(); - Future future = scheduledThreadPool.scheduleAtFixedRate(task, - txTimeoutScanPeriod, - txTimeoutScanPeriod, - TimeUnit.MILLISECONDS); + Future future = scheduledThreadPool.scheduleAtFixedRate(task, txTimeoutScanPeriod, txTimeoutScanPeriod, TimeUnit.MILLISECONDS); task.setFuture(future); started = true; } @Override - public void stop() throws Exception - { - if (!started) - { + public void stop() throws Exception { + if (!started) { return; } - if (task != null) - { + if (task != null) { task.close(); } @@ -95,81 +86,65 @@ public class ResourceManagerImpl implements ResourceManager } @Override - public boolean isStarted() - { + public boolean isStarted() { return started; } // ResourceManager implementation --------------------------------------------- - public Transaction getTransaction(final Xid xid) - { + public Transaction getTransaction(final Xid xid) { return transactions.get(xid); } - public boolean putTransaction(final Xid xid, final Transaction tx) - { + public boolean putTransaction(final Xid xid, final Transaction tx) { return transactions.putIfAbsent(xid, tx) == null; } - public Transaction removeTransaction(final Xid xid) - { + public Transaction removeTransaction(final Xid xid) { return transactions.remove(xid); } - public int getTimeoutSeconds() - { + public int getTimeoutSeconds() { return defaultTimeoutSeconds; } - public List getPreparedTransactions() - { + public List getPreparedTransactions() { List xids = new ArrayList(); - for (Map.Entry entry : transactions.entrySet()) - { - if (entry.getValue().getState() == Transaction.State.PREPARED) - { + for (Map.Entry entry : transactions.entrySet()) { + if (entry.getValue().getState() == Transaction.State.PREPARED) { xids.add(entry.getKey()); } } return xids; } - public Map getPreparedTransactionsWithCreationTime() - { + public Map getPreparedTransactionsWithCreationTime() { Map xidsWithCreationTime = new HashMap(); - for (Map.Entry entry : transactions.entrySet()) - { + for (Map.Entry entry : transactions.entrySet()) { xidsWithCreationTime.put(entry.getKey(), entry.getValue().getCreateTime()); } return xidsWithCreationTime; } - public void putHeuristicCompletion(final long recordID, final Xid xid, final boolean isCommit) - { + public void putHeuristicCompletion(final long recordID, final Xid xid, final boolean isCommit) { heuristicCompletions.add(new HeuristicCompletionHolder(recordID, xid, isCommit)); } - public List getHeuristicCommittedTransactions() - { + public List getHeuristicCommittedTransactions() { return getHeuristicCompletedTransactions(true); } - public List getHeuristicRolledbackTransactions() - { + public List getHeuristicRolledbackTransactions() { return getHeuristicCompletedTransactions(false); } - public long removeHeuristicCompletion(final Xid xid) - { + public long removeHeuristicCompletion(final Xid xid) { Iterator iterator = heuristicCompletions.iterator(); - while (iterator.hasNext()) - { + while (iterator.hasNext()) { ResourceManagerImpl.HeuristicCompletionHolder holder = iterator.next(); - if (holder.xid.equals(xid)) - { + if (holder.xid.equals(xid)) { iterator.remove(); return holder.recordID; } @@ -177,29 +152,24 @@ public class ResourceManagerImpl implements ResourceManager return -1; } - private List getHeuristicCompletedTransactions(final boolean isCommit) - { + private List getHeuristicCompletedTransactions(final boolean isCommit) { List xids = new ArrayList(); - for (HeuristicCompletionHolder holder : heuristicCompletions) - { - if (holder.isCommit == isCommit) - { + for (HeuristicCompletionHolder holder : heuristicCompletions) { + if (holder.isCommit == isCommit) { xids.add(holder.xid); } } return xids; } - private class TxTimeoutHandler implements Runnable - { + private class TxTimeoutHandler implements Runnable { + private boolean closed = false; private Future future; - public void run() - { - if (closed) - { + public void run() { + if (closed) { return; } @@ -207,38 +177,30 @@ public class ResourceManagerImpl implements ResourceManager long now = System.currentTimeMillis(); - for (Transaction tx : transactions.values()) - { - if (tx.hasTimedOut(now, defaultTimeoutSeconds)) - { + for (Transaction tx : transactions.values()) { + if (tx.hasTimedOut(now, defaultTimeoutSeconds)) { transactions.remove(tx.getXid()); ActiveMQServerLogger.LOGGER.unexpectedXid(tx.getXid()); timedoutTransactions.add(tx); } } - for (Transaction failedTransaction : timedoutTransactions) - { - try - { + for (Transaction failedTransaction : timedoutTransactions) { + try { failedTransaction.rollback(); } - catch (Exception e) - { + catch (Exception e) { ActiveMQServerLogger.LOGGER.errorTimingOutTX(e, failedTransaction.getXid()); } } } - synchronized void setFuture(final Future future) - { + synchronized void setFuture(final Future future) { this.future = future; } - void close() - { - if (future != null) - { + void close() { + if (future != null) { future.cancel(false); } @@ -247,16 +209,15 @@ public class ResourceManagerImpl implements ResourceManager } - private static final class HeuristicCompletionHolder - { + private static final class HeuristicCompletionHolder { + public final boolean isCommit; public final Xid xid; public final long recordID; - public HeuristicCompletionHolder(final long recordID, final Xid xid, final boolean isCommit) - { + public HeuristicCompletionHolder(final long recordID, final Xid xid, final boolean isCommit) { this.recordID = recordID; this.xid = xid; this.isCommit = isCommit; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/impl/TransactionImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/impl/TransactionImpl.java index 357ce6f607..b71c7428b2 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/impl/TransactionImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/transaction/impl/TransactionImpl.java @@ -31,8 +31,8 @@ import org.apache.activemq.artemis.core.server.impl.RefsOperation; import org.apache.activemq.artemis.core.transaction.Transaction; import org.apache.activemq.artemis.core.transaction.TransactionOperation; -public class TransactionImpl implements Transaction -{ +public class TransactionImpl implements Transaction { + private List operations; private static final int INITIAL_NUM_PROPERTIES = 10; @@ -45,7 +45,6 @@ public class TransactionImpl implements Transaction private final long id; - private volatile State state = State.ACTIVE; private ActiveMQException exception; @@ -58,8 +57,7 @@ public class TransactionImpl implements Transaction private int timeoutSeconds = -1; - public TransactionImpl(final StorageManager storageManager, final int timeoutSeconds) - { + public TransactionImpl(final StorageManager storageManager, final int timeoutSeconds) { this.storageManager = storageManager; xid = null; @@ -71,8 +69,7 @@ public class TransactionImpl implements Transaction this.timeoutSeconds = timeoutSeconds; } - public TransactionImpl(final StorageManager storageManager) - { + public TransactionImpl(final StorageManager storageManager) { this.storageManager = storageManager; xid = null; @@ -82,8 +79,7 @@ public class TransactionImpl implements Transaction createTime = System.currentTimeMillis(); } - public TransactionImpl(final Xid xid, final StorageManager storageManager, final int timeoutSeconds) - { + public TransactionImpl(final Xid xid, final StorageManager storageManager, final int timeoutSeconds) { this.storageManager = storageManager; this.xid = xid; @@ -95,8 +91,7 @@ public class TransactionImpl implements Transaction this.timeoutSeconds = timeoutSeconds; } - public TransactionImpl(final long id, final Xid xid, final StorageManager storageManager) - { + public TransactionImpl(final long id, final Xid xid, final StorageManager storageManager) { this.storageManager = storageManager; this.xid = xid; @@ -109,83 +104,65 @@ public class TransactionImpl implements Transaction // Transaction implementation // ----------------------------------------------------------- - public void setContainsPersistent() - { + public void setContainsPersistent() { containsPersistent = true; } - public boolean isContainsPersistent() - { + public boolean isContainsPersistent() { return containsPersistent; } - public void setTimeout(final int timeout) - { + public void setTimeout(final int timeout) { this.timeoutSeconds = timeout; } @Override - public RefsOperation createRefsOperation(Queue queue) - { + public RefsOperation createRefsOperation(Queue queue) { return new RefsOperation(queue, storageManager); } - public long getID() - { + public long getID() { return id; } - public long getCreateTime() - { + public long getCreateTime() { return createTime; } - public boolean hasTimedOut(final long currentTime, final int defaultTimeout) - { - if (timeoutSeconds == -1) - { + public boolean hasTimedOut(final long currentTime, final int defaultTimeout) { + if (timeoutSeconds == -1) { return getState() != Transaction.State.PREPARED && currentTime > createTime + defaultTimeout * 1000; } - else - { + else { return getState() != Transaction.State.PREPARED && currentTime > createTime + timeoutSeconds * 1000; } } - public void prepare() throws Exception - { + public void prepare() throws Exception { storageManager.readLock(); - try - { - synchronized (timeoutLock) - { - if (state == State.ROLLBACK_ONLY) - { - if (exception != null) - { + try { + synchronized (timeoutLock) { + if (state == State.ROLLBACK_ONLY) { + if (exception != null) { // this TX will never be rolled back, // so we reset it now beforeRollback(); afterRollback(); - if (operations != null) - { + if (operations != null) { operations.clear(); } throw exception; } - else - { + else { // Do nothing return; } } - else if (state != State.ACTIVE) - { + else if (state != State.ACTIVE) { throw new IllegalStateException("Transaction is in invalid state " + state); } - if (xid == null) - { + if (xid == null) { throw new IllegalStateException("Cannot prepare non XA transaction"); } @@ -197,62 +174,48 @@ public class TransactionImpl implements Transaction // We use the Callback even for non persistence // If we are using non-persistence with replication, the replication manager will have // to execute this runnable in the correct order - storageManager.afterCompleteOperations(new IOCallback() - { + storageManager.afterCompleteOperations(new IOCallback() { - public void onError(final int errorCode, final String errorMessage) - { + public void onError(final int errorCode, final String errorMessage) { ActiveMQServerLogger.LOGGER.ioErrorOnTX(errorCode, errorMessage); } - public void done() - { + public void done() { afterPrepare(); } }); } } - finally - { + finally { storageManager.readUnLock(); } } - public void commit() throws Exception - { + public void commit() throws Exception { commit(true); } - public void commit(final boolean onePhase) throws Exception - { - synchronized (timeoutLock) - { - if (state == State.ROLLBACK_ONLY) - { + public void commit(final boolean onePhase) throws Exception { + synchronized (timeoutLock) { + if (state == State.ROLLBACK_ONLY) { rollback(); - if (exception != null) - { + if (exception != null) { throw exception; } - else - { + else { // Do nothing return; } } - if (xid != null) - { - if (onePhase && state != State.ACTIVE || !onePhase && state != State.PREPARED) - { + if (xid != null) { + if (onePhase && state != State.ACTIVE || !onePhase && state != State.PREPARED) { throw new IllegalStateException("Transaction is in invalid state " + state); } } - else - { - if (state != State.ACTIVE) - { + else { + if (state != State.ACTIVE) { throw new IllegalStateException("Transaction is in invalid state " + state); } } @@ -266,16 +229,13 @@ public class TransactionImpl implements Transaction // to execute this runnable in the correct order // This also will only use a different thread if there are any IO pending. // If the IO finished early by the time we got here, we won't need an executor - storageManager.afterCompleteOperations(new IOCallback() - { + storageManager.afterCompleteOperations(new IOCallback() { - public void onError(final int errorCode, final String errorMessage) - { + public void onError(final int errorCode, final String errorMessage) { ActiveMQServerLogger.LOGGER.ioErrorOnTX(errorCode, errorMessage); } - public void done() - { + public void done() { afterCommit(); } }); @@ -286,10 +246,8 @@ public class TransactionImpl implements Transaction /** * @throws Exception */ - protected void doCommit() throws Exception - { - if (containsPersistent || xid != null && state == State.PREPARED) - { + protected void doCommit() throws Exception { + if (containsPersistent || xid != null && state == State.PREPARED) { storageManager.commit(id); @@ -297,21 +255,15 @@ public class TransactionImpl implements Transaction } } - public void rollback() throws Exception - { - synchronized (timeoutLock) - { - if (xid != null) - { - if (state != State.PREPARED && state != State.ACTIVE && state != State.ROLLBACK_ONLY) - { + public void rollback() throws Exception { + synchronized (timeoutLock) { + if (xid != null) { + if (state != State.PREPARED && state != State.ACTIVE && state != State.ROLLBACK_ONLY) { throw new IllegalStateException("Transaction is in invalid state " + state); } } - else - { - if (state != State.ACTIVE && state != State.ROLLBACK_ONLY) - { + else { + if (state != State.ACTIVE && state != State.ROLLBACK_ONLY) { throw new IllegalStateException("Transaction is in invalid state " + state); } } @@ -323,16 +275,13 @@ public class TransactionImpl implements Transaction // We use the Callback even for non persistence // If we are using non-persistence with replication, the replication manager will have // to execute this runnable in the correct order - storageManager.afterCompleteOperations(new IOCallback() - { + storageManager.afterCompleteOperations(new IOCallback() { - public void onError(final int errorCode, final String errorMessage) - { + public void onError(final int errorCode, final String errorMessage) { ActiveMQServerLogger.LOGGER.ioErrorOnTX(errorCode, errorMessage); } - public void done() - { + public void done() { afterRollback(); state = State.ROLLEDBACK; } @@ -340,43 +289,34 @@ public class TransactionImpl implements Transaction } } - public void suspend() - { - if (state != State.ACTIVE) - { + public void suspend() { + if (state != State.ACTIVE) { throw new IllegalStateException("Can only suspend active transaction"); } state = State.SUSPENDED; } - public void resume() - { - if (state != State.SUSPENDED) - { + public void resume() { + if (state != State.SUSPENDED) { throw new IllegalStateException("Can only resume a suspended transaction"); } state = State.ACTIVE; } - public Transaction.State getState() - { + public Transaction.State getState() { return state; } - public void setState(final State state) - { + public void setState(final State state) { this.state = state; } - public Xid getXid() - { + public Xid getXid() { return xid; } - public void markAsRollbackOnly(final ActiveMQException exception1) - { - if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) - { + public void markAsRollbackOnly(final ActiveMQException exception1) { + if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Marking Transaction " + this.id + " as rollback only"); } state = State.ROLLBACK_ONLY; @@ -384,29 +324,24 @@ public class TransactionImpl implements Transaction this.exception = exception1; } - public synchronized void addOperation(final TransactionOperation operation) - { + public synchronized void addOperation(final TransactionOperation operation) { checkCreateOperations(); operations.add(operation); } - private int getOperationsCount() - { + private int getOperationsCount() { checkCreateOperations(); return operations.size(); } - public synchronized List getAllOperations() - { + public synchronized List getAllOperations() { return new ArrayList(operations); } - public void putProperty(final int index, final Object property) - { - if (index >= properties.length) - { + public void putProperty(final int index, final Object property) { + if (index >= properties.length) { Object[] newProperties = new Object[index]; System.arraycopy(properties, 0, newProperties, 0, properties.length); @@ -417,99 +352,75 @@ public class TransactionImpl implements Transaction properties[index] = property; } - public Object getProperty(final int index) - { + public Object getProperty(final int index) { return properties[index]; } // Private // ------------------------------------------------------------------- - private void doRollback() throws Exception - { - if (containsPersistent || xid != null && state == State.PREPARED) - { + private void doRollback() throws Exception { + if (containsPersistent || xid != null && state == State.PREPARED) { storageManager.rollback(id); } } - private void checkCreateOperations() - { - if (operations == null) - { + private void checkCreateOperations() { + if (operations == null) { operations = new ArrayList(); } } - private synchronized void afterCommit() - { - if (operations != null) - { - for (TransactionOperation operation : operations) - { + private synchronized void afterCommit() { + if (operations != null) { + for (TransactionOperation operation : operations) { operation.afterCommit(this); } } } - private synchronized void afterRollback() - { - if (operations != null) - { - for (TransactionOperation operation : operations) - { + private synchronized void afterRollback() { + if (operations != null) { + for (TransactionOperation operation : operations) { operation.afterRollback(this); } } } - private synchronized void beforeCommit() throws Exception - { - if (operations != null) - { - for (TransactionOperation operation : operations) - { + private synchronized void beforeCommit() throws Exception { + if (operations != null) { + for (TransactionOperation operation : operations) { operation.beforeCommit(this); } } } - private synchronized void beforePrepare() throws Exception - { - if (operations != null) - { - for (TransactionOperation operation : operations) - { + private synchronized void beforePrepare() throws Exception { + if (operations != null) { + for (TransactionOperation operation : operations) { operation.beforePrepare(this); } } } - private synchronized void beforeRollback() throws Exception - { - if (operations != null) - { - for (TransactionOperation operation : operations) - { + private synchronized void beforeRollback() throws Exception { + if (operations != null) { + for (TransactionOperation operation : operations) { operation.beforeRollback(this); } } } - private synchronized void afterPrepare() - { - if (operations != null) - { - for (TransactionOperation operation : operations) - { + private synchronized void afterPrepare() { + if (operations != null) { + for (TransactionOperation operation : operations) { operation.afterPrepare(this); } } } @Override - public String toString() - { + public String toString() { Date dt = new Date(this.createTime); return "TransactionImpl [xid=" + xid + ", id=" + diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/naming/BindingRegistry.java b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/naming/BindingRegistry.java index 62fbfe4cbd..87d44c06cd 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/naming/BindingRegistry.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/naming/BindingRegistry.java @@ -19,8 +19,8 @@ package org.apache.activemq.artemis.spi.core.naming; /** * Abstract interface for a registry to store endpoints like connection factories into. */ -public interface BindingRegistry -{ +public interface BindingRegistry { + Object lookup(String name); boolean bind(String name, Object obj); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/protocol/AbstractProtocolManagerFactory.java b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/protocol/AbstractProtocolManagerFactory.java index a8ea22ddd8..6c4eb8bfa1 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/protocol/AbstractProtocolManagerFactory.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/protocol/AbstractProtocolManagerFactory.java @@ -23,8 +23,7 @@ import java.util.concurrent.CopyOnWriteArrayList; import org.apache.activemq.artemis.api.core.BaseInterceptor; -public abstract class AbstractProtocolManagerFactory

    implements ProtocolManagerFactory

    -{ +public abstract class AbstractProtocolManagerFactory

    implements ProtocolManagerFactory

    { /** * This method exists because java templates won't store the type of P at runtime. @@ -35,19 +34,14 @@ public abstract class AbstractProtocolManagerFactory

    * @param listIn * @return */ - protected List

    filterInterceptors(Class

    type, List listIn) - { - if (listIn == null) - { + protected List

    filterInterceptors(Class

    type, List listIn) { + if (listIn == null) { return Collections.emptyList(); } - else - { + else { CopyOnWriteArrayList

    listOut = new CopyOnWriteArrayList(); - for (BaseInterceptor in : listIn) - { - if (type.isInstance(in)) - { + for (BaseInterceptor in : listIn) { + if (type.isInstance(in)) { listOut.add((P) in); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/protocol/MessageConverter.java b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/protocol/MessageConverter.java index 1655c6b1bb..a342e13f0f 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/protocol/MessageConverter.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/protocol/MessageConverter.java @@ -19,8 +19,8 @@ package org.apache.activemq.artemis.spi.core.protocol; import org.apache.activemq.artemis.core.server.ServerMessage; // TODO: use this interface properly on OpenWire -public interface MessageConverter -{ +public interface MessageConverter { + ServerMessage inbound(Object messageInbound) throws Exception; Object outbound(ServerMessage messageOutbound, int deliveryCount) throws Exception; diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/protocol/ProtocolManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/protocol/ProtocolManager.java index 867625cb18..8ff315a748 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/protocol/ProtocolManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/protocol/ProtocolManager.java @@ -25,8 +25,8 @@ import org.apache.activemq.artemis.core.remoting.impl.netty.NettyServerConnectio import org.apache.activemq.artemis.spi.core.remoting.Acceptor; import org.apache.activemq.artemis.spi.core.remoting.Connection; -public interface ProtocolManager

    -{ +public interface ProtocolManager

    { + ProtocolManagerFactory

    getFactory(); /** diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/protocol/ProtocolManagerFactory.java b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/protocol/ProtocolManagerFactory.java index ea36307b4f..e7c1d0700c 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/protocol/ProtocolManagerFactory.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/protocol/ProtocolManagerFactory.java @@ -21,21 +21,25 @@ import java.util.List; import org.apache.activemq.artemis.api.core.BaseInterceptor; import org.apache.activemq.artemis.core.server.ActiveMQServer; -public interface ProtocolManagerFactory

    -{ +public interface ProtocolManagerFactory

    { + /** * When you create the ProtocolManager, you should filter out any interceptors that won't belong * to this Protocol. * For example don't send any core Interceptors {@link org.apache.activemq.artemis.api.core.Interceptor} to Stomp * * * + * * @param server * @param incomingInterceptors * @param outgoingInterceptors * @return */ - ProtocolManager createProtocolManager(ActiveMQServer server, List

    incomingInterceptors, List

    outgoingInterceptors); + ProtocolManager createProtocolManager(ActiveMQServer server, + List

    incomingInterceptors, + List

    outgoingInterceptors); /** * This should get the entire list and only return the ones this factory can deal with * + * * @param interceptors * @return */ diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/protocol/SessionCallback.java b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/protocol/SessionCallback.java index 8aaa15ab11..3c9670d03c 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/protocol/SessionCallback.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/protocol/SessionCallback.java @@ -21,9 +21,11 @@ import org.apache.activemq.artemis.core.server.ServerConsumer; import org.apache.activemq.artemis.core.server.ServerMessage; import org.apache.activemq.artemis.spi.core.remoting.ReadyListener; -public interface SessionCallback -{ - /** This one gives a chance for Proton to have its own flow control. */ +public interface SessionCallback { + + /** + * This one gives a chance for Proton to have its own flow control. + */ boolean hasCredits(ServerConsumer consumerID); void sendProducerCreditsMessage(int credits, SimpleString address); @@ -34,7 +36,10 @@ public interface SessionCallback int sendLargeMessage(ServerMessage message, ServerConsumer consumerID, long bodySize, int deliveryCount); - int sendLargeMessageContinuation(ServerConsumer consumerID, byte[] body, boolean continues, boolean requiresResponse); + int sendLargeMessageContinuation(ServerConsumer consumerID, + byte[] body, + boolean continues, + boolean requiresResponse); void closed(); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/remoting/Acceptor.java b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/remoting/Acceptor.java index 6a85135da8..517ea3c839 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/remoting/Acceptor.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/remoting/Acceptor.java @@ -27,8 +27,8 @@ import org.apache.activemq.artemis.core.server.management.NotificationService; * An Acceptor is used by the RemotingService to allow clients to connect. It should take care of * dispatching client requests to the RemotingService's Dispatcher. */ -public interface Acceptor extends ActiveMQComponent -{ +public interface Acceptor extends ActiveMQComponent { + /** * Pause the acceptor and stop it from receiving client requests. */ @@ -49,12 +49,13 @@ public interface Acceptor extends ActiveMQComponent void setNotificationService(NotificationService notificationService); /** - * Set the default security Principal to be used when no user/pass are defined, only for InVM - */ + * Set the default security Principal to be used when no user/pass are defined, only for InVM + */ void setDefaultActiveMQPrincipal(ActiveMQPrincipal defaultActiveMQPrincipal); /** * Whether this acceptor allows insecure connections. + * * @throws java.lang.IllegalStateException if false @setDefaultActiveMQPrincipal */ boolean isUnsecurable(); diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/remoting/AcceptorFactory.java b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/remoting/AcceptorFactory.java index b1926340e9..1580d18870 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/remoting/AcceptorFactory.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/remoting/AcceptorFactory.java @@ -28,8 +28,8 @@ import org.apache.activemq.artemis.spi.core.protocol.ProtocolManager; *

    * An Acceptor is an endpoint that a {@link org.apache.activemq.artemis.spi.core.remoting.Connector} will connect to and is used by the remoting service. */ -public interface AcceptorFactory -{ +public interface AcceptorFactory { + /** * Create a new instance of an Acceptor. * diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ServerConnectionLifeCycleListener.java b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ServerConnectionLifeCycleListener.java index 43f92ef4fe..1d8d5b0781 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ServerConnectionLifeCycleListener.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ServerConnectionLifeCycleListener.java @@ -16,15 +16,15 @@ */ package org.apache.activemq.artemis.spi.core.remoting; -public interface ServerConnectionLifeCycleListener extends ConnectionLifeCycleListener -{ - /** +public interface ServerConnectionLifeCycleListener extends ConnectionLifeCycleListener { + + /** * This method is used both by client connector creation and server connection creation through acceptors. * the acceptor will be set to null on client operations * - * @param acceptor The acceptor here will be always null on a client connection created event. + * @param acceptor The acceptor here will be always null on a client connection created event. * @param connection the connection that has been created - * @param protocol the protocol to use + * @param protocol the protocol to use */ void connectionCreated(Acceptor acceptor, Connection connection, String protocol); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/security/ActiveMQSecurityManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/security/ActiveMQSecurityManager.java index 659305d159..86de242c5d 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/security/ActiveMQSecurityManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/security/ActiveMQSecurityManager.java @@ -25,11 +25,12 @@ import org.apache.activemq.artemis.core.security.Role; * Use to validate whether a user has is valid to connect to the server and perform certain * functions */ -public interface ActiveMQSecurityManager -{ +public interface ActiveMQSecurityManager { + /** * is this a valid user. - * @param user the user + * + * @param user the user * @param password the users password * @return true if a valid user */ @@ -38,9 +39,9 @@ public interface ActiveMQSecurityManager /** * is this a valid user and do they have the correct role * - * @param user the user - * @param password the users password - * @param roles the roles the user has + * @param user the user + * @param password the users password + * @param roles the roles the user has * @param checkType the type of check to perform * @return true if the user is valid and they have the correct roles */ diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/security/ActiveMQSecurityManagerImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/security/ActiveMQSecurityManagerImpl.java index c3bd1a2196..a9d4991ccc 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/security/ActiveMQSecurityManagerImpl.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/security/ActiveMQSecurityManagerImpl.java @@ -29,37 +29,31 @@ import org.apache.activemq.artemis.core.server.ActiveMQServerLogger; * A basic implementation of the ActiveMQSecurityManager. This can be used within an appserver and be deployed by * BasicUserCredentialsDeployer or used standalone or embedded. */ -public class ActiveMQSecurityManagerImpl implements ActiveMQSecurityManager -{ +public class ActiveMQSecurityManagerImpl implements ActiveMQSecurityManager { + private final SecurityConfiguration configuration; private ActiveMQServerLogger logger = ActiveMQServerLogger.LOGGER; - public ActiveMQSecurityManagerImpl() - { + public ActiveMQSecurityManagerImpl() { configuration = new SecurityConfiguration(); } - public ActiveMQSecurityManagerImpl(SecurityConfiguration configuration) - { + public ActiveMQSecurityManagerImpl(SecurityConfiguration configuration) { this.configuration = configuration; } // Public --------------------------------------------------------------------- - public boolean validateUser(final String username, final String password) - { - if (username != null) - { + public boolean validateUser(final String username, final String password) { + if (username != null) { User user = configuration.getUser(username); return user != null && user.isValid(username, password); } - else if (username == null && password == null) - { + else if (username == null && password == null) { return configuration.getDefaultUser() != null; } - else // the only possible case here is user == null, password != null - { + else { // the only possible case here is user == null, password != null logger.debug("Validating default user against a provided password. This happens when username=null, password!=null"); String defaultUsername = configuration.getDefaultUser(); User defaultUser = configuration.getUser(defaultUsername); @@ -70,26 +64,19 @@ public class ActiveMQSecurityManagerImpl implements ActiveMQSecurityManager public boolean validateUserAndRole(final String user, final String password, final Set roles, - final CheckType checkType) - { - if (validateUser(user, password)) - { + final CheckType checkType) { + if (validateUser(user, password)) { String defaultUser = configuration.getDefaultUser(); List availableRoles = configuration.getRole(user == null ? defaultUser : user); - if (availableRoles == null) - { + if (availableRoles == null) { return false; } - for (String availableRole : availableRoles) - { - if (roles != null) - { - for (Role role : roles) - { - if (role.getName().equals(availableRole) && checkType.hasRole(role)) - { + for (String availableRole : availableRoles) { + if (roles != null) { + for (Role role : roles) { + if (role.getName().equals(availableRole) && checkType.hasRole(role)) { return true; } } @@ -100,8 +87,7 @@ public class ActiveMQSecurityManagerImpl implements ActiveMQSecurityManager return false; } - public SecurityConfiguration getConfiguration() - { + public SecurityConfiguration getConfiguration() { return configuration; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/security/JAASSecurityManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/security/JAASSecurityManager.java index 60fca8227a..48699b64a1 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/security/JAASSecurityManager.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/security/JAASSecurityManager.java @@ -38,8 +38,7 @@ import org.apache.activemq.artemis.core.server.ActiveMQServerLogger; * The {@link Subject} returned by the login context is expecting to have a {@link Group} with the Roles name * containing a set of {@link Principal} for each role of the user. */ -public class JAASSecurityManager implements ActiveMQSecurityManager -{ +public class JAASSecurityManager implements ActiveMQSecurityManager { // Static -------------------------------------------------------- // Attributes ---------------------------------------------------- @@ -54,15 +53,12 @@ public class JAASSecurityManager implements ActiveMQSecurityManager // ActiveMQSecurityManager implementation ----------------------------- - public boolean validateUser(final String user, final String password) - { - try - { + public boolean validateUser(final String user, final String password) { + try { getAuthenticatedSubject(user, password); return true; } - catch (LoginException e1) - { + catch (LoginException e1) { return false; } } @@ -70,22 +66,18 @@ public class JAASSecurityManager implements ActiveMQSecurityManager public boolean validateUserAndRole(final String user, final String password, final Set roles, - final CheckType checkType) - { + final CheckType checkType) { Subject localSubject = null; - try - { + try { localSubject = getAuthenticatedSubject(user, password); } - catch (LoginException e1) - { + catch (LoginException e1) { return false; } boolean authenticated = true; - if (localSubject != null) - { + if (localSubject != null) { Set rolePrincipals = getRolePrincipals(checkType, roles); // authenticated = realmMapping.doesUserHaveRole(principal, rolePrincipals); @@ -95,11 +87,9 @@ public class JAASSecurityManager implements ActiveMQSecurityManager // Check the caller's roles Group subjectRoles = getSubjectRoles(localSubject); - if (subjectRoles != null) - { + if (subjectRoles != null) { Iterator iter = rolePrincipals.iterator(); - while (!hasRole && iter.hasNext()) - { + while (!hasRole && iter.hasNext()) { Principal role = iter.next(); hasRole = subjectRoles.isMember(role); } @@ -107,29 +97,25 @@ public class JAASSecurityManager implements ActiveMQSecurityManager authenticated = hasRole; - if (trace) - { + if (trace) { ActiveMQServerLogger.LOGGER.trace("user " + user + (authenticated ? " is " : " is NOT ") + "authorized"); } } return authenticated; } - private Subject getAuthenticatedSubject(final String user, final String password) throws LoginException - { + private Subject getAuthenticatedSubject(final String user, final String password) throws LoginException { SimplePrincipal principal = user == null ? null : new SimplePrincipal(user); char[] passwordChars = null; - if (password != null) - { + if (password != null) { passwordChars = password.toCharArray(); } Subject subject = new Subject(); - if (user != null) - { + if (user != null) { subject.getPrincipals().add(principal); } subject.getPrivateCredentials().add(passwordChars); @@ -139,30 +125,24 @@ public class JAASSecurityManager implements ActiveMQSecurityManager return lc.getSubject(); } - private Group getSubjectRoles(final Subject subject) - { + private Group getSubjectRoles(final Subject subject) { Set subjectGroups = subject.getPrincipals(Group.class); Iterator iter = subjectGroups.iterator(); Group roles = null; - while (iter.hasNext()) - { + while (iter.hasNext()) { Group grp = iter.next(); String name = grp.getName(); - if (name.equals("Roles")) - { + if (name.equals("Roles")) { roles = grp; } } return roles; } - private Set getRolePrincipals(final CheckType checkType, final Set roles) - { + private Set getRolePrincipals(final CheckType checkType, final Set roles) { Set principals = new HashSet(); - for (Role role : roles) - { - if (checkType.hasRole(role)) - { + for (Role role : roles) { + if (checkType.hasRole(role)) { principals.add(new SimplePrincipal(role.getName())); } } @@ -171,18 +151,15 @@ public class JAASSecurityManager implements ActiveMQSecurityManager // Public -------------------------------------------------------- - public void setConfigurationName(final String configurationName) - { + public void setConfigurationName(final String configurationName) { this.configurationName = configurationName; } - public void setCallbackHandler(final CallbackHandler handler) - { + public void setCallbackHandler(final CallbackHandler handler) { callbackHandler = handler; } - public void setConfiguration(final Configuration config) - { + public void setConfiguration(final Configuration config) { this.config = config; } @@ -190,54 +167,48 @@ public class JAASSecurityManager implements ActiveMQSecurityManager // Inner classes ------------------------------------------------- - public static class SimplePrincipal implements Principal, java.io.Serializable - { + public static class SimplePrincipal implements Principal, java.io.Serializable { + private static final long serialVersionUID = 1L; private final String name; - public SimplePrincipal(final String name) - { + public SimplePrincipal(final String name) { this.name = name; } - /** Compare this SimplePrincipal's name against another Principal - @return true if name equals another.getName(); + /** + * Compare this SimplePrincipal's name against another Principal + * + * @return true if name equals another.getName(); */ @Override - public boolean equals(final Object another) - { - if (!(another instanceof Principal)) - { + public boolean equals(final Object another) { + if (!(another instanceof Principal)) { return false; } - String anotherName = ((Principal)another).getName(); + String anotherName = ((Principal) another).getName(); boolean equals = false; - if (name == null) - { + if (name == null) { equals = anotherName == null; } - else - { + else { equals = name.equals(anotherName); } return equals; } @Override - public int hashCode() - { + public int hashCode() { return name == null ? 0 : name.hashCode(); } @Override - public String toString() - { + public String toString() { return name; } - public String getName() - { + public String getName() { return name; } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/uri/AcceptorTransportConfigurationParser.java b/artemis-server/src/main/java/org/apache/activemq/artemis/uri/AcceptorTransportConfigurationParser.java index 84b0a9346a..e8f7dce8c2 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/uri/AcceptorTransportConfigurationParser.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/uri/AcceptorTransportConfigurationParser.java @@ -22,10 +22,9 @@ import org.apache.activemq.artemis.utils.uri.URIFactory; import java.util.List; -public class AcceptorTransportConfigurationParser extends URIFactory, String> -{ - public AcceptorTransportConfigurationParser() - { +public class AcceptorTransportConfigurationParser extends URIFactory, String> { + + public AcceptorTransportConfigurationParser() { registerSchema(new TCPAcceptorTransportConfigurationSchema(TransportConstants.ALLOWABLE_ACCEPTOR_KEYS)); registerSchema(new InVMAcceptorTransportConfigurationSchema()); } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/uri/InVMAcceptorTransportConfigurationSchema.java b/artemis-server/src/main/java/org/apache/activemq/artemis/uri/InVMAcceptorTransportConfigurationSchema.java index aa7a9cfb0e..309a87871c 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/uri/InVMAcceptorTransportConfigurationSchema.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/uri/InVMAcceptorTransportConfigurationSchema.java @@ -18,10 +18,9 @@ package org.apache.activemq.artemis.uri; import org.apache.activemq.artemis.core.remoting.impl.invm.InVMAcceptorFactory; -public class InVMAcceptorTransportConfigurationSchema extends InVMTransportConfigurationSchema -{ - protected String getFactoryName() - { +public class InVMAcceptorTransportConfigurationSchema extends InVMTransportConfigurationSchema { + + protected String getFactoryName() { return InVMAcceptorFactory.class.getName(); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/uri/TCPAcceptorTransportConfigurationSchema.java b/artemis-server/src/main/java/org/apache/activemq/artemis/uri/TCPAcceptorTransportConfigurationSchema.java index a5d3af2c9d..7b11a95e76 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/uri/TCPAcceptorTransportConfigurationSchema.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/uri/TCPAcceptorTransportConfigurationSchema.java @@ -21,15 +21,13 @@ import org.apache.activemq.artemis.core.remoting.impl.netty.NettyAcceptorFactory import java.net.URI; import java.util.Set; -public class TCPAcceptorTransportConfigurationSchema extends TCPTransportConfigurationSchema -{ - public TCPAcceptorTransportConfigurationSchema(Set allowableProperties) - { +public class TCPAcceptorTransportConfigurationSchema extends TCPTransportConfigurationSchema { + + public TCPAcceptorTransportConfigurationSchema(Set allowableProperties) { super(allowableProperties); } - public String getFactoryName(URI uri) - { + public String getFactoryName(URI uri) { return NettyAcceptorFactory.class.getName(); } } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/utils/XMLConfigurationUtil.java b/artemis-server/src/main/java/org/apache/activemq/artemis/utils/XMLConfigurationUtil.java index b0fe58d09a..1327cf918d 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/utils/XMLConfigurationUtil.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/utils/XMLConfigurationUtil.java @@ -21,16 +21,13 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -public class XMLConfigurationUtil -{ +public class XMLConfigurationUtil { - public static final String getAttributeValue(Node element, String attribute) - { + public static final String getAttributeValue(Node element, String attribute) { return element.getAttributes().getNamedItem(attribute).getNodeValue(); } - public static final String getTrimmedTextContent(Node element) - { + public static final String getTrimmedTextContent(Node element) { String content = element.getTextContent(); if (content == null) return null; @@ -38,101 +35,85 @@ public class XMLConfigurationUtil } public static final Double getDouble(final Element e, - final String name, - final double def, - final Validators.Validator validator) - { + final String name, + final double def, + final Validators.Validator validator) { NodeList nl = e.getElementsByTagName(name); - if (nl.getLength() > 0) - { + if (nl.getLength() > 0) { double val = XMLUtil.parseDouble(nl.item(0)); validator.validate(name, val); return val; } - else - { + else { validator.validate(name, def); return def; } } public static final String getString(final Element e, - final String name, - final String def, - final Validators.Validator validator) - { + final String name, + final String def, + final Validators.Validator validator) { NodeList nl = e.getElementsByTagName(name); - if (nl.getLength() > 0) - { + if (nl.getLength() > 0) { String val = nl.item(0).getTextContent().trim(); validator.validate(name, val); return val; } - else - { + else { validator.validate(name, def); return def; } } - public static final Long getLong(final Element e, final String name, final long def, - final Validators.Validator validator) - { + public static final Long getLong(final Element e, + final String name, + final long def, + final Validators.Validator validator) { NodeList nl = e.getElementsByTagName(name); - if (nl.getLength() > 0) - { + if (nl.getLength() > 0) { long val = XMLUtil.parseLong(nl.item(0)); validator.validate(name, val); return val; } - else - { + else { validator.validate(name, def); return def; } } public static final Integer getInteger(final Element e, - final String name, - final int def, - final Validators.Validator validator) - { + final String name, + final int def, + final Validators.Validator validator) { NodeList nl = e.getElementsByTagName(name); - if (nl.getLength() > 0) - { + if (nl.getLength() > 0) { int val = XMLUtil.parseInt(nl.item(0)); validator.validate(name, val); return val; } - else - { + else { validator.validate(name, def); return def; } } - public static final Boolean getBoolean(final Element e, final String name, final boolean def) - { + public static final Boolean getBoolean(final Element e, final String name, final boolean def) { NodeList nl = e.getElementsByTagName(name); - if (nl.getLength() > 0) - { + if (nl.getLength() > 0) { return XMLUtil.parseBoolean(nl.item(0)); } - else - { + else { return def; } } - public static final Boolean parameterExists(final Element e, final String name) - { + public static final Boolean parameterExists(final Element e, final String name) { NodeList nl = e.getElementsByTagName(name); - if (nl.getLength() > 0) - { + if (nl.getLength() > 0) { return true; } - else - { + else { return false; } } diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/ConfigurationImplTest.java b/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/ConfigurationImplTest.java index b6d036f934..1fdcdbdf24 100644 --- a/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/ConfigurationImplTest.java +++ b/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/ConfigurationImplTest.java @@ -28,17 +28,14 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class ConfigurationImplTest extends ActiveMQTestBase -{ +public class ConfigurationImplTest extends ActiveMQTestBase { + protected Configuration conf; @Test - public void testDefaults() - { - Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultScheduledThreadPoolMaxSize(), - conf.getScheduledThreadPoolMaxSize()); - Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultSecurityInvalidationInterval(), - conf.getSecurityInvalidationInterval()); + public void testDefaults() { + Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultScheduledThreadPoolMaxSize(), conf.getScheduledThreadPoolMaxSize()); + Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultSecurityInvalidationInterval(), conf.getSecurityInvalidationInterval()); Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultSecurityEnabled(), conf.isSecurityEnabled()); Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultBindingsDirectory(), conf.getBindingsDirectory()); Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultCreateBindingsDir(), conf.isCreateBindingsDir()); @@ -46,8 +43,7 @@ public class ConfigurationImplTest extends ActiveMQTestBase Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultCreateJournalDir(), conf.isCreateJournalDir()); Assert.assertEquals(ConfigurationImpl.DEFAULT_JOURNAL_TYPE, conf.getJournalType()); Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultJournalSyncTransactional(), conf.isJournalSyncTransactional()); - Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultJournalSyncNonTransactional(), - conf.isJournalSyncNonTransactional()); + Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultJournalSyncNonTransactional(), conf.isJournalSyncNonTransactional()); Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultJournalFileSize(), conf.getJournalFileSize()); Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultJournalMinFiles(), conf.getJournalMinFiles()); Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultJournalMaxIoAio(), conf.getJournalMaxIO_AIO()); @@ -55,24 +51,19 @@ public class ConfigurationImplTest extends ActiveMQTestBase Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultWildcardRoutingEnabled(), conf.isWildcardRoutingEnabled()); Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultTransactionTimeout(), conf.getTransactionTimeout()); Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultMessageExpiryScanPeriod(), conf.getMessageExpiryScanPeriod()); // OK - Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultMessageExpiryThreadPriority(), - conf.getMessageExpiryThreadPriority()); // OK - Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultTransactionTimeoutScanPeriod(), - conf.getTransactionTimeoutScanPeriod()); // OK + Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultMessageExpiryThreadPriority(), conf.getMessageExpiryThreadPriority()); // OK + Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultTransactionTimeoutScanPeriod(), conf.getTransactionTimeoutScanPeriod()); // OK Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultManagementAddress(), conf.getManagementAddress()); // OK - Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultManagementNotificationAddress(), - conf.getManagementNotificationAddress()); // OK + Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultManagementNotificationAddress(), conf.getManagementNotificationAddress()); // OK Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultClusterUser(), conf.getClusterUser()); // OK Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultClusterPassword(), conf.getClusterPassword()); // OK Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultPersistenceEnabled(), conf.isPersistenceEnabled()); - Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultPersistDeliveryCountBeforeDelivery(), - conf.isPersistDeliveryCountBeforeDelivery()); + Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultPersistDeliveryCountBeforeDelivery(), conf.isPersistDeliveryCountBeforeDelivery()); Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultFileDeployerScanPeriod(), conf.getFileDeployerScanPeriod()); Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultThreadPoolMaxSize(), conf.getThreadPoolMaxSize()); Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultJmxManagementEnabled(), conf.isJMXManagementEnabled()); Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultConnectionTtlOverride(), conf.getConnectionTTLOverride()); - Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultAsyncConnectionExecutionEnabled(), - conf.isAsyncConnectionExecutionEnabled()); + Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultAsyncConnectionExecutionEnabled(), conf.isAsyncConnectionExecutionEnabled()); Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultPagingDir(), conf.getPagingDirectory()); Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultLargeMessagesDir(), conf.getLargeMessagesDirectory()); Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultJournalCompactPercentage(), conf.getJournalCompactPercentage()); @@ -83,8 +74,7 @@ public class ConfigurationImplTest extends ActiveMQTestBase Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultJournalLogWriteRate(), conf.isLogJournalWriteRate()); Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultJournalPerfBlastPages(), conf.getJournalPerfBlastPages()); Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultMessageCounterEnabled(), conf.isMessageCounterEnabled()); - Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultMessageCounterMaxDayHistory(), - conf.getMessageCounterMaxDayHistory()); + Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultMessageCounterMaxDayHistory(), conf.getMessageCounterMaxDayHistory()); Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultMessageCounterSamplePeriod(), conf.getMessageCounterSamplePeriod()); Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultIdCacheSize(), conf.getIDCacheSize()); Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultPersistIdCache(), conf.isPersistIDCache()); @@ -94,10 +84,8 @@ public class ConfigurationImplTest extends ActiveMQTestBase } @Test - public void testSetGetAttributes() throws Exception - { - for (int j = 0; j < 100; j++) - { + public void testSetGetAttributes() throws Exception { + for (int j = 0; j < 100; j++) { int i = RandomUtil.randomInt(); conf.setScheduledThreadPoolMaxSize(i); Assert.assertEquals(i, conf.getScheduledThreadPoolMaxSize()); @@ -286,8 +274,7 @@ public class ConfigurationImplTest extends ActiveMQTestBase } @Test - public void testGetSetInterceptors() - { + public void testGetSetInterceptors() { final String name1 = "uqwyuqywuy"; final String name2 = "yugyugyguyg"; @@ -300,8 +287,7 @@ public class ConfigurationImplTest extends ActiveMQTestBase } @Test - public void testSerialize() throws Exception - { + public void testSerialize() throws Exception { boolean b = RandomUtil.randomBoolean(); conf.setHAPolicyConfiguration(new LiveOnlyPolicyConfiguration()); @@ -403,7 +389,6 @@ public class ConfigurationImplTest extends ActiveMQTestBase conf.setThreadPoolMaxSize(i); Assert.assertEquals(i, conf.getThreadPoolMaxSize()); - SimpleString ss = RandomUtil.randomSimpleString(); conf.setManagementNotificationAddress(ss); Assert.assertEquals(ss, conf.getManagementNotificationAddress()); @@ -495,21 +480,18 @@ public class ConfigurationImplTest extends ActiveMQTestBase // This will use serialization to perform a deep copy of the object Configuration conf2 = conf.copy(); - Assert.assertTrue(conf.equals(conf2)); } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); conf = createConfiguration(); } - protected Configuration createConfiguration() throws Exception - { + protected Configuration createConfiguration() throws Exception { return new ConfigurationImpl(); } } diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/DefaultsFileConfigurationTest.java b/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/DefaultsFileConfigurationTest.java index 22197c4fbe..cd5a3f6a5f 100644 --- a/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/DefaultsFileConfigurationTest.java +++ b/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/DefaultsFileConfigurationTest.java @@ -28,20 +28,17 @@ import org.junit.Assert; import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.core.journal.impl.JournalConstants; -public class DefaultsFileConfigurationTest extends ConfigurationImplTest -{ +public class DefaultsFileConfigurationTest extends ConfigurationImplTest { + @Override @Test - public void testDefaults() - { + public void testDefaults() { - Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultScheduledThreadPoolMaxSize(), - conf.getScheduledThreadPoolMaxSize()); + Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultScheduledThreadPoolMaxSize(), conf.getScheduledThreadPoolMaxSize()); Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultThreadPoolMaxSize(), conf.getThreadPoolMaxSize()); - Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultSecurityInvalidationInterval(), - conf.getSecurityInvalidationInterval()); + Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultSecurityInvalidationInterval(), conf.getSecurityInvalidationInterval()); Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultSecurityEnabled(), conf.isSecurityEnabled()); @@ -71,8 +68,7 @@ public class DefaultsFileConfigurationTest extends ConfigurationImplTest Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultManagementAddress(), conf.getManagementAddress()); - Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultManagementNotificationAddress(), - conf.getManagementNotificationAddress()); + Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultManagementNotificationAddress(), conf.getManagementNotificationAddress()); Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultClusterUser(), conf.getClusterUser()); @@ -90,8 +86,7 @@ public class DefaultsFileConfigurationTest extends ConfigurationImplTest Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultJournalSyncTransactional(), conf.isJournalSyncTransactional()); - Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultJournalSyncNonTransactional(), - conf.isJournalSyncNonTransactional()); + Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultJournalSyncNonTransactional(), conf.isJournalSyncNonTransactional()); Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultJournalFileSize(), conf.getJournalFileSize()); @@ -127,13 +122,11 @@ public class DefaultsFileConfigurationTest extends ConfigurationImplTest Assert.assertEquals(ActiveMQDefaultConfiguration.isDefaultMessageCounterEnabled(), conf.isMessageCounterEnabled()); - Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultTransactionTimeoutScanPeriod(), - conf.getTransactionTimeoutScanPeriod()); + Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultTransactionTimeoutScanPeriod(), conf.getTransactionTimeoutScanPeriod()); Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultMessageExpiryScanPeriod(), conf.getMessageExpiryScanPeriod()); - Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultMessageExpiryThreadPriority(), - conf.getMessageExpiryThreadPriority()); + Assert.assertEquals(ActiveMQDefaultConfiguration.getDefaultMessageExpiryThreadPriority(), conf.getMessageExpiryThreadPriority()); Assert.assertTrue(conf.getHAPolicyConfiguration() instanceof LiveOnlyPolicyConfiguration); @@ -145,8 +138,7 @@ public class DefaultsFileConfigurationTest extends ConfigurationImplTest // Protected --------------------------------------------------------------------------------------------- @Override - protected Configuration createConfiguration() throws Exception - { + protected Configuration createConfiguration() throws Exception { FileConfiguration fc = new FileConfiguration(); FileDeploymentManager deploymentManager = new FileDeploymentManager("ConfigurationTest-defaults.xml"); deploymentManager.addDeployable(fc); diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/FileConfigurationParserTest.java b/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/FileConfigurationParserTest.java index 2e2e90b906..e2d2f83860 100644 --- a/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/FileConfigurationParserTest.java +++ b/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/FileConfigurationParserTest.java @@ -29,8 +29,8 @@ import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; -public class FileConfigurationParserTest extends ActiveMQTestBase -{ +public class FileConfigurationParserTest extends ActiveMQTestBase { + /** * These "InvalidConfigurationTest*.xml" files are modified copies of {@value * ConfigurationTest-full-config.xml}, so just diff it for changes, e.g. @@ -42,22 +42,18 @@ public class FileConfigurationParserTest extends ActiveMQTestBase * @throws Exception */ @Test - public void testSchemaValidation() throws Exception - { - for (int i = 0; i < 6; i++) - { + public void testSchemaValidation() throws Exception { + for (int i = 0; i < 6; i++) { String filename = "InvalidConfigurationTest" + i + ".xml"; FileConfiguration fc = new FileConfiguration(); FileDeploymentManager deploymentManager = new FileDeploymentManager(filename); deploymentManager.addDeployable(fc); - try - { + try { deploymentManager.readConfiguration(); fail("parsing should have failed for " + filename); } - catch (java.lang.IllegalStateException e) - { + catch (java.lang.IllegalStateException e) { Throwable cause = e.getCause(); assertTrue("must have been org.xml.sax.SAXParseException", cause instanceof org.xml.sax.SAXParseException); } @@ -65,8 +61,7 @@ public class FileConfigurationParserTest extends ActiveMQTestBase } @Test - public void testDivertRoutingNameIsNotRequired() throws Exception - { + public void testDivertRoutingNameIsNotRequired() throws Exception { String filename = "divertRoutingNameNotRequired.xml"; FileConfiguration fc = new FileConfiguration(); FileDeploymentManager deploymentManager = new FileDeploymentManager(filename); @@ -75,8 +70,7 @@ public class FileConfigurationParserTest extends ActiveMQTestBase } @Test - public void testParsingDefaultServerConfig() throws Exception - { + public void testParsingDefaultServerConfig() throws Exception { FileConfigurationParser parser = new FileConfigurationParser(); String configStr = firstPart + lastPart; @@ -130,46 +124,38 @@ public class FileConfigurationParserTest extends ActiveMQTestBase assertEquals("newpassword", config.getClusterPassword()); } - private static String firstPart = - "" + "\n" + - "ActiveMQ.main.config" + "\n" + - "org.apache.activemq.artemis.integration.logging.Log4jLogDelegateFactory" + "\n" + - "${jboss.server.data.dir}/activemq/bindings" + "\n" + - "${jboss.server.data.dir}/activemq/journal" + "\n" + - "10" + "\n" + - "${jboss.server.data.dir}/activemq/largemessages" + "\n" + - "${jboss.server.data.dir}/activemq/paging" + "\n" + - "" + "\n" + - "tcp://localhost:61616" + "\n" + - "tcp://localhost:5545" + "\n" + - "vm://0" + "\n" + - "" + "\n" + - "" + "\n" + - "tcp://localhost:5545" + "\n" + - "tcp://localhost:5545" + "\n" + - "vm://0" + "\n" + - "" + "\n" + - "" + "\n" + - "" + "\n" + - "" + "\n" + - "" + "\n" + - "" + "\n" + - "" + "\n" + - "" + "\n" + - "" + "\n" + - "" + "\n" + - "" + "\n" + - "" + "\n" + - "" - + "\n" + "jms.queue.DLQ\n" + "\n" - + "jms.queue.ExpiryQueue\n" + "\n" - + "0\n" + "\n" - + "10485760\n" + "\n" - + "10" + "\n" - + "BLOCK" + "\n" + - "" + "\n" + - "" + "\n"; - + private static String firstPart = "" + "\n" + + "ActiveMQ.main.config" + "\n" + + "org.apache.activemq.artemis.integration.logging.Log4jLogDelegateFactory" + "\n" + + "${jboss.server.data.dir}/activemq/bindings" + "\n" + + "${jboss.server.data.dir}/activemq/journal" + "\n" + + "10" + "\n" + + "${jboss.server.data.dir}/activemq/largemessages" + "\n" + + "${jboss.server.data.dir}/activemq/paging" + "\n" + + "" + "\n" + + "tcp://localhost:61616" + "\n" + + "tcp://localhost:5545" + "\n" + + "vm://0" + "\n" + + "" + "\n" + + "" + "\n" + + "tcp://localhost:5545" + "\n" + + "tcp://localhost:5545" + "\n" + + "vm://0" + "\n" + + "" + "\n" + + "" + "\n" + + "" + "\n" + + "" + "\n" + + "" + "\n" + + "" + "\n" + + "" + "\n" + + "" + "\n" + + "" + "\n" + + "" + "\n" + + "" + "\n" + + "" + "\n" + + "" + "\n" + "jms.queue.DLQ\n" + "\n" + "jms.queue.ExpiryQueue\n" + "\n" + "0\n" + "\n" + "10485760\n" + "\n" + "10" + "\n" + "BLOCK" + "\n" + + "" + "\n" + + "" + "\n"; private static String lastPart = ""; } diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/FileConfigurationTest.java b/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/FileConfigurationTest.java index 94118ebdc0..b809aa4ca0 100644 --- a/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/FileConfigurationTest.java +++ b/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/FileConfigurationTest.java @@ -44,15 +44,13 @@ import org.apache.activemq.artemis.core.settings.impl.SlowConsumerPolicy; import org.junit.Assert; import org.junit.Test; -public class FileConfigurationTest extends ConfigurationImplTest -{ +public class FileConfigurationTest extends ConfigurationImplTest { private final String fullConfigurationName = "ConfigurationTest-full-config.xml"; @Override @Test - public void testDefaults() - { + public void testDefaults() { // Check they match the values from the test file Assert.assertEquals("SomeNameForUseOnTheApplicationServer", conf.getName()); Assert.assertEquals(false, conf.isPersistenceEnabled()); @@ -104,11 +102,8 @@ public class FileConfigurationTest extends ConfigurationImplTest Assert.assertEquals(95, conf.getMemoryWarningThreshold()); Assert.assertEquals(2, conf.getIncomingInterceptorClassNames().size()); - Assert.assertTrue(conf.getIncomingInterceptorClassNames() - .contains("org.apache.activemq.artemis.tests.unit.core.config.impl.TestInterceptor1")); - Assert.assertTrue(conf.getIncomingInterceptorClassNames() - .contains("org.apache.activemq.artemis.tests.unit.core.config.impl.TestInterceptor2")); - + Assert.assertTrue(conf.getIncomingInterceptorClassNames().contains("org.apache.activemq.artemis.tests.unit.core.config.impl.TestInterceptor1")); + Assert.assertTrue(conf.getIncomingInterceptorClassNames().contains("org.apache.activemq.artemis.tests.unit.core.config.impl.TestInterceptor2")); Assert.assertEquals(2, conf.getConnectorConfigurations().size()); @@ -126,29 +121,23 @@ public class FileConfigurationTest extends ConfigurationImplTest Assert.assertEquals("5", tc.getParams().get("serverId")); Assert.assertEquals(2, conf.getAcceptorConfigurations().size()); - for (TransportConfiguration ac : conf.getAcceptorConfigurations()) - { - if (ac.getFactoryClassName().equals("org.apache.activemq.artemis.core.remoting.impl.netty.NettyAcceptorFactory")) - { + for (TransportConfiguration ac : conf.getAcceptorConfigurations()) { + if (ac.getFactoryClassName().equals("org.apache.activemq.artemis.core.remoting.impl.netty.NettyAcceptorFactory")) { Assert.assertEquals("456", ac.getParams().get("tcpNoDelay")); Assert.assertEquals("44", ac.getParams().get("connectionTtl")); Assert.assertEquals("92", ac.getParams().get(TransportConstants.CONNECTIONS_ALLOWED)); } - else - { - Assert.assertEquals("org.apache.activemq.artemis.core.remoting.impl.invm.InVMAcceptorFactory", - ac.getFactoryClassName()); + else { + Assert.assertEquals("org.apache.activemq.artemis.core.remoting.impl.invm.InVMAcceptorFactory", ac.getFactoryClassName()); Assert.assertEquals("0", ac.getParams().get("serverId")); Assert.assertEquals("87", ac.getParams().get(org.apache.activemq.artemis.core.remoting.impl.invm.TransportConstants.CONNECTIONS_ALLOWED)); } } Assert.assertEquals(2, conf.getBroadcastGroupConfigurations().size()); - for (BroadcastGroupConfiguration bc : conf.getBroadcastGroupConfigurations()) - { + for (BroadcastGroupConfiguration bc : conf.getBroadcastGroupConfigurations()) { UDPBroadcastEndpointFactory udpBc = (UDPBroadcastEndpointFactory) bc.getEndpointFactory(); - if (bc.getName().equals("bg1")) - { + if (bc.getName().equals("bg1")) { Assert.assertEquals("bg1", bc.getName()); Assert.assertEquals(10999, udpBc.getLocalBindPort()); Assert.assertEquals("192.168.0.120", udpBc.getGroupAddress()); @@ -156,8 +145,7 @@ public class FileConfigurationTest extends ConfigurationImplTest Assert.assertEquals(12345, bc.getBroadcastPeriod()); Assert.assertEquals("connector1", bc.getConnectorInfos().get(0)); } - else - { + else { Assert.assertEquals("bg2", bc.getName()); Assert.assertEquals(12999, udpBc.getLocalBindPort()); Assert.assertEquals("192.168.0.121", udpBc.getGroupAddress()); @@ -183,10 +171,8 @@ public class FileConfigurationTest extends ConfigurationImplTest Assert.assertEquals(23456, dc.getRefreshTimeout()); Assert.assertEquals(2, conf.getDivertConfigurations().size()); - for (DivertConfiguration dic : conf.getDivertConfigurations()) - { - if (dic.getName().equals("divert1")) - { + for (DivertConfiguration dic : conf.getDivertConfigurations()) { + if (dic.getName().equals("divert1")) { Assert.assertEquals("divert1", dic.getName()); Assert.assertEquals("routing-name1", dic.getRoutingName()); Assert.assertEquals("address1", dic.getAddress()); @@ -195,8 +181,7 @@ public class FileConfigurationTest extends ConfigurationImplTest Assert.assertEquals("org.foo.Transformer", dic.getTransformerClassName()); Assert.assertEquals(true, dic.isExclusive()); } - else - { + else { Assert.assertEquals("divert2", dic.getName()); Assert.assertEquals("routing-name2", dic.getRoutingName()); Assert.assertEquals("address2", dic.getAddress()); @@ -208,10 +193,8 @@ public class FileConfigurationTest extends ConfigurationImplTest } Assert.assertEquals(2, conf.getBridgeConfigurations().size()); - for (BridgeConfiguration bc : conf.getBridgeConfigurations()) - { - if (bc.getName().equals("bridge1")) - { + for (BridgeConfiguration bc : conf.getBridgeConfigurations()) { + if (bc.getName().equals("bridge1")) { Assert.assertEquals("bridge1", bc.getName()); Assert.assertEquals("queue1", bc.getQueueName()); Assert.assertEquals("minLargeMessageSize", 4, bc.getMinLargeMessageSize()); @@ -228,8 +211,7 @@ public class FileConfigurationTest extends ConfigurationImplTest Assert.assertEquals("connector1", bc.getStaticConnectors().get(0)); Assert.assertEquals(null, bc.getDiscoveryGroupName()); } - else - { + else { Assert.assertEquals("bridge2", bc.getName()); Assert.assertEquals("queue2", bc.getQueueName()); Assert.assertEquals("bridge-forwarding-address2", bc.getForwardingAddress()); @@ -250,10 +232,8 @@ public class FileConfigurationTest extends ConfigurationImplTest assertEquals(lopc.getScaleDownConfiguration().getGroupName(), "boo!"); assertEquals(lopc.getScaleDownConfiguration().getDiscoveryGroup(), "dg1"); - for (ClusterConnectionConfiguration ccc : conf.getClusterConfigurations()) - { - if (ccc.getName().equals("cluster-connection1")) - { + for (ClusterConnectionConfiguration ccc : conf.getClusterConfigurations()) { + if (ccc.getName().equals("cluster-connection1")) { Assert.assertEquals("cluster-connection1", ccc.getName()); Assert.assertEquals("clusterConnectionConf minLargeMessageSize", 321, ccc.getMinLargeMessageSize()); assertEquals("check-period", 331, ccc.getClientFailureCheckPeriod()); @@ -272,8 +252,7 @@ public class FileConfigurationTest extends ConfigurationImplTest Assert.assertEquals("connector2", ccc.getStaticConnectors().get(1)); Assert.assertEquals(null, ccc.getDiscoveryGroupName()); } - else - { + else { Assert.assertEquals("cluster-connection2", ccc.getName()); Assert.assertEquals("queues2", ccc.getAddress()); Assert.assertEquals(4, ccc.getRetryInterval()); @@ -287,7 +266,6 @@ public class FileConfigurationTest extends ConfigurationImplTest } } - assertEquals(2, conf.getAddressesSettings().size()); assertTrue(conf.getAddressesSettings().get("a1") != null); @@ -361,16 +339,14 @@ public class FileConfigurationTest extends ConfigurationImplTest assertTrue(a2Role.isDeleteNonDurableQueue()); assertFalse(a2Role.isManage()); - } + @Test - public void testContextClassLoaderUsage() throws Exception - { + public void testContextClassLoaderUsage() throws Exception { final File customConfiguration = File.createTempFile("hornetq-unittest", ".xml"); - try - { + try { // copy working configuration to a location where the standard classloader cannot find it final Path workingConfiguration = new File(getClass().getResource("/" + fullConfigurationName).toURI()).toPath(); @@ -387,28 +363,24 @@ public class FileConfigurationTest extends ConfigurationImplTest expect no exception in this thread when the class loading works as expected */ - final class ThrowableHolder - { + final class ThrowableHolder { + volatile Exception t; } final ThrowableHolder holder = new ThrowableHolder(); - final Thread webappContextThread = new Thread(new Runnable() - { + final Thread webappContextThread = new Thread(new Runnable() { @Override - public void run() - { + public void run() { FileConfiguration fileConfiguration = new FileConfiguration(); - try - { + try { FileDeploymentManager deploymentManager = new FileDeploymentManager(customConfiguration.getName()); deploymentManager.addDeployable(fileConfiguration); deploymentManager.readConfiguration(); } - catch (Exception e) - { + catch (Exception e) { holder.t = e; } } @@ -419,22 +391,18 @@ public class FileConfigurationTest extends ConfigurationImplTest webappContextThread.start(); webappContextThread.join(); - if (holder.t != null) - { + if (holder.t != null) { fail("Exception caught while loading configuration with the context class loader: " + holder.t.getMessage()); } } - finally - { + finally { customConfiguration.delete(); } } - @Override - protected Configuration createConfiguration() throws Exception - { + protected Configuration createConfiguration() throws Exception { FileConfiguration fc = new FileConfiguration(); FileDeploymentManager deploymentManager = new FileDeploymentManager(fullConfigurationName); deploymentManager.addDeployable(fc); diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/HAPolicyConfigurationTest.java b/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/HAPolicyConfigurationTest.java index 16a8616729..9f5d2c52e7 100644 --- a/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/HAPolicyConfigurationTest.java +++ b/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/HAPolicyConfigurationTest.java @@ -39,15 +39,13 @@ import org.junit.Test; import java.util.List; -public class HAPolicyConfigurationTest extends ActiveMQTestBase -{ +public class HAPolicyConfigurationTest extends ActiveMQTestBase { + @Test - public void liveOnlyTest() throws Exception - { + public void liveOnlyTest() throws Exception { Configuration configuration = createConfiguration("live-only-hapolicy-config.xml"); ActiveMQServerImpl server = new ActiveMQServerImpl(configuration); - try - { + try { server.start(); Activation activation = server.getActivation(); assertTrue(activation instanceof LiveOnlyActivation); @@ -62,19 +60,16 @@ public class HAPolicyConfigurationTest extends ActiveMQTestBase assertNotNull(connectors); assertEquals(connectors.size(), 0); } - finally - { + finally { server.stop(); } } @Test - public void liveOnlyTest2() throws Exception - { + public void liveOnlyTest2() throws Exception { Configuration configuration = createConfiguration("live-only-hapolicy-config2.xml"); ActiveMQServerImpl server = new ActiveMQServerImpl(configuration); - try - { + try { server.start(); Activation activation = server.getActivation(); assertTrue(activation instanceof LiveOnlyActivation); @@ -92,36 +87,31 @@ public class HAPolicyConfigurationTest extends ActiveMQTestBase assertTrue(connectors.contains("sd-connector1")); assertTrue(connectors.contains("sd-connector2")); } - finally - { + finally { server.stop(); } } @Test - public void liveOnlyTest3() throws Exception - { + public void liveOnlyTest3() throws Exception { liveOnlyTest("live-only-hapolicy-config3.xml"); } @Test - public void liveOnlyTest4() throws Exception - { + public void liveOnlyTest4() throws Exception { liveOnlyTest("live-only-hapolicy-config4.xml"); } + @Test - public void liveOnlyTest5() throws Exception - { + public void liveOnlyTest5() throws Exception { liveOnlyTest("live-only-hapolicy-config5.xml"); } @Test - public void ReplicatedTest() throws Exception - { + public void ReplicatedTest() throws Exception { Configuration configuration = createConfiguration("replicated-hapolicy-config.xml"); ActiveMQServerImpl server = new ActiveMQServerImpl(configuration); - try - { + try { server.start(); Activation activation = server.getActivation(); assertTrue(activation instanceof SharedNothingLiveActivation); @@ -132,19 +122,16 @@ public class HAPolicyConfigurationTest extends ActiveMQTestBase assertTrue(replicatedPolicy.isCheckForLiveServer()); assertEquals(replicatedPolicy.getClusterName(), "abcdefg"); } - finally - { + finally { server.stop(); } } @Test - public void ReplicaTest() throws Exception - { + public void ReplicaTest() throws Exception { Configuration configuration = createConfiguration("replica-hapolicy-config.xml"); ActiveMQServerImpl server = new ActiveMQServerImpl(configuration); - try - { + try { server.start(); Activation activation = server.getActivation(); assertTrue(activation instanceof SharedNothingBackupActivation); @@ -163,19 +150,16 @@ public class HAPolicyConfigurationTest extends ActiveMQTestBase assertNotNull(connectors); assertEquals(connectors.size(), 0); } - finally - { + finally { server.stop(); } } @Test - public void ReplicaTest2() throws Exception - { + public void ReplicaTest2() throws Exception { Configuration configuration = createConfiguration("replica-hapolicy-config2.xml"); ActiveMQServerImpl server = new ActiveMQServerImpl(configuration); - try - { + try { server.start(); Activation activation = server.getActivation(); assertTrue(activation instanceof SharedNothingBackupActivation); @@ -196,19 +180,16 @@ public class HAPolicyConfigurationTest extends ActiveMQTestBase assertTrue(connectors.contains("sd-connector1")); assertTrue(connectors.contains("sd-connector2")); } - finally - { + finally { server.stop(); } } @Test - public void ReplicaTest3() throws Exception - { + public void ReplicaTest3() throws Exception { Configuration configuration = createConfiguration("replica-hapolicy-config3.xml"); ActiveMQServerImpl server = new ActiveMQServerImpl(configuration); - try - { + try { server.start(); Activation activation = server.getActivation(); assertTrue(activation instanceof SharedNothingBackupActivation); @@ -222,19 +203,16 @@ public class HAPolicyConfigurationTest extends ActiveMQTestBase ScaleDownPolicy scaleDownPolicy = replicaPolicy.getScaleDownPolicy(); assertNull(scaleDownPolicy); } - finally - { + finally { server.stop(); } } @Test - public void SharedStoreMasterTest() throws Exception - { + public void SharedStoreMasterTest() throws Exception { Configuration configuration = createConfiguration("shared-store-master-hapolicy-config.xml"); ActiveMQServerImpl server = new ActiveMQServerImpl(configuration); - try - { + try { server.start(); Activation activation = server.getActivation(); assertTrue(activation instanceof SharedStoreLiveActivation); @@ -244,19 +222,16 @@ public class HAPolicyConfigurationTest extends ActiveMQTestBase assertEquals(masterPolicy.getFailbackDelay(), 3456); assertFalse(masterPolicy.isFailoverOnServerShutdown()); } - finally - { + finally { server.stop(); } } @Test - public void SharedStoreSlaveTest() throws Exception - { + public void SharedStoreSlaveTest() throws Exception { Configuration configuration = createConfiguration("shared-store-slave-hapolicy-config.xml"); ActiveMQServerImpl server = new ActiveMQServerImpl(configuration); - try - { + try { server.start(); Activation activation = server.getActivation(); assertTrue(activation instanceof SharedStoreBackupActivation); @@ -274,19 +249,16 @@ public class HAPolicyConfigurationTest extends ActiveMQTestBase assertNotNull(connectors); assertEquals(connectors.size(), 0); } - finally - { + finally { server.stop(); } } @Test - public void SharedStoreSlaveTest2() throws Exception - { + public void SharedStoreSlaveTest2() throws Exception { Configuration configuration = createConfiguration("shared-store-slave-hapolicy-config2.xml"); ActiveMQServerImpl server = new ActiveMQServerImpl(configuration); - try - { + try { server.start(); Activation activation = server.getActivation(); assertTrue(activation instanceof SharedStoreBackupActivation); @@ -306,19 +278,16 @@ public class HAPolicyConfigurationTest extends ActiveMQTestBase assertTrue(connectors.contains("sd-connector1")); assertTrue(connectors.contains("sd-connector2")); } - finally - { + finally { server.stop(); } } @Test - public void SharedStoreSlaveTest3() throws Exception - { + public void SharedStoreSlaveTest3() throws Exception { Configuration configuration = createConfiguration("shared-store-slave-hapolicy-config3.xml"); ActiveMQServerImpl server = new ActiveMQServerImpl(configuration); - try - { + try { server.start(); Activation activation = server.getActivation(); assertTrue(activation instanceof SharedStoreBackupActivation); @@ -331,19 +300,16 @@ public class HAPolicyConfigurationTest extends ActiveMQTestBase ScaleDownPolicy scaleDownPolicy = replicaPolicy.getScaleDownPolicy(); assertNull(scaleDownPolicy); } - finally - { + finally { server.stop(); } } @Test - public void colocatedTest() throws Exception - { + public void colocatedTest() throws Exception { Configuration configuration = createConfiguration("colocated-hapolicy-config.xml"); ActiveMQServerImpl server = new ActiveMQServerImpl(configuration); - try - { + try { server.start(); Activation activation = server.getActivation(); assertTrue(activation instanceof ColocatedActivation); @@ -363,20 +329,16 @@ public class HAPolicyConfigurationTest extends ActiveMQTestBase assertEquals(backupPolicy.getClusterName(), "33rrrrr"); assertFalse(backupPolicy.isRestartBackup()); } - finally - { + finally { server.stop(); } } - @Test - public void colocatedTest2() throws Exception - { + public void colocatedTest2() throws Exception { Configuration configuration = createConfiguration("colocated-hapolicy-config2.xml"); ActiveMQServerImpl server = new ActiveMQServerImpl(configuration); - try - { + try { server.start(); Activation activation = server.getActivation(); assertTrue(activation instanceof ColocatedActivation); @@ -394,18 +356,15 @@ public class HAPolicyConfigurationTest extends ActiveMQTestBase assertFalse(backupPolicy.isFailoverOnServerShutdown()); assertFalse(backupPolicy.isRestartBackup()); } - finally - { + finally { server.stop(); } } - private void liveOnlyTest(String file) throws Exception - { + private void liveOnlyTest(String file) throws Exception { Configuration configuration = createConfiguration(file); ActiveMQServerImpl server = new ActiveMQServerImpl(configuration); - try - { + try { server.start(); Activation activation = server.getActivation(); assertTrue(activation instanceof LiveOnlyActivation); @@ -415,15 +374,12 @@ public class HAPolicyConfigurationTest extends ActiveMQTestBase ScaleDownPolicy scaleDownPolicy = liveOnlyPolicy.getScaleDownPolicy(); assertNull(scaleDownPolicy); } - finally - { + finally { server.stop(); } } - - protected Configuration createConfiguration(String fileName) throws Exception - { + protected Configuration createConfiguration(String fileName) throws Exception { FileConfiguration fc = new FileConfiguration(); FileDeploymentManager deploymentManager = new FileDeploymentManager(fileName); deploymentManager.addDeployable(fc); diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/ValidatorsTest.java b/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/ValidatorsTest.java index 2332c48a6a..048f1c4b3b 100644 --- a/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/ValidatorsTest.java +++ b/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/ValidatorsTest.java @@ -20,27 +20,21 @@ import org.junit.Test; import org.junit.Assert; - import org.apache.activemq.artemis.core.server.JournalType; import org.apache.activemq.artemis.tests.util.RandomUtil; -public class ValidatorsTest extends Assert -{ +public class ValidatorsTest extends Assert { - private static void success(final Validators.Validator validator, final Object value) - { + private static void success(final Validators.Validator validator, final Object value) { validator.validate(RandomUtil.randomString(), value); } - private static void failure(final Validators.Validator validator, final Object value) - { - try - { + private static void failure(final Validators.Validator validator, final Object value) { + try { validator.validate(RandomUtil.randomString(), value); Assert.fail(validator + " must not validate " + value); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { } } @@ -50,8 +44,7 @@ public class ValidatorsTest extends Assert // Public -------------------------------------------------------- @Test - public void testGE_ZERO() throws Exception - { + public void testGE_ZERO() throws Exception { ValidatorsTest.failure(Validators.GE_ZERO, -1); ValidatorsTest.success(Validators.GE_ZERO, 0); ValidatorsTest.success(Validators.GE_ZERO, 0.1); @@ -59,8 +52,7 @@ public class ValidatorsTest extends Assert } @Test - public void testGT_ZERO() throws Exception - { + public void testGT_ZERO() throws Exception { ValidatorsTest.failure(Validators.GT_ZERO, -1); ValidatorsTest.failure(Validators.GT_ZERO, 0); ValidatorsTest.success(Validators.GT_ZERO, 0.1); @@ -68,8 +60,7 @@ public class ValidatorsTest extends Assert } @Test - public void testMINUS_ONE_OR_GE_ZERO() throws Exception - { + public void testMINUS_ONE_OR_GE_ZERO() throws Exception { ValidatorsTest.failure(Validators.MINUS_ONE_OR_GE_ZERO, -2); ValidatorsTest.success(Validators.MINUS_ONE_OR_GE_ZERO, -1); ValidatorsTest.success(Validators.MINUS_ONE_OR_GE_ZERO, 0); @@ -78,8 +69,7 @@ public class ValidatorsTest extends Assert } @Test - public void testMINUS_ONE_OR_GT_ZERO() throws Exception - { + public void testMINUS_ONE_OR_GT_ZERO() throws Exception { ValidatorsTest.failure(Validators.MINUS_ONE_OR_GT_ZERO, -2); ValidatorsTest.success(Validators.MINUS_ONE_OR_GT_ZERO, -1); ValidatorsTest.failure(Validators.MINUS_ONE_OR_GT_ZERO, 0); @@ -88,8 +78,7 @@ public class ValidatorsTest extends Assert } @Test - public void testNO_CHECK() throws Exception - { + public void testNO_CHECK() throws Exception { ValidatorsTest.success(Validators.NO_CHECK, -1); ValidatorsTest.success(Validators.NO_CHECK, null); ValidatorsTest.success(Validators.NO_CHECK, ""); @@ -98,18 +87,15 @@ public class ValidatorsTest extends Assert } @Test - public void testNOT_NULL_OR_EMPTY() throws Exception - { + public void testNOT_NULL_OR_EMPTY() throws Exception { ValidatorsTest.failure(Validators.NOT_NULL_OR_EMPTY, null); ValidatorsTest.failure(Validators.NOT_NULL_OR_EMPTY, ""); ValidatorsTest.success(Validators.NOT_NULL_OR_EMPTY, RandomUtil.randomString()); } @Test - public void testJOURNAL_TYPE() throws Exception - { - for (JournalType type : JournalType.values()) - { + public void testJOURNAL_TYPE() throws Exception { + for (JournalType type : JournalType.values()) { ValidatorsTest.success(Validators.JOURNAL_TYPE, type.toString()); } ValidatorsTest.failure(Validators.JOURNAL_TYPE, null); @@ -118,8 +104,7 @@ public class ValidatorsTest extends Assert } @Test - public void testPERCENTAGE() - { + public void testPERCENTAGE() { ValidatorsTest.success(Validators.PERCENTAGE, 99); ValidatorsTest.success(Validators.PERCENTAGE, 100); ValidatorsTest.success(Validators.PERCENTAGE, 0); diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/WrongRoleFileConfigurationParserTest.java b/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/WrongRoleFileConfigurationParserTest.java index 46b0d145e4..9e8ffbcbb5 100644 --- a/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/WrongRoleFileConfigurationParserTest.java +++ b/artemis-server/src/test/java/org/apache/activemq/artemis/core/config/impl/WrongRoleFileConfigurationParserTest.java @@ -30,11 +30,10 @@ import java.nio.charset.StandardCharsets; * When running this test from an IDE add this to the test command line so that the AssertionLoggerHandler works properly: * -Djava.util.logging.manager=org.jboss.logmanager.LogManager -Dlogging.configuration=file:/tests/config/logging.properties */ -public class WrongRoleFileConfigurationParserTest extends ActiveMQTestBase -{ +public class WrongRoleFileConfigurationParserTest extends ActiveMQTestBase { + @BeforeClass - public static void prepareLogger() - { + public static void prepareLogger() { AssertionLoggerHandler.startCapture(); } @@ -44,8 +43,7 @@ public class WrongRoleFileConfigurationParserTest extends ActiveMQTestBase * */ @Test - public void testParsingDefaultServerConfig() throws Exception - { + public void testParsingDefaultServerConfig() throws Exception { FileConfigurationParser parser = new FileConfigurationParser(); ByteArrayInputStream input = new ByteArrayInputStream(configuration.getBytes(StandardCharsets.UTF_8)); parser.parseMainConfig(input); @@ -56,51 +54,43 @@ public class WrongRoleFileConfigurationParserTest extends ActiveMQTestBase } @AfterClass - public static void clearLogger() - { + public static void clearLogger() { AssertionLoggerHandler.stopCapture(); } - private static final String configuration = - "\n" + - "ActiveMQ.main.config" + "\n" + - "org.apache.activemq.artemis.integration.logging.Log4jLogDelegateFactory" + "\n" + - "${jboss.server.data.dir}/activemq/bindings" + "\n" + - "${jboss.server.data.dir}/activemq/journal" + "\n" + - "10" + "\n" + - "${jboss.server.data.dir}/activemq/largemessages" + "\n" + - "${jboss.server.data.dir}/activemq/paging" + "\n" + - "" + "\n" + - "tcp://localhost:61616" + "\n" + - "tcp://localhost:5545" + "\n" + - "vm://0" + "\n" + - "" + "\n" + - "" + "\n" + - "tcp://localhost:5545" + "\n" + - "tcp://localhost:5545" + "\n" + - "vm://0" + "\n" + - "" + "\n" + - "" + "\n" + - "" + "\n" + - "" + "\n" + - "" + "\n" + - "" + "\n" + - "" + "\n" + - "" + "\n" + - "" + "\n" + - "" + "\n" + - "" + "\n" + - "" + "\n" + - "" - + "\n" + "jms.queue.DLQ\n" + "\n" - + "jms.queue.ExpiryQueue\n" + "\n" - + "0\n" + "\n" - + "10485760\n" + "\n" - + "10" + "\n" - + "BLOCK" + "\n" + - "" + "\n" + - "" + "\n" + - ""; + private static final String configuration = "\n" + + "ActiveMQ.main.config" + "\n" + + "org.apache.activemq.artemis.integration.logging.Log4jLogDelegateFactory" + "\n" + + "${jboss.server.data.dir}/activemq/bindings" + "\n" + + "${jboss.server.data.dir}/activemq/journal" + "\n" + + "10" + "\n" + + "${jboss.server.data.dir}/activemq/largemessages" + "\n" + + "${jboss.server.data.dir}/activemq/paging" + "\n" + + "" + "\n" + + "tcp://localhost:61616" + "\n" + + "tcp://localhost:5545" + "\n" + + "vm://0" + "\n" + + "" + "\n" + + "" + "\n" + + "tcp://localhost:5545" + "\n" + + "tcp://localhost:5545" + "\n" + + "vm://0" + "\n" + + "" + "\n" + + "" + "\n" + + "" + "\n" + + "" + "\n" + + "" + "\n" + + "" + "\n" + + "" + "\n" + + "" + "\n" + + "" + "\n" + + "" + "\n" + + "" + "\n" + + "" + "\n" + + "" + "\n" + "jms.queue.DLQ\n" + "\n" + "jms.queue.ExpiryQueue\n" + "\n" + "0\n" + "\n" + "10485760\n" + "\n" + "10" + "\n" + "BLOCK" + "\n" + + "" + "\n" + + "" + "\n" + + ""; } diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/core/filter/impl/FilterTest.java b/artemis-server/src/test/java/org/apache/activemq/artemis/core/filter/impl/FilterTest.java index 7c1aed3a90..0ef4f0232b 100644 --- a/artemis-server/src/test/java/org/apache/activemq/artemis/core/filter/impl/FilterTest.java +++ b/artemis-server/src/test/java/org/apache/activemq/artemis/core/filter/impl/FilterTest.java @@ -31,23 +31,21 @@ import org.junit.Test; /** * Tests the compliance with the ActiveMQ Artemis Filter syntax. */ -public class FilterTest extends SilentTestCase -{ +public class FilterTest extends SilentTestCase { + private Filter filter; private ServerMessage message; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); message = new ServerMessageImpl(1, 1000); } @Test - public void testNewlineMatch() throws Exception - { + public void testNewlineMatch() throws Exception { filter = FilterImpl.createFilter(new SimpleString("fooprop LIKE '%1234%'")); message.putStringProperty(new SimpleString("fooprop"), new SimpleString("hello1234\n")); @@ -56,8 +54,7 @@ public class FilterTest extends SilentTestCase } @Test - public void testFilterForgets() throws Exception - { + public void testFilterForgets() throws Exception { filter = FilterImpl.createFilter(new SimpleString("color = 'RED'")); message.putStringProperty(new SimpleString("color"), new SimpleString("RED")); @@ -67,8 +64,7 @@ public class FilterTest extends SilentTestCase } @Test - public void testInvalidString() throws Exception - { + public void testInvalidString() throws Exception { testInvalidFilter("color = 'red"); testInvalidFilter(new SimpleString("color = 'red")); @@ -77,8 +73,7 @@ public class FilterTest extends SilentTestCase } @Test - public void testNullFilter() throws Exception - { + public void testNullFilter() throws Exception { Assert.assertNull(FilterImpl.createFilter((String) null)); Assert.assertNull(FilterImpl.createFilter("")); Assert.assertNull(FilterImpl.createFilter((SimpleString) null)); @@ -86,8 +81,7 @@ public class FilterTest extends SilentTestCase } @Test - public void testAMQDurable() throws Exception - { + public void testAMQDurable() throws Exception { filter = FilterImpl.createFilter(new SimpleString("AMQDurable='DURABLE'")); message.setDurable(true); @@ -112,8 +106,7 @@ public class FilterTest extends SilentTestCase } @Test - public void testAMQSize() throws Exception - { + public void testAMQSize() throws Exception { message.setAddress(RandomUtil.randomSimpleString()); int encodeSize = message.getEncodeSize(); @@ -133,28 +126,23 @@ public class FilterTest extends SilentTestCase } @Test - public void testAMQPriority() throws Exception - { + public void testAMQPriority() throws Exception { filter = FilterImpl.createFilter(new SimpleString("AMQPriority=3")); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { message.setPriority((byte) i); - if (i == 3) - { + if (i == 3) { Assert.assertTrue(filter.match(message)); } - else - { + else { Assert.assertFalse(filter.match(message)); } } } @Test - public void testAMQTimestamp() throws Exception - { + public void testAMQTimestamp() throws Exception { filter = FilterImpl.createFilter(new SimpleString("AMQTimestamp=12345678")); message.setTimestamp(87654321); @@ -167,24 +155,21 @@ public class FilterTest extends SilentTestCase } @Test - public void testBooleanTrue() throws Exception - { + public void testBooleanTrue() throws Exception { filter = FilterImpl.createFilter(new SimpleString("MyBoolean=true")); testBoolean("MyBoolean", true); } @Test - public void testIdentifier() throws Exception - { + public void testIdentifier() throws Exception { filter = FilterImpl.createFilter(new SimpleString("MyBoolean")); testBoolean("MyBoolean", true); } @Test - public void testDifferentNullString() throws Exception - { + public void testDifferentNullString() throws Exception { filter = FilterImpl.createFilter(new SimpleString("prop <> 'foo'")); Assert.assertTrue(filter.match(message)); @@ -201,14 +186,12 @@ public class FilterTest extends SilentTestCase } @Test - public void testBooleanFalse() throws Exception - { + public void testBooleanFalse() throws Exception { filter = FilterImpl.createFilter(new SimpleString("MyBoolean=false")); testBoolean("MyBoolean", false); } - private void testBoolean(final String name, final boolean flag) throws Exception - { + private void testBoolean(final String name, final boolean flag) throws Exception { message.putBooleanProperty(new SimpleString(name), flag); Assert.assertTrue(filter.match(message)); @@ -217,8 +200,7 @@ public class FilterTest extends SilentTestCase } @Test - public void testStringEquals() throws Exception - { + public void testStringEquals() throws Exception { // First, simple test of string equality and inequality filter = FilterImpl.createFilter(new SimpleString("MyString='astring'")); @@ -252,8 +234,7 @@ public class FilterTest extends SilentTestCase } @Test - public void testNOT_INWithNullProperty() throws Exception - { + public void testNOT_INWithNullProperty() throws Exception { filter = FilterImpl.createFilter(new SimpleString("myNullProp NOT IN ('foo','jms','test')")); assertFalse(filter.match(message)); @@ -263,8 +244,7 @@ public class FilterTest extends SilentTestCase } @Test - public void testNOT_LIKEWithNullProperty() throws Exception - { + public void testNOT_LIKEWithNullProperty() throws Exception { filter = FilterImpl.createFilter(new SimpleString("myNullProp NOT LIKE '1_3'")); assertFalse(filter.match(message)); @@ -274,8 +254,7 @@ public class FilterTest extends SilentTestCase } @Test - public void testIS_NOT_NULLWithNullProperty() throws Exception - { + public void testIS_NOT_NULLWithNullProperty() throws Exception { filter = FilterImpl.createFilter(new SimpleString("myNullProp IS NOT NULL")); assertFalse(filter.match(message)); @@ -285,8 +264,7 @@ public class FilterTest extends SilentTestCase } @Test - public void testStringLike() throws Exception - { + public void testStringLike() throws Exception { // test LIKE operator with no wildcards filter = FilterImpl.createFilter(new SimpleString("MyString LIKE 'astring'")); Assert.assertFalse(filter.match(message)); @@ -336,8 +314,7 @@ public class FilterTest extends SilentTestCase } @Test - public void testStringLikeUnderbarWildcard() throws Exception - { + public void testStringLikeUnderbarWildcard() throws Exception { // test LIKE operator with the _ wildcard, which // matches any single character @@ -468,8 +445,7 @@ public class FilterTest extends SilentTestCase } @Test - public void testNotLikeExpression() throws Exception - { + public void testNotLikeExpression() throws Exception { // Should evaluate to false when the property MyString is not set filter = FilterImpl.createFilter(new SimpleString("NOT (MyString LIKE '%')")); @@ -477,8 +453,7 @@ public class FilterTest extends SilentTestCase } @Test - public void testStringLikePercentWildcard() throws Exception - { + public void testStringLikePercentWildcard() throws Exception { // test LIKE operator with the % wildcard, which // matches any sequence of characters // note many of the tests are similar to those for _ @@ -610,8 +585,7 @@ public class FilterTest extends SilentTestCase } @Test - public void testStringLikePunctuation() throws Exception - { + public void testStringLikePunctuation() throws Exception { // test proper handling of some punctuation characters. // non-trivial since the underlying implementation might // (and in fact currently does) use a general-purpose @@ -695,69 +669,60 @@ public class FilterTest extends SilentTestCase Assert.assertTrue(filter.match(message)); } -// TODO: re-implement this. -// -// @Test -// public void testStringLongToken() throws Exception -// { -// String largeString; -// -// { -// StringBuffer strBuffer = new StringBuffer(); -// strBuffer.append('\''); -// for (int i = 0; i < 4800; i++) -// { -// strBuffer.append('a'); -// } -// strBuffer.append('\''); -// -// largeString = strBuffer.toString(); -// } -// -// FilterParser parse = new FilterParser(); -// SimpleStringReader reader = new SimpleStringReader(new SimpleString(largeString)); -// parse.ReInit(reader); -// // the server would fail at doing this when HORNETQ-545 wasn't solved -// parse.getNextToken(); -// } + // TODO: re-implement this. + // + // @Test + // public void testStringLongToken() throws Exception + // { + // String largeString; + // + // { + // StringBuffer strBuffer = new StringBuffer(); + // strBuffer.append('\''); + // for (int i = 0; i < 4800; i++) + // { + // strBuffer.append('a'); + // } + // strBuffer.append('\''); + // + // largeString = strBuffer.toString(); + // } + // + // FilterParser parse = new FilterParser(); + // SimpleStringReader reader = new SimpleStringReader(new SimpleString(largeString)); + // parse.ReInit(reader); + // // the server would fail at doing this when HORNETQ-545 wasn't solved + // parse.getNextToken(); + // } // Private ----------------------------------------------------------------------------------- - private void doPutStringProperty(final String key, final String value) - { + private void doPutStringProperty(final String key, final String value) { message.putStringProperty(new SimpleString(key), new SimpleString(value)); } - private void testInvalidFilter(final String filterString) throws Exception - { - try - { + private void testInvalidFilter(final String filterString) throws Exception { + try { filter = FilterImpl.createFilter(filterString); Assert.fail("Should throw exception"); } - catch (ActiveMQInvalidFilterExpressionException ife) - { + catch (ActiveMQInvalidFilterExpressionException ife) { //pass } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid exception type:" + e.getType()); } } - private void testInvalidFilter(final SimpleString filterString) throws Exception - { - try - { + private void testInvalidFilter(final SimpleString filterString) throws Exception { + try { filter = FilterImpl.createFilter(filterString); Assert.fail("Should throw exception"); } - catch (ActiveMQInvalidFilterExpressionException ife) - { + catch (ActiveMQInvalidFilterExpressionException ife) { //pass } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid exception type:" + e.getType()); } } diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/core/list/PriorityLinkedListTest.java b/artemis-server/src/test/java/org/apache/activemq/artemis/core/list/PriorityLinkedListTest.java index 2c7b5b8512..7dcf7a0a37 100644 --- a/artemis-server/src/test/java/org/apache/activemq/artemis/core/list/PriorityLinkedListTest.java +++ b/artemis-server/src/test/java/org/apache/activemq/artemis/core/list/PriorityLinkedListTest.java @@ -22,8 +22,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public final class PriorityLinkedListTest extends Assert -{ +public final class PriorityLinkedListTest extends Assert { + protected Wibble a; protected Wibble b; @@ -78,15 +78,12 @@ public final class PriorityLinkedListTest extends Assert private PriorityLinkedListImpl list; - protected PriorityLinkedListImpl getList() - { + protected PriorityLinkedListImpl getList() { return new PriorityLinkedListImpl(10); } @Before - public void setUp() throws Exception - { - + public void setUp() throws Exception { list = getList(); @@ -119,8 +116,7 @@ public final class PriorityLinkedListTest extends Assert } @Test - public void testEmpty() throws Exception - { + public void testEmpty() throws Exception { Assert.assertTrue(list.isEmpty()); list.addHead(a, 0); @@ -135,8 +131,7 @@ public final class PriorityLinkedListTest extends Assert } @Test - public void testaddHead() throws Exception - { + public void testaddHead() throws Exception { list.addHead(a, 0); list.addHead(b, 0); list.addHead(c, 0); @@ -156,8 +151,7 @@ public final class PriorityLinkedListTest extends Assert } @Test - public void testaddTail() throws Exception - { + public void testaddTail() throws Exception { list.addTail(a, 0); list.addTail(b, 0); list.addTail(c, 0); @@ -177,8 +171,7 @@ public final class PriorityLinkedListTest extends Assert } @Test - public void testAddLastAndFirst() throws Exception - { + public void testAddLastAndFirst() throws Exception { list.addTail(a, 0); list.addTail(b, 0); list.addTail(c, 0); @@ -225,8 +218,7 @@ public final class PriorityLinkedListTest extends Assert } @Test - public void testAddLastAndFirstWithIterator() throws Exception - { + public void testAddLastAndFirstWithIterator() throws Exception { list.addTail(a, 0); list.addTail(b, 0); list.addTail(c, 0); @@ -295,8 +287,7 @@ public final class PriorityLinkedListTest extends Assert } @Test - public void testPoll() throws Exception - { + public void testPoll() throws Exception { list.addTail(a, 0); list.addTail(b, 1); list.addTail(c, 2); @@ -446,8 +437,7 @@ public final class PriorityLinkedListTest extends Assert } @Test - public void testIterator() - { + public void testIterator() { list.addTail(a, 9); list.addTail(b, 9); list.addTail(c, 8); @@ -479,8 +469,7 @@ public final class PriorityLinkedListTest extends Assert int count = 0; Wibble w1; - while (iter.hasNext()) - { + while (iter.hasNext()) { w1 = iter.next(); count++; } @@ -775,8 +764,7 @@ public final class PriorityLinkedListTest extends Assert } @Test - public void testIteratorPicksUpHigherPriorities() - { + public void testIteratorPicksUpHigherPriorities() { list.addTail(a, 4); list.addTail(b, 4); list.addTail(c, 4); @@ -812,8 +800,7 @@ public final class PriorityLinkedListTest extends Assert } @Test - public void testClear() - { + public void testClear() { list.addTail(a, 0); list.addTail(b, 3); list.addTail(c, 3); @@ -831,8 +818,7 @@ public final class PriorityLinkedListTest extends Assert } @Test - public void testMixupIterator() - { + public void testMixupIterator() { list.addTail(c, 5); list.addTail(a, 4); list.addTail(b, 4); @@ -851,8 +837,7 @@ public final class PriorityLinkedListTest extends Assert } @Test - public void testMixupIterator2() - { + public void testMixupIterator2() { list.addTail(c, 5); list.addTail(k, 0); @@ -885,18 +870,16 @@ public final class PriorityLinkedListTest extends Assert iter.remove(); } - static class Wibble - { + static class Wibble { + String s1; - Wibble(final String s) - { + Wibble(final String s) { this.s1 = s; } @Override - public String toString() - { + public String toString() { return s1; } } diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/core/message/impl/MessagePropertyTest.java b/artemis-server/src/test/java/org/apache/activemq/artemis/core/message/impl/MessagePropertyTest.java index bd8d6d57d6..b80fef89af 100644 --- a/artemis-server/src/test/java/org/apache/activemq/artemis/core/message/impl/MessagePropertyTest.java +++ b/artemis-server/src/test/java/org/apache/activemq/artemis/core/message/impl/MessagePropertyTest.java @@ -28,8 +28,8 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Before; import org.junit.Test; -public class MessagePropertyTest extends ActiveMQTestBase -{ +public class MessagePropertyTest extends ActiveMQTestBase { + private ActiveMQServer server; private ServerLocator locator; private ClientSessionFactory sf; @@ -40,8 +40,7 @@ public class MessagePropertyTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(true); server.start(); @@ -49,14 +48,12 @@ public class MessagePropertyTest extends ActiveMQTestBase sf = createSessionFactory(locator); } - private void sendMessages() throws Exception - { + private void sendMessages() throws Exception { ClientSession session = sf.createSession(true, true); session.createQueue(ADDRESS, ADDRESS, null, true); ClientProducer producer = session.createProducer(ADDRESS); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(true); setBody(i, message); message.putIntProperty("int", i); @@ -71,31 +68,25 @@ public class MessagePropertyTest extends ActiveMQTestBase session.commit(); } - private float floatValue(int i) - { + private float floatValue(int i) { return (float) (i * 1.3); } - private byte[] byteArray(int i) - { + private byte[] byteArray(int i) { return new byte[]{(byte) i, (byte) (i / 2)}; } @Test - public void testProperties() throws Exception - { + public void testProperties() throws Exception { sendMessages(); receiveMessages(); } - - private void receiveMessages() throws Exception - { + private void receiveMessages() throws Exception { ClientSession session = sf.createSession(true, true); session.start(); ClientConsumer consumer = session.createConsumer(ADDRESS); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(100); assertNotNull("Expecting a message " + i, message); assertMessageBody(i, message); @@ -103,8 +94,7 @@ public class MessagePropertyTest extends ActiveMQTestBase assertEquals((short) i, message.getShortProperty("short").shortValue()); assertEquals((byte) i, message.getByteProperty("byte").byteValue()); assertEquals(floatValue(i), message.getFloatProperty("float").floatValue(), 0.001); - assertEquals(new SimpleString(Integer.toString(i)), - message.getSimpleStringProperty(SIMPLE_STRING_KEY.toString())); + assertEquals(new SimpleString(Integer.toString(i)), message.getSimpleStringProperty(SIMPLE_STRING_KEY.toString())); assertEqualsByteArrays(byteArray(i), message.getBytesProperty("byte[]")); assertTrue(message.containsProperty("null-value")); diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/core/security/RoleTest.java b/artemis-server/src/test/java/org/apache/activemq/artemis/core/security/RoleTest.java index b3721b77ca..f069e68ba3 100644 --- a/artemis-server/src/test/java/org/apache/activemq/artemis/core/security/RoleTest.java +++ b/artemis-server/src/test/java/org/apache/activemq/artemis/core/security/RoleTest.java @@ -26,8 +26,7 @@ import static org.apache.activemq.artemis.core.security.CheckType.DELETE_DURABLE import static org.apache.activemq.artemis.core.security.CheckType.DELETE_NON_DURABLE_QUEUE; import static org.apache.activemq.artemis.core.security.CheckType.SEND; -public class RoleTest extends Assert -{ +public class RoleTest extends Assert { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -39,8 +38,7 @@ public class RoleTest extends Assert // Public -------------------------------------------------------- @Test - public void testReadRole() throws Exception - { + public void testReadRole() throws Exception { Role role = new Role("testReadRole", true, false, false, false, false, false, false); Assert.assertTrue(SEND.hasRole(role)); Assert.assertFalse(CONSUME.hasRole(role)); @@ -51,8 +49,7 @@ public class RoleTest extends Assert } @Test - public void testWriteRole() throws Exception - { + public void testWriteRole() throws Exception { Role role = new Role("testWriteRole", false, true, false, false, false, false, false); Assert.assertFalse(SEND.hasRole(role)); Assert.assertTrue(CONSUME.hasRole(role)); @@ -63,8 +60,7 @@ public class RoleTest extends Assert } @Test - public void testCreateRole() throws Exception - { + public void testCreateRole() throws Exception { Role role = new Role("testWriteRole", false, false, true, false, false, false, false); Assert.assertFalse(SEND.hasRole(role)); Assert.assertFalse(CONSUME.hasRole(role)); @@ -75,8 +71,7 @@ public class RoleTest extends Assert } @Test - public void testEqualsAndHashcode() throws Exception - { + public void testEqualsAndHashcode() throws Exception { Role role = new Role("testEquals", true, true, true, false, false, false, false); Role sameRole = new Role("testEquals", true, true, true, false, false, false, false); Role roleWithDifferentName = new Role("notEquals", true, true, true, false, false, false, false); diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/core/server/group/impl/ClusteredResetMockTest.java b/artemis-server/src/test/java/org/apache/activemq/artemis/core/server/group/impl/ClusteredResetMockTest.java index 9c0d514fdf..b01b271099 100644 --- a/artemis-server/src/test/java/org/apache/activemq/artemis/core/server/group/impl/ClusteredResetMockTest.java +++ b/artemis-server/src/test/java/org/apache/activemq/artemis/core/server/group/impl/ClusteredResetMockTest.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.core.server.group.impl; - import org.apache.activemq.artemis.api.core.BroadcastGroupConfiguration; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.TransportConfiguration; @@ -65,14 +64,12 @@ import java.util.concurrent.TimeUnit; * There is a small window where you could receive notifications wrongly * this test will make sure the component would play well with that notification */ -public class ClusteredResetMockTest extends ActiveMQTestBase -{ +public class ClusteredResetMockTest extends ActiveMQTestBase { public static final SimpleString ANYCLUSTER = SimpleString.toSimpleString("anycluster"); @Test - public void testMultipleSenders() throws Throwable - { + public void testMultipleSenders() throws Throwable { int NUMBER_OF_SENDERS = 100; ReusableLatch latchSends = new ReusableLatch(NUMBER_OF_SENDERS); @@ -81,26 +78,20 @@ public class ClusteredResetMockTest extends ActiveMQTestBase RemoteGroupingHandler handler = new RemoteGroupingHandler(fake, SimpleString.toSimpleString("tst1"), SimpleString.toSimpleString("tst2"), 50000, 499); handler.start(); - Sender[] sn = new Sender[NUMBER_OF_SENDERS]; - for (int i = 0; i < sn.length; i++) - { + for (int i = 0; i < sn.length; i++) { sn[i] = new Sender("grp" + i, handler); sn[i].start(); } - - try - { + try { // Waiting two requests to arrive Assert.assertTrue(latchSends.await(1, TimeUnit.MINUTES)); - // we will ask a resend.. need to add 2 back - for (int i = 0; i < NUMBER_OF_SENDERS; i++) - { + for (int i = 0; i < NUMBER_OF_SENDERS; i++) { // There is no countUp(NUMBER_OF_SENDERS); adding two back on the reusable latch latchSends.countUp(); } @@ -113,82 +104,64 @@ public class ClusteredResetMockTest extends ActiveMQTestBase HashSet codesAsked = new HashSet(); - for (Notification notification : fake.pendingNotifications) - { + for (Notification notification : fake.pendingNotifications) { codesAsked.add(notification.getProperties().getSimpleStringProperty(ManagementHelper.HDR_PROPOSAL_GROUP_ID)); } - for (Sender snItem : sn) - { + for (Sender snItem : sn) { assertTrue(codesAsked.contains(snItem.code)); } - - for (int i = NUMBER_OF_SENDERS - 1; i >= 0; i--) - { + for (int i = NUMBER_OF_SENDERS - 1; i >= 0; i--) { // Sending back the response as Notifications would be doing Response response = new Response(sn[i].code, ANYCLUSTER); handler.proposed(response); } - - for (Sender sni : sn) - { + for (Sender sni : sn) { sni.join(); - if (sni.ex != null) - { + if (sni.ex != null) { throw sni.ex; } } } - finally - { + finally { - for (Sender sni : sn) - { + for (Sender sni : sn) { sni.interrupt(); } } - } + class Sender extends Thread { - class Sender extends Thread - { SimpleString code; public RemoteGroupingHandler handler; Throwable ex; - Sender(String code, RemoteGroupingHandler handler) - { + Sender(String code, RemoteGroupingHandler handler) { super("Sender::" + code); this.code = SimpleString.toSimpleString(code); this.handler = handler; } - - public void run() - { + public void run() { Proposal proposal = new Proposal(code, ANYCLUSTER); - try - { + try { Response response = handler.propose(proposal); - if (response == null) - { + if (response == null) { ex = new NullPointerException("expected value on " + getName()); } - if (!response.getGroupId().equals(code)) - { + if (!response.getGroupId().equals(code)) { ex = new IllegalStateException("expected code=" + code + " but it was " + response.getGroupId()); } } - catch (Throwable ex) - { + catch (Throwable ex) { ex.printStackTrace(); this.ex = ex; } @@ -196,229 +169,204 @@ public class ClusteredResetMockTest extends ActiveMQTestBase } } + class FakeManagement implements ManagementService { - class FakeManagement implements ManagementService - { public ConcurrentHashSet pendingNotifications = new ConcurrentHashSet(); final ReusableLatch latch; - FakeManagement(ReusableLatch latch) - { + FakeManagement(ReusableLatch latch) { this.latch = latch; } @Override - public MessageCounterManager getMessageCounterManager() - { + public MessageCounterManager getMessageCounterManager() { return null; } @Override - public SimpleString getManagementAddress() - { + public SimpleString getManagementAddress() { return null; } @Override - public SimpleString getManagementNotificationAddress() - { + public SimpleString getManagementNotificationAddress() { return null; } @Override - public ObjectNameBuilder getObjectNameBuilder() - { + public ObjectNameBuilder getObjectNameBuilder() { return null; } @Override - public void setStorageManager(StorageManager storageManager) - { + public void setStorageManager(StorageManager storageManager) { } @Override - public ActiveMQServerControlImpl registerServer(PostOffice postOffice, StorageManager storageManager, Configuration configuration, HierarchicalRepository addressSettingsRepository, HierarchicalRepository> securityRepository, ResourceManager resourceManager, RemotingService remotingService, ActiveMQServer messagingServer, QueueFactory queueFactory, ScheduledExecutorService scheduledThreadPool, PagingManager pagingManager, boolean backup) throws Exception - { + public ActiveMQServerControlImpl registerServer(PostOffice postOffice, + StorageManager storageManager, + Configuration configuration, + HierarchicalRepository addressSettingsRepository, + HierarchicalRepository> securityRepository, + ResourceManager resourceManager, + RemotingService remotingService, + ActiveMQServer messagingServer, + QueueFactory queueFactory, + ScheduledExecutorService scheduledThreadPool, + PagingManager pagingManager, + boolean backup) throws Exception { return null; } @Override - public void unregisterServer() throws Exception - { + public void unregisterServer() throws Exception { } @Override - public void registerInJMX(ObjectName objectName, Object managedResource) throws Exception - { + public void registerInJMX(ObjectName objectName, Object managedResource) throws Exception { } @Override - public void unregisterFromJMX(ObjectName objectName) throws Exception - { + public void unregisterFromJMX(ObjectName objectName) throws Exception { } @Override - public void registerInRegistry(String resourceName, Object managedResource) - { + public void registerInRegistry(String resourceName, Object managedResource) { } @Override - public void unregisterFromRegistry(String resourceName) - { + public void unregisterFromRegistry(String resourceName) { } @Override - public void registerAddress(SimpleString address) throws Exception - { + public void registerAddress(SimpleString address) throws Exception { } @Override - public void unregisterAddress(SimpleString address) throws Exception - { + public void unregisterAddress(SimpleString address) throws Exception { } @Override - public void registerQueue(Queue queue, SimpleString address, StorageManager storageManager) throws Exception - { + public void registerQueue(Queue queue, SimpleString address, StorageManager storageManager) throws Exception { } @Override - public void unregisterQueue(SimpleString name, SimpleString address) throws Exception - { + public void unregisterQueue(SimpleString name, SimpleString address) throws Exception { } @Override - public void registerAcceptor(Acceptor acceptor, TransportConfiguration configuration) throws Exception - { + public void registerAcceptor(Acceptor acceptor, TransportConfiguration configuration) throws Exception { } @Override - public void unregisterAcceptors() - { + public void unregisterAcceptors() { } @Override - public void registerDivert(Divert divert, DivertConfiguration config) throws Exception - { + public void registerDivert(Divert divert, DivertConfiguration config) throws Exception { } @Override - public void unregisterDivert(SimpleString name) throws Exception - { + public void unregisterDivert(SimpleString name) throws Exception { } @Override - public void registerBroadcastGroup(BroadcastGroup broadcastGroup, BroadcastGroupConfiguration configuration) throws Exception - { + public void registerBroadcastGroup(BroadcastGroup broadcastGroup, + BroadcastGroupConfiguration configuration) throws Exception { } @Override - public void unregisterBroadcastGroup(String name) throws Exception - { + public void unregisterBroadcastGroup(String name) throws Exception { } @Override - public void registerBridge(Bridge bridge, BridgeConfiguration configuration) throws Exception - { + public void registerBridge(Bridge bridge, BridgeConfiguration configuration) throws Exception { } @Override - public void unregisterBridge(String name) throws Exception - { + public void unregisterBridge(String name) throws Exception { } @Override - public void registerCluster(ClusterConnection cluster, ClusterConnectionConfiguration configuration) throws Exception - { + public void registerCluster(ClusterConnection cluster, + ClusterConnectionConfiguration configuration) throws Exception { } @Override - public void unregisterCluster(String name) throws Exception - { + public void unregisterCluster(String name) throws Exception { } @Override - public Object getResource(String resourceName) - { + public Object getResource(String resourceName) { return null; } @Override - public Object[] getResources(Class resourceType) - { + public Object[] getResources(Class resourceType) { return new Object[0]; } @Override - public ServerMessage handleMessage(ServerMessage message) throws Exception - { + public ServerMessage handleMessage(ServerMessage message) throws Exception { return null; } @Override - public void start() throws Exception - { + public void start() throws Exception { } @Override - public void stop() throws Exception - { + public void stop() throws Exception { } @Override - public boolean isStarted() - { + public boolean isStarted() { return false; } @Override - public void sendNotification(Notification notification) throws Exception - { + public void sendNotification(Notification notification) throws Exception { pendingNotifications.add(notification); latch.countDown(); } @Override - public void enableNotifications(boolean enable) - { + public void enableNotifications(boolean enable) { } @Override - public void addNotificationListener(NotificationListener listener) - { + public void addNotificationListener(NotificationListener listener) { } @Override - public void removeNotificationListener(NotificationListener listener) - { + public void removeNotificationListener(NotificationListener listener) { } } - } diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/core/server/impl/EmbeddedServerTest.java b/artemis-server/src/test/java/org/apache/activemq/artemis/core/server/impl/EmbeddedServerTest.java index 399a86fd44..0f2e0f065a 100644 --- a/artemis-server/src/test/java/org/apache/activemq/artemis/core/server/impl/EmbeddedServerTest.java +++ b/artemis-server/src/test/java/org/apache/activemq/artemis/core/server/impl/EmbeddedServerTest.java @@ -31,8 +31,8 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -public class EmbeddedServerTest -{ +public class EmbeddedServerTest { + private static final String SERVER_LOCK_NAME = "server.lock"; private static final String SERVER_JOURNAL_DIR = "target/data/journal"; @@ -40,41 +40,30 @@ public class EmbeddedServerTest private Configuration configuration; @Before - public void setup() - { - configuration = new ConfigurationImpl() - .setJournalDirectory(SERVER_JOURNAL_DIR) - .setPersistenceEnabled(false) - .setSecurityEnabled(false) - .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())); + public void setup() { + configuration = new ConfigurationImpl().setJournalDirectory(SERVER_JOURNAL_DIR).setPersistenceEnabled(false).setSecurityEnabled(false).addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())); server = ActiveMQServers.newActiveMQServer(configuration); - try - { + try { server.start(); } - catch (Exception e) - { + catch (Exception e) { Assert.fail(); } } @After - public void teardown() - { - try - { + public void teardown() { + try { server.stop(); } - catch (Exception e) - { + catch (Exception e) { // Do Nothing } } @Test - public void testNoLockFileWithPersistenceFalse() - { + public void testNoLockFileWithPersistenceFalse() { Path journalDir = Paths.get(SERVER_JOURNAL_DIR, SERVER_LOCK_NAME); boolean lockExists = Files.exists(journalDir); Assert.assertFalse(lockExists); diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/core/server/impl/ScheduledDeliveryHandlerTest.java b/artemis-server/src/test/java/org/apache/activemq/artemis/core/server/impl/ScheduledDeliveryHandlerTest.java index 2bc0dc3355..d42c89df64 100644 --- a/artemis-server/src/test/java/org/apache/activemq/artemis/core/server/impl/ScheduledDeliveryHandlerTest.java +++ b/artemis-server/src/test/java/org/apache/activemq/artemis/core/server/impl/ScheduledDeliveryHandlerTest.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.core.server.impl; - import java.io.InputStream; import java.util.Collection; import java.util.HashSet; @@ -55,27 +54,23 @@ import org.apache.activemq.artemis.utils.UUID; import org.junit.Assert; import org.junit.Test; -public class ScheduledDeliveryHandlerTest extends Assert -{ +public class ScheduledDeliveryHandlerTest extends Assert { @Test - public void testScheduleRandom() throws Exception - { + public void testScheduleRandom() throws Exception { ScheduledDeliveryHandlerImpl handler = new ScheduledDeliveryHandlerImpl(null); - long nextMessage = 0; long NUMBER_OF_SEQUENCES = 100000; - for (int i = 0; i < NUMBER_OF_SEQUENCES; i++) - { + for (int i = 0; i < NUMBER_OF_SEQUENCES; i++) { int numberOfMessages = RandomUtil.randomInt() % 10; - if (numberOfMessages == 0) numberOfMessages = 1; + if (numberOfMessages == 0) + numberOfMessages = 1; long nextScheduledTime = RandomUtil.randomPositiveLong(); - for (int j = 0; j < numberOfMessages; j++) - { + for (int j = 0; j < numberOfMessages; j++) { boolean tail = RandomUtil.randomBoolean(); addMessage(handler, nextMessage++, nextScheduledTime, tail); @@ -87,21 +82,17 @@ public class ScheduledDeliveryHandlerTest extends Assert } @Test - public void testScheduleSameTimeHeadAndTail() throws Exception - { + public void testScheduleSameTimeHeadAndTail() throws Exception { ScheduledDeliveryHandlerImpl handler = new ScheduledDeliveryHandlerImpl(null); long time = System.currentTimeMillis() + 10000; - for (int i = 10001; i < 20000; i++) - { + for (int i = 10001; i < 20000; i++) { addMessage(handler, i, time, true); } addMessage(handler, 10000, time, false); - time = System.currentTimeMillis() + 5000; - for (int i = 1; i < 10000; i++) - { + for (int i = 1; i < 10000; i++) { addMessage(handler, i, time, true); } addMessage(handler, 0, time, false); @@ -113,11 +104,9 @@ public class ScheduledDeliveryHandlerTest extends Assert } @Test - public void testScheduleFixedSample() throws Exception - { + public void testScheduleFixedSample() throws Exception { ScheduledDeliveryHandlerImpl handler = new ScheduledDeliveryHandlerImpl(null); - addMessage(handler, 0, 48L, true); addMessage(handler, 1, 75L, true); addMessage(handler, 2, 56L, true); @@ -129,18 +118,15 @@ public class ScheduledDeliveryHandlerTest extends Assert } @Test - public void testScheduleWithAddHeads() throws Exception - { + public void testScheduleWithAddHeads() throws Exception { ScheduledDeliveryHandlerImpl handler = new ScheduledDeliveryHandlerImpl(null); - addMessage(handler, 0, 1, true); addMessage(handler, 1, 2, true); addMessage(handler, 2, 3, true); addMessage(handler, 3, 3, true); addMessage(handler, 4, 4, true); - addMessage(handler, 10, 5, false); addMessage(handler, 9, 5, false); addMessage(handler, 8, 5, false); @@ -152,13 +138,10 @@ public class ScheduledDeliveryHandlerTest extends Assert } - @Test - public void testScheduleFixedSampleTailAndHead() throws Exception - { + public void testScheduleFixedSampleTailAndHead() throws Exception { ScheduledDeliveryHandlerImpl handler = new ScheduledDeliveryHandlerImpl(null); - // mix a sequence of tails / heads, but at the end this was supposed to be all sequential addMessage(handler, 1, 48L, true); addMessage(handler, 2, 48L, true); @@ -167,7 +150,6 @@ public class ScheduledDeliveryHandlerTest extends Assert addMessage(handler, 5, 48L, true); addMessage(handler, 0, 48L, false); - addMessage(handler, 13, 59L, true); addMessage(handler, 14, 59L, true); addMessage(handler, 15, 59L, true); @@ -175,7 +157,6 @@ public class ScheduledDeliveryHandlerTest extends Assert addMessage(handler, 17, 59L, true); addMessage(handler, 12, 59L, false); - addMessage(handler, 7, 49L, true); addMessage(handler, 8, 49L, true); addMessage(handler, 9, 49L, true); @@ -187,28 +168,23 @@ public class ScheduledDeliveryHandlerTest extends Assert } @Test - public void testScheduleNow() throws Exception - { + public void testScheduleNow() throws Exception { ExecutorService executor = Executors.newFixedThreadPool(50); ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(1); - try - { - for (int i = 0; i < 100; i++) - { + try { + for (int i = 0; i < 100; i++) { // it's better to run the test a few times instead of run millions of messages here internalSchedule(executor, scheduler); } } - finally - { + finally { scheduler.shutdownNow(); executor.shutdownNow(); } } - private void internalSchedule(ExecutorService executor, ScheduledThreadPoolExecutor scheduler) throws Exception - { + private void internalSchedule(ExecutorService executor, ScheduledThreadPoolExecutor scheduler) throws Exception { final int NUMBER_OF_MESSAGES = 200; int NUMBER_OF_THREADS = 20; final ScheduledDeliveryHandlerImpl handler = new ScheduledDeliveryHandlerImpl(scheduler); @@ -220,32 +196,26 @@ public class ScheduledDeliveryHandlerTest extends Assert final AtomicInteger error = new AtomicInteger(0); - class ProducerThread implements Runnable - { - public void run() - { - try - { - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { + class ProducerThread implements Runnable { + + public void run() { + try { + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { checkAndSchedule(handler, i, now, false, fakeQueue); } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); error.incrementAndGet(); } - finally - { + finally { latchDone.countDown(); } } } - for (int i = 0; i < NUMBER_OF_THREADS; i++) - { + for (int i = 0; i < NUMBER_OF_THREADS; i++) { executor.execute(new ProducerThread()); } @@ -253,759 +223,639 @@ public class ScheduledDeliveryHandlerTest extends Assert assertEquals(0, error.get()); - if (!fakeQueue.waitCompletion(2, TimeUnit.SECONDS)) - { + if (!fakeQueue.waitCompletion(2, TimeUnit.SECONDS)) { fail("Couldn't complete queue.add, expected " + NUMBER_OF_MESSAGES + ", still missing " + fakeQueue.expectedElements.toString()); } } - private void validateSequence(ScheduledDeliveryHandlerImpl handler) - { + private void validateSequence(ScheduledDeliveryHandlerImpl handler) { long lastSequence = -1; - for (MessageReference ref : handler.getScheduledReferences()) - { + for (MessageReference ref : handler.getScheduledReferences()) { assertEquals(lastSequence + 1, ref.getMessage().getMessageID()); lastSequence = ref.getMessage().getMessageID(); } } - private void addMessage(ScheduledDeliveryHandlerImpl handler, long nextMessageID, long nextScheduledTime, boolean tail) - { + private void addMessage(ScheduledDeliveryHandlerImpl handler, + long nextMessageID, + long nextScheduledTime, + boolean tail) { MessageReferenceImpl refImpl = new MessageReferenceImpl(new FakeMessage(nextMessageID), null); refImpl.setScheduledDeliveryTime(nextScheduledTime); handler.addInPlace(nextScheduledTime, refImpl, tail); } - private void checkAndSchedule(ScheduledDeliveryHandlerImpl handler, long nextMessageID, long nextScheduledTime, boolean tail, Queue queue) - { + private void checkAndSchedule(ScheduledDeliveryHandlerImpl handler, + long nextMessageID, + long nextScheduledTime, + boolean tail, + Queue queue) { MessageReferenceImpl refImpl = new MessageReferenceImpl(new FakeMessage(nextMessageID), queue); refImpl.setScheduledDeliveryTime(nextScheduledTime); handler.checkAndSchedule(refImpl, tail); } - - private void debugList(boolean fail, ScheduledDeliveryHandlerImpl handler, long numberOfExpectedMessages) - { + private void debugList(boolean fail, ScheduledDeliveryHandlerImpl handler, long numberOfExpectedMessages) { List refs = handler.getScheduledReferences(); HashSet messages = new HashSet(); long lastTime = -1; - for (MessageReference ref : refs) - { + for (MessageReference ref : refs) { assertFalse(messages.contains(ref.getMessage().getMessageID())); messages.add(ref.getMessage().getMessageID()); - if (fail) - { + if (fail) { assertTrue(ref.getScheduledDeliveryTime() >= lastTime); } - else - { - if (ref.getScheduledDeliveryTime() < lastTime) - { + else { + if (ref.getScheduledDeliveryTime() < lastTime) { System.out.println("^^^fail at " + ref.getScheduledDeliveryTime()); } } lastTime = ref.getScheduledDeliveryTime(); } - for (long i = 0; i < numberOfExpectedMessages; i++) - { + for (long i = 0; i < numberOfExpectedMessages; i++) { assertTrue(messages.contains(Long.valueOf(i))); } } - class FakeMessage implements ServerMessage - { + class FakeMessage implements ServerMessage { final long id; - public FakeMessage(final long id) - { + public FakeMessage(final long id) { this.id = id; } @Override - public FakeMessage setMessageID(long id) - { + public FakeMessage setMessageID(long id) { return this; } @Override - public long getMessageID() - { + public long getMessageID() { return id; } @Override - public MessageReference createReference(Queue queue) - { + public MessageReference createReference(Queue queue) { return null; } @Override - public void forceAddress(SimpleString address) - { + public void forceAddress(SimpleString address) { } @Override - public int incrementRefCount() throws Exception - { + public int incrementRefCount() throws Exception { return 0; } @Override - public int decrementRefCount() throws Exception - { + public int decrementRefCount() throws Exception { return 0; } @Override - public int incrementDurableRefCount() - { + public int incrementDurableRefCount() { return 0; } @Override - public int decrementDurableRefCount() - { + public int decrementDurableRefCount() { return 0; } @Override - public ServerMessage copy(long newID) - { + public ServerMessage copy(long newID) { return null; } @Override - public void finishCopy() throws Exception - { + public void finishCopy() throws Exception { } @Override - public ServerMessage copy() - { + public ServerMessage copy() { return null; } @Override - public int getMemoryEstimate() - { + public int getMemoryEstimate() { return 0; } @Override - public int getRefCount() - { + public int getRefCount() { return 0; } @Override - public ServerMessage makeCopyForExpiryOrDLA(long newID, MessageReference originalReference, boolean expiry, boolean copyOriginalHeaders) throws Exception - { + public ServerMessage makeCopyForExpiryOrDLA(long newID, + MessageReference originalReference, + boolean expiry, + boolean copyOriginalHeaders) throws Exception { return null; } @Override - public void setOriginalHeaders(ServerMessage other, MessageReference originalReference, boolean expiry) - { + public void setOriginalHeaders(ServerMessage other, MessageReference originalReference, boolean expiry) { } @Override - public void setPagingStore(PagingStore store) - { + public void setPagingStore(PagingStore store) { } @Override - public PagingStore getPagingStore() - { + public PagingStore getPagingStore() { return null; } @Override - public boolean hasInternalProperties() - { + public boolean hasInternalProperties() { return false; } @Override - public boolean storeIsPaging() - { + public boolean storeIsPaging() { return false; } @Override - public void encodeMessageIDToBuffer() - { + public void encodeMessageIDToBuffer() { } @Override - public byte[] getDuplicateIDBytes() - { + public byte[] getDuplicateIDBytes() { return new byte[0]; } @Override - public Object getDuplicateProperty() - { + public Object getDuplicateProperty() { return null; } @Override - public void encode(ActiveMQBuffer buffer) - { + public void encode(ActiveMQBuffer buffer) { } @Override - public void decode(ActiveMQBuffer buffer) - { + public void decode(ActiveMQBuffer buffer) { } @Override - public void decodeFromBuffer(ActiveMQBuffer buffer) - { + public void decodeFromBuffer(ActiveMQBuffer buffer) { } @Override - public int getEndOfMessagePosition() - { + public int getEndOfMessagePosition() { return 0; } @Override - public int getEndOfBodyPosition() - { + public int getEndOfBodyPosition() { return 0; } @Override - public void checkCopy() - { + public void checkCopy() { } @Override - public void bodyChanged() - { + public void bodyChanged() { } @Override - public void resetCopied() - { + public void resetCopied() { } @Override - public boolean isServerMessage() - { + public boolean isServerMessage() { return false; } @Override - public ActiveMQBuffer getEncodedBuffer() - { + public ActiveMQBuffer getEncodedBuffer() { return null; } @Override - public int getHeadersAndPropertiesEncodeSize() - { + public int getHeadersAndPropertiesEncodeSize() { return 0; } @Override - public ActiveMQBuffer getWholeBuffer() - { + public ActiveMQBuffer getWholeBuffer() { return null; } @Override - public void encodeHeadersAndProperties(ActiveMQBuffer buffer) - { + public void encodeHeadersAndProperties(ActiveMQBuffer buffer) { } @Override - public void decodeHeadersAndProperties(ActiveMQBuffer buffer) - { + public void decodeHeadersAndProperties(ActiveMQBuffer buffer) { } @Override - public BodyEncoder getBodyEncoder() throws ActiveMQException - { + public BodyEncoder getBodyEncoder() throws ActiveMQException { return null; } @Override - public InputStream getBodyInputStream() - { + public InputStream getBodyInputStream() { return null; } @Override - public void setAddressTransient(SimpleString address) - { + public void setAddressTransient(SimpleString address) { } @Override - public TypedProperties getTypedProperties() - { + public TypedProperties getTypedProperties() { return null; } @Override - public UUID getUserID() - { + public UUID getUserID() { return null; } @Override - public FakeMessage setUserID(UUID userID) - { + public FakeMessage setUserID(UUID userID) { return this; } @Override - public SimpleString getAddress() - { + public SimpleString getAddress() { return null; } @Override - public Message setAddress(SimpleString address) - { + public Message setAddress(SimpleString address) { return null; } @Override - public byte getType() - { + public byte getType() { return 0; } @Override - public boolean isDurable() - { + public boolean isDurable() { return false; } @Override - public FakeMessage setDurable(boolean durable) - { + public FakeMessage setDurable(boolean durable) { return this; } @Override - public long getExpiration() - { + public long getExpiration() { return 0; } @Override - public boolean isExpired() - { + public boolean isExpired() { return false; } @Override - public FakeMessage setExpiration(long expiration) - { + public FakeMessage setExpiration(long expiration) { return this; } @Override - public long getTimestamp() - { + public long getTimestamp() { return 0; } @Override - public FakeMessage setTimestamp(long timestamp) - { + public FakeMessage setTimestamp(long timestamp) { return this; } @Override - public byte getPriority() - { + public byte getPriority() { return 0; } @Override - public FakeMessage setPriority(byte priority) - { + public FakeMessage setPriority(byte priority) { return this; } @Override - public int getEncodeSize() - { + public int getEncodeSize() { return 0; } @Override - public boolean isLargeMessage() - { + public boolean isLargeMessage() { return false; } @Override - public ActiveMQBuffer getBodyBuffer() - { + public ActiveMQBuffer getBodyBuffer() { return null; } @Override - public ActiveMQBuffer getBodyBufferCopy() - { + public ActiveMQBuffer getBodyBufferCopy() { return null; } @Override - public Message putBooleanProperty(SimpleString key, boolean value) - { + public Message putBooleanProperty(SimpleString key, boolean value) { return null; } @Override - public Message putBooleanProperty(String key, boolean value) - { + public Message putBooleanProperty(String key, boolean value) { return null; } @Override - public Message putByteProperty(SimpleString key, byte value) - { + public Message putByteProperty(SimpleString key, byte value) { return null; } @Override - public Message putByteProperty(String key, byte value) - { + public Message putByteProperty(String key, byte value) { return null; } @Override - public Message putBytesProperty(SimpleString key, byte[] value) - { + public Message putBytesProperty(SimpleString key, byte[] value) { return null; } @Override - public Message putBytesProperty(String key, byte[] value) - { + public Message putBytesProperty(String key, byte[] value) { return null; } @Override - public Message putShortProperty(SimpleString key, short value) - { + public Message putShortProperty(SimpleString key, short value) { return null; } @Override - public Message putShortProperty(String key, short value) - { + public Message putShortProperty(String key, short value) { return null; } @Override - public Message putCharProperty(SimpleString key, char value) - { + public Message putCharProperty(SimpleString key, char value) { return null; } @Override - public Message putCharProperty(String key, char value) - { + public Message putCharProperty(String key, char value) { return null; } @Override - public Message putIntProperty(SimpleString key, int value) - { + public Message putIntProperty(SimpleString key, int value) { return null; } @Override - public Message putIntProperty(String key, int value) - { + public Message putIntProperty(String key, int value) { return null; } @Override - public Message putLongProperty(SimpleString key, long value) - { + public Message putLongProperty(SimpleString key, long value) { return null; } @Override - public Message putLongProperty(String key, long value) - { + public Message putLongProperty(String key, long value) { return null; } @Override - public Message putFloatProperty(SimpleString key, float value) - { + public Message putFloatProperty(SimpleString key, float value) { return null; } @Override - public Message putFloatProperty(String key, float value) - { + public Message putFloatProperty(String key, float value) { return null; } @Override - public Message putDoubleProperty(SimpleString key, double value) - { + public Message putDoubleProperty(SimpleString key, double value) { return null; } @Override - public Message putDoubleProperty(String key, double value) - { + public Message putDoubleProperty(String key, double value) { return null; } @Override - public Message putStringProperty(SimpleString key, SimpleString value) - { + public Message putStringProperty(SimpleString key, SimpleString value) { return null; } @Override - public Message putStringProperty(String key, String value) - { + public Message putStringProperty(String key, String value) { return null; } @Override - public Message putObjectProperty(SimpleString key, Object value) throws ActiveMQPropertyConversionException - { + public Message putObjectProperty(SimpleString key, Object value) throws ActiveMQPropertyConversionException { return null; } @Override - public Message putObjectProperty(String key, Object value) throws ActiveMQPropertyConversionException - { + public Message putObjectProperty(String key, Object value) throws ActiveMQPropertyConversionException { return null; } @Override - public Object removeProperty(SimpleString key) - { + public Object removeProperty(SimpleString key) { return null; } @Override - public Object removeProperty(String key) - { + public Object removeProperty(String key) { return null; } @Override - public boolean containsProperty(SimpleString key) - { + public boolean containsProperty(SimpleString key) { return false; } @Override - public boolean containsProperty(String key) - { + public boolean containsProperty(String key) { return false; } @Override - public Boolean getBooleanProperty(SimpleString key) throws ActiveMQPropertyConversionException - { + public Boolean getBooleanProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override - public Boolean getBooleanProperty(String key) throws ActiveMQPropertyConversionException - { + public Boolean getBooleanProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override - public Byte getByteProperty(SimpleString key) throws ActiveMQPropertyConversionException - { + public Byte getByteProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override - public Byte getByteProperty(String key) throws ActiveMQPropertyConversionException - { + public Byte getByteProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override - public Double getDoubleProperty(SimpleString key) throws ActiveMQPropertyConversionException - { + public Double getDoubleProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override - public Double getDoubleProperty(String key) throws ActiveMQPropertyConversionException - { + public Double getDoubleProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override - public Integer getIntProperty(SimpleString key) throws ActiveMQPropertyConversionException - { + public Integer getIntProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override - public Integer getIntProperty(String key) throws ActiveMQPropertyConversionException - { + public Integer getIntProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override - public Long getLongProperty(SimpleString key) throws ActiveMQPropertyConversionException - { + public Long getLongProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override - public Long getLongProperty(String key) throws ActiveMQPropertyConversionException - { + public Long getLongProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override - public Object getObjectProperty(SimpleString key) - { + public Object getObjectProperty(SimpleString key) { return null; } @Override - public Object getObjectProperty(String key) - { + public Object getObjectProperty(String key) { return null; } @Override - public Short getShortProperty(SimpleString key) throws ActiveMQPropertyConversionException - { + public Short getShortProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override - public Short getShortProperty(String key) throws ActiveMQPropertyConversionException - { + public Short getShortProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override - public Float getFloatProperty(SimpleString key) throws ActiveMQPropertyConversionException - { + public Float getFloatProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override - public Float getFloatProperty(String key) throws ActiveMQPropertyConversionException - { + public Float getFloatProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override - public String getStringProperty(SimpleString key) throws ActiveMQPropertyConversionException - { + public String getStringProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override - public String getStringProperty(String key) throws ActiveMQPropertyConversionException - { + public String getStringProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override - public SimpleString getSimpleStringProperty(SimpleString key) throws ActiveMQPropertyConversionException - { + public SimpleString getSimpleStringProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override - public SimpleString getSimpleStringProperty(String key) throws ActiveMQPropertyConversionException - { + public SimpleString getSimpleStringProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override - public byte[] getBytesProperty(SimpleString key) throws ActiveMQPropertyConversionException - { + public byte[] getBytesProperty(SimpleString key) throws ActiveMQPropertyConversionException { return new byte[0]; } @Override - public byte[] getBytesProperty(String key) throws ActiveMQPropertyConversionException - { + public byte[] getBytesProperty(String key) throws ActiveMQPropertyConversionException { return new byte[0]; } @Override - public Set getPropertyNames() - { + public Set getPropertyNames() { return null; } @Override - public Map toMap() - { + public Map toMap() { return null; } @Override - public FakeMessage writeBodyBufferBytes(byte[] bytes) - { + public FakeMessage writeBodyBufferBytes(byte[] bytes) { return this; } @Override - public FakeMessage writeBodyBufferString(String string) - { + public FakeMessage writeBodyBufferString(String string) { return this; } } - - public class FakeQueueForScheduleUnitTest implements Queue - { + public class FakeQueueForScheduleUnitTest implements Queue { @Override - public void unproposed(SimpleString groupID) - { + public void unproposed(SimpleString groupID) { } - public FakeQueueForScheduleUnitTest(final int expectedElements) - { + public FakeQueueForScheduleUnitTest(final int expectedElements) { this.expectedElements = new CountDownLatch(expectedElements); } - - public boolean waitCompletion(long timeout, TimeUnit timeUnit) throws Exception - { + public boolean waitCompletion(long timeout, TimeUnit timeUnit) throws Exception { return expectedElements.await(timeout, timeUnit); } @@ -1013,509 +863,429 @@ public class ScheduledDeliveryHandlerTest extends Assert LinkedList messages = new LinkedList<>(); @Override - public SimpleString getName() - { + public SimpleString getName() { return null; } @Override - public long getID() - { + public long getID() { return 0; } @Override - public Filter getFilter() - { + public Filter getFilter() { return null; } @Override - public PageSubscription getPageSubscription() - { + public PageSubscription getPageSubscription() { return null; } @Override - public boolean isDurable() - { + public boolean isDurable() { return false; } @Override - public boolean isTemporary() - { + public boolean isTemporary() { return false; } @Override - public boolean isAutoCreated() - { + public boolean isAutoCreated() { return false; } @Override - public void addConsumer(Consumer consumer) throws Exception - { + public void addConsumer(Consumer consumer) throws Exception { } @Override - public void removeConsumer(Consumer consumer) - { + public void removeConsumer(Consumer consumer) { } @Override - public int getConsumerCount() - { + public int getConsumerCount() { return 0; } @Override - public void setConsumersRefCount(ReferenceCounter referenceCounter) - { + public void setConsumersRefCount(ReferenceCounter referenceCounter) { } @Override - public ReferenceCounter getConsumersRefCount() - { + public ReferenceCounter getConsumersRefCount() { return null; } @Override - public void reload(MessageReference ref) - { + public void reload(MessageReference ref) { } @Override - public void addTail(MessageReference ref) - { + public void addTail(MessageReference ref) { } @Override - public void addTail(MessageReference ref, boolean direct) - { + public void addTail(MessageReference ref, boolean direct) { } @Override - public void addHead(MessageReference ref) - { + public void addHead(MessageReference ref) { } @Override - public void addHead(List refs) - { - for (MessageReference ref : refs) - { + public void addHead(List refs) { + for (MessageReference ref : refs) { addFirst(ref); } } - private void addFirst(MessageReference ref) - { + private void addFirst(MessageReference ref) { expectedElements.countDown(); this.messages.addFirst(ref); } @Override - public void acknowledge(MessageReference ref) throws Exception - { + public void acknowledge(MessageReference ref) throws Exception { } @Override - public void acknowledge(Transaction tx, MessageReference ref) throws Exception - { + public void acknowledge(Transaction tx, MessageReference ref) throws Exception { } @Override - public void reacknowledge(Transaction tx, MessageReference ref) throws Exception - { + public void reacknowledge(Transaction tx, MessageReference ref) throws Exception { } @Override - public void cancel(Transaction tx, MessageReference ref) - { + public void cancel(Transaction tx, MessageReference ref) { } @Override - public void cancel(Transaction tx, MessageReference ref, boolean ignoreRedeliveryCheck) - { + public void cancel(Transaction tx, MessageReference ref, boolean ignoreRedeliveryCheck) { } @Override - public void cancel(MessageReference reference, long timeBase) throws Exception - { + public void cancel(MessageReference reference, long timeBase) throws Exception { } @Override - public void deliverAsync() - { + public void deliverAsync() { } @Override - public void forceDelivery() - { + public void forceDelivery() { } @Override - public void deleteQueue() throws Exception - { + public void deleteQueue() throws Exception { } @Override - public void deleteQueue(boolean removeConsumers) throws Exception - { + public void deleteQueue(boolean removeConsumers) throws Exception { } @Override - public void destroyPaging() throws Exception - { + public void destroyPaging() throws Exception { } @Override - public long getMessageCount() - { + public long getMessageCount() { return 0; } @Override - public int getDeliveringCount() - { + public int getDeliveringCount() { return 0; } @Override - public void referenceHandled() - { + public void referenceHandled() { } @Override - public int getScheduledCount() - { + public int getScheduledCount() { return 0; } @Override - public List getScheduledMessages() - { + public List getScheduledMessages() { return null; } @Override - public Map> getDeliveringMessages() - { + public Map> getDeliveringMessages() { return null; } @Override - public long getMessagesAdded() - { + public long getMessagesAdded() { return 0; } @Override - public long getMessagesAcknowledged() - { + public long getMessagesAcknowledged() { return 0; } @Override - public MessageReference removeReferenceWithID(long id) throws Exception - { + public MessageReference removeReferenceWithID(long id) throws Exception { return null; } @Override - public MessageReference getReference(long id) - { + public MessageReference getReference(long id) { return null; } @Override - public int deleteAllReferences() throws Exception - { + public int deleteAllReferences() throws Exception { return 0; } @Override - public int deleteAllReferences(int flushLimit) throws Exception - { + public int deleteAllReferences(int flushLimit) throws Exception { return 0; } @Override - public boolean deleteReference(long messageID) throws Exception - { + public boolean deleteReference(long messageID) throws Exception { return false; } @Override - public int deleteMatchingReferences(Filter filter) throws Exception - { + public int deleteMatchingReferences(Filter filter) throws Exception { return 0; } @Override - public int deleteMatchingReferences(int flushLImit, Filter filter) throws Exception - { + public int deleteMatchingReferences(int flushLImit, Filter filter) throws Exception { return 0; } @Override - public boolean expireReference(long messageID) throws Exception - { + public boolean expireReference(long messageID) throws Exception { return false; } @Override - public int expireReferences(Filter filter) throws Exception - { + public int expireReferences(Filter filter) throws Exception { return 0; } @Override - public void expireReferences() throws Exception - { + public void expireReferences() throws Exception { } @Override - public void expire(MessageReference ref) throws Exception - { + public void expire(MessageReference ref) throws Exception { } @Override - public boolean sendMessageToDeadLetterAddress(long messageID) throws Exception - { + public boolean sendMessageToDeadLetterAddress(long messageID) throws Exception { return false; } @Override - public int sendMessagesToDeadLetterAddress(Filter filter) throws Exception - { + public int sendMessagesToDeadLetterAddress(Filter filter) throws Exception { return 0; } @Override - public boolean changeReferencePriority(long messageID, byte newPriority) throws Exception - { + public boolean changeReferencePriority(long messageID, byte newPriority) throws Exception { return false; } @Override - public int changeReferencesPriority(Filter filter, byte newPriority) throws Exception - { + public int changeReferencesPriority(Filter filter, byte newPriority) throws Exception { return 0; } @Override - public boolean moveReference(long messageID, SimpleString toAddress) throws Exception - { + public boolean moveReference(long messageID, SimpleString toAddress) throws Exception { return false; } @Override - public boolean moveReference(long messageID, SimpleString toAddress, boolean rejectDuplicates) throws Exception - { + public boolean moveReference(long messageID, SimpleString toAddress, boolean rejectDuplicates) throws Exception { return false; } @Override - public int moveReferences(Filter filter, SimpleString toAddress) throws Exception - { + public int moveReferences(Filter filter, SimpleString toAddress) throws Exception { return 0; } @Override - public int moveReferences(int flushLimit, Filter filter, SimpleString toAddress, boolean rejectDuplicates) throws Exception - { + public int moveReferences(int flushLimit, + Filter filter, + SimpleString toAddress, + boolean rejectDuplicates) throws Exception { return 0; } @Override - public void addRedistributor(long delay) - { + public void addRedistributor(long delay) { } @Override - public void cancelRedistributor() throws Exception - { + public void cancelRedistributor() throws Exception { } @Override - public boolean hasMatchingConsumer(ServerMessage message) - { + public boolean hasMatchingConsumer(ServerMessage message) { return false; } @Override - public Collection getConsumers() - { + public Collection getConsumers() { return null; } @Override - public boolean checkRedelivery(MessageReference ref, long timeBase, boolean ignoreRedeliveryDelay) throws Exception - { + public boolean checkRedelivery(MessageReference ref, + long timeBase, + boolean ignoreRedeliveryDelay) throws Exception { return false; } @Override - public LinkedListIterator iterator() - { + public LinkedListIterator iterator() { return null; } @Override - public LinkedListIterator totalIterator() - { + public LinkedListIterator totalIterator() { return null; } @Override - public SimpleString getExpiryAddress() - { + public SimpleString getExpiryAddress() { return null; } @Override - public void pause() - { + public void pause() { } @Override - public void resume() - { + public void resume() { } @Override - public boolean isPaused() - { + public boolean isPaused() { return false; } @Override - public Executor getExecutor() - { + public Executor getExecutor() { return null; } @Override - public void resetAllIterators() - { + public void resetAllIterators() { } @Override - public boolean flushExecutor() - { + public boolean flushExecutor() { return false; } @Override - public void close() throws Exception - { + public void close() throws Exception { } @Override - public boolean isDirectDeliver() - { + public boolean isDirectDeliver() { return false; } @Override - public SimpleString getAddress() - { + public SimpleString getAddress() { return null; } @Override - public boolean isInternalQueue() - { + public boolean isInternalQueue() { return false; } @Override - public void setInternalQueue(boolean internalQueue) - { + public void setInternalQueue(boolean internalQueue) { } @Override - public void resetMessagesAdded() - { + public void resetMessagesAdded() { } @Override - public void resetMessagesAcknowledged() - { + public void resetMessagesAcknowledged() { } @Override - public void incrementMesssagesAdded() - { + public void incrementMesssagesAdded() { } @Override - public void deliverScheduledMessages() - { + public void deliverScheduledMessages() { } @Override - public void route(ServerMessage message, RoutingContext context) throws Exception - { + public void route(ServerMessage message, RoutingContext context) throws Exception { } @Override - public void routeWithAck(ServerMessage message, RoutingContext context) - { + public void routeWithAck(ServerMessage message, RoutingContext context) { } @Override - public void postAcknowledge(MessageReference ref) - { + public void postAcknowledge(MessageReference ref) { } @Override - public float getRate() - { + public float getRate() { return 0.0f; } @Override - public SimpleString getUser() - { + public SimpleString getUser() { return null; } } diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/core/settings/AddressSettingsTest.java b/artemis-server/src/test/java/org/apache/activemq/artemis/core/settings/AddressSettingsTest.java index 00b95fcc54..4b84e75322 100644 --- a/artemis-server/src/test/java/org/apache/activemq/artemis/core/settings/AddressSettingsTest.java +++ b/artemis-server/src/test/java/org/apache/activemq/artemis/core/settings/AddressSettingsTest.java @@ -23,23 +23,19 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Assert; import org.junit.Test; -public class AddressSettingsTest extends ActiveMQTestBase -{ +public class AddressSettingsTest extends ActiveMQTestBase { + @Test - public void testDefaults() - { + public void testDefaults() { AddressSettings addressSettings = new AddressSettings(); Assert.assertEquals(null, addressSettings.getDeadLetterAddress()); Assert.assertEquals(null, addressSettings.getExpiryAddress()); Assert.assertEquals(AddressSettings.DEFAULT_MAX_DELIVERY_ATTEMPTS, addressSettings.getMaxDeliveryAttempts()); Assert.assertEquals(addressSettings.getMaxSizeBytes(), AddressSettings.DEFAULT_MAX_SIZE_BYTES); Assert.assertEquals(AddressSettings.DEFAULT_PAGE_SIZE, addressSettings.getPageSizeBytes()); - Assert.assertEquals(AddressSettings.DEFAULT_MESSAGE_COUNTER_HISTORY_DAY_LIMIT, - addressSettings.getMessageCounterHistoryDayLimit()); + Assert.assertEquals(AddressSettings.DEFAULT_MESSAGE_COUNTER_HISTORY_DAY_LIMIT, addressSettings.getMessageCounterHistoryDayLimit()); Assert.assertEquals(AddressSettings.DEFAULT_REDELIVER_DELAY, addressSettings.getRedeliveryDelay()); - Assert.assertEquals(AddressSettings.DEFAULT_REDELIVER_MULTIPLIER, - addressSettings.getRedeliveryMultiplier(), - 0.000001); + Assert.assertEquals(AddressSettings.DEFAULT_REDELIVER_MULTIPLIER, addressSettings.getRedeliveryMultiplier(), 0.000001); Assert.assertEquals(AddressSettings.DEFAULT_SLOW_CONSUMER_THRESHOLD, addressSettings.getSlowConsumerThreshold()); Assert.assertEquals(AddressSettings.DEFAULT_SLOW_CONSUMER_CHECK_PERIOD, addressSettings.getSlowConsumerCheckPeriod()); Assert.assertEquals(AddressSettings.DEFAULT_SLOW_CONSUMER_POLICY, addressSettings.getSlowConsumerPolicy()); @@ -48,8 +44,7 @@ public class AddressSettingsTest extends ActiveMQTestBase } @Test - public void testSingleMerge() - { + public void testSingleMerge() { AddressSettings addressSettings = new AddressSettings(); AddressSettings addressSettingsToMerge = new AddressSettings(); SimpleString DLQ = new SimpleString("testDLQ"); @@ -74,8 +69,7 @@ public class AddressSettingsTest extends ActiveMQTestBase } @Test - public void testMultipleMerge() - { + public void testMultipleMerge() { AddressSettings addressSettings = new AddressSettings(); AddressSettings addressSettingsToMerge = new AddressSettings(); SimpleString DLQ = new SimpleString("testDLQ"); @@ -107,8 +101,7 @@ public class AddressSettingsTest extends ActiveMQTestBase } @Test - public void testMultipleMergeAll() - { + public void testMultipleMergeAll() { AddressSettings addressSettings = new AddressSettings(); AddressSettings addressSettingsToMerge = new AddressSettings(); SimpleString DLQ = new SimpleString("testDLQ"); diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/core/settings/RepositoryTest.java b/artemis-server/src/test/java/org/apache/activemq/artemis/core/settings/RepositoryTest.java index 9f3b7de169..a5266d57d8 100644 --- a/artemis-server/src/test/java/org/apache/activemq/artemis/core/settings/RepositoryTest.java +++ b/artemis-server/src/test/java/org/apache/activemq/artemis/core/settings/RepositoryTest.java @@ -27,22 +27,20 @@ import java.util.ArrayList; import java.util.HashSet; import java.util.concurrent.atomic.AtomicInteger; -public class RepositoryTest extends ActiveMQTestBase -{ +public class RepositoryTest extends ActiveMQTestBase { + HierarchicalRepository> securityRepository; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); securityRepository = new HierarchicalObjectRepository<>(); } @Test - public void testDefault() - { + public void testDefault() { securityRepository.setDefault(new HashSet()); HashSet roles = securityRepository.getMatch("queues.something"); @@ -50,8 +48,7 @@ public class RepositoryTest extends ActiveMQTestBase } @Test - public void testMatchingDocs() throws Throwable - { + public void testMatchingDocs() throws Throwable { HierarchicalObjectRepository repo = new HierarchicalObjectRepository<>(); repo.addMatch("a.b.#", "ab#"); @@ -65,16 +62,14 @@ public class RepositoryTest extends ActiveMQTestBase } @Test - public void testSingleMatch() - { + public void testSingleMatch() { securityRepository.addMatch("queues.*", new HashSet()); HashSet hashSet = securityRepository.getMatch("queues.something"); Assert.assertEquals(hashSet.size(), 0); } @Test - public void testSingletwo() - { + public void testSingletwo() { securityRepository.addMatch("queues.another.aq.*", new HashSet()); HashSet roles = new HashSet(2); roles.add(new Role("test1", true, true, true, true, true, true, true)); @@ -91,8 +86,7 @@ public class RepositoryTest extends ActiveMQTestBase } @Test - public void testWithoutWildcard() - { + public void testWithoutWildcard() { securityRepository.addMatch("queues.1.*", new HashSet()); HashSet roles = new HashSet(2); roles.add(new Role("test1", true, true, true, true, true, true, true)); @@ -103,8 +97,7 @@ public class RepositoryTest extends ActiveMQTestBase } @Test - public void testMultipleWildcards() - { + public void testMultipleWildcards() { HierarchicalRepository repository = new HierarchicalObjectRepository(); repository.addMatch("#", "#"); repository.addMatch("a", "a"); @@ -148,8 +141,7 @@ public class RepositoryTest extends ActiveMQTestBase } @Test - public void testRepositoryMerge() - { + public void testRepositoryMerge() { HierarchicalRepository repository = new HierarchicalObjectRepository(); repository.addMatch("#", new DummyMergeable(1)); repository.addMatch("a.#", new DummyMergeable(2)); @@ -178,20 +170,16 @@ public class RepositoryTest extends ActiveMQTestBase DummyMergeable.reset(); } - @Test - public void testAddListener() - { + public void testAddListener() { HierarchicalRepository repository = new HierarchicalObjectRepository(); repository.addMatch("#", "1"); repository.addMatch("B", "2"); final AtomicInteger called = new AtomicInteger(0); - repository.registerListener(new HierarchicalRepositoryChangeListener() - { + repository.registerListener(new HierarchicalRepositoryChangeListener() { @Override - public void onChange() - { + public void onChange() { called.incrementAndGet(); } }); @@ -223,60 +211,50 @@ public class RepositoryTest extends ActiveMQTestBase assertEquals(4, called.get()); } - @Test - public void testIllegalMatches() - { + public void testIllegalMatches() { HierarchicalRepository repository = new HierarchicalObjectRepository(); - try - { + try { repository.addMatch("hjhjhjhjh.#.hhh", "test"); fail("expected exception"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { // pass } - try - { + try { repository.addMatch(null, "test"); fail("expected exception"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { // pass } } - static class DummyMergeable implements Mergeable - { + static class DummyMergeable implements Mergeable { + static int timesMerged = 0; static ArrayList merged = new ArrayList(); private final Integer id; - static void reset() - { + static void reset() { DummyMergeable.timesMerged = 0; DummyMergeable.merged = new ArrayList(); } - static boolean contains(final Integer i) - { + static boolean contains(final Integer i) { return DummyMergeable.merged.contains(i); } - public DummyMergeable(final Integer id) - { + public DummyMergeable(final Integer id) { this.id = id; } - public void merge(final Object merged) - { + public void merge(final Object merged) { DummyMergeable.timesMerged++; DummyMergeable.merged.add(id); - DummyMergeable.merged.add(((DummyMergeable)merged).id); + DummyMergeable.merged.add(((DummyMergeable) merged).id); } } } diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/core/version/impl/VersionImplTest.java b/artemis-server/src/test/java/org/apache/activemq/artemis/core/version/impl/VersionImplTest.java index fef518ac9a..f6ea5d05e5 100644 --- a/artemis-server/src/test/java/org/apache/activemq/artemis/core/version/impl/VersionImplTest.java +++ b/artemis-server/src/test/java/org/apache/activemq/artemis/core/version/impl/VersionImplTest.java @@ -25,9 +25,7 @@ import java.io.ObjectOutputStream; import org.junit.Assert; - -public class VersionImplTest extends Assert -{ +public class VersionImplTest extends Assert { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -39,21 +37,15 @@ public class VersionImplTest extends Assert // Public -------------------------------------------------------- @Test - public void testVersionImpl() throws Exception - { + public void testVersionImpl() throws Exception { String versionName = "ACTIVEMQ"; int majorVersion = 2; int minorVersion = 0; int microVersion = 1; int incrementingVersion = 10; - int[] compatibleVersionList = {7,8,9,10}; - VersionImpl version = new VersionImpl(versionName, - majorVersion, - minorVersion, - microVersion, - incrementingVersion, - compatibleVersionList); + int[] compatibleVersionList = {7, 8, 9, 10}; + VersionImpl version = new VersionImpl(versionName, majorVersion, minorVersion, microVersion, incrementingVersion, compatibleVersionList); Assert.assertEquals(versionName, version.getVersionName()); Assert.assertEquals(majorVersion, version.getMajorVersion()); @@ -63,11 +55,10 @@ public class VersionImplTest extends Assert } @Test - public void testEquals() throws Exception - { - VersionImpl version = new VersionImpl("ACTIVEMQ", 2, 0, 1, 10, new int[]{7,8,9,10}); - VersionImpl sameVersion = new VersionImpl("ACTIVEMQ", 2, 0, 1, 10, new int[]{7,8,9,10}); - VersionImpl differentVersion = new VersionImpl("ACTIVEMQ", 2, 0, 1, 11, new int[]{7,8,9,10,11}); + public void testEquals() throws Exception { + VersionImpl version = new VersionImpl("ACTIVEMQ", 2, 0, 1, 10, new int[]{7, 8, 9, 10}); + VersionImpl sameVersion = new VersionImpl("ACTIVEMQ", 2, 0, 1, 10, new int[]{7, 8, 9, 10}); + VersionImpl differentVersion = new VersionImpl("ACTIVEMQ", 2, 0, 1, 11, new int[]{7, 8, 9, 10, 11}); Assert.assertFalse(version.equals(new Object())); @@ -77,9 +68,8 @@ public class VersionImplTest extends Assert } @Test - public void testSerialize() throws Exception - { - VersionImpl version = new VersionImpl("uyiuy", 3, 7, 6, 12, new int[]{9,10,11,12}); + public void testSerialize() throws Exception { + VersionImpl version = new VersionImpl("uyiuy", 3, 7, 6, 12, new int[]{9, 10, 11, 12}); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(version); @@ -87,7 +77,7 @@ public class VersionImplTest extends Assert ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); - VersionImpl version2 = (VersionImpl)ois.readObject(); + VersionImpl version2 = (VersionImpl) ois.readObject(); Assert.assertTrue(version.equals(version2)); } diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/ActiveMQTestBase.java b/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/ActiveMQTestBase.java index 4142f1f46a..ab68c8d91b 100644 --- a/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/ActiveMQTestBase.java +++ b/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/ActiveMQTestBase.java @@ -134,8 +134,8 @@ import org.junit.runner.Description; /** * Base class with basic utilities on starting up a basic server */ -public abstract class ActiveMQTestBase extends Assert -{ +public abstract class ActiveMQTestBase extends Assert { + public static final String TARGET_TMP = "./target/tmp"; public static final String INVM_ACCEPTOR_FACTORY = InVMAcceptorFactory.class.getCanonicalName(); public static final String INVM_CONNECTOR_FACTORY = InVMConnectorFactory.class.getCanonicalName(); @@ -183,74 +183,58 @@ public abstract class ActiveMQTestBase extends Assert public RemoveFolder folder = new RemoveFolder(TARGET_TMP); @Rule - public TestRule watcher = new TestWatcher() - { + public TestRule watcher = new TestWatcher() { @Override - protected void starting(Description description) - { + protected void starting(Description description) { log.info(String.format("#*#*# Starting test: %s()...", description.getMethodName())); } @Override - protected void finished(Description description) - { + protected void finished(Description description) { log.info(String.format("#*#*# Finished test: %s()...", description.getMethodName())); } }; - static - { + static { Random random = new Random(); DEFAULT_UDP_PORT = 6000 + random.nextInt(1000); } - public ActiveMQTestBase() - { + public ActiveMQTestBase() { File parent = new File(TARGET_TMP); parent.mkdirs(); temporaryFolder = new TemporaryFolder(parent); } @After - public void tearDown() throws Exception - { - for (ExecutorService s : executorSet) - { + public void tearDown() throws Exception { + for (ExecutorService s : executorSet) { s.shutdown(); } closeAllSessionFactories(); closeAllServerLocatorsFactories(); - try - { + try { assertAllExecutorsFinished(); assertAllClientConsumersAreClosed(); assertAllClientProducersAreClosed(); assertAllClientSessionsAreClosed(); } - finally - { - synchronized (servers) - { - for (ActiveMQServer server : servers) - { - if (server == null) - { + finally { + synchronized (servers) { + for (ActiveMQServer server : servers) { + if (server == null) { continue; } - try - { + try { final ClusterManager clusterManager = server.getClusterManager(); - if (clusterManager != null) - { - for (ClusterConnection cc : clusterManager.getClusterConnections()) - { + if (clusterManager != null) { + for (ClusterConnection cc : clusterManager.getClusterConnections()) { stopComponent(cc); } } } - catch (Exception e) - { + catch (Exception e) { // no-op } stopComponentOutputExceptions(server); @@ -261,72 +245,60 @@ public abstract class ActiveMQTestBase extends Assert closeAllOtherComponents(); ArrayList exceptions; - try - { + try { exceptions = checkCsfStopped(); } - finally - { + finally { cleanupPools(); } //clean up pools before failing - if (!exceptions.isEmpty()) - { - for (Exception exception : exceptions) - { + if (!exceptions.isEmpty()) { + for (Exception exception : exceptions) { exception.printStackTrace(); } fail("Client Session Factories still trying to reconnect, see above to see where created"); } Map threadMap = Thread.getAllStackTraces(); - for (Thread thread : threadMap.keySet()) - { + for (Thread thread : threadMap.keySet()) { StackTraceElement[] stack = threadMap.get(thread); - for (StackTraceElement stackTraceElement : stack) - { - if (stackTraceElement.getMethodName().contains("getConnectionWithRetry") && !alreadyFailedThread.contains(thread)) - { + for (StackTraceElement stackTraceElement : stack) { + if (stackTraceElement.getMethodName().contains("getConnectionWithRetry") && !alreadyFailedThread.contains(thread)) { alreadyFailedThread.add(thread); System.out.println(threadDump(this.getName() + " has left threads running. Look at thread " + - thread.getName() + - " id = " + - thread.getId() + - " has running locators on test " + - this.getName() + - " on this following dump")); + thread.getName() + + " id = " + + thread.getId() + + " has running locators on test " + + this.getName() + + " on this following dump")); fail("test '" + getName() + "' left serverlocator running, this could effect other tests"); } - else if (stackTraceElement.getMethodName().contains("BroadcastGroupImpl.run") && !alreadyFailedThread.contains(thread)) - { + else if (stackTraceElement.getMethodName().contains("BroadcastGroupImpl.run") && !alreadyFailedThread.contains(thread)) { alreadyFailedThread.add(thread); System.out.println(threadDump(this.getName() + " has left threads running. Look at thread " + - thread.getName() + - " id = " + - thread.getId() + - " is still broadcasting " + - this.getName() + - " on this following dump")); + thread.getName() + + " id = " + + thread.getId() + + " is still broadcasting " + + this.getName() + + " on this following dump")); fail("test left broadcastgroupimpl running, this could effect other tests"); } } } - if (checkThread) - { + if (checkThread) { StringBuffer buffer = null; boolean failed = true; - long timeout = System.currentTimeMillis() + 60000; - while (failed && timeout > System.currentTimeMillis()) - { + while (failed && timeout > System.currentTimeMillis()) { buffer = new StringBuffer(); failed = checkThread(buffer); - if (failed) - { + if (failed) { forceGC(); Thread.sleep(500); log.info("There are still threads running, trying again"); @@ -334,23 +306,20 @@ public abstract class ActiveMQTestBase extends Assert } } - if (failed) - { + if (failed) { logAndSystemOut("Thread leaked on test " + this.getClass().getName() + "::" + this.getName() + "\n" + - buffer); + buffer); logAndSystemOut("Thread leakage"); fail("Thread leaked"); } } - else - { + else { checkThread = true; } - if (Thread.currentThread().getContextClassLoader() == null) - { + if (Thread.currentThread().getContextClassLoader() == null) { Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); fail("Thread Context ClassLoader was set to null at some point before this test. We will set to this.getClass().getClassLoader(), but you are supposed to fix your tests"); } @@ -358,15 +327,13 @@ public abstract class ActiveMQTestBase extends Assert checkFilesUsage(); } - if (InVMRegistry.instance.size() > 0) - { + if (InVMRegistry.instance.size() > 0) { fail("InVMREgistry size > 0"); } } @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { sendMsgCount = 0; testDir = temporaryFolder.getRoot().getAbsolutePath(); clearDataRecreateServerDirs(); @@ -381,80 +348,63 @@ public abstract class ActiveMQTestBase extends Assert logAndSystemOut("#test " + getName()); } - public static void assertEqualsByteArrays(final byte[] expected, final byte[] actual) - { - for (int i = 0; i < expected.length; i++) - { + public static void assertEqualsByteArrays(final byte[] expected, final byte[] actual) { + for (int i = 0; i < expected.length; i++) { Assert.assertEquals("byte at index " + i, expected[i], actual[i]); } } /** - * * @param str * @param sub * @return */ - public static int countOccurrencesOf(String str, String sub) - { - if (str == null || sub == null || str.length() == 0 || sub.length() == 0) - { + public static int countOccurrencesOf(String str, String sub) { + if (str == null || sub == null || str.length() == 0 || sub.length() == 0) { return 0; } int count = 0; int pos = 0; int idx; - while ((idx = str.indexOf(sub, pos)) != -1) - { + while ((idx = str.indexOf(sub, pos)) != -1) { ++count; pos = idx + sub.length(); } return count; } - protected void disableCheckThread() - { + protected void disableCheckThread() { checkThread = false; } - protected String getName() - { + protected String getName() { return name.getMethodName(); } - protected boolean isWindows() - { + protected boolean isWindows() { return (OS_TYPE.indexOf("win") >= 0); } - protected Configuration createDefaultInVMConfig() throws Exception - { + protected Configuration createDefaultInVMConfig() throws Exception { return createDefaultConfig(0, false); } - protected Configuration createDefaultInVMConfig(final int serverID) throws Exception - { + protected Configuration createDefaultInVMConfig(final int serverID) throws Exception { return createDefaultConfig(serverID, false); } - protected Configuration createDefaultNettyConfig() throws Exception - { + protected Configuration createDefaultNettyConfig() throws Exception { return createDefaultConfig(0, true); } - protected Configuration createDefaultConfig(final boolean netty) throws Exception - { + protected Configuration createDefaultConfig(final boolean netty) throws Exception { return createDefaultConfig(0, netty); } - protected Configuration createDefaultConfig(final int serverID, final boolean netty) throws Exception - { - ConfigurationImpl configuration = createBasicConfig(serverID) - .setJMXManagementEnabled(false) - .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, generateInVMParams(serverID))); + protected Configuration createDefaultConfig(final int serverID, final boolean netty) throws Exception { + ConfigurationImpl configuration = createBasicConfig(serverID).setJMXManagementEnabled(false).addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, generateInVMParams(serverID))); - if (netty) - { + if (netty) { configuration.addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY)); } @@ -462,13 +412,11 @@ public abstract class ActiveMQTestBase extends Assert } private Configuration createDefaultConfig(final int index, - final Map params, - final String... acceptors) - { + final Map params, + final String... acceptors) { Configuration configuration = createBasicConfig(index); - for (String acceptor : acceptors) - { + for (String acceptor : acceptors) { TransportConfiguration transportConfig = new TransportConfiguration(acceptor, params); configuration.getAcceptorConfigurations().add(transportConfig); } @@ -476,8 +424,7 @@ public abstract class ActiveMQTestBase extends Assert return configuration; } - protected ConfigurationImpl createBasicConfig() throws Exception - { + protected ConfigurationImpl createBasicConfig() throws Exception { return createBasicConfig(-1); } @@ -486,26 +433,13 @@ public abstract class ActiveMQTestBase extends Assert * @return * @throws Exception */ - protected ConfigurationImpl createBasicConfig(final int serverID) - { - ConfigurationImpl configuration = new ConfigurationImpl() - .setSecurityEnabled(false) - .setJournalMinFiles(2) - .setJournalFileSize(100 * 1024) - .setJournalType(getDefaultJournalType()) - .setJournalDirectory(getJournalDir(serverID, false)) - .setBindingsDirectory(getBindingsDir(serverID, false)) - .setPagingDirectory(getPageDir(serverID, false)) - .setLargeMessagesDirectory(getLargeMessagesDir(serverID, false)) - .setJournalCompactMinFiles(0) - .setJournalCompactPercentage(0) - .setClusterPassword(CLUSTER_PASSWORD); + protected ConfigurationImpl createBasicConfig(final int serverID) { + ConfigurationImpl configuration = new ConfigurationImpl().setSecurityEnabled(false).setJournalMinFiles(2).setJournalFileSize(100 * 1024).setJournalType(getDefaultJournalType()).setJournalDirectory(getJournalDir(serverID, false)).setBindingsDirectory(getBindingsDir(serverID, false)).setPagingDirectory(getPageDir(serverID, false)).setLargeMessagesDirectory(getLargeMessagesDir(serverID, false)).setJournalCompactMinFiles(0).setJournalCompactPercentage(0).setClusterPassword(CLUSTER_PASSWORD); return configuration; } - protected Map generateInVMParams(final int node) - { + protected Map generateInVMParams(final int node) { Map params = new HashMap(); params.put(org.apache.activemq.artemis.core.remoting.impl.invm.TransportConstants.SERVER_ID_PROP_NAME, node); @@ -513,41 +447,28 @@ public abstract class ActiveMQTestBase extends Assert return params; } - protected static final ClusterConnectionConfiguration basicClusterConnectionConfig(String connectorName, String... connectors) - { + protected static final ClusterConnectionConfiguration basicClusterConnectionConfig(String connectorName, + String... connectors) { ArrayList connectors0 = new ArrayList<>(); - for (String c : connectors) - { + for (String c : connectors) { connectors0.add(c); } - ClusterConnectionConfiguration clusterConnectionConfiguration = new ClusterConnectionConfiguration() - .setName("cluster1") - .setAddress("jms") - .setConnectorName(connectorName) - .setRetryInterval(1000) - .setDuplicateDetection(false) - .setMaxHops(1) - .setConfirmationWindowSize(1) - .setMessageLoadBalancingType(MessageLoadBalancingType.STRICT) - .setStaticConnectors(connectors0); + ClusterConnectionConfiguration clusterConnectionConfiguration = new ClusterConnectionConfiguration().setName("cluster1").setAddress("jms").setConnectorName(connectorName).setRetryInterval(1000).setDuplicateDetection(false).setMaxHops(1).setConfirmationWindowSize(1).setMessageLoadBalancingType(MessageLoadBalancingType.STRICT).setStaticConnectors(connectors0); return clusterConnectionConfiguration; } - protected final OrderedExecutorFactory getOrderedExecutor() - { + protected final OrderedExecutorFactory getOrderedExecutor() { final ExecutorService executor = Executors.newCachedThreadPool(); executorSet.add(executor); return new OrderedExecutorFactory(executor); } - protected static String getUDPDiscoveryAddress() - { + protected static String getUDPDiscoveryAddress() { return System.getProperty("TEST-UDP-ADDRESS", "230.1.2.3"); } - protected static String getUDPDiscoveryAddress(final int variant) - { + protected static String getUDPDiscoveryAddress(final int variant) { String value = getUDPDiscoveryAddress(); int posPoint = value.lastIndexOf('.'); @@ -557,72 +478,57 @@ public abstract class ActiveMQTestBase extends Assert return value.substring(0, posPoint + 1) + (last + variant); } - public static int getUDPDiscoveryPort() - { + public static int getUDPDiscoveryPort() { String port = System.getProperty("TEST-UDP-PORT"); - if (port != null) - { + if (port != null) { return Integer.parseInt(port); } return DEFAULT_UDP_PORT; } - public static int getUDPDiscoveryPort(final int variant) - { + public static int getUDPDiscoveryPort(final int variant) { return getUDPDiscoveryPort() + variant; } - public static JournalType getDefaultJournalType() - { - if (LibaioContext.isLoaded()) - { + public static JournalType getDefaultJournalType() { + if (LibaioContext.isLoaded()) { return JournalType.ASYNCIO; } - else - { + else { return JournalType.NIO; } } - public static void forceGC() - { + public static void forceGC() { log.info("#test forceGC"); WeakReference dumbReference = new WeakReference(new Object()); // A loop that will wait GC, using the minimal time as possible - while (dumbReference.get() != null) - { + while (dumbReference.get() != null) { System.gc(); - try - { + try { Thread.sleep(100); } - catch (InterruptedException e) - { + catch (InterruptedException e) { } } log.info("#test forceGC Done"); } - public static void forceGC(final Reference ref, final long timeout) - { + public static void forceGC(final Reference ref, final long timeout) { long waitUntil = System.currentTimeMillis() + timeout; // A loop that will wait GC, using the minimal time as possible - while (ref.get() != null && System.currentTimeMillis() < waitUntil) - { + while (ref.get() != null && System.currentTimeMillis() < waitUntil) { ArrayList list = new ArrayList(); - for (int i = 0; i < 1000; i++) - { + for (int i = 0; i < 1000; i++) { list.add("Some string with garbage with concatenation " + i); } list.clear(); list = null; System.gc(); - try - { + try { Thread.sleep(500); } - catch (InterruptedException e) - { + catch (InterruptedException e) { } } } @@ -633,39 +539,31 @@ public abstract class ActiveMQTestBase extends Assert * @param references * @throws InterruptedException */ - public static void checkWeakReferences(final WeakReference... references) - { + public static void checkWeakReferences(final WeakReference... references) { int i = 0; boolean hasValue = false; - do - { + do { hasValue = false; - if (i > 0) - { + if (i > 0) { forceGC(); } - for (WeakReference ref : references) - { - if (ref.get() != null) - { + for (WeakReference ref : references) { + if (ref.get() != null) { hasValue = true; break; } } - } - while (i++ <= 30 && hasValue); + } while (i++ <= 30 && hasValue); - for (WeakReference ref : references) - { + for (WeakReference ref : references) { Assert.assertNull(ref.get()); } } - public static String threadDump(final String msg) - { + public static String threadDump(final String msg) { StringWriter str = new StringWriter(); PrintWriter out = new PrintWriter(str); @@ -674,19 +572,17 @@ public abstract class ActiveMQTestBase extends Assert out.println("*******************************************************************************"); out.println("Complete Thread dump " + msg); - for (Map.Entry el : stackTrace.entrySet()) - { + for (Map.Entry el : stackTrace.entrySet()) { out.println("==============================================================================="); out.println("Thread " + el.getKey() + - " name = " + - el.getKey().getName() + - " id = " + - el.getKey().getId() + - " group = " + - el.getKey().getThreadGroup()); + " name = " + + el.getKey().getName() + + " id = " + + el.getKey().getId() + + " group = " + + el.getKey().getThreadGroup()); out.println(); - for (StackTraceElement traceEl : el.getValue()) - { + for (StackTraceElement traceEl : el.getValue()) { out.println(traceEl); } } @@ -701,13 +597,11 @@ public abstract class ActiveMQTestBase extends Assert /** * Sends the message to both logger and System.out (for unit report) */ - public void logAndSystemOut(String message, Exception e) - { + public void logAndSystemOut(String message, Exception e) { ActiveMQServerLogger log0 = ActiveMQServerLogger.LOGGER; log0.info(message, e); System.out.println(message); - if (e != null) - { + if (e != null) { e.printStackTrace(System.out); } } @@ -715,23 +609,19 @@ public abstract class ActiveMQTestBase extends Assert /** * Sends the message to both logger and System.out (for unit report) */ - public void logAndSystemOut(String message) - { + public void logAndSystemOut(String message) { logAndSystemOut(message, null); } - public static String dumpBytes(final byte[] bytes) - { + public static String dumpBytes(final byte[] bytes) { StringBuffer buff = new StringBuffer(); buff.append(System.identityHashCode(bytes) + ", size: " + bytes.length + " ["); - for (int i = 0; i < bytes.length; i++) - { + for (int i = 0; i < bytes.length; i++) { buff.append(bytes[i]); - if (i != bytes.length - 1) - { + if (i != bytes.length - 1) { buff.append(", "); } } @@ -741,22 +631,18 @@ public abstract class ActiveMQTestBase extends Assert return buff.toString(); } - public static String dumpBytesHex(final byte[] buffer, final int bytesPerLine) - { + public static String dumpBytesHex(final byte[] buffer, final int bytesPerLine) { StringBuffer buff = new StringBuffer(); buff.append("["); - for (int i = 0; i < buffer.length; i++) - { + for (int i = 0; i < buffer.length; i++) { buff.append(String.format("%1$2X", buffer[i])); - if (i + 1 < buffer.length) - { + if (i + 1 < buffer.length) { buff.append(", "); } - if ((i + 1) % bytesPerLine == 0) - { + if ((i + 1) % bytesPerLine == 0) { buff.append("\n "); } } @@ -766,23 +652,19 @@ public abstract class ActiveMQTestBase extends Assert } public static void assertEqualsTransportConfigurations(final TransportConfiguration[] expected, - final TransportConfiguration[] actual) - { + final TransportConfiguration[] actual) { assertEquals(expected.length, actual.length); - for (int i = 0; i < expected.length; i++) - { + for (int i = 0; i < expected.length; i++) { Assert.assertEquals("TransportConfiguration at index " + i, expected[i], actual[i]); } } - public static void assertEqualsBuffers(final int size, final ActiveMQBuffer expected, final ActiveMQBuffer actual) - { + public static void assertEqualsBuffers(final int size, final ActiveMQBuffer expected, final ActiveMQBuffer actual) { // assertEquals(expected.length, actual.length); expected.readerIndex(0); actual.readerIndex(0); - for (int i = 0; i < size; i++) - { + for (int i = 0; i < size; i++) { byte b1 = expected.readByte(); byte b2 = actual.readByte(); Assert.assertEquals("byte at index " + i, b1, b2); @@ -791,26 +673,22 @@ public abstract class ActiveMQTestBase extends Assert actual.resetReaderIndex(); } - public static void assertEqualsByteArrays(final int length, final byte[] expected, final byte[] actual) - { + public static void assertEqualsByteArrays(final int length, final byte[] expected, final byte[] actual) { // we check only for the given length (the arrays might be // larger) Assert.assertTrue(expected.length >= length); Assert.assertTrue(actual.length >= length); - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { Assert.assertEquals("byte at index " + i, expected[i], actual[i]); } } - public static void assertSameXids(final List expected, final List actual) - { + public static void assertSameXids(final List expected, final List actual) { Assert.assertNotNull(expected); Assert.assertNotNull(actual); Assert.assertEquals(expected.size(), actual.size()); - for (int i = 0; i < expected.size(); i++) - { + for (int i = 0; i < expected.size(); i++) { Xid expectedXid = expected.get(i); Xid actualXid = actual.get(i); assertEqualsByteArrays(expectedXid.getBranchQualifier(), actualXid.getBranchQualifier()); @@ -819,20 +697,16 @@ public abstract class ActiveMQTestBase extends Assert } } - protected static void checkNoBinding(final Context context, final String binding) - { - try - { + protected static void checkNoBinding(final Context context, final String binding) { + try { context.lookup(binding); Assert.fail("there must be no resource to look up for " + binding); } - catch (Exception e) - { + catch (Exception e) { } } - protected static Object checkBinding(final Context context, final String binding) throws Exception - { + protected static Object checkBinding(final Context context, final String binding) throws Exception { Object o = context.lookup(binding); Assert.assertNotNull(o); return o; @@ -843,14 +717,12 @@ public abstract class ActiveMQTestBase extends Assert * @return */ protected ArrayList registerConnectors(final ActiveMQServer server, - final List connectorConfigs) - { + final List connectorConfigs) { // The connectors need to be pre-configured at main config object but this method is taking // TransportConfigurations directly // So this will first register them at the config and then generate a list of objects ArrayList connectors = new ArrayList(); - for (TransportConfiguration tnsp : connectorConfigs) - { + for (TransportConfiguration tnsp : connectorConfigs) { String name1 = RandomUtil.randomString(); server.getConfiguration().getConnectorConfigurations().put(name1, tnsp); @@ -860,29 +732,21 @@ public abstract class ActiveMQTestBase extends Assert return connectors; } - protected static final void checkFreePort(final int... ports) - { - for (int port : ports) - { + protected static final void checkFreePort(final int... ports) { + for (int port : ports) { ServerSocket ssocket = null; - try - { + try { ssocket = new ServerSocket(port); } - catch (Exception e) - { + catch (Exception e) { throw new IllegalStateException("port " + port + " is bound", e); } - finally - { - if (ssocket != null) - { - try - { + finally { + if (ssocket != null) { + try { ssocket.close(); } - catch (IOException e) - { + catch (IOException e) { } } } @@ -892,28 +756,23 @@ public abstract class ActiveMQTestBase extends Assert /** * @return the testDir */ - protected final String getTestDir() - { + protected final String getTestDir() { return testDir; } - protected final File getTestDirfile() - { + protected final File getTestDirfile() { return new File(testDir); } - protected final void setTestDir(String testDir) - { + protected final void setTestDir(String testDir) { this.testDir = testDir; } - protected final void clearDataRecreateServerDirs() - { + protected final void clearDataRecreateServerDirs() { clearDataRecreateServerDirs(getTestDir()); } - protected void clearDataRecreateServerDirs(final String testDir1) - { + protected void clearDataRecreateServerDirs(final String testDir1) { // Need to delete the root File file = new File(testDir1); @@ -931,65 +790,55 @@ public abstract class ActiveMQTestBase extends Assert /** * @return the journalDir */ - public String getJournalDir() - { + public String getJournalDir() { return getJournalDir(getTestDir()); } - protected static String getJournalDir(final String testDir1) - { + protected static String getJournalDir(final String testDir1) { return testDir1 + "/journal"; } - protected String getJournalDir(final int index, final boolean backup) - { + protected String getJournalDir(final int index, final boolean backup) { return getJournalDir(getTestDir(), index, backup); } - public static String getJournalDir(final String testDir, final int index, final boolean backup) - { + public static String getJournalDir(final String testDir, final int index, final boolean backup) { return getJournalDir(testDir) + directoryNameSuffix(index, backup); } /** * @return the bindingsDir */ - protected String getBindingsDir() - { + protected String getBindingsDir() { return getBindingsDir(getTestDir()); } /** * @return the bindingsDir */ - protected static String getBindingsDir(final String testDir1) - { + protected static String getBindingsDir(final String testDir1) { return testDir1 + "/bindings"; } /** * @return the bindingsDir */ - protected String getBindingsDir(final int index, final boolean backup) - { + protected String getBindingsDir(final int index, final boolean backup) { return getBindingsDir(getTestDir(), index, backup); } - public static String getBindingsDir(final String testDir, final int index, final boolean backup) - { + public static String getBindingsDir(final String testDir, final int index, final boolean backup) { return getBindingsDir(testDir) + directoryNameSuffix(index, backup); } /** * @return the pageDir */ - protected String getPageDir() - { + protected String getPageDir() { return getPageDir(getTestDir()); } - protected File getPageDirFile() - { + protected File getPageDirFile() { return new File(getPageDir()); } @@ -997,49 +846,41 @@ public abstract class ActiveMQTestBase extends Assert /** * @return the pageDir */ - protected static String getPageDir(final String testDir1) - { + protected static String getPageDir(final String testDir1) { return testDir1 + "/page"; } - protected String getPageDir(final int index, final boolean backup) - { + protected String getPageDir(final int index, final boolean backup) { return getPageDir(getTestDir(), index, backup); } - public static String getPageDir(final String testDir, final int index, final boolean backup) - { + public static String getPageDir(final String testDir, final int index, final boolean backup) { return getPageDir(testDir) + directoryNameSuffix(index, backup); } /** * @return the largeMessagesDir */ - protected String getLargeMessagesDir() - { + protected String getLargeMessagesDir() { return getLargeMessagesDir(getTestDir()); } /** * @return the largeMessagesDir */ - protected static String getLargeMessagesDir(final String testDir1) - { + protected static String getLargeMessagesDir(final String testDir1) { return testDir1 + "/large-msg"; } - protected String getLargeMessagesDir(final int index, final boolean backup) - { + protected String getLargeMessagesDir(final int index, final boolean backup) { return getLargeMessagesDir(getTestDir(), index, backup); } - public static String getLargeMessagesDir(final String testDir, final int index, final boolean backup) - { + public static String getLargeMessagesDir(final String testDir, final int index, final boolean backup) { return getLargeMessagesDir(testDir) + directoryNameSuffix(index, backup); } - private static String directoryNameSuffix(int index, boolean backup) - { + private static String directoryNameSuffix(int index, boolean backup) { if (index == -1) return ""; return index + "-" + (backup ? "B" : "L"); @@ -1048,104 +889,85 @@ public abstract class ActiveMQTestBase extends Assert /** * @return the clientLargeMessagesDir */ - protected String getClientLargeMessagesDir() - { + protected String getClientLargeMessagesDir() { return getClientLargeMessagesDir(getTestDir()); } /** * @return the clientLargeMessagesDir */ - protected String getClientLargeMessagesDir(final String testDir1) - { + protected String getClientLargeMessagesDir(final String testDir1) { return testDir1 + "/client-large-msg"; } /** * @return the temporaryDir */ - protected final String getTemporaryDir() - { + protected final String getTemporaryDir() { return getTemporaryDir(getTestDir()); } /** * @return the temporaryDir */ - protected String getTemporaryDir(final String testDir1) - { + protected String getTemporaryDir(final String testDir1) { return testDir1 + "/temp"; } - protected static void expectActiveMQException(final String message, final ActiveMQExceptionType errorCode, final ActiveMQAction action) - { - try - { + protected static void expectActiveMQException(final String message, + final ActiveMQExceptionType errorCode, + final ActiveMQAction action) { + try { action.run(); Assert.fail(message); } - catch (Exception e) - { + catch (Exception e) { Assert.assertTrue(e instanceof ActiveMQException); Assert.assertEquals(errorCode, ((ActiveMQException) e).getType()); } } - protected static void expectActiveMQException(final ActiveMQExceptionType errorCode, final ActiveMQAction action) - { - expectActiveMQException("must throw an ActiveMQException with the expected errorCode: " + errorCode, - errorCode, - action); + protected static void expectActiveMQException(final ActiveMQExceptionType errorCode, final ActiveMQAction action) { + expectActiveMQException("must throw an ActiveMQException with the expected errorCode: " + errorCode, errorCode, action); } - protected static void expectXAException(final int errorCode, final ActiveMQAction action) - { - try - { + protected static void expectXAException(final int errorCode, final ActiveMQAction action) { + try { action.run(); Assert.fail("must throw a XAException with the expected errorCode: " + errorCode); } - catch (Exception e) - { + catch (Exception e) { Assert.assertTrue(e instanceof XAException); Assert.assertEquals(errorCode, ((XAException) e).errorCode); } } - public static byte getSamplebyte(final long position) - { + public static byte getSamplebyte(final long position) { return (byte) ('a' + position % ('z' - 'a' + 1)); } // Creates a Fake LargeStream without using a real file - public static InputStream createFakeLargeStream(final long size) throws Exception - { - return new InputStream() - { + public static InputStream createFakeLargeStream(final long size) throws Exception { + return new InputStream() { private long count; private boolean closed = false; @Override - public void close() throws IOException - { + public void close() throws IOException { super.close(); closed = true; } @Override - public int read() throws IOException - { - if (closed) - { + public int read() throws IOException { + if (closed) { throw new IOException("Stream was closed"); } - if (count++ < size) - { + if (count++ < size) { return getSamplebyte(count - 1); } - else - { + else { return -1; } } @@ -1157,12 +979,10 @@ public abstract class ActiveMQTestBase extends Assert * It validates a Bean (POJO) using simple setters and getters with random values. * You can pass a list of properties to be ignored, as some properties will have a pre-defined domain (not being possible to use random-values on them) */ - protected void validateGettersAndSetters(final Object pojo, final String... ignoredProperties) throws Exception - { + protected void validateGettersAndSetters(final Object pojo, final String... ignoredProperties) throws Exception { HashSet ignoreSet = new HashSet(); - for (String ignore : ignoredProperties) - { + for (String ignore : ignoredProperties) { ignoreSet.add(ignore); } @@ -1170,44 +990,35 @@ public abstract class ActiveMQTestBase extends Assert PropertyDescriptor[] properties = info.getPropertyDescriptors(); - for (PropertyDescriptor prop : properties) - { + for (PropertyDescriptor prop : properties) { Object value; - if (prop.getPropertyType() == String.class) - { + if (prop.getPropertyType() == String.class) { value = RandomUtil.randomString(); } - else if (prop.getPropertyType() == Integer.class || prop.getPropertyType() == Integer.TYPE) - { + else if (prop.getPropertyType() == Integer.class || prop.getPropertyType() == Integer.TYPE) { value = RandomUtil.randomInt(); } - else if (prop.getPropertyType() == Long.class || prop.getPropertyType() == Long.TYPE) - { + else if (prop.getPropertyType() == Long.class || prop.getPropertyType() == Long.TYPE) { value = RandomUtil.randomLong(); } - else if (prop.getPropertyType() == Boolean.class || prop.getPropertyType() == Boolean.TYPE) - { + else if (prop.getPropertyType() == Boolean.class || prop.getPropertyType() == Boolean.TYPE) { value = RandomUtil.randomBoolean(); } - else if (prop.getPropertyType() == Double.class || prop.getPropertyType() == Double.TYPE) - { + else if (prop.getPropertyType() == Double.class || prop.getPropertyType() == Double.TYPE) { value = RandomUtil.randomDouble(); } - else - { + else { System.out.println("Can't validate property of type " + prop.getPropertyType() + " on " + prop.getName()); value = null; } - if (value != null && prop.getWriteMethod() != null && prop.getReadMethod() == null) - { + if (value != null && prop.getWriteMethod() != null && prop.getReadMethod() == null) { System.out.println("WriteOnly property " + prop.getName() + " on " + pojo.getClass()); } else if (value != null & prop.getWriteMethod() != null && - prop.getReadMethod() != null && - !ignoreSet.contains(prop.getName())) - { + prop.getReadMethod() != null && + !ignoreSet.contains(prop.getName())) { System.out.println("Validating " + prop.getName() + " type = " + prop.getPropertyType()); prop.getWriteMethod().invoke(pojo, value); @@ -1220,41 +1031,39 @@ public abstract class ActiveMQTestBase extends Assert * @param queue * @throws InterruptedException */ - protected void waitForNotPaging(Queue queue) throws InterruptedException - { + protected void waitForNotPaging(Queue queue) throws InterruptedException { waitForNotPaging(queue.getPageSubscription().getPagingStore()); } - protected void waitForNotPaging(PagingStore store) throws InterruptedException - { + protected void waitForNotPaging(PagingStore store) throws InterruptedException { long timeout = System.currentTimeMillis() + 10000; - while (timeout > System.currentTimeMillis() && store.isPaging()) - { + while (timeout > System.currentTimeMillis() && store.isPaging()) { Thread.sleep(100); } assertFalse(store.isPaging()); } - protected Topology waitForTopology(final ActiveMQServer server, final int nodes) throws Exception - { + protected Topology waitForTopology(final ActiveMQServer server, final int nodes) throws Exception { return waitForTopology(server, nodes, -1, WAIT_TIMEOUT); } - protected Topology waitForTopology(final ActiveMQServer server, final int nodes, final int backups) throws Exception - { + protected Topology waitForTopology(final ActiveMQServer server, + final int nodes, + final int backups) throws Exception { return waitForTopology(server, nodes, backups, WAIT_TIMEOUT); } - protected Topology waitForTopology(final ActiveMQServer server, final int liveNodes, final int backupNodes, final long timeout) throws Exception - { + protected Topology waitForTopology(final ActiveMQServer server, + final int liveNodes, + final int backupNodes, + final long timeout) throws Exception { ActiveMQServerLogger.LOGGER.debug("waiting for " + liveNodes + " on the topology for server = " + server); long start = System.currentTimeMillis(); Set ccs = server.getClusterManager().getClusterConnections(); - if (ccs.size() != 1) - { + if (ccs.size() != 1) { throw new IllegalStateException("You need a single cluster connection on this version of waitForTopology on ServiceTestBase"); } @@ -1264,32 +1073,25 @@ public abstract class ActiveMQTestBase extends Assert int backupNodesCount = 0; - - do - { + do { liveNodesCount = 0; backupNodesCount = 0; - for (TopologyMemberImpl member : topology.getMembers()) - { - if (member.getLive() != null) - { + for (TopologyMemberImpl member : topology.getMembers()) { + if (member.getLive() != null) { liveNodesCount++; } - if (member.getBackup() != null) - { + if (member.getBackup() != null) { backupNodesCount++; } } - if ((liveNodes == -1 || liveNodes == liveNodesCount) && (backupNodes == -1 || backupNodes == backupNodesCount)) - { + if ((liveNodes == -1 || liveNodes == liveNodesCount) && (backupNodes == -1 || backupNodes == backupNodesCount)) { return topology; } Thread.sleep(10); - } - while (System.currentTimeMillis() - start < timeout); + } while (System.currentTimeMillis() - start < timeout); String msg = "Timed out waiting for cluster topology of live=" + liveNodes + ",backup=" + backupNodes + " (received live=" + liveNodesCount + ", backup=" + backupNodesCount + @@ -1302,28 +1104,25 @@ public abstract class ActiveMQTestBase extends Assert throw new Exception(msg); } - - protected void waitForTopology(final ActiveMQServer server, String clusterConnectionName, final int nodes, final long timeout) throws Exception - { + protected void waitForTopology(final ActiveMQServer server, + String clusterConnectionName, + final int nodes, + final long timeout) throws Exception { ActiveMQServerLogger.LOGGER.debug("waiting for " + nodes + " on the topology for server = " + server); long start = System.currentTimeMillis(); ClusterConnection clusterConnection = server.getClusterManager().getClusterConnection(clusterConnectionName); - Topology topology = clusterConnection.getTopology(); - do - { - if (nodes == topology.getMembers().size()) - { + do { + if (nodes == topology.getMembers().size()) { return; } Thread.sleep(10); - } - while (System.currentTimeMillis() - start < timeout); + } while (System.currentTimeMillis() - start < timeout); String msg = "Timed out waiting for cluster topology of " + nodes + " (received " + @@ -1337,89 +1136,71 @@ public abstract class ActiveMQTestBase extends Assert throw new Exception(msg); } - protected static final void waitForComponent(final ActiveMQComponent component, final long seconds) throws InterruptedException - { + protected static final void waitForComponent(final ActiveMQComponent component, + final long seconds) throws InterruptedException { long time = System.currentTimeMillis(); long toWait = seconds * 1000; - while (!component.isStarted()) - { + while (!component.isStarted()) { Thread.sleep(50); - if (System.currentTimeMillis() > (time + toWait)) - { + if (System.currentTimeMillis() > (time + toWait)) { fail("component did not start within timeout of " + seconds); } } } - protected static final Map generateParams(final int node, final boolean netty) - { + protected static final Map generateParams(final int node, final boolean netty) { Map params = new HashMap(); - if (netty) - { - params.put(org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.PORT_PROP_NAME, - org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.DEFAULT_PORT + node); + if (netty) { + params.put(org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.PORT_PROP_NAME, org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.DEFAULT_PORT + node); } - else - { + else { params.put(org.apache.activemq.artemis.core.remoting.impl.invm.TransportConstants.SERVER_ID_PROP_NAME, node); } return params; } - protected static final TransportConfiguration getNettyAcceptorTransportConfiguration(final boolean live) - { - if (live) - { + protected static final TransportConfiguration getNettyAcceptorTransportConfiguration(final boolean live) { + if (live) { return new TransportConfiguration(NETTY_ACCEPTOR_FACTORY); } Map server1Params = new HashMap(); - server1Params.put(org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.PORT_PROP_NAME, - org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.DEFAULT_PORT + 1); + server1Params.put(org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.PORT_PROP_NAME, org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.DEFAULT_PORT + 1); return new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, server1Params); } - protected static final TransportConfiguration getNettyConnectorTransportConfiguration(final boolean live) - { - if (live) - { + protected static final TransportConfiguration getNettyConnectorTransportConfiguration(final boolean live) { + if (live) { return new TransportConfiguration(NETTY_CONNECTOR_FACTORY); } Map server1Params = new HashMap(); - server1Params.put(org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.PORT_PROP_NAME, - org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.DEFAULT_PORT + 1); + server1Params.put(org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.PORT_PROP_NAME, org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.DEFAULT_PORT + 1); return new TransportConfiguration(NETTY_CONNECTOR_FACTORY, server1Params); } - protected static final TransportConfiguration createTransportConfiguration(boolean netty, boolean acceptor, - Map params) - { + protected static final TransportConfiguration createTransportConfiguration(boolean netty, + boolean acceptor, + Map params) { String className; - if (netty) - { - if (acceptor) - { + if (netty) { + if (acceptor) { className = NETTY_ACCEPTOR_FACTORY; } - else - { + else { className = NETTY_CONNECTOR_FACTORY; } } - else - { - if (acceptor) - { + else { + if (acceptor) { className = INVM_ACCEPTOR_FACTORY; } - else - { + else { className = INVM_CONNECTOR_FACTORY; } } @@ -1428,44 +1209,36 @@ public abstract class ActiveMQTestBase extends Assert return new TransportConfiguration(className, params); } - - protected void waitForServerToStart(ActiveMQServer server) throws InterruptedException - { + protected void waitForServerToStart(ActiveMQServer server) throws InterruptedException { if (server == null) return; final long wait = 5000; long timetowait = System.currentTimeMillis() + wait; - while (!server.isStarted() && System.currentTimeMillis() < timetowait) - { + while (!server.isStarted() && System.currentTimeMillis() < timetowait) { Thread.sleep(50); } - if (!server.isStarted()) - { + if (!server.isStarted()) { log.info(threadDump("Server didn't start")); fail("server didn't start: " + server); } - if (!server.getHAPolicy().isBackup()) - { + if (!server.getHAPolicy().isBackup()) { if (!server.waitForActivation(wait, TimeUnit.MILLISECONDS)) fail("Server didn't initialize: " + server); } } - protected void waitForServerToStop(ActiveMQServer server) throws InterruptedException - { + protected void waitForServerToStop(ActiveMQServer server) throws InterruptedException { if (server == null) return; final long wait = 5000; long timetowait = System.currentTimeMillis() + wait; - while (server.isStarted() && System.currentTimeMillis() < timetowait) - { + while (server.isStarted() && System.currentTimeMillis() < timetowait) { Thread.sleep(50); } - if (server.isStarted()) - { + if (server.isStarted()) { log.info(threadDump("Server didn't start")); fail("server didnt start: " + server); } @@ -1474,8 +1247,7 @@ public abstract class ActiveMQTestBase extends Assert /** * @param backup */ - public static final void waitForRemoteBackupSynchronization(final ActiveMQServer backup) - { + public static final void waitForRemoteBackupSynchronization(final ActiveMQServer backup) { waitForRemoteBackup(null, 10, true, backup); } @@ -1485,172 +1257,134 @@ public abstract class ActiveMQTestBase extends Assert * @param waitForSync * @param backup */ - public static final void waitForRemoteBackup(ClientSessionFactory sessionFactoryP, int seconds, - boolean waitForSync, final ActiveMQServer backup) - { - ClientSessionFactoryInternal sessionFactory = (ClientSessionFactoryInternal)sessionFactoryP; + public static final void waitForRemoteBackup(ClientSessionFactory sessionFactoryP, + int seconds, + boolean waitForSync, + final ActiveMQServer backup) { + ClientSessionFactoryInternal sessionFactory = (ClientSessionFactoryInternal) sessionFactoryP; final ActiveMQServerImpl actualServer = (ActiveMQServerImpl) backup; final long toWait = seconds * 1000; final long time = System.currentTimeMillis(); int loop = 0; - while (true) - { + while (true) { Activation activation = actualServer.getActivation(); boolean isReplicated = !backup.getHAPolicy().isSharedStore(); boolean isRemoteUpToDate = true; - if (isReplicated) - { - if (activation instanceof SharedNothingBackupActivation) - { + if (isReplicated) { + if (activation instanceof SharedNothingBackupActivation) { isRemoteUpToDate = ((SharedNothingBackupActivation) activation).isRemoteBackupUpToDate(); } - else - { + else { //we may have already failed over and changed the Activation - if (actualServer.isStarted()) - { + if (actualServer.isStarted()) { //let it fail a few time to have time to start stopping in the case of waiting to failback isRemoteUpToDate = loop++ > 10; } //we could be waiting to failback or restart if the server is stopping - else - { + else { isRemoteUpToDate = false; } } } if ((sessionFactory == null || sessionFactory.getBackupConnector() != null) && - (isRemoteUpToDate || !waitForSync) && - (!waitForSync || actualServer.getBackupManager() != null && actualServer.getBackupManager().isBackupAnnounced())) - { + (isRemoteUpToDate || !waitForSync) && + (!waitForSync || actualServer.getBackupManager() != null && actualServer.getBackupManager().isBackupAnnounced())) { break; } - if (System.currentTimeMillis() > (time + toWait)) - { + if (System.currentTimeMillis() > (time + toWait)) { fail("backup started? (" + actualServer.isStarted() + "). Finished synchronizing (" + - (activation) + "). SessionFactory!=null ? " + (sessionFactory != null) + + (activation) + "). SessionFactory!=null ? " + (sessionFactory != null) + " || sessionFactory.getBackupConnector()==" + (sessionFactory != null ? sessionFactory.getBackupConnector() : "not-applicable")); } - try - { + try { Thread.sleep(100); } - catch (InterruptedException e) - { + catch (InterruptedException e) { fail(e.getMessage()); } } } - public static final void waitForRemoteBackup(ClientSessionFactory sessionFactory, int seconds) - { + public static final void waitForRemoteBackup(ClientSessionFactory sessionFactory, int seconds) { ClientSessionFactoryInternal factoryInternal = (ClientSessionFactoryInternal) sessionFactory; final long toWait = seconds * 1000; final long time = System.currentTimeMillis(); - while (true) - { - if (factoryInternal.getBackupConnector() != null) - { + while (true) { + if (factoryInternal.getBackupConnector() != null) { break; } - if (System.currentTimeMillis() > (time + toWait)) - { + if (System.currentTimeMillis() > (time + toWait)) { fail("Backup wasn't located"); } - try - { + try { Thread.sleep(100); } - catch (InterruptedException e) - { + catch (InterruptedException e) { fail(e.getMessage()); } } } protected final ActiveMQServer createServer(final boolean realFiles, - final Configuration configuration, - final long pageSize, - final long maxAddressSize, - final Map settings) - { + final Configuration configuration, + final long pageSize, + final long maxAddressSize, + final Map settings) { ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(configuration, realFiles)); - if (settings != null) - { - for (Map.Entry setting : settings.entrySet()) - { + if (settings != null) { + for (Map.Entry setting : settings.entrySet()) { server.getAddressSettingsRepository().addMatch(setting.getKey(), setting.getValue()); } } - AddressSettings defaultSetting = new AddressSettings() - .setPageSizeBytes(pageSize) - .setMaxSizeBytes(maxAddressSize) - .setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE); + AddressSettings defaultSetting = new AddressSettings().setPageSizeBytes(pageSize).setMaxSizeBytes(maxAddressSize).setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE); server.getAddressSettingsRepository().addMatch("#", defaultSetting); return server; } - protected final ActiveMQServer createServer(final boolean realFiles) throws Exception - { + protected final ActiveMQServer createServer(final boolean realFiles) throws Exception { return createServer(realFiles, false); } - protected final ActiveMQServer createServer(final boolean realFiles, final boolean netty) throws Exception - { + protected final ActiveMQServer createServer(final boolean realFiles, final boolean netty) throws Exception { return createServer(realFiles, createDefaultConfig(netty), AddressSettings.DEFAULT_PAGE_SIZE, AddressSettings.DEFAULT_MAX_SIZE_BYTES, new HashMap()); } - protected ActiveMQServer createServer(final boolean realFiles, final Configuration configuration) - { + protected ActiveMQServer createServer(final boolean realFiles, final Configuration configuration) { return createServer(realFiles, configuration, AddressSettings.DEFAULT_PAGE_SIZE, AddressSettings.DEFAULT_MAX_SIZE_BYTES, new HashMap()); } - protected final ActiveMQServer createServer(final Configuration configuration) - { + protected final ActiveMQServer createServer(final Configuration configuration) { return createServer(configuration.isPersistenceEnabled(), configuration, AddressSettings.DEFAULT_PAGE_SIZE, AddressSettings.DEFAULT_MAX_SIZE_BYTES, new HashMap()); } protected ActiveMQServer createInVMFailoverServer(final boolean realFiles, - final Configuration configuration, - final NodeManager nodeManager, - final int id) - { - return createInVMFailoverServer(realFiles, - configuration, - -1, - -1, - new HashMap(), - nodeManager, - id); + final Configuration configuration, + final NodeManager nodeManager, + final int id) { + return createInVMFailoverServer(realFiles, configuration, -1, -1, new HashMap(), nodeManager, id); } protected ActiveMQServer createInVMFailoverServer(final boolean realFiles, - final Configuration configuration, - final int pageSize, - final int maxAddressSize, - final Map settings, - NodeManager nodeManager, - final int id) - { + final Configuration configuration, + final int pageSize, + final int maxAddressSize, + final Map settings, + NodeManager nodeManager, + final int id) { ActiveMQServer server; ActiveMQSecurityManager securityManager = new ActiveMQSecurityManagerImpl(); configuration.setPersistenceEnabled(realFiles); - server = addServer(new InVMNodeManagerServer(configuration, - ManagementFactory.getPlatformMBeanServer(), - securityManager, - nodeManager)); + server = addServer(new InVMNodeManagerServer(configuration, ManagementFactory.getPlatformMBeanServer(), securityManager, nodeManager)); - try - { + try { server.setIdentity("Server " + id); - for (Map.Entry setting : settings.entrySet()) - { + for (Map.Entry setting : settings.entrySet()) { server.getAddressSettingsRepository().addMatch(setting.getKey(), setting.getValue()); } @@ -1662,52 +1396,36 @@ public abstract class ActiveMQTestBase extends Assert return server; } - finally - { + finally { addServer(server); } } protected ActiveMQServer createColocatedInVMFailoverServer(final boolean realFiles, - final Configuration configuration, - NodeManager liveNodeManager, - NodeManager backupNodeManager, - final int id) - { - return createColocatedInVMFailoverServer(realFiles, - configuration, - -1, - -1, - new HashMap(), - liveNodeManager, - backupNodeManager, - id); + final Configuration configuration, + NodeManager liveNodeManager, + NodeManager backupNodeManager, + final int id) { + return createColocatedInVMFailoverServer(realFiles, configuration, -1, -1, new HashMap(), liveNodeManager, backupNodeManager, id); } protected ActiveMQServer createColocatedInVMFailoverServer(final boolean realFiles, - final Configuration configuration, - final int pageSize, - final int maxAddressSize, - final Map settings, - NodeManager liveNodeManager, - NodeManager backupNodeManager, - final int id) - { + final Configuration configuration, + final int pageSize, + final int maxAddressSize, + final Map settings, + NodeManager liveNodeManager, + NodeManager backupNodeManager, + final int id) { ActiveMQServer server; ActiveMQSecurityManager securityManager = new ActiveMQSecurityManagerImpl(); configuration.setPersistenceEnabled(realFiles); - server = new ColocatedActiveMQServer(configuration, - ManagementFactory.getPlatformMBeanServer(), - securityManager, - liveNodeManager, - backupNodeManager); + server = new ColocatedActiveMQServer(configuration, ManagementFactory.getPlatformMBeanServer(), securityManager, liveNodeManager, backupNodeManager); - try - { + try { server.setIdentity("Server " + id); - for (Map.Entry setting : settings.entrySet()) - { + for (Map.Entry setting : settings.entrySet()) { server.getAddressSettingsRepository().addMatch(setting.getKey(), setting.getValue()); } @@ -1719,66 +1437,52 @@ public abstract class ActiveMQTestBase extends Assert return server; } - finally - { + finally { addServer(server); } } protected ActiveMQServer createClusteredServerWithParams(final boolean isNetty, - final int index, - final boolean realFiles, - final Map params) throws Exception - { + final int index, + final boolean realFiles, + final Map params) throws Exception { String acceptor = isNetty ? NETTY_ACCEPTOR_FACTORY : INVM_ACCEPTOR_FACTORY; - return createServer(realFiles, createDefaultConfig(index, params, acceptor), -1, -1, - new HashMap()); + return createServer(realFiles, createDefaultConfig(index, params, acceptor), -1, -1, new HashMap()); } protected ActiveMQServer createClusteredServerWithParams(final boolean isNetty, - final int index, - final boolean realFiles, - final int pageSize, - final int maxAddressSize, - final Map params) throws Exception - { - return createServer(realFiles, createDefaultConfig(index, params, (isNetty ? NETTY_ACCEPTOR_FACTORY : INVM_ACCEPTOR_FACTORY)), - pageSize, - maxAddressSize, - new HashMap()); + final int index, + final boolean realFiles, + final int pageSize, + final int maxAddressSize, + final Map params) throws Exception { + return createServer(realFiles, createDefaultConfig(index, params, (isNetty ? NETTY_ACCEPTOR_FACTORY : INVM_ACCEPTOR_FACTORY)), pageSize, maxAddressSize, new HashMap()); } - protected ServerLocator createFactory(final boolean isNetty) throws Exception - { - if (isNetty) - { + protected ServerLocator createFactory(final boolean isNetty) throws Exception { + if (isNetty) { return createNettyNonHALocator(); } - else - { + else { return createInVMNonHALocator(); } } - protected void createQueue(final String address, final String queue) throws Exception - { + protected void createQueue(final String address, final String queue) throws Exception { ServerLocator locator = createInVMNonHALocator(); ClientSessionFactory sf = locator.createSessionFactory(); ClientSession session = sf.createSession(); - try - { + try { session.createQueue(address, queue); } - finally - { + finally { session.close(); closeSessionFactory(sf); closeServerLocator(locator); } } - protected final ServerLocator createInVMLocator(final int serverID) - { + protected final ServerLocator createInVMLocator(final int serverID) { TransportConfiguration tnspConfig = createInVMTransportConnectorConfig(serverID, UUIDGenerator.getInstance().generateStringUUID()); ServerLocator locator = ActiveMQClient.createServerLocatorWithHA(tnspConfig); @@ -1789,12 +1493,10 @@ public abstract class ActiveMQTestBase extends Assert * @param serverID * @return */ - protected final TransportConfiguration createInVMTransportConnectorConfig(final int serverID, String name1) - { + protected final TransportConfiguration createInVMTransportConnectorConfig(final int serverID, String name1) { Map server1Params = new HashMap(); - if (serverID != 0) - { + if (serverID != 0) { server1Params.put(TransportConstants.SERVER_ID_PROP_NAME, serverID); } @@ -1802,8 +1504,7 @@ public abstract class ActiveMQTestBase extends Assert return tnspConfig; } - public String getTextMessage(final ClientMessage m) - { + public String getTextMessage(final ClientMessage m) { m.getBodyBuffer().resetReaderIndex(); return m.getBodyBuffer().readString(); } @@ -1811,8 +1512,7 @@ public abstract class ActiveMQTestBase extends Assert protected ClientMessage createBytesMessage(final ClientSession session, final byte type, final byte[] b, - final boolean durable) - { + final boolean durable) { ClientMessage message = session.createMessage(type, durable, 0, System.currentTimeMillis(), (byte) 1); message.getBodyBuffer().writeBytes(b); return message; @@ -1823,8 +1523,7 @@ public abstract class ActiveMQTestBase extends Assert * @param message * @throws Exception */ - protected void setBody(final int i, final ClientMessage message) - { + protected void setBody(final int i, final ClientMessage message) { message.getBodyBuffer().writeString("message" + i); } @@ -1832,8 +1531,7 @@ public abstract class ActiveMQTestBase extends Assert * @param i * @param message */ - protected void assertMessageBody(final int i, final ClientMessage message) - { + protected void assertMessageBody(final int i, final ClientMessage message) { Assert.assertEquals(message.toString(), "message" + i, message.getBodyBuffer().readString()); } @@ -1845,16 +1543,17 @@ public abstract class ActiveMQTestBase extends Assert * @param numMessages * @throws Exception */ - public final void sendMessages(ClientSession session, ClientProducer producer, int numMessages) throws ActiveMQException - { - for (int i = 0; i < numMessages; i++) - { + public final void sendMessages(ClientSession session, + ClientProducer producer, + int numMessages) throws ActiveMQException { + for (int i = 0; i < numMessages; i++) { producer.send(createMessage(session, i, true)); } } - protected final ClientMessage createMessage(ClientSession session, int counter, boolean durable) throws ActiveMQException - { + protected final ClientMessage createMessage(ClientSession session, + int counter, + boolean durable) throws ActiveMQException { ClientMessage message = session.createMessage(durable); setBody(counter, message); message.putIntProperty("counter", counter); @@ -1862,10 +1561,11 @@ public abstract class ActiveMQTestBase extends Assert return message; } - protected final void receiveMessages(ClientConsumer consumer, final int start, final int msgCount, final boolean ack) throws ActiveMQException - { - for (int i = start; i < msgCount; i++) - { + protected final void receiveMessages(ClientConsumer consumer, + final int start, + final int msgCount, + final boolean ack) throws ActiveMQException { + for (int i = start; i < msgCount; i++) { ClientMessage message = consumer.receive(1000); Assert.assertNotNull("Expecting a message " + i, message); // sendCallNumber is just a debugging measure. @@ -1873,8 +1573,7 @@ public abstract class ActiveMQTestBase extends Assert if (prop == null) prop = Integer.valueOf(-1); final int actual = message.getIntProperty("counter").intValue(); - Assert.assertEquals("expected=" + i + ". Got: property['counter']=" + actual + " sendNumber=" + prop, i, - actual); + Assert.assertEquals("expected=" + i + ". Got: property['counter']=" + actual + " sendNumber=" + prop, i, actual); assertMessageBody(i, message); if (ack) message.acknowledge(); @@ -1889,21 +1588,12 @@ public abstract class ActiveMQTestBase extends Assert * @return * @throws Exception */ - protected Pair, List> loadMessageJournal(Configuration config) throws Exception - { + protected Pair, List> loadMessageJournal(Configuration config) throws Exception { JournalImpl messagesJournal = null; - try - { + try { SequentialFileFactory messagesFF = new NIOSequentialFileFactory(new File(getJournalDir()), null, 1); - messagesJournal = new JournalImpl(config.getJournalFileSize(), - config.getJournalMinFiles(), - 0, - 0, - messagesFF, - "activemq-data", - "amq", - 1); + messagesJournal = new JournalImpl(config.getJournalFileSize(), config.getJournalMinFiles(), 0, 0, messagesFF, "activemq-data", "amq", 1); final List committedRecords = new LinkedList(); final List preparedTransactions = new LinkedList(); @@ -1913,17 +1603,13 @@ public abstract class ActiveMQTestBase extends Assert return new Pair, List>(committedRecords, preparedTransactions); } - finally - { - try - { - if (messagesJournal != null) - { + finally { + try { + if (messagesJournal != null) { messagesJournal.stop(); } } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } @@ -1937,23 +1623,14 @@ public abstract class ActiveMQTestBase extends Assert * @return * @throws Exception */ - protected HashMap countJournal(Configuration config) throws Exception - { + protected HashMap countJournal(Configuration config) throws Exception { final HashMap recordsType = new HashMap(); SequentialFileFactory messagesFF = new NIOSequentialFileFactory(config.getJournalLocation(), null, 1); - JournalImpl messagesJournal = new JournalImpl(config.getJournalFileSize(), - config.getJournalMinFiles(), - 0, - 0, - messagesFF, - "activemq-data", - "amq", - 1); + JournalImpl messagesJournal = new JournalImpl(config.getJournalFileSize(), config.getJournalMinFiles(), 0, 0, messagesFF, "activemq-data", "amq", 1); List filesToRead = messagesJournal.orderFiles(); - for (JournalFile file : filesToRead) - { + for (JournalFile file : filesToRead) { JournalImpl.readJournalFile(messagesFF, file, new RecordTypeCounter(recordsType)); } return recordsType; @@ -1966,8 +1643,7 @@ public abstract class ActiveMQTestBase extends Assert * @return * @throws Exception */ - protected HashMap countJournalLivingRecords(Configuration config) throws Exception - { + protected HashMap countJournalLivingRecords(Configuration config) throws Exception { return internalCountJournalLivingRecords(config, true); } @@ -1979,52 +1655,32 @@ public abstract class ActiveMQTestBase extends Assert * @return * @throws Exception */ - protected HashMap internalCountJournalLivingRecords(Configuration config, boolean messageJournal) throws Exception - { + protected HashMap internalCountJournalLivingRecords(Configuration config, + boolean messageJournal) throws Exception { final HashMap recordsType = new HashMap(); SequentialFileFactory ff; JournalImpl journal; - if (messageJournal) - { + if (messageJournal) { ff = new NIOSequentialFileFactory(config.getJournalLocation(), null, 1); - journal = new JournalImpl(config.getJournalFileSize(), - config.getJournalMinFiles(), - 0, - 0, - ff, - "activemq-data", - "amq", - 1); + journal = new JournalImpl(config.getJournalFileSize(), config.getJournalMinFiles(), 0, 0, ff, "activemq-data", "amq", 1); } - else - { + else { ff = new NIOSequentialFileFactory(config.getBindingsLocation(), null, 1); - journal = new JournalImpl(1024 * 1024, - 2, - config.getJournalCompactMinFiles(), - config.getJournalCompactPercentage(), - ff, - "activemq-bindings", - "bindings", - 1); + journal = new JournalImpl(1024 * 1024, 2, config.getJournalCompactMinFiles(), config.getJournalCompactPercentage(), ff, "activemq-bindings", "bindings", 1); } journal.start(); - final List committedRecords = new LinkedList(); final List preparedTransactions = new LinkedList(); - journal.load(committedRecords, preparedTransactions, null, false); - for (RecordInfo info : committedRecords) - { + for (RecordInfo info : committedRecords) { Integer ikey = new Integer(info.getUserRecordType()); AtomicInteger value = recordsType.get(ikey); - if (value == null) - { + if (value == null) { value = new AtomicInteger(); recordsType.put(ikey, value); } @@ -2036,76 +1692,62 @@ public abstract class ActiveMQTestBase extends Assert return recordsType; } - private static final class RecordTypeCounter implements JournalReaderCallback - { + private static final class RecordTypeCounter implements JournalReaderCallback { + private final HashMap recordsType; /** * @param recordsType */ - public RecordTypeCounter(HashMap recordsType) - { + public RecordTypeCounter(HashMap recordsType) { this.recordsType = recordsType; } - AtomicInteger getType(byte key) - { - if (key == 0) - { + AtomicInteger getType(byte key) { + if (key == 0) { System.out.println("huh?"); } Integer ikey = new Integer(key); AtomicInteger value = recordsType.get(ikey); - if (value == null) - { + if (value == null) { value = new AtomicInteger(); recordsType.put(ikey, value); } return value; } - public void onReadUpdateRecordTX(long transactionID, RecordInfo recordInfo) throws Exception - { + public void onReadUpdateRecordTX(long transactionID, RecordInfo recordInfo) throws Exception { getType(recordInfo.getUserRecordType()).incrementAndGet(); } - public void onReadUpdateRecord(RecordInfo recordInfo) throws Exception - { + public void onReadUpdateRecord(RecordInfo recordInfo) throws Exception { getType(recordInfo.getUserRecordType()).incrementAndGet(); } - public void onReadAddRecordTX(long transactionID, RecordInfo recordInfo) throws Exception - { + public void onReadAddRecordTX(long transactionID, RecordInfo recordInfo) throws Exception { getType(recordInfo.getUserRecordType()).incrementAndGet(); } - public void onReadAddRecord(RecordInfo recordInfo) throws Exception - { + public void onReadAddRecord(RecordInfo recordInfo) throws Exception { getType(recordInfo.getUserRecordType()).incrementAndGet(); } - public void onReadRollbackRecord(long transactionID) throws Exception - { + public void onReadRollbackRecord(long transactionID) throws Exception { } - public void onReadPrepareRecord(long transactionID, byte[] extraData, int numberOfRecords) throws Exception - { + public void onReadPrepareRecord(long transactionID, byte[] extraData, int numberOfRecords) throws Exception { } - public void onReadDeleteRecordTX(long transactionID, RecordInfo recordInfo) throws Exception - { + public void onReadDeleteRecordTX(long transactionID, RecordInfo recordInfo) throws Exception { } - public void onReadDeleteRecord(long recordID) throws Exception - { + public void onReadDeleteRecord(long recordID) throws Exception { } - public void onReadCommitRecord(long transactionID, int numberOfRecords) throws Exception - { + public void onReadCommitRecord(long transactionID, int numberOfRecords) throws Exception { } - public void markAsDataFile(JournalFile file0) - { + public void markAsDataFile(JournalFile file0) { } } @@ -2125,8 +1767,7 @@ public abstract class ActiveMQTestBase extends Assert final boolean local, final int expectedBindingCount, final int expectedConsumerCount, - long timeout) throws Exception - { + long timeout) throws Exception { final PostOffice po = server.getPostOffice(); long start = System.currentTimeMillis(); @@ -2135,18 +1776,15 @@ public abstract class ActiveMQTestBase extends Assert int totConsumers = 0; - do - { + do { bindingCount = 0; totConsumers = 0; Bindings bindings = po.getBindingsForAddress(new SimpleString(address)); - for (Binding binding : bindings.getBindings()) - { - if (binding.isConnected() && (binding instanceof LocalQueueBinding && local || binding instanceof RemoteQueueBinding && !local)) - { + for (Binding binding : bindings.getBindings()) { + if (binding.isConnected() && (binding instanceof LocalQueueBinding && local || binding instanceof RemoteQueueBinding && !local)) { QueueBinding qBinding = (QueueBinding) binding; bindingCount++; @@ -2155,14 +1793,12 @@ public abstract class ActiveMQTestBase extends Assert } } - if (bindingCount == expectedBindingCount && totConsumers == expectedConsumerCount) - { + if (bindingCount == expectedBindingCount && totConsumers == expectedConsumerCount) { return true; } Thread.sleep(10); - } - while (System.currentTimeMillis() - start < timeout); + } while (System.currentTimeMillis() - start < timeout); String msg = "Timed out waiting for bindings (bindingCount = " + bindingCount + " (expecting " + @@ -2183,22 +1819,17 @@ public abstract class ActiveMQTestBase extends Assert * Deleting a file on LargeDir is an asynchronous process. We need to keep looking for a while if * the file hasn't been deleted yet. */ - protected void validateNoFilesOnLargeDir(final String directory, final int expect) throws Exception - { + protected void validateNoFilesOnLargeDir(final String directory, final int expect) throws Exception { File largeMessagesFileDir = new File(directory); // Deleting the file is async... we keep looking for a period of the time until the file is really gone long timeout = System.currentTimeMillis() + 5000; - while (timeout > System.currentTimeMillis() && largeMessagesFileDir.listFiles().length != expect) - { + while (timeout > System.currentTimeMillis() && largeMessagesFileDir.listFiles().length != expect) { Thread.sleep(100); } - - if (expect != largeMessagesFileDir.listFiles().length) - { - for (File file : largeMessagesFileDir.listFiles()) - { + if (expect != largeMessagesFileDir.listFiles().length) { + for (File file : largeMessagesFileDir.listFiles()) { System.out.println("File " + file + " still on "); } } @@ -2210,47 +1841,38 @@ public abstract class ActiveMQTestBase extends Assert * Deleting a file on LargeDire is an asynchronous process. Wee need to keep looking for a while * if the file hasn't been deleted yet */ - protected void validateNoFilesOnLargeDir() throws Exception - { + protected void validateNoFilesOnLargeDir() throws Exception { validateNoFilesOnLargeDir(getLargeMessagesDir(), 0); } - public void printBindings(ActiveMQServer server, String address) throws Exception - { + public void printBindings(ActiveMQServer server, String address) throws Exception { PostOffice po = server.getPostOffice(); Bindings bindings = po.getBindingsForAddress(new SimpleString(address)); System.err.println("======================================================================="); System.err.println("Binding information for address = " + address + " for server " + server); - for (Binding binding : bindings.getBindings()) - { + for (Binding binding : bindings.getBindings()) { QueueBinding qBinding = (QueueBinding) binding; System.err.println("Binding = " + qBinding + ", queue=" + qBinding.getQueue()); } } - private void assertAllExecutorsFinished() throws InterruptedException - { - for (ExecutorService s : executorSet) - { + private void assertAllExecutorsFinished() throws InterruptedException { + for (ExecutorService s : executorSet) { Assert.assertTrue(s.awaitTermination(5, TimeUnit.SECONDS)); } } - private ArrayList checkCsfStopped() - { + private ArrayList checkCsfStopped() { long time = System.currentTimeMillis(); long waitUntil = time + 5000; - while (!ClientSessionFactoryImpl.CLOSE_RUNNABLES.isEmpty() && time < waitUntil) - { - try - { + while (!ClientSessionFactoryImpl.CLOSE_RUNNABLES.isEmpty() && time < waitUntil) { + try { Thread.sleep(50); } - catch (InterruptedException e) - { + catch (InterruptedException e) { //ignore } time = System.currentTimeMillis(); @@ -2258,12 +1880,9 @@ public abstract class ActiveMQTestBase extends Assert List closeRunnables = new ArrayList<>(ClientSessionFactoryImpl.CLOSE_RUNNABLES); ArrayList exceptions = new ArrayList<>(); - if (!closeRunnables.isEmpty()) - { - for (ClientSessionFactoryImpl.CloseRunnable closeRunnable : closeRunnables) - { - if (closeRunnable != null) - { + if (!closeRunnables.isEmpty()) { + for (ClientSessionFactoryImpl.CloseRunnable closeRunnable : closeRunnables) { + if (closeRunnable != null) { exceptions.add(closeRunnable.stop().createTrace); } } @@ -2272,12 +1891,9 @@ public abstract class ActiveMQTestBase extends Assert return exceptions; } - private void assertAllClientProducersAreClosed() - { - synchronized (clientProducers) - { - for (ClientProducer p : clientProducers) - { + private void assertAllClientProducersAreClosed() { + synchronized (clientProducers) { + for (ClientProducer p : clientProducers) { assertTrue(p + " should be closed", p.isClosed()); } clientProducers.clear(); @@ -2287,12 +1903,9 @@ public abstract class ActiveMQTestBase extends Assert /** * */ - private void closeAllOtherComponents() - { - synchronized (otherComponents) - { - for (ActiveMQComponent c : otherComponents) - { + private void closeAllOtherComponents() { + synchronized (otherComponents) { + for (ActiveMQComponent c : otherComponents) { stopComponent(c); } otherComponents.clear(); @@ -2303,28 +1916,23 @@ public abstract class ActiveMQTestBase extends Assert * @param buffer * @return */ - private boolean checkThread(StringBuffer buffer) - { + private boolean checkThread(StringBuffer buffer) { boolean failedThread = false; Map postThreads = Thread.getAllStackTraces(); - if (postThreads != null && previousThreads != null && postThreads.size() > previousThreads.size()) - { + if (postThreads != null && previousThreads != null && postThreads.size() > previousThreads.size()) { buffer.append("*********************************************************************************\n"); buffer.append("LEAKING THREADS\n"); - for (Thread aliveThread : postThreads.keySet()) - { - if (!isExpectedThread(aliveThread) && !previousThreads.containsKey(aliveThread)) - { + for (Thread aliveThread : postThreads.keySet()) { + if (!isExpectedThread(aliveThread) && !previousThreads.containsKey(aliveThread)) { failedThread = true; buffer.append("=============================================================================\n"); buffer.append("Thread " + aliveThread + " is still alive with the following stackTrace:\n"); StackTraceElement[] elements = postThreads.get(aliveThread); - for (StackTraceElement el : elements) - { + for (StackTraceElement el : elements) { buffer.append(el + "\n"); } } @@ -2342,54 +1950,42 @@ public abstract class ActiveMQTestBase extends Assert * @param thread * @return */ - private boolean isExpectedThread(Thread thread) - { + private boolean isExpectedThread(Thread thread) { final String threadName = thread.getName(); final ThreadGroup group = thread.getThreadGroup(); final boolean isSystemThread = group != null && "system".equals(group.getName()); final String javaVendor = System.getProperty("java.vendor"); - if (threadName.contains("SunPKCS11")) - { + if (threadName.contains("SunPKCS11")) { return true; } - else if (threadName.contains("Attach Listener")) - { + else if (threadName.contains("Attach Listener")) { return true; } - else if ((javaVendor.contains("IBM") || isSystemThread) && threadName.equals("process reaper")) - { + else if ((javaVendor.contains("IBM") || isSystemThread) && threadName.equals("process reaper")) { return true; } - else if (javaVendor.contains("IBM") && threadName.equals("MemoryPoolMXBean notification dispatcher")) - { + else if (javaVendor.contains("IBM") && threadName.equals("MemoryPoolMXBean notification dispatcher")) { return true; } - else if (threadName.contains("globalEventExecutor")) - { + else if (threadName.contains("globalEventExecutor")) { return true; } - else if (threadName.contains("threadDeathWatcher")) - { + else if (threadName.contains("threadDeathWatcher")) { return true; } - else if (threadName.contains("netty-threads")) - { + else if (threadName.contains("netty-threads")) { // This is ok as we use EventLoopGroup.shutdownGracefully() which will shutdown things with a bit of delay // if the EventLoop's are still busy. return true; } - else if (threadName.contains("threadDeathWatcher")) - { + else if (threadName.contains("threadDeathWatcher")) { //another netty thread return true; } - else - { - for (StackTraceElement element : thread.getStackTrace()) - { - if (element.getClassName().contains("org.jboss.byteman.agent.TransformListener")) - { + else { + for (StackTraceElement element : thread.getStackTrace()) { + if (element.getClassName().contains("org.jboss.byteman.agent.TransformListener")) { return true; } } @@ -2397,97 +1993,82 @@ public abstract class ActiveMQTestBase extends Assert } } - private void checkFilesUsage() - { - + private void checkFilesUsage() { long timeout = System.currentTimeMillis() + 15000; -// while (AsynchronousFileImpl.getTotalMaxIO() != 0 && System.currentTimeMillis() > timeout) -// { -// try -// { -// Thread.sleep(100); -// } -// catch (Exception ignored) -// { -// } -// } -// -// int invmSize = InVMRegistry.instance.size(); -// if (invmSize > 0) -// { -// InVMRegistry.instance.clear(); -// log.info(threadDump("Thread dump")); -// fail("invm registry still had acceptors registered"); -// } -// -// final int totalMaxIO = AsynchronousFileImpl.getTotalMaxIO(); -// if (totalMaxIO != 0) -// { -// AsynchronousFileImpl.resetMaxAIO(); -// Assert.fail("test did not close all its files " + totalMaxIO); -// } + // while (AsynchronousFileImpl.getTotalMaxIO() != 0 && System.currentTimeMillis() > timeout) + // { + // try + // { + // Thread.sleep(100); + // } + // catch (Exception ignored) + // { + // } + // } + // + // int invmSize = InVMRegistry.instance.size(); + // if (invmSize > 0) + // { + // InVMRegistry.instance.clear(); + // log.info(threadDump("Thread dump")); + // fail("invm registry still had acceptors registered"); + // } + // + // final int totalMaxIO = AsynchronousFileImpl.getTotalMaxIO(); + // if (totalMaxIO != 0) + // { + // AsynchronousFileImpl.resetMaxAIO(); + // Assert.fail("test did not close all its files " + totalMaxIO); + // } } - private void cleanupPools() - { + private void cleanupPools() { OperationContextImpl.clearContext(); // We shutdown the global pools to give a better isolation between tests - try - { + try { ServerLocatorImpl.clearThreadPools(); } - catch (Throwable e) - { + catch (Throwable e) { log.info(threadDump(e.getMessage())); System.err.println(threadDump(e.getMessage())); } - try - { + try { NettyConnector.clearThreadPools(); } - catch (Exception e) - { + catch (Exception e) { log.info(threadDump(e.getMessage())); System.err.println(threadDump(e.getMessage())); } } - protected static final void recreateDirectory(final String directory) - { + protected static final void recreateDirectory(final String directory) { File file = new File(directory); deleteDirectory(file); file.mkdirs(); } - protected static final boolean deleteDirectory(final File directory) - { - if (directory.isDirectory()) - { + protected static final boolean deleteDirectory(final File directory) { + if (directory.isDirectory()) { String[] files = directory.list(); int num = 5; int attempts = 0; - while (files == null && (attempts < num)) - { - try - { + while (files == null && (attempts < num)) { + try { Thread.sleep(100); } - catch (InterruptedException e) - { + catch (InterruptedException e) { } files = directory.list(); attempts++; } - for (String file : files) - { + for (String file : files) { File f = new File(directory, file); - if (!deleteDirectory(f)) - { + if (!deleteDirectory(f)) { log.warn("Failed to clean up file: " + f.getAbsolutePath()); } } @@ -2496,68 +2077,55 @@ public abstract class ActiveMQTestBase extends Assert return directory.delete(); } - protected static final void copyRecursive(final File from, final File to) throws Exception - { - if (from.isDirectory()) - { - if (!to.exists()) - { + protected static final void copyRecursive(final File from, final File to) throws Exception { + if (from.isDirectory()) { + if (!to.exists()) { to.mkdir(); } String[] subs = from.list(); - for (String sub : subs) - { + for (String sub : subs) { copyRecursive(new File(from, sub), new File(to, sub)); } } - else - { + else { InputStream in = null; OutputStream out = null; - try - { + try { in = new BufferedInputStream(new FileInputStream(from)); out = new BufferedOutputStream(new FileOutputStream(to)); int b; - while ((b = in.read()) != -1) - { + while ((b = in.read()) != -1) { out.write(b); } } - finally - { - if (in != null) - { + finally { + if (in != null) { in.close(); } - if (out != null) - { + if (out != null) { out.close(); } } } } - protected void assertRefListsIdenticalRefs(final List l1, final List l2) - { - if (l1.size() != l2.size()) - { + protected void assertRefListsIdenticalRefs(final List l1, final List l2) { + if (l1.size() != l2.size()) { Assert.fail("Lists different sizes: " + l1.size() + ", " + l2.size()); } Iterator iter1 = l1.iterator(); Iterator iter2 = l2.iterator(); - while (iter1.hasNext()) - { + while (iter1.hasNext()) { MessageReference o1 = iter1.next(); MessageReference o2 = iter2.next(); @@ -2565,8 +2133,7 @@ public abstract class ActiveMQTestBase extends Assert } } - protected ServerMessage generateMessage(final long id) - { + protected ServerMessage generateMessage(final long id) { ServerMessage message = new ServerMessageImpl(id, 1000); message.setMessageID(id); @@ -2578,42 +2145,31 @@ public abstract class ActiveMQTestBase extends Assert return message; } - protected MessageReference generateReference(final Queue queue, final long id) - { + protected MessageReference generateReference(final Queue queue, final long id) { ServerMessage message = generateMessage(id); return message.createReference(queue); } - protected int calculateRecordSize(final int size, final int alignment) - { + protected int calculateRecordSize(final int size, final int alignment) { return (size / alignment + (size % alignment != 0 ? 1 : 0)) * alignment; } - protected ClientMessage createTextMessage(final ClientSession session, final String s) - { + protected ClientMessage createTextMessage(final ClientSession session, final String s) { return createTextMessage(session, s, true); } - - protected ClientMessage createTextMessage(final ClientSession session, final String s, final boolean durable) - { - ClientMessage message = session.createMessage(Message.TEXT_TYPE, - durable, - 0, - System.currentTimeMillis(), - (byte) 4); + protected ClientMessage createTextMessage(final ClientSession session, final String s, final boolean durable) { + ClientMessage message = session.createMessage(Message.TEXT_TYPE, durable, 0, System.currentTimeMillis(), (byte) 4); message.getBodyBuffer().writeString(s); return message; } - protected XidImpl newXID() - { + protected XidImpl newXID() { return new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); } - protected int getMessageCount(final ActiveMQServer service, final String address) throws Exception - { + protected int getMessageCount(final ActiveMQServer service, final String address) throws Exception { return getMessageCount(service.getPostOffice(), address); } @@ -2623,14 +2179,12 @@ public abstract class ActiveMQTestBase extends Assert * @return * @throws Exception */ - protected int getMessageCount(final PostOffice postOffice, final String address) throws Exception - { + protected int getMessageCount(final PostOffice postOffice, final String address) throws Exception { int messageCount = 0; List bindings = getLocalQueueBindings(postOffice, address); - for (QueueBinding qBinding : bindings) - { + for (QueueBinding qBinding : bindings) { qBinding.getQueue().flushExecutor(); messageCount += getMessageCount(qBinding.getQueue()); } @@ -2638,46 +2192,39 @@ public abstract class ActiveMQTestBase extends Assert return messageCount; } - protected int getMessageCount(final Queue queue) - { + protected int getMessageCount(final Queue queue) { queue.flushExecutor(); - return (int)queue.getMessageCount(); + return (int) queue.getMessageCount(); } - protected int getMessagesAdded(final Queue queue) - { + protected int getMessagesAdded(final Queue queue) { queue.flushExecutor(); - return (int)queue.getMessagesAdded(); + return (int) queue.getMessagesAdded(); } - private List getLocalQueueBindings(final PostOffice postOffice, final String address) throws Exception - { + private List getLocalQueueBindings(final PostOffice postOffice, + final String address) throws Exception { ArrayList bindingsFound = new ArrayList(); Bindings bindings = postOffice.getBindingsForAddress(new SimpleString(address)); - for (Binding binding : bindings.getBindings()) - { - if (binding instanceof LocalQueueBinding) - { + for (Binding binding : bindings.getBindings()) { + if (binding instanceof LocalQueueBinding) { bindingsFound.add((QueueBinding) binding); } } return bindingsFound; } - protected final ServerLocator createInVMNonHALocator() - { + protected final ServerLocator createInVMNonHALocator() { return createNonHALocator(false); } - protected final ServerLocator createNettyNonHALocator() - { + protected final ServerLocator createNettyNonHALocator() { return createNonHALocator(true); } - protected final ServerLocator createNonHALocator(final boolean isNetty) - { + protected final ServerLocator createNonHALocator(final boolean isNetty) { ServerLocator locatorWithoutHA = internalCreateNonHALocator(isNetty); return addServerLocator(locatorWithoutHA); } @@ -2685,141 +2232,108 @@ public abstract class ActiveMQTestBase extends Assert /** * Creates the Locator without adding it to the list where the tearDown will take place * This is because we don't want it closed in certain tests where we are issuing failures + * * @param isNetty * @return */ - public ServerLocator internalCreateNonHALocator(boolean isNetty) - { - return isNetty - ? ActiveMQClient.createServerLocatorWithoutHA(new TransportConfiguration(NETTY_CONNECTOR_FACTORY)) - : ActiveMQClient.createServerLocatorWithoutHA(new TransportConfiguration(INVM_CONNECTOR_FACTORY)); + public ServerLocator internalCreateNonHALocator(boolean isNetty) { + return isNetty ? ActiveMQClient.createServerLocatorWithoutHA(new TransportConfiguration(NETTY_CONNECTOR_FACTORY)) : ActiveMQClient.createServerLocatorWithoutHA(new TransportConfiguration(INVM_CONNECTOR_FACTORY)); } - protected static final void stopComponent(ActiveMQComponent component) - { + protected static final void stopComponent(ActiveMQComponent component) { if (component == null) return; - try - { + try { component.stop(); } - catch (Exception e) - { + catch (Exception e) { // no-op } } - protected static final void stopComponentOutputExceptions(ActiveMQComponent component) - { + protected static final void stopComponentOutputExceptions(ActiveMQComponent component) { if (component == null) return; - try - { + try { component.stop(); } - catch (Exception e) - { + catch (Exception e) { System.err.println("Exception closing " + component); e.printStackTrace(); } } - protected final ClientSessionFactory createSessionFactory(ServerLocator locator) throws Exception - { + protected final ClientSessionFactory createSessionFactory(ServerLocator locator) throws Exception { ClientSessionFactory sf = locator.createSessionFactory(); addSessionFactory(sf); return sf; } - protected final ActiveMQServer addServer(final ActiveMQServer server) - { - if (server != null) - { - synchronized (servers) - { + protected final ActiveMQServer addServer(final ActiveMQServer server) { + if (server != null) { + synchronized (servers) { servers.add(server); } } return server; } - protected final ServerLocator addServerLocator(final ServerLocator locator) - { - if (locator != null) - { - synchronized (locators) - { + protected final ServerLocator addServerLocator(final ServerLocator locator) { + if (locator != null) { + synchronized (locators) { locators.add(locator); } } return locator; } - protected final ClientSession addClientSession(final ClientSession session) - { - if (session != null) - { - synchronized (clientSessions) - { + protected final ClientSession addClientSession(final ClientSession session) { + if (session != null) { + synchronized (clientSessions) { clientSessions.add(session); } } return session; } - protected final ClientConsumer addClientConsumer(final ClientConsumer consumer) - { - if (consumer != null) - { - synchronized (clientConsumers) - { + protected final ClientConsumer addClientConsumer(final ClientConsumer consumer) { + if (consumer != null) { + synchronized (clientConsumers) { clientConsumers.add(consumer); } } return consumer; } - protected final ClientProducer addClientProducer(final ClientProducer producer) - { - if (producer != null) - { - synchronized (clientProducers) - { + protected final ClientProducer addClientProducer(final ClientProducer producer) { + if (producer != null) { + synchronized (clientProducers) { clientProducers.add(producer); } } return producer; } - protected final void addActiveMQComponent(final ActiveMQComponent component) - { - if (component != null) - { - synchronized (otherComponents) - { + protected final void addActiveMQComponent(final ActiveMQComponent component) { + if (component != null) { + synchronized (otherComponents) { otherComponents.add(component); } } } - protected final ClientSessionFactory addSessionFactory(final ClientSessionFactory sf) - { - if (sf != null) - { - synchronized (sessionFactories) - { + protected final ClientSessionFactory addSessionFactory(final ClientSessionFactory sf) { + if (sf != null) { + synchronized (sessionFactories) { sessionFactories.add(sf); } } return sf; } - private void assertAllClientConsumersAreClosed() - { - synchronized (clientConsumers) - { - for (ClientConsumer cc : clientConsumers) - { + private void assertAllClientConsumersAreClosed() { + synchronized (clientConsumers) { + for (ClientConsumer cc : clientConsumers) { if (cc == null) continue; assertTrue(cc.isClosed()); @@ -2828,12 +2342,9 @@ public abstract class ActiveMQTestBase extends Assert } } - private void assertAllClientSessionsAreClosed() - { - synchronized (clientSessions) - { - for (final ClientSession cs : clientSessions) - { + private void assertAllClientSessionsAreClosed() { + synchronized (clientSessions) { + for (final ClientSession cs : clientSessions) { if (cs == null) continue; assertTrue(cs.isClosed()); @@ -2842,12 +2353,9 @@ public abstract class ActiveMQTestBase extends Assert } } - protected void closeAllSessionFactories() - { - synchronized (sessionFactories) - { - for (ClientSessionFactory sf : sessionFactories) - { + protected void closeAllSessionFactories() { + synchronized (sessionFactories) { + for (ClientSessionFactory sf : sessionFactories) { closeSessionFactory(sf); assert sf.isClosed(); } @@ -2855,51 +2363,40 @@ public abstract class ActiveMQTestBase extends Assert } } - protected void closeAllServerLocatorsFactories() - { - synchronized (locators) - { - for (ServerLocator locator : locators) - { + protected void closeAllServerLocatorsFactories() { + synchronized (locators) { + for (ServerLocator locator : locators) { closeServerLocator(locator); } locators.clear(); } } - public static final void closeServerLocator(ServerLocator locator) - { + public static final void closeServerLocator(ServerLocator locator) { if (locator == null) return; - try - { + try { locator.close(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } - public static final void closeSessionFactory(final ClientSessionFactory sf) - { + public static final void closeSessionFactory(final ClientSessionFactory sf) { if (sf == null) return; - try - { + try { sf.close(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } - public static void crashAndWaitForFailure(ActiveMQServer server, ClientSession... sessions) throws Exception - { + public static void crashAndWaitForFailure(ActiveMQServer server, ClientSession... sessions) throws Exception { CountDownLatch latch = new CountDownLatch(sessions.length); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { CountDownSessionFailureListener listener = new CountDownSessionFailureListener(latch, session); session.addFailureListener(listener); } @@ -2910,65 +2407,53 @@ public abstract class ActiveMQTestBase extends Assert Assert.assertTrue("server should be running!", server.isStarted()); server.stop(true); - if (sessions.length > 0) - { + if (sessions.length > 0) { // Wait to be informed of failure boolean ok = latch.await(10000, TimeUnit.MILLISECONDS); Assert.assertTrue("Failed to stop the server! Latch count is " + latch.getCount() + " out of " + - sessions.length, ok); + sessions.length, ok); } } - public static void crashAndWaitForFailure(ActiveMQServer server, ServerLocator locator) throws Exception - { + public static void crashAndWaitForFailure(ActiveMQServer server, ServerLocator locator) throws Exception { ClientSessionFactory sf = locator.createSessionFactory(); ClientSession session = sf.createSession(); - try - { + try { crashAndWaitForFailure(server, session); } - finally - { - try - { + finally { + try { session.close(); sf.close(); } - catch (Exception ignored) - { + catch (Exception ignored) { } } } - public interface RunnerWithEX - { + public interface RunnerWithEX { + void run() throws Throwable; } // This can be used to interrupt a thread if it takes more than timeoutMilliseconds - public boolean runWithTimeout(final RunnerWithEX runner, final long timeoutMilliseconds) throws Throwable - { + public boolean runWithTimeout(final RunnerWithEX runner, final long timeoutMilliseconds) throws Throwable { - class ThreadRunner extends Thread - { + class ThreadRunner extends Thread { Throwable t; final RunnerWithEX run; - ThreadRunner(RunnerWithEX run) - { + ThreadRunner(RunnerWithEX run) { this.run = run; } - public void run() - { - try - { + public void run() { + try { runner.run(); } - catch (Throwable t) - { + catch (Throwable t) { this.t = t; } } @@ -2979,14 +2464,11 @@ public abstract class ActiveMQTestBase extends Assert runnerThread.start(); boolean hadToInterrupt = false; - while (runnerThread.isAlive()) - { + while (runnerThread.isAlive()) { runnerThread.join(timeoutMilliseconds); - if (runnerThread.isAlive()) - { + if (runnerThread.isAlive()) { System.err.println("Thread still running, interrupting it now:"); - for (Object t : runnerThread.getStackTrace()) - { + for (Object t : runnerThread.getStackTrace()) { System.err.println(t); } hadToInterrupt = true; @@ -2994,8 +2476,7 @@ public abstract class ActiveMQTestBase extends Assert } } - if (runnerThread.t != null) - { + if (runnerThread.t != null) { runnerThread.t.printStackTrace(); throw runnerThread.t; } @@ -3005,13 +2486,12 @@ public abstract class ActiveMQTestBase extends Assert return !hadToInterrupt; } - // Private ------------------------------------------------------- // Inner classes ------------------------------------------------- - protected interface ActiveMQAction - { + protected interface ActiveMQAction { + void run() throws Exception; } @@ -3024,8 +2504,7 @@ public abstract class ActiveMQTestBase extends Assert * @param latch * @throws InterruptedException */ - public static void waitForLatch(CountDownLatch latch) throws InterruptedException - { + public static void waitForLatch(CountDownLatch latch) throws InterruptedException { assertTrue("Latch has got to return within a minute", latch.await(1, TimeUnit.MINUTES)); } } diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/ColocatedActiveMQServer.java b/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/ColocatedActiveMQServer.java index 845c9da3b5..d76a72c9ab 100644 --- a/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/ColocatedActiveMQServer.java +++ b/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/ColocatedActiveMQServer.java @@ -30,69 +30,64 @@ import org.apache.activemq.artemis.core.server.impl.FileLockNodeManager; import org.apache.activemq.artemis.jlibaio.LibaioContext; import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManager; +public class ColocatedActiveMQServer extends ActiveMQServerImpl { -public class ColocatedActiveMQServer extends ActiveMQServerImpl -{ private final NodeManager nodeManagerLive; private final NodeManager nodeManagerBackup; boolean backup = false; public ColocatedActiveMQServer backupServer; - public ColocatedActiveMQServer(FileConfiguration fc, ActiveMQSecurityManager sm, NodeManager nodeManagerLive, NodeManager nodeManagerBackup) - { + public ColocatedActiveMQServer(FileConfiguration fc, + ActiveMQSecurityManager sm, + NodeManager nodeManagerLive, + NodeManager nodeManagerBackup) { super(fc, sm); this.nodeManagerLive = nodeManagerLive; this.nodeManagerBackup = nodeManagerBackup; } - public ColocatedActiveMQServer(Configuration backupServerConfiguration, ActiveMQServer parentServer, NodeManager nodeManagerBackup, NodeManager nodeManagerLive) - { + public ColocatedActiveMQServer(Configuration backupServerConfiguration, + ActiveMQServer parentServer, + NodeManager nodeManagerBackup, + NodeManager nodeManagerLive) { super(backupServerConfiguration, null, null, parentServer); this.nodeManagerLive = nodeManagerLive; this.nodeManagerBackup = nodeManagerBackup; } - public ColocatedActiveMQServer(Configuration configuration, MBeanServer platformMBeanServer, ActiveMQSecurityManager securityManager, - NodeManager nodeManagerLive, NodeManager nodeManagerBackup) - { + public ColocatedActiveMQServer(Configuration configuration, + MBeanServer platformMBeanServer, + ActiveMQSecurityManager securityManager, + NodeManager nodeManagerLive, + NodeManager nodeManagerBackup) { super(configuration, platformMBeanServer, securityManager); this.nodeManagerLive = nodeManagerLive; this.nodeManagerBackup = nodeManagerBackup; } - @Override - protected NodeManager - createNodeManager(final File directory, boolean replicatingBackup) - { - if (replicatingBackup) - { + protected NodeManager createNodeManager(final File directory, boolean replicatingBackup) { + if (replicatingBackup) { NodeManager manager; - if (getConfiguration().getJournalType() == JournalType.ASYNCIO && LibaioContext.isLoaded()) - { + if (getConfiguration().getJournalType() == JournalType.ASYNCIO && LibaioContext.isLoaded()) { return new AIOFileLockNodeManager(directory, replicatingBackup, getConfiguration().getJournalLockAcquisitionTimeout()); } - else - { + else { return new FileLockNodeManager(directory, replicatingBackup, getConfiguration().getJournalLockAcquisitionTimeout()); } } - else - { - if (backup) - { + else { + if (backup) { return nodeManagerBackup; } - else - { + else { return nodeManagerLive; } } } @Override - public ActiveMQServer createBackupServer(Configuration configuration) - { + public ActiveMQServer createBackupServer(Configuration configuration) { ColocatedActiveMQServer backup = new ColocatedActiveMQServer(configuration, this, nodeManagerBackup, nodeManagerLive); backup.backup = true; this.backupServer = backup; diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/CountDownSessionFailureListener.java b/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/CountDownSessionFailureListener.java index 17dd475dcb..3ee7c1f5d3 100644 --- a/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/CountDownSessionFailureListener.java +++ b/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/CountDownSessionFailureListener.java @@ -22,50 +22,43 @@ import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.api.core.client.SessionFailureListener; -public final class CountDownSessionFailureListener implements SessionFailureListener -{ +public final class CountDownSessionFailureListener implements SessionFailureListener { + private final CountDownLatch latch; private final ClientSession session; - public CountDownSessionFailureListener(ClientSession session) - { + public CountDownSessionFailureListener(ClientSession session) { this(1, session); } - public CountDownSessionFailureListener(int n, ClientSession session) - { + public CountDownSessionFailureListener(int n, ClientSession session) { latch = new CountDownLatch(n); this.session = session; } - public CountDownSessionFailureListener(CountDownLatch latch, ClientSession session) - { + public CountDownSessionFailureListener(CountDownLatch latch, ClientSession session) { this.latch = latch; this.session = session; } @Override - public void connectionFailed(ActiveMQException exception, boolean failedOver, String scaleDownTargetNodeID) - { + public void connectionFailed(ActiveMQException exception, boolean failedOver, String scaleDownTargetNodeID) { connectionFailed(exception, failedOver); } @Override - public void connectionFailed(ActiveMQException exception, boolean failedOver) - { + public void connectionFailed(ActiveMQException exception, boolean failedOver) { latch.countDown(); session.removeFailureListener(this); } - public CountDownLatch getLatch() - { + public CountDownLatch getLatch() { return latch; } @Override - public void beforeReconnect(ActiveMQException exception) - { + public void beforeReconnect(ActiveMQException exception) { // No-op } diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/InVMNodeManagerServer.java b/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/InVMNodeManagerServer.java index ea887e13dd..a14cb5293f 100644 --- a/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/InVMNodeManagerServer.java +++ b/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/InVMNodeManagerServer.java @@ -25,34 +25,30 @@ import org.apache.activemq.artemis.core.server.NodeManager; import org.apache.activemq.artemis.core.server.impl.ActiveMQServerImpl; import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManager; -public final class InVMNodeManagerServer extends ActiveMQServerImpl -{ +public final class InVMNodeManagerServer extends ActiveMQServerImpl { + final NodeManager nodeManager; - public InVMNodeManagerServer(final NodeManager nodeManager) - { + public InVMNodeManagerServer(final NodeManager nodeManager) { super(); this.nodeManager = nodeManager; } - public InVMNodeManagerServer(final Configuration configuration, final NodeManager nodeManager) - { + public InVMNodeManagerServer(final Configuration configuration, final NodeManager nodeManager) { super(configuration); this.nodeManager = nodeManager; } public InVMNodeManagerServer(final Configuration configuration, final MBeanServer mbeanServer, - final NodeManager nodeManager) - { + final NodeManager nodeManager) { super(configuration, mbeanServer); this.nodeManager = nodeManager; } public InVMNodeManagerServer(final Configuration configuration, final ActiveMQSecurityManager securityManager, - final NodeManager nodeManager) - { + final NodeManager nodeManager) { super(configuration, securityManager); this.nodeManager = nodeManager; } @@ -60,15 +56,13 @@ public final class InVMNodeManagerServer extends ActiveMQServerImpl public InVMNodeManagerServer(final Configuration configuration, final MBeanServer mbeanServer, final ActiveMQSecurityManager securityManager, - final NodeManager nodeManager) - { + final NodeManager nodeManager) { super(configuration, mbeanServer, securityManager); this.nodeManager = nodeManager; } @Override - protected NodeManager createNodeManager(final File directory, boolean replicatingBackup) - { + protected NodeManager createNodeManager(final File directory, boolean replicatingBackup) { return nodeManager; } diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/RemoveFolder.java b/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/RemoveFolder.java index 3fdbaa1695..a44ab16b93 100644 --- a/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/RemoveFolder.java +++ b/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/RemoveFolder.java @@ -24,20 +24,18 @@ import org.junit.rules.ExternalResource; /** * This will remove a folder on a tearDown * */ -public class RemoveFolder extends ExternalResource -{ +public class RemoveFolder extends ExternalResource { + private final String folderName; - public RemoveFolder(String folderName) - { + public RemoveFolder(String folderName) { this.folderName = folderName; } /** * Override to tear down your specific external resource. */ - protected void after() - { + protected void after() { ActiveMQTestBase.deleteDirectory(new File(folderName)); } } diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/SimpleStringTest.java b/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/SimpleStringTest.java index 801fde25ac..e5a9dff8c0 100644 --- a/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/SimpleStringTest.java +++ b/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/SimpleStringTest.java @@ -22,28 +22,26 @@ import java.util.concurrent.CountDownLatch; import org.junit.Assert; - import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.utils.DataConstants; -public class SimpleStringTest extends Assert -{ +public class SimpleStringTest extends Assert { + /** * Converting back and forth between char and byte requires care as char is unsigned. + * * @see SimpleString#getChars(int, int, char[], int) * @see SimpleString#charAt(int) * @see SimpleString#split(char) * @see SimpleString#concat(char) */ @Test - public void testGetChar() - { + public void testGetChar() { SimpleString p1 = new SimpleString("foo"); SimpleString p2 = new SimpleString("bar"); - for (int i = 0; i < 1 << 16; i++) - { + for (int i = 0; i < 1 << 16; i++) { String msg = "expecting " + i; - char c = (char)i; + char c = (char) i; SimpleString s = new SimpleString(String.valueOf(c)); // test getChars(...) @@ -66,20 +64,17 @@ public class SimpleStringTest extends Assert assertEquals(split1.length + split2.length, chunks.length); int j = 0; - for (SimpleString iS : split1) - { + for (SimpleString iS : split1) { assertEquals(iS.toString(), iS, chunks[j++]); } - for (SimpleString iS : split2) - { + for (SimpleString iS : split2) { assertEquals(iS.toString(), iS, chunks[j++]); } } } @Test - public void testString() throws Exception - { + public void testString() throws Exception { final String str = "hello123ABC__524`16254`6125!%^$!%$!%$!%$!%!$%!$$!\uA324"; SimpleString s = new SimpleString(str); @@ -96,8 +91,7 @@ public class SimpleStringTest extends Assert } @Test - public void testStartsWith() throws Exception - { + public void testStartsWith() throws Exception { SimpleString s1 = new SimpleString("abcdefghi"); Assert.assertTrue(s1.startsWith(new SimpleString("abc"))); @@ -114,8 +108,7 @@ public class SimpleStringTest extends Assert } @Test - public void testCharSequence() throws Exception - { + public void testCharSequence() throws Exception { String s = "abcdefghijkl"; SimpleString s1 = new SimpleString(s); @@ -125,43 +118,35 @@ public class SimpleStringTest extends Assert Assert.assertEquals('k', s1.charAt(10)); Assert.assertEquals('l', s1.charAt(11)); - try - { + try { s1.charAt(-1); Assert.fail("Should throw exception"); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { // OK } - try - { + try { s1.charAt(-2); Assert.fail("Should throw exception"); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { // OK } - try - { + try { s1.charAt(s.length()); Assert.fail("Should throw exception"); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { // OK } - try - { + try { s1.charAt(s.length() + 1); Assert.fail("Should throw exception"); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { // OK } @@ -180,60 +165,49 @@ public class SimpleStringTest extends Assert ss = s1.subSequence(5, 12); Assert.assertEquals(ss, new SimpleString("fghijkl")); - try - { + try { s1.subSequence(-1, 2); Assert.fail("Should throw exception"); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { // OK } - try - { + try { s1.subSequence(-4, -2); Assert.fail("Should throw exception"); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { // OK } - try - { + try { s1.subSequence(0, s1.length() + 1); Assert.fail("Should throw exception"); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { // OK } - try - { + try { s1.subSequence(0, s1.length() + 2); Assert.fail("Should throw exception"); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { // OK } - try - { + try { s1.subSequence(5, 1); Assert.fail("Should throw exception"); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { // OK } } @Test - public void testEquals() throws Exception - { + public void testEquals() throws Exception { Assert.assertFalse(new SimpleString("abcdef").equals(new Object())); Assert.assertFalse(new SimpleString("abcef").equals(null)); @@ -245,8 +219,7 @@ public class SimpleStringTest extends Assert } @Test - public void testHashcode() throws Exception - { + public void testHashcode() throws Exception { SimpleString str = new SimpleString("abcdef"); SimpleString sameStr = new SimpleString("abcdef"); SimpleString differentStr = new SimpleString("ghijk"); @@ -256,8 +229,7 @@ public class SimpleStringTest extends Assert } @Test - public void testUnicode() throws Exception - { + public void testUnicode() throws Exception { String myString = "abcdef&^*&!^ghijkl\uB5E2\uCAC7\uB2BB\uB7DD\uB7C7\uB3A3\uBCE4\uB5A5"; SimpleString s = new SimpleString(myString); @@ -268,8 +240,7 @@ public class SimpleStringTest extends Assert } @Test - public void testUnicodeWithSurrogates() throws Exception - { + public void testUnicodeWithSurrogates() throws Exception { String myString = "abcdef&^*&!^ghijkl\uD900\uDD00"; SimpleString s = new SimpleString(myString); @@ -280,8 +251,7 @@ public class SimpleStringTest extends Assert } @Test - public void testSizeofString() throws Exception - { + public void testSizeofString() throws Exception { Assert.assertEquals(DataConstants.SIZE_INT, SimpleString.sizeofString(new SimpleString(""))); SimpleString str = new SimpleString(RandomUtil.randomString()); @@ -289,8 +259,7 @@ public class SimpleStringTest extends Assert } @Test - public void testSizeofNullableString() throws Exception - { + public void testSizeofNullableString() throws Exception { Assert.assertEquals(1, SimpleString.sizeofNullableString(null)); Assert.assertEquals(1 + DataConstants.SIZE_INT, SimpleString.sizeofNullableString(new SimpleString(""))); @@ -300,8 +269,7 @@ public class SimpleStringTest extends Assert } @Test - public void testSplitNoDelimeter() throws Exception - { + public void testSplitNoDelimeter() throws Exception { SimpleString s = new SimpleString("abcdefghi"); SimpleString[] strings = s.split('.'); Assert.assertNotNull(strings); @@ -310,8 +278,7 @@ public class SimpleStringTest extends Assert } @Test - public void testSplit1Delimeter() throws Exception - { + public void testSplit1Delimeter() throws Exception { SimpleString s = new SimpleString("abcd.efghi"); SimpleString[] strings = s.split('.'); Assert.assertNotNull(strings); @@ -321,8 +288,7 @@ public class SimpleStringTest extends Assert } @Test - public void testSplitmanyDelimeters() throws Exception - { + public void testSplitmanyDelimeters() throws Exception { SimpleString s = new SimpleString("abcd.efghi.jklmn.opqrs.tuvw.xyz"); SimpleString[] strings = s.split('.'); Assert.assertNotNull(strings); @@ -336,8 +302,7 @@ public class SimpleStringTest extends Assert } @Test - public void testContains() - { + public void testContains() { SimpleString simpleString = new SimpleString("abcdefghijklmnopqrst"); Assert.assertFalse(simpleString.contains('.')); Assert.assertFalse(simpleString.contains('%')); @@ -366,31 +331,26 @@ public class SimpleStringTest extends Assert } @Test - public void testConcat() - { + public void testConcat() { SimpleString start = new SimpleString("abcdefg"); SimpleString middle = new SimpleString("hijklmnop"); SimpleString end = new SimpleString("qrstuvwxyz"); Assert.assertEquals(start.concat(middle).concat(end), new SimpleString("abcdefghijklmnopqrstuvwxyz")); Assert.assertEquals(start.concat('.').concat(end), new SimpleString("abcdefg.qrstuvwxyz")); // Testing concat of SimpleString with String - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { Assert.assertEquals(new SimpleString("abcdefg-" + i), start.concat("-" + Integer.toString(i))); } } @Test - public void testMultithreadHashCode() throws Exception - { - for (int repeat = 0; repeat < 10; repeat++) - { + public void testMultithreadHashCode() throws Exception { + for (int repeat = 0; repeat < 10; repeat++) { StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { buffer.append("Some Big String " + i); } String strvalue = buffer.toString(); @@ -403,27 +363,23 @@ public class SimpleStringTest extends Assert final CountDownLatch latch = new CountDownLatch(nThreads); final CountDownLatch start = new CountDownLatch(1); - class T extends Thread - { + class T extends Thread { + boolean failed = false; @Override - public void run() - { - try - { + public void run() { + try { latch.countDown(); start.await(); int newhash = value.hashCode(); - if (newhash != initialhash) - { + if (newhash != initialhash) { failed = true; } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); failed = true; } @@ -431,8 +387,7 @@ public class SimpleStringTest extends Assert } T[] x = new T[nThreads]; - for (int i = 0; i < nThreads; i++) - { + for (int i = 0; i < nThreads; i++) { x[i] = new T(); x[i].start(); } @@ -440,13 +395,11 @@ public class SimpleStringTest extends Assert ActiveMQTestBase.waitForLatch(latch); start.countDown(); - for (T t : x) - { + for (T t : x) { t.join(); } - for (T t : x) - { + for (T t : x) { Assert.assertFalse(t.failed); } } diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/SingleServerTestBase.java b/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/SingleServerTestBase.java index ee684233bf..df2bff5e62 100644 --- a/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/SingleServerTestBase.java +++ b/artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/SingleServerTestBase.java @@ -26,8 +26,8 @@ import org.junit.Before; * Any test based on a single server can extend this class. * This is useful for quick writing tests with starting a server, locator, factory... etc */ -public abstract class SingleServerTestBase extends ActiveMQTestBase -{ +public abstract class SingleServerTestBase extends ActiveMQTestBase { + protected ActiveMQServer server; protected ClientSession session; @@ -36,11 +36,9 @@ public abstract class SingleServerTestBase extends ActiveMQTestBase protected ServerLocator locator; - @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(false, createDefaultInVMConfig()); @@ -51,8 +49,7 @@ public abstract class SingleServerTestBase extends ActiveMQTestBase session = addClientSession(sf.createSession(false, true, true)); } - protected ServerLocator createLocator() - { + protected ServerLocator createLocator() { return createInVMNonHALocator(); } } diff --git a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/ActiveMQServiceExtensionLogger.java b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/ActiveMQServiceExtensionLogger.java index 4f2edab3b8..3461bad3dd 100644 --- a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/ActiveMQServiceExtensionLogger.java +++ b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/ActiveMQServiceExtensionLogger.java @@ -39,8 +39,8 @@ import org.jboss.logging.annotations.MessageLogger; */ @MessageLogger(projectCode = "AMQ") -public interface ActiveMQServiceExtensionLogger extends BasicLogger -{ +public interface ActiveMQServiceExtensionLogger extends BasicLogger { + /** * The default logger. */ diff --git a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/ServiceUtils.java b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/ServiceUtils.java index ba0efe8839..6452c6ee1c 100644 --- a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/ServiceUtils.java +++ b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/ServiceUtils.java @@ -27,64 +27,52 @@ import org.apache.activemq.artemis.service.extensions.xa.ActiveMQXAResourceWrapp import org.apache.activemq.artemis.service.extensions.xa.ActiveMQXAResourceWrapperFactory; import org.apache.activemq.artemis.service.extensions.xa.ActiveMQXAResourceWrapperFactoryImpl; -public class ServiceUtils -{ +public class ServiceUtils { + private static ActiveMQXAResourceWrapperFactory activeMQXAResourceWrapperFactory; private static TransactionManager transactionManager; private static boolean transactionManagerLoaded = false; - private static ActiveMQXAResourceWrapperFactory getActiveMQXAResourceWrapperFactory() - { - if (activeMQXAResourceWrapperFactory == null) - { + private static ActiveMQXAResourceWrapperFactory getActiveMQXAResourceWrapperFactory() { + if (activeMQXAResourceWrapperFactory == null) { setActiveMQXAResourceWrapperFactory(ServiceLoader.load(ActiveMQXAResourceWrapperFactory.class)); } return activeMQXAResourceWrapperFactory; } - public static ActiveMQXAResourceWrapper wrapXAResource(XAResource xaResource, Map properties) - { + public static ActiveMQXAResourceWrapper wrapXAResource(XAResource xaResource, Map properties) { return getActiveMQXAResourceWrapperFactory().wrap(xaResource, properties); } - public static synchronized TransactionManager getTransactionManager() - { - if (!transactionManagerLoaded) - { + public static synchronized TransactionManager getTransactionManager() { + if (!transactionManagerLoaded) { Iterator it = ServiceLoader.load(TransactionManagerLocator.class).iterator(); - while (it.hasNext() && transactionManager == null) - { + while (it.hasNext() && transactionManager == null) { transactionManager = it.next().getTransactionManager(); } - if (transactionManager != null) - { + if (transactionManager != null) { transactionManagerLoaded = true; } - else - { + else { ActiveMQServiceExtensionLogger.LOGGER.transactionManagerNotFound(); } } return transactionManager; } - public static void setTransactionManager(TransactionManager tm) - { + public static void setTransactionManager(TransactionManager tm) { transactionManager = tm; transactionManagerLoaded = (transactionManager != null); } - private static void setActiveMQXAResourceWrapperFactory(Iterable iterable) - { - if (iterable.iterator().hasNext()) - { + private static void setActiveMQXAResourceWrapperFactory(Iterable iterable) { + if (iterable.iterator().hasNext()) { activeMQXAResourceWrapperFactory = iterable.iterator().next(); } - else - { + else { activeMQXAResourceWrapperFactory = new ActiveMQXAResourceWrapperFactoryImpl(); } } diff --git a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/transactions/TransactionManagerLocator.java b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/transactions/TransactionManagerLocator.java index 8fd0042681..907a72fa89 100644 --- a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/transactions/TransactionManagerLocator.java +++ b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/transactions/TransactionManagerLocator.java @@ -18,7 +18,7 @@ package org.apache.activemq.artemis.service.extensions.transactions; import javax.transaction.TransactionManager; -public interface TransactionManagerLocator -{ +public interface TransactionManagerLocator { + TransactionManager getTransactionManager(); } diff --git a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/ActiveMQXAResourceWrapper.java b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/ActiveMQXAResourceWrapper.java index 5a45212cc9..66546bd5a8 100644 --- a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/ActiveMQXAResourceWrapper.java +++ b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/ActiveMQXAResourceWrapper.java @@ -18,8 +18,8 @@ package org.apache.activemq.artemis.service.extensions.xa; import javax.transaction.xa.XAResource; -public interface ActiveMQXAResourceWrapper extends XAResource -{ +public interface ActiveMQXAResourceWrapper extends XAResource { + // List of supported properties String ACTIVEMQ_JNDI_NAME = "ACTIVEMQ_JNDI_ID"; diff --git a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/ActiveMQXAResourceWrapperFactory.java b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/ActiveMQXAResourceWrapperFactory.java index 2d5e51b672..da96cc3446 100644 --- a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/ActiveMQXAResourceWrapperFactory.java +++ b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/ActiveMQXAResourceWrapperFactory.java @@ -19,7 +19,7 @@ package org.apache.activemq.artemis.service.extensions.xa; import javax.transaction.xa.XAResource; import java.util.Map; -public interface ActiveMQXAResourceWrapperFactory -{ +public interface ActiveMQXAResourceWrapperFactory { + ActiveMQXAResourceWrapper wrap(XAResource xaResource, Map properties); } diff --git a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/ActiveMQXAResourceWrapperFactoryImpl.java b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/ActiveMQXAResourceWrapperFactoryImpl.java index 08f464ed72..15cc7957d6 100644 --- a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/ActiveMQXAResourceWrapperFactoryImpl.java +++ b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/ActiveMQXAResourceWrapperFactoryImpl.java @@ -19,12 +19,10 @@ package org.apache.activemq.artemis.service.extensions.xa; import javax.transaction.xa.XAResource; import java.util.Map; -public class ActiveMQXAResourceWrapperFactoryImpl implements ActiveMQXAResourceWrapperFactory -{ +public class ActiveMQXAResourceWrapperFactoryImpl implements ActiveMQXAResourceWrapperFactory { @Override - public ActiveMQXAResourceWrapper wrap(XAResource xaResource, Map properties) - { + public ActiveMQXAResourceWrapper wrap(XAResource xaResource, Map properties) { return new ActiveMQXAResourceWrapperImpl(xaResource, properties); } } diff --git a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/ActiveMQXAResourceWrapperImpl.java b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/ActiveMQXAResourceWrapperImpl.java index f814f1b680..99223260ec 100644 --- a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/ActiveMQXAResourceWrapperImpl.java +++ b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/ActiveMQXAResourceWrapperImpl.java @@ -21,8 +21,8 @@ import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; import java.util.Map; -public class ActiveMQXAResourceWrapperImpl implements ActiveMQXAResourceWrapper -{ +public class ActiveMQXAResourceWrapperImpl implements ActiveMQXAResourceWrapper { + private final XAResource xaResource; // The EIS Name @@ -42,8 +42,7 @@ public class ActiveMQXAResourceWrapperImpl implements ActiveMQXAResourceWrapper * @param xaResource * @param properties */ - public ActiveMQXAResourceWrapperImpl(XAResource xaResource, Map properties) - { + public ActiveMQXAResourceWrapperImpl(XAResource xaResource, Map properties) { this.xaResource = xaResource; //this.productName = ActiveMQResourceAdapter.PRODUCT_NAME; this.productName = (String) properties.get(ACTIVEMQ_PRODUCT_NAME); @@ -54,83 +53,69 @@ public class ActiveMQXAResourceWrapperImpl implements ActiveMQXAResourceWrapper " NodeId:" + properties.get(ACTIVEMQ_NODE_ID); } - public XAResource getResource() - { + public XAResource getResource() { return xaResource; } - public String getProductName() - { + public String getProductName() { return productName; } - public String getProductVersion() - { + public String getProductVersion() { return productVersion; } - public String getJndiName() - { + public String getJndiName() { return jndiNameNodeId; } @Override - public void commit(Xid xid, boolean b) throws XAException - { + public void commit(Xid xid, boolean b) throws XAException { getResource().commit(xid, b); } @Override - public void end(Xid xid, int i) throws XAException - { + public void end(Xid xid, int i) throws XAException { getResource().end(xid, i); } @Override - public void forget(Xid xid) throws XAException - { + public void forget(Xid xid) throws XAException { getResource().forget(xid); } @Override - public int getTransactionTimeout() throws XAException - { + public int getTransactionTimeout() throws XAException { return getResource().getTransactionTimeout(); } @Override - public boolean isSameRM(XAResource xaResource) throws XAException - { + public boolean isSameRM(XAResource xaResource) throws XAException { return getResource().isSameRM(xaResource); } @Override - public int prepare(Xid xid) throws XAException - { + public int prepare(Xid xid) throws XAException { return getResource().prepare(xid); } @Override - public Xid[] recover(int i) throws XAException - { + public Xid[] recover(int i) throws XAException { return getResource().recover(i); } @Override - public void rollback(Xid xid) throws XAException - { + public void rollback(Xid xid) throws XAException { getResource().rollback(xid); } @Override - public boolean setTransactionTimeout(int i) throws XAException - { + public boolean setTransactionTimeout(int i) throws XAException { return getResource().setTransactionTimeout(i); } @Override - public void start(Xid xid, int i) throws XAException - { + public void start(Xid xid, int i) throws XAException { getResource().start(xid, i); } diff --git a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/ActiveMQRegistry.java b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/ActiveMQRegistry.java index d8de8a3f22..f64c68b105 100644 --- a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/ActiveMQRegistry.java +++ b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/ActiveMQRegistry.java @@ -17,8 +17,8 @@ package org.apache.activemq.artemis.service.extensions.xa.recovery; -public interface ActiveMQRegistry -{ +public interface ActiveMQRegistry { + void register(final XARecoveryConfig resourceConfig); void unRegister(final XARecoveryConfig resourceConfig); diff --git a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/ActiveMQRegistryImpl.java b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/ActiveMQRegistryImpl.java index 3312fbe190..83c693a954 100644 --- a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/ActiveMQRegistryImpl.java +++ b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/ActiveMQRegistryImpl.java @@ -17,40 +17,34 @@ package org.apache.activemq.artemis.service.extensions.xa.recovery; -public class ActiveMQRegistryImpl implements ActiveMQRegistry -{ +public class ActiveMQRegistryImpl implements ActiveMQRegistry { + private static ActiveMQRegistryImpl instance; - public static ActiveMQRegistry getInstance() - { - if (instance == null) - { + public static ActiveMQRegistry getInstance() { + if (instance == null) { instance = new ActiveMQRegistryImpl(); } return instance; } @Override - public void register(XARecoveryConfig resourceConfig) - { + public void register(XARecoveryConfig resourceConfig) { } @Override - public void unRegister(XARecoveryConfig resourceConfig) - { + public void unRegister(XARecoveryConfig resourceConfig) { } @Override - public void stop() - { + public void stop() { } @Override - public void init() - { + public void init() { } } diff --git a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/ActiveMQXARecoveryLogger.java b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/ActiveMQXARecoveryLogger.java index b04bbc1b09..b27c4b22d1 100644 --- a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/ActiveMQXARecoveryLogger.java +++ b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/ActiveMQXARecoveryLogger.java @@ -40,76 +40,76 @@ import org.w3c.dom.Node; * so an INFO message would be 121000 to 121999 */ @MessageLogger(projectCode = "AMQ") -public interface ActiveMQXARecoveryLogger extends BasicLogger -{ +public interface ActiveMQXARecoveryLogger extends BasicLogger { + /** * The default logger. */ ActiveMQXARecoveryLogger LOGGER = Logger.getMessageLogger(ActiveMQXARecoveryLogger.class, ActiveMQXARecoveryLogger.class.getPackage().getName()); @LogMessage(level = Logger.Level.INFO) - @Message(id = 121003, value = "JMS Server Manager Running cached command for {0}" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 121003, value = "JMS Server Manager Running cached command for {0}", format = Message.Format.MESSAGE_FORMAT) void serverRunningCachedCommand(Runnable run); @LogMessage(level = Logger.Level.INFO) @Message(id = 121004, value = "JMS Server Manager Caching command for {0} since the JMS Server is not active yet", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void serverCachingCommand(Object runnable); @LogMessage(level = Logger.Level.INFO) @Message(id = 121005, value = "Invalid \"host\" value \"0.0.0.0\" detected for \"{0}\" connector. Switching to \"{1}\". If this new address is incorrect please manually configure the connector to use the proper one.", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void invalidHostForConnector(String name, String newHost); @LogMessage(level = Logger.Level.WARN) - @Message(id = 122007, value = "Queue {0} does not exist on the topic {1}. It was deleted manually probably." , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 122007, value = "Queue {0} does not exist on the topic {1}. It was deleted manually probably.", format = Message.Format.MESSAGE_FORMAT) void noQueueOnTopic(String queueName, String name); @LogMessage(level = Logger.Level.WARN) - @Message(id = 122008, value = "XA Recovery can not connect to any broker on recovery {0}" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 122008, value = "XA Recovery can not connect to any broker on recovery {0}", format = Message.Format.MESSAGE_FORMAT) void recoveryConnectFailed(String s); @LogMessage(level = Logger.Level.WARN) - @Message(id = 122011, value = "error unbinding {0} from JNDI" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 122011, value = "error unbinding {0} from JNDI", format = Message.Format.MESSAGE_FORMAT) void jndiUnbindError(@Cause Exception e, String key); @LogMessage(level = Logger.Level.WARN) - @Message(id = 122012, value = "JMS Server Manager error" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 122012, value = "JMS Server Manager error", format = Message.Format.MESSAGE_FORMAT) void jmsServerError(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) - @Message(id = 122013, value = "Error in XA Recovery recover" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 122013, value = "Error in XA Recovery recover", format = Message.Format.MESSAGE_FORMAT) void xaRecoverError(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 122014, value = "Notified of connection failure in xa recovery connectionFactory for provider {0} will attempt reconnect on next pass", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void xaRecoverConnectionError(@Cause Exception e, ClientSessionFactory csf); @LogMessage(level = Logger.Level.WARN) @Message(id = 122015, value = "Can not connect to {0} on auto-generated resource recovery", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void xaRecoverAutoConnectionError(@Cause Throwable e, XARecoveryConfig csf); @LogMessage(level = Logger.Level.DEBUG) - @Message(id = 122016, value = "Error in XA Recovery" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 122016, value = "Error in XA Recovery", format = Message.Format.MESSAGE_FORMAT) void xaRecoveryError(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 122017, value = "Tried to correct invalid \"host\" value \"0.0.0.0\" for \"{0}\" connector, but received an exception.", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void failedToCorrectHost(@Cause Exception e, String name); @LogMessage(level = Logger.Level.WARN) @Message(id = 122018, value = "Could not start recovery discovery on {0}, we will retry every recovery scan until the server is available", - format = Message.Format.MESSAGE_FORMAT) + format = Message.Format.MESSAGE_FORMAT) void xaRecoveryStartError(XARecoveryConfig e); @LogMessage(level = Logger.Level.ERROR) - @Message(id = 124000, value = "key attribute missing for JMS configuration {0}" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 124000, value = "key attribute missing for JMS configuration {0}", format = Message.Format.MESSAGE_FORMAT) void jmsConfigMissingKey(Node e); @LogMessage(level = Logger.Level.ERROR) - @Message(id = 124002, value = "Failed to start JMS deployer" , format = Message.Format.MESSAGE_FORMAT) + @Message(id = 124002, value = "Failed to start JMS deployer", format = Message.Format.MESSAGE_FORMAT) void jmsDeployerStartError(@Cause Exception e); } diff --git a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/ActiveMQXAResourceRecovery.java b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/ActiveMQXAResourceRecovery.java index 214d5c11fa..3c1861d03d 100644 --- a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/ActiveMQXAResourceRecovery.java +++ b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/ActiveMQXAResourceRecovery.java @@ -46,33 +46,28 @@ import org.apache.activemq.artemis.api.core.TransportConfiguration; * value="org.apache.activemq.artemis.jms.server.recovery.ActiveMQXAResourceRecovery;org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnectorFactory,guest,guest,host=localhost,port=61616;org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnectorFactory,guest,guest,host=localhost2,port=61617"/> * */ -public class ActiveMQXAResourceRecovery -{ +public class ActiveMQXAResourceRecovery { + private final boolean trace = ActiveMQXARecoveryLogger.LOGGER.isTraceEnabled(); private boolean hasMore; private ActiveMQXAResourceWrapper res; - public ActiveMQXAResourceRecovery() - { - if (trace) - { + public ActiveMQXAResourceRecovery() { + if (trace) { ActiveMQXARecoveryLogger.LOGGER.trace("Constructing ActiveMQXAResourceRecovery"); } } - public boolean initialise(final String config) - { - if (ActiveMQXARecoveryLogger.LOGGER.isTraceEnabled()) - { + public boolean initialise(final String config) { + if (ActiveMQXARecoveryLogger.LOGGER.isTraceEnabled()) { ActiveMQXARecoveryLogger.LOGGER.trace(this + " intialise: " + config); } String[] configs = config.split(";"); XARecoveryConfig[] xaRecoveryConfigs = new XARecoveryConfig[configs.length]; - for (int i = 0, configsLength = configs.length; i < configsLength; i++) - { + for (int i = 0, configsLength = configs.length; i < configsLength; i++) { String s = configs[i]; ConfigParser parser = new ConfigParser(s); String connectorFactoryClassName = parser.getConnectorFactoryClassName(); @@ -83,21 +78,17 @@ public class ActiveMQXAResourceRecovery xaRecoveryConfigs[i] = new XARecoveryConfig(false, new TransportConfiguration[]{transportConfiguration}, username, password); } - res = new ActiveMQXAResourceWrapper(xaRecoveryConfigs); - if (ActiveMQXARecoveryLogger.LOGGER.isTraceEnabled()) - { + if (ActiveMQXARecoveryLogger.LOGGER.isTraceEnabled()) { ActiveMQXARecoveryLogger.LOGGER.trace(this + " initialised"); } return true; } - public boolean hasMoreResources() - { - if (ActiveMQXARecoveryLogger.LOGGER.isTraceEnabled()) - { + public boolean hasMoreResources() { + if (ActiveMQXARecoveryLogger.LOGGER.isTraceEnabled()) { ActiveMQXARecoveryLogger.LOGGER.trace(this + " hasMoreResources"); } @@ -120,29 +111,25 @@ public class ActiveMQXAResourceRecovery return hasMore; } - public XAResource getXAResource() - { - if (ActiveMQXARecoveryLogger.LOGGER.isTraceEnabled()) - { + public XAResource getXAResource() { + if (ActiveMQXARecoveryLogger.LOGGER.isTraceEnabled()) { ActiveMQXARecoveryLogger.LOGGER.trace(this + " getXAResource"); } return res; } - public XAResource[] getXAResources() - { + public XAResource[] getXAResources() { return new XAResource[]{res}; } @Override - protected void finalize() - { + protected void finalize() { res.close(); } - public static class ConfigParser - { + public static class ConfigParser { + private final String connectorFactoryClassName; private final Map connectorParameters; @@ -151,18 +138,15 @@ public class ActiveMQXAResourceRecovery private String password; - public ConfigParser(final String config) - { - if (config == null || config.length() == 0) - { + public ConfigParser(final String config) { + if (config == null || config.length() == 0) { throw new IllegalArgumentException("Must specify provider connector factory class name in config"); } String[] strings = config.split(","); // First (mandatory) param is the connector factory class name - if (strings.length < 1) - { + if (strings.length < 1) { throw new IllegalArgumentException("Must specify provider connector factory class name in config"); } @@ -170,59 +154,48 @@ public class ActiveMQXAResourceRecovery // Next two (optional) parameters are the username and password to use for creating the session for recovery - if (strings.length >= 2) - { + if (strings.length >= 2) { username = strings[1].trim(); - if (username.length() == 0) - { + if (username.length() == 0) { username = null; } - if (strings.length == 2) - { + if (strings.length == 2) { throw new IllegalArgumentException("If username is specified, password must be specified too"); } password = strings[2].trim(); - if (password.length() == 0) - { + if (password.length() == 0) { password = null; } } // other tokens are for connector configurations connectorParameters = new HashMap(); - if (strings.length >= 3) - { - for (int i = 3; i < strings.length; i++) - { + if (strings.length >= 3) { + for (int i = 3; i < strings.length; i++) { String[] str = strings[i].split("="); - if (str.length == 2) - { + if (str.length == 2) { connectorParameters.put(str[0].trim(), str[1].trim()); } } } } - public String getConnectorFactoryClassName() - { + public String getConnectorFactoryClassName() { return connectorFactoryClassName; } - public Map getConnectorParameters() - { + public Map getConnectorParameters() { return connectorParameters; } - public String getUsername() - { + public String getUsername() { return username; } - public String getPassword() - { + public String getPassword() { return password; } } diff --git a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/ActiveMQXAResourceWrapper.java b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/ActiveMQXAResourceWrapper.java index 9c886bd7ad..33695323d1 100644 --- a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/ActiveMQXAResourceWrapper.java +++ b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/ActiveMQXAResourceWrapper.java @@ -40,9 +40,11 @@ import org.apache.activemq.artemis.api.core.client.SessionFailureListener; * the RM_FAIL or RM_ERR is thrown, but in ActiveMQ Artemis we throw XA_RETRY since we want the recovery manager to be able * to retry on failure without having to manually retry */ -public class ActiveMQXAResourceWrapper implements XAResource, SessionFailureListener -{ - /** The state lock */ +public class ActiveMQXAResourceWrapper implements XAResource, SessionFailureListener { + + /** + * The state lock + */ private static final Object lock = new Object(); private ServerLocator serverLocator; @@ -53,224 +55,175 @@ public class ActiveMQXAResourceWrapper implements XAResource, SessionFailureList private XARecoveryConfig[] xaRecoveryConfigs; - public ActiveMQXAResourceWrapper(XARecoveryConfig... xaRecoveryConfigs) - { + public ActiveMQXAResourceWrapper(XARecoveryConfig... xaRecoveryConfigs) { this.xaRecoveryConfigs = xaRecoveryConfigs; - if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) { ActiveMQXARecoveryLogger.LOGGER.debug("Recovery configured with " + Arrays.toString(xaRecoveryConfigs) + - ", instance=" + - System.identityHashCode(this)); + ", instance=" + + System.identityHashCode(this)); } } - public Xid[] recover(final int flag) throws XAException - { + public Xid[] recover(final int flag) throws XAException { XAResource xaResource = getDelegate(false); - if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) { ActiveMQXARecoveryLogger.LOGGER.debug("looking for recover at " + xaResource + " configuration " + Arrays.toString(this.xaRecoveryConfigs)); } - try - { + try { Xid[] xids = xaResource.recover(flag); - if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled() && xids != null && xids.length > 0) - { + if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled() && xids != null && xids.length > 0) { ActiveMQXARecoveryLogger.LOGGER.debug("Recovering these following IDs " + Arrays.toString(xids) + " at " + this); } return xids; } - catch (XAException e) - { + catch (XAException e) { ActiveMQXARecoveryLogger.LOGGER.xaRecoverError(e); throw check(e); } } - public void commit(final Xid xid, final boolean onePhase) throws XAException - { + public void commit(final Xid xid, final boolean onePhase) throws XAException { XAResource xaResource = getDelegate(true); - if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) { ActiveMQXARecoveryLogger.LOGGER.debug("Commit " + xaResource + " xid " + " onePhase=" + onePhase); } - try - { + try { xaResource.commit(xid, onePhase); } - catch (XAException e) - { + catch (XAException e) { throw check(e); } } - public void rollback(final Xid xid) throws XAException - { + public void rollback(final Xid xid) throws XAException { XAResource xaResource = getDelegate(true); - if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) { ActiveMQXARecoveryLogger.LOGGER.debug("Rollback " + xaResource + " xid "); } - try - { + try { xaResource.rollback(xid); } - catch (XAException e) - { + catch (XAException e) { throw check(e); } } - public void forget(final Xid xid) throws XAException - { + public void forget(final Xid xid) throws XAException { XAResource xaResource = getDelegate(false); - if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) { ActiveMQXARecoveryLogger.LOGGER.debug("Forget " + xaResource + " xid "); } - try - { + try { xaResource.forget(xid); } - catch (XAException e) - { + catch (XAException e) { throw check(e); } } - public boolean isSameRM(XAResource xaRes) throws XAException - { - if (xaRes instanceof ActiveMQXAResourceWrapper) - { - xaRes = ((ActiveMQXAResourceWrapper)xaRes).getDelegate(false); + public boolean isSameRM(XAResource xaRes) throws XAException { + if (xaRes instanceof ActiveMQXAResourceWrapper) { + xaRes = ((ActiveMQXAResourceWrapper) xaRes).getDelegate(false); } XAResource xaResource = getDelegate(false); - try - { + try { return xaResource.isSameRM(xaRes); } - catch (XAException e) - { + catch (XAException e) { throw check(e); } } - public int prepare(final Xid xid) throws XAException - { + public int prepare(final Xid xid) throws XAException { XAResource xaResource = getDelegate(true); - if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) { ActiveMQXARecoveryLogger.LOGGER.debug("prepare " + xaResource + " xid "); } - try - { + try { return xaResource.prepare(xid); } - catch (XAException e) - { + catch (XAException e) { throw check(e); } } - public void start(final Xid xid, final int flags) throws XAException - { + public void start(final Xid xid, final int flags) throws XAException { XAResource xaResource = getDelegate(false); - if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) { ActiveMQXARecoveryLogger.LOGGER.debug("start " + xaResource + " xid "); } - try - { + try { xaResource.start(xid, flags); } - catch (XAException e) - { + catch (XAException e) { throw check(e); } } - public void end(final Xid xid, final int flags) throws XAException - { + public void end(final Xid xid, final int flags) throws XAException { XAResource xaResource = getDelegate(false); - if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) { ActiveMQXARecoveryLogger.LOGGER.debug("end " + xaResource + " xid "); } - try - { + try { xaResource.end(xid, flags); } - catch (XAException e) - { + catch (XAException e) { throw check(e); } } - public int getTransactionTimeout() throws XAException - { + public int getTransactionTimeout() throws XAException { XAResource xaResource = getDelegate(false); - if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) { ActiveMQXARecoveryLogger.LOGGER.debug("getTransactionTimeout " + xaResource + " xid "); } - try - { + try { return xaResource.getTransactionTimeout(); } - catch (XAException e) - { + catch (XAException e) { throw check(e); } } - public boolean setTransactionTimeout(final int seconds) throws XAException - { + public boolean setTransactionTimeout(final int seconds) throws XAException { XAResource xaResource = getDelegate(false); - if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) { ActiveMQXARecoveryLogger.LOGGER.debug("setTransactionTimeout " + xaResource + " xid "); } - try - { + try { return xaResource.setTransactionTimeout(seconds); } - catch (XAException e) - { + catch (XAException e) { throw check(e); } } - public void connectionFailed(final ActiveMQException me, boolean failedOver) - { - if (me.getType() == ActiveMQExceptionType.DISCONNECTED) - { - if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver) { + if (me.getType() == ActiveMQExceptionType.DISCONNECTED) { + if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) { ActiveMQXARecoveryLogger.LOGGER.debug("being disconnected for server shutdown", me); } } - else - { + else { ActiveMQXARecoveryLogger.LOGGER.xaRecoverConnectionError(me, csf); } close(); } @Override - public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) { connectionFailed(me, failedOver); } - public void beforeReconnect(final ActiveMQException me) - { + public void beforeReconnect(final ActiveMQException me) { } /** @@ -279,47 +232,37 @@ public class ActiveMQXAResourceWrapper implements XAResource, SessionFailureList * @return the connectionFactory * @throws XAException for any problem */ - private XAResource getDelegate(boolean retry) throws XAException - { + private XAResource getDelegate(boolean retry) throws XAException { XAResource result = null; Exception error = null; - try - { + try { result = connect(); } - catch (Exception e) - { + catch (Exception e) { error = e; } - if (result == null) - { + if (result == null) { // we should always throw a retry for certain methods comit etc, if not the tx is marked as a heuristic and // all chaos is let loose - if (retry) - { + if (retry) { XAException xae = new XAException("Connection unavailable for xa recovery"); xae.errorCode = XAException.XA_RETRY; - if (error != null) - { + if (error != null) { xae.initCause(error); } - if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) { ActiveMQXARecoveryLogger.LOGGER.debug("Cannot get connectionFactory XAResource", xae); } throw xae; } - else - { + else { XAException xae = new XAException("Error trying to connect to any providers for xa recovery"); xae.errorCode = XAException.XAER_RMFAIL; - if (error != null) - { + if (error != null) { xae.initCause(error); } - if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) { ActiveMQXARecoveryLogger.LOGGER.debug("Cannot get connectionFactory XAResource", xae); } throw xae; @@ -336,79 +279,59 @@ public class ActiveMQXAResourceWrapper implements XAResource, SessionFailureList * @return the connectionFactory XAResource * @throws Exception for any problem */ - protected XAResource connect() throws Exception - { + protected XAResource connect() throws Exception { // Do we already have a valid connectionFactory? - synchronized (ActiveMQXAResourceWrapper.lock) - { - if (delegate != null) - { + synchronized (ActiveMQXAResourceWrapper.lock) { + if (delegate != null) { return delegate; } } - for (XARecoveryConfig xaRecoveryConfig : xaRecoveryConfigs) - { + for (XARecoveryConfig xaRecoveryConfig : xaRecoveryConfigs) { - if (xaRecoveryConfig == null) - { + if (xaRecoveryConfig == null) { continue; } - if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) { ActiveMQXARecoveryLogger.LOGGER.debug("Trying to connect recovery on " + xaRecoveryConfig + " of " + Arrays.toString(xaRecoveryConfigs)); } ClientSession cs = null; - try - { + try { // setting ha=false because otherwise the connector would go towards any server, causing Heuristic exceptions // we really need to control what server it's connected to // Manual configuration may still use discovery, so we will keep this - if (xaRecoveryConfig.getDiscoveryConfiguration() != null) - { + if (xaRecoveryConfig.getDiscoveryConfiguration() != null) { serverLocator = ActiveMQClient.createServerLocator(false, xaRecoveryConfig.getDiscoveryConfiguration()); } - else - { + else { serverLocator = ActiveMQClient.createServerLocator(false, xaRecoveryConfig.getTransportConfig()); } serverLocator.disableFinalizeCheck(); csf = serverLocator.createSessionFactory(); - if (xaRecoveryConfig.getUsername() == null) - { + if (xaRecoveryConfig.getUsername() == null) { cs = csf.createSession(true, false, false); } - else - { - cs = csf.createSession(xaRecoveryConfig.getUsername(), - xaRecoveryConfig.getPassword(), - true, - false, - false, - false, - 1); + else { + cs = csf.createSession(xaRecoveryConfig.getUsername(), xaRecoveryConfig.getPassword(), true, false, false, false, 1); } } - catch (Throwable e) - { + catch (Throwable e) { ActiveMQXARecoveryLogger.LOGGER.xaRecoverAutoConnectionError(e, xaRecoveryConfig); - if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) - { + if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) { ActiveMQXARecoveryLogger.LOGGER.debug(e.getMessage(), e); } - try - { - if (cs != null) cs.close(); - if (serverLocator != null) serverLocator.close(); + try { + if (cs != null) + cs.close(); + if (serverLocator != null) + serverLocator.close(); } - catch (Throwable ignored) - { - if (ActiveMQXARecoveryLogger.LOGGER.isTraceEnabled()) - { + catch (Throwable ignored) { + if (ActiveMQXARecoveryLogger.LOGGER.isTraceEnabled()) { ActiveMQXARecoveryLogger.LOGGER.trace(e.getMessage(), ignored); } } @@ -417,8 +340,7 @@ public class ActiveMQXAResourceWrapper implements XAResource, SessionFailureList cs.addFailureListener(this); - synchronized (ActiveMQXAResourceWrapper.lock) - { + synchronized (ActiveMQXAResourceWrapper.lock) { delegate = cs; } @@ -432,8 +354,7 @@ public class ActiveMQXAResourceWrapper implements XAResource, SessionFailureList * @see java.lang.Object#toString() */ @Override - public String toString() - { + public String toString() { return "ActiveMQXAResourceWrapper [serverLocator=" + serverLocator + ", csf=" + csf + @@ -449,13 +370,11 @@ public class ActiveMQXAResourceWrapper implements XAResource, SessionFailureList /** * Close the connection */ - public void close() - { + public void close() { ServerLocator oldServerLocator = null; ClientSessionFactory oldCSF = null; ClientSession oldDelegate = null; - synchronized (ActiveMQXAResourceWrapper.lock) - { + synchronized (ActiveMQXAResourceWrapper.lock) { oldCSF = csf; csf = null; oldDelegate = delegate; @@ -464,38 +383,29 @@ public class ActiveMQXAResourceWrapper implements XAResource, SessionFailureList serverLocator = null; } - if (oldDelegate != null) - { - try - { + if (oldDelegate != null) { + try { oldDelegate.close(); } - catch (Throwable ignorable) - { + catch (Throwable ignorable) { ActiveMQXARecoveryLogger.LOGGER.debug(ignorable.getMessage(), ignorable); } } - if (oldCSF != null) - { - try - { + if (oldCSF != null) { + try { oldCSF.close(); } - catch (Throwable ignorable) - { + catch (Throwable ignorable) { ActiveMQXARecoveryLogger.LOGGER.debug(ignorable.getMessage(), ignorable); } } - if (oldServerLocator != null) - { - try - { + if (oldServerLocator != null) { + try { oldServerLocator.close(); } - catch (Throwable ignorable) - { + catch (Throwable ignorable) { ActiveMQXARecoveryLogger.LOGGER.debug(ignorable.getMessage(), ignorable); } } @@ -509,19 +419,16 @@ public class ActiveMQXAResourceWrapper implements XAResource, SessionFailureList * @return never * @throws XAException always */ - protected XAException check(final XAException e) throws XAException - { + protected XAException check(final XAException e) throws XAException { ActiveMQXARecoveryLogger.LOGGER.xaRecoveryError(e); - // If any exception happened, we close the connection so we may start fresh close(); throw e; } @Override - protected void finalize() throws Throwable - { + protected void finalize() throws Throwable { close(); } } diff --git a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/XARecoveryConfig.java b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/XARecoveryConfig.java index 154e4a9dc6..c6101ae87e 100644 --- a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/XARecoveryConfig.java +++ b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/XARecoveryConfig.java @@ -25,13 +25,11 @@ import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; /** - * * This represents the configuration of a single connection factory. * * A wrapper around info needed for the xa recovery resource */ -public class XARecoveryConfig -{ +public class XARecoveryConfig { private final boolean ha; private final TransportConfiguration[] transportConfiguration; @@ -39,23 +37,20 @@ public class XARecoveryConfig private final String username; private final String password; - public static XARecoveryConfig newConfig(ActiveMQConnectionFactory factory, - String userName, - String password) - { - if (factory.getServerLocator().getDiscoveryGroupConfiguration() != null) - { + public static XARecoveryConfig newConfig(ActiveMQConnectionFactory factory, String userName, String password) { + if (factory.getServerLocator().getDiscoveryGroupConfiguration() != null) { return new XARecoveryConfig(factory.getServerLocator().isHA(), factory.getServerLocator().getDiscoveryGroupConfiguration(), userName, password); } - else - { + else { return new XARecoveryConfig(factory.getServerLocator().isHA(), factory.getServerLocator().getStaticTransportConfigurations(), userName, password); } } - public XARecoveryConfig(final boolean ha, final TransportConfiguration[] transportConfiguration, final String username, final String password) - { + public XARecoveryConfig(final boolean ha, + final TransportConfiguration[] transportConfiguration, + final String username, + final String password) { this.transportConfiguration = transportConfiguration; this.discoveryConfiguration = null; this.username = username; @@ -63,8 +58,10 @@ public class XARecoveryConfig this.ha = ha; } - public XARecoveryConfig(final boolean ha, final DiscoveryGroupConfiguration discoveryConfiguration, final String username, final String password) - { + public XARecoveryConfig(final boolean ha, + final DiscoveryGroupConfiguration discoveryConfiguration, + final String username, + final String password) { this.discoveryConfiguration = discoveryConfiguration; this.transportConfiguration = null; this.username = username; @@ -72,52 +69,43 @@ public class XARecoveryConfig this.ha = ha; } - public boolean isHA() - { + public boolean isHA() { return ha; } - public DiscoveryGroupConfiguration getDiscoveryConfiguration() - { + public DiscoveryGroupConfiguration getDiscoveryConfiguration() { return discoveryConfiguration; } - public TransportConfiguration[] getTransportConfig() - { + public TransportConfiguration[] getTransportConfig() { return transportConfiguration; } - public String getUsername() - { + public String getUsername() { return username; } - public String getPassword() - { + public String getPassword() { return password; } - /** * Create a serverLocator using the configuration + * * @return locator */ - public ServerLocator createServerLocator() - { - if (getDiscoveryConfiguration() != null) - { + public ServerLocator createServerLocator() { + if (getDiscoveryConfiguration() != null) { return ActiveMQClient.createServerLocator(isHA(), getDiscoveryConfiguration()); } - else - { + else { return ActiveMQClient.createServerLocator(isHA(), getTransportConfig()); } } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((discoveryConfiguration == null) ? 0 : discoveryConfiguration.hashCode()); @@ -130,17 +118,15 @@ public class XARecoveryConfig * Just having the connector is enough, as we don't want to duplicate resources just because of usernames */ @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; - XARecoveryConfig other = (XARecoveryConfig)obj; - if (discoveryConfiguration == null) - { + XARecoveryConfig other = (XARecoveryConfig) obj; + if (discoveryConfiguration == null) { if (other.discoveryConfiguration != null) return false; } @@ -155,12 +141,11 @@ public class XARecoveryConfig * @see java.lang.Object#toString() */ @Override - public String toString() - { + public String toString() { return "XARecoveryConfig [transportConfiguration = " + Arrays.toString(transportConfiguration) + - ", discoveryConfiguration = " + discoveryConfiguration + - ", username=" + - username + - ", password=****]"; + ", discoveryConfiguration = " + discoveryConfiguration + + ", username=" + + username + + ", password=****]"; } } diff --git a/artemis-service-extensions/src/test/java/org/apache/activemq/artemis/service/extensions/tests/transactions/DummyTransactionManagerLocator.java b/artemis-service-extensions/src/test/java/org/apache/activemq/artemis/service/extensions/tests/transactions/DummyTransactionManagerLocator.java index c840697f19..3ed77fcde6 100644 --- a/artemis-service-extensions/src/test/java/org/apache/activemq/artemis/service/extensions/tests/transactions/DummyTransactionManagerLocator.java +++ b/artemis-service-extensions/src/test/java/org/apache/activemq/artemis/service/extensions/tests/transactions/DummyTransactionManagerLocator.java @@ -27,65 +27,55 @@ import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.TransactionManager; -public class DummyTransactionManagerLocator implements TransactionManagerLocator,TransactionManager -{ +public class DummyTransactionManagerLocator implements TransactionManagerLocator, TransactionManager { + @Override - public void begin() throws NotSupportedException, SystemException - { + public void begin() throws NotSupportedException, SystemException { } @Override - public void commit() throws HeuristicMixedException, HeuristicRollbackException, IllegalStateException, RollbackException, SecurityException, SystemException - { + public void commit() throws HeuristicMixedException, HeuristicRollbackException, IllegalStateException, RollbackException, SecurityException, SystemException { } @Override - public int getStatus() throws SystemException - { + public int getStatus() throws SystemException { return 0; } @Override - public Transaction getTransaction() throws SystemException - { + public Transaction getTransaction() throws SystemException { return null; } @Override - public void resume(Transaction transaction) throws IllegalStateException, InvalidTransactionException, SystemException - { + public void resume(Transaction transaction) throws IllegalStateException, InvalidTransactionException, SystemException { } @Override - public void rollback() throws IllegalStateException, SecurityException, SystemException - { + public void rollback() throws IllegalStateException, SecurityException, SystemException { } @Override - public void setRollbackOnly() throws IllegalStateException, SystemException - { + public void setRollbackOnly() throws IllegalStateException, SystemException { } @Override - public void setTransactionTimeout(int i) throws SystemException - { + public void setTransactionTimeout(int i) throws SystemException { } @Override - public Transaction suspend() throws SystemException - { + public Transaction suspend() throws SystemException { return null; } @Override - public TransactionManager getTransactionManager() - { + public TransactionManager getTransactionManager() { return this; } } diff --git a/artemis-service-extensions/src/test/java/org/apache/activemq/artemis/service/extensions/tests/transactions/TransactionManagerLocatorTest.java b/artemis-service-extensions/src/test/java/org/apache/activemq/artemis/service/extensions/tests/transactions/TransactionManagerLocatorTest.java index 7446f24fbd..6585e7ee38 100644 --- a/artemis-service-extensions/src/test/java/org/apache/activemq/artemis/service/extensions/tests/transactions/TransactionManagerLocatorTest.java +++ b/artemis-service-extensions/src/test/java/org/apache/activemq/artemis/service/extensions/tests/transactions/TransactionManagerLocatorTest.java @@ -20,11 +20,10 @@ import org.apache.activemq.artemis.service.extensions.ServiceUtils; import org.junit.Assert; import org.junit.Test; -public class TransactionManagerLocatorTest extends Assert -{ +public class TransactionManagerLocatorTest extends Assert { + @Test - public void getTM() - { + public void getTM() { assertNotNull(ServiceUtils.getTransactionManager()); assertEquals(ServiceUtils.getTransactionManager().getClass(), DummyTransactionManagerLocator.class); } diff --git a/artemis-service-extensions/src/test/java/org/apache/activemq/artemis/service/extensions/tests/xa/ActiveMQXAResourceWrapperImplTest.java b/artemis-service-extensions/src/test/java/org/apache/activemq/artemis/service/extensions/tests/xa/ActiveMQXAResourceWrapperImplTest.java index 9c78d0febb..eff8533b38 100644 --- a/artemis-service-extensions/src/test/java/org/apache/activemq/artemis/service/extensions/tests/xa/ActiveMQXAResourceWrapperImplTest.java +++ b/artemis-service-extensions/src/test/java/org/apache/activemq/artemis/service/extensions/tests/xa/ActiveMQXAResourceWrapperImplTest.java @@ -27,11 +27,10 @@ import org.junit.Test; import static org.jgroups.util.Util.assertEquals; -public class ActiveMQXAResourceWrapperImplTest -{ +public class ActiveMQXAResourceWrapperImplTest { + @Test - public void testXAResourceWrapper() - { + public void testXAResourceWrapper() { String jndiName = "java://jmsXA"; String nodeId = "0"; XAResource xaResource = new MockXAResource(); diff --git a/artemis-service-extensions/src/test/java/org/apache/activemq/artemis/service/extensions/tests/xa/MockActiveMQResourceWrapperFactory.java b/artemis-service-extensions/src/test/java/org/apache/activemq/artemis/service/extensions/tests/xa/MockActiveMQResourceWrapperFactory.java index 90a0abcf0b..e7c97546ae 100644 --- a/artemis-service-extensions/src/test/java/org/apache/activemq/artemis/service/extensions/tests/xa/MockActiveMQResourceWrapperFactory.java +++ b/artemis-service-extensions/src/test/java/org/apache/activemq/artemis/service/extensions/tests/xa/MockActiveMQResourceWrapperFactory.java @@ -22,11 +22,10 @@ import java.util.Map; import org.apache.activemq.artemis.service.extensions.xa.ActiveMQXAResourceWrapper; import org.apache.activemq.artemis.service.extensions.xa.ActiveMQXAResourceWrapperFactory; -public class MockActiveMQResourceWrapperFactory implements ActiveMQXAResourceWrapperFactory -{ +public class MockActiveMQResourceWrapperFactory implements ActiveMQXAResourceWrapperFactory { + @Override - public ActiveMQXAResourceWrapper wrap(XAResource xaResource, Map properties) - { + public ActiveMQXAResourceWrapper wrap(XAResource xaResource, Map properties) { return null; } } diff --git a/artemis-service-extensions/src/test/java/org/apache/activemq/artemis/service/extensions/tests/xa/MockXAResource.java b/artemis-service-extensions/src/test/java/org/apache/activemq/artemis/service/extensions/tests/xa/MockXAResource.java index aaa9b7195a..c4bfed30b1 100644 --- a/artemis-service-extensions/src/test/java/org/apache/activemq/artemis/service/extensions/tests/xa/MockXAResource.java +++ b/artemis-service-extensions/src/test/java/org/apache/activemq/artemis/service/extensions/tests/xa/MockXAResource.java @@ -20,65 +20,55 @@ import javax.transaction.xa.XAException; import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; -public class MockXAResource implements XAResource -{ +public class MockXAResource implements XAResource { + @Override - public void commit(Xid xid, boolean b) throws XAException - { + public void commit(Xid xid, boolean b) throws XAException { } @Override - public void end(Xid xid, int i) throws XAException - { + public void end(Xid xid, int i) throws XAException { } @Override - public void forget(Xid xid) throws XAException - { + public void forget(Xid xid) throws XAException { } @Override - public int getTransactionTimeout() throws XAException - { + public int getTransactionTimeout() throws XAException { return 0; } @Override - public boolean isSameRM(XAResource xaResource) throws XAException - { + public boolean isSameRM(XAResource xaResource) throws XAException { return false; } @Override - public int prepare(Xid xid) throws XAException - { + public int prepare(Xid xid) throws XAException { return 0; } @Override - public Xid[] recover(int i) throws XAException - { + public Xid[] recover(int i) throws XAException { return new Xid[0]; } @Override - public void rollback(Xid xid) throws XAException - { + public void rollback(Xid xid) throws XAException { } @Override - public boolean setTransactionTimeout(int i) throws XAException - { + public boolean setTransactionTimeout(int i) throws XAException { return false; } @Override - public void start(Xid xid, int i) throws XAException - { + public void start(Xid xid, int i) throws XAException { } } diff --git a/artemis-service-extensions/src/test/java/org/apache/activemq/artemis/service/extensions/tests/xa/ServiceUtilsTest.java b/artemis-service-extensions/src/test/java/org/apache/activemq/artemis/service/extensions/tests/xa/ServiceUtilsTest.java index ec72a7bcb6..90754bd7b2 100644 --- a/artemis-service-extensions/src/test/java/org/apache/activemq/artemis/service/extensions/tests/xa/ServiceUtilsTest.java +++ b/artemis-service-extensions/src/test/java/org/apache/activemq/artemis/service/extensions/tests/xa/ServiceUtilsTest.java @@ -28,11 +28,10 @@ import org.junit.Test; import static org.jgroups.util.Util.assertTrue; -public class ServiceUtilsTest -{ +public class ServiceUtilsTest { + @Test - public void testSetActiveMQXAResourceWrapperFactorySetsDefaultImplWhenNoOther() throws Exception - { + public void testSetActiveMQXAResourceWrapperFactorySetsDefaultImplWhenNoOther() throws Exception { List factories = new ArrayList(); Method method = ServiceUtils.class.getDeclaredMethod("setActiveMQXAResourceWrapperFactory", Iterable.class); @@ -45,8 +44,7 @@ public class ServiceUtilsTest } @Test - public void testSetActiveMQXAResourceWrapperFactorySetsExtensionImplWhenSupplied() throws Exception - { + public void testSetActiveMQXAResourceWrapperFactorySetsExtensionImplWhenSupplied() throws Exception { List factories = new ArrayList(); factories.add(new MockActiveMQResourceWrapperFactory()); diff --git a/artemis-web/src/main/java/org/apache/activemq/artemis/component/WebServerComponent.java b/artemis-web/src/main/java/org/apache/activemq/artemis/component/WebServerComponent.java index 7a1a42357f..25565dab2b 100644 --- a/artemis-web/src/main/java/org/apache/activemq/artemis/component/WebServerComponent.java +++ b/artemis-web/src/main/java/org/apache/activemq/artemis/component/WebServerComponent.java @@ -30,17 +30,15 @@ import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.server.handler.ResourceHandler; import org.eclipse.jetty.webapp.WebAppContext; -public class WebServerComponent implements ExternalComponent -{ +public class WebServerComponent implements ExternalComponent { private Server server; private HandlerList handlers; private WebServerDTO webServerConfig; @Override - public void configure(ComponentDTO config, String artemisInstance, String artemisHome) throws Exception - { - webServerConfig = (WebServerDTO)config; + public void configure(ComponentDTO config, String artemisInstance, String artemisHome) throws Exception { + webServerConfig = (WebServerDTO) config; String path = webServerConfig.path.startsWith("/") ? webServerConfig.path : "/" + webServerConfig.path; URI uri = new URI(webServerConfig.bind); server = new Server(); @@ -52,10 +50,8 @@ public class WebServerComponent implements ExternalComponent handlers = new HandlerList(); - if (webServerConfig.apps != null) - { - for (AppDTO app : webServerConfig.apps) - { + if (webServerConfig.apps != null) { + for (AppDTO app : webServerConfig.apps) { deployWar(app.url, app.war, artemisHome, path); } } @@ -78,32 +74,26 @@ public class WebServerComponent implements ExternalComponent server.setHandler(handlers); } - public void start() throws Exception - { + public void start() throws Exception { server.start(); System.out.println("HTTP Server started at " + webServerConfig.bind); } - public void stop() throws Exception - { + public void stop() throws Exception { server.stop(); } - public boolean isStarted() - { + public boolean isStarted() { return server != null && server.isStarted(); } - private void deployWar(String url, String warURL, String activeMQHome, String path) - { + private void deployWar(String url, String warURL, String activeMQHome, String path) { WebAppContext webapp = new WebAppContext(); - if (url.startsWith("/")) - { + if (url.startsWith("/")) { webapp.setContextPath(url); } - else - { + else { webapp.setContextPath("/" + url); } webapp.setWar(activeMQHome + path + "/" + warURL); diff --git a/artemis-web/src/test/java/org/apache/activemq/cli/test/WebServerComponentTest.java b/artemis-web/src/test/java/org/apache/activemq/cli/test/WebServerComponentTest.java index 5175c61784..8532e36052 100644 --- a/artemis-web/src/test/java/org/apache/activemq/cli/test/WebServerComponentTest.java +++ b/artemis-web/src/test/java/org/apache/activemq/cli/test/WebServerComponentTest.java @@ -44,22 +44,21 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class WebServerComponentTest extends Assert -{ +public class WebServerComponentTest extends Assert { + static final String URL = System.getProperty("url", "http://localhost:8161/WebServerComponentTest.txt"); private Bootstrap bootstrap; private EventLoopGroup group; @Before - public void setupNetty() throws URISyntaxException - { + public void setupNetty() throws URISyntaxException { // Configure the client. group = new NioEventLoopGroup(); bootstrap = new Bootstrap(); } + @Test - public void simpleServer() throws Exception - { + public void simpleServer() throws Exception { WebServerDTO webServerDTO = new WebServerDTO(); webServerDTO.bind = "http://localhost:8161"; webServerDTO.path = "webapps"; @@ -70,11 +69,9 @@ public class WebServerComponentTest extends Assert // Make the connection attempt. CountDownLatch latch = new CountDownLatch(1); final ClientHandler clientHandler = new ClientHandler(latch); - bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer() - { + bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer() { @Override - protected void initChannel(Channel ch) throws Exception - { + protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new HttpClientCodec()); ch.pipeline().addLast(clientHandler); } @@ -86,7 +83,6 @@ public class WebServerComponentTest extends Assert HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath()); request.headers().set(HttpHeaders.Names.HOST, "localhost"); - // Send the HTTP request. ch.writeAndFlush(request); assertTrue(latch.await(5, TimeUnit.SECONDS)); @@ -98,29 +94,25 @@ public class WebServerComponentTest extends Assert Assert.assertFalse(webServerComponent.isStarted()); } - class ClientHandler extends SimpleChannelInboundHandler - { + class ClientHandler extends SimpleChannelInboundHandler { + private CountDownLatch latch; private String body; - public ClientHandler(CountDownLatch latch) - { + public ClientHandler(CountDownLatch latch) { this.latch = latch; } @Override - public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) - { - if (msg instanceof HttpContent) - { + public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) { + if (msg instanceof HttpContent) { HttpContent content = (HttpContent) msg; body = content.content().toString(CharsetUtil.UTF_8); latch.countDown(); } } - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) - { + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } diff --git a/etc/IDEA-style.jar b/etc/IDEA-style.jar index 979e06dac6..83893f3fa5 100644 Binary files a/etc/IDEA-style.jar and b/etc/IDEA-style.jar differ diff --git a/etc/checkstyle.xml b/etc/checkstyle.xml index cd189c4c46..11deca68e5 100644 --- a/etc/checkstyle.xml +++ b/etc/checkstyle.xml @@ -67,9 +67,9 @@ under the License. - + - + diff --git a/examples/core/embedded-remote/src/main/java/org/apache/activemq/artemis/core/example/EmbeddedRemoteExample.java b/examples/core/embedded-remote/src/main/java/org/apache/activemq/artemis/core/example/EmbeddedRemoteExample.java index fe3d84686f..cec295a94c 100644 --- a/examples/core/embedded-remote/src/main/java/org/apache/activemq/artemis/core/example/EmbeddedRemoteExample.java +++ b/examples/core/embedded-remote/src/main/java/org/apache/activemq/artemis/core/example/EmbeddedRemoteExample.java @@ -31,17 +31,13 @@ import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnectorFactory; /** - * * This example shows how to run an ActiveMQ Artemis core client and server embedded in your * own application */ -public class EmbeddedRemoteExample -{ +public class EmbeddedRemoteExample { - public static void main(final String[] args) - { - try - { + public static void main(final String[] args) { + try { // Step 3. As we are not using a JNDI environment we instantiate the objects directly /** @@ -49,7 +45,7 @@ public class EmbeddedRemoteExample * If you modify it to run the example in two different hosts, remember to also modify the * server's Acceptor at {@link EmbeddedServer} */ - Map map = new HashMap(); + Map map = new HashMap(); map.put("host", "localhost"); map.put("port", 61616); // ------------------------------------------------------- @@ -68,8 +64,7 @@ public class EmbeddedRemoteExample ClientSession session = null; - try - { + try { // Step 5. Create the session, and producer session = sf.createSession(); @@ -95,17 +90,14 @@ public class EmbeddedRemoteExample ClientMessage messageReceived = messageConsumer.receive(1000); System.out.println("Received TextMessage:" + messageReceived.getStringProperty(propName)); } - finally - { + finally { // Step 9. Be sure to close our resources! - if (sf != null) - { + if (sf != null) { sf.close(); } } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } diff --git a/examples/core/embedded-remote/src/main/java/org/apache/activemq/artemis/core/example/EmbeddedServer.java b/examples/core/embedded-remote/src/main/java/org/apache/activemq/artemis/core/example/EmbeddedServer.java index 412d468468..16993f7436 100644 --- a/examples/core/embedded-remote/src/main/java/org/apache/activemq/artemis/core/example/EmbeddedServer.java +++ b/examples/core/embedded-remote/src/main/java/org/apache/activemq/artemis/core/example/EmbeddedServer.java @@ -30,13 +30,10 @@ import org.apache.activemq.artemis.core.server.ActiveMQServers; /** * An EmbeddedServer */ -public class EmbeddedServer -{ +public class EmbeddedServer { - public static void main(final String arg[]) throws Exception - { - try - { + public static void main(final String arg[]) throws Exception { + try { // Step 1. Create the Configuration, and set the properties accordingly Configuration configuration = new ConfigurationImpl(); //we only need this for the server lock file @@ -52,7 +49,7 @@ public class EmbeddedServer map.put("host", "localhost"); map.put("port", 61616); - TransportConfiguration transpConf = new TransportConfiguration(NettyAcceptorFactory.class.getName(),map); + TransportConfiguration transpConf = new TransportConfiguration(NettyAcceptorFactory.class.getName(), map); HashSet setTransp = new HashSet(); setTransp.add(transpConf); @@ -63,8 +60,7 @@ public class EmbeddedServer ActiveMQServer server = ActiveMQServers.newActiveMQServer(configuration); server.start(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); throw e; } diff --git a/examples/core/embedded/src/main/java/org/apache/activemq/artemis/core/example/EmbeddedExample.java b/examples/core/embedded/src/main/java/org/apache/activemq/artemis/core/example/EmbeddedExample.java index 17395b67a6..d3f8f86cf1 100644 --- a/examples/core/embedded/src/main/java/org/apache/activemq/artemis/core/example/EmbeddedExample.java +++ b/examples/core/embedded/src/main/java/org/apache/activemq/artemis/core/example/EmbeddedExample.java @@ -34,17 +34,13 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.ActiveMQServers; /** - * * This example shows how to run an ActiveMQ Artemis core client and server embedded in your * own application */ -public class EmbeddedExample -{ +public class EmbeddedExample { - public static void main(final String[] args) throws Exception - { - try - { + public static void main(final String[] args) throws Exception { + try { // Step 1. Create the Configuration, and set the properties accordingly Configuration configuration = new ConfigurationImpl(); //we only need this for the server lock file @@ -72,8 +68,7 @@ public class EmbeddedExample ClientSession session = null; - try - { + try { // Step 5. Create the session, and producer session = sf.createSession(); @@ -99,11 +94,9 @@ public class EmbeddedExample ClientMessage messageReceived = messageConsumer.receive(1000); System.out.println("Received TextMessage:" + messageReceived.getStringProperty(propName)); } - finally - { + finally { // Step 9. Be sure to close our resources! - if (sf != null) - { + if (sf != null) { sf.close(); } @@ -111,8 +104,7 @@ public class EmbeddedExample server.stop(); } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); throw e; } diff --git a/examples/core/perf/src/main/java/org/apache/activemq/artemis/core/example/PerfBase.java b/examples/core/perf/src/main/java/org/apache/activemq/artemis/core/example/PerfBase.java index bbbb67fb04..c1988c963d 100644 --- a/examples/core/perf/src/main/java/org/apache/activemq/artemis/core/example/PerfBase.java +++ b/examples/core/perf/src/main/java/org/apache/activemq/artemis/core/example/PerfBase.java @@ -43,39 +43,33 @@ import org.apache.activemq.artemis.utils.TokenBucketLimiter; import org.apache.activemq.artemis.utils.TokenBucketLimiterImpl; /** - * * A PerfBase */ -public abstract class PerfBase -{ +public abstract class PerfBase { + private static final Logger log = Logger.getLogger(PerfSender.class.getName()); private static final String DEFAULT_PERF_PROPERTIES_FILE_NAME = "perf.properties"; - private static byte[] randomByteArray(final int length) - { + private static byte[] randomByteArray(final int length) { byte[] bytes = new byte[length]; Random random = new Random(); - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { bytes[i] = Integer.valueOf(random.nextInt()).byteValue(); } return bytes; } - protected static String getPerfFileName(final String[] args) - { + protected static String getPerfFileName(final String[] args) { String fileName; - if (args.length > 0) - { + if (args.length > 0) { fileName = args[0]; } - else - { + else { fileName = PerfBase.DEFAULT_PERF_PROPERTIES_FILE_NAME; } @@ -84,24 +78,20 @@ public abstract class PerfBase return fileName; } - protected static PerfParams getParams(final String fileName) throws Exception - { + protected static PerfParams getParams(final String fileName) throws Exception { Properties props = null; InputStream is = null; - try - { + try { is = new FileInputStream(fileName); props = new Properties(); props.load(is); } - finally - { - if (is != null) - { + finally { + if (is != null) { is.close(); } } @@ -150,8 +140,7 @@ public abstract class PerfBase PerfBase.log.info("block-persistent:" + blockOnPersistent); PerfBase.log.info("use-send-acks:" + useSendAcks); - if (useSendAcks && confirmationWindowSize < 1) - { + if (useSendAcks && confirmationWindowSize < 1) { throw new IllegalArgumentException("If you use send acks, then need to set confirmation-window-size to a positive integer"); } @@ -183,8 +172,7 @@ public abstract class PerfBase private final PerfParams perfParams; - protected PerfBase(final PerfParams perfParams) - { + protected PerfBase(final PerfParams perfParams) { this.perfParams = perfParams; } @@ -192,8 +180,7 @@ public abstract class PerfBase private long start; - private void init(final boolean transacted, final String queueName) throws Exception - { + private void init(final boolean transacted, final String queueName) throws Exception { Map params = new HashMap(); params.put(TransportConstants.TCP_NODELAY_PROPNAME, perfParams.isTcpNoDelay()); @@ -216,70 +203,45 @@ public abstract class PerfBase } - private void displayAverage(final long numberOfMessages, final long start, final long end) - { + private void displayAverage(final long numberOfMessages, final long start, final long end) { double duration = (1.0 * end - start) / 1000; // in seconds double average = 1.0 * numberOfMessages / duration; - PerfBase.log.info(String.format("average: %.2f msg/s (%d messages in %2.2fs)", - average, - numberOfMessages, - duration)); + PerfBase.log.info(String.format("average: %.2f msg/s (%d messages in %2.2fs)", average, numberOfMessages, duration)); } - protected void runSender() - { - try - { + protected void runSender() { + try { PerfBase.log.info("params = " + perfParams); init(perfParams.isSessionTransacted(), perfParams.getQueueName()); - if (perfParams.isDrainQueue()) - { + if (perfParams.isDrainQueue()) { drainQueue(); } start = System.currentTimeMillis(); PerfBase.log.info("warming up by sending " + perfParams.getNoOfWarmupMessages() + " messages"); - sendMessages(perfParams.getNoOfWarmupMessages(), - perfParams.getBatchSize(), - perfParams.isDurable(), - perfParams.isSessionTransacted(), - false, - perfParams.getThrottleRate(), - perfParams.getMessageSize(), - perfParams.isUseSendAcks()); + sendMessages(perfParams.getNoOfWarmupMessages(), perfParams.getBatchSize(), perfParams.isDurable(), perfParams.isSessionTransacted(), false, perfParams.getThrottleRate(), perfParams.getMessageSize(), perfParams.isUseSendAcks()); PerfBase.log.info("warmed up"); start = System.currentTimeMillis(); - sendMessages(perfParams.getNoOfMessagesToSend(), - perfParams.getBatchSize(), - perfParams.isDurable(), - perfParams.isSessionTransacted(), - true, - perfParams.getThrottleRate(), - perfParams.getMessageSize(), - perfParams.isUseSendAcks()); + sendMessages(perfParams.getNoOfMessagesToSend(), perfParams.getBatchSize(), perfParams.isDurable(), perfParams.isSessionTransacted(), true, perfParams.getThrottleRate(), perfParams.getMessageSize(), perfParams.isUseSendAcks()); long end = System.currentTimeMillis(); displayAverage(perfParams.getNoOfMessagesToSend(), start, end); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } - protected void runListener() - { + protected void runListener() { ClientSession session = null; - try - { + try { init(perfParams.isSessionTransacted(), perfParams.getQueueName()); session = factory.createSession(!perfParams.isSessionTransacted(), !perfParams.isSessionTransacted()); - if (perfParams.isDrainQueue()) - { + if (perfParams.isDrainQueue()) { drainQueue(); } @@ -296,34 +258,27 @@ public abstract class PerfBase // start was set on the first received message displayAverage(perfParams.getNoOfMessagesToSend(), start, end); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } - finally - { - if (factory != null) - { - try - { + finally { + if (factory != null) { + try { factory.close(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } } } - private void drainQueue() throws Exception - { + private void drainQueue() throws Exception { PerfBase.log.info("Draining queue"); ClientSession session = null; - try - { + try { session = factory.createSession(); ClientConsumer consumer = session.createConsumer(perfParams.getQueueName()); @@ -333,25 +288,20 @@ public abstract class PerfBase ClientMessage message = null; int count = 0; - do - { + do { message = consumer.receive(3000); - if (message != null) - { + if (message != null) { message.acknowledge(); count++; } - } - while (message != null); + } while (message != null); PerfBase.log.info("Drained " + count + " messages"); } - finally - { - if (session != null) - { + finally { + if (session != null) { session.close(); } } @@ -364,24 +314,20 @@ public abstract class PerfBase final boolean display, final int throttleRate, final int messageSize, - final boolean useSendAcks) throws Exception - { + final boolean useSendAcks) throws Exception { ClientSession session = null; - try - { + try { session = factory.createSession(!transacted, !transacted); CountDownLatch theLatch = null; - if (useSendAcks) - { + if (useSendAcks) { final CountDownLatch latch = new CountDownLatch(numberOfMessages); - class MySendAckHandler implements SendAcknowledgementHandler - { - public void sendAcknowledged(Message message) - { + class MySendAckHandler implements SendAcknowledgementHandler { + + public void sendAcknowledged(Message message) { latch.countDown(); } } @@ -405,59 +351,49 @@ public abstract class PerfBase boolean committed = false; - for (int i = 1; i <= numberOfMessages; i++) - { + for (int i = 1; i <= numberOfMessages; i++) { producer.send(message); - if (transacted) - { - if (i % txBatchSize == 0) - { + if (transacted) { + if (i % txBatchSize == 0) { session.commit(); committed = true; } - else - { + else { committed = false; } } - if (display && i % modulo == 0) - { + if (display && i % modulo == 0) { double duration = (1.0 * System.currentTimeMillis() - start) / 1000; PerfBase.log.info(String.format("sent %6d messages in %2.2fs", i, duration)); } // log.info("sent message " + i); - if (tbl != null) - { + if (tbl != null) { tbl.limit(); } } - if (transacted && !committed) - { + if (transacted && !committed) { session.commit(); } session.close(); - if (useSendAcks) - { + if (useSendAcks) { theLatch.await(); } } - finally - { - if (session != null) - { + finally { + if (session != null) { session.close(); } } } - private class PerfListener implements MessageHandler - { + private class PerfListener implements MessageHandler { + private final CountDownLatch countDownLatch; private final PerfParams perfParams; @@ -472,8 +408,9 @@ public abstract class PerfBase private final ClientSession session; - public PerfListener(final ClientSession session, final CountDownLatch countDownLatch, final PerfParams perfParams) - { + public PerfListener(final ClientSession session, + final CountDownLatch countDownLatch, + final PerfParams perfParams) { this.session = session; this.countDownLatch = countDownLatch; this.perfParams = perfParams; @@ -481,18 +418,13 @@ public abstract class PerfBase modulo = 2000; } - public void onMessage(final ClientMessage message) - { - try - { - if (warmingUp) - { + public void onMessage(final ClientMessage message) { + try { + if (warmingUp) { boolean committed = checkCommit(session); - if (count.incrementAndGet() == perfParams.getNoOfWarmupMessages()) - { + if (count.incrementAndGet() == perfParams.getNoOfWarmupMessages()) { PerfBase.log.info("warmed up after receiving " + count.longValue() + " msgs"); - if (!committed) - { + if (!committed) { checkCommit(session); } warmingUp = false; @@ -500,8 +432,7 @@ public abstract class PerfBase return; } - if (!started) - { + if (!started) { started = true; // reset count to take stats count.set(0); @@ -512,32 +443,25 @@ public abstract class PerfBase long currentCount = count.incrementAndGet(); boolean committed = checkCommit(session); - if (currentCount == perfParams.getNoOfMessagesToSend()) - { - if (!committed) - { + if (currentCount == perfParams.getNoOfMessagesToSend()) { + if (!committed) { checkCommit(session); } countDownLatch.countDown(); } - if (currentCount % modulo == 0) - { + if (currentCount % modulo == 0) { double duration = (1.0 * System.currentTimeMillis() - start) / 1000; PerfBase.log.info(String.format("received %6d messages in %2.2fs", currentCount, duration)); } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } - private boolean checkCommit(final ClientSession session) throws Exception - { - if (perfParams.isSessionTransacted()) - { - if (count.longValue() % perfParams.getBatchSize() == 0) - { + private boolean checkCommit(final ClientSession session) throws Exception { + if (perfParams.isSessionTransacted()) { + if (count.longValue() % perfParams.getBatchSize() == 0) { session.commit(); return true; diff --git a/examples/core/perf/src/main/java/org/apache/activemq/artemis/core/example/PerfListener.java b/examples/core/perf/src/main/java/org/apache/activemq/artemis/core/example/PerfListener.java index f5edc634a6..1ad32574e3 100644 --- a/examples/core/perf/src/main/java/org/apache/activemq/artemis/core/example/PerfListener.java +++ b/examples/core/perf/src/main/java/org/apache/activemq/artemis/core/example/PerfListener.java @@ -18,33 +18,28 @@ package org.apache.activemq.artemis.core.example; import java.util.logging.Logger; -public class PerfListener extends PerfBase -{ +public class PerfListener extends PerfBase { + private static final Logger log = Logger.getLogger(PerfListener.class.getName()); - public static void main(final String[] args) - { - try - { + public static void main(final String[] args) { + try { String fileName = PerfBase.getPerfFileName(args); PerfParams params = PerfBase.getParams(fileName); new PerfListener(params).run(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } - private PerfListener(final PerfParams perfParams) - { + private PerfListener(final PerfParams perfParams) { super(perfParams); } - public void run() throws Exception - { + public void run() throws Exception { runListener(); } diff --git a/examples/core/perf/src/main/java/org/apache/activemq/artemis/core/example/PerfParams.java b/examples/core/perf/src/main/java/org/apache/activemq/artemis/core/example/PerfParams.java index 4d5f06f8bb..933322a6e2 100644 --- a/examples/core/perf/src/main/java/org/apache/activemq/artemis/core/example/PerfParams.java +++ b/examples/core/perf/src/main/java/org/apache/activemq/artemis/core/example/PerfParams.java @@ -21,8 +21,8 @@ import java.io.Serializable; /** * Class that holds the parameters used in the performance examples */ -public class PerfParams implements Serializable -{ +public class PerfParams implements Serializable { + private static final long serialVersionUID = -4336539641012356002L; private int noOfMessagesToSend = 1000; @@ -67,234 +67,191 @@ public class PerfParams implements Serializable private boolean useSendAcks; - public boolean isBlockOnPersistent() - { + public boolean isBlockOnPersistent() { return blockOnPersistent; } - public void setBlockOnPersistent(final boolean blockOnPersistent) - { + public void setBlockOnPersistent(final boolean blockOnPersistent) { this.blockOnPersistent = blockOnPersistent; } - public boolean isBlockOnACK() - { + public boolean isBlockOnACK() { return blockOnACK; } - public void setBlockOnACK(final boolean blockOnACK) - { + public void setBlockOnACK(final boolean blockOnACK) { this.blockOnACK = blockOnACK; } - public int getNoOfMessagesToSend() - { + public int getNoOfMessagesToSend() { return noOfMessagesToSend; } - public void setNoOfMessagesToSend(final int noOfMessagesToSend) - { + public void setNoOfMessagesToSend(final int noOfMessagesToSend) { this.noOfMessagesToSend = noOfMessagesToSend; } - public int getNoOfWarmupMessages() - { + public int getNoOfWarmupMessages() { return noOfWarmupMessages; } - public void setNoOfWarmupMessages(final int noOfWarmupMessages) - { + public void setNoOfWarmupMessages(final int noOfWarmupMessages) { this.noOfWarmupMessages = noOfWarmupMessages; } - public int getMessageSize() - { + public int getMessageSize() { return messageSize; } - public void setMessageSize(final int messageSize) - { + public void setMessageSize(final int messageSize) { this.messageSize = messageSize; } - public boolean isDurable() - { + public boolean isDurable() { return durable; } - public void setDurable(final boolean durable) - { + public void setDurable(final boolean durable) { this.durable = durable; } - public boolean isSessionTransacted() - { + public boolean isSessionTransacted() { return isSessionTransacted; } - public void setSessionTransacted(final boolean sessionTransacted) - { + public void setSessionTransacted(final boolean sessionTransacted) { isSessionTransacted = sessionTransacted; } - public int getBatchSize() - { + public int getBatchSize() { return batchSize; } - public void setBatchSize(final int batchSize) - { + public void setBatchSize(final int batchSize) { this.batchSize = batchSize; } - public boolean isDrainQueue() - { + public boolean isDrainQueue() { return drainQueue; } - public void setDrainQueue(final boolean drainQueue) - { + public void setDrainQueue(final boolean drainQueue) { this.drainQueue = drainQueue; } - public String getQueueName() - { + public String getQueueName() { return queueName; } - public void setQueueName(final String queueName) - { + public void setQueueName(final String queueName) { this.queueName = queueName; } - public String getAddress() - { + public String getAddress() { return address; } - public void setAddress(final String address) - { + public void setAddress(final String address) { this.address = address; } - public int getThrottleRate() - { + public int getThrottleRate() { return throttleRate; } - public void setThrottleRate(final int throttleRate) - { + public void setThrottleRate(final int throttleRate) { this.throttleRate = throttleRate; } @Override - public String toString() - { + public String toString() { return "message to send = " + noOfMessagesToSend + - ", Durable = " + - durable + - ", session transacted = " + - isSessionTransacted + - (isSessionTransacted ? ", transaction batch size = " + batchSize : "") + - ", drain queue = " + - drainQueue + - ", queue name = " + - queueName + - ", Throttle rate = " + - throttleRate + - ", blockOnPersistent = " + - blockOnPersistent + - ". blockOnACK = " + - blockOnACK; + ", Durable = " + + durable + + ", session transacted = " + + isSessionTransacted + + (isSessionTransacted ? ", transaction batch size = " + batchSize : "") + + ", drain queue = " + + drainQueue + + ", queue name = " + + queueName + + ", Throttle rate = " + + throttleRate + + ", blockOnPersistent = " + + blockOnPersistent + + ". blockOnACK = " + + blockOnACK; } - public synchronized String getHost() - { + public synchronized String getHost() { return host; } - public synchronized void setHost(final String host) - { + public synchronized void setHost(final String host) { this.host = host; } - public synchronized int getPort() - { + public synchronized int getPort() { return port; } - public synchronized void setPort(final int port) - { + public synchronized void setPort(final int port) { this.port = port; } - public synchronized int getTcpBufferSize() - { + public synchronized int getTcpBufferSize() { return tcpBufferSize; } - public synchronized void setTcpBufferSize(final int tcpBufferSize) - { + public synchronized void setTcpBufferSize(final int tcpBufferSize) { this.tcpBufferSize = tcpBufferSize; } - public synchronized boolean isTcpNoDelay() - { + public synchronized boolean isTcpNoDelay() { return tcpNoDelay; } - public synchronized void setTcpNoDelay(final boolean tcpNoDelay) - { + public synchronized void setTcpNoDelay(final boolean tcpNoDelay) { this.tcpNoDelay = tcpNoDelay; } - public synchronized boolean isPreAck() - { + public synchronized boolean isPreAck() { return preAck; } - public synchronized void setPreAck(final boolean preAck) - { + public synchronized void setPreAck(final boolean preAck) { this.preAck = preAck; } - public synchronized int getConfirmationWindow() - { + public synchronized int getConfirmationWindow() { return confirmationWindow; } - public synchronized void setConfirmationWindow(final int confirmationWindow) - { + public synchronized void setConfirmationWindow(final int confirmationWindow) { this.confirmationWindow = confirmationWindow; } - public int getProducerWindow() - { + public int getProducerWindow() { return producerWindow; } - public void setProducerWindow(final int producerWindow) - { + public void setProducerWindow(final int producerWindow) { this.producerWindow = producerWindow; } - public int getConsumerWindow() - { + public int getConsumerWindow() { return consumerWindow; } - public void setConsumerWindow(final int consumerWindow) - { + public void setConsumerWindow(final int consumerWindow) { this.consumerWindow = consumerWindow; } - public boolean isUseSendAcks() - { + public boolean isUseSendAcks() { return useSendAcks; } - public void setUseSendAcks(boolean useSendAcks) - { + public void setUseSendAcks(boolean useSendAcks) { this.useSendAcks = useSendAcks; } } diff --git a/examples/core/perf/src/main/java/org/apache/activemq/artemis/core/example/PerfSender.java b/examples/core/perf/src/main/java/org/apache/activemq/artemis/core/example/PerfSender.java index c423eb1943..4fed6b5606 100644 --- a/examples/core/perf/src/main/java/org/apache/activemq/artemis/core/example/PerfSender.java +++ b/examples/core/perf/src/main/java/org/apache/activemq/artemis/core/example/PerfSender.java @@ -18,33 +18,28 @@ package org.apache.activemq.artemis.core.example; import java.util.logging.Logger; -public class PerfSender extends PerfBase -{ +public class PerfSender extends PerfBase { + private static final Logger log = Logger.getLogger(PerfSender.class.getName()); - public static void main(final String[] args) - { - try - { + public static void main(final String[] args) { + try { String fileName = PerfBase.getPerfFileName(args); PerfParams params = PerfBase.getParams(fileName); new PerfSender(params).run(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } - private PerfSender(final PerfParams perfParams) - { + private PerfSender(final PerfParams perfParams) { super(perfParams); } - public void run() throws Exception - { + public void run() throws Exception { runSender(); } diff --git a/examples/core/vertx-connector/src/main/java/org/apache/activemq/artemis/core/example/ExampleVerticle.java b/examples/core/vertx-connector/src/main/java/org/apache/activemq/artemis/core/example/ExampleVerticle.java index 9d54f5d818..50a8f7918b 100644 --- a/examples/core/vertx-connector/src/main/java/org/apache/activemq/artemis/core/example/ExampleVerticle.java +++ b/examples/core/vertx-connector/src/main/java/org/apache/activemq/artemis/core/example/ExampleVerticle.java @@ -24,36 +24,31 @@ import org.vertx.java.core.eventbus.EventBus; import org.vertx.java.core.eventbus.Message; import org.vertx.java.platform.Verticle; -public class ExampleVerticle extends Verticle -{ +public class ExampleVerticle extends Verticle { + @Override - public void start() - { + public void start() { EventBus eventBus = vertx.eventBus(); final CountDownLatch latch0 = new CountDownLatch(1); // Register a handler on the outgoing connector's address - eventBus.registerHandler(VertxConnectorExample.OUTGOING, - new Handler>() { - @Override - public void handle(Message startMsg) - { - Object body = startMsg.body(); - System.out.println("Verticle receives a message: " + body); - VertxConnectorExample.result.set(VertxConnectorExample.MSG.equals(body)); - latch0.countDown(); - //Tell the example to finish. - VertxConnectorExample.latch.countDown(); - } - }); + eventBus.registerHandler(VertxConnectorExample.OUTGOING, new Handler>() { + @Override + public void handle(Message startMsg) { + Object body = startMsg.body(); + System.out.println("Verticle receives a message: " + body); + VertxConnectorExample.result.set(VertxConnectorExample.MSG.equals(body)); + latch0.countDown(); + //Tell the example to finish. + VertxConnectorExample.latch.countDown(); + } + }); - try - { + try { latch0.await(5000, TimeUnit.MILLISECONDS); } - catch (InterruptedException e) - { + catch (InterruptedException e) { } } } diff --git a/examples/core/vertx-connector/src/main/java/org/apache/activemq/artemis/core/example/VertxConnectorExample.java b/examples/core/vertx-connector/src/main/java/org/apache/activemq/artemis/core/example/VertxConnectorExample.java index 4f2646fe5b..2194e3051d 100644 --- a/examples/core/vertx-connector/src/main/java/org/apache/activemq/artemis/core/example/VertxConnectorExample.java +++ b/examples/core/vertx-connector/src/main/java/org/apache/activemq/artemis/core/example/VertxConnectorExample.java @@ -31,8 +31,8 @@ import org.vertx.java.spi.cluster.impl.hazelcast.HazelcastClusterManagerFactory; /** * A simple example of using Vert.x connector service. */ -public class VertxConnectorExample -{ +public class VertxConnectorExample { + public static final String INCOMING = "incoming.vertx.address"; public static final String OUTGOING = "outgoing.vertx.address"; public static final String MSG = "Welcome to Vertx world!"; @@ -43,14 +43,11 @@ public class VertxConnectorExample private static final String HOST = "127.0.0.1"; private static final int PORT = 0; - public static void main(final String[] args) throws Exception - { - System.setProperty("vertx.clusterManagerFactory", - HazelcastClusterManagerFactory.class.getName()); + public static void main(final String[] args) throws Exception { + System.setProperty("vertx.clusterManagerFactory", HazelcastClusterManagerFactory.class.getName()); PlatformManager platformManager = null; - try - { + try { // Step 1 Create a Vert.x PlatformManager platformManager = PlatformLocator.factory.createPlatformManager(PORT, HOST); @@ -58,20 +55,17 @@ public class VertxConnectorExample // Step 2 Deploy a Verticle to receive message String verticle = "org.apache.activemq.artemis.core.example.ExampleVerticle"; - platformManager.deployVerticle(verticle, null, new URL[0], 1, null, - new Handler>(){ + platformManager.deployVerticle(verticle, null, new URL[0], 1, null, new Handler>() { - @Override - public void handle(AsyncResult result) - { - if (!result.succeeded()) - { - throw new RuntimeException("failed to deploy verticle", result.cause()); - } - latch0.countDown(); - } + @Override + public void handle(AsyncResult result) { + if (!result.succeeded()) { + throw new RuntimeException("failed to deploy verticle", result.cause()); + } + latch0.countDown(); + } - }); + }); latch0.await(); @@ -82,10 +76,8 @@ public class VertxConnectorExample // Step 4 Waiting for the Verticle to process the message latch.await(10000, TimeUnit.MILLISECONDS); } - finally - { - if(platformManager != null) - { + finally { + if (platformManager != null) { platformManager.undeployAll(null); platformManager.stop(); } @@ -93,18 +85,15 @@ public class VertxConnectorExample } } - private static void reportResultAndExit() - { - if (!result.get()) - { + private static void reportResultAndExit() { + if (!result.get()) { System.err.println(); System.err.println("#####################"); System.err.println("### FAILURE! ###"); System.err.println("#####################"); System.exit(1); } - else - { + else { System.out.println(); System.out.println("#####################"); System.out.println("### SUCCESS! ###"); diff --git a/examples/jms/aerogear/src/main/java/org/apache/activemq/artemis/jms/example/AerogearExample.java b/examples/jms/aerogear/src/main/java/org/apache/activemq/artemis/jms/example/AerogearExample.java index 346b8a1cb3..b412d8773a 100644 --- a/examples/jms/aerogear/src/main/java/org/apache/activemq/artemis/jms/example/AerogearExample.java +++ b/examples/jms/aerogear/src/main/java/org/apache/activemq/artemis/jms/example/AerogearExample.java @@ -27,22 +27,20 @@ import javax.naming.InitialContext; /** * A simple JMS Queue example that creates a producer and consumer on a queue and sends then receives a message. */ -public class AerogearExample -{ - public static void main(final String[] args) throws Exception - { +public class AerogearExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Perfom a lookup on the queue - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 3. Perform a lookup on the Connection Factory - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4.Create a JMS Connection connection = cf.createConnection(); @@ -66,15 +64,12 @@ public class AerogearExample System.in.read(); } - finally - { + finally { // Step 12. Be sure to close our JMS resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } diff --git a/examples/jms/application-layer-failover/src/main/java/org/apache/activemq/artemis/jms/example/ApplicationLayerFailoverExample.java b/examples/jms/application-layer-failover/src/main/java/org/apache/activemq/artemis/jms/example/ApplicationLayerFailoverExample.java index 86a23390e0..2d0dc0c8de 100644 --- a/examples/jms/application-layer-failover/src/main/java/org/apache/activemq/artemis/jms/example/ApplicationLayerFailoverExample.java +++ b/examples/jms/application-layer-failover/src/main/java/org/apache/activemq/artemis/jms/example/ApplicationLayerFailoverExample.java @@ -37,8 +37,8 @@ import org.apache.activemq.artemis.util.ServerUtil; * A simple example that demonstrates application-layer failover of the JMS connection from one node to another * when the live server crashes */ -public class ApplicationLayerFailoverExample -{ +public class ApplicationLayerFailoverExample { + private static InitialContext initialContext; private static Connection connection; @@ -55,10 +55,8 @@ public class ApplicationLayerFailoverExample private static Process server1; - public static void main(final String[] args) throws Exception - { - try - { + public static void main(final String[] args) throws Exception { + try { server0 = ServerUtil.startServer(args[0], ApplicationLayerFailoverExample.class.getSimpleName() + "0", 0, 5000); server1 = ServerUtil.startServer(args[1], ApplicationLayerFailoverExample.class.getSimpleName() + "1", 1, 5000); @@ -75,8 +73,7 @@ public class ApplicationLayerFailoverExample final int numMessages = 10; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session.createTextMessage("This is text message " + i); producer.send(message); @@ -86,9 +83,8 @@ public class ApplicationLayerFailoverExample // Step 4. We consume those messages on server 1. - for (int i = 0; i < numMessages; i++) - { - TextMessage message0 = (TextMessage)consumer.receive(5000); + for (int i = 0; i < numMessages; i++) { + TextMessage message0 = (TextMessage) consumer.receive(5000); System.out.println("Got message: " + message0.getText()); } @@ -108,8 +104,7 @@ public class ApplicationLayerFailoverExample // Step 8. We now send some more messages - for (int i = numMessages; i < numMessages * 2; i++) - { + for (int i = numMessages; i < numMessages * 2; i++) { TextMessage message = session.createTextMessage("This is text message " + i); producer.send(message); @@ -119,19 +114,16 @@ public class ApplicationLayerFailoverExample // Step 9. And consume them. - for (int i = 0; i < numMessages; i++) - { - TextMessage message0 = (TextMessage)consumer.receive(5000); + for (int i = 0; i < numMessages; i++) { + TextMessage message0 = (TextMessage) consumer.receive(5000); System.out.println("Got message: " + message0.getText()); } } - catch(Throwable t) - { + catch (Throwable t) { t.printStackTrace(); } - finally - { + finally { // Step 14. Be sure to close our resources! closeResources(); ServerUtil.killServer(server0); @@ -139,8 +131,7 @@ public class ApplicationLayerFailoverExample } } - private static void createJMSObjects(final int server) throws Exception - { + private static void createJMSObjects(final int server) throws Exception { // Step 1. Instantiate a JMS Connection Factory object from JNDI on server 1 ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://127.0.0.1:" + (61616 + server)); @@ -163,49 +154,37 @@ public class ApplicationLayerFailoverExample producer = session.createProducer(queue); } - private static void closeResources() - { - if (initialContext != null) - { - try - { + private static void closeResources() { + if (initialContext != null) { + try { initialContext.close(); } - catch (NamingException e) - { + catch (NamingException e) { e.printStackTrace(); } } - if (connection != null) - { - try - { + if (connection != null) { + try { connection.close(); } - catch (JMSException e) - { + catch (JMSException e) { e.printStackTrace(); } } } - private static class ExampleListener implements ExceptionListener - { - public void onException(final JMSException exception) - { - try - { + private static class ExampleListener implements ExceptionListener { + + public void onException(final JMSException exception) { + try { connection.close(); } - catch (JMSException e) - { + catch (JMSException e) { //ignore } - for(int i = 0; i < 10; i++) - { - try - { + for (int i = 0; i < 10; i++) { + try { // Step 7. The ExceptionListener gets called and we recreate the JMS objects on the new node System.out.println("Connection failure has been detected on a the client."); @@ -226,15 +205,12 @@ public class ApplicationLayerFailoverExample return; } - catch (Exception e) - { + catch (Exception e) { System.out.println("Failed to handle failover, trying again."); - try - { + try { Thread.sleep(500); } - catch (InterruptedException e1) - { + catch (InterruptedException e1) { //ignored } } diff --git a/examples/jms/bridge/src/main/java/org/apache/activemq/artemis/jms/example/BridgeExample.java b/examples/jms/bridge/src/main/java/org/apache/activemq/artemis/jms/example/BridgeExample.java index a4a165c0ec..0fa17c2710 100644 --- a/examples/jms/bridge/src/main/java/org/apache/activemq/artemis/jms/example/BridgeExample.java +++ b/examples/jms/bridge/src/main/java/org/apache/activemq/artemis/jms/example/BridgeExample.java @@ -30,10 +30,9 @@ import java.util.Hashtable; * This example demonstrates a core bridge set-up between two nodes, consuming messages from a queue * on one node and forwarding them to an address on the second node. */ -public class BridgeExample -{ - public static void main(final String[] args) throws Exception - { +public class BridgeExample { + + public static void main(final String[] args) throws Exception { Connection connection0 = null; Connection connection1 = null; @@ -42,8 +41,7 @@ public class BridgeExample InitialContext ic1 = null; - try - { + try { // Step 1 - we create an initial context for looking up JNDI on node 0 Hashtable properties = new Hashtable(); @@ -54,11 +52,11 @@ public class BridgeExample // Step 2 - we look up the sausage-factory queue from node 0 - Queue sausageFactory = (Queue)ic0.lookup("queue/sausage-factory"); + Queue sausageFactory = (Queue) ic0.lookup("queue/sausage-factory"); // Step 3 - we look up a JMS ConnectionFactory object from node 0 - ConnectionFactory cf0 = (ConnectionFactory)ic0.lookup("ConnectionFactory"); + ConnectionFactory cf0 = (ConnectionFactory) ic0.lookup("ConnectionFactory"); // Step 4 - we create an initial context for looking up JNDI on node 1 @@ -70,11 +68,11 @@ public class BridgeExample // Step 5 - we look up the mincing-machine queue on node 1 - Queue mincingMachine = (Queue)ic1.lookup("queue/mincing-machine"); + Queue mincingMachine = (Queue) ic1.lookup("queue/mincing-machine"); // Step 6 - we look up a JMS ConnectionFactory object from node 1 - ConnectionFactory cf1 = (ConnectionFactory)ic1.lookup("ConnectionFactory"); + ConnectionFactory cf1 = (ConnectionFactory) ic1.lookup("ConnectionFactory"); // Step 7. We create a JMS Connection connection0 which is a connection to server 0 @@ -112,9 +110,9 @@ public class BridgeExample producer.send(message); System.out.println("Sent " + message.getStringProperty("name") + - " message with " + - message.getStringProperty("hat") + - " hat to sausage-factory on node 0"); + " message with " + + message.getStringProperty("hat") + + " hat to sausage-factory on node 0"); // Step 14 - we successfully receive the aardvark message from the mincing-machine one node 1. The aardvark's // hat is now blue since it has been transformed! @@ -122,9 +120,9 @@ public class BridgeExample Message receivedMessage = consumer.receive(5000); System.out.println("Received " + receivedMessage.getStringProperty("name") + - " message with " + - receivedMessage.getStringProperty("hat") + - " hat from mincing-machine on node 1"); + " message with " + + receivedMessage.getStringProperty("hat") + + " hat from mincing-machine on node 1"); // Step 13. We create and send another message, this time representing a sasquatch with a mauve hat to the // sausage-factory on node 0. This won't be bridged to the mincing-machine since we only want aardvarks, not @@ -139,44 +137,37 @@ public class BridgeExample producer.send(message); System.out.println("Sent " + message.getStringProperty("name") + - " message with " + - message.getStringProperty("hat") + - " hat to sausage-factory on node 0"); + " message with " + + message.getStringProperty("hat") + + " hat to sausage-factory on node 0"); // Step 14. We don't receive the message since it has not been bridged. receivedMessage = consumer.receive(1000); - if (receivedMessage == null) - { + if (receivedMessage == null) { System.out.println("Didn't receive that message from mincing-machine on node 1"); } - else - { + else { throw new IllegalStateException(); } } - finally - { + finally { // Step 15. Be sure to close our resources! - if (connection0 != null) - { + if (connection0 != null) { connection0.close(); } - if (connection1 != null) - { + if (connection1 != null) { connection1.close(); } - if (ic0 != null) - { + if (ic0 != null) { ic0.close(); } - if (ic1 != null) - { + if (ic1 != null) { ic1.close(); } } diff --git a/examples/jms/bridge/src/main/java/org/apache/activemq/artemis/jms/example/HatColourChangeTransformer.java b/examples/jms/bridge/src/main/java/org/apache/activemq/artemis/jms/example/HatColourChangeTransformer.java index f68cd44555..ae8cf39b6e 100644 --- a/examples/jms/bridge/src/main/java/org/apache/activemq/artemis/jms/example/HatColourChangeTransformer.java +++ b/examples/jms/bridge/src/main/java/org/apache/activemq/artemis/jms/example/HatColourChangeTransformer.java @@ -20,10 +20,9 @@ import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.server.ServerMessage; import org.apache.activemq.artemis.core.server.cluster.Transformer; -public class HatColourChangeTransformer implements Transformer -{ - public ServerMessage transform(final ServerMessage message) - { +public class HatColourChangeTransformer implements Transformer { + + public ServerMessage transform(final ServerMessage message) { SimpleString propName = new SimpleString("hat"); SimpleString oldProp = message.getSimpleStringProperty(propName); diff --git a/examples/jms/browser/src/main/java/org/apache/activemq/artemis/jms/example/QueueBrowserExample.java b/examples/jms/browser/src/main/java/org/apache/activemq/artemis/jms/example/QueueBrowserExample.java index d7f060c830..1c9db3b469 100644 --- a/examples/jms/browser/src/main/java/org/apache/activemq/artemis/jms/example/QueueBrowserExample.java +++ b/examples/jms/browser/src/main/java/org/apache/activemq/artemis/jms/example/QueueBrowserExample.java @@ -30,25 +30,22 @@ import java.util.Enumeration; /** * A simple example which shows how to use a QueueBrowser to look at messages of a queue without removing them from the queue */ -public class QueueBrowserExample -{ - public static void main(final String[] args) throws Exception - { +public class QueueBrowserExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Perfom a lookup on the queue - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 3. Perform a lookup on the Connection Factory // you could alternatively instantiate the connection directly // ConnectionFactory cf = new ActiveMQConnectionFactory(); // this would accept the broker URI as well - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); - + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4. Create a JMS Connection connection = cf.createConnection(); @@ -73,9 +70,8 @@ public class QueueBrowserExample // Step 10. Browse the messages on the queue // Browsing a queue does not remove the messages from the queue Enumeration messageEnum = browser.getEnumeration(); - while (messageEnum.hasMoreElements()) - { - TextMessage message = (TextMessage)messageEnum.nextElement(); + while (messageEnum.hasMoreElements()) { + TextMessage message = (TextMessage) messageEnum.nextElement(); System.out.println("Browsing: " + message.getText()); } @@ -89,20 +85,17 @@ public class QueueBrowserExample connection.start(); // Step 14. Receive the 2 messages - TextMessage messageReceived = (TextMessage)messageConsumer.receive(5000); + TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000); System.out.println("Received message: " + messageReceived.getText()); - messageReceived = (TextMessage)messageConsumer.receive(5000); + messageReceived = (TextMessage) messageConsumer.receive(5000); System.out.println("Received message: " + messageReceived.getText()); } - finally - { + finally { // Step 15. Be sure to close our JMS resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } diff --git a/examples/jms/client-kickoff/src/main/java/org/apache/activemq/artemis/jms/example/ClientKickoffExample.java b/examples/jms/client-kickoff/src/main/java/org/apache/activemq/artemis/jms/example/ClientKickoffExample.java index 54217390a0..a0b3a7ed6a 100644 --- a/examples/jms/client-kickoff/src/main/java/org/apache/activemq/artemis/jms/example/ClientKickoffExample.java +++ b/examples/jms/client-kickoff/src/main/java/org/apache/activemq/artemis/jms/example/ClientKickoffExample.java @@ -37,32 +37,28 @@ import org.apache.activemq.artemis.api.core.management.ObjectNameBuilder; /** * An example that shows how to kick off a client connected to ActiveMQ Artemis by using JMX. */ -public class ClientKickoffExample -{ +public class ClientKickoffExample { + private static final String JMX_URL = "service:jmx:rmi:///jndi/rmi://localhost:3000/jmxrmi"; - public static void main(final String[] args) throws Exception - { + public static void main(final String[] args) throws Exception { QueueConnection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Perform a lookup on the Connection Factory - QueueConnectionFactory cf = (QueueConnectionFactory)initialContext.lookup("ConnectionFactory"); + QueueConnectionFactory cf = (QueueConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 3.Create a JMS Connection connection = cf.createQueueConnection(); // Step 4. Set an exception listener on the connection to be notified after a problem occurred final AtomicReference exception = new AtomicReference(); - connection.setExceptionListener(new ExceptionListener() - { + connection.setExceptionListener(new ExceptionListener() { @Override - public void onException(final JMSException e) - { + public void onException(final JMSException e) { exception.set(e); } }); @@ -74,17 +70,13 @@ public class ClientKickoffExample ObjectName on = ObjectNameBuilder.DEFAULT.getActiveMQServerObjectName(); JMXConnector connector = JMXConnectorFactory.connect(new JMXServiceURL(JMX_URL), new HashMap()); MBeanServerConnection mbsc = connector.getMBeanServerConnection(); - ActiveMQServerControl serverControl = MBeanServerInvocationHandler.newProxyInstance(mbsc, - on, - ActiveMQServerControl.class, - false); + ActiveMQServerControl serverControl = MBeanServerInvocationHandler.newProxyInstance(mbsc, on, ActiveMQServerControl.class, false); // Step 7. List the remote address connected to the server System.out.println("List of remote addresses connected to the server:"); System.out.println("----------------------------------"); String[] remoteAddresses = serverControl.listRemoteAddresses(); - for (String remoteAddress : remoteAddresses) - { + for (String remoteAddress : remoteAddresses) { System.out.println(remoteAddress); } System.out.println("----------------------------------"); @@ -102,15 +94,12 @@ public class ClientKickoffExample exception.get().printStackTrace(); System.err.println("----------------------------------"); } - finally - { + finally { // Step 10. Be sure to close the resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } diff --git a/examples/jms/client-side-failoverlistener/src/main/java/org/apache/activemq/artemis/jms/example/ClientSideFailoverListerExample.java b/examples/jms/client-side-failoverlistener/src/main/java/org/apache/activemq/artemis/jms/example/ClientSideFailoverListerExample.java index 006613930d..4dcfd87750 100644 --- a/examples/jms/client-side-failoverlistener/src/main/java/org/apache/activemq/artemis/jms/example/ClientSideFailoverListerExample.java +++ b/examples/jms/client-side-failoverlistener/src/main/java/org/apache/activemq/artemis/jms/example/ClientSideFailoverListerExample.java @@ -36,20 +36,18 @@ import javax.naming.InitialContext; * In this example there are two nodes running in a cluster, both server will be running for start, * but after a while the first server will crash. This will trigger a fail-over event */ -public class ClientSideFailoverListerExample -{ +public class ClientSideFailoverListerExample { + private static Process server0; private static Process server1; - public static void main(final String[] args) throws Exception - { + public static void main(final String[] args) throws Exception { InitialContext initialContext = null; Connection connectionA = null; - try - { + try { server0 = ServerUtil.startServer(args[0], ClientSideFailoverListerExample.class.getSimpleName() + "0", 0, 5000); server1 = ServerUtil.startServer(args[1], ClientSideFailoverListerExample.class.getSimpleName() + "1", 1, 0); @@ -77,8 +75,7 @@ public class ClientSideFailoverListerExample // Step 7. We send some messages on each producer final int numMessages = 10; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage messageA = sessionA.createTextMessage("A:This is text message " + i); producerA.send(messageA); System.out.println("Sent message: " + messageA.getText()); @@ -92,17 +89,14 @@ public class ClientSideFailoverListerExample // We reached message no 5 the first server will crash consume(sessionA, queue, numMessages, "A"); } - finally - { + finally { // Step 10. Be sure to close our resources! - if (connectionA != null) - { + if (connectionA != null) { connectionA.close(); } - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } @@ -111,16 +105,13 @@ public class ClientSideFailoverListerExample } } - private static void consume(Session session, Queue queue, int numMessages, String node) throws Exception - { + private static void consume(Session session, Queue queue, int numMessages, String node) throws Exception { MessageConsumer consumer = session.createConsumer(queue); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = (TextMessage) consumer.receive(2000); System.out.println("Got message: " + message.getText() + " from node " + node); - if (i == 5) - { + if (i == 5) { ServerUtil.killServer(server0); } } @@ -129,10 +120,9 @@ public class ClientSideFailoverListerExample } - private static class FailoverListenerImpl implements FailoverEventListener - { - public void failoverEvent(FailoverEventType eventType) - { + private static class FailoverListenerImpl implements FailoverEventListener { + + public void failoverEvent(FailoverEventType eventType) { System.out.println("Failover event triggered :" + eventType.toString()); } } diff --git a/examples/jms/client-side-load-balancing/src/main/java/org/apache/activemq/artemis/jms/example/ClientSideLoadBalancingExample.java b/examples/jms/client-side-load-balancing/src/main/java/org/apache/activemq/artemis/jms/example/ClientSideLoadBalancingExample.java index 688ba5aa57..1281017797 100644 --- a/examples/jms/client-side-load-balancing/src/main/java/org/apache/activemq/artemis/jms/example/ClientSideLoadBalancingExample.java +++ b/examples/jms/client-side-load-balancing/src/main/java/org/apache/activemq/artemis/jms/example/ClientSideLoadBalancingExample.java @@ -33,26 +33,24 @@ import javax.naming.InitialContext; * In this example there are three nodes and we use a round-robin client side load-balancing * policy. */ -public class ClientSideLoadBalancingExample -{ - public static void main(final String[] args) throws Exception - { +public class ClientSideLoadBalancingExample { + + public static void main(final String[] args) throws Exception { InitialContext initialContext = null; Connection connectionA = null; Connection connectionB = null; Connection connectionC = null; - try - { + try { // Step 1. Get an initial context for looking up JNDI from server 0 initialContext = new InitialContext(); // Step 2. Look-up the JMS Queue object from JNDI - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 3. Look-up a JMS Connection Factory object from JNDI on server 0 - ConnectionFactory connectionFactory = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory connectionFactory = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4. We create 3 JMS connections from the same connection factory. Since we are using round-robin // load-balancing this should result in each sessions being connected to a different node of the cluster @@ -69,9 +67,9 @@ public class ClientSideLoadBalancingExample Session sessionB = connectionB.createSession(false, Session.AUTO_ACKNOWLEDGE); Session sessionC = connectionC.createSession(false, Session.AUTO_ACKNOWLEDGE); - System.out.println("Session A - " + ((org.apache.activemq.artemis.core.client.impl.DelegatingSession) ((org.apache.activemq.artemis.jms.client.ActiveMQSession) sessionA).getCoreSession()).getConnection().getRemoteAddress() ); - System.out.println("Session B - " + ((org.apache.activemq.artemis.core.client.impl.DelegatingSession) ((org.apache.activemq.artemis.jms.client.ActiveMQSession) sessionB).getCoreSession()).getConnection().getRemoteAddress() ); - System.out.println("Session C - " + ((org.apache.activemq.artemis.core.client.impl.DelegatingSession) ((org.apache.activemq.artemis.jms.client.ActiveMQSession) sessionC).getCoreSession()).getConnection().getRemoteAddress() ); + System.out.println("Session A - " + ((org.apache.activemq.artemis.core.client.impl.DelegatingSession) ((org.apache.activemq.artemis.jms.client.ActiveMQSession) sessionA).getCoreSession()).getConnection().getRemoteAddress()); + System.out.println("Session B - " + ((org.apache.activemq.artemis.core.client.impl.DelegatingSession) ((org.apache.activemq.artemis.jms.client.ActiveMQSession) sessionB).getCoreSession()).getConnection().getRemoteAddress()); + System.out.println("Session C - " + ((org.apache.activemq.artemis.core.client.impl.DelegatingSession) ((org.apache.activemq.artemis.jms.client.ActiveMQSession) sessionC).getCoreSession()).getConnection().getRemoteAddress()); // Step 6. We create JMS MessageProducer objects on the sessions MessageProducer producerA = sessionA.createProducer(queue); @@ -81,8 +79,7 @@ public class ClientSideLoadBalancingExample // Step 7. We send some messages on each producer final int numMessages = 10; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage messageA = sessionA.createTextMessage("A:This is text message " + i); producerA.send(messageA); System.out.println("Sent message: " + messageA.getText()); @@ -109,37 +106,30 @@ public class ClientSideLoadBalancingExample consume(sessionB, queue, numMessages, "B"); consume(sessionC, queue, numMessages, "C"); } - finally - { + finally { // Step 10. Be sure to close our resources! - if (connectionA != null) - { + if (connectionA != null) { connectionA.close(); } - if (connectionB != null) - { + if (connectionB != null) { connectionB.close(); } - if (connectionC != null) - { + if (connectionC != null) { connectionC.close(); } - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } } } - private static void consume(Session session, Queue queue, int numMessages, String node) throws JMSException - { + private static void consume(Session session, Queue queue, int numMessages, String node) throws JMSException { MessageConsumer consumer = session.createConsumer(queue); - for (int i = 0; i < numMessages; i++) - { - TextMessage message = (TextMessage)consumer.receive(2000); + for (int i = 0; i < numMessages; i++) { + TextMessage message = (TextMessage) consumer.receive(2000); System.out.println("Got message: " + message.getText() + " from node " + node); } diff --git a/examples/jms/clustered-durable-subscription/src/main/java/org/apache/activemq/artemis/jms/example/ClusteredDurableSubscriptionExample.java b/examples/jms/clustered-durable-subscription/src/main/java/org/apache/activemq/artemis/jms/example/ClusteredDurableSubscriptionExample.java index 2dceb7c5fb..f8803e1e28 100644 --- a/examples/jms/clustered-durable-subscription/src/main/java/org/apache/activemq/artemis/jms/example/ClusteredDurableSubscriptionExample.java +++ b/examples/jms/clustered-durable-subscription/src/main/java/org/apache/activemq/artemis/jms/example/ClusteredDurableSubscriptionExample.java @@ -34,16 +34,14 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; * The same durable subscription can exist on more than one node of the cluster, and messages * sent to the topic will be load-balanced in a round-robin fashion between the two nodes */ -public class ClusteredDurableSubscriptionExample -{ - public static void main(final String[] args) throws Exception - { +public class ClusteredDurableSubscriptionExample { + + public static void main(final String[] args) throws Exception { Connection connection0 = null; Connection connection1 = null; - try - { + try { // Step 1. Instantiate the connection factory on server 0 ConnectionFactory cf0 = new ActiveMQConnectionFactory("tcp://localhost:61616"); @@ -96,8 +94,7 @@ public class ClusteredDurableSubscriptionExample final int numMessages = 10; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session0.createTextMessage("This is text message " + i); producer.send(message); @@ -111,27 +108,23 @@ public class ClusteredDurableSubscriptionExample // The "logical" subscription is distributed across the cluster and contains exactly one copy of all the // messages - for (int i = 0; i < numMessages; i += 2) - { - TextMessage message0 = (TextMessage)subscriber0.receive(5000); + for (int i = 0; i < numMessages; i += 2) { + TextMessage message0 = (TextMessage) subscriber0.receive(5000); System.out.println("Got message: " + message0.getText() + " from node 0"); - TextMessage message1 = (TextMessage)subscriber1.receive(5000); + TextMessage message1 = (TextMessage) subscriber1.receive(5000); System.out.println("Got message: " + message1.getText() + " from node 1"); } } - finally - { + finally { // Step 15. Be sure to close our JMS resources! - if (connection0 != null) - { + if (connection0 != null) { connection0.close(); } - if (connection1 != null) - { + if (connection1 != null) { connection1.close(); } } diff --git a/examples/jms/clustered-grouping/src/main/java/org/apache/activemq/artemis/jms/example/ClusteredGroupingExample.java b/examples/jms/clustered-grouping/src/main/java/org/apache/activemq/artemis/jms/example/ClusteredGroupingExample.java index 04fec83a47..a64e33ab8f 100644 --- a/examples/jms/clustered-grouping/src/main/java/org/apache/activemq/artemis/jms/example/ClusteredGroupingExample.java +++ b/examples/jms/clustered-grouping/src/main/java/org/apache/activemq/artemis/jms/example/ClusteredGroupingExample.java @@ -32,21 +32,19 @@ import org.apache.activemq.artemis.jms.client.ActiveMQQueue; * A simple example that demonstrates server side load-balancing of messages between the queue instances on different * nodes of the cluster. */ -public class ClusteredGroupingExample -{ - public static void main(String[] args) throws Exception - { +public class ClusteredGroupingExample { + + public static void main(String[] args) throws Exception { Connection connection0 = null; Connection connection1 = null; Connection connection2 = null; - try - { + try { // Step 1. We will instantiate the queue object directly on this example // This could be done through JNDI or JMSession.createQueue - Queue queue = ActiveMQJMSClient.createQueue("exampleQueue"); + Queue queue = ActiveMQJMSClient.createQueue("exampleQueue"); // Step 2. create a connection factory towards server 0. ConnectionFactory cf0 = new ActiveMQConnectionFactory("tcp://localhost:61616"); @@ -85,7 +83,6 @@ public class ClusteredGroupingExample // Step 12. We create JMS MessageConsumer objects on server 0 MessageConsumer consumer = session0.createConsumer(queue); - // Step 13. We create a JMS MessageProducer object on server 0, 1 and 2 MessageProducer producer0 = session0.createProducer(queue); @@ -97,8 +94,7 @@ public class ClusteredGroupingExample final int numMessages = 10; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session0.createTextMessage("This is text message " + i); message.setStringProperty("JMSXGroupID", "Group-0"); @@ -108,8 +104,7 @@ public class ClusteredGroupingExample System.out.println("Sent messages: " + message.getText() + " to node 0"); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session1.createTextMessage("This is text message " + (i + 10)); message.setStringProperty("JMSXGroupID", "Group-0"); @@ -120,8 +115,7 @@ public class ClusteredGroupingExample } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session2.createTextMessage("This is text message " + (i + 20)); message.setStringProperty("JMSXGroupID", "Group-0"); @@ -134,30 +128,25 @@ public class ClusteredGroupingExample // Step 15. We now consume those messages from server 0 // We note the messages have all been sent to the same consumer on the same node - for (int i = 0; i < numMessages * 3; i++) - { - TextMessage message0 = (TextMessage)consumer.receive(5000); + for (int i = 0; i < numMessages * 3; i++) { + TextMessage message0 = (TextMessage) consumer.receive(5000); System.out.println("Got message: " + message0.getText() + " from node 0"); } } - finally - { + finally { // Step 17. Be sure to close our resources! - if (connection0 != null) - { + if (connection0 != null) { connection0.close(); } - if (connection1 != null) - { + if (connection1 != null) { connection1.close(); } - if (connection2 != null) - { + if (connection2 != null) { connection2.close(); } } diff --git a/examples/jms/clustered-jgroups/src/main/java/org/apache/activemq/artemis/jms/example/ClusteredJgroupsExample.java b/examples/jms/clustered-jgroups/src/main/java/org/apache/activemq/artemis/jms/example/ClusteredJgroupsExample.java index 532161890d..f8016b1fb7 100644 --- a/examples/jms/clustered-jgroups/src/main/java/org/apache/activemq/artemis/jms/example/ClusteredJgroupsExample.java +++ b/examples/jms/clustered-jgroups/src/main/java/org/apache/activemq/artemis/jms/example/ClusteredJgroupsExample.java @@ -29,10 +29,9 @@ import java.util.Hashtable; /** * A simple example that demonstrates clustering using jgroups. */ -public class ClusteredJgroupsExample -{ - public static void main(final String[] args) throws Exception - { +public class ClusteredJgroupsExample { + + public static void main(final String[] args) throws Exception { Connection connection0 = null; Connection connection1 = null; @@ -41,8 +40,7 @@ public class ClusteredJgroupsExample InitialContext ic1 = null; - try - { + try { // Step 1. Get an initial context for looking up JNDI from server 0 Hashtable properties = new Hashtable(); properties.put("java.naming.factory.initial", "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory"); @@ -51,10 +49,10 @@ public class ClusteredJgroupsExample ic0 = new InitialContext(properties); // Step 2. Look-up the JMS Queue object from JNDI - Queue queue = (Queue)ic0.lookup("queue/exampleQueue"); + Queue queue = (Queue) ic0.lookup("queue/exampleQueue"); // Step 3. Look-up a JMS Connection Factory object from JNDI on server 0 - ConnectionFactory cf0 = (ConnectionFactory)ic0.lookup("ConnectionFactory"); + ConnectionFactory cf0 = (ConnectionFactory) ic0.lookup("ConnectionFactory"); // Step 4. Get an initial context for looking up JNDI from server 1 properties = new Hashtable(); @@ -63,7 +61,7 @@ public class ClusteredJgroupsExample ic1 = new InitialContext(properties); // Step 5. Look-up a JMS Connection Factory object from JNDI on server 1 - ConnectionFactory cf1 = (ConnectionFactory)ic1.lookup("ConnectionFactory"); + ConnectionFactory cf1 = (ConnectionFactory) ic1.lookup("ConnectionFactory"); // Step 6. We create a JMS Connection connection0 which is a connection to server 0 connection0 = cf0.createConnection(); @@ -96,8 +94,7 @@ public class ClusteredJgroupsExample final int numMessages = 10; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session0.createTextMessage("This is text message " + i); producer.send(message); @@ -110,38 +107,32 @@ public class ClusteredJgroupsExample // JMS Queues implement point-to-point message where each message is only ever consumed by a // maximum of one consumer - for (int i = 0; i < numMessages; i += 2) - { - TextMessage message0 = (TextMessage)consumer0.receive(5000); + for (int i = 0; i < numMessages; i += 2) { + TextMessage message0 = (TextMessage) consumer0.receive(5000); System.out.println("Got message: " + message0.getText() + " from node 0"); - TextMessage message1 = (TextMessage)consumer1.receive(5000); + TextMessage message1 = (TextMessage) consumer1.receive(5000); System.out.println("Got message: " + message1.getText() + " from node 1"); } } - finally - { + finally { // Step 15. Be sure to close our resources! - if (connection0 != null) - { + if (connection0 != null) { connection0.close(); } - if (connection1 != null) - { + if (connection1 != null) { connection1.close(); } - if (ic0 != null) - { + if (ic0 != null) { ic0.close(); } - if (ic1 != null) - { + if (ic1 != null) { ic1.close(); } } diff --git a/examples/jms/clustered-queue/src/main/java/org/apache/activemq/artemis/jms/example/ClusteredQueueExample.java b/examples/jms/clustered-queue/src/main/java/org/apache/activemq/artemis/jms/example/ClusteredQueueExample.java index 1ee779ac9a..15f95f64da 100644 --- a/examples/jms/clustered-queue/src/main/java/org/apache/activemq/artemis/jms/example/ClusteredQueueExample.java +++ b/examples/jms/clustered-queue/src/main/java/org/apache/activemq/artemis/jms/example/ClusteredQueueExample.java @@ -32,16 +32,14 @@ import org.apache.activemq.artemis.jms.client.ActiveMQQueue; * A simple example that demonstrates server side load-balancing of messages between the queue instances on different * nodes of the cluster. */ -public class ClusteredQueueExample -{ - public static void main(final String[] args) throws Exception - { +public class ClusteredQueueExample { + + public static void main(final String[] args) throws Exception { Connection connection0 = null; Connection connection1 = null; - try - { + try { // Step 2. Instantiate the Queue Queue queue = ActiveMQJMSClient.createQueue("exampleQueue"); @@ -82,8 +80,7 @@ public class ClusteredQueueExample final int numMessages = 10; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session0.createTextMessage("This is text message " + i); producer.send(message); @@ -96,28 +93,24 @@ public class ClusteredQueueExample // JMS Queues implement point-to-point message where each message is only ever consumed by a // maximum of one consumer - for (int i = 0; i < numMessages; i += 2) - { - TextMessage message0 = (TextMessage)consumer0.receive(5000); + for (int i = 0; i < numMessages; i += 2) { + TextMessage message0 = (TextMessage) consumer0.receive(5000); System.out.println("Got message: " + message0.getText() + " from node 0"); - TextMessage message1 = (TextMessage)consumer1.receive(5000); + TextMessage message1 = (TextMessage) consumer1.receive(5000); System.out.println("Got message: " + message1.getText() + " from node 1"); } } - finally - { + finally { // Step 15. Be sure to close our resources! - if (connection0 != null) - { + if (connection0 != null) { connection0.close(); } - if (connection1 != null) - { + if (connection1 != null) { connection1.close(); } } diff --git a/examples/jms/clustered-static-discovery/src/main/java/org/apache/activemq/artemis/jms/example/StaticClusteredQueueExample.java b/examples/jms/clustered-static-discovery/src/main/java/org/apache/activemq/artemis/jms/example/StaticClusteredQueueExample.java index 6716075085..453fafc6a6 100644 --- a/examples/jms/clustered-static-discovery/src/main/java/org/apache/activemq/artemis/jms/example/StaticClusteredQueueExample.java +++ b/examples/jms/clustered-static-discovery/src/main/java/org/apache/activemq/artemis/jms/example/StaticClusteredQueueExample.java @@ -32,10 +32,9 @@ import org.apache.activemq.artemis.util.ServerUtil; * A simple example that demonstrates server side load-balancing of messages between the queue instances on different * nodes of the cluster. The cluster is created from a static list of nodes. */ -public class StaticClusteredQueueExample -{ - public static void main(final String[] args) throws Exception - { +public class StaticClusteredQueueExample { + + public static void main(final String[] args) throws Exception { Connection initialConnection = null; Connection connection0 = null; @@ -46,8 +45,7 @@ public class StaticClusteredQueueExample Connection connection3 = null; - try - { + try { // Step 2. Use direct instantiation (or JNDI if you like) Queue queue = ActiveMQJMSClient.createQueue("exampleQueue"); @@ -77,7 +75,6 @@ public class StaticClusteredQueueExample // Step 9. We create a JMS Session on server 1 Session session1 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE); - // Step 8. We create a JMS Session on server 0 Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -111,8 +108,7 @@ public class StaticClusteredQueueExample final int numMessages = 20; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session0.createTextMessage("This is text message " + i); producer.send(message); @@ -129,55 +125,47 @@ public class StaticClusteredQueueExample int con2Node = ServerUtil.getServer(connection2); int con3Node = ServerUtil.getServer(connection3); - if(con0Node + con1Node + con2Node + con3Node != 6) - { + if (con0Node + con1Node + con2Node + con3Node != 6) { throw new IllegalStateException(); } - for (int i = 0; i < numMessages; i += 4) - { - TextMessage message0 = (TextMessage)consumer0.receive(5000); + for (int i = 0; i < numMessages; i += 4) { + TextMessage message0 = (TextMessage) consumer0.receive(5000); System.out.println("Got message: " + message0.getText() + " from node " + con0Node); - TextMessage message1 = (TextMessage)consumer1.receive(5000); + TextMessage message1 = (TextMessage) consumer1.receive(5000); System.out.println("Got message: " + message1.getText() + " from node " + con1Node); - TextMessage message2 = (TextMessage)consumer2.receive(5000); + TextMessage message2 = (TextMessage) consumer2.receive(5000); System.out.println("Got message: " + message2.getText() + " from node " + con2Node); - TextMessage message3 = (TextMessage)consumer3.receive(5000); + TextMessage message3 = (TextMessage) consumer3.receive(5000); System.out.println("Got message: " + message3.getText() + " from node " + con3Node); } } - finally - { + finally { // Step 15. Be sure to close our resources! - if (initialConnection != null) - { + if (initialConnection != null) { initialConnection.close(); } - if (connection0 != null) - { + if (connection0 != null) { connection0.close(); } - if (connection1 != null) - { + if (connection1 != null) { connection1.close(); } - if (connection2 != null) - { + if (connection2 != null) { connection2.close(); } - if (connection3 != null) - { + if (connection3 != null) { connection3.close(); } } diff --git a/examples/jms/clustered-static-oneway/src/main/java/org/apache/activemq/artemis/jms/example/ClusterStaticOnewayExample.java b/examples/jms/clustered-static-oneway/src/main/java/org/apache/activemq/artemis/jms/example/ClusterStaticOnewayExample.java index 53d98bc8ec..03979074b8 100644 --- a/examples/jms/clustered-static-oneway/src/main/java/org/apache/activemq/artemis/jms/example/ClusterStaticOnewayExample.java +++ b/examples/jms/clustered-static-oneway/src/main/java/org/apache/activemq/artemis/jms/example/ClusterStaticOnewayExample.java @@ -32,10 +32,9 @@ import org.apache.activemq.artemis.util.ServerUtil; * A simple example that demonstrates server side load-balancing of messages between the queue instances on different * nodes of the cluster. The cluster is created from a static list of nodes. */ -public class ClusterStaticOnewayExample -{ - public static void main(final String[] args) throws Exception - { +public class ClusterStaticOnewayExample { + + public static void main(final String[] args) throws Exception { Connection initialConnection = null; Connection connection0 = null; @@ -44,8 +43,7 @@ public class ClusterStaticOnewayExample Connection connection2 = null; - try - { + try { // Step 2. Instantiate Queue Queue queue = ActiveMQJMSClient.createQueue("exampleQueue"); @@ -99,8 +97,7 @@ public class ClusterStaticOnewayExample System.out.println("con1Node = " + con1Node); System.out.println("con2Node = " + con2Node); - if(con0Node + con1Node + con2Node != 3) - { + if (con0Node + con1Node + con2Node != 3) { throw new IllegalStateException("connections not load balanced"); } // Step 13. We create a JMS MessageProducer object on server 0 @@ -112,8 +109,7 @@ public class ClusterStaticOnewayExample final int numMessages = 18; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session0.createTextMessage("This is text message " + i); producer.send(message); @@ -126,42 +122,36 @@ public class ClusterStaticOnewayExample // JMS Queues implement point-to-point message where each message is only ever consumed by a // maximum of one consumer - for (int i = 0; i < numMessages; i += 3) - { - TextMessage message0 = (TextMessage)consumer0.receive(5000); + for (int i = 0; i < numMessages; i += 3) { + TextMessage message0 = (TextMessage) consumer0.receive(5000); System.out.println("Got message: " + message0.getText() + " from node " + con0Node); - TextMessage message1 = (TextMessage)consumer1.receive(5000); + TextMessage message1 = (TextMessage) consumer1.receive(5000); System.out.println("Got message: " + message1.getText() + " from node " + con1Node); - TextMessage message2 = (TextMessage)consumer2.receive(5000); + TextMessage message2 = (TextMessage) consumer2.receive(5000); System.out.println("Got message: " + message2.getText() + " from node " + con2Node); } } - finally - { + finally { // Step 15. Be sure to close our resources! - if (initialConnection != null) - { + if (initialConnection != null) { initialConnection.close(); } - if (connection0 != null) - { + if (connection0 != null) { connection0.close(); } - if (connection1 != null) - { + if (connection1 != null) { connection1.close(); } - if (connection2 != null) - { + if (connection2 != null) { connection2.close(); } } diff --git a/examples/jms/clustered-topic/src/main/java/org/apache/activemq/artemis/jms/example/ClusteredTopicExample.java b/examples/jms/clustered-topic/src/main/java/org/apache/activemq/artemis/jms/example/ClusteredTopicExample.java index a12fedd894..f3ce9a05d4 100644 --- a/examples/jms/clustered-topic/src/main/java/org/apache/activemq/artemis/jms/example/ClusteredTopicExample.java +++ b/examples/jms/clustered-topic/src/main/java/org/apache/activemq/artemis/jms/example/ClusteredTopicExample.java @@ -32,10 +32,9 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; * A simple example that shows a JMS Topic clustered across two nodes of a cluster. * Messages are sent on one node and received by consumers on both nodes. */ -public class ClusteredTopicExample -{ - public static void main(final String[] args) throws Exception - { +public class ClusteredTopicExample { + + public static void main(final String[] args) throws Exception { Connection connection0 = null; Connection connection1 = null; @@ -44,8 +43,7 @@ public class ClusteredTopicExample InitialContext ic1 = null; - try - { + try { // Step 1. Instantiate topic Topic topic = ActiveMQJMSClient.createTopic("exampleTopic"); @@ -87,8 +85,7 @@ public class ClusteredTopicExample final int numMessages = 10; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session0.createTextMessage("This is text message " + i); producer.send(message); @@ -100,37 +97,31 @@ public class ClusteredTopicExample // We note that all messages have been consumed by *both* consumers. // JMS Topics implement *publish-subscribe* messaging where all consumers get a copy of all messages - for (int i = 0; i < numMessages; i++) - { - TextMessage message0 = (TextMessage)consumer0.receive(5000); + for (int i = 0; i < numMessages; i++) { + TextMessage message0 = (TextMessage) consumer0.receive(5000); System.out.println("Got message: " + message0.getText() + " from node 0"); - TextMessage message1 = (TextMessage)consumer1.receive(5000); + TextMessage message1 = (TextMessage) consumer1.receive(5000); System.out.println("Got message: " + message1.getText() + " from node 1"); } } - finally - { + finally { // Step 15. Be sure to close our JMS resources! - if (connection0 != null) - { + if (connection0 != null) { connection0.close(); } - if (connection1 != null) - { + if (connection1 != null) { connection1.close(); } - if (ic0 != null) - { + if (ic0 != null) { ic0.close(); } - if (ic1 != null) - { + if (ic1 != null) { ic1.close(); } } diff --git a/examples/jms/colocated-failover-scale-down/src/main/java/org/apache/activemq/artemis/jms/example/ColocatedFailoverScaleDownExample.java b/examples/jms/colocated-failover-scale-down/src/main/java/org/apache/activemq/artemis/jms/example/ColocatedFailoverScaleDownExample.java index 147f65b6f1..69b7b126f3 100644 --- a/examples/jms/colocated-failover-scale-down/src/main/java/org/apache/activemq/artemis/jms/example/ColocatedFailoverScaleDownExample.java +++ b/examples/jms/colocated-failover-scale-down/src/main/java/org/apache/activemq/artemis/jms/example/ColocatedFailoverScaleDownExample.java @@ -33,14 +33,13 @@ import java.util.Hashtable; * A simple example that demonstrates server side load-balancing of messages between the queue instances on different * nodes of the cluster. */ -public class ColocatedFailoverScaleDownExample -{ +public class ColocatedFailoverScaleDownExample { + private static Process server0; private static Process server1; - public static void main(final String[] args) throws Exception - { + public static void main(final String[] args) throws Exception { final int numMessages = 30; Connection connection = null; @@ -49,8 +48,7 @@ public class ColocatedFailoverScaleDownExample InitialContext initialContext = null; InitialContext initialContext1 = null; - try - { + try { server0 = ServerUtil.startServer(args[0], ColocatedFailoverScaleDownExample.class.getSimpleName() + "0", 0, 5000); server1 = ServerUtil.startServer(args[1], ColocatedFailoverScaleDownExample.class.getSimpleName() + "1", 1, 5000); @@ -67,9 +65,9 @@ public class ColocatedFailoverScaleDownExample initialContext = new InitialContext(properties); // Step 2. Look up the JMS resources from JNDI - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); - ConnectionFactory connectionFactory = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); - ConnectionFactory connectionFactory1 = (ConnectionFactory)initialContext1.lookup("ConnectionFactory"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); + ConnectionFactory connectionFactory = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); + ConnectionFactory connectionFactory1 = (ConnectionFactory) initialContext1.lookup("ConnectionFactory"); // Step 3. Create a JMS Connections connection = connectionFactory.createConnection(); @@ -84,8 +82,7 @@ public class ColocatedFailoverScaleDownExample MessageProducer producer1 = session1.createProducer(queue); // Step 6. Send some messages to both servers - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session.createTextMessage("This is text message " + i); producer.send(message); System.out.println("Sent message: " + message.getText()); @@ -110,37 +107,30 @@ public class ColocatedFailoverScaleDownExample // because they were initially round robined to both nodes then when the server failed were reloaded into the // live server. TextMessage message0 = null; - for (int i = 0; i < numMessages * 2; i++) - { - message0 = (TextMessage)consumer.receive(5000); - if (message0 == null) - { + for (int i = 0; i < numMessages * 2; i++) { + message0 = (TextMessage) consumer.receive(5000); + if (message0 == null) { throw new IllegalStateException("Message not received!"); } System.out.println("Got message: " + message0.getText()); } message0.acknowledge(); } - finally - { + finally { // Step 11. Be sure to close our resources! - if (connection != null) - { + if (connection != null) { connection.close(); } - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection1 != null) - { + if (connection1 != null) { connection1.close(); } - if (initialContext1 != null) - { + if (initialContext1 != null) { initialContext1.close(); } diff --git a/examples/jms/colocated-failover/src/main/java/org/apache/activemq/artemis/jms/example/ColocatedFailoverExample.java b/examples/jms/colocated-failover/src/main/java/org/apache/activemq/artemis/jms/example/ColocatedFailoverExample.java index c5bb765c46..2d96738ee2 100644 --- a/examples/jms/colocated-failover/src/main/java/org/apache/activemq/artemis/jms/example/ColocatedFailoverExample.java +++ b/examples/jms/colocated-failover/src/main/java/org/apache/activemq/artemis/jms/example/ColocatedFailoverExample.java @@ -31,16 +31,14 @@ import java.util.Hashtable; /** * A simple example that demonstrates a colocated server - * */ -public class ColocatedFailoverExample -{ +public class ColocatedFailoverExample { + private static Process server0; private static Process server1; - public static void main(final String[] args) throws Exception - { + public static void main(final String[] args) throws Exception { final int numMessages = 30; Connection connection = null; @@ -49,8 +47,7 @@ public class ColocatedFailoverExample InitialContext initialContext = null; InitialContext initialContext1 = null; - try - { + try { server0 = ServerUtil.startServer(args[0], ColocatedFailoverExample.class.getSimpleName() + "0", 0, 5000); server1 = ServerUtil.startServer(args[1], ColocatedFailoverExample.class.getSimpleName() + "1", 1, 5000); @@ -67,9 +64,9 @@ public class ColocatedFailoverExample initialContext1 = new InitialContext(properties); // Step 2. Look up the JMS resources from JNDI - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); - ConnectionFactory connectionFactory = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); - ConnectionFactory connectionFactory1 = (ConnectionFactory)initialContext1.lookup("ConnectionFactory"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); + ConnectionFactory connectionFactory = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); + ConnectionFactory connectionFactory1 = (ConnectionFactory) initialContext1.lookup("ConnectionFactory"); // Step 3. Create a JMS Connections connection = connectionFactory.createConnection(); @@ -84,8 +81,7 @@ public class ColocatedFailoverExample MessageProducer producer1 = session1.createProducer(queue); // Step 6. Send some messages to both servers - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session.createTextMessage("This is text message " + i); producer.send(message); System.out.println("Sent message: " + message.getText()); @@ -109,11 +105,9 @@ public class ColocatedFailoverExample // Step 10. Receive and acknowledge all of the sent messages, the backup server that is colocated with server 1 // will have become live and is now handling messages for server 0. TextMessage message0 = null; - for (int i = 0; i < numMessages; i++) - { - message0 = (TextMessage)consumer.receive(5000); - if (message0 == null) - { + for (int i = 0; i < numMessages; i++) { + message0 = (TextMessage) consumer.receive(5000); + if (message0 == null) { throw new IllegalStateException("Message not received!"); } System.out.println("Got message: " + message0.getText()); @@ -123,33 +117,27 @@ public class ColocatedFailoverExample MessageConsumer consumer1 = session.createConsumer(queue); // Step 11. Receive and acknowledge the rest of the sent messages from server 1. - for (int i = 0; i < numMessages; i++) - { - message0 = (TextMessage)consumer1.receive(5000); + for (int i = 0; i < numMessages; i++) { + message0 = (TextMessage) consumer1.receive(5000); System.out.println("Got message: " + message0.getText()); } message0.acknowledge(); } - finally - { + finally { // Step 11. Be sure to close our resources! - if (connection != null) - { + if (connection != null) { connection.close(); } - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection1 != null) - { + if (connection1 != null) { connection1.close(); } - if (initialContext1 != null) - { + if (initialContext1 != null) { initialContext1.close(); } diff --git a/examples/jms/consumer-rate-limit/src/main/java/org/apache/activemq/artemis/jms/example/ConsumerRateLimitExample.java b/examples/jms/consumer-rate-limit/src/main/java/org/apache/activemq/artemis/jms/example/ConsumerRateLimitExample.java index a8a66f9f71..f49a2fc488 100644 --- a/examples/jms/consumer-rate-limit/src/main/java/org/apache/activemq/artemis/jms/example/ConsumerRateLimitExample.java +++ b/examples/jms/consumer-rate-limit/src/main/java/org/apache/activemq/artemis/jms/example/ConsumerRateLimitExample.java @@ -30,22 +30,20 @@ import java.lang.Exception; * This example demonstrates how a message consumer can be limited to consumer messages at a maximum rate * specified in messages per sec. */ -public class ConsumerRateLimitExample -{ - public static void main(final String[] args) throws Exception - { +public class ConsumerRateLimitExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Perfom a lookup on the queue - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 3. Perform a lookup on the Connection Factory - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4. Create a JMS Connection connection = cf.createConnection(); @@ -68,8 +66,7 @@ public class ConsumerRateLimitExample final int numMessages = 150; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session.createTextMessage("This is text message: " + i); producer.send(message); @@ -87,12 +84,10 @@ public class ConsumerRateLimitExample long start = System.currentTimeMillis(); - while (System.currentTimeMillis() - start <= duration) - { - TextMessage message = (TextMessage)consumer.receive(2000); + while (System.currentTimeMillis() - start <= duration) { + TextMessage message = (TextMessage) consumer.receive(2000); - if (message == null) - { + if (message == null) { throw new RuntimeException("Message was null"); } @@ -101,22 +96,19 @@ public class ConsumerRateLimitExample long end = System.currentTimeMillis(); - double rate = 1000 * (double)i / (end - start); + double rate = 1000 * (double) i / (end - start); System.out.println("We consumed " + i + " messages in " + (end - start) + " milliseconds"); System.out.println("Actual consume rate was " + rate + " messages per second"); } - finally - { + finally { // Step 9. Be sure to close our resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } diff --git a/examples/jms/dead-letter/src/main/java/org/apache/activemq/artemis/jms/example/DeadLetterExample.java b/examples/jms/dead-letter/src/main/java/org/apache/activemq/artemis/jms/example/DeadLetterExample.java index fb976ab70c..db28568c2d 100644 --- a/examples/jms/dead-letter/src/main/java/org/apache/activemq/artemis/jms/example/DeadLetterExample.java +++ b/examples/jms/dead-letter/src/main/java/org/apache/activemq/artemis/jms/example/DeadLetterExample.java @@ -28,23 +28,21 @@ import javax.naming.InitialContext; /** * An example showing how messages are moved to dead letter destination when they are unsuccessfully delivered multiple times */ -public class DeadLetterExample -{ - public static void main(final String[] args) throws Exception - { +public class DeadLetterExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Perfom a lookup on the queue - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 3. Perform a lookup on the Connection Factory - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4.Create a JMS Connection connection = cf.createConnection(); @@ -72,43 +70,43 @@ public class DeadLetterExample connection.start(); // Step 12. We receive a message... - TextMessage messageReceived = (TextMessage)messageConsumer.receive(5000); + TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000); System.out.println("1st delivery from " + queue.getQueueName() + ": " + messageReceived.getText()); // Step 13. ... but we roll back the session. the message returns to the queue ready to be redelivered session.rollback(); // Step 14. We receive a message and roll back the session a second time - messageReceived = (TextMessage)messageConsumer.receive(5000); + messageReceived = (TextMessage) messageConsumer.receive(5000); System.out.println("2nd delivery from " + queue.getQueueName() + ": " + messageReceived.getText()); session.rollback(); // Step 15. We receive a message and roll back the session a third time - messageReceived = (TextMessage)messageConsumer.receive(5000); + messageReceived = (TextMessage) messageConsumer.receive(5000); System.out.println("3rd delivery from " + queue.getQueueName() + ": " + messageReceived.getText()); session.rollback(); // The message has been delivered unsuccessfully 3 times -> it is moved to the dead letter queue. // Step 16. The 4th time, call will timeout after 5000ms and messageReceived will be null - messageReceived = (TextMessage)messageConsumer.receive(5000); + messageReceived = (TextMessage) messageConsumer.receive(5000); System.out.println("4th delivery from " + queue.getQueueName() + ": " + messageReceived); // We will now consume the message from the dead letter queue // Step 17. Perform a lookup on the dead letter queue - Queue deadLetterQueue = (Queue)initialContext.lookup("queue/deadLetterQueue"); + Queue deadLetterQueue = (Queue) initialContext.lookup("queue/deadLetterQueue"); // Step 18. Create a JMS Message Consumer for the dead letter queue MessageConsumer deadLetterConsumer = session.createConsumer(deadLetterQueue); // Step 19. Receive the message from the dead letter queue - messageReceived = (TextMessage)deadLetterConsumer.receive(5000); + messageReceived = (TextMessage) deadLetterConsumer.receive(5000); // Step 20. The message sent to the queue was moved to the dead letter queue after 3 unsuccessful deliveries System.out.println("Received message from " + deadLetterQueue.getQueueName() + - ": " + - messageReceived.getText()); + ": " + + messageReceived.getText()); // The message received from the dead letter queue has the same content than the undelivered message but its // JMS headers @@ -117,7 +115,7 @@ public class DeadLetterExample System.out.println(); // Step 21. the messageReceived's destination is now the dead letter queue. - System.out.println("Destination of the message: " + ((Queue)messageReceived.getJMSDestination()).getQueueName()); + System.out.println("Destination of the message: " + ((Queue) messageReceived.getJMSDestination()).getQueueName()); // Step 22. the *origin* destination is stored in the _AMQ_ORIG_ADDRESS property System.out.println("*Origin destination* of the message: " + messageReceived.getStringProperty("_AMQ_ORIG_ADDRESS")); @@ -125,15 +123,12 @@ public class DeadLetterExample // Step 23. This time, we commit the session, the delivery from the dead letter queue is successful! session.commit(); } - finally - { + finally { // Step 24. Be sure to close our JMS resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } diff --git a/examples/jms/delayed-redelivery/src/main/java/org/apache/activemq/artemis/jms/example/DelayedRedeliveryExample.java b/examples/jms/delayed-redelivery/src/main/java/org/apache/activemq/artemis/jms/example/DelayedRedeliveryExample.java index 6a2d15d49d..afa538ffcb 100644 --- a/examples/jms/delayed-redelivery/src/main/java/org/apache/activemq/artemis/jms/example/DelayedRedeliveryExample.java +++ b/examples/jms/delayed-redelivery/src/main/java/org/apache/activemq/artemis/jms/example/DelayedRedeliveryExample.java @@ -31,23 +31,21 @@ import javax.naming.InitialContext; * * Please see the readme.html for more information */ -public class DelayedRedeliveryExample -{ - public static void main(final String[] args) throws Exception - { +public class DelayedRedeliveryExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Perform a lookup on the queue - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 3. Perform a lookup on the Connection Factory - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4. Create a JMS Connection connection = cf.createConnection(); @@ -76,7 +74,7 @@ public class DelayedRedeliveryExample connection.start(); // Step 12. We receive a message... - TextMessage messageReceived = (TextMessage)messageConsumer.receive(5000); + TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000); System.out.println("1st delivery from " + queue.getQueueName() + ": " + messageReceived.getText()); // Step 13. ... but we roll back the session. the message returns to the queue, but only after a @@ -84,10 +82,9 @@ public class DelayedRedeliveryExample session.rollback(); // Step 14. We try to receive the message but it's being delayed - messageReceived = (TextMessage)messageConsumer.receive(3000); + messageReceived = (TextMessage) messageConsumer.receive(3000); - if (messageReceived != null) - { + if (messageReceived != null) { throw new IllegalStateException("Expected to recieve message."); } @@ -95,7 +92,7 @@ public class DelayedRedeliveryExample // Step 15. We try and receive the message again, this time we should get it - messageReceived = (TextMessage)messageConsumer.receive(3000); + messageReceived = (TextMessage) messageConsumer.receive(3000); System.out.println("2nd delivery from " + queue.getQueueName() + ": " + messageReceived.getText()); @@ -105,26 +102,23 @@ public class DelayedRedeliveryExample session.rollback(); - messageReceived = (TextMessage)messageConsumer.receive(8000); + messageReceived = (TextMessage) messageConsumer.receive(8000); long end = System.currentTimeMillis(); System.out.println("3nd delivery from " + queue.getQueueName() + - ": " + - messageReceived.getText() + - " after " + - (end - start) + - " milliseconds."); + ": " + + messageReceived.getText() + + " after " + + (end - start) + + " milliseconds."); } - finally - { + finally { // Step 17. Be sure to close our JMS resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } diff --git a/examples/jms/divert/src/main/java/org/apache/activemq/artemis/jms/example/AddForwardingTimeTransformer.java b/examples/jms/divert/src/main/java/org/apache/activemq/artemis/jms/example/AddForwardingTimeTransformer.java index f78377edd0..15d8e65f4d 100644 --- a/examples/jms/divert/src/main/java/org/apache/activemq/artemis/jms/example/AddForwardingTimeTransformer.java +++ b/examples/jms/divert/src/main/java/org/apache/activemq/artemis/jms/example/AddForwardingTimeTransformer.java @@ -20,10 +20,9 @@ import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.server.ServerMessage; import org.apache.activemq.artemis.core.server.cluster.Transformer; -public class AddForwardingTimeTransformer implements Transformer -{ - public ServerMessage transform(final ServerMessage message) - { +public class AddForwardingTimeTransformer implements Transformer { + + public ServerMessage transform(final ServerMessage message) { message.putLongProperty(new SimpleString("time_of_forward"), System.currentTimeMillis()); return message; diff --git a/examples/jms/divert/src/main/java/org/apache/activemq/artemis/jms/example/DivertExample.java b/examples/jms/divert/src/main/java/org/apache/activemq/artemis/jms/example/DivertExample.java index 3d74c55368..e0146938ea 100644 --- a/examples/jms/divert/src/main/java/org/apache/activemq/artemis/jms/example/DivertExample.java +++ b/examples/jms/divert/src/main/java/org/apache/activemq/artemis/jms/example/DivertExample.java @@ -35,15 +35,13 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; * * Please see the readme.html for more information. */ -public class DivertExample -{ - public static void main(final String[] args) throws Exception - { +public class DivertExample { + + public static void main(final String[] args) throws Exception { Connection connectionLondon = null; Connection connectionNewYork = null; - try - { + try { // Step 2. Look-up the queue orderQueue on the London server - this is the queue any orders are sent to Queue orderQueue = ActiveMQJMSClient.createQueue("orders"); @@ -67,7 +65,7 @@ public class DivertExample ConnectionFactory cfLondon = new ActiveMQConnectionFactory("tcp://localhost:61616"); // Step 9. Perform a lookup on the Connection Factory on the New York server - ConnectionFactory cfNewYork = new ActiveMQConnectionFactory("tcp://localhost:61617"); + ConnectionFactory cfNewYork = new ActiveMQConnectionFactory("tcp://localhost:61617"); // Step 10. Create a JMS Connection on the London server connectionLondon = cfLondon.createConnection(); @@ -122,16 +120,16 @@ public class DivertExample System.out.println("Sent message: " + orderMessage.getText()); // Step 24. The order message is consumed by the orderConsumer on the London server - TextMessage receivedOrder = (TextMessage)orderConsumer.receive(5000); + TextMessage receivedOrder = (TextMessage) orderConsumer.receive(5000); System.out.println("Received order: " + receivedOrder.getText()); // Step 25. A copy of the order is also received by the spyTopic subscribers on the London server - TextMessage spiedOrder1 = (TextMessage)spySubscriberA.receive(5000); + TextMessage spiedOrder1 = (TextMessage) spySubscriberA.receive(5000); System.out.println("Snooped on order: " + spiedOrder1.getText()); - TextMessage spiedOrder2 = (TextMessage)spySubscriberB.receive(5000); + TextMessage spiedOrder2 = (TextMessage) spySubscriberB.receive(5000); System.out.println("Snooped on order: " + spiedOrder2.getText()); @@ -144,25 +142,23 @@ public class DivertExample // Step 27. The price update *should* be received by the local subscriber since we only divert messages // where office = New York - TextMessage receivedUpdate = (TextMessage)priceUpdatesSubscriberLondon.receive(2000); + TextMessage receivedUpdate = (TextMessage) priceUpdatesSubscriberLondon.receive(2000); System.out.println("Received price update locally: " + receivedUpdate.getText()); // Step 28. The price update *should not* be received in New York - TextMessage priceUpdate1 = (TextMessage)newYorkPriceUpdatesSubscriberA.receive(1000); + TextMessage priceUpdate1 = (TextMessage) newYorkPriceUpdatesSubscriberA.receive(1000); - if (priceUpdate1 != null) - { + if (priceUpdate1 != null) { throw new IllegalStateException("Message is not null"); } System.out.println("Did not received price update in New York, look it's: " + priceUpdate1); - TextMessage priceUpdate2 = (TextMessage)newYorkPriceUpdatesSubscriberB.receive(1000); + TextMessage priceUpdate2 = (TextMessage) newYorkPriceUpdatesSubscriberB.receive(1000); - if (priceUpdate2 != null) - { + if (priceUpdate2 != null) { throw new IllegalStateException("Message is not null"); } @@ -182,8 +178,7 @@ public class DivertExample // it is destined for the New York office Message message = priceUpdatesSubscriberLondon.receive(1000); - if (message != null) - { + if (message != null) { throw new IllegalStateException("Message is not null"); } @@ -195,24 +190,21 @@ public class DivertExample // We notice how the forwarded messages have had a special header added by our custom transformer that // we told the divert to use - priceUpdate1 = (TextMessage)newYorkPriceUpdatesSubscriberA.receive(5000); + priceUpdate1 = (TextMessage) newYorkPriceUpdatesSubscriberA.receive(5000); System.out.println("Received forwarded price update on server 1: " + priceUpdate1.getText()); System.out.println("Time of forward: " + priceUpdate1.getLongProperty("time_of_forward")); - priceUpdate2 = (TextMessage)newYorkPriceUpdatesSubscriberB.receive(5000); + priceUpdate2 = (TextMessage) newYorkPriceUpdatesSubscriberB.receive(5000); System.out.println("Received forwarded price update on server 2: " + priceUpdate2.getText()); System.out.println("Time of forward: " + priceUpdate2.getLongProperty("time_of_forward")); } - finally - { - if (connectionLondon != null) - { + finally { + if (connectionLondon != null) { connectionLondon.close(); } - if (connectionNewYork != null) - { + if (connectionNewYork != null) { connectionNewYork.close(); } } diff --git a/examples/jms/durable-subscription/src/main/java/org/apache/activemq/artemis/jms/example/DurableSubscriptionExample.java b/examples/jms/durable-subscription/src/main/java/org/apache/activemq/artemis/jms/example/DurableSubscriptionExample.java index 2a8eabf114..46cd94cf7b 100644 --- a/examples/jms/durable-subscription/src/main/java/org/apache/activemq/artemis/jms/example/DurableSubscriptionExample.java +++ b/examples/jms/durable-subscription/src/main/java/org/apache/activemq/artemis/jms/example/DurableSubscriptionExample.java @@ -28,22 +28,20 @@ import javax.naming.InitialContext; /** * A simple JMS example that shows how to use a durable subscription. */ -public class DurableSubscriptionExample -{ - public static void main(final String[] args) throws Exception - { +public class DurableSubscriptionExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Look-up the JMS topic - Topic topic = (Topic)initialContext.lookup("topic/exampleTopic"); + Topic topic = (Topic) initialContext.lookup("topic/exampleTopic"); // Step 3. Look-up the JMS connection factory - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4. Create a JMS connection connection = cf.createConnection(); @@ -73,7 +71,7 @@ public class DurableSubscriptionExample // Step 12. Consume the message from the durable subscription - TextMessage messageReceived = (TextMessage)subscriber.receive(); + TextMessage messageReceived = (TextMessage) subscriber.receive(); System.out.println("Received message: " + messageReceived.getText()); @@ -94,7 +92,7 @@ public class DurableSubscriptionExample // Step 16. Consume the message - messageReceived = (TextMessage)subscriber.receive(); + messageReceived = (TextMessage) subscriber.receive(); System.out.println("Received message: " + messageReceived.getText()); @@ -104,15 +102,12 @@ public class DurableSubscriptionExample // Step 18. Delete the durable subscription session.unsubscribe("subscriber-1"); } - finally - { - if (connection != null) - { + finally { + if (connection != null) { // Step 19. Be sure to close our JMS resources! connection.close(); } - if (initialContext != null) - { + if (initialContext != null) { // Step 20. Also close the initialContext! initialContext.close(); } diff --git a/examples/jms/embedded-simple/src/main/java/org/apache/activemq/artemis/jms/example/EmbeddedExample.java b/examples/jms/embedded-simple/src/main/java/org/apache/activemq/artemis/jms/example/EmbeddedExample.java index 2bf15a2a39..7d00c7e05a 100644 --- a/examples/jms/embedded-simple/src/main/java/org/apache/activemq/artemis/jms/example/EmbeddedExample.java +++ b/examples/jms/embedded-simple/src/main/java/org/apache/activemq/artemis/jms/example/EmbeddedExample.java @@ -36,10 +36,9 @@ import java.util.List; /** * This example demonstrates how to run an ActiveMQ Artemis embedded with JMS */ -public class EmbeddedExample -{ - public static void main(final String[] args) throws Exception - { +public class EmbeddedExample { + + public static void main(final String[] args) throws Exception { EmbeddedJMS jmsServer = new EmbeddedJMS(); SecurityConfiguration securityConfig = new SecurityConfiguration(); @@ -62,8 +61,7 @@ public class EmbeddedExample // Step 10. Send and receive a message using JMS API Connection connection = null; - try - { + try { connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(queue); @@ -75,10 +73,8 @@ public class EmbeddedExample TextMessage messageReceived = (TextMessage) messageConsumer.receive(1000); System.out.println("Received message:" + messageReceived.getText()); } - finally - { - if (connection != null) - { + finally { + if (connection != null) { connection.close(); } diff --git a/examples/jms/embedded/src/main/java/org/apache/activemq/artemis/jms/example/EmbeddedExample.java b/examples/jms/embedded/src/main/java/org/apache/activemq/artemis/jms/example/EmbeddedExample.java index 2a97c0f3b6..cb39fd0aca 100644 --- a/examples/jms/embedded/src/main/java/org/apache/activemq/artemis/jms/example/EmbeddedExample.java +++ b/examples/jms/embedded/src/main/java/org/apache/activemq/artemis/jms/example/EmbeddedExample.java @@ -42,11 +42,9 @@ import org.apache.activemq.artemis.jms.server.embedded.EmbeddedJMS; /** * This example demonstrates how to run an ActiveMQ Artemis embedded with JMS */ -public final class EmbeddedExample -{ +public final class EmbeddedExample { - public static void main(final String[] args) throws Exception - { + public static void main(final String[] args) throws Exception { // Step 1. Create ActiveMQ Artemis core configuration, and set the properties accordingly Configuration configuration = new ConfigurationImpl(); configuration.setPersistenceEnabled(false); @@ -58,24 +56,17 @@ public final class EmbeddedExample configuration.getConnectorConfigurations().put("connector", connectorConfig); - // Step 2. Create the JMS configuration JMSConfiguration jmsConfig = new JMSConfigurationImpl(); // Step 3. Configure the JMS ConnectionFactory ArrayList connectorNames = new ArrayList(); connectorNames.add("connector"); - ConnectionFactoryConfiguration cfConfig = new ConnectionFactoryConfigurationImpl() - .setName("cf") - .setConnectorNames(connectorNames) - .setBindings("cf"); + ConnectionFactoryConfiguration cfConfig = new ConnectionFactoryConfigurationImpl().setName("cf").setConnectorNames(connectorNames).setBindings("cf"); jmsConfig.getConnectionFactoryConfigurations().add(cfConfig); // Step 4. Configure the JMS Queue - JMSQueueConfiguration queueConfig = new JMSQueueConfigurationImpl() - .setName("queue1") - .setDurable(false) - .setBindings("queue/queue1"); + JMSQueueConfiguration queueConfig = new JMSQueueConfigurationImpl().setName("queue1").setDurable(false).setBindings("queue/queue1"); jmsConfig.getQueueConfigurations().add(queueConfig); // Step 5. Start the JMS Server using the ActiveMQ Artemis core server and the JMS configuration @@ -91,8 +82,7 @@ public final class EmbeddedExample // Step 7. Send and receive a message using JMS API Connection connection = null; - try - { + try { connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(queue); @@ -104,10 +94,8 @@ public final class EmbeddedExample TextMessage messageReceived = (TextMessage) messageConsumer.receive(1000); System.out.println("Received message:" + messageReceived.getText()); } - finally - { - if (connection != null) - { + finally { + if (connection != null) { connection.close(); } diff --git a/examples/jms/expiry/src/main/java/org/apache/activemq/artemis/jms/example/ExpiryExample.java b/examples/jms/expiry/src/main/java/org/apache/activemq/artemis/jms/example/ExpiryExample.java index dfb4324fd4..996da7438a 100644 --- a/examples/jms/expiry/src/main/java/org/apache/activemq/artemis/jms/example/ExpiryExample.java +++ b/examples/jms/expiry/src/main/java/org/apache/activemq/artemis/jms/example/ExpiryExample.java @@ -28,22 +28,20 @@ import javax.naming.InitialContext; /** * An example showing how messages are moved to an expiry queue when they expire. */ -public class ExpiryExample -{ - public static void main(final String[] args) throws Exception - { +public class ExpiryExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Perfom a lookup on the queue - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 3. Perform a lookup on the Connection Factory - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4.Create a JMS Connection connection = cf.createConnection(); @@ -76,17 +74,17 @@ public class ExpiryExample // Step 13. Trying to receive a message. Since there is none on the queue, the call will timeout after 5000ms // and messageReceived will be null - TextMessage messageReceived = (TextMessage)messageConsumer.receive(5000); + TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000); System.out.println("Received message from " + queue.getQueueName() + ": " + messageReceived); // Step 14. Perfom a lookup on the expiry queue - Queue expiryQueue = (Queue)initialContext.lookup("queue/expiryQueue"); + Queue expiryQueue = (Queue) initialContext.lookup("queue/expiryQueue"); // Step 15. Create a JMS Message Consumer for the expiry queue MessageConsumer expiryConsumer = session.createConsumer(expiryQueue); // Step 16. Receive the message from the expiry queue - messageReceived = (TextMessage)expiryConsumer.receive(5000); + messageReceived = (TextMessage) expiryConsumer.receive(5000); // Step 17. The message sent to the queue was moved to the expiry queue when it expired. System.out.println("Received message from " + expiryQueue.getQueueName() + ": " + messageReceived.getText()); @@ -99,7 +97,7 @@ public class ExpiryExample System.out.println(); // Step 18. the messageReceived's destination is now the expiry queue. - System.out.println("Destination of the expired message: " + ((Queue)messageReceived.getJMSDestination()).getQueueName()); + System.out.println("Destination of the expired message: " + ((Queue) messageReceived.getJMSDestination()).getQueueName()); // Step 19. and its own expiration (the time to live in the *expiry* queue) System.out.println("Expiration time of the expired message (relative to the expiry queue): " + messageReceived.getJMSExpiration()); @@ -109,15 +107,12 @@ public class ExpiryExample // Step 21. the actual expiration time is stored in the _AMQ_ACTUAL_EXPIRY property System.out.println("*Actual expiration time* of the expired message: " + messageReceived.getLongProperty("_AMQ_ACTUAL_EXPIRY")); } - finally - { + finally { // Step 22. Be sure to close the resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } diff --git a/examples/jms/ha-policy-autobackup/src/main/java/org/apache/activemq/artemis/jms/example/HAPolicyAutoBackupExample.java b/examples/jms/ha-policy-autobackup/src/main/java/org/apache/activemq/artemis/jms/example/HAPolicyAutoBackupExample.java index 93d3d53f5b..0df8bfd9bf 100644 --- a/examples/jms/ha-policy-autobackup/src/main/java/org/apache/activemq/artemis/jms/example/HAPolicyAutoBackupExample.java +++ b/examples/jms/ha-policy-autobackup/src/main/java/org/apache/activemq/artemis/jms/example/HAPolicyAutoBackupExample.java @@ -39,20 +39,18 @@ import org.apache.activemq.artemis.util.ServerUtil; * A simple example that demonstrates server side load-balancing of messages between the queue instances on different * nodes of the cluster. */ -public class HAPolicyAutoBackupExample -{ +public class HAPolicyAutoBackupExample { + private static Process server0; private static Process server1; - public static void main(final String[] args) throws Exception - { + public static void main(final String[] args) throws Exception { Connection connection0 = null; Connection connection1 = null; - try - { + try { server0 = ServerUtil.startServer(args[0], HAPolicyAutoBackupExample.class.getSimpleName() + "0", 0, 5000); server1 = ServerUtil.startServer(args[1], HAPolicyAutoBackupExample.class.getSimpleName() + "1", 1, 5000); @@ -89,8 +87,7 @@ public class HAPolicyAutoBackupExample final int numMessages = 10; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session0.createTextMessage("This is text message " + i); producer.send(message); @@ -100,8 +97,7 @@ public class HAPolicyAutoBackupExample // Step 13. We now consume half the messages on consumer0 // note that the other half of the messages will have been sent to server1 for consumer1 - for (int i = 0; i < numMessages / 2; i++) - { + for (int i = 0; i < numMessages / 2; i++) { TextMessage message0 = (TextMessage) consumer0.receive(5000); System.out.println("Got message: " + message0.getText() + " from node 0"); @@ -115,24 +111,20 @@ public class HAPolicyAutoBackupExample Thread.sleep(5000); // Step 16. we now receive the messages that were on server1 but were scaled down to server0 - for (int i = 0; i < numMessages / 2; i++) - { + for (int i = 0; i < numMessages / 2; i++) { TextMessage message0 = (TextMessage) consumer0.receive(5000); System.out.println("Got message: " + message0.getText() + " from node 1"); } } - finally - { + finally { // Step 17. Be sure to close our resources! - if (connection0 != null) - { + if (connection0 != null) { connection0.close(); } - if (connection1 != null) - { + if (connection1 != null) { connection1.close(); } @@ -141,25 +133,21 @@ public class HAPolicyAutoBackupExample } } - private static void waitForBackups(ConnectionFactory cf0, int backups) throws InterruptedException - { + private static void waitForBackups(ConnectionFactory cf0, int backups) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(backups); - ((ActiveMQConnectionFactory) cf0).getServerLocator().addClusterTopologyListener(new ClusterTopologyListener() - { + ((ActiveMQConnectionFactory) cf0).getServerLocator().addClusterTopologyListener(new ClusterTopologyListener() { List backups = new ArrayList(); + @Override - public void nodeUP(TopologyMember member, boolean last) - { - if (member.getBackup() != null && !backups.contains(member.getBackup())) - { + public void nodeUP(TopologyMember member, boolean last) { + if (member.getBackup() != null && !backups.contains(member.getBackup())) { backups.add(member.getBackup()); latch.countDown(); } } @Override - public void nodeDown(long eventUID, String nodeID) - { + public void nodeDown(long eventUID, String nodeID) { } }); latch.await(30000, TimeUnit.MILLISECONDS); diff --git a/examples/jms/http-transport/src/main/java/org/apache/activemq/artemis/jms/example/HttpTransportExample.java b/examples/jms/http-transport/src/main/java/org/apache/activemq/artemis/jms/example/HttpTransportExample.java index 9ae1cbacea..25baae2259 100644 --- a/examples/jms/http-transport/src/main/java/org/apache/activemq/artemis/jms/example/HttpTransportExample.java +++ b/examples/jms/http-transport/src/main/java/org/apache/activemq/artemis/jms/example/HttpTransportExample.java @@ -31,13 +31,11 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; /** * A simple JMS Queue example that uses HTTP protocol. */ -public class HttpTransportExample -{ - public static void main(final String[] args) throws Exception - { +public class HttpTransportExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; - try - { + try { // Step 2. Perfom a lookup on the queue Queue queue = ActiveMQJMSClient.createQueue("exampleQueue"); @@ -70,15 +68,13 @@ public class HttpTransportExample connection.start(); // Step 11. Receive the message - TextMessage messageReceived = (TextMessage)messageConsumer.receive(5000); + TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000); System.out.println("Received message: " + messageReceived.getText()); } - finally - { - if (connection != null) - { + finally { + if (connection != null) { connection.close(); } } diff --git a/examples/jms/instantiate-connection-factory/src/main/java/org/apache/activemq/artemis/jms/example/InstantiateConnectionFactoryExample.java b/examples/jms/instantiate-connection-factory/src/main/java/org/apache/activemq/artemis/jms/example/InstantiateConnectionFactoryExample.java index 9b1e46ea20..47bc66c9ea 100644 --- a/examples/jms/instantiate-connection-factory/src/main/java/org/apache/activemq/artemis/jms/example/InstantiateConnectionFactoryExample.java +++ b/examples/jms/instantiate-connection-factory/src/main/java/org/apache/activemq/artemis/jms/example/InstantiateConnectionFactoryExample.java @@ -28,19 +28,16 @@ import org.apache.activemq.artemis.api.jms.ActiveMQJMSClient; import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; /** - * * This example demonstrates how a JMS client can directly instantiate it's JMS Objects like * Queue, ConnectionFactory, etc. without having to use JNDI at all. * * For more information please see the readme.html file. */ -public class InstantiateConnectionFactoryExample -{ - public static void main(final String[] args) throws Exception - { +public class InstantiateConnectionFactoryExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; - try - { + try { // Step 1. Directly instantiate the JMS Queue object. Queue queue = ActiveMQJMSClient.createQueue("exampleQueue"); @@ -71,14 +68,12 @@ public class InstantiateConnectionFactoryExample connection.start(); // Step 11. Receive the message - TextMessage messageReceived = (TextMessage)messageConsumer.receive(5000); + TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000); System.out.println("Received message: " + messageReceived.getText()); } - finally - { - if (connection != null) - { + finally { + if (connection != null) { connection.close(); } } diff --git a/examples/jms/interceptor/src/main/java/org/apache/activemq/artemis/jms/example/InterceptorExample.java b/examples/jms/interceptor/src/main/java/org/apache/activemq/artemis/jms/example/InterceptorExample.java index 1a277268d7..b78875f662 100644 --- a/examples/jms/interceptor/src/main/java/org/apache/activemq/artemis/jms/example/InterceptorExample.java +++ b/examples/jms/interceptor/src/main/java/org/apache/activemq/artemis/jms/example/InterceptorExample.java @@ -28,22 +28,20 @@ import javax.naming.InitialContext; /** * A simple JMS example that shows how to implement and use interceptors with ActiveMQ Artemis. */ -public class InterceptorExample -{ - public static void main(final String[] args) throws Exception - { +public class InterceptorExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Perform a lookup on the queue - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 3. Perform a lookup on the Connection Factory - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4.Create a JMS Connection connection = cf.createConnection(); @@ -58,8 +56,8 @@ public class InterceptorExample TextMessage message = session.createTextMessage("This is a text message"); System.out.println("Sending message [" + message.getText() + - "] with String property: " + - message.getStringProperty("newproperty")); + "] with String property: " + + message.getStringProperty("newproperty")); // Step 8. Send the Message producer.send(message); @@ -71,21 +69,18 @@ public class InterceptorExample connection.start(); // Step 11. Receive the message - TextMessage messageReceived = (TextMessage)messageConsumer.receive(5000); + TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000); System.out.println("Received message [" + messageReceived.getText() + - "] with String property: " + - messageReceived.getStringProperty("newproperty")); + "] with String property: " + + messageReceived.getStringProperty("newproperty")); } - finally - { + finally { // Step 12. Be sure to close our JMS resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } diff --git a/examples/jms/interceptor/src/main/java/org/apache/activemq/artemis/jms/example/SimpleInterceptor.java b/examples/jms/interceptor/src/main/java/org/apache/activemq/artemis/jms/example/SimpleInterceptor.java index 3077f5131b..6836930990 100644 --- a/examples/jms/interceptor/src/main/java/org/apache/activemq/artemis/jms/example/SimpleInterceptor.java +++ b/examples/jms/interceptor/src/main/java/org/apache/activemq/artemis/jms/example/SimpleInterceptor.java @@ -27,18 +27,15 @@ import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; /** * A simple Interceptor implementation */ -public class SimpleInterceptor implements Interceptor -{ +public class SimpleInterceptor implements Interceptor { - public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException - { + public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { System.out.println("SimpleInterceptor gets called!"); System.out.println("Packet: " + packet.getClass().getName()); System.out.println("RemotingConnection: " + connection.getRemoteAddress()); - if (packet instanceof SessionSendMessage) - { - SessionSendMessage realPacket = (SessionSendMessage)packet; + if (packet instanceof SessionSendMessage) { + SessionSendMessage realPacket = (SessionSendMessage) packet; Message msg = realPacket.getMessage(); msg.putStringProperty(new SimpleString("newproperty"), new SimpleString("Hello from interceptor!")); } diff --git a/examples/jms/jms-auto-closeable/src/main/java/org/apache/activemq/artemis/jms/example/JMSAutoCloseableExample.java b/examples/jms/jms-auto-closeable/src/main/java/org/apache/activemq/artemis/jms/example/JMSAutoCloseableExample.java index a4f13e8827..d53a3736b5 100644 --- a/examples/jms/jms-auto-closeable/src/main/java/org/apache/activemq/artemis/jms/example/JMSAutoCloseableExample.java +++ b/examples/jms/jms-auto-closeable/src/main/java/org/apache/activemq/artemis/jms/example/JMSAutoCloseableExample.java @@ -26,10 +26,9 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; /** * A simple JMS example that shows how AutoCloseable is used by JMS 2 resources. */ -public class JMSAutoCloseableExample -{ - public static void main(final String[] args) throws Exception - { +public class JMSAutoCloseableExample { + + public static void main(final String[] args) throws Exception { // Step 2. Perfom a lookup on the queue Queue queue = ActiveMQJMSClient.createQueue("exampleQueue"); @@ -39,8 +38,7 @@ public class JMSAutoCloseableExample // Even though ConnectionFactory is not closeable it would be nice to close an ActiveMQConnectionFactory ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(); JMSContext jmsContext = cf.createContext() - ) - { + ) { // Step 5. create a jms producer JMSProducer jmsProducer = jmsContext.createProducer(); diff --git a/examples/jms/jms-bridge/src/main/java/org/apache/activemq/artemis/jms/example/JMSBridgeExample.java b/examples/jms/jms-bridge/src/main/java/org/apache/activemq/artemis/jms/example/JMSBridgeExample.java index 13d30e702f..8a65cd5895 100644 --- a/examples/jms/jms-bridge/src/main/java/org/apache/activemq/artemis/jms/example/JMSBridgeExample.java +++ b/examples/jms/jms-bridge/src/main/java/org/apache/activemq/artemis/jms/example/JMSBridgeExample.java @@ -38,16 +38,15 @@ import org.apache.activemq.artemis.jms.bridge.impl.JNDIDestinationFactory; * The source and target destinations are located on 2 different ActiveMQ Artemis server. * The source and target queues are bridged by a JMS Bridge configured and running on the "target" server. */ -public class JMSBridgeExample -{ - public static void main(final String[] args) throws Exception - { +public class JMSBridgeExample { + + public static void main(final String[] args) throws Exception { String sourceServer = "tcp://localhost:61616"; String targetServer = "tcp://localhost:61617"; System.out.println("client will publish messages to " + sourceServer + - " and receives message from " + - targetServer); + " and receives message from " + + targetServer); // Step 1. Create JNDI contexts for source and target servers InitialContext sourceContext = JMSBridgeExample.createContext(sourceServer); @@ -57,33 +56,15 @@ public class JMSBridgeExample Hashtable targetJndiParams = createJndiParams(targetServer); // Step 2. Create and start a JMS Bridge // Note, the Bridge needs a transaction manager, in this instance we will use the JBoss TM - JMSBridge jmsBridge = new JMSBridgeImpl( - new JNDIConnectionFactoryFactory(sourceJndiParams, "ConnectionFactory"), - new JNDIConnectionFactoryFactory(targetJndiParams, "ConnectionFactory"), - new JNDIDestinationFactory(sourceJndiParams, "source/topic"), - new JNDIDestinationFactory(targetJndiParams, "target/queue"), - null, - null, - null, - null, - null, - 5000, - 10, - QualityOfServiceMode.DUPLICATES_OK, - 1, - -1, - null, - null, - true); + JMSBridge jmsBridge = new JMSBridgeImpl(new JNDIConnectionFactoryFactory(sourceJndiParams, "ConnectionFactory"), new JNDIConnectionFactoryFactory(targetJndiParams, "ConnectionFactory"), new JNDIDestinationFactory(sourceJndiParams, "source/topic"), new JNDIDestinationFactory(targetJndiParams, "target/queue"), null, null, null, null, null, 5000, 10, QualityOfServiceMode.DUPLICATES_OK, 1, -1, null, null, true); Connection sourceConnection = null; Connection targetConnection = null; - try - { + try { jmsBridge.start(); // Step 3. Lookup the *source* JMS resources - ConnectionFactory sourceConnectionFactory = (ConnectionFactory)sourceContext.lookup("ConnectionFactory"); - Topic sourceTopic = (Topic)sourceContext.lookup("source/topic"); + ConnectionFactory sourceConnectionFactory = (ConnectionFactory) sourceContext.lookup("ConnectionFactory"); + Topic sourceTopic = (Topic) sourceContext.lookup("source/topic"); // Step 4. Create a connection, a session and a message producer for the *source* topic sourceConnection = sourceConnectionFactory.createConnection(); @@ -93,17 +74,15 @@ public class JMSBridgeExample // Step 5. Create and send a text message to the *source* queue TextMessage message = sourceSession.createTextMessage("this is a text message sent at " + System.currentTimeMillis()); sourceProducer.send(message); - System.out.format("Sent message to %s: %s%n", - ((Topic)message.getJMSDestination()).getTopicName(), - message.getText()); + System.out.format("Sent message to %s: %s%n", ((Topic) message.getJMSDestination()).getTopicName(), message.getText()); System.out.format("Message ID : %s%n", message.getJMSMessageID()); // Step 6. Close the *source* connection sourceConnection.close(); // Step 7. Lookup the *target* JMS resources - ConnectionFactory targetConnectionFactory = (ConnectionFactory)targetContext.lookup("ConnectionFactory"); - Queue targetQueue = (Queue)targetContext.lookup("target/queue"); + ConnectionFactory targetConnectionFactory = (ConnectionFactory) targetContext.lookup("ConnectionFactory"); + Queue targetQueue = (Queue) targetContext.lookup("target/queue"); // Step 8. Create a connection, a session and a message consumer for the *target* queue targetConnection = targetConnectionFactory.createConnection(); @@ -114,49 +93,39 @@ public class JMSBridgeExample targetConnection.start(); // Step 10. Receive a message from the *target* queue - TextMessage messageReceived = (TextMessage)targetConsumer.receive(5000); - System.out.format("%nReceived from %s: %s%n", - ((Queue)messageReceived.getJMSDestination()).getQueueName(), - messageReceived.getText()); + TextMessage messageReceived = (TextMessage) targetConsumer.receive(5000); + System.out.format("%nReceived from %s: %s%n", ((Queue) messageReceived.getJMSDestination()).getQueueName(), messageReceived.getText()); // Step 11. Display the received message's ID and this "bridged" message ID System.out.format("Message ID : %s%n", messageReceived.getJMSMessageID()); System.out.format("Bridged Message ID : %s%n", messageReceived.getStringProperty("AMQ_BRIDGE_MSG_ID_LIST")); } - finally - { + finally { // Step 12. Be sure to close the resources! - if(jmsBridge != null) - { + if (jmsBridge != null) { jmsBridge.stop(); } - if (sourceContext != null) - { + if (sourceContext != null) { sourceContext.close(); } - if (targetContext != null) - { + if (targetContext != null) { targetContext.close(); } - if (sourceConnection != null) - { + if (sourceConnection != null) { sourceConnection.close(); } - if (targetConnection != null) - { + if (targetConnection != null) { targetConnection.close(); } } } - private static InitialContext createContext(final String server) throws Exception - { + private static InitialContext createContext(final String server) throws Exception { Hashtable jndiProps = createJndiParams(server); return new InitialContext(jndiProps); } - private static Hashtable createJndiParams(String server) - { + private static Hashtable createJndiParams(String server) { Hashtable jndiProps = new Hashtable(); jndiProps.put("connectionFactory.ConnectionFactory", server); jndiProps.put("java.naming.factory.initial", "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory"); diff --git a/examples/jms/jms-completion-listener/src/main/java/org/apache/activemq/artemis/jms/example/JMSCompletionListenerExample.java b/examples/jms/jms-completion-listener/src/main/java/org/apache/activemq/artemis/jms/example/JMSCompletionListenerExample.java index 5de38cbeb6..0d0c441f77 100644 --- a/examples/jms/jms-completion-listener/src/main/java/org/apache/activemq/artemis/jms/example/JMSCompletionListenerExample.java +++ b/examples/jms/jms-completion-listener/src/main/java/org/apache/activemq/artemis/jms/example/JMSCompletionListenerExample.java @@ -35,13 +35,11 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; /** * A JMS Completion Listener Example. */ -public class JMSCompletionListenerExample -{ - public static void main(final String[] args) throws Exception - { +public class JMSCompletionListenerExample { + + public static void main(final String[] args) throws Exception { JMSContext jmsContext = null; - try - { + try { // Step 2. Perfom a lookup on the queue Queue queue = ActiveMQJMSClient.createQueue("exampleQueue"); @@ -57,18 +55,15 @@ public class JMSCompletionListenerExample final CountDownLatch latch = new CountDownLatch(1); //Step 6. We want to send the message Asynchronously and be notified when the Broker receives it so we set a completion handler - producer.setAsync(new CompletionListener() - { + producer.setAsync(new CompletionListener() { @Override - public void onCompletion(Message message) - { + public void onCompletion(Message message) { System.out.println("message acknowledged by ActiveMQ"); latch.countDown(); } @Override - public void onException(Message message, Exception e) - { + public void onException(Message message, Exception e) { e.printStackTrace(); } }); @@ -77,15 +72,12 @@ public class JMSCompletionListenerExample producer.send(queue, "this is a string"); //Step 7. wait for the Completion handler - if (!latch.await(5, TimeUnit.SECONDS)) - { + if (!latch.await(5, TimeUnit.SECONDS)) { throw new IllegalStateException("Completion listener not called as expected."); } } - finally - { - if (jmsContext != null) - { + finally { + if (jmsContext != null) { jmsContext.close(); } } diff --git a/examples/jms/jms-context/src/main/java/org/apache/activemq/artemis/jms/example/JMSContextExample.java b/examples/jms/jms-context/src/main/java/org/apache/activemq/artemis/jms/example/JMSContextExample.java index 27be3b025e..d2a341c5d5 100644 --- a/examples/jms/jms-context/src/main/java/org/apache/activemq/artemis/jms/example/JMSContextExample.java +++ b/examples/jms/jms-context/src/main/java/org/apache/activemq/artemis/jms/example/JMSContextExample.java @@ -26,10 +26,9 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; /** * A simple JMS Queue example that creates a producer and consumer on a queue and sends then receives a message. */ -public class JMSContextExample -{ - public static void main(final String[] args) throws Exception - { +public class JMSContextExample { + + public static void main(final String[] args) throws Exception { // Instantiate the queue Queue queue = ActiveMQJMSClient.createQueue("exampleQueue"); @@ -37,8 +36,7 @@ public class JMSContextExample // Also instantiate the jmsContext // Using closeable interface try (ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(); - JMSContext jmsContext = cf.createContext()) - { + JMSContext jmsContext = cf.createContext()) { // Create a message producer, note that we can chain all this into one statement jmsContext.createProducer().setDeliveryMode(DeliveryMode.PERSISTENT).send(queue, "this is a string"); diff --git a/examples/jms/jms-shared-consumer/src/main/java/org/apache/activemq/artemis/jms/example/JMSSharedConsumerExample.java b/examples/jms/jms-shared-consumer/src/main/java/org/apache/activemq/artemis/jms/example/JMSSharedConsumerExample.java index c45f79bfb2..da43eb0805 100644 --- a/examples/jms/jms-shared-consumer/src/main/java/org/apache/activemq/artemis/jms/example/JMSSharedConsumerExample.java +++ b/examples/jms/jms-shared-consumer/src/main/java/org/apache/activemq/artemis/jms/example/JMSSharedConsumerExample.java @@ -26,15 +26,13 @@ import javax.naming.InitialContext; /** * A JMS Example that uses shared consumers. */ -public class JMSSharedConsumerExample -{ - public static void main(final String[] args) throws Exception - { +public class JMSSharedConsumerExample { + + public static void main(final String[] args) throws Exception { InitialContext initialContext = null; JMSContext jmsContext = null; JMSContext jmsContext2 = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); @@ -42,7 +40,7 @@ public class JMSSharedConsumerExample Topic topic = (Topic) initialContext.lookup("topic/exampleTopic"); // Step 3. Perform a lookup on the Connection Factory - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4.Create a JMS Context jmsContext = cf.createContext(); @@ -60,9 +58,9 @@ public class JMSSharedConsumerExample JMSConsumer jmsConsumer2 = jmsContext2.createSharedConsumer(topic, "sc1"); // Step 9. send 2 messages - producer.send(topic, "this is a String!") ; + producer.send(topic, "this is a String!"); - producer.send(topic, "this is a second String!") ; + producer.send(topic, "this is a second String!"); // Step 10. receive the messages shared by both consumers String body = jmsConsumer.receiveBody(String.class, 5000); @@ -73,19 +71,15 @@ public class JMSSharedConsumerExample System.out.println("body = " + body); } - finally - { + finally { // Step 11. Be sure to close our JMS resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (jmsContext != null) - { + if (jmsContext != null) { jmsContext.close(); } - if (jmsContext2 != null) - { + if (jmsContext2 != null) { jmsContext2.close(); } } diff --git a/examples/jms/jmx/src/main/java/org/apache/activemq/artemis/jms/example/JMXExample.java b/examples/jms/jmx/src/main/java/org/apache/activemq/artemis/jms/example/JMXExample.java index 8d36d53fff..108897f89f 100644 --- a/examples/jms/jmx/src/main/java/org/apache/activemq/artemis/jms/example/JMXExample.java +++ b/examples/jms/jmx/src/main/java/org/apache/activemq/artemis/jms/example/JMXExample.java @@ -40,24 +40,22 @@ import org.apache.activemq.artemis.api.jms.management.JMSQueueControl; /** * An example that shows how to manage ActiveMQ Artemis using JMX. */ -public class JMXExample -{ +public class JMXExample { + private static final String JMX_URL = "service:jmx:rmi:///jndi/rmi://localhost:3000/jmxrmi"; - public static void main(final String[] args) throws Exception - { + public static void main(final String[] args) throws Exception { QueueConnection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Perfom a lookup on the queue - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 3. Perform a lookup on the Connection Factory - QueueConnectionFactory cf = (QueueConnectionFactory)initialContext.lookup("ConnectionFactory"); + QueueConnectionFactory cf = (QueueConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4.Create a JMS Connection connection = cf.createQueueConnection(); @@ -85,10 +83,7 @@ public class JMXExample MBeanServerConnection mbsc = connector.getMBeanServerConnection(); // Step 12. Create a JMSQueueControl proxy to manage the queue on the server - JMSQueueControl queueControl = MBeanServerInvocationHandler.newProxyInstance(mbsc, - on, - JMSQueueControl.class, - false); + JMSQueueControl queueControl = MBeanServerInvocationHandler.newProxyInstance(mbsc, on, JMSQueueControl.class, false); // Step 13. Display the number of messages in the queue System.out.println(queueControl.getName() + " contains " + queueControl.getMessageCount() + " messages"); @@ -110,18 +105,15 @@ public class JMXExample // Step 19. Trying to receive a message. Since the only message in the queue was removed by a management // operation, there is none to consume. // The call will timeout after 5000ms and messageReceived will be null - TextMessage messageReceived = (TextMessage)messageConsumer.receive(5000); + TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000); System.out.println("Received message: " + messageReceived); } - finally - { + finally { // Step 20. Be sure to close the resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } diff --git a/examples/jms/large-message/src/main/java/org/apache/activemq/artemis/jms/example/LargeMessageExample.java b/examples/jms/large-message/src/main/java/org/apache/activemq/artemis/jms/example/LargeMessageExample.java index b7cf3de1fc..ae384863da 100644 --- a/examples/jms/large-message/src/main/java/org/apache/activemq/artemis/jms/example/LargeMessageExample.java +++ b/examples/jms/large-message/src/main/java/org/apache/activemq/artemis/jms/example/LargeMessageExample.java @@ -38,8 +38,8 @@ import java.io.IOException; * This example demonstrates the ability of ActiveMQ Artemis to send and consume a very large message, much * bigger than can fit in RAM. */ -public class LargeMessageExample -{ +public class LargeMessageExample { + /** * The message we will send is size 2GiB, even though we are only running in 50MB of RAM on both * client and server. @@ -49,26 +49,24 @@ public class LargeMessageExample */ private static final long FILE_SIZE = 2L * 1024 * 1024 * 1024; // 2 GiB message - public static void main(final String[] args) throws Exception - { + public static void main(final String[] args) throws Exception { Process server = null; Connection connection = null; InitialContext initialContext = null; - try - { + try { server = ServerUtil.startServer(args[0], LargeMessageExample.class.getSimpleName(), 0, 5000); // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Perfom a lookup on the queue - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 3. Perform a lookup on the Connection Factory. This ConnectionFactory has a special attribute set on // it. // Messages with more than 10K are considered large - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4. Create the JMS objects connection = cf.createConnection(); @@ -80,8 +78,8 @@ public class LargeMessageExample // Step 5. Create a huge file - this will form the body of the message we will send. System.out.println("Creating a file to send of size " + FILE_SIZE + - " bytes. This may take a little while... " + - "If this is too big for your disk you can easily change the FILE_SIZE in the example."); + " bytes. This may take a little while... " + + "If this is too big for your disk you can easily change the FILE_SIZE in the example."); File fileInput = new File("huge_message_to_send.dat"); @@ -129,9 +127,9 @@ public class LargeMessageExample initialContext = new InitialContext(); - queue = (Queue)initialContext.lookup("queue/exampleQueue"); + queue = (Queue) initialContext.lookup("queue/exampleQueue"); - cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); connection = cf.createConnection(); @@ -145,10 +143,10 @@ public class LargeMessageExample // Step 12. Receive the message. When we receive the large message we initially just receive the message with // an empty body. - BytesMessage messageReceived = (BytesMessage)messageConsumer.receive(120000); + BytesMessage messageReceived = (BytesMessage) messageConsumer.receive(120000); System.out.println("Received message with: " + messageReceived.getLongProperty("_AMQ_LARGE_SIZE") + - " bytes. Now streaming to file on disk."); + " bytes. Now streaming to file on disk."); // Step 13. We set an OutputStream on the message. This causes the message body to be written to the // OutputStream until there are no more bytes to be written. @@ -169,16 +167,13 @@ public class LargeMessageExample System.out.println("File streamed to disk. Size of received file on disk is " + outputFile.length()); } - finally - { + finally { // Step 12. Be sure to close our resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } @@ -192,13 +187,11 @@ public class LargeMessageExample * @throws FileNotFoundException * @throws IOException */ - private static void createFile(final File file, final long fileSize) throws IOException - { + private static void createFile(final File file, final long fileSize) throws IOException { FileOutputStream fileOut = new FileOutputStream(file); BufferedOutputStream buffOut = new BufferedOutputStream(fileOut); byte[] outBuffer = new byte[1024 * 1024]; - for (long i = 0; i < fileSize; i += outBuffer.length) - { + for (long i = 0; i < fileSize; i += outBuffer.length) { buffOut.write(outBuffer); } buffOut.close(); diff --git a/examples/jms/last-value-queue/src/main/java/org/apache/activemq/artemis/jms/example/LastValueQueueExample.java b/examples/jms/last-value-queue/src/main/java/org/apache/activemq/artemis/jms/example/LastValueQueueExample.java index 2c375037e1..469f839766 100644 --- a/examples/jms/last-value-queue/src/main/java/org/apache/activemq/artemis/jms/example/LastValueQueueExample.java +++ b/examples/jms/last-value-queue/src/main/java/org/apache/activemq/artemis/jms/example/LastValueQueueExample.java @@ -32,13 +32,11 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; * This example shows how to configure and use a Last-Value queues. * Only the last message with a well-defined property is hold by the queue. */ -public class LastValueQueueExample -{ - public static void main(final String[] args) throws Exception - { +public class LastValueQueueExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; - try - { + try { // Step 2. new Queue Queue queue = ActiveMQJMSClient.createQueue("exampleQueue"); @@ -71,9 +69,8 @@ public class LastValueQueueExample // Step 8. Browse the queue. There is only 1 message in it, the last sent QueueBrowser browser = session.createBrowser(queue); Enumeration enumeration = browser.getEnumeration(); - while (enumeration.hasMoreElements()) - { - TextMessage messageInTheQueue = (TextMessage)enumeration.nextElement(); + while (enumeration.hasMoreElements()) { + TextMessage messageInTheQueue = (TextMessage) enumeration.nextElement(); System.out.format("Message in the queue: %s%n", messageInTheQueue.getText()); } browser.close(); @@ -86,22 +83,20 @@ public class LastValueQueueExample // Step 11. Trying to receive a message. Since the queue is configured to keep only the // last message with the Last-Value header set, the message received is the last sent - TextMessage messageReceived = (TextMessage)messageConsumer.receive(5000); + TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000); System.out.format("Received message: %s%n", messageReceived.getText()); // Step 12. Trying to receive another message but there will be none. // The 1st message was discarded when the 2nd was sent to the queue. // The 2nd message was in turn discarded when the 3trd was sent to the queue - messageReceived = (TextMessage)messageConsumer.receive(5000); + messageReceived = (TextMessage) messageConsumer.receive(5000); System.out.format("Received message: %s%n", messageReceived); cf.close(); } - finally - { + finally { // Step 13. Be sure to close our JMS resources! - if (connection != null) - { + if (connection != null) { connection.close(); } } diff --git a/examples/jms/management-notifications/src/main/java/org/apache/activemq/artemis/jms/example/ManagementNotificationExample.java b/examples/jms/management-notifications/src/main/java/org/apache/activemq/artemis/jms/example/ManagementNotificationExample.java index 9b26ae4136..5fc00cf550 100644 --- a/examples/jms/management-notifications/src/main/java/org/apache/activemq/artemis/jms/example/ManagementNotificationExample.java +++ b/examples/jms/management-notifications/src/main/java/org/apache/activemq/artemis/jms/example/ManagementNotificationExample.java @@ -33,22 +33,20 @@ import javax.naming.InitialContext; /** * An example that shows how to receive management notifications using JMS messages. */ -public class ManagementNotificationExample -{ - public static void main(final String[] args) throws Exception - { +public class ManagementNotificationExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Perform a lookup on the queue - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 3. Perform a lookup on the Connection Factory - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4.Create a JMS connection, a session and a producer for the queue connection = cf.createConnection(); @@ -56,28 +54,23 @@ public class ManagementNotificationExample MessageProducer producer = session.createProducer(queue); // Step 5. Perform a lookup on the notifications topic - Topic notificationsTopic = (Topic)initialContext.lookup("topic/notificationsTopic"); + Topic notificationsTopic = (Topic) initialContext.lookup("topic/notificationsTopic"); // Step 6. Create a JMS message consumer for the notification queue and set its message listener // It will display all the properties of the JMS Message MessageConsumer notificationConsumer = session.createConsumer(notificationsTopic); - notificationConsumer.setMessageListener(new MessageListener() - { - public void onMessage(final Message notif) - { + notificationConsumer.setMessageListener(new MessageListener() { + public void onMessage(final Message notif) { System.out.println("------------------------"); System.out.println("Received notification:"); - try - { + try { Enumeration propertyNames = notif.getPropertyNames(); - while (propertyNames.hasMoreElements()) - { - String propertyName = (String)propertyNames.nextElement(); + while (propertyNames.hasMoreElements()) { + String propertyName = (String) propertyNames.nextElement(); System.out.format(" %s: %s%n", propertyName, notif.getObjectProperty(propertyName)); } } - catch (JMSException e) - { + catch (JMSException e) { } System.out.println("------------------------"); } @@ -93,27 +86,22 @@ public class ManagementNotificationExample consumer.close(); // Step 10. Try to create a connection with unknown user - try - { + try { cf.createConnection("not.a.valid.user", "not.a.valid.password"); } - catch (JMSException e) - { + catch (JMSException e) { } // sleep a little bit to be sure to receive the notification for the security // authentication violation before leaving the example Thread.sleep(2000); } - finally - { + finally { // Step 11. Be sure to close the resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } diff --git a/examples/jms/management/src/main/java/org/apache/activemq/artemis/jms/example/ManagementExample.java b/examples/jms/management/src/main/java/org/apache/activemq/artemis/jms/example/ManagementExample.java index fd92ddcb5e..8c780c36e1 100644 --- a/examples/jms/management/src/main/java/org/apache/activemq/artemis/jms/example/ManagementExample.java +++ b/examples/jms/management/src/main/java/org/apache/activemq/artemis/jms/example/ManagementExample.java @@ -34,22 +34,20 @@ import org.apache.activemq.artemis.api.jms.management.JMSManagementHelper; /** * An example that shows how to manage ActiveMQ Artemis using JMS messages. */ -public class ManagementExample -{ - public static void main(final String[] args) throws Exception - { +public class ManagementExample { + + public static void main(final String[] args) throws Exception { QueueConnection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Perfom a lookup on the queue - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 3. Perform a lookup on the Connection Factory - QueueConnectionFactory cf = (QueueConnectionFactory)initialContext.lookup("ConnectionFactory"); + QueueConnectionFactory cf = (QueueConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4.Create a JMS Connection connection = cf.createQueueConnection(); @@ -89,7 +87,7 @@ public class ManagementExample Message reply = requestor.request(m); // Step 15. Use a helper class to retrieve the operation result - int messageCount = (Integer)JMSManagementHelper.getResult(reply); + int messageCount = (Integer) JMSManagementHelper.getResult(reply); System.out.println(queue.getQueueName() + " contains " + messageCount + " messages"); // Step 16. Create another JMS message to use as a management message @@ -99,10 +97,7 @@ public class ManagementExample // * the object name of the resource to manage (i.e. the queue) // * in this case, we want to call the "removeMessage" operation with the JMS MessageID // of the message sent to the queue in step 8. - JMSManagementHelper.putOperationInvocation(m, - "jms.queue.exampleQueue", - "removeMessage", - message.getJMSMessageID()); + JMSManagementHelper.putOperationInvocation(m, "jms.queue.exampleQueue", "removeMessage", message.getJMSMessageID()); // Step 18 Use the requestor to send the request and wait for the reply reply = requestor.request(m); @@ -113,7 +108,7 @@ public class ManagementExample // Step 20. Use a helper class to retrieve the operation result // in that case, a boolean which is true if the message was removed, false else - boolean messageRemoved = (Boolean)JMSManagementHelper.getResult(reply); + boolean messageRemoved = (Boolean) JMSManagementHelper.getResult(reply); System.out.println("message has been removed: " + messageRemoved); // Step 21. Create a JMS Message Consumer on the queue @@ -122,18 +117,15 @@ public class ManagementExample // Step 22. Trying to receive a message. Since the only message in the queue was removed by a management // operation, // there is none to consume. The call will timeout after 5000ms and messageReceived will be null - TextMessage messageReceived = (TextMessage)messageConsumer.receive(5000); + TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000); System.out.println("Received message: " + messageReceived); } - finally - { + finally { // Step 23. Be sure to close the resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } diff --git a/examples/jms/message-counters/src/main/java/org/apache/activemq/artemis/jms/example/MessageCounterExample.java b/examples/jms/message-counters/src/main/java/org/apache/activemq/artemis/jms/example/MessageCounterExample.java index 1e9865f1a9..8e6cc26aea 100644 --- a/examples/jms/message-counters/src/main/java/org/apache/activemq/artemis/jms/example/MessageCounterExample.java +++ b/examples/jms/message-counters/src/main/java/org/apache/activemq/artemis/jms/example/MessageCounterExample.java @@ -41,24 +41,22 @@ import org.apache.activemq.artemis.api.jms.management.JMSQueueControl; /** * An example showing how to use message counters to have information on a queue. */ -public class MessageCounterExample -{ +public class MessageCounterExample { + private static final String JMX_URL = "service:jmx:rmi:///jndi/rmi://localhost:3001/jmxrmi"; - public static void main(final String[] args) throws Exception - { + public static void main(final String[] args) throws Exception { QueueConnection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Perfom a lookup on the queue - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 3. Perform a lookup on the Connection Factory - QueueConnectionFactory cf = (QueueConnectionFactory)initialContext.lookup("ConnectionFactory"); + QueueConnectionFactory cf = (QueueConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4.Create a JMS Connection, session and a producer for the queue connection = cf.createQueueConnection(); @@ -76,13 +74,9 @@ public class MessageCounterExample // Step 7. Use JMX to retrieve the message counters using the JMSQueueControl ObjectName on = ObjectNameBuilder.DEFAULT.getJMSQueueObjectName(queue.getQueueName()); - JMXConnector connector = - JMXConnectorFactory.connect(new JMXServiceURL(JMX_URL), new HashMap()); + JMXConnector connector = JMXConnectorFactory.connect(new JMXServiceURL(JMX_URL), new HashMap()); MBeanServerConnection mbsc = connector.getMBeanServerConnection(); - JMSQueueControl queueControl = MBeanServerInvocationHandler.newProxyInstance(mbsc, - on, - JMSQueueControl.class, - false); + JMSQueueControl queueControl = MBeanServerInvocationHandler.newProxyInstance(mbsc, on, JMSQueueControl.class, false); // Step 8. List the message counters and convert them to MessageCounterInfo data structure. String counters = queueControl.listMessageCounter(); @@ -107,7 +101,7 @@ public class MessageCounterExample connection.start(); // Step 14. Receive a JMS message from the queue. It corresponds to the message sent at step #5 - TextMessage messageReceived = (TextMessage)consumer.receive(5000); + TextMessage messageReceived = (TextMessage) consumer.receive(5000); System.out.format("Received message: %s%n%n", messageReceived.getText()); // Step 15. Sleep on last time to have the queue sampled @@ -119,29 +113,21 @@ public class MessageCounterExample messageCounter = MessageCounterInfo.fromJSON(counters); displayMessageCounter(messageCounter); } - finally - { + finally { // Step 17. Be sure to close our JMS resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } } - private static void displayMessageCounter(final MessageCounterInfo counter) - { + private static void displayMessageCounter(final MessageCounterInfo counter) { System.out.format("%s (sample updated at %s)%n", counter.getName(), counter.getUdpateTimestamp()); - System.out.format(" %s message(s) added to the queue (since last sample: %s)%n", - counter.getCount(), - counter.getCountDelta()); - System.out.format(" %s message(s) in the queue (since last sample: %s)%n", - counter.getDepth(), - counter.getDepthDelta()); + System.out.format(" %s message(s) added to the queue (since last sample: %s)%n", counter.getCount(), counter.getCountDelta()); + System.out.format(" %s message(s) in the queue (since last sample: %s)%n", counter.getDepth(), counter.getDepthDelta()); System.out.format(" last message added at %s%n%n", counter.getLastAddTimestamp()); } diff --git a/examples/jms/message-group/src/main/java/org/apache/activemq/artemis/jms/example/MessageGroupExample.java b/examples/jms/message-group/src/main/java/org/apache/activemq/artemis/jms/example/MessageGroupExample.java index 7acf3c4b67..c614860e4e 100644 --- a/examples/jms/message-group/src/main/java/org/apache/activemq/artemis/jms/example/MessageGroupExample.java +++ b/examples/jms/message-group/src/main/java/org/apache/activemq/artemis/jms/example/MessageGroupExample.java @@ -34,14 +34,12 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; /** * A simple JMS Queue example that sends and receives message groups. */ -public class MessageGroupExample -{ - public static void main(final String[] args) throws Exception - { +public class MessageGroupExample { + + public static void main(final String[] args) throws Exception { final Map messageReceiverMap = new ConcurrentHashMap(); Connection connection = null; - try - { + try { // Step 2. Perform a lookup on the queue Queue queue = ActiveMQJMSClient.createQueue("queue/exampleQueue"); @@ -67,8 +65,7 @@ public class MessageGroupExample // Step 8. Create and send 10 text messages with group id 'Group-0' int msgCount = 10; TextMessage[] groupMessages = new TextMessage[msgCount]; - for (int i = 0; i < msgCount; i++) - { + for (int i = 0; i < msgCount; i++) { groupMessages[i] = session.createTextMessage("Group-0 message " + i); groupMessages[i].setStringProperty("JMSXGroupID", "Group-0"); producer.send(groupMessages[i]); @@ -84,49 +81,41 @@ public class MessageGroupExample // Step 10. check the group messages are received by only one consumer String trueReceiver = messageReceiverMap.get(groupMessages[0].getText()); - for (TextMessage grpMsg : groupMessages) - { + for (TextMessage grpMsg : groupMessages) { String receiver = messageReceiverMap.get(grpMsg.getText()); - if (!trueReceiver.equals(receiver)) - { + if (!trueReceiver.equals(receiver)) { throw new IllegalStateException("Group message [" + grpMsg.getText() + "[ went to wrong receiver: " + receiver); } } cf.close(); } - finally - { + finally { // Step 11. Be sure to close our JMS resources! - if (connection != null) - { + if (connection != null) { connection.close(); } } } } -class SimpleMessageListener implements MessageListener -{ +class SimpleMessageListener implements MessageListener { + private final String name; private final Map messageReceiverMap; - public SimpleMessageListener(final String listenerName, Map messageReceiverMap) - { + public SimpleMessageListener(final String listenerName, Map messageReceiverMap) { name = listenerName; this.messageReceiverMap = messageReceiverMap; } - public void onMessage(final Message message) - { - try - { - TextMessage msg = (TextMessage)message; + public void onMessage(final Message message) { + try { + TextMessage msg = (TextMessage) message; System.out.format("Message: [%s] received by %s%n", msg.getText(), name); messageReceiverMap.put(msg.getText(), name); } - catch (JMSException e) - { + catch (JMSException e) { e.printStackTrace(); } } diff --git a/examples/jms/message-group2/src/main/java/org/apache/activemq/artemis/jms/example/MessageGroup2Example.java b/examples/jms/message-group2/src/main/java/org/apache/activemq/artemis/jms/example/MessageGroup2Example.java index c70c932bfa..a2164cfcf0 100644 --- a/examples/jms/message-group2/src/main/java/org/apache/activemq/artemis/jms/example/MessageGroup2Example.java +++ b/examples/jms/message-group2/src/main/java/org/apache/activemq/artemis/jms/example/MessageGroup2Example.java @@ -34,16 +34,14 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; /** * A simple JMS Queue example that sends and receives message groups. */ -public class MessageGroup2Example -{ +public class MessageGroup2Example { + private boolean result = true; - public static void main(String[] args) throws Exception - { + public static void main(String[] args) throws Exception { final Map messageReceiverMap = new ConcurrentHashMap(); Connection connection = null; - try - { + try { //Step 2. Perform a lookup on the queue Queue queue = ActiveMQJMSClient.createQueue("exampleQueue"); @@ -69,8 +67,7 @@ public class MessageGroup2Example //Step 8. Create and send 10 text messages with each producer int msgCount = 10; - for (int i = 0; i < msgCount; i++) - { + for (int i = 0; i < msgCount; i++) { TextMessage m = session.createTextMessage("producer1 message " + i); producer1.send(m); System.out.println("Sent message: " + m.getText()); @@ -89,54 +86,43 @@ public class MessageGroup2Example //Step 10. check the group messages are received by only one consumer String trueReceiver = messageReceiverMap.get("producer1 message " + 0); - for (int i = 0; i < msgCount; i++) - { + for (int i = 0; i < msgCount; i++) { String receiver = messageReceiverMap.get("producer1 message " + i); - if (!trueReceiver.equals(receiver)) - { + if (!trueReceiver.equals(receiver)) { throw new IllegalStateException("Group message [producer1 message " + i + "] went to wrong receiver: " + receiver); } receiver = messageReceiverMap.get("producer2 message " + i); - if (!trueReceiver.equals(receiver)) - { + if (!trueReceiver.equals(receiver)) { throw new IllegalStateException("Group message [producer2 message " + i + "] went to wrong receiver: " + receiver); } } } - finally - { + finally { //Step 11. Be sure to close our JMS resources! - if(connection != null) - { + if (connection != null) { connection.close(); } } } } -class SimpleMessageListener implements MessageListener -{ +class SimpleMessageListener implements MessageListener { + private final String name; final Map messageReceiverMap; - public SimpleMessageListener(String listenerName, Map messageReceiverMap) - { + public SimpleMessageListener(String listenerName, Map messageReceiverMap) { name = listenerName; this.messageReceiverMap = messageReceiverMap; } - public void onMessage(Message message) - { - try - { - TextMessage msg = (TextMessage)message; - System.out.format("Message: [%s] received by %s%n", - msg.getText(), - name); + public void onMessage(Message message) { + try { + TextMessage msg = (TextMessage) message; + System.out.format("Message: [%s] received by %s%n", msg.getText(), name); messageReceiverMap.put(msg.getText(), name); } - catch (JMSException e) - { + catch (JMSException e) { e.printStackTrace(); } } diff --git a/examples/jms/message-priority/src/main/java/org/apache/activemq/artemis/jms/example/MessagePriorityExample.java b/examples/jms/message-priority/src/main/java/org/apache/activemq/artemis/jms/example/MessagePriorityExample.java index 5f137feadd..f54e5edb1a 100644 --- a/examples/jms/message-priority/src/main/java/org/apache/activemq/artemis/jms/example/MessagePriorityExample.java +++ b/examples/jms/message-priority/src/main/java/org/apache/activemq/artemis/jms/example/MessagePriorityExample.java @@ -38,15 +38,13 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; /** * A simple JMS example that shows the delivery order of messages with priorities. */ -public class MessagePriorityExample -{ - public static void main(final String[] args) throws Exception - { +public class MessagePriorityExample { + + public static void main(final String[] args) throws Exception { AtomicBoolean result = new AtomicBoolean(true); final ArrayList msgReceived = new ArrayList(); Connection connection = null; - try - { + try { // Step 2. look-up the JMS queue object from JNDI Queue queue = ActiveMQJMSClient.createQueue("exampleQueue"); @@ -76,16 +74,16 @@ public class MessagePriorityExample // Step 9. Send the Messages, each has a different priority producer.send(sentMessages[0]); System.out.println("Message sent: " + sentMessages[0].getText() + - " with priority: " + - sentMessages[0].getJMSPriority()); + " with priority: " + + sentMessages[0].getJMSPriority()); producer.send(sentMessages[1], DeliveryMode.NON_PERSISTENT, 5, 0); System.out.println("Message sent: " + sentMessages[1].getText() + - "with priority: " + - sentMessages[1].getJMSPriority()); + "with priority: " + + sentMessages[1].getJMSPriority()); producer.send(sentMessages[2], DeliveryMode.NON_PERSISTENT, 9, 0); System.out.println("Message sent: " + sentMessages[2].getText() + - "with priority: " + - sentMessages[2].getJMSPriority()); + "with priority: " + + sentMessages[2].getJMSPriority()); // Step 10. Start the connection now. connection.start(); @@ -94,11 +92,9 @@ public class MessagePriorityExample Thread.sleep(5000); // Step 12. Examine the order - for (int i = 0; i < 3; i++) - { + for (int i = 0; i < 3; i++) { TextMessage rm = msgReceived.get(i); - if (!rm.getText().equals(sentMessages[2 - i].getText())) - { + if (!rm.getText().equals(sentMessages[2 - i].getText())) { throw new IllegalStateException("Priority is broken!"); } } @@ -106,37 +102,31 @@ public class MessagePriorityExample if (!result.get()) throw new IllegalStateException(); } - finally - { + finally { // Step 13. Be sure to close our JMS resources! - if (connection != null) - { + if (connection != null) { connection.close(); } } } } -class SimpleMessageListener implements MessageListener -{ +class SimpleMessageListener implements MessageListener { + ArrayList msgReceived; AtomicBoolean result; - public SimpleMessageListener(ArrayList msgReceived, AtomicBoolean result) - { + public SimpleMessageListener(ArrayList msgReceived, AtomicBoolean result) { this.msgReceived = msgReceived; this.result = result; } - public void onMessage(final Message msg) - { - TextMessage textMessage = (TextMessage)msg; - try - { + public void onMessage(final Message msg) { + TextMessage textMessage = (TextMessage) msg; + try { System.out.println("Received message : [" + textMessage.getText() + "]"); } - catch (JMSException e) - { + catch (JMSException e) { result.set(false); } msgReceived.add(textMessage); diff --git a/examples/jms/multiple-failover-failback/src/main/java/org/apache/activemq/artemis/jms/example/MultipleFailoverFailbackExample.java b/examples/jms/multiple-failover-failback/src/main/java/org/apache/activemq/artemis/jms/example/MultipleFailoverFailbackExample.java index dcfb685874..ab0baecedc 100644 --- a/examples/jms/multiple-failover-failback/src/main/java/org/apache/activemq/artemis/jms/example/MultipleFailoverFailbackExample.java +++ b/examples/jms/multiple-failover-failback/src/main/java/org/apache/activemq/artemis/jms/example/MultipleFailoverFailbackExample.java @@ -28,10 +28,9 @@ import javax.jms.Session; import javax.jms.TextMessage; import javax.naming.InitialContext; -public class MultipleFailoverFailbackExample -{ - public static void main(final String[] args) throws Exception - { +public class MultipleFailoverFailbackExample { + + public static void main(final String[] args) throws Exception { final int numMessages = 30; Connection connection = null; @@ -40,10 +39,8 @@ public class MultipleFailoverFailbackExample Process[] servers = new Process[3]; - try - { - for (int i = 0; i < args.length; i++) - { + try { + for (int i = 0; i < args.length; i++) { servers[i] = ServerUtil.startServer(args[i], MultipleFailoverFailbackExample.class.getSimpleName() + i, i, 5000); } @@ -51,8 +48,8 @@ public class MultipleFailoverFailbackExample initialContext = new InitialContext(); // Step 2. Look up the JMS resources from JNDI - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); - ConnectionFactory connectionFactory = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); + ConnectionFactory connectionFactory = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 3. Create a JMS Connection connection = connectionFactory.createConnection(); @@ -68,8 +65,7 @@ public class MultipleFailoverFailbackExample MessageConsumer consumer = session.createConsumer(queue); // Step 7. Send some messages to server #1, the live server - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session.createTextMessage("This is text message " + i); producer.send(message); System.out.println("Sent message: " + message.getText()); @@ -77,17 +73,15 @@ public class MultipleFailoverFailbackExample // Step 8. Receive and acknowledge a third of the sent messages TextMessage message0 = null; - for (int i = 0; i < numMessages / 3; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = 0; i < numMessages / 3; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.println("Got message: " + message0.getText()); } message0.acknowledge(); // Step 9. Receive the rest third of the sent messages but *do not* acknowledge them yet - for (int i = numMessages / 3; i < numMessages; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = numMessages / 3; i < numMessages; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.println("Got message: " + message0.getText()); } @@ -97,19 +91,16 @@ public class MultipleFailoverFailbackExample // Step 11. Acknowledging the 2nd half of the sent messages will fail as failover to the // backup server has occurred - try - { + try { message0.acknowledge(); } - catch (JMSException e) - { + catch (JMSException e) { System.err.println("Got exception while acknowledging message: " + e.getMessage()); } // Step 12. Consume again the 2nd third of the messages again. Note that they are not considered as redelivered. - for (int i = numMessages / 3; i < (numMessages / 3) * 2; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = numMessages / 3; i < (numMessages / 3) * 2; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.printf("Got message: %s (redelivered?: %s)%n", message0.getText(), message0.getJMSRedelivered()); } message0.acknowledge(); @@ -118,39 +109,32 @@ public class MultipleFailoverFailbackExample // Step 11. Acknowledging the 2nd half of the sent messages will fail as failover to the // backup server has occurred - try - { + try { message0.acknowledge(); } - catch (JMSException e) - { + catch (JMSException e) { System.err.println("Got exception while acknowledging message: " + e.getMessage()); } // Step 12. Consume again the 2nd third of the messages again. Note that they are not considered as redelivered. - for (int i = (numMessages / 3) * 2; i < numMessages; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = (numMessages / 3) * 2; i < numMessages; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.printf("Got message: %s (redelivered?: %s)%n", message0.getText(), message0.getJMSRedelivered()); } message0.acknowledge(); } - finally - { + finally { // Step 13. Be sure to close our resources! - if (connection != null) - { + if (connection != null) { connection.close(); } - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - for (int i = 0; i < args.length; i++) - { + for (int i = 0; i < args.length; i++) { ServerUtil.killServer(servers[i]); } } diff --git a/examples/jms/multiple-failover/src/main/java/org/apache/activemq/artemis/jms/example/MultipleFailoverExample.java b/examples/jms/multiple-failover/src/main/java/org/apache/activemq/artemis/jms/example/MultipleFailoverExample.java index 928e6fbf91..41d9e52c33 100644 --- a/examples/jms/multiple-failover/src/main/java/org/apache/activemq/artemis/jms/example/MultipleFailoverExample.java +++ b/examples/jms/multiple-failover/src/main/java/org/apache/activemq/artemis/jms/example/MultipleFailoverExample.java @@ -28,10 +28,9 @@ import javax.jms.Session; import javax.jms.TextMessage; import javax.naming.InitialContext; -public class MultipleFailoverExample -{ - public static void main(final String[] args) throws Exception - { +public class MultipleFailoverExample { + + public static void main(final String[] args) throws Exception { final int numMessages = 30; Connection connection = null; @@ -40,10 +39,8 @@ public class MultipleFailoverExample Process[] servers = new Process[3]; - try - { - for (int i = 0; i < args.length; i++) - { + try { + for (int i = 0; i < args.length; i++) { servers[i] = ServerUtil.startServer(args[i], MultipleFailoverExample.class.getSimpleName() + i, i, 5000); } @@ -51,8 +48,8 @@ public class MultipleFailoverExample initialContext = new InitialContext(); // Step 2. Look up the JMS resources from JNDI - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); - ConnectionFactory connectionFactory = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); + ConnectionFactory connectionFactory = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 3. Create a JMS Connection connection = connectionFactory.createConnection(); @@ -68,8 +65,7 @@ public class MultipleFailoverExample MessageConsumer consumer = session.createConsumer(queue); // Step 7. Send some messages to server #1, the live server - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session.createTextMessage("This is text message " + i); producer.send(message); System.out.println("Sent message: " + message.getText()); @@ -77,17 +73,15 @@ public class MultipleFailoverExample // Step 8. Receive and acknowledge a third of the sent messages TextMessage message0 = null; - for (int i = 0; i < numMessages / 3; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = 0; i < numMessages / 3; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.println("Got message: " + message0.getText()); } message0.acknowledge(); // Step 9. Receive the rest third of the sent messages but *do not* acknowledge them yet - for (int i = numMessages / 3; i < numMessages; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = numMessages / 3; i < numMessages; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.println("Got message: " + message0.getText()); } @@ -97,19 +91,16 @@ public class MultipleFailoverExample // Step 11. Acknowledging the 2nd half of the sent messages will fail as failover to the // backup server has occurred - try - { + try { message0.acknowledge(); } - catch (JMSException e) - { + catch (JMSException e) { System.err.println("Got exception while acknowledging message: " + e.getMessage()); } // Step 12. Consume again the 2nd third of the messages again. Note that they are not considered as redelivered. - for (int i = numMessages / 3; i < (numMessages / 3) * 2; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = numMessages / 3; i < (numMessages / 3) * 2; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.printf("Got message: %s (redelivered?: %s)%n", message0.getText(), message0.getJMSRedelivered()); } message0.acknowledge(); @@ -118,39 +109,32 @@ public class MultipleFailoverExample // Step 11. Acknowledging the 2nd half of the sent messages will fail as failover to the // backup server has occurred - try - { + try { message0.acknowledge(); } - catch (JMSException e) - { + catch (JMSException e) { throw new IllegalStateException("Got exception while acknowledging message: " + e.getMessage()); } // Step 12. Consume again the 2nd third of the messages again. Note that they are not considered as redelivered. - for (int i = (numMessages / 3) * 2; i < numMessages; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = (numMessages / 3) * 2; i < numMessages; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.printf("Got message: %s (redelivered?: %s)%n", message0.getText(), message0.getJMSRedelivered()); } message0.acknowledge(); } - finally - { + finally { // Step 13. Be sure to close our resources! - if (connection != null) - { + if (connection != null) { connection.close(); } - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - for (int i = 0; i < args.length; i++) - { + for (int i = 0; i < args.length; i++) { ServerUtil.killServer(servers[i]); } } diff --git a/examples/jms/no-consumer-buffering/src/main/java/org/apache/activemq/artemis/jms/example/NoConsumerBufferingExample.java b/examples/jms/no-consumer-buffering/src/main/java/org/apache/activemq/artemis/jms/example/NoConsumerBufferingExample.java index c7fdf5618d..6f321b08d4 100644 --- a/examples/jms/no-consumer-buffering/src/main/java/org/apache/activemq/artemis/jms/example/NoConsumerBufferingExample.java +++ b/examples/jms/no-consumer-buffering/src/main/java/org/apache/activemq/artemis/jms/example/NoConsumerBufferingExample.java @@ -31,13 +31,11 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; * This example demonstrates how ActiveMQ Artemis consumers can be configured to not buffer any messages from * the server. */ -public class NoConsumerBufferingExample -{ - public static void main(final String[] args) throws Exception - { +public class NoConsumerBufferingExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; - try - { + try { // Step 2. Perfom a lookup on the queue Queue queue = ActiveMQJMSClient.createQueue("exampleQueue"); @@ -65,8 +63,7 @@ public class NoConsumerBufferingExample final int numMessages = 10; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session.createTextMessage("This is text message: " + i); producer.send(message); @@ -80,37 +77,32 @@ public class NoConsumerBufferingExample // Step 11. Consume three messages from consumer2 - for (int i = 0; i < 3; i++) - { - TextMessage message = (TextMessage)consumer2.receive(2000); + for (int i = 0; i < 3; i++) { + TextMessage message = (TextMessage) consumer2.receive(2000); System.out.println("Consumed message from consumer2: " + message.getText()); } // Step 12. Consume five messages from consumer1 - for (int i = 0; i < 5; i++) - { - TextMessage message = (TextMessage)consumer1.receive(2000); + for (int i = 0; i < 5; i++) { + TextMessage message = (TextMessage) consumer1.receive(2000); System.out.println("Consumed message from consumer1: " + message.getText()); } // Step 13. Consume another two messages from consumer2 - for (int i = 0; i < 2; i++) - { - TextMessage message = (TextMessage)consumer2.receive(2000); + for (int i = 0; i < 2; i++) { + TextMessage message = (TextMessage) consumer2.receive(2000); System.out.println("Consumed message from consumer1: " + message.getText()); } } - finally - { + finally { // Step 9. Be sure to close our resources! - if (connection != null) - { + if (connection != null) { connection.close(); } } diff --git a/examples/jms/non-transaction-failover/src/main/java/org/apache/activemq/artemis/jms/example/NonTransactionFailoverExample.java b/examples/jms/non-transaction-failover/src/main/java/org/apache/activemq/artemis/jms/example/NonTransactionFailoverExample.java index c5560722d7..9352ac5ca0 100644 --- a/examples/jms/non-transaction-failover/src/main/java/org/apache/activemq/artemis/jms/example/NonTransactionFailoverExample.java +++ b/examples/jms/non-transaction-failover/src/main/java/org/apache/activemq/artemis/jms/example/NonTransactionFailoverExample.java @@ -32,10 +32,9 @@ import javax.naming.InitialContext; * A simple example that demonstrates failover of the JMS connection from one node to another * when the live server crashes using a JMS non-transacted session. */ -public class NonTransactionFailoverExample -{ - public static void main(final String[] args) throws Exception - { +public class NonTransactionFailoverExample { + + public static void main(final String[] args) throws Exception { final int numMessages = 10; Connection connection = null; @@ -44,10 +43,8 @@ public class NonTransactionFailoverExample Process[] servers = new Process[2]; - try - { - for (int i = 0; i < args.length; i++) - { + try { + for (int i = 0; i < args.length; i++) { servers[i] = ServerUtil.startServer(args[i], NonTransactionFailoverExample.class.getSimpleName() + i, i, 5000); } @@ -55,8 +52,8 @@ public class NonTransactionFailoverExample initialContext = new InitialContext(); // Step 2. Look up the JMS resources from JNDI - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); - ConnectionFactory connectionFactory = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); + ConnectionFactory connectionFactory = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 3. Create a JMS Connection connection = connectionFactory.createConnection(); @@ -72,8 +69,7 @@ public class NonTransactionFailoverExample MessageConsumer consumer = session.createConsumer(queue); // Step 7. Send some messages to server #1, the live server - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session.createTextMessage("This is text message " + i); producer.send(message); System.out.println("Sent message: " + message.getText()); @@ -81,17 +77,15 @@ public class NonTransactionFailoverExample // Step 8. Receive and acknowledge half of the sent messages TextMessage message0 = null; - for (int i = 0; i < numMessages / 2; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = 0; i < numMessages / 2; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.println("Got message: " + message0.getText()); } message0.acknowledge(); // Step 9. Receive the 2nd half of the sent messages but *do not* acknowledge them yet - for (int i = numMessages / 2; i < numMessages; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = numMessages / 2; i < numMessages; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.println("Got message: " + message0.getText()); } @@ -101,39 +95,32 @@ public class NonTransactionFailoverExample // Step 11. Acknowledging the 2nd half of the sent messages will fail as failover to the // backup server has occurred - try - { + try { message0.acknowledge(); } - catch (JMSException e) - { + catch (JMSException e) { System.err.println("Got exception while acknowledging message: " + e.getMessage()); } // Step 12. Consume again the 2nd half of the messages again. Note that they are not considered as redelivered. - for (int i = numMessages / 2; i < numMessages; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = numMessages / 2; i < numMessages; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.printf("Got message: %s (redelivered?: %s)%n", message0.getText(), message0.getJMSRedelivered()); } message0.acknowledge(); } - finally - { + finally { // Step 13. Be sure to close our resources! - if (connection != null) - { + if (connection != null) { connection.close(); } - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - for (int i = 0; i < args.length; i++) - { + for (int i = 0; i < args.length; i++) { ServerUtil.killServer(servers[i]); } } diff --git a/examples/jms/paging/src/main/java/org/apache/activemq/artemis/jms/example/PagingExample.java b/examples/jms/paging/src/main/java/org/apache/activemq/artemis/jms/example/PagingExample.java index 77f8eb6595..19d8a178ab 100644 --- a/examples/jms/paging/src/main/java/org/apache/activemq/artemis/jms/example/PagingExample.java +++ b/examples/jms/paging/src/main/java/org/apache/activemq/artemis/jms/example/PagingExample.java @@ -29,27 +29,25 @@ import javax.naming.InitialContext; /** * A simple JMS Queue example that creates a producer and consumer on a queue and sends then receives a message. */ -public class PagingExample -{ - public static void main(final String[] args) throws Exception - { +public class PagingExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Perform a lookup on the Connection Factory - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 3. We look-up the JMS queue object from JNDI. pagingQueue is configured to hold a very limited number // of bytes in memory - Queue pageQueue = (Queue)initialContext.lookup("queue/pagingQueue"); + Queue pageQueue = (Queue) initialContext.lookup("queue/pagingQueue"); // Step 4. Lookup for a JMS Queue - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 5. Create a JMS Connection connection = cf.createConnection(); @@ -69,8 +67,7 @@ public class PagingExample // Step 10. Send only 20 messages to the Queue. This will be already enough for pagingQueue. Look at // ./paging/config/activemq-queues.xml for the config. - for (int i = 0; i < 20; i++) - { + for (int i = 0; i < 20; i++) { pageMessageProducer.send(message); } @@ -81,8 +78,7 @@ public class PagingExample messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); // Step 13. Send the message for about 1K, which should be over the memory limit imposed by the server - for (int i = 0; i < 1000; i++) - { + for (int i = 0; i < 1000; i++) { messageProducer.send(message); } @@ -100,12 +96,10 @@ public class PagingExample // paging // until messages are ACKed - for (int i = 0; i < 1000; i++) - { - message = (BytesMessage)messageConsumer.receive(3000); + for (int i = 0; i < 1000; i++) { + message = (BytesMessage) messageConsumer.receive(3000); - if (i % 100 == 0) - { + if (i % 100 == 0) { System.out.println("Received " + i + " messages"); message.acknowledge(); } @@ -117,27 +111,23 @@ public class PagingExample messageConsumer.close(); messageConsumer = session.createConsumer(pageQueue); - for (int i = 0; i < 20; i++) - { - message = (BytesMessage)messageConsumer.receive(1000); + for (int i = 0; i < 20; i++) { + message = (BytesMessage) messageConsumer.receive(1000); System.out.println("Received message " + i + " from pageQueue"); message.acknowledge(); } } - finally - { + finally { // And finally, always remember to close your JMS connections after use, in a finally block. Closing a JMS // connection will automatically close all of its sessions, consumers, producer and browser objects - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } diff --git a/examples/jms/perf/src/main/java/org/apache/activemq/artemis/jms/example/PerfBase.java b/examples/jms/perf/src/main/java/org/apache/activemq/artemis/jms/example/PerfBase.java index 8909f49be5..869ee09a49 100644 --- a/examples/jms/perf/src/main/java/org/apache/activemq/artemis/jms/example/PerfBase.java +++ b/examples/jms/perf/src/main/java/org/apache/activemq/artemis/jms/example/PerfBase.java @@ -30,60 +30,51 @@ import javax.naming.InitialContext; import org.apache.activemq.artemis.utils.TokenBucketLimiter; import org.apache.activemq.artemis.utils.TokenBucketLimiterImpl; -public abstract class PerfBase -{ +public abstract class PerfBase { + private static final Logger log = Logger.getLogger(PerfSender.class.getName()); private static final String DEFAULT_PERF_PROPERTIES_FILE_NAME = "target/classes/perf.properties"; - private static byte[] randomByteArray(final int length) - { + private static byte[] randomByteArray(final int length) { byte[] bytes = new byte[length]; Random random = new Random(); - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { bytes[i] = Integer.valueOf(random.nextInt()).byteValue(); } return bytes; } - protected static String getPerfFileName(final String[] args) - { + protected static String getPerfFileName(final String[] args) { String fileName; - if (args.length > 0) - { + if (args.length > 0) { fileName = args[0]; } - else - { + else { fileName = PerfBase.DEFAULT_PERF_PROPERTIES_FILE_NAME; } return fileName; } - protected static PerfParams getParams(final String fileName) throws Exception - { + protected static PerfParams getParams(final String fileName) throws Exception { Properties props = null; InputStream is = null; - try - { + try { is = new FileInputStream(fileName); props = new Properties(); props.load(is); } - finally - { - if (is != null) - { + finally { + if (is != null) { is.close(); } } @@ -136,8 +127,7 @@ public abstract class PerfBase private final PerfParams perfParams; - protected PerfBase(final PerfParams perfParams) - { + protected PerfBase(final PerfParams perfParams) { this.perfParams = perfParams; } @@ -151,103 +141,71 @@ public abstract class PerfBase private long start; - private void init() throws Exception - { + private void init() throws Exception { InitialContext ic = new InitialContext(); System.out.println("ic = " + ic); - factory = (ConnectionFactory)ic.lookup(perfParams.getConnectionFactoryLookup()); + factory = (ConnectionFactory) ic.lookup(perfParams.getConnectionFactoryLookup()); - destination = (Destination)ic.lookup(perfParams.getDestinationLookup()); + destination = (Destination) ic.lookup(perfParams.getDestinationLookup()); connection = factory.createConnection(); - session = connection.createSession(perfParams.isSessionTransacted(), - perfParams.isDupsOK() ? Session.DUPS_OK_ACKNOWLEDGE : Session.AUTO_ACKNOWLEDGE); + session = connection.createSession(perfParams.isSessionTransacted(), perfParams.isDupsOK() ? Session.DUPS_OK_ACKNOWLEDGE : Session.AUTO_ACKNOWLEDGE); ic.close(); } - private void displayAverage(final long numberOfMessages, final long start, final long end) - { + private void displayAverage(final long numberOfMessages, final long start, final long end) { double duration = (1.0 * end - start) / 1000; // in seconds double average = 1.0 * numberOfMessages / duration; - PerfBase.log.info(String.format("average: %.2f msg/s (%d messages in %2.2fs)", - average, - numberOfMessages, - duration)); + PerfBase.log.info(String.format("average: %.2f msg/s (%d messages in %2.2fs)", average, numberOfMessages, duration)); } - protected void runSender() - { - try - { + protected void runSender() { + try { init(); - if (perfParams.isDrainQueue()) - { + if (perfParams.isDrainQueue()) { drainQueue(); } start = System.currentTimeMillis(); PerfBase.log.info("warming up by sending " + perfParams.getNoOfWarmupMessages() + " messages"); - sendMessages(perfParams.getNoOfWarmupMessages(), - perfParams.getBatchSize(), - perfParams.isDurable(), - perfParams.isSessionTransacted(), - false, - perfParams.getThrottleRate(), - perfParams.getMessageSize()); + sendMessages(perfParams.getNoOfWarmupMessages(), perfParams.getBatchSize(), perfParams.isDurable(), perfParams.isSessionTransacted(), false, perfParams.getThrottleRate(), perfParams.getMessageSize()); PerfBase.log.info("warmed up"); start = System.currentTimeMillis(); - sendMessages(perfParams.getNoOfMessagesToSend(), - perfParams.getBatchSize(), - perfParams.isDurable(), - perfParams.isSessionTransacted(), - true, - perfParams.getThrottleRate(), - perfParams.getMessageSize()); + sendMessages(perfParams.getNoOfMessagesToSend(), perfParams.getBatchSize(), perfParams.isDurable(), perfParams.isSessionTransacted(), true, perfParams.getThrottleRate(), perfParams.getMessageSize()); long end = System.currentTimeMillis(); displayAverage(perfParams.getNoOfMessagesToSend(), start, end); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } - finally - { - if (session != null) - { - try - { + finally { + if (session != null) { + try { session.close(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } - if(connection != null) - { - try - { + if (connection != null) { + try { connection.close(); } - catch (JMSException e) - { + catch (JMSException e) { e.printStackTrace(); } } } } - protected void runListener() - { - try - { + protected void runListener() { + try { init(); - if (perfParams.isDrainQueue()) - { + if (perfParams.isDrainQueue()) { drainQueue(); } @@ -264,39 +222,30 @@ public abstract class PerfBase // start was set on the first received message displayAverage(perfParams.getNoOfMessagesToSend(), start, end); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } - finally - { - if (session != null) - { - try - { + finally { + if (session != null) { + try { session.close(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } - if(connection != null) - { - try - { + if (connection != null) { + try { connection.close(); } - catch (JMSException e) - { + catch (JMSException e) { e.printStackTrace(); } } } } - private void drainQueue() throws Exception - { + private void drainQueue() throws Exception { PerfBase.log.info("Draining queue"); Session drainSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -308,18 +257,15 @@ public abstract class PerfBase Message message = null; int count = 0; - do - { + do { message = consumer.receive(3000); - if (message != null) - { + if (message != null) { message.acknowledge(); count++; } - } - while (message != null); + } while (message != null); drainSession.close(); @@ -332,8 +278,7 @@ public abstract class PerfBase final boolean transacted, final boolean display, final int throttleRate, - final int messageSize) throws Exception - { + final int messageSize) throws Exception { MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(perfParams.isDurable() ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT); @@ -353,42 +298,35 @@ public abstract class PerfBase TokenBucketLimiter tbl = throttleRate != -1 ? new TokenBucketLimiterImpl(throttleRate, false) : null; boolean committed = false; - for (int i = 1; i <= numberOfMessages; i++) - { + for (int i = 1; i <= numberOfMessages; i++) { producer.send(message); - if (transacted) - { - if (i % txBatchSize == 0) - { + if (transacted) { + if (i % txBatchSize == 0) { session.commit(); committed = true; } - else - { + else { committed = false; } } - if (display && i % modulo == 0) - { + if (display && i % modulo == 0) { double duration = (1.0 * System.currentTimeMillis() - start) / 1000; PerfBase.log.info(String.format("sent %6d messages in %2.2fs", i, duration)); } - if (tbl != null) - { + if (tbl != null) { tbl.limit(); } } - if (transacted && !committed) - { + if (transacted && !committed) { session.commit(); } } - private class PerfListener implements MessageListener - { + private class PerfListener implements MessageListener { + private final CountDownLatch countDownLatch; private final PerfParams perfParams; @@ -401,26 +339,20 @@ public abstract class PerfBase private final AtomicLong count = new AtomicLong(0); - public PerfListener(final CountDownLatch countDownLatch, final PerfParams perfParams) - { + public PerfListener(final CountDownLatch countDownLatch, final PerfParams perfParams) { this.countDownLatch = countDownLatch; this.perfParams = perfParams; warmingUp = perfParams.getNoOfWarmupMessages() > 0; modulo = 2000; } - public void onMessage(final Message message) - { - try - { - if (warmingUp) - { + public void onMessage(final Message message) { + try { + if (warmingUp) { boolean committed = checkCommit(); - if (count.incrementAndGet() == perfParams.getNoOfWarmupMessages()) - { + if (count.incrementAndGet() == perfParams.getNoOfWarmupMessages()) { PerfBase.log.info("warmed up after receiving " + count.longValue() + " msgs"); - if (!committed) - { + if (!committed) { checkCommit(); } warmingUp = false; @@ -428,8 +360,7 @@ public abstract class PerfBase return; } - if (!started) - { + if (!started) { started = true; // reset count to take stats count.set(0); @@ -438,32 +369,25 @@ public abstract class PerfBase long currentCount = count.incrementAndGet(); boolean committed = checkCommit(); - if (currentCount == perfParams.getNoOfMessagesToSend()) - { - if (!committed) - { + if (currentCount == perfParams.getNoOfMessagesToSend()) { + if (!committed) { checkCommit(); } countDownLatch.countDown(); } - if (currentCount % modulo == 0) - { + if (currentCount % modulo == 0) { double duration = (1.0 * System.currentTimeMillis() - start) / 1000; PerfBase.log.info(String.format("received %6d messages in %2.2fs", currentCount, duration)); } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } - private boolean checkCommit() throws Exception - { - if (perfParams.isSessionTransacted()) - { - if (count.longValue() % perfParams.getBatchSize() == 0) - { + private boolean checkCommit() throws Exception { + if (perfParams.isSessionTransacted()) { + if (count.longValue() % perfParams.getBatchSize() == 0) { session.commit(); return true; diff --git a/examples/jms/perf/src/main/java/org/apache/activemq/artemis/jms/example/PerfListener.java b/examples/jms/perf/src/main/java/org/apache/activemq/artemis/jms/example/PerfListener.java index 3894306abe..3f2c4785dc 100644 --- a/examples/jms/perf/src/main/java/org/apache/activemq/artemis/jms/example/PerfListener.java +++ b/examples/jms/perf/src/main/java/org/apache/activemq/artemis/jms/example/PerfListener.java @@ -18,33 +18,28 @@ package org.apache.activemq.artemis.jms.example; import java.util.logging.Logger; -public class PerfListener extends PerfBase -{ +public class PerfListener extends PerfBase { + private static final Logger log = Logger.getLogger(PerfListener.class.getName()); - public static void main(final String[] args) - { - try - { + public static void main(final String[] args) { + try { String fileName = PerfBase.getPerfFileName(args); PerfParams params = PerfBase.getParams(fileName); new PerfListener(params).run(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } - private PerfListener(final PerfParams perfParams) - { + private PerfListener(final PerfParams perfParams) { super(perfParams); } - public void run() throws Exception - { + public void run() throws Exception { runListener(); } diff --git a/examples/jms/perf/src/main/java/org/apache/activemq/artemis/jms/example/PerfParams.java b/examples/jms/perf/src/main/java/org/apache/activemq/artemis/jms/example/PerfParams.java index 2a526f1b4c..c3581711ab 100644 --- a/examples/jms/perf/src/main/java/org/apache/activemq/artemis/jms/example/PerfParams.java +++ b/examples/jms/perf/src/main/java/org/apache/activemq/artemis/jms/example/PerfParams.java @@ -21,8 +21,8 @@ import java.io.Serializable; /** * Class that holds the parameters used in the performance examples */ -public class PerfParams implements Serializable -{ +public class PerfParams implements Serializable { + private static final long serialVersionUID = -4336539641012356002L; private int noOfMessagesToSend = 1000; @@ -51,133 +51,107 @@ public class PerfParams implements Serializable private boolean dupsOK; - public synchronized int getNoOfMessagesToSend() - { + public synchronized int getNoOfMessagesToSend() { return noOfMessagesToSend; } - public synchronized void setNoOfMessagesToSend(final int noOfMessagesToSend) - { + public synchronized void setNoOfMessagesToSend(final int noOfMessagesToSend) { this.noOfMessagesToSend = noOfMessagesToSend; } - public synchronized int getNoOfWarmupMessages() - { + public synchronized int getNoOfWarmupMessages() { return noOfWarmupMessages; } - public synchronized void setNoOfWarmupMessages(final int noOfWarmupMessages) - { + public synchronized void setNoOfWarmupMessages(final int noOfWarmupMessages) { this.noOfWarmupMessages = noOfWarmupMessages; } - public synchronized int getMessageSize() - { + public synchronized int getMessageSize() { return messageSize; } - public synchronized void setMessageSize(final int messageSize) - { + public synchronized void setMessageSize(final int messageSize) { this.messageSize = messageSize; } - public synchronized boolean isDurable() - { + public synchronized boolean isDurable() { return durable; } - public synchronized void setDurable(final boolean durable) - { + public synchronized void setDurable(final boolean durable) { this.durable = durable; } - public synchronized boolean isSessionTransacted() - { + public synchronized boolean isSessionTransacted() { return isSessionTransacted; } - public synchronized void setSessionTransacted(final boolean isSessionTransacted) - { + public synchronized void setSessionTransacted(final boolean isSessionTransacted) { this.isSessionTransacted = isSessionTransacted; } - public synchronized int getBatchSize() - { + public synchronized int getBatchSize() { return batchSize; } - public synchronized void setBatchSize(final int batchSize) - { + public synchronized void setBatchSize(final int batchSize) { this.batchSize = batchSize; } - public synchronized boolean isDrainQueue() - { + public synchronized boolean isDrainQueue() { return drainQueue; } - public synchronized void setDrainQueue(final boolean drainQueue) - { + public synchronized void setDrainQueue(final boolean drainQueue) { this.drainQueue = drainQueue; } - public synchronized String getConnectionFactoryLookup() - { + public synchronized String getConnectionFactoryLookup() { return connectionFactoryLookup; } - public synchronized void setConnectionFactoryLookup(final String connectionFactoryLookup) - { + public synchronized void setConnectionFactoryLookup(final String connectionFactoryLookup) { this.connectionFactoryLookup = connectionFactoryLookup; } - public synchronized String getDestinationLookup() - { + public synchronized String getDestinationLookup() { return destinationLookup; } - public synchronized void setDestinationLookup(final String destinationLookup) - { + public synchronized void setDestinationLookup(final String destinationLookup) { this.destinationLookup = destinationLookup; } - public synchronized int getThrottleRate() - { + public synchronized int getThrottleRate() { return throttleRate; } - public synchronized void setThrottleRate(final int throttleRate) - { + public synchronized void setThrottleRate(final int throttleRate) { this.throttleRate = throttleRate; } - public synchronized boolean isDisableMessageID() - { + public synchronized boolean isDisableMessageID() { return disableMessageID; } - public synchronized void setDisableMessageID(final boolean disableMessageID) - { + public synchronized void setDisableMessageID(final boolean disableMessageID) { this.disableMessageID = disableMessageID; } - public synchronized boolean isDisableTimestamp() - { + public synchronized boolean isDisableTimestamp() { return disableTimestamp; } - public synchronized void setDisableTimestamp(final boolean disableTimestamp) - { + public synchronized void setDisableTimestamp(final boolean disableTimestamp) { this.disableTimestamp = disableTimestamp; } - public synchronized boolean isDupsOK() - { + public synchronized boolean isDupsOK() { return dupsOK; } - public synchronized void setDupsOK(final boolean dupsOK) - { + public synchronized void setDupsOK(final boolean dupsOK) { this.dupsOK = dupsOK; } diff --git a/examples/jms/perf/src/main/java/org/apache/activemq/artemis/jms/example/PerfSender.java b/examples/jms/perf/src/main/java/org/apache/activemq/artemis/jms/example/PerfSender.java index 0c875748bc..6649bfa674 100644 --- a/examples/jms/perf/src/main/java/org/apache/activemq/artemis/jms/example/PerfSender.java +++ b/examples/jms/perf/src/main/java/org/apache/activemq/artemis/jms/example/PerfSender.java @@ -18,33 +18,28 @@ package org.apache.activemq.artemis.jms.example; import java.util.logging.Logger; -public class PerfSender extends PerfBase -{ +public class PerfSender extends PerfBase { + private static final Logger log = Logger.getLogger(PerfSender.class.getName()); - public static void main(final String[] args) - { - try - { + public static void main(final String[] args) { + try { String fileName = PerfBase.getPerfFileName(args); PerfParams params = PerfBase.getParams(fileName); new PerfSender(params).run(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } - private PerfSender(final PerfParams perfParams) - { + private PerfSender(final PerfParams perfParams) { super(perfParams); } - public void run() throws Exception - { + public void run() throws Exception { runSender(); } diff --git a/examples/jms/perf/src/main/java/org/apache/activemq/artemis/jms/example/Server.java b/examples/jms/perf/src/main/java/org/apache/activemq/artemis/jms/example/Server.java index d844c40340..14a8e7a5e4 100644 --- a/examples/jms/perf/src/main/java/org/apache/activemq/artemis/jms/example/Server.java +++ b/examples/jms/perf/src/main/java/org/apache/activemq/artemis/jms/example/Server.java @@ -17,10 +17,9 @@ package org.apache.activemq.artemis.jms.example; -public class Server -{ - public static void main(String arg[]) - { +public class Server { + + public static void main(String arg[]) { System.out.println("***********************************************************************************"); System.out.println("You need to start manually under ./target/server/bin just run ./artemis run"); System.out.println("***********************************************************************************"); diff --git a/examples/jms/pre-acknowledge/src/main/java/org/apache/activemq/artemis/jms/example/PreacknowledgeExample.java b/examples/jms/pre-acknowledge/src/main/java/org/apache/activemq/artemis/jms/example/PreacknowledgeExample.java index 5191f85762..834b54a778 100644 --- a/examples/jms/pre-acknowledge/src/main/java/org/apache/activemq/artemis/jms/example/PreacknowledgeExample.java +++ b/examples/jms/pre-acknowledge/src/main/java/org/apache/activemq/artemis/jms/example/PreacknowledgeExample.java @@ -39,13 +39,11 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; * * Please see the readme.html for more details. */ -public class PreacknowledgeExample -{ - public static void main(final String[] args) throws Exception - { +public class PreacknowledgeExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; - try - { + try { // Step 2. instantiate the queue object Queue queue = ActiveMQJMSClient.createQueue("exampleQueue"); @@ -86,21 +84,18 @@ public class PreacknowledgeExample System.out.println("Queue message count is now " + count); - if (count != 0) - { + if (count != 0) { throw new IllegalStateException("Queue message count is not 0."); } // Step 8. Finally, receive the message - TextMessage messageReceived = (TextMessage)messageConsumer.receive(5000); + TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000); System.out.println("Received message: " + messageReceived.getText()); } - finally - { + finally { // Step 9. Be sure to close our resources! - if (connection != null) - { + if (connection != null) { connection.close(); } } @@ -108,9 +103,8 @@ public class PreacknowledgeExample // To do this we send a management message to get the message count. // In real life you wouldn't create a new session every time you send a management message - private static int getMessageCount(final Connection connection) throws Exception - { - QueueSession session = ((QueueConnection)connection).createQueueSession(false, Session.AUTO_ACKNOWLEDGE); + private static int getMessageCount(final Connection connection) throws Exception { + QueueSession session = ((QueueConnection) connection).createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Queue managementQueue = ActiveMQJMSClient.createQueue("activemq.management"); @@ -124,7 +118,7 @@ public class PreacknowledgeExample Message response = requestor.request(m); - int messageCount = (Integer)JMSManagementHelper.getResult(response); + int messageCount = (Integer) JMSManagementHelper.getResult(response); return messageCount; } diff --git a/examples/jms/producer-rate-limit/src/main/java/org/apache/activemq/artemis/jms/example/ProducerRateLimitExample.java b/examples/jms/producer-rate-limit/src/main/java/org/apache/activemq/artemis/jms/example/ProducerRateLimitExample.java index cfae82e729..a7623bbbec 100644 --- a/examples/jms/producer-rate-limit/src/main/java/org/apache/activemq/artemis/jms/example/ProducerRateLimitExample.java +++ b/examples/jms/producer-rate-limit/src/main/java/org/apache/activemq/artemis/jms/example/ProducerRateLimitExample.java @@ -31,13 +31,11 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; * This example demonstrates how a message producer can be limited to produce messages at a maximum rate * specified in messages per sec. */ -public class ProducerRateLimitExample -{ - public static void main(final String[] args) throws Exception - { +public class ProducerRateLimitExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; - try - { + try { // Step 2. Perfom a lookup on the queue Queue queue = ActiveMQJMSClient.createQueue("exampleQueue"); @@ -63,8 +61,7 @@ public class ProducerRateLimitExample long start = System.currentTimeMillis(); - while (System.currentTimeMillis() - start <= duration) - { + while (System.currentTimeMillis() - start <= duration) { TextMessage message = session.createTextMessage("This is text message: " + i++); producer.send(message); @@ -72,7 +69,7 @@ public class ProducerRateLimitExample long end = System.currentTimeMillis(); - double rate = 1000 * (double)i / (end - start); + double rate = 1000 * (double) i / (end - start); System.out.println("We sent " + i + " messages in " + (end - start) + " milliseconds"); @@ -87,12 +84,10 @@ public class ProducerRateLimitExample System.out.println("Now consuming the messages..."); i = 0; - while (true) - { - TextMessage messageReceived = (TextMessage)messageConsumer.receive(5000); + while (true) { + TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000); - if (messageReceived == null) - { + if (messageReceived == null) { break; } @@ -101,11 +96,9 @@ public class ProducerRateLimitExample System.out.println("Received " + i + " messages"); } - finally - { + finally { // Step 9. Be sure to close our resources! - if (connection != null) - { + if (connection != null) { connection.close(); } } diff --git a/examples/jms/proton-cpp/src/main/java/org/apache/activemq/artemis/jms/example/ProtonCPPExample.java b/examples/jms/proton-cpp/src/main/java/org/apache/activemq/artemis/jms/example/ProtonCPPExample.java index 79c6bbc78f..be9c2f3a38 100644 --- a/examples/jms/proton-cpp/src/main/java/org/apache/activemq/artemis/jms/example/ProtonCPPExample.java +++ b/examples/jms/proton-cpp/src/main/java/org/apache/activemq/artemis/jms/example/ProtonCPPExample.java @@ -37,22 +37,20 @@ import org.apache.activemq.artemis.api.jms.management.JMSManagementHelper; * * Please see the readme.html for more details. */ -public class ProtonCPPExample -{ - public static void main(final String[] args) throws Exception - { +public class ProtonCPPExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Perform the look-ups - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 3. Create a the JMS objects connection = cf.createConnection(); @@ -75,29 +73,24 @@ public class ProtonCPPExample // Step 5. Finally, receive the message Message messageReceived = messageConsumer.receive(5000); - if (messageReceived == null) - { + if (messageReceived == null) { // We are not going to issue this as an error because // we also use this example as part of our tests on artemis // this is not considered an error, just that no messages arrived (i.e. hello wasn't called) } - else - { + else { System.out.println("message received: " + messageReceived); // Sending message back to client producerAnswer.send(session.createTextMessage("HELLO from Apache ActiveMQ Artemis")); } } - finally - { + finally { // Step 9. Be sure to close our resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } @@ -105,9 +98,8 @@ public class ProtonCPPExample // To do this we send a management message to get the message count. // In real life you wouldn't create a new session every time you send a management message - private int getMessageCount(final Connection connection) throws Exception - { - QueueSession session = ((QueueConnection)connection).createQueueSession(false, Session.AUTO_ACKNOWLEDGE); + private int getMessageCount(final Connection connection) throws Exception { + QueueSession session = ((QueueConnection) connection).createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Queue managementQueue = ActiveMQJMSClient.createQueue("activemq.management"); @@ -121,7 +113,7 @@ public class ProtonCPPExample Message response = requestor.request(m); - int messageCount = (Integer)JMSManagementHelper.getResult(response); + int messageCount = (Integer) JMSManagementHelper.getResult(response); return messageCount; } diff --git a/examples/jms/proton-j/src/main/java/org/apache/activemq/artemis/jms/example/ProtonJExample.java b/examples/jms/proton-j/src/main/java/org/apache/activemq/artemis/jms/example/ProtonJExample.java index 482151d239..85334b4568 100644 --- a/examples/jms/proton-j/src/main/java/org/apache/activemq/artemis/jms/example/ProtonJExample.java +++ b/examples/jms/proton-j/src/main/java/org/apache/activemq/artemis/jms/example/ProtonJExample.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.jms.example; - import org.apache.qpid.amqp_1_0.client.Connection; import org.apache.qpid.amqp_1_0.client.Message; import org.apache.qpid.amqp_1_0.client.Receiver; @@ -24,16 +23,14 @@ import org.apache.qpid.amqp_1_0.client.Sender; import org.apache.qpid.amqp_1_0.client.Session; import org.apache.qpid.amqp_1_0.type.UnsignedInteger; -public class ProtonJExample -{ - public static void main(String[] args) throws Exception - { +public class ProtonJExample { + + public static void main(String[] args) throws Exception { Connection connection = null; - try - { + try { // Step 1. Create an amqp qpid 1.0 connection - connection= new Connection("localhost", 5672, null, null); + connection = new Connection("localhost", 5672, null, null); // Step 2. Create a session Session session = connection.createSession(); @@ -57,10 +54,8 @@ public class ProtonJExample // Step 8. acknowledge the message rec.acknowledge(m); } - finally - { - if(connection != null) - { + finally { + if (connection != null) { // Step 9. close the connection connection.close(); } diff --git a/examples/jms/queue-message-redistribution/src/main/java/org/apache/activemq/artemis/jms/example/QueueMessageRedistributionExample.java b/examples/jms/queue-message-redistribution/src/main/java/org/apache/activemq/artemis/jms/example/QueueMessageRedistributionExample.java index f6cdb5eb9f..d04fee0c05 100644 --- a/examples/jms/queue-message-redistribution/src/main/java/org/apache/activemq/artemis/jms/example/QueueMessageRedistributionExample.java +++ b/examples/jms/queue-message-redistribution/src/main/java/org/apache/activemq/artemis/jms/example/QueueMessageRedistributionExample.java @@ -35,16 +35,14 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; * The consumer on one of the nodes is then closed, and we demonstrate that the "stranded" messages * are redistributed to the other node which has a consumer so they can be consumed. */ -public class QueueMessageRedistributionExample -{ - public static void main(final String[] args) throws Exception - { +public class QueueMessageRedistributionExample { + + public static void main(final String[] args) throws Exception { Connection connection0 = null; Connection connection1 = null; - try - { + try { // Step 2. Look-up the JMS Queue object from JNDI Queue queue = ActiveMQJMSClient.createQueue("exampleQueue"); @@ -85,8 +83,7 @@ public class QueueMessageRedistributionExample final int numMessages = 10; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session0.createTextMessage("This is text message " + i); producer.send(message); @@ -103,13 +100,12 @@ public class QueueMessageRedistributionExample TextMessage message1 = null; - for (int i = 0; i < numMessages; i += 2) - { - message0 = (TextMessage)consumer0.receive(5000); + for (int i = 0; i < numMessages; i += 2) { + message0 = (TextMessage) consumer0.receive(5000); System.out.println("Got message: " + message0.getText() + " from node 0"); - message1 = (TextMessage)consumer1.receive(5000); + message1 = (TextMessage) consumer1.receive(5000); System.out.println("Got message: " + message1.getText() + " from node 1"); } @@ -127,9 +123,8 @@ public class QueueMessageRedistributionExample // consumers) // so ActiveMQ Artemis will redistribute them to node 0 so they can be consumed. - for (int i = 0; i < numMessages; i += 2) - { - message0 = (TextMessage)consumer0.receive(5000); + for (int i = 0; i < numMessages; i += 2) { + message0 = (TextMessage) consumer0.receive(5000); System.out.println("Got message: " + message0.getText() + " from node 0"); } @@ -137,17 +132,14 @@ public class QueueMessageRedistributionExample // Step 18. We ack the messages. message0.acknowledge(); } - finally - { + finally { // Step 18. Be sure to close our resources! - if (connection0 != null) - { + if (connection0 != null) { connection0.close(); } - if (connection1 != null) - { + if (connection1 != null) { connection1.close(); } } diff --git a/examples/jms/queue-requestor/src/main/java/org/apache/activemq/artemis/jms/example/QueueRequestorExample.java b/examples/jms/queue-requestor/src/main/java/org/apache/activemq/artemis/jms/example/QueueRequestorExample.java index b86ad9c8d7..607d82fc38 100644 --- a/examples/jms/queue-requestor/src/main/java/org/apache/activemq/artemis/jms/example/QueueRequestorExample.java +++ b/examples/jms/queue-requestor/src/main/java/org/apache/activemq/artemis/jms/example/QueueRequestorExample.java @@ -29,22 +29,20 @@ import javax.naming.InitialContext; /** * A simple JMS example that shows how to use queues requestors. */ -public class QueueRequestorExample -{ - public static void main(final String[] args) throws Exception - { +public class QueueRequestorExample { + + public static void main(final String[] args) throws Exception { QueueConnection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Perfom a lookup on the queue - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 3. Look-up the JMS queue connection factory - QueueConnectionFactory cf = (QueueConnectionFactory)initialContext.lookup("ConnectionFactory"); + QueueConnectionFactory cf = (QueueConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4. Create a TextReverserService which consumes messages from the queue and sends message with reversed // text @@ -66,7 +64,7 @@ public class QueueRequestorExample TextMessage request = session.createTextMessage("Hello, World!"); // Step 10. Use the requestor to send the request and wait to receive a reply - TextMessage reply = (TextMessage)queueRequestor.request(request); + TextMessage reply = (TextMessage) queueRequestor.request(request); // Step 11. The reply's text contains the reversed request's text System.out.println("Send request: " + request.getText()); @@ -78,23 +76,18 @@ public class QueueRequestorExample // Step 13. close the text reverser service reverserService.close(); } - finally - { - if (connection != null) - { - try - { + finally { + if (connection != null) { + try { // Step 14. Be sure to close the JMS resources! connection.close(); } - catch (JMSException e) - { + catch (JMSException e) { e.printStackTrace(); } } - if (initialContext != null) - { + if (initialContext != null) { // Also the InitialContext initialContext.close(); } diff --git a/examples/jms/queue-requestor/src/main/java/org/apache/activemq/artemis/jms/example/TextReverserService.java b/examples/jms/queue-requestor/src/main/java/org/apache/activemq/artemis/jms/example/TextReverserService.java index 280f99698d..63fdad265e 100644 --- a/examples/jms/queue-requestor/src/main/java/org/apache/activemq/artemis/jms/example/TextReverserService.java +++ b/examples/jms/queue-requestor/src/main/java/org/apache/activemq/artemis/jms/example/TextReverserService.java @@ -32,8 +32,7 @@ import javax.jms.TextMessage; * and replies with text messages containing the reversed text. * It sends replies to the destination specified by the JMS ReplyTo header of the consumed messages. */ -public class TextReverserService implements MessageListener -{ +public class TextReverserService implements MessageListener { // Constants ----------------------------------------------------- @@ -45,15 +44,13 @@ public class TextReverserService implements MessageListener // Static -------------------------------------------------------- - private static String reverse(final String text) - { + private static String reverse(final String text) { return new StringBuffer(text).reverse().toString(); } // Constructors -------------------------------------------------- - public TextReverserService(final ConnectionFactory cf, final Destination destination) throws JMSException - { + public TextReverserService(final ConnectionFactory cf, final Destination destination) throws JMSException { // create a JMS connection connection = cf.createConnection(); // create a JMS session @@ -69,11 +66,9 @@ public class TextReverserService implements MessageListener // MessageListener implementation -------------------------------- - public void onMessage(final Message request) - { - TextMessage textMessage = (TextMessage)request; - try - { + public void onMessage(final Message request) { + TextMessage textMessage = (TextMessage) request; + try { // retrieve the request's text String text = textMessage.getText(); // create a reply containing the reversed text @@ -88,25 +83,20 @@ public class TextReverserService implements MessageListener // close the producer producer.close(); } - catch (JMSException e) - { + catch (JMSException e) { e.printStackTrace(); } } // Public -------------------------------------------------------- - public void close() - { - if (connection != null) - { - try - { + public void close() { + if (connection != null) { + try { // be sure to close the JMS resources connection.close(); } - catch (JMSException e) - { + catch (JMSException e) { e.printStackTrace(); } } diff --git a/examples/jms/queue-selector/src/main/java/org/apache/activemq/artemis/jms/example/QueueSelectorExample.java b/examples/jms/queue-selector/src/main/java/org/apache/activemq/artemis/jms/example/QueueSelectorExample.java index 4811257eb2..465a4e2279 100644 --- a/examples/jms/queue-selector/src/main/java/org/apache/activemq/artemis/jms/example/QueueSelectorExample.java +++ b/examples/jms/queue-selector/src/main/java/org/apache/activemq/artemis/jms/example/QueueSelectorExample.java @@ -32,23 +32,21 @@ import java.util.concurrent.atomic.AtomicBoolean; /** * A simple JMS example that uses selectors with queue consumers. */ -public class QueueSelectorExample -{ - public static void main(final String[] args) throws Exception - { +public class QueueSelectorExample { + + public static void main(final String[] args) throws Exception { AtomicBoolean result = new AtomicBoolean(true); Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. look-up the JMS queue object from JNDI - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 3. look-up the JMS connection factory object from JNDI - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4. Create a JMS Connection connection = cf.createConnection(); @@ -102,50 +100,42 @@ public class QueueSelectorExample if (!result.get()) throw new IllegalStateException(); } - finally - { + finally { // Step 12. Be sure to close our JMS resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } } } -class SimpleMessageListener implements MessageListener -{ +class SimpleMessageListener implements MessageListener { + private final String name; private AtomicBoolean result; - public SimpleMessageListener(final String listener, AtomicBoolean result) - { + public SimpleMessageListener(final String listener, AtomicBoolean result) { name = listener; this.result = result; } - public void onMessage(final Message msg) - { - TextMessage textMessage = (TextMessage)msg; - try - { + public void onMessage(final Message msg) { + TextMessage textMessage = (TextMessage) msg; + try { String colorProp = msg.getStringProperty("color"); System.out.println("Receiver " + name + - " receives message [" + - textMessage.getText() + - "] with color property: " + - colorProp); - if (!colorProp.equals(name) && !name.equals("any")) - { + " receives message [" + + textMessage.getText() + + "] with color property: " + + colorProp); + if (!colorProp.equals(name) && !name.equals("any")) { result.set(false); } } - catch (JMSException e) - { + catch (JMSException e) { e.printStackTrace(); result.set(false); } diff --git a/examples/jms/queue/src/main/java/org/apache/activemq/artemis/jms/example/QueueExample.java b/examples/jms/queue/src/main/java/org/apache/activemq/artemis/jms/example/QueueExample.java index 5cbf0cd8ac..b6ce381510 100644 --- a/examples/jms/queue/src/main/java/org/apache/activemq/artemis/jms/example/QueueExample.java +++ b/examples/jms/queue/src/main/java/org/apache/activemq/artemis/jms/example/QueueExample.java @@ -28,22 +28,20 @@ import javax.naming.InitialContext; /** * A simple JMS Queue example that creates a producer and consumer on a queue and sends then receives a message. */ -public class QueueExample -{ - public static void main(final String[] args) throws Exception - { +public class QueueExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Perfom a lookup on the queue - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 3. Perform a lookup on the Connection Factory - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4.Create a JMS Connection connection = cf.createConnection(); @@ -69,19 +67,16 @@ public class QueueExample connection.start(); // Step 11. Receive the message - TextMessage messageReceived = (TextMessage)messageConsumer.receive(5000); + TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000); System.out.println("Received message: " + messageReceived.getText()); } - finally - { + finally { // Step 12. Be sure to close our JMS resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } diff --git a/examples/jms/reattach-node/src/main/java/org/apache/activemq/artemis/jms/example/ReattachExample.java b/examples/jms/reattach-node/src/main/java/org/apache/activemq/artemis/jms/example/ReattachExample.java index 3a47fca307..459c33b357 100644 --- a/examples/jms/reattach-node/src/main/java/org/apache/activemq/artemis/jms/example/ReattachExample.java +++ b/examples/jms/reattach-node/src/main/java/org/apache/activemq/artemis/jms/example/ReattachExample.java @@ -35,23 +35,21 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; * * The network is brought back up and the client reconnects and resumes transparently. */ -public class ReattachExample -{ - public static void main(final String[] args) throws Exception - { +public class ReattachExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Perform a lookup on the queue - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 3. Perform a lookup on the Connection Factory - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4. Create a JMS Connection connection = cf.createConnection(); @@ -92,45 +90,38 @@ public class ReattachExample System.out.println("Restarted acceptor. The client will now reconnect."); // Step 13. We receive the message - TextMessage messageReceived = (TextMessage)messageConsumer.receive(5000); + TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000); System.out.println("Received message: " + messageReceived.getText()); } - finally - { + finally { // Step 14. Be sure to close our JMS resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } } - private static void stopAcceptor() throws Exception - { + private static void stopAcceptor() throws Exception { stopStartAcceptor(true); } - private static void startAcceptor() throws Exception - { + private static void startAcceptor() throws Exception { stopStartAcceptor(false); } // To do this we send a management message to close the acceptor, we do this on a different // connection factory which uses a different remoting connection so we can still send messages // when the main connection has been stopped - private static void stopStartAcceptor(final boolean stop) throws Exception - { + private static void stopStartAcceptor(final boolean stop) throws Exception { ConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61617"); Connection connection = null; - try - { + try { connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -149,10 +140,8 @@ public class ReattachExample producer.send(m); } - finally - { - if (connection != null) - { + finally { + if (connection != null) { connection.close(); } } diff --git a/examples/jms/replicated-failback-static/src/main/java/org/apache/activemq/artemis/jms/example/ReplicatedFailbackStaticExample.java b/examples/jms/replicated-failback-static/src/main/java/org/apache/activemq/artemis/jms/example/ReplicatedFailbackStaticExample.java index 2f22cb9fcd..d2f74ba28d 100644 --- a/examples/jms/replicated-failback-static/src/main/java/org/apache/activemq/artemis/jms/example/ReplicatedFailbackStaticExample.java +++ b/examples/jms/replicated-failback-static/src/main/java/org/apache/activemq/artemis/jms/example/ReplicatedFailbackStaticExample.java @@ -35,22 +35,20 @@ import javax.naming.InitialContext; *

    * Later the live server is restarted and takes back its position by asking the backup to stop ("fail-back"). */ -public class ReplicatedFailbackStaticExample -{ +public class ReplicatedFailbackStaticExample { + private static Process server0; private static Process server1; - public static void main(final String[] args) throws Exception - { + public static void main(final String[] args) throws Exception { final int numMessages = 30; Connection connection = null; InitialContext initialContext = null; - try - { + try { server0 = ServerUtil.startServer(args[0], ReplicatedFailbackStaticExample.class.getSimpleName() + "0", 0, 30000); server1 = ServerUtil.startServer(args[1], ReplicatedFailbackStaticExample.class.getSimpleName() + "1", 1, 10000); @@ -58,8 +56,8 @@ public class ReplicatedFailbackStaticExample initialContext = new InitialContext(); // Step 2. Look up the JMS resources from JNDI - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); - ConnectionFactory connectionFactory = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); + ConnectionFactory connectionFactory = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 3. Create a JMS Connection connection = connectionFactory.createConnection(); @@ -75,8 +73,7 @@ public class ReplicatedFailbackStaticExample MessageConsumer consumer = session.createConsumer(queue); // Step 7. Send some messages to server #1, the live server - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session.createTextMessage("This is text message " + i); producer.send(message); System.out.println("Sent message: " + message.getText()); @@ -84,17 +81,15 @@ public class ReplicatedFailbackStaticExample // Step 8. Receive and acknowledge a third of the sent messages TextMessage message0 = null; - for (int i = 0; i < numMessages / 3; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = 0; i < numMessages / 3; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.println("Got message: " + message0.getText()); } message0.acknowledge(); // Step 9. Receive the rest third of the sent messages but *do not* acknowledge them yet - for (int i = numMessages / 3; i < numMessages; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = numMessages / 3; i < numMessages; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.println("Got message: " + message0.getText()); } @@ -104,19 +99,16 @@ public class ReplicatedFailbackStaticExample // Step 11. Acknowledging the 2nd half of the sent messages will fail as failover to the // backup server has occurred - try - { + try { message0.acknowledge(); } - catch (JMSException e) - { + catch (JMSException e) { System.out.println("Got (the expected) exception while acknowledging message: " + e.getMessage()); } // Step 12. Consume again the 2nd third of the messages again. Note that they are not considered as redelivered. - for (int i = numMessages / 3; i < (numMessages / 3) * 2; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = numMessages / 3; i < (numMessages / 3) * 2; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.printf("Got message: %s (redelivered?: %s)\n", message0.getText(), message0.getJMSRedelivered()); } message0.acknowledge(); @@ -125,34 +117,28 @@ public class ReplicatedFailbackStaticExample // Step 11. Acknowledging the 2nd half of the sent messages will fail as failover to the // backup server has occurred - try - { + try { message0.acknowledge(); } - catch (JMSException e) - { + catch (JMSException e) { System.err.println("Got exception while acknowledging message: " + e.getMessage()); } // Step 12. Consume again the 2nd third of the messages again. Note that they are not considered as redelivered. - for (int i = (numMessages / 3) * 2; i < numMessages; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = (numMessages / 3) * 2; i < numMessages; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.printf("Got message: %s (redelivered?: %s)\n", message0.getText(), message0.getJMSRedelivered()); } message0.acknowledge(); } - finally - { + finally { // Step 13. Be sure to close our resources! - if (connection != null) - { + if (connection != null) { connection.close(); } - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } diff --git a/examples/jms/replicated-failback/src/main/java/org/apache/activemq/artemis/jms/example/ReplicatedFailbackExample.java b/examples/jms/replicated-failback/src/main/java/org/apache/activemq/artemis/jms/example/ReplicatedFailbackExample.java index 1cd933addc..29ae3816b1 100644 --- a/examples/jms/replicated-failback/src/main/java/org/apache/activemq/artemis/jms/example/ReplicatedFailbackExample.java +++ b/examples/jms/replicated-failback/src/main/java/org/apache/activemq/artemis/jms/example/ReplicatedFailbackExample.java @@ -35,22 +35,20 @@ import javax.naming.InitialContext; *

    * Later the live server is restarted and takes back its position by asking the backup to stop ("fail-back"). */ -public class ReplicatedFailbackExample -{ +public class ReplicatedFailbackExample { + private static Process server0; private static Process server1; - public static void main(final String[] args) throws Exception - { + public static void main(final String[] args) throws Exception { final int numMessages = 30; Connection connection = null; InitialContext initialContext = null; - try - { + try { server0 = ServerUtil.startServer(args[0], ReplicatedFailbackExample.class.getSimpleName() + "0", 0, 30000); server1 = ServerUtil.startServer(args[1], ReplicatedFailbackExample.class.getSimpleName() + "1", 1, 10000); @@ -58,8 +56,8 @@ public class ReplicatedFailbackExample initialContext = new InitialContext(); // Step 2. Look up the JMS resources from JNDI - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); - ConnectionFactory connectionFactory = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); + ConnectionFactory connectionFactory = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 3. Create a JMS Connection connection = connectionFactory.createConnection(); @@ -75,8 +73,7 @@ public class ReplicatedFailbackExample MessageConsumer consumer = session.createConsumer(queue); // Step 7. Send some messages to server #1, the live server - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session.createTextMessage("This is text message " + i); producer.send(message); System.out.println("Sent message: " + message.getText()); @@ -84,17 +81,15 @@ public class ReplicatedFailbackExample // Step 8. Receive and acknowledge a third of the sent messages TextMessage message0 = null; - for (int i = 0; i < numMessages / 3; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = 0; i < numMessages / 3; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.println("Got message: " + message0.getText()); } message0.acknowledge(); // Step 9. Receive the rest third of the sent messages but *do not* acknowledge them yet - for (int i = numMessages / 3; i < numMessages; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = numMessages / 3; i < numMessages; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.println("Got message: " + message0.getText()); } @@ -104,19 +99,16 @@ public class ReplicatedFailbackExample // Step 11. Acknowledging the 2nd half of the sent messages will fail as failover to the // backup server has occurred - try - { + try { message0.acknowledge(); } - catch (JMSException e) - { + catch (JMSException e) { System.out.println("Got (the expected) exception while acknowledging message: " + e.getMessage()); } // Step 12. Consume again the 2nd third of the messages again. Note that they are not considered as redelivered. - for (int i = numMessages / 3; i < (numMessages / 3) * 2; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = numMessages / 3; i < (numMessages / 3) * 2; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.printf("Got message: %s (redelivered?: %s)\n", message0.getText(), message0.getJMSRedelivered()); } message0.acknowledge(); @@ -125,34 +117,28 @@ public class ReplicatedFailbackExample // Step 11. Acknowledging the 2nd half of the sent messages will fail as failover to the // backup server has occurred - try - { + try { message0.acknowledge(); } - catch (JMSException e) - { + catch (JMSException e) { System.err.println("Got exception while acknowledging message: " + e.getMessage()); } // Step 12. Consume again the 2nd third of the messages again. Note that they are not considered as redelivered. - for (int i = (numMessages / 3) * 2; i < numMessages; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = (numMessages / 3) * 2; i < numMessages; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.printf("Got message: %s (redelivered?: %s)\n", message0.getText(), message0.getJMSRedelivered()); } message0.acknowledge(); } - finally - { + finally { // Step 13. Be sure to close our resources! - if (connection != null) - { + if (connection != null) { connection.close(); } - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } diff --git a/examples/jms/replicated-multiple-failover/src/main/java/org/apache/activemq/artemis/jms/example/ReplicatedMultipleFailoverExample.java b/examples/jms/replicated-multiple-failover/src/main/java/org/apache/activemq/artemis/jms/example/ReplicatedMultipleFailoverExample.java index 31dc492eb8..491d792a96 100644 --- a/examples/jms/replicated-multiple-failover/src/main/java/org/apache/activemq/artemis/jms/example/ReplicatedMultipleFailoverExample.java +++ b/examples/jms/replicated-multiple-failover/src/main/java/org/apache/activemq/artemis/jms/example/ReplicatedMultipleFailoverExample.java @@ -28,36 +28,34 @@ import javax.jms.Session; import javax.jms.TextMessage; import javax.naming.InitialContext; -public class ReplicatedMultipleFailoverExample -{ +public class ReplicatedMultipleFailoverExample { + private static Process server0; private static Process server1; private static Process server2; - public static void main(final String[] args) throws Exception - { + public static void main(final String[] args) throws Exception { final int numMessages = 30; Connection connection = null; InitialContext initialContext = null; - try - { + try { server0 = ServerUtil.startServer(args[0], ReplicatedMultipleFailoverExample.class.getSimpleName() + "0", 0, 5000); server1 = ServerUtil.startServer(args[1], ReplicatedMultipleFailoverExample.class.getSimpleName() + "1", 1, 5000); server2 = ServerUtil.startServer(args[2], ReplicatedMultipleFailoverExample.class.getSimpleName() + "2", 2, 5000); - Process[] processes = new Process[] {server0, server1, server2}; + Process[] processes = new Process[]{server0, server1, server2}; // Step 1. Get an initial context for looking up JNDI from the server #1 initialContext = new InitialContext(); // Step 2. Look up the JMS resources from JNDI - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); - ConnectionFactory connectionFactory = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); + ConnectionFactory connectionFactory = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 3. Create a JMS Connection connection = connectionFactory.createConnection(); @@ -73,8 +71,7 @@ public class ReplicatedMultipleFailoverExample MessageConsumer consumer = session.createConsumer(queue); // Step 7. Send some messages to server #1, the live server - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session.createTextMessage("This is text message " + i); producer.send(message); System.out.println("Sent message: " + message.getText()); @@ -82,17 +79,15 @@ public class ReplicatedMultipleFailoverExample // Step 8. Receive and acknowledge a third of the sent messages TextMessage message0 = null; - for (int i = 0; i < numMessages / 3; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = 0; i < numMessages / 3; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.println("Got message: " + message0.getText()); } message0.acknowledge(); // Step 9. Receive the rest third of the sent messages but *do not* acknowledge them yet - for (int i = numMessages / 3; i < numMessages; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = numMessages / 3; i < numMessages; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.println("Got message: " + message0.getText()); } @@ -103,19 +98,16 @@ public class ReplicatedMultipleFailoverExample // Step 11. Acknowledging the 2nd half of the sent messages will fail as failover to the // backup server has occurred - try - { + try { message0.acknowledge(); } - catch (JMSException e) - { + catch (JMSException e) { System.err.println("Got exception while acknowledging message: " + e.getMessage()); } // Step 12. Consume again the 2nd third of the messages again. Note that they are not considered as redelivered. - for (int i = numMessages / 3; i < (numMessages / 3) * 2; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = numMessages / 3; i < (numMessages / 3) * 2; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.printf("Got message: %s (redelivered?: %s)%n", message0.getText(), message0.getJMSRedelivered()); } message0.acknowledge(); @@ -124,34 +116,28 @@ public class ReplicatedMultipleFailoverExample // Step 11. Acknowledging the 2nd half of the sent messages will fail as failover to the // backup server has occurred - try - { + try { message0.acknowledge(); } - catch (JMSException e) - { + catch (JMSException e) { System.err.println("Got exception while acknowledging message: " + e.getMessage()); } // Step 12. Consume again the 2nd third of the messages again. Note that they are not considered as redelivered. - for (int i = (numMessages / 3) * 2; i < numMessages; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = (numMessages / 3) * 2; i < numMessages; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.printf("Got message: %s (redelivered?: %s)%n", message0.getText(), message0.getJMSRedelivered()); } message0.acknowledge(); } - finally - { + finally { // Step 13. Be sure to close our resources! - if (connection != null) - { + if (connection != null) { connection.close(); } - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } diff --git a/examples/jms/replicated-transaction-failover/src/main/java/org/apache/activemq/artemis/jms/example/ReplicatedTransactionFailoverExample.java b/examples/jms/replicated-transaction-failover/src/main/java/org/apache/activemq/artemis/jms/example/ReplicatedTransactionFailoverExample.java index dcc89d2e57..e6887c7ddf 100644 --- a/examples/jms/replicated-transaction-failover/src/main/java/org/apache/activemq/artemis/jms/example/ReplicatedTransactionFailoverExample.java +++ b/examples/jms/replicated-transaction-failover/src/main/java/org/apache/activemq/artemis/jms/example/ReplicatedTransactionFailoverExample.java @@ -33,8 +33,8 @@ import javax.naming.InitialContext; * A simple example that demonstrates failover of the JMS connection from one node to another * when the live server crashes using a JMS transacted session and replication. */ -public class ReplicatedTransactionFailoverExample -{ +public class ReplicatedTransactionFailoverExample { + private static Process server0; private static Process server1; @@ -45,16 +45,14 @@ public class ReplicatedTransactionFailoverExample // We recommend some sort of UUID, but for this example the Current Time as string would be enough private static String uniqueID = Long.toString(System.currentTimeMillis()); - public static void main(final String[] args) throws Exception - { + public static void main(final String[] args) throws Exception { final int numMessages = 10; Connection connection = null; InitialContext initialContext = null; - try - { + try { server0 = ServerUtil.startServer(args[0], ReplicatedTransactionFailoverExample.class.getSimpleName() + "0", 0, 5000); server1 = ServerUtil.startServer(args[1], ReplicatedTransactionFailoverExample.class.getSimpleName() + "1", 1, 5000); @@ -62,8 +60,8 @@ public class ReplicatedTransactionFailoverExample initialContext = new InitialContext(); // Step 2. Look-up the JMS resources from JNDI - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); - ConnectionFactory connectionFactory = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); + ConnectionFactory connectionFactory = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 3. We create a JMS Connection connection = connectionFactory.createConnection(); @@ -84,12 +82,10 @@ public class ReplicatedTransactionFailoverExample sendMessages(session, producer, numMessages, true); // Step 9. As failover occurred during transaction, the session has been marked for rollback only - try - { + try { session.commit(); } - catch (TransactionRolledBackException e) - { + catch (TransactionRolledBackException e) { System.err.println("transaction has been rolled back: " + e.getMessage()); } @@ -102,12 +98,10 @@ public class ReplicatedTransactionFailoverExample // Step 12. We are now transparently reconnected to server #0, the backup server. // We consume the messages sent before the crash of the live server and commit the session. - for (int i = 0; i < numMessages; i++) - { - TextMessage message0 = (TextMessage)consumer.receive(5000); + for (int i = 0; i < numMessages; i++) { + TextMessage message0 = (TextMessage) consumer.receive(5000); - if (message0 == null) - { + if (message0 == null) { throw new IllegalStateException("Example failed - message wasn't received"); } @@ -118,17 +112,14 @@ public class ReplicatedTransactionFailoverExample System.out.println("Other message on the server? " + consumer.receive(5000)); } - finally - { + finally { // Step 13. Be sure to close our resources! - if (connection != null) - { + if (connection != null) { connection.close(); } - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } @@ -138,13 +129,11 @@ public class ReplicatedTransactionFailoverExample } private static void sendMessages(final Session session, - final MessageProducer producer, - final int numMessages, - final boolean killServer) throws Exception - { + final MessageProducer producer, + final int numMessages, + final boolean killServer) throws Exception { // We send half of messages - for (int i = 0; i < numMessages / 2; i++) - { + for (int i = 0; i < numMessages / 2; i++) { TextMessage message = session.createTextMessage("This is text message " + i); // We set the duplicate detection header - so the server will ignore the same message @@ -157,14 +146,12 @@ public class ReplicatedTransactionFailoverExample System.out.println("Sent message: " + message.getText()); } - if (killServer) - { + if (killServer) { ServerUtil.killServer(server0); } // We send the remaining half of messages - for (int i = numMessages / 2; i < numMessages; i++) - { + for (int i = numMessages / 2; i < numMessages; i++) { TextMessage message = session.createTextMessage("This is text message " + i); // We set the duplicate detection header - so the server will ignore the same message diff --git a/examples/jms/request-reply/src/main/java/org/apache/activemq/artemis/jms/example/RequestReplyExample.java b/examples/jms/request-reply/src/main/java/org/apache/activemq/artemis/jms/example/RequestReplyExample.java index 7e9093fa09..5d2e4dc2eb 100644 --- a/examples/jms/request-reply/src/main/java/org/apache/activemq/artemis/jms/example/RequestReplyExample.java +++ b/examples/jms/request-reply/src/main/java/org/apache/activemq/artemis/jms/example/RequestReplyExample.java @@ -41,16 +41,14 @@ import javax.naming.InitialContext; * * Or better still use the correlation id, and just store the requests in a map, then you don't need a temporary queue at all */ -public class RequestReplyExample -{ - public static void main(final String[] args) throws Exception - { +public class RequestReplyExample { + + public static void main(final String[] args) throws Exception { final Map requestMap = new HashMap(); Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Start the request server SimpleRequestServer server = new SimpleRequestServer(); server.start(); @@ -59,10 +57,10 @@ public class RequestReplyExample initialContext = new InitialContext(); // Step 3. Lookup the queue for sending the request message - Queue requestQueue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue requestQueue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 4. Lookup for the Connection Factory - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 5. Create a JMS Connection connection = cf.createConnection(); @@ -100,7 +98,7 @@ public class RequestReplyExample requestMap.put(requestMsg.getJMSMessageID(), requestMsg); // Step 15. Receive the reply message. - TextMessage replyMessageReceived = (TextMessage)replyConsumer.receive(); + TextMessage replyMessageReceived = (TextMessage) replyConsumer.receive(); System.out.println("Received reply: " + replyMessageReceived.getText()); System.out.println("CorrelatedId: " + replyMessageReceived.getJMSCorrelationID()); @@ -121,24 +119,21 @@ public class RequestReplyExample // Step 19. Shutdown the request server server.shutdown(); } - finally - { + finally { // Step 20. Be sure to close our JMS resources! - if (connection != null) - { + if (connection != null) { connection.close(); } // Step 21. Also close the initialContext! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } } } } -class SimpleRequestServer implements MessageListener -{ +class SimpleRequestServer implements MessageListener { + private Connection connection; private Session session; @@ -147,16 +142,15 @@ class SimpleRequestServer implements MessageListener MessageConsumer requestConsumer; - public void start() throws Exception - { + public void start() throws Exception { // Get an initial context to perform the JNDI lookup. InitialContext initialContext = new InitialContext(); // Lookup the queue to receive the request message - Queue requestQueue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue requestQueue = (Queue) initialContext.lookup("queue/exampleQueue"); // Lookup for the Connection Factory - ConnectionFactory cfact = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cfact = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Create a connection connection = cfact.createConnection(); @@ -177,11 +171,9 @@ class SimpleRequestServer implements MessageListener requestConsumer.setMessageListener(this); } - public void onMessage(final Message request) - { - try - { - System.out.println("Received request message: " + ((TextMessage)request).getText()); + public void onMessage(final Message request) { + try { + System.out.println("Received request message: " + ((TextMessage) request).getText()); // Extract the ReplyTo destination Destination replyDestination = request.getJMSReplyTo(); @@ -199,14 +191,12 @@ class SimpleRequestServer implements MessageListener System.out.println("Reply sent"); } - catch (JMSException e) - { + catch (JMSException e) { e.printStackTrace(); } } - public void shutdown() throws JMSException - { + public void shutdown() throws JMSException { connection.close(); } } diff --git a/examples/jms/rest/dup-send/src/main/java/Order.java b/examples/jms/rest/dup-send/src/main/java/Order.java index aa3ad9315d..2b938f7634 100644 --- a/examples/jms/rest/dup-send/src/main/java/Order.java +++ b/examples/jms/rest/dup-send/src/main/java/Order.java @@ -14,64 +14,56 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; -@XmlRootElement(name="order") -public class Order implements Serializable -{ +@XmlRootElement(name = "order") +public class Order implements Serializable { + private String name; private String amount; private String item; - public Order() - { + public Order() { } - public Order(String name, String amount, String item) - { + public Order(String name, String amount, String item) { this.name = name; this.amount = amount; this.item = item; } - public String getName() - { + public String getName() { return name; } - public void setName(String name) - { + public void setName(String name) { this.name = name; } - public String getAmount() - { + public String getAmount() { return amount; } - public void setAmount(String amount) - { + public void setAmount(String amount) { this.amount = amount; } - public String getItem() - { + public String getItem() { return item; } - public void setItem(String item) - { + public void setItem(String item) { this.item = item; } @Override - public String toString() - { + public String toString() { return "Order{" + - "name='" + name + '\'' + - ", amount='" + amount + '\'' + - ", item='" + item + '\'' + - '}'; + "name='" + name + '\'' + + ", amount='" + amount + '\'' + + ", item='" + item + '\'' + + '}'; } } diff --git a/examples/jms/rest/dup-send/src/main/java/PostOrder.java b/examples/jms/rest/dup-send/src/main/java/PostOrder.java index 6652777715..0e853003a0 100644 --- a/examples/jms/rest/dup-send/src/main/java/PostOrder.java +++ b/examples/jms/rest/dup-send/src/main/java/PostOrder.java @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + import org.apache.activemq.artemis.jms.client.ActiveMQDestination; import org.jboss.resteasy.client.ClientRequest; import org.jboss.resteasy.client.ClientResponse; @@ -26,10 +27,9 @@ import javax.jms.MessageProducer; import javax.jms.ObjectMessage; import javax.jms.Session; -public class PostOrder -{ - public static void main(String[] args) throws Exception - { +public class PostOrder { + + public static void main(String[] args) throws Exception { // first get the create URL for the shipping queue ClientRequest request = new ClientRequest("http://localhost:9095/queues/jms.queue.orders"); ClientResponse res = request.head(); @@ -43,18 +43,19 @@ public class PostOrder res = create.request().body("application/xml", order).post(); - if (res.getStatus() == 307) - { + if (res.getStatus() == 307) { Link redirect = res.getLocationLink(); res.releaseConnection(); res = redirect.request().body("application/xml", order).post(); } - if (res.getStatus() != 201) throw new RuntimeException("Failed to post"); + if (res.getStatus() != 201) + throw new RuntimeException("Failed to post"); create = res.getHeaderAsLink("msg-create-next"); - if (res.getStatus() != 201) throw new RuntimeException("Failed to post"); + if (res.getStatus() != 201) + throw new RuntimeException("Failed to post"); System.out.println("Send Monica's order..."); order.setName("Monica"); @@ -62,13 +63,15 @@ public class PostOrder res.releaseConnection(); res = create.request().body("application/xml", order).post(); - if (res.getStatus() != 201) throw new RuntimeException("Failed to post"); + if (res.getStatus() != 201) + throw new RuntimeException("Failed to post"); System.out.println("Resend Monica's order over same create-next link..."); res.releaseConnection(); res = create.request().body("application/xml", order).post(); - if (res.getStatus() != 201) throw new RuntimeException("Failed to post"); + if (res.getStatus() != 201) + throw new RuntimeException("Failed to post"); } } diff --git a/examples/jms/rest/dup-send/src/main/java/PostOrderWithId.java b/examples/jms/rest/dup-send/src/main/java/PostOrderWithId.java index 384b321afa..6b610e7547 100644 --- a/examples/jms/rest/dup-send/src/main/java/PostOrderWithId.java +++ b/examples/jms/rest/dup-send/src/main/java/PostOrderWithId.java @@ -14,22 +14,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + import org.jboss.resteasy.client.ClientRequest; import org.jboss.resteasy.client.ClientResponse; import org.jboss.resteasy.spi.Link; -public class PostOrderWithId -{ - public static void main(String[] args) throws Exception - { - if (args.length < 1 || args[0] == null) throw new RuntimeException("You must pass in a parameter"); +public class PostOrderWithId { + + public static void main(String[] args) throws Exception { + if (args.length < 1 || args[0] == null) + throw new RuntimeException("You must pass in a parameter"); // first get the create URL for the shipping queue ClientRequest request = new ClientRequest("http://localhost:9095/queues/jms.queue.orders"); ClientResponse res = request.head(); Link create = res.getHeaderAsLink("msg-create-with-id"); - Order order = new Order(); order.setName(args[0]); order.setItem("iPhone4"); @@ -37,7 +37,8 @@ public class PostOrderWithId res = create.request().pathParameter("id", args[0]).body("application/xml", order).post(); - if (res.getStatus() != 201) throw new RuntimeException("Failed to post"); + if (res.getStatus() != 201) + throw new RuntimeException("Failed to post"); System.out.println("Sent order " + args[0]); } diff --git a/examples/jms/rest/dup-send/src/main/java/ReceiveOrder.java b/examples/jms/rest/dup-send/src/main/java/ReceiveOrder.java index 379e5b039a..a00d11056b 100644 --- a/examples/jms/rest/dup-send/src/main/java/ReceiveOrder.java +++ b/examples/jms/rest/dup-send/src/main/java/ReceiveOrder.java @@ -14,14 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + import org.jboss.resteasy.client.ClientRequest; import org.jboss.resteasy.client.ClientResponse; import org.jboss.resteasy.spi.Link; -public class ReceiveOrder -{ - public static void main(String[] args) throws Exception - { +public class ReceiveOrder { + + public static void main(String[] args) throws Exception { // first get the create URL for the shipping queue ClientRequest request = new ClientRequest("http://localhost:9095/queues/jms.queue.orders"); ClientResponse res = request.head(); @@ -30,23 +30,19 @@ public class ReceiveOrder res = pullConsumers.request().post(); Link consumeNext = res.getHeaderAsLink("msg-consume-next"); res.releaseConnection(); - while (true) - { + while (true) { System.out.println("Waiting..."); res = consumeNext.request().header("Accept-Wait", "10").post(); - if (res.getStatus() == 503) - { + if (res.getStatus() == 503) { System.out.println("Timeout..."); consumeNext = res.getHeaderAsLink("msg-consume-next"); } - else if (res.getStatus() == 200) - { + else if (res.getStatus() == 200) { Order order = (Order) res.getEntity(Order.class); System.out.println(order); consumeNext = res.getHeaderAsLink("msg-consume-next"); } - else - { + else { throw new RuntimeException("Failure! " + res.getStatus()); } res.releaseConnection(); diff --git a/examples/jms/rest/javascript-chat/src/test/java/org/jboss/resteasy/messaging/test/AutoAckTopicTest.java b/examples/jms/rest/javascript-chat/src/test/java/org/jboss/resteasy/messaging/test/AutoAckTopicTest.java index 8aab03a978..05bc68545f 100644 --- a/examples/jms/rest/javascript-chat/src/test/java/org/jboss/resteasy/messaging/test/AutoAckTopicTest.java +++ b/examples/jms/rest/javascript-chat/src/test/java/org/jboss/resteasy/messaging/test/AutoAckTopicTest.java @@ -23,17 +23,15 @@ import org.apache.activemq.artemis.rest.util.LinkStrategy; import org.junit.Assert; import org.junit.Test; -public class AutoAckTopicTest -{ - public static Link getLinkByTitle(LinkStrategy strategy, ClientResponse response, String title) - { +public class AutoAckTopicTest { + + public static Link getLinkByTitle(LinkStrategy strategy, ClientResponse response, String title) { return response.getLinkHeader().getLinkByTitle(title); } //todo fix //@Test - public void testSuccessFirst() throws Exception - { + public void testSuccessFirst() throws Exception { ClientRequest request = new ClientRequest("http://localhost:9095/topics/jms.topic.chat"); ClientResponse response = request.head(); diff --git a/examples/jms/rest/jms-to-rest/src/main/java/JmsHelper.java b/examples/jms/rest/jms-to-rest/src/main/java/JmsHelper.java index f7e1bfc26c..8de4ab69e8 100644 --- a/examples/jms/rest/jms-to-rest/src/main/java/JmsHelper.java +++ b/examples/jms/rest/jms-to-rest/src/main/java/JmsHelper.java @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.api.core.client.ActiveMQClient; @@ -27,10 +28,9 @@ import org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory; import javax.jms.ConnectionFactory; import javax.jms.Destination; -public class JmsHelper -{ - public static ConnectionFactory createConnectionFactory(String configFile) throws Exception - { +public class JmsHelper { + + public static ConnectionFactory createConnectionFactory(String configFile) throws Exception { FileConfiguration config = new FileConfiguration(); FileDeploymentManager deploymentManager = new FileDeploymentManager(configFile); deploymentManager.addDeployable(config); diff --git a/examples/jms/rest/jms-to-rest/src/main/java/JmsReceive.java b/examples/jms/rest/jms-to-rest/src/main/java/JmsReceive.java index 009d2175f9..37de8a2f9b 100644 --- a/examples/jms/rest/jms-to-rest/src/main/java/JmsReceive.java +++ b/examples/jms/rest/jms-to-rest/src/main/java/JmsReceive.java @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + import org.apache.activemq.artemis.jms.client.ActiveMQDestination; import org.apache.activemq.artemis.rest.Jms; @@ -25,35 +26,29 @@ import javax.jms.MessageConsumer; import javax.jms.MessageListener; import javax.jms.Session; -public class JmsReceive -{ - public static void main(String[] args) throws Exception - { +public class JmsReceive { + + public static void main(String[] args) throws Exception { System.out.println("Receive Setup..."); ConnectionFactory factory = JmsHelper.createConnectionFactory("activemq-client.xml"); Destination destination = (ActiveMQDestination) ActiveMQDestination.fromAddress("jms.queue.orders"); Connection conn = factory.createConnection(); - try - { + try { Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(destination); - consumer.setMessageListener(new MessageListener() - { - @Override - public void onMessage(Message message) - { - System.out.println("Received Message: "); - Order order = Jms.getEntity(message, Order.class); - System.out.println(order); - } - } - ); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + System.out.println("Received Message: "); + Order order = Jms.getEntity(message, Order.class); + System.out.println(order); + } + }); conn.start(); Thread.sleep(1000000); } - finally - { + finally { conn.close(); } } diff --git a/examples/jms/rest/jms-to-rest/src/main/java/JmsSend.java b/examples/jms/rest/jms-to-rest/src/main/java/JmsSend.java index fd0d2bd86e..bf3370e13d 100644 --- a/examples/jms/rest/jms-to-rest/src/main/java/JmsSend.java +++ b/examples/jms/rest/jms-to-rest/src/main/java/JmsSend.java @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + import org.apache.activemq.artemis.jms.client.ActiveMQDestination; import javax.jms.Connection; @@ -23,16 +24,14 @@ import javax.jms.MessageProducer; import javax.jms.ObjectMessage; import javax.jms.Session; -public class JmsSend -{ - public static void main(String[] args) throws Exception - { +public class JmsSend { + + public static void main(String[] args) throws Exception { ConnectionFactory factory = JmsHelper.createConnectionFactory("activemq-client.xml"); Destination destination = (ActiveMQDestination) ActiveMQDestination.fromAddress("jms.queue.orders"); Connection conn = factory.createConnection(); - try - { + try { Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(destination); ObjectMessage message = session.createObjectMessage(); @@ -41,8 +40,7 @@ public class JmsSend message.setObject(order); producer.send(message); } - finally - { + finally { conn.close(); } } diff --git a/examples/jms/rest/jms-to-rest/src/main/java/Order.java b/examples/jms/rest/jms-to-rest/src/main/java/Order.java index aa3ad9315d..2b938f7634 100644 --- a/examples/jms/rest/jms-to-rest/src/main/java/Order.java +++ b/examples/jms/rest/jms-to-rest/src/main/java/Order.java @@ -14,64 +14,56 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; -@XmlRootElement(name="order") -public class Order implements Serializable -{ +@XmlRootElement(name = "order") +public class Order implements Serializable { + private String name; private String amount; private String item; - public Order() - { + public Order() { } - public Order(String name, String amount, String item) - { + public Order(String name, String amount, String item) { this.name = name; this.amount = amount; this.item = item; } - public String getName() - { + public String getName() { return name; } - public void setName(String name) - { + public void setName(String name) { this.name = name; } - public String getAmount() - { + public String getAmount() { return amount; } - public void setAmount(String amount) - { + public void setAmount(String amount) { this.amount = amount; } - public String getItem() - { + public String getItem() { return item; } - public void setItem(String item) - { + public void setItem(String item) { this.item = item; } @Override - public String toString() - { + public String toString() { return "Order{" + - "name='" + name + '\'' + - ", amount='" + amount + '\'' + - ", item='" + item + '\'' + - '}'; + "name='" + name + '\'' + + ", amount='" + amount + '\'' + + ", item='" + item + '\'' + + '}'; } } diff --git a/examples/jms/rest/jms-to-rest/src/main/java/RestReceive.java b/examples/jms/rest/jms-to-rest/src/main/java/RestReceive.java index 20bef4ded0..4fc493ab20 100644 --- a/examples/jms/rest/jms-to-rest/src/main/java/RestReceive.java +++ b/examples/jms/rest/jms-to-rest/src/main/java/RestReceive.java @@ -14,14 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + import org.jboss.resteasy.client.ClientRequest; import org.jboss.resteasy.client.ClientResponse; import org.jboss.resteasy.spi.Link; -public class RestReceive -{ - public static void main(String[] args) throws Exception - { +public class RestReceive { + + public static void main(String[] args) throws Exception { // first get the create URL for the shipping queue ClientRequest request = new ClientRequest("http://localhost:9095/queues/jms.queue.orders"); ClientResponse res = request.head(); @@ -29,28 +29,21 @@ public class RestReceive res = pullConsumers.request().formParameter("autoAck", "false").post(); Link ackNext = res.getHeaderAsLink("msg-acknowledge-next"); res.releaseConnection(); - while (true) - { + while (true) { System.out.println("Waiting..."); - res = ackNext.request() - .header("Accept-Wait", "10") - .header("Accept", "application/xml") - .post(); - if (res.getStatus() == 503) - { + res = ackNext.request().header("Accept-Wait", "10").header("Accept", "application/xml").post(); + if (res.getStatus() == 503) { System.out.println("Timeout..."); ackNext = res.getHeaderAsLink("msg-acknowledge-next"); } - else if (res.getStatus() == 200) - { + else if (res.getStatus() == 200) { Order order = (Order) res.getEntity(Order.class); System.out.println(order); Link ack = res.getHeaderAsLink("msg-acknowledgement"); res = ack.request().formParameter("acknowledge", "true").post(); ackNext = res.getHeaderAsLink("msg-acknowledge-next"); } - else - { + else { throw new RuntimeException("Failure! " + res.getStatus()); } res.releaseConnection(); diff --git a/examples/jms/rest/jms-to-rest/src/main/java/RestSend.java b/examples/jms/rest/jms-to-rest/src/main/java/RestSend.java index 435a0a0215..902c4f7cb6 100644 --- a/examples/jms/rest/jms-to-rest/src/main/java/RestSend.java +++ b/examples/jms/rest/jms-to-rest/src/main/java/RestSend.java @@ -14,14 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + import org.jboss.resteasy.client.ClientRequest; import org.jboss.resteasy.client.ClientResponse; import org.jboss.resteasy.spi.Link; -public class RestSend -{ - public static void main(String[] args) throws Exception - { +public class RestSend { + + public static void main(String[] args) throws Exception { // first get the create URL for the shipping queue ClientRequest request = new ClientRequest("http://localhost:9095/queues/jms.queue.orders"); ClientResponse res = request.head(); @@ -34,6 +34,7 @@ public class RestSend order.setAmount("$199.99"); res = create.request().body("application/xml", order).post(); - if (res.getStatus() != 201) throw new RuntimeException("Failed to post"); + if (res.getStatus() != 201) + throw new RuntimeException("Failed to post"); } } diff --git a/examples/jms/rest/push/src/main/java/JmsHelper.java b/examples/jms/rest/push/src/main/java/JmsHelper.java index 9f1707d17d..f4e066e36a 100644 --- a/examples/jms/rest/push/src/main/java/JmsHelper.java +++ b/examples/jms/rest/push/src/main/java/JmsHelper.java @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.api.core.client.ActiveMQClient; @@ -26,10 +27,9 @@ import org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory; import javax.jms.ConnectionFactory; import javax.jms.Destination; -public class JmsHelper -{ - public static ConnectionFactory createConnectionFactory(String configFile) throws Exception - { +public class JmsHelper { + + public static ConnectionFactory createConnectionFactory(String configFile) throws Exception { FileConfiguration config = new FileConfiguration(); FileDeploymentManager deploymentManager = new FileDeploymentManager(configFile); deploymentManager.addDeployable(config); diff --git a/examples/jms/rest/push/src/main/java/Order.java b/examples/jms/rest/push/src/main/java/Order.java index aa3ad9315d..2b938f7634 100644 --- a/examples/jms/rest/push/src/main/java/Order.java +++ b/examples/jms/rest/push/src/main/java/Order.java @@ -14,64 +14,56 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; -@XmlRootElement(name="order") -public class Order implements Serializable -{ +@XmlRootElement(name = "order") +public class Order implements Serializable { + private String name; private String amount; private String item; - public Order() - { + public Order() { } - public Order(String name, String amount, String item) - { + public Order(String name, String amount, String item) { this.name = name; this.amount = amount; this.item = item; } - public String getName() - { + public String getName() { return name; } - public void setName(String name) - { + public void setName(String name) { this.name = name; } - public String getAmount() - { + public String getAmount() { return amount; } - public void setAmount(String amount) - { + public void setAmount(String amount) { this.amount = amount; } - public String getItem() - { + public String getItem() { return item; } - public void setItem(String item) - { + public void setItem(String item) { this.item = item; } @Override - public String toString() - { + public String toString() { return "Order{" + - "name='" + name + '\'' + - ", amount='" + amount + '\'' + - ", item='" + item + '\'' + - '}'; + "name='" + name + '\'' + + ", amount='" + amount + '\'' + + ", item='" + item + '\'' + + '}'; } } diff --git a/examples/jms/rest/push/src/main/java/PostOrder.java b/examples/jms/rest/push/src/main/java/PostOrder.java index 3933e03a2d..96786e6a45 100644 --- a/examples/jms/rest/push/src/main/java/PostOrder.java +++ b/examples/jms/rest/push/src/main/java/PostOrder.java @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + import org.apache.activemq.artemis.jms.client.ActiveMQDestination; import javax.jms.Connection; @@ -23,16 +24,14 @@ import javax.jms.MessageProducer; import javax.jms.ObjectMessage; import javax.jms.Session; -public class PostOrder -{ - public static void main(String[] args) throws Exception - { +public class PostOrder { + + public static void main(String[] args) throws Exception { ConnectionFactory factory = JmsHelper.createConnectionFactory("activemq-client.xml"); Destination destination = (ActiveMQDestination) ActiveMQDestination.fromAddress("jms.queue.orders"); Connection conn = factory.createConnection(); - try - { + try { Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(destination); ObjectMessage message = session.createObjectMessage(); @@ -41,8 +40,7 @@ public class PostOrder message.setObject(order); producer.send(message); } - finally - { + finally { conn.close(); } } diff --git a/examples/jms/rest/push/src/main/java/PushReg.java b/examples/jms/rest/push/src/main/java/PushReg.java index 058c5741a7..2567826e2a 100644 --- a/examples/jms/rest/push/src/main/java/PushReg.java +++ b/examples/jms/rest/push/src/main/java/PushReg.java @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + import org.apache.activemq.artemis.rest.queue.push.xml.Authentication; import org.apache.activemq.artemis.rest.queue.push.xml.BasicAuth; import org.apache.activemq.artemis.rest.queue.push.xml.PushRegistration; @@ -22,10 +23,9 @@ import org.jboss.resteasy.client.ClientRequest; import org.jboss.resteasy.client.ClientResponse; import org.jboss.resteasy.spi.Link; -public class PushReg -{ - public static void main(String[] args) throws Exception - { +public class PushReg { + + public static void main(String[] args) throws Exception { // get the push consumers factory resource ClientRequest request = new ClientRequest("http://localhost:9095/queues/jms.queue.orders"); ClientResponse res = request.head(); diff --git a/examples/jms/rest/push/src/main/java/ReceiveShipping.java b/examples/jms/rest/push/src/main/java/ReceiveShipping.java index ecc62abcc4..46a3619b6c 100644 --- a/examples/jms/rest/push/src/main/java/ReceiveShipping.java +++ b/examples/jms/rest/push/src/main/java/ReceiveShipping.java @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + import org.apache.activemq.artemis.jms.client.ActiveMQDestination; import org.apache.activemq.artemis.rest.Jms; @@ -25,34 +26,28 @@ import javax.jms.MessageConsumer; import javax.jms.MessageListener; import javax.jms.Session; -public class ReceiveShipping -{ - public static void main(String[] args) throws Exception - { +public class ReceiveShipping { + + public static void main(String[] args) throws Exception { ConnectionFactory factory = JmsHelper.createConnectionFactory("activemq-client.xml"); Destination destination = (ActiveMQDestination) ActiveMQDestination.fromAddress("jms.queue.shipping"); Connection conn = factory.createConnection(); - try - { + try { Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(destination); - consumer.setMessageListener(new MessageListener() - { - @Override - public void onMessage(Message message) - { - System.out.println("Received Message: "); - Order order = Jms.getEntity(message, Order.class); - System.out.println(order); - } - } - ); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + System.out.println("Received Message: "); + Order order = Jms.getEntity(message, Order.class); + System.out.println(order); + } + }); conn.start(); Thread.sleep(1000000); } - finally - { + finally { conn.close(); } } diff --git a/examples/jms/scale-down/src/main/java/org/apache/activemq/artemis/jms/example/ScaleDownExample.java b/examples/jms/scale-down/src/main/java/org/apache/activemq/artemis/jms/example/ScaleDownExample.java index 73adf3320a..3d81a38539 100644 --- a/examples/jms/scale-down/src/main/java/org/apache/activemq/artemis/jms/example/ScaleDownExample.java +++ b/examples/jms/scale-down/src/main/java/org/apache/activemq/artemis/jms/example/ScaleDownExample.java @@ -30,16 +30,14 @@ import java.util.Hashtable; /** * A simple example that demonstrates a colocated server - * */ -public class ScaleDownExample -{ +public class ScaleDownExample { + private static Process server0; private static Process server1; - public static void main(final String[] args) throws Exception - { + public static void main(final String[] args) throws Exception { final int numMessages = 30; Connection connection = null; @@ -48,8 +46,7 @@ public class ScaleDownExample InitialContext initialContext = null; InitialContext initialContext1 = null; - try - { + try { server0 = ServerUtil.startServer(args[0], ScaleDownExample.class.getSimpleName() + "0", 0, 5000); server1 = ServerUtil.startServer(args[1], ScaleDownExample.class.getSimpleName() + "1", 1, 5000); @@ -66,9 +63,9 @@ public class ScaleDownExample initialContext1 = new InitialContext(properties); // Step 2. Look up the JMS resources from JNDI - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); - ConnectionFactory connectionFactory = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); - ConnectionFactory connectionFactory1 = (ConnectionFactory)initialContext1.lookup("ConnectionFactory"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); + ConnectionFactory connectionFactory = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); + ConnectionFactory connectionFactory1 = (ConnectionFactory) initialContext1.lookup("ConnectionFactory"); // Step 3. Create a JMS Connections connection = connectionFactory.createConnection(); @@ -83,8 +80,7 @@ public class ScaleDownExample MessageProducer producer1 = session1.createProducer(queue); // Step 6. Send some messages to both servers - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session.createTextMessage("This is text message " + i); producer.send(message); System.out.println("Sent message: " + message.getText()); @@ -105,33 +101,27 @@ public class ScaleDownExample // Step 10. Receive and acknowledge all of the sent messages, the backup server that is colocated with server 1 // will have become live and is now handling messages for server 0. TextMessage message0 = null; - for (int i = 0; i < numMessages * 2; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = 0; i < numMessages * 2; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.println("Got message: " + message0.getText()); } message0.acknowledge(); } - finally - { + finally { // Step 11. Be sure to close our resources! - if (connection != null) - { + if (connection != null) { connection.close(); } - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection1 != null) - { + if (connection1 != null) { connection1.close(); } - if (initialContext1 != null) - { + if (initialContext1 != null) { initialContext1.close(); } diff --git a/examples/jms/scheduled-message/src/main/java/org/apache/activemq/artemis/jms/example/ScheduledMessageExample.java b/examples/jms/scheduled-message/src/main/java/org/apache/activemq/artemis/jms/example/ScheduledMessageExample.java index ffc99d84ef..ba869496b6 100644 --- a/examples/jms/scheduled-message/src/main/java/org/apache/activemq/artemis/jms/example/ScheduledMessageExample.java +++ b/examples/jms/scheduled-message/src/main/java/org/apache/activemq/artemis/jms/example/ScheduledMessageExample.java @@ -30,22 +30,20 @@ import javax.naming.InitialContext; import org.apache.activemq.artemis.api.core.Message; -public class ScheduledMessageExample -{ - public static void main(final String[] args) throws Exception - { +public class ScheduledMessageExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Perfom a lookup on the queue - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 3. Perform a lookup on the Connection Factory - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4.Create a JMS Connection connection = cf.createConnection(); @@ -78,20 +76,17 @@ public class ScheduledMessageExample connection.start(); // Step 12. Receive the message - TextMessage messageReceived = (TextMessage)messageConsumer.receive(); + TextMessage messageReceived = (TextMessage) messageConsumer.receive(); System.out.println("Received message: " + messageReceived.getText()); System.out.println("Time of receive: " + formatter.format(new Date())); } - finally - { + finally { // Step 13. Be sure to close our JMS resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } diff --git a/examples/jms/security/src/main/java/org/apache/activemq/artemis/jms/example/SecurityExample.java b/examples/jms/security/src/main/java/org/apache/activemq/artemis/jms/example/SecurityExample.java index fc83fe7ebd..88fd1dab40 100644 --- a/examples/jms/security/src/main/java/org/apache/activemq/artemis/jms/example/SecurityExample.java +++ b/examples/jms/security/src/main/java/org/apache/activemq/artemis/jms/example/SecurityExample.java @@ -27,11 +27,9 @@ import javax.jms.TextMessage; import javax.jms.Topic; import javax.naming.InitialContext; -public class SecurityExample -{ +public class SecurityExample { - public static void main(final String[] args) throws Exception - { + public static void main(final String[] args) throws Exception { boolean result = true; Connection failConnection = null; Connection billConnection = null; @@ -40,39 +38,34 @@ public class SecurityExample Connection samConnection = null; InitialContext initialContext = null; - try - { + try { // /Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. perform lookup on the topics - Topic genericTopic = (Topic)initialContext.lookup("topic/genericTopic"); - Topic europeTopic = (Topic)initialContext.lookup("topic/europeTopic"); - Topic usTopic = (Topic)initialContext.lookup("topic/usTopic"); + Topic genericTopic = (Topic) initialContext.lookup("topic/genericTopic"); + Topic europeTopic = (Topic) initialContext.lookup("topic/europeTopic"); + Topic usTopic = (Topic) initialContext.lookup("topic/usTopic"); // Step 3. perform a lookup on the Connection Factory - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4. Try to create a JMS Connection without user/password. It will fail. - try - { + try { failConnection = cf.createConnection(); result = false; } - catch (JMSSecurityException e) - { + catch (JMSSecurityException e) { System.out.println("Default user cannot get a connection. Details: " + e.getMessage()); } // Step 5. bill tries to make a connection using wrong password billConnection = null; - try - { + try { billConnection = createConnection("bill", "activemq1", cf); result = false; } - catch (JMSException e) - { + catch (JMSException e) { System.out.println("User bill failed to connect. Details: " + e.getMessage()); } @@ -130,33 +123,26 @@ public class SecurityExample checkUserReceiveNoSend(usTopic, samConnection, "sam", frankConnection); System.out.println("-------------------------------------------------------------------------------------"); } - finally - { + finally { // Step 19. Be sure to close our JMS resources! - if (failConnection != null) - { + if (failConnection != null) { failConnection.close(); } - if (billConnection != null) - { + if (billConnection != null) { billConnection.close(); } - if (andrewConnection != null) - { + if (andrewConnection != null) { andrewConnection.close(); } - if (frankConnection != null) - { + if (frankConnection != null) { frankConnection.close(); } - if (samConnection != null) - { + if (samConnection != null) { samConnection.close(); } // Also the initialContext - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } } @@ -164,26 +150,23 @@ public class SecurityExample // Check the user can receive message but cannot send message. private static void checkUserReceiveNoSend(final Topic topic, - final Connection connection, - final String user, - final Connection sendingConn) throws JMSException - { + final Connection connection, + final String user, + final Connection sendingConn) throws JMSException { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(topic); MessageConsumer consumer = session.createConsumer(topic); TextMessage msg = session.createTextMessage("hello-world-1"); - try - { + try { producer.send(msg); throw new IllegalStateException("Security setting is broken! User " + user + - " can send message [" + - msg.getText() + - "] to topic " + - topic); + " can send message [" + + msg.getText() + + "] to topic " + + topic); } - catch (JMSException e) - { + catch (JMSException e) { System.out.println("User " + user + " cannot send message [" + msg.getText() + "] to topic: " + topic); } @@ -192,14 +175,12 @@ public class SecurityExample producer = session1.createProducer(topic); producer.send(msg); - TextMessage receivedMsg = (TextMessage)consumer.receive(2000); + TextMessage receivedMsg = (TextMessage) consumer.receive(2000); - if (receivedMsg != null) - { + if (receivedMsg != null) { System.out.println("User " + user + " can receive message [" + receivedMsg.getText() + "] from topic " + topic); } - else - { + else { throw new IllegalStateException("Security setting is broken! User " + user + " cannot receive message from topic " + topic); } @@ -209,18 +190,15 @@ public class SecurityExample // Check the user can send message but cannot receive message private static void checkUserSendNoReceive(final Topic topic, - final Connection connection, - final String user, - final Connection receivingConn) throws JMSException - { + final Connection connection, + final String user, + final Connection receivingConn) throws JMSException { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(topic); - try - { + try { session.createConsumer(topic); } - catch (JMSException e) - { + catch (JMSException e) { System.out.println("User " + user + " cannot receive any message from topic " + topic); } @@ -230,18 +208,16 @@ public class SecurityExample TextMessage msg = session.createTextMessage("hello-world-2"); producer.send(msg); - TextMessage receivedMsg = (TextMessage)goodConsumer.receive(2000); - if (receivedMsg != null) - { + TextMessage receivedMsg = (TextMessage) goodConsumer.receive(2000); + if (receivedMsg != null) { System.out.println("User " + user + " can send message [" + receivedMsg.getText() + "] to topic " + topic); } - else - { + else { throw new IllegalStateException("Security setting is broken! User " + user + - " cannot send message [" + - msg.getText() + - "] to topic " + - topic); + " cannot send message [" + + msg.getText() + + "] to topic " + + topic); } session.close(); @@ -249,32 +225,29 @@ public class SecurityExample } // Check the user has neither send nor receive permission on topic - private static void checkUserNoSendNoReceive(final Topic topic, final Connection connection, final String user) throws JMSException - { + private static void checkUserNoSendNoReceive(final Topic topic, + final Connection connection, + final String user) throws JMSException { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(topic); - try - { + try { session.createConsumer(topic); } - catch (JMSException e) - { + catch (JMSException e) { System.out.println("User " + user + " cannot create consumer on topic " + topic); } TextMessage msg = session.createTextMessage("hello-world-3"); - try - { + try { producer.send(msg); throw new IllegalStateException("Security setting is broken! User " + user + - " can send message [" + - msg.getText() + - "] to topic " + - topic); + " can send message [" + + msg.getText() + + "] to topic " + + topic); } - catch (JMSException e) - { + catch (JMSException e) { System.out.println("User " + user + " cannot send message [" + msg.getText() + "] to topic: " + topic); } @@ -282,28 +255,28 @@ public class SecurityExample } // Check the user connection has both send and receive permissions on the topic - private static void checkUserSendAndReceive(final Topic topic, final Connection connection, final String user) throws JMSException - { + private static void checkUserSendAndReceive(final Topic topic, + final Connection connection, + final String user) throws JMSException { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); TextMessage msg = session.createTextMessage("hello-world-4"); MessageProducer producer = session.createProducer(topic); MessageConsumer consumer = session.createConsumer(topic); producer.send(msg); - TextMessage receivedMsg = (TextMessage)consumer.receive(5000); - if (receivedMsg != null) - { + TextMessage receivedMsg = (TextMessage) consumer.receive(5000); + if (receivedMsg != null) { System.out.println("User " + user + " can send message: [" + msg.getText() + "] to topic: " + topic); System.out.println("User " + user + " can receive message: [" + msg.getText() + "] from topic: " + topic); } - else - { + else { throw new IllegalStateException("Error! User " + user + " cannot receive the message! "); } session.close(); } - private static Connection createConnection(final String username, final String password, final ConnectionFactory cf) throws JMSException - { + private static Connection createConnection(final String username, + final String password, + final ConnectionFactory cf) throws JMSException { return cf.createConnection(username, password); } } diff --git a/examples/jms/send-acknowledgements/src/main/java/org/apache/activemq/artemis/jms/example/SendAcknowledgementsExample.java b/examples/jms/send-acknowledgements/src/main/java/org/apache/activemq/artemis/jms/example/SendAcknowledgementsExample.java index 99fb0bae21..578d1984b9 100644 --- a/examples/jms/send-acknowledgements/src/main/java/org/apache/activemq/artemis/jms/example/SendAcknowledgementsExample.java +++ b/examples/jms/send-acknowledgements/src/main/java/org/apache/activemq/artemis/jms/example/SendAcknowledgementsExample.java @@ -30,39 +30,35 @@ import org.apache.activemq.artemis.api.core.client.SendAcknowledgementHandler; import org.apache.activemq.artemis.jms.client.ActiveMQSession; /** - * * Asynchronous Send Acknowledgements are an advanced feature of ActiveMQ Artemis which allow you to * receive acknowledgements that messages were successfully received at the server in a separate stream * to the stream of messages being sent to the server. * For more information please see the readme.html file */ -public class SendAcknowledgementsExample -{ - public static void main(final String[] args) throws Exception - { +public class SendAcknowledgementsExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Perfom a lookup on the queue - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 3. Perform a lookup on the Connection Factory - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4. Create a JMS Connection connection = cf.createConnection(); // Step 5. Define a SendAcknowledgementHandler which will receive asynchronous acknowledgements - class MySendAcknowledgementsHandler implements SendAcknowledgementHandler - { + class MySendAcknowledgementsHandler implements SendAcknowledgementHandler { + int count = 0; - public void sendAcknowledged(final Message message) - { + public void sendAcknowledged(final Message message) { System.out.println("Received send acknowledgement for message " + count++); } } @@ -72,7 +68,7 @@ public class SendAcknowledgementsExample // Step 7. Set the handler on the underlying core session - ClientSession coreSession = ((ActiveMQSession)session).getCoreSession(); + ClientSession coreSession = ((ActiveMQSession) session).getCoreSession(); coreSession.setSendAcknowledgementHandler(new MySendAcknowledgementsHandler()); @@ -86,8 +82,7 @@ public class SendAcknowledgementsExample final int numMessages = 5000; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { javax.jms.Message jmsMessage = session.createMessage(); producer.send(jmsMessage); @@ -95,16 +90,13 @@ public class SendAcknowledgementsExample System.out.println("Sent message " + i); } } - finally - { + finally { // Step 12. Be sure to close our JMS resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } diff --git a/examples/jms/spring-integration/src/main/java/org/apache/activemq/artemis/jms/example/ExampleListener.java b/examples/jms/spring-integration/src/main/java/org/apache/activemq/artemis/jms/example/ExampleListener.java index 759ca5fcba..3d4e063f6b 100644 --- a/examples/jms/spring-integration/src/main/java/org/apache/activemq/artemis/jms/example/ExampleListener.java +++ b/examples/jms/spring-integration/src/main/java/org/apache/activemq/artemis/jms/example/ExampleListener.java @@ -21,18 +21,15 @@ import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; -public class ExampleListener implements MessageListener -{ +public class ExampleListener implements MessageListener { + protected static String lastMessage = null; - public void onMessage(Message message) - { - try - { - lastMessage = ((TextMessage)message).getText(); + public void onMessage(Message message) { + try { + lastMessage = ((TextMessage) message).getText(); } - catch (JMSException e) - { + catch (JMSException e) { throw new RuntimeException(e); } System.out.println("MESSAGE RECEIVED: " + lastMessage); diff --git a/examples/jms/spring-integration/src/main/java/org/apache/activemq/artemis/jms/example/MessageSender.java b/examples/jms/spring-integration/src/main/java/org/apache/activemq/artemis/jms/example/MessageSender.java index 3519080267..594c69b335 100644 --- a/examples/jms/spring-integration/src/main/java/org/apache/activemq/artemis/jms/example/MessageSender.java +++ b/examples/jms/spring-integration/src/main/java/org/apache/activemq/artemis/jms/example/MessageSender.java @@ -24,56 +24,45 @@ import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; -public class MessageSender -{ +public class MessageSender { + private ConnectionFactory connectionFactory; private Destination destination; - public ConnectionFactory getConnectionFactory() - { + public ConnectionFactory getConnectionFactory() { return connectionFactory; } - public void setConnectionFactory(ConnectionFactory connectionFactory) - { + public void setConnectionFactory(ConnectionFactory connectionFactory) { this.connectionFactory = connectionFactory; } - public Destination getDestination() - { + public Destination getDestination() { return destination; } - public void setDestination(Destination destination) - { + public void setDestination(Destination destination) { this.destination = destination; } - public void send(String msg) - { + public void send(String msg) { Connection conn = null; - try - { + try { conn = connectionFactory.createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(destination); TextMessage message = session.createTextMessage(msg); producer.send(message); } - catch (Exception ex) - { + catch (Exception ex) { ex.printStackTrace(); } - finally - { - if (conn != null) - { - try - { + finally { + if (conn != null) { + try { conn.close(); } - catch (JMSException e) - { + catch (JMSException e) { e.printStackTrace(); } } diff --git a/examples/jms/spring-integration/src/main/java/org/apache/activemq/artemis/jms/example/SpringExample.java b/examples/jms/spring-integration/src/main/java/org/apache/activemq/artemis/jms/example/SpringExample.java index 3de0527bf6..cf3ec49375 100644 --- a/examples/jms/spring-integration/src/main/java/org/apache/activemq/artemis/jms/example/SpringExample.java +++ b/examples/jms/spring-integration/src/main/java/org/apache/activemq/artemis/jms/example/SpringExample.java @@ -18,13 +18,12 @@ package org.apache.activemq.artemis.jms.example; import org.springframework.context.support.ClassPathXmlApplicationContext; -public class SpringExample -{ - public static void main(String[] args) throws Exception - { +public class SpringExample { + + public static void main(String[] args) throws Exception { System.out.println("Creating bean factory..."); - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"spring-jms-beans.xml"}); - MessageSender sender = (MessageSender)context.getBean("MessageSender"); + ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"spring-jms-beans.xml"}); + MessageSender sender = (MessageSender) context.getBean("MessageSender"); System.out.println("Sending message..."); sender.send("Hello world"); Thread.sleep(100); diff --git a/examples/jms/ssl-enabled/src/main/java/org/apache/activemq/artemis/jms/example/SSLExample.java b/examples/jms/ssl-enabled/src/main/java/org/apache/activemq/artemis/jms/example/SSLExample.java index a43e4c00c6..27bf7390e4 100644 --- a/examples/jms/ssl-enabled/src/main/java/org/apache/activemq/artemis/jms/example/SSLExample.java +++ b/examples/jms/ssl-enabled/src/main/java/org/apache/activemq/artemis/jms/example/SSLExample.java @@ -28,22 +28,20 @@ import javax.naming.InitialContext; /** * A simple JMS Queue example that uses SSL secure transport. */ -public class SSLExample -{ - public static void main(final String[] args) throws Exception - { +public class SSLExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Perfom a lookup on the queue - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 3. Perform a lookup on the Connection Factory - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4.Create a JMS Connection connection = cf.createConnection(); @@ -69,21 +67,18 @@ public class SSLExample connection.start(); // Step 11. Receive the message - TextMessage messageReceived = (TextMessage)messageConsumer.receive(5000); + TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000); System.out.println("Received message: " + messageReceived.getText()); initialContext.close(); } - finally - { + finally { // Step 12. Be sure to close our JMS resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } diff --git a/examples/jms/static-selector/src/main/java/org/apache/activemq/artemis/jms/example/StaticSelectorExample.java b/examples/jms/static-selector/src/main/java/org/apache/activemq/artemis/jms/example/StaticSelectorExample.java index 532ca50bc6..08f9db966d 100644 --- a/examples/jms/static-selector/src/main/java/org/apache/activemq/artemis/jms/example/StaticSelectorExample.java +++ b/examples/jms/static-selector/src/main/java/org/apache/activemq/artemis/jms/example/StaticSelectorExample.java @@ -32,23 +32,21 @@ import java.util.concurrent.atomic.AtomicBoolean; /** * A simple JMS example that shows how static message selectors work. */ -public class StaticSelectorExample -{ - public static void main(final String[] args) throws Exception - { +public class StaticSelectorExample { + + public static void main(final String[] args) throws Exception { AtomicBoolean result = new AtomicBoolean(true); Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. look-up the JMS queue object from JNDI, this is the queue that has filter configured with it. - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 3. look-up the JMS connection factory object from JNDI - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4. Create a JMS Connection connection = cf.createConnection(); @@ -96,51 +94,42 @@ public class StaticSelectorExample if (!result.get()) throw new IllegalStateException(); } - finally - { + finally { // Step 12. Be sure to close our JMS resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } } } +class SimpleMessageListener implements MessageListener { -class SimpleMessageListener implements MessageListener -{ private final String name; private AtomicBoolean result; - public SimpleMessageListener(final String listener, AtomicBoolean result) - { + public SimpleMessageListener(final String listener, AtomicBoolean result) { name = listener; this.result = result; } - public void onMessage(final Message msg) - { - TextMessage textMessage = (TextMessage)msg; - try - { + public void onMessage(final Message msg) { + TextMessage textMessage = (TextMessage) msg; + try { String colorProp = msg.getStringProperty("color"); System.out.println("Receiver " + name + - " receives message [" + - textMessage.getText() + - "] with color property: " + - colorProp); - if (colorProp != null && !colorProp.equals(name)) - { + " receives message [" + + textMessage.getText() + + "] with color property: " + + colorProp); + if (colorProp != null && !colorProp.equals(name)) { result.set(false); } } - catch (JMSException e) - { + catch (JMSException e) { e.printStackTrace(); result.set(false); } diff --git a/examples/jms/stomp-websockets/src/main/java/org/apache/activemq/artemis/jms/example/StompWebSocketExample.java b/examples/jms/stomp-websockets/src/main/java/org/apache/activemq/artemis/jms/example/StompWebSocketExample.java index 7260a091d9..d784e6b09a 100644 --- a/examples/jms/stomp-websockets/src/main/java/org/apache/activemq/artemis/jms/example/StompWebSocketExample.java +++ b/examples/jms/stomp-websockets/src/main/java/org/apache/activemq/artemis/jms/example/StompWebSocketExample.java @@ -31,17 +31,15 @@ import javax.naming.InitialContext; * An example where a client will send a JMS message to a Topic. * Browser clients connected using Web Sockets will be able to receive the message. */ -public class StompWebSocketExample -{ - public static void main(final String[] args) throws Exception - { +public class StompWebSocketExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext initialContext = null; - try - { + try { initialContext = new InitialContext(); - Topic topic = (Topic)initialContext.lookup("topic/chat"); - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + Topic topic = (Topic) initialContext.lookup("topic/chat"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -60,18 +58,15 @@ public class StompWebSocketExample connection.start(); - message = (TextMessage)consumer.receive(); + message = (TextMessage) consumer.receive(); System.out.println("Received message: " + message.getText()); } - finally - { - if (connection != null) - { + finally { + if (connection != null) { connection.close(); } - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } } diff --git a/examples/jms/stomp/src/main/java/org/apache/activemq/artemis/jms/example/StompExample.java b/examples/jms/stomp/src/main/java/org/apache/activemq/artemis/jms/example/StompExample.java index 0d4f28f3e0..e7ea406f18 100644 --- a/examples/jms/stomp/src/main/java/org/apache/activemq/artemis/jms/example/StompExample.java +++ b/examples/jms/stomp/src/main/java/org/apache/activemq/artemis/jms/example/StompExample.java @@ -33,27 +33,25 @@ import javax.naming.InitialContext; * An example where a client will send a Stomp message on a TCP socket * and consume it from a JMS MessageConsumer. */ -public class StompExample -{ +public class StompExample { + private static final String END_OF_FRAME = "\u0000"; - public static void main(final String[] args) throws Exception - { + public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create a TCP socket to connect to the Stomp port Socket socket = new Socket("localhost", 61613); // Step 2. Send a CONNECT frame to connect to the server String connectFrame = "CONNECT\n" + - "login: guest\n" + - "passcode: guest\n" + - "request-id: 1\n" + - "\n" + - END_OF_FRAME; + "login: guest\n" + + "passcode: guest\n" + + "request-id: 1\n" + + "\n" + + END_OF_FRAME; sendFrame(socket, connectFrame); readFrame(socket); @@ -62,17 +60,17 @@ public class StompExample // jms.queue.exampleQueue address with a text body String text = "Hello, world from Stomp!"; String message = "SEND\n" + - "destination: jms.queue.exampleQueue\n" + - "\n" + - text + - END_OF_FRAME; + "destination: jms.queue.exampleQueue\n" + + "\n" + + text + + END_OF_FRAME; sendFrame(socket, message); System.out.println("Sent Stomp message: " + text); // Step 4. Send a DISCONNECT frame to disconnect from the server String disconnectFrame = "DISCONNECT\n" + - "\n" + - END_OF_FRAME; + "\n" + + END_OF_FRAME; sendFrame(socket, disconnectFrame); // Step 5. Slose the TCP socket @@ -84,8 +82,8 @@ public class StompExample initialContext = new InitialContext(); // Step 7. Perform a lookup on the queue and the connection factory - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 8.Create a JMS Connection, Session and a MessageConsumer on the queue connection = cf.createConnection(); @@ -96,36 +94,30 @@ public class StompExample connection.start(); // Step 10. Receive the message - TextMessage messageReceived = (TextMessage)consumer.receive(5000); + TextMessage messageReceived = (TextMessage) consumer.receive(5000); System.out.println("Received JMS message: " + messageReceived.getText()); } - finally - { + finally { // Step 11. Be sure to close our JMS resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } } - private static void sendFrame(Socket socket, String data) throws Exception - { + private static void sendFrame(Socket socket, String data) throws Exception { byte[] bytes = data.getBytes(StandardCharsets.UTF_8); OutputStream outputStream = socket.getOutputStream(); - for (int i = 0; i < bytes.length; i++) - { + for (int i = 0; i < bytes.length; i++) { outputStream.write(bytes[i]); } outputStream.flush(); } - private static String readFrame(Socket socket) throws Exception - { + private static String readFrame(Socket socket) throws Exception { byte[] bytes = new byte[2048]; InputStream inputStream = socket.getInputStream(); int nbytes = inputStream.read(bytes); diff --git a/examples/jms/stomp1.1/src/main/java/org/apache/activemq/artemis/jms/example/StompExample.java b/examples/jms/stomp1.1/src/main/java/org/apache/activemq/artemis/jms/example/StompExample.java index 7d3b3cc5bd..4e22435af3 100644 --- a/examples/jms/stomp1.1/src/main/java/org/apache/activemq/artemis/jms/example/StompExample.java +++ b/examples/jms/stomp1.1/src/main/java/org/apache/activemq/artemis/jms/example/StompExample.java @@ -33,29 +33,27 @@ import javax.naming.InitialContext; * An example where a Stomp 1.1 client sends a message on a TCP socket * and consumes it from a JMS MessageConsumer. */ -public class StompExample -{ +public class StompExample { + private static final String END_OF_FRAME = "\u0000"; - public static void main(final String[] args) throws Exception - { + public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create a TCP socket to connect to the Stomp port Socket socket = new Socket("localhost", 61613); // Step 2. Send a CONNECT frame to connect to the server String connectFrame = "CONNECT\n" + - "accept-version:1.1\n" + - "host:localhost\n" + - "login:guest\n" + - "passcode:guest\n" + - "request-id:1\n" + - "\n" + - END_OF_FRAME; + "accept-version:1.1\n" + + "host:localhost\n" + + "login:guest\n" + + "passcode:guest\n" + + "request-id:1\n" + + "\n" + + END_OF_FRAME; sendFrame(socket, connectFrame); String response = receiveFrame(socket); @@ -65,17 +63,17 @@ public class StompExample // jms.queue.exampleQueue address with a text body String text = "Hello World from Stomp 1.1 !"; String message = "SEND\n" + - "destination:jms.queue.exampleQueue\n" + - "\n" + - text + - END_OF_FRAME; + "destination:jms.queue.exampleQueue\n" + + "\n" + + text + + END_OF_FRAME; sendFrame(socket, message); System.out.println("Sent Stomp message: " + text); // Step 4. Send a DISCONNECT frame to disconnect from the server String disconnectFrame = "DISCONNECT\n" + - "\n" + - END_OF_FRAME; + "\n" + + END_OF_FRAME; sendFrame(socket, disconnectFrame); // Step 5. Slose the TCP socket @@ -87,8 +85,8 @@ public class StompExample initialContext = new InitialContext(); // Step 7. Perform a lookup on the queue and the connection factory - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 8.Create a JMS Connection, Session and a MessageConsumer on the queue connection = cf.createConnection(); @@ -99,36 +97,30 @@ public class StompExample connection.start(); // Step 10. Receive the message - TextMessage messageReceived = (TextMessage)consumer.receive(5000); + TextMessage messageReceived = (TextMessage) consumer.receive(5000); System.out.println("Received JMS message: " + messageReceived.getText()); } - finally - { + finally { // Step 11. Be sure to close our JMS resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } } - private static void sendFrame(Socket socket, String data) throws Exception - { + private static void sendFrame(Socket socket, String data) throws Exception { byte[] bytes = data.getBytes(StandardCharsets.UTF_8); OutputStream outputStream = socket.getOutputStream(); - for (int i = 0; i < bytes.length; i++) - { + for (int i = 0; i < bytes.length; i++) { outputStream.write(bytes[i]); } outputStream.flush(); } - private static String receiveFrame(Socket socket) throws Exception - { + private static String receiveFrame(Socket socket) throws Exception { InputStream inputStream = socket.getInputStream(); byte[] buffer = new byte[1024]; int size = inputStream.read(buffer); diff --git a/examples/jms/stomp1.2/src/main/java/org/apache/activemq/artemis/jms/example/StompExample.java b/examples/jms/stomp1.2/src/main/java/org/apache/activemq/artemis/jms/example/StompExample.java index fc978f7113..116e464dd5 100644 --- a/examples/jms/stomp1.2/src/main/java/org/apache/activemq/artemis/jms/example/StompExample.java +++ b/examples/jms/stomp1.2/src/main/java/org/apache/activemq/artemis/jms/example/StompExample.java @@ -32,29 +32,27 @@ import javax.naming.InitialContext; * An example where a Stomp 1.2 client sends a message on a TCP socket * and consumes it from a JMS MessageConsumer. */ -public class StompExample -{ +public class StompExample { + private static final String END_OF_FRAME = "\u0000"; - public static void main(final String[] args) throws Exception - { + public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create a TCP socket to connect to the Stomp port Socket socket = new Socket("localhost", 61613); // Step 2. Send a CONNECT frame to connect to the server String connectFrame = "CONNECT\n" + - "accept-version:1.2\n" + - "host:localhost\n" + - "login:guest\n" + - "passcode:guest\n" + - "request-id:1\n" + - "\n" + - END_OF_FRAME; + "accept-version:1.2\n" + + "host:localhost\n" + + "login:guest\n" + + "passcode:guest\n" + + "request-id:1\n" + + "\n" + + END_OF_FRAME; sendFrame(socket, connectFrame); String response = receiveFrame(socket); @@ -64,17 +62,17 @@ public class StompExample // jms.queue.exampleQueue address with a text body String text = "Hello World from Stomp 1.2 !"; String message = "SEND\n" + - "destination:jms.queue.exampleQueue\n" + - "\n" + - text + - END_OF_FRAME; + "destination:jms.queue.exampleQueue\n" + + "\n" + + text + + END_OF_FRAME; sendFrame(socket, message); System.out.println("Sent Stomp message: " + text); // Step 4. Send a DISCONNECT frame to disconnect from the server String disconnectFrame = "DISCONNECT\n" + - "\n" + - END_OF_FRAME; + "\n" + + END_OF_FRAME; sendFrame(socket, disconnectFrame); // Step 5. Slose the TCP socket @@ -86,8 +84,8 @@ public class StompExample initialContext = new InitialContext(); // Step 7. Perform a lookup on the queue and the connection factory - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 8.Create a JMS Connection, Session and a MessageConsumer on the queue connection = cf.createConnection(); @@ -98,36 +96,30 @@ public class StompExample connection.start(); // Step 10. Receive the message - TextMessage messageReceived = (TextMessage)consumer.receive(5000); + TextMessage messageReceived = (TextMessage) consumer.receive(5000); System.out.println("Received JMS message: " + messageReceived.getText()); } - finally - { + finally { // Step 11. Be sure to close our JMS resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } } - private static void sendFrame(Socket socket, String data) throws Exception - { + private static void sendFrame(Socket socket, String data) throws Exception { byte[] bytes = data.getBytes("UTF-8"); OutputStream outputStream = socket.getOutputStream(); - for (int i = 0; i < bytes.length; i++) - { + for (int i = 0; i < bytes.length; i++) { outputStream.write(bytes[i]); } outputStream.flush(); } - private static String receiveFrame(Socket socket) throws Exception - { + private static String receiveFrame(Socket socket) throws Exception { InputStream inputStream = socket.getInputStream(); byte[] buffer = new byte[1024]; int size = inputStream.read(buffer); diff --git a/examples/jms/stop-server-failover/src/main/java/org/apache/activemq/artemis/jms/example/StopServerFailoverExample.java b/examples/jms/stop-server-failover/src/main/java/org/apache/activemq/artemis/jms/example/StopServerFailoverExample.java index 01ee51bd66..38f06c07b6 100644 --- a/examples/jms/stop-server-failover/src/main/java/org/apache/activemq/artemis/jms/example/StopServerFailoverExample.java +++ b/examples/jms/stop-server-failover/src/main/java/org/apache/activemq/artemis/jms/example/StopServerFailoverExample.java @@ -30,24 +30,22 @@ import javax.naming.InitialContext; * A simple example that demonstrates failover of the JMS connection from one node to another * when the live server crashes using a JMS non-transacted session. */ -public class StopServerFailoverExample -{ - public static void main(final String[] args) throws Exception - { +public class StopServerFailoverExample { + + public static void main(final String[] args) throws Exception { final int numMessages = 10; Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Get an initial context for looking up JNDI from the server #1 initialContext = new InitialContext(); // Step 2. Look up the JMS resources from JNDI - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); - ConnectionFactory connectionFactory = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); + ConnectionFactory connectionFactory = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 3. Create a JMS Connection connection = connectionFactory.createConnection(); @@ -63,8 +61,7 @@ public class StopServerFailoverExample MessageConsumer consumer = session.createConsumer(queue); // Step 7. Send some messages to server #1, the live server - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session.createTextMessage("This is text message " + i); producer.send(message); System.out.println("Sent message: " + message.getText()); @@ -72,17 +69,15 @@ public class StopServerFailoverExample // Step 8. Receive and acknowledge half of the sent messages TextMessage message0 = null; - for (int i = 0; i < numMessages / 2; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = 0; i < numMessages / 2; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.println("Got message: " + message0.getText()); } message0.acknowledge(); // Step 9. Receive the 2nd half of the sent messages but *do not* acknowledge them yet - for (int i = numMessages / 2; i < numMessages; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = numMessages / 2; i < numMessages; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.println("Got message: " + message0.getText()); } @@ -93,34 +88,28 @@ public class StopServerFailoverExample // Step 11. Acknowledging the 2nd half of the sent messages will fail as failover to the // backup server has occurred - try - { + try { message0.acknowledge(); } - catch (JMSException e) - { + catch (JMSException e) { System.err.println("Got exception while acknowledging message: " + e.getMessage()); } // Step 12. Consume again the 2nd half of the messages again. Note that they are not considered as redelivered. - for (int i = numMessages / 2; i < numMessages; i++) - { - message0 = (TextMessage)consumer.receive(5000); + for (int i = numMessages / 2; i < numMessages; i++) { + message0 = (TextMessage) consumer.receive(5000); System.out.printf("Got message: %s (redelivered?: %s)\n", message0.getText(), message0.getJMSRedelivered()); } message0.acknowledge(); } - finally - { + finally { // Step 13. Be sure to close our resources! - if (connection != null) - { + if (connection != null) { connection.close(); } - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } } diff --git a/examples/jms/symmetric-cluster/src/main/java/org/apache/activemq/artemis/jms/example/SymmetricClusterExample.java b/examples/jms/symmetric-cluster/src/main/java/org/apache/activemq/artemis/jms/example/SymmetricClusterExample.java index e332f04607..1163ec872d 100644 --- a/examples/jms/symmetric-cluster/src/main/java/org/apache/activemq/artemis/jms/example/SymmetricClusterExample.java +++ b/examples/jms/symmetric-cluster/src/main/java/org/apache/activemq/artemis/jms/example/SymmetricClusterExample.java @@ -47,10 +47,9 @@ import org.apache.activemq.artemis.api.jms.JMSFactoryType; *

    * Please see the readme.html file for more information. */ -public class SymmetricClusterExample -{ - public static void main(final String[] args) throws Exception - { +public class SymmetricClusterExample { + + public static void main(final String[] args) throws Exception { Connection connection0 = null; Connection connection1 = null; @@ -63,8 +62,7 @@ public class SymmetricClusterExample Connection connection5 = null; - try - { + try { // Step 1 - We instantiate a connection factory directly, specifying the UDP address and port for discovering // the list of servers in the cluster. // We could use JNDI to look-up a connection factory, but we'd need to know the JNDI server host and port for @@ -154,8 +152,7 @@ public class SymmetricClusterExample final int numMessages = 500; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message1 = session2.createTextMessage("Topic message " + i); producer2.send(topic, message1); @@ -167,60 +164,51 @@ public class SymmetricClusterExample // Step 9. Verify all subscribers and the consumer receive the messages - for (int i = 0; i < numMessages; i++) - { - TextMessage received0 = (TextMessage)subscriber0.receive(5000); + for (int i = 0; i < numMessages; i++) { + TextMessage received0 = (TextMessage) subscriber0.receive(5000); - if (received0 == null) - { + if (received0 == null) { throw new IllegalStateException("Message is null!"); } - TextMessage received1 = (TextMessage)subscriber1.receive(5000); + TextMessage received1 = (TextMessage) subscriber1.receive(5000); - if (received1 == null) - { + if (received1 == null) { throw new IllegalStateException("Message is null!"); } - TextMessage received2 = (TextMessage)subscriber2.receive(5000); + TextMessage received2 = (TextMessage) subscriber2.receive(5000); - if (received2 == null) - { + if (received2 == null) { throw new IllegalStateException("Message is null!"); } - TextMessage received3 = (TextMessage)subscriber3.receive(5000); + TextMessage received3 = (TextMessage) subscriber3.receive(5000); - if (received3 == null) - { + if (received3 == null) { throw new IllegalStateException("Message is null!"); } - TextMessage received4 = (TextMessage)subscriber4.receive(5000); + TextMessage received4 = (TextMessage) subscriber4.receive(5000); - if (received4 == null) - { + if (received4 == null) { throw new IllegalStateException("Message is null!"); } - TextMessage received5 = (TextMessage)subscriber5.receive(5000); + TextMessage received5 = (TextMessage) subscriber5.receive(5000); - if (received5 == null) - { + if (received5 == null) { throw new IllegalStateException("Message is null!"); } - TextMessage received6 = (TextMessage)consumer0.receive(5000); + TextMessage received6 = (TextMessage) consumer0.receive(5000); - if (received6 == null) - { + if (received6 == null) { throw new IllegalStateException("Message is null!"); } } } - finally - { + finally { // Step 15. Be sure to close our resources! connection0.close(); diff --git a/examples/jms/temp-queue/src/main/java/org/apache/activemq/artemis/jms/example/TemporaryQueueExample.java b/examples/jms/temp-queue/src/main/java/org/apache/activemq/artemis/jms/example/TemporaryQueueExample.java index a2f7d3841d..5747faeceb 100644 --- a/examples/jms/temp-queue/src/main/java/org/apache/activemq/artemis/jms/example/TemporaryQueueExample.java +++ b/examples/jms/temp-queue/src/main/java/org/apache/activemq/artemis/jms/example/TemporaryQueueExample.java @@ -29,19 +29,17 @@ import javax.naming.InitialContext; /** * A simple JMS example that shows how to use temporary queues. */ -public class TemporaryQueueExample -{ - public static void main(final String[] args) throws Exception - { +public class TemporaryQueueExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Look-up the JMS connection factory - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 3. Create a JMS Connection connection = cf.createConnection(); @@ -72,7 +70,7 @@ public class TemporaryQueueExample MessageConsumer messageConsumer = session.createConsumer(tempQueue); // Step 12. Receive the message from the queue - message = (TextMessage)messageConsumer.receive(5000); + message = (TextMessage) messageConsumer.receive(5000); System.out.println("Received message: " + message.getText()); @@ -98,25 +96,20 @@ public class TemporaryQueueExample session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Step 19. Try to access the tempQueue2 outside its lifetime - try - { + try { messageConsumer = session.createConsumer(tempQueue2); throw new Exception("Temporary queue cannot be accessed outside its lifecycle!"); } - catch (JMSException e) - { + catch (JMSException e) { System.out.println("Exception got when trying to access a temp queue outside its scope: " + e); } } - finally - { - if (connection != null) - { + finally { + if (connection != null) { // Step 20. Be sure to close our JMS resources! connection.close(); } - if (initialContext != null) - { + if (initialContext != null) { // Step 21. Also close the initialContext! initialContext.close(); } diff --git a/examples/jms/topic-hierarchies/src/main/java/org/apache/activemq/artemis/jms/example/TopicHierarchyExample.java b/examples/jms/topic-hierarchies/src/main/java/org/apache/activemq/artemis/jms/example/TopicHierarchyExample.java index f2385baf07..0a720dac12 100644 --- a/examples/jms/topic-hierarchies/src/main/java/org/apache/activemq/artemis/jms/example/TopicHierarchyExample.java +++ b/examples/jms/topic-hierarchies/src/main/java/org/apache/activemq/artemis/jms/example/TopicHierarchyExample.java @@ -33,19 +33,17 @@ import org.apache.activemq.artemis.api.jms.ActiveMQJMSClient; * * For more information please see the readme.html */ -public class TopicHierarchyExample -{ - public static void main(final String[] args) throws Exception - { +public class TopicHierarchyExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 3. Perform a lookup on the Connection Factory - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4. Create a JMS Connection connection = cf.createConnection(); @@ -94,32 +92,28 @@ public class TopicHierarchyExample // that doesn't match news.usa.wrestling. However we do receive the Europe sport message, and the // europe entertainment message, since these match the wildcard. - TextMessage messageReceived1 = (TextMessage)messageConsumer.receive(5000); + TextMessage messageReceived1 = (TextMessage) messageConsumer.receive(5000); System.out.println("Received message: " + messageReceived1.getText()); - TextMessage messageReceived2 = (TextMessage)messageConsumer.receive(5000); + TextMessage messageReceived2 = (TextMessage) messageConsumer.receive(5000); System.out.println("Received message: " + messageReceived2.getText()); Message message = messageConsumer.receive(1000); - if (message != null) - { + if (message != null) { throw new IllegalStateException("Message was not null."); } System.out.println("Didn't received any more message: " + message); } - finally - { + finally { // Step 12. Be sure to close our resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } diff --git a/examples/jms/topic-selector-example1/src/main/java/org/apache/activemq/artemis/jms/example/TopicSelectorExample1.java b/examples/jms/topic-selector-example1/src/main/java/org/apache/activemq/artemis/jms/example/TopicSelectorExample1.java index 28c128ed02..53aee126cd 100644 --- a/examples/jms/topic-selector-example1/src/main/java/org/apache/activemq/artemis/jms/example/TopicSelectorExample1.java +++ b/examples/jms/topic-selector-example1/src/main/java/org/apache/activemq/artemis/jms/example/TopicSelectorExample1.java @@ -28,24 +28,22 @@ import javax.naming.InitialContext; /** * A simple JMS Topic example that creates a producer and consumer on a queue and sends and receives a message. */ -public class TopicSelectorExample1 -{ - public static void main(final String[] args) throws Exception - { +public class TopicSelectorExample1 { + + public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Look-up the JMS topic - Topic topic = (Topic)initialContext.lookup("topic/exampleTopic"); + Topic topic = (Topic) initialContext.lookup("topic/exampleTopic"); // Step 3. Look-up the JMS connection factory - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4. Create a JMS connection connection = cf.createConnection(); @@ -67,14 +65,12 @@ public class TopicSelectorExample1 // Step 10. Send 20 messages, 10 with someID=1, 10 with someID=2 - for (int i = 1; i < 10; i++) - { - for (int someID = 1; someID <= 2; someID++) - { + for (int i = 1; i < 10; i++) { + for (int someID = 1; someID <= 2; someID++) { // Step 10.1 Create a text message TextMessage message1 = session.createTextMessage("This is a text message " + i + - " sent for someID=" + - someID); + " sent for someID=" + + someID); // Step 10.1 Set a property message1.setIntProperty("someID", someID); @@ -93,48 +89,42 @@ public class TopicSelectorExample1 System.out.println("*************************************************************"); System.out.println("MessageConsumer1 will only receive messages where someID=1:"); - for (;;) - { - TextMessage messageReceivedA = (TextMessage)messageConsumer1.receive(1000); - if (messageReceivedA == null) - { + for (;;) { + TextMessage messageReceivedA = (TextMessage) messageConsumer1.receive(1000); + if (messageReceivedA == null) { break; } System.out.println("messageConsumer1 received " + messageReceivedA.getText() + - " someID = " + - messageReceivedA.getIntProperty("someID")); + " someID = " + + messageReceivedA.getIntProperty("someID")); } // Step 13. Consume the messages from MessageConsumer2, filtering out someID=2 System.out.println("*************************************************************"); System.out.println("MessageConsumer2 will only receive messages where someID=2:"); - for (;;) - { - TextMessage messageReceivedB = (TextMessage)messageConsumer2.receive(1000); - if (messageReceivedB == null) - { + for (;;) { + TextMessage messageReceivedB = (TextMessage) messageConsumer2.receive(1000); + if (messageReceivedB == null) { break; } System.out.println("messageConsumer2 received " + messageReceivedB.getText() + - " someID = " + - messageReceivedB.getIntProperty("someID")); + " someID = " + + messageReceivedB.getIntProperty("someID")); } // Step 14. Consume the messages from MessageConsumer3, receiving the complete set of messages System.out.println("*************************************************************"); System.out.println("MessageConsumer3 will receive every message:"); - for (;;) - { - TextMessage messageReceivedC = (TextMessage)messageConsumer3.receive(1000); - if (messageReceivedC == null) - { + for (;;) { + TextMessage messageReceivedC = (TextMessage) messageConsumer3.receive(1000); + if (messageReceivedC == null) { break; } System.out.println("messageConsumer3 received " + messageReceivedC.getText() + - " someID = " + - messageReceivedC.getIntProperty("someID")); + " someID = " + + messageReceivedC.getIntProperty("someID")); } // Step 15. Close the subscribers @@ -142,15 +132,12 @@ public class TopicSelectorExample1 messageConsumer2.close(); messageConsumer3.close(); } - finally - { + finally { // Step 15. Be sure to close our JMS resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } diff --git a/examples/jms/topic-selector-example2/src/main/java/org/apache/activemq/artemis/jms/example/TopicSelectorExample2.java b/examples/jms/topic-selector-example2/src/main/java/org/apache/activemq/artemis/jms/example/TopicSelectorExample2.java index e80d22d99b..464b21bbe3 100644 --- a/examples/jms/topic-selector-example2/src/main/java/org/apache/activemq/artemis/jms/example/TopicSelectorExample2.java +++ b/examples/jms/topic-selector-example2/src/main/java/org/apache/activemq/artemis/jms/example/TopicSelectorExample2.java @@ -32,23 +32,21 @@ import java.util.concurrent.atomic.AtomicBoolean; /** * A simple JMS example that consumes messages using selectors. */ -public class TopicSelectorExample2 -{ - public static void main(final String[] args) throws Exception - { +public class TopicSelectorExample2 { + + public static void main(final String[] args) throws Exception { AtomicBoolean result = new AtomicBoolean(true); Connection connection = null; InitialContext initialContext = null; - try - { + try { // /Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. perform a lookup on the topic - Topic topic = (Topic)initialContext.lookup("topic/exampleTopic"); + Topic topic = (Topic) initialContext.lookup("topic/exampleTopic"); // Step 3. perform a lookup on the Connection Factory - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4. Create a JMS Connection connection = cf.createConnection(); @@ -102,52 +100,44 @@ public class TopicSelectorExample2 if (!result.get()) throw new IllegalStateException(); } - finally - { + finally { // Step 14. Be sure to close our JMS resources! - if (connection != null) - { + if (connection != null) { connection.close(); } // Also the initialContext - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } } } } -class SimpleMessageListener implements MessageListener -{ +class SimpleMessageListener implements MessageListener { + private final String name; AtomicBoolean result; - public SimpleMessageListener(final String listener, AtomicBoolean result) - { + public SimpleMessageListener(final String listener, AtomicBoolean result) { name = listener; this.result = result; } - public void onMessage(final Message msg) - { - TextMessage textMessage = (TextMessage)msg; - try - { + public void onMessage(final Message msg) { + TextMessage textMessage = (TextMessage) msg; + try { String colorProp = msg.getStringProperty("color"); System.out.println("Receiver " + name + - " receives message [" + - textMessage.getText() + - "] with color property: " + - colorProp); - if (!colorProp.equals(name) && !name.equals("all")) - { + " receives message [" + + textMessage.getText() + + "] with color property: " + + colorProp); + if (!colorProp.equals(name) && !name.equals("all")) { result.set(false); } } - catch (JMSException e) - { + catch (JMSException e) { e.printStackTrace(); result.set(false); } diff --git a/examples/jms/topic/src/main/java/org/apache/activemq/artemis/jms/example/TopicExample.java b/examples/jms/topic/src/main/java/org/apache/activemq/artemis/jms/example/TopicExample.java index 08ca057b8e..1c8695b813 100644 --- a/examples/jms/topic/src/main/java/org/apache/activemq/artemis/jms/example/TopicExample.java +++ b/examples/jms/topic/src/main/java/org/apache/activemq/artemis/jms/example/TopicExample.java @@ -28,22 +28,20 @@ import javax.naming.InitialContext; /** * A simple JMS Topic example that creates a producer and consumer on a queue and sends and receives a message. */ -public class TopicExample -{ - public static void main(final String[] args) throws Exception - { +public class TopicExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext initialContext = null; - try - { + try { // /Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. perform a lookup on the topic - Topic topic = (Topic)initialContext.lookup("topic/exampleTopic"); + Topic topic = (Topic) initialContext.lookup("topic/exampleTopic"); // Step 3. perform a lookup on the Connection Factory - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4. Create a JMS Connection connection = cf.createConnection(); @@ -72,26 +70,23 @@ public class TopicExample connection.start(); // Step 12. Receive the message - TextMessage messageReceived = (TextMessage)messageConsumer1.receive(); + TextMessage messageReceived = (TextMessage) messageConsumer1.receive(); System.out.println("Consumer 1 Received message: " + messageReceived.getText()); // Step 13. Receive the message - messageReceived = (TextMessage)messageConsumer2.receive(); + messageReceived = (TextMessage) messageConsumer2.receive(); System.out.println("Consumer 2 Received message: " + messageReceived.getText()); } - finally - { + finally { // Step 14. Be sure to close our JMS resources! - if (connection != null) - { + if (connection != null) { connection.close(); } // Also the initialContext - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } } diff --git a/examples/jms/transaction-failover/src/main/java/org/apache/activemq/artemis/jms/example/TransactionFailoverExample.java b/examples/jms/transaction-failover/src/main/java/org/apache/activemq/artemis/jms/example/TransactionFailoverExample.java index 119bdf8f98..58c514a5ea 100644 --- a/examples/jms/transaction-failover/src/main/java/org/apache/activemq/artemis/jms/example/TransactionFailoverExample.java +++ b/examples/jms/transaction-failover/src/main/java/org/apache/activemq/artemis/jms/example/TransactionFailoverExample.java @@ -33,8 +33,8 @@ import javax.naming.InitialContext; * A simple example that demonstrates failover of the JMS connection from one node to another * when the live server crashes using a JMS transacted session. */ -public class TransactionFailoverExample -{ +public class TransactionFailoverExample { + // You need to guarantee uniqueIDs when using duplicate detection // It needs to be unique even after a restart // as these IDs are stored on the journal for control @@ -45,16 +45,14 @@ public class TransactionFailoverExample private static Process server1; - public static void main(final String[] args) throws Exception - { + public static void main(final String[] args) throws Exception { final int numMessages = 10; Connection connection = null; InitialContext initialContext = null; - try - { + try { server0 = ServerUtil.startServer(args[0], TransactionFailoverExample.class.getSimpleName() + "0", 0, 5000); server1 = ServerUtil.startServer(args[1], TransactionFailoverExample.class.getSimpleName() + "1", 1, 5000); @@ -62,8 +60,8 @@ public class TransactionFailoverExample initialContext = new InitialContext(); // Step 2. Look-up the JMS resources from JNDI - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); - ConnectionFactory connectionFactory = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); + ConnectionFactory connectionFactory = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 3. We create a JMS Connection connection = connectionFactory.createConnection(); @@ -84,12 +82,10 @@ public class TransactionFailoverExample sendMessages(session, producer, numMessages, true); // Step 9. As failover occurred during transaction, the session has been marked for rollback only - try - { + try { session.commit(); } - catch (TransactionRolledBackException e) - { + catch (TransactionRolledBackException e) { System.err.println("transaction has been rolled back: " + e.getMessage()); } @@ -102,12 +98,10 @@ public class TransactionFailoverExample // Step 12. We are now transparently reconnected to server #0, the backup server. // We consume the messages sent before the crash of the live server and commit the session. - for (int i = 0; i < numMessages; i++) - { - TextMessage message0 = (TextMessage)consumer.receive(5000); + for (int i = 0; i < numMessages; i++) { + TextMessage message0 = (TextMessage) consumer.receive(5000); - if (message0 == null) - { + if (message0 == null) { throw new IllegalStateException("Example failed - message wasn't received"); } @@ -118,17 +112,14 @@ public class TransactionFailoverExample System.out.println("Other message on the server? " + consumer.receive(5000)); } - finally - { + finally { // Step 13. Be sure to close our resources! - if (connection != null) - { + if (connection != null) { connection.close(); } - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } @@ -138,33 +129,29 @@ public class TransactionFailoverExample } private static void sendMessages(final Session session, - final MessageProducer producer, - final int numMessages, - final boolean killServer) throws Exception - { + final MessageProducer producer, + final int numMessages, + final boolean killServer) throws Exception { // We send half of messages - for (int i = 0; i < numMessages / 2; i++) - { + for (int i = 0; i < numMessages / 2; i++) { TextMessage message = session.createTextMessage("This is text message " + i); - message.setStringProperty(Message.HDR_DUPLICATE_DETECTION_ID.toString(), uniqueID + i); + message.setStringProperty(Message.HDR_DUPLICATE_DETECTION_ID.toString(), uniqueID + i); producer.send(message); System.out.println("Sent message: " + message.getText()); } - if (killServer) - { + if (killServer) { Thread.sleep(5000); ServerUtil.killServer(server0); } // We send the remaining half of messages - for (int i = numMessages / 2; i < numMessages; i++) - { + for (int i = numMessages / 2; i < numMessages; i++) { TextMessage message = session.createTextMessage("This is text message " + i); // We set the duplicate detection header - so the server will ignore the same message diff --git a/examples/jms/transactional/src/main/java/org/apache/activemq/artemis/jms/example/TransactionalExample.java b/examples/jms/transactional/src/main/java/org/apache/activemq/artemis/jms/example/TransactionalExample.java index 794b76f394..09c2a3d052 100644 --- a/examples/jms/transactional/src/main/java/org/apache/activemq/artemis/jms/example/TransactionalExample.java +++ b/examples/jms/transactional/src/main/java/org/apache/activemq/artemis/jms/example/TransactionalExample.java @@ -28,22 +28,20 @@ import javax.naming.InitialContext; /** * A simple JMS example that sends and consume message transactionally. */ -public class TransactionalExample -{ - public static void main(final String[] args) throws Exception - { +public class TransactionalExample { + + public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Look-up the JMS topic - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 3. Look-up the JMS connection factory - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); // Step 4. Create a JMS connection connection = cf.createConnection(); @@ -72,7 +70,7 @@ public class TransactionalExample System.out.println("Sent message: " + message2.getText()); // Step 11. Receive the message, it will return null as the transaction is not committed. - TextMessage receivedMessage = (TextMessage)messageConsumer.receive(5000); + TextMessage receivedMessage = (TextMessage) messageConsumer.receive(5000); System.out.println("Message received before send commit: " + receivedMessage); @@ -80,7 +78,7 @@ public class TransactionalExample session.commit(); // Step 13. Receive the messages again - receivedMessage = (TextMessage)messageConsumer.receive(5000); + receivedMessage = (TextMessage) messageConsumer.receive(5000); System.out.println("Message received after send commit: " + receivedMessage.getText()); @@ -88,15 +86,15 @@ public class TransactionalExample session.rollback(); // Step 15. Receive the message again, we will get two messages - receivedMessage = (TextMessage)messageConsumer.receive(5000); + receivedMessage = (TextMessage) messageConsumer.receive(5000); System.out.println("Message1 received after receive rollback: " + receivedMessage.getText()); - receivedMessage = (TextMessage)messageConsumer.receive(5000); + receivedMessage = (TextMessage) messageConsumer.receive(5000); System.out.println("Message2 received after receive rollback: " + receivedMessage.getText()); - receivedMessage = (TextMessage)messageConsumer.receive(5000); + receivedMessage = (TextMessage) messageConsumer.receive(5000); System.out.println("Message3 received after receive rollback: " + receivedMessage); @@ -104,10 +102,9 @@ public class TransactionalExample session.commit(); // Step 17. Receive the message again. Nothing should be received. - receivedMessage = (TextMessage)messageConsumer.receive(5000); + receivedMessage = (TextMessage) messageConsumer.receive(5000); - if (receivedMessage != null) - { + if (receivedMessage != null) { // This was not supposed to happen throw new IllegalStateException("Message is not null."); } @@ -115,15 +112,12 @@ public class TransactionalExample System.out.println("Message received after receive commit: " + receivedMessage); } - finally - { - if (connection != null) - { + finally { + if (connection != null) { // Step 18. Be sure to close our JMS resources! connection.close(); } - if (initialContext != null) - { + if (initialContext != null) { // Step 19. Also close initial context! initialContext.close(); } diff --git a/examples/jms/xa-heuristic/src/main/java/org/apache/activemq/artemis/jms/example/DummyXid.java b/examples/jms/xa-heuristic/src/main/java/org/apache/activemq/artemis/jms/example/DummyXid.java index 2b8a200528..8b6be805e5 100644 --- a/examples/jms/xa-heuristic/src/main/java/org/apache/activemq/artemis/jms/example/DummyXid.java +++ b/examples/jms/xa-heuristic/src/main/java/org/apache/activemq/artemis/jms/example/DummyXid.java @@ -20,8 +20,8 @@ import javax.transaction.xa.Xid; import org.apache.activemq.artemis.utils.Base64; -public class DummyXid implements Xid -{ +public class DummyXid implements Xid { + private static final long serialVersionUID = 407053232840068514L; private final byte[] branchQualifier; @@ -36,13 +36,11 @@ public class DummyXid implements Xid // Static -------------------------------------------------------- - public static String toBase64String(final Xid xid) - { + public static String toBase64String(final Xid xid) { return Base64.encodeBytes(DummyXid.toByteArray(xid)); } - private static byte[] toByteArray(final Xid xid) - { + private static byte[] toByteArray(final Xid xid) { byte[] branchQualifier = xid.getBranchQualifier(); byte[] globalTransactionId = xid.getGlobalTransactionId(); int formatId = xid.getFormatId(); @@ -51,9 +49,8 @@ public class DummyXid implements Xid System.arraycopy(branchQualifier, 0, hashBytes, 0, branchQualifier.length); System.arraycopy(globalTransactionId, 0, hashBytes, branchQualifier.length, globalTransactionId.length); byte[] intBytes = new byte[4]; - for (int i = 0; i < 4; i++) - { - intBytes[i] = (byte)((formatId >> i * 8) % 0xFF); + for (int i = 0; i < 4; i++) { + intBytes[i] = (byte) ((formatId >> i * 8) % 0xFF); } System.arraycopy(intBytes, 0, hashBytes, branchQualifier.length + globalTransactionId.length, 4); return hashBytes; @@ -63,12 +60,12 @@ public class DummyXid implements Xid /** * Standard constructor + * * @param branchQualifier * @param formatId * @param globalTransactionId */ - public DummyXid(final byte[] branchQualifier, final int formatId, final byte[] globalTransactionId) - { + public DummyXid(final byte[] branchQualifier, final int formatId, final byte[] globalTransactionId) { this.branchQualifier = branchQualifier; this.formatId = formatId; this.globalTransactionId = globalTransactionId; @@ -76,10 +73,10 @@ public class DummyXid implements Xid /** * Copy constructor + * * @param other */ - public DummyXid(final Xid other) - { + public DummyXid(final Xid other) { branchQualifier = copyBytes(other.getBranchQualifier()); formatId = other.getFormatId(); globalTransactionId = copyBytes(other.getGlobalTransactionId()); @@ -87,70 +84,55 @@ public class DummyXid implements Xid // Xid implementation ------------------------------------------------------------------ - public byte[] getBranchQualifier() - { + public byte[] getBranchQualifier() { return branchQualifier; } - public int getFormatId() - { + public int getFormatId() { return formatId; } - public byte[] getGlobalTransactionId() - { + public byte[] getGlobalTransactionId() { return globalTransactionId; } // Public ------------------------------------------------------------------------------- @Override - public int hashCode() - { - if (!hashCalculated) - { + public int hashCode() { + if (!hashCalculated) { calcHash(); } return hash; } @Override - public boolean equals(final Object other) - { - if (this == other) - { + public boolean equals(final Object other) { + if (this == other) { return true; } - if (!(other instanceof Xid)) - { + if (!(other instanceof Xid)) { return false; } - Xid xother = (Xid)other; - if (xother.getFormatId() != formatId) - { + Xid xother = (Xid) other; + if (xother.getFormatId() != formatId) { return false; } - if (xother.getBranchQualifier().length != branchQualifier.length) - { + if (xother.getBranchQualifier().length != branchQualifier.length) { return false; } - if (xother.getGlobalTransactionId().length != globalTransactionId.length) - { + if (xother.getGlobalTransactionId().length != globalTransactionId.length) { return false; } - for (int i = 0; i < branchQualifier.length; i++) - { + for (int i = 0; i < branchQualifier.length; i++) { byte[] otherBQ = xother.getBranchQualifier(); - if (branchQualifier[i] != otherBQ[i]) - { + if (branchQualifier[i] != otherBQ[i]) { return false; } } - for (int i = 0; i < globalTransactionId.length; i++) - { + for (int i = 0; i < globalTransactionId.length; i++) { byte[] otherGtx = xother.getGlobalTransactionId(); - if (globalTransactionId[i] != otherGtx[i]) - { + if (globalTransactionId[i] != otherGtx[i]) { return false; } } @@ -158,30 +140,26 @@ public class DummyXid implements Xid } @Override - public String toString() - { + public String toString() { return "XidImpl (" + System.identityHashCode(this) + - " bq:" + - stringRep(branchQualifier) + - " formatID:" + - formatId + - " gtxid:" + - stringRep(globalTransactionId); + " bq:" + + stringRep(branchQualifier) + + " formatID:" + + formatId + + " gtxid:" + + stringRep(globalTransactionId); } // Private ------------------------------------------------------------------------------- - private String stringRep(final byte[] bytes) - { + private String stringRep(final byte[] bytes) { StringBuilder buff = new StringBuilder(); - for (int i = 0; i < bytes.length; i++) - { + for (int i = 0; i < bytes.length; i++) { byte b = bytes[i]; buff.append(b); - if (i != bytes.length - 1) - { + if (i != bytes.length - 1) { buff.append('.'); } } @@ -189,16 +167,14 @@ public class DummyXid implements Xid return buff.toString(); } - private void calcHash() - { + private void calcHash() { byte[] hashBytes = org.apache.activemq.artemis.jms.example.DummyXid.toByteArray(this); String s = new String(hashBytes); hash = s.hashCode(); hashCalculated = true; } - private byte[] copyBytes(final byte[] other) - { + private byte[] copyBytes(final byte[] other) { byte[] bytes = new byte[other.length]; System.arraycopy(other, 0, bytes, 0, other.length); diff --git a/examples/jms/xa-heuristic/src/main/java/org/apache/activemq/artemis/jms/example/XAHeuristicExample.java b/examples/jms/xa-heuristic/src/main/java/org/apache/activemq/artemis/jms/example/XAHeuristicExample.java index 4da5c83329..d2337311dd 100644 --- a/examples/jms/xa-heuristic/src/main/java/org/apache/activemq/artemis/jms/example/XAHeuristicExample.java +++ b/examples/jms/xa-heuristic/src/main/java/org/apache/activemq/artemis/jms/example/XAHeuristicExample.java @@ -45,26 +45,24 @@ import org.apache.activemq.artemis.utils.UUIDGenerator; /** * A simple JMS example showing how to administer un-finished transactions. */ -public class XAHeuristicExample -{ +public class XAHeuristicExample { + private static final String JMX_URL = "service:jmx:rmi:///jndi/rmi://localhost:3001/jmxrmi"; - public static void main(final String[] args) throws Exception - { + public static void main(final String[] args) throws Exception { Boolean result = true; final ArrayList receiveHolder = new ArrayList(); XAConnection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Lookup on the queue - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 3. Perform a lookup on the XA Connection Factory - XAConnectionFactory cf = (XAConnectionFactory)initialContext.lookup("XAConnectionFactory"); + XAConnectionFactory cf = (XAConnectionFactory) initialContext.lookup("XAConnectionFactory"); // Step 4.Create a JMS XAConnection connection = cf.createXAConnection(); @@ -93,9 +91,7 @@ public class XAHeuristicExample TextMessage worldMessage = session.createTextMessage("world"); // Step 12. create a transaction - Xid xid1 = new DummyXid("xa-example1".getBytes(StandardCharsets.ISO_8859_1), 1, UUIDGenerator.getInstance() - .generateStringUUID() - .getBytes()); + Xid xid1 = new DummyXid("xa-example1".getBytes(StandardCharsets.ISO_8859_1), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); // Step 13. Get the JMS XAResource XAResource xaRes = xaSession.getXAResource(); @@ -118,9 +114,7 @@ public class XAHeuristicExample checkNoMessageReceived(receiveHolder); // Step 19. Create another transaction. - Xid xid2 = new DummyXid("xa-example2".getBytes(), 1, UUIDGenerator.getInstance() - .generateStringUUID() - .getBytes()); + Xid xid2 = new DummyXid("xa-example2".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); // Step 20. Begin the transaction work xaRes.start(xid2, XAResource.TMNOFLAGS); @@ -147,25 +141,18 @@ public class XAHeuristicExample // Step 27. List the prepared transactions ObjectName serverObject = ObjectNameBuilder.DEFAULT.getActiveMQServerObjectName(); - String[] infos = (String[])mbsc.invoke(serverObject, "listPreparedTransactions", null, null); + String[] infos = (String[]) mbsc.invoke(serverObject, "listPreparedTransactions", null, null); System.out.println("Prepared transactions: "); - for (String i : infos) - { + for (String i : infos) { System.out.println(i); } // Step 28. Roll back the first transaction - mbsc.invoke(serverObject, - "rollbackPreparedTransaction", - new String[] { DummyXid.toBase64String(xid1) }, - new String[] { "java.lang.String" }); + mbsc.invoke(serverObject, "rollbackPreparedTransaction", new String[]{DummyXid.toBase64String(xid1)}, new String[]{"java.lang.String"}); // Step 29. Commit the second one - mbsc.invoke(serverObject, - "commitPreparedTransaction", - new String[] { DummyXid.toBase64String(xid2) }, - new String[] { "java.lang.String" }); + mbsc.invoke(serverObject, "commitPreparedTransaction", new String[]{DummyXid.toBase64String(xid2)}, new String[]{"java.lang.String"}); Thread.sleep(2000); @@ -173,70 +160,58 @@ public class XAHeuristicExample checkMessageReceived("world", receiveHolder); // Step 31. Check the prepared transaction again, should have none. - infos = (String[])mbsc.invoke(serverObject, "listPreparedTransactions", null, null); + infos = (String[]) mbsc.invoke(serverObject, "listPreparedTransactions", null, null); System.out.println("No. of prepared transactions now: " + infos.length); // Step 32. Close the JMX Connector connector.close(); } - finally - { + finally { // Step 32. Be sure to close our JMS resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } } - private static void checkMessageReceived(final String value, ArrayList receiveHolder) - { - if (receiveHolder.size() != 1) - { + private static void checkMessageReceived(final String value, ArrayList receiveHolder) { + if (receiveHolder.size() != 1) { throw new IllegalStateException("Number of messages received not correct ! -- " + receiveHolder.size()); } String msg = receiveHolder.get(0); - if (!msg.equals(value)) - { + if (!msg.equals(value)) { throw new IllegalStateException("Received message [" + msg + "], but we expect [" + value + "]"); } receiveHolder.clear(); } - private static void checkNoMessageReceived(ArrayList receiveHolder) - { - if (receiveHolder.size() > 0) - { + private static void checkNoMessageReceived(ArrayList receiveHolder) { + if (receiveHolder.size() > 0) { throw new IllegalStateException("Message received, wrong!"); } receiveHolder.clear(); } } -class SimpleMessageListener implements MessageListener -{ +class SimpleMessageListener implements MessageListener { + ArrayList receiveHolder; Boolean result; - SimpleMessageListener(ArrayList receiveHolder, Boolean result) - { + SimpleMessageListener(ArrayList receiveHolder, Boolean result) { this.receiveHolder = receiveHolder; this.result = result; } - public void onMessage(final Message message) - { - try - { - System.out.println("Message received: " + ((TextMessage)message).getText()); - receiveHolder.add(((TextMessage)message).getText()); + public void onMessage(final Message message) { + try { + System.out.println("Message received: " + ((TextMessage) message).getText()); + receiveHolder.add(((TextMessage) message).getText()); } - catch (JMSException e) - { + catch (JMSException e) { result = false; e.printStackTrace(); } diff --git a/examples/jms/xa-receive/src/main/java/org/apache/activemq/artemis/jms/example/DummyXid.java b/examples/jms/xa-receive/src/main/java/org/apache/activemq/artemis/jms/example/DummyXid.java index c8bf9cc834..4dbe2f8ae4 100644 --- a/examples/jms/xa-receive/src/main/java/org/apache/activemq/artemis/jms/example/DummyXid.java +++ b/examples/jms/xa-receive/src/main/java/org/apache/activemq/artemis/jms/example/DummyXid.java @@ -20,8 +20,8 @@ import org.apache.activemq.artemis.utils.Base64; import javax.transaction.xa.Xid; -public class DummyXid implements Xid -{ +public class DummyXid implements Xid { + private static final long serialVersionUID = 407053232840068514L; private final byte[] branchQualifier; @@ -36,13 +36,11 @@ public class DummyXid implements Xid // Static -------------------------------------------------------- - public static String toBase64String(final Xid xid) - { + public static String toBase64String(final Xid xid) { return Base64.encodeBytes(DummyXid.toByteArray(xid)); } - private static byte[] toByteArray(final Xid xid) - { + private static byte[] toByteArray(final Xid xid) { byte[] branchQualifier = xid.getBranchQualifier(); byte[] globalTransactionId = xid.getGlobalTransactionId(); int formatId = xid.getFormatId(); @@ -51,9 +49,8 @@ public class DummyXid implements Xid System.arraycopy(branchQualifier, 0, hashBytes, 0, branchQualifier.length); System.arraycopy(globalTransactionId, 0, hashBytes, branchQualifier.length, globalTransactionId.length); byte[] intBytes = new byte[4]; - for (int i = 0; i < 4; i++) - { - intBytes[i] = (byte)((formatId >> i * 8) % 0xFF); + for (int i = 0; i < 4; i++) { + intBytes[i] = (byte) ((formatId >> i * 8) % 0xFF); } System.arraycopy(intBytes, 0, hashBytes, branchQualifier.length + globalTransactionId.length, 4); return hashBytes; @@ -63,12 +60,12 @@ public class DummyXid implements Xid /** * Standard constructor + * * @param branchQualifier * @param formatId * @param globalTransactionId */ - public DummyXid(final byte[] branchQualifier, final int formatId, final byte[] globalTransactionId) - { + public DummyXid(final byte[] branchQualifier, final int formatId, final byte[] globalTransactionId) { this.branchQualifier = branchQualifier; this.formatId = formatId; this.globalTransactionId = globalTransactionId; @@ -76,10 +73,10 @@ public class DummyXid implements Xid /** * Copy constructor + * * @param other */ - public DummyXid(final Xid other) - { + public DummyXid(final Xid other) { branchQualifier = copyBytes(other.getBranchQualifier()); formatId = other.getFormatId(); globalTransactionId = copyBytes(other.getGlobalTransactionId()); @@ -87,70 +84,55 @@ public class DummyXid implements Xid // Xid implementation ------------------------------------------------------------------ - public byte[] getBranchQualifier() - { + public byte[] getBranchQualifier() { return branchQualifier; } - public int getFormatId() - { + public int getFormatId() { return formatId; } - public byte[] getGlobalTransactionId() - { + public byte[] getGlobalTransactionId() { return globalTransactionId; } // Public ------------------------------------------------------------------------------- @Override - public int hashCode() - { - if (!hashCalculated) - { + public int hashCode() { + if (!hashCalculated) { calcHash(); } return hash; } @Override - public boolean equals(final Object other) - { - if (this == other) - { + public boolean equals(final Object other) { + if (this == other) { return true; } - if (!(other instanceof Xid)) - { + if (!(other instanceof Xid)) { return false; } - Xid xother = (Xid)other; - if (xother.getFormatId() != formatId) - { + Xid xother = (Xid) other; + if (xother.getFormatId() != formatId) { return false; } - if (xother.getBranchQualifier().length != branchQualifier.length) - { + if (xother.getBranchQualifier().length != branchQualifier.length) { return false; } - if (xother.getGlobalTransactionId().length != globalTransactionId.length) - { + if (xother.getGlobalTransactionId().length != globalTransactionId.length) { return false; } - for (int i = 0; i < branchQualifier.length; i++) - { + for (int i = 0; i < branchQualifier.length; i++) { byte[] otherBQ = xother.getBranchQualifier(); - if (branchQualifier[i] != otherBQ[i]) - { + if (branchQualifier[i] != otherBQ[i]) { return false; } } - for (int i = 0; i < globalTransactionId.length; i++) - { + for (int i = 0; i < globalTransactionId.length; i++) { byte[] otherGtx = xother.getGlobalTransactionId(); - if (globalTransactionId[i] != otherGtx[i]) - { + if (globalTransactionId[i] != otherGtx[i]) { return false; } } @@ -158,30 +140,26 @@ public class DummyXid implements Xid } @Override - public String toString() - { + public String toString() { return "XidImpl (" + System.identityHashCode(this) + - " bq:" + - stringRep(branchQualifier) + - " formatID:" + - formatId + - " gtxid:" + - stringRep(globalTransactionId); + " bq:" + + stringRep(branchQualifier) + + " formatID:" + + formatId + + " gtxid:" + + stringRep(globalTransactionId); } // Private ------------------------------------------------------------------------------- - private String stringRep(final byte[] bytes) - { + private String stringRep(final byte[] bytes) { StringBuilder buff = new StringBuilder(); - for (int i = 0; i < bytes.length; i++) - { + for (int i = 0; i < bytes.length; i++) { byte b = bytes[i]; buff.append(b); - if (i != bytes.length - 1) - { + if (i != bytes.length - 1) { buff.append('.'); } } @@ -189,16 +167,14 @@ public class DummyXid implements Xid return buff.toString(); } - private void calcHash() - { + private void calcHash() { byte[] hashBytes = DummyXid.toByteArray(this); String s = new String(hashBytes); hash = s.hashCode(); hashCalculated = true; } - private byte[] copyBytes(final byte[] other) - { + private byte[] copyBytes(final byte[] other) { byte[] bytes = new byte[other.length]; System.arraycopy(other, 0, bytes, 0, other.length); diff --git a/examples/jms/xa-receive/src/main/java/org/apache/activemq/artemis/jms/example/XAReceiveExample.java b/examples/jms/xa-receive/src/main/java/org/apache/activemq/artemis/jms/example/XAReceiveExample.java index 6562cea5ca..4c4448dd5b 100644 --- a/examples/jms/xa-receive/src/main/java/org/apache/activemq/artemis/jms/example/XAReceiveExample.java +++ b/examples/jms/xa-receive/src/main/java/org/apache/activemq/artemis/jms/example/XAReceiveExample.java @@ -34,22 +34,20 @@ import org.apache.activemq.artemis.utils.UUIDGenerator; /** * A simple JMS example showing the usage of XA support in JMS. */ -public class XAReceiveExample -{ - public static void main(final String[] args) throws Exception - { +public class XAReceiveExample { + + public static void main(final String[] args) throws Exception { XAConnection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Lookup on the queue - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 3. Perform a lookup on the XA Connection Factory - XAConnectionFactory cf = (XAConnectionFactory)initialContext.lookup("XAConnectionFactory"); + XAConnectionFactory cf = (XAConnectionFactory) initialContext.lookup("XAConnectionFactory"); // Step 4.Create a JMS XAConnection connection = cf.createXAConnection(); @@ -77,9 +75,7 @@ public class XAReceiveExample TextMessage worldMessage = session.createTextMessage("world"); // Step 12. create a transaction - Xid xid1 = new DummyXid("xa-example1".getBytes(StandardCharsets.US_ASCII), 1, UUIDGenerator.getInstance() - .generateStringUUID() - .getBytes()); + Xid xid1 = new DummyXid("xa-example1".getBytes(StandardCharsets.US_ASCII), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); // Step 13. Get the JMS XAResource XAResource xaRes = xaSession.getXAResource(); @@ -92,9 +88,9 @@ public class XAReceiveExample normalProducer.send(worldMessage); // Step 16. Receive the message - TextMessage rm1 = (TextMessage)xaConsumer.receive(); + TextMessage rm1 = (TextMessage) xaConsumer.receive(); System.out.println("Message received: " + rm1.getText()); - TextMessage rm2 = (TextMessage)xaConsumer.receive(); + TextMessage rm2 = (TextMessage) xaConsumer.receive(); System.out.println("Message received: " + rm2.getText()); // Step 17. Stop the work @@ -107,17 +103,15 @@ public class XAReceiveExample xaRes.rollback(xid1); // Step 20. Create another transaction - Xid xid2 = new DummyXid("xa-example2".getBytes(), 1, UUIDGenerator.getInstance() - .generateStringUUID() - .getBytes()); + Xid xid2 = new DummyXid("xa-example2".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); // Step 21. Start the transaction xaRes.start(xid2, XAResource.TMNOFLAGS); // Step 22. receive those messages again - rm1 = (TextMessage)xaConsumer.receive(); + rm1 = (TextMessage) xaConsumer.receive(); System.out.println("Message received again: " + rm1.getText()); - rm2 = (TextMessage)xaConsumer.receive(); + rm2 = (TextMessage) xaConsumer.receive(); System.out.println("Message received again: " + rm2.getText()); // Step 23. Stop the work @@ -130,25 +124,20 @@ public class XAReceiveExample xaRes.commit(xid2, false); // Step 26. Check no more messages are received. - TextMessage rm3 = (TextMessage)xaConsumer.receive(2000); - if (rm3 == null) - { + TextMessage rm3 = (TextMessage) xaConsumer.receive(2000); + if (rm3 == null) { System.out.println("No message received after commit."); } - else - { + else { throw new IllegalStateException(); } } - finally - { + finally { // Step 27. Be sure to close our JMS resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } diff --git a/examples/jms/xa-send/src/main/java/org/apache/activemq/artemis/jms/example/DummyXid.java b/examples/jms/xa-send/src/main/java/org/apache/activemq/artemis/jms/example/DummyXid.java index c8bf9cc834..4dbe2f8ae4 100644 --- a/examples/jms/xa-send/src/main/java/org/apache/activemq/artemis/jms/example/DummyXid.java +++ b/examples/jms/xa-send/src/main/java/org/apache/activemq/artemis/jms/example/DummyXid.java @@ -20,8 +20,8 @@ import org.apache.activemq.artemis.utils.Base64; import javax.transaction.xa.Xid; -public class DummyXid implements Xid -{ +public class DummyXid implements Xid { + private static final long serialVersionUID = 407053232840068514L; private final byte[] branchQualifier; @@ -36,13 +36,11 @@ public class DummyXid implements Xid // Static -------------------------------------------------------- - public static String toBase64String(final Xid xid) - { + public static String toBase64String(final Xid xid) { return Base64.encodeBytes(DummyXid.toByteArray(xid)); } - private static byte[] toByteArray(final Xid xid) - { + private static byte[] toByteArray(final Xid xid) { byte[] branchQualifier = xid.getBranchQualifier(); byte[] globalTransactionId = xid.getGlobalTransactionId(); int formatId = xid.getFormatId(); @@ -51,9 +49,8 @@ public class DummyXid implements Xid System.arraycopy(branchQualifier, 0, hashBytes, 0, branchQualifier.length); System.arraycopy(globalTransactionId, 0, hashBytes, branchQualifier.length, globalTransactionId.length); byte[] intBytes = new byte[4]; - for (int i = 0; i < 4; i++) - { - intBytes[i] = (byte)((formatId >> i * 8) % 0xFF); + for (int i = 0; i < 4; i++) { + intBytes[i] = (byte) ((formatId >> i * 8) % 0xFF); } System.arraycopy(intBytes, 0, hashBytes, branchQualifier.length + globalTransactionId.length, 4); return hashBytes; @@ -63,12 +60,12 @@ public class DummyXid implements Xid /** * Standard constructor + * * @param branchQualifier * @param formatId * @param globalTransactionId */ - public DummyXid(final byte[] branchQualifier, final int formatId, final byte[] globalTransactionId) - { + public DummyXid(final byte[] branchQualifier, final int formatId, final byte[] globalTransactionId) { this.branchQualifier = branchQualifier; this.formatId = formatId; this.globalTransactionId = globalTransactionId; @@ -76,10 +73,10 @@ public class DummyXid implements Xid /** * Copy constructor + * * @param other */ - public DummyXid(final Xid other) - { + public DummyXid(final Xid other) { branchQualifier = copyBytes(other.getBranchQualifier()); formatId = other.getFormatId(); globalTransactionId = copyBytes(other.getGlobalTransactionId()); @@ -87,70 +84,55 @@ public class DummyXid implements Xid // Xid implementation ------------------------------------------------------------------ - public byte[] getBranchQualifier() - { + public byte[] getBranchQualifier() { return branchQualifier; } - public int getFormatId() - { + public int getFormatId() { return formatId; } - public byte[] getGlobalTransactionId() - { + public byte[] getGlobalTransactionId() { return globalTransactionId; } // Public ------------------------------------------------------------------------------- @Override - public int hashCode() - { - if (!hashCalculated) - { + public int hashCode() { + if (!hashCalculated) { calcHash(); } return hash; } @Override - public boolean equals(final Object other) - { - if (this == other) - { + public boolean equals(final Object other) { + if (this == other) { return true; } - if (!(other instanceof Xid)) - { + if (!(other instanceof Xid)) { return false; } - Xid xother = (Xid)other; - if (xother.getFormatId() != formatId) - { + Xid xother = (Xid) other; + if (xother.getFormatId() != formatId) { return false; } - if (xother.getBranchQualifier().length != branchQualifier.length) - { + if (xother.getBranchQualifier().length != branchQualifier.length) { return false; } - if (xother.getGlobalTransactionId().length != globalTransactionId.length) - { + if (xother.getGlobalTransactionId().length != globalTransactionId.length) { return false; } - for (int i = 0; i < branchQualifier.length; i++) - { + for (int i = 0; i < branchQualifier.length; i++) { byte[] otherBQ = xother.getBranchQualifier(); - if (branchQualifier[i] != otherBQ[i]) - { + if (branchQualifier[i] != otherBQ[i]) { return false; } } - for (int i = 0; i < globalTransactionId.length; i++) - { + for (int i = 0; i < globalTransactionId.length; i++) { byte[] otherGtx = xother.getGlobalTransactionId(); - if (globalTransactionId[i] != otherGtx[i]) - { + if (globalTransactionId[i] != otherGtx[i]) { return false; } } @@ -158,30 +140,26 @@ public class DummyXid implements Xid } @Override - public String toString() - { + public String toString() { return "XidImpl (" + System.identityHashCode(this) + - " bq:" + - stringRep(branchQualifier) + - " formatID:" + - formatId + - " gtxid:" + - stringRep(globalTransactionId); + " bq:" + + stringRep(branchQualifier) + + " formatID:" + + formatId + + " gtxid:" + + stringRep(globalTransactionId); } // Private ------------------------------------------------------------------------------- - private String stringRep(final byte[] bytes) - { + private String stringRep(final byte[] bytes) { StringBuilder buff = new StringBuilder(); - for (int i = 0; i < bytes.length; i++) - { + for (int i = 0; i < bytes.length; i++) { byte b = bytes[i]; buff.append(b); - if (i != bytes.length - 1) - { + if (i != bytes.length - 1) { buff.append('.'); } } @@ -189,16 +167,14 @@ public class DummyXid implements Xid return buff.toString(); } - private void calcHash() - { + private void calcHash() { byte[] hashBytes = DummyXid.toByteArray(this); String s = new String(hashBytes); hash = s.hashCode(); hashCalculated = true; } - private byte[] copyBytes(final byte[] other) - { + private byte[] copyBytes(final byte[] other) { byte[] bytes = new byte[other.length]; System.arraycopy(other, 0, bytes, 0, other.length); diff --git a/examples/jms/xa-send/src/main/java/org/apache/activemq/artemis/jms/example/XASendExample.java b/examples/jms/xa-send/src/main/java/org/apache/activemq/artemis/jms/example/XASendExample.java index 43d6c21193..fd87f61788 100644 --- a/examples/jms/xa-send/src/main/java/org/apache/activemq/artemis/jms/example/XASendExample.java +++ b/examples/jms/xa-send/src/main/java/org/apache/activemq/artemis/jms/example/XASendExample.java @@ -39,24 +39,22 @@ import org.apache.activemq.artemis.utils.UUIDGenerator; /** * A simple JMS example showing the usage of XA support in JMS. */ -public class XASendExample -{ - public static void main(final String[] args) throws Exception - { +public class XASendExample { + + public static void main(final String[] args) throws Exception { AtomicBoolean result = new AtomicBoolean(true); final ArrayList receiveHolder = new ArrayList(); XAConnection connection = null; InitialContext initialContext = null; - try - { + try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = new InitialContext(); // Step 2. Lookup on the queue - Queue queue = (Queue)initialContext.lookup("queue/exampleQueue"); + Queue queue = (Queue) initialContext.lookup("queue/exampleQueue"); // Step 3. Perform a lookup on the XA Connection Factory - XAConnectionFactory cf = (XAConnectionFactory)initialContext.lookup("XAConnectionFactory"); + XAConnectionFactory cf = (XAConnectionFactory) initialContext.lookup("XAConnectionFactory"); // Step 4.Create a JMS XAConnection connection = cf.createXAConnection(); @@ -85,9 +83,7 @@ public class XASendExample TextMessage worldMessage = session.createTextMessage("world"); // Step 12. create a transaction - Xid xid1 = new DummyXid("xa-example1".getBytes(StandardCharsets.UTF_8), 1, UUIDGenerator.getInstance() - .generateStringUUID() - .getBytes()); + Xid xid1 = new DummyXid("xa-example1".getBytes(StandardCharsets.UTF_8), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); // Step 13. Get the JMS XAResource XAResource xaRes = xaSession.getXAResource(); @@ -117,9 +113,7 @@ public class XASendExample checkNoMessageReceived(receiveHolder); // Step 21. Create another transaction - Xid xid2 = new DummyXid("xa-example2".getBytes(), 1, UUIDGenerator.getInstance() - .generateStringUUID() - .getBytes()); + Xid xid2 = new DummyXid("xa-example2".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); // Step 22. Start the transaction xaRes.start(xid2, XAResource.TMNOFLAGS); @@ -148,59 +142,48 @@ public class XASendExample if (!result.get()) throw new IllegalStateException(); } - finally - { + finally { // Step 29. Be sure to close our JMS resources! - if (initialContext != null) - { + if (initialContext != null) { initialContext.close(); } - if (connection != null) - { + if (connection != null) { connection.close(); } } } - private static void checkAllMessageReceived(ArrayList receiveHolder) - { - if (receiveHolder.size() != 2) - { + private static void checkAllMessageReceived(ArrayList receiveHolder) { + if (receiveHolder.size() != 2) { throw new IllegalStateException("Number of messages received not correct ! -- " + receiveHolder.size()); } receiveHolder.clear(); } - private static void checkNoMessageReceived(ArrayList receiveHolder) - { - if (receiveHolder.size() > 0) - { + private static void checkNoMessageReceived(ArrayList receiveHolder) { + if (receiveHolder.size() > 0) { throw new IllegalStateException("Message received, wrong!"); } receiveHolder.clear(); } } -class SimpleMessageListener implements MessageListener -{ +class SimpleMessageListener implements MessageListener { + ArrayList receiveHolder; AtomicBoolean result; - public SimpleMessageListener(ArrayList receiveHolder, AtomicBoolean result) - { + public SimpleMessageListener(ArrayList receiveHolder, AtomicBoolean result) { this.receiveHolder = receiveHolder; this.result = result; } - public void onMessage(final Message message) - { - try - { + public void onMessage(final Message message) { + try { System.out.println("Message received: " + message); - receiveHolder.add(((TextMessage)message).getText()); + receiveHolder.add(((TextMessage) message).getText()); } - catch (JMSException e) - { + catch (JMSException e) { result.set(false); e.printStackTrace(); } diff --git a/examples/soak/normal/src/main/java/org/apache/activemq/artemis/jms/soak/example/SoakBase.java b/examples/soak/normal/src/main/java/org/apache/activemq/artemis/jms/soak/example/SoakBase.java index fb8d028a42..ce5b9bc3c8 100644 --- a/examples/soak/normal/src/main/java/org/apache/activemq/artemis/jms/soak/example/SoakBase.java +++ b/examples/soak/normal/src/main/java/org/apache/activemq/artemis/jms/soak/example/SoakBase.java @@ -22,56 +22,48 @@ import java.util.Properties; import java.util.Random; import java.util.logging.Logger; -public class SoakBase -{ +public class SoakBase { + private static final Logger log = Logger.getLogger(SoakBase.class.getName()); private static final String DEFAULT_SOAK_PROPERTIES_FILE_NAME = "soak.properties"; public static final int TO_MILLIS = 60 * 1000; // from minute to milliseconds - public static byte[] randomByteArray(final int length) - { + public static byte[] randomByteArray(final int length) { byte[] bytes = new byte[length]; Random random = new Random(); - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { bytes[i] = Integer.valueOf(random.nextInt()).byteValue(); } return bytes; } - protected static String getPerfFileName() - { + protected static String getPerfFileName() { String fileName = System.getProperty("soak.props"); - if (fileName == null) - { + if (fileName == null) { fileName = SoakBase.DEFAULT_SOAK_PROPERTIES_FILE_NAME; } return fileName; } - protected static SoakParams getParams(final String fileName) throws Exception - { + protected static SoakParams getParams(final String fileName) throws Exception { Properties props = null; InputStream is = null; - try - { + try { is = new FileInputStream(fileName); props = new Properties(); props.load(is); } - finally - { - if (is != null) - { + finally { + if (is != null) { is.close(); } } diff --git a/examples/soak/normal/src/main/java/org/apache/activemq/artemis/jms/soak/example/SoakParams.java b/examples/soak/normal/src/main/java/org/apache/activemq/artemis/jms/soak/example/SoakParams.java index fb87a5faea..dda2ac196c 100644 --- a/examples/soak/normal/src/main/java/org/apache/activemq/artemis/jms/soak/example/SoakParams.java +++ b/examples/soak/normal/src/main/java/org/apache/activemq/artemis/jms/soak/example/SoakParams.java @@ -19,11 +19,10 @@ package org.apache.activemq.artemis.jms.soak.example; import java.io.Serializable; /** - * * Class that holds the parameters used in the performance examples */ -public class SoakParams implements Serializable -{ +public class SoakParams implements Serializable { + private static final long serialVersionUID = -4336539641012356002L; private int durationInMinutes = 60; @@ -52,133 +51,107 @@ public class SoakParams implements Serializable private boolean dupsOK; - public synchronized int getDurationInMinutes() - { + public synchronized int getDurationInMinutes() { return durationInMinutes; } - public synchronized void setDurationInMinutes(final int durationInMinutes) - { + public synchronized void setDurationInMinutes(final int durationInMinutes) { this.durationInMinutes = durationInMinutes; } - public synchronized int getNoOfWarmupMessages() - { + public synchronized int getNoOfWarmupMessages() { return noOfWarmupMessages; } - public synchronized void setNoOfWarmupMessages(final int noOfWarmupMessages) - { + public synchronized void setNoOfWarmupMessages(final int noOfWarmupMessages) { this.noOfWarmupMessages = noOfWarmupMessages; } - public synchronized int getMessageSize() - { + public synchronized int getMessageSize() { return messageSize; } - public synchronized void setMessageSize(final int messageSize) - { + public synchronized void setMessageSize(final int messageSize) { this.messageSize = messageSize; } - public synchronized boolean isDurable() - { + public synchronized boolean isDurable() { return durable; } - public synchronized void setDurable(final boolean durable) - { + public synchronized void setDurable(final boolean durable) { this.durable = durable; } - public synchronized boolean isSessionTransacted() - { + public synchronized boolean isSessionTransacted() { return isSessionTransacted; } - public synchronized void setSessionTransacted(final boolean isSessionTransacted) - { + public synchronized void setSessionTransacted(final boolean isSessionTransacted) { this.isSessionTransacted = isSessionTransacted; } - public synchronized int getBatchSize() - { + public synchronized int getBatchSize() { return batchSize; } - public synchronized void setBatchSize(final int batchSize) - { + public synchronized void setBatchSize(final int batchSize) { this.batchSize = batchSize; } - public synchronized boolean isDrainQueue() - { + public synchronized boolean isDrainQueue() { return drainQueue; } - public synchronized void setDrainQueue(final boolean drainQueue) - { + public synchronized void setDrainQueue(final boolean drainQueue) { this.drainQueue = drainQueue; } - public synchronized String getConnectionFactoryLookup() - { + public synchronized String getConnectionFactoryLookup() { return connectionFactoryLookup; } - public synchronized void setConnectionFactoryLookup(final String connectionFactoryLookup) - { + public synchronized void setConnectionFactoryLookup(final String connectionFactoryLookup) { this.connectionFactoryLookup = connectionFactoryLookup; } - public synchronized String getDestinationLookup() - { + public synchronized String getDestinationLookup() { return destinationLookup; } - public synchronized void setDestinationLookup(final String destinationLookup) - { + public synchronized void setDestinationLookup(final String destinationLookup) { this.destinationLookup = destinationLookup; } - public synchronized int getThrottleRate() - { + public synchronized int getThrottleRate() { return throttleRate; } - public synchronized void setThrottleRate(final int throttleRate) - { + public synchronized void setThrottleRate(final int throttleRate) { this.throttleRate = throttleRate; } - public synchronized boolean isDisableMessageID() - { + public synchronized boolean isDisableMessageID() { return disableMessageID; } - public synchronized void setDisableMessageID(final boolean disableMessageID) - { + public synchronized void setDisableMessageID(final boolean disableMessageID) { this.disableMessageID = disableMessageID; } - public synchronized boolean isDisableTimestamp() - { + public synchronized boolean isDisableTimestamp() { return disableTimestamp; } - public synchronized void setDisableTimestamp(final boolean disableTimestamp) - { + public synchronized void setDisableTimestamp(final boolean disableTimestamp) { this.disableTimestamp = disableTimestamp; } - public synchronized boolean isDupsOK() - { + public synchronized boolean isDupsOK() { return dupsOK; } - public synchronized void setDupsOK(final boolean dupsOK) - { + public synchronized void setDupsOK(final boolean dupsOK) { this.dupsOK = dupsOK; } diff --git a/examples/soak/normal/src/main/java/org/apache/activemq/artemis/jms/soak/example/SoakReceiver.java b/examples/soak/normal/src/main/java/org/apache/activemq/artemis/jms/soak/example/SoakReceiver.java index c903831919..ce39968b93 100644 --- a/examples/soak/normal/src/main/java/org/apache/activemq/artemis/jms/soak/example/SoakReceiver.java +++ b/examples/soak/normal/src/main/java/org/apache/activemq/artemis/jms/soak/example/SoakReceiver.java @@ -31,41 +31,34 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Logger; -public class SoakReceiver -{ +public class SoakReceiver { + private static final Logger log = Logger.getLogger(SoakReceiver.class.getName()); private static final String EOF = UUID.randomUUID().toString(); - public static void main(final String[] args) - { - Runnable runnable = new Runnable() - { + public static void main(final String[] args) { + Runnable runnable = new Runnable() { @Override - public void run() - { + public void run() { - try - { + try { String fileName = SoakBase.getPerfFileName(); SoakParams params = SoakBase.getParams(fileName); final SoakReceiver receiver = new SoakReceiver(params); - Runtime.getRuntime().addShutdownHook(new Thread() - { + Runtime.getRuntime().addShutdownHook(new Thread() { @Override - public void run() - { + public void run() { receiver.disconnect(); } }); receiver.run(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -77,17 +70,14 @@ public class SoakReceiver private final SoakParams perfParams; - private final ExceptionListener exceptionListener = new ExceptionListener() - { - public void onException(final JMSException e) - { + private final ExceptionListener exceptionListener = new ExceptionListener() { + public void onException(final JMSException e) { disconnect(); connect(); } }; - private final MessageListener listener = new MessageListener() - { + private final MessageListener listener = new MessageListener() { int modulo = 10000; private final AtomicLong count = new AtomicLong(0); @@ -96,33 +86,24 @@ public class SoakReceiver long moduloStart = start; - public void onMessage(final Message msg) - { + public void onMessage(final Message msg) { long totalDuration = System.currentTimeMillis() - start; - try - { - if (SoakReceiver.EOF.equals(msg.getStringProperty("eof"))) - { - SoakReceiver.log.info(String.format("Received %s messages in %.2f minutes", count, 1.0 * totalDuration / - SoakBase.TO_MILLIS)); + try { + if (SoakReceiver.EOF.equals(msg.getStringProperty("eof"))) { + SoakReceiver.log.info(String.format("Received %s messages in %.2f minutes", count, 1.0 * totalDuration / SoakBase.TO_MILLIS)); SoakReceiver.log.info("END OF RUN"); return; } } - catch (JMSException e1) - { + catch (JMSException e1) { e1.printStackTrace(); } - if (count.incrementAndGet() % modulo == 0) - { + if (count.incrementAndGet() % modulo == 0) { double duration = (1.0 * System.currentTimeMillis() - moduloStart) / 1000; moduloStart = System.currentTimeMillis(); - SoakReceiver.log.info(String.format("received %s messages in %2.2fs (total: %.0fs)", - modulo, - duration, - totalDuration / 1000.0)); + SoakReceiver.log.info(String.format("received %s messages in %2.2fs (total: %.0fs)", modulo, duration, totalDuration / 1000.0)); } } }; @@ -131,19 +112,16 @@ public class SoakReceiver private Connection connection; - private SoakReceiver(final SoakParams perfParams) - { + private SoakReceiver(final SoakParams perfParams) { this.perfParams = perfParams; } - public void run() throws Exception - { + public void run() throws Exception { connect(); boolean runInfinitely = perfParams.getDurationInMinutes() == -1; - if (!runInfinitely) - { + if (!runInfinitely) { Thread.sleep(perfParams.getDurationInMinutes() * SoakBase.TO_MILLIS); // send EOF message @@ -151,76 +129,60 @@ public class SoakReceiver eof.setStringProperty("eof", SoakReceiver.EOF); listener.onMessage(eof); - if (connection != null) - { + if (connection != null) { connection.close(); connection = null; } } - else - { - while (true) - { + else { + while (true) { Thread.sleep(500); } } } - private void disconnect() - { - if (connection != null) - { - try - { + private void disconnect() { + if (connection != null) { + try { connection.setExceptionListener(null); connection.close(); } - catch (JMSException e) - { + catch (JMSException e) { e.printStackTrace(); } - finally - { + finally { connection = null; } } } - private void connect() - { + private void connect() { InitialContext ic = null; - try - { + try { ic = new InitialContext(); - ConnectionFactory factory = (ConnectionFactory)ic.lookup(perfParams.getConnectionFactoryLookup()); + ConnectionFactory factory = (ConnectionFactory) ic.lookup(perfParams.getConnectionFactoryLookup()); - Destination destination = (Destination)ic.lookup(perfParams.getDestinationLookup()); + Destination destination = (Destination) ic.lookup(perfParams.getDestinationLookup()); connection = factory.createConnection(); connection.setExceptionListener(exceptionListener); - session = connection.createSession(perfParams.isSessionTransacted(), - perfParams.isDupsOK() ? Session.DUPS_OK_ACKNOWLEDGE - : Session.AUTO_ACKNOWLEDGE); + session = connection.createSession(perfParams.isSessionTransacted(), perfParams.isDupsOK() ? Session.DUPS_OK_ACKNOWLEDGE : Session.AUTO_ACKNOWLEDGE); MessageConsumer messageConsumer = session.createConsumer(destination); messageConsumer.setMessageListener(listener); connection.start(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } - finally - { - try - { + finally { + try { ic.close(); } - catch (NamingException e) - { + catch (NamingException e) { e.printStackTrace(); } } diff --git a/examples/soak/normal/src/main/java/org/apache/activemq/artemis/jms/soak/example/SoakSender.java b/examples/soak/normal/src/main/java/org/apache/activemq/artemis/jms/soak/example/SoakSender.java index 2e81de63c6..10fbbd889b 100644 --- a/examples/soak/normal/src/main/java/org/apache/activemq/artemis/jms/soak/example/SoakSender.java +++ b/examples/soak/normal/src/main/java/org/apache/activemq/artemis/jms/soak/example/SoakSender.java @@ -33,32 +33,27 @@ import java.util.logging.Logger; import org.apache.activemq.artemis.utils.TokenBucketLimiter; import org.apache.activemq.artemis.utils.TokenBucketLimiterImpl; -public class SoakSender -{ +public class SoakSender { + private static final Logger log = Logger.getLogger(SoakSender.class.getName()); - public static void main(final String[] args) - { - try - { + public static void main(final String[] args) { + try { String fileName = SoakBase.getPerfFileName(); SoakParams params = SoakBase.getParams(fileName); final SoakSender sender = new SoakSender(params); - Runtime.getRuntime().addShutdownHook(new Thread() - { + Runtime.getRuntime().addShutdownHook(new Thread() { @Override - public void run() - { + public void run() { sender.disconnect(); } }); sender.run(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -71,10 +66,8 @@ public class SoakSender private MessageProducer producer; - private final ExceptionListener exceptionListener = new ExceptionListener() - { - public void onException(final JMSException e) - { + private final ExceptionListener exceptionListener = new ExceptionListener() { + public void onException(final JMSException e) { System.out.println("SoakReconnectableSender.exceptionListener.new ExceptionListener() {...}.onException()"); disconnect(); connect(); @@ -82,13 +75,11 @@ public class SoakSender }; - private SoakSender(final SoakParams perfParams) - { + private SoakSender(final SoakParams perfParams) { this.perfParams = perfParams; } - public void run() throws Exception - { + public void run() throws Exception { connect(); boolean runInfinitely = perfParams.getDurationInMinutes() == -1; @@ -101,9 +92,7 @@ public class SoakSender final int modulo = 10000; - TokenBucketLimiter tbl = perfParams.getThrottleRate() != -1 ? new TokenBucketLimiterImpl(perfParams.getThrottleRate(), - false) - : null; + TokenBucketLimiter tbl = perfParams.getThrottleRate() != -1 ? new TokenBucketLimiterImpl(perfParams.getThrottleRate(), false) : null; boolean transacted = perfParams.isSessionTransacted(); int txBatchSize = perfParams.getBatchSize(); @@ -112,45 +101,34 @@ public class SoakSender long start = System.currentTimeMillis(); long moduleStart = start; AtomicLong count = new AtomicLong(0); - while (true) - { - try - { + while (true) { + try { producer.send(message); count.incrementAndGet(); - if (transacted) - { - if (count.longValue() % txBatchSize == 0) - { + if (transacted) { + if (count.longValue() % txBatchSize == 0) { session.commit(); } } long totalDuration = System.currentTimeMillis() - start; - if (display && count.longValue() % modulo == 0) - { + if (display && count.longValue() % modulo == 0) { double duration = (1.0 * System.currentTimeMillis() - moduleStart) / 1000; moduleStart = System.currentTimeMillis(); - SoakSender.log.info(String.format("sent %s messages in %2.2fs (time: %.0fs)", - modulo, - duration, - totalDuration / 1000.0)); + SoakSender.log.info(String.format("sent %s messages in %2.2fs (time: %.0fs)", modulo, duration, totalDuration / 1000.0)); } - if (tbl != null) - { + if (tbl != null) { tbl.limit(); } - if (!runInfinitely && totalDuration > perfParams.getDurationInMinutes() * SoakBase.TO_MILLIS) - { + if (!runInfinitely && totalDuration > perfParams.getDurationInMinutes() * SoakBase.TO_MILLIS) { break; } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -158,49 +136,39 @@ public class SoakSender SoakSender.log.info(String.format("Sent %s messages in %s minutes", count, perfParams.getDurationInMinutes())); SoakSender.log.info("END OF RUN"); - if (connection != null) - { + if (connection != null) { connection.close(); connection = null; } } - private synchronized void disconnect() - { - if (connection != null) - { - try - { + private synchronized void disconnect() { + if (connection != null) { + try { connection.setExceptionListener(null); connection.close(); } - catch (JMSException e) - { + catch (JMSException e) { e.printStackTrace(); } - finally - { + finally { connection = null; } } } - private void connect() - { + private void connect() { InitialContext ic = null; - try - { + try { ic = new InitialContext(); - ConnectionFactory factory = (ConnectionFactory)ic.lookup(perfParams.getConnectionFactoryLookup()); + ConnectionFactory factory = (ConnectionFactory) ic.lookup(perfParams.getConnectionFactoryLookup()); - Destination destination = (Destination)ic.lookup(perfParams.getDestinationLookup()); + Destination destination = (Destination) ic.lookup(perfParams.getDestinationLookup()); connection = factory.createConnection(); - session = connection.createSession(perfParams.isSessionTransacted(), - perfParams.isDupsOK() ? Session.DUPS_OK_ACKNOWLEDGE - : Session.AUTO_ACKNOWLEDGE); + session = connection.createSession(perfParams.isSessionTransacted(), perfParams.isDupsOK() ? Session.DUPS_OK_ACKNOWLEDGE : Session.AUTO_ACKNOWLEDGE); producer = session.createProducer(destination); @@ -212,18 +180,14 @@ public class SoakSender connection.setExceptionListener(exceptionListener); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } - finally - { - try - { + finally { + try { ic.close(); } - catch (NamingException e) - { + catch (NamingException e) { e.printStackTrace(); } } diff --git a/integration/activemq-aerogear-integration/src/main/java/org/apache/activemq/artemis/integration/aerogear/ActiveMQAeroGearBundle.java b/integration/activemq-aerogear-integration/src/main/java/org/apache/activemq/artemis/integration/aerogear/ActiveMQAeroGearBundle.java index cad01222b9..e389def98b 100644 --- a/integration/activemq-aerogear-integration/src/main/java/org/apache/activemq/artemis/integration/aerogear/ActiveMQAeroGearBundle.java +++ b/integration/activemq-aerogear-integration/src/main/java/org/apache/activemq/artemis/integration/aerogear/ActiveMQAeroGearBundle.java @@ -22,15 +22,15 @@ import org.jboss.logging.annotations.MessageBundle; import org.jboss.logging.Messages; /** - * Logger Code 23 - *
    - * each message id must be 6 digits long starting with 10, the 3rd digit should be 9 - *
    - * so 239000 to 239999 + * Logger Code 23 + *
    + * each message id must be 6 digits long starting with 10, the 3rd digit should be 9 + *
    + * so 239000 to 239999 */ @MessageBundle(projectCode = "AMQ") -public interface ActiveMQAeroGearBundle -{ +public interface ActiveMQAeroGearBundle { + ActiveMQAeroGearBundle BUNDLE = Messages.getBundle(ActiveMQAeroGearBundle.class); @Message(id = 239000, value = "endpoint can not be null") diff --git a/integration/activemq-aerogear-integration/src/main/java/org/apache/activemq/artemis/integration/aerogear/ActiveMQAeroGearLogger.java b/integration/activemq-aerogear-integration/src/main/java/org/apache/activemq/artemis/integration/aerogear/ActiveMQAeroGearLogger.java index 3de68e881b..c8e7c57bc3 100644 --- a/integration/activemq-aerogear-integration/src/main/java/org/apache/activemq/artemis/integration/aerogear/ActiveMQAeroGearLogger.java +++ b/integration/activemq-aerogear-integration/src/main/java/org/apache/activemq/artemis/integration/aerogear/ActiveMQAeroGearLogger.java @@ -37,8 +37,8 @@ import org.jboss.logging.annotations.MessageLogger; * so an INFO message would be 181000 to 181999 */ @MessageLogger(projectCode = "AMQ") -public interface ActiveMQAeroGearLogger extends BasicLogger -{ +public interface ActiveMQAeroGearLogger extends BasicLogger { + /** * The aerogear logger. */ diff --git a/integration/activemq-aerogear-integration/src/main/java/org/apache/activemq/artemis/integration/aerogear/AeroGearConnectorService.java b/integration/activemq-aerogear-integration/src/main/java/org/apache/activemq/artemis/integration/aerogear/AeroGearConnectorService.java index 4a2497e8e8..0be4cd0f06 100644 --- a/integration/activemq-aerogear-integration/src/main/java/org/apache/activemq/artemis/integration/aerogear/AeroGearConnectorService.java +++ b/integration/activemq-aerogear-integration/src/main/java/org/apache/activemq/artemis/integration/aerogear/AeroGearConnectorService.java @@ -44,8 +44,8 @@ import org.jboss.aerogear.unifiedpush.SenderClient; import org.jboss.aerogear.unifiedpush.message.MessageResponseCallback; import org.jboss.aerogear.unifiedpush.message.UnifiedMessage; -public class AeroGearConnectorService implements ConnectorService, Consumer, MessageResponseCallback -{ +public class AeroGearConnectorService implements ConnectorService, Consumer, MessageResponseCallback { + private final String connectorName; private final PostOffice postOffice; @@ -92,8 +92,10 @@ public class AeroGearConnectorService implements ConnectorService, Consumer, Mes private boolean reconnecting = false; - public AeroGearConnectorService(String connectorName, Map configuration, PostOffice postOffice, ScheduledExecutorService scheduledThreadPool) - { + public AeroGearConnectorService(String connectorName, + Map configuration, + PostOffice postOffice, + ScheduledExecutorService scheduledThreadPool) { this.connectorName = connectorName; this.postOffice = postOffice; this.scheduledThreadPool = scheduledThreadPool; @@ -110,56 +112,45 @@ public class AeroGearConnectorService implements ConnectorService, Consumer, Mes this.retryInterval = ConfigurationHelper.getIntProperty(AeroGearConstants.RETRY_INTERVAL_NAME, AeroGearConstants.DEFAULT_RETRY_INTERVAL, configuration); this.retryAttempts = ConfigurationHelper.getIntProperty(AeroGearConstants.RETRY_ATTEMPTS_NAME, AeroGearConstants.DEFAULT_RETRY_ATTEMPTS, configuration); String variantsString = ConfigurationHelper.getStringProperty(AeroGearConstants.VARIANTS_NAME, null, configuration); - if (variantsString != null) - { + if (variantsString != null) { variants = variantsString.split(","); } String aliasesString = ConfigurationHelper.getStringProperty(AeroGearConstants.ALIASES_NAME, null, configuration); - if (aliasesString != null) - { + if (aliasesString != null) { aliases = aliasesString.split(","); } String deviceTypeString = ConfigurationHelper.getStringProperty(AeroGearConstants.DEVICE_TYPE_NAME, null, configuration); - if (deviceTypeString != null) - { + if (deviceTypeString != null) { deviceTypes = deviceTypeString.split(","); } } @Override - public String getName() - { + public String getName() { return connectorName; } @Override - public void start() throws Exception - { - if (started) - { + public void start() throws Exception { + if (started) { return; } - if (filterString != null) - { + if (filterString != null) { filter = FilterImpl.createFilter(filterString); } - if (endpoint == null || endpoint.isEmpty()) - { + if (endpoint == null || endpoint.isEmpty()) { throw ActiveMQAeroGearBundle.BUNDLE.endpointNull(); } - if (applicationId == null || applicationId.isEmpty()) - { + if (applicationId == null || applicationId.isEmpty()) { throw ActiveMQAeroGearBundle.BUNDLE.applicationIdNull(); } - if (applicationMasterSecret == null || applicationMasterSecret.isEmpty()) - { + if (applicationMasterSecret == null || applicationMasterSecret.isEmpty()) { throw ActiveMQAeroGearBundle.BUNDLE.masterSecretNull(); } Binding b = postOffice.getBinding(new SimpleString(queueName)); - if (b == null) - { + if (b == null) { throw ActiveMQAeroGearBundle.BUNDLE.noQueue(connectorName, queueName); } @@ -171,42 +162,34 @@ public class AeroGearConnectorService implements ConnectorService, Consumer, Mes } @Override - public void stop() throws Exception - { - if (!started) - { + public void stop() throws Exception { + if (!started) { return; } queue.removeConsumer(this); } @Override - public boolean isStarted() - { + public boolean isStarted() { return started; } @Override - public HandleStatus handle(final MessageReference reference) throws Exception - { - if (reconnecting) - { + public HandleStatus handle(final MessageReference reference) throws Exception { + if (reconnecting) { return HandleStatus.BUSY; } ServerMessage message = reference.getMessage(); - if (filter != null && !filter.match(message)) - { - if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) - { + if (filter != null && !filter.match(message)) { + if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("Reference " + reference + " is a noMatch on consumer " + this); } return HandleStatus.NO_MATCH; } //we only accept if the alert is set - if (!message.containsProperty(AeroGearConstants.AEROGEAR_ALERT)) - { + if (!message.containsProperty(AeroGearConstants.AEROGEAR_ALERT)) { return HandleStatus.NO_MATCH; } @@ -216,42 +199,35 @@ public class AeroGearConnectorService implements ConnectorService, Consumer, Mes UnifiedMessage.Builder builder = new UnifiedMessage.Builder(); - builder.pushApplicationId(applicationId) - .masterSecret(applicationMasterSecret) - .alert(alert); + builder.pushApplicationId(applicationId).masterSecret(applicationMasterSecret).alert(alert); String sound = message.containsProperty(AeroGearConstants.AEROGEAR_SOUND) ? message.getStringProperty(AeroGearConstants.AEROGEAR_SOUND) : this.sound; - if (sound != null) - { + if (sound != null) { builder.sound(sound); } String badge = message.containsProperty(AeroGearConstants.AEROGEAR_BADGE) ? message.getStringProperty(AeroGearConstants.AEROGEAR_BADGE) : this.badge; - if (badge != null) - { + if (badge != null) { builder.badge(badge); } boolean contentAvailable = message.containsProperty(AeroGearConstants.AEROGEAR_CONTENT_AVAILABLE) ? message.getBooleanProperty(AeroGearConstants.AEROGEAR_CONTENT_AVAILABLE) : this.contentAvailable; - if (contentAvailable) - { + if (contentAvailable) { builder.contentAvailable(); } String actionCategory = message.containsProperty(AeroGearConstants.AEROGEAR_ACTION_CATEGORY) ? message.getStringProperty(AeroGearConstants.AEROGEAR_ACTION_CATEGORY) : this.actionCategory; - if (actionCategory != null) - { + if (actionCategory != null) { builder.actionCategory(actionCategory); } Integer ttl = message.containsProperty(AeroGearConstants.AEROGEAR_TTL) ? message.getIntProperty(AeroGearConstants.AEROGEAR_TTL) : this.ttl; - if (ttl != null) - { + if (ttl != null) { builder.timeToLive(ttl); } @@ -259,8 +235,7 @@ public class AeroGearConnectorService implements ConnectorService, Consumer, Mes String[] variants = variantsString != null ? variantsString.split(",") : this.variants; - if (variants != null) - { + if (variants != null) { builder.variants(Arrays.asList(variants)); } @@ -268,8 +243,7 @@ public class AeroGearConnectorService implements ConnectorService, Consumer, Mes String[] aliases = aliasesString != null ? aliasesString.split(",") : this.aliases; - if (aliases != null) - { + if (aliases != null) { builder.aliases(Arrays.asList(aliases)); } @@ -277,17 +251,14 @@ public class AeroGearConnectorService implements ConnectorService, Consumer, Mes String[] deviceTypes = deviceTypesString != null ? deviceTypesString.split(",") : this.deviceTypes; - if (deviceTypes != null) - { + if (deviceTypes != null) { builder.deviceType(Arrays.asList(deviceTypes)); } Set propertyNames = message.getPropertyNames(); - for (SimpleString propertyName : propertyNames) - { - if (propertyName.toString().startsWith("AEROGEAR_") && !AeroGearConstants.ALLOWABLE_PROPERTIES.contains(propertyName)) - { + for (SimpleString propertyName : propertyNames) { + if (propertyName.toString().startsWith("AEROGEAR_") && !AeroGearConstants.ALLOWABLE_PROPERTIES.contains(propertyName)) { Object property = message.getTypedProperties().getProperty(propertyName); builder.attribute(propertyName.toString(), property.toString()); } @@ -297,89 +268,72 @@ public class AeroGearConnectorService implements ConnectorService, Consumer, Mes sender.send(unifiedMessage, this); - if (handled) - { + if (handled) { reference.acknowledge(); return HandleStatus.HANDLED; } //if we have been stopped we must return no match as we have been removed as a consumer, // anything else will cause an exception - else if (!started) - { + else if (!started) { return HandleStatus.NO_MATCH; } //we must be reconnecting return HandleStatus.BUSY; } - @Override - public void onComplete(int statusCode) - { - if (statusCode != 200) - { + public void onComplete(int statusCode) { + if (statusCode != 200) { handled = false; - if (statusCode == 401) - { + if (statusCode == 401) { ActiveMQAeroGearLogger.LOGGER.reply401(); } - else if (statusCode == 404) - { + else if (statusCode == 404) { ActiveMQAeroGearLogger.LOGGER.reply404(); } - else - { + else { ActiveMQAeroGearLogger.LOGGER.replyUnknown(statusCode); } queue.removeConsumer(this); started = false; } - else - { + else { handled = true; } } @Override - public void onError(Throwable throwable) - { + public void onError(Throwable throwable) { ActiveMQAeroGearLogger.LOGGER.sendFailed(retryInterval); handled = false; reconnecting = true; scheduledThreadPool.schedule(new ReconnectRunnable(0), retryInterval, TimeUnit.SECONDS); } - private class ReconnectRunnable implements Runnable - { + private class ReconnectRunnable implements Runnable { private int retryAttempt; - public ReconnectRunnable(int retryAttempt) - { + public ReconnectRunnable(int retryAttempt) { this.retryAttempt = retryAttempt; } @Override - public void run() - { - try - { + public void run() { + try { HttpURLConnection conn = (HttpURLConnection) new URL(endpoint).openConnection(); conn.connect(); reconnecting = false; ActiveMQAeroGearLogger.LOGGER.connected(endpoint); queue.deliverAsync(); } - catch (Exception e) - { + catch (Exception e) { retryAttempt++; - if (retryAttempts == -1 || retryAttempt < retryAttempts) - { + if (retryAttempts == -1 || retryAttempt < retryAttempts) { scheduledThreadPool.schedule(this, retryInterval, TimeUnit.SECONDS); } - else - { + else { ActiveMQAeroGearLogger.LOGGER.unableToReconnect(retryAttempt); started = false; } @@ -388,37 +342,31 @@ public class AeroGearConnectorService implements ConnectorService, Consumer, Mes } @Override - public List getDeliveringMessages() - { + public List getDeliveringMessages() { return Collections.emptyList(); } @Override - public void proceedDeliver(MessageReference reference) throws Exception - { + public void proceedDeliver(MessageReference reference) throws Exception { //noop } @Override - public Filter getFilter() - { + public Filter getFilter() { return filter; } @Override - public String debug() - { + public String debug() { return "aerogear connected to " + endpoint; } @Override - public String toManagementString() - { + public String toManagementString() { return "aerogear connected to " + endpoint; } @Override - public void disconnect() - { + public void disconnect() { } } diff --git a/integration/activemq-aerogear-integration/src/main/java/org/apache/activemq/artemis/integration/aerogear/AeroGearConnectorServiceFactory.java b/integration/activemq-aerogear-integration/src/main/java/org/apache/activemq/artemis/integration/aerogear/AeroGearConnectorServiceFactory.java index d0ba2e7789..585fa1b877 100644 --- a/integration/activemq-aerogear-integration/src/main/java/org/apache/activemq/artemis/integration/aerogear/AeroGearConnectorServiceFactory.java +++ b/integration/activemq-aerogear-integration/src/main/java/org/apache/activemq/artemis/integration/aerogear/AeroGearConnectorServiceFactory.java @@ -25,24 +25,24 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.ScheduledExecutorService; +public class AeroGearConnectorServiceFactory implements ConnectorServiceFactory { -public class AeroGearConnectorServiceFactory implements ConnectorServiceFactory -{ @Override - public ConnectorService createConnectorService(String connectorName, Map configuration, StorageManager storageManager, PostOffice postOffice, ScheduledExecutorService scheduledThreadPool) - { + public ConnectorService createConnectorService(String connectorName, + Map configuration, + StorageManager storageManager, + PostOffice postOffice, + ScheduledExecutorService scheduledThreadPool) { return new AeroGearConnectorService(connectorName, configuration, postOffice, scheduledThreadPool); } @Override - public Set getAllowableProperties() - { + public Set getAllowableProperties() { return AeroGearConstants.ALLOWABLE_PROPERTIES; } @Override - public Set getRequiredProperties() - { + public Set getRequiredProperties() { return AeroGearConstants.REQUIRED_PROPERTIES; } } diff --git a/integration/activemq-aerogear-integration/src/main/java/org/apache/activemq/artemis/integration/aerogear/AeroGearConstants.java b/integration/activemq-aerogear-integration/src/main/java/org/apache/activemq/artemis/integration/aerogear/AeroGearConstants.java index 38154f1862..4e921283dc 100644 --- a/integration/activemq-aerogear-integration/src/main/java/org/apache/activemq/artemis/integration/aerogear/AeroGearConstants.java +++ b/integration/activemq-aerogear-integration/src/main/java/org/apache/activemq/artemis/integration/aerogear/AeroGearConstants.java @@ -21,8 +21,8 @@ import org.apache.activemq.artemis.api.core.SimpleString; import java.util.HashSet; import java.util.Set; -public class AeroGearConstants -{ +public class AeroGearConstants { + public static final Set ALLOWABLE_PROPERTIES = new HashSet<>(); public static final Set REQUIRED_PROPERTIES = new HashSet<>(); @@ -42,7 +42,6 @@ public class AeroGearConstants public static final String ALIASES_NAME = "aliases"; public static final String DEVICE_TYPE_NAME = "device-types"; - public static final SimpleString AEROGEAR_ALERT = new SimpleString("AEROGEAR_ALERT"); public static final SimpleString AEROGEAR_SOUND = new SimpleString("AEROGEAR_SOUND"); public static final SimpleString AEROGEAR_CONTENT_AVAILABLE = new SimpleString("AEROGEAR_CONTENT_AVAILABLE"); @@ -58,8 +57,7 @@ public class AeroGearConstants public static final int DEFAULT_RETRY_INTERVAL = 5; public static final int DEFAULT_RETRY_ATTEMPTS = 5; - static - { + static { ALLOWABLE_PROPERTIES.add(QUEUE_NAME); ALLOWABLE_PROPERTIES.add(ENDPOINT_NAME); ALLOWABLE_PROPERTIES.add(APPLICATION_ID_NAME); diff --git a/integration/activemq-spring-integration/src/main/java/org/apache/activemq/artemis/integration/spring/SpringBindingRegistry.java b/integration/activemq-spring-integration/src/main/java/org/apache/activemq/artemis/integration/spring/SpringBindingRegistry.java index b01a3d5d0e..db6ee37a5a 100644 --- a/integration/activemq-spring-integration/src/main/java/org/apache/activemq/artemis/integration/spring/SpringBindingRegistry.java +++ b/integration/activemq-spring-integration/src/main/java/org/apache/activemq/artemis/integration/spring/SpringBindingRegistry.java @@ -20,40 +20,33 @@ import org.apache.activemq.artemis.spi.core.naming.BindingRegistry; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.config.ConfigurableBeanFactory; -public class SpringBindingRegistry implements BindingRegistry -{ +public class SpringBindingRegistry implements BindingRegistry { + private ConfigurableBeanFactory factory; - public SpringBindingRegistry(ConfigurableBeanFactory factory) - { + public SpringBindingRegistry(ConfigurableBeanFactory factory) { this.factory = factory; } - public Object lookup(String name) - { + public Object lookup(String name) { Object obj = null; - try - { + try { obj = factory.getBean(name); } - catch (NoSuchBeanDefinitionException e) - { + catch (NoSuchBeanDefinitionException e) { //ignore } return obj; } - public boolean bind(String name, Object obj) - { + public boolean bind(String name, Object obj) { factory.registerSingleton(name, obj); return true; } - public void unbind(String name) - { + public void unbind(String name) { } - public void close() - { + public void close() { } } diff --git a/integration/activemq-spring-integration/src/main/java/org/apache/activemq/artemis/integration/spring/SpringJmsBootstrap.java b/integration/activemq-spring-integration/src/main/java/org/apache/activemq/artemis/integration/spring/SpringJmsBootstrap.java index 85e68cd902..02886288a3 100644 --- a/integration/activemq-spring-integration/src/main/java/org/apache/activemq/artemis/integration/spring/SpringJmsBootstrap.java +++ b/integration/activemq-spring-integration/src/main/java/org/apache/activemq/artemis/integration/spring/SpringJmsBootstrap.java @@ -22,10 +22,9 @@ import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.config.ConfigurableBeanFactory; -public class SpringJmsBootstrap extends EmbeddedJMS implements BeanFactoryAware -{ - public void setBeanFactory(BeanFactory beanFactory) throws BeansException - { +public class SpringJmsBootstrap extends EmbeddedJMS implements BeanFactoryAware { + + public void setBeanFactory(BeanFactory beanFactory) throws BeansException { registry = new SpringBindingRegistry((ConfigurableBeanFactory) beanFactory); } } diff --git a/integration/activemq-spring-integration/src/main/java/org/apache/activemq/artemis/spring/ActiveMQSpringBundle.java b/integration/activemq-spring-integration/src/main/java/org/apache/activemq/artemis/spring/ActiveMQSpringBundle.java index d6d0af1414..c931b5ac86 100644 --- a/integration/activemq-spring-integration/src/main/java/org/apache/activemq/artemis/spring/ActiveMQSpringBundle.java +++ b/integration/activemq-spring-integration/src/main/java/org/apache/activemq/artemis/spring/ActiveMQSpringBundle.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.spring; - import org.jboss.logging.annotations.MessageBundle; /** @@ -27,6 +26,6 @@ import org.jboss.logging.annotations.MessageBundle; * so 179000 to 179999 */ @MessageBundle(projectCode = "AMQ") -public class ActiveMQSpringBundle -{ +public class ActiveMQSpringBundle { + } diff --git a/integration/activemq-spring-integration/src/main/java/org/apache/activemq/artemis/spring/ActiveMQSpringLogger.java b/integration/activemq-spring-integration/src/main/java/org/apache/activemq/artemis/spring/ActiveMQSpringLogger.java index a6a0c1705d..57e997105f 100644 --- a/integration/activemq-spring-integration/src/main/java/org/apache/activemq/artemis/spring/ActiveMQSpringLogger.java +++ b/integration/activemq-spring-integration/src/main/java/org/apache/activemq/artemis/spring/ActiveMQSpringLogger.java @@ -33,6 +33,6 @@ import org.jboss.logging.annotations.MessageLogger; * so an INFO message would be 171000 to 171999 */ @MessageLogger(projectCode = "AMQ") -public class ActiveMQSpringLogger -{ +public class ActiveMQSpringLogger { + } diff --git a/integration/activemq-vertx-integration/src/main/java/org/apache/activemq/artemis/integration/vertx/ActiveMQVertxLogger.java b/integration/activemq-vertx-integration/src/main/java/org/apache/activemq/artemis/integration/vertx/ActiveMQVertxLogger.java index 00c27e6c08..e4a0382904 100644 --- a/integration/activemq-vertx-integration/src/main/java/org/apache/activemq/artemis/integration/vertx/ActiveMQVertxLogger.java +++ b/integration/activemq-vertx-integration/src/main/java/org/apache/activemq/artemis/integration/vertx/ActiveMQVertxLogger.java @@ -38,8 +38,8 @@ import org.jboss.logging.annotations.MessageLogger; * so an INFO message would be 191000 to 191999 */ @MessageLogger(projectCode = "AMQ") -public interface ActiveMQVertxLogger extends BasicLogger -{ +public interface ActiveMQVertxLogger extends BasicLogger { + /** * The vertx logger. */ diff --git a/integration/activemq-vertx-integration/src/main/java/org/apache/activemq/artemis/integration/vertx/IncomingVertxEventHandler.java b/integration/activemq-vertx-integration/src/main/java/org/apache/activemq/artemis/integration/vertx/IncomingVertxEventHandler.java index ac19b65656..a321820de2 100644 --- a/integration/activemq-vertx-integration/src/main/java/org/apache/activemq/artemis/integration/vertx/IncomingVertxEventHandler.java +++ b/integration/activemq-vertx-integration/src/main/java/org/apache/activemq/artemis/integration/vertx/IncomingVertxEventHandler.java @@ -40,8 +40,8 @@ import org.vertx.java.platform.PlatformLocator; import org.vertx.java.platform.PlatformManager; import org.vertx.java.spi.cluster.impl.hazelcast.HazelcastClusterManagerFactory; -public class IncomingVertxEventHandler implements ConnectorService -{ +public class IncomingVertxEventHandler implements ConnectorService { + private final String connectorName; private final String queueName; @@ -68,51 +68,41 @@ public class IncomingVertxEventHandler implements ConnectorService private boolean isStarted = false; - public IncomingVertxEventHandler(String connectorName, Map configuration, - StorageManager storageManager, PostOffice postOffice, - ScheduledExecutorService scheduledThreadPool) - { + public IncomingVertxEventHandler(String connectorName, + Map configuration, + StorageManager storageManager, + PostOffice postOffice, + ScheduledExecutorService scheduledThreadPool) { this.connectorName = connectorName; - this.queueName = ConfigurationHelper.getStringProperty(VertxConstants.QUEUE_NAME, null, - configuration); + this.queueName = ConfigurationHelper.getStringProperty(VertxConstants.QUEUE_NAME, null, configuration); this.port = ConfigurationHelper.getIntProperty(VertxConstants.PORT, 0, configuration); - this.host = ConfigurationHelper.getStringProperty(VertxConstants.HOST, "localhost", - configuration); - this.quorumSize = ConfigurationHelper.getIntProperty(VertxConstants.VERTX_QUORUM_SIZE, - -1, configuration); - this.haGroup = ConfigurationHelper.getStringProperty(VertxConstants.VERTX_HA_GROUP, - "activemq", configuration); - this.vertxAddress = ConfigurationHelper.getStringProperty(VertxConstants.VERTX_ADDRESS, - "org.apache.activemq", configuration); + this.host = ConfigurationHelper.getStringProperty(VertxConstants.HOST, "localhost", configuration); + this.quorumSize = ConfigurationHelper.getIntProperty(VertxConstants.VERTX_QUORUM_SIZE, -1, configuration); + this.haGroup = ConfigurationHelper.getStringProperty(VertxConstants.VERTX_HA_GROUP, "activemq", configuration); + this.vertxAddress = ConfigurationHelper.getStringProperty(VertxConstants.VERTX_ADDRESS, "org.apache.activemq", configuration); this.storageManager = storageManager; this.postOffice = postOffice; } @Override - public void start() throws Exception - { - if (this.isStarted) - { + public void start() throws Exception { + if (this.isStarted) { return; } - System.setProperty("vertx.clusterManagerFactory", - HazelcastClusterManagerFactory.class.getName()); - if (quorumSize != -1) - { + System.setProperty("vertx.clusterManagerFactory", HazelcastClusterManagerFactory.class.getName()); + if (quorumSize != -1) { platformManager = PlatformLocator.factory.createPlatformManager(port, host, quorumSize, haGroup); } - else - { + else { platformManager = PlatformLocator.factory.createPlatformManager(port, host); } eventBus = platformManager.vertx().eventBus(); Binding b = postOffice.getBinding(new SimpleString(queueName)); - if (b == null) - { + if (b == null) { throw new Exception(connectorName + ": queue " + queueName + " not found"); } @@ -124,10 +114,8 @@ public class IncomingVertxEventHandler implements ConnectorService } @Override - public void stop() throws Exception - { - if (!isStarted) - { + public void stop() throws Exception { + if (!isStarted) { return; } eventBus.unregisterHandler(vertxAddress, handler); @@ -138,31 +126,26 @@ public class IncomingVertxEventHandler implements ConnectorService } @Override - public boolean isStarted() - { + public boolean isStarted() { return isStarted; } @Override - public String getName() - { + public String getName() { return connectorName; } - private class EventHandler implements Handler> - { + private class EventHandler implements Handler> { + @Override - public void handle(Message message) - { - ServerMessage msg = new ServerMessageImpl(storageManager.generateID(), - VertxConstants.INITIAL_MESSAGE_BUFFER_SIZE); + public void handle(Message message) { + ServerMessage msg = new ServerMessageImpl(storageManager.generateID(), VertxConstants.INITIAL_MESSAGE_BUFFER_SIZE); msg.setAddress(new SimpleString(queueName)); msg.setDurable(true); msg.encodeMessageIDToBuffer(); String replyAddress = message.replyAddress(); - if (replyAddress != null) - { + if (replyAddress != null) { msg.putStringProperty(VertxConstants.VERTX_MESSAGE_REPLYADDRESS, replyAddress); } @@ -173,20 +156,16 @@ public class IncomingVertxEventHandler implements ConnectorService manualEncodeVertxMessageBody(msg.getBodyBuffer(), message.body(), type); - try - { + try { postOffice.route(msg, null, false); } - catch (Exception e) - { + catch (Exception e) { ActiveMQVertxLogger.LOGGER.error("failed to route msg " + msg, e); } } - private void manualEncodeVertxMessageBody(ActiveMQBuffer bodyBuffer, Object body, int type) - { - switch (type) - { + private void manualEncodeVertxMessageBody(ActiveMQBuffer bodyBuffer, Object body, int type) { + switch (type) { case VertxConstants.TYPE_BOOLEAN: bodyBuffer.writeBoolean(((Boolean) body)); break; @@ -243,69 +222,53 @@ public class IncomingVertxEventHandler implements ConnectorService } } - private int getMessageType(Message message) - { + private int getMessageType(Message message) { Object body = message.body(); - if (message instanceof PingMessage) - { + if (message instanceof PingMessage) { return VertxConstants.TYPE_PING; } - else if (body instanceof Buffer) - { + else if (body instanceof Buffer) { return VertxConstants.TYPE_BUFFER; } - else if (body instanceof Boolean) - { + else if (body instanceof Boolean) { return VertxConstants.TYPE_BOOLEAN; } - else if (body instanceof byte[]) - { + else if (body instanceof byte[]) { return VertxConstants.TYPE_BYTEARRAY; } - else if (body instanceof Byte) - { + else if (body instanceof Byte) { return VertxConstants.TYPE_BYTE; } - else if (body instanceof Character) - { + else if (body instanceof Character) { return VertxConstants.TYPE_CHARACTER; } - else if (body instanceof Double) - { + else if (body instanceof Double) { return VertxConstants.TYPE_DOUBLE; } - else if (body instanceof Float) - { + else if (body instanceof Float) { return VertxConstants.TYPE_FLOAT; } - else if (body instanceof Integer) - { + else if (body instanceof Integer) { return VertxConstants.TYPE_INT; } - else if (body instanceof Long) - { + else if (body instanceof Long) { return VertxConstants.TYPE_LONG; } - else if (body instanceof Short) - { + else if (body instanceof Short) { return VertxConstants.TYPE_SHORT; } - else if (body instanceof String) - { + else if (body instanceof String) { return VertxConstants.TYPE_STRING; } - else if (body instanceof JsonArray) - { + else if (body instanceof JsonArray) { return VertxConstants.TYPE_JSON_ARRAY; } - else if (body instanceof JsonObject) - { + else if (body instanceof JsonObject) { return VertxConstants.TYPE_JSON_OBJECT; } - else if (body instanceof ReplyException) - { + else if (body instanceof ReplyException) { return VertxConstants.TYPE_REPLY_FAILURE; } @@ -315,9 +278,7 @@ public class IncomingVertxEventHandler implements ConnectorService } @Override - public String toString() - { - return "[IncomingVertxEventHandler(" + connectorName + "), queueName: " + queueName - + " host: " + host + " port: " + port + " vertxAddress: " + vertxAddress + "]"; + public String toString() { + return "[IncomingVertxEventHandler(" + connectorName + "), queueName: " + queueName + " host: " + host + " port: " + port + " vertxAddress: " + vertxAddress + "]"; } } diff --git a/integration/activemq-vertx-integration/src/main/java/org/apache/activemq/artemis/integration/vertx/OutgoingVertxEventHandler.java b/integration/activemq-vertx-integration/src/main/java/org/apache/activemq/artemis/integration/vertx/OutgoingVertxEventHandler.java index c50a4541bd..2651adf2a8 100644 --- a/integration/activemq-vertx-integration/src/main/java/org/apache/activemq/artemis/integration/vertx/OutgoingVertxEventHandler.java +++ b/integration/activemq-vertx-integration/src/main/java/org/apache/activemq/artemis/integration/vertx/OutgoingVertxEventHandler.java @@ -43,8 +43,8 @@ import org.vertx.java.platform.PlatformLocator; import org.vertx.java.platform.PlatformManager; import org.vertx.java.spi.cluster.impl.hazelcast.HazelcastClusterManagerFactory; -public class OutgoingVertxEventHandler implements Consumer, ConnectorService -{ +public class OutgoingVertxEventHandler implements Consumer, ConnectorService { + private final String connectorName; private final String queueName; @@ -73,62 +73,49 @@ public class OutgoingVertxEventHandler implements Consumer, ConnectorService private boolean isStarted = false; - public OutgoingVertxEventHandler(String connectorName, Map configuration, - StorageManager storageManager, PostOffice postOffice, - ScheduledExecutorService scheduledThreadPool) - { + public OutgoingVertxEventHandler(String connectorName, + Map configuration, + StorageManager storageManager, + PostOffice postOffice, + ScheduledExecutorService scheduledThreadPool) { this.connectorName = connectorName; - this.queueName = ConfigurationHelper.getStringProperty(VertxConstants.QUEUE_NAME, null, - configuration); + this.queueName = ConfigurationHelper.getStringProperty(VertxConstants.QUEUE_NAME, null, configuration); this.postOffice = postOffice; this.port = ConfigurationHelper.getIntProperty(VertxConstants.PORT, 0, configuration); - this.host = ConfigurationHelper.getStringProperty(VertxConstants.HOST, "localhost", - configuration); - this.quorumSize = ConfigurationHelper.getIntProperty(VertxConstants.VERTX_QUORUM_SIZE, - -1, configuration); - this.haGroup = ConfigurationHelper.getStringProperty(VertxConstants.VERTX_HA_GROUP, - "activemq", configuration); - this.vertxAddress = ConfigurationHelper.getStringProperty(VertxConstants.VERTX_ADDRESS, - "org.apache.activemq", configuration); - this.publish = ConfigurationHelper.getBooleanProperty(VertxConstants.VERTX_PUBLISH, false, - configuration); + this.host = ConfigurationHelper.getStringProperty(VertxConstants.HOST, "localhost", configuration); + this.quorumSize = ConfigurationHelper.getIntProperty(VertxConstants.VERTX_QUORUM_SIZE, -1, configuration); + this.haGroup = ConfigurationHelper.getStringProperty(VertxConstants.VERTX_HA_GROUP, "activemq", configuration); + this.vertxAddress = ConfigurationHelper.getStringProperty(VertxConstants.VERTX_ADDRESS, "org.apache.activemq", configuration); + this.publish = ConfigurationHelper.getBooleanProperty(VertxConstants.VERTX_PUBLISH, false, configuration); } @Override - public void start() throws Exception - { - if (this.isStarted) - { + public void start() throws Exception { + if (this.isStarted) { return; } - System.setProperty("vertx.clusterManagerFactory", - HazelcastClusterManagerFactory.class.getName()); - if (quorumSize != -1) - { + System.setProperty("vertx.clusterManagerFactory", HazelcastClusterManagerFactory.class.getName()); + if (quorumSize != -1) { platformManager = PlatformLocator.factory.createPlatformManager(port, host, quorumSize, haGroup); } - else - { + else { platformManager = PlatformLocator.factory.createPlatformManager(port, host); } eventBus = platformManager.vertx().eventBus(); - if (this.connectorName == null || this.connectorName.trim().equals("")) - { + if (this.connectorName == null || this.connectorName.trim().equals("")) { throw new Exception("invalid connector name: " + this.connectorName); } - if (this.queueName == null || this.queueName.trim().equals("")) - { + if (this.queueName == null || this.queueName.trim().equals("")) { throw new Exception("invalid queue name: " + queueName); } SimpleString name = new SimpleString(this.queueName); Binding b = this.postOffice.getBinding(name); - if (b == null) - { + if (b == null) { throw new Exception(connectorName + ": queue " + queueName + " not found"); } this.queue = (Queue) b.getBindable(); @@ -141,10 +128,8 @@ public class OutgoingVertxEventHandler implements Consumer, ConnectorService } @Override - public void stop() throws Exception - { - if (!this.isStarted) - { + public void stop() throws Exception { + if (!this.isStarted) { return; } @@ -159,27 +144,22 @@ public class OutgoingVertxEventHandler implements Consumer, ConnectorService } @Override - public boolean isStarted() - { + public boolean isStarted() { return this.isStarted; } @Override - public String getName() - { + public String getName() { return this.connectorName; } @Override - public HandleStatus handle(MessageReference ref) throws Exception - { - if (filter != null && !filter.match(ref.getMessage())) - { + public HandleStatus handle(MessageReference ref) throws Exception { + if (filter != null && !filter.match(ref.getMessage())) { return HandleStatus.NO_MATCH; } - synchronized (this) - { + synchronized (this) { ref.handled(); ServerMessage message = ref.getMessage(); @@ -188,8 +168,7 @@ public class OutgoingVertxEventHandler implements Consumer, ConnectorService // extract information from message Integer type = message.getIntProperty(VertxConstants.VERTX_MESSAGE_TYPE); - if (type == null) - { + if (type == null) { // log a warning and default to raw bytes ActiveMQVertxLogger.LOGGER.nonVertxMessage(message); type = VertxConstants.TYPE_RAWBYTES; @@ -198,35 +177,29 @@ public class OutgoingVertxEventHandler implements Consumer, ConnectorService // from vertx vertxMsgBody = extractMessageBody(message, type); - if (vertxMsgBody == null) - { + if (vertxMsgBody == null) { return HandleStatus.NO_MATCH; } // send to bus - if (!publish) - { + if (!publish) { eventBus.send(vertxAddress, vertxMsgBody); } - else - { + else { eventBus.publish(vertxAddress, vertxMsgBody); } queue.acknowledge(ref); - ActiveMQVertxLogger.LOGGER.debug(connectorName + ": forwarded to vertx: " - + message.getMessageID()); + ActiveMQVertxLogger.LOGGER.debug(connectorName + ": forwarded to vertx: " + message.getMessageID()); return HandleStatus.HANDLED; } } - private Object extractMessageBody(ServerMessage message, Integer type) throws Exception - { + private Object extractMessageBody(ServerMessage message, Integer type) throws Exception { Object vertxMsgBody = null; ActiveMQBuffer bodyBuffer = message.getBodyBuffer(); - switch (type) - { + switch (type) { case VertxConstants.TYPE_PING: case VertxConstants.TYPE_STRING: bodyBuffer.resetReaderIndex(); @@ -278,8 +251,7 @@ public class OutgoingVertxEventHandler implements Consumer, ConnectorService int failureType = bodyBuffer.readInt(); int failureCode = bodyBuffer.readInt(); String errMsg = bodyBuffer.readString(); - vertxMsgBody = new ReplyException(ReplyFailure.fromInt(failureType), failureCode, - errMsg); + vertxMsgBody = new ReplyException(ReplyFailure.fromInt(failureType), failureCode, errMsg); break; case VertxConstants.TYPE_RAWBYTES: int size = bodyBuffer.readableBytes(); @@ -295,38 +267,32 @@ public class OutgoingVertxEventHandler implements Consumer, ConnectorService } @Override - public void proceedDeliver(MessageReference reference) throws Exception - { + public void proceedDeliver(MessageReference reference) throws Exception { // no op } @Override - public Filter getFilter() - { + public Filter getFilter() { return this.filter; } @Override - public String debug() - { + public String debug() { return null; } @Override - public String toManagementString() - { + public String toManagementString() { return null; } @Override - public List getDeliveringMessages() - { + public List getDeliveringMessages() { return null; } @Override - public void disconnect() - { + public void disconnect() { } } diff --git a/integration/activemq-vertx-integration/src/main/java/org/apache/activemq/artemis/integration/vertx/VertxConstants.java b/integration/activemq-vertx-integration/src/main/java/org/apache/activemq/artemis/integration/vertx/VertxConstants.java index ca14816cd3..209dda5edc 100644 --- a/integration/activemq-vertx-integration/src/main/java/org/apache/activemq/artemis/integration/vertx/VertxConstants.java +++ b/integration/activemq-vertx-integration/src/main/java/org/apache/activemq/artemis/integration/vertx/VertxConstants.java @@ -19,8 +19,8 @@ package org.apache.activemq.artemis.integration.vertx; import java.util.HashSet; import java.util.Set; -public class VertxConstants -{ +public class VertxConstants { + // org.vertx.java.core.eventbus.impl.MessageFactory public static final int TYPE_PING = 0; public static final int TYPE_BUFFER = 1; @@ -39,7 +39,6 @@ public class VertxConstants public static final int TYPE_REPLY_FAILURE = 100; public static final int TYPE_RAWBYTES = 200; - public static final String PORT = "port"; public static final String HOST = "host"; public static final String QUEUE_NAME = "queue"; @@ -56,8 +55,7 @@ public class VertxConstants public static final String VERTX_MESSAGE_REPLYADDRESS = "VertxMessageReplyAddress"; public static final String VERTX_MESSAGE_TYPE = "VertxMessageType"; - static - { + static { ALLOWABLE_INCOMING_CONNECTOR_KEYS = new HashSet(); ALLOWABLE_INCOMING_CONNECTOR_KEYS.add(PORT); ALLOWABLE_INCOMING_CONNECTOR_KEYS.add(HOST); diff --git a/integration/activemq-vertx-integration/src/main/java/org/apache/activemq/artemis/integration/vertx/VertxIncomingConnectorServiceFactory.java b/integration/activemq-vertx-integration/src/main/java/org/apache/activemq/artemis/integration/vertx/VertxIncomingConnectorServiceFactory.java index a91fa0f011..58d20e800f 100644 --- a/integration/activemq-vertx-integration/src/main/java/org/apache/activemq/artemis/integration/vertx/VertxIncomingConnectorServiceFactory.java +++ b/integration/activemq-vertx-integration/src/main/java/org/apache/activemq/artemis/integration/vertx/VertxIncomingConnectorServiceFactory.java @@ -25,29 +25,26 @@ import org.apache.activemq.artemis.core.postoffice.PostOffice; import org.apache.activemq.artemis.core.server.ConnectorService; import org.apache.activemq.artemis.core.server.ConnectorServiceFactory; -public class VertxIncomingConnectorServiceFactory implements ConnectorServiceFactory -{ +public class VertxIncomingConnectorServiceFactory implements ConnectorServiceFactory { @Override public ConnectorService createConnectorService(String connectorName, - Map configuration, StorageManager storageManager, - PostOffice postOffice, ScheduledExecutorService scheduledThreadPool) - { + Map configuration, + StorageManager storageManager, + PostOffice postOffice, + ScheduledExecutorService scheduledThreadPool) { - return new IncomingVertxEventHandler(connectorName, configuration, storageManager, - postOffice, scheduledThreadPool); + return new IncomingVertxEventHandler(connectorName, configuration, storageManager, postOffice, scheduledThreadPool); } @Override - public Set getAllowableProperties() - { + public Set getAllowableProperties() { return VertxConstants.ALLOWABLE_INCOMING_CONNECTOR_KEYS; } @Override - public Set getRequiredProperties() - { + public Set getRequiredProperties() { return VertxConstants.REQUIRED_INCOMING_CONNECTOR_KEYS; } diff --git a/integration/activemq-vertx-integration/src/main/java/org/apache/activemq/artemis/integration/vertx/VertxOutgoingConnectorServiceFactory.java b/integration/activemq-vertx-integration/src/main/java/org/apache/activemq/artemis/integration/vertx/VertxOutgoingConnectorServiceFactory.java index 0ecc995946..7c92bc7f0b 100644 --- a/integration/activemq-vertx-integration/src/main/java/org/apache/activemq/artemis/integration/vertx/VertxOutgoingConnectorServiceFactory.java +++ b/integration/activemq-vertx-integration/src/main/java/org/apache/activemq/artemis/integration/vertx/VertxOutgoingConnectorServiceFactory.java @@ -25,27 +25,24 @@ import org.apache.activemq.artemis.core.postoffice.PostOffice; import org.apache.activemq.artemis.core.server.ConnectorService; import org.apache.activemq.artemis.core.server.ConnectorServiceFactory; -public class VertxOutgoingConnectorServiceFactory implements ConnectorServiceFactory -{ +public class VertxOutgoingConnectorServiceFactory implements ConnectorServiceFactory { @Override public ConnectorService createConnectorService(String connectorName, - Map configuration, StorageManager storageManager, - PostOffice postOffice, ScheduledExecutorService scheduledThreadPool) - { - return new OutgoingVertxEventHandler(connectorName, configuration, storageManager, - postOffice, scheduledThreadPool); + Map configuration, + StorageManager storageManager, + PostOffice postOffice, + ScheduledExecutorService scheduledThreadPool) { + return new OutgoingVertxEventHandler(connectorName, configuration, storageManager, postOffice, scheduledThreadPool); } @Override - public Set getAllowableProperties() - { + public Set getAllowableProperties() { return VertxConstants.ALLOWABLE_OUTGOING_CONNECTOR_KEYS; } @Override - public Set getRequiredProperties() - { + public Set getRequiredProperties() { return VertxConstants.REQUIRED_OUTGOING_CONNECTOR_KEYS; } diff --git a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/ActiveMQConnectionFactory.java b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/ActiveMQConnectionFactory.java index 0de77f7b74..e6d835ee14 100644 --- a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/ActiveMQConnectionFactory.java +++ b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/ActiveMQConnectionFactory.java @@ -55,11 +55,13 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ActiveMQConnectionFactory extends JNDIBaseStorable implements ConnectionFactory, QueueConnectionFactory, TopicConnectionFactory, StatsCapable, Cloneable { + private static final Logger LOG = LoggerFactory.getLogger(ActiveMQConnectionFactory.class); private static final String DEFAULT_BROKER_HOST; private static final int DEFAULT_BROKER_PORT; private static URI defaultTcpUri; - static{ + + static { String host = null; String port = null; try { @@ -67,7 +69,7 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne @Override public String run() { String result = System.getProperty("org.apache.activemq.AMQ_HOST"); - result = (result==null||result.isEmpty()) ? System.getProperty("AMQ_HOST","localhost") : result; + result = (result == null || result.isEmpty()) ? System.getProperty("AMQ_HOST", "localhost") : result; return result; } }); @@ -75,12 +77,13 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne @Override public String run() { String result = System.getProperty("org.apache.activemq.AMQ_PORT"); - result = (result==null||result.isEmpty()) ? System.getProperty("AMQ_PORT","61616") : result; + result = (result == null || result.isEmpty()) ? System.getProperty("AMQ_PORT", "61616") : result; return result; } }); - }catch(Throwable e){ - LOG.debug("Failed to look up System properties for host and port",e); + } + catch (Throwable e) { + LOG.debug("Failed to look up System properties for host and port", e); } host = (host == null || host.isEmpty()) ? "localhost" : host; port = (port == null || port.isEmpty()) ? "61616" : port; @@ -88,10 +91,9 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne DEFAULT_BROKER_PORT = Integer.parseInt(port); } - public static final String DEFAULT_BROKER_BIND_URL; - static{ + static { final String defaultURL = "tcp://" + DEFAULT_BROKER_HOST + ":" + DEFAULT_BROKER_PORT; String bindURL = null; @@ -100,24 +102,26 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne @Override public String run() { String result = System.getProperty("org.apache.activemq.BROKER_BIND_URL"); - result = (result==null||result.isEmpty()) ? System.getProperty("BROKER_BIND_URL",defaultURL) : result; + result = (result == null || result.isEmpty()) ? System.getProperty("BROKER_BIND_URL", defaultURL) : result; return result; } }); - }catch(Throwable e){ - LOG.debug("Failed to look up System properties for host and port",e); + } + catch (Throwable e) { + LOG.debug("Failed to look up System properties for host and port", e); } bindURL = (bindURL == null || bindURL.isEmpty()) ? defaultURL : bindURL; DEFAULT_BROKER_BIND_URL = bindURL; - try { - defaultTcpUri = new URI(defaultURL); - } catch (URISyntaxException e) { - LOG.debug("Failed to build default tcp url",e); - } + try { + defaultTcpUri = new URI(defaultURL); + } + catch (URISyntaxException e) { + LOG.debug("Failed to build default tcp url", e); + } } - public static final String DEFAULT_BROKER_URL = "failover://"+DEFAULT_BROKER_BIND_URL; + public static final String DEFAULT_BROKER_URL = "failover://" + DEFAULT_BROKER_BIND_URL; public static final String DEFAULT_USER = null; public static final String DEFAULT_PASSWORD = null; public static final int DEFAULT_PRODUCER_WINDOW_SIZE = 0; @@ -127,8 +131,8 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne protected String userName; protected String password; protected String clientID; - protected boolean dispatchAsync=true; - protected boolean alwaysSessionAsync=true; + protected boolean dispatchAsync = true; + protected boolean alwaysSessionAsync = true; JMSStatsImpl factoryStats = new JMSStatsImpl(); @@ -140,9 +144,11 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne // client policies private ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); private RedeliveryPolicyMap redeliveryPolicyMap = new RedeliveryPolicyMap(); + { redeliveryPolicyMap.setDefaultEntry(new RedeliveryPolicy()); } + private BlobTransferPolicy blobTransferPolicy = new BlobTransferPolicy(); private MessageTransformer transformer; @@ -164,7 +170,7 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne private int producerWindowSize = DEFAULT_PRODUCER_WINDOW_SIZE; private long warnAboutUnstartedConnectionTimeout = 500L; private int sendTimeout = 0; - private boolean sendAcksAsync=true; + private boolean sendAcksAsync = true; private TransportListener transportListener; private ExceptionListener exceptionListener; private int auditDepth = ActiveMQMessageAudit.DEFAULT_WINDOW_SIZE; @@ -195,19 +201,18 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne public ActiveMQConnectionFactory(String brokerURL) { this(createURI(brokerURL)); - try - { + try { URI uri = new URI(brokerURL); String scheme = uri.getScheme(); if ("vm".equals(scheme)) { Map params = URISupport.parseParameters(uri); params.clear(); - this.vmBrokerUri = URISupport.createRemainingURI(uri, params);; + this.vmBrokerUri = URISupport.createRemainingURI(uri, params); + ; } } - catch (URISyntaxException e) - { + catch (URISyntaxException e) { } } @@ -230,8 +235,9 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne public ActiveMQConnectionFactory copy() { try { - return (ActiveMQConnectionFactory)super.clone(); - } catch (CloneNotSupportedException e) { + return (ActiveMQConnectionFactory) super.clone(); + } + catch (CloneNotSupportedException e) { throw new RuntimeException("This should never happen: " + e, e); } } @@ -241,18 +247,19 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne URI uri = new URI(brokerURL); String scheme = uri.getScheme(); if ("vm".equals(scheme)) { - Map params = URISupport.parseParameters(uri); - //EMPTY_MAP is immutable, so use a normal map instead. - if (params == Collections.EMPTY_MAP) { - params = new HashMap(); - } - params.put("invmBrokerId", uri.getHost() == null ? "localhost" : uri.getHost()); - defaultTcpUri = URISupport.createRemainingURI(defaultTcpUri, params); - return defaultTcpUri; + Map params = URISupport.parseParameters(uri); + //EMPTY_MAP is immutable, so use a normal map instead. + if (params == Collections.EMPTY_MAP) { + params = new HashMap(); + } + params.put("invmBrokerId", uri.getHost() == null ? "localhost" : uri.getHost()); + defaultTcpUri = URISupport.createRemainingURI(defaultTcpUri, params); + return defaultTcpUri; } return uri; - } catch (URISyntaxException e) { - throw (IllegalArgumentException)new IllegalArgumentException("Invalid broker URI: " + brokerURL).initCause(e); + } + catch (URISyntaxException e) { + throw (IllegalArgumentException) new IllegalArgumentException("Invalid broker URI: " + brokerURL).initCause(e); } } @@ -307,7 +314,8 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne Transport t = TransportFactory.connect(brokerURL); System.out.println("xxxxxxxxxxxx created transport" + t); return t; - } catch (Exception e) { + } + catch (Exception e) { throw JMSExceptionSupport.create("Could not create Transport. Reason: " + e, e); } } @@ -333,26 +341,29 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne } return connection; - } catch (JMSException e) { + } + catch (JMSException e) { // Clean up! try { connection.close(); - } catch (Throwable ignore) { + } + catch (Throwable ignore) { } throw e; - } catch (Exception e) { + } + catch (Exception e) { // Clean up! try { connection.close(); - } catch (Throwable ignore) { + } + catch (Throwable ignore) { } throw JMSExceptionSupport.create("Could not connect to broker URL: " + brokerURL + ". Reason: " + e, e); } } protected ActiveMQConnection createActiveMQConnection(Transport transport, JMSStatsImpl stats) throws Exception { - ActiveMQConnection connection = new ActiveMQConnection(transport, getClientIdGenerator(), - getConnectionIdGenerator(), stats); + ActiveMQConnection connection = new ActiveMQConnection(transport, getClientIdGenerator(), getConnectionIdGenerator(), stats); return connection; } @@ -414,22 +425,21 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne public String getBrokerURL() { System.out.println("vm uri: " + vmBrokerUri); - if (vmBrokerUri != null) return vmBrokerUri.toString(); + if (vmBrokerUri != null) + return vmBrokerUri.toString(); return brokerURL == null ? null : brokerURL.toString(); } public void setBrokerURL(String brokerURL) { URI uri = null; - try - { + try { uri = new URI(brokerURL); String scheme = uri.getScheme(); if ("vm".equals(scheme)) { this.vmBrokerUri = uri; } } - catch (URISyntaxException e) - { + catch (URISyntaxException e) { } this.brokerURL = createURI(brokerURL); @@ -440,43 +450,38 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne // It might be a standard URI or... try { - Map map = URISupport.parseQuery(this.brokerURL.getQuery()); - Map jmsOptionsMap = IntrospectionSupport.extractProperties(map, "jms."); + Map map = URISupport.parseQuery(this.brokerURL.getQuery()); + Map jmsOptionsMap = IntrospectionSupport.extractProperties(map, "jms."); if (buildFromMap(jmsOptionsMap)) { if (!jmsOptionsMap.isEmpty()) { - String msg = "There are " + jmsOptionsMap.size() - + " jms options that couldn't be set on the ConnectionFactory." - + " Check the options are spelled correctly." - + " Unknown parameters=[" + jmsOptionsMap + "]." - + " This connection factory cannot be started."; + String msg = "There are " + jmsOptionsMap.size() + " jms options that couldn't be set on the ConnectionFactory." + " Check the options are spelled correctly." + " Unknown parameters=[" + jmsOptionsMap + "]." + " This connection factory cannot be started."; throw new IllegalArgumentException(msg); } this.brokerURL = URISupport.createRemainingURI(this.brokerURL, map); } - } catch (URISyntaxException e) { + } + catch (URISyntaxException e) { } - } else { + } + else { // It might be a composite URI. try { CompositeData data = URISupport.parseComposite(this.brokerURL); - Map jmsOptionsMap = IntrospectionSupport.extractProperties(data.getParameters(), "jms."); + Map jmsOptionsMap = IntrospectionSupport.extractProperties(data.getParameters(), "jms."); if (buildFromMap(jmsOptionsMap)) { if (!jmsOptionsMap.isEmpty()) { - String msg = "There are " + jmsOptionsMap.size() - + " jms options that couldn't be set on the ConnectionFactory." - + " Check the options are spelled correctly." - + " Unknown parameters=[" + jmsOptionsMap + "]." - + " This connection factory cannot be started."; + String msg = "There are " + jmsOptionsMap.size() + " jms options that couldn't be set on the ConnectionFactory." + " Check the options are spelled correctly." + " Unknown parameters=[" + jmsOptionsMap + "]." + " This connection factory cannot be started."; throw new IllegalArgumentException(msg); } this.brokerURL = data.toURI(); } - } catch (URISyntaxException e) { + } + catch (URISyntaxException e) { } } } @@ -629,12 +634,11 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne this.messagePrioritySupported = messagePrioritySupported; } - public void setTransformer(MessageTransformer transformer) { this.transformer = transformer; } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Override public void buildFromProperties(Properties properties) { @@ -722,7 +726,7 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne props.setProperty("alwaysSyncSend", Boolean.toString(isAlwaysSyncSend())); props.setProperty("producerWindowSize", Integer.toString(getProducerWindowSize())); props.setProperty("sendTimeout", Integer.toString(getSendTimeout())); - props.setProperty("sendAcksAsync",Boolean.toString(isSendAcksAsync())); + props.setProperty("sendAcksAsync", Boolean.toString(isSendAcksAsync())); props.setProperty("auditDepth", Integer.toString(getAuditDepth())); props.setProperty("auditMaximumProducerNumber", Integer.toString(getAuditMaximumProducerNumber())); props.setProperty("checkForDuplicates", Boolean.toString(isCheckForDuplicates())); @@ -785,7 +789,7 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne } public void setOptimizeAcknowledgeTimeOut(long optimizeAcknowledgeTimeOut) { - this.optimizeAcknowledgeTimeOut = optimizeAcknowledgeTimeOut; + this.optimizeAcknowledgeTimeOut = optimizeAcknowledgeTimeOut; } public long getOptimizeAcknowledgeTimeOut() { @@ -812,7 +816,8 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne if (clientIdGenerator == null) { if (clientIDPrefix != null) { clientIdGenerator = new IdGenerator(clientIDPrefix); - } else { + } + else { clientIdGenerator = new IdGenerator(); } } @@ -831,7 +836,8 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne if (connectionIdGenerator == null) { if (connectionIDPrefix != null) { connectionIdGenerator = new IdGenerator(connectionIDPrefix); - } else { + } + else { connectionIdGenerator = new IdGenerator(); } } @@ -874,7 +880,6 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne this.transportListener = transportListener; } - public ExceptionListener getExceptionListener() { return exceptionListener; } @@ -919,8 +924,7 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne return clientInternalExceptionListener; } - public void setClientInternalExceptionListener( - ClientInternalExceptionListener clientInternalExceptionListener) { + public void setClientInternalExceptionListener(ClientInternalExceptionListener clientInternalExceptionListener) { this.clientInternalExceptionListener = clientInternalExceptionListener; } @@ -940,7 +944,6 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne this.transactedIndividualAck = transactedIndividualAck; } - public boolean isNonBlockingRedelivery() { return nonBlockingRedelivery; } @@ -981,7 +984,6 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne this.optimizedAckScheduledAckInterval = optimizedAckScheduledAckInterval; } - public boolean isRmIdFromConnectionId() { return rmIdFromConnectionId; } diff --git a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/artemiswrapper/ArtemisBrokerHelper.java b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/artemiswrapper/ArtemisBrokerHelper.java index d58688627b..bc4bb119c9 100644 --- a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/artemiswrapper/ArtemisBrokerHelper.java +++ b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/artemiswrapper/ArtemisBrokerHelper.java @@ -32,11 +32,13 @@ public class ArtemisBrokerHelper { static { try { serviceClass = Class.forName("org.apache.activemq.broker.BrokerService"); - } catch (ClassNotFoundException e) { + } + catch (ClassNotFoundException e) { e.printStackTrace(); } } + // start a tcp transport artemis broker, the broker need to // be invm with client. public static void startArtemisBroker(URI location) throws IOException { @@ -47,17 +49,23 @@ public class ArtemisBrokerHelper { service = serviceClass.newInstance(); Method startMethod = serviceClass.getMethod("start"); startMethod.invoke(service, (Object[]) null); - } catch (InstantiationException e) { + } + catch (InstantiationException e) { throw new IOException("Inst exception", e); - } catch (IllegalAccessException e) { + } + catch (IllegalAccessException e) { throw new IOException("IllegalAccess exception ", e); - } catch (NoSuchMethodException e) { + } + catch (NoSuchMethodException e) { throw new IOException("Nosuchmethod", e); - } catch (SecurityException e) { + } + catch (SecurityException e) { throw new IOException("Security exception", e); - } catch (IllegalArgumentException e) { + } + catch (IllegalArgumentException e) { throw new IOException("IllegalArgumentException exception", e); - } catch (InvocationTargetException e) { + } + catch (InvocationTargetException e) { throw new IOException("InvocationTargetException exception", e); } } @@ -74,21 +82,17 @@ public class ArtemisBrokerHelper { } public static BrokerService getBroker() { - return (BrokerService)service; + return (BrokerService) service; } - public static void stopArtemisBroker() throws Exception - { - try - { - if (service != null) - { + public static void stopArtemisBroker() throws Exception { + try { + if (service != null) { Method startMethod = serviceClass.getMethod("stop"); startMethod.invoke(service, (Object[]) null); } } - finally - { + finally { service = null; } } diff --git a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/BrokerService.java b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/BrokerService.java index 8ce8fd950b..b46c3461c4 100644 --- a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/BrokerService.java +++ b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/BrokerService.java @@ -63,10 +63,9 @@ import org.slf4j.LoggerFactory; * Manages the life-cycle of an ActiveMQ Broker. A BrokerService consists of a * number of transport connectors, network connectors and a bunch of properties * which can be used to configure the broker as its lazily created. - * */ -public class BrokerService implements Service -{ +public class BrokerService implements Service { + public static final String DEFAULT_PORT = "61616"; public static final String DEFAULT_BROKER_NAME = "localhost"; public static final String BROKER_VERSION; @@ -99,81 +98,63 @@ public class BrokerService implements Service public static WeakHashMap map = new WeakHashMap<>(); - static - { + static { InputStream in; String version = null; - if ((in = BrokerService.class.getResourceAsStream("/org/apache/activemq/version.txt")) != null) - { + if ((in = BrokerService.class.getResourceAsStream("/org/apache/activemq/version.txt")) != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); - try - { + try { version = reader.readLine(); } - catch (Exception e) - { + catch (Exception e) { } } BROKER_VERSION = version; } @Override - public String toString() - { + public String toString() { return "BrokerService[" + getBrokerName() + "]"; } - private String getBrokerVersion() - { + private String getBrokerVersion() { String version = ActiveMQConnectionMetaData.PROVIDER_VERSION; - if (version == null) - { + if (version == null) { version = BROKER_VERSION; } return version; } - @Override - public void start() throws Exception - { + public void start() throws Exception { Exception e = new Exception(); e.fillInStackTrace(); startBroker(startAsync); map.put(broker, e); } - private void startBroker(boolean async) throws Exception - { - if (async) - { - new Thread("Broker Starting Thread") - { + private void startBroker(boolean async) throws Exception { + if (async) { + new Thread("Broker Starting Thread") { @Override - public void run() - { - try - { + public void run() { + try { doStartBroker(); } - catch (Throwable t) - { + catch (Throwable t) { startException = t; } } }.start(); } - else - { + else { doStartBroker(); } } - private void doStartBroker() throws Exception - { - if (startException != null) - { + private void doStartBroker() throws Exception { + if (startException != null) { return; } @@ -182,16 +163,13 @@ public class BrokerService implements Service LOG.info("Apache ActiveMQ Artemis Wrapper {} ({}, {}) is starting", new Object[]{getBrokerVersion(), getBrokerName(), brokerId}); - try - { + try { broker.start(); } - catch (Exception e) - { + catch (Exception e) { throw e; } - catch (Throwable t) - { + catch (Throwable t) { throw new Exception(t); } @@ -201,14 +179,12 @@ public class BrokerService implements Service } @Override - public void stop() throws Exception - { + public void stop() throws Exception { System.out.println("broker is: " + broker); LOG.info("Apache ActiveMQ Artemis{} ({}, {}) is shutting down", new Object[]{getBrokerVersion(), getBrokerName(), brokerId}); - if (broker != null) - { + if (broker != null) { System.out.println("______________________stopping broker: " + broker.getClass().getName()); broker.stop(); broker = null; @@ -219,63 +195,51 @@ public class BrokerService implements Service // Properties // ------------------------------------------------------------------------- - public Broker getBroker() throws Exception - { - if (broker == null) - { + public Broker getBroker() throws Exception { + if (broker == null) { broker = createBroker(); } return broker; } - public String getBrokerName() - { + public String getBrokerName() { return brokerName; } - public void setBrokerName(String brokerName) - { - if (brokerName == null) - { + public void setBrokerName(String brokerName) { + if (brokerName == null) { throw new NullPointerException("The broker name cannot be null"); } String str = brokerName.replaceAll("[^a-zA-Z0-9\\.\\_\\-\\:]", "_"); - if (!str.equals(brokerName)) - { + if (!str.equals(brokerName)) { LOG.error("Broker Name: {} contained illegal characters - replaced with {}", brokerName, str); } this.brokerName = str.trim(); } - protected Broker createBroker() throws Exception - { + protected Broker createBroker() throws Exception { broker = createBrokerWrapper(); return broker; } - private Broker createBrokerWrapper() - { + private Broker createBrokerWrapper() { return new ArtemisBrokerWrapper(this); } - public void makeSureDestinationExists(ActiveMQDestination activemqDestination) throws Exception - { + public void makeSureDestinationExists(ActiveMQDestination activemqDestination) throws Exception { ArtemisBrokerWrapper hqBroker = (ArtemisBrokerWrapper) this.broker; //it can be null - if (activemqDestination == null) - { + if (activemqDestination == null) { return; } - if (activemqDestination.isQueue()) - { + if (activemqDestination.isQueue()) { String qname = activemqDestination.getPhysicalName(); System.out.println("physical name: " + qname); hqBroker.makeSureQueueExists(qname); } } - public boolean enableSsl() - { + public boolean enableSsl() { return this.SERVER_SIDE_KEYSTORE != null; } @@ -286,413 +250,325 @@ public class BrokerService implements Service //we may get class cast exception as in TestSupport it //casts the broker to RegionBroker, which we didn't //implement (wrap) yet. Consider solving it later. - public Broker getRegionBroker() - { + public Broker getRegionBroker() { return broker; } - public void setPersistenceAdapter(PersistenceAdapter persistenceAdapter) throws IOException - { + public void setPersistenceAdapter(PersistenceAdapter persistenceAdapter) throws IOException { } - public File getDataDirectoryFile() - { - if (dataDirectoryFile == null) - { + public File getDataDirectoryFile() { + if (dataDirectoryFile == null) { dataDirectoryFile = new File(IOHelper.getDefaultDataDirectory()); } return dataDirectoryFile; } - public File getBrokerDataDirectory() - { + public File getBrokerDataDirectory() { String brokerDir = getBrokerName(); return new File(getDataDirectoryFile(), brokerDir); } - public PersistenceAdapter getPersistenceAdapter() throws IOException - { + public PersistenceAdapter getPersistenceAdapter() throws IOException { return null; } - public void waitUntilStopped() - { + public void waitUntilStopped() { } - public boolean waitUntilStarted() - { + public boolean waitUntilStarted() { return true; } - public void setDestinationPolicy(PolicyMap policyMap) - { + public void setDestinationPolicy(PolicyMap policyMap) { this.destinationPolicy = policyMap; } - public void setDeleteAllMessagesOnStartup(boolean deletePersistentMessagesOnStartup) - { + public void setDeleteAllMessagesOnStartup(boolean deletePersistentMessagesOnStartup) { } - public void setUseJmx(boolean useJmx) - { + public void setUseJmx(boolean useJmx) { } - public ManagementContext getManagementContext() - { + public ManagementContext getManagementContext() { return null; } - public BrokerView getAdminView() throws Exception - { + public BrokerView getAdminView() throws Exception { return null; } - public List getTransportConnectors() - { + public List getTransportConnectors() { return transportConnectors; } - public TransportConnector addConnector(String bindAddress) throws Exception - { + public TransportConnector addConnector(String bindAddress) throws Exception { return addConnector(new URI(bindAddress)); } - public void setIoExceptionHandler(IOExceptionHandler ioExceptionHandler) - { + public void setIoExceptionHandler(IOExceptionHandler ioExceptionHandler) { } - public void setPersistent(boolean persistent) - { + public void setPersistent(boolean persistent) { } - public boolean isSlave() - { + public boolean isSlave() { return false; } - public Destination getDestination(ActiveMQDestination destination) throws Exception - { + public Destination getDestination(ActiveMQDestination destination) throws Exception { return null; } - public void setAllowTempAutoCreationOnSend(boolean allowTempAutoCreationOnSend) - { + public void setAllowTempAutoCreationOnSend(boolean allowTempAutoCreationOnSend) { } - public void setDedicatedTaskRunner(boolean dedicatedTaskRunner) - { + public void setDedicatedTaskRunner(boolean dedicatedTaskRunner) { } - public void setAdvisorySupport(boolean advisorySupport) - { + public void setAdvisorySupport(boolean advisorySupport) { } - public void setUseShutdownHook(boolean useShutdownHook) - { + public void setUseShutdownHook(boolean useShutdownHook) { } - public void deleteAllMessages() throws IOException - { + public void deleteAllMessages() throws IOException { } - public Service[] getServices() - { + public Service[] getServices() { return null; } - public void setPopulateUserNameInMBeans(boolean value) - { + public void setPopulateUserNameInMBeans(boolean value) { } - public void setDestinations(ActiveMQDestination[] destinations) - { + public void setDestinations(ActiveMQDestination[] destinations) { } - public URI getVmConnectorURI() - { + public URI getVmConnectorURI() { return null; } - public SystemUsage getSystemUsage() - { - if (systemUsage == null) - { + public SystemUsage getSystemUsage() { + if (systemUsage == null) { systemUsage = new SystemUsage(); } return systemUsage; } - public synchronized PListStore getTempDataStore() - { + public synchronized PListStore getTempDataStore() { return null; } - public void setJmsBridgeConnectors(JmsConnector[] jmsConnectors) - { + public void setJmsBridgeConnectors(JmsConnector[] jmsConnectors) { } - public void setDestinationInterceptors(DestinationInterceptor[] destinationInterceptors) - { + public void setDestinationInterceptors(DestinationInterceptor[] destinationInterceptors) { } - public SslContext getSslContext() - { + public SslContext getSslContext() { return null; } - public void setDataDirectory(String dataDirectory) - { + public void setDataDirectory(String dataDirectory) { } - public void setPlugins(BrokerPlugin[] plugins) - { + public void setPlugins(BrokerPlugin[] plugins) { } - public void setKeepDurableSubsActive(boolean keepDurableSubsActive) - { + public void setKeepDurableSubsActive(boolean keepDurableSubsActive) { } - public NetworkConnector addNetworkConnector(String discoveryAddress) throws Exception - { + public NetworkConnector addNetworkConnector(String discoveryAddress) throws Exception { return null; } - public TransportConnector getConnectorByName(String connectorName) - { + public TransportConnector getConnectorByName(String connectorName) { return null; } - public TransportConnector addConnector(TransportConnector connector) throws Exception - { + public TransportConnector addConnector(TransportConnector connector) throws Exception { return connector; } - public void setEnableStatistics(boolean enableStatistics) - { + public void setEnableStatistics(boolean enableStatistics) { } - public void setSystemUsage(SystemUsage memoryManager) - { + public void setSystemUsage(SystemUsage memoryManager) { this.systemUsage = memoryManager; } - public void setManagementContext(ManagementContext managementContext) - { + public void setManagementContext(ManagementContext managementContext) { } - public void setSchedulerDirectoryFile(File schedulerDirectory) - { + public void setSchedulerDirectoryFile(File schedulerDirectory) { } - public List getNetworkConnectors() - { + public List getNetworkConnectors() { return new ArrayList<>(); } - public void setSchedulerSupport(boolean schedulerSupport) - { + public void setSchedulerSupport(boolean schedulerSupport) { } - public void setPopulateJMSXUserID(boolean populateJMSXUserID) - { + public void setPopulateJMSXUserID(boolean populateJMSXUserID) { } - public boolean isUseJmx() - { + public boolean isUseJmx() { return false; } - public boolean isPersistent() - { + public boolean isPersistent() { return false; } - public TransportConnector getTransportConnectorByScheme(String scheme) - { + public TransportConnector getTransportConnectorByScheme(String scheme) { return null; } - public TaskRunnerFactory getTaskRunnerFactory() - { + public TaskRunnerFactory getTaskRunnerFactory() { return null; } - public boolean isStarted() - { - if (broker == null) return false; + public boolean isStarted() { + if (broker == null) + return false; return !broker.isStopped(); } - public ProxyConnector addProxyConnector(ProxyConnector connector) throws Exception - { + public ProxyConnector addProxyConnector(ProxyConnector connector) throws Exception { return connector; } - public void setDataDirectoryFile(File dataDirectoryFile) - { + public void setDataDirectoryFile(File dataDirectoryFile) { this.dataDirectoryFile = dataDirectoryFile; } - public PolicyMap getDestinationPolicy() - { + public PolicyMap getDestinationPolicy() { return this.destinationPolicy; } - public void setTransportConnectorURIs(String[] transportConnectorURIs) - { + public void setTransportConnectorURIs(String[] transportConnectorURIs) { } - public boolean isPopulateJMSXUserID() - { + public boolean isPopulateJMSXUserID() { return false; } - public NetworkConnector getNetworkConnectorByName(String connectorName) - { + public NetworkConnector getNetworkConnectorByName(String connectorName) { return null; } - public boolean removeNetworkConnector(NetworkConnector connector) - { + public boolean removeNetworkConnector(NetworkConnector connector) { return true; } - public void setTransportConnectors(List transportConnectors) throws Exception - { + public void setTransportConnectors(List transportConnectors) throws Exception { } - public NetworkConnector addNetworkConnector(NetworkConnector connector) throws Exception - { + public NetworkConnector addNetworkConnector(NetworkConnector connector) throws Exception { return connector; } - public void setTempDataStore(PListStore tempDataStore) - { + public void setTempDataStore(PListStore tempDataStore) { } - public void setJobSchedulerStore(JobSchedulerStore jobSchedulerStore) - { + public void setJobSchedulerStore(JobSchedulerStore jobSchedulerStore) { } - public ObjectName getBrokerObjectName() throws MalformedObjectNameException - { + public ObjectName getBrokerObjectName() throws MalformedObjectNameException { return null; } - public TransportConnector addConnector(URI bindAddress) throws Exception - { + public TransportConnector addConnector(URI bindAddress) throws Exception { Integer port = bindAddress.getPort(); FakeTransportConnector connector = null; - if (port != 0) - { + if (port != 0) { connector = new FakeTransportConnector(bindAddress); this.transportConnectors.add(connector); this.extraConnectors.add(port); } - else - { + else { connector = new FakeTransportConnector(new URI(this.getDefaultUri())); this.transportConnectors.add(connector); } return connector; } - public void setCacheTempDestinations(boolean cacheTempDestinations) - { + public void setCacheTempDestinations(boolean cacheTempDestinations) { } - public void setOfflineDurableSubscriberTimeout(long offlineDurableSubscriberTimeout) - { + public void setOfflineDurableSubscriberTimeout(long offlineDurableSubscriberTimeout) { } - public void setOfflineDurableSubscriberTaskSchedule(long offlineDurableSubscriberTaskSchedule) - { + public void setOfflineDurableSubscriberTaskSchedule(long offlineDurableSubscriberTaskSchedule) { } - public boolean isStopped() - { + public boolean isStopped() { return broker != null ? broker.isStopped() : true; } - public void setBrokerId(String brokerId) - { + public void setBrokerId(String brokerId) { } - public BrokerPlugin[] getPlugins() - { + public BrokerPlugin[] getPlugins() { return null; } - public void stopAllConnectors(ServiceStopper stopper) - { + public void stopAllConnectors(ServiceStopper stopper) { } - public void setMessageAuthorizationPolicy(MessageAuthorizationPolicy messageAuthorizationPolicy) - { + public void setMessageAuthorizationPolicy(MessageAuthorizationPolicy messageAuthorizationPolicy) { } - public void setNetworkConnectorStartAsync(boolean networkConnectorStartAsync) - { + public void setNetworkConnectorStartAsync(boolean networkConnectorStartAsync) { } - public boolean isRestartAllowed() - { + public boolean isRestartAllowed() { return true; } - public void setTaskRunnerFactory(TaskRunnerFactory taskRunnerFactory) - { + public void setTaskRunnerFactory(TaskRunnerFactory taskRunnerFactory) { } - public void start(boolean force) throws Exception - { + public void start(boolean force) throws Exception { this.start(); } - public void setMonitorConnectionSplits(boolean monitorConnectionSplits) - { + public void setMonitorConnectionSplits(boolean monitorConnectionSplits) { } - public void setUseMirroredQueues(boolean useMirroredQueues) - { + public void setUseMirroredQueues(boolean useMirroredQueues) { } - public File getTmpDataDirectory() - { + public File getTmpDataDirectory() { return null; } - public boolean isUseShutdownHook() - { + public boolean isUseShutdownHook() { return true; } - public boolean isDeleteAllMessagesOnStartup() - { + public boolean isDeleteAllMessagesOnStartup() { return false; } - public void setUseVirtualTopics(boolean useVirtualTopics) - { + public void setUseVirtualTopics(boolean useVirtualTopics) { } - public boolean isUseLoggingForShutdownErrors() - { + public boolean isUseLoggingForShutdownErrors() { return true; } - public TransportConnector addConnector(TransportServer transport) throws Exception - { + public TransportConnector addConnector(TransportServer transport) throws Exception { return null; } - public synchronized JobSchedulerStore getJobSchedulerStore() - { + public synchronized JobSchedulerStore getJobSchedulerStore() { return null; } - public boolean removeConnector(TransportConnector connector) throws Exception - { + public boolean removeConnector(TransportConnector connector) throws Exception { return true; } @@ -700,71 +576,54 @@ public class BrokerService implements Service return null; } - public void setUseAuthenticatedPrincipalForJMSXUserID(boolean useAuthenticatedPrincipalForJMSXUserID) - { + public void setUseAuthenticatedPrincipalForJMSXUserID(boolean useAuthenticatedPrincipalForJMSXUserID) { } - public void setSchedulePeriodForDestinationPurge(int schedulePeriodForDestinationPurge) - { + public void setSchedulePeriodForDestinationPurge(int schedulePeriodForDestinationPurge) { } - public void setMbeanInvocationTimeout(long mbeanInvocationTimeout) - { + public void setMbeanInvocationTimeout(long mbeanInvocationTimeout) { } - public void setNetworkConnectors(List networkConnectors) throws Exception - { + public void setNetworkConnectors(List networkConnectors) throws Exception { } - public void removeDestination(ActiveMQDestination destination) throws Exception - { + public void removeDestination(ActiveMQDestination destination) throws Exception { } - public void setMaxPurgedDestinationsPerSweep(int maxPurgedDestinationsPerSweep) - { + public void setMaxPurgedDestinationsPerSweep(int maxPurgedDestinationsPerSweep) { } - public void setBrokerObjectName(ObjectName brokerObjectName) - { + public void setBrokerObjectName(ObjectName brokerObjectName) { } - public Map getTransportConnectorURIsAsMap() - { + public Map getTransportConnectorURIsAsMap() { return null; } - public void setSslContext(SslContext sslContext) - { + public void setSslContext(SslContext sslContext) { } - public void setPersistenceFactory(PersistenceAdapterFactory persistenceFactory) - { + public void setPersistenceFactory(PersistenceAdapterFactory persistenceFactory) { } - protected TransportConnector createTransportConnector(URI brokerURI) throws Exception - { + protected TransportConnector createTransportConnector(URI brokerURI) throws Exception { return null; } - public String getDefaultUri() - { + public String getDefaultUri() { return "tcp://localhost:61616"; } - public static boolean checkStopped() - { + public static boolean checkStopped() { boolean runningBrokers = false; - for (Map.Entry brokerExceptionEntry : map.entrySet()) - { + for (Map.Entry brokerExceptionEntry : map.entrySet()) { Broker b = brokerExceptionEntry.getKey(); - if (!b.isStopped()) - { - try - { + if (!b.isStopped()) { + try { b.stop(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } brokerExceptionEntry.getValue().printStackTrace(); diff --git a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/FakeTransportConnector.java b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/FakeTransportConnector.java index 4d4ab0050e..9fb8233c03 100644 --- a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/FakeTransportConnector.java +++ b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/FakeTransportConnector.java @@ -16,13 +16,11 @@ */ package org.apache.activemq.broker; - import java.net.URI; -public class FakeTransportConnector extends TransportConnector -{ - public FakeTransportConnector(URI uri) - { +public class FakeTransportConnector extends TransportConnector { + + public FakeTransportConnector(URI uri) { super(); this.setUri(uri); } diff --git a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/SslBrokerService.java b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/SslBrokerService.java index 9699cf3f85..2535012ef6 100644 --- a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/SslBrokerService.java +++ b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/SslBrokerService.java @@ -34,28 +34,36 @@ import java.security.SecureRandom; * AND the key and trust managers need to be specified from within code. In * fact, if the URI passed to this class does not have an "ssl" scheme, this * class will pass all work on to its superclass. - * + * * @author sepandm@gmail.com (Sepand) */ -public class SslBrokerService extends BrokerService -{ +public class SslBrokerService extends BrokerService { - public TransportConnector addSslConnector(String bindAddress, KeyManager[] km, TrustManager[] tm, SecureRandom random) throws Exception { - return null; - } + public TransportConnector addSslConnector(String bindAddress, + KeyManager[] km, + TrustManager[] tm, + SecureRandom random) throws Exception { + return null; + } - public TransportConnector addSslConnector(URI bindAddress, KeyManager[] km, TrustManager[] tm, SecureRandom random) throws Exception { - return null; - } + public TransportConnector addSslConnector(URI bindAddress, + KeyManager[] km, + TrustManager[] tm, + SecureRandom random) throws Exception { + return null; + } - protected TransportServer createSslTransportServer(URI brokerURI, KeyManager[] km, TrustManager[] tm, SecureRandom random) throws IOException, KeyManagementException { - return null; - } + protected TransportServer createSslTransportServer(URI brokerURI, + KeyManager[] km, + TrustManager[] tm, + SecureRandom random) throws IOException, KeyManagementException { + return null; + } - //one way - public void setupSsl(String keystoreType, String password, String serverKeystore) { - this.SERVER_SIDE_KEYSTORE = serverKeystore; - this.KEYSTORE_PASSWORD = password; - this.storeType = keystoreType; - } + //one way + public void setupSsl(String keystoreType, String password, String serverKeystore) { + this.SERVER_SIDE_KEYSTORE = serverKeystore; + this.KEYSTORE_PASSWORD = password; + this.storeType = keystoreType; + } } diff --git a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/ArtemisBrokerBase.java b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/ArtemisBrokerBase.java index e7e117e625..6f2fff6546 100644 --- a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/ArtemisBrokerBase.java +++ b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/ArtemisBrokerBase.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.broker.artemiswrapper; - import java.io.File; import java.io.IOException; import java.net.URI; @@ -72,603 +71,547 @@ import org.slf4j.LoggerFactory; public abstract class ArtemisBrokerBase implements Broker { - private static final Logger LOG = LoggerFactory - .getLogger(ArtemisBrokerBase.class); - public static final String INVM_ACCEPTOR_FACTORY = InVMAcceptorFactory.class - .getCanonicalName(); - - public static final String NETTY_ACCEPTOR_FACTORY = NettyAcceptorFactory.class - .getCanonicalName(); - - public static final String NETTY_CONNECTOR_FACTORY = NettyConnectorFactory.class - .getCanonicalName(); - - protected static final String CLUSTER_PASSWORD = "UnitTestsClusterPassword"; - - protected volatile boolean stopped; - protected BrokerId brokerId = new BrokerId("Artemis Broker"); - protected BrokerService bservice; - protected TemporaryFolder temporaryFolder = new TemporaryFolder(); - protected String testDir; - protected boolean realStore = false; - - protected ActiveMQServer server; - - protected boolean enableSecurity = false; - - public ArtemisBrokerBase() { - try { - this.temporaryFolder.create(); - } catch (IOException e) { - } - } - @Override - public Destination addDestination(ConnectionContext context, - ActiveMQDestination destination, boolean createIfTemporary) - throws Exception { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void removeDestination(ConnectionContext context, - ActiveMQDestination destination, long timeout) throws Exception { - throw new RuntimeException("Don't call me!"); - } - - @Override - public Map getDestinationMap() { - throw new RuntimeException("Don't call me!"); - } - - @Override - public Subscription addConsumer(ConnectionContext context, ConsumerInfo info) - throws Exception { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void removeConsumer(ConnectionContext context, ConsumerInfo info) - throws Exception { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void removeSubscription(ConnectionContext context, - RemoveSubscriptionInfo info) throws Exception { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void send(ProducerBrokerExchange producerExchange, Message message) - throws Exception { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void acknowledge(ConsumerBrokerExchange consumerExchange, - MessageAck ack) throws Exception { - throw new RuntimeException("Don't call me!"); - } - - @Override - public Response messagePull(ConnectionContext context, MessagePull pull) - throws Exception { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void processDispatchNotification( - MessageDispatchNotification messageDispatchNotification) - throws Exception { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void gc() { - throw new RuntimeException("Don't call me!"); - } - - @Override - public Set getDestinations(ActiveMQDestination destination) { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void processConsumerControl(ConsumerBrokerExchange consumerExchange, - ConsumerControl control) { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void reapplyInterceptor() { - throw new RuntimeException("Don't call me!"); - } - - @Override - public Broker getAdaptor(Class type) { - throw new RuntimeException("Don't call me!"); - } - - @Override - public BrokerId getBrokerId() { - return brokerId; - } - - @Override - public String getBrokerName() { - return "Artemis Broker"; - } - - @Override - public void addBroker(Connection connection, BrokerInfo info) { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void removeBroker(Connection connection, BrokerInfo info) { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void addConnection(ConnectionContext context, ConnectionInfo info) - throws Exception { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void removeConnection(ConnectionContext context, - ConnectionInfo info, Throwable error) throws Exception { - throw new RuntimeException("Don't call me!"); - - } - - @Override - public void addSession(ConnectionContext context, SessionInfo info) - throws Exception { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void removeSession(ConnectionContext context, SessionInfo info) - throws Exception { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void addProducer(ConnectionContext context, ProducerInfo info) - throws Exception { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void removeProducer(ConnectionContext context, ProducerInfo info) - throws Exception { - throw new RuntimeException("Don't call me!"); - - } - - @Override - public Connection[] getClients() throws Exception { - throw new RuntimeException("Don't call me!"); - } - - @Override - public ActiveMQDestination[] getDestinations() throws Exception { - throw new RuntimeException("Don't call me!"); - } - - @Override - public Map getDestinationMap( - ActiveMQDestination destination) { - throw new RuntimeException("Don't call me!"); - } - - @Override - public TransactionId[] getPreparedTransactions(ConnectionContext context) - throws Exception { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void beginTransaction(ConnectionContext context, TransactionId xid) - throws Exception { - throw new RuntimeException("Don't call me!"); - } - - @Override - public int prepareTransaction(ConnectionContext context, TransactionId xid) - throws Exception { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void rollbackTransaction(ConnectionContext context, TransactionId xid) - throws Exception { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void commitTransaction(ConnectionContext context, TransactionId xid, - boolean onePhase) throws Exception { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void forgetTransaction(ConnectionContext context, - TransactionId transactionId) throws Exception { - throw new RuntimeException("Don't call me!"); - } - - @Override - public BrokerInfo[] getPeerBrokerInfos() { - return null; - } - - @Override - public void preProcessDispatch(MessageDispatch messageDispatch) { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void postProcessDispatch(MessageDispatch messageDispatch) { - throw new RuntimeException("Don't call me!"); - } - - @Override - public boolean isStopped() { - return stopped; - } - - @Override - public Set getDurableDestinations() { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void addDestinationInfo(ConnectionContext context, - DestinationInfo info) throws Exception { - throw new RuntimeException("Don't call me!"); - - } - - @Override - public void removeDestinationInfo(ConnectionContext context, - DestinationInfo info) throws Exception { - throw new RuntimeException("Don't call me!"); - - } - - @Override - public boolean isFaultTolerantConfiguration() { - return false; - } - - @Override - public ConnectionContext getAdminConnectionContext() { - return null; - } - - @Override - public void setAdminConnectionContext( - ConnectionContext adminConnectionContext) { - // - } - - @Override - public PListStore getTempDataStore() { - throw new RuntimeException("Don't call me!"); - } - - @Override - public URI getVmConnectorURI() { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void brokerServiceStarted() { - stopped = false; - } - - @Override - public BrokerService getBrokerService() { - return this.bservice; - } - - @Override - public Broker getRoot() { - return this; - } - - @Override - public boolean isExpired(MessageReference messageReference) { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void messageExpired(ConnectionContext context, - MessageReference messageReference, Subscription subscription) { - throw new RuntimeException("Don't call me!"); - - } - - @Override - public boolean sendToDeadLetterQueue(ConnectionContext context, - MessageReference messageReference, Subscription subscription, - Throwable poisonCause) { - throw new RuntimeException("Don't call me!"); - } - - @Override - public long getBrokerSequenceId() { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void messageConsumed(ConnectionContext context, - MessageReference messageReference) { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void messageDelivered(ConnectionContext context, - MessageReference messageReference) { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void messageDiscarded(ConnectionContext context, Subscription sub, - MessageReference messageReference) { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void slowConsumer(ConnectionContext context, - Destination destination, Subscription subs) { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void fastProducer(ConnectionContext context, - ProducerInfo producerInfo, ActiveMQDestination destination) { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void isFull(ConnectionContext context, Destination destination, - Usage usage) { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void nowMasterBroker() { - } - - @Override - public Scheduler getScheduler() { - throw new RuntimeException("Don't call me!"); - } - - @Override - public ThreadPoolExecutor getExecutor() { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void networkBridgeStarted(BrokerInfo brokerInfo, - boolean createdByDuplex, String remoteIp) { - throw new RuntimeException("Don't call me!"); - } - - @Override - public void networkBridgeStopped(BrokerInfo brokerInfo) { - throw new RuntimeException("Don't call me!"); - } - - protected final ActiveMQServer createServer(final boolean realFiles, - final boolean netty) throws Exception { - return createServer(realFiles, createDefaultConfig(netty), -1, -1, - new HashMap()); - } - - protected final ActiveMQServer createServer(final boolean realFiles, - final Configuration configuration, final int pageSize, - final int maxAddressSize, - final Map settings) { - return createServer(realFiles, configuration, pageSize, maxAddressSize, - AddressFullMessagePolicy.PAGE, settings); - } - - protected final ActiveMQServer createServer(final boolean realFiles, - final Configuration configuration, final int pageSize, - final int maxAddressSize, - final AddressFullMessagePolicy fullPolicy, - final Map settings) { - ActiveMQServer server = ActiveMQServers.newActiveMQServer(configuration, - realFiles); - if (settings != null) { - for (Map.Entry setting : settings - .entrySet()) { - server.getAddressSettingsRepository().addMatch( - setting.getKey(), setting.getValue()); - } - } - - AddressSettings defaultSetting = new AddressSettings(); - defaultSetting.setPageSizeBytes(pageSize); - defaultSetting.setMaxSizeBytes(maxAddressSize); - defaultSetting.setAddressFullMessagePolicy(fullPolicy); - - server.getAddressSettingsRepository().addMatch("#", defaultSetting); - - return server; - } - - protected Configuration createDefaultConfig(final boolean netty) - throws Exception { - if (netty) { - return createDefaultConfig(new HashMap(), - NETTY_ACCEPTOR_FACTORY); - } else { - return createDefaultConfig(new HashMap(), - INVM_ACCEPTOR_FACTORY); - } - } - - protected Configuration createDefaultConfig( - final Map params, final String... acceptors) - throws Exception { - ConfigurationImpl configuration = createBasicConfig(-1) - .setJMXManagementEnabled(false) - .clearAcceptorConfigurations(); - - for (String acceptor : acceptors) { - TransportConfiguration transportConfig = new TransportConfiguration( - acceptor, params); - configuration.addAcceptorConfiguration(transportConfig); - } - - return configuration; - } - - protected final ConfigurationImpl createBasicConfig(final int serverID) { - ConfigurationImpl configuration = new ConfigurationImpl() - .setSecurityEnabled(false) - .setJournalMinFiles(2) - .setJournalFileSize(100 * 1024) - .setJournalType(getDefaultJournalType()) - .setJournalDirectory(getJournalDir(serverID, false)) - .setBindingsDirectory(getBindingsDir(serverID, false)) - .setPagingDirectory(getPageDir(serverID, false)) - .setLargeMessagesDirectory(getLargeMessagesDir(serverID, false)) - .setJournalCompactMinFiles(0).setJournalCompactPercentage(0) - .setClusterPassword(CLUSTER_PASSWORD); - - return configuration; - } - - protected String getLargeMessagesDir(final int index, final boolean backup) { - return getLargeMessagesDir(testDir, index, backup); - } - - protected static String getLargeMessagesDir(final String testDir, - final int index, final boolean backup) { - return getLargeMessagesDir(testDir) - + directoryNameSuffix(index, backup); - } - - protected String getPageDir(final int index, final boolean backup) { - return getPageDir(testDir, index, backup); - } - - protected static String getPageDir(final String testDir, final int index, - final boolean backup) { - return getPageDir(testDir) + directoryNameSuffix(index, backup); - } - - protected String getBindingsDir(final int index, final boolean backup) { - return getBindingsDir(testDir, index, backup); - } - - protected static String getBindingsDir(final String testDir, - final int index, final boolean backup) { - return getBindingsDir(testDir) + directoryNameSuffix(index, backup); - } - - protected String getJournalDir(final int index, final boolean backup) { - return getJournalDir(testDir, index, backup); - } - - protected static String getJournalDir(final String testDir, - final int index, final boolean backup) { - return getJournalDir(testDir) + directoryNameSuffix(index, backup); - } - - private static String directoryNameSuffix(int index, boolean backup) { - if (index == -1) - return ""; - return index + "-" + (backup ? "B" : "L"); - } - - protected static JournalType getDefaultJournalType() { - if (LibaioContext.isLoaded()) { - return JournalType.ASYNCIO; - } else { - return JournalType.NIO; - } - } - - protected final void clearDataRecreateServerDirs() { - clearDataRecreateServerDirs(testDir); - } - - protected void clearDataRecreateServerDirs(final String testDir1) { - // Need to delete the root - - File file = new File(testDir1); - deleteDirectory(file); - file.mkdirs(); - - recreateDirectory(getJournalDir(testDir1)); - recreateDirectory(getBindingsDir(testDir1)); - recreateDirectory(getPageDir(testDir1)); - recreateDirectory(getLargeMessagesDir(testDir1)); - recreateDirectory(getClientLargeMessagesDir(testDir1)); - recreateDirectory(getTemporaryDir(testDir1)); - } - - protected String getTemporaryDir(final String testDir1) { - return testDir1 + "/temp"; - } - - protected String getClientLargeMessagesDir(final String testDir1) { - return testDir1 + "/client-large-msg"; - } - - protected static String getLargeMessagesDir(final String testDir1) { - return testDir1 + "/large-msg"; - } - - protected static String getPageDir(final String testDir1) { - return testDir1 + "/page"; - } - - protected static String getBindingsDir(final String testDir1) { - return testDir1 + "/bindings"; - } - - protected static String getJournalDir(final String testDir1) { - return testDir1 + "/journal"; - } - - protected static final void recreateDirectory(final String directory) { - File file = new File(directory); - deleteDirectory(file); - file.mkdirs(); - } - - protected static final boolean deleteDirectory(final File directory) { - if (directory.isDirectory()) { - String[] files = directory.list(); - int num = 5; - int attempts = 0; - while (files == null && (attempts < num)) { - try { - Thread.sleep(100); - } catch (InterruptedException e) { - } - files = directory.list(); - attempts++; - } - - for (String file : files) { - File f = new File(directory, file); - if (!deleteDirectory(f)) { - LOG.warn("Failed to clean up file: " + f.getAbsolutePath()); - } - } - } - - return directory.delete(); - } + private static final Logger LOG = LoggerFactory.getLogger(ArtemisBrokerBase.class); + public static final String INVM_ACCEPTOR_FACTORY = InVMAcceptorFactory.class.getCanonicalName(); + + public static final String NETTY_ACCEPTOR_FACTORY = NettyAcceptorFactory.class.getCanonicalName(); + + public static final String NETTY_CONNECTOR_FACTORY = NettyConnectorFactory.class.getCanonicalName(); + + protected static final String CLUSTER_PASSWORD = "UnitTestsClusterPassword"; + + protected volatile boolean stopped; + protected BrokerId brokerId = new BrokerId("Artemis Broker"); + protected BrokerService bservice; + protected TemporaryFolder temporaryFolder = new TemporaryFolder(); + protected String testDir; + protected boolean realStore = false; + + protected ActiveMQServer server; + + protected boolean enableSecurity = false; + + public ArtemisBrokerBase() { + try { + this.temporaryFolder.create(); + } + catch (IOException e) { + } + } + + @Override + public Destination addDestination(ConnectionContext context, + ActiveMQDestination destination, + boolean createIfTemporary) throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void removeDestination(ConnectionContext context, + ActiveMQDestination destination, + long timeout) throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public Map getDestinationMap() { + throw new RuntimeException("Don't call me!"); + } + + @Override + public Subscription addConsumer(ConnectionContext context, ConsumerInfo info) throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void removeConsumer(ConnectionContext context, ConsumerInfo info) throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void removeSubscription(ConnectionContext context, RemoveSubscriptionInfo info) throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void send(ProducerBrokerExchange producerExchange, Message message) throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void acknowledge(ConsumerBrokerExchange consumerExchange, MessageAck ack) throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public Response messagePull(ConnectionContext context, MessagePull pull) throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void processDispatchNotification(MessageDispatchNotification messageDispatchNotification) throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void gc() { + throw new RuntimeException("Don't call me!"); + } + + @Override + public Set getDestinations(ActiveMQDestination destination) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void processConsumerControl(ConsumerBrokerExchange consumerExchange, ConsumerControl control) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void reapplyInterceptor() { + throw new RuntimeException("Don't call me!"); + } + + @Override + public Broker getAdaptor(Class type) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public BrokerId getBrokerId() { + return brokerId; + } + + @Override + public String getBrokerName() { + return "Artemis Broker"; + } + + @Override + public void addBroker(Connection connection, BrokerInfo info) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void removeBroker(Connection connection, BrokerInfo info) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void addConnection(ConnectionContext context, ConnectionInfo info) throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void removeConnection(ConnectionContext context, ConnectionInfo info, Throwable error) throws Exception { + throw new RuntimeException("Don't call me!"); + + } + + @Override + public void addSession(ConnectionContext context, SessionInfo info) throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void removeSession(ConnectionContext context, SessionInfo info) throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void addProducer(ConnectionContext context, ProducerInfo info) throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void removeProducer(ConnectionContext context, ProducerInfo info) throws Exception { + throw new RuntimeException("Don't call me!"); + + } + + @Override + public Connection[] getClients() throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public ActiveMQDestination[] getDestinations() throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public Map getDestinationMap(ActiveMQDestination destination) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public TransactionId[] getPreparedTransactions(ConnectionContext context) throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void beginTransaction(ConnectionContext context, TransactionId xid) throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public int prepareTransaction(ConnectionContext context, TransactionId xid) throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void rollbackTransaction(ConnectionContext context, TransactionId xid) throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void commitTransaction(ConnectionContext context, TransactionId xid, boolean onePhase) throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void forgetTransaction(ConnectionContext context, TransactionId transactionId) throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public BrokerInfo[] getPeerBrokerInfos() { + return null; + } + + @Override + public void preProcessDispatch(MessageDispatch messageDispatch) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void postProcessDispatch(MessageDispatch messageDispatch) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public boolean isStopped() { + return stopped; + } + + @Override + public Set getDurableDestinations() { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void addDestinationInfo(ConnectionContext context, DestinationInfo info) throws Exception { + throw new RuntimeException("Don't call me!"); + + } + + @Override + public void removeDestinationInfo(ConnectionContext context, DestinationInfo info) throws Exception { + throw new RuntimeException("Don't call me!"); + + } + + @Override + public boolean isFaultTolerantConfiguration() { + return false; + } + + @Override + public ConnectionContext getAdminConnectionContext() { + return null; + } + + @Override + public void setAdminConnectionContext(ConnectionContext adminConnectionContext) { + // + } + + @Override + public PListStore getTempDataStore() { + throw new RuntimeException("Don't call me!"); + } + + @Override + public URI getVmConnectorURI() { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void brokerServiceStarted() { + stopped = false; + } + + @Override + public BrokerService getBrokerService() { + return this.bservice; + } + + @Override + public Broker getRoot() { + return this; + } + + @Override + public boolean isExpired(MessageReference messageReference) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void messageExpired(ConnectionContext context, MessageReference messageReference, Subscription subscription) { + throw new RuntimeException("Don't call me!"); + + } + + @Override + public boolean sendToDeadLetterQueue(ConnectionContext context, + MessageReference messageReference, + Subscription subscription, + Throwable poisonCause) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public long getBrokerSequenceId() { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void messageConsumed(ConnectionContext context, MessageReference messageReference) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void messageDelivered(ConnectionContext context, MessageReference messageReference) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void messageDiscarded(ConnectionContext context, Subscription sub, MessageReference messageReference) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void slowConsumer(ConnectionContext context, Destination destination, Subscription subs) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void fastProducer(ConnectionContext context, ProducerInfo producerInfo, ActiveMQDestination destination) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void isFull(ConnectionContext context, Destination destination, Usage usage) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void nowMasterBroker() { + } + + @Override + public Scheduler getScheduler() { + throw new RuntimeException("Don't call me!"); + } + + @Override + public ThreadPoolExecutor getExecutor() { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void networkBridgeStarted(BrokerInfo brokerInfo, boolean createdByDuplex, String remoteIp) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void networkBridgeStopped(BrokerInfo brokerInfo) { + throw new RuntimeException("Don't call me!"); + } + + protected final ActiveMQServer createServer(final boolean realFiles, final boolean netty) throws Exception { + return createServer(realFiles, createDefaultConfig(netty), -1, -1, new HashMap()); + } + + protected final ActiveMQServer createServer(final boolean realFiles, + final Configuration configuration, + final int pageSize, + final int maxAddressSize, + final Map settings) { + return createServer(realFiles, configuration, pageSize, maxAddressSize, AddressFullMessagePolicy.PAGE, settings); + } + + protected final ActiveMQServer createServer(final boolean realFiles, + final Configuration configuration, + final int pageSize, + final int maxAddressSize, + final AddressFullMessagePolicy fullPolicy, + final Map settings) { + ActiveMQServer server = ActiveMQServers.newActiveMQServer(configuration, realFiles); + if (settings != null) { + for (Map.Entry setting : settings.entrySet()) { + server.getAddressSettingsRepository().addMatch(setting.getKey(), setting.getValue()); + } + } + + AddressSettings defaultSetting = new AddressSettings(); + defaultSetting.setPageSizeBytes(pageSize); + defaultSetting.setMaxSizeBytes(maxAddressSize); + defaultSetting.setAddressFullMessagePolicy(fullPolicy); + + server.getAddressSettingsRepository().addMatch("#", defaultSetting); + + return server; + } + + protected Configuration createDefaultConfig(final boolean netty) throws Exception { + if (netty) { + return createDefaultConfig(new HashMap(), NETTY_ACCEPTOR_FACTORY); + } + else { + return createDefaultConfig(new HashMap(), INVM_ACCEPTOR_FACTORY); + } + } + + protected Configuration createDefaultConfig(final Map params, + final String... acceptors) throws Exception { + ConfigurationImpl configuration = createBasicConfig(-1).setJMXManagementEnabled(false).clearAcceptorConfigurations(); + + for (String acceptor : acceptors) { + TransportConfiguration transportConfig = new TransportConfiguration(acceptor, params); + configuration.addAcceptorConfiguration(transportConfig); + } + + return configuration; + } + + protected final ConfigurationImpl createBasicConfig(final int serverID) { + ConfigurationImpl configuration = new ConfigurationImpl().setSecurityEnabled(false).setJournalMinFiles(2).setJournalFileSize(100 * 1024).setJournalType(getDefaultJournalType()).setJournalDirectory(getJournalDir(serverID, false)).setBindingsDirectory(getBindingsDir(serverID, false)).setPagingDirectory(getPageDir(serverID, false)).setLargeMessagesDirectory(getLargeMessagesDir(serverID, false)).setJournalCompactMinFiles(0).setJournalCompactPercentage(0).setClusterPassword(CLUSTER_PASSWORD); + + return configuration; + } + + protected String getLargeMessagesDir(final int index, final boolean backup) { + return getLargeMessagesDir(testDir, index, backup); + } + + protected static String getLargeMessagesDir(final String testDir, final int index, final boolean backup) { + return getLargeMessagesDir(testDir) + directoryNameSuffix(index, backup); + } + + protected String getPageDir(final int index, final boolean backup) { + return getPageDir(testDir, index, backup); + } + + protected static String getPageDir(final String testDir, final int index, final boolean backup) { + return getPageDir(testDir) + directoryNameSuffix(index, backup); + } + + protected String getBindingsDir(final int index, final boolean backup) { + return getBindingsDir(testDir, index, backup); + } + + protected static String getBindingsDir(final String testDir, final int index, final boolean backup) { + return getBindingsDir(testDir) + directoryNameSuffix(index, backup); + } + + protected String getJournalDir(final int index, final boolean backup) { + return getJournalDir(testDir, index, backup); + } + + protected static String getJournalDir(final String testDir, final int index, final boolean backup) { + return getJournalDir(testDir) + directoryNameSuffix(index, backup); + } + + private static String directoryNameSuffix(int index, boolean backup) { + if (index == -1) + return ""; + return index + "-" + (backup ? "B" : "L"); + } + + protected static JournalType getDefaultJournalType() { + if (LibaioContext.isLoaded()) { + return JournalType.ASYNCIO; + } + else { + return JournalType.NIO; + } + } + + protected final void clearDataRecreateServerDirs() { + clearDataRecreateServerDirs(testDir); + } + + protected void clearDataRecreateServerDirs(final String testDir1) { + // Need to delete the root + + File file = new File(testDir1); + deleteDirectory(file); + file.mkdirs(); + + recreateDirectory(getJournalDir(testDir1)); + recreateDirectory(getBindingsDir(testDir1)); + recreateDirectory(getPageDir(testDir1)); + recreateDirectory(getLargeMessagesDir(testDir1)); + recreateDirectory(getClientLargeMessagesDir(testDir1)); + recreateDirectory(getTemporaryDir(testDir1)); + } + + protected String getTemporaryDir(final String testDir1) { + return testDir1 + "/temp"; + } + + protected String getClientLargeMessagesDir(final String testDir1) { + return testDir1 + "/client-large-msg"; + } + + protected static String getLargeMessagesDir(final String testDir1) { + return testDir1 + "/large-msg"; + } + + protected static String getPageDir(final String testDir1) { + return testDir1 + "/page"; + } + + protected static String getBindingsDir(final String testDir1) { + return testDir1 + "/bindings"; + } + + protected static String getJournalDir(final String testDir1) { + return testDir1 + "/journal"; + } + + protected static final void recreateDirectory(final String directory) { + File file = new File(directory); + deleteDirectory(file); + file.mkdirs(); + } + + protected static final boolean deleteDirectory(final File directory) { + if (directory.isDirectory()) { + String[] files = directory.list(); + int num = 5; + int attempts = 0; + while (files == null && (attempts < num)) { + try { + Thread.sleep(100); + } + catch (InterruptedException e) { + } + files = directory.list(); + attempts++; + } + + for (String file : files) { + File f = new File(directory, file); + if (!deleteDirectory(f)) { + LOG.warn("Failed to clean up file: " + f.getAbsolutePath()); + } + } + } + + return directory.delete(); + } } diff --git a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/ArtemisBrokerWrapper.java b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/ArtemisBrokerWrapper.java index 7e7ec19215..31da179ebf 100644 --- a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/ArtemisBrokerWrapper.java +++ b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/ArtemisBrokerWrapper.java @@ -43,20 +43,17 @@ import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.region.policy.PolicyEntry; import org.apache.activemq.broker.region.policy.PolicyMap; -public class ArtemisBrokerWrapper extends ArtemisBrokerBase -{ +public class ArtemisBrokerWrapper extends ArtemisBrokerBase { protected final Map testQueues = new HashMap(); protected JMSServerManagerImpl jmsServer; - public ArtemisBrokerWrapper(BrokerService brokerService) - { + public ArtemisBrokerWrapper(BrokerService brokerService) { this.bservice = brokerService; } @Override - public void start() throws Exception - { + public void start() throws Exception { testDir = temporaryFolder.getRoot().getAbsolutePath(); clearDataRecreateServerDirs(); server = createServer(realStore, true); @@ -73,15 +70,13 @@ public class ArtemisBrokerWrapper extends ArtemisBrokerBase //do policy translation PolicyMap policyMap = this.bservice.getDestinationPolicy(); - if (policyMap != null) - { + if (policyMap != null) { translatePolicyMap(serverConfig, policyMap); } String match = "jms.queue.#"; AddressSettings commonSettings = addressSettingsMap.get(match); - if (commonSettings == null) - { + if (commonSettings == null) { commonSettings = new AddressSettings(); addressSettingsMap.put(match, commonSettings); } @@ -89,8 +84,7 @@ public class ArtemisBrokerWrapper extends ArtemisBrokerBase commonSettings.setDeadLetterAddress(dla); serverConfig.getAcceptorConfigurations().add(transportConfiguration); - if (this.bservice.enableSsl()) - { + if (this.bservice.enableSsl()) { params = new HashMap(); params.put(TransportConstants.SSL_ENABLED_PROP_NAME, true); params.put(TransportConstants.PORT_PROP_NAME, 61611); @@ -98,8 +92,7 @@ public class ArtemisBrokerWrapper extends ArtemisBrokerBase params.put(TransportConstants.KEYSTORE_PATH_PROP_NAME, bservice.SERVER_SIDE_KEYSTORE); params.put(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, bservice.KEYSTORE_PASSWORD); params.put(TransportConstants.KEYSTORE_PROVIDER_PROP_NAME, bservice.storeType); - if (bservice.SERVER_SIDE_TRUSTSTORE != null) - { + if (bservice.SERVER_SIDE_TRUSTSTORE != null) { params.put(TransportConstants.NEED_CLIENT_AUTH_PROP_NAME, true); params.put(TransportConstants.TRUSTSTORE_PATH_PROP_NAME, bservice.SERVER_SIDE_TRUSTSTORE); params.put(TransportConstants.TRUSTSTORE_PASSWORD_PROP_NAME, bservice.TRUSTSTORE_PASSWORD); @@ -109,10 +102,8 @@ public class ArtemisBrokerWrapper extends ArtemisBrokerBase serverConfig.getAcceptorConfigurations().add(sslTransportConfig); } - for (Integer port : bservice.extraConnectors) - { - if (port.intValue() != 61616) - { + for (Integer port : bservice.extraConnectors) { + if (port.intValue() != 61616) { //extra port params = new HashMap(); params.put(TransportConstants.PORT_PROP_NAME, port.intValue()); @@ -126,8 +117,7 @@ public class ArtemisBrokerWrapper extends ArtemisBrokerBase //extraServerConfig(serverConfig); - if (enableSecurity) - { + if (enableSecurity) { ActiveMQSecurityManagerImpl sm = (ActiveMQSecurityManagerImpl) server.getSecurityManager(); SecurityConfiguration securityConfig = sm.getConfiguration(); securityConfig.addRole("openwireSender", "sender"); @@ -153,14 +143,12 @@ public class ArtemisBrokerWrapper extends ArtemisBrokerBase Role destRole = new Role("manager", false, false, false, false, true, true, false); Map> settings = server.getConfiguration().getSecurityRoles(); - if (settings == null) - { + if (settings == null) { settings = new HashMap>(); server.getConfiguration().setSecurityRoles(settings); } Set anySet = settings.get("#"); - if (anySet == null) - { + if (anySet == null) { anySet = new HashSet(); settings.put("#", anySet); } @@ -172,8 +160,7 @@ public class ArtemisBrokerWrapper extends ArtemisBrokerBase Set acceptors = serverConfig.getAcceptorConfigurations(); Iterator iter = acceptors.iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { System.out.println("acceptor =>: " + iter.next()); } @@ -185,7 +172,7 @@ public class ArtemisBrokerWrapper extends ArtemisBrokerBase server.start(); /* - registerConnectionFactory(); + registerConnectionFactory(); mbeanServer = MBeanServerFactory.createMBeanServer(); */ @@ -194,24 +181,20 @@ public class ArtemisBrokerWrapper extends ArtemisBrokerBase } - private void translatePolicyMap(Configuration serverConfig, PolicyMap policyMap) - { + private void translatePolicyMap(Configuration serverConfig, PolicyMap policyMap) { List allEntries = policyMap.getAllEntries(); Map settingsMap = serverConfig.getAddressesSettings(); - for (Object o : allEntries) - { - PolicyEntry entry = (PolicyEntry)o; + for (Object o : allEntries) { + PolicyEntry entry = (PolicyEntry) o; org.apache.activemq.command.ActiveMQDestination targetDest = entry.getDestination(); String match = getCorePattern(targetDest); AddressSettings settings = settingsMap.get(match); - if (settings == null) - { + if (settings == null) { settings = new AddressSettings(); settingsMap.put(match, settings); } - if (entry.isAdvisoryForSlowConsumers()) - { + if (entry.isAdvisoryForSlowConsumers()) { settings.setSlowConsumerThreshold(1000); settings.setSlowConsumerCheckPeriod(1); settings.setSlowConsumerPolicy(SlowConsumerPolicy.NOTIFY); @@ -219,35 +202,28 @@ public class ArtemisBrokerWrapper extends ArtemisBrokerBase } PolicyEntry defaultEntry = policyMap.getDefaultEntry(); - if (defaultEntry != null) - { + if (defaultEntry != null) { AddressSettings defSettings = settingsMap.get("#"); - if (defSettings == null) - { + if (defSettings == null) { defSettings = new AddressSettings(); settingsMap.put("#", defSettings); } - if (defaultEntry.isProducerFlowControl()) - { + if (defaultEntry.isProducerFlowControl()) { defSettings.setMaxSizeBytes(1).setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK); - if (bservice.getSystemUsage().isSendFailIfNoSpace()) - { + if (bservice.getSystemUsage().isSendFailIfNoSpace()) { defSettings.setAddressFullMessagePolicy(AddressFullMessagePolicy.FAIL); } } } } - private String getCorePattern(org.apache.activemq.command.ActiveMQDestination dest) - { + private String getCorePattern(org.apache.activemq.command.ActiveMQDestination dest) { String physicalName = dest.getPhysicalName(); String pattern = physicalName.replace(">", "#"); - if (dest.isTopic()) - { + if (dest.isTopic()) { pattern = "jms.topic." + pattern; } - else - { + else { pattern = "jms.queue." + pattern; } @@ -255,39 +231,30 @@ public class ArtemisBrokerWrapper extends ArtemisBrokerBase } @Override - public void stop() throws Exception - { - try - { + public void stop() throws Exception { + try { server.stop(); testQueues.clear(); stopped = true; } - catch (Throwable t) - { + catch (Throwable t) { //ignore } - finally - { + finally { server = null; } } - public void makeSureQueueExists(String qname) throws Exception - { - synchronized (testQueues) - { + public void makeSureQueueExists(String qname) throws Exception { + synchronized (testQueues) { SimpleString coreQ = testQueues.get(qname); - if (coreQ == null) - { + if (coreQ == null) { coreQ = new SimpleString("jms.queue." + qname); - try - { + try { this.server.createQueue(coreQ, coreQ, null, false, false); testQueues.put(qname, coreQ); } - catch (ActiveMQQueueExistsException e) - { + catch (ActiveMQQueueExistsException e) { //ignore } } diff --git a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/InVMNameParser.java b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/InVMNameParser.java index 293cdb023e..9bfd194427 100644 --- a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/InVMNameParser.java +++ b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/InVMNameParser.java @@ -27,10 +27,8 @@ import javax.naming.NamingException; /** * @author Ovidiu Feodorov * @version $Revision: 2868 $ - * */ -public class InVMNameParser implements NameParser, Serializable -{ +public class InVMNameParser implements NameParser, Serializable { // Constants ----------------------------------------------------- private static final long serialVersionUID = 2925203703371001031L; @@ -39,8 +37,7 @@ public class InVMNameParser implements NameParser, Serializable static Properties syntax; - static - { + static { InVMNameParser.syntax = new Properties(); InVMNameParser.syntax.put("jndi.syntax.direction", "left_to_right"); InVMNameParser.syntax.put("jndi.syntax.ignorecase", "false"); @@ -53,13 +50,11 @@ public class InVMNameParser implements NameParser, Serializable // Public -------------------------------------------------------- - public static Properties getSyntax() - { + public static Properties getSyntax() { return InVMNameParser.syntax; } - public Name parse(final String name) throws NamingException - { + public Name parse(final String name) throws NamingException { return new CompoundName(name, InVMNameParser.syntax); } diff --git a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/InVMNamingContext.java b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/InVMNamingContext.java index 017fa1775e..5579b1ac1e 100644 --- a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/InVMNamingContext.java +++ b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/InVMNamingContext.java @@ -37,8 +37,7 @@ import javax.naming.NamingException; import javax.naming.RefAddr; import javax.naming.Reference; -public class InVMNamingContext implements Context, Serializable -{ +public class InVMNamingContext implements Context, Serializable { // Constants ----------------------------------------------------- private static final long serialVersionUID = 385743957345L; @@ -55,169 +54,137 @@ public class InVMNamingContext implements Context, Serializable // Constructors -------------------------------------------------- - public InVMNamingContext() - { + public InVMNamingContext() { map = Collections.synchronizedMap(new HashMap()); } - public InVMNamingContext(final String nameInNamespace) - { + public InVMNamingContext(final String nameInNamespace) { this(); this.nameInNamespace = nameInNamespace; } // Context implementation ---------------------------------------- - public Object lookup(final Name name) throws NamingException - { + public Object lookup(final Name name) throws NamingException { throw new UnsupportedOperationException(); } - public Object lookup(String name) throws NamingException - { + public Object lookup(String name) throws NamingException { name = trimSlashes(name); int i = name.indexOf("/"); String tok = i == -1 ? name : name.substring(0, i); Object value = map.get(tok); - if (value == null) - { + if (value == null) { throw new NameNotFoundException("Name not found: " + tok); } - if (value instanceof InVMNamingContext && i != -1) - { - return ((InVMNamingContext)value).lookup(name.substring(i)); + if (value instanceof InVMNamingContext && i != -1) { + return ((InVMNamingContext) value).lookup(name.substring(i)); } - if (value instanceof Reference) - { - Reference ref = (Reference)value; + if (value instanceof Reference) { + Reference ref = (Reference) value; RefAddr refAddr = ref.get("nns"); // we only deal with references create by NonSerializableFactory - String key = (String)refAddr.getContent(); + String key = (String) refAddr.getContent(); return NonSerializableFactory.lookup(key); } - else - { + else { return value; } } - public void bind(final Name name, final Object obj) throws NamingException - { + public void bind(final Name name, final Object obj) throws NamingException { throw new UnsupportedOperationException(); } - public void bind(final String name, final Object obj) throws NamingException - { + public void bind(final String name, final Object obj) throws NamingException { internalBind(name, obj, false); } - public void rebind(final Name name, final Object obj) throws NamingException - { + public void rebind(final Name name, final Object obj) throws NamingException { throw new UnsupportedOperationException(); } - public void rebind(final String name, final Object obj) throws NamingException - { + public void rebind(final String name, final Object obj) throws NamingException { internalBind(name, obj, true); } - public void unbind(final Name name) throws NamingException - { + public void unbind(final Name name) throws NamingException { unbind(name.toString()); } - public void unbind(String name) throws NamingException - { + public void unbind(String name) throws NamingException { name = trimSlashes(name); int i = name.indexOf("/"); boolean terminal = i == -1; - if (terminal) - { + if (terminal) { map.remove(name); } - else - { + else { String tok = name.substring(0, i); - InVMNamingContext c = (InVMNamingContext)map.get(tok); - if (c == null) - { + InVMNamingContext c = (InVMNamingContext) map.get(tok); + if (c == null) { throw new NameNotFoundException("Context not found: " + tok); } c.unbind(name.substring(i)); } } - public void rename(final Name oldName, final Name newName) throws NamingException - { + public void rename(final Name oldName, final Name newName) throws NamingException { throw new UnsupportedOperationException(); } - public void rename(final String oldName, final String newName) throws NamingException - { + public void rename(final String oldName, final String newName) throws NamingException { throw new UnsupportedOperationException(); } - public NamingEnumeration list(final Name name) throws NamingException - { + public NamingEnumeration list(final Name name) throws NamingException { throw new UnsupportedOperationException(); } - public NamingEnumeration list(final String name) throws NamingException - { + public NamingEnumeration list(final String name) throws NamingException { throw new UnsupportedOperationException(); } - public NamingEnumeration listBindings(final Name name) throws NamingException - { + public NamingEnumeration listBindings(final Name name) throws NamingException { throw new UnsupportedOperationException(); } - public NamingEnumeration listBindings(String contextName) throws NamingException - { + public NamingEnumeration listBindings(String contextName) throws NamingException { contextName = trimSlashes(contextName); - if (!"".equals(contextName) && !".".equals(contextName)) - { - try - { - return ((InVMNamingContext)lookup(contextName)).listBindings(""); + if (!"".equals(contextName) && !".".equals(contextName)) { + try { + return ((InVMNamingContext) lookup(contextName)).listBindings(""); } - catch (Throwable t) - { + catch (Throwable t) { throw new NamingException(t.getMessage()); } } List l = new ArrayList(); - for (Object element : map.keySet()) - { - String name = (String)element; + for (Object element : map.keySet()) { + String name = (String) element; Object object = map.get(name); l.add(new Binding(name, object)); } return new NamingEnumerationImpl(l.iterator()); } - public void destroySubcontext(final Name name) throws NamingException - { + public void destroySubcontext(final Name name) throws NamingException { destroySubcontext(name.toString()); } - public void destroySubcontext(final String name) throws NamingException - { + public void destroySubcontext(final String name) throws NamingException { map.remove(trimSlashes(name)); } - public Context createSubcontext(final Name name) throws NamingException - { + public Context createSubcontext(final Name name) throws NamingException { throw new UnsupportedOperationException(); } - public Context createSubcontext(String name) throws NamingException - { + public Context createSubcontext(String name) throws NamingException { name = trimSlashes(name); - if (map.get(name) != null) - { + if (map.get(name) != null) { throw new NameAlreadyBoundException(name); } InVMNamingContext c = new InVMNamingContext(getNameInNamespace()); @@ -225,59 +192,48 @@ public class InVMNamingContext implements Context, Serializable return c; } - public Object lookupLink(final Name name) throws NamingException - { + public Object lookupLink(final Name name) throws NamingException { throw new UnsupportedOperationException(); } - public Object lookupLink(final String name) throws NamingException - { + public Object lookupLink(final String name) throws NamingException { throw new UnsupportedOperationException(); } - public NameParser getNameParser(final Name name) throws NamingException - { + public NameParser getNameParser(final Name name) throws NamingException { return getNameParser(name.toString()); } - public NameParser getNameParser(final String name) throws NamingException - { + public NameParser getNameParser(final String name) throws NamingException { return parser; } - public Name composeName(final Name name, final Name prefix) throws NamingException - { + public Name composeName(final Name name, final Name prefix) throws NamingException { throw new UnsupportedOperationException(); } - public String composeName(final String name, final String prefix) throws NamingException - { + public String composeName(final String name, final String prefix) throws NamingException { throw new UnsupportedOperationException(); } - public Object addToEnvironment(final String propName, final Object propVal) throws NamingException - { + public Object addToEnvironment(final String propName, final Object propVal) throws NamingException { throw new UnsupportedOperationException(); } - public Object removeFromEnvironment(final String propName) throws NamingException - { + public Object removeFromEnvironment(final String propName) throws NamingException { throw new UnsupportedOperationException(); } - public Hashtable getEnvironment() throws NamingException - { + public Hashtable getEnvironment() throws NamingException { Hashtable env = new Hashtable(); env.put("java.naming.factory.initial", "org.apache.activemq.artemis.jms.tests.tools.container.InVMInitialContextFactory"); return env; } - public void close() throws NamingException - { + public void close() throws NamingException { } - public String getNameInNamespace() throws NamingException - { + public String getNameInNamespace() throws NamingException { return nameInNamespace; } @@ -289,23 +245,18 @@ public class InVMNamingContext implements Context, Serializable // Private ------------------------------------------------------- - private String trimSlashes(String s) - { + private String trimSlashes(String s) { int i = 0; - while (true) - { - if (i == s.length() || s.charAt(i) != '/') - { + while (true) { + if (i == s.length() || s.charAt(i) != '/') { break; } i++; } s = s.substring(i); i = s.length() - 1; - while (true) - { - if (i == -1 || s.charAt(i) != '/') - { + while (true) { + if (i == -1 || s.charAt(i) != '/') { break; } i--; @@ -313,19 +264,16 @@ public class InVMNamingContext implements Context, Serializable return s.substring(0, i + 1); } - private void internalBind(String name, final Object obj, final boolean rebind) throws NamingException - { + private void internalBind(String name, final Object obj, final boolean rebind) throws NamingException { name = trimSlashes(name); int i = name.lastIndexOf("/"); InVMNamingContext c = this; - if (i != -1) - { + if (i != -1) { String path = name.substring(0, i); - c = (InVMNamingContext)lookup(path); + c = (InVMNamingContext) lookup(path); } name = name.substring(i + 1); - if (!rebind && c.map.get(name) != null) - { + if (!rebind && c.map.get(name) != null) { throw new NameAlreadyBoundException(name); } c.map.put(name, obj); @@ -333,37 +281,31 @@ public class InVMNamingContext implements Context, Serializable // Inner classes ------------------------------------------------- - private class NamingEnumerationImpl implements NamingEnumeration - { + private class NamingEnumerationImpl implements NamingEnumeration { + private final Iterator iterator; - NamingEnumerationImpl(final Iterator bindingIterator) - { + NamingEnumerationImpl(final Iterator bindingIterator) { iterator = bindingIterator; } - public void close() throws NamingException - { + public void close() throws NamingException { throw new UnsupportedOperationException(); } - public boolean hasMore() throws NamingException - { + public boolean hasMore() throws NamingException { return iterator.hasNext(); } - public T next() throws NamingException - { + public T next() throws NamingException { return iterator.next(); } - public boolean hasMoreElements() - { + public boolean hasMoreElements() { return iterator.hasNext(); } - public T nextElement() - { + public T nextElement() { return iterator.next(); } } diff --git a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/NonSerializableFactory.java b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/NonSerializableFactory.java index 0c39f130f3..4f4ddd12ae 100644 --- a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/NonSerializableFactory.java +++ b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/NonSerializableFactory.java @@ -36,74 +36,72 @@ import java.util.Map; * * @author Andy Taylor */ -public class NonSerializableFactory implements ObjectFactory -{ +public class NonSerializableFactory implements ObjectFactory { - public NonSerializableFactory() - { - } -/* - public static void unbind(final Context ctx, final String strName) throws NamingException - { - Name name = ctx.getNameParser("").parse(strName); - int size = name.size(); - String atom = name.get(size - 1); - Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1)); - String key = new StringBuilder().append(parentCtx.getNameInNamespace()).append("/").append(atom).toString(); - NonSerializableFactory.getWrapperMap().remove(key); - Util.unbind(ctx, strName); + public NonSerializableFactory() { } - public static void rebind(final Context ctx, final String strName, final Object value) throws NamingException - { - Name name = ctx.getNameParser("").parse(strName); - int size = name.size(); - String atom = name.get(size - 1); - Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1)); - String key = new StringBuilder().append(parentCtx.getNameInNamespace()).append("/").append(atom).toString(); - NonSerializableFactory.getWrapperMap().put(key, value); - String className = value.getClass().getName(); - String factory = NonSerializableFactory.class.getName(); - StringRefAddr addr = new StringRefAddr("nns", key); - Reference memoryRef = new Reference(className, addr, factory, null); - parentCtx.rebind(atom, memoryRef); - } - - public static void bind(final Context ctx, final String strName, final Object value) throws NamingException - { - Name name = ctx.getNameParser("").parse(strName); - int size = name.size(); - String atom = name.get(size - 1); - Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1)); - String key = new StringBuilder().append(parentCtx.getNameInNamespace()).append("/").append(atom).toString(); - NonSerializableFactory.getWrapperMap().put(key, value); - String className = value.getClass().getName(); - String factory = NonSerializableFactory.class.getName(); - StringRefAddr addr = new StringRefAddr("nns", key); - Reference memoryRef = new Reference(className, addr, factory, null); - - parentCtx.bind(atom, memoryRef); - } -*/ - public static Object lookup(final String name) throws NamingException - { - if (NonSerializableFactory.getWrapperMap().get(name) == null) + /* + public static void unbind(final Context ctx, final String strName) throws NamingException { + Name name = ctx.getNameParser("").parse(strName); + int size = name.size(); + String atom = name.get(size - 1); + Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1)); + String key = new StringBuilder().append(parentCtx.getNameInNamespace()).append("/").append(atom).toString(); + NonSerializableFactory.getWrapperMap().remove(key); + Util.unbind(ctx, strName); + } + + public static void rebind(final Context ctx, final String strName, final Object value) throws NamingException + { + Name name = ctx.getNameParser("").parse(strName); + int size = name.size(); + String atom = name.get(size - 1); + Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1)); + String key = new StringBuilder().append(parentCtx.getNameInNamespace()).append("/").append(atom).toString(); + NonSerializableFactory.getWrapperMap().put(key, value); + String className = value.getClass().getName(); + String factory = NonSerializableFactory.class.getName(); + StringRefAddr addr = new StringRefAddr("nns", key); + Reference memoryRef = new Reference(className, addr, factory, null); + parentCtx.rebind(atom, memoryRef); + } + + public static void bind(final Context ctx, final String strName, final Object value) throws NamingException + { + Name name = ctx.getNameParser("").parse(strName); + int size = name.size(); + String atom = name.get(size - 1); + Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1)); + String key = new StringBuilder().append(parentCtx.getNameInNamespace()).append("/").append(atom).toString(); + NonSerializableFactory.getWrapperMap().put(key, value); + String className = value.getClass().getName(); + String factory = NonSerializableFactory.class.getName(); + StringRefAddr addr = new StringRefAddr("nns", key); + Reference memoryRef = new Reference(className, addr, factory, null); + + parentCtx.bind(atom, memoryRef); + } + */ + public static Object lookup(final String name) throws NamingException { + if (NonSerializableFactory.getWrapperMap().get(name) == null) { throw new NamingException(name + " not found"); } return NonSerializableFactory.getWrapperMap().get(name); } - public Object getObjectInstance(final Object obj, final Name name, final Context nameCtx, final Hashtable env) throws Exception - { + public Object getObjectInstance(final Object obj, + final Name name, + final Context nameCtx, + final Hashtable env) throws Exception { Reference ref = (Reference) obj; RefAddr addr = ref.get("nns"); String key = (String) addr.getContent(); return NonSerializableFactory.getWrapperMap().get(key); } - public static Map getWrapperMap() - { + public static Map getWrapperMap() { return NonSerializableFactory.wrapperMap; } diff --git a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/region/policy/PolicyMap.java b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/region/policy/PolicyMap.java index 58aa694da9..fe90ac3893 100644 --- a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/region/policy/PolicyMap.java +++ b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/region/policy/PolicyMap.java @@ -23,45 +23,37 @@ import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.filter.DestinationMap; import org.apache.activemq.filter.DestinationMapEntry; -public class PolicyMap extends DestinationMap -{ +public class PolicyMap extends DestinationMap { private PolicyEntry defaultEntry; private List allEntries = new ArrayList(); - public PolicyEntry getEntryFor(ActiveMQDestination destination) - { + public PolicyEntry getEntryFor(ActiveMQDestination destination) { PolicyEntry answer = (PolicyEntry) chooseValue(destination); - if (answer == null) - { + if (answer == null) { answer = getDefaultEntry(); } return answer; } - public void setPolicyEntries(List entries) - { + public void setPolicyEntries(List entries) { super.setEntries(entries); allEntries.addAll(entries); } - public List getAllEntries() - { + public List getAllEntries() { return allEntries; } - public PolicyEntry getDefaultEntry() - { + public PolicyEntry getDefaultEntry() { return defaultEntry; } - public void setDefaultEntry(PolicyEntry defaultEntry) - { + public void setDefaultEntry(PolicyEntry defaultEntry) { this.defaultEntry = defaultEntry; } - protected Class getEntryClass() - { + protected Class getEntryClass() { return PolicyEntry.class; } } diff --git a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/transport/tcp/TcpTransportFactory.java b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/transport/tcp/TcpTransportFactory.java index 959dea4abe..6279f33d03 100644 --- a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/transport/tcp/TcpTransportFactory.java +++ b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/transport/tcp/TcpTransportFactory.java @@ -39,6 +39,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TcpTransportFactory extends TransportFactory { + private static final Logger LOG = LoggerFactory.getLogger(TcpTransportFactory.class); private static volatile String brokerService = null; @@ -81,19 +82,21 @@ public class TcpTransportFactory extends TransportFactory { server.bind(); return server; - } catch (URISyntaxException e) { + } + catch (URISyntaxException e) { throw IOExceptionSupport.create(e); } } - protected TcpTransportServer createTcpTransportServer(final URI location, ServerSocketFactory serverSocketFactory) throws IOException, URISyntaxException { + protected TcpTransportServer createTcpTransportServer(final URI location, + ServerSocketFactory serverSocketFactory) throws IOException, URISyntaxException { return new TcpTransportServer(this, location, serverSocketFactory); } @SuppressWarnings("rawtypes") public Transport compositeConfigure(Transport transport, WireFormat format, Map options) { - TcpTransport tcpTransport = (TcpTransport)transport.narrow(TcpTransport.class); + TcpTransport tcpTransport = (TcpTransport) transport.narrow(TcpTransport.class); IntrospectionSupport.setProperties(tcpTransport, options); Map socketOptions = IntrospectionSupport.extractProperties(options, "socket."); @@ -102,7 +105,8 @@ public class TcpTransportFactory extends TransportFactory { if (tcpTransport.isTrace()) { try { transport = TransportLoggerSupport.createTransportLogger(transport, tcpTransport.getLogWriterName(), tcpTransport.isDynamicManagement(), tcpTransport.isStartLogging(), tcpTransport.getJmxPort()); - } catch (Throwable e) { + } + catch (Throwable e) { LOG.error("Could not create TransportLogger object for: " + tcpTransport.getLogWriterName() + ", reason: " + e, e); } } @@ -115,7 +119,7 @@ public class TcpTransportFactory extends TransportFactory { // Only need the WireFormatNegotiator if using openwire if (format instanceof OpenWireFormat) { - transport = new WireFormatNegotiator(transport, (OpenWireFormat)format, tcpTransport.getMinmumWireFormatVersion()); + transport = new WireFormatNegotiator(transport, (OpenWireFormat) format, tcpTransport.getMinmumWireFormatVersion()); } return super.compositeConfigure(transport, format, options); @@ -135,9 +139,10 @@ public class TcpTransportFactory extends TransportFactory { Integer.parseInt(path.substring(localPortIndex + 1, path.length())); String localString = location.getScheme() + ":/" + path; localLocation = new URI(localString); - } catch (Exception e) { + } + catch (Exception e) { LOG.warn("path isn't a valid local location for TcpTransport to use", e.getMessage()); - if(LOG.isDebugEnabled()) { + if (LOG.isDebugEnabled()) { LOG.debug("Failure detail", e); } } @@ -146,7 +151,10 @@ public class TcpTransportFactory extends TransportFactory { return createTcpTransport(wf, socketFactory, location, localLocation); } - protected TcpTransport createTcpTransport(WireFormat wf, SocketFactory socketFactory, URI location, URI localLocation) throws UnknownHostException, IOException { + protected TcpTransport createTcpTransport(WireFormat wf, + SocketFactory socketFactory, + URI location, + URI localLocation) throws UnknownHostException, IOException { return new TcpTransport(wf, socketFactory, location, localLocation); } @@ -162,8 +170,7 @@ public class TcpTransportFactory extends TransportFactory { return new InactivityMonitor(transport, format); } - public static void clearService() - { + public static void clearService() { brokerService = null; } } diff --git a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/usage/SystemUsage.java b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/usage/SystemUsage.java index 5086daebe7..e36ab87f63 100644 --- a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/usage/SystemUsage.java +++ b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/usage/SystemUsage.java @@ -52,7 +52,10 @@ public class SystemUsage implements Service { this("default", null, null, null); } - public SystemUsage(String name, PersistenceAdapter adapter, PListStore tempStore, JobSchedulerStore jobSchedulerStore) { + public SystemUsage(String name, + PersistenceAdapter adapter, + PListStore tempStore, + JobSchedulerStore jobSchedulerStore) { this.parent = null; this.name = name; this.memoryUsage = new MemoryUsage(name + ":memory"); @@ -144,7 +147,8 @@ public class SystemUsage implements Service { public boolean isSendFailIfNoSpace() { if (sendFailIfNoSpaceExplicitySet || parent == null) { return sendFailIfNoSpace; - } else { + } + else { return parent.isSendFailIfNoSpace(); } } @@ -176,7 +180,8 @@ public class SystemUsage implements Service { public long getSendFailIfNoSpaceAfterTimeout() { if (sendFailIfNoSpaceAfterTimeoutExplicitySet || parent == null) { return sendFailIfNoSpaceAfterTimeout; - } else { + } + else { return parent.getSendFailIfNoSpaceAfterTimeout(); } } @@ -255,8 +260,7 @@ public class SystemUsage implements Service { } /** - * @param executor - * the executor to set + * @param executor the executor to set */ public void setExecutor(ThreadPoolExecutor executor) { this.executor = executor; @@ -269,7 +273,7 @@ public class SystemUsage implements Service { if (this.tempUsage != null) { this.tempUsage.setExecutor(this.executor); } - if(this.jobSchedulerUsage != null) { + if (this.jobSchedulerUsage != null) { this.jobSchedulerUsage.setExecutor(this.executor); } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ActiveMQConnectionFactoryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ActiveMQConnectionFactoryTest.java index bb1776cfb8..e1ea7e6f8f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ActiveMQConnectionFactoryTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ActiveMQConnectionFactoryTest.java @@ -36,234 +36,234 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ActiveMQConnectionFactoryTest extends CombinationTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(ActiveMQConnectionFactoryTest.class); - private ActiveMQConnection connection; - private BrokerService broker; + private static final Logger LOG = LoggerFactory.getLogger(ActiveMQConnectionFactoryTest.class); - public void testUseURIToSetUseClientIDPrefixOnConnectionFactory() throws URISyntaxException, JMSException { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory( - "vm://localhost?jms.clientIDPrefix=Cheese"); - assertEquals("Cheese", cf.getClientIDPrefix()); + private ActiveMQConnection connection; + private BrokerService broker; - connection = (ActiveMQConnection)cf.createConnection(); - connection.start(); + public void testUseURIToSetUseClientIDPrefixOnConnectionFactory() throws URISyntaxException, JMSException { + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost?jms.clientIDPrefix=Cheese"); + assertEquals("Cheese", cf.getClientIDPrefix()); - String clientID = connection.getClientID(); - LOG.info("Got client ID: " + clientID); + connection = (ActiveMQConnection) cf.createConnection(); + connection.start(); - assertTrue("should start with Cheese! but was: " + clientID, clientID.startsWith("Cheese")); - } + String clientID = connection.getClientID(); + LOG.info("Got client ID: " + clientID); - @Override - public void tearDown() throws Exception { - // Try our best to close any previously opend connection. - try { - connection.close(); - } catch (Throwable ignore) { - } - // Try our best to stop any previously started broker. - try { - broker.stop(); - } catch (Throwable ignore) { - } - try { - ArtemisBrokerHelper.stopArtemisBroker(); - } catch (Throwable ignore) { - } - TcpTransportFactory.clearService(); - } + assertTrue("should start with Cheese! but was: " + clientID, clientID.startsWith("Cheese")); + } - public void testUseURIToSetOptionsOnConnectionFactory() throws URISyntaxException, JMSException { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost?jms.useAsyncSend=true"); - assertTrue(cf.isUseAsyncSend()); - // the broker url have been adjusted. - assertEquals("vm://localhost", cf.getBrokerURL()); + @Override + public void tearDown() throws Exception { + // Try our best to close any previously opend connection. + try { + connection.close(); + } + catch (Throwable ignore) { + } + // Try our best to stop any previously started broker. + try { + broker.stop(); + } + catch (Throwable ignore) { + } + try { + ArtemisBrokerHelper.stopArtemisBroker(); + } + catch (Throwable ignore) { + } + TcpTransportFactory.clearService(); + } - cf = new ActiveMQConnectionFactory("vm://localhost?jms.useAsyncSend=false"); - assertFalse(cf.isUseAsyncSend()); - // the broker url have been adjusted. - assertEquals("vm://localhost", cf.getBrokerURL()); + public void testUseURIToSetOptionsOnConnectionFactory() throws URISyntaxException, JMSException { + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost?jms.useAsyncSend=true"); + assertTrue(cf.isUseAsyncSend()); + // the broker url have been adjusted. + assertEquals("vm://localhost", cf.getBrokerURL()); - cf = new ActiveMQConnectionFactory("vm:(broker:()/localhost)?jms.useAsyncSend=true"); - assertTrue(cf.isUseAsyncSend()); - // the broker url have been adjusted. - assertEquals("vm:(broker:()/localhost)", cf.getBrokerURL()); + cf = new ActiveMQConnectionFactory("vm://localhost?jms.useAsyncSend=false"); + assertFalse(cf.isUseAsyncSend()); + // the broker url have been adjusted. + assertEquals("vm://localhost", cf.getBrokerURL()); - cf = new ActiveMQConnectionFactory("vm://localhost?jms.auditDepth=5000"); - assertEquals(5000, cf.getAuditDepth()); - } + cf = new ActiveMQConnectionFactory("vm:(broker:()/localhost)?jms.useAsyncSend=true"); + assertTrue(cf.isUseAsyncSend()); + // the broker url have been adjusted. + assertEquals("vm:(broker:()/localhost)", cf.getBrokerURL()); - public void testUseURIToConfigureRedeliveryPolicy() throws URISyntaxException, JMSException { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory( - "vm://localhost?jms.redeliveryPolicy.maximumRedeliveries=2"); - assertEquals("connection redeliveries", 2, cf.getRedeliveryPolicy().getMaximumRedeliveries()); + cf = new ActiveMQConnectionFactory("vm://localhost?jms.auditDepth=5000"); + assertEquals(5000, cf.getAuditDepth()); + } - ActiveMQConnection connection = (ActiveMQConnection)cf.createConnection(); - assertEquals("connection redeliveries", 2, connection.getRedeliveryPolicy().getMaximumRedeliveries()); + public void testUseURIToConfigureRedeliveryPolicy() throws URISyntaxException, JMSException { + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost?jms.redeliveryPolicy.maximumRedeliveries=2"); + assertEquals("connection redeliveries", 2, cf.getRedeliveryPolicy().getMaximumRedeliveries()); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer)session.createConsumer(session - .createQueue("FOO.BAR")); - assertEquals("consumer redeliveries", 2, consumer.getRedeliveryPolicy().getMaximumRedeliveries()); - connection.close(); - } + ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection(); + assertEquals("connection redeliveries", 2, connection.getRedeliveryPolicy().getMaximumRedeliveries()); - public void testCreateVMConnectionWithEmbdeddBroker() throws URISyntaxException, JMSException { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://myBroker2?broker.persistent=false"); - // Make sure the broker is not created until the connection is - // instantiated. - assertNull(BrokerRegistry.getInstance().lookup("myBroker2")); - connection = (ActiveMQConnection)cf.createConnection(); - // This should create the connection. - assertNotNull(connection); - // Verify the broker was created. - assertNotNull(BrokerRegistry.getInstance().lookup("myBroker2")); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer) session.createConsumer(session.createQueue("FOO.BAR")); + assertEquals("consumer redeliveries", 2, consumer.getRedeliveryPolicy().getMaximumRedeliveries()); + connection.close(); + } - connection.close(); + public void testCreateVMConnectionWithEmbdeddBroker() throws URISyntaxException, JMSException { + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://myBroker2?broker.persistent=false"); + // Make sure the broker is not created until the connection is + // instantiated. + assertNull(BrokerRegistry.getInstance().lookup("myBroker2")); + connection = (ActiveMQConnection) cf.createConnection(); + // This should create the connection. + assertNotNull(connection); + // Verify the broker was created. + assertNotNull(BrokerRegistry.getInstance().lookup("myBroker2")); - // Verify the broker was destroyed. - assertNull(BrokerRegistry.getInstance().lookup("myBroker2")); - } + connection.close(); - public void testGetBrokerName() throws URISyntaxException, JMSException { - System.out.println("------------------beging testing..............."); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); - connection = (ActiveMQConnection)cf.createConnection(); - connection.start(); + // Verify the broker was destroyed. + assertNull(BrokerRegistry.getInstance().lookup("myBroker2")); + } - String brokerName = connection.getBrokerName(); - LOG.info("Got broker name: " + brokerName); + public void testGetBrokerName() throws URISyntaxException, JMSException { + System.out.println("------------------beging testing..............."); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); + connection = (ActiveMQConnection) cf.createConnection(); + connection.start(); - assertNotNull("No broker name available!", brokerName); - } + String brokerName = connection.getBrokerName(); + LOG.info("Got broker name: " + brokerName); - public void testCreateTcpConnectionUsingAllocatedPort() throws Exception { - assertCreateConnection("tcp://localhost:0?wireFormat.tcpNoDelayEnabled=true"); - } + assertNotNull("No broker name available!", brokerName); + } - public void testCreateTcpConnectionUsingKnownPort() throws Exception { - assertCreateConnection("tcp://localhost:61610?wireFormat.tcpNoDelayEnabled=true"); - } + public void testCreateTcpConnectionUsingAllocatedPort() throws Exception { + assertCreateConnection("tcp://localhost:0?wireFormat.tcpNoDelayEnabled=true"); + } - public void testCreateTcpConnectionUsingKnownLocalPort() throws Exception { - broker = new BrokerService(); - broker.setPersistent(false); - broker.addConnector("tcp://localhost:61610?wireFormat.tcpNoDelayEnabled=true"); - broker.start(); + public void testCreateTcpConnectionUsingKnownPort() throws Exception { + assertCreateConnection("tcp://localhost:61610?wireFormat.tcpNoDelayEnabled=true"); + } - // This should create the connection. - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61610/localhost:51610"); - connection = (ActiveMQConnection)cf.createConnection(); - assertNotNull(connection); + public void testCreateTcpConnectionUsingKnownLocalPort() throws Exception { + broker = new BrokerService(); + broker.setPersistent(false); + broker.addConnector("tcp://localhost:61610?wireFormat.tcpNoDelayEnabled=true"); + broker.start(); - connection.close(); + // This should create the connection. + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61610/localhost:51610"); + connection = (ActiveMQConnection) cf.createConnection(); + assertNotNull(connection); - broker.stop(); - } + connection.close(); - public void testConnectionFailsToConnectToVMBrokerThatIsNotRunning() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?create=false"); - try { - factory.createConnection(); - fail("Expected connection failure."); - } catch (JMSException e) { - } - } + broker.stop(); + } - public void testFactorySerializable() throws Exception { - String clientID = "TestClientID"; - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(); - cf.setClientID(clientID); - ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); - ObjectOutputStream objectsOut = new ObjectOutputStream(bytesOut); - objectsOut.writeObject(cf); - objectsOut.flush(); - byte[] data = bytesOut.toByteArray(); - ByteArrayInputStream bytesIn = new ByteArrayInputStream(data); - ObjectInputStream objectsIn = new ObjectInputStream(bytesIn); - cf = (ActiveMQConnectionFactory)objectsIn.readObject(); - assertEquals(cf.getClientID(), clientID); - } + public void testConnectionFailsToConnectToVMBrokerThatIsNotRunning() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?create=false"); + try { + factory.createConnection(); + fail("Expected connection failure."); + } + catch (JMSException e) { + } + } - public void testSetExceptionListener() throws Exception { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); - connection = (ActiveMQConnection)cf.createConnection(); - assertNull(connection.getExceptionListener()); + public void testFactorySerializable() throws Exception { + String clientID = "TestClientID"; + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(); + cf.setClientID(clientID); + ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); + ObjectOutputStream objectsOut = new ObjectOutputStream(bytesOut); + objectsOut.writeObject(cf); + objectsOut.flush(); + byte[] data = bytesOut.toByteArray(); + ByteArrayInputStream bytesIn = new ByteArrayInputStream(data); + ObjectInputStream objectsIn = new ObjectInputStream(bytesIn); + cf = (ActiveMQConnectionFactory) objectsIn.readObject(); + assertEquals(cf.getClientID(), clientID); + } - ExceptionListener exListener = new ExceptionListener() { - @Override - public void onException(JMSException arg0) { - } - }; - cf.setExceptionListener(exListener); - connection.close(); + public void testSetExceptionListener() throws Exception { + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); + connection = (ActiveMQConnection) cf.createConnection(); + assertNull(connection.getExceptionListener()); - connection = (ActiveMQConnection)cf.createConnection(); - assertNotNull(connection.getExceptionListener()); - assertEquals(exListener, connection.getExceptionListener()); - connection.close(); + ExceptionListener exListener = new ExceptionListener() { + @Override + public void onException(JMSException arg0) { + } + }; + cf.setExceptionListener(exListener); + connection.close(); - connection = (ActiveMQConnection)cf.createConnection(); - assertEquals(exListener, connection.getExceptionListener()); + connection = (ActiveMQConnection) cf.createConnection(); + assertNotNull(connection.getExceptionListener()); + assertEquals(exListener, connection.getExceptionListener()); + connection.close(); - assertEquals(exListener, cf.getExceptionListener()); - connection.close(); + connection = (ActiveMQConnection) cf.createConnection(); + assertEquals(exListener, connection.getExceptionListener()); - } + assertEquals(exListener, cf.getExceptionListener()); + connection.close(); + } - public void testSetClientInternalExceptionListener() throws Exception { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); - connection = (ActiveMQConnection)cf.createConnection(); - assertNull(connection.getClientInternalExceptionListener()); + public void testSetClientInternalExceptionListener() throws Exception { + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); + connection = (ActiveMQConnection) cf.createConnection(); + assertNull(connection.getClientInternalExceptionListener()); - ClientInternalExceptionListener listener = new ClientInternalExceptionListener() { - @Override - public void onException(Throwable exception) { - } - }; - connection.setClientInternalExceptionListener(listener); - cf.setClientInternalExceptionListener(listener); - connection.close(); + ClientInternalExceptionListener listener = new ClientInternalExceptionListener() { + @Override + public void onException(Throwable exception) { + } + }; + connection.setClientInternalExceptionListener(listener); + cf.setClientInternalExceptionListener(listener); + connection.close(); - connection = (ActiveMQConnection)cf.createConnection(); - assertNotNull(connection.getClientInternalExceptionListener()); - assertEquals(listener, connection.getClientInternalExceptionListener()); - connection.close(); + connection = (ActiveMQConnection) cf.createConnection(); + assertNotNull(connection.getClientInternalExceptionListener()); + assertEquals(listener, connection.getClientInternalExceptionListener()); + connection.close(); - connection = (ActiveMQConnection)cf.createConnection(); - assertEquals(listener, connection.getClientInternalExceptionListener()); - assertEquals(listener, cf.getClientInternalExceptionListener()); - connection.close(); + connection = (ActiveMQConnection) cf.createConnection(); + assertEquals(listener, connection.getClientInternalExceptionListener()); + assertEquals(listener, cf.getClientInternalExceptionListener()); + connection.close(); - } + } - protected void assertCreateConnection(String uri) throws Exception { - // Start up a broker with a tcp connector. - broker = new BrokerService(); - broker.setPersistent(false); - broker.setUseJmx(false); - TransportConnector connector = broker.addConnector(uri); - broker.start(); + protected void assertCreateConnection(String uri) throws Exception { + // Start up a broker with a tcp connector. + broker = new BrokerService(); + broker.setPersistent(false); + broker.setUseJmx(false); + TransportConnector connector = broker.addConnector(uri); + broker.start(); - URI temp = new URI(uri); - // URI connectURI = connector.getServer().getConnectURI(); - // TODO this sometimes fails when using the actual local host name - URI currentURI = new URI(connector.getPublishableConnectString()); + URI temp = new URI(uri); + // URI connectURI = connector.getServer().getConnectURI(); + // TODO this sometimes fails when using the actual local host name + URI currentURI = new URI(connector.getPublishableConnectString()); - // sometimes the actual host name doesn't work in this test case - // e.g. on OS X so lets use the original details but just use the actual - // port - URI connectURI = new URI(temp.getScheme(), temp.getUserInfo(), temp.getHost(), currentURI.getPort(), - temp.getPath(), temp.getQuery(), temp.getFragment()); + // sometimes the actual host name doesn't work in this test case + // e.g. on OS X so lets use the original details but just use the actual + // port + URI connectURI = new URI(temp.getScheme(), temp.getUserInfo(), temp.getHost(), currentURI.getPort(), temp.getPath(), temp.getQuery(), temp.getFragment()); - LOG.info("connection URI is: " + connectURI); + LOG.info("connection URI is: " + connectURI); - // This should create the connection. - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(connectURI); - connection = (ActiveMQConnection)cf.createConnection(); - assertNotNull(connection); - } + // This should create the connection. + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(connectURI); + connection = (ActiveMQConnection) cf.createConnection(); + assertNotNull(connection); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ActiveMQInputStreamTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ActiveMQInputStreamTest.java index c3fd2d0f6d..c94a342f14 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ActiveMQInputStreamTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ActiveMQInputStreamTest.java @@ -34,115 +34,117 @@ import org.slf4j.LoggerFactory; @Deprecated public class ActiveMQInputStreamTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(ActiveMQInputStreamTest.class); + private static final Logger LOG = LoggerFactory.getLogger(ActiveMQInputStreamTest.class); - private static final String BROKER_URL = "tcp://localhost:0"; - private static final String DESTINATION = "destination"; - private static final int STREAM_LENGTH = 64 * 1024 + 0; // change 0 to 1 to make it not crash + private static final String BROKER_URL = "tcp://localhost:0"; + private static final String DESTINATION = "destination"; + private static final int STREAM_LENGTH = 64 * 1024 + 0; // change 0 to 1 to make it not crash - private BrokerService broker; - private String connectionUri; + private BrokerService broker; + private String connectionUri; - @Override - public void setUp() throws Exception { - broker = new BrokerService(); - broker.setUseJmx(false); - broker.setPersistent(false); - broker.setDestinations(new ActiveMQDestination[] { - ActiveMQDestination.createDestination(DESTINATION, ActiveMQDestination.QUEUE_TYPE), - }); - broker.addConnector(BROKER_URL); - broker.start(); - broker.waitUntilStarted(); + @Override + public void setUp() throws Exception { + broker = new BrokerService(); + broker.setUseJmx(false); + broker.setPersistent(false); + broker.setDestinations(new ActiveMQDestination[]{ActiveMQDestination.createDestination(DESTINATION, ActiveMQDestination.QUEUE_TYPE),}); + broker.addConnector(BROKER_URL); + broker.start(); + broker.waitUntilStarted(); - //some internal api we don't implement - connectionUri = broker.getDefaultUri(); - } + //some internal api we don't implement + connectionUri = broker.getDefaultUri(); + } - @Override - public void tearDown() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } + @Override + public void tearDown() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + } - public void testInputStreamSetSyncSendOption() throws Exception { + public void testInputStreamSetSyncSendOption() throws Exception { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionUri); - ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue destination = session.createQueue(DESTINATION + "?producer.alwaysSyncSend=true"); + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionUri); + ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue destination = session.createQueue(DESTINATION + "?producer.alwaysSyncSend=true"); - OutputStream out = null; - try { - out = connection.createOutputStream(destination); + OutputStream out = null; + try { + out = connection.createOutputStream(destination); - assertTrue(((ActiveMQOutputStream)out).isAlwaysSyncSend()); + assertTrue(((ActiveMQOutputStream) out).isAlwaysSyncSend()); - LOG.debug("writing..."); - for (int i = 0; i < STREAM_LENGTH; ++i) { - out.write(0); - } - LOG.debug("wrote " + STREAM_LENGTH + " bytes"); - } finally { - if (out != null) { - out.close(); - } - } + LOG.debug("writing..."); + for (int i = 0; i < STREAM_LENGTH; ++i) { + out.write(0); + } + LOG.debug("wrote " + STREAM_LENGTH + " bytes"); + } + finally { + if (out != null) { + out.close(); + } + } - InputStream in = null; - try { - in = connection.createInputStream(destination); - LOG.debug("reading..."); - int count = 0; - while (-1 != in.read()) { - ++count; - } - LOG.debug("read " + count + " bytes"); - } finally { - if (in != null) { - in.close(); - } - } + InputStream in = null; + try { + in = connection.createInputStream(destination); + LOG.debug("reading..."); + int count = 0; + while (-1 != in.read()) { + ++count; + } + LOG.debug("read " + count + " bytes"); + } + finally { + if (in != null) { + in.close(); + } + } - connection.close(); - } + connection.close(); + } - public void testInputStreamMatchesDefaultChuckSize() throws Exception { + public void testInputStreamMatchesDefaultChuckSize() throws Exception { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionUri); - ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue destination = session.createQueue(DESTINATION); + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionUri); + ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue destination = session.createQueue(DESTINATION); - OutputStream out = null; - try { - out = connection.createOutputStream(destination); - LOG.debug("writing..."); - for (int i = 0; i < STREAM_LENGTH; ++i) { - out.write(0); - } - LOG.debug("wrote " + STREAM_LENGTH + " bytes"); - } finally { - if (out != null) { - out.close(); - } - } + OutputStream out = null; + try { + out = connection.createOutputStream(destination); + LOG.debug("writing..."); + for (int i = 0; i < STREAM_LENGTH; ++i) { + out.write(0); + } + LOG.debug("wrote " + STREAM_LENGTH + " bytes"); + } + finally { + if (out != null) { + out.close(); + } + } - InputStream in = null; - try { - in = connection.createInputStream(destination); - LOG.debug("reading..."); - int count = 0; - while (-1 != in.read()) { - ++count; - } - LOG.debug("read " + count + " bytes"); - } finally { - if (in != null) { - in.close(); - } - } + InputStream in = null; + try { + in = connection.createInputStream(destination); + LOG.debug("reading..."); + int count = 0; + while (-1 != in.read()) { + ++count; + } + LOG.debug("read " + count + " bytes"); + } + finally { + if (in != null) { + in.close(); + } + } - connection.close(); - } + connection.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ActiveMQMessageAuditTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ActiveMQMessageAuditTest.java index af18084683..24213a16a2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ActiveMQMessageAuditTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ActiveMQMessageAuditTest.java @@ -22,7 +22,9 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.List; + import junit.framework.TestCase; + import org.apache.activemq.broker.region.MessageReference; import org.apache.activemq.command.ActiveMQMessage; import org.apache.activemq.command.MessageId; @@ -33,154 +35,152 @@ import org.slf4j.LoggerFactory; /** * ActiveMQMessageAuditTest - * - * */ public class ActiveMQMessageAuditTest extends TestCase { - static final Logger LOG = LoggerFactory.getLogger(ActiveMQMessageAuditTest.class); + static final Logger LOG = LoggerFactory.getLogger(ActiveMQMessageAuditTest.class); - /** - * Constructor for ActiveMQMessageAuditTest. - * - * @param name - */ - public ActiveMQMessageAuditTest(String name) { - super(name); - } + /** + * Constructor for ActiveMQMessageAuditTest. + * + * @param name + */ + public ActiveMQMessageAuditTest(String name) { + super(name); + } - public static void main(String[] args) { - } + public static void main(String[] args) { + } - protected void setUp() throws Exception { - super.setUp(); - } + protected void setUp() throws Exception { + super.setUp(); + } - protected void tearDown() throws Exception { - super.tearDown(); - } + protected void tearDown() throws Exception { + super.tearDown(); + } - /** - * test case for isDuplicate - */ - public void testIsDuplicateString() { - int count = 10000; - ActiveMQMessageAudit audit = new ActiveMQMessageAudit(); - IdGenerator idGen = new IdGenerator(); - // add to a list - List list = new ArrayList(); - for (int i = 0; i < count; i++) { - String id = idGen.generateId(); - list.add(id); + /** + * test case for isDuplicate + */ + public void testIsDuplicateString() { + int count = 10000; + ActiveMQMessageAudit audit = new ActiveMQMessageAudit(); + IdGenerator idGen = new IdGenerator(); + // add to a list + List list = new ArrayList(); + for (int i = 0; i < count; i++) { + String id = idGen.generateId(); + list.add(id); + assertFalse(audit.isDuplicate(id)); + } + List windowList = list.subList(list.size() - 1 - audit.getAuditDepth(), list.size() - 1); + for (String id : windowList) { + assertTrue("duplicate, id:" + id, audit.isDuplicate(id)); + } + } + + public void testIsDuplicateMessageReference() { + int count = 10000; + ActiveMQMessageAudit audit = new ActiveMQMessageAudit(); + // add to a list + List list = new ArrayList(); + for (int i = 0; i < count; i++) { + ProducerId pid = new ProducerId(); + pid.setConnectionId("test"); + pid.setSessionId(0); + pid.setValue(1); + MessageId id = new MessageId(); + id.setProducerId(pid); + id.setProducerSequenceId(i); + ActiveMQMessage msg = new ActiveMQMessage(); + msg.setMessageId(id); + list.add(msg); + assertFalse(audit.isDuplicate(msg.getMessageId())); + } + List windowList = list.subList(list.size() - 1 - audit.getAuditDepth(), list.size() - 1); + for (MessageReference msg : windowList) { + assertTrue("duplicate msg:" + msg, audit.isDuplicate(msg)); + } + } + + public void testIsInOrderString() { + int count = 10000; + ActiveMQMessageAudit audit = new ActiveMQMessageAudit(); + IdGenerator idGen = new IdGenerator(); + // add to a list + List list = new ArrayList(); + for (int i = 0; i < count; i++) { + String id = idGen.generateId(); + if (i == 0) { assertFalse(audit.isDuplicate(id)); - } - List windowList = list.subList(list.size() -1 -audit.getAuditDepth(), list.size() -1); - for (String id : windowList) { - assertTrue("duplicate, id:" + id, audit.isDuplicate(id)); - } - } + assertTrue(audit.isInOrder(id)); + } + if (i > 1 && i % 2 != 0) { + list.add(id); + } - public void testIsDuplicateMessageReference() { - int count = 10000; - ActiveMQMessageAudit audit = new ActiveMQMessageAudit(); - // add to a list - List list = new ArrayList(); - for (int i = 0; i < count; i++) { - ProducerId pid = new ProducerId(); - pid.setConnectionId("test"); - pid.setSessionId(0); - pid.setValue(1); + } + for (String id : list) { + assertFalse(audit.isInOrder(id)); + assertFalse(audit.isDuplicate(id)); + } + } + + public void testSerialization() throws Exception { + ActiveMQMessageAuditNoSync audit = new ActiveMQMessageAuditNoSync(); + + byte[] bytes = serialize(audit); + LOG.debug("Length: " + bytes.length); + audit = recover(bytes); + + List list = new ArrayList(); + + for (int j = 0; j < 1000; j++) { + ProducerId pid = new ProducerId(); + pid.setConnectionId("test"); + pid.setSessionId(0); + pid.setValue(j); + LOG.debug("producer " + j); + + for (int i = 0; i < 1000; i++) { MessageId id = new MessageId(); id.setProducerId(pid); id.setProducerSequenceId(i); ActiveMQMessage msg = new ActiveMQMessage(); msg.setMessageId(id); list.add(msg); - assertFalse(audit.isDuplicate(msg.getMessageId())); - } - List windowList = list.subList(list.size() -1 -audit.getAuditDepth(), list.size() -1); - for (MessageReference msg : windowList) { - assertTrue("duplicate msg:" + msg, audit.isDuplicate(msg)); - } - } + assertFalse(audit.isDuplicate(msg.getMessageId().toString())); - public void testIsInOrderString() { - int count = 10000; - ActiveMQMessageAudit audit = new ActiveMQMessageAudit(); - IdGenerator idGen = new IdGenerator(); - // add to a list - List list = new ArrayList(); - for (int i = 0; i < count; i++) { - String id = idGen.generateId(); - if (i==0) { - assertFalse(audit.isDuplicate(id)); - assertTrue(audit.isInOrder(id)); - } - if (i > 1 && i%2 != 0) { - list.add(id); + if (i % 100 == 0) { + bytes = serialize(audit); + LOG.debug("Length: " + bytes.length); + audit = recover(bytes); } - } - for (String id : list) { - assertFalse(audit.isInOrder(id)); - assertFalse(audit.isDuplicate(id)); - } - } - - public void testSerialization() throws Exception { - ActiveMQMessageAuditNoSync audit = new ActiveMQMessageAuditNoSync(); - - byte[] bytes = serialize(audit); - LOG.debug("Length: " + bytes.length); - audit = recover(bytes); - - List list = new ArrayList(); - - for (int j = 0; j < 1000; j++) { - ProducerId pid = new ProducerId(); - pid.setConnectionId("test"); - pid.setSessionId(0); - pid.setValue(j); - LOG.debug("producer " + j); - - for (int i = 0; i < 1000; i++) { - MessageId id = new MessageId(); - id.setProducerId(pid); - id.setProducerSequenceId(i); - ActiveMQMessage msg = new ActiveMQMessage(); - msg.setMessageId(id); - list.add(msg); - assertFalse(audit.isDuplicate(msg.getMessageId().toString())); - - if (i % 100 == 0) { - bytes = serialize(audit); - LOG.debug("Length: " + bytes.length); - audit = recover(bytes); - } - - if (i % 250 == 0) { - for (MessageReference message : list) { - audit.rollback(message.getMessageId().toString()); - } - list.clear(); - bytes = serialize(audit); - LOG.debug("Length: " + bytes.length); - audit = recover(bytes); - } + if (i % 250 == 0) { + for (MessageReference message : list) { + audit.rollback(message.getMessageId().toString()); + } + list.clear(); + bytes = serialize(audit); + LOG.debug("Length: " + bytes.length); + audit = recover(bytes); } - } - } + } + } + } - protected byte[] serialize(ActiveMQMessageAuditNoSync audit) throws Exception { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oout = new ObjectOutputStream(baos); - oout.writeObject(audit); - oout.flush(); - return baos.toByteArray(); - } + protected byte[] serialize(ActiveMQMessageAuditNoSync audit) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(baos); + oout.writeObject(audit); + oout.flush(); + return baos.toByteArray(); + } - protected ActiveMQMessageAuditNoSync recover(byte[] bytes) throws Exception { - ObjectInputStream objectIn = new ObjectInputStream(new ByteArrayInputStream(bytes)); - return (ActiveMQMessageAuditNoSync)objectIn.readObject(); - } + protected ActiveMQMessageAuditNoSync recover(byte[] bytes) throws Exception { + ObjectInputStream objectIn = new ObjectInputStream(new ByteArrayInputStream(bytes)); + return (ActiveMQMessageAuditNoSync) objectIn.readObject(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ActiveMQSslConnectionFactoryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ActiveMQSslConnectionFactoryTest.java index 5d1ec8034e..e85f6a87c0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ActiveMQSslConnectionFactoryTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ActiveMQSslConnectionFactoryTest.java @@ -34,229 +34,229 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class ActiveMQSslConnectionFactoryTest extends CombinationTestSupport { - private static final Log LOG = LogFactory.getLog(ActiveMQSslConnectionFactoryTest.class); - public static final String KEYSTORE_TYPE = "jks"; - public static final String PASSWORD = "password"; - public static final String SERVER_KEYSTORE = "src/test/resources/server.keystore"; - public static final String TRUST_KEYSTORE = "src/test/resources/client.keystore"; + private static final Log LOG = LogFactory.getLog(ActiveMQSslConnectionFactoryTest.class); - private ActiveMQConnection connection; - private BrokerService broker; + public static final String KEYSTORE_TYPE = "jks"; + public static final String PASSWORD = "password"; + public static final String SERVER_KEYSTORE = "src/test/resources/server.keystore"; + public static final String TRUST_KEYSTORE = "src/test/resources/client.keystore"; - @Override - protected void tearDown() throws Exception { - // Try our best to close any previously opend connection. - try { - connection.close(); - } catch (Throwable ignore) { - } - // Try our best to stop any previously started broker. - try { - broker.stop(); - } catch (Throwable ignore) { - } - } + private ActiveMQConnection connection; + private BrokerService broker; - public void testCreateTcpConnectionUsingKnownPort() throws Exception { - // Control case: check that the factory can create an ordinary (non-ssl) connection. - broker = createBroker("tcp://localhost:61610?wireFormat.tcpNoDelayEnabled=true"); + @Override + protected void tearDown() throws Exception { + // Try our best to close any previously opend connection. + try { + connection.close(); + } + catch (Throwable ignore) { + } + // Try our best to stop any previously started broker. + try { + broker.stop(); + } + catch (Throwable ignore) { + } + } - // This should create the connection. - ActiveMQSslConnectionFactory cf = new ActiveMQSslConnectionFactory("tcp://localhost:61610?wireFormat.tcpNoDelayEnabled=true"); - connection = (ActiveMQConnection)cf.createConnection(); - assertNotNull(connection); - connection.start(); - connection.stop(); - brokerStop(); - } + public void testCreateTcpConnectionUsingKnownPort() throws Exception { + // Control case: check that the factory can create an ordinary (non-ssl) connection. + broker = createBroker("tcp://localhost:61610?wireFormat.tcpNoDelayEnabled=true"); - public void testCreateFailoverTcpConnectionUsingKnownPort() throws Exception { - // Control case: check that the factory can create an ordinary (non-ssl) connection. - broker = createBroker("tcp://localhost:61610?wireFormat.tcpNoDelayEnabled=true"); + // This should create the connection. + ActiveMQSslConnectionFactory cf = new ActiveMQSslConnectionFactory("tcp://localhost:61610?wireFormat.tcpNoDelayEnabled=true"); + connection = (ActiveMQConnection) cf.createConnection(); + assertNotNull(connection); + connection.start(); + connection.stop(); + brokerStop(); + } - // This should create the connection. - ActiveMQSslConnectionFactory cf = new ActiveMQSslConnectionFactory("failover:(tcp://localhost:61610?wireFormat.tcpNoDelayEnabled=true)"); - connection = (ActiveMQConnection)cf.createConnection(); - assertNotNull(connection); - connection.start(); - connection.stop(); - brokerStop(); - } + public void testCreateFailoverTcpConnectionUsingKnownPort() throws Exception { + // Control case: check that the factory can create an ordinary (non-ssl) connection. + broker = createBroker("tcp://localhost:61610?wireFormat.tcpNoDelayEnabled=true"); - public void testCreateSslConnection() throws Exception { - // Create SSL/TLS connection with trusted cert from truststore. - String sslUri = "ssl://localhost:61611"; - broker = createSslBroker(sslUri); - assertNotNull(broker); + // This should create the connection. + ActiveMQSslConnectionFactory cf = new ActiveMQSslConnectionFactory("failover:(tcp://localhost:61610?wireFormat.tcpNoDelayEnabled=true)"); + connection = (ActiveMQConnection) cf.createConnection(); + assertNotNull(connection); + connection.start(); + connection.stop(); + brokerStop(); + } - // This should create the connection. - ActiveMQSslConnectionFactory cf = new ActiveMQSslConnectionFactory(sslUri); - cf.setTrustStore("server.keystore"); - cf.setTrustStorePassword("password"); - connection = (ActiveMQConnection)cf.createConnection(); - LOG.info("Created client connection"); - assertNotNull(connection); - connection.start(); - connection.stop(); - brokerStop(); - } + public void testCreateSslConnection() throws Exception { + // Create SSL/TLS connection with trusted cert from truststore. + String sslUri = "ssl://localhost:61611"; + broker = createSslBroker(sslUri); + assertNotNull(broker); - public void testFailoverSslConnection() throws Exception { - // Create SSL/TLS connection with trusted cert from truststore. - String sslUri = "ssl://localhost:61611"; - broker = createSslBroker(sslUri); - assertNotNull(broker); + // This should create the connection. + ActiveMQSslConnectionFactory cf = new ActiveMQSslConnectionFactory(sslUri); + cf.setTrustStore("server.keystore"); + cf.setTrustStorePassword("password"); + connection = (ActiveMQConnection) cf.createConnection(); + LOG.info("Created client connection"); + assertNotNull(connection); + connection.start(); + connection.stop(); + brokerStop(); + } - // This should create the connection. - ActiveMQSslConnectionFactory cf = new ActiveMQSslConnectionFactory("failover:(" + sslUri + ")?maxReconnectAttempts=4"); - cf.setTrustStore("server.keystore"); - cf.setTrustStorePassword("password"); - connection = (ActiveMQConnection)cf.createConnection(); - LOG.info("Created client connection"); - assertNotNull(connection); - connection.start(); - connection.stop(); + public void testFailoverSslConnection() throws Exception { + // Create SSL/TLS connection with trusted cert from truststore. + String sslUri = "ssl://localhost:61611"; + broker = createSslBroker(sslUri); + assertNotNull(broker); - brokerStop(); - } + // This should create the connection. + ActiveMQSslConnectionFactory cf = new ActiveMQSslConnectionFactory("failover:(" + sslUri + ")?maxReconnectAttempts=4"); + cf.setTrustStore("server.keystore"); + cf.setTrustStorePassword("password"); + connection = (ActiveMQConnection) cf.createConnection(); + LOG.info("Created client connection"); + assertNotNull(connection); + connection.start(); + connection.stop(); - public void testFailoverSslConnectionWithKeyAndTrustManagers() throws Exception { - String sslUri = "ssl://localhost:61611"; - broker = createSslBroker(sslUri); - assertNotNull(broker); + brokerStop(); + } - ActiveMQSslConnectionFactory cf = new ActiveMQSslConnectionFactory("failover:(" + sslUri + ")?maxReconnectAttempts=4"); - cf.setKeyAndTrustManagers(getKeyManager(), getTrustManager(), new SecureRandom()); - connection = (ActiveMQConnection)cf.createConnection(); - LOG.info("Created client connection"); - assertNotNull(connection); - connection.start(); - connection.stop(); + public void testFailoverSslConnectionWithKeyAndTrustManagers() throws Exception { + String sslUri = "ssl://localhost:61611"; + broker = createSslBroker(sslUri); + assertNotNull(broker); - brokerStop(); - } + ActiveMQSslConnectionFactory cf = new ActiveMQSslConnectionFactory("failover:(" + sslUri + ")?maxReconnectAttempts=4"); + cf.setKeyAndTrustManagers(getKeyManager(), getTrustManager(), new SecureRandom()); + connection = (ActiveMQConnection) cf.createConnection(); + LOG.info("Created client connection"); + assertNotNull(connection); + connection.start(); + connection.stop(); - public void testNegativeCreateSslConnectionWithWrongPassword() throws Exception { - // Create SSL/TLS connection with trusted cert from truststore. - String sslUri = "ssl://localhost:61611"; - broker = createSslBroker(sslUri); - assertNotNull(broker); + brokerStop(); + } - // This should FAIL to connect, due to wrong password. - ActiveMQSslConnectionFactory cf = new ActiveMQSslConnectionFactory(sslUri); - cf.setTrustStore("server.keystore"); - cf.setTrustStorePassword("wrongPassword"); - try { - connection = (ActiveMQConnection)cf.createConnection(); - } - catch (javax.jms.JMSException ignore) { - // Expected exception - LOG.info("Expected java.io.Exception [" + ignore + "]"); - } - assertNull(connection); + public void testNegativeCreateSslConnectionWithWrongPassword() throws Exception { + // Create SSL/TLS connection with trusted cert from truststore. + String sslUri = "ssl://localhost:61611"; + broker = createSslBroker(sslUri); + assertNotNull(broker); - brokerStop(); - } + // This should FAIL to connect, due to wrong password. + ActiveMQSslConnectionFactory cf = new ActiveMQSslConnectionFactory(sslUri); + cf.setTrustStore("server.keystore"); + cf.setTrustStorePassword("wrongPassword"); + try { + connection = (ActiveMQConnection) cf.createConnection(); + } + catch (javax.jms.JMSException ignore) { + // Expected exception + LOG.info("Expected java.io.Exception [" + ignore + "]"); + } + assertNull(connection); - public void testNegativeCreateSslConnectionWithWrongCert() throws Exception { - // Create SSL/TLS connection with trusted cert from truststore. - String sslUri = "ssl://localhost:61611"; - broker = createSslBroker(sslUri); - assertNotNull(broker); + brokerStop(); + } - // This should FAIL to connect, due to wrong password. - ActiveMQSslConnectionFactory cf = new ActiveMQSslConnectionFactory(sslUri); - cf.setTrustStore("dummy.keystore"); - cf.setTrustStorePassword("password"); - try { - connection = (ActiveMQConnection)cf.createConnection(); - } - catch (javax.jms.JMSException ignore) { - // Expected exception - LOG.info("Expected SSLHandshakeException [" + ignore + "]"); - } - assertNull(connection); + public void testNegativeCreateSslConnectionWithWrongCert() throws Exception { + // Create SSL/TLS connection with trusted cert from truststore. + String sslUri = "ssl://localhost:61611"; + broker = createSslBroker(sslUri); + assertNotNull(broker); - brokerStop(); - } + // This should FAIL to connect, due to wrong password. + ActiveMQSslConnectionFactory cf = new ActiveMQSslConnectionFactory(sslUri); + cf.setTrustStore("dummy.keystore"); + cf.setTrustStorePassword("password"); + try { + connection = (ActiveMQConnection) cf.createConnection(); + } + catch (javax.jms.JMSException ignore) { + // Expected exception + LOG.info("Expected SSLHandshakeException [" + ignore + "]"); + } + assertNull(connection); - protected BrokerService createBroker(String uri) throws Exception { - // Start up a broker with a tcp connector. - BrokerService service = new BrokerService(); - service.setPersistent(false); - service.setUseJmx(false); - service.addConnector(uri); - service.start(); + brokerStop(); + } - return service; - } + protected BrokerService createBroker(String uri) throws Exception { + // Start up a broker with a tcp connector. + BrokerService service = new BrokerService(); + service.setPersistent(false); + service.setUseJmx(false); + service.addConnector(uri); + service.start(); - protected BrokerService createSslBroker(String uri) throws Exception { + return service; + } - // http://java.sun.com/javase/javaseforbusiness/docs/TLSReadme.html - // work around: javax.net.ssl.SSLHandshakeException: renegotiation is not allowed - //System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true"); + protected BrokerService createSslBroker(String uri) throws Exception { - SslBrokerService service = new SslBrokerService(); - service.setPersistent(false); + // http://java.sun.com/javase/javaseforbusiness/docs/TLSReadme.html + // work around: javax.net.ssl.SSLHandshakeException: renegotiation is not allowed + //System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true"); - service.setupSsl(KEYSTORE_TYPE, PASSWORD, SERVER_KEYSTORE); + SslBrokerService service = new SslBrokerService(); + service.setPersistent(false); - service.start(); + service.setupSsl(KEYSTORE_TYPE, PASSWORD, SERVER_KEYSTORE); - return service; - } + service.start(); - protected void brokerStop() throws Exception { - broker.stop(); - } + return service; + } - public static TrustManager[] getTrustManager() throws Exception { - TrustManager[] trustStoreManagers = null; - KeyStore trustedCertStore = KeyStore.getInstance(ActiveMQSslConnectionFactoryTest.KEYSTORE_TYPE); + protected void brokerStop() throws Exception { + broker.stop(); + } - trustedCertStore.load(new FileInputStream(ActiveMQSslConnectionFactoryTest.TRUST_KEYSTORE), null); - TrustManagerFactory tmf = - TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + public static TrustManager[] getTrustManager() throws Exception { + TrustManager[] trustStoreManagers = null; + KeyStore trustedCertStore = KeyStore.getInstance(ActiveMQSslConnectionFactoryTest.KEYSTORE_TYPE); - tmf.init(trustedCertStore); - trustStoreManagers = tmf.getTrustManagers(); - return trustStoreManagers; - } + trustedCertStore.load(new FileInputStream(ActiveMQSslConnectionFactoryTest.TRUST_KEYSTORE), null); + TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - public static KeyManager[] getKeyManager() throws Exception { - KeyManagerFactory kmf = - KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); - KeyStore ks = KeyStore.getInstance(ActiveMQSslConnectionFactoryTest.KEYSTORE_TYPE); - KeyManager[] keystoreManagers = null; + tmf.init(trustedCertStore); + trustStoreManagers = tmf.getTrustManagers(); + return trustStoreManagers; + } - byte[] sslCert = loadClientCredential(ActiveMQSslConnectionFactoryTest.SERVER_KEYSTORE); + public static KeyManager[] getKeyManager() throws Exception { + KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + KeyStore ks = KeyStore.getInstance(ActiveMQSslConnectionFactoryTest.KEYSTORE_TYPE); + KeyManager[] keystoreManagers = null; + byte[] sslCert = loadClientCredential(ActiveMQSslConnectionFactoryTest.SERVER_KEYSTORE); - if (sslCert != null && sslCert.length > 0) { - ByteArrayInputStream bin = new ByteArrayInputStream(sslCert); - ks.load(bin, ActiveMQSslConnectionFactoryTest.PASSWORD.toCharArray()); - kmf.init(ks, ActiveMQSslConnectionFactoryTest.PASSWORD.toCharArray()); - keystoreManagers = kmf.getKeyManagers(); - } - return keystoreManagers; - } + if (sslCert != null && sslCert.length > 0) { + ByteArrayInputStream bin = new ByteArrayInputStream(sslCert); + ks.load(bin, ActiveMQSslConnectionFactoryTest.PASSWORD.toCharArray()); + kmf.init(ks, ActiveMQSslConnectionFactoryTest.PASSWORD.toCharArray()); + keystoreManagers = kmf.getKeyManagers(); + } + return keystoreManagers; + } - private static byte[] loadClientCredential(String fileName) throws IOException { - if (fileName == null) { - return null; - } - FileInputStream in = new FileInputStream(fileName); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - byte[] buf = new byte[512]; - int i = in.read(buf); - while (i > 0) { - out.write(buf, 0, i); - i = in.read(buf); - } - in.close(); - return out.toByteArray(); - } + private static byte[] loadClientCredential(String fileName) throws IOException { + if (fileName == null) { + return null; + } + FileInputStream in = new FileInputStream(fileName); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buf = new byte[512]; + int i = in.read(buf); + while (i > 0) { + out.write(buf, 0, i); + i = in.read(buf); + } + in.close(); + return out.toByteArray(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ActiveMQXAConnectionFactoryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ActiveMQXAConnectionFactoryTest.java index bafcaa6120..fa745ba26c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ActiveMQXAConnectionFactoryTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ActiveMQXAConnectionFactoryTest.java @@ -54,532 +54,547 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ActiveMQXAConnectionFactoryTest extends CombinationTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(ActiveMQXAConnectionFactoryTest.class); - long txGenerator = System.currentTimeMillis(); - private ActiveMQConnection connection; - private BrokerService broker; - @Override - public void tearDown() throws Exception { - // Try our best to close any previously opend connection. - try { - connection.close(); - } catch (Throwable ignore) { - } - // Try our best to stop any previously started broker. - try { - broker.stop(); - } catch (Throwable ignore) { - } - super.tearDown(); - } + private static final Logger LOG = LoggerFactory.getLogger(ActiveMQXAConnectionFactoryTest.class); + long txGenerator = System.currentTimeMillis(); + private ActiveMQConnection connection; + private BrokerService broker; - public void testCopy() throws URISyntaxException, JMSException { - ActiveMQXAConnectionFactory cf = new ActiveMQXAConnectionFactory("vm://localhost?"); - ActiveMQConnectionFactory copy = cf.copy(); - assertTrue("Should be an ActiveMQXAConnectionFactory", copy instanceof ActiveMQXAConnectionFactory); - } + @Override + public void tearDown() throws Exception { + // Try our best to close any previously opend connection. + try { + connection.close(); + } + catch (Throwable ignore) { + } + // Try our best to stop any previously started broker. + try { + broker.stop(); + } + catch (Throwable ignore) { + } + super.tearDown(); + } - public void testUseURIToSetOptionsOnConnectionFactory() throws URISyntaxException, JMSException { - ActiveMQXAConnectionFactory cf = new ActiveMQXAConnectionFactory( - "vm://localhost?jms.useAsyncSend=true"); - assertTrue(cf.isUseAsyncSend()); - // the broker url have been adjusted. - assertEquals("vm://localhost", cf.getBrokerURL()); + public void testCopy() throws URISyntaxException, JMSException { + ActiveMQXAConnectionFactory cf = new ActiveMQXAConnectionFactory("vm://localhost?"); + ActiveMQConnectionFactory copy = cf.copy(); + assertTrue("Should be an ActiveMQXAConnectionFactory", copy instanceof ActiveMQXAConnectionFactory); + } - cf = new ActiveMQXAConnectionFactory("vm://localhost?jms.useAsyncSend=false"); - assertFalse(cf.isUseAsyncSend()); - // the broker url have been adjusted. - assertEquals("vm://localhost", cf.getBrokerURL()); + public void testUseURIToSetOptionsOnConnectionFactory() throws URISyntaxException, JMSException { + ActiveMQXAConnectionFactory cf = new ActiveMQXAConnectionFactory("vm://localhost?jms.useAsyncSend=true"); + assertTrue(cf.isUseAsyncSend()); + // the broker url have been adjusted. + assertEquals("vm://localhost", cf.getBrokerURL()); - cf = new ActiveMQXAConnectionFactory("vm:(broker:()/localhost)?jms.useAsyncSend=true"); - assertTrue(cf.isUseAsyncSend()); - // the broker url have been adjusted. - assertEquals("vm:(broker:()/localhost)", cf.getBrokerURL()); + cf = new ActiveMQXAConnectionFactory("vm://localhost?jms.useAsyncSend=false"); + assertFalse(cf.isUseAsyncSend()); + // the broker url have been adjusted. + assertEquals("vm://localhost", cf.getBrokerURL()); - cf = new ActiveMQXAConnectionFactory( - "vm://localhost?jms.redeliveryPolicy.maximumRedeliveries=10&" + - "jms.redeliveryPolicy.initialRedeliveryDelay=10000&" + - "jms.redeliveryPolicy.redeliveryDelay=10000&" + - "jms.redeliveryPolicy.useExponentialBackOff=true&" + - "jms.redeliveryPolicy.backOffMultiplier=2"); - assertEquals(10, cf.getRedeliveryPolicy().getMaximumRedeliveries()); - assertEquals(10000, cf.getRedeliveryPolicy().getInitialRedeliveryDelay()); - assertEquals(10000, cf.getRedeliveryPolicy().getRedeliveryDelay()); - assertEquals(true, cf.getRedeliveryPolicy().isUseExponentialBackOff()); - assertEquals(2.0, cf.getRedeliveryPolicy().getBackOffMultiplier(), 0.1); + cf = new ActiveMQXAConnectionFactory("vm:(broker:()/localhost)?jms.useAsyncSend=true"); + assertTrue(cf.isUseAsyncSend()); + // the broker url have been adjusted. + assertEquals("vm:(broker:()/localhost)", cf.getBrokerURL()); - // the broker url have been adjusted. - assertEquals("vm://localhost", cf.getBrokerURL()); - } + cf = new ActiveMQXAConnectionFactory("vm://localhost?jms.redeliveryPolicy.maximumRedeliveries=10&" + + "jms.redeliveryPolicy.initialRedeliveryDelay=10000&" + + "jms.redeliveryPolicy.redeliveryDelay=10000&" + + "jms.redeliveryPolicy.useExponentialBackOff=true&" + + "jms.redeliveryPolicy.backOffMultiplier=2"); + assertEquals(10, cf.getRedeliveryPolicy().getMaximumRedeliveries()); + assertEquals(10000, cf.getRedeliveryPolicy().getInitialRedeliveryDelay()); + assertEquals(10000, cf.getRedeliveryPolicy().getRedeliveryDelay()); + assertEquals(true, cf.getRedeliveryPolicy().isUseExponentialBackOff()); + assertEquals(2.0, cf.getRedeliveryPolicy().getBackOffMultiplier(), 0.1); - public void testCreateVMConnectionWithEmbdeddBroker() throws URISyntaxException, JMSException { - ActiveMQXAConnectionFactory cf = new ActiveMQXAConnectionFactory("vm://myBroker?broker.persistent=false"); - // Make sure the broker is not created until the connection is - // instantiated. - assertNull(BrokerRegistry.getInstance().lookup("myBroker")); - connection = (ActiveMQConnection) cf.createConnection(); - // This should create the connection. - assertNotNull(connection); - // Verify the broker was created. - assertNotNull(BrokerRegistry.getInstance().lookup("myBroker")); - connection.close(); - // Verify the broker was destroyed. - assertNull(BrokerRegistry.getInstance().lookup("myBroker")); + // the broker url have been adjusted. + assertEquals("vm://localhost", cf.getBrokerURL()); + } - connection.close(); - } + public void testCreateVMConnectionWithEmbdeddBroker() throws URISyntaxException, JMSException { + ActiveMQXAConnectionFactory cf = new ActiveMQXAConnectionFactory("vm://myBroker?broker.persistent=false"); + // Make sure the broker is not created until the connection is + // instantiated. + assertNull(BrokerRegistry.getInstance().lookup("myBroker")); + connection = (ActiveMQConnection) cf.createConnection(); + // This should create the connection. + assertNotNull(connection); + // Verify the broker was created. + assertNotNull(BrokerRegistry.getInstance().lookup("myBroker")); + connection.close(); + // Verify the broker was destroyed. + assertNull(BrokerRegistry.getInstance().lookup("myBroker")); - public void testGetBrokerName() throws URISyntaxException, JMSException { - ActiveMQXAConnectionFactory cf = new ActiveMQXAConnectionFactory("vm://localhost?broker.persistent=false"); - connection = (ActiveMQConnection)cf.createConnection(); - connection.start(); + connection.close(); + } - String brokerName = connection.getBrokerName(); - LOG.info("Got broker name: " + brokerName); + public void testGetBrokerName() throws URISyntaxException, JMSException { + ActiveMQXAConnectionFactory cf = new ActiveMQXAConnectionFactory("vm://localhost?broker.persistent=false"); + connection = (ActiveMQConnection) cf.createConnection(); + connection.start(); - assertNotNull("No broker name available!", brokerName); - connection.close(); - } + String brokerName = connection.getBrokerName(); + LOG.info("Got broker name: " + brokerName); - public void testCreateTcpConnectionUsingAllocatedPort() throws Exception { - assertCreateConnection("tcp://localhost:0?wireFormat.tcpNoDelayEnabled=true"); - } + assertNotNull("No broker name available!", brokerName); + connection.close(); + } - public void testCreateTcpConnectionUsingKnownPort() throws Exception { - assertCreateConnection("tcp://localhost:61610?wireFormat.tcpNoDelayEnabled=true"); - } + public void testCreateTcpConnectionUsingAllocatedPort() throws Exception { + assertCreateConnection("tcp://localhost:0?wireFormat.tcpNoDelayEnabled=true"); + } - public void testIsSameRM() throws URISyntaxException, JMSException, XAException { + public void testCreateTcpConnectionUsingKnownPort() throws Exception { + assertCreateConnection("tcp://localhost:61610?wireFormat.tcpNoDelayEnabled=true"); + } - XAConnection connection1 = null; - XAConnection connection2 = null; - try { - ActiveMQXAConnectionFactory cf1 = new ActiveMQXAConnectionFactory("vm://localhost?broker.persistent=false"); - connection1 = (XAConnection)cf1.createConnection(); - XASession session1 = connection1.createXASession(); - XAResource resource1 = session1.getXAResource(); + public void testIsSameRM() throws URISyntaxException, JMSException, XAException { - ActiveMQXAConnectionFactory cf2 = new ActiveMQXAConnectionFactory("vm://localhost?broker.persistent=false"); - connection2 = (XAConnection)cf2.createConnection(); - XASession session2 = connection2.createXASession(); - XAResource resource2 = session2.getXAResource(); + XAConnection connection1 = null; + XAConnection connection2 = null; + try { + ActiveMQXAConnectionFactory cf1 = new ActiveMQXAConnectionFactory("vm://localhost?broker.persistent=false"); + connection1 = (XAConnection) cf1.createConnection(); + XASession session1 = connection1.createXASession(); + XAResource resource1 = session1.getXAResource(); - assertTrue(resource1.isSameRM(resource2)); - session1.close(); - session2.close(); - } finally { - if (connection1 != null) { - try { - connection1.close(); - } catch (Exception e) { - // ignore - } + ActiveMQXAConnectionFactory cf2 = new ActiveMQXAConnectionFactory("vm://localhost?broker.persistent=false"); + connection2 = (XAConnection) cf2.createConnection(); + XASession session2 = connection2.createXASession(); + XAResource resource2 = session2.getXAResource(); + + assertTrue(resource1.isSameRM(resource2)); + session1.close(); + session2.close(); + } + finally { + if (connection1 != null) { + try { + connection1.close(); } - if (connection2 != null) { - try { - connection2.close(); - } catch (Exception e) { - // ignore - } + catch (Exception e) { + // ignore } - } - } - - public void testIsSameRMOverride() throws URISyntaxException, JMSException, XAException { - - XAConnection connection1 = null; - XAConnection connection2 = null; - try { - ActiveMQXAConnectionFactory cf1 = new ActiveMQXAConnectionFactory("vm://localhost?broker.persistent=false&jms.rmIdFromConnectionId=true"); - connection1 = (XAConnection)cf1.createConnection(); - XASession session1 = connection1.createXASession(); - XAResource resource1 = session1.getXAResource(); - - ActiveMQXAConnectionFactory cf2 = new ActiveMQXAConnectionFactory("vm://localhost?broker.persistent=false"); - connection2 = (XAConnection)cf2.createConnection(); - XASession session2 = connection2.createXASession(); - XAResource resource2 = session2.getXAResource(); - - assertFalse(resource1.isSameRM(resource2)); - - // ensure identity is preserved - XASession session1a = connection1.createXASession(); - assertTrue(resource1.isSameRM(session1a.getXAResource())); - session1.close(); - session2.close(); - } finally { - if (connection1 != null) { - try { - connection1.close(); - } catch (Exception e) { - // ignore - } + } + if (connection2 != null) { + try { + connection2.close(); } - if (connection2 != null) { - try { - connection2.close(); - } catch (Exception e) { - // ignore - } + catch (Exception e) { + // ignore } - } - } + } + } + } - public void testVanilaTransactionalProduceReceive() throws Exception { + public void testIsSameRMOverride() throws URISyntaxException, JMSException, XAException { - XAConnection connection1 = null; - try { - ActiveMQXAConnectionFactory cf1 = new ActiveMQXAConnectionFactory("vm://localhost?broker.persistent=false"); - connection1 = (XAConnection)cf1.createConnection(); - connection1.start(); - XASession session = connection1.createXASession(); - XAResource resource = session.getXAResource(); - Destination dest = new ActiveMQQueue(getName()); + XAConnection connection1 = null; + XAConnection connection2 = null; + try { + ActiveMQXAConnectionFactory cf1 = new ActiveMQXAConnectionFactory("vm://localhost?broker.persistent=false&jms.rmIdFromConnectionId=true"); + connection1 = (XAConnection) cf1.createConnection(); + XASession session1 = connection1.createXASession(); + XAResource resource1 = session1.getXAResource(); - // publish a message - Xid tid = createXid(); - resource.start(tid, XAResource.TMNOFLAGS); - MessageProducer producer = session.createProducer(dest); - ActiveMQTextMessage message = new ActiveMQTextMessage(); - message.setText(getName()); - producer.send(message); - resource.end(tid, XAResource.TMSUCCESS); - resource.commit(tid, true); - session.close(); + ActiveMQXAConnectionFactory cf2 = new ActiveMQXAConnectionFactory("vm://localhost?broker.persistent=false"); + connection2 = (XAConnection) cf2.createConnection(); + XASession session2 = connection2.createXASession(); + XAResource resource2 = session2.getXAResource(); - session = connection1.createXASession(); - MessageConsumer consumer = session.createConsumer(dest); - tid = createXid(); - resource = session.getXAResource(); - resource.start(tid, XAResource.TMNOFLAGS); - TextMessage receivedMessage = (TextMessage) consumer.receive(1000); - assertNotNull(receivedMessage); - assertEquals(getName(), receivedMessage.getText()); - resource.end(tid, XAResource.TMSUCCESS); - resource.commit(tid, true); - session.close(); + assertFalse(resource1.isSameRM(resource2)); - } finally { - if (connection1 != null) { - try { - connection1.close(); - } catch (Exception e) { - // ignore - } + // ensure identity is preserved + XASession session1a = connection1.createXASession(); + assertTrue(resource1.isSameRM(session1a.getXAResource())); + session1.close(); + session2.close(); + } + finally { + if (connection1 != null) { + try { + connection1.close(); } - } - } - - public void testConsumerCloseTransactionalSendReceive() throws Exception { - - ActiveMQXAConnectionFactory cf1 = new ActiveMQXAConnectionFactory("vm://localhost?broker.persistent=false"); - XAConnection connection1 = (XAConnection)cf1.createConnection(); - connection1.start(); - XASession session = connection1.createXASession(); - XAResource resource = session.getXAResource(); - Destination dest = new ActiveMQQueue(getName()); - - // publish a message - Xid tid = createXid(); - resource.start(tid, XAResource.TMNOFLAGS); - MessageProducer producer = session.createProducer(dest); - ActiveMQTextMessage message = new ActiveMQTextMessage(); - message.setText(getName()); - producer.send(message); - producer.close(); - resource.end(tid, XAResource.TMSUCCESS); - resource.commit(tid, true); - session.close(); - - session = connection1.createXASession(); - MessageConsumer consumer = session.createConsumer(dest); - tid = createXid(); - resource = session.getXAResource(); - resource.start(tid, XAResource.TMNOFLAGS); - TextMessage receivedMessage = (TextMessage) consumer.receive(1000); - consumer.close(); - assertNotNull(receivedMessage); - assertEquals(getName(), receivedMessage.getText()); - resource.end(tid, XAResource.TMSUCCESS); - resource.commit(tid, true); - - session = connection1.createXASession(); - consumer = session.createConsumer(dest); - tid = createXid(); - resource = session.getXAResource(); - resource.start(tid, XAResource.TMNOFLAGS); - assertNull(consumer.receive(1000)); - resource.end(tid, XAResource.TMSUCCESS); - resource.commit(tid, true); - - } - - public void testSessionCloseTransactionalSendReceive() throws Exception { - - ActiveMQXAConnectionFactory cf1 = new ActiveMQXAConnectionFactory("vm://localhost?broker.persistent=false"); - XAConnection connection1 = (XAConnection)cf1.createConnection(); - connection1.start(); - XASession session = connection1.createXASession(); - XAResource resource = session.getXAResource(); - Destination dest = new ActiveMQQueue(getName()); - - // publish a message - Xid tid = createXid(); - resource.start(tid, XAResource.TMNOFLAGS); - MessageProducer producer = session.createProducer(dest); - ActiveMQTextMessage message = new ActiveMQTextMessage(); - message.setText(getName()); - producer.send(message); - session.close(); - resource.end(tid, XAResource.TMSUCCESS); - resource.commit(tid, true); - - - session = connection1.createXASession(); - MessageConsumer consumer = session.createConsumer(dest); - tid = createXid(); - resource = session.getXAResource(); - resource.start(tid, XAResource.TMNOFLAGS); - TextMessage receivedMessage = (TextMessage) consumer.receive(1000); - session.close(); - assertNotNull(receivedMessage); - assertEquals(getName(), receivedMessage.getText()); - resource.end(tid, XAResource.TMSUCCESS); - resource.commit(tid, true); - - session = connection1.createXASession(); - consumer = session.createConsumer(dest); - tid = createXid(); - resource = session.getXAResource(); - resource.start(tid, XAResource.TMNOFLAGS); - assertNull(consumer.receive(1000)); - resource.end(tid, XAResource.TMSUCCESS); - resource.commit(tid, true); - } - - - public void testReadonlyNoLeak() throws Exception { - final String brokerName = "readOnlyNoLeak"; - BrokerService broker = BrokerFactory.createBroker(new URI("broker:(tcp://localhost:0)/" + brokerName)); - broker.setPersistent(false); - broker.start(); - ActiveMQXAConnectionFactory cf1 = new ActiveMQXAConnectionFactory("failover:(" + broker.getTransportConnectors().get(0).getConnectUri() + ")"); - cf1.setStatsEnabled(true); - ActiveMQXAConnection xaConnection = (ActiveMQXAConnection)cf1.createConnection(); - xaConnection.start(); - XASession session = xaConnection.createXASession(); - XAResource resource = session.getXAResource(); - Xid tid = createXid(); - resource.start(tid, XAResource.TMNOFLAGS); - session.close(); - resource.end(tid, XAResource.TMSUCCESS); - resource.commit(tid, true); - - assertTransactionGoneFromBroker(tid); - assertTransactionGoneFromConnection(brokerName, xaConnection.getClientID(), xaConnection.getConnectionInfo().getConnectionId(), tid); - assertSessionGone(xaConnection, session); - assertTransactionGoneFromFailoverState(xaConnection, tid); - - // two phase - session = xaConnection.createXASession(); - resource = session.getXAResource(); - tid = createXid(); - resource.start(tid, XAResource.TMNOFLAGS); - session.close(); - resource.end(tid, XAResource.TMSUCCESS); - assertEquals(XAResource.XA_RDONLY, resource.prepare(tid)); - - // no need for a commit on read only - assertTransactionGoneFromBroker(tid); - assertTransactionGoneFromConnection(brokerName, xaConnection.getClientID(), xaConnection.getConnectionInfo().getConnectionId(), tid); - assertSessionGone(xaConnection, session); - assertTransactionGoneFromFailoverState(xaConnection, tid); - - xaConnection.close(); - broker.stop(); - - } - - public void testCloseSendConnection() throws Exception { - String brokerName = "closeSend"; - BrokerService broker = BrokerFactory.createBroker(new URI("broker:(tcp://localhost:0)/" + brokerName)); - broker.start(); - broker.waitUntilStarted(); - ActiveMQXAConnectionFactory cf = new ActiveMQXAConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri()); - XAConnection connection = (XAConnection)cf.createConnection(); - connection.start(); - XASession session = connection.createXASession(); - XAResource resource = session.getXAResource(); - Destination dest = new ActiveMQQueue(getName()); - - // publish a message - Xid tid = createXid(); - resource.start(tid, XAResource.TMNOFLAGS); - MessageProducer producer = session.createProducer(dest); - ActiveMQTextMessage message = new ActiveMQTextMessage(); - message.setText(getName()); - producer.send(message); - - connection.close(); - - assertTransactionGoneFromBroker(tid); - - broker.stop(); - } - - public void testExceptionAfterClose() throws Exception { - - ActiveMQXAConnectionFactory cf1 = new ActiveMQXAConnectionFactory("vm://localhost?broker.persistent=false"); - XAConnection connection1 = (XAConnection)cf1.createConnection(); - connection1.start(); - - XASession session = connection1.createXASession(); - session.close(); - try { - session.commit(); - fail("expect exception after close"); - } catch (javax.jms.IllegalStateException expected) {} - - try { - session.rollback(); - fail("expect exception after close"); - } catch (javax.jms.IllegalStateException expected) {} - - try { - session.getTransacted(); - fail("expect exception after close"); - } catch (javax.jms.IllegalStateException expected) {} - } - - public void testRollbackXaErrorCode() throws Exception { - String brokerName = "rollbackErrorCode"; - BrokerService broker = BrokerFactory.createBroker(new URI("broker:(tcp://localhost:0)/" + brokerName)); - broker.start(); - broker.waitUntilStarted(); - ActiveMQXAConnectionFactory cf = new ActiveMQXAConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri()); - XAConnection connection = (XAConnection)cf.createConnection(); - connection.start(); - XASession session = connection.createXASession(); - XAResource resource = session.getXAResource(); - - Xid tid = createXid(); - try { - resource.rollback(tid); - fail("Expected xa exception on no tx"); - } catch (XAException expected) { - LOG.info("got expected xa", expected); - assertEquals("no tx", XAException.XAER_NOTA, expected.errorCode); - } - connection.close(); - broker.stop(); - } - - private void assertTransactionGoneFromFailoverState( - ActiveMQXAConnection connection1, Xid tid) throws Exception { - - FailoverTransport transport = (FailoverTransport) connection1.getTransport().narrow(FailoverTransport.class); - TransactionInfo info = new TransactionInfo(connection1.getConnectionInfo().getConnectionId(), new XATransactionId(tid), TransactionInfo.COMMIT_ONE_PHASE); - assertNull("transaction should not exist in the state tracker", - transport.getStateTracker().processCommitTransactionOnePhase(info)); - } - - private void assertSessionGone(ActiveMQXAConnection connection1, - XASession session) { - JMSConnectionStatsImpl stats = (JMSConnectionStatsImpl)connection1.getStats(); - // should be no dangling sessions maintained by the transaction - assertEquals("should be no sessions", 0, stats.getSessions().length); - } - - private void assertTransactionGoneFromConnection(String brokerName, String clientId, ConnectionId connectionId, Xid tid) throws Exception { - BrokerService broker = BrokerRegistry.getInstance().lookup(brokerName); - CopyOnWriteArrayList connections = broker.getTransportConnectors().get(0).getConnections(); - for (TransportConnection connection: connections) { - if (connection.getConnectionId().equals(clientId)) { - try { - connection.processPrepareTransaction(new TransactionInfo(connectionId, new XATransactionId(tid), TransactionInfo.PREPARE)); - fail("did not get expected excepton on missing transaction, it must be still there in error!"); - } catch (IllegalStateException expectedOnNoTransaction) { - } + catch (Exception e) { + // ignore } - } - } - - private void assertTransactionGoneFromBroker(Xid tid) throws Exception { - BrokerService broker = BrokerRegistry.getInstance().lookup("localhost"); - TransactionBroker transactionBroker = (TransactionBroker)broker.getBroker().getAdaptor(TransactionBroker.class); - try { - transactionBroker.getTransaction(null, new XATransactionId(tid), false); - fail("expected exception on tx not found"); - } catch (XAException expectedOnNotFound) { - } - } - - protected void assertCreateConnection(String uri) throws Exception { - // Start up a broker with a tcp connector. - broker = new BrokerService(); - broker.setPersistent(false); - broker.setUseJmx(false); - TransportConnector connector = broker.addConnector(uri); - broker.start(); - - URI temp = new URI(uri); - // URI connectURI = connector.getServer().getConnectURI(); - // TODO this sometimes fails when using the actual local host name - URI currentURI = new URI(connector.getPublishableConnectString()); - - // sometimes the actual host name doesn't work in this test case - // e.g. on OS X so lets use the original details but just use the actual - // port - URI connectURI = new URI(temp.getScheme(), temp.getUserInfo(), temp.getHost(), currentURI.getPort(), - temp.getPath(), temp.getQuery(), temp.getFragment()); - - LOG.info("connection URI is: " + connectURI); - - // This should create the connection. - ActiveMQXAConnectionFactory cf = new ActiveMQXAConnectionFactory(connectURI); - Connection connection = cf.createConnection(); - - assertXAConnection(connection); - - assertNotNull(connection); - connection.close(); - - connection = cf.createXAConnection(); - - assertXAConnection(connection); - - assertNotNull(connection); - } - - private void assertXAConnection(Connection connection) { - assertTrue("Should be an XAConnection", connection instanceof XAConnection); - assertTrue("Should be an XATopicConnection", connection instanceof XATopicConnection); - assertTrue("Should be an XAQueueConnection", connection instanceof XAQueueConnection); - } - - public Xid createXid() throws IOException { - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream os = new DataOutputStream(baos); - os.writeLong(++txGenerator); - os.close(); - final byte[] bs = baos.toByteArray(); - - return new Xid() { - public int getFormatId() { - return 86; + } + if (connection2 != null) { + try { + connection2.close(); } - - public byte[] getGlobalTransactionId() { - return bs; + catch (Exception e) { + // ignore } + } + } + } - public byte[] getBranchQualifier() { - return bs; + public void testVanilaTransactionalProduceReceive() throws Exception { + + XAConnection connection1 = null; + try { + ActiveMQXAConnectionFactory cf1 = new ActiveMQXAConnectionFactory("vm://localhost?broker.persistent=false"); + connection1 = (XAConnection) cf1.createConnection(); + connection1.start(); + XASession session = connection1.createXASession(); + XAResource resource = session.getXAResource(); + Destination dest = new ActiveMQQueue(getName()); + + // publish a message + Xid tid = createXid(); + resource.start(tid, XAResource.TMNOFLAGS); + MessageProducer producer = session.createProducer(dest); + ActiveMQTextMessage message = new ActiveMQTextMessage(); + message.setText(getName()); + producer.send(message); + resource.end(tid, XAResource.TMSUCCESS); + resource.commit(tid, true); + session.close(); + + session = connection1.createXASession(); + MessageConsumer consumer = session.createConsumer(dest); + tid = createXid(); + resource = session.getXAResource(); + resource.start(tid, XAResource.TMNOFLAGS); + TextMessage receivedMessage = (TextMessage) consumer.receive(1000); + assertNotNull(receivedMessage); + assertEquals(getName(), receivedMessage.getText()); + resource.end(tid, XAResource.TMSUCCESS); + resource.commit(tid, true); + session.close(); + + } + finally { + if (connection1 != null) { + try { + connection1.close(); } - }; + catch (Exception e) { + // ignore + } + } + } + } - } + public void testConsumerCloseTransactionalSendReceive() throws Exception { + + ActiveMQXAConnectionFactory cf1 = new ActiveMQXAConnectionFactory("vm://localhost?broker.persistent=false"); + XAConnection connection1 = (XAConnection) cf1.createConnection(); + connection1.start(); + XASession session = connection1.createXASession(); + XAResource resource = session.getXAResource(); + Destination dest = new ActiveMQQueue(getName()); + + // publish a message + Xid tid = createXid(); + resource.start(tid, XAResource.TMNOFLAGS); + MessageProducer producer = session.createProducer(dest); + ActiveMQTextMessage message = new ActiveMQTextMessage(); + message.setText(getName()); + producer.send(message); + producer.close(); + resource.end(tid, XAResource.TMSUCCESS); + resource.commit(tid, true); + session.close(); + + session = connection1.createXASession(); + MessageConsumer consumer = session.createConsumer(dest); + tid = createXid(); + resource = session.getXAResource(); + resource.start(tid, XAResource.TMNOFLAGS); + TextMessage receivedMessage = (TextMessage) consumer.receive(1000); + consumer.close(); + assertNotNull(receivedMessage); + assertEquals(getName(), receivedMessage.getText()); + resource.end(tid, XAResource.TMSUCCESS); + resource.commit(tid, true); + + session = connection1.createXASession(); + consumer = session.createConsumer(dest); + tid = createXid(); + resource = session.getXAResource(); + resource.start(tid, XAResource.TMNOFLAGS); + assertNull(consumer.receive(1000)); + resource.end(tid, XAResource.TMSUCCESS); + resource.commit(tid, true); + + } + + public void testSessionCloseTransactionalSendReceive() throws Exception { + + ActiveMQXAConnectionFactory cf1 = new ActiveMQXAConnectionFactory("vm://localhost?broker.persistent=false"); + XAConnection connection1 = (XAConnection) cf1.createConnection(); + connection1.start(); + XASession session = connection1.createXASession(); + XAResource resource = session.getXAResource(); + Destination dest = new ActiveMQQueue(getName()); + + // publish a message + Xid tid = createXid(); + resource.start(tid, XAResource.TMNOFLAGS); + MessageProducer producer = session.createProducer(dest); + ActiveMQTextMessage message = new ActiveMQTextMessage(); + message.setText(getName()); + producer.send(message); + session.close(); + resource.end(tid, XAResource.TMSUCCESS); + resource.commit(tid, true); + + session = connection1.createXASession(); + MessageConsumer consumer = session.createConsumer(dest); + tid = createXid(); + resource = session.getXAResource(); + resource.start(tid, XAResource.TMNOFLAGS); + TextMessage receivedMessage = (TextMessage) consumer.receive(1000); + session.close(); + assertNotNull(receivedMessage); + assertEquals(getName(), receivedMessage.getText()); + resource.end(tid, XAResource.TMSUCCESS); + resource.commit(tid, true); + + session = connection1.createXASession(); + consumer = session.createConsumer(dest); + tid = createXid(); + resource = session.getXAResource(); + resource.start(tid, XAResource.TMNOFLAGS); + assertNull(consumer.receive(1000)); + resource.end(tid, XAResource.TMSUCCESS); + resource.commit(tid, true); + } + + public void testReadonlyNoLeak() throws Exception { + final String brokerName = "readOnlyNoLeak"; + BrokerService broker = BrokerFactory.createBroker(new URI("broker:(tcp://localhost:0)/" + brokerName)); + broker.setPersistent(false); + broker.start(); + ActiveMQXAConnectionFactory cf1 = new ActiveMQXAConnectionFactory("failover:(" + broker.getTransportConnectors().get(0).getConnectUri() + ")"); + cf1.setStatsEnabled(true); + ActiveMQXAConnection xaConnection = (ActiveMQXAConnection) cf1.createConnection(); + xaConnection.start(); + XASession session = xaConnection.createXASession(); + XAResource resource = session.getXAResource(); + Xid tid = createXid(); + resource.start(tid, XAResource.TMNOFLAGS); + session.close(); + resource.end(tid, XAResource.TMSUCCESS); + resource.commit(tid, true); + + assertTransactionGoneFromBroker(tid); + assertTransactionGoneFromConnection(brokerName, xaConnection.getClientID(), xaConnection.getConnectionInfo().getConnectionId(), tid); + assertSessionGone(xaConnection, session); + assertTransactionGoneFromFailoverState(xaConnection, tid); + + // two phase + session = xaConnection.createXASession(); + resource = session.getXAResource(); + tid = createXid(); + resource.start(tid, XAResource.TMNOFLAGS); + session.close(); + resource.end(tid, XAResource.TMSUCCESS); + assertEquals(XAResource.XA_RDONLY, resource.prepare(tid)); + + // no need for a commit on read only + assertTransactionGoneFromBroker(tid); + assertTransactionGoneFromConnection(brokerName, xaConnection.getClientID(), xaConnection.getConnectionInfo().getConnectionId(), tid); + assertSessionGone(xaConnection, session); + assertTransactionGoneFromFailoverState(xaConnection, tid); + + xaConnection.close(); + broker.stop(); + + } + + public void testCloseSendConnection() throws Exception { + String brokerName = "closeSend"; + BrokerService broker = BrokerFactory.createBroker(new URI("broker:(tcp://localhost:0)/" + brokerName)); + broker.start(); + broker.waitUntilStarted(); + ActiveMQXAConnectionFactory cf = new ActiveMQXAConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri()); + XAConnection connection = (XAConnection) cf.createConnection(); + connection.start(); + XASession session = connection.createXASession(); + XAResource resource = session.getXAResource(); + Destination dest = new ActiveMQQueue(getName()); + + // publish a message + Xid tid = createXid(); + resource.start(tid, XAResource.TMNOFLAGS); + MessageProducer producer = session.createProducer(dest); + ActiveMQTextMessage message = new ActiveMQTextMessage(); + message.setText(getName()); + producer.send(message); + + connection.close(); + + assertTransactionGoneFromBroker(tid); + + broker.stop(); + } + + public void testExceptionAfterClose() throws Exception { + + ActiveMQXAConnectionFactory cf1 = new ActiveMQXAConnectionFactory("vm://localhost?broker.persistent=false"); + XAConnection connection1 = (XAConnection) cf1.createConnection(); + connection1.start(); + + XASession session = connection1.createXASession(); + session.close(); + try { + session.commit(); + fail("expect exception after close"); + } + catch (javax.jms.IllegalStateException expected) { + } + + try { + session.rollback(); + fail("expect exception after close"); + } + catch (javax.jms.IllegalStateException expected) { + } + + try { + session.getTransacted(); + fail("expect exception after close"); + } + catch (javax.jms.IllegalStateException expected) { + } + } + + public void testRollbackXaErrorCode() throws Exception { + String brokerName = "rollbackErrorCode"; + BrokerService broker = BrokerFactory.createBroker(new URI("broker:(tcp://localhost:0)/" + brokerName)); + broker.start(); + broker.waitUntilStarted(); + ActiveMQXAConnectionFactory cf = new ActiveMQXAConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri()); + XAConnection connection = (XAConnection) cf.createConnection(); + connection.start(); + XASession session = connection.createXASession(); + XAResource resource = session.getXAResource(); + + Xid tid = createXid(); + try { + resource.rollback(tid); + fail("Expected xa exception on no tx"); + } + catch (XAException expected) { + LOG.info("got expected xa", expected); + assertEquals("no tx", XAException.XAER_NOTA, expected.errorCode); + } + connection.close(); + broker.stop(); + } + + private void assertTransactionGoneFromFailoverState(ActiveMQXAConnection connection1, Xid tid) throws Exception { + + FailoverTransport transport = (FailoverTransport) connection1.getTransport().narrow(FailoverTransport.class); + TransactionInfo info = new TransactionInfo(connection1.getConnectionInfo().getConnectionId(), new XATransactionId(tid), TransactionInfo.COMMIT_ONE_PHASE); + assertNull("transaction should not exist in the state tracker", transport.getStateTracker().processCommitTransactionOnePhase(info)); + } + + private void assertSessionGone(ActiveMQXAConnection connection1, XASession session) { + JMSConnectionStatsImpl stats = (JMSConnectionStatsImpl) connection1.getStats(); + // should be no dangling sessions maintained by the transaction + assertEquals("should be no sessions", 0, stats.getSessions().length); + } + + private void assertTransactionGoneFromConnection(String brokerName, + String clientId, + ConnectionId connectionId, + Xid tid) throws Exception { + BrokerService broker = BrokerRegistry.getInstance().lookup(brokerName); + CopyOnWriteArrayList connections = broker.getTransportConnectors().get(0).getConnections(); + for (TransportConnection connection : connections) { + if (connection.getConnectionId().equals(clientId)) { + try { + connection.processPrepareTransaction(new TransactionInfo(connectionId, new XATransactionId(tid), TransactionInfo.PREPARE)); + fail("did not get expected excepton on missing transaction, it must be still there in error!"); + } + catch (IllegalStateException expectedOnNoTransaction) { + } + } + } + } + + private void assertTransactionGoneFromBroker(Xid tid) throws Exception { + BrokerService broker = BrokerRegistry.getInstance().lookup("localhost"); + TransactionBroker transactionBroker = (TransactionBroker) broker.getBroker().getAdaptor(TransactionBroker.class); + try { + transactionBroker.getTransaction(null, new XATransactionId(tid), false); + fail("expected exception on tx not found"); + } + catch (XAException expectedOnNotFound) { + } + } + + protected void assertCreateConnection(String uri) throws Exception { + // Start up a broker with a tcp connector. + broker = new BrokerService(); + broker.setPersistent(false); + broker.setUseJmx(false); + TransportConnector connector = broker.addConnector(uri); + broker.start(); + + URI temp = new URI(uri); + // URI connectURI = connector.getServer().getConnectURI(); + // TODO this sometimes fails when using the actual local host name + URI currentURI = new URI(connector.getPublishableConnectString()); + + // sometimes the actual host name doesn't work in this test case + // e.g. on OS X so lets use the original details but just use the actual + // port + URI connectURI = new URI(temp.getScheme(), temp.getUserInfo(), temp.getHost(), currentURI.getPort(), temp.getPath(), temp.getQuery(), temp.getFragment()); + + LOG.info("connection URI is: " + connectURI); + + // This should create the connection. + ActiveMQXAConnectionFactory cf = new ActiveMQXAConnectionFactory(connectURI); + Connection connection = cf.createConnection(); + + assertXAConnection(connection); + + assertNotNull(connection); + connection.close(); + + connection = cf.createXAConnection(); + + assertXAConnection(connection); + + assertNotNull(connection); + } + + private void assertXAConnection(Connection connection) { + assertTrue("Should be an XAConnection", connection instanceof XAConnection); + assertTrue("Should be an XATopicConnection", connection instanceof XATopicConnection); + assertTrue("Should be an XAQueueConnection", connection instanceof XAQueueConnection); + } + + public Xid createXid() throws IOException { + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream os = new DataOutputStream(baos); + os.writeLong(++txGenerator); + os.close(); + final byte[] bs = baos.toByteArray(); + + return new Xid() { + public int getFormatId() { + return 86; + } + + public byte[] getGlobalTransactionId() { + return bs; + } + + public byte[] getBranchQualifier() { + return bs; + } + }; + + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ClientTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ClientTestSupport.java index eafe359540..afa6846476 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ClientTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ClientTestSupport.java @@ -45,133 +45,136 @@ import org.apache.activemq.transport.TransportFactory; public class ClientTestSupport extends TestCase { - protected BrokerService broker; - protected long idGenerator; + protected BrokerService broker; + protected long idGenerator; - private ActiveMQConnectionFactory connFactory; - private final String brokerURL = "vm://localhost?broker.persistent=false"; + private ActiveMQConnectionFactory connFactory; + private final String brokerURL = "vm://localhost?broker.persistent=false"; - @Override - public void setUp() throws Exception { - final AtomicBoolean connected = new AtomicBoolean(false); - TransportConnector connector; + @Override + public void setUp() throws Exception { + final AtomicBoolean connected = new AtomicBoolean(false); + TransportConnector connector; - // Start up a broker with a tcp connector. - try { - broker = BrokerFactory.createBroker(new URI(this.brokerURL)); - broker.getBrokerName(); - connector = new TransportConnector(TransportFactory.bind(new URI(this.brokerURL))) { - // Hook into the connector so we can assert that the server - // accepted a connection. - @Override - protected org.apache.activemq.broker.Connection createConnection(org.apache.activemq.transport.Transport transport) throws IOException { - connected.set(true); - return super.createConnection(transport); - } - }; - broker.addConnector(connector); - broker.start(); - - } catch (IOException e) { - throw new JMSException("Error creating broker " + e); - } catch (URISyntaxException e) { - throw new JMSException("Error creating broker " + e); - } - - URI connectURI; - connectURI = connector.getServer().getConnectURI(); - - // This should create the connection. - connFactory = new ActiveMQConnectionFactory(connectURI); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - if (broker != null) { - broker.stop(); - } - } - - public ActiveMQConnectionFactory getConnectionFactory() throws JMSException { - if (this.connFactory == null) { - throw new JMSException("ActiveMQConnectionFactory is null "); - } - return this.connFactory; - } - - // Helper Classes - protected ConnectionInfo createConnectionInfo() throws Exception { - ConnectionInfo info = new ConnectionInfo(); - info.setConnectionId(new ConnectionId("connection:" + (++idGenerator))); - info.setClientId(info.getConnectionId().getValue()); - return info; - } - - protected SessionInfo createSessionInfo(ConnectionInfo connectionInfo) throws Exception { - SessionInfo info = new SessionInfo(connectionInfo, ++idGenerator); - return info; - } - - protected ConsumerInfo createConsumerInfo(SessionInfo sessionInfo, ActiveMQDestination destination) throws Exception { - ConsumerInfo info = new ConsumerInfo(sessionInfo, ++idGenerator); - info.setBrowser(false); - info.setDestination(destination); - info.setPrefetchSize(1000); - info.setDispatchAsync(false); - return info; - } - - protected RemoveInfo closeConsumerInfo(ConsumerInfo consumerInfo) { - return consumerInfo.createRemoveCommand(); - } - - protected MessageAck createAck(ConsumerInfo consumerInfo, Message msg, int count, byte ackType) { - MessageAck ack = new MessageAck(); - ack.setAckType(ackType); - ack.setConsumerId(consumerInfo.getConsumerId()); - ack.setDestination(msg.getDestination()); - ack.setLastMessageId(msg.getMessageId()); - ack.setMessageCount(count); - return ack; - } - - protected Message receiveMessage(StubConnection connection, int maxWait) throws InterruptedException { - while (true) { - Object o = connection.getDispatchQueue().poll(maxWait, TimeUnit.MILLISECONDS); - - if (o == null) { - return null; + // Start up a broker with a tcp connector. + try { + broker = BrokerFactory.createBroker(new URI(this.brokerURL)); + broker.getBrokerName(); + connector = new TransportConnector(TransportFactory.bind(new URI(this.brokerURL))) { + // Hook into the connector so we can assert that the server + // accepted a connection. + @Override + protected org.apache.activemq.broker.Connection createConnection(org.apache.activemq.transport.Transport transport) throws IOException { + connected.set(true); + return super.createConnection(transport); } + }; + broker.addConnector(connector); + broker.start(); - if (o instanceof MessageDispatch) { - MessageDispatch dispatch = (MessageDispatch)o; - return dispatch.getMessage(); - } - } - } + } + catch (IOException e) { + throw new JMSException("Error creating broker " + e); + } + catch (URISyntaxException e) { + throw new JMSException("Error creating broker " + e); + } - protected Broker getBroker() throws Exception { - return this.broker != null ? this.broker.getBroker() : null; - } + URI connectURI; + connectURI = connector.getServer().getConnectURI(); - public static void removeMessageStore() { - if (System.getProperty("activemq.store.dir") != null) { - recursiveDelete(new File(System.getProperty("activemq.store.dir"))); - } - if (System.getProperty("derby.system.home") != null) { - recursiveDelete(new File(System.getProperty("derby.system.home"))); - } - } + // This should create the connection. + connFactory = new ActiveMQConnectionFactory(connectURI); + } - public static void recursiveDelete(File f) { - if (f.isDirectory()) { - File[] files = f.listFiles(); - for (int i = 0; i < files.length; i++) { - recursiveDelete(files[i]); - } - } - f.delete(); - } + @Override + protected void tearDown() throws Exception { + super.tearDown(); + if (broker != null) { + broker.stop(); + } + } + + public ActiveMQConnectionFactory getConnectionFactory() throws JMSException { + if (this.connFactory == null) { + throw new JMSException("ActiveMQConnectionFactory is null "); + } + return this.connFactory; + } + + // Helper Classes + protected ConnectionInfo createConnectionInfo() throws Exception { + ConnectionInfo info = new ConnectionInfo(); + info.setConnectionId(new ConnectionId("connection:" + (++idGenerator))); + info.setClientId(info.getConnectionId().getValue()); + return info; + } + + protected SessionInfo createSessionInfo(ConnectionInfo connectionInfo) throws Exception { + SessionInfo info = new SessionInfo(connectionInfo, ++idGenerator); + return info; + } + + protected ConsumerInfo createConsumerInfo(SessionInfo sessionInfo, + ActiveMQDestination destination) throws Exception { + ConsumerInfo info = new ConsumerInfo(sessionInfo, ++idGenerator); + info.setBrowser(false); + info.setDestination(destination); + info.setPrefetchSize(1000); + info.setDispatchAsync(false); + return info; + } + + protected RemoveInfo closeConsumerInfo(ConsumerInfo consumerInfo) { + return consumerInfo.createRemoveCommand(); + } + + protected MessageAck createAck(ConsumerInfo consumerInfo, Message msg, int count, byte ackType) { + MessageAck ack = new MessageAck(); + ack.setAckType(ackType); + ack.setConsumerId(consumerInfo.getConsumerId()); + ack.setDestination(msg.getDestination()); + ack.setLastMessageId(msg.getMessageId()); + ack.setMessageCount(count); + return ack; + } + + protected Message receiveMessage(StubConnection connection, int maxWait) throws InterruptedException { + while (true) { + Object o = connection.getDispatchQueue().poll(maxWait, TimeUnit.MILLISECONDS); + + if (o == null) { + return null; + } + + if (o instanceof MessageDispatch) { + MessageDispatch dispatch = (MessageDispatch) o; + return dispatch.getMessage(); + } + } + } + + protected Broker getBroker() throws Exception { + return this.broker != null ? this.broker.getBroker() : null; + } + + public static void removeMessageStore() { + if (System.getProperty("activemq.store.dir") != null) { + recursiveDelete(new File(System.getProperty("activemq.store.dir"))); + } + if (System.getProperty("derby.system.home") != null) { + recursiveDelete(new File(System.getProperty("derby.system.home"))); + } + } + + public static void recursiveDelete(File f) { + if (f.isDirectory()) { + File[] files = f.listFiles(); + for (int i = 0; i < files.length; i++) { + recursiveDelete(files[i]); + } + } + f.delete(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/CombinationTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/CombinationTestSupport.java index f26a97542c..2b1b3bb590 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/CombinationTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/CombinationTestSupport.java @@ -47,10 +47,10 @@ import org.slf4j.LoggerFactory; * combinations of options. Usage: If you have a test case called testFoo what * you want to run through a few combinations, of of values for the attributes * age and color, you would something like: - * public void initCombosForTestFoo() { - * addCombinationValues( "age", new Object[]{ new Integer(21), new Integer(30) } ); - * addCombinationValues( "color", new Object[]{"blue", "green"} ); - * } + * public void initCombosForTestFoo() { + * addCombinationValues( "age", new Object[]{ new Integer(21), new Integer(30) } ); + * addCombinationValues( "color", new Object[]{"blue", "green"} ); + * } * * The testFoo test case would be run for each possible combination of age and * color that you setup in the initCombosForTestFoo method. Before each @@ -58,257 +58,261 @@ import org.slf4j.LoggerFactory; * of the values defined. This is done before the normal setUp method is called. * If you want the test combinations to show up as separate test runs in the * JUnit reports, add a suite method to your test case similar to: - * public static Test suite() { - * return suite(FooTest.class); - * } + * public static Test suite() { + * return suite(FooTest.class); + * } * - * - * */ public abstract class CombinationTestSupport extends AutoFailTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(CombinationTestSupport.class); + private static final Logger LOG = LoggerFactory.getLogger(CombinationTestSupport.class); - private final HashMap comboOptions = new HashMap(); - private boolean combosEvaluated; - private Map options; - protected File basedir; + private final HashMap comboOptions = new HashMap(); + private boolean combosEvaluated; + private Map options; + protected File basedir; - static protected File basedir(Class clazz) { - try { - ProtectionDomain protectionDomain = clazz.getProtectionDomain(); - return new File(new File(protectionDomain.getCodeSource().getLocation().getPath()), "../..").getCanonicalFile(); - } catch (IOException e) { - return new File("."); - } - } + static protected File basedir(Class clazz) { + try { + ProtectionDomain protectionDomain = clazz.getProtectionDomain(); + return new File(new File(protectionDomain.getCodeSource().getLocation().getPath()), "../..").getCanonicalFile(); + } + catch (IOException e) { + return new File("."); + } + } - static class ComboOption { - final String attribute; - final LinkedHashSet values = new LinkedHashSet(); + static class ComboOption { - public ComboOption(String attribute, Collection options) { - this.attribute = attribute; - this.values.addAll(options); - } - } + final String attribute; + final LinkedHashSet values = new LinkedHashSet(); - public CombinationTestSupport() { - basedir = basedir(getClass()); - } - public void addCombinationValues(String attribute, Object[] options) { - ComboOption co = this.comboOptions.get(attribute); - if (co == null) { - this.comboOptions.put(attribute, new ComboOption(attribute, Arrays.asList(options))); - } else { - co.values.addAll(Arrays.asList(options)); - } - } + public ComboOption(String attribute, Collection options) { + this.attribute = attribute; + this.values.addAll(options); + } + } - @Override - protected void tearDown() throws Exception - { - super.tearDown(); - checkStopped(); - } + public CombinationTestSupport() { + basedir = basedir(getClass()); + } - public static void checkStopped() throws Exception - { - ArtemisBrokerHelper.stopArtemisBroker(); - boolean notStopped = BrokerService.checkStopped(); - TcpTransportFactory.setBrokerName(null); - if (notStopped) - { - fail("brokers not stopped see exceptions above"); - } - ServerSocket socket = null; - try - { - socket = new ServerSocket(61616); - } - catch (IOException e) - { - fail("61616 port not released"); - } - finally - { - if (socket != null) - try - { - socket.close(); - } - catch (IOException e) - { - } - } - } + public void addCombinationValues(String attribute, Object[] options) { + ComboOption co = this.comboOptions.get(attribute); + if (co == null) { + this.comboOptions.put(attribute, new ComboOption(attribute, Arrays.asList(options))); + } + else { + co.values.addAll(Arrays.asList(options)); + } + } - @Override - public void runBare() throws Throwable { - if (combosEvaluated) { - super.runBare(); - } else { - CombinationTestSupport[] combinations = getCombinations(); - for (int i = 0; i < combinations.length; i++) { - CombinationTestSupport test = combinations[i]; - if (getName() == null || getName().equals(test.getName())) { - test.runBare(); - } - } - } - } + @Override + protected void tearDown() throws Exception { + super.tearDown(); + checkStopped(); + } - private void setOptions(Map options) throws NoSuchFieldException, IllegalAccessException { - this.options = options; - for (Iterator iterator = options.keySet().iterator(); iterator.hasNext();) { - String attribute = iterator.next(); - Object value = options.get(attribute); + public static void checkStopped() throws Exception { + ArtemisBrokerHelper.stopArtemisBroker(); + boolean notStopped = BrokerService.checkStopped(); + TcpTransportFactory.setBrokerName(null); + if (notStopped) { + fail("brokers not stopped see exceptions above"); + } + ServerSocket socket = null; + try { + socket = new ServerSocket(61616); + } + catch (IOException e) { + fail("61616 port not released"); + } + finally { + if (socket != null) try { - Field field = getClass().getField(attribute); - field.set(this, value); - } catch (Throwable e) { - try { - boolean found = false; - String setterName = "set" + attribute.substring(0, 1).toUpperCase() + - attribute.substring(1); - for(Method method : getClass().getMethods()) { - if (method.getName().equals(setterName)) { - method.invoke(this, value); - found = true; - break; - } - } - - if (!found) { - throw new NoSuchMethodError("No setter found for field: " + attribute); - } - - } catch(Throwable ex) { - LOG.info("Could not set field '" + attribute + "' to value '" + value + - "', make sure the field exists and is public or has a setter."); - } + socket.close(); } - } - } - - private CombinationTestSupport[] getCombinations() { - try { - Method method = getClass().getMethod("initCombos", (Class[])null); - method.invoke(this, (Object[])null); - } catch (Throwable e) { - } - - String name = getName().split(" ")[0]; - String comboSetupMethodName = "initCombosFor" + Character.toUpperCase(name.charAt(0)) + name.substring(1); - try { - Method method = getClass().getMethod(comboSetupMethodName, (Class[])null); - method.invoke(this, (Object[])null); - } catch (Throwable e) { - } - - try { - ArrayList> expandedOptions = new ArrayList>(); - expandCombinations(new ArrayList(comboOptions.values()), expandedOptions); - - if (expandedOptions.isEmpty()) { - combosEvaluated = true; - return new CombinationTestSupport[] {this}; - } else { - - ArrayList result = new ArrayList(); - // Run the test case for each possible combination - for (Iterator> iter = expandedOptions.iterator(); iter.hasNext();) { - CombinationTestSupport combo = (CombinationTestSupport)TestSuite.createTest(getClass(), name); - combo.combosEvaluated = true; - combo.setOptions(iter.next()); - result.add(combo); - } - - CombinationTestSupport rc[] = new CombinationTestSupport[result.size()]; - result.toArray(rc); - return rc; + catch (IOException e) { } - } catch (Throwable e) { + } + } + + @Override + public void runBare() throws Throwable { + if (combosEvaluated) { + super.runBare(); + } + else { + CombinationTestSupport[] combinations = getCombinations(); + for (int i = 0; i < combinations.length; i++) { + CombinationTestSupport test = combinations[i]; + if (getName() == null || getName().equals(test.getName())) { + test.runBare(); + } + } + } + } + + private void setOptions(Map options) throws NoSuchFieldException, IllegalAccessException { + this.options = options; + for (Iterator iterator = options.keySet().iterator(); iterator.hasNext(); ) { + String attribute = iterator.next(); + Object value = options.get(attribute); + try { + Field field = getClass().getField(attribute); + field.set(this, value); + } + catch (Throwable e) { + try { + boolean found = false; + String setterName = "set" + attribute.substring(0, 1).toUpperCase() + + attribute.substring(1); + for (Method method : getClass().getMethods()) { + if (method.getName().equals(setterName)) { + method.invoke(this, value); + found = true; + break; + } + } + + if (!found) { + throw new NoSuchMethodError("No setter found for field: " + attribute); + } + + } + catch (Throwable ex) { + LOG.info("Could not set field '" + attribute + "' to value '" + value + + "', make sure the field exists and is public or has a setter."); + } + } + } + } + + private CombinationTestSupport[] getCombinations() { + try { + Method method = getClass().getMethod("initCombos", (Class[]) null); + method.invoke(this, (Object[]) null); + } + catch (Throwable e) { + } + + String name = getName().split(" ")[0]; + String comboSetupMethodName = "initCombosFor" + Character.toUpperCase(name.charAt(0)) + name.substring(1); + try { + Method method = getClass().getMethod(comboSetupMethodName, (Class[]) null); + method.invoke(this, (Object[]) null); + } + catch (Throwable e) { + } + + try { + ArrayList> expandedOptions = new ArrayList>(); + expandCombinations(new ArrayList(comboOptions.values()), expandedOptions); + + if (expandedOptions.isEmpty()) { combosEvaluated = true; - return new CombinationTestSupport[] {this}; - } + return new CombinationTestSupport[]{this}; + } + else { - } - - private void expandCombinations(List optionsLeft, List> expandedCombos) { - if (!optionsLeft.isEmpty()) { - HashMap map; - if (comboOptions.size() == optionsLeft.size()) { - map = new HashMap(); - expandedCombos.add(map); - } else { - map = expandedCombos.get(expandedCombos.size() - 1); + ArrayList result = new ArrayList(); + // Run the test case for each possible combination + for (Iterator> iter = expandedOptions.iterator(); iter.hasNext(); ) { + CombinationTestSupport combo = (CombinationTestSupport) TestSuite.createTest(getClass(), name); + combo.combosEvaluated = true; + combo.setOptions(iter.next()); + result.add(combo); } - LinkedList l = new LinkedList(optionsLeft); - ComboOption comboOption = l.removeLast(); - int i = 0; - if (comboOption.values.isEmpty() && !l.isEmpty()) { - expandCombinations(l, expandedCombos); - } else { - for (Iterator iter = comboOption.values.iterator(); iter.hasNext();) { - Object value = iter.next(); - if (i != 0) { - map = new HashMap(map); - expandedCombos.add(map); - } - map.put(comboOption.attribute, value); - expandCombinations(l, expandedCombos); - i++; - } + CombinationTestSupport rc[] = new CombinationTestSupport[result.size()]; + result.toArray(rc); + return rc; + } + } + catch (Throwable e) { + combosEvaluated = true; + return new CombinationTestSupport[]{this}; + } + + } + + private void expandCombinations(List optionsLeft, List> expandedCombos) { + if (!optionsLeft.isEmpty()) { + HashMap map; + if (comboOptions.size() == optionsLeft.size()) { + map = new HashMap(); + expandedCombos.add(map); + } + else { + map = expandedCombos.get(expandedCombos.size() - 1); + } + + LinkedList l = new LinkedList(optionsLeft); + ComboOption comboOption = l.removeLast(); + int i = 0; + if (comboOption.values.isEmpty() && !l.isEmpty()) { + expandCombinations(l, expandedCombos); + } + else { + for (Iterator iter = comboOption.values.iterator(); iter.hasNext(); ) { + Object value = iter.next(); + if (i != 0) { + map = new HashMap(map); + expandedCombos.add(map); + } + map.put(comboOption.attribute, value); + expandCombinations(l, expandedCombos); + i++; } - } - } + } + } + } - public static Test suite(Class clazz) { - TestSuite suite = new TestSuite(); + public static Test suite(Class clazz) { + TestSuite suite = new TestSuite(); - ArrayList names = new ArrayList(); - Method[] methods = clazz.getMethods(); - for (int i = 0; i < methods.length; i++) { - String name = methods[i].getName(); - if (names.contains(name) || !isPublicTestMethod(methods[i])) { - continue; + ArrayList names = new ArrayList(); + Method[] methods = clazz.getMethods(); + for (int i = 0; i < methods.length; i++) { + String name = methods[i].getName(); + if (names.contains(name) || !isPublicTestMethod(methods[i])) { + continue; + } + names.add(name); + Test test = TestSuite.createTest(clazz, name); + if (test instanceof CombinationTestSupport) { + CombinationTestSupport[] combinations = ((CombinationTestSupport) test).getCombinations(); + for (int j = 0; j < combinations.length; j++) { + suite.addTest(combinations[j]); } - names.add(name); - Test test = TestSuite.createTest(clazz, name); - if (test instanceof CombinationTestSupport) { - CombinationTestSupport[] combinations = ((CombinationTestSupport)test).getCombinations(); - for (int j = 0; j < combinations.length; j++) { - suite.addTest(combinations[j]); - } - } else { - suite.addTest(test); - } - } - return suite; - } + } + else { + suite.addTest(test); + } + } + return suite; + } - private static boolean isPublicTestMethod(Method m) { - return isTestMethod(m) && Modifier.isPublic(m.getModifiers()); - } + private static boolean isPublicTestMethod(Method m) { + return isTestMethod(m) && Modifier.isPublic(m.getModifiers()); + } - private static boolean isTestMethod(Method m) { - String name = m.getName(); - Class[] parameters = m.getParameterTypes(); - Class returnType = m.getReturnType(); - return parameters.length == 0 && name.startsWith("test") && returnType.equals(Void.TYPE); - } + private static boolean isTestMethod(Method m) { + String name = m.getName(); + Class[] parameters = m.getParameterTypes(); + Class returnType = m.getReturnType(); + return parameters.length == 0 && name.startsWith("test") && returnType.equals(Void.TYPE); + } - @Override - public String getName() { - return getName(false); - } + @Override + public String getName() { + return getName(false); + } - public String getName(boolean original) { - if (options != null && !original) { - return super.getName() + " " + options; - } - return super.getName(); - } + public String getName(boolean original) { + if (options != null && !original) { + return super.getName() + " " + options; + } + return super.getName(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ConnectionCleanupTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ConnectionCleanupTest.java index f7a64acdc8..dd9e3e215a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ConnectionCleanupTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ConnectionCleanupTest.java @@ -22,48 +22,50 @@ import javax.jms.Session; import junit.framework.TestCase; /** - * + * */ public class ConnectionCleanupTest extends TestCase { - private ActiveMQConnection connection; + private ActiveMQConnection connection; - protected void setUp() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - connection = (ActiveMQConnection)factory.createConnection(); - } + protected void setUp() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + connection = (ActiveMQConnection) factory.createConnection(); + } - /** - * @see junit.framework.TestCase#tearDown() - */ - protected void tearDown() throws Exception { - connection.close(); - } + /** + * @see junit.framework.TestCase#tearDown() + */ + protected void tearDown() throws Exception { + connection.close(); + } - /** - * @throws JMSException - */ - public void testChangeClientID() throws JMSException { + /** + * @throws JMSException + */ + public void testChangeClientID() throws JMSException { - connection.setClientID("test"); - connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + connection.setClientID("test"); + connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - try { - connection.setClientID("test"); - // fail("Should have received JMSException"); - } catch (JMSException e) { - } + try { + connection.setClientID("test"); + // fail("Should have received JMSException"); + } + catch (JMSException e) { + } - connection.cleanup(); - connection.setClientID("test"); + connection.cleanup(); + connection.setClientID("test"); - connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - try { - connection.setClientID("test"); - // fail("Should have received JMSException"); - } catch (JMSException e) { - } - } + try { + connection.setClientID("test"); + // fail("Should have received JMSException"); + } + catch (JMSException e) { + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ConnectionCloseMultipleTimesConcurrentTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ConnectionCloseMultipleTimesConcurrentTest.java index ae15671ada..a53b143be6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ConnectionCloseMultipleTimesConcurrentTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ConnectionCloseMultipleTimesConcurrentTest.java @@ -26,71 +26,72 @@ import javax.jms.Session; import junit.framework.TestCase; /** - * + * */ public class ConnectionCloseMultipleTimesConcurrentTest extends TestCase { - private ActiveMQConnection connection; - private ExecutorService executor; - private int size = 200; + private ActiveMQConnection connection; + private ExecutorService executor; + private int size = 200; - protected void setUp() throws Exception { - executor = Executors.newFixedThreadPool(20); + protected void setUp() throws Exception { + executor = Executors.newFixedThreadPool(20); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - connection = (ActiveMQConnection)factory.createConnection(); - connection.start(); - } + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + connection = (ActiveMQConnection) factory.createConnection(); + connection.start(); + } - /** - * @see junit.framework.TestCase#tearDown() - */ - protected void tearDown() throws Exception { - if (connection.isStarted()) { - connection.stop(); - } - if (executor != null) { - executor.shutdownNow(); - } - } + /** + * @see junit.framework.TestCase#tearDown() + */ + protected void tearDown() throws Exception { + if (connection.isStarted()) { + connection.stop(); + } + if (executor != null) { + executor.shutdownNow(); + } + } - /** - * @throws javax.jms.JMSException - */ - public void testCloseMultipleTimes() throws Exception { - connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + /** + * @throws javax.jms.JMSException + */ + public void testCloseMultipleTimes() throws Exception { + connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - assertTrue(connection.isStarted()); - assertFalse(connection.isClosed()); + assertTrue(connection.isStarted()); + assertFalse(connection.isClosed()); - final CountDownLatch latch = new CountDownLatch(size); + final CountDownLatch latch = new CountDownLatch(size); - for (int i = 0; i < size; i++) { - executor.submit(new Runnable() { - @Override - public void run() { - try { - connection.close(); + for (int i = 0; i < size; i++) { + executor.submit(new Runnable() { + @Override + public void run() { + try { + connection.close(); - assertFalse(connection.isStarted()); - assertTrue(connection.isClosed()); + assertFalse(connection.isStarted()); + assertTrue(connection.isClosed()); - latch.countDown(); - } catch (JMSException e) { - // ignore - } - } - }); - } + latch.countDown(); + } + catch (JMSException e) { + // ignore + } + } + }); + } - boolean zero = latch.await(20, TimeUnit.SECONDS); - assertTrue("Should complete all", zero); + boolean zero = latch.await(20, TimeUnit.SECONDS); + assertTrue("Should complete all", zero); - // should not fail calling again - connection.close(); + // should not fail calling again + connection.close(); - assertFalse(connection.isStarted()); - assertTrue(connection.isClosed()); - } + assertFalse(connection.isStarted()); + assertTrue(connection.isClosed()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ConnectionCloseMultipleTimesTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ConnectionCloseMultipleTimesTest.java index 3e78d73a02..c33e0f3504 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ConnectionCloseMultipleTimesTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ConnectionCloseMultipleTimesTest.java @@ -22,46 +22,46 @@ import javax.jms.Session; import junit.framework.TestCase; /** - * + * */ public class ConnectionCloseMultipleTimesTest extends TestCase { - private ActiveMQConnection connection; + private ActiveMQConnection connection; - protected void setUp() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - connection = (ActiveMQConnection)factory.createConnection(); - connection.start(); - } + protected void setUp() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + connection = (ActiveMQConnection) factory.createConnection(); + connection.start(); + } - /** - * @see junit.framework.TestCase#tearDown() - */ - protected void tearDown() throws Exception { - if (connection.isStarted()) { - connection.stop(); - } - } + /** + * @see junit.framework.TestCase#tearDown() + */ + protected void tearDown() throws Exception { + if (connection.isStarted()) { + connection.stop(); + } + } - /** - * @throws javax.jms.JMSException - */ - public void testCloseMultipleTimes() throws JMSException { - connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + /** + * @throws javax.jms.JMSException + */ + public void testCloseMultipleTimes() throws JMSException { + connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - assertTrue(connection.isStarted()); - assertFalse(connection.isClosed()); + assertTrue(connection.isStarted()); + assertFalse(connection.isClosed()); - connection.close(); + connection.close(); - assertFalse(connection.isStarted()); - assertTrue(connection.isClosed()); + assertFalse(connection.isStarted()); + assertTrue(connection.isClosed()); - // should not fail calling again - connection.close(); + // should not fail calling again + connection.close(); - assertFalse(connection.isStarted()); - assertTrue(connection.isClosed()); - } + assertFalse(connection.isStarted()); + assertTrue(connection.isClosed()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ConsumerReceiveWithTimeoutTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ConsumerReceiveWithTimeoutTest.java index b34fe7f739..89f6c81d8b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ConsumerReceiveWithTimeoutTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ConsumerReceiveWithTimeoutTest.java @@ -25,63 +25,64 @@ import javax.jms.Queue; import javax.jms.Session; /** - * + * */ public class ConsumerReceiveWithTimeoutTest extends TestSupport { - private Connection connection; + private Connection connection; - protected void setUp() throws Exception { - super.setUp(); - connection = createConnection(); - } + protected void setUp() throws Exception { + super.setUp(); + connection = createConnection(); + } - /** - * @see junit.framework.TestCase#tearDown() - */ - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - connection = null; - } - super.tearDown(); - } + /** + * @see junit.framework.TestCase#tearDown() + */ + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + connection = null; + } + super.tearDown(); + } - /** - * Test to check if consumer thread wakes up inside a receive(timeout) after - * a message is dispatched to the consumer - * - * @throws javax.jms.JMSException - */ - public void testConsumerReceiveBeforeMessageDispatched() throws JMSException { + /** + * Test to check if consumer thread wakes up inside a receive(timeout) after + * a message is dispatched to the consumer + * + * @throws javax.jms.JMSException + */ + public void testConsumerReceiveBeforeMessageDispatched() throws JMSException { - connection.start(); + connection.start(); - final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final Queue queue = session.createQueue("test"); + final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final Queue queue = session.createQueue("test"); - Thread t = new Thread() { - public void run() { - try { - // wait for 10 seconds to allow consumer.receive to be run - // first - Thread.sleep(10000); - MessageProducer producer = session.createProducer(queue); - producer.send(session.createTextMessage("Hello")); - } catch (Exception e) { - e.printStackTrace(); - } + Thread t = new Thread() { + public void run() { + try { + // wait for 10 seconds to allow consumer.receive to be run + // first + Thread.sleep(10000); + MessageProducer producer = session.createProducer(queue); + producer.send(session.createTextMessage("Hello")); } - }; + catch (Exception e) { + e.printStackTrace(); + } + } + }; - t.start(); + t.start(); - // Consume the message... - MessageConsumer consumer = session.createConsumer(queue); - Message msg = consumer.receive(60000); - assertNotNull(msg); - session.close(); + // Consume the message... + MessageConsumer consumer = session.createConsumer(queue); + Message msg = consumer.receive(60000); + assertNotNull(msg); + session.close(); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/CreateConsumerButDontStartConnectionWarningTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/CreateConsumerButDontStartConnectionWarningTest.java index 773e87129f..185fc48c9e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/CreateConsumerButDontStartConnectionWarningTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/CreateConsumerButDontStartConnectionWarningTest.java @@ -22,22 +22,24 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class CreateConsumerButDontStartConnectionWarningTest extends JmsQueueSendReceiveTest { - private static final transient Logger LOG = LoggerFactory.getLogger(CreateConsumerButDontStartConnectionWarningTest.class); - @Override - protected void startConnection() throws JMSException { - // don't start the connection - } + private static final transient Logger LOG = LoggerFactory.getLogger(CreateConsumerButDontStartConnectionWarningTest.class); - @Override - protected void assertMessagesAreReceived() throws JMSException { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - LOG.warn("Caught: " + e, e); - } - } + @Override + protected void startConnection() throws JMSException { + // don't start the connection + } + + @Override + protected void assertMessagesAreReceived() throws JMSException { + try { + Thread.sleep(1000); + } + catch (InterruptedException e) { + LOG.warn("Caught: " + e, e); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/EmbeddedBrokerAndConnectionTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/EmbeddedBrokerAndConnectionTestSupport.java index aa39cc1085..1a3dab7d0a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/EmbeddedBrokerAndConnectionTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/EmbeddedBrokerAndConnectionTestSupport.java @@ -20,25 +20,24 @@ import javax.jms.Connection; /** * A base class for a test case which creates an embedded broker and uses a connection and session - * - * */ public abstract class EmbeddedBrokerAndConnectionTestSupport extends EmbeddedBrokerTestSupport { - protected Connection connection; - @Override - protected void setUp() throws Exception { - super.setUp(); + protected Connection connection; - connection = createConnection(); - connection.start(); - } + @Override + protected void setUp() throws Exception { + super.setUp(); - @Override - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - super.tearDown(); - } + connection = createConnection(); + connection.start(); + } + + @Override + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + } + super.tearDown(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/EmbeddedBrokerTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/EmbeddedBrokerTestSupport.java index b049e960c9..6ae8a2dad9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/EmbeddedBrokerTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/EmbeddedBrokerTestSupport.java @@ -21,123 +21,124 @@ import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTopic; import org.springframework.jms.core.JmsTemplate; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; /** * A useful base class which creates and closes an embedded broker - * - * */ public abstract class EmbeddedBrokerTestSupport extends CombinationTestSupport { - protected BrokerService broker; - // protected String bindAddress = "tcp://localhost:61616"; - protected String bindAddress = "vm://localhost"; - protected ConnectionFactory connectionFactory; - protected boolean useTopic; - protected ActiveMQDestination destination; - protected JmsTemplate template; + protected BrokerService broker; + // protected String bindAddress = "tcp://localhost:61616"; + protected String bindAddress = "vm://localhost"; + protected ConnectionFactory connectionFactory; + protected boolean useTopic; + protected ActiveMQDestination destination; + protected JmsTemplate template; - protected void setUp() throws Exception { - if (broker == null) { - broker = createBroker(); - } - startBroker(); + protected void setUp() throws Exception { + if (broker == null) { + broker = createBroker(); + } + startBroker(); - connectionFactory = createConnectionFactory(); + connectionFactory = createConnectionFactory(); - destination = createDestination(); + destination = createDestination(); - template = createJmsTemplate(); - template.setDefaultDestination(destination); - template.setPubSubDomain(useTopic); - template.afterPropertiesSet(); - } + template = createJmsTemplate(); + template.setDefaultDestination(destination); + template.setPubSubDomain(useTopic); + template.afterPropertiesSet(); + } - protected void tearDown() throws Exception { - if (broker != null) { - try { - broker.stop(); - } catch (Exception e) { - } - } - } + protected void tearDown() throws Exception { + if (broker != null) { + try { + broker.stop(); + } + catch (Exception e) { + } + } + } - /** - * Factory method to create a new {@link JmsTemplate} - * - * @return a newly created JmsTemplate - */ - protected JmsTemplate createJmsTemplate() { - return new JmsTemplate(connectionFactory); - } + /** + * Factory method to create a new {@link JmsTemplate} + * + * @return a newly created JmsTemplate + */ + protected JmsTemplate createJmsTemplate() { + return new JmsTemplate(connectionFactory); + } - /** - * Factory method to create a new {@link Destination} - * - * @return newly created Destinaiton - */ - protected ActiveMQDestination createDestination() { - return createDestination(getDestinationString()); - } + /** + * Factory method to create a new {@link Destination} + * + * @return newly created Destinaiton + */ + protected ActiveMQDestination createDestination() { + return createDestination(getDestinationString()); + } - /** - * Factory method to create the destination in either the queue or topic - * space based on the value of the {@link #useTopic} field - */ - protected ActiveMQDestination createDestination(String subject) { - if (useTopic) { - return new ActiveMQTopic(subject); - } else { - return new ActiveMQQueue(subject); - } - } + /** + * Factory method to create the destination in either the queue or topic + * space based on the value of the {@link #useTopic} field + */ + protected ActiveMQDestination createDestination(String subject) { + if (useTopic) { + return new ActiveMQTopic(subject); + } + else { + return new ActiveMQQueue(subject); + } + } - /** - * Returns the name of the destination used in this test case - */ - protected String getDestinationString() { - return getClass().getName() + "." + getName(); - } + /** + * Returns the name of the destination used in this test case + */ + protected String getDestinationString() { + return getClass().getName() + "." + getName(); + } - /** - * Factory method to create a new {@link ConnectionFactory} instance - * - * @return a newly created connection factory - */ - protected ConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(bindAddress); - } + /** + * Factory method to create a new {@link ConnectionFactory} instance + * + * @return a newly created connection factory + */ + protected ConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory(bindAddress); + } - /** - * Factory method to create a new broker - * - * @throws Exception - */ - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setPersistent(isPersistent()); - answer.addConnector(bindAddress); - return answer; - } + /** + * Factory method to create a new broker + * + * @throws Exception + */ + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + answer.setPersistent(isPersistent()); + answer.addConnector(bindAddress); + return answer; + } - protected void startBroker() throws Exception { - broker.start(); - } + protected void startBroker() throws Exception { + broker.start(); + } - /** - * @return whether or not persistence should be used - */ - protected boolean isPersistent() { - return false; - } + /** + * @return whether or not persistence should be used + */ + protected boolean isPersistent() { + return false; + } - /** - * Factory method to create a new connection - */ - protected Connection createConnection() throws Exception { - return connectionFactory.createConnection(); - } + /** + * Factory method to create a new connection + */ + protected Connection createConnection() throws Exception { + return connectionFactory.createConnection(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ExclusiveConsumerStartupDestinationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ExclusiveConsumerStartupDestinationTest.java index 7aa22e36a2..06fbbbed3e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ExclusiveConsumerStartupDestinationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ExclusiveConsumerStartupDestinationTest.java @@ -29,175 +29,177 @@ import org.apache.activemq.broker.region.policy.PolicyEntry; import org.apache.activemq.broker.region.policy.PolicyMap; import org.apache.activemq.command.ActiveMQQueue; -public class ExclusiveConsumerStartupDestinationTest extends EmbeddedBrokerTestSupport{ +public class ExclusiveConsumerStartupDestinationTest extends EmbeddedBrokerTestSupport { - private static final String VM_BROKER_URL = "vm://localhost"; + private static final String VM_BROKER_URL = "vm://localhost"; - @Override - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setPersistent(false); - PolicyMap map = new PolicyMap(); - PolicyEntry entry = new PolicyEntry(); - entry.setAllConsumersExclusiveByDefault(true); - map.setDefaultEntry(entry); - answer.setDestinationPolicy(map); - return answer; - } + @Override + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + answer.setPersistent(false); + PolicyMap map = new PolicyMap(); + PolicyEntry entry = new PolicyEntry(); + entry.setAllConsumersExclusiveByDefault(true); + map.setDefaultEntry(entry); + answer.setDestinationPolicy(map); + return answer; + } - protected String getBrokerConfigUri() { - return "org/apache/activemq/broker/exclusive-consumer-startup-destination.xml"; - } + protected String getBrokerConfigUri() { + return "org/apache/activemq/broker/exclusive-consumer-startup-destination.xml"; + } - private Connection createConnection(final boolean start) throws JMSException { - ConnectionFactory cf = new ActiveMQConnectionFactory(VM_BROKER_URL); - Connection conn = cf.createConnection(); - if (start) { - conn.start(); - } - return conn; - } + private Connection createConnection(final boolean start) throws JMSException { + ConnectionFactory cf = new ActiveMQConnectionFactory(VM_BROKER_URL); + Connection conn = cf.createConnection(); + if (start) { + conn.start(); + } + return conn; + } - public void testExclusiveConsumerSelectedCreatedFirst() throws JMSException, InterruptedException { - Connection conn = createConnection(true); + public void testExclusiveConsumerSelectedCreatedFirst() throws JMSException, InterruptedException { + Connection conn = createConnection(true); - Session exclusiveSession = null; - Session fallbackSession = null; - Session senderSession = null; + Session exclusiveSession = null; + Session fallbackSession = null; + Session senderSession = null; - try { + try { - exclusiveSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - fallbackSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - senderSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + exclusiveSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + fallbackSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + senderSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQQueue exclusiveQueue = new ActiveMQQueue("TEST.QUEUE1"); - MessageConsumer exclusiveConsumer = exclusiveSession.createConsumer(exclusiveQueue); + ActiveMQQueue exclusiveQueue = new ActiveMQQueue("TEST.QUEUE1"); + MessageConsumer exclusiveConsumer = exclusiveSession.createConsumer(exclusiveQueue); - ActiveMQQueue fallbackQueue = new ActiveMQQueue("TEST.QUEUE1"); - MessageConsumer fallbackConsumer = fallbackSession.createConsumer(fallbackQueue); + ActiveMQQueue fallbackQueue = new ActiveMQQueue("TEST.QUEUE1"); + MessageConsumer fallbackConsumer = fallbackSession.createConsumer(fallbackQueue); - ActiveMQQueue senderQueue = new ActiveMQQueue("TEST.QUEUE1"); + ActiveMQQueue senderQueue = new ActiveMQQueue("TEST.QUEUE1"); - MessageProducer producer = senderSession.createProducer(senderQueue); + MessageProducer producer = senderSession.createProducer(senderQueue); - Message msg = senderSession.createTextMessage("test"); - producer.send(msg); - // TODO need two send a 2nd message - bug AMQ-1024 - // producer.send(msg); - Thread.sleep(100); + Message msg = senderSession.createTextMessage("test"); + producer.send(msg); + // TODO need two send a 2nd message - bug AMQ-1024 + // producer.send(msg); + Thread.sleep(100); - // Verify exclusive consumer receives the message. - assertNotNull(exclusiveConsumer.receive(100)); - assertNull(fallbackConsumer.receive(100)); - } finally { - fallbackSession.close(); - senderSession.close(); - conn.close(); - } - } + // Verify exclusive consumer receives the message. + assertNotNull(exclusiveConsumer.receive(100)); + assertNull(fallbackConsumer.receive(100)); + } + finally { + fallbackSession.close(); + senderSession.close(); + conn.close(); + } + } - public void testFailoverToAnotherExclusiveConsumerCreatedFirst() throws JMSException, - InterruptedException { - Connection conn = createConnection(true); + public void testFailoverToAnotherExclusiveConsumerCreatedFirst() throws JMSException, InterruptedException { + Connection conn = createConnection(true); - Session exclusiveSession1 = null; - Session exclusiveSession2 = null; - Session fallbackSession = null; - Session senderSession = null; + Session exclusiveSession1 = null; + Session exclusiveSession2 = null; + Session fallbackSession = null; + Session senderSession = null; - try { + try { - exclusiveSession1 = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - exclusiveSession2 = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - fallbackSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - senderSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + exclusiveSession1 = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + exclusiveSession2 = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + fallbackSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + senderSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - // This creates the exclusive consumer first which avoids AMQ-1024 - // bug. - ActiveMQQueue exclusiveQueue = new ActiveMQQueue("TEST.QUEUE2"); - MessageConsumer exclusiveConsumer1 = exclusiveSession1.createConsumer(exclusiveQueue); - MessageConsumer exclusiveConsumer2 = exclusiveSession2.createConsumer(exclusiveQueue); + // This creates the exclusive consumer first which avoids AMQ-1024 + // bug. + ActiveMQQueue exclusiveQueue = new ActiveMQQueue("TEST.QUEUE2"); + MessageConsumer exclusiveConsumer1 = exclusiveSession1.createConsumer(exclusiveQueue); + MessageConsumer exclusiveConsumer2 = exclusiveSession2.createConsumer(exclusiveQueue); - ActiveMQQueue fallbackQueue = new ActiveMQQueue("TEST.QUEUE2"); - MessageConsumer fallbackConsumer = fallbackSession.createConsumer(fallbackQueue); + ActiveMQQueue fallbackQueue = new ActiveMQQueue("TEST.QUEUE2"); + MessageConsumer fallbackConsumer = fallbackSession.createConsumer(fallbackQueue); - ActiveMQQueue senderQueue = new ActiveMQQueue("TEST.QUEUE2"); + ActiveMQQueue senderQueue = new ActiveMQQueue("TEST.QUEUE2"); - MessageProducer producer = senderSession.createProducer(senderQueue); + MessageProducer producer = senderSession.createProducer(senderQueue); - Message msg = senderSession.createTextMessage("test"); - producer.send(msg); - Thread.sleep(100); + Message msg = senderSession.createTextMessage("test"); + producer.send(msg); + Thread.sleep(100); - // Verify exclusive consumer receives the message. - assertNotNull(exclusiveConsumer1.receive(100)); - assertNull(exclusiveConsumer2.receive(100)); - assertNull(fallbackConsumer.receive(100)); + // Verify exclusive consumer receives the message. + assertNotNull(exclusiveConsumer1.receive(100)); + assertNull(exclusiveConsumer2.receive(100)); + assertNull(fallbackConsumer.receive(100)); - // Close the exclusive consumer to verify the non-exclusive consumer - // takes over - exclusiveConsumer1.close(); + // Close the exclusive consumer to verify the non-exclusive consumer + // takes over + exclusiveConsumer1.close(); - producer.send(msg); - producer.send(msg); + producer.send(msg); + producer.send(msg); - assertNotNull("Should have received a message", exclusiveConsumer2.receive(100)); - assertNull("Should not have received a message", fallbackConsumer.receive(100)); + assertNotNull("Should have received a message", exclusiveConsumer2.receive(100)); + assertNull("Should not have received a message", fallbackConsumer.receive(100)); - } finally { - fallbackSession.close(); - senderSession.close(); - conn.close(); - } + } + finally { + fallbackSession.close(); + senderSession.close(); + conn.close(); + } - } + } - public void testFailoverToNonExclusiveConsumer() throws JMSException, InterruptedException { - Connection conn = createConnection(true); + public void testFailoverToNonExclusiveConsumer() throws JMSException, InterruptedException { + Connection conn = createConnection(true); - Session exclusiveSession = null; - Session fallbackSession = null; - Session senderSession = null; + Session exclusiveSession = null; + Session fallbackSession = null; + Session senderSession = null; - try { + try { - exclusiveSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - fallbackSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - senderSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + exclusiveSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + fallbackSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + senderSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - // This creates the exclusive consumer first which avoids AMQ-1024 - // bug. - ActiveMQQueue exclusiveQueue = new ActiveMQQueue("TEST.QUEUE3"); - MessageConsumer exclusiveConsumer = exclusiveSession.createConsumer(exclusiveQueue); + // This creates the exclusive consumer first which avoids AMQ-1024 + // bug. + ActiveMQQueue exclusiveQueue = new ActiveMQQueue("TEST.QUEUE3"); + MessageConsumer exclusiveConsumer = exclusiveSession.createConsumer(exclusiveQueue); - ActiveMQQueue fallbackQueue = new ActiveMQQueue("TEST.QUEUE3"); - MessageConsumer fallbackConsumer = fallbackSession.createConsumer(fallbackQueue); + ActiveMQQueue fallbackQueue = new ActiveMQQueue("TEST.QUEUE3"); + MessageConsumer fallbackConsumer = fallbackSession.createConsumer(fallbackQueue); - ActiveMQQueue senderQueue = new ActiveMQQueue("TEST.QUEUE3"); + ActiveMQQueue senderQueue = new ActiveMQQueue("TEST.QUEUE3"); - MessageProducer producer = senderSession.createProducer(senderQueue); + MessageProducer producer = senderSession.createProducer(senderQueue); - Message msg = senderSession.createTextMessage("test"); - producer.send(msg); - Thread.sleep(100); + Message msg = senderSession.createTextMessage("test"); + producer.send(msg); + Thread.sleep(100); - // Verify exclusive consumer receives the message. - assertNotNull(exclusiveConsumer.receive(100)); - assertNull(fallbackConsumer.receive(100)); + // Verify exclusive consumer receives the message. + assertNotNull(exclusiveConsumer.receive(100)); + assertNull(fallbackConsumer.receive(100)); - // Close the exclusive consumer to verify the non-exclusive consumer - // takes over - exclusiveConsumer.close(); + // Close the exclusive consumer to verify the non-exclusive consumer + // takes over + exclusiveConsumer.close(); - producer.send(msg); + producer.send(msg); - assertNotNull(fallbackConsumer.receive(100)); + assertNotNull(fallbackConsumer.receive(100)); - } finally { - fallbackSession.close(); - senderSession.close(); - conn.close(); - } - } + } + finally { + fallbackSession.close(); + senderSession.close(); + conn.close(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ExclusiveConsumerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ExclusiveConsumerTest.java index 53ef28fc5a..0287a7770b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ExclusiveConsumerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ExclusiveConsumerTest.java @@ -30,328 +30,332 @@ import org.apache.activemq.command.ActiveMQQueue; public class ExclusiveConsumerTest extends TestCase { - private static final String VM_BROKER_URL = "vm://localhost?broker.persistent=false&broker.useJmx=true"; + private static final String VM_BROKER_URL = "vm://localhost?broker.persistent=false&broker.useJmx=true"; - public ExclusiveConsumerTest(String name) { - super(name); - } + public ExclusiveConsumerTest(String name) { + super(name); + } - @Override - protected void setUp() throws Exception { - super.setUp(); - } + @Override + protected void setUp() throws Exception { + super.setUp(); + } - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } - private Connection createConnection(final boolean start) throws JMSException { - ConnectionFactory cf = new ActiveMQConnectionFactory(VM_BROKER_URL); - Connection conn = cf.createConnection(); - if (start) { - conn.start(); - } - return conn; - } + private Connection createConnection(final boolean start) throws JMSException { + ConnectionFactory cf = new ActiveMQConnectionFactory(VM_BROKER_URL); + Connection conn = cf.createConnection(); + if (start) { + conn.start(); + } + return conn; + } - public void testExclusiveConsumerSelectedCreatedFirst() throws JMSException, InterruptedException { - Connection conn = createConnection(true); + public void testExclusiveConsumerSelectedCreatedFirst() throws JMSException, InterruptedException { + Connection conn = createConnection(true); - Session exclusiveSession = null; - Session fallbackSession = null; - Session senderSession = null; + Session exclusiveSession = null; + Session fallbackSession = null; + Session senderSession = null; - try { + try { - exclusiveSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - fallbackSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - senderSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + exclusiveSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + fallbackSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + senderSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQQueue exclusiveQueue = new ActiveMQQueue("TEST.QUEUE1?consumer.exclusive=true"); - MessageConsumer exclusiveConsumer = exclusiveSession.createConsumer(exclusiveQueue); + ActiveMQQueue exclusiveQueue = new ActiveMQQueue("TEST.QUEUE1?consumer.exclusive=true"); + MessageConsumer exclusiveConsumer = exclusiveSession.createConsumer(exclusiveQueue); - ActiveMQQueue fallbackQueue = new ActiveMQQueue("TEST.QUEUE1"); - MessageConsumer fallbackConsumer = fallbackSession.createConsumer(fallbackQueue); + ActiveMQQueue fallbackQueue = new ActiveMQQueue("TEST.QUEUE1"); + MessageConsumer fallbackConsumer = fallbackSession.createConsumer(fallbackQueue); - ActiveMQQueue senderQueue = new ActiveMQQueue("TEST.QUEUE1"); + ActiveMQQueue senderQueue = new ActiveMQQueue("TEST.QUEUE1"); - MessageProducer producer = senderSession.createProducer(senderQueue); + MessageProducer producer = senderSession.createProducer(senderQueue); - Message msg = senderSession.createTextMessage("test"); - producer.send(msg); - // TODO need two send a 2nd message - bug AMQ-1024 - // producer.send(msg); - Thread.sleep(100); + Message msg = senderSession.createTextMessage("test"); + producer.send(msg); + // TODO need two send a 2nd message - bug AMQ-1024 + // producer.send(msg); + Thread.sleep(100); - // Verify exclusive consumer receives the message. - assertNotNull(exclusiveConsumer.receive(100)); - assertNull(fallbackConsumer.receive(100)); + // Verify exclusive consumer receives the message. + assertNotNull(exclusiveConsumer.receive(100)); + assertNull(fallbackConsumer.receive(100)); - } finally { - fallbackSession.close(); - senderSession.close(); - conn.close(); - } + } + finally { + fallbackSession.close(); + senderSession.close(); + conn.close(); + } - } + } - public void testExclusiveConsumerSelectedCreatedAfter() throws JMSException, InterruptedException { - Connection conn = createConnection(true); + public void testExclusiveConsumerSelectedCreatedAfter() throws JMSException, InterruptedException { + Connection conn = createConnection(true); - Session exclusiveSession = null; - Session fallbackSession = null; - Session senderSession = null; + Session exclusiveSession = null; + Session fallbackSession = null; + Session senderSession = null; - try { + try { - exclusiveSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - fallbackSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - senderSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + exclusiveSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + fallbackSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + senderSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQQueue fallbackQueue = new ActiveMQQueue("TEST.QUEUE5"); - MessageConsumer fallbackConsumer = fallbackSession.createConsumer(fallbackQueue); + ActiveMQQueue fallbackQueue = new ActiveMQQueue("TEST.QUEUE5"); + MessageConsumer fallbackConsumer = fallbackSession.createConsumer(fallbackQueue); - ActiveMQQueue exclusiveQueue = new ActiveMQQueue("TEST.QUEUE5?consumer.exclusive=true"); - MessageConsumer exclusiveConsumer = exclusiveSession.createConsumer(exclusiveQueue); + ActiveMQQueue exclusiveQueue = new ActiveMQQueue("TEST.QUEUE5?consumer.exclusive=true"); + MessageConsumer exclusiveConsumer = exclusiveSession.createConsumer(exclusiveQueue); - ActiveMQQueue senderQueue = new ActiveMQQueue("TEST.QUEUE5"); + ActiveMQQueue senderQueue = new ActiveMQQueue("TEST.QUEUE5"); - MessageProducer producer = senderSession.createProducer(senderQueue); + MessageProducer producer = senderSession.createProducer(senderQueue); - Message msg = senderSession.createTextMessage("test"); - producer.send(msg); - Thread.sleep(100); + Message msg = senderSession.createTextMessage("test"); + producer.send(msg); + Thread.sleep(100); - // Verify exclusive consumer receives the message. - assertNotNull(exclusiveConsumer.receive(100)); - assertNull(fallbackConsumer.receive(100)); + // Verify exclusive consumer receives the message. + assertNotNull(exclusiveConsumer.receive(100)); + assertNull(fallbackConsumer.receive(100)); - } finally { - fallbackSession.close(); - senderSession.close(); - conn.close(); - } + } + finally { + fallbackSession.close(); + senderSession.close(); + conn.close(); + } - } + } - public void testFailoverToAnotherExclusiveConsumerCreatedFirst() throws JMSException, - InterruptedException { - Connection conn = createConnection(true); + public void testFailoverToAnotherExclusiveConsumerCreatedFirst() throws JMSException, InterruptedException { + Connection conn = createConnection(true); - Session exclusiveSession1 = null; - Session exclusiveSession2 = null; - Session fallbackSession = null; - Session senderSession = null; + Session exclusiveSession1 = null; + Session exclusiveSession2 = null; + Session fallbackSession = null; + Session senderSession = null; - try { + try { - exclusiveSession1 = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - exclusiveSession2 = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - fallbackSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - senderSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + exclusiveSession1 = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + exclusiveSession2 = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + fallbackSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + senderSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - // This creates the exclusive consumer first which avoids AMQ-1024 - // bug. - ActiveMQQueue exclusiveQueue = new ActiveMQQueue("TEST.QUEUE2?consumer.exclusive=true"); - MessageConsumer exclusiveConsumer1 = exclusiveSession1.createConsumer(exclusiveQueue); - MessageConsumer exclusiveConsumer2 = exclusiveSession2.createConsumer(exclusiveQueue); + // This creates the exclusive consumer first which avoids AMQ-1024 + // bug. + ActiveMQQueue exclusiveQueue = new ActiveMQQueue("TEST.QUEUE2?consumer.exclusive=true"); + MessageConsumer exclusiveConsumer1 = exclusiveSession1.createConsumer(exclusiveQueue); + MessageConsumer exclusiveConsumer2 = exclusiveSession2.createConsumer(exclusiveQueue); - ActiveMQQueue fallbackQueue = new ActiveMQQueue("TEST.QUEUE2"); - MessageConsumer fallbackConsumer = fallbackSession.createConsumer(fallbackQueue); + ActiveMQQueue fallbackQueue = new ActiveMQQueue("TEST.QUEUE2"); + MessageConsumer fallbackConsumer = fallbackSession.createConsumer(fallbackQueue); - ActiveMQQueue senderQueue = new ActiveMQQueue("TEST.QUEUE2"); + ActiveMQQueue senderQueue = new ActiveMQQueue("TEST.QUEUE2"); - MessageProducer producer = senderSession.createProducer(senderQueue); + MessageProducer producer = senderSession.createProducer(senderQueue); - Message msg = senderSession.createTextMessage("test"); - producer.send(msg); - Thread.sleep(100); + Message msg = senderSession.createTextMessage("test"); + producer.send(msg); + Thread.sleep(100); - // Verify exclusive consumer receives the message. - assertNotNull(exclusiveConsumer1.receive(100)); - assertNull(exclusiveConsumer2.receive(100)); - assertNull(fallbackConsumer.receive(100)); + // Verify exclusive consumer receives the message. + assertNotNull(exclusiveConsumer1.receive(100)); + assertNull(exclusiveConsumer2.receive(100)); + assertNull(fallbackConsumer.receive(100)); - // Close the exclusive consumer to verify the non-exclusive consumer - // takes over - exclusiveConsumer1.close(); + // Close the exclusive consumer to verify the non-exclusive consumer + // takes over + exclusiveConsumer1.close(); - producer.send(msg); - producer.send(msg); + producer.send(msg); + producer.send(msg); - assertNotNull(exclusiveConsumer2.receive(100)); - assertNull(fallbackConsumer.receive(100)); + assertNotNull(exclusiveConsumer2.receive(100)); + assertNull(fallbackConsumer.receive(100)); - } finally { - fallbackSession.close(); - senderSession.close(); - conn.close(); - } + } + finally { + fallbackSession.close(); + senderSession.close(); + conn.close(); + } - } + } - public void testFailoverToAnotherExclusiveConsumerCreatedAfter() throws JMSException, - InterruptedException { - Connection conn = createConnection(true); + public void testFailoverToAnotherExclusiveConsumerCreatedAfter() throws JMSException, InterruptedException { + Connection conn = createConnection(true); - Session exclusiveSession1 = null; - Session exclusiveSession2 = null; - Session fallbackSession = null; - Session senderSession = null; + Session exclusiveSession1 = null; + Session exclusiveSession2 = null; + Session fallbackSession = null; + Session senderSession = null; - try { + try { - exclusiveSession1 = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - exclusiveSession2 = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - fallbackSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - senderSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + exclusiveSession1 = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + exclusiveSession2 = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + fallbackSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + senderSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - // This creates the exclusive consumer first which avoids AMQ-1024 - // bug. - ActiveMQQueue exclusiveQueue = new ActiveMQQueue("TEST.QUEUE6?consumer.exclusive=true"); - MessageConsumer exclusiveConsumer1 = exclusiveSession1.createConsumer(exclusiveQueue); + // This creates the exclusive consumer first which avoids AMQ-1024 + // bug. + ActiveMQQueue exclusiveQueue = new ActiveMQQueue("TEST.QUEUE6?consumer.exclusive=true"); + MessageConsumer exclusiveConsumer1 = exclusiveSession1.createConsumer(exclusiveQueue); - ActiveMQQueue fallbackQueue = new ActiveMQQueue("TEST.QUEUE6"); - MessageConsumer fallbackConsumer = fallbackSession.createConsumer(fallbackQueue); + ActiveMQQueue fallbackQueue = new ActiveMQQueue("TEST.QUEUE6"); + MessageConsumer fallbackConsumer = fallbackSession.createConsumer(fallbackQueue); - MessageConsumer exclusiveConsumer2 = exclusiveSession2.createConsumer(exclusiveQueue); + MessageConsumer exclusiveConsumer2 = exclusiveSession2.createConsumer(exclusiveQueue); - ActiveMQQueue senderQueue = new ActiveMQQueue("TEST.QUEUE6"); + ActiveMQQueue senderQueue = new ActiveMQQueue("TEST.QUEUE6"); - MessageProducer producer = senderSession.createProducer(senderQueue); + MessageProducer producer = senderSession.createProducer(senderQueue); - Message msg = senderSession.createTextMessage("test"); - producer.send(msg); - Thread.sleep(100); + Message msg = senderSession.createTextMessage("test"); + producer.send(msg); + Thread.sleep(100); - // Verify exclusive consumer receives the message. - assertNotNull(exclusiveConsumer1.receive(100)); - assertNull(exclusiveConsumer2.receive(100)); - assertNull(fallbackConsumer.receive(100)); + // Verify exclusive consumer receives the message. + assertNotNull(exclusiveConsumer1.receive(100)); + assertNull(exclusiveConsumer2.receive(100)); + assertNull(fallbackConsumer.receive(100)); - // Close the exclusive consumer to verify the non-exclusive consumer - // takes over - exclusiveConsumer1.close(); + // Close the exclusive consumer to verify the non-exclusive consumer + // takes over + exclusiveConsumer1.close(); - producer.send(msg); - producer.send(msg); + producer.send(msg); + producer.send(msg); - assertNotNull(exclusiveConsumer2.receive(1000)); - assertNull(fallbackConsumer.receive(100)); + assertNotNull(exclusiveConsumer2.receive(1000)); + assertNull(fallbackConsumer.receive(100)); - } finally { - fallbackSession.close(); - senderSession.close(); - conn.close(); - } + } + finally { + fallbackSession.close(); + senderSession.close(); + conn.close(); + } - } + } - public void testFailoverToNonExclusiveConsumer() throws JMSException, InterruptedException { - Connection conn = createConnection(true); + public void testFailoverToNonExclusiveConsumer() throws JMSException, InterruptedException { + Connection conn = createConnection(true); - Session exclusiveSession = null; - Session fallbackSession = null; - Session senderSession = null; + Session exclusiveSession = null; + Session fallbackSession = null; + Session senderSession = null; - try { + try { - exclusiveSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - fallbackSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - senderSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + exclusiveSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + fallbackSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + senderSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - // This creates the exclusive consumer first which avoids AMQ-1024 - // bug. - ActiveMQQueue exclusiveQueue = new ActiveMQQueue("TEST.QUEUE3?consumer.exclusive=true"); - MessageConsumer exclusiveConsumer = exclusiveSession.createConsumer(exclusiveQueue); + // This creates the exclusive consumer first which avoids AMQ-1024 + // bug. + ActiveMQQueue exclusiveQueue = new ActiveMQQueue("TEST.QUEUE3?consumer.exclusive=true"); + MessageConsumer exclusiveConsumer = exclusiveSession.createConsumer(exclusiveQueue); - ActiveMQQueue fallbackQueue = new ActiveMQQueue("TEST.QUEUE3"); - MessageConsumer fallbackConsumer = fallbackSession.createConsumer(fallbackQueue); + ActiveMQQueue fallbackQueue = new ActiveMQQueue("TEST.QUEUE3"); + MessageConsumer fallbackConsumer = fallbackSession.createConsumer(fallbackQueue); - ActiveMQQueue senderQueue = new ActiveMQQueue("TEST.QUEUE3"); + ActiveMQQueue senderQueue = new ActiveMQQueue("TEST.QUEUE3"); - MessageProducer producer = senderSession.createProducer(senderQueue); + MessageProducer producer = senderSession.createProducer(senderQueue); - Message msg = senderSession.createTextMessage("test"); - producer.send(msg); - Thread.sleep(100); + Message msg = senderSession.createTextMessage("test"); + producer.send(msg); + Thread.sleep(100); - // Verify exclusive consumer receives the message. - assertNotNull(exclusiveConsumer.receive(100)); - assertNull(fallbackConsumer.receive(100)); + // Verify exclusive consumer receives the message. + assertNotNull(exclusiveConsumer.receive(100)); + assertNull(fallbackConsumer.receive(100)); - // Close the exclusive consumer to verify the non-exclusive consumer - // takes over - exclusiveConsumer.close(); + // Close the exclusive consumer to verify the non-exclusive consumer + // takes over + exclusiveConsumer.close(); - producer.send(msg); + producer.send(msg); - assertNotNull(fallbackConsumer.receive(100)); + assertNotNull(fallbackConsumer.receive(100)); - } finally { - fallbackSession.close(); - senderSession.close(); - conn.close(); - } + } + finally { + fallbackSession.close(); + senderSession.close(); + conn.close(); + } - } + } - public void testFallbackToExclusiveConsumer() throws JMSException, InterruptedException { - Connection conn = createConnection(true); + public void testFallbackToExclusiveConsumer() throws JMSException, InterruptedException { + Connection conn = createConnection(true); - Session exclusiveSession = null; - Session fallbackSession = null; - Session senderSession = null; + Session exclusiveSession = null; + Session fallbackSession = null; + Session senderSession = null; - try { + try { - exclusiveSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - fallbackSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - senderSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + exclusiveSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + fallbackSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + senderSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - // This creates the exclusive consumer first which avoids AMQ-1024 - // bug. - ActiveMQQueue exclusiveQueue = new ActiveMQQueue("TEST.QUEUE4?consumer.exclusive=true"); - MessageConsumer exclusiveConsumer = exclusiveSession.createConsumer(exclusiveQueue); + // This creates the exclusive consumer first which avoids AMQ-1024 + // bug. + ActiveMQQueue exclusiveQueue = new ActiveMQQueue("TEST.QUEUE4?consumer.exclusive=true"); + MessageConsumer exclusiveConsumer = exclusiveSession.createConsumer(exclusiveQueue); - ActiveMQQueue fallbackQueue = new ActiveMQQueue("TEST.QUEUE4"); - MessageConsumer fallbackConsumer = fallbackSession.createConsumer(fallbackQueue); + ActiveMQQueue fallbackQueue = new ActiveMQQueue("TEST.QUEUE4"); + MessageConsumer fallbackConsumer = fallbackSession.createConsumer(fallbackQueue); - ActiveMQQueue senderQueue = new ActiveMQQueue("TEST.QUEUE4"); + ActiveMQQueue senderQueue = new ActiveMQQueue("TEST.QUEUE4"); - MessageProducer producer = senderSession.createProducer(senderQueue); + MessageProducer producer = senderSession.createProducer(senderQueue); - Message msg = senderSession.createTextMessage("test"); - producer.send(msg); - Thread.sleep(100); + Message msg = senderSession.createTextMessage("test"); + producer.send(msg); + Thread.sleep(100); - // Verify exclusive consumer receives the message. - assertNotNull(exclusiveConsumer.receive(100)); - assertNull(fallbackConsumer.receive(100)); + // Verify exclusive consumer receives the message. + assertNotNull(exclusiveConsumer.receive(100)); + assertNull(fallbackConsumer.receive(100)); - // Close the exclusive consumer to verify the non-exclusive consumer - // takes over - exclusiveConsumer.close(); + // Close the exclusive consumer to verify the non-exclusive consumer + // takes over + exclusiveConsumer.close(); - producer.send(msg); + producer.send(msg); - // Verify other non-exclusive consumer receices the message. - assertNotNull(fallbackConsumer.receive(100)); + // Verify other non-exclusive consumer receices the message. + assertNotNull(fallbackConsumer.receive(100)); - // Create exclusive consumer to determine if it will start receiving - // the messages. - exclusiveConsumer = exclusiveSession.createConsumer(exclusiveQueue); + // Create exclusive consumer to determine if it will start receiving + // the messages. + exclusiveConsumer = exclusiveSession.createConsumer(exclusiveQueue); - producer.send(msg); - assertNotNull(exclusiveConsumer.receive(100)); - assertNull(fallbackConsumer.receive(100)); + producer.send(msg); + assertNotNull(exclusiveConsumer.receive(100)); + assertNull(fallbackConsumer.receive(100)); - } finally { - fallbackSession.close(); - senderSession.close(); - conn.close(); - } + } + finally { + fallbackSession.close(); + senderSession.close(); + conn.close(); + } - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ExpiryHogTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ExpiryHogTest.java index a07ee1e681..69d8c2d10d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ExpiryHogTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ExpiryHogTest.java @@ -20,6 +20,7 @@ import java.util.concurrent.TimeUnit; import javax.jms.ConnectionFactory; import javax.jms.Session; import javax.jms.TextMessage; + import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.region.policy.PolicyEntry; import org.apache.activemq.broker.region.policy.PolicyMap; @@ -33,47 +34,48 @@ import org.junit.runners.BlockJUnit4ClassRunner; */ @RunWith(BlockJUnit4ClassRunner.class) public class ExpiryHogTest extends JmsMultipleClientsTestSupport { - boolean sleep = false; - int numMessages = 4; + boolean sleep = false; - @Test(timeout = 2 * 60 * 1000) - public void testImmediateDispatchWhenCacheDisabled() throws Exception { - ConnectionFactory f = createConnectionFactory(); - destination = createDestination(); - startConsumers(f, destination); - sleep = true; - this.startProducers(f, destination, numMessages); - allMessagesList.assertMessagesReceived(numMessages); - } + int numMessages = 4; - protected BrokerService createBroker() throws Exception { - BrokerService bs = new BrokerService(); - bs.setDeleteAllMessagesOnStartup(true); - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setExpireMessagesPeriod(5000); - defaultEntry.setUseCache(false); - policyMap.setDefaultEntry(defaultEntry); - bs.setDestinationPolicy(policyMap); + @Test(timeout = 2 * 60 * 1000) + public void testImmediateDispatchWhenCacheDisabled() throws Exception { + ConnectionFactory f = createConnectionFactory(); + destination = createDestination(); + startConsumers(f, destination); + sleep = true; + this.startProducers(f, destination, numMessages); + allMessagesList.assertMessagesReceived(numMessages); + } - return bs; - } + protected BrokerService createBroker() throws Exception { + BrokerService bs = new BrokerService(); + bs.setDeleteAllMessagesOnStartup(true); + PolicyMap policyMap = new PolicyMap(); + PolicyEntry defaultEntry = new PolicyEntry(); + defaultEntry.setExpireMessagesPeriod(5000); + defaultEntry.setUseCache(false); + policyMap.setDefaultEntry(defaultEntry); + bs.setDestinationPolicy(policyMap); - protected TextMessage createTextMessage(Session session, String initText) throws Exception { - if (sleep) { - TimeUnit.SECONDS.sleep(10); - } - TextMessage msg = super.createTextMessage(session, initText); - msg.setJMSExpiration(4000); - return msg; - } + return bs; + } - @Override - @Before - public void setUp() throws Exception { - autoFail = false; - persistent = true; - super.setUp(); - } + protected TextMessage createTextMessage(Session session, String initText) throws Exception { + if (sleep) { + TimeUnit.SECONDS.sleep(10); + } + TextMessage msg = super.createTextMessage(session, initText); + msg.setJMSExpiration(4000); + return msg; + } + + @Override + @Before + public void setUp() throws Exception { + autoFail = false; + persistent = true; + super.setUp(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JMSConsumerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JMSConsumerTest.java index c793dc8e2c..bb00a2b9cd 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JMSConsumerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JMSConsumerTest.java @@ -47,891 +47,879 @@ import org.slf4j.LoggerFactory; /** * Test cases used to test the JMS message consumer. - * - * */ public class JMSConsumerTest extends JmsTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(JMSConsumerTest.class); + private static final Logger LOG = LoggerFactory.getLogger(JMSConsumerTest.class); - public ActiveMQDestination destination; - public int deliveryMode; - public int prefetch; - public int ackMode; - public byte destinationType; - public boolean durableConsumer; + public ActiveMQDestination destination; + public int deliveryMode; + public int prefetch; + public int ackMode; + public byte destinationType; + public boolean durableConsumer; - public static Test suite() { - return suite(JMSConsumerTest.class); - } + public static Test suite() { + return suite(JMSConsumerTest.class); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - public void initCombosForTestMessageListenerWithConsumerCanBeStopped() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); - } + public void initCombosForTestMessageListenerWithConsumerCanBeStopped() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); + } - public void testMessageListenerWithConsumerCanBeStopped() throws Exception { + public void testMessageListenerWithConsumerCanBeStopped() throws Exception { - final AtomicInteger counter = new AtomicInteger(0); - final CountDownLatch done1 = new CountDownLatch(1); - final CountDownLatch done2 = new CountDownLatch(1); + final AtomicInteger counter = new AtomicInteger(0); + final CountDownLatch done1 = new CountDownLatch(1); + final CountDownLatch done2 = new CountDownLatch(1); - // Receive a message with the JMS API - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - destination = createDestination(session, destinationType); - ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer)session.createConsumer(destination); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message m) { - counter.incrementAndGet(); - if (counter.get() == 1) { - done1.countDown(); - } - if (counter.get() == 2) { - done2.countDown(); - } + // Receive a message with the JMS API + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + destination = createDestination(session, destinationType); + ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer) session.createConsumer(destination); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message m) { + counter.incrementAndGet(); + if (counter.get() == 1) { + done1.countDown(); } - }); - - // Send a first message to make sure that the consumer dispatcher is - // running - sendMessages(session, destination, 1); - assertTrue(done1.await(1, TimeUnit.SECONDS)); - assertEquals(1, counter.get()); - - // Stop the consumer. - consumer.stop(); - - // Send a message, but should not get delivered. - sendMessages(session, destination, 1); - assertFalse(done2.await(1, TimeUnit.SECONDS)); - assertEquals(1, counter.get()); - - // Start the consumer, and the message should now get delivered. - consumer.start(); - assertTrue(done2.await(1, TimeUnit.SECONDS)); - assertEquals(2, counter.get()); - } - - - public void testMessageListenerWithConsumerCanBeStoppedConcurently() throws Exception { - - final AtomicInteger counter = new AtomicInteger(0); - final CountDownLatch closeDone = new CountDownLatch(1); - - connection.start(); - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); - - // preload the queue - sendMessages(session, destination, 2000); - - - final ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer)session.createConsumer(destination); - - final Map exceptions = - Collections.synchronizedMap(new HashMap()); - Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { - @Override - public void uncaughtException(Thread t, Throwable e) { - LOG.error("Uncaught exception:", e); - exceptions.put(t, e); + if (counter.get() == 2) { + done2.countDown(); } - }); + } + }); - final class AckAndClose implements Runnable { - private final Message message; + // Send a first message to make sure that the consumer dispatcher is + // running + sendMessages(session, destination, 1); + assertTrue(done1.await(1, TimeUnit.SECONDS)); + assertEquals(1, counter.get()); - public AckAndClose(Message m) { - this.message = m; + // Stop the consumer. + consumer.stop(); + + // Send a message, but should not get delivered. + sendMessages(session, destination, 1); + assertFalse(done2.await(1, TimeUnit.SECONDS)); + assertEquals(1, counter.get()); + + // Start the consumer, and the message should now get delivered. + consumer.start(); + assertTrue(done2.await(1, TimeUnit.SECONDS)); + assertEquals(2, counter.get()); + } + + public void testMessageListenerWithConsumerCanBeStoppedConcurently() throws Exception { + + final AtomicInteger counter = new AtomicInteger(0); + final CountDownLatch closeDone = new CountDownLatch(1); + + connection.start(); + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); + + // preload the queue + sendMessages(session, destination, 2000); + + final ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer) session.createConsumer(destination); + + final Map exceptions = Collections.synchronizedMap(new HashMap()); + Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { + @Override + public void uncaughtException(Thread t, Throwable e) { + LOG.error("Uncaught exception:", e); + exceptions.put(t, e); + } + }); + + final class AckAndClose implements Runnable { + + private final Message message; + + public AckAndClose(Message m) { + this.message = m; + } + + @Override + public void run() { + try { + int count = counter.incrementAndGet(); + if (count == 590) { + // close in a separate thread is ok by jms + consumer.close(); + closeDone.countDown(); + } + if (count % 200 == 0) { + // ensure there are some outstanding messages + // ack every 200 + message.acknowledge(); + } } - - @Override - public void run() { - try { - int count = counter.incrementAndGet(); - if (count == 590) { - // close in a separate thread is ok by jms - consumer.close(); - closeDone.countDown(); - } - if (count % 200 == 0) { - // ensure there are some outstanding messages - // ack every 200 - message.acknowledge(); - } - } catch (Exception e) { - LOG.error("Exception on close or ack:", e); - exceptions.put(Thread.currentThread(), e); - } + catch (Exception e) { + LOG.error("Exception on close or ack:", e); + exceptions.put(Thread.currentThread(), e); } - }; + } + } + ; - final ExecutorService executor = Executors.newCachedThreadPool(); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message m) { - // ack and close eventually in separate thread - executor.execute(new AckAndClose(m)); + final ExecutorService executor = Executors.newCachedThreadPool(); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message m) { + // ack and close eventually in separate thread + executor.execute(new AckAndClose(m)); + } + }); + + assertTrue(closeDone.await(20, TimeUnit.SECONDS)); + // await possible exceptions + Thread.sleep(1000); + assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); + } + + public void initCombosForTestMutiReceiveWithPrefetch1() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("ackMode", new Object[]{Integer.valueOf(Session.AUTO_ACKNOWLEDGE), Integer.valueOf(Session.DUPS_OK_ACKNOWLEDGE), Integer.valueOf(Session.CLIENT_ACKNOWLEDGE)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); + } + + public void testMutiReceiveWithPrefetch1() throws Exception { + + // Set prefetch to 1 + connection.getPrefetchPolicy().setAll(1); + connection.start(); + + // Use all the ack modes + Session session = connection.createSession(false, ackMode); + destination = createDestination(session, destinationType); + MessageConsumer consumer = session.createConsumer(destination); + + // Send the messages + sendMessages(session, destination, 4); + + // Make sure 4 messages were delivered. + Message message = null; + for (int i = 0; i < 4; i++) { + message = consumer.receive(1000); + assertNotNull(message); + } + assertNull(consumer.receiveNoWait()); + message.acknowledge(); + } + + public void initCombosForTestDurableConsumerSelectorChange() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); + } + + public void testDurableConsumerSelectorChange() throws Exception { + + // Receive a message with the JMS API + connection.setClientID("test"); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + destination = createDestination(session, destinationType); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(deliveryMode); + MessageConsumer consumer = session.createDurableSubscriber((Topic) destination, "test", "color='red'", false); + + // Send the messages + TextMessage message = session.createTextMessage("1st"); + message.setStringProperty("color", "red"); + producer.send(message); + + Message m = consumer.receive(1000); + assertNotNull(m); + assertEquals("1st", ((TextMessage) m).getText()); + + // Change the subscription. + consumer.close(); + consumer = session.createDurableSubscriber((Topic) destination, "test", "color='blue'", false); + + message = session.createTextMessage("2nd"); + message.setStringProperty("color", "red"); + producer.send(message); + message = session.createTextMessage("3rd"); + message.setStringProperty("color", "blue"); + producer.send(message); + + // Selector should skip the 2nd message. + m = consumer.receive(1000); + assertNotNull(m); + assertEquals("3rd", ((TextMessage) m).getText()); + + assertNull(consumer.receiveNoWait()); + } + + public void initCombosForTestSendReceiveBytesMessage() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); + } + + public void testSendReceiveBytesMessage() throws Exception { + + // Receive a message with the JMS API + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + destination = createDestination(session, destinationType); + MessageConsumer consumer = session.createConsumer(destination); + MessageProducer producer = session.createProducer(destination); + + BytesMessage message = session.createBytesMessage(); + message.writeBoolean(true); + message.writeBoolean(false); + producer.send(message); + + // Make sure only 1 message was delivered. + BytesMessage m = (BytesMessage) consumer.receive(1000); + assertNotNull(m); + assertTrue(m.readBoolean()); + assertFalse(m.readBoolean()); + + assertNull(consumer.receiveNoWait()); + } + + public void initCombosForTestSetMessageListenerAfterStart() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); + } + + public void testSetMessageListenerAfterStart() throws Exception { + + final AtomicInteger counter = new AtomicInteger(0); + final CountDownLatch done = new CountDownLatch(1); + + // Receive a message with the JMS API + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + destination = createDestination(session, destinationType); + MessageConsumer consumer = session.createConsumer(destination); + + // Send the messages + sendMessages(session, destination, 4); + + // See if the message get sent to the listener + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message m) { + counter.incrementAndGet(); + if (counter.get() == 4) { + done.countDown(); } - }); + } + }); - assertTrue(closeDone.await(20, TimeUnit.SECONDS)); - // await possible exceptions - Thread.sleep(1000); - assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); - } + assertTrue(done.await(1000, TimeUnit.MILLISECONDS)); + Thread.sleep(200); + // Make sure only 4 messages were delivered. + assertEquals(4, counter.get()); + } - public void initCombosForTestMutiReceiveWithPrefetch1() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("ackMode", new Object[] {Integer.valueOf(Session.AUTO_ACKNOWLEDGE), Integer.valueOf(Session.DUPS_OK_ACKNOWLEDGE), - Integer.valueOf(Session.CLIENT_ACKNOWLEDGE)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); - } + public void initCombosForTestPassMessageListenerIntoCreateConsumer() { + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); + } - public void testMutiReceiveWithPrefetch1() throws Exception { + public void testPassMessageListenerIntoCreateConsumer() throws Exception { - // Set prefetch to 1 - connection.getPrefetchPolicy().setAll(1); - connection.start(); + final AtomicInteger counter = new AtomicInteger(0); + final CountDownLatch done = new CountDownLatch(1); - // Use all the ack modes - Session session = connection.createSession(false, ackMode); - destination = createDestination(session, destinationType); - MessageConsumer consumer = session.createConsumer(destination); - - // Send the messages - sendMessages(session, destination, 4); - - // Make sure 4 messages were delivered. - Message message = null; - for (int i = 0; i < 4; i++) { - message = consumer.receive(1000); - assertNotNull(message); - } - assertNull(consumer.receiveNoWait()); - message.acknowledge(); - } - - public void initCombosForTestDurableConsumerSelectorChange() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); - } - - public void testDurableConsumerSelectorChange() throws Exception { - - // Receive a message with the JMS API - connection.setClientID("test"); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - destination = createDestination(session, destinationType); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(deliveryMode); - MessageConsumer consumer = session.createDurableSubscriber((Topic)destination, "test", "color='red'", false); - - // Send the messages - TextMessage message = session.createTextMessage("1st"); - message.setStringProperty("color", "red"); - producer.send(message); - - Message m = consumer.receive(1000); - assertNotNull(m); - assertEquals("1st", ((TextMessage)m).getText()); - - // Change the subscription. - consumer.close(); - consumer = session.createDurableSubscriber((Topic)destination, "test", "color='blue'", false); - - message = session.createTextMessage("2nd"); - message.setStringProperty("color", "red"); - producer.send(message); - message = session.createTextMessage("3rd"); - message.setStringProperty("color", "blue"); - producer.send(message); - - // Selector should skip the 2nd message. - m = consumer.receive(1000); - assertNotNull(m); - assertEquals("3rd", ((TextMessage)m).getText()); - - assertNull(consumer.receiveNoWait()); - } - - public void initCombosForTestSendReceiveBytesMessage() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); - } - - public void testSendReceiveBytesMessage() throws Exception { - - // Receive a message with the JMS API - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - destination = createDestination(session, destinationType); - MessageConsumer consumer = session.createConsumer(destination); - MessageProducer producer = session.createProducer(destination); - - BytesMessage message = session.createBytesMessage(); - message.writeBoolean(true); - message.writeBoolean(false); - producer.send(message); - - // Make sure only 1 message was delivered. - BytesMessage m = (BytesMessage)consumer.receive(1000); - assertNotNull(m); - assertTrue(m.readBoolean()); - assertFalse(m.readBoolean()); - - assertNull(consumer.receiveNoWait()); - } - - public void initCombosForTestSetMessageListenerAfterStart() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); - } - - public void testSetMessageListenerAfterStart() throws Exception { - - final AtomicInteger counter = new AtomicInteger(0); - final CountDownLatch done = new CountDownLatch(1); - - // Receive a message with the JMS API - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - destination = createDestination(session, destinationType); - MessageConsumer consumer = session.createConsumer(destination); - - // Send the messages - sendMessages(session, destination, 4); - - // See if the message get sent to the listener - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message m) { - counter.incrementAndGet(); - if (counter.get() == 4) { - done.countDown(); - } + // Receive a message with the JMS API + connection.start(); + ActiveMQSession session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + destination = createDestination(session, destinationType); + MessageConsumer consumer = session.createConsumer(destination, new MessageListener() { + @Override + public void onMessage(Message m) { + counter.incrementAndGet(); + if (counter.get() == 4) { + done.countDown(); } - }); + } + }); + assertNotNull(consumer); - assertTrue(done.await(1000, TimeUnit.MILLISECONDS)); - Thread.sleep(200); + // Send the messages + sendMessages(session, destination, 4); - // Make sure only 4 messages were delivered. - assertEquals(4, counter.get()); - } + assertTrue(done.await(1000, TimeUnit.MILLISECONDS)); + Thread.sleep(200); - public void initCombosForTestPassMessageListenerIntoCreateConsumer() { - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); - } + // Make sure only 4 messages were delivered. + assertEquals(4, counter.get()); + } - public void testPassMessageListenerIntoCreateConsumer() throws Exception { + public void initCombosForTestMessageListenerOnMessageCloseUnackedWithPrefetch1StayInQueue() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("ackMode", new Object[]{Integer.valueOf(Session.CLIENT_ACKNOWLEDGE)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE)}); + } - final AtomicInteger counter = new AtomicInteger(0); - final CountDownLatch done = new CountDownLatch(1); + public void testMessageListenerOnMessageCloseUnackedWithPrefetch1StayInQueue() throws Exception { - // Receive a message with the JMS API - connection.start(); - ActiveMQSession session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - destination = createDestination(session, destinationType); - MessageConsumer consumer = session.createConsumer(destination, new MessageListener() { - @Override - public void onMessage(Message m) { - counter.incrementAndGet(); - if (counter.get() == 4) { - done.countDown(); - } + final AtomicInteger counter = new AtomicInteger(0); + final CountDownLatch sendDone = new CountDownLatch(1); + final CountDownLatch got2Done = new CountDownLatch(1); + + // Set prefetch to 1 + connection.getPrefetchPolicy().setAll(1); + // This test case does not work if optimized message dispatch is used as + // the main thread send block until the consumer receives the + // message. This test depends on thread decoupling so that the main + // thread can stop the consumer thread. + connection.setOptimizedMessageDispatch(false); + connection.start(); + + // Use all the ack modes + Session session = connection.createSession(false, ackMode); + destination = createDestination(session, destinationType); + MessageConsumer consumer = session.createConsumer(destination); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message m) { + try { + TextMessage tm = (TextMessage) m; + LOG.info("Got in first listener: " + tm.getText()); + assertEquals("" + counter.get(), tm.getText()); + counter.incrementAndGet(); + if (counter.get() == 2) { + sendDone.await(); + connection.close(); + got2Done.countDown(); + } + tm.acknowledge(); } - }); - assertNotNull(consumer); - - // Send the messages - sendMessages(session, destination, 4); - - assertTrue(done.await(1000, TimeUnit.MILLISECONDS)); - Thread.sleep(200); - - // Make sure only 4 messages were delivered. - assertEquals(4, counter.get()); - } - - public void initCombosForTestMessageListenerOnMessageCloseUnackedWithPrefetch1StayInQueue() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("ackMode", new Object[] {Integer.valueOf(Session.CLIENT_ACKNOWLEDGE)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE)}); - } - - public void testMessageListenerOnMessageCloseUnackedWithPrefetch1StayInQueue() throws Exception { - - final AtomicInteger counter = new AtomicInteger(0); - final CountDownLatch sendDone = new CountDownLatch(1); - final CountDownLatch got2Done = new CountDownLatch(1); - - // Set prefetch to 1 - connection.getPrefetchPolicy().setAll(1); - // This test case does not work if optimized message dispatch is used as - // the main thread send block until the consumer receives the - // message. This test depends on thread decoupling so that the main - // thread can stop the consumer thread. - connection.setOptimizedMessageDispatch(false); - connection.start(); - - // Use all the ack modes - Session session = connection.createSession(false, ackMode); - destination = createDestination(session, destinationType); - MessageConsumer consumer = session.createConsumer(destination); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message m) { - try { - TextMessage tm = (TextMessage)m; - LOG.info("Got in first listener: " + tm.getText()); - assertEquals("" + counter.get(), tm.getText()); - counter.incrementAndGet(); - if (counter.get() == 2) { - sendDone.await(); - connection.close(); - got2Done.countDown(); - } - tm.acknowledge(); - } catch (Throwable e) { - e.printStackTrace(); - } + catch (Throwable e) { + e.printStackTrace(); } - }); + } + }); - // Send the messages - sendMessages(session, destination, 4); - sendDone.countDown(); + // Send the messages + sendMessages(session, destination, 4); + sendDone.countDown(); - // Wait for first 2 messages to arrive. - assertTrue(got2Done.await(100000, TimeUnit.MILLISECONDS)); + // Wait for first 2 messages to arrive. + assertTrue(got2Done.await(100000, TimeUnit.MILLISECONDS)); - // Re-start connection. - connection = (ActiveMQConnection)factory.createConnection(); - connections.add(connection); + // Re-start connection. + connection = (ActiveMQConnection) factory.createConnection(); + connections.add(connection); - connection.getPrefetchPolicy().setAll(1); - connection.start(); + connection.getPrefetchPolicy().setAll(1); + connection.start(); - // Pickup the remaining messages. - final CountDownLatch done2 = new CountDownLatch(1); - session = connection.createSession(false, ackMode); - consumer = session.createConsumer(destination); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message m) { - try { - TextMessage tm = (TextMessage)m; - LOG.info("Got in second listener: " + tm.getText()); - // order is not guaranteed as the connection is started before the listener is set. - // assertEquals("" + counter.get(), tm.getText()); - counter.incrementAndGet(); - if (counter.get() == 4) { - done2.countDown(); - } - } catch (Throwable e) { - LOG.error("unexpected ex onMessage: ", e); - } + // Pickup the remaining messages. + final CountDownLatch done2 = new CountDownLatch(1); + session = connection.createSession(false, ackMode); + consumer = session.createConsumer(destination); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message m) { + try { + TextMessage tm = (TextMessage) m; + LOG.info("Got in second listener: " + tm.getText()); + // order is not guaranteed as the connection is started before the listener is set. + // assertEquals("" + counter.get(), tm.getText()); + counter.incrementAndGet(); + if (counter.get() == 4) { + done2.countDown(); + } } - }); - - assertTrue(done2.await(1000, TimeUnit.MILLISECONDS)); - Thread.sleep(200); - - // assert msg 2 was redelivered as close() from onMessages() will only ack in auto_ack and dups_ok mode - assertEquals(5, counter.get()); - } - - public void initCombosForTestMessageListenerAutoAckOnCloseWithPrefetch1() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("ackMode", new Object[] {Integer.valueOf(Session.AUTO_ACKNOWLEDGE), Integer.valueOf(Session.CLIENT_ACKNOWLEDGE)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE)}); - } - - public void testMessageListenerAutoAckOnCloseWithPrefetch1() throws Exception { - - final AtomicInteger counter = new AtomicInteger(0); - final CountDownLatch sendDone = new CountDownLatch(1); - final CountDownLatch got2Done = new CountDownLatch(1); - - // Set prefetch to 1 - connection.getPrefetchPolicy().setAll(1); - // This test case does not work if optimized message dispatch is used as - // the main thread send block until the consumer receives the - // message. This test depends on thread decoupling so that the main - // thread can stop the consumer thread. - connection.setOptimizedMessageDispatch(false); - connection.start(); - - // Use all the ack modes - Session session = connection.createSession(false, ackMode); - destination = createDestination(session, destinationType); - MessageConsumer consumer = session.createConsumer(destination); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message m) { - try { - TextMessage tm = (TextMessage)m; - LOG.info("Got in first listener: " + tm.getText()); - assertEquals("" + counter.get(), tm.getText()); - counter.incrementAndGet(); - m.acknowledge(); - if (counter.get() == 2) { - sendDone.await(); - connection.close(); - got2Done.countDown(); - } - } catch (Throwable e) { - e.printStackTrace(); - } + catch (Throwable e) { + LOG.error("unexpected ex onMessage: ", e); } - }); + } + }); - // Send the messages - sendMessages(session, destination, 4); - sendDone.countDown(); + assertTrue(done2.await(1000, TimeUnit.MILLISECONDS)); + Thread.sleep(200); - // Wait for first 2 messages to arrive. - assertTrue(got2Done.await(100000, TimeUnit.MILLISECONDS)); + // assert msg 2 was redelivered as close() from onMessages() will only ack in auto_ack and dups_ok mode + assertEquals(5, counter.get()); + } - // Re-start connection. - connection = (ActiveMQConnection)factory.createConnection(); - connections.add(connection); + public void initCombosForTestMessageListenerAutoAckOnCloseWithPrefetch1() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("ackMode", new Object[]{Integer.valueOf(Session.AUTO_ACKNOWLEDGE), Integer.valueOf(Session.CLIENT_ACKNOWLEDGE)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE)}); + } - connection.getPrefetchPolicy().setAll(1); - connection.start(); + public void testMessageListenerAutoAckOnCloseWithPrefetch1() throws Exception { - // Pickup the remaining messages. - final CountDownLatch done2 = new CountDownLatch(1); - session = connection.createSession(false, ackMode); - consumer = session.createConsumer(destination); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message m) { - try { - TextMessage tm = (TextMessage)m; - LOG.info("Got in second listener: " + tm.getText()); - counter.incrementAndGet(); - if (counter.get() == 4) { - done2.countDown(); - } - } catch (Throwable e) { - LOG.error("unexpected ex onMessage: ", e); - } + final AtomicInteger counter = new AtomicInteger(0); + final CountDownLatch sendDone = new CountDownLatch(1); + final CountDownLatch got2Done = new CountDownLatch(1); + + // Set prefetch to 1 + connection.getPrefetchPolicy().setAll(1); + // This test case does not work if optimized message dispatch is used as + // the main thread send block until the consumer receives the + // message. This test depends on thread decoupling so that the main + // thread can stop the consumer thread. + connection.setOptimizedMessageDispatch(false); + connection.start(); + + // Use all the ack modes + Session session = connection.createSession(false, ackMode); + destination = createDestination(session, destinationType); + MessageConsumer consumer = session.createConsumer(destination); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message m) { + try { + TextMessage tm = (TextMessage) m; + LOG.info("Got in first listener: " + tm.getText()); + assertEquals("" + counter.get(), tm.getText()); + counter.incrementAndGet(); + m.acknowledge(); + if (counter.get() == 2) { + sendDone.await(); + connection.close(); + got2Done.countDown(); + } } - }); - - assertTrue(done2.await(1000, TimeUnit.MILLISECONDS)); - Thread.sleep(200); - - // close from onMessage with Auto_ack will ack - // Make sure only 4 messages were delivered. - assertEquals(4, counter.get()); - } - - public void initCombosForTestMessageListenerWithConsumerWithPrefetch1() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); - } - - public void testMessageListenerWithConsumerWithPrefetch1() throws Exception { - - final AtomicInteger counter = new AtomicInteger(0); - final CountDownLatch done = new CountDownLatch(1); - - // Receive a message with the JMS API - connection.getPrefetchPolicy().setAll(1); - connection.start(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - destination = createDestination(session, destinationType); - MessageConsumer consumer = session.createConsumer(destination); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message m) { - counter.incrementAndGet(); - if (counter.get() == 4) { - done.countDown(); - } + catch (Throwable e) { + e.printStackTrace(); } - }); + } + }); - // Send the messages - sendMessages(session, destination, 4); + // Send the messages + sendMessages(session, destination, 4); + sendDone.countDown(); - assertTrue(done.await(1000, TimeUnit.MILLISECONDS)); - Thread.sleep(200); + // Wait for first 2 messages to arrive. + assertTrue(got2Done.await(100000, TimeUnit.MILLISECONDS)); - // Make sure only 4 messages were delivered. - assertEquals(4, counter.get()); - } + // Re-start connection. + connection = (ActiveMQConnection) factory.createConnection(); + connections.add(connection); - public void initCombosForTestMessageListenerWithConsumer() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); - } + connection.getPrefetchPolicy().setAll(1); + connection.start(); - public void testMessageListenerWithConsumer() throws Exception { - - final AtomicInteger counter = new AtomicInteger(0); - final CountDownLatch done = new CountDownLatch(1); - - // Receive a message with the JMS API - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - destination = createDestination(session, destinationType); - MessageConsumer consumer = session.createConsumer(destination); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message m) { - counter.incrementAndGet(); - if (counter.get() == 4) { - done.countDown(); - } + // Pickup the remaining messages. + final CountDownLatch done2 = new CountDownLatch(1); + session = connection.createSession(false, ackMode); + consumer = session.createConsumer(destination); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message m) { + try { + TextMessage tm = (TextMessage) m; + LOG.info("Got in second listener: " + tm.getText()); + counter.incrementAndGet(); + if (counter.get() == 4) { + done2.countDown(); + } } - }); - - // Send the messages - sendMessages(session, destination, 4); - - assertTrue(done.await(1000, TimeUnit.MILLISECONDS)); - Thread.sleep(200); - - // Make sure only 4 messages were delivered. - assertEquals(4, counter.get()); - } - - public void initCombosForTestUnackedWithPrefetch1StayInQueue() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("ackMode", new Object[] {Integer.valueOf(Session.AUTO_ACKNOWLEDGE), Integer.valueOf(Session.DUPS_OK_ACKNOWLEDGE), - Integer.valueOf(Session.CLIENT_ACKNOWLEDGE)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE)}); - } + catch (Throwable e) { + LOG.error("unexpected ex onMessage: ", e); + } + } + }); + + assertTrue(done2.await(1000, TimeUnit.MILLISECONDS)); + Thread.sleep(200); + + // close from onMessage with Auto_ack will ack + // Make sure only 4 messages were delivered. + assertEquals(4, counter.get()); + } + + public void initCombosForTestMessageListenerWithConsumerWithPrefetch1() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); + } + + public void testMessageListenerWithConsumerWithPrefetch1() throws Exception { + + final AtomicInteger counter = new AtomicInteger(0); + final CountDownLatch done = new CountDownLatch(1); + + // Receive a message with the JMS API + connection.getPrefetchPolicy().setAll(1); + connection.start(); + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + destination = createDestination(session, destinationType); + MessageConsumer consumer = session.createConsumer(destination); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message m) { + counter.incrementAndGet(); + if (counter.get() == 4) { + done.countDown(); + } + } + }); + + // Send the messages + sendMessages(session, destination, 4); + + assertTrue(done.await(1000, TimeUnit.MILLISECONDS)); + Thread.sleep(200); + + // Make sure only 4 messages were delivered. + assertEquals(4, counter.get()); + } + + public void initCombosForTestMessageListenerWithConsumer() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); + } + + public void testMessageListenerWithConsumer() throws Exception { + + final AtomicInteger counter = new AtomicInteger(0); + final CountDownLatch done = new CountDownLatch(1); + + // Receive a message with the JMS API + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + destination = createDestination(session, destinationType); + MessageConsumer consumer = session.createConsumer(destination); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message m) { + counter.incrementAndGet(); + if (counter.get() == 4) { + done.countDown(); + } + } + }); + + // Send the messages + sendMessages(session, destination, 4); + + assertTrue(done.await(1000, TimeUnit.MILLISECONDS)); + Thread.sleep(200); + + // Make sure only 4 messages were delivered. + assertEquals(4, counter.get()); + } + + public void initCombosForTestUnackedWithPrefetch1StayInQueue() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("ackMode", new Object[]{Integer.valueOf(Session.AUTO_ACKNOWLEDGE), Integer.valueOf(Session.DUPS_OK_ACKNOWLEDGE), Integer.valueOf(Session.CLIENT_ACKNOWLEDGE)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE)}); + } + + public void testUnackedWithPrefetch1StayInQueue() throws Exception { + + // Set prefetch to 1 + connection.getPrefetchPolicy().setAll(1); + connection.start(); + + // Use all the ack modes + Session session = connection.createSession(false, ackMode); + destination = createDestination(session, destinationType); + MessageConsumer consumer = session.createConsumer(destination); + + // Send the messages + sendMessages(session, destination, 4); + + // Only pick up the first 2 messages. + Message message = null; + for (int i = 0; i < 2; i++) { + message = consumer.receive(1000); + assertNotNull(message); + } + message.acknowledge(); + + connection.close(); + connection = (ActiveMQConnection) factory.createConnection(); + connections.add(connection); + connection.getPrefetchPolicy().setAll(1); + connection.start(); + + // Use all the ack modes + session = connection.createSession(false, ackMode); + consumer = session.createConsumer(destination); + + // Pickup the rest of the messages. + for (int i = 0; i < 2; i++) { + message = consumer.receive(1000); + assertNotNull(message); + } + message.acknowledge(); + assertNull(consumer.receiveNoWait()); + + } + + public void initCombosForTestPrefetch1MessageNotDispatched() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + } + + public void testPrefetch1MessageNotDispatched() throws Exception { + + // Set prefetch to 1 + connection.getPrefetchPolicy().setAll(1); + connection.start(); + + Session session = connection.createSession(true, 0); + destination = new ActiveMQQueue("TEST"); + MessageConsumer consumer = session.createConsumer(destination); + + // Send 2 messages to the destination. + sendMessages(session, destination, 2); + session.commit(); + + // The prefetch should fill up with 1 message. + // Since prefetch is still full, the 2nd message should get dispatched + // to another consumer.. lets create the 2nd consumer test that it does + // make sure it does. + ActiveMQConnection connection2 = (ActiveMQConnection) factory.createConnection(); + connection2.start(); + connections.add(connection2); + Session session2 = connection2.createSession(true, 0); + MessageConsumer consumer2 = session2.createConsumer(destination); + + // Pick up the first message. + Message message1 = consumer.receive(1000); + assertNotNull(message1); + + // Pick up the 2nd messages. + Message message2 = consumer2.receive(5000); + assertNotNull(message2); + + session.commit(); + session2.commit(); - public void testUnackedWithPrefetch1StayInQueue() throws Exception { - - // Set prefetch to 1 - connection.getPrefetchPolicy().setAll(1); - connection.start(); - - // Use all the ack modes - Session session = connection.createSession(false, ackMode); - destination = createDestination(session, destinationType); - MessageConsumer consumer = session.createConsumer(destination); + assertNull(consumer.receiveNoWait()); - // Send the messages - sendMessages(session, destination, 4); + } - // Only pick up the first 2 messages. - Message message = null; - for (int i = 0; i < 2; i++) { - message = consumer.receive(1000); - assertNotNull(message); - } - message.acknowledge(); + public void initCombosForTestDontStart() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); + } - connection.close(); - connection = (ActiveMQConnection)factory.createConnection(); - connections.add(connection); - connection.getPrefetchPolicy().setAll(1); - connection.start(); + public void testDontStart() throws Exception { - // Use all the ack modes - session = connection.createSession(false, ackMode); - consumer = session.createConsumer(destination); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + destination = createDestination(session, destinationType); + MessageConsumer consumer = session.createConsumer(destination); + + // Send the messages + sendMessages(session, destination, 1); - // Pickup the rest of the messages. - for (int i = 0; i < 2; i++) { - message = consumer.receive(1000); - assertNotNull(message); - } - message.acknowledge(); - assertNull(consumer.receiveNoWait()); + // Make sure no messages were delivered. + assertNull(consumer.receive(1000)); + } + + public void initCombosForTestStartAfterSend() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); + } + + public void testStartAfterSend() throws Exception { - } + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + destination = createDestination(session, destinationType); + MessageConsumer consumer = session.createConsumer(destination); - public void initCombosForTestPrefetch1MessageNotDispatched() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - } - - public void testPrefetch1MessageNotDispatched() throws Exception { - - // Set prefetch to 1 - connection.getPrefetchPolicy().setAll(1); - connection.start(); + // Send the messages + sendMessages(session, destination, 1); - Session session = connection.createSession(true, 0); - destination = new ActiveMQQueue("TEST"); - MessageConsumer consumer = session.createConsumer(destination); + // Start the conncection after the message was sent. + connection.start(); - // Send 2 messages to the destination. - sendMessages(session, destination, 2); - session.commit(); + // Make sure only 1 message was delivered. + assertNotNull(consumer.receive(1000)); + assertNull(consumer.receiveNoWait()); + } - // The prefetch should fill up with 1 message. - // Since prefetch is still full, the 2nd message should get dispatched - // to another consumer.. lets create the 2nd consumer test that it does - // make sure it does. - ActiveMQConnection connection2 = (ActiveMQConnection)factory.createConnection(); - connection2.start(); - connections.add(connection2); - Session session2 = connection2.createSession(true, 0); - MessageConsumer consumer2 = session2.createConsumer(destination); - - // Pick up the first message. - Message message1 = consumer.receive(1000); - assertNotNull(message1); - - // Pick up the 2nd messages. - Message message2 = consumer2.receive(5000); - assertNotNull(message2); + public void initCombosForTestReceiveMessageWithConsumer() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); + } - session.commit(); - session2.commit(); + public void testReceiveMessageWithConsumer() throws Exception { - assertNull(consumer.receiveNoWait()); + // Receive a message with the JMS API + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + destination = createDestination(session, destinationType); + MessageConsumer consumer = session.createConsumer(destination); - } + // Send the messages + sendMessages(session, destination, 1); - public void initCombosForTestDontStart() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); - } - - public void testDontStart() throws Exception { + // Make sure only 1 message was delivered. + Message m = consumer.receive(1000); + assertNotNull(m); + assertEquals("0", ((TextMessage) m).getText()); + assertNull(consumer.receiveNoWait()); + } - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - destination = createDestination(session, destinationType); - MessageConsumer consumer = session.createConsumer(destination); + public void testDupsOkConsumer() throws Exception { - // Send the messages - sendMessages(session, destination, 1); + // Receive a message with the JMS API + connection.start(); + Session session = connection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE); + destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); + MessageConsumer consumer = session.createConsumer(destination); - // Make sure no messages were delivered. - assertNull(consumer.receive(1000)); - } - - public void initCombosForTestStartAfterSend() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); - } - - public void testStartAfterSend() throws Exception { + // Send the messages + sendMessages(session, destination, 4); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - destination = createDestination(session, destinationType); - MessageConsumer consumer = session.createConsumer(destination); + // Make sure only 4 message are delivered. + for (int i = 0; i < 4; i++) { + Message m = consumer.receive(1000); + assertNotNull(m); + } + assertNull(consumer.receive(1000)); - // Send the messages - sendMessages(session, destination, 1); + // Close out the consumer.. no other messages should be left on the queue. + consumer.close(); - // Start the conncection after the message was sent. - connection.start(); + consumer = session.createConsumer(destination); + assertNull(consumer.receive(1000)); + } - // Make sure only 1 message was delivered. - assertNotNull(consumer.receive(1000)); - assertNull(consumer.receiveNoWait()); - } + public void testRedispatchOfUncommittedTx() throws Exception { - public void initCombosForTestReceiveMessageWithConsumer() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); - } + connection.start(); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); - public void testReceiveMessageWithConsumer() throws Exception { + sendMessages(connection, destination, 2); - // Receive a message with the JMS API - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - destination = createDestination(session, destinationType); - MessageConsumer consumer = session.createConsumer(destination); + MessageConsumer consumer = session.createConsumer(destination); + assertNotNull(consumer.receive(1000)); + assertNotNull(consumer.receive(1000)); - // Send the messages - sendMessages(session, destination, 1); + // install another consumer while message dispatch is unacked/uncommitted + Session redispatchSession = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageConsumer redispatchConsumer = redispatchSession.createConsumer(destination); - // Make sure only 1 message was delivered. - Message m = consumer.receive(1000); - assertNotNull(m); - assertEquals("0", ((TextMessage)m).getText()); - assertNull(consumer.receiveNoWait()); - } + // no commit so will auto rollback and get re-dispatched to redisptachConsumer + session.close(); + Message msg = redispatchConsumer.receive(1000); + assertNotNull(msg); + assertTrue("redelivered flag set", msg.getJMSRedelivered()); + assertEquals(2, msg.getLongProperty("JMSXDeliveryCount")); - public void testDupsOkConsumer() throws Exception { - - // Receive a message with the JMS API - connection.start(); - Session session = connection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE); - destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); - MessageConsumer consumer = session.createConsumer(destination); - - // Send the messages - sendMessages(session, destination, 4); - - // Make sure only 4 message are delivered. - for( int i=0; i < 4; i++){ - Message m = consumer.receive(1000); - assertNotNull(m); - } - assertNull(consumer.receive(1000)); - - // Close out the consumer.. no other messages should be left on the queue. - consumer.close(); - - consumer = session.createConsumer(destination); - assertNull(consumer.receive(1000)); - } - - public void testRedispatchOfUncommittedTx() throws Exception { - - connection.start(); - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); - - sendMessages(connection, destination, 2); - - MessageConsumer consumer = session.createConsumer(destination); - assertNotNull(consumer.receive(1000)); - assertNotNull(consumer.receive(1000)); - - // install another consumer while message dispatch is unacked/uncommitted - Session redispatchSession = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageConsumer redispatchConsumer = redispatchSession.createConsumer(destination); - - // no commit so will auto rollback and get re-dispatched to redisptachConsumer - session.close(); - - Message msg = redispatchConsumer.receive(1000); - assertNotNull(msg); - assertTrue("redelivered flag set", msg.getJMSRedelivered()); - assertEquals(2, msg.getLongProperty("JMSXDeliveryCount")); - - msg = redispatchConsumer.receive(1000); - assertNotNull(msg); - assertTrue(msg.getJMSRedelivered()); - assertEquals(2, msg.getLongProperty("JMSXDeliveryCount")); - redispatchSession.commit(); - - assertNull(redispatchConsumer.receive(500)); - redispatchSession.close(); - } - - - public void testRedispatchOfRolledbackTx() throws Exception { - - connection.start(); - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); - - sendMessages(connection, destination, 2); - - MessageConsumer consumer = session.createConsumer(destination); - assertNotNull(consumer.receive(1000)); - assertNotNull(consumer.receive(1000)); - - // install another consumer while message dispatch is unacked/uncommitted - Session redispatchSession = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageConsumer redispatchConsumer = redispatchSession.createConsumer(destination); - - session.rollback(); - session.close(); - - Message msg = redispatchConsumer.receive(1000); - assertNotNull(msg); - assertTrue(msg.getJMSRedelivered()); - assertEquals(2, msg.getLongProperty("JMSXDeliveryCount")); - msg = redispatchConsumer.receive(1000); - assertNotNull(msg); - assertTrue(msg.getJMSRedelivered()); - assertEquals(2, msg.getLongProperty("JMSXDeliveryCount")); - redispatchSession.commit(); - - assertNull(redispatchConsumer.receive(500)); - redispatchSession.close(); - } - - - public void initCombosForTestAckOfExpired() { - addCombinationValues("destinationType", - new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); - } - - public void testAckOfExpired() throws Exception { - - ActiveMQConnectionFactory fact = new ActiveMQConnectionFactory("vm://localhost?jms.prefetchPolicy.all=4&jms.sendAcksAsync=false"); - connection = fact.createActiveMQConnection(); - - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - destination = (ActiveMQDestination) (destinationType == ActiveMQDestination.QUEUE_TYPE ? - session.createQueue("test") : session.createTopic("test")); - - MessageConsumer consumer = session.createConsumer(destination); - connection.setStatsEnabled(true); - - Session sendSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = sendSession.createProducer(destination); - producer.setTimeToLive(1000); - final int count = 4; - for (int i = 0; i < count; i++) { - TextMessage message = sendSession.createTextMessage("" + i); - producer.send(message); - } - - // let first bunch in queue expire - Thread.sleep(2000); - - producer.setTimeToLive(0); - for (int i = 0; i < count; i++) { - TextMessage message = sendSession.createTextMessage("no expiry" + i); - producer.send(message); - } - - ActiveMQMessageConsumer amqConsumer = (ActiveMQMessageConsumer) consumer; - - for(int i=0; i props = new HashMap(); - - @Override - public String getJMSMessageID() throws JMSException { - return messageId; - } - - @Override - public void setJMSMessageID(String arg0) throws JMSException { - messageId = arg0; - } - - @Override - public long getJMSTimestamp() throws JMSException { - return timestamp; - } - - @Override - public void setJMSTimestamp(long arg0) throws JMSException { - timestamp = arg0; - } - - @Override - public byte[] getJMSCorrelationIDAsBytes() throws JMSException { - return null; - } - - @Override - public void setJMSCorrelationIDAsBytes(byte[] arg0) throws JMSException { - } - - @Override - public void setJMSCorrelationID(String arg0) throws JMSException { - correlationId = arg0; - } - - @Override - public String getJMSCorrelationID() throws JMSException { - return correlationId; - } - - @Override - public Destination getJMSReplyTo() throws JMSException { - return replyTo; - } - - @Override - public void setJMSReplyTo(Destination arg0) throws JMSException { - replyTo = arg0; - } - - @Override - public Destination getJMSDestination() throws JMSException { - return destination; - } - - @Override - public void setJMSDestination(Destination arg0) throws JMSException { - destination = arg0; - } - - @Override - public int getJMSDeliveryMode() throws JMSException { - return deliveryMode; - } - - @Override - public void setJMSDeliveryMode(int arg0) throws JMSException { - deliveryMode = arg0; - } - - @Override - public boolean getJMSRedelivered() throws JMSException { - return redelivered; - } - - @Override - public void setJMSRedelivered(boolean arg0) throws JMSException { - redelivered = arg0; - } - - @Override - public String getJMSType() throws JMSException { - return type; - } - - @Override - public void setJMSType(String arg0) throws JMSException { - type = arg0; - } - - @Override - public long getJMSExpiration() throws JMSException { - return expiration; - } - - @Override - public void setJMSExpiration(long arg0) throws JMSException { - expiration = arg0; - } - - @Override - public int getJMSPriority() throws JMSException { - return priority; - } - - @Override - public void setJMSPriority(int arg0) throws JMSException { - priority = arg0; - } - - @Override - public void clearProperties() throws JMSException { - } - - @Override - public boolean propertyExists(String arg0) throws JMSException { - return false; - } - - @Override - public boolean getBooleanProperty(String arg0) throws JMSException { - return false; - } - - @Override - public byte getByteProperty(String arg0) throws JMSException { - return 0; - } - - @Override - public short getShortProperty(String arg0) throws JMSException { - return 0; - } - - @Override - public int getIntProperty(String arg0) throws JMSException { - return 0; - } - - @Override - public long getLongProperty(String arg0) throws JMSException { - return 0; - } - - @Override - public float getFloatProperty(String arg0) throws JMSException { - return 0; - } - - @Override - public double getDoubleProperty(String arg0) throws JMSException { - return 0; - } - - @Override - public String getStringProperty(String arg0) throws JMSException { - return (String)props.get(arg0); - } - - @Override - public Object getObjectProperty(String arg0) throws JMSException { - return props.get(arg0); - } - - @Override - public Enumeration getPropertyNames() throws JMSException { - return new Vector(props.keySet()).elements(); - } - - @Override - public void setBooleanProperty(String arg0, boolean arg1) throws JMSException { - } - - @Override - public void setByteProperty(String arg0, byte arg1) throws JMSException { - } - - @Override - public void setShortProperty(String arg0, short arg1) throws JMSException { - } - - @Override - public void setIntProperty(String arg0, int arg1) throws JMSException { - } - - @Override - public void setLongProperty(String arg0, long arg1) throws JMSException { - } - - @Override - public void setFloatProperty(String arg0, float arg1) throws JMSException { - } - - @Override - public void setDoubleProperty(String arg0, double arg1) throws JMSException { - } - - @Override - public void setStringProperty(String arg0, String arg1) throws JMSException { - props.put(arg0, arg1); - } - - @Override - public void setObjectProperty(String arg0, Object arg1) throws JMSException { - props.put(arg0, arg1); - } - - @Override - public void acknowledge() throws JMSException { - } - - @Override - public void clearBody() throws JMSException { - } - - @Override - public void setText(String arg0) throws JMSException { - text = arg0; - } - - @Override - public String getText() throws JMSException { - return text; - } - } - - public void testForeignMessage() throws Exception { - - // Receive a message with the JMS API - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - destination = createDestination(session, destinationType); - MessageConsumer consumer = session.createConsumer(destination); - MessageProducer producer = session.createProducer(destination); - - // Send the message. - { - ForeignMessage message = new ForeignMessage(); - message.text = "Hello"; - message.setStringProperty("test", "value"); - long timeToLive = 10000L; - long start = System.currentTimeMillis(); - producer.send(message, Session.AUTO_ACKNOWLEDGE, 7, timeToLive); - long end = System.currentTimeMillis(); - - - //validate jms spec 1.1 section 3.4.11 table 3.1 - // JMSDestination, JMSDeliveryMode, JMSExpiration, JMSPriority, JMSMessageID, and JMSTimestamp - //must be set by sending a message. - - assertNotNull(message.getJMSDestination()); - assertEquals(Session.AUTO_ACKNOWLEDGE, message.getJMSDeliveryMode()); - assertTrue(start + timeToLive <= message.getJMSExpiration()); - assertTrue(end + timeToLive >= message.getJMSExpiration()); - assertEquals(7, message.getJMSPriority()); - assertNotNull(message.getJMSMessageID()); - assertTrue(start <= message.getJMSTimestamp()); - assertTrue(end >= message.getJMSTimestamp()); - } - - // Validate message is OK. - { - TextMessage message = (TextMessage)consumer.receive(1000); - assertNotNull(message); - assertEquals("Hello", message.getText()); - assertEquals("value", message.getStringProperty("test")); - } - - assertNull(consumer.receiveNoWait()); - } + public ActiveMQDestination destination; + public int deliveryMode = DeliveryMode.NON_PERSISTENT; + public int prefetch; + public int ackMode; + public byte destinationType = ActiveMQDestination.QUEUE_TYPE; + public boolean durableConsumer; + public String connectURL = "vm://localhost?marshal=false"; + + /** + * Run all these tests in both marshaling and non-marshaling mode. + */ + public void initCombos() { + addCombinationValues("connectURL", new Object[]{"vm://localhost?marshal=false", "vm://localhost?marshal=true"}); + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE)}); + } + + public void testTextMessage() throws Exception { + + // Receive a message with the JMS API + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + destination = createDestination(session, destinationType); + MessageConsumer consumer = session.createConsumer(destination); + MessageProducer producer = session.createProducer(destination); + + // Send the message. + { + TextMessage message = session.createTextMessage(); + message.setText("Hi"); + producer.send(message); + } + + // Check the Message + { + TextMessage message = (TextMessage) consumer.receive(1000); + assertNotNull(message); + assertEquals("Hi", message.getText()); + } + + assertNull(consumer.receiveNoWait()); + } + + public static Test suite() { + return suite(JMSMessageTest.class); + } + + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } + + @Override + protected ConnectionFactory createConnectionFactory() throws URISyntaxException { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectURL); + return factory; + } + + public void testBytesMessageLength() throws Exception { + + // Receive a message with the JMS API + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + destination = createDestination(session, destinationType); + MessageConsumer consumer = session.createConsumer(destination); + MessageProducer producer = session.createProducer(destination); + + // Send the message + { + BytesMessage message = session.createBytesMessage(); + message.writeInt(1); + message.writeInt(2); + message.writeInt(3); + message.writeInt(4); + producer.send(message); + } + + // Check the message. + { + BytesMessage message = (BytesMessage) consumer.receive(1000); + assertNotNull(message); + assertEquals(16, message.getBodyLength()); + } + + assertNull(consumer.receiveNoWait()); + } + + public void testObjectMessage() throws Exception { + + // Receive a message with the JMS API + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + destination = createDestination(session, destinationType); + MessageConsumer consumer = session.createConsumer(destination); + MessageProducer producer = session.createProducer(destination); + + // send the message. + { + ObjectMessage message = session.createObjectMessage(); + message.setObject("Hi"); + producer.send(message); + } + + // Check the message + { + ObjectMessage message = (ObjectMessage) consumer.receive(1000); + assertNotNull(message); + assertEquals("Hi", message.getObject()); + } + assertNull(consumer.receiveNoWait()); + } + + public void testBytesMessage() throws Exception { + + // Receive a message with the JMS API + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + destination = createDestination(session, destinationType); + MessageConsumer consumer = session.createConsumer(destination); + MessageProducer producer = session.createProducer(destination); + + // Send the message + { + BytesMessage message = session.createBytesMessage(); + message.writeBoolean(true); + producer.send(message); + } + + // Check the message + { + BytesMessage message = (BytesMessage) consumer.receive(1000); + assertNotNull(message); + assertTrue(message.readBoolean()); + + try { + message.readByte(); + fail("Expected exception not thrown."); + } + catch (MessageEOFException e) { + } + + } + assertNull(consumer.receiveNoWait()); + } + + public void testStreamMessage() throws Exception { + + // Receive a message with the JMS API + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + destination = createDestination(session, destinationType); + MessageConsumer consumer = session.createConsumer(destination); + MessageProducer producer = session.createProducer(destination); + + // Send the message. + { + StreamMessage message = session.createStreamMessage(); + message.writeString("This is a test to see how it works."); + producer.send(message); + } + + // Check the message. + { + StreamMessage message = (StreamMessage) consumer.receive(1000); + assertNotNull(message); + + // Invalid conversion should throw exception and not move the stream + // position. + try { + message.readByte(); + fail("Should have received NumberFormatException"); + } + catch (NumberFormatException e) { + } + + assertEquals("This is a test to see how it works.", message.readString()); + + // Invalid conversion should throw exception and not move the stream + // position. + try { + message.readByte(); + fail("Should have received MessageEOFException"); + } + catch (MessageEOFException e) { + } + } + assertNull(consumer.receiveNoWait()); + } + + public void testMapMessage() throws Exception { + + // Receive a message with the JMS API + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + destination = createDestination(session, destinationType); + MessageConsumer consumer = session.createConsumer(destination); + MessageProducer producer = session.createProducer(destination); + + // send the message. + { + MapMessage message = session.createMapMessage(); + message.setBoolean("boolKey", true); + producer.send(message); + } + + // get the message. + { + MapMessage message = (MapMessage) consumer.receive(1000); + assertNotNull(message); + assertTrue(message.getBoolean("boolKey")); + } + assertNull(consumer.receiveNoWait()); + } + + static class ForeignMessage implements TextMessage { + + public int deliveryMode; + + private String messageId; + private long timestamp; + private String correlationId; + private Destination replyTo; + private Destination destination; + private boolean redelivered; + private String type; + private long expiration; + private int priority; + private String text; + private final HashMap props = new HashMap(); + + @Override + public String getJMSMessageID() throws JMSException { + return messageId; + } + + @Override + public void setJMSMessageID(String arg0) throws JMSException { + messageId = arg0; + } + + @Override + public long getJMSTimestamp() throws JMSException { + return timestamp; + } + + @Override + public void setJMSTimestamp(long arg0) throws JMSException { + timestamp = arg0; + } + + @Override + public byte[] getJMSCorrelationIDAsBytes() throws JMSException { + return null; + } + + @Override + public void setJMSCorrelationIDAsBytes(byte[] arg0) throws JMSException { + } + + @Override + public void setJMSCorrelationID(String arg0) throws JMSException { + correlationId = arg0; + } + + @Override + public String getJMSCorrelationID() throws JMSException { + return correlationId; + } + + @Override + public Destination getJMSReplyTo() throws JMSException { + return replyTo; + } + + @Override + public void setJMSReplyTo(Destination arg0) throws JMSException { + replyTo = arg0; + } + + @Override + public Destination getJMSDestination() throws JMSException { + return destination; + } + + @Override + public void setJMSDestination(Destination arg0) throws JMSException { + destination = arg0; + } + + @Override + public int getJMSDeliveryMode() throws JMSException { + return deliveryMode; + } + + @Override + public void setJMSDeliveryMode(int arg0) throws JMSException { + deliveryMode = arg0; + } + + @Override + public boolean getJMSRedelivered() throws JMSException { + return redelivered; + } + + @Override + public void setJMSRedelivered(boolean arg0) throws JMSException { + redelivered = arg0; + } + + @Override + public String getJMSType() throws JMSException { + return type; + } + + @Override + public void setJMSType(String arg0) throws JMSException { + type = arg0; + } + + @Override + public long getJMSExpiration() throws JMSException { + return expiration; + } + + @Override + public void setJMSExpiration(long arg0) throws JMSException { + expiration = arg0; + } + + @Override + public int getJMSPriority() throws JMSException { + return priority; + } + + @Override + public void setJMSPriority(int arg0) throws JMSException { + priority = arg0; + } + + @Override + public void clearProperties() throws JMSException { + } + + @Override + public boolean propertyExists(String arg0) throws JMSException { + return false; + } + + @Override + public boolean getBooleanProperty(String arg0) throws JMSException { + return false; + } + + @Override + public byte getByteProperty(String arg0) throws JMSException { + return 0; + } + + @Override + public short getShortProperty(String arg0) throws JMSException { + return 0; + } + + @Override + public int getIntProperty(String arg0) throws JMSException { + return 0; + } + + @Override + public long getLongProperty(String arg0) throws JMSException { + return 0; + } + + @Override + public float getFloatProperty(String arg0) throws JMSException { + return 0; + } + + @Override + public double getDoubleProperty(String arg0) throws JMSException { + return 0; + } + + @Override + public String getStringProperty(String arg0) throws JMSException { + return (String) props.get(arg0); + } + + @Override + public Object getObjectProperty(String arg0) throws JMSException { + return props.get(arg0); + } + + @Override + public Enumeration getPropertyNames() throws JMSException { + return new Vector(props.keySet()).elements(); + } + + @Override + public void setBooleanProperty(String arg0, boolean arg1) throws JMSException { + } + + @Override + public void setByteProperty(String arg0, byte arg1) throws JMSException { + } + + @Override + public void setShortProperty(String arg0, short arg1) throws JMSException { + } + + @Override + public void setIntProperty(String arg0, int arg1) throws JMSException { + } + + @Override + public void setLongProperty(String arg0, long arg1) throws JMSException { + } + + @Override + public void setFloatProperty(String arg0, float arg1) throws JMSException { + } + + @Override + public void setDoubleProperty(String arg0, double arg1) throws JMSException { + } + + @Override + public void setStringProperty(String arg0, String arg1) throws JMSException { + props.put(arg0, arg1); + } + + @Override + public void setObjectProperty(String arg0, Object arg1) throws JMSException { + props.put(arg0, arg1); + } + + @Override + public void acknowledge() throws JMSException { + } + + @Override + public void clearBody() throws JMSException { + } + + @Override + public void setText(String arg0) throws JMSException { + text = arg0; + } + + @Override + public String getText() throws JMSException { + return text; + } + } + + public void testForeignMessage() throws Exception { + + // Receive a message with the JMS API + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + destination = createDestination(session, destinationType); + MessageConsumer consumer = session.createConsumer(destination); + MessageProducer producer = session.createProducer(destination); + + // Send the message. + { + ForeignMessage message = new ForeignMessage(); + message.text = "Hello"; + message.setStringProperty("test", "value"); + long timeToLive = 10000L; + long start = System.currentTimeMillis(); + producer.send(message, Session.AUTO_ACKNOWLEDGE, 7, timeToLive); + long end = System.currentTimeMillis(); + + //validate jms spec 1.1 section 3.4.11 table 3.1 + // JMSDestination, JMSDeliveryMode, JMSExpiration, JMSPriority, JMSMessageID, and JMSTimestamp + //must be set by sending a message. + + assertNotNull(message.getJMSDestination()); + assertEquals(Session.AUTO_ACKNOWLEDGE, message.getJMSDeliveryMode()); + assertTrue(start + timeToLive <= message.getJMSExpiration()); + assertTrue(end + timeToLive >= message.getJMSExpiration()); + assertEquals(7, message.getJMSPriority()); + assertNotNull(message.getJMSMessageID()); + assertTrue(start <= message.getJMSTimestamp()); + assertTrue(end >= message.getJMSTimestamp()); + } + + // Validate message is OK. + { + TextMessage message = (TextMessage) consumer.receive(1000); + assertNotNull(message); + assertEquals("Hello", message.getText()); + assertEquals("value", message.getStringProperty("test")); + } + + assertNull(consumer.receiveNoWait()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JMSQueueRedeliverTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JMSQueueRedeliverTest.java index be8a6f26df..543c678dfe 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JMSQueueRedeliverTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JMSQueueRedeliverTest.java @@ -17,11 +17,12 @@ package org.apache.activemq; /** - * + * */ public class JMSQueueRedeliverTest extends JmsTopicRedeliverTest { - protected void setUp() throws Exception { - topic = false; - super.setUp(); - } + + protected void setUp() throws Exception { + topic = false; + super.setUp(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JMSUsecaseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JMSUsecaseTest.java index d22907a95a..534e190afe 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JMSUsecaseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JMSUsecaseTest.java @@ -34,108 +34,106 @@ import org.apache.activemq.command.ActiveMQMessage; public class JMSUsecaseTest extends JmsTestSupport { - public ActiveMQDestination destination; - public int deliveryMode; - public int prefetch; - public byte destinationType; - public boolean durableConsumer; + public ActiveMQDestination destination; + public int deliveryMode; + public int prefetch; + public byte destinationType; + public boolean durableConsumer; - public static Test suite() { - return suite(JMSUsecaseTest.class); - } + public static Test suite() { + return suite(JMSUsecaseTest.class); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - public void initCombosForTestQueueBrowser() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE)}); - } + public void initCombosForTestQueueBrowser() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE)}); + } - public void testQueueBrowser() throws Exception { + public void testQueueBrowser() throws Exception { - // Send a message to the broker. - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - destination = createDestination(session, destinationType); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(this.deliveryMode); - sendMessages(session, producer, 5); - producer.close(); + // Send a message to the broker. + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + destination = createDestination(session, destinationType); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(this.deliveryMode); + sendMessages(session, producer, 5); + producer.close(); - QueueBrowser browser = session.createBrowser((Queue)destination); - Enumeration enumeration = browser.getEnumeration(); - for (int i = 0; i < 5; i++) { - Thread.sleep(100); - assertTrue(enumeration.hasMoreElements()); - Message m = (Message)enumeration.nextElement(); - assertNotNull(m); - assertEquals("" + i, ((TextMessage)m).getText()); - } - assertFalse(enumeration.hasMoreElements()); - } + QueueBrowser browser = session.createBrowser((Queue) destination); + Enumeration enumeration = browser.getEnumeration(); + for (int i = 0; i < 5; i++) { + Thread.sleep(100); + assertTrue(enumeration.hasMoreElements()); + Message m = (Message) enumeration.nextElement(); + assertNotNull(m); + assertEquals("" + i, ((TextMessage) m).getText()); + } + assertFalse(enumeration.hasMoreElements()); + } - public void initCombosForTestSendReceive() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); - } + public void initCombosForTestSendReceive() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); + } - public void testSendReceive() throws Exception { - // Send a message to the broker. - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - destination = createDestination(session, destinationType); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(this.deliveryMode); - MessageConsumer consumer = session.createConsumer(destination); - ActiveMQMessage message = new ActiveMQMessage(); - producer.send(message); + public void testSendReceive() throws Exception { + // Send a message to the broker. + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + destination = createDestination(session, destinationType); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(this.deliveryMode); + MessageConsumer consumer = session.createConsumer(destination); + ActiveMQMessage message = new ActiveMQMessage(); + producer.send(message); - // Make sure only 1 message was delivered. - assertNotNull(consumer.receive(1000)); - assertNull(consumer.receiveNoWait()); - } + // Make sure only 1 message was delivered. + assertNotNull(consumer.receive(1000)); + assertNull(consumer.receiveNoWait()); + } - public void initCombosForTestSendReceiveTransacted() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); - } + public void initCombosForTestSendReceiveTransacted() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); + } - public void testSendReceiveTransacted() throws Exception { - // Send a message to the broker. - connection.start(); - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - destination = createDestination(session, destinationType); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(this.deliveryMode); - MessageConsumer consumer = session.createConsumer(destination); - producer.send(session.createTextMessage("test")); + public void testSendReceiveTransacted() throws Exception { + // Send a message to the broker. + connection.start(); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + destination = createDestination(session, destinationType); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(this.deliveryMode); + MessageConsumer consumer = session.createConsumer(destination); + producer.send(session.createTextMessage("test")); - // Message should not be delivered until commit. - assertNull(consumer.receiveNoWait()); - session.commit(); + // Message should not be delivered until commit. + assertNull(consumer.receiveNoWait()); + session.commit(); - // Make sure only 1 message was delivered. - Message message = consumer.receive(1000); - assertNotNull(message); - assertFalse(message.getJMSRedelivered()); - assertNull(consumer.receiveNoWait()); + // Make sure only 1 message was delivered. + Message message = consumer.receive(1000); + assertNotNull(message); + assertFalse(message.getJMSRedelivered()); + assertNull(consumer.receiveNoWait()); - // Message should be redelivered is rollback is used. - session.rollback(); + // Message should be redelivered is rollback is used. + session.rollback(); - // Make sure only 1 message was delivered. - message = consumer.receive(2000); - assertNotNull(message); - assertTrue(message.getJMSRedelivered()); - assertNull(consumer.receiveNoWait()); + // Make sure only 1 message was delivered. + message = consumer.receive(2000); + assertNotNull(message); + assertTrue(message.getJMSRedelivered()); + assertNull(consumer.receiveNoWait()); - // If we commit now, the message should not be redelivered. - session.commit(); - assertNull(consumer.receiveNoWait()); - } + // If we commit now, the message should not be redelivered. + session.commit(); + assertNull(consumer.receiveNoWait()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JMSXAConsumerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JMSXAConsumerTest.java index 7deff2732e..fcebb6433e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JMSXAConsumerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JMSXAConsumerTest.java @@ -17,6 +17,7 @@ package org.apache.activemq; import javax.jms.ConnectionFactory; + import junit.framework.Test; /* @@ -25,26 +26,26 @@ import junit.framework.Test; */ public class JMSXAConsumerTest extends JMSConsumerTest { - public static Test suite() { - return suite(JMSXAConsumerTest.class); - } + public static Test suite() { + return suite(JMSXAConsumerTest.class); + } - @Override - protected ConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQXAConnectionFactory("vm://localhost"); - } + @Override + protected ConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQXAConnectionFactory("vm://localhost"); + } - // some tests use transactions, these will not work unless an XA transaction is in place - // slip these - public void testPrefetch1MessageNotDispatched() throws Exception { - } + // some tests use transactions, these will not work unless an XA transaction is in place + // slip these + public void testPrefetch1MessageNotDispatched() throws Exception { + } - public void testRedispatchOfUncommittedTx() throws Exception { - } + public void testRedispatchOfUncommittedTx() throws Exception { + } - public void testRedispatchOfRolledbackTx() throws Exception { - } + public void testRedispatchOfRolledbackTx() throws Exception { + } - public void testMessageListenerOnMessageCloseUnackedWithPrefetch1StayInQueue() throws Exception { - } + public void testMessageListenerOnMessageCloseUnackedWithPrefetch1StayInQueue() throws Exception { + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsAutoAckListenerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsAutoAckListenerTest.java index 5f34106ae2..6da44effc3 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsAutoAckListenerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsAutoAckListenerTest.java @@ -25,56 +25,56 @@ import javax.jms.Queue; import javax.jms.Session; /** - * + * */ public class JmsAutoAckListenerTest extends TestSupport implements MessageListener { - private Connection connection; + private Connection connection; - protected void setUp() throws Exception { - super.setUp(); - connection = createConnection(); - } + protected void setUp() throws Exception { + super.setUp(); + connection = createConnection(); + } - /** - * @see junit.framework.TestCase#tearDown() - */ - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - connection = null; - } - super.tearDown(); - } + /** + * @see junit.framework.TestCase#tearDown() + */ + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + connection = null; + } + super.tearDown(); + } - /** - * Tests if acknowleged messages are being consumed. - * - * @throws javax.jms.JMSException - */ - public void testAckedMessageAreConsumed() throws Exception { - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createQueue("test"); - MessageProducer producer = session.createProducer(queue); - producer.send(session.createTextMessage("Hello")); + /** + * Tests if acknowleged messages are being consumed. + * + * @throws javax.jms.JMSException + */ + public void testAckedMessageAreConsumed() throws Exception { + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = session.createQueue("test"); + MessageProducer producer = session.createProducer(queue); + producer.send(session.createTextMessage("Hello")); - // Consume the message... - MessageConsumer consumer = session.createConsumer(queue); - consumer.setMessageListener(this); + // Consume the message... + MessageConsumer consumer = session.createConsumer(queue); + consumer.setMessageListener(this); - Thread.sleep(10000); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - // Attempt to Consume the message...check if message was acknowledge - consumer = session.createConsumer(queue); - Message msg = consumer.receive(1000); - assertNull(msg); + Thread.sleep(10000); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + // Attempt to Consume the message...check if message was acknowledge + consumer = session.createConsumer(queue); + Message msg = consumer.receive(1000); + assertNull(msg); - session.close(); - } + session.close(); + } - public void onMessage(Message message) { - assertNotNull(message); + public void onMessage(Message message) { + assertNotNull(message); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsAutoAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsAutoAckTest.java index 90ee032bbe..0bca656486 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsAutoAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsAutoAckTest.java @@ -25,56 +25,55 @@ import javax.jms.Queue; import javax.jms.Session; /** - * + * */ public class JmsAutoAckTest extends TestSupport { - private Connection connection; + private Connection connection; - protected void setUp() throws Exception { - super.setUp(); - connection = createConnection(); - } + protected void setUp() throws Exception { + super.setUp(); + connection = createConnection(); + } - /** - * @see junit.framework.TestCase#tearDown() - */ - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - connection = null; - } - super.tearDown(); - } - - /** - * Tests if acknowleged messages are being consumed. - * - * @throws javax.jms.JMSException - */ - public void testAckedMessageAreConsumed() throws JMSException { - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createQueue("test"); - MessageProducer producer = session.createProducer(queue); - producer.send(session.createTextMessage("Hello")); + /** + * @see junit.framework.TestCase#tearDown() + */ + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + connection = null; + } + super.tearDown(); + } - // Consume the message... - MessageConsumer consumer = session.createConsumer(queue); - Message msg = consumer.receive(1000); - assertNotNull(msg); - - // Reset the session. - session.close(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // Attempt to Consume the message... - consumer = session.createConsumer(queue); - msg = consumer.receive(1000); - assertNull(msg); + /** + * Tests if acknowleged messages are being consumed. + * + * @throws javax.jms.JMSException + */ + public void testAckedMessageAreConsumed() throws JMSException { + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = session.createQueue("test"); + MessageProducer producer = session.createProducer(queue); + producer.send(session.createTextMessage("Hello")); - session.close(); - } - + // Consume the message... + MessageConsumer consumer = session.createConsumer(queue); + Message msg = consumer.receive(1000); + assertNotNull(msg); + + // Reset the session. + session.close(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + // Attempt to Consume the message... + consumer = session.createConsumer(queue); + msg = consumer.receive(1000); + assertNull(msg); + + session.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsBenchmark.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsBenchmark.java index 52a70a0791..be59cd1074 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsBenchmark.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsBenchmark.java @@ -50,160 +50,161 @@ import org.slf4j.LoggerFactory; * same destination. Make sure you run with jvm option -server (makes a big * difference). The tests simulate storing 1000 1k jms messages to see the rate * of processing msg/sec. - * - * */ public class JmsBenchmark extends JmsTestSupport { - private static final transient Logger LOG = LoggerFactory.getLogger(JmsBenchmark.class); - private static final long SAMPLE_DELAY = Integer.parseInt(System.getProperty("SAMPLE_DELAY", "" + 1000 * 5)); - private static final long SAMPLES = Integer.parseInt(System.getProperty("SAMPLES", "10")); - private static final long SAMPLE_DURATION = Integer.parseInt(System.getProperty("SAMPLES_DURATION", "" + 1000 * 60)); - private static final int PRODUCER_COUNT = Integer.parseInt(System.getProperty("PRODUCER_COUNT", "10")); - private static final int CONSUMER_COUNT = Integer.parseInt(System.getProperty("CONSUMER_COUNT", "10")); + private static final transient Logger LOG = LoggerFactory.getLogger(JmsBenchmark.class); - public ActiveMQDestination destination; + private static final long SAMPLE_DELAY = Integer.parseInt(System.getProperty("SAMPLE_DELAY", "" + 1000 * 5)); + private static final long SAMPLES = Integer.parseInt(System.getProperty("SAMPLES", "10")); + private static final long SAMPLE_DURATION = Integer.parseInt(System.getProperty("SAMPLES_DURATION", "" + 1000 * 60)); + private static final int PRODUCER_COUNT = Integer.parseInt(System.getProperty("PRODUCER_COUNT", "10")); + private static final int CONSUMER_COUNT = Integer.parseInt(System.getProperty("CONSUMER_COUNT", "10")); - public static Test suite() { - return suite(JmsBenchmark.class); - } + public ActiveMQDestination destination; - public static void main(String[] args) { - junit.textui.TestRunner.run(JmsBenchmark.class); - } + public static Test suite() { + return suite(JmsBenchmark.class); + } - public void initCombos() { - addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST")}); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(JmsBenchmark.class); + } - @Override - protected BrokerService createBroker() throws Exception { - return BrokerFactory.createBroker(new URI("broker://(tcp://localhost:0)?persistent=false")); - } + public void initCombos() { + addCombinationValues("destination", new Object[]{new ActiveMQQueue("TEST")}); + } - @Override - protected ConnectionFactory createConnectionFactory() throws URISyntaxException, IOException { - return new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getServer().getConnectURI()); - } + @Override + protected BrokerService createBroker() throws Exception { + return BrokerFactory.createBroker(new URI("broker://(tcp://localhost:0)?persistent=false")); + } - /** - * @throws Throwable - */ - public void testConcurrentSendReceive() throws Throwable { + @Override + protected ConnectionFactory createConnectionFactory() throws URISyntaxException, IOException { + return new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getServer().getConnectURI()); + } - final Semaphore connectionsEstablished = new Semaphore(1 - (CONSUMER_COUNT + PRODUCER_COUNT)); - final Semaphore workerDone = new Semaphore(1 - (CONSUMER_COUNT + PRODUCER_COUNT)); - final CountDownLatch sampleTimeDone = new CountDownLatch(1); + /** + * @throws Throwable + */ + public void testConcurrentSendReceive() throws Throwable { - final AtomicInteger producedMessages = new AtomicInteger(0); - final AtomicInteger receivedMessages = new AtomicInteger(0); + final Semaphore connectionsEstablished = new Semaphore(1 - (CONSUMER_COUNT + PRODUCER_COUNT)); + final Semaphore workerDone = new Semaphore(1 - (CONSUMER_COUNT + PRODUCER_COUNT)); + final CountDownLatch sampleTimeDone = new CountDownLatch(1); - final Callable producer = new Callable() { - @Override - public Object call() throws JMSException, InterruptedException { - Connection connection = factory.createConnection(); - connections.add(connection); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - BytesMessage message = session.createBytesMessage(); - message.writeBytes(new byte[1024]); - connection.start(); - connectionsEstablished.release(); + final AtomicInteger producedMessages = new AtomicInteger(0); + final AtomicInteger receivedMessages = new AtomicInteger(0); - while (!sampleTimeDone.await(0, TimeUnit.MILLISECONDS)) { - producer.send(message); - producedMessages.incrementAndGet(); - } + final Callable producer = new Callable() { + @Override + public Object call() throws JMSException, InterruptedException { + Connection connection = factory.createConnection(); + connections.add(connection); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + BytesMessage message = session.createBytesMessage(); + message.writeBytes(new byte[1024]); + connection.start(); + connectionsEstablished.release(); - connection.close(); - workerDone.release(); - return null; + while (!sampleTimeDone.await(0, TimeUnit.MILLISECONDS)) { + producer.send(message); + producedMessages.incrementAndGet(); } - }; - final Callable consumer = new Callable() { + connection.close(); + workerDone.release(); + return null; + } + }; + + final Callable consumer = new Callable() { + @Override + public Object call() throws JMSException, InterruptedException { + Connection connection = factory.createConnection(); + connections.add(connection); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(destination); + + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message msg) { + receivedMessages.incrementAndGet(); + } + }); + connection.start(); + + connectionsEstablished.release(); + sampleTimeDone.await(); + + connection.close(); + workerDone.release(); + return null; + } + }; + + final Throwable workerError[] = new Throwable[1]; + for (int i = 0; i < PRODUCER_COUNT; i++) { + new Thread("Producer:" + i) { @Override - public Object call() throws JMSException, InterruptedException { - Connection connection = factory.createConnection(); - connections.add(connection); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); - - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message msg) { - receivedMessages.incrementAndGet(); - } - }); - connection.start(); - - connectionsEstablished.release(); - sampleTimeDone.await(); - - connection.close(); - workerDone.release(); - return null; + public void run() { + try { + producer.call(); + } + catch (Throwable e) { + e.printStackTrace(); + workerError[0] = e; + } } - }; + }.start(); + } - final Throwable workerError[] = new Throwable[1]; - for (int i = 0; i < PRODUCER_COUNT; i++) { - new Thread("Producer:" + i) { - @Override - public void run() { - try { - producer.call(); - } catch (Throwable e) { - e.printStackTrace(); - workerError[0] = e; - } - } - }.start(); - } + for (int i = 0; i < CONSUMER_COUNT; i++) { + new Thread("Consumer:" + i) { + @Override + public void run() { + try { + consumer.call(); + } + catch (Throwable e) { + e.printStackTrace(); + workerError[0] = e; + } + } + }.start(); + } - for (int i = 0; i < CONSUMER_COUNT; i++) { - new Thread("Consumer:" + i) { - @Override - public void run() { - try { - consumer.call(); - } catch (Throwable e) { - e.printStackTrace(); - workerError[0] = e; - } - } - }.start(); - } + LOG.info(getName() + ": Waiting for Producers and Consumers to startup."); + connectionsEstablished.acquire(); + LOG.info("Producers and Consumers are now running. Waiting for system to reach steady state: " + (SAMPLE_DELAY / 1000.0f) + " seconds"); + Thread.sleep(1000 * 10); - LOG.info(getName() + ": Waiting for Producers and Consumers to startup."); - connectionsEstablished.acquire(); - LOG.info("Producers and Consumers are now running. Waiting for system to reach steady state: " + (SAMPLE_DELAY / 1000.0f) + " seconds"); - Thread.sleep(1000 * 10); + LOG.info("Starting sample: " + SAMPLES + " each lasting " + (SAMPLE_DURATION / 1000.0f) + " seconds"); - LOG.info("Starting sample: " + SAMPLES + " each lasting " + (SAMPLE_DURATION / 1000.0f) + " seconds"); + for (int i = 0; i < SAMPLES; i++) { - for (int i = 0; i < SAMPLES; i++) { + long start = System.currentTimeMillis(); + producedMessages.set(0); + receivedMessages.set(0); - long start = System.currentTimeMillis(); - producedMessages.set(0); - receivedMessages.set(0); + Thread.sleep(SAMPLE_DURATION); - Thread.sleep(SAMPLE_DURATION); + long end = System.currentTimeMillis(); + int r = receivedMessages.get(); + int p = producedMessages.get(); - long end = System.currentTimeMillis(); - int r = receivedMessages.get(); - int p = producedMessages.get(); + LOG.info("published: " + p + " msgs at " + (p * 1000f / (end - start)) + " msgs/sec, " + "consumed: " + r + " msgs at " + (r * 1000f / (end - start)) + " msgs/sec"); + } - LOG.info("published: " + p + " msgs at " + (p * 1000f / (end - start)) + " msgs/sec, " + "consumed: " + r + " msgs at " + (r * 1000f / (end - start)) + " msgs/sec"); - } + LOG.info("Sample done."); + sampleTimeDone.countDown(); - LOG.info("Sample done."); - sampleTimeDone.countDown(); - - workerDone.acquire(); - if (workerError[0] != null) { - throw workerError[0]; - } - } + workerDone.acquire(); + if (workerError[0] != null) { + throw workerError[0]; + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsClientAckListenerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsClientAckListenerTest.java index c1228077c6..fe96ecf4a6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsClientAckListenerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsClientAckListenerTest.java @@ -25,106 +25,107 @@ import javax.jms.Queue; import javax.jms.Session; /** - * + * */ public class JmsClientAckListenerTest extends TestSupport implements MessageListener { - private Connection connection; - private boolean dontAck; + private Connection connection; + private boolean dontAck; - protected void setUp() throws Exception { - super.setUp(); - connection = createConnection(); - } + protected void setUp() throws Exception { + super.setUp(); + connection = createConnection(); + } - /** - * @see junit.framework.TestCase#tearDown() - */ - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - connection = null; - } - super.tearDown(); - } + /** + * @see junit.framework.TestCase#tearDown() + */ + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + connection = null; + } + super.tearDown(); + } - /** - * Tests if acknowleged messages are being consumed. - * - * @throws javax.jms.JMSException - */ - public void testAckedMessageAreConsumed() throws Exception { - connection.start(); - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Queue queue = session.createQueue("test"); - MessageProducer producer = session.createProducer(queue); - producer.send(session.createTextMessage("Hello")); + /** + * Tests if acknowleged messages are being consumed. + * + * @throws javax.jms.JMSException + */ + public void testAckedMessageAreConsumed() throws Exception { + connection.start(); + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Queue queue = session.createQueue("test"); + MessageProducer producer = session.createProducer(queue); + producer.send(session.createTextMessage("Hello")); - // Consume the message... - MessageConsumer consumer = session.createConsumer(queue); - consumer.setMessageListener(this); + // Consume the message... + MessageConsumer consumer = session.createConsumer(queue); + consumer.setMessageListener(this); - Thread.sleep(10000); + Thread.sleep(10000); - // Reset the session. - session.close(); + // Reset the session. + session.close(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - // Attempt to Consume the message... - consumer = session.createConsumer(queue); - Message msg = consumer.receive(1000); - assertNull(msg); + // Attempt to Consume the message... + consumer = session.createConsumer(queue); + Message msg = consumer.receive(1000); + assertNull(msg); - session.close(); - } + session.close(); + } - /** - * Tests if unacknowleged messages are being redelivered when the consumer - * connects again. - * - * @throws javax.jms.JMSException - */ - public void testUnAckedMessageAreNotConsumedOnSessionClose() throws Exception { - connection.start(); - // don't aknowledge message on onMessage() call - dontAck = true; - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Queue queue = session.createQueue("test"); - MessageProducer producer = session.createProducer(queue); - producer.send(session.createTextMessage("Hello")); + /** + * Tests if unacknowleged messages are being redelivered when the consumer + * connects again. + * + * @throws javax.jms.JMSException + */ + public void testUnAckedMessageAreNotConsumedOnSessionClose() throws Exception { + connection.start(); + // don't aknowledge message on onMessage() call + dontAck = true; + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Queue queue = session.createQueue("test"); + MessageProducer producer = session.createProducer(queue); + producer.send(session.createTextMessage("Hello")); - // Consume the message... - MessageConsumer consumer = session.createConsumer(queue); - consumer.setMessageListener(this); - // Don't ack the message. + // Consume the message... + MessageConsumer consumer = session.createConsumer(queue); + consumer.setMessageListener(this); + // Don't ack the message. - // Reset the session. This should cause the Unacked message to be - // redelivered. - session.close(); + // Reset the session. This should cause the Unacked message to be + // redelivered. + session.close(); - Thread.sleep(10000); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - // Attempt to Consume the message... - consumer = session.createConsumer(queue); - Message msg = consumer.receive(2000); - assertNotNull(msg); - msg.acknowledge(); + Thread.sleep(10000); + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + // Attempt to Consume the message... + consumer = session.createConsumer(queue); + Message msg = consumer.receive(2000); + assertNotNull(msg); + msg.acknowledge(); - session.close(); - } + session.close(); + } - public void onMessage(Message message) { + public void onMessage(Message message) { - assertNotNull(message); - if (!dontAck) { - try { - message.acknowledge(); - } catch (Exception e) { - e.printStackTrace(); - } + assertNotNull(message); + if (!dontAck) { + try { + message.acknowledge(); + } + catch (Exception e) { + e.printStackTrace(); + } - } + } - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsClientAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsClientAckTest.java index ef33f9ac20..0e54ef2864 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsClientAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsClientAckTest.java @@ -25,127 +25,127 @@ import javax.jms.Queue; import javax.jms.Session; /** - * + * */ public class JmsClientAckTest extends TestSupport { - private Connection connection; + private Connection connection; - protected void setUp() throws Exception { - super.setUp(); - connection = createConnection(); - } + protected void setUp() throws Exception { + super.setUp(); + connection = createConnection(); + } - /** - * @see junit.framework.TestCase#tearDown() - */ - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - connection = null; - } - super.tearDown(); - } + /** + * @see junit.framework.TestCase#tearDown() + */ + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + connection = null; + } + super.tearDown(); + } - /** - * Tests if acknowledged messages are being consumed. - * - * @throws JMSException - */ - public void testAckedMessageAreConsumed() throws JMSException { - connection.start(); - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Queue queue = session.createQueue(getQueueName()); - MessageProducer producer = session.createProducer(queue); - producer.send(session.createTextMessage("Hello")); + /** + * Tests if acknowledged messages are being consumed. + * + * @throws JMSException + */ + public void testAckedMessageAreConsumed() throws JMSException { + connection.start(); + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Queue queue = session.createQueue(getQueueName()); + MessageProducer producer = session.createProducer(queue); + producer.send(session.createTextMessage("Hello")); - // Consume the message... - MessageConsumer consumer = session.createConsumer(queue); - Message msg = consumer.receive(1000); - assertNotNull(msg); - msg.acknowledge(); + // Consume the message... + MessageConsumer consumer = session.createConsumer(queue); + Message msg = consumer.receive(1000); + assertNotNull(msg); + msg.acknowledge(); - // Reset the session. - session.close(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + // Reset the session. + session.close(); + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - // Attempt to Consume the message... - consumer = session.createConsumer(queue); - msg = consumer.receive(1000); - assertNull(msg); + // Attempt to Consume the message... + consumer = session.createConsumer(queue); + msg = consumer.receive(1000); + assertNull(msg); - session.close(); - } + session.close(); + } - /** - * Tests if acknowledged messages are being consumed. - * - * @throws JMSException - */ - public void testLastMessageAcked() throws JMSException { - connection.start(); - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Queue queue = session.createQueue(getQueueName()); - MessageProducer producer = session.createProducer(queue); - producer.send(session.createTextMessage("Hello")); - producer.send(session.createTextMessage("Hello2")); - producer.send(session.createTextMessage("Hello3")); + /** + * Tests if acknowledged messages are being consumed. + * + * @throws JMSException + */ + public void testLastMessageAcked() throws JMSException { + connection.start(); + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Queue queue = session.createQueue(getQueueName()); + MessageProducer producer = session.createProducer(queue); + producer.send(session.createTextMessage("Hello")); + producer.send(session.createTextMessage("Hello2")); + producer.send(session.createTextMessage("Hello3")); - // Consume the message... - MessageConsumer consumer = session.createConsumer(queue); - Message msg = consumer.receive(1000); - assertNotNull(msg); - msg = consumer.receive(1000); - assertNotNull(msg); - msg = consumer.receive(1000); - assertNotNull(msg); - msg.acknowledge(); + // Consume the message... + MessageConsumer consumer = session.createConsumer(queue); + Message msg = consumer.receive(1000); + assertNotNull(msg); + msg = consumer.receive(1000); + assertNotNull(msg); + msg = consumer.receive(1000); + assertNotNull(msg); + msg.acknowledge(); - // Reset the session. - session.close(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + // Reset the session. + session.close(); + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - // Attempt to Consume the message... - consumer = session.createConsumer(queue); - msg = consumer.receive(1000); - assertNull(msg); + // Attempt to Consume the message... + consumer = session.createConsumer(queue); + msg = consumer.receive(1000); + assertNull(msg); - session.close(); - } - - /** - * Tests if unacknowledged messages are being re-delivered when the consumer connects again. - * - * @throws JMSException - */ - public void testUnAckedMessageAreNotConsumedOnSessionClose() throws JMSException { - connection.start(); - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Queue queue = session.createQueue(getQueueName()); - MessageProducer producer = session.createProducer(queue); - producer.send(session.createTextMessage("Hello")); + session.close(); + } - // Consume the message... - MessageConsumer consumer = session.createConsumer(queue); - Message msg = consumer.receive(1000); - assertNotNull(msg); - // Don't ack the message. - - // Reset the session. This should cause the unacknowledged message to be re-delivered. - session.close(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - - // Attempt to Consume the message... - consumer = session.createConsumer(queue); - msg = consumer.receive(2000); - assertNotNull(msg); - msg.acknowledge(); - - session.close(); - } + /** + * Tests if unacknowledged messages are being re-delivered when the consumer connects again. + * + * @throws JMSException + */ + public void testUnAckedMessageAreNotConsumedOnSessionClose() throws JMSException { + connection.start(); + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Queue queue = session.createQueue(getQueueName()); + MessageProducer producer = session.createProducer(queue); + producer.send(session.createTextMessage("Hello")); - protected String getQueueName() { - return getClass().getName() + "." + getName(); - } + // Consume the message... + MessageConsumer consumer = session.createConsumer(queue); + Message msg = consumer.receive(1000); + assertNotNull(msg); + // Don't ack the message. + + // Reset the session. This should cause the unacknowledged message to be re-delivered. + session.close(); + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + + // Attempt to Consume the message... + consumer = session.createConsumer(queue); + msg = consumer.receive(2000); + assertNotNull(msg); + msg.acknowledge(); + + session.close(); + } + + protected String getQueueName() { + return getClass().getName() + "." + getName(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsConnectionStartStopTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsConnectionStartStopTest.java index c972b1e0d7..0bf2799b8c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsConnectionStartStopTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsConnectionStartStopTest.java @@ -36,123 +36,121 @@ import javax.jms.Topic; */ public class JmsConnectionStartStopTest extends TestSupport { - private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory - .getLog(JmsConnectionStartStopTest.class); + private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(JmsConnectionStartStopTest.class); - private Connection startedConnection; - private Connection stoppedConnection; + private Connection startedConnection; + private Connection stoppedConnection; - /** - * @see junit.framework.TestCase#setUp() - */ - @Override - protected void setUp() throws Exception { + /** + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { - LOG.info(getClass().getClassLoader().getResource("log4j.properties")); + LOG.info(getClass().getClassLoader().getResource("log4j.properties")); - ActiveMQConnectionFactory factory = createConnectionFactory(); - startedConnection = factory.createConnection(); - startedConnection.start(); - stoppedConnection = factory.createConnection(); - } + ActiveMQConnectionFactory factory = createConnectionFactory(); + startedConnection = factory.createConnection(); + startedConnection.start(); + stoppedConnection = factory.createConnection(); + } - /** - * @see junit.framework.TestCase#tearDown() - */ - @Override - protected void tearDown() throws Exception { - stoppedConnection.close(); - startedConnection.close(); - } + /** + * @see junit.framework.TestCase#tearDown() + */ + @Override + protected void tearDown() throws Exception { + stoppedConnection.close(); + startedConnection.close(); + } - /** - * Tests if the consumer receives the messages that were sent before the - * connection was started. - * - * @throws JMSException - */ - public void testStoppedConsumerHoldsMessagesTillStarted() throws JMSException { - Session startedSession = startedConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Session stoppedSession = stoppedConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + /** + * Tests if the consumer receives the messages that were sent before the + * connection was started. + * + * @throws JMSException + */ + public void testStoppedConsumerHoldsMessagesTillStarted() throws JMSException { + Session startedSession = startedConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Session stoppedSession = stoppedConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - // Setup the consumers. - Topic topic = startedSession.createTopic("test"); - MessageConsumer startedConsumer = startedSession.createConsumer(topic); - MessageConsumer stoppedConsumer = stoppedSession.createConsumer(topic); + // Setup the consumers. + Topic topic = startedSession.createTopic("test"); + MessageConsumer startedConsumer = startedSession.createConsumer(topic); + MessageConsumer stoppedConsumer = stoppedSession.createConsumer(topic); - // Send the message. - MessageProducer producer = startedSession.createProducer(topic); - TextMessage message = startedSession.createTextMessage("Hello"); - producer.send(message); + // Send the message. + MessageProducer producer = startedSession.createProducer(topic); + TextMessage message = startedSession.createTextMessage("Hello"); + producer.send(message); - // Test the assertions. - Message m = startedConsumer.receive(1000); - assertNotNull(m); + // Test the assertions. + Message m = startedConsumer.receive(1000); + assertNotNull(m); - m = stoppedConsumer.receive(1000); - assertNull(m); + m = stoppedConsumer.receive(1000); + assertNull(m); - stoppedConnection.start(); - m = stoppedConsumer.receive(5000); - assertNotNull(m); + stoppedConnection.start(); + m = stoppedConsumer.receive(5000); + assertNotNull(m); - startedSession.close(); - stoppedSession.close(); - } + startedSession.close(); + stoppedSession.close(); + } - /** - * Tests if the consumer is able to receive messages eveb when the - * connecction restarts multiple times. - * - * @throws Exception - */ - public void testMultipleConnectionStops() throws Exception { - testStoppedConsumerHoldsMessagesTillStarted(); - stoppedConnection.stop(); - testStoppedConsumerHoldsMessagesTillStarted(); - stoppedConnection.stop(); - testStoppedConsumerHoldsMessagesTillStarted(); - } + /** + * Tests if the consumer is able to receive messages eveb when the + * connecction restarts multiple times. + * + * @throws Exception + */ + public void testMultipleConnectionStops() throws Exception { + testStoppedConsumerHoldsMessagesTillStarted(); + stoppedConnection.stop(); + testStoppedConsumerHoldsMessagesTillStarted(); + stoppedConnection.stop(); + testStoppedConsumerHoldsMessagesTillStarted(); + } - - public void testConcurrentSessionCreateWithStart() throws Exception { - ThreadPoolExecutor executor = new ThreadPoolExecutor(50, Integer.MAX_VALUE, - 60L, TimeUnit.SECONDS, - new SynchronousQueue()); - final Vector exceptions = new Vector(); - final Random rand = new Random(); - Runnable createSessionTask = new Runnable() { - @Override - public void run() { - try { - TimeUnit.MILLISECONDS.sleep(rand.nextInt(10)); - stoppedConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } catch (Exception e) { - exceptions.add(e); - } + public void testConcurrentSessionCreateWithStart() throws Exception { + ThreadPoolExecutor executor = new ThreadPoolExecutor(50, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue()); + final Vector exceptions = new Vector(); + final Random rand = new Random(); + Runnable createSessionTask = new Runnable() { + @Override + public void run() { + try { + TimeUnit.MILLISECONDS.sleep(rand.nextInt(10)); + stoppedConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); } - }; - - Runnable startStopTask = new Runnable() { - @Override - public void run() { - try { - TimeUnit.MILLISECONDS.sleep(rand.nextInt(10)); - stoppedConnection.start(); - stoppedConnection.stop(); - } catch (Exception e) { - exceptions.add(e); - } + catch (Exception e) { + exceptions.add(e); } - }; + } + }; - for (int i=0; i<1000; i++) { - executor.execute(createSessionTask); - executor.execute(startStopTask); - } + Runnable startStopTask = new Runnable() { + @Override + public void run() { + try { + TimeUnit.MILLISECONDS.sleep(rand.nextInt(10)); + stoppedConnection.start(); + stoppedConnection.stop(); + } + catch (Exception e) { + exceptions.add(e); + } + } + }; - executor.shutdown(); - assertTrue("executor terminated", executor.awaitTermination(30, TimeUnit.SECONDS)); - assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); - } + for (int i = 0; i < 1000; i++) { + executor.execute(createSessionTask); + executor.execute(startStopTask); + } + + executor.shutdown(); + assertTrue("executor terminated", executor.awaitTermination(30, TimeUnit.SECONDS)); + assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsConsumerResetActiveListenerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsConsumerResetActiveListenerTest.java index 1a1a95890c..7900b6f9d4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsConsumerResetActiveListenerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsConsumerResetActiveListenerTest.java @@ -34,118 +34,121 @@ import javax.jms.TextMessage; import junit.framework.TestCase; - public class JmsConsumerResetActiveListenerTest extends TestCase { - private Connection connection; - private ActiveMQConnectionFactory factory; - - protected void setUp() throws Exception { - factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); - connection = factory.createConnection(); - } + private Connection connection; + private ActiveMQConnectionFactory factory; - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - connection = null; - } - } - - /** - * verify the (undefined by spec) behaviour of setting a listener while receiving a message. - * - * @throws Exception - */ - public void testSetListenerFromListener() throws Exception { - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Destination dest = session.createQueue("Queue-" + getName()); - final MessageConsumer consumer = session.createConsumer(dest); - - final CountDownLatch latch = new CountDownLatch(2); - final AtomicBoolean first = new AtomicBoolean(true); - final Vector results = new Vector(); - consumer.setMessageListener(new MessageListener() { + protected void setUp() throws Exception { + factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); + connection = factory.createConnection(); + } - public void onMessage(Message message) { - if (first.compareAndSet(true, false)) { - try { - consumer.setMessageListener(this); - results.add(message); - } catch (JMSException e) { - results.add(e); - } - } else { - results.add(message); - } - latch.countDown(); + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + connection = null; + } + } + + /** + * verify the (undefined by spec) behaviour of setting a listener while receiving a message. + * + * @throws Exception + */ + public void testSetListenerFromListener() throws Exception { + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Destination dest = session.createQueue("Queue-" + getName()); + final MessageConsumer consumer = session.createConsumer(dest); + + final CountDownLatch latch = new CountDownLatch(2); + final AtomicBoolean first = new AtomicBoolean(true); + final Vector results = new Vector(); + consumer.setMessageListener(new MessageListener() { + + public void onMessage(Message message) { + if (first.compareAndSet(true, false)) { + try { + consumer.setMessageListener(this); + results.add(message); + } + catch (JMSException e) { + results.add(e); + } } - }); - - connection.start(); - - MessageProducer producer = session.createProducer(dest); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - producer.send(session.createTextMessage("First")); - producer.send(session.createTextMessage("Second")); - - assertTrue("we did not timeout", latch.await(5, TimeUnit.SECONDS)); - - assertEquals("we have a result", 2, results.size()); - Object result = results.get(0); - assertTrue(result instanceof TextMessage); - assertEquals("result is first", "First", ((TextMessage)result).getText()); - result = results.get(1); - assertTrue(result instanceof TextMessage); - assertEquals("result is first", "Second", ((TextMessage)result).getText()); - } - - /** - * and a listener on a new consumer, just in case. - * - * @throws Exception - */ - public void testNewConsumerSetListenerFromListener() throws Exception { - final Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - final Destination dest = session.createQueue("Queue-" + getName()); - final MessageConsumer consumer = session.createConsumer(dest); - - final CountDownLatch latch = new CountDownLatch(2); - final AtomicBoolean first = new AtomicBoolean(true); - final Vector results = new Vector(); - consumer.setMessageListener(new MessageListener() { - - public void onMessage(Message message) { - if (first.compareAndSet(true, false)) { - try { - MessageConsumer anotherConsumer = session.createConsumer(dest); - anotherConsumer.setMessageListener(this); - results.add(message); - } catch (JMSException e) { - results.add(e); - } - } else { - results.add(message); - } - latch.countDown(); + else { + results.add(message); } - }); + latch.countDown(); + } + }); - connection.start(); - - MessageProducer producer = session.createProducer(dest); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - producer.send(session.createTextMessage("First")); - producer.send(session.createTextMessage("Second")); - - assertTrue("we did not timeout", latch.await(5, TimeUnit.SECONDS)); - - assertEquals("we have a result", 2, results.size()); - Object result = results.get(0); - assertTrue(result instanceof TextMessage); - assertEquals("result is first", "First", ((TextMessage)result).getText()); - result = results.get(1); - assertTrue(result instanceof TextMessage); - assertEquals("result is first", "Second", ((TextMessage)result).getText()); - } - } + connection.start(); + + MessageProducer producer = session.createProducer(dest); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + producer.send(session.createTextMessage("First")); + producer.send(session.createTextMessage("Second")); + + assertTrue("we did not timeout", latch.await(5, TimeUnit.SECONDS)); + + assertEquals("we have a result", 2, results.size()); + Object result = results.get(0); + assertTrue(result instanceof TextMessage); + assertEquals("result is first", "First", ((TextMessage) result).getText()); + result = results.get(1); + assertTrue(result instanceof TextMessage); + assertEquals("result is first", "Second", ((TextMessage) result).getText()); + } + + /** + * and a listener on a new consumer, just in case. + * + * @throws Exception + */ + public void testNewConsumerSetListenerFromListener() throws Exception { + final Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + final Destination dest = session.createQueue("Queue-" + getName()); + final MessageConsumer consumer = session.createConsumer(dest); + + final CountDownLatch latch = new CountDownLatch(2); + final AtomicBoolean first = new AtomicBoolean(true); + final Vector results = new Vector(); + consumer.setMessageListener(new MessageListener() { + + public void onMessage(Message message) { + if (first.compareAndSet(true, false)) { + try { + MessageConsumer anotherConsumer = session.createConsumer(dest); + anotherConsumer.setMessageListener(this); + results.add(message); + } + catch (JMSException e) { + results.add(e); + } + } + else { + results.add(message); + } + latch.countDown(); + } + }); + + connection.start(); + + MessageProducer producer = session.createProducer(dest); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + producer.send(session.createTextMessage("First")); + producer.send(session.createTextMessage("Second")); + + assertTrue("we did not timeout", latch.await(5, TimeUnit.SECONDS)); + + assertEquals("we have a result", 2, results.size()); + Object result = results.get(0); + assertTrue(result instanceof TextMessage); + assertEquals("result is first", "First", ((TextMessage) result).getText()); + result = results.get(1); + assertTrue(result instanceof TextMessage); + assertEquals("result is first", "Second", ((TextMessage) result).getText()); + } +} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsCreateConsumerInOnMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsCreateConsumerInOnMessageTest.java index c0a4f5fd68..b1b39551de 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsCreateConsumerInOnMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsCreateConsumerInOnMessageTest.java @@ -25,75 +25,76 @@ import javax.jms.Session; import javax.jms.Topic; /** - * + * */ public class JmsCreateConsumerInOnMessageTest extends TestSupport implements MessageListener { - private Connection connection; - private Session publisherSession; - private Session consumerSession; - private MessageConsumer consumer; - private MessageConsumer testConsumer; - private MessageProducer producer; - private Topic topic; - private final Object lock = new Object(); + private Connection connection; + private Session publisherSession; + private Session consumerSession; + private MessageConsumer consumer; + private MessageConsumer testConsumer; + private MessageProducer producer; + private Topic topic; + private final Object lock = new Object(); - /* - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - super.topic = true; - connection = createConnection(); - connection.setClientID("connection:" + getSubject()); - publisherSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - topic = (Topic)super.createDestination("Test.Topic"); - consumer = consumerSession.createConsumer(topic); - consumer.setMessageListener(this); - producer = publisherSession.createProducer(topic); - connection.start(); - } + /* + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + super.topic = true; + connection = createConnection(); + connection.setClientID("connection:" + getSubject()); + publisherSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + topic = (Topic) super.createDestination("Test.Topic"); + consumer = consumerSession.createConsumer(topic); + consumer.setMessageListener(this); + producer = publisherSession.createProducer(topic); + connection.start(); + } - /* - * @see junit.framework.TestCase#tearDown() - */ - protected void tearDown() throws Exception { - super.tearDown(); - connection.close(); - } + /* + * @see junit.framework.TestCase#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + connection.close(); + } - /** - * Tests if a consumer can be created asynchronusly - * - * @throws Exception - */ - public void testCreateConsumer() throws Exception { - Message msg = super.createMessage(); - producer.send(msg); - synchronized (lock) { - while(testConsumer == null) { - lock.wait(3000); - } - } - assertTrue(testConsumer != null); - } + /** + * Tests if a consumer can be created asynchronusly + * + * @throws Exception + */ + public void testCreateConsumer() throws Exception { + Message msg = super.createMessage(); + producer.send(msg); + synchronized (lock) { + while (testConsumer == null) { + lock.wait(3000); + } + } + assertTrue(testConsumer != null); + } - /** - * Use the asynchronous subscription mechanism - * - * @param message - */ - public void onMessage(Message message) { - try { - testConsumer = consumerSession.createConsumer(topic); - consumerSession.createProducer(topic); - synchronized (lock) { - lock.notify(); - } - } catch (Exception ex) { - ex.printStackTrace(); - assertTrue(false); - } - } + /** + * Use the asynchronous subscription mechanism + * + * @param message + */ + public void onMessage(Message message) { + try { + testConsumer = consumerSession.createConsumer(topic); + consumerSession.createProducer(topic); + synchronized (lock) { + lock.notify(); + } + } + catch (Exception ex) { + ex.printStackTrace(); + assertTrue(false); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsDurableQueueWildcardSendReceiveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsDurableQueueWildcardSendReceiveTest.java index 72dd8bcbd7..9b336cd083 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsDurableQueueWildcardSendReceiveTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsDurableQueueWildcardSendReceiveTest.java @@ -21,32 +21,32 @@ import javax.jms.DeliveryMode; import org.apache.activemq.test.JmsTopicSendReceiveTest; /** - * + * */ public class JmsDurableQueueWildcardSendReceiveTest extends JmsTopicSendReceiveTest { - /** - * Set up the test with a queue and persistent delivery mode. - * - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception { - topic = false; - deliveryMode = DeliveryMode.PERSISTENT; - super.setUp(); - } + /** + * Set up the test with a queue and persistent delivery mode. + * + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + topic = false; + deliveryMode = DeliveryMode.PERSISTENT; + super.setUp(); + } - /** - * Returns the consumer subject. - */ - protected String getConsumerSubject() { - return "FOO.>"; - } + /** + * Returns the consumer subject. + */ + protected String getConsumerSubject() { + return "FOO.>"; + } - /** - * Returns the producer subject. - */ - protected String getProducerSubject() { - return "FOO.BAR.HUMBUG"; - } + /** + * Returns the producer subject. + */ + protected String getProducerSubject() { + return "FOO.BAR.HUMBUG"; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsDurableTopicSelectorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsDurableTopicSelectorTest.java index cc212ab903..3c1b04371c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsDurableTopicSelectorTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsDurableTopicSelectorTest.java @@ -17,11 +17,12 @@ package org.apache.activemq; /** - * + * */ public class JmsDurableTopicSelectorTest extends JmsTopicSelectorTest { - public void setUp() throws Exception { - durable = true; - super.setUp(); - } + + public void setUp() throws Exception { + durable = true; + super.setUp(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsDurableTopicSendReceiveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsDurableTopicSendReceiveTest.java index fa47ea9ede..494fb7be8e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsDurableTopicSendReceiveTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsDurableTopicSendReceiveTest.java @@ -30,61 +30,62 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class JmsDurableTopicSendReceiveTest extends JmsTopicSendReceiveTest { - private static final Logger LOG = LoggerFactory.getLogger(JmsDurableTopicSendReceiveTest.class); - protected Connection connection2; - protected Session session2; - protected Session consumeSession2; - protected MessageConsumer consumer2; - protected MessageProducer producer2; - protected Destination consumerDestination2; - protected Destination producerDestination2; + private static final Logger LOG = LoggerFactory.getLogger(JmsDurableTopicSendReceiveTest.class); - /** - * Set up a durable suscriber test. - * - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception { - this.durable = true; - super.setUp(); - } + protected Connection connection2; + protected Session session2; + protected Session consumeSession2; + protected MessageConsumer consumer2; + protected MessageProducer producer2; + protected Destination consumerDestination2; + protected Destination producerDestination2; - /** - * Test if all the messages sent are being received. - * - * @throws Exception - */ - public void testSendWhileClosed() throws Exception { - connection2 = createConnection(); - connection2.setClientID("test"); - connection2.start(); - session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer2 = session2.createProducer(null); - producer2.setDeliveryMode(deliveryMode); - producerDestination2 = session2.createTopic(getProducerSubject() + "2"); - Thread.sleep(1000); + /** + * Set up a durable suscriber test. + * + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + this.durable = true; + super.setUp(); + } - consumeSession2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumerDestination2 = session2.createTopic(getConsumerSubject() + "2"); - consumer2 = consumeSession2.createDurableSubscriber((Topic)consumerDestination2, getName()); - Thread.sleep(1000); - consumer2.close(); - TextMessage message = session2.createTextMessage("test"); - message.setStringProperty("test", "test"); - message.setJMSType("test"); - producer2.send(producerDestination2, message); - LOG.info("Creating durable consumer"); - consumer2 = consumeSession2.createDurableSubscriber((Topic)consumerDestination2, getName()); - Message msg = consumer2.receive(1000); - assertNotNull(msg); - assertEquals(((TextMessage)msg).getText(), "test"); - assertEquals(msg.getJMSType(), "test"); - assertEquals(msg.getStringProperty("test"), "test"); - connection2.stop(); - connection2.close(); - } + /** + * Test if all the messages sent are being received. + * + * @throws Exception + */ + public void testSendWhileClosed() throws Exception { + connection2 = createConnection(); + connection2.setClientID("test"); + connection2.start(); + session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer2 = session2.createProducer(null); + producer2.setDeliveryMode(deliveryMode); + producerDestination2 = session2.createTopic(getProducerSubject() + "2"); + Thread.sleep(1000); + + consumeSession2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumerDestination2 = session2.createTopic(getConsumerSubject() + "2"); + consumer2 = consumeSession2.createDurableSubscriber((Topic) consumerDestination2, getName()); + Thread.sleep(1000); + consumer2.close(); + TextMessage message = session2.createTextMessage("test"); + message.setStringProperty("test", "test"); + message.setJMSType("test"); + producer2.send(producerDestination2, message); + LOG.info("Creating durable consumer"); + consumer2 = consumeSession2.createDurableSubscriber((Topic) consumerDestination2, getName()); + Message msg = consumer2.receive(1000); + assertNotNull(msg); + assertEquals(((TextMessage) msg).getText(), "test"); + assertEquals(msg.getJMSType(), "test"); + assertEquals(msg.getStringProperty("test"), "test"); + connection2.stop(); + connection2.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsDurableTopicTransactionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsDurableTopicTransactionTest.java index c01fb7f1ef..b9fe5eff5d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsDurableTopicTransactionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsDurableTopicTransactionTest.java @@ -21,20 +21,20 @@ import javax.jms.DeliveryMode; import org.apache.activemq.test.JmsResourceProvider; /** - * + * */ public class JmsDurableTopicTransactionTest extends JmsTopicTransactionTest { - /** - * @see JmsTransactionTestSupport#getJmsResourceProvider() - */ - protected JmsResourceProvider getJmsResourceProvider() { - JmsResourceProvider provider = new JmsResourceProvider(); - provider.setTopic(true); - provider.setDeliveryMode(DeliveryMode.PERSISTENT); - provider.setClientID(getClass().getName()); - provider.setDurableName(getName()); - return provider; - } + /** + * @see JmsTransactionTestSupport#getJmsResourceProvider() + */ + protected JmsResourceProvider getJmsResourceProvider() { + JmsResourceProvider provider = new JmsResourceProvider(); + provider.setTopic(true); + provider.setDeliveryMode(DeliveryMode.PERSISTENT); + provider.setClientID(getClass().getName()); + provider.setDurableName(getName()); + return provider; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsDurableTopicWildcardSendReceiveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsDurableTopicWildcardSendReceiveTest.java index 3058a574df..4e0a2dc7f7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsDurableTopicWildcardSendReceiveTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsDurableTopicWildcardSendReceiveTest.java @@ -21,34 +21,34 @@ import javax.jms.DeliveryMode; import org.apache.activemq.test.JmsTopicSendReceiveTest; /** - * + * */ public class JmsDurableTopicWildcardSendReceiveTest extends JmsTopicSendReceiveTest { - /** - * Sets up a test with a topic destination, durable suscriber and persistent - * delivery mode. - * - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception { - topic = true; - durable = true; - deliveryMode = DeliveryMode.PERSISTENT; - super.setUp(); - } + /** + * Sets up a test with a topic destination, durable suscriber and persistent + * delivery mode. + * + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + topic = true; + durable = true; + deliveryMode = DeliveryMode.PERSISTENT; + super.setUp(); + } - /** - * Returns the consumer subject. - */ - protected String getConsumerSubject() { - return "FOO.>"; - } + /** + * Returns the consumer subject. + */ + protected String getConsumerSubject() { + return "FOO.>"; + } - /** - * Returns the producer subject. - */ - protected String getProducerSubject() { - return "FOO.BAR.HUMBUG"; - } + /** + * Returns the producer subject. + */ + protected String getProducerSubject() { + return "FOO.BAR.HUMBUG"; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsMessageConsumerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsMessageConsumerTest.java index 908de0dfa7..e74c13aa73 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsMessageConsumerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsMessageConsumerTest.java @@ -41,130 +41,131 @@ import org.junit.rules.TestName; public class JmsMessageConsumerTest { - private BrokerService brokerService; - private String brokerURI; + private BrokerService brokerService; + private String brokerURI; - @Rule public TestName name = new TestName(); + @Rule + public TestName name = new TestName(); - @Before - public void startBroker() throws Exception { - brokerService = new BrokerService(); - brokerService.setPersistent(false); - brokerService.setUseJmx(false); - brokerService.start(); - brokerService.waitUntilStarted(); + @Before + public void startBroker() throws Exception { + brokerService = new BrokerService(); + brokerService.setPersistent(false); + brokerService.setUseJmx(false); + brokerService.start(); + brokerService.waitUntilStarted(); - brokerURI = "vm://localhost?create=false"; - } + brokerURI = "vm://localhost?create=false"; + } - @After - public void stopBroker() throws Exception { - if (brokerService != null) { - brokerService.stop(); - } - } + @After + public void stopBroker() throws Exception { + if (brokerService != null) { + brokerService.stop(); + } + } - @Test - public void testSyncReceiveWithExpirationChecks() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURI); + @Test + public void testSyncReceiveWithExpirationChecks() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURI); - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(name.getMethodName()); - MessageConsumer consumer = session.createConsumer(destination); - MessageProducer producer = session.createProducer(destination); - producer.setTimeToLive(TimeUnit.SECONDS.toMillis(2)); - connection.start(); + Connection connection = factory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue(name.getMethodName()); + MessageConsumer consumer = session.createConsumer(destination); + MessageProducer producer = session.createProducer(destination); + producer.setTimeToLive(TimeUnit.SECONDS.toMillis(2)); + connection.start(); - producer.send(session.createTextMessage("test")); + producer.send(session.createTextMessage("test")); - // Allow message to expire in the prefetch buffer - TimeUnit.SECONDS.sleep(4); + // Allow message to expire in the prefetch buffer + TimeUnit.SECONDS.sleep(4); - assertNull(consumer.receive(1000)); - connection.close(); - } + assertNull(consumer.receive(1000)); + connection.close(); + } - @Test - public void testSyncReceiveWithIgnoreExpirationChecks() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURI); - factory.setConsumerExpiryCheckEnabled(false); + @Test + public void testSyncReceiveWithIgnoreExpirationChecks() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURI); + factory.setConsumerExpiryCheckEnabled(false); - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(name.getMethodName()); - MessageConsumer consumer = session.createConsumer(destination); - MessageProducer producer = session.createProducer(destination); - producer.setTimeToLive(TimeUnit.SECONDS.toMillis(2)); - connection.start(); + Connection connection = factory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue(name.getMethodName()); + MessageConsumer consumer = session.createConsumer(destination); + MessageProducer producer = session.createProducer(destination); + producer.setTimeToLive(TimeUnit.SECONDS.toMillis(2)); + connection.start(); - producer.send(session.createTextMessage("test")); + producer.send(session.createTextMessage("test")); - // Allow message to expire in the prefetch buffer - TimeUnit.SECONDS.sleep(4); + // Allow message to expire in the prefetch buffer + TimeUnit.SECONDS.sleep(4); - assertNotNull(consumer.receive(1000)); - connection.close(); - } + assertNotNull(consumer.receive(1000)); + connection.close(); + } - @Test - public void testAsyncReceiveWithExpirationChecks() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURI); + @Test + public void testAsyncReceiveWithExpirationChecks() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURI); - final CountDownLatch received = new CountDownLatch(1); + final CountDownLatch received = new CountDownLatch(1); - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(name.getMethodName()); - MessageConsumer consumer = session.createConsumer(destination); - consumer.setMessageListener(new MessageListener() { + Connection connection = factory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue(name.getMethodName()); + MessageConsumer consumer = session.createConsumer(destination); + consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - received.countDown(); - } - }); - MessageProducer producer = session.createProducer(destination); - producer.setTimeToLive(TimeUnit.SECONDS.toMillis(2)); + @Override + public void onMessage(Message message) { + received.countDown(); + } + }); + MessageProducer producer = session.createProducer(destination); + producer.setTimeToLive(TimeUnit.SECONDS.toMillis(2)); - producer.send(session.createTextMessage("test")); + producer.send(session.createTextMessage("test")); - // Allow message to expire in the prefetch buffer - TimeUnit.SECONDS.sleep(4); - connection.start(); + // Allow message to expire in the prefetch buffer + TimeUnit.SECONDS.sleep(4); + connection.start(); - assertFalse(received.await(1, TimeUnit.SECONDS)); - connection.close(); - } + assertFalse(received.await(1, TimeUnit.SECONDS)); + connection.close(); + } - @Test - public void testAsyncReceiveWithoutExpirationChecks() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURI); - factory.setConsumerExpiryCheckEnabled(false); + @Test + public void testAsyncReceiveWithoutExpirationChecks() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURI); + factory.setConsumerExpiryCheckEnabled(false); - final CountDownLatch received = new CountDownLatch(1); + final CountDownLatch received = new CountDownLatch(1); - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(name.getMethodName()); - MessageConsumer consumer = session.createConsumer(destination); - consumer.setMessageListener(new MessageListener() { + Connection connection = factory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue(name.getMethodName()); + MessageConsumer consumer = session.createConsumer(destination); + consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - received.countDown(); - } - }); - MessageProducer producer = session.createProducer(destination); - producer.setTimeToLive(TimeUnit.SECONDS.toMillis(2)); + @Override + public void onMessage(Message message) { + received.countDown(); + } + }); + MessageProducer producer = session.createProducer(destination); + producer.setTimeToLive(TimeUnit.SECONDS.toMillis(2)); - producer.send(session.createTextMessage("test")); + producer.send(session.createTextMessage("test")); - // Allow message to expire in the prefetch buffer - TimeUnit.SECONDS.sleep(4); - connection.start(); + // Allow message to expire in the prefetch buffer + TimeUnit.SECONDS.sleep(4); + connection.start(); - assertTrue(received.await(5, TimeUnit.SECONDS)); - connection.close(); - } + assertTrue(received.await(5, TimeUnit.SECONDS)); + connection.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsMultipleBrokersTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsMultipleBrokersTestSupport.java index 1d994b9af1..5f871990b6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsMultipleBrokersTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsMultipleBrokersTestSupport.java @@ -69,573 +69,602 @@ import org.springframework.core.io.Resource; /** * Test case support that allows the easy management and connection of several * brokers. - * - * */ public class JmsMultipleBrokersTestSupport extends CombinationTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(JmsMultipleBrokersTestSupport.class); - public static final String AUTO_ASSIGN_TRANSPORT = "tcp://localhost:0"; - public static int maxSetupTime = 5000; - protected Map brokers; - protected Map destinations; + private static final Logger LOG = LoggerFactory.getLogger(JmsMultipleBrokersTestSupport.class); + public static final String AUTO_ASSIGN_TRANSPORT = "tcp://localhost:0"; + public static int maxSetupTime = 5000; - protected int messageSize = 1; + protected Map brokers; + protected Map destinations; - protected boolean persistentDelivery = true; - protected boolean verbose; + protected int messageSize = 1; - protected NetworkConnector bridgeBrokers(String localBrokerName, String remoteBrokerName) throws Exception { - return bridgeBrokers(localBrokerName, remoteBrokerName, false, 1, true); - } + protected boolean persistentDelivery = true; + protected boolean verbose; - protected NetworkConnector bridgeBrokers(String localBrokerName, String remoteBrokerName, boolean dynamicOnly) throws Exception { - BrokerService localBroker = brokers.get(localBrokerName).broker; - BrokerService remoteBroker = brokers.get(remoteBrokerName).broker; + protected NetworkConnector bridgeBrokers(String localBrokerName, String remoteBrokerName) throws Exception { + return bridgeBrokers(localBrokerName, remoteBrokerName, false, 1, true); + } - return bridgeBrokers(localBroker, remoteBroker, dynamicOnly, 1, true, false); - } + protected NetworkConnector bridgeBrokers(String localBrokerName, + String remoteBrokerName, + boolean dynamicOnly) throws Exception { + BrokerService localBroker = brokers.get(localBrokerName).broker; + BrokerService remoteBroker = brokers.get(remoteBrokerName).broker; - protected NetworkConnector bridgeBrokers(String localBrokerName, String remoteBrokerName, boolean dynamicOnly, int networkTTL, boolean conduit) throws Exception { - BrokerService localBroker = brokers.get(localBrokerName).broker; - BrokerService remoteBroker = brokers.get(remoteBrokerName).broker; + return bridgeBrokers(localBroker, remoteBroker, dynamicOnly, 1, true, false); + } - return bridgeBrokers(localBroker, remoteBroker, dynamicOnly, networkTTL, conduit, false); - } + protected NetworkConnector bridgeBrokers(String localBrokerName, + String remoteBrokerName, + boolean dynamicOnly, + int networkTTL, + boolean conduit) throws Exception { + BrokerService localBroker = brokers.get(localBrokerName).broker; + BrokerService remoteBroker = brokers.get(remoteBrokerName).broker; - // Overwrite this method to specify how you want to bridge the two brokers - // By default, bridge them using add network connector of the local broker - // and the first connector of the remote broker - protected NetworkConnector bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker, boolean dynamicOnly, int networkTTL, boolean conduit, boolean failover) throws Exception { - List transportConnectors = remoteBroker.getTransportConnectors(); - URI remoteURI; - if (!transportConnectors.isEmpty()) { - remoteURI = transportConnectors.get(0).getConnectUri(); - String uri = "static:(" + remoteURI + ")"; - if (failover) { - uri = "static:(failover:(" + remoteURI + "))"; - } - NetworkConnector connector = new DiscoveryNetworkConnector(new URI(uri)); - connector.setName("to-" + remoteBroker.getBrokerName()); - connector.setDynamicOnly(dynamicOnly); - connector.setNetworkTTL(networkTTL); - connector.setConduitSubscriptions(conduit); - localBroker.addNetworkConnector(connector); - maxSetupTime = 2000; - return connector; - } else { - throw new Exception("Remote broker has no registered connectors."); - } + return bridgeBrokers(localBroker, remoteBroker, dynamicOnly, networkTTL, conduit, false); + } - } + // Overwrite this method to specify how you want to bridge the two brokers + // By default, bridge them using add network connector of the local broker + // and the first connector of the remote broker + protected NetworkConnector bridgeBrokers(BrokerService localBroker, + BrokerService remoteBroker, + boolean dynamicOnly, + int networkTTL, + boolean conduit, + boolean failover) throws Exception { + List transportConnectors = remoteBroker.getTransportConnectors(); + URI remoteURI; + if (!transportConnectors.isEmpty()) { + remoteURI = transportConnectors.get(0).getConnectUri(); + String uri = "static:(" + remoteURI + ")"; + if (failover) { + uri = "static:(failover:(" + remoteURI + "))"; + } + NetworkConnector connector = new DiscoveryNetworkConnector(new URI(uri)); + connector.setName("to-" + remoteBroker.getBrokerName()); + connector.setDynamicOnly(dynamicOnly); + connector.setNetworkTTL(networkTTL); + connector.setConduitSubscriptions(conduit); + localBroker.addNetworkConnector(connector); + maxSetupTime = 2000; + return connector; + } + else { + throw new Exception("Remote broker has no registered connectors."); + } - // This will interconnect all brokers using multicast - protected void bridgeAllBrokers() throws Exception { - bridgeAllBrokers("default", 1, false, false); - } - - protected void bridgeAllBrokers(String groupName, int ttl, boolean suppressduplicateQueueSubs) throws Exception { - bridgeAllBrokers(groupName, ttl, suppressduplicateQueueSubs, false); - } + } - protected void bridgeAllBrokers(String groupName, int ttl, boolean suppressduplicateQueueSubs, boolean decreasePriority) throws Exception { - Collection brokerList = brokers.values(); - for (Iterator i = brokerList.iterator(); i.hasNext();) { - BrokerService broker = i.next().broker; - List transportConnectors = broker.getTransportConnectors(); + // This will interconnect all brokers using multicast + protected void bridgeAllBrokers() throws Exception { + bridgeAllBrokers("default", 1, false, false); + } - if (transportConnectors.isEmpty()) { - broker.addConnector(new URI(AUTO_ASSIGN_TRANSPORT)); - transportConnectors = broker.getTransportConnectors(); - } + protected void bridgeAllBrokers(String groupName, int ttl, boolean suppressduplicateQueueSubs) throws Exception { + bridgeAllBrokers(groupName, ttl, suppressduplicateQueueSubs, false); + } - TransportConnector transport = transportConnectors.get(0); - transport.setDiscoveryUri(new URI("multicast://default?group=" + groupName)); - NetworkConnector nc = broker.addNetworkConnector("multicast://default?group=" + groupName); - nc.setNetworkTTL(ttl); - nc.setSuppressDuplicateQueueSubscriptions(suppressduplicateQueueSubs); - nc.setDecreaseNetworkConsumerPriority(decreasePriority); - } + protected void bridgeAllBrokers(String groupName, + int ttl, + boolean suppressduplicateQueueSubs, + boolean decreasePriority) throws Exception { + Collection brokerList = brokers.values(); + for (Iterator i = brokerList.iterator(); i.hasNext(); ) { + BrokerService broker = i.next().broker; + List transportConnectors = broker.getTransportConnectors(); - // Multicasting may take longer to setup - maxSetupTime = 8000; - } + if (transportConnectors.isEmpty()) { + broker.addConnector(new URI(AUTO_ASSIGN_TRANSPORT)); + transportConnectors = broker.getTransportConnectors(); + } + TransportConnector transport = transportConnectors.get(0); + transport.setDiscoveryUri(new URI("multicast://default?group=" + groupName)); + NetworkConnector nc = broker.addNetworkConnector("multicast://default?group=" + groupName); + nc.setNetworkTTL(ttl); + nc.setSuppressDuplicateQueueSubscriptions(suppressduplicateQueueSubs); + nc.setDecreaseNetworkConsumerPriority(decreasePriority); + } - protected void waitForBridgeFormation(final int min) throws Exception { - for (BrokerItem brokerItem : brokers.values()) { - final BrokerService broker = brokerItem.broker; - waitForBridgeFormation(broker, min, 0); - } - } + // Multicasting may take longer to setup + maxSetupTime = 8000; + } - public boolean waitForBridgeFormation(final BrokerService broker, final int min, final int bridgeIndex) throws Exception { - return waitForBridgeFormation(broker, min, bridgeIndex, Wait.MAX_WAIT_MILLIS*2); - } + protected void waitForBridgeFormation(final int min) throws Exception { + for (BrokerItem brokerItem : brokers.values()) { + final BrokerService broker = brokerItem.broker; + waitForBridgeFormation(broker, min, 0); + } + } - public boolean waitForBridgeFormation(final BrokerService broker, final int min, final int bridgeIndex, long wait) throws Exception { + public boolean waitForBridgeFormation(final BrokerService broker, + final int min, + final int bridgeIndex) throws Exception { + return waitForBridgeFormation(broker, min, bridgeIndex, Wait.MAX_WAIT_MILLIS * 2); + } - boolean result = false; - if (!broker.getNetworkConnectors().isEmpty()) { - result = Wait.waitFor(new Wait.Condition() { - public boolean isSatisified() throws Exception { - int activeCount = 0; - for (NetworkBridge bridge : broker.getNetworkConnectors().get(bridgeIndex).activeBridges()) { - if (bridge.getRemoteBrokerName() != null) { - LOG.info("found bridge[" + bridge + "] to " + bridge.getRemoteBrokerName() + " on broker :" + broker.getBrokerName()); - activeCount++; - } - } - return activeCount >= min; - }}, wait); - } - return result; - } + public boolean waitForBridgeFormation(final BrokerService broker, + final int min, + final int bridgeIndex, + long wait) throws Exception { - protected void waitForMinTopicRegionConsumerCount(final String name, final int count) throws Exception { - final BrokerService broker = brokers.get(name).broker; - final TopicRegion topicRegion = (TopicRegion) ((RegionBroker) broker.getRegionBroker()).getTopicRegion(); - assertTrue("found expected consumers in topic region of" + name, Wait.waitFor(new Wait.Condition() { - @Override + boolean result = false; + if (!broker.getNetworkConnectors().isEmpty()) { + result = Wait.waitFor(new Wait.Condition() { public boolean isSatisified() throws Exception { - LOG.info("topic consumers: " + name +", " + topicRegion.getSubscriptions().toString()); - return topicRegion.getSubscriptions().size() >= count; + int activeCount = 0; + for (NetworkBridge bridge : broker.getNetworkConnectors().get(bridgeIndex).activeBridges()) { + if (bridge.getRemoteBrokerName() != null) { + LOG.info("found bridge[" + bridge + "] to " + bridge.getRemoteBrokerName() + " on broker :" + broker.getBrokerName()); + activeCount++; + } + } + return activeCount >= min; } - })); - } + }, wait); + } + return result; + } - /** - * Timed wait for {@link #hasBridge(String, String)}. - * - * @see #hasBridge(String, String) - * - * @param localBrokerName - * - the name of the broker on the "local" side of the bridge - * @param remoteBrokerName - * - the name of the broker on the "remote" side of the bridge - * @param time - * - the maximum time to wait for the bridge to be established - * @param units - * - the units for time - * @throws InterruptedException - * - if the calling thread is interrupted - * @throws TimeoutException - * - if the bridge is not established within the time limit - * @throws Exception - * - some other unknown error occurs - */ - protected void waitForBridge(final String localBrokerName, - final String remoteBrokerName, long time, TimeUnit units) - throws InterruptedException, TimeoutException, Exception { - if (!Wait.waitFor(new Wait.Condition() { - public boolean isSatisified() { - return hasBridge(localBrokerName, remoteBrokerName); + protected void waitForMinTopicRegionConsumerCount(final String name, final int count) throws Exception { + final BrokerService broker = brokers.get(name).broker; + final TopicRegion topicRegion = (TopicRegion) ((RegionBroker) broker.getRegionBroker()).getTopicRegion(); + assertTrue("found expected consumers in topic region of" + name, Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("topic consumers: " + name + ", " + topicRegion.getSubscriptions().toString()); + return topicRegion.getSubscriptions().size() >= count; + } + })); + } + + /** + * Timed wait for {@link #hasBridge(String, String)}. + * + * @param localBrokerName - the name of the broker on the "local" side of the bridge + * @param remoteBrokerName - the name of the broker on the "remote" side of the bridge + * @param time - the maximum time to wait for the bridge to be established + * @param units - the units for time + * @throws InterruptedException - if the calling thread is interrupted + * @throws TimeoutException - if the bridge is not established within the time limit + * @throws Exception - some other unknown error occurs + * @see #hasBridge(String, String) + */ + protected void waitForBridge(final String localBrokerName, + final String remoteBrokerName, + long time, + TimeUnit units) throws InterruptedException, TimeoutException, Exception { + if (!Wait.waitFor(new Wait.Condition() { + public boolean isSatisified() { + return hasBridge(localBrokerName, remoteBrokerName); + } + }, units.toMillis(time))) { + throw new TimeoutException("Bridge not established from broker " + localBrokerName + " to " + remoteBrokerName + " within " + units.toMillis(time) + " milliseconds."); + } + } + + /** + * Determines whether a bridge has been established between the specified + * brokers.Establishment means that connections have been created and broker + * info has been exchanged. Due to the asynchronous nature of the + * connections, there is still a possibility that the bridge may fail + * shortly after establishment. + * + * @param localBrokerName - the name of the broker on the "local" side of the bridge + * @param remoteBrokerName - the name of the broker on the "remote" side of the bridge + */ + protected boolean hasBridge(String localBrokerName, String remoteBrokerName) { + final BrokerItem fromBroker = brokers.get(localBrokerName); + if (fromBroker == null) { + throw new IllegalArgumentException("Unknown broker: " + localBrokerName); + } + + for (BrokerInfo peerInfo : fromBroker.broker.getRegionBroker().getPeerBrokerInfos()) { + if (peerInfo.getBrokerName().equals(remoteBrokerName)) { + return true; + } + } + return false; + } + + protected void waitForBridgeFormation() throws Exception { + waitForBridgeFormation(1); + } + + protected void startAllBrokers() throws Exception { + Collection brokerList = brokers.values(); + for (Iterator i = brokerList.iterator(); i.hasNext(); ) { + BrokerService broker = i.next().broker; + broker.start(); + broker.waitUntilStarted(); + } + + Thread.sleep(maxSetupTime); + } + + protected BrokerService createBroker(String brokerName) throws Exception { + BrokerService broker = new BrokerService(); + broker.setBrokerName(brokerName); + brokers.put(brokerName, new BrokerItem(broker)); + + return broker; + } + + protected BrokerService createBroker(URI brokerUri) throws Exception { + BrokerService broker = BrokerFactory.createBroker(brokerUri); + configureBroker(broker); + brokers.put(broker.getBrokerName(), new BrokerItem(broker)); + + return broker; + } + + protected void configureBroker(BrokerService broker) { + } + + protected BrokerService createBroker(Resource configFile) throws Exception { + BrokerFactoryBean brokerFactory = new BrokerFactoryBean(configFile); + brokerFactory.afterPropertiesSet(); + + BrokerService broker = brokerFactory.getBroker(); + brokers.put(broker.getBrokerName(), new BrokerItem(broker)); + + return broker; + } + + protected ConnectionFactory getConnectionFactory(String brokerName) throws Exception { + BrokerItem brokerItem = brokers.get(brokerName); + if (brokerItem != null) { + return brokerItem.factory; + } + return null; + } + + protected Connection createConnection(String brokerName) throws Exception { + BrokerItem brokerItem = brokers.get(brokerName); + if (brokerItem != null) { + return brokerItem.createConnection(); + } + return null; + } + + protected MessageConsumer createSyncConsumer(String brokerName, Destination dest) throws Exception { + BrokerItem brokerItem = brokers.get(brokerName); + if (brokerItem != null) { + Connection con = brokerItem.createConnection(); + con.start(); + Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = sess.createConsumer(dest); + return consumer; + } + return null; + } + + protected MessageConsumer createConsumer(String brokerName, Destination dest) throws Exception { + return createConsumer(brokerName, dest, null, null); + } + + protected MessageConsumer createConsumer(String brokerName, + Destination dest, + String messageSelector) throws Exception { + return createConsumer(brokerName, dest, null, messageSelector); + } + + protected MessageConsumer createConsumer(String brokerName, + Destination dest, + CountDownLatch latch) throws Exception { + return createConsumer(brokerName, dest, latch, null); + } + + protected MessageConsumer createConsumer(String brokerName, + Destination dest, + CountDownLatch latch, + String messageSelector) throws Exception { + BrokerItem brokerItem = brokers.get(brokerName); + if (brokerItem != null) { + return brokerItem.createConsumer(dest, latch, messageSelector); + } + return null; + } + + protected QueueBrowser createBrowser(String brokerName, Destination dest) throws Exception { + BrokerItem brokerItem = brokers.get(brokerName); + if (brokerItem != null) { + return brokerItem.createBrowser(dest); + } + return null; + } + + protected MessageConsumer createDurableSubscriber(String brokerName, Topic dest, String name) throws Exception { + BrokerItem brokerItem = brokers.get(brokerName); + if (brokerItem != null) { + return brokerItem.createDurableSubscriber(dest, name); + } + return null; + } + + protected MessageIdList getBrokerMessages(String brokerName) { + BrokerItem brokerItem = brokers.get(brokerName); + if (brokerItem != null) { + return brokerItem.getAllMessages(); + } + return null; + } + + protected MessageIdList getConsumerMessages(String brokerName, MessageConsumer consumer) { + BrokerItem brokerItem = brokers.get(brokerName); + if (brokerItem != null) { + return brokerItem.getConsumerMessages(consumer); + } + return null; + } + + protected void assertConsumersConnect(String brokerName, + Destination destination, + final int count, + long timeout) throws Exception { + BrokerItem brokerItem = brokers.get(brokerName); + Connection conn = brokerItem.createConnection(); + conn.start(); + ConsumerEventSource ces = new ConsumerEventSource(conn, destination); + + try { + final AtomicInteger actualConnected = new AtomicInteger(); + final CountDownLatch latch = new CountDownLatch(1); + ces.setConsumerListener(new ConsumerListener() { + public void onConsumerEvent(ConsumerEvent event) { + if (actualConnected.get() < count) { + actualConnected.set(event.getConsumerCount()); + } + if (event.getConsumerCount() >= count) { + latch.countDown(); + } } - }, units.toMillis(time))) { - throw new TimeoutException("Bridge not established from broker " - + localBrokerName + " to " + remoteBrokerName + " within " - + units.toMillis(time) + " milliseconds."); - } - } + }); + ces.start(); - /** - * Determines whether a bridge has been established between the specified - * brokers.Establishment means that connections have been created and broker - * info has been exchanged. Due to the asynchronous nature of the - * connections, there is still a possibility that the bridge may fail - * shortly after establishment. - * - * @param localBrokerName - * - the name of the broker on the "local" side of the bridge - * @param remoteBrokerName - * - the name of the broker on the "remote" side of the bridge - */ - protected boolean hasBridge(String localBrokerName, String remoteBrokerName) { - final BrokerItem fromBroker = brokers.get(localBrokerName); - if (fromBroker == null) { - throw new IllegalArgumentException("Unknown broker: " - + localBrokerName); - } + latch.await(timeout, TimeUnit.MILLISECONDS); + assertTrue("Expected at least " + count + " consumers to connect, but only " + actualConnected.get() + " connectect within " + timeout + " ms", actualConnected.get() >= count); - for (BrokerInfo peerInfo : fromBroker.broker.getRegionBroker() - .getPeerBrokerInfos()) { - if (peerInfo.getBrokerName().equals(remoteBrokerName)) { - return true; + } + finally { + ces.stop(); + conn.close(); + brokerItem.connections.remove(conn); + } + } + + protected void sendMessages(String brokerName, Destination destination, int count) throws Exception { + sendMessages(brokerName, destination, count, null); + } + + protected void sendMessages(String brokerName, + Destination destination, + int count, + HashMap properties) throws Exception { + BrokerItem brokerItem = brokers.get(brokerName); + + Connection conn = brokerItem.createConnection(); + conn.start(); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + + MessageProducer producer = brokerItem.createProducer(destination, sess); + producer.setDeliveryMode(persistentDelivery ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT); + + for (int i = 0; i < count; i++) { + TextMessage msg = createTextMessage(sess, conn.getClientID() + ": Message-" + i); + if (properties != null) { + for (String propertyName : properties.keySet()) { + msg.setObjectProperty(propertyName, properties.get(propertyName)); } - } - return false; - } - - protected void waitForBridgeFormation() throws Exception { - waitForBridgeFormation(1); - } + } + producer.send(msg); + onSend(i, msg); + } - protected void startAllBrokers() throws Exception { - Collection brokerList = brokers.values(); - for (Iterator i = brokerList.iterator(); i.hasNext();) { - BrokerService broker = i.next().broker; - broker.start(); - broker.waitUntilStarted(); - } + producer.close(); + sess.close(); + conn.close(); + brokerItem.connections.remove(conn); + } - Thread.sleep(maxSetupTime); - } + protected void onSend(int i, TextMessage msg) { + } - protected BrokerService createBroker(String brokerName) throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName(brokerName); - brokers.put(brokerName, new BrokerItem(broker)); + protected TextMessage createTextMessage(Session session, String initText) throws Exception { + TextMessage msg = session.createTextMessage(); - return broker; - } + // Pad message text + if (initText.length() < messageSize) { + char[] data = new char[messageSize - initText.length()]; + Arrays.fill(data, '*'); + String str = new String(data); + msg.setText(initText + str); - protected BrokerService createBroker(URI brokerUri) throws Exception { - BrokerService broker = BrokerFactory.createBroker(brokerUri); - configureBroker(broker); - brokers.put(broker.getBrokerName(), new BrokerItem(broker)); + // Do not pad message text + } + else { + msg.setText(initText); + } - return broker; - } + return msg; + } - protected void configureBroker(BrokerService broker) { - } + protected ActiveMQDestination createDestination(String name, boolean topic) throws JMSException { + Destination dest; + if (topic) { + dest = new ActiveMQTopic(name); + destinations.put(name, dest); + return (ActiveMQDestination) dest; + } + else { + dest = new ActiveMQQueue(name); + destinations.put(name, dest); + return (ActiveMQDestination) dest; + } + } - protected BrokerService createBroker(Resource configFile) throws Exception { - BrokerFactoryBean brokerFactory = new BrokerFactoryBean(configFile); - brokerFactory.afterPropertiesSet(); + protected void setUp() throws Exception { + super.setUp(); + brokers = new HashMap(); + destinations = new HashMap(); + } - BrokerService broker = brokerFactory.getBroker(); - brokers.put(broker.getBrokerName(), new BrokerItem(broker)); + protected void tearDown() throws Exception { + destroyAllBrokers(); + super.tearDown(); + } - return broker; - } + protected void destroyBroker(String brokerName) throws Exception { + BrokerItem brokerItem = brokers.remove(brokerName); - protected ConnectionFactory getConnectionFactory(String brokerName) throws Exception { - BrokerItem brokerItem = brokers.get(brokerName); - if (brokerItem != null) { - return brokerItem.factory; - } - return null; - } + if (brokerItem != null) { + brokerItem.destroy(); + } + } - protected Connection createConnection(String brokerName) throws Exception { - BrokerItem brokerItem = brokers.get(brokerName); - if (brokerItem != null) { - return brokerItem.createConnection(); - } - return null; - } + protected void destroyAllBrokers() throws Exception { + for (Iterator i = brokers.values().iterator(); i.hasNext(); ) { + BrokerItem brokerItem = i.next(); + brokerItem.destroy(); + } + brokers.clear(); + } - protected MessageConsumer createSyncConsumer(String brokerName, Destination dest) throws Exception { - BrokerItem brokerItem = brokers.get(brokerName); - if (brokerItem != null) { - Connection con = brokerItem.createConnection(); - con.start(); - Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = sess.createConsumer(dest); - return consumer; - } - return null; - } + // Class to group broker components together + public class BrokerItem { - protected MessageConsumer createConsumer(String brokerName, Destination dest) throws Exception { - return createConsumer(brokerName, dest, null, null); - } + public BrokerService broker; + public ActiveMQConnectionFactory factory; + public List connections; + public Map consumers; + public MessageIdList allMessages = new MessageIdList(); + public boolean persistent; + private IdGenerator id; - protected MessageConsumer createConsumer(String brokerName, Destination dest, String messageSelector) throws Exception { - return createConsumer(brokerName, dest, null, messageSelector); - } - - protected MessageConsumer createConsumer(String brokerName, Destination dest, CountDownLatch latch) throws Exception { - return createConsumer(brokerName, dest, latch, null); - } - - protected MessageConsumer createConsumer(String brokerName, Destination dest, CountDownLatch latch, String messageSelector) throws Exception { - BrokerItem brokerItem = brokers.get(brokerName); - if (brokerItem != null) { - return brokerItem.createConsumer(dest, latch, messageSelector); - } - return null; - } - - protected QueueBrowser createBrowser(String brokerName, Destination dest) throws Exception { - BrokerItem brokerItem = brokers.get(brokerName); - if (brokerItem != null) { - return brokerItem.createBrowser(dest); - } - return null; - } + public BrokerItem(BrokerService broker) throws Exception { + this.broker = broker; - protected MessageConsumer createDurableSubscriber(String brokerName, Topic dest, String name) throws Exception { - BrokerItem brokerItem = brokers.get(brokerName); - if (brokerItem != null) { - return brokerItem.createDurableSubscriber(dest, name); - } - return null; - } + factory = new ActiveMQConnectionFactory(broker.getVmConnectorURI()); + factory.setConnectionIDPrefix(broker.getBrokerName()); + consumers = Collections.synchronizedMap(new HashMap()); + connections = Collections.synchronizedList(new ArrayList()); + allMessages.setVerbose(verbose); + id = new IdGenerator(broker.getBrokerName() + ":"); + } - protected MessageIdList getBrokerMessages(String brokerName) { - BrokerItem brokerItem = brokers.get(brokerName); - if (brokerItem != null) { - return brokerItem.getAllMessages(); - } - return null; - } + public Connection createConnection() throws Exception { + Connection conn = factory.createConnection(); + conn.setClientID(id.generateId()); - protected MessageIdList getConsumerMessages(String brokerName, MessageConsumer consumer) { - BrokerItem brokerItem = brokers.get(brokerName); - if (brokerItem != null) { - return brokerItem.getConsumerMessages(consumer); - } - return null; - } + connections.add(conn); + return conn; + } - protected void assertConsumersConnect(String brokerName, Destination destination, final int count, long timeout) throws Exception { - BrokerItem brokerItem = brokers.get(brokerName); - Connection conn = brokerItem.createConnection(); - conn.start(); - ConsumerEventSource ces = new ConsumerEventSource(conn, destination); + public MessageConsumer createConsumer(Destination dest) throws Exception { + return createConsumer(dest, null, null); + } - try { - final AtomicInteger actualConnected = new AtomicInteger(); - final CountDownLatch latch = new CountDownLatch(1); - ces.setConsumerListener(new ConsumerListener(){ - public void onConsumerEvent(ConsumerEvent event) { - if( actualConnected.get() < count ) { - actualConnected.set(event.getConsumerCount()); - } - if( event.getConsumerCount() >= count ) { - latch.countDown(); - } - } - }); - ces.start(); - - latch.await(timeout, TimeUnit.MILLISECONDS); - assertTrue("Expected at least "+count+" consumers to connect, but only "+actualConnected.get()+" connectect within "+timeout+" ms", actualConnected.get() >= count); - - } finally { - ces.stop(); - conn.close(); - brokerItem.connections.remove(conn); - } - } + public MessageConsumer createConsumer(Destination dest, String messageSelector) throws Exception { + return createConsumer(dest, null, messageSelector); + } + public MessageConsumer createConsumer(Destination dest, + CountDownLatch latch, + String messageSelector) throws Exception { + Connection c = createConnection(); + c.start(); + Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); + return createConsumerWithSession(dest, s, latch, messageSelector); + } - protected void sendMessages(String brokerName, Destination destination, int count) throws Exception { - sendMessages(brokerName, destination, count, null); - } - - protected void sendMessages(String brokerName, Destination destination, int count, HashMapproperties) throws Exception { - BrokerItem brokerItem = brokers.get(brokerName); + public MessageConsumer createConsumerWithSession(Destination dest, Session sess) throws Exception { + return createConsumerWithSession(dest, sess, null, null); + } - Connection conn = brokerItem.createConnection(); - conn.start(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + public MessageConsumer createConsumerWithSession(Destination dest, + Session sess, + CountDownLatch latch, + String messageSelector) throws Exception { + MessageConsumer client = sess.createConsumer(dest, messageSelector); + MessageIdList messageIdList = new MessageIdList(); + messageIdList.setCountDownLatch(latch); + messageIdList.setParent(allMessages); + client.setMessageListener(messageIdList); + consumers.put(client, messageIdList); + return client; + } - MessageProducer producer = brokerItem.createProducer(destination, sess); - producer.setDeliveryMode(persistentDelivery ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT); + public QueueBrowser createBrowser(Destination dest) throws Exception { + Connection c = createConnection(); + c.start(); + Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); + return s.createBrowser((Queue) dest); + } - for (int i = 0; i < count; i++) { - TextMessage msg = createTextMessage(sess, conn.getClientID() + ": Message-" + i); - if (properties != null) { - for (String propertyName : properties.keySet()) { - msg.setObjectProperty(propertyName, properties.get(propertyName)); - } + public MessageConsumer createDurableSubscriber(Topic dest, String name) throws Exception { + Connection c = createConnection(); + c.start(); + Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); + return createDurableSubscriber(dest, s, name); + } + + public MessageConsumer createDurableSubscriber(Topic dest, Session sess, String name) throws Exception { + MessageConsumer client = sess.createDurableSubscriber((Topic) dest, name); + MessageIdList messageIdList = new MessageIdList(); + messageIdList.setParent(allMessages); + client.setMessageListener(messageIdList); + consumers.put(client, messageIdList); + + return client; + } + + public MessageIdList getAllMessages() { + return allMessages; + } + + public MessageIdList getConsumerMessages(MessageConsumer consumer) { + return consumers.get(consumer); + } + + public MessageProducer createProducer(Destination dest) throws Exception { + Connection c = createConnection(); + c.start(); + Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); + return createProducer(dest, s); + } + + public MessageProducer createProducer(Destination dest, Session sess) throws Exception { + MessageProducer client = sess.createProducer(dest); + client.setDeliveryMode(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT); + return client; + } + + public void destroy() throws Exception { + while (!connections.isEmpty()) { + Connection c = connections.remove(0); + try { + c.close(); } - producer.send(msg); - onSend(i, msg); - } - - producer.close(); - sess.close(); - conn.close(); - brokerItem.connections.remove(conn); - } - - protected void onSend(int i, TextMessage msg) { - } - - protected TextMessage createTextMessage(Session session, String initText) throws Exception { - TextMessage msg = session.createTextMessage(); - - // Pad message text - if (initText.length() < messageSize) { - char[] data = new char[messageSize - initText.length()]; - Arrays.fill(data, '*'); - String str = new String(data); - msg.setText(initText + str); - - // Do not pad message text - } else { - msg.setText(initText); - } - - return msg; - } - - protected ActiveMQDestination createDestination(String name, boolean topic) throws JMSException { - Destination dest; - if (topic) { - dest = new ActiveMQTopic(name); - destinations.put(name, dest); - return (ActiveMQDestination)dest; - } else { - dest = new ActiveMQQueue(name); - destinations.put(name, dest); - return (ActiveMQDestination)dest; - } - } - - protected void setUp() throws Exception { - super.setUp(); - brokers = new HashMap(); - destinations = new HashMap(); - } - - protected void tearDown() throws Exception { - destroyAllBrokers(); - super.tearDown(); - } - - protected void destroyBroker(String brokerName) throws Exception { - BrokerItem brokerItem = brokers.remove(brokerName); - - if (brokerItem != null) { - brokerItem.destroy(); - } - } - - protected void destroyAllBrokers() throws Exception { - for (Iterator i = brokers.values().iterator(); i.hasNext();) { - BrokerItem brokerItem = i.next(); - brokerItem.destroy(); - } - brokers.clear(); - } - - // Class to group broker components together - public class BrokerItem { - public BrokerService broker; - public ActiveMQConnectionFactory factory; - public List connections; - public Map consumers; - public MessageIdList allMessages = new MessageIdList(); - public boolean persistent; - private IdGenerator id; - - public BrokerItem(BrokerService broker) throws Exception { - this.broker = broker; - - factory = new ActiveMQConnectionFactory(broker.getVmConnectorURI()); - factory.setConnectionIDPrefix(broker.getBrokerName()); - consumers = Collections.synchronizedMap(new HashMap()); - connections = Collections.synchronizedList(new ArrayList()); - allMessages.setVerbose(verbose); - id = new IdGenerator(broker.getBrokerName() + ":"); - } - - public Connection createConnection() throws Exception { - Connection conn = factory.createConnection(); - conn.setClientID(id.generateId()); - - connections.add(conn); - return conn; - } - - public MessageConsumer createConsumer(Destination dest) throws Exception { - return createConsumer(dest, null, null); - } - - public MessageConsumer createConsumer(Destination dest, String messageSelector) throws Exception { - return createConsumer(dest, null, messageSelector); - } - - public MessageConsumer createConsumer(Destination dest, CountDownLatch latch, String messageSelector) throws Exception { - Connection c = createConnection(); - c.start(); - Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); - return createConsumerWithSession(dest, s, latch, messageSelector); - } - - public MessageConsumer createConsumerWithSession(Destination dest, Session sess) throws Exception { - return createConsumerWithSession(dest, sess, null, null); - } - - public MessageConsumer createConsumerWithSession(Destination dest, Session sess, CountDownLatch latch, String messageSelector) throws Exception { - MessageConsumer client = sess.createConsumer(dest, messageSelector); - MessageIdList messageIdList = new MessageIdList(); - messageIdList.setCountDownLatch(latch); - messageIdList.setParent(allMessages); - client.setMessageListener(messageIdList); - consumers.put(client, messageIdList); - return client; - } - - public QueueBrowser createBrowser(Destination dest) throws Exception { - Connection c = createConnection(); - c.start(); - Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); - return s.createBrowser((Queue)dest); - } - - public MessageConsumer createDurableSubscriber(Topic dest, String name) throws Exception { - Connection c = createConnection(); - c.start(); - Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); - return createDurableSubscriber(dest, s, name); - } - - public MessageConsumer createDurableSubscriber(Topic dest, Session sess, String name) throws Exception { - MessageConsumer client = sess.createDurableSubscriber((Topic)dest, name); - MessageIdList messageIdList = new MessageIdList(); - messageIdList.setParent(allMessages); - client.setMessageListener(messageIdList); - consumers.put(client, messageIdList); - - return client; - } - - public MessageIdList getAllMessages() { - return allMessages; - } - - public MessageIdList getConsumerMessages(MessageConsumer consumer) { - return consumers.get(consumer); - } - - public MessageProducer createProducer(Destination dest) throws Exception { - Connection c = createConnection(); - c.start(); - Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); - return createProducer(dest, s); - } - - public MessageProducer createProducer(Destination dest, Session sess) throws Exception { - MessageProducer client = sess.createProducer(dest); - client.setDeliveryMode(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT); - return client; - } - - public void destroy() throws Exception { - while (!connections.isEmpty()) { - Connection c = connections.remove(0); - try { - c.close(); - } catch (ConnectionClosedException e) { - } catch (JMSException e) { - } + catch (ConnectionClosedException e) { } + catch (JMSException e) { + } + } - broker.stop(); - broker.waitUntilStopped(); - consumers.clear(); + broker.stop(); + broker.waitUntilStopped(); + consumers.clear(); - broker = null; - connections = null; - consumers = null; - factory = null; - } - } + broker = null; + connections = null; + consumers = null; + factory = null; + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsMultipleClientsTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsMultipleClientsTestSupport.java index 5c73a6e4e0..38dbcd1fed 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsMultipleClientsTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsMultipleClientsTestSupport.java @@ -55,279 +55,281 @@ import static org.junit.Assert.*; /** * Test case support used to test multiple message comsumers and message * producers connecting to a single broker. - * - * */ public class JmsMultipleClientsTestSupport { - @Rule - public TestName testName = new TestName(); + @Rule + public TestName testName = new TestName(); - protected static final Logger LOG = LoggerFactory.getLogger(JmsMultipleClientsTestSupport.class); + protected static final Logger LOG = LoggerFactory.getLogger(JmsMultipleClientsTestSupport.class); - protected Map consumers = new HashMap(); // Map of consumer with messages - // received - protected int consumerCount = 1; - protected int producerCount = 1; + protected Map consumers = new HashMap(); // Map of consumer with messages + // received + protected int consumerCount = 1; + protected int producerCount = 1; - protected int messageSize = 1024; + protected int messageSize = 1024; - protected boolean useConcurrentSend = true; - protected boolean autoFail = true; - protected boolean durable; - public boolean topic; - protected boolean persistent; + protected boolean useConcurrentSend = true; + protected boolean autoFail = true; + protected boolean durable; + public boolean topic; + protected boolean persistent; - protected BrokerService broker; - protected Destination destination; - protected List connections = Collections.synchronizedList(new ArrayList()); - protected MessageIdList allMessagesList = new MessageIdList(); + protected BrokerService broker; + protected Destination destination; + protected List connections = Collections.synchronizedList(new ArrayList()); + protected MessageIdList allMessagesList = new MessageIdList(); - protected void startProducers(Destination dest, int msgCount) throws Exception { - startProducers(createConnectionFactory(), dest, msgCount); - } + protected void startProducers(Destination dest, int msgCount) throws Exception { + startProducers(createConnectionFactory(), dest, msgCount); + } - protected void startProducers(final ConnectionFactory factory, final Destination dest, final int msgCount) throws Exception { - // Use concurrent send - if (useConcurrentSend) { - final AtomicInteger producerLock = new AtomicInteger(producerCount); + protected void startProducers(final ConnectionFactory factory, + final Destination dest, + final int msgCount) throws Exception { + // Use concurrent send + if (useConcurrentSend) { + final AtomicInteger producerLock = new AtomicInteger(producerCount); - for (int i = 0; i < producerCount; i++) { - Thread t = new Thread(new Runnable() { - public void run() { - try { - sendMessages(factory.createConnection(), dest, msgCount); - } catch (Exception e) { - e.printStackTrace(); - } + for (int i = 0; i < producerCount; i++) { + Thread t = new Thread(new Runnable() { + public void run() { + try { + sendMessages(factory.createConnection(), dest, msgCount); + } + catch (Exception e) { + e.printStackTrace(); + } - synchronized (producerLock) { - producerLock.decrementAndGet(); - producerLock.notifyAll(); - } - } - }); + synchronized (producerLock) { + producerLock.decrementAndGet(); + producerLock.notifyAll(); + } + } + }); - t.start(); + t.start(); + } + + // Wait for all producers to finish sending + synchronized (producerLock) { + while (producerLock.get() != 0) { + producerLock.wait(2000); } + } - // Wait for all producers to finish sending - synchronized (producerLock) { - while (producerLock.get() != 0) { - producerLock.wait(2000); - } - } + // Use serialized send + } + else { + for (int i = 0; i < producerCount; i++) { + sendMessages(factory.createConnection(), dest, msgCount); + } + } + } - // Use serialized send - } else { - for (int i = 0; i < producerCount; i++) { - sendMessages(factory.createConnection(), dest, msgCount); - } - } - } + protected void sendMessages(Connection connection, Destination destination, int count) throws Exception { + connections.add(connection); + connection.start(); - protected void sendMessages(Connection connection, Destination destination, int count) throws Exception { - connections.add(connection); - connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT); + for (int i = 0; i < count; i++) { + TextMessage msg = createTextMessage(session, "" + i); + producer.send(msg); + } - for (int i = 0; i < count; i++) { - TextMessage msg = createTextMessage(session, "" + i); - producer.send(msg); - } + producer.close(); + session.close(); + connection.close(); + } - producer.close(); - session.close(); - connection.close(); - } + protected TextMessage createTextMessage(Session session, String initText) throws Exception { + TextMessage msg = session.createTextMessage(); - protected TextMessage createTextMessage(Session session, String initText) throws Exception { - TextMessage msg = session.createTextMessage(); + // Pad message text + if (initText.length() < messageSize) { + char[] data = new char[messageSize - initText.length()]; + Arrays.fill(data, '*'); + String str = new String(data); + msg.setText(initText + str); - // Pad message text - if (initText.length() < messageSize) { - char[] data = new char[messageSize - initText.length()]; - Arrays.fill(data, '*'); - String str = new String(data); - msg.setText(initText + str); + // Do not pad message text + } + else { + msg.setText(initText); + } - // Do not pad message text - } else { - msg.setText(initText); - } + return msg; + } - return msg; - } + protected void startConsumers(Destination dest) throws Exception { + startConsumers(createConnectionFactory(), dest); + } - protected void startConsumers(Destination dest) throws Exception { - startConsumers(createConnectionFactory(), dest); - } + protected void startConsumers(ConnectionFactory factory, Destination dest) throws Exception { + MessageConsumer consumer; + for (int i = 0; i < consumerCount; i++) { + if (durable && topic) { + consumer = createDurableSubscriber(factory.createConnection(), dest, "consumer" + (i + 1)); + } + else { + consumer = createMessageConsumer(factory.createConnection(), dest); + } + MessageIdList list = new MessageIdList(); + list.setParent(allMessagesList); + consumer.setMessageListener(list); + consumers.put(consumer, list); + } + } - protected void startConsumers(ConnectionFactory factory, Destination dest) throws Exception { - MessageConsumer consumer; - for (int i = 0; i < consumerCount; i++) { - if (durable && topic) { - consumer = createDurableSubscriber(factory.createConnection(), dest, "consumer" + (i + 1)); - } else { - consumer = createMessageConsumer(factory.createConnection(), dest); - } - MessageIdList list = new MessageIdList(); - list.setParent(allMessagesList); - consumer.setMessageListener(list); - consumers.put(consumer, list); - } - } + protected MessageConsumer createMessageConsumer(Connection conn, Destination dest) throws Exception { + connections.add(conn); - protected MessageConsumer createMessageConsumer(Connection conn, Destination dest) throws Exception { - connections.add(conn); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + final MessageConsumer consumer = sess.createConsumer(dest); + conn.start(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageConsumer consumer = sess.createConsumer(dest); - conn.start(); + return consumer; + } - return consumer; - } + protected TopicSubscriber createDurableSubscriber(Connection conn, Destination dest, String name) throws Exception { + conn.setClientID(name); + connections.add(conn); + conn.start(); - protected TopicSubscriber createDurableSubscriber(Connection conn, Destination dest, String name) throws Exception { - conn.setClientID(name); - connections.add(conn); - conn.start(); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + final TopicSubscriber consumer = sess.createDurableSubscriber((javax.jms.Topic) dest, name); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - final TopicSubscriber consumer = sess.createDurableSubscriber((javax.jms.Topic)dest, name); + return consumer; + } - return consumer; - } + protected void waitForAllMessagesToBeReceived(int messageCount) throws Exception { + allMessagesList.waitForMessagesToArrive(messageCount); + } - protected void waitForAllMessagesToBeReceived(int messageCount) throws Exception { - allMessagesList.waitForMessagesToArrive(messageCount); - } + protected ActiveMQDestination createDestination() throws JMSException { + String name = "." + getClass().getName() + "." + getName(); + // ensure not inadvertently composite because of combos + name = name.replace(' ', '_'); + name = name.replace(',', '&'); + if (topic) { + destination = new ActiveMQTopic("Topic" + name); + return (ActiveMQDestination) destination; + } + else { + destination = new ActiveMQQueue("Queue" + name); + return (ActiveMQDestination) destination; + } + } - protected ActiveMQDestination createDestination() throws JMSException { - String name = "." + getClass().getName() + "." + getName(); - // ensure not inadvertently composite because of combos - name = name.replace(' ','_'); - name = name.replace(',','&'); - if (topic) { - destination = new ActiveMQTopic("Topic" + name); - return (ActiveMQDestination)destination; - } else { - destination = new ActiveMQQueue("Queue" + name); - return (ActiveMQDestination)destination; - } - } + protected ConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory("vm://localhost"); + } - protected ConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://localhost"); - } + protected BrokerService createBroker() throws Exception { + return BrokerFactory.createBroker(new URI("broker://()/localhost?persistent=false&useJmx=true")); + } - protected BrokerService createBroker() throws Exception { - return BrokerFactory.createBroker(new URI("broker://()/localhost?persistent=false&useJmx=true")); - } + @Before + public void setUp() throws Exception { + broker = createBroker(); + broker.start(); + } - @Before - public void setUp() throws Exception { - broker = createBroker(); - broker.start(); - } + @After + public void tearDown() throws Exception { + for (Iterator iter = connections.iterator(); iter.hasNext(); ) { + Connection conn = iter.next(); + try { + conn.close(); + } + catch (Throwable e) { + } + } + if (broker != null) { // FIXME remove + broker.stop(); + allMessagesList.flushMessages(); + consumers.clear(); + } + } - @After - public void tearDown() throws Exception { - for (Iterator iter = connections.iterator(); iter.hasNext();) { - Connection conn = iter.next(); - try { - conn.close(); - } catch (Throwable e) { - } - } - if (broker !=null ) { // FIXME remove - broker.stop(); - allMessagesList.flushMessages(); - consumers.clear(); - } - } + /* + * Some helpful assertions for multiple consumers. + */ + protected void assertConsumerReceivedAtLeastXMessages(MessageConsumer consumer, int msgCount) { + MessageIdList messageIdList = consumers.get(consumer); + messageIdList.assertAtLeastMessagesReceived(msgCount); + } - /* - * Some helpful assertions for multiple consumers. - */ - protected void assertConsumerReceivedAtLeastXMessages(MessageConsumer consumer, int msgCount) { - MessageIdList messageIdList = consumers.get(consumer); - messageIdList.assertAtLeastMessagesReceived(msgCount); - } + protected void assertConsumerReceivedAtMostXMessages(MessageConsumer consumer, int msgCount) { + MessageIdList messageIdList = consumers.get(consumer); + messageIdList.assertAtMostMessagesReceived(msgCount); + } - protected void assertConsumerReceivedAtMostXMessages(MessageConsumer consumer, int msgCount) { - MessageIdList messageIdList = consumers.get(consumer); - messageIdList.assertAtMostMessagesReceived(msgCount); - } + protected void assertConsumerReceivedXMessages(MessageConsumer consumer, int msgCount) { + MessageIdList messageIdList = consumers.get(consumer); + messageIdList.assertMessagesReceivedNoWait(msgCount); + } - protected void assertConsumerReceivedXMessages(MessageConsumer consumer, int msgCount) { - MessageIdList messageIdList = consumers.get(consumer); - messageIdList.assertMessagesReceivedNoWait(msgCount); - } + protected void assertEachConsumerReceivedAtLeastXMessages(int msgCount) { + for (Iterator i = consumers.keySet().iterator(); i.hasNext(); ) { + assertConsumerReceivedAtLeastXMessages(i.next(), msgCount); + } + } - protected void assertEachConsumerReceivedAtLeastXMessages(int msgCount) { - for (Iterator i = consumers.keySet().iterator(); i.hasNext();) { - assertConsumerReceivedAtLeastXMessages(i.next(), msgCount); - } - } + protected void assertEachConsumerReceivedAtMostXMessages(int msgCount) { + for (Iterator i = consumers.keySet().iterator(); i.hasNext(); ) { + assertConsumerReceivedAtMostXMessages(i.next(), msgCount); + } + } - protected void assertEachConsumerReceivedAtMostXMessages(int msgCount) { - for (Iterator i = consumers.keySet().iterator(); i.hasNext();) { - assertConsumerReceivedAtMostXMessages(i.next(), msgCount); - } - } + protected void assertEachConsumerReceivedXMessages(int msgCount) { + for (Iterator i = consumers.keySet().iterator(); i.hasNext(); ) { + assertConsumerReceivedXMessages(i.next(), msgCount); + } + } - protected void assertEachConsumerReceivedXMessages(int msgCount) { - for (Iterator i = consumers.keySet().iterator(); i.hasNext();) { - assertConsumerReceivedXMessages(i.next(), msgCount); - } - } + protected void assertTotalMessagesReceived(int msgCount) { + allMessagesList.assertMessagesReceivedNoWait(msgCount); - protected void assertTotalMessagesReceived(int msgCount) { - allMessagesList.assertMessagesReceivedNoWait(msgCount); + // now lets count the individual messages received + int totalMsg = 0; + for (Iterator i = consumers.keySet().iterator(); i.hasNext(); ) { + MessageIdList messageIdList = consumers.get(i.next()); + totalMsg += messageIdList.getMessageCount(); + } + assertEquals("Total of consumers message count", msgCount, totalMsg); + } - // now lets count the individual messages received - int totalMsg = 0; - for (Iterator i = consumers.keySet().iterator(); i.hasNext();) { - MessageIdList messageIdList = consumers.get(i.next()); - totalMsg += messageIdList.getMessageCount(); - } - assertEquals("Total of consumers message count", msgCount, totalMsg); - } + public String getName() { + return getName(false); + } + public String getName(boolean original) { + String currentTestName = testName.getMethodName(); + currentTestName = currentTestName.replace("[", ""); + currentTestName = currentTestName.replace("]", ""); + return currentTestName; + } - public String getName() { - return getName(false); - } + public void assertDestinationMemoryUsageGoesToZero() throws Exception { + assertEquals("destination memory is back to 0", 0, TestSupport.getDestination(broker, ActiveMQDestination.transform(destination)).getMemoryUsage().getPercentUsage()); + } - public String getName(boolean original) { - String currentTestName = testName.getMethodName(); - currentTestName = currentTestName.replace("[",""); - currentTestName = currentTestName.replace("]",""); - return currentTestName; - } - - public void assertDestinationMemoryUsageGoesToZero() throws Exception { - assertEquals("destination memory is back to 0", 0, - TestSupport.getDestination(broker, ActiveMQDestination.transform(destination)).getMemoryUsage().getPercentUsage()); - } - - - - /* - * This is copied from AutoFailTestSupport. We may want to move it to someplace where more - * tests can use it. - */ - public static void dumpAllThreads(String prefix) { - Map stacks = Thread.getAllStackTraces(); - for (Map.Entry stackEntry : stacks.entrySet()) { - System.err.println(prefix + " " + stackEntry.getKey()); - for(StackTraceElement element : stackEntry.getValue()) { - System.err.println(" " + element); - } - } - } + /* + * This is copied from AutoFailTestSupport. We may want to move it to someplace where more + * tests can use it. + */ + public static void dumpAllThreads(String prefix) { + Map stacks = Thread.getAllStackTraces(); + for (Map.Entry stackEntry : stacks.entrySet()) { + System.err.println(prefix + " " + stackEntry.getKey()); + for (StackTraceElement element : stackEntry.getValue()) { + System.err.println(" " + element); + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueBrowserTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueBrowserTest.java index c063e24fbf..059ec2cbc9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueBrowserTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueBrowserTest.java @@ -43,406 +43,401 @@ import org.slf4j.LoggerFactory; public class JmsQueueBrowserTest extends JmsTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(ActiveMQXAConnectionFactoryTest.class); - public boolean isUseCache = false; + private static final Logger LOG = LoggerFactory.getLogger(ActiveMQXAConnectionFactoryTest.class); + public boolean isUseCache = false; - public static Test suite() throws Exception { - return suite(JmsQueueBrowserTest.class); - } + public static Test suite() throws Exception { + return suite(JmsQueueBrowserTest.class); + } - /** - * Tests the queue browser. Browses the messages then the consumer tries to receive them. The messages should still - * be in the queue even when it was browsed. - * - * @throws Exception - */ - public void testReceiveBrowseReceive() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQQueue destination = new ActiveMQQueue("TEST"); - MessageProducer producer = session.createProducer(destination); - MessageConsumer consumer = session.createConsumer(destination); - connection.start(); + /** + * Tests the queue browser. Browses the messages then the consumer tries to receive them. The messages should still + * be in the queue even when it was browsed. + * + * @throws Exception + */ + public void testReceiveBrowseReceive() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQQueue destination = new ActiveMQQueue("TEST"); + MessageProducer producer = session.createProducer(destination); + MessageConsumer consumer = session.createConsumer(destination); + connection.start(); - Message[] outbound = new Message[]{session.createTextMessage("First Message"), - session.createTextMessage("Second Message"), - session.createTextMessage("Third Message")}; + Message[] outbound = new Message[]{session.createTextMessage("First Message"), session.createTextMessage("Second Message"), session.createTextMessage("Third Message")}; - // lets consume any outstanding messages from previous test runs - while (consumer.receive(1000) != null) { - } + // lets consume any outstanding messages from previous test runs + while (consumer.receive(1000) != null) { + } - producer.send(outbound[0]); - producer.send(outbound[1]); - producer.send(outbound[2]); + producer.send(outbound[0]); + producer.send(outbound[1]); + producer.send(outbound[2]); - // Get the first. - assertEquals(outbound[0], consumer.receive(1000)); - consumer.close(); + // Get the first. + assertEquals(outbound[0], consumer.receive(1000)); + consumer.close(); - QueueBrowser browser = session.createBrowser(destination); - Enumeration enumeration = browser.getEnumeration(); + QueueBrowser browser = session.createBrowser(destination); + Enumeration enumeration = browser.getEnumeration(); - // browse the second - assertTrue("should have received the second message", enumeration.hasMoreElements()); - assertEquals(outbound[1], enumeration.nextElement()); + // browse the second + assertTrue("should have received the second message", enumeration.hasMoreElements()); + assertEquals(outbound[1], enumeration.nextElement()); - // browse the third. - assertTrue("Should have received the third message", enumeration.hasMoreElements()); - assertEquals(outbound[2], enumeration.nextElement()); + // browse the third. + assertTrue("Should have received the third message", enumeration.hasMoreElements()); + assertEquals(outbound[2], enumeration.nextElement()); - // There should be no more. - boolean tooMany = false; - while (enumeration.hasMoreElements()) { - LOG.info("Got extra message: " + ((TextMessage) enumeration.nextElement()).getText()); - tooMany = true; - } - assertFalse(tooMany); - browser.close(); + // There should be no more. + boolean tooMany = false; + while (enumeration.hasMoreElements()) { + LOG.info("Got extra message: " + ((TextMessage) enumeration.nextElement()).getText()); + tooMany = true; + } + assertFalse(tooMany); + browser.close(); - // Re-open the consumer. - consumer = session.createConsumer(destination); - // Receive the second. - assertEquals(outbound[1], consumer.receive(1000)); - // Receive the third. - assertEquals(outbound[2], consumer.receive(1000)); - consumer.close(); - } + // Re-open the consumer. + consumer = session.createConsumer(destination); + // Receive the second. + assertEquals(outbound[1], consumer.receive(1000)); + // Receive the third. + assertEquals(outbound[2], consumer.receive(1000)); + consumer.close(); + } - public void initCombosForTestBatchSendBrowseReceive() { - addCombinationValues("isUseCache", new Boolean[]{Boolean.TRUE, Boolean.FALSE}); - } + public void initCombosForTestBatchSendBrowseReceive() { + addCombinationValues("isUseCache", new Boolean[]{Boolean.TRUE, Boolean.FALSE}); + } - public void testBatchSendBrowseReceive() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQQueue destination = new ActiveMQQueue("TEST"); - MessageProducer producer = session.createProducer(destination); - MessageConsumer consumer = session.createConsumer(destination); - connection.start(); + public void testBatchSendBrowseReceive() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQQueue destination = new ActiveMQQueue("TEST"); + MessageProducer producer = session.createProducer(destination); + MessageConsumer consumer = session.createConsumer(destination); + connection.start(); - TextMessage[] outbound = new TextMessage[10]; - for (int i=0; i<10; i++) { - outbound[i] = session.createTextMessage( i + " Message"); - }; + TextMessage[] outbound = new TextMessage[10]; + for (int i = 0; i < 10; i++) { + outbound[i] = session.createTextMessage(i + " Message"); + } + ; - // lets consume any outstanding messages from previous test runs - while (consumer.receive(1000) != null) { - } - consumer.close(); + // lets consume any outstanding messages from previous test runs + while (consumer.receive(1000) != null) { + } + consumer.close(); - for (int i=0;i enumeration = browser.getEnumeration(); + QueueBrowser browser = session.createBrowser(destination); + Enumeration enumeration = browser.getEnumeration(); - for (int i=0; i 0); - - assertEquals("Queue size", outbound.length, proxy.getQueueSize()); - assertEquals("Queue size", outbound.length, compdatalist.length); - assertEquals("Queue size", outbound.length, table.size()); - - - LOG.info("Send another 10"); - for (int i=0;i 0); - - assertEquals("Queue size", outbound.length*2, proxy.getQueueSize()); - assertEquals("Queue size", outbound.length*2, compdatalist.length); - assertEquals("Queue size", outbound.length * 2, table.size()); - - consumer = session.createConsumer(destination); - for (int i=0; i enumeration = browser.getEnumeration(); - - // browse the first message - assertTrue("should have received the first message", enumeration.hasMoreElements()); - assertEquals(outbound[0], enumeration.nextElement()); - - // Receive the first message. - assertEquals(outbound[0], consumer.receive(1000)); - consumer.close(); - browser.close(); - producer.close(); - } - - public void testLargeNumberOfMessages() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQQueue destination = new ActiveMQQueue("TEST"); - connection.start(); - - MessageProducer producer = session.createProducer(destination); - - int numberOfMessages = 4096; - - for (int i = 0; i < numberOfMessages; i++) { - producer.send(session.createTextMessage("Message: " + i)); - } - - QueueBrowser browser = session.createBrowser(destination); - Enumeration enumeration = browser.getEnumeration(); - - assertTrue(enumeration.hasMoreElements()); - - int numberBrowsed = 0; - - while (enumeration.hasMoreElements()) { - Message browsed = (Message) enumeration.nextElement(); - - if (LOG.isDebugEnabled()) { - LOG.debug("Browsed Message [{}]", browsed.getJMSMessageID()); - } - - numberBrowsed++; - } - - System.out.println("Number browsed: " + numberBrowsed); - assertEquals(numberOfMessages, numberBrowsed); - browser.close(); - producer.close(); - } - - public void testQueueBrowserWith2Consumers() throws Exception { - final int numMessages = 1000; - connection.setAlwaysSyncSend(false); - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - ActiveMQQueue destination = new ActiveMQQueue("TEST"); - ActiveMQQueue destinationPrefetch10 = new ActiveMQQueue("TEST?jms.prefetchSize=10"); - ActiveMQQueue destinationPrefetch1 = new ActiveMQQueue("TEST?jms.prefetchsize=1"); - connection.start(); - - ActiveMQConnection connection2 = (ActiveMQConnection)factory.createConnection(userName, password); - connection2.start(); - connections.add(connection2); - Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageProducer producer = session.createProducer(destination); - MessageConsumer consumer = session.createConsumer(destinationPrefetch10); - - // lets consume any outstanding messages from previous test runs - while (consumer.receive(1000) != null) { - } - - for (int i=0; i browserView = browser.getEnumeration(); - - List messages = new ArrayList(); - for (int i = 0; i < numMessages; i++) { - Message m1 = consumer.receive(5000); - assertNotNull("m1 is null for index: " + i, m1); - messages.add(m1); - } - - int i = 0; - for (; i < numMessages && browserView.hasMoreElements(); i++) { - Message m1 = messages.get(i); - Message m2 = browserView.nextElement(); - assertNotNull("m2 is null for index: " + i, m2); - assertEquals(m1.getJMSMessageID(), m2.getJMSMessageID()); - } - - // currently browse max page size is ignored for a queue browser consumer - // only guarantee is a page size - but a snapshot of pagedinpending is - // used so it is most likely more - assertTrue("got at least our expected minimum in the browser: ", i > BaseDestination.MAX_PAGE_SIZE); - - assertFalse("nothing left in the browser", browserView.hasMoreElements()); - assertNull("consumer finished", consumer.receiveNoWait()); - } - - public void testBrowseClose() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQQueue destination = new ActiveMQQueue("TEST"); - - connection.start(); - - TextMessage[] outbound = new TextMessage[]{session.createTextMessage("First Message"), - session.createTextMessage("Second Message"), - session.createTextMessage("Third Message")}; - - // create consumer - MessageConsumer consumer = session.createConsumer(destination); - // lets consume any outstanding messages from previous test runs - while (consumer.receive(1000) != null) { - } - - MessageProducer producer = session.createProducer(destination); - producer.send(outbound[0]); - producer.send(outbound[1]); - producer.send(outbound[2]); - - // create browser first - QueueBrowser browser = session.createBrowser(destination); - Enumeration enumeration = browser.getEnumeration(); - - // browse some messages - assertEquals(outbound[0], enumeration.nextElement()); - assertEquals(outbound[1], enumeration.nextElement()); - //assertEquals(outbound[2], (Message) enumeration.nextElement()); - - browser.close(); - - // Receive the first message. - TextMessage msg = (TextMessage)consumer.receive(1000); - assertEquals("Expected " + outbound[0].getText() + " but received " + msg.getText(), outbound[0], msg); - msg = (TextMessage)consumer.receive(1000); - assertEquals("Expected " + outbound[1].getText() + " but received " + msg.getText(), outbound[1], msg); - msg = (TextMessage)consumer.receive(1000); - assertEquals("Expected " + outbound[2].getText() + " but received " + msg.getText(), outbound[2], msg); - - consumer.close(); - producer.close(); - } - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService brokerService = super.createBroker(); - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policyEntry = new PolicyEntry(); - policyEntry.setUseCache(isUseCache); - policyEntry.setMaxBrowsePageSize(4096); - policyMap.setDefaultEntry(policyEntry); - brokerService.setDestinationPolicy(policyMap); - return brokerService; - } + assertEquals("j=" + j + ", i=" + i, outbound[i].getText(), ((TextMessage) enumeration.nextElement()).getText()); + } + } + browser.close(); + + consumer = session.createConsumer(destination); + for (int i = 0; i < outbound.length * 2; i++) { + assertNotNull("Got message: " + i, consumer.receive(2000)); + } + consumer.close(); + } + + public void initCombosForTestBatchSendJmxBrowseReceive() { + addCombinationValues("isUseCache", new Boolean[]{Boolean.TRUE, Boolean.FALSE}); + } + + public void testBatchSendJmxBrowseReceive() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQQueue destination = new ActiveMQQueue("TEST"); + MessageProducer producer = session.createProducer(destination); + MessageConsumer consumer = session.createConsumer(destination); + connection.start(); + + TextMessage[] outbound = new TextMessage[10]; + for (int i = 0; i < 10; i++) { + outbound[i] = session.createTextMessage(i + " Message"); + } + ; + + // lets consume any outstanding messages from previous test runs + while (consumer.receive(1000) != null) { + } + consumer.close(); + + for (int i = 0; i < outbound.length; i++) { + producer.send(outbound[i]); + } + + ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=TEST"); + + LOG.info("Create QueueView MBean..."); + QueueViewMBean proxy = (QueueViewMBean) broker.getManagementContext().newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); + + long concount = proxy.getConsumerCount(); + LOG.info("Consumer Count :" + concount); + long messcount = proxy.getQueueSize(); + LOG.info("current number of messages in the queue :" + messcount); + + // lets browse + CompositeData[] compdatalist = proxy.browse(); + if (compdatalist.length == 0) { + fail("There is no message in the queue:"); + } + String[] messageIDs = new String[compdatalist.length]; + + for (int i = 0; i < compdatalist.length; i++) { + CompositeData cdata = compdatalist[i]; + + if (i == 0) { + LOG.info("Columns: " + cdata.getCompositeType().keySet()); + } + messageIDs[i] = (String) cdata.get("JMSMessageID"); + LOG.info("message " + i + " : " + cdata.values()); + } + + TabularData table = proxy.browseAsTable(); + LOG.info("Found tabular data: " + table); + assertTrue("Table should not be empty!", table.size() > 0); + + assertEquals("Queue size", outbound.length, proxy.getQueueSize()); + assertEquals("Queue size", outbound.length, compdatalist.length); + assertEquals("Queue size", outbound.length, table.size()); + + LOG.info("Send another 10"); + for (int i = 0; i < outbound.length; i++) { + producer.send(outbound[i]); + } + + LOG.info("Browse again"); + + messcount = proxy.getQueueSize(); + LOG.info("current number of messages in the queue :" + messcount); + + compdatalist = proxy.browse(); + if (compdatalist.length == 0) { + fail("There is no message in the queue:"); + } + messageIDs = new String[compdatalist.length]; + + for (int i = 0; i < compdatalist.length; i++) { + CompositeData cdata = compdatalist[i]; + + if (i == 0) { + LOG.info("Columns: " + cdata.getCompositeType().keySet()); + } + messageIDs[i] = (String) cdata.get("JMSMessageID"); + LOG.info("message " + i + " : " + cdata.values()); + } + + table = proxy.browseAsTable(); + LOG.info("Found tabular data: " + table); + assertTrue("Table should not be empty!", table.size() > 0); + + assertEquals("Queue size", outbound.length * 2, proxy.getQueueSize()); + assertEquals("Queue size", outbound.length * 2, compdatalist.length); + assertEquals("Queue size", outbound.length * 2, table.size()); + + consumer = session.createConsumer(destination); + for (int i = 0; i < outbound.length * 2; i++) { + assertNotNull("Got message: " + i, consumer.receive(2000)); + } + consumer.close(); + } + + public void testBrowseReceive() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQQueue destination = new ActiveMQQueue("TEST"); + + connection.start(); + + // create consumer + MessageConsumer consumer = session.createConsumer(destination); + // lets consume any outstanding messages from previous test runs + while (consumer.receive(1000) != null) { + } + + Message[] outbound = new Message[]{session.createTextMessage("First Message"), session.createTextMessage("Second Message"), session.createTextMessage("Third Message")}; + + MessageProducer producer = session.createProducer(destination); + producer.send(outbound[0]); + + // create browser first + QueueBrowser browser = session.createBrowser(destination); + Enumeration enumeration = browser.getEnumeration(); + + // browse the first message + assertTrue("should have received the first message", enumeration.hasMoreElements()); + assertEquals(outbound[0], enumeration.nextElement()); + + // Receive the first message. + assertEquals(outbound[0], consumer.receive(1000)); + consumer.close(); + browser.close(); + producer.close(); + } + + public void testLargeNumberOfMessages() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQQueue destination = new ActiveMQQueue("TEST"); + connection.start(); + + MessageProducer producer = session.createProducer(destination); + + int numberOfMessages = 4096; + + for (int i = 0; i < numberOfMessages; i++) { + producer.send(session.createTextMessage("Message: " + i)); + } + + QueueBrowser browser = session.createBrowser(destination); + Enumeration enumeration = browser.getEnumeration(); + + assertTrue(enumeration.hasMoreElements()); + + int numberBrowsed = 0; + + while (enumeration.hasMoreElements()) { + Message browsed = (Message) enumeration.nextElement(); + + if (LOG.isDebugEnabled()) { + LOG.debug("Browsed Message [{}]", browsed.getJMSMessageID()); + } + + numberBrowsed++; + } + + System.out.println("Number browsed: " + numberBrowsed); + assertEquals(numberOfMessages, numberBrowsed); + browser.close(); + producer.close(); + } + + public void testQueueBrowserWith2Consumers() throws Exception { + final int numMessages = 1000; + connection.setAlwaysSyncSend(false); + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + ActiveMQQueue destination = new ActiveMQQueue("TEST"); + ActiveMQQueue destinationPrefetch10 = new ActiveMQQueue("TEST?jms.prefetchSize=10"); + ActiveMQQueue destinationPrefetch1 = new ActiveMQQueue("TEST?jms.prefetchsize=1"); + connection.start(); + + ActiveMQConnection connection2 = (ActiveMQConnection) factory.createConnection(userName, password); + connection2.start(); + connections.add(connection2); + Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE); + + MessageProducer producer = session.createProducer(destination); + MessageConsumer consumer = session.createConsumer(destinationPrefetch10); + + // lets consume any outstanding messages from previous test runs + while (consumer.receive(1000) != null) { + } + + for (int i = 0; i < numMessages; i++) { + TextMessage message = session.createTextMessage("Message: " + i); + producer.send(message); + } + + QueueBrowser browser = session2.createBrowser(destinationPrefetch1); + @SuppressWarnings("unchecked") + Enumeration browserView = browser.getEnumeration(); + + List messages = new ArrayList(); + for (int i = 0; i < numMessages; i++) { + Message m1 = consumer.receive(5000); + assertNotNull("m1 is null for index: " + i, m1); + messages.add(m1); + } + + int i = 0; + for (; i < numMessages && browserView.hasMoreElements(); i++) { + Message m1 = messages.get(i); + Message m2 = browserView.nextElement(); + assertNotNull("m2 is null for index: " + i, m2); + assertEquals(m1.getJMSMessageID(), m2.getJMSMessageID()); + } + + // currently browse max page size is ignored for a queue browser consumer + // only guarantee is a page size - but a snapshot of pagedinpending is + // used so it is most likely more + assertTrue("got at least our expected minimum in the browser: ", i > BaseDestination.MAX_PAGE_SIZE); + + assertFalse("nothing left in the browser", browserView.hasMoreElements()); + assertNull("consumer finished", consumer.receiveNoWait()); + } + + public void testBrowseClose() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQQueue destination = new ActiveMQQueue("TEST"); + + connection.start(); + + TextMessage[] outbound = new TextMessage[]{session.createTextMessage("First Message"), session.createTextMessage("Second Message"), session.createTextMessage("Third Message")}; + + // create consumer + MessageConsumer consumer = session.createConsumer(destination); + // lets consume any outstanding messages from previous test runs + while (consumer.receive(1000) != null) { + } + + MessageProducer producer = session.createProducer(destination); + producer.send(outbound[0]); + producer.send(outbound[1]); + producer.send(outbound[2]); + + // create browser first + QueueBrowser browser = session.createBrowser(destination); + Enumeration enumeration = browser.getEnumeration(); + + // browse some messages + assertEquals(outbound[0], enumeration.nextElement()); + assertEquals(outbound[1], enumeration.nextElement()); + //assertEquals(outbound[2], (Message) enumeration.nextElement()); + + browser.close(); + + // Receive the first message. + TextMessage msg = (TextMessage) consumer.receive(1000); + assertEquals("Expected " + outbound[0].getText() + " but received " + msg.getText(), outbound[0], msg); + msg = (TextMessage) consumer.receive(1000); + assertEquals("Expected " + outbound[1].getText() + " but received " + msg.getText(), outbound[1], msg); + msg = (TextMessage) consumer.receive(1000); + assertEquals("Expected " + outbound[2].getText() + " but received " + msg.getText(), outbound[2], msg); + + consumer.close(); + producer.close(); + } + + @Override + protected BrokerService createBroker() throws Exception { + BrokerService brokerService = super.createBroker(); + PolicyMap policyMap = new PolicyMap(); + PolicyEntry policyEntry = new PolicyEntry(); + policyEntry.setUseCache(isUseCache); + policyEntry.setMaxBrowsePageSize(4096); + policyMap.setDefaultEntry(policyEntry); + brokerService.setDestinationPolicy(policyMap); + return brokerService; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueCompositeSendReceiveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueCompositeSendReceiveTest.java index d7f5ea3deb..79485cd056 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueCompositeSendReceiveTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueCompositeSendReceiveTest.java @@ -30,87 +30,87 @@ import org.apache.activemq.artemis.core.client.impl.ServerLocatorImpl; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.test.JmsTopicSendReceiveTest; - /** * */ public class JmsQueueCompositeSendReceiveTest extends JmsTopicSendReceiveTest { - private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory - .getLog(JmsQueueCompositeSendReceiveTest.class); - /** - * Sets a test to have a queue destination and non-persistent delivery mode. - * - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception { - topic = false; - deliveryMode = DeliveryMode.NON_PERSISTENT; - super.setUp(); - } + private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(JmsQueueCompositeSendReceiveTest.class); - /** - * Returns the consumer subject. - * - * @return String - consumer subject - * @see org.apache.activemq.test.TestSupport#getConsumerSubject() - */ - protected String getConsumerSubject() { - return "FOO.BAR.HUMBUG"; - } + /** + * Sets a test to have a queue destination and non-persistent delivery mode. + * + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + topic = false; + deliveryMode = DeliveryMode.NON_PERSISTENT; + super.setUp(); + } - /** - * Returns the producer subject. - * - * @return String - producer subject - * @see org.apache.activemq.test.TestSupport#getProducerSubject() - */ - protected String getProducerSubject() { - return "FOO.BAR.HUMBUG,FOO.BAR.HUMBUG2"; - } + /** + * Returns the consumer subject. + * + * @return String - consumer subject + * @see org.apache.activemq.test.TestSupport#getConsumerSubject() + */ + protected String getConsumerSubject() { + return "FOO.BAR.HUMBUG"; + } - /** - * Test if all the messages sent are being received. - * - * @throws Exception - */ - public void testSendReceive() throws Exception { - super.testSendReceive(); - messages.clear(); - Destination consumerDestination = consumeSession.createQueue("FOO.BAR.HUMBUG2"); - LOG.info("Created consumer destination: " + consumerDestination + " of type: " + consumerDestination.getClass()); - MessageConsumer consumer = null; - if (durable) { - LOG.info("Creating durable consumer"); - consumer = consumeSession.createDurableSubscriber((Topic) consumerDestination, getName()); - } else { - consumer = consumeSession.createConsumer(consumerDestination); - } - consumer.setMessageListener(this); + /** + * Returns the producer subject. + * + * @return String - producer subject + * @see org.apache.activemq.test.TestSupport#getProducerSubject() + */ + protected String getProducerSubject() { + return "FOO.BAR.HUMBUG,FOO.BAR.HUMBUG2"; + } - assertMessagesAreReceived(); - LOG.info("" + data.length + " messages(s) received, closing down connections"); - } + /** + * Test if all the messages sent are being received. + * + * @throws Exception + */ + public void testSendReceive() throws Exception { + super.testSendReceive(); + messages.clear(); + Destination consumerDestination = consumeSession.createQueue("FOO.BAR.HUMBUG2"); + LOG.info("Created consumer destination: " + consumerDestination + " of type: " + consumerDestination.getClass()); + MessageConsumer consumer = null; + if (durable) { + LOG.info("Creating durable consumer"); + consumer = consumeSession.createDurableSubscriber((Topic) consumerDestination, getName()); + } + else { + consumer = consumeSession.createConsumer(consumerDestination); + } + consumer.setMessageListener(this); - public void testDuplicate() throws Exception { - ActiveMQDestination queue = (ActiveMQDestination)session.createQueue("TEST,TEST"); - for (int i = 0; i < data.length; i++) { - Message message = createMessage(i); - configureMessage(message); - if (verbose) { - LOG.info("About to send a message: " + message + " with text: " + data[i]); - } - producer.send(queue, message); - } + assertMessagesAreReceived(); + LOG.info("" + data.length + " messages(s) received, closing down connections"); + } - Thread.sleep(200); // wait for messages to be queue; + public void testDuplicate() throws Exception { + ActiveMQDestination queue = (ActiveMQDestination) session.createQueue("TEST,TEST"); + for (int i = 0; i < data.length; i++) { + Message message = createMessage(i); + configureMessage(message); + if (verbose) { + LOG.info("About to send a message: " + message + " with text: " + data[i]); + } + producer.send(queue, message); + } - try (ServerLocator locator = ServerLocatorImpl.newLocator("tcp://localhost:61616"); - ClientSessionFactory factory = locator.createSessionFactory(); - ClientSession session = factory.createSession()) { - ClientSession.QueueQuery query = session.queueQuery(new SimpleString("jms.queue.TEST")); - assertNotNull(query); - assertEquals(data.length, query.getMessageCount()); - } - } + Thread.sleep(200); // wait for messages to be queue; + + try (ServerLocator locator = ServerLocatorImpl.newLocator("tcp://localhost:61616"); + ClientSessionFactory factory = locator.createSessionFactory(); + ClientSession session = factory.createSession()) { + ClientSession.QueueQuery query = session.queueQuery(new SimpleString("jms.queue.TEST")); + assertNotNull(query); + assertEquals(data.length, query.getMessageCount()); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueRequestReplyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueRequestReplyTest.java index 9282c0ce01..ed847313f7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueRequestReplyTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueRequestReplyTest.java @@ -17,17 +17,17 @@ package org.apache.activemq; /** - * + * */ public class JmsQueueRequestReplyTest extends JmsTopicRequestReplyTest { - /** - * Set up the test with a queue. - * - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception { - topic = false; - super.setUp(); - } + /** + * Set up the test with a queue. + * + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + topic = false; + super.setUp(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueSelectorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueSelectorTest.java index 449edda5a5..93169f5b1e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueSelectorTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueSelectorTest.java @@ -18,11 +18,12 @@ package org.apache.activemq; /** - * + * */ public class JmsQueueSelectorTest extends JmsTopicSelectorTest { - public void setUp() throws Exception { - topic = false; - super.setUp(); - } + + public void setUp() throws Exception { + topic = false; + super.setUp(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueSendReceiveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueSendReceiveTest.java index 73e3e2474f..3a8c23c22c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueSendReceiveTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueSendReceiveTest.java @@ -19,17 +19,17 @@ package org.apache.activemq; import org.apache.activemq.test.JmsTopicSendReceiveTest; /** - * + * */ public class JmsQueueSendReceiveTest extends JmsTopicSendReceiveTest { - /** - * Set up the test with a queue. - * - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception { - topic = false; - super.setUp(); - } + /** + * Set up the test with a queue. + * + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + topic = false; + super.setUp(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueSendReceiveTwoConnectionsStartBeforeBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueSendReceiveTwoConnectionsStartBeforeBrokerTest.java index 367aaeb231..b717607289 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueSendReceiveTwoConnectionsStartBeforeBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueSendReceiveTwoConnectionsStartBeforeBrokerTest.java @@ -24,63 +24,66 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class JmsQueueSendReceiveTwoConnectionsStartBeforeBrokerTest extends JmsQueueSendReceiveTwoConnectionsTest { - private static final Logger LOG = LoggerFactory.getLogger(JmsQueueSendReceiveTwoConnectionsStartBeforeBrokerTest.class); - private Queue errors = new ConcurrentLinkedQueue(); - private int delayBeforeStartingBroker = 1000; - private BrokerService broker; + private static final Logger LOG = LoggerFactory.getLogger(JmsQueueSendReceiveTwoConnectionsStartBeforeBrokerTest.class); - public void startBroker() { - // Initialize the broker - LOG.info("Lets wait: " + delayBeforeStartingBroker + " millis before creating the broker"); - try { - Thread.sleep(delayBeforeStartingBroker); - } catch (InterruptedException e) { - e.printStackTrace(); - } + private Queue errors = new ConcurrentLinkedQueue(); + private int delayBeforeStartingBroker = 1000; + private BrokerService broker; - LOG.info("Now starting the broker"); - try { - broker = new BrokerService(); - broker.setPersistent(false); - broker.addConnector("tcp://localhost:61616"); - broker.start(); - } catch (Exception e) { - LOG.info("Caught: " + e); - errors.add(e); - } - } + public void startBroker() { + // Initialize the broker + LOG.info("Lets wait: " + delayBeforeStartingBroker + " millis before creating the broker"); + try { + Thread.sleep(delayBeforeStartingBroker); + } + catch (InterruptedException e) { + e.printStackTrace(); + } - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("failover:(tcp://localhost:61616)?maxReconnectAttempts=10&useExponentialBackOff=false&initialReconnectDelay=200"); - } + LOG.info("Now starting the broker"); + try { + broker = new BrokerService(); + broker.setPersistent(false); + broker.addConnector("tcp://localhost:61616"); + broker.start(); + } + catch (Exception e) { + LOG.info("Caught: " + e); + errors.add(e); + } + } - protected void setUp() throws Exception { - setAutoFail(true); - // now lets asynchronously start a broker - Thread thread = new Thread() { - public void run() { - startBroker(); - } - }; - thread.start(); + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory("failover:(tcp://localhost:61616)?maxReconnectAttempts=10&useExponentialBackOff=false&initialReconnectDelay=200"); + } - super.setUp(); - } + protected void setUp() throws Exception { + setAutoFail(true); + // now lets asynchronously start a broker + Thread thread = new Thread() { + public void run() { + startBroker(); + } + }; + thread.start(); - protected void tearDown() throws Exception { - super.tearDown(); + super.setUp(); + } - if (broker != null) { - broker.stop(); - } - if (!errors.isEmpty()) { - Exception e = errors.remove(); - throw e; - } - } + protected void tearDown() throws Exception { + super.tearDown(); + + if (broker != null) { + broker.stop(); + } + if (!errors.isEmpty()) { + Exception e = errors.remove(); + throw e; + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueSendReceiveTwoConnectionsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueSendReceiveTwoConnectionsTest.java index f29cc09e6c..01eda1dffd 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueSendReceiveTwoConnectionsTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueSendReceiveTwoConnectionsTest.java @@ -23,14 +23,14 @@ import org.apache.activemq.test.JmsTopicSendReceiveWithTwoConnectionsTest; */ public class JmsQueueSendReceiveTwoConnectionsTest extends JmsTopicSendReceiveWithTwoConnectionsTest { - /** - * Set up the test with a queue and using two connections. - * - * @see junit.framework.TestCase#setUp() - */ - @Override - protected void setUp() throws Exception { - topic = false; - super.setUp(); - } + /** + * Set up the test with a queue and using two connections. + * + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + topic = false; + super.setUp(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueSendReceiveUsingTwoSessionsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueSendReceiveUsingTwoSessionsTest.java index cb793d0c3a..de1c17aa2e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueSendReceiveUsingTwoSessionsTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueSendReceiveUsingTwoSessionsTest.java @@ -17,17 +17,17 @@ package org.apache.activemq; /** - * + * */ public class JmsQueueSendReceiveUsingTwoSessionsTest extends JmsQueueSendReceiveTest { - /** - * Set up the test using two sessions. - * - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception { - useSeparateSession = true; - super.setUp(); - } + /** + * Set up the test using two sessions. + * + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + useSeparateSession = true; + super.setUp(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueTopicCompositeSendReceiveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueTopicCompositeSendReceiveTest.java index d92696e8db..fe1d53303e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueTopicCompositeSendReceiveTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueTopicCompositeSendReceiveTest.java @@ -23,66 +23,66 @@ import javax.jms.Topic; import org.apache.activemq.test.JmsTopicSendReceiveTest; - /** - * + * */ public class JmsQueueTopicCompositeSendReceiveTest extends JmsTopicSendReceiveTest { - private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory - .getLog(JmsQueueTopicCompositeSendReceiveTest.class); - Destination consumerDestination2; - MessageConsumer consumer2; - /** - * Sets a test to have a queue destination and non-persistent delivery mode. - * - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception { - deliveryMode = DeliveryMode.NON_PERSISTENT; - topic = false; - super.setUp(); - consumerDestination2 = consumeSession.createTopic("FOO.BAR.HUMBUG2"); - LOG.info("Created consumer destination: " + consumerDestination2 + " of type: " + consumerDestination2.getClass()); - if (durable) { - LOG.info("Creating durable consumer"); - consumer2 = consumeSession.createDurableSubscriber((Topic) consumerDestination2, getName()); - } else { - consumer2 = consumeSession.createConsumer(consumerDestination2); - } + private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(JmsQueueTopicCompositeSendReceiveTest.class); + Destination consumerDestination2; + MessageConsumer consumer2; - } + /** + * Sets a test to have a queue destination and non-persistent delivery mode. + * + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + deliveryMode = DeliveryMode.NON_PERSISTENT; + topic = false; + super.setUp(); + consumerDestination2 = consumeSession.createTopic("FOO.BAR.HUMBUG2"); + LOG.info("Created consumer destination: " + consumerDestination2 + " of type: " + consumerDestination2.getClass()); + if (durable) { + LOG.info("Creating durable consumer"); + consumer2 = consumeSession.createDurableSubscriber((Topic) consumerDestination2, getName()); + } + else { + consumer2 = consumeSession.createConsumer(consumerDestination2); + } - /** - * Returns the consumer subject. - * - * @return String - consumer subject - * @see org.apache.activemq.test.TestSupport#getConsumerSubject() - */ - protected String getConsumerSubject() { - return "FOO.BAR.HUMBUG"; - } + } - /** - * Returns the producer subject. - * - * @return String - producer subject - * @see org.apache.activemq.test.TestSupport#getProducerSubject() - */ - protected String getProducerSubject() { - return "queue://FOO.BAR.HUMBUG,topic://FOO.BAR.HUMBUG2"; - } + /** + * Returns the consumer subject. + * + * @return String - consumer subject + * @see org.apache.activemq.test.TestSupport#getConsumerSubject() + */ + protected String getConsumerSubject() { + return "FOO.BAR.HUMBUG"; + } - /** - * Test if all the messages sent are being received. - * - * @throws Exception - */ - public void testSendReceive() throws Exception { - super.testSendReceive(); - messages.clear(); - consumer2.setMessageListener(this); - assertMessagesAreReceived(); - LOG.info("" + data.length + " messages(s) received, closing down connections"); - } + /** + * Returns the producer subject. + * + * @return String - producer subject + * @see org.apache.activemq.test.TestSupport#getProducerSubject() + */ + protected String getProducerSubject() { + return "queue://FOO.BAR.HUMBUG,topic://FOO.BAR.HUMBUG2"; + } + + /** + * Test if all the messages sent are being received. + * + * @throws Exception + */ + public void testSendReceive() throws Exception { + super.testSendReceive(); + messages.clear(); + consumer2.setMessageListener(this); + assertMessagesAreReceived(); + LOG.info("" + data.length + " messages(s) received, closing down connections"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueWildcardSendReceiveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueWildcardSendReceiveTest.java index b689664ac0..96ae1c7249 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueWildcardSendReceiveTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsQueueWildcardSendReceiveTest.java @@ -29,146 +29,146 @@ import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.test.JmsTopicSendReceiveTest; /** - * + * */ public class JmsQueueWildcardSendReceiveTest extends JmsTopicSendReceiveTest { - private String destination1String = "TEST.ONE.ONE"; - private String destination2String = "TEST.ONE.ONE.ONE"; - private String destination3String = "TEST.ONE.TWO"; - private String destination4String = "TEST.TWO.ONE"; + private String destination1String = "TEST.ONE.ONE"; + private String destination2String = "TEST.ONE.ONE.ONE"; + private String destination3String = "TEST.ONE.TWO"; + private String destination4String = "TEST.TWO.ONE"; - /** - * Sets a test to have a queue destination and non-persistent delivery mode. - * - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception { - topic = false; - deliveryMode = DeliveryMode.NON_PERSISTENT; - super.setUp(); - } + /** + * Sets a test to have a queue destination and non-persistent delivery mode. + * + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + topic = false; + deliveryMode = DeliveryMode.NON_PERSISTENT; + super.setUp(); + } - /** - * Returns the consumer subject. - * - * @return String - consumer subject - * @see org.apache.activemq.test.TestSupport#getConsumerSubject() - */ - protected String getConsumerSubject() { - return "FOO.>"; - } + /** + * Returns the consumer subject. + * + * @return String - consumer subject + * @see org.apache.activemq.test.TestSupport#getConsumerSubject() + */ + protected String getConsumerSubject() { + return "FOO.>"; + } - /** - * Returns the producer subject. - * - * @return String - producer subject - * @see org.apache.activemq.test.TestSupport#getProducerSubject() - */ - protected String getProducerSubject() { - return "FOO.BAR.HUMBUG"; - } + /** + * Returns the producer subject. + * + * @return String - producer subject + * @see org.apache.activemq.test.TestSupport#getProducerSubject() + */ + protected String getProducerSubject() { + return "FOO.BAR.HUMBUG"; + } - public void testReceiveWildcardQueueEndAsterisk() throws Exception { - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + public void testReceiveWildcardQueueEndAsterisk() throws Exception { + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination1 = (ActiveMQDestination)session.createQueue(destination1String); - ActiveMQDestination destination3 = (ActiveMQDestination)session.createQueue(destination3String); + ActiveMQDestination destination1 = (ActiveMQDestination) session.createQueue(destination1String); + ActiveMQDestination destination3 = (ActiveMQDestination) session.createQueue(destination3String); - Message m = null; - MessageConsumer consumer = null; - String text = null; + Message m = null; + MessageConsumer consumer = null; + String text = null; - sendMessage(session, destination1, destination1String); - sendMessage(session, destination3, destination3String); - ActiveMQDestination destination6 = (ActiveMQDestination)session.createQueue("TEST.ONE.*"); - consumer = session.createConsumer(destination6); - m = consumer.receive(1000); - assertNotNull(m); - text = ((TextMessage)m).getText(); - if (!(text.equals(destination1String) || text.equals(destination3String))) { - fail("unexpected message:" + text); - } - m = consumer.receive(1000); - assertNotNull(m); - text = ((TextMessage)m).getText(); - if (!(text.equals(destination1String) || text.equals(destination3String))) { - fail("unexpected message:" + text); - } - assertNull(consumer.receiveNoWait()); - } + sendMessage(session, destination1, destination1String); + sendMessage(session, destination3, destination3String); + ActiveMQDestination destination6 = (ActiveMQDestination) session.createQueue("TEST.ONE.*"); + consumer = session.createConsumer(destination6); + m = consumer.receive(1000); + assertNotNull(m); + text = ((TextMessage) m).getText(); + if (!(text.equals(destination1String) || text.equals(destination3String))) { + fail("unexpected message:" + text); + } + m = consumer.receive(1000); + assertNotNull(m); + text = ((TextMessage) m).getText(); + if (!(text.equals(destination1String) || text.equals(destination3String))) { + fail("unexpected message:" + text); + } + assertNull(consumer.receiveNoWait()); + } - public void testReceiveWildcardQueueEndGreaterThan() throws Exception { - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + public void testReceiveWildcardQueueEndGreaterThan() throws Exception { + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination1 = (ActiveMQDestination)session.createQueue(destination1String); - ActiveMQDestination destination2 = (ActiveMQDestination)session.createQueue(destination2String); - ActiveMQDestination destination3 = (ActiveMQDestination)session.createQueue(destination3String); + ActiveMQDestination destination1 = (ActiveMQDestination) session.createQueue(destination1String); + ActiveMQDestination destination2 = (ActiveMQDestination) session.createQueue(destination2String); + ActiveMQDestination destination3 = (ActiveMQDestination) session.createQueue(destination3String); - Message m = null; - MessageConsumer consumer = null; - String text = null; + Message m = null; + MessageConsumer consumer = null; + String text = null; - sendMessage(session, destination1, destination1String); - sendMessage(session, destination2, destination2String); - sendMessage(session, destination3, destination3String); - ActiveMQDestination destination7 = (ActiveMQDestination)session.createQueue("TEST.ONE.>"); - consumer = session.createConsumer(destination7); - m = consumer.receive(1000); - assertNotNull(m); - text = ((TextMessage)m).getText(); - if (!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { - fail("unexpected message:" + text); - } - m = consumer.receive(1000); - assertNotNull(m); - if (!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { - fail("unexpected message:" + text); - } - m = consumer.receive(1000); - assertNotNull(m); - if (!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { - fail("unexpected message:" + text); - } - assertNull(consumer.receiveNoWait()); - } + sendMessage(session, destination1, destination1String); + sendMessage(session, destination2, destination2String); + sendMessage(session, destination3, destination3String); + ActiveMQDestination destination7 = (ActiveMQDestination) session.createQueue("TEST.ONE.>"); + consumer = session.createConsumer(destination7); + m = consumer.receive(1000); + assertNotNull(m); + text = ((TextMessage) m).getText(); + if (!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { + fail("unexpected message:" + text); + } + m = consumer.receive(1000); + assertNotNull(m); + if (!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { + fail("unexpected message:" + text); + } + m = consumer.receive(1000); + assertNotNull(m); + if (!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { + fail("unexpected message:" + text); + } + assertNull(consumer.receiveNoWait()); + } - public void testReceiveWildcardQueueMidAsterisk() throws Exception { - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + public void testReceiveWildcardQueueMidAsterisk() throws Exception { + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination1 = (ActiveMQDestination)session.createQueue(destination1String); - ActiveMQDestination destination4 = (ActiveMQDestination)session.createQueue(destination4String); + ActiveMQDestination destination1 = (ActiveMQDestination) session.createQueue(destination1String); + ActiveMQDestination destination4 = (ActiveMQDestination) session.createQueue(destination4String); - Message m = null; - MessageConsumer consumer = null; - String text = null; + Message m = null; + MessageConsumer consumer = null; + String text = null; - sendMessage(session, destination1, destination1String); - sendMessage(session, destination4, destination4String); - ActiveMQDestination destination8 = (ActiveMQDestination)session.createQueue("TEST.*.ONE"); - consumer = session.createConsumer(destination8); - m = consumer.receive(1000); - assertNotNull(m); - text = ((TextMessage)m).getText(); - if (!(text.equals(destination1String) || text.equals(destination4String))) { - fail("unexpected message:" + text); - } - m = consumer.receive(1000); - assertNotNull(m); - text = ((TextMessage)m).getText(); - if (!(text.equals(destination1String) || text.equals(destination4String))) { - fail("unexpected message:" + text); - } - assertNull(consumer.receiveNoWait()); + sendMessage(session, destination1, destination1String); + sendMessage(session, destination4, destination4String); + ActiveMQDestination destination8 = (ActiveMQDestination) session.createQueue("TEST.*.ONE"); + consumer = session.createConsumer(destination8); + m = consumer.receive(1000); + assertNotNull(m); + text = ((TextMessage) m).getText(); + if (!(text.equals(destination1String) || text.equals(destination4String))) { + fail("unexpected message:" + text); + } + m = consumer.receive(1000); + assertNotNull(m); + text = ((TextMessage) m).getText(); + if (!(text.equals(destination1String) || text.equals(destination4String))) { + fail("unexpected message:" + text); + } + assertNull(consumer.receiveNoWait()); - } + } - private void sendMessage(Session session, Destination destination, String text) throws JMSException { - MessageProducer producer = session.createProducer(destination); - producer.send(session.createTextMessage(text)); - producer.close(); - } + private void sendMessage(Session session, Destination destination, String text) throws JMSException { + MessageProducer producer = session.createProducer(destination); + producer.send(session.createTextMessage(text)); + producer.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsRedeliveredTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsRedeliveredTest.java index 07e8eebce9..a6a4f23bfb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsRedeliveredTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsRedeliveredTest.java @@ -32,536 +32,531 @@ import javax.jms.Topic; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; + import org.apache.activemq.transport.tcp.TcpTransport; import org.apache.activemq.transport.vm.VMTransport; import org.apache.activemq.util.Wait; /** - * + * */ public class JmsRedeliveredTest extends TestCase { - private Connection connection; - - /* - * (non-Javadoc) - * - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception { - connection = createConnection(); - } - - /** - * @see junit.framework.TestCase#tearDown() - */ - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - connection = null; - } - CombinationTestSupport.checkStopped(); - } - - /** - * Creates a connection. - * - * @return connection - * @throws Exception - */ - protected Connection createConnection() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory( - "vm://localhost?broker.persistent=false"); - return factory.createConnection(); - } - - /** - * Tests if a message unacknowledged message gets to be resent when the - * session is closed and then a new consumer session is created. - * - */ - public void testQueueSessionCloseMarksMessageRedelivered() throws JMSException { - connection.start(); - - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Queue queue = session.createQueue("queue-" + getName()); - MessageProducer producer = createProducer(session, queue); - producer.send(createTextMessage(session)); - - // Consume the message... - MessageConsumer consumer = session.createConsumer(queue); - Message msg = consumer.receive(1000); - assertNotNull(msg); - assertFalse("Message should not be redelivered.", msg.getJMSRedelivered()); - // Don't ack the message. - - // Reset the session. This should cause the Unacked message to be - // redelivered. - session.close(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - - // Attempt to Consume the message... - consumer = session.createConsumer(queue); - msg = consumer.receive(2000); - assertNotNull(msg); - assertTrue("Message should be redelivered.", msg.getJMSRedelivered()); - msg.acknowledge(); - - session.close(); - } - - - - public void testQueueSessionCloseMarksUnAckedMessageRedelivered() throws JMSException { - connection.start(); - - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Queue queue = session.createQueue("queue-" + getName()); - MessageProducer producer = createProducer(session, queue); - producer.send(createTextMessage(session, "1")); - producer.send(createTextMessage(session, "2")); - - // Consume the message... - MessageConsumer consumer = session.createConsumer(queue); - Message msg = consumer.receive(1000); - assertNotNull(msg); - assertFalse("Message should not be redelivered.", msg.getJMSRedelivered()); - assertEquals("1", ((TextMessage)msg).getText()); - msg.acknowledge(); - - // Don't ack the message. - msg = consumer.receive(1000); - assertNotNull(msg); - assertFalse("Message should not be redelivered.", msg.getJMSRedelivered()); - assertEquals("2", ((TextMessage)msg).getText()); - - // Reset the session. This should cause the Unacked message to be - // redelivered. - session.close(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - - // Attempt to Consume the message... - consumer = session.createConsumer(queue); - msg = consumer.receive(2000); - assertNotNull(msg); - assertEquals("2", ((TextMessage)msg).getText()); - assertTrue("Message should be redelivered.", msg.getJMSRedelivered()); - msg.acknowledge(); - - session.close(); - } - - /** - * Tests session recovery and that the redelivered message is marked as - * such. Session uses client acknowledgement, the destination is a queue. - * - * @throws JMSException - */ - public void testQueueRecoverMarksMessageRedelivered() throws JMSException { - connection.start(); - - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Queue queue = session.createQueue("queue-" + getName()); - MessageProducer producer = createProducer(session, queue); - producer.send(createTextMessage(session)); - - // Consume the message... - MessageConsumer consumer = session.createConsumer(queue); - Message msg = consumer.receive(1000); - assertNotNull(msg); - assertFalse("Message should not be redelivered.", msg.getJMSRedelivered()); - // Don't ack the message. - - // Reset the session. This should cause the Unacked message to be - // redelivered. - session.recover(); - - // Attempt to Consume the message... - msg = consumer.receive(2000); - assertNotNull(msg); - assertTrue("Message should be redelivered.", msg.getJMSRedelivered()); - msg.acknowledge(); - - session.close(); - } - - /** - * Tests rollback message to be marked as redelivered. Session uses client - * acknowledgement and the destination is a queue. - * - * @throws JMSException - */ - public void testQueueRollbackMarksMessageRedelivered() throws JMSException { - connection.start(); - - Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); - Queue queue = session.createQueue("queue-" + getName()); - MessageProducer producer = createProducer(session, queue); - producer.send(createTextMessage(session)); - session.commit(); - - // Get the message... Should not be redelivered. - MessageConsumer consumer = session.createConsumer(queue); - Message msg = consumer.receive(1000); - assertNotNull(msg); - assertFalse("Message should not be redelivered.", msg.getJMSRedelivered()); - - // Rollback.. should cause redelivery. - session.rollback(); - - // Attempt to Consume the message... - msg = consumer.receive(2000); - assertNotNull(msg); - assertTrue("Message should be redelivered.", msg.getJMSRedelivered()); - - session.commit(); - session.close(); - } - - /** - * Tests if the message gets to be re-delivered when the session closes and - * that the re-delivered message is marked as such. Session uses client - * acknowledgment, the destination is a topic and the consumer is a durable - * subscriber. - * - * @throws JMSException - */ - public void testDurableTopicSessionCloseMarksMessageRedelivered() throws JMSException { - connection.setClientID(getName()); - connection.start(); - - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Topic topic = session.createTopic("topic-" + getName()); - MessageConsumer consumer = session.createDurableSubscriber(topic, "sub1"); - - // This case only works with persistent messages since transient - // messages - // are dropped when the consumer goes offline. - MessageProducer producer = session.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - producer.send(createTextMessage(session)); - - // Consume the message... - Message msg = consumer.receive(1000); - assertNotNull(msg); - assertFalse("Message should not be re-delivered.", msg.getJMSRedelivered()); - // Don't ack the message. - - // Reset the session. This should cause the Unacked message to be - // re-delivered. - session.close(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - - // Attempt to Consume the message... - consumer = session.createDurableSubscriber(topic, "sub1"); - msg = consumer.receive(2000); - assertNotNull(msg); - assertTrue("Message should be redelivered.", msg.getJMSRedelivered()); - msg.acknowledge(); - - session.close(); - } - - /** - * Tests session recovery and that the redelivered message is marked as - * such. Session uses client acknowledgement, the destination is a topic and - * the consumer is a durable suscriber. - * - * @throws JMSException - */ - public void testDurableTopicRecoverMarksMessageRedelivered() throws JMSException { - connection.setClientID(getName()); - connection.start(); - - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Topic topic = session.createTopic("topic-" + getName()); - MessageConsumer consumer = session.createDurableSubscriber(topic, "sub1"); - - MessageProducer producer = createProducer(session, topic); - producer.send(createTextMessage(session)); - - // Consume the message... - Message msg = consumer.receive(1000); - assertNotNull(msg); - assertFalse("Message should not be redelivered.", msg.getJMSRedelivered()); - // Don't ack the message. - - // Reset the session. This should cause the Unacked message to be - // redelivered. - session.recover(); - - // Attempt to Consume the message... - msg = consumer.receive(2000); - assertNotNull(msg); - assertTrue("Message should be redelivered.", msg.getJMSRedelivered()); - msg.acknowledge(); - - session.close(); - } - - /** - * Tests rollback message to be marked as redelivered. Session uses client - * acknowledgement and the destination is a topic. - * - * @throws JMSException - */ - public void testDurableTopicRollbackMarksMessageRedelivered() throws JMSException { - connection.setClientID(getName()); - connection.start(); - - Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); - Topic topic = session.createTopic("topic-" + getName()); - MessageConsumer consumer = session.createDurableSubscriber(topic, "sub1"); - - MessageProducer producer = createProducer(session, topic); - producer.send(createTextMessage(session)); - session.commit(); - - // Get the message... Should not be redelivered. - Message msg = consumer.receive(1000); - assertNotNull(msg); - assertFalse("Message should not be redelivered.", msg.getJMSRedelivered()); - - // Rollback.. should cause redelivery. - session.rollback(); - - // Attempt to Consume the message... - msg = consumer.receive(2000); - assertNotNull(msg); - assertTrue("Message should be redelivered.", msg.getJMSRedelivered()); - - session.commit(); - session.close(); - } - - /** - * - * - * @throws JMSException - */ - public void testTopicRecoverMarksMessageRedelivered() throws JMSException { - - connection.setClientID(getName()); - connection.start(); - - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Topic topic = session.createTopic("topic-" + getName()); - MessageConsumer consumer = session.createConsumer(topic); - - MessageProducer producer = createProducer(session, topic); - producer.send(createTextMessage(session)); - - // Consume the message... - Message msg = consumer.receive(1000); - assertNotNull(msg); - assertFalse("Message should not be redelivered.", msg.getJMSRedelivered()); - // Don't ack the message. - - // Reset the session. This should cause the Unacked message to be - // redelivered. - session.recover(); - - // Attempt to Consume the message... - msg = consumer.receive(2000); - assertNotNull(msg); - assertTrue("Message should be redelivered.", msg.getJMSRedelivered()); - msg.acknowledge(); - - session.close(); - } - - /** - * Tests rollback message to be marked as redelivered. Session uses client - * acknowledgement and the destination is a topic. - * - * @throws JMSException - */ - public void testTopicRollbackMarksMessageRedelivered() throws JMSException { - connection.setClientID(getName()); - connection.start(); - - Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); - Topic topic = session.createTopic("topic-" + getName()); - MessageConsumer consumer = session.createConsumer(topic); - - MessageProducer producer = createProducer(session, topic); - producer.send(createTextMessage(session)); - session.commit(); - - // Get the message... Should not be redelivered. - Message msg = consumer.receive(1000); - assertNotNull(msg); - assertFalse("Message should not be redelivered.", msg.getJMSRedelivered()); - - // Rollback.. should cause redelivery. - session.rollback(); - - // Attempt to Consume the message... - msg = consumer.receive(2000); - assertNotNull(msg); - assertTrue("Message should be redelivered.", msg.getJMSRedelivered()); - - session.commit(); - session.close(); - } - - public void testNoReceiveConsumerDisconnectDoesNotIncrementRedelivery() throws Exception { - connection.setClientID(getName()); - connection.start(); - - Connection keepBrokerAliveConnection = createConnection(); - keepBrokerAliveConnection.start(); - - Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); - Queue queue = session.createQueue("queue-" + getName()); - final MessageConsumer consumer = session.createConsumer(queue); - - MessageProducer producer = createProducer(session, queue); - producer.send(createTextMessage(session)); - session.commit(); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return ((ActiveMQMessageConsumer)consumer).getMessageSize() == 1; - } - }); - - connection.close(); - - session = keepBrokerAliveConnection.createSession(true, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer messageConsumer = session.createConsumer(queue); - Message msg = messageConsumer.receive(1000); - assertNotNull(msg); - msg.acknowledge(); - - assertFalse("Message should not be redelivered.", msg.getJMSRedelivered()); - session.commit(); - session.close(); - keepBrokerAliveConnection.close(); - } - - public void testNoReceiveConsumerDoesNotIncrementRedelivery() throws Exception { - connection.setClientID(getName()); - connection.start(); - - Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); - Queue queue = session.createQueue("queue-" + getName()); - MessageConsumer consumer = session.createConsumer(queue); - - MessageProducer producer = createProducer(session, queue); - producer.send(createTextMessage(session)); - session.commit(); - - TimeUnit.SECONDS.sleep(1); - consumer.close(); - - consumer = session.createConsumer(queue); - Message msg = consumer.receive(1000); - assertNotNull(msg); - - assertFalse("Message should not be redelivered.", msg.getJMSRedelivered()); - session.commit(); - session.close(); - } - - public void testNoReceiveDurableConsumerDoesNotIncrementRedelivery() throws Exception { - connection.setClientID(getName()); - connection.start(); - - Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); - Topic topic = session.createTopic("topic-" + getName()); - MessageConsumer consumer = session.createDurableSubscriber(topic, "sub"); - - MessageProducer producer = createProducer(session, topic); - producer.send(createTextMessage(session)); - session.commit(); - - TimeUnit.SECONDS.sleep(1); - consumer.close(); - - consumer = session.createDurableSubscriber(topic, "sub"); - Message msg = consumer.receive(1000); - assertNotNull(msg); - - assertFalse("Message should not be redelivered.", msg.getJMSRedelivered()); - - session.commit(); - session.close(); - } - - /** - * Creates a text message. - * - * @param session - * @return TextMessage. - * @throws JMSException - */ - private TextMessage createTextMessage(Session session) throws JMSException { - return createTextMessage(session, "Hello"); - } - - private TextMessage createTextMessage(Session session, String txt) throws JMSException { - return session.createTextMessage(txt); - } - - /** - * Creates a producer. - * - * @param session - * @param queue - destination. - * @return MessageProducer - * @throws JMSException - */ - private MessageProducer createProducer(Session session, Destination queue) throws JMSException { - MessageProducer producer = session.createProducer(queue); - producer.setDeliveryMode(getDeliveryMode()); - return producer; - } - - /** - * Returns delivery mode. - * - * @return int - persistent delivery mode. - */ - protected int getDeliveryMode() { - return DeliveryMode.PERSISTENT; - } - - /** - * Run the JmsRedeliverTest with the delivery mode set as persistent. - */ - public static final class PersistentCase extends JmsRedeliveredTest { - - /** - * Returns delivery mode. - * - * @return int - persistent delivery mode. - */ - protected int getDeliveryMode() { - return DeliveryMode.PERSISTENT; - } - } - - /** - * Run the JmsRedeliverTest with the delivery mode set as non-persistent. - */ - public static final class TransientCase extends JmsRedeliveredTest { - - /** - * Returns delivery mode. - * - * @return int - non-persistent delivery mode. - */ - protected int getDeliveryMode() { - return DeliveryMode.NON_PERSISTENT; - } - } - - public static Test suite() { - TestSuite suite = new TestSuite(); - suite.addTestSuite(PersistentCase.class); - suite.addTestSuite(TransientCase.class); - return suite; - } + private Connection connection; + + /* + * (non-Javadoc) + * + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + connection = createConnection(); + } + + /** + * @see junit.framework.TestCase#tearDown() + */ + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + connection = null; + } + CombinationTestSupport.checkStopped(); + } + + /** + * Creates a connection. + * + * @return connection + * @throws Exception + */ + protected Connection createConnection() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); + return factory.createConnection(); + } + + /** + * Tests if a message unacknowledged message gets to be resent when the + * session is closed and then a new consumer session is created. + */ + public void testQueueSessionCloseMarksMessageRedelivered() throws JMSException { + connection.start(); + + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Queue queue = session.createQueue("queue-" + getName()); + MessageProducer producer = createProducer(session, queue); + producer.send(createTextMessage(session)); + + // Consume the message... + MessageConsumer consumer = session.createConsumer(queue); + Message msg = consumer.receive(1000); + assertNotNull(msg); + assertFalse("Message should not be redelivered.", msg.getJMSRedelivered()); + // Don't ack the message. + + // Reset the session. This should cause the Unacked message to be + // redelivered. + session.close(); + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + + // Attempt to Consume the message... + consumer = session.createConsumer(queue); + msg = consumer.receive(2000); + assertNotNull(msg); + assertTrue("Message should be redelivered.", msg.getJMSRedelivered()); + msg.acknowledge(); + + session.close(); + } + + public void testQueueSessionCloseMarksUnAckedMessageRedelivered() throws JMSException { + connection.start(); + + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Queue queue = session.createQueue("queue-" + getName()); + MessageProducer producer = createProducer(session, queue); + producer.send(createTextMessage(session, "1")); + producer.send(createTextMessage(session, "2")); + + // Consume the message... + MessageConsumer consumer = session.createConsumer(queue); + Message msg = consumer.receive(1000); + assertNotNull(msg); + assertFalse("Message should not be redelivered.", msg.getJMSRedelivered()); + assertEquals("1", ((TextMessage) msg).getText()); + msg.acknowledge(); + + // Don't ack the message. + msg = consumer.receive(1000); + assertNotNull(msg); + assertFalse("Message should not be redelivered.", msg.getJMSRedelivered()); + assertEquals("2", ((TextMessage) msg).getText()); + + // Reset the session. This should cause the Unacked message to be + // redelivered. + session.close(); + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + + // Attempt to Consume the message... + consumer = session.createConsumer(queue); + msg = consumer.receive(2000); + assertNotNull(msg); + assertEquals("2", ((TextMessage) msg).getText()); + assertTrue("Message should be redelivered.", msg.getJMSRedelivered()); + msg.acknowledge(); + + session.close(); + } + + /** + * Tests session recovery and that the redelivered message is marked as + * such. Session uses client acknowledgement, the destination is a queue. + * + * @throws JMSException + */ + public void testQueueRecoverMarksMessageRedelivered() throws JMSException { + connection.start(); + + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Queue queue = session.createQueue("queue-" + getName()); + MessageProducer producer = createProducer(session, queue); + producer.send(createTextMessage(session)); + + // Consume the message... + MessageConsumer consumer = session.createConsumer(queue); + Message msg = consumer.receive(1000); + assertNotNull(msg); + assertFalse("Message should not be redelivered.", msg.getJMSRedelivered()); + // Don't ack the message. + + // Reset the session. This should cause the Unacked message to be + // redelivered. + session.recover(); + + // Attempt to Consume the message... + msg = consumer.receive(2000); + assertNotNull(msg); + assertTrue("Message should be redelivered.", msg.getJMSRedelivered()); + msg.acknowledge(); + + session.close(); + } + + /** + * Tests rollback message to be marked as redelivered. Session uses client + * acknowledgement and the destination is a queue. + * + * @throws JMSException + */ + public void testQueueRollbackMarksMessageRedelivered() throws JMSException { + connection.start(); + + Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); + Queue queue = session.createQueue("queue-" + getName()); + MessageProducer producer = createProducer(session, queue); + producer.send(createTextMessage(session)); + session.commit(); + + // Get the message... Should not be redelivered. + MessageConsumer consumer = session.createConsumer(queue); + Message msg = consumer.receive(1000); + assertNotNull(msg); + assertFalse("Message should not be redelivered.", msg.getJMSRedelivered()); + + // Rollback.. should cause redelivery. + session.rollback(); + + // Attempt to Consume the message... + msg = consumer.receive(2000); + assertNotNull(msg); + assertTrue("Message should be redelivered.", msg.getJMSRedelivered()); + + session.commit(); + session.close(); + } + + /** + * Tests if the message gets to be re-delivered when the session closes and + * that the re-delivered message is marked as such. Session uses client + * acknowledgment, the destination is a topic and the consumer is a durable + * subscriber. + * + * @throws JMSException + */ + public void testDurableTopicSessionCloseMarksMessageRedelivered() throws JMSException { + connection.setClientID(getName()); + connection.start(); + + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Topic topic = session.createTopic("topic-" + getName()); + MessageConsumer consumer = session.createDurableSubscriber(topic, "sub1"); + + // This case only works with persistent messages since transient + // messages + // are dropped when the consumer goes offline. + MessageProducer producer = session.createProducer(topic); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + producer.send(createTextMessage(session)); + + // Consume the message... + Message msg = consumer.receive(1000); + assertNotNull(msg); + assertFalse("Message should not be re-delivered.", msg.getJMSRedelivered()); + // Don't ack the message. + + // Reset the session. This should cause the Unacked message to be + // re-delivered. + session.close(); + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + + // Attempt to Consume the message... + consumer = session.createDurableSubscriber(topic, "sub1"); + msg = consumer.receive(2000); + assertNotNull(msg); + assertTrue("Message should be redelivered.", msg.getJMSRedelivered()); + msg.acknowledge(); + + session.close(); + } + + /** + * Tests session recovery and that the redelivered message is marked as + * such. Session uses client acknowledgement, the destination is a topic and + * the consumer is a durable suscriber. + * + * @throws JMSException + */ + public void testDurableTopicRecoverMarksMessageRedelivered() throws JMSException { + connection.setClientID(getName()); + connection.start(); + + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Topic topic = session.createTopic("topic-" + getName()); + MessageConsumer consumer = session.createDurableSubscriber(topic, "sub1"); + + MessageProducer producer = createProducer(session, topic); + producer.send(createTextMessage(session)); + + // Consume the message... + Message msg = consumer.receive(1000); + assertNotNull(msg); + assertFalse("Message should not be redelivered.", msg.getJMSRedelivered()); + // Don't ack the message. + + // Reset the session. This should cause the Unacked message to be + // redelivered. + session.recover(); + + // Attempt to Consume the message... + msg = consumer.receive(2000); + assertNotNull(msg); + assertTrue("Message should be redelivered.", msg.getJMSRedelivered()); + msg.acknowledge(); + + session.close(); + } + + /** + * Tests rollback message to be marked as redelivered. Session uses client + * acknowledgement and the destination is a topic. + * + * @throws JMSException + */ + public void testDurableTopicRollbackMarksMessageRedelivered() throws JMSException { + connection.setClientID(getName()); + connection.start(); + + Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); + Topic topic = session.createTopic("topic-" + getName()); + MessageConsumer consumer = session.createDurableSubscriber(topic, "sub1"); + + MessageProducer producer = createProducer(session, topic); + producer.send(createTextMessage(session)); + session.commit(); + + // Get the message... Should not be redelivered. + Message msg = consumer.receive(1000); + assertNotNull(msg); + assertFalse("Message should not be redelivered.", msg.getJMSRedelivered()); + + // Rollback.. should cause redelivery. + session.rollback(); + + // Attempt to Consume the message... + msg = consumer.receive(2000); + assertNotNull(msg); + assertTrue("Message should be redelivered.", msg.getJMSRedelivered()); + + session.commit(); + session.close(); + } + + /** + * @throws JMSException + */ + public void testTopicRecoverMarksMessageRedelivered() throws JMSException { + + connection.setClientID(getName()); + connection.start(); + + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Topic topic = session.createTopic("topic-" + getName()); + MessageConsumer consumer = session.createConsumer(topic); + + MessageProducer producer = createProducer(session, topic); + producer.send(createTextMessage(session)); + + // Consume the message... + Message msg = consumer.receive(1000); + assertNotNull(msg); + assertFalse("Message should not be redelivered.", msg.getJMSRedelivered()); + // Don't ack the message. + + // Reset the session. This should cause the Unacked message to be + // redelivered. + session.recover(); + + // Attempt to Consume the message... + msg = consumer.receive(2000); + assertNotNull(msg); + assertTrue("Message should be redelivered.", msg.getJMSRedelivered()); + msg.acknowledge(); + + session.close(); + } + + /** + * Tests rollback message to be marked as redelivered. Session uses client + * acknowledgement and the destination is a topic. + * + * @throws JMSException + */ + public void testTopicRollbackMarksMessageRedelivered() throws JMSException { + connection.setClientID(getName()); + connection.start(); + + Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); + Topic topic = session.createTopic("topic-" + getName()); + MessageConsumer consumer = session.createConsumer(topic); + + MessageProducer producer = createProducer(session, topic); + producer.send(createTextMessage(session)); + session.commit(); + + // Get the message... Should not be redelivered. + Message msg = consumer.receive(1000); + assertNotNull(msg); + assertFalse("Message should not be redelivered.", msg.getJMSRedelivered()); + + // Rollback.. should cause redelivery. + session.rollback(); + + // Attempt to Consume the message... + msg = consumer.receive(2000); + assertNotNull(msg); + assertTrue("Message should be redelivered.", msg.getJMSRedelivered()); + + session.commit(); + session.close(); + } + + public void testNoReceiveConsumerDisconnectDoesNotIncrementRedelivery() throws Exception { + connection.setClientID(getName()); + connection.start(); + + Connection keepBrokerAliveConnection = createConnection(); + keepBrokerAliveConnection.start(); + + Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); + Queue queue = session.createQueue("queue-" + getName()); + final MessageConsumer consumer = session.createConsumer(queue); + + MessageProducer producer = createProducer(session, queue); + producer.send(createTextMessage(session)); + session.commit(); + + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return ((ActiveMQMessageConsumer) consumer).getMessageSize() == 1; + } + }); + + connection.close(); + + session = keepBrokerAliveConnection.createSession(true, Session.CLIENT_ACKNOWLEDGE); + MessageConsumer messageConsumer = session.createConsumer(queue); + Message msg = messageConsumer.receive(1000); + assertNotNull(msg); + msg.acknowledge(); + + assertFalse("Message should not be redelivered.", msg.getJMSRedelivered()); + session.commit(); + session.close(); + keepBrokerAliveConnection.close(); + } + + public void testNoReceiveConsumerDoesNotIncrementRedelivery() throws Exception { + connection.setClientID(getName()); + connection.start(); + + Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); + Queue queue = session.createQueue("queue-" + getName()); + MessageConsumer consumer = session.createConsumer(queue); + + MessageProducer producer = createProducer(session, queue); + producer.send(createTextMessage(session)); + session.commit(); + + TimeUnit.SECONDS.sleep(1); + consumer.close(); + + consumer = session.createConsumer(queue); + Message msg = consumer.receive(1000); + assertNotNull(msg); + + assertFalse("Message should not be redelivered.", msg.getJMSRedelivered()); + session.commit(); + session.close(); + } + + public void testNoReceiveDurableConsumerDoesNotIncrementRedelivery() throws Exception { + connection.setClientID(getName()); + connection.start(); + + Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); + Topic topic = session.createTopic("topic-" + getName()); + MessageConsumer consumer = session.createDurableSubscriber(topic, "sub"); + + MessageProducer producer = createProducer(session, topic); + producer.send(createTextMessage(session)); + session.commit(); + + TimeUnit.SECONDS.sleep(1); + consumer.close(); + + consumer = session.createDurableSubscriber(topic, "sub"); + Message msg = consumer.receive(1000); + assertNotNull(msg); + + assertFalse("Message should not be redelivered.", msg.getJMSRedelivered()); + + session.commit(); + session.close(); + } + + /** + * Creates a text message. + * + * @param session + * @return TextMessage. + * @throws JMSException + */ + private TextMessage createTextMessage(Session session) throws JMSException { + return createTextMessage(session, "Hello"); + } + + private TextMessage createTextMessage(Session session, String txt) throws JMSException { + return session.createTextMessage(txt); + } + + /** + * Creates a producer. + * + * @param session + * @param queue - destination. + * @return MessageProducer + * @throws JMSException + */ + private MessageProducer createProducer(Session session, Destination queue) throws JMSException { + MessageProducer producer = session.createProducer(queue); + producer.setDeliveryMode(getDeliveryMode()); + return producer; + } + + /** + * Returns delivery mode. + * + * @return int - persistent delivery mode. + */ + protected int getDeliveryMode() { + return DeliveryMode.PERSISTENT; + } + + /** + * Run the JmsRedeliverTest with the delivery mode set as persistent. + */ + public static final class PersistentCase extends JmsRedeliveredTest { + + /** + * Returns delivery mode. + * + * @return int - persistent delivery mode. + */ + protected int getDeliveryMode() { + return DeliveryMode.PERSISTENT; + } + } + + /** + * Run the JmsRedeliverTest with the delivery mode set as non-persistent. + */ + public static final class TransientCase extends JmsRedeliveredTest { + + /** + * Returns delivery mode. + * + * @return int - non-persistent delivery mode. + */ + protected int getDeliveryMode() { + return DeliveryMode.NON_PERSISTENT; + } + } + + public static Test suite() { + TestSuite suite = new TestSuite(); + suite.addTestSuite(PersistentCase.class); + suite.addTestSuite(TransientCase.class); + return suite; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsRollbackRedeliveryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsRollbackRedeliveryTest.java index 91e29c053d..3c50c62e73 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsRollbackRedeliveryTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsRollbackRedeliveryTest.java @@ -42,317 +42,313 @@ import org.slf4j.LoggerFactory; import static org.junit.Assert.*; public class JmsRollbackRedeliveryTest { - @Rule - public TestName testName = new TestName(); - protected static final Logger LOG = LoggerFactory.getLogger(JmsRollbackRedeliveryTest.class); - final int nbMessages = 10; - final String destinationName = "Destination"; - final String brokerUrl = "vm://localhost?create=false"; - boolean consumerClose = true; - boolean rollback = true; - BrokerService broker; + @Rule + public TestName testName = new TestName(); - @Before - public void setUp() throws Exception { - LOG.debug("Starting " + testName.getMethodName()); - broker = new BrokerService(); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.start(); - broker.waitUntilStarted(); - } + protected static final Logger LOG = LoggerFactory.getLogger(JmsRollbackRedeliveryTest.class); + final int nbMessages = 10; + final String destinationName = "Destination"; + final String brokerUrl = "vm://localhost?create=false"; + boolean consumerClose = true; + boolean rollback = true; + BrokerService broker; - @After - public void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - LOG.debug("Finishing " + testName.getMethodName()); - Thread.sleep(100); - } - - @Test - public void testRedelivery() throws Exception { - doTestRedelivery(brokerUrl, false); - } + @Before + public void setUp() throws Exception { + LOG.debug("Starting " + testName.getMethodName()); + broker = new BrokerService(); + broker.setPersistent(false); + broker.setUseJmx(false); + broker.start(); + broker.waitUntilStarted(); + } - @Test - public void testRedeliveryWithInterleavedProducer() throws Exception { - doTestRedelivery(brokerUrl, true); - } + @After + public void tearDown() throws Exception { + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + LOG.debug("Finishing " + testName.getMethodName()); + Thread.sleep(100); + } + @Test + public void testRedelivery() throws Exception { + doTestRedelivery(brokerUrl, false); + } - @Test - public void testRedeliveryWithPrefetch0() throws Exception { - doTestRedelivery(brokerUrl + "?jms.prefetchPolicy.queuePrefetch=0", true); - } + @Test + public void testRedeliveryWithInterleavedProducer() throws Exception { + doTestRedelivery(brokerUrl, true); + } - @Test - public void testRedeliveryWithPrefetch1() throws Exception { - doTestRedelivery(brokerUrl + "?jms.prefetchPolicy.queuePrefetch=1", true); - } - - public void doTestRedelivery(String brokerUrl, boolean interleaveProducer) throws Exception { - LOG.debug("entering doTestRedelivery interleaveProducer is " + interleaveProducer); - ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl); - - Connection connection = connectionFactory.createConnection(); - connection.start(); + @Test + public void testRedeliveryWithPrefetch0() throws Exception { + doTestRedelivery(brokerUrl + "?jms.prefetchPolicy.queuePrefetch=0", true); + } - if (interleaveProducer) { - populateDestinationWithInterleavedProducer(nbMessages, destinationName, connection); - } else { - populateDestination(nbMessages, destinationName, connection); - } - - // Consume messages and rollback transactions - { - AtomicInteger received = new AtomicInteger(); - Map rolledback = new ConcurrentHashMap(); - while (received.get() < nbMessages) { - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(destinationName); - MessageConsumer consumer = session.createConsumer(destination); - TextMessage msg = (TextMessage) consumer.receive(6000000); - if (msg != null) { - if (msg != null && rolledback.put(msg.getText(), Boolean.TRUE) != null) { - LOG.info("Received message " + msg.getText() + " (" + received.getAndIncrement() + ")" + msg.getJMSMessageID()); - assertTrue(msg.getJMSRedelivered()); - assertEquals(2, msg.getLongProperty("JMSXDeliveryCount")); - session.commit(); - } else { - LOG.info("Rollback message " + msg.getText() + " id: " + msg.getJMSMessageID()); - assertFalse("should not have redelivery flag set, id: " + msg.getJMSMessageID(), msg.getJMSRedelivered()); - session.rollback(); - } - } - consumer.close(); - session.close(); - } - } - } + @Test + public void testRedeliveryWithPrefetch1() throws Exception { + doTestRedelivery(brokerUrl + "?jms.prefetchPolicy.queuePrefetch=1", true); + } - @Test - public void testRedeliveryOnSingleConsumer() throws Exception { + public void doTestRedelivery(String brokerUrl, boolean interleaveProducer) throws Exception { + LOG.debug("entering doTestRedelivery interleaveProducer is " + interleaveProducer); + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl); - ConnectionFactory connectionFactory = - new ActiveMQConnectionFactory(brokerUrl); - Connection connection = connectionFactory.createConnection(); - connection.start(); + Connection connection = connectionFactory.createConnection(); + connection.start(); - populateDestinationWithInterleavedProducer(nbMessages, destinationName, connection); + if (interleaveProducer) { + populateDestinationWithInterleavedProducer(nbMessages, destinationName, connection); + } + else { + populateDestination(nbMessages, destinationName, connection); + } - // Consume messages and rollback transactions - { - AtomicInteger received = new AtomicInteger(); - Map rolledback = new ConcurrentHashMap(); + // Consume messages and rollback transactions + { + AtomicInteger received = new AtomicInteger(); + Map rolledback = new ConcurrentHashMap(); + while (received.get() < nbMessages) { Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(destinationName); - MessageConsumer consumer = session.createConsumer(destination); - while (received.get() < nbMessages) { - TextMessage msg = (TextMessage) consumer.receive(6000000); - if (msg != null) { - if (msg != null && rolledback.put(msg.getText(), Boolean.TRUE) != null) { - LOG.info("Received message " + msg.getText() + " (" + received.getAndIncrement() + ")" + msg.getJMSMessageID()); - assertTrue(msg.getJMSRedelivered()); - session.commit(); - } else { - LOG.info("Rollback message " + msg.getText() + " id: " + msg.getJMSMessageID()); - session.rollback(); - } - } + MessageConsumer consumer = session.createConsumer(destination); + TextMessage msg = (TextMessage) consumer.receive(6000000); + if (msg != null) { + if (msg != null && rolledback.put(msg.getText(), Boolean.TRUE) != null) { + LOG.info("Received message " + msg.getText() + " (" + received.getAndIncrement() + ")" + msg.getJMSMessageID()); + assertTrue(msg.getJMSRedelivered()); + assertEquals(2, msg.getLongProperty("JMSXDeliveryCount")); + session.commit(); + } + else { + LOG.info("Rollback message " + msg.getText() + " id: " + msg.getJMSMessageID()); + assertFalse("should not have redelivery flag set, id: " + msg.getJMSMessageID(), msg.getJMSRedelivered()); + session.rollback(); + } } consumer.close(); session.close(); - } - } + } + } + } + @Test + public void testRedeliveryOnSingleConsumer() throws Exception { - @Test - public void testRedeliveryOnSingleSession() throws Exception { + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl); + Connection connection = connectionFactory.createConnection(); + connection.start(); - ConnectionFactory connectionFactory = - new ActiveMQConnectionFactory(brokerUrl); - Connection connection = connectionFactory.createConnection(); - connection.start(); + populateDestinationWithInterleavedProducer(nbMessages, destinationName, connection); - populateDestination(nbMessages, destinationName, connection); + // Consume messages and rollback transactions + { + AtomicInteger received = new AtomicInteger(); + Map rolledback = new ConcurrentHashMap(); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue(destinationName); + MessageConsumer consumer = session.createConsumer(destination); + while (received.get() < nbMessages) { + TextMessage msg = (TextMessage) consumer.receive(6000000); + if (msg != null) { + if (msg != null && rolledback.put(msg.getText(), Boolean.TRUE) != null) { + LOG.info("Received message " + msg.getText() + " (" + received.getAndIncrement() + ")" + msg.getJMSMessageID()); + assertTrue(msg.getJMSRedelivered()); + session.commit(); + } + else { + LOG.info("Rollback message " + msg.getText() + " id: " + msg.getJMSMessageID()); + session.rollback(); + } + } + } + consumer.close(); + session.close(); + } + } - // Consume messages and rollback transactions - { - AtomicInteger received = new AtomicInteger(); - Map rolledback = new ConcurrentHashMap(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + @Test + public void testRedeliveryOnSingleSession() throws Exception { + + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl); + Connection connection = connectionFactory.createConnection(); + connection.start(); + + populateDestination(nbMessages, destinationName, connection); + + // Consume messages and rollback transactions + { + AtomicInteger received = new AtomicInteger(); + Map rolledback = new ConcurrentHashMap(); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue(destinationName); + while (received.get() < nbMessages) { + MessageConsumer consumer = session.createConsumer(destination); + TextMessage msg = (TextMessage) consumer.receive(6000000); + if (msg != null) { + if (msg != null && rolledback.put(msg.getText(), Boolean.TRUE) != null) { + LOG.info("Received message " + msg.getText() + " (" + received.getAndIncrement() + ")" + msg.getJMSMessageID()); + assertTrue(msg.getJMSRedelivered()); + session.commit(); + } + else { + LOG.info("Rollback message " + msg.getText() + " id: " + msg.getJMSMessageID()); + session.rollback(); + } + } + consumer.close(); + } + session.close(); + } + } + + // AMQ-1593 + @Test + public void testValidateRedeliveryCountOnRollback() throws Exception { + + final int numMessages = 1; + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl); + Connection connection = connectionFactory.createConnection(); + connection.start(); + + populateDestination(numMessages, destinationName, connection); + + { + AtomicInteger received = new AtomicInteger(); + final int maxRetries = new RedeliveryPolicy().getMaximumRedeliveries(); + while (received.get() < maxRetries) { + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); Destination destination = session.createQueue(destinationName); - while (received.get() < nbMessages) { - MessageConsumer consumer = session.createConsumer(destination); - TextMessage msg = (TextMessage) consumer.receive(6000000); - if (msg != null) { - if (msg != null && rolledback.put(msg.getText(), Boolean.TRUE) != null) { - LOG.info("Received message " + msg.getText() + " (" + received.getAndIncrement() + ")" + msg.getJMSMessageID()); - assertTrue(msg.getJMSRedelivered()); - session.commit(); - } else { - LOG.info("Rollback message " + msg.getText() + " id: " + msg.getJMSMessageID()); - session.rollback(); - } - } - consumer.close(); + + MessageConsumer consumer = session.createConsumer(destination); + TextMessage msg = (TextMessage) consumer.receive(1000); + if (msg != null) { + LOG.info("Received message " + msg.getText() + " (" + received.getAndIncrement() + ")" + msg.getJMSMessageID()); + assertEquals("redelivery property matches deliveries", received.get(), msg.getLongProperty("JMSXDeliveryCount")); + session.rollback(); } session.close(); - } - } - - // AMQ-1593 - @Test - public void testValidateRedeliveryCountOnRollback() throws Exception { + } + consumeMessage(connection, maxRetries + 1); + } + } - final int numMessages = 1; - ConnectionFactory connectionFactory = - new ActiveMQConnectionFactory(brokerUrl); - Connection connection = connectionFactory.createConnection(); - connection.start(); + // AMQ-1593 + @Test + public void testValidateRedeliveryCountOnRollbackWithPrefetch0() throws Exception { - populateDestination(numMessages, destinationName, connection); + final int numMessages = 1; + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl + "?jms.prefetchPolicy.queuePrefetch=0"); + Connection connection = connectionFactory.createConnection(); + connection.start(); - { - AtomicInteger received = new AtomicInteger(); - final int maxRetries = new RedeliveryPolicy().getMaximumRedeliveries(); - while (received.get() < maxRetries) { - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Destination destination = session.createQueue(destinationName); + populateDestination(numMessages, destinationName, connection); - MessageConsumer consumer = session.createConsumer(destination); - TextMessage msg = (TextMessage) consumer.receive(1000); - if (msg != null) { - LOG.info("Received message " + msg.getText() + " (" + received.getAndIncrement() + ")" + msg.getJMSMessageID()); - assertEquals("redelivery property matches deliveries", received.get(), msg.getLongProperty("JMSXDeliveryCount")); - session.rollback(); - } - session.close(); + { + AtomicInteger received = new AtomicInteger(); + final int maxRetries = new RedeliveryPolicy().getMaximumRedeliveries(); + while (received.get() < maxRetries) { + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + Destination destination = session.createQueue(destinationName); + + MessageConsumer consumer = session.createConsumer(destination); + TextMessage msg = (TextMessage) consumer.receive(1000); + if (msg != null) { + LOG.info("Received message " + msg.getText() + " (" + received.getAndIncrement() + ")" + msg.getJMSMessageID()); + assertEquals("redelivery property matches deliveries", received.get(), msg.getLongProperty("JMSXDeliveryCount")); + session.rollback(); } - consumeMessage(connection, maxRetries + 1); - } - } - - // AMQ-1593 - @Test - public void testValidateRedeliveryCountOnRollbackWithPrefetch0() throws Exception { + session.close(); + } - final int numMessages = 1; - ConnectionFactory connectionFactory = - new ActiveMQConnectionFactory(brokerUrl + "?jms.prefetchPolicy.queuePrefetch=0"); - Connection connection = connectionFactory.createConnection(); - connection.start(); + consumeMessage(connection, maxRetries + 1); + } + } - populateDestination(numMessages, destinationName, connection); + private void consumeMessage(Connection connection, final int deliveryCount) throws JMSException { + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + Destination destination = session.createQueue(destinationName); + MessageConsumer consumer = session.createConsumer(destination); + TextMessage msg = (TextMessage) consumer.receive(1000); + assertNotNull(msg); + assertEquals("redelivery property matches deliveries", deliveryCount, msg.getLongProperty("JMSXDeliveryCount")); + session.commit(); + session.close(); + } - { - AtomicInteger received = new AtomicInteger(); - final int maxRetries = new RedeliveryPolicy().getMaximumRedeliveries(); - while (received.get() < maxRetries) { - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Destination destination = session.createQueue(destinationName); + @Test + public void testRedeliveryPropertyWithNoRollback() throws Exception { + final int numMessages = 1; + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl); + Connection connection = connectionFactory.createConnection(); + connection.start(); - MessageConsumer consumer = session.createConsumer(destination); - TextMessage msg = (TextMessage) consumer.receive(1000); - if (msg != null) { - LOG.info("Received message " + msg.getText() + " (" + received.getAndIncrement() + ")" + msg.getJMSMessageID()); - assertEquals("redelivery property matches deliveries", received.get(), msg.getLongProperty("JMSXDeliveryCount")); - session.rollback(); - } - session.close(); - } - - consumeMessage(connection, maxRetries + 1); - } - } + populateDestination(numMessages, destinationName, connection); + connection.close(); - - private void consumeMessage(Connection connection, final int deliveryCount) - throws JMSException { - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Destination destination = session.createQueue(destinationName); - MessageConsumer consumer = session.createConsumer(destination); - TextMessage msg = (TextMessage) consumer.receive(1000); - assertNotNull(msg); - assertEquals("redelivery property matches deliveries", deliveryCount, msg.getLongProperty("JMSXDeliveryCount")); - session.commit(); - session.close(); - } - - @Test - public void testRedeliveryPropertyWithNoRollback() throws Exception { - final int numMessages = 1; - ConnectionFactory connectionFactory = - new ActiveMQConnectionFactory(brokerUrl); - Connection connection = connectionFactory.createConnection(); - connection.start(); - - populateDestination(numMessages, destinationName, connection); - connection.close(); - - { - AtomicInteger received = new AtomicInteger(); - final int maxRetries = new RedeliveryPolicy().getMaximumRedeliveries(); - while (received.get() < maxRetries) { - connection = connectionFactory.createConnection(); - connection.start(); - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Destination destination = session.createQueue(destinationName); - - MessageConsumer consumer = session.createConsumer(destination); - TextMessage msg = (TextMessage) consumer.receive(2000); - if (msg != null) { - LOG.info("Received message " + msg.getText() + " (" + received.getAndIncrement() + ")" + msg.getJMSMessageID()); - assertEquals("redelivery property matches deliveries", received.get(), msg.getLongProperty("JMSXDeliveryCount")); - } - session.close(); - connection.close(); - } + { + AtomicInteger received = new AtomicInteger(); + final int maxRetries = new RedeliveryPolicy().getMaximumRedeliveries(); + while (received.get() < maxRetries) { connection = connectionFactory.createConnection(); connection.start(); - consumeMessage(connection, maxRetries + 1); - } - } - - private void populateDestination(final int nbMessages, - final String destinationName, Connection connection) - throws JMSException { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(destinationName); - MessageProducer producer = session.createProducer(destination); - for (int i = 1; i <= nbMessages; i++) { - producer.send(session.createTextMessage("")); - } - producer.close(); - session.close(); - } + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + Destination destination = session.createQueue(destinationName); - - private void populateDestinationWithInterleavedProducer(final int nbMessages, - final String destinationName, Connection connection) - throws JMSException { - Session session1 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination1 = session1.createQueue(destinationName); - MessageProducer producer1 = session1.createProducer(destination1); - Session session2 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination2 = session2.createQueue(destinationName); - MessageProducer producer2 = session2.createProducer(destination2); - - for (int i = 1; i <= nbMessages; i++) { - if (i%2 == 0) { - producer1.send(session1.createTextMessage("")); - } else { - producer2.send(session2.createTextMessage("")); + MessageConsumer consumer = session.createConsumer(destination); + TextMessage msg = (TextMessage) consumer.receive(2000); + if (msg != null) { + LOG.info("Received message " + msg.getText() + " (" + received.getAndIncrement() + ")" + msg.getJMSMessageID()); + assertEquals("redelivery property matches deliveries", received.get(), msg.getLongProperty("JMSXDeliveryCount")); } - } - producer1.close(); - session1.close(); - producer2.close(); - session2.close(); - } + session.close(); + connection.close(); + } + connection = connectionFactory.createConnection(); + connection.start(); + consumeMessage(connection, maxRetries + 1); + } + } + + private void populateDestination(final int nbMessages, + final String destinationName, + Connection connection) throws JMSException { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue(destinationName); + MessageProducer producer = session.createProducer(destination); + for (int i = 1; i <= nbMessages; i++) { + producer.send(session.createTextMessage("")); + } + producer.close(); + session.close(); + } + + private void populateDestinationWithInterleavedProducer(final int nbMessages, + final String destinationName, + Connection connection) throws JMSException { + Session session1 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination1 = session1.createQueue(destinationName); + MessageProducer producer1 = session1.createProducer(destination1); + Session session2 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination2 = session2.createQueue(destinationName); + MessageProducer producer2 = session2.createProducer(destination2); + + for (int i = 1; i <= nbMessages; i++) { + if (i % 2 == 0) { + producer1.send(session1.createTextMessage("")); + } + else { + producer2.send(session2.createTextMessage("")); + } + } + producer1.close(); + session1.close(); + producer2.close(); + session2.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsSendReceiveTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsSendReceiveTestSupport.java index d852f54946..b3c2d37e18 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsSendReceiveTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsSendReceiveTestSupport.java @@ -37,201 +37,205 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class JmsSendReceiveTestSupport extends TestSupport implements MessageListener { - private static final Logger LOG = LoggerFactory.getLogger(JmsSendReceiveTestSupport.class); - protected int messageCount = 100; - protected String[] data; - protected Session session; - protected MessageConsumer consumer; - protected MessageProducer producer; - protected Destination consumerDestination; - protected Destination producerDestination; - protected List messages = createConcurrentList(); - protected boolean topic = true; - protected boolean durable; - protected int deliveryMode = DeliveryMode.PERSISTENT; - protected final Object lock = new Object(); - protected boolean verbose; + private static final Logger LOG = LoggerFactory.getLogger(JmsSendReceiveTestSupport.class); - /* - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - String temp = System.getProperty("messageCount"); + protected int messageCount = 100; + protected String[] data; + protected Session session; + protected MessageConsumer consumer; + protected MessageProducer producer; + protected Destination consumerDestination; + protected Destination producerDestination; + protected List messages = createConcurrentList(); + protected boolean topic = true; + protected boolean durable; + protected int deliveryMode = DeliveryMode.PERSISTENT; + protected final Object lock = new Object(); + protected boolean verbose; - if (temp != null) { - int i = Integer.parseInt(temp); - if (i > 0) { - messageCount = i; - } - } + /* + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + String temp = System.getProperty("messageCount"); - LOG.info("Message count for test case is: " + messageCount); - data = new String[messageCount]; + if (temp != null) { + int i = Integer.parseInt(temp); + if (i > 0) { + messageCount = i; + } + } - for (int i = 0; i < messageCount; i++) { - data[i] = "Text for message: " + i + " at " + new Date(); - } - } + LOG.info("Message count for test case is: " + messageCount); + data = new String[messageCount]; - /** - * Sends and consumes the messages. - * - * @throws Exception - */ - public void testSendReceive() throws Exception { - messages.clear(); - for (int i = 0; i < data.length; i++) { - Message message = session.createTextMessage(data[i]); - message.setStringProperty("stringProperty", data[i]); - message.setIntProperty("intProperty", i); + for (int i = 0; i < messageCount; i++) { + data[i] = "Text for message: " + i + " at " + new Date(); + } + } - if (verbose) { - if (LOG.isDebugEnabled()) { - LOG.debug("About to send a message: " + message + " with text: " + data[i]); - } - } + /** + * Sends and consumes the messages. + * + * @throws Exception + */ + public void testSendReceive() throws Exception { + messages.clear(); + for (int i = 0; i < data.length; i++) { + Message message = session.createTextMessage(data[i]); + message.setStringProperty("stringProperty", data[i]); + message.setIntProperty("intProperty", i); - sendToProducer(producer, producerDestination, message); - messageSent(); - } - - assertMessagesAreReceived(); - LOG.info("" + data.length + " messages(s) received, closing down connections"); - } - - /** - * Sends a message to a destination using the supplied producer - * @param producer - * @param producerDestination - * @param message - * @throws JMSException - */ - protected void sendToProducer(MessageProducer producer, - Destination producerDestination, Message message) throws JMSException { - producer.send(producerDestination, message); - } - - /** - * Asserts messages are received. - * - * @throws JMSException - */ - protected void assertMessagesAreReceived() throws JMSException { - waitForMessagesToBeDelivered(); - assertMessagesReceivedAreValid(messages); - } - - /** - * Tests if the messages received are valid. - * - * @param receivedMessages - list of received messages. - * @throws JMSException - */ - protected void assertMessagesReceivedAreValid(List receivedMessages) throws JMSException { - List copyOfMessages = Arrays.asList(receivedMessages.toArray()); - int counter = 0; - - if (data.length != copyOfMessages.size()) { - for (Iterator iter = copyOfMessages.iterator(); iter.hasNext();) { - TextMessage message = (TextMessage)iter.next(); - if (LOG.isInfoEnabled()) { - LOG.info("<== " + counter++ + " = " + message.getText()); - } - } - } - - assertEquals("Not enough messages received", data.length, receivedMessages.size()); - - for (int i = 0; i < data.length; i++) { - TextMessage received = (TextMessage)receivedMessages.get(i); - String text = received.getText(); - String stringProperty = received.getStringProperty("stringProperty"); - int intProperty = received.getIntProperty("intProperty"); - - if (verbose) { - if (LOG.isDebugEnabled()) { - LOG.info("Received Text: " + text); - } - } - - assertEquals("Message: " + i, data[i], text); - assertEquals(data[i], stringProperty); - assertEquals(i, intProperty); - } - } - - /** - * Waits for messages to be delivered. - */ - protected void waitForMessagesToBeDelivered() { - long maxWaitTime = 60000; - long waitTime = maxWaitTime; - long start = (maxWaitTime <= 0) ? 0 : System.currentTimeMillis(); - - synchronized (lock) { - while (messages.size() < data.length && waitTime >= 0) { - try { - lock.wait(200); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - waitTime = maxWaitTime - (System.currentTimeMillis() - start); - } - } - } - - /* - * (non-Javadoc) - * - * @see javax.jms.MessageListener#onMessage(javax.jms.Message) - */ - public synchronized void onMessage(Message message) { - consumeMessage(message, messages); - } - - /** - * Consumes messages. - * - * @param message - message to be consumed. - * @param messageList -list of consumed messages. - */ - protected void consumeMessage(Message message, List messageList) { - if (verbose) { + if (verbose) { if (LOG.isDebugEnabled()) { - LOG.info("Received message: " + message); + LOG.debug("About to send a message: " + message + " with text: " + data[i]); } - } + } - messageList.add(message); + sendToProducer(producer, producerDestination, message); + messageSent(); + } - if (messageList.size() >= data.length) { - synchronized (lock) { - lock.notifyAll(); + assertMessagesAreReceived(); + LOG.info("" + data.length + " messages(s) received, closing down connections"); + } + + /** + * Sends a message to a destination using the supplied producer + * + * @param producer + * @param producerDestination + * @param message + * @throws JMSException + */ + protected void sendToProducer(MessageProducer producer, + Destination producerDestination, + Message message) throws JMSException { + producer.send(producerDestination, message); + } + + /** + * Asserts messages are received. + * + * @throws JMSException + */ + protected void assertMessagesAreReceived() throws JMSException { + waitForMessagesToBeDelivered(); + assertMessagesReceivedAreValid(messages); + } + + /** + * Tests if the messages received are valid. + * + * @param receivedMessages - list of received messages. + * @throws JMSException + */ + protected void assertMessagesReceivedAreValid(List receivedMessages) throws JMSException { + List copyOfMessages = Arrays.asList(receivedMessages.toArray()); + int counter = 0; + + if (data.length != copyOfMessages.size()) { + for (Iterator iter = copyOfMessages.iterator(); iter.hasNext(); ) { + TextMessage message = (TextMessage) iter.next(); + if (LOG.isInfoEnabled()) { + LOG.info("<== " + counter++ + " = " + message.getText()); } - } - } + } + } - /** - * Returns the ArrayList as a synchronized list. - * - * @return List - */ - protected List createConcurrentList() { - return Collections.synchronizedList(new ArrayList()); - } + assertEquals("Not enough messages received", data.length, receivedMessages.size()); - /** - * Just a hook so can insert failure tests - * - * @throws Exception - */ - protected void messageSent() throws Exception { + for (int i = 0; i < data.length; i++) { + TextMessage received = (TextMessage) receivedMessages.get(i); + String text = received.getText(); + String stringProperty = received.getStringProperty("stringProperty"); + int intProperty = received.getIntProperty("intProperty"); - } + if (verbose) { + if (LOG.isDebugEnabled()) { + LOG.info("Received Text: " + text); + } + } + + assertEquals("Message: " + i, data[i], text); + assertEquals(data[i], stringProperty); + assertEquals(i, intProperty); + } + } + + /** + * Waits for messages to be delivered. + */ + protected void waitForMessagesToBeDelivered() { + long maxWaitTime = 60000; + long waitTime = maxWaitTime; + long start = (maxWaitTime <= 0) ? 0 : System.currentTimeMillis(); + + synchronized (lock) { + while (messages.size() < data.length && waitTime >= 0) { + try { + lock.wait(200); + } + catch (InterruptedException e) { + e.printStackTrace(); + } + + waitTime = maxWaitTime - (System.currentTimeMillis() - start); + } + } + } + + /* + * (non-Javadoc) + * + * @see javax.jms.MessageListener#onMessage(javax.jms.Message) + */ + public synchronized void onMessage(Message message) { + consumeMessage(message, messages); + } + + /** + * Consumes messages. + * + * @param message - message to be consumed. + * @param messageList -list of consumed messages. + */ + protected void consumeMessage(Message message, List messageList) { + if (verbose) { + if (LOG.isDebugEnabled()) { + LOG.info("Received message: " + message); + } + } + + messageList.add(message); + + if (messageList.size() >= data.length) { + synchronized (lock) { + lock.notifyAll(); + } + } + } + + /** + * Returns the ArrayList as a synchronized list. + * + * @return List + */ + protected List createConcurrentList() { + return Collections.synchronizedList(new ArrayList()); + } + + /** + * Just a hook so can insert failure tests + * + * @throws Exception + */ + protected void messageSent() throws Exception { + + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsSendReceiveWithMessageExpirationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsSendReceiveWithMessageExpirationTest.java index 391253ee70..f7889dc3ba 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsSendReceiveWithMessageExpirationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsSendReceiveWithMessageExpirationTest.java @@ -42,269 +42,269 @@ import org.slf4j.LoggerFactory; */ public class JmsSendReceiveWithMessageExpirationTest extends TestSupport { - private static final Logger LOG = LoggerFactory.getLogger(JmsSendReceiveWithMessageExpirationTest.class); + private static final Logger LOG = LoggerFactory.getLogger(JmsSendReceiveWithMessageExpirationTest.class); - protected int messageCount = 100; - protected String[] data; - protected Session session; - protected Destination consumerDestination; - protected Destination producerDestination; - protected boolean durable; - protected int deliveryMode = DeliveryMode.PERSISTENT; - protected long timeToLive = 5000; - protected boolean verbose; + protected int messageCount = 100; + protected String[] data; + protected Session session; + protected Destination consumerDestination; + protected Destination producerDestination; + protected boolean durable; + protected int deliveryMode = DeliveryMode.PERSISTENT; + protected long timeToLive = 5000; + protected boolean verbose; - protected Connection connection; + protected Connection connection; - protected void setUp() throws Exception { + protected void setUp() throws Exception { - super.setUp(); + super.setUp(); - data = new String[messageCount]; + data = new String[messageCount]; - for (int i = 0; i < messageCount; i++) { - data[i] = "Text for message: " + i + " at " + new Date(); - } + for (int i = 0; i < messageCount; i++) { + data[i] = "Text for message: " + i + " at " + new Date(); + } - connectionFactory = createConnectionFactory(); - connection = createConnection(); + connectionFactory = createConnectionFactory(); + connection = createConnection(); - if (durable) { - connection.setClientID(getClass().getName()); - } + if (durable) { + connection.setClientID(getClass().getName()); + } - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + } - /** - * Test consuming an expired queue. - * - * @throws Exception - */ - public void testConsumeExpiredQueue() throws Exception { + /** + * Test consuming an expired queue. + * + * @throws Exception + */ + public void testConsumeExpiredQueue() throws Exception { - MessageProducer producer = createProducer(timeToLive); + MessageProducer producer = createProducer(timeToLive); - consumerDestination = session.createQueue(getConsumerSubject()); - producerDestination = session.createQueue(getProducerSubject()); + consumerDestination = session.createQueue(getConsumerSubject()); + producerDestination = session.createQueue(getProducerSubject()); - MessageConsumer consumer = createConsumer(); - connection.start(); + MessageConsumer consumer = createConsumer(); + connection.start(); - for (int i = 0; i < data.length; i++) { - Message message = session.createTextMessage(data[i]); - message.setStringProperty("stringProperty", data[i]); - message.setIntProperty("intProperty", i); + for (int i = 0; i < data.length; i++) { + Message message = session.createTextMessage(data[i]); + message.setStringProperty("stringProperty", data[i]); + message.setIntProperty("intProperty", i); - if (verbose) { - if (LOG.isDebugEnabled()) { - LOG.debug("About to send a queue message: " + message + " with text: " + data[i]); - } + if (verbose) { + if (LOG.isDebugEnabled()) { + LOG.debug("About to send a queue message: " + message + " with text: " + data[i]); } - - producer.send(producerDestination, message); - } - - // sleeps a second longer than the expiration time. - // Basically waits till queue expires. - Thread.sleep(timeToLive + 1000); - - // message should have expired. - assertNull(consumer.receive(1000)); - } - - public void testConsumeExpiredQueueAndDlq() throws Exception { - - MessageProducer producerNormal = createProducer(0); - MessageProducer producerExpire = createProducer(500); - - consumerDestination = session.createQueue("ActiveMQ.DLQ"); - MessageConsumer dlqConsumer = createConsumer(); - - consumerDestination = session.createQueue(getConsumerSubject()); - producerDestination = session.createQueue(getProducerSubject()); - - - Connection consumerConnection = createConnection(); - ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); - prefetchPolicy.setAll(10); - ((ActiveMQConnection)consumerConnection).setPrefetchPolicy(prefetchPolicy); - Session consumerSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = consumerSession.createConsumer(consumerDestination); - consumerConnection.start(); - connection.start(); - - String msgBody = new String(new byte[20*1024]); - for (int i = 0; i < data.length; i++) { - Message message = session.createTextMessage(msgBody); - producerExpire.send(producerDestination, message); } - for (int i = 0; i < data.length; i++) { - Message message = session.createTextMessage(msgBody); - producerNormal.send(producerDestination, message); + producer.send(producerDestination, message); + } + + // sleeps a second longer than the expiration time. + // Basically waits till queue expires. + Thread.sleep(timeToLive + 1000); + + // message should have expired. + assertNull(consumer.receive(1000)); + } + + public void testConsumeExpiredQueueAndDlq() throws Exception { + + MessageProducer producerNormal = createProducer(0); + MessageProducer producerExpire = createProducer(500); + + consumerDestination = session.createQueue("ActiveMQ.DLQ"); + MessageConsumer dlqConsumer = createConsumer(); + + consumerDestination = session.createQueue(getConsumerSubject()); + producerDestination = session.createQueue(getProducerSubject()); + + Connection consumerConnection = createConnection(); + ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); + prefetchPolicy.setAll(10); + ((ActiveMQConnection) consumerConnection).setPrefetchPolicy(prefetchPolicy); + Session consumerSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + MessageConsumer consumer = consumerSession.createConsumer(consumerDestination); + consumerConnection.start(); + connection.start(); + + String msgBody = new String(new byte[20 * 1024]); + for (int i = 0; i < data.length; i++) { + Message message = session.createTextMessage(msgBody); + producerExpire.send(producerDestination, message); + } + + for (int i = 0; i < data.length; i++) { + Message message = session.createTextMessage(msgBody); + producerNormal.send(producerDestination, message); + } + + Vector messages = new Vector(); + Message received; + while ((received = consumer.receive(1000)) != null) { + messages.add(received); + if (messages.size() == 1) { + TimeUnit.SECONDS.sleep(1); + } + received.acknowledge(); + } + ; + + assertEquals("got all (normal plus one with ttl) messages", messageCount + 1, messages.size()); + + Vector dlqMessages = new Vector(); + while ((received = dlqConsumer.receive(1000)) != null) { + dlqMessages.add(received); + } + ; + + assertEquals("got dlq messages", data.length - 1, dlqMessages.size()); + + final DestinationStatistics view = getDestinationStatistics(BrokerRegistry.getInstance().findFirst(), ActiveMQDestination.transform(consumerDestination)); + + // wait for all to inflight to expire + assertTrue("all inflight messages expired ", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return view.getInflight().getCount() == 0; + } + })); + assertEquals("Wrong inFlightCount: ", 0, view.getInflight().getCount()); + + LOG.info("Stats: received: " + messages.size() + ", messages: " + view.getMessages().getCount() + ", enqueues: " + view.getEnqueues().getCount() + ", dequeues: " + view.getDequeues().getCount() + ", dispatched: " + view.getDispatched().getCount() + ", inflight: " + view.getInflight().getCount() + ", expired: " + view.getExpired().getCount()); + + } + + /** + * Sends and consumes the messages to a queue destination. + * + * @throws Exception + */ + public void testConsumeQueue() throws Exception { + + MessageProducer producer = createProducer(0); + + consumerDestination = session.createQueue(getConsumerSubject()); + producerDestination = session.createQueue(getProducerSubject()); + + MessageConsumer consumer = createConsumer(); + connection.start(); + + for (int i = 0; i < data.length; i++) { + Message message = session.createTextMessage(data[i]); + message.setStringProperty("stringProperty", data[i]); + message.setIntProperty("intProperty", i); + + if (verbose) { + if (LOG.isDebugEnabled()) { + LOG.debug("About to send a queue message: " + message + " with text: " + data[i]); + } } - Vector messages = new Vector(); - Message received; - while ((received = consumer.receive(1000)) != null) { - messages.add(received); - if (messages.size() == 1) { - TimeUnit.SECONDS.sleep(1); - } - received.acknowledge(); - }; + producer.send(producerDestination, message); + } - assertEquals("got all (normal plus one with ttl) messages", messageCount + 1, messages.size()); + // should receive a queue since there is no expiration. + assertNotNull(consumer.receive(1000)); + } - Vector dlqMessages = new Vector(); - while ((received = dlqConsumer.receive(1000)) != null) { - dlqMessages.add(received); - }; + /** + * Test consuming an expired topic. + * + * @throws Exception + */ + public void testConsumeExpiredTopic() throws Exception { - assertEquals("got dlq messages", data.length - 1, dlqMessages.size()); + MessageProducer producer = createProducer(timeToLive); - final DestinationStatistics view = getDestinationStatistics(BrokerRegistry.getInstance().findFirst(), ActiveMQDestination.transform(consumerDestination)); + consumerDestination = session.createTopic(getConsumerSubject()); + producerDestination = session.createTopic(getProducerSubject()); - // wait for all to inflight to expire - assertTrue("all inflight messages expired ", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return view.getInflight().getCount() == 0; - } - })); - assertEquals("Wrong inFlightCount: ", 0, view.getInflight().getCount()); + MessageConsumer consumer = createConsumer(); + connection.start(); - LOG.info("Stats: received: " + messages.size() + ", messages: " + view.getMessages().getCount() + ", enqueues: " + view.getEnqueues().getCount() + ", dequeues: " + view.getDequeues().getCount() - + ", dispatched: " + view.getDispatched().getCount() + ", inflight: " + view.getInflight().getCount() + ", expired: " + view.getExpired().getCount()); + for (int i = 0; i < data.length; i++) { + Message message = session.createTextMessage(data[i]); + message.setStringProperty("stringProperty", data[i]); + message.setIntProperty("intProperty", i); - } - - /** - * Sends and consumes the messages to a queue destination. - * - * @throws Exception - */ - public void testConsumeQueue() throws Exception { - - MessageProducer producer = createProducer(0); - - consumerDestination = session.createQueue(getConsumerSubject()); - producerDestination = session.createQueue(getProducerSubject()); - - MessageConsumer consumer = createConsumer(); - connection.start(); - - for (int i = 0; i < data.length; i++) { - Message message = session.createTextMessage(data[i]); - message.setStringProperty("stringProperty", data[i]); - message.setIntProperty("intProperty", i); - - if (verbose) { - if (LOG.isDebugEnabled()) { - LOG.debug("About to send a queue message: " + message + " with text: " + data[i]); - } + if (verbose) { + if (LOG.isDebugEnabled()) { + LOG.debug("About to send a topic message: " + message + " with text: " + data[i]); } + } - producer.send(producerDestination, message); - } + producer.send(producerDestination, message); + } - // should receive a queue since there is no expiration. - assertNotNull(consumer.receive(1000)); - } + // sleeps a second longer than the expiration time. + // Basically waits till topic expires. + Thread.sleep(timeToLive + 1000); - /** - * Test consuming an expired topic. - * - * @throws Exception - */ - public void testConsumeExpiredTopic() throws Exception { + // message should have expired. + assertNull(consumer.receive(1000)); + } - MessageProducer producer = createProducer(timeToLive); + /** + * Sends and consumes the messages to a topic destination. + * + * @throws Exception + */ + public void testConsumeTopic() throws Exception { - consumerDestination = session.createTopic(getConsumerSubject()); - producerDestination = session.createTopic(getProducerSubject()); + MessageProducer producer = createProducer(0); - MessageConsumer consumer = createConsumer(); - connection.start(); + consumerDestination = session.createTopic(getConsumerSubject()); + producerDestination = session.createTopic(getProducerSubject()); - for (int i = 0; i < data.length; i++) { - Message message = session.createTextMessage(data[i]); - message.setStringProperty("stringProperty", data[i]); - message.setIntProperty("intProperty", i); + MessageConsumer consumer = createConsumer(); + connection.start(); - if (verbose) { - if (LOG.isDebugEnabled()) { - LOG.debug("About to send a topic message: " + message + " with text: " + data[i]); - } + for (int i = 0; i < data.length; i++) { + Message message = session.createTextMessage(data[i]); + message.setStringProperty("stringProperty", data[i]); + message.setIntProperty("intProperty", i); + + if (verbose) { + if (LOG.isDebugEnabled()) { + LOG.debug("About to send a topic message: " + message + " with text: " + data[i]); } + } - producer.send(producerDestination, message); - } + producer.send(producerDestination, message); + } - // sleeps a second longer than the expiration time. - // Basically waits till topic expires. - Thread.sleep(timeToLive + 1000); + // should receive a topic since there is no expiration. + assertNotNull(consumer.receive(1000)); + } - // message should have expired. - assertNull(consumer.receive(1000)); - } + protected MessageProducer createProducer(long timeToLive) throws JMSException { + MessageProducer producer = session.createProducer(null); + producer.setDeliveryMode(deliveryMode); + producer.setTimeToLive(timeToLive); - /** - * Sends and consumes the messages to a topic destination. - * - * @throws Exception - */ - public void testConsumeTopic() throws Exception { + return producer; + } - MessageProducer producer = createProducer(0); + protected MessageConsumer createConsumer() throws JMSException { + if (durable) { + LOG.info("Creating durable consumer"); + return session.createDurableSubscriber((Topic) consumerDestination, getName()); + } + return session.createConsumer(consumerDestination); + } - consumerDestination = session.createTopic(getConsumerSubject()); - producerDestination = session.createTopic(getProducerSubject()); + protected void tearDown() throws Exception { + LOG.info("Dumping stats..."); + LOG.info("Closing down connection"); - MessageConsumer consumer = createConsumer(); - connection.start(); - - for (int i = 0; i < data.length; i++) { - Message message = session.createTextMessage(data[i]); - message.setStringProperty("stringProperty", data[i]); - message.setIntProperty("intProperty", i); - - if (verbose) { - if (LOG.isDebugEnabled()) { - LOG.debug("About to send a topic message: " + message + " with text: " + data[i]); - } - } - - producer.send(producerDestination, message); - } - - // should receive a topic since there is no expiration. - assertNotNull(consumer.receive(1000)); - } - - protected MessageProducer createProducer(long timeToLive) throws JMSException { - MessageProducer producer = session.createProducer(null); - producer.setDeliveryMode(deliveryMode); - producer.setTimeToLive(timeToLive); - - return producer; - } - - protected MessageConsumer createConsumer() throws JMSException { - if (durable) { - LOG.info("Creating durable consumer"); - return session.createDurableSubscriber((Topic)consumerDestination, getName()); - } - return session.createConsumer(consumerDestination); - } - - protected void tearDown() throws Exception { - LOG.info("Dumping stats..."); - LOG.info("Closing down connection"); - - session.close(); - connection.close(); - } + session.close(); + connection.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsSendWithAsyncCallbackTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsSendWithAsyncCallbackTest.java index cf14453668..f2717d283e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsSendWithAsyncCallbackTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsSendWithAsyncCallbackTest.java @@ -35,93 +35,93 @@ import org.slf4j.LoggerFactory; */ public class JmsSendWithAsyncCallbackTest extends TestSupport { - private static final Logger LOG = LoggerFactory.getLogger(JmsSendWithAsyncCallbackTest.class); + private static final Logger LOG = LoggerFactory.getLogger(JmsSendWithAsyncCallbackTest.class); - private Connection connection; + private Connection connection; - @Override - protected void setUp() throws Exception { - super.setUp(); - connection = createConnection(); - } + @Override + protected void setUp() throws Exception { + super.setUp(); + connection = createConnection(); + } - /** - * @see junit.framework.TestCase#tearDown() - */ - @Override - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - connection = null; - } - super.tearDown(); - } + /** + * @see junit.framework.TestCase#tearDown() + */ + @Override + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + connection = null; + } + super.tearDown(); + } - public void testAsyncCallbackIsFaster() throws JMSException, InterruptedException { - connection.start(); + public void testAsyncCallbackIsFaster() throws JMSException, InterruptedException { + connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createQueue(getName()); + 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() { + // 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); + } + + private double benchmarkNonCallbackRate() throws JMSException { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = session.createQueue(getName()); + int count = 1000; + ActiveMQMessageProducer producer = (ActiveMQMessageProducer) session.createProducer(queue); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + long start = System.currentTimeMillis(); + for (int i = 0; i < count; i++) { + producer.send(session.createTextMessage("Hello")); + } + return 1000.0 * count / (System.currentTimeMillis() - start); + } + + private double benchmarkCallbackRate() throws JMSException, InterruptedException { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = session.createQueue(getName()); + int count = 1000; + final CountDownLatch messagesSent = new CountDownLatch(count); + ActiveMQMessageProducer producer = (ActiveMQMessageProducer) session.createProducer(queue); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + long start = System.currentTimeMillis(); + for (int i = 0; i < count; i++) { + producer.send(session.createTextMessage("Hello"), new AsyncCallback() { @Override - public void onMessage(Message message) { + public void onSuccess() { + messagesSent.countDown(); } - }); - // 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); - } - - private double benchmarkNonCallbackRate() throws JMSException { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createQueue(getName()); - int count = 1000; - ActiveMQMessageProducer producer = (ActiveMQMessageProducer) session.createProducer(queue); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - long start = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - producer.send(session.createTextMessage("Hello")); - } - return 1000.0 * count / (System.currentTimeMillis() - start); - } - - private double benchmarkCallbackRate() throws JMSException, InterruptedException { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createQueue(getName()); - int count = 1000; - final CountDownLatch messagesSent = new CountDownLatch(count); - ActiveMQMessageProducer producer = (ActiveMQMessageProducer) session.createProducer(queue); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - long start = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - producer.send(session.createTextMessage("Hello"), new AsyncCallback() { - @Override - public void onSuccess() { - messagesSent.countDown(); - } - - @Override - public void onException(JMSException exception) { - exception.printStackTrace(); - } - }); - } - messagesSent.await(); - return 1000.0 * count / (System.currentTimeMillis() - start); - } + @Override + public void onException(JMSException exception) { + exception.printStackTrace(); + } + }); + } + messagesSent.await(); + return 1000.0 * count / (System.currentTimeMillis() - start); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsSessionRecoverTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsSessionRecoverTest.java index a6908a0afa..f0737241eb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsSessionRecoverTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsSessionRecoverTest.java @@ -31,264 +31,261 @@ import javax.jms.Session; import javax.jms.TextMessage; import junit.framework.TestCase; + import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTopic; /** * Testcases to see if Session.recover() work. - * - * */ public class JmsSessionRecoverTest extends TestCase { - private Connection connection; - private ActiveMQConnectionFactory factory; - private Destination dest; + private Connection connection; + private ActiveMQConnectionFactory factory; + private Destination dest; - /** - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception { - factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); - connection = factory.createConnection(); - } + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); + connection = factory.createConnection(); + } - /** - * @see junit.framework.TestCase#tearDown() - */ - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - connection = null; - } - } + /** + * @see junit.framework.TestCase#tearDown() + */ + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + connection = null; + } + } - /** - * - * @throws JMSException - * @throws InterruptedException - */ - public void testQueueSynchRecover() throws JMSException, InterruptedException { - dest = new ActiveMQQueue("Queue-" + System.currentTimeMillis()); - doTestSynchRecover(); - } + /** + * @throws JMSException + * @throws InterruptedException + */ + public void testQueueSynchRecover() throws JMSException, InterruptedException { + dest = new ActiveMQQueue("Queue-" + System.currentTimeMillis()); + doTestSynchRecover(); + } - /** - * - * @throws JMSException - * @throws InterruptedException - */ - public void testQueueAsynchRecover() throws JMSException, InterruptedException { - dest = new ActiveMQQueue("Queue-" + System.currentTimeMillis()); - doTestAsynchRecover(); - } + /** + * @throws JMSException + * @throws InterruptedException + */ + public void testQueueAsynchRecover() throws JMSException, InterruptedException { + dest = new ActiveMQQueue("Queue-" + System.currentTimeMillis()); + doTestAsynchRecover(); + } - /** - * - * @throws JMSException - * @throws InterruptedException - */ - public void testTopicSynchRecover() throws JMSException, InterruptedException { - dest = new ActiveMQTopic("Topic-" + System.currentTimeMillis()); - doTestSynchRecover(); - } + /** + * @throws JMSException + * @throws InterruptedException + */ + public void testTopicSynchRecover() throws JMSException, InterruptedException { + dest = new ActiveMQTopic("Topic-" + System.currentTimeMillis()); + doTestSynchRecover(); + } - /** - * - * @throws JMSException - * @throws InterruptedException - */ - public void testTopicAsynchRecover() throws JMSException, InterruptedException { - dest = new ActiveMQTopic("Topic-" + System.currentTimeMillis()); - doTestAsynchRecover(); - } + /** + * @throws JMSException + * @throws InterruptedException + */ + public void testTopicAsynchRecover() throws JMSException, InterruptedException { + dest = new ActiveMQTopic("Topic-" + System.currentTimeMillis()); + doTestAsynchRecover(); + } - /** - * - * @throws JMSException - * @throws InterruptedException - */ - public void testQueueAsynchRecoverWithAutoAck() throws JMSException, InterruptedException { - dest = new ActiveMQQueue("Queue-" + System.currentTimeMillis()); - doTestAsynchRecoverWithAutoAck(); - } + /** + * @throws JMSException + * @throws InterruptedException + */ + public void testQueueAsynchRecoverWithAutoAck() throws JMSException, InterruptedException { + dest = new ActiveMQQueue("Queue-" + System.currentTimeMillis()); + doTestAsynchRecoverWithAutoAck(); + } - /** - * - * @throws JMSException - * @throws InterruptedException - */ - public void testTopicAsynchRecoverWithAutoAck() throws JMSException, InterruptedException { - dest = new ActiveMQTopic("Topic-" + System.currentTimeMillis()); - doTestAsynchRecoverWithAutoAck(); - } + /** + * @throws JMSException + * @throws InterruptedException + */ + public void testTopicAsynchRecoverWithAutoAck() throws JMSException, InterruptedException { + dest = new ActiveMQTopic("Topic-" + System.currentTimeMillis()); + doTestAsynchRecoverWithAutoAck(); + } - /** - * Test to make sure that a Sync recover works. - * - * @throws JMSException - */ - public void doTestSynchRecover() throws JMSException { - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(dest); - connection.start(); + /** + * Test to make sure that a Sync recover works. + * + * @throws JMSException + */ + public void doTestSynchRecover() throws JMSException { + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(dest); + connection.start(); - MessageProducer producer = session.createProducer(dest); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - producer.send(session.createTextMessage("First")); - producer.send(session.createTextMessage("Second")); + MessageProducer producer = session.createProducer(dest); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + producer.send(session.createTextMessage("First")); + producer.send(session.createTextMessage("Second")); - TextMessage message = (TextMessage)consumer.receive(1000); - assertEquals("First", message.getText()); - assertFalse(message.getJMSRedelivered()); - message.acknowledge(); + TextMessage message = (TextMessage) consumer.receive(1000); + assertEquals("First", message.getText()); + assertFalse(message.getJMSRedelivered()); + message.acknowledge(); - message = (TextMessage)consumer.receive(1000); - assertEquals("Second", message.getText()); - assertFalse(message.getJMSRedelivered()); + message = (TextMessage) consumer.receive(1000); + assertEquals("Second", message.getText()); + assertFalse(message.getJMSRedelivered()); - session.recover(); + session.recover(); - message = (TextMessage)consumer.receive(2000); - assertEquals("Second", message.getText()); - assertTrue(message.getJMSRedelivered()); + message = (TextMessage) consumer.receive(2000); + assertEquals("Second", message.getText()); + assertTrue(message.getJMSRedelivered()); - message.acknowledge(); - } + message.acknowledge(); + } - /** - * Test to make sure that an Async recover works. - * - * @throws JMSException - * @throws InterruptedException - */ - public void doTestAsynchRecover() throws JMSException, InterruptedException { + /** + * Test to make sure that an Async recover works. + * + * @throws JMSException + * @throws InterruptedException + */ + public void doTestAsynchRecover() throws JMSException, InterruptedException { - final Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - final String errorMessage[] = new String[] {null}; - final CountDownLatch doneCountDownLatch = new CountDownLatch(1); + final Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + final String errorMessage[] = new String[]{null}; + final CountDownLatch doneCountDownLatch = new CountDownLatch(1); - MessageConsumer consumer = session.createConsumer(dest); + MessageConsumer consumer = session.createConsumer(dest); - MessageProducer producer = session.createProducer(dest); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - producer.send(session.createTextMessage("First")); - producer.send(session.createTextMessage("Second")); + MessageProducer producer = session.createProducer(dest); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + producer.send(session.createTextMessage("First")); + producer.send(session.createTextMessage("Second")); - consumer.setMessageListener(new MessageListener() { - int counter; + consumer.setMessageListener(new MessageListener() { + int counter; - public void onMessage(Message msg) { - counter++; - try { - TextMessage message = (TextMessage)msg; - switch (counter) { - case 1: - assertEquals("First", message.getText()); - assertFalse(message.getJMSRedelivered()); - message.acknowledge(); + public void onMessage(Message msg) { + counter++; + try { + TextMessage message = (TextMessage) msg; + switch (counter) { + case 1: + assertEquals("First", message.getText()); + assertFalse(message.getJMSRedelivered()); + message.acknowledge(); - break; - case 2: - assertEquals("Second", message.getText()); - assertFalse(message.getJMSRedelivered()); - session.recover(); - break; + break; + case 2: + assertEquals("Second", message.getText()); + assertFalse(message.getJMSRedelivered()); + session.recover(); + break; - case 3: - assertEquals("Second", message.getText()); - assertTrue(message.getJMSRedelivered()); - message.acknowledge(); - doneCountDownLatch.countDown(); - break; + case 3: + assertEquals("Second", message.getText()); + assertTrue(message.getJMSRedelivered()); + message.acknowledge(); + doneCountDownLatch.countDown(); + break; - default: - errorMessage[0] = "Got too many messages: " + counter; - doneCountDownLatch.countDown(); - } - } catch (Throwable e) { - e.printStackTrace(); - errorMessage[0] = "Got exception: " + e; - doneCountDownLatch.countDown(); - } + default: + errorMessage[0] = "Got too many messages: " + counter; + doneCountDownLatch.countDown(); + } } - }); - connection.start(); - - if (doneCountDownLatch.await(5, TimeUnit.SECONDS)) { - if (errorMessage[0] != null) { - fail(errorMessage[0]); + catch (Throwable e) { + e.printStackTrace(); + errorMessage[0] = "Got exception: " + e; + doneCountDownLatch.countDown(); } - } else { - fail("Timeout waiting for async message delivery to complete."); - } + } + }); + connection.start(); - } + if (doneCountDownLatch.await(5, TimeUnit.SECONDS)) { + if (errorMessage[0] != null) { + fail(errorMessage[0]); + } + } + else { + fail("Timeout waiting for async message delivery to complete."); + } - /** - * Test to make sure that an Async recover works when using AUTO_ACKNOWLEDGE. - * - * @throws JMSException - * @throws InterruptedException - */ - public void doTestAsynchRecoverWithAutoAck() throws JMSException, InterruptedException { + } - final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final String errorMessage[] = new String[] {null}; - final CountDownLatch doneCountDownLatch = new CountDownLatch(1); + /** + * Test to make sure that an Async recover works when using AUTO_ACKNOWLEDGE. + * + * @throws JMSException + * @throws InterruptedException + */ + public void doTestAsynchRecoverWithAutoAck() throws JMSException, InterruptedException { - MessageConsumer consumer = session.createConsumer(dest); + final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final String errorMessage[] = new String[]{null}; + final CountDownLatch doneCountDownLatch = new CountDownLatch(1); - MessageProducer producer = session.createProducer(dest); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - producer.send(session.createTextMessage("First")); - producer.send(session.createTextMessage("Second")); + MessageConsumer consumer = session.createConsumer(dest); - consumer.setMessageListener(new MessageListener() { - int counter; + MessageProducer producer = session.createProducer(dest); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + producer.send(session.createTextMessage("First")); + producer.send(session.createTextMessage("Second")); - public void onMessage(Message msg) { - counter++; - try { - TextMessage message = (TextMessage)msg; - switch (counter) { - case 1: - assertEquals("First", message.getText()); - assertFalse(message.getJMSRedelivered()); - break; - case 2: - // This should rollback the delivery of this message.. - // and re-deliver. - assertEquals("Second", message.getText()); - assertFalse(message.getJMSRedelivered()); - session.recover(); - break; + consumer.setMessageListener(new MessageListener() { + int counter; - case 3: - assertEquals("Second", message.getText()); - assertTrue(message.getJMSRedelivered()); - doneCountDownLatch.countDown(); - break; + public void onMessage(Message msg) { + counter++; + try { + TextMessage message = (TextMessage) msg; + switch (counter) { + case 1: + assertEquals("First", message.getText()); + assertFalse(message.getJMSRedelivered()); + break; + case 2: + // This should rollback the delivery of this message.. + // and re-deliver. + assertEquals("Second", message.getText()); + assertFalse(message.getJMSRedelivered()); + session.recover(); + break; - default: - errorMessage[0] = "Got too many messages: " + counter; - doneCountDownLatch.countDown(); - } - } catch (Throwable e) { - e.printStackTrace(); - errorMessage[0] = "Got exception: " + e; - doneCountDownLatch.countDown(); - } + case 3: + assertEquals("Second", message.getText()); + assertTrue(message.getJMSRedelivered()); + doneCountDownLatch.countDown(); + break; + + default: + errorMessage[0] = "Got too many messages: " + counter; + doneCountDownLatch.countDown(); + } } - }); - connection.start(); - - if (doneCountDownLatch.await(5000, TimeUnit.SECONDS)) { - if (errorMessage[0] != null) { - fail(errorMessage[0]); + catch (Throwable e) { + e.printStackTrace(); + errorMessage[0] = "Got exception: " + e; + doneCountDownLatch.countDown(); } - } else { - fail("Timeout waiting for async message delivery to complete."); - } - } + } + }); + connection.start(); + + if (doneCountDownLatch.await(5000, TimeUnit.SECONDS)) { + if (errorMessage[0] != null) { + fail(errorMessage[0]); + } + } + else { + fail("Timeout waiting for async message delivery to complete."); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTempDestinationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTempDestinationTest.java index bd87b3daa8..c1d75a4f77 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTempDestinationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTempDestinationTest.java @@ -52,326 +52,332 @@ import org.slf4j.LoggerFactory; */ public class JmsTempDestinationTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(JmsTempDestinationTest.class); - private Connection connection; - private ActiveMQConnectionFactory factory; - protected List connections = Collections.synchronizedList(new ArrayList()); + private static final Logger LOG = LoggerFactory.getLogger(JmsTempDestinationTest.class); + private Connection connection; + private ActiveMQConnectionFactory factory; + protected List connections = Collections.synchronizedList(new ArrayList()); - @Override - protected void setUp() throws Exception { - factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); - factory.setAlwaysSyncSend(true); - connection = factory.createConnection(); - connections.add(connection); - } + @Override + protected void setUp() throws Exception { + factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); + factory.setAlwaysSyncSend(true); + connection = factory.createConnection(); + connections.add(connection); + } - /** - * @see junit.framework.TestCase#tearDown() - */ - @Override - protected void tearDown() throws Exception { - for (Iterator iter = connections.iterator(); iter.hasNext();) { - Connection conn = iter.next(); - try { - conn.close(); - } catch (Throwable e) { + /** + * @see junit.framework.TestCase#tearDown() + */ + @Override + protected void tearDown() throws Exception { + for (Iterator iter = connections.iterator(); iter.hasNext(); ) { + Connection conn = iter.next(); + try { + conn.close(); + } + catch (Throwable e) { + } + iter.remove(); + } + } + + /** + * Make sure Temp destination can only be consumed by local connection + * + * @throws JMSException + */ + public void testTempDestOnlyConsumedByLocalConn() throws JMSException { + connection.start(); + + Session tempSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + TemporaryQueue queue = tempSession.createTemporaryQueue(); + MessageProducer producer = tempSession.createProducer(queue); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + TextMessage message = tempSession.createTextMessage("First"); + producer.send(message); + + // temp destination should not be consume when using another connection + Connection otherConnection = factory.createConnection(); + connections.add(otherConnection); + Session otherSession = otherConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + TemporaryQueue otherQueue = otherSession.createTemporaryQueue(); + MessageConsumer consumer = otherSession.createConsumer(otherQueue); + Message msg = consumer.receive(3000); + assertNull(msg); + + // should throw InvalidDestinationException when consuming a temp + // destination from another connection + try { + consumer = otherSession.createConsumer(queue); + fail("Send should fail since temp destination should be used from another connection"); + } + catch (InvalidDestinationException e) { + assertTrue("failed to throw an exception", true); + } + + // should be able to consume temp destination from the same connection + consumer = tempSession.createConsumer(queue); + msg = consumer.receive(3000); + assertNotNull(msg); + + } + + /** + * Make sure that a temp queue does not drop message if there is an active + * consumers. + * + * @throws JMSException + */ + public void testTempQueueHoldsMessagesWithConsumers() throws JMSException { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = session.createTemporaryQueue(); + MessageConsumer consumer = session.createConsumer(queue); + connection.start(); + + MessageProducer producer = session.createProducer(queue); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + TextMessage message = session.createTextMessage("Hello"); + producer.send(message); + + Message message2 = consumer.receive(1000); + assertNotNull(message2); + assertTrue("Expected message to be a TextMessage", message2 instanceof TextMessage); + assertTrue("Expected message to be a '" + message.getText() + "'", ((TextMessage) message2).getText().equals(message.getText())); + } + + /** + * Make sure that a temp queue does not drop message if there are no active + * consumers. + * + * @throws JMSException + */ + public void testTempQueueHoldsMessagesWithoutConsumers() throws JMSException { + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = session.createTemporaryQueue(); + MessageProducer producer = session.createProducer(queue); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + TextMessage message = session.createTextMessage("Hello"); + producer.send(message); + + connection.start(); + MessageConsumer consumer = session.createConsumer(queue); + Message message2 = consumer.receive(3000); + assertNotNull(message2); + assertTrue("Expected message to be a TextMessage", message2 instanceof TextMessage); + assertTrue("Expected message to be a '" + message.getText() + "'", ((TextMessage) message2).getText().equals(message.getText())); + + } + + /** + * Test temp queue works under load + * + * @throws JMSException + */ + public void testTmpQueueWorksUnderLoad() throws JMSException { + int count = 500; + int dataSize = 1024; + + ArrayList list = new ArrayList(count); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = session.createTemporaryQueue(); + MessageProducer producer = session.createProducer(queue); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + + byte[] data = new byte[dataSize]; + for (int i = 0; i < count; i++) { + BytesMessage message = session.createBytesMessage(); + message.writeBytes(data); + message.setIntProperty("c", i); + producer.send(message); + list.add(message); + } + + connection.start(); + MessageConsumer consumer = session.createConsumer(queue); + for (int i = 0; i < count; i++) { + Message message2 = consumer.receive(2000); + assertTrue(message2 != null); + assertEquals(i, message2.getIntProperty("c")); + assertTrue(message2.equals(list.get(i))); + } + } + + /** + * Make sure you cannot publish to a temp destination that does not exist + * anymore. + * + * @throws JMSException + * @throws InterruptedException + * @throws URISyntaxException + */ + public void testPublishFailsForClosedConnection() throws Exception { + + Connection tempConnection = factory.createConnection(); + connections.add(tempConnection); + Session tempSession = tempConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final TemporaryQueue queue = tempSession.createTemporaryQueue(); + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + connection.start(); + + final ActiveMQConnection activeMQConnection = (ActiveMQConnection) connection; + assertTrue("creation advisory received in time with async dispatch", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return activeMQConnection.activeTempDestinations.containsKey(queue); + } + })); + + // This message delivery should work since the temp connection is still + // open. + MessageProducer producer = session.createProducer(queue); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + TextMessage message = session.createTextMessage("First"); + producer.send(message); + + // Closing the connection should destroy the temp queue that was + // created. + tempConnection.close(); + Thread.sleep(5000); // Wait a little bit to let the delete take effect. + + // This message delivery NOT should work since the temp connection is + // now closed. + try { + message = session.createTextMessage("Hello"); + producer.send(message); + fail("Send should fail since temp destination should not exist anymore."); + } + catch (JMSException e) { + } + } + + /** + * Make sure you cannot publish to a temp destination that does not exist + * anymore. + * + * @throws JMSException + * @throws InterruptedException + */ + public void testPublishFailsForDestroyedTempDestination() throws Exception { + + Connection tempConnection = factory.createConnection(); + connections.add(tempConnection); + Session tempSession = tempConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final TemporaryQueue queue = tempSession.createTemporaryQueue(); + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + connection.start(); + + final ActiveMQConnection activeMQConnection = (ActiveMQConnection) connection; + assertTrue("creation advisory received in time with async dispatch", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return activeMQConnection.activeTempDestinations.containsKey(queue); + } + })); + + // This message delivery should work since the temp connection is still + // open. + MessageProducer producer = session.createProducer(queue); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + TextMessage message = session.createTextMessage("First"); + producer.send(message); + + // deleting the Queue will cause sends to fail + queue.delete(); + Thread.sleep(5000); // Wait a little bit to let the delete take effect. + + // This message delivery NOT should work since the temp connection is + // now closed. + try { + message = session.createTextMessage("Hello"); + producer.send(message); + fail("Send should fail since temp destination should not exist anymore."); + } + catch (JMSException e) { + assertTrue("failed to throw an exception", true); + } + } + + /** + * Test you can't delete a Destination with Active Subscribers + * + * @throws JMSException + */ + public void testDeleteDestinationWithSubscribersFails() throws JMSException { + Connection connection = factory.createConnection(); + connections.add(connection); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + TemporaryQueue queue = session.createTemporaryQueue(); + + connection.start(); + + session.createConsumer(queue); + + // This message delivery should NOT work since the temp connection is + // now closed. + try { + queue.delete(); + fail("Should fail as Subscribers are active"); + } + catch (JMSException e) { + assertTrue("failed to throw an exception", true); + } + } + + public void testSlowConsumerDoesNotBlockFastTempUsers() throws Exception { + ActiveMQConnectionFactory advisoryConnFactory = new ActiveMQConnectionFactory("vm://localhost?asyncQueueDepth=20"); + Connection connection = advisoryConnFactory.createConnection(); + connections.add(connection); + connection.start(); + + final CountDownLatch done = new CountDownLatch(1); + final AtomicBoolean ok = new AtomicBoolean(true); + final AtomicBoolean first = new AtomicBoolean(true); + VMTransport t = ((ActiveMQConnection) connection).getTransport().narrow(VMTransport.class); + t.setTransportListener(new TransportListener() { + @Override + public void onCommand(Object command) { + // block first dispatch for a while so broker backs up, but other connection should be able to proceed + if (first.compareAndSet(true, false)) { + try { + ok.set(done.await(35, TimeUnit.SECONDS)); + LOG.info("Done waiting: " + ok.get()); + } + catch (InterruptedException e) { + e.printStackTrace(); + } } - iter.remove(); - } - } + } - /** - * Make sure Temp destination can only be consumed by local connection - * - * @throws JMSException - */ - public void testTempDestOnlyConsumedByLocalConn() throws JMSException { - connection.start(); + @Override + public void onException(IOException error) { + } - Session tempSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TemporaryQueue queue = tempSession.createTemporaryQueue(); - MessageProducer producer = tempSession.createProducer(queue); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - TextMessage message = tempSession.createTextMessage("First"); - producer.send(message); + @Override + public void transportInterupted() { + } - // temp destination should not be consume when using another connection - Connection otherConnection = factory.createConnection(); - connections.add(otherConnection); - Session otherSession = otherConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TemporaryQueue otherQueue = otherSession.createTemporaryQueue(); - MessageConsumer consumer = otherSession.createConsumer(otherQueue); - Message msg = consumer.receive(3000); - assertNull(msg); + @Override + public void transportResumed() { + } + }); - // should throw InvalidDestinationException when consuming a temp - // destination from another connection - try { - consumer = otherSession.createConsumer(queue); - fail("Send should fail since temp destination should be used from another connection"); - } catch (InvalidDestinationException e) { - assertTrue("failed to throw an exception", true); - } + connection = factory.createConnection(); + connections.add(connection); + ((ActiveMQConnection) connection).setWatchTopicAdvisories(false); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - // should be able to consume temp destination from the same connection - consumer = tempSession.createConsumer(queue); - msg = consumer.receive(3000); - assertNotNull(msg); - - } - - /** - * Make sure that a temp queue does not drop message if there is an active - * consumers. - * - * @throws JMSException - */ - public void testTempQueueHoldsMessagesWithConsumers() throws JMSException { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createTemporaryQueue(); - MessageConsumer consumer = session.createConsumer(queue); - connection.start(); - - MessageProducer producer = session.createProducer(queue); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - TextMessage message = session.createTextMessage("Hello"); - producer.send(message); - - Message message2 = consumer.receive(1000); - assertNotNull(message2); - assertTrue("Expected message to be a TextMessage", message2 instanceof TextMessage); - assertTrue("Expected message to be a '" + message.getText() + "'", ((TextMessage)message2).getText().equals(message.getText())); - } - - /** - * Make sure that a temp queue does not drop message if there are no active - * consumers. - * - * @throws JMSException - */ - public void testTempQueueHoldsMessagesWithoutConsumers() throws JMSException { - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createTemporaryQueue(); - MessageProducer producer = session.createProducer(queue); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - TextMessage message = session.createTextMessage("Hello"); - producer.send(message); - - connection.start(); - MessageConsumer consumer = session.createConsumer(queue); - Message message2 = consumer.receive(3000); - assertNotNull(message2); - assertTrue("Expected message to be a TextMessage", message2 instanceof TextMessage); - assertTrue("Expected message to be a '" + message.getText() + "'", ((TextMessage)message2).getText().equals(message.getText())); - - } - - /** - * Test temp queue works under load - * - * @throws JMSException - */ - public void testTmpQueueWorksUnderLoad() throws JMSException { - int count = 500; - int dataSize = 1024; - - ArrayList list = new ArrayList(count); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createTemporaryQueue(); - MessageProducer producer = session.createProducer(queue); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - - byte[] data = new byte[dataSize]; - for (int i = 0; i < count; i++) { - BytesMessage message = session.createBytesMessage(); - message.writeBytes(data); - message.setIntProperty("c", i); - producer.send(message); - list.add(message); - } - - connection.start(); - MessageConsumer consumer = session.createConsumer(queue); - for (int i = 0; i < count; i++) { - Message message2 = consumer.receive(2000); - assertTrue(message2 != null); - assertEquals(i, message2.getIntProperty("c")); - assertTrue(message2.equals(list.get(i))); - } - } - - /** - * Make sure you cannot publish to a temp destination that does not exist - * anymore. - * - * @throws JMSException - * @throws InterruptedException - * @throws URISyntaxException - */ - public void testPublishFailsForClosedConnection() throws Exception { - - Connection tempConnection = factory.createConnection(); - connections.add(tempConnection); - Session tempSession = tempConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final TemporaryQueue queue = tempSession.createTemporaryQueue(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - connection.start(); - - final ActiveMQConnection activeMQConnection = (ActiveMQConnection) connection; - assertTrue("creation advisory received in time with async dispatch", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return activeMQConnection.activeTempDestinations.containsKey(queue); - } - })); - - // This message delivery should work since the temp connection is still - // open. - MessageProducer producer = session.createProducer(queue); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - TextMessage message = session.createTextMessage("First"); - producer.send(message); - - // Closing the connection should destroy the temp queue that was - // created. - tempConnection.close(); - Thread.sleep(5000); // Wait a little bit to let the delete take effect. - - // This message delivery NOT should work since the temp connection is - // now closed. - try { - message = session.createTextMessage("Hello"); - producer.send(message); - fail("Send should fail since temp destination should not exist anymore."); - } catch (JMSException e) { - } - } - - /** - * Make sure you cannot publish to a temp destination that does not exist - * anymore. - * - * @throws JMSException - * @throws InterruptedException - */ - public void testPublishFailsForDestroyedTempDestination() throws Exception { - - Connection tempConnection = factory.createConnection(); - connections.add(tempConnection); - Session tempSession = tempConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final TemporaryQueue queue = tempSession.createTemporaryQueue(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - connection.start(); - - final ActiveMQConnection activeMQConnection = (ActiveMQConnection) connection; - assertTrue("creation advisory received in time with async dispatch", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return activeMQConnection.activeTempDestinations.containsKey(queue); - } - })); - - // This message delivery should work since the temp connection is still - // open. - MessageProducer producer = session.createProducer(queue); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - TextMessage message = session.createTextMessage("First"); - producer.send(message); - - // deleting the Queue will cause sends to fail - queue.delete(); - Thread.sleep(5000); // Wait a little bit to let the delete take effect. - - // This message delivery NOT should work since the temp connection is - // now closed. - try { - message = session.createTextMessage("Hello"); - producer.send(message); - fail("Send should fail since temp destination should not exist anymore."); - } catch (JMSException e) { - assertTrue("failed to throw an exception", true); - } - } - - /** - * Test you can't delete a Destination with Active Subscribers - * - * @throws JMSException - */ - public void testDeleteDestinationWithSubscribersFails() throws JMSException { - Connection connection = factory.createConnection(); - connections.add(connection); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TemporaryQueue queue = session.createTemporaryQueue(); - - connection.start(); - - session.createConsumer(queue); - - // This message delivery should NOT work since the temp connection is - // now closed. - try { - queue.delete(); - fail("Should fail as Subscribers are active"); - } catch (JMSException e) { - assertTrue("failed to throw an exception", true); - } - } - - public void testSlowConsumerDoesNotBlockFastTempUsers() throws Exception { - ActiveMQConnectionFactory advisoryConnFactory = new ActiveMQConnectionFactory("vm://localhost?asyncQueueDepth=20"); - Connection connection = advisoryConnFactory.createConnection(); - connections.add(connection); - connection.start(); - - final CountDownLatch done = new CountDownLatch(1); - final AtomicBoolean ok = new AtomicBoolean(true); - final AtomicBoolean first = new AtomicBoolean(true); - VMTransport t = ((ActiveMQConnection)connection).getTransport().narrow(VMTransport.class); - t.setTransportListener(new TransportListener() { - @Override - public void onCommand(Object command) { - // block first dispatch for a while so broker backs up, but other connection should be able to proceed - if (first.compareAndSet(true, false)) { - try { - ok.set(done.await(35, TimeUnit.SECONDS)); - LOG.info("Done waiting: " + ok.get()); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - @Override - public void onException(IOException error) { - } - - @Override - public void transportInterupted() { - } - - @Override - public void transportResumed() { - } - }); - - connection = factory.createConnection(); - connections.add(connection); - ((ActiveMQConnection)connection).setWatchTopicAdvisories(false); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - for (int i=0; i<2500; i++) { - TemporaryQueue queue = session.createTemporaryQueue(); - MessageConsumer consumer = session.createConsumer(queue); - consumer.close(); - queue.delete(); - } - LOG.info("Done with work: " + ok.get()); - done.countDown(); - assertTrue("ok", ok.get()); - } + for (int i = 0; i < 2500; i++) { + TemporaryQueue queue = session.createTemporaryQueue(); + MessageConsumer consumer = session.createConsumer(queue); + consumer.close(); + queue.delete(); + } + LOG.info("Done with work: " + ok.get()); + done.countDown(); + assertTrue("ok", ok.get()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTestSupport.java index 29d84c9ecc..3fc6addd58 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTestSupport.java @@ -39,148 +39,151 @@ import org.apache.activemq.command.ActiveMQDestination; /** * Test cases used to test the JMS message consumer. - * - * */ public class JmsTestSupport extends CombinationTestSupport { - static final private AtomicLong TEST_COUNTER = new AtomicLong(); - public String userName; - public String password; - public String messageTextPrefix = ""; + static final private AtomicLong TEST_COUNTER = new AtomicLong(); + public String userName; + public String password; + public String messageTextPrefix = ""; - protected ConnectionFactory factory; - protected ActiveMQConnection connection; - protected BrokerService broker; + protected ConnectionFactory factory; + protected ActiveMQConnection connection; + protected BrokerService broker; - protected List connections = Collections.synchronizedList(new ArrayList()); + protected List connections = Collections.synchronizedList(new ArrayList()); - // ///////////////////////////////////////////////////////////////// - // - // Test support methods. - // - // ///////////////////////////////////////////////////////////////// - protected ActiveMQDestination createDestination(Session session, byte type) throws JMSException { - String testMethod = getName(); - if( testMethod.indexOf(" ")>0 ) { - testMethod = testMethod.substring(0, testMethod.indexOf(" ")); - } - String name = "TEST." + getClass().getName() + "." +testMethod+"."+TEST_COUNTER.getAndIncrement(); - switch (type) { - case ActiveMQDestination.QUEUE_TYPE: - return (ActiveMQDestination)session.createQueue(name); - case ActiveMQDestination.TOPIC_TYPE: - return (ActiveMQDestination)session.createTopic(name); - case ActiveMQDestination.TEMP_QUEUE_TYPE: - return (ActiveMQDestination)session.createTemporaryQueue(); - case ActiveMQDestination.TEMP_TOPIC_TYPE: - return (ActiveMQDestination)session.createTemporaryTopic(); - default: + // ///////////////////////////////////////////////////////////////// + // + // Test support methods. + // + // ///////////////////////////////////////////////////////////////// + protected ActiveMQDestination createDestination(Session session, byte type) throws JMSException { + String testMethod = getName(); + if (testMethod.indexOf(" ") > 0) { + testMethod = testMethod.substring(0, testMethod.indexOf(" ")); + } + String name = "TEST." + getClass().getName() + "." + testMethod + "." + TEST_COUNTER.getAndIncrement(); + switch (type) { + case ActiveMQDestination.QUEUE_TYPE: + return (ActiveMQDestination) session.createQueue(name); + case ActiveMQDestination.TOPIC_TYPE: + return (ActiveMQDestination) session.createTopic(name); + case ActiveMQDestination.TEMP_QUEUE_TYPE: + return (ActiveMQDestination) session.createTemporaryQueue(); + case ActiveMQDestination.TEMP_TOPIC_TYPE: + return (ActiveMQDestination) session.createTemporaryTopic(); + default: throw new IllegalArgumentException("type: " + type); - } - } + } + } - protected void sendMessages(Destination destination, int count) throws Exception { - ConnectionFactory factory = createConnectionFactory(); - Connection connection = factory.createConnection(); - connection.start(); - sendMessages(connection, destination, count); - connection.close(); - } + protected void sendMessages(Destination destination, int count) throws Exception { + ConnectionFactory factory = createConnectionFactory(); + Connection connection = factory.createConnection(); + connection.start(); + sendMessages(connection, destination, count); + connection.close(); + } - protected void sendMessages(Connection connection, Destination destination, int count) throws JMSException { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - sendMessages(session, destination, count); - session.close(); - } + protected void sendMessages(Connection connection, Destination destination, int count) throws JMSException { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + sendMessages(session, destination, count); + session.close(); + } - protected void sendMessages(Session session, Destination destination, int count) throws JMSException { - MessageProducer producer = session.createProducer(destination); - sendMessages(session, producer, count); - producer.close(); - } + protected void sendMessages(Session session, Destination destination, int count) throws JMSException { + MessageProducer producer = session.createProducer(destination); + sendMessages(session, producer, count); + producer.close(); + } - protected void sendMessages(Session session, MessageProducer producer, int count) throws JMSException { - for (int i = 0; i < count; i++) { - producer.send(session.createTextMessage(messageTextPrefix + i)); - } - } + protected void sendMessages(Session session, MessageProducer producer, int count) throws JMSException { + for (int i = 0; i < count; i++) { + producer.send(session.createTextMessage(messageTextPrefix + i)); + } + } - protected ConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("tcp://localhost:61616"); - } + protected ConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory("tcp://localhost:61616"); + } - protected BrokerService createBroker() throws Exception { - return BrokerFactory.createBroker(new URI("broker://()/localhost?persistent=false")); - } + protected BrokerService createBroker() throws Exception { + return BrokerFactory.createBroker(new URI("broker://()/localhost?persistent=false")); + } - protected void setUp() throws Exception { - super.setUp(); + protected void setUp() throws Exception { + super.setUp(); - if (System.getProperty("basedir") == null) { - File file = new File("."); - System.setProperty("basedir", file.getAbsolutePath()); - } + if (System.getProperty("basedir") == null) { + File file = new File("."); + System.setProperty("basedir", file.getAbsolutePath()); + } - broker = createBroker(); - broker.start(); - factory = createConnectionFactory(); - connection = (ActiveMQConnection)factory.createConnection(userName, password); - connections.add(connection); - } + broker = createBroker(); + broker.start(); + factory = createConnectionFactory(); + connection = (ActiveMQConnection) factory.createConnection(userName, password); + connections.add(connection); + } - protected void tearDown() throws Exception { - for (Iterator iter = connections.iterator(); iter.hasNext();) { - Connection conn = iter.next(); - try { - conn.close(); - } catch (Throwable e) { - } - iter.remove(); - } - broker.stop(); - super.tearDown(); - } + protected void tearDown() throws Exception { + for (Iterator iter = connections.iterator(); iter.hasNext(); ) { + Connection conn = iter.next(); + try { + conn.close(); + } + catch (Throwable e) { + } + iter.remove(); + } + broker.stop(); + super.tearDown(); + } - protected void safeClose(Connection c) { - try { - c.close(); - } catch (Throwable e) { - } - } + protected void safeClose(Connection c) { + try { + c.close(); + } + catch (Throwable e) { + } + } - protected void safeClose(Session s) { - try { - s.close(); - } catch (Throwable e) { - } - } + protected void safeClose(Session s) { + try { + s.close(); + } + catch (Throwable e) { + } + } - protected void safeClose(MessageConsumer c) { - try { - c.close(); - } catch (Throwable e) { - } - } + protected void safeClose(MessageConsumer c) { + try { + c.close(); + } + catch (Throwable e) { + } + } - protected void safeClose(MessageProducer p) { - try { - p.close(); - } catch (Throwable e) { - } - } + protected void safeClose(MessageProducer p) { + try { + p.close(); + } + catch (Throwable e) { + } + } - protected void profilerPause(String prompt) throws IOException { - if (System.getProperty("profiler") != null) { - pause(prompt); - } - } + protected void profilerPause(String prompt) throws IOException { + if (System.getProperty("profiler") != null) { + pause(prompt); + } + } - protected void pause(String prompt) throws IOException { - System.out.println(); - System.out.println(prompt + "> Press enter to continue: "); - while (System.in.read() != '\n') { - } - } + protected void pause(String prompt) throws IOException { + System.out.println(); + System.out.println(prompt + "> Press enter to continue: "); + while (System.in.read() != '\n') { + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicCompositeSendReceiveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicCompositeSendReceiveTest.java index a948ffa950..4536d3b9f1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicCompositeSendReceiveTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicCompositeSendReceiveTest.java @@ -23,66 +23,66 @@ import javax.jms.Topic; import org.apache.activemq.test.JmsTopicSendReceiveTest; - /** - * + * */ public class JmsTopicCompositeSendReceiveTest extends JmsTopicSendReceiveTest { - private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory - .getLog(JmsTopicCompositeSendReceiveTest.class); - - Destination consumerDestination2; - MessageConsumer consumer2; - /** - * Sets a test to have a queue destination and non-persistent delivery mode. - * - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception { - deliveryMode = DeliveryMode.NON_PERSISTENT; - super.setUp(); - consumerDestination2 = consumeSession.createTopic("FOO.BAR.HUMBUG2"); - LOG.info("Created consumer destination: " + consumerDestination2 + " of type: " + consumerDestination2.getClass()); - if (durable) { - LOG.info("Creating durable consumer"); - consumer2 = consumeSession.createDurableSubscriber((Topic) consumerDestination2, getName()); - } else { - consumer2 = consumeSession.createConsumer(consumerDestination2); - } + private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(JmsTopicCompositeSendReceiveTest.class); - } + Destination consumerDestination2; + MessageConsumer consumer2; - /** - * Returns the consumer subject. - * - * @return String - consumer subject - * @see org.apache.activemq.test.TestSupport#getConsumerSubject() - */ - protected String getConsumerSubject() { - return "FOO.BAR.HUMBUG"; - } + /** + * Sets a test to have a queue destination and non-persistent delivery mode. + * + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + deliveryMode = DeliveryMode.NON_PERSISTENT; + super.setUp(); + consumerDestination2 = consumeSession.createTopic("FOO.BAR.HUMBUG2"); + LOG.info("Created consumer destination: " + consumerDestination2 + " of type: " + consumerDestination2.getClass()); + if (durable) { + LOG.info("Creating durable consumer"); + consumer2 = consumeSession.createDurableSubscriber((Topic) consumerDestination2, getName()); + } + else { + consumer2 = consumeSession.createConsumer(consumerDestination2); + } - /** - * Returns the producer subject. - * - * @return String - producer subject - * @see org.apache.activemq.test.TestSupport#getProducerSubject() - */ - protected String getProducerSubject() { - return "FOO.BAR.HUMBUG,FOO.BAR.HUMBUG2"; - } + } - /** - * Test if all the messages sent are being received. - * - * @throws Exception - */ - public void testSendReceive() throws Exception { - super.testSendReceive(); - messages.clear(); - consumer2.setMessageListener(this); - assertMessagesAreReceived(); - LOG.info("" + data.length + " messages(s) received, closing down connections"); - } + /** + * Returns the consumer subject. + * + * @return String - consumer subject + * @see org.apache.activemq.test.TestSupport#getConsumerSubject() + */ + protected String getConsumerSubject() { + return "FOO.BAR.HUMBUG"; + } + + /** + * Returns the producer subject. + * + * @return String - producer subject + * @see org.apache.activemq.test.TestSupport#getProducerSubject() + */ + protected String getProducerSubject() { + return "FOO.BAR.HUMBUG,FOO.BAR.HUMBUG2"; + } + + /** + * Test if all the messages sent are being received. + * + * @throws Exception + */ + public void testSendReceive() throws Exception { + super.testSendReceive(); + messages.clear(); + consumer2.setMessageListener(this); + assertMessagesAreReceived(); + LOG.info("" + data.length + " messages(s) received, closing down connections"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicRedeliverTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicRedeliverTest.java index 188e4cd89a..2842e0b059 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicRedeliverTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicRedeliverTest.java @@ -30,132 +30,133 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class JmsTopicRedeliverTest extends TestSupport { - private static final Logger LOG = LoggerFactory.getLogger(JmsTopicRedeliverTest.class); + private static final Logger LOG = LoggerFactory.getLogger(JmsTopicRedeliverTest.class); - protected Connection connection; - protected Session session; - protected Session consumeSession; - protected MessageConsumer consumer; - protected MessageProducer producer; - protected Destination consumerDestination; - protected Destination producerDestination; - protected boolean topic = true; - protected boolean durable; - protected boolean verbose; - protected long initRedeliveryDelay; + protected Connection connection; + protected Session session; + protected Session consumeSession; + protected MessageConsumer consumer; + protected MessageProducer producer; + protected Destination consumerDestination; + protected Destination producerDestination; + protected boolean topic = true; + protected boolean durable; + protected boolean verbose; + protected long initRedeliveryDelay; - protected void setUp() throws Exception { - super.setUp(); + protected void setUp() throws Exception { + super.setUp(); - connectionFactory = createConnectionFactory(); - connection = createConnection(); - initRedeliveryDelay = ((ActiveMQConnection)connection).getRedeliveryPolicy().getInitialRedeliveryDelay(); + connectionFactory = createConnectionFactory(); + connection = createConnection(); + initRedeliveryDelay = ((ActiveMQConnection) connection).getRedeliveryPolicy().getInitialRedeliveryDelay(); - if (durable) { - connection.setClientID(getClass().getName()); - } + if (durable) { + connection.setClientID(getClass().getName()); + } - LOG.info("Created connection: " + connection); + LOG.info("Created connection: " + connection); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - consumeSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + consumeSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - LOG.info("Created session: " + session); - LOG.info("Created consumeSession: " + consumeSession); - producer = session.createProducer(null); - // producer.setDeliveryMode(deliveryMode); + LOG.info("Created session: " + session); + LOG.info("Created consumeSession: " + consumeSession); + producer = session.createProducer(null); + // producer.setDeliveryMode(deliveryMode); - LOG.info("Created producer: " + producer); + LOG.info("Created producer: " + producer); - if (topic) { - consumerDestination = session.createTopic(getConsumerSubject()); - producerDestination = session.createTopic(getProducerSubject()); - } else { - consumerDestination = session.createQueue(getConsumerSubject()); - producerDestination = session.createQueue(getProducerSubject()); - } + if (topic) { + consumerDestination = session.createTopic(getConsumerSubject()); + producerDestination = session.createTopic(getProducerSubject()); + } + else { + consumerDestination = session.createQueue(getConsumerSubject()); + producerDestination = session.createQueue(getProducerSubject()); + } - LOG.info("Created consumer destination: " + consumerDestination + " of type: " + consumerDestination.getClass()); - LOG.info("Created producer destination: " + producerDestination + " of type: " + producerDestination.getClass()); - consumer = createConsumer(); - connection.start(); + LOG.info("Created consumer destination: " + consumerDestination + " of type: " + consumerDestination.getClass()); + LOG.info("Created producer destination: " + producerDestination + " of type: " + producerDestination.getClass()); + consumer = createConsumer(); + connection.start(); - LOG.info("Created connection: " + connection); - } + LOG.info("Created connection: " + connection); + } - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - super.tearDown(); - } + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + } + super.tearDown(); + } - /** - * Returns the consumer subject. - * - * @return String - consumer subject - * @see org.apache.activemq.test.TestSupport#getConsumerSubject() - */ - protected String getConsumerSubject() { - return "TEST"; - } + /** + * Returns the consumer subject. + * + * @return String - consumer subject + * @see org.apache.activemq.test.TestSupport#getConsumerSubject() + */ + protected String getConsumerSubject() { + return "TEST"; + } - /** - * Returns the producer subject. - * - * @return String - producer subject - * @see org.apache.activemq.test.TestSupport#getProducerSubject() - */ - protected String getProducerSubject() { - return "TEST"; - } + /** + * Returns the producer subject. + * + * @return String - producer subject + * @see org.apache.activemq.test.TestSupport#getProducerSubject() + */ + protected String getProducerSubject() { + return "TEST"; + } - /** - * Sends and consumes the messages. - * - * @throws Exception - */ - public void testRecover() throws Exception { - String text = "TEST"; - Message sendMessage = session.createTextMessage(text); + /** + * Sends and consumes the messages. + * + * @throws Exception + */ + public void testRecover() throws Exception { + String text = "TEST"; + Message sendMessage = session.createTextMessage(text); - if (verbose) { - LOG.info("About to send a message: " + sendMessage + " with text: " + text); - } - producer.send(producerDestination, sendMessage); + if (verbose) { + LOG.info("About to send a message: " + sendMessage + " with text: " + text); + } + producer.send(producerDestination, sendMessage); - // receive but don't acknowledge - Message unackMessage = consumer.receive(initRedeliveryDelay + 1000); - assertNotNull(unackMessage); - String unackId = unackMessage.getJMSMessageID(); - assertEquals(((TextMessage)unackMessage).getText(), text); - assertFalse(unackMessage.getJMSRedelivered()); - // assertEquals(unackMessage.getIntProperty("JMSXDeliveryCount"),1); + // receive but don't acknowledge + Message unackMessage = consumer.receive(initRedeliveryDelay + 1000); + assertNotNull(unackMessage); + String unackId = unackMessage.getJMSMessageID(); + assertEquals(((TextMessage) unackMessage).getText(), text); + assertFalse(unackMessage.getJMSRedelivered()); + // assertEquals(unackMessage.getIntProperty("JMSXDeliveryCount"),1); - // receive then acknowledge - consumeSession.recover(); - Message ackMessage = consumer.receive(initRedeliveryDelay + 1000); - assertNotNull(ackMessage); - ackMessage.acknowledge(); - String ackId = ackMessage.getJMSMessageID(); - assertEquals(((TextMessage)ackMessage).getText(), text); - assertTrue(ackMessage.getJMSRedelivered()); - // assertEquals(ackMessage.getIntProperty("JMSXDeliveryCount"),2); - assertEquals(unackId, ackId); - consumeSession.recover(); - assertNull(consumer.receiveNoWait()); - } + // receive then acknowledge + consumeSession.recover(); + Message ackMessage = consumer.receive(initRedeliveryDelay + 1000); + assertNotNull(ackMessage); + ackMessage.acknowledge(); + String ackId = ackMessage.getJMSMessageID(); + assertEquals(((TextMessage) ackMessage).getText(), text); + assertTrue(ackMessage.getJMSRedelivered()); + // assertEquals(ackMessage.getIntProperty("JMSXDeliveryCount"),2); + assertEquals(unackId, ackId); + consumeSession.recover(); + assertNull(consumer.receiveNoWait()); + } - protected MessageConsumer createConsumer() throws JMSException { - if (durable) { - LOG.info("Creating durable consumer"); - return consumeSession.createDurableSubscriber((Topic)consumerDestination, getName()); - } - return consumeSession.createConsumer(consumerDestination); - } + protected MessageConsumer createConsumer() throws JMSException { + if (durable) { + LOG.info("Creating durable consumer"); + return consumeSession.createDurableSubscriber((Topic) consumerDestination, getName()); + } + return consumeSession.createConsumer(consumerDestination); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicRequestReplyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicRequestReplyTest.java index f5d1d2c905..02848bf489 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicRequestReplyTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicRequestReplyTest.java @@ -36,187 +36,195 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class JmsTopicRequestReplyTest extends TestSupport implements MessageListener { - private static final Logger LOG = LoggerFactory.getLogger(JmsTopicRequestReplyTest.class); - protected boolean useAsyncConsume; - private Connection serverConnection; - private Connection clientConnection; - private MessageProducer replyProducer; - private Session serverSession; - private Destination requestDestination; - private List failures = new Vector(); - private boolean dynamicallyCreateProducer; - private String clientSideClientID; + private static final Logger LOG = LoggerFactory.getLogger(JmsTopicRequestReplyTest.class); - public void testSendAndReceive() throws Exception { - clientConnection = createConnection(); - clientConnection.setClientID("ClientConnection:" + getSubject()); + protected boolean useAsyncConsume; + private Connection serverConnection; + private Connection clientConnection; + private MessageProducer replyProducer; + private Session serverSession; + private Destination requestDestination; + private List failures = new Vector(); + private boolean dynamicallyCreateProducer; + private String clientSideClientID; - Session session = clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + public void testSendAndReceive() throws Exception { + clientConnection = createConnection(); + clientConnection.setClientID("ClientConnection:" + getSubject()); - clientConnection.start(); + Session session = clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination replyDestination = createTemporaryDestination(session); + clientConnection.start(); - // lets test the destination - clientSideClientID = clientConnection.getClientID(); + Destination replyDestination = createTemporaryDestination(session); - // TODO - // String value = ActiveMQDestination.getClientId((ActiveMQDestination) - // replyDestination); - // assertEquals("clientID from the temporary destination must be the - // same", clientSideClientID, value); - LOG.info("Both the clientID and destination clientID match properly: " + clientSideClientID); + // lets test the destination + clientSideClientID = clientConnection.getClientID(); + + // TODO + // String value = ActiveMQDestination.getClientId((ActiveMQDestination) + // replyDestination); + // assertEquals("clientID from the temporary destination must be the + // same", clientSideClientID, value); + LOG.info("Both the clientID and destination clientID match properly: " + clientSideClientID); /* build queues */ - MessageProducer requestProducer = session.createProducer(requestDestination); - MessageConsumer replyConsumer = session.createConsumer(replyDestination); + MessageProducer requestProducer = session.createProducer(requestDestination); + MessageConsumer replyConsumer = session.createConsumer(replyDestination); /* build requestmessage */ - TextMessage requestMessage = session.createTextMessage("Olivier"); - requestMessage.setJMSReplyTo(replyDestination); - requestProducer.send(requestMessage); + TextMessage requestMessage = session.createTextMessage("Olivier"); + requestMessage.setJMSReplyTo(replyDestination); + requestProducer.send(requestMessage); - LOG.info("Sent request."); - LOG.info(requestMessage.toString()); + LOG.info("Sent request."); + LOG.info(requestMessage.toString()); - Message msg = replyConsumer.receive(5000); + Message msg = replyConsumer.receive(5000); - if (msg instanceof TextMessage) { - TextMessage replyMessage = (TextMessage)msg; - LOG.info("Received reply."); - LOG.info(replyMessage.toString()); - assertEquals("Wrong message content", "Hello: Olivier", replyMessage.getText()); - } else { - fail("Should have received a reply by now"); - } - replyConsumer.close(); - deleteTemporaryDestination(replyDestination); + if (msg instanceof TextMessage) { + TextMessage replyMessage = (TextMessage) msg; + LOG.info("Received reply."); + LOG.info(replyMessage.toString()); + assertEquals("Wrong message content", "Hello: Olivier", replyMessage.getText()); + } + else { + fail("Should have received a reply by now"); + } + replyConsumer.close(); + deleteTemporaryDestination(replyDestination); - assertEquals("Should not have had any failures: " + failures, 0, failures.size()); - } + assertEquals("Should not have had any failures: " + failures, 0, failures.size()); + } - public void testSendAndReceiveWithDynamicallyCreatedProducer() throws Exception { - dynamicallyCreateProducer = true; - testSendAndReceive(); - } + public void testSendAndReceiveWithDynamicallyCreatedProducer() throws Exception { + dynamicallyCreateProducer = true; + testSendAndReceive(); + } - /** - * Use the asynchronous subscription mechanism - */ - public void onMessage(Message message) { - try { - TextMessage requestMessage = (TextMessage)message; + /** + * Use the asynchronous subscription mechanism + */ + public void onMessage(Message message) { + try { + TextMessage requestMessage = (TextMessage) message; - LOG.info("Received request."); - LOG.info(requestMessage.toString()); + LOG.info("Received request."); + LOG.info(requestMessage.toString()); - Destination replyDestination = requestMessage.getJMSReplyTo(); + Destination replyDestination = requestMessage.getJMSReplyTo(); - // TODO - // String value = - // ActiveMQDestination.getClientId((ActiveMQDestination) - // replyDestination); - // assertEquals("clientID from the temporary destination must be the - // same", clientSideClientID, value); + // TODO + // String value = + // ActiveMQDestination.getClientId((ActiveMQDestination) + // replyDestination); + // assertEquals("clientID from the temporary destination must be the + // same", clientSideClientID, value); - TextMessage replyMessage = serverSession.createTextMessage("Hello: " + requestMessage.getText()); + TextMessage replyMessage = serverSession.createTextMessage("Hello: " + requestMessage.getText()); - replyMessage.setJMSCorrelationID(requestMessage.getJMSMessageID()); + replyMessage.setJMSCorrelationID(requestMessage.getJMSMessageID()); - if (dynamicallyCreateProducer) { - replyProducer = serverSession.createProducer(replyDestination); - replyProducer.send(replyMessage); - } else { - replyProducer.send(replyDestination, replyMessage); - } + if (dynamicallyCreateProducer) { + replyProducer = serverSession.createProducer(replyDestination); + replyProducer.send(replyMessage); + } + else { + replyProducer.send(replyDestination, replyMessage); + } - LOG.info("Sent reply."); - LOG.info(replyMessage.toString()); - } catch (JMSException e) { - onException(e); - } - } + LOG.info("Sent reply."); + LOG.info(replyMessage.toString()); + } + catch (JMSException e) { + onException(e); + } + } - /** - * Use the synchronous subscription mechanism - */ - protected void syncConsumeLoop(MessageConsumer requestConsumer) { - try { - Message message = requestConsumer.receive(5000); - if (message != null) { - onMessage(message); - } else { - LOG.error("No message received"); - } - } catch (JMSException e) { - onException(e); - } - } + /** + * Use the synchronous subscription mechanism + */ + protected void syncConsumeLoop(MessageConsumer requestConsumer) { + try { + Message message = requestConsumer.receive(5000); + if (message != null) { + onMessage(message); + } + else { + LOG.error("No message received"); + } + } + catch (JMSException e) { + onException(e); + } + } - protected void setUp() throws Exception { - super.setUp(); + protected void setUp() throws Exception { + super.setUp(); - serverConnection = createConnection(); - serverConnection.setClientID("serverConnection:" + getSubject()); - serverSession = serverConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + serverConnection = createConnection(); + serverConnection.setClientID("serverConnection:" + getSubject()); + serverSession = serverConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - replyProducer = serverSession.createProducer(null); + replyProducer = serverSession.createProducer(null); - requestDestination = createDestination(serverSession); + requestDestination = createDestination(serverSession); /* build queues */ - final MessageConsumer requestConsumer = serverSession.createConsumer(requestDestination); - if (useAsyncConsume) { - requestConsumer.setMessageListener(this); - } else { - Thread thread = new Thread(new Runnable() { - public void run() { - syncConsumeLoop(requestConsumer); - } - }); - thread.start(); - } - serverConnection.start(); - } + final MessageConsumer requestConsumer = serverSession.createConsumer(requestDestination); + if (useAsyncConsume) { + requestConsumer.setMessageListener(this); + } + else { + Thread thread = new Thread(new Runnable() { + public void run() { + syncConsumeLoop(requestConsumer); + } + }); + thread.start(); + } + serverConnection.start(); + } - protected void tearDown() throws Exception { - super.tearDown(); + protected void tearDown() throws Exception { + super.tearDown(); - serverConnection.close(); - clientConnection.stop(); - clientConnection.close(); - } + serverConnection.close(); + clientConnection.stop(); + clientConnection.close(); + } - protected void onException(JMSException e) { - LOG.info("Caught: " + e); - e.printStackTrace(); - failures.add(e); - } + protected void onException(JMSException e) { + LOG.info("Caught: " + e); + e.printStackTrace(); + failures.add(e); + } - protected Destination createDestination(Session session) throws JMSException { - if (topic) { - return session.createTopic(getSubject()); - } - return session.createQueue(getSubject()); - } + protected Destination createDestination(Session session) throws JMSException { + if (topic) { + return session.createTopic(getSubject()); + } + return session.createQueue(getSubject()); + } - protected Destination createTemporaryDestination(Session session) throws JMSException { - if (topic) { - return session.createTemporaryTopic(); - } - return session.createTemporaryQueue(); - } - - protected void deleteTemporaryDestination(Destination dest) throws JMSException { - if (topic) { - ((TemporaryTopic)dest).delete(); - } else { - ((TemporaryQueue)dest).delete(); - } - } + protected Destination createTemporaryDestination(Session session) throws JMSException { + if (topic) { + return session.createTemporaryTopic(); + } + return session.createTemporaryQueue(); + } + + protected void deleteTemporaryDestination(Destination dest) throws JMSException { + if (topic) { + ((TemporaryTopic) dest).delete(); + } + else { + ((TemporaryQueue) dest).delete(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicSelectorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicSelectorTest.java index e6a2503601..ece92cb818 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicSelectorTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicSelectorTest.java @@ -35,174 +35,176 @@ import org.slf4j.LoggerFactory; * */ public class JmsTopicSelectorTest extends TestSupport { - private static final Logger LOG = LoggerFactory.getLogger(JmsTopicSelectorTest.class); - protected Connection connection; - protected Session session; - protected MessageConsumer consumer; - protected MessageProducer producer; - protected Destination consumerDestination; - protected Destination producerDestination; - protected boolean topic = true; - protected boolean durable; - protected int deliveryMode = DeliveryMode.PERSISTENT; + private static final Logger LOG = LoggerFactory.getLogger(JmsTopicSelectorTest.class); - public void setUp() throws Exception { - super.setUp(); + protected Connection connection; + protected Session session; + protected MessageConsumer consumer; + protected MessageProducer producer; + protected Destination consumerDestination; + protected Destination producerDestination; + protected boolean topic = true; + protected boolean durable; + protected int deliveryMode = DeliveryMode.PERSISTENT; - connectionFactory = createConnectionFactory(); - connection = createConnection(); - if (durable) { - connection.setClientID(getClass().getName()); - } + public void setUp() throws Exception { + super.setUp(); - LOG.info("Created connection: " + connection); + connectionFactory = createConnectionFactory(); + connection = createConnection(); + if (durable) { + connection.setClientID(getClass().getName()); + } - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + LOG.info("Created connection: " + connection); - LOG.info("Created session: " + session); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - if (topic) { - consumerDestination = session.createTopic(getConsumerSubject()); - producerDestination = session.createTopic(getProducerSubject()); - } else { - consumerDestination = session.createQueue(getConsumerSubject()); - producerDestination = session.createQueue(getProducerSubject()); - } + LOG.info("Created session: " + session); - LOG.info("Created consumer destination: " + consumerDestination + " of type: " + consumerDestination.getClass()); - LOG.info("Created producer destination: " + producerDestination + " of type: " + producerDestination.getClass()); - producer = session.createProducer(producerDestination); - producer.setDeliveryMode(deliveryMode); + if (topic) { + consumerDestination = session.createTopic(getConsumerSubject()); + producerDestination = session.createTopic(getProducerSubject()); + } + else { + consumerDestination = session.createQueue(getConsumerSubject()); + producerDestination = session.createQueue(getProducerSubject()); + } - LOG.info("Created producer: " + producer + " delivery mode = " + (deliveryMode == DeliveryMode.PERSISTENT ? "PERSISTENT" : "NON_PERSISTENT")); - connection.start(); - } + LOG.info("Created consumer destination: " + consumerDestination + " of type: " + consumerDestination.getClass()); + LOG.info("Created producer destination: " + producerDestination + " of type: " + producerDestination.getClass()); + producer = session.createProducer(producerDestination); + producer.setDeliveryMode(deliveryMode); - public void tearDown() throws Exception { - session.close(); - connection.close(); - } + LOG.info("Created producer: " + producer + " delivery mode = " + (deliveryMode == DeliveryMode.PERSISTENT ? "PERSISTENT" : "NON_PERSISTENT")); + connection.start(); + } - protected MessageConsumer createConsumer(String selector) throws JMSException { - if (durable) { - LOG.info("Creating durable consumer"); - return session.createDurableSubscriber((Topic)consumerDestination, getName(), selector, false); - } - return session.createConsumer(consumerDestination, selector); - } + public void tearDown() throws Exception { + session.close(); + connection.close(); + } - public void sendMessages() throws Exception { - TextMessage message = session.createTextMessage("1"); - message.setIntProperty("id", 1); - message.setJMSType("a"); - message.setStringProperty("stringProperty", "a"); - message.setLongProperty("longProperty", 1); - message.setBooleanProperty("booleanProperty", true); - producer.send(message); + protected MessageConsumer createConsumer(String selector) throws JMSException { + if (durable) { + LOG.info("Creating durable consumer"); + return session.createDurableSubscriber((Topic) consumerDestination, getName(), selector, false); + } + return session.createConsumer(consumerDestination, selector); + } - message = session.createTextMessage("2"); - message.setIntProperty("id", 2); - message.setJMSType("a"); - message.setStringProperty("stringProperty", "a"); - message.setLongProperty("longProperty", 1); - message.setBooleanProperty("booleanProperty", false); - producer.send(message); + public void sendMessages() throws Exception { + TextMessage message = session.createTextMessage("1"); + message.setIntProperty("id", 1); + message.setJMSType("a"); + message.setStringProperty("stringProperty", "a"); + message.setLongProperty("longProperty", 1); + message.setBooleanProperty("booleanProperty", true); + producer.send(message); - message = session.createTextMessage("3"); - message.setIntProperty("id", 3); - message.setJMSType("a"); - message.setStringProperty("stringProperty", "a"); - message.setLongProperty("longProperty", 1); - message.setBooleanProperty("booleanProperty", true); - producer.send(message); + message = session.createTextMessage("2"); + message.setIntProperty("id", 2); + message.setJMSType("a"); + message.setStringProperty("stringProperty", "a"); + message.setLongProperty("longProperty", 1); + message.setBooleanProperty("booleanProperty", false); + producer.send(message); - message = session.createTextMessage("4"); - message.setIntProperty("id", 4); - message.setJMSType("b"); - message.setStringProperty("stringProperty", "b"); - message.setLongProperty("longProperty", 2); - message.setBooleanProperty("booleanProperty", false); - producer.send(message); + message = session.createTextMessage("3"); + message.setIntProperty("id", 3); + message.setJMSType("a"); + message.setStringProperty("stringProperty", "a"); + message.setLongProperty("longProperty", 1); + message.setBooleanProperty("booleanProperty", true); + producer.send(message); - message = session.createTextMessage("5"); - message.setIntProperty("id", 5); - message.setJMSType("c"); - message.setStringProperty("stringProperty", "c"); - message.setLongProperty("longProperty", 3); - message.setBooleanProperty("booleanProperty", true); - producer.send(message); - } + message = session.createTextMessage("4"); + message.setIntProperty("id", 4); + message.setJMSType("b"); + message.setStringProperty("stringProperty", "b"); + message.setLongProperty("longProperty", 2); + message.setBooleanProperty("booleanProperty", false); + producer.send(message); - public void consumeMessages(int remaining) throws Exception { - consumer = createConsumer(null); - for (int i = 0; i < remaining; i++) { - consumer.receive(1000); - } - consumer.close(); + message = session.createTextMessage("5"); + message.setIntProperty("id", 5); + message.setJMSType("c"); + message.setStringProperty("stringProperty", "c"); + message.setLongProperty("longProperty", 3); + message.setBooleanProperty("booleanProperty", true); + producer.send(message); + } - } + public void consumeMessages(int remaining) throws Exception { + consumer = createConsumer(null); + for (int i = 0; i < remaining; i++) { + consumer.receive(1000); + } + consumer.close(); - public void testEmptyPropertySelector() throws Exception { - int remaining = 5; - Message message = null; - consumer = createConsumer(""); - sendMessages(); - while (true) { - message = consumer.receive(1000); - if (message == null) { - break; - } + } - remaining--; - } - assertEquals(remaining, 0); - consumer.close(); - consumeMessages(remaining); - } + public void testEmptyPropertySelector() throws Exception { + int remaining = 5; + Message message = null; + consumer = createConsumer(""); + sendMessages(); + while (true) { + message = consumer.receive(1000); + if (message == null) { + break; + } - public void testPropertySelector() throws Exception { - int remaining = 5; - Message message = null; - consumer = createConsumer("stringProperty = 'a' and longProperty = 1 and booleanProperty = true"); - sendMessages(); - while (true) { - message = consumer.receive(1000); - if (message == null) { - break; - } - String text = ((TextMessage)message).getText(); - if (!text.equals("1") && !text.equals("3")) { - fail("unexpected message: " + text); - } - remaining--; - } - assertEquals(remaining, 3); - consumer.close(); - consumeMessages(remaining); + remaining--; + } + assertEquals(remaining, 0); + consumer.close(); + consumeMessages(remaining); + } - } + public void testPropertySelector() throws Exception { + int remaining = 5; + Message message = null; + consumer = createConsumer("stringProperty = 'a' and longProperty = 1 and booleanProperty = true"); + sendMessages(); + while (true) { + message = consumer.receive(1000); + if (message == null) { + break; + } + String text = ((TextMessage) message).getText(); + if (!text.equals("1") && !text.equals("3")) { + fail("unexpected message: " + text); + } + remaining--; + } + assertEquals(remaining, 3); + consumer.close(); + consumeMessages(remaining); - public void testJMSPropertySelector() throws Exception { - int remaining = 5; - Message message = null; - consumer = createConsumer("JMSType = 'a' and stringProperty = 'a'"); - sendMessages(); - while (true) { - message = consumer.receive(1000); - if (message == null) { - break; - } - String text = ((TextMessage)message).getText(); - if (!text.equals("1") && !text.equals("2") && !text.equals("3")) { - fail("unexpected message: " + text); - } - remaining--; - } - assertEquals(remaining, 2); - consumer.close(); - consumeMessages(remaining); + } - } + public void testJMSPropertySelector() throws Exception { + int remaining = 5; + Message message = null; + consumer = createConsumer("JMSType = 'a' and stringProperty = 'a'"); + sendMessages(); + while (true) { + message = consumer.receive(1000); + if (message == null) { + break; + } + String text = ((TextMessage) message).getText(); + if (!text.equals("1") && !text.equals("2") && !text.equals("3")) { + fail("unexpected message: " + text); + } + remaining--; + } + assertEquals(remaining, 2); + consumer.close(); + consumeMessages(remaining); + + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicSendReceiveSubscriberTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicSendReceiveSubscriberTest.java index 7cb09ea505..514b70e9cc 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicSendReceiveSubscriberTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicSendReceiveSubscriberTest.java @@ -22,15 +22,17 @@ import javax.jms.Topic; import javax.jms.TopicSession; /** - * + * */ public class JmsTopicSendReceiveSubscriberTest extends JmsTopicSendReceiveTest { - protected MessageConsumer createConsumer() throws JMSException { - if (durable) { - return super.createConsumer(); - } else { - TopicSession topicSession = (TopicSession)session; - return topicSession.createSubscriber((Topic)consumerDestination, null, false); - } - } + + protected MessageConsumer createConsumer() throws JMSException { + if (durable) { + return super.createConsumer(); + } + else { + TopicSession topicSession = (TopicSession) session; + return topicSession.createSubscriber((Topic) consumerDestination, null, false); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicSendReceiveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicSendReceiveTest.java index fd91ec4fa2..a801911b0e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicSendReceiveTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicSendReceiveTest.java @@ -27,66 +27,68 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class JmsTopicSendReceiveTest extends JmsSendReceiveTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(JmsTopicSendReceiveTest.class); - protected Connection connection; + private static final Logger LOG = LoggerFactory.getLogger(JmsTopicSendReceiveTest.class); - protected void setUp() throws Exception { - super.setUp(); + protected Connection connection; - connectionFactory = createConnectionFactory(); - connection = createConnection(); - if (durable) { - connection.setClientID(getClass().getName()); - } + protected void setUp() throws Exception { + super.setUp(); - LOG.info("Created connection: " + connection); + connectionFactory = createConnectionFactory(); + connection = createConnection(); + if (durable) { + connection.setClientID(getClass().getName()); + } - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + LOG.info("Created connection: " + connection); - LOG.info("Created session: " + session); - producer = session.createProducer(null); - producer.setDeliveryMode(deliveryMode); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - LOG.info("Created producer: " + producer + " delivery mode = " + (deliveryMode == DeliveryMode.PERSISTENT ? "PERSISTENT" : "NON_PERSISTENT")); + LOG.info("Created session: " + session); + producer = session.createProducer(null); + producer.setDeliveryMode(deliveryMode); - if (topic) { - consumerDestination = session.createTopic(getConsumerSubject()); - producerDestination = session.createTopic(getProducerSubject()); - } else { - consumerDestination = session.createQueue(getConsumerSubject()); - producerDestination = session.createQueue(getProducerSubject()); - } + LOG.info("Created producer: " + producer + " delivery mode = " + (deliveryMode == DeliveryMode.PERSISTENT ? "PERSISTENT" : "NON_PERSISTENT")); - LOG.info("Created consumer destination: " + consumerDestination + " of type: " + consumerDestination.getClass()); - LOG.info("Created producer destination: " + producerDestination + " of type: " + producerDestination.getClass()); - consumer = createConsumer(); - consumer.setMessageListener(this); - connection.start(); + if (topic) { + consumerDestination = session.createTopic(getConsumerSubject()); + producerDestination = session.createTopic(getProducerSubject()); + } + else { + consumerDestination = session.createQueue(getConsumerSubject()); + producerDestination = session.createQueue(getProducerSubject()); + } - // log.info("Created connection: " + connection); - } + LOG.info("Created consumer destination: " + consumerDestination + " of type: " + consumerDestination.getClass()); + LOG.info("Created producer destination: " + producerDestination + " of type: " + producerDestination.getClass()); + consumer = createConsumer(); + consumer.setMessageListener(this); + connection.start(); - protected MessageConsumer createConsumer() throws JMSException { - if (durable) { - LOG.info("Creating durable consumer"); - return session.createDurableSubscriber((Topic)consumerDestination, getName()); - } - return session.createConsumer(consumerDestination); - } + // log.info("Created connection: " + connection); + } - protected void tearDown() throws Exception { - LOG.info("Dumping stats..."); - // connectionFactory.getStats().reset(); + protected MessageConsumer createConsumer() throws JMSException { + if (durable) { + LOG.info("Creating durable consumer"); + return session.createDurableSubscriber((Topic) consumerDestination, getName()); + } + return session.createConsumer(consumerDestination); + } - LOG.info("Closing down connection"); + protected void tearDown() throws Exception { + LOG.info("Dumping stats..."); + // connectionFactory.getStats().reset(); - /** TODO we should be able to shut down properly */ - session.close(); - connection.close(); - } + LOG.info("Closing down connection"); + + /** TODO we should be able to shut down properly */ + session.close(); + connection.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicSendReceiveWithTwoConnectionsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicSendReceiveWithTwoConnectionsTest.java index b56c15de35..be9abb1c39 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicSendReceiveWithTwoConnectionsTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicSendReceiveWithTwoConnectionsTest.java @@ -28,86 +28,83 @@ import javax.jms.Session; */ public class JmsTopicSendReceiveWithTwoConnectionsTest extends JmsSendReceiveTestSupport { - private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory - .getLog(JmsTopicSendReceiveWithTwoConnectionsTest.class); + private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(JmsTopicSendReceiveWithTwoConnectionsTest.class); - protected Connection sendConnection; - protected Connection receiveConnection; - protected Session receiveSession; + protected Connection sendConnection; + protected Connection receiveConnection; + protected Session receiveSession; - protected void setUp() throws Exception { - super.setUp(); + protected void setUp() throws Exception { + super.setUp(); - connectionFactory = createConnectionFactory(); + connectionFactory = createConnectionFactory(); - sendConnection = createSendConnection(); - sendConnection.start(); + sendConnection = createSendConnection(); + sendConnection.start(); - receiveConnection = createReceiveConnection(); - receiveConnection.start(); + receiveConnection = createReceiveConnection(); + receiveConnection.start(); - LOG.info("Created sendConnection: " + sendConnection); - LOG.info("Created receiveConnection: " + receiveConnection); + LOG.info("Created sendConnection: " + sendConnection); + LOG.info("Created receiveConnection: " + receiveConnection); - session = createSendSession(sendConnection); - receiveSession = createReceiveSession(receiveConnection); + session = createSendSession(sendConnection); + receiveSession = createReceiveSession(receiveConnection); - LOG.info("Created sendSession: " + session); - LOG.info("Created receiveSession: " + receiveSession); + LOG.info("Created sendSession: " + session); + LOG.info("Created receiveSession: " + receiveSession); - producer = session.createProducer(null); - producer.setDeliveryMode(deliveryMode); + producer = session.createProducer(null); + producer.setDeliveryMode(deliveryMode); - LOG.info("Created producer: " + producer + " delivery mode = " - + (deliveryMode == DeliveryMode.PERSISTENT ? "PERSISTENT" : "NON_PERSISTENT")); + LOG.info("Created producer: " + producer + " delivery mode = " + (deliveryMode == DeliveryMode.PERSISTENT ? "PERSISTENT" : "NON_PERSISTENT")); - if (topic) { - consumerDestination = session.createTopic(getConsumerSubject()); - producerDestination = session.createTopic(getProducerSubject()); - } else { - consumerDestination = session.createQueue(getConsumerSubject()); - producerDestination = session.createQueue(getProducerSubject()); - } + if (topic) { + consumerDestination = session.createTopic(getConsumerSubject()); + producerDestination = session.createTopic(getProducerSubject()); + } + else { + consumerDestination = session.createQueue(getConsumerSubject()); + producerDestination = session.createQueue(getProducerSubject()); + } - LOG.info("Created consumer destination: " + consumerDestination + " of type: " - + consumerDestination.getClass()); - LOG.info("Created producer destination: " + producerDestination + " of type: " - + producerDestination.getClass()); + LOG.info("Created consumer destination: " + consumerDestination + " of type: " + consumerDestination.getClass()); + LOG.info("Created producer destination: " + producerDestination + " of type: " + producerDestination.getClass()); - consumer = createConsumer(receiveSession, consumerDestination); - consumer.setMessageListener(this); + consumer = createConsumer(receiveSession, consumerDestination); + consumer.setMessageListener(this); - LOG.info("Started connections"); - } + LOG.info("Started connections"); + } - protected Session createReceiveSession(Connection receiveConnection) throws Exception { - return receiveConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } + protected Session createReceiveSession(Connection receiveConnection) throws Exception { + return receiveConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + } - protected Session createSendSession(Connection sendConnection) throws Exception { - return sendConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } + protected Session createSendSession(Connection sendConnection) throws Exception { + return sendConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + } - protected Connection createReceiveConnection() throws Exception { - return createConnection(); - } + protected Connection createReceiveConnection() throws Exception { + return createConnection(); + } - protected Connection createSendConnection() throws Exception { - return createConnection(); - } + protected Connection createSendConnection() throws Exception { + return createConnection(); + } - protected MessageConsumer createConsumer(Session session, Destination dest) throws JMSException { - return session.createConsumer(dest); - } + protected MessageConsumer createConsumer(Session session, Destination dest) throws JMSException { + return session.createConsumer(dest); + } - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); + } - protected void tearDown() throws Exception { - session.close(); - receiveSession.close(); - sendConnection.close(); - receiveConnection.close(); - } + protected void tearDown() throws Exception { + session.close(); + receiveSession.close(); + sendConnection.close(); + receiveConnection.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicSendReceiveWithTwoConnectionsWithJMXTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicSendReceiveWithTwoConnectionsWithJMXTest.java index da2c80cdcd..508740f0ca 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicSendReceiveWithTwoConnectionsWithJMXTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicSendReceiveWithTwoConnectionsWithJMXTest.java @@ -17,13 +17,12 @@ package org.apache.activemq; /** - * - * + * + * */ -public class JmsTopicSendReceiveWithTwoConnectionsWithJMXTest extends - JmsTopicSendReceiveWithTwoConnectionsTest { +public class JmsTopicSendReceiveWithTwoConnectionsWithJMXTest extends JmsTopicSendReceiveWithTwoConnectionsTest { - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false&broker.useJmx=true"); - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false&broker.useJmx=true"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicSendSameMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicSendSameMessageTest.java index 9a92e4994c..02c408a47f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicSendSameMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicSendSameMessageTest.java @@ -19,30 +19,29 @@ package org.apache.activemq; import javax.jms.TextMessage; /** - * + * */ public class JmsTopicSendSameMessageTest extends JmsTopicSendReceiveWithTwoConnectionsTest { - private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory - .getLog(JmsTopicSendSameMessageTest.class); + private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(JmsTopicSendSameMessageTest.class); - public void testSendReceive() throws Exception { - messages.clear(); + public void testSendReceive() throws Exception { + messages.clear(); - TextMessage message = session.createTextMessage(); + TextMessage message = session.createTextMessage(); - for (int i = 0; i < data.length; i++) { - message.setText(data[i]); - message.setStringProperty("stringProperty", data[i]); - message.setIntProperty("intProperty", i); + for (int i = 0; i < data.length; i++) { + message.setText(data[i]); + message.setStringProperty("stringProperty", data[i]); + message.setIntProperty("intProperty", i); - if (verbose) { - LOG.info("About to send a message: " + message + " with text: " + data[i]); - } + if (verbose) { + LOG.info("About to send a message: " + message + " with text: " + data[i]); + } - producer.send(producerDestination, message); - } + producer.send(producerDestination, message); + } - assertMessagesAreReceived(); - } + assertMessagesAreReceived(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicTransactionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicTransactionTest.java index cf5cdc0c03..2beb0a0d59 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicTransactionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicTransactionTest.java @@ -18,21 +18,20 @@ package org.apache.activemq; import org.apache.activemq.test.JmsResourceProvider; - /** - * + * */ public class JmsTopicTransactionTest extends JmsTransactionTestSupport { - /** - * @see org.apache.activemq.JmsTransactionTestSupport#getJmsResourceProvider() - */ - protected JmsResourceProvider getJmsResourceProvider() { - JmsResourceProvider p = new JmsResourceProvider(); - p.setTopic(true); - p.setDurableName("testsub"); - p.setClientID("testclient"); - return p; - } + /** + * @see org.apache.activemq.JmsTransactionTestSupport#getJmsResourceProvider() + */ + protected JmsResourceProvider getJmsResourceProvider() { + JmsResourceProvider p = new JmsResourceProvider(); + p.setTopic(true); + p.setDurableName("testsub"); + p.setClientID("testclient"); + return p; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicWildcardSendReceiveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicWildcardSendReceiveTest.java index eeb599988a..69177714a9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicWildcardSendReceiveTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsTopicWildcardSendReceiveTest.java @@ -24,186 +24,183 @@ import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; + import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.test.JmsTopicSendReceiveTest; /** - * + * */ public class JmsTopicWildcardSendReceiveTest extends JmsTopicSendReceiveTest { - private String destination1String = "TEST.ONE.ONE"; - private String destination2String = "TEST.ONE.ONE.ONE"; - private String destination3String = "TEST.ONE.TWO"; - private String destination4String = "TEST.TWO.ONE"; + private String destination1String = "TEST.ONE.ONE"; + private String destination2String = "TEST.ONE.ONE.ONE"; + private String destination3String = "TEST.ONE.TWO"; + private String destination4String = "TEST.TWO.ONE"; - protected void setUp() throws Exception { - topic = true; - durable = false; - deliveryMode = DeliveryMode.NON_PERSISTENT; - super.setUp(); - } + protected void setUp() throws Exception { + topic = true; + durable = false; + deliveryMode = DeliveryMode.NON_PERSISTENT; + super.setUp(); + } - protected String getConsumerSubject() { - return "FOO.>"; - } + protected String getConsumerSubject() { + return "FOO.>"; + } - protected String getProducerSubject() { - return "FOO.BAR.HUMBUG"; - } + protected String getProducerSubject() { + return "FOO.BAR.HUMBUG"; + } - public void testReceiveWildcardTopicEndAsterisk() throws Exception { - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + public void testReceiveWildcardTopicEndAsterisk() throws Exception { + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination1 = (ActiveMQDestination)session.createTopic(destination1String); - ActiveMQDestination destination3 = (ActiveMQDestination)session.createTopic(destination3String); + ActiveMQDestination destination1 = (ActiveMQDestination) session.createTopic(destination1String); + ActiveMQDestination destination3 = (ActiveMQDestination) session.createTopic(destination3String); - Message m = null; - MessageConsumer consumer = null; - String text = null; + Message m = null; + MessageConsumer consumer = null; + String text = null; - ActiveMQDestination destination6 = (ActiveMQDestination)session.createTopic("TEST.ONE.*"); - consumer = session.createConsumer(destination6); - sendMessage(session, destination1, destination1String); - sendMessage(session, destination3, destination3String); - m = consumer.receive(1000); - assertNotNull(m); - text = ((TextMessage)m).getText(); - if (!(text.equals(destination1String) || text.equals(destination3String))) { - fail("unexpected message:" + text); - } - m = consumer.receive(1000); - assertNotNull(m); - text = ((TextMessage)m).getText(); - if (!(text.equals(destination1String) || text.equals(destination3String))) { - fail("unexpected message:" + text); - } - assertNull(consumer.receiveNoWait()); - } + ActiveMQDestination destination6 = (ActiveMQDestination) session.createTopic("TEST.ONE.*"); + consumer = session.createConsumer(destination6); + sendMessage(session, destination1, destination1String); + sendMessage(session, destination3, destination3String); + m = consumer.receive(1000); + assertNotNull(m); + text = ((TextMessage) m).getText(); + if (!(text.equals(destination1String) || text.equals(destination3String))) { + fail("unexpected message:" + text); + } + m = consumer.receive(1000); + assertNotNull(m); + text = ((TextMessage) m).getText(); + if (!(text.equals(destination1String) || text.equals(destination3String))) { + fail("unexpected message:" + text); + } + assertNull(consumer.receiveNoWait()); + } - public void testReceiveWildcardTopicEndGreaterThan() throws Exception { - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + public void testReceiveWildcardTopicEndGreaterThan() throws Exception { + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination1 = (ActiveMQDestination)session.createTopic(destination1String); - ActiveMQDestination destination2 = (ActiveMQDestination)session.createTopic(destination2String); - ActiveMQDestination destination3 = (ActiveMQDestination)session.createTopic(destination3String); + ActiveMQDestination destination1 = (ActiveMQDestination) session.createTopic(destination1String); + ActiveMQDestination destination2 = (ActiveMQDestination) session.createTopic(destination2String); + ActiveMQDestination destination3 = (ActiveMQDestination) session.createTopic(destination3String); - Message m = null; - MessageConsumer consumer = null; - String text = null; + Message m = null; + MessageConsumer consumer = null; + String text = null; - ActiveMQDestination destination7 = (ActiveMQDestination)session.createTopic("TEST.ONE.>"); - consumer = session.createConsumer(destination7); - sendMessage(session, destination1, destination1String); - sendMessage(session, destination2, destination2String); - sendMessage(session, destination3, destination3String); - m = consumer.receive(1000); - assertNotNull(m); - text = ((TextMessage)m).getText(); - if (!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { - fail("unexpected message:" + text); - } - m = consumer.receive(1000); - assertNotNull(m); - if (!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { - fail("unexpected message:" + text); - } - m = consumer.receive(1000); - assertNotNull(m); - if (!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { - fail("unexpected message:" + text); - } - assertNull(consumer.receiveNoWait()); - } + ActiveMQDestination destination7 = (ActiveMQDestination) session.createTopic("TEST.ONE.>"); + consumer = session.createConsumer(destination7); + sendMessage(session, destination1, destination1String); + sendMessage(session, destination2, destination2String); + sendMessage(session, destination3, destination3String); + m = consumer.receive(1000); + assertNotNull(m); + text = ((TextMessage) m).getText(); + if (!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { + fail("unexpected message:" + text); + } + m = consumer.receive(1000); + assertNotNull(m); + if (!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { + fail("unexpected message:" + text); + } + m = consumer.receive(1000); + assertNotNull(m); + if (!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { + fail("unexpected message:" + text); + } + assertNull(consumer.receiveNoWait()); + } - public void testReceiveWildcardTopicMidAsterisk() throws Exception { - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + public void testReceiveWildcardTopicMidAsterisk() throws Exception { + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination1 = (ActiveMQDestination)session.createTopic(destination1String); - ActiveMQDestination destination4 = (ActiveMQDestination)session.createTopic(destination4String); + ActiveMQDestination destination1 = (ActiveMQDestination) session.createTopic(destination1String); + ActiveMQDestination destination4 = (ActiveMQDestination) session.createTopic(destination4String); - Message m = null; - MessageConsumer consumer = null; - String text = null; + Message m = null; + MessageConsumer consumer = null; + String text = null; - ActiveMQDestination destination8 = (ActiveMQDestination)session.createTopic("TEST.*.ONE"); - consumer = session.createConsumer(destination8); - sendMessage(session, destination1, destination1String); - sendMessage(session, destination4, destination4String); - m = consumer.receive(1000); - assertNotNull(m); - text = ((TextMessage)m).getText(); - if (!(text.equals(destination1String) || text.equals(destination4String))) { - fail("unexpected message:" + text); - } - m = consumer.receive(1000); - assertNotNull(m); - text = ((TextMessage)m).getText(); - if (!(text.equals(destination1String) || text.equals(destination4String))) { - fail("unexpected message:" + text); - } - assertNull(consumer.receiveNoWait()); + ActiveMQDestination destination8 = (ActiveMQDestination) session.createTopic("TEST.*.ONE"); + consumer = session.createConsumer(destination8); + sendMessage(session, destination1, destination1String); + sendMessage(session, destination4, destination4String); + m = consumer.receive(1000); + assertNotNull(m); + text = ((TextMessage) m).getText(); + if (!(text.equals(destination1String) || text.equals(destination4String))) { + fail("unexpected message:" + text); + } + m = consumer.receive(1000); + assertNotNull(m); + text = ((TextMessage) m).getText(); + if (!(text.equals(destination1String) || text.equals(destination4String))) { + fail("unexpected message:" + text); + } + assertNull(consumer.receiveNoWait()); - } + } - public void testReceiveWildcardTopicMatchDoubleWildcard() throws Exception { - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + public void testReceiveWildcardTopicMatchDoubleWildcard() throws Exception { + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination1 = (ActiveMQDestination)session.createTopic("a.*.>.>"); - ActiveMQDestination destination2 = (ActiveMQDestination)session.createTopic("a.b"); + ActiveMQDestination destination1 = (ActiveMQDestination) session.createTopic("a.*.>.>"); + ActiveMQDestination destination2 = (ActiveMQDestination) session.createTopic("a.b"); - Message m = null; - MessageConsumer consumer = null; - String text = null; + Message m = null; + MessageConsumer consumer = null; + String text = null; + consumer = session.createConsumer(destination1); + sendMessage(session, destination2, destination3String); - consumer = session.createConsumer(destination1); - sendMessage(session, destination2, destination3String); + m = consumer.receive(1000); + assertNotNull(m); + text = ((TextMessage) m).getText(); + if (!(text.equals(destination1String) || text.equals(destination3String))) { + fail("unexpected message:" + text); + } - m = consumer.receive(1000); - assertNotNull(m); - text = ((TextMessage)m).getText(); - if (!(text.equals(destination1String) || text.equals(destination3String))) { - fail("unexpected message:" + text); - } + assertNull(consumer.receiveNoWait()); + } - assertNull(consumer.receiveNoWait()); - } + public void testReceiveWildcardTopicMatchSinglePastTheEndWildcard() throws Exception { + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - public void testReceiveWildcardTopicMatchSinglePastTheEndWildcard() throws Exception { - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQDestination destination1 = (ActiveMQDestination) session.createTopic("a.>"); + ActiveMQDestination destination2 = (ActiveMQDestination) session.createTopic("a"); - ActiveMQDestination destination1 = (ActiveMQDestination)session.createTopic("a.>"); - ActiveMQDestination destination2 = (ActiveMQDestination)session.createTopic("a"); + Message m = null; + MessageConsumer consumer = null; + String text = null; - Message m = null; - MessageConsumer consumer = null; - String text = null; + consumer = session.createConsumer(destination1); + sendMessage(session, destination2, destination3String); + m = consumer.receive(1000); + assertNotNull(m); + text = ((TextMessage) m).getText(); + if (!(text.equals(destination1String) || text.equals(destination3String))) { + fail("unexpected message:" + text); + } - consumer = session.createConsumer(destination1); - sendMessage(session, destination2, destination3String); + assertNull(consumer.receiveNoWait()); + } - m = consumer.receive(1000); - assertNotNull(m); - text = ((TextMessage)m).getText(); - if (!(text.equals(destination1String) || text.equals(destination3String))) { - fail("unexpected message:" + text); - } - - assertNull(consumer.receiveNoWait()); - } - - - - private void sendMessage(Session session, Destination destination, String text) throws JMSException { - MessageProducer producer = session.createProducer(destination); - producer.send(session.createTextMessage(text)); - producer.close(); - } + private void sendMessage(Session session, Destination destination, String text) throws JMSException { + MessageProducer producer = session.createProducer(destination); + producer.send(session.createTextMessage(text)); + producer.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/LargeMessageTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/LargeMessageTestSupport.java index d1ab8a5ba7..55cb99780e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/LargeMessageTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/LargeMessageTestSupport.java @@ -39,159 +39,164 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class LargeMessageTestSupport extends ClientTestSupport implements MessageListener { - protected static final int LARGE_MESSAGE_SIZE = 128 * 1024; - protected static final int MESSAGE_COUNT = 100; + protected static final int LARGE_MESSAGE_SIZE = 128 * 1024; + protected static final int MESSAGE_COUNT = 100; - private static final Logger LOG = LoggerFactory.getLogger(LargeMessageTestSupport.class); + private static final Logger LOG = LoggerFactory.getLogger(LargeMessageTestSupport.class); - protected Connection producerConnection; - protected Connection consumerConnection; - protected MessageConsumer consumer; - protected MessageProducer producer; - protected Session producerSession; - protected Session consumerSession; - protected byte[] largeMessageData; - protected Destination destination; - protected boolean isTopic = true; - protected boolean isDurable = true; - protected int deliveryMode = DeliveryMode.PERSISTENT; - protected IdGenerator idGen = new IdGenerator(); - protected boolean validMessageConsumption = true; - protected final AtomicInteger messageCount = new AtomicInteger(0); + protected Connection producerConnection; + protected Connection consumerConnection; + protected MessageConsumer consumer; + protected MessageProducer producer; + protected Session producerSession; + protected Session consumerSession; + protected byte[] largeMessageData; + protected Destination destination; + protected boolean isTopic = true; + protected boolean isDurable = true; + protected int deliveryMode = DeliveryMode.PERSISTENT; + protected IdGenerator idGen = new IdGenerator(); + protected boolean validMessageConsumption = true; + protected final AtomicInteger messageCount = new AtomicInteger(0); - protected int prefetchValue = 10000000; + protected int prefetchValue = 10000000; - protected Destination createDestination() { - String subject = getClass().getName(); - if (isTopic) { - return new ActiveMQTopic(subject); - } else { - return new ActiveMQQueue(subject); - } - } + protected Destination createDestination() { + String subject = getClass().getName(); + if (isTopic) { + return new ActiveMQTopic(subject); + } + else { + return new ActiveMQQueue(subject); + } + } - protected MessageConsumer createConsumer() throws JMSException { - if (isTopic && isDurable) { - return consumerSession.createDurableSubscriber((Topic)destination, idGen.generateId()); - } else { - return consumerSession.createConsumer(destination); - } - } + protected MessageConsumer createConsumer() throws JMSException { + if (isTopic && isDurable) { + return consumerSession.createDurableSubscriber((Topic) destination, idGen.generateId()); + } + else { + return consumerSession.createConsumer(destination); + } + } - public void setUp() throws Exception { - super.setUp(); - ClientTestSupport.removeMessageStore(); - LOG.info("Setting up . . . . . "); - messageCount.set(0); + public void setUp() throws Exception { + super.setUp(); + ClientTestSupport.removeMessageStore(); + LOG.info("Setting up . . . . . "); + messageCount.set(0); - destination = createDestination(); - largeMessageData = new byte[LARGE_MESSAGE_SIZE]; - for (int i = 0; i < LARGE_MESSAGE_SIZE; i++) { - if (i % 2 == 0) { - largeMessageData[i] = 'a'; - } else { - largeMessageData[i] = 'z'; + destination = createDestination(); + largeMessageData = new byte[LARGE_MESSAGE_SIZE]; + for (int i = 0; i < LARGE_MESSAGE_SIZE; i++) { + if (i % 2 == 0) { + largeMessageData[i] = 'a'; + } + else { + largeMessageData[i] = 'z'; + } + } + + try { + // allow the broker to start + Thread.sleep(1000); + } + catch (InterruptedException e) { + throw new JMSException(e.getMessage()); + } + + ActiveMQConnectionFactory fac = getConnectionFactory(); + producerConnection = fac.createConnection(); + setPrefetchPolicy((ActiveMQConnection) producerConnection); + producerConnection.start(); + + consumerConnection = fac.createConnection(); + setPrefetchPolicy((ActiveMQConnection) consumerConnection); + consumerConnection.setClientID(idGen.generateId()); + consumerConnection.start(); + producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer = producerSession.createProducer(createDestination()); + producer.setDeliveryMode(deliveryMode); + consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumer = createConsumer(); + consumer.setMessageListener(this); + LOG.info("Setup complete"); + } + + protected void setPrefetchPolicy(ActiveMQConnection activeMQConnection) { + activeMQConnection.getPrefetchPolicy().setTopicPrefetch(prefetchValue); + activeMQConnection.getPrefetchPolicy().setQueuePrefetch(prefetchValue); + activeMQConnection.getPrefetchPolicy().setDurableTopicPrefetch(prefetchValue); + activeMQConnection.getPrefetchPolicy().setQueueBrowserPrefetch(prefetchValue); + activeMQConnection.getPrefetchPolicy().setOptimizeDurableTopicPrefetch(prefetchValue); + } + + public void tearDown() throws Exception { + Thread.sleep(1000); + producerConnection.close(); + consumerConnection.close(); + + super.tearDown(); + + largeMessageData = null; + } + + protected boolean isSame(BytesMessage msg1) throws Exception { + boolean result = false; + ((ActiveMQMessage) msg1).setReadOnlyBody(true); + + for (int i = 0; i < LARGE_MESSAGE_SIZE; i++) { + result = msg1.readByte() == largeMessageData[i]; + if (!result) { + break; + } + } + + return result; + } + + public void onMessage(Message msg) { + try { + BytesMessage ba = (BytesMessage) msg; + validMessageConsumption &= isSame(ba); + assertTrue(ba.getBodyLength() == LARGE_MESSAGE_SIZE); + if (messageCount.incrementAndGet() >= MESSAGE_COUNT) { + synchronized (messageCount) { + messageCount.notify(); } - } + } + LOG.info("got message = " + messageCount); + if (messageCount.get() % 50 == 0) { + LOG.info("count = " + messageCount); + } + } + catch (Exception e) { + e.printStackTrace(); + } + } - try { - // allow the broker to start - Thread.sleep(1000); - } catch (InterruptedException e) { - throw new JMSException(e.getMessage()); - } - - ActiveMQConnectionFactory fac = getConnectionFactory(); - producerConnection = fac.createConnection(); - setPrefetchPolicy((ActiveMQConnection)producerConnection); - producerConnection.start(); - - consumerConnection = fac.createConnection(); - setPrefetchPolicy((ActiveMQConnection)consumerConnection); - consumerConnection.setClientID(idGen.generateId()); - consumerConnection.start(); - producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = producerSession.createProducer(createDestination()); - producer.setDeliveryMode(deliveryMode); - consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = createConsumer(); - consumer.setMessageListener(this); - LOG.info("Setup complete"); - } - - protected void setPrefetchPolicy(ActiveMQConnection activeMQConnection) { - activeMQConnection.getPrefetchPolicy().setTopicPrefetch(prefetchValue); - activeMQConnection.getPrefetchPolicy().setQueuePrefetch(prefetchValue); - activeMQConnection.getPrefetchPolicy().setDurableTopicPrefetch(prefetchValue); - activeMQConnection.getPrefetchPolicy().setQueueBrowserPrefetch(prefetchValue); - activeMQConnection.getPrefetchPolicy().setOptimizeDurableTopicPrefetch(prefetchValue); - } - - public void tearDown() throws Exception { - Thread.sleep(1000); - producerConnection.close(); - consumerConnection.close(); - - super.tearDown(); - - largeMessageData = null; - } - - protected boolean isSame(BytesMessage msg1) throws Exception { - boolean result = false; - ((ActiveMQMessage)msg1).setReadOnlyBody(true); - - for (int i = 0; i < LARGE_MESSAGE_SIZE; i++) { - result = msg1.readByte() == largeMessageData[i]; - if (!result) { - break; - } - } - - return result; - } - - public void onMessage(Message msg) { - try { - BytesMessage ba = (BytesMessage)msg; - validMessageConsumption &= isSame(ba); - assertTrue(ba.getBodyLength() == LARGE_MESSAGE_SIZE); - if (messageCount.incrementAndGet() >= MESSAGE_COUNT) { - synchronized (messageCount) { - messageCount.notify(); - } - } - LOG.info("got message = " + messageCount); - if (messageCount.get() % 50 == 0) { - LOG.info("count = " + messageCount); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - public void testLargeMessages() throws Exception { - for (int i = 0; i < MESSAGE_COUNT; i++) { - LOG.info("Sending message: " + i); - BytesMessage msg = producerSession.createBytesMessage(); - msg.writeBytes(largeMessageData); - producer.send(msg); - } - long now = System.currentTimeMillis(); - synchronized (messageCount) { - while (now + 60000 > System.currentTimeMillis() && messageCount.get() < MESSAGE_COUNT) { - LOG.info("message count = " + messageCount); - messageCount.wait(1000); - } - } - LOG.info("Finished count = " + messageCount); - assertTrue("Not enough messages - expected " + MESSAGE_COUNT + " but got " + messageCount, messageCount.get() == MESSAGE_COUNT); - assertTrue("received messages are not valid", validMessageConsumption); - Thread.sleep(1000); - LOG.info("FINAL count = " + messageCount); - } + public void testLargeMessages() throws Exception { + for (int i = 0; i < MESSAGE_COUNT; i++) { + LOG.info("Sending message: " + i); + BytesMessage msg = producerSession.createBytesMessage(); + msg.writeBytes(largeMessageData); + producer.send(msg); + } + long now = System.currentTimeMillis(); + synchronized (messageCount) { + while (now + 60000 > System.currentTimeMillis() && messageCount.get() < MESSAGE_COUNT) { + LOG.info("message count = " + messageCount); + messageCount.wait(1000); + } + } + LOG.info("Finished count = " + messageCount); + assertTrue("Not enough messages - expected " + MESSAGE_COUNT + " but got " + messageCount, messageCount.get() == MESSAGE_COUNT); + assertTrue("received messages are not valid", validMessageConsumption); + Thread.sleep(1000); + LOG.info("FINAL count = " + messageCount); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/LargeStreamletTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/LargeStreamletTest.java index d624d368c5..37899e8a29 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/LargeStreamletTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/LargeStreamletTest.java @@ -52,111 +52,119 @@ import org.slf4j.LoggerFactory; */ public final class LargeStreamletTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(LargeStreamletTest.class); - private static final String BROKER_URL = "vm://localhost?broker.persistent=false"; - private static final int BUFFER_SIZE = 1 * 1024; - private static final int MESSAGE_COUNT = 10 * 1024; + private static final Logger LOG = LoggerFactory.getLogger(LargeStreamletTest.class); + private static final String BROKER_URL = "vm://localhost?broker.persistent=false"; + private static final int BUFFER_SIZE = 1 * 1024; + private static final int MESSAGE_COUNT = 10 * 1024; - protected Exception writerException; - protected Exception readerException; + protected Exception writerException; + protected Exception readerException; - private final AtomicInteger totalRead = new AtomicInteger(); - private final AtomicInteger totalWritten = new AtomicInteger(); - private final AtomicBoolean stopThreads = new AtomicBoolean(false); + private final AtomicInteger totalRead = new AtomicInteger(); + private final AtomicInteger totalWritten = new AtomicInteger(); + private final AtomicBoolean stopThreads = new AtomicBoolean(false); - public void testStreamlets() throws Exception { - final ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(BROKER_URL); + public void testStreamlets() throws Exception { + final ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(BROKER_URL); - final ActiveMQConnection connection = (ActiveMQConnection)factory.createConnection(); - connection.start(); - try { - final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - try { - final Destination destination = session.createQueue("wibble"); - final Thread readerThread = new Thread(new Runnable() { + final ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); + connection.start(); + try { + final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + try { + final Destination destination = session.createQueue("wibble"); + final Thread readerThread = new Thread(new Runnable() { - @Override - public void run() { - totalRead.set(0); - try { - final InputStream inputStream = connection.createInputStream(destination); - try { - int read; - final byte[] buf = new byte[BUFFER_SIZE]; - while (!stopThreads.get() && (read = inputStream.read(buf)) != -1) { - totalRead.addAndGet(read); - } - } finally { - inputStream.close(); - } - } catch (Exception e) { - readerException = e; - e.printStackTrace(); - } finally { - LOG.info(totalRead + " total bytes read."); + @Override + public void run() { + totalRead.set(0); + try { + final InputStream inputStream = connection.createInputStream(destination); + try { + int read; + final byte[] buf = new byte[BUFFER_SIZE]; + while (!stopThreads.get() && (read = inputStream.read(buf)) != -1) { + totalRead.addAndGet(read); } - } - }); + } + finally { + inputStream.close(); + } + } + catch (Exception e) { + readerException = e; + e.printStackTrace(); + } + finally { + LOG.info(totalRead + " total bytes read."); + } + } + }); - final Thread writerThread = new Thread(new Runnable() { - private final Random random = new Random(); + final Thread writerThread = new Thread(new Runnable() { + private final Random random = new Random(); - @Override - public void run() { - totalWritten.set(0); - int count = MESSAGE_COUNT; - try { - final OutputStream outputStream = connection.createOutputStream(destination); - try { - final byte[] buf = new byte[BUFFER_SIZE]; - random.nextBytes(buf); - while (count > 0 && !stopThreads.get()) { - outputStream.write(buf); - totalWritten.addAndGet(buf.length); - count--; - } - } finally { - outputStream.close(); - } - } catch (Exception e) { - writerException = e; - e.printStackTrace(); - } finally { - LOG.info(totalWritten + " total bytes written."); + @Override + public void run() { + totalWritten.set(0); + int count = MESSAGE_COUNT; + try { + final OutputStream outputStream = connection.createOutputStream(destination); + try { + final byte[] buf = new byte[BUFFER_SIZE]; + random.nextBytes(buf); + while (count > 0 && !stopThreads.get()) { + outputStream.write(buf); + totalWritten.addAndGet(buf.length); + count--; } - } - }); + } + finally { + outputStream.close(); + } + } + catch (Exception e) { + writerException = e; + e.printStackTrace(); + } + finally { + LOG.info(totalWritten + " total bytes written."); + } + } + }); - readerThread.start(); - writerThread.start(); + readerThread.start(); + writerThread.start(); - // Wait till reader is has finished receiving all the messages - // or he has stopped - // receiving messages. - Thread.sleep(1000); - int lastRead = totalRead.get(); - while (readerThread.isAlive()) { - readerThread.join(1000); - // No progress?? then stop waiting.. - if (lastRead == totalRead.get()) { - break; - } - lastRead = totalRead.get(); - } - - stopThreads.set(true); - - assertTrue("Should not have received a reader exception", readerException == null); - assertTrue("Should not have received a writer exception", writerException == null); - - assertEquals("Not all messages accounted for", totalWritten.get(), totalRead.get()); - - } finally { - session.close(); + // Wait till reader is has finished receiving all the messages + // or he has stopped + // receiving messages. + Thread.sleep(1000); + int lastRead = totalRead.get(); + while (readerThread.isAlive()) { + readerThread.join(1000); + // No progress?? then stop waiting.. + if (lastRead == totalRead.get()) { + break; + } + lastRead = totalRead.get(); } - } finally { - connection.close(); - } - } + + stopThreads.set(true); + + assertTrue("Should not have received a reader exception", readerException == null); + assertTrue("Should not have received a writer exception", writerException == null); + + assertEquals("Not all messages accounted for", totalWritten.get(), totalRead.get()); + + } + finally { + session.close(); + } + } + finally { + connection.close(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/LoadTestBurnIn.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/LoadTestBurnIn.java index 4462844bd6..e243a6afe3 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/LoadTestBurnIn.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/LoadTestBurnIn.java @@ -34,6 +34,7 @@ import javax.jms.Session; import javax.jms.Topic; import junit.framework.Test; + import org.apache.activemq.broker.BrokerFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.TransportConnector; @@ -45,127 +46,125 @@ import org.slf4j.LoggerFactory; * Small burn test moves sends a moderate amount of messages through the broker, * to checking to make sure that the broker does not lock up after a while of * sustained messaging. - * - * */ public class LoadTestBurnIn extends JmsTestSupport { - private static final transient Logger LOG = LoggerFactory.getLogger(LoadTestBurnIn.class); - public ActiveMQDestination destination; - public int deliveryMode; - public byte destinationType; - public boolean durableConsumer; - public int messageCount = 50000; - public int messageSize = 1024; + private static final transient Logger LOG = LoggerFactory.getLogger(LoadTestBurnIn.class); - public static Test suite() { - return suite(LoadTestBurnIn.class); - } + public ActiveMQDestination destination; + public int deliveryMode; + public byte destinationType; + public boolean durableConsumer; + public int messageCount = 50000; + public int messageSize = 1024; - protected void setUp() throws Exception { - LOG.info("Start: " + getName()); - super.setUp(); - } + public static Test suite() { + return suite(LoadTestBurnIn.class); + } - protected void tearDown() throws Exception { - try { - super.tearDown(); - } catch (Throwable e) { - e.printStackTrace(System.out); - } finally { - LOG.info("End: " + getName()); - } - } + protected void setUp() throws Exception { + LOG.info("Start: " + getName()); + super.setUp(); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + protected void tearDown() throws Exception { + try { + super.tearDown(); + } + catch (Throwable e) { + e.printStackTrace(System.out); + } + finally { + LOG.info("End: " + getName()); + } + } - protected BrokerService createBroker() throws Exception { - return BrokerFactory.createBroker(new URI("broker://(tcp://localhost:0)?useJmx=true")); - // return BrokerFactory.createBroker(new - // URI("xbean:org/apache/activemq/broker/store/loadtester.xml")); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - protected ConnectionFactory createConnectionFactory() throws URISyntaxException, IOException { - return new ActiveMQConnectionFactory(((TransportConnector)broker.getTransportConnectors().get(0)) - .getServer().getConnectURI()); - } + protected BrokerService createBroker() throws Exception { + return BrokerFactory.createBroker(new URI("broker://(tcp://localhost:0)?useJmx=true")); + // return BrokerFactory.createBroker(new + // URI("xbean:org/apache/activemq/broker/store/loadtester.xml")); + } - public void initCombosForTestSendReceive() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); - addCombinationValues("durableConsumer", new Object[] {Boolean.TRUE}); - addCombinationValues("messageSize", new Object[] {Integer.valueOf(101), Integer.valueOf(102), - Integer.valueOf(103), Integer.valueOf(104), - Integer.valueOf(105), Integer.valueOf(106), - Integer.valueOf(107), Integer.valueOf(108)}); - } + protected ConnectionFactory createConnectionFactory() throws URISyntaxException, IOException { + return new ActiveMQConnectionFactory(((TransportConnector) broker.getTransportConnectors().get(0)).getServer().getConnectURI()); + } - public void testSendReceive() throws Exception { + public void initCombosForTestSendReceive() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); + addCombinationValues("durableConsumer", new Object[]{Boolean.TRUE}); + addCombinationValues("messageSize", new Object[]{Integer.valueOf(101), Integer.valueOf(102), Integer.valueOf(103), Integer.valueOf(104), Integer.valueOf(105), Integer.valueOf(106), Integer.valueOf(107), Integer.valueOf(108)}); + } - // Durable consumer combination is only valid with topics - if (durableConsumer && destinationType != ActiveMQDestination.TOPIC_TYPE) { - return; - } + public void testSendReceive() throws Exception { - connection.setClientID(getName()); - connection.getPrefetchPolicy().setAll(1000); - connection.start(); + // Durable consumer combination is only valid with topics + if (durableConsumer && destinationType != ActiveMQDestination.TOPIC_TYPE) { + return; + } - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - destination = createDestination(session, destinationType); - MessageConsumer consumer; - if (durableConsumer) { - consumer = session.createDurableSubscriber((Topic)destination, "sub1:" - + System.currentTimeMillis()); - } else { - consumer = session.createConsumer(destination); - } - profilerPause("Ready: "); + connection.setClientID(getName()); + connection.getPrefetchPolicy().setAll(1000); + connection.start(); - final CountDownLatch producerDoneLatch = new CountDownLatch(1); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + destination = createDestination(session, destinationType); + MessageConsumer consumer; + if (durableConsumer) { + consumer = session.createDurableSubscriber((Topic) destination, "sub1:" + System.currentTimeMillis()); + } + else { + consumer = session.createConsumer(destination); + } + profilerPause("Ready: "); - // Send the messages, async - new Thread() { - public void run() { - Connection connection2 = null; - try { - connection2 = factory.createConnection(); - Session session = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(deliveryMode); - for (int i = 0; i < messageCount; i++) { - BytesMessage m = session.createBytesMessage(); - m.writeBytes(new byte[messageSize]); - producer.send(m); - } - producer.close(); - } catch (JMSException e) { - e.printStackTrace(); - } finally { - safeClose(connection2); - producerDoneLatch.countDown(); - } + final CountDownLatch producerDoneLatch = new CountDownLatch(1); + // Send the messages, async + new Thread() { + public void run() { + Connection connection2 = null; + try { + connection2 = factory.createConnection(); + Session session = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(deliveryMode); + for (int i = 0; i < messageCount; i++) { + BytesMessage m = session.createBytesMessage(); + m.writeBytes(new byte[messageSize]); + producer.send(m); + } + producer.close(); + } + catch (JMSException e) { + e.printStackTrace(); + } + finally { + safeClose(connection2); + producerDoneLatch.countDown(); } - }.start(); - // Make sure all the messages were delivered. - Message message = null; - for (int i = 0; i < messageCount; i++) { - message = consumer.receive(5000); - assertNotNull("Did not get message: " + i, message); - } + } + }.start(); - profilerPause("Done: "); + // Make sure all the messages were delivered. + Message message = null; + for (int i = 0; i < messageCount; i++) { + message = consumer.receive(5000); + assertNotNull("Did not get message: " + i, message); + } - assertNull(consumer.receiveNoWait()); - message.acknowledge(); + profilerPause("Done: "); - // Make sure the producer thread finishes. - assertTrue(producerDoneLatch.await(5, TimeUnit.SECONDS)); - } + assertNull(consumer.receiveNoWait()); + message.acknowledge(); + + // Make sure the producer thread finishes. + assertTrue(producerDoneLatch.await(5, TimeUnit.SECONDS)); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/MessageEvictionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/MessageEvictionTest.java index efa86a9330..2a091b138e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/MessageEvictionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/MessageEvictionTest.java @@ -58,237 +58,241 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MessageEvictionTest { - static final Logger LOG = LoggerFactory.getLogger(MessageEvictionTest.class); - private BrokerService broker; - private ConnectionFactory connectionFactory; - Connection connection; - private Session session; - private Topic destination; - private final String destinationName = "verifyEvection"; - protected int numMessages = 2000; - protected String payload = new String(new byte[1024*2]); - public void setUp(PendingSubscriberMessageStoragePolicy pendingSubscriberPolicy) throws Exception { - broker = createBroker(pendingSubscriberPolicy); - broker.start(); - connectionFactory = createConnectionFactory(); - connection = connectionFactory.createConnection(); - connection.start(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - destination = session.createTopic(destinationName); - } + static final Logger LOG = LoggerFactory.getLogger(MessageEvictionTest.class); + private BrokerService broker; + private ConnectionFactory connectionFactory; + Connection connection; + private Session session; + private Topic destination; + private final String destinationName = "verifyEvection"; + protected int numMessages = 2000; + protected String payload = new String(new byte[1024 * 2]); - @After - public void tearDown() throws Exception { - if (connection != null) - { - connection.stop(); - } - if (broker != null) - { - broker.stop(); - } - } + public void setUp(PendingSubscriberMessageStoragePolicy pendingSubscriberPolicy) throws Exception { + broker = createBroker(pendingSubscriberPolicy); + broker.start(); + connectionFactory = createConnectionFactory(); + connection = connectionFactory.createConnection(); + connection.start(); + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + destination = session.createTopic(destinationName); + } - @Test - public void testMessageEvictionMemoryUsageFileCursor() throws Exception { - setUp(new FilePendingSubscriberMessageStoragePolicy()); - doTestMessageEvictionMemoryUsage(); - } + @After + public void tearDown() throws Exception { + if (connection != null) { + connection.stop(); + } + if (broker != null) { + broker.stop(); + } + } - @Test - public void testMessageEvictionMemoryUsageVmCursor() throws Exception { - setUp(new VMPendingSubscriberMessageStoragePolicy()); - doTestMessageEvictionMemoryUsage(); - } + @Test + public void testMessageEvictionMemoryUsageFileCursor() throws Exception { + setUp(new FilePendingSubscriberMessageStoragePolicy()); + doTestMessageEvictionMemoryUsage(); + } - @Test - public void testMessageEvictionDiscardedAdvisory() throws Exception { - setUp(new VMPendingSubscriberMessageStoragePolicy()); + @Test + public void testMessageEvictionMemoryUsageVmCursor() throws Exception { + setUp(new VMPendingSubscriberMessageStoragePolicy()); + doTestMessageEvictionMemoryUsage(); + } - ExecutorService executor = Executors.newSingleThreadExecutor(); - final CountDownLatch consumerRegistered = new CountDownLatch(1); - final CountDownLatch gotAdvisory = new CountDownLatch(1); - final CountDownLatch advisoryIsGood = new CountDownLatch(1); + @Test + public void testMessageEvictionDiscardedAdvisory() throws Exception { + setUp(new VMPendingSubscriberMessageStoragePolicy()); - executor.execute(new Runnable() { - @Override - public void run() { - try { - ActiveMQTopic discardedAdvisoryDestination = - AdvisorySupport.getMessageDiscardedAdvisoryTopic(destination); - // use separate session rather than asyncDispatch on consumer session - // as we want consumer session to block - Session advisorySession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageConsumer consumer = advisorySession.createConsumer(discardedAdvisoryDestination); - consumer.setMessageListener(new MessageListener() { - int advisoriesReceived = 0; - @Override - public void onMessage(Message message) { - try { - LOG.info("advisory:" + message); - ActiveMQMessage activeMQMessage = (ActiveMQMessage) message; - assertNotNull(activeMQMessage.getStringProperty(AdvisorySupport.MSG_PROPERTY_CONSUMER_ID)); - assertEquals(++advisoriesReceived, activeMQMessage.getIntProperty(AdvisorySupport.MSG_PROPERTY_DISCARDED_COUNT)); - message.acknowledge(); - advisoryIsGood.countDown(); - } catch (JMSException e) { - e.printStackTrace(); - fail(e.toString()); - } finally { - gotAdvisory.countDown(); - } - } - }); - consumerRegistered.countDown(); - gotAdvisory.await(120, TimeUnit.SECONDS); - consumer.close(); - advisorySession.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(e.toString()); - } + ExecutorService executor = Executors.newSingleThreadExecutor(); + final CountDownLatch consumerRegistered = new CountDownLatch(1); + final CountDownLatch gotAdvisory = new CountDownLatch(1); + final CountDownLatch advisoryIsGood = new CountDownLatch(1); + + executor.execute(new Runnable() { + @Override + public void run() { + try { + ActiveMQTopic discardedAdvisoryDestination = AdvisorySupport.getMessageDiscardedAdvisoryTopic(destination); + // use separate session rather than asyncDispatch on consumer session + // as we want consumer session to block + Session advisorySession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final MessageConsumer consumer = advisorySession.createConsumer(discardedAdvisoryDestination); + consumer.setMessageListener(new MessageListener() { + int advisoriesReceived = 0; + + @Override + public void onMessage(Message message) { + try { + LOG.info("advisory:" + message); + ActiveMQMessage activeMQMessage = (ActiveMQMessage) message; + assertNotNull(activeMQMessage.getStringProperty(AdvisorySupport.MSG_PROPERTY_CONSUMER_ID)); + assertEquals(++advisoriesReceived, activeMQMessage.getIntProperty(AdvisorySupport.MSG_PROPERTY_DISCARDED_COUNT)); + message.acknowledge(); + advisoryIsGood.countDown(); + } + catch (JMSException e) { + e.printStackTrace(); + fail(e.toString()); + } + finally { + gotAdvisory.countDown(); + } + } + }); + consumerRegistered.countDown(); + gotAdvisory.await(120, TimeUnit.SECONDS); + consumer.close(); + advisorySession.close(); } - }); - assertTrue("we have an advisory consumer", consumerRegistered.await(60, TimeUnit.SECONDS)); - doTestMessageEvictionMemoryUsage(); - assertTrue("got an advisory for discarded", gotAdvisory.await(0, TimeUnit.SECONDS)); - assertTrue("advisory is good",advisoryIsGood.await(0, TimeUnit.SECONDS)); - } - - public void doTestMessageEvictionMemoryUsage() throws Exception { - - ExecutorService executor = Executors.newCachedThreadPool(); - final CountDownLatch doAck = new CountDownLatch(1); - final CountDownLatch ackDone = new CountDownLatch(1); - final CountDownLatch consumerRegistered = new CountDownLatch(1); - executor.execute(new Runnable() { - @Override - public void run() { - try { - final MessageConsumer consumer = session.createConsumer(destination); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - try { - // very slow, only ack once - doAck.await(60, TimeUnit.SECONDS); - LOG.info("acking: " + message.getJMSMessageID()); - message.acknowledge(); - ackDone.countDown(); - } catch (Exception e) { - e.printStackTrace(); - fail(e.toString()); - } finally { - consumerRegistered.countDown(); - ackDone.countDown(); - } - } - }); - consumerRegistered.countDown(); - ackDone.await(60, TimeUnit.SECONDS); - consumer.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(e.toString()); - } + catch (Exception e) { + e.printStackTrace(); + fail(e.toString()); } - }); + } + }); + assertTrue("we have an advisory consumer", consumerRegistered.await(60, TimeUnit.SECONDS)); + doTestMessageEvictionMemoryUsage(); + assertTrue("got an advisory for discarded", gotAdvisory.await(0, TimeUnit.SECONDS)); + assertTrue("advisory is good", advisoryIsGood.await(0, TimeUnit.SECONDS)); + } - assertTrue("we have a consumer", consumerRegistered.await(10, TimeUnit.SECONDS)); + public void doTestMessageEvictionMemoryUsage() throws Exception { - final AtomicInteger sent = new AtomicInteger(0); - final CountDownLatch sendDone = new CountDownLatch(1); - executor.execute(new Runnable() { - @Override - public void run() { - MessageProducer producer; - try { - producer = session.createProducer(destination); - for (int i=0; i< numMessages; i++) { - producer.send(session.createTextMessage(payload)); - sent.incrementAndGet(); - TimeUnit.MILLISECONDS.sleep(10); - } - producer.close(); - sendDone.countDown(); - } catch (Exception e) { - sendDone.countDown(); - e.printStackTrace(); - fail(e.toString()); + ExecutorService executor = Executors.newCachedThreadPool(); + final CountDownLatch doAck = new CountDownLatch(1); + final CountDownLatch ackDone = new CountDownLatch(1); + final CountDownLatch consumerRegistered = new CountDownLatch(1); + executor.execute(new Runnable() { + @Override + public void run() { + try { + final MessageConsumer consumer = session.createConsumer(destination); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + try { + // very slow, only ack once + doAck.await(60, TimeUnit.SECONDS); + LOG.info("acking: " + message.getJMSMessageID()); + message.acknowledge(); + ackDone.countDown(); + } + catch (Exception e) { + e.printStackTrace(); + fail(e.toString()); + } + finally { + consumerRegistered.countDown(); + ackDone.countDown(); + } + } + }); + consumerRegistered.countDown(); + ackDone.await(60, TimeUnit.SECONDS); + consumer.close(); + } + catch (Exception e) { + e.printStackTrace(); + fail(e.toString()); + } + } + }); + + assertTrue("we have a consumer", consumerRegistered.await(10, TimeUnit.SECONDS)); + + final AtomicInteger sent = new AtomicInteger(0); + final CountDownLatch sendDone = new CountDownLatch(1); + executor.execute(new Runnable() { + @Override + public void run() { + MessageProducer producer; + try { + producer = session.createProducer(destination); + for (int i = 0; i < numMessages; i++) { + producer.send(session.createTextMessage(payload)); + sent.incrementAndGet(); + TimeUnit.MILLISECONDS.sleep(10); } + producer.close(); + sendDone.countDown(); } - }); - - assertTrue("messages sending done", sendDone.await(180, TimeUnit.SECONDS)); - assertEquals("all message were sent", numMessages, sent.get()); - - doAck.countDown(); - executor.shutdown(); - executor.awaitTermination(30, TimeUnit.SECONDS); - - assertTrue("usage goes to 0 once consumer goes away", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return 0 == TestSupport.getDestination(broker, - ActiveMQDestination.transform(destination)).getMemoryUsage().getPercentUsage(); + catch (Exception e) { + sendDone.countDown(); + e.printStackTrace(); + fail(e.toString()); } - })); - } + } + }); - BrokerService createBroker(PendingSubscriberMessageStoragePolicy pendingSubscriberPolicy) throws Exception { - BrokerService brokerService = new BrokerService(); - brokerService.addConnector("tcp://localhost:0"); - brokerService.setUseJmx(false); - brokerService.setDeleteAllMessagesOnStartup(true); + assertTrue("messages sending done", sendDone.await(180, TimeUnit.SECONDS)); + assertEquals("all message were sent", numMessages, sent.get()); - // spooling to disk early so topic memory limit is not reached - brokerService.getSystemUsage().getMemoryUsage().setLimit(500*1024); + doAck.countDown(); + executor.shutdown(); + executor.awaitTermination(30, TimeUnit.SECONDS); - final List policyEntries = new ArrayList(); - final PolicyEntry entry = new PolicyEntry(); - entry.setTopic(">"); + assertTrue("usage goes to 0 once consumer goes away", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return 0 == TestSupport.getDestination(broker, ActiveMQDestination.transform(destination)).getMemoryUsage().getPercentUsage(); + } + })); + } - entry.setAdvisoryForDiscardingMessages(true); + BrokerService createBroker(PendingSubscriberMessageStoragePolicy pendingSubscriberPolicy) throws Exception { + BrokerService brokerService = new BrokerService(); + brokerService.addConnector("tcp://localhost:0"); + brokerService.setUseJmx(false); + brokerService.setDeleteAllMessagesOnStartup(true); - // so consumer does not get over run while blocked limit the prefetch - entry.setTopicPrefetch(50); + // spooling to disk early so topic memory limit is not reached + brokerService.getSystemUsage().getMemoryUsage().setLimit(500 * 1024); + final List policyEntries = new ArrayList(); + final PolicyEntry entry = new PolicyEntry(); + entry.setTopic(">"); - entry.setPendingSubscriberPolicy(pendingSubscriberPolicy); + entry.setAdvisoryForDiscardingMessages(true); - // limit the number of outstanding messages, large enough to use the file store - // or small enough not to blow memory limit - int pendingMessageLimit = 50; - if (pendingSubscriberPolicy instanceof FilePendingSubscriberMessageStoragePolicy) { - pendingMessageLimit = 500; - } - ConstantPendingMessageLimitStrategy pendingMessageLimitStrategy = new ConstantPendingMessageLimitStrategy(); - pendingMessageLimitStrategy.setLimit(pendingMessageLimit); - entry.setPendingMessageLimitStrategy(pendingMessageLimitStrategy); + // so consumer does not get over run while blocked limit the prefetch + entry.setTopicPrefetch(50); - // to keep the limit in check and up to date rather than just the first few, evict some - OldestMessageEvictionStrategy messageEvictionStrategy = new OldestMessageEvictionStrategy(); - // whether to check expiry before eviction, default limit 1000 is fine as no ttl set in this test - //messageEvictionStrategy.setEvictExpiredMessagesHighWatermark(1000); - entry.setMessageEvictionStrategy(messageEvictionStrategy); + entry.setPendingSubscriberPolicy(pendingSubscriberPolicy); - // let evicted messaged disappear - entry.setDeadLetterStrategy(null); - policyEntries.add(entry); + // limit the number of outstanding messages, large enough to use the file store + // or small enough not to blow memory limit + int pendingMessageLimit = 50; + if (pendingSubscriberPolicy instanceof FilePendingSubscriberMessageStoragePolicy) { + pendingMessageLimit = 500; + } + ConstantPendingMessageLimitStrategy pendingMessageLimitStrategy = new ConstantPendingMessageLimitStrategy(); + pendingMessageLimitStrategy.setLimit(pendingMessageLimit); + entry.setPendingMessageLimitStrategy(pendingMessageLimitStrategy); - final PolicyMap policyMap = new PolicyMap(); - policyMap.setPolicyEntries(policyEntries); - brokerService.setDestinationPolicy(policyMap); + // to keep the limit in check and up to date rather than just the first few, evict some + OldestMessageEvictionStrategy messageEvictionStrategy = new OldestMessageEvictionStrategy(); + // whether to check expiry before eviction, default limit 1000 is fine as no ttl set in this test + //messageEvictionStrategy.setEvictExpiredMessagesHighWatermark(1000); + entry.setMessageEvictionStrategy(messageEvictionStrategy); - return brokerService; - } + // let evicted messaged disappear + entry.setDeadLetterStrategy(null); + policyEntries.add(entry); - ConnectionFactory createConnectionFactory() throws Exception { - String url = broker.getTransportConnectors().get(0).getServer().getConnectURI().toString(); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(url); - factory.setWatchTopicAdvisories(false); - return factory; - } + final PolicyMap policyMap = new PolicyMap(); + policyMap.setPolicyEntries(policyEntries); + brokerService.setDestinationPolicy(policyMap); + + return brokerService; + } + + ConnectionFactory createConnectionFactory() throws Exception { + String url = broker.getTransportConnectors().get(0).getServer().getConnectURI().toString(); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(url); + factory.setWatchTopicAdvisories(false); + return factory; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/MessageListenerRedeliveryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/MessageListenerRedeliveryTest.java index 0fb9728aa5..f2db097823 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/MessageListenerRedeliveryTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/MessageListenerRedeliveryTest.java @@ -43,315 +43,329 @@ import org.slf4j.LoggerFactory; public class MessageListenerRedeliveryTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(MessageListenerRedeliveryTest.class); + private static final Logger LOG = LoggerFactory.getLogger(MessageListenerRedeliveryTest.class); - private Connection connection; + private Connection connection; - @Override - protected void setUp() throws Exception { - connection = createConnection(); - } + @Override + protected void setUp() throws Exception { + connection = createConnection(); + } - /** - * @see junit.framework.TestCase#tearDown() - */ - @Override - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - connection = null; - } - } + /** + * @see junit.framework.TestCase#tearDown() + */ + @Override + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + connection = null; + } + } - protected RedeliveryPolicy getRedeliveryPolicy() { - RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy(); - redeliveryPolicy.setInitialRedeliveryDelay(0); - redeliveryPolicy.setRedeliveryDelay(1000); - redeliveryPolicy.setMaximumRedeliveries(3); - redeliveryPolicy.setBackOffMultiplier((short)2); - redeliveryPolicy.setUseExponentialBackOff(true); - return redeliveryPolicy; - } + protected RedeliveryPolicy getRedeliveryPolicy() { + RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy(); + redeliveryPolicy.setInitialRedeliveryDelay(0); + redeliveryPolicy.setRedeliveryDelay(1000); + redeliveryPolicy.setMaximumRedeliveries(3); + redeliveryPolicy.setBackOffMultiplier((short) 2); + redeliveryPolicy.setUseExponentialBackOff(true); + return redeliveryPolicy; + } - protected Connection createConnection() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false&marshal=true"); - factory.setRedeliveryPolicy(getRedeliveryPolicy()); - return factory.createConnection(); - } + protected Connection createConnection() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false&marshal=true"); + factory.setRedeliveryPolicy(getRedeliveryPolicy()); + return factory.createConnection(); + } - private class TestMessageListener implements MessageListener { + private class TestMessageListener implements MessageListener { - public int counter; - private final Session session; + public int counter; + private final Session session; - public TestMessageListener(Session session) { - this.session = session; - } + public TestMessageListener(Session session) { + this.session = session; + } - @Override - public void onMessage(Message message) { + @Override + public void onMessage(Message message) { + try { + LOG.info("Message Received: " + message); + counter++; + if (counter <= 4) { + LOG.info("Message Rollback."); + session.rollback(); + } + else { + LOG.info("Message Commit."); + message.acknowledge(); + session.commit(); + } + } + catch (JMSException e) { + LOG.error("Error when rolling back transaction"); + } + } + } + + public void testQueueRollbackConsumerListener() throws JMSException { + connection.start(); + + Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); + Queue queue = session.createQueue("queue-" + getName()); + MessageProducer producer = createProducer(session, queue); + Message message = createTextMessage(session); + producer.send(message); + session.commit(); + + MessageConsumer consumer = session.createConsumer(queue); + + ActiveMQMessageConsumer mc = (ActiveMQMessageConsumer) consumer; + mc.setRedeliveryPolicy(getRedeliveryPolicy()); + + TestMessageListener listener = new TestMessageListener(session); + consumer.setMessageListener(listener); + + try { + Thread.sleep(500); + } + catch (InterruptedException e) { + } + + // first try.. should get 2 since there is no delay on the + // first redeliver.. + assertEquals(2, listener.counter); + + try { + Thread.sleep(1000); + } + catch (InterruptedException e) { + } + // 2nd redeliver (redelivery after 1 sec) + assertEquals(3, listener.counter); + + try { + Thread.sleep(2000); + } + catch (InterruptedException e) { + } + // 3rd redeliver (redelivery after 2 seconds) - it should give up after + // that + assertEquals(4, listener.counter); + + // create new message + producer.send(createTextMessage(session)); + session.commit(); + + try { + Thread.sleep(500); + } + catch (InterruptedException e) { + } + // it should be committed, so no redelivery + assertEquals(5, listener.counter); + + try { + Thread.sleep(1500); + } + catch (InterruptedException e) { + } + // no redelivery, counter should still be 4 + assertEquals(5, listener.counter); + + session.close(); + } + + public void testQueueRollbackSessionListener() throws JMSException { + connection.start(); + + Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); + Queue queue = session.createQueue("queue-" + getName()); + MessageProducer producer = createProducer(session, queue); + Message message = createTextMessage(session); + producer.send(message); + session.commit(); + + MessageConsumer consumer = session.createConsumer(queue); + + ActiveMQMessageConsumer mc = (ActiveMQMessageConsumer) consumer; + mc.setRedeliveryPolicy(getRedeliveryPolicy()); + + TestMessageListener listener = new TestMessageListener(session); + consumer.setMessageListener(listener); + + try { + Thread.sleep(500); + } + catch (InterruptedException e) { + + } + // first try + assertEquals(2, listener.counter); + + try { + Thread.sleep(1000); + } + catch (InterruptedException e) { + + } + // second try (redelivery after 1 sec) + assertEquals(3, listener.counter); + + try { + Thread.sleep(2000); + } + catch (InterruptedException e) { + + } + // third try (redelivery after 2 seconds) - it should give up after that + assertEquals(4, listener.counter); + + // create new message + producer.send(createTextMessage(session)); + session.commit(); + + try { + Thread.sleep(500); + } + catch (InterruptedException e) { + // ignore + } + // it should be committed, so no redelivery + assertEquals(5, listener.counter); + + try { + Thread.sleep(1500); + } + catch (InterruptedException e) { + // ignore + } + // no redelivery, counter should still be 4 + assertEquals(5, listener.counter); + + session.close(); + } + + public void testQueueSessionListenerExceptionRetry() throws Exception { + connection.start(); + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = session.createQueue("queue-" + getName()); + MessageProducer producer = createProducer(session, queue); + Message message = createTextMessage(session, "1"); + producer.send(message); + message = createTextMessage(session, "2"); + producer.send(message); + + MessageConsumer consumer = session.createConsumer(queue); + + final CountDownLatch gotMessage = new CountDownLatch(2); + final AtomicInteger count = new AtomicInteger(0); + final int maxDeliveries = getRedeliveryPolicy().getMaximumRedeliveries(); + final ArrayList received = new ArrayList(); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + LOG.info("Message Received: " + message); try { - LOG.info("Message Received: " + message); - counter++; - if (counter <= 4) { - LOG.info("Message Rollback."); - session.rollback(); - } else { - LOG.info("Message Commit."); - message.acknowledge(); - session.commit(); - } - } catch (JMSException e) { - LOG.error("Error when rolling back transaction"); + received.add(((TextMessage) message).getText()); } - } - } - - public void testQueueRollbackConsumerListener() throws JMSException { - connection.start(); - - Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); - Queue queue = session.createQueue("queue-" + getName()); - MessageProducer producer = createProducer(session, queue); - Message message = createTextMessage(session); - producer.send(message); - session.commit(); - - MessageConsumer consumer = session.createConsumer(queue); - - ActiveMQMessageConsumer mc = (ActiveMQMessageConsumer)consumer; - mc.setRedeliveryPolicy(getRedeliveryPolicy()); - - TestMessageListener listener = new TestMessageListener(session); - consumer.setMessageListener(listener); - - try { - Thread.sleep(500); - } catch (InterruptedException e) { - } - - // first try.. should get 2 since there is no delay on the - // first redeliver.. - assertEquals(2, listener.counter); - - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - } - // 2nd redeliver (redelivery after 1 sec) - assertEquals(3, listener.counter); - - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - } - // 3rd redeliver (redelivery after 2 seconds) - it should give up after - // that - assertEquals(4, listener.counter); - - // create new message - producer.send(createTextMessage(session)); - session.commit(); - - try { - Thread.sleep(500); - } catch (InterruptedException e) { - } - // it should be committed, so no redelivery - assertEquals(5, listener.counter); - - try { - Thread.sleep(1500); - } catch (InterruptedException e) { - } - // no redelivery, counter should still be 4 - assertEquals(5, listener.counter); - - session.close(); - } - - public void testQueueRollbackSessionListener() throws JMSException { - connection.start(); - - Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); - Queue queue = session.createQueue("queue-" + getName()); - MessageProducer producer = createProducer(session, queue); - Message message = createTextMessage(session); - producer.send(message); - session.commit(); - - MessageConsumer consumer = session.createConsumer(queue); - - ActiveMQMessageConsumer mc = (ActiveMQMessageConsumer)consumer; - mc.setRedeliveryPolicy(getRedeliveryPolicy()); - - TestMessageListener listener = new TestMessageListener(session); - consumer.setMessageListener(listener); - - try { - Thread.sleep(500); - } catch (InterruptedException e) { - - } - // first try - assertEquals(2, listener.counter); - - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - - } - // second try (redelivery after 1 sec) - assertEquals(3, listener.counter); - - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - - } - // third try (redelivery after 2 seconds) - it should give up after that - assertEquals(4, listener.counter); - - // create new message - producer.send(createTextMessage(session)); - session.commit(); - - try { - Thread.sleep(500); - } catch (InterruptedException e) { - // ignore - } - // it should be committed, so no redelivery - assertEquals(5, listener.counter); - - try { - Thread.sleep(1500); - } catch (InterruptedException e) { - // ignore - } - // no redelivery, counter should still be 4 - assertEquals(5, listener.counter); - - session.close(); - } - - public void testQueueSessionListenerExceptionRetry() throws Exception { - connection.start(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createQueue("queue-" + getName()); - MessageProducer producer = createProducer(session, queue); - Message message = createTextMessage(session, "1"); - producer.send(message); - message = createTextMessage(session, "2"); - producer.send(message); - - MessageConsumer consumer = session.createConsumer(queue); - - final CountDownLatch gotMessage = new CountDownLatch(2); - final AtomicInteger count = new AtomicInteger(0); - final int maxDeliveries = getRedeliveryPolicy().getMaximumRedeliveries(); - final ArrayList received = new ArrayList(); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - LOG.info("Message Received: " + message); - try { - received.add(((TextMessage) message).getText()); - } catch (JMSException e) { - e.printStackTrace(); - fail(e.toString()); - } - if (count.incrementAndGet() < maxDeliveries) { - throw new RuntimeException(getName() + " force a redelivery"); - } - // new blood - count.set(0); - gotMessage.countDown(); + catch (JMSException e) { + e.printStackTrace(); + fail(e.toString()); } - }); - - assertTrue("got message before retry expiry", gotMessage.await(20, TimeUnit.SECONDS)); - - for (int i=0; i 0); - assertEquals("received what was committed", sent.get(), received); - } + assertTrue("filler started..", fillerStarted.await(20, TimeUnit.SECONDS)); + waitForBlocked(done); - protected void waitForBlocked(final AtomicBoolean done) - throws InterruptedException { - while (true) { - Thread.sleep(1000); - // the producer is blocked once the done flag stays true - if (done.get()) { - LOG.info("Blocked...."); - break; + // consume and rollback some so message gets to DLQ + connection = (ActiveMQConnection) factory.createConnection(); + connections.add(connection); + connection.start(); + TextMessage msg; + int received = 0; + for (; received < sent.get(); ++received) { + msg = (TextMessage) consumer.receive(4000); + if (msg == null) { + LOG.info("received null on count: " + received); + break; + } + LOG.info("received: " + received + ", msg: " + msg.getJMSMessageID()); + if (received % 5 == 0) { + if (received % 3 == 0) { + // force the use of the DLQ which will use some more store + LOG.info("rollback on : " + received); + consumerSession.rollback(); } - done.set(true); - } - } + else { + LOG.info("commit on : " + received); + consumerSession.commit(); + } + } + } + LOG.info("Done:: sent: " + sent.get() + ", received: " + received); + keepGoing.set(false); + assertTrue("some were sent:", sent.get() > 0); + assertEquals("received what was committed", sent.get(), received); + } - protected BrokerService createBroker() throws Exception { - BrokerService service = new BrokerService(); - service.setDeleteAllMessagesOnStartup(true); - - service.setUseJmx(false); + protected void waitForBlocked(final AtomicBoolean done) throws InterruptedException { + while (true) { + Thread.sleep(1000); + // the producer is blocked once the done flag stays true + if (done.get()) { + LOG.info("Blocked...."); + break; + } + done.set(true); + } + } - service.getSystemUsage().getStoreUsage().setLimit(200*1024); - - // allow destination to use 50% of store, leaving 50% for DLQ. - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policy = new PolicyEntry(); - policy.setStoreUsageHighWaterMark(50); - policyMap.put(queueDest, policy); - policyMap.put(topicDest, policy); - service.setDestinationPolicy(policyMap); + protected BrokerService createBroker() throws Exception { + BrokerService service = new BrokerService(); + service.setDeleteAllMessagesOnStartup(true); - connector = service.addConnector("tcp://localhost:0"); - return service; - } + service.setUseJmx(false); - public void setUp() throws Exception { - setAutoFail(true); - super.setUp(); - } - - protected void tearDown() throws Exception { - if (connection != null) { - TcpTransport t = (TcpTransport)connection.getTransport().narrow(TcpTransport.class); - t.getTransportListener().onException(new IOException("Disposed.")); - connection.getTransport().stop(); - super.tearDown(); - } - } + service.getSystemUsage().getStoreUsage().setLimit(200 * 1024); - protected ConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(connector.getConnectUri()); - } + // allow destination to use 50% of store, leaving 50% for DLQ. + PolicyMap policyMap = new PolicyMap(); + PolicyEntry policy = new PolicyEntry(); + policy.setStoreUsageHighWaterMark(50); + policyMap.put(queueDest, policy); + policyMap.put(topicDest, policy); + service.setDestinationPolicy(policyMap); + + connector = service.addConnector("tcp://localhost:0"); + return service; + } + + public void setUp() throws Exception { + setAutoFail(true); + super.setUp(); + } + + protected void tearDown() throws Exception { + if (connection != null) { + TcpTransport t = (TcpTransport) connection.getTransport().narrow(TcpTransport.class); + t.getTransportListener().onException(new IOException("Disposed.")); + connection.getTransport().stop(); + super.tearDown(); + } + } + + protected ConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory(connector.getConnectUri()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ProducerFlowControlSendFailTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ProducerFlowControlSendFailTest.java index 12aa47d23f..535f991753 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ProducerFlowControlSendFailTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ProducerFlowControlSendFailTest.java @@ -36,141 +36,143 @@ import org.apache.activemq.broker.region.policy.VMPendingSubscriberMessageStorag public class ProducerFlowControlSendFailTest extends ProducerFlowControlTest { - protected BrokerService createBroker() throws Exception { - BrokerService service = new BrokerService(); - service.setPersistent(false); - service.setUseJmx(false); + protected BrokerService createBroker() throws Exception { + BrokerService service = new BrokerService(); + service.setPersistent(false); + service.setUseJmx(false); - // Setup a destination policy where it takes only 1 message at a time. - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policy = new PolicyEntry(); - policy.setMemoryLimit(1); - policy.setPendingSubscriberPolicy(new VMPendingSubscriberMessageStoragePolicy()); - policy.setPendingQueuePolicy(new VMPendingQueueMessageStoragePolicy()); - policy.setProducerFlowControl(true); - policyMap.setDefaultEntry(policy); - service.setDestinationPolicy(policyMap); - - service.getSystemUsage().setSendFailIfNoSpace(true); + // Setup a destination policy where it takes only 1 message at a time. + PolicyMap policyMap = new PolicyMap(); + PolicyEntry policy = new PolicyEntry(); + policy.setMemoryLimit(1); + policy.setPendingSubscriberPolicy(new VMPendingSubscriberMessageStoragePolicy()); + policy.setPendingQueuePolicy(new VMPendingQueueMessageStoragePolicy()); + policy.setProducerFlowControl(true); + policyMap.setDefaultEntry(policy); + service.setDestinationPolicy(policyMap); - connector = service.addConnector("tcp://localhost:0"); - return service; - } - - @Override - public void test2ndPublisherWithStandardConnectionThatIsBlocked() throws Exception { - // with sendFailIfNoSpace set, there is no blocking of the connection - } - - @Override - public void testAsyncPublisherRecoverAfterBlock() throws Exception { - // sendFail means no flowControllwindow as there is no producer ack, just an exception - } - - @Override - public void testPublisherRecoverAfterBlock() throws Exception { - ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory)createConnectionFactory(); - // with sendFail, there must be no flowControllwindow - // sendFail is an alternative flow control mechanism that does not block - factory.setUseAsyncSend(true); - connection = (ActiveMQConnection)factory.createConnection(); - connections.add(connection); - connection.start(); + service.getSystemUsage().setSendFailIfNoSpace(true); - final Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - final MessageProducer producer = session.createProducer(queueA); - - final AtomicBoolean keepGoing = new AtomicBoolean(true); - - Thread thread = new Thread("Filler") { - @Override - public void run() { - while (keepGoing.get()) { - try { - producer.send(session.createTextMessage("Test message")); - if (gotResourceException.get()) { - // do not flood the broker with requests when full as we are sending async and they - // will be limited by the network buffers - Thread.sleep(200); - } - } catch (Exception e) { - // with async send, there will be no exceptions - e.printStackTrace(); - } - } + connector = service.addConnector("tcp://localhost:0"); + return service; + } + + @Override + public void test2ndPublisherWithStandardConnectionThatIsBlocked() throws Exception { + // with sendFailIfNoSpace set, there is no blocking of the connection + } + + @Override + public void testAsyncPublisherRecoverAfterBlock() throws Exception { + // sendFail means no flowControllwindow as there is no producer ack, just an exception + } + + @Override + public void testPublisherRecoverAfterBlock() throws Exception { + ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) createConnectionFactory(); + // with sendFail, there must be no flowControllwindow + // sendFail is an alternative flow control mechanism that does not block + factory.setUseAsyncSend(true); + connection = (ActiveMQConnection) factory.createConnection(); + connections.add(connection); + connection.start(); + + final Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + final MessageProducer producer = session.createProducer(queueA); + + final AtomicBoolean keepGoing = new AtomicBoolean(true); + + Thread thread = new Thread("Filler") { + @Override + public void run() { + while (keepGoing.get()) { + try { + producer.send(session.createTextMessage("Test message")); + if (gotResourceException.get()) { + // do not flood the broker with requests when full as we are sending async and they + // will be limited by the network buffers + Thread.sleep(200); + } + } + catch (Exception e) { + // with async send, there will be no exceptions + e.printStackTrace(); + } } - }; - thread.start(); - waitForBlockedOrResourceLimit(new AtomicBoolean(false)); + } + }; + thread.start(); + waitForBlockedOrResourceLimit(new AtomicBoolean(false)); - // resourceException on second message, resumption if we - // can receive 10 - MessageConsumer consumer = session.createConsumer(queueA); - TextMessage msg; - for (int idx = 0; idx < 10; ++idx) { - msg = (TextMessage) consumer.receive(1000); - if (msg != null) { - msg.acknowledge(); + // resourceException on second message, resumption if we + // can receive 10 + MessageConsumer consumer = session.createConsumer(queueA); + TextMessage msg; + for (int idx = 0; idx < 10; ++idx) { + msg = (TextMessage) consumer.receive(1000); + if (msg != null) { + msg.acknowledge(); + } + } + keepGoing.set(false); + } + + public void testPublisherRecoverAfterBlockWithSyncSend() throws Exception { + ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) createConnectionFactory(); + factory.setExceptionListener(null); + factory.setUseAsyncSend(false); + connection = (ActiveMQConnection) factory.createConnection(); + connections.add(connection); + connection.start(); + + final Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + final MessageProducer producer = session.createProducer(queueA); + + final AtomicBoolean keepGoing = new AtomicBoolean(true); + final AtomicInteger exceptionCount = new AtomicInteger(0); + Thread thread = new Thread("Filler") { + @Override + public void run() { + while (keepGoing.get()) { + try { + producer.send(session.createTextMessage("Test message")); + } + catch (JMSException arg0) { + if (arg0 instanceof ResourceAllocationException) { + gotResourceException.set(true); + exceptionCount.incrementAndGet(); + } + } } - } - keepGoing.set(false); - } + } + }; + thread.start(); + waitForBlockedOrResourceLimit(new AtomicBoolean(false)); - public void testPublisherRecoverAfterBlockWithSyncSend() throws Exception { - ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory)createConnectionFactory(); - factory.setExceptionListener(null); - factory.setUseAsyncSend(false); - connection = (ActiveMQConnection)factory.createConnection(); - connections.add(connection); - connection.start(); + // resourceException on second message, resumption if we + // can receive 10 + MessageConsumer consumer = session.createConsumer(queueA); + TextMessage msg; + for (int idx = 0; idx < 10; ++idx) { + msg = (TextMessage) consumer.receive(1000); + if (msg != null) { + msg.acknowledge(); + } + } + assertTrue("we were blocked at least 5 times", 5 < exceptionCount.get()); + keepGoing.set(false); + } - final Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - final MessageProducer producer = session.createProducer(queueA); - - final AtomicBoolean keepGoing = new AtomicBoolean(true); - final AtomicInteger exceptionCount = new AtomicInteger(0); - Thread thread = new Thread("Filler") { - @Override - public void run() { - while (keepGoing.get()) { - try { - producer.send(session.createTextMessage("Test message")); - } catch (JMSException arg0) { - if (arg0 instanceof ResourceAllocationException) { - gotResourceException.set(true); - exceptionCount.incrementAndGet(); - } - } - } + @Override + protected ConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connector.getConnectUri()); + connectionFactory.setExceptionListener(new ExceptionListener() { + public void onException(JMSException arg0) { + if (arg0 instanceof ResourceAllocationException) { + gotResourceException.set(true); } - }; - thread.start(); - waitForBlockedOrResourceLimit(new AtomicBoolean(false)); - - // resourceException on second message, resumption if we - // can receive 10 - MessageConsumer consumer = session.createConsumer(queueA); - TextMessage msg; - for (int idx = 0; idx < 10; ++idx) { - msg = (TextMessage) consumer.receive(1000); - if (msg != null) { - msg.acknowledge(); - } - } - assertTrue("we were blocked at least 5 times", 5 < exceptionCount.get()); - keepGoing.set(false); - } - - @Override - protected ConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connector.getConnectUri()); - connectionFactory.setExceptionListener(new ExceptionListener() { - public void onException(JMSException arg0) { - if (arg0 instanceof ResourceAllocationException) { - gotResourceException.set(true); - } - } - }); - return connectionFactory; - } + } + }); + return connectionFactory; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ProducerFlowControlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ProducerFlowControlTest.java index a79e738329..0ab2c03371 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ProducerFlowControlTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ProducerFlowControlTest.java @@ -41,308 +41,314 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ProducerFlowControlTest extends JmsTestSupport { - static final Logger LOG = LoggerFactory.getLogger(ProducerFlowControlTest.class); - ActiveMQQueue queueA = new ActiveMQQueue("QUEUE.A"); - ActiveMQQueue queueB = new ActiveMQQueue("QUEUE.B"); - protected TransportConnector connector; - protected ActiveMQConnection connection; - // used to test sendFailIfNoSpace on SystemUsage - protected final AtomicBoolean gotResourceException = new AtomicBoolean(false); - public void test2ndPublisherWithProducerWindowSendConnectionThatIsBlocked() throws Exception { - ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory)createConnectionFactory(); - factory.setProducerWindowSize(1024 * 64); - connection = (ActiveMQConnection)factory.createConnection(); - connections.add(connection); - connection.start(); + static final Logger LOG = LoggerFactory.getLogger(ProducerFlowControlTest.class); + ActiveMQQueue queueA = new ActiveMQQueue("QUEUE.A"); + ActiveMQQueue queueB = new ActiveMQQueue("QUEUE.B"); + protected TransportConnector connector; + protected ActiveMQConnection connection; + // used to test sendFailIfNoSpace on SystemUsage + protected final AtomicBoolean gotResourceException = new AtomicBoolean(false); - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(queueB); + public void test2ndPublisherWithProducerWindowSendConnectionThatIsBlocked() throws Exception { + ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) createConnectionFactory(); + factory.setProducerWindowSize(1024 * 64); + connection = (ActiveMQConnection) factory.createConnection(); + connections.add(connection); + connection.start(); - // Test sending to Queue A - // 1 few sends should not block until the producer window is used up. - fillQueue(queueA); + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(queueB); - // Test sending to Queue B it should not block since the connection - // should not be blocked. - CountDownLatch pubishDoneToQeueuB = asyncSendTo(queueB, "Message 1"); - assertTrue(pubishDoneToQeueuB.await(2, TimeUnit.SECONDS)); + // Test sending to Queue A + // 1 few sends should not block until the producer window is used up. + fillQueue(queueA); - TextMessage msg = (TextMessage)consumer.receive(); - assertEquals("Message 1", msg.getText()); - msg.acknowledge(); + // Test sending to Queue B it should not block since the connection + // should not be blocked. + CountDownLatch pubishDoneToQeueuB = asyncSendTo(queueB, "Message 1"); + assertTrue(pubishDoneToQeueuB.await(2, TimeUnit.SECONDS)); - pubishDoneToQeueuB = asyncSendTo(queueB, "Message 2"); - assertTrue(pubishDoneToQeueuB.await(2, TimeUnit.SECONDS)); + TextMessage msg = (TextMessage) consumer.receive(); + assertEquals("Message 1", msg.getText()); + msg.acknowledge(); - msg = (TextMessage)consumer.receive(); - assertEquals("Message 2", msg.getText()); - msg.acknowledge(); - } + pubishDoneToQeueuB = asyncSendTo(queueB, "Message 2"); + assertTrue(pubishDoneToQeueuB.await(2, TimeUnit.SECONDS)); - public void testPublisherRecoverAfterBlock() throws Exception { - ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory)createConnectionFactory(); - connection = (ActiveMQConnection)factory.createConnection(); - connections.add(connection); - connection.start(); + msg = (TextMessage) consumer.receive(); + assertEquals("Message 2", msg.getText()); + msg.acknowledge(); + } - final Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - final MessageProducer producer = session.createProducer(queueA); - - final AtomicBoolean done = new AtomicBoolean(true); - final AtomicBoolean keepGoing = new AtomicBoolean(true); - - - Thread thread = new Thread("Filler") { - int i; - @Override - public void run() { - while (keepGoing.get()) { - done.set(false); - try { - producer.send(session.createTextMessage("Test message " + ++i)); - LOG.info("sent: " + i); - } catch (JMSException e) { - } - } - } - }; - thread.start(); - waitForBlockedOrResourceLimit(done); + public void testPublisherRecoverAfterBlock() throws Exception { + ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) createConnectionFactory(); + connection = (ActiveMQConnection) factory.createConnection(); + connections.add(connection); + connection.start(); - // after receiveing messges, producer should continue sending messages - // (done == false) - MessageConsumer consumer = session.createConsumer(queueA); - TextMessage msg; - for (int idx = 0; idx < 5; ++idx) { - msg = (TextMessage) consumer.receive(1000); - LOG.info("received: " + idx + ", msg: " + msg.getJMSMessageID()); - msg.acknowledge(); - } - Thread.sleep(1000); - keepGoing.set(false); - - assertFalse("producer has resumed", done.get()); - } + final Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + final MessageProducer producer = session.createProducer(queueA); - public void testAsyncPublisherRecoverAfterBlock() throws Exception { - ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory)createConnectionFactory(); - factory.setProducerWindowSize(1024 * 5); - factory.setUseAsyncSend(true); - connection = (ActiveMQConnection)factory.createConnection(); - connections.add(connection); - connection.start(); + final AtomicBoolean done = new AtomicBoolean(true); + final AtomicBoolean keepGoing = new AtomicBoolean(true); - final Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - final MessageProducer producer = session.createProducer(queueA); - - final AtomicBoolean done = new AtomicBoolean(true); - final AtomicBoolean keepGoing = new AtomicBoolean(true); - - - Thread thread = new Thread("Filler") { - int i; - @Override - public void run() { - while (keepGoing.get()) { - done.set(false); - try { - producer.send(session.createTextMessage("Test message " + ++i)); - LOG.info("sent: " + i); - } catch (JMSException e) { - } - } + Thread thread = new Thread("Filler") { + int i; + + @Override + public void run() { + while (keepGoing.get()) { + done.set(false); + try { + producer.send(session.createTextMessage("Test message " + ++i)); + LOG.info("sent: " + i); + } + catch (JMSException e) { + } } - }; - thread.start(); - waitForBlockedOrResourceLimit(done); + } + }; + thread.start(); + waitForBlockedOrResourceLimit(done); - // after receiveing messges, producer should continue sending messages - // (done == false) - MessageConsumer consumer = session.createConsumer(queueA); - TextMessage msg; - for (int idx = 0; idx < 5; ++idx) { - msg = (TextMessage) consumer.receive(1000); - assertNotNull("Got a message", msg); - LOG.info("received: " + idx + ", msg: " + msg.getJMSMessageID()); - msg.acknowledge(); - } - Thread.sleep(1000); - keepGoing.set(false); - - assertFalse("producer has resumed", done.get()); - } + // after receiveing messges, producer should continue sending messages + // (done == false) + MessageConsumer consumer = session.createConsumer(queueA); + TextMessage msg; + for (int idx = 0; idx < 5; ++idx) { + msg = (TextMessage) consumer.receive(1000); + LOG.info("received: " + idx + ", msg: " + msg.getJMSMessageID()); + msg.acknowledge(); + } + Thread.sleep(1000); + keepGoing.set(false); - public void test2ndPublisherWithSyncSendConnectionThatIsBlocked() throws Exception { - ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory)createConnectionFactory(); - factory.setAlwaysSyncSend(true); - connection = (ActiveMQConnection)factory.createConnection(); - connections.add(connection); - connection.start(); + assertFalse("producer has resumed", done.get()); + } - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(queueB); + public void testAsyncPublisherRecoverAfterBlock() throws Exception { + ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) createConnectionFactory(); + factory.setProducerWindowSize(1024 * 5); + factory.setUseAsyncSend(true); + connection = (ActiveMQConnection) factory.createConnection(); + connections.add(connection); + connection.start(); - // Test sending to Queue A - // 1st send should not block. But the rest will. - fillQueue(queueA); + final Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + final MessageProducer producer = session.createProducer(queueA); - // Test sending to Queue B it should not block. - CountDownLatch pubishDoneToQeueuB = asyncSendTo(queueB, "Message 1"); - assertTrue(pubishDoneToQeueuB.await(2, TimeUnit.SECONDS)); + final AtomicBoolean done = new AtomicBoolean(true); + final AtomicBoolean keepGoing = new AtomicBoolean(true); - TextMessage msg = (TextMessage)consumer.receive(); - assertEquals("Message 1", msg.getText()); - msg.acknowledge(); + Thread thread = new Thread("Filler") { + int i; - pubishDoneToQeueuB = asyncSendTo(queueB, "Message 2"); - assertTrue(pubishDoneToQeueuB.await(2, TimeUnit.SECONDS)); - - msg = (TextMessage)consumer.receive(); - assertEquals("Message 2", msg.getText()); - msg.acknowledge(); - } - - public void testSimpleSendReceive() throws Exception { - ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory)createConnectionFactory(); - factory.setAlwaysSyncSend(true); - connection = (ActiveMQConnection)factory.createConnection(); - connections.add(connection); - connection.start(); - - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(queueA); - - // Test sending to Queue B it should not block. - CountDownLatch pubishDoneToQeueuA = asyncSendTo(queueA, "Message 1"); - assertTrue(pubishDoneToQeueuA.await(2, TimeUnit.SECONDS)); - - TextMessage msg = (TextMessage)consumer.receive(); - assertEquals("Message 1", msg.getText()); - msg.acknowledge(); - - pubishDoneToQeueuA = asyncSendTo(queueA, "Message 2"); - assertTrue(pubishDoneToQeueuA.await(2, TimeUnit.SECONDS)); - - msg = (TextMessage)consumer.receive(); - assertEquals("Message 2", msg.getText()); - msg.acknowledge(); - } - - public void test2ndPublisherWithStandardConnectionThatIsBlocked() throws Exception { - ConnectionFactory factory = createConnectionFactory(); - connection = (ActiveMQConnection)factory.createConnection(); - connections.add(connection); - connection.start(); - - // Test sending to Queue A - // 1st send should not block. - fillQueue(queueA); - - // Test sending to Queue B it should block. - // Since even though the it's queue limits have not been reached, the - // connection - // is blocked. - CountDownLatch pubishDoneToQeueuB = asyncSendTo(queueB, "Message 1"); - assertFalse(pubishDoneToQeueuB.await(2, TimeUnit.SECONDS)); - } - - private void fillQueue(final ActiveMQQueue queue) throws JMSException, InterruptedException { - final AtomicBoolean done = new AtomicBoolean(true); - final AtomicBoolean keepGoing = new AtomicBoolean(true); - - // Starts an async thread that every time it publishes it sets the done - // flag to false. - // Once the send starts to block it will not reset the done flag - // anymore. - new Thread("Fill thread.") { - public void run() { - Session session = null; - try { - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(queue); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - while (keepGoing.get()) { - done.set(false); - producer.send(session.createTextMessage("Hello World")); - } - } catch (JMSException e) { - } finally { - safeClose(session); - } + @Override + public void run() { + while (keepGoing.get()) { + done.set(false); + try { + producer.send(session.createTextMessage("Test message " + ++i)); + LOG.info("sent: " + i); + } + catch (JMSException e) { + } } - }.start(); + } + }; + thread.start(); + waitForBlockedOrResourceLimit(done); - waitForBlockedOrResourceLimit(done); - keepGoing.set(false); - } + // after receiveing messges, producer should continue sending messages + // (done == false) + MessageConsumer consumer = session.createConsumer(queueA); + TextMessage msg; + for (int idx = 0; idx < 5; ++idx) { + msg = (TextMessage) consumer.receive(1000); + assertNotNull("Got a message", msg); + LOG.info("received: " + idx + ", msg: " + msg.getJMSMessageID()); + msg.acknowledge(); + } + Thread.sleep(1000); + keepGoing.set(false); - protected void waitForBlockedOrResourceLimit(final AtomicBoolean done) - throws InterruptedException { - while (true) { - Thread.sleep(1000); - // the producer is blocked once the done flag stays true or there is a resource exception - if (done.get() || gotResourceException.get()) { - break; + assertFalse("producer has resumed", done.get()); + } + + public void test2ndPublisherWithSyncSendConnectionThatIsBlocked() throws Exception { + ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) createConnectionFactory(); + factory.setAlwaysSyncSend(true); + connection = (ActiveMQConnection) factory.createConnection(); + connections.add(connection); + connection.start(); + + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(queueB); + + // Test sending to Queue A + // 1st send should not block. But the rest will. + fillQueue(queueA); + + // Test sending to Queue B it should not block. + CountDownLatch pubishDoneToQeueuB = asyncSendTo(queueB, "Message 1"); + assertTrue(pubishDoneToQeueuB.await(2, TimeUnit.SECONDS)); + + TextMessage msg = (TextMessage) consumer.receive(); + assertEquals("Message 1", msg.getText()); + msg.acknowledge(); + + pubishDoneToQeueuB = asyncSendTo(queueB, "Message 2"); + assertTrue(pubishDoneToQeueuB.await(2, TimeUnit.SECONDS)); + + msg = (TextMessage) consumer.receive(); + assertEquals("Message 2", msg.getText()); + msg.acknowledge(); + } + + public void testSimpleSendReceive() throws Exception { + ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) createConnectionFactory(); + factory.setAlwaysSyncSend(true); + connection = (ActiveMQConnection) factory.createConnection(); + connections.add(connection); + connection.start(); + + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(queueA); + + // Test sending to Queue B it should not block. + CountDownLatch pubishDoneToQeueuA = asyncSendTo(queueA, "Message 1"); + assertTrue(pubishDoneToQeueuA.await(2, TimeUnit.SECONDS)); + + TextMessage msg = (TextMessage) consumer.receive(); + assertEquals("Message 1", msg.getText()); + msg.acknowledge(); + + pubishDoneToQeueuA = asyncSendTo(queueA, "Message 2"); + assertTrue(pubishDoneToQeueuA.await(2, TimeUnit.SECONDS)); + + msg = (TextMessage) consumer.receive(); + assertEquals("Message 2", msg.getText()); + msg.acknowledge(); + } + + public void test2ndPublisherWithStandardConnectionThatIsBlocked() throws Exception { + ConnectionFactory factory = createConnectionFactory(); + connection = (ActiveMQConnection) factory.createConnection(); + connections.add(connection); + connection.start(); + + // Test sending to Queue A + // 1st send should not block. + fillQueue(queueA); + + // Test sending to Queue B it should block. + // Since even though the it's queue limits have not been reached, the + // connection + // is blocked. + CountDownLatch pubishDoneToQeueuB = asyncSendTo(queueB, "Message 1"); + assertFalse(pubishDoneToQeueuB.await(2, TimeUnit.SECONDS)); + } + + private void fillQueue(final ActiveMQQueue queue) throws JMSException, InterruptedException { + final AtomicBoolean done = new AtomicBoolean(true); + final AtomicBoolean keepGoing = new AtomicBoolean(true); + + // Starts an async thread that every time it publishes it sets the done + // flag to false. + // Once the send starts to block it will not reset the done flag + // anymore. + new Thread("Fill thread.") { + public void run() { + Session session = null; + try { + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(queue); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + while (keepGoing.get()) { + done.set(false); + producer.send(session.createTextMessage("Hello World")); + } } - done.set(true); - } - } - - private CountDownLatch asyncSendTo(final ActiveMQQueue queue, final String message) throws JMSException { - final CountDownLatch done = new CountDownLatch(1); - new Thread("Send thread.") { - public void run() { - Session session = null; - try { - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(queue); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - producer.send(session.createTextMessage(message)); - done.countDown(); - } catch (JMSException e) { - } finally { - safeClose(session); - } + catch (JMSException e) { } - }.start(); - return done; - } + finally { + safeClose(session); + } + } + }.start(); - protected BrokerService createBroker() throws Exception { - BrokerService service = new BrokerService(); - service.setPersistent(false); - service.setUseJmx(false); + waitForBlockedOrResourceLimit(done); + keepGoing.set(false); + } - // Setup a destination policy where it takes only 1 message at a time. - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policy = new PolicyEntry(); - policy.setMemoryLimit(1); - policy.setPendingSubscriberPolicy(new VMPendingSubscriberMessageStoragePolicy()); - policy.setPendingQueuePolicy(new VMPendingQueueMessageStoragePolicy()); - policy.setProducerFlowControl(true); - policyMap.setDefaultEntry(policy); - service.setDestinationPolicy(policyMap); + protected void waitForBlockedOrResourceLimit(final AtomicBoolean done) throws InterruptedException { + while (true) { + Thread.sleep(1000); + // the producer is blocked once the done flag stays true or there is a resource exception + if (done.get() || gotResourceException.get()) { + break; + } + done.set(true); + } + } - connector = service.addConnector("tcp://localhost:0"); - return service; - } + private CountDownLatch asyncSendTo(final ActiveMQQueue queue, final String message) throws JMSException { + final CountDownLatch done = new CountDownLatch(1); + new Thread("Send thread.") { + public void run() { + Session session = null; + try { + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(queue); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + producer.send(session.createTextMessage(message)); + done.countDown(); + } + catch (JMSException e) { + } + finally { + safeClose(session); + } + } + }.start(); + return done; + } - public void setUp() throws Exception { - setAutoFail(true); - super.setUp(); - } - - protected void tearDown() throws Exception { - if (connection != null) { - TcpTransport t = (TcpTransport)connection.getTransport().narrow(TcpTransport.class); - t.getTransportListener().onException(new IOException("Disposed.")); - connection.getTransport().stop(); - } - super.tearDown(); - } + protected BrokerService createBroker() throws Exception { + BrokerService service = new BrokerService(); + service.setPersistent(false); + service.setUseJmx(false); - protected ConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(connector.getConnectUri()); - } + // Setup a destination policy where it takes only 1 message at a time. + PolicyMap policyMap = new PolicyMap(); + PolicyEntry policy = new PolicyEntry(); + policy.setMemoryLimit(1); + policy.setPendingSubscriberPolicy(new VMPendingSubscriberMessageStoragePolicy()); + policy.setPendingQueuePolicy(new VMPendingQueueMessageStoragePolicy()); + policy.setProducerFlowControl(true); + policyMap.setDefaultEntry(policy); + service.setDestinationPolicy(policyMap); + + connector = service.addConnector("tcp://localhost:0"); + return service; + } + + public void setUp() throws Exception { + setAutoFail(true); + super.setUp(); + } + + protected void tearDown() throws Exception { + if (connection != null) { + TcpTransport t = (TcpTransport) connection.getTransport().narrow(TcpTransport.class); + t.getTransportListener().onException(new IOException("Disposed.")); + connection.getTransport().stop(); + } + super.tearDown(); + } + + protected ConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory(connector.getConnectUri()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/QueueConsumerPriorityTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/QueueConsumerPriorityTest.java index 2a61820cc3..035832371f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/QueueConsumerPriorityTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/QueueConsumerPriorityTest.java @@ -30,65 +30,66 @@ import org.apache.activemq.command.ActiveMQQueue; public class QueueConsumerPriorityTest extends TestCase { - private static final String VM_BROKER_URL = "vm://localhost?broker.persistent=false&broker.useJmx=true"; + private static final String VM_BROKER_URL = "vm://localhost?broker.persistent=false&broker.useJmx=true"; - public QueueConsumerPriorityTest(String name) { - super(name); - } + public QueueConsumerPriorityTest(String name) { + super(name); + } - @Override - protected void setUp() throws Exception { - super.setUp(); - } + @Override + protected void setUp() throws Exception { + super.setUp(); + } - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } - private Connection createConnection(final boolean start) throws JMSException { - ConnectionFactory cf = new ActiveMQConnectionFactory(VM_BROKER_URL); - Connection conn = cf.createConnection(); - if (start) { - conn.start(); - } - return conn; - } + private Connection createConnection(final boolean start) throws JMSException { + ConnectionFactory cf = new ActiveMQConnectionFactory(VM_BROKER_URL); + Connection conn = cf.createConnection(); + if (start) { + conn.start(); + } + return conn; + } - public void testQueueConsumerPriority() throws JMSException, InterruptedException { - Connection conn = createConnection(true); + public void testQueueConsumerPriority() throws JMSException, InterruptedException { + Connection conn = createConnection(true); - Session consumerLowPriority = null; - Session consumerHighPriority = null; - Session senderSession = null; + Session consumerLowPriority = null; + Session consumerHighPriority = null; + Session senderSession = null; - try { + try { - consumerLowPriority = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumerHighPriority = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - assertNotNull(consumerHighPriority); - senderSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - String queueName = getClass().getName(); - ActiveMQQueue low = new ActiveMQQueue(queueName+"?consumer.priority=1"); - MessageConsumer lowConsumer = consumerLowPriority.createConsumer(low); + consumerLowPriority = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumerHighPriority = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + assertNotNull(consumerHighPriority); + senderSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + String queueName = getClass().getName(); + ActiveMQQueue low = new ActiveMQQueue(queueName + "?consumer.priority=1"); + MessageConsumer lowConsumer = consumerLowPriority.createConsumer(low); - ActiveMQQueue high = new ActiveMQQueue(queueName+"?consumer.priority=2"); - MessageConsumer highConsumer = consumerLowPriority.createConsumer(high); + ActiveMQQueue high = new ActiveMQQueue(queueName + "?consumer.priority=2"); + MessageConsumer highConsumer = consumerLowPriority.createConsumer(high); - ActiveMQQueue senderQueue = new ActiveMQQueue(queueName); + ActiveMQQueue senderQueue = new ActiveMQQueue(queueName); - MessageProducer producer = senderSession.createProducer(senderQueue); + MessageProducer producer = senderSession.createProducer(senderQueue); - Message msg = senderSession.createTextMessage("test"); - for (int i =0; i< 10000;i++) { - producer.send(msg); - assertNotNull("null on iteration: " + i, highConsumer.receive(500)); - } - assertNull(lowConsumer.receive(2000)); + Message msg = senderSession.createTextMessage("test"); + for (int i = 0; i < 10000; i++) { + producer.send(msg); + assertNotNull("null on iteration: " + i, highConsumer.receive(500)); + } + assertNull(lowConsumer.receive(2000)); - } finally { - conn.close(); - } - } + } + finally { + conn.close(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ReconnectWithSameClientIDTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ReconnectWithSameClientIDTest.java index 81d13b2f1e..e11820074e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ReconnectWithSameClientIDTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ReconnectWithSameClientIDTest.java @@ -24,6 +24,7 @@ import javax.jms.JMSException; import javax.jms.Session; import junit.framework.Test; + import org.apache.activemq.util.DefaultTestAppender; import org.apache.log4j.Appender; import org.apache.log4j.spi.LoggingEvent; @@ -31,86 +32,88 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ReconnectWithSameClientIDTest extends EmbeddedBrokerTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(ReconnectWithSameClientIDTest.class); - protected Connection connection; - protected boolean transacted; - protected int authMode = Session.AUTO_ACKNOWLEDGE; - public boolean useFailover = false; + private static final Logger LOG = LoggerFactory.getLogger(ReconnectWithSameClientIDTest.class); - public static Test suite() { - return suite(ReconnectWithSameClientIDTest.class); - } + protected Connection connection; + protected boolean transacted; + protected int authMode = Session.AUTO_ACKNOWLEDGE; + public boolean useFailover = false; - public void initCombosForTestReconnectMultipleTimesWithSameClientID() { - addCombinationValues("useFailover", new Object[]{Boolean.FALSE, Boolean.TRUE}); - } + public static Test suite() { + return suite(ReconnectWithSameClientIDTest.class); + } - public void testReconnectMultipleTimesWithSameClientID() throws Exception { + public void initCombosForTestReconnectMultipleTimesWithSameClientID() { + addCombinationValues("useFailover", new Object[]{Boolean.FALSE, Boolean.TRUE}); + } - org.apache.log4j.Logger log4jLogger = - org.apache.log4j.Logger.getLogger(org.apache.activemq.broker.jmx.ManagedTransportConnection.class); - final AtomicBoolean failed = new AtomicBoolean(false); + public void testReconnectMultipleTimesWithSameClientID() throws Exception { - Appender appender = new DefaultTestAppender() { - @Override - public void doAppend(LoggingEvent event) { - if (event.getMessage().toString().startsWith("Failed to register MBean")) { - LOG.info("received unexpected log message: " + event.getMessage()); - failed.set(true); - } + org.apache.log4j.Logger log4jLogger = org.apache.log4j.Logger.getLogger(org.apache.activemq.broker.jmx.ManagedTransportConnection.class); + final AtomicBoolean failed = new AtomicBoolean(false); + + Appender appender = new DefaultTestAppender() { + @Override + public void doAppend(LoggingEvent event) { + if (event.getMessage().toString().startsWith("Failed to register MBean")) { + LOG.info("received unexpected log message: " + event.getMessage()); + failed.set(true); } - }; - log4jLogger.addAppender(appender); - try { - connection = connectionFactory.createConnection(); - useConnection(connection); + } + }; + log4jLogger.addAppender(appender); + try { + connection = connectionFactory.createConnection(); + useConnection(connection); - // now lets create another which should fail - for (int i = 1; i < 11; i++) { - Connection connection2 = connectionFactory.createConnection(); - try { - useConnection(connection2); - fail("Should have thrown InvalidClientIDException on attempt" + i); - } catch (InvalidClientIDException e) { - LOG.info("Caught expected: " + e); - } finally { - connection2.close(); - } + // now lets create another which should fail + for (int i = 1; i < 11; i++) { + Connection connection2 = connectionFactory.createConnection(); + try { + useConnection(connection2); + fail("Should have thrown InvalidClientIDException on attempt" + i); } + catch (InvalidClientIDException e) { + LOG.info("Caught expected: " + e); + } + finally { + connection2.close(); + } + } - // now lets try closing the original connection and creating a new - // connection with the same ID - connection.close(); - connection = connectionFactory.createConnection(); - useConnection(connection); - } finally { - log4jLogger.removeAppender(appender); - } - assertFalse("failed on unexpected log event", failed.get()); - } + // now lets try closing the original connection and creating a new + // connection with the same ID + connection.close(); + connection = connectionFactory.createConnection(); + useConnection(connection); + } + finally { + log4jLogger.removeAppender(appender); + } + assertFalse("failed on unexpected log event", failed.get()); + } - @Override - protected ConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory((useFailover ? "failover:" : "") + - broker.getTransportConnectors().get(0).getPublishableConnectString()); - } + @Override + protected ConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory((useFailover ? "failover:" : "") + broker.getTransportConnectors().get(0).getPublishableConnectString()); + } - protected void setUp() throws Exception { - bindAddress = "tcp://localhost:0"; - super.setUp(); - } + protected void setUp() throws Exception { + bindAddress = "tcp://localhost:0"; + super.setUp(); + } - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - connection = null; - } - super.tearDown(); - } + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + connection = null; + } + super.tearDown(); + } - protected void useConnection(Connection connection) throws JMSException { - connection.setClientID("foo"); - connection.start(); - } + protected void useConnection(Connection connection) throws JMSException { + connection.setClientID("foo"); + connection.start(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/RedeliveryPolicyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/RedeliveryPolicyTest.java index e2b58677c3..ea042bf279 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/RedeliveryPolicyTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/RedeliveryPolicyTest.java @@ -29,6 +29,7 @@ import javax.jms.ServerSession; import javax.jms.ServerSessionPool; import javax.jms.Session; import javax.jms.TextMessage; + import junit.framework.Test; import org.apache.activemq.broker.region.policy.RedeliveryPolicyMap; @@ -40,791 +41,783 @@ import org.apache.activemq.util.Wait; public class RedeliveryPolicyTest extends JmsTestSupport { - public static Test suite() { - return suite(RedeliveryPolicyTest.class); - } + public static Test suite() { + return suite(RedeliveryPolicyTest.class); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } + public void testGetNext() throws Exception { - public void testGetNext() throws Exception { + RedeliveryPolicy policy = new RedeliveryPolicy(); + policy.setInitialRedeliveryDelay(0); + policy.setRedeliveryDelay(500); + policy.setBackOffMultiplier((short) 2); + policy.setUseExponentialBackOff(true); - RedeliveryPolicy policy = new RedeliveryPolicy(); - policy.setInitialRedeliveryDelay(0); - policy.setRedeliveryDelay(500); - policy.setBackOffMultiplier((short) 2); - policy.setUseExponentialBackOff(true); + long delay = policy.getNextRedeliveryDelay(0); + assertEquals(500, delay); + delay = policy.getNextRedeliveryDelay(delay); + assertEquals(500 * 2, delay); + delay = policy.getNextRedeliveryDelay(delay); + assertEquals(500 * 4, delay); - long delay = policy.getNextRedeliveryDelay(0); - assertEquals(500, delay); - delay = policy.getNextRedeliveryDelay(delay); - assertEquals(500*2, delay); - delay = policy.getNextRedeliveryDelay(delay); - assertEquals(500*4, delay); + policy.setUseExponentialBackOff(false); + delay = policy.getNextRedeliveryDelay(delay); + assertEquals(500, delay); + } - policy.setUseExponentialBackOff(false); - delay = policy.getNextRedeliveryDelay(delay); - assertEquals(500, delay); - } + /** + * @throws Exception + */ + public void testExponentialRedeliveryPolicyDelaysDeliveryOnRollback() throws Exception { - /** - * @throws Exception - */ - public void testExponentialRedeliveryPolicyDelaysDeliveryOnRollback() throws Exception { + // Receive a message with the JMS API + RedeliveryPolicy policy = connection.getRedeliveryPolicy(); + policy.setInitialRedeliveryDelay(0); + policy.setRedeliveryDelay(500); + policy.setBackOffMultiplier((short) 2); + policy.setUseExponentialBackOff(true); - // Receive a message with the JMS API - RedeliveryPolicy policy = connection.getRedeliveryPolicy(); - policy.setInitialRedeliveryDelay(0); - policy.setRedeliveryDelay(500); - policy.setBackOffMultiplier((short) 2); - policy.setUseExponentialBackOff(true); + connection.start(); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + ActiveMQQueue destination = new ActiveMQQueue(getName()); + MessageProducer producer = session.createProducer(destination); - connection.start(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - ActiveMQQueue destination = new ActiveMQQueue(getName()); - MessageProducer producer = session.createProducer(destination); + MessageConsumer consumer = session.createConsumer(destination); - MessageConsumer consumer = session.createConsumer(destination); + // Send the messages + producer.send(session.createTextMessage("1st")); + producer.send(session.createTextMessage("2nd")); + session.commit(); - // Send the messages - producer.send(session.createTextMessage("1st")); - producer.send(session.createTextMessage("2nd")); - session.commit(); + TextMessage m; + m = (TextMessage) consumer.receive(1000); + assertNotNull(m); + assertEquals("1st", m.getText()); + session.rollback(); - TextMessage m; - m = (TextMessage)consumer.receive(1000); - assertNotNull(m); - assertEquals("1st", m.getText()); - session.rollback(); + // No delay on first rollback.. + m = (TextMessage) consumer.receive(100); + assertNotNull(m); + session.rollback(); - // No delay on first rollback.. - m = (TextMessage)consumer.receive(100); - assertNotNull(m); - session.rollback(); + // Show subsequent re-delivery delay is incrementing. + m = (TextMessage) consumer.receive(100); + assertNull(m); - // Show subsequent re-delivery delay is incrementing. - m = (TextMessage)consumer.receive(100); - assertNull(m); + m = (TextMessage) consumer.receive(700); + assertNotNull(m); + assertEquals("1st", m.getText()); + session.rollback(); - m = (TextMessage)consumer.receive(700); - assertNotNull(m); - assertEquals("1st", m.getText()); - session.rollback(); + // Show re-delivery delay is incrementing exponentially + m = (TextMessage) consumer.receive(100); + assertNull(m); + m = (TextMessage) consumer.receive(500); + assertNull(m); + m = (TextMessage) consumer.receive(700); + assertNotNull(m); + assertEquals("1st", m.getText()); - // Show re-delivery delay is incrementing exponentially - m = (TextMessage)consumer.receive(100); - assertNull(m); - m = (TextMessage)consumer.receive(500); - assertNull(m); - m = (TextMessage)consumer.receive(700); - assertNotNull(m); - assertEquals("1st", m.getText()); + } - } + /** + * @throws Exception + */ + public void testNornalRedeliveryPolicyDelaysDeliveryOnRollback() throws Exception { + // Receive a message with the JMS API + RedeliveryPolicy policy = connection.getRedeliveryPolicy(); + policy.setInitialRedeliveryDelay(0); + policy.setRedeliveryDelay(500); - /** - * @throws Exception - */ - public void testNornalRedeliveryPolicyDelaysDeliveryOnRollback() throws Exception { + connection.start(); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + ActiveMQQueue destination = new ActiveMQQueue(getName()); + MessageProducer producer = session.createProducer(destination); - // Receive a message with the JMS API - RedeliveryPolicy policy = connection.getRedeliveryPolicy(); - policy.setInitialRedeliveryDelay(0); - policy.setRedeliveryDelay(500); + MessageConsumer consumer = session.createConsumer(destination); - connection.start(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - ActiveMQQueue destination = new ActiveMQQueue(getName()); - MessageProducer producer = session.createProducer(destination); + // Send the messages + producer.send(session.createTextMessage("1st")); + producer.send(session.createTextMessage("2nd")); + session.commit(); - MessageConsumer consumer = session.createConsumer(destination); + TextMessage m; + m = (TextMessage) consumer.receive(1000); + assertNotNull(m); + assertEquals("1st", m.getText()); + session.rollback(); - // Send the messages - producer.send(session.createTextMessage("1st")); - producer.send(session.createTextMessage("2nd")); - session.commit(); + // No delay on first rollback.. + m = (TextMessage) consumer.receive(100); + assertNotNull(m); + session.rollback(); - TextMessage m; - m = (TextMessage)consumer.receive(1000); - assertNotNull(m); - assertEquals("1st", m.getText()); - session.rollback(); + // Show subsequent re-delivery delay is incrementing. + m = (TextMessage) consumer.receive(100); + assertNull(m); + m = (TextMessage) consumer.receive(700); + assertNotNull(m); + assertEquals("1st", m.getText()); + session.rollback(); - // No delay on first rollback.. - m = (TextMessage)consumer.receive(100); - assertNotNull(m); - session.rollback(); + // The message gets redelivered after 500 ms every time since + // we are not using exponential backoff. + m = (TextMessage) consumer.receive(100); + assertNull(m); + m = (TextMessage) consumer.receive(700); + assertNotNull(m); + assertEquals("1st", m.getText()); - // Show subsequent re-delivery delay is incrementing. - m = (TextMessage)consumer.receive(100); - assertNull(m); - m = (TextMessage)consumer.receive(700); - assertNotNull(m); - assertEquals("1st", m.getText()); - session.rollback(); + } - // The message gets redelivered after 500 ms every time since - // we are not using exponential backoff. - m = (TextMessage)consumer.receive(100); - assertNull(m); - m = (TextMessage)consumer.receive(700); - assertNotNull(m); - assertEquals("1st", m.getText()); + /** + * @throws Exception + */ + public void testDLQHandling() throws Exception { - } + // Receive a message with the JMS API + RedeliveryPolicy policy = connection.getRedeliveryPolicy(); + policy.setInitialRedeliveryDelay(100); + policy.setUseExponentialBackOff(false); + policy.setMaximumRedeliveries(2); - /** - * @throws Exception - */ - public void testDLQHandling() throws Exception { + connection.start(); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + ActiveMQQueue destination = new ActiveMQQueue("TEST"); + MessageProducer producer = session.createProducer(destination); - // Receive a message with the JMS API - RedeliveryPolicy policy = connection.getRedeliveryPolicy(); - policy.setInitialRedeliveryDelay(100); - policy.setUseExponentialBackOff(false); - policy.setMaximumRedeliveries(2); + MessageConsumer consumer = session.createConsumer(destination); + MessageConsumer dlqConsumer = session.createConsumer(new ActiveMQQueue("ActiveMQ.DLQ")); - connection.start(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - ActiveMQQueue destination = new ActiveMQQueue("TEST"); - MessageProducer producer = session.createProducer(destination); + // Send the messages + producer.send(session.createTextMessage("1st")); + producer.send(session.createTextMessage("2nd")); + session.commit(); - MessageConsumer consumer = session.createConsumer(destination); - MessageConsumer dlqConsumer = session.createConsumer(new ActiveMQQueue("ActiveMQ.DLQ")); + TextMessage m; + m = (TextMessage) consumer.receive(1000); + assertNotNull(m); + assertEquals("1st", m.getText()); + session.rollback(); - // Send the messages - producer.send(session.createTextMessage("1st")); - producer.send(session.createTextMessage("2nd")); - session.commit(); + m = (TextMessage) consumer.receive(1000); + assertNotNull(m); + assertEquals("1st", m.getText()); + session.rollback(); - TextMessage m; - m = (TextMessage)consumer.receive(1000); - assertNotNull(m); - assertEquals("1st", m.getText()); - session.rollback(); + m = (TextMessage) consumer.receive(2000); + assertNotNull(m); + assertEquals("1st", m.getText()); + session.rollback(); - m = (TextMessage)consumer.receive(1000); - assertNotNull(m); - assertEquals("1st", m.getText()); - session.rollback(); + // The last rollback should cause the 1st message to get sent to the DLQ + m = (TextMessage) consumer.receive(1000); + assertNotNull(m); + assertEquals("2nd", m.getText()); + session.commit(); - m = (TextMessage)consumer.receive(2000); - assertNotNull(m); - assertEquals("1st", m.getText()); - session.rollback(); + // We should be able to get the message off the DLQ now. + m = (TextMessage) dlqConsumer.receive(1000); + assertNotNull(m); + assertEquals("1st", m.getText()); + String cause = m.getStringProperty(ActiveMQMessage.DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY); + assertTrue("cause exception has policy ref", cause.contains("RedeliveryPolicy")); + session.commit(); - // The last rollback should cause the 1st message to get sent to the DLQ - m = (TextMessage)consumer.receive(1000); - assertNotNull(m); - assertEquals("2nd", m.getText()); - session.commit(); + } - // We should be able to get the message off the DLQ now. - m = (TextMessage)dlqConsumer.receive(1000); - assertNotNull(m); - assertEquals("1st", m.getText()); - String cause = m.getStringProperty(ActiveMQMessage.DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY); - assertTrue("cause exception has policy ref", cause.contains("RedeliveryPolicy")); - session.commit(); + /** + * @throws Exception + */ + public void testInfiniteMaximumNumberOfRedeliveries() throws Exception { - } + // Receive a message with the JMS API + RedeliveryPolicy policy = connection.getRedeliveryPolicy(); + policy.setInitialRedeliveryDelay(100); + policy.setUseExponentialBackOff(false); + // let's set the maximum redeliveries to no maximum (ie. infinite) + policy.setMaximumRedeliveries(-1); + connection.start(); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + ActiveMQQueue destination = new ActiveMQQueue("TEST"); + MessageProducer producer = session.createProducer(destination); - /** - * @throws Exception - */ - public void testInfiniteMaximumNumberOfRedeliveries() throws Exception { + MessageConsumer consumer = session.createConsumer(destination); - // Receive a message with the JMS API - RedeliveryPolicy policy = connection.getRedeliveryPolicy(); - policy.setInitialRedeliveryDelay(100); - policy.setUseExponentialBackOff(false); - // let's set the maximum redeliveries to no maximum (ie. infinite) - policy.setMaximumRedeliveries(-1); + // Send the messages + producer.send(session.createTextMessage("1st")); + producer.send(session.createTextMessage("2nd")); + session.commit(); + TextMessage m; - connection.start(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - ActiveMQQueue destination = new ActiveMQQueue("TEST"); - MessageProducer producer = session.createProducer(destination); + m = (TextMessage) consumer.receive(1000); + assertNotNull(m); + assertEquals("1st", m.getText()); + session.rollback(); - MessageConsumer consumer = session.createConsumer(destination); + //we should be able to get the 1st message redelivered until a session.commit is called + m = (TextMessage) consumer.receive(1000); + assertNotNull(m); + assertEquals("1st", m.getText()); + session.rollback(); - // Send the messages - producer.send(session.createTextMessage("1st")); - producer.send(session.createTextMessage("2nd")); - session.commit(); + m = (TextMessage) consumer.receive(2000); + assertNotNull(m); + assertEquals("1st", m.getText()); + session.rollback(); - TextMessage m; + m = (TextMessage) consumer.receive(2000); + assertNotNull(m); + assertEquals("1st", m.getText()); + session.rollback(); - m = (TextMessage)consumer.receive(1000); - assertNotNull(m); - assertEquals("1st", m.getText()); - session.rollback(); + m = (TextMessage) consumer.receive(2000); + assertNotNull(m); + assertEquals("1st", m.getText()); + session.rollback(); - //we should be able to get the 1st message redelivered until a session.commit is called - m = (TextMessage)consumer.receive(1000); - assertNotNull(m); - assertEquals("1st", m.getText()); - session.rollback(); + m = (TextMessage) consumer.receive(2000); + assertNotNull(m); + assertEquals("1st", m.getText()); + session.commit(); - m = (TextMessage)consumer.receive(2000); - assertNotNull(m); - assertEquals("1st", m.getText()); - session.rollback(); + m = (TextMessage) consumer.receive(2000); + assertNotNull(m); + assertEquals("2nd", m.getText()); + session.commit(); - m = (TextMessage)consumer.receive(2000); - assertNotNull(m); - assertEquals("1st", m.getText()); - session.rollback(); + } - m = (TextMessage)consumer.receive(2000); - assertNotNull(m); - assertEquals("1st", m.getText()); - session.rollback(); + /** + * @throws Exception + */ + public void testMaximumRedeliveryDelay() throws Exception { - m = (TextMessage)consumer.receive(2000); - assertNotNull(m); - assertEquals("1st", m.getText()); - session.commit(); + // Receive a message with the JMS API + RedeliveryPolicy policy = connection.getRedeliveryPolicy(); + policy.setInitialRedeliveryDelay(10); + policy.setUseExponentialBackOff(true); + policy.setMaximumRedeliveries(-1); + policy.setRedeliveryDelay(50); + policy.setMaximumRedeliveryDelay(1000); + policy.setBackOffMultiplier((short) 2); + policy.setUseExponentialBackOff(true); - m = (TextMessage)consumer.receive(2000); - assertNotNull(m); - assertEquals("2nd", m.getText()); - session.commit(); + connection.start(); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + ActiveMQQueue destination = new ActiveMQQueue("TEST"); + MessageProducer producer = session.createProducer(destination); - } + MessageConsumer consumer = session.createConsumer(destination); - /** - * @throws Exception - */ - public void testMaximumRedeliveryDelay() throws Exception { + // Send the messages + producer.send(session.createTextMessage("1st")); + producer.send(session.createTextMessage("2nd")); + session.commit(); - // Receive a message with the JMS API - RedeliveryPolicy policy = connection.getRedeliveryPolicy(); - policy.setInitialRedeliveryDelay(10); - policy.setUseExponentialBackOff(true); - policy.setMaximumRedeliveries(-1); - policy.setRedeliveryDelay(50); - policy.setMaximumRedeliveryDelay(1000); - policy.setBackOffMultiplier((short) 2); - policy.setUseExponentialBackOff(true); + TextMessage m; - connection.start(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - ActiveMQQueue destination = new ActiveMQQueue("TEST"); - MessageProducer producer = session.createProducer(destination); + for (int i = 0; i < 10; ++i) { + // we should be able to get the 1st message redelivered until a session.commit is called + m = (TextMessage) consumer.receive(2000); + assertNotNull(m); + assertEquals("1st", m.getText()); + session.rollback(); + } - MessageConsumer consumer = session.createConsumer(destination); + m = (TextMessage) consumer.receive(2000); + assertNotNull(m); + assertEquals("1st", m.getText()); + session.commit(); - // Send the messages - producer.send(session.createTextMessage("1st")); - producer.send(session.createTextMessage("2nd")); - session.commit(); + m = (TextMessage) consumer.receive(2000); + assertNotNull(m); + assertEquals("2nd", m.getText()); + session.commit(); - TextMessage m; + assertTrue(policy.getNextRedeliveryDelay(Long.MAX_VALUE) == 1000); + } - for(int i = 0; i < 10; ++i) { - // we should be able to get the 1st message redelivered until a session.commit is called - m = (TextMessage)consumer.receive(2000); - assertNotNull(m); + /** + * @throws Exception + */ + public void testZeroMaximumNumberOfRedeliveries() throws Exception { + + // Receive a message with the JMS API + RedeliveryPolicy policy = connection.getRedeliveryPolicy(); + policy.setInitialRedeliveryDelay(100); + policy.setUseExponentialBackOff(false); + //let's set the maximum redeliveries to 0 + policy.setMaximumRedeliveries(0); + + connection.start(); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + ActiveMQQueue destination = new ActiveMQQueue("TEST"); + MessageProducer producer = session.createProducer(destination); + + MessageConsumer consumer = session.createConsumer(destination); + + // Send the messages + producer.send(session.createTextMessage("1st")); + producer.send(session.createTextMessage("2nd")); + session.commit(); + + TextMessage m; + m = (TextMessage) consumer.receive(1000); + assertNotNull(m); + assertEquals("1st", m.getText()); + session.rollback(); + + //the 1st message should not be redelivered since maximumRedeliveries is set to 0 + m = (TextMessage) consumer.receive(1000); + assertNotNull(m); + assertEquals("2nd", m.getText()); + session.commit(); + + } + + public void testRepeatedRedeliveryReceiveNoCommit() throws Exception { + + connection.start(); + Session dlqSession = connection.createSession(true, Session.SESSION_TRANSACTED); + ActiveMQQueue destination = new ActiveMQQueue("TEST"); + MessageProducer producer = dlqSession.createProducer(destination); + + // Send the messages + producer.send(dlqSession.createTextMessage("1st")); + + dlqSession.commit(); + MessageConsumer dlqConsumer = dlqSession.createConsumer(new ActiveMQQueue("ActiveMQ.DLQ")); + + final int maxRedeliveries = 4; + for (int i = 0; i <= maxRedeliveries + 1; i++) { + + connection = (ActiveMQConnection) factory.createConnection(userName, password); + connections.add(connection); + // Receive a message with the JMS API + RedeliveryPolicy policy = connection.getRedeliveryPolicy(); + policy.setInitialRedeliveryDelay(0); + policy.setUseExponentialBackOff(false); + policy.setMaximumRedeliveries(maxRedeliveries); + + connection.start(); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(destination); + + ActiveMQTextMessage m = ((ActiveMQTextMessage) consumer.receive(4000)); + if (i <= maxRedeliveries) { assertEquals("1st", m.getText()); - session.rollback(); - } + assertEquals(i, m.getRedeliveryCounter()); + } + else { + assertNull("null on exceeding redelivery count", m); + } + connection.close(); + connections.remove(connection); + } - m = (TextMessage)consumer.receive(2000); - assertNotNull(m); - assertEquals("1st", m.getText()); - session.commit(); + // We should be able to get the message off the DLQ now. + TextMessage m = (TextMessage) dlqConsumer.receive(1000); + assertNotNull("Got message from DLQ", m); + assertEquals("1st", m.getText()); + String cause = m.getStringProperty(ActiveMQMessage.DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY); + assertTrue("cause exception has policy ref", cause.contains("RedeliveryPolicy")); + dlqSession.commit(); - m = (TextMessage)consumer.receive(2000); - assertNotNull(m); - assertEquals("2nd", m.getText()); - session.commit(); + } - assertTrue(policy.getNextRedeliveryDelay(Long.MAX_VALUE) == 1000 ); - } + public void testRepeatedRedeliveryOnMessageNoCommit() throws Exception { - /** - * @throws Exception - */ - public void testZeroMaximumNumberOfRedeliveries() throws Exception { + connection.start(); + Session dlqSession = connection.createSession(true, Session.SESSION_TRANSACTED); + ActiveMQQueue destination = new ActiveMQQueue("TEST"); + MessageProducer producer = dlqSession.createProducer(destination); - // Receive a message with the JMS API - RedeliveryPolicy policy = connection.getRedeliveryPolicy(); - policy.setInitialRedeliveryDelay(100); - policy.setUseExponentialBackOff(false); - //let's set the maximum redeliveries to 0 - policy.setMaximumRedeliveries(0); + // Send the messages + producer.send(dlqSession.createTextMessage("1st")); - connection.start(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - ActiveMQQueue destination = new ActiveMQQueue("TEST"); - MessageProducer producer = session.createProducer(destination); + dlqSession.commit(); + MessageConsumer dlqConsumer = dlqSession.createConsumer(new ActiveMQQueue("ActiveMQ.DLQ")); - MessageConsumer consumer = session.createConsumer(destination); + final int maxRedeliveries = 4; + final AtomicInteger receivedCount = new AtomicInteger(0); - // Send the messages - producer.send(session.createTextMessage("1st")); - producer.send(session.createTextMessage("2nd")); - session.commit(); + for (int i = 0; i <= maxRedeliveries + 1; i++) { - TextMessage m; - m = (TextMessage)consumer.receive(1000); - assertNotNull(m); - assertEquals("1st", m.getText()); - session.rollback(); + connection = (ActiveMQConnection) factory.createConnection(userName, password); + connections.add(connection); - //the 1st message should not be redelivered since maximumRedeliveries is set to 0 - m = (TextMessage)consumer.receive(1000); - assertNotNull(m); - assertEquals("2nd", m.getText()); - session.commit(); + RedeliveryPolicy policy = connection.getRedeliveryPolicy(); + policy.setInitialRedeliveryDelay(0); + policy.setUseExponentialBackOff(false); + policy.setMaximumRedeliveries(maxRedeliveries); + connection.start(); + final Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageConsumer consumer = session.createConsumer(destination); + final CountDownLatch done = new CountDownLatch(1); - - } - - public void testRepeatedRedeliveryReceiveNoCommit() throws Exception { - - connection.start(); - Session dlqSession = connection.createSession(true, Session.SESSION_TRANSACTED); - ActiveMQQueue destination = new ActiveMQQueue("TEST"); - MessageProducer producer = dlqSession.createProducer(destination); - - // Send the messages - producer.send(dlqSession.createTextMessage("1st")); - - dlqSession.commit(); - MessageConsumer dlqConsumer = dlqSession.createConsumer(new ActiveMQQueue("ActiveMQ.DLQ")); - - final int maxRedeliveries = 4; - for (int i=0;i<=maxRedeliveries +1;i++) { - - connection = (ActiveMQConnection)factory.createConnection(userName, password); - connections.add(connection); - // Receive a message with the JMS API - RedeliveryPolicy policy = connection.getRedeliveryPolicy(); - policy.setInitialRedeliveryDelay(0); - policy.setUseExponentialBackOff(false); - policy.setMaximumRedeliveries(maxRedeliveries); - - connection.start(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); - - ActiveMQTextMessage m = ((ActiveMQTextMessage)consumer.receive(4000)); - if (i<=maxRedeliveries) { - assertEquals("1st", m.getText()); - assertEquals(i, m.getRedeliveryCounter()); - } else { - assertNull("null on exceeding redelivery count", m); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + try { + ActiveMQTextMessage m = (ActiveMQTextMessage) message; + assertEquals("1st", m.getText()); + assertEquals(receivedCount.get(), m.getRedeliveryCounter()); + receivedCount.incrementAndGet(); + done.countDown(); + } + catch (Exception ignored) { + ignored.printStackTrace(); + } } - connection.close(); - connections.remove(connection); - } + }); - // We should be able to get the message off the DLQ now. - TextMessage m = (TextMessage)dlqConsumer.receive(1000); - assertNotNull("Got message from DLQ", m); - assertEquals("1st", m.getText()); - String cause = m.getStringProperty(ActiveMQMessage.DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY); - assertTrue("cause exception has policy ref", cause.contains("RedeliveryPolicy")); - dlqSession.commit(); + if (i <= maxRedeliveries) { + assertTrue("listener done", done.await(5, TimeUnit.SECONDS)); + } + else { + // final redlivery gets poisoned before dispatch + assertFalse("listener done", done.await(1, TimeUnit.SECONDS)); + } + connection.close(); + connections.remove(connection); + } - } + // We should be able to get the message off the DLQ now. + TextMessage m = (TextMessage) dlqConsumer.receive(1000); + assertNotNull("Got message from DLQ", m); + assertEquals("1st", m.getText()); + String cause = m.getStringProperty(ActiveMQMessage.DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY); + assertTrue("cause exception has policy ref", cause.contains("RedeliveryPolicy")); + dlqSession.commit(); + } - public void testRepeatedRedeliveryOnMessageNoCommit() throws Exception { + public void testRepeatedRedeliveryServerSessionNoCommit() throws Exception { - connection.start(); - Session dlqSession = connection.createSession(true, Session.SESSION_TRANSACTED); - ActiveMQQueue destination = new ActiveMQQueue("TEST"); - MessageProducer producer = dlqSession.createProducer(destination); + connection.start(); + Session dlqSession = connection.createSession(true, Session.SESSION_TRANSACTED); + ActiveMQQueue destination = new ActiveMQQueue("TEST"); + MessageProducer producer = dlqSession.createProducer(destination); - // Send the messages - producer.send(dlqSession.createTextMessage("1st")); + // Send the messages + producer.send(dlqSession.createTextMessage("1st")); - dlqSession.commit(); - MessageConsumer dlqConsumer = dlqSession.createConsumer(new ActiveMQQueue("ActiveMQ.DLQ")); + dlqSession.commit(); + MessageConsumer dlqConsumer = dlqSession.createConsumer(new ActiveMQQueue("ActiveMQ.DLQ")); - final int maxRedeliveries = 4; - final AtomicInteger receivedCount = new AtomicInteger(0); + final int maxRedeliveries = 4; + final AtomicInteger receivedCount = new AtomicInteger(0); - for (int i=0;i<=maxRedeliveries+1;i++) { + for (int i = 0; i <= maxRedeliveries + 1; i++) { - connection = (ActiveMQConnection)factory.createConnection(userName, password); - connections.add(connection); + connection = (ActiveMQConnection) factory.createConnection(userName, password); + connections.add(connection); - RedeliveryPolicy policy = connection.getRedeliveryPolicy(); - policy.setInitialRedeliveryDelay(0); - policy.setUseExponentialBackOff(false); - policy.setMaximumRedeliveries(maxRedeliveries); + RedeliveryPolicy policy = connection.getRedeliveryPolicy(); + policy.setInitialRedeliveryDelay(0); + policy.setUseExponentialBackOff(false); + policy.setMaximumRedeliveries(maxRedeliveries); - connection.start(); - final Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageConsumer consumer = session.createConsumer(destination); - final CountDownLatch done = new CountDownLatch(1); + connection.start(); + final CountDownLatch done = new CountDownLatch(1); - consumer.setMessageListener(new MessageListener(){ - @Override - public void onMessage(Message message) { - try { - ActiveMQTextMessage m = (ActiveMQTextMessage)message; - assertEquals("1st", m.getText()); - assertEquals(receivedCount.get(), m.getRedeliveryCounter()); - receivedCount.incrementAndGet(); - done.countDown(); - } catch (Exception ignored) { - ignored.printStackTrace(); - } - } - }); - - if (i<=maxRedeliveries) { - assertTrue("listener done", done.await(5, TimeUnit.SECONDS)); - } else { - // final redlivery gets poisoned before dispatch - assertFalse("listener done", done.await(1, TimeUnit.SECONDS)); + final ActiveMQSession session = (ActiveMQSession) connection.createSession(true, Session.SESSION_TRANSACTED); + session.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + try { + ActiveMQTextMessage m = (ActiveMQTextMessage) message; + assertEquals("1st", m.getText()); + assertEquals(receivedCount.get(), m.getRedeliveryCounter()); + receivedCount.incrementAndGet(); + done.countDown(); + } + catch (Exception ignored) { + ignored.printStackTrace(); + } } - connection.close(); - connections.remove(connection); - } + }); - // We should be able to get the message off the DLQ now. - TextMessage m = (TextMessage)dlqConsumer.receive(1000); - assertNotNull("Got message from DLQ", m); - assertEquals("1st", m.getText()); - String cause = m.getStringProperty(ActiveMQMessage.DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY); - assertTrue("cause exception has policy ref", cause.contains("RedeliveryPolicy")); - dlqSession.commit(); + connection.createConnectionConsumer(destination, null, new ServerSessionPool() { + @Override + public ServerSession getServerSession() throws JMSException { + return new ServerSession() { + @Override + public Session getSession() throws JMSException { + return session; + } - } + @Override + public void start() throws JMSException { + } + }; + } + }, 100, false); - public void testRepeatedRedeliveryServerSessionNoCommit() throws Exception { - - connection.start(); - Session dlqSession = connection.createSession(true, Session.SESSION_TRANSACTED); - ActiveMQQueue destination = new ActiveMQQueue("TEST"); - MessageProducer producer = dlqSession.createProducer(destination); - - // Send the messages - producer.send(dlqSession.createTextMessage("1st")); - - dlqSession.commit(); - MessageConsumer dlqConsumer = dlqSession.createConsumer(new ActiveMQQueue("ActiveMQ.DLQ")); - - final int maxRedeliveries = 4; - final AtomicInteger receivedCount = new AtomicInteger(0); - - for (int i=0;i<=maxRedeliveries+1;i++) { - - connection = (ActiveMQConnection)factory.createConnection(userName, password); - connections.add(connection); - - RedeliveryPolicy policy = connection.getRedeliveryPolicy(); - policy.setInitialRedeliveryDelay(0); - policy.setUseExponentialBackOff(false); - policy.setMaximumRedeliveries(maxRedeliveries); - - connection.start(); - final CountDownLatch done = new CountDownLatch(1); - - final ActiveMQSession session = (ActiveMQSession) connection.createSession(true, Session.SESSION_TRANSACTED); - session.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - try { - ActiveMQTextMessage m = (ActiveMQTextMessage) message; - assertEquals("1st", m.getText()); - assertEquals(receivedCount.get(), m.getRedeliveryCounter()); - receivedCount.incrementAndGet(); - done.countDown(); - } catch (Exception ignored) { - ignored.printStackTrace(); - } - } - }); - - connection.createConnectionConsumer( - destination, - null, - new ServerSessionPool() { - @Override - public ServerSession getServerSession() throws JMSException { - return new ServerSession() { - @Override - public Session getSession() throws JMSException { - return session; - } - - @Override - public void start() throws JMSException { - } - }; - } - }, - 100, - false); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - session.run(); - return done.await(10, TimeUnit.MILLISECONDS); - } - }); - - if (i<=maxRedeliveries) { - assertTrue("listener done @" + i, done.await(5, TimeUnit.SECONDS)); - } else { - // final redlivery gets poisoned before dispatch - assertFalse("listener not done @" + i, done.await(1, TimeUnit.SECONDS)); + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + session.run(); + return done.await(10, TimeUnit.MILLISECONDS); } - connection.close(); - connections.remove(connection); - } + }); - // We should be able to get the message off the DLQ now. - TextMessage m = (TextMessage)dlqConsumer.receive(1000); - assertNotNull("Got message from DLQ", m); - assertEquals("1st", m.getText()); - String cause = m.getStringProperty(ActiveMQMessage.DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY); - assertTrue("cause exception has policy ref", cause.contains("RedeliveryPolicy")); - dlqSession.commit(); + if (i <= maxRedeliveries) { + assertTrue("listener done @" + i, done.await(5, TimeUnit.SECONDS)); + } + else { + // final redlivery gets poisoned before dispatch + assertFalse("listener not done @" + i, done.await(1, TimeUnit.SECONDS)); + } + connection.close(); + connections.remove(connection); + } - } + // We should be able to get the message off the DLQ now. + TextMessage m = (TextMessage) dlqConsumer.receive(1000); + assertNotNull("Got message from DLQ", m); + assertEquals("1st", m.getText()); + String cause = m.getStringProperty(ActiveMQMessage.DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY); + assertTrue("cause exception has policy ref", cause.contains("RedeliveryPolicy")); + dlqSession.commit(); - public void testInitialRedeliveryDelayZero() throws Exception { + } - // Receive a message with the JMS API - RedeliveryPolicy policy = connection.getRedeliveryPolicy(); - policy.setInitialRedeliveryDelay(0); - policy.setUseExponentialBackOff(false); - policy.setMaximumRedeliveries(1); + public void testInitialRedeliveryDelayZero() throws Exception { - connection.start(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - ActiveMQQueue destination = new ActiveMQQueue("TEST"); - MessageProducer producer = session.createProducer(destination); + // Receive a message with the JMS API + RedeliveryPolicy policy = connection.getRedeliveryPolicy(); + policy.setInitialRedeliveryDelay(0); + policy.setUseExponentialBackOff(false); + policy.setMaximumRedeliveries(1); - MessageConsumer consumer = session.createConsumer(destination); + connection.start(); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + ActiveMQQueue destination = new ActiveMQQueue("TEST"); + MessageProducer producer = session.createProducer(destination); - // Send the messages - producer.send(session.createTextMessage("1st")); - producer.send(session.createTextMessage("2nd")); - session.commit(); + MessageConsumer consumer = session.createConsumer(destination); - TextMessage m; - m = (TextMessage)consumer.receive(100); - assertNotNull(m); - assertEquals("1st", m.getText()); - session.rollback(); + // Send the messages + producer.send(session.createTextMessage("1st")); + producer.send(session.createTextMessage("2nd")); + session.commit(); - m = (TextMessage)consumer.receive(100); - assertNotNull(m); - assertEquals("1st", m.getText()); + TextMessage m; + m = (TextMessage) consumer.receive(100); + assertNotNull(m); + assertEquals("1st", m.getText()); + session.rollback(); - m = (TextMessage)consumer.receive(100); - assertNotNull(m); - assertEquals("2nd", m.getText()); - session.commit(); + m = (TextMessage) consumer.receive(100); + assertNotNull(m); + assertEquals("1st", m.getText()); - session.commit(); - } + m = (TextMessage) consumer.receive(100); + assertNotNull(m); + assertEquals("2nd", m.getText()); + session.commit(); + session.commit(); + } - public void testInitialRedeliveryDelayOne() throws Exception { + public void testInitialRedeliveryDelayOne() throws Exception { - // Receive a message with the JMS API - RedeliveryPolicy policy = connection.getRedeliveryPolicy(); - policy.setInitialRedeliveryDelay(1000); - policy.setUseExponentialBackOff(false); - policy.setMaximumRedeliveries(1); + // Receive a message with the JMS API + RedeliveryPolicy policy = connection.getRedeliveryPolicy(); + policy.setInitialRedeliveryDelay(1000); + policy.setUseExponentialBackOff(false); + policy.setMaximumRedeliveries(1); - connection.start(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - ActiveMQQueue destination = new ActiveMQQueue("TEST"); - MessageProducer producer = session.createProducer(destination); + connection.start(); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + ActiveMQQueue destination = new ActiveMQQueue("TEST"); + MessageProducer producer = session.createProducer(destination); - MessageConsumer consumer = session.createConsumer(destination); + MessageConsumer consumer = session.createConsumer(destination); - // Send the messages - producer.send(session.createTextMessage("1st")); - producer.send(session.createTextMessage("2nd")); - session.commit(); + // Send the messages + producer.send(session.createTextMessage("1st")); + producer.send(session.createTextMessage("2nd")); + session.commit(); - TextMessage m; - m = (TextMessage)consumer.receive(100); - assertNotNull(m); - assertEquals("1st", m.getText()); - session.rollback(); + TextMessage m; + m = (TextMessage) consumer.receive(100); + assertNotNull(m); + assertEquals("1st", m.getText()); + session.rollback(); - m = (TextMessage)consumer.receive(100); - assertNull(m); + m = (TextMessage) consumer.receive(100); + assertNull(m); - m = (TextMessage)consumer.receive(2000); - assertNotNull(m); - assertEquals("1st", m.getText()); + m = (TextMessage) consumer.receive(2000); + assertNotNull(m); + assertEquals("1st", m.getText()); - m = (TextMessage)consumer.receive(100); - assertNotNull(m); - assertEquals("2nd", m.getText()); - session.commit(); - } + m = (TextMessage) consumer.receive(100); + assertNotNull(m); + assertEquals("2nd", m.getText()); + session.commit(); + } - public void testRedeliveryDelayOne() throws Exception { + public void testRedeliveryDelayOne() throws Exception { - // Receive a message with the JMS API - RedeliveryPolicy policy = connection.getRedeliveryPolicy(); - policy.setInitialRedeliveryDelay(0); - policy.setRedeliveryDelay(1000); - policy.setUseExponentialBackOff(false); - policy.setMaximumRedeliveries(2); + // Receive a message with the JMS API + RedeliveryPolicy policy = connection.getRedeliveryPolicy(); + policy.setInitialRedeliveryDelay(0); + policy.setRedeliveryDelay(1000); + policy.setUseExponentialBackOff(false); + policy.setMaximumRedeliveries(2); - connection.start(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - ActiveMQQueue destination = new ActiveMQQueue("TEST"); - MessageProducer producer = session.createProducer(destination); + connection.start(); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + ActiveMQQueue destination = new ActiveMQQueue("TEST"); + MessageProducer producer = session.createProducer(destination); - MessageConsumer consumer = session.createConsumer(destination); + MessageConsumer consumer = session.createConsumer(destination); - // Send the messages - producer.send(session.createTextMessage("1st")); - producer.send(session.createTextMessage("2nd")); - session.commit(); + // Send the messages + producer.send(session.createTextMessage("1st")); + producer.send(session.createTextMessage("2nd")); + session.commit(); - TextMessage m; - m = (TextMessage)consumer.receive(100); - assertNotNull(m); - assertEquals("1st", m.getText()); - session.rollback(); + TextMessage m; + m = (TextMessage) consumer.receive(100); + assertNotNull(m); + assertEquals("1st", m.getText()); + session.rollback(); - m = (TextMessage)consumer.receive(100); - assertNotNull("first immediate redelivery", m); - session.rollback(); + m = (TextMessage) consumer.receive(100); + assertNotNull("first immediate redelivery", m); + session.rollback(); - m = (TextMessage)consumer.receive(100); - assertNull("second delivery delayed: " + m, m); + m = (TextMessage) consumer.receive(100); + assertNull("second delivery delayed: " + m, m); - m = (TextMessage)consumer.receive(2000); - assertNotNull(m); - assertEquals("1st", m.getText()); + m = (TextMessage) consumer.receive(2000); + assertNotNull(m); + assertEquals("1st", m.getText()); - m = (TextMessage)consumer.receive(100); - assertNotNull(m); - assertEquals("2nd", m.getText()); - session.commit(); - } + m = (TextMessage) consumer.receive(100); + assertNotNull(m); + assertEquals("2nd", m.getText()); + session.commit(); + } - public void testRedeliveryPolicyPerDestination() throws Exception { + public void testRedeliveryPolicyPerDestination() throws Exception { - RedeliveryPolicy queuePolicy = new RedeliveryPolicy(); - queuePolicy.setInitialRedeliveryDelay(0); - queuePolicy.setRedeliveryDelay(1000); - queuePolicy.setUseExponentialBackOff(false); - queuePolicy.setMaximumRedeliveries(2); + RedeliveryPolicy queuePolicy = new RedeliveryPolicy(); + queuePolicy.setInitialRedeliveryDelay(0); + queuePolicy.setRedeliveryDelay(1000); + queuePolicy.setUseExponentialBackOff(false); + queuePolicy.setMaximumRedeliveries(2); - RedeliveryPolicy topicPolicy = new RedeliveryPolicy(); - topicPolicy.setInitialRedeliveryDelay(0); - topicPolicy.setRedeliveryDelay(1000); - topicPolicy.setUseExponentialBackOff(false); - topicPolicy.setMaximumRedeliveries(3); + RedeliveryPolicy topicPolicy = new RedeliveryPolicy(); + topicPolicy.setInitialRedeliveryDelay(0); + topicPolicy.setRedeliveryDelay(1000); + topicPolicy.setUseExponentialBackOff(false); + topicPolicy.setMaximumRedeliveries(3); - // Receive a message with the JMS API - RedeliveryPolicyMap map = connection.getRedeliveryPolicyMap(); - map.put(new ActiveMQTopic(">"), topicPolicy); - map.put(new ActiveMQQueue(">"), queuePolicy); + // Receive a message with the JMS API + RedeliveryPolicyMap map = connection.getRedeliveryPolicyMap(); + map.put(new ActiveMQTopic(">"), topicPolicy); + map.put(new ActiveMQQueue(">"), queuePolicy); - connection.start(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - ActiveMQQueue queue = new ActiveMQQueue("TEST"); - ActiveMQTopic topic = new ActiveMQTopic("TEST"); + connection.start(); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + ActiveMQQueue queue = new ActiveMQQueue("TEST"); + ActiveMQTopic topic = new ActiveMQTopic("TEST"); - MessageProducer producer = session.createProducer(null); + MessageProducer producer = session.createProducer(null); - MessageConsumer queueConsumer = session.createConsumer(queue); - MessageConsumer topicConsumer = session.createConsumer(topic); + MessageConsumer queueConsumer = session.createConsumer(queue); + MessageConsumer topicConsumer = session.createConsumer(topic); - // Send the messages - producer.send(queue, session.createTextMessage("1st")); - producer.send(queue, session.createTextMessage("2nd")); - producer.send(topic, session.createTextMessage("1st")); - producer.send(topic, session.createTextMessage("2nd")); + // Send the messages + producer.send(queue, session.createTextMessage("1st")); + producer.send(queue, session.createTextMessage("2nd")); + producer.send(topic, session.createTextMessage("1st")); + producer.send(topic, session.createTextMessage("2nd")); - session.commit(); + session.commit(); - TextMessage m; - m = (TextMessage)queueConsumer.receive(100); - assertNotNull(m); - assertEquals("1st", m.getText()); - m = (TextMessage)topicConsumer.receive(100); - assertNotNull(m); - assertEquals("1st", m.getText()); - m = (TextMessage)queueConsumer.receive(100); - assertNotNull(m); - assertEquals("2nd", m.getText()); - m = (TextMessage)topicConsumer.receive(100); - assertNotNull(m); - assertEquals("2nd", m.getText()); - session.rollback(); + TextMessage m; + m = (TextMessage) queueConsumer.receive(100); + assertNotNull(m); + assertEquals("1st", m.getText()); + m = (TextMessage) topicConsumer.receive(100); + assertNotNull(m); + assertEquals("1st", m.getText()); + m = (TextMessage) queueConsumer.receive(100); + assertNotNull(m); + assertEquals("2nd", m.getText()); + m = (TextMessage) topicConsumer.receive(100); + assertNotNull(m); + assertEquals("2nd", m.getText()); + session.rollback(); - m = (TextMessage)queueConsumer.receive(100); - assertNotNull("first immediate redelivery", m); - m = (TextMessage)topicConsumer.receive(100); - assertNotNull("first immediate redelivery", m); - session.rollback(); + m = (TextMessage) queueConsumer.receive(100); + assertNotNull("first immediate redelivery", m); + m = (TextMessage) topicConsumer.receive(100); + assertNotNull("first immediate redelivery", m); + session.rollback(); - m = (TextMessage)queueConsumer.receive(100); - assertNull("second delivery delayed: " + m, m); - m = (TextMessage)topicConsumer.receive(100); - assertNull("second delivery delayed: " + m, m); + m = (TextMessage) queueConsumer.receive(100); + assertNull("second delivery delayed: " + m, m); + m = (TextMessage) topicConsumer.receive(100); + assertNull("second delivery delayed: " + m, m); - m = (TextMessage)queueConsumer.receive(2000); - assertNotNull(m); - assertEquals("1st", m.getText()); - m = (TextMessage)topicConsumer.receive(2000); - assertNotNull(m); - assertEquals("1st", m.getText()); + m = (TextMessage) queueConsumer.receive(2000); + assertNotNull(m); + assertEquals("1st", m.getText()); + m = (TextMessage) topicConsumer.receive(2000); + assertNotNull(m); + assertEquals("1st", m.getText()); - m = (TextMessage)queueConsumer.receive(100); - assertNotNull(m); - assertEquals("2nd", m.getText()); - m = (TextMessage)topicConsumer.receive(100); - assertNotNull(m); - assertEquals("2nd", m.getText()); - session.rollback(); + m = (TextMessage) queueConsumer.receive(100); + assertNotNull(m); + assertEquals("2nd", m.getText()); + m = (TextMessage) topicConsumer.receive(100); + assertNotNull(m); + assertEquals("2nd", m.getText()); + session.rollback(); - m = (TextMessage)queueConsumer.receive(2000); - assertNotNull(m); - assertEquals("1st", m.getText()); - m = (TextMessage)topicConsumer.receive(2000); - assertNotNull(m); - assertEquals("1st", m.getText()); + m = (TextMessage) queueConsumer.receive(2000); + assertNotNull(m); + assertEquals("1st", m.getText()); + m = (TextMessage) topicConsumer.receive(2000); + assertNotNull(m); + assertEquals("1st", m.getText()); - m = (TextMessage)queueConsumer.receive(100); - assertNotNull(m); - assertEquals("2nd", m.getText()); - m = (TextMessage)topicConsumer.receive(100); - assertNotNull(m); - assertEquals("2nd", m.getText()); - session.rollback(); + m = (TextMessage) queueConsumer.receive(100); + assertNotNull(m); + assertEquals("2nd", m.getText()); + m = (TextMessage) topicConsumer.receive(100); + assertNotNull(m); + assertEquals("2nd", m.getText()); + session.rollback(); - // No third attempt for the Queue consumer - m = (TextMessage)queueConsumer.receive(2000); - assertNull(m); - m = (TextMessage)topicConsumer.receive(2000); - assertNotNull(m); - assertEquals("1st", m.getText()); + // No third attempt for the Queue consumer + m = (TextMessage) queueConsumer.receive(2000); + assertNull(m); + m = (TextMessage) topicConsumer.receive(2000); + assertNotNull(m); + assertEquals("1st", m.getText()); - m = (TextMessage)queueConsumer.receive(100); - assertNull(m); - m = (TextMessage)topicConsumer.receive(100); - assertNotNull(m); - assertEquals("2nd", m.getText()); - session.commit(); - } + m = (TextMessage) queueConsumer.receive(100); + assertNull(m); + m = (TextMessage) topicConsumer.receive(100); + assertNotNull(m); + assertEquals("2nd", m.getText()); + session.commit(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/RemoveDestinationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/RemoveDestinationTest.java index 009221b53f..542972392d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/RemoveDestinationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/RemoveDestinationTest.java @@ -45,121 +45,121 @@ import org.junit.Test; public class RemoveDestinationTest { - private static final String VM_BROKER_URL = "vm://localhost?create=false"; - private static final String BROKER_URL = "broker:vm://localhost?broker.persistent=false&broker.useJmx=true"; + private static final String VM_BROKER_URL = "vm://localhost?create=false"; + private static final String BROKER_URL = "broker:vm://localhost?broker.persistent=false&broker.useJmx=true"; - BrokerService broker; + BrokerService broker; - @Before - public void setUp() throws Exception { - broker = BrokerFactory.createBroker(new URI(BROKER_URL)); - broker.start(); - broker.waitUntilStarted(); - } + @Before + public void setUp() throws Exception { + broker = BrokerFactory.createBroker(new URI(BROKER_URL)); + broker.start(); + broker.waitUntilStarted(); + } - @After - public void tearDown() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - broker = null; - } + @After + public void tearDown() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + broker = null; + } - private Connection createConnection(final boolean start) throws JMSException { - ConnectionFactory cf = new ActiveMQConnectionFactory(VM_BROKER_URL); - Connection conn = cf.createConnection(); - if (start) { - conn.start(); - } - return conn; - } + private Connection createConnection(final boolean start) throws JMSException { + ConnectionFactory cf = new ActiveMQConnectionFactory(VM_BROKER_URL); + Connection conn = cf.createConnection(); + if (start) { + conn.start(); + } + return conn; + } - @Test - public void testRemoveDestinationWithoutSubscriber() throws Exception { + @Test + public void testRemoveDestinationWithoutSubscriber() throws Exception { - ActiveMQConnection amqConnection = (ActiveMQConnection) createConnection(true); - DestinationSource destinationSource = amqConnection.getDestinationSource(); - Session session = amqConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic("TEST.FOO"); - MessageProducer producer = session.createProducer(topic); - MessageConsumer consumer = session.createConsumer(topic); + ActiveMQConnection amqConnection = (ActiveMQConnection) createConnection(true); + DestinationSource destinationSource = amqConnection.getDestinationSource(); + Session session = amqConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Topic topic = session.createTopic("TEST.FOO"); + MessageProducer producer = session.createProducer(topic); + MessageConsumer consumer = session.createConsumer(topic); - TextMessage msg = session.createTextMessage("Hellow World"); - producer.send(msg); - assertNotNull(consumer.receive(5000)); - Thread.sleep(1000); + TextMessage msg = session.createTextMessage("Hellow World"); + producer.send(msg); + assertNotNull(consumer.receive(5000)); + Thread.sleep(1000); - ActiveMQTopic amqTopic = (ActiveMQTopic) topic; - assertTrue(destinationSource.getTopics().contains(amqTopic)); + ActiveMQTopic amqTopic = (ActiveMQTopic) topic; + assertTrue(destinationSource.getTopics().contains(amqTopic)); - consumer.close(); - producer.close(); - session.close(); + consumer.close(); + producer.close(); + session.close(); - Thread.sleep(3000); - amqConnection.destroyDestination((ActiveMQDestination) topic); - Thread.sleep(3000); - assertFalse(destinationSource.getTopics().contains(amqTopic)); - } + Thread.sleep(3000); + amqConnection.destroyDestination((ActiveMQDestination) topic); + Thread.sleep(3000); + assertFalse(destinationSource.getTopics().contains(amqTopic)); + } - @Test - public void testRemoveDestinationWithSubscriber() throws Exception { - ActiveMQConnection amqConnection = (ActiveMQConnection) createConnection(true); - DestinationSource destinationSource = amqConnection.getDestinationSource(); + @Test + public void testRemoveDestinationWithSubscriber() throws Exception { + ActiveMQConnection amqConnection = (ActiveMQConnection) createConnection(true); + DestinationSource destinationSource = amqConnection.getDestinationSource(); - Session session = amqConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic("TEST.FOO"); - MessageProducer producer = session.createProducer(topic); - MessageConsumer consumer = session.createConsumer(topic); + Session session = amqConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Topic topic = session.createTopic("TEST.FOO"); + MessageProducer producer = session.createProducer(topic); + MessageConsumer consumer = session.createConsumer(topic); - TextMessage msg = session.createTextMessage("Hellow World"); - producer.send(msg); - assertNotNull(consumer.receive(5000)); - Thread.sleep(1000); + TextMessage msg = session.createTextMessage("Hellow World"); + producer.send(msg); + assertNotNull(consumer.receive(5000)); + Thread.sleep(1000); - ActiveMQTopic amqTopic = (ActiveMQTopic) topic; + ActiveMQTopic amqTopic = (ActiveMQTopic) topic; - assertTrue(destinationPresentInAdminView(broker, amqTopic)); - assertTrue(destinationSource.getTopics().contains(amqTopic)); + assertTrue(destinationPresentInAdminView(broker, amqTopic)); + assertTrue(destinationSource.getTopics().contains(amqTopic)); - // This line generates a broker error since the consumer is still active. - try { - amqConnection.destroyDestination((ActiveMQDestination) topic); - fail("expect exception on destroy if comsumer present"); - } catch (JMSException expected) { - assertTrue(expected.getMessage().indexOf(amqTopic.getTopicName()) != -1); - } + // This line generates a broker error since the consumer is still active. + try { + amqConnection.destroyDestination((ActiveMQDestination) topic); + fail("expect exception on destroy if comsumer present"); + } + catch (JMSException expected) { + assertTrue(expected.getMessage().indexOf(amqTopic.getTopicName()) != -1); + } - Thread.sleep(3000); + Thread.sleep(3000); - assertTrue(destinationSource.getTopics().contains(amqTopic)); - assertTrue(destinationPresentInAdminView(broker, amqTopic)); + assertTrue(destinationSource.getTopics().contains(amqTopic)); + assertTrue(destinationPresentInAdminView(broker, amqTopic)); - consumer.close(); - producer.close(); - session.close(); + consumer.close(); + producer.close(); + session.close(); - Thread.sleep(3000); + Thread.sleep(3000); - // The destination will not be removed with this call, but if you remove - // the call above that generates the error it will. - amqConnection.destroyDestination(amqTopic); - Thread.sleep(3000); - assertFalse(destinationSource.getTopics().contains(amqTopic)); - assertFalse(destinationPresentInAdminView(broker, amqTopic)); - } + // The destination will not be removed with this call, but if you remove + // the call above that generates the error it will. + amqConnection.destroyDestination(amqTopic); + Thread.sleep(3000); + assertFalse(destinationSource.getTopics().contains(amqTopic)); + assertFalse(destinationPresentInAdminView(broker, amqTopic)); + } - private boolean destinationPresentInAdminView(BrokerService broker2, ActiveMQTopic amqTopic) throws Exception { - boolean found = false; - for (ObjectName name : broker.getAdminView().getTopics()) { + private boolean destinationPresentInAdminView(BrokerService broker2, ActiveMQTopic amqTopic) throws Exception { + boolean found = false; + for (ObjectName name : broker.getAdminView().getTopics()) { - DestinationViewMBean proxy = (DestinationViewMBean) - broker.getManagementContext().newProxyInstance(name, DestinationViewMBean.class, true); + DestinationViewMBean proxy = (DestinationViewMBean) broker.getManagementContext().newProxyInstance(name, DestinationViewMBean.class, true); - if (proxy.getName().equals(amqTopic.getPhysicalName())) { - found = true; - break; - } - } - return found; - } + if (proxy.getName().equals(amqTopic.getPhysicalName())) { + found = true; + break; + } + } + return found; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/SpringTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/SpringTestSupport.java index f713120139..f8cc498192 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/SpringTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/SpringTestSupport.java @@ -27,39 +27,39 @@ import org.springframework.context.support.AbstractApplicationContext; /** * A useful base class for spring based unit test cases - * - * */ public abstract class SpringTestSupport extends TestCase { - protected AbstractApplicationContext context; + protected AbstractApplicationContext context; - @Override - protected void setUp() throws Exception { - context = createApplicationContext(); - } + @Override + protected void setUp() throws Exception { + context = createApplicationContext(); + } - protected abstract AbstractApplicationContext createApplicationContext();; + protected abstract AbstractApplicationContext createApplicationContext(); - @Override - protected void tearDown() throws Exception { - if (context != null) { - context.destroy(); - } - } + ; - protected Object getBean(String name) { - Object bean = context.getBean(name); - if (bean == null) { - fail("Should have found bean named '" + name + "' in the Spring ApplicationContext"); - } - return bean; - } + @Override + protected void tearDown() throws Exception { + if (context != null) { + context.destroy(); + } + } - protected void assertSetEquals(String description, Object[] expected, Set actual) { - Set expectedSet = new HashSet(); - expectedSet.addAll(Arrays.asList(expected)); - assertEquals(description, expectedSet, actual); - } + protected Object getBean(String name) { + Object bean = context.getBean(name); + if (bean == null) { + fail("Should have found bean named '" + name + "' in the Spring ApplicationContext"); + } + return bean; + } + + protected void assertSetEquals(String description, Object[] expected, Set actual) { + Set expectedSet = new HashSet(); + expectedSet.addAll(Arrays.asList(expected)); + assertEquals(description, expectedSet, actual); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/TestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/TestSupport.java index a762f89f6a..247047dcb4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/TestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/TestSupport.java @@ -41,188 +41,187 @@ import org.apache.activemq.store.memory.MemoryPersistenceAdapter; /** * Useful base class for unit test cases - * - * */ public abstract class TestSupport extends CombinationTestSupport { - protected ActiveMQConnectionFactory connectionFactory; - protected boolean topic = true; - public PersistenceAdapterChoice defaultPersistenceAdapter = PersistenceAdapterChoice.KahaDB; + protected ActiveMQConnectionFactory connectionFactory; + protected boolean topic = true; + public PersistenceAdapterChoice defaultPersistenceAdapter = PersistenceAdapterChoice.KahaDB; - protected ActiveMQMessage createMessage() { - return new ActiveMQMessage(); - } + protected ActiveMQMessage createMessage() { + return new ActiveMQMessage(); + } - protected Destination createDestination(String subject) { - if (topic) { - return new ActiveMQTopic(subject); - } else { - return new ActiveMQQueue(subject); - } - } + protected Destination createDestination(String subject) { + if (topic) { + return new ActiveMQTopic(subject); + } + else { + return new ActiveMQQueue(subject); + } + } - protected Destination createDestination() { - return createDestination(getDestinationString()); - } + protected Destination createDestination() { + return createDestination(getDestinationString()); + } - /** - * Returns the name of the destination used in this test case - */ - protected String getDestinationString() { - return getClass().getName() + "." + getName(true); - } + /** + * Returns the name of the destination used in this test case + */ + protected String getDestinationString() { + return getClass().getName() + "." + getName(true); + } - /** - * @param messsage - * @param firstSet - * @param secondSet - */ - protected void assertTextMessagesEqual(String messsage, Message[] firstSet, Message[] secondSet) - throws JMSException { - assertEquals("Message count does not match: " + messsage, firstSet.length, secondSet.length); - for (int i = 0; i < secondSet.length; i++) { - TextMessage m1 = (TextMessage)firstSet[i]; - TextMessage m2 = (TextMessage)secondSet[i]; - assertFalse("Message " + (i + 1) + " did not match : " + messsage + ": expected {" + m1 - + "}, but was {" + m2 + "}", m1 == null ^ m2 == null); - assertEquals("Message " + (i + 1) + " did not match: " + messsage + ": expected {" + m1 - + "}, but was {" + m2 + "}", m1.getText(), m2.getText()); - } - } + /** + * @param messsage + * @param firstSet + * @param secondSet + */ + protected void assertTextMessagesEqual(String messsage, + Message[] firstSet, + Message[] secondSet) throws JMSException { + assertEquals("Message count does not match: " + messsage, firstSet.length, secondSet.length); + for (int i = 0; i < secondSet.length; i++) { + TextMessage m1 = (TextMessage) firstSet[i]; + TextMessage m2 = (TextMessage) secondSet[i]; + assertFalse("Message " + (i + 1) + " did not match : " + messsage + ": expected {" + m1 + "}, but was {" + m2 + "}", m1 == null ^ m2 == null); + assertEquals("Message " + (i + 1) + " did not match: " + messsage + ": expected {" + m1 + "}, but was {" + m2 + "}", m1.getText(), m2.getText()); + } + } - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); + } - /** - * Factory method to create a new connection - */ - protected Connection createConnection() throws Exception { - return getConnectionFactory().createConnection(); - } + /** + * Factory method to create a new connection + */ + protected Connection createConnection() throws Exception { + return getConnectionFactory().createConnection(); + } - public ActiveMQConnectionFactory getConnectionFactory() throws Exception { - if (connectionFactory == null) { - connectionFactory = createConnectionFactory(); - assertTrue("Should have created a connection factory!", connectionFactory != null); - } - return connectionFactory; - } + public ActiveMQConnectionFactory getConnectionFactory() throws Exception { + if (connectionFactory == null) { + connectionFactory = createConnectionFactory(); + assertTrue("Should have created a connection factory!", connectionFactory != null); + } + return connectionFactory; + } - protected String getConsumerSubject() { - return getSubject(); - } + protected String getConsumerSubject() { + return getSubject(); + } - protected String getProducerSubject() { - return getSubject(); - } + protected String getProducerSubject() { + return getSubject(); + } - protected String getSubject() { - return getName(); - } + protected String getSubject() { + return getName(); + } - public static void recursiveDelete(File f) { - if (f.isDirectory()) { - File[] files = f.listFiles(); - for (int i = 0; i < files.length; i++) { - recursiveDelete(files[i]); - } - } - f.delete(); - } + public static void recursiveDelete(File f) { + if (f.isDirectory()) { + File[] files = f.listFiles(); + for (int i = 0; i < files.length; i++) { + recursiveDelete(files[i]); + } + } + f.delete(); + } - public static void removeMessageStore() { - if (System.getProperty("activemq.store.dir") != null) { - recursiveDelete(new File(System.getProperty("activemq.store.dir"))); - } - if (System.getProperty("derby.system.home") != null) { - recursiveDelete(new File(System.getProperty("derby.system.home"))); - } - } + public static void removeMessageStore() { + if (System.getProperty("activemq.store.dir") != null) { + recursiveDelete(new File(System.getProperty("activemq.store.dir"))); + } + if (System.getProperty("derby.system.home") != null) { + recursiveDelete(new File(System.getProperty("derby.system.home"))); + } + } - public static DestinationStatistics getDestinationStatistics(BrokerService broker, ActiveMQDestination destination) { - DestinationStatistics result = null; - org.apache.activemq.broker.region.Destination dest = getDestination(broker, destination); - if (dest != null) { - result = dest.getDestinationStatistics(); - } - return result; - } + public static DestinationStatistics getDestinationStatistics(BrokerService broker, ActiveMQDestination destination) { + DestinationStatistics result = null; + org.apache.activemq.broker.region.Destination dest = getDestination(broker, destination); + if (dest != null) { + result = dest.getDestinationStatistics(); + } + return result; + } - public static org.apache.activemq.broker.region.Destination getDestination(BrokerService target, ActiveMQDestination destination) { - org.apache.activemq.broker.region.Destination result = null; - for (org.apache.activemq.broker.region.Destination dest : getDestinationMap(target, destination).values()) { - if (dest.getName().equals(destination.getPhysicalName())) { - result = dest; - break; - } - } - return result; - } + public static org.apache.activemq.broker.region.Destination getDestination(BrokerService target, + ActiveMQDestination destination) { + org.apache.activemq.broker.region.Destination result = null; + for (org.apache.activemq.broker.region.Destination dest : getDestinationMap(target, destination).values()) { + if (dest.getName().equals(destination.getPhysicalName())) { + result = dest; + break; + } + } + return result; + } - private static Map getDestinationMap(BrokerService target, - ActiveMQDestination destination) { - RegionBroker regionBroker = (RegionBroker) target.getRegionBroker(); - if (destination.isTemporary()) { - return destination.isQueue() ? regionBroker.getTempQueueRegion().getDestinationMap() : - regionBroker.getTempTopicRegion().getDestinationMap(); - } - return destination.isQueue() ? - regionBroker.getQueueRegion().getDestinationMap() : - regionBroker.getTopicRegion().getDestinationMap(); - } + private static Map getDestinationMap( + BrokerService target, + ActiveMQDestination destination) { + RegionBroker regionBroker = (RegionBroker) target.getRegionBroker(); + if (destination.isTemporary()) { + return destination.isQueue() ? regionBroker.getTempQueueRegion().getDestinationMap() : regionBroker.getTempTopicRegion().getDestinationMap(); + } + return destination.isQueue() ? regionBroker.getQueueRegion().getDestinationMap() : regionBroker.getTopicRegion().getDestinationMap(); + } - public static enum PersistenceAdapterChoice {LevelDB, KahaDB, AMQ, JDBC, MEM }; + public static enum PersistenceAdapterChoice {LevelDB, KahaDB, AMQ, JDBC, MEM} - public PersistenceAdapter setDefaultPersistenceAdapter(BrokerService broker) throws IOException { - return setPersistenceAdapter(broker, defaultPersistenceAdapter); - } + ; - public static PersistenceAdapter setPersistenceAdapter(BrokerService broker, PersistenceAdapterChoice choice) throws IOException { - PersistenceAdapter adapter = null; - switch (choice) { - case JDBC: + public PersistenceAdapter setDefaultPersistenceAdapter(BrokerService broker) throws IOException { + return setPersistenceAdapter(broker, defaultPersistenceAdapter); + } + + public static PersistenceAdapter setPersistenceAdapter(BrokerService broker, + PersistenceAdapterChoice choice) throws IOException { + PersistenceAdapter adapter = null; + switch (choice) { + case JDBC: JDBCPersistenceAdapter jdbcPersistenceAdapter = new JDBCPersistenceAdapter(); jdbcPersistenceAdapter.setUseLock(false); // rollback (at shutdown) on derby can take a long time with file io etc adapter = jdbcPersistenceAdapter; break; - case KahaDB: + case KahaDB: adapter = new KahaDBPersistenceAdapter(); break; - case LevelDB: + case LevelDB: adapter = new LevelDBPersistenceAdapter(); break; - case MEM: + case MEM: adapter = new MemoryPersistenceAdapter(); break; - } - broker.setPersistenceAdapter(adapter); - adapter.setDirectory(new File(broker.getBrokerDataDirectory(), choice.name())); - return adapter; - } + } + broker.setPersistenceAdapter(adapter); + adapter.setDirectory(new File(broker.getBrokerDataDirectory(), choice.name())); + return adapter; + } - public void stopBrokerWithStoreFailure(BrokerService broker, PersistenceAdapterChoice choice) throws Exception { - switch (choice) { - case KahaDB: - KahaDBPersistenceAdapter kahaDBPersistenceAdapter = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); + public void stopBrokerWithStoreFailure(BrokerService broker, PersistenceAdapterChoice choice) throws Exception { + switch (choice) { + case KahaDB: + KahaDBPersistenceAdapter kahaDBPersistenceAdapter = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); - // have the broker stop with an IOException on next checkpoint so it has a pending local transaction to recover - kahaDBPersistenceAdapter.getStore().getJournal().close(); - break; - default: - // just stop normally by default - broker.stop(); - } - broker.waitUntilStopped(); - } + // have the broker stop with an IOException on next checkpoint so it has a pending local transaction to recover + kahaDBPersistenceAdapter.getStore().getJournal().close(); + break; + default: + // just stop normally by default + broker.stop(); + } + broker.waitUntilStopped(); + } - - /** - * Test if base directory contains spaces - */ - protected void assertBaseDirectoryContainsSpaces() { - assertFalse("Base directory cannot contain spaces.", new File(System.getProperty("basedir", ".")).getAbsoluteFile().toString().contains(" ")); - } + /** + * Test if base directory contains spaces + */ + protected void assertBaseDirectoryContainsSpaces() { + assertFalse("Base directory cannot contain spaces.", new File(System.getProperty("basedir", ".")).getAbsoluteFile().toString().contains(" ")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/TimeStampTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/TimeStampTest.java index 448bd3cba8..87c5fc963d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/TimeStampTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/TimeStampTest.java @@ -25,6 +25,7 @@ import javax.jms.MessageProducer; import javax.jms.Session; import junit.framework.TestCase; + import org.apache.activemq.broker.BrokerPlugin; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.TransportConnector; @@ -32,66 +33,64 @@ import org.apache.activemq.broker.util.UDPTraceBrokerPlugin; import org.apache.activemq.broker.view.ConnectionDotFilePlugin; public class TimeStampTest extends TestCase { - public void test() throws Exception { - BrokerService broker = new BrokerService(); - broker.setPersistent(false); - broker.setUseJmx(true); - broker.setPlugins(new BrokerPlugin[] {new ConnectionDotFilePlugin(), new UDPTraceBrokerPlugin()}); - TransportConnector tcpConnector = broker.addConnector("tcp://localhost:0"); - broker.addConnector("stomp://localhost:0"); - broker.start(); - // Create a ConnectionFactory - ActiveMQConnectionFactory connectionFactory = - new ActiveMQConnectionFactory(tcpConnector.getConnectUri()); + public void test() throws Exception { + BrokerService broker = new BrokerService(); + broker.setPersistent(false); + broker.setUseJmx(true); + broker.setPlugins(new BrokerPlugin[]{new ConnectionDotFilePlugin(), new UDPTraceBrokerPlugin()}); + TransportConnector tcpConnector = broker.addConnector("tcp://localhost:0"); + broker.addConnector("stomp://localhost:0"); + broker.start(); - // Create a Connection - Connection connection = connectionFactory.createConnection(); - connection.start(); + // Create a ConnectionFactory + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(tcpConnector.getConnectUri()); - // Create a Session - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + // Create a Connection + Connection connection = connectionFactory.createConnection(); + connection.start(); - // Create the destination Queue - Destination destination = session.createQueue("TEST.FOO"); + // Create a Session + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - // Create a MessageProducer from the Session to the Topic or Queue - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + // Create the destination Queue + Destination destination = session.createQueue("TEST.FOO"); - // Create a messages - Message sentMessage = session.createMessage(); + // Create a MessageProducer from the Session to the Topic or Queue + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - // Tell the producer to send the message - long beforeSend = System.currentTimeMillis(); - producer.send(sentMessage); - long afterSend = System.currentTimeMillis(); + // Create a messages + Message sentMessage = session.createMessage(); - // assert message timestamp is in window - assertTrue(beforeSend <= sentMessage.getJMSTimestamp() && sentMessage.getJMSTimestamp() <= afterSend); + // Tell the producer to send the message + long beforeSend = System.currentTimeMillis(); + producer.send(sentMessage); + long afterSend = System.currentTimeMillis(); - // Create a MessageConsumer from the Session to the Topic or Queue - MessageConsumer consumer = session.createConsumer(destination); + // assert message timestamp is in window + assertTrue(beforeSend <= sentMessage.getJMSTimestamp() && sentMessage.getJMSTimestamp() <= afterSend); - // Wait for a message - Message receivedMessage = consumer.receive(1000); + // Create a MessageConsumer from the Session to the Topic or Queue + MessageConsumer consumer = session.createConsumer(destination); - // assert we got the same message ID we sent - assertEquals(sentMessage.getJMSMessageID(), receivedMessage.getJMSMessageID()); + // Wait for a message + Message receivedMessage = consumer.receive(1000); - // assert message timestamp is in window - assertTrue("JMS Message Timestamp should be set during the send method: \n" + " beforeSend = " + beforeSend + "\n" + " getJMSTimestamp = " - + receivedMessage.getJMSTimestamp() + "\n" + " afterSend = " + afterSend + "\n", beforeSend <= receivedMessage.getJMSTimestamp() - && receivedMessage.getJMSTimestamp() <= afterSend); + // assert we got the same message ID we sent + assertEquals(sentMessage.getJMSMessageID(), receivedMessage.getJMSMessageID()); - // assert message timestamp is unchanged - assertEquals("JMS Message Timestamp of received message should be the same as the sent message\n ", sentMessage.getJMSTimestamp(), receivedMessage.getJMSTimestamp()); + // assert message timestamp is in window + assertTrue("JMS Message Timestamp should be set during the send method: \n" + " beforeSend = " + beforeSend + "\n" + " getJMSTimestamp = " + receivedMessage.getJMSTimestamp() + "\n" + " afterSend = " + afterSend + "\n", beforeSend <= receivedMessage.getJMSTimestamp() && receivedMessage.getJMSTimestamp() <= afterSend); - // Clean up - producer.close(); - consumer.close(); - session.close(); - connection.close(); - broker.stop(); - } + // assert message timestamp is unchanged + assertEquals("JMS Message Timestamp of received message should be the same as the sent message\n ", sentMessage.getJMSTimestamp(), receivedMessage.getJMSTimestamp()); + + // Clean up + producer.close(); + consumer.close(); + session.close(); + connection.close(); + broker.stop(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/TransactionContextTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/TransactionContextTest.java index 5e45d522e8..8d239e7c89 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/TransactionContextTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/TransactionContextTest.java @@ -29,112 +29,113 @@ import org.junit.Before; import org.junit.Test; public class TransactionContextTest { - - TransactionContext underTest; - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - ActiveMQConnection connection; - - - @Before - public void setup() throws Exception { - connection = factory.createActiveMQConnection(); - underTest = new TransactionContext(connection); - } - - @After - public void tearDown() throws Exception { - connection.close(); - } - - @Test - public void testSyncBeforeEndCalledOnceOnRollback() throws Exception { - final AtomicInteger beforeEndCountA = new AtomicInteger(0); - final AtomicInteger beforeEndCountB = new AtomicInteger(0); - final AtomicInteger rollbackCountA = new AtomicInteger(0); - final AtomicInteger rollbackCountB = new AtomicInteger(0); - underTest.addSynchronization(new Synchronization() { - @Override - public void beforeEnd() throws Exception { - if (beforeEndCountA.getAndIncrement() == 0) { - throw new TransactionRolledBackException("force rollback"); - } - } - @Override - public void afterCommit() throws Exception { - fail("exepcted rollback exception"); - } + TransactionContext underTest; + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + ActiveMQConnection connection; - @Override - public void afterRollback() throws Exception { - rollbackCountA.incrementAndGet(); - } - - }); - - underTest.addSynchronization(new Synchronization() { - @Override - public void beforeEnd() throws Exception { - beforeEndCountB.getAndIncrement(); - } - - @Override - public void afterCommit() throws Exception { - fail("exepcted rollback exception"); - } + @Before + public void setup() throws Exception { + connection = factory.createActiveMQConnection(); + underTest = new TransactionContext(connection); + } - @Override - public void afterRollback() throws Exception { - rollbackCountB.incrementAndGet(); - } + @After + public void tearDown() throws Exception { + connection.close(); + } - }); - - - try { - underTest.commit(); + @Test + public void testSyncBeforeEndCalledOnceOnRollback() throws Exception { + final AtomicInteger beforeEndCountA = new AtomicInteger(0); + final AtomicInteger beforeEndCountB = new AtomicInteger(0); + final AtomicInteger rollbackCountA = new AtomicInteger(0); + final AtomicInteger rollbackCountB = new AtomicInteger(0); + underTest.addSynchronization(new Synchronization() { + @Override + public void beforeEnd() throws Exception { + if (beforeEndCountA.getAndIncrement() == 0) { + throw new TransactionRolledBackException("force rollback"); + } + } + + @Override + public void afterCommit() throws Exception { fail("exepcted rollback exception"); - } catch (TransactionRolledBackException expected) { - } - - assertEquals("beforeEnd A called once", 1, beforeEndCountA.get()); - assertEquals("beforeEnd B called once", 1, beforeEndCountA.get()); - assertEquals("rollbackCount B 0", 1, rollbackCountB.get()); - assertEquals("rollbackCount A B", rollbackCountA.get(), rollbackCountB.get()); - } - - @Test - public void testSyncIndexCleared() throws Exception { - final AtomicInteger beforeEndCountA = new AtomicInteger(0); - final AtomicInteger rollbackCountA = new AtomicInteger(0); - Synchronization sync = new Synchronization() { - @Override - public void beforeEnd() throws Exception { - beforeEndCountA.getAndIncrement(); - } - @Override - public void afterCommit() throws Exception { - fail("exepcted rollback exception"); - } - @Override - public void afterRollback() throws Exception { - rollbackCountA.incrementAndGet(); - } - }; - - underTest.begin(); - underTest.addSynchronization(sync); - underTest.rollback(); - - assertEquals("beforeEnd", 1, beforeEndCountA.get()); - assertEquals("rollback", 1, rollbackCountA.get()); - - // do it again - underTest.begin(); - underTest.addSynchronization(sync); - underTest.rollback(); - - assertEquals("beforeEnd", 2, beforeEndCountA.get()); - assertEquals("rollback", 2, rollbackCountA.get()); - } + } + + @Override + public void afterRollback() throws Exception { + rollbackCountA.incrementAndGet(); + } + + }); + + underTest.addSynchronization(new Synchronization() { + @Override + public void beforeEnd() throws Exception { + beforeEndCountB.getAndIncrement(); + } + + @Override + public void afterCommit() throws Exception { + fail("exepcted rollback exception"); + } + + @Override + public void afterRollback() throws Exception { + rollbackCountB.incrementAndGet(); + } + + }); + + try { + underTest.commit(); + fail("exepcted rollback exception"); + } + catch (TransactionRolledBackException expected) { + } + + assertEquals("beforeEnd A called once", 1, beforeEndCountA.get()); + assertEquals("beforeEnd B called once", 1, beforeEndCountA.get()); + assertEquals("rollbackCount B 0", 1, rollbackCountB.get()); + assertEquals("rollbackCount A B", rollbackCountA.get(), rollbackCountB.get()); + } + + @Test + public void testSyncIndexCleared() throws Exception { + final AtomicInteger beforeEndCountA = new AtomicInteger(0); + final AtomicInteger rollbackCountA = new AtomicInteger(0); + Synchronization sync = new Synchronization() { + @Override + public void beforeEnd() throws Exception { + beforeEndCountA.getAndIncrement(); + } + + @Override + public void afterCommit() throws Exception { + fail("exepcted rollback exception"); + } + + @Override + public void afterRollback() throws Exception { + rollbackCountA.incrementAndGet(); + } + }; + + underTest.begin(); + underTest.addSynchronization(sync); + underTest.rollback(); + + assertEquals("beforeEnd", 1, beforeEndCountA.get()); + assertEquals("rollback", 1, rollbackCountA.get()); + + // do it again + underTest.begin(); + underTest.addSynchronization(sync); + underTest.rollback(); + + assertEquals("beforeEnd", 2, beforeEndCountA.get()); + assertEquals("rollback", 2, rollbackCountA.get()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ZeroPrefetchConsumerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ZeroPrefetchConsumerTest.java index d4cecaba06..d207da736b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ZeroPrefetchConsumerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ZeroPrefetchConsumerTest.java @@ -43,362 +43,362 @@ import org.slf4j.LoggerFactory; */ public class ZeroPrefetchConsumerTest extends EmbeddedBrokerTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(ZeroPrefetchConsumerTest.class); + private static final Logger LOG = LoggerFactory.getLogger(ZeroPrefetchConsumerTest.class); - protected Connection connection; - protected Queue queue; - protected Queue brokerZeroQueue = new ActiveMQQueue("brokerZeroConfig"); + protected Connection connection; + protected Queue queue; + protected Queue brokerZeroQueue = new ActiveMQQueue("brokerZeroConfig"); - public void testCannotUseMessageListener() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(queue); + public void testCannotUseMessageListener() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(queue); - MessageListener listener = new SpringConsumer(); - try { - consumer.setMessageListener(listener); - fail("Should have thrown JMSException as we cannot use MessageListener with zero prefetch"); - } catch (JMSException e) { - LOG.info("Received expected exception : " + e); - } - } + MessageListener listener = new SpringConsumer(); + try { + consumer.setMessageListener(listener); + fail("Should have thrown JMSException as we cannot use MessageListener with zero prefetch"); + } + catch (JMSException e) { + LOG.info("Received expected exception : " + e); + } + } - public void testPullConsumerWorks() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + public void testPullConsumerWorks() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(queue); - producer.send(session.createTextMessage("Hello World!")); + MessageProducer producer = session.createProducer(queue); + producer.send(session.createTextMessage("Hello World!")); - // now lets receive it - MessageConsumer consumer = session.createConsumer(queue); - Message answer = consumer.receive(5000); - assertNotNull("Should have received a message!", answer); - // check if method will return at all and will return a null - answer = consumer.receive(1); - assertNull("Should have not received a message!", answer); - answer = consumer.receiveNoWait(); - assertNull("Should have not received a message!", answer); - } + // now lets receive it + MessageConsumer consumer = session.createConsumer(queue); + Message answer = consumer.receive(5000); + assertNotNull("Should have received a message!", answer); + // check if method will return at all and will return a null + answer = consumer.receive(1); + assertNull("Should have not received a message!", answer); + answer = consumer.receiveNoWait(); + assertNull("Should have not received a message!", answer); + } - public void testIdleConsumer() throws Exception { - doTestIdleConsumer(false); - } + public void testIdleConsumer() throws Exception { + doTestIdleConsumer(false); + } - public void testIdleConsumerTranscated() throws Exception { - doTestIdleConsumer(true); - } + public void testIdleConsumerTranscated() throws Exception { + doTestIdleConsumer(true); + } - private void doTestIdleConsumer(boolean transacted) throws Exception { - Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE); + private void doTestIdleConsumer(boolean transacted) throws Exception { + Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(queue); - producer.send(session.createTextMessage("Msg1")); - producer.send(session.createTextMessage("Msg2")); - if (transacted) { - session.commit(); - } - // now lets receive it - MessageConsumer consumer = session.createConsumer(queue); + MessageProducer producer = session.createProducer(queue); + producer.send(session.createTextMessage("Msg1")); + producer.send(session.createTextMessage("Msg2")); + if (transacted) { + session.commit(); + } + // now lets receive it + MessageConsumer consumer = session.createConsumer(queue); - session.createConsumer(queue); - TextMessage answer = (TextMessage)consumer.receive(5000); - assertEquals("Should have received a message!", answer.getText(), "Msg1"); - if (transacted) { - session.commit(); - } - // this call would return null if prefetchSize > 0 - answer = (TextMessage)consumer.receive(5000); - assertEquals("Should have received a message!", answer.getText(), "Msg2"); - if (transacted) { - session.commit(); - } - answer = (TextMessage)consumer.receiveNoWait(); - assertNull("Should have not received a message!", answer); - } + session.createConsumer(queue); + TextMessage answer = (TextMessage) consumer.receive(5000); + assertEquals("Should have received a message!", answer.getText(), "Msg1"); + if (transacted) { + session.commit(); + } + // this call would return null if prefetchSize > 0 + answer = (TextMessage) consumer.receive(5000); + assertEquals("Should have received a message!", answer.getText(), "Msg2"); + if (transacted) { + session.commit(); + } + answer = (TextMessage) consumer.receiveNoWait(); + assertNull("Should have not received a message!", answer); + } - public void testRecvRecvCommit() throws Exception { - doTestRecvRecvCommit(false); - } + public void testRecvRecvCommit() throws Exception { + doTestRecvRecvCommit(false); + } - public void testRecvRecvCommitTranscated() throws Exception { - doTestRecvRecvCommit(true); - } + public void testRecvRecvCommitTranscated() throws Exception { + doTestRecvRecvCommit(true); + } - private void doTestRecvRecvCommit(boolean transacted) throws Exception { - Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE); + private void doTestRecvRecvCommit(boolean transacted) throws Exception { + Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(queue); - producer.send(session.createTextMessage("Msg1")); - producer.send(session.createTextMessage("Msg2")); - if (transacted) { - session.commit(); - } - // now lets receive it - MessageConsumer consumer = session.createConsumer(queue); - TextMessage answer = (TextMessage)consumer.receiveNoWait(); - assertEquals("Should have received a message!", answer.getText(), "Msg1"); - answer = (TextMessage)consumer.receiveNoWait(); - assertEquals("Should have received a message!", answer.getText(), "Msg2"); - if (transacted) { - session.commit(); - } - answer = (TextMessage)consumer.receiveNoWait(); - assertNull("Should have not received a message!", answer); - } + MessageProducer producer = session.createProducer(queue); + producer.send(session.createTextMessage("Msg1")); + producer.send(session.createTextMessage("Msg2")); + if (transacted) { + session.commit(); + } + // now lets receive it + MessageConsumer consumer = session.createConsumer(queue); + TextMessage answer = (TextMessage) consumer.receiveNoWait(); + assertEquals("Should have received a message!", answer.getText(), "Msg1"); + answer = (TextMessage) consumer.receiveNoWait(); + assertEquals("Should have received a message!", answer.getText(), "Msg2"); + if (transacted) { + session.commit(); + } + answer = (TextMessage) consumer.receiveNoWait(); + assertNull("Should have not received a message!", answer); + } - public void testTwoConsumers() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + public void testTwoConsumers() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(queue); - producer.send(session.createTextMessage("Msg1")); - producer.send(session.createTextMessage("Msg2")); + MessageProducer producer = session.createProducer(queue); + producer.send(session.createTextMessage("Msg1")); + producer.send(session.createTextMessage("Msg2")); - // now lets receive it - MessageConsumer consumer1 = session.createConsumer(queue); - MessageConsumer consumer2 = session.createConsumer(queue); - TextMessage answer = (TextMessage)consumer1.receiveNoWait(); - assertEquals("Should have received a message!", answer.getText(), "Msg1"); - answer = (TextMessage)consumer2.receiveNoWait(); - assertEquals("Should have received a message!", answer.getText(), "Msg2"); + // now lets receive it + MessageConsumer consumer1 = session.createConsumer(queue); + MessageConsumer consumer2 = session.createConsumer(queue); + TextMessage answer = (TextMessage) consumer1.receiveNoWait(); + assertEquals("Should have received a message!", answer.getText(), "Msg1"); + answer = (TextMessage) consumer2.receiveNoWait(); + assertEquals("Should have received a message!", answer.getText(), "Msg2"); - answer = (TextMessage)consumer2.receiveNoWait(); - assertNull("Should have not received a message!", answer); - } + answer = (TextMessage) consumer2.receiveNoWait(); + assertNull("Should have not received a message!", answer); + } - // https://issues.apache.org/activemq/browse/AMQ-2567 - public void testManyMessageConsumer() throws Exception { - doTestManyMessageConsumer(true); - } + // https://issues.apache.org/activemq/browse/AMQ-2567 + public void testManyMessageConsumer() throws Exception { + doTestManyMessageConsumer(true); + } - public void testManyMessageConsumerNoTransaction() throws Exception { - doTestManyMessageConsumer(false); - } + public void testManyMessageConsumerNoTransaction() throws Exception { + doTestManyMessageConsumer(false); + } - private void doTestManyMessageConsumer(boolean transacted) throws Exception { - Session session = connection.createSession(transacted, transacted ? Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE); + private void doTestManyMessageConsumer(boolean transacted) throws Exception { + Session session = connection.createSession(transacted, transacted ? Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(queue); - producer.send(session.createTextMessage("Msg1")); - producer.send(session.createTextMessage("Msg2")); - producer.send(session.createTextMessage("Msg3")); - producer.send(session.createTextMessage("Msg4")); - producer.send(session.createTextMessage("Msg5")); - producer.send(session.createTextMessage("Msg6")); - producer.send(session.createTextMessage("Msg7")); - producer.send(session.createTextMessage("Msg8")); - if (transacted) { - session.commit(); - } - // now lets receive it - MessageConsumer consumer = session.createConsumer(queue); + MessageProducer producer = session.createProducer(queue); + producer.send(session.createTextMessage("Msg1")); + producer.send(session.createTextMessage("Msg2")); + producer.send(session.createTextMessage("Msg3")); + producer.send(session.createTextMessage("Msg4")); + producer.send(session.createTextMessage("Msg5")); + producer.send(session.createTextMessage("Msg6")); + producer.send(session.createTextMessage("Msg7")); + producer.send(session.createTextMessage("Msg8")); + if (transacted) { + session.commit(); + } + // now lets receive it + MessageConsumer consumer = session.createConsumer(queue); - MessageConsumer consumer2 = session.createConsumer(queue); - TextMessage answer = (TextMessage)consumer.receive(5000); - assertEquals("Should have received a message!", answer.getText(), "Msg1"); - if (transacted) { - session.commit(); - } - answer = (TextMessage)consumer.receive(5000); - assertEquals("Should have received a message!", answer.getText(), "Msg2"); - if (transacted) { - session.commit(); - } - answer = (TextMessage)consumer.receive(5000); - assertEquals("Should have received a message!", answer.getText(), "Msg3"); - if (transacted) { - session.commit(); - } - // this call would return null if prefetchSize > 0 - answer = (TextMessage)consumer.receive(5000); - assertEquals("Should have received a message!", answer.getText(), "Msg4"); - if (transacted) { - session.commit(); - } - // Now using other consumer - // this call should return the next message (Msg5) still left on the queue - answer = (TextMessage)consumer2.receive(5000); - assertEquals("Should have received a message!", answer.getText(), "Msg5"); - if (transacted) { - session.commit(); - } - // Now using other consumer - // this call should return the next message still left on the queue - answer = (TextMessage)consumer.receive(5000); - assertEquals("Should have received a message!", answer.getText(), "Msg6"); - // read one more message without commit - // this call should return the next message still left on the queue - answer = (TextMessage)consumer.receive(5000); - assertEquals("Should have received a message!", answer.getText(), "Msg7"); - if (transacted) { - session.commit(); - } - // Now using other consumer - // this call should return the next message (Msg5) still left on the queue - answer = (TextMessage)consumer2.receive(5000); - assertEquals("Should have received a message!", answer.getText(), "Msg8"); - if (transacted) { - session.commit(); - } - answer = (TextMessage)consumer.receiveNoWait(); - assertNull("Should have not received a message!", answer); - } + MessageConsumer consumer2 = session.createConsumer(queue); + TextMessage answer = (TextMessage) consumer.receive(5000); + assertEquals("Should have received a message!", answer.getText(), "Msg1"); + if (transacted) { + session.commit(); + } + answer = (TextMessage) consumer.receive(5000); + assertEquals("Should have received a message!", answer.getText(), "Msg2"); + if (transacted) { + session.commit(); + } + answer = (TextMessage) consumer.receive(5000); + assertEquals("Should have received a message!", answer.getText(), "Msg3"); + if (transacted) { + session.commit(); + } + // this call would return null if prefetchSize > 0 + answer = (TextMessage) consumer.receive(5000); + assertEquals("Should have received a message!", answer.getText(), "Msg4"); + if (transacted) { + session.commit(); + } + // Now using other consumer + // this call should return the next message (Msg5) still left on the queue + answer = (TextMessage) consumer2.receive(5000); + assertEquals("Should have received a message!", answer.getText(), "Msg5"); + if (transacted) { + session.commit(); + } + // Now using other consumer + // this call should return the next message still left on the queue + answer = (TextMessage) consumer.receive(5000); + assertEquals("Should have received a message!", answer.getText(), "Msg6"); + // read one more message without commit + // this call should return the next message still left on the queue + answer = (TextMessage) consumer.receive(5000); + assertEquals("Should have received a message!", answer.getText(), "Msg7"); + if (transacted) { + session.commit(); + } + // Now using other consumer + // this call should return the next message (Msg5) still left on the queue + answer = (TextMessage) consumer2.receive(5000); + assertEquals("Should have received a message!", answer.getText(), "Msg8"); + if (transacted) { + session.commit(); + } + answer = (TextMessage) consumer.receiveNoWait(); + assertNull("Should have not received a message!", answer); + } - public void testManyMessageConsumerWithSend() throws Exception { - doTestManyMessageConsumerWithSend(true); - } + public void testManyMessageConsumerWithSend() throws Exception { + doTestManyMessageConsumerWithSend(true); + } - public void testManyMessageConsumerWithTxSendPrioritySupport() throws Exception { - ((ActiveMQConnection)connection).setMessagePrioritySupported(true); - doTestManyMessageConsumerWithSend(true); - } + public void testManyMessageConsumerWithTxSendPrioritySupport() throws Exception { + ((ActiveMQConnection) connection).setMessagePrioritySupported(true); + doTestManyMessageConsumerWithSend(true); + } - public void testManyMessageConsumerWithSendNoTransaction() throws Exception { - doTestManyMessageConsumerWithSend(false); - } + public void testManyMessageConsumerWithSendNoTransaction() throws Exception { + doTestManyMessageConsumerWithSend(false); + } - private void doTestManyMessageConsumerWithSend(boolean transacted) throws Exception { - Session session = connection.createSession(transacted, transacted ? Session.SESSION_TRANSACTED :Session.AUTO_ACKNOWLEDGE); + private void doTestManyMessageConsumerWithSend(boolean transacted) throws Exception { + Session session = connection.createSession(transacted, transacted ? Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(queue); - producer.send(session.createTextMessage("Msg1")); - producer.send(session.createTextMessage("Msg2")); - producer.send(session.createTextMessage("Msg3")); - producer.send(session.createTextMessage("Msg4")); - producer.send(session.createTextMessage("Msg5")); - producer.send(session.createTextMessage("Msg6")); - producer.send(session.createTextMessage("Msg7")); - producer.send(session.createTextMessage("Msg8")); - if (transacted) { - session.commit(); - } - // now lets receive it - MessageConsumer consumer = session.createConsumer(queue); + MessageProducer producer = session.createProducer(queue); + producer.send(session.createTextMessage("Msg1")); + producer.send(session.createTextMessage("Msg2")); + producer.send(session.createTextMessage("Msg3")); + producer.send(session.createTextMessage("Msg4")); + producer.send(session.createTextMessage("Msg5")); + producer.send(session.createTextMessage("Msg6")); + producer.send(session.createTextMessage("Msg7")); + producer.send(session.createTextMessage("Msg8")); + if (transacted) { + session.commit(); + } + // now lets receive it + MessageConsumer consumer = session.createConsumer(queue); - MessageConsumer consumer2 = session.createConsumer(queue); - TextMessage answer = (TextMessage)consumer.receive(5000); - assertEquals("Should have received a message!", answer.getText(), "Msg1"); - if (transacted) { - session.commit(); - } - answer = (TextMessage)consumer.receive(5000); - assertEquals("Should have received a message!", answer.getText(), "Msg2"); - if (transacted) { - session.commit(); - } - answer = (TextMessage)consumer.receive(5000); - assertEquals("Should have received a message!", answer.getText(), "Msg3"); - if (transacted) { - session.commit(); - } - // Now using other consumer take 2 - answer = (TextMessage)consumer2.receive(5000); - assertEquals("Should have received a message!", answer.getText(), "Msg4"); - answer = (TextMessage)consumer2.receive(5000); - assertEquals("Should have received a message!", answer.getText(), "Msg5"); + MessageConsumer consumer2 = session.createConsumer(queue); + TextMessage answer = (TextMessage) consumer.receive(5000); + assertEquals("Should have received a message!", answer.getText(), "Msg1"); + if (transacted) { + session.commit(); + } + answer = (TextMessage) consumer.receive(5000); + assertEquals("Should have received a message!", answer.getText(), "Msg2"); + if (transacted) { + session.commit(); + } + answer = (TextMessage) consumer.receive(5000); + assertEquals("Should have received a message!", answer.getText(), "Msg3"); + if (transacted) { + session.commit(); + } + // Now using other consumer take 2 + answer = (TextMessage) consumer2.receive(5000); + assertEquals("Should have received a message!", answer.getText(), "Msg4"); + answer = (TextMessage) consumer2.receive(5000); + assertEquals("Should have received a message!", answer.getText(), "Msg5"); - // ensure prefetch extension ok by sending another that could get dispatched - producer.send(session.createTextMessage("Msg9")); - if (transacted) { - session.commit(); - } + // ensure prefetch extension ok by sending another that could get dispatched + producer.send(session.createTextMessage("Msg9")); + if (transacted) { + session.commit(); + } - answer = (TextMessage)consumer.receive(5000); - assertEquals("Should have received a message!", answer.getText(), "Msg6"); - // read one more message without commit - // and using other consumer - answer = (TextMessage)consumer2.receive(5000); - assertEquals("Should have received a message!", answer.getText(), "Msg7"); - if (transacted) { - session.commit(); - } + answer = (TextMessage) consumer.receive(5000); + assertEquals("Should have received a message!", answer.getText(), "Msg6"); + // read one more message without commit + // and using other consumer + answer = (TextMessage) consumer2.receive(5000); + assertEquals("Should have received a message!", answer.getText(), "Msg7"); + if (transacted) { + session.commit(); + } - answer = (TextMessage)consumer2.receive(5000); - assertEquals("Should have received a message!", answer.getText(), "Msg8"); - if (transacted) { - session.commit(); - } + answer = (TextMessage) consumer2.receive(5000); + assertEquals("Should have received a message!", answer.getText(), "Msg8"); + if (transacted) { + session.commit(); + } - answer = (TextMessage)consumer.receive(5000); - assertEquals("Should have received a message!", answer.getText(), "Msg9"); - if (transacted) { - session.commit(); - } - answer = (TextMessage)consumer.receiveNoWait(); - assertNull("Should have not received a message!", answer); - } + answer = (TextMessage) consumer.receive(5000); + assertEquals("Should have received a message!", answer.getText(), "Msg9"); + if (transacted) { + session.commit(); + } + answer = (TextMessage) consumer.receiveNoWait(); + assertNull("Should have not received a message!", answer); + } - // https://issues.apache.org/jira/browse/AMQ-4224 - public void testBrokerZeroPrefetchConfig() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + // https://issues.apache.org/jira/browse/AMQ-4224 + public void testBrokerZeroPrefetchConfig() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(brokerZeroQueue); - producer.send(session.createTextMessage("Msg1")); - // now lets receive it - MessageConsumer consumer = session.createConsumer(brokerZeroQueue); + MessageProducer producer = session.createProducer(brokerZeroQueue); + producer.send(session.createTextMessage("Msg1")); + // now lets receive it + MessageConsumer consumer = session.createConsumer(brokerZeroQueue); - TextMessage answer = (TextMessage)consumer.receive(5000); - assertEquals("Should have received a message!", answer.getText(), "Msg1"); - } + TextMessage answer = (TextMessage) consumer.receive(5000); + assertEquals("Should have received a message!", answer.getText(), "Msg1"); + } - // https://issues.apache.org/jira/browse/AMQ-4234 - // https://issues.apache.org/jira/browse/AMQ-4235 - public void testBrokerZeroPrefetchConfigWithConsumerControl() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + // https://issues.apache.org/jira/browse/AMQ-4234 + // https://issues.apache.org/jira/browse/AMQ-4235 + public void testBrokerZeroPrefetchConfigWithConsumerControl() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer) session.createConsumer(brokerZeroQueue); - assertEquals("broker config prefetch in effect", 0, consumer.info.getCurrentPrefetchSize()); + ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer) session.createConsumer(brokerZeroQueue); + assertEquals("broker config prefetch in effect", 0, consumer.info.getCurrentPrefetchSize()); - // verify sub view broker - Subscription sub = - broker.getRegionBroker().getDestinationMap().get(ActiveMQDestination.transform(brokerZeroQueue)).getConsumers().get(0); - assertEquals("broker sub prefetch is correct", 0, sub.getConsumerInfo().getCurrentPrefetchSize()); + // verify sub view broker + Subscription sub = broker.getRegionBroker().getDestinationMap().get(ActiveMQDestination.transform(brokerZeroQueue)).getConsumers().get(0); + assertEquals("broker sub prefetch is correct", 0, sub.getConsumerInfo().getCurrentPrefetchSize()); - // manipulate Prefetch (like failover and stomp) - ConsumerControl consumerControl = new ConsumerControl(); - consumerControl.setConsumerId(consumer.info.getConsumerId()); - consumerControl.setDestination(ActiveMQDestination.transform(brokerZeroQueue)); - consumerControl.setPrefetch(1000); // default for a q + // manipulate Prefetch (like failover and stomp) + ConsumerControl consumerControl = new ConsumerControl(); + consumerControl.setConsumerId(consumer.info.getConsumerId()); + consumerControl.setDestination(ActiveMQDestination.transform(brokerZeroQueue)); + consumerControl.setPrefetch(1000); // default for a q - Object reply = ((ActiveMQConnection) connection).getTransport().request(consumerControl); - assertTrue("good request", !(reply instanceof ExceptionResponse)); - assertEquals("broker config prefetch in effect", 0, consumer.info.getCurrentPrefetchSize()); - assertEquals("broker sub prefetch is correct", 0, sub.getConsumerInfo().getCurrentPrefetchSize()); - } + Object reply = ((ActiveMQConnection) connection).getTransport().request(consumerControl); + assertTrue("good request", !(reply instanceof ExceptionResponse)); + assertEquals("broker config prefetch in effect", 0, consumer.info.getCurrentPrefetchSize()); + assertEquals("broker sub prefetch is correct", 0, sub.getConsumerInfo().getCurrentPrefetchSize()); + } - @Override - protected BrokerService createBroker() throws Exception { - BrokerService brokerService = super.createBroker(); - PolicyMap policyMap = new PolicyMap(); - PolicyEntry zeroPrefetchPolicy = new PolicyEntry(); - zeroPrefetchPolicy.setQueuePrefetch(0); - policyMap.put(ActiveMQDestination.transform(brokerZeroQueue), zeroPrefetchPolicy); - brokerService.setDestinationPolicy(policyMap); - return brokerService; - } + @Override + protected BrokerService createBroker() throws Exception { + BrokerService brokerService = super.createBroker(); + PolicyMap policyMap = new PolicyMap(); + PolicyEntry zeroPrefetchPolicy = new PolicyEntry(); + zeroPrefetchPolicy.setQueuePrefetch(0); + policyMap.put(ActiveMQDestination.transform(brokerZeroQueue), zeroPrefetchPolicy); + brokerService.setDestinationPolicy(policyMap); + return brokerService; + } - @Override - protected void setUp() throws Exception { - bindAddress = "tcp://localhost:0"; - super.setUp(); + @Override + protected void setUp() throws Exception { + bindAddress = "tcp://localhost:0"; + super.setUp(); - connection = createConnection(); - connection.start(); - queue = createQueue(); - } + connection = createConnection(); + connection.start(); + queue = createQueue(); + } - @Override - protected void startBroker() throws Exception { - super.startBroker(); - bindAddress = broker.getTransportConnectors().get(0).getConnectUri().toString(); - } + @Override + protected void startBroker() throws Exception { + super.startBroker(); + bindAddress = broker.getTransportConnectors().get(0).getConnectUri().toString(); + } - @Override - protected void tearDown() throws Exception { - connection.close(); - super.tearDown(); - } + @Override + protected void tearDown() throws Exception { + connection.close(); + super.tearDown(); + } - protected Queue createQueue() { - return new ActiveMQQueue(getDestinationString() + "?consumer.prefetchSize=0"); - } + protected Queue createQueue() { + return new ActiveMQQueue(getDestinationString() + "?consumer.prefetchSize=0"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/AdvisoryTempDestinationTests.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/AdvisoryTempDestinationTests.java index 5e20f79c3b..65b5243819 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/AdvisoryTempDestinationTests.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/AdvisoryTempDestinationTests.java @@ -44,189 +44,184 @@ import org.apache.activemq.command.ActiveMQMessage; public class AdvisoryTempDestinationTests extends TestCase { - protected static final int MESSAGE_COUNT = 2000; - protected BrokerService broker; - protected Connection connection; - protected String bindAddress = ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL; - protected int topicCount; + protected static final int MESSAGE_COUNT = 2000; + protected BrokerService broker; + protected Connection connection; + protected String bindAddress = ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL; + protected int topicCount; + public void testNoSlowConsumerAdvisory() throws Exception { + Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + TemporaryQueue queue = s.createTemporaryQueue(); + MessageConsumer consumer = s.createConsumer(queue); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + } + }); + Topic advisoryTopic = AdvisorySupport.getSlowConsumerAdvisoryTopic((ActiveMQDestination) queue); + s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); + // start throwing messages at the consumer + MessageProducer producer = s.createProducer(queue); + for (int i = 0; i < MESSAGE_COUNT; i++) { + BytesMessage m = s.createBytesMessage(); + m.writeBytes(new byte[1024]); + producer.send(m); + } + Message msg = advisoryConsumer.receive(1000); + assertNull(msg); + } - public void testNoSlowConsumerAdvisory() throws Exception { - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TemporaryQueue queue = s.createTemporaryQueue(); - MessageConsumer consumer = s.createConsumer(queue); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - } - }); - Topic advisoryTopic = AdvisorySupport - .getSlowConsumerAdvisoryTopic((ActiveMQDestination) queue); - s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); - // start throwing messages at the consumer - MessageProducer producer = s.createProducer(queue); - for (int i = 0; i < MESSAGE_COUNT; i++) { - BytesMessage m = s.createBytesMessage(); - m.writeBytes(new byte[1024]); - producer.send(m); - } - Message msg = advisoryConsumer.receive(1000); - assertNull(msg); - } + public void testSlowConsumerAdvisory() throws Exception { + Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + TemporaryQueue queue = s.createTemporaryQueue(); + MessageConsumer consumer = s.createConsumer(queue); + assertNotNull(consumer); - public void testSlowConsumerAdvisory() throws Exception { - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TemporaryQueue queue = s.createTemporaryQueue(); - MessageConsumer consumer = s.createConsumer(queue); - assertNotNull(consumer); + Topic advisoryTopic = AdvisorySupport.getSlowConsumerAdvisoryTopic((ActiveMQDestination) queue); + s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); + // start throwing messages at the consumer + MessageProducer producer = s.createProducer(queue); + for (int i = 0; i < MESSAGE_COUNT; i++) { + BytesMessage m = s.createBytesMessage(); + m.writeBytes(new byte[1024]); + producer.send(m); + } + Message msg = advisoryConsumer.receive(1000); + assertNotNull(msg); + } - Topic advisoryTopic = AdvisorySupport - .getSlowConsumerAdvisoryTopic((ActiveMQDestination) queue); - s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); - // start throwing messages at the consumer - MessageProducer producer = s.createProducer(queue); - for (int i = 0; i < MESSAGE_COUNT; i++) { - BytesMessage m = s.createBytesMessage(); - m.writeBytes(new byte[1024]); - producer.send(m); - } - Message msg = advisoryConsumer.receive(1000); - assertNotNull(msg); - } + public void testMessageDeliveryAdvisory() throws Exception { + Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + TemporaryQueue queue = s.createTemporaryQueue(); + MessageConsumer consumer = s.createConsumer(queue); + assertNotNull(consumer); - public void testMessageDeliveryAdvisory() throws Exception { - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TemporaryQueue queue = s.createTemporaryQueue(); - MessageConsumer consumer = s.createConsumer(queue); - assertNotNull(consumer); + Topic advisoryTopic = AdvisorySupport.getMessageDeliveredAdvisoryTopic((ActiveMQDestination) queue); + MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); + //start throwing messages at the consumer + MessageProducer producer = s.createProducer(queue); - Topic advisoryTopic = AdvisorySupport.getMessageDeliveredAdvisoryTopic((ActiveMQDestination) queue); - MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); - //start throwing messages at the consumer - MessageProducer producer = s.createProducer(queue); + BytesMessage m = s.createBytesMessage(); + m.writeBytes(new byte[1024]); + producer.send(m); - BytesMessage m = s.createBytesMessage(); - m.writeBytes(new byte[1024]); - producer.send(m); + Message msg = advisoryConsumer.receive(1000); + assertNotNull(msg); + } - Message msg = advisoryConsumer.receive(1000); - assertNotNull(msg); - } + public void testTempMessageConsumedAdvisory() throws Exception { + Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + TemporaryQueue queue = s.createTemporaryQueue(); + MessageConsumer consumer = s.createConsumer(queue); - public void testTempMessageConsumedAdvisory() throws Exception { - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TemporaryQueue queue = s.createTemporaryQueue(); - MessageConsumer consumer = s.createConsumer(queue); + Topic advisoryTopic = AdvisorySupport.getMessageConsumedAdvisoryTopic((ActiveMQDestination) queue); + MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); + //start throwing messages at the consumer + MessageProducer producer = s.createProducer(queue); - Topic advisoryTopic = AdvisorySupport.getMessageConsumedAdvisoryTopic((ActiveMQDestination) queue); - MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); - //start throwing messages at the consumer - MessageProducer producer = s.createProducer(queue); + BytesMessage m = s.createBytesMessage(); + m.writeBytes(new byte[1024]); + producer.send(m); + String id = m.getJMSMessageID(); + Message msg = consumer.receive(1000); + assertNotNull(msg); - BytesMessage m = s.createBytesMessage(); - m.writeBytes(new byte[1024]); - producer.send(m); - String id = m.getJMSMessageID(); - Message msg = consumer.receive(1000); - assertNotNull(msg); + msg = advisoryConsumer.receive(1000); + assertNotNull(msg); - msg = advisoryConsumer.receive(1000); - assertNotNull(msg); + ActiveMQMessage message = (ActiveMQMessage) msg; + ActiveMQMessage payload = (ActiveMQMessage) message.getDataStructure(); + String originalId = payload.getJMSMessageID(); + assertEquals(originalId, id); + } - ActiveMQMessage message = (ActiveMQMessage) msg; - ActiveMQMessage payload = (ActiveMQMessage) message.getDataStructure(); - String originalId = payload.getJMSMessageID(); - assertEquals(originalId, id); - } + public void testMessageExpiredAdvisory() throws Exception { + Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = s.createQueue(getClass().getName()); + MessageConsumer consumer = s.createConsumer(queue); + assertNotNull(consumer); - public void testMessageExpiredAdvisory() throws Exception { - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = s.createQueue(getClass().getName()); - MessageConsumer consumer = s.createConsumer(queue); - assertNotNull(consumer); + Topic advisoryTopic = AdvisorySupport.getExpiredMessageTopic((ActiveMQDestination) queue); + MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); + //start throwing messages at the consumer + MessageProducer producer = s.createProducer(queue); + producer.setTimeToLive(1); + for (int i = 0; i < MESSAGE_COUNT; i++) { + BytesMessage m = s.createBytesMessage(); + m.writeBytes(new byte[1024]); + producer.send(m); + } - Topic advisoryTopic = AdvisorySupport.getExpiredMessageTopic((ActiveMQDestination) queue); - MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); - //start throwing messages at the consumer - MessageProducer producer = s.createProducer(queue); - producer.setTimeToLive(1); - for (int i = 0; i < MESSAGE_COUNT; i++) { - BytesMessage m = s.createBytesMessage(); - m.writeBytes(new byte[1024]); - producer.send(m); - } + Message msg = advisoryConsumer.receive(5000); + assertNotNull(msg); + } - Message msg = advisoryConsumer.receive(5000); - assertNotNull(msg); - } + @Override + protected void setUp() throws Exception { + if (broker == null) { + broker = createBroker(); + } + ConnectionFactory factory = createConnectionFactory(); + connection = factory.createConnection(); + connection.start(); + super.setUp(); + } - @Override - protected void setUp() throws Exception { - if (broker == null) { - broker = createBroker(); - } - ConnectionFactory factory = createConnectionFactory(); - connection = factory.createConnection(); - connection.start(); - super.setUp(); - } + @Override + protected void tearDown() throws Exception { + super.tearDown(); + connection.close(); + if (broker != null) { + broker.stop(); + } + } - @Override - protected void tearDown() throws Exception { - super.tearDown(); - connection.close(); - if (broker != null) { - broker.stop(); - } - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL); + return cf; + } - protected ActiveMQConnectionFactory createConnectionFactory() - throws Exception { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory( - ActiveMQConnection.DEFAULT_BROKER_URL); - return cf; - } + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + configureBroker(answer); + answer.start(); + return answer; + } - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - configureBroker(answer); - answer.start(); - return answer; - } + protected void configureBroker(BrokerService answer) throws Exception { + answer.setPersistent(false); + ConstantPendingMessageLimitStrategy strategy = new ConstantPendingMessageLimitStrategy(); + strategy.setLimit(10); + PolicyEntry tempQueueEntry = createPolicyEntry(strategy); + tempQueueEntry.setTempQueue(true); + PolicyEntry tempTopicEntry = createPolicyEntry(strategy); + tempTopicEntry.setTempTopic(true); - protected void configureBroker(BrokerService answer) throws Exception { - answer.setPersistent(false); - ConstantPendingMessageLimitStrategy strategy = new ConstantPendingMessageLimitStrategy(); - strategy.setLimit(10); - PolicyEntry tempQueueEntry = createPolicyEntry(strategy); - tempQueueEntry.setTempQueue(true); - PolicyEntry tempTopicEntry = createPolicyEntry(strategy); - tempTopicEntry.setTempTopic(true); + PolicyMap pMap = new PolicyMap(); + final List policyEntries = new ArrayList(); + policyEntries.add(tempQueueEntry); + policyEntries.add(tempTopicEntry); + pMap.setPolicyEntries(policyEntries); - PolicyMap pMap = new PolicyMap(); - final List policyEntries = new ArrayList(); - policyEntries.add(tempQueueEntry); - policyEntries.add(tempTopicEntry); - pMap.setPolicyEntries(policyEntries); + answer.setDestinationPolicy(pMap); + answer.addConnector(bindAddress); + answer.setDeleteAllMessagesOnStartup(true); + } - answer.setDestinationPolicy(pMap); - answer.addConnector(bindAddress); - answer.setDeleteAllMessagesOnStartup(true); - } + private PolicyEntry createPolicyEntry(ConstantPendingMessageLimitStrategy strategy) { + PolicyEntry policy = new PolicyEntry(); + policy.setAdvisoryForFastProducers(true); + policy.setAdvisoryForConsumed(true); + policy.setAdvisoryForDelivery(true); + policy.setAdvisoryForDiscardingMessages(true); + policy.setAdvisoryForSlowConsumers(true); + policy.setAdvisoryWhenFull(true); + policy.setProducerFlowControl(false); + policy.setPendingMessageLimitStrategy(strategy); - private PolicyEntry createPolicyEntry(ConstantPendingMessageLimitStrategy strategy) { - PolicyEntry policy = new PolicyEntry(); - policy.setAdvisoryForFastProducers(true); - policy.setAdvisoryForConsumed(true); - policy.setAdvisoryForDelivery(true); - policy.setAdvisoryForDiscardingMessages(true); - policy.setAdvisoryForSlowConsumers(true); - policy.setAdvisoryWhenFull(true); - policy.setProducerFlowControl(false); - policy.setPendingMessageLimitStrategy(strategy); - - return policy; - } + return policy; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/AdvisoryTests.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/AdvisoryTests.java index 4bb90532f5..d399eb22a9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/AdvisoryTests.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/AdvisoryTests.java @@ -43,196 +43,192 @@ import org.apache.activemq.command.ActiveMQMessage; * */ public class AdvisoryTests extends TestCase { - protected static final int MESSAGE_COUNT = 2000; - protected BrokerService broker; - protected Connection connection; - protected String bindAddress = ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL; - protected int topicCount; + protected static final int MESSAGE_COUNT = 2000; + protected BrokerService broker; + protected Connection connection; + protected String bindAddress = ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL; + protected int topicCount; - public void testNoSlowConsumerAdvisory() throws Exception { - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = s.createQueue(getClass().getName()); - MessageConsumer consumer = s.createConsumer(queue); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - } - }); - Topic advisoryTopic = AdvisorySupport - .getSlowConsumerAdvisoryTopic((ActiveMQDestination) queue); - s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); - // start throwing messages at the consumer - MessageProducer producer = s.createProducer(queue); - for (int i = 0; i < MESSAGE_COUNT; i++) { - BytesMessage m = s.createBytesMessage(); - m.writeBytes(new byte[1024]); - producer.send(m); - } - Message msg = advisoryConsumer.receive(1000); - assertNull(msg); - } + public void testNoSlowConsumerAdvisory() throws Exception { + Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = s.createQueue(getClass().getName()); + MessageConsumer consumer = s.createConsumer(queue); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + } + }); + Topic advisoryTopic = AdvisorySupport.getSlowConsumerAdvisoryTopic((ActiveMQDestination) queue); + s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); + // start throwing messages at the consumer + MessageProducer producer = s.createProducer(queue); + for (int i = 0; i < MESSAGE_COUNT; i++) { + BytesMessage m = s.createBytesMessage(); + m.writeBytes(new byte[1024]); + producer.send(m); + } + Message msg = advisoryConsumer.receive(1000); + assertNull(msg); + } - public void testSlowConsumerAdvisory() throws Exception { - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = s.createQueue(getClass().getName()); - MessageConsumer consumer = s.createConsumer(queue); - assertNotNull(consumer); + public void testSlowConsumerAdvisory() throws Exception { + Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = s.createQueue(getClass().getName()); + MessageConsumer consumer = s.createConsumer(queue); + assertNotNull(consumer); - Topic advisoryTopic = AdvisorySupport - .getSlowConsumerAdvisoryTopic((ActiveMQDestination) queue); - s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); - // start throwing messages at the consumer - MessageProducer producer = s.createProducer(queue); - for (int i = 0; i < MESSAGE_COUNT; i++) { - BytesMessage m = s.createBytesMessage(); - m.writeBytes(new byte[1024]); - producer.send(m); - } - Message msg = advisoryConsumer.receive(1000); - assertNotNull(msg); - } + Topic advisoryTopic = AdvisorySupport.getSlowConsumerAdvisoryTopic((ActiveMQDestination) queue); + s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); + // start throwing messages at the consumer + MessageProducer producer = s.createProducer(queue); + for (int i = 0; i < MESSAGE_COUNT; i++) { + BytesMessage m = s.createBytesMessage(); + m.writeBytes(new byte[1024]); + producer.send(m); + } + Message msg = advisoryConsumer.receive(1000); + assertNotNull(msg); + } - public void testMessageDeliveryAdvisory() throws Exception { - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = s.createQueue(getClass().getName()); - MessageConsumer consumer = s.createConsumer(queue); - assertNotNull(consumer); + public void testMessageDeliveryAdvisory() throws Exception { + Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = s.createQueue(getClass().getName()); + MessageConsumer consumer = s.createConsumer(queue); + assertNotNull(consumer); - Topic advisoryTopic = AdvisorySupport.getMessageDeliveredAdvisoryTopic((ActiveMQDestination) queue); - MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); - //start throwing messages at the consumer - MessageProducer producer = s.createProducer(queue); + Topic advisoryTopic = AdvisorySupport.getMessageDeliveredAdvisoryTopic((ActiveMQDestination) queue); + MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); + //start throwing messages at the consumer + MessageProducer producer = s.createProducer(queue); - BytesMessage m = s.createBytesMessage(); - m.writeBytes(new byte[1024]); - producer.send(m); + BytesMessage m = s.createBytesMessage(); + m.writeBytes(new byte[1024]); + producer.send(m); - Message msg = advisoryConsumer.receive(1000); - assertNotNull(msg); - } + Message msg = advisoryConsumer.receive(1000); + assertNotNull(msg); + } - public void testMessageConsumedAdvisory() throws Exception { - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = s.createQueue(getClass().getName()); - MessageConsumer consumer = s.createConsumer(queue); + public void testMessageConsumedAdvisory() throws Exception { + Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = s.createQueue(getClass().getName()); + MessageConsumer consumer = s.createConsumer(queue); - Topic advisoryTopic = AdvisorySupport.getMessageConsumedAdvisoryTopic((ActiveMQDestination) queue); - MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); - //start throwing messages at the consumer - MessageProducer producer = s.createProducer(queue); + Topic advisoryTopic = AdvisorySupport.getMessageConsumedAdvisoryTopic((ActiveMQDestination) queue); + MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); + //start throwing messages at the consumer + MessageProducer producer = s.createProducer(queue); - BytesMessage m = s.createBytesMessage(); - m.writeBytes(new byte[1024]); - producer.send(m); - String id = m.getJMSMessageID(); - Message msg = consumer.receive(1000); - assertNotNull(msg); + BytesMessage m = s.createBytesMessage(); + m.writeBytes(new byte[1024]); + producer.send(m); + String id = m.getJMSMessageID(); + Message msg = consumer.receive(1000); + assertNotNull(msg); - msg = advisoryConsumer.receive(1000); - assertNotNull(msg); + msg = advisoryConsumer.receive(1000); + assertNotNull(msg); - ActiveMQMessage message = (ActiveMQMessage) msg; - ActiveMQMessage payload = (ActiveMQMessage) message.getDataStructure(); - String originalId = payload.getJMSMessageID(); - assertEquals(originalId, id); - } + ActiveMQMessage message = (ActiveMQMessage) msg; + ActiveMQMessage payload = (ActiveMQMessage) message.getDataStructure(); + String originalId = payload.getJMSMessageID(); + assertEquals(originalId, id); + } - public void testMessageExpiredAdvisory() throws Exception { - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = s.createQueue(getClass().getName()); - MessageConsumer consumer = s.createConsumer(queue); - assertNotNull(consumer); + public void testMessageExpiredAdvisory() throws Exception { + Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = s.createQueue(getClass().getName()); + MessageConsumer consumer = s.createConsumer(queue); + assertNotNull(consumer); - Topic advisoryTopic = AdvisorySupport.getExpiredMessageTopic((ActiveMQDestination) queue); - MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); - //start throwing messages at the consumer - MessageProducer producer = s.createProducer(queue); - producer.setTimeToLive(1); - for (int i = 0; i < MESSAGE_COUNT; i++) { - BytesMessage m = s.createBytesMessage(); - m.writeBytes(new byte[1024]); - producer.send(m); - } + Topic advisoryTopic = AdvisorySupport.getExpiredMessageTopic((ActiveMQDestination) queue); + MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); + //start throwing messages at the consumer + MessageProducer producer = s.createProducer(queue); + producer.setTimeToLive(1); + for (int i = 0; i < MESSAGE_COUNT; i++) { + BytesMessage m = s.createBytesMessage(); + m.writeBytes(new byte[1024]); + producer.send(m); + } - Message msg = advisoryConsumer.receive(2000); - assertNotNull(msg); - } + Message msg = advisoryConsumer.receive(2000); + assertNotNull(msg); + } - public void xtestMessageDiscardedAdvisory() throws Exception { - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic = s.createTopic(getClass().getName()); - MessageConsumer consumer = s.createConsumer(topic); - assertNotNull(consumer); + public void xtestMessageDiscardedAdvisory() throws Exception { + Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Topic topic = s.createTopic(getClass().getName()); + MessageConsumer consumer = s.createConsumer(topic); + assertNotNull(consumer); - Topic advisoryTopic = AdvisorySupport.getMessageDiscardedAdvisoryTopic((ActiveMQDestination) topic); - MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); - //start throwing messages at the consumer - MessageProducer producer = s.createProducer(topic); - int count = (new ActiveMQPrefetchPolicy().getTopicPrefetch() * 2); - for (int i = 0; i < count; i++) { - BytesMessage m = s.createBytesMessage(); - producer.send(m); - } + Topic advisoryTopic = AdvisorySupport.getMessageDiscardedAdvisoryTopic((ActiveMQDestination) topic); + MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); + //start throwing messages at the consumer + MessageProducer producer = s.createProducer(topic); + int count = (new ActiveMQPrefetchPolicy().getTopicPrefetch() * 2); + for (int i = 0; i < count; i++) { + BytesMessage m = s.createBytesMessage(); + producer.send(m); + } - Message msg = advisoryConsumer.receive(1000); - assertNotNull(msg); - } + Message msg = advisoryConsumer.receive(1000); + assertNotNull(msg); + } - @Override - protected void setUp() throws Exception { - if (broker == null) { - broker = createBroker(); - } - ConnectionFactory factory = createConnectionFactory(); - connection = factory.createConnection(); - connection.start(); - super.setUp(); - } + @Override + protected void setUp() throws Exception { + if (broker == null) { + broker = createBroker(); + } + ConnectionFactory factory = createConnectionFactory(); + connection = factory.createConnection(); + connection.start(); + super.setUp(); + } - @Override - protected void tearDown() throws Exception { - super.tearDown(); - connection.close(); - if (broker != null) { - broker.stop(); - } - } + @Override + protected void tearDown() throws Exception { + super.tearDown(); + connection.close(); + if (broker != null) { + broker.stop(); + } + } - protected ActiveMQConnectionFactory createConnectionFactory() - throws Exception { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory( - ActiveMQConnection.DEFAULT_BROKER_URL); - return cf; - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL); + return cf; + } - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - configureBroker(answer); - answer.start(); - return answer; - } + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + configureBroker(answer); + answer.start(); + return answer; + } - protected void configureBroker(BrokerService answer) throws Exception { - answer.setPersistent(false); - PolicyEntry policy = new PolicyEntry(); - policy.setAdvisoryForFastProducers(true); - policy.setAdvisoryForConsumed(true); - policy.setAdvisoryForDelivery(true); - policy.setAdvisoryForDiscardingMessages(true); - policy.setAdvisoryForSlowConsumers(true); - policy.setAdvisoryWhenFull(true); - policy.setProducerFlowControl(false); - ConstantPendingMessageLimitStrategy strategy = new ConstantPendingMessageLimitStrategy(); - strategy.setLimit(10); - policy.setPendingMessageLimitStrategy(strategy); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); + protected void configureBroker(BrokerService answer) throws Exception { + answer.setPersistent(false); + PolicyEntry policy = new PolicyEntry(); + policy.setAdvisoryForFastProducers(true); + policy.setAdvisoryForConsumed(true); + policy.setAdvisoryForDelivery(true); + policy.setAdvisoryForDiscardingMessages(true); + policy.setAdvisoryForSlowConsumers(true); + policy.setAdvisoryWhenFull(true); + policy.setProducerFlowControl(false); + ConstantPendingMessageLimitStrategy strategy = new ConstantPendingMessageLimitStrategy(); + strategy.setLimit(10); + policy.setPendingMessageLimitStrategy(strategy); + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); - answer.setDestinationPolicy(pMap); - answer.addConnector(bindAddress); - answer.setDeleteAllMessagesOnStartup(true); - } + answer.setDestinationPolicy(pMap); + answer.addConnector(bindAddress); + answer.setDeleteAllMessagesOnStartup(true); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/ConsumerListenerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/ConsumerListenerTest.java index 2c5f9cd15e..cdf6143e3b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/ConsumerListenerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/ConsumerListenerTest.java @@ -33,120 +33,121 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * - * + * + * */ public class ConsumerListenerTest extends EmbeddedBrokerTestSupport implements ConsumerListener { - private static final Logger LOG = LoggerFactory.getLogger(ConsumerListenerTest.class); - protected Session consumerSession1; - protected Session consumerSession2; - protected int consumerCounter; - protected ConsumerEventSource consumerEventSource; - protected BlockingQueue eventQueue = new ArrayBlockingQueue(1000); - private Connection connection; + private static final Logger LOG = LoggerFactory.getLogger(ConsumerListenerTest.class); - public void testConsumerEvents() throws Exception { - consumerEventSource.start(); + protected Session consumerSession1; + protected Session consumerSession2; + protected int consumerCounter; + protected ConsumerEventSource consumerEventSource; + protected BlockingQueue eventQueue = new ArrayBlockingQueue(1000); + private Connection connection; - consumerSession1 = createConsumer(); - assertConsumerEvent(1, true); + public void testConsumerEvents() throws Exception { + consumerEventSource.start(); - consumerSession2 = createConsumer(); - assertConsumerEvent(2, true); + consumerSession1 = createConsumer(); + assertConsumerEvent(1, true); - consumerSession1.close(); - consumerSession1 = null; - assertConsumerEvent(1, false); + consumerSession2 = createConsumer(); + assertConsumerEvent(2, true); - consumerSession2.close(); - consumerSession2 = null; - assertConsumerEvent(0, false); - } + consumerSession1.close(); + consumerSession1 = null; + assertConsumerEvent(1, false); - public void testListenWhileAlreadyConsumersActive() throws Exception { - consumerSession1 = createConsumer(); - consumerSession2 = createConsumer(); + consumerSession2.close(); + consumerSession2 = null; + assertConsumerEvent(0, false); + } - consumerEventSource.start(); - assertConsumerEvent(2, true); - assertConsumerEvent(2, true); + public void testListenWhileAlreadyConsumersActive() throws Exception { + consumerSession1 = createConsumer(); + consumerSession2 = createConsumer(); - consumerSession1.close(); - consumerSession1 = null; - assertConsumerEvent(1, false); + consumerEventSource.start(); + assertConsumerEvent(2, true); + assertConsumerEvent(2, true); - consumerSession2.close(); - consumerSession2 = null; - assertConsumerEvent(0, false); - } + consumerSession1.close(); + consumerSession1 = null; + assertConsumerEvent(1, false); - public void testConsumerEventsOnTemporaryDestination() throws Exception { + consumerSession2.close(); + consumerSession2 = null; + assertConsumerEvent(0, false); + } - Session s = connection.createSession(true,Session.AUTO_ACKNOWLEDGE); - Destination dest = useTopic ? s.createTemporaryTopic() : s.createTemporaryQueue(); - consumerEventSource = new ConsumerEventSource(connection, dest); - consumerEventSource.setConsumerListener(this); - consumerEventSource.start(); - MessageConsumer consumer = s.createConsumer(dest); - assertConsumerEvent(1,true); - consumer.close(); - assertConsumerEvent(0,false); - } + public void testConsumerEventsOnTemporaryDestination() throws Exception { - public void onConsumerEvent(ConsumerEvent event) { - eventQueue.add(event); - } + Session s = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + Destination dest = useTopic ? s.createTemporaryTopic() : s.createTemporaryQueue(); + consumerEventSource = new ConsumerEventSource(connection, dest); + consumerEventSource.setConsumerListener(this); + consumerEventSource.start(); + MessageConsumer consumer = s.createConsumer(dest); + assertConsumerEvent(1, true); + consumer.close(); + assertConsumerEvent(0, false); + } - protected void setUp() throws Exception { - super.setUp(); + public void onConsumerEvent(ConsumerEvent event) { + eventQueue.add(event); + } - connection = createConnection(); - connection.start(); - consumerEventSource = new ConsumerEventSource(connection, destination); - consumerEventSource.setConsumerListener(this); - } + protected void setUp() throws Exception { + super.setUp(); - protected void tearDown() throws Exception { - if (consumerEventSource != null) { - consumerEventSource.stop(); - } - if (consumerSession2 != null) { - consumerSession2.close(); - } - if (consumerSession1 != null) { - consumerSession1.close(); - } - if (connection != null) { - connection.close(); - } - super.tearDown(); - } + connection = createConnection(); + connection.start(); + consumerEventSource = new ConsumerEventSource(connection, destination); + consumerEventSource.setConsumerListener(this); + } - protected void assertConsumerEvent(int count, boolean started) throws InterruptedException { - ConsumerEvent event = waitForConsumerEvent(); - assertEquals("Consumer count", count, event.getConsumerCount()); - assertEquals("started", started, event.isStarted()); - } + protected void tearDown() throws Exception { + if (consumerEventSource != null) { + consumerEventSource.stop(); + } + if (consumerSession2 != null) { + consumerSession2.close(); + } + if (consumerSession1 != null) { + consumerSession1.close(); + } + if (connection != null) { + connection.close(); + } + super.tearDown(); + } - protected Session createConsumer() throws JMSException { - final String consumerText = "Consumer: " + (++consumerCounter); - LOG.info("Creating consumer: " + consumerText + " on destination: " + destination); + protected void assertConsumerEvent(int count, boolean started) throws InterruptedException { + ConsumerEvent event = waitForConsumerEvent(); + assertEquals("Consumer count", count, event.getConsumerCount()); + assertEquals("started", started, event.isStarted()); + } - Session answer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = answer.createConsumer(destination); - consumer.setMessageListener(new MessageListener() { - public void onMessage(Message message) { - LOG.info("Received message by: " + consumerText + " message: " + message); - } - }); - return answer; - } + protected Session createConsumer() throws JMSException { + final String consumerText = "Consumer: " + (++consumerCounter); + LOG.info("Creating consumer: " + consumerText + " on destination: " + destination); - protected ConsumerEvent waitForConsumerEvent() throws InterruptedException { - ConsumerEvent answer = eventQueue.poll(100000, TimeUnit.MILLISECONDS); - assertTrue("Should have received a consumer event!", answer != null); - return answer; - } + Session answer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = answer.createConsumer(destination); + consumer.setMessageListener(new MessageListener() { + public void onMessage(Message message) { + LOG.info("Received message by: " + consumerText + " message: " + message); + } + }); + return answer; + } + + protected ConsumerEvent waitForConsumerEvent() throws InterruptedException { + ConsumerEvent answer = eventQueue.poll(100000, TimeUnit.MILLISECONDS); + assertTrue("Should have received a consumer event!", answer != null); + return answer; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/DestinationListenerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/DestinationListenerTest.java index 01dc443123..8a227861c8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/DestinationListenerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/DestinationListenerTest.java @@ -32,98 +32,97 @@ import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTopic; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; /** - * + * */ public class DestinationListenerTest extends EmbeddedBrokerTestSupport implements DestinationListener { - private static final transient Logger LOG = LoggerFactory.getLogger(DestinationListenerTest.class); - protected ActiveMQConnection connection; - protected ActiveMQQueue sampleQueue = new ActiveMQQueue("foo.bar"); - protected ActiveMQTopic sampleTopic = new ActiveMQTopic("cheese"); - protected List newDestinations = new ArrayList(); - public void testDestiationSourceHasInitialDestinations() throws Exception { - Thread.sleep(1000); + private static final transient Logger LOG = LoggerFactory.getLogger(DestinationListenerTest.class); + protected ActiveMQConnection connection; + protected ActiveMQQueue sampleQueue = new ActiveMQQueue("foo.bar"); + protected ActiveMQTopic sampleTopic = new ActiveMQTopic("cheese"); + protected List newDestinations = new ArrayList(); - DestinationSource destinationSource = connection.getDestinationSource(); - Set queues = destinationSource.getQueues(); - Set topics = destinationSource.getTopics(); + public void testDestiationSourceHasInitialDestinations() throws Exception { + Thread.sleep(1000); - LOG.info("Queues: " + queues); - LOG.info("Topics: " + topics); + DestinationSource destinationSource = connection.getDestinationSource(); + Set queues = destinationSource.getQueues(); + Set topics = destinationSource.getTopics(); - assertTrue("The queues should not be empty!", !queues.isEmpty()); - assertTrue("The topics should not be empty!", !topics.isEmpty()); + LOG.info("Queues: " + queues); + LOG.info("Topics: " + topics); - assertTrue("queues contains initial queue: " + queues, queues.contains(sampleQueue)); - assertTrue("topics contains initial topic: " + queues, topics.contains(sampleTopic)); - } + assertTrue("The queues should not be empty!", !queues.isEmpty()); + assertTrue("The topics should not be empty!", !topics.isEmpty()); - public void testConsumerForcesNotificationOfNewDestination() throws Exception { - // now lets cause a destination to be created - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQQueue newQueue = new ActiveMQQueue("Test.Cheese"); - session.createConsumer(newQueue); + assertTrue("queues contains initial queue: " + queues, queues.contains(sampleQueue)); + assertTrue("topics contains initial topic: " + queues, topics.contains(sampleTopic)); + } - Thread.sleep(3000); + public void testConsumerForcesNotificationOfNewDestination() throws Exception { + // now lets cause a destination to be created + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQQueue newQueue = new ActiveMQQueue("Test.Cheese"); + session.createConsumer(newQueue); - assertThat(newQueue, isIn(newDestinations)); + Thread.sleep(3000); - LOG.info("New destinations are: " + newDestinations); - } + assertThat(newQueue, isIn(newDestinations)); - public void testProducerForcesNotificationOfNewDestination() throws Exception { - // now lets cause a destination to be created - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQQueue newQueue = new ActiveMQQueue("Test.Beer"); - MessageProducer producer = session.createProducer(newQueue); - TextMessage message = session.createTextMessage("world"); - producer.send(message); + LOG.info("New destinations are: " + newDestinations); + } - Thread.sleep(3000); + public void testProducerForcesNotificationOfNewDestination() throws Exception { + // now lets cause a destination to be created + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQQueue newQueue = new ActiveMQQueue("Test.Beer"); + MessageProducer producer = session.createProducer(newQueue); + TextMessage message = session.createTextMessage("world"); + producer.send(message); - assertThat(newQueue, isIn(newDestinations)); + Thread.sleep(3000); - LOG.info("New destinations are: " + newDestinations); - } + assertThat(newQueue, isIn(newDestinations)); - public void onDestinationEvent(DestinationEvent event) { - ActiveMQDestination destination = event.getDestination(); - if (event.isAddOperation()) { - LOG.info("Added: " + destination); - newDestinations.add(destination); - } - else { - LOG.info("Removed: " + destination); - newDestinations.remove(destination); - } - } + LOG.info("New destinations are: " + newDestinations); + } - protected void setUp() throws Exception { - super.setUp(); + public void onDestinationEvent(DestinationEvent event) { + ActiveMQDestination destination = event.getDestination(); + if (event.isAddOperation()) { + LOG.info("Added: " + destination); + newDestinations.add(destination); + } + else { + LOG.info("Removed: " + destination); + newDestinations.remove(destination); + } + } - connection = (ActiveMQConnection) createConnection(); - connection.start(); - connection.getDestinationSource().setDestinationListener(this); - } + protected void setUp() throws Exception { + super.setUp(); - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - broker.setDestinations(new ActiveMQDestination[]{ - sampleQueue, - sampleTopic - }); - return broker; - } + connection = (ActiveMQConnection) createConnection(); + connection.start(); + connection.getDestinationSource().setDestinationListener(this); + } - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - super.tearDown(); - } + @Override + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); + broker.setDestinations(new ActiveMQDestination[]{sampleQueue, sampleTopic}); + return broker; + } + + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + } + super.tearDown(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/ProducerListenerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/ProducerListenerTest.java index dfa1b5e39b..fa12fd5b56 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/ProducerListenerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/ProducerListenerTest.java @@ -25,6 +25,7 @@ import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.MessageProducer; import javax.jms.Session; + import org.apache.activemq.EmbeddedBrokerTestSupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,118 +35,117 @@ import org.slf4j.LoggerFactory; * */ public class ProducerListenerTest extends EmbeddedBrokerTestSupport implements ProducerListener { - private static final Logger LOG = LoggerFactory.getLogger(ProducerListenerTest.class); - protected Session consumerSession1; - protected Session consumerSession2; - protected int consumerCounter; - protected ProducerEventSource producerEventSource; - protected BlockingQueue eventQueue = new ArrayBlockingQueue(1000); - private Connection connection; + private static final Logger LOG = LoggerFactory.getLogger(ProducerListenerTest.class); - public void testProducerEvents() throws Exception { - producerEventSource.start(); + protected Session consumerSession1; + protected Session consumerSession2; + protected int consumerCounter; + protected ProducerEventSource producerEventSource; + protected BlockingQueue eventQueue = new ArrayBlockingQueue(1000); + private Connection connection; - consumerSession1 = createProducer(); - assertProducerEvent(1, true); + public void testProducerEvents() throws Exception { + producerEventSource.start(); - consumerSession2 = createProducer(); - assertProducerEvent(2, true); + consumerSession1 = createProducer(); + assertProducerEvent(1, true); - consumerSession1.close(); - consumerSession1 = null; - assertProducerEvent(1, false); + consumerSession2 = createProducer(); + assertProducerEvent(2, true); - consumerSession2.close(); - consumerSession2 = null; - assertProducerEvent(0, false); - } + consumerSession1.close(); + consumerSession1 = null; + assertProducerEvent(1, false); - public void testListenWhileAlreadyConsumersActive() throws Exception { - consumerSession1 = createProducer(); - consumerSession2 = createProducer(); + consumerSession2.close(); + consumerSession2 = null; + assertProducerEvent(0, false); + } - producerEventSource.start(); - assertProducerEvent(2, true); - assertProducerEvent(2, true); + public void testListenWhileAlreadyConsumersActive() throws Exception { + consumerSession1 = createProducer(); + consumerSession2 = createProducer(); - consumerSession1.close(); - consumerSession1 = null; - assertProducerEvent(1, false); + producerEventSource.start(); + assertProducerEvent(2, true); + assertProducerEvent(2, true); - consumerSession2.close(); - consumerSession2 = null; - assertProducerEvent(0, false); - } + consumerSession1.close(); + consumerSession1 = null; + assertProducerEvent(1, false); - public void testConsumerEventsOnTemporaryDestination() throws Exception { + consumerSession2.close(); + consumerSession2 = null; + assertProducerEvent(0, false); + } - Session s = connection.createSession(true,Session.AUTO_ACKNOWLEDGE); - Destination dest = useTopic ? s.createTemporaryTopic() : s.createTemporaryQueue(); - producerEventSource = new ProducerEventSource(connection, dest); - producerEventSource.setProducerListener(this); - producerEventSource.start(); - MessageProducer producer = s.createProducer(dest); - assertProducerEvent(1, true); - producer.close(); - assertProducerEvent(0, false); - } + public void testConsumerEventsOnTemporaryDestination() throws Exception { + Session s = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + Destination dest = useTopic ? s.createTemporaryTopic() : s.createTemporaryQueue(); + producerEventSource = new ProducerEventSource(connection, dest); + producerEventSource.setProducerListener(this); + producerEventSource.start(); + MessageProducer producer = s.createProducer(dest); + assertProducerEvent(1, true); + producer.close(); + assertProducerEvent(0, false); + } + @Override + public void onProducerEvent(ProducerEvent event) { + eventQueue.add(event); + } - @Override - public void onProducerEvent(ProducerEvent event) { - eventQueue.add(event); - } + @Override + protected void setUp() throws Exception { + super.setUp(); - @Override - protected void setUp() throws Exception { - super.setUp(); + connection = createConnection(); + connection.start(); + producerEventSource = new ProducerEventSource(connection, destination); + producerEventSource.setProducerListener(this); + } - connection = createConnection(); - connection.start(); - producerEventSource = new ProducerEventSource(connection, destination); - producerEventSource.setProducerListener(this); - } + @Override + protected void tearDown() throws Exception { + if (producerEventSource != null) { + producerEventSource.stop(); + } + if (consumerSession2 != null) { + consumerSession2.close(); + } + if (consumerSession1 != null) { + consumerSession1.close(); + } + if (connection != null) { + connection.close(); + } + super.tearDown(); + } - @Override - protected void tearDown() throws Exception { - if (producerEventSource != null) { - producerEventSource.stop(); - } - if (consumerSession2 != null) { - consumerSession2.close(); - } - if (consumerSession1 != null) { - consumerSession1.close(); - } - if (connection != null) { - connection.close(); - } - super.tearDown(); - } + protected void assertProducerEvent(int count, boolean started) throws InterruptedException { + ProducerEvent event = waitForProducerEvent(); + assertEquals("Producer count", count, event.getProducerCount()); + assertEquals("started", started, event.isStarted()); + } - protected void assertProducerEvent(int count, boolean started) throws InterruptedException { - ProducerEvent event = waitForProducerEvent(); - assertEquals("Producer count", count, event.getProducerCount()); - assertEquals("started", started, event.isStarted()); - } + protected Session createProducer() throws JMSException { + final String consumerText = "Consumer: " + (++consumerCounter); + LOG.info("Creating consumer: " + consumerText + " on destination: " + destination); - protected Session createProducer() throws JMSException { - final String consumerText = "Consumer: " + (++consumerCounter); - LOG.info("Creating consumer: " + consumerText + " on destination: " + destination); + Session answer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = answer.createProducer(destination); + assertNotNull(producer); - Session answer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = answer.createProducer(destination); - assertNotNull(producer); + return answer; + } - return answer; - } - - protected ProducerEvent waitForProducerEvent() throws InterruptedException { - ProducerEvent answer = eventQueue.poll(100000, TimeUnit.MILLISECONDS); - assertTrue("Should have received a consumer event!", answer != null); - return answer; - } + protected ProducerEvent waitForProducerEvent() throws InterruptedException { + ProducerEvent answer = eventQueue.poll(100000, TimeUnit.MILLISECONDS); + assertTrue("Should have received a consumer event!", answer != null); + return answer; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/TempDestDeleteTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/TempDestDeleteTest.java index 123c7787dd..5c8ea8966f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/TempDestDeleteTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/TempDestDeleteTest.java @@ -37,113 +37,113 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class TempDestDeleteTest extends EmbeddedBrokerTestSupport implements ConsumerListener { - private static final Logger LOG = LoggerFactory.getLogger(TempDestDeleteTest.class); - protected int consumerCounter; - protected ConsumerEventSource topicConsumerEventSource; - protected BlockingQueue eventQueue = new ArrayBlockingQueue(1000); - - private ConsumerEventSource queueConsumerEventSource; - private Connection connection; - private Session session; - private ActiveMQTempTopic tempTopic; - private ActiveMQTempQueue tempQueue; + private static final Logger LOG = LoggerFactory.getLogger(TempDestDeleteTest.class); - public void testDeleteTempTopicDeletesAvisoryTopics() throws Exception { - topicConsumerEventSource.start(); + protected int consumerCounter; + protected ConsumerEventSource topicConsumerEventSource; + protected BlockingQueue eventQueue = new ArrayBlockingQueue(1000); - MessageConsumer consumer = createConsumer(tempTopic); - assertConsumerEvent(1, true); + private ConsumerEventSource queueConsumerEventSource; + private Connection connection; + private Session session; + private ActiveMQTempTopic tempTopic; + private ActiveMQTempQueue tempQueue; - Topic advisoryTopic = AdvisorySupport.getConsumerAdvisoryTopic(tempTopic); - assertTrue(destinationExists(advisoryTopic)); + public void testDeleteTempTopicDeletesAvisoryTopics() throws Exception { + topicConsumerEventSource.start(); - consumer.close(); + MessageConsumer consumer = createConsumer(tempTopic); + assertConsumerEvent(1, true); - // Once we delete the topic, the advisory topic for the destination - // should also be deleted. - tempTopic.delete(); + Topic advisoryTopic = AdvisorySupport.getConsumerAdvisoryTopic(tempTopic); + assertTrue(destinationExists(advisoryTopic)); - assertFalse(destinationExists(advisoryTopic)); - } + consumer.close(); - public void testDeleteTempQueueDeletesAvisoryTopics() throws Exception { - queueConsumerEventSource.start(); + // Once we delete the topic, the advisory topic for the destination + // should also be deleted. + tempTopic.delete(); - MessageConsumer consumer = createConsumer(tempQueue); - assertConsumerEvent(1, true); + assertFalse(destinationExists(advisoryTopic)); + } - Topic advisoryTopic = AdvisorySupport.getConsumerAdvisoryTopic(tempQueue); - assertTrue(destinationExists(advisoryTopic)); + public void testDeleteTempQueueDeletesAvisoryTopics() throws Exception { + queueConsumerEventSource.start(); - consumer.close(); + MessageConsumer consumer = createConsumer(tempQueue); + assertConsumerEvent(1, true); - // Once we delete the queue, the advisory topic for the destination - // should also be deleted. - tempQueue.delete(); + Topic advisoryTopic = AdvisorySupport.getConsumerAdvisoryTopic(tempQueue); + assertTrue(destinationExists(advisoryTopic)); - assertFalse(destinationExists(advisoryTopic)); - } + consumer.close(); - private boolean destinationExists(Destination dest) throws Exception { - RegionBroker rb = (RegionBroker)broker.getBroker().getAdaptor(RegionBroker.class); - return rb.getTopicRegion().getDestinationMap().containsKey(dest) || rb.getQueueRegion().getDestinationMap().containsKey(dest) - || rb.getTempTopicRegion().getDestinationMap().containsKey(dest) || rb.getTempQueueRegion().getDestinationMap().containsKey(dest); - } + // Once we delete the queue, the advisory topic for the destination + // should also be deleted. + tempQueue.delete(); - public void onConsumerEvent(ConsumerEvent event) { - eventQueue.add(event); - } + assertFalse(destinationExists(advisoryTopic)); + } - protected void setUp() throws Exception { - super.setUp(); - connection = createConnection(); - connection.start(); + private boolean destinationExists(Destination dest) throws Exception { + RegionBroker rb = (RegionBroker) broker.getBroker().getAdaptor(RegionBroker.class); + return rb.getTopicRegion().getDestinationMap().containsKey(dest) || rb.getQueueRegion().getDestinationMap().containsKey(dest) || rb.getTempTopicRegion().getDestinationMap().containsKey(dest) || rb.getTempQueueRegion().getDestinationMap().containsKey(dest); + } - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + public void onConsumerEvent(ConsumerEvent event) { + eventQueue.add(event); + } - tempTopic = (ActiveMQTempTopic)session.createTemporaryTopic(); - topicConsumerEventSource = new ConsumerEventSource(connection, tempTopic); - topicConsumerEventSource.setConsumerListener(this); + protected void setUp() throws Exception { + super.setUp(); + connection = createConnection(); + connection.start(); - tempQueue = (ActiveMQTempQueue)session.createTemporaryQueue(); - queueConsumerEventSource = new ConsumerEventSource(connection, tempQueue); - queueConsumerEventSource.setConsumerListener(this); - } + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - super.tearDown(); - } + tempTopic = (ActiveMQTempTopic) session.createTemporaryTopic(); + topicConsumerEventSource = new ConsumerEventSource(connection, tempTopic); + topicConsumerEventSource.setConsumerListener(this); - protected void assertConsumerEvent(int count, boolean started) throws InterruptedException { - ConsumerEvent event = waitForConsumerEvent(); - assertEquals("Consumer count", count, event.getConsumerCount()); - assertEquals("started", started, event.isStarted()); - } + tempQueue = (ActiveMQTempQueue) session.createTemporaryQueue(); + queueConsumerEventSource = new ConsumerEventSource(connection, tempQueue); + queueConsumerEventSource.setConsumerListener(this); + } - protected MessageConsumer createConsumer(Destination dest) throws JMSException { - final String consumerText = "Consumer: " + (++consumerCounter); - LOG.info("Creating consumer: " + consumerText + " on destination: " + dest); + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + } + super.tearDown(); + } - MessageConsumer consumer = session.createConsumer(dest); - consumer.setMessageListener(new MessageListener() { - public void onMessage(Message message) { - LOG.info("Received message by: " + consumerText + " message: " + message); - } - }); - return consumer; - } + protected void assertConsumerEvent(int count, boolean started) throws InterruptedException { + ConsumerEvent event = waitForConsumerEvent(); + assertEquals("Consumer count", count, event.getConsumerCount()); + assertEquals("started", started, event.isStarted()); + } - protected ConsumerEvent waitForConsumerEvent() throws InterruptedException { - ConsumerEvent answer = eventQueue.poll(1000, TimeUnit.MILLISECONDS); - assertTrue("Should have received a consumer event!", answer != null); - return answer; - } + protected MessageConsumer createConsumer(Destination dest) throws JMSException { + final String consumerText = "Consumer: " + (++consumerCounter); + LOG.info("Creating consumer: " + consumerText + " on destination: " + dest); + + MessageConsumer consumer = session.createConsumer(dest); + consumer.setMessageListener(new MessageListener() { + public void onMessage(Message message) { + LOG.info("Received message by: " + consumerText + " message: " + message); + } + }); + return consumer; + } + + protected ConsumerEvent waitForConsumerEvent() throws InterruptedException { + ConsumerEvent answer = eventQueue.poll(1000, TimeUnit.MILLISECONDS); + assertTrue("Should have received a consumer event!", answer != null); + return answer; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/TempDestLoadTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/TempDestLoadTest.java index cab4e5924b..19e5edf0d2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/TempDestLoadTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/TempDestLoadTest.java @@ -34,82 +34,79 @@ import org.slf4j.LoggerFactory; */ public class TempDestLoadTest extends EmbeddedBrokerTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(TempDestLoadTest.class); + private static final Logger LOG = LoggerFactory.getLogger(TempDestLoadTest.class); - protected int consumerCounter; - private Connection connection; - private Session session; - private static final int MESSAGE_COUNT = 2000; + protected int consumerCounter; + private Connection connection; + private Session session; + private static final int MESSAGE_COUNT = 2000; - public void testLoadTempAdvisoryQueues() throws Exception { + public void testLoadTempAdvisoryQueues() throws Exception { - for (int i = 0; i < MESSAGE_COUNT; i++) { - TemporaryQueue tempQueue = session.createTemporaryQueue(); - MessageConsumer consumer = session.createConsumer(tempQueue); - MessageProducer producer = session.createProducer(tempQueue); - consumer.close(); - producer.close(); - tempQueue.delete(); - } + for (int i = 0; i < MESSAGE_COUNT; i++) { + TemporaryQueue tempQueue = session.createTemporaryQueue(); + MessageConsumer consumer = session.createConsumer(tempQueue); + MessageProducer producer = session.createProducer(tempQueue); + consumer.close(); + producer.close(); + tempQueue.delete(); + } - AdvisoryBroker ab = (AdvisoryBroker) broker.getBroker().getAdaptor( - AdvisoryBroker.class); + AdvisoryBroker ab = (AdvisoryBroker) broker.getBroker().getAdaptor(AdvisoryBroker.class); - assertTrue(ab.getAdvisoryDestinations().size() == 0); - assertTrue(ab.getAdvisoryConsumers().size() == 0); - assertTrue(ab.getAdvisoryProducers().size() == 0); + assertTrue(ab.getAdvisoryDestinations().size() == 0); + assertTrue(ab.getAdvisoryConsumers().size() == 0); + assertTrue(ab.getAdvisoryProducers().size() == 0); - RegionBroker rb = (RegionBroker) broker.getBroker().getAdaptor(RegionBroker.class); + RegionBroker rb = (RegionBroker) broker.getBroker().getAdaptor(RegionBroker.class); - for (Destination dest : rb.getDestinationMap().values()) { - LOG.debug("Destination: {}", dest); - } + for (Destination dest : rb.getDestinationMap().values()) { + LOG.debug("Destination: {}", dest); + } - // there should be at least 2 destinations - advisories - - // 1 for the connection + 1 generic ones - assertTrue("Should be at least 2 destinations", rb.getDestinationMap().size() > 2); - } + // there should be at least 2 destinations - advisories - + // 1 for the connection + 1 generic ones + assertTrue("Should be at least 2 destinations", rb.getDestinationMap().size() > 2); + } - public void testLoadTempAdvisoryTopics() throws Exception { - for (int i = 0; i < MESSAGE_COUNT; i++) { - TemporaryTopic tempTopic = session.createTemporaryTopic(); - MessageConsumer consumer = session.createConsumer(tempTopic); - MessageProducer producer = session.createProducer(tempTopic); - consumer.close(); - producer.close(); - tempTopic.delete(); - } + public void testLoadTempAdvisoryTopics() throws Exception { + for (int i = 0; i < MESSAGE_COUNT; i++) { + TemporaryTopic tempTopic = session.createTemporaryTopic(); + MessageConsumer consumer = session.createConsumer(tempTopic); + MessageProducer producer = session.createProducer(tempTopic); + consumer.close(); + producer.close(); + tempTopic.delete(); + } - AdvisoryBroker ab = (AdvisoryBroker) broker.getBroker().getAdaptor( - AdvisoryBroker.class); - assertTrue(ab.getAdvisoryDestinations().size() == 0); - assertTrue(ab.getAdvisoryConsumers().size() == 0); - assertTrue(ab.getAdvisoryProducers().size() == 0); - RegionBroker rb = (RegionBroker) broker.getBroker().getAdaptor( - RegionBroker.class); + AdvisoryBroker ab = (AdvisoryBroker) broker.getBroker().getAdaptor(AdvisoryBroker.class); + assertTrue(ab.getAdvisoryDestinations().size() == 0); + assertTrue(ab.getAdvisoryConsumers().size() == 0); + assertTrue(ab.getAdvisoryProducers().size() == 0); + RegionBroker rb = (RegionBroker) broker.getBroker().getAdaptor(RegionBroker.class); - for (Destination dest : rb.getDestinationMap().values()) { - LOG.debug("Destination: {}", dest); - } + for (Destination dest : rb.getDestinationMap().values()) { + LOG.debug("Destination: {}", dest); + } - // there should be at least 2 destinations - advisories - - // 1 for the connection + 1 generic ones - assertTrue("Should be at least 2 destinations", rb.getDestinationMap().size() > 2); - } + // there should be at least 2 destinations - advisories - + // 1 for the connection + 1 generic ones + assertTrue("Should be at least 2 destinations", rb.getDestinationMap().size() > 2); + } - @Override - protected void setUp() throws Exception { - super.setUp(); - connection = createConnection(); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } + @Override + protected void setUp() throws Exception { + super.setUp(); + connection = createConnection(); + connection.start(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + } - @Override - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - super.tearDown(); - } + @Override + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + } + super.tearDown(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/TempQueueMemoryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/TempQueueMemoryTest.java index 9bf8ed1426..ce9efc9c14 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/TempQueueMemoryTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/TempQueueMemoryTest.java @@ -35,137 +35,140 @@ import org.apache.activemq.command.ActiveMQQueue; public class TempQueueMemoryTest extends EmbeddedBrokerTestSupport { - protected Connection serverConnection; - protected Session serverSession; - protected Connection clientConnection; - protected Session clientSession; - protected Destination serverDestination; - protected int messagesToSend = 10; - protected boolean deleteTempQueue = true; - protected boolean serverTransactional = false; - protected boolean clientTransactional = false; - protected int numConsumers = 1; - protected int numProducers = 1; + protected Connection serverConnection; + protected Session serverSession; + protected Connection clientConnection; + protected Session clientSession; + protected Destination serverDestination; + protected int messagesToSend = 10; + protected boolean deleteTempQueue = true; + protected boolean serverTransactional = false; + protected boolean clientTransactional = false; + protected int numConsumers = 1; + protected int numProducers = 1; - public void testConcurrentProducerRequestReply() throws Exception { - numProducers = 10; - testLoadRequestReply(); - } - - public void testLoadRequestReply() throws Exception { - for (int i = 0; i < numConsumers; i++) { - serverSession.createConsumer(serverDestination).setMessageListener(new MessageListener() { - @Override - public void onMessage(Message msg) { - try { - Destination replyTo = msg.getJMSReplyTo(); - MessageProducer producer = serverSession.createProducer(replyTo); - producer.send(replyTo, msg); - if (serverTransactional) { - serverSession.commit(); - } - producer.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - } - - class Producer extends Thread { - private final int numToSend; - - public Producer(int numToSend) { - this.numToSend = numToSend; - } + public void testConcurrentProducerRequestReply() throws Exception { + numProducers = 10; + testLoadRequestReply(); + } + public void testLoadRequestReply() throws Exception { + for (int i = 0; i < numConsumers; i++) { + serverSession.createConsumer(serverDestination).setMessageListener(new MessageListener() { @Override - public void run() { - try { - Session session = clientConnection.createSession(clientTransactional, clientTransactional ? - Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(serverDestination); - - for (int i = 0; i < numToSend; i++) { - TemporaryQueue replyTo = session.createTemporaryQueue(); - MessageConsumer consumer = session.createConsumer(replyTo); - Message msg = session.createMessage(); - msg.setJMSReplyTo(replyTo); - producer.send(msg); - if (clientTransactional) { - session.commit(); - } - consumer.receive(); - if (clientTransactional) { - session.commit(); - } - consumer.close(); - if (deleteTempQueue) { - replyTo.delete(); - } else { - // temp queue will be cleaned up on clientConnection.close - } - } - } catch (JMSException e) { - e.printStackTrace(); - } + public void onMessage(Message msg) { + try { + Destination replyTo = msg.getJMSReplyTo(); + MessageProducer producer = serverSession.createProducer(replyTo); + producer.send(replyTo, msg); + if (serverTransactional) { + serverSession.commit(); + } + producer.close(); + } + catch (Exception e) { + e.printStackTrace(); + } } - } - Vector threads = new Vector(numProducers); - for (int i = 0; i < numProducers; i++) { - threads.add(new Producer(messagesToSend / numProducers)); - } - startAndJoinThreads(threads); + }); + } - clientSession.close(); - serverSession.close(); - clientConnection.close(); - serverConnection.close(); + class Producer extends Thread { - AdvisoryBroker ab = (AdvisoryBroker) broker.getBroker().getAdaptor(AdvisoryBroker.class); + private final int numToSend; - // The server destination will be left - assertTrue(ab.getAdvisoryDestinations().size() == 1); + public Producer(int numToSend) { + this.numToSend = numToSend; + } - assertTrue("should be zero but is " + ab.getAdvisoryConsumers().size(), ab.getAdvisoryConsumers().size() == 0); - assertTrue("should be zero but is " + ab.getAdvisoryProducers().size(), ab.getAdvisoryProducers().size() == 0); + @Override + public void run() { + try { + Session session = clientConnection.createSession(clientTransactional, clientTransactional ? Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(serverDestination); - RegionBroker rb = (RegionBroker) broker.getBroker().getAdaptor(RegionBroker.class); + for (int i = 0; i < numToSend; i++) { + TemporaryQueue replyTo = session.createTemporaryQueue(); + MessageConsumer consumer = session.createConsumer(replyTo); + Message msg = session.createMessage(); + msg.setJMSReplyTo(replyTo); + producer.send(msg); + if (clientTransactional) { + session.commit(); + } + consumer.receive(); + if (clientTransactional) { + session.commit(); + } + consumer.close(); + if (deleteTempQueue) { + replyTo.delete(); + } + else { + // temp queue will be cleaned up on clientConnection.close + } + } + } + catch (JMSException e) { + e.printStackTrace(); + } + } + } + Vector threads = new Vector(numProducers); + for (int i = 0; i < numProducers; i++) { + threads.add(new Producer(messagesToSend / numProducers)); + } + startAndJoinThreads(threads); - assertTrue(rb.getDestinationMap().size() >= 6); - } + clientSession.close(); + serverSession.close(); + clientConnection.close(); + serverConnection.close(); - private void startAndJoinThreads(Vector threads) throws Exception { - for (Thread thread : threads) { - thread.start(); - } - for (Thread thread : threads) { - thread.join(); - } - } + AdvisoryBroker ab = (AdvisoryBroker) broker.getBroker().getAdaptor(AdvisoryBroker.class); - @Override - protected void setUp() throws Exception { - super.setUp(); - serverConnection = createConnection(); - serverConnection.start(); - serverSession = serverConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - clientConnection = createConnection(); - clientConnection.start(); - clientSession = clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - serverDestination = createDestination(); - } + // The server destination will be left + assertTrue(ab.getAdvisoryDestinations().size() == 1); - @Override - protected void tearDown() throws Exception { - super.tearDown(); - serverTransactional = clientTransactional = false; - numConsumers = numProducers = 1; - messagesToSend = 2000; - } + assertTrue("should be zero but is " + ab.getAdvisoryConsumers().size(), ab.getAdvisoryConsumers().size() == 0); + assertTrue("should be zero but is " + ab.getAdvisoryProducers().size(), ab.getAdvisoryProducers().size() == 0); - @Override - protected ActiveMQDestination createDestination() { - return new ActiveMQQueue(getClass().getName()); - } + RegionBroker rb = (RegionBroker) broker.getBroker().getAdaptor(RegionBroker.class); + + assertTrue(rb.getDestinationMap().size() >= 6); + } + + private void startAndJoinThreads(Vector threads) throws Exception { + for (Thread thread : threads) { + thread.start(); + } + for (Thread thread : threads) { + thread.join(); + } + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + serverConnection = createConnection(); + serverConnection.start(); + serverSession = serverConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + clientConnection = createConnection(); + clientConnection.start(); + clientSession = clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + serverDestination = createDestination(); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + serverTransactional = clientTransactional = false; + numConsumers = numProducers = 1; + messagesToSend = 2000; + } + + @Override + protected ActiveMQDestination createDestination() { + return new ActiveMQQueue(getClass().getName()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/BlobTransferPolicyUriTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/BlobTransferPolicyUriTest.java index 40405699b2..940d03ac9c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/BlobTransferPolicyUriTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/BlobTransferPolicyUriTest.java @@ -17,16 +17,18 @@ package org.apache.activemq.blob; import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; /** - * + * */ public class BlobTransferPolicyUriTest extends TestCase { - public void testBlobTransferPolicyIsConfiguredViaUri() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?jms.blobTransferPolicy.defaultUploadUrl=http://foo.com"); - BlobTransferPolicy policy = factory.getBlobTransferPolicy(); - assertEquals("http://foo.com", policy.getDefaultUploadUrl()); - assertEquals("http://foo.com", policy.getUploadUrl()); - } + + public void testBlobTransferPolicyIsConfiguredViaUri() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?jms.blobTransferPolicy.defaultUploadUrl=http://foo.com"); + BlobTransferPolicy policy = factory.getBlobTransferPolicy(); + assertEquals("http://foo.com", policy.getDefaultUploadUrl()); + assertEquals("http://foo.com", policy.getUploadUrl()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPBlobDownloadStrategyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPBlobDownloadStrategyTest.java index 0875a5b3c8..43e463945c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPBlobDownloadStrategyTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPBlobDownloadStrategyTest.java @@ -28,81 +28,86 @@ import org.apache.activemq.command.ActiveMQBlobMessage; public class FTPBlobDownloadStrategyTest extends FTPTestSupport { - final int FILE_SIZE = Short.MAX_VALUE * 10; + final int FILE_SIZE = Short.MAX_VALUE * 10; - public void testDownload() throws Exception { - setConnection(); + public void testDownload() throws Exception { + setConnection(); - // create file - File uploadFile = new File(ftpHomeDirFile, "test.txt"); - FileWriter wrt = new FileWriter(uploadFile); + // create file + File uploadFile = new File(ftpHomeDirFile, "test.txt"); + FileWriter wrt = new FileWriter(uploadFile); - wrt.write("hello world"); + wrt.write("hello world"); - for(int ix = 0; ix < FILE_SIZE; ++ix ) { - wrt.write("a"); - } + for (int ix = 0; ix < FILE_SIZE; ++ix) { + wrt.write("a"); + } - wrt.close(); + wrt.close(); - ActiveMQBlobMessage message = new ActiveMQBlobMessage(); - BlobDownloadStrategy strategy = new FTPBlobDownloadStrategy(new BlobTransferPolicy()); - InputStream stream; - try { - message.setURL(new URL(ftpUrl + "test.txt")); - stream = strategy.getInputStream(message); - int i = stream.read(); - StringBuilder sb = new StringBuilder(2048); - while(i != -1) { - sb.append((char)i); - i = stream.read(); - } - assertEquals("hello world", sb.toString().substring(0, "hello world".length())); - assertEquals(FILE_SIZE, sb.toString().substring("hello world".length()).length()); + ActiveMQBlobMessage message = new ActiveMQBlobMessage(); + BlobDownloadStrategy strategy = new FTPBlobDownloadStrategy(new BlobTransferPolicy()); + InputStream stream; + try { + message.setURL(new URL(ftpUrl + "test.txt")); + stream = strategy.getInputStream(message); + int i = stream.read(); + StringBuilder sb = new StringBuilder(2048); + while (i != -1) { + sb.append((char) i); + i = stream.read(); + } + assertEquals("hello world", sb.toString().substring(0, "hello world".length())); + assertEquals(FILE_SIZE, sb.toString().substring("hello world".length()).length()); - assertTrue(uploadFile.exists()); - strategy.deleteFile(message); - assertFalse(uploadFile.exists()); + assertTrue(uploadFile.exists()); + strategy.deleteFile(message); + assertFalse(uploadFile.exists()); - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } + } + catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } - public void testWrongAuthentification() throws MalformedURLException { - ActiveMQBlobMessage message = new ActiveMQBlobMessage(); - BlobDownloadStrategy strategy = new FTPBlobDownloadStrategy(new BlobTransferPolicy()); - try { - message.setURL(new URL("ftp://" + userNamePass + "_wrong:" + userNamePass + "@localhost:" + ftpPort + "/ftptest/")); - strategy.getInputStream(message); - } catch(JMSException e) { - assertEquals("Wrong Exception", "Cant Authentificate to FTP-Server", e.getMessage()); - return; - } catch(Exception e) { - System.out.println(e); - assertTrue("Wrong Exception "+ e, false); - return; - } + public void testWrongAuthentification() throws MalformedURLException { + ActiveMQBlobMessage message = new ActiveMQBlobMessage(); + BlobDownloadStrategy strategy = new FTPBlobDownloadStrategy(new BlobTransferPolicy()); + try { + message.setURL(new URL("ftp://" + userNamePass + "_wrong:" + userNamePass + "@localhost:" + ftpPort + "/ftptest/")); + strategy.getInputStream(message); + } + catch (JMSException e) { + assertEquals("Wrong Exception", "Cant Authentificate to FTP-Server", e.getMessage()); + return; + } + catch (Exception e) { + System.out.println(e); + assertTrue("Wrong Exception " + e, false); + return; + } - assertTrue("Expect Exception", false); - } + assertTrue("Expect Exception", false); + } - public void testWrongFTPPort() throws MalformedURLException { - ActiveMQBlobMessage message = new ActiveMQBlobMessage(); - BlobDownloadStrategy strategy = new FTPBlobDownloadStrategy(new BlobTransferPolicy()); - try { - message.setURL(new URL("ftp://" + userNamePass + ":" + userNamePass + "@localhost:" + 422 + "/ftptest/")); - strategy.getInputStream(message); - } catch(JMSException e) { - assertEquals("Wrong Exception", "Problem connecting the FTP-server", e.getMessage()); - return; - } catch(Exception e) { - e.printStackTrace(); - assertTrue("Wrong Exception "+ e, false); - return; - } + public void testWrongFTPPort() throws MalformedURLException { + ActiveMQBlobMessage message = new ActiveMQBlobMessage(); + BlobDownloadStrategy strategy = new FTPBlobDownloadStrategy(new BlobTransferPolicy()); + try { + message.setURL(new URL("ftp://" + userNamePass + ":" + userNamePass + "@localhost:" + 422 + "/ftptest/")); + strategy.getInputStream(message); + } + catch (JMSException e) { + assertEquals("Wrong Exception", "Problem connecting the FTP-server", e.getMessage()); + return; + } + catch (Exception e) { + e.printStackTrace(); + assertTrue("Wrong Exception " + e, false); + return; + } - assertTrue("Expect Exception", false); - } + assertTrue("Expect Exception", false); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPBlobTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPBlobTest.java index 4aecc09529..57387fb052 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPBlobTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPBlobTest.java @@ -32,44 +32,43 @@ import org.apache.activemq.command.ActiveMQBlobMessage; public class FTPBlobTest extends FTPTestSupport { - public void testBlobFile() throws Exception { - setConnection(); - // first create Message - File file = File.createTempFile("amq-data-file-", ".dat"); - // lets write some data - String content = "hello world " + System.currentTimeMillis(); - BufferedWriter writer = new BufferedWriter(new FileWriter(file)); - writer.append(content); - writer.close(); + public void testBlobFile() throws Exception { + setConnection(); + // first create Message + File file = File.createTempFile("amq-data-file-", ".dat"); + // lets write some data + String content = "hello world " + System.currentTimeMillis(); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.append(content); + writer.close(); - ActiveMQSession session = (ActiveMQSession) connection.createSession( - false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - MessageConsumer consumer = session.createConsumer(destination); - BlobMessage message = session.createBlobMessage(file); - message.setName("fileName"); + ActiveMQSession session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + MessageConsumer consumer = session.createConsumer(destination); + BlobMessage message = session.createBlobMessage(file); + message.setName("fileName"); - producer.send(message); - Thread.sleep(1000); + producer.send(message); + Thread.sleep(1000); - // check message send - Message msg = consumer.receive(1000); - assertTrue(msg instanceof ActiveMQBlobMessage); + // check message send + Message msg = consumer.receive(1000); + assertTrue(msg instanceof ActiveMQBlobMessage); - assertEquals("name is correct", "fileName", ((ActiveMQBlobMessage)msg).getName()); - InputStream input = ((ActiveMQBlobMessage) msg).getInputStream(); - StringBuilder b = new StringBuilder(); - int i = input.read(); - while (i != -1) { - b.append((char) i); - i = input.read(); - } - input.close(); - File uploaded = new File(ftpHomeDirFile, msg.getJMSMessageID().toString().replace(":", "_")); - assertEquals(content, b.toString()); - assertTrue(uploaded.exists()); - ((ActiveMQBlobMessage)msg).deleteFile(); - assertFalse(uploaded.exists()); - } + assertEquals("name is correct", "fileName", ((ActiveMQBlobMessage) msg).getName()); + InputStream input = ((ActiveMQBlobMessage) msg).getInputStream(); + StringBuilder b = new StringBuilder(); + int i = input.read(); + while (i != -1) { + b.append((char) i); + i = input.read(); + } + input.close(); + File uploaded = new File(ftpHomeDirFile, msg.getJMSMessageID().toString().replace(":", "_")); + assertEquals(content, b.toString()); + assertTrue(uploaded.exists()); + ((ActiveMQBlobMessage) msg).deleteFile(); + assertFalse(uploaded.exists()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPBlobUploadStrategyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPBlobUploadStrategyTest.java index cac9a0aabd..b8238c7612 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPBlobUploadStrategyTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPBlobUploadStrategyTest.java @@ -27,49 +27,49 @@ import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQSession; import org.apache.activemq.command.ActiveMQBlobMessage; - public class FTPBlobUploadStrategyTest extends FTPTestSupport { - public void testFileUpload() throws Exception { - setConnection(); - File file = File.createTempFile("amq-data-file-", ".dat"); - // lets write some data - BufferedWriter writer = new BufferedWriter(new FileWriter(file)); - writer.append("hello world"); - writer.close(); + public void testFileUpload() throws Exception { + setConnection(); + File file = File.createTempFile("amq-data-file-", ".dat"); + // lets write some data + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.append("hello world"); + writer.close(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ((ActiveMQConnection)connection).setCopyMessageOnSend(false); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ((ActiveMQConnection) connection).setCopyMessageOnSend(false); - ActiveMQBlobMessage message = (ActiveMQBlobMessage) ((ActiveMQSession)session).createBlobMessage(file); - message.setJMSMessageID("testmessage"); - message.onSend(); - assertEquals(ftpUrl + "ID_testmessage", message.getURL().toString()); - File uploaded = new File(ftpHomeDirFile, "ID_testmessage"); - assertTrue("File doesn't exists", uploaded.exists()); - } + ActiveMQBlobMessage message = (ActiveMQBlobMessage) ((ActiveMQSession) session).createBlobMessage(file); + message.setJMSMessageID("testmessage"); + message.onSend(); + assertEquals(ftpUrl + "ID_testmessage", message.getURL().toString()); + File uploaded = new File(ftpHomeDirFile, "ID_testmessage"); + assertTrue("File doesn't exists", uploaded.exists()); + } - public void testWriteDenied() throws Exception { - userNamePass = "guest"; - setConnection(); - File file = File.createTempFile("amq-data-file-", ".dat"); - // lets write some data - BufferedWriter writer = new BufferedWriter(new FileWriter(file)); - writer.append("hello world"); - writer.close(); + public void testWriteDenied() throws Exception { + userNamePass = "guest"; + setConnection(); + File file = File.createTempFile("amq-data-file-", ".dat"); + // lets write some data + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.append("hello world"); + writer.close(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ((ActiveMQConnection)connection).setCopyMessageOnSend(false); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ((ActiveMQConnection) connection).setCopyMessageOnSend(false); - ActiveMQBlobMessage message = (ActiveMQBlobMessage) ((ActiveMQSession)session).createBlobMessage(file); - message.setJMSMessageID("testmessage"); - try { - message.onSend(); - } catch (JMSException e) { - e.printStackTrace(); - return; - } - fail("Should have failed with permission denied exception!"); - } + ActiveMQBlobMessage message = (ActiveMQBlobMessage) ((ActiveMQSession) session).createBlobMessage(file); + message.setJMSMessageID("testmessage"); + try { + message.onSend(); + } + catch (JMSException e) { + e.printStackTrace(); + return; + } + fail("Should have failed with permission denied exception!"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPTestSupport.java index 6145f3be06..8d66d46565 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPTestSupport.java @@ -35,90 +35,80 @@ import org.apache.ftpserver.usermanager.impl.WritePermission; import org.jmock.Mockery; public abstract class FTPTestSupport extends EmbeddedBrokerTestSupport { - - protected static final String ftpServerListenerName = "default"; - protected Connection connection; - protected FtpServer server; - String userNamePass = "activemq"; - Mockery context = null; - String ftpUrl; - int ftpPort; - - final File ftpHomeDirFile = new File("target/FTPBlobTest/ftptest"); - - protected void setUp() throws Exception { - - if (ftpHomeDirFile.getParentFile().exists()) { - IOHelper.deleteFile(ftpHomeDirFile.getParentFile()); - } - ftpHomeDirFile.mkdirs(); - ftpHomeDirFile.getParentFile().deleteOnExit(); + protected static final String ftpServerListenerName = "default"; + protected Connection connection; + protected FtpServer server; + String userNamePass = "activemq"; - FtpServerFactory serverFactory = new FtpServerFactory(); - ListenerFactory factory = new ListenerFactory(); + Mockery context = null; + String ftpUrl; + int ftpPort; - PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory(); - UserManager userManager = userManagerFactory.createUserManager(); + final File ftpHomeDirFile = new File("target/FTPBlobTest/ftptest"); - BaseUser user = new BaseUser(); - user.setName("activemq"); - user.setPassword("activemq"); - user.setHomeDirectory(ftpHomeDirFile.getParent()); - - // authorize user - List auths = new ArrayList(); - Authority auth = new WritePermission(); - auths.add(auth); - user.setAuthorities(auths); - - userManager.save(user); + protected void setUp() throws Exception { - BaseUser guest = new BaseUser(); - guest.setName("guest"); - guest.setPassword("guest"); - guest.setHomeDirectory(ftpHomeDirFile.getParent()); - - userManager.save(guest); - - serverFactory.setUserManager(userManager); - factory.setPort(0); - serverFactory.addListener(ftpServerListenerName, factory - .createListener()); - server = serverFactory.createServer(); - server.start(); - ftpPort = serverFactory.getListener(ftpServerListenerName) - .getPort(); - super.setUp(); - } - - public void setConnection() throws Exception { - ftpUrl = "ftp://" - + userNamePass - + ":" - + userNamePass - + "@localhost:" - + ftpPort - + "/ftptest/"; - bindAddress = "vm://localhost?jms.blobTransferPolicy.defaultUploadUrl=" + ftpUrl; - - connectionFactory = createConnectionFactory(); - - connection = createConnection(); - connection.start(); - } - - protected void tearDown() throws Exception { - if (connection != null) { - connection.stop(); - } - super.tearDown(); - if (server != null) { - server.stop(); - } - IOHelper.deleteFile(ftpHomeDirFile.getParentFile()); - } + if (ftpHomeDirFile.getParentFile().exists()) { + IOHelper.deleteFile(ftpHomeDirFile.getParentFile()); + } + ftpHomeDirFile.mkdirs(); + ftpHomeDirFile.getParentFile().deleteOnExit(); + + FtpServerFactory serverFactory = new FtpServerFactory(); + ListenerFactory factory = new ListenerFactory(); + + PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory(); + UserManager userManager = userManagerFactory.createUserManager(); + + BaseUser user = new BaseUser(); + user.setName("activemq"); + user.setPassword("activemq"); + user.setHomeDirectory(ftpHomeDirFile.getParent()); + + // authorize user + List auths = new ArrayList(); + Authority auth = new WritePermission(); + auths.add(auth); + user.setAuthorities(auths); + + userManager.save(user); + + BaseUser guest = new BaseUser(); + guest.setName("guest"); + guest.setPassword("guest"); + guest.setHomeDirectory(ftpHomeDirFile.getParent()); + + userManager.save(guest); + + serverFactory.setUserManager(userManager); + factory.setPort(0); + serverFactory.addListener(ftpServerListenerName, factory.createListener()); + server = serverFactory.createServer(); + server.start(); + ftpPort = serverFactory.getListener(ftpServerListenerName).getPort(); + super.setUp(); + } + + public void setConnection() throws Exception { + ftpUrl = "ftp://" + userNamePass + ":" + userNamePass + "@localhost:" + ftpPort + "/ftptest/"; + bindAddress = "vm://localhost?jms.blobTransferPolicy.defaultUploadUrl=" + ftpUrl; + + connectionFactory = createConnectionFactory(); + + connection = createConnection(); + connection.start(); + } + + protected void tearDown() throws Exception { + if (connection != null) { + connection.stop(); + } + super.tearDown(); + if (server != null) { + server.stop(); + } + IOHelper.deleteFile(ftpHomeDirFile.getParentFile()); + } - - } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FilesystemBlobTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FilesystemBlobTest.java index 1754689c71..51949bbbb4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FilesystemBlobTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FilesystemBlobTest.java @@ -35,70 +35,70 @@ import org.apache.activemq.util.IOHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - public class FilesystemBlobTest extends EmbeddedBrokerTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(FilesystemBlobTest.class); - private Connection connection; - private final String tmpDir = System.getProperty("user.dir") + "/target/FilesystemBlobTest"; - @Override - public void setUp() throws Exception { - super.setUp(); - // replace \ with / to let it work on windows too - String fileUrl = "file:///" +tmpDir.replaceAll("\\\\", "/"); - LOG.info("Using file: " + fileUrl); - bindAddress = "vm://localhost?jms.blobTransferPolicy.defaultUploadUrl=" + fileUrl; + private static final Logger LOG = LoggerFactory.getLogger(FilesystemBlobTest.class); - connectionFactory = createConnectionFactory(); + private Connection connection; + private final String tmpDir = System.getProperty("user.dir") + "/target/FilesystemBlobTest"; - connection = createConnection(); - connection.start(); - } + @Override + public void setUp() throws Exception { + super.setUp(); + // replace \ with / to let it work on windows too + String fileUrl = "file:///" + tmpDir.replaceAll("\\\\", "/"); + LOG.info("Using file: " + fileUrl); + bindAddress = "vm://localhost?jms.blobTransferPolicy.defaultUploadUrl=" + fileUrl; - public void testBlobFile() throws Exception { - // first create Message - File file = File.createTempFile("amq-data-file-", ".dat"); - // lets write some data - String content = "hello world " + System.currentTimeMillis(); - BufferedWriter writer = new BufferedWriter(new FileWriter(file)); - writer.append(content); - writer.close(); + connectionFactory = createConnectionFactory(); - ActiveMQSession session = (ActiveMQSession) connection.createSession( - false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - MessageConsumer consumer = session.createConsumer(destination); - BlobMessage message = session.createBlobMessage(file); + connection = createConnection(); + connection.start(); + } - producer.send(message); - Thread.sleep(1000); + public void testBlobFile() throws Exception { + // first create Message + File file = File.createTempFile("amq-data-file-", ".dat"); + // lets write some data + String content = "hello world " + System.currentTimeMillis(); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.append(content); + writer.close(); - // check message send - Message msg = consumer.receive(1000); - assertTrue(msg instanceof ActiveMQBlobMessage); + ActiveMQSession session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + MessageConsumer consumer = session.createConsumer(destination); + BlobMessage message = session.createBlobMessage(file); - InputStream input = ((ActiveMQBlobMessage) msg).getInputStream(); - StringBuilder b = new StringBuilder(); - int i = input.read(); - while (i != -1) { - b.append((char) i); - i = input.read(); - } - input.close(); - File uploaded = new File(tmpDir, msg.getJMSMessageID().toString().replace(":", "_")); - assertEquals(content, b.toString()); - assertTrue(uploaded.exists()); - ((ActiveMQBlobMessage)msg).deleteFile(); - assertFalse(uploaded.exists()); - } + producer.send(message); + Thread.sleep(1000); - @Override - protected void tearDown() throws Exception { - if (connection != null) { - connection.stop(); - } - super.tearDown(); + // check message send + Message msg = consumer.receive(1000); + assertTrue(msg instanceof ActiveMQBlobMessage); - IOHelper.deleteFile(new File(tmpDir)); - } + InputStream input = ((ActiveMQBlobMessage) msg).getInputStream(); + StringBuilder b = new StringBuilder(); + int i = input.read(); + while (i != -1) { + b.append((char) i); + i = input.read(); + } + input.close(); + File uploaded = new File(tmpDir, msg.getJMSMessageID().toString().replace(":", "_")); + assertEquals(content, b.toString()); + assertTrue(uploaded.exists()); + ((ActiveMQBlobMessage) msg).deleteFile(); + assertFalse(uploaded.exists()); + } + + @Override + protected void tearDown() throws Exception { + if (connection != null) { + connection.stop(); + } + super.tearDown(); + + IOHelper.deleteFile(new File(tmpDir)); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/AMQ4351Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/AMQ4351Test.java index e810f920de..408159393f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/AMQ4351Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/AMQ4351Test.java @@ -17,6 +17,7 @@ package org.apache.activemq.broker; import junit.framework.Test; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.command.ActiveMQTopic; import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter; @@ -41,220 +42,229 @@ import java.util.concurrent.atomic.AtomicLong; */ public class AMQ4351Test extends BrokerTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(AMQ4351Test.class); + private static final Logger LOG = LoggerFactory.getLogger(AMQ4351Test.class); - public static Test suite() { - return suite(AMQ4351Test.class); - } + public static Test suite() { + return suite(AMQ4351Test.class); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); + protected BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); - // Lets clean up often. - broker.setOfflineDurableSubscriberTaskSchedule(500); - broker.setOfflineDurableSubscriberTimeout(2000); // lets delete durable subs much faster. + // Lets clean up often. + broker.setOfflineDurableSubscriberTaskSchedule(500); + broker.setOfflineDurableSubscriberTimeout(2000); // lets delete durable subs much faster. - JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); - EmbeddedDataSource dataSource = new EmbeddedDataSource(); - dataSource.setDatabaseName("derbyDb"); - dataSource.setCreateDatabase("create"); - jdbc.setDataSource(dataSource); + JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); + EmbeddedDataSource dataSource = new EmbeddedDataSource(); + dataSource.setDatabaseName("derbyDb"); + dataSource.setCreateDatabase("create"); + jdbc.setDataSource(dataSource); - jdbc.deleteAllMessages(); - broker.setPersistenceAdapter(jdbc); - return broker; - } + jdbc.deleteAllMessages(); + broker.setPersistenceAdapter(jdbc); + return broker; + } - ActiveMQConnectionFactory connectionFactory; - ActiveMQTopic destination = new ActiveMQTopic("TEST"); + ActiveMQConnectionFactory connectionFactory; + ActiveMQTopic destination = new ActiveMQTopic("TEST"); - @Override - protected void setUp() throws Exception { - super.setUp(); - connectionFactory = new ActiveMQConnectionFactory(broker.getVmConnectorURI()); - } + @Override + protected void setUp() throws Exception { + super.setUp(); + connectionFactory = new ActiveMQConnectionFactory(broker.getVmConnectorURI()); + } - class ProducingClient implements Runnable { - final AtomicLong size = new AtomicLong(); - final AtomicBoolean done = new AtomicBoolean(); - CountDownLatch doneLatch = new CountDownLatch(1); + class ProducingClient implements Runnable { - Connection connection; - Session session; - MessageProducer producer; + final AtomicLong size = new AtomicLong(); + final AtomicBoolean done = new AtomicBoolean(); + CountDownLatch doneLatch = new CountDownLatch(1); - ProducingClient() throws JMSException { - connection = connectionFactory.createConnection(); + Connection connection; + Session session; + MessageProducer producer; + + ProducingClient() throws JMSException { + connection = connectionFactory.createConnection(); + connection.start(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer = session.createProducer(destination); + } + + private void sendMessage() { + try { + producer.send(session.createTextMessage("Test")); + long i = size.incrementAndGet(); + if ((i % 1000) == 0) { + LOG.info("produced " + i + "."); + } + } + catch (JMSException e) { + e.printStackTrace(); + } + } + + public void start() { + new Thread(this, "ProducingClient").start(); + } + + public void stop() throws InterruptedException { + done.set(true); + if (!doneLatch.await(20, TimeUnit.MILLISECONDS)) { + try { + connection.close(); + doneLatch.await(); + } + catch (JMSException e) { + } + } + } + + @Override + public void run() { + try { + try { + while (!done.get()) { + sendMessage(); + Thread.sleep(10); + } + } + finally { + connection.close(); + } + } + catch (Exception e) { + e.printStackTrace(); + done.set(true); + } + finally { + doneLatch.countDown(); + } + } + } + + class ConsumingClient implements Runnable { + + final String name; + final AtomicLong size = new AtomicLong(); + final AtomicBoolean done = new AtomicBoolean(); + CountDownLatch doneLatch = new CountDownLatch(1); + CountDownLatch started; + CountDownLatch finished; + + public ConsumingClient(String name, CountDownLatch started, CountDownLatch finished) { + this.name = name; + this.started = started; + this.finished = finished; + } + + public void start() { + LOG.info("Starting JMS listener " + name); + new Thread(this, "ConsumingClient: " + name).start(); + } + + public void stopAsync() { + finished.countDown(); + done.set(true); + } + + public void stop() throws InterruptedException { + stopAsync(); + doneLatch.await(); + } + + @Override + public void run() { + try { + Connection connection = connectionFactory.createConnection(); + connection.setClientID(name); connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(destination); - } - - private void sendMessage() { try { - producer.send(session.createTextMessage("Test")); - long i = size.incrementAndGet(); - if( (i % 1000) == 0 ) { - LOG.info("produced " + i + "."); - } - } catch (JMSException e) { - e.printStackTrace(); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageConsumer consumer = session.createDurableSubscriber(destination, name, null, false); + started.countDown(); + while (!done.get()) { + Message msg = consumer.receive(100); + if (msg != null) { + size.incrementAndGet(); + session.commit(); + } + } } - } - - public void start() { - new Thread(this, "ProducingClient").start(); - } - - public void stop() throws InterruptedException { + finally { + connection.close(); + LOG.info("Stopped JMS listener " + name); + } + } + catch (Exception e) { + e.printStackTrace(); done.set(true); - if( !doneLatch.await(20, TimeUnit.MILLISECONDS) ) { - try { - connection.close(); - doneLatch.await(); - } catch (JMSException e) { - } - } - } + } + finally { + doneLatch.countDown(); + } + } - @Override - public void run() { - try { - try { - while (!done.get()) { - sendMessage(); - Thread.sleep(10); - } - } finally { - connection.close(); - } - } catch (Exception e) { - e.printStackTrace(); - done.set(true); - } finally { - doneLatch.countDown(); - } - } - } + } - class ConsumingClient implements Runnable { - final String name; - final AtomicLong size = new AtomicLong(); - final AtomicBoolean done = new AtomicBoolean(); - CountDownLatch doneLatch = new CountDownLatch(1); - CountDownLatch started; - CountDownLatch finished; + public void testAMQ4351() throws InterruptedException, JMSException { + LOG.info("Start test."); + int subs = 100; + CountDownLatch startedLatch = new CountDownLatch(subs - 1); + CountDownLatch shutdownLatch = new CountDownLatch(subs - 4); + ProducingClient producer = new ProducingClient(); + ConsumingClient listener1 = new ConsumingClient("subscriber-1", startedLatch, shutdownLatch); + ConsumingClient listener2 = new ConsumingClient("subscriber-2", startedLatch, shutdownLatch); + ConsumingClient listener3 = new ConsumingClient("subscriber-3", startedLatch, shutdownLatch); + try { - public ConsumingClient(String name, CountDownLatch started, CountDownLatch finished) { - this.name = name; - this.started = started; - this.finished = finished; - } + listener1.start(); + listener2.start(); + listener3.start(); - public void start() { - LOG.info("Starting JMS listener " + name); - new Thread(this, "ConsumingClient: "+name).start(); - } + List subscribers = new ArrayList(subs); + for (int i = 4; i < subs; i++) { + ConsumingClient client = new ConsumingClient("subscriber-" + i, startedLatch, shutdownLatch); + subscribers.add(client); + client.start(); + } + startedLatch.await(10, TimeUnit.SECONDS); - public void stopAsync() { - finished.countDown(); - done.set(true); - } + LOG.info("All subscribers started."); + producer.sendMessage(); - public void stop() throws InterruptedException { - stopAsync(); - doneLatch.await(); - } + LOG.info("Stopping 97 subscribers...."); + for (ConsumingClient client : subscribers) { + client.stopAsync(); + } + shutdownLatch.await(10, TimeUnit.SECONDS); - @Override - public void run() { - try { - Connection connection = connectionFactory.createConnection(); - connection.setClientID(name); - connection.start(); - try { - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageConsumer consumer = session.createDurableSubscriber(destination, name, null, false); - started.countDown(); - while( !done.get() ) { - Message msg = consumer.receive(100); - if(msg!=null ) { - size.incrementAndGet(); - session.commit(); - } - } - } finally { - connection.close(); - LOG.info("Stopped JMS listener " + name); - } - } catch (Exception e) { - e.printStackTrace(); - done.set(true); - } finally { - doneLatch.countDown(); - } - } + // Start producing messages for 10 minutes, at high rate + LOG.info("Starting mass message producer..."); + producer.start(); - } - - public void testAMQ4351() throws InterruptedException, JMSException { - LOG.info("Start test."); - int subs = 100; - CountDownLatch startedLatch = new CountDownLatch(subs - 1); - CountDownLatch shutdownLatch = new CountDownLatch(subs - 4); - - - ProducingClient producer = new ProducingClient(); - ConsumingClient listener1 = new ConsumingClient("subscriber-1", startedLatch, shutdownLatch); - ConsumingClient listener2 = new ConsumingClient("subscriber-2", startedLatch, shutdownLatch); - ConsumingClient listener3 = new ConsumingClient("subscriber-3", startedLatch, shutdownLatch); - try { - - listener1.start(); - listener2.start(); - listener3.start(); - - List subscribers = new ArrayList(subs); - for (int i = 4; i < subs; i++) { - ConsumingClient client = new ConsumingClient("subscriber-" + i, startedLatch, shutdownLatch); - subscribers.add(client); - client.start(); - } - startedLatch.await(10, TimeUnit.SECONDS); - - LOG.info("All subscribers started."); - producer.sendMessage(); - - LOG.info("Stopping 97 subscribers...."); - for (ConsumingClient client : subscribers) { - client.stopAsync(); - } - shutdownLatch.await(10, TimeUnit.SECONDS); - - // Start producing messages for 10 minutes, at high rate - LOG.info("Starting mass message producer..."); - producer.start(); - - long lastSize = listener1.size.get(); - for( int i=0 ; i < 10; i++ ) { - Thread.sleep(1000); - long size = listener1.size.get(); - LOG.info("Listener 1: consumed: "+(size - lastSize)); - assertTrue( size > lastSize ); - lastSize = size; - } - } finally { - LOG.info("Stopping clients"); - listener1.stop(); - listener2.stop(); - listener3.stop(); - producer.stop(); - } - } + long lastSize = listener1.size.get(); + for (int i = 0; i < 10; i++) { + Thread.sleep(1000); + long size = listener1.size.get(); + LOG.info("Listener 1: consumed: " + (size - lastSize)); + assertTrue(size > lastSize); + lastSize = size; + } + } + finally { + LOG.info("Stopping clients"); + listener1.stop(); + listener2.stop(); + listener3.stop(); + producer.stop(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerBenchmark.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerBenchmark.java index 3e154f9a9a..cd616c24f9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerBenchmark.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerBenchmark.java @@ -20,6 +20,7 @@ import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicInteger; import junit.framework.Test; + import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTopic; @@ -41,153 +42,159 @@ import org.slf4j.LoggerFactory; * Queue vs. Topic, 1 vs. 10 producer threads, 1 vs. 10 consumer threads, and * Persistent vs. Non-Persistent messages. Message Acking uses client ack style * batch acking since that typically has the best ack performance. - * - * */ public class BrokerBenchmark extends BrokerTestSupport { - private static final transient Logger LOG = LoggerFactory.getLogger(BrokerBenchmark.class); - public int produceCount = Integer.parseInt(System.getProperty("PRODUCE_COUNT", "10000")); - public ActiveMQDestination destination; - public int prodcuerCount; - public int consumerCount; - public boolean deliveryMode; + private static final transient Logger LOG = LoggerFactory.getLogger(BrokerBenchmark.class); - public void initCombosForTestPerformance() { - addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST")}); - addCombinationValues("PRODUCER_COUNT", new Object[] {new Integer("1"), new Integer("10")}); - addCombinationValues("CONSUMER_COUNT", new Object[] {new Integer("1"), new Integer("10")}); - addCombinationValues("CONSUMER_COUNT", new Object[] {new Integer("1"), new Integer("10")}); - addCombinationValues("deliveryMode", new Object[] {Boolean.TRUE}); - } + public int produceCount = Integer.parseInt(System.getProperty("PRODUCE_COUNT", "10000")); + public ActiveMQDestination destination; + public int prodcuerCount; + public int consumerCount; + public boolean deliveryMode; - public void testPerformance() throws Exception { + public void initCombosForTestPerformance() { + addCombinationValues("destination", new Object[]{new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST")}); + addCombinationValues("PRODUCER_COUNT", new Object[]{new Integer("1"), new Integer("10")}); + addCombinationValues("CONSUMER_COUNT", new Object[]{new Integer("1"), new Integer("10")}); + addCombinationValues("CONSUMER_COUNT", new Object[]{new Integer("1"), new Integer("10")}); + addCombinationValues("deliveryMode", new Object[]{Boolean.TRUE}); + } - LOG.info("Running Benchmark for destination=" + destination + ", producers=" + prodcuerCount + ", consumers=" + consumerCount + ", deliveryMode=" + deliveryMode); - final int consumeCount = destination.isTopic() ? consumerCount * produceCount : produceCount; + public void testPerformance() throws Exception { - final Semaphore consumersStarted = new Semaphore(1 - consumerCount); - final Semaphore producersFinished = new Semaphore(1 - prodcuerCount); - final Semaphore consumersFinished = new Semaphore(1 - consumerCount); - final ProgressPrinter printer = new ProgressPrinter(produceCount + consumeCount, 10); + LOG.info("Running Benchmark for destination=" + destination + ", producers=" + prodcuerCount + ", consumers=" + consumerCount + ", deliveryMode=" + deliveryMode); + final int consumeCount = destination.isTopic() ? consumerCount * produceCount : produceCount; - // Start a producer and consumer + final Semaphore consumersStarted = new Semaphore(1 - consumerCount); + final Semaphore producersFinished = new Semaphore(1 - prodcuerCount); + final Semaphore consumersFinished = new Semaphore(1 - consumerCount); + final ProgressPrinter printer = new ProgressPrinter(produceCount + consumeCount, 10); - profilerPause("Benchmark ready. Start profiler "); + // Start a producer and consumer - long start = System.currentTimeMillis(); + profilerPause("Benchmark ready. Start profiler "); - final AtomicInteger receiveCounter = new AtomicInteger(0); - for (int i = 0; i < consumerCount; i++) { - new Thread() { - public void run() { - try { + long start = System.currentTimeMillis(); - // Consume the messages - StubConnection connection = new StubConnection(broker); - ConnectionInfo connectionInfo = createConnectionInfo(); - connection.send(connectionInfo); + final AtomicInteger receiveCounter = new AtomicInteger(0); + for (int i = 0; i < consumerCount; i++) { + new Thread() { + public void run() { + try { - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setPrefetchSize(1000); - connection.send(sessionInfo); - connection.send(consumerInfo); + // Consume the messages + StubConnection connection = new StubConnection(broker); + ConnectionInfo connectionInfo = createConnectionInfo(); + connection.send(connectionInfo); - consumersStarted.release(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + consumerInfo.setPrefetchSize(1000); + connection.send(sessionInfo); + connection.send(consumerInfo); - while (receiveCounter.get() < consumeCount) { + consumersStarted.release(); - int counter = 0; - // Get a least 1 message. - Message msg = receiveMessage(connection, 2000); - if (msg != null) { - printer.increment(); - receiveCounter.incrementAndGet(); + while (receiveCounter.get() < consumeCount) { - counter++; + int counter = 0; + // Get a least 1 message. + Message msg = receiveMessage(connection, 2000); + if (msg != null) { + printer.increment(); + receiveCounter.incrementAndGet(); - // Try to piggy back a few extra message acks if - // they are ready. - Message extra = null; - while ((extra = receiveMessage(connection, 0)) != null) { - msg = extra; - printer.increment(); - receiveCounter.incrementAndGet(); - counter++; - } - } + counter++; - if (msg != null) { - connection.send(createAck(consumerInfo, msg, counter, MessageAck.STANDARD_ACK_TYPE)); - } else if (receiveCounter.get() < consumeCount) { - LOG.info("Consumer stall, waiting for message #" + receiveCounter.get() + 1); - } + // Try to piggy back a few extra message acks if + // they are ready. + Message extra = null; + while ((extra = receiveMessage(connection, 0)) != null) { + msg = extra; + printer.increment(); + receiveCounter.incrementAndGet(); + counter++; } + } - connection.send(closeConsumerInfo(consumerInfo)); - } catch (Throwable e) { - e.printStackTrace(); - } finally { - consumersFinished.release(); - } - } + if (msg != null) { + connection.send(createAck(consumerInfo, msg, counter, MessageAck.STANDARD_ACK_TYPE)); + } + else if (receiveCounter.get() < consumeCount) { + LOG.info("Consumer stall, waiting for message #" + receiveCounter.get() + 1); + } + } - }.start(); - } + connection.send(closeConsumerInfo(consumerInfo)); + } + catch (Throwable e) { + e.printStackTrace(); + } + finally { + consumersFinished.release(); + } + } - // Make sure that the consumers are started first to avoid sending - // messages - // before a topic is subscribed so that those messages are not missed. - consumersStarted.acquire(); + }.start(); + } - // Send the messages in an async thread. - for (int i = 0; i < prodcuerCount; i++) { - new Thread() { - public void run() { - try { - StubConnection connection = new StubConnection(broker); - ConnectionInfo connectionInfo = createConnectionInfo(); - connection.send(connectionInfo); + // Make sure that the consumers are started first to avoid sending + // messages + // before a topic is subscribed so that those messages are not missed. + consumersStarted.acquire(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); + // Send the messages in an async thread. + for (int i = 0; i < prodcuerCount; i++) { + new Thread() { + public void run() { + try { + StubConnection connection = new StubConnection(broker); + ConnectionInfo connectionInfo = createConnectionInfo(); + connection.send(connectionInfo); - for (int i = 0; i < produceCount / prodcuerCount; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(deliveryMode); - message.setResponseRequired(false); - connection.send(message); - printer.increment(); - } - } catch (Throwable e) { - e.printStackTrace(); - } finally { - producersFinished.release(); - } - }; - }.start(); - } + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); - producersFinished.acquire(); - long end1 = System.currentTimeMillis(); - consumersFinished.acquire(); - long end2 = System.currentTimeMillis(); + for (int i = 0; i < produceCount / prodcuerCount; i++) { + Message message = createMessage(producerInfo, destination); + message.setPersistent(deliveryMode); + message.setResponseRequired(false); + connection.send(message); + printer.increment(); + } + } + catch (Throwable e) { + e.printStackTrace(); + } + finally { + producersFinished.release(); + } + } - LOG.info("Results for destination=" + destination + ", producers=" + prodcuerCount + ", consumers=" + consumerCount + ", deliveryMode=" + deliveryMode); - LOG.info("Produced at messages/sec: " + (produceCount * 1000.0 / (end1 - start))); - LOG.info("Consumed at messages/sec: " + (consumeCount * 1000.0 / (end2 - start))); - profilerPause("Benchmark done. Stop profiler "); - } + ; + }.start(); + } - public static Test suite() { - return suite(BrokerBenchmark.class); - } + producersFinished.acquire(); + long end1 = System.currentTimeMillis(); + consumersFinished.acquire(); + long end2 = System.currentTimeMillis(); - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + LOG.info("Results for destination=" + destination + ", producers=" + prodcuerCount + ", consumers=" + consumerCount + ", deliveryMode=" + deliveryMode); + LOG.info("Produced at messages/sec: " + (produceCount * 1000.0 / (end1 - start))); + LOG.info("Consumed at messages/sec: " + (consumeCount * 1000.0 / (end2 - start))); + profilerPause("Benchmark done. Stop profiler "); + } + + public static Test suite() { + return suite(BrokerBenchmark.class); + } + + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerRedeliveryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerRedeliveryTest.java index 1fc7a6aeb2..2d0da8b2ce 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerRedeliveryTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerRedeliveryTest.java @@ -21,6 +21,7 @@ import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; + import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQPrefetchPolicy; @@ -34,152 +35,151 @@ import org.slf4j.LoggerFactory; public class BrokerRedeliveryTest extends org.apache.activemq.TestSupport { - static final Logger LOG = LoggerFactory.getLogger(BrokerRedeliveryTest.class); - BrokerService broker = null; + static final Logger LOG = LoggerFactory.getLogger(BrokerRedeliveryTest.class); + BrokerService broker = null; - final ActiveMQQueue destination = new ActiveMQQueue("Redelivery"); - final String data = "hi"; - final long redeliveryDelayMillis = 2000; - long initialRedeliveryDelayMillis = 4000; - int maxBrokerRedeliveries = 2; + final ActiveMQQueue destination = new ActiveMQQueue("Redelivery"); + final String data = "hi"; + final long redeliveryDelayMillis = 2000; + long initialRedeliveryDelayMillis = 4000; + int maxBrokerRedeliveries = 2; - public void testScheduledRedelivery() throws Exception { - doTestScheduledRedelivery(maxBrokerRedeliveries, true); - } + public void testScheduledRedelivery() throws Exception { + doTestScheduledRedelivery(maxBrokerRedeliveries, true); + } - public void testInfiniteRedelivery() throws Exception { - initialRedeliveryDelayMillis = redeliveryDelayMillis; - maxBrokerRedeliveries = RedeliveryPolicy.NO_MAXIMUM_REDELIVERIES; - doTestScheduledRedelivery(RedeliveryPolicy.DEFAULT_MAXIMUM_REDELIVERIES + 1, false); - } + public void testInfiniteRedelivery() throws Exception { + initialRedeliveryDelayMillis = redeliveryDelayMillis; + maxBrokerRedeliveries = RedeliveryPolicy.NO_MAXIMUM_REDELIVERIES; + doTestScheduledRedelivery(RedeliveryPolicy.DEFAULT_MAXIMUM_REDELIVERIES + 1, false); + } - public void doTestScheduledRedelivery(int maxBrokerRedeliveriesToValidate, boolean validateDLQ) throws Exception { + public void doTestScheduledRedelivery(int maxBrokerRedeliveriesToValidate, boolean validateDLQ) throws Exception { - startBroker(true); - sendMessage(0); + startBroker(true); + sendMessage(0); - ActiveMQConnection consumerConnection = (ActiveMQConnection) createConnection(); - RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy(); - redeliveryPolicy.setInitialRedeliveryDelay(0); - redeliveryPolicy.setMaximumRedeliveries(0); - consumerConnection.setRedeliveryPolicy(redeliveryPolicy); - consumerConnection.start(); - Session consumerSession = consumerConnection.createSession(true, Session.SESSION_TRANSACTED); - MessageConsumer consumer = consumerSession.createConsumer(destination); - Message message = consumer.receive(1000); - assertNotNull("got message", message); - LOG.info("got: " + message); - consumerSession.rollback(); + ActiveMQConnection consumerConnection = (ActiveMQConnection) createConnection(); + RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy(); + redeliveryPolicy.setInitialRedeliveryDelay(0); + redeliveryPolicy.setMaximumRedeliveries(0); + consumerConnection.setRedeliveryPolicy(redeliveryPolicy); + consumerConnection.start(); + Session consumerSession = consumerConnection.createSession(true, Session.SESSION_TRANSACTED); + MessageConsumer consumer = consumerSession.createConsumer(destination); + Message message = consumer.receive(1000); + assertNotNull("got message", message); + LOG.info("got: " + message); + consumerSession.rollback(); - for (int i=0;i 0) { - producer.setTimeToLive(timeToLive); - } - Message message = producerSession.createMessage(); - message.setStringProperty("data", data); - producer.send(message); - producerConnection.close(); - } + private void sendMessage(int timeToLive) throws Exception { + ActiveMQConnection producerConnection = (ActiveMQConnection) createConnection(); + producerConnection.start(); + Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = producerSession.createProducer(destination); + if (timeToLive > 0) { + producer.setTimeToLive(timeToLive); + } + Message message = producerSession.createMessage(); + message.setStringProperty("data", data); + producer.send(message); + producerConnection.close(); + } - private void startBroker(boolean deleteMessages) throws Exception { - broker = new BrokerService(); - broker.setSchedulerSupport(true); + private void startBroker(boolean deleteMessages) throws Exception { + broker = new BrokerService(); + broker.setSchedulerSupport(true); + RedeliveryPlugin redeliveryPlugin = new RedeliveryPlugin(); - RedeliveryPlugin redeliveryPlugin = new RedeliveryPlugin(); + RedeliveryPolicy brokerRedeliveryPolicy = new RedeliveryPolicy(); + brokerRedeliveryPolicy.setRedeliveryDelay(redeliveryDelayMillis); + brokerRedeliveryPolicy.setInitialRedeliveryDelay(initialRedeliveryDelayMillis); + brokerRedeliveryPolicy.setMaximumRedeliveries(maxBrokerRedeliveries); - RedeliveryPolicy brokerRedeliveryPolicy = new RedeliveryPolicy(); - brokerRedeliveryPolicy.setRedeliveryDelay(redeliveryDelayMillis); - brokerRedeliveryPolicy.setInitialRedeliveryDelay(initialRedeliveryDelayMillis); - brokerRedeliveryPolicy.setMaximumRedeliveries(maxBrokerRedeliveries); + RedeliveryPolicyMap redeliveryPolicyMap = new RedeliveryPolicyMap(); + redeliveryPolicyMap.setDefaultEntry(brokerRedeliveryPolicy); + redeliveryPlugin.setRedeliveryPolicyMap(redeliveryPolicyMap); - RedeliveryPolicyMap redeliveryPolicyMap = new RedeliveryPolicyMap(); - redeliveryPolicyMap.setDefaultEntry(brokerRedeliveryPolicy); - redeliveryPlugin.setRedeliveryPolicyMap(redeliveryPolicyMap); + broker.setPlugins(new BrokerPlugin[]{redeliveryPlugin}); - broker.setPlugins(new BrokerPlugin[]{redeliveryPlugin}); + if (deleteMessages) { + broker.setDeleteAllMessagesOnStartup(true); + } + broker.start(); + } - if (deleteMessages) { - broker.setDeleteAllMessagesOnStartup(true); - } - broker.start(); - } + private void stopBroker() throws Exception { + if (broker != null) + broker.stop(); + broker = null; + } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory("vm://localhost"); + } - private void stopBroker() throws Exception { - if (broker != null) - broker.stop(); - broker = null; - } - - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://localhost"); - } - - @Override - protected void tearDown() throws Exception { - stopBroker(); - super.tearDown(); - } + @Override + protected void tearDown() throws Exception { + stopBroker(); + super.tearDown(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerRestartTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerRestartTestSupport.java index c4e3848803..be5720c811 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerRestartTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerRestartTestSupport.java @@ -24,44 +24,44 @@ import org.apache.activemq.util.IOHelper; public class BrokerRestartTestSupport extends BrokerTestSupport { - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - File dir = broker.getBrokerDataDirectory(); - if (dir != null) { - IOHelper.deleteChildren(dir); - } - broker.setDeleteAllMessagesOnStartup(true); - configureBroker(broker); - return broker; - } + @Override + protected BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); + File dir = broker.getBrokerDataDirectory(); + if (dir != null) { + IOHelper.deleteChildren(dir); + } + broker.setDeleteAllMessagesOnStartup(true); + configureBroker(broker); + return broker; + } - /** - * @return - * @throws Exception - */ - protected BrokerService createRestartedBroker() throws Exception { - BrokerService broker = new BrokerService(); - configureBroker(broker); - return broker; - } + /** + * @return + * @throws Exception + */ + protected BrokerService createRestartedBroker() throws Exception { + BrokerService broker = new BrokerService(); + configureBroker(broker); + return broker; + } - protected void configureBroker(BrokerService broker) throws Exception { - broker.setDestinationPolicy(policyMap); - } + protected void configureBroker(BrokerService broker) throws Exception { + broker.setDestinationPolicy(policyMap); + } - /** - * Simulates a broker restart. The memory based persistence adapter is - * reused so that it does not "loose" it's "persistent" messages. - * - * @throws IOException - * @throws URISyntaxException - */ - protected void restartBroker() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - broker = createRestartedBroker(); - broker.start(); - } + /** + * Simulates a broker restart. The memory based persistence adapter is + * reused so that it does not "loose" it's "persistent" messages. + * + * @throws IOException + * @throws URISyntaxException + */ + protected void restartBroker() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + broker = createRestartedBroker(); + broker.start(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerServiceTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerServiceTest.java index 9d55d04d48..2611c411e4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerServiceTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerServiceTest.java @@ -17,68 +17,68 @@ package org.apache.activemq.broker; import junit.framework.TestCase; + import org.apache.activemq.network.NetworkConnector; /** * Tests for the BrokerService class - * + * * @author chirino */ public class BrokerServiceTest extends TestCase { - public void testAddRemoveTransportsWithJMX() throws Exception { - BrokerService service = new BrokerService(); - service.setUseJmx(true); - service.setPersistent(false); - TransportConnector connector = service.addConnector("tcp://localhost:0"); - service.start(); + public void testAddRemoveTransportsWithJMX() throws Exception { + BrokerService service = new BrokerService(); + service.setUseJmx(true); + service.setPersistent(false); + TransportConnector connector = service.addConnector("tcp://localhost:0"); + service.start(); - service.removeConnector(connector); - connector.stop(); - service.stop(); - } + service.removeConnector(connector); + connector.stop(); + service.stop(); + } - public void testAddRemoveTransportsWithoutJMX() throws Exception { - BrokerService service = new BrokerService(); - service.setPersistent(false); - service.setUseJmx(false); - TransportConnector connector = service.addConnector("tcp://localhost:0"); - service.start(); + public void testAddRemoveTransportsWithoutJMX() throws Exception { + BrokerService service = new BrokerService(); + service.setPersistent(false); + service.setUseJmx(false); + TransportConnector connector = service.addConnector("tcp://localhost:0"); + service.start(); - service.removeConnector(connector); - connector.stop(); - service.stop(); - } + service.removeConnector(connector); + connector.stop(); + service.stop(); + } - public void testAddRemoveNetworkWithJMX() throws Exception { - BrokerService service = new BrokerService(); - service.setPersistent(false); - service.setUseJmx(true); - NetworkConnector connector = service.addNetworkConnector("multicast://default?group=group-"+System.currentTimeMillis()); - service.start(); + public void testAddRemoveNetworkWithJMX() throws Exception { + BrokerService service = new BrokerService(); + service.setPersistent(false); + service.setUseJmx(true); + NetworkConnector connector = service.addNetworkConnector("multicast://default?group=group-" + System.currentTimeMillis()); + service.start(); - service.removeNetworkConnector(connector); - connector.stop(); - service.stop(); - } + service.removeNetworkConnector(connector); + connector.stop(); + service.stop(); + } - public void testAddRemoveNetworkWithoutJMX() throws Exception { - BrokerService service = new BrokerService(); - service.setPersistent(false); - service.setUseJmx(false); - NetworkConnector connector = service.addNetworkConnector("multicast://default?group=group-"+System.currentTimeMillis()); - service.start(); + public void testAddRemoveNetworkWithoutJMX() throws Exception { + BrokerService service = new BrokerService(); + service.setPersistent(false); + service.setUseJmx(false); + NetworkConnector connector = service.addNetworkConnector("multicast://default?group=group-" + System.currentTimeMillis()); + service.start(); - service.removeNetworkConnector(connector); - connector.stop(); - service.stop(); - } - - public void testSystemUsage() - { - BrokerService service = new BrokerService(); - assertEquals( 1024 * 1024 * 1024, service.getSystemUsage().getMemoryUsage().getLimit() ); - assertEquals( 1024L * 1024 * 1024 * 50, service.getSystemUsage().getTempUsage().getLimit() ); - assertEquals( 1024L * 1024 * 1024 * 100, service.getSystemUsage().getStoreUsage().getLimit() ); - } + service.removeNetworkConnector(connector); + connector.stop(); + service.stop(); + } + + public void testSystemUsage() { + BrokerService service = new BrokerService(); + assertEquals(1024 * 1024 * 1024, service.getSystemUsage().getMemoryUsage().getLimit()); + assertEquals(1024L * 1024 * 1024 * 50, service.getSystemUsage().getTempUsage().getLimit()); + assertEquals(1024L * 1024 * 1024 * 100, service.getSystemUsage().getStoreUsage().getLimit()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerTest.java index fc3438e144..e225f00f8a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerTest.java @@ -37,1723 +37,1632 @@ import org.apache.activemq.command.SessionInfo; public class BrokerTest extends BrokerTestSupport { - public ActiveMQDestination destination; - public int deliveryMode; - public int prefetch; - public byte destinationType; - public boolean durableConsumer; - protected static final int MAX_NULL_WAIT=500; + public ActiveMQDestination destination; + public int deliveryMode; + public int prefetch; + public byte destinationType; + public boolean durableConsumer; + protected static final int MAX_NULL_WAIT = 500; - public void initCombosForTestQueueOnlyOnceDeliveryWith2Consumers() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - } + public void initCombosForTestQueueOnlyOnceDeliveryWith2Consumers() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + } - public void testQueueOnlyOnceDeliveryWith2Consumers() throws Exception { + public void testQueueOnlyOnceDeliveryWith2Consumers() throws Exception { - ActiveMQDestination destination = new ActiveMQQueue("TEST"); + ActiveMQDestination destination = new ActiveMQQueue("TEST"); - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo); + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo); - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(1); - connection1.request(consumerInfo1); + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + consumerInfo1.setPrefetchSize(1); + connection1.request(consumerInfo1); - // Setup a second connection - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); - consumerInfo2.setPrefetchSize(1); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.request(consumerInfo2); + // Setup a second connection + StubConnection connection2 = createConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); + consumerInfo2.setPrefetchSize(1); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + connection2.request(consumerInfo2); - // Send the messages - connection1.send(createMessage(producerInfo, destination, deliveryMode)); - connection1.send(createMessage(producerInfo, destination, deliveryMode)); - connection1.send(createMessage(producerInfo, destination, deliveryMode)); - connection1.request(createMessage(producerInfo, destination, deliveryMode)); + // Send the messages + connection1.send(createMessage(producerInfo, destination, deliveryMode)); + connection1.send(createMessage(producerInfo, destination, deliveryMode)); + connection1.send(createMessage(producerInfo, destination, deliveryMode)); + connection1.request(createMessage(producerInfo, destination, deliveryMode)); - for (int i = 0; i < 2; i++) { - Message m1 = receiveMessage(connection1); - Message m2 = receiveMessage(connection2); + for (int i = 0; i < 2; i++) { + Message m1 = receiveMessage(connection1); + Message m2 = receiveMessage(connection2); - assertNotNull("m1 is null for index: " + i, m1); - assertNotNull("m2 is null for index: " + i, m2); + assertNotNull("m1 is null for index: " + i, m1); + assertNotNull("m2 is null for index: " + i, m2); - assertNotSame(m1.getMessageId(), m2.getMessageId()); - connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); - connection2.send(createAck(consumerInfo2, m2, 1, MessageAck.STANDARD_ACK_TYPE)); - } + assertNotSame(m1.getMessageId(), m2.getMessageId()); + connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); + connection2.send(createAck(consumerInfo2, m2, 1, MessageAck.STANDARD_ACK_TYPE)); + } - assertNoMessagesLeft(connection1); - assertNoMessagesLeft(connection2); - } + assertNoMessagesLeft(connection1); + assertNoMessagesLeft(connection2); + } - public void initCombosForTestQueueBrowserWith2Consumers() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - } + public void initCombosForTestQueueBrowserWith2Consumers() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + } - public void testQueueBrowserWith2Consumers() throws Exception { + public void testQueueBrowserWith2Consumers() throws Exception { - ActiveMQDestination destination = new ActiveMQQueue("TEST"); + ActiveMQDestination destination = new ActiveMQQueue("TEST"); - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo); + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo); - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(10); - connection1.request(consumerInfo1); + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + consumerInfo1.setPrefetchSize(10); + connection1.request(consumerInfo1); - // Send the messages - connection1.send(createMessage(producerInfo, destination, deliveryMode)); - connection1.send(createMessage(producerInfo, destination, deliveryMode)); - connection1.send(createMessage(producerInfo, destination, deliveryMode)); - //as the messages are sent async - need to synchronize the last - //one to ensure they arrive in the order we want - connection1.request(createMessage(producerInfo, destination, deliveryMode)); + // Send the messages + connection1.send(createMessage(producerInfo, destination, deliveryMode)); + connection1.send(createMessage(producerInfo, destination, deliveryMode)); + connection1.send(createMessage(producerInfo, destination, deliveryMode)); + //as the messages are sent async - need to synchronize the last + //one to ensure they arrive in the order we want + connection1.request(createMessage(producerInfo, destination, deliveryMode)); - // Setup a second connection with a queue browser. - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); - consumerInfo2.setPrefetchSize(1); - consumerInfo2.setBrowser(true); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.request(consumerInfo2); + // Setup a second connection with a queue browser. + StubConnection connection2 = createConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); + consumerInfo2.setPrefetchSize(1); + consumerInfo2.setBrowser(true); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + connection2.request(consumerInfo2); - List messages = new ArrayList(); + List messages = new ArrayList(); - for (int i = 0; i < 4; i++) { - Message m1 = receiveMessage(connection1); - assertNotNull("m1 is null for index: " + i, m1); - messages.add(m1); - } + for (int i = 0; i < 4; i++) { + Message m1 = receiveMessage(connection1); + assertNotNull("m1 is null for index: " + i, m1); + messages.add(m1); + } - for (int i = 0; i < 4; i++) { - Message m1 = messages.get(i); - Message m2 = receiveMessage(connection2); - assertNotNull("m2 is null for index: " + i, m2); - assertEquals(m1.getMessageId(), m2.getMessageId()); - connection2.send(createAck(consumerInfo2, m2, 1, MessageAck.DELIVERED_ACK_TYPE)); - } + for (int i = 0; i < 4; i++) { + Message m1 = messages.get(i); + Message m2 = receiveMessage(connection2); + assertNotNull("m2 is null for index: " + i, m2); + assertEquals(m1.getMessageId(), m2.getMessageId()); + connection2.send(createAck(consumerInfo2, m2, 1, MessageAck.DELIVERED_ACK_TYPE)); + } - assertNoMessagesLeft(connection1); - assertNoMessagesLeft(connection2); - } + assertNoMessagesLeft(connection1); + assertNoMessagesLeft(connection2); + } - - /* - * change the order of the above test - */ - public void testQueueBrowserWith2ConsumersBrowseFirst() throws Exception { + /* + * change the order of the above test + */ + public void testQueueBrowserWith2ConsumersBrowseFirst() throws Exception { - ActiveMQDestination destination = new ActiveMQQueue("TEST"); - deliveryMode = DeliveryMode.NON_PERSISTENT; - - - // Setup a second connection with a queue browser. - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); - consumerInfo2.setPrefetchSize(10); - consumerInfo2.setBrowser(true); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.request(consumerInfo2); + ActiveMQDestination destination = new ActiveMQQueue("TEST"); + deliveryMode = DeliveryMode.NON_PERSISTENT; - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo); + // Setup a second connection with a queue browser. + StubConnection connection2 = createConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); + consumerInfo2.setPrefetchSize(10); + consumerInfo2.setBrowser(true); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + connection2.request(consumerInfo2); - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(10); - connection1.request(consumerInfo1); + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo); - // Send the messages - connection1.send(createMessage(producerInfo, destination, deliveryMode)); - connection1.send(createMessage(producerInfo, destination, deliveryMode)); - connection1.send(createMessage(producerInfo, destination, deliveryMode)); - //as the messages are sent async - need to synchronize the last - //one to ensure they arrive in the order we want - connection1.request(createMessage(producerInfo, destination, deliveryMode)); + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + consumerInfo1.setPrefetchSize(10); + connection1.request(consumerInfo1); + // Send the messages + connection1.send(createMessage(producerInfo, destination, deliveryMode)); + connection1.send(createMessage(producerInfo, destination, deliveryMode)); + connection1.send(createMessage(producerInfo, destination, deliveryMode)); + //as the messages are sent async - need to synchronize the last + //one to ensure they arrive in the order we want + connection1.request(createMessage(producerInfo, destination, deliveryMode)); - List messages = new ArrayList(); + List messages = new ArrayList(); - for (int i = 0; i < 4; i++) { - Message m1 = receiveMessage(connection1); - assertNotNull("m1 is null for index: " + i, m1); - messages.add(m1); - } + for (int i = 0; i < 4; i++) { + Message m1 = receiveMessage(connection1); + assertNotNull("m1 is null for index: " + i, m1); + messages.add(m1); + } - // no messages present in queue browser as there were no messages when it - // was created - assertNoMessagesLeft(connection1); - assertNoMessagesLeft(connection2); - } + // no messages present in queue browser as there were no messages when it + // was created + assertNoMessagesLeft(connection1); + assertNoMessagesLeft(connection2); + } - public void testQueueBrowserWith2ConsumersInterleaved() throws Exception { + public void testQueueBrowserWith2ConsumersInterleaved() throws Exception { - ActiveMQDestination destination = new ActiveMQQueue("TEST"); - deliveryMode = DeliveryMode.NON_PERSISTENT; - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo); + ActiveMQDestination destination = new ActiveMQQueue("TEST"); + deliveryMode = DeliveryMode.NON_PERSISTENT; - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(10); - connection1.request(consumerInfo1); + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo); - // Send the messages - connection1.request(createMessage(producerInfo, destination, deliveryMode)); - - // Setup a second connection with a queue browser. - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); - consumerInfo2.setPrefetchSize(1); - consumerInfo2.setBrowser(true); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.request(consumerInfo2); + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + consumerInfo1.setPrefetchSize(10); + connection1.request(consumerInfo1); - - connection1.send(createMessage(producerInfo, destination, deliveryMode)); - connection1.send(createMessage(producerInfo, destination, deliveryMode)); - //as the messages are sent async - need to synchronize the last - //one to ensure they arrive in the order we want - connection1.request(createMessage(producerInfo, destination, deliveryMode)); + // Send the messages + connection1.request(createMessage(producerInfo, destination, deliveryMode)); - - List messages = new ArrayList(); + // Setup a second connection with a queue browser. + StubConnection connection2 = createConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); + consumerInfo2.setPrefetchSize(1); + consumerInfo2.setBrowser(true); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + connection2.request(consumerInfo2); - for (int i = 0; i < 4; i++) { - Message m1 = receiveMessage(connection1); - assertNotNull("m1 is null for index: " + i, m1); - messages.add(m1); - } + connection1.send(createMessage(producerInfo, destination, deliveryMode)); + connection1.send(createMessage(producerInfo, destination, deliveryMode)); + //as the messages are sent async - need to synchronize the last + //one to ensure they arrive in the order we want + connection1.request(createMessage(producerInfo, destination, deliveryMode)); - for (int i = 0; i < 4; i++) { - Message m1 = messages.get(i); - Message m2 = receiveMessage(connection2); - assertNotNull("m2 is null for index: " + i, m2); - assertEquals(m1.getMessageId(), m2.getMessageId()); - connection2.send(createAck(consumerInfo2, m2, 1, MessageAck.DELIVERED_ACK_TYPE)); - } + List messages = new ArrayList(); - assertNoMessagesLeft(connection1); - assertNoMessagesLeft(connection2); - } + for (int i = 0; i < 4; i++) { + Message m1 = receiveMessage(connection1); + assertNotNull("m1 is null for index: " + i, m1); + messages.add(m1); + } - - public void initCombosForTestConsumerPrefetchAndStandardAck() { - addCombinationValues("deliveryMode", new Object[] { - // Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", - new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); - } + for (int i = 0; i < 4; i++) { + Message m1 = messages.get(i); + Message m2 = receiveMessage(connection2); + assertNotNull("m2 is null for index: " + i, m2); + assertEquals(m1.getMessageId(), m2.getMessageId()); + connection2.send(createAck(consumerInfo2, m2, 1, MessageAck.DELIVERED_ACK_TYPE)); + } - public void testConsumerPrefetchAndStandardAck() throws Exception { + assertNoMessagesLeft(connection1); + assertNoMessagesLeft(connection2); + } - // Start a producer and consumer - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); + public void initCombosForTestConsumerPrefetchAndStandardAck() { + addCombinationValues("deliveryMode", new Object[]{ + // Integer.valueOf(DeliveryMode.NON_PERSISTENT), + Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); + } - destination = createDestinationInfo(connection, connectionInfo, destinationType); + public void testConsumerPrefetchAndStandardAck() throws Exception { - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setPrefetchSize(1); - connection.send(consumerInfo); + // Start a producer and consumer + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); - // Send 3 messages to the broker. - connection.send(createMessage(producerInfo, destination, deliveryMode)); - connection.send(createMessage(producerInfo, destination, deliveryMode)); - connection.request(createMessage(producerInfo, destination, deliveryMode)); + destination = createDestinationInfo(connection, connectionInfo, destinationType); - // Make sure only 1 message was delivered. - Message m1 = receiveMessage(connection); - assertNotNull(m1); - assertNoMessagesLeft(connection); + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + consumerInfo.setPrefetchSize(1); + connection.send(consumerInfo); - // Acknowledge the first message. This should cause the next message to - // get dispatched. - connection.send(createAck(consumerInfo, m1, 1, MessageAck.STANDARD_ACK_TYPE)); + // Send 3 messages to the broker. + connection.send(createMessage(producerInfo, destination, deliveryMode)); + connection.send(createMessage(producerInfo, destination, deliveryMode)); + connection.request(createMessage(producerInfo, destination, deliveryMode)); - Message m2 = receiveMessage(connection); - assertNotNull(m2); - connection.send(createAck(consumerInfo, m2, 1, MessageAck.STANDARD_ACK_TYPE)); + // Make sure only 1 message was delivered. + Message m1 = receiveMessage(connection); + assertNotNull(m1); + assertNoMessagesLeft(connection); - Message m3 = receiveMessage(connection); - assertNotNull(m3); - connection.send(createAck(consumerInfo, m3, 1, MessageAck.STANDARD_ACK_TYPE)); + // Acknowledge the first message. This should cause the next message to + // get dispatched. + connection.send(createAck(consumerInfo, m1, 1, MessageAck.STANDARD_ACK_TYPE)); - connection.send(closeConnectionInfo(connectionInfo)); - } + Message m2 = receiveMessage(connection); + assertNotNull(m2); + connection.send(createAck(consumerInfo, m2, 1, MessageAck.STANDARD_ACK_TYPE)); - public void initCombosForTestTransactedAckWithPrefetchOfOne() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", - new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); - } + Message m3 = receiveMessage(connection); + assertNotNull(m3); + connection.send(createAck(consumerInfo, m3, 1, MessageAck.STANDARD_ACK_TYPE)); - public void testTransactedAckWithPrefetchOfOne() throws Exception { + connection.send(closeConnectionInfo(connectionInfo)); + } - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo1); + public void initCombosForTestTransactedAckWithPrefetchOfOne() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); + } - destination = createDestinationInfo(connection1, connectionInfo1, destinationType); + public void testTransactedAckWithPrefetchOfOne() throws Exception { - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(1); - connection1.send(consumerInfo1); + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo1); - // Send the messages - for (int i = 0; i < 4; i++) { - Message message = createMessage(producerInfo1, destination, deliveryMode); - connection1.send(message); - } + destination = createDestinationInfo(connection1, connectionInfo1, destinationType); - + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + consumerInfo1.setPrefetchSize(1); + connection1.send(consumerInfo1); - // Now get the messages. - for (int i = 0; i < 4; i++) { - // Begin the transaction. - LocalTransactionId txid = createLocalTransaction(sessionInfo1); - connection1.send(createBeginTransaction(connectionInfo1, txid)); - Message m1 = receiveMessage(connection1); - assertNotNull(m1); - MessageAck ack = createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection1.send(ack); + // Send the messages + for (int i = 0; i < 4; i++) { + Message message = createMessage(producerInfo1, destination, deliveryMode); + connection1.send(message); + } + + // Now get the messages. + for (int i = 0; i < 4; i++) { + // Begin the transaction. + LocalTransactionId txid = createLocalTransaction(sessionInfo1); + connection1.send(createBeginTransaction(connectionInfo1, txid)); + Message m1 = receiveMessage(connection1); + assertNotNull(m1); + MessageAck ack = createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE); + ack.setTransactionId(txid); + connection1.send(ack); // Commit the transaction. - connection1.send(createCommitTransaction1Phase(connectionInfo1, txid)); - } - assertNoMessagesLeft(connection1); - } - - public void initCombosForTestTransactedSend() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", - new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); - } - - public void testTransactedSend() throws Exception { - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo1); - - destination = createDestinationInfo(connection1, connectionInfo1, destinationType); - - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(100); - connection1.send(consumerInfo1); - - // Begin the transaction. - LocalTransactionId txid = createLocalTransaction(sessionInfo1); - connection1.send(createBeginTransaction(connectionInfo1, txid)); - - // Send the messages - for (int i = 0; i < 4; i++) { - Message message = createMessage(producerInfo1, destination, deliveryMode); - message.setTransactionId(txid); - connection1.request(message); - } - - // The point of this test is that message should not be delivered until - // send is committed. - assertNull(receiveMessage(connection1,MAX_NULL_WAIT)); - - // Commit the transaction. - connection1.send(createCommitTransaction1Phase(connectionInfo1, txid)); - - // Now get the messages. - for (int i = 0; i < 4; i++) { - Message m1 = receiveMessage(connection1); - assertNotNull(m1); - } - - assertNoMessagesLeft(connection1); - } - - public void initCombosForTestQueueTransactedAck() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", - new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE)}); - } - - public void testQueueTransactedAck() throws Exception { - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo1); - - destination = createDestinationInfo(connection1, connectionInfo1, destinationType); - - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(100); - connection1.send(consumerInfo1); - - // Send the messages - for (int i = 0; i < 4; i++) { - Message message = createMessage(producerInfo1, destination, deliveryMode); - connection1.send(message); - } - - // Begin the transaction. - LocalTransactionId txid = createLocalTransaction(sessionInfo1); - connection1.send(createBeginTransaction(connectionInfo1, txid)); - - // Acknowledge the first 2 messages. - for (int i = 0; i < 2; i++) { - Message m1 = receiveMessage(connection1); - assertNotNull("m1 is null for index: " + i, m1); - MessageAck ack = createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection1.request(ack); - } - - // Commit the transaction. - connection1.send(createCommitTransaction1Phase(connectionInfo1, txid)); - - // The queue should now only have the remaining 2 messages - assertEquals(2, countMessagesInQueue(connection1, connectionInfo1, destination)); - } - - public void initCombosForTestConsumerCloseCausesRedelivery() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST")}); - } - - public void testConsumerCloseCausesRedelivery() throws Exception { - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo1); - - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(100); - connection1.request(consumerInfo1); - - // Send the messages - connection1.send(createMessage(producerInfo1, destination, deliveryMode)); - connection1.send(createMessage(producerInfo1, destination, deliveryMode)); - connection1.send(createMessage(producerInfo1, destination, deliveryMode)); - connection1.send(createMessage(producerInfo1, destination, deliveryMode)); - - // Receive the messages. - for (int i = 0; i < 4; i++) { - Message m1 = receiveMessage(connection1); - assertNotNull("m1 is null for index: " + i, m1); - assertFalse(m1.isRedelivered()); - } - - // Close the consumer without acking.. this should cause re-delivery of - // the messages. - connection1.send(consumerInfo1.createRemoveCommand()); - - // Create another consumer that should get the messages again. - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo1, destination); - consumerInfo2.setPrefetchSize(100); - connection1.request(consumerInfo2); - - // Receive the messages. - for (int i = 0; i < 4; i++) { - Message m1 = receiveMessage(connection1); - assertNotNull("m1 is null for index: " + i, m1); - assertTrue(m1.isRedelivered()); - } - assertNoMessagesLeft(connection1); - - } - - public void testTopicDurableSubscriptionCanBeRestored() throws Exception { - - ActiveMQDestination destination = new ActiveMQTopic("TEST"); - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - connectionInfo1.setClientId("clientid1"); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo1); - - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(100); - consumerInfo1.setSubscriptionName("test"); - connection1.send(consumerInfo1); - - // Send the messages - connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); - connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); - connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); - connection1.request(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); - - // Get the messages - Message m = null; - for (int i = 0; i < 2; i++) { - m = receiveMessage(connection1); - assertNotNull(m); - } - // Ack the last message. - connection1.send(createAck(consumerInfo1, m, 2, MessageAck.STANDARD_ACK_TYPE)); - // Close the connection. - connection1.request(closeConnectionInfo(connectionInfo1)); - connection1.stop(); - - // Setup a second connection - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - connectionInfo2.setClientId("clientid1"); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); - consumerInfo2.setPrefetchSize(100); - consumerInfo2.setSubscriptionName("test"); - - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.send(consumerInfo2); - - // Get the rest of the messages - for (int i = 0; i < 2; i++) { - Message m1 = receiveMessage(connection2); - assertNotNull("m1 is null for index: " + i, m1); - } - assertNoMessagesLeft(connection2); - } - - public void initCombosForTestGroupedMessagesDeliveredToOnlyOneConsumer() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - } - - public void testGroupedMessagesDeliveredToOnlyOneConsumer() throws Exception { - - ActiveMQDestination destination = new ActiveMQQueue("TEST"); - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo); - - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(1); - connection1.send(consumerInfo1); - - // Send the messages. - for (int i = 0; i < 4; i++) { - Message message = createMessage(producerInfo, destination, deliveryMode); - message.setGroupID("TEST-GROUP"); - message.setGroupSequence(i + 1); - connection1.request(message); - } - - // Setup a second connection - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); - consumerInfo2.setPrefetchSize(1); - connection2.send(consumerInfo2); - - // All the messages should have been sent down connection 1.. just get - // the first 3 - for (int i = 0; i < 3; i++) { - Message m1 = receiveMessage(connection1); - assertNotNull("m1 is null for index: " + i, m1); - connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); - } - - // Close the first consumer. - connection1.request(closeConsumerInfo(consumerInfo1)); - - // The last messages should now go the the second consumer. - for (int i = 0; i < 1; i++) { - Message m1 = receiveMessage(connection2); - assertNotNull("m1 is null for index: " + i, m1); - connection2.request(createAck(consumerInfo2, m1, 1, MessageAck.STANDARD_ACK_TYPE)); - } - - assertNoMessagesLeft(connection2); - } - - public void initCombosForTestTopicConsumerOnlySeeMessagesAfterCreation() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("durableConsumer", new Object[] {Boolean.TRUE, Boolean.FALSE}); - } - - public void testTopicConsumerOnlySeeMessagesAfterCreation() throws Exception { - - ActiveMQDestination destination = new ActiveMQTopic("TEST"); - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - connectionInfo1.setClientId("A"); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo1); - - // Send the 1st message - connection1.send(createMessage(producerInfo1, destination, deliveryMode)); - - // Create the durable subscription. - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - if (durableConsumer) { - consumerInfo1.setSubscriptionName("test"); - } - consumerInfo1.setPrefetchSize(100); - connection1.send(consumerInfo1); - - Message m = createMessage(producerInfo1, destination, deliveryMode); - connection1.send(m); - connection1.send(createMessage(producerInfo1, destination, deliveryMode)); - - // Subscription should skip over the first message - Message m2 = receiveMessage(connection1); - assertNotNull(m2); - assertEquals(m.getMessageId(), m2.getMessageId()); - m2 = receiveMessage(connection1); - assertNotNull(m2); - - assertNoMessagesLeft(connection1); - } - - public void initCombosForTestTopicRetroactiveConsumerSeeMessagesBeforeCreation() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("durableConsumer", new Object[] {Boolean.TRUE, Boolean.FALSE}); - } - - public void testTopicRetroactiveConsumerSeeMessagesBeforeCreation() throws Exception { - - ActiveMQDestination destination = new ActiveMQTopic("TEST"); - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - connectionInfo1.setClientId("A"); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo1); - - // Send the messages - Message m = createMessage(producerInfo1, destination, deliveryMode); - connection1.send(m); - - // Create the durable subscription. - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - if (durableConsumer) { - consumerInfo1.setSubscriptionName("test"); - } - consumerInfo1.setPrefetchSize(100); - consumerInfo1.setRetroactive(true); - connection1.send(consumerInfo1); - - connection1.send(createMessage(producerInfo1, destination, deliveryMode)); - connection1.request(createMessage(producerInfo1, destination, deliveryMode)); - - // the behavior is VERY dependent on the recovery policy used. - // But the default broker settings try to make it as consistent as - // possible - - // Subscription should see all messages sent. - Message m2 = receiveMessage(connection1); - assertNotNull(m2); - assertEquals(m.getMessageId(), m2.getMessageId()); - for (int i = 0; i < 2; i++) { - m2 = receiveMessage(connection1); - assertNotNull(m2); - } - - assertNoMessagesLeft(connection1); - } - - // - // TODO: need to reimplement this since we don't fail when we send to a - // non-existent - // destination. But if we can access the Region directly then we should be - // able to - // check that if the destination was removed. - // - // public void initCombosForTestTempDestinationsRemovedOnConnectionClose() { - // addCombinationValues( "deliveryMode", new Object[]{ - // Integer.valueOf(DeliveryMode.NON_PERSISTENT), - // Integer.valueOf(DeliveryMode.PERSISTENT)} ); - // addCombinationValues( "destinationType", new Object[]{ - // Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), - // Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)} ); - // } - // - // public void testTempDestinationsRemovedOnConnectionClose() throws - // Exception { - // - // // Setup a first connection - // StubConnection connection1 = createConnection(); - // ConnectionInfo connectionInfo1 = createConnectionInfo(); - // SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - // ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); - // connection1.send(connectionInfo1); - // connection1.send(sessionInfo1); - // connection1.send(producerInfo1); - // - // destination = createDestinationInfo(connection1, connectionInfo1, - // destinationType); - // - // StubConnection connection2 = createConnection(); - // ConnectionInfo connectionInfo2 = createConnectionInfo(); - // SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - // ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); - // connection2.send(connectionInfo2); - // connection2.send(sessionInfo2); - // connection2.send(producerInfo2); - // - // // Send from connection2 to connection1's temp destination. Should - // succeed. - // connection2.send(createMessage(producerInfo2, destination, - // deliveryMode)); - // - // // Close connection 1 - // connection1.request(closeConnectionInfo(connectionInfo1)); - // - // try { - // // Send from connection2 to connection1's temp destination. Should not - // succeed. - // connection2.request(createMessage(producerInfo2, destination, - // deliveryMode)); - // fail("Expected JMSException."); - // } catch ( JMSException success ) { - // } - // - // } - - // public void initCombosForTestTempDestinationsAreNotAutoCreated() { - // addCombinationValues( "deliveryMode", new Object[]{ - // Integer.valueOf(DeliveryMode.NON_PERSISTENT), - // Integer.valueOf(DeliveryMode.PERSISTENT)} ); - // addCombinationValues( "destinationType", new Object[]{ - // Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), - // Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)} ); - // } - // - // - - // We create temp destination on demand now so this test case is no longer - // valid. - // - // public void testTempDestinationsAreNotAutoCreated() throws Exception { - // - // // Setup a first connection - // StubConnection connection1 = createConnection(); - // ConnectionInfo connectionInfo1 = createConnectionInfo(); - // SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - // ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); - // connection1.send(connectionInfo1); - // connection1.send(sessionInfo1); - // connection1.send(producerInfo1); - // - // destination = - // ActiveMQDestination.createDestination(connectionInfo1.getConnectionId()+":1", - // destinationType); - // - // // Should not be able to send to a non-existent temp destination. - // try { - // connection1.request(createMessage(producerInfo1, destination, - // deliveryMode)); - // fail("Expected JMSException."); - // } catch ( JMSException success ) { - // } - // - // } - - - public void initCombosForTestExclusiveQueueDeliversToOnlyOneConsumer() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - } - - public void testExclusiveQueueDeliversToOnlyOneConsumer() throws Exception { - - ActiveMQDestination destination = new ActiveMQQueue("TEST"); - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo); - - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(1); - consumerInfo1.setExclusive(true); - connection1.send(consumerInfo1); - - // Send a message.. this should make consumer 1 the exclusive owner. - connection1.request(createMessage(producerInfo, destination, deliveryMode)); - - // Setup a second connection - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); - consumerInfo2.setPrefetchSize(1); - consumerInfo2.setExclusive(true); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.request(consumerInfo2); - - // Second message should go to consumer 1 even though consumer 2 is - // ready - // for dispatch. - connection1.send(createMessage(producerInfo, destination, deliveryMode)); - connection1.send(createMessage(producerInfo, destination, deliveryMode)); - - // Acknowledge the first 2 messages - for (int i = 0; i < 2; i++) { - Message m1 = receiveMessage(connection1); - assertNotNull(m1); - connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); - } - - // Close the first consumer. - connection1.send(closeConsumerInfo(consumerInfo1)); - - // The last two messages should now go the the second consumer. - connection1.send(createMessage(producerInfo, destination, deliveryMode)); - - for (int i = 0; i < 2; i++) { - Message m1 = receiveMessage(connection2); - assertNotNull(m1); - connection2.send(createAck(consumerInfo2, m1, 1, MessageAck.STANDARD_ACK_TYPE)); - } - - assertNoMessagesLeft(connection2); - } - - public void initCombosForTestWildcardConsume() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); - } - - public void testWildcardConsume() throws Exception { - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo1); - - // setup the wildcard consumer. - ActiveMQDestination compositeDestination = ActiveMQDestination.createDestination("WILD.*.TEST", - destinationType); - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, compositeDestination); - consumerInfo1.setPrefetchSize(100); - connection1.send(consumerInfo1); - - // These two message should NOT match the wild card. - connection1.send(createMessage(producerInfo1, ActiveMQDestination.createDestination("WILD.CARD", - destinationType), - deliveryMode)); - connection1.send(createMessage(producerInfo1, ActiveMQDestination.createDestination("WILD.TEST", - destinationType), - deliveryMode)); - - // These two message should match the wild card. - ActiveMQDestination d1 = ActiveMQDestination.createDestination("WILD.CARD.TEST", destinationType); - connection1.send(createMessage(producerInfo1, d1, deliveryMode)); - - Message m = receiveMessage(connection1); - assertNotNull(m); - assertEquals(d1, m.getDestination()); - - ActiveMQDestination d2 = ActiveMQDestination.createDestination("WILD.FOO.TEST", destinationType); - connection1.request(createMessage(producerInfo1, d2, deliveryMode)); - m = receiveMessage(connection1); - assertNotNull(m); - assertEquals(d2, m.getDestination()); - - assertNoMessagesLeft(connection1); - connection1.send(closeConnectionInfo(connectionInfo1)); - } - - public void initCombosForTestCompositeConsume() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); - } - - public void testCompositeConsume() throws Exception { - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo1); - - // setup the composite consumer. - ActiveMQDestination compositeDestination = ActiveMQDestination.createDestination("A,B", - destinationType); - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, compositeDestination); - consumerInfo1.setRetroactive(true); - consumerInfo1.setPrefetchSize(100); - connection1.send(consumerInfo1); - - // Publish to the two destinations - ActiveMQDestination destinationA = ActiveMQDestination.createDestination("A", destinationType); - ActiveMQDestination destinationB = ActiveMQDestination.createDestination("B", destinationType); - - // Send a message to each destination . - connection1.send(createMessage(producerInfo1, destinationA, deliveryMode)); - connection1.send(createMessage(producerInfo1, destinationB, deliveryMode)); - - // The consumer should get both messages. - for (int i = 0; i < 2; i++) { - Message m1 = receiveMessage(connection1); - assertNotNull(m1); - } - - assertNoMessagesLeft(connection1); - connection1.send(closeConnectionInfo(connectionInfo1)); - } - - public void initCombosForTestCompositeSend() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); - } - - public void testCompositeSend() throws Exception { - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo1); - - ActiveMQDestination destinationA = ActiveMQDestination.createDestination("A", destinationType); - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destinationA); - consumerInfo1.setRetroactive(true); - consumerInfo1.setPrefetchSize(100); - connection1.request(consumerInfo1); - - // Setup a second connection - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - - ActiveMQDestination destinationB = ActiveMQDestination.createDestination("B", destinationType); - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destinationB); - consumerInfo2.setRetroactive(true); - consumerInfo2.setPrefetchSize(100); - connection2.request(consumerInfo2); - - // Send the messages to the composite destination. - ActiveMQDestination compositeDestination = ActiveMQDestination.createDestination("A,B", - destinationType); - for (int i = 0; i < 4; i++) { - connection1.request(createMessage(producerInfo1, compositeDestination, deliveryMode)); - } - - // The messages should have been delivered to both the A and B - // destination. - for (int i = 0; i < 4; i++) { - Message m1 = receiveMessage(connection1); - Message m2 = receiveMessage(connection2); - - assertNotNull(m1); - assertNotNull(m2); - - assertEquals(m1.getMessageId(), m2.getMessageId()); - assertEquals(compositeDestination, m1.getOriginalDestination()); - assertEquals(compositeDestination, m2.getOriginalDestination()); - - connection1.request(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); - connection2.request(createAck(consumerInfo2, m2, 1, MessageAck.STANDARD_ACK_TYPE)); - - } - - assertNoMessagesLeft(connection1); - assertNoMessagesLeft(connection2); - - connection1.send(closeConnectionInfo(connectionInfo1)); - connection2.send(closeConnectionInfo(connectionInfo2)); - } - - public void initCombosForTestConnectionCloseCascades() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destination", new Object[] {new ActiveMQTopic("TEST"), - new ActiveMQQueue("TEST")}); - } - - public void testConnectionCloseCascades() throws Exception { - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo1); - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(100); - consumerInfo1.setNoLocal(true); - connection1.request(consumerInfo1); - - // Setup a second connection - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.send(producerInfo2); - - // Send the messages - connection2.send(createMessage(producerInfo2, destination, deliveryMode)); - connection2.send(createMessage(producerInfo2, destination, deliveryMode)); - connection2.send(createMessage(producerInfo2, destination, deliveryMode)); - connection2.send(createMessage(producerInfo2, destination, deliveryMode)); - - for (int i = 0; i < 4; i++) { - Message m1 = receiveMessage(connection1); - assertNotNull(m1); - connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); - } - - // give the async ack a chance to perculate and validate all are currently consumed - Message msg = receiveMessage(connection1, MAX_NULL_WAIT); - assertNull("all messages were received " + msg, msg); - - // Close the connection, this should in turn close the consumer. - connection1.request(closeConnectionInfo(connectionInfo1)); - - // Send another message, connection1 should not get the message. - connection2.request(createMessage(producerInfo2, destination, deliveryMode)); - - assertNull("no message received", receiveMessage(connection1, MAX_NULL_WAIT)); - } - - public void initCombosForTestSessionCloseCascades() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destination", new Object[] {new ActiveMQTopic("TEST"), - new ActiveMQQueue("TEST")}); - } - - public void testSessionCloseCascades() throws Exception { - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo1); - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(100); - consumerInfo1.setNoLocal(true); - connection1.request(consumerInfo1); - - // Setup a second connection - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.send(producerInfo2); - - // Send the messages - connection2.send(createMessage(producerInfo2, destination, deliveryMode)); - connection2.send(createMessage(producerInfo2, destination, deliveryMode)); - connection2.send(createMessage(producerInfo2, destination, deliveryMode)); - connection2.send(createMessage(producerInfo2, destination, deliveryMode)); - - for (int i = 0; i < 4; i++) { - Message m1 = receiveMessage(connection1); - assertNotNull(m1); - connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); - } - - // Close the session, this should in turn close the consumer. - connection1.request(closeSessionInfo(sessionInfo1)); - - // Send another message, connection1 should not get the message. - connection2.request(createMessage(producerInfo2, destination, deliveryMode)); - - Message msg = receiveMessage(connection1,MAX_NULL_WAIT); - assertNull("no message received from connection1 after session close", msg); - } - - public void initCombosForTestConsumerClose() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destination", new Object[] {new ActiveMQTopic("TEST"), - new ActiveMQQueue("TEST")}); - } - - public void testConsumerClose() throws Exception { - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo1); - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(100); - consumerInfo1.setNoLocal(true); - connection1.request(consumerInfo1); - - // Setup a second connection - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.send(producerInfo2); - - // Send the messages - connection2.send(createMessage(producerInfo2, destination, deliveryMode)); - connection2.send(createMessage(producerInfo2, destination, deliveryMode)); - connection2.send(createMessage(producerInfo2, destination, deliveryMode)); - connection2.send(createMessage(producerInfo2, destination, deliveryMode)); - - for (int i = 0; i < 4; i++) { - Message m1 = receiveMessage(connection1); - assertNotNull(m1); - connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); - } - - // give the async ack a chance to perculate and validate all are currently consumed - // use receive rather than poll as broker info is sent async and may still need to be dequeued - Message result = receiveMessage(connection1, MAX_NULL_WAIT); - assertNull("no more messages " + result, result); - - // Close the consumer. - connection1.request(closeConsumerInfo(consumerInfo1)); - - // Send another message, connection1 should not get the message. - connection2.request(createMessage(producerInfo2, destination, deliveryMode)); - - result = receiveMessage(connection1, MAX_NULL_WAIT); - assertNull("no message received after close " + result, result); - } - - public void initCombosForTestTopicNoLocal() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - } - - public void testTopicNoLocal() throws Exception { - - ActiveMQDestination destination = new ActiveMQTopic("TEST"); - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo1); - - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setRetroactive(true); - consumerInfo1.setPrefetchSize(100); - consumerInfo1.setNoLocal(true); - connection1.send(consumerInfo1); - - // Setup a second connection - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.send(producerInfo2); - - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); - consumerInfo2.setRetroactive(true); - consumerInfo2.setPrefetchSize(100); - consumerInfo2.setNoLocal(true); - connection2.send(consumerInfo2); - - // Send the messages - connection1.send(createMessage(producerInfo1, destination, deliveryMode)); - connection1.send(createMessage(producerInfo1, destination, deliveryMode)); - connection1.send(createMessage(producerInfo1, destination, deliveryMode)); - connection1.send(createMessage(producerInfo1, destination, deliveryMode)); - - // The 2nd connection should get the messages. - for (int i = 0; i < 4; i++) { - Message m1 = receiveMessage(connection2); - assertNotNull(m1); - } - - // Send a message with the 2nd connection - Message message = createMessage(producerInfo2, destination, deliveryMode); - connection2.send(message); - - // The first connection should not see the initial 4 local messages sent - // but should - // see the messages from connection 2. - Message m = receiveMessage(connection1); - assertNotNull(m); - assertEquals(message.getMessageId(), m.getMessageId()); - - assertNoMessagesLeft(connection1); - assertNoMessagesLeft(connection2); - } - - public void initCombosForTopicDispatchIsBroadcast() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - } - - public void testTopicDispatchIsBroadcast() throws Exception { - - ActiveMQDestination destination = new ActiveMQTopic("TEST"); - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo1); - - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setRetroactive(true); - consumerInfo1.setPrefetchSize(100); - connection1.send(consumerInfo1); - - // Setup a second connection - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); - consumerInfo2.setRetroactive(true); - consumerInfo2.setPrefetchSize(100); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.send(consumerInfo2); - - // Send the messages - connection1.send(createMessage(producerInfo1, destination, deliveryMode)); - connection1.send(createMessage(producerInfo1, destination, deliveryMode)); - connection1.send(createMessage(producerInfo1, destination, deliveryMode)); - connection1.send(createMessage(producerInfo1, destination, deliveryMode)); - - // Get the messages - for (int i = 0; i < 4; i++) { - Message m1 = receiveMessage(connection1); - assertNotNull(m1); - m1 = receiveMessage(connection2); - assertNotNull(m1); - } - } - - public void initCombosForTestQueueDispatchedAreRedeliveredOnConsumerClose() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", - new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE)}); - } - - public void testQueueDispatchedAreRedeliveredOnConsumerClose() throws Exception { - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo); - - destination = createDestinationInfo(connection1, connectionInfo1, destinationType); - - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(100); - connection1.send(consumerInfo1); - - // Send the messages - connection1.send(createMessage(producerInfo, destination, deliveryMode)); - connection1.send(createMessage(producerInfo, destination, deliveryMode)); - connection1.send(createMessage(producerInfo, destination, deliveryMode)); - connection1.send(createMessage(producerInfo, destination, deliveryMode)); - - // Get the messages - for (int i = 0; i < 4; i++) { - Message m1 = receiveMessage(connection1); - assertNotNull(m1); - assertFalse(m1.isRedelivered()); - } - // Close the consumer without sending any ACKS. - connection1.send(closeConsumerInfo(consumerInfo1)); - - // Drain any in flight messages.. - while (connection1.getDispatchQueue().poll(0, TimeUnit.MILLISECONDS) != null) { - } - - // Add the second consumer - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo1, destination); - consumerInfo2.setPrefetchSize(100); - connection1.send(consumerInfo2); - - // Make sure the messages were re delivered to the 2nd consumer. - for (int i = 0; i < 4; i++) { - Message m1 = receiveMessage(connection1); - assertNotNull(m1); - assertTrue(m1.isRedelivered()); - } - } - - public void initCombosForTestQueueBrowseMessages() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", - new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE)}); - } - - public void testQueueBrowseMessages() throws Exception { - - // Start a producer and consumer - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - destination = createDestinationInfo(connection, connectionInfo, destinationType); - - connection.send(createMessage(producerInfo, destination, deliveryMode)); - connection.send(createMessage(producerInfo, destination, deliveryMode)); - connection.send(createMessage(producerInfo, destination, deliveryMode)); - connection.send(createMessage(producerInfo, destination, deliveryMode)); - - // Use selector to skip first message. - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setBrowser(true); - connection.send(consumerInfo); - - for (int i = 0; i < 4; i++) { - Message m = receiveMessage(connection); - assertNotNull(m); - connection.send(createAck(consumerInfo, m, 1, MessageAck.DELIVERED_ACK_TYPE)); - } - - assertNoMessagesLeft(connection); - } - - public void initCombosForTestQueueSendThenAddConsumer() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", - new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE)}); - } - - public void testQueueSendThenAddConsumer() throws Exception { - - // Start a producer - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - destination = createDestinationInfo(connection, connectionInfo, destinationType); - - // Send a message to the broker. - connection.send(createMessage(producerInfo, destination, deliveryMode)); - - // Start the consumer - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // Make sure the message was delivered. - Message m = receiveMessage(connection); - assertNotNull(m); - - } - - public void initCombosForTestQueueAckRemovesMessage() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", - new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE)}); - } - - public void testQueueAckRemovesMessage() throws Exception { - - // Start a producer and consumer - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - destination = createDestinationInfo(connection, connectionInfo, destinationType); - - Message message1 = createMessage(producerInfo, destination, deliveryMode); - Message message2 = createMessage(producerInfo, destination, deliveryMode); - connection.send(message1); - connection.send(message2); - - // Make sure the message was delivered. - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.request(consumerInfo); - Message m = receiveMessage(connection); - assertNotNull(m); - assertEquals(m.getMessageId(), message1.getMessageId()); - - assertTrue(countMessagesInQueue(connection, connectionInfo, destination) == 2); - connection.send(createAck(consumerInfo, m, 1, MessageAck.DELIVERED_ACK_TYPE)); - assertTrue(countMessagesInQueue(connection, connectionInfo, destination) == 2); - connection.send(createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE)); - assertTrue(countMessagesInQueue(connection, connectionInfo, destination) == 1); - - } - - public void initCombosForTestSelectorSkipsMessages() { - addCombinationValues("destination", new Object[] {new ActiveMQTopic("TEST_TOPIC"), - new ActiveMQQueue("TEST_QUEUE")}); - addCombinationValues("destinationType", - new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); - } - - public void testSelectorSkipsMessages() throws Exception { - - // Start a producer and consumer - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - destination = createDestinationInfo(connection, connectionInfo, destinationType); - - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setSelector("JMSType='last'"); - connection.send(consumerInfo); - - Message message1 = createMessage(producerInfo, destination, deliveryMode); - message1.setType("first"); - Message message2 = createMessage(producerInfo, destination, deliveryMode); - message2.setType("last"); - connection.send(message1); - connection.send(message2); - - // Use selector to skip first message. - Message m = receiveMessage(connection); - assertNotNull(m); - assertEquals(m.getMessageId(), message2.getMessageId()); - connection.send(createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE)); - connection.send(closeConsumerInfo(consumerInfo)); - - assertNoMessagesLeft(connection); - } - - public void initCombosForTestAddConsumerThenSend() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", - new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); - } - - public void testAddConsumerThenSend() throws Exception { - - // Start a producer and consumer - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - destination = createDestinationInfo(connection, connectionInfo, destinationType); - - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - connection.send(createMessage(producerInfo, destination, deliveryMode)); - - // Make sure the message was delivered. - Message m = receiveMessage(connection); - assertNotNull(m); - } - - public void initCombosForTestConsumerPrefetchAtOne() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", - new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); - } - - public void testConsumerPrefetchAtOne() throws Exception { - - // Start a producer and consumer - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - destination = createDestinationInfo(connection, connectionInfo, destinationType); - - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setPrefetchSize(1); - connection.send(consumerInfo); - - // Send 2 messages to the broker. - connection.send(createMessage(producerInfo, destination, deliveryMode)); - connection.send(createMessage(producerInfo, destination, deliveryMode)); - - // Make sure only 1 message was delivered. - Message m = receiveMessage(connection); - assertNotNull(m); - assertNoMessagesLeft(connection); - - } - - public void initCombosForTestConsumerPrefetchAtTwo() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", - new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); - } - - public void testConsumerPrefetchAtTwo() throws Exception { - - // Start a producer and consumer - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - destination = createDestinationInfo(connection, connectionInfo, destinationType); - - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setPrefetchSize(2); - connection.send(consumerInfo); - - // Send 3 messages to the broker. - connection.send(createMessage(producerInfo, destination, deliveryMode)); - connection.send(createMessage(producerInfo, destination, deliveryMode)); - connection.send(createMessage(producerInfo, destination, deliveryMode)); - - // Make sure only 1 message was delivered. - Message m = receiveMessage(connection); - assertNotNull(m); - m = receiveMessage(connection); - assertNotNull(m); - assertNoMessagesLeft(connection); - - } - - public void initCombosForTestConsumerPrefetchAndDeliveredAck() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", - new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); - } - - public void testConsumerPrefetchAndDeliveredAck() throws Exception { - - // Start a producer and consumer - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - destination = createDestinationInfo(connection, connectionInfo, destinationType); - - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setPrefetchSize(1); - connection.request(consumerInfo); - - // Send 3 messages to the broker. - connection.send(createMessage(producerInfo, destination, deliveryMode)); - connection.send(createMessage(producerInfo, destination, deliveryMode)); - connection.request(createMessage(producerInfo, destination, deliveryMode)); - - // Make sure only 1 message was delivered. - Message m1 = receiveMessage(connection); - assertNotNull(m1); - - assertNoMessagesLeft(connection); - - // Acknowledge the first message. This should cause the next message to - // get dispatched. - connection.request(createAck(consumerInfo, m1, 1, MessageAck.DELIVERED_ACK_TYPE)); - - Message m2 = receiveMessage(connection); - assertNotNull(m2); - connection.request(createAck(consumerInfo, m2, 1, MessageAck.DELIVERED_ACK_TYPE)); - - Message m3 = receiveMessage(connection); - assertNotNull(m3); - connection.request(createAck(consumerInfo, m3, 1, MessageAck.DELIVERED_ACK_TYPE)); - } - - public void testGetServices() throws Exception { - assertTrue(broker.getServices().length != 0); - } - - public static Test suite() { - return suite(BrokerTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + connection1.send(createCommitTransaction1Phase(connectionInfo1, txid)); + } + assertNoMessagesLeft(connection1); + } + + public void initCombosForTestTransactedSend() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); + } + + public void testTransactedSend() throws Exception { + + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo1); + + destination = createDestinationInfo(connection1, connectionInfo1, destinationType); + + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + consumerInfo1.setPrefetchSize(100); + connection1.send(consumerInfo1); + + // Begin the transaction. + LocalTransactionId txid = createLocalTransaction(sessionInfo1); + connection1.send(createBeginTransaction(connectionInfo1, txid)); + + // Send the messages + for (int i = 0; i < 4; i++) { + Message message = createMessage(producerInfo1, destination, deliveryMode); + message.setTransactionId(txid); + connection1.request(message); + } + + // The point of this test is that message should not be delivered until + // send is committed. + assertNull(receiveMessage(connection1, MAX_NULL_WAIT)); + + // Commit the transaction. + connection1.send(createCommitTransaction1Phase(connectionInfo1, txid)); + + // Now get the messages. + for (int i = 0; i < 4; i++) { + Message m1 = receiveMessage(connection1); + assertNotNull(m1); + } + + assertNoMessagesLeft(connection1); + } + + public void initCombosForTestQueueTransactedAck() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE)}); + } + + public void testQueueTransactedAck() throws Exception { + + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo1); + + destination = createDestinationInfo(connection1, connectionInfo1, destinationType); + + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + consumerInfo1.setPrefetchSize(100); + connection1.send(consumerInfo1); + + // Send the messages + for (int i = 0; i < 4; i++) { + Message message = createMessage(producerInfo1, destination, deliveryMode); + connection1.send(message); + } + + // Begin the transaction. + LocalTransactionId txid = createLocalTransaction(sessionInfo1); + connection1.send(createBeginTransaction(connectionInfo1, txid)); + + // Acknowledge the first 2 messages. + for (int i = 0; i < 2; i++) { + Message m1 = receiveMessage(connection1); + assertNotNull("m1 is null for index: " + i, m1); + MessageAck ack = createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE); + ack.setTransactionId(txid); + connection1.request(ack); + } + + // Commit the transaction. + connection1.send(createCommitTransaction1Phase(connectionInfo1, txid)); + + // The queue should now only have the remaining 2 messages + assertEquals(2, countMessagesInQueue(connection1, connectionInfo1, destination)); + } + + public void initCombosForTestConsumerCloseCausesRedelivery() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("TEST")}); + } + + public void testConsumerCloseCausesRedelivery() throws Exception { + + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo1); + + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + consumerInfo1.setPrefetchSize(100); + connection1.request(consumerInfo1); + + // Send the messages + connection1.send(createMessage(producerInfo1, destination, deliveryMode)); + connection1.send(createMessage(producerInfo1, destination, deliveryMode)); + connection1.send(createMessage(producerInfo1, destination, deliveryMode)); + connection1.send(createMessage(producerInfo1, destination, deliveryMode)); + + // Receive the messages. + for (int i = 0; i < 4; i++) { + Message m1 = receiveMessage(connection1); + assertNotNull("m1 is null for index: " + i, m1); + assertFalse(m1.isRedelivered()); + } + + // Close the consumer without acking.. this should cause re-delivery of + // the messages. + connection1.send(consumerInfo1.createRemoveCommand()); + + // Create another consumer that should get the messages again. + ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo1, destination); + consumerInfo2.setPrefetchSize(100); + connection1.request(consumerInfo2); + + // Receive the messages. + for (int i = 0; i < 4; i++) { + Message m1 = receiveMessage(connection1); + assertNotNull("m1 is null for index: " + i, m1); + assertTrue(m1.isRedelivered()); + } + assertNoMessagesLeft(connection1); + + } + + public void testTopicDurableSubscriptionCanBeRestored() throws Exception { + + ActiveMQDestination destination = new ActiveMQTopic("TEST"); + + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + connectionInfo1.setClientId("clientid1"); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo1); + + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + consumerInfo1.setPrefetchSize(100); + consumerInfo1.setSubscriptionName("test"); + connection1.send(consumerInfo1); + + // Send the messages + connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); + connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); + connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); + connection1.request(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); + + // Get the messages + Message m = null; + for (int i = 0; i < 2; i++) { + m = receiveMessage(connection1); + assertNotNull(m); + } + // Ack the last message. + connection1.send(createAck(consumerInfo1, m, 2, MessageAck.STANDARD_ACK_TYPE)); + // Close the connection. + connection1.request(closeConnectionInfo(connectionInfo1)); + connection1.stop(); + + // Setup a second connection + StubConnection connection2 = createConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + connectionInfo2.setClientId("clientid1"); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); + consumerInfo2.setPrefetchSize(100); + consumerInfo2.setSubscriptionName("test"); + + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + connection2.send(consumerInfo2); + + // Get the rest of the messages + for (int i = 0; i < 2; i++) { + Message m1 = receiveMessage(connection2); + assertNotNull("m1 is null for index: " + i, m1); + } + assertNoMessagesLeft(connection2); + } + + public void initCombosForTestGroupedMessagesDeliveredToOnlyOneConsumer() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + } + + public void testGroupedMessagesDeliveredToOnlyOneConsumer() throws Exception { + + ActiveMQDestination destination = new ActiveMQQueue("TEST"); + + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo); + + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + consumerInfo1.setPrefetchSize(1); + connection1.send(consumerInfo1); + + // Send the messages. + for (int i = 0; i < 4; i++) { + Message message = createMessage(producerInfo, destination, deliveryMode); + message.setGroupID("TEST-GROUP"); + message.setGroupSequence(i + 1); + connection1.request(message); + } + + // Setup a second connection + StubConnection connection2 = createConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + + ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); + consumerInfo2.setPrefetchSize(1); + connection2.send(consumerInfo2); + + // All the messages should have been sent down connection 1.. just get + // the first 3 + for (int i = 0; i < 3; i++) { + Message m1 = receiveMessage(connection1); + assertNotNull("m1 is null for index: " + i, m1); + connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); + } + + // Close the first consumer. + connection1.request(closeConsumerInfo(consumerInfo1)); + + // The last messages should now go the the second consumer. + for (int i = 0; i < 1; i++) { + Message m1 = receiveMessage(connection2); + assertNotNull("m1 is null for index: " + i, m1); + connection2.request(createAck(consumerInfo2, m1, 1, MessageAck.STANDARD_ACK_TYPE)); + } + + assertNoMessagesLeft(connection2); + } + + public void initCombosForTestTopicConsumerOnlySeeMessagesAfterCreation() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("durableConsumer", new Object[]{Boolean.TRUE, Boolean.FALSE}); + } + + public void testTopicConsumerOnlySeeMessagesAfterCreation() throws Exception { + + ActiveMQDestination destination = new ActiveMQTopic("TEST"); + + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + connectionInfo1.setClientId("A"); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo1); + + // Send the 1st message + connection1.send(createMessage(producerInfo1, destination, deliveryMode)); + + // Create the durable subscription. + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + if (durableConsumer) { + consumerInfo1.setSubscriptionName("test"); + } + consumerInfo1.setPrefetchSize(100); + connection1.send(consumerInfo1); + + Message m = createMessage(producerInfo1, destination, deliveryMode); + connection1.send(m); + connection1.send(createMessage(producerInfo1, destination, deliveryMode)); + + // Subscription should skip over the first message + Message m2 = receiveMessage(connection1); + assertNotNull(m2); + assertEquals(m.getMessageId(), m2.getMessageId()); + m2 = receiveMessage(connection1); + assertNotNull(m2); + + assertNoMessagesLeft(connection1); + } + + public void initCombosForTestTopicRetroactiveConsumerSeeMessagesBeforeCreation() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("durableConsumer", new Object[]{Boolean.TRUE, Boolean.FALSE}); + } + + public void testTopicRetroactiveConsumerSeeMessagesBeforeCreation() throws Exception { + + ActiveMQDestination destination = new ActiveMQTopic("TEST"); + + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + connectionInfo1.setClientId("A"); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo1); + + // Send the messages + Message m = createMessage(producerInfo1, destination, deliveryMode); + connection1.send(m); + + // Create the durable subscription. + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + if (durableConsumer) { + consumerInfo1.setSubscriptionName("test"); + } + consumerInfo1.setPrefetchSize(100); + consumerInfo1.setRetroactive(true); + connection1.send(consumerInfo1); + + connection1.send(createMessage(producerInfo1, destination, deliveryMode)); + connection1.request(createMessage(producerInfo1, destination, deliveryMode)); + + // the behavior is VERY dependent on the recovery policy used. + // But the default broker settings try to make it as consistent as + // possible + + // Subscription should see all messages sent. + Message m2 = receiveMessage(connection1); + assertNotNull(m2); + assertEquals(m.getMessageId(), m2.getMessageId()); + for (int i = 0; i < 2; i++) { + m2 = receiveMessage(connection1); + assertNotNull(m2); + } + + assertNoMessagesLeft(connection1); + } + + // + // TODO: need to reimplement this since we don't fail when we send to a + // non-existent + // destination. But if we can access the Region directly then we should be + // able to + // check that if the destination was removed. + // + // public void initCombosForTestTempDestinationsRemovedOnConnectionClose() { + // addCombinationValues( "deliveryMode", new Object[]{ + // Integer.valueOf(DeliveryMode.NON_PERSISTENT), + // Integer.valueOf(DeliveryMode.PERSISTENT)} ); + // addCombinationValues( "destinationType", new Object[]{ + // Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), + // Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)} ); + // } + // + // public void testTempDestinationsRemovedOnConnectionClose() throws + // Exception { + // + // // Setup a first connection + // StubConnection connection1 = createConnection(); + // ConnectionInfo connectionInfo1 = createConnectionInfo(); + // SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + // ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); + // connection1.send(connectionInfo1); + // connection1.send(sessionInfo1); + // connection1.send(producerInfo1); + // + // destination = createDestinationInfo(connection1, connectionInfo1, + // destinationType); + // + // StubConnection connection2 = createConnection(); + // ConnectionInfo connectionInfo2 = createConnectionInfo(); + // SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + // ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); + // connection2.send(connectionInfo2); + // connection2.send(sessionInfo2); + // connection2.send(producerInfo2); + // + // // Send from connection2 to connection1's temp destination. Should + // succeed. + // connection2.send(createMessage(producerInfo2, destination, + // deliveryMode)); + // + // // Close connection 1 + // connection1.request(closeConnectionInfo(connectionInfo1)); + // + // try { + // // Send from connection2 to connection1's temp destination. Should not + // succeed. + // connection2.request(createMessage(producerInfo2, destination, + // deliveryMode)); + // fail("Expected JMSException."); + // } catch ( JMSException success ) { + // } + // + // } + + // public void initCombosForTestTempDestinationsAreNotAutoCreated() { + // addCombinationValues( "deliveryMode", new Object[]{ + // Integer.valueOf(DeliveryMode.NON_PERSISTENT), + // Integer.valueOf(DeliveryMode.PERSISTENT)} ); + // addCombinationValues( "destinationType", new Object[]{ + // Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), + // Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)} ); + // } + // + // + + // We create temp destination on demand now so this test case is no longer + // valid. + // + // public void testTempDestinationsAreNotAutoCreated() throws Exception { + // + // // Setup a first connection + // StubConnection connection1 = createConnection(); + // ConnectionInfo connectionInfo1 = createConnectionInfo(); + // SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + // ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); + // connection1.send(connectionInfo1); + // connection1.send(sessionInfo1); + // connection1.send(producerInfo1); + // + // destination = + // ActiveMQDestination.createDestination(connectionInfo1.getConnectionId()+":1", + // destinationType); + // + // // Should not be able to send to a non-existent temp destination. + // try { + // connection1.request(createMessage(producerInfo1, destination, + // deliveryMode)); + // fail("Expected JMSException."); + // } catch ( JMSException success ) { + // } + // + // } + + public void initCombosForTestExclusiveQueueDeliversToOnlyOneConsumer() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + } + + public void testExclusiveQueueDeliversToOnlyOneConsumer() throws Exception { + + ActiveMQDestination destination = new ActiveMQQueue("TEST"); + + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo); + + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + consumerInfo1.setPrefetchSize(1); + consumerInfo1.setExclusive(true); + connection1.send(consumerInfo1); + + // Send a message.. this should make consumer 1 the exclusive owner. + connection1.request(createMessage(producerInfo, destination, deliveryMode)); + + // Setup a second connection + StubConnection connection2 = createConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); + consumerInfo2.setPrefetchSize(1); + consumerInfo2.setExclusive(true); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + connection2.request(consumerInfo2); + + // Second message should go to consumer 1 even though consumer 2 is + // ready + // for dispatch. + connection1.send(createMessage(producerInfo, destination, deliveryMode)); + connection1.send(createMessage(producerInfo, destination, deliveryMode)); + + // Acknowledge the first 2 messages + for (int i = 0; i < 2; i++) { + Message m1 = receiveMessage(connection1); + assertNotNull(m1); + connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); + } + + // Close the first consumer. + connection1.send(closeConsumerInfo(consumerInfo1)); + + // The last two messages should now go the the second consumer. + connection1.send(createMessage(producerInfo, destination, deliveryMode)); + + for (int i = 0; i < 2; i++) { + Message m1 = receiveMessage(connection2); + assertNotNull(m1); + connection2.send(createAck(consumerInfo2, m1, 1, MessageAck.STANDARD_ACK_TYPE)); + } + + assertNoMessagesLeft(connection2); + } + + public void initCombosForTestWildcardConsume() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); + } + + public void testWildcardConsume() throws Exception { + + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo1); + + // setup the wildcard consumer. + ActiveMQDestination compositeDestination = ActiveMQDestination.createDestination("WILD.*.TEST", destinationType); + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, compositeDestination); + consumerInfo1.setPrefetchSize(100); + connection1.send(consumerInfo1); + + // These two message should NOT match the wild card. + connection1.send(createMessage(producerInfo1, ActiveMQDestination.createDestination("WILD.CARD", destinationType), deliveryMode)); + connection1.send(createMessage(producerInfo1, ActiveMQDestination.createDestination("WILD.TEST", destinationType), deliveryMode)); + + // These two message should match the wild card. + ActiveMQDestination d1 = ActiveMQDestination.createDestination("WILD.CARD.TEST", destinationType); + connection1.send(createMessage(producerInfo1, d1, deliveryMode)); + + Message m = receiveMessage(connection1); + assertNotNull(m); + assertEquals(d1, m.getDestination()); + + ActiveMQDestination d2 = ActiveMQDestination.createDestination("WILD.FOO.TEST", destinationType); + connection1.request(createMessage(producerInfo1, d2, deliveryMode)); + m = receiveMessage(connection1); + assertNotNull(m); + assertEquals(d2, m.getDestination()); + + assertNoMessagesLeft(connection1); + connection1.send(closeConnectionInfo(connectionInfo1)); + } + + public void initCombosForTestCompositeConsume() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); + } + + public void testCompositeConsume() throws Exception { + + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo1); + + // setup the composite consumer. + ActiveMQDestination compositeDestination = ActiveMQDestination.createDestination("A,B", destinationType); + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, compositeDestination); + consumerInfo1.setRetroactive(true); + consumerInfo1.setPrefetchSize(100); + connection1.send(consumerInfo1); + + // Publish to the two destinations + ActiveMQDestination destinationA = ActiveMQDestination.createDestination("A", destinationType); + ActiveMQDestination destinationB = ActiveMQDestination.createDestination("B", destinationType); + + // Send a message to each destination . + connection1.send(createMessage(producerInfo1, destinationA, deliveryMode)); + connection1.send(createMessage(producerInfo1, destinationB, deliveryMode)); + + // The consumer should get both messages. + for (int i = 0; i < 2; i++) { + Message m1 = receiveMessage(connection1); + assertNotNull(m1); + } + + assertNoMessagesLeft(connection1); + connection1.send(closeConnectionInfo(connectionInfo1)); + } + + public void initCombosForTestCompositeSend() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); + } + + public void testCompositeSend() throws Exception { + + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo1); + + ActiveMQDestination destinationA = ActiveMQDestination.createDestination("A", destinationType); + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destinationA); + consumerInfo1.setRetroactive(true); + consumerInfo1.setPrefetchSize(100); + connection1.request(consumerInfo1); + + // Setup a second connection + StubConnection connection2 = createConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + + ActiveMQDestination destinationB = ActiveMQDestination.createDestination("B", destinationType); + ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destinationB); + consumerInfo2.setRetroactive(true); + consumerInfo2.setPrefetchSize(100); + connection2.request(consumerInfo2); + + // Send the messages to the composite destination. + ActiveMQDestination compositeDestination = ActiveMQDestination.createDestination("A,B", destinationType); + for (int i = 0; i < 4; i++) { + connection1.request(createMessage(producerInfo1, compositeDestination, deliveryMode)); + } + + // The messages should have been delivered to both the A and B + // destination. + for (int i = 0; i < 4; i++) { + Message m1 = receiveMessage(connection1); + Message m2 = receiveMessage(connection2); + + assertNotNull(m1); + assertNotNull(m2); + + assertEquals(m1.getMessageId(), m2.getMessageId()); + assertEquals(compositeDestination, m1.getOriginalDestination()); + assertEquals(compositeDestination, m2.getOriginalDestination()); + + connection1.request(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); + connection2.request(createAck(consumerInfo2, m2, 1, MessageAck.STANDARD_ACK_TYPE)); + + } + + assertNoMessagesLeft(connection1); + assertNoMessagesLeft(connection2); + + connection1.send(closeConnectionInfo(connectionInfo1)); + connection2.send(closeConnectionInfo(connectionInfo2)); + } + + public void initCombosForTestConnectionCloseCascades() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destination", new Object[]{new ActiveMQTopic("TEST"), new ActiveMQQueue("TEST")}); + } + + public void testConnectionCloseCascades() throws Exception { + + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo1); + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + consumerInfo1.setPrefetchSize(100); + consumerInfo1.setNoLocal(true); + connection1.request(consumerInfo1); + + // Setup a second connection + StubConnection connection2 = createConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + connection2.send(producerInfo2); + + // Send the messages + connection2.send(createMessage(producerInfo2, destination, deliveryMode)); + connection2.send(createMessage(producerInfo2, destination, deliveryMode)); + connection2.send(createMessage(producerInfo2, destination, deliveryMode)); + connection2.send(createMessage(producerInfo2, destination, deliveryMode)); + + for (int i = 0; i < 4; i++) { + Message m1 = receiveMessage(connection1); + assertNotNull(m1); + connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); + } + + // give the async ack a chance to perculate and validate all are currently consumed + Message msg = receiveMessage(connection1, MAX_NULL_WAIT); + assertNull("all messages were received " + msg, msg); + + // Close the connection, this should in turn close the consumer. + connection1.request(closeConnectionInfo(connectionInfo1)); + + // Send another message, connection1 should not get the message. + connection2.request(createMessage(producerInfo2, destination, deliveryMode)); + + assertNull("no message received", receiveMessage(connection1, MAX_NULL_WAIT)); + } + + public void initCombosForTestSessionCloseCascades() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destination", new Object[]{new ActiveMQTopic("TEST"), new ActiveMQQueue("TEST")}); + } + + public void testSessionCloseCascades() throws Exception { + + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo1); + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + consumerInfo1.setPrefetchSize(100); + consumerInfo1.setNoLocal(true); + connection1.request(consumerInfo1); + + // Setup a second connection + StubConnection connection2 = createConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + connection2.send(producerInfo2); + + // Send the messages + connection2.send(createMessage(producerInfo2, destination, deliveryMode)); + connection2.send(createMessage(producerInfo2, destination, deliveryMode)); + connection2.send(createMessage(producerInfo2, destination, deliveryMode)); + connection2.send(createMessage(producerInfo2, destination, deliveryMode)); + + for (int i = 0; i < 4; i++) { + Message m1 = receiveMessage(connection1); + assertNotNull(m1); + connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); + } + + // Close the session, this should in turn close the consumer. + connection1.request(closeSessionInfo(sessionInfo1)); + + // Send another message, connection1 should not get the message. + connection2.request(createMessage(producerInfo2, destination, deliveryMode)); + + Message msg = receiveMessage(connection1, MAX_NULL_WAIT); + assertNull("no message received from connection1 after session close", msg); + } + + public void initCombosForTestConsumerClose() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destination", new Object[]{new ActiveMQTopic("TEST"), new ActiveMQQueue("TEST")}); + } + + public void testConsumerClose() throws Exception { + + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo1); + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + consumerInfo1.setPrefetchSize(100); + consumerInfo1.setNoLocal(true); + connection1.request(consumerInfo1); + + // Setup a second connection + StubConnection connection2 = createConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + connection2.send(producerInfo2); + + // Send the messages + connection2.send(createMessage(producerInfo2, destination, deliveryMode)); + connection2.send(createMessage(producerInfo2, destination, deliveryMode)); + connection2.send(createMessage(producerInfo2, destination, deliveryMode)); + connection2.send(createMessage(producerInfo2, destination, deliveryMode)); + + for (int i = 0; i < 4; i++) { + Message m1 = receiveMessage(connection1); + assertNotNull(m1); + connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); + } + + // give the async ack a chance to perculate and validate all are currently consumed + // use receive rather than poll as broker info is sent async and may still need to be dequeued + Message result = receiveMessage(connection1, MAX_NULL_WAIT); + assertNull("no more messages " + result, result); + + // Close the consumer. + connection1.request(closeConsumerInfo(consumerInfo1)); + + // Send another message, connection1 should not get the message. + connection2.request(createMessage(producerInfo2, destination, deliveryMode)); + + result = receiveMessage(connection1, MAX_NULL_WAIT); + assertNull("no message received after close " + result, result); + } + + public void initCombosForTestTopicNoLocal() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + } + + public void testTopicNoLocal() throws Exception { + + ActiveMQDestination destination = new ActiveMQTopic("TEST"); + + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo1); + + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + consumerInfo1.setRetroactive(true); + consumerInfo1.setPrefetchSize(100); + consumerInfo1.setNoLocal(true); + connection1.send(consumerInfo1); + + // Setup a second connection + StubConnection connection2 = createConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + connection2.send(producerInfo2); + + ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); + consumerInfo2.setRetroactive(true); + consumerInfo2.setPrefetchSize(100); + consumerInfo2.setNoLocal(true); + connection2.send(consumerInfo2); + + // Send the messages + connection1.send(createMessage(producerInfo1, destination, deliveryMode)); + connection1.send(createMessage(producerInfo1, destination, deliveryMode)); + connection1.send(createMessage(producerInfo1, destination, deliveryMode)); + connection1.send(createMessage(producerInfo1, destination, deliveryMode)); + + // The 2nd connection should get the messages. + for (int i = 0; i < 4; i++) { + Message m1 = receiveMessage(connection2); + assertNotNull(m1); + } + + // Send a message with the 2nd connection + Message message = createMessage(producerInfo2, destination, deliveryMode); + connection2.send(message); + + // The first connection should not see the initial 4 local messages sent + // but should + // see the messages from connection 2. + Message m = receiveMessage(connection1); + assertNotNull(m); + assertEquals(message.getMessageId(), m.getMessageId()); + + assertNoMessagesLeft(connection1); + assertNoMessagesLeft(connection2); + } + + public void initCombosForTopicDispatchIsBroadcast() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + } + + public void testTopicDispatchIsBroadcast() throws Exception { + + ActiveMQDestination destination = new ActiveMQTopic("TEST"); + + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo1); + + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + consumerInfo1.setRetroactive(true); + consumerInfo1.setPrefetchSize(100); + connection1.send(consumerInfo1); + + // Setup a second connection + StubConnection connection2 = createConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); + consumerInfo2.setRetroactive(true); + consumerInfo2.setPrefetchSize(100); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + connection2.send(consumerInfo2); + + // Send the messages + connection1.send(createMessage(producerInfo1, destination, deliveryMode)); + connection1.send(createMessage(producerInfo1, destination, deliveryMode)); + connection1.send(createMessage(producerInfo1, destination, deliveryMode)); + connection1.send(createMessage(producerInfo1, destination, deliveryMode)); + + // Get the messages + for (int i = 0; i < 4; i++) { + Message m1 = receiveMessage(connection1); + assertNotNull(m1); + m1 = receiveMessage(connection2); + assertNotNull(m1); + } + } + + public void initCombosForTestQueueDispatchedAreRedeliveredOnConsumerClose() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE)}); + } + + public void testQueueDispatchedAreRedeliveredOnConsumerClose() throws Exception { + + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo); + + destination = createDestinationInfo(connection1, connectionInfo1, destinationType); + + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + consumerInfo1.setPrefetchSize(100); + connection1.send(consumerInfo1); + + // Send the messages + connection1.send(createMessage(producerInfo, destination, deliveryMode)); + connection1.send(createMessage(producerInfo, destination, deliveryMode)); + connection1.send(createMessage(producerInfo, destination, deliveryMode)); + connection1.send(createMessage(producerInfo, destination, deliveryMode)); + + // Get the messages + for (int i = 0; i < 4; i++) { + Message m1 = receiveMessage(connection1); + assertNotNull(m1); + assertFalse(m1.isRedelivered()); + } + // Close the consumer without sending any ACKS. + connection1.send(closeConsumerInfo(consumerInfo1)); + + // Drain any in flight messages.. + while (connection1.getDispatchQueue().poll(0, TimeUnit.MILLISECONDS) != null) { + } + + // Add the second consumer + ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo1, destination); + consumerInfo2.setPrefetchSize(100); + connection1.send(consumerInfo2); + + // Make sure the messages were re delivered to the 2nd consumer. + for (int i = 0; i < 4; i++) { + Message m1 = receiveMessage(connection1); + assertNotNull(m1); + assertTrue(m1.isRedelivered()); + } + } + + public void initCombosForTestQueueBrowseMessages() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE)}); + } + + public void testQueueBrowseMessages() throws Exception { + + // Start a producer and consumer + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); + + destination = createDestinationInfo(connection, connectionInfo, destinationType); + + connection.send(createMessage(producerInfo, destination, deliveryMode)); + connection.send(createMessage(producerInfo, destination, deliveryMode)); + connection.send(createMessage(producerInfo, destination, deliveryMode)); + connection.send(createMessage(producerInfo, destination, deliveryMode)); + + // Use selector to skip first message. + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + consumerInfo.setBrowser(true); + connection.send(consumerInfo); + + for (int i = 0; i < 4; i++) { + Message m = receiveMessage(connection); + assertNotNull(m); + connection.send(createAck(consumerInfo, m, 1, MessageAck.DELIVERED_ACK_TYPE)); + } + + assertNoMessagesLeft(connection); + } + + public void initCombosForTestQueueSendThenAddConsumer() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE)}); + } + + public void testQueueSendThenAddConsumer() throws Exception { + + // Start a producer + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); + + destination = createDestinationInfo(connection, connectionInfo, destinationType); + + // Send a message to the broker. + connection.send(createMessage(producerInfo, destination, deliveryMode)); + + // Start the consumer + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); + + // Make sure the message was delivered. + Message m = receiveMessage(connection); + assertNotNull(m); + + } + + public void initCombosForTestQueueAckRemovesMessage() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE)}); + } + + public void testQueueAckRemovesMessage() throws Exception { + + // Start a producer and consumer + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); + + destination = createDestinationInfo(connection, connectionInfo, destinationType); + + Message message1 = createMessage(producerInfo, destination, deliveryMode); + Message message2 = createMessage(producerInfo, destination, deliveryMode); + connection.send(message1); + connection.send(message2); + + // Make sure the message was delivered. + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.request(consumerInfo); + Message m = receiveMessage(connection); + assertNotNull(m); + assertEquals(m.getMessageId(), message1.getMessageId()); + + assertTrue(countMessagesInQueue(connection, connectionInfo, destination) == 2); + connection.send(createAck(consumerInfo, m, 1, MessageAck.DELIVERED_ACK_TYPE)); + assertTrue(countMessagesInQueue(connection, connectionInfo, destination) == 2); + connection.send(createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE)); + assertTrue(countMessagesInQueue(connection, connectionInfo, destination) == 1); + + } + + public void initCombosForTestSelectorSkipsMessages() { + addCombinationValues("destination", new Object[]{new ActiveMQTopic("TEST_TOPIC"), new ActiveMQQueue("TEST_QUEUE")}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); + } + + public void testSelectorSkipsMessages() throws Exception { + + // Start a producer and consumer + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); + + destination = createDestinationInfo(connection, connectionInfo, destinationType); + + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + consumerInfo.setSelector("JMSType='last'"); + connection.send(consumerInfo); + + Message message1 = createMessage(producerInfo, destination, deliveryMode); + message1.setType("first"); + Message message2 = createMessage(producerInfo, destination, deliveryMode); + message2.setType("last"); + connection.send(message1); + connection.send(message2); + + // Use selector to skip first message. + Message m = receiveMessage(connection); + assertNotNull(m); + assertEquals(m.getMessageId(), message2.getMessageId()); + connection.send(createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE)); + connection.send(closeConsumerInfo(consumerInfo)); + + assertNoMessagesLeft(connection); + } + + public void initCombosForTestAddConsumerThenSend() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); + } + + public void testAddConsumerThenSend() throws Exception { + + // Start a producer and consumer + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); + + destination = createDestinationInfo(connection, connectionInfo, destinationType); + + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); + + connection.send(createMessage(producerInfo, destination, deliveryMode)); + + // Make sure the message was delivered. + Message m = receiveMessage(connection); + assertNotNull(m); + } + + public void initCombosForTestConsumerPrefetchAtOne() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); + } + + public void testConsumerPrefetchAtOne() throws Exception { + + // Start a producer and consumer + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); + + destination = createDestinationInfo(connection, connectionInfo, destinationType); + + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + consumerInfo.setPrefetchSize(1); + connection.send(consumerInfo); + + // Send 2 messages to the broker. + connection.send(createMessage(producerInfo, destination, deliveryMode)); + connection.send(createMessage(producerInfo, destination, deliveryMode)); + + // Make sure only 1 message was delivered. + Message m = receiveMessage(connection); + assertNotNull(m); + assertNoMessagesLeft(connection); + + } + + public void initCombosForTestConsumerPrefetchAtTwo() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); + } + + public void testConsumerPrefetchAtTwo() throws Exception { + + // Start a producer and consumer + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); + + destination = createDestinationInfo(connection, connectionInfo, destinationType); + + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + consumerInfo.setPrefetchSize(2); + connection.send(consumerInfo); + + // Send 3 messages to the broker. + connection.send(createMessage(producerInfo, destination, deliveryMode)); + connection.send(createMessage(producerInfo, destination, deliveryMode)); + connection.send(createMessage(producerInfo, destination, deliveryMode)); + + // Make sure only 1 message was delivered. + Message m = receiveMessage(connection); + assertNotNull(m); + m = receiveMessage(connection); + assertNotNull(m); + assertNoMessagesLeft(connection); + + } + + public void initCombosForTestConsumerPrefetchAndDeliveredAck() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); + } + + public void testConsumerPrefetchAndDeliveredAck() throws Exception { + + // Start a producer and consumer + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); + + destination = createDestinationInfo(connection, connectionInfo, destinationType); + + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + consumerInfo.setPrefetchSize(1); + connection.request(consumerInfo); + + // Send 3 messages to the broker. + connection.send(createMessage(producerInfo, destination, deliveryMode)); + connection.send(createMessage(producerInfo, destination, deliveryMode)); + connection.request(createMessage(producerInfo, destination, deliveryMode)); + + // Make sure only 1 message was delivered. + Message m1 = receiveMessage(connection); + assertNotNull(m1); + + assertNoMessagesLeft(connection); + + // Acknowledge the first message. This should cause the next message to + // get dispatched. + connection.request(createAck(consumerInfo, m1, 1, MessageAck.DELIVERED_ACK_TYPE)); + + Message m2 = receiveMessage(connection); + assertNotNull(m2); + connection.request(createAck(consumerInfo, m2, 1, MessageAck.DELIVERED_ACK_TYPE)); + + Message m3 = receiveMessage(connection); + assertNotNull(m3); + connection.request(createAck(consumerInfo, m3, 1, MessageAck.DELIVERED_ACK_TYPE)); + } + + public void testGetServices() throws Exception { + assertTrue(broker.getServices().length != 0); + } + + public static Test suite() { + return suite(BrokerTest.class); + } + + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerTestSupport.java index 5fa0620bad..dd247d3254 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerTestSupport.java @@ -56,302 +56,313 @@ import org.apache.activemq.usage.SystemUsage; public class BrokerTestSupport extends CombinationTestSupport { - /** - * Setting this to false makes the test run faster but they may be less - * accurate. - */ - public static final boolean FAST_NO_MESSAGE_LEFT_ASSERT = System.getProperty("FAST_NO_MESSAGE_LEFT_ASSERT", "true").equals("true"); + /** + * Setting this to false makes the test run faster but they may be less + * accurate. + */ + public static final boolean FAST_NO_MESSAGE_LEFT_ASSERT = System.getProperty("FAST_NO_MESSAGE_LEFT_ASSERT", "true").equals("true"); - protected RegionBroker regionBroker; - public BrokerService broker; - protected long idGenerator; - protected int msgIdGenerator; - protected int txGenerator; - protected int tempDestGenerator; - public PersistenceAdapter persistenceAdapter; + protected RegionBroker regionBroker; + public BrokerService broker; + protected long idGenerator; + protected int msgIdGenerator; + protected int txGenerator; + protected int tempDestGenerator; + public PersistenceAdapter persistenceAdapter; - protected String queueName = "TEST"; + protected String queueName = "TEST"; - protected int maxWait = 10000; + protected int maxWait = 10000; - protected SystemUsage memoryManager; - protected PolicyMap policyMap = new PolicyMap(); + protected SystemUsage memoryManager; + protected PolicyMap policyMap = new PolicyMap(); - @Override - protected void setUp() throws Exception { - super.setUp(); - broker = createBroker(); - policyMap.setDefaultEntry(getDefaultPolicy()); - broker.setDestinationPolicy(policyMap); - broker.start(); - } + @Override + protected void setUp() throws Exception { + super.setUp(); + broker = createBroker(); + policyMap.setDefaultEntry(getDefaultPolicy()); + broker.setDestinationPolicy(policyMap); + broker.start(); + } - protected PolicyEntry getDefaultPolicy() { - PolicyEntry policy = new PolicyEntry(); - policy.setDispatchPolicy(new RoundRobinDispatchPolicy()); - policy.setSubscriptionRecoveryPolicy(new FixedCountSubscriptionRecoveryPolicy()); - return policy; - } + protected PolicyEntry getDefaultPolicy() { + PolicyEntry policy = new PolicyEntry(); + policy.setDispatchPolicy(new RoundRobinDispatchPolicy()); + policy.setSubscriptionRecoveryPolicy(new FixedCountSubscriptionRecoveryPolicy()); + return policy; + } - protected BrokerService createBroker() throws Exception { - BrokerService broker = BrokerFactory.createBroker(new URI("broker:()/localhost?persistent=false")); - return broker; - } + protected BrokerService createBroker() throws Exception { + BrokerService broker = BrokerFactory.createBroker(new URI("broker:()/localhost?persistent=false")); + return broker; + } - @Override - protected void tearDown() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - broker = null; - regionBroker = null; - persistenceAdapter = null; - memoryManager = null; - super.tearDown(); - } + @Override + protected void tearDown() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + broker = null; + regionBroker = null; + persistenceAdapter = null; + memoryManager = null; + super.tearDown(); + } - protected ConsumerInfo createConsumerInfo(SessionInfo sessionInfo, ActiveMQDestination destination) throws Exception { - ConsumerInfo info = new ConsumerInfo(sessionInfo, ++idGenerator); - info.setBrowser(false); - info.setDestination(destination); - info.setPrefetchSize(1000); - info.setDispatchAsync(false); - return info; - } + protected ConsumerInfo createConsumerInfo(SessionInfo sessionInfo, + ActiveMQDestination destination) throws Exception { + ConsumerInfo info = new ConsumerInfo(sessionInfo, ++idGenerator); + info.setBrowser(false); + info.setDestination(destination); + info.setPrefetchSize(1000); + info.setDispatchAsync(false); + return info; + } - protected RemoveInfo closeConsumerInfo(ConsumerInfo consumerInfo) { - return consumerInfo.createRemoveCommand(); - } + protected RemoveInfo closeConsumerInfo(ConsumerInfo consumerInfo) { + return consumerInfo.createRemoveCommand(); + } - protected ProducerInfo createProducerInfo(SessionInfo sessionInfo) throws Exception { - ProducerInfo info = new ProducerInfo(sessionInfo, ++idGenerator); - return info; - } + protected ProducerInfo createProducerInfo(SessionInfo sessionInfo) throws Exception { + ProducerInfo info = new ProducerInfo(sessionInfo, ++idGenerator); + return info; + } - protected SessionInfo createSessionInfo(ConnectionInfo connectionInfo) throws Exception { - SessionInfo info = new SessionInfo(connectionInfo, ++idGenerator); - return info; - } + protected SessionInfo createSessionInfo(ConnectionInfo connectionInfo) throws Exception { + SessionInfo info = new SessionInfo(connectionInfo, ++idGenerator); + return info; + } - protected ConnectionInfo createConnectionInfo() throws Exception { - ConnectionInfo info = new ConnectionInfo(); - info.setConnectionId(new ConnectionId("connection:" + (++idGenerator))); - info.setClientId(info.getConnectionId().getValue()); - return info; - } + protected ConnectionInfo createConnectionInfo() throws Exception { + ConnectionInfo info = new ConnectionInfo(); + info.setConnectionId(new ConnectionId("connection:" + (++idGenerator))); + info.setClientId(info.getConnectionId().getValue()); + return info; + } - protected Message createMessage(ProducerInfo producerInfo, ActiveMQDestination destination) { - ActiveMQTextMessage message = new ActiveMQTextMessage(); - message.setMessageId(new MessageId(producerInfo, ++msgIdGenerator)); - message.setDestination(destination); - message.setPersistent(false); - try { - message.setText("Test Message Payload."); - } catch (MessageNotWriteableException e) { - } - return message; - } + protected Message createMessage(ProducerInfo producerInfo, ActiveMQDestination destination) { + ActiveMQTextMessage message = new ActiveMQTextMessage(); + message.setMessageId(new MessageId(producerInfo, ++msgIdGenerator)); + message.setDestination(destination); + message.setPersistent(false); + try { + message.setText("Test Message Payload."); + } + catch (MessageNotWriteableException e) { + } + return message; + } - protected MessageAck createAck(ConsumerInfo consumerInfo, Message msg, int count, byte ackType) { - MessageAck ack = new MessageAck(); - ack.setAckType(ackType); - ack.setConsumerId(consumerInfo.getConsumerId()); - ack.setDestination(msg.getDestination()); - ack.setLastMessageId(msg.getMessageId()); - ack.setMessageCount(count); - return ack; - } + protected MessageAck createAck(ConsumerInfo consumerInfo, Message msg, int count, byte ackType) { + MessageAck ack = new MessageAck(); + ack.setAckType(ackType); + ack.setConsumerId(consumerInfo.getConsumerId()); + ack.setDestination(msg.getDestination()); + ack.setLastMessageId(msg.getMessageId()); + ack.setMessageCount(count); + return ack; + } - protected void gc() { - regionBroker.gc(); - } + protected void gc() { + regionBroker.gc(); + } - protected void profilerPause(String prompt) throws IOException { - if (System.getProperty("profiler") != null) { - System.out.println(); - System.out.println(prompt + "> Press enter to continue: "); - while (System.in.read() != '\n') { + protected void profilerPause(String prompt) throws IOException { + if (System.getProperty("profiler") != null) { + System.out.println(); + System.out.println(prompt + "> Press enter to continue: "); + while (System.in.read() != '\n') { + } + System.out.println(prompt + "> Done."); + } + } + + protected RemoveInfo closeConnectionInfo(ConnectionInfo info) { + return info.createRemoveCommand(); + } + + protected RemoveInfo closeSessionInfo(SessionInfo info) { + return info.createRemoveCommand(); + } + + protected RemoveInfo closeProducerInfo(ProducerInfo info) { + return info.createRemoveCommand(); + } + + protected Message createMessage(ProducerInfo producerInfo, ActiveMQDestination destination, int deliveryMode) { + Message message = createMessage(producerInfo, destination); + message.setPersistent(deliveryMode == DeliveryMode.PERSISTENT); + return message; + } + + protected LocalTransactionId createLocalTransaction(SessionInfo info) { + LocalTransactionId id = new LocalTransactionId(info.getSessionId().getParentId(), ++txGenerator); + return id; + } + + protected XATransactionId createXATransaction(SessionInfo info) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream os = new DataOutputStream(baos); + os.writeLong(++txGenerator); + os.close(); + byte[] bs = baos.toByteArray(); + + XATransactionId xid = new XATransactionId(); + xid.setBranchQualifier(bs); + xid.setGlobalTransactionId(bs); + xid.setFormatId(55); + return xid; + } + + protected TransactionInfo createBeginTransaction(ConnectionInfo connectionInfo, TransactionId txid) { + TransactionInfo info = new TransactionInfo(connectionInfo.getConnectionId(), txid, TransactionInfo.BEGIN); + return info; + } + + protected TransactionInfo createPrepareTransaction(ConnectionInfo connectionInfo, TransactionId txid) { + TransactionInfo info = new TransactionInfo(connectionInfo.getConnectionId(), txid, TransactionInfo.PREPARE); + return info; + } + + protected TransactionInfo createCommitTransaction1Phase(ConnectionInfo connectionInfo, TransactionId txid) { + TransactionInfo info = new TransactionInfo(connectionInfo.getConnectionId(), txid, TransactionInfo.COMMIT_ONE_PHASE); + return info; + } + + protected TransactionInfo createCommitTransaction2Phase(ConnectionInfo connectionInfo, TransactionId txid) { + TransactionInfo info = new TransactionInfo(connectionInfo.getConnectionId(), txid, TransactionInfo.COMMIT_TWO_PHASE); + return info; + } + + protected TransactionInfo createRollbackTransaction(ConnectionInfo connectionInfo, TransactionId txid) { + TransactionInfo info = new TransactionInfo(connectionInfo.getConnectionId(), txid, TransactionInfo.ROLLBACK); + return info; + } + + protected int countMessagesInQueue(StubConnection connection, + ConnectionInfo connectionInfo, + ActiveMQDestination destination) throws Exception { + + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + connection.send(sessionInfo); + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + consumerInfo.setPrefetchSize(1); + consumerInfo.setBrowser(true); + connection.send(consumerInfo); + + ArrayList skipped = new ArrayList(); + + // Now get the messages. + Object m = connection.getDispatchQueue().poll(maxWait, TimeUnit.MILLISECONDS); + int i = 0; + while (m != null) { + if (m instanceof MessageDispatch && ((MessageDispatch) m).getConsumerId().equals(consumerInfo.getConsumerId())) { + MessageDispatch md = (MessageDispatch) m; + if (md.getMessage() != null) { + i++; + connection.send(createAck(consumerInfo, md.getMessage(), 1, MessageAck.STANDARD_ACK_TYPE)); } - System.out.println(prompt + "> Done."); - } - } - - protected RemoveInfo closeConnectionInfo(ConnectionInfo info) { - return info.createRemoveCommand(); - } - - protected RemoveInfo closeSessionInfo(SessionInfo info) { - return info.createRemoveCommand(); - } - - protected RemoveInfo closeProducerInfo(ProducerInfo info) { - return info.createRemoveCommand(); - } - - protected Message createMessage(ProducerInfo producerInfo, ActiveMQDestination destination, int deliveryMode) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(deliveryMode == DeliveryMode.PERSISTENT); - return message; - } - - protected LocalTransactionId createLocalTransaction(SessionInfo info) { - LocalTransactionId id = new LocalTransactionId(info.getSessionId().getParentId(), ++txGenerator); - return id; - } - - protected XATransactionId createXATransaction(SessionInfo info) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream os = new DataOutputStream(baos); - os.writeLong(++txGenerator); - os.close(); - byte[] bs = baos.toByteArray(); - - XATransactionId xid = new XATransactionId(); - xid.setBranchQualifier(bs); - xid.setGlobalTransactionId(bs); - xid.setFormatId(55); - return xid; - } - - protected TransactionInfo createBeginTransaction(ConnectionInfo connectionInfo, TransactionId txid) { - TransactionInfo info = new TransactionInfo(connectionInfo.getConnectionId(), txid, TransactionInfo.BEGIN); - return info; - } - - protected TransactionInfo createPrepareTransaction(ConnectionInfo connectionInfo, TransactionId txid) { - TransactionInfo info = new TransactionInfo(connectionInfo.getConnectionId(), txid, TransactionInfo.PREPARE); - return info; - } - - protected TransactionInfo createCommitTransaction1Phase(ConnectionInfo connectionInfo, TransactionId txid) { - TransactionInfo info = new TransactionInfo(connectionInfo.getConnectionId(), txid, TransactionInfo.COMMIT_ONE_PHASE); - return info; - } - - protected TransactionInfo createCommitTransaction2Phase(ConnectionInfo connectionInfo, TransactionId txid) { - TransactionInfo info = new TransactionInfo(connectionInfo.getConnectionId(), txid, TransactionInfo.COMMIT_TWO_PHASE); - return info; - } - - protected TransactionInfo createRollbackTransaction(ConnectionInfo connectionInfo, TransactionId txid) { - TransactionInfo info = new TransactionInfo(connectionInfo.getConnectionId(), txid, TransactionInfo.ROLLBACK); - return info; - } - - protected int countMessagesInQueue(StubConnection connection, ConnectionInfo connectionInfo, ActiveMQDestination destination) throws Exception { - - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - connection.send(sessionInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setPrefetchSize(1); - consumerInfo.setBrowser(true); - connection.send(consumerInfo); - - ArrayList skipped = new ArrayList(); - - // Now get the messages. - Object m = connection.getDispatchQueue().poll(maxWait, TimeUnit.MILLISECONDS); - int i = 0; - while (m != null) { - if (m instanceof MessageDispatch && ((MessageDispatch)m).getConsumerId().equals(consumerInfo.getConsumerId())) { - MessageDispatch md = (MessageDispatch)m; - if (md.getMessage() != null) { - i++; - connection.send(createAck(consumerInfo, md.getMessage(), 1, MessageAck.STANDARD_ACK_TYPE)); - } else { - break; - } - } else { - skipped.add(m); + else { + break; } - m = connection.getDispatchQueue().poll(maxWait, TimeUnit.MILLISECONDS); - } + } + else { + skipped.add(m); + } + m = connection.getDispatchQueue().poll(maxWait, TimeUnit.MILLISECONDS); + } - for (Iterator iter = skipped.iterator(); iter.hasNext();) { - connection.getDispatchQueue().put(iter.next()); - } + for (Iterator iter = skipped.iterator(); iter.hasNext(); ) { + connection.getDispatchQueue().put(iter.next()); + } - connection.send(closeSessionInfo(sessionInfo)); - return i; + connection.send(closeSessionInfo(sessionInfo)); + return i; - } + } - protected DestinationInfo createTempDestinationInfo(ConnectionInfo connectionInfo, byte destinationType) { - DestinationInfo info = new DestinationInfo(); - info.setConnectionId(connectionInfo.getConnectionId()); - info.setOperationType(DestinationInfo.ADD_OPERATION_TYPE); - info.setDestination(ActiveMQDestination.createDestination(info.getConnectionId() + ":" + (++tempDestGenerator), destinationType)); - return info; - } + protected DestinationInfo createTempDestinationInfo(ConnectionInfo connectionInfo, byte destinationType) { + DestinationInfo info = new DestinationInfo(); + info.setConnectionId(connectionInfo.getConnectionId()); + info.setOperationType(DestinationInfo.ADD_OPERATION_TYPE); + info.setDestination(ActiveMQDestination.createDestination(info.getConnectionId() + ":" + (++tempDestGenerator), destinationType)); + return info; + } - protected ActiveMQDestination createDestinationInfo(StubConnection connection, ConnectionInfo connectionInfo1, byte destinationType) throws Exception { - if ((destinationType & ActiveMQDestination.TEMP_MASK) != 0) { - DestinationInfo info = createTempDestinationInfo(connectionInfo1, destinationType); - connection.send(info); - return info.getDestination(); - } else { - return ActiveMQDestination.createDestination(queueName, destinationType); - } - } + protected ActiveMQDestination createDestinationInfo(StubConnection connection, + ConnectionInfo connectionInfo1, + byte destinationType) throws Exception { + if ((destinationType & ActiveMQDestination.TEMP_MASK) != 0) { + DestinationInfo info = createTempDestinationInfo(connectionInfo1, destinationType); + connection.send(info); + return info.getDestination(); + } + else { + return ActiveMQDestination.createDestination(queueName, destinationType); + } + } - protected DestinationInfo closeDestinationInfo(DestinationInfo info) { - info.setOperationType(DestinationInfo.REMOVE_OPERATION_TYPE); - info.setTimeout(0); - return info; - } + protected DestinationInfo closeDestinationInfo(DestinationInfo info) { + info.setOperationType(DestinationInfo.REMOVE_OPERATION_TYPE); + info.setTimeout(0); + return info; + } - public static void recursiveDelete(File f) { - if (f.isDirectory()) { - File[] files = f.listFiles(); - for (int i = 0; i < files.length; i++) { - recursiveDelete(files[i]); + public static void recursiveDelete(File f) { + if (f.isDirectory()) { + File[] files = f.listFiles(); + for (int i = 0; i < files.length; i++) { + recursiveDelete(files[i]); + } + } + f.delete(); + } + + protected StubConnection createConnection() throws Exception { + return new StubConnection(broker); + } + + /** + * @param connection + * @return + * @throws InterruptedException + */ + public Message receiveMessage(StubConnection connection) throws InterruptedException { + return receiveMessage(connection, maxWait); + } + + public Message receiveMessage(StubConnection connection, long timeout) throws InterruptedException { + while (true) { + Object o = connection.getDispatchQueue().poll(timeout, TimeUnit.MILLISECONDS); + + if (o == null) { + return null; + } + if (o instanceof MessageDispatch) { + + MessageDispatch dispatch = (MessageDispatch) o; + if (dispatch.getMessage() == null) { + return null; } - } - f.delete(); - } + dispatch.setMessage(dispatch.getMessage().copy()); + dispatch.getMessage().setRedeliveryCounter(dispatch.getRedeliveryCounter()); + return dispatch.getMessage(); + } + } + } - protected StubConnection createConnection() throws Exception { - return new StubConnection(broker); - } + ; - /** - * @param connection - * @return - * @throws InterruptedException - */ - public Message receiveMessage(StubConnection connection) throws InterruptedException { - return receiveMessage(connection, maxWait); - } - - public Message receiveMessage(StubConnection connection, long timeout) throws InterruptedException { - while (true) { - Object o = connection.getDispatchQueue().poll(timeout, TimeUnit.MILLISECONDS); - - if (o == null) { - return null; - } - if (o instanceof MessageDispatch) { - - MessageDispatch dispatch = (MessageDispatch)o; - if (dispatch.getMessage() == null) { - return null; - } - dispatch.setMessage(dispatch.getMessage().copy()); - dispatch.getMessage().setRedeliveryCounter(dispatch.getRedeliveryCounter()); - return dispatch.getMessage(); - } - } - }; - - protected void assertNoMessagesLeft(StubConnection connection) throws InterruptedException { - long wait = FAST_NO_MESSAGE_LEFT_ASSERT ? 0 : maxWait; - while (true) { - Object o = connection.getDispatchQueue().poll(wait, TimeUnit.MILLISECONDS); - if (o == null) { - return; - } - if (o instanceof MessageDispatch && ((MessageDispatch)o).getMessage() != null) { - fail("Received a message: "+((MessageDispatch)o).getMessage().getMessageId()); - } - } - } + protected void assertNoMessagesLeft(StubConnection connection) throws InterruptedException { + long wait = FAST_NO_MESSAGE_LEFT_ASSERT ? 0 : maxWait; + while (true) { + Object o = connection.getDispatchQueue().poll(wait, TimeUnit.MILLISECONDS); + if (o == null) { + return; + } + if (o instanceof MessageDispatch && ((MessageDispatch) o).getMessage() != null) { + fail("Received a message: " + ((MessageDispatch) o).getMessage().getMessageId()); + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ConcurrentConnectSimulationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ConcurrentConnectSimulationTest.java index 0c791fdda0..1f83947268 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ConcurrentConnectSimulationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ConcurrentConnectSimulationTest.java @@ -26,34 +26,34 @@ import org.apache.activemq.command.SessionId; public class ConcurrentConnectSimulationTest extends BrokerTestSupport { - /* - * simulate failover and retry of connection before broker has killed connection - * which appears as a concurrent connect request to the broker - * see: https://issues.apache.org/activemq/browse/AMQ-2241 - */ - public void testConcurrentConnection() throws Exception { + /* + * simulate failover and retry of connection before broker has killed connection + * which appears as a concurrent connect request to the broker + * see: https://issues.apache.org/activemq/browse/AMQ-2241 + */ + public void testConcurrentConnection() throws Exception { - StubConnection connection1 = createConnection(); - StubConnection connection2 = createConnection(); - - // reuse same connection info - ConnectionInfo connectionInfo = createConnectionInfo(); - connection1.request(connectionInfo); - connection2.request(connectionInfo); - - // second one should win out, verify using consumer on default session (watchAdvisories) - ConsumerId consumerId = new ConsumerId(new SessionId(connectionInfo.getConnectionId(), -1), 1); - ConsumerInfo consumerInfo = new ConsumerInfo(consumerId); - consumerInfo.setDestination(AdvisorySupport.TEMP_DESTINATION_COMPOSITE_ADVISORY_TOPIC); + StubConnection connection1 = createConnection(); + StubConnection connection2 = createConnection(); - connection2.request(consumerInfo); - } - - public static Test suite() { - return suite(ConcurrentConnectSimulationTest.class); - } + // reuse same connection info + ConnectionInfo connectionInfo = createConnectionInfo(); + connection1.request(connectionInfo); + connection2.request(connectionInfo); - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + // second one should win out, verify using consumer on default session (watchAdvisories) + ConsumerId consumerId = new ConsumerId(new SessionId(connectionInfo.getConnectionId(), -1), 1); + ConsumerInfo consumerInfo = new ConsumerInfo(consumerId); + consumerInfo.setDestination(AdvisorySupport.TEMP_DESTINATION_COMPOSITE_ADVISORY_TOPIC); + + connection2.request(consumerInfo); + } + + public static Test suite() { + return suite(ConcurrentConnectSimulationTest.class); + } + + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/CreateDestinationsOnStartupViaXBeanTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/CreateDestinationsOnStartupViaXBeanTest.java index 70fda7c7f4..9532a2e903 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/CreateDestinationsOnStartupViaXBeanTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/CreateDestinationsOnStartupViaXBeanTest.java @@ -26,44 +26,44 @@ import org.apache.activemq.command.ActiveMQTopic; import org.apache.activemq.xbean.XBeanBrokerFactory; /** - * - * + * + * */ public class CreateDestinationsOnStartupViaXBeanTest extends EmbeddedBrokerTestSupport { - public void testNewDestinationsAreCreatedOnStartup() throws Exception { - assertQueueCreated("FOO.BAR", true); - assertQueueCreated("FOO.DoesNotExist", false); - - assertTopicCreated("SOME.TOPIC", true); - assertTopicCreated("FOO.DoesNotExist", false); - } + public void testNewDestinationsAreCreatedOnStartup() throws Exception { + assertQueueCreated("FOO.BAR", true); + assertQueueCreated("FOO.DoesNotExist", false); - protected void assertQueueCreated(String name, boolean expected) throws Exception { - assertDestinationCreated(new ActiveMQQueue(name), expected); - } - - protected void assertTopicCreated(String name, boolean expected) throws Exception { - assertDestinationCreated(new ActiveMQTopic(name), expected); - } + assertTopicCreated("SOME.TOPIC", true); + assertTopicCreated("FOO.DoesNotExist", false); + } - protected void assertDestinationCreated(ActiveMQDestination destination, boolean expected) throws Exception { - Set answer = broker.getBroker().getDestinations(destination); - int size = expected ? 1 : 0; - assertEquals("Could not find destination: " + destination + ". Size of found destinations: " + answer, size, answer.size()); - } - - protected BrokerService createBroker() throws Exception { - XBeanBrokerFactory factory = new XBeanBrokerFactory(); - BrokerService answer = factory.createBroker(new URI(getBrokerConfigUri())); - - // lets disable persistence as we are a test - answer.setPersistent(false); - - return answer; - } + protected void assertQueueCreated(String name, boolean expected) throws Exception { + assertDestinationCreated(new ActiveMQQueue(name), expected); + } - protected String getBrokerConfigUri() { - return "org/apache/activemq/broker/destinations-on-start.xml"; - } + protected void assertTopicCreated(String name, boolean expected) throws Exception { + assertDestinationCreated(new ActiveMQTopic(name), expected); + } + + protected void assertDestinationCreated(ActiveMQDestination destination, boolean expected) throws Exception { + Set answer = broker.getBroker().getDestinations(destination); + int size = expected ? 1 : 0; + assertEquals("Could not find destination: " + destination + ". Size of found destinations: " + answer, size, answer.size()); + } + + protected BrokerService createBroker() throws Exception { + XBeanBrokerFactory factory = new XBeanBrokerFactory(); + BrokerService answer = factory.createBroker(new URI(getBrokerConfigUri())); + + // lets disable persistence as we are a test + answer.setPersistent(false); + + return answer; + } + + protected String getBrokerConfigUri() { + return "org/apache/activemq/broker/destinations-on-start.xml"; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/DedicatedTaskRunnerBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/DedicatedTaskRunnerBrokerTest.java index c1864207c4..e2779b1407 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/DedicatedTaskRunnerBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/DedicatedTaskRunnerBrokerTest.java @@ -20,18 +20,18 @@ import junit.framework.Test; public class DedicatedTaskRunnerBrokerTest extends BrokerTest { - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - broker.setDedicatedTaskRunner(true); - return broker; - } - - public static Test suite() { - return suite(DedicatedTaskRunnerBrokerTest.class); - } + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); + broker.setDedicatedTaskRunner(true); + return broker; + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static Test suite() { + return suite(DedicatedTaskRunnerBrokerTest.class); + } + + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/DoubleSubscriptionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/DoubleSubscriptionTest.java index 8fd129256e..d88afc73cf 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/DoubleSubscriptionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/DoubleSubscriptionTest.java @@ -19,6 +19,7 @@ package org.apache.activemq.broker; import javax.jms.DeliveryMode; import junit.framework.Test; + import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ConnectionInfo; @@ -36,83 +37,83 @@ import org.apache.activemq.network.NetworkTestSupport; public class DoubleSubscriptionTest extends NetworkTestSupport { - public ActiveMQDestination destination; - public int deliveryMode; + public ActiveMQDestination destination; + public int deliveryMode; - private String remoteURI = "tcp://localhost:0?wireFormat.tcpNoDelayEnabled=true"; + private String remoteURI = "tcp://localhost:0?wireFormat.tcpNoDelayEnabled=true"; - public static Test suite() { - return suite(DoubleSubscriptionTest.class); - } + public static Test suite() { + return suite(DoubleSubscriptionTest.class); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - public void initCombosForTestDoubleSubscription() { - addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST"), new ActiveMQQueue("TEST")}); - } + public void initCombosForTestDoubleSubscription() { + addCombinationValues("destination", new Object[]{new ActiveMQQueue("TEST"), new ActiveMQQueue("TEST")}); + } - public void testDoubleSubscription() throws Exception { + public void testDoubleSubscription() throws Exception { - // Start a normal consumer on the remote broker - StubConnection connection1 = createRemoteConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.request(consumerInfo1); + // Start a normal consumer on the remote broker + StubConnection connection1 = createRemoteConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.request(consumerInfo1); - // Start a normal producer on a remote broker - StubConnection connection2 = createRemoteConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.request(producerInfo2); + // Start a normal producer on a remote broker + StubConnection connection2 = createRemoteConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + connection2.request(producerInfo2); - // Send a message to make sure the basics are working - connection2.request(createMessage(producerInfo2, destination, DeliveryMode.PERSISTENT)); + // Send a message to make sure the basics are working + connection2.request(createMessage(producerInfo2, destination, DeliveryMode.PERSISTENT)); - Message m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNoMessagesLeft(connection1); + Message m1 = receiveMessage(connection1); + assertNotNull(m1); + assertNoMessagesLeft(connection1); - connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); + connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); - // Send a message to sit on the broker while we mess with it - connection2.request(createMessage(producerInfo2, destination, DeliveryMode.PERSISTENT)); + // Send a message to sit on the broker while we mess with it + connection2.request(createMessage(producerInfo2, destination, DeliveryMode.PERSISTENT)); - // Now we're going to resend the same consumer commands again and see if - // the broker - // can handle it. - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.request(consumerInfo1); + // Now we're going to resend the same consumer commands again and see if + // the broker + // can handle it. + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.request(consumerInfo1); - // After this there should be 2 messages on the broker... - connection2.request(createMessage(producerInfo2, destination, DeliveryMode.PERSISTENT)); + // After this there should be 2 messages on the broker... + connection2.request(createMessage(producerInfo2, destination, DeliveryMode.PERSISTENT)); - // ... let's start a fresh consumer... - connection1.stop(); - StubConnection connection3 = createRemoteConnection(); - ConnectionInfo connectionInfo3 = createConnectionInfo(); - SessionInfo sessionInfo3 = createSessionInfo(connectionInfo3); - ConsumerInfo consumerInfo3 = createConsumerInfo(sessionInfo3, destination); - connection3.send(connectionInfo3); - connection3.send(sessionInfo3); - connection3.request(consumerInfo3); + // ... let's start a fresh consumer... + connection1.stop(); + StubConnection connection3 = createRemoteConnection(); + ConnectionInfo connectionInfo3 = createConnectionInfo(); + SessionInfo sessionInfo3 = createSessionInfo(connectionInfo3); + ConsumerInfo consumerInfo3 = createConsumerInfo(sessionInfo3, destination); + connection3.send(connectionInfo3); + connection3.send(sessionInfo3); + connection3.request(consumerInfo3); - // ... and then grab the 2 that should be there. - assertNotNull(receiveMessage(connection3)); - assertNotNull(receiveMessage(connection3)); - assertNoMessagesLeft(connection3); - } + // ... and then grab the 2 that should be there. + assertNotNull(receiveMessage(connection3)); + assertNotNull(receiveMessage(connection3)); + assertNoMessagesLeft(connection3); + } - protected String getRemoteURI() { - return remoteURI; - } + protected String getRemoteURI() { + return remoteURI; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/DurablePersistentFalseRestartTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/DurablePersistentFalseRestartTest.java index b9724984e6..a9bb7a90bc 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/DurablePersistentFalseRestartTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/DurablePersistentFalseRestartTest.java @@ -24,7 +24,9 @@ import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; import javax.jms.Topic; + import junit.framework.Test; + import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; @@ -32,59 +34,57 @@ import org.apache.activemq.transport.failover.FailoverTransport; public class DurablePersistentFalseRestartTest extends BrokerRestartTestSupport { - @Override - protected void configureBroker(BrokerService broker) throws Exception { - super.configureBroker(broker); - broker.setPersistent(false); - broker.setPersistenceAdapter(new KahaDBPersistenceAdapter()); - broker.addConnector("tcp://0.0.0.0:0"); - } + @Override + protected void configureBroker(BrokerService broker) throws Exception { + super.configureBroker(broker); + broker.setPersistent(false); + broker.setPersistenceAdapter(new KahaDBPersistenceAdapter()); + broker.addConnector("tcp://0.0.0.0:0"); + } - public void testValidateNoPersistenceForDurableAfterRestart() throws Exception { + public void testValidateNoPersistenceForDurableAfterRestart() throws Exception { - ConnectionFactory connectionFactory = - new ActiveMQConnectionFactory("failover:(" + broker.getTransportConnectors().get(0).getPublishableConnectString() + ")"); - ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.setClientID("clientId"); - connection.start(); + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(" + broker.getTransportConnectors().get(0).getPublishableConnectString() + ")"); + ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.setClientID("clientId"); + connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Topic destination = session.createTopic(queueName); - MessageConsumer consumer = session.createDurableSubscriber(destination, "subscriberName"); + Topic destination = session.createTopic(queueName); + MessageConsumer consumer = session.createDurableSubscriber(destination, "subscriberName"); - populateDestination(10, destination, connection); + populateDestination(10, destination, connection); - restartBroker(); + restartBroker(); - // make failover aware of the restarted auto assigned port - ((FailoverTransport) connection.getTransport().narrow(FailoverTransport.class)).add(true, broker.getTransportConnectors().get(0).getPublishableConnectString()); + // make failover aware of the restarted auto assigned port + ((FailoverTransport) connection.getTransport().narrow(FailoverTransport.class)).add(true, broker.getTransportConnectors().get(0).getPublishableConnectString()); - TextMessage msg = (TextMessage) consumer.receive(4000); - assertNull("did not get a message when persistent=false, message: " + msg, msg); + TextMessage msg = (TextMessage) consumer.receive(4000); + assertNull("did not get a message when persistent=false, message: " + msg, msg); - connection.close(); - } + connection.close(); + } - private void populateDestination(final int nbMessages, - final Destination destination, javax.jms.Connection connection) - throws JMSException { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - for (int i = 1; i <= nbMessages; i++) { - producer.send(session.createTextMessage("")); - } - producer.close(); - session.close(); - } + private void populateDestination(final int nbMessages, + final Destination destination, + javax.jms.Connection connection) throws JMSException { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + for (int i = 1; i <= nbMessages; i++) { + producer.send(session.createTextMessage("")); + } + producer.close(); + session.close(); + } + public static Test suite() { + return suite(DurablePersistentFalseRestartTest.class); + } - public static Test suite() { - return suite(DurablePersistentFalseRestartTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/JdbcXARecoveryBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/JdbcXARecoveryBrokerTest.java index 5788dadf11..30650349a2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/JdbcXARecoveryBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/JdbcXARecoveryBrokerTest.java @@ -17,6 +17,7 @@ package org.apache.activemq.broker; import junit.framework.Test; + import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter; @@ -25,65 +26,66 @@ import org.apache.derby.jdbc.EmbeddedXADataSource; public class JdbcXARecoveryBrokerTest extends XARecoveryBrokerTest { - EmbeddedXADataSource dataSource; + EmbeddedXADataSource dataSource; - @Override - protected void setUp() throws Exception { - dataSource = new EmbeddedXADataSource(); - dataSource.setDatabaseName("derbyDb"); - dataSource.setCreateDatabase("create"); - super.setUp(); - } + @Override + protected void setUp() throws Exception { + dataSource = new EmbeddedXADataSource(); + dataSource.setDatabaseName("derbyDb"); + dataSource.setCreateDatabase("create"); + super.setUp(); + } - @Override - protected void tearDown() throws Exception { - super.tearDown(); - stopDerby(); - } + @Override + protected void tearDown() throws Exception { + super.tearDown(); + stopDerby(); + } - @Override - protected void configureBroker(BrokerService broker) throws Exception { - super.configureBroker(broker); + @Override + protected void configureBroker(BrokerService broker) throws Exception { + super.configureBroker(broker); - JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); - jdbc.setDataSource(dataSource); - broker.setPersistenceAdapter(jdbc); - } + JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); + jdbc.setDataSource(dataSource); + broker.setPersistenceAdapter(jdbc); + } - @Override - protected void restartBroker() throws Exception { - broker.stop(); - stopDerby(); - dataSource = new EmbeddedXADataSource(); - dataSource.setDatabaseName("derbyDb"); - dataSource.setCreateDatabase("create"); + @Override + protected void restartBroker() throws Exception { + broker.stop(); + stopDerby(); + dataSource = new EmbeddedXADataSource(); + dataSource.setDatabaseName("derbyDb"); + dataSource.setCreateDatabase("create"); - broker = createRestartedBroker(); - broker.start(); - } + broker = createRestartedBroker(); + broker.start(); + } - private void stopDerby() { - LOG.info("STOPPING DB!@!!!!"); - final EmbeddedDataSource ds = dataSource; - try { - ds.setShutdownDatabase("shutdown"); - ds.getConnection(); - } catch (Exception ignored) { - } + private void stopDerby() { + LOG.info("STOPPING DB!@!!!!"); + final EmbeddedDataSource ds = dataSource; + try { + ds.setShutdownDatabase("shutdown"); + ds.getConnection(); + } + catch (Exception ignored) { + } - } + } - public static Test suite() { - return suite(JdbcXARecoveryBrokerTest.class); - } + public static Test suite() { + return suite(JdbcXARecoveryBrokerTest.class); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - @Override - protected ActiveMQDestination createDestination() { - return new ActiveMQQueue("test,special"); - } + @Override + protected ActiveMQDestination createDestination() { + return new ActiveMQQueue("test,special"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/Main.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/Main.java index 9e1fa5e878..4fa4174477 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/Main.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/Main.java @@ -27,60 +27,61 @@ import org.apache.activemq.demo.DefaultQueueSender; /** * A helper class which can be handy for running a broker in your IDE from the * activemq-core module. - * - * */ public final class Main { - protected static boolean createConsumers; - private Main() { - } - - /** - * @param args - */ - public static void main(String[] args) { - try { - BrokerService broker = new BrokerService(); - broker.setPersistent(false); + protected static boolean createConsumers; - // String brokerDir = "xbean:...; - // System.setProperty("activemq.base", brokerDir); - // BrokerService broker = BrokerFactory.createBroker(new URI(brokerDir + "/activemq.xml")); + private Main() { + } - // for running on Java 5 without mx4j - ManagementContext managementContext = broker.getManagementContext(); - managementContext.setFindTigerMbeanServer(true); - managementContext.setUseMBeanServer(true); - managementContext.setCreateConnector(false); + /** + * @param args + */ + public static void main(String[] args) { + try { + BrokerService broker = new BrokerService(); + broker.setPersistent(false); - broker.setUseJmx(true); - // broker.setPlugins(new BrokerPlugin[] { new - // ConnectionDotFilePlugin(), new UDPTraceBrokerPlugin() }); - broker.addConnector("tcp://localhost:61616"); - broker.addConnector("stomp://localhost:61613"); - broker.start(); + // String brokerDir = "xbean:...; + // System.setProperty("activemq.base", brokerDir); + // BrokerService broker = BrokerFactory.createBroker(new URI(brokerDir + "/activemq.xml")); - // lets publish some messages so that there is some stuff to browse - DefaultQueueSender.main(new String[] {"Prices.Equity.IBM"}); - DefaultQueueSender.main(new String[] {"Prices.Equity.MSFT"}); + // for running on Java 5 without mx4j + ManagementContext managementContext = broker.getManagementContext(); + managementContext.setFindTigerMbeanServer(true); + managementContext.setUseMBeanServer(true); + managementContext.setCreateConnector(false); - // lets create a dummy couple of consumers - if (createConsumers) { - Connection connection = new ActiveMQConnectionFactory().createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createConsumer(new ActiveMQQueue("Orders.IBM")); - session.createConsumer(new ActiveMQQueue("Orders.MSFT"), "price > 100"); - Session session2 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session2.createConsumer(new ActiveMQQueue("Orders.MSFT"), "price > 200"); - } else { - // Lets wait for the broker - broker.waitUntilStopped(); - } - } catch (Exception e) { - System.out.println("Failed: " + e); - e.printStackTrace(); - } - } + broker.setUseJmx(true); + // broker.setPlugins(new BrokerPlugin[] { new + // ConnectionDotFilePlugin(), new UDPTraceBrokerPlugin() }); + broker.addConnector("tcp://localhost:61616"); + broker.addConnector("stomp://localhost:61613"); + broker.start(); + + // lets publish some messages so that there is some stuff to browse + DefaultQueueSender.main(new String[]{"Prices.Equity.IBM"}); + DefaultQueueSender.main(new String[]{"Prices.Equity.MSFT"}); + + // lets create a dummy couple of consumers + if (createConsumers) { + Connection connection = new ActiveMQConnectionFactory().createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createConsumer(new ActiveMQQueue("Orders.IBM")); + session.createConsumer(new ActiveMQQueue("Orders.MSFT"), "price > 100"); + Session session2 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + session2.createConsumer(new ActiveMQQueue("Orders.MSFT"), "price > 200"); + } + else { + // Lets wait for the broker + broker.waitUntilStopped(); + } + } + catch (Exception e) { + System.out.println("Failed: " + e); + e.printStackTrace(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/MarshallingBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/MarshallingBrokerTest.java index 31751562ff..45cf41af54 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/MarshallingBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/MarshallingBrokerTest.java @@ -27,49 +27,49 @@ import org.apache.activemq.wireformat.WireFormat; /** * Runs against the broker but marshals all request and response commands. - * - * */ public class MarshallingBrokerTest extends BrokerTest { - public WireFormat wireFormat = new OpenWireFormat(); + public WireFormat wireFormat = new OpenWireFormat(); - public void initCombos() { + public void initCombos() { - OpenWireFormat wf1 = new OpenWireFormat(); - wf1.setCacheEnabled(false); - OpenWireFormat wf2 = new OpenWireFormat(); - wf2.setCacheEnabled(true); + OpenWireFormat wf1 = new OpenWireFormat(); + wf1.setCacheEnabled(false); + OpenWireFormat wf2 = new OpenWireFormat(); + wf2.setCacheEnabled(true); - addCombinationValues("wireFormat", new Object[] {wf1, wf2, }); - } + addCombinationValues("wireFormat", new Object[]{wf1, wf2,}); + } - protected StubConnection createConnection() throws Exception { - return new StubConnection(broker) { - public Response request(Command command) throws Exception { - Response r = super.request((Command)wireFormat.unmarshal(wireFormat.marshal(command))); - if (r != null) { - r = (Response)wireFormat.unmarshal(wireFormat.marshal(r)); - } - return r; + protected StubConnection createConnection() throws Exception { + return new StubConnection(broker) { + public Response request(Command command) throws Exception { + Response r = super.request((Command) wireFormat.unmarshal(wireFormat.marshal(command))); + if (r != null) { + r = (Response) wireFormat.unmarshal(wireFormat.marshal(r)); } + return r; + } - public void send(Command command) throws Exception { - super.send((Command)wireFormat.unmarshal(wireFormat.marshal(command))); - } + public void send(Command command) throws Exception { + super.send((Command) wireFormat.unmarshal(wireFormat.marshal(command))); + } - protected void dispatch(Command command) throws InterruptedException, IOException { - super.dispatch((Command)wireFormat.unmarshal(wireFormat.marshal(command))); - }; - }; - } + protected void dispatch(Command command) throws InterruptedException, IOException { + super.dispatch((Command) wireFormat.unmarshal(wireFormat.marshal(command))); + } - public static Test suite() { - return suite(MarshallingBrokerTest.class); - } + ; + }; + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static Test suite() { + return suite(MarshallingBrokerTest.class); + } + + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/MessageExpirationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/MessageExpirationTest.java index 5c7f29d257..b112515b10 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/MessageExpirationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/MessageExpirationTest.java @@ -33,242 +33,243 @@ import org.apache.activemq.command.SessionInfo; public class MessageExpirationTest extends BrokerTestSupport { - public ActiveMQDestination destination; - public int deliveryMode = DeliveryMode.NON_PERSISTENT; - public int prefetch; - public byte destinationType = ActiveMQDestination.QUEUE_TYPE; - public boolean durableConsumer; + public ActiveMQDestination destination; + public int deliveryMode = DeliveryMode.NON_PERSISTENT; + public int prefetch; + public byte destinationType = ActiveMQDestination.QUEUE_TYPE; + public boolean durableConsumer; - protected Message createMessage(ProducerInfo producerInfo, ActiveMQDestination destination, int deliveryMode, int timeToLive) { - Message message = createMessage(producerInfo, destination, deliveryMode); - long now = System.currentTimeMillis(); - message.setTimestamp(now); - message.setExpiration(now + timeToLive); - return message; - } + protected Message createMessage(ProducerInfo producerInfo, + ActiveMQDestination destination, + int deliveryMode, + int timeToLive) { + Message message = createMessage(producerInfo, destination, deliveryMode); + long now = System.currentTimeMillis(); + message.setTimestamp(now); + message.setExpiration(now + timeToLive); + return message; + } - public void initCombosForTestMessagesWaitingForUssageDecreaseExpire() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE), - Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); - } + public void initCombosForTestMessagesWaitingForUssageDecreaseExpire() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); + } - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setPersistent(false); - return broker; - } + @Override + protected BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setPersistent(false); + return broker; + } - protected PolicyEntry getDefaultPolicy() { - PolicyEntry policy = super.getDefaultPolicy(); - // disable spooling - policy.setPendingSubscriberPolicy(new VMPendingSubscriberMessageStoragePolicy()); - // have aggressive expiry period to ensure no deadlock or clash - policy.setExpireMessagesPeriod(100); - - return policy; - } + protected PolicyEntry getDefaultPolicy() { + PolicyEntry policy = super.getDefaultPolicy(); + // disable spooling + policy.setPendingSubscriberPolicy(new VMPendingSubscriberMessageStoragePolicy()); + // have aggressive expiry period to ensure no deadlock or clash + policy.setExpireMessagesPeriod(100); - public void testMessagesWaitingForUsageDecreaseExpire() throws Exception { + return policy; + } - // Start a producer - final StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - final ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); + public void testMessagesWaitingForUsageDecreaseExpire() throws Exception { - // Start a consumer.. - final StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); + // Start a producer + final StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + final ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); - destination = createDestinationInfo(connection2, connectionInfo2, destinationType); - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); - consumerInfo2.setPrefetchSize(1); - connection2.request(consumerInfo2); + // Start a consumer.. + final StubConnection connection2 = createConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); - // Reduce the limit so that only 1 message can flow through the broker - // at a time. - broker.getSystemUsage().getMemoryUsage().setLimit(1); + destination = createDestinationInfo(connection2, connectionInfo2, destinationType); + ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); + consumerInfo2.setPrefetchSize(1); + connection2.request(consumerInfo2); - final Message m1 = createMessage(producerInfo, destination, deliveryMode); - final Message m2 = createMessage(producerInfo, destination, deliveryMode, 1000); - final Message m3 = createMessage(producerInfo, destination, deliveryMode); - final Message m4 = createMessage(producerInfo, destination, deliveryMode, 1000); + // Reduce the limit so that only 1 message can flow through the broker + // at a time. + broker.getSystemUsage().getMemoryUsage().setLimit(1); - // Produce in an async thread since the producer will be getting blocked - // by the usage manager.. - new Thread() { - public void run() { - // m1 and m3 should not expire.. but the others should. - try { - connection.send(m1); - connection.send(m2); - connection.send(m3); - connection.send(m4); - } catch (Exception e) { - e.printStackTrace(); - } + final Message m1 = createMessage(producerInfo, destination, deliveryMode); + final Message m2 = createMessage(producerInfo, destination, deliveryMode, 1000); + final Message m3 = createMessage(producerInfo, destination, deliveryMode); + final Message m4 = createMessage(producerInfo, destination, deliveryMode, 1000); + + // Produce in an async thread since the producer will be getting blocked + // by the usage manager.. + new Thread() { + public void run() { + // m1 and m3 should not expire.. but the others should. + try { + connection.send(m1); + connection.send(m2); + connection.send(m3); + connection.send(m4); } - }.start(); + catch (Exception e) { + e.printStackTrace(); + } + } + }.start(); - // Make sure only 1 message was delivered due to prefetch == 1 - Message m = receiveMessage(connection2); - assertNotNull(m); - assertEquals(m1.getMessageId(), m.getMessageId()); - assertNoMessagesLeft(connection); + // Make sure only 1 message was delivered due to prefetch == 1 + Message m = receiveMessage(connection2); + assertNotNull(m); + assertEquals(m1.getMessageId(), m.getMessageId()); + assertNoMessagesLeft(connection); - // Sleep before we ack so that the messages expire on the usage manager - Thread.sleep(1500); - connection2.send(createAck(consumerInfo2, m, 1, MessageAck.STANDARD_ACK_TYPE)); + // Sleep before we ack so that the messages expire on the usage manager + Thread.sleep(1500); + connection2.send(createAck(consumerInfo2, m, 1, MessageAck.STANDARD_ACK_TYPE)); - // 2nd message received should be m3.. it should have expired 2nd - // message sent. - m = receiveMessage(connection2); - assertNotNull(m); - assertEquals(m3.getMessageId(), m.getMessageId()); + // 2nd message received should be m3.. it should have expired 2nd + // message sent. + m = receiveMessage(connection2); + assertNotNull(m); + assertEquals(m3.getMessageId(), m.getMessageId()); - // Sleep before we ack so that the messages expire on the usage manager - Thread.sleep(1500); - connection2.send(createAck(consumerInfo2, m, 1, MessageAck.STANDARD_ACK_TYPE)); + // Sleep before we ack so that the messages expire on the usage manager + Thread.sleep(1500); + connection2.send(createAck(consumerInfo2, m, 1, MessageAck.STANDARD_ACK_TYPE)); - // And there should be no messages left now.. - assertNoMessagesLeft(connection2); + // And there should be no messages left now.. + assertNoMessagesLeft(connection2); - connection.send(closeConnectionInfo(connectionInfo)); - connection.send(closeConnectionInfo(connectionInfo2)); - } + connection.send(closeConnectionInfo(connectionInfo)); + connection.send(closeConnectionInfo(connectionInfo2)); + } - public void initCombosForTestMessagesInLongTransactionExpire() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.PERSISTENT), Integer.valueOf(DeliveryMode.NON_PERSISTENT)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); - } + public void initCombosForTestMessagesInLongTransactionExpire() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.PERSISTENT), Integer.valueOf(DeliveryMode.NON_PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); + } - public void testMessagesInLongTransactionExpire() throws Exception { + public void testMessagesInLongTransactionExpire() throws Exception { - // Start a producer and consumer - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); + // Start a producer and consumer + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); - destination = createDestinationInfo(connection, connectionInfo, destinationType); + destination = createDestinationInfo(connection, connectionInfo, destinationType); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setPrefetchSize(1000); - connection.send(consumerInfo); + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + consumerInfo.setPrefetchSize(1000); + connection.send(consumerInfo); - // Start the tx.. - LocalTransactionId txid = createLocalTransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); + // Start the tx.. + LocalTransactionId txid = createLocalTransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); - // m1 and m3 should not expire.. but the others should. - Message m1 = createMessage(producerInfo, destination, deliveryMode); - m1.setTransactionId(txid); - connection.send(m1); - Message m = createMessage(producerInfo, destination, deliveryMode, 1000); - m.setTransactionId(txid); - connection.send(m); - Message m3 = createMessage(producerInfo, destination, deliveryMode); - m3.setTransactionId(txid); - connection.send(m3); - m = createMessage(producerInfo, destination, deliveryMode, 1000); - m.setTransactionId(txid); - connection.send(m); + // m1 and m3 should not expire.. but the others should. + Message m1 = createMessage(producerInfo, destination, deliveryMode); + m1.setTransactionId(txid); + connection.send(m1); + Message m = createMessage(producerInfo, destination, deliveryMode, 1000); + m.setTransactionId(txid); + connection.send(m); + Message m3 = createMessage(producerInfo, destination, deliveryMode); + m3.setTransactionId(txid); + connection.send(m3); + m = createMessage(producerInfo, destination, deliveryMode, 1000); + m.setTransactionId(txid); + connection.send(m); - // Sleep before we commit so that the messages expire on the commit - // list.. - Thread.sleep(1500); - connection.send(createCommitTransaction1Phase(connectionInfo, txid)); + // Sleep before we commit so that the messages expire on the commit + // list.. + Thread.sleep(1500); + connection.send(createCommitTransaction1Phase(connectionInfo, txid)); - m = receiveMessage(connection); - assertNotNull(m); - assertEquals(m1.getMessageId(), m.getMessageId()); - connection.send(createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE)); + m = receiveMessage(connection); + assertNotNull(m); + assertEquals(m1.getMessageId(), m.getMessageId()); + connection.send(createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE)); - // 2nd message received should be m3.. it should have expired 2nd - // message sent. - m = receiveMessage(connection); - assertNotNull(m); - assertEquals(m3.getMessageId(), m.getMessageId()); - connection.send(createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE)); + // 2nd message received should be m3.. it should have expired 2nd + // message sent. + m = receiveMessage(connection); + assertNotNull(m); + assertEquals(m3.getMessageId(), m.getMessageId()); + connection.send(createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE)); - // And there should be no messages left now.. - assertNoMessagesLeft(connection); + // And there should be no messages left now.. + assertNoMessagesLeft(connection); - connection.send(closeConnectionInfo(connectionInfo)); - } + connection.send(closeConnectionInfo(connectionInfo)); + } - public void initCombosForTestMessagesInSubscriptionPendingListExpire() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), - Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); - } + public void initCombosForTestMessagesInSubscriptionPendingListExpire() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); + } - public void testMessagesInSubscriptionPendingListExpire() throws Exception { + public void testMessagesInSubscriptionPendingListExpire() throws Exception { - // Start a producer and consumer - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); + // Start a producer and consumer + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); - destination = createDestinationInfo(connection, connectionInfo, destinationType); + destination = createDestinationInfo(connection, connectionInfo, destinationType); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setPrefetchSize(1); - connection.send(consumerInfo); + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + consumerInfo.setPrefetchSize(1); + connection.send(consumerInfo); - // m1 and m3 should not expire.. but the others should. - Message m1 = createMessage(producerInfo, destination, deliveryMode); - connection.send(m1); - connection.send(createMessage(producerInfo, destination, deliveryMode, 1000)); - Message m3 = createMessage(producerInfo, destination, deliveryMode); - connection.send(m3); - connection.send(createMessage(producerInfo, destination, deliveryMode, 1000)); + // m1 and m3 should not expire.. but the others should. + Message m1 = createMessage(producerInfo, destination, deliveryMode); + connection.send(m1); + connection.send(createMessage(producerInfo, destination, deliveryMode, 1000)); + Message m3 = createMessage(producerInfo, destination, deliveryMode); + connection.send(m3); + connection.send(createMessage(producerInfo, destination, deliveryMode, 1000)); - // Make sure only 1 message was delivered due to prefetch == 1 - Message m = receiveMessage(connection); - assertNotNull(m); - assertEquals(m1.getMessageId(), m.getMessageId()); - assertNoMessagesLeft(connection); + // Make sure only 1 message was delivered due to prefetch == 1 + Message m = receiveMessage(connection); + assertNotNull(m); + assertEquals(m1.getMessageId(), m.getMessageId()); + assertNoMessagesLeft(connection); - // Sleep before we ack so that the messages expire on the pending list.. - Thread.sleep(1500); - connection.send(createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE)); + // Sleep before we ack so that the messages expire on the pending list.. + Thread.sleep(1500); + connection.send(createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE)); - // 2nd message received should be m3.. it should have expired 2nd - // message sent. - m = receiveMessage(connection); - assertNotNull(m); - assertEquals(m3.getMessageId(), m.getMessageId()); - connection.send(createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE)); + // 2nd message received should be m3.. it should have expired 2nd + // message sent. + m = receiveMessage(connection); + assertNotNull(m); + assertEquals(m3.getMessageId(), m.getMessageId()); + connection.send(createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE)); - // And there should be no messages left now.. - assertNoMessagesLeft(connection); + // And there should be no messages left now.. + assertNoMessagesLeft(connection); - connection.send(closeConnectionInfo(connectionInfo)); - } + connection.send(closeConnectionInfo(connectionInfo)); + } - public static Test suite() { - return suite(MessageExpirationTest.class); - } + public static Test suite() { + return suite(MessageExpirationTest.class); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/NioQueueSubscriptionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/NioQueueSubscriptionTest.java index 898256ce7d..3126491638 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/NioQueueSubscriptionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/NioQueueSubscriptionTest.java @@ -47,88 +47,87 @@ import static org.junit.Assert.fail; @RunWith(BlockJUnit4ClassRunner.class) public class NioQueueSubscriptionTest extends QueueSubscriptionTest { - protected static final Logger LOG = LoggerFactory.getLogger(NioQueueSubscriptionTest.class); + protected static final Logger LOG = LoggerFactory.getLogger(NioQueueSubscriptionTest.class); - private final Map exceptions = Collections.synchronizedMap(new HashMap()); + private final Map exceptions = Collections.synchronizedMap(new HashMap()); - @Override - protected ConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("tcp://localhost:62621?trace=false"); - } + @Override + protected ConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory("tcp://localhost:62621?trace=false"); + } + @Override + protected BrokerService createBroker() throws Exception { + BrokerService answer = BrokerFactory.createBroker(new URI("broker://nio://localhost:62621?useQueueForAccept=false&persistent=false&wiewformat.maxInactivityDuration=0")); + answer.getManagementContext().setCreateConnector(false); + answer.setUseJmx(false); + answer.setDeleteAllMessagesOnStartup(true); + final List policyEntries = new ArrayList(); + final PolicyEntry entry = new PolicyEntry(); + entry.setQueue(">"); + entry.setOptimizedDispatch(true); + policyEntries.add(entry); - @Override - protected BrokerService createBroker() throws Exception { - BrokerService answer = BrokerFactory.createBroker(new URI( - "broker://nio://localhost:62621?useQueueForAccept=false&persistent=false&wiewformat.maxInactivityDuration=0")); - answer.getManagementContext().setCreateConnector(false); - answer.setUseJmx(false); - answer.setDeleteAllMessagesOnStartup(true); - final List policyEntries = new ArrayList(); - final PolicyEntry entry = new PolicyEntry(); - entry.setQueue(">"); - entry.setOptimizedDispatch(true); - policyEntries.add(entry); + final PolicyMap policyMap = new PolicyMap(); + policyMap.setPolicyEntries(policyEntries); + answer.setDestinationPolicy(policyMap); + return answer; + } - final PolicyMap policyMap = new PolicyMap(); - policyMap.setPolicyEntries(policyEntries); - answer.setDestinationPolicy(policyMap); - return answer; - } + @Ignore("See AMQ-4286") + @Test(timeout = 60 * 1000) + public void testLotsOfConcurrentConnections() throws Exception { + ExecutorService executor = Executors.newCachedThreadPool(); + final ConnectionFactory factory = createConnectionFactory(); + int connectionCount = 400; + final AtomicInteger threadId = new AtomicInteger(0); + for (int i = 0; i < connectionCount; i++) { + executor.execute(new Runnable() { + @Override + public void run() { + final int innerId = threadId.incrementAndGet(); + try { + ExceptionListener listener = new NioQueueSubscriptionTestListener(innerId, exceptions, LOG); + ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); + connection.setExceptionListener(listener); + connection.start(); + assertNotNull(connection.getBrokerName()); + connections.add(connection); + } + catch (Exception e) { + LOG.error(">>>> Exception in run() on thread " + innerId, e); + exceptions.put(Thread.currentThread(), e); + } + } + }); + } + executor.shutdown(); + executor.awaitTermination(30, TimeUnit.SECONDS); - @Ignore("See AMQ-4286") - @Test(timeout = 60 * 1000) - public void testLotsOfConcurrentConnections() throws Exception { - ExecutorService executor = Executors.newCachedThreadPool(); - final ConnectionFactory factory = createConnectionFactory(); - int connectionCount = 400; - final AtomicInteger threadId = new AtomicInteger(0); - for (int i = 0; i < connectionCount; i++) { - executor.execute(new Runnable() { - @Override - public void run() { - final int innerId = threadId.incrementAndGet(); - try { - ExceptionListener listener = new NioQueueSubscriptionTestListener(innerId, exceptions, LOG); - ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); - connection.setExceptionListener(listener); - connection.start(); - assertNotNull(connection.getBrokerName()); - connections.add(connection); - } catch (Exception e) { - LOG.error(">>>> Exception in run() on thread " + innerId, e); - exceptions.put(Thread.currentThread(), e); - } - } - }); - } - - executor.shutdown(); - executor.awaitTermination(30, TimeUnit.SECONDS); - - if (!exceptions.isEmpty()) { - LOG.error(">>>> " + exceptions.size() + " exceptions like", exceptions.values().iterator().next()); - fail("unexpected exceptions in worker threads: " + exceptions.values().iterator().next()); - } - LOG.info("created " + connectionCount + " connections"); - } + if (!exceptions.isEmpty()) { + LOG.error(">>>> " + exceptions.size() + " exceptions like", exceptions.values().iterator().next()); + fail("unexpected exceptions in worker threads: " + exceptions.values().iterator().next()); + } + LOG.info("created " + connectionCount + " connections"); + } } class NioQueueSubscriptionTestListener implements ExceptionListener { - private int id = 0; - protected Logger LOG; - private final Map exceptions; - public NioQueueSubscriptionTestListener(int id, Map exceptions, Logger log) { - this.id = id; - this.exceptions = exceptions; - this.LOG = log; - } + private int id = 0; + protected Logger LOG; + private final Map exceptions; - @Override - public void onException(JMSException exception) { - LOG.error(">>>> Exception in onException() on thread " + id, exception); - exceptions.put(Thread.currentThread(), exception); - } + public NioQueueSubscriptionTestListener(int id, Map exceptions, Logger log) { + this.id = id; + this.exceptions = exceptions; + this.LOG = log; + } + + @Override + public void onException(JMSException exception) { + LOG.error(">>>> Exception in onException() on thread " + id, exception); + exceptions.put(Thread.currentThread(), exception); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/OutOfOrderXMLTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/OutOfOrderXMLTest.java index 11fbb56902..df3830d30c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/OutOfOrderXMLTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/OutOfOrderXMLTest.java @@ -17,17 +17,17 @@ package org.apache.activemq.broker; import java.net.URI; + import org.apache.activemq.xbean.XBeanBrokerFactory; import org.junit.Test; // https://issues.apache.org/activemq/browse/AMQ-2939 public class OutOfOrderXMLTest { - @Test - public void verifyBrokerCreationWhenXmlOutOfOrderValidationFalse() throws Exception { - BrokerService answer = - BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/broker/out-of-order-broker-elements.xml?validate=false")); - answer.stop(); + @Test + public void verifyBrokerCreationWhenXmlOutOfOrderValidationFalse() throws Exception { + BrokerService answer = BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/broker/out-of-order-broker-elements.xml?validate=false")); + answer.stop(); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ProgressPrinter.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ProgressPrinter.java index dcf4b6e614..361f2a1f77 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ProgressPrinter.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ProgressPrinter.java @@ -19,25 +19,25 @@ package org.apache.activemq.broker; public class ProgressPrinter { - private final long total; - private final long interval; - private long percentDone; - private long counter; + private final long total; + private final long interval; + private long percentDone; + private long counter; - public ProgressPrinter(long total, long interval) { - this.total = total; - this.interval = interval; - } + public ProgressPrinter(long total, long interval) { + this.total = total; + this.interval = interval; + } - public synchronized void increment() { - update(++counter); - } + public synchronized void increment() { + update(++counter); + } - public synchronized void update(long current) { - long at = 100 * current / total; - if ((percentDone / interval) != (at / interval)) { - percentDone = at; - System.out.println("Completed: " + percentDone + "%"); - } - } + public synchronized void update(long current) { + long at = 100 * current / total; + if ((percentDone / interval) != (at / interval)) { + percentDone = at; + System.out.println("Completed: " + percentDone + "%"); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/QueueMbeanRestartTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/QueueMbeanRestartTest.java index c004fefca2..8010961c59 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/QueueMbeanRestartTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/QueueMbeanRestartTest.java @@ -37,87 +37,86 @@ import org.slf4j.LoggerFactory; @RunWith(value = Parameterized.class) public class QueueMbeanRestartTest extends TestSupport { - private static final transient Logger LOG = LoggerFactory.getLogger(QueueMbeanRestartTest.class); - BrokerService broker; + private static final transient Logger LOG = LoggerFactory.getLogger(QueueMbeanRestartTest.class); - private final TestSupport.PersistenceAdapterChoice persistenceAdapterChoice; + BrokerService broker; - @Parameterized.Parameters - public static Collection getTestParameters() { - TestSupport.PersistenceAdapterChoice[] kahaDb = {TestSupport.PersistenceAdapterChoice.KahaDB}; - TestSupport.PersistenceAdapterChoice[] levelDb = {TestSupport.PersistenceAdapterChoice.LevelDB}; - TestSupport.PersistenceAdapterChoice[] jdbc = {TestSupport.PersistenceAdapterChoice.JDBC}; - List choices = new ArrayList(); - choices.add(kahaDb); - choices.add(levelDb); - choices.add(jdbc); + private final TestSupport.PersistenceAdapterChoice persistenceAdapterChoice; - return choices; - } + @Parameterized.Parameters + public static Collection getTestParameters() { + TestSupport.PersistenceAdapterChoice[] kahaDb = {TestSupport.PersistenceAdapterChoice.KahaDB}; + TestSupport.PersistenceAdapterChoice[] levelDb = {TestSupport.PersistenceAdapterChoice.LevelDB}; + TestSupport.PersistenceAdapterChoice[] jdbc = {TestSupport.PersistenceAdapterChoice.JDBC}; + List choices = new ArrayList(); + choices.add(kahaDb); + choices.add(levelDb); + choices.add(jdbc); - public QueueMbeanRestartTest(TestSupport.PersistenceAdapterChoice choice) { - this.persistenceAdapterChoice = choice; - } + return choices; + } - @Before - public void setUp() throws Exception { - topic = false; - super.setUp(); - } + public QueueMbeanRestartTest(TestSupport.PersistenceAdapterChoice choice) { + this.persistenceAdapterChoice = choice; + } - @After - public void tearDown() throws Exception { - super.tearDown(); - broker.stop(); - } + @Before + public void setUp() throws Exception { + topic = false; + super.setUp(); + } - @Test(timeout = 60000) - public void testMBeanPresenceOnRestart() throws Exception { - createBroker(true); + @After + public void tearDown() throws Exception { + super.tearDown(); + broker.stop(); + } - sendMessages(); - verifyPresenceOfQueueMbean(); - LOG.info("restart...."); + @Test(timeout = 60000) + public void testMBeanPresenceOnRestart() throws Exception { + createBroker(true); - restartBroker(); - verifyPresenceOfQueueMbean(); - } + sendMessages(); + verifyPresenceOfQueueMbean(); + LOG.info("restart...."); - private void restartBroker() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - Thread.sleep(5 * 1000); - createBroker(false); - broker.waitUntilStarted(); - } + restartBroker(); + verifyPresenceOfQueueMbean(); + } - private void verifyPresenceOfQueueMbean() throws Exception { - for (ObjectName name : broker.getManagementContext().queryNames(null, null)) { - LOG.info("candidate :" + name); - String type = name.getKeyProperty("destinationType"); - if (type != null && type.equals("Queue")) { - assertEquals( - JMXSupport.encodeObjectNamePart(((ActiveMQQueue) createDestination()).getPhysicalName()), - name.getKeyProperty("destinationName")); - LOG.info("found mbbean " + name); - return; - } - } - fail("expected to find matching queue mbean for: " + createDestination()); - } + private void restartBroker() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + Thread.sleep(5 * 1000); + createBroker(false); + broker.waitUntilStarted(); + } - private void sendMessages() throws Exception { - Session session = createConnection().createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(createDestination()); - producer.send(session.createTextMessage()); - } + private void verifyPresenceOfQueueMbean() throws Exception { + for (ObjectName name : broker.getManagementContext().queryNames(null, null)) { + LOG.info("candidate :" + name); + String type = name.getKeyProperty("destinationType"); + if (type != null && type.equals("Queue")) { + assertEquals(JMXSupport.encodeObjectNamePart(((ActiveMQQueue) createDestination()).getPhysicalName()), name.getKeyProperty("destinationName")); + LOG.info("found mbbean " + name); + return; + } + } + fail("expected to find matching queue mbean for: " + createDestination()); + } - private void createBroker(boolean deleteAll) throws Exception { - broker = new BrokerService(); - setPersistenceAdapter(broker, persistenceAdapterChoice); + private void sendMessages() throws Exception { + Session session = createConnection().createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(createDestination()); + producer.send(session.createTextMessage()); + } - broker.setDeleteAllMessagesOnStartup(deleteAll); - broker.start(); - } + private void createBroker(boolean deleteAll) throws Exception { + broker = new BrokerService(); + setPersistenceAdapter(broker, persistenceAdapterChoice); + + broker.setDeleteAllMessagesOnStartup(deleteAll); + broker.start(); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/QueueSubscriptionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/QueueSubscriptionTest.java index 6c3dc159cb..c1fed67b96 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/QueueSubscriptionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/QueueSubscriptionTest.java @@ -27,162 +27,162 @@ import org.junit.runners.BlockJUnit4ClassRunner; @RunWith(BlockJUnit4ClassRunner.class) public class QueueSubscriptionTest extends JmsMultipleClientsTestSupport { - protected int messageCount = 1000; // 1000 Messages per producer - protected int prefetchCount = 10; - @Before - @Override - public void setUp() throws Exception { - super.setUp(); - durable = false; - topic = false; - } + protected int messageCount = 1000; // 1000 Messages per producer + protected int prefetchCount = 10; - @After - @Override - public void tearDown() throws Exception { - super.tearDown(); - } + @Before + @Override + public void setUp() throws Exception { + super.setUp(); + durable = false; + topic = false; + } + @After + @Override + public void tearDown() throws Exception { + super.tearDown(); + } - @Test(timeout = 60 * 1000) - public void testManyProducersOneConsumer() throws Exception { - consumerCount = 1; - producerCount = 10; - messageCount = 100; - messageSize = 1; // 1 byte - prefetchCount = 10; + @Test(timeout = 60 * 1000) + public void testManyProducersOneConsumer() throws Exception { + consumerCount = 1; + producerCount = 10; + messageCount = 100; + messageSize = 1; // 1 byte + prefetchCount = 10; - doMultipleClientsTest(); + doMultipleClientsTest(); - assertTotalMessagesReceived(messageCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } + assertTotalMessagesReceived(messageCount * producerCount); + assertDestinationMemoryUsageGoesToZero(); + } - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersSmallMessagesOnePrefetch() throws Exception { - consumerCount = 2; - producerCount = 1; - messageCount = 1000; - messageSize = 1024; // 1 Kb - configurePrefetchOfOne(); + @Test(timeout = 60 * 1000) + public void testOneProducerTwoConsumersSmallMessagesOnePrefetch() throws Exception { + consumerCount = 2; + producerCount = 1; + messageCount = 1000; + messageSize = 1024; // 1 Kb + configurePrefetchOfOne(); - doMultipleClientsTest(); + doMultipleClientsTest(); - assertTotalMessagesReceived(messageCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } + assertTotalMessagesReceived(messageCount * producerCount); + assertDestinationMemoryUsageGoesToZero(); + } - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersSmallMessagesLargePrefetch() throws Exception { - consumerCount = 2; - producerCount = 1; - messageCount = 1000; - prefetchCount = messageCount * 2; - messageSize = 1024; // 1 Kb + @Test(timeout = 60 * 1000) + public void testOneProducerTwoConsumersSmallMessagesLargePrefetch() throws Exception { + consumerCount = 2; + producerCount = 1; + messageCount = 1000; + prefetchCount = messageCount * 2; + messageSize = 1024; // 1 Kb - doMultipleClientsTest(); + doMultipleClientsTest(); - assertTotalMessagesReceived(messageCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } + assertTotalMessagesReceived(messageCount * producerCount); + assertDestinationMemoryUsageGoesToZero(); + } - @Test(timeout = 2 * 60 * 1000) - public void testOneProducerTwoConsumersLargeMessagesOnePrefetch() throws Exception { - consumerCount = 2; - producerCount = 1; - messageCount = 10; - messageSize = 1024 * 1024 * 1; // 2 MB - configurePrefetchOfOne(); + @Test(timeout = 2 * 60 * 1000) + public void testOneProducerTwoConsumersLargeMessagesOnePrefetch() throws Exception { + consumerCount = 2; + producerCount = 1; + messageCount = 10; + messageSize = 1024 * 1024 * 1; // 2 MB + configurePrefetchOfOne(); - doMultipleClientsTest(); + doMultipleClientsTest(); - assertTotalMessagesReceived(messageCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } + assertTotalMessagesReceived(messageCount * producerCount); + assertDestinationMemoryUsageGoesToZero(); + } - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersLargeMessagesLargePrefetch() throws Exception { - consumerCount = 2; - producerCount = 1; - messageCount = 10; - prefetchCount = messageCount * 2; - messageSize = 1024 * 1024 * 1; // 2 MB + @Test(timeout = 60 * 1000) + public void testOneProducerTwoConsumersLargeMessagesLargePrefetch() throws Exception { + consumerCount = 2; + producerCount = 1; + messageCount = 10; + prefetchCount = messageCount * 2; + messageSize = 1024 * 1024 * 1; // 2 MB - doMultipleClientsTest(); + doMultipleClientsTest(); - assertTotalMessagesReceived(messageCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } + assertTotalMessagesReceived(messageCount * producerCount); + assertDestinationMemoryUsageGoesToZero(); + } - @Test(timeout = 60 * 1000) - public void testOneProducerManyConsumersFewMessages() throws Exception { - consumerCount = 50; - producerCount = 1; - messageCount = 10; - messageSize = 1; // 1 byte - prefetchCount = 10; + @Test(timeout = 60 * 1000) + public void testOneProducerManyConsumersFewMessages() throws Exception { + consumerCount = 50; + producerCount = 1; + messageCount = 10; + messageSize = 1; // 1 byte + prefetchCount = 10; - doMultipleClientsTest(); + doMultipleClientsTest(); - assertTotalMessagesReceived(messageCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } + assertTotalMessagesReceived(messageCount * producerCount); + assertDestinationMemoryUsageGoesToZero(); + } - @Test(timeout = 60 * 1000) - public void testOneProducerManyConsumersManyMessages() throws Exception { - consumerCount = 50; - producerCount = 1; - messageCount = 1000; - messageSize = 1; // 1 byte - prefetchCount = messageCount / consumerCount; - allMessagesList.setMaximumDuration(allMessagesList.getMaximumDuration() * 20); - doMultipleClientsTest(); + @Test(timeout = 60 * 1000) + public void testOneProducerManyConsumersManyMessages() throws Exception { + consumerCount = 50; + producerCount = 1; + messageCount = 1000; + messageSize = 1; // 1 byte + prefetchCount = messageCount / consumerCount; + allMessagesList.setMaximumDuration(allMessagesList.getMaximumDuration() * 20); + doMultipleClientsTest(); - assertTotalMessagesReceived(messageCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } + assertTotalMessagesReceived(messageCount * producerCount); + assertDestinationMemoryUsageGoesToZero(); + } - @Test(timeout = 2 * 60 * 1000) - public void testManyProducersManyConsumers() throws Exception { - consumerCount = 200; - producerCount = 50; - messageCount = 100; - messageSize = 1; // 1 byte - prefetchCount = 100; - allMessagesList.setMaximumDuration(allMessagesList.getMaximumDuration() * 20); - doMultipleClientsTest(); + @Test(timeout = 2 * 60 * 1000) + public void testManyProducersManyConsumers() throws Exception { + consumerCount = 200; + producerCount = 50; + messageCount = 100; + messageSize = 1; // 1 byte + prefetchCount = 100; + allMessagesList.setMaximumDuration(allMessagesList.getMaximumDuration() * 20); + doMultipleClientsTest(); - assertTotalMessagesReceived(messageCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } + assertTotalMessagesReceived(messageCount * producerCount); + assertDestinationMemoryUsageGoesToZero(); + } - protected void configurePrefetchOfOne() { - prefetchCount = 1; + protected void configurePrefetchOfOne() { + prefetchCount = 1; - // this is gonna be a bit slow what with the low prefetch so bump up the - // wait time - allMessagesList.setMaximumDuration(allMessagesList.getMaximumDuration() * 20); - } + // this is gonna be a bit slow what with the low prefetch so bump up the + // wait time + allMessagesList.setMaximumDuration(allMessagesList.getMaximumDuration() * 20); + } - public void doMultipleClientsTest() throws Exception { - // Create destination - final ActiveMQDestination dest = createDestination(); + public void doMultipleClientsTest() throws Exception { + // Create destination + final ActiveMQDestination dest = createDestination(); - // Create consumers - ActiveMQConnectionFactory consumerFactory = (ActiveMQConnectionFactory)createConnectionFactory(); - consumerFactory.getPrefetchPolicy().setAll(prefetchCount); + // Create consumers + ActiveMQConnectionFactory consumerFactory = (ActiveMQConnectionFactory) createConnectionFactory(); + consumerFactory.getPrefetchPolicy().setAll(prefetchCount); - startConsumers(consumerFactory, dest); + startConsumers(consumerFactory, dest); - startProducers(dest, messageCount); + startProducers(dest, messageCount); - // Wait for messages to be received. Make it proportional to the - // messages delivered. - int totalMessageCount = messageCount * producerCount; - if (dest.isTopic()) { - totalMessageCount *= consumerCount; - } - waitForAllMessagesToBeReceived(totalMessageCount); - } + // Wait for messages to be received. Make it proportional to the + // messages delivered. + int totalMessageCount = messageCount * producerCount; + if (dest.isTopic()) { + totalMessageCount *= consumerCount; + } + waitForAllMessagesToBeReceived(totalMessageCount); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ReconnectWithJMXEnabledTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ReconnectWithJMXEnabledTest.java index 181a90777c..a1555de7b0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ReconnectWithJMXEnabledTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ReconnectWithJMXEnabledTest.java @@ -33,60 +33,60 @@ import org.apache.activemq.EmbeddedBrokerTestSupport; */ public class ReconnectWithJMXEnabledTest extends EmbeddedBrokerTestSupport { - protected Connection connection; - protected boolean transacted; - protected int authMode = Session.AUTO_ACKNOWLEDGE; + protected Connection connection; + protected boolean transacted; + protected int authMode = Session.AUTO_ACKNOWLEDGE; - public void testTestUseConnectionCloseBrokerThenRestartInSameJVM() throws Exception { - connection = connectionFactory.createConnection(); - useConnection(connection); - connection.close(); + public void testTestUseConnectionCloseBrokerThenRestartInSameJVM() throws Exception { + connection = connectionFactory.createConnection(); + useConnection(connection); + connection.close(); - broker.stop(); - broker = createBroker(); - startBroker(); + broker.stop(); + broker = createBroker(); + startBroker(); - connectionFactory = createConnectionFactory(); - connection = connectionFactory.createConnection(); - useConnection(connection); - } + connectionFactory = createConnectionFactory(); + connection = connectionFactory.createConnection(); + useConnection(connection); + } - protected void setUp() throws Exception { - bindAddress = "tcp://localhost:0"; - super.setUp(); - } + protected void setUp() throws Exception { + bindAddress = "tcp://localhost:0"; + super.setUp(); + } - @Override - protected ConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString()); - } + @Override + protected ConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString()); + } - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - connection = null; - } - super.tearDown(); - } + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + connection = null; + } + super.tearDown(); + } - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setUseJmx(true); - answer.setPersistent(isPersistent()); - answer.addConnector(bindAddress); - return answer; - } + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + answer.setUseJmx(true); + answer.setPersistent(isPersistent()); + answer.addConnector(bindAddress); + return answer; + } - protected void useConnection(Connection connection) throws Exception { - connection.setClientID("foo"); - connection.start(); - Session session = connection.createSession(transacted, authMode); - Destination destination = createDestination(); - MessageConsumer consumer = session.createConsumer(destination); - MessageProducer producer = session.createProducer(destination); - Message message = session.createTextMessage("Hello World"); - producer.send(message); - Thread.sleep(1000); - consumer.close(); - } + protected void useConnection(Connection connection) throws Exception { + connection.setClientID("foo"); + connection.start(); + Session session = connection.createSession(transacted, authMode); + Destination destination = createDestination(); + MessageConsumer consumer = session.createConsumer(destination); + MessageProducer producer = session.createProducer(destination); + Message message = session.createTextMessage("Hello World"); + producer.send(message); + Thread.sleep(1000); + consumer.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/RecoveryBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/RecoveryBrokerTest.java index e56306397b..65612fe4ee 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/RecoveryBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/RecoveryBrokerTest.java @@ -37,550 +37,545 @@ import org.apache.activemq.command.XATransactionId; /** * Used to simulate the recovery that occurs when a broker shuts down. - * - * */ public class RecoveryBrokerTest extends BrokerRestartTestSupport { - /** - * Used to verify that after a broker restart durable subscriptions that use - * wild cards are still wild card subscription after broker restart. - * - * @throws Exception - */ - //need to revist!!! - public void XtestWildCardSubscriptionPreservedOnRestart() throws Exception { - ActiveMQDestination dest1 = new ActiveMQTopic("TEST.A"); - ActiveMQDestination dest2 = new ActiveMQTopic("TEST.B"); - ActiveMQDestination dest3 = new ActiveMQTopic("TEST.C"); - ActiveMQDestination wildDest = new ActiveMQTopic("TEST.>"); + /** + * Used to verify that after a broker restart durable subscriptions that use + * wild cards are still wild card subscription after broker restart. + * + * @throws Exception + */ + //need to revist!!! + public void XtestWildCardSubscriptionPreservedOnRestart() throws Exception { + ActiveMQDestination dest1 = new ActiveMQTopic("TEST.A"); + ActiveMQDestination dest2 = new ActiveMQTopic("TEST.B"); + ActiveMQDestination dest3 = new ActiveMQTopic("TEST.C"); + ActiveMQDestination wildDest = new ActiveMQTopic("TEST.>"); - ArrayList sentBeforeRestart = new ArrayList(); - ArrayList sentBeforeCreateConsumer = new ArrayList(); - ArrayList sentAfterCreateConsumer = new ArrayList(); + ArrayList sentBeforeRestart = new ArrayList(); + ArrayList sentBeforeCreateConsumer = new ArrayList(); + ArrayList sentAfterCreateConsumer = new ArrayList(); - // Setup a first connection - { - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - connectionInfo1.setClientId("A"); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo1); + // Setup a first connection + { + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + connectionInfo1.setClientId("A"); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo1); - // Create the durable subscription. - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, wildDest); - consumerInfo1.setSubscriptionName("test"); - consumerInfo1.setPrefetchSize(100); - connection1.send(consumerInfo1); + // Create the durable subscription. + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, wildDest); + consumerInfo1.setSubscriptionName("test"); + consumerInfo1.setPrefetchSize(100); + connection1.send(consumerInfo1); - // Close the subscription. - connection1.send(closeConsumerInfo(consumerInfo1)); + // Close the subscription. + connection1.send(closeConsumerInfo(consumerInfo1)); - // Send the messages - for (int i = 0; i < 4; i++) { - Message m = createMessage(producerInfo1, dest1, DeliveryMode.PERSISTENT); - connection1.send(m); - sentBeforeRestart.add(m.getMessageId()); - } - connection1.request(closeConnectionInfo(connectionInfo1)); - connection1.stop(); - } + // Send the messages + for (int i = 0; i < 4; i++) { + Message m = createMessage(producerInfo1, dest1, DeliveryMode.PERSISTENT); + connection1.send(m); + sentBeforeRestart.add(m.getMessageId()); + } + connection1.request(closeConnectionInfo(connectionInfo1)); + connection1.stop(); + } - // Restart the broker. - restartBroker(); + // Restart the broker. + restartBroker(); - // Get a connection to the new broker. - { - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - connectionInfo2.setClientId("A"); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); + // Get a connection to the new broker. + { + StubConnection connection2 = createConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + connectionInfo2.setClientId("A"); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); - ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); - connection2.send(producerInfo2); + ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); + connection2.send(producerInfo2); - // Send messages before the durable subscription is re-activated. - for (int i = 0; i < 4; i++) { - Message m = createMessage(producerInfo2, dest2, DeliveryMode.PERSISTENT); - connection2.send(m); - sentBeforeCreateConsumer.add(m.getMessageId()); - } + // Send messages before the durable subscription is re-activated. + for (int i = 0; i < 4; i++) { + Message m = createMessage(producerInfo2, dest2, DeliveryMode.PERSISTENT); + connection2.send(m); + sentBeforeCreateConsumer.add(m.getMessageId()); + } - // Re-open the subscription. - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, wildDest); - consumerInfo2.setSubscriptionName("test"); - consumerInfo2.setPrefetchSize(100); - connection2.send(consumerInfo2); + // Re-open the subscription. + ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, wildDest); + consumerInfo2.setSubscriptionName("test"); + consumerInfo2.setPrefetchSize(100); + connection2.send(consumerInfo2); - // Send messages after the subscription is activated. - for (int i = 0; i < 4; i++) { - Message m = createMessage(producerInfo2, dest3, DeliveryMode.PERSISTENT); - connection2.send(m); - sentAfterCreateConsumer.add(m.getMessageId()); - } + // Send messages after the subscription is activated. + for (int i = 0; i < 4; i++) { + Message m = createMessage(producerInfo2, dest3, DeliveryMode.PERSISTENT); + connection2.send(m); + sentAfterCreateConsumer.add(m.getMessageId()); + } - // We should get the recovered messages... - for (int i = 0; i < 4; i++) { - Message m2 = receiveMessage(connection2); - assertNotNull("Recovered message missing: " + i, m2); - assertEquals(sentBeforeRestart.get(i), m2.getMessageId()); - } - - // We should get get the messages that were sent before the sub was - // reactivated. - for (int i = 0; i < 4; i++) { - Message m2 = receiveMessage(connection2); - assertNotNull("Before activated message missing: " + i, m2); - assertEquals(sentBeforeCreateConsumer.get(i), m2.getMessageId()); - } - - // We should get get the messages that were sent after the sub was - // reactivated. - for (int i = 0; i < 4; i++) { - Message m2 = receiveMessage(connection2); - assertNotNull("After activated message missing: " + i, m2); - assertEquals("" + i, sentAfterCreateConsumer.get(i), m2.getMessageId()); - } - - assertNoMessagesLeft(connection2); - } - - } - - public void testConsumedQueuePersistentMessagesLostOnRestart() throws Exception { - - ActiveMQDestination destination = new ActiveMQQueue("TEST"); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - for (int i = 0; i < 4; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - } - - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // The we should get the messages. - for (int i = 0; i < 4; i++) { - Message m2 = receiveMessage(connection); - assertNotNull(m2); - } - - // restart the broker. - restartBroker(); - - // No messages should be delivered. - Message m = receiveMessage(connection); - assertNull(m); - } - - public void testQueuePersistentUncommitedMessagesLostOnRestart() throws Exception { - - ActiveMQDestination destination = new ActiveMQQueue("TEST"); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - // Begin the transaction. - LocalTransactionId txid = createLocalTransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - for (int i = 0; i < 4; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - message.setTransactionId(txid); - connection.send(message); - } - - // Don't commit - - // restart the broker. - restartBroker(); - - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // No messages should be delivered. - Message m = receiveMessage(connection); - assertNull(m); - } - - public void testTopicDurableConsumerHoldsPersistentMessageAfterRestart() throws Exception { - - ActiveMQDestination destination = new ActiveMQTopic("TEST"); - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - connectionInfo1.setClientId("A"); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo1); - - // Create the durable subscription. - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setSubscriptionName("test"); - consumerInfo1.setPrefetchSize(100); - connection1.send(consumerInfo1); - - // Close the subscription. - connection1.send(closeConsumerInfo(consumerInfo1)); - - // Send the messages - connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); - connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); - connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); - connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); - connection1.request(closeConnectionInfo(connectionInfo1)); - // Restart the broker. - restartBroker(); - - // Get a connection to the new broker. - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - connectionInfo2.setClientId("A"); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - - // Re-open the subscription. - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); - consumerInfo2.setSubscriptionName("test"); - consumerInfo2.setPrefetchSize(100); - connection2.send(consumerInfo2); - - // The we should get the messages. - for (int i = 0; i < 4; i++) { + // We should get the recovered messages... + for (int i = 0; i < 4; i++) { Message m2 = receiveMessage(connection2); - assertNotNull("Did not get message "+i, m2); - } - assertNoMessagesLeft(connection2); - } + assertNotNull("Recovered message missing: " + i, m2); + assertEquals(sentBeforeRestart.get(i), m2.getMessageId()); + } - public void testQueuePersistentMessagesNotLostOnRestart() throws Exception { + // We should get get the messages that were sent before the sub was + // reactivated. + for (int i = 0; i < 4; i++) { + Message m2 = receiveMessage(connection2); + assertNotNull("Before activated message missing: " + i, m2); + assertEquals(sentBeforeCreateConsumer.get(i), m2.getMessageId()); + } - ActiveMQDestination destination = new ActiveMQQueue("TEST"); + // We should get get the messages that were sent after the sub was + // reactivated. + for (int i = 0; i < 4; i++) { + Message m2 = receiveMessage(connection2); + assertNotNull("After activated message missing: " + i, m2); + assertEquals("" + i, sentAfterCreateConsumer.get(i), m2.getMessageId()); + } - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - connection.request(closeConnectionInfo(connectionInfo)); + assertNoMessagesLeft(connection2); + } - // restart the broker. - restartBroker(); + } - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); + public void testConsumedQueuePersistentMessagesLostOnRestart() throws Exception { - // Message should have been dropped due to broker restart. - Message m = receiveMessage(connection); - assertNotNull("Should have received a message by now!", m); - assertEquals(m.getMessageId(), message.getMessageId()); - } + ActiveMQDestination destination = new ActiveMQQueue("TEST"); - public void testQueueNonPersistentMessagesLostOnRestart() throws Exception { + // Setup the producer and send the message. + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); - ActiveMQDestination destination = new ActiveMQQueue("TEST"); + for (int i = 0; i < 4; i++) { + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + connection.send(message); + } - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - Message message = createMessage(producerInfo, destination); - message.setPersistent(false); - connection.send(message); + // Setup the consumer and receive the message. + connection = createConnection(); + connectionInfo = createConnectionInfo(); + sessionInfo = createSessionInfo(connectionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); - // restart the broker. - restartBroker(); + // The we should get the messages. + for (int i = 0; i < 4; i++) { + Message m2 = receiveMessage(connection); + assertNotNull(m2); + } - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); + // restart the broker. + restartBroker(); - // Message should have been dropped due to broker restart. - assertNoMessagesLeft(connection); - } + // No messages should be delivered. + Message m = receiveMessage(connection); + assertNull(m); + } - public void testQueuePersistentCommittedMessagesNotLostOnRestart() throws Exception { + public void testQueuePersistentUncommitedMessagesLostOnRestart() throws Exception { - ActiveMQDestination destination = new ActiveMQQueue("TEST"); + ActiveMQDestination destination = new ActiveMQQueue("TEST"); - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); + // Setup the producer and send the message. + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); - // Begin the transaction. - LocalTransactionId txid = createLocalTransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); + // Begin the transaction. + LocalTransactionId txid = createLocalTransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); - for (int i = 0; i < 4; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - message.setTransactionId(txid); - connection.send(message); - } + for (int i = 0; i < 4; i++) { + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + message.setTransactionId(txid); + connection.send(message); + } - // Commit - connection.send(createCommitTransaction1Phase(connectionInfo, txid)); - connection.request(closeConnectionInfo(connectionInfo)); - // restart the broker. - restartBroker(); + // Don't commit - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); + // restart the broker. + restartBroker(); - for (int i = 0; i < 4; i++) { - Message m = receiveMessage(connection); - assertNotNull(m); - } + // Setup the consumer and receive the message. + connection = createConnection(); + connectionInfo = createConnectionInfo(); + sessionInfo = createSessionInfo(connectionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); - assertNoMessagesLeft(connection); - } - + // No messages should be delivered. + Message m = receiveMessage(connection); + assertNull(m); + } - public void testQueuePersistentCommittedAcksNotLostOnRestart() throws Exception { + public void testTopicDurableConsumerHoldsPersistentMessageAfterRestart() throws Exception { - ActiveMQDestination destination = new ActiveMQQueue("TEST"); + ActiveMQDestination destination = new ActiveMQTopic("TEST"); - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + connectionInfo1.setClientId("A"); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo1); - for (int i = 0; i < 4; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - } + // Create the durable subscription. + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + consumerInfo1.setSubscriptionName("test"); + consumerInfo1.setPrefetchSize(100); + connection1.send(consumerInfo1); - // Setup the consumer and receive the message. - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); + // Close the subscription. + connection1.send(closeConsumerInfo(consumerInfo1)); - // Begin the transaction. - LocalTransactionId txid = createLocalTransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - for (int i = 0; i < 4; i++) { - Message m = receiveMessage(connection); - assertNotNull(m); - MessageAck ack = createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); - } - // Commit - connection.send(createCommitTransaction1Phase(connectionInfo, txid)); - connection.request(closeConnectionInfo(connectionInfo)); - // restart the broker. - restartBroker(); + // Send the messages + connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); + connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); + connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); + connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); + connection1.request(closeConnectionInfo(connectionInfo1)); + // Restart the broker. + restartBroker(); - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); + // Get a connection to the new broker. + StubConnection connection2 = createConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + connectionInfo2.setClientId("A"); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); - // No messages should be delivered. - Message m = receiveMessage(connection); - assertNull(m); - } - - + // Re-open the subscription. + ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); + consumerInfo2.setSubscriptionName("test"); + consumerInfo2.setPrefetchSize(100); + connection2.send(consumerInfo2); - public void testQueuePersistentUncommitedAcksLostOnRestart() throws Exception { + // The we should get the messages. + for (int i = 0; i < 4; i++) { + Message m2 = receiveMessage(connection2); + assertNotNull("Did not get message " + i, m2); + } + assertNoMessagesLeft(connection2); + } - ActiveMQDestination destination = new ActiveMQQueue("TEST"); + public void testQueuePersistentMessagesNotLostOnRestart() throws Exception { - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); + ActiveMQDestination destination = new ActiveMQQueue("TEST"); - for (int i = 0; i < 4; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - } + // Setup the producer and send the message. + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + connection.send(message); + connection.request(closeConnectionInfo(connectionInfo)); - // Setup the consumer and receive the message. - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); + // restart the broker. + restartBroker(); - // Begin the transaction. - LocalTransactionId txid = createLocalTransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - for (int i = 0; i < 4; i++) { - Message m = receiveMessage(connection); - assertNotNull(m); - MessageAck ack = createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); - } - // Don't commit + // Setup the consumer and receive the message. + connection = createConnection(); + connectionInfo = createConnectionInfo(); + sessionInfo = createSessionInfo(connectionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); - // restart the broker. - restartBroker(); + // Message should have been dropped due to broker restart. + Message m = receiveMessage(connection); + assertNotNull("Should have received a message by now!", m); + assertEquals(m.getMessageId(), message.getMessageId()); + } - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); + public void testQueueNonPersistentMessagesLostOnRestart() throws Exception { - // All messages should be re-delivered. - for (int i = 0; i < 4; i++) { - Message m = receiveMessage(connection); - assertNotNull(m); - } + ActiveMQDestination destination = new ActiveMQQueue("TEST"); - assertNoMessagesLeft(connection); - } - - public void testQueuePersistentXAUncommitedAcksLostOnRestart() throws Exception { - int NUMBER = 100; - ActiveMQDestination destination = new ActiveMQQueue("TEST"); + // Setup the producer and send the message. + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); + Message message = createMessage(producerInfo, destination); + message.setPersistent(false); + connection.send(message); - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); + // restart the broker. + restartBroker(); - for (int i = 0; i < NUMBER; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - } + // Setup the consumer and receive the message. + connection = createConnection(); + connectionInfo = createConnectionInfo(); + sessionInfo = createSessionInfo(connectionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); - // Setup the consumer and receive the message. - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); + // Message should have been dropped due to broker restart. + assertNoMessagesLeft(connection); + } - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - Message m = null; - for (int i = 0; i < NUMBER; i++) { - m = receiveMessage(connection); - assertNotNull(m); - } - MessageAck ack = createAck(consumerInfo, m, NUMBER, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); + public void testQueuePersistentCommittedMessagesNotLostOnRestart() throws Exception { - // Don't commit + ActiveMQDestination destination = new ActiveMQQueue("TEST"); - // restart the broker. - restartBroker(); + // Setup the producer and send the message. + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); + // Begin the transaction. + LocalTransactionId txid = createLocalTransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); - // All messages should be re-delivered. - for (int i = 0; i < NUMBER; i++) { - m = receiveMessage(connection); - assertNotNull(m); - } + for (int i = 0; i < 4; i++) { + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + message.setTransactionId(txid); + connection.send(message); + } - assertNoMessagesLeft(connection); - } + // Commit + connection.send(createCommitTransaction1Phase(connectionInfo, txid)); + connection.request(closeConnectionInfo(connectionInfo)); + // restart the broker. + restartBroker(); - public static Test suite() { - return suite(RecoveryBrokerTest.class); - } + // Setup the consumer and receive the message. + connection = createConnection(); + connectionInfo = createConnectionInfo(); + sessionInfo = createSessionInfo(connectionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + for (int i = 0; i < 4; i++) { + Message m = receiveMessage(connection); + assertNotNull(m); + } + + assertNoMessagesLeft(connection); + } + + public void testQueuePersistentCommittedAcksNotLostOnRestart() throws Exception { + + ActiveMQDestination destination = new ActiveMQQueue("TEST"); + + // Setup the producer and send the message. + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); + + for (int i = 0; i < 4; i++) { + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + connection.send(message); + } + + // Setup the consumer and receive the message. + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); + + // Begin the transaction. + LocalTransactionId txid = createLocalTransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); + for (int i = 0; i < 4; i++) { + Message m = receiveMessage(connection); + assertNotNull(m); + MessageAck ack = createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE); + ack.setTransactionId(txid); + connection.send(ack); + } + // Commit + connection.send(createCommitTransaction1Phase(connectionInfo, txid)); + connection.request(closeConnectionInfo(connectionInfo)); + // restart the broker. + restartBroker(); + + // Setup the consumer and receive the message. + connection = createConnection(); + connectionInfo = createConnectionInfo(); + sessionInfo = createSessionInfo(connectionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); + + // No messages should be delivered. + Message m = receiveMessage(connection); + assertNull(m); + } + + public void testQueuePersistentUncommitedAcksLostOnRestart() throws Exception { + + ActiveMQDestination destination = new ActiveMQQueue("TEST"); + + // Setup the producer and send the message. + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); + + for (int i = 0; i < 4; i++) { + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + connection.send(message); + } + + // Setup the consumer and receive the message. + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); + + // Begin the transaction. + LocalTransactionId txid = createLocalTransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); + for (int i = 0; i < 4; i++) { + Message m = receiveMessage(connection); + assertNotNull(m); + MessageAck ack = createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE); + ack.setTransactionId(txid); + connection.send(ack); + } + // Don't commit + + // restart the broker. + restartBroker(); + + // Setup the consumer and receive the message. + connection = createConnection(); + connectionInfo = createConnectionInfo(); + sessionInfo = createSessionInfo(connectionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); + + // All messages should be re-delivered. + for (int i = 0; i < 4; i++) { + Message m = receiveMessage(connection); + assertNotNull(m); + } + + assertNoMessagesLeft(connection); + } + + public void testQueuePersistentXAUncommitedAcksLostOnRestart() throws Exception { + int NUMBER = 100; + ActiveMQDestination destination = new ActiveMQQueue("TEST"); + + // Setup the producer and send the message. + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); + + for (int i = 0; i < NUMBER; i++) { + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + connection.send(message); + } + + // Setup the consumer and receive the message. + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); + + // Begin the transaction. + XATransactionId txid = createXATransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); + Message m = null; + for (int i = 0; i < NUMBER; i++) { + m = receiveMessage(connection); + assertNotNull(m); + } + MessageAck ack = createAck(consumerInfo, m, NUMBER, MessageAck.STANDARD_ACK_TYPE); + ack.setTransactionId(txid); + connection.send(ack); + + // Don't commit + + // restart the broker. + restartBroker(); + + // Setup the consumer and receive the message. + connection = createConnection(); + connectionInfo = createConnectionInfo(); + sessionInfo = createSessionInfo(connectionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); + + // All messages should be re-delivered. + for (int i = 0; i < NUMBER; i++) { + m = receiveMessage(connection); + assertNotNull(m); + } + + assertNoMessagesLeft(connection); + } + + public static Test suite() { + return suite(RecoveryBrokerTest.class); + } + + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/RedeliveryRestartTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/RedeliveryRestartTest.java index 032934b112..51af6011cf 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/RedeliveryRestartTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/RedeliveryRestartTest.java @@ -25,6 +25,7 @@ import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; import javax.jms.TopicSubscriber; + import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.TestSupport; @@ -42,256 +43,251 @@ import org.slf4j.LoggerFactory; @RunWith(value = Parameterized.class) public class RedeliveryRestartTest extends TestSupport { - private static final transient Logger LOG = LoggerFactory.getLogger(RedeliveryRestartTest.class); - ActiveMQConnection connection; - BrokerService broker = null; - String queueName = "redeliveryRestartQ"; + private static final transient Logger LOG = LoggerFactory.getLogger(RedeliveryRestartTest.class); + ActiveMQConnection connection; + BrokerService broker = null; + String queueName = "redeliveryRestartQ"; - @Parameterized.Parameter - public TestSupport.PersistenceAdapterChoice persistenceAdapterChoice = PersistenceAdapterChoice.KahaDB; + @Parameterized.Parameter + public TestSupport.PersistenceAdapterChoice persistenceAdapterChoice = PersistenceAdapterChoice.KahaDB; - @Parameterized.Parameters(name="Store={0}") - public static Iterable data() { - return Arrays.asList(new Object[][]{{TestSupport.PersistenceAdapterChoice.KahaDB},{TestSupport.PersistenceAdapterChoice.JDBC},{TestSupport.PersistenceAdapterChoice.LevelDB}}); - } + @Parameterized.Parameters(name = "Store={0}") + public static Iterable data() { + return Arrays.asList(new Object[][]{{TestSupport.PersistenceAdapterChoice.KahaDB}, {TestSupport.PersistenceAdapterChoice.JDBC}, {TestSupport.PersistenceAdapterChoice.LevelDB}}); + } - @Override - @Before - public void setUp() throws Exception { - super.setUp(); - broker = new BrokerService(); - configureBroker(broker); - broker.setDeleteAllMessagesOnStartup(true); - broker.start(); - } + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + broker = new BrokerService(); + configureBroker(broker); + broker.setDeleteAllMessagesOnStartup(true); + broker.start(); + } - @Override - @After - public void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - broker.stop(); - super.tearDown(); - } + @Override + @After + public void tearDown() throws Exception { + if (connection != null) { + connection.close(); + } + broker.stop(); + super.tearDown(); + } - protected void configureBroker(BrokerService broker) throws Exception { - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policy = new PolicyEntry(); - policy.setPersistJMSRedelivered(true); - policyMap.setDefaultEntry(policy); - broker.setDestinationPolicy(policyMap); - setPersistenceAdapter(broker, persistenceAdapterChoice); - broker.addConnector("tcp://0.0.0.0:0"); - } + protected void configureBroker(BrokerService broker) throws Exception { + PolicyMap policyMap = new PolicyMap(); + PolicyEntry policy = new PolicyEntry(); + policy.setPersistJMSRedelivered(true); + policyMap.setDefaultEntry(policy); + broker.setDestinationPolicy(policyMap); + setPersistenceAdapter(broker, persistenceAdapterChoice); + broker.addConnector("tcp://0.0.0.0:0"); + } - @org.junit.Test - public void testValidateRedeliveryFlagAfterRestartNoTx() throws Exception { + @org.junit.Test + public void testValidateRedeliveryFlagAfterRestartNoTx() throws Exception { - ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(" + broker.getTransportConnectors().get(0).getPublishableConnectString() - + ")?jms.prefetchPolicy.all=0"); - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(" + broker.getTransportConnectors().get(0).getPublishableConnectString() + ")?jms.prefetchPolicy.all=0"); + connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.start(); - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Destination destination = session.createQueue(queueName); - populateDestination(10, destination, connection); + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Destination destination = session.createQueue(queueName); + populateDestination(10, destination, connection); - MessageConsumer consumer = session.createConsumer(destination); - TextMessage msg = null; - for (int i = 0; i < 5; i++) { - msg = (TextMessage) consumer.receive(20000); - LOG.info("not redelivered? got: " + msg); - assertNotNull("got the message", msg); - assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); - assertEquals("not a redelivery", false, msg.getJMSRedelivered()); - } - consumer.close(); + MessageConsumer consumer = session.createConsumer(destination); + TextMessage msg = null; + for (int i = 0; i < 5; i++) { + msg = (TextMessage) consumer.receive(20000); + LOG.info("not redelivered? got: " + msg); + assertNotNull("got the message", msg); + assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); + assertEquals("not a redelivery", false, msg.getJMSRedelivered()); + } + consumer.close(); - restartBroker(); + restartBroker(); - // make failover aware of the restarted auto assigned port - connection.getTransport().narrow(FailoverTransport.class).add(true, broker.getTransportConnectors().get(0) - .getPublishableConnectString()); + // make failover aware of the restarted auto assigned port + connection.getTransport().narrow(FailoverTransport.class).add(true, broker.getTransportConnectors().get(0).getPublishableConnectString()); - consumer = session.createConsumer(destination); - for (int i = 0; i < 5; i++) { - msg = (TextMessage) consumer.receive(4000); - LOG.info("redelivered? got: " + msg); - assertNotNull("got the message again", msg); - assertEquals("re delivery flag", true, msg.getJMSRedelivered()); - assertEquals("redelivery count survives restart", 2, msg.getLongProperty("JMSXDeliveryCount")); - msg.acknowledge(); - } + consumer = session.createConsumer(destination); + for (int i = 0; i < 5; i++) { + msg = (TextMessage) consumer.receive(4000); + LOG.info("redelivered? got: " + msg); + assertNotNull("got the message again", msg); + assertEquals("re delivery flag", true, msg.getJMSRedelivered()); + assertEquals("redelivery count survives restart", 2, msg.getLongProperty("JMSXDeliveryCount")); + msg.acknowledge(); + } - // consume the rest that were not redeliveries - for (int i = 0; i < 5; i++) { - msg = (TextMessage) consumer.receive(20000); - LOG.info("not redelivered? got: " + msg); - assertNotNull("got the message", msg); - assertEquals("not a redelivery", false, msg.getJMSRedelivered()); - assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); - msg.acknowledge(); - } - connection.close(); - } + // consume the rest that were not redeliveries + for (int i = 0; i < 5; i++) { + msg = (TextMessage) consumer.receive(20000); + LOG.info("not redelivered? got: " + msg); + assertNotNull("got the message", msg); + assertEquals("not a redelivery", false, msg.getJMSRedelivered()); + assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); + msg.acknowledge(); + } + connection.close(); + } - @org.junit.Test - public void testDurableSubRedeliveryFlagAfterRestartNotSupported() throws Exception { + @org.junit.Test + public void testDurableSubRedeliveryFlagAfterRestartNotSupported() throws Exception { - ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(" + broker.getTransportConnectors().get(0).getPublishableConnectString() - + ")?jms.prefetchPolicy.all=0"); - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.setClientID("id"); - connection.start(); + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(" + broker.getTransportConnectors().get(0).getPublishableConnectString() + ")?jms.prefetchPolicy.all=0"); + connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.setClientID("id"); + connection.start(); - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - ActiveMQTopic destination = new ActiveMQTopic(queueName); + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + ActiveMQTopic destination = new ActiveMQTopic(queueName); - TopicSubscriber durableSub = session.createDurableSubscriber(destination, "id"); + TopicSubscriber durableSub = session.createDurableSubscriber(destination, "id"); - populateDestination(10, destination, connection); + populateDestination(10, destination, connection); - TextMessage msg = null; - for (int i = 0; i < 5; i++) { - msg = (TextMessage) durableSub.receive(20000); - LOG.info("not redelivered? got: " + msg); - assertNotNull("got the message", msg); - assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); - assertEquals("not a redelivery", false, msg.getJMSRedelivered()); - } - durableSub.close(); + TextMessage msg = null; + for (int i = 0; i < 5; i++) { + msg = (TextMessage) durableSub.receive(20000); + LOG.info("not redelivered? got: " + msg); + assertNotNull("got the message", msg); + assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); + assertEquals("not a redelivery", false, msg.getJMSRedelivered()); + } + durableSub.close(); - restartBroker(); + restartBroker(); - // make failover aware of the restarted auto assigned port - connection.getTransport().narrow(FailoverTransport.class).add(true, broker.getTransportConnectors().get(0) - .getPublishableConnectString()); + // make failover aware of the restarted auto assigned port + connection.getTransport().narrow(FailoverTransport.class).add(true, broker.getTransportConnectors().get(0).getPublishableConnectString()); - durableSub = session.createDurableSubscriber(destination, "id"); - for (int i = 0; i < 10; i++) { - msg = (TextMessage) durableSub.receive(4000); - LOG.info("redelivered? got: " + msg); - assertNotNull("got the message again", msg); - assertEquals("no reDelivery flag", false, msg.getJMSRedelivered()); - msg.acknowledge(); - } - connection.close(); - } + durableSub = session.createDurableSubscriber(destination, "id"); + for (int i = 0; i < 10; i++) { + msg = (TextMessage) durableSub.receive(4000); + LOG.info("redelivered? got: " + msg); + assertNotNull("got the message again", msg); + assertEquals("no reDelivery flag", false, msg.getJMSRedelivered()); + msg.acknowledge(); + } + connection.close(); + } - @org.junit.Test - public void testValidateRedeliveryFlagAfterRestart() throws Exception { + @org.junit.Test + public void testValidateRedeliveryFlagAfterRestart() throws Exception { - ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(" + broker.getTransportConnectors().get(0).getPublishableConnectString() - + ")?jms.prefetchPolicy.all=0"); - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(" + broker.getTransportConnectors().get(0).getPublishableConnectString() + ")?jms.prefetchPolicy.all=0"); + connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.start(); - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Destination destination = session.createQueue(queueName); - populateDestination(10, destination, connection); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + Destination destination = session.createQueue(queueName); + populateDestination(10, destination, connection); - MessageConsumer consumer = session.createConsumer(destination); - TextMessage msg = null; - for (int i = 0; i < 5; i++) { - msg = (TextMessage) consumer.receive(20000); - LOG.info("not redelivered? got: " + msg); - assertNotNull("got the message", msg); - assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); - assertEquals("not a redelivery", false, msg.getJMSRedelivered()); - } - session.rollback(); - consumer.close(); + MessageConsumer consumer = session.createConsumer(destination); + TextMessage msg = null; + for (int i = 0; i < 5; i++) { + msg = (TextMessage) consumer.receive(20000); + LOG.info("not redelivered? got: " + msg); + assertNotNull("got the message", msg); + assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); + assertEquals("not a redelivery", false, msg.getJMSRedelivered()); + } + session.rollback(); + consumer.close(); - restartBroker(); + restartBroker(); - // make failover aware of the restarted auto assigned port - connection.getTransport().narrow(FailoverTransport.class).add(true, broker.getTransportConnectors().get(0) - .getPublishableConnectString()); + // make failover aware of the restarted auto assigned port + connection.getTransport().narrow(FailoverTransport.class).add(true, broker.getTransportConnectors().get(0).getPublishableConnectString()); - consumer = session.createConsumer(destination); - for (int i = 0; i < 5; i++) { - msg = (TextMessage) consumer.receive(4000); - LOG.info("redelivered? got: " + msg); - assertNotNull("got the message again", msg); - assertEquals("redelivery count survives restart", 2, msg.getLongProperty("JMSXDeliveryCount")); - assertEquals("re delivery flag", true, msg.getJMSRedelivered()); - } - session.commit(); + consumer = session.createConsumer(destination); + for (int i = 0; i < 5; i++) { + msg = (TextMessage) consumer.receive(4000); + LOG.info("redelivered? got: " + msg); + assertNotNull("got the message again", msg); + assertEquals("redelivery count survives restart", 2, msg.getLongProperty("JMSXDeliveryCount")); + assertEquals("re delivery flag", true, msg.getJMSRedelivered()); + } + session.commit(); - // consume the rest that were not redeliveries - for (int i = 0; i < 5; i++) { - msg = (TextMessage) consumer.receive(20000); - LOG.info("not redelivered? got: " + msg); - assertNotNull("got the message", msg); - assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); - assertEquals("not a redelivery", false, msg.getJMSRedelivered()); - } - session.commit(); + // consume the rest that were not redeliveries + for (int i = 0; i < 5; i++) { + msg = (TextMessage) consumer.receive(20000); + LOG.info("not redelivered? got: " + msg); + assertNotNull("got the message", msg); + assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); + assertEquals("not a redelivery", false, msg.getJMSRedelivered()); + } + session.commit(); - connection.close(); - } + connection.close(); + } - @org.junit.Test - public void testValidateRedeliveryFlagAfterRecovery() throws Exception { - ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString() - + "?jms.prefetchPolicy.all=0"); - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); + @org.junit.Test + public void testValidateRedeliveryFlagAfterRecovery() throws Exception { + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString() + "?jms.prefetchPolicy.all=0"); + connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.start(); - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Destination destination = session.createQueue(queueName); - populateDestination(1, destination, connection); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + Destination destination = session.createQueue(queueName); + populateDestination(1, destination, connection); - MessageConsumer consumer = session.createConsumer(destination); - TextMessage msg = (TextMessage) consumer.receive(5000); - LOG.info("got: " + msg); - assertNotNull("got the message", msg); - assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); - assertEquals("not a redelivery", false, msg.getJMSRedelivered()); + MessageConsumer consumer = session.createConsumer(destination); + TextMessage msg = (TextMessage) consumer.receive(5000); + LOG.info("got: " + msg); + assertNotNull("got the message", msg); + assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); + assertEquals("not a redelivery", false, msg.getJMSRedelivered()); - stopBrokerWithStoreFailure(broker, persistenceAdapterChoice); + stopBrokerWithStoreFailure(broker, persistenceAdapterChoice); - broker = createRestartedBroker(); - broker.start(); + broker = createRestartedBroker(); + broker.start(); - connection.close(); + connection.close(); - connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString()); - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); + connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString()); + connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.start(); - session = connection.createSession(true, Session.SESSION_TRANSACTED); - consumer = session.createConsumer(destination); - msg = (TextMessage) consumer.receive(10000); - assertNotNull("got the message again", msg); - assertEquals("redelivery count survives restart", 2, msg.getLongProperty("JMSXDeliveryCount")); - assertEquals("re delivery flag", true, msg.getJMSRedelivered()); + session = connection.createSession(true, Session.SESSION_TRANSACTED); + consumer = session.createConsumer(destination); + msg = (TextMessage) consumer.receive(10000); + assertNotNull("got the message again", msg); + assertEquals("redelivery count survives restart", 2, msg.getLongProperty("JMSXDeliveryCount")); + assertEquals("re delivery flag", true, msg.getJMSRedelivered()); - session.commit(); - connection.close(); - } + session.commit(); + connection.close(); + } - private void restartBroker() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - broker = createRestartedBroker(); - broker.start(); - } + private void restartBroker() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + broker = createRestartedBroker(); + broker.start(); + } - private BrokerService createRestartedBroker() throws Exception { - broker = new BrokerService(); - configureBroker(broker); - return broker; - } + private BrokerService createRestartedBroker() throws Exception { + broker = new BrokerService(); + configureBroker(broker); + return broker; + } - private void populateDestination(final int nbMessages, final Destination destination, javax.jms.Connection connection) throws JMSException { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - for (int i = 1; i <= nbMessages; i++) { - producer.send(session.createTextMessage("")); - } - producer.close(); - session.close(); - } + private void populateDestination(final int nbMessages, + final Destination destination, + javax.jms.Connection connection) throws JMSException { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + for (int i = 1; i <= nbMessages; i++) { + producer.send(session.createTextMessage("")); + } + producer.close(); + session.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/RedeliveryRestartWithExceptionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/RedeliveryRestartWithExceptionTest.java index 5d8b62ec81..d977107d3b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/RedeliveryRestartWithExceptionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/RedeliveryRestartWithExceptionTest.java @@ -27,6 +27,7 @@ import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; + import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.TestSupport; @@ -54,419 +55,416 @@ import org.slf4j.LoggerFactory; public class RedeliveryRestartWithExceptionTest extends TestSupport { - private static final transient Logger LOG = LoggerFactory.getLogger(RedeliveryRestartWithExceptionTest.class); - ActiveMQConnection connection; - BrokerService broker = null; - String queueName = "redeliveryRestartQ"; + private static final transient Logger LOG = LoggerFactory.getLogger(RedeliveryRestartWithExceptionTest.class); + ActiveMQConnection connection; + BrokerService broker = null; + String queueName = "redeliveryRestartQ"; - @Override - @Before - public void setUp() throws Exception { - super.setUp(); - broker = new BrokerService(); - configureBroker(broker, true); - broker.setDeleteAllMessagesOnStartup(true); - broker.start(); - } + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + broker = new BrokerService(); + configureBroker(broker, true); + broker.setDeleteAllMessagesOnStartup(true); + broker.start(); + } - @Override - @After - public void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - broker.stop(); - super.tearDown(); - } + @Override + @After + public void tearDown() throws Exception { + if (connection != null) { + connection.close(); + } + broker.stop(); + super.tearDown(); + } - protected void configureBroker(BrokerService broker, boolean throwExceptionOnUpdate) throws Exception { - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policy = new PolicyEntry(); - policy.setPersistJMSRedelivered(true); - policyMap.setDefaultEntry(policy); - broker.setDestinationPolicy(policyMap); - broker.setPersistenceAdapter(new KahaDBWithUpdateExceptionPersistenceAdapter(throwExceptionOnUpdate)); - broker.addConnector("tcp://0.0.0.0:0"); - } + protected void configureBroker(BrokerService broker, boolean throwExceptionOnUpdate) throws Exception { + PolicyMap policyMap = new PolicyMap(); + PolicyEntry policy = new PolicyEntry(); + policy.setPersistJMSRedelivered(true); + policyMap.setDefaultEntry(policy); + broker.setDestinationPolicy(policyMap); + broker.setPersistenceAdapter(new KahaDBWithUpdateExceptionPersistenceAdapter(throwExceptionOnUpdate)); + broker.addConnector("tcp://0.0.0.0:0"); + } - @org.junit.Test - public void testValidateRedeliveryFlagAfterRestart() throws Exception { + @org.junit.Test + public void testValidateRedeliveryFlagAfterRestart() throws Exception { - ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString() - + "?jms.prefetchPolicy.all=0"); - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString() + "?jms.prefetchPolicy.all=0"); + connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.start(); - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Destination destination = session.createQueue(queueName); - populateDestination(10, destination, connection, true); - TextMessage msg = null; - MessageConsumer consumer = session.createConsumer(destination); - Exception expectedException = null; - try { - for (int i = 0; i < 5; i++) { - msg = (TextMessage) consumer.receive(5000); - LOG.info("not redelivered? got: " + msg); - assertNotNull("got the message", msg); - assertTrue("Should not receive the 5th message", i < 4); - //The first 4 messages will be ok but the 5th one should hit an exception in updateMessage and should not be delivered - } - } catch (Exception e) { - //Expecting an exception and disconnect on the 5th message - LOG.info("Got expected:", e); - expectedException = e; - } - assertNotNull("Expecting an exception when updateMessage fails", expectedException); - - consumer.close(); - connection.close(); - - restartBroker(); - - connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString() - + "?jms.prefetchPolicy.all=0"); - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); - - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - destination = session.createQueue(queueName); - consumer = session.createConsumer(destination); - - - // consume the messages that were previously delivered - for (int i = 0; i < 4; i++) { - msg = (TextMessage) consumer.receive(4000); - LOG.info("redelivered? got: " + msg); - assertNotNull("got the message again", msg); - assertEquals("re delivery flag", true, msg.getJMSRedelivered()); - assertTrue("redelivery count survives restart", msg.getLongProperty("JMSXDeliveryCount") > 1); - msg.acknowledge(); - } - - - // consume the rest that were not redeliveries - for (int i = 0; i < 6; i++) { - msg = (TextMessage) consumer.receive(4000); - LOG.info("not redelivered? got: " + msg); - assertNotNull("got the message", msg); - assertEquals("not a redelivery", false, msg.getJMSRedelivered()); - assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); - msg.acknowledge(); - } - connection.close(); - } - - - @org.junit.Test - public void testValidateRedeliveryFlagAfterTransientFailureConnectionDrop() throws Exception { - - ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString() - + "?jms.prefetchPolicy.all=0"); - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); - - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Destination destination = session.createQueue(queueName); - populateDestination(10, destination, connection, true); - TextMessage msg = null; - MessageConsumer consumer = session.createConsumer(destination); - Exception expectedException = null; - try { - for (int i = 0; i < 5; i++) { - msg = (TextMessage) consumer.receive(5000); - LOG.info("not redelivered? got: " + msg); - assertNotNull("got the message", msg); - assertTrue("Should not receive the 5th message", i < 4); - //The first 4 messages will be ok but the 5th one should hit an exception in updateMessage and should not be delivered - } - } catch (Exception e) { - //Expecting an exception and disconnect on the 5th message - LOG.info("Got expected:", e); - expectedException = e; - } - assertNotNull("Expecting an exception when updateMessage fails", expectedException); - - consumer.close(); - connection.close(); - - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); - - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - destination = session.createQueue(queueName); - consumer = session.createConsumer(destination); - - - // consume the messages that were previously delivered - for (int i = 0; i < 4; i++) { - msg = (TextMessage) consumer.receive(4000); - LOG.info("redelivered? got: " + msg); - assertNotNull("got the message again", msg); - assertEquals("re delivery flag on:" + i, true, msg.getJMSRedelivered()); - assertTrue("redelivery count survives reconnect for:" + i, msg.getLongProperty("JMSXDeliveryCount") > 1); - msg.acknowledge(); - } - - - // consume the rest that were not redeliveries - for (int i = 0; i < 6; i++) { - msg = (TextMessage) consumer.receive(4000); - LOG.info("not redelivered? got: " + msg); - assertNotNull("got the message", msg); - assertEquals("not a redelivery", false, msg.getJMSRedelivered()); - assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); - msg.acknowledge(); - } - connection.close(); - } - - @org.junit.Test - public void testValidateRedeliveryFlagOnNonPersistentAfterTransientFailureConnectionDrop() throws Exception { - - ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString() - + "?jms.prefetchPolicy.all=0"); - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); - - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Destination destination = session.createQueue(queueName); - populateDestination(10, destination, connection, false); - TextMessage msg = null; - MessageConsumer consumer = session.createConsumer(destination); - for (int i = 0; i < 5; i++) { + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Destination destination = session.createQueue(queueName); + populateDestination(10, destination, connection, true); + TextMessage msg = null; + MessageConsumer consumer = session.createConsumer(destination); + Exception expectedException = null; + try { + for (int i = 0; i < 5; i++) { msg = (TextMessage) consumer.receive(5000); - assertNotNull("got the message", msg); - assertFalse("not redelivered", msg.getJMSRedelivered()); - } - - connection.getTransport().narrow(TcpTransport.class).getTransportListener().onException(new IOException("Die")); - - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); - - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - destination = session.createQueue(queueName); - consumer = session.createConsumer(destination); - - // consume the messages that were previously delivered - for (int i = 0; i < 5; i++) { - msg = (TextMessage) consumer.receive(4000); - LOG.info("redelivered? got: " + msg); - assertNotNull("got the message again", msg); - assertEquals("redelivery flag set on:" + i, true, msg.getJMSRedelivered()); - assertTrue("redelivery count survives reconnect for:" + i, msg.getLongProperty("JMSXDeliveryCount") > 1); - msg.acknowledge(); - } - - // consume the rest that were not redeliveries - for (int i = 0; i < 5; i++) { - msg = (TextMessage) consumer.receive(4000); LOG.info("not redelivered? got: " + msg); assertNotNull("got the message", msg); - assertEquals("not a redelivery", false, msg.getJMSRedelivered()); - assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); - msg.acknowledge(); - } - connection.close(); - } + assertTrue("Should not receive the 5th message", i < 4); + //The first 4 messages will be ok but the 5th one should hit an exception in updateMessage and should not be delivered + } + } + catch (Exception e) { + //Expecting an exception and disconnect on the 5th message + LOG.info("Got expected:", e); + expectedException = e; + } + assertNotNull("Expecting an exception when updateMessage fails", expectedException); - private void restartBroker() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - broker = createRestartedBroker(); - broker.start(); - } + consumer.close(); + connection.close(); - private BrokerService createRestartedBroker() throws Exception { - broker = new BrokerService(); - configureBroker(broker, false); - return broker; - } + restartBroker(); - private void populateDestination(final int nbMessages, final Destination destination, javax.jms.Connection connection, boolean persistent) throws JMSException { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT); - for (int i = 1; i <= nbMessages; i++) { - producer.send(session.createTextMessage("")); - } - producer.close(); - session.close(); - } - - private class KahaDBWithUpdateExceptionPersistenceAdapter implements PersistenceAdapter { - - private KahaDBPersistenceAdapter kahaDB = new KahaDBPersistenceAdapter(); - private boolean throwExceptionOnUpdate; - - public KahaDBWithUpdateExceptionPersistenceAdapter(boolean throwExceptionOnUpdate) { - this.throwExceptionOnUpdate = throwExceptionOnUpdate; - } - - @Override - public void start() throws Exception { - kahaDB.start(); - } + connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString() + "?jms.prefetchPolicy.all=0"); + connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.start(); - @Override - public void stop() throws Exception { - kahaDB.stop(); - } + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + destination = session.createQueue(queueName); + consumer = session.createConsumer(destination); - @Override - public Set getDestinations() { - return kahaDB.getDestinations(); - } + // consume the messages that were previously delivered + for (int i = 0; i < 4; i++) { + msg = (TextMessage) consumer.receive(4000); + LOG.info("redelivered? got: " + msg); + assertNotNull("got the message again", msg); + assertEquals("re delivery flag", true, msg.getJMSRedelivered()); + assertTrue("redelivery count survives restart", msg.getLongProperty("JMSXDeliveryCount") > 1); + msg.acknowledge(); + } - @Override - public MessageStore createQueueMessageStore(ActiveMQQueue destination) - throws IOException { - MessageStore proxyMessageStoreWithException = new ProxyMessageStoreWithUpdateException( - kahaDB.createQueueMessageStore(destination), throwExceptionOnUpdate); - return proxyMessageStoreWithException; - } + // consume the rest that were not redeliveries + for (int i = 0; i < 6; i++) { + msg = (TextMessage) consumer.receive(4000); + LOG.info("not redelivered? got: " + msg); + assertNotNull("got the message", msg); + assertEquals("not a redelivery", false, msg.getJMSRedelivered()); + assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); + msg.acknowledge(); + } + connection.close(); + } - @Override - public TopicMessageStore createTopicMessageStore( - ActiveMQTopic destination) throws IOException { - TopicMessageStore proxyMessageStoreWithException = new ProxyTopicMessageStoreWithUpdateException( - kahaDB.createTopicMessageStore(destination), throwExceptionOnUpdate); - return proxyMessageStoreWithException; - } - - @Override - public JobSchedulerStore createJobSchedulerStore() throws IOException, UnsupportedOperationException { - return kahaDB.createJobSchedulerStore(); - } + @org.junit.Test + public void testValidateRedeliveryFlagAfterTransientFailureConnectionDrop() throws Exception { - @Override - public void removeQueueMessageStore(ActiveMQQueue destination) { - kahaDB.removeQueueMessageStore(destination); - } + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString() + "?jms.prefetchPolicy.all=0"); + connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.start(); - @Override - public void removeTopicMessageStore(ActiveMQTopic destination) { - kahaDB.removeTopicMessageStore(destination); - } + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Destination destination = session.createQueue(queueName); + populateDestination(10, destination, connection, true); + TextMessage msg = null; + MessageConsumer consumer = session.createConsumer(destination); + Exception expectedException = null; + try { + for (int i = 0; i < 5; i++) { + msg = (TextMessage) consumer.receive(5000); + LOG.info("not redelivered? got: " + msg); + assertNotNull("got the message", msg); + assertTrue("Should not receive the 5th message", i < 4); + //The first 4 messages will be ok but the 5th one should hit an exception in updateMessage and should not be delivered + } + } + catch (Exception e) { + //Expecting an exception and disconnect on the 5th message + LOG.info("Got expected:", e); + expectedException = e; + } + assertNotNull("Expecting an exception when updateMessage fails", expectedException); - @Override - public TransactionStore createTransactionStore() throws IOException { - return kahaDB.createTransactionStore(); - } + consumer.close(); + connection.close(); - @Override - public void beginTransaction(ConnectionContext context) - throws IOException { - kahaDB.beginTransaction(context); - } + connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.start(); - @Override - public void commitTransaction(ConnectionContext context) - throws IOException { - kahaDB.commitTransaction(context); - } + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + destination = session.createQueue(queueName); + consumer = session.createConsumer(destination); - @Override - public void rollbackTransaction(ConnectionContext context) - throws IOException { - kahaDB.rollbackTransaction(context); - } + // consume the messages that were previously delivered + for (int i = 0; i < 4; i++) { + msg = (TextMessage) consumer.receive(4000); + LOG.info("redelivered? got: " + msg); + assertNotNull("got the message again", msg); + assertEquals("re delivery flag on:" + i, true, msg.getJMSRedelivered()); + assertTrue("redelivery count survives reconnect for:" + i, msg.getLongProperty("JMSXDeliveryCount") > 1); + msg.acknowledge(); + } - @Override - public long getLastMessageBrokerSequenceId() throws IOException { - return kahaDB.getLastMessageBrokerSequenceId(); - } + // consume the rest that were not redeliveries + for (int i = 0; i < 6; i++) { + msg = (TextMessage) consumer.receive(4000); + LOG.info("not redelivered? got: " + msg); + assertNotNull("got the message", msg); + assertEquals("not a redelivery", false, msg.getJMSRedelivered()); + assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); + msg.acknowledge(); + } + connection.close(); + } - @Override - public void deleteAllMessages() throws IOException { - kahaDB.deleteAllMessages(); - } + @org.junit.Test + public void testValidateRedeliveryFlagOnNonPersistentAfterTransientFailureConnectionDrop() throws Exception { - @Override - public void setUsageManager(SystemUsage usageManager) { - kahaDB.setUsageManager(usageManager); - } + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString() + "?jms.prefetchPolicy.all=0"); + connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.start(); - @Override - public void setBrokerName(String brokerName) { - kahaDB.setBrokerName(brokerName); - } + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Destination destination = session.createQueue(queueName); + populateDestination(10, destination, connection, false); + TextMessage msg = null; + MessageConsumer consumer = session.createConsumer(destination); + for (int i = 0; i < 5; i++) { + msg = (TextMessage) consumer.receive(5000); + assertNotNull("got the message", msg); + assertFalse("not redelivered", msg.getJMSRedelivered()); + } - @Override - public void setDirectory(File dir) { - kahaDB.setDirectory(dir); - } + connection.getTransport().narrow(TcpTransport.class).getTransportListener().onException(new IOException("Die")); - @Override - public File getDirectory() { - return kahaDB.getDirectory(); - } + connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.start(); - @Override - public void checkpoint(boolean sync) throws IOException { - kahaDB.checkpoint(sync); - } + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + destination = session.createQueue(queueName); + consumer = session.createConsumer(destination); - @Override - public long size() { - return kahaDB.size(); - } + // consume the messages that were previously delivered + for (int i = 0; i < 5; i++) { + msg = (TextMessage) consumer.receive(4000); + LOG.info("redelivered? got: " + msg); + assertNotNull("got the message again", msg); + assertEquals("redelivery flag set on:" + i, true, msg.getJMSRedelivered()); + assertTrue("redelivery count survives reconnect for:" + i, msg.getLongProperty("JMSXDeliveryCount") > 1); + msg.acknowledge(); + } - @Override - public long getLastProducerSequenceId(ProducerId id) throws IOException { - return kahaDB.getLastProducerSequenceId(id); - } - - } - - private class ProxyMessageStoreWithUpdateException extends ProxyMessageStore { - private boolean throwExceptionOnUpdate; - private int numBeforeException = 4; - public ProxyMessageStoreWithUpdateException(MessageStore delegate, boolean throwExceptionOnUpdate) { - super(delegate); - this.throwExceptionOnUpdate = throwExceptionOnUpdate; - } - - @Override - public void updateMessage(Message message) throws IOException { - if(throwExceptionOnUpdate) { - if(numBeforeException > 0) { - numBeforeException--; - super.updateMessage(message); - } else { - // lets only do it once so we can validate transient store failure - throwExceptionOnUpdate = false; + // consume the rest that were not redeliveries + for (int i = 0; i < 5; i++) { + msg = (TextMessage) consumer.receive(4000); + LOG.info("not redelivered? got: " + msg); + assertNotNull("got the message", msg); + assertEquals("not a redelivery", false, msg.getJMSRedelivered()); + assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); + msg.acknowledge(); + } + connection.close(); + } - //A message that has never been delivered will hit this exception - throw new IOException("Hit our simulated exception writing the update to disk"); - } - } else { - super.updateMessage(message); + private void restartBroker() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + broker = createRestartedBroker(); + broker.start(); + } + + private BrokerService createRestartedBroker() throws Exception { + broker = new BrokerService(); + configureBroker(broker, false); + return broker; + } + + private void populateDestination(final int nbMessages, + final Destination destination, + javax.jms.Connection connection, + boolean persistent) throws JMSException { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT); + for (int i = 1; i <= nbMessages; i++) { + producer.send(session.createTextMessage("")); + } + producer.close(); + session.close(); + } + + private class KahaDBWithUpdateExceptionPersistenceAdapter implements PersistenceAdapter { + + private KahaDBPersistenceAdapter kahaDB = new KahaDBPersistenceAdapter(); + private boolean throwExceptionOnUpdate; + + public KahaDBWithUpdateExceptionPersistenceAdapter(boolean throwExceptionOnUpdate) { + this.throwExceptionOnUpdate = throwExceptionOnUpdate; + } + + @Override + public void start() throws Exception { + kahaDB.start(); + } + + @Override + public void stop() throws Exception { + kahaDB.stop(); + } + + @Override + public Set getDestinations() { + return kahaDB.getDestinations(); + } + + @Override + public MessageStore createQueueMessageStore(ActiveMQQueue destination) throws IOException { + MessageStore proxyMessageStoreWithException = new ProxyMessageStoreWithUpdateException(kahaDB.createQueueMessageStore(destination), throwExceptionOnUpdate); + return proxyMessageStoreWithException; + } + + @Override + public TopicMessageStore createTopicMessageStore(ActiveMQTopic destination) throws IOException { + TopicMessageStore proxyMessageStoreWithException = new ProxyTopicMessageStoreWithUpdateException(kahaDB.createTopicMessageStore(destination), throwExceptionOnUpdate); + return proxyMessageStoreWithException; + } + + @Override + public JobSchedulerStore createJobSchedulerStore() throws IOException, UnsupportedOperationException { + return kahaDB.createJobSchedulerStore(); + } + + @Override + public void removeQueueMessageStore(ActiveMQQueue destination) { + kahaDB.removeQueueMessageStore(destination); + } + + @Override + public void removeTopicMessageStore(ActiveMQTopic destination) { + kahaDB.removeTopicMessageStore(destination); + } + + @Override + public TransactionStore createTransactionStore() throws IOException { + return kahaDB.createTransactionStore(); + } + + @Override + public void beginTransaction(ConnectionContext context) throws IOException { + kahaDB.beginTransaction(context); + } + + @Override + public void commitTransaction(ConnectionContext context) throws IOException { + kahaDB.commitTransaction(context); + } + + @Override + public void rollbackTransaction(ConnectionContext context) throws IOException { + kahaDB.rollbackTransaction(context); + } + + @Override + public long getLastMessageBrokerSequenceId() throws IOException { + return kahaDB.getLastMessageBrokerSequenceId(); + } + + @Override + public void deleteAllMessages() throws IOException { + kahaDB.deleteAllMessages(); + } + + @Override + public void setUsageManager(SystemUsage usageManager) { + kahaDB.setUsageManager(usageManager); + } + + @Override + public void setBrokerName(String brokerName) { + kahaDB.setBrokerName(brokerName); + } + + @Override + public void setDirectory(File dir) { + kahaDB.setDirectory(dir); + } + + @Override + public File getDirectory() { + return kahaDB.getDirectory(); + } + + @Override + public void checkpoint(boolean sync) throws IOException { + kahaDB.checkpoint(sync); + } + + @Override + public long size() { + return kahaDB.size(); + } + + @Override + public long getLastProducerSequenceId(ProducerId id) throws IOException { + return kahaDB.getLastProducerSequenceId(id); + } + + } + + private class ProxyMessageStoreWithUpdateException extends ProxyMessageStore { + + private boolean throwExceptionOnUpdate; + private int numBeforeException = 4; + + public ProxyMessageStoreWithUpdateException(MessageStore delegate, boolean throwExceptionOnUpdate) { + super(delegate); + this.throwExceptionOnUpdate = throwExceptionOnUpdate; + } + + @Override + public void updateMessage(Message message) throws IOException { + if (throwExceptionOnUpdate) { + if (numBeforeException > 0) { + numBeforeException--; + super.updateMessage(message); } - } - } - - private class ProxyTopicMessageStoreWithUpdateException extends ProxyTopicMessageStore { - private boolean throwExceptionOnUpdate; - private int numBeforeException = 4; - public ProxyTopicMessageStoreWithUpdateException(TopicMessageStore delegate, boolean throwExceptionOnUpdate) { - super(delegate); - this.throwExceptionOnUpdate = throwExceptionOnUpdate; - } - - @Override - public void updateMessage(Message message) throws IOException { - if(throwExceptionOnUpdate) { - if(numBeforeException > 0) { - numBeforeException--; - super.updateMessage(message); - } else { - //A message that has never been delivered will hit this exception - throw new IOException("Hit our simulated exception writing the update to disk"); - } - } else { - super.updateMessage(message); + else { + // lets only do it once so we can validate transient store failure + throwExceptionOnUpdate = false; + + //A message that has never been delivered will hit this exception + throw new IOException("Hit our simulated exception writing the update to disk"); } - } - } + } + else { + super.updateMessage(message); + } + } + } + + private class ProxyTopicMessageStoreWithUpdateException extends ProxyTopicMessageStore { + + private boolean throwExceptionOnUpdate; + private int numBeforeException = 4; + + public ProxyTopicMessageStoreWithUpdateException(TopicMessageStore delegate, boolean throwExceptionOnUpdate) { + super(delegate); + this.throwExceptionOnUpdate = throwExceptionOnUpdate; + } + + @Override + public void updateMessage(Message message) throws IOException { + if (throwExceptionOnUpdate) { + if (numBeforeException > 0) { + numBeforeException--; + super.updateMessage(message); + } + else { + //A message that has never been delivered will hit this exception + throw new IOException("Hit our simulated exception writing the update to disk"); + } + } + else { + super.updateMessage(message); + } + } + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/SpringTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/SpringTest.java index 7902baa853..db79ce8dab 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/SpringTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/SpringTest.java @@ -31,75 +31,76 @@ import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringTest extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(SpringTest.class); - protected AbstractApplicationContext context; - protected SpringConsumer consumer; - protected SpringProducer producer; + private static final Logger LOG = LoggerFactory.getLogger(SpringTest.class); - public void testSenderWithSpringXml() throws Exception { - assertSenderConfig("org/apache/activemq/broker/spring.xml"); - } - /** - * assert method that is used by all the test method to send and receive messages - * based on each spring configuration. - * - * @param config - * @throws Exception - */ - protected void assertSenderConfig(String config) throws Exception { - context = new ClassPathXmlApplicationContext(config); + protected AbstractApplicationContext context; + protected SpringConsumer consumer; + protected SpringProducer producer; - consumer = (SpringConsumer) context.getBean("consumer"); - assertTrue("Found a valid consumer", consumer != null); + public void testSenderWithSpringXml() throws Exception { + assertSenderConfig("org/apache/activemq/broker/spring.xml"); + } - consumer.start(); + /** + * assert method that is used by all the test method to send and receive messages + * based on each spring configuration. + * + * @param config + * @throws Exception + */ + protected void assertSenderConfig(String config) throws Exception { + context = new ClassPathXmlApplicationContext(config); - producer = (SpringProducer) context.getBean("producer"); - assertTrue("Found a valid producer", producer != null); + consumer = (SpringConsumer) context.getBean("consumer"); + assertTrue("Found a valid consumer", consumer != null); - consumer.flushMessages(); - producer.start(); + consumer.start(); - // lets sleep a little to give the JMS time to dispatch stuff - consumer.waitForMessagesToArrive(producer.getMessageCount()); + producer = (SpringProducer) context.getBean("producer"); + assertTrue("Found a valid producer", producer != null); - // now lets check that the consumer has received some messages - List messages = consumer.flushMessages(); - LOG.info("Consumer has received messages...."); - for (Iterator iter = messages.iterator(); iter.hasNext();) { - Object message = iter.next(); - LOG.info("Received: " + message); - } + consumer.flushMessages(); + producer.start(); - assertEquals("Message count", producer.getMessageCount(), messages.size()); - } + // lets sleep a little to give the JMS time to dispatch stuff + consumer.waitForMessagesToArrive(producer.getMessageCount()); - /** - * Clean up method. - * - * @throws Exception - */ - protected void tearDown() throws Exception { - if (consumer != null) { - consumer.stop(); - } - if (producer != null) { - producer.stop(); - } + // now lets check that the consumer has received some messages + List messages = consumer.flushMessages(); + LOG.info("Consumer has received messages...."); + for (Iterator iter = messages.iterator(); iter.hasNext(); ) { + Object message = iter.next(); + LOG.info("Received: " + message); + } - if (context != null) { - context.destroy(); - } - } + assertEquals("Message count", producer.getMessageCount(), messages.size()); + } - protected void setUp() throws Exception { - if (System.getProperty("basedir") == null) { - File file = new File("."); - System.setProperty("basedir", file.getAbsolutePath()); - } - super.setUp(); - } + /** + * Clean up method. + * + * @throws Exception + */ + protected void tearDown() throws Exception { + if (consumer != null) { + consumer.stop(); + } + if (producer != null) { + producer.stop(); + } + + if (context != null) { + context.destroy(); + } + } + + protected void setUp() throws Exception { + if (System.getProperty("basedir") == null) { + File file = new File("."); + System.setProperty("basedir", file.getAbsolutePath()); + } + super.setUp(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/StubBroker.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/StubBroker.java index 7b4fa1bbc2..3a8d7ffc5d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/StubBroker.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/StubBroker.java @@ -18,40 +18,44 @@ package org.apache.activemq.broker; import java.util.LinkedList; + import org.apache.activemq.command.ConnectionInfo; public class StubBroker extends EmptyBroker { - public LinkedList addConnectionData = new LinkedList(); - public LinkedList removeConnectionData = new LinkedList(); - public class AddConnectionData { - public final ConnectionContext connectionContext; - public final ConnectionInfo connectionInfo; + public LinkedList addConnectionData = new LinkedList(); + public LinkedList removeConnectionData = new LinkedList(); - public AddConnectionData(ConnectionContext context, ConnectionInfo info) { - connectionContext = context; - connectionInfo = info; - } - } + public class AddConnectionData { - public static class RemoveConnectionData { - public final ConnectionContext connectionContext; - public final ConnectionInfo connectionInfo; - public final Throwable error; + public final ConnectionContext connectionContext; + public final ConnectionInfo connectionInfo; - public RemoveConnectionData(ConnectionContext context, ConnectionInfo info, Throwable error) { - connectionContext = context; - connectionInfo = info; - this.error = error; - } - } + public AddConnectionData(ConnectionContext context, ConnectionInfo info) { + connectionContext = context; + connectionInfo = info; + } + } - public void addConnection(ConnectionContext context, ConnectionInfo info) throws Exception { - addConnectionData.add(new AddConnectionData(context, info)); - } + public static class RemoveConnectionData { - public void removeConnection(ConnectionContext context, ConnectionInfo info, Throwable error) throws Exception { - removeConnectionData.add(new RemoveConnectionData(context, info, error)); - } + public final ConnectionContext connectionContext; + public final ConnectionInfo connectionInfo; + public final Throwable error; + + public RemoveConnectionData(ConnectionContext context, ConnectionInfo info, Throwable error) { + connectionContext = context; + connectionInfo = info; + this.error = error; + } + } + + public void addConnection(ConnectionContext context, ConnectionInfo info) throws Exception { + addConnectionData.add(new AddConnectionData(context, info)); + } + + public void removeConnection(ConnectionContext context, ConnectionInfo info, Throwable error) throws Exception { + removeConnectionData.add(new RemoveConnectionData(context, info, error)); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/StubConnection.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/StubConnection.java index 9a70c4ee08..904cf8a06c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/StubConnection.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/StubConnection.java @@ -36,129 +36,133 @@ import org.apache.activemq.util.ServiceSupport; public class StubConnection implements Service { - private final BlockingQueue dispatchQueue = new LinkedBlockingQueue(); - private Connection connection; - private Transport transport; - private boolean shuttingDown; - private TransportListener listener; - public AtomicReference error = new AtomicReference(); + private final BlockingQueue dispatchQueue = new LinkedBlockingQueue(); + private Connection connection; + private Transport transport; + private boolean shuttingDown; + private TransportListener listener; + public AtomicReference error = new AtomicReference(); - public StubConnection(BrokerService broker) throws Exception { - this(TransportFactory.connect(broker.getVmConnectorURI())); - } + public StubConnection(BrokerService broker) throws Exception { + this(TransportFactory.connect(broker.getVmConnectorURI())); + } - public StubConnection(Connection connection) { - this.connection = connection; - } + public StubConnection(Connection connection) { + this.connection = connection; + } - public StubConnection(Transport transport) throws Exception { - this(transport, null); - } + public StubConnection(Transport transport) throws Exception { + this(transport, null); + } - public StubConnection(Transport transport, TransportListener transportListener) throws Exception { - listener = transportListener; - this.transport = transport; - transport.setTransportListener(new DefaultTransportListener() { - public void onCommand(Object command) { - try { - if (command.getClass() == ShutdownInfo.class) { - shuttingDown = true; - } - StubConnection.this.dispatch(command); - } catch (Exception e) { - onException(new IOException("" + e)); - } - } - - public void onException(IOException e) { - if (listener != null) { - listener.onException(e); - } - error.set(e); - } - }); - transport.start(); - } - - protected void dispatch(Object command) throws InterruptedException, IOException { - if (listener != null) { - listener.onCommand(command); - } - dispatchQueue.put(command); - } - - public BlockingQueue getDispatchQueue() { - return dispatchQueue; - } - - public void send(Command command) throws Exception { - if (command instanceof Message) { - Message message = (Message)command; - message.setProducerId(message.getMessageId().getProducerId()); - } - command.setResponseRequired(false); - if (connection != null) { - Response response = connection.service(command); - if (response != null && response.isException()) { - ExceptionResponse er = (ExceptionResponse)response; - throw JMSExceptionSupport.create(er.getException()); - } - } else if (transport != null) { - transport.oneway(command); - } - } - - public Response request(Command command) throws Exception { - if (command instanceof Message) { - Message message = (Message)command; - message.setProducerId(message.getMessageId().getProducerId()); - } - command.setResponseRequired(true); - if (connection != null) { - Response response = connection.service(command); - if (response != null && response.isException()) { - ExceptionResponse er = (ExceptionResponse)response; - throw JMSExceptionSupport.create(er.getException()); - } - return response; - } else if (transport != null) { - Response response = (Response)transport.request(command); - if (response != null && response.isException()) { - ExceptionResponse er = (ExceptionResponse)response; - throw JMSExceptionSupport.create(er.getException()); - } - return response; - } - return null; - } - - public Connection getConnection() { - return connection; - } - - public Transport getTransport() { - return transport; - } - - public void start() throws Exception { - } - - public void stop() throws Exception { - shuttingDown = true; - if (transport != null) { + public StubConnection(Transport transport, TransportListener transportListener) throws Exception { + listener = transportListener; + this.transport = transport; + transport.setTransportListener(new DefaultTransportListener() { + public void onCommand(Object command) { try { - transport.oneway(new ShutdownInfo()); - } catch (IOException e) { + if (command.getClass() == ShutdownInfo.class) { + shuttingDown = true; + } + StubConnection.this.dispatch(command); } - ServiceSupport.dispose(transport); - } - } + catch (Exception e) { + onException(new IOException("" + e)); + } + } - public TransportListener getListener() { - return listener; - } + public void onException(IOException e) { + if (listener != null) { + listener.onException(e); + } + error.set(e); + } + }); + transport.start(); + } - public void setListener(TransportListener listener) { - this.listener = listener; - } + protected void dispatch(Object command) throws InterruptedException, IOException { + if (listener != null) { + listener.onCommand(command); + } + dispatchQueue.put(command); + } + + public BlockingQueue getDispatchQueue() { + return dispatchQueue; + } + + public void send(Command command) throws Exception { + if (command instanceof Message) { + Message message = (Message) command; + message.setProducerId(message.getMessageId().getProducerId()); + } + command.setResponseRequired(false); + if (connection != null) { + Response response = connection.service(command); + if (response != null && response.isException()) { + ExceptionResponse er = (ExceptionResponse) response; + throw JMSExceptionSupport.create(er.getException()); + } + } + else if (transport != null) { + transport.oneway(command); + } + } + + public Response request(Command command) throws Exception { + if (command instanceof Message) { + Message message = (Message) command; + message.setProducerId(message.getMessageId().getProducerId()); + } + command.setResponseRequired(true); + if (connection != null) { + Response response = connection.service(command); + if (response != null && response.isException()) { + ExceptionResponse er = (ExceptionResponse) response; + throw JMSExceptionSupport.create(er.getException()); + } + return response; + } + else if (transport != null) { + Response response = (Response) transport.request(command); + if (response != null && response.isException()) { + ExceptionResponse er = (ExceptionResponse) response; + throw JMSExceptionSupport.create(er.getException()); + } + return response; + } + return null; + } + + public Connection getConnection() { + return connection; + } + + public Transport getTransport() { + return transport; + } + + public void start() throws Exception { + } + + public void stop() throws Exception { + shuttingDown = true; + if (transport != null) { + try { + transport.oneway(new ShutdownInfo()); + } + catch (IOException e) { + } + ServiceSupport.dispose(transport); + } + } + + public TransportListener getListener() { + return listener; + } + + public void setListener(TransportListener listener) { + this.listener = listener; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/TopicSubscriptionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/TopicSubscriptionTest.java index 61ba79c96d..2314b319c5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/TopicSubscriptionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/TopicSubscriptionTest.java @@ -17,6 +17,7 @@ package org.apache.activemq.broker; import java.util.concurrent.TimeUnit; + import org.apache.activemq.TestSupport; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.util.ThreadTracker; @@ -28,133 +29,131 @@ import org.junit.runners.BlockJUnit4ClassRunner; import static org.junit.Assert.*; - @RunWith(BlockJUnit4ClassRunner.class) public class TopicSubscriptionTest extends QueueSubscriptionTest { - @Before - public void setUp() throws Exception { - super.setUp(); - durable = true; - topic = true; - } + @Before + public void setUp() throws Exception { + super.setUp(); + durable = true; + topic = true; + } - @After - public void tearDown() throws Exception { - super.tearDown(); - ThreadTracker.result(); - } + @After + public void tearDown() throws Exception { + super.tearDown(); + ThreadTracker.result(); + } - @Test(timeout = 60 * 1000) - public void testManyProducersManyConsumers() throws Exception { - consumerCount = 40; - producerCount = 20; - messageCount = 100; - messageSize = 1; - prefetchCount = 10; + @Test(timeout = 60 * 1000) + public void testManyProducersManyConsumers() throws Exception { + consumerCount = 40; + producerCount = 20; + messageCount = 100; + messageSize = 1; + prefetchCount = 10; - doMultipleClientsTest(); + doMultipleClientsTest(); - assertTotalMessagesReceived(messageCount * producerCount * consumerCount); - assertDestinationMemoryUsageGoesToZero(); - } + assertTotalMessagesReceived(messageCount * producerCount * consumerCount); + assertDestinationMemoryUsageGoesToZero(); + } - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersLargeMessagesOnePrefetch() throws Exception { - consumerCount = 2; - producerCount = 1; - messageCount = 10; - messageSize = 1024 * 1024 * 1; // 1 MB - prefetchCount = 1; + @Test(timeout = 60 * 1000) + public void testOneProducerTwoConsumersLargeMessagesOnePrefetch() throws Exception { + consumerCount = 2; + producerCount = 1; + messageCount = 10; + messageSize = 1024 * 1024 * 1; // 1 MB + prefetchCount = 1; - doMultipleClientsTest(); + doMultipleClientsTest(); - assertTotalMessagesReceived(messageCount * consumerCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } + assertTotalMessagesReceived(messageCount * consumerCount * producerCount); + assertDestinationMemoryUsageGoesToZero(); + } - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersSmallMessagesOnePrefetch() throws Exception { - consumerCount = 2; - producerCount = 1; - prefetchCount = 1; - messageSize = 1024; - messageCount = 1000; + @Test(timeout = 60 * 1000) + public void testOneProducerTwoConsumersSmallMessagesOnePrefetch() throws Exception { + consumerCount = 2; + producerCount = 1; + prefetchCount = 1; + messageSize = 1024; + messageCount = 1000; - doMultipleClientsTest(); + doMultipleClientsTest(); - assertTotalMessagesReceived(messageCount * consumerCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } + assertTotalMessagesReceived(messageCount * consumerCount * producerCount); + assertDestinationMemoryUsageGoesToZero(); + } - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersSmallMessagesLargePrefetch() throws Exception { - consumerCount = 2; - producerCount = 1; - messageCount = 1000; - messageSize = 1024; - prefetchCount = messageCount * 2; + @Test(timeout = 60 * 1000) + public void testOneProducerTwoConsumersSmallMessagesLargePrefetch() throws Exception { + consumerCount = 2; + producerCount = 1; + messageCount = 1000; + messageSize = 1024; + prefetchCount = messageCount * 2; - doMultipleClientsTest(); + doMultipleClientsTest(); - assertTotalMessagesReceived(messageCount * consumerCount * producerCount); - } + assertTotalMessagesReceived(messageCount * consumerCount * producerCount); + } - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersLargeMessagesLargePrefetch() throws Exception { - consumerCount = 2; - producerCount = 1; - messageCount = 10; - messageSize = 1024 * 1024 * 1; // 1 MB - prefetchCount = messageCount * 2; + @Test(timeout = 60 * 1000) + public void testOneProducerTwoConsumersLargeMessagesLargePrefetch() throws Exception { + consumerCount = 2; + producerCount = 1; + messageCount = 10; + messageSize = 1024 * 1024 * 1; // 1 MB + prefetchCount = messageCount * 2; - doMultipleClientsTest(); + doMultipleClientsTest(); - assertTotalMessagesReceived(messageCount * consumerCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } + assertTotalMessagesReceived(messageCount * consumerCount * producerCount); + assertDestinationMemoryUsageGoesToZero(); + } - @Test(timeout = 60 * 1000) - public void testOneProducerManyConsumersFewMessages() throws Exception { - consumerCount = 50; - producerCount = 1; - messageCount = 10; - messageSize = 1; // 1 byte - prefetchCount = 10; + @Test(timeout = 60 * 1000) + public void testOneProducerManyConsumersFewMessages() throws Exception { + consumerCount = 50; + producerCount = 1; + messageCount = 10; + messageSize = 1; // 1 byte + prefetchCount = 10; - doMultipleClientsTest(); + doMultipleClientsTest(); - assertTotalMessagesReceived(messageCount * consumerCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } + assertTotalMessagesReceived(messageCount * consumerCount * producerCount); + assertDestinationMemoryUsageGoesToZero(); + } - @Test(timeout = 60 * 1000) - public void testOneProducerManyConsumersManyMessages() throws Exception { - consumerCount = 50; - producerCount = 1; - messageCount = 100; - messageSize = 1; // 1 byte - prefetchCount = 10; + @Test(timeout = 60 * 1000) + public void testOneProducerManyConsumersManyMessages() throws Exception { + consumerCount = 50; + producerCount = 1; + messageCount = 100; + messageSize = 1; // 1 byte + prefetchCount = 10; - doMultipleClientsTest(); + doMultipleClientsTest(); - assertTotalMessagesReceived(messageCount * consumerCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } + assertTotalMessagesReceived(messageCount * consumerCount * producerCount); + assertDestinationMemoryUsageGoesToZero(); + } + @Test(timeout = 60 * 1000) + public void testManyProducersOneConsumer() throws Exception { + consumerCount = 1; + producerCount = 20; + messageCount = 100; + messageSize = 1; // 1 byte + prefetchCount = 10; - @Test(timeout = 60 * 1000) - public void testManyProducersOneConsumer() throws Exception { - consumerCount = 1; - producerCount = 20; - messageCount = 100; - messageSize = 1; // 1 byte - prefetchCount = 10; + doMultipleClientsTest(); - doMultipleClientsTest(); - - assertTotalMessagesReceived(messageCount * producerCount * consumerCount); - assertDestinationMemoryUsageGoesToZero(); - } + assertTotalMessagesReceived(messageCount * producerCount * consumerCount); + assertDestinationMemoryUsageGoesToZero(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/XARecoveryBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/XARecoveryBrokerTest.java index 6c25796e6e..9032f37df4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/XARecoveryBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/XARecoveryBrokerTest.java @@ -24,7 +24,9 @@ import javax.jms.JMSException; import javax.management.InstanceNotFoundException; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; + import junit.framework.Test; + import org.apache.activemq.broker.jmx.BrokerMBeanSupport; import org.apache.activemq.broker.jmx.DestinationViewMBean; import org.apache.activemq.broker.jmx.PersistenceAdapterViewMBean; @@ -39,1208 +41,1203 @@ import org.slf4j.LoggerFactory; /** * Used to simulate the recovery that occurs when a broker shuts down. - * - * */ public class XARecoveryBrokerTest extends BrokerRestartTestSupport { - protected static final Logger LOG = LoggerFactory.getLogger(XARecoveryBrokerTest.class); - public boolean prioritySupport = false; - - public void testPreparedJmxView() throws Exception { - - ActiveMQDestination destination = createDestination(); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // Prepare 4 message sends. - for (int i = 0; i < 4; i++) { - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - message.setTransactionId(txid); - connection.send(message); - - // Prepare - connection.send(createPrepareTransaction(connectionInfo, txid)); - } - - Response response = connection.request(new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER)); - assertNotNull(response); - DataArrayResponse dar = (DataArrayResponse)response; - assertEquals(4, dar.getData().length); - - // view prepared in kahadb view - if (broker.getPersistenceAdapter() instanceof KahaDBPersistenceAdapter) { - PersistenceAdapterViewMBean kahadbView = getProxyToPersistenceAdapter(broker.getPersistenceAdapter().toString()); - String txFromView = kahadbView.getTransactions(); - LOG.info("Tx view fromm PA:" + txFromView); - assertTrue("xid with our dud format in transaction string " + txFromView, txFromView.contains("XID:[55,")); - } - - // restart the broker. - restartBroker(); - - connection = createConnection(); - connectionInfo = createConnectionInfo(); - connection.send(connectionInfo); - - - response = connection.request(new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER)); - assertNotNull(response); - dar = (DataArrayResponse)response; - assertEquals(4, dar.getData().length); - - // validate destination depth via jmx - DestinationViewMBean destinationView = getProxyToDestination(destinationList(destination)[0]); - assertEquals("enqueue count does not see prepared", 0, destinationView.getQueueSize()); - - TransactionId first = (TransactionId)dar.getData()[0]; - int commitCount = 0; - // via jmx, force outcome - for (int i = 0; i < 4; i++) { - RecoveredXATransactionViewMBean mbean = getProxyToPreparedTransactionViewMBean((TransactionId)dar.getData()[i]); - if (i%2==0) { - mbean.heuristicCommit(); - commitCount++; - } else { - mbean.heuristicRollback(); - } - } - - // verify all completed - response = connection.request(new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER)); - assertNotNull(response); - dar = (DataArrayResponse)response; - assertEquals(0, dar.getData().length); - - // verify messages available - assertEquals("enqueue count reflects outcome", commitCount, destinationView.getQueueSize()); - - // verify mbeans gone - try { - RecoveredXATransactionViewMBean gone = getProxyToPreparedTransactionViewMBean(first); - gone.heuristicRollback(); - fail("Excepted not found"); - } catch (InstanceNotFoundException expectedNotfound) { - } - } - - private PersistenceAdapterViewMBean getProxyToPersistenceAdapter(String name) throws MalformedObjectNameException, JMSException { - return (PersistenceAdapterViewMBean)broker.getManagementContext().newProxyInstance( - BrokerMBeanSupport.createPersistenceAdapterName(broker.getBrokerObjectName().toString(), name), - PersistenceAdapterViewMBean.class, true); - } - - private RecoveredXATransactionViewMBean getProxyToPreparedTransactionViewMBean(TransactionId xid) throws MalformedObjectNameException, JMSException { - - ObjectName objectName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,transactionType=RecoveredXaTransaction,xid=" + - JMXSupport.encodeObjectNamePart(xid.toString())); - RecoveredXATransactionViewMBean proxy = (RecoveredXATransactionViewMBean) broker.getManagementContext().newProxyInstance(objectName, - RecoveredXATransactionViewMBean.class, true); - return proxy; - } - - private DestinationViewMBean getProxyToDestination(ActiveMQDestination destination) throws MalformedObjectNameException, JMSException { - - final ObjectName objectName = new ObjectName("org.apache.activemq:type=Broker,brokerName="+broker.getBrokerName()+",destinationType=" - + JMXSupport.encodeObjectNamePart(destination.getDestinationTypeAsString()) - + ",destinationName=" + JMXSupport.encodeObjectNamePart(destination.getPhysicalName())); - - DestinationViewMBean proxy = (DestinationViewMBean) broker.getManagementContext().newProxyInstance(objectName, - DestinationViewMBean.class, true); - return proxy; - - } - - public void testPreparedTransactionRecoveredOnRestart() throws Exception { - - ActiveMQDestination destination = createDestination(); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // Prepare 4 message sends. - for (int i = 0; i < 4; i++) { - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - message.setTransactionId(txid); - connection.send(message); - - // Prepare - connection.send(createPrepareTransaction(connectionInfo, txid)); - } - - // Since prepared but not committed.. they should not get delivered. - assertNull(receiveMessage(connection)); - assertNoMessagesLeft(connection); - connection.request(closeConnectionInfo(connectionInfo)); - - // restart the broker. - restartBroker(); - - // Setup the consumer and try receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // Since prepared but not committed.. they should not get delivered. - assertNull(receiveMessage(connection)); - assertNoMessagesLeft(connection); - - Response response = connection.request(new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER)); - assertNotNull(response); - DataArrayResponse dar = (DataArrayResponse)response; - assertEquals(4, dar.getData().length); - - // ensure we can close a connection with prepared transactions - connection.request(closeConnectionInfo(connectionInfo)); - - // open again to deliver outcome - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // Commit the prepared transactions. - for (int i = 0; i < dar.getData().length; i++) { - TransactionId transactionId = (TransactionId) dar.getData()[i]; - LOG.info("commit: " + transactionId); - connection.request(createCommitTransaction2Phase(connectionInfo, transactionId)); - } - - // We should get the committed transactions. - final int countToReceive = expectedMessageCount(4, destination); - for (int i = 0; i < countToReceive ; i++) { - Message m = receiveMessage(connection, TimeUnit.SECONDS.toMillis(10)); - LOG.info("received: " + m); - assertNotNull("Got non null message: " + i, m); - } - - assertNoMessagesLeft(connection); - assertEmptyDLQ(); - } - - private void assertEmptyDLQ() throws Exception { - try { - DestinationViewMBean destinationView = getProxyToDestination(new ActiveMQQueue(SharedDeadLetterStrategy.DEFAULT_DEAD_LETTER_QUEUE_NAME)); - assertEquals("nothing on dlq", 0, destinationView.getQueueSize()); - assertEquals("nothing added to dlq", 0, destinationView.getEnqueueCount()); - } catch (java.lang.reflect.UndeclaredThrowableException maybeOk) { - if (maybeOk.getUndeclaredThrowable() instanceof javax.management.InstanceNotFoundException) { - // perfect no dlq - } else { - throw maybeOk; - } - } - } - - public void testPreparedInterleavedTransactionRecoveredOnRestart() throws Exception { - - ActiveMQDestination destination = createDestination(); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // Prepare 4 message sends. - for (int i = 0; i < 4; i++) { - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - message.setTransactionId(txid); - connection.send(message); - - // Prepare - connection.send(createPrepareTransaction(connectionInfo, txid)); - } - - // Since prepared but not committed.. they should not get delivered. - assertNull(receiveMessage(connection)); - assertNoMessagesLeft(connection); - - // send non tx message - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.request(message); - - connection.request(closeConnectionInfo(connectionInfo)); - - // restart the broker. - restartBroker(); - - // Setup the consumer and try receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // consume non transacted message, but don't ack - int countToReceive = expectedMessageCount(1, destination); - for (int i=0; i< countToReceive; i++) { - Message m = receiveMessage(connection, TimeUnit.SECONDS.toMillis(10)); - LOG.info("received: " + m); - assertNotNull("got non tx message after prepared", m); - } - - // Since prepared but not committed.. they should not get delivered. - assertNull(receiveMessage(connection)); - assertNoMessagesLeft(connection); - - Response response = connection.request(new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER)); - assertNotNull(response); - DataArrayResponse dar = (DataArrayResponse)response; - assertEquals(4, dar.getData().length); - - // ensure we can close a connection with prepared transactions - connection.request(closeConnectionInfo(connectionInfo)); - - // open again to deliver outcome - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - - // Commit the prepared transactions. - for (int i = 0; i < dar.getData().length; i++) { - TransactionId transactionId = (TransactionId) dar.getData()[i]; - LOG.info("commit: " + transactionId); - connection.request(createCommitTransaction2Phase(connectionInfo, transactionId)); - } - - consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // We should get the committed transactions and the non tx message - countToReceive = expectedMessageCount(5, destination); - for (int i = 0; i < countToReceive ; i++) { - Message m = receiveMessage(connection, TimeUnit.SECONDS.toMillis(10)); - LOG.info("received: " + m); - assertNotNull("Got non null message: " + i, m); - } - - assertNoMessagesLeft(connection); - assertEmptyDLQ(); - } - - public void testTopicPreparedTransactionRecoveredOnRestart() throws Exception { - ActiveMQDestination destination = new ActiveMQTopic("TryTopic"); - - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - connectionInfo.setClientId("durable"); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setSubscriptionName("durable"); - connection.send(consumerInfo); - - // Prepare 4 message sends. - for (int i = 0; i < 4; i++) { - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - message.setTransactionId(txid); - connection.send(message); - - // Prepare - connection.send(createPrepareTransaction(connectionInfo, txid)); - } - - // Since prepared but not committed.. they should not get delivered. - assertNull(receiveMessage(connection)); - assertNoMessagesLeft(connection); - connection.request(closeConnectionInfo(connectionInfo)); - - // restart the broker. - restartBroker(); - - // Setup the consumer and try receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - connectionInfo.setClientId("durable"); - - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setSubscriptionName("durable"); - connection.send(consumerInfo); - - // Since prepared but not committed.. they should not get delivered. - assertNull(receiveMessage(connection)); - assertNoMessagesLeft(connection); - - Response response = connection.request(new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER)); - assertNotNull(response); - DataArrayResponse dar = (DataArrayResponse) response; - assertEquals(4, dar.getData().length); - - // ensure we can close a connection with prepared transactions - connection.request(closeConnectionInfo(connectionInfo)); - - // open again to deliver outcome - connection = createConnection(); - connectionInfo = createConnectionInfo(); - connectionInfo.setClientId("durable"); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setSubscriptionName("durable"); - connection.send(consumerInfo); - - // Commit the prepared transactions. - for (int i = 0; i < dar.getData().length; i++) { - connection.request(createCommitTransaction2Phase(connectionInfo, (TransactionId) dar.getData()[i])); - } - - // We should get the committed transactions. - for (int i = 0; i < expectedMessageCount(4, destination); i++) { - Message m = receiveMessage(connection, TimeUnit.SECONDS.toMillis(10)); - assertNotNull(m); - } - - assertNoMessagesLeft(connection); - - } - - public void testQueuePersistentCommittedMessagesNotLostOnRestart() throws Exception { - - ActiveMQDestination destination = createDestination(); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - for (int i = 0; i < 4; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - message.setTransactionId(txid); - connection.send(message); - } - - // Commit - connection.send(createCommitTransaction1Phase(connectionInfo, txid)); - connection.request(closeConnectionInfo(connectionInfo)); - // restart the broker. - restartBroker(); - - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - for (int i = 0; i < expectedMessageCount(4, destination); i++) { - Message m = receiveMessage(connection); - assertNotNull(m); - } - - assertNoMessagesLeft(connection); - } - - public void testQueuePersistentCommitted2PhaseMessagesNotLostOnRestart() throws Exception { - - ActiveMQDestination destination = createDestination(); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - for (int i = 0; i < 4; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - message.setTransactionId(txid); - connection.send(message); - } - - // Commit 2 phase - connection.request(createPrepareTransaction(connectionInfo, txid)); - connection.send(createCommitTransaction2Phase(connectionInfo, txid)); - - connection.request(closeConnectionInfo(connectionInfo)); - // restart the broker. - restartBroker(); - - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - for (int i = 0; i < expectedMessageCount(4, destination); i++) { - Message m = receiveMessage(connection); - assertNotNull(m); - } - - assertNoMessagesLeft(connection); - } - - public void testQueuePersistentCommittedAcksNotLostOnRestart() throws Exception { - - ActiveMQDestination destination = createDestination(); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - for (int i = 0; i < 4; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - } - - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - ConsumerInfo consumerInfo; - Message m = null; - for (ActiveMQDestination dest : destinationList(destination)) { - // Setup the consumer and receive the message. - consumerInfo = createConsumerInfo(sessionInfo, dest); - connection.send(consumerInfo); - - for (int i = 0; i < 4; i++) { - m = receiveMessage(connection); - assertNotNull(m); - } - - MessageAck ack = createAck(consumerInfo, m, 4, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); - } - - // Commit - connection.request(createCommitTransaction1Phase(connectionInfo, txid)); - - // restart the broker. - restartBroker(); - - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // No messages should be delivered. - assertNoMessagesLeft(connection); - - m = receiveMessage(connection); - assertNull(m); - } - - public void testQueuePersistentPreparedAcksNotLostOnRestart() throws Exception { - - ActiveMQDestination destination = createDestination(); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - for (int i = 0; i < 4; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - } - - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - ConsumerInfo consumerInfo; - Message m = null; - for (ActiveMQDestination dest : destinationList(destination)) { - // Setup the consumer and receive the message. - consumerInfo = createConsumerInfo(sessionInfo, dest); - connection.send(consumerInfo); - - for (int i = 0; i < 4; i++) { - m = receiveMessage(connection); - assertNotNull(m); - } - - // one ack with last received, mimic a beforeEnd synchronization - MessageAck ack = createAck(consumerInfo, m, 4, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); - } - - connection.request(createPrepareTransaction(connectionInfo, txid)); - - // restart the broker. - restartBroker(); - - connection = createConnection(); - connectionInfo = createConnectionInfo(); - connection.send(connectionInfo); - - // validate recovery - TransactionInfo recoverInfo = new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER); - DataArrayResponse dataArrayResponse = (DataArrayResponse)connection.request(recoverInfo); - - assertEquals("there is a prepared tx", 1, dataArrayResponse.getData().length); - assertEquals("it matches", txid, dataArrayResponse.getData()[0]); - - sessionInfo = createSessionInfo(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // no redelivery, exactly once semantics unless there is rollback - m = receiveMessage(connection); - assertNull(m); - assertNoMessagesLeft(connection); - - // validate destination depth via jmx - DestinationViewMBean destinationView = getProxyToDestination(destinationList(destination)[0]); - assertEquals("enqueue count does not see prepared acks", 4, destinationView.getQueueSize()); - assertEquals("enqueue count does not see prepared acks", 0, destinationView.getDequeueCount()); - - connection.request(createCommitTransaction2Phase(connectionInfo, txid)); - - // validate recovery complete - dataArrayResponse = (DataArrayResponse)connection.request(recoverInfo); - assertEquals("there are no prepared tx", 0, dataArrayResponse.getData().length); - - assertEquals("enqueue count does not see committed acks", 0, destinationView.getQueueSize()); - assertEquals("enqueue count does not see committed acks", 4, destinationView.getDequeueCount()); - - } - - public void initCombosForTestTopicPersistentPreparedAcksNotLostOnRestart() { - addCombinationValues("prioritySupport", new Boolean[]{Boolean.FALSE, Boolean.TRUE}); - } - - public void testTopicPersistentPreparedAcksNotLostOnRestart() throws Exception { - ActiveMQDestination destination = new ActiveMQTopic("TryTopic"); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - connectionInfo.setClientId("durable"); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - // setup durable subs - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setSubscriptionName("durable"); - connection.send(consumerInfo); - - final int numMessages = 4; - for (int i = 0; i < numMessages; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - } - - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - final int messageCount = expectedMessageCount(numMessages, destination); - Message m = null; - for (int i = 0; i < messageCount; i++) { + + protected static final Logger LOG = LoggerFactory.getLogger(XARecoveryBrokerTest.class); + public boolean prioritySupport = false; + + public void testPreparedJmxView() throws Exception { + + ActiveMQDestination destination = createDestination(); + + // Setup the producer and send the message. + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); + + // Prepare 4 message sends. + for (int i = 0; i < 4; i++) { + // Begin the transaction. + XATransactionId txid = createXATransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); + + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + message.setTransactionId(txid); + connection.send(message); + + // Prepare + connection.send(createPrepareTransaction(connectionInfo, txid)); + } + + Response response = connection.request(new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER)); + assertNotNull(response); + DataArrayResponse dar = (DataArrayResponse) response; + assertEquals(4, dar.getData().length); + + // view prepared in kahadb view + if (broker.getPersistenceAdapter() instanceof KahaDBPersistenceAdapter) { + PersistenceAdapterViewMBean kahadbView = getProxyToPersistenceAdapter(broker.getPersistenceAdapter().toString()); + String txFromView = kahadbView.getTransactions(); + LOG.info("Tx view fromm PA:" + txFromView); + assertTrue("xid with our dud format in transaction string " + txFromView, txFromView.contains("XID:[55,")); + } + + // restart the broker. + restartBroker(); + + connection = createConnection(); + connectionInfo = createConnectionInfo(); + connection.send(connectionInfo); + + response = connection.request(new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER)); + assertNotNull(response); + dar = (DataArrayResponse) response; + assertEquals(4, dar.getData().length); + + // validate destination depth via jmx + DestinationViewMBean destinationView = getProxyToDestination(destinationList(destination)[0]); + assertEquals("enqueue count does not see prepared", 0, destinationView.getQueueSize()); + + TransactionId first = (TransactionId) dar.getData()[0]; + int commitCount = 0; + // via jmx, force outcome + for (int i = 0; i < 4; i++) { + RecoveredXATransactionViewMBean mbean = getProxyToPreparedTransactionViewMBean((TransactionId) dar.getData()[i]); + if (i % 2 == 0) { + mbean.heuristicCommit(); + commitCount++; + } + else { + mbean.heuristicRollback(); + } + } + + // verify all completed + response = connection.request(new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER)); + assertNotNull(response); + dar = (DataArrayResponse) response; + assertEquals(0, dar.getData().length); + + // verify messages available + assertEquals("enqueue count reflects outcome", commitCount, destinationView.getQueueSize()); + + // verify mbeans gone + try { + RecoveredXATransactionViewMBean gone = getProxyToPreparedTransactionViewMBean(first); + gone.heuristicRollback(); + fail("Excepted not found"); + } + catch (InstanceNotFoundException expectedNotfound) { + } + } + + private PersistenceAdapterViewMBean getProxyToPersistenceAdapter(String name) throws MalformedObjectNameException, JMSException { + return (PersistenceAdapterViewMBean) broker.getManagementContext().newProxyInstance(BrokerMBeanSupport.createPersistenceAdapterName(broker.getBrokerObjectName().toString(), name), PersistenceAdapterViewMBean.class, true); + } + + private RecoveredXATransactionViewMBean getProxyToPreparedTransactionViewMBean(TransactionId xid) throws MalformedObjectNameException, JMSException { + + ObjectName objectName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,transactionType=RecoveredXaTransaction,xid=" + JMXSupport.encodeObjectNamePart(xid.toString())); + RecoveredXATransactionViewMBean proxy = (RecoveredXATransactionViewMBean) broker.getManagementContext().newProxyInstance(objectName, RecoveredXATransactionViewMBean.class, true); + return proxy; + } + + private DestinationViewMBean getProxyToDestination(ActiveMQDestination destination) throws MalformedObjectNameException, JMSException { + + final ObjectName objectName = new ObjectName("org.apache.activemq:type=Broker,brokerName=" + broker.getBrokerName() + ",destinationType=" + JMXSupport.encodeObjectNamePart(destination.getDestinationTypeAsString()) + ",destinationName=" + JMXSupport.encodeObjectNamePart(destination.getPhysicalName())); + + DestinationViewMBean proxy = (DestinationViewMBean) broker.getManagementContext().newProxyInstance(objectName, DestinationViewMBean.class, true); + return proxy; + + } + + public void testPreparedTransactionRecoveredOnRestart() throws Exception { + + ActiveMQDestination destination = createDestination(); + + // Setup the producer and send the message. + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); + + // Prepare 4 message sends. + for (int i = 0; i < 4; i++) { + // Begin the transaction. + XATransactionId txid = createXATransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); + + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + message.setTransactionId(txid); + connection.send(message); + + // Prepare + connection.send(createPrepareTransaction(connectionInfo, txid)); + } + + // Since prepared but not committed.. they should not get delivered. + assertNull(receiveMessage(connection)); + assertNoMessagesLeft(connection); + connection.request(closeConnectionInfo(connectionInfo)); + + // restart the broker. + restartBroker(); + + // Setup the consumer and try receive the message. + connection = createConnection(); + connectionInfo = createConnectionInfo(); + sessionInfo = createSessionInfo(connectionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); + + // Since prepared but not committed.. they should not get delivered. + assertNull(receiveMessage(connection)); + assertNoMessagesLeft(connection); + + Response response = connection.request(new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER)); + assertNotNull(response); + DataArrayResponse dar = (DataArrayResponse) response; + assertEquals(4, dar.getData().length); + + // ensure we can close a connection with prepared transactions + connection.request(closeConnectionInfo(connectionInfo)); + + // open again to deliver outcome + connection = createConnection(); + connectionInfo = createConnectionInfo(); + sessionInfo = createSessionInfo(connectionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); + + // Commit the prepared transactions. + for (int i = 0; i < dar.getData().length; i++) { + TransactionId transactionId = (TransactionId) dar.getData()[i]; + LOG.info("commit: " + transactionId); + connection.request(createCommitTransaction2Phase(connectionInfo, transactionId)); + } + + // We should get the committed transactions. + final int countToReceive = expectedMessageCount(4, destination); + for (int i = 0; i < countToReceive; i++) { + Message m = receiveMessage(connection, TimeUnit.SECONDS.toMillis(10)); + LOG.info("received: " + m); + assertNotNull("Got non null message: " + i, m); + } + + assertNoMessagesLeft(connection); + assertEmptyDLQ(); + } + + private void assertEmptyDLQ() throws Exception { + try { + DestinationViewMBean destinationView = getProxyToDestination(new ActiveMQQueue(SharedDeadLetterStrategy.DEFAULT_DEAD_LETTER_QUEUE_NAME)); + assertEquals("nothing on dlq", 0, destinationView.getQueueSize()); + assertEquals("nothing added to dlq", 0, destinationView.getEnqueueCount()); + } + catch (java.lang.reflect.UndeclaredThrowableException maybeOk) { + if (maybeOk.getUndeclaredThrowable() instanceof javax.management.InstanceNotFoundException) { + // perfect no dlq + } + else { + throw maybeOk; + } + } + } + + public void testPreparedInterleavedTransactionRecoveredOnRestart() throws Exception { + + ActiveMQDestination destination = createDestination(); + + // Setup the producer and send the message. + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); + + // Prepare 4 message sends. + for (int i = 0; i < 4; i++) { + // Begin the transaction. + XATransactionId txid = createXATransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); + + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + message.setTransactionId(txid); + connection.send(message); + + // Prepare + connection.send(createPrepareTransaction(connectionInfo, txid)); + } + + // Since prepared but not committed.. they should not get delivered. + assertNull(receiveMessage(connection)); + assertNoMessagesLeft(connection); + + // send non tx message + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + connection.request(message); + + connection.request(closeConnectionInfo(connectionInfo)); + + // restart the broker. + restartBroker(); + + // Setup the consumer and try receive the message. + connection = createConnection(); + connectionInfo = createConnectionInfo(); + sessionInfo = createSessionInfo(connectionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); + + // consume non transacted message, but don't ack + int countToReceive = expectedMessageCount(1, destination); + for (int i = 0; i < countToReceive; i++) { + Message m = receiveMessage(connection, TimeUnit.SECONDS.toMillis(10)); + LOG.info("received: " + m); + assertNotNull("got non tx message after prepared", m); + } + + // Since prepared but not committed.. they should not get delivered. + assertNull(receiveMessage(connection)); + assertNoMessagesLeft(connection); + + Response response = connection.request(new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER)); + assertNotNull(response); + DataArrayResponse dar = (DataArrayResponse) response; + assertEquals(4, dar.getData().length); + + // ensure we can close a connection with prepared transactions + connection.request(closeConnectionInfo(connectionInfo)); + + // open again to deliver outcome + connection = createConnection(); + connectionInfo = createConnectionInfo(); + sessionInfo = createSessionInfo(connectionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + + // Commit the prepared transactions. + for (int i = 0; i < dar.getData().length; i++) { + TransactionId transactionId = (TransactionId) dar.getData()[i]; + LOG.info("commit: " + transactionId); + connection.request(createCommitTransaction2Phase(connectionInfo, transactionId)); + } + + consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); + + // We should get the committed transactions and the non tx message + countToReceive = expectedMessageCount(5, destination); + for (int i = 0; i < countToReceive; i++) { + Message m = receiveMessage(connection, TimeUnit.SECONDS.toMillis(10)); + LOG.info("received: " + m); + assertNotNull("Got non null message: " + i, m); + } + + assertNoMessagesLeft(connection); + assertEmptyDLQ(); + } + + public void testTopicPreparedTransactionRecoveredOnRestart() throws Exception { + ActiveMQDestination destination = new ActiveMQTopic("TryTopic"); + + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + connectionInfo.setClientId("durable"); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + consumerInfo.setSubscriptionName("durable"); + connection.send(consumerInfo); + + // Prepare 4 message sends. + for (int i = 0; i < 4; i++) { + // Begin the transaction. + XATransactionId txid = createXATransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); + + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + message.setTransactionId(txid); + connection.send(message); + + // Prepare + connection.send(createPrepareTransaction(connectionInfo, txid)); + } + + // Since prepared but not committed.. they should not get delivered. + assertNull(receiveMessage(connection)); + assertNoMessagesLeft(connection); + connection.request(closeConnectionInfo(connectionInfo)); + + // restart the broker. + restartBroker(); + + // Setup the consumer and try receive the message. + connection = createConnection(); + connectionInfo = createConnectionInfo(); + connectionInfo.setClientId("durable"); + + sessionInfo = createSessionInfo(connectionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + consumerInfo = createConsumerInfo(sessionInfo, destination); + consumerInfo.setSubscriptionName("durable"); + connection.send(consumerInfo); + + // Since prepared but not committed.. they should not get delivered. + assertNull(receiveMessage(connection)); + assertNoMessagesLeft(connection); + + Response response = connection.request(new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER)); + assertNotNull(response); + DataArrayResponse dar = (DataArrayResponse) response; + assertEquals(4, dar.getData().length); + + // ensure we can close a connection with prepared transactions + connection.request(closeConnectionInfo(connectionInfo)); + + // open again to deliver outcome + connection = createConnection(); + connectionInfo = createConnectionInfo(); + connectionInfo.setClientId("durable"); + sessionInfo = createSessionInfo(connectionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + consumerInfo = createConsumerInfo(sessionInfo, destination); + consumerInfo.setSubscriptionName("durable"); + connection.send(consumerInfo); + + // Commit the prepared transactions. + for (int i = 0; i < dar.getData().length; i++) { + connection.request(createCommitTransaction2Phase(connectionInfo, (TransactionId) dar.getData()[i])); + } + + // We should get the committed transactions. + for (int i = 0; i < expectedMessageCount(4, destination); i++) { + Message m = receiveMessage(connection, TimeUnit.SECONDS.toMillis(10)); + assertNotNull(m); + } + + assertNoMessagesLeft(connection); + + } + + public void testQueuePersistentCommittedMessagesNotLostOnRestart() throws Exception { + + ActiveMQDestination destination = createDestination(); + + // Setup the producer and send the message. + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); + + // Begin the transaction. + XATransactionId txid = createXATransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); + + for (int i = 0; i < 4; i++) { + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + message.setTransactionId(txid); + connection.send(message); + } + + // Commit + connection.send(createCommitTransaction1Phase(connectionInfo, txid)); + connection.request(closeConnectionInfo(connectionInfo)); + // restart the broker. + restartBroker(); + + // Setup the consumer and receive the message. + connection = createConnection(); + connectionInfo = createConnectionInfo(); + sessionInfo = createSessionInfo(connectionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); + + for (int i = 0; i < expectedMessageCount(4, destination); i++) { + Message m = receiveMessage(connection); + assertNotNull(m); + } + + assertNoMessagesLeft(connection); + } + + public void testQueuePersistentCommitted2PhaseMessagesNotLostOnRestart() throws Exception { + + ActiveMQDestination destination = createDestination(); + + // Setup the producer and send the message. + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); + + // Begin the transaction. + XATransactionId txid = createXATransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); + + for (int i = 0; i < 4; i++) { + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + message.setTransactionId(txid); + connection.send(message); + } + + // Commit 2 phase + connection.request(createPrepareTransaction(connectionInfo, txid)); + connection.send(createCommitTransaction2Phase(connectionInfo, txid)); + + connection.request(closeConnectionInfo(connectionInfo)); + // restart the broker. + restartBroker(); + + // Setup the consumer and receive the message. + connection = createConnection(); + connectionInfo = createConnectionInfo(); + sessionInfo = createSessionInfo(connectionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); + + for (int i = 0; i < expectedMessageCount(4, destination); i++) { + Message m = receiveMessage(connection); + assertNotNull(m); + } + + assertNoMessagesLeft(connection); + } + + public void testQueuePersistentCommittedAcksNotLostOnRestart() throws Exception { + + ActiveMQDestination destination = createDestination(); + + // Setup the producer and send the message. + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); + + for (int i = 0; i < 4; i++) { + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + connection.send(message); + } + + // Begin the transaction. + XATransactionId txid = createXATransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); + + ConsumerInfo consumerInfo; + Message m = null; + for (ActiveMQDestination dest : destinationList(destination)) { + // Setup the consumer and receive the message. + consumerInfo = createConsumerInfo(sessionInfo, dest); + connection.send(consumerInfo); + + for (int i = 0; i < 4; i++) { m = receiveMessage(connection); - assertNotNull("unexpected null on: " + i, m); - } + assertNotNull(m); + } - // one ack with last received, mimic a beforeEnd synchronization - MessageAck ack = createAck(consumerInfo, m, messageCount, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); + MessageAck ack = createAck(consumerInfo, m, 4, MessageAck.STANDARD_ACK_TYPE); + ack.setTransactionId(txid); + connection.send(ack); + } - connection.request(createPrepareTransaction(connectionInfo, txid)); + // Commit + connection.request(createCommitTransaction1Phase(connectionInfo, txid)); - // restart the broker. - restartBroker(); + // restart the broker. + restartBroker(); - connection = createConnection(); - connectionInfo = createConnectionInfo(); - connectionInfo.setClientId("durable"); - connection.send(connectionInfo); + // Setup the consumer and receive the message. + connection = createConnection(); + connectionInfo = createConnectionInfo(); + sessionInfo = createSessionInfo(connectionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); - // validate recovery - TransactionInfo recoverInfo = new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER); - DataArrayResponse dataArrayResponse = (DataArrayResponse)connection.request(recoverInfo); + // No messages should be delivered. + assertNoMessagesLeft(connection); - assertEquals("there is a prepared tx", 1, dataArrayResponse.getData().length); - assertEquals("it matches", txid, dataArrayResponse.getData()[0]); + m = receiveMessage(connection); + assertNull(m); + } - sessionInfo = createSessionInfo(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setSubscriptionName("durable"); - connection.send(consumerInfo); + public void testQueuePersistentPreparedAcksNotLostOnRestart() throws Exception { - // no redelivery, exactly once semantics unless there is rollback - m = receiveMessage(connection); - assertNull(m); - assertNoMessagesLeft(connection); + ActiveMQDestination destination = createDestination(); - connection.request(createCommitTransaction2Phase(connectionInfo, txid)); + // Setup the producer and send the message. + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); - // validate recovery complete - dataArrayResponse = (DataArrayResponse)connection.request(recoverInfo); - assertEquals("there are no prepared tx", 0, dataArrayResponse.getData().length); - } + for (int i = 0; i < 4; i++) { + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + connection.send(message); + } - public void testQueuePersistentPreparedAcksAvailableAfterRestartAndRollback() throws Exception { + // Begin the transaction. + XATransactionId txid = createXATransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); - ActiveMQDestination destination = createDestination(); + ConsumerInfo consumerInfo; + Message m = null; + for (ActiveMQDestination dest : destinationList(destination)) { + // Setup the consumer and receive the message. + consumerInfo = createConsumerInfo(sessionInfo, dest); + connection.send(consumerInfo); - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); + for (int i = 0; i < 4; i++) { + m = receiveMessage(connection); + assertNotNull(m); + } - int numMessages = 4; - for (int i = 0; i < numMessages; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - } + // one ack with last received, mimic a beforeEnd synchronization + MessageAck ack = createAck(consumerInfo, m, 4, MessageAck.STANDARD_ACK_TYPE); + ack.setTransactionId(txid); + connection.send(ack); + } - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); + connection.request(createPrepareTransaction(connectionInfo, txid)); - ConsumerInfo consumerInfo; - Message message = null; - for (ActiveMQDestination dest : destinationList(destination)) { - // Setup the consumer and receive the message. - consumerInfo = createConsumerInfo(sessionInfo, dest); - connection.send(consumerInfo); + // restart the broker. + restartBroker(); - for (int i = 0; i < numMessages; i++) { - message = receiveMessage(connection); - assertNotNull(message); - } + connection = createConnection(); + connectionInfo = createConnectionInfo(); + connection.send(connectionInfo); - // one ack with last received, mimic a beforeEnd synchronization - MessageAck ack = createAck(consumerInfo, message, numMessages, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); - } + // validate recovery + TransactionInfo recoverInfo = new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER); + DataArrayResponse dataArrayResponse = (DataArrayResponse) connection.request(recoverInfo); - connection.request(createPrepareTransaction(connectionInfo, txid)); + assertEquals("there is a prepared tx", 1, dataArrayResponse.getData().length); + assertEquals("it matches", txid, dataArrayResponse.getData()[0]); - // restart the broker. - restartBroker(); + sessionInfo = createSessionInfo(connectionInfo); + connection.send(sessionInfo); + consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); - connection = createConnection(); - connectionInfo = createConnectionInfo(); - connection.send(connectionInfo); + // no redelivery, exactly once semantics unless there is rollback + m = receiveMessage(connection); + assertNull(m); + assertNoMessagesLeft(connection); - // validate recovery - TransactionInfo recoverInfo = new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER); - DataArrayResponse dataArrayResponse = (DataArrayResponse)connection.request(recoverInfo); + // validate destination depth via jmx + DestinationViewMBean destinationView = getProxyToDestination(destinationList(destination)[0]); + assertEquals("enqueue count does not see prepared acks", 4, destinationView.getQueueSize()); + assertEquals("enqueue count does not see prepared acks", 0, destinationView.getDequeueCount()); - assertEquals("there is a prepared tx", 1, dataArrayResponse.getData().length); - assertEquals("it matches", txid, dataArrayResponse.getData()[0]); + connection.request(createCommitTransaction2Phase(connectionInfo, txid)); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); + // validate recovery complete + dataArrayResponse = (DataArrayResponse) connection.request(recoverInfo); + assertEquals("there are no prepared tx", 0, dataArrayResponse.getData().length); - // no redelivery, exactly once semantics while prepared - message = receiveMessage(connection); - assertNull(message); - assertNoMessagesLeft(connection); + assertEquals("enqueue count does not see committed acks", 0, destinationView.getQueueSize()); + assertEquals("enqueue count does not see committed acks", 4, destinationView.getDequeueCount()); - // rollback so we get redelivery - connection.request(createRollbackTransaction(connectionInfo, txid)); + } - LOG.info("new tx for redelivery"); - txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); + public void initCombosForTestTopicPersistentPreparedAcksNotLostOnRestart() { + addCombinationValues("prioritySupport", new Boolean[]{Boolean.FALSE, Boolean.TRUE}); + } - for (ActiveMQDestination dest : destinationList(destination)) { - // Setup the consumer and receive the message. - consumerInfo = createConsumerInfo(sessionInfo, dest); - connection.send(consumerInfo); + public void testTopicPersistentPreparedAcksNotLostOnRestart() throws Exception { + ActiveMQDestination destination = new ActiveMQTopic("TryTopic"); - for (int i = 0; i < numMessages; i++) { - message = receiveMessage(connection); - assertNotNull("unexpected null on:" + i, message); - } - MessageAck ack = createAck(consumerInfo, message, numMessages, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); - } + // Setup the producer and send the message. + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + connectionInfo.setClientId("durable"); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); - // Commit - connection.request(createCommitTransaction1Phase(connectionInfo, txid)); + // setup durable subs + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + consumerInfo.setSubscriptionName("durable"); + connection.send(consumerInfo); - // validate recovery complete - dataArrayResponse = (DataArrayResponse)connection.request(recoverInfo); - assertEquals("there are no prepared tx", 0, dataArrayResponse.getData().length); - } + final int numMessages = 4; + for (int i = 0; i < numMessages; i++) { + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + connection.send(message); + } - public void testQueuePersistentPreparedAcksAvailableAfterRollbackPrefetchOne() throws Exception { + // Begin the transaction. + XATransactionId txid = createXATransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); - ActiveMQDestination destination = createDestination(); + final int messageCount = expectedMessageCount(numMessages, destination); + Message m = null; + for (int i = 0; i < messageCount; i++) { + m = receiveMessage(connection); + assertNotNull("unexpected null on: " + i, m); + } - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); + // one ack with last received, mimic a beforeEnd synchronization + MessageAck ack = createAck(consumerInfo, m, messageCount, MessageAck.STANDARD_ACK_TYPE); + ack.setTransactionId(txid); + connection.send(ack); - int numMessages = 1; - for (int i = 0; i < numMessages; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - } + connection.request(createPrepareTransaction(connectionInfo, txid)); - final int messageCount = expectedMessageCount(numMessages, destination); + // restart the broker. + restartBroker(); - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); + connection = createConnection(); + connectionInfo = createConnectionInfo(); + connectionInfo.setClientId("durable"); + connection.send(connectionInfo); - // use consumer per destination for the composite dest case - // bc the same composite dest is used for sending so there - // will be duplicate message ids in the mix which a single - // consumer (PrefetchSubscription) cannot handle in a tx - // atm. The matching is based on messageId rather than messageId - // and destination - Set consumerInfos = new HashSet(); - for (ActiveMQDestination dest : destinationList(destination)) { - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, dest); - consumerInfo.setPrefetchSize(numMessages); - consumerInfos.add(consumerInfo); - } + // validate recovery + TransactionInfo recoverInfo = new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER); + DataArrayResponse dataArrayResponse = (DataArrayResponse) connection.request(recoverInfo); - for (ConsumerInfo info : consumerInfos) { - connection.send(info); - } + assertEquals("there is a prepared tx", 1, dataArrayResponse.getData().length); + assertEquals("it matches", txid, dataArrayResponse.getData()[0]); - Message message = null; - for (ConsumerInfo info : consumerInfos) { - for (int i = 0; i < numMessages; i++) { - message = receiveMessage(connection); - assertNotNull(message); - connection.send(createAck(info, message, 1, MessageAck.DELIVERED_ACK_TYPE)); - } - MessageAck ack = createAck(info, message, numMessages, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); - } - connection.request(createPrepareTransaction(connectionInfo, txid)); + sessionInfo = createSessionInfo(connectionInfo); + connection.send(sessionInfo); + consumerInfo = createConsumerInfo(sessionInfo, destination); + consumerInfo.setSubscriptionName("durable"); + connection.send(consumerInfo); - // reconnect - connection.send(connectionInfo.createRemoveCommand()); - connection = createConnection(); - connection.send(connectionInfo); + // no redelivery, exactly once semantics unless there is rollback + m = receiveMessage(connection); + assertNull(m); + assertNoMessagesLeft(connection); - // validate recovery - TransactionInfo recoverInfo = new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER); - DataArrayResponse dataArrayResponse = (DataArrayResponse) connection.request(recoverInfo); + connection.request(createCommitTransaction2Phase(connectionInfo, txid)); - assertEquals("there is a prepared tx", 1, dataArrayResponse.getData().length); - assertEquals("it matches", txid, dataArrayResponse.getData()[0]); + // validate recovery complete + dataArrayResponse = (DataArrayResponse) connection.request(recoverInfo); + assertEquals("there are no prepared tx", 0, dataArrayResponse.getData().length); + } - connection.send(sessionInfo); + public void testQueuePersistentPreparedAcksAvailableAfterRestartAndRollback() throws Exception { - for (ConsumerInfo info : consumerInfos) { - connection.send(info); - } + ActiveMQDestination destination = createDestination(); - // no redelivery, exactly once semantics while prepared - message = receiveMessage(connection); - assertNull(message); - assertNoMessagesLeft(connection); + // Setup the producer and send the message. + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); - // rollback so we get redelivery - connection.request(createRollbackTransaction(connectionInfo, txid)); + int numMessages = 4; + for (int i = 0; i < numMessages; i++) { + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + connection.send(message); + } - LOG.info("new tx for redelivery"); - txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); + // Begin the transaction. + XATransactionId txid = createXATransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); - for (ConsumerInfo info : consumerInfos) { - for (int i = 0; i < numMessages; i++) { - message = receiveMessage(connection); - assertNotNull("unexpected null on:" + i, message); - MessageAck ack = createAck(info, message, 1, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); - } - } + ConsumerInfo consumerInfo; + Message message = null; + for (ActiveMQDestination dest : destinationList(destination)) { + // Setup the consumer and receive the message. + consumerInfo = createConsumerInfo(sessionInfo, dest); + connection.send(consumerInfo); - // Commit - connection.request(createCommitTransaction1Phase(connectionInfo, txid)); - - // validate recovery complete - dataArrayResponse = (DataArrayResponse) connection.request(recoverInfo); - assertEquals("there are no prepared tx", 0, dataArrayResponse.getData().length); - } - - public void initCombosForTestTopicPersistentPreparedAcksAvailableAfterRestartAndRollback() { - addCombinationValues("prioritySupport", new Boolean[]{Boolean.FALSE, Boolean.TRUE}); - } - - public void testTopicPersistentPreparedAcksAvailableAfterRestartAndRollback() throws Exception { - - ActiveMQDestination destination = new ActiveMQTopic("TryTopic"); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - connectionInfo.setClientId("durable"); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - // setup durable subs - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setSubscriptionName("durable"); - connection.send(consumerInfo); - - int numMessages = 4; - for (int i = 0; i < numMessages; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - } - - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - Message message = null; - for (int i = 0; i < numMessages; i++) { + for (int i = 0; i < numMessages; i++) { message = receiveMessage(connection); assertNotNull(message); - } + } - // one ack with last received, mimic a beforeEnd synchronization - MessageAck ack = createAck(consumerInfo, message, numMessages, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); + // one ack with last received, mimic a beforeEnd synchronization + MessageAck ack = createAck(consumerInfo, message, numMessages, MessageAck.STANDARD_ACK_TYPE); + ack.setTransactionId(txid); + connection.send(ack); + } - connection.request(createPrepareTransaction(connectionInfo, txid)); + connection.request(createPrepareTransaction(connectionInfo, txid)); - // restart the broker. - restartBroker(); + // restart the broker. + restartBroker(); - connection = createConnection(); - connectionInfo = createConnectionInfo(); - connectionInfo.setClientId("durable"); - connection.send(connectionInfo); + connection = createConnection(); + connectionInfo = createConnectionInfo(); + connection.send(connectionInfo); - // validate recovery - TransactionInfo recoverInfo = new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER); - DataArrayResponse dataArrayResponse = (DataArrayResponse)connection.request(recoverInfo); + // validate recovery + TransactionInfo recoverInfo = new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER); + DataArrayResponse dataArrayResponse = (DataArrayResponse) connection.request(recoverInfo); - assertEquals("there is a prepared tx", 1, dataArrayResponse.getData().length); - assertEquals("it matches", txid, dataArrayResponse.getData()[0]); + assertEquals("there is a prepared tx", 1, dataArrayResponse.getData().length); + assertEquals("it matches", txid, dataArrayResponse.getData()[0]); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setSubscriptionName("durable"); - connection.send(consumerInfo); + sessionInfo = createSessionInfo(connectionInfo); + connection.send(sessionInfo); + consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); - // no redelivery, exactly once semantics while prepared - message = receiveMessage(connection); - assertNull(message); - assertNoMessagesLeft(connection); + // no redelivery, exactly once semantics while prepared + message = receiveMessage(connection); + assertNull(message); + assertNoMessagesLeft(connection); - // rollback so we get redelivery - connection.request(createRollbackTransaction(connectionInfo, txid)); + // rollback so we get redelivery + connection.request(createRollbackTransaction(connectionInfo, txid)); - LOG.info("new tx for redelivery"); - txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); + LOG.info("new tx for redelivery"); + txid = createXATransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); - for (int i = 0; i < numMessages; i++) { + for (ActiveMQDestination dest : destinationList(destination)) { + // Setup the consumer and receive the message. + consumerInfo = createConsumerInfo(sessionInfo, dest); + connection.send(consumerInfo); + + for (int i = 0; i < numMessages; i++) { message = receiveMessage(connection); assertNotNull("unexpected null on:" + i, message); - } - ack = createAck(consumerInfo, message, numMessages, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); + } + MessageAck ack = createAck(consumerInfo, message, numMessages, MessageAck.STANDARD_ACK_TYPE); + ack.setTransactionId(txid); + connection.send(ack); + } - // Commit - connection.request(createCommitTransaction1Phase(connectionInfo, txid)); + // Commit + connection.request(createCommitTransaction1Phase(connectionInfo, txid)); - // validate recovery complete - dataArrayResponse = (DataArrayResponse)connection.request(recoverInfo); - assertEquals("there are no prepared tx", 0, dataArrayResponse.getData().length); - } + // validate recovery complete + dataArrayResponse = (DataArrayResponse) connection.request(recoverInfo); + assertEquals("there are no prepared tx", 0, dataArrayResponse.getData().length); + } - public void initCombosForTestTopicPersistentPreparedAcksAvailableAfterRollback() { - addCombinationValues("prioritySupport", new Boolean[]{Boolean.FALSE, Boolean.TRUE}); - } + public void testQueuePersistentPreparedAcksAvailableAfterRollbackPrefetchOne() throws Exception { - public void testTopicPersistentPreparedAcksAvailableAfterRollback() throws Exception { + ActiveMQDestination destination = createDestination(); - ActiveMQDestination destination = new ActiveMQTopic("TryTopic"); + // Setup the producer and send the message. + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - connectionInfo.setClientId("durable"); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); + int numMessages = 1; + for (int i = 0; i < numMessages; i++) { + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + connection.send(message); + } - // setup durable subs - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setSubscriptionName("durable"); - connection.send(consumerInfo); + final int messageCount = expectedMessageCount(numMessages, destination); - int numMessages = 4; - for (int i = 0; i < numMessages; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - } + // Begin the transaction. + XATransactionId txid = createXATransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); + // use consumer per destination for the composite dest case + // bc the same composite dest is used for sending so there + // will be duplicate message ids in the mix which a single + // consumer (PrefetchSubscription) cannot handle in a tx + // atm. The matching is based on messageId rather than messageId + // and destination + Set consumerInfos = new HashSet(); + for (ActiveMQDestination dest : destinationList(destination)) { + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, dest); + consumerInfo.setPrefetchSize(numMessages); + consumerInfos.add(consumerInfo); + } - Message message = null; - for (int i = 0; i < numMessages; i++) { + for (ConsumerInfo info : consumerInfos) { + connection.send(info); + } + + Message message = null; + for (ConsumerInfo info : consumerInfos) { + for (int i = 0; i < numMessages; i++) { message = receiveMessage(connection); assertNotNull(message); - } + connection.send(createAck(info, message, 1, MessageAck.DELIVERED_ACK_TYPE)); + } + MessageAck ack = createAck(info, message, numMessages, MessageAck.STANDARD_ACK_TYPE); + ack.setTransactionId(txid); + connection.send(ack); + } + connection.request(createPrepareTransaction(connectionInfo, txid)); - // one ack with last received, mimic a beforeEnd synchronization - MessageAck ack = createAck(consumerInfo, message, numMessages, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); + // reconnect + connection.send(connectionInfo.createRemoveCommand()); + connection = createConnection(); + connection.send(connectionInfo); - connection.request(createPrepareTransaction(connectionInfo, txid)); + // validate recovery + TransactionInfo recoverInfo = new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER); + DataArrayResponse dataArrayResponse = (DataArrayResponse) connection.request(recoverInfo); - // rollback so we get redelivery - connection.request(createRollbackTransaction(connectionInfo, txid)); + assertEquals("there is a prepared tx", 1, dataArrayResponse.getData().length); + assertEquals("it matches", txid, dataArrayResponse.getData()[0]); - LOG.info("new consumer/tx for redelivery"); - connection.request(closeConnectionInfo(connectionInfo)); + connection.send(sessionInfo); - connectionInfo = createConnectionInfo(); - connectionInfo.setClientId("durable"); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); + for (ConsumerInfo info : consumerInfos) { + connection.send(info); + } - // setup durable subs - consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setSubscriptionName("durable"); - connection.send(consumerInfo); + // no redelivery, exactly once semantics while prepared + message = receiveMessage(connection); + assertNull(message); + assertNoMessagesLeft(connection); - txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); + // rollback so we get redelivery + connection.request(createRollbackTransaction(connectionInfo, txid)); - for (int i = 0; i < numMessages; i++) { + LOG.info("new tx for redelivery"); + txid = createXATransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); + + for (ConsumerInfo info : consumerInfos) { + for (int i = 0; i < numMessages; i++) { message = receiveMessage(connection); assertNotNull("unexpected null on:" + i, message); - } - ack = createAck(consumerInfo, message, numMessages, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); - - // Commit - connection.request(createCommitTransaction1Phase(connectionInfo, txid)); - } - - private ActiveMQDestination[] destinationList(ActiveMQDestination dest) { - return dest.isComposite() ? dest.getCompositeDestinations() : new ActiveMQDestination[]{dest}; - } - - private int expectedMessageCount(int i, ActiveMQDestination destination) { - return i * (destination.isComposite() ? destination.getCompositeDestinations().length : 1); - } - - public void testQueuePersistentUncommittedAcksLostOnRestart() throws Exception { - - ActiveMQDestination destination = createDestination(); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - for (int i = 0; i < 4; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - } - - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - Message message = null; - for (ActiveMQDestination dest : destinationList(destination)) { - // Setup the consumer and receive the message. - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, dest); - connection.send(consumerInfo); - - for (int i = 0; i < 4; i++) { - message = receiveMessage(connection); - assertNotNull(message); - } - MessageAck ack = createAck(consumerInfo, message, 4, MessageAck.STANDARD_ACK_TYPE); + MessageAck ack = createAck(info, message, 1, MessageAck.STANDARD_ACK_TYPE); ack.setTransactionId(txid); - connection.request(ack); - } + connection.send(ack); + } + } - // Don't commit + // Commit + connection.request(createCommitTransaction1Phase(connectionInfo, txid)); - // restart the broker. - restartBroker(); + // validate recovery complete + dataArrayResponse = (DataArrayResponse) connection.request(recoverInfo); + assertEquals("there are no prepared tx", 0, dataArrayResponse.getData().length); + } - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); + public void initCombosForTestTopicPersistentPreparedAcksAvailableAfterRestartAndRollback() { + addCombinationValues("prioritySupport", new Boolean[]{Boolean.FALSE, Boolean.TRUE}); + } - for (ActiveMQDestination dest : destinationList(destination)) { - // Setup the consumer and receive the message. - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, dest); - connection.send(consumerInfo); + public void testTopicPersistentPreparedAcksAvailableAfterRestartAndRollback() throws Exception { - for (int i = 0; i < 4; i++) { - message = receiveMessage(connection); - assertNotNull(message); - } - } + ActiveMQDestination destination = new ActiveMQTopic("TryTopic"); - assertNoMessagesLeft(connection); - } + // Setup the producer and send the message. + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + connectionInfo.setClientId("durable"); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); - @Override - protected PolicyEntry getDefaultPolicy() { - PolicyEntry policyEntry = super.getDefaultPolicy(); - policyEntry.setPrioritizedMessages(prioritySupport); - return policyEntry; - } + // setup durable subs + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + consumerInfo.setSubscriptionName("durable"); + connection.send(consumerInfo); - public static Test suite() { - return suite(XARecoveryBrokerTest.class); - } + int numMessages = 4; + for (int i = 0; i < numMessages; i++) { + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + connection.send(message); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + // Begin the transaction. + XATransactionId txid = createXATransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); - protected ActiveMQDestination createDestination() { - return new ActiveMQQueue(getClass().getName() + "." + getName()); - } + Message message = null; + for (int i = 0; i < numMessages; i++) { + message = receiveMessage(connection); + assertNotNull(message); + } + + // one ack with last received, mimic a beforeEnd synchronization + MessageAck ack = createAck(consumerInfo, message, numMessages, MessageAck.STANDARD_ACK_TYPE); + ack.setTransactionId(txid); + connection.send(ack); + + connection.request(createPrepareTransaction(connectionInfo, txid)); + + // restart the broker. + restartBroker(); + + connection = createConnection(); + connectionInfo = createConnectionInfo(); + connectionInfo.setClientId("durable"); + connection.send(connectionInfo); + + // validate recovery + TransactionInfo recoverInfo = new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER); + DataArrayResponse dataArrayResponse = (DataArrayResponse) connection.request(recoverInfo); + + assertEquals("there is a prepared tx", 1, dataArrayResponse.getData().length); + assertEquals("it matches", txid, dataArrayResponse.getData()[0]); + + sessionInfo = createSessionInfo(connectionInfo); + connection.send(sessionInfo); + consumerInfo = createConsumerInfo(sessionInfo, destination); + consumerInfo.setSubscriptionName("durable"); + connection.send(consumerInfo); + + // no redelivery, exactly once semantics while prepared + message = receiveMessage(connection); + assertNull(message); + assertNoMessagesLeft(connection); + + // rollback so we get redelivery + connection.request(createRollbackTransaction(connectionInfo, txid)); + + LOG.info("new tx for redelivery"); + txid = createXATransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); + + for (int i = 0; i < numMessages; i++) { + message = receiveMessage(connection); + assertNotNull("unexpected null on:" + i, message); + } + ack = createAck(consumerInfo, message, numMessages, MessageAck.STANDARD_ACK_TYPE); + ack.setTransactionId(txid); + connection.send(ack); + + // Commit + connection.request(createCommitTransaction1Phase(connectionInfo, txid)); + + // validate recovery complete + dataArrayResponse = (DataArrayResponse) connection.request(recoverInfo); + assertEquals("there are no prepared tx", 0, dataArrayResponse.getData().length); + } + + public void initCombosForTestTopicPersistentPreparedAcksAvailableAfterRollback() { + addCombinationValues("prioritySupport", new Boolean[]{Boolean.FALSE, Boolean.TRUE}); + } + + public void testTopicPersistentPreparedAcksAvailableAfterRollback() throws Exception { + + ActiveMQDestination destination = new ActiveMQTopic("TryTopic"); + + // Setup the producer and send the message. + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + connectionInfo.setClientId("durable"); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); + + // setup durable subs + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + consumerInfo.setSubscriptionName("durable"); + connection.send(consumerInfo); + + int numMessages = 4; + for (int i = 0; i < numMessages; i++) { + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + connection.send(message); + } + + // Begin the transaction. + XATransactionId txid = createXATransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); + + Message message = null; + for (int i = 0; i < numMessages; i++) { + message = receiveMessage(connection); + assertNotNull(message); + } + + // one ack with last received, mimic a beforeEnd synchronization + MessageAck ack = createAck(consumerInfo, message, numMessages, MessageAck.STANDARD_ACK_TYPE); + ack.setTransactionId(txid); + connection.send(ack); + + connection.request(createPrepareTransaction(connectionInfo, txid)); + + // rollback so we get redelivery + connection.request(createRollbackTransaction(connectionInfo, txid)); + + LOG.info("new consumer/tx for redelivery"); + connection.request(closeConnectionInfo(connectionInfo)); + + connectionInfo = createConnectionInfo(); + connectionInfo.setClientId("durable"); + sessionInfo = createSessionInfo(connectionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + + // setup durable subs + consumerInfo = createConsumerInfo(sessionInfo, destination); + consumerInfo.setSubscriptionName("durable"); + connection.send(consumerInfo); + + txid = createXATransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); + + for (int i = 0; i < numMessages; i++) { + message = receiveMessage(connection); + assertNotNull("unexpected null on:" + i, message); + } + ack = createAck(consumerInfo, message, numMessages, MessageAck.STANDARD_ACK_TYPE); + ack.setTransactionId(txid); + connection.send(ack); + + // Commit + connection.request(createCommitTransaction1Phase(connectionInfo, txid)); + } + + private ActiveMQDestination[] destinationList(ActiveMQDestination dest) { + return dest.isComposite() ? dest.getCompositeDestinations() : new ActiveMQDestination[]{dest}; + } + + private int expectedMessageCount(int i, ActiveMQDestination destination) { + return i * (destination.isComposite() ? destination.getCompositeDestinations().length : 1); + } + + public void testQueuePersistentUncommittedAcksLostOnRestart() throws Exception { + + ActiveMQDestination destination = createDestination(); + + // Setup the producer and send the message. + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); + + for (int i = 0; i < 4; i++) { + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + connection.send(message); + } + + // Begin the transaction. + XATransactionId txid = createXATransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); + + Message message = null; + for (ActiveMQDestination dest : destinationList(destination)) { + // Setup the consumer and receive the message. + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, dest); + connection.send(consumerInfo); + + for (int i = 0; i < 4; i++) { + message = receiveMessage(connection); + assertNotNull(message); + } + MessageAck ack = createAck(consumerInfo, message, 4, MessageAck.STANDARD_ACK_TYPE); + ack.setTransactionId(txid); + connection.request(ack); + } + + // Don't commit + + // restart the broker. + restartBroker(); + + // Setup the consumer and receive the message. + connection = createConnection(); + connectionInfo = createConnectionInfo(); + sessionInfo = createSessionInfo(connectionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + + for (ActiveMQDestination dest : destinationList(destination)) { + // Setup the consumer and receive the message. + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, dest); + connection.send(consumerInfo); + + for (int i = 0; i < 4; i++) { + message = receiveMessage(connection); + assertNotNull(message); + } + } + + assertNoMessagesLeft(connection); + } + + @Override + protected PolicyEntry getDefaultPolicy() { + PolicyEntry policyEntry = super.getDefaultPolicy(); + policyEntry.setPrioritizedMessages(prioritySupport); + return policyEntry; + } + + public static Test suite() { + return suite(XARecoveryBrokerTest.class); + } + + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } + + protected ActiveMQDestination createDestination() { + return new ActiveMQQueue(getClass().getName() + "." + getName()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryBrokerTest.java index c65dc53931..b82503cd48 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryBrokerTest.java @@ -31,300 +31,299 @@ import org.apache.activemq.command.RemoveInfo; import org.apache.activemq.command.SessionInfo; public class AdvisoryBrokerTest extends BrokerTestSupport { - - public void testConnectionAdvisories() throws Exception { - - ActiveMQDestination destination = AdvisorySupport.getConnectionAdvisoryTopic(); - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(100); - - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(consumerInfo1); - // We should get an advisory of our own connection. - Message m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - assertEquals(((ConnectionInfo)m1.getDataStructure()).getConnectionId(), connectionInfo1.getConnectionId()); + public void testConnectionAdvisories() throws Exception { - // Setup a second connection - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - connection2.send(connectionInfo2); - - // We should get an advisory of the second connection. - m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - assertEquals(((ConnectionInfo)m1.getDataStructure()).getConnectionId(), connectionInfo2.getConnectionId()); + ActiveMQDestination destination = AdvisorySupport.getConnectionAdvisoryTopic(); - // Close the second connection. - connection2.send(closeConnectionInfo(connectionInfo2)); - connection2.stop(); + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + consumerInfo1.setPrefetchSize(100); - // We should get an advisory of the second connection closing - m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - RemoveInfo r = (RemoveInfo) m1.getDataStructure(); - assertEquals(r.getObjectId(), connectionInfo2.getConnectionId()); - - assertNoMessagesLeft(connection1); - } + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(consumerInfo1); - public void testConsumerAdvisories() throws Exception { + // We should get an advisory of our own connection. + Message m1 = receiveMessage(connection1); + assertNotNull(m1); + assertNotNull(m1.getDataStructure()); + assertEquals(((ConnectionInfo) m1.getDataStructure()).getConnectionId(), connectionInfo1.getConnectionId()); - ActiveMQDestination queue = new ActiveMQQueue("test"); - ActiveMQDestination destination = AdvisorySupport.getConsumerAdvisoryTopic(queue); - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(100); - - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(consumerInfo1); + // Setup a second connection + StubConnection connection2 = createConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + connection2.send(connectionInfo2); - // We should not see and advisory for the advisory consumer. - assertNoMessagesLeft(connection1); + // We should get an advisory of the second connection. + m1 = receiveMessage(connection1); + assertNotNull(m1); + assertNotNull(m1.getDataStructure()); + assertEquals(((ConnectionInfo) m1.getDataStructure()).getConnectionId(), connectionInfo2.getConnectionId()); - // Setup a second consumer. - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, queue); - consumerInfo1.setPrefetchSize(100); - - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.send(consumerInfo2); - - // We should get an advisory of the new consumer. - Message m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - assertEquals(((ConsumerInfo)m1.getDataStructure()).getConsumerId(), consumerInfo2.getConsumerId()); + // Close the second connection. + connection2.send(closeConnectionInfo(connectionInfo2)); + connection2.stop(); - // Close the second connection. - connection2.request(closeConnectionInfo(connectionInfo2)); - connection2.stop(); + // We should get an advisory of the second connection closing + m1 = receiveMessage(connection1); + assertNotNull(m1); + assertNotNull(m1.getDataStructure()); + RemoveInfo r = (RemoveInfo) m1.getDataStructure(); + assertEquals(r.getObjectId(), connectionInfo2.getConnectionId()); - // We should get an advisory of the consumer closing - m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - RemoveInfo r = (RemoveInfo) m1.getDataStructure(); - assertEquals(r.getObjectId(), consumerInfo2.getConsumerId()); - - assertNoMessagesLeft(connection2); - } + assertNoMessagesLeft(connection1); + } - public void testConsumerAdvisoriesReplayed() throws Exception { + public void testConsumerAdvisories() throws Exception { - ActiveMQDestination queue = new ActiveMQQueue("test"); - ActiveMQDestination destination = AdvisorySupport.getConsumerAdvisoryTopic(queue); - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); + ActiveMQDestination queue = new ActiveMQQueue("test"); + ActiveMQDestination destination = AdvisorySupport.getConsumerAdvisoryTopic(queue); - // Setup a second consumer. - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, queue); - consumerInfo2.setPrefetchSize(100); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.send(consumerInfo2); - - // We should get an advisory of the previous consumer. - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(100); - connection1.send(consumerInfo1); + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + consumerInfo1.setPrefetchSize(100); - Message m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - assertEquals(((ConsumerInfo)m1.getDataStructure()).getConsumerId(), consumerInfo2.getConsumerId()); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(consumerInfo1); - // Close the second connection. - connection2.request(closeConnectionInfo(connectionInfo2)); - connection2.stop(); + // We should not see and advisory for the advisory consumer. + assertNoMessagesLeft(connection1); - // We should get an advisory of the consumer closing - m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - RemoveInfo r = (RemoveInfo) m1.getDataStructure(); - assertEquals(r.getObjectId(), consumerInfo2.getConsumerId()); - - assertNoMessagesLeft(connection2); - } + // Setup a second consumer. + StubConnection connection2 = createConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, queue); + consumerInfo1.setPrefetchSize(100); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + connection2.send(consumerInfo2); - public void testProducerAdvisories() throws Exception { + // We should get an advisory of the new consumer. + Message m1 = receiveMessage(connection1); + assertNotNull(m1); + assertNotNull(m1.getDataStructure()); + assertEquals(((ConsumerInfo) m1.getDataStructure()).getConsumerId(), consumerInfo2.getConsumerId()); - ActiveMQDestination queue = new ActiveMQQueue("test"); - ActiveMQDestination destination = AdvisorySupport.getProducerAdvisoryTopic(queue); - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(100); - - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(consumerInfo1); + // Close the second connection. + connection2.request(closeConnectionInfo(connectionInfo2)); + connection2.stop(); - assertNoMessagesLeft(connection1); + // We should get an advisory of the consumer closing + m1 = receiveMessage(connection1); + assertNotNull(m1); + assertNotNull(m1.getDataStructure()); + RemoveInfo r = (RemoveInfo) m1.getDataStructure(); + assertEquals(r.getObjectId(), consumerInfo2.getConsumerId()); - // Setup a producer. - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); - producerInfo2.setDestination(queue); - - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.send(producerInfo2); - - // We should get an advisory of the new produver. - Message m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - assertEquals(((ProducerInfo)m1.getDataStructure()).getProducerId(), producerInfo2.getProducerId()); + assertNoMessagesLeft(connection2); + } - // Close the second connection. - connection2.request(closeConnectionInfo(connectionInfo2)); - connection2.stop(); + public void testConsumerAdvisoriesReplayed() throws Exception { - // We should get an advisory of the producer closing - m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - RemoveInfo r = (RemoveInfo) m1.getDataStructure(); - assertEquals(r.getObjectId(), producerInfo2.getProducerId()); - - assertNoMessagesLeft(connection2); - } - - public void testProducerAdvisoriesReplayed() throws Exception { + ActiveMQDestination queue = new ActiveMQQueue("test"); + ActiveMQDestination destination = AdvisorySupport.getConsumerAdvisoryTopic(queue); - ActiveMQDestination queue = new ActiveMQQueue("test"); - ActiveMQDestination destination = AdvisorySupport.getProducerAdvisoryTopic(queue); - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - // Setup a producer. - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); - producerInfo2.setDestination(queue); - - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.send(producerInfo2); - - // Create the advisory consumer.. it should see the previous producer - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(100); - connection1.send(consumerInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); - Message m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - assertEquals(((ProducerInfo)m1.getDataStructure()).getProducerId(), producerInfo2.getProducerId()); + // Setup a second consumer. + StubConnection connection2 = createConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, queue); + consumerInfo2.setPrefetchSize(100); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + connection2.send(consumerInfo2); - // Close the second connection. - connection2.request(closeConnectionInfo(connectionInfo2)); - connection2.stop(); + // We should get an advisory of the previous consumer. + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + consumerInfo1.setPrefetchSize(100); + connection1.send(consumerInfo1); - // We should get an advisory of the producer closing - m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - RemoveInfo r = (RemoveInfo) m1.getDataStructure(); - assertEquals(r.getObjectId(), producerInfo2.getProducerId()); - - assertNoMessagesLeft(connection2); - } + Message m1 = receiveMessage(connection1); + assertNotNull(m1); + assertNotNull(m1.getDataStructure()); + assertEquals(((ConsumerInfo) m1.getDataStructure()).getConsumerId(), consumerInfo2.getConsumerId()); - public void testProducerAdvisoriesReplayedOnlyTargetNewConsumer() throws Exception { + // Close the second connection. + connection2.request(closeConnectionInfo(connectionInfo2)); + connection2.stop(); - ActiveMQDestination queue = new ActiveMQQueue("test"); - ActiveMQDestination destination = AdvisorySupport.getProducerAdvisoryTopic(queue); - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - // Create the first consumer.. - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(100); - connection1.send(consumerInfo1); + // We should get an advisory of the consumer closing + m1 = receiveMessage(connection1); + assertNotNull(m1); + assertNotNull(m1.getDataStructure()); + RemoveInfo r = (RemoveInfo) m1.getDataStructure(); + assertEquals(r.getObjectId(), consumerInfo2.getConsumerId()); - // Setup a producer. - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); - producerInfo2.setDestination(queue); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.send(producerInfo2); - - Message m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - assertEquals(((ProducerInfo)m1.getDataStructure()).getProducerId(), producerInfo2.getProducerId()); - - // Create the 2nd consumer.. - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); - consumerInfo2.setPrefetchSize(100); - connection2.send(consumerInfo2); + assertNoMessagesLeft(connection2); + } - // The second consumer should se a replay - m1 = receiveMessage(connection2); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - assertEquals(((ProducerInfo)m1.getDataStructure()).getProducerId(), producerInfo2.getProducerId()); + public void testProducerAdvisories() throws Exception { - // But the first consumer should not see the replay. - assertNoMessagesLeft(connection1); - } + ActiveMQDestination queue = new ActiveMQQueue("test"); + ActiveMQDestination destination = AdvisorySupport.getProducerAdvisoryTopic(queue); - public static Test suite() { - return suite(AdvisoryBrokerTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + consumerInfo1.setPrefetchSize(100); + + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(consumerInfo1); + + assertNoMessagesLeft(connection1); + + // Setup a producer. + StubConnection connection2 = createConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); + producerInfo2.setDestination(queue); + + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + connection2.send(producerInfo2); + + // We should get an advisory of the new produver. + Message m1 = receiveMessage(connection1); + assertNotNull(m1); + assertNotNull(m1.getDataStructure()); + assertEquals(((ProducerInfo) m1.getDataStructure()).getProducerId(), producerInfo2.getProducerId()); + + // Close the second connection. + connection2.request(closeConnectionInfo(connectionInfo2)); + connection2.stop(); + + // We should get an advisory of the producer closing + m1 = receiveMessage(connection1); + assertNotNull(m1); + assertNotNull(m1.getDataStructure()); + RemoveInfo r = (RemoveInfo) m1.getDataStructure(); + assertEquals(r.getObjectId(), producerInfo2.getProducerId()); + + assertNoMessagesLeft(connection2); + } + + public void testProducerAdvisoriesReplayed() throws Exception { + + ActiveMQDestination queue = new ActiveMQQueue("test"); + ActiveMQDestination destination = AdvisorySupport.getProducerAdvisoryTopic(queue); + + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + + // Setup a producer. + StubConnection connection2 = createConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); + producerInfo2.setDestination(queue); + + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + connection2.send(producerInfo2); + + // Create the advisory consumer.. it should see the previous producer + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + consumerInfo1.setPrefetchSize(100); + connection1.send(consumerInfo1); + + Message m1 = receiveMessage(connection1); + assertNotNull(m1); + assertNotNull(m1.getDataStructure()); + assertEquals(((ProducerInfo) m1.getDataStructure()).getProducerId(), producerInfo2.getProducerId()); + + // Close the second connection. + connection2.request(closeConnectionInfo(connectionInfo2)); + connection2.stop(); + + // We should get an advisory of the producer closing + m1 = receiveMessage(connection1); + assertNotNull(m1); + assertNotNull(m1.getDataStructure()); + RemoveInfo r = (RemoveInfo) m1.getDataStructure(); + assertEquals(r.getObjectId(), producerInfo2.getProducerId()); + + assertNoMessagesLeft(connection2); + } + + public void testProducerAdvisoriesReplayedOnlyTargetNewConsumer() throws Exception { + + ActiveMQDestination queue = new ActiveMQQueue("test"); + ActiveMQDestination destination = AdvisorySupport.getProducerAdvisoryTopic(queue); + + // Setup a first connection + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + // Create the first consumer.. + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + consumerInfo1.setPrefetchSize(100); + connection1.send(consumerInfo1); + + // Setup a producer. + StubConnection connection2 = createConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); + producerInfo2.setDestination(queue); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + connection2.send(producerInfo2); + + Message m1 = receiveMessage(connection1); + assertNotNull(m1); + assertNotNull(m1.getDataStructure()); + assertEquals(((ProducerInfo) m1.getDataStructure()).getProducerId(), producerInfo2.getProducerId()); + + // Create the 2nd consumer.. + ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); + consumerInfo2.setPrefetchSize(100); + connection2.send(consumerInfo2); + + // The second consumer should se a replay + m1 = receiveMessage(connection2); + assertNotNull(m1); + assertNotNull(m1.getDataStructure()); + assertEquals(((ProducerInfo) m1.getDataStructure()).getProducerId(), producerInfo2.getProducerId()); + + // But the first consumer should not see the replay. + assertNoMessagesLeft(connection1); + } + + public static Test suite() { + return suite(AdvisoryBrokerTest.class); + } + + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryDuplexNetworkBridgeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryDuplexNetworkBridgeTest.java index e791fbed76..0c7c2e8051 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryDuplexNetworkBridgeTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryDuplexNetworkBridgeTest.java @@ -23,25 +23,25 @@ import java.net.URI; public class AdvisoryDuplexNetworkBridgeTest extends AdvisoryNetworkBridgeTest { - @Override - public void createBroker1() throws Exception { - broker1 = new BrokerService(); - broker1.setBrokerName("broker1"); - broker1.addConnector("tcp://localhost:61617"); - broker1.setUseJmx(false); - broker1.setPersistent(false); - broker1.start(); - broker1.waitUntilStarted(); - } + @Override + public void createBroker1() throws Exception { + broker1 = new BrokerService(); + broker1.setBrokerName("broker1"); + broker1.addConnector("tcp://localhost:61617"); + broker1.setUseJmx(false); + broker1.setPersistent(false); + broker1.start(); + broker1.waitUntilStarted(); + } - @Override - public void createBroker2() throws Exception { - broker2 = BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/network/duplexLocalBroker.xml")); - broker2.start(); - broker2.waitUntilStarted(); - } + @Override + public void createBroker2() throws Exception { + broker2 = BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/network/duplexLocalBroker.xml")); + broker2.start(); + broker2.waitUntilStarted(); + } - public void assertCreatedByDuplex(boolean createdByDuplex) { - assertTrue(createdByDuplex); - } + public void assertCreatedByDuplex(boolean createdByDuplex) { + assertTrue(createdByDuplex); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryJmxTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryJmxTest.java index d452bed3aa..0e17f70bfe 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryJmxTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryJmxTest.java @@ -33,54 +33,52 @@ import javax.management.remote.JMXServiceURL; public class AdvisoryJmxTest extends EmbeddedBrokerTestSupport { - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setPersistent(isPersistent()); - answer.addConnector(bindAddress); - ManagementContext context = new ManagementContext(); - context.setConnectorPort(1199); - answer.setManagementContext(context); - return answer; - } + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + answer.setPersistent(isPersistent()); + answer.addConnector(bindAddress); + ManagementContext context = new ManagementContext(); + context.setConnectorPort(1199); + answer.setManagementContext(context); + return answer; + } - public void testCreateDeleteDestinations() throws Exception { - JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1199/jmxrmi"); - JMXConnector connector = JMXConnectorFactory.connect(url, null); - connector.connect(); - MBeanServerConnection connection = connector.getMBeanServerConnection(); - ObjectName name = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost"); - BrokerViewMBean brokerMbean = (BrokerViewMBean) MBeanServerInvocationHandler.newProxyInstance(connection, name, BrokerViewMBean.class, true); - Connection conn = createConnection(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = sess.createConsumer(sess.createTopic("ActiveMQ.Advisory.Queue")); - conn.start(); - Destination dest = sess.createQueue("test"); + public void testCreateDeleteDestinations() throws Exception { + JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1199/jmxrmi"); + JMXConnector connector = JMXConnectorFactory.connect(url, null); + connector.connect(); + MBeanServerConnection connection = connector.getMBeanServerConnection(); + ObjectName name = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost"); + BrokerViewMBean brokerMbean = (BrokerViewMBean) MBeanServerInvocationHandler.newProxyInstance(connection, name, BrokerViewMBean.class, true); + Connection conn = createConnection(); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = sess.createConsumer(sess.createTopic("ActiveMQ.Advisory.Queue")); + conn.start(); + Destination dest = sess.createQueue("test"); - brokerMbean.addQueue("test"); + brokerMbean.addQueue("test"); - ActiveMQMessage msg = (ActiveMQMessage)consumer.receive(1000); - assertNotNull(msg); - assertTrue(msg.getDataStructure() instanceof DestinationInfo); - assertEquals(((DestinationInfo)msg.getDataStructure()).getDestination(), dest); - assertEquals(((DestinationInfo)msg.getDataStructure()).getOperationType(), 0); + ActiveMQMessage msg = (ActiveMQMessage) consumer.receive(1000); + assertNotNull(msg); + assertTrue(msg.getDataStructure() instanceof DestinationInfo); + assertEquals(((DestinationInfo) msg.getDataStructure()).getDestination(), dest); + assertEquals(((DestinationInfo) msg.getDataStructure()).getOperationType(), 0); - brokerMbean.removeQueue("test"); + brokerMbean.removeQueue("test"); - msg = (ActiveMQMessage)consumer.receive(1000); - assertNotNull(msg); - assertTrue(msg.getDataStructure() instanceof DestinationInfo); - assertEquals(((DestinationInfo)msg.getDataStructure()).getDestination(), dest); - assertEquals(((DestinationInfo)msg.getDataStructure()).getOperationType(), 1); - - - brokerMbean.addQueue("test"); - msg = (ActiveMQMessage)consumer.receive(1000); - assertNotNull(msg); - assertTrue(msg.getDataStructure() instanceof DestinationInfo); - assertEquals(((DestinationInfo)msg.getDataStructure()).getDestination(), dest); - assertEquals(((DestinationInfo)msg.getDataStructure()).getOperationType(), 0); - assertEquals(((DestinationInfo)msg.getDataStructure()).getOperationType(), 0); - } + msg = (ActiveMQMessage) consumer.receive(1000); + assertNotNull(msg); + assertTrue(msg.getDataStructure() instanceof DestinationInfo); + assertEquals(((DestinationInfo) msg.getDataStructure()).getDestination(), dest); + assertEquals(((DestinationInfo) msg.getDataStructure()).getOperationType(), 1); + brokerMbean.addQueue("test"); + msg = (ActiveMQMessage) consumer.receive(1000); + assertNotNull(msg); + assertTrue(msg.getDataStructure() instanceof DestinationInfo); + assertEquals(((DestinationInfo) msg.getDataStructure()).getDestination(), dest); + assertEquals(((DestinationInfo) msg.getDataStructure()).getOperationType(), 0); + assertEquals(((DestinationInfo) msg.getDataStructure()).getOperationType(), 0); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryNetworkBridgeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryNetworkBridgeTest.java index da9cc6d053..2e9601485f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryNetworkBridgeTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryNetworkBridgeTest.java @@ -17,6 +17,7 @@ package org.apache.activemq.broker.advisory; import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.advisory.AdvisorySupport; import org.apache.activemq.broker.BrokerFactory; @@ -31,98 +32,96 @@ import java.net.URI; public class AdvisoryNetworkBridgeTest extends TestCase { - BrokerService broker1; - BrokerService broker2; + BrokerService broker1; + BrokerService broker2; + public void testAdvisory() throws Exception { + createBroker1(); - public void testAdvisory() throws Exception { - createBroker1(); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://broker1"); + Connection conn = factory.createConnection(); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + conn.start(); + MessageConsumer consumer = sess.createConsumer(AdvisorySupport.getNetworkBridgeAdvisoryTopic()); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://broker1"); - Connection conn = factory.createConnection(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); - MessageConsumer consumer = sess.createConsumer(AdvisorySupport.getNetworkBridgeAdvisoryTopic()); - - Thread.sleep(1000); + Thread.sleep(1000); - createBroker2(); - - ActiveMQMessage advisory = (ActiveMQMessage)consumer.receive(2000); - assertNotNull(advisory); - assertTrue(advisory.getDataStructure() instanceof BrokerInfo); - assertTrue(advisory.getBooleanProperty("started")); - assertCreatedByDuplex(advisory.getBooleanProperty("createdByDuplex")); - - broker2.stop(); - broker2.waitUntilStopped(); + createBroker2(); - advisory = (ActiveMQMessage)consumer.receive(2000); - assertNotNull(advisory); - assertTrue(advisory.getDataStructure() instanceof BrokerInfo); - assertFalse(advisory.getBooleanProperty("started")); + ActiveMQMessage advisory = (ActiveMQMessage) consumer.receive(2000); + assertNotNull(advisory); + assertTrue(advisory.getDataStructure() instanceof BrokerInfo); + assertTrue(advisory.getBooleanProperty("started")); + assertCreatedByDuplex(advisory.getBooleanProperty("createdByDuplex")); - conn.close(); - } + broker2.stop(); + broker2.waitUntilStopped(); - public void testAddConsumerLater() throws Exception { - createBroker1(); + advisory = (ActiveMQMessage) consumer.receive(2000); + assertNotNull(advisory); + assertTrue(advisory.getDataStructure() instanceof BrokerInfo); + assertFalse(advisory.getBooleanProperty("started")); - createBroker2(); + conn.close(); + } - Thread.sleep(1000); + public void testAddConsumerLater() throws Exception { + createBroker1(); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://broker1"); - Connection conn = factory.createConnection(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); - MessageConsumer consumer = sess.createConsumer(AdvisorySupport.getNetworkBridgeAdvisoryTopic()); + createBroker2(); - ActiveMQMessage advisory = (ActiveMQMessage)consumer.receive(2000); - assertNotNull(advisory); - assertTrue(advisory.getDataStructure() instanceof BrokerInfo); - assertTrue(advisory.getBooleanProperty("started")); - assertCreatedByDuplex(advisory.getBooleanProperty("createdByDuplex")); + Thread.sleep(1000); - broker2.stop(); - broker2.waitUntilStopped(); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://broker1"); + Connection conn = factory.createConnection(); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + conn.start(); + MessageConsumer consumer = sess.createConsumer(AdvisorySupport.getNetworkBridgeAdvisoryTopic()); - advisory = (ActiveMQMessage)consumer.receive(2000); - assertNotNull(advisory); - assertTrue(advisory.getDataStructure() instanceof BrokerInfo); - assertFalse(advisory.getBooleanProperty("started")); + ActiveMQMessage advisory = (ActiveMQMessage) consumer.receive(2000); + assertNotNull(advisory); + assertTrue(advisory.getDataStructure() instanceof BrokerInfo); + assertTrue(advisory.getBooleanProperty("started")); + assertCreatedByDuplex(advisory.getBooleanProperty("createdByDuplex")); - consumer = sess.createConsumer(AdvisorySupport.getNetworkBridgeAdvisoryTopic()); - advisory = (ActiveMQMessage)consumer.receive(1000); - assertNull(advisory); + broker2.stop(); + broker2.waitUntilStopped(); - conn.close(); + advisory = (ActiveMQMessage) consumer.receive(2000); + assertNotNull(advisory); + assertTrue(advisory.getDataStructure() instanceof BrokerInfo); + assertFalse(advisory.getBooleanProperty("started")); - } + consumer = sess.createConsumer(AdvisorySupport.getNetworkBridgeAdvisoryTopic()); + advisory = (ActiveMQMessage) consumer.receive(1000); + assertNull(advisory); - public void assertCreatedByDuplex(boolean createdByDuplex) { - assertFalse(createdByDuplex); - } + conn.close(); - public void createBroker1() throws Exception { - broker1 = BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/network/reconnect-broker1.xml")); - broker1.start(); - broker1.waitUntilStarted(); - } + } - public void createBroker2() throws Exception { - broker2 = BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/network/reconnect-broker2.xml")); - broker2.start(); - broker2.waitUntilStarted(); - } + public void assertCreatedByDuplex(boolean createdByDuplex) { + assertFalse(createdByDuplex); + } + public void createBroker1() throws Exception { + broker1 = BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/network/reconnect-broker1.xml")); + broker1.start(); + broker1.waitUntilStarted(); + } - @Override - protected void tearDown() throws Exception { - broker1.stop(); - broker1.waitUntilStopped(); + public void createBroker2() throws Exception { + broker2 = BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/network/reconnect-broker2.xml")); + broker2.start(); + broker2.waitUntilStarted(); + } - broker2.stop(); - broker2.waitUntilStopped(); - } + @Override + protected void tearDown() throws Exception { + broker1.stop(); + broker1.waitUntilStopped(); + + broker2.stop(); + broker2.waitUntilStopped(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueMasterSlaveLeaseQuiesceTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueMasterSlaveLeaseQuiesceTest.java index e71cfe6d0d..280705e42c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueMasterSlaveLeaseQuiesceTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueMasterSlaveLeaseQuiesceTest.java @@ -17,6 +17,7 @@ package org.apache.activemq.broker.ft; import java.util.concurrent.TimeUnit; + import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.util.LeaseLockerIOExceptionHandler; @@ -24,57 +25,62 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DbRestartJDBCQueueMasterSlaveLeaseQuiesceTest extends DbRestartJDBCQueueMasterSlaveLeaseTest { - private static final transient Logger LOG = LoggerFactory.getLogger(DbRestartJDBCQueueMasterSlaveLeaseQuiesceTest.class); - private long restartDelay = 2000; + private static final transient Logger LOG = LoggerFactory.getLogger(DbRestartJDBCQueueMasterSlaveLeaseQuiesceTest.class); - @Override - protected void configureBroker(BrokerService brokerService) { - // master and slave survive db restart and retain master/slave status - LeaseLockerIOExceptionHandler stopConnectors = new LeaseLockerIOExceptionHandler(); - brokerService.setIoExceptionHandler(stopConnectors); - } + private long restartDelay = 2000; - @Override - protected void delayTillRestartRequired() { - if (restartDelay > 2000) { - LOG.info("delay for more than lease quantum. While Db is offline, master should stay alive but could loose lease"); - } else { - LOG.info("delay for less than lease quantum. While Db is offline, master should stay alive"); - } - try { - TimeUnit.MILLISECONDS.sleep(restartDelay); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } + @Override + protected void configureBroker(BrokerService brokerService) { + // master and slave survive db restart and retain master/slave status + LeaseLockerIOExceptionHandler stopConnectors = new LeaseLockerIOExceptionHandler(); + brokerService.setIoExceptionHandler(stopConnectors); + } - @Override - protected void verifyExpectedBroker(int inflightMessageCount) { - if (inflightMessageCount == 0 || (inflightMessageCount == failureCount + 10 && restartDelay <= 500)) { - assertEquals("connected to master", master.getBrokerName(), ((ActiveMQConnection)sendConnection).getBrokerName()); - } else { - // lease expired while DB was offline, either or master/slave can grab it so assert is not deterministic - // but we still need to validate sent == received - } - } + @Override + protected void delayTillRestartRequired() { + if (restartDelay > 2000) { + LOG.info("delay for more than lease quantum. While Db is offline, master should stay alive but could loose lease"); + } + else { + LOG.info("delay for less than lease quantum. While Db is offline, master should stay alive"); + } + try { + TimeUnit.MILLISECONDS.sleep(restartDelay); + } + catch (InterruptedException e) { + e.printStackTrace(); + } + } - @Override - public void setUp() throws Exception { - restartDelay = 2000; - super.setUp(); - } + @Override + protected void verifyExpectedBroker(int inflightMessageCount) { + if (inflightMessageCount == 0 || (inflightMessageCount == failureCount + 10 && restartDelay <= 500)) { + assertEquals("connected to master", master.getBrokerName(), ((ActiveMQConnection) sendConnection).getBrokerName()); + } + else { + // lease expired while DB was offline, either or master/slave can grab it so assert is not deterministic + // but we still need to validate sent == received + } + } - public void testSendReceiveWithLeaseExpiry() throws Exception { - restartDelay = 10000; - testSendReceive(); - } + @Override + public void setUp() throws Exception { + restartDelay = 2000; + super.setUp(); + } - // ignore this test case - public void testAdvisory() throws Exception {} + public void testSendReceiveWithLeaseExpiry() throws Exception { + restartDelay = 10000; + testSendReceive(); + } + + // ignore this test case + public void testAdvisory() throws Exception { + } @Override public void testSendReceive() throws Exception { - // Ignore this test for now, see AMQ-4975 + // Ignore this test for now, see AMQ-4975 } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueMasterSlaveLeaseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueMasterSlaveLeaseTest.java index 422b5ffe44..e46daa305b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueMasterSlaveLeaseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueMasterSlaveLeaseTest.java @@ -26,32 +26,33 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DbRestartJDBCQueueMasterSlaveLeaseTest extends DbRestartJDBCQueueMasterSlaveTest { - private static final transient Logger LOG = LoggerFactory.getLogger(DbRestartJDBCQueueMasterSlaveLeaseTest.class); - @Override - protected void configureJdbcPersistenceAdapter(JDBCPersistenceAdapter persistenceAdapter) throws IOException { - super.configureJdbcPersistenceAdapter(persistenceAdapter); - persistenceAdapter.setLocker(new LeaseDatabaseLocker()); - persistenceAdapter.getLocker().setLockAcquireSleepInterval(getLockAcquireSleepInterval()); - persistenceAdapter.setLockKeepAlivePeriod(getLockKeepAlivePeriod()); - } + private static final transient Logger LOG = LoggerFactory.getLogger(DbRestartJDBCQueueMasterSlaveLeaseTest.class); - @Override - protected void configureBroker(BrokerService brokerService) { - //let the brokers die on exception and master should have lease on restart - // which will delay slave start till it expires - LeaseLockerIOExceptionHandler ioExceptionHandler = new LeaseLockerIOExceptionHandler(); - ioExceptionHandler.setIgnoreSQLExceptions(false); - ioExceptionHandler.setStopStartConnectors(false); - ioExceptionHandler.setResumeCheckSleepPeriod(500L); - brokerService.setIoExceptionHandler(ioExceptionHandler); - } + @Override + protected void configureJdbcPersistenceAdapter(JDBCPersistenceAdapter persistenceAdapter) throws IOException { + super.configureJdbcPersistenceAdapter(persistenceAdapter); + persistenceAdapter.setLocker(new LeaseDatabaseLocker()); + persistenceAdapter.getLocker().setLockAcquireSleepInterval(getLockAcquireSleepInterval()); + persistenceAdapter.setLockKeepAlivePeriod(getLockKeepAlivePeriod()); + } - private long getLockKeepAlivePeriod() { - return 1000; - } + @Override + protected void configureBroker(BrokerService brokerService) { + //let the brokers die on exception and master should have lease on restart + // which will delay slave start till it expires + LeaseLockerIOExceptionHandler ioExceptionHandler = new LeaseLockerIOExceptionHandler(); + ioExceptionHandler.setIgnoreSQLExceptions(false); + ioExceptionHandler.setStopStartConnectors(false); + ioExceptionHandler.setResumeCheckSleepPeriod(500L); + brokerService.setIoExceptionHandler(ioExceptionHandler); + } - private long getLockAcquireSleepInterval() { - return 8000; - } + private long getLockKeepAlivePeriod() { + return 1000; + } + + private long getLockAcquireSleepInterval() { + return 8000; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueMasterSlaveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueMasterSlaveTest.java index fb04803128..d30ea815eb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueMasterSlaveTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueMasterSlaveTest.java @@ -27,6 +27,7 @@ import javax.jms.Message; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TransactionRolledBackException; + import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.command.ActiveMQMessage; @@ -37,113 +38,122 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DbRestartJDBCQueueMasterSlaveTest extends JDBCQueueMasterSlaveTest { - private static final transient Logger LOG = LoggerFactory.getLogger(DbRestartJDBCQueueMasterSlaveTest.class); - - protected void messageSent() throws Exception { - verifyExpectedBroker(inflightMessageCount); - if (++inflightMessageCount == failureCount) { - LOG.info("STOPPING DB!@!!!!"); - final EmbeddedDataSource ds = ((SyncCreateDataSource)getExistingDataSource()).getDelegate(); - ds.setShutdownDatabase("shutdown"); - LOG.info("DB STOPPED!@!!!!"); - - Thread dbRestartThread = new Thread("db-re-start-thread") { - public void run() { - delayTillRestartRequired(); - ds.setShutdownDatabase("false"); - LOG.info("DB RESTARTED!@!!!!"); - } - }; - dbRestartThread.start(); - } - verifyExpectedBroker(inflightMessageCount); - } - protected void verifyExpectedBroker(int inflightMessageCount) { - if (inflightMessageCount == 0) { - assertEquals("connected to master", master.getBrokerName(), ((ActiveMQConnection)sendConnection).getBrokerName()); - } else if (inflightMessageCount == failureCount + 10) { - assertEquals("connected to slave, count:" + inflightMessageCount, slave.get().getBrokerName(), ((ActiveMQConnection)sendConnection).getBrokerName()); - } - } + private static final transient Logger LOG = LoggerFactory.getLogger(DbRestartJDBCQueueMasterSlaveTest.class); - protected void delayTillRestartRequired() { - LOG.info("Waiting for master broker to Stop"); - master.waitUntilStopped(); - } + protected void messageSent() throws Exception { + verifyExpectedBroker(inflightMessageCount); + if (++inflightMessageCount == failureCount) { + LOG.info("STOPPING DB!@!!!!"); + final EmbeddedDataSource ds = ((SyncCreateDataSource) getExistingDataSource()).getDelegate(); + ds.setShutdownDatabase("shutdown"); + LOG.info("DB STOPPED!@!!!!"); - protected void sendToProducer(MessageProducer producer, - Destination producerDestination, Message message) throws JMSException { - producer.send(producerDestination, message); - } - - @Override - protected Session createReceiveSession(Connection receiveConnection) throws Exception { - return receiveConnection.createSession(true, Session.SESSION_TRANSACTED); - } - - @Override - protected void consumeMessage(Message message, List messageList) { - try { - receiveSession.commit(); - super.consumeMessage(message, messageList); - } catch (JMSException e) { - LOG.info("Failed to commit message receipt: " + message, e); - try { - receiveSession.rollback(); - } catch (JMSException ignored) { + Thread dbRestartThread = new Thread("db-re-start-thread") { + public void run() { + delayTillRestartRequired(); + ds.setShutdownDatabase("false"); + LOG.info("DB RESTARTED!@!!!!"); } + }; + dbRestartThread.start(); + } + verifyExpectedBroker(inflightMessageCount); + } - if (e instanceof TransactionRolledBackException) { - TransactionRolledBackException transactionRolledBackException = (TransactionRolledBackException) e; - if (transactionRolledBackException.getMessage().indexOf("in doubt") != -1) { - // failover chucked bc there is a missing reply to a commit. - // failover is involved b/c the store exception is handled broker side and the client just - // sees a disconnect (socket.close()). - // If the client needs to be aware of the failure then it should not use IOExceptionHandler - // so that the exception will propagate back + protected void verifyExpectedBroker(int inflightMessageCount) { + if (inflightMessageCount == 0) { + assertEquals("connected to master", master.getBrokerName(), ((ActiveMQConnection) sendConnection).getBrokerName()); + } + else if (inflightMessageCount == failureCount + 10) { + assertEquals("connected to slave, count:" + inflightMessageCount, slave.get().getBrokerName(), ((ActiveMQConnection) sendConnection).getBrokerName()); + } + } - // for this test case: - // the commit may have got there and the reply is lost "or" the commit may be lost. - // so we may or may not get a resend. - // - // At the application level we need to determine if the message is there or not which is not trivial - // for this test we assert received == sent - // so we need to know whether the message will be replayed. - // we can ask the store b/c we know it is jdbc - guess we could go through a destination - // message store interface also or use jmx - java.sql.Connection dbConnection = null; - try { - ActiveMQMessage mqMessage = (ActiveMQMessage) message; - MessageId id = mqMessage.getMessageId(); - dbConnection = sharedDs.getConnection(); - PreparedStatement s = dbConnection.prepareStatement(((JDBCPersistenceAdapter) connectedToBroker().getPersistenceAdapter()).getStatements().getFindMessageStatement()); - s.setString(1, id.getProducerId().toString()); - s.setLong(2, id.getProducerSequenceId()); - ResultSet rs = s.executeQuery(); + protected void delayTillRestartRequired() { + LOG.info("Waiting for master broker to Stop"); + master.waitUntilStopped(); + } - if (!rs.next()) { - // message is gone, so lets count it as consumed - LOG.info("On TransactionRolledBackException we know that the ack/commit got there b/c message is gone so we count it: " + mqMessage); - super.consumeMessage(message, messageList); - } else { - LOG.info("On TransactionRolledBackException we know that the ack/commit was lost so we expect a replay of: " + mqMessage); - } - } catch (Exception dbe) { - dbe.printStackTrace(); - } finally { - try { - dbConnection.close(); - } catch (SQLException e1) { - e1.printStackTrace(); - } - } - } + protected void sendToProducer(MessageProducer producer, + Destination producerDestination, + Message message) throws JMSException { + producer.send(producerDestination, message); + } + + @Override + protected Session createReceiveSession(Connection receiveConnection) throws Exception { + return receiveConnection.createSession(true, Session.SESSION_TRANSACTED); + } + + @Override + protected void consumeMessage(Message message, List messageList) { + try { + receiveSession.commit(); + super.consumeMessage(message, messageList); + } + catch (JMSException e) { + LOG.info("Failed to commit message receipt: " + message, e); + try { + receiveSession.rollback(); + } + catch (JMSException ignored) { + } + + if (e instanceof TransactionRolledBackException) { + TransactionRolledBackException transactionRolledBackException = (TransactionRolledBackException) e; + if (transactionRolledBackException.getMessage().indexOf("in doubt") != -1) { + // failover chucked bc there is a missing reply to a commit. + // failover is involved b/c the store exception is handled broker side and the client just + // sees a disconnect (socket.close()). + // If the client needs to be aware of the failure then it should not use IOExceptionHandler + // so that the exception will propagate back + + // for this test case: + // the commit may have got there and the reply is lost "or" the commit may be lost. + // so we may or may not get a resend. + // + // At the application level we need to determine if the message is there or not which is not trivial + // for this test we assert received == sent + // so we need to know whether the message will be replayed. + // we can ask the store b/c we know it is jdbc - guess we could go through a destination + // message store interface also or use jmx + java.sql.Connection dbConnection = null; + try { + ActiveMQMessage mqMessage = (ActiveMQMessage) message; + MessageId id = mqMessage.getMessageId(); + dbConnection = sharedDs.getConnection(); + PreparedStatement s = dbConnection.prepareStatement(((JDBCPersistenceAdapter) connectedToBroker().getPersistenceAdapter()).getStatements().getFindMessageStatement()); + s.setString(1, id.getProducerId().toString()); + s.setLong(2, id.getProducerSequenceId()); + ResultSet rs = s.executeQuery(); + + if (!rs.next()) { + // message is gone, so lets count it as consumed + LOG.info("On TransactionRolledBackException we know that the ack/commit got there b/c message is gone so we count it: " + mqMessage); + super.consumeMessage(message, messageList); + } + else { + LOG.info("On TransactionRolledBackException we know that the ack/commit was lost so we expect a replay of: " + mqMessage); + } + } + catch (Exception dbe) { + dbe.printStackTrace(); + } + finally { + try { + dbConnection.close(); + } + catch (SQLException e1) { + e1.printStackTrace(); + } + } } - } - } + } + } + } - private BrokerService connectedToBroker() { - return ((ActiveMQConnection)receiveConnection).getBrokerInfo().getBrokerName().equals("master") ? master : slave.get(); - } + private BrokerService connectedToBroker() { + return ((ActiveMQConnection) receiveConnection).getBrokerInfo().getBrokerName().equals("master") ? master : slave.get(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueTest.java index 9b21c441ea..923b8adbc4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueTest.java @@ -25,6 +25,7 @@ import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageProducer; import javax.jms.Session; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.JmsTopicSendReceiveWithTwoConnectionsTest; import org.apache.activemq.broker.BrokerService; @@ -37,122 +38,127 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DbRestartJDBCQueueTest extends JmsTopicSendReceiveWithTwoConnectionsTest implements ExceptionListener { - private static final transient Logger LOG = LoggerFactory.getLogger(DbRestartJDBCQueueTest.class); - public boolean transactedSends = false; - public int failureCount = 25; // or 20 for even tx batch boundary + private static final transient Logger LOG = LoggerFactory.getLogger(DbRestartJDBCQueueTest.class); - int inflightMessageCount = 0; - EmbeddedDataSource sharedDs; - BrokerService broker; - final CountDownLatch restartDBLatch = new CountDownLatch(1); + public boolean transactedSends = false; + public int failureCount = 25; // or 20 for even tx batch boundary - protected void setUp() throws Exception { - setAutoFail(true); - topic = false; - verbose = true; - // startup db - sharedDs = (EmbeddedDataSource) DataSourceServiceSupport.createDataSource(IOHelper.getDefaultDataDirectory()); + int inflightMessageCount = 0; + EmbeddedDataSource sharedDs; + BrokerService broker; + final CountDownLatch restartDBLatch = new CountDownLatch(1); - broker = new BrokerService(); + protected void setUp() throws Exception { + setAutoFail(true); + topic = false; + verbose = true; + // startup db + sharedDs = (EmbeddedDataSource) DataSourceServiceSupport.createDataSource(IOHelper.getDefaultDataDirectory()); - DefaultIOExceptionHandler handler = new DefaultIOExceptionHandler(); - handler.setIgnoreSQLExceptions(false); - handler.setStopStartConnectors(true); - broker.setIoExceptionHandler(handler); - broker.addConnector("tcp://localhost:0"); - broker.setUseJmx(false); - broker.setPersistent(true); - broker.setDeleteAllMessagesOnStartup(true); - JDBCPersistenceAdapter persistenceAdapter = new JDBCPersistenceAdapter(); - persistenceAdapter.setDataSource(sharedDs); - persistenceAdapter.setUseLock(false); - persistenceAdapter.setLockKeepAlivePeriod(500); - persistenceAdapter.getLocker().setLockAcquireSleepInterval(500); - broker.setPersistenceAdapter(persistenceAdapter); - broker.start(); - super.setUp(); - } + broker = new BrokerService(); - protected void tearDown() throws Exception { - super.tearDown(); - broker.stop(); - } + DefaultIOExceptionHandler handler = new DefaultIOExceptionHandler(); + handler.setIgnoreSQLExceptions(false); + handler.setStopStartConnectors(true); + broker.setIoExceptionHandler(handler); + broker.addConnector("tcp://localhost:0"); + broker.setUseJmx(false); + broker.setPersistent(true); + broker.setDeleteAllMessagesOnStartup(true); + JDBCPersistenceAdapter persistenceAdapter = new JDBCPersistenceAdapter(); + persistenceAdapter.setDataSource(sharedDs); + persistenceAdapter.setUseLock(false); + persistenceAdapter.setLockKeepAlivePeriod(500); + persistenceAdapter.getLocker().setLockAcquireSleepInterval(500); + broker.setPersistenceAdapter(persistenceAdapter); + broker.start(); + super.setUp(); + } + protected void tearDown() throws Exception { + super.tearDown(); + broker.stop(); + } - protected Session createSendSession(Connection sendConnection) throws Exception { - if (transactedSends) { - return sendConnection.createSession(true, Session.SESSION_TRANSACTED); - } else { - return sendConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } - } + protected Session createSendSession(Connection sendConnection) throws Exception { + if (transactedSends) { + return sendConnection.createSession(true, Session.SESSION_TRANSACTED); + } + else { + return sendConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + } + } - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory f = - new ActiveMQConnectionFactory("failover://" + broker.getTransportConnectors().get(0).getPublishableConnectString()); - f.setExceptionListener(this); - return f; - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory f = new ActiveMQConnectionFactory("failover://" + broker.getTransportConnectors().get(0).getPublishableConnectString()); + f.setExceptionListener(this); + return f; + } - @Override - protected void messageSent() throws Exception { - if (++inflightMessageCount == failureCount) { - LOG.info("STOPPING DB!@!!!!"); - final EmbeddedDataSource ds = sharedDs; - ds.setShutdownDatabase("shutdown"); - try { - ds.getConnection(); - } catch (Exception ignored) { + @Override + protected void messageSent() throws Exception { + if (++inflightMessageCount == failureCount) { + LOG.info("STOPPING DB!@!!!!"); + final EmbeddedDataSource ds = sharedDs; + ds.setShutdownDatabase("shutdown"); + try { + ds.getConnection(); + } + catch (Exception ignored) { + } + LOG.info("DB STOPPED!@!!!!"); + + Thread dbRestartThread = new Thread("db-re-start-thread") { + public void run() { + LOG.info("Sleeping for 10 seconds before allowing db restart"); + try { + restartDBLatch.await(10, TimeUnit.SECONDS); + } + catch (InterruptedException e) { + e.printStackTrace(); + } + ds.setShutdownDatabase("false"); + LOG.info("DB RESTARTED!@!!!!"); } - LOG.info("DB STOPPED!@!!!!"); - - Thread dbRestartThread = new Thread("db-re-start-thread") { - public void run() { - LOG.info("Sleeping for 10 seconds before allowing db restart"); - try { - restartDBLatch.await(10, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - ds.setShutdownDatabase("false"); - LOG.info("DB RESTARTED!@!!!!"); - } - }; - dbRestartThread.start(); - } - } - - protected void sendToProducer(MessageProducer producer, - Destination producerDestination, Message message) throws JMSException { - { - // do some retries as db failures filter back to the client until broker sees - // db lock failure and shuts down - boolean sent = false; - do { - try { - producer.send(producerDestination, message); + }; + dbRestartThread.start(); + } + } - if (transactedSends && ((inflightMessageCount+1) %10 == 0 || (inflightMessageCount+1) >= messageCount)) { - LOG.info("committing on send: " + inflightMessageCount + " message: " + message); - session.commit(); - } + protected void sendToProducer(MessageProducer producer, + Destination producerDestination, + Message message) throws JMSException { + { + // do some retries as db failures filter back to the client until broker sees + // db lock failure and shuts down + boolean sent = false; + do { + try { + producer.send(producerDestination, message); - sent = true; - } catch (JMSException e) { - LOG.info("Exception on producer send:", e); - try { - Thread.sleep(2000); - } catch (InterruptedException ignored) { - } - } - } while(!sent); + if (transactedSends && ((inflightMessageCount + 1) % 10 == 0 || (inflightMessageCount + 1) >= messageCount)) { + LOG.info("committing on send: " + inflightMessageCount + " message: " + message); + session.commit(); + } - } - } + sent = true; + } + catch (JMSException e) { + LOG.info("Exception on producer send:", e); + try { + Thread.sleep(2000); + } + catch (InterruptedException ignored) { + } + } + } while (!sent); - @Override - public void onException(JMSException exception) { - LOG.error("exception on connection: ", exception); - } + } + } + + @Override + public void onException(JMSException exception) { + LOG.error("exception on connection: ", exception); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/JDBCQueueMasterSlaveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/JDBCQueueMasterSlaveTest.java index c7b0ec6980..a30ddb7f56 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/JDBCQueueMasterSlaveTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/JDBCQueueMasterSlaveTest.java @@ -35,78 +35,81 @@ import org.apache.activemq.util.IOHelper; import org.apache.derby.jdbc.EmbeddedDataSource; public class JDBCQueueMasterSlaveTest extends QueueMasterSlaveTestSupport { - protected DataSource sharedDs; - protected String MASTER_URL = "tcp://localhost:62001"; - protected String SLAVE_URL = "tcp://localhost:62002"; - protected void setUp() throws Exception { - // startup db - sharedDs = new SyncCreateDataSource((EmbeddedDataSource) DataSourceServiceSupport.createDataSource(IOHelper.getDefaultDataDirectory())); - super.setUp(); - } + protected DataSource sharedDs; + protected String MASTER_URL = "tcp://localhost:62001"; + protected String SLAVE_URL = "tcp://localhost:62002"; - protected void createMaster() throws Exception { - master = new BrokerService(); - master.setBrokerName("master"); - master.addConnector(MASTER_URL); - master.setUseJmx(false); - master.setPersistent(true); - master.setDeleteAllMessagesOnStartup(true); - JDBCPersistenceAdapter persistenceAdapter = new JDBCPersistenceAdapter(); - persistenceAdapter.setDataSource(getExistingDataSource()); - configureJdbcPersistenceAdapter(persistenceAdapter); - master.setPersistenceAdapter(persistenceAdapter); - configureBroker(master); - master.start(); - } + protected void setUp() throws Exception { + // startup db + sharedDs = new SyncCreateDataSource((EmbeddedDataSource) DataSourceServiceSupport.createDataSource(IOHelper.getDefaultDataDirectory())); + super.setUp(); + } - protected void configureBroker(BrokerService brokerService) { - DefaultIOExceptionHandler stopBrokerOnStoreException = new DefaultIOExceptionHandler(); - // we want any store io exception to stop the broker - stopBrokerOnStoreException.setIgnoreSQLExceptions(false); - brokerService.setIoExceptionHandler(stopBrokerOnStoreException); - } + protected void createMaster() throws Exception { + master = new BrokerService(); + master.setBrokerName("master"); + master.addConnector(MASTER_URL); + master.setUseJmx(false); + master.setPersistent(true); + master.setDeleteAllMessagesOnStartup(true); + JDBCPersistenceAdapter persistenceAdapter = new JDBCPersistenceAdapter(); + persistenceAdapter.setDataSource(getExistingDataSource()); + configureJdbcPersistenceAdapter(persistenceAdapter); + master.setPersistenceAdapter(persistenceAdapter); + configureBroker(master); + master.start(); + } - protected void createSlave() throws Exception { - // use a separate thread as the slave will block waiting for - // the exclusive db lock - Thread t = new Thread() { - public void run() { - try { - BrokerService broker = new BrokerService(); - broker.setBrokerName("slave"); - TransportConnector connector = new TransportConnector(); - connector.setUri(new URI(SLAVE_URL)); - broker.addConnector(connector); - // no need for broker.setMasterConnectorURI(masterConnectorURI) - // as the db lock provides the slave/master initialisation - broker.setUseJmx(false); - broker.setPersistent(true); - JDBCPersistenceAdapter persistenceAdapter = new JDBCPersistenceAdapter(); - persistenceAdapter.setDataSource(getExistingDataSource()); - persistenceAdapter.setCreateTablesOnStartup(false); - broker.setPersistenceAdapter(persistenceAdapter); - configureJdbcPersistenceAdapter(persistenceAdapter); - configureBroker(broker); - broker.start(); - slave.set(broker); - slaveStarted.countDown(); - } catch (IllegalStateException expectedOnShutdown) { - } catch (Exception e) { - fail("failed to start slave broker, reason:" + e); - } + protected void configureBroker(BrokerService brokerService) { + DefaultIOExceptionHandler stopBrokerOnStoreException = new DefaultIOExceptionHandler(); + // we want any store io exception to stop the broker + stopBrokerOnStoreException.setIgnoreSQLExceptions(false); + brokerService.setIoExceptionHandler(stopBrokerOnStoreException); + } + + protected void createSlave() throws Exception { + // use a separate thread as the slave will block waiting for + // the exclusive db lock + Thread t = new Thread() { + public void run() { + try { + BrokerService broker = new BrokerService(); + broker.setBrokerName("slave"); + TransportConnector connector = new TransportConnector(); + connector.setUri(new URI(SLAVE_URL)); + broker.addConnector(connector); + // no need for broker.setMasterConnectorURI(masterConnectorURI) + // as the db lock provides the slave/master initialisation + broker.setUseJmx(false); + broker.setPersistent(true); + JDBCPersistenceAdapter persistenceAdapter = new JDBCPersistenceAdapter(); + persistenceAdapter.setDataSource(getExistingDataSource()); + persistenceAdapter.setCreateTablesOnStartup(false); + broker.setPersistenceAdapter(persistenceAdapter); + configureJdbcPersistenceAdapter(persistenceAdapter); + configureBroker(broker); + broker.start(); + slave.set(broker); + slaveStarted.countDown(); } - }; - t.start(); - } + catch (IllegalStateException expectedOnShutdown) { + } + catch (Exception e) { + fail("failed to start slave broker, reason:" + e); + } + } + }; + t.start(); + } - protected void configureJdbcPersistenceAdapter(JDBCPersistenceAdapter persistenceAdapter) throws IOException { - persistenceAdapter.setLockKeepAlivePeriod(500); - persistenceAdapter.getLocker().setLockAcquireSleepInterval(500); - } + protected void configureJdbcPersistenceAdapter(JDBCPersistenceAdapter persistenceAdapter) throws IOException { + persistenceAdapter.setLockKeepAlivePeriod(500); + persistenceAdapter.getLocker().setLockAcquireSleepInterval(500); + } - protected DataSource getExistingDataSource() throws Exception { - return sharedDs; - } + protected DataSource getExistingDataSource() throws Exception { + return sharedDs; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveSingleUrlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveSingleUrlTest.java index 7dc88f753b..355fd5290b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveSingleUrlTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveSingleUrlTest.java @@ -25,71 +25,71 @@ import org.apache.activemq.broker.TransportConnector; import org.apache.activemq.leveldb.LevelDBStore; import org.junit.Ignore; - public class QueueMasterSlaveSingleUrlTest extends QueueMasterSlaveTestSupport { - private final String brokerUrl = "tcp://localhost:62001"; - private final String singleUriString = "failover://(" + brokerUrl +")?randomize=false"; - @Override - protected void setUp() throws Exception { - setAutoFail(true); - super.setUp(); - } + private final String brokerUrl = "tcp://localhost:62001"; + private final String singleUriString = "failover://(" + brokerUrl + ")?randomize=false"; - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(singleUriString); - } + @Override + protected void setUp() throws Exception { + setAutoFail(true); + super.setUp(); + } - @Override - protected void createMaster() throws Exception { - master = new BrokerService(); - master.setBrokerName("shared-master"); - configureSharedPersistenceAdapter(master); - master.addConnector(brokerUrl); - master.start(); - } + @Override + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory(singleUriString); + } - private void configureSharedPersistenceAdapter(BrokerService broker) throws Exception { - LevelDBStore adapter = new LevelDBStore(); - adapter.setDirectory(new File("shared")); - broker.setPersistenceAdapter(adapter); - } + @Override + protected void createMaster() throws Exception { + master = new BrokerService(); + master.setBrokerName("shared-master"); + configureSharedPersistenceAdapter(master); + master.addConnector(brokerUrl); + master.start(); + } - @Override - protected void createSlave() throws Exception { - new Thread(new Runnable() { - @Override - public void run() { - try { - BrokerService broker = new BrokerService(); - broker.setBrokerName("shared-slave"); - configureSharedPersistenceAdapter(broker); - // add transport as a service so that it is bound on start, after store started - final TransportConnector tConnector = new TransportConnector(); - tConnector.setUri(new URI(brokerUrl)); - broker.addConnector(tConnector); + private void configureSharedPersistenceAdapter(BrokerService broker) throws Exception { + LevelDBStore adapter = new LevelDBStore(); + adapter.setDirectory(new File("shared")); + broker.setPersistenceAdapter(adapter); + } - broker.start(); - slave.set(broker); - slaveStarted.countDown(); - } catch (Exception e) { - e.printStackTrace(); - } + @Override + protected void createSlave() throws Exception { + new Thread(new Runnable() { + @Override + public void run() { + try { + BrokerService broker = new BrokerService(); + broker.setBrokerName("shared-slave"); + configureSharedPersistenceAdapter(broker); + // add transport as a service so that it is bound on start, after store started + final TransportConnector tConnector = new TransportConnector(); + tConnector.setUri(new URI(brokerUrl)); + broker.addConnector(tConnector); + + broker.start(); + slave.set(broker); + slaveStarted.countDown(); } + catch (Exception e) { + e.printStackTrace(); + } + } - }).start(); - } + }).start(); + } - - // The @Ignore is just here for documentation, since this is a JUnit3 test - // I added the sleep because without it the two other test cases fail. I haven't looked into it, but - // my guess whatever setUp does isn't really finished when the teardown runs. - @Ignore("See https://issues.apache.org/jira/browse/AMQ-5164") - @Override - public void testAdvisory() throws Exception { - Thread.sleep(5 * 1000); - //super.testAdvisory(); - } + // The @Ignore is just here for documentation, since this is a JUnit3 test + // I added the sleep because without it the two other test cases fail. I haven't looked into it, but + // my guess whatever setUp does isn't really finished when the teardown runs. + @Ignore("See https://issues.apache.org/jira/browse/AMQ-5164") + @Override + public void testAdvisory() throws Exception { + Thread.sleep(5 * 1000); + //super.testAdvisory(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveTestSupport.java index 2808ebe143..d3e1a712a1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveTestSupport.java @@ -40,117 +40,118 @@ import org.springframework.core.io.ClassPathResource; * Test failover for Queues */ abstract public class QueueMasterSlaveTestSupport extends JmsTopicSendReceiveWithTwoConnectionsTest { - private static final transient Logger LOG = LoggerFactory.getLogger(QueueMasterSlaveTestSupport.class); - protected BrokerService master; - protected AtomicReference slave = new AtomicReference(); - protected CountDownLatch slaveStarted = new CountDownLatch(1); - protected int inflightMessageCount; - protected int failureCount = 50; - protected String uriString = "failover://(tcp://localhost:62001,tcp://localhost:62002)?randomize=false&useExponentialBackOff=false"; + private static final transient Logger LOG = LoggerFactory.getLogger(QueueMasterSlaveTestSupport.class); - @Override - protected void setUp() throws Exception { - setMaxTestTime(TimeUnit.MINUTES.toMillis(10)); - setAutoFail(true); - if (System.getProperty("basedir") == null) { - File file = new File("."); - System.setProperty("basedir", file.getAbsolutePath()); - } - super.messageCount = 500; - failureCount = super.messageCount / 2; - super.topic = isTopic(); - createMaster(); - createSlave(); - // wait for thing to connect - Thread.sleep(1000); - super.setUp(); - } + protected BrokerService master; + protected AtomicReference slave = new AtomicReference(); + protected CountDownLatch slaveStarted = new CountDownLatch(1); + protected int inflightMessageCount; + protected int failureCount = 50; + protected String uriString = "failover://(tcp://localhost:62001,tcp://localhost:62002)?randomize=false&useExponentialBackOff=false"; - protected String getSlaveXml() { - return "org/apache/activemq/broker/ft/slave.xml"; - } + @Override + protected void setUp() throws Exception { + setMaxTestTime(TimeUnit.MINUTES.toMillis(10)); + setAutoFail(true); + if (System.getProperty("basedir") == null) { + File file = new File("."); + System.setProperty("basedir", file.getAbsolutePath()); + } + super.messageCount = 500; + failureCount = super.messageCount / 2; + super.topic = isTopic(); + createMaster(); + createSlave(); + // wait for thing to connect + Thread.sleep(1000); + super.setUp(); + } - protected String getMasterXml() { - return "org/apache/activemq/broker/ft/master.xml"; - } + protected String getSlaveXml() { + return "org/apache/activemq/broker/ft/slave.xml"; + } - @Override - protected void tearDown() throws Exception { - super.tearDown(); - master.stop(); - master.waitUntilStopped(); - slaveStarted.await(60, TimeUnit.SECONDS); - BrokerService brokerService = slave.get(); - if( brokerService!=null ) { - brokerService.stop(); - } - master.stop(); - } + protected String getMasterXml() { + return "org/apache/activemq/broker/ft/master.xml"; + } - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(uriString); - } + @Override + protected void tearDown() throws Exception { + super.tearDown(); + master.stop(); + master.waitUntilStopped(); + slaveStarted.await(60, TimeUnit.SECONDS); + BrokerService brokerService = slave.get(); + if (brokerService != null) { + brokerService.stop(); + } + master.stop(); + } - @Override - protected void messageSent() throws Exception { - if (++inflightMessageCount == failureCount) { - Thread.sleep(1000); - LOG.error("MASTER STOPPED!@!!!!"); - master.stop(); - } - } + @Override + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory(uriString); + } - protected boolean isTopic() { - return false; - } + @Override + protected void messageSent() throws Exception { + if (++inflightMessageCount == failureCount) { + Thread.sleep(1000); + LOG.error("MASTER STOPPED!@!!!!"); + master.stop(); + } + } - protected void createMaster() throws Exception { - BrokerFactoryBean brokerFactory = new BrokerFactoryBean(new ClassPathResource(getMasterXml())); - brokerFactory.afterPropertiesSet(); - master = brokerFactory.getBroker(); - master.start(); - } + protected boolean isTopic() { + return false; + } - protected void createSlave() throws Exception { - BrokerFactoryBean brokerFactory = new BrokerFactoryBean(new ClassPathResource(getSlaveXml())); - brokerFactory.afterPropertiesSet(); - BrokerService broker = brokerFactory.getBroker(); - broker.start(); - slave.set(broker); - slaveStarted.countDown(); - } + protected void createMaster() throws Exception { + BrokerFactoryBean brokerFactory = new BrokerFactoryBean(new ClassPathResource(getMasterXml())); + brokerFactory.afterPropertiesSet(); + master = brokerFactory.getBroker(); + master.start(); + } - public void testVirtualTopicFailover() throws Exception { + protected void createSlave() throws Exception { + BrokerFactoryBean brokerFactory = new BrokerFactoryBean(new ClassPathResource(getSlaveXml())); + brokerFactory.afterPropertiesSet(); + BrokerService broker = brokerFactory.getBroker(); + broker.start(); + slave.set(broker); + slaveStarted.countDown(); + } - MessageConsumer qConsumer = session.createConsumer(new ActiveMQQueue("Consumer.A.VirtualTopic.TA1")); - assertNull("No message there yet", qConsumer.receive(1000)); - qConsumer.close(); - assertTrue(!master.isSlave()); - master.stop(); - assertTrue("slave started", slaveStarted.await(60, TimeUnit.SECONDS)); - assertTrue(!slave.get().isSlave()); + public void testVirtualTopicFailover() throws Exception { - final String text = "ForUWhenSlaveKicksIn"; - producer.send(new ActiveMQTopic("VirtualTopic.TA1"), session.createTextMessage(text)); + MessageConsumer qConsumer = session.createConsumer(new ActiveMQQueue("Consumer.A.VirtualTopic.TA1")); + assertNull("No message there yet", qConsumer.receive(1000)); + qConsumer.close(); + assertTrue(!master.isSlave()); + master.stop(); + assertTrue("slave started", slaveStarted.await(60, TimeUnit.SECONDS)); + assertTrue(!slave.get().isSlave()); - qConsumer = session.createConsumer(new ActiveMQQueue("Consumer.A.VirtualTopic.TA1")); + final String text = "ForUWhenSlaveKicksIn"; + producer.send(new ActiveMQTopic("VirtualTopic.TA1"), session.createTextMessage(text)); - javax.jms.Message message = qConsumer.receive(4000); - assertNotNull("Get message after failover", message); - assertEquals("correct message", text, ((TextMessage)message).getText()); - } + qConsumer = session.createConsumer(new ActiveMQQueue("Consumer.A.VirtualTopic.TA1")); - public void testAdvisory() throws Exception { - MessageConsumer advConsumer = session.createConsumer(AdvisorySupport.getMasterBrokerAdvisoryTopic()); + javax.jms.Message message = qConsumer.receive(4000); + assertNotNull("Get message after failover", message); + assertEquals("correct message", text, ((TextMessage) message).getText()); + } - master.stop(); - assertTrue("slave started", slaveStarted.await(60, TimeUnit.SECONDS)); - LOG.info("slave started"); - Message advisoryMessage = advConsumer.receive(5000); - LOG.info("received " + advisoryMessage); - assertNotNull("Didn't received advisory", advisoryMessage); + public void testAdvisory() throws Exception { + MessageConsumer advConsumer = session.createConsumer(AdvisorySupport.getMasterBrokerAdvisoryTopic()); - } + master.stop(); + assertTrue("slave started", slaveStarted.await(60, TimeUnit.SECONDS)); + LOG.info("slave started"); + Message advisoryMessage = advConsumer.receive(5000); + LOG.info("received " + advisoryMessage); + assertNotNull("Didn't received advisory", advisoryMessage); + + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveTestUsingSharedFileTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveTestUsingSharedFileTest.java index c9f178dd47..cc1a52718e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveTestUsingSharedFileTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveTestUsingSharedFileTest.java @@ -16,29 +16,29 @@ */ package org.apache.activemq.broker.ft; -public class QueueMasterSlaveTestUsingSharedFileTest extends - QueueMasterSlaveTestSupport { - - protected String getSlaveXml() { - return "org/apache/activemq/broker/ft/sharedFileSlave.xml"; - } - - protected String getMasterXml() { - return "org/apache/activemq/broker/ft/sharedFileMaster.xml"; - } - - protected void createSlave() throws Exception { - // Start the Brokers async since starting them up could be a blocking operation.. - new Thread(new Runnable() { - public void run() { - try { - QueueMasterSlaveTestUsingSharedFileTest.super.createSlave(); - } catch (Exception e) { - e.printStackTrace(); - } - } +public class QueueMasterSlaveTestUsingSharedFileTest extends QueueMasterSlaveTestSupport { - }).start(); - } + protected String getSlaveXml() { + return "org/apache/activemq/broker/ft/sharedFileSlave.xml"; + } + + protected String getMasterXml() { + return "org/apache/activemq/broker/ft/sharedFileMaster.xml"; + } + + protected void createSlave() throws Exception { + // Start the Brokers async since starting them up could be a blocking operation.. + new Thread(new Runnable() { + public void run() { + try { + QueueMasterSlaveTestUsingSharedFileTest.super.createSlave(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + }).start(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/SyncCreateDataSource.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/SyncCreateDataSource.java index 5331a226a6..a86937be8a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/SyncCreateDataSource.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/SyncCreateDataSource.java @@ -22,65 +22,67 @@ import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.logging.Logger; import javax.sql.DataSource; + import org.apache.derby.jdbc.EmbeddedDataSource; // prevent concurrent calls from attempting to create the db at the same time // can result in "already exists in this jvm" errors public class SyncCreateDataSource implements DataSource { - final EmbeddedDataSource delegate; - SyncCreateDataSource(EmbeddedDataSource dataSource) { - this.delegate = dataSource; - } + final EmbeddedDataSource delegate; - @Override - public Connection getConnection() throws SQLException { - synchronized (this) { - return delegate.getConnection(); - } - } + SyncCreateDataSource(EmbeddedDataSource dataSource) { + this.delegate = dataSource; + } - @Override - public Connection getConnection(String username, String password) throws SQLException { - synchronized (this) { - return delegate.getConnection(); - } - } + @Override + public Connection getConnection() throws SQLException { + synchronized (this) { + return delegate.getConnection(); + } + } - @Override - public PrintWriter getLogWriter() throws SQLException { - return null; - } + @Override + public Connection getConnection(String username, String password) throws SQLException { + synchronized (this) { + return delegate.getConnection(); + } + } - @Override - public void setLogWriter(PrintWriter out) throws SQLException { - } + @Override + public PrintWriter getLogWriter() throws SQLException { + return null; + } - @Override - public int getLoginTimeout() throws SQLException { - return 0; - } + @Override + public void setLogWriter(PrintWriter out) throws SQLException { + } - @Override - public void setLoginTimeout(int seconds) throws SQLException { - } + @Override + public int getLoginTimeout() throws SQLException { + return 0; + } - @Override - public T unwrap(Class iface) throws SQLException { - return null; - } + @Override + public void setLoginTimeout(int seconds) throws SQLException { + } - @Override - public boolean isWrapperFor(Class iface) throws SQLException { - return false; - } + @Override + public T unwrap(Class iface) throws SQLException { + return null; + } - EmbeddedDataSource getDelegate() { - return delegate; - } + @Override + public boolean isWrapperFor(Class iface) throws SQLException { + return false; + } - public Logger getParentLogger() throws SQLFeatureNotSupportedException { - return null; - } + EmbeddedDataSource getDelegate() { + return delegate; + } + + public Logger getParentLogger() throws SQLFeatureNotSupportedException { + return null; + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/kahaDbJdbcLeaseQueueMasterSlaveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/kahaDbJdbcLeaseQueueMasterSlaveTest.java index ee7ca0f8c8..cf97994aa4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/kahaDbJdbcLeaseQueueMasterSlaveTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/kahaDbJdbcLeaseQueueMasterSlaveTest.java @@ -19,6 +19,7 @@ package org.apache.activemq.broker.ft; import java.io.IOException; import java.net.URI; import javax.sql.DataSource; + import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.TransportConnector; import org.apache.activemq.store.jdbc.DataSourceServiceSupport; @@ -30,85 +31,88 @@ import org.apache.activemq.util.IOHelper; import org.apache.derby.jdbc.EmbeddedDataSource; public class kahaDbJdbcLeaseQueueMasterSlaveTest extends QueueMasterSlaveTestSupport { - protected DataSource sharedDs; - protected String MASTER_URL = "tcp://localhost:62001"; - protected String SLAVE_URL = "tcp://localhost:62002"; - protected void setUp() throws Exception { - // startup db - sharedDs = new SyncCreateDataSource((EmbeddedDataSource) DataSourceServiceSupport.createDataSource(IOHelper.getDefaultDataDirectory())); - super.setUp(); - } + protected DataSource sharedDs; + protected String MASTER_URL = "tcp://localhost:62001"; + protected String SLAVE_URL = "tcp://localhost:62002"; - protected void createMaster() throws Exception { - master = new BrokerService(); - master.setBrokerName("master"); - master.addConnector(MASTER_URL); - master.setUseJmx(false); - master.setPersistent(true); - master.setDeleteAllMessagesOnStartup(true); - KahaDBPersistenceAdapter kahaDBPersistenceAdapter = (KahaDBPersistenceAdapter) master.getPersistenceAdapter(); - LeaseDatabaseLocker leaseDatabaseLocker = new LeaseDatabaseLocker(); - leaseDatabaseLocker.setCreateTablesOnStartup(true); - leaseDatabaseLocker.setDataSource(getExistingDataSource()); - leaseDatabaseLocker.setStatements(new Statements()); - kahaDBPersistenceAdapter.setLocker(leaseDatabaseLocker); - configureLocker(kahaDBPersistenceAdapter); - configureBroker(master); - master.start(); - } + protected void setUp() throws Exception { + // startup db + sharedDs = new SyncCreateDataSource((EmbeddedDataSource) DataSourceServiceSupport.createDataSource(IOHelper.getDefaultDataDirectory())); + super.setUp(); + } - protected void configureBroker(BrokerService brokerService) { - DefaultIOExceptionHandler stopBrokerOnStoreException = new DefaultIOExceptionHandler(); - // we want any store io exception to stop the broker - stopBrokerOnStoreException.setIgnoreSQLExceptions(false); - brokerService.setIoExceptionHandler(stopBrokerOnStoreException); - } + protected void createMaster() throws Exception { + master = new BrokerService(); + master.setBrokerName("master"); + master.addConnector(MASTER_URL); + master.setUseJmx(false); + master.setPersistent(true); + master.setDeleteAllMessagesOnStartup(true); + KahaDBPersistenceAdapter kahaDBPersistenceAdapter = (KahaDBPersistenceAdapter) master.getPersistenceAdapter(); + LeaseDatabaseLocker leaseDatabaseLocker = new LeaseDatabaseLocker(); + leaseDatabaseLocker.setCreateTablesOnStartup(true); + leaseDatabaseLocker.setDataSource(getExistingDataSource()); + leaseDatabaseLocker.setStatements(new Statements()); + kahaDBPersistenceAdapter.setLocker(leaseDatabaseLocker); + configureLocker(kahaDBPersistenceAdapter); + configureBroker(master); + master.start(); + } - protected void createSlave() throws Exception { - // use a separate thread as the slave will block waiting for - // the exclusive db lock - Thread t = new Thread() { - public void run() { - try { - BrokerService broker = new BrokerService(); - broker.setBrokerName("slave"); - TransportConnector connector = new TransportConnector(); - connector.setUri(new URI(SLAVE_URL)); - broker.addConnector(connector); - broker.setUseJmx(false); - broker.setPersistent(true); - KahaDBPersistenceAdapter kahaDBPersistenceAdapter = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); - LeaseDatabaseLocker leaseDatabaseLocker = new LeaseDatabaseLocker(); - leaseDatabaseLocker.setDataSource(getExistingDataSource()); - leaseDatabaseLocker.setStatements(new Statements()); - kahaDBPersistenceAdapter.setLocker(leaseDatabaseLocker); - configureLocker(kahaDBPersistenceAdapter); - configureBroker(broker); - broker.start(); - slave.set(broker); - slaveStarted.countDown(); - } catch (IllegalStateException expectedOnShutdown) { - } catch (Exception e) { - fail("failed to start slave broker, reason:" + e); - } + protected void configureBroker(BrokerService brokerService) { + DefaultIOExceptionHandler stopBrokerOnStoreException = new DefaultIOExceptionHandler(); + // we want any store io exception to stop the broker + stopBrokerOnStoreException.setIgnoreSQLExceptions(false); + brokerService.setIoExceptionHandler(stopBrokerOnStoreException); + } + + protected void createSlave() throws Exception { + // use a separate thread as the slave will block waiting for + // the exclusive db lock + Thread t = new Thread() { + public void run() { + try { + BrokerService broker = new BrokerService(); + broker.setBrokerName("slave"); + TransportConnector connector = new TransportConnector(); + connector.setUri(new URI(SLAVE_URL)); + broker.addConnector(connector); + broker.setUseJmx(false); + broker.setPersistent(true); + KahaDBPersistenceAdapter kahaDBPersistenceAdapter = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); + LeaseDatabaseLocker leaseDatabaseLocker = new LeaseDatabaseLocker(); + leaseDatabaseLocker.setDataSource(getExistingDataSource()); + leaseDatabaseLocker.setStatements(new Statements()); + kahaDBPersistenceAdapter.setLocker(leaseDatabaseLocker); + configureLocker(kahaDBPersistenceAdapter); + configureBroker(broker); + broker.start(); + slave.set(broker); + slaveStarted.countDown(); } - }; - t.start(); - } + catch (IllegalStateException expectedOnShutdown) { + } + catch (Exception e) { + fail("failed to start slave broker, reason:" + e); + } + } + }; + t.start(); + } - protected void configureLocker(KahaDBPersistenceAdapter kahaDBPersistenceAdapter) throws IOException { - kahaDBPersistenceAdapter.setLockKeepAlivePeriod(500); - kahaDBPersistenceAdapter.getLocker().setLockAcquireSleepInterval(500); - } + protected void configureLocker(KahaDBPersistenceAdapter kahaDBPersistenceAdapter) throws IOException { + kahaDBPersistenceAdapter.setLockKeepAlivePeriod(500); + kahaDBPersistenceAdapter.getLocker().setLockAcquireSleepInterval(500); + } - @Override - public void testVirtualTopicFailover() throws Exception { - // Ignoring for now, see AMQ-4842 - } + @Override + public void testVirtualTopicFailover() throws Exception { + // Ignoring for now, see AMQ-4842 + } - protected DataSource getExistingDataSource() throws Exception { - return sharedDs; - } + protected DataSource getExistingDataSource() throws Exception { + return sharedDs; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/mKahaDbQueueMasterSlaveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/mKahaDbQueueMasterSlaveTest.java index ad9cca1ba0..5eafadc350 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/mKahaDbQueueMasterSlaveTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/mKahaDbQueueMasterSlaveTest.java @@ -19,6 +19,7 @@ package org.apache.activemq.broker.ft; import java.net.URI; import java.util.LinkedList; import java.util.List; + import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.TransportConnector; import org.apache.activemq.store.kahadb.FilteredKahaDBPersistenceAdapter; @@ -26,64 +27,67 @@ import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; import org.apache.activemq.store.kahadb.MultiKahaDBPersistenceAdapter; public class mKahaDbQueueMasterSlaveTest extends QueueMasterSlaveTestSupport { - protected String MASTER_URL = "tcp://localhost:62001"; - protected String SLAVE_URL = "tcp://localhost:62002"; - protected void createMaster() throws Exception { - master = new BrokerService(); - master.setBrokerName("master"); - master.addConnector(MASTER_URL); - master.setUseJmx(false); - master.setPersistent(true); - master.setDeleteAllMessagesOnStartup(true); + protected String MASTER_URL = "tcp://localhost:62001"; + protected String SLAVE_URL = "tcp://localhost:62002"; - MultiKahaDBPersistenceAdapter mKahaDB = new MultiKahaDBPersistenceAdapter(); - List adapters = new LinkedList(); - FilteredKahaDBPersistenceAdapter defaultEntry = new FilteredKahaDBPersistenceAdapter(); - defaultEntry.setPersistenceAdapter(new KahaDBPersistenceAdapter()); - defaultEntry.setPerDestination(true); - adapters.add(defaultEntry); + protected void createMaster() throws Exception { + master = new BrokerService(); + master.setBrokerName("master"); + master.addConnector(MASTER_URL); + master.setUseJmx(false); + master.setPersistent(true); + master.setDeleteAllMessagesOnStartup(true); - mKahaDB.setFilteredPersistenceAdapters(adapters); - master.setPersistenceAdapter(mKahaDB); + MultiKahaDBPersistenceAdapter mKahaDB = new MultiKahaDBPersistenceAdapter(); + List adapters = new LinkedList(); + FilteredKahaDBPersistenceAdapter defaultEntry = new FilteredKahaDBPersistenceAdapter(); + defaultEntry.setPersistenceAdapter(new KahaDBPersistenceAdapter()); + defaultEntry.setPerDestination(true); + adapters.add(defaultEntry); - master.start(); - } + mKahaDB.setFilteredPersistenceAdapters(adapters); + master.setPersistenceAdapter(mKahaDB); - protected void createSlave() throws Exception { - // use a separate thread as the slave will block waiting for - // the exclusive db lock - Thread t = new Thread() { - public void run() { - try { - BrokerService broker = new BrokerService(); - broker.setBrokerName("slave"); - TransportConnector connector = new TransportConnector(); - connector.setUri(new URI(SLAVE_URL)); - broker.addConnector(connector); - // no need for broker.setMasterConnectorURI(masterConnectorURI) - // as the db lock provides the slave/master initialisation - broker.setUseJmx(false); - broker.setPersistent(true); + master.start(); + } - MultiKahaDBPersistenceAdapter mKahaDB = new MultiKahaDBPersistenceAdapter(); - List adapters = new LinkedList(); - FilteredKahaDBPersistenceAdapter defaultEntry = new FilteredKahaDBPersistenceAdapter(); - defaultEntry.setPersistenceAdapter(new KahaDBPersistenceAdapter()); - defaultEntry.setPerDestination(true); - adapters.add(defaultEntry); + protected void createSlave() throws Exception { + // use a separate thread as the slave will block waiting for + // the exclusive db lock + Thread t = new Thread() { + public void run() { + try { + BrokerService broker = new BrokerService(); + broker.setBrokerName("slave"); + TransportConnector connector = new TransportConnector(); + connector.setUri(new URI(SLAVE_URL)); + broker.addConnector(connector); + // no need for broker.setMasterConnectorURI(masterConnectorURI) + // as the db lock provides the slave/master initialisation + broker.setUseJmx(false); + broker.setPersistent(true); - mKahaDB.setFilteredPersistenceAdapters(adapters); - broker.setPersistenceAdapter(mKahaDB); - broker.start(); - slave.set(broker); - slaveStarted.countDown(); - } catch (IllegalStateException expectedOnShutdown) { - } catch (Exception e) { - fail("failed to start slave broker, reason:" + e); - } + MultiKahaDBPersistenceAdapter mKahaDB = new MultiKahaDBPersistenceAdapter(); + List adapters = new LinkedList(); + FilteredKahaDBPersistenceAdapter defaultEntry = new FilteredKahaDBPersistenceAdapter(); + defaultEntry.setPersistenceAdapter(new KahaDBPersistenceAdapter()); + defaultEntry.setPerDestination(true); + adapters.add(defaultEntry); + + mKahaDB.setFilteredPersistenceAdapters(adapters); + broker.setPersistenceAdapter(mKahaDB); + broker.start(); + slave.set(broker); + slaveStarted.countDown(); } - }; - t.start(); - } + catch (IllegalStateException expectedOnShutdown) { + } + catch (Exception e) { + fail("failed to start slave broker, reason:" + e); + } + } + }; + t.start(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/BrokerViewSlowStoreStartupTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/BrokerViewSlowStoreStartupTest.java index cf1b7672d1..6d0a70e125 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/BrokerViewSlowStoreStartupTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/BrokerViewSlowStoreStartupTest.java @@ -37,320 +37,359 @@ import org.slf4j.LoggerFactory; */ public class BrokerViewSlowStoreStartupTest { - private static final Logger LOG = LoggerFactory.getLogger(BrokerViewSlowStoreStartupTest.class); + private static final Logger LOG = LoggerFactory.getLogger(BrokerViewSlowStoreStartupTest.class); - private final CountDownLatch holdStoreStart = new CountDownLatch(1); - private final String brokerName = "brokerViewTest"; + private final CountDownLatch holdStoreStart = new CountDownLatch(1); + private final String brokerName = "brokerViewTest"; - private BrokerService broker; - private Thread startThread; + private BrokerService broker; + private Thread startThread; - private BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName(brokerName); + private BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setBrokerName(brokerName); - KahaDBStore kaha = new KahaDBStore() { + KahaDBStore kaha = new KahaDBStore() { - @Override - public void start() throws Exception { - LOG.info("Test KahaDB class is waiting for signal to complete its start()"); - holdStoreStart.await(); - super.start(); - LOG.info("Test KahaDB class is completed its start()"); + @Override + public void start() throws Exception { + LOG.info("Test KahaDB class is waiting for signal to complete its start()"); + holdStoreStart.await(); + super.start(); + LOG.info("Test KahaDB class is completed its start()"); + } + }; + + kaha.setDirectory(new File("target/activemq-data/kahadb")); + kaha.deleteAllMessages(); + + broker.setPersistenceAdapter(kaha); + broker.setUseJmx(true); + + return broker; + } + + @Before + public void setUp() throws Exception { + broker = createBroker(); + + startThread = new Thread(new Runnable() { + + @Override + public void run() { + try { + broker.start(); } - }; - - kaha.setDirectory(new File("target/activemq-data/kahadb")); - kaha.deleteAllMessages(); - - broker.setPersistenceAdapter(kaha); - broker.setUseJmx(true); - - return broker; - } - - @Before - public void setUp() throws Exception { - broker = createBroker(); - - startThread = new Thread(new Runnable() { - - @Override - public void run() { - try { - broker.start(); - } catch(Exception e) { - e.printStackTrace(); - } + catch (Exception e) { + e.printStackTrace(); } - }); - startThread.start(); - } + } + }); + startThread.start(); + } - @After - public void tearDown() throws Exception { + @After + public void tearDown() throws Exception { - // ensure we don't keep the broker held if an exception occurs somewhere. - holdStoreStart.countDown(); + // ensure we don't keep the broker held if an exception occurs somewhere. + holdStoreStart.countDown(); - startThread.join(); + startThread.join(); - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - } + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + } - @Test(timeout=120000) - public void testBrokerViewOnSlowStoreStart() throws Exception { + @Test(timeout = 120000) + public void testBrokerViewOnSlowStoreStart() throws Exception { - // Ensure we have an Admin View. - assertTrue(Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return (broker.getAdminView()) != null; - } - })); + // Ensure we have an Admin View. + assertTrue(Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return (broker.getAdminView()) != null; + } + })); - final BrokerView view = broker.getAdminView(); + final BrokerView view = broker.getAdminView(); - try { - view.getBrokerName(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.getBrokerName(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.getBrokerId(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.getBrokerId(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.getTotalEnqueueCount(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.getTotalEnqueueCount(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.getTotalDequeueCount(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.getTotalDequeueCount(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.getTotalConsumerCount(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.getTotalConsumerCount(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.getTotalProducerCount(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.getTotalProducerCount(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.getTotalMessageCount(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.getTotalMessageCount(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.getTotalMessagesCached(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.getTotalMessagesCached(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.resetStatistics(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.resetStatistics(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.enableStatistics(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.enableStatistics(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.disableStatistics(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.disableStatistics(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.isStatisticsEnabled(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.isStatisticsEnabled(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.getTopics(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.getTopics(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.getQueues(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.getQueues(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.getTemporaryTopics(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.getTemporaryTopics(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.getTemporaryQueues(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.getTemporaryQueues(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.getTopicSubscribers(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.getTopicSubscribers(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.getDurableTopicSubscribers(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.getDurableTopicSubscribers(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.getQueueSubscribers(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.getQueueSubscribers(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.getTemporaryTopicSubscribers(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.getTemporaryTopicSubscribers(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.getTemporaryQueueSubscribers(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.getTemporaryQueueSubscribers(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.getInactiveDurableTopicSubscribers(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.getInactiveDurableTopicSubscribers(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.getTopicProducers(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.getTopicProducers(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.getQueueProducers(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.getQueueProducers(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.getTemporaryTopicProducers(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.getTemporaryTopicProducers(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.getTemporaryQueueProducers(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.getTemporaryQueueProducers(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.getDynamicDestinationProducers(); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.getDynamicDestinationProducers(); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.removeConnector("tcp"); - fail("Should have thrown a NoSuchElementException"); - } catch(NoSuchElementException e) { - } + try { + view.removeConnector("tcp"); + fail("Should have thrown a NoSuchElementException"); + } + catch (NoSuchElementException e) { + } - try { - view.removeNetworkConnector("tcp"); - fail("Should have thrown a NoSuchElementException"); - } catch(NoSuchElementException e) { - } + try { + view.removeNetworkConnector("tcp"); + fail("Should have thrown a NoSuchElementException"); + } + catch (NoSuchElementException e) { + } - try { - view.addTopic("TEST"); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.addTopic("TEST"); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.addQueue("TEST"); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.addQueue("TEST"); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.removeTopic("TEST"); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.removeTopic("TEST"); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.removeQueue("TEST"); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.removeQueue("TEST"); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.createDurableSubscriber("1", "2", "3","4"); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.createDurableSubscriber("1", "2", "3", "4"); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - try { - view.destroyDurableSubscriber("1", "2"); - fail("Should have thrown an IllegalStateException"); - } catch(IllegalStateException e) { - } + try { + view.destroyDurableSubscriber("1", "2"); + fail("Should have thrown an IllegalStateException"); + } + catch (IllegalStateException e) { + } - holdStoreStart.countDown(); - startThread.join(); + holdStoreStart.countDown(); + startThread.join(); - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return view.getBroker() != null; - } - }); - assertNotNull(view.getBroker()); + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return view.getBroker() != null; + } + }); + assertNotNull(view.getBroker()); - try { - view.getBrokerName(); - } catch(Exception e) { - fail("caught an exception getting the Broker property: " + e.getClass().getName()); - } + try { + view.getBrokerName(); + } + catch (Exception e) { + fail("caught an exception getting the Broker property: " + e.getClass().getName()); + } - try { - view.getBrokerId(); - } catch(IllegalStateException e) { - fail("caught an exception getting the Broker property: " + e.getClass().getName()); - } + try { + view.getBrokerId(); + } + catch (IllegalStateException e) { + fail("caught an exception getting the Broker property: " + e.getClass().getName()); + } - try { - view.getTotalEnqueueCount(); - } catch(IllegalStateException e) { - fail("caught an exception getting the Broker property: " + e.getClass().getName()); - } - } + try { + view.getTotalEnqueueCount(); + } + catch (IllegalStateException e) { + fail("caught an exception getting the Broker property: " + e.getClass().getName()); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/HealthViewMBeanTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/HealthViewMBeanTest.java index 9998be975e..6406b852e3 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/HealthViewMBeanTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/HealthViewMBeanTest.java @@ -36,82 +36,84 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HealthViewMBeanTest extends EmbeddedBrokerTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(MBeanTest.class); - protected MBeanServer mbeanServer; - protected String domain = "org.apache.activemq"; - @Override - protected void setUp() throws Exception { - bindAddress = "tcp://localhost:0"; - useTopic = false; - super.setUp(); - mbeanServer = broker.getManagementContext().getMBeanServer(); - } + private static final Logger LOG = LoggerFactory.getLogger(MBeanTest.class); + protected MBeanServer mbeanServer; + protected String domain = "org.apache.activemq"; - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } + @Override + protected void setUp() throws Exception { + bindAddress = "tcp://localhost:0"; + useTopic = false; + super.setUp(); + mbeanServer = broker.getManagementContext().getMBeanServer(); + } - @Override - protected ConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString()); - } + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } - @Override - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setPersistent(true); - answer.setDeleteAllMessagesOnStartup(true); - answer.getSystemUsage().getMemoryUsage().setLimit(1024 * 1024 * 64); - answer.getSystemUsage().getTempUsage().setLimit(1024 * 1024 * 64); - answer.getSystemUsage().getStoreUsage().setLimit(1024 * 1024 * 64); - answer.setUseJmx(true); - answer.setSchedulerSupport(true); + @Override + protected ConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString()); + } - // allow options to be visible via jmx + @Override + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + answer.setPersistent(true); + answer.setDeleteAllMessagesOnStartup(true); + answer.getSystemUsage().getMemoryUsage().setLimit(1024 * 1024 * 64); + answer.getSystemUsage().getTempUsage().setLimit(1024 * 1024 * 64); + answer.getSystemUsage().getStoreUsage().setLimit(1024 * 1024 * 64); + answer.setUseJmx(true); + answer.setSchedulerSupport(true); - answer.addConnector(bindAddress); - return answer; - } + // allow options to be visible via jmx - public void testHealthView() throws Exception{ - Connection connection = connectionFactory.createConnection(); + answer.addConnector(bindAddress); + return answer; + } - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - destination = createDestination(); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + public void testHealthView() throws Exception { + Connection connection = connectionFactory.createConnection(); - for (int i = 0; i < 60; i++) { - BytesMessage message = session.createBytesMessage(); - message.writeBytes(new byte[1024 *1024]); - producer.send(message); - } + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + destination = createDestination(); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - Thread.sleep(1000); + for (int i = 0; i < 60; i++) { + BytesMessage message = session.createBytesMessage(); + message.writeBytes(new byte[1024 * 1024]); + producer.send(message); + } - String objectNameStr = broker.getBrokerObjectName().toString(); - objectNameStr += ",service=Health"; - ObjectName brokerName = assertRegisteredObjectName(objectNameStr); - HealthViewMBean health = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, HealthViewMBean.class, true); - List list = health.healthList(); + Thread.sleep(1000); - for (HealthStatus status : list) { - LOG.info("Health status: {}", status); - } + String objectNameStr = broker.getBrokerObjectName().toString(); + objectNameStr += ",service=Health"; + ObjectName brokerName = assertRegisteredObjectName(objectNameStr); + HealthViewMBean health = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, HealthViewMBean.class, true); + List list = health.healthList(); - assertEquals(2, list.size()); - } + for (HealthStatus status : list) { + LOG.info("Health status: {}", status); + } - protected ObjectName assertRegisteredObjectName(String name) throws MalformedObjectNameException, NullPointerException { - ObjectName objectName = new ObjectName(name); - if (mbeanServer.isRegistered(objectName)) { - LOG.info("Bean Registered: " + objectName); - } else { - fail("Could not find MBean!: " + objectName); - } - return objectName; - } + assertEquals(2, list.size()); + } + + protected ObjectName assertRegisteredObjectName(String name) throws MalformedObjectNameException, NullPointerException { + ObjectName objectName = new ObjectName(name); + if (mbeanServer.isRegistered(objectName)) { + LOG.info("Bean Registered: " + objectName); + } + else { + fail("Could not find MBean!: " + objectName); + } + return objectName; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/Log4JConfigTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/Log4JConfigTest.java index 2c2b3735cd..82f1c4e3ae 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/Log4JConfigTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/Log4JConfigTest.java @@ -34,167 +34,161 @@ import org.slf4j.LoggerFactory; public class Log4JConfigTest extends EmbeddedBrokerTestSupport { - private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(Log4JConfigTest.class); + private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(Log4JConfigTest.class); - private static final String BROKER_LOGGER = "org.apache.activemq.broker.BrokerService"; + private static final String BROKER_LOGGER = "org.apache.activemq.broker.BrokerService"; - protected MBeanServer mbeanServer; - protected String domain = "org.apache.activemq"; + protected MBeanServer mbeanServer; + protected String domain = "org.apache.activemq"; - @Override - protected void setUp() throws Exception { - bindAddress = "tcp://localhost:0"; - useTopic = false; - super.setUp(); - mbeanServer = broker.getManagementContext().getMBeanServer(); - } + @Override + protected void setUp() throws Exception { + bindAddress = "tcp://localhost:0"; + useTopic = false; + super.setUp(); + mbeanServer = broker.getManagementContext().getMBeanServer(); + } - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } - @Override - protected ConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString()); - } + @Override + protected ConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString()); + } - @Override - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setPersistent(true); - answer.setDeleteAllMessagesOnStartup(true); - answer.setUseJmx(true); - answer.setSchedulerSupport(true); - answer.addConnector(bindAddress); - return answer; - } + @Override + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + answer.setPersistent(true); + answer.setDeleteAllMessagesOnStartup(true); + answer.setUseJmx(true); + answer.setSchedulerSupport(true); + answer.addConnector(bindAddress); + return answer; + } - @Test - public void testLog4JConfigViewExists() throws Exception { - String brokerObjectName = broker.getBrokerObjectName().toString(); - String log4jConfigViewName = BrokerMBeanSupport.createLog4JConfigViewName(brokerObjectName).toString(); - assertRegisteredObjectName(log4jConfigViewName); - } + @Test + public void testLog4JConfigViewExists() throws Exception { + String brokerObjectName = broker.getBrokerObjectName().toString(); + String log4jConfigViewName = BrokerMBeanSupport.createLog4JConfigViewName(brokerObjectName).toString(); + assertRegisteredObjectName(log4jConfigViewName); + } - @Test - public void testLog4JConfigViewGetLoggers() throws Throwable { - String brokerObjectName = broker.getBrokerObjectName().toString(); - ObjectName log4jConfigViewName = BrokerMBeanSupport.createLog4JConfigViewName(brokerObjectName); - Log4JConfigViewMBean log4jConfigView = MBeanServerInvocationHandler.newProxyInstance( - mbeanServer, log4jConfigViewName, Log4JConfigViewMBean.class, true); + @Test + public void testLog4JConfigViewGetLoggers() throws Throwable { + String brokerObjectName = broker.getBrokerObjectName().toString(); + ObjectName log4jConfigViewName = BrokerMBeanSupport.createLog4JConfigViewName(brokerObjectName); + Log4JConfigViewMBean log4jConfigView = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, log4jConfigViewName, Log4JConfigViewMBean.class, true); - List loggers = log4jConfigView.getLoggers(); - assertNotNull(loggers); - assertFalse(loggers.isEmpty()); - } + List loggers = log4jConfigView.getLoggers(); + assertNotNull(loggers); + assertFalse(loggers.isEmpty()); + } - @Test - public void testLog4JConfigViewGetLevel() throws Throwable { - String brokerObjectName = broker.getBrokerObjectName().toString(); - ObjectName log4jConfigViewName = BrokerMBeanSupport.createLog4JConfigViewName(brokerObjectName); - Log4JConfigViewMBean log4jConfigView = MBeanServerInvocationHandler.newProxyInstance( - mbeanServer, log4jConfigViewName, Log4JConfigViewMBean.class, true); + @Test + public void testLog4JConfigViewGetLevel() throws Throwable { + String brokerObjectName = broker.getBrokerObjectName().toString(); + ObjectName log4jConfigViewName = BrokerMBeanSupport.createLog4JConfigViewName(brokerObjectName); + Log4JConfigViewMBean log4jConfigView = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, log4jConfigViewName, Log4JConfigViewMBean.class, true); - String level = log4jConfigView.getLogLevel(BROKER_LOGGER); - assertNotNull(level); - assertFalse(level.isEmpty()); - } + String level = log4jConfigView.getLogLevel(BROKER_LOGGER); + assertNotNull(level); + assertFalse(level.isEmpty()); + } - @Test - public void testLog4JConfigViewGetLevelUnknownLoggerName() throws Throwable { - String brokerObjectName = broker.getBrokerObjectName().toString(); - ObjectName log4jConfigViewName = BrokerMBeanSupport.createLog4JConfigViewName(brokerObjectName); - Log4JConfigViewMBean log4jConfigView = MBeanServerInvocationHandler.newProxyInstance( - mbeanServer, log4jConfigViewName, Log4JConfigViewMBean.class, true); + @Test + public void testLog4JConfigViewGetLevelUnknownLoggerName() throws Throwable { + String brokerObjectName = broker.getBrokerObjectName().toString(); + ObjectName log4jConfigViewName = BrokerMBeanSupport.createLog4JConfigViewName(brokerObjectName); + Log4JConfigViewMBean log4jConfigView = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, log4jConfigViewName, Log4JConfigViewMBean.class, true); - // Non-existent loggers will return a name equal to the root level. - String level = log4jConfigView.getLogLevel("not.a.logger"); - assertNotNull(level); - assertFalse(level.isEmpty()); - assertEquals(Logger.getRootLogger().getLevel().toString(), level); - } + // Non-existent loggers will return a name equal to the root level. + String level = log4jConfigView.getLogLevel("not.a.logger"); + assertNotNull(level); + assertFalse(level.isEmpty()); + assertEquals(Logger.getRootLogger().getLevel().toString(), level); + } - @Test - public void testLog4JConfigViewSetLevel() throws Throwable { - String brokerObjectName = broker.getBrokerObjectName().toString(); - ObjectName log4jConfigViewName = BrokerMBeanSupport.createLog4JConfigViewName(brokerObjectName); - Log4JConfigViewMBean log4jConfigView = MBeanServerInvocationHandler.newProxyInstance( - mbeanServer, log4jConfigViewName, Log4JConfigViewMBean.class, true); + @Test + public void testLog4JConfigViewSetLevel() throws Throwable { + String brokerObjectName = broker.getBrokerObjectName().toString(); + ObjectName log4jConfigViewName = BrokerMBeanSupport.createLog4JConfigViewName(brokerObjectName); + Log4JConfigViewMBean log4jConfigView = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, log4jConfigViewName, Log4JConfigViewMBean.class, true); - String level = log4jConfigView.getLogLevel(BROKER_LOGGER); - assertNotNull(level); - assertFalse(level.isEmpty()); + String level = log4jConfigView.getLogLevel(BROKER_LOGGER); + assertNotNull(level); + assertFalse(level.isEmpty()); - log4jConfigView.setLogLevel(BROKER_LOGGER, "WARN"); - level = log4jConfigView.getLogLevel(BROKER_LOGGER); - assertNotNull(level); - assertEquals("WARN", level); + log4jConfigView.setLogLevel(BROKER_LOGGER, "WARN"); + level = log4jConfigView.getLogLevel(BROKER_LOGGER); + assertNotNull(level); + assertEquals("WARN", level); - log4jConfigView.setLogLevel(BROKER_LOGGER, "INFO"); - level = log4jConfigView.getLogLevel(BROKER_LOGGER); - assertNotNull(level); - assertEquals("INFO", level); - } + log4jConfigView.setLogLevel(BROKER_LOGGER, "INFO"); + level = log4jConfigView.getLogLevel(BROKER_LOGGER); + assertNotNull(level); + assertEquals("INFO", level); + } - @Test - public void testLog4JConfigViewSetLevelNoChangeIfLevelIsBad() throws Throwable { - String brokerObjectName = broker.getBrokerObjectName().toString(); - ObjectName log4jConfigViewName = BrokerMBeanSupport.createLog4JConfigViewName(brokerObjectName); - Log4JConfigViewMBean log4jConfigView = MBeanServerInvocationHandler.newProxyInstance( - mbeanServer, log4jConfigViewName, Log4JConfigViewMBean.class, true); + @Test + public void testLog4JConfigViewSetLevelNoChangeIfLevelIsBad() throws Throwable { + String brokerObjectName = broker.getBrokerObjectName().toString(); + ObjectName log4jConfigViewName = BrokerMBeanSupport.createLog4JConfigViewName(brokerObjectName); + Log4JConfigViewMBean log4jConfigView = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, log4jConfigViewName, Log4JConfigViewMBean.class, true); - log4jConfigView.setLogLevel(BROKER_LOGGER, "INFO"); - String level = log4jConfigView.getLogLevel(BROKER_LOGGER); - assertNotNull(level); - assertEquals("INFO", level); + log4jConfigView.setLogLevel(BROKER_LOGGER, "INFO"); + String level = log4jConfigView.getLogLevel(BROKER_LOGGER); + assertNotNull(level); + assertEquals("INFO", level); - log4jConfigView.setLogLevel(BROKER_LOGGER, "BAD"); - level = log4jConfigView.getLogLevel(BROKER_LOGGER); - assertNotNull(level); - assertEquals("INFO", level); - } + log4jConfigView.setLogLevel(BROKER_LOGGER, "BAD"); + level = log4jConfigView.getLogLevel(BROKER_LOGGER); + assertNotNull(level); + assertEquals("INFO", level); + } - @Test - public void testLog4JConfigViewGetRootLogLevel() throws Throwable { - String brokerObjectName = broker.getBrokerObjectName().toString(); - ObjectName log4jConfigViewName = BrokerMBeanSupport.createLog4JConfigViewName(brokerObjectName); - Log4JConfigViewMBean log4jConfigView = MBeanServerInvocationHandler.newProxyInstance( - mbeanServer, log4jConfigViewName, Log4JConfigViewMBean.class, true); + @Test + public void testLog4JConfigViewGetRootLogLevel() throws Throwable { + String brokerObjectName = broker.getBrokerObjectName().toString(); + ObjectName log4jConfigViewName = BrokerMBeanSupport.createLog4JConfigViewName(brokerObjectName); + Log4JConfigViewMBean log4jConfigView = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, log4jConfigViewName, Log4JConfigViewMBean.class, true); - String level = log4jConfigView.getRootLogLevel(); - assertNotNull(level); - assertFalse(level.isEmpty()); + String level = log4jConfigView.getRootLogLevel(); + assertNotNull(level); + assertFalse(level.isEmpty()); - String currentRootLevel = Logger.getRootLogger().getLevel().toString(); - assertEquals(currentRootLevel, level); - } + String currentRootLevel = Logger.getRootLogger().getLevel().toString(); + assertEquals(currentRootLevel, level); + } - @Test - public void testLog4JConfigViewSetRootLevel() throws Throwable { - String brokerObjectName = broker.getBrokerObjectName().toString(); - ObjectName log4jConfigViewName = BrokerMBeanSupport.createLog4JConfigViewName(brokerObjectName); - Log4JConfigViewMBean log4jConfigView = MBeanServerInvocationHandler.newProxyInstance( - mbeanServer, log4jConfigViewName, Log4JConfigViewMBean.class, true); + @Test + public void testLog4JConfigViewSetRootLevel() throws Throwable { + String brokerObjectName = broker.getBrokerObjectName().toString(); + ObjectName log4jConfigViewName = BrokerMBeanSupport.createLog4JConfigViewName(brokerObjectName); + Log4JConfigViewMBean log4jConfigView = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, log4jConfigViewName, Log4JConfigViewMBean.class, true); - String currentRootLevel = Logger.getRootLogger().getLevel().toString(); - log4jConfigView.setRootLogLevel("WARN"); - currentRootLevel = Logger.getRootLogger().getLevel().toString(); - assertEquals("WARN", currentRootLevel); - log4jConfigView.setRootLogLevel("INFO"); - currentRootLevel = Logger.getRootLogger().getLevel().toString(); - assertEquals("INFO", currentRootLevel); + String currentRootLevel = Logger.getRootLogger().getLevel().toString(); + log4jConfigView.setRootLogLevel("WARN"); + currentRootLevel = Logger.getRootLogger().getLevel().toString(); + assertEquals("WARN", currentRootLevel); + log4jConfigView.setRootLogLevel("INFO"); + currentRootLevel = Logger.getRootLogger().getLevel().toString(); + assertEquals("INFO", currentRootLevel); - Level level; - } + Level level; + } - protected ObjectName assertRegisteredObjectName(String name) throws MalformedObjectNameException, NullPointerException { - ObjectName objectName = new ObjectName(name); - if (mbeanServer.isRegistered(objectName)) { - LOG.info("Bean Registered: " + objectName); - } else { - fail("Could not find MBean!: " + objectName); - } - return objectName; - } + protected ObjectName assertRegisteredObjectName(String name) throws MalformedObjectNameException, NullPointerException { + ObjectName objectName = new ObjectName(name); + if (mbeanServer.isRegistered(objectName)) { + LOG.info("Bean Registered: " + objectName); + } + else { + fail("Could not find MBean!: " + objectName); + } + return objectName; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/MBeanOperationTimeoutTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/MBeanOperationTimeoutTest.java index b7c00b8a62..cb26d86e98 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/MBeanOperationTimeoutTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/MBeanOperationTimeoutTest.java @@ -28,6 +28,7 @@ import javax.management.MBeanServer; import javax.management.MBeanServerInvocationHandler; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.junit.After; @@ -35,97 +36,101 @@ import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; public class MBeanOperationTimeoutTest { - private static final Logger LOG = LoggerFactory.getLogger(MBeanOperationTimeoutTest.class); - private ActiveMQConnectionFactory connectionFactory; - private BrokerService broker; - private String connectionUri; - private static final String destinationName = "MBeanOperationTimeoutTestQ"; - private static final String moveToDestinationName = "MBeanOperationTimeoutTestQ.Moved"; + private static final Logger LOG = LoggerFactory.getLogger(MBeanOperationTimeoutTest.class); - protected MBeanServer mbeanServer; - protected String domain = "org.apache.activemq"; + private ActiveMQConnectionFactory connectionFactory; + private BrokerService broker; + private String connectionUri; + private static final String destinationName = "MBeanOperationTimeoutTestQ"; + private static final String moveToDestinationName = "MBeanOperationTimeoutTestQ.Moved"; - protected int messageCount = 50000; + protected MBeanServer mbeanServer; + protected String domain = "org.apache.activemq"; - @Test(expected = TimeoutException.class) - public void testLongOperationTimesOut() throws Exception { + protected int messageCount = 50000; - sendMessages(messageCount); - LOG.info("Produced " + messageCount + " messages to the broker."); + @Test(expected = TimeoutException.class) + public void testLongOperationTimesOut() throws Exception { - // Now get the QueueViewMBean and purge - String objectNameStr = broker.getBrokerObjectName().toString(); - objectNameStr += ",destinationType=Queue,destinationName="+destinationName; + sendMessages(messageCount); + LOG.info("Produced " + messageCount + " messages to the broker."); - ObjectName queueViewMBeanName = assertRegisteredObjectName(objectNameStr); - QueueViewMBean proxy = (QueueViewMBean)MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); + // Now get the QueueViewMBean and purge + String objectNameStr = broker.getBrokerObjectName().toString(); + objectNameStr += ",destinationType=Queue,destinationName=" + destinationName; - long count = proxy.getQueueSize(); - assertEquals("Queue size", count, messageCount); + ObjectName queueViewMBeanName = assertRegisteredObjectName(objectNameStr); + QueueViewMBean proxy = (QueueViewMBean) MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - LOG.info("Attempting to move one message, TimeoutException expected"); - proxy.moveMatchingMessagesTo(null, moveToDestinationName); - } + long count = proxy.getQueueSize(); + assertEquals("Queue size", count, messageCount); - private void sendMessages(int count) throws Exception { - Connection connection = connectionFactory.createConnection(); - try { - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Destination destination = session.createQueue(destinationName); - MessageProducer producer = session.createProducer(destination); - for (int i = 0; i < messageCount; i++) { - Message message = session.createMessage(); - message.setIntProperty("id", i); - producer.send(message); - } - session.commit(); - } finally { - connection.close(); - } - } + LOG.info("Attempting to move one message, TimeoutException expected"); + proxy.moveMatchingMessagesTo(null, moveToDestinationName); + } - protected ObjectName assertRegisteredObjectName(String name) throws MalformedObjectNameException, NullPointerException { - ObjectName objectName = new ObjectName(name); - if (mbeanServer.isRegistered(objectName)) { - LOG.info("Bean Registered: " + objectName); - } else { - fail("Could not find MBean!: " + objectName); - } - return objectName; - } + private void sendMessages(int count) throws Exception { + Connection connection = connectionFactory.createConnection(); + try { + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + Destination destination = session.createQueue(destinationName); + MessageProducer producer = session.createProducer(destination); + for (int i = 0; i < messageCount; i++) { + Message message = session.createMessage(); + message.setIntProperty("id", i); + producer.send(message); + } + session.commit(); + } + finally { + connection.close(); + } + } - @Before - public void setUp() throws Exception { - broker = createBroker(); - broker.start(); - broker.waitUntilStarted(); + protected ObjectName assertRegisteredObjectName(String name) throws MalformedObjectNameException, NullPointerException { + ObjectName objectName = new ObjectName(name); + if (mbeanServer.isRegistered(objectName)) { + LOG.info("Bean Registered: " + objectName); + } + else { + fail("Could not find MBean!: " + objectName); + } + return objectName; + } - connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); - connectionFactory = new ActiveMQConnectionFactory(connectionUri); - mbeanServer = broker.getManagementContext().getMBeanServer(); - } + @Before + public void setUp() throws Exception { + broker = createBroker(); + broker.start(); + broker.waitUntilStarted(); - @After - public void tearDown() throws Exception { - Thread.sleep(500); - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - broker = null; - } - } + connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); + connectionFactory = new ActiveMQConnectionFactory(connectionUri); + mbeanServer = broker.getManagementContext().getMBeanServer(); + } - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setMbeanInvocationTimeout(TimeUnit.SECONDS.toMillis(1)); - answer.setUseJmx(true); - answer.addConnector("vm://localhost"); - answer.setDeleteAllMessagesOnStartup(true); - return answer; - } + @After + public void tearDown() throws Exception { + Thread.sleep(500); + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + broker = null; + } + } + + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + answer.setMbeanInvocationTimeout(TimeUnit.SECONDS.toMillis(1)); + answer.setUseJmx(true); + answer.addConnector("vm://localhost"); + answer.setDeleteAllMessagesOnStartup(true); + return answer; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/MBeanTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/MBeanTest.java index b679313fc1..a156393491 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/MBeanTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/MBeanTest.java @@ -71,1438 +71,1435 @@ import org.slf4j.LoggerFactory; * command line application. */ public class MBeanTest extends EmbeddedBrokerTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(MBeanTest.class); - - private static boolean waitForKeyPress; - - protected MBeanServer mbeanServer; - protected String domain = "org.apache.activemq"; - protected String clientID = "foo"; - - protected Connection connection; - protected boolean transacted; - protected int authMode = Session.AUTO_ACKNOWLEDGE; - protected static final int MESSAGE_COUNT = 2*BaseDestination.MAX_PAGE_SIZE; - final static String QUEUE_WITH_OPTIONS = "QueueWithOptions"; - - /** - * When you run this test case from the command line it will pause before - * terminating so that you can look at the MBeans state for debugging - * purposes. - */ - public static void main(String[] args) { - waitForKeyPress = true; - TestRunner.run(MBeanTest.class); - } - - public void testConnectors() throws Exception{ - ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); - BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); - - assertEquals("openwire URL port doesn't equal bind Address", - new URI(broker.getTransportConnectorByType("tcp")).getPort(), - new URI(this.broker.getTransportConnectors().get(0).getPublishableConnectString()).getPort()); - } - - public void testMBeans() throws Exception { - connection = connectionFactory.createConnection(); - useConnection(connection); - - // test all the various MBeans now we have a producer, consumer and - // messages on a queue - assertSendViaMBean(); - assertSendCsnvViaMBean(); - assertQueueBrowseWorks(); - assertCreateAndDestroyDurableSubscriptions(); - assertConsumerCounts(); - assertProducerCounts(); - } - - public void testMoveMessages() throws Exception { - connection = connectionFactory.createConnection(); - useConnection(connection); - - ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); - - QueueViewMBean queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - - CompositeData[] compdatalist = queue.browse(); - int initialQueueSize = compdatalist.length; - if (initialQueueSize == 0) { - fail("There is no message in the queue:"); - } - else { - echo("Current queue size: " + initialQueueSize); - } - int messageCount = initialQueueSize; - String[] messageIDs = new String[messageCount]; - for (int i = 0; i < messageCount; i++) { - CompositeData cdata = compdatalist[i]; - String messageID = (String) cdata.get("JMSMessageID"); - assertNotNull("Should have a message ID for message " + i, messageID); - messageIDs[i] = messageID; - } - - assertTrue("dest has some memory usage", queue.getMemoryPercentUsage() > 0); - - echo("About to move " + messageCount + " messages"); - - String newDestination = getSecondDestinationString(); - for (String messageID : messageIDs) { - //echo("Moving message: " + messageID); - queue.moveMessageTo(messageID, newDestination); - } - - echo("Now browsing the queue"); - compdatalist = queue.browse(); - int actualCount = compdatalist.length; - echo("Current queue size: " + actualCount); - assertEquals("Should now have empty queue but was", initialQueueSize - messageCount, actualCount); - - echo("Now browsing the second queue"); - - queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + newDestination ); - QueueViewMBean queueNew = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - - long newQueuesize = queueNew.getQueueSize(); - echo("Second queue size: " + newQueuesize); - assertEquals("Unexpected number of messages ",messageCount, newQueuesize); - - // check memory usage migration - assertTrue("new dest has some memory usage", queueNew.getMemoryPercentUsage() > 0); - assertEquals("old dest has no memory usage", 0, queue.getMemoryPercentUsage()); - assertTrue("use cache", queueNew.isUseCache()); - assertTrue("cache enabled", queueNew.isCacheEnabled()); - assertEquals("no forwards", 0, queueNew.getForwardCount()); - } - - public void testRemoveMessages() throws Exception { - ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); - BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); - broker.addQueue(getDestinationString()); - - ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); - - QueueViewMBean queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - String msg1 = queue.sendTextMessage("message 1"); - String msg2 = queue.sendTextMessage("message 2"); - - assertTrue(queue.removeMessage(msg2)); - - connection = connectionFactory.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination dest = createDestination(); - - MessageConsumer consumer = session.createConsumer(dest); - Message message = consumer.receive(1000); - assertNotNull(message); - assertEquals(msg1, message.getJMSMessageID()); - - String msg3 = queue.sendTextMessage("message 3"); - message = consumer.receive(1000); - assertNotNull(message); - assertEquals(msg3, message.getJMSMessageID()); - - message = consumer.receive(1000); - assertNull(message); - - } - - public void testRemoveQueue() throws Exception { - String queueName = "TEST"; - ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); - BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); - broker.addQueue(queueName); - - ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + queueName); - - QueueViewMBean queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - queue.sendTextMessage("message 1"); - queue.sendTextMessage("message 2"); - - assertEquals(2, broker.getTotalMessageCount()); - - broker.removeQueue(queueName); - - assertEquals(0, broker.getTotalMessageCount()); - - } - - public void testRetryMessages() throws Exception { - // lets speed up redelivery - ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) connectionFactory; - factory.getRedeliveryPolicy().setCollisionAvoidancePercent((short) 0); - factory.getRedeliveryPolicy().setMaximumRedeliveries(1); - factory.getRedeliveryPolicy().setInitialRedeliveryDelay(0); - factory.getRedeliveryPolicy().setUseCollisionAvoidance(false); - factory.getRedeliveryPolicy().setUseExponentialBackOff(false); - factory.getRedeliveryPolicy().setBackOffMultiplier((short) 0); - - connection = connectionFactory.createConnection(); - useConnection(connection); - ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); - QueueViewMBean queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); + private static final Logger LOG = LoggerFactory.getLogger(MBeanTest.class); + + private static boolean waitForKeyPress; + + protected MBeanServer mbeanServer; + protected String domain = "org.apache.activemq"; + protected String clientID = "foo"; + + protected Connection connection; + protected boolean transacted; + protected int authMode = Session.AUTO_ACKNOWLEDGE; + protected static final int MESSAGE_COUNT = 2 * BaseDestination.MAX_PAGE_SIZE; + final static String QUEUE_WITH_OPTIONS = "QueueWithOptions"; + + /** + * When you run this test case from the command line it will pause before + * terminating so that you can look at the MBeans state for debugging + * purposes. + */ + public static void main(String[] args) { + waitForKeyPress = true; + TestRunner.run(MBeanTest.class); + } + + public void testConnectors() throws Exception { + ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); + BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); + + assertEquals("openwire URL port doesn't equal bind Address", new URI(broker.getTransportConnectorByType("tcp")).getPort(), new URI(this.broker.getTransportConnectors().get(0).getPublishableConnectString()).getPort()); + } + + public void testMBeans() throws Exception { + connection = connectionFactory.createConnection(); + useConnection(connection); + + // test all the various MBeans now we have a producer, consumer and + // messages on a queue + assertSendViaMBean(); + assertSendCsnvViaMBean(); + assertQueueBrowseWorks(); + assertCreateAndDestroyDurableSubscriptions(); + assertConsumerCounts(); + assertProducerCounts(); + } + + public void testMoveMessages() throws Exception { + connection = connectionFactory.createConnection(); + useConnection(connection); + + ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); + + QueueViewMBean queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); + + CompositeData[] compdatalist = queue.browse(); + int initialQueueSize = compdatalist.length; + if (initialQueueSize == 0) { + fail("There is no message in the queue:"); + } + else { + echo("Current queue size: " + initialQueueSize); + } + int messageCount = initialQueueSize; + String[] messageIDs = new String[messageCount]; + for (int i = 0; i < messageCount; i++) { + CompositeData cdata = compdatalist[i]; + String messageID = (String) cdata.get("JMSMessageID"); + assertNotNull("Should have a message ID for message " + i, messageID); + messageIDs[i] = messageID; + } + + assertTrue("dest has some memory usage", queue.getMemoryPercentUsage() > 0); + + echo("About to move " + messageCount + " messages"); + + String newDestination = getSecondDestinationString(); + for (String messageID : messageIDs) { + //echo("Moving message: " + messageID); + queue.moveMessageTo(messageID, newDestination); + } + + echo("Now browsing the queue"); + compdatalist = queue.browse(); + int actualCount = compdatalist.length; + echo("Current queue size: " + actualCount); + assertEquals("Should now have empty queue but was", initialQueueSize - messageCount, actualCount); + + echo("Now browsing the second queue"); + + queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + newDestination); + QueueViewMBean queueNew = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); + + long newQueuesize = queueNew.getQueueSize(); + echo("Second queue size: " + newQueuesize); + assertEquals("Unexpected number of messages ", messageCount, newQueuesize); + + // check memory usage migration + assertTrue("new dest has some memory usage", queueNew.getMemoryPercentUsage() > 0); + assertEquals("old dest has no memory usage", 0, queue.getMemoryPercentUsage()); + assertTrue("use cache", queueNew.isUseCache()); + assertTrue("cache enabled", queueNew.isCacheEnabled()); + assertEquals("no forwards", 0, queueNew.getForwardCount()); + } + + public void testRemoveMessages() throws Exception { + ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); + BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); + broker.addQueue(getDestinationString()); + + ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); + + QueueViewMBean queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); + String msg1 = queue.sendTextMessage("message 1"); + String msg2 = queue.sendTextMessage("message 2"); + + assertTrue(queue.removeMessage(msg2)); + + connection = connectionFactory.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQDestination dest = createDestination(); + + MessageConsumer consumer = session.createConsumer(dest); + Message message = consumer.receive(1000); + assertNotNull(message); + assertEquals(msg1, message.getJMSMessageID()); + + String msg3 = queue.sendTextMessage("message 3"); + message = consumer.receive(1000); + assertNotNull(message); + assertEquals(msg3, message.getJMSMessageID()); + + message = consumer.receive(1000); + assertNull(message); + + } + + public void testRemoveQueue() throws Exception { + String queueName = "TEST"; + ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); + BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); + broker.addQueue(queueName); + + ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + queueName); + + QueueViewMBean queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); + queue.sendTextMessage("message 1"); + queue.sendTextMessage("message 2"); + + assertEquals(2, broker.getTotalMessageCount()); + + broker.removeQueue(queueName); + + assertEquals(0, broker.getTotalMessageCount()); + + } + + public void testRetryMessages() throws Exception { + // lets speed up redelivery + ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) connectionFactory; + factory.getRedeliveryPolicy().setCollisionAvoidancePercent((short) 0); + factory.getRedeliveryPolicy().setMaximumRedeliveries(1); + factory.getRedeliveryPolicy().setInitialRedeliveryDelay(0); + factory.getRedeliveryPolicy().setUseCollisionAvoidance(false); + factory.getRedeliveryPolicy().setUseExponentialBackOff(false); + factory.getRedeliveryPolicy().setBackOffMultiplier((short) 0); + + connection = connectionFactory.createConnection(); + useConnection(connection); - long initialQueueSize = queue.getQueueSize(); - echo("current queue size: " + initialQueueSize); - assertTrue("dest has some memory usage", queue.getMemoryPercentUsage() > 0); - - // lets create a duff consumer which keeps rolling back... - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageConsumer consumer = session.createConsumer(new ActiveMQQueue(getDestinationString())); - Message message = consumer.receive(5000); - while (message != null) { - echo("Message: " + message.getJMSMessageID() + " redelivered " + message.getJMSRedelivered() + " counter " + message.getObjectProperty("JMSXDeliveryCount")); - session.rollback(); - message = consumer.receive(2000); - } - consumer.close(); - session.close(); + ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); + QueueViewMBean queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - // now lets get the dead letter queue - Thread.sleep(1000); + long initialQueueSize = queue.getQueueSize(); + echo("current queue size: " + initialQueueSize); + assertTrue("dest has some memory usage", queue.getMemoryPercentUsage() > 0); + + // lets create a duff consumer which keeps rolling back... + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageConsumer consumer = session.createConsumer(new ActiveMQQueue(getDestinationString())); + Message message = consumer.receive(5000); + while (message != null) { + echo("Message: " + message.getJMSMessageID() + " redelivered " + message.getJMSRedelivered() + " counter " + message.getObjectProperty("JMSXDeliveryCount")); + session.rollback(); + message = consumer.receive(2000); + } + consumer.close(); + session.close(); - ObjectName dlqQueueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + SharedDeadLetterStrategy.DEFAULT_DEAD_LETTER_QUEUE_NAME ); - QueueViewMBean dlq = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, dlqQueueViewMBeanName, QueueViewMBean.class, true); + // now lets get the dead letter queue + Thread.sleep(1000); - long initialDlqSize = dlq.getQueueSize(); - CompositeData[] compdatalist = dlq.browse(); - int dlqQueueSize = compdatalist.length; - if (dlqQueueSize == 0) { - fail("There are no messages in the queue:"); - } - else { - echo("Current DLQ queue size: " + dlqQueueSize); - } - int messageCount = dlqQueueSize; - String[] messageIDs = new String[messageCount]; - for (int i = 0; i < messageCount; i++) { - CompositeData cdata = compdatalist[i]; - String messageID = (String) cdata.get("JMSMessageID"); - assertNotNull("Should have a message ID for message " + i, messageID); - messageIDs[i] = messageID; - } + ObjectName dlqQueueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + SharedDeadLetterStrategy.DEFAULT_DEAD_LETTER_QUEUE_NAME); + QueueViewMBean dlq = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, dlqQueueViewMBeanName, QueueViewMBean.class, true); - int dlqMemUsage = dlq.getMemoryPercentUsage(); - assertTrue("dlq has some memory usage", dlqMemUsage > 0); - assertEquals("dest has no memory usage", 0, queue.getMemoryPercentUsage()); + long initialDlqSize = dlq.getQueueSize(); + CompositeData[] compdatalist = dlq.browse(); + int dlqQueueSize = compdatalist.length; + if (dlqQueueSize == 0) { + fail("There are no messages in the queue:"); + } + else { + echo("Current DLQ queue size: " + dlqQueueSize); + } + int messageCount = dlqQueueSize; + String[] messageIDs = new String[messageCount]; + for (int i = 0; i < messageCount; i++) { + CompositeData cdata = compdatalist[i]; + String messageID = (String) cdata.get("JMSMessageID"); + assertNotNull("Should have a message ID for message " + i, messageID); + messageIDs[i] = messageID; + } - echo("About to retry " + messageCount + " messages"); + int dlqMemUsage = dlq.getMemoryPercentUsage(); + assertTrue("dlq has some memory usage", dlqMemUsage > 0); + assertEquals("dest has no memory usage", 0, queue.getMemoryPercentUsage()); - for (String messageID : messageIDs) { - echo("Retrying message: " + messageID); - dlq.retryMessage(messageID); - } + echo("About to retry " + messageCount + " messages"); - long queueSize = queue.getQueueSize(); - compdatalist = queue.browse(); - int actualCount = compdatalist.length; - echo("Original queue size is now " + queueSize); - echo("Original browse queue size: " + actualCount); + for (String messageID : messageIDs) { + echo("Retrying message: " + messageID); + dlq.retryMessage(messageID); + } - long dlqSize = dlq.getQueueSize(); - echo("DLQ size: " + dlqSize); + long queueSize = queue.getQueueSize(); + compdatalist = queue.browse(); + int actualCount = compdatalist.length; + echo("Original queue size is now " + queueSize); + echo("Original browse queue size: " + actualCount); - assertEquals("DLQ size", initialDlqSize - messageCount, dlqSize); - assertEquals("queue size", initialQueueSize, queueSize); - assertEquals("browse queue size", initialQueueSize, actualCount); + long dlqSize = dlq.getQueueSize(); + echo("DLQ size: " + dlqSize); - assertEquals("dest has some memory usage", dlqMemUsage, queue.getMemoryPercentUsage()); - } + assertEquals("DLQ size", initialDlqSize - messageCount, dlqSize); + assertEquals("queue size", initialQueueSize, queueSize); + assertEquals("browse queue size", initialQueueSize, actualCount); - public void testMoveMessagesBySelector() throws Exception { - connection = connectionFactory.createConnection(); - useConnection(connection); + assertEquals("dest has some memory usage", dlqMemUsage, queue.getMemoryPercentUsage()); + } - ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString() ); + public void testMoveMessagesBySelector() throws Exception { + connection = connectionFactory.createConnection(); + useConnection(connection); - QueueViewMBean queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); + ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); - String newDestination = getSecondDestinationString(); - queue.moveMatchingMessagesTo("counter > 2", newDestination); + QueueViewMBean queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + newDestination); + String newDestination = getSecondDestinationString(); + queue.moveMatchingMessagesTo("counter > 2", newDestination); - queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - int movedSize = MESSAGE_COUNT-3; - assertEquals("Unexpected number of messages ",movedSize,queue.getQueueSize()); - - // now lets remove them by selector - queue.removeMatchingMessages("counter > 2"); - - assertEquals("Should have no more messages in the queue: " + queueViewMBeanName, 0, queue.getQueueSize()); - assertEquals("dest has no memory usage", 0, queue.getMemoryPercentUsage()); - } - - public void testCopyMessagesBySelector() throws Exception { - connection = connectionFactory.createConnection(); - useConnection(connection); - - ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); + queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + newDestination); + + queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); + int movedSize = MESSAGE_COUNT - 3; + assertEquals("Unexpected number of messages ", movedSize, queue.getQueueSize()); + + // now lets remove them by selector + queue.removeMatchingMessages("counter > 2"); + + assertEquals("Should have no more messages in the queue: " + queueViewMBeanName, 0, queue.getQueueSize()); + assertEquals("dest has no memory usage", 0, queue.getMemoryPercentUsage()); + } + + public void testCopyMessagesBySelector() throws Exception { + connection = connectionFactory.createConnection(); + useConnection(connection); + + ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); + + QueueViewMBean queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); + + String newDestination = getSecondDestinationString(); + long queueSize = queue.getQueueSize(); + assertTrue(queueSize > 0); + queue.copyMatchingMessagesTo("counter > 2", newDestination); + + queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + newDestination); + + queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); + + LOG.info("Queue: " + queueViewMBeanName + " now has: " + queue.getQueueSize() + " message(s)"); + assertEquals("Expected messages in a queue: " + queueViewMBeanName, MESSAGE_COUNT - 3, queue.getQueueSize()); + // now lets remove them by selector + queue.removeMatchingMessages("counter > 2"); + + assertEquals("Should have no more messages in the queue: " + queueViewMBeanName, 0, queue.getQueueSize()); + assertEquals("dest has no memory usage", 0, queue.getMemoryPercentUsage()); + } + + public void testCreateDestinationWithSpacesAtEnds() throws Exception { + ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); + BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); + + assertTrue("broker is not a slave", !broker.isSlave()); + // create 2 topics + broker.addTopic(getDestinationString() + "1 "); + broker.addTopic(" " + getDestinationString() + "2"); + broker.addTopic(" " + getDestinationString() + "3 "); + + assertNotRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Topic,destinationName=" + getDestinationString() + "1 "); + assertNotRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Topic,destinationName= " + getDestinationString() + "2"); + assertNotRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Topic,destinationName= " + getDestinationString() + "3 "); + + ObjectName topicObjName1 = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Topic,destinationName=" + getDestinationString() + "1"); + ObjectName topicObjName2 = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Topic,destinationName=" + getDestinationString() + "2"); + ObjectName topicObjName3 = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Topic,destinationName=" + getDestinationString() + "3"); - QueueViewMBean queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - - String newDestination = getSecondDestinationString(); - long queueSize = queue.getQueueSize(); - assertTrue(queueSize > 0); - queue.copyMatchingMessagesTo("counter > 2", newDestination); - - queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + newDestination); - - queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - - LOG.info("Queue: " + queueViewMBeanName + " now has: " + queue.getQueueSize() + " message(s)"); - assertEquals("Expected messages in a queue: " + queueViewMBeanName, MESSAGE_COUNT-3, queue.getQueueSize()); - // now lets remove them by selector - queue.removeMatchingMessages("counter > 2"); + TopicViewMBean topic1 = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, topicObjName1, TopicViewMBean.class, true); + TopicViewMBean topic2 = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, topicObjName2, TopicViewMBean.class, true); + TopicViewMBean topic3 = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, topicObjName3, TopicViewMBean.class, true); - assertEquals("Should have no more messages in the queue: " + queueViewMBeanName, 0, queue.getQueueSize()); - assertEquals("dest has no memory usage", 0, queue.getMemoryPercentUsage()); - } - - public void testCreateDestinationWithSpacesAtEnds() throws Exception { - ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); - BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); - - assertTrue("broker is not a slave", !broker.isSlave()); - // create 2 topics - broker.addTopic(getDestinationString() + "1 "); - broker.addTopic(" " + getDestinationString() + "2"); - broker.addTopic(" " + getDestinationString() + "3 "); - - - assertNotRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Topic,destinationName=" + getDestinationString() + "1 "); - assertNotRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Topic,destinationName= " + getDestinationString() + "2"); - assertNotRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Topic,destinationName= " + getDestinationString() + "3 "); - - ObjectName topicObjName1 = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Topic,destinationName=" + getDestinationString() + "1"); - ObjectName topicObjName2 = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Topic,destinationName=" + getDestinationString() + "2"); - ObjectName topicObjName3 = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Topic,destinationName=" + getDestinationString() + "3"); + assertEquals("topic1 Durable subscriber count", 0, topic1.getConsumerCount()); + assertEquals("topic2 Durable subscriber count", 0, topic2.getConsumerCount()); + assertEquals("topic3 Durable subscriber count", 0, topic3.getConsumerCount()); - TopicViewMBean topic1 = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, topicObjName1, TopicViewMBean.class, true); - TopicViewMBean topic2 = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, topicObjName2, TopicViewMBean.class, true); - TopicViewMBean topic3 = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, topicObjName3, TopicViewMBean.class, true); + String topicName = getDestinationString(); + String selector = null; - assertEquals("topic1 Durable subscriber count", 0, topic1.getConsumerCount()); - assertEquals("topic2 Durable subscriber count", 0, topic2.getConsumerCount()); - assertEquals("topic3 Durable subscriber count", 0, topic3.getConsumerCount()); + // create 1 subscriber for each topic + broker.createDurableSubscriber(clientID, "topic1.subscriber1", topicName + "1", selector); + broker.createDurableSubscriber(clientID, "topic2.subscriber1", topicName + "2", selector); + broker.createDurableSubscriber(clientID, "topic3.subscriber1", topicName + "3", selector); - String topicName = getDestinationString(); - String selector = null; - - // create 1 subscriber for each topic - broker.createDurableSubscriber(clientID, "topic1.subscriber1", topicName + "1", selector); - broker.createDurableSubscriber(clientID, "topic2.subscriber1", topicName + "2", selector); - broker.createDurableSubscriber(clientID, "topic3.subscriber1", topicName + "3", selector); + assertEquals("topic1 Durable subscriber count", 1, topic1.getConsumerCount()); + assertEquals("topic2 Durable subscriber count", 1, topic2.getConsumerCount()); + assertEquals("topic3 Durable subscriber count", 1, topic3.getConsumerCount()); + } - assertEquals("topic1 Durable subscriber count", 1, topic1.getConsumerCount()); - assertEquals("topic2 Durable subscriber count", 1, topic2.getConsumerCount()); - assertEquals("topic3 Durable subscriber count", 1, topic3.getConsumerCount()); - } + protected void assertSendViaMBean() throws Exception { + String queueName = getDestinationString() + ".SendMBBean"; - protected void assertSendViaMBean() throws Exception { - String queueName = getDestinationString() + ".SendMBBean"; + ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); + echo("Create QueueView MBean..."); + BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); + broker.addQueue(queueName); - ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); - echo("Create QueueView MBean..."); - BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); - broker.addQueue(queueName); + ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + queueName); - ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + queueName); + echo("Create QueueView MBean..."); + QueueViewMBean proxy = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - echo("Create QueueView MBean..."); - QueueViewMBean proxy = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); + proxy.purge(); - proxy.purge(); - - int count = 5; - for (int i = 0; i < count; i++) { - String body = "message:" + i; - - Map headers = new HashMap(); - headers.put("JMSCorrelationID", "MyCorrId"); - headers.put("JMSDeliveryMode", Boolean.FALSE); - headers.put("JMSXGroupID", "MyGroupID"); - headers.put("JMSXGroupSeq", 1234); - headers.put("JMSPriority", i + 1); - headers.put("JMSType", "MyType"); - headers.put("MyHeader", i); - headers.put("MyStringHeader", "StringHeader" + i); - - proxy.sendTextMessage(headers, body); - } - - browseAndVerify(proxy); - } - - private void browseAndVerify(QueueViewMBean proxy) throws Exception { - browseAndVerifyTypes(proxy, false); - } - - @SuppressWarnings("rawtypes") - private void browseAndVerifyTypes(QueueViewMBean proxy, boolean allStrings) throws Exception { - CompositeData[] compdatalist = proxy.browse(); - if (compdatalist.length == 0) { - fail("There is no message in the queue:"); - } - - for (int i = 0; i < compdatalist.length; i++) { - CompositeData cdata = compdatalist[i]; - - if (i == 0) { - echo("Columns: " + cdata.getCompositeType().keySet()); - } - - assertComplexData(i, cdata, "JMSCorrelationID", "MyCorrId"); - assertComplexData(i, cdata, "JMSPriority", i + 1); - assertComplexData(i, cdata, "JMSType", "MyType"); - assertComplexData(i, cdata, "JMSCorrelationID", "MyCorrId"); - assertComplexData(i, cdata, "JMSDeliveryMode", "NON-PERSISTENT"); - String expected = "{MyStringHeader=StringHeader" + i + ", MyHeader=" + i + "}"; - // The order of the properties is different when using the ibm jdk. - if (System.getProperty("java.vendor").equals("IBM Corporation")) { - expected = "{MyHeader=" + i + ", MyStringHeader=StringHeader" + i + "}"; - } - assertComplexData(i, cdata, "PropertiesText", expected); - - if (allStrings) { - Map stringProperties = CompositeDataHelper.getTabularMap(cdata, CompositeDataConstants.STRING_PROPERTIES); - assertEquals("stringProperties size()", 2, stringProperties.size()); - assertEquals("stringProperties.MyHeader", "StringHeader" + i, stringProperties.get("MyStringHeader")); - assertEquals("stringProperties.MyHeader", "" + i, stringProperties.get("MyHeader")); - - } else { - Map intProperties = CompositeDataHelper.getTabularMap(cdata, CompositeDataConstants.INT_PROPERTIES); - assertEquals("intProperties size()", 1, intProperties.size()); - assertEquals("intProperties.MyHeader", i, intProperties.get("MyHeader")); - - Map stringProperties = CompositeDataHelper.getTabularMap(cdata, CompositeDataConstants.STRING_PROPERTIES); - assertEquals("stringProperties size()", 1, stringProperties.size()); - assertEquals("stringProperties.MyHeader", "StringHeader" + i, stringProperties.get("MyStringHeader")); - } - - Map properties = CompositeDataHelper.getMessageUserProperties(cdata); - assertEquals("properties size()", 2, properties.size()); - assertEquals("properties.MyHeader", allStrings ? "" + i : i, properties.get("MyHeader")); - assertEquals("properties.MyHeader", "StringHeader" + i, properties.get("MyStringHeader")); - - assertComplexData(i, cdata, "JMSXGroupSeq", 1234); - assertComplexData(i, cdata, "JMSXGroupID", "MyGroupID"); - assertComplexData(i, cdata, "Text", "message:" + i); - } - } - - protected void assertSendCsnvViaMBean() throws Exception { - String queueName = getDestinationString() + ".SendMBBean"; - - ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); - echo("Create QueueView MBean..."); - BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); - broker.addQueue(queueName); - - ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + queueName); - - echo("Create QueueView MBean..."); - QueueViewMBean proxy = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - - proxy.purge(); - - int count = 5; - for (int i = 0; i < count; i++) { - String props = "body=message:" + i; - - props += ",JMSCorrelationID=MyCorrId"; - props += ",JMSDeliveryMode=1"; - props += ",JMSXGroupID=MyGroupID"; - props += ",JMSXGroupSeq=1234"; - props += ",JMSPriority=" + (i + 1); - props += ",JMSType=MyType"; - props += ",MyHeader=" + i; - props += ",MyStringHeader=StringHeader" + i; - - proxy.sendTextMessageWithProperties(props); - } - - browseAndVerifyTypes(proxy, true); - } - - protected void assertComplexData(int messageIndex, CompositeData cdata, String name, Object expected) { - Object value = cdata.get(name); - assertEquals("Message " + messageIndex + " CData field: " + name, expected, value); - } - - protected void assertQueueBrowseWorks() throws Exception { - Integer mbeancnt = mbeanServer.getMBeanCount(); - echo("Mbean count :" + mbeancnt); - - ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); - - echo("Create QueueView MBean..."); - QueueViewMBean proxy = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - - long concount = proxy.getConsumerCount(); - echo("Consumer Count :" + concount); - long messcount = proxy.getQueueSize(); - echo("current number of messages in the queue :" + messcount); - - // lets browse - CompositeData[] compdatalist = proxy.browse(); - if (compdatalist.length == 0) { - fail("There is no message in the queue:"); - } - String[] messageIDs = new String[compdatalist.length]; - - for (int i = 0; i < compdatalist.length; i++) { - CompositeData cdata = compdatalist[i]; - - if (i == 0) { - echo("Columns: " + cdata.getCompositeType().keySet()); - } - messageIDs[i] = (String)cdata.get("JMSMessageID"); - echo("message " + i + " : " + cdata.values()); - } - - TabularData table = proxy.browseAsTable(); - echo("Found tabular data: " + table); - assertTrue("Table should not be empty!", table.size() > 0); - - assertEquals("Queue size", MESSAGE_COUNT, proxy.getQueueSize()); - - String messageID = messageIDs[0]; - String newDestinationName = "queue://dummy.test.cheese"; - echo("Attempting to copy: " + messageID + " to destination: " + newDestinationName); - proxy.copyMessageTo(messageID, newDestinationName); - - assertEquals("Queue size", MESSAGE_COUNT, proxy.getQueueSize()); - - messageID = messageIDs[1]; - echo("Attempting to remove: " + messageID); - proxy.removeMessage(messageID); - - assertEquals("Queue size", MESSAGE_COUNT-1, proxy.getQueueSize()); - - echo("Worked!"); - } - - protected void assertCreateAndDestroyDurableSubscriptions() throws Exception { - // lets create a new topic - ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); - echo("Create QueueView MBean..."); - BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); - - broker.addTopic(getDestinationString()); - - assertEquals("Durable subscriber count", 0, broker.getDurableTopicSubscribers().length); - - String topicName = getDestinationString(); - String selector = null; - ObjectName name1 = broker.createDurableSubscriber(clientID, "subscriber1", topicName, selector); - broker.createDurableSubscriber(clientID, "subscriber2", topicName, selector); - assertEquals("Durable subscriber count", 2, broker.getInactiveDurableTopicSubscribers().length); - - assertNotNull("Should have created an mbean name for the durable subscriber!", name1); - - LOG.info("Created durable subscriber with name: " + name1); - - // now lets try destroy it - broker.destroyDurableSubscriber(clientID, "subscriber1"); - assertEquals("Durable subscriber count", 1, broker.getInactiveDurableTopicSubscribers().length); - } - - protected void assertConsumerCounts() throws Exception { - ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); - BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); - - assertTrue("broker is not a slave", !broker.isSlave()); - // create 2 topics - broker.addTopic(getDestinationString() + "1"); - broker.addTopic(getDestinationString() + "2"); - - ObjectName topicObjName1 = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Topic,destinationName=" + getDestinationString() + "1"); - ObjectName topicObjName2 = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Topic,destinationName=" + getDestinationString() + "2"); - TopicViewMBean topic1 = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, topicObjName1, TopicViewMBean.class, true); - TopicViewMBean topic2 = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, topicObjName2, TopicViewMBean.class, true); - - assertEquals("topic1 Durable subscriber count", 0, topic1.getConsumerCount()); - assertEquals("topic2 Durable subscriber count", 0, topic2.getConsumerCount()); - - String topicName = getDestinationString(); - String selector = null; - - // create 1 subscriber for each topic - broker.createDurableSubscriber(clientID, "topic1.subscriber1", topicName + "1", selector); - broker.createDurableSubscriber(clientID, "topic2.subscriber1", topicName + "2", selector); - - assertEquals("topic1 Durable subscriber count", 1, topic1.getConsumerCount()); - assertEquals("topic2 Durable subscriber count", 1, topic2.getConsumerCount()); - - // create 1 more subscriber for topic1 - broker.createDurableSubscriber(clientID, "topic1.subscriber2", topicName + "1", selector); - - assertEquals("topic1 Durable subscriber count", 2, topic1.getConsumerCount()); - assertEquals("topic2 Durable subscriber count", 1, topic2.getConsumerCount()); - - // destroy topic1 subscriber - broker.destroyDurableSubscriber(clientID, "topic1.subscriber1"); - - assertEquals("topic1 Durable subscriber count", 1, topic1.getConsumerCount()); - assertEquals("topic2 Durable subscriber count", 1, topic2.getConsumerCount()); - - // destroy topic2 subscriber - broker.destroyDurableSubscriber(clientID, "topic2.subscriber1"); - - assertEquals("topic1 Durable subscriber count", 1, topic1.getConsumerCount()); - assertEquals("topic2 Durable subscriber count", 0, topic2.getConsumerCount()); - - // destroy remaining topic1 subscriber - broker.destroyDurableSubscriber(clientID, "topic1.subscriber2"); - - assertEquals("topic1 Durable subscriber count", 0, topic1.getConsumerCount()); - assertEquals("topic2 Durable subscriber count", 0, topic2.getConsumerCount()); - } - - protected void assertProducerCounts() throws Exception { - ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); - BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); - - assertTrue("broker is not a slave", !broker.isSlave()); - // create 2 topics - broker.addTopic(getDestinationString() + "1"); - broker.addTopic(getDestinationString() + "2"); - - ObjectName topicObjName1 = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Topic,destinationName=" + getDestinationString() + "1"); - ObjectName topicObjName2 = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Topic,destinationName=" + getDestinationString() + "2"); - TopicViewMBean topic1 = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, topicObjName1, TopicViewMBean.class, true); - TopicViewMBean topic2 = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, topicObjName2, TopicViewMBean.class, true); - - assertEquals("topic1 Producer count", 0, topic1.getProducerCount()); - assertEquals("topic2 Producer count", 0, topic2.getProducerCount()); - assertEquals("broker Topic Producer count", 0, broker.getTopicProducers().length); - - // create 1 producer for each topic - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination dest1 = session.createTopic(getDestinationString() + "1"); - Destination dest2 = session.createTopic(getDestinationString() + "2"); - MessageProducer producer1 = session.createProducer(dest1); - MessageProducer producer2 = session.createProducer(dest2); - Thread.sleep(500); - - assertEquals("topic1 Producer count", 1, topic1.getProducerCount()); - assertEquals("topic2 Producer count", 1, topic2.getProducerCount()); - - assertEquals("broker Topic Producer count", 2, broker.getTopicProducers().length); - - // create 1 more producer for topic1 - MessageProducer producer3 = session.createProducer(dest1); - Thread.sleep(500); - - assertEquals("topic1 Producer count", 2, topic1.getProducerCount()); - assertEquals("topic2 Producer count", 1, topic2.getProducerCount()); - - assertEquals("broker Topic Producer count", 3, broker.getTopicProducers().length); - - // destroy topic1 producer - producer1.close(); - Thread.sleep(500); - - assertEquals("topic1 Producer count", 1, topic1.getProducerCount()); - assertEquals("topic2 Producer count", 1, topic2.getProducerCount()); - - assertEquals("broker Topic Producer count", 2, broker.getTopicProducers().length); - - // destroy topic2 producer - producer2.close(); - Thread.sleep(500); - - assertEquals("topic1 Producer count", 1, topic1.getProducerCount()); - assertEquals("topic2 Producer count", 0, topic2.getProducerCount()); - - assertEquals("broker Topic Producer count", 1, broker.getTopicProducers().length); - - // destroy remaining topic1 producer - producer3.close(); - Thread.sleep(500); - - assertEquals("topic1 Producer count", 0, topic1.getProducerCount()); - assertEquals("topic2 Producer count", 0, topic2.getProducerCount()); - - MessageProducer producer4 = session.createProducer(null); - Thread.sleep(500); - assertEquals(1, broker.getDynamicDestinationProducers().length); - producer4.close(); - Thread.sleep(500); - - assertEquals("broker Topic Producer count", 0, broker.getTopicProducers().length); - } - - protected ObjectName assertRegisteredObjectName(String name) throws MalformedObjectNameException, Exception { - final ObjectName objectName = new ObjectName(name); - final AtomicBoolean result = new AtomicBoolean(false); - assertTrue("Bean registered: " + objectName, Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - try { - result.set(mbeanServer.isRegistered(objectName)); - } catch (Exception ignored) { - LOG.debug(ignored.toString()); - } - return result.get(); - } - })); - return objectName; - } - - protected ObjectName assertNotRegisteredObjectName(String name) throws MalformedObjectNameException, NullPointerException { - ObjectName objectName = new ObjectName(name); - if (mbeanServer.isRegistered(objectName)) { - fail("Found the MBean!: " + objectName); - } else { - echo("Bean not registered Registered: " + objectName); - } - return objectName; - } - - @Override - protected void setUp() throws Exception { - bindAddress = "tcp://localhost:0"; - useTopic = false; - super.setUp(); - ManagementContext managementContext = broker.getManagementContext(); - mbeanServer = managementContext.getMBeanServer(); - } - - @Override - protected void tearDown() throws Exception { - if (waitForKeyPress) { - // We are running from the command line so let folks browse the - // mbeans... - System.out.println(); - System.out.println("Press enter to terminate the program."); - System.out.println("In the meantime you can use your JMX console to view the current MBeans"); - BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); - reader.readLine(); - } - - if (connection != null) { - connection.close(); - connection = null; - } - super.tearDown(); - } - - @Override - protected ConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString()); - } - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setPersistent(false); - answer.setDeleteAllMessagesOnStartup(true); - answer.setUseJmx(true); - - // apply memory limit so that %usage is visible - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setMemoryLimit(1024*1024*4); - policyMap.setDefaultEntry(defaultEntry); - answer.setDestinationPolicy(policyMap); - - // allow options to be visible via jmx - answer.setDestinations(new ActiveMQDestination[]{new ActiveMQQueue(QUEUE_WITH_OPTIONS + "?topQueue=true&hasOptions=2")}); - - answer.addConnector(bindAddress); - return answer; - } - - protected void useConnection(Connection connection) throws Exception { - connection.setClientID(clientID); - connection.start(); - Session session = connection.createSession(transacted, authMode); - destination = createDestination(); - MessageProducer producer = session.createProducer(destination); - for (int i = 0; i < MESSAGE_COUNT; i++) { - Message message = session.createTextMessage("Message: " + i); - message.setIntProperty("counter", i); - message.setJMSCorrelationID("MyCorrelationID"); - message.setJMSReplyTo(new ActiveMQQueue("MyReplyTo")); - message.setJMSType("MyType"); - message.setJMSPriority(5); - producer.send(message); - } - Thread.sleep(1000); - } - - protected void useConnectionWithBlobMessage(Connection connection) throws Exception { - connection.setClientID(clientID); - connection.start(); - ActiveMQSession session = (ActiveMQSession) connection.createSession(transacted, authMode); - destination = createDestination(); - MessageProducer producer = session.createProducer(destination); - for (int i = 0; i < MESSAGE_COUNT; i++) { - BlobMessage message = session.createBlobMessage(new URL("http://foo.bar/test")); - message.setIntProperty("counter", i); - message.setJMSCorrelationID("MyCorrelationID"); - message.setJMSReplyTo(new ActiveMQQueue("MyReplyTo")); - message.setJMSType("MyType"); - message.setJMSPriority(5); - producer.send(message); - } - Thread.sleep(1000); - } - - protected void useConnectionWithByteMessage(Connection connection) throws Exception { - connection.setClientID(clientID); - connection.start(); - ActiveMQSession session = (ActiveMQSession) connection.createSession(transacted, authMode); - destination = createDestination(); - MessageProducer producer = session.createProducer(destination); - for (int i = 0; i < MESSAGE_COUNT; i++) { - BytesMessage message = session.createBytesMessage(); - message.writeBytes(("Message: " + i).getBytes()); - message.setIntProperty("counter", i); - message.setJMSCorrelationID("MyCorrelationID"); - message.setJMSReplyTo(new ActiveMQQueue("MyReplyTo")); - message.setJMSType("MyType"); - message.setJMSPriority(5); - producer.send(message); - } - Thread.sleep(1000); - } - - protected void echo(String text) { - //LOG.info(text); - } - - protected String getSecondDestinationString() { - return "test.new.destination." + getClass() + "." + getName(); - } - - public void testDynamicProducerView() throws Exception { - connection = connectionFactory.createConnection(); - - ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); - BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); - - assertEquals(0, broker.getDynamicDestinationProducers().length); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); - - Destination dest1 = session.createTopic("DynamicDest-1"); - Destination dest2 = session.createTopic("DynamicDest-2"); - Destination dest3 = session.createQueue("DynamicDest-3"); - - // Wait a bit to let the producer get registered. - Thread.sleep(100); - - assertEquals(1, broker.getDynamicDestinationProducers().length); - - ObjectName viewName = broker.getDynamicDestinationProducers()[0]; - assertNotNull(viewName); - ProducerViewMBean view = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, viewName, ProducerViewMBean.class, true); - assertNotNull(view); - - assertEquals("NOTSET", view.getDestinationName()); - - producer.send(dest1, session.createTextMessage("Test Message 1")); - Thread.sleep(200); - assertEquals(((ActiveMQDestination)dest1).getPhysicalName(), view.getDestinationName()); - assertTrue(view.isDestinationTopic()); - assertFalse(view.isDestinationQueue()); - assertFalse(view.isDestinationTemporary()); - - producer.send(dest2, session.createTextMessage("Test Message 2")); - Thread.sleep(200); - assertEquals(((ActiveMQDestination)dest2).getPhysicalName(), view.getDestinationName()); - assertTrue(view.isDestinationTopic()); - assertFalse(view.isDestinationQueue()); - assertFalse(view.isDestinationTemporary()); - - producer.send(dest3, session.createTextMessage("Test Message 3")); - Thread.sleep(200); - assertEquals(((ActiveMQDestination)dest3).getPhysicalName(), view.getDestinationName()); - assertTrue(view.isDestinationQueue()); - assertFalse(view.isDestinationTopic()); - assertFalse(view.isDestinationTemporary()); - - producer.close(); - Thread.sleep(200); - assertEquals(0, broker.getDynamicDestinationProducers().length); - } - - public void testTempQueueJMXDelete() throws Exception { - connection = connectionFactory.createConnection(); - - connection.setClientID(clientID); - connection.start(); - Session session = connection.createSession(transacted, authMode); - ActiveMQTempQueue tQueue = (ActiveMQTempQueue) session.createTemporaryQueue(); - Thread.sleep(1000); - - ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=" - + JMXSupport.encodeObjectNamePart(tQueue.getDestinationTypeAsString()) - + ",destinationName=" + JMXSupport.encodeObjectNamePart(tQueue.getPhysicalName())); - - // should not throw an exception - - mbeanServer.getObjectInstance(queueViewMBeanName); - - tQueue.delete(); - Thread.sleep(1000); - try { - // should throw an exception - mbeanServer.getObjectInstance(queueViewMBeanName); - - fail("should be deleted already!"); - } catch (Exception e) { - // expected! - } - } - - // Test for AMQ-3029 - public void testBrowseBlobMessages() throws Exception { - connection = connectionFactory.createConnection(); - useConnectionWithBlobMessage(connection); - - ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); - - QueueViewMBean queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - - CompositeData[] compdatalist = queue.browse(); - int initialQueueSize = compdatalist.length; - if (initialQueueSize == 0) { - fail("There is no message in the queue:"); - } - else { - echo("Current queue size: " + initialQueueSize); - } - int messageCount = initialQueueSize; - String[] messageIDs = new String[messageCount]; - for (int i = 0; i < messageCount; i++) { - CompositeData cdata = compdatalist[i]; - String messageID = (String) cdata.get("JMSMessageID"); - assertNotNull("Should have a message ID for message " + i, messageID); - - messageIDs[i] = messageID; - } - - assertTrue("dest has some memory usage", queue.getMemoryPercentUsage() > 0); - } - - public void testDestinationOptionsAreVisible() throws Exception { - ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + QUEUE_WITH_OPTIONS ); - - QueueViewMBean queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - - assertEquals("name match", QUEUE_WITH_OPTIONS, queue.getName()); - - String options = queue.getOptions(); - LOG.info("Got options: " + options); - - Map optionsMap = URISupport.parseQuery(options); - assertEquals("got a map", 2, optionsMap.size()); - assertTrue("matches our options", optionsMap.containsKey("hasOptions")); - assertTrue("matches our options", optionsMap.containsKey("topQueue")); - - assertTrue("matches our options", optionsMap.containsValue("true")); - assertTrue("matches our options", optionsMap.containsValue("2")); - } - - public void testSubscriptionViewToConnectionMBean() throws Exception { - - connection = connectionFactory.createConnection("admin", "admin"); - connection.setClientID("MBeanTest"); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination queue = session.createQueue(getDestinationString() + ".Queue"); - MessageConsumer queueConsumer = session.createConsumer(queue); - MessageProducer producer = session.createProducer(queue); - - ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); - BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); - - Thread.sleep(100); - - assertTrue(broker.getQueueSubscribers().length == 1); - - ObjectName subscriptionName = broker.getQueueSubscribers()[0]; - LOG.info("Looking for Subscription: " + subscriptionName); - - SubscriptionViewMBean subscriberView = - MBeanServerInvocationHandler.newProxyInstance( - mbeanServer, subscriptionName, SubscriptionViewMBean.class, true); - assertNotNull(subscriberView); - - ObjectName connectionName = subscriberView.getConnection(); - LOG.info("Looking for Connection: " + connectionName); - assertNotNull(connectionName); - ConnectionViewMBean connectionView = - MBeanServerInvocationHandler.newProxyInstance( - mbeanServer, connectionName, ConnectionViewMBean.class, true); - assertNotNull(connectionView); - - // Our consumer plus one advisory consumer. - assertEquals(2, connectionView.getConsumers().length); - - assertEquals("client id match", "MBeanTest", connectionView.getClientId()); - - // Check that the subscription view we found earlier is in this list. - boolean found = false; - for (ObjectName name : connectionView.getConsumers()) { - if (name.equals(subscriptionName)) { - found = true; - } - } - assertTrue("We should have found: " + subscriptionName, found); - - // Our producer and no others. - assertEquals(1, connectionView.getProducers().length); - - // Bean should detect the updates. - queueConsumer.close(); - producer.close(); - - Thread.sleep(200); - - // Only an advisory consumers now. - assertEquals(1, connectionView.getConsumers().length); - assertEquals(0, connectionView.getProducers().length); - } - - public void testCreateAndUnsubscribeDurableSubscriptions() throws Exception { - - connection = connectionFactory.createConnection("admin", "admin"); - connection.setClientID("MBeanTest"); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - String topicName = getDestinationString() + ".DurableTopic"; - Topic topic = session.createTopic(topicName); - - ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); - echo("Create QueueView MBean..."); - BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); - - assertEquals("Durable subscriber count", 0, broker.getDurableTopicSubscribers().length); - assertEquals("Durable subscriber count", 0, broker.getInactiveDurableTopicSubscribers().length); - - MessageConsumer durableConsumer1 = session.createDurableSubscriber(topic, "subscription1"); - MessageConsumer durableConsumer2 = session.createDurableSubscriber(topic, "subscription2"); - - Thread.sleep(100); - - assertEquals("Durable subscriber count", 2, broker.getDurableTopicSubscribers().length); - assertEquals("Durable subscriber count", 0, broker.getInactiveDurableTopicSubscribers().length); - - durableConsumer1.close(); - durableConsumer2.close(); - - Thread.sleep(100); - - assertEquals("Durable subscriber count", 0, broker.getDurableTopicSubscribers().length); - assertEquals("Durable subscriber count", 2, broker.getInactiveDurableTopicSubscribers().length); - - session.unsubscribe("subscription1"); - - Thread.sleep(100); - - assertEquals("Inactive Durable subscriber count", 1, broker.getInactiveDurableTopicSubscribers().length); - - session.unsubscribe("subscription2"); - - assertEquals("Inactive Durable subscriber count", 0, broker.getInactiveDurableTopicSubscribers().length); - } - - public void testUserNamePopulated() throws Exception { - doTestUserNameInMBeans(true); - } - - public void testUserNameNotPopulated() throws Exception { - doTestUserNameInMBeans(false); - } - - @SuppressWarnings("unused") - private void doTestUserNameInMBeans(boolean expect) throws Exception { - broker.setPopulateUserNameInMBeans(expect); - - connection = connectionFactory.createConnection("admin", "admin"); - connection.setClientID("MBeanTest"); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination queue = session.createQueue(getDestinationString() + ".Queue"); - Topic topic = session.createTopic(getDestinationString() + ".Topic"); - MessageProducer producer = session.createProducer(queue); - MessageConsumer queueConsumer = session.createConsumer(queue); - MessageConsumer topicConsumer = session.createConsumer(topic); - MessageConsumer durable = session.createDurableSubscriber(topic, "Durable"); - - ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); - BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); - - Thread.sleep(100); - - assertTrue(broker.getQueueProducers().length == 1); - assertTrue(broker.getTopicSubscribers().length == 2); - assertTrue(broker.getQueueSubscribers().length == 1); - - ObjectName producerName = broker.getQueueProducers()[0]; - ProducerViewMBean producerView = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, producerName, ProducerViewMBean.class, true); - assertNotNull(producerView); - - if (expect) { - assertEquals("admin", producerView.getUserName()); - } else { - assertNull(producerView.getUserName()); - } - - for (ObjectName name : broker.getTopicSubscribers()) { - SubscriptionViewMBean subscriberView = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, name, SubscriptionViewMBean.class, true); - if (expect) { - assertEquals("admin", subscriberView.getUserName()); - } else { - assertNull(subscriberView.getUserName()); - } - } - - for (ObjectName name : broker.getQueueSubscribers()) { - SubscriptionViewMBean subscriberView = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, name, SubscriptionViewMBean.class, true); - if (expect) { - assertEquals("admin", subscriberView.getUserName()); - } else { - assertNull(subscriberView.getUserName()); - } - } - ObjectName query = //new ObjectName(domain + ":type=Broker,brokerName=localhost,connector=*," + "connectorName=*,connectionName=MBeanTest"); - BrokerMBeanSupport.createConnectionQuery(domain, "localhost", connection.getClientID()); - - Set names = mbeanServer.queryNames(query, null); - boolean found = false; - for (ObjectName name : names) { - if (name.toString().endsWith("connectionName=MBeanTest")) { - - ConnectionViewMBean connectionView = - MBeanServerInvocationHandler.newProxyInstance(mbeanServer, name, ConnectionViewMBean.class, true); - assertNotNull(connectionView); - - if (expect) { - assertEquals("admin", connectionView.getUserName()); - } else { - assertNull(connectionView.getUserName()); - } - - found = true; - break; - } - } - - assertTrue("Should find the connection's ManagedTransportConnection", found); - } - - public void testMoveMessagesToRetainOrder() throws Exception { - connection = connectionFactory.createConnection(); - useConnection(connection); - - ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); - - QueueViewMBean queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - - String newDestination = getSecondDestinationString(); - queue.moveMatchingMessagesTo("", newDestination); - - queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + newDestination); - - queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - int movedSize = MESSAGE_COUNT; - assertEquals("Unexpected number of messages ",movedSize,queue.getQueueSize()); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(newDestination); - MessageConsumer consumer = session.createConsumer(destination); - - int last = -1; - int current = -1; - Message message = null; - while ((message = consumer.receive(2000)) != null) { - if (message.propertyExists("counter")) { - current = message.getIntProperty("counter"); - assertEquals(last, current - 1); - last = current; - } - } - - // now lets remove them by selector - queue.removeMatchingMessages(""); - - assertEquals("Should have no more messages in the queue: " + queueViewMBeanName, 0, queue.getQueueSize()); - assertEquals("dest has no memory usage", 0, queue.getMemoryPercentUsage()); - } - - public void testConnectionCounts() throws Exception { - - ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); - BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); - - assertEquals(0, broker.getCurrentConnectionsCount()); - - connection = connectionFactory.createConnection(); - useConnection(connection); - - assertEquals(1, broker.getCurrentConnectionsCount()); - connection.close(); - assertEquals(0, broker.getCurrentConnectionsCount()); - assertEquals(1, broker.getTotalConnectionsCount()); - } - - public void testCopyMessagesToRetainOrder() throws Exception { - connection = connectionFactory.createConnection(); - useConnection(connection); - - ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); - - QueueViewMBean queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - - String newDestination = getSecondDestinationString(); - queue.copyMatchingMessagesTo("", newDestination); - - queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + newDestination ); - - queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - int movedSize = MESSAGE_COUNT; - assertEquals("Unexpected number of messages ",movedSize,queue.getQueueSize()); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(newDestination); - MessageConsumer consumer = session.createConsumer(destination); - - int last = -1; - int current = -1; - Message message = null; - while ((message = consumer.receive(2000)) != null) { - if (message.propertyExists("counter")) { - current = message.getIntProperty("counter"); - assertEquals(last, current - 1); - last = current; - } - } - - // now lets remove them by selector - queue.removeMatchingMessages(""); - - assertEquals("Should have no more messages in the queue: " + queueViewMBeanName, 0, queue.getQueueSize()); - assertEquals("dest has no memory usage", 0, queue.getMemoryPercentUsage()); - } - - public void testRemoveMatchingMessageRetainOrder() throws Exception { - connection = connectionFactory.createConnection(); - useConnection(connection); - - ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); - - QueueViewMBean queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - - String queueName = getDestinationString(); - queue.removeMatchingMessages("counter < 10"); - - int newSize = MESSAGE_COUNT - 10; - assertEquals("Unexpected number of messages ", newSize, queue.getQueueSize()); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(queueName); - MessageConsumer consumer = session.createConsumer(destination); - - int last = 9; - int current = 0; - Message message = null; - while ((message = consumer.receive(2000)) != null) { - if (message.propertyExists("counter")) { - current = message.getIntProperty("counter"); - assertEquals(last, current - 1); - last = current; - } - } - - // now lets remove them by selector - queue.removeMatchingMessages(""); - - assertEquals("Should have no more messages in the queue: " + queueViewMBeanName, 0, queue.getQueueSize()); - assertEquals("dest has no memory usage", 0, queue.getMemoryPercentUsage()); - } - - public void testBrowseBytesMessages() throws Exception { - connection = connectionFactory.createConnection(); - useConnectionWithByteMessage(connection); - - ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); - - QueueViewMBean queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - - CompositeData[] compdatalist = queue.browse(); - int initialQueueSize = compdatalist.length; - if (initialQueueSize == 0) { - fail("There is no message in the queue:"); - } - else { - echo("Current queue size: " + initialQueueSize); - } - int messageCount = initialQueueSize; - String[] messageIDs = new String[messageCount]; - for (int i = 0; i < messageCount; i++) { - CompositeData cdata = compdatalist[i]; - String messageID = (String) cdata.get("JMSMessageID"); - assertNotNull("Should have a message ID for message " + i, messageID); - messageIDs[i] = messageID; - - Byte[] preview = (Byte[]) cdata.get(CompositeDataConstants.BODY_PREVIEW); - assertNotNull("should be a preview", preview); - assertTrue("not empty", preview.length > 0); - } - - assertTrue("dest has some memory usage", queue.getMemoryPercentUsage() > 0); - - // consume all the messages - echo("Attempting to consume all bytes messages from: " + destination); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); - for (int i=0; i headers = new HashMap(); + headers.put("JMSCorrelationID", "MyCorrId"); + headers.put("JMSDeliveryMode", Boolean.FALSE); + headers.put("JMSXGroupID", "MyGroupID"); + headers.put("JMSXGroupSeq", 1234); + headers.put("JMSPriority", i + 1); + headers.put("JMSType", "MyType"); + headers.put("MyHeader", i); + headers.put("MyStringHeader", "StringHeader" + i); + + proxy.sendTextMessage(headers, body); + } + + browseAndVerify(proxy); + } + + private void browseAndVerify(QueueViewMBean proxy) throws Exception { + browseAndVerifyTypes(proxy, false); + } + + @SuppressWarnings("rawtypes") + private void browseAndVerifyTypes(QueueViewMBean proxy, boolean allStrings) throws Exception { + CompositeData[] compdatalist = proxy.browse(); + if (compdatalist.length == 0) { + fail("There is no message in the queue:"); + } + + for (int i = 0; i < compdatalist.length; i++) { + CompositeData cdata = compdatalist[i]; + + if (i == 0) { + echo("Columns: " + cdata.getCompositeType().keySet()); + } + + assertComplexData(i, cdata, "JMSCorrelationID", "MyCorrId"); + assertComplexData(i, cdata, "JMSPriority", i + 1); + assertComplexData(i, cdata, "JMSType", "MyType"); + assertComplexData(i, cdata, "JMSCorrelationID", "MyCorrId"); + assertComplexData(i, cdata, "JMSDeliveryMode", "NON-PERSISTENT"); + String expected = "{MyStringHeader=StringHeader" + i + ", MyHeader=" + i + "}"; + // The order of the properties is different when using the ibm jdk. + if (System.getProperty("java.vendor").equals("IBM Corporation")) { + expected = "{MyHeader=" + i + ", MyStringHeader=StringHeader" + i + "}"; + } + assertComplexData(i, cdata, "PropertiesText", expected); + + if (allStrings) { + Map stringProperties = CompositeDataHelper.getTabularMap(cdata, CompositeDataConstants.STRING_PROPERTIES); + assertEquals("stringProperties size()", 2, stringProperties.size()); + assertEquals("stringProperties.MyHeader", "StringHeader" + i, stringProperties.get("MyStringHeader")); + assertEquals("stringProperties.MyHeader", "" + i, stringProperties.get("MyHeader")); + + } + else { Map intProperties = CompositeDataHelper.getTabularMap(cdata, CompositeDataConstants.INT_PROPERTIES); - assertTrue("not empty", intProperties.size() > 0); - assertEquals("counter in order", i, intProperties.get("counter")); - } + assertEquals("intProperties size()", 1, intProperties.size()); + assertEquals("intProperties.MyHeader", i, intProperties.get("MyHeader")); - echo("Attempting to consume 5 bytes messages from: " + destination); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); - for (int i=0; i<5; i++) { - Message message = consumer.receive(5000); - assertNotNull(message); - assertEquals("ordered", i, message.getIntProperty("counter")); - echo("Consumed: " + message.getIntProperty("counter")); - } - consumer.close(); - session.close(); - connection.close(); + Map stringProperties = CompositeDataHelper.getTabularMap(cdata, CompositeDataConstants.STRING_PROPERTIES); + assertEquals("stringProperties size()", 1, stringProperties.size()); + assertEquals("stringProperties.MyHeader", "StringHeader" + i, stringProperties.get("MyStringHeader")); + } - // browse again and verify order - compdatalist = queue.browse(); - initialQueueSize = compdatalist.length; - assertEquals("5 gone", MESSAGE_COUNT - 5, initialQueueSize); + Map properties = CompositeDataHelper.getMessageUserProperties(cdata); + assertEquals("properties size()", 2, properties.size()); + assertEquals("properties.MyHeader", allStrings ? "" + i : i, properties.get("MyHeader")); + assertEquals("properties.MyHeader", "StringHeader" + i, properties.get("MyStringHeader")); - messageCount = initialQueueSize; - for (int i = 0; i < messageCount - 4; i++) { - CompositeData cdata = compdatalist[i]; + assertComplexData(i, cdata, "JMSXGroupSeq", 1234); + assertComplexData(i, cdata, "JMSXGroupID", "MyGroupID"); + assertComplexData(i, cdata, "Text", "message:" + i); + } + } - Map intProperties = CompositeDataHelper.getTabularMap(cdata, CompositeDataConstants.INT_PROPERTIES); - assertTrue("not empty", intProperties.size() > 0); - assertEquals("counter in order", i + 5, intProperties.get("counter")); - echo("Got: " + intProperties.get("counter")); - } - } + protected void assertSendCsnvViaMBean() throws Exception { + String queueName = getDestinationString() + ".SendMBBean"; - public void testAddRemoveConnectorBrokerView() throws Exception { + ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); + echo("Create QueueView MBean..."); + BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); + broker.addQueue(queueName); - ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); - BrokerViewMBean brokerView = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); + ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + queueName); - Map connectors = brokerView.getTransportConnectors(); - LOG.info("Connectors: " + connectors); - assertEquals("one connector", 1, connectors.size()); + echo("Create QueueView MBean..."); + QueueViewMBean proxy = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - ConnectorViewMBean connector = getProxyToConnectionView("tcp"); - assertNotNull(connector); + proxy.purge(); - String name = connectors.keySet().iterator().next().toString(); + int count = 5; + for (int i = 0; i < count; i++) { + String props = "body=message:" + i; - brokerView.removeConnector(name); + props += ",JMSCorrelationID=MyCorrId"; + props += ",JMSDeliveryMode=1"; + props += ",JMSXGroupID=MyGroupID"; + props += ",JMSXGroupSeq=1234"; + props += ",JMSPriority=" + (i + 1); + props += ",JMSType=MyType"; + props += ",MyHeader=" + i; + props += ",MyStringHeader=StringHeader" + i; - connectors = brokerView.getTransportConnectors(); - assertEquals("empty", 0, connectors.size()); + proxy.sendTextMessageWithProperties(props); + } - name = brokerView.addConnector("tcp://0.0.0.0:0"); + browseAndVerifyTypes(proxy, true); + } - connector = getProxyToConnectionView("tcp"); - assertNotNull(connector); + protected void assertComplexData(int messageIndex, CompositeData cdata, String name, Object expected) { + Object value = cdata.get(name); + assertEquals("Message " + messageIndex + " CData field: " + name, expected, value); + } - connectors = brokerView.getTransportConnectors(); - LOG.info("Connectors: " + connectors); - assertEquals("one connector", 1, connectors.size()); - assertTrue("name is in map: " + connectors.keySet(), connectors.keySet().contains(name)); - } + protected void assertQueueBrowseWorks() throws Exception { + Integer mbeancnt = mbeanServer.getMBeanCount(); + echo("Mbean count :" + mbeancnt); - public void testConnectorView() throws Exception { - ConnectorViewMBean connector = getProxyToConnectionView("tcp"); - assertNotNull(connector); + ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); - assertFalse(connector.isRebalanceClusterClients()); - assertFalse(connector.isUpdateClusterClientsOnRemove()); - assertFalse(connector.isUpdateClusterClients()); - assertFalse(connector.isAllowLinkStealingEnabled()); - } + echo("Create QueueView MBean..."); + QueueViewMBean proxy = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - protected ConnectorViewMBean getProxyToConnectionView(String connectionType) throws Exception { - ObjectName connectorQuery = new ObjectName( - "org.apache.activemq:type=Broker,brokerName=localhost,connector=clientConnectors,connectorName="+connectionType+"_//*"); + long concount = proxy.getConsumerCount(); + echo("Consumer Count :" + concount); + long messcount = proxy.getQueueSize(); + echo("current number of messages in the queue :" + messcount); - Set results = broker.getManagementContext().queryNames(connectorQuery, null); + // lets browse + CompositeData[] compdatalist = proxy.browse(); + if (compdatalist.length == 0) { + fail("There is no message in the queue:"); + } + String[] messageIDs = new String[compdatalist.length]; - if (results == null || results.isEmpty() || results.size() > 1) { - throw new Exception("Unable to find the exact Connector instance."); - } + for (int i = 0; i < compdatalist.length; i++) { + CompositeData cdata = compdatalist[i]; - ConnectorViewMBean proxy = (ConnectorViewMBean) broker.getManagementContext() - .newProxyInstance(results.iterator().next(), ConnectorViewMBean.class, true); - return proxy; - } + if (i == 0) { + echo("Columns: " + cdata.getCompositeType().keySet()); + } + messageIDs[i] = (String) cdata.get("JMSMessageID"); + echo("message " + i + " : " + cdata.values()); + } - public void testDynamicProducers() throws Exception { - connection = connectionFactory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); + TabularData table = proxy.browseAsTable(); + echo("Found tabular data: " + table); + assertTrue("Table should not be empty!", table.size() > 0); - ObjectName query = new ObjectName(domain + ":type=Broker,brokerName=localhost,endpoint=dynamicProducer,*"); - Set mbeans = mbeanServer.queryMBeans(query, null); - assertEquals(mbeans.size(), 1); - producer.close(); - } + assertEquals("Queue size", MESSAGE_COUNT, proxy.getQueueSize()); - public void testDurableSubQuery() throws Exception { - connection = connectionFactory.createConnection(); - connection.setClientID("test"); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber sub = session.createDurableSubscriber(session.createTopic("test.topic"), "test.consumer"); + String messageID = messageIDs[0]; + String newDestinationName = "queue://dummy.test.cheese"; + echo("Attempting to copy: " + messageID + " to destination: " + newDestinationName); + proxy.copyMessageTo(messageID, newDestinationName); - ObjectName query = new ObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Topic,destinationName=test.topic,endpoint=Consumer,consumerId=Durable(*),*"); - Set mbeans = mbeanServer.queryMBeans(query, null); - assertEquals(mbeans.size(), 1); - sub.close(); - } + assertEquals("Queue size", MESSAGE_COUNT, proxy.getQueueSize()); + + messageID = messageIDs[1]; + echo("Attempting to remove: " + messageID); + proxy.removeMessage(messageID); + + assertEquals("Queue size", MESSAGE_COUNT - 1, proxy.getQueueSize()); + + echo("Worked!"); + } + + protected void assertCreateAndDestroyDurableSubscriptions() throws Exception { + // lets create a new topic + ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); + echo("Create QueueView MBean..."); + BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); + + broker.addTopic(getDestinationString()); + + assertEquals("Durable subscriber count", 0, broker.getDurableTopicSubscribers().length); + + String topicName = getDestinationString(); + String selector = null; + ObjectName name1 = broker.createDurableSubscriber(clientID, "subscriber1", topicName, selector); + broker.createDurableSubscriber(clientID, "subscriber2", topicName, selector); + assertEquals("Durable subscriber count", 2, broker.getInactiveDurableTopicSubscribers().length); + + assertNotNull("Should have created an mbean name for the durable subscriber!", name1); + + LOG.info("Created durable subscriber with name: " + name1); + + // now lets try destroy it + broker.destroyDurableSubscriber(clientID, "subscriber1"); + assertEquals("Durable subscriber count", 1, broker.getInactiveDurableTopicSubscribers().length); + } + + protected void assertConsumerCounts() throws Exception { + ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); + BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); + + assertTrue("broker is not a slave", !broker.isSlave()); + // create 2 topics + broker.addTopic(getDestinationString() + "1"); + broker.addTopic(getDestinationString() + "2"); + + ObjectName topicObjName1 = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Topic,destinationName=" + getDestinationString() + "1"); + ObjectName topicObjName2 = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Topic,destinationName=" + getDestinationString() + "2"); + TopicViewMBean topic1 = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, topicObjName1, TopicViewMBean.class, true); + TopicViewMBean topic2 = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, topicObjName2, TopicViewMBean.class, true); + + assertEquals("topic1 Durable subscriber count", 0, topic1.getConsumerCount()); + assertEquals("topic2 Durable subscriber count", 0, topic2.getConsumerCount()); + + String topicName = getDestinationString(); + String selector = null; + + // create 1 subscriber for each topic + broker.createDurableSubscriber(clientID, "topic1.subscriber1", topicName + "1", selector); + broker.createDurableSubscriber(clientID, "topic2.subscriber1", topicName + "2", selector); + + assertEquals("topic1 Durable subscriber count", 1, topic1.getConsumerCount()); + assertEquals("topic2 Durable subscriber count", 1, topic2.getConsumerCount()); + + // create 1 more subscriber for topic1 + broker.createDurableSubscriber(clientID, "topic1.subscriber2", topicName + "1", selector); + + assertEquals("topic1 Durable subscriber count", 2, topic1.getConsumerCount()); + assertEquals("topic2 Durable subscriber count", 1, topic2.getConsumerCount()); + + // destroy topic1 subscriber + broker.destroyDurableSubscriber(clientID, "topic1.subscriber1"); + + assertEquals("topic1 Durable subscriber count", 1, topic1.getConsumerCount()); + assertEquals("topic2 Durable subscriber count", 1, topic2.getConsumerCount()); + + // destroy topic2 subscriber + broker.destroyDurableSubscriber(clientID, "topic2.subscriber1"); + + assertEquals("topic1 Durable subscriber count", 1, topic1.getConsumerCount()); + assertEquals("topic2 Durable subscriber count", 0, topic2.getConsumerCount()); + + // destroy remaining topic1 subscriber + broker.destroyDurableSubscriber(clientID, "topic1.subscriber2"); + + assertEquals("topic1 Durable subscriber count", 0, topic1.getConsumerCount()); + assertEquals("topic2 Durable subscriber count", 0, topic2.getConsumerCount()); + } + + protected void assertProducerCounts() throws Exception { + ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); + BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); + + assertTrue("broker is not a slave", !broker.isSlave()); + // create 2 topics + broker.addTopic(getDestinationString() + "1"); + broker.addTopic(getDestinationString() + "2"); + + ObjectName topicObjName1 = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Topic,destinationName=" + getDestinationString() + "1"); + ObjectName topicObjName2 = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Topic,destinationName=" + getDestinationString() + "2"); + TopicViewMBean topic1 = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, topicObjName1, TopicViewMBean.class, true); + TopicViewMBean topic2 = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, topicObjName2, TopicViewMBean.class, true); + + assertEquals("topic1 Producer count", 0, topic1.getProducerCount()); + assertEquals("topic2 Producer count", 0, topic2.getProducerCount()); + assertEquals("broker Topic Producer count", 0, broker.getTopicProducers().length); + + // create 1 producer for each topic + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination dest1 = session.createTopic(getDestinationString() + "1"); + Destination dest2 = session.createTopic(getDestinationString() + "2"); + MessageProducer producer1 = session.createProducer(dest1); + MessageProducer producer2 = session.createProducer(dest2); + Thread.sleep(500); + + assertEquals("topic1 Producer count", 1, topic1.getProducerCount()); + assertEquals("topic2 Producer count", 1, topic2.getProducerCount()); + + assertEquals("broker Topic Producer count", 2, broker.getTopicProducers().length); + + // create 1 more producer for topic1 + MessageProducer producer3 = session.createProducer(dest1); + Thread.sleep(500); + + assertEquals("topic1 Producer count", 2, topic1.getProducerCount()); + assertEquals("topic2 Producer count", 1, topic2.getProducerCount()); + + assertEquals("broker Topic Producer count", 3, broker.getTopicProducers().length); + + // destroy topic1 producer + producer1.close(); + Thread.sleep(500); + + assertEquals("topic1 Producer count", 1, topic1.getProducerCount()); + assertEquals("topic2 Producer count", 1, topic2.getProducerCount()); + + assertEquals("broker Topic Producer count", 2, broker.getTopicProducers().length); + + // destroy topic2 producer + producer2.close(); + Thread.sleep(500); + + assertEquals("topic1 Producer count", 1, topic1.getProducerCount()); + assertEquals("topic2 Producer count", 0, topic2.getProducerCount()); + + assertEquals("broker Topic Producer count", 1, broker.getTopicProducers().length); + + // destroy remaining topic1 producer + producer3.close(); + Thread.sleep(500); + + assertEquals("topic1 Producer count", 0, topic1.getProducerCount()); + assertEquals("topic2 Producer count", 0, topic2.getProducerCount()); + + MessageProducer producer4 = session.createProducer(null); + Thread.sleep(500); + assertEquals(1, broker.getDynamicDestinationProducers().length); + producer4.close(); + Thread.sleep(500); + + assertEquals("broker Topic Producer count", 0, broker.getTopicProducers().length); + } + + protected ObjectName assertRegisteredObjectName(String name) throws MalformedObjectNameException, Exception { + final ObjectName objectName = new ObjectName(name); + final AtomicBoolean result = new AtomicBoolean(false); + assertTrue("Bean registered: " + objectName, Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + try { + result.set(mbeanServer.isRegistered(objectName)); + } + catch (Exception ignored) { + LOG.debug(ignored.toString()); + } + return result.get(); + } + })); + return objectName; + } + + protected ObjectName assertNotRegisteredObjectName(String name) throws MalformedObjectNameException, NullPointerException { + ObjectName objectName = new ObjectName(name); + if (mbeanServer.isRegistered(objectName)) { + fail("Found the MBean!: " + objectName); + } + else { + echo("Bean not registered Registered: " + objectName); + } + return objectName; + } + + @Override + protected void setUp() throws Exception { + bindAddress = "tcp://localhost:0"; + useTopic = false; + super.setUp(); + ManagementContext managementContext = broker.getManagementContext(); + mbeanServer = managementContext.getMBeanServer(); + } + + @Override + protected void tearDown() throws Exception { + if (waitForKeyPress) { + // We are running from the command line so let folks browse the + // mbeans... + System.out.println(); + System.out.println("Press enter to terminate the program."); + System.out.println("In the meantime you can use your JMX console to view the current MBeans"); + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + reader.readLine(); + } + + if (connection != null) { + connection.close(); + connection = null; + } + super.tearDown(); + } + + @Override + protected ConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString()); + } + + @Override + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + answer.setPersistent(false); + answer.setDeleteAllMessagesOnStartup(true); + answer.setUseJmx(true); + + // apply memory limit so that %usage is visible + PolicyMap policyMap = new PolicyMap(); + PolicyEntry defaultEntry = new PolicyEntry(); + defaultEntry.setMemoryLimit(1024 * 1024 * 4); + policyMap.setDefaultEntry(defaultEntry); + answer.setDestinationPolicy(policyMap); + + // allow options to be visible via jmx + answer.setDestinations(new ActiveMQDestination[]{new ActiveMQQueue(QUEUE_WITH_OPTIONS + "?topQueue=true&hasOptions=2")}); + + answer.addConnector(bindAddress); + return answer; + } + + protected void useConnection(Connection connection) throws Exception { + connection.setClientID(clientID); + connection.start(); + Session session = connection.createSession(transacted, authMode); + destination = createDestination(); + MessageProducer producer = session.createProducer(destination); + for (int i = 0; i < MESSAGE_COUNT; i++) { + Message message = session.createTextMessage("Message: " + i); + message.setIntProperty("counter", i); + message.setJMSCorrelationID("MyCorrelationID"); + message.setJMSReplyTo(new ActiveMQQueue("MyReplyTo")); + message.setJMSType("MyType"); + message.setJMSPriority(5); + producer.send(message); + } + Thread.sleep(1000); + } + + protected void useConnectionWithBlobMessage(Connection connection) throws Exception { + connection.setClientID(clientID); + connection.start(); + ActiveMQSession session = (ActiveMQSession) connection.createSession(transacted, authMode); + destination = createDestination(); + MessageProducer producer = session.createProducer(destination); + for (int i = 0; i < MESSAGE_COUNT; i++) { + BlobMessage message = session.createBlobMessage(new URL("http://foo.bar/test")); + message.setIntProperty("counter", i); + message.setJMSCorrelationID("MyCorrelationID"); + message.setJMSReplyTo(new ActiveMQQueue("MyReplyTo")); + message.setJMSType("MyType"); + message.setJMSPriority(5); + producer.send(message); + } + Thread.sleep(1000); + } + + protected void useConnectionWithByteMessage(Connection connection) throws Exception { + connection.setClientID(clientID); + connection.start(); + ActiveMQSession session = (ActiveMQSession) connection.createSession(transacted, authMode); + destination = createDestination(); + MessageProducer producer = session.createProducer(destination); + for (int i = 0; i < MESSAGE_COUNT; i++) { + BytesMessage message = session.createBytesMessage(); + message.writeBytes(("Message: " + i).getBytes()); + message.setIntProperty("counter", i); + message.setJMSCorrelationID("MyCorrelationID"); + message.setJMSReplyTo(new ActiveMQQueue("MyReplyTo")); + message.setJMSType("MyType"); + message.setJMSPriority(5); + producer.send(message); + } + Thread.sleep(1000); + } + + protected void echo(String text) { + //LOG.info(text); + } + + protected String getSecondDestinationString() { + return "test.new.destination." + getClass() + "." + getName(); + } + + public void testDynamicProducerView() throws Exception { + connection = connectionFactory.createConnection(); + + ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); + BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); + + assertEquals(0, broker.getDynamicDestinationProducers().length); + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(null); + + Destination dest1 = session.createTopic("DynamicDest-1"); + Destination dest2 = session.createTopic("DynamicDest-2"); + Destination dest3 = session.createQueue("DynamicDest-3"); + + // Wait a bit to let the producer get registered. + Thread.sleep(100); + + assertEquals(1, broker.getDynamicDestinationProducers().length); + + ObjectName viewName = broker.getDynamicDestinationProducers()[0]; + assertNotNull(viewName); + ProducerViewMBean view = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, viewName, ProducerViewMBean.class, true); + assertNotNull(view); + + assertEquals("NOTSET", view.getDestinationName()); + + producer.send(dest1, session.createTextMessage("Test Message 1")); + Thread.sleep(200); + assertEquals(((ActiveMQDestination) dest1).getPhysicalName(), view.getDestinationName()); + assertTrue(view.isDestinationTopic()); + assertFalse(view.isDestinationQueue()); + assertFalse(view.isDestinationTemporary()); + + producer.send(dest2, session.createTextMessage("Test Message 2")); + Thread.sleep(200); + assertEquals(((ActiveMQDestination) dest2).getPhysicalName(), view.getDestinationName()); + assertTrue(view.isDestinationTopic()); + assertFalse(view.isDestinationQueue()); + assertFalse(view.isDestinationTemporary()); + + producer.send(dest3, session.createTextMessage("Test Message 3")); + Thread.sleep(200); + assertEquals(((ActiveMQDestination) dest3).getPhysicalName(), view.getDestinationName()); + assertTrue(view.isDestinationQueue()); + assertFalse(view.isDestinationTopic()); + assertFalse(view.isDestinationTemporary()); + + producer.close(); + Thread.sleep(200); + assertEquals(0, broker.getDynamicDestinationProducers().length); + } + + public void testTempQueueJMXDelete() throws Exception { + connection = connectionFactory.createConnection(); + + connection.setClientID(clientID); + connection.start(); + Session session = connection.createSession(transacted, authMode); + ActiveMQTempQueue tQueue = (ActiveMQTempQueue) session.createTemporaryQueue(); + Thread.sleep(1000); + + ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=" + JMXSupport.encodeObjectNamePart(tQueue.getDestinationTypeAsString()) + ",destinationName=" + JMXSupport.encodeObjectNamePart(tQueue.getPhysicalName())); + + // should not throw an exception + + mbeanServer.getObjectInstance(queueViewMBeanName); + + tQueue.delete(); + Thread.sleep(1000); + try { + // should throw an exception + mbeanServer.getObjectInstance(queueViewMBeanName); + + fail("should be deleted already!"); + } + catch (Exception e) { + // expected! + } + } + + // Test for AMQ-3029 + public void testBrowseBlobMessages() throws Exception { + connection = connectionFactory.createConnection(); + useConnectionWithBlobMessage(connection); + + ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); + + QueueViewMBean queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); + + CompositeData[] compdatalist = queue.browse(); + int initialQueueSize = compdatalist.length; + if (initialQueueSize == 0) { + fail("There is no message in the queue:"); + } + else { + echo("Current queue size: " + initialQueueSize); + } + int messageCount = initialQueueSize; + String[] messageIDs = new String[messageCount]; + for (int i = 0; i < messageCount; i++) { + CompositeData cdata = compdatalist[i]; + String messageID = (String) cdata.get("JMSMessageID"); + assertNotNull("Should have a message ID for message " + i, messageID); + + messageIDs[i] = messageID; + } + + assertTrue("dest has some memory usage", queue.getMemoryPercentUsage() > 0); + } + + public void testDestinationOptionsAreVisible() throws Exception { + ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + QUEUE_WITH_OPTIONS); + + QueueViewMBean queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); + + assertEquals("name match", QUEUE_WITH_OPTIONS, queue.getName()); + + String options = queue.getOptions(); + LOG.info("Got options: " + options); + + Map optionsMap = URISupport.parseQuery(options); + assertEquals("got a map", 2, optionsMap.size()); + assertTrue("matches our options", optionsMap.containsKey("hasOptions")); + assertTrue("matches our options", optionsMap.containsKey("topQueue")); + + assertTrue("matches our options", optionsMap.containsValue("true")); + assertTrue("matches our options", optionsMap.containsValue("2")); + } + + public void testSubscriptionViewToConnectionMBean() throws Exception { + + connection = connectionFactory.createConnection("admin", "admin"); + connection.setClientID("MBeanTest"); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination queue = session.createQueue(getDestinationString() + ".Queue"); + MessageConsumer queueConsumer = session.createConsumer(queue); + MessageProducer producer = session.createProducer(queue); + + ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); + BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); + + Thread.sleep(100); + + assertTrue(broker.getQueueSubscribers().length == 1); + + ObjectName subscriptionName = broker.getQueueSubscribers()[0]; + LOG.info("Looking for Subscription: " + subscriptionName); + + SubscriptionViewMBean subscriberView = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, subscriptionName, SubscriptionViewMBean.class, true); + assertNotNull(subscriberView); + + ObjectName connectionName = subscriberView.getConnection(); + LOG.info("Looking for Connection: " + connectionName); + assertNotNull(connectionName); + ConnectionViewMBean connectionView = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, connectionName, ConnectionViewMBean.class, true); + assertNotNull(connectionView); + + // Our consumer plus one advisory consumer. + assertEquals(2, connectionView.getConsumers().length); + + assertEquals("client id match", "MBeanTest", connectionView.getClientId()); + + // Check that the subscription view we found earlier is in this list. + boolean found = false; + for (ObjectName name : connectionView.getConsumers()) { + if (name.equals(subscriptionName)) { + found = true; + } + } + assertTrue("We should have found: " + subscriptionName, found); + + // Our producer and no others. + assertEquals(1, connectionView.getProducers().length); + + // Bean should detect the updates. + queueConsumer.close(); + producer.close(); + + Thread.sleep(200); + + // Only an advisory consumers now. + assertEquals(1, connectionView.getConsumers().length); + assertEquals(0, connectionView.getProducers().length); + } + + public void testCreateAndUnsubscribeDurableSubscriptions() throws Exception { + + connection = connectionFactory.createConnection("admin", "admin"); + connection.setClientID("MBeanTest"); + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + String topicName = getDestinationString() + ".DurableTopic"; + Topic topic = session.createTopic(topicName); + + ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); + echo("Create QueueView MBean..."); + BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); + + assertEquals("Durable subscriber count", 0, broker.getDurableTopicSubscribers().length); + assertEquals("Durable subscriber count", 0, broker.getInactiveDurableTopicSubscribers().length); + + MessageConsumer durableConsumer1 = session.createDurableSubscriber(topic, "subscription1"); + MessageConsumer durableConsumer2 = session.createDurableSubscriber(topic, "subscription2"); + + Thread.sleep(100); + + assertEquals("Durable subscriber count", 2, broker.getDurableTopicSubscribers().length); + assertEquals("Durable subscriber count", 0, broker.getInactiveDurableTopicSubscribers().length); + + durableConsumer1.close(); + durableConsumer2.close(); + + Thread.sleep(100); + + assertEquals("Durable subscriber count", 0, broker.getDurableTopicSubscribers().length); + assertEquals("Durable subscriber count", 2, broker.getInactiveDurableTopicSubscribers().length); + + session.unsubscribe("subscription1"); + + Thread.sleep(100); + + assertEquals("Inactive Durable subscriber count", 1, broker.getInactiveDurableTopicSubscribers().length); + + session.unsubscribe("subscription2"); + + assertEquals("Inactive Durable subscriber count", 0, broker.getInactiveDurableTopicSubscribers().length); + } + + public void testUserNamePopulated() throws Exception { + doTestUserNameInMBeans(true); + } + + public void testUserNameNotPopulated() throws Exception { + doTestUserNameInMBeans(false); + } + + @SuppressWarnings("unused") + private void doTestUserNameInMBeans(boolean expect) throws Exception { + broker.setPopulateUserNameInMBeans(expect); + + connection = connectionFactory.createConnection("admin", "admin"); + connection.setClientID("MBeanTest"); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination queue = session.createQueue(getDestinationString() + ".Queue"); + Topic topic = session.createTopic(getDestinationString() + ".Topic"); + MessageProducer producer = session.createProducer(queue); + MessageConsumer queueConsumer = session.createConsumer(queue); + MessageConsumer topicConsumer = session.createConsumer(topic); + MessageConsumer durable = session.createDurableSubscriber(topic, "Durable"); + + ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); + BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); + + Thread.sleep(100); + + assertTrue(broker.getQueueProducers().length == 1); + assertTrue(broker.getTopicSubscribers().length == 2); + assertTrue(broker.getQueueSubscribers().length == 1); + + ObjectName producerName = broker.getQueueProducers()[0]; + ProducerViewMBean producerView = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, producerName, ProducerViewMBean.class, true); + assertNotNull(producerView); + + if (expect) { + assertEquals("admin", producerView.getUserName()); + } + else { + assertNull(producerView.getUserName()); + } + + for (ObjectName name : broker.getTopicSubscribers()) { + SubscriptionViewMBean subscriberView = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, name, SubscriptionViewMBean.class, true); + if (expect) { + assertEquals("admin", subscriberView.getUserName()); + } + else { + assertNull(subscriberView.getUserName()); + } + } + + for (ObjectName name : broker.getQueueSubscribers()) { + SubscriptionViewMBean subscriberView = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, name, SubscriptionViewMBean.class, true); + if (expect) { + assertEquals("admin", subscriberView.getUserName()); + } + else { + assertNull(subscriberView.getUserName()); + } + } + ObjectName query = //new ObjectName(domain + ":type=Broker,brokerName=localhost,connector=*," + "connectorName=*,connectionName=MBeanTest"); + BrokerMBeanSupport.createConnectionQuery(domain, "localhost", connection.getClientID()); + + Set names = mbeanServer.queryNames(query, null); + boolean found = false; + for (ObjectName name : names) { + if (name.toString().endsWith("connectionName=MBeanTest")) { + + ConnectionViewMBean connectionView = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, name, ConnectionViewMBean.class, true); + assertNotNull(connectionView); + + if (expect) { + assertEquals("admin", connectionView.getUserName()); + } + else { + assertNull(connectionView.getUserName()); + } + + found = true; + break; + } + } + + assertTrue("Should find the connection's ManagedTransportConnection", found); + } + + public void testMoveMessagesToRetainOrder() throws Exception { + connection = connectionFactory.createConnection(); + useConnection(connection); + + ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); + + QueueViewMBean queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); + + String newDestination = getSecondDestinationString(); + queue.moveMatchingMessagesTo("", newDestination); + + queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + newDestination); + + queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); + int movedSize = MESSAGE_COUNT; + assertEquals("Unexpected number of messages ", movedSize, queue.getQueueSize()); + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue(newDestination); + MessageConsumer consumer = session.createConsumer(destination); + + int last = -1; + int current = -1; + Message message = null; + while ((message = consumer.receive(2000)) != null) { + if (message.propertyExists("counter")) { + current = message.getIntProperty("counter"); + assertEquals(last, current - 1); + last = current; + } + } + + // now lets remove them by selector + queue.removeMatchingMessages(""); + + assertEquals("Should have no more messages in the queue: " + queueViewMBeanName, 0, queue.getQueueSize()); + assertEquals("dest has no memory usage", 0, queue.getMemoryPercentUsage()); + } + + public void testConnectionCounts() throws Exception { + + ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); + BrokerViewMBean broker = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); + + assertEquals(0, broker.getCurrentConnectionsCount()); + + connection = connectionFactory.createConnection(); + useConnection(connection); + + assertEquals(1, broker.getCurrentConnectionsCount()); + connection.close(); + assertEquals(0, broker.getCurrentConnectionsCount()); + assertEquals(1, broker.getTotalConnectionsCount()); + } + + public void testCopyMessagesToRetainOrder() throws Exception { + connection = connectionFactory.createConnection(); + useConnection(connection); + + ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); + + QueueViewMBean queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); + + String newDestination = getSecondDestinationString(); + queue.copyMatchingMessagesTo("", newDestination); + + queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + newDestination); + + queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); + int movedSize = MESSAGE_COUNT; + assertEquals("Unexpected number of messages ", movedSize, queue.getQueueSize()); + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue(newDestination); + MessageConsumer consumer = session.createConsumer(destination); + + int last = -1; + int current = -1; + Message message = null; + while ((message = consumer.receive(2000)) != null) { + if (message.propertyExists("counter")) { + current = message.getIntProperty("counter"); + assertEquals(last, current - 1); + last = current; + } + } + + // now lets remove them by selector + queue.removeMatchingMessages(""); + + assertEquals("Should have no more messages in the queue: " + queueViewMBeanName, 0, queue.getQueueSize()); + assertEquals("dest has no memory usage", 0, queue.getMemoryPercentUsage()); + } + + public void testRemoveMatchingMessageRetainOrder() throws Exception { + connection = connectionFactory.createConnection(); + useConnection(connection); + + ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); + + QueueViewMBean queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); + + String queueName = getDestinationString(); + queue.removeMatchingMessages("counter < 10"); + + int newSize = MESSAGE_COUNT - 10; + assertEquals("Unexpected number of messages ", newSize, queue.getQueueSize()); + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue(queueName); + MessageConsumer consumer = session.createConsumer(destination); + + int last = 9; + int current = 0; + Message message = null; + while ((message = consumer.receive(2000)) != null) { + if (message.propertyExists("counter")) { + current = message.getIntProperty("counter"); + assertEquals(last, current - 1); + last = current; + } + } + + // now lets remove them by selector + queue.removeMatchingMessages(""); + + assertEquals("Should have no more messages in the queue: " + queueViewMBeanName, 0, queue.getQueueSize()); + assertEquals("dest has no memory usage", 0, queue.getMemoryPercentUsage()); + } + + public void testBrowseBytesMessages() throws Exception { + connection = connectionFactory.createConnection(); + useConnectionWithByteMessage(connection); + + ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); + + QueueViewMBean queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); + + CompositeData[] compdatalist = queue.browse(); + int initialQueueSize = compdatalist.length; + if (initialQueueSize == 0) { + fail("There is no message in the queue:"); + } + else { + echo("Current queue size: " + initialQueueSize); + } + int messageCount = initialQueueSize; + String[] messageIDs = new String[messageCount]; + for (int i = 0; i < messageCount; i++) { + CompositeData cdata = compdatalist[i]; + String messageID = (String) cdata.get("JMSMessageID"); + assertNotNull("Should have a message ID for message " + i, messageID); + messageIDs[i] = messageID; + + Byte[] preview = (Byte[]) cdata.get(CompositeDataConstants.BODY_PREVIEW); + assertNotNull("should be a preview", preview); + assertTrue("not empty", preview.length > 0); + } + + assertTrue("dest has some memory usage", queue.getMemoryPercentUsage() > 0); + + // consume all the messages + echo("Attempting to consume all bytes messages from: " + destination); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(destination); + for (int i = 0; i < MESSAGE_COUNT; i++) { + Message message = consumer.receive(5000); + assertNotNull(message); + assertTrue(message instanceof BytesMessage); + } + consumer.close(); + session.close(); + } + + public void testBrowseOrder() throws Exception { + connection = connectionFactory.createConnection(); + ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); + prefetchPolicy.setAll(20); + ((ActiveMQConnection) connection).setPrefetchPolicy(prefetchPolicy); + useConnection(connection); + + ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); + + QueueViewMBean queue = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); + + CompositeData[] compdatalist = queue.browse(); + int initialQueueSize = compdatalist.length; + assertEquals("expected", MESSAGE_COUNT, initialQueueSize); + + int messageCount = initialQueueSize; + for (int i = 0; i < messageCount; i++) { + CompositeData cdata = compdatalist[i]; + String messageID = (String) cdata.get("JMSMessageID"); + assertNotNull("Should have a message ID for message " + i, messageID); + + Map intProperties = CompositeDataHelper.getTabularMap(cdata, CompositeDataConstants.INT_PROPERTIES); + assertTrue("not empty", intProperties.size() > 0); + assertEquals("counter in order", i, intProperties.get("counter")); + } + + echo("Attempting to consume 5 bytes messages from: " + destination); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(destination); + for (int i = 0; i < 5; i++) { + Message message = consumer.receive(5000); + assertNotNull(message); + assertEquals("ordered", i, message.getIntProperty("counter")); + echo("Consumed: " + message.getIntProperty("counter")); + } + consumer.close(); + session.close(); + connection.close(); + + // browse again and verify order + compdatalist = queue.browse(); + initialQueueSize = compdatalist.length; + assertEquals("5 gone", MESSAGE_COUNT - 5, initialQueueSize); + + messageCount = initialQueueSize; + for (int i = 0; i < messageCount - 4; i++) { + CompositeData cdata = compdatalist[i]; + + Map intProperties = CompositeDataHelper.getTabularMap(cdata, CompositeDataConstants.INT_PROPERTIES); + assertTrue("not empty", intProperties.size() > 0); + assertEquals("counter in order", i + 5, intProperties.get("counter")); + echo("Got: " + intProperties.get("counter")); + } + } + + public void testAddRemoveConnectorBrokerView() throws Exception { + + ObjectName brokerName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); + BrokerViewMBean brokerView = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerName, BrokerViewMBean.class, true); + + Map connectors = brokerView.getTransportConnectors(); + LOG.info("Connectors: " + connectors); + assertEquals("one connector", 1, connectors.size()); + + ConnectorViewMBean connector = getProxyToConnectionView("tcp"); + assertNotNull(connector); + + String name = connectors.keySet().iterator().next().toString(); + + brokerView.removeConnector(name); + + connectors = brokerView.getTransportConnectors(); + assertEquals("empty", 0, connectors.size()); + + name = brokerView.addConnector("tcp://0.0.0.0:0"); + + connector = getProxyToConnectionView("tcp"); + assertNotNull(connector); + + connectors = brokerView.getTransportConnectors(); + LOG.info("Connectors: " + connectors); + assertEquals("one connector", 1, connectors.size()); + assertTrue("name is in map: " + connectors.keySet(), connectors.keySet().contains(name)); + } + + public void testConnectorView() throws Exception { + ConnectorViewMBean connector = getProxyToConnectionView("tcp"); + assertNotNull(connector); + + assertFalse(connector.isRebalanceClusterClients()); + assertFalse(connector.isUpdateClusterClientsOnRemove()); + assertFalse(connector.isUpdateClusterClients()); + assertFalse(connector.isAllowLinkStealingEnabled()); + } + + protected ConnectorViewMBean getProxyToConnectionView(String connectionType) throws Exception { + ObjectName connectorQuery = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,connector=clientConnectors,connectorName=" + connectionType + "_//*"); + + Set results = broker.getManagementContext().queryNames(connectorQuery, null); + + if (results == null || results.isEmpty() || results.size() > 1) { + throw new Exception("Unable to find the exact Connector instance."); + } + + ConnectorViewMBean proxy = (ConnectorViewMBean) broker.getManagementContext().newProxyInstance(results.iterator().next(), ConnectorViewMBean.class, true); + return proxy; + } + + public void testDynamicProducers() throws Exception { + connection = connectionFactory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(null); + + ObjectName query = new ObjectName(domain + ":type=Broker,brokerName=localhost,endpoint=dynamicProducer,*"); + Set mbeans = mbeanServer.queryMBeans(query, null); + assertEquals(mbeans.size(), 1); + producer.close(); + } + + public void testDurableSubQuery() throws Exception { + connection = connectionFactory.createConnection(); + connection.setClientID("test"); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + TopicSubscriber sub = session.createDurableSubscriber(session.createTopic("test.topic"), "test.consumer"); + + ObjectName query = new ObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Topic,destinationName=test.topic,endpoint=Consumer,consumerId=Durable(*),*"); + Set mbeans = mbeanServer.queryMBeans(query, null); + assertEquals(mbeans.size(), 1); + sub.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/PurgeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/PurgeTest.java index ce8e3aecb0..e6057e4ac0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/PurgeTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/PurgeTest.java @@ -26,7 +26,9 @@ import javax.management.MBeanServer; import javax.management.MBeanServerInvocationHandler; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; + import junit.framework.Test; + import junit.textui.TestRunner; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.EmbeddedBrokerTestSupport; @@ -41,210 +43,212 @@ import org.slf4j.LoggerFactory; * A specific test of Queue.purge() functionality */ public class PurgeTest extends EmbeddedBrokerTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(PurgeTest.class); - protected MBeanServer mbeanServer; - protected String domain = "org.apache.activemq"; - protected String clientID = "foo"; + private static final Logger LOG = LoggerFactory.getLogger(PurgeTest.class); - protected Connection connection; - protected boolean transacted; - protected int authMode = Session.AUTO_ACKNOWLEDGE; - protected int messageCount = 10; - public PersistenceAdapter persistenceAdapter; + protected MBeanServer mbeanServer; + protected String domain = "org.apache.activemq"; + protected String clientID = "foo"; - public static void main(String[] args) { - TestRunner.run(PurgeTest.class); - } + protected Connection connection; + protected boolean transacted; + protected int authMode = Session.AUTO_ACKNOWLEDGE; + protected int messageCount = 10; + public PersistenceAdapter persistenceAdapter; - public static Test suite() { - return suite(PurgeTest.class); - } + public static void main(String[] args) { + TestRunner.run(PurgeTest.class); + } - public void testPurge() throws Exception { - // Send some messages - connection = connectionFactory.createConnection(); - connection.setClientID(clientID); - connection.start(); - Session session = connection.createSession(transacted, authMode); - destination = createDestination(); - MessageProducer producer = session.createProducer(destination); - for (int i = 0; i < messageCount; i++) { - Message message = session.createTextMessage("Message: " + i); - producer.send(message); - } + public static Test suite() { + return suite(PurgeTest.class); + } - // Now get the QueueViewMBean and purge - String objectNameStr = broker.getBrokerObjectName().toString(); - objectNameStr += ",destinationType=Queue,destinationName="+getDestinationString(); - ObjectName queueViewMBeanName = assertRegisteredObjectName(objectNameStr); - QueueViewMBean proxy = (QueueViewMBean)MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); + public void testPurge() throws Exception { + // Send some messages + connection = connectionFactory.createConnection(); + connection.setClientID(clientID); + connection.start(); + Session session = connection.createSession(transacted, authMode); + destination = createDestination(); + MessageProducer producer = session.createProducer(destination); + for (int i = 0; i < messageCount; i++) { + Message message = session.createTextMessage("Message: " + i); + producer.send(message); + } - long count = proxy.getQueueSize(); - assertEquals("Queue size", count, messageCount); + // Now get the QueueViewMBean and purge + String objectNameStr = broker.getBrokerObjectName().toString(); + objectNameStr += ",destinationType=Queue,destinationName=" + getDestinationString(); + ObjectName queueViewMBeanName = assertRegisteredObjectName(objectNameStr); + QueueViewMBean proxy = (QueueViewMBean) MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - proxy.purge(); - count = proxy.getQueueSize(); - assertEquals("Queue size", count, 0); - assertEquals("Browse size", proxy.browseMessages().size(), 0); + long count = proxy.getQueueSize(); + assertEquals("Queue size", count, messageCount); - // Queues have a special case once there are more than a thousand - // dead messages, make sure we hit that. - messageCount += 1000; - for (int i = 0; i < messageCount; i++) { - Message message = session.createTextMessage("Message: " + i); - producer.send(message); - } + proxy.purge(); + count = proxy.getQueueSize(); + assertEquals("Queue size", count, 0); + assertEquals("Browse size", proxy.browseMessages().size(), 0); - count = proxy.getQueueSize(); - assertEquals("Queue size", count, messageCount); + // Queues have a special case once there are more than a thousand + // dead messages, make sure we hit that. + messageCount += 1000; + for (int i = 0; i < messageCount; i++) { + Message message = session.createTextMessage("Message: " + i); + producer.send(message); + } - proxy.purge(); - count = proxy.getQueueSize(); - assertEquals("Queue size", count, 0); - assertEquals("Browse size", proxy.browseMessages().size(), 0); + count = proxy.getQueueSize(); + assertEquals("Queue size", count, messageCount); - producer.close(); - } + proxy.purge(); + count = proxy.getQueueSize(); + assertEquals("Queue size", count, 0); + assertEquals("Browse size", proxy.browseMessages().size(), 0); - public void initCombosForTestDelete() { - addCombinationValues("persistenceAdapter", new Object[] {new MemoryPersistenceAdapter(), new KahaDBPersistenceAdapter()}); - } + producer.close(); + } - public void testDeleteSameProducer() throws Exception { - connection = connectionFactory.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - destination = createDestination(); + public void initCombosForTestDelete() { + addCombinationValues("persistenceAdapter", new Object[]{new MemoryPersistenceAdapter(), new KahaDBPersistenceAdapter()}); + } - MessageProducer producer = session.createProducer(destination); - Message message = session.createTextMessage("Test Message"); - producer.send(message); + public void testDeleteSameProducer() throws Exception { + connection = connectionFactory.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + destination = createDestination(); - MessageConsumer consumer = session.createConsumer(destination); + MessageProducer producer = session.createProducer(destination); + Message message = session.createTextMessage("Test Message"); + producer.send(message); - Message received = consumer.receive(1000); - assertEquals(message, received); + MessageConsumer consumer = session.createConsumer(destination); - ObjectName brokerViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); - BrokerViewMBean brokerProxy = (BrokerViewMBean)MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerViewMBeanName, BrokerViewMBean.class, true); + Message received = consumer.receive(1000); + assertEquals(message, received); - brokerProxy.removeQueue(getDestinationString()); - producer.send(message); + ObjectName brokerViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); + BrokerViewMBean brokerProxy = (BrokerViewMBean) MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerViewMBeanName, BrokerViewMBean.class, true); - received = consumer.receive(1000); + brokerProxy.removeQueue(getDestinationString()); + producer.send(message); - assertNotNull("Message not received", received); - assertEquals(message, received); - } + received = consumer.receive(1000); - public void testDelete() throws Exception { - // Send some messages - connection = connectionFactory.createConnection(); - connection.setClientID(clientID); - connection.start(); - Session session = connection.createSession(transacted, authMode); - destination = createDestination(); - sendMessages(session, messageCount); + assertNotNull("Message not received", received); + assertEquals(message, received); + } - // Now get the QueueViewMBean and purge + public void testDelete() throws Exception { + // Send some messages + connection = connectionFactory.createConnection(); + connection.setClientID(clientID); + connection.start(); + Session session = connection.createSession(transacted, authMode); + destination = createDestination(); + sendMessages(session, messageCount); - ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); - QueueViewMBean queueProxy = (QueueViewMBean)MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); + // Now get the QueueViewMBean and purge - ObjectName brokerViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); - BrokerViewMBean brokerProxy = (BrokerViewMBean)MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerViewMBeanName, BrokerViewMBean.class, true); + ObjectName queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); + QueueViewMBean queueProxy = (QueueViewMBean) MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - long count = queueProxy.getQueueSize(); - assertEquals("Queue size", count, messageCount); + ObjectName brokerViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost"); + BrokerViewMBean brokerProxy = (BrokerViewMBean) MBeanServerInvocationHandler.newProxyInstance(mbeanServer, brokerViewMBeanName, BrokerViewMBean.class, true); - brokerProxy.removeQueue(getDestinationString()); + long count = queueProxy.getQueueSize(); + assertEquals("Queue size", count, messageCount); - sendMessages(session, messageCount); + brokerProxy.removeQueue(getDestinationString()); - queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); - queueProxy = (QueueViewMBean)MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); + sendMessages(session, messageCount); - count = queueProxy.getQueueSize(); - assertEquals("Queue size", count, messageCount); + queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); + queueProxy = (QueueViewMBean) MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - queueProxy.purge(); + count = queueProxy.getQueueSize(); + assertEquals("Queue size", count, messageCount); - // Queue have a special case once there are more than a thousand - // dead messages, make sure we hit that. - messageCount += 1000; - sendMessages(session, messageCount); + queueProxy.purge(); - count = queueProxy.getQueueSize(); - assertEquals("Queue size", count, messageCount); + // Queue have a special case once there are more than a thousand + // dead messages, make sure we hit that. + messageCount += 1000; + sendMessages(session, messageCount); - brokerProxy.removeQueue(getDestinationString()); + count = queueProxy.getQueueSize(); + assertEquals("Queue size", count, messageCount); - sendMessages(session, messageCount); + brokerProxy.removeQueue(getDestinationString()); - queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); - queueProxy = (QueueViewMBean)MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); + sendMessages(session, messageCount); - count = queueProxy.getQueueSize(); - assertEquals("Queue size", count, messageCount); - } + queueViewMBeanName = assertRegisteredObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + getDestinationString()); + queueProxy = (QueueViewMBean) MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); - private void sendMessages(Session session, int count) throws Exception { - MessageProducer producer = session.createProducer(destination); - for (int i = 0; i < messageCount; i++) { - Message message = session.createTextMessage("Message: " + i); - producer.send(message); - } - } + count = queueProxy.getQueueSize(); + assertEquals("Queue size", count, messageCount); + } - protected ObjectName assertRegisteredObjectName(String name) throws MalformedObjectNameException, NullPointerException { - ObjectName objectName = new ObjectName(name); - if (mbeanServer.isRegistered(objectName)) { - echo("Bean Registered: " + objectName); - } else { - fail("Could not find MBean!: " + objectName); - } - return objectName; - } + private void sendMessages(Session session, int count) throws Exception { + MessageProducer producer = session.createProducer(destination); + for (int i = 0; i < messageCount; i++) { + Message message = session.createTextMessage("Message: " + i); + producer.send(message); + } + } - protected void setUp() throws Exception { - bindAddress = "tcp://localhost:0"; - useTopic = false; - super.setUp(); - mbeanServer = broker.getManagementContext().getMBeanServer(); - } + protected ObjectName assertRegisteredObjectName(String name) throws MalformedObjectNameException, NullPointerException { + ObjectName objectName = new ObjectName(name); + if (mbeanServer.isRegistered(objectName)) { + echo("Bean Registered: " + objectName); + } + else { + fail("Could not find MBean!: " + objectName); + } + return objectName; + } - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - connection = null; - } - super.tearDown(); - } + protected void setUp() throws Exception { + bindAddress = "tcp://localhost:0"; + useTopic = false; + super.setUp(); + mbeanServer = broker.getManagementContext().getMBeanServer(); + } - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setUseJmx(true); - answer.setEnableStatistics(true); - answer.addConnector(bindAddress); - answer.setPersistenceAdapter(persistenceAdapter); - answer.deleteAllMessages(); - return answer; - } + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + connection = null; + } + super.tearDown(); + } - @Override - protected ConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString()); - } + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + answer.setUseJmx(true); + answer.setEnableStatistics(true); + answer.addConnector(bindAddress); + answer.setPersistenceAdapter(persistenceAdapter); + answer.deleteAllMessages(); + return answer; + } - protected void echo(String text) { - LOG.info(text); - } + @Override + protected ConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString()); + } - /** - * Returns the name of the destination used in this test case - */ - protected String getDestinationString() { - return getClass().getName() + "." + getName(true); - } + protected void echo(String text) { + LOG.info(text); + } + + /** + * Returns the name of the destination used in this test case + */ + protected String getDestinationString() { + return getClass().getName() + "." + getName(true); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/TransportConnectorMBeanTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/TransportConnectorMBeanTest.java index 6f55e3de38..3653bf7dc4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/TransportConnectorMBeanTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/jmx/TransportConnectorMBeanTest.java @@ -36,105 +36,106 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TransportConnectorMBeanTest { - private static final Logger LOG = LoggerFactory.getLogger(TransportConnectorMBeanTest.class); - BrokerService broker; + private static final Logger LOG = LoggerFactory.getLogger(TransportConnectorMBeanTest.class); - @Test - public void verifyRemoteAddressInMbeanName() throws Exception { - doVerifyRemoteAddressInMbeanName(true); - } + BrokerService broker; - @Test - public void verifyRemoteAddressNotInMbeanName() throws Exception { - doVerifyRemoteAddressInMbeanName(false); - } + @Test + public void verifyRemoteAddressInMbeanName() throws Exception { + doVerifyRemoteAddressInMbeanName(true); + } - @Test - public void verifyClientIdNetwork() throws Exception { - doVerifyClientIdNetwork(false); - } + @Test + public void verifyRemoteAddressNotInMbeanName() throws Exception { + doVerifyRemoteAddressInMbeanName(false); + } - @Test - public void verifyClientIdDuplexNetwork() throws Exception { - doVerifyClientIdNetwork(true); - } + @Test + public void verifyClientIdNetwork() throws Exception { + doVerifyClientIdNetwork(false); + } - private void doVerifyClientIdNetwork(boolean duplex) throws Exception { - createBroker(true); + @Test + public void verifyClientIdDuplexNetwork() throws Exception { + doVerifyClientIdNetwork(true); + } - BrokerService networked = new BrokerService(); - networked.setBrokerName("networked"); - networked.setPersistent(false); - NetworkConnector nc = networked.addNetworkConnector("static:" + broker.getTransportConnectors().get(0).getPublishableConnectString()); - nc.setDuplex(duplex); - networked.start(); + private void doVerifyClientIdNetwork(boolean duplex) throws Exception { + createBroker(true); - try { - assertTrue("presence of mbean with clientId", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Set registeredMbeans = getRegisteredMbeans(); - return match("_outbound", registeredMbeans); - } - })); + BrokerService networked = new BrokerService(); + networked.setBrokerName("networked"); + networked.setPersistent(false); + NetworkConnector nc = networked.addNetworkConnector("static:" + broker.getTransportConnectors().get(0).getPublishableConnectString()); + nc.setDuplex(duplex); + networked.start(); - } finally { - networked.stop(); - } - } - - private void doVerifyRemoteAddressInMbeanName(boolean allowRemoteAddress) throws Exception { - createBroker(allowRemoteAddress); - ActiveMQConnection connection = createConnection(); - Set registeredMbeans = getRegisteredMbeans(); - assertEquals("presence of mbean with clientId", true, match(connection.getClientID(), registeredMbeans)); - assertEquals("presence of mbean with local port", allowRemoteAddress, match(extractLocalPort(connection), registeredMbeans)); - } - - @After - public void stopBroker() throws Exception { - if (broker != null) { - broker.stop(); - } - } - - private boolean match(String s, Set registeredMbeans) { - String encodedName = JMXSupport.encodeObjectNamePart(s); - for (ObjectName name : registeredMbeans) { - LOG.info("checking for match:" + encodedName + ", with: " + name.toString()); - if (name.toString().contains(encodedName)) { - return true; + try { + assertTrue("presence of mbean with clientId", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Set registeredMbeans = getRegisteredMbeans(); + return match("_outbound", registeredMbeans); } - } - return false; - } + })); - private String extractLocalPort(ActiveMQConnection connection) throws Exception { - Socket socket = connection.getTransport().narrow(Socket.class); - return String.valueOf(socket.getLocalPort()); - } + } + finally { + networked.stop(); + } + } - private Set getRegisteredMbeans() throws Exception { - // need a little sleep to ensure JMX is up to date - Thread.sleep(200); - return broker.getManagementContext().queryNames(null, null); - } + private void doVerifyRemoteAddressInMbeanName(boolean allowRemoteAddress) throws Exception { + createBroker(allowRemoteAddress); + ActiveMQConnection connection = createConnection(); + Set registeredMbeans = getRegisteredMbeans(); + assertEquals("presence of mbean with clientId", true, match(connection.getClientID(), registeredMbeans)); + assertEquals("presence of mbean with local port", allowRemoteAddress, match(extractLocalPort(connection), registeredMbeans)); + } - private ActiveMQConnection createConnection() throws Exception { - final String opts = "?jms.watchTopicAdvisories=false"; - ActiveMQConnection connection = (ActiveMQConnection) - new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri() + opts).createConnection(); - connection.start(); - return connection; - } + @After + public void stopBroker() throws Exception { + if (broker != null) { + broker.stop(); + } + } - private void createBroker(boolean allowRemoteAddressInMbeanNames) throws Exception { - broker = new BrokerService(); - broker.setPersistent(false); - broker.addConnector("tcp://localhost:0"); - broker.getManagementContext().setAllowRemoteAddressInMBeanNames(allowRemoteAddressInMbeanNames); - broker.start(); - } + private boolean match(String s, Set registeredMbeans) { + String encodedName = JMXSupport.encodeObjectNamePart(s); + for (ObjectName name : registeredMbeans) { + LOG.info("checking for match:" + encodedName + ", with: " + name.toString()); + if (name.toString().contains(encodedName)) { + return true; + } + } + return false; + } + + private String extractLocalPort(ActiveMQConnection connection) throws Exception { + Socket socket = connection.getTransport().narrow(Socket.class); + return String.valueOf(socket.getLocalPort()); + } + + private Set getRegisteredMbeans() throws Exception { + // need a little sleep to ensure JMX is up to date + Thread.sleep(200); + return broker.getManagementContext().queryNames(null, null); + } + + private ActiveMQConnection createConnection() throws Exception { + final String opts = "?jms.watchTopicAdvisories=false"; + ActiveMQConnection connection = (ActiveMQConnection) new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri() + opts).createConnection(); + connection.start(); + return connection; + } + + private void createBroker(boolean allowRemoteAddressInMbeanNames) throws Exception { + broker = new BrokerService(); + broker.setPersistent(false); + broker.addConnector("tcp://localhost:0"); + broker.getManagementContext().setAllowRemoteAddressInMBeanNames(allowRemoteAddressInMbeanNames); + broker.start(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/mKahaDBXARecoveryBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/mKahaDBXARecoveryBrokerTest.java index 4cc57ba27c..c832238d90 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/mKahaDBXARecoveryBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/mKahaDBXARecoveryBrokerTest.java @@ -20,6 +20,7 @@ import java.util.LinkedList; import java.util.List; import junit.framework.Test; + import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.store.kahadb.FilteredKahaDBPersistenceAdapter; @@ -28,35 +29,35 @@ import org.apache.activemq.store.kahadb.MultiKahaDBPersistenceAdapter; public class mKahaDBXARecoveryBrokerTest extends XARecoveryBrokerTest { - @Override - protected void configureBroker(BrokerService broker) throws Exception { - super.configureBroker(broker); + @Override + protected void configureBroker(BrokerService broker) throws Exception { + super.configureBroker(broker); - MultiKahaDBPersistenceAdapter mKahaDB = new MultiKahaDBPersistenceAdapter(); - List adapters = new LinkedList(); - FilteredKahaDBPersistenceAdapter defaultEntry = new FilteredKahaDBPersistenceAdapter(); - defaultEntry.setPersistenceAdapter(new KahaDBPersistenceAdapter()); - adapters.add(defaultEntry); + MultiKahaDBPersistenceAdapter mKahaDB = new MultiKahaDBPersistenceAdapter(); + List adapters = new LinkedList(); + FilteredKahaDBPersistenceAdapter defaultEntry = new FilteredKahaDBPersistenceAdapter(); + defaultEntry.setPersistenceAdapter(new KahaDBPersistenceAdapter()); + adapters.add(defaultEntry); - FilteredKahaDBPersistenceAdapter special = new FilteredKahaDBPersistenceAdapter(); - special.setDestination(new ActiveMQQueue("special")); - special.setPersistenceAdapter(new KahaDBPersistenceAdapter()); - adapters.add(special); + FilteredKahaDBPersistenceAdapter special = new FilteredKahaDBPersistenceAdapter(); + special.setDestination(new ActiveMQQueue("special")); + special.setPersistenceAdapter(new KahaDBPersistenceAdapter()); + adapters.add(special); - mKahaDB.setFilteredPersistenceAdapters(adapters); - broker.setPersistenceAdapter(mKahaDB); - } + mKahaDB.setFilteredPersistenceAdapters(adapters); + broker.setPersistenceAdapter(mKahaDB); + } - public static Test suite() { - return suite(mKahaDBXARecoveryBrokerTest.class); - } + public static Test suite() { + return suite(mKahaDBXARecoveryBrokerTest.class); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - protected ActiveMQDestination createDestination() { - return new ActiveMQQueue("test,special"); - } + protected ActiveMQDestination createDestination() { + return new ActiveMQQueue("test,special"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/mLevelDBXARecoveryBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/mLevelDBXARecoveryBrokerTest.java index 147d89a02f..0b66883d4e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/mLevelDBXARecoveryBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/mLevelDBXARecoveryBrokerTest.java @@ -17,6 +17,7 @@ package org.apache.activemq.broker; import junit.framework.Test; + import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.store.kahadb.FilteredKahaDBPersistenceAdapter; @@ -29,41 +30,42 @@ import java.util.List; public class mLevelDBXARecoveryBrokerTest extends XARecoveryBrokerTest { - @Override - protected void configureBroker(BrokerService broker) throws Exception { - super.configureBroker(broker); + @Override + protected void configureBroker(BrokerService broker) throws Exception { + super.configureBroker(broker); - MultiKahaDBPersistenceAdapter mKahaDB = new MultiKahaDBPersistenceAdapter(); - List adapters = new LinkedList(); - FilteredKahaDBPersistenceAdapter defaultEntry = new FilteredKahaDBPersistenceAdapter(); - defaultEntry.setPersistenceAdapter(new LevelDBPersistenceAdapter()); - adapters.add(defaultEntry); + MultiKahaDBPersistenceAdapter mKahaDB = new MultiKahaDBPersistenceAdapter(); + List adapters = new LinkedList(); + FilteredKahaDBPersistenceAdapter defaultEntry = new FilteredKahaDBPersistenceAdapter(); + defaultEntry.setPersistenceAdapter(new LevelDBPersistenceAdapter()); + adapters.add(defaultEntry); - FilteredKahaDBPersistenceAdapter special = new FilteredKahaDBPersistenceAdapter(); - special.setDestination(new ActiveMQQueue("special")); - special.setPersistenceAdapter(new LevelDBPersistenceAdapter()); - adapters.add(special); + FilteredKahaDBPersistenceAdapter special = new FilteredKahaDBPersistenceAdapter(); + special.setDestination(new ActiveMQQueue("special")); + special.setPersistenceAdapter(new LevelDBPersistenceAdapter()); + adapters.add(special); - mKahaDB.setFilteredPersistenceAdapters(adapters); - broker.setPersistenceAdapter(mKahaDB); - } + mKahaDB.setFilteredPersistenceAdapters(adapters); + broker.setPersistenceAdapter(mKahaDB); + } - public static Test suite() { - return suite(mLevelDBXARecoveryBrokerTest.class); - } + public static Test suite() { + return suite(mLevelDBXARecoveryBrokerTest.class); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - protected ActiveMQDestination createDestination() { - return new ActiveMQQueue("test,special"); - } + protected ActiveMQDestination createDestination() { + return new ActiveMQQueue("test,special"); + } - public void testQueuePersistentPreparedAcksAvailableAfterRestartAndRollback() throws Exception { - // super.testQueuePersistentPreparedAcksAvailableAfterRestartAndRollback(); - } - public void testQueuePersistentUncommittedAcksLostOnRestart() throws Exception { - // super.testQueuePersistentUncommittedAcksLostOnRestart(); - } + public void testQueuePersistentPreparedAcksAvailableAfterRestartAndRollback() throws Exception { + // super.testQueuePersistentPreparedAcksAvailableAfterRestartAndRollback(); + } + + public void testQueuePersistentUncommittedAcksLostOnRestart() throws Exception { + // super.testQueuePersistentUncommittedAcksLostOnRestart(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/message/security/MessageAuthenticationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/message/security/MessageAuthenticationTest.java index 092c554c5f..1244581fdf 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/message/security/MessageAuthenticationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/message/security/MessageAuthenticationTest.java @@ -36,64 +36,67 @@ import org.apache.activemq.EmbeddedBrokerTestSupport; import org.apache.activemq.spring.ConsumerBean; /** - * + * */ public class MessageAuthenticationTest extends EmbeddedBrokerTestSupport { - private Connection connection; + private Connection connection; - public void testSendInvalidMessage() throws Exception { - if (connection == null) { - connection = createConnection(); - } - connection.start(); + public void testSendInvalidMessage() throws Exception { + if (connection == null) { + connection = createConnection(); + } + connection.start(); - ConsumerBean messageList = new ConsumerBean(); - messageList.setVerbose(true); + ConsumerBean messageList = new ConsumerBean(); + messageList.setVerbose(true); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = new ActiveMQQueue("MyQueue"); + Destination destination = new ActiveMQQueue("MyQueue"); - MessageConsumer c1 = session.createConsumer(destination); + MessageConsumer c1 = session.createConsumer(destination); - c1.setMessageListener(messageList); + c1.setMessageListener(messageList); - MessageProducer producer = session.createProducer(destination); - assertNotNull(producer); + MessageProducer producer = session.createProducer(destination); + assertNotNull(producer); - producer.send(createMessage(session, "invalidBody", "myHeader", "xyz")); - producer.send(createMessage(session, "validBody", "myHeader", "abc")); + producer.send(createMessage(session, "invalidBody", "myHeader", "xyz")); + producer.send(createMessage(session, "validBody", "myHeader", "abc")); - messageList.assertMessagesArrived(1); - assertEquals("validBody", ((TextMessage) messageList.flushMessages().get(0)).getText()); - } + messageList.assertMessagesArrived(1); + assertEquals("validBody", ((TextMessage) messageList.flushMessages().get(0)).getText()); + } - private javax.jms.Message createMessage(Session session, String body, String header, String value) throws JMSException { - TextMessage msg = session.createTextMessage(body); - msg.setStringProperty(header, value); - return msg; - } + private javax.jms.Message createMessage(Session session, + String body, + String header, + String value) throws JMSException { + TextMessage msg = session.createTextMessage(body); + msg.setStringProperty(header, value); + return msg; + } - @Override - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setPersistent(false); - answer.setMessageAuthorizationPolicy(new MessageAuthorizationPolicy() { - public boolean isAllowedToConsume(ConnectionContext context, Message message) { - try { - Object value = message.getProperty("myHeader"); - return "abc".equals(value); - } - catch (IOException e) { - System.out.println("Caught: " + e); - e.printStackTrace(); - return false; - } + @Override + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + answer.setPersistent(false); + answer.setMessageAuthorizationPolicy(new MessageAuthorizationPolicy() { + public boolean isAllowedToConsume(ConnectionContext context, Message message) { + try { + Object value = message.getProperty("myHeader"); + return "abc".equals(value); } - }); - answer.addConnector(bindAddress); - return answer; - } + catch (IOException e) { + System.out.println("Caught: " + e); + e.printStackTrace(); + return false; + } + } + }); + answer.addConnector(bindAddress); + return answer; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/partition/SpringPartitionBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/partition/SpringPartitionBrokerTest.java index dcf4e69e5f..c82cb1ba65 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/partition/SpringPartitionBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/partition/SpringPartitionBrokerTest.java @@ -17,6 +17,7 @@ package org.apache.activemq.broker.partition; import junit.framework.TestCase; + import org.apache.activemq.broker.BrokerFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.partition.PartitionBrokerPlugin; @@ -26,28 +27,28 @@ import org.apache.activemq.partition.dto.Partitioning; */ public class SpringPartitionBrokerTest extends TestCase { - public void testCreatePartitionBroker() throws Exception { + public void testCreatePartitionBroker() throws Exception { - BrokerService broker = BrokerFactory.createBroker("xbean:activemq-partition.xml"); - assertEquals(1, broker.getPlugins().length); - PartitionBrokerPlugin plugin = (PartitionBrokerPlugin)broker.getPlugins()[0]; - Partitioning config = plugin.getConfig(); - assertEquals(2, config.getBrokers().size()); + BrokerService broker = BrokerFactory.createBroker("xbean:activemq-partition.xml"); + assertEquals(1, broker.getPlugins().length); + PartitionBrokerPlugin plugin = (PartitionBrokerPlugin) broker.getPlugins()[0]; + Partitioning config = plugin.getConfig(); + assertEquals(2, config.getBrokers().size()); - Object o; - String json = "{\n" + - " \"by_client_id\":{\n" + - " \"client1\":{\"ids\":[\"broker1\"]},\n" + - " \"client2\":{\"ids\":[\"broker1\",\"broker2\"]}\n" + - " },\n" + - " \"brokers\":{\n" + - " \"broker1\":\"tcp://localhost:61616\",\n" + - " \"broker2\":\"tcp://localhost:61616\"\n" + - " }\n" + - "}"; - Partitioning expected = Partitioning.MAPPER.readValue(json, Partitioning.class); - assertEquals(expected.toString(), config.toString()); + Object o; + String json = "{\n" + + " \"by_client_id\":{\n" + + " \"client1\":{\"ids\":[\"broker1\"]},\n" + + " \"client2\":{\"ids\":[\"broker1\",\"broker2\"]}\n" + + " },\n" + + " \"brokers\":{\n" + + " \"broker1\":\"tcp://localhost:61616\",\n" + + " \"broker2\":\"tcp://localhost:61616\"\n" + + " }\n" + + "}"; + Partitioning expected = Partitioning.MAPPER.readValue(json, Partitioning.class); + assertEquals(expected.toString(), config.toString()); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowAckConsumer0Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowAckConsumer0Test.java index 3cfd59545d..16c342d97d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowAckConsumer0Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowAckConsumer0Test.java @@ -41,138 +41,142 @@ import org.slf4j.LoggerFactory; @RunWith(value = Parameterized.class) public class AbortSlowAckConsumer0Test extends AbortSlowConsumer0Test { - private static final Logger LOG = LoggerFactory.getLogger(AbortSlowAckConsumer0Test.class); - protected long maxTimeSinceLastAck = 5 * 1000; - AbortSlowAckConsumerStrategy strategy; + private static final Logger LOG = LoggerFactory.getLogger(AbortSlowAckConsumer0Test.class); + protected long maxTimeSinceLastAck = 5 * 1000; - public AbortSlowAckConsumer0Test(Boolean isTopic) { - super(isTopic); - } + AbortSlowAckConsumerStrategy strategy; - @Override - protected AbortSlowAckConsumerStrategy createSlowConsumerStrategy() { - AbortSlowAckConsumerStrategy strategy = new AbortSlowAckConsumerStrategy(); - strategy.setAbortConnection(abortConnection); - strategy.setCheckPeriod(checkPeriod); - strategy.setMaxSlowDuration(maxSlowDuration); - strategy.setMaxTimeSinceLastAck(maxTimeSinceLastAck); + public AbortSlowAckConsumer0Test(Boolean isTopic) { + super(isTopic); + } - return strategy; - } + @Override + protected AbortSlowAckConsumerStrategy createSlowConsumerStrategy() { + AbortSlowAckConsumerStrategy strategy = new AbortSlowAckConsumerStrategy(); + strategy.setAbortConnection(abortConnection); + strategy.setCheckPeriod(checkPeriod); + strategy.setMaxSlowDuration(maxSlowDuration); + strategy.setMaxTimeSinceLastAck(maxTimeSinceLastAck); - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - PolicyEntry policy = new PolicyEntry(); + return strategy; + } - strategy = createSlowConsumerStrategy(); - underTest = strategy; + @Override + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); + PolicyEntry policy = new PolicyEntry(); - policy.setSlowConsumerStrategy(strategy); - policy.setQueuePrefetch(10); - policy.setTopicPrefetch(10); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - broker.setDestinationPolicy(pMap); - return broker; - } + strategy = createSlowConsumerStrategy(); + underTest = strategy; - @Override - protected ConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - factory.getPrefetchPolicy().setAll(1); - return factory; - } + policy.setSlowConsumerStrategy(strategy); + policy.setQueuePrefetch(10); + policy.setTopicPrefetch(10); + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); + broker.setDestinationPolicy(pMap); + return broker; + } - @Override - @Test - public void testSlowConsumerIsAbortedViaJmx() throws Exception { - strategy.setMaxTimeSinceLastAck(500); // so jmx does the abort - super.testSlowConsumerIsAbortedViaJmx(); - } + @Override + protected ConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + factory.getPrefetchPolicy().setAll(1); + return factory; + } - @Test - public void testZeroPrefetchConsumerIsAborted() throws Exception { - strategy.setMaxTimeSinceLastAck(2000); // Make it shorter + @Override + @Test + public void testSlowConsumerIsAbortedViaJmx() throws Exception { + strategy.setMaxTimeSinceLastAck(500); // so jmx does the abort + super.testSlowConsumerIsAbortedViaJmx(); + } - ActiveMQConnection conn = (ActiveMQConnection) createConnectionFactory().createConnection(); - conn.setExceptionListener(this); - connections.add(conn); + @Test + public void testZeroPrefetchConsumerIsAborted() throws Exception { + strategy.setMaxTimeSinceLastAck(2000); // Make it shorter - Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); - final MessageConsumer consumer = sess.createConsumer(destination); - assertNotNull(consumer); - conn.start(); - startProducers(destination, 20); + ActiveMQConnection conn = (ActiveMQConnection) createConnectionFactory().createConnection(); + conn.setExceptionListener(this); + connections.add(conn); - Message message = consumer.receive(5000); - assertNotNull(message); + Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); + final MessageConsumer consumer = sess.createConsumer(destination); + assertNotNull(consumer); + conn.start(); + startProducers(destination, 20); - TimeUnit.SECONDS.sleep(15); + Message message = consumer.receive(5000); + assertNotNull(message); - try { - consumer.receive(5000); - fail("Slow consumer not aborted."); - } catch (Exception ex) { - } - } + TimeUnit.SECONDS.sleep(15); - @Test - public void testIdleConsumerCanBeAbortedNoMessages() throws Exception { - strategy.setIgnoreIdleConsumers(false); - strategy.setMaxTimeSinceLastAck(2000); // Make it shorter + try { + consumer.receive(5000); + fail("Slow consumer not aborted."); + } + catch (Exception ex) { + } + } - ActiveMQConnection conn = (ActiveMQConnection) createConnectionFactory().createConnection(); - conn.setExceptionListener(this); - connections.add(conn); + @Test + public void testIdleConsumerCanBeAbortedNoMessages() throws Exception { + strategy.setIgnoreIdleConsumers(false); + strategy.setMaxTimeSinceLastAck(2000); // Make it shorter - Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); - final MessageConsumer consumer = sess.createConsumer(destination); - assertNotNull(consumer); - conn.start(); + ActiveMQConnection conn = (ActiveMQConnection) createConnectionFactory().createConnection(); + conn.setExceptionListener(this); + connections.add(conn); - startProducers(destination, 1); + Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); + final MessageConsumer consumer = sess.createConsumer(destination); + assertNotNull(consumer); + conn.start(); - Message message = consumer.receive(5000); - assertNotNull(message); + startProducers(destination, 1); - // Consumer needs to be closed before the reeive call. - TimeUnit.SECONDS.sleep(15); + Message message = consumer.receive(5000); + assertNotNull(message); - try { - consumer.receive(5000); - fail("Idle consumer not aborted."); - } catch (Exception ex) { - } - } + // Consumer needs to be closed before the reeive call. + TimeUnit.SECONDS.sleep(15); - @Test - public void testIdleConsumerCanBeAborted() throws Exception { - strategy.setIgnoreIdleConsumers(false); - strategy.setMaxTimeSinceLastAck(2000); // Make it shorter + try { + consumer.receive(5000); + fail("Idle consumer not aborted."); + } + catch (Exception ex) { + } + } - ActiveMQConnection conn = (ActiveMQConnection) createConnectionFactory().createConnection(); - conn.setExceptionListener(this); - connections.add(conn); + @Test + public void testIdleConsumerCanBeAborted() throws Exception { + strategy.setIgnoreIdleConsumers(false); + strategy.setMaxTimeSinceLastAck(2000); // Make it shorter - Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); - final MessageConsumer consumer = sess.createConsumer(destination); - assertNotNull(consumer); - conn.start(); - startProducers(destination, 1); + ActiveMQConnection conn = (ActiveMQConnection) createConnectionFactory().createConnection(); + conn.setExceptionListener(this); + connections.add(conn); - Message message = consumer.receive(5000); - assertNotNull(message); - message.acknowledge(); + Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); + final MessageConsumer consumer = sess.createConsumer(destination); + assertNotNull(consumer); + conn.start(); + startProducers(destination, 1); - // Consumer needs to be closed before the reeive call. - TimeUnit.SECONDS.sleep(15); + Message message = consumer.receive(5000); + assertNotNull(message); + message.acknowledge(); - try { - consumer.receive(5000); - fail("Idle consumer not aborted."); - } catch (Exception ex) { - } - } + // Consumer needs to be closed before the reeive call. + TimeUnit.SECONDS.sleep(15); + + try { + consumer.receive(5000); + fail("Idle consumer not aborted."); + } + catch (Exception ex) { + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowAckConsumer1Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowAckConsumer1Test.java index 6d3e970c78..d6ee00c4da 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowAckConsumer1Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowAckConsumer1Test.java @@ -17,6 +17,7 @@ package org.apache.activemq.broker.policy; import javax.jms.ConnectionFactory; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.region.policy.AbortSlowAckConsumerStrategy; @@ -29,43 +30,42 @@ import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) public class AbortSlowAckConsumer1Test extends AbortSlowConsumer1Test { - protected long maxTimeSinceLastAck = 5 * 1000; + protected long maxTimeSinceLastAck = 5 * 1000; - public AbortSlowAckConsumer1Test(Boolean abortConnection, Boolean topic) { - super(abortConnection, topic); - } + public AbortSlowAckConsumer1Test(Boolean abortConnection, Boolean topic) { + super(abortConnection, topic); + } - @Override - protected AbortSlowConsumerStrategy createSlowConsumerStrategy() { - return new AbortSlowConsumerStrategy(); - } + @Override + protected AbortSlowConsumerStrategy createSlowConsumerStrategy() { + return new AbortSlowConsumerStrategy(); + } - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - PolicyEntry policy = new PolicyEntry(); + @Override + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); + PolicyEntry policy = new PolicyEntry(); - AbortSlowAckConsumerStrategy strategy = new AbortSlowAckConsumerStrategy(); - strategy.setAbortConnection(abortConnection); - strategy.setCheckPeriod(checkPeriod); - strategy.setMaxSlowDuration(maxSlowDuration); - strategy.setMaxTimeSinceLastAck(maxTimeSinceLastAck); + AbortSlowAckConsumerStrategy strategy = new AbortSlowAckConsumerStrategy(); + strategy.setAbortConnection(abortConnection); + strategy.setCheckPeriod(checkPeriod); + strategy.setMaxSlowDuration(maxSlowDuration); + strategy.setMaxTimeSinceLastAck(maxTimeSinceLastAck); - policy.setSlowConsumerStrategy(strategy); - policy.setQueuePrefetch(10); - policy.setTopicPrefetch(10); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - broker.setDestinationPolicy(pMap); - return broker; - } - - @Override - protected ConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - factory.getPrefetchPolicy().setAll(1); - return factory; - } + policy.setSlowConsumerStrategy(strategy); + policy.setQueuePrefetch(10); + policy.setTopicPrefetch(10); + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); + broker.setDestinationPolicy(pMap); + return broker; + } + @Override + protected ConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + factory.getPrefetchPolicy().setAll(1); + return factory; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowAckConsumer2Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowAckConsumer2Test.java index 948613e0c8..ea7714f64c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowAckConsumer2Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowAckConsumer2Test.java @@ -17,6 +17,7 @@ package org.apache.activemq.broker.policy; import javax.jms.ConnectionFactory; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.region.policy.AbortSlowAckConsumerStrategy; @@ -29,43 +30,42 @@ import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) public class AbortSlowAckConsumer2Test extends AbortSlowConsumer2Test { - protected long maxTimeSinceLastAck = 5 * 1000; + protected long maxTimeSinceLastAck = 5 * 1000; - public AbortSlowAckConsumer2Test(Boolean topic) { - super(topic); - } + public AbortSlowAckConsumer2Test(Boolean topic) { + super(topic); + } - @Override - protected AbortSlowConsumerStrategy createSlowConsumerStrategy() { - return new AbortSlowConsumerStrategy(); - } + @Override + protected AbortSlowConsumerStrategy createSlowConsumerStrategy() { + return new AbortSlowConsumerStrategy(); + } - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - PolicyEntry policy = new PolicyEntry(); + @Override + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); + PolicyEntry policy = new PolicyEntry(); - AbortSlowAckConsumerStrategy strategy = new AbortSlowAckConsumerStrategy(); - strategy.setAbortConnection(abortConnection); - strategy.setCheckPeriod(checkPeriod); - strategy.setMaxSlowDuration(maxSlowDuration); - strategy.setMaxTimeSinceLastAck(maxTimeSinceLastAck); + AbortSlowAckConsumerStrategy strategy = new AbortSlowAckConsumerStrategy(); + strategy.setAbortConnection(abortConnection); + strategy.setCheckPeriod(checkPeriod); + strategy.setMaxSlowDuration(maxSlowDuration); + strategy.setMaxTimeSinceLastAck(maxTimeSinceLastAck); - policy.setSlowConsumerStrategy(strategy); - policy.setQueuePrefetch(10); - policy.setTopicPrefetch(10); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - broker.setDestinationPolicy(pMap); - return broker; - } - - @Override - protected ConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - factory.getPrefetchPolicy().setAll(1); - return factory; - } + policy.setSlowConsumerStrategy(strategy); + policy.setQueuePrefetch(10); + policy.setTopicPrefetch(10); + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); + broker.setDestinationPolicy(pMap); + return broker; + } + @Override + protected ConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + factory.getPrefetchPolicy().setAll(1); + return factory; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumer0Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumer0Test.java index 9f2344350d..a335380d9b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumer0Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumer0Test.java @@ -30,6 +30,7 @@ import javax.management.InstanceNotFoundException; import javax.management.ObjectName; import javax.management.openmbean.CompositeData; import javax.management.openmbean.TabularData; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQMessageConsumer; import org.apache.activemq.ActiveMQPrefetchPolicy; @@ -49,196 +50,191 @@ import org.junit.runners.Parameterized; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import static org.junit.Assert.*; - @RunWith(value = Parameterized.class) public class AbortSlowConsumer0Test extends AbortSlowConsumerBase { - private static final Logger LOG = LoggerFactory.getLogger(AbortSlowConsumer0Test.class); + private static final Logger LOG = LoggerFactory.getLogger(AbortSlowConsumer0Test.class); - @Parameterized.Parameters(name = "isTopic({0})") - public static Collection getTestParameters() { - return Arrays.asList(new Object[][]{{Boolean.TRUE}, {Boolean.FALSE}}); - } + @Parameterized.Parameters(name = "isTopic({0})") + public static Collection getTestParameters() { + return Arrays.asList(new Object[][]{{Boolean.TRUE}, {Boolean.FALSE}}); + } - public AbortSlowConsumer0Test(Boolean isTopic) { - this.topic = isTopic; - } + public AbortSlowConsumer0Test(Boolean isTopic) { + this.topic = isTopic; + } - @Test - public void testRegularConsumerIsNotAborted() throws Exception { - startConsumers(destination); - for (Connection c : connections) { - c.setExceptionListener(this); - } - startProducers(destination, 100); - allMessagesList.waitForMessagesToArrive(10); - allMessagesList.assertAtLeastMessagesReceived(10); - } + @Test + public void testRegularConsumerIsNotAborted() throws Exception { + startConsumers(destination); + for (Connection c : connections) { + c.setExceptionListener(this); + } + startProducers(destination, 100); + allMessagesList.waitForMessagesToArrive(10); + allMessagesList.assertAtLeastMessagesReceived(10); + } - @Test - public void testSlowConsumerIsAbortedViaJmx() throws Exception { - underTest.setMaxSlowDuration(60*1000); // so jmx does the abort - startConsumers(withPrefetch(2, destination)); - Entry consumertoAbort = consumers.entrySet().iterator().next(); - consumertoAbort.getValue().setProcessingDelay(8 * 1000); - for (Connection c : connections) { - c.setExceptionListener(this); - } - startProducers(destination, 100); + @Test + public void testSlowConsumerIsAbortedViaJmx() throws Exception { + underTest.setMaxSlowDuration(60 * 1000); // so jmx does the abort + startConsumers(withPrefetch(2, destination)); + Entry consumertoAbort = consumers.entrySet().iterator().next(); + consumertoAbort.getValue().setProcessingDelay(8 * 1000); + for (Connection c : connections) { + c.setExceptionListener(this); + } + startProducers(destination, 100); - consumertoAbort.getValue().assertMessagesReceived(1); + consumertoAbort.getValue().assertMessagesReceived(1); - ActiveMQDestination amqDest = (ActiveMQDestination)destination; - ObjectName destinationViewMBean = new ObjectName("org.apache.activemq:destinationType=" + - (amqDest.isTopic() ? "Topic" : "Queue") +",destinationName=" - + amqDest.getPhysicalName() + ",type=Broker,brokerName=localhost"); + ActiveMQDestination amqDest = (ActiveMQDestination) destination; + ObjectName destinationViewMBean = new ObjectName("org.apache.activemq:destinationType=" + + (amqDest.isTopic() ? "Topic" : "Queue") + ",destinationName=" + amqDest.getPhysicalName() + ",type=Broker,brokerName=localhost"); - DestinationViewMBean queue = (DestinationViewMBean) broker.getManagementContext().newProxyInstance(destinationViewMBean, DestinationViewMBean.class, true); - ObjectName slowConsumerPolicyMBeanName = queue.getSlowConsumerStrategy(); + DestinationViewMBean queue = (DestinationViewMBean) broker.getManagementContext().newProxyInstance(destinationViewMBean, DestinationViewMBean.class, true); + ObjectName slowConsumerPolicyMBeanName = queue.getSlowConsumerStrategy(); - assertNotNull(slowConsumerPolicyMBeanName); + assertNotNull(slowConsumerPolicyMBeanName); - AbortSlowConsumerStrategyViewMBean abortPolicy = (AbortSlowConsumerStrategyViewMBean) - broker.getManagementContext().newProxyInstance(slowConsumerPolicyMBeanName, AbortSlowConsumerStrategyViewMBean.class, true); + AbortSlowConsumerStrategyViewMBean abortPolicy = (AbortSlowConsumerStrategyViewMBean) broker.getManagementContext().newProxyInstance(slowConsumerPolicyMBeanName, AbortSlowConsumerStrategyViewMBean.class, true); - TimeUnit.SECONDS.sleep(3); + TimeUnit.SECONDS.sleep(3); - TabularData slowOnes = abortPolicy.getSlowConsumers(); - assertEquals("one slow consumers", 1, slowOnes.size()); + TabularData slowOnes = abortPolicy.getSlowConsumers(); + assertEquals("one slow consumers", 1, slowOnes.size()); - LOG.info("slow ones:" + slowOnes); + LOG.info("slow ones:" + slowOnes); - CompositeData slowOne = (CompositeData) slowOnes.values().iterator().next(); - LOG.info("Slow one: " + slowOne); + CompositeData slowOne = (CompositeData) slowOnes.values().iterator().next(); + LOG.info("Slow one: " + slowOne); - assertTrue("we have an object name", slowOne.get("subscription") instanceof ObjectName); - abortPolicy.abortConsumer((ObjectName)slowOne.get("subscription")); + assertTrue("we have an object name", slowOne.get("subscription") instanceof ObjectName); + abortPolicy.abortConsumer((ObjectName) slowOne.get("subscription")); - consumertoAbort.getValue().assertAtMostMessagesReceived(1); + consumertoAbort.getValue().assertAtMostMessagesReceived(1); - slowOnes = abortPolicy.getSlowConsumers(); - assertEquals("no slow consumers left", 0, slowOnes.size()); + slowOnes = abortPolicy.getSlowConsumers(); + assertEquals("no slow consumers left", 0, slowOnes.size()); - // verify mbean gone with destination - broker.getAdminView().removeTopic(amqDest.getPhysicalName()); + // verify mbean gone with destination + broker.getAdminView().removeTopic(amqDest.getPhysicalName()); - try { - abortPolicy.getSlowConsumers(); - fail("expect not found post destination removal"); - } catch(UndeclaredThrowableException expected) { - assertTrue("correct exception: " + expected.getCause(), - expected.getCause() instanceof InstanceNotFoundException); - } - } + try { + abortPolicy.getSlowConsumers(); + fail("expect not found post destination removal"); + } + catch (UndeclaredThrowableException expected) { + assertTrue("correct exception: " + expected.getCause(), expected.getCause() instanceof InstanceNotFoundException); + } + } - private Destination withPrefetch(int i, Destination destination) { - String destWithPrefetch = - ((ActiveMQDestination) destination).getPhysicalName() + "?consumer.prefetchSize=" + i; - return topic ? new ActiveMQTopic(destWithPrefetch) : new ActiveMQQueue(destWithPrefetch); - } + private Destination withPrefetch(int i, Destination destination) { + String destWithPrefetch = ((ActiveMQDestination) destination).getPhysicalName() + "?consumer.prefetchSize=" + i; + return topic ? new ActiveMQTopic(destWithPrefetch) : new ActiveMQQueue(destWithPrefetch); + } - @Test - public void testOnlyOneSlowConsumerIsAborted() throws Exception { - consumerCount = 10; - startConsumers(destination); - Entry consumertoAbort = consumers.entrySet().iterator().next(); - consumertoAbort.getValue().setProcessingDelay(8 * 1000); - for (Connection c : connections) { - c.setExceptionListener(this); - } - startProducers(destination, 100); + @Test + public void testOnlyOneSlowConsumerIsAborted() throws Exception { + consumerCount = 10; + startConsumers(destination); + Entry consumertoAbort = consumers.entrySet().iterator().next(); + consumertoAbort.getValue().setProcessingDelay(8 * 1000); + for (Connection c : connections) { + c.setExceptionListener(this); + } + startProducers(destination, 100); - allMessagesList.waitForMessagesToArrive(99); - allMessagesList.assertAtLeastMessagesReceived(99); + allMessagesList.waitForMessagesToArrive(99); + allMessagesList.assertAtLeastMessagesReceived(99); - consumertoAbort.getValue().assertMessagesReceived(1); - TimeUnit.SECONDS.sleep(5); - consumertoAbort.getValue().assertAtMostMessagesReceived(1); - } + consumertoAbort.getValue().assertMessagesReceived(1); + TimeUnit.SECONDS.sleep(5); + consumertoAbort.getValue().assertAtMostMessagesReceived(1); + } - @Test - public void testAbortAlreadyClosingConsumers() throws Exception { - consumerCount = 1; - startConsumers(withPrefetch(2, destination)); - for (MessageIdList list : consumers.values()) { - list.setProcessingDelay(6 * 1000); - } - for (Connection c : connections) { - c.setExceptionListener(this); - } - startProducers(destination, 100); - allMessagesList.waitForMessagesToArrive(consumerCount); + @Test + public void testAbortAlreadyClosingConsumers() throws Exception { + consumerCount = 1; + startConsumers(withPrefetch(2, destination)); + for (MessageIdList list : consumers.values()) { + list.setProcessingDelay(6 * 1000); + } + for (Connection c : connections) { + c.setExceptionListener(this); + } + startProducers(destination, 100); + allMessagesList.waitForMessagesToArrive(consumerCount); - for (MessageConsumer consumer : consumers.keySet()) { - LOG.info("closing consumer: " + consumer); - /// will block waiting for on message till 6secs expire - consumer.close(); - } - } + for (MessageConsumer consumer : consumers.keySet()) { + LOG.info("closing consumer: " + consumer); + /// will block waiting for on message till 6secs expire + consumer.close(); + } + } - @Test - public void testAbortConsumerOnDeadConnection() throws Exception { - TransportConnector transportConnector = broker.addConnector("tcp://0.0.0.0:0"); - transportConnector.setBrokerService(broker); - transportConnector.setTaskRunnerFactory(broker.getTaskRunnerFactory()); - transportConnector.start(); - SocketProxy socketProxy = new SocketProxy(transportConnector.getPublishableConnectURI()); - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(socketProxy.getUrl()); - ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); - prefetchPolicy.setAll(4); - connectionFactory.setPrefetchPolicy(prefetchPolicy); - Connection c = connectionFactory.createConnection(); - connections.add(c); - c.start(); - Session session = c.createSession(false, Session.CLIENT_ACKNOWLEDGE); - final ActiveMQMessageConsumer messageconsumer = (ActiveMQMessageConsumer) session.createConsumer(destination); - startProducers(destination, 10); + @Test + public void testAbortConsumerOnDeadConnection() throws Exception { + TransportConnector transportConnector = broker.addConnector("tcp://0.0.0.0:0"); + transportConnector.setBrokerService(broker); + transportConnector.setTaskRunnerFactory(broker.getTaskRunnerFactory()); + transportConnector.start(); + SocketProxy socketProxy = new SocketProxy(transportConnector.getPublishableConnectURI()); + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(socketProxy.getUrl()); + ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); + prefetchPolicy.setAll(4); + connectionFactory.setPrefetchPolicy(prefetchPolicy); + Connection c = connectionFactory.createConnection(); + connections.add(c); + c.start(); + Session session = c.createSession(false, Session.CLIENT_ACKNOWLEDGE); + final ActiveMQMessageConsumer messageconsumer = (ActiveMQMessageConsumer) session.createConsumer(destination); + startProducers(destination, 10); - messageconsumer.receive(4000).acknowledge(); - assertNotNull(messageconsumer.receive(4000)); - assertNotNull(messageconsumer.receive(4000)); - assertNotNull(messageconsumer.receive(4000)); + messageconsumer.receive(4000).acknowledge(); + assertNotNull(messageconsumer.receive(4000)); + assertNotNull(messageconsumer.receive(4000)); + assertNotNull(messageconsumer.receive(4000)); - // close control command won't get through - socketProxy.pause(); + // close control command won't get through + socketProxy.pause(); - ActiveMQDestination amqDest = (ActiveMQDestination)destination; - ObjectName destinationViewMBean = new ObjectName("org.apache.activemq:destinationType=" + - (amqDest.isTopic() ? "Topic" : "Queue") +",destinationName=" - + amqDest.getPhysicalName() + ",type=Broker,brokerName=localhost"); + ActiveMQDestination amqDest = (ActiveMQDestination) destination; + ObjectName destinationViewMBean = new ObjectName("org.apache.activemq:destinationType=" + + (amqDest.isTopic() ? "Topic" : "Queue") + ",destinationName=" + amqDest.getPhysicalName() + ",type=Broker,brokerName=localhost"); - final DestinationViewMBean destView = (DestinationViewMBean) broker.getManagementContext().newProxyInstance(destinationViewMBean, DestinationViewMBean.class, true); + final DestinationViewMBean destView = (DestinationViewMBean) broker.getManagementContext().newProxyInstance(destinationViewMBean, DestinationViewMBean.class, true); - assertTrue("Consumer gone from broker view", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("DestView {} comsumerCount {}", destView, destView.getConsumerCount()); - return 0 == destView.getConsumerCount(); + assertTrue("Consumer gone from broker view", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("DestView {} comsumerCount {}", destView, destView.getConsumerCount()); + return 0 == destView.getConsumerCount(); + } + })); + + socketProxy.goOn(); + + assertTrue("consumer was closed", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + boolean closed = false; + try { + messageconsumer.receive(400); } - })); - - socketProxy.goOn(); - - assertTrue("consumer was closed", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - boolean closed = false; - try { - messageconsumer.receive(400); - } catch (javax.jms.IllegalStateException expected) { - closed = expected.toString().contains("closed"); - } - return closed; + catch (javax.jms.IllegalStateException expected) { + closed = expected.toString().contains("closed"); } - })); - } + return closed; + } + })); + } - @Override - public void onException(JMSException exception) { - exceptions.add(exception); - exception.printStackTrace(); - } + @Override + public void onException(JMSException exception) { + exceptions.add(exception); + exception.printStackTrace(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumer1Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumer1Test.java index 4368f7927a..90d6d85770 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumer1Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumer1Test.java @@ -36,69 +36,65 @@ import static org.junit.Assert.assertTrue; @RunWith(value = Parameterized.class) public class AbortSlowConsumer1Test extends AbortSlowConsumerBase { - private static final Logger LOG = LoggerFactory.getLogger(AbortSlowConsumer1Test.class); + private static final Logger LOG = LoggerFactory.getLogger(AbortSlowConsumer1Test.class); - @Parameterized.Parameters(name = "abortConnection({0})-isTopic({1})") - public static Collection getTestParameters() { - return Arrays.asList(new Object[][]{ - {Boolean.TRUE, Boolean.TRUE}, - {Boolean.TRUE, Boolean.FALSE}, - {Boolean.FALSE, Boolean.TRUE}, - {Boolean.FALSE, Boolean.FALSE}}); - } + @Parameterized.Parameters(name = "abortConnection({0})-isTopic({1})") + public static Collection getTestParameters() { + return Arrays.asList(new Object[][]{{Boolean.TRUE, Boolean.TRUE}, {Boolean.TRUE, Boolean.FALSE}, {Boolean.FALSE, Boolean.TRUE}, {Boolean.FALSE, Boolean.FALSE}}); + } - public AbortSlowConsumer1Test(Boolean abortConnection, Boolean topic) { - this.abortConnection = abortConnection; - this.topic = topic; - } + public AbortSlowConsumer1Test(Boolean abortConnection, Boolean topic) { + this.abortConnection = abortConnection; + this.topic = topic; + } - @Test(timeout = 60 * 1000) - public void testSlowConsumerIsAborted() throws Exception { - startConsumers(destination); - Entry consumertoAbort = consumers.entrySet().iterator().next(); - consumertoAbort.getValue().setProcessingDelay(8 * 1000); - for (Connection c : connections) { - c.setExceptionListener(this); - } - startProducers(destination, 100); + @Test(timeout = 60 * 1000) + public void testSlowConsumerIsAborted() throws Exception { + startConsumers(destination); + Entry consumertoAbort = consumers.entrySet().iterator().next(); + consumertoAbort.getValue().setProcessingDelay(8 * 1000); + for (Connection c : connections) { + c.setExceptionListener(this); + } + startProducers(destination, 100); - consumertoAbort.getValue().assertMessagesReceived(1); - TimeUnit.SECONDS.sleep(5); - consumertoAbort.getValue().assertAtMostMessagesReceived(1); - } + consumertoAbort.getValue().assertMessagesReceived(1); + TimeUnit.SECONDS.sleep(5); + consumertoAbort.getValue().assertAtMostMessagesReceived(1); + } - @Test(timeout = 60 * 1000) - public void testAbortAlreadyClosedConsumers() throws Exception { - Connection conn = createConnectionFactory().createConnection(); - conn.setExceptionListener(this); - connections.add(conn); + @Test(timeout = 60 * 1000) + public void testAbortAlreadyClosedConsumers() throws Exception { + Connection conn = createConnectionFactory().createConnection(); + conn.setExceptionListener(this); + connections.add(conn); - Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); - final MessageConsumer consumer = sess.createConsumer(destination); - conn.start(); - startProducers(destination, 20); - TimeUnit.SECONDS.sleep(1); - LOG.info("closing consumer: " + consumer); - consumer.close(); + Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); + final MessageConsumer consumer = sess.createConsumer(destination); + conn.start(); + startProducers(destination, 20); + TimeUnit.SECONDS.sleep(1); + LOG.info("closing consumer: " + consumer); + consumer.close(); - TimeUnit.SECONDS.sleep(5); - assertTrue("no exceptions : " + exceptions, exceptions.isEmpty()); - } + TimeUnit.SECONDS.sleep(5); + assertTrue("no exceptions : " + exceptions, exceptions.isEmpty()); + } - @Test(timeout = 60 * 1000) - public void testAbortAlreadyClosedConnection() throws Exception { - Connection conn = createConnectionFactory().createConnection(); - conn.setExceptionListener(this); + @Test(timeout = 60 * 1000) + public void testAbortAlreadyClosedConnection() throws Exception { + Connection conn = createConnectionFactory().createConnection(); + conn.setExceptionListener(this); - Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); - sess.createConsumer(destination); - conn.start(); - startProducers(destination, 20); - TimeUnit.SECONDS.sleep(1); - LOG.info("closing connection: " + conn); - conn.close(); + Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); + sess.createConsumer(destination); + conn.start(); + startProducers(destination, 20); + TimeUnit.SECONDS.sleep(1); + LOG.info("closing connection: " + conn); + conn.close(); - TimeUnit.SECONDS.sleep(5); - assertTrue("no exceptions : " + exceptions, exceptions.isEmpty()); - } + TimeUnit.SECONDS.sleep(5); + assertTrue("no exceptions : " + exceptions, exceptions.isEmpty()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumer2Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumer2Test.java index 72630278cc..b664122e0a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumer2Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumer2Test.java @@ -21,6 +21,7 @@ import java.util.Collection; import java.util.Map.Entry; import javax.jms.Connection; import javax.jms.MessageConsumer; + import org.apache.activemq.util.MessageIdList; import org.junit.Test; import org.junit.runner.RunWith; @@ -29,25 +30,25 @@ import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) public class AbortSlowConsumer2Test extends AbortSlowConsumerBase { - @Parameterized.Parameters(name = "isTopic({0})") - public static Collection getTestParameters() { - return Arrays.asList(new Object[][]{{Boolean.TRUE}, {Boolean.FALSE}}); - } + @Parameterized.Parameters(name = "isTopic({0})") + public static Collection getTestParameters() { + return Arrays.asList(new Object[][]{{Boolean.TRUE}, {Boolean.FALSE}}); + } - public AbortSlowConsumer2Test(Boolean isTopic) { - this.topic = isTopic; - } + public AbortSlowConsumer2Test(Boolean isTopic) { + this.topic = isTopic; + } - @Test(timeout = 60 * 1000) - public void testLittleSlowConsumerIsNotAborted() throws Exception { - startConsumers(destination); - Entry consumertoAbort = consumers.entrySet().iterator().next(); - consumertoAbort.getValue().setProcessingDelay(500); - for (Connection c : connections) { - c.setExceptionListener(this); - } - startProducers(destination, 12); - allMessagesList.waitForMessagesToArrive(10); - allMessagesList.assertAtLeastMessagesReceived(10); - } + @Test(timeout = 60 * 1000) + public void testLittleSlowConsumerIsNotAborted() throws Exception { + startConsumers(destination); + Entry consumertoAbort = consumers.entrySet().iterator().next(); + consumertoAbort.getValue().setProcessingDelay(500); + for (Connection c : connections) { + c.setExceptionListener(this); + } + startProducers(destination, 12); + allMessagesList.waitForMessagesToArrive(10); + allMessagesList.assertAtLeastMessagesReceived(10); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumerBase.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumerBase.java index ee28112dbe..28cb1ee9bb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumerBase.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumerBase.java @@ -17,6 +17,7 @@ package org.apache.activemq.broker.policy; import junit.framework.Test; + import org.apache.activemq.JmsMultipleClientsTestSupport; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.jmx.AbortSlowConsumerStrategyViewMBean; @@ -45,52 +46,51 @@ import java.util.List; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; - public class AbortSlowConsumerBase extends JmsMultipleClientsTestSupport implements ExceptionListener { - private static final Logger LOG = LoggerFactory.getLogger(AbortSlowConsumerBase.class); + private static final Logger LOG = LoggerFactory.getLogger(AbortSlowConsumerBase.class); - protected AbortSlowConsumerStrategy underTest; - protected boolean abortConnection = false; - protected long checkPeriod = 2 * 1000; - protected long maxSlowDuration = 5 * 1000; - protected final List exceptions = new ArrayList(); + protected AbortSlowConsumerStrategy underTest; + protected boolean abortConnection = false; + protected long checkPeriod = 2 * 1000; + protected long maxSlowDuration = 5 * 1000; + protected final List exceptions = new ArrayList(); - @Override - @Before - public void setUp() throws Exception { - exceptions.clear(); - topic = true; - underTest = createSlowConsumerStrategy(); - super.setUp(); - createDestination(); - } + @Override + @Before + public void setUp() throws Exception { + exceptions.clear(); + topic = true; + underTest = createSlowConsumerStrategy(); + super.setUp(); + createDestination(); + } - protected AbortSlowConsumerStrategy createSlowConsumerStrategy() { - return new AbortSlowConsumerStrategy(); - } + protected AbortSlowConsumerStrategy createSlowConsumerStrategy() { + return new AbortSlowConsumerStrategy(); + } - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - PolicyEntry policy = new PolicyEntry(); - underTest.setAbortConnection(abortConnection); - underTest.setCheckPeriod(checkPeriod); - underTest.setMaxSlowDuration(maxSlowDuration); + @Override + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); + PolicyEntry policy = new PolicyEntry(); + underTest.setAbortConnection(abortConnection); + underTest.setCheckPeriod(checkPeriod); + underTest.setMaxSlowDuration(maxSlowDuration); - policy.setSlowConsumerStrategy(underTest); - policy.setQueuePrefetch(10); - policy.setTopicPrefetch(10); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - broker.setDestinationPolicy(pMap); - return broker; - } + policy.setSlowConsumerStrategy(underTest); + policy.setQueuePrefetch(10); + policy.setTopicPrefetch(10); + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); + broker.setDestinationPolicy(pMap); + return broker; + } - @Override - public void onException(JMSException exception) { - exceptions.add(exception); - exception.printStackTrace(); - } + @Override + public void onException(JMSException exception) { + exceptions.add(exception); + exception.printStackTrace(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DeadLetterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DeadLetterTest.java index 6c31237759..a22dc25241 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DeadLetterTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DeadLetterTest.java @@ -27,68 +27,69 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * - * + * + * */ public class DeadLetterTest extends DeadLetterTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(DeadLetterTest.class); - protected int rollbackCount; + private static final Logger LOG = LoggerFactory.getLogger(DeadLetterTest.class); - protected void doTest() throws Exception { - connection.start(); + protected int rollbackCount; - ActiveMQConnection amqConnection = (ActiveMQConnection) connection; - rollbackCount = amqConnection.getRedeliveryPolicy().getMaximumRedeliveries() + 1; - LOG.info("Will redeliver messages: " + rollbackCount + " times"); + protected void doTest() throws Exception { + connection.start(); - makeConsumer(); - makeDlqConsumer(); + ActiveMQConnection amqConnection = (ActiveMQConnection) connection; + rollbackCount = amqConnection.getRedeliveryPolicy().getMaximumRedeliveries() + 1; + LOG.info("Will redeliver messages: " + rollbackCount + " times"); - sendMessages(); + makeConsumer(); + makeDlqConsumer(); - // now lets receive and rollback N times - for (int i = 0; i < messageCount; i++) { - consumeAndRollback(i); - } + sendMessages(); - for (int i = 0; i < messageCount; i++) { - Message msg = dlqConsumer.receive(1000); - assertMessage(msg, i); - assertNotNull("Should be a DLQ message for loop: " + i, msg); - } - session.commit(); - } + // now lets receive and rollback N times + for (int i = 0; i < messageCount; i++) { + consumeAndRollback(i); + } - protected void consumeAndRollback(int messageCounter) throws Exception { - for (int i = 0; i < rollbackCount; i++) { - Message message = consumer.receive(5000); - assertNotNull("No message received for message: " + messageCounter + " and rollback loop: " + i, message); - assertMessage(message, messageCounter); + for (int i = 0; i < messageCount; i++) { + Message msg = dlqConsumer.receive(1000); + assertMessage(msg, i); + assertNotNull("Should be a DLQ message for loop: " + i, msg); + } + session.commit(); + } - session.rollback(); - } - LOG.info("Rolled back: " + rollbackCount + " times"); - } + protected void consumeAndRollback(int messageCounter) throws Exception { + for (int i = 0; i < rollbackCount; i++) { + Message message = consumer.receive(5000); + assertNotNull("No message received for message: " + messageCounter + " and rollback loop: " + i, message); + assertMessage(message, messageCounter); - protected void setUp() throws Exception { - transactedMode = true; - super.setUp(); - } + session.rollback(); + } + LOG.info("Rolled back: " + rollbackCount + " times"); + } - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory answer = super.createConnectionFactory(); - RedeliveryPolicy policy = new RedeliveryPolicy(); - policy.setMaximumRedeliveries(3); - policy.setBackOffMultiplier((short) 1); - policy.setInitialRedeliveryDelay(10); - policy.setUseExponentialBackOff(false); - answer.setRedeliveryPolicy(policy); - return answer; - } + protected void setUp() throws Exception { + transactedMode = true; + super.setUp(); + } - protected Destination createDlqDestination() { - return new ActiveMQQueue("ActiveMQ.DLQ"); - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory answer = super.createConnectionFactory(); + RedeliveryPolicy policy = new RedeliveryPolicy(); + policy.setMaximumRedeliveries(3); + policy.setBackOffMultiplier((short) 1); + policy.setInitialRedeliveryDelay(10); + policy.setUseExponentialBackOff(false); + answer.setRedeliveryPolicy(policy); + return answer; + } + + protected Destination createDlqDestination() { + return new ActiveMQQueue("ActiveMQ.DLQ"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DeadLetterTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DeadLetterTestSupport.java index b275f2ea39..d61baa9a6e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DeadLetterTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DeadLetterTestSupport.java @@ -40,172 +40,174 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public abstract class DeadLetterTestSupport extends TestSupport { - private static final Logger LOG = LoggerFactory.getLogger(DeadLetterTestSupport.class); - protected int messageCount = 10; - protected long timeToLive; - protected Connection connection; - protected Session session; - protected MessageConsumer consumer; - protected MessageProducer producer; - protected int deliveryMode = DeliveryMode.PERSISTENT; - protected boolean durableSubscriber; - protected Destination dlqDestination; - protected MessageConsumer dlqConsumer; - protected QueueBrowser dlqBrowser; - protected BrokerService broker; - protected boolean transactedMode; - protected int acknowledgeMode = Session.CLIENT_ACKNOWLEDGE; - private Destination destination; + private static final Logger LOG = LoggerFactory.getLogger(DeadLetterTestSupport.class); - protected void setUp() throws Exception { - super.setUp(); - broker = createBroker(); - broker.start(); - connection = createConnection(); - connection.setClientID(createClientId()); + protected int messageCount = 10; + protected long timeToLive; + protected Connection connection; + protected Session session; + protected MessageConsumer consumer; + protected MessageProducer producer; + protected int deliveryMode = DeliveryMode.PERSISTENT; + protected boolean durableSubscriber; + protected Destination dlqDestination; + protected MessageConsumer dlqConsumer; + protected QueueBrowser dlqBrowser; + protected BrokerService broker; + protected boolean transactedMode; + protected int acknowledgeMode = Session.CLIENT_ACKNOWLEDGE; + private Destination destination; - session = connection.createSession(transactedMode, acknowledgeMode); - connection.start(); - } + protected void setUp() throws Exception { + super.setUp(); + broker = createBroker(); + broker.start(); + connection = createConnection(); + connection.setClientID(createClientId()); - protected String createClientId() { - return toString(); - } + session = connection.createSession(transactedMode, acknowledgeMode); + connection.start(); + } - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - if (broker != null) { - broker.stop(); - } - } + protected String createClientId() { + return toString(); + } - protected abstract void doTest() throws Exception; + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + } + if (broker != null) { + broker.stop(); + } + } - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setPersistent(false); - PolicyEntry policy = new PolicyEntry(); - DeadLetterStrategy defaultDeadLetterStrategy = policy.getDeadLetterStrategy(); - if(defaultDeadLetterStrategy!=null) { - defaultDeadLetterStrategy.setProcessNonPersistent(true); - } - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - broker.setDestinationPolicy(pMap); - return broker; - } + protected abstract void doTest() throws Exception; - protected void makeConsumer() throws JMSException { - Destination destination = getDestination(); - LOG.info("Consuming from: " + destination); - if (durableSubscriber) { - consumer = session.createDurableSubscriber((Topic)destination, destination.toString()); - } else { - consumer = session.createConsumer(destination); - } - } + protected BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setPersistent(false); + PolicyEntry policy = new PolicyEntry(); + DeadLetterStrategy defaultDeadLetterStrategy = policy.getDeadLetterStrategy(); + if (defaultDeadLetterStrategy != null) { + defaultDeadLetterStrategy.setProcessNonPersistent(true); + } + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); + broker.setDestinationPolicy(pMap); + return broker; + } - protected void makeDlqConsumer() throws Exception { - dlqDestination = createDlqDestination(); + protected void makeConsumer() throws JMSException { + Destination destination = getDestination(); + LOG.info("Consuming from: " + destination); + if (durableSubscriber) { + consumer = session.createDurableSubscriber((Topic) destination, destination.toString()); + } + else { + consumer = session.createConsumer(destination); + } + } - LOG.info("Consuming from dead letter on: " + dlqDestination); - dlqConsumer = session.createConsumer(dlqDestination); - } - - protected void makeDlqBrowser() throws JMSException { - dlqDestination = createDlqDestination(); + protected void makeDlqConsumer() throws Exception { + dlqDestination = createDlqDestination(); - LOG.info("Browsing dead letter on: " + dlqDestination); - dlqBrowser = session.createBrowser((Queue)dlqDestination); - } + LOG.info("Consuming from dead letter on: " + dlqDestination); + dlqConsumer = session.createConsumer(dlqDestination); + } - protected void sendMessages() throws JMSException { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(getDestination()); - producer.setDeliveryMode(deliveryMode); - producer.setTimeToLive(timeToLive); + protected void makeDlqBrowser() throws JMSException { + dlqDestination = createDlqDestination(); - LOG.info("Sending " + messageCount + " messages to: " + getDestination()); - for (int i = 0; i < messageCount; i++) { - Message message = createMessage(session, i); - producer.send(message); - } - } + LOG.info("Browsing dead letter on: " + dlqDestination); + dlqBrowser = session.createBrowser((Queue) dlqDestination); + } - protected TextMessage createMessage(Session session, int i) throws JMSException { - return session.createTextMessage(getMessageText(i)); - } + protected void sendMessages() throws JMSException { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer = session.createProducer(getDestination()); + producer.setDeliveryMode(deliveryMode); + producer.setTimeToLive(timeToLive); - protected String getMessageText(int i) { - return "message: " + i; - } + LOG.info("Sending " + messageCount + " messages to: " + getDestination()); + for (int i = 0; i < messageCount; i++) { + Message message = createMessage(session, i); + producer.send(message); + } + } - protected void assertMessage(Message message, int i) throws Exception { - LOG.info("Received message: " + message); - assertNotNull("No message received for index: " + i, message); - assertTrue("Should be a TextMessage not: " + message, message instanceof TextMessage); - TextMessage textMessage = (TextMessage)message; - assertEquals("text of message: " + i, getMessageText(i), textMessage.getText()); - } + protected TextMessage createMessage(Session session, int i) throws JMSException { + return session.createTextMessage(getMessageText(i)); + } - protected abstract Destination createDlqDestination(); + protected String getMessageText(int i) { + return "message: " + i; + } - public void testTransientTopicMessage() throws Exception { - super.topic = true; - deliveryMode = DeliveryMode.NON_PERSISTENT; - durableSubscriber = true; - doTest(); - } + protected void assertMessage(Message message, int i) throws Exception { + LOG.info("Received message: " + message); + assertNotNull("No message received for index: " + i, message); + assertTrue("Should be a TextMessage not: " + message, message instanceof TextMessage); + TextMessage textMessage = (TextMessage) message; + assertEquals("text of message: " + i, getMessageText(i), textMessage.getText()); + } - public void testDurableTopicMessage() throws Exception { - super.topic = true; - deliveryMode = DeliveryMode.PERSISTENT; - durableSubscriber = true; - doTest(); - } + protected abstract Destination createDlqDestination(); - public void testTransientQueueMessage() throws Exception { - super.topic = false; - deliveryMode = DeliveryMode.NON_PERSISTENT; - durableSubscriber = false; - doTest(); - validateConsumerPrefetch(this.getDestinationString(), 0); - } - - public void testDurableQueueMessage() throws Exception { - super.topic = false; - deliveryMode = DeliveryMode.PERSISTENT; - durableSubscriber = false; - doTest(); - validateConsumerPrefetch(this.getDestinationString(), 0); - } + public void testTransientTopicMessage() throws Exception { + super.topic = true; + deliveryMode = DeliveryMode.NON_PERSISTENT; + durableSubscriber = true; + doTest(); + } - public Destination getDestination() { - if (destination == null) { - destination = createDestination(); - } - return destination; - } - - private void validateConsumerPrefetch(String destination, long expectedCount) { - try { - Thread.sleep(100); - } catch (InterruptedException e) { - } - RegionBroker regionBroker = (RegionBroker) broker.getRegionBroker(); - for (org.apache.activemq.broker.region.Destination dest : regionBroker.getQueueRegion().getDestinationMap().values()) { - if (dest.getName().equals(destination)) { - DestinationStatistics stats = dest.getDestinationStatistics(); - LOG.info(">>>> inflight for : " + dest.getName() + ": " + stats.getInflight().getCount()); - assertEquals("inflight for: " + dest.getName() + ": " + stats.getInflight().getCount() + " matches", - expectedCount, stats.getInflight().getCount()); - } - } - } + public void testDurableTopicMessage() throws Exception { + super.topic = true; + deliveryMode = DeliveryMode.PERSISTENT; + durableSubscriber = true; + doTest(); + } + + public void testTransientQueueMessage() throws Exception { + super.topic = false; + deliveryMode = DeliveryMode.NON_PERSISTENT; + durableSubscriber = false; + doTest(); + validateConsumerPrefetch(this.getDestinationString(), 0); + } + + public void testDurableQueueMessage() throws Exception { + super.topic = false; + deliveryMode = DeliveryMode.PERSISTENT; + durableSubscriber = false; + doTest(); + validateConsumerPrefetch(this.getDestinationString(), 0); + } + + public Destination getDestination() { + if (destination == null) { + destination = createDestination(); + } + return destination; + } + + private void validateConsumerPrefetch(String destination, long expectedCount) { + try { + Thread.sleep(100); + } + catch (InterruptedException e) { + } + RegionBroker regionBroker = (RegionBroker) broker.getRegionBroker(); + for (org.apache.activemq.broker.region.Destination dest : regionBroker.getQueueRegion().getDestinationMap().values()) { + if (dest.getName().equals(destination)) { + DestinationStatistics stats = dest.getDestinationStatistics(); + LOG.info(">>>> inflight for : " + dest.getName() + ": " + stats.getInflight().getCount()); + assertEquals("inflight for: " + dest.getName() + ": " + stats.getInflight().getCount() + " matches", expectedCount, stats.getInflight().getCount()); + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DestinationCursorConfigTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DestinationCursorConfigTest.java index a5f7984b38..faab3acbf1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DestinationCursorConfigTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DestinationCursorConfigTest.java @@ -28,47 +28,48 @@ import org.apache.activemq.xbean.BrokerFactoryBean; import org.springframework.core.io.ClassPathResource; /** - * + * */ public class DestinationCursorConfigTest extends TestSupport { - protected BrokerService broker; - @Override - protected void setUp() throws Exception { - broker = createBroker(); - super.setUp(); - } + protected BrokerService broker; - @Override - protected void tearDown() throws Exception { - broker.stop(); - super.tearDown(); - } + @Override + protected void setUp() throws Exception { + broker = createBroker(); + super.setUp(); + } - protected BrokerService createBroker() throws Exception { - BrokerFactoryBean factory = new BrokerFactoryBean(new ClassPathResource("org/apache/activemq/broker/policy/cursor.xml")); - factory.afterPropertiesSet(); - BrokerService answer = factory.getBroker(); - return answer; - } + @Override + protected void tearDown() throws Exception { + broker.stop(); + super.tearDown(); + } - public void testQueueConfiguration() throws Exception { - super.topic = false; - ActiveMQDestination destination = (ActiveMQDestination) createDestination("org.apache.foo"); - PolicyEntry entry = broker.getDestinationPolicy().getEntryFor(destination); - PendingQueueMessageStoragePolicy policy = entry.getPendingQueuePolicy(); - assertNotNull(policy); - assertTrue("Policy is: " + policy, policy instanceof VMPendingQueueMessageStoragePolicy); - } + protected BrokerService createBroker() throws Exception { + BrokerFactoryBean factory = new BrokerFactoryBean(new ClassPathResource("org/apache/activemq/broker/policy/cursor.xml")); + factory.afterPropertiesSet(); + BrokerService answer = factory.getBroker(); + return answer; + } - public void testTopicConfiguration() throws Exception { - super.topic = true; - ActiveMQDestination destination = (ActiveMQDestination) createDestination("org.apache.foo"); - PolicyEntry entry = broker.getDestinationPolicy().getEntryFor(destination); - PendingSubscriberMessageStoragePolicy policy = entry.getPendingSubscriberPolicy(); - assertNotNull(policy); - assertFalse(entry.isProducerFlowControl()); - assertTrue(entry.getMemoryLimit()==(1024*1024)); - assertTrue("subscriberPolicy is: " + policy, policy instanceof VMPendingSubscriberMessageStoragePolicy); - } + public void testQueueConfiguration() throws Exception { + super.topic = false; + ActiveMQDestination destination = (ActiveMQDestination) createDestination("org.apache.foo"); + PolicyEntry entry = broker.getDestinationPolicy().getEntryFor(destination); + PendingQueueMessageStoragePolicy policy = entry.getPendingQueuePolicy(); + assertNotNull(policy); + assertTrue("Policy is: " + policy, policy instanceof VMPendingQueueMessageStoragePolicy); + } + + public void testTopicConfiguration() throws Exception { + super.topic = true; + ActiveMQDestination destination = (ActiveMQDestination) createDestination("org.apache.foo"); + PolicyEntry entry = broker.getDestinationPolicy().getEntryFor(destination); + PendingSubscriberMessageStoragePolicy policy = entry.getPendingSubscriberPolicy(); + assertNotNull(policy); + assertFalse(entry.isProducerFlowControl()); + assertTrue(entry.getMemoryLimit() == (1024 * 1024)); + assertTrue("subscriberPolicy is: " + policy, policy instanceof VMPendingSubscriberMessageStoragePolicy); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DiscardingDeadLetterPolicyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DiscardingDeadLetterPolicyTest.java index f43f886088..d360286c0d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DiscardingDeadLetterPolicyTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DiscardingDeadLetterPolicyTest.java @@ -31,47 +31,48 @@ import org.slf4j.LoggerFactory; * */ public class DiscardingDeadLetterPolicyTest extends DeadLetterTest { - private static final Logger LOG = LoggerFactory.getLogger(DiscardingDeadLetterPolicyTest.class); - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); + private static final Logger LOG = LoggerFactory.getLogger(DiscardingDeadLetterPolicyTest.class); - PolicyEntry policy = new PolicyEntry(); - DeadLetterStrategy strategy = new DiscardingDeadLetterStrategy(); - strategy.setProcessNonPersistent(true); - policy.setDeadLetterStrategy(strategy); + @Override + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); + PolicyEntry policy = new PolicyEntry(); + DeadLetterStrategy strategy = new DiscardingDeadLetterStrategy(); + strategy.setProcessNonPersistent(true); + policy.setDeadLetterStrategy(strategy); - broker.setDestinationPolicy(pMap); + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); - return broker; - } + broker.setDestinationPolicy(pMap); - @Override - protected void doTest() throws Exception { - connection.start(); + return broker; + } - ActiveMQConnection amqConnection = (ActiveMQConnection) connection; - rollbackCount = amqConnection.getRedeliveryPolicy().getMaximumRedeliveries() + 1; - LOG.info("Will redeliver messages: " + rollbackCount + " times"); + @Override + protected void doTest() throws Exception { + connection.start(); - makeConsumer(); - makeDlqConsumer(); + ActiveMQConnection amqConnection = (ActiveMQConnection) connection; + rollbackCount = amqConnection.getRedeliveryPolicy().getMaximumRedeliveries() + 1; + LOG.info("Will redeliver messages: " + rollbackCount + " times"); - sendMessages(); + makeConsumer(); + makeDlqConsumer(); - // now lets receive and rollback N times - for (int i = 0; i < messageCount; i++) { - consumeAndRollback(i); - } + sendMessages(); - for (int i = 0; i < messageCount; i++) { - Message msg = dlqConsumer.receive(1000); - assertNull("Should not be a DLQ message for loop: " + i, msg); - } - session.commit(); - } + // now lets receive and rollback N times + for (int i = 0; i < messageCount; i++) { + consumeAndRollback(i); + } + + for (int i = 0; i < messageCount; i++) { + Message msg = dlqConsumer.receive(1000); + assertNull("Should not be a DLQ message for loop: " + i, msg); + } + session.commit(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/IndividualDeadLetterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/IndividualDeadLetterTest.java index a587be89d4..fdb5eba4a5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/IndividualDeadLetterTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/IndividualDeadLetterTest.java @@ -38,72 +38,73 @@ import org.slf4j.LoggerFactory; * */ public class IndividualDeadLetterTest extends DeadLetterTest { - private static final Logger LOG = LoggerFactory.getLogger(IndividualDeadLetterTest.class); - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); + private static final Logger LOG = LoggerFactory.getLogger(IndividualDeadLetterTest.class); - PolicyEntry policy = new PolicyEntry(); - DeadLetterStrategy strategy = new IndividualDeadLetterStrategy(); - strategy.setProcessNonPersistent(true); - policy.setDeadLetterStrategy(strategy); + @Override + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); + PolicyEntry policy = new PolicyEntry(); + DeadLetterStrategy strategy = new IndividualDeadLetterStrategy(); + strategy.setProcessNonPersistent(true); + policy.setDeadLetterStrategy(strategy); - broker.setDestinationPolicy(pMap); + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); - return broker; - } + broker.setDestinationPolicy(pMap); - @Override - protected Destination createDlqDestination() { - String prefix = topic ? "ActiveMQ.DLQ.Topic." : "ActiveMQ.DLQ.Queue."; - return new ActiveMQQueue(prefix + getClass().getName() + "." + getName()); - } + return broker; + } - public void testDLQBrowsing() throws Exception { - super.topic = false; - deliveryMode = DeliveryMode.PERSISTENT; - durableSubscriber = false; - messageCount = 1; + @Override + protected Destination createDlqDestination() { + String prefix = topic ? "ActiveMQ.DLQ.Topic." : "ActiveMQ.DLQ.Queue."; + return new ActiveMQQueue(prefix + getClass().getName() + "." + getName()); + } - connection.start(); + public void testDLQBrowsing() throws Exception { + super.topic = false; + deliveryMode = DeliveryMode.PERSISTENT; + durableSubscriber = false; + messageCount = 1; - ActiveMQConnection amqConnection = (ActiveMQConnection) connection; - rollbackCount = amqConnection.getRedeliveryPolicy().getMaximumRedeliveries() + 1; - LOG.info("Will redeliver messages: " + rollbackCount + " times"); + connection.start(); - sendMessages(); + ActiveMQConnection amqConnection = (ActiveMQConnection) connection; + rollbackCount = amqConnection.getRedeliveryPolicy().getMaximumRedeliveries() + 1; + LOG.info("Will redeliver messages: " + rollbackCount + " times"); - // now lets receive and rollback N times - for (int i = 0; i < rollbackCount; i++) { - makeConsumer(); - Message message = consumer.receive(5000); - assertNotNull("No message received: ", message); + sendMessages(); - session.rollback(); - LOG.info("Rolled back: " + rollbackCount + " times"); - consumer.close(); - } + // now lets receive and rollback N times + for (int i = 0; i < rollbackCount; i++) { + makeConsumer(); + Message message = consumer.receive(5000); + assertNotNull("No message received: ", message); - makeDlqBrowser(); - browseDlq(); - dlqBrowser.close(); - session.close(); - Thread.sleep(1000); - session = connection.createSession(transactedMode, acknowledgeMode); - Queue testQueue = new ActiveMQQueue("ActiveMQ.DLQ.Queue.ActiveMQ.DLQ.Queue." + getClass().getName() + "." + getName()); - MessageConsumer testConsumer = session.createConsumer(testQueue); - assertNull("The message shouldn't be sent to another DLQ", testConsumer.receive(1000)); + session.rollback(); + LOG.info("Rolled back: " + rollbackCount + " times"); + consumer.close(); + } - } + makeDlqBrowser(); + browseDlq(); + dlqBrowser.close(); + session.close(); + Thread.sleep(1000); + session = connection.createSession(transactedMode, acknowledgeMode); + Queue testQueue = new ActiveMQQueue("ActiveMQ.DLQ.Queue.ActiveMQ.DLQ.Queue." + getClass().getName() + "." + getName()); + MessageConsumer testConsumer = session.createConsumer(testQueue); + assertNull("The message shouldn't be sent to another DLQ", testConsumer.receive(1000)); - protected void browseDlq() throws Exception { - Enumeration messages = dlqBrowser.getEnumeration(); - while (messages.hasMoreElements()) { - LOG.info("Browsing: " + messages.nextElement()); - } - } + } + + protected void browseDlq() throws Exception { + Enumeration messages = dlqBrowser.getEnumeration(); + while (messages.hasMoreElements()) { + LOG.info("Browsing: " + messages.nextElement()); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/IndividualDeadLetterViaXmlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/IndividualDeadLetterViaXmlTest.java index 6dd87c2c38..138b91faf6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/IndividualDeadLetterViaXmlTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/IndividualDeadLetterViaXmlTest.java @@ -27,22 +27,22 @@ import org.springframework.core.io.ClassPathResource; /** * - * + * */ public class IndividualDeadLetterViaXmlTest extends DeadLetterTest { - private static final Logger LOG = LoggerFactory.getLogger(IndividualDeadLetterViaXmlTest.class); + private static final Logger LOG = LoggerFactory.getLogger(IndividualDeadLetterViaXmlTest.class); - protected BrokerService createBroker() throws Exception { - BrokerFactoryBean factory = new BrokerFactoryBean(new ClassPathResource("org/apache/activemq/broker/policy/individual-dlq.xml")); - factory.afterPropertiesSet(); - BrokerService answer = factory.getBroker(); - return answer; - } + protected BrokerService createBroker() throws Exception { + BrokerFactoryBean factory = new BrokerFactoryBean(new ClassPathResource("org/apache/activemq/broker/policy/individual-dlq.xml")); + factory.afterPropertiesSet(); + BrokerService answer = factory.getBroker(); + return answer; + } - protected Destination createDlqDestination() { - String queueName = "Test.DLQ." + getClass().getName() + "." + getName(); - LOG.info("Using queue name: " + queueName); - return new ActiveMQQueue(queueName); - } + protected Destination createDlqDestination() { + String queueName = "Test.DLQ." + getClass().getName() + "." + getName(); + LOG.info("Using queue name: " + queueName); + return new ActiveMQQueue(queueName); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/MessageGroupConfigTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/MessageGroupConfigTest.java index 112cc463db..e5e815b657 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/MessageGroupConfigTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/MessageGroupConfigTest.java @@ -28,66 +28,64 @@ import org.apache.activemq.broker.region.policy.PolicyMap; import org.apache.activemq.command.ActiveMQDestination; /** - * + * */ public class MessageGroupConfigTest extends TestSupport { - protected BrokerService broker; - @Override - protected void setUp() throws Exception { - super.setUp(); - } + protected BrokerService broker; - @Override - protected void tearDown() throws Exception { - broker.stop(); - super.tearDown(); - } + @Override + protected void setUp() throws Exception { + super.setUp(); + } + @Override + protected void tearDown() throws Exception { + broker.stop(); + super.tearDown(); + } + public void testCachedGroupConfiguration() throws Exception { + doTestGroupConfiguration("cached", CachedMessageGroupMap.class); + } - public void testCachedGroupConfiguration() throws Exception { - doTestGroupConfiguration("cached",CachedMessageGroupMap.class); - } + public void testCachedGroupConfigurationWithCacheSize() throws Exception { + CachedMessageGroupMap result = (CachedMessageGroupMap) doTestGroupConfiguration("cached?cacheSize=10", CachedMessageGroupMap.class); + assertEquals(10, result.getMaximumCacheSize()); - public void testCachedGroupConfigurationWithCacheSize() throws Exception { - CachedMessageGroupMap result = (CachedMessageGroupMap) doTestGroupConfiguration("cached?cacheSize=10",CachedMessageGroupMap.class); - assertEquals(10,result.getMaximumCacheSize()); + } - } + public void testSimpleGroupConfiguration() throws Exception { + doTestGroupConfiguration("simple", SimpleMessageGroupMap.class); + } - public void testSimpleGroupConfiguration() throws Exception { - doTestGroupConfiguration("simple", SimpleMessageGroupMap.class); - } + public void testBucketGroupConfiguration() throws Exception { + doTestGroupConfiguration("bucket", MessageGroupHashBucket.class); + } - public void testBucketGroupConfiguration() throws Exception { - doTestGroupConfiguration("bucket", MessageGroupHashBucket.class); - } + public void testBucketGroupConfigurationWithBucketCount() throws Exception { + MessageGroupHashBucket result = (MessageGroupHashBucket) doTestGroupConfiguration("bucket?bucketCount=2", MessageGroupHashBucket.class); + assertEquals(2, result.getBucketCount()); + } - public void testBucketGroupConfigurationWithBucketCount() throws Exception { - MessageGroupHashBucket result = (MessageGroupHashBucket) doTestGroupConfiguration("bucket?bucketCount=2", MessageGroupHashBucket.class); - assertEquals(2,result.getBucketCount()); - } + public MessageGroupMap doTestGroupConfiguration(String type, Class classType) throws Exception { + broker = new BrokerService(); - public MessageGroupMap doTestGroupConfiguration(String type, Class classType) throws Exception { - broker = new BrokerService(); - - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setMessageGroupMapFactoryType(type); - PolicyMap policyMap = new PolicyMap(); - policyMap.setDefaultEntry(defaultEntry); - broker.setDestinationPolicy(policyMap); - broker.start(); - super.topic = false; - ActiveMQDestination destination = (ActiveMQDestination) createDestination("org.apache.foo"); - Queue brokerDestination = (Queue) broker.getDestination(destination); - - assertNotNull(brokerDestination); - MessageGroupMap messageGroupMap = brokerDestination.getMessageGroupOwners(); - assertNotNull(messageGroupMap); - assertTrue(messageGroupMap.getClass().isAssignableFrom(classType)); - return messageGroupMap; - } + PolicyEntry defaultEntry = new PolicyEntry(); + defaultEntry.setMessageGroupMapFactoryType(type); + PolicyMap policyMap = new PolicyMap(); + policyMap.setDefaultEntry(defaultEntry); + broker.setDestinationPolicy(policyMap); + broker.start(); + super.topic = false; + ActiveMQDestination destination = (ActiveMQDestination) createDestination("org.apache.foo"); + Queue brokerDestination = (Queue) broker.getDestination(destination); + assertNotNull(brokerDestination); + MessageGroupMap messageGroupMap = brokerDestination.getMessageGroupOwners(); + assertNotNull(messageGroupMap); + assertTrue(messageGroupMap.getClass().isAssignableFrom(classType)); + return messageGroupMap; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/MessageListenerDeadLetterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/MessageListenerDeadLetterTest.java index b91f5a8b84..3ee3702506 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/MessageListenerDeadLetterTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/MessageListenerDeadLetterTest.java @@ -32,120 +32,122 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MessageListenerDeadLetterTest extends DeadLetterTestSupport { - private static final Logger LOG = LoggerFactory - .getLogger(MessageListenerDeadLetterTest.class); - private int rollbackCount; + private static final Logger LOG = LoggerFactory.getLogger(MessageListenerDeadLetterTest.class); - private Session dlqSession; + private int rollbackCount; - private final Error[] error = new Error[1]; + private Session dlqSession; - protected void doTest() throws Exception { - messageCount = 200; - connection.start(); + private final Error[] error = new Error[1]; - ActiveMQConnection amqConnection = (ActiveMQConnection) connection; - rollbackCount = amqConnection.getRedeliveryPolicy().getMaximumRedeliveries() + 1; - LOG.info("Will redeliver messages: " + rollbackCount + " times"); + protected void doTest() throws Exception { + messageCount = 200; + connection.start(); - makeConsumer(); - makeDlqConsumer(); + ActiveMQConnection amqConnection = (ActiveMQConnection) connection; + rollbackCount = amqConnection.getRedeliveryPolicy().getMaximumRedeliveries() + 1; + LOG.info("Will redeliver messages: " + rollbackCount + " times"); - sendMessages(); + makeConsumer(); + makeDlqConsumer(); - // now lets receive and rollback N times - int maxRollbacks = messageCount * rollbackCount; - consumer.setMessageListener(new RollbackMessageListener(maxRollbacks, rollbackCount)); + sendMessages(); - for (int i = 0; i < messageCount; i++) { - Message msg = dlqConsumer.receive(4000); - if (error[0] != null) { - // error from message listener - throw error[0]; - } - assertMessage(msg, i); - assertNotNull("Should be a DLQ message for loop: " + i, msg); - } - if (error[0] != null) { + // now lets receive and rollback N times + int maxRollbacks = messageCount * rollbackCount; + consumer.setMessageListener(new RollbackMessageListener(maxRollbacks, rollbackCount)); + + for (int i = 0; i < messageCount; i++) { + Message msg = dlqConsumer.receive(4000); + if (error[0] != null) { + // error from message listener throw error[0]; - } - } + } + assertMessage(msg, i); + assertNotNull("Should be a DLQ message for loop: " + i, msg); + } + if (error[0] != null) { + throw error[0]; + } + } - protected void makeDlqConsumer() throws JMSException { - dlqDestination = createDlqDestination(); + protected void makeDlqConsumer() throws JMSException { + dlqDestination = createDlqDestination(); - LOG.info("Consuming from dead letter on: " + dlqDestination); - dlqConsumer = dlqSession.createConsumer(dlqDestination); - } + LOG.info("Consuming from dead letter on: " + dlqDestination); + dlqConsumer = dlqSession.createConsumer(dlqDestination); + } - @Override - protected void setUp() throws Exception { - transactedMode = true; - super.setUp(); - dlqSession = connection.createSession(transactedMode, acknowledgeMode); - } + @Override + protected void setUp() throws Exception { + transactedMode = true; + super.setUp(); + dlqSession = connection.createSession(transactedMode, acknowledgeMode); + } - @Override - protected void tearDown() throws Exception { - dlqConsumer.close(); - dlqSession.close(); - session.close(); - super.tearDown(); - }; + @Override + protected void tearDown() throws Exception { + dlqConsumer.close(); + dlqSession.close(); + session.close(); + super.tearDown(); + } - protected ActiveMQConnectionFactory createConnectionFactory() - throws Exception { - ActiveMQConnectionFactory answer = super.createConnectionFactory(); - RedeliveryPolicy policy = new RedeliveryPolicy(); - policy.setMaximumRedeliveries(3); - policy.setBackOffMultiplier((short) 1); - policy.setRedeliveryDelay(0); - policy.setInitialRedeliveryDelay(0); - policy.setUseExponentialBackOff(false); - answer.setRedeliveryPolicy(policy); - return answer; - } + ; - protected Destination createDlqDestination() { - return new ActiveMQQueue("ActiveMQ.DLQ"); - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory answer = super.createConnectionFactory(); + RedeliveryPolicy policy = new RedeliveryPolicy(); + policy.setMaximumRedeliveries(3); + policy.setBackOffMultiplier((short) 1); + policy.setRedeliveryDelay(0); + policy.setInitialRedeliveryDelay(0); + policy.setUseExponentialBackOff(false); + answer.setRedeliveryPolicy(policy); + return answer; + } - class RollbackMessageListener implements MessageListener { + protected Destination createDlqDestination() { + return new ActiveMQQueue("ActiveMQ.DLQ"); + } - final int maxRollbacks; + class RollbackMessageListener implements MessageListener { - final int deliveryCount; + final int maxRollbacks; - AtomicInteger rollbacks = new AtomicInteger(); + final int deliveryCount; - RollbackMessageListener(int c, int delvery) { - maxRollbacks = c; - deliveryCount = delvery; - } + AtomicInteger rollbacks = new AtomicInteger(); - public void onMessage(Message message) { - try { - int expectedMessageId = rollbacks.get() / deliveryCount; - LOG.info("expecting messageId: " + expectedMessageId); - assertMessage(message, expectedMessageId); - if (rollbacks.incrementAndGet() > maxRollbacks) { - fail("received too many messages, already done too many rollbacks: " - + rollbacks); - } - session.rollback(); - - } catch (Throwable e) { - LOG.error("unexpected exception:" + e, e); - // propagating assertError to execution task will cause a hang - // at shutdown - if (e instanceof Error) { - error[0] = (Error) e; - } else { - fail("unexpected exception: " + e); - } + RollbackMessageListener(int c, int delvery) { + maxRollbacks = c; + deliveryCount = delvery; + } + public void onMessage(Message message) { + try { + int expectedMessageId = rollbacks.get() / deliveryCount; + LOG.info("expecting messageId: " + expectedMessageId); + assertMessage(message, expectedMessageId); + if (rollbacks.incrementAndGet() > maxRollbacks) { + fail("received too many messages, already done too many rollbacks: " + rollbacks); } - } - } + session.rollback(); + + } + catch (Throwable e) { + LOG.error("unexpected exception:" + e, e); + // propagating assertError to execution task will cause a hang + // at shutdown + if (e instanceof Error) { + error[0] = (Error) e; + } + else { + fail("unexpected exception: " + e); + } + + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/NoConsumerDeadLetterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/NoConsumerDeadLetterTest.java index 7c5373099f..28773f6f51 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/NoConsumerDeadLetterTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/NoConsumerDeadLetterTest.java @@ -34,79 +34,80 @@ import org.apache.activemq.broker.region.policy.PolicyMap; import org.apache.activemq.command.ActiveMQDestination; /** - * + * */ public class NoConsumerDeadLetterTest extends DeadLetterTestSupport { - // lets disable the inapplicable tests - public void testDurableQueueMessage() throws Exception { - } + // lets disable the inapplicable tests + public void testDurableQueueMessage() throws Exception { + } - public void testDurableTopicMessage() throws Exception { - } + public void testDurableTopicMessage() throws Exception { + } - protected void doTest() throws Exception { - makeDlqConsumer(); - sendMessages(); + protected void doTest() throws Exception { + makeDlqConsumer(); + sendMessages(); - for (int i = 0; i < messageCount; i++) { - Message msg = dlqConsumer.receive(1000); - assertNotNull("Should be a message for loop: " + i, msg); - } - } - - public void testConsumerReceivesMessages() throws Exception { - this.topic = false; - ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory)createConnectionFactory(); - connection = (ActiveMQConnection)factory.createConnection(); - connection.start(); + for (int i = 0; i < messageCount; i++) { + Message msg = dlqConsumer.receive(1000); + assertNotNull("Should be a message for loop: " + i, msg); + } + } - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(getDestination()); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - - Topic advisoryTopic = AdvisorySupport.getNoQueueConsumersAdvisoryTopic(getDestination()); - MessageConsumer advisoryConsumer = session.createConsumer(advisoryTopic); - - TextMessage msg = session.createTextMessage("Message: x"); - producer.send(msg); - - Message advisoryMessage = advisoryConsumer.receive(1000); - assertNotNull("Advisory message not received", advisoryMessage); - - Thread.sleep(1000); - - factory = (ActiveMQConnectionFactory)createConnectionFactory(); - connection = (ActiveMQConnection)factory.createConnection(); - connection.start(); - - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageConsumer consumer = session.createConsumer(getDestination()); - Message received = consumer.receive(1000); - assertNotNull("Message not received", received); - } + public void testConsumerReceivesMessages() throws Exception { + this.topic = false; + ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) createConnectionFactory(); + connection = (ActiveMQConnection) factory.createConnection(); + connection.start(); - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(getDestination()); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - PolicyEntry policy = new PolicyEntry(); - policy.setSendAdvisoryIfNoConsumers(true); + Topic advisoryTopic = AdvisorySupport.getNoQueueConsumersAdvisoryTopic(getDestination()); + MessageConsumer advisoryConsumer = session.createConsumer(advisoryTopic); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); + TextMessage msg = session.createTextMessage("Message: x"); + producer.send(msg); - broker.setDestinationPolicy(pMap); + Message advisoryMessage = advisoryConsumer.receive(1000); + assertNotNull("Advisory message not received", advisoryMessage); - return broker; - } + Thread.sleep(1000); - protected Destination createDlqDestination() { - if (this.topic) { - return AdvisorySupport.getNoTopicConsumersAdvisoryTopic((ActiveMQDestination)getDestination()); - } else { - return AdvisorySupport.getNoQueueConsumersAdvisoryTopic((ActiveMQDestination)getDestination()); - } - } + factory = (ActiveMQConnectionFactory) createConnectionFactory(); + connection = (ActiveMQConnection) factory.createConnection(); + connection.start(); + + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + MessageConsumer consumer = session.createConsumer(getDestination()); + Message received = consumer.receive(1000); + assertNotNull("Message not received", received); + } + + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); + + PolicyEntry policy = new PolicyEntry(); + policy.setSendAdvisoryIfNoConsumers(true); + + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); + + broker.setDestinationPolicy(pMap); + + return broker; + } + + protected Destination createDlqDestination() { + if (this.topic) { + return AdvisorySupport.getNoTopicConsumersAdvisoryTopic((ActiveMQDestination) getDestination()); + } + else { + return AdvisorySupport.getNoQueueConsumersAdvisoryTopic((ActiveMQDestination) getDestination()); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/NoRetryDeadLetterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/NoRetryDeadLetterTest.java index a14df74b7d..2abb21637f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/NoRetryDeadLetterTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/NoRetryDeadLetterTest.java @@ -21,13 +21,13 @@ import org.apache.activemq.RedeliveryPolicy; public class NoRetryDeadLetterTest extends DeadLetterTest { - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory connectionFactory = super.createConnectionFactory(); - RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy(); - redeliveryPolicy.setMaximumRedeliveries(0); - connectionFactory.setRedeliveryPolicy(redeliveryPolicy); - return connectionFactory; - } + @Override + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory connectionFactory = super.createConnectionFactory(); + RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy(); + redeliveryPolicy.setMaximumRedeliveries(0); + connectionFactory.setRedeliveryPolicy(redeliveryPolicy); + return connectionFactory; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/PerDurableConsumerDeadLetterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/PerDurableConsumerDeadLetterTest.java index 05be639562..e5c095ca8d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/PerDurableConsumerDeadLetterTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/PerDurableConsumerDeadLetterTest.java @@ -31,40 +31,40 @@ import org.apache.activemq.command.ActiveMQQueue; */ public class PerDurableConsumerDeadLetterTest extends DeadLetterTest { - private static final String CLIENT_ID = "george"; + private static final String CLIENT_ID = "george"; - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); + @Override + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); - PolicyEntry policy = new PolicyEntry(); - IndividualDeadLetterStrategy strategy = new IndividualDeadLetterStrategy(); - strategy.setProcessNonPersistent(true); - strategy.setDestinationPerDurableSubscriber(true); - policy.setDeadLetterStrategy(strategy); + PolicyEntry policy = new PolicyEntry(); + IndividualDeadLetterStrategy strategy = new IndividualDeadLetterStrategy(); + strategy.setProcessNonPersistent(true); + strategy.setDestinationPerDurableSubscriber(true); + policy.setDeadLetterStrategy(strategy); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); - broker.setDestinationPolicy(pMap); + broker.setDestinationPolicy(pMap); - return broker; - } + return broker; + } - @Override - protected String createClientId() { - return CLIENT_ID; - } + @Override + protected String createClientId() { + return CLIENT_ID; + } - @Override - protected Destination createDlqDestination() { - String prefix = topic ? "ActiveMQ.DLQ.Topic." : "ActiveMQ.DLQ.Queue."; - String destinationName = prefix + getClass().getName() + "." + getName(); - if (durableSubscriber) { - String subName = // connectionId:SubName - CLIENT_ID + ":" + getDestination().toString(); - destinationName += "." + subName ; - } - return new ActiveMQQueue(destinationName); - } + @Override + protected Destination createDlqDestination() { + String prefix = topic ? "ActiveMQ.DLQ.Topic." : "ActiveMQ.DLQ.Queue."; + String destinationName = prefix + getClass().getName() + "." + getName(); + if (durableSubscriber) { + String subName = // connectionId:SubName + CLIENT_ID + ":" + getDestination().toString(); + destinationName += "." + subName; + } + return new ActiveMQQueue(destinationName); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/PriorityNetworkDispatchPolicyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/PriorityNetworkDispatchPolicyTest.java index 448f47c349..9367184483 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/PriorityNetworkDispatchPolicyTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/PriorityNetworkDispatchPolicyTest.java @@ -38,44 +38,44 @@ import org.junit.Test; public class PriorityNetworkDispatchPolicyTest { - PriorityNetworkDispatchPolicy underTest = new PriorityNetworkDispatchPolicy(); - SystemUsage usageManager = new SystemUsage(); - ConsumerInfo info = new ConsumerInfo(); - ActiveMQMessage node = new ActiveMQMessage(); - ConsumerId id = new ConsumerId(); - ConnectionContext context = new ConnectionContext(); - BrokerService brokerService = new BrokerService(); + PriorityNetworkDispatchPolicy underTest = new PriorityNetworkDispatchPolicy(); + SystemUsage usageManager = new SystemUsage(); + ConsumerInfo info = new ConsumerInfo(); + ActiveMQMessage node = new ActiveMQMessage(); + ConsumerId id = new ConsumerId(); + ConnectionContext context = new ConnectionContext(); + BrokerService brokerService = new BrokerService(); - @Before - public void init() throws Exception { - info.setDestination(ActiveMQDestination.createDestination("test", ActiveMQDestination.TOPIC_TYPE)); - info.setConsumerId(id); - info.setNetworkSubscription(true); - info.setNetworkConsumerPath(new ConsumerId[]{id}); - node.setMessageId(new MessageId("test:1:1:1:1")); - } + @Before + public void init() throws Exception { + info.setDestination(ActiveMQDestination.createDestination("test", ActiveMQDestination.TOPIC_TYPE)); + info.setConsumerId(id); + info.setNetworkSubscription(true); + info.setNetworkConsumerPath(new ConsumerId[]{id}); + node.setMessageId(new MessageId("test:1:1:1:1")); + } - @After - public void stopBroker() throws Exception { - brokerService.stop(); - } + @After + public void stopBroker() throws Exception { + brokerService.stop(); + } - @Test - public void testRemoveLowerPriorityDup() throws Exception { + @Test + public void testRemoveLowerPriorityDup() throws Exception { - List consumers = new ArrayList(); + List consumers = new ArrayList(); - for (int i=0; i<3; i++) { - ConsumerInfo instance = info.copy(); - instance.setPriority((byte)i); - consumers.add(new TopicSubscription(brokerService.getBroker(), context, instance, usageManager)); - } - underTest.dispatch(node, null, consumers); + for (int i = 0; i < 3; i++) { + ConsumerInfo instance = info.copy(); + instance.setPriority((byte) i); + consumers.add(new TopicSubscription(brokerService.getBroker(), context, instance, usageManager)); + } + underTest.dispatch(node, null, consumers); - long count = 0; - for (Subscription consumer : consumers) { - count += consumer.getEnqueueCounter(); - } - assertEquals("only one sub got message", 1, count); - } + long count = 0; + for (Subscription consumer : consumers) { + count += consumer.getEnqueueCounter(); + } + assertEquals("only one sub got message", 1, count); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/RoundRobinDispatchPolicyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/RoundRobinDispatchPolicyTest.java index 221f603e8b..1c1fa2c9dc 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/RoundRobinDispatchPolicyTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/RoundRobinDispatchPolicyTest.java @@ -33,93 +33,95 @@ import javax.jms.Session; @RunWith(BlockJUnit4ClassRunner.class) public class RoundRobinDispatchPolicyTest extends QueueSubscriptionTest { - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); - PolicyEntry policy = new PolicyEntry(); - policy.setDispatchPolicy(new RoundRobinDispatchPolicy()); + PolicyEntry policy = new PolicyEntry(); + policy.setDispatchPolicy(new RoundRobinDispatchPolicy()); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); - broker.setDestinationPolicy(pMap); + broker.setDestinationPolicy(pMap); - return broker; - } + return broker; + } - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersSmallMessagesOnePrefetch() throws Exception { - super.testOneProducerTwoConsumersSmallMessagesOnePrefetch(); + @Test(timeout = 60 * 1000) + public void testOneProducerTwoConsumersSmallMessagesOnePrefetch() throws Exception { + super.testOneProducerTwoConsumersSmallMessagesOnePrefetch(); - // Ensure that each consumer should have received at least one message - // We cannot guarantee that messages will be equally divided, since - // prefetch is one - assertEachConsumerReceivedAtLeastXMessages(1); - } + // Ensure that each consumer should have received at least one message + // We cannot guarantee that messages will be equally divided, since + // prefetch is one + assertEachConsumerReceivedAtLeastXMessages(1); + } - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersSmallMessagesLargePrefetch() throws Exception { - super.testOneProducerTwoConsumersSmallMessagesLargePrefetch(); - assertMessagesDividedAmongConsumers(); - } + @Test(timeout = 60 * 1000) + public void testOneProducerTwoConsumersSmallMessagesLargePrefetch() throws Exception { + super.testOneProducerTwoConsumersSmallMessagesLargePrefetch(); + assertMessagesDividedAmongConsumers(); + } - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersLargeMessagesOnePrefetch() throws Exception { - super.testOneProducerTwoConsumersLargeMessagesOnePrefetch(); + @Test(timeout = 60 * 1000) + public void testOneProducerTwoConsumersLargeMessagesOnePrefetch() throws Exception { + super.testOneProducerTwoConsumersLargeMessagesOnePrefetch(); - // Ensure that each consumer should have received at least one message - // We cannot guarantee that messages will be equally divided, since - // prefetch is one - assertEachConsumerReceivedAtLeastXMessages(1); - } + // Ensure that each consumer should have received at least one message + // We cannot guarantee that messages will be equally divided, since + // prefetch is one + assertEachConsumerReceivedAtLeastXMessages(1); + } - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersLargeMessagesLargePrefetch() throws Exception { - super.testOneProducerTwoConsumersLargeMessagesLargePrefetch(); - assertMessagesDividedAmongConsumers(); - } + @Test(timeout = 60 * 1000) + public void testOneProducerTwoConsumersLargeMessagesLargePrefetch() throws Exception { + super.testOneProducerTwoConsumersLargeMessagesLargePrefetch(); + assertMessagesDividedAmongConsumers(); + } - @Test(timeout = 60 * 1000) - public void testOneProducerManyConsumersFewMessages() throws Exception { - super.testOneProducerManyConsumersFewMessages(); + @Test(timeout = 60 * 1000) + public void testOneProducerManyConsumersFewMessages() throws Exception { + super.testOneProducerManyConsumersFewMessages(); - // Since there are more consumers, each consumer should have received at - // most one message only - assertMessagesDividedAmongConsumers(); - } + // Since there are more consumers, each consumer should have received at + // most one message only + assertMessagesDividedAmongConsumers(); + } - @Test(timeout = 60 * 1000) - public void testOneProducerManyConsumersManyMessages() throws Exception { - super.testOneProducerManyConsumersManyMessages(); - assertMessagesDividedAmongConsumers(); - } + @Test(timeout = 60 * 1000) + public void testOneProducerManyConsumersManyMessages() throws Exception { + super.testOneProducerManyConsumersManyMessages(); + assertMessagesDividedAmongConsumers(); + } - @Test(timeout = 60 * 1000) - public void testManyProducersManyConsumers() throws Exception { - super.testManyProducersManyConsumers(); - assertMessagesDividedAmongConsumers(); - } + @Test(timeout = 60 * 1000) + public void testManyProducersManyConsumers() throws Exception { + super.testManyProducersManyConsumers(); + assertMessagesDividedAmongConsumers(); + } - @Test(timeout = 60 * 1000) - public void testOneProducerTwoMatchingConsumersOneNotMatchingConsumer() throws Exception { - // Create consumer that won't consume any message - createMessageConsumer(createConnectionFactory().createConnection(), createDestination(), "JMSPriority<1"); - super.testOneProducerTwoConsumersSmallMessagesLargePrefetch(); - assertMessagesDividedAmongConsumers(); - } + @Test(timeout = 60 * 1000) + public void testOneProducerTwoMatchingConsumersOneNotMatchingConsumer() throws Exception { + // Create consumer that won't consume any message + createMessageConsumer(createConnectionFactory().createConnection(), createDestination(), "JMSPriority<1"); + super.testOneProducerTwoConsumersSmallMessagesLargePrefetch(); + assertMessagesDividedAmongConsumers(); + } - protected MessageConsumer createMessageConsumer(Connection conn, Destination dest, String selector) throws Exception { - connections.add(conn); + protected MessageConsumer createMessageConsumer(Connection conn, + Destination dest, + String selector) throws Exception { + connections.add(conn); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageConsumer consumer = sess.createConsumer(dest, selector); - conn.start(); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + final MessageConsumer consumer = sess.createConsumer(dest, selector); + conn.start(); - return consumer; - } + return consumer; + } - public void assertMessagesDividedAmongConsumers() { - assertEachConsumerReceivedAtLeastXMessages((messageCount * producerCount) / consumerCount); - assertEachConsumerReceivedAtMostXMessages(((messageCount * producerCount) / consumerCount) + 1); - } + public void assertMessagesDividedAmongConsumers() { + assertEachConsumerReceivedAtLeastXMessages((messageCount * producerCount) / consumerCount); + assertEachConsumerReceivedAtMostXMessages(((messageCount * producerCount) / consumerCount) + 1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/SecureDLQTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/SecureDLQTest.java index 354031ed9c..de51ff93b7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/SecureDLQTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/SecureDLQTest.java @@ -29,100 +29,100 @@ import static org.apache.activemq.security.SimpleSecurityBrokerSystemTest.*; public class SecureDLQTest extends DeadLetterTestSupport { - Connection dlqConnection; - Session dlqSession; + Connection dlqConnection; + Session dlqSession; - public static AuthorizationMap createAuthorizationMap() { - DestinationMap readAccess = new DefaultAuthorizationMap(); - readAccess.put(new ActiveMQQueue("TEST"), ADMINS); - readAccess.put(new ActiveMQQueue("TEST"), USERS); - readAccess.put(new ActiveMQQueue("ActiveMQ.DLQ"), ADMINS); + public static AuthorizationMap createAuthorizationMap() { + DestinationMap readAccess = new DefaultAuthorizationMap(); + readAccess.put(new ActiveMQQueue("TEST"), ADMINS); + readAccess.put(new ActiveMQQueue("TEST"), USERS); + readAccess.put(new ActiveMQQueue("ActiveMQ.DLQ"), ADMINS); - DestinationMap writeAccess = new DefaultAuthorizationMap(); - writeAccess.put(new ActiveMQQueue("TEST"), ADMINS); - writeAccess.put(new ActiveMQQueue("TEST"), USERS); - writeAccess.put(new ActiveMQQueue("ActiveMQ.DLQ"), ADMINS); + DestinationMap writeAccess = new DefaultAuthorizationMap(); + writeAccess.put(new ActiveMQQueue("TEST"), ADMINS); + writeAccess.put(new ActiveMQQueue("TEST"), USERS); + writeAccess.put(new ActiveMQQueue("ActiveMQ.DLQ"), ADMINS); - readAccess.put(new ActiveMQTopic("ActiveMQ.Advisory.>"), WILDCARD); - writeAccess.put(new ActiveMQTopic("ActiveMQ.Advisory.>"), WILDCARD); + readAccess.put(new ActiveMQTopic("ActiveMQ.Advisory.>"), WILDCARD); + writeAccess.put(new ActiveMQTopic("ActiveMQ.Advisory.>"), WILDCARD); - DestinationMap adminAccess = new DefaultAuthorizationMap(); - adminAccess.put(new ActiveMQQueue("TEST"), ADMINS); - adminAccess.put(new ActiveMQQueue("TEST"), USERS); - adminAccess.put(new ActiveMQQueue("ActiveMQ.DLQ"), ADMINS); - adminAccess.put(new ActiveMQTopic("ActiveMQ.Advisory.>"), WILDCARD); + DestinationMap adminAccess = new DefaultAuthorizationMap(); + adminAccess.put(new ActiveMQQueue("TEST"), ADMINS); + adminAccess.put(new ActiveMQQueue("TEST"), USERS); + adminAccess.put(new ActiveMQQueue("ActiveMQ.DLQ"), ADMINS); + adminAccess.put(new ActiveMQTopic("ActiveMQ.Advisory.>"), WILDCARD); - return new SimpleAuthorizationMap(writeAccess, readAccess, adminAccess); - } + return new SimpleAuthorizationMap(writeAccess, readAccess, adminAccess); + } - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - AuthorizationPlugin authorizationPlugin = new AuthorizationPlugin(createAuthorizationMap()); + @Override + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); + AuthorizationPlugin authorizationPlugin = new AuthorizationPlugin(createAuthorizationMap()); - broker.setPlugins(new BrokerPlugin[] {authorizationPlugin, new SimpleSecurityBrokerSystemTest.SimpleAuthenticationFactory()}); - return broker; - } + broker.setPlugins(new BrokerPlugin[]{authorizationPlugin, new SimpleSecurityBrokerSystemTest.SimpleAuthenticationFactory()}); + return broker; + } - // lets disable the inapplicable tests - public void testTransientTopicMessage() throws Exception { - } + // lets disable the inapplicable tests + public void testTransientTopicMessage() throws Exception { + } - public void testDurableTopicMessage() throws Exception { - } + public void testDurableTopicMessage() throws Exception { + } - @Override - protected void doTest() throws Exception { - timeToLive = 1000; - acknowledgeMode = Session.CLIENT_ACKNOWLEDGE; - makeConsumer(); - sendMessages(); - Thread.sleep(1000); - consumer.close(); + @Override + protected void doTest() throws Exception { + timeToLive = 1000; + acknowledgeMode = Session.CLIENT_ACKNOWLEDGE; + makeConsumer(); + sendMessages(); + Thread.sleep(1000); + consumer.close(); - Thread.sleep(1000); - // this should try to send expired messages to dlq - makeConsumer(); + Thread.sleep(1000); + // this should try to send expired messages to dlq + makeConsumer(); - makeDlqConsumer(); - for (int i = 0; i < messageCount; i++) { - Message msg = dlqConsumer.receive(1000); - assertMessage(msg, i); - assertNotNull("Should be a DLQ message for loop: " + i, msg); - } + makeDlqConsumer(); + for (int i = 0; i < messageCount; i++) { + Message msg = dlqConsumer.receive(1000); + assertMessage(msg, i); + assertNotNull("Should be a DLQ message for loop: " + i, msg); + } - } + } - @Override - public void tearDown() throws Exception { - if (dlqConnection != null) { - dlqConnection.close(); - } - super.tearDown(); - } + @Override + public void tearDown() throws Exception { + if (dlqConnection != null) { + dlqConnection.close(); + } + super.tearDown(); + } - @Override - protected Connection createConnection() throws Exception { - return getConnectionFactory().createConnection("user", "password"); - } + @Override + protected Connection createConnection() throws Exception { + return getConnectionFactory().createConnection("user", "password"); + } - @Override - protected void makeDlqConsumer() throws Exception { - dlqDestination = createDlqDestination(); - dlqConnection = getConnectionFactory().createConnection("system", "manager"); - dlqConnection.start(); - dlqSession = dlqConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + @Override + protected void makeDlqConsumer() throws Exception { + dlqDestination = createDlqDestination(); + dlqConnection = getConnectionFactory().createConnection("system", "manager"); + dlqConnection.start(); + dlqSession = dlqConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - dlqConsumer = dlqSession.createConsumer(dlqDestination); - } + dlqConsumer = dlqSession.createConsumer(dlqDestination); + } - @Override - protected Destination createDlqDestination() { - return new ActiveMQQueue("ActiveMQ.DLQ"); - } + @Override + protected Destination createDlqDestination() { + return new ActiveMQQueue("ActiveMQ.DLQ"); + } - @Override - protected String getDestinationString() { - return "TEST"; - } + @Override + protected String getDestinationString() { + return "TEST"; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/SimpleDispatchPolicyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/SimpleDispatchPolicyTest.java index d6d6b08c6b..570473055e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/SimpleDispatchPolicyTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/SimpleDispatchPolicyTest.java @@ -36,56 +36,57 @@ import static org.junit.Assert.fail; @RunWith(BlockJUnit4ClassRunner.class) public class SimpleDispatchPolicyTest extends QueueSubscriptionTest { - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); + @Override + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); - PolicyEntry policy = new PolicyEntry(); - policy.setDispatchPolicy(new SimpleDispatchPolicy()); - policy.setSubscriptionRecoveryPolicy(new FixedCountSubscriptionRecoveryPolicy()); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); + PolicyEntry policy = new PolicyEntry(); + policy.setDispatchPolicy(new SimpleDispatchPolicy()); + policy.setSubscriptionRecoveryPolicy(new FixedCountSubscriptionRecoveryPolicy()); + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); - broker.setDestinationPolicy(pMap); + broker.setDestinationPolicy(pMap); - return broker; - } + return broker; + } - @Override - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersSmallMessagesLargePrefetch() throws Exception { - super.testOneProducerTwoConsumersSmallMessagesLargePrefetch(); + @Override + @Test(timeout = 60 * 1000) + public void testOneProducerTwoConsumersSmallMessagesLargePrefetch() throws Exception { + super.testOneProducerTwoConsumersSmallMessagesLargePrefetch(); - // One consumer should have received all messages, and the rest none - // assertOneConsumerReceivedAllMessages(messageCount); - } + // One consumer should have received all messages, and the rest none + // assertOneConsumerReceivedAllMessages(messageCount); + } - @Override - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersLargeMessagesLargePrefetch() throws Exception { - super.testOneProducerTwoConsumersLargeMessagesLargePrefetch(); + @Override + @Test(timeout = 60 * 1000) + public void testOneProducerTwoConsumersLargeMessagesLargePrefetch() throws Exception { + super.testOneProducerTwoConsumersLargeMessagesLargePrefetch(); - // One consumer should have received all messages, and the rest none - // assertOneConsumerReceivedAllMessages(messageCount); - } + // One consumer should have received all messages, and the rest none + // assertOneConsumerReceivedAllMessages(messageCount); + } - public void assertOneConsumerReceivedAllMessages(int messageCount) throws Exception { - boolean found = false; - for (Iterator i = consumers.keySet().iterator(); i.hasNext();) { - MessageIdList messageIdList = consumers.get(i.next()); - int count = messageIdList.getMessageCount(); - if (count > 0) { - if (found) { - fail("No other consumers should have received any messages"); - } else { - assertEquals("Consumer should have received all messages.", messageCount, count); - found = true; - } + public void assertOneConsumerReceivedAllMessages(int messageCount) throws Exception { + boolean found = false; + for (Iterator i = consumers.keySet().iterator(); i.hasNext(); ) { + MessageIdList messageIdList = consumers.get(i.next()); + int count = messageIdList.getMessageCount(); + if (count > 0) { + if (found) { + fail("No other consumers should have received any messages"); } - } + else { + assertEquals("Consumer should have received all messages.", messageCount, count); + found = true; + } + } + } - if (!found) { - fail("At least one consumer should have received all messages"); - } - } + if (!found) { + fail("At least one consumer should have received all messages"); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/StrictOrderDispatchPolicyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/StrictOrderDispatchPolicyTest.java index dbeabfe941..395c2ec48f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/StrictOrderDispatchPolicyTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/StrictOrderDispatchPolicyTest.java @@ -35,99 +35,98 @@ import static org.junit.Assert.*; @RunWith(BlockJUnit4ClassRunner.class) public class StrictOrderDispatchPolicyTest extends TopicSubscriptionTest { - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); + @Override + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); - PolicyEntry policy = new PolicyEntry(); - policy.setDispatchPolicy(new StrictOrderDispatchPolicy()); + PolicyEntry policy = new PolicyEntry(); + policy.setDispatchPolicy(new StrictOrderDispatchPolicy()); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); - broker.setDestinationPolicy(pMap); + broker.setDestinationPolicy(pMap); - return broker; - } + return broker; + } - @Test - @Override - public void testOneProducerTwoConsumersLargeMessagesOnePrefetch() throws Exception { - super.testOneProducerTwoConsumersLargeMessagesOnePrefetch(); + @Test + @Override + public void testOneProducerTwoConsumersLargeMessagesOnePrefetch() throws Exception { + super.testOneProducerTwoConsumersLargeMessagesOnePrefetch(); - assertReceivedMessagesAreOrdered(); - } + assertReceivedMessagesAreOrdered(); + } - @Test - @Override - public void testOneProducerTwoConsumersSmallMessagesOnePrefetch() throws Exception { - super.testOneProducerTwoConsumersSmallMessagesOnePrefetch(); + @Test + @Override + public void testOneProducerTwoConsumersSmallMessagesOnePrefetch() throws Exception { + super.testOneProducerTwoConsumersSmallMessagesOnePrefetch(); - assertReceivedMessagesAreOrdered(); - } + assertReceivedMessagesAreOrdered(); + } - @Test - @Override - public void testOneProducerTwoConsumersSmallMessagesLargePrefetch() throws Exception { - super.testOneProducerTwoConsumersSmallMessagesLargePrefetch(); + @Test + @Override + public void testOneProducerTwoConsumersSmallMessagesLargePrefetch() throws Exception { + super.testOneProducerTwoConsumersSmallMessagesLargePrefetch(); - assertReceivedMessagesAreOrdered(); - } + assertReceivedMessagesAreOrdered(); + } - @Test - @Override - public void testOneProducerTwoConsumersLargeMessagesLargePrefetch() throws Exception { - super.testOneProducerTwoConsumersLargeMessagesLargePrefetch(); + @Test + @Override + public void testOneProducerTwoConsumersLargeMessagesLargePrefetch() throws Exception { + super.testOneProducerTwoConsumersLargeMessagesLargePrefetch(); - assertReceivedMessagesAreOrdered(); - } + assertReceivedMessagesAreOrdered(); + } - @Test - @Override - public void testOneProducerManyConsumersFewMessages() throws Exception { - super.testOneProducerManyConsumersFewMessages(); + @Test + @Override + public void testOneProducerManyConsumersFewMessages() throws Exception { + super.testOneProducerManyConsumersFewMessages(); - assertReceivedMessagesAreOrdered(); - } + assertReceivedMessagesAreOrdered(); + } + @Test + @Override + public void testOneProducerManyConsumersManyMessages() throws Exception { + super.testOneProducerManyConsumersManyMessages(); - @Test - @Override - public void testOneProducerManyConsumersManyMessages() throws Exception { - super.testOneProducerManyConsumersManyMessages(); + assertReceivedMessagesAreOrdered(); + } - assertReceivedMessagesAreOrdered(); - } + @Test + @Override + public void testManyProducersOneConsumer() throws Exception { + super.testManyProducersOneConsumer(); - @Test - @Override - public void testManyProducersOneConsumer() throws Exception { - super.testManyProducersOneConsumer(); + assertReceivedMessagesAreOrdered(); + } - assertReceivedMessagesAreOrdered(); - } + @Test + @Override + public void testManyProducersManyConsumers() throws Exception { + super.testManyProducersManyConsumers(); - @Test - @Override - public void testManyProducersManyConsumers() throws Exception { - super.testManyProducersManyConsumers(); + assertReceivedMessagesAreOrdered(); + } - assertReceivedMessagesAreOrdered(); - } + public void assertReceivedMessagesAreOrdered() throws Exception { + // If there is only one consumer, messages is definitely ordered + if (consumers.size() <= 1) { + return; + } - public void assertReceivedMessagesAreOrdered() throws Exception { - // If there is only one consumer, messages is definitely ordered - if (consumers.size() <= 1) { - return; - } + // Get basis of order + Iterator i = consumers.keySet().iterator(); + MessageIdList messageOrder = (MessageIdList) consumers.get(i.next()); - // Get basis of order - Iterator i = consumers.keySet().iterator(); - MessageIdList messageOrder = (MessageIdList)consumers.get(i.next()); - - for (; i.hasNext();) { - MessageIdList messageIdList = (MessageIdList)consumers.get(i.next()); - assertTrue("Messages are not ordered.", messageOrder.equals(messageIdList)); - } - } + for (; i.hasNext(); ) { + MessageIdList messageIdList = (MessageIdList) consumers.get(i.next()); + assertTrue("Messages are not ordered.", messageOrder.equals(messageIdList)); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/DestinationGCTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/DestinationGCTest.java index 17bf2b242f..cc957ae9cc 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/DestinationGCTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/DestinationGCTest.java @@ -36,78 +36,78 @@ import org.apache.activemq.util.Wait.Condition; public class DestinationGCTest extends EmbeddedBrokerTestSupport { - ActiveMQQueue queue = new ActiveMQQueue("TEST"); - ActiveMQQueue otherQueue = new ActiveMQQueue("TEST-OTHER"); + ActiveMQQueue queue = new ActiveMQQueue("TEST"); + ActiveMQQueue otherQueue = new ActiveMQQueue("TEST-OTHER"); - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - broker.setDestinations(new ActiveMQDestination[] {queue}); - broker.setSchedulePeriodForDestinationPurge(1000); - broker.setMaxPurgedDestinationsPerSweep(1); - PolicyEntry entry = new PolicyEntry(); - entry.setGcInactiveDestinations(true); - entry.setInactiveTimoutBeforeGC(3000); - PolicyMap map = new PolicyMap(); - map.setDefaultEntry(entry); - broker.setDestinationPolicy(map); - return broker; - } + @Override + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); + broker.setDestinations(new ActiveMQDestination[]{queue}); + broker.setSchedulePeriodForDestinationPurge(1000); + broker.setMaxPurgedDestinationsPerSweep(1); + PolicyEntry entry = new PolicyEntry(); + entry.setGcInactiveDestinations(true); + entry.setInactiveTimoutBeforeGC(3000); + PolicyMap map = new PolicyMap(); + map.setDefaultEntry(entry); + broker.setDestinationPolicy(map); + return broker; + } - public void testDestinationGCWithActiveConsumers() throws Exception { - assertEquals(1, broker.getAdminView().getQueues().length); + public void testDestinationGCWithActiveConsumers() throws Exception { + assertEquals(1, broker.getAdminView().getQueues().length); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?create=false"); - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createProducer(otherQueue).close(); - MessageConsumer consumer = session.createConsumer(queue); - consumer.setMessageListener(new MessageListener() { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?create=false"); + Connection connection = factory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createProducer(otherQueue).close(); + MessageConsumer consumer = session.createConsumer(queue); + consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - } - }); - connection.start(); + @Override + public void onMessage(Message message) { + } + }); + connection.start(); - TimeUnit.SECONDS.sleep(5); + TimeUnit.SECONDS.sleep(5); - assertTrue("After GC runs there should be one Queue.", Wait.waitFor(new Condition() { - @Override - public boolean isSatisified() throws Exception { - return broker.getAdminView().getQueues().length == 1; - } - })); + assertTrue("After GC runs there should be one Queue.", Wait.waitFor(new Condition() { + @Override + public boolean isSatisified() throws Exception { + return broker.getAdminView().getQueues().length == 1; + } + })); - connection.close(); - } + connection.close(); + } - public void testDestinationGc() throws Exception { - assertEquals(1, broker.getAdminView().getQueues().length); - assertTrue("After GC runs the Queue should be empty.", Wait.waitFor(new Condition() { - @Override - public boolean isSatisified() throws Exception { - return broker.getAdminView().getQueues().length == 0; - } - })); - } + public void testDestinationGc() throws Exception { + assertEquals(1, broker.getAdminView().getQueues().length); + assertTrue("After GC runs the Queue should be empty.", Wait.waitFor(new Condition() { + @Override + public boolean isSatisified() throws Exception { + return broker.getAdminView().getQueues().length == 0; + } + })); + } - public void testDestinationGcLimit() throws Exception { + public void testDestinationGcLimit() throws Exception { - broker.getAdminView().addQueue("TEST1"); - broker.getAdminView().addQueue("TEST2"); - broker.getAdminView().addQueue("TEST3"); - broker.getAdminView().addQueue("TEST4"); + broker.getAdminView().addQueue("TEST1"); + broker.getAdminView().addQueue("TEST2"); + broker.getAdminView().addQueue("TEST3"); + broker.getAdminView().addQueue("TEST4"); - assertEquals(5, broker.getAdminView().getQueues().length); - Thread.sleep(7000); - int queues = broker.getAdminView().getQueues().length; - assertTrue(queues > 0 && queues < 5); - assertTrue("After GC runs the Queue should be empty.", Wait.waitFor(new Condition() { - @Override - public boolean isSatisified() throws Exception { - return broker.getAdminView().getQueues().length == 0; - } - })); - } + assertEquals(5, broker.getAdminView().getQueues().length); + Thread.sleep(7000); + int queues = broker.getAdminView().getQueues().length; + assertTrue(queues > 0 && queues < 5); + assertTrue("After GC runs the Queue should be empty.", Wait.waitFor(new Condition() { + @Override + public boolean isSatisified() throws Exception { + return broker.getAdminView().getQueues().length == 0; + } + })); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/DestinationRemoveRestartTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/DestinationRemoveRestartTest.java index 06011fe6f7..38a0846e88 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/DestinationRemoveRestartTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/DestinationRemoveRestartTest.java @@ -17,101 +17,100 @@ package org.apache.activemq.broker.region; import junit.framework.Test; + import org.apache.activemq.CombinationTestSupport; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.command.ActiveMQDestination; // from https://issues.apache.org/activemq/browse/AMQ-2216 public class DestinationRemoveRestartTest extends CombinationTestSupport { - private final static String destinationName = "TEST"; - public byte destinationType = ActiveMQDestination.QUEUE_TYPE; - BrokerService broker; - @Override - protected void setUp() throws Exception { - broker = createBroker(); - } + private final static String destinationName = "TEST"; + public byte destinationType = ActiveMQDestination.QUEUE_TYPE; + BrokerService broker; - private BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setUseJmx(false); - broker.setPersistent(true); - broker.setDeleteAllMessagesOnStartup(true); - broker.start(); - return broker; - } + @Override + protected void setUp() throws Exception { + broker = createBroker(); + } - @Override - protected void tearDown() throws Exception { - broker.stop(); - } + private BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setUseJmx(false); + broker.setPersistent(true); + broker.setDeleteAllMessagesOnStartup(true); + broker.start(); + return broker; + } - public void initCombosForTestCheckDestinationRemoveActionAfterRestart() { - addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); - } - - public void testCheckDestinationRemoveActionAfterRestart() throws Exception { - doAddDestination(); - doRemoveDestination(); - broker.stop(); - broker.waitUntilStopped(); - broker = createBroker(); - doCheckRemoveActionAfterRestart(); - } + @Override + protected void tearDown() throws Exception { + broker.stop(); + } - public void doAddDestination() throws Exception { - boolean res = false; - - ActiveMQDestination amqDestination = - ActiveMQDestination.createDestination(destinationName, destinationType); - broker.getRegionBroker().addDestination(broker.getAdminConnectionContext(), amqDestination,true); - - final ActiveMQDestination[] list = broker.getRegionBroker().getDestinations(); - for (final ActiveMQDestination element : list) { - final Destination destination = broker.getDestination(element); - if (destination.getActiveMQDestination().getPhysicalName().equals(destinationName)) { - res = true; - break; - } - } - - assertTrue("Adding destination Failed", res); - } - - public void doRemoveDestination() throws Exception { - boolean res = true; - - broker.removeDestination(ActiveMQDestination.createDestination(destinationName, destinationType)); - final ActiveMQDestination[] list = broker.getRegionBroker().getDestinations(); - for (final ActiveMQDestination element : list) { - final Destination destination = broker.getDestination(element); - if (destination.getActiveMQDestination().getPhysicalName().equals(destinationName)) { - res = false; - break; - } - } - - assertTrue("Removing destination Failed", res); - } - - - public void doCheckRemoveActionAfterRestart() throws Exception { - boolean res = true; - - final ActiveMQDestination[] list = broker.getRegionBroker().getDestinations(); - for (final ActiveMQDestination element : list) { - final Destination destination = broker.getDestination(element); - if (destination.getActiveMQDestination().getPhysicalName().equals(destinationName)) { - res = false; - break; - } - } - - assertTrue("The removed destination is reloaded after restart !", res); - } - - public static Test suite() { - return suite(DestinationRemoveRestartTest.class); - } + public void initCombosForTestCheckDestinationRemoveActionAfterRestart() { + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); + } + + public void testCheckDestinationRemoveActionAfterRestart() throws Exception { + doAddDestination(); + doRemoveDestination(); + broker.stop(); + broker.waitUntilStopped(); + broker = createBroker(); + doCheckRemoveActionAfterRestart(); + } + + public void doAddDestination() throws Exception { + boolean res = false; + + ActiveMQDestination amqDestination = ActiveMQDestination.createDestination(destinationName, destinationType); + broker.getRegionBroker().addDestination(broker.getAdminConnectionContext(), amqDestination, true); + + final ActiveMQDestination[] list = broker.getRegionBroker().getDestinations(); + for (final ActiveMQDestination element : list) { + final Destination destination = broker.getDestination(element); + if (destination.getActiveMQDestination().getPhysicalName().equals(destinationName)) { + res = true; + break; + } + } + + assertTrue("Adding destination Failed", res); + } + + public void doRemoveDestination() throws Exception { + boolean res = true; + + broker.removeDestination(ActiveMQDestination.createDestination(destinationName, destinationType)); + final ActiveMQDestination[] list = broker.getRegionBroker().getDestinations(); + for (final ActiveMQDestination element : list) { + final Destination destination = broker.getDestination(element); + if (destination.getActiveMQDestination().getPhysicalName().equals(destinationName)) { + res = false; + break; + } + } + + assertTrue("Removing destination Failed", res); + } + + public void doCheckRemoveActionAfterRestart() throws Exception { + boolean res = true; + + final ActiveMQDestination[] list = broker.getRegionBroker().getDestinations(); + for (final ActiveMQDestination element : list) { + final Destination destination = broker.getDestination(element); + if (destination.getActiveMQDestination().getPhysicalName().equals(destinationName)) { + res = false; + break; + } + } + + assertTrue("The removed destination is reloaded after restart !", res); + } + + public static Test suite() { + return suite(DestinationRemoveRestartTest.class); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueueDuplicatesFromStoreTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueueDuplicatesFromStoreTest.java index f69c380fa5..842da31db9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueueDuplicatesFromStoreTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueueDuplicatesFromStoreTest.java @@ -54,354 +54,337 @@ import org.slf4j.LoggerFactory; /** * @author gtully * @see https://issues.apache.org/activemq/browse/AMQ-2020 - **/ + */ public class QueueDuplicatesFromStoreTest extends TestCase { - private static final Logger LOG = LoggerFactory - .getLogger(QueueDuplicatesFromStoreTest.class); - ActiveMQQueue destination = new ActiveMQQueue("queue-" - + QueueDuplicatesFromStoreTest.class.getSimpleName()); - BrokerService brokerService; + private static final Logger LOG = LoggerFactory.getLogger(QueueDuplicatesFromStoreTest.class); - final static String mesageIdRoot = "11111:22222:"; - final int messageBytesSize = 256; - final String text = new String(new byte[messageBytesSize]); + ActiveMQQueue destination = new ActiveMQQueue("queue-" + QueueDuplicatesFromStoreTest.class.getSimpleName()); + BrokerService brokerService; - final int ackStartIndex = 100; - final int ackWindow = 50; - final int ackBatchSize = 50; - final int fullWindow = 200; - protected int count = 5000; + final static String mesageIdRoot = "11111:22222:"; + final int messageBytesSize = 256; + final String text = new String(new byte[messageBytesSize]); - @Override - public void setUp() throws Exception { - brokerService = createBroker(); - brokerService.setUseJmx(false); - brokerService.deleteAllMessages(); - brokerService.start(); - } + final int ackStartIndex = 100; + final int ackWindow = 50; + final int ackBatchSize = 50; + final int fullWindow = 200; + protected int count = 5000; - protected BrokerService createBroker() throws Exception { - return new BrokerService(); - } + @Override + public void setUp() throws Exception { + brokerService = createBroker(); + brokerService.setUseJmx(false); + brokerService.deleteAllMessages(); + brokerService.start(); + } - @Override - public void tearDown() throws Exception { - brokerService.stop(); - } + protected BrokerService createBroker() throws Exception { + return new BrokerService(); + } - public void testNoDuplicateAfterCacheFullAndAckedWithLargeAuditDepth() throws Exception { - doTestNoDuplicateAfterCacheFullAndAcked(1024*10); - } + @Override + public void tearDown() throws Exception { + brokerService.stop(); + } - public void testNoDuplicateAfterCacheFullAndAckedWithSmallAuditDepth() throws Exception { - doTestNoDuplicateAfterCacheFullAndAcked(512); - } + public void testNoDuplicateAfterCacheFullAndAckedWithLargeAuditDepth() throws Exception { + doTestNoDuplicateAfterCacheFullAndAcked(1024 * 10); + } - public void doTestNoDuplicateAfterCacheFullAndAcked(final int auditDepth) throws Exception { - final PersistenceAdapter persistenceAdapter = brokerService.getPersistenceAdapter(); - final MessageStore queueMessageStore = - persistenceAdapter.createQueueMessageStore(destination); - final ConnectionContext contextNotInTx = new ConnectionContext(); - final ConsumerInfo consumerInfo = new ConsumerInfo(); - final DestinationStatistics destinationStatistics = new DestinationStatistics(); - consumerInfo.setExclusive(true); - final Queue queue = new Queue(brokerService, destination, - queueMessageStore, destinationStatistics, brokerService.getTaskRunnerFactory()); + public void testNoDuplicateAfterCacheFullAndAckedWithSmallAuditDepth() throws Exception { + doTestNoDuplicateAfterCacheFullAndAcked(512); + } - // a workaround for this issue - // queue.setUseCache(false); - queue.systemUsage.getMemoryUsage().setLimit(1024 * 1024 * 10); - queue.setMaxAuditDepth(auditDepth); - queue.initialize(); - queue.start(); + public void doTestNoDuplicateAfterCacheFullAndAcked(final int auditDepth) throws Exception { + final PersistenceAdapter persistenceAdapter = brokerService.getPersistenceAdapter(); + final MessageStore queueMessageStore = persistenceAdapter.createQueueMessageStore(destination); + final ConnectionContext contextNotInTx = new ConnectionContext(); + final ConsumerInfo consumerInfo = new ConsumerInfo(); + final DestinationStatistics destinationStatistics = new DestinationStatistics(); + consumerInfo.setExclusive(true); + final Queue queue = new Queue(brokerService, destination, queueMessageStore, destinationStatistics, brokerService.getTaskRunnerFactory()); + // a workaround for this issue + // queue.setUseCache(false); + queue.systemUsage.getMemoryUsage().setLimit(1024 * 1024 * 10); + queue.setMaxAuditDepth(auditDepth); + queue.initialize(); + queue.start(); - ProducerBrokerExchange producerExchange = new ProducerBrokerExchange(); - ProducerInfo producerInfo = new ProducerInfo(); - ProducerState producerState = new ProducerState(producerInfo); - producerExchange.setProducerState(producerState); - producerExchange.setConnectionContext(contextNotInTx); + ProducerBrokerExchange producerExchange = new ProducerBrokerExchange(); + ProducerInfo producerInfo = new ProducerInfo(); + ProducerState producerState = new ProducerState(producerInfo); + producerExchange.setProducerState(producerState); + producerExchange.setConnectionContext(contextNotInTx); - final CountDownLatch receivedLatch = new CountDownLatch(count); - final AtomicLong ackedCount = new AtomicLong(0); - final AtomicLong enqueueCounter = new AtomicLong(0); - final Vector errors = new Vector(); + final CountDownLatch receivedLatch = new CountDownLatch(count); + final AtomicLong ackedCount = new AtomicLong(0); + final AtomicLong enqueueCounter = new AtomicLong(0); + final Vector errors = new Vector(); - // populate the queue store, exceed memory limit so that cache is disabled - for (int i = 0; i < count; i++) { - Message message = getMessage(i); - queue.send(producerExchange, message); - } + // populate the queue store, exceed memory limit so that cache is disabled + for (int i = 0; i < count; i++) { + Message message = getMessage(i); + queue.send(producerExchange, message); + } - assertEquals("store count is correct", count, queueMessageStore.getMessageCount()); + assertEquals("store count is correct", count, queueMessageStore.getMessageCount()); - // pull from store in small windows - Subscription subscription = new Subscription() { + // pull from store in small windows + Subscription subscription = new Subscription() { - @Override - public void add(MessageReference node) throws Exception { - if (enqueueCounter.get() != node.getMessageId().getProducerSequenceId()) { - errors.add("Not in sequence at: " + enqueueCounter.get() + ", received: " - + node.getMessageId().getProducerSequenceId()); - } - assertEquals("is in order", enqueueCounter.get(), node - .getMessageId().getProducerSequenceId()); - receivedLatch.countDown(); - enqueueCounter.incrementAndGet(); - node.decrementReferenceCount(); + @Override + public void add(MessageReference node) throws Exception { + if (enqueueCounter.get() != node.getMessageId().getProducerSequenceId()) { + errors.add("Not in sequence at: " + enqueueCounter.get() + ", received: " + node.getMessageId().getProducerSequenceId()); } + assertEquals("is in order", enqueueCounter.get(), node.getMessageId().getProducerSequenceId()); + receivedLatch.countDown(); + enqueueCounter.incrementAndGet(); + node.decrementReferenceCount(); + } - @Override - public void add(ConnectionContext context, Destination destination) - throws Exception { + @Override + public void add(ConnectionContext context, Destination destination) throws Exception { + } + + @Override + public int countBeforeFull() { + if (isFull()) { + return 0; } - - @Override - public int countBeforeFull() { - if (isFull()) { - return 0; - } else { - return fullWindow - (int) (enqueueCounter.get() - ackedCount.get()); - } + else { + return fullWindow - (int) (enqueueCounter.get() - ackedCount.get()); } + } - @Override - public void destroy() { - }; + @Override + public void destroy() { + } - @Override - public void gc() { + ; + + @Override + public void gc() { + } + + @Override + public ConsumerInfo getConsumerInfo() { + return consumerInfo; + } + + @Override + public ConnectionContext getContext() { + return null; + } + + @Override + public long getDequeueCounter() { + return 0; + } + + @Override + public long getDispatchedCounter() { + return 0; + } + + @Override + public int getDispatchedQueueSize() { + return 0; + } + + @Override + public long getEnqueueCounter() { + return 0; + } + + @Override + public int getInFlightSize() { + return 0; + } + + @Override + public int getInFlightUsage() { + return 0; + } + + @Override + public ObjectName getObjectName() { + return null; + } + + @Override + public int getPendingQueueSize() { + return 0; + } + + @Override + public int getPrefetchSize() { + return 0; + } + + @Override + public String getSelector() { + return null; + } + + @Override + public boolean isBrowser() { + return false; + } + + @Override + public boolean isFull() { + return (enqueueCounter.get() - ackedCount.get()) >= fullWindow; + } + + @Override + public boolean isHighWaterMark() { + return false; + } + + @Override + public boolean isLowWaterMark() { + return false; + } + + @Override + public boolean isRecoveryRequired() { + return false; + } + + @Override + public boolean matches(MessageReference node, MessageEvaluationContext context) throws IOException { + return true; + } + + @Override + public boolean matches(ActiveMQDestination destination) { + return true; + } + + @Override + public void processMessageDispatchNotification(MessageDispatchNotification mdn) throws Exception { + } + + @Override + public Response pullMessage(ConnectionContext context, MessagePull pull) throws Exception { + return null; + } + + @Override + public boolean isWildcard() { + return false; + } + + @Override + public List remove(ConnectionContext context, Destination destination) throws Exception { + return null; + } + + @Override + public void setObjectName(ObjectName objectName) { + } + + @Override + public void setSelector(String selector) throws InvalidSelectorException, UnsupportedOperationException { + } + + @Override + public void updateConsumerPrefetch(int newPrefetch) { + } + + @Override + public boolean addRecoveredMessage(ConnectionContext context, MessageReference message) throws Exception { + return false; + } + + @Override + public ActiveMQDestination getActiveMQDestination() { + return destination; + } + + @Override + public void acknowledge(ConnectionContext context, MessageAck ack) throws Exception { + } + + @Override + public int getCursorMemoryHighWaterMark() { + return 0; + } + + @Override + public void setCursorMemoryHighWaterMark(int cursorMemoryHighWaterMark) { + } + + @Override + public boolean isSlowConsumer() { + return false; + } + + @Override + public void unmatched(MessageReference node) throws IOException { + } + + @Override + public long getTimeOfLastMessageAck() { + return 0; + } + + @Override + public long getConsumedCount() { + return 0; + } + + public void incrementConsumedCount() { + + } + + public void resetConsumedCount() { + + } + }; + + queue.addSubscription(contextNotInTx, subscription); + int removeIndex = 0; + do { + // Simulate periodic acks in small but recent windows + long receivedCount = enqueueCounter.get(); + if (receivedCount > ackStartIndex) { + if (receivedCount >= removeIndex + ackWindow) { + for (int j = 0; j < ackBatchSize; j++, removeIndex++) { + ackedCount.incrementAndGet(); + MessageAck ack = new MessageAck(); + ack.setLastMessageId(new MessageId(mesageIdRoot + removeIndex)); + ack.setMessageCount(1); + queue.removeMessage(contextNotInTx, subscription, new IndirectMessageReference(getMessage(removeIndex)), ack); + queue.wakeup(); + + } + if (removeIndex % 1000 == 0) { + LOG.info("acked: " + removeIndex); + persistenceAdapter.checkpoint(true); + } } + } - @Override - public ConsumerInfo getConsumerInfo() { - return consumerInfo; - } + } while (!receivedLatch.await(0, TimeUnit.MILLISECONDS) && errors.isEmpty()); - @Override - public ConnectionContext getContext() { - return null; - } + assertTrue("There are no errors: " + errors, errors.isEmpty()); + assertEquals(count, enqueueCounter.get()); + assertEquals("store count is correct", count - removeIndex, queueMessageStore.getMessageCount()); + } - @Override - public long getDequeueCounter() { - return 0; - } - - @Override - public long getDispatchedCounter() { - return 0; - } - - @Override - public int getDispatchedQueueSize() { - return 0; - } - - @Override - public long getEnqueueCounter() { - return 0; - } - - @Override - public int getInFlightSize() { - return 0; - } - - @Override - public int getInFlightUsage() { - return 0; - } - - @Override - public ObjectName getObjectName() { - return null; - } - - @Override - public int getPendingQueueSize() { - return 0; - } - - @Override - public int getPrefetchSize() { - return 0; - } - - @Override - public String getSelector() { - return null; - } - - @Override - public boolean isBrowser() { - return false; - } - - @Override - public boolean isFull() { - return (enqueueCounter.get() - ackedCount.get()) >= fullWindow; - } - - @Override - public boolean isHighWaterMark() { - return false; - } - - @Override - public boolean isLowWaterMark() { - return false; - } - - @Override - public boolean isRecoveryRequired() { - return false; - } - - @Override - public boolean matches(MessageReference node, - MessageEvaluationContext context) throws IOException { - return true; - } - - @Override - public boolean matches(ActiveMQDestination destination) { - return true; - } - - @Override - public void processMessageDispatchNotification( - MessageDispatchNotification mdn) throws Exception { - } - - @Override - public Response pullMessage(ConnectionContext context, - MessagePull pull) throws Exception { - return null; - } - - @Override - public boolean isWildcard() { - return false; - } - - @Override - public List remove(ConnectionContext context, - Destination destination) throws Exception { - return null; - } - - @Override - public void setObjectName(ObjectName objectName) { - } - - @Override - public void setSelector(String selector) - throws InvalidSelectorException, - UnsupportedOperationException { - } - - @Override - public void updateConsumerPrefetch(int newPrefetch) { - } - - @Override - public boolean addRecoveredMessage(ConnectionContext context, - MessageReference message) throws Exception { - return false; - } - - @Override - public ActiveMQDestination getActiveMQDestination() { - return destination; - } - - @Override - public void acknowledge(ConnectionContext context, MessageAck ack) - throws Exception { - } - - @Override - public int getCursorMemoryHighWaterMark(){ - return 0; - } - - @Override - public void setCursorMemoryHighWaterMark( - int cursorMemoryHighWaterMark) { - } - - @Override - public boolean isSlowConsumer() { - return false; - } - - @Override - public void unmatched(MessageReference node) throws IOException { - } - - @Override - public long getTimeOfLastMessageAck() { - return 0; - } - - @Override - public long getConsumedCount() { - return 0; - } - - public void incrementConsumedCount(){ - - } - - public void resetConsumedCount(){ - - } - }; - - queue.addSubscription(contextNotInTx, subscription); - int removeIndex = 0; - do { - // Simulate periodic acks in small but recent windows - long receivedCount = enqueueCounter.get(); - if (receivedCount > ackStartIndex) { - if (receivedCount >= removeIndex + ackWindow) { - for (int j = 0; j < ackBatchSize; j++, removeIndex++) { - ackedCount.incrementAndGet(); - MessageAck ack = new MessageAck(); - ack.setLastMessageId(new MessageId(mesageIdRoot - + removeIndex)); - ack.setMessageCount(1); - queue.removeMessage(contextNotInTx, subscription, - new IndirectMessageReference( - getMessage(removeIndex)), ack); - queue.wakeup(); - - } - if (removeIndex % 1000 == 0) { - LOG.info("acked: " + removeIndex); - persistenceAdapter.checkpoint(true); - } - } - } - - } while (!receivedLatch.await(0, TimeUnit.MILLISECONDS) && errors.isEmpty()); - - assertTrue("There are no errors: " + errors, errors.isEmpty()); - assertEquals(count, enqueueCounter.get()); - assertEquals("store count is correct", count - removeIndex, - queueMessageStore.getMessageCount()); - } - - private Message getMessage(int i) throws Exception { - ActiveMQTextMessage message = new ActiveMQTextMessage(); - message.setMessageId(new MessageId(mesageIdRoot + i)); - message.setDestination(destination); - message.setPersistent(true); - message.setResponseRequired(true); - message.setText("Msg:" + i + " " + text); - assertEquals(message.getMessageId().getProducerSequenceId(), i); - return message; - } + private Message getMessage(int i) throws Exception { + ActiveMQTextMessage message = new ActiveMQTextMessage(); + message.setMessageId(new MessageId(mesageIdRoot + i)); + message.setDestination(destination); + message.setPersistent(true); + message.setResponseRequired(true); + message.setText("Msg:" + i + " " + text); + assertEquals(message.getMessageId().getProducerSequenceId(), i); + return message; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueueOptimizedDispatchExceptionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueueOptimizedDispatchExceptionTest.java index b46169e194..95e4ab88de 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueueOptimizedDispatchExceptionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueueOptimizedDispatchExceptionTest.java @@ -45,211 +45,209 @@ import org.slf4j.LoggerFactory; public class QueueOptimizedDispatchExceptionTest { - private static final Logger LOG = LoggerFactory.getLogger(QueueOptimizedDispatchExceptionTest.class); + private static final Logger LOG = LoggerFactory.getLogger(QueueOptimizedDispatchExceptionTest.class); - private static final String brokerName = "testBroker"; - private static final String brokerUrl = "vm://" + brokerName; - private static final int count = 50; + private static final String brokerName = "testBroker"; + private static final String brokerUrl = "vm://" + brokerName; + private static final int count = 50; - private final static String mesageIdRoot = "11111:22222:"; - private final ActiveMQQueue destination = new ActiveMQQueue("queue-" - + QueueOptimizedDispatchExceptionTest.class.getSimpleName()); - private final int messageBytesSize = 256; - private final String text = new String(new byte[messageBytesSize]); + private final static String mesageIdRoot = "11111:22222:"; + private final ActiveMQQueue destination = new ActiveMQQueue("queue-" + QueueOptimizedDispatchExceptionTest.class.getSimpleName()); + private final int messageBytesSize = 256; + private final String text = new String(new byte[messageBytesSize]); - private BrokerService broker; + private BrokerService broker; - @Before - public void setUp() throws Exception { + @Before + public void setUp() throws Exception { - // Setup and start the broker - broker = new BrokerService(); - broker.setBrokerName(brokerName); - broker.setPersistent(false); - broker.setSchedulerSupport(false); - broker.setUseJmx(false); - broker.setUseShutdownHook(false); - broker.addConnector(brokerUrl); + // Setup and start the broker + broker = new BrokerService(); + broker.setBrokerName(brokerName); + broker.setPersistent(false); + broker.setSchedulerSupport(false); + broker.setUseJmx(false); + broker.setUseShutdownHook(false); + broker.addConnector(brokerUrl); - // Start the broker - broker.start(); - broker.waitUntilStarted(); - } + // Start the broker + broker.start(); + broker.waitUntilStarted(); + } - @After - public void tearDown() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } + @After + public void tearDown() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + } - private class MockMemoryUsage extends MemoryUsage { + private class MockMemoryUsage extends MemoryUsage { - private boolean full = true; + private boolean full = true; - public void setFull(boolean full) { - this.full = full; - } + public void setFull(boolean full) { + this.full = full; + } - @Override - public boolean isFull() { - return full; - } - } + @Override + public boolean isFull() { + return full; + } + } - @Test - public void TestOptimizedDispatchCME() throws Exception { - final PersistenceAdapter persistenceAdapter = broker.getPersistenceAdapter(); - final MessageStore queueMessageStore = - persistenceAdapter.createQueueMessageStore(destination); - final ConnectionContext contextNotInTx = new ConnectionContext(); - contextNotInTx.setConnection(new Connection() { + @Test + public void TestOptimizedDispatchCME() throws Exception { + final PersistenceAdapter persistenceAdapter = broker.getPersistenceAdapter(); + final MessageStore queueMessageStore = persistenceAdapter.createQueueMessageStore(destination); + final ConnectionContext contextNotInTx = new ConnectionContext(); + contextNotInTx.setConnection(new Connection() { - @Override - public void stop() throws Exception { - } + @Override + public void stop() throws Exception { + } - @Override - public void start() throws Exception { - } + @Override + public void start() throws Exception { + } - @Override - public void updateClient(ConnectionControl control) { - } + @Override + public void updateClient(ConnectionControl control) { + } - @Override - public void serviceExceptionAsync(IOException e) { - } + @Override + public void serviceExceptionAsync(IOException e) { + } - @Override - public void serviceException(Throwable error) { - } + @Override + public void serviceException(Throwable error) { + } - @Override - public Response service(Command command) { - return null; - } + @Override + public Response service(Command command) { + return null; + } - @Override - public boolean isSlow() { - return false; - } + @Override + public boolean isSlow() { + return false; + } - @Override - public boolean isNetworkConnection() { - return false; - } + @Override + public boolean isNetworkConnection() { + return false; + } - @Override - public boolean isManageable() { - return false; - } + @Override + public boolean isManageable() { + return false; + } - @Override - public boolean isFaultTolerantConnection() { - return false; - } + @Override + public boolean isFaultTolerantConnection() { + return false; + } - @Override - public boolean isConnected() { - return true; - } + @Override + public boolean isConnected() { + return true; + } - @Override - public boolean isBlocked() { - return false; - } + @Override + public boolean isBlocked() { + return false; + } - @Override - public boolean isActive() { - return false; - } + @Override + public boolean isActive() { + return false; + } - @Override - public ConnectionStatistics getStatistics() { - return null; - } + @Override + public ConnectionStatistics getStatistics() { + return null; + } - @Override - public String getRemoteAddress() { - return null; - } + @Override + public String getRemoteAddress() { + return null; + } - @Override - public int getDispatchQueueSize() { - return 0; - } + @Override + public int getDispatchQueueSize() { + return 0; + } - @Override - public Connector getConnector() { - // TODO Auto-generated method stub - return null; - } + @Override + public Connector getConnector() { + // TODO Auto-generated method stub + return null; + } - @Override - public String getConnectionId() { - return null; - } + @Override + public String getConnectionId() { + return null; + } - @Override - public void dispatchSync(Command message) { - } + @Override + public void dispatchSync(Command message) { + } - @Override - public void dispatchAsync(Command command) { - } + @Override + public void dispatchAsync(Command command) { + } - @Override - public int getActiveTransactionCount() { - return 0; - } + @Override + public int getActiveTransactionCount() { + return 0; + } - @Override - public Long getOldestActiveTransactionDuration() { - return null; - } - }); + @Override + public Long getOldestActiveTransactionDuration() { + return null; + } + }); - final DestinationStatistics destinationStatistics = new DestinationStatistics(); - final Queue queue = new Queue(broker, destination, - queueMessageStore, destinationStatistics, broker.getTaskRunnerFactory()); + final DestinationStatistics destinationStatistics = new DestinationStatistics(); + final Queue queue = new Queue(broker, destination, queueMessageStore, destinationStatistics, broker.getTaskRunnerFactory()); - final MockMemoryUsage usage = new MockMemoryUsage(); + final MockMemoryUsage usage = new MockMemoryUsage(); - queue.setOptimizedDispatch(true); - queue.initialize(); - queue.start(); - queue.memoryUsage = usage; + queue.setOptimizedDispatch(true); + queue.initialize(); + queue.start(); + queue.memoryUsage = usage; - ProducerBrokerExchange producerExchange = new ProducerBrokerExchange(); - ProducerInfo producerInfo = new ProducerInfo(); - ProducerState producerState = new ProducerState(producerInfo); - producerExchange.setProducerState(producerState); - producerExchange.setConnectionContext(contextNotInTx); + ProducerBrokerExchange producerExchange = new ProducerBrokerExchange(); + ProducerInfo producerInfo = new ProducerInfo(); + ProducerState producerState = new ProducerState(producerInfo); + producerExchange.setProducerState(producerState); + producerExchange.setConnectionContext(contextNotInTx); - // populate the queue store, exceed memory limit so that cache is disabled - for (int i = 0; i < count; i++) { - Message message = getMessage(i); - queue.send(producerExchange, message); - } + // populate the queue store, exceed memory limit so that cache is disabled + for (int i = 0; i < count; i++) { + Message message = getMessage(i); + queue.send(producerExchange, message); + } - usage.setFull(false); + usage.setFull(false); - try { - queue.wakeup(); - } catch(Exception e) { - LOG.error("Queue threw an unexpected exception: " + e.toString()); - fail("Should not throw an exception."); - } - } + try { + queue.wakeup(); + } + catch (Exception e) { + LOG.error("Queue threw an unexpected exception: " + e.toString()); + fail("Should not throw an exception."); + } + } - private Message getMessage(int i) throws Exception { - ActiveMQTextMessage message = new ActiveMQTextMessage(); - message.setMessageId(new MessageId(mesageIdRoot + i)); - message.setDestination(destination); - message.setPersistent(false); - message.setResponseRequired(true); - message.setText("Msg:" + i + " " + text); - assertEquals(message.getMessageId().getProducerSequenceId(), i); - return message; - } + private Message getMessage(int i) throws Exception { + ActiveMQTextMessage message = new ActiveMQTextMessage(); + message.setMessageId(new MessageId(mesageIdRoot + i)); + message.setDestination(destination); + message.setPersistent(false); + message.setResponseRequired(true); + message.setText("Msg:" + i + " " + text); + assertEquals(message.getMessageId().getProducerSequenceId(), i); + return message; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueuePurgeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueuePurgeTest.java index d02085aed6..2bff33cfae 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueuePurgeTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueuePurgeTest.java @@ -30,6 +30,7 @@ import javax.jms.Session; import javax.jms.TextMessage; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.CombinationTestSupport; import org.apache.activemq.broker.BrokerService; @@ -47,170 +48,162 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class QueuePurgeTest extends CombinationTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(QueuePurgeTest.class); - private static final int NUM_TO_SEND = 20000; - private final String MESSAGE_TEXT = new String(new byte[1024]); - BrokerService broker; - ConnectionFactory factory; - Connection connection; - Session session; - Queue queue; - MessageConsumer consumer; - protected void setUp() throws Exception { - setMaxTestTime(10*60*1000); // 10 mins - setAutoFail(true); - super.setUp(); - broker = new BrokerService(); + private static final Logger LOG = LoggerFactory.getLogger(QueuePurgeTest.class); + private static final int NUM_TO_SEND = 20000; + private final String MESSAGE_TEXT = new String(new byte[1024]); + BrokerService broker; + ConnectionFactory factory; + Connection connection; + Session session; + Queue queue; + MessageConsumer consumer; - File testDataDir = new File("target/activemq-data/QueuePurgeTest"); - broker.setDataDirectoryFile(testDataDir); - broker.setUseJmx(true); - broker.setDeleteAllMessagesOnStartup(true); - broker.getSystemUsage().getMemoryUsage().setLimit(1024L*1024*64); - KahaDBPersistenceAdapter persistenceAdapter = new KahaDBPersistenceAdapter(); - persistenceAdapter.setDirectory(new File(testDataDir, "kahadb")); - broker.setPersistenceAdapter(persistenceAdapter); - broker.addConnector("tcp://localhost:0"); - broker.start(); - factory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri().toString()); - connection = factory.createConnection(); - connection.start(); - } + protected void setUp() throws Exception { + setMaxTestTime(10 * 60 * 1000); // 10 mins + setAutoFail(true); + super.setUp(); + broker = new BrokerService(); - protected void tearDown() throws Exception { - super.tearDown(); - if (consumer != null) { - consumer.close(); - } - session.close(); - connection.stop(); - connection.close(); - broker.stop(); - } + File testDataDir = new File("target/activemq-data/QueuePurgeTest"); + broker.setDataDirectoryFile(testDataDir); + broker.setUseJmx(true); + broker.setDeleteAllMessagesOnStartup(true); + broker.getSystemUsage().getMemoryUsage().setLimit(1024L * 1024 * 64); + KahaDBPersistenceAdapter persistenceAdapter = new KahaDBPersistenceAdapter(); + persistenceAdapter.setDirectory(new File(testDataDir, "kahadb")); + broker.setPersistenceAdapter(persistenceAdapter); + broker.addConnector("tcp://localhost:0"); + broker.start(); + factory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri().toString()); + connection = factory.createConnection(); + connection.start(); + } - public void testPurgeLargeQueue() throws Exception { - applyBrokerSpoolingPolicy(); - createProducerAndSendMessages(NUM_TO_SEND); - QueueViewMBean proxy = getProxyToQueueViewMBean(); - LOG.info("purging.."); + protected void tearDown() throws Exception { + super.tearDown(); + if (consumer != null) { + consumer.close(); + } + session.close(); + connection.stop(); + connection.close(); + broker.stop(); + } - org.apache.log4j.Logger log4jLogger = org.apache.log4j.Logger.getLogger(org.apache.activemq.broker.region.Queue.class); - final AtomicBoolean gotPurgeLogMessage = new AtomicBoolean(false); + public void testPurgeLargeQueue() throws Exception { + applyBrokerSpoolingPolicy(); + createProducerAndSendMessages(NUM_TO_SEND); + QueueViewMBean proxy = getProxyToQueueViewMBean(); + LOG.info("purging.."); - Appender appender = new DefaultTestAppender() { - @Override - public void doAppend(LoggingEvent event) { - if (event.getMessage() instanceof String) { - String message = (String) event.getMessage(); - if (message.contains("purged of " + NUM_TO_SEND +" messages")) { - LOG.info("Received a log message: {} ", event.getMessage()); - gotPurgeLogMessage.set(true); - } - } + org.apache.log4j.Logger log4jLogger = org.apache.log4j.Logger.getLogger(org.apache.activemq.broker.region.Queue.class); + final AtomicBoolean gotPurgeLogMessage = new AtomicBoolean(false); + + Appender appender = new DefaultTestAppender() { + @Override + public void doAppend(LoggingEvent event) { + if (event.getMessage() instanceof String) { + String message = (String) event.getMessage(); + if (message.contains("purged of " + NUM_TO_SEND + " messages")) { + LOG.info("Received a log message: {} ", event.getMessage()); + gotPurgeLogMessage.set(true); + } } - }; + } + }; - Level level = log4jLogger.getLevel(); - log4jLogger.setLevel(Level.INFO); - log4jLogger.addAppender(appender); - try { + Level level = log4jLogger.getLevel(); + log4jLogger.setLevel(Level.INFO); + log4jLogger.addAppender(appender); + try { - proxy.purge(); + proxy.purge(); - } finally { - log4jLogger.setLevel(level); - log4jLogger.removeAppender(appender); - } + } + finally { + log4jLogger.setLevel(level); + log4jLogger.removeAppender(appender); + } - assertEquals("Queue size is not zero, it's " + proxy.getQueueSize(), 0, - proxy.getQueueSize()); - assertTrue("cache is disabled, temp store being used", !proxy.isCacheEnabled()); - assertTrue("got expected info purge log message", gotPurgeLogMessage.get()); - } + assertEquals("Queue size is not zero, it's " + proxy.getQueueSize(), 0, proxy.getQueueSize()); + assertTrue("cache is disabled, temp store being used", !proxy.isCacheEnabled()); + assertTrue("got expected info purge log message", gotPurgeLogMessage.get()); + } - public void testRepeatedExpiryProcessingOfLargeQueue() throws Exception { - applyBrokerSpoolingPolicy(); - final int expiryPeriod = 500; - applyExpiryDuration(expiryPeriod); - createProducerAndSendMessages(NUM_TO_SEND); - QueueViewMBean proxy = getProxyToQueueViewMBean(); - LOG.info("waiting for expiry to kick in a bunch of times to verify it does not blow mem"); - Thread.sleep(5000); - assertEquals("Queue size is has not changed " + proxy.getQueueSize(), NUM_TO_SEND, - proxy.getQueueSize()); - } - + public void testRepeatedExpiryProcessingOfLargeQueue() throws Exception { + applyBrokerSpoolingPolicy(); + final int expiryPeriod = 500; + applyExpiryDuration(expiryPeriod); + createProducerAndSendMessages(NUM_TO_SEND); + QueueViewMBean proxy = getProxyToQueueViewMBean(); + LOG.info("waiting for expiry to kick in a bunch of times to verify it does not blow mem"); + Thread.sleep(5000); + assertEquals("Queue size is has not changed " + proxy.getQueueSize(), NUM_TO_SEND, proxy.getQueueSize()); + } - private void applyExpiryDuration(int i) { - broker.getDestinationPolicy().getDefaultEntry().setExpireMessagesPeriod(i); - } + private void applyExpiryDuration(int i) { + broker.getDestinationPolicy().getDefaultEntry().setExpireMessagesPeriod(i); + } - private void applyBrokerSpoolingPolicy() { - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setProducerFlowControl(false); - PendingQueueMessageStoragePolicy pendingQueuePolicy = new FilePendingQueueMessageStoragePolicy(); - defaultEntry.setPendingQueuePolicy(pendingQueuePolicy); - policyMap.setDefaultEntry(defaultEntry); - broker.setDestinationPolicy(policyMap); - } + private void applyBrokerSpoolingPolicy() { + PolicyMap policyMap = new PolicyMap(); + PolicyEntry defaultEntry = new PolicyEntry(); + defaultEntry.setProducerFlowControl(false); + PendingQueueMessageStoragePolicy pendingQueuePolicy = new FilePendingQueueMessageStoragePolicy(); + defaultEntry.setPendingQueuePolicy(pendingQueuePolicy); + policyMap.setDefaultEntry(defaultEntry); + broker.setDestinationPolicy(policyMap); + } - - public void testPurgeLargeQueueWithConsumer() throws Exception { - applyBrokerSpoolingPolicy(); - createProducerAndSendMessages(NUM_TO_SEND); - QueueViewMBean proxy = getProxyToQueueViewMBean(); - createConsumer(); - long start = System.currentTimeMillis(); - LOG.info("purging.."); - proxy.purge(); - LOG.info("purge done: " + (System.currentTimeMillis() - start) + "ms"); - assertEquals("Queue size is not zero, it's " + proxy.getQueueSize(), 0, - proxy.getQueueSize()); - assertEquals("usage goes to duck", 0, proxy.getMemoryPercentUsage()); - Message msg; - do { - msg = consumer.receive(1000); - if (msg != null) { - msg.acknowledge(); - } - } while (msg != null); - assertEquals("Queue size not valid", 0, proxy.getQueueSize()); - } + public void testPurgeLargeQueueWithConsumer() throws Exception { + applyBrokerSpoolingPolicy(); + createProducerAndSendMessages(NUM_TO_SEND); + QueueViewMBean proxy = getProxyToQueueViewMBean(); + createConsumer(); + long start = System.currentTimeMillis(); + LOG.info("purging.."); + proxy.purge(); + LOG.info("purge done: " + (System.currentTimeMillis() - start) + "ms"); + assertEquals("Queue size is not zero, it's " + proxy.getQueueSize(), 0, proxy.getQueueSize()); + assertEquals("usage goes to duck", 0, proxy.getMemoryPercentUsage()); + Message msg; + do { + msg = consumer.receive(1000); + if (msg != null) { + msg.acknowledge(); + } + } while (msg != null); + assertEquals("Queue size not valid", 0, proxy.getQueueSize()); + } - private QueueViewMBean getProxyToQueueViewMBean() - throws MalformedObjectNameException, JMSException { - ObjectName queueViewMBeanName = - new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" - + queue.getQueueName()); - QueueViewMBean proxy = (QueueViewMBean) broker.getManagementContext() - .newProxyInstance(queueViewMBeanName, - QueueViewMBean.class, true); - return proxy; - } + private QueueViewMBean getProxyToQueueViewMBean() throws MalformedObjectNameException, JMSException { + ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + queue.getQueueName()); + QueueViewMBean proxy = (QueueViewMBean) broker.getManagementContext().newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); + return proxy; + } - private void createProducerAndSendMessages(int numToSend) throws Exception { - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - queue = session.createQueue("test1"); - MessageProducer producer = session.createProducer(queue); - for (int i = 0; i < numToSend; i++) { - TextMessage message = session.createTextMessage(MESSAGE_TEXT + i); - if (i != 0 && i % 10000 == 0) { - LOG.info("sent: " + i); - } - producer.send(message); - } - producer.close(); - } + private void createProducerAndSendMessages(int numToSend) throws Exception { + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + queue = session.createQueue("test1"); + MessageProducer producer = session.createProducer(queue); + for (int i = 0; i < numToSend; i++) { + TextMessage message = session.createTextMessage(MESSAGE_TEXT + i); + if (i != 0 && i % 10000 == 0) { + LOG.info("sent: " + i); + } + producer.send(message); + } + producer.close(); + } - private void createConsumer() throws Exception { - consumer = session.createConsumer(queue); - // wait for buffer fill out - Thread.sleep(5 * 1000); - for (int i = 0; i < 500; ++i) { - Message message = consumer.receive(); - message.acknowledge(); - } - } + private void createConsumer() throws Exception { + consumer = session.createConsumer(queue); + // wait for buffer fill out + Thread.sleep(5 * 1000); + for (int i = 0; i < 500; ++i) { + Message message = consumer.receive(); + message.acknowledge(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueueResendDuringShutdownTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueueResendDuringShutdownTest.java index c7154a9768..9445fe5e71 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueueResendDuringShutdownTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueueResendDuringShutdownTest.java @@ -43,208 +43,213 @@ import org.junit.*; * Confirm that the broker does not resend unacknowledged messages during a broker shutdown. */ public class QueueResendDuringShutdownTest { - private static final Logger LOG = LoggerFactory.getLogger(QueueResendDuringShutdownTest.class); - public static final int NUM_CONNECTION_TO_TEST = 8; - private static boolean iterationFoundFailure = false; + private static final Logger LOG = LoggerFactory.getLogger(QueueResendDuringShutdownTest.class); + public static final int NUM_CONNECTION_TO_TEST = 8; - private BrokerService broker; - private ActiveMQConnectionFactory factory; - private Connection[] connections; - private Connection producerConnection; - private Queue queue; + private static boolean iterationFoundFailure = false; - private final Object messageReceiveSync = new Object(); - private int receiveCount; + private BrokerService broker; + private ActiveMQConnectionFactory factory; + private Connection[] connections; + private Connection producerConnection; + private Queue queue; - @Before - public void setUp () throws Exception { - this.receiveCount = 0; + private final Object messageReceiveSync = new Object(); + private int receiveCount; - this.broker = new BrokerService(); - this.broker.setPersistent(false); - this.broker.start(); - this.broker.waitUntilStarted(); + @Before + public void setUp() throws Exception { + this.receiveCount = 0; - this.factory = new ActiveMQConnectionFactory(broker.getVmConnectorURI()); - this.queue = new ActiveMQQueue("TESTQUEUE"); + this.broker = new BrokerService(); + this.broker.setPersistent(false); + this.broker.start(); + this.broker.waitUntilStarted(); - connections = new Connection[NUM_CONNECTION_TO_TEST]; - int iter = 0; - while ( iter < NUM_CONNECTION_TO_TEST ) { - this.connections[iter] = factory.createConnection(); - iter++; - } + this.factory = new ActiveMQConnectionFactory(broker.getVmConnectorURI()); + this.queue = new ActiveMQQueue("TESTQUEUE"); - this.producerConnection = factory.createConnection(); - this.producerConnection.start(); - } + connections = new Connection[NUM_CONNECTION_TO_TEST]; + int iter = 0; + while (iter < NUM_CONNECTION_TO_TEST) { + this.connections[iter] = factory.createConnection(); + iter++; + } - @After - public void cleanup () throws Exception { - for ( Connection oneConnection : connections ) { - if ( oneConnection != null ) { - closeConnection(oneConnection); + this.producerConnection = factory.createConnection(); + this.producerConnection.start(); + } + + @After + public void cleanup() throws Exception { + for (Connection oneConnection : connections) { + if (oneConnection != null) { + closeConnection(oneConnection); + } + } + connections = null; + + if (this.producerConnection != null) { + closeConnection(this.producerConnection); + this.producerConnection = null; + } + + this.broker.stop(); + this.broker.waitUntilStopped(); + } + + @Test(timeout = 3000) + public void testRedeliverAtBrokerShutdownAutoAckMsgListenerIter1() throws Throwable { + runTestIteration(); + } + + @Test(timeout = 3000) + public void testRedeliverAtBrokerShutdownAutoAckMsgListenerIter2() throws Throwable { + runTestIteration(); + } + + @Test(timeout = 3000) + public void testRedeliverAtBrokerShutdownAutoAckMsgListenerIter3() throws Throwable { + runTestIteration(); + } + + /** + * Run one iteration of the test, skipping it if a failure was found on a prior iteration since a single failure is + * enough. Also keep track of the state of failure for the iteration. + */ + protected void runTestIteration() throws Throwable { + if (iterationFoundFailure) { + LOG.info("skipping test iteration; failure previously detected"); + return; + } + try { + testRedeliverAtBrokerShutdownAutoAckMsgListener(); + } + catch (Throwable thrown) { + iterationFoundFailure = true; + throw thrown; + } + } + + protected void testRedeliverAtBrokerShutdownAutoAckMsgListener() throws Exception { + // Start consumers on all of the connections + for (Connection oneConnection : connections) { + MessageConsumer consumer = startupConsumer(oneConnection, false, Session.AUTO_ACKNOWLEDGE); + configureMessageListener(consumer); + oneConnection.start(); + } + + // Send one message to the Queue and wait a short time for the dispatch to occur. + this.sendMessage(); + waitForMessage(1000); + + // Verify one consumer received it + assertEquals(1, this.receiveCount); + + // Shutdown the broker + this.broker.stop(); + this.broker.waitUntilStopped(); + delay(100, "give queue time flush"); + + // Verify still only one consumer received it + assertEquals(1, this.receiveCount); + } + + /** + * Start a consumer on the given connection using the session transaction and acknowledge settings given. + */ + protected MessageConsumer startupConsumer(Connection conn, boolean transInd, int ackMode) throws JMSException { + Session sess; + MessageConsumer consumer; + + sess = conn.createSession(transInd, ackMode); + consumer = sess.createConsumer(queue); + + return consumer; + } + + /** + * Mark the receipt of a message from one of the consumers. + */ + protected void messageReceived() { + synchronized (this) { + this.receiveCount++; + synchronized (this.messageReceiveSync) { + this.messageReceiveSync.notifyAll(); + } + } + } + + /** + * Setup the MessageListener for the given consumer. The listener uses a long delay on receiving the message to + * simulate the reported case of problems at shutdown caused by a message listener's connection closing while it is + * still processing. + */ + protected void configureMessageListener(MessageConsumer consumer) throws JMSException { + final MessageConsumer fConsumer = consumer; + + consumer.setMessageListener(new MessageListener() { + public void onMessage(Message msg) { + LOG.debug("got a message on consumer {}", fConsumer); + messageReceived(); + + // Delay long enough for the consumer to get closed while this delay is active. + delay(3000, "pause so connection shutdown leads to unacked message redelivery"); + } + }); + } + + /** + * Send a test message now. + */ + protected void sendMessage() throws JMSException { + Session sess = this.producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer prod = sess.createProducer(queue); + prod.send(sess.createTextMessage("X-TEST-MSG-X")); + prod.close(); + sess.close(); + } + + /** + * Close the given connection safely and log any exception caught. + */ + protected void closeConnection(Connection conn) { + try { + conn.close(); + } + catch (JMSException jmsExc) { + LOG.info("failed to cleanup connection", jmsExc); + } + } + + /** + * Pause for the given length of time, in milliseconds, logging an interruption if one occurs. Don't try to + * recover from interrupt - the test case does not support interrupting and such an occurrence likely means the + * test is being aborted. + */ + protected void delay(long delayMs, String desc) { + try { + Thread.sleep(delayMs); + } + catch (InterruptedException intExc) { + LOG.warn("sleep interrupted: " + desc, intExc); + } + } + + /** + * Wait up to the specified duration for a message to be received by any consumer. + */ + protected void waitForMessage(long delayMs) { + try { + synchronized (this.messageReceiveSync) { + while (this.receiveCount == 0) { + this.messageReceiveSync.wait(delayMs); } - } - connections = null; - - if ( this.producerConnection != null ) { - closeConnection(this.producerConnection); - this.producerConnection = null; - } - - this.broker.stop(); - this.broker.waitUntilStopped(); - } - - @Test(timeout=3000) - public void testRedeliverAtBrokerShutdownAutoAckMsgListenerIter1 () throws Throwable { - runTestIteration(); - } - - @Test(timeout=3000) - public void testRedeliverAtBrokerShutdownAutoAckMsgListenerIter2 () throws Throwable { - runTestIteration(); - } - - @Test(timeout=3000) - public void testRedeliverAtBrokerShutdownAutoAckMsgListenerIter3 () throws Throwable { - runTestIteration(); - } - - /** - * Run one iteration of the test, skipping it if a failure was found on a prior iteration since a single failure is - * enough. Also keep track of the state of failure for the iteration. - */ - protected void runTestIteration () throws Throwable { - if ( iterationFoundFailure ) { - LOG.info("skipping test iteration; failure previously detected"); - return; - } try { - testRedeliverAtBrokerShutdownAutoAckMsgListener(); - } catch ( Throwable thrown ) { - iterationFoundFailure = true; - throw thrown; - } - } - - protected void testRedeliverAtBrokerShutdownAutoAckMsgListener () throws Exception { - // Start consumers on all of the connections - for ( Connection oneConnection : connections ) { - MessageConsumer consumer = startupConsumer(oneConnection, false, Session.AUTO_ACKNOWLEDGE); - configureMessageListener(consumer); - oneConnection.start(); - } - - // Send one message to the Queue and wait a short time for the dispatch to occur. - this.sendMessage(); - waitForMessage(1000); - - // Verify one consumer received it - assertEquals(1, this.receiveCount); - - // Shutdown the broker - this.broker.stop(); - this.broker.waitUntilStopped(); - delay(100, "give queue time flush"); - - // Verify still only one consumer received it - assertEquals(1, this.receiveCount); - } - - /** - * Start a consumer on the given connection using the session transaction and acknowledge settings given. - */ - protected MessageConsumer startupConsumer (Connection conn, boolean transInd, int ackMode) - throws JMSException { - Session sess; - MessageConsumer consumer; - - sess = conn.createSession(transInd, ackMode); - consumer = sess.createConsumer(queue); - - return consumer; - } - - /** - * Mark the receipt of a message from one of the consumers. - */ - protected void messageReceived () { - synchronized ( this ) { - this.receiveCount++; - synchronized ( this.messageReceiveSync ) { - this.messageReceiveSync.notifyAll(); - } - } - } - - /** - * Setup the MessageListener for the given consumer. The listener uses a long delay on receiving the message to - * simulate the reported case of problems at shutdown caused by a message listener's connection closing while it is - * still processing. - */ - protected void configureMessageListener (MessageConsumer consumer) throws JMSException { - final MessageConsumer fConsumer = consumer; - - consumer.setMessageListener(new MessageListener() { - public void onMessage (Message msg) { - LOG.debug("got a message on consumer {}", fConsumer); - messageReceived(); - - // Delay long enough for the consumer to get closed while this delay is active. - delay(3000, "pause so connection shutdown leads to unacked message redelivery"); - } - }); - } - - /** - * Send a test message now. - */ - protected void sendMessage () throws JMSException { - Session sess = this.producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer prod = sess.createProducer(queue); - prod.send(sess.createTextMessage("X-TEST-MSG-X")); - prod.close(); - sess.close(); - } - - /** - * Close the given connection safely and log any exception caught. - */ - protected void closeConnection (Connection conn) { - try { - conn.close(); - } catch ( JMSException jmsExc ) { - LOG.info("failed to cleanup connection", jmsExc); - } - } - - /** - * Pause for the given length of time, in milliseconds, logging an interruption if one occurs. Don't try to - * recover from interrupt - the test case does not support interrupting and such an occurrence likely means the - * test is being aborted. - */ - protected void delay (long delayMs, String desc) { - try { - Thread.sleep(delayMs); - } catch ( InterruptedException intExc ) { - LOG.warn("sleep interrupted: " + desc, intExc); - } - } - - /** - * Wait up to the specified duration for a message to be received by any consumer. - */ - protected void waitForMessage (long delayMs) { - try { - synchronized ( this.messageReceiveSync ) { - while ( this.receiveCount == 0 ) { - this.messageReceiveSync.wait(delayMs); - } - } - } catch ( InterruptedException intExc ) { - LOG.warn("sleep interrupted: wait for message to arrive"); - } - } + } + } + catch (InterruptedException intExc) { + LOG.warn("sleep interrupted: wait for message to arrive"); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/SubscriptionAddRemoveQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/SubscriptionAddRemoveQueueTest.java index 6964842614..a54c8406d9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/SubscriptionAddRemoveQueueTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/SubscriptionAddRemoveQueueTest.java @@ -61,314 +61,307 @@ import org.apache.activemq.filter.MessageEvaluationContext; import org.apache.activemq.state.ProducerState; import org.apache.activemq.store.MessageStore; import org.apache.activemq.thread.TaskRunnerFactory; + import junit.framework.TestCase; public class SubscriptionAddRemoveQueueTest extends TestCase { - Queue queue; + Queue queue; - ConsumerInfo info = new ConsumerInfo(); - List subs = new ArrayList(); - ConnectionContext context = new ConnectionContext(); - ProducerBrokerExchange producerBrokerExchange = new ProducerBrokerExchange(); - ProducerInfo producerInfo = new ProducerInfo(); - ProducerState producerState = new ProducerState(producerInfo); - ActiveMQDestination destination = new ActiveMQQueue("TEST"); - int numSubscriptions = 1000; - boolean working = true; - int senders = 20; + ConsumerInfo info = new ConsumerInfo(); + List subs = new ArrayList(); + ConnectionContext context = new ConnectionContext(); + ProducerBrokerExchange producerBrokerExchange = new ProducerBrokerExchange(); + ProducerInfo producerInfo = new ProducerInfo(); + ProducerState producerState = new ProducerState(producerInfo); + ActiveMQDestination destination = new ActiveMQQueue("TEST"); + int numSubscriptions = 1000; + boolean working = true; + int senders = 20; + @Override + public void setUp() throws Exception { + BrokerService brokerService = new BrokerService(); + brokerService.start(); + DestinationStatistics parentStats = new DestinationStatistics(); + parentStats.setEnabled(true); - @Override - public void setUp() throws Exception { - BrokerService brokerService = new BrokerService(); - brokerService.start(); - DestinationStatistics parentStats = new DestinationStatistics(); - parentStats.setEnabled(true); + TaskRunnerFactory taskFactory = new TaskRunnerFactory(); + MessageStore store = null; - TaskRunnerFactory taskFactory = new TaskRunnerFactory(); - MessageStore store = null; + info.setDestination(destination); + info.setPrefetchSize(100); - info.setDestination(destination); - info.setPrefetchSize(100); + producerBrokerExchange.setProducerState(producerState); + producerBrokerExchange.setConnectionContext(context); - producerBrokerExchange.setProducerState(producerState); - producerBrokerExchange.setConnectionContext(context); + queue = new Queue(brokerService, destination, store, parentStats, taskFactory); + queue.initialize(); + } - queue = new Queue(brokerService, destination, store, parentStats, taskFactory); - queue.initialize(); - } - - public void testNoDispatchToRemovedConsumers() throws Exception { - final AtomicInteger producerId = new AtomicInteger(); - Runnable sender = new Runnable() { - public void run() { - AtomicInteger id = new AtomicInteger(); - int producerIdAndIncrement = producerId.getAndIncrement(); - while (working) { - try { - Message msg = new ActiveMQMessage(); - msg.setDestination(destination); - msg.setMessageId(new MessageId(producerIdAndIncrement + ":0:" + id.getAndIncrement())); - queue.send(producerBrokerExchange, msg); - } catch (Exception e) { - e.printStackTrace(); - fail("unexpected exception in sendMessage, ex:" + e); - } - } + public void testNoDispatchToRemovedConsumers() throws Exception { + final AtomicInteger producerId = new AtomicInteger(); + Runnable sender = new Runnable() { + public void run() { + AtomicInteger id = new AtomicInteger(); + int producerIdAndIncrement = producerId.getAndIncrement(); + while (working) { + try { + Message msg = new ActiveMQMessage(); + msg.setDestination(destination); + msg.setMessageId(new MessageId(producerIdAndIncrement + ":0:" + id.getAndIncrement())); + queue.send(producerBrokerExchange, msg); + } + catch (Exception e) { + e.printStackTrace(); + fail("unexpected exception in sendMessage, ex:" + e); + } } - }; + } + }; - Runnable subRemover = new Runnable() { - public void run() { - for (Subscription sub : subs) { - try { - queue.removeSubscription(context, sub, 0); - } catch (Exception e) { - e.printStackTrace(); - fail("unexpected exception in removeSubscription, ex:" + e); - } - } + Runnable subRemover = new Runnable() { + public void run() { + for (Subscription sub : subs) { + try { + queue.removeSubscription(context, sub, 0); + } + catch (Exception e) { + e.printStackTrace(); + fail("unexpected exception in removeSubscription, ex:" + e); + } } - }; + } + }; - for (int i=0;i result = executor.submit(subRemover); - result.get(); - working = false; - assertEquals("there are no subscriptions", 0, queue.getDestinationStatistics().getConsumers().getCount()); + Future result = executor.submit(subRemover); + result.get(); + working = false; + assertEquals("there are no subscriptions", 0, queue.getDestinationStatistics().getConsumers().getCount()); - for (SimpleImmediateDispatchSubscription sub : subs) { - assertTrue("There are no locked messages in any removed subscriptions", !hasSomeLocks(sub.dispatched)); - } + for (SimpleImmediateDispatchSubscription sub : subs) { + assertTrue("There are no locked messages in any removed subscriptions", !hasSomeLocks(sub.dispatched)); + } - } + } - private boolean hasSomeLocks(List dispatched) { - boolean hasLock = false; - for (MessageReference mr: dispatched) { - QueueMessageReference qmr = (QueueMessageReference) mr; - if (qmr.getLockOwner() != null) { - hasLock = true; - break; - } - } - return hasLock; - } + private boolean hasSomeLocks(List dispatched) { + boolean hasLock = false; + for (MessageReference mr : dispatched) { + QueueMessageReference qmr = (QueueMessageReference) mr; + if (qmr.getLockOwner() != null) { + hasLock = true; + break; + } + } + return hasLock; + } - public class SimpleImmediateDispatchSubscription implements Subscription, LockOwner { + public class SimpleImmediateDispatchSubscription implements Subscription, LockOwner { - List dispatched = - Collections.synchronizedList(new ArrayList()); + List dispatched = Collections.synchronizedList(new ArrayList()); - public void acknowledge(ConnectionContext context, MessageAck ack) - throws Exception { - } + public void acknowledge(ConnectionContext context, MessageAck ack) throws Exception { + } - public void add(MessageReference node) throws Exception { - // immediate dispatch - QueueMessageReference qmr = (QueueMessageReference)node; - qmr.lock(this); - dispatched.add(qmr); - } + public void add(MessageReference node) throws Exception { + // immediate dispatch + QueueMessageReference qmr = (QueueMessageReference) node; + qmr.lock(this); + dispatched.add(qmr); + } - public ConnectionContext getContext() { - return null; - } + public ConnectionContext getContext() { + return null; + } - @Override - public int getCursorMemoryHighWaterMark() { - return 0; - } + @Override + public int getCursorMemoryHighWaterMark() { + return 0; + } - @Override - public void setCursorMemoryHighWaterMark(int cursorMemoryHighWaterMark) { - } + @Override + public void setCursorMemoryHighWaterMark(int cursorMemoryHighWaterMark) { + } - @Override - public boolean isSlowConsumer() { - return false; - } + @Override + public boolean isSlowConsumer() { + return false; + } - @Override - public void unmatched(MessageReference node) throws IOException { - } + @Override + public void unmatched(MessageReference node) throws IOException { + } - @Override - public long getTimeOfLastMessageAck() { - return 0; - } + @Override + public long getTimeOfLastMessageAck() { + return 0; + } - @Override - public long getConsumedCount() { - return 0; - } + @Override + public long getConsumedCount() { + return 0; + } - @Override - public void incrementConsumedCount() { - } + @Override + public void incrementConsumedCount() { + } - @Override - public void resetConsumedCount() { - } + @Override + public void resetConsumedCount() { + } - public void add(ConnectionContext context, Destination destination) - throws Exception { - } + public void add(ConnectionContext context, Destination destination) throws Exception { + } - public void destroy() { - } + public void destroy() { + } - public void gc() { - } + public void gc() { + } - public ConsumerInfo getConsumerInfo() { - return info; - } + public ConsumerInfo getConsumerInfo() { + return info; + } - public long getDequeueCounter() { - return 0; - } + public long getDequeueCounter() { + return 0; + } - public long getDispatchedCounter() { - return 0; - } + public long getDispatchedCounter() { + return 0; + } - public int getDispatchedQueueSize() { - return 0; - } + public int getDispatchedQueueSize() { + return 0; + } - public long getEnqueueCounter() { - return 0; - } + public long getEnqueueCounter() { + return 0; + } - public int getInFlightSize() { - return 0; - } + public int getInFlightSize() { + return 0; + } - public int getInFlightUsage() { - return 0; - } + public int getInFlightUsage() { + return 0; + } - public ObjectName getObjectName() { - return null; - } + public ObjectName getObjectName() { + return null; + } - public int getPendingQueueSize() { - return 0; - } + public int getPendingQueueSize() { + return 0; + } - public int getPrefetchSize() { - return 0; - } + public int getPrefetchSize() { + return 0; + } - public String getSelector() { - return null; - } + public String getSelector() { + return null; + } - public boolean isBrowser() { - return false; - } + public boolean isBrowser() { + return false; + } - public boolean isFull() { - return false; - } + public boolean isFull() { + return false; + } - public boolean isHighWaterMark() { - return false; - } + public boolean isHighWaterMark() { + return false; + } - public boolean isLowWaterMark() { - return false; - } + public boolean isLowWaterMark() { + return false; + } - public boolean isRecoveryRequired() { - return false; - } + public boolean isRecoveryRequired() { + return false; + } - public boolean isSlave() { - return false; - } + public boolean isSlave() { + return false; + } - public boolean matches(MessageReference node, - MessageEvaluationContext context) throws IOException { - return true; - } + public boolean matches(MessageReference node, MessageEvaluationContext context) throws IOException { + return true; + } - public boolean matches(ActiveMQDestination destination) { - return false; - } + public boolean matches(ActiveMQDestination destination) { + return false; + } - public void processMessageDispatchNotification( - MessageDispatchNotification mdn) throws Exception { - } + public void processMessageDispatchNotification(MessageDispatchNotification mdn) throws Exception { + } - public Response pullMessage(ConnectionContext context, MessagePull pull) - throws Exception { - return null; - } + public Response pullMessage(ConnectionContext context, MessagePull pull) throws Exception { + return null; + } - @Override - public boolean isWildcard() { - return false; - } + @Override + public boolean isWildcard() { + return false; + } - public List remove(ConnectionContext context, - Destination destination) throws Exception { - return new ArrayList(dispatched); - } + public List remove(ConnectionContext context, Destination destination) throws Exception { + return new ArrayList(dispatched); + } - public void setObjectName(ObjectName objectName) { - } + public void setObjectName(ObjectName objectName) { + } - public void setSelector(String selector) - throws InvalidSelectorException, UnsupportedOperationException { - } + public void setSelector(String selector) throws InvalidSelectorException, UnsupportedOperationException { + } - public void updateConsumerPrefetch(int newPrefetch) { - } + public void updateConsumerPrefetch(int newPrefetch) { + } - public boolean addRecoveredMessage(ConnectionContext context, - MessageReference message) throws Exception { - return false; - } + public boolean addRecoveredMessage(ConnectionContext context, MessageReference message) throws Exception { + return false; + } - public ActiveMQDestination getActiveMQDestination() { - return null; - } + public ActiveMQDestination getActiveMQDestination() { + return null; + } - public int getLockPriority() { - return 0; - } + public int getLockPriority() { + return 0; + } - public boolean isLockExclusive() { - return false; - } + public boolean isLockExclusive() { + return false; + } - public void addDestination(Destination destination) { - } + public void addDestination(Destination destination) { + } - public void removeDestination(Destination destination) { - } + public void removeDestination(Destination destination) { + } - public int countBeforeFull() { - return 10; - } + public int countBeforeFull() { + return 10; + } - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/UniquePropertyMessageEvictionStrategyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/UniquePropertyMessageEvictionStrategyTest.java index 5657e5cd4b..4779e91483 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/UniquePropertyMessageEvictionStrategyTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/UniquePropertyMessageEvictionStrategyTest.java @@ -30,76 +30,73 @@ import java.util.List; public class UniquePropertyMessageEvictionStrategyTest extends EmbeddedBrokerTestSupport { + @Override + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); + final List policyEntries = new ArrayList(); + final PolicyEntry entry = new PolicyEntry(); + entry.setTopic(">"); + entry.setAdvisoryForDiscardingMessages(true); + entry.setTopicPrefetch(1); - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - final List policyEntries = new ArrayList(); - final PolicyEntry entry = new PolicyEntry(); - entry.setTopic(">"); + ConstantPendingMessageLimitStrategy pendingMessageLimitStrategy = new ConstantPendingMessageLimitStrategy(); + pendingMessageLimitStrategy.setLimit(10); + entry.setPendingMessageLimitStrategy(pendingMessageLimitStrategy); - entry.setAdvisoryForDiscardingMessages(true); - entry.setTopicPrefetch(1); + UniquePropertyMessageEvictionStrategy messageEvictionStrategy = new UniquePropertyMessageEvictionStrategy(); + messageEvictionStrategy.setPropertyName("sequenceI"); + entry.setMessageEvictionStrategy(messageEvictionStrategy); - ConstantPendingMessageLimitStrategy pendingMessageLimitStrategy = new ConstantPendingMessageLimitStrategy(); - pendingMessageLimitStrategy.setLimit(10); - entry.setPendingMessageLimitStrategy(pendingMessageLimitStrategy); + // let evicted messages disappear + entry.setDeadLetterStrategy(null); + policyEntries.add(entry); + final PolicyMap policyMap = new PolicyMap(); + policyMap.setPolicyEntries(policyEntries); + broker.setDestinationPolicy(policyMap); - UniquePropertyMessageEvictionStrategy messageEvictionStrategy = new UniquePropertyMessageEvictionStrategy(); - messageEvictionStrategy.setPropertyName("sequenceI"); - entry.setMessageEvictionStrategy(messageEvictionStrategy); + return broker; + } - // let evicted messages disappear - entry.setDeadLetterStrategy(null); - policyEntries.add(entry); + public void testEviction() throws Exception { + Connection conn = connectionFactory.createConnection(); + conn.start(); + Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + javax.jms.Topic destination = session.createTopic("TEST"); - final PolicyMap policyMap = new PolicyMap(); - policyMap.setPolicyEntries(policyEntries); - broker.setDestinationPolicy(policyMap); + MessageProducer producer = session.createProducer(destination); + MessageConsumer consumer = session.createConsumer(destination); - return broker; - } + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + TextMessage msg = session.createTextMessage("message " + i + j); + msg.setIntProperty("sequenceI", i); + msg.setIntProperty("sequenceJ", j); + producer.send(msg); + Thread.sleep(100); + } + } - public void testEviction() throws Exception { - Connection conn = connectionFactory.createConnection(); - conn.start(); - Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - javax.jms.Topic destination = session.createTopic("TEST"); + for (int i = 0; i < 11; i++) { + javax.jms.Message msg = consumer.receive(1000); + assertNotNull(msg); + int seqI = msg.getIntProperty("sequenceI"); + int seqJ = msg.getIntProperty("sequenceJ"); + if (i == 0) { + assertEquals(0, seqI); + assertEquals(0, seqJ); + } + else { + assertEquals(9, seqJ); + assertEquals(i - 1, seqI); + } + //System.out.println(msg.getIntProperty("sequenceI") + " " + msg.getIntProperty("sequenceJ")); + } - MessageProducer producer = session.createProducer(destination); - MessageConsumer consumer = session.createConsumer(destination); + javax.jms.Message msg = consumer.receive(1000); + assertNull(msg); - for (int i = 0; i < 10; i++) { - for (int j = 0; j < 10; j++) { - TextMessage msg = session.createTextMessage("message " + i + j); - msg.setIntProperty("sequenceI", i); - msg.setIntProperty("sequenceJ", j); - producer.send(msg); - Thread.sleep(100); - } - } - - - for (int i = 0; i < 11; i++) { - javax.jms.Message msg = consumer.receive(1000); - assertNotNull(msg); - int seqI = msg.getIntProperty("sequenceI"); - int seqJ = msg.getIntProperty("sequenceJ"); - if (i ==0 ) { - assertEquals(0, seqI); - assertEquals(0, seqJ); - } else { - assertEquals(9, seqJ); - assertEquals(i - 1, seqI); - } - //System.out.println(msg.getIntProperty("sequenceI") + " " + msg.getIntProperty("sequenceJ")); - } - - javax.jms.Message msg = consumer.receive(1000); - assertNull(msg); - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/CursorDurableTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/CursorDurableTest.java index 12589ca238..460cb06cfa 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/CursorDurableTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/CursorDurableTest.java @@ -23,35 +23,36 @@ import javax.jms.JMSException; import javax.jms.MessageConsumer; import javax.jms.Session; import javax.jms.Topic; + import org.apache.activemq.broker.BrokerService; /** - * + * */ public class CursorDurableTest extends CursorSupport { - protected Destination getDestination(Session session) throws JMSException { - String topicName = getClass().getName(); - return session.createTopic(topicName); - } + protected Destination getDestination(Session session) throws JMSException { + String topicName = getClass().getName(); + return session.createTopic(topicName); + } - protected Connection getConsumerConnection(ConnectionFactory fac) throws JMSException { - Connection connection = fac.createConnection(); - connection.setClientID("testConsumer"); - connection.start(); - return connection; - } + protected Connection getConsumerConnection(ConnectionFactory fac) throws JMSException { + Connection connection = fac.createConnection(); + connection.setClientID("testConsumer"); + connection.start(); + return connection; + } - protected MessageConsumer getConsumer(Connection connection) throws Exception { - Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic = (Topic)getDestination(consumerSession); - MessageConsumer consumer = consumerSession.createDurableSubscriber(topic, "testConsumer"); - return consumer; - } + protected MessageConsumer getConsumer(Connection connection) throws Exception { + Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Topic topic = (Topic) getDestination(consumerSession); + MessageConsumer consumer = consumerSession.createDurableSubscriber(topic, "testConsumer"); + return consumer; + } - protected void configureBroker(BrokerService answer) throws Exception { - answer.setDeleteAllMessagesOnStartup(true); - answer.addConnector(bindAddress); - answer.setDeleteAllMessagesOnStartup(true); - } + protected void configureBroker(BrokerService answer) throws Exception { + answer.setDeleteAllMessagesOnStartup(true); + answer.addConnector(bindAddress); + answer.setDeleteAllMessagesOnStartup(true); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/CursorQueueStoreTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/CursorQueueStoreTest.java index b0668d9138..6523109efe 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/CursorQueueStoreTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/CursorQueueStoreTest.java @@ -31,45 +31,45 @@ import org.apache.activemq.broker.region.policy.PolicyMap; import org.apache.activemq.broker.region.policy.StorePendingQueueMessageStoragePolicy; /** - * + * */ public class CursorQueueStoreTest extends CursorSupport { - protected Destination getDestination(Session session) throws JMSException { - String queueName = "QUEUE" + getClass().getName(); - return session.createQueue(queueName); - } + protected Destination getDestination(Session session) throws JMSException { + String queueName = "QUEUE" + getClass().getName(); + return session.createQueue(queueName); + } - protected Connection getConsumerConnection(ConnectionFactory fac) throws JMSException { - Connection connection = fac.createConnection(); - connection.setClientID("testConsumer"); - connection.start(); - return connection; - } + protected Connection getConsumerConnection(ConnectionFactory fac) throws JMSException { + Connection connection = fac.createConnection(); + connection.setClientID("testConsumer"); + connection.start(); + return connection; + } - protected MessageConsumer getConsumer(Connection connection) throws Exception { - Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination dest = getDestination(consumerSession); - MessageConsumer consumer = consumerSession.createConsumer(dest); - return consumer; - } + protected MessageConsumer getConsumer(Connection connection) throws Exception { + Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination dest = getDestination(consumerSession); + MessageConsumer consumer = consumerSession.createConsumer(dest); + return consumer; + } - protected void configureBroker(BrokerService answer) throws Exception { - PolicyEntry policy = new PolicyEntry(); - policy.setPendingQueuePolicy(new StorePendingQueueMessageStoragePolicy()); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - answer.setDestinationPolicy(pMap); - answer.setDeleteAllMessagesOnStartup(true); - answer.addConnector(bindAddress); - answer.setDeleteAllMessagesOnStartup(true); - } - - public static Test suite() { - return suite(CursorQueueStoreTest.class); - } + protected void configureBroker(BrokerService answer) throws Exception { + PolicyEntry policy = new PolicyEntry(); + policy.setPendingQueuePolicy(new StorePendingQueueMessageStoragePolicy()); + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); + answer.setDestinationPolicy(pMap); + answer.setDeleteAllMessagesOnStartup(true); + answer.addConnector(bindAddress); + answer.setDeleteAllMessagesOnStartup(true); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static Test suite() { + return suite(CursorQueueStoreTest.class); + } + + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/CursorSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/CursorSupport.java index 3c014a6728..4d03fa1faf 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/CursorSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/CursorSupport.java @@ -21,6 +21,7 @@ import org.apache.activemq.CombinationTestSupport; import org.apache.activemq.broker.BrokerService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import java.util.ArrayList; import java.util.List; import java.util.Properties; @@ -42,157 +43,155 @@ import javax.jms.TextMessage; */ public abstract class CursorSupport extends CombinationTestSupport { - public int MESSAGE_COUNT = 500; - public int PREFETCH_SIZE = 50; - private static final Logger LOG = LoggerFactory.getLogger(CursorSupport.class); + public int MESSAGE_COUNT = 500; + public int PREFETCH_SIZE = 50; + private static final Logger LOG = LoggerFactory.getLogger(CursorSupport.class); - protected BrokerService broker; - protected String bindAddress = "tcp://localhost:60706"; + protected BrokerService broker; + protected String bindAddress = "tcp://localhost:60706"; - protected abstract Destination getDestination(Session session) throws JMSException; + protected abstract Destination getDestination(Session session) throws JMSException; - protected abstract MessageConsumer getConsumer(Connection connection) throws Exception; + protected abstract MessageConsumer getConsumer(Connection connection) throws Exception; - protected abstract void configureBroker(BrokerService answer) throws Exception; + protected abstract void configureBroker(BrokerService answer) throws Exception; - public void testSendFirstThenConsume() throws Exception { - ConnectionFactory factory = createConnectionFactory(); - Connection consumerConnection = getConsumerConnection(factory); - MessageConsumer consumer = getConsumer(consumerConnection); - consumerConnection.close(); - Connection producerConnection = factory.createConnection(); - producerConnection.start(); - Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(getDestination(session)); - List senderList = new ArrayList(); - for (int i = 0; i < MESSAGE_COUNT; i++) { - Message msg = session.createTextMessage("test" + i); - senderList.add(msg); - producer.send(msg); - } - producerConnection.close(); - // now consume the messages - consumerConnection = getConsumerConnection(factory); - // create durable subs - consumer = getConsumer(consumerConnection); - List consumerList = new ArrayList(); - for (int i = 0; i < MESSAGE_COUNT; i++) { - Message msg = consumer.receive(1000*5); - assertNotNull("Message "+i+" was missing.", msg); - consumerList.add(msg); - } - assertEquals(senderList, consumerList); - consumerConnection.close(); - } + public void testSendFirstThenConsume() throws Exception { + ConnectionFactory factory = createConnectionFactory(); + Connection consumerConnection = getConsumerConnection(factory); + MessageConsumer consumer = getConsumer(consumerConnection); + consumerConnection.close(); + Connection producerConnection = factory.createConnection(); + producerConnection.start(); + Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(getDestination(session)); + List senderList = new ArrayList(); + for (int i = 0; i < MESSAGE_COUNT; i++) { + Message msg = session.createTextMessage("test" + i); + senderList.add(msg); + producer.send(msg); + } + producerConnection.close(); + // now consume the messages + consumerConnection = getConsumerConnection(factory); + // create durable subs + consumer = getConsumer(consumerConnection); + List consumerList = new ArrayList(); + for (int i = 0; i < MESSAGE_COUNT; i++) { + Message msg = consumer.receive(1000 * 5); + assertNotNull("Message " + i + " was missing.", msg); + consumerList.add(msg); + } + assertEquals(senderList, consumerList); + consumerConnection.close(); + } + public void initCombosForTestSendWhilstConsume() { + addCombinationValues("MESSAGE_COUNT", new Object[]{Integer.valueOf(400), Integer.valueOf(500)}); + addCombinationValues("PREFETCH_SIZE", new Object[]{Integer.valueOf(100), Integer.valueOf(50)}); + } - public void initCombosForTestSendWhilstConsume() { - addCombinationValues("MESSAGE_COUNT", new Object[] {Integer.valueOf(400), - Integer.valueOf(500)}); - addCombinationValues("PREFETCH_SIZE", new Object[] {Integer.valueOf(100), - Integer.valueOf(50)}); - } + public void testSendWhilstConsume() throws Exception { + ConnectionFactory factory = createConnectionFactory(); + Connection consumerConnection = getConsumerConnection(factory); + // create durable subs + MessageConsumer consumer = getConsumer(consumerConnection); + consumerConnection.close(); + Connection producerConnection = factory.createConnection(); + producerConnection.start(); + Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(getDestination(session)); + List senderList = new ArrayList(); + for (int i = 0; i < MESSAGE_COUNT / 10; i++) { + TextMessage msg = session.createTextMessage("test" + i); + senderList.add(msg); + producer.send(msg); + } + // now consume the messages + consumerConnection = getConsumerConnection(factory); + // create durable subs + consumer = getConsumer(consumerConnection); + final List consumerList = new ArrayList(); + final CountDownLatch latch = new CountDownLatch(1); + consumer.setMessageListener(new MessageListener() { - public void testSendWhilstConsume() throws Exception { - ConnectionFactory factory = createConnectionFactory(); - Connection consumerConnection = getConsumerConnection(factory); - // create durable subs - MessageConsumer consumer = getConsumer(consumerConnection); - consumerConnection.close(); - Connection producerConnection = factory.createConnection(); - producerConnection.start(); - Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(getDestination(session)); - List senderList = new ArrayList(); - for (int i = 0; i < MESSAGE_COUNT / 10; i++) { - TextMessage msg = session.createTextMessage("test" + i); - senderList.add(msg); - producer.send(msg); - } - // now consume the messages - consumerConnection = getConsumerConnection(factory); - // create durable subs - consumer = getConsumer(consumerConnection); - final List consumerList = new ArrayList(); - final CountDownLatch latch = new CountDownLatch(1); - consumer.setMessageListener(new MessageListener() { - - public void onMessage(Message msg) { - try { - // sleep to act as a slow consumer - // which will force a mix of direct and polled dispatching - // using the cursor on the broker - Thread.sleep(50); - } catch (Exception e) { - e.printStackTrace(); - } - consumerList.add(msg); - if (consumerList.size() == MESSAGE_COUNT) { - latch.countDown(); - } + public void onMessage(Message msg) { + try { + // sleep to act as a slow consumer + // which will force a mix of direct and polled dispatching + // using the cursor on the broker + Thread.sleep(50); } - }); - for (int i = MESSAGE_COUNT / 10; i < MESSAGE_COUNT; i++) { - TextMessage msg = session.createTextMessage("test" + i); - senderList.add(msg); - producer.send(msg); - } - latch.await(300000, TimeUnit.MILLISECONDS); - producerConnection.close(); - consumerConnection.close(); - assertEquals("Still dipatching - count down latch not sprung", latch.getCount(), 0); - //assertEquals("cosumerList - expected: " + MESSAGE_COUNT + " but was: " + consumerList.size(), consumerList.size(), senderList.size()); - for (int i = 0; i < senderList.size(); i++) { - Message sent = senderList.get(i); - Message consumed = consumerList.get(i); - if (!sent.equals(consumed)) { - LOG.error("BAD MATCH AT POS " + i); - LOG.error(sent.toString()); - LOG.error(consumed.toString()); + catch (Exception e) { + e.printStackTrace(); + } + consumerList.add(msg); + if (consumerList.size() == MESSAGE_COUNT) { + latch.countDown(); + } + } + }); + for (int i = MESSAGE_COUNT / 10; i < MESSAGE_COUNT; i++) { + TextMessage msg = session.createTextMessage("test" + i); + senderList.add(msg); + producer.send(msg); + } + latch.await(300000, TimeUnit.MILLISECONDS); + producerConnection.close(); + consumerConnection.close(); + assertEquals("Still dipatching - count down latch not sprung", latch.getCount(), 0); + //assertEquals("cosumerList - expected: " + MESSAGE_COUNT + " but was: " + consumerList.size(), consumerList.size(), senderList.size()); + for (int i = 0; i < senderList.size(); i++) { + Message sent = senderList.get(i); + Message consumed = consumerList.get(i); + if (!sent.equals(consumed)) { + LOG.error("BAD MATCH AT POS " + i); + LOG.error(sent.toString()); + LOG.error(consumed.toString()); /* * log.error("\n\n\n\n\n"); for (int j = 0; j < * consumerList.size(); j++) { log.error(consumerList.get(j)); } */ - } - assertEquals("This should be the same at pos " + i + " in the list", sent.getJMSMessageID(), consumed.getJMSMessageID()); - } - } + } + assertEquals("This should be the same at pos " + i + " in the list", sent.getJMSMessageID(), consumed.getJMSMessageID()); + } + } - protected Connection getConsumerConnection(ConnectionFactory fac) throws JMSException { - Connection connection = fac.createConnection(); - connection.setClientID("testConsumer"); - connection.start(); - return connection; - } + protected Connection getConsumerConnection(ConnectionFactory fac) throws JMSException { + Connection connection = fac.createConnection(); + connection.setClientID("testConsumer"); + connection.start(); + return connection; + } - protected void setUp() throws Exception { - if (broker == null) { - broker = createBroker(); - } - super.setUp(); - } + protected void setUp() throws Exception { + if (broker == null) { + broker = createBroker(); + } + super.setUp(); + } - protected void tearDown() throws Exception { - super.tearDown(); - if (broker != null) { - broker.stop(); - } - } + protected void tearDown() throws Exception { + super.tearDown(); + if (broker != null) { + broker.stop(); + } + } - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(bindAddress); - Properties props = new Properties(); - props.setProperty("prefetchPolicy.durableTopicPrefetch", "" + PREFETCH_SIZE); - props.setProperty("prefetchPolicy.optimizeDurableTopicPrefetch", "" + PREFETCH_SIZE); - props.setProperty("prefetchPolicy.queuePrefetch", "" + PREFETCH_SIZE); - cf.setProperties(props); - return cf; - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(bindAddress); + Properties props = new Properties(); + props.setProperty("prefetchPolicy.durableTopicPrefetch", "" + PREFETCH_SIZE); + props.setProperty("prefetchPolicy.optimizeDurableTopicPrefetch", "" + PREFETCH_SIZE); + props.setProperty("prefetchPolicy.queuePrefetch", "" + PREFETCH_SIZE); + cf.setProperties(props); + return cf; + } - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - configureBroker(answer); - answer.start(); - return answer; - } + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + configureBroker(answer); + answer.start(); + return answer; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/FilePendingMessageCursorTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/FilePendingMessageCursorTestSupport.java index 123263d95b..b512657f3a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/FilePendingMessageCursorTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/FilePendingMessageCursorTestSupport.java @@ -32,58 +32,60 @@ import static org.junit.Assert.fail; public class FilePendingMessageCursorTestSupport { - protected static final Logger LOG = LoggerFactory.getLogger(FilePendingMessageCursorTestSupport.class); - protected BrokerService brokerService; - protected FilePendingMessageCursor underTest; + protected static final Logger LOG = LoggerFactory.getLogger(FilePendingMessageCursorTestSupport.class); + protected BrokerService brokerService; + protected FilePendingMessageCursor underTest; - @After - public void stopBroker() throws Exception { - if (brokerService != null) { - brokerService.getTempDataStore().stop(); - } - } + @After + public void stopBroker() throws Exception { + if (brokerService != null) { + brokerService.getTempDataStore().stop(); + } + } - private void createBrokerWithTempStoreLimit() throws Exception { - brokerService = new BrokerService(); - brokerService.setUseJmx(false); - SystemUsage usage = brokerService.getSystemUsage(); - usage.getTempUsage().setLimit(1025*1024*15); + private void createBrokerWithTempStoreLimit() throws Exception { + brokerService = new BrokerService(); + brokerService.setUseJmx(false); + SystemUsage usage = brokerService.getSystemUsage(); + usage.getTempUsage().setLimit(1025 * 1024 * 15); - // put something in the temp store to on demand initialise it - PList dud = brokerService.getTempDataStore().getPList("dud"); - dud.addFirst("A", new ByteSequence("A".getBytes())); - } + // put something in the temp store to on demand initialise it + PList dud = brokerService.getTempDataStore().getPList("dud"); + dud.addFirst("A", new ByteSequence("A".getBytes())); + } - @Test - public void testAddToEmptyCursorWhenTempStoreIsFull() throws Exception { - createBrokerWithTempStoreLimit(); - SystemUsage usage = brokerService.getSystemUsage(); - assertTrue("temp store is full: %" + usage.getTempUsage().getPercentUsage(), usage.getTempUsage().isFull()); + @Test + public void testAddToEmptyCursorWhenTempStoreIsFull() throws Exception { + createBrokerWithTempStoreLimit(); + SystemUsage usage = brokerService.getSystemUsage(); + assertTrue("temp store is full: %" + usage.getTempUsage().getPercentUsage(), usage.getTempUsage().isFull()); - underTest = new FilePendingMessageCursor(brokerService.getBroker(), "test", false); - underTest.setSystemUsage(usage); + underTest = new FilePendingMessageCursor(brokerService.getBroker(), "test", false); + underTest.setSystemUsage(usage); - // ok to add - underTest.addMessageLast(QueueMessageReference.NULL_MESSAGE); + // ok to add + underTest.addMessageLast(QueueMessageReference.NULL_MESSAGE); - assertFalse("cursor is not full", underTest.isFull()); - } + assertFalse("cursor is not full", underTest.isFull()); + } - @Test - public void testResetClearsIterator() throws Exception { - createBrokerWithTempStoreLimit(); + @Test + public void testResetClearsIterator() throws Exception { + createBrokerWithTempStoreLimit(); - underTest = new FilePendingMessageCursor(brokerService.getBroker(), "test", false); - // ok to add - underTest.addMessageLast(QueueMessageReference.NULL_MESSAGE); + underTest = new FilePendingMessageCursor(brokerService.getBroker(), "test", false); + // ok to add + underTest.addMessageLast(QueueMessageReference.NULL_MESSAGE); - underTest.reset(); - underTest.release(); + underTest.reset(); + underTest.release(); - try { - underTest.hasNext(); - fail("expect npe on use of iterator after release"); - } catch (NullPointerException expected) {} - } + try { + underTest.hasNext(); + fail("expect npe on use of iterator after release"); + } + catch (NullPointerException expected) { + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/NegativeQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/NegativeQueueTest.java index 1401b35efb..a0b67acfb9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/NegativeQueueTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/NegativeQueueTest.java @@ -59,363 +59,374 @@ import org.slf4j.LoggerFactory; * Keys to reproducing: * 1) Consecutive queues with listener on first sending to second queue * 2) Push each queue to the memory limit - * This seems to help reproduce the issue more consistently, but - * we have seen times in our production environment where the - * negative queue can occur without. Our memory limits are - * very high in production and it still happens in varying - * frequency. + * This seems to help reproduce the issue more consistently, but + * we have seen times in our production environment where the + * negative queue can occur without. Our memory limits are + * very high in production and it still happens in varying + * frequency. * 3) Prefetch - * Lowering the prefetch down to 10 and below seems to help - * reduce occurrences. + * Lowering the prefetch down to 10 and below seems to help + * reduce occurrences. * 4) # of consumers per queue - * The issue occurs less with fewer consumers + * The issue occurs less with fewer consumers * * Things that do not affect reproduction: * 1) Spring - we use spring in our production applications, but this test case works - * with or without it. + * with or without it. * 2) transacted - * */ public class NegativeQueueTest extends AutoFailTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(NegativeQueueTest.class); - public static SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd,hh:mm:ss:SSS"); + private static final Logger LOG = LoggerFactory.getLogger(NegativeQueueTest.class); - private static final String QUEUE_1_NAME = "conn.test.queue.1"; - private static final String QUEUE_2_NAME = "conn.test.queue.2"; + public static SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd,hh:mm:ss:SSS"); - private static final long QUEUE_MEMORY_LIMIT = 2097152; - private static final long MEMORY_USAGE = 400000000; - private static final long TEMP_USAGE = 200000000; - private static final long STORE_USAGE = 1000000000; - // ensure we exceed the cache 70% - private static final int MESSAGE_COUNT = 2100; + private static final String QUEUE_1_NAME = "conn.test.queue.1"; + private static final String QUEUE_2_NAME = "conn.test.queue.2"; - protected static final boolean TRANSACTED = true; - protected static final boolean DEBUG = true; - protected static int NUM_CONSUMERS = 20; - protected static int PREFETCH_SIZE = 1000; + private static final long QUEUE_MEMORY_LIMIT = 2097152; + private static final long MEMORY_USAGE = 400000000; + private static final long TEMP_USAGE = 200000000; + private static final long STORE_USAGE = 1000000000; + // ensure we exceed the cache 70% + private static final int MESSAGE_COUNT = 2100; - protected BrokerService broker; - protected String bindAddress = "tcp://localhost:0"; + protected static final boolean TRANSACTED = true; + protected static final boolean DEBUG = true; + protected static int NUM_CONSUMERS = 20; + protected static int PREFETCH_SIZE = 1000; - public void testWithDefaultPrefetch() throws Exception{ - PREFETCH_SIZE = 1000; - NUM_CONSUMERS = 20; - blastAndConsume(); - } + protected BrokerService broker; + protected String bindAddress = "tcp://localhost:0"; - public void x_testWithDefaultPrefetchFiveConsumers() throws Exception{ - PREFETCH_SIZE = 1000; - NUM_CONSUMERS = 5; - blastAndConsume(); - } + public void testWithDefaultPrefetch() throws Exception { + PREFETCH_SIZE = 1000; + NUM_CONSUMERS = 20; + blastAndConsume(); + } - public void x_testWithDefaultPrefetchTwoConsumers() throws Exception{ - PREFETCH_SIZE = 1000; - NUM_CONSUMERS = 2; - blastAndConsume(); - } + public void x_testWithDefaultPrefetchFiveConsumers() throws Exception { + PREFETCH_SIZE = 1000; + NUM_CONSUMERS = 5; + blastAndConsume(); + } - public void testWithDefaultPrefetchOneConsumer() throws Exception{ - PREFETCH_SIZE = 1000; - NUM_CONSUMERS = 1; - blastAndConsume(); - } + public void x_testWithDefaultPrefetchTwoConsumers() throws Exception { + PREFETCH_SIZE = 1000; + NUM_CONSUMERS = 2; + blastAndConsume(); + } - public void testWithMediumPrefetch() throws Exception{ - PREFETCH_SIZE = 50; - NUM_CONSUMERS = 20; - blastAndConsume(); - } + public void testWithDefaultPrefetchOneConsumer() throws Exception { + PREFETCH_SIZE = 1000; + NUM_CONSUMERS = 1; + blastAndConsume(); + } - public void x_testWithSmallPrefetch() throws Exception{ - PREFETCH_SIZE = 10; - NUM_CONSUMERS = 20; - blastAndConsume(); - } + public void testWithMediumPrefetch() throws Exception { + PREFETCH_SIZE = 50; + NUM_CONSUMERS = 20; + blastAndConsume(); + } - public void testWithNoPrefetch() throws Exception{ - PREFETCH_SIZE = 1; - NUM_CONSUMERS = 20; - blastAndConsume(); - } + public void x_testWithSmallPrefetch() throws Exception { + PREFETCH_SIZE = 10; + NUM_CONSUMERS = 20; + blastAndConsume(); + } - public void blastAndConsume() throws Exception { - LOG.info(getName()); - ConnectionFactory factory = createConnectionFactory(); + public void testWithNoPrefetch() throws Exception { + PREFETCH_SIZE = 1; + NUM_CONSUMERS = 20; + blastAndConsume(); + } - //get proxy queues for statistics lookups - Connection proxyConnection = factory.createConnection(); - proxyConnection.start(); - Session proxySession = proxyConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final QueueViewMBean proxyQueue1 = getProxyToQueueViewMBean(proxySession.createQueue(QUEUE_1_NAME)); - final QueueViewMBean proxyQueue2 = getProxyToQueueViewMBean(proxySession.createQueue(QUEUE_2_NAME)); + public void blastAndConsume() throws Exception { + LOG.info(getName()); + ConnectionFactory factory = createConnectionFactory(); - // LOAD THE QUEUE - Connection producerConnection = factory.createConnection(); - producerConnection.start(); - Session session = producerConnection.createSession(TRANSACTED, Session.AUTO_ACKNOWLEDGE); - Destination queue = session.createQueue(QUEUE_1_NAME); - MessageProducer producer = session.createProducer(queue); - List senderList = new ArrayList(); - for (int i = 0; i < MESSAGE_COUNT; i++) { - TextMessage msg = session.createTextMessage(i + " " + formatter.format(new Date())); - senderList.add(msg); - producer.send(msg); - if(TRANSACTED) session.commit(); - if(DEBUG && i%100 == 0){ - int index = (i/100)+1; - System.out.print(index-((index/10)*10)); + //get proxy queues for statistics lookups + Connection proxyConnection = factory.createConnection(); + proxyConnection.start(); + Session proxySession = proxyConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final QueueViewMBean proxyQueue1 = getProxyToQueueViewMBean(proxySession.createQueue(QUEUE_1_NAME)); + final QueueViewMBean proxyQueue2 = getProxyToQueueViewMBean(proxySession.createQueue(QUEUE_2_NAME)); + + // LOAD THE QUEUE + Connection producerConnection = factory.createConnection(); + producerConnection.start(); + Session session = producerConnection.createSession(TRANSACTED, Session.AUTO_ACKNOWLEDGE); + Destination queue = session.createQueue(QUEUE_1_NAME); + MessageProducer producer = session.createProducer(queue); + List senderList = new ArrayList(); + for (int i = 0; i < MESSAGE_COUNT; i++) { + TextMessage msg = session.createTextMessage(i + " " + formatter.format(new Date())); + senderList.add(msg); + producer.send(msg); + if (TRANSACTED) + session.commit(); + if (DEBUG && i % 100 == 0) { + int index = (i / 100) + 1; + System.out.print(index - ((index / 10) * 10)); + } + } + + //get access to the Queue info + if (DEBUG) { + System.out.println(""); + System.out.println("Queue1 Size = " + proxyQueue1.getQueueSize()); + System.out.println("Queue1 Memory % Used = " + proxyQueue1.getMemoryPercentUsage()); + System.out.println("Queue1 Memory Available = " + proxyQueue1.getMemoryLimit()); + } + + // FLUSH THE QUEUE + final CountDownLatch latch1 = new CountDownLatch(1); + final CountDownLatch latch2 = new CountDownLatch(1); + Connection[] consumerConnections1 = new Connection[NUM_CONSUMERS]; + List consumerList1 = new ArrayList(); + Connection[] consumerConnections2 = new Connection[NUM_CONSUMERS]; + Connection[] producerConnections2 = new Connection[NUM_CONSUMERS]; + List consumerList2 = new ArrayList(); + + for (int ix = 0; ix < NUM_CONSUMERS; ix++) { + producerConnections2[ix] = factory.createConnection(); + producerConnections2[ix].start(); + consumerConnections1[ix] = getConsumerConnection(factory); + Session consumerSession = consumerConnections1[ix].createSession(TRANSACTED, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = consumerSession.createConsumer(session.createQueue(QUEUE_1_NAME)); + consumer.setMessageListener(new SessionAwareMessageListener(producerConnections2[ix], consumerSession, QUEUE_2_NAME, latch1, consumerList1)); + } + + latch1.await(200000, TimeUnit.MILLISECONDS); + if (DEBUG) { + System.out.println(""); + System.out.println("Queue2 Size = " + proxyQueue2.getQueueSize()); + System.out.println("Queue2 Memory % Used = " + proxyQueue2.getMemoryPercentUsage()); + System.out.println("Queue2 Memory Available = " + proxyQueue2.getMemoryLimit()); + } + + for (int ix = 0; ix < NUM_CONSUMERS; ix++) { + consumerConnections2[ix] = getConsumerConnection(factory); + Session consumerSession = consumerConnections2[ix].createSession(TRANSACTED, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = consumerSession.createConsumer(session.createQueue(QUEUE_2_NAME)); + consumer.setMessageListener(new SessionAwareMessageListener(consumerSession, latch2, consumerList2)); + } + + boolean success = Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + boolean done = latch2.await(10, TimeUnit.SECONDS); + if (DEBUG) { + System.out.println(""); + System.out.println("Queue1 Size = " + proxyQueue1.getQueueSize()); + System.out.println("Queue1 Memory % Used = " + proxyQueue1.getMemoryPercentUsage()); + System.out.println("Queue2 Size = " + proxyQueue2.getQueueSize()); + System.out.println("Queue2 Memory % Used = " + proxyQueue2.getMemoryPercentUsage()); + System.out.println("Queue2 Memory Available = " + proxyQueue2.getMemoryLimit()); } - } + return done; + } + }, 300 * 1000); + if (!success) { + dumpAllThreads("blocked waiting on 2"); + } + assertTrue("got all expected messages on 2", success); - //get access to the Queue info - if(DEBUG){ - System.out.println(""); - System.out.println("Queue1 Size = "+proxyQueue1.getQueueSize()); - System.out.println("Queue1 Memory % Used = "+proxyQueue1.getMemoryPercentUsage()); - System.out.println("Queue1 Memory Available = "+proxyQueue1.getMemoryLimit()); - } + producerConnection.close(); + for (int ix = 0; ix < NUM_CONSUMERS; ix++) { + consumerConnections1[ix].close(); + consumerConnections2[ix].close(); + producerConnections2[ix].close(); + } - // FLUSH THE QUEUE - final CountDownLatch latch1 = new CountDownLatch(1); - final CountDownLatch latch2 = new CountDownLatch(1); - Connection[] consumerConnections1 = new Connection[NUM_CONSUMERS]; - List consumerList1 = new ArrayList(); - Connection[] consumerConnections2 = new Connection[NUM_CONSUMERS]; - Connection[] producerConnections2 = new Connection[NUM_CONSUMERS]; - List consumerList2 = new ArrayList(); + //let the consumer statistics on queue2 have time to update + Thread.sleep(500); - for(int ix=0; ix consumerList; - private final CountDownLatch latch; - private final Session consumerSession; - private Session producerSession; - private MessageProducer producer; + /** + * Message listener that is given the Session for transacted consumers + */ + class SessionAwareMessageListener implements MessageListener { - public SessionAwareMessageListener(Session consumerSession, CountDownLatch latch, List consumerList){ - this(null, consumerSession, null, latch, consumerList); - } + private final List consumerList; + private final CountDownLatch latch; + private final Session consumerSession; + private Session producerSession; + private MessageProducer producer; - public SessionAwareMessageListener(Connection producerConnection, Session consumerSession, String outQueueName, - CountDownLatch latch, List consumerList){ - this.consumerList = consumerList; - this.latch = latch; - this.consumerSession = consumerSession; + public SessionAwareMessageListener(Session consumerSession, CountDownLatch latch, List consumerList) { + this(null, consumerSession, null, latch, consumerList); + } - if(producerConnection != null){ - try { - producerSession = producerConnection.createSession(TRANSACTED, Session.AUTO_ACKNOWLEDGE); - Destination queue = producerSession.createQueue(outQueueName); - producer = producerSession.createProducer(queue); - } catch (JMSException e) { - e.printStackTrace(); - } - } - } + public SessionAwareMessageListener(Connection producerConnection, + Session consumerSession, + String outQueueName, + CountDownLatch latch, + List consumerList) { + this.consumerList = consumerList; + this.latch = latch; + this.consumerSession = consumerSession; - @Override - public void onMessage(Message msg) { + if (producerConnection != null) { try { - if(producer == null){ - // sleep to act as a slow consumer - // which will force a mix of direct and polled dispatching - // using the cursor on the broker - Thread.sleep(50); - }else{ - producer.send(msg); - if(TRANSACTED) producerSession.commit(); - } - } catch (Exception e) { - e.printStackTrace(); + producerSession = producerConnection.createSession(TRANSACTED, Session.AUTO_ACKNOWLEDGE); + Destination queue = producerSession.createQueue(outQueueName); + producer = producerSession.createProducer(queue); } + catch (JMSException e) { + e.printStackTrace(); + } + } + } - synchronized(consumerList){ - consumerList.add(msg); - if(DEBUG && consumerList.size()%100 == 0) { - int index = consumerList.size()/100; - System.out.print(index-((index/10)*10)); - } - if (consumerList.size() == MESSAGE_COUNT) { - latch.countDown(); - } + @Override + public void onMessage(Message msg) { + try { + if (producer == null) { + // sleep to act as a slow consumer + // which will force a mix of direct and polled dispatching + // using the cursor on the broker + Thread.sleep(50); } - if(TRANSACTED){ - try { - consumerSession.commit(); - } catch (JMSException e) { - e.printStackTrace(); - } + else { + producer.send(msg); + if (TRANSACTED) + producerSession.commit(); } - } - } + } + catch (Exception e) { + e.printStackTrace(); + } + + synchronized (consumerList) { + consumerList.add(msg); + if (DEBUG && consumerList.size() % 100 == 0) { + int index = consumerList.size() / 100; + System.out.print(index - ((index / 10) * 10)); + } + if (consumerList.size() == MESSAGE_COUNT) { + latch.countDown(); + } + } + if (TRANSACTED) { + try { + consumerSession.commit(); + } + catch (JMSException e) { + e.printStackTrace(); + } + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/OrderPendingListTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/OrderPendingListTest.java index 79d7e6c36e..634f3822c3 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/OrderPendingListTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/OrderPendingListTest.java @@ -34,411 +34,412 @@ import org.junit.Test; public class OrderPendingListTest { - @Test - public void testAddMessageFirst() throws Exception { + @Test + public void testAddMessageFirst() throws Exception { - OrderedPendingList list = new OrderedPendingList(); + OrderedPendingList list = new OrderedPendingList(); - list.addMessageFirst(new TestMessageReference(1)); - list.addMessageFirst(new TestMessageReference(2)); - list.addMessageFirst(new TestMessageReference(3)); - list.addMessageFirst(new TestMessageReference(4)); - list.addMessageFirst(new TestMessageReference(5)); + list.addMessageFirst(new TestMessageReference(1)); + list.addMessageFirst(new TestMessageReference(2)); + list.addMessageFirst(new TestMessageReference(3)); + list.addMessageFirst(new TestMessageReference(4)); + list.addMessageFirst(new TestMessageReference(5)); - assertTrue(list.size() == 5); - assertEquals(5, list.getAsList().size()); + assertTrue(list.size() == 5); + assertEquals(5, list.getAsList().size()); - Iterator iter = list.iterator(); - int lastId = list.size(); - while (iter.hasNext()) { - assertEquals(lastId--, iter.next().getMessageId().getProducerSequenceId()); - } - } + Iterator iter = list.iterator(); + int lastId = list.size(); + while (iter.hasNext()) { + assertEquals(lastId--, iter.next().getMessageId().getProducerSequenceId()); + } + } - @Test - public void testAddMessageLast() throws Exception { + @Test + public void testAddMessageLast() throws Exception { - OrderedPendingList list = new OrderedPendingList(); + OrderedPendingList list = new OrderedPendingList(); - list.addMessageLast(new TestMessageReference(1)); - list.addMessageLast(new TestMessageReference(2)); - list.addMessageLast(new TestMessageReference(3)); - list.addMessageLast(new TestMessageReference(4)); - list.addMessageLast(new TestMessageReference(5)); + list.addMessageLast(new TestMessageReference(1)); + list.addMessageLast(new TestMessageReference(2)); + list.addMessageLast(new TestMessageReference(3)); + list.addMessageLast(new TestMessageReference(4)); + list.addMessageLast(new TestMessageReference(5)); - assertTrue(list.size() == 5); - assertEquals(5, list.getAsList().size()); + assertTrue(list.size() == 5); + assertEquals(5, list.getAsList().size()); - Iterator iter = list.iterator(); - int lastId = 1; - while (iter.hasNext()) { - assertEquals(lastId++, iter.next().getMessageId().getProducerSequenceId()); - } - } + Iterator iter = list.iterator(); + int lastId = 1; + while (iter.hasNext()) { + assertEquals(lastId++, iter.next().getMessageId().getProducerSequenceId()); + } + } - @Test - public void testClear() throws Exception { - OrderedPendingList list = new OrderedPendingList(); + @Test + public void testClear() throws Exception { + OrderedPendingList list = new OrderedPendingList(); - list.addMessageFirst(new TestMessageReference(1)); - list.addMessageFirst(new TestMessageReference(2)); - list.addMessageFirst(new TestMessageReference(3)); - list.addMessageFirst(new TestMessageReference(4)); - list.addMessageFirst(new TestMessageReference(5)); + list.addMessageFirst(new TestMessageReference(1)); + list.addMessageFirst(new TestMessageReference(2)); + list.addMessageFirst(new TestMessageReference(3)); + list.addMessageFirst(new TestMessageReference(4)); + list.addMessageFirst(new TestMessageReference(5)); - assertFalse(list.isEmpty()); - assertTrue(list.size() == 5); - assertEquals(5, list.getAsList().size()); + assertFalse(list.isEmpty()); + assertTrue(list.size() == 5); + assertEquals(5, list.getAsList().size()); - list.clear(); + list.clear(); - assertTrue(list.isEmpty()); - assertTrue(list.size() == 0); - assertEquals(0, list.getAsList().size()); + assertTrue(list.isEmpty()); + assertTrue(list.size() == 0); + assertEquals(0, list.getAsList().size()); - list.addMessageFirst(new TestMessageReference(1)); - list.addMessageLast(new TestMessageReference(2)); - list.addMessageLast(new TestMessageReference(3)); - list.addMessageFirst(new TestMessageReference(4)); - list.addMessageLast(new TestMessageReference(5)); + list.addMessageFirst(new TestMessageReference(1)); + list.addMessageLast(new TestMessageReference(2)); + list.addMessageLast(new TestMessageReference(3)); + list.addMessageFirst(new TestMessageReference(4)); + list.addMessageLast(new TestMessageReference(5)); - assertFalse(list.isEmpty()); - assertTrue(list.size() == 5); - assertEquals(5, list.getAsList().size()); - } + assertFalse(list.isEmpty()); + assertTrue(list.size() == 5); + assertEquals(5, list.getAsList().size()); + } - @Test - public void testIsEmpty() throws Exception { - OrderedPendingList list = new OrderedPendingList(); - assertTrue(list.isEmpty()); + @Test + public void testIsEmpty() throws Exception { + OrderedPendingList list = new OrderedPendingList(); + assertTrue(list.isEmpty()); - list.addMessageFirst(new TestMessageReference(1)); - list.addMessageFirst(new TestMessageReference(2)); - list.addMessageFirst(new TestMessageReference(3)); - list.addMessageFirst(new TestMessageReference(4)); - list.addMessageFirst(new TestMessageReference(5)); + list.addMessageFirst(new TestMessageReference(1)); + list.addMessageFirst(new TestMessageReference(2)); + list.addMessageFirst(new TestMessageReference(3)); + list.addMessageFirst(new TestMessageReference(4)); + list.addMessageFirst(new TestMessageReference(5)); - assertFalse(list.isEmpty()); - list.clear(); - assertTrue(list.isEmpty()); - } + assertFalse(list.isEmpty()); + list.clear(); + assertTrue(list.isEmpty()); + } - @Test - public void testSize() { - OrderedPendingList list = new OrderedPendingList(); - assertTrue(list.isEmpty()); + @Test + public void testSize() { + OrderedPendingList list = new OrderedPendingList(); + assertTrue(list.isEmpty()); - assertTrue(list.size() == 0); - list.addMessageFirst(new TestMessageReference(1)); - assertTrue(list.size() == 1); - list.addMessageLast(new TestMessageReference(2)); - assertTrue(list.size() == 2); - list.addMessageFirst(new TestMessageReference(3)); - assertTrue(list.size() == 3); - list.addMessageLast(new TestMessageReference(4)); - assertTrue(list.size() == 4); - list.addMessageFirst(new TestMessageReference(5)); - assertTrue(list.size() == 5); + assertTrue(list.size() == 0); + list.addMessageFirst(new TestMessageReference(1)); + assertTrue(list.size() == 1); + list.addMessageLast(new TestMessageReference(2)); + assertTrue(list.size() == 2); + list.addMessageFirst(new TestMessageReference(3)); + assertTrue(list.size() == 3); + list.addMessageLast(new TestMessageReference(4)); + assertTrue(list.size() == 4); + list.addMessageFirst(new TestMessageReference(5)); + assertTrue(list.size() == 5); - assertFalse(list.isEmpty()); - list.clear(); - assertTrue(list.isEmpty()); - assertTrue(list.size() == 0); - } + assertFalse(list.isEmpty()); + list.clear(); + assertTrue(list.isEmpty()); + assertTrue(list.size() == 0); + } - @Test - public void testRemove() throws Exception { + @Test + public void testRemove() throws Exception { - OrderedPendingList list = new OrderedPendingList(); + OrderedPendingList list = new OrderedPendingList(); - TestMessageReference toRemove = new TestMessageReference(6); + TestMessageReference toRemove = new TestMessageReference(6); - list.addMessageFirst(new TestMessageReference(1)); - list.addMessageFirst(new TestMessageReference(2)); - list.addMessageFirst(new TestMessageReference(3)); - list.addMessageFirst(new TestMessageReference(4)); - list.addMessageFirst(new TestMessageReference(5)); + list.addMessageFirst(new TestMessageReference(1)); + list.addMessageFirst(new TestMessageReference(2)); + list.addMessageFirst(new TestMessageReference(3)); + list.addMessageFirst(new TestMessageReference(4)); + list.addMessageFirst(new TestMessageReference(5)); - assertTrue(list.size() == 5); - assertEquals(5, list.getAsList().size()); + assertTrue(list.size() == 5); + assertEquals(5, list.getAsList().size()); - list.addMessageLast(toRemove); - list.remove(toRemove); + list.addMessageLast(toRemove); + list.remove(toRemove); - assertTrue(list.size() == 5); - assertEquals(5, list.getAsList().size()); + assertTrue(list.size() == 5); + assertEquals(5, list.getAsList().size()); - list.remove(toRemove); + list.remove(toRemove); - assertTrue(list.size() == 5); - assertEquals(5, list.getAsList().size()); + assertTrue(list.size() == 5); + assertEquals(5, list.getAsList().size()); - Iterator iter = list.iterator(); - int lastId = list.size(); - while (iter.hasNext()) { - assertEquals(lastId--, iter.next().getMessageId().getProducerSequenceId()); - } + Iterator iter = list.iterator(); + int lastId = list.size(); + while (iter.hasNext()) { + assertEquals(lastId--, iter.next().getMessageId().getProducerSequenceId()); + } - list.remove(null); - } + list.remove(null); + } - @Test - public void testContains() throws Exception { + @Test + public void testContains() throws Exception { - OrderedPendingList list = new OrderedPendingList(); + OrderedPendingList list = new OrderedPendingList(); - TestMessageReference toRemove = new TestMessageReference(6); + TestMessageReference toRemove = new TestMessageReference(6); - assertFalse(list.contains(toRemove)); - assertFalse(list.contains(null)); + assertFalse(list.contains(toRemove)); + assertFalse(list.contains(null)); - list.addMessageFirst(new TestMessageReference(1)); - list.addMessageFirst(new TestMessageReference(2)); - list.addMessageFirst(new TestMessageReference(3)); - list.addMessageFirst(new TestMessageReference(4)); - list.addMessageFirst(new TestMessageReference(5)); + list.addMessageFirst(new TestMessageReference(1)); + list.addMessageFirst(new TestMessageReference(2)); + list.addMessageFirst(new TestMessageReference(3)); + list.addMessageFirst(new TestMessageReference(4)); + list.addMessageFirst(new TestMessageReference(5)); - assertTrue(list.size() == 5); - assertEquals(5, list.getAsList().size()); + assertTrue(list.size() == 5); + assertEquals(5, list.getAsList().size()); - list.addMessageLast(toRemove); - assertTrue(list.size() == 6); - assertTrue(list.contains(toRemove)); - list.remove(toRemove); - assertFalse(list.contains(toRemove)); + list.addMessageLast(toRemove); + assertTrue(list.size() == 6); + assertTrue(list.contains(toRemove)); + list.remove(toRemove); + assertFalse(list.contains(toRemove)); - assertTrue(list.size() == 5); - assertEquals(5, list.getAsList().size()); - } + assertTrue(list.size() == 5); + assertEquals(5, list.getAsList().size()); + } - @Test - public void testValues() throws Exception { + @Test + public void testValues() throws Exception { - OrderedPendingList list = new OrderedPendingList(); + OrderedPendingList list = new OrderedPendingList(); - TestMessageReference toRemove = new TestMessageReference(6); + TestMessageReference toRemove = new TestMessageReference(6); - assertFalse(list.contains(toRemove)); + assertFalse(list.contains(toRemove)); - list.addMessageFirst(new TestMessageReference(1)); - list.addMessageFirst(new TestMessageReference(2)); - list.addMessageFirst(new TestMessageReference(3)); - list.addMessageFirst(new TestMessageReference(4)); - list.addMessageFirst(new TestMessageReference(5)); + list.addMessageFirst(new TestMessageReference(1)); + list.addMessageFirst(new TestMessageReference(2)); + list.addMessageFirst(new TestMessageReference(3)); + list.addMessageFirst(new TestMessageReference(4)); + list.addMessageFirst(new TestMessageReference(5)); - Collection values = list.values(); - assertEquals(5, values.size()); + Collection values = list.values(); + assertEquals(5, values.size()); - for (MessageReference msg : values) { - assertTrue(values.contains(msg)); - } + for (MessageReference msg : values) { + assertTrue(values.contains(msg)); + } - assertFalse(values.contains(toRemove)); + assertFalse(values.contains(toRemove)); - list.addMessageLast(toRemove); - values = list.values(); - assertEquals(6, values.size()); - for (MessageReference msg : values) { - assertTrue(values.contains(msg)); - } + list.addMessageLast(toRemove); + values = list.values(); + assertEquals(6, values.size()); + for (MessageReference msg : values) { + assertTrue(values.contains(msg)); + } - assertTrue(values.contains(toRemove)); - } + assertTrue(values.contains(toRemove)); + } - @Test - public void testAddAll() throws Exception { - OrderedPendingList list = new OrderedPendingList(); - TestPendingList source = new TestPendingList(); + @Test + public void testAddAll() throws Exception { + OrderedPendingList list = new OrderedPendingList(); + TestPendingList source = new TestPendingList(); - source.addMessageFirst(new TestMessageReference(1)); - source.addMessageFirst(new TestMessageReference(2)); - source.addMessageFirst(new TestMessageReference(3)); - source.addMessageFirst(new TestMessageReference(4)); - source.addMessageFirst(new TestMessageReference(5)); + source.addMessageFirst(new TestMessageReference(1)); + source.addMessageFirst(new TestMessageReference(2)); + source.addMessageFirst(new TestMessageReference(3)); + source.addMessageFirst(new TestMessageReference(4)); + source.addMessageFirst(new TestMessageReference(5)); - assertTrue(list.isEmpty()); - assertEquals(5, source.size()); - list.addAll(source); - assertEquals(5, list.size()); + assertTrue(list.isEmpty()); + assertEquals(5, source.size()); + list.addAll(source); + assertEquals(5, list.size()); - for (MessageReference message : source) { - assertTrue(list.contains(message)); - } + for (MessageReference message : source) { + assertTrue(list.contains(message)); + } - list.addAll(null); - } + list.addAll(null); + } - static class TestPendingList implements PendingList { + static class TestPendingList implements PendingList { - private final LinkedList theList = new LinkedList(); + private final LinkedList theList = new LinkedList(); - @Override - public boolean isEmpty() { - return theList.isEmpty(); - } + @Override + public boolean isEmpty() { + return theList.isEmpty(); + } - @Override - public void clear() { - theList.clear(); - } + @Override + public void clear() { + theList.clear(); + } - @Override - public PendingNode addMessageFirst(MessageReference message) { - theList.addFirst(message); + @Override + public PendingNode addMessageFirst(MessageReference message) { + theList.addFirst(message); + return new PendingNode(null, message); + } + + @Override + public PendingNode addMessageLast(MessageReference message) { + theList.addLast(message); + return new PendingNode(null, message); + } + + @Override + public PendingNode remove(MessageReference message) { + if (theList.remove(message)) { return new PendingNode(null, message); - } + } + else { + return null; + } + } - @Override - public PendingNode addMessageLast(MessageReference message) { - theList.addLast(message); - return new PendingNode(null, message); - } + @Override + public int size() { + return theList.size(); + } - @Override - public PendingNode remove(MessageReference message) { - if (theList.remove(message)) { - return new PendingNode(null, message); - } else { - return null; + @Override + public Iterator iterator() { + return theList.iterator(); + } + + @Override + public boolean contains(MessageReference message) { + return theList.contains(message); + } + + @Override + public Collection values() { + return theList; + } + + @Override + public void addAll(PendingList pendingList) { + for (MessageReference messageReference : pendingList) { + theList.add(messageReference); + } + } + + @Override + public MessageReference get(MessageId messageId) { + for (MessageReference messageReference : theList) { + if (messageReference.getMessageId().equals(messageId)) { + return messageReference; } - } + } + return null; + } + } - @Override - public int size() { - return theList.size(); - } + static class TestMessageReference implements MessageReference { - @Override - public Iterator iterator() { - return theList.iterator(); - } + private static final IdGenerator id = new IdGenerator(); - @Override - public boolean contains(MessageReference message) { - return theList.contains(message); - } + private MessageId messageId; + private int referenceCount = 0; - @Override - public Collection values() { - return theList; - } + public TestMessageReference(int sequenceId) { + messageId = new MessageId(id.generateId() + ":1", sequenceId); + } - @Override - public void addAll(PendingList pendingList) { - for(MessageReference messageReference : pendingList) { - theList.add(messageReference); - } - } + @Override + public MessageId getMessageId() { + return messageId; + } - @Override - public MessageReference get(MessageId messageId) { - for(MessageReference messageReference : theList) { - if (messageReference.getMessageId().equals(messageId)) { - return messageReference; - } - } - return null; - } - } + @Override + public Message getMessageHardRef() { + return null; + } - static class TestMessageReference implements MessageReference { + @Override + public Message getMessage() { + return null; + } - private static final IdGenerator id = new IdGenerator(); + @Override + public boolean isPersistent() { + return false; + } - private MessageId messageId; - private int referenceCount = 0; + @Override + public Destination getRegionDestination() { + return null; + } - public TestMessageReference(int sequenceId) { - messageId = new MessageId(id.generateId() + ":1", sequenceId); - } + @Override + public int getRedeliveryCounter() { + return 0; + } - @Override - public MessageId getMessageId() { - return messageId; - } + @Override + public void incrementRedeliveryCounter() { + } - @Override - public Message getMessageHardRef() { - return null; - } + @Override + public int getReferenceCount() { + return this.referenceCount; + } - @Override - public Message getMessage() { - return null; - } + @Override + public int incrementReferenceCount() { + return this.referenceCount++; + } - @Override - public boolean isPersistent() { - return false; - } + @Override + public int decrementReferenceCount() { + return this.referenceCount--; + } - @Override - public Destination getRegionDestination() { - return null; - } + @Override + public ConsumerId getTargetConsumerId() { + return null; + } - @Override - public int getRedeliveryCounter() { - return 0; - } + @Override + public int getSize() { + return 1; + } - @Override - public void incrementRedeliveryCounter() { - } + @Override + public long getExpiration() { + return 0; + } - @Override - public int getReferenceCount() { - return this.referenceCount; - } + @Override + public String getGroupID() { + return null; + } - @Override - public int incrementReferenceCount() { - return this.referenceCount++; - } + @Override + public int getGroupSequence() { + return 0; + } - @Override - public int decrementReferenceCount() { - return this.referenceCount--; - } + @Override + public boolean isExpired() { + return false; + } - @Override - public ConsumerId getTargetConsumerId() { - return null; - } + @Override + public boolean isDropped() { + return false; + } - @Override - public int getSize() { - return 1; - } - - @Override - public long getExpiration() { - return 0; - } - - @Override - public String getGroupID() { - return null; - } - - @Override - public int getGroupSequence() { - return 0; - } - - @Override - public boolean isExpired() { - return false; - } - - @Override - public boolean isDropped() { - return false; - } - - @Override - public boolean isAdvisory() { - return false; - } - } + @Override + public boolean isAdvisory() { + return false; + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/PrioritizedPendingListTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/PrioritizedPendingListTest.java index 6c40239b8a..e48f9db84b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/PrioritizedPendingListTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/PrioritizedPendingListTest.java @@ -34,270 +34,270 @@ import org.junit.Test; public class PrioritizedPendingListTest { - @Test - public void testAddMessageFirst() { - PrioritizedPendingList list = new PrioritizedPendingList(); + @Test + public void testAddMessageFirst() { + PrioritizedPendingList list = new PrioritizedPendingList(); - list.addMessageFirst(new TestMessageReference(1)); - list.addMessageFirst(new TestMessageReference(2)); - list.addMessageFirst(new TestMessageReference(3)); - list.addMessageFirst(new TestMessageReference(4)); - list.addMessageFirst(new TestMessageReference(5)); + list.addMessageFirst(new TestMessageReference(1)); + list.addMessageFirst(new TestMessageReference(2)); + list.addMessageFirst(new TestMessageReference(3)); + list.addMessageFirst(new TestMessageReference(4)); + list.addMessageFirst(new TestMessageReference(5)); - assertTrue(list.size() == 5); + assertTrue(list.size() == 5); - Iterator iter = list.iterator(); - int lastId = list.size(); - while (iter.hasNext()) { - assertEquals(lastId--, iter.next().getMessageId().getProducerSequenceId()); - } - } + Iterator iter = list.iterator(); + int lastId = list.size(); + while (iter.hasNext()) { + assertEquals(lastId--, iter.next().getMessageId().getProducerSequenceId()); + } + } - @Test - public void testAddMessageLast() { + @Test + public void testAddMessageLast() { - PrioritizedPendingList list = new PrioritizedPendingList(); + PrioritizedPendingList list = new PrioritizedPendingList(); - list.addMessageLast(new TestMessageReference(1)); - list.addMessageLast(new TestMessageReference(2)); - list.addMessageLast(new TestMessageReference(3)); - list.addMessageLast(new TestMessageReference(4)); - list.addMessageLast(new TestMessageReference(5)); + list.addMessageLast(new TestMessageReference(1)); + list.addMessageLast(new TestMessageReference(2)); + list.addMessageLast(new TestMessageReference(3)); + list.addMessageLast(new TestMessageReference(4)); + list.addMessageLast(new TestMessageReference(5)); - assertTrue(list.size() == 5); + assertTrue(list.size() == 5); - Iterator iter = list.iterator(); - int lastId = 1; - while (iter.hasNext()) { - assertEquals(lastId++, iter.next().getMessageId().getProducerSequenceId()); - } - } + Iterator iter = list.iterator(); + int lastId = 1; + while (iter.hasNext()) { + assertEquals(lastId++, iter.next().getMessageId().getProducerSequenceId()); + } + } - @Test - public void testClear() { - PrioritizedPendingList list = new PrioritizedPendingList(); + @Test + public void testClear() { + PrioritizedPendingList list = new PrioritizedPendingList(); - list.addMessageFirst(new TestMessageReference(1)); - list.addMessageFirst(new TestMessageReference(2)); - list.addMessageFirst(new TestMessageReference(3)); - list.addMessageFirst(new TestMessageReference(4)); - list.addMessageFirst(new TestMessageReference(5)); + list.addMessageFirst(new TestMessageReference(1)); + list.addMessageFirst(new TestMessageReference(2)); + list.addMessageFirst(new TestMessageReference(3)); + list.addMessageFirst(new TestMessageReference(4)); + list.addMessageFirst(new TestMessageReference(5)); - assertFalse(list.isEmpty()); - assertTrue(list.size() == 5); + assertFalse(list.isEmpty()); + assertTrue(list.size() == 5); - list.clear(); + list.clear(); - assertTrue(list.isEmpty()); - assertTrue(list.size() == 0); + assertTrue(list.isEmpty()); + assertTrue(list.size() == 0); - list.addMessageFirst(new TestMessageReference(1)); - list.addMessageLast(new TestMessageReference(2)); - list.addMessageLast(new TestMessageReference(3)); - list.addMessageFirst(new TestMessageReference(4)); - list.addMessageLast(new TestMessageReference(5)); + list.addMessageFirst(new TestMessageReference(1)); + list.addMessageLast(new TestMessageReference(2)); + list.addMessageLast(new TestMessageReference(3)); + list.addMessageFirst(new TestMessageReference(4)); + list.addMessageLast(new TestMessageReference(5)); - assertFalse(list.isEmpty()); - assertTrue(list.size() == 5); - } + assertFalse(list.isEmpty()); + assertTrue(list.size() == 5); + } - @Test - public void testIsEmpty() { - PrioritizedPendingList list = new PrioritizedPendingList(); - assertTrue(list.isEmpty()); + @Test + public void testIsEmpty() { + PrioritizedPendingList list = new PrioritizedPendingList(); + assertTrue(list.isEmpty()); - list.addMessageFirst(new TestMessageReference(1)); - list.addMessageFirst(new TestMessageReference(2)); - list.addMessageFirst(new TestMessageReference(3)); - list.addMessageFirst(new TestMessageReference(4)); - list.addMessageFirst(new TestMessageReference(5)); + list.addMessageFirst(new TestMessageReference(1)); + list.addMessageFirst(new TestMessageReference(2)); + list.addMessageFirst(new TestMessageReference(3)); + list.addMessageFirst(new TestMessageReference(4)); + list.addMessageFirst(new TestMessageReference(5)); - assertFalse(list.isEmpty()); - list.clear(); - assertTrue(list.isEmpty()); - } + assertFalse(list.isEmpty()); + list.clear(); + assertTrue(list.isEmpty()); + } - @Test - public void testRemove() { - PrioritizedPendingList list = new PrioritizedPendingList(); + @Test + public void testRemove() { + PrioritizedPendingList list = new PrioritizedPendingList(); - TestMessageReference toRemove = new TestMessageReference(6); + TestMessageReference toRemove = new TestMessageReference(6); - list.addMessageFirst(new TestMessageReference(1)); - list.addMessageFirst(new TestMessageReference(2)); - list.addMessageFirst(new TestMessageReference(3)); - list.addMessageFirst(new TestMessageReference(4)); - list.addMessageFirst(new TestMessageReference(5)); + list.addMessageFirst(new TestMessageReference(1)); + list.addMessageFirst(new TestMessageReference(2)); + list.addMessageFirst(new TestMessageReference(3)); + list.addMessageFirst(new TestMessageReference(4)); + list.addMessageFirst(new TestMessageReference(5)); - assertTrue(list.size() == 5); + assertTrue(list.size() == 5); - list.addMessageLast(toRemove); - list.remove(toRemove); + list.addMessageLast(toRemove); + list.remove(toRemove); - assertTrue(list.size() == 5); + assertTrue(list.size() == 5); - list.remove(toRemove); + list.remove(toRemove); - assertTrue(list.size() == 5); + assertTrue(list.size() == 5); - Iterator iter = list.iterator(); - int lastId = list.size(); - while (iter.hasNext()) { - assertEquals(lastId--, iter.next().getMessageId().getProducerSequenceId()); - } + Iterator iter = list.iterator(); + int lastId = list.size(); + while (iter.hasNext()) { + assertEquals(lastId--, iter.next().getMessageId().getProducerSequenceId()); + } - list.remove(null); - } + list.remove(null); + } - @Test - public void testSize() { - PrioritizedPendingList list = new PrioritizedPendingList(); - assertTrue(list.isEmpty()); + @Test + public void testSize() { + PrioritizedPendingList list = new PrioritizedPendingList(); + assertTrue(list.isEmpty()); - assertTrue(list.size() == 0); - list.addMessageFirst(new TestMessageReference(1)); - assertTrue(list.size() == 1); - list.addMessageLast(new TestMessageReference(2)); - assertTrue(list.size() == 2); - list.addMessageFirst(new TestMessageReference(3)); - assertTrue(list.size() == 3); - list.addMessageLast(new TestMessageReference(4)); - assertTrue(list.size() == 4); - list.addMessageFirst(new TestMessageReference(5)); - assertTrue(list.size() == 5); + assertTrue(list.size() == 0); + list.addMessageFirst(new TestMessageReference(1)); + assertTrue(list.size() == 1); + list.addMessageLast(new TestMessageReference(2)); + assertTrue(list.size() == 2); + list.addMessageFirst(new TestMessageReference(3)); + assertTrue(list.size() == 3); + list.addMessageLast(new TestMessageReference(4)); + assertTrue(list.size() == 4); + list.addMessageFirst(new TestMessageReference(5)); + assertTrue(list.size() == 5); - assertFalse(list.isEmpty()); - list.clear(); - assertTrue(list.isEmpty()); - assertTrue(list.size() == 0); - } + assertFalse(list.isEmpty()); + list.clear(); + assertTrue(list.isEmpty()); + assertTrue(list.size() == 0); + } - @Test - public void testPrioritization() { - PrioritizedPendingList list = new PrioritizedPendingList(); + @Test + public void testPrioritization() { + PrioritizedPendingList list = new PrioritizedPendingList(); - list.addMessageFirst(new TestMessageReference(1, 5)); - list.addMessageFirst(new TestMessageReference(2, 4)); - list.addMessageFirst(new TestMessageReference(3, 3)); - list.addMessageFirst(new TestMessageReference(4, 2)); - list.addMessageFirst(new TestMessageReference(5, 1)); + list.addMessageFirst(new TestMessageReference(1, 5)); + list.addMessageFirst(new TestMessageReference(2, 4)); + list.addMessageFirst(new TestMessageReference(3, 3)); + list.addMessageFirst(new TestMessageReference(4, 2)); + list.addMessageFirst(new TestMessageReference(5, 1)); - assertTrue(list.size() == 5); + assertTrue(list.size() == 5); - Iterator iter = list.iterator(); - int lastId = list.size(); - while (iter.hasNext()) { - assertEquals(lastId--, iter.next().getMessage().getPriority()); - } - } + Iterator iter = list.iterator(); + int lastId = list.size(); + while (iter.hasNext()) { + assertEquals(lastId--, iter.next().getMessage().getPriority()); + } + } - static class TestMessageReference implements MessageReference { + static class TestMessageReference implements MessageReference { - private static final IdGenerator id = new IdGenerator(); + private static final IdGenerator id = new IdGenerator(); - private Message message; - private MessageId messageId; - private int referenceCount = 0; + private Message message; + private MessageId messageId; + private int referenceCount = 0; - public TestMessageReference(int sequenceId) { - messageId = new MessageId(id.generateId() + ":1", sequenceId); - message = new ActiveMQMessage(); - message.setPriority((byte) javax.jms.Message.DEFAULT_PRIORITY); - } + public TestMessageReference(int sequenceId) { + messageId = new MessageId(id.generateId() + ":1", sequenceId); + message = new ActiveMQMessage(); + message.setPriority((byte) javax.jms.Message.DEFAULT_PRIORITY); + } - public TestMessageReference(int sequenceId, int priority) { - messageId = new MessageId(id.generateId() + ":1", sequenceId); - message = new ActiveMQMessage(); - message.setPriority((byte) priority); - } + public TestMessageReference(int sequenceId, int priority) { + messageId = new MessageId(id.generateId() + ":1", sequenceId); + message = new ActiveMQMessage(); + message.setPriority((byte) priority); + } - @Override - public MessageId getMessageId() { - return messageId; - } + @Override + public MessageId getMessageId() { + return messageId; + } - @Override - public Message getMessageHardRef() { - return null; - } + @Override + public Message getMessageHardRef() { + return null; + } - @Override - public Message getMessage() { - return message; - } + @Override + public Message getMessage() { + return message; + } - @Override - public boolean isPersistent() { - return false; - } + @Override + public boolean isPersistent() { + return false; + } - @Override - public Destination getRegionDestination() { - return null; - } + @Override + public Destination getRegionDestination() { + return null; + } - @Override - public int getRedeliveryCounter() { - return 0; - } + @Override + public int getRedeliveryCounter() { + return 0; + } - @Override - public void incrementRedeliveryCounter() { - } + @Override + public void incrementRedeliveryCounter() { + } - @Override - public int getReferenceCount() { - return this.referenceCount; - } + @Override + public int getReferenceCount() { + return this.referenceCount; + } - @Override - public int incrementReferenceCount() { - return this.referenceCount++; - } + @Override + public int incrementReferenceCount() { + return this.referenceCount++; + } - @Override - public int decrementReferenceCount() { - return this.referenceCount--; - } + @Override + public int decrementReferenceCount() { + return this.referenceCount--; + } - @Override - public ConsumerId getTargetConsumerId() { - return null; - } + @Override + public ConsumerId getTargetConsumerId() { + return null; + } - @Override - public int getSize() { - return 1; - } + @Override + public int getSize() { + return 1; + } - @Override - public long getExpiration() { - return 0; - } + @Override + public long getExpiration() { + return 0; + } - @Override - public String getGroupID() { - return null; - } + @Override + public String getGroupID() { + return null; + } - @Override - public int getGroupSequence() { - return 0; - } + @Override + public int getGroupSequence() { + return 0; + } - @Override - public boolean isExpired() { - return false; - } + @Override + public boolean isExpired() { + return false; + } - @Override - public boolean isDropped() { - return false; - } + @Override + public boolean isDropped() { + return false; + } - @Override - public boolean isAdvisory() { - return false; - } - } + @Override + public boolean isAdvisory() { + return false; + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreBasedCursorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreBasedCursorTest.java index a330723060..c3a6a2fe53 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreBasedCursorTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreBasedCursorTest.java @@ -39,122 +39,124 @@ import org.apache.activemq.broker.region.policy.PolicyMap; import org.apache.activemq.usage.SystemUsage; public class StoreBasedCursorTest extends TestCase { - protected String bindAddress = "tcp://localhost:60706"; - BrokerService broker; - ActiveMQConnectionFactory factory; - Connection connection; - Session session; - Queue queue; - int messageSize = 1024; - // actual message is messageSize*2, and 4*MessageSize would allow 2 messages be delivered, but the flush of the cache is async so the flush - // triggered on 2nd message maxing out the usage may not be in effect for the 3rd message to succeed. Making the memory usage more lenient - // gives the usageChange listener in the cursor an opportunity to kick in. - int memoryLimit = 12 * messageSize; - - protected void setUp() throws Exception { - super.setUp(); - if (broker == null) { - broker = new BrokerService(); - broker.setAdvisorySupport(false); - } - } - protected void tearDown() throws Exception { - super.tearDown(); - if (broker != null) { - broker.stop(); - broker = null; - } - } - - protected void start() throws Exception { - broker.start(); - factory = new ActiveMQConnectionFactory("vm://localhost?jms.alwaysSyncSend=true"); - factory.setWatchTopicAdvisories(false); - connection = factory.createConnection(); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - queue = session.createQueue("QUEUE." + this.getClass().getName()); - } - - protected void stop() throws Exception { - session.close(); - connection.close(); - broker.stop(); - broker = null; - } - - protected void configureBroker(long memoryLimit, long systemLimit) throws Exception { - broker.setDeleteAllMessagesOnStartup(true); - broker.addConnector(bindAddress); - broker.setPersistent(true); - - SystemUsage systemUsage = broker.getSystemUsage(); - systemUsage.setSendFailIfNoSpace(true); - systemUsage.getMemoryUsage().setLimit(systemLimit); - - PolicyEntry policy = new PolicyEntry(); - policy.setProducerFlowControl(true); - policy.setUseCache(true); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - broker.setDestinationPolicy(pMap); - } - - protected String createMessageText(int index) { - StringBuffer buffer = new StringBuffer(messageSize); - buffer.append("Message: " + index + " sent at: " + new Date()); - if (buffer.length() > messageSize) { - return buffer.substring(0, messageSize); - } - for (int i = buffer.length(); i < messageSize; i++) { - buffer.append(' '); - } - return buffer.toString(); - } - - protected void sendMessages(int deliveryMode) throws Exception { - start(); - MessageProducer producer = session.createProducer(queue); - producer.setDeliveryMode(deliveryMode); - int i =0; - try { - for (i = 0; i < 200; i++) { - TextMessage message = session.createTextMessage(createMessageText(i)); - producer.send(message); - } - } catch (javax.jms.ResourceAllocationException e) { - e.printStackTrace(); - fail(e.getMessage() + " num msgs = " + i + ". percentUsage = " + broker.getSystemUsage().getMemoryUsage().getPercentUsage()); - } - stop(); - } - - // use QueueStorePrefetch - public void testTwoUsageEqualPersistent() throws Exception { - configureBroker(memoryLimit, memoryLimit); - sendMessages(DeliveryMode.PERSISTENT); - } - - public void testUseCachePersistent() throws Exception { - int limit = memoryLimit / 2; - configureBroker(limit, memoryLimit); - sendMessages(DeliveryMode.PERSISTENT); - } - - public void testMemoryUsageLowPersistent() throws Exception { - configureBroker(memoryLimit, 10 * memoryLimit); - sendMessages(DeliveryMode.PERSISTENT); - } - - // use FilePendingMessageCursor - public void testTwoUsageEqualNonPersistent() throws Exception { - configureBroker(memoryLimit, memoryLimit); - sendMessages(DeliveryMode.NON_PERSISTENT); - } - - public void testMemoryUsageLowNonPersistent() throws Exception { - configureBroker(memoryLimit, 10 * memoryLimit); - sendMessages(DeliveryMode.NON_PERSISTENT); - } + protected String bindAddress = "tcp://localhost:60706"; + BrokerService broker; + ActiveMQConnectionFactory factory; + Connection connection; + Session session; + Queue queue; + int messageSize = 1024; + // actual message is messageSize*2, and 4*MessageSize would allow 2 messages be delivered, but the flush of the cache is async so the flush + // triggered on 2nd message maxing out the usage may not be in effect for the 3rd message to succeed. Making the memory usage more lenient + // gives the usageChange listener in the cursor an opportunity to kick in. + int memoryLimit = 12 * messageSize; + + protected void setUp() throws Exception { + super.setUp(); + if (broker == null) { + broker = new BrokerService(); + broker.setAdvisorySupport(false); + } + } + + protected void tearDown() throws Exception { + super.tearDown(); + if (broker != null) { + broker.stop(); + broker = null; + } + } + + protected void start() throws Exception { + broker.start(); + factory = new ActiveMQConnectionFactory("vm://localhost?jms.alwaysSyncSend=true"); + factory.setWatchTopicAdvisories(false); + connection = factory.createConnection(); + connection.start(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + queue = session.createQueue("QUEUE." + this.getClass().getName()); + } + + protected void stop() throws Exception { + session.close(); + connection.close(); + broker.stop(); + broker = null; + } + + protected void configureBroker(long memoryLimit, long systemLimit) throws Exception { + broker.setDeleteAllMessagesOnStartup(true); + broker.addConnector(bindAddress); + broker.setPersistent(true); + + SystemUsage systemUsage = broker.getSystemUsage(); + systemUsage.setSendFailIfNoSpace(true); + systemUsage.getMemoryUsage().setLimit(systemLimit); + + PolicyEntry policy = new PolicyEntry(); + policy.setProducerFlowControl(true); + policy.setUseCache(true); + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); + broker.setDestinationPolicy(pMap); + } + + protected String createMessageText(int index) { + StringBuffer buffer = new StringBuffer(messageSize); + buffer.append("Message: " + index + " sent at: " + new Date()); + if (buffer.length() > messageSize) { + return buffer.substring(0, messageSize); + } + for (int i = buffer.length(); i < messageSize; i++) { + buffer.append(' '); + } + return buffer.toString(); + } + + protected void sendMessages(int deliveryMode) throws Exception { + start(); + MessageProducer producer = session.createProducer(queue); + producer.setDeliveryMode(deliveryMode); + int i = 0; + try { + for (i = 0; i < 200; i++) { + TextMessage message = session.createTextMessage(createMessageText(i)); + producer.send(message); + } + } + catch (javax.jms.ResourceAllocationException e) { + e.printStackTrace(); + fail(e.getMessage() + " num msgs = " + i + ". percentUsage = " + broker.getSystemUsage().getMemoryUsage().getPercentUsage()); + } + stop(); + } + + // use QueueStorePrefetch + public void testTwoUsageEqualPersistent() throws Exception { + configureBroker(memoryLimit, memoryLimit); + sendMessages(DeliveryMode.PERSISTENT); + } + + public void testUseCachePersistent() throws Exception { + int limit = memoryLimit / 2; + configureBroker(limit, memoryLimit); + sendMessages(DeliveryMode.PERSISTENT); + } + + public void testMemoryUsageLowPersistent() throws Exception { + configureBroker(memoryLimit, 10 * memoryLimit); + sendMessages(DeliveryMode.PERSISTENT); + } + + // use FilePendingMessageCursor + public void testTwoUsageEqualNonPersistent() throws Exception { + configureBroker(memoryLimit, memoryLimit); + sendMessages(DeliveryMode.NON_PERSISTENT); + } + + public void testMemoryUsageLowNonPersistent() throws Exception { + configureBroker(memoryLimit, 10 * memoryLimit); + sendMessages(DeliveryMode.NON_PERSISTENT); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorJDBCNoDuplicateTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorJDBCNoDuplicateTest.java index 6b49c8d546..68a2b51614 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorJDBCNoDuplicateTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorJDBCNoDuplicateTest.java @@ -24,14 +24,14 @@ import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter; /** * @author gtully * @see https://issues.apache.org/activemq/browse/AMQ-2020 - **/ + */ public class StoreQueueCursorJDBCNoDuplicateTest extends StoreQueueCursorNoDuplicateTest { - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - PersistenceAdapter persistenceAdapter = new JDBCPersistenceAdapter(); - broker.setPersistenceAdapter(persistenceAdapter); - return broker; - } + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); + PersistenceAdapter persistenceAdapter = new JDBCPersistenceAdapter(); + broker.setPersistenceAdapter(persistenceAdapter); + return broker; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorKahaDBNoDuplicateTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorKahaDBNoDuplicateTest.java index 11a98d694d..265e96557d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorKahaDBNoDuplicateTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorKahaDBNoDuplicateTest.java @@ -26,15 +26,15 @@ import org.apache.activemq.store.kahadb.KahaDBStore; /** * @author gtully * @see https://issues.apache.org/activemq/browse/AMQ-2020 - **/ + */ public class StoreQueueCursorKahaDBNoDuplicateTest extends StoreQueueCursorNoDuplicateTest { - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - PersistenceAdapter persistenceAdapter = new KahaDBStore(); - persistenceAdapter.setDirectory(new File("target/activemq-data/kahadb")); - broker.setPersistenceAdapter(persistenceAdapter); - return broker; - } + @Override + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); + PersistenceAdapter persistenceAdapter = new KahaDBStore(); + persistenceAdapter.setDirectory(new File("target/activemq-data/kahadb")); + broker.setPersistenceAdapter(persistenceAdapter); + return broker; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorLevelDBNoDuplicateTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorLevelDBNoDuplicateTest.java index d119d506ed..9ed7b1b690 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorLevelDBNoDuplicateTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorLevelDBNoDuplicateTest.java @@ -27,14 +27,15 @@ import java.io.File; /** * @author gtully * @see https://issues.apache.org/activemq/browse/AMQ-2020 - **/ + */ public class StoreQueueCursorLevelDBNoDuplicateTest extends StoreQueueCursorNoDuplicateTest { - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - LevelDBStore store = new LevelDBStore(); - store.setDirectory(new File("target/activemq-data/leveldb")); - broker.setPersistenceAdapter(store); - return broker; - } + + @Override + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); + LevelDBStore store = new LevelDBStore(); + store.setDirectory(new File("target/activemq-data/leveldb")); + broker.setPersistenceAdapter(store); + return broker; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorMemoryNoDuplicateTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorMemoryNoDuplicateTest.java index a62748a86b..616b374ca6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorMemoryNoDuplicateTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorMemoryNoDuplicateTest.java @@ -22,12 +22,12 @@ import org.apache.activemq.broker.BrokerService; /** * @author gtully * @see https://issues.apache.org/activemq/browse/AMQ-2020 - **/ + */ public class StoreQueueCursorMemoryNoDuplicateTest extends StoreQueueCursorNoDuplicateTest { - - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - broker.setPersistent(false); - return broker; - } + + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); + broker.setPersistent(false); + return broker; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorNoDuplicateTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorNoDuplicateTest.java index 2406e88b94..abfb005fe4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorNoDuplicateTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorNoDuplicateTest.java @@ -36,98 +36,94 @@ import org.slf4j.LoggerFactory; /** * @author gtully - * https://issues.apache.org/activemq/browse/AMQ-2020 - **/ + * https://issues.apache.org/activemq/browse/AMQ-2020 + */ public class StoreQueueCursorNoDuplicateTest extends TestCase { - static final Logger LOG = LoggerFactory.getLogger(StoreQueueCursorNoDuplicateTest.class); - ActiveMQQueue destination = new ActiveMQQueue("queue-" - + StoreQueueCursorNoDuplicateTest.class.getSimpleName()); - BrokerService brokerService; - final static String mesageIdRoot = "11111:22222:0:"; - final int messageBytesSize = 1024; - final String text = new String(new byte[messageBytesSize]); + static final Logger LOG = LoggerFactory.getLogger(StoreQueueCursorNoDuplicateTest.class); + ActiveMQQueue destination = new ActiveMQQueue("queue-" + StoreQueueCursorNoDuplicateTest.class.getSimpleName()); + BrokerService brokerService; - protected int count = 6; + final static String mesageIdRoot = "11111:22222:0:"; + final int messageBytesSize = 1024; + final String text = new String(new byte[messageBytesSize]); - @Override - public void setUp() throws Exception { - brokerService = createBroker(); - brokerService.setUseJmx(false); - brokerService.deleteAllMessages(); - brokerService.start(); - } + protected int count = 6; - protected BrokerService createBroker() throws Exception { - return new BrokerService(); - } + @Override + public void setUp() throws Exception { + brokerService = createBroker(); + brokerService.setUseJmx(false); + brokerService.deleteAllMessages(); + brokerService.start(); + } - @Override - public void tearDown() throws Exception { - brokerService.stop(); - } + protected BrokerService createBroker() throws Exception { + return new BrokerService(); + } - public void testNoDuplicateAfterCacheFullAndReadPast() throws Exception { - final PersistenceAdapter persistenceAdapter = brokerService - .getPersistenceAdapter(); - final MessageStore queueMessageStore = persistenceAdapter - .createQueueMessageStore(destination); - final ConsumerInfo consumerInfo = new ConsumerInfo(); - final DestinationStatistics destinationStatistics = new DestinationStatistics(); - consumerInfo.setExclusive(true); + @Override + public void tearDown() throws Exception { + brokerService.stop(); + } - final Queue queue = new Queue(brokerService, destination, - queueMessageStore, destinationStatistics, null); + public void testNoDuplicateAfterCacheFullAndReadPast() throws Exception { + final PersistenceAdapter persistenceAdapter = brokerService.getPersistenceAdapter(); + final MessageStore queueMessageStore = persistenceAdapter.createQueueMessageStore(destination); + final ConsumerInfo consumerInfo = new ConsumerInfo(); + final DestinationStatistics destinationStatistics = new DestinationStatistics(); + consumerInfo.setExclusive(true); - queueMessageStore.start(); - queueMessageStore.registerIndexListener(null); + final Queue queue = new Queue(brokerService, destination, queueMessageStore, destinationStatistics, null); - QueueStorePrefetch underTest = new QueueStorePrefetch(queue, brokerService.getBroker()); - SystemUsage systemUsage = new SystemUsage(); - // ensure memory limit is reached - systemUsage.getMemoryUsage().setLimit(messageBytesSize * (count + 2)); - underTest.setSystemUsage(systemUsage); - underTest.setEnableAudit(false); - underTest.start(); - assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); + queueMessageStore.start(); + queueMessageStore.registerIndexListener(null); - final ConnectionContext contextNotInTx = new ConnectionContext(); - for (int i = 0; i < count; i++) { - ActiveMQTextMessage msg = getMessage(i); - msg.setMemoryUsage(systemUsage.getMemoryUsage()); + QueueStorePrefetch underTest = new QueueStorePrefetch(queue, brokerService.getBroker()); + SystemUsage systemUsage = new SystemUsage(); + // ensure memory limit is reached + systemUsage.getMemoryUsage().setLimit(messageBytesSize * (count + 2)); + underTest.setSystemUsage(systemUsage); + underTest.setEnableAudit(false); + underTest.start(); + assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); - queueMessageStore.addMessage(contextNotInTx, msg); - underTest.addMessageLast(msg); - } + final ConnectionContext contextNotInTx = new ConnectionContext(); + for (int i = 0; i < count; i++) { + ActiveMQTextMessage msg = getMessage(i); + msg.setMemoryUsage(systemUsage.getMemoryUsage()); - assertTrue("cache is disabled as limit reached", !underTest.isCacheEnabled()); - int dequeueCount = 0; + queueMessageStore.addMessage(contextNotInTx, msg); + underTest.addMessageLast(msg); + } - underTest.setMaxBatchSize(2); - underTest.reset(); - while (underTest.hasNext() && dequeueCount < count) { - MessageReference ref = underTest.next(); - ref.decrementReferenceCount(); - underTest.remove(); - LOG.info("Received message: {} with body: {}", - ref.getMessageId(), ((ActiveMQTextMessage)ref.getMessage()).getText()); - assertEquals(dequeueCount++, ref.getMessageId().getProducerSequenceId()); - } - underTest.release(); - assertEquals(count, dequeueCount); - } + assertTrue("cache is disabled as limit reached", !underTest.isCacheEnabled()); + int dequeueCount = 0; - private ActiveMQTextMessage getMessage(int i) throws Exception { - ActiveMQTextMessage message = new ActiveMQTextMessage(); - MessageId id = new MessageId(mesageIdRoot + i); - id.setBrokerSequenceId(i); - id.setProducerSequenceId(i); - message.setMessageId(id); - message.setDestination(destination); - message.setPersistent(true); - message.setResponseRequired(true); - message.setText("Msg:" + i + " " + text); - assertEquals(message.getMessageId().getProducerSequenceId(), i); - return message; - } + underTest.setMaxBatchSize(2); + underTest.reset(); + while (underTest.hasNext() && dequeueCount < count) { + MessageReference ref = underTest.next(); + ref.decrementReferenceCount(); + underTest.remove(); + LOG.info("Received message: {} with body: {}", ref.getMessageId(), ((ActiveMQTextMessage) ref.getMessage()).getText()); + assertEquals(dequeueCount++, ref.getMessageId().getProducerSequenceId()); + } + underTest.release(); + assertEquals(count, dequeueCount); + } + + private ActiveMQTextMessage getMessage(int i) throws Exception { + ActiveMQTextMessage message = new ActiveMQTextMessage(); + MessageId id = new MessageId(mesageIdRoot + i); + id.setBrokerSequenceId(i); + id.setProducerSequenceId(i); + message.setMessageId(id); + message.setDestination(destination); + message.setPersistent(true); + message.setResponseRequired(true); + message.setText("Msg:" + i + " " + text); + assertEquals(message.getMessageId().getProducerSequenceId(), i); + return message; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorOrderTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorOrderTest.java index e5431c065d..58f3528877 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorOrderTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorOrderTest.java @@ -21,6 +21,7 @@ import java.io.IOException; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; import java.util.concurrent.atomic.AtomicLong; + import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.ConnectionContext; import org.apache.activemq.broker.region.DestinationStatistics; @@ -42,476 +43,465 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class StoreQueueCursorOrderTest { - private static final Logger LOG = LoggerFactory.getLogger(StoreQueueCursorOrderTest.class); - - ActiveMQQueue destination = new ActiveMQQueue("queue-" - + StoreQueueCursorOrderTest.class.getSimpleName()); - BrokerService brokerService; - - final static String mesageIdRoot = "11111:22222:0:"; - final int messageBytesSize = 1024; - final String text = new String(new byte[messageBytesSize]); - - @Before - public void setUp() throws Exception { - brokerService = createBroker(); - brokerService.setUseJmx(false); - brokerService.deleteAllMessages(); - brokerService.start(); - } - - protected BrokerService createBroker() throws Exception { - return new BrokerService(); - } - - @After - public void tearDown() throws Exception { - brokerService.stop(); - } - - @Test - public void tesBlockedFuture() throws Exception { - final int count = 2; - final Message[] messages = new Message[count]; - final TestMessageStore queueMessageStore = new TestMessageStore(messages, destination); - final ConsumerInfo consumerInfo = new ConsumerInfo(); - final DestinationStatistics destinationStatistics = new DestinationStatistics(); - consumerInfo.setExclusive(true); - - final Queue queue = new Queue(brokerService, destination, - queueMessageStore, destinationStatistics, null); - - queueMessageStore.start(); - queueMessageStore.registerIndexListener(null); - - QueueStorePrefetch underTest = new QueueStorePrefetch(queue, brokerService.getBroker()); - SystemUsage systemUsage = new SystemUsage(); - // ensure memory limit is reached - systemUsage.getMemoryUsage().setLimit(messageBytesSize * 1); - underTest.setSystemUsage(systemUsage); - underTest.setEnableAudit(false); - underTest.start(); - assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); - - ActiveMQTextMessage msg = getMessage(0); - messages[1] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.setRecievedByDFBridge(true); - FutureTask future = new FutureTask(new Runnable() { - @Override - public void run() { - } - }, 2L) {}; - msg.getMessageId().setFutureOrSequenceLong(future); - underTest.addMessageLast(msg); - - assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); - - // second message will flip the cache but will be stored before the future task - msg = getMessage(1); - messages[0] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.getMessageId().setFutureOrSequenceLong(1L); - underTest.addMessageLast(msg); - - - assertTrue("cache is disabled as limit reached", !underTest.isCacheEnabled()); - assertEquals("setBatch unset", 0L, queueMessageStore.batch.get()); - - int dequeueCount = 0; - - underTest.setMaxBatchSize(2); - underTest.reset(); - while (underTest.hasNext() && dequeueCount < count) { - MessageReference ref = underTest.next(); - ref.decrementReferenceCount(); - underTest.remove(); - LOG.info("Received message: {} with body: {}", - ref.getMessageId(), ((ActiveMQTextMessage)ref.getMessage()).getText()); - assertEquals(dequeueCount++, ref.getMessageId().getProducerSequenceId()); - } - underTest.release(); - assertEquals(count, dequeueCount); - } - - @Test - public void testNoSetBatchWithUnOrderedFutureCurrentSync() throws Exception { - final int count = 2; - final Message[] messages = new Message[count]; - final TestMessageStore queueMessageStore = new TestMessageStore(messages, destination); - final ConsumerInfo consumerInfo = new ConsumerInfo(); - final DestinationStatistics destinationStatistics = new DestinationStatistics(); - consumerInfo.setExclusive(true); - - final Queue queue = new Queue(brokerService, destination, - queueMessageStore, destinationStatistics, null); - - queueMessageStore.start(); - queueMessageStore.registerIndexListener(null); - - QueueStorePrefetch underTest = new QueueStorePrefetch(queue, brokerService.getBroker()); - SystemUsage systemUsage = new SystemUsage(); - // ensure memory limit is reached - systemUsage.getMemoryUsage().setLimit(messageBytesSize * 1); - underTest.setSystemUsage(systemUsage); - underTest.setEnableAudit(false); - underTest.start(); - assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); - - ActiveMQTextMessage msg = getMessage(0); - messages[1] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.setRecievedByDFBridge(true); - final ActiveMQTextMessage msgRef = msg; - FutureTask future = new FutureTask(new Runnable() { - @Override - public void run() { - msgRef.getMessageId().setFutureOrSequenceLong(1L); - } - }, 1L) {}; - msg.getMessageId().setFutureOrSequenceLong(future); - Executors.newSingleThreadExecutor().submit(future); - underTest.addMessageLast(msg); - - assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); - - // second message will flip the cache but will be stored before the future task - msg = getMessage(1); - messages[0] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.getMessageId().setFutureOrSequenceLong(1L); - underTest.addMessageLast(msg); - - - assertTrue("cache is disabled as limit reached", !underTest.isCacheEnabled()); - assertEquals("setBatch unset", 0L, queueMessageStore.batch.get()); - - int dequeueCount = 0; - - underTest.setMaxBatchSize(2); - underTest.reset(); - while (underTest.hasNext() && dequeueCount < count) { - MessageReference ref = underTest.next(); - ref.decrementReferenceCount(); - underTest.remove(); - LOG.info("Received message: {} with body: {}", - ref.getMessageId(), ((ActiveMQTextMessage)ref.getMessage()).getText()); - assertEquals(dequeueCount++, ref.getMessageId().getProducerSequenceId()); - } - underTest.release(); - assertEquals(count, dequeueCount); - } - - @Test - public void testSetBatchWithOrderedFutureCurrentFuture() throws Exception { - final int count = 2; - final Message[] messages = new Message[count]; - final TestMessageStore queueMessageStore = new TestMessageStore(messages, destination); - final ConsumerInfo consumerInfo = new ConsumerInfo(); - final DestinationStatistics destinationStatistics = new DestinationStatistics(); - consumerInfo.setExclusive(true); - - final Queue queue = new Queue(brokerService, destination, - queueMessageStore, destinationStatistics, null); - - queueMessageStore.start(); - queueMessageStore.registerIndexListener(null); - - QueueStorePrefetch underTest = new QueueStorePrefetch(queue, brokerService.getBroker()); - SystemUsage systemUsage = new SystemUsage(); - // ensure memory limit is reached - systemUsage.getMemoryUsage().setLimit(messageBytesSize * 1); - underTest.setSystemUsage(systemUsage); - underTest.setEnableAudit(false); - underTest.start(); - assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); - - ActiveMQTextMessage msg = getMessage(0); - messages[0] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.setRecievedByDFBridge(true); - final ActiveMQTextMessage msgRef = msg; - FutureTask future = new FutureTask(new Runnable() { - @Override - public void run() { - msgRef.getMessageId().setFutureOrSequenceLong(0L); - } - }, 0L) {}; - msg.getMessageId().setFutureOrSequenceLong(future); - Executors.newSingleThreadExecutor().submit(future); - underTest.addMessageLast(msg); - - assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); - - // second message will flip the cache but will be stored before the future task - msg = getMessage(1); - messages[1] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.setRecievedByDFBridge(true); - final ActiveMQTextMessage msgRe2f = msg; - FutureTask future2 = new FutureTask(new Runnable() { - @Override - public void run() { - msgRe2f.getMessageId().setFutureOrSequenceLong(1L); - } - }, 1L) {}; - msg.getMessageId().setFutureOrSequenceLong(future2); - Executors.newSingleThreadExecutor().submit(future2); - underTest.addMessageLast(msg); - - - assertTrue("cache is disabled as limit reached", !underTest.isCacheEnabled()); - assertEquals("setBatch set", 1L, queueMessageStore.batch.get()); - - int dequeueCount = 0; - - underTest.setMaxBatchSize(2); - underTest.reset(); - while (underTest.hasNext() && dequeueCount < count) { - MessageReference ref = underTest.next(); - ref.decrementReferenceCount(); - underTest.remove(); - LOG.info("Received message: {} with body: {}", - ref.getMessageId(), ((ActiveMQTextMessage)ref.getMessage()).getText()); - assertEquals(dequeueCount++, ref.getMessageId().getProducerSequenceId()); - } - underTest.release(); - assertEquals(count, dequeueCount); - } - - @Test - public void testSetBatchWithFuture() throws Exception { - final int count = 4; - final Message[] messages = new Message[count]; - final TestMessageStore queueMessageStore = new TestMessageStore(messages, destination); - final ConsumerInfo consumerInfo = new ConsumerInfo(); - final DestinationStatistics destinationStatistics = new DestinationStatistics(); - consumerInfo.setExclusive(true); - - final Queue queue = new Queue(brokerService, destination, - queueMessageStore, destinationStatistics, null); - - queueMessageStore.start(); - queueMessageStore.registerIndexListener(null); - - QueueStorePrefetch underTest = new QueueStorePrefetch(queue, brokerService.getBroker()); - SystemUsage systemUsage = new SystemUsage(); - // ensure memory limit is reached - systemUsage.getMemoryUsage().setLimit(messageBytesSize * (count + 6)); - underTest.setSystemUsage(systemUsage); - underTest.setEnableAudit(false); - underTest.start(); - assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); - - ActiveMQTextMessage msg = getMessage(0); - messages[0] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.setRecievedByDFBridge(true); - final ActiveMQTextMessage msgRef = msg; - FutureTask future0 = new FutureTask(new Runnable() { - @Override - public void run() { - msgRef.getMessageId().setFutureOrSequenceLong(0L); - } - }, 0L) {}; - msg.getMessageId().setFutureOrSequenceLong(future0); - underTest.addMessageLast(msg); - Executors.newSingleThreadExecutor().submit(future0); - - - msg = getMessage(1); - messages[3] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.setRecievedByDFBridge(true); - final ActiveMQTextMessage msgRef1 = msg; - FutureTask future1 = new FutureTask(new Runnable() { - @Override - public void run() { - msgRef1.getMessageId().setFutureOrSequenceLong(3L); - } - }, 3L) {}; - msg.getMessageId().setFutureOrSequenceLong(future1); - underTest.addMessageLast(msg); - - - msg = getMessage(2); - messages[1] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.getMessageId().setFutureOrSequenceLong(1L); - underTest.addMessageLast(msg); - - assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); - - // out of order future - Executors.newSingleThreadExecutor().submit(future1); - - // sync add to flip cache - msg = getMessage(3); - messages[2] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.getMessageId().setFutureOrSequenceLong(3L); - underTest.addMessageLast(msg); - - - assertTrue("cache is disabled as limit reached", !underTest.isCacheEnabled()); - assertEquals("setBatch set", 2L, queueMessageStore.batch.get()); - - int dequeueCount = 0; - - underTest.setMaxBatchSize(count); - underTest.reset(); - while (underTest.hasNext() && dequeueCount < count) { - MessageReference ref = underTest.next(); - ref.decrementReferenceCount(); - underTest.remove(); - LOG.info("Received message: {} with body: {}", - ref.getMessageId(), ((ActiveMQTextMessage)ref.getMessage()).getText()); - assertEquals(dequeueCount++, ref.getMessageId().getProducerSequenceId()); - } - underTest.release(); - assertEquals(count, dequeueCount); - } - - @Test - public void testSetBatch() throws Exception { - final int count = 3; - final Message[] messages = new Message[count]; - final TestMessageStore queueMessageStore = new TestMessageStore(messages, destination); - final ConsumerInfo consumerInfo = new ConsumerInfo(); - final DestinationStatistics destinationStatistics = new DestinationStatistics(); - consumerInfo.setExclusive(true); - - final Queue queue = new Queue(brokerService, destination, - queueMessageStore, destinationStatistics, null); - - queueMessageStore.start(); - queueMessageStore.registerIndexListener(null); - - QueueStorePrefetch underTest = new QueueStorePrefetch(queue, brokerService.getBroker()); - SystemUsage systemUsage = new SystemUsage(); - // ensure memory limit is reached - systemUsage.getMemoryUsage().setLimit(messageBytesSize * 5); - underTest.setSystemUsage(systemUsage); - underTest.setEnableAudit(false); - underTest.start(); - assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); - - - ActiveMQTextMessage msg = getMessage(0); - messages[0] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.getMessageId().setFutureOrSequenceLong(0L); - underTest.addMessageLast(msg); - - msg = getMessage(1); - messages[1] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.getMessageId().setFutureOrSequenceLong(1L); - underTest.addMessageLast(msg); - - assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); - - msg = getMessage(2); - messages[2] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.getMessageId().setFutureOrSequenceLong(2L); - underTest.addMessageLast(msg); - - - assertTrue("cache is disabled as limit reached", !underTest.isCacheEnabled()); - assertEquals("setBatch set", 2L, queueMessageStore.batch.get()); - - int dequeueCount = 0; - - underTest.setMaxBatchSize(2); - underTest.reset(); - while (underTest.hasNext() && dequeueCount < count) { - MessageReference ref = underTest.next(); - ref.decrementReferenceCount(); - underTest.remove(); - LOG.info("Received message: {} with body: {}", - ref.getMessageId(), ((ActiveMQTextMessage)ref.getMessage()).getText()); - assertEquals(dequeueCount++, ref.getMessageId().getProducerSequenceId()); - } - underTest.release(); - assertEquals(count, dequeueCount); - } - - private ActiveMQTextMessage getMessage(int i) throws Exception { - ActiveMQTextMessage message = new ActiveMQTextMessage(); - MessageId id = new MessageId(mesageIdRoot + i); - id.setBrokerSequenceId(i); - id.setProducerSequenceId(i); - message.setMessageId(id); - message.setDestination(destination); - message.setPersistent(true); - message.setResponseRequired(true); - message.setText("Msg:" + i + " " + text); - assertEquals(message.getMessageId().getProducerSequenceId(), i); - return message; - } - - class TestMessageStore extends AbstractMessageStore { - final Message[] messages; - public AtomicLong batch = new AtomicLong(); - - public TestMessageStore(Message[] messages, ActiveMQDestination dest) { - super(dest); - this.messages = messages; - } - - @Override - public void addMessage(ConnectionContext context, Message message) throws IOException { - - } - - @Override - public Message getMessage(MessageId identity) throws IOException { - return null; - } - - @Override - public void removeMessage(ConnectionContext context, MessageAck ack) throws IOException { - - } - - @Override - public void removeAllMessages(ConnectionContext context) throws IOException { - - } - - @Override - public void recover(MessageRecoveryListener container) throws Exception { - - } - - @Override - public int getMessageCount() throws IOException { - return 0; - } - - @Override - public void resetBatching() { - - } - @Override - public void recoverNextMessages(int maxReturned, MessageRecoveryListener listener) throws Exception { - for (int i=batch.intValue();i future = new FutureTask(new Runnable() { + @Override + public void run() { + } + }, 2L) { + }; + msg.getMessageId().setFutureOrSequenceLong(future); + underTest.addMessageLast(msg); + + assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); + + // second message will flip the cache but will be stored before the future task + msg = getMessage(1); + messages[0] = msg; + msg.setMemoryUsage(systemUsage.getMemoryUsage()); + msg.getMessageId().setFutureOrSequenceLong(1L); + underTest.addMessageLast(msg); + + assertTrue("cache is disabled as limit reached", !underTest.isCacheEnabled()); + assertEquals("setBatch unset", 0L, queueMessageStore.batch.get()); + + int dequeueCount = 0; + + underTest.setMaxBatchSize(2); + underTest.reset(); + while (underTest.hasNext() && dequeueCount < count) { + MessageReference ref = underTest.next(); + ref.decrementReferenceCount(); + underTest.remove(); + LOG.info("Received message: {} with body: {}", ref.getMessageId(), ((ActiveMQTextMessage) ref.getMessage()).getText()); + assertEquals(dequeueCount++, ref.getMessageId().getProducerSequenceId()); + } + underTest.release(); + assertEquals(count, dequeueCount); + } + + @Test + public void testNoSetBatchWithUnOrderedFutureCurrentSync() throws Exception { + final int count = 2; + final Message[] messages = new Message[count]; + final TestMessageStore queueMessageStore = new TestMessageStore(messages, destination); + final ConsumerInfo consumerInfo = new ConsumerInfo(); + final DestinationStatistics destinationStatistics = new DestinationStatistics(); + consumerInfo.setExclusive(true); + + final Queue queue = new Queue(brokerService, destination, queueMessageStore, destinationStatistics, null); + + queueMessageStore.start(); + queueMessageStore.registerIndexListener(null); + + QueueStorePrefetch underTest = new QueueStorePrefetch(queue, brokerService.getBroker()); + SystemUsage systemUsage = new SystemUsage(); + // ensure memory limit is reached + systemUsage.getMemoryUsage().setLimit(messageBytesSize * 1); + underTest.setSystemUsage(systemUsage); + underTest.setEnableAudit(false); + underTest.start(); + assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); + + ActiveMQTextMessage msg = getMessage(0); + messages[1] = msg; + msg.setMemoryUsage(systemUsage.getMemoryUsage()); + msg.setRecievedByDFBridge(true); + final ActiveMQTextMessage msgRef = msg; + FutureTask future = new FutureTask(new Runnable() { + @Override + public void run() { + msgRef.getMessageId().setFutureOrSequenceLong(1L); + } + }, 1L) { + }; + msg.getMessageId().setFutureOrSequenceLong(future); + Executors.newSingleThreadExecutor().submit(future); + underTest.addMessageLast(msg); + + assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); + + // second message will flip the cache but will be stored before the future task + msg = getMessage(1); + messages[0] = msg; + msg.setMemoryUsage(systemUsage.getMemoryUsage()); + msg.getMessageId().setFutureOrSequenceLong(1L); + underTest.addMessageLast(msg); + + assertTrue("cache is disabled as limit reached", !underTest.isCacheEnabled()); + assertEquals("setBatch unset", 0L, queueMessageStore.batch.get()); + + int dequeueCount = 0; + + underTest.setMaxBatchSize(2); + underTest.reset(); + while (underTest.hasNext() && dequeueCount < count) { + MessageReference ref = underTest.next(); + ref.decrementReferenceCount(); + underTest.remove(); + LOG.info("Received message: {} with body: {}", ref.getMessageId(), ((ActiveMQTextMessage) ref.getMessage()).getText()); + assertEquals(dequeueCount++, ref.getMessageId().getProducerSequenceId()); + } + underTest.release(); + assertEquals(count, dequeueCount); + } + + @Test + public void testSetBatchWithOrderedFutureCurrentFuture() throws Exception { + final int count = 2; + final Message[] messages = new Message[count]; + final TestMessageStore queueMessageStore = new TestMessageStore(messages, destination); + final ConsumerInfo consumerInfo = new ConsumerInfo(); + final DestinationStatistics destinationStatistics = new DestinationStatistics(); + consumerInfo.setExclusive(true); + + final Queue queue = new Queue(brokerService, destination, queueMessageStore, destinationStatistics, null); + + queueMessageStore.start(); + queueMessageStore.registerIndexListener(null); + + QueueStorePrefetch underTest = new QueueStorePrefetch(queue, brokerService.getBroker()); + SystemUsage systemUsage = new SystemUsage(); + // ensure memory limit is reached + systemUsage.getMemoryUsage().setLimit(messageBytesSize * 1); + underTest.setSystemUsage(systemUsage); + underTest.setEnableAudit(false); + underTest.start(); + assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); + + ActiveMQTextMessage msg = getMessage(0); + messages[0] = msg; + msg.setMemoryUsage(systemUsage.getMemoryUsage()); + msg.setRecievedByDFBridge(true); + final ActiveMQTextMessage msgRef = msg; + FutureTask future = new FutureTask(new Runnable() { + @Override + public void run() { + msgRef.getMessageId().setFutureOrSequenceLong(0L); + } + }, 0L) { + }; + msg.getMessageId().setFutureOrSequenceLong(future); + Executors.newSingleThreadExecutor().submit(future); + underTest.addMessageLast(msg); + + assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); + + // second message will flip the cache but will be stored before the future task + msg = getMessage(1); + messages[1] = msg; + msg.setMemoryUsage(systemUsage.getMemoryUsage()); + msg.setRecievedByDFBridge(true); + final ActiveMQTextMessage msgRe2f = msg; + FutureTask future2 = new FutureTask(new Runnable() { + @Override + public void run() { + msgRe2f.getMessageId().setFutureOrSequenceLong(1L); + } + }, 1L) { + }; + msg.getMessageId().setFutureOrSequenceLong(future2); + Executors.newSingleThreadExecutor().submit(future2); + underTest.addMessageLast(msg); + + assertTrue("cache is disabled as limit reached", !underTest.isCacheEnabled()); + assertEquals("setBatch set", 1L, queueMessageStore.batch.get()); + + int dequeueCount = 0; + + underTest.setMaxBatchSize(2); + underTest.reset(); + while (underTest.hasNext() && dequeueCount < count) { + MessageReference ref = underTest.next(); + ref.decrementReferenceCount(); + underTest.remove(); + LOG.info("Received message: {} with body: {}", ref.getMessageId(), ((ActiveMQTextMessage) ref.getMessage()).getText()); + assertEquals(dequeueCount++, ref.getMessageId().getProducerSequenceId()); + } + underTest.release(); + assertEquals(count, dequeueCount); + } + + @Test + public void testSetBatchWithFuture() throws Exception { + final int count = 4; + final Message[] messages = new Message[count]; + final TestMessageStore queueMessageStore = new TestMessageStore(messages, destination); + final ConsumerInfo consumerInfo = new ConsumerInfo(); + final DestinationStatistics destinationStatistics = new DestinationStatistics(); + consumerInfo.setExclusive(true); + + final Queue queue = new Queue(brokerService, destination, queueMessageStore, destinationStatistics, null); + + queueMessageStore.start(); + queueMessageStore.registerIndexListener(null); + + QueueStorePrefetch underTest = new QueueStorePrefetch(queue, brokerService.getBroker()); + SystemUsage systemUsage = new SystemUsage(); + // ensure memory limit is reached + systemUsage.getMemoryUsage().setLimit(messageBytesSize * (count + 6)); + underTest.setSystemUsage(systemUsage); + underTest.setEnableAudit(false); + underTest.start(); + assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); + + ActiveMQTextMessage msg = getMessage(0); + messages[0] = msg; + msg.setMemoryUsage(systemUsage.getMemoryUsage()); + msg.setRecievedByDFBridge(true); + final ActiveMQTextMessage msgRef = msg; + FutureTask future0 = new FutureTask(new Runnable() { + @Override + public void run() { + msgRef.getMessageId().setFutureOrSequenceLong(0L); + } + }, 0L) { + }; + msg.getMessageId().setFutureOrSequenceLong(future0); + underTest.addMessageLast(msg); + Executors.newSingleThreadExecutor().submit(future0); + + msg = getMessage(1); + messages[3] = msg; + msg.setMemoryUsage(systemUsage.getMemoryUsage()); + msg.setRecievedByDFBridge(true); + final ActiveMQTextMessage msgRef1 = msg; + FutureTask future1 = new FutureTask(new Runnable() { + @Override + public void run() { + msgRef1.getMessageId().setFutureOrSequenceLong(3L); + } + }, 3L) { + }; + msg.getMessageId().setFutureOrSequenceLong(future1); + underTest.addMessageLast(msg); + + msg = getMessage(2); + messages[1] = msg; + msg.setMemoryUsage(systemUsage.getMemoryUsage()); + msg.getMessageId().setFutureOrSequenceLong(1L); + underTest.addMessageLast(msg); + + assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); + + // out of order future + Executors.newSingleThreadExecutor().submit(future1); + + // sync add to flip cache + msg = getMessage(3); + messages[2] = msg; + msg.setMemoryUsage(systemUsage.getMemoryUsage()); + msg.getMessageId().setFutureOrSequenceLong(3L); + underTest.addMessageLast(msg); + + assertTrue("cache is disabled as limit reached", !underTest.isCacheEnabled()); + assertEquals("setBatch set", 2L, queueMessageStore.batch.get()); + + int dequeueCount = 0; + + underTest.setMaxBatchSize(count); + underTest.reset(); + while (underTest.hasNext() && dequeueCount < count) { + MessageReference ref = underTest.next(); + ref.decrementReferenceCount(); + underTest.remove(); + LOG.info("Received message: {} with body: {}", ref.getMessageId(), ((ActiveMQTextMessage) ref.getMessage()).getText()); + assertEquals(dequeueCount++, ref.getMessageId().getProducerSequenceId()); + } + underTest.release(); + assertEquals(count, dequeueCount); + } + + @Test + public void testSetBatch() throws Exception { + final int count = 3; + final Message[] messages = new Message[count]; + final TestMessageStore queueMessageStore = new TestMessageStore(messages, destination); + final ConsumerInfo consumerInfo = new ConsumerInfo(); + final DestinationStatistics destinationStatistics = new DestinationStatistics(); + consumerInfo.setExclusive(true); + + final Queue queue = new Queue(brokerService, destination, queueMessageStore, destinationStatistics, null); + + queueMessageStore.start(); + queueMessageStore.registerIndexListener(null); + + QueueStorePrefetch underTest = new QueueStorePrefetch(queue, brokerService.getBroker()); + SystemUsage systemUsage = new SystemUsage(); + // ensure memory limit is reached + systemUsage.getMemoryUsage().setLimit(messageBytesSize * 5); + underTest.setSystemUsage(systemUsage); + underTest.setEnableAudit(false); + underTest.start(); + assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); + + ActiveMQTextMessage msg = getMessage(0); + messages[0] = msg; + msg.setMemoryUsage(systemUsage.getMemoryUsage()); + msg.getMessageId().setFutureOrSequenceLong(0L); + underTest.addMessageLast(msg); + + msg = getMessage(1); + messages[1] = msg; + msg.setMemoryUsage(systemUsage.getMemoryUsage()); + msg.getMessageId().setFutureOrSequenceLong(1L); + underTest.addMessageLast(msg); + + assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); + + msg = getMessage(2); + messages[2] = msg; + msg.setMemoryUsage(systemUsage.getMemoryUsage()); + msg.getMessageId().setFutureOrSequenceLong(2L); + underTest.addMessageLast(msg); + + assertTrue("cache is disabled as limit reached", !underTest.isCacheEnabled()); + assertEquals("setBatch set", 2L, queueMessageStore.batch.get()); + + int dequeueCount = 0; + + underTest.setMaxBatchSize(2); + underTest.reset(); + while (underTest.hasNext() && dequeueCount < count) { + MessageReference ref = underTest.next(); + ref.decrementReferenceCount(); + underTest.remove(); + LOG.info("Received message: {} with body: {}", ref.getMessageId(), ((ActiveMQTextMessage) ref.getMessage()).getText()); + assertEquals(dequeueCount++, ref.getMessageId().getProducerSequenceId()); + } + underTest.release(); + assertEquals(count, dequeueCount); + } + + private ActiveMQTextMessage getMessage(int i) throws Exception { + ActiveMQTextMessage message = new ActiveMQTextMessage(); + MessageId id = new MessageId(mesageIdRoot + i); + id.setBrokerSequenceId(i); + id.setProducerSequenceId(i); + message.setMessageId(id); + message.setDestination(destination); + message.setPersistent(true); + message.setResponseRequired(true); + message.setText("Msg:" + i + " " + text); + assertEquals(message.getMessageId().getProducerSequenceId(), i); + return message; + } + + class TestMessageStore extends AbstractMessageStore { + + final Message[] messages; + public AtomicLong batch = new AtomicLong(); + + public TestMessageStore(Message[] messages, ActiveMQDestination dest) { + super(dest); + this.messages = messages; + } + + @Override + public void addMessage(ConnectionContext context, Message message) throws IOException { + + } + + @Override + public Message getMessage(MessageId identity) throws IOException { + return null; + } + + @Override + public void removeMessage(ConnectionContext context, MessageAck ack) throws IOException { + + } + + @Override + public void removeAllMessages(ConnectionContext context) throws IOException { + + } + + @Override + public void recover(MessageRecoveryListener container) throws Exception { + + } + + @Override + public int getMessageCount() throws IOException { + return 0; + } + + @Override + public void resetBatching() { + + } + + @Override + public void recoverNextMessages(int maxReturned, MessageRecoveryListener listener) throws Exception { + for (int i = batch.intValue(); i < messages.length; i++) { + LOG.info("recovered index:" + i); + listener.recoverMessage(messages[i]); + } + } + + @Override + public void setBatch(MessageId message) { + batch.set((Long) message.getFutureOrSequenceLong()); + batch.incrementAndGet(); + } + + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupHashBucketTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupHashBucketTest.java index fc35be6d2e..538593b03a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupHashBucketTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupHashBucketTest.java @@ -16,15 +16,14 @@ */ package org.apache.activemq.broker.region.group; - /** * - * + * */ public class MessageGroupHashBucketTest extends MessageGroupMapTest { - protected MessageGroupMap createMessageGroupMap() { - return new MessageGroupHashBucket(1024, 64); - } + protected MessageGroupMap createMessageGroupMap() { + return new MessageGroupHashBucket(1024, 64); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupMapTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupMapTest.java index ab02426cce..9c80487393 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupMapTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupMapTest.java @@ -17,88 +17,89 @@ package org.apache.activemq.broker.region.group; import junit.framework.TestCase; + import org.apache.activemq.command.ConnectionId; import org.apache.activemq.command.ConsumerId; import org.apache.activemq.command.SessionId; /** - * - * + * + * */ public class MessageGroupMapTest extends TestCase { - protected MessageGroupMap map; - private ConsumerId consumer1; - private ConsumerId consumer2; - private ConsumerId consumer3; - private long idCounter; + protected MessageGroupMap map; + private ConsumerId consumer1; + private ConsumerId consumer2; + private ConsumerId consumer3; + private long idCounter; - public void testSingleConsumerForManyBucks() throws Exception { - assertGet("1", null); + public void testSingleConsumerForManyBucks() throws Exception { + assertGet("1", null); - map.put("1", consumer1); - assertGet("1", consumer1); - map.put("2", consumer1); - assertGet("2", consumer1); - map.put("3", consumer1); - assertGet("3", consumer1); + map.put("1", consumer1); + assertGet("1", consumer1); + map.put("2", consumer1); + assertGet("2", consumer1); + map.put("3", consumer1); + assertGet("3", consumer1); - MessageGroupSet set = map.removeConsumer(consumer1); - assertContains(set, "1"); - assertContains(set, "2"); - assertContains(set, "3"); - assertGet("1", null); - assertGet("2", null); - assertGet("3", null); - } + MessageGroupSet set = map.removeConsumer(consumer1); + assertContains(set, "1"); + assertContains(set, "2"); + assertContains(set, "3"); + assertGet("1", null); + assertGet("2", null); + assertGet("3", null); + } - public void testManyConsumers() throws Exception { - assertGet("1", null); + public void testManyConsumers() throws Exception { + assertGet("1", null); - map.put("1", consumer1); - assertGet("1", consumer1); - map.put("2", consumer2); - assertGet("2", consumer2); - map.put("3", consumer3); - assertGet("3", consumer3); + map.put("1", consumer1); + assertGet("1", consumer1); + map.put("2", consumer2); + assertGet("2", consumer2); + map.put("3", consumer3); + assertGet("3", consumer3); - MessageGroupSet set = map.removeConsumer(consumer1); - assertContains(set, "1"); + MessageGroupSet set = map.removeConsumer(consumer1); + assertContains(set, "1"); - assertGet("1", null); - map.put("1", consumer2); - assertGet("1", consumer2); + assertGet("1", null); + map.put("1", consumer2); + assertGet("1", consumer2); - set = map.removeConsumer(consumer2); - assertContains(set, "1"); - assertContains(set, "2"); - } + set = map.removeConsumer(consumer2); + assertContains(set, "1"); + assertContains(set, "2"); + } - protected void setUp() throws Exception { - super.setUp(); - map = createMessageGroupMap(); - consumer1 = createConsumerId(); - consumer2 = createConsumerId(); - consumer3 = createConsumerId(); - } + protected void setUp() throws Exception { + super.setUp(); + map = createMessageGroupMap(); + consumer1 = createConsumerId(); + consumer2 = createConsumerId(); + consumer3 = createConsumerId(); + } - protected MessageGroupMap createMessageGroupMap() { - return new SimpleMessageGroupMap(); - } + protected MessageGroupMap createMessageGroupMap() { + return new SimpleMessageGroupMap(); + } - protected ConsumerId createConsumerId() { - ConnectionId connectionId = new ConnectionId("" + ++idCounter); - SessionId sessionId = new SessionId(connectionId, ++idCounter); - ConsumerId answer = new ConsumerId(sessionId, ++idCounter); - return answer; - } + protected ConsumerId createConsumerId() { + ConnectionId connectionId = new ConnectionId("" + ++idCounter); + SessionId sessionId = new SessionId(connectionId, ++idCounter); + ConsumerId answer = new ConsumerId(sessionId, ++idCounter); + return answer; + } - protected void assertGet(String groupdId, ConsumerId expected) { - ConsumerId actual = map.get(groupdId); - assertEquals("Entry for groupId: " + groupdId, expected, actual); - } + protected void assertGet(String groupdId, ConsumerId expected) { + ConsumerId actual = map.get(groupdId); + assertEquals("Entry for groupId: " + groupdId, expected, actual); + } - protected void assertContains(MessageGroupSet set, String groupID) { - assertTrue("MessageGroup set: " + set + " does not contain groupID: " + groupID, set.contains(groupID)); - } + protected void assertContains(MessageGroupSet set, String groupID) { + assertTrue("MessageGroup set: " + set + " does not contain groupID: " + groupID, set.contains(groupID)); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupTest.java index 86741c98de..aa7501e480 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupTest.java @@ -31,151 +31,149 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MessageGroupTest extends JmsTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(CombinationTestSupport.class); - public void testGroupedMessagesDeliveredToOnlyOneConsumer() throws Exception { + private static final Logger LOG = LoggerFactory.getLogger(CombinationTestSupport.class); - ActiveMQDestination destination = new ActiveMQQueue("TEST"); + public void testGroupedMessagesDeliveredToOnlyOneConsumer() throws Exception { - // Setup a first connection - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer1 = session.createConsumer(destination); - MessageProducer producer = session.createProducer(destination); + ActiveMQDestination destination = new ActiveMQQueue("TEST"); - // Send the messages. - for (int i = 0; i < 4; i++) { - TextMessage message = session.createTextMessage("message " + i); - message.setStringProperty("JMSXGroupID", "TEST-GROUP"); - message.setIntProperty("JMSXGroupSeq", i + 1); - LOG.info("sending message: " + message); - producer.send(message); - } + // Setup a first connection + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer1 = session.createConsumer(destination); + MessageProducer producer = session.createProducer(destination); - // All the messages should have been sent down connection 1.. just get - // the first 3 - for (int i = 0; i < 3; i++) { - TextMessage m1 = (TextMessage)consumer1.receive(500); - assertNotNull("m1 is null for index: " + i, m1); - assertEquals(m1.getIntProperty("JMSXGroupSeq"), i + 1); - } - - // Setup a second connection - Connection connection1 = factory.createConnection(userName, password); - connection1.start(); - Session session2 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer2 = session2.createConsumer(destination); + // Send the messages. + for (int i = 0; i < 4; i++) { + TextMessage message = session.createTextMessage("message " + i); + message.setStringProperty("JMSXGroupID", "TEST-GROUP"); + message.setIntProperty("JMSXGroupSeq", i + 1); + LOG.info("sending message: " + message); + producer.send(message); + } - // Close the first consumer. - consumer1.close(); + // All the messages should have been sent down connection 1.. just get + // the first 3 + for (int i = 0; i < 3; i++) { + TextMessage m1 = (TextMessage) consumer1.receive(500); + assertNotNull("m1 is null for index: " + i, m1); + assertEquals(m1.getIntProperty("JMSXGroupSeq"), i + 1); + } - // The last messages should now go the the second consumer. - for (int i = 0; i < 1; i++) { - TextMessage m1 = (TextMessage)consumer2.receive(500); - assertNotNull("m1 is null for index: " + i, m1); - assertEquals(m1.getIntProperty("JMSXGroupSeq"), 4 + i); - } + // Setup a second connection + Connection connection1 = factory.createConnection(userName, password); + connection1.start(); + Session session2 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer2 = session2.createConsumer(destination); - //assert that there are no other messages left for the consumer 2 - Message m = consumer2.receive(100); - assertNull("consumer 2 has some messages left", m); - } - - public void testAddingConsumer() throws Exception { - ActiveMQDestination destination = new ActiveMQQueue("TEST"); + // Close the first consumer. + consumer1.close(); - // Setup a first connection - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageProducer producer = session.createProducer(destination); - //MessageConsumer consumer = session.createConsumer(destination); - - TextMessage message = session.createTextMessage("message"); - message.setStringProperty("JMSXGroupID", "TEST-GROUP"); - - LOG.info("sending message: " + message); - producer.send(message); - - MessageConsumer consumer = session.createConsumer(destination); - - TextMessage msg = (TextMessage)consumer.receive(); - assertNotNull(msg); - boolean first = msg.getBooleanProperty("JMSXGroupFirstForConsumer"); - assertTrue(first); - } - - public void testClosingMessageGroup() throws Exception { + // The last messages should now go the the second consumer. + for (int i = 0; i < 1; i++) { + TextMessage m1 = (TextMessage) consumer2.receive(500); + assertNotNull("m1 is null for index: " + i, m1); + assertEquals(m1.getIntProperty("JMSXGroupSeq"), 4 + i); + } - ActiveMQDestination destination = new ActiveMQQueue("TEST"); + //assert that there are no other messages left for the consumer 2 + Message m = consumer2.receive(100); + assertNull("consumer 2 has some messages left", m); + } - // Setup a first connection - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer1 = session.createConsumer(destination); - MessageProducer producer = session.createProducer(destination); + public void testAddingConsumer() throws Exception { + ActiveMQDestination destination = new ActiveMQQueue("TEST"); - // Send the messages. - for (int i = 0; i < 4; i++) { - TextMessage message = session.createTextMessage("message " + i); - message.setStringProperty("JMSXGroupID", "TEST-GROUP"); - LOG.info("sending message: " + message); - producer.send(message); - } + // Setup a first connection + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + //MessageConsumer consumer = session.createConsumer(destination); + TextMessage message = session.createTextMessage("message"); + message.setStringProperty("JMSXGroupID", "TEST-GROUP"); - // All the messages should have been sent down consumer1.. just get - // the first 3 - for (int i = 0; i < 3; i++) { - TextMessage m1 = (TextMessage)consumer1.receive(500); - assertNotNull("m1 is null for index: " + i, m1); - } - - // Setup a second consumer - Connection connection1 = factory.createConnection(userName, password); - connection1.start(); - Session session2 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer2 = session2.createConsumer(destination); - - //assert that there are no messages for the consumer 2 - Message m = consumer2.receive(100); - assertNull("consumer 2 has some messages", m); + LOG.info("sending message: " + message); + producer.send(message); - // Close the group - TextMessage message = session.createTextMessage("message " + 5); - message.setStringProperty("JMSXGroupID", "TEST-GROUP"); - message.setIntProperty("JMSXGroupSeq", -1); - LOG.info("sending message: " + message); - producer.send(message); - - //Send some more messages - for (int i = 0; i < 4; i++) { - message = session.createTextMessage("message " + i); - message.setStringProperty("JMSXGroupID", "TEST-GROUP"); - LOG.info("sending message: " + message); - producer.send(message); - } - - // Receive the fourth message - TextMessage m1 = (TextMessage)consumer1.receive(500); - assertNotNull("m1 is null for index: " + 4, m1); - - // Receive the closing message - m1 = (TextMessage)consumer1.receive(500); - assertNotNull("m1 is null for index: " + 5, m1); - - //assert that there are no messages for the consumer 1 - m = consumer1.receive(100); - assertNull("consumer 1 has some messages left: " + m, m); + MessageConsumer consumer = session.createConsumer(destination); - // The messages should now go to the second consumer. - for (int i = 0; i < 4; i++) { - m1 = (TextMessage)consumer2.receive(500); - assertNotNull("m1 is null for index: " + i, m1); - } + TextMessage msg = (TextMessage) consumer.receive(); + assertNotNull(msg); + boolean first = msg.getBooleanProperty("JMSXGroupFirstForConsumer"); + assertTrue(first); + } + + public void testClosingMessageGroup() throws Exception { + + ActiveMQDestination destination = new ActiveMQQueue("TEST"); + + // Setup a first connection + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer1 = session.createConsumer(destination); + MessageProducer producer = session.createProducer(destination); + + // Send the messages. + for (int i = 0; i < 4; i++) { + TextMessage message = session.createTextMessage("message " + i); + message.setStringProperty("JMSXGroupID", "TEST-GROUP"); + LOG.info("sending message: " + message); + producer.send(message); + } + + // All the messages should have been sent down consumer1.. just get + // the first 3 + for (int i = 0; i < 3; i++) { + TextMessage m1 = (TextMessage) consumer1.receive(500); + assertNotNull("m1 is null for index: " + i, m1); + } + + // Setup a second consumer + Connection connection1 = factory.createConnection(userName, password); + connection1.start(); + Session session2 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer2 = session2.createConsumer(destination); + + //assert that there are no messages for the consumer 2 + Message m = consumer2.receive(100); + assertNull("consumer 2 has some messages", m); + + // Close the group + TextMessage message = session.createTextMessage("message " + 5); + message.setStringProperty("JMSXGroupID", "TEST-GROUP"); + message.setIntProperty("JMSXGroupSeq", -1); + LOG.info("sending message: " + message); + producer.send(message); + + //Send some more messages + for (int i = 0; i < 4; i++) { + message = session.createTextMessage("message " + i); + message.setStringProperty("JMSXGroupID", "TEST-GROUP"); + LOG.info("sending message: " + message); + producer.send(message); + } + + // Receive the fourth message + TextMessage m1 = (TextMessage) consumer1.receive(500); + assertNotNull("m1 is null for index: " + 4, m1); + + // Receive the closing message + m1 = (TextMessage) consumer1.receive(500); + assertNotNull("m1 is null for index: " + 5, m1); + + //assert that there are no messages for the consumer 1 + m = consumer1.receive(100); + assertNull("consumer 1 has some messages left: " + m, m); + + // The messages should now go to the second consumer. + for (int i = 0; i < 4; i++) { + m1 = (TextMessage) consumer2.receive(500); + assertNotNull("m1 is null for index: " + i, m1); + } + + } - } - } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JmsCronSchedulerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JmsCronSchedulerTest.java index 44ef670287..6dd8b84b5a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JmsCronSchedulerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JmsCronSchedulerTest.java @@ -44,75 +44,76 @@ import org.slf4j.LoggerFactory; public class JmsCronSchedulerTest extends JobSchedulerTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(JmsCronSchedulerTest.class); + private static final Logger LOG = LoggerFactory.getLogger(JmsCronSchedulerTest.class); - @Test - public void testSimulatenousCron() throws Exception { + @Test + public void testSimulatenousCron() throws Exception { - final int COUNT = 10; - final AtomicInteger count = new AtomicInteger(); - Connection connection = createConnection(); + final int COUNT = 10; + final AtomicInteger count = new AtomicInteger(); + Connection connection = createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); + MessageConsumer consumer = session.createConsumer(destination); - final CountDownLatch latch = new CountDownLatch(COUNT); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - count.incrementAndGet(); - latch.countDown(); - assertTrue(message instanceof TextMessage); - TextMessage tm = (TextMessage) message; - try { - LOG.info("Received [{}] count: {} ", tm.getText(), count.get()); - } catch (JMSException e) { - LOG.error("Unexpected exception in onMessage", e); - fail("Unexpected exception in onMessage: " + e.getMessage()); - } + final CountDownLatch latch = new CountDownLatch(COUNT); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + count.incrementAndGet(); + latch.countDown(); + assertTrue(message instanceof TextMessage); + TextMessage tm = (TextMessage) message; + try { + LOG.info("Received [{}] count: {} ", tm.getText(), count.get()); } - }); + catch (JMSException e) { + LOG.error("Unexpected exception in onMessage", e); + fail("Unexpected exception in onMessage: " + e.getMessage()); + } + } + }); - connection.start(); - for (int i = 0; i < COUNT; i++) { - MessageProducer producer = session.createProducer(destination); - TextMessage message = session.createTextMessage("test msg "+ i); - message.setStringProperty(ScheduledMessage.AMQ_SCHEDULED_CRON, "* * * * *"); - producer.send(message); - LOG.info("Message {} sent at {}", i, new Date().toString()); - producer.close(); - //wait a couple sec so cron start time is different for next message - Thread.sleep(2000); - } - SchedulerBroker sb = (SchedulerBroker) this.broker.getBroker().getAdaptor(SchedulerBroker.class); - JobScheduler js = sb.getJobScheduler(); - List list = js.getAllJobs(); - assertEquals(COUNT, list.size()); - latch.await(2, TimeUnit.MINUTES); - //All should messages should have been received by now - assertEquals(COUNT, count.get()); - } + connection.start(); + for (int i = 0; i < COUNT; i++) { + MessageProducer producer = session.createProducer(destination); + TextMessage message = session.createTextMessage("test msg " + i); + message.setStringProperty(ScheduledMessage.AMQ_SCHEDULED_CRON, "* * * * *"); + producer.send(message); + LOG.info("Message {} sent at {}", i, new Date().toString()); + producer.close(); + //wait a couple sec so cron start time is different for next message + Thread.sleep(2000); + } + SchedulerBroker sb = (SchedulerBroker) this.broker.getBroker().getAdaptor(SchedulerBroker.class); + JobScheduler js = sb.getJobScheduler(); + List list = js.getAllJobs(); + assertEquals(COUNT, list.size()); + latch.await(2, TimeUnit.MINUTES); + //All should messages should have been received by now + assertEquals(COUNT, count.get()); + } - @Test - public void testCronScheduleWithTtlSet() throws Exception { + @Test + public void testCronScheduleWithTtlSet() throws Exception { - Connection connection = createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); - connection.start(); + Connection connection = createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(destination); + connection.start(); - MessageProducer producer = session.createProducer(destination); - producer.setTimeToLive(TimeUnit.MINUTES.toMillis(1)); - TextMessage message = session.createTextMessage("test msg "); - message.setStringProperty(ScheduledMessage.AMQ_SCHEDULED_CRON, "* * * * *"); + MessageProducer producer = session.createProducer(destination); + producer.setTimeToLive(TimeUnit.MINUTES.toMillis(1)); + TextMessage message = session.createTextMessage("test msg "); + message.setStringProperty(ScheduledMessage.AMQ_SCHEDULED_CRON, "* * * * *"); - producer.send(message); - producer.close(); + producer.send(message); + producer.close(); - Thread.sleep(TimeUnit.MINUTES.toMillis(2)); + Thread.sleep(TimeUnit.MINUTES.toMillis(2)); - assertNotNull(consumer.receiveNoWait()); - assertNull(consumer.receiveNoWait()); - } + assertNotNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JmsSchedulerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JmsSchedulerTest.java index 41b0f0dc02..25c9b6f907 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JmsSchedulerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JmsSchedulerTest.java @@ -41,248 +41,248 @@ import org.junit.Test; public class JmsSchedulerTest extends JobSchedulerTestSupport { - @Test - public void testCron() throws Exception { - final int COUNT = 10; - final AtomicInteger count = new AtomicInteger(); - Connection connection = createConnection(); + @Test + public void testCron() throws Exception { + final int COUNT = 10; + final AtomicInteger count = new AtomicInteger(); + Connection connection = createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); + MessageConsumer consumer = session.createConsumer(destination); - final CountDownLatch latch = new CountDownLatch(COUNT); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - latch.countDown(); - count.incrementAndGet(); + final CountDownLatch latch = new CountDownLatch(COUNT); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + latch.countDown(); + count.incrementAndGet(); + } + }); + + connection.start(); + MessageProducer producer = session.createProducer(destination); + TextMessage message = session.createTextMessage("test msg"); + long time = 1000; + message.setStringProperty(ScheduledMessage.AMQ_SCHEDULED_CRON, "* * * * *"); + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, 500); + message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, COUNT - 1); + + producer.send(message); + producer.close(); + + Thread.sleep(500); + SchedulerBroker sb = (SchedulerBroker) this.broker.getBroker().getAdaptor(SchedulerBroker.class); + JobScheduler js = sb.getJobScheduler(); + List list = js.getAllJobs(); + assertEquals(1, list.size()); + latch.await(240, TimeUnit.SECONDS); + assertEquals(COUNT, count.get()); + } + + @Test + public void testSchedule() throws Exception { + final int COUNT = 1; + Connection connection = createConnection(); + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + MessageConsumer consumer = session.createConsumer(destination); + + final CountDownLatch latch = new CountDownLatch(COUNT); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + latch.countDown(); + } + }); + + connection.start(); + long time = 5000; + MessageProducer producer = session.createProducer(destination); + TextMessage message = session.createTextMessage("test msg"); + + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); + + producer.send(message); + producer.close(); + // make sure the message isn't delivered early + Thread.sleep(2000); + assertEquals(latch.getCount(), COUNT); + latch.await(5, TimeUnit.SECONDS); + assertEquals(latch.getCount(), 0); + } + + @Test + public void testTransactedSchedule() throws Exception { + final int COUNT = 1; + Connection connection = createConnection(); + + final Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + + MessageConsumer consumer = session.createConsumer(destination); + + final CountDownLatch latch = new CountDownLatch(COUNT); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + try { + session.commit(); } - }); - - connection.start(); - MessageProducer producer = session.createProducer(destination); - TextMessage message = session.createTextMessage("test msg"); - long time = 1000; - message.setStringProperty(ScheduledMessage.AMQ_SCHEDULED_CRON, "* * * * *"); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, 500); - message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, COUNT - 1); - - producer.send(message); - producer.close(); - - Thread.sleep(500); - SchedulerBroker sb = (SchedulerBroker) this.broker.getBroker().getAdaptor(SchedulerBroker.class); - JobScheduler js = sb.getJobScheduler(); - List list = js.getAllJobs(); - assertEquals(1, list.size()); - latch.await(240, TimeUnit.SECONDS); - assertEquals(COUNT, count.get()); - } - - @Test - public void testSchedule() throws Exception { - final int COUNT = 1; - Connection connection = createConnection(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageConsumer consumer = session.createConsumer(destination); - - final CountDownLatch latch = new CountDownLatch(COUNT); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - latch.countDown(); + catch (JMSException e) { + e.printStackTrace(); } - }); + latch.countDown(); + } + }); - connection.start(); - long time = 5000; - MessageProducer producer = session.createProducer(destination); - TextMessage message = session.createTextMessage("test msg"); + connection.start(); + long time = 5000; + MessageProducer producer = session.createProducer(destination); + TextMessage message = session.createTextMessage("test msg"); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - producer.send(message); - producer.close(); - // make sure the message isn't delivered early - Thread.sleep(2000); - assertEquals(latch.getCount(), COUNT); - latch.await(5, TimeUnit.SECONDS); - assertEquals(latch.getCount(), 0); - } + producer.send(message); + session.commit(); + producer.close(); + // make sure the message isn't delivered early + Thread.sleep(2000); + assertEquals(latch.getCount(), COUNT); + latch.await(5, TimeUnit.SECONDS); + assertEquals(latch.getCount(), 0); + } - @Test - public void testTransactedSchedule() throws Exception { - final int COUNT = 1; - Connection connection = createConnection(); + @Test + public void testScheduleRepeated() throws Exception { + final int NUMBER = 10; + final AtomicInteger count = new AtomicInteger(); + Connection connection = createConnection(); - final Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); + MessageConsumer consumer = session.createConsumer(destination); - final CountDownLatch latch = new CountDownLatch(COUNT); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - try { - session.commit(); - } catch (JMSException e) { - e.printStackTrace(); - } - latch.countDown(); - } - }); + final CountDownLatch latch = new CountDownLatch(NUMBER); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + latch.countDown(); + count.incrementAndGet(); + } + }); - connection.start(); - long time = 5000; - MessageProducer producer = session.createProducer(destination); - TextMessage message = session.createTextMessage("test msg"); + connection.start(); + MessageProducer producer = session.createProducer(destination); + TextMessage message = session.createTextMessage("test msg"); + long time = 1000; + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, 500); + message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, NUMBER - 1); + producer.send(message); + producer.close(); + assertEquals(latch.getCount(), NUMBER); + latch.await(10, TimeUnit.SECONDS); + assertEquals(0, latch.getCount()); + // wait a little longer - make sure we only get NUMBER of replays + Thread.sleep(1000); + assertEquals(NUMBER, count.get()); + } - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); + @Test + public void testScheduleRestart() throws Exception { + // send a message + Connection connection = createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + connection.start(); + MessageProducer producer = session.createProducer(destination); + TextMessage message = session.createTextMessage("test msg"); + long time = 5000; + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); + producer.send(message); + producer.close(); - producer.send(message); - session.commit(); - producer.close(); - // make sure the message isn't delivered early - Thread.sleep(2000); - assertEquals(latch.getCount(), COUNT); - latch.await(5, TimeUnit.SECONDS); - assertEquals(latch.getCount(), 0); - } + //restart broker + broker.stop(); + broker.waitUntilStopped(); - @Test - public void testScheduleRepeated() throws Exception { - final int NUMBER = 10; - final AtomicInteger count = new AtomicInteger(); - Connection connection = createConnection(); + broker = createBroker(false); + broker.start(); + broker.waitUntilStarted(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + // consume the message + connection = createConnection(); + connection.start(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(destination); + Message msg = consumer.receive(5000); + assertNotNull("Didn't receive the message", msg); - MessageConsumer consumer = session.createConsumer(destination); + //send another message + producer = session.createProducer(destination); + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); + producer.send(message); + producer.close(); + } - final CountDownLatch latch = new CountDownLatch(NUMBER); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - latch.countDown(); - count.incrementAndGet(); - } - }); + @Test + public void testJobSchedulerStoreUsage() throws Exception { - connection.start(); - MessageProducer producer = session.createProducer(destination); - TextMessage message = session.createTextMessage("test msg"); - long time = 1000; - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, 500); - message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, NUMBER - 1); - producer.send(message); - producer.close(); - assertEquals(latch.getCount(), NUMBER); - latch.await(10, TimeUnit.SECONDS); - assertEquals(0, latch.getCount()); - // wait a little longer - make sure we only get NUMBER of replays - Thread.sleep(1000); - assertEquals(NUMBER, count.get()); - } + // Shrink the store limit down so we get the producer to block + broker.getSystemUsage().getJobSchedulerUsage().setLimit(10 * 1024); - @Test - public void testScheduleRestart() throws Exception { - // send a message - Connection connection = createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - connection.start(); - MessageProducer producer = session.createProducer(destination); - TextMessage message = session.createTextMessage("test msg"); - long time = 5000; - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - producer.send(message); - producer.close(); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + Connection conn = factory.createConnection(); + conn.start(); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + final long time = 5000; + final ProducerThread producer = new ProducerThread(sess, destination) { + @Override + protected Message createMessage(int i) throws Exception { + Message message = super.createMessage(i); + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); + return message; + } + }; + producer.setMessageCount(100); + producer.start(); - //restart broker - broker.stop(); - broker.waitUntilStopped(); + MessageConsumer consumer = sess.createConsumer(destination); + final CountDownLatch latch = new CountDownLatch(100); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + latch.countDown(); + } + }); - broker = createBroker(false); - broker.start(); - broker.waitUntilStarted(); + // wait for the producer to block, which should happen immediately, and also wait long + // enough for the delay to elapse. We should see no deliveries as the send should block + // on the first message. + Thread.sleep(10000L); + assertEquals(100, latch.getCount()); - // consume the message - connection = createConnection(); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); - Message msg = consumer.receive(5000); - assertNotNull("Didn't receive the message", msg); + // Increase the store limit so the producer unblocks. Everything should enqueue at this point. + broker.getSystemUsage().getJobSchedulerUsage().setLimit(1024 * 1024 * 33); - //send another message - producer = session.createProducer(destination); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - producer.send(message); - producer.close(); - } + // Wait long enough that the messages are enqueued and the delivery delay has elapsed. + Thread.sleep(10000L); - @Test - public void testJobSchedulerStoreUsage() throws Exception { + // Make sure we sent all the messages we expected to send + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return producer.getSentCount() == producer.getMessageCount(); + } + }, 20000L); - // Shrink the store limit down so we get the producer to block - broker.getSystemUsage().getJobSchedulerUsage().setLimit(10 * 1024); + assertEquals("Producer didn't send all messages", producer.getMessageCount(), producer.getSentCount()); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - Connection conn = factory.createConnection(); - conn.start(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - final long time = 5000; - final ProducerThread producer = new ProducerThread(sess, destination) { - @Override - protected Message createMessage(int i) throws Exception { - Message message = super.createMessage(i); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - return message; - } - }; - producer.setMessageCount(100); - producer.start(); + // Make sure we got all the messages we expected to get + latch.await(20000L, TimeUnit.MILLISECONDS); - MessageConsumer consumer = sess.createConsumer(destination); - final CountDownLatch latch = new CountDownLatch(100); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - latch.countDown(); - } - }); - - // wait for the producer to block, which should happen immediately, and also wait long - // enough for the delay to elapse. We should see no deliveries as the send should block - // on the first message. - Thread.sleep(10000L); - - assertEquals(100, latch.getCount()); - - // Increase the store limit so the producer unblocks. Everything should enqueue at this point. - broker.getSystemUsage().getJobSchedulerUsage().setLimit(1024 * 1024 * 33); - - // Wait long enough that the messages are enqueued and the delivery delay has elapsed. - Thread.sleep(10000L); - - // Make sure we sent all the messages we expected to send - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return producer.getSentCount() == producer.getMessageCount(); - } - }, 20000L); - - assertEquals("Producer didn't send all messages", producer.getMessageCount(), producer.getSentCount()); - - // Make sure we got all the messages we expected to get - latch.await(20000L, TimeUnit.MILLISECONDS); - - assertEquals("Consumer did not receive all messages.", 0, latch.getCount()); - } + assertEquals("Consumer did not receive all messages.", 0, latch.getCount()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerBrokerShutdownTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerBrokerShutdownTest.java index 641ee97247..d9bada00f9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerBrokerShutdownTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerBrokerShutdownTest.java @@ -30,49 +30,49 @@ import org.apache.activemq.util.ProducerThread; public class JobSchedulerBrokerShutdownTest extends EmbeddedBrokerTestSupport { - @Override - protected BrokerService createBroker() throws Exception { - File schedulerDirectory = new File("target/scheduler"); + @Override + protected BrokerService createBroker() throws Exception { + File schedulerDirectory = new File("target/scheduler"); - IOHelper.mkdirs(schedulerDirectory); - IOHelper.deleteChildren(schedulerDirectory); + IOHelper.mkdirs(schedulerDirectory); + IOHelper.deleteChildren(schedulerDirectory); - BrokerService broker = super.createBroker(); - broker.setSchedulerSupport(true); - broker.setDataDirectory("target"); - broker.setSchedulerDirectoryFile(schedulerDirectory); - broker.getSystemUsage().getStoreUsage().setLimit(1 * 512); - broker.deleteAllMessages(); - return broker; - } + BrokerService broker = super.createBroker(); + broker.setSchedulerSupport(true); + broker.setDataDirectory("target"); + broker.setSchedulerDirectoryFile(schedulerDirectory); + broker.getSystemUsage().getStoreUsage().setLimit(1 * 512); + broker.deleteAllMessages(); + return broker; + } - @Override - protected boolean isPersistent() { - return true; - } + @Override + protected boolean isPersistent() { + return true; + } - public void testSchedule() throws Exception { + public void testSchedule() throws Exception { - Connection connection = createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Connection connection = createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - connection.start(); - final long time = 1000; + connection.start(); + final long time = 1000; - ProducerThread producer = new ProducerThread(session, destination) { - @Override - protected Message createMessage(int i) throws Exception { - Message message = super.createMessage(i); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - return message; - } - }; + ProducerThread producer = new ProducerThread(session, destination) { + @Override + protected Message createMessage(int i) throws Exception { + Message message = super.createMessage(i); + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); + return message; + } + }; - producer.setMessageCount(200); - producer.setDaemon(true); + producer.setMessageCount(200); + producer.setDaemon(true); - producer.start(); + producer.start(); - Thread.sleep(5000); - } + Thread.sleep(5000); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerJmxManagementTests.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerJmxManagementTests.java index b5d2227088..b8ea674603 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerJmxManagementTests.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerJmxManagementTests.java @@ -42,114 +42,114 @@ import org.slf4j.LoggerFactory; */ public class JobSchedulerJmxManagementTests extends JobSchedulerTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(JobSchedulerJmxManagementTests.class); + private static final Logger LOG = LoggerFactory.getLogger(JobSchedulerJmxManagementTests.class); - @Test - public void testJobSchedulerMBeanIsRegistered() throws Exception { - JobSchedulerViewMBean view = getJobSchedulerMBean(); - assertNotNull(view); - assertTrue(view.getAllJobs().isEmpty()); - } + @Test + public void testJobSchedulerMBeanIsRegistered() throws Exception { + JobSchedulerViewMBean view = getJobSchedulerMBean(); + assertNotNull(view); + assertTrue(view.getAllJobs().isEmpty()); + } - @Test - public void testGetNumberOfJobs() throws Exception { - JobSchedulerViewMBean view = getJobSchedulerMBean(); - assertNotNull(view); - assertTrue(view.getAllJobs().isEmpty()); - scheduleMessage(60000, -1, -1); - assertFalse(view.getAllJobs().isEmpty()); - assertEquals(1, view.getAllJobs().size()); - scheduleMessage(60000, -1, -1); - assertEquals(2, view.getAllJobs().size()); - } + @Test + public void testGetNumberOfJobs() throws Exception { + JobSchedulerViewMBean view = getJobSchedulerMBean(); + assertNotNull(view); + assertTrue(view.getAllJobs().isEmpty()); + scheduleMessage(60000, -1, -1); + assertFalse(view.getAllJobs().isEmpty()); + assertEquals(1, view.getAllJobs().size()); + scheduleMessage(60000, -1, -1); + assertEquals(2, view.getAllJobs().size()); + } - @Test - public void testRemvoeJob() throws Exception { - JobSchedulerViewMBean view = getJobSchedulerMBean(); - assertNotNull(view); - assertTrue(view.getAllJobs().isEmpty()); - scheduleMessage(60000, -1, -1); - assertFalse(view.getAllJobs().isEmpty()); - TabularData jobs = view.getAllJobs(); - assertEquals(1, jobs.size()); - for (Object key : jobs.keySet()) { - String jobId = ((List)key).get(0).toString(); - LOG.info("Attempting to remove Job: {}", jobId); - view.removeJob(jobId); - } - assertTrue(view.getAllJobs().isEmpty()); - } + @Test + public void testRemvoeJob() throws Exception { + JobSchedulerViewMBean view = getJobSchedulerMBean(); + assertNotNull(view); + assertTrue(view.getAllJobs().isEmpty()); + scheduleMessage(60000, -1, -1); + assertFalse(view.getAllJobs().isEmpty()); + TabularData jobs = view.getAllJobs(); + assertEquals(1, jobs.size()); + for (Object key : jobs.keySet()) { + String jobId = ((List) key).get(0).toString(); + LOG.info("Attempting to remove Job: {}", jobId); + view.removeJob(jobId); + } + assertTrue(view.getAllJobs().isEmpty()); + } - @Test - public void testRemvoeJobInRange() throws Exception { - JobSchedulerViewMBean view = getJobSchedulerMBean(); - assertNotNull(view); - assertTrue(view.getAllJobs().isEmpty()); - scheduleMessage(60000, -1, -1); - assertFalse(view.getAllJobs().isEmpty()); - String now = JobSupport.getDateTime(System.currentTimeMillis()); - String later = JobSupport.getDateTime(System.currentTimeMillis() + 120 * 1000); - view.removeAllJobs(now, later); - assertTrue(view.getAllJobs().isEmpty()); - } + @Test + public void testRemvoeJobInRange() throws Exception { + JobSchedulerViewMBean view = getJobSchedulerMBean(); + assertNotNull(view); + assertTrue(view.getAllJobs().isEmpty()); + scheduleMessage(60000, -1, -1); + assertFalse(view.getAllJobs().isEmpty()); + String now = JobSupport.getDateTime(System.currentTimeMillis()); + String later = JobSupport.getDateTime(System.currentTimeMillis() + 120 * 1000); + view.removeAllJobs(now, later); + assertTrue(view.getAllJobs().isEmpty()); + } - @Test - public void testGetNextScheduledJob() throws Exception { - JobSchedulerViewMBean view = getJobSchedulerMBean(); - assertNotNull(view); - assertTrue(view.getAllJobs().isEmpty()); - scheduleMessage(60000, -1, -1); - assertFalse(view.getAllJobs().isEmpty()); - long before = System.currentTimeMillis() + 57 * 1000; - long toLate = System.currentTimeMillis() + 63 * 1000; - String next = view.getNextScheduleTime(); - long nextTime = JobSupport.getDataTime(next); - LOG.info("Next Scheduled Time: {} should be after: {}", next, JobSupport.getDateTime(before)); - assertTrue(nextTime > before); - assertTrue(nextTime < toLate); - } + @Test + public void testGetNextScheduledJob() throws Exception { + JobSchedulerViewMBean view = getJobSchedulerMBean(); + assertNotNull(view); + assertTrue(view.getAllJobs().isEmpty()); + scheduleMessage(60000, -1, -1); + assertFalse(view.getAllJobs().isEmpty()); + long before = System.currentTimeMillis() + 57 * 1000; + long toLate = System.currentTimeMillis() + 63 * 1000; + String next = view.getNextScheduleTime(); + long nextTime = JobSupport.getDataTime(next); + LOG.info("Next Scheduled Time: {} should be after: {}", next, JobSupport.getDateTime(before)); + assertTrue(nextTime > before); + assertTrue(nextTime < toLate); + } - @Test - public void testGetExecutionCount() throws Exception { - final JobSchedulerViewMBean view = getJobSchedulerMBean(); - assertNotNull(view); - assertTrue(view.getAllJobs().isEmpty()); - scheduleMessage(10000, 1000, 10); - assertFalse(view.getAllJobs().isEmpty()); - TabularData jobs = view.getAllJobs(); - assertEquals(1, jobs.size()); - String jobId = null; - for (Object key : jobs.keySet()) { - jobId = ((List)key).get(0).toString(); - } + @Test + public void testGetExecutionCount() throws Exception { + final JobSchedulerViewMBean view = getJobSchedulerMBean(); + assertNotNull(view); + assertTrue(view.getAllJobs().isEmpty()); + scheduleMessage(10000, 1000, 10); + assertFalse(view.getAllJobs().isEmpty()); + TabularData jobs = view.getAllJobs(); + assertEquals(1, jobs.size()); + String jobId = null; + for (Object key : jobs.keySet()) { + jobId = ((List) key).get(0).toString(); + } - final String fixedJobId = jobId; - LOG.info("Attempting to get execution count for Job: {}", jobId); - assertEquals(0, view.getExecutionCount(jobId)); + final String fixedJobId = jobId; + LOG.info("Attempting to get execution count for Job: {}", jobId); + assertEquals(0, view.getExecutionCount(jobId)); - assertTrue("Should execute again", Wait.waitFor(new Wait.Condition() { + assertTrue("Should execute again", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return view.getExecutionCount(fixedJobId) > 0; - } - })); - } + @Override + public boolean isSatisified() throws Exception { + return view.getExecutionCount(fixedJobId) > 0; + } + })); + } - @Override - protected boolean isUseJmx() { - return true; - } + @Override + protected boolean isUseJmx() { + return true; + } - protected void scheduleMessage(int time, int period, int repeat) throws Exception { - Connection connection = createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - TextMessage message = session.createTextMessage("test msg"); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, period); - message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, repeat); - producer.send(message); - connection.close(); - } + protected void scheduleMessage(int time, int period, int repeat) throws Exception { + Connection connection = createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + TextMessage message = session.createTextMessage("test msg"); + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, period); + message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, repeat); + producer.send(message); + connection.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerManagementTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerManagementTest.java index c82f8ef1b4..afedf7aad9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerManagementTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerManagementTest.java @@ -41,369 +41,371 @@ import org.slf4j.LoggerFactory; public class JobSchedulerManagementTest extends JobSchedulerTestSupport { - private static final transient Logger LOG = LoggerFactory.getLogger(JobSchedulerManagementTest.class); - - @Test - public void testRemoveAllScheduled() throws Exception { - final int COUNT = 5; - Connection connection = createConnection(); - - // Setup the scheduled Message - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(6), COUNT); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // Create the Browse Destination and the Reply To location - Destination management = session.createTopic(ScheduledMessage.AMQ_SCHEDULER_MANAGEMENT_DESTINATION); - - // Create the eventual Consumer to receive the scheduled message - MessageConsumer consumer = session.createConsumer(destination); - - final CountDownLatch latch = new CountDownLatch(COUNT); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - latch.countDown(); - } - }); - - connection.start(); - - // Send the remove request - MessageProducer producer = session.createProducer(management); - Message request = session.createMessage(); - request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_REMOVEALL); - producer.send(request); - - // Now wait and see if any get delivered, none should. - latch.await(10, TimeUnit.SECONDS); - assertEquals(latch.getCount(), COUNT); - } - - @Test - public void testRemoveAllScheduledAtTime() throws Exception { - final int COUNT = 3; - Connection connection = createConnection(); - - // Setup the scheduled Message - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(6)); - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(15)); - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(20)); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // Create the Browse Destination and the Reply To location - Destination management = session.createTopic(ScheduledMessage.AMQ_SCHEDULER_MANAGEMENT_DESTINATION); - Destination browseDest = session.createTemporaryQueue(); - - // Create the eventual Consumer to receive the scheduled message - MessageConsumer consumer = session.createConsumer(destination); - - final CountDownLatch latch = new CountDownLatch(COUNT); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - latch.countDown(); - } - }); - - // Create the "Browser" - MessageConsumer browser = session.createConsumer(browseDest); - final CountDownLatch browsedLatch = new CountDownLatch(COUNT); - browser.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - browsedLatch.countDown(); - LOG.debug("Scheduled Message Browser got Message: " + message); - } - }); - - connection.start(); - - long start = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(10); - long end = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(30); - - // Send the remove request - MessageProducer producer = session.createProducer(management); - Message request = session.createMessage(); - request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_REMOVEALL); - request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION_START_TIME, Long.toString(start)); - request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION_END_TIME, Long.toString(end)); - producer.send(request); - - // Send the browse request - request = session.createMessage(); - request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_BROWSE); - request.setJMSReplyTo(browseDest); - producer.send(request); - - // now see if we got back only the one remaining message. - latch.await(10, TimeUnit.SECONDS); - assertEquals(2, browsedLatch.getCount()); - - // Now wait and see if any get delivered, none should. - latch.await(10, TimeUnit.SECONDS); - assertEquals(2, latch.getCount()); - } - - @Test - public void testBrowseAllScheduled() throws Exception { - final int COUNT = 10; - Connection connection = createConnection(); - - // Setup the scheduled Message - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(9), COUNT); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // Create the Browse Destination and the Reply To location - Destination requestBrowse = session.createTopic(ScheduledMessage.AMQ_SCHEDULER_MANAGEMENT_DESTINATION); - Destination browseDest = session.createTemporaryQueue(); - - // Create the eventual Consumer to receive the scheduled message - MessageConsumer consumer = session.createConsumer(destination); - - final CountDownLatch latch = new CountDownLatch(COUNT); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - latch.countDown(); - } - }); - - // Create the "Browser" - MessageConsumer browser = session.createConsumer(browseDest); - final CountDownLatch browsedLatch = new CountDownLatch(COUNT); - browser.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - browsedLatch.countDown(); - LOG.debug("Scheduled Message Browser got Message: " + message); - } - }); - - connection.start(); - - // Send the browse request - MessageProducer producer = session.createProducer(requestBrowse); - Message request = session.createMessage(); - request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_BROWSE); - request.setJMSReplyTo(browseDest); - producer.send(request); - - // make sure the message isn't delivered early because we browsed it - Thread.sleep(2000); - assertEquals(latch.getCount(), COUNT); - - // now see if we got all the scheduled messages on the browse - // destination. - latch.await(10, TimeUnit.SECONDS); - assertEquals(browsedLatch.getCount(), 0); - - // now check that they all got delivered - latch.await(10, TimeUnit.SECONDS); - assertEquals(latch.getCount(), 0); - } - - @Test - public void testBrowseWindowlScheduled() throws Exception { - final int COUNT = 10; - Connection connection = createConnection(); - - // Setup the scheduled Message - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(5)); - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(10), COUNT); - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(20)); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // Create the Browse Destination and the Reply To location - Destination requestBrowse = session.createTopic(ScheduledMessage.AMQ_SCHEDULER_MANAGEMENT_DESTINATION); - Destination browseDest = session.createTemporaryQueue(); - - // Create the eventual Consumer to receive the scheduled message - MessageConsumer consumer = session.createConsumer(destination); - - final CountDownLatch latch = new CountDownLatch(COUNT + 2); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - latch.countDown(); - } - }); - - // Create the "Browser" - MessageConsumer browser = session.createConsumer(browseDest); - final CountDownLatch browsedLatch = new CountDownLatch(COUNT); - browser.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - browsedLatch.countDown(); - LOG.debug("Scheduled Message Browser got Message: " + message); - } - }); - - connection.start(); - - long start = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(6); - long end = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(15); - - // Send the browse request - MessageProducer producer = session.createProducer(requestBrowse); - Message request = session.createMessage(); - request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_BROWSE); - request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION_START_TIME, Long.toString(start)); - request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION_END_TIME, Long.toString(end)); - request.setJMSReplyTo(browseDest); - producer.send(request); - - // make sure the message isn't delivered early because we browsed it - Thread.sleep(2000); - assertEquals(COUNT + 2, latch.getCount()); - - // now see if we got all the scheduled messages on the browse - // destination. - latch.await(15, TimeUnit.SECONDS); - assertEquals(0, browsedLatch.getCount()); - - // now see if we got all the scheduled messages on the browse - // destination. - latch.await(20, TimeUnit.SECONDS); - assertEquals(0, latch.getCount()); - } - - @Test - public void testRemoveScheduled() throws Exception { - final int COUNT = 10; - Connection connection = createConnection(); - - // Setup the scheduled Message - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(9), COUNT); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // Create the Browse Destination and the Reply To location - Destination management = session.createTopic(ScheduledMessage.AMQ_SCHEDULER_MANAGEMENT_DESTINATION); - Destination browseDest = session.createTemporaryQueue(); - - // Create the eventual Consumer to receive the scheduled message - MessageConsumer consumer = session.createConsumer(destination); - MessageProducer producer = session.createProducer(management); - - final CountDownLatch latch = new CountDownLatch(COUNT); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - latch.countDown(); - } - }); - - // Create the "Browser" - Session browseSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer browser = browseSession.createConsumer(browseDest); - - connection.start(); - - // Send the browse request - Message request = session.createMessage(); - request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_BROWSE); - request.setJMSReplyTo(browseDest); - producer.send(request); - - // Browse all the Scheduled Messages. - for (int i = 0; i < COUNT; ++i) { - Message message = browser.receive(2000); - assertNotNull(message); - - try { - Message remove = session.createMessage(); - remove.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_REMOVE); - remove.setStringProperty(ScheduledMessage.AMQ_SCHEDULED_ID, message.getStringProperty(ScheduledMessage.AMQ_SCHEDULED_ID)); - producer.send(remove); - } catch (Exception e) { - } - } - - // now check that they all got removed and are not delivered. - latch.await(11, TimeUnit.SECONDS); - assertEquals(COUNT, latch.getCount()); - } - - @Test - public void testRemoveNotScheduled() throws Exception { - Connection connection = createConnection(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // Create the Browse Destination and the Reply To location - Destination management = session.createTopic(ScheduledMessage.AMQ_SCHEDULER_MANAGEMENT_DESTINATION); - - MessageProducer producer = session.createProducer(management); - - try { - - // Send the remove request + private static final transient Logger LOG = LoggerFactory.getLogger(JobSchedulerManagementTest.class); + + @Test + public void testRemoveAllScheduled() throws Exception { + final int COUNT = 5; + Connection connection = createConnection(); + + // Setup the scheduled Message + scheduleMessage(connection, TimeUnit.SECONDS.toMillis(6), COUNT); + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + // Create the Browse Destination and the Reply To location + Destination management = session.createTopic(ScheduledMessage.AMQ_SCHEDULER_MANAGEMENT_DESTINATION); + + // Create the eventual Consumer to receive the scheduled message + MessageConsumer consumer = session.createConsumer(destination); + + final CountDownLatch latch = new CountDownLatch(COUNT); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + latch.countDown(); + } + }); + + connection.start(); + + // Send the remove request + MessageProducer producer = session.createProducer(management); + Message request = session.createMessage(); + request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_REMOVEALL); + producer.send(request); + + // Now wait and see if any get delivered, none should. + latch.await(10, TimeUnit.SECONDS); + assertEquals(latch.getCount(), COUNT); + } + + @Test + public void testRemoveAllScheduledAtTime() throws Exception { + final int COUNT = 3; + Connection connection = createConnection(); + + // Setup the scheduled Message + scheduleMessage(connection, TimeUnit.SECONDS.toMillis(6)); + scheduleMessage(connection, TimeUnit.SECONDS.toMillis(15)); + scheduleMessage(connection, TimeUnit.SECONDS.toMillis(20)); + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + // Create the Browse Destination and the Reply To location + Destination management = session.createTopic(ScheduledMessage.AMQ_SCHEDULER_MANAGEMENT_DESTINATION); + Destination browseDest = session.createTemporaryQueue(); + + // Create the eventual Consumer to receive the scheduled message + MessageConsumer consumer = session.createConsumer(destination); + + final CountDownLatch latch = new CountDownLatch(COUNT); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + latch.countDown(); + } + }); + + // Create the "Browser" + MessageConsumer browser = session.createConsumer(browseDest); + final CountDownLatch browsedLatch = new CountDownLatch(COUNT); + browser.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + browsedLatch.countDown(); + LOG.debug("Scheduled Message Browser got Message: " + message); + } + }); + + connection.start(); + + long start = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(10); + long end = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(30); + + // Send the remove request + MessageProducer producer = session.createProducer(management); + Message request = session.createMessage(); + request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_REMOVEALL); + request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION_START_TIME, Long.toString(start)); + request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION_END_TIME, Long.toString(end)); + producer.send(request); + + // Send the browse request + request = session.createMessage(); + request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_BROWSE); + request.setJMSReplyTo(browseDest); + producer.send(request); + + // now see if we got back only the one remaining message. + latch.await(10, TimeUnit.SECONDS); + assertEquals(2, browsedLatch.getCount()); + + // Now wait and see if any get delivered, none should. + latch.await(10, TimeUnit.SECONDS); + assertEquals(2, latch.getCount()); + } + + @Test + public void testBrowseAllScheduled() throws Exception { + final int COUNT = 10; + Connection connection = createConnection(); + + // Setup the scheduled Message + scheduleMessage(connection, TimeUnit.SECONDS.toMillis(9), COUNT); + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + // Create the Browse Destination and the Reply To location + Destination requestBrowse = session.createTopic(ScheduledMessage.AMQ_SCHEDULER_MANAGEMENT_DESTINATION); + Destination browseDest = session.createTemporaryQueue(); + + // Create the eventual Consumer to receive the scheduled message + MessageConsumer consumer = session.createConsumer(destination); + + final CountDownLatch latch = new CountDownLatch(COUNT); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + latch.countDown(); + } + }); + + // Create the "Browser" + MessageConsumer browser = session.createConsumer(browseDest); + final CountDownLatch browsedLatch = new CountDownLatch(COUNT); + browser.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + browsedLatch.countDown(); + LOG.debug("Scheduled Message Browser got Message: " + message); + } + }); + + connection.start(); + + // Send the browse request + MessageProducer producer = session.createProducer(requestBrowse); + Message request = session.createMessage(); + request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_BROWSE); + request.setJMSReplyTo(browseDest); + producer.send(request); + + // make sure the message isn't delivered early because we browsed it + Thread.sleep(2000); + assertEquals(latch.getCount(), COUNT); + + // now see if we got all the scheduled messages on the browse + // destination. + latch.await(10, TimeUnit.SECONDS); + assertEquals(browsedLatch.getCount(), 0); + + // now check that they all got delivered + latch.await(10, TimeUnit.SECONDS); + assertEquals(latch.getCount(), 0); + } + + @Test + public void testBrowseWindowlScheduled() throws Exception { + final int COUNT = 10; + Connection connection = createConnection(); + + // Setup the scheduled Message + scheduleMessage(connection, TimeUnit.SECONDS.toMillis(5)); + scheduleMessage(connection, TimeUnit.SECONDS.toMillis(10), COUNT); + scheduleMessage(connection, TimeUnit.SECONDS.toMillis(20)); + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + // Create the Browse Destination and the Reply To location + Destination requestBrowse = session.createTopic(ScheduledMessage.AMQ_SCHEDULER_MANAGEMENT_DESTINATION); + Destination browseDest = session.createTemporaryQueue(); + + // Create the eventual Consumer to receive the scheduled message + MessageConsumer consumer = session.createConsumer(destination); + + final CountDownLatch latch = new CountDownLatch(COUNT + 2); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + latch.countDown(); + } + }); + + // Create the "Browser" + MessageConsumer browser = session.createConsumer(browseDest); + final CountDownLatch browsedLatch = new CountDownLatch(COUNT); + browser.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + browsedLatch.countDown(); + LOG.debug("Scheduled Message Browser got Message: " + message); + } + }); + + connection.start(); + + long start = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(6); + long end = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(15); + + // Send the browse request + MessageProducer producer = session.createProducer(requestBrowse); + Message request = session.createMessage(); + request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_BROWSE); + request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION_START_TIME, Long.toString(start)); + request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION_END_TIME, Long.toString(end)); + request.setJMSReplyTo(browseDest); + producer.send(request); + + // make sure the message isn't delivered early because we browsed it + Thread.sleep(2000); + assertEquals(COUNT + 2, latch.getCount()); + + // now see if we got all the scheduled messages on the browse + // destination. + latch.await(15, TimeUnit.SECONDS); + assertEquals(0, browsedLatch.getCount()); + + // now see if we got all the scheduled messages on the browse + // destination. + latch.await(20, TimeUnit.SECONDS); + assertEquals(0, latch.getCount()); + } + + @Test + public void testRemoveScheduled() throws Exception { + final int COUNT = 10; + Connection connection = createConnection(); + + // Setup the scheduled Message + scheduleMessage(connection, TimeUnit.SECONDS.toMillis(9), COUNT); + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + // Create the Browse Destination and the Reply To location + Destination management = session.createTopic(ScheduledMessage.AMQ_SCHEDULER_MANAGEMENT_DESTINATION); + Destination browseDest = session.createTemporaryQueue(); + + // Create the eventual Consumer to receive the scheduled message + MessageConsumer consumer = session.createConsumer(destination); + MessageProducer producer = session.createProducer(management); + + final CountDownLatch latch = new CountDownLatch(COUNT); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + latch.countDown(); + } + }); + + // Create the "Browser" + Session browseSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer browser = browseSession.createConsumer(browseDest); + + connection.start(); + + // Send the browse request + Message request = session.createMessage(); + request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_BROWSE); + request.setJMSReplyTo(browseDest); + producer.send(request); + + // Browse all the Scheduled Messages. + for (int i = 0; i < COUNT; ++i) { + Message message = browser.receive(2000); + assertNotNull(message); + + try { Message remove = session.createMessage(); - remove.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_REMOVEALL); - remove.setStringProperty(ScheduledMessage.AMQ_SCHEDULED_ID, new IdGenerator().generateId()); + remove.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_REMOVE); + remove.setStringProperty(ScheduledMessage.AMQ_SCHEDULED_ID, message.getStringProperty(ScheduledMessage.AMQ_SCHEDULED_ID)); producer.send(remove); - } catch (Exception e) { - fail("Caught unexpected exception during remove of unscheduled message."); - } - } + } + catch (Exception e) { + } + } - @Test - public void testBrowseWithSelector() throws Exception { - Connection connection = createConnection(); + // now check that they all got removed and are not delivered. + latch.await(11, TimeUnit.SECONDS); + assertEquals(COUNT, latch.getCount()); + } - // Setup the scheduled Message - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(9)); - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(10)); - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(5)); - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(45)); + @Test + public void testRemoveNotScheduled() throws Exception { + Connection connection = createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - // Create the Browse Destination and the Reply To location - Destination requestBrowse = session.createTopic(ScheduledMessage.AMQ_SCHEDULER_MANAGEMENT_DESTINATION); - Destination browseDest = session.createTemporaryTopic(); + // Create the Browse Destination and the Reply To location + Destination management = session.createTopic(ScheduledMessage.AMQ_SCHEDULER_MANAGEMENT_DESTINATION); - // Create the "Browser" - MessageConsumer browser = session.createConsumer(browseDest, ScheduledMessage.AMQ_SCHEDULED_DELAY + " = 45000"); + MessageProducer producer = session.createProducer(management); - connection.start(); + try { - // Send the browse request - MessageProducer producer = session.createProducer(requestBrowse); - Message request = session.createMessage(); - request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_BROWSE); - request.setJMSReplyTo(browseDest); - producer.send(request); + // Send the remove request + Message remove = session.createMessage(); + remove.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_REMOVEALL); + remove.setStringProperty(ScheduledMessage.AMQ_SCHEDULED_ID, new IdGenerator().generateId()); + producer.send(remove); + } + catch (Exception e) { + fail("Caught unexpected exception during remove of unscheduled message."); + } + } - // Now try and receive the one we selected - Message message = browser.receive(5000); - assertNotNull(message); - assertEquals(45000, message.getLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY)); + @Test + public void testBrowseWithSelector() throws Exception { + Connection connection = createConnection(); - // Now check if there are anymore, there shouldn't be - message = browser.receive(5000); - assertNull(message); - } + // Setup the scheduled Message + scheduleMessage(connection, TimeUnit.SECONDS.toMillis(9)); + scheduleMessage(connection, TimeUnit.SECONDS.toMillis(10)); + scheduleMessage(connection, TimeUnit.SECONDS.toMillis(5)); + scheduleMessage(connection, TimeUnit.SECONDS.toMillis(45)); - protected void scheduleMessage(Connection connection, long delay) throws Exception { - scheduleMessage(connection, delay, 1); - } + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - protected void scheduleMessage(Connection connection, long delay, int count) throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - TextMessage message = session.createTextMessage("test msg"); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay); + // Create the Browse Destination and the Reply To location + Destination requestBrowse = session.createTopic(ScheduledMessage.AMQ_SCHEDULER_MANAGEMENT_DESTINATION); + Destination browseDest = session.createTemporaryTopic(); - for (int i = 0; i < count; ++i) { - producer.send(message); - } + // Create the "Browser" + MessageConsumer browser = session.createConsumer(browseDest, ScheduledMessage.AMQ_SCHEDULED_DELAY + " = 45000"); - producer.close(); - } + connection.start(); + + // Send the browse request + MessageProducer producer = session.createProducer(requestBrowse); + Message request = session.createMessage(); + request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_BROWSE); + request.setJMSReplyTo(browseDest); + producer.send(request); + + // Now try and receive the one we selected + Message message = browser.receive(5000); + assertNotNull(message); + assertEquals(45000, message.getLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY)); + + // Now check if there are anymore, there shouldn't be + message = browser.receive(5000); + assertNull(message); + } + + protected void scheduleMessage(Connection connection, long delay) throws Exception { + scheduleMessage(connection, delay, 1); + } + + protected void scheduleMessage(Connection connection, long delay, int count) throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + TextMessage message = session.createTextMessage("test msg"); + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay); + + for (int i = 0; i < count; ++i) { + producer.send(message); + } + + producer.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerStoreCheckpointTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerStoreCheckpointTest.java index c013a4c5f0..7abf7fb272 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerStoreCheckpointTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerStoreCheckpointTest.java @@ -37,89 +37,89 @@ import org.slf4j.LoggerFactory; public class JobSchedulerStoreCheckpointTest { - static final Logger LOG = LoggerFactory.getLogger(JobSchedulerStoreCheckpointTest.class); + static final Logger LOG = LoggerFactory.getLogger(JobSchedulerStoreCheckpointTest.class); - private JobSchedulerStoreImpl store; - private JobScheduler scheduler; - private ByteSequence payload; + private JobSchedulerStoreImpl store; + private JobScheduler scheduler; + private ByteSequence payload; - @Before - public void setUp() throws Exception { - File directory = new File("target/test/ScheduledJobsDB"); - IOHelper.mkdirs(directory); - IOHelper.deleteChildren(directory); - startStore(directory); + @Before + public void setUp() throws Exception { + File directory = new File("target/test/ScheduledJobsDB"); + IOHelper.mkdirs(directory); + IOHelper.deleteChildren(directory); + startStore(directory); - byte[] data = new byte[8192]; - for (int i = 0; i < data.length; ++i) { - data[i] = (byte) (i % 256); - } + byte[] data = new byte[8192]; + for (int i = 0; i < data.length; ++i) { + data[i] = (byte) (i % 256); + } - payload = new ByteSequence(data); - } + payload = new ByteSequence(data); + } - protected void startStore(File directory) throws Exception { - store = new JobSchedulerStoreImpl(); - store.setDirectory(directory); - store.setCheckpointInterval(5000); - store.setCleanupInterval(10000); - store.setJournalMaxFileLength(10 * 1024); - store.start(); - scheduler = store.getJobScheduler("test"); - scheduler.startDispatching(); - } + protected void startStore(File directory) throws Exception { + store = new JobSchedulerStoreImpl(); + store.setDirectory(directory); + store.setCheckpointInterval(5000); + store.setCleanupInterval(10000); + store.setJournalMaxFileLength(10 * 1024); + store.start(); + scheduler = store.getJobScheduler("test"); + scheduler.startDispatching(); + } - private int getNumJournalFiles() throws IOException { - return store.getJournal().getFileMap().size(); - } + private int getNumJournalFiles() throws IOException { + return store.getJournal().getFileMap().size(); + } - @After - public void tearDown() throws Exception { - scheduler.stopDispatching(); - store.stop(); - } + @After + public void tearDown() throws Exception { + scheduler.stopDispatching(); + store.stop(); + } - @Test - public void test() throws Exception { - final int COUNT = 10; - final CountDownLatch latch = new CountDownLatch(COUNT); - scheduler.addListener(new JobListener() { - @Override - public void scheduledJob(String id, ByteSequence job) { - latch.countDown(); - } - }); + @Test + public void test() throws Exception { + final int COUNT = 10; + final CountDownLatch latch = new CountDownLatch(COUNT); + scheduler.addListener(new JobListener() { + @Override + public void scheduledJob(String id, ByteSequence job) { + latch.countDown(); + } + }); - long time = TimeUnit.SECONDS.toMillis(30); - for (int i = 0; i < COUNT; i++) { - scheduler.schedule("id" + i, payload, "", time, 0, 0); - } + long time = TimeUnit.SECONDS.toMillis(30); + for (int i = 0; i < COUNT; i++) { + scheduler.schedule("id" + i, payload, "", time, 0, 0); + } - int size = scheduler.getAllJobs().size(); - assertEquals(size, COUNT); + int size = scheduler.getAllJobs().size(); + assertEquals(size, COUNT); - LOG.info("Number of journal log files: {}", getNumJournalFiles()); - // need a little slack so go over 60 seconds - assertTrue(latch.await(70, TimeUnit.SECONDS)); - assertEquals(0, latch.getCount()); + LOG.info("Number of journal log files: {}", getNumJournalFiles()); + // need a little slack so go over 60 seconds + assertTrue(latch.await(70, TimeUnit.SECONDS)); + assertEquals(0, latch.getCount()); - for (int i = 0; i < COUNT; i++) { - scheduler.schedule("id" + i, payload, "", time, 0, 0); - } + for (int i = 0; i < COUNT; i++) { + scheduler.schedule("id" + i, payload, "", time, 0, 0); + } - LOG.info("Number of journal log files: {}", getNumJournalFiles()); - // need a little slack so go over 60 seconds - assertTrue(latch.await(70, TimeUnit.SECONDS)); - assertEquals(0, latch.getCount()); + LOG.info("Number of journal log files: {}", getNumJournalFiles()); + // need a little slack so go over 60 seconds + assertTrue(latch.await(70, TimeUnit.SECONDS)); + assertEquals(0, latch.getCount()); - assertTrue("Should be only one log left: " + getNumJournalFiles(), Wait.waitFor(new Wait.Condition() { + assertTrue("Should be only one log left: " + getNumJournalFiles(), Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return getNumJournalFiles() == 1; - } - }, TimeUnit.MINUTES.toMillis(2))); + @Override + public boolean isSatisified() throws Exception { + return getNumJournalFiles() == 1; + } + }, TimeUnit.MINUTES.toMillis(2))); - LOG.info("Number of journal log files: {}", getNumJournalFiles()); - } + LOG.info("Number of journal log files: {}", getNumJournalFiles()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerStoreTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerStoreTest.java index df1e7ff838..c816d45649 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerStoreTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerStoreTest.java @@ -31,47 +31,47 @@ import org.slf4j.LoggerFactory; public class JobSchedulerStoreTest { - private static final Logger LOG = LoggerFactory.getLogger(JobSchedulerStoreTest.class); + private static final Logger LOG = LoggerFactory.getLogger(JobSchedulerStoreTest.class); - @Test(timeout = 120 * 1000) - public void testRestart() throws Exception { - JobSchedulerStore store = new JobSchedulerStoreImpl(); - File directory = new File("target/test/ScheduledDB"); - IOHelper.mkdirs(directory); - IOHelper.deleteChildren(directory); - store.setDirectory(directory); - final int NUMBER = 1000; - store.start(); - List list = new ArrayList(); - for (int i = 0; i < NUMBER; i++) { - ByteSequence buff = new ByteSequence(new String("testjob" + i).getBytes()); - list.add(buff); - } + @Test(timeout = 120 * 1000) + public void testRestart() throws Exception { + JobSchedulerStore store = new JobSchedulerStoreImpl(); + File directory = new File("target/test/ScheduledDB"); + IOHelper.mkdirs(directory); + IOHelper.deleteChildren(directory); + store.setDirectory(directory); + final int NUMBER = 1000; + store.start(); + List list = new ArrayList(); + for (int i = 0; i < NUMBER; i++) { + ByteSequence buff = new ByteSequence(new String("testjob" + i).getBytes()); + list.add(buff); + } - JobScheduler js = store.getJobScheduler("test"); - js.startDispatching(); - int count = 0; - long startTime = 10 * 60 * 1000; - long period = startTime; - for (ByteSequence job : list) { - js.schedule("id:" + (count++), job, "", startTime, period, -1); - } + JobScheduler js = store.getJobScheduler("test"); + js.startDispatching(); + int count = 0; + long startTime = 10 * 60 * 1000; + long period = startTime; + for (ByteSequence job : list) { + js.schedule("id:" + (count++), job, "", startTime, period, -1); + } - List test = js.getAllJobs(); - LOG.debug("Found {} jobs in the store before restart", test.size()); - assertEquals(list.size(), test.size()); - store.stop(); + List test = js.getAllJobs(); + LOG.debug("Found {} jobs in the store before restart", test.size()); + assertEquals(list.size(), test.size()); + store.stop(); - store.start(); - js = store.getJobScheduler("test"); - test = js.getAllJobs(); - LOG.debug("Found {} jobs in the store after restart", test.size()); - assertEquals(list.size(), test.size()); + store.start(); + js = store.getJobScheduler("test"); + test = js.getAllJobs(); + LOG.debug("Found {} jobs in the store after restart", test.size()); + assertEquals(list.size(), test.size()); - for (int i = 0; i < list.size(); i++) { - String orig = new String(list.get(i).getData()); - String payload = new String(test.get(i).getPayload()); - assertEquals(orig, payload); - } - } + for (int i = 0; i < list.size(); i++) { + String orig = new String(list.get(i).getData()); + String payload = new String(test.get(i).getPayload()); + assertEquals(orig, payload); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerTest.java index bc0fab7225..b77d0eb4a5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerTest.java @@ -36,262 +36,262 @@ import org.slf4j.LoggerFactory; public class JobSchedulerTest { - private static final Logger LOG = LoggerFactory.getLogger(JobSchedulerTest.class); + private static final Logger LOG = LoggerFactory.getLogger(JobSchedulerTest.class); - private JobSchedulerStore store; - private JobScheduler scheduler; + private JobSchedulerStore store; + private JobScheduler scheduler; - @Test - public void testAddLongStringByteSequence() throws Exception { - final int COUNT = 10; - final CountDownLatch latch = new CountDownLatch(COUNT); - scheduler.addListener(new JobListener() { - @Override - public void scheduledJob(String id, ByteSequence job) { - latch.countDown(); - } + @Test + public void testAddLongStringByteSequence() throws Exception { + final int COUNT = 10; + final CountDownLatch latch = new CountDownLatch(COUNT); + scheduler.addListener(new JobListener() { + @Override + public void scheduledJob(String id, ByteSequence job) { + latch.countDown(); + } - }); - for (int i = 0; i < COUNT; i++) { - String test = new String("test" + i); - scheduler.schedule("id" + i, new ByteSequence(test.getBytes()), 1000); - } - latch.await(5, TimeUnit.SECONDS); - assertEquals(0, latch.getCount()); - } + }); + for (int i = 0; i < COUNT; i++) { + String test = new String("test" + i); + scheduler.schedule("id" + i, new ByteSequence(test.getBytes()), 1000); + } + latch.await(5, TimeUnit.SECONDS); + assertEquals(0, latch.getCount()); + } - @Test - public void testAddCronAndByteSequence() throws Exception { + @Test + public void testAddCronAndByteSequence() throws Exception { - final CountDownLatch latch = new CountDownLatch(1); - scheduler.addListener(new JobListener() { - @Override - public void scheduledJob(String id, ByteSequence job) { - latch.countDown(); - } - }); + final CountDownLatch latch = new CountDownLatch(1); + scheduler.addListener(new JobListener() { + @Override + public void scheduledJob(String id, ByteSequence job) { + latch.countDown(); + } + }); - Calendar current = Calendar.getInstance(); - current.add(Calendar.MINUTE, 1); - int minutes = current.get(Calendar.MINUTE); - int hour = current.get(Calendar.HOUR_OF_DAY); - int day = current.get(Calendar.DAY_OF_WEEK) - 1; + Calendar current = Calendar.getInstance(); + current.add(Calendar.MINUTE, 1); + int minutes = current.get(Calendar.MINUTE); + int hour = current.get(Calendar.HOUR_OF_DAY); + int day = current.get(Calendar.DAY_OF_WEEK) - 1; - String cronTab = String.format("%d %d * * %d", minutes, hour, day); + String cronTab = String.format("%d %d * * %d", minutes, hour, day); - String str = new String("test1"); - scheduler.schedule("id:1", new ByteSequence(str.getBytes()), cronTab, 0, 0, 0); + String str = new String("test1"); + scheduler.schedule("id:1", new ByteSequence(str.getBytes()), cronTab, 0, 0, 0); - // need a little slack so go over 60 seconds - assertTrue(latch.await(70, TimeUnit.SECONDS)); - assertEquals(0, latch.getCount()); - } + // need a little slack so go over 60 seconds + assertTrue(latch.await(70, TimeUnit.SECONDS)); + assertEquals(0, latch.getCount()); + } - @Test - public void testAddLongLongIntStringByteSequence() throws Exception { - final int COUNT = 10; - final CountDownLatch latch = new CountDownLatch(COUNT); - scheduler.addListener(new JobListener() { - @Override - public void scheduledJob(String id, ByteSequence job) { - latch.countDown(); - } - }); - long time = 2000; - for (int i = 0; i < COUNT; i++) { - String test = new String("test" + i); - scheduler.schedule("id" + i, new ByteSequence(test.getBytes()), "", time, 10, -1); - } - assertTrue(latch.getCount() == COUNT); - latch.await(3000, TimeUnit.SECONDS); - assertTrue(latch.getCount() == 0); - } + @Test + public void testAddLongLongIntStringByteSequence() throws Exception { + final int COUNT = 10; + final CountDownLatch latch = new CountDownLatch(COUNT); + scheduler.addListener(new JobListener() { + @Override + public void scheduledJob(String id, ByteSequence job) { + latch.countDown(); + } + }); + long time = 2000; + for (int i = 0; i < COUNT; i++) { + String test = new String("test" + i); + scheduler.schedule("id" + i, new ByteSequence(test.getBytes()), "", time, 10, -1); + } + assertTrue(latch.getCount() == COUNT); + latch.await(3000, TimeUnit.SECONDS); + assertTrue(latch.getCount() == 0); + } - @Test - public void testAddStopThenDeliver() throws Exception { - final int COUNT = 10; - final CountDownLatch latch = new CountDownLatch(COUNT); - long time = 2000; - for (int i = 0; i < COUNT; i++) { - String test = new String("test" + i); - scheduler.schedule("id" + i, new ByteSequence(test.getBytes()), "", time, 1000, -1); - } - File directory = store.getDirectory(); - tearDown(); - startStore(directory); - scheduler.addListener(new JobListener() { - @Override - public void scheduledJob(String id, ByteSequence job) { - latch.countDown(); - } - }); - assertTrue(latch.getCount() == COUNT); - latch.await(3000, TimeUnit.SECONDS); - assertTrue(latch.getCount() == 0); - } + @Test + public void testAddStopThenDeliver() throws Exception { + final int COUNT = 10; + final CountDownLatch latch = new CountDownLatch(COUNT); + long time = 2000; + for (int i = 0; i < COUNT; i++) { + String test = new String("test" + i); + scheduler.schedule("id" + i, new ByteSequence(test.getBytes()), "", time, 1000, -1); + } + File directory = store.getDirectory(); + tearDown(); + startStore(directory); + scheduler.addListener(new JobListener() { + @Override + public void scheduledJob(String id, ByteSequence job) { + latch.countDown(); + } + }); + assertTrue(latch.getCount() == COUNT); + latch.await(3000, TimeUnit.SECONDS); + assertTrue(latch.getCount() == 0); + } - @Test - public void testRemoveLong() throws Exception { - final int COUNT = 10; + @Test + public void testRemoveLong() throws Exception { + final int COUNT = 10; - long time = 60000; - for (int i = 0; i < COUNT; i++) { - String str = new String("test" + i); - scheduler.schedule("id" + i, new ByteSequence(str.getBytes()), "", time, 1000, -1); - } + long time = 60000; + for (int i = 0; i < COUNT; i++) { + String str = new String("test" + i); + scheduler.schedule("id" + i, new ByteSequence(str.getBytes()), "", time, 1000, -1); + } - int size = scheduler.getAllJobs().size(); - assertEquals(size, COUNT); + int size = scheduler.getAllJobs().size(); + assertEquals(size, COUNT); - long removeTime = scheduler.getNextScheduleTime(); - scheduler.remove(removeTime); + long removeTime = scheduler.getNextScheduleTime(); + scheduler.remove(removeTime); - // If all jobs are not started within the same second we need to call remove again - if (size != 0) { - removeTime = scheduler.getNextScheduleTime(); - scheduler.remove(removeTime); - } + // If all jobs are not started within the same second we need to call remove again + if (size != 0) { + removeTime = scheduler.getNextScheduleTime(); + scheduler.remove(removeTime); + } - size = scheduler.getAllJobs().size(); - assertEquals(0, size); - } + size = scheduler.getAllJobs().size(); + assertEquals(0, size); + } - @Test - public void testRemoveString() throws Exception { - final int COUNT = 10; - final String test = "TESTREMOVE"; - long time = 20000; + @Test + public void testRemoveString() throws Exception { + final int COUNT = 10; + final String test = "TESTREMOVE"; + long time = 20000; - for (int i = 0; i < COUNT; i++) { - String str = new String("test" + i); - scheduler.schedule("id" + i, new ByteSequence(str.getBytes()), "", time, 1000, -1); - if (i == COUNT / 2) { - scheduler.schedule(test, new ByteSequence(test.getBytes()), "", time, 1000, -1); - } - } + for (int i = 0; i < COUNT; i++) { + String str = new String("test" + i); + scheduler.schedule("id" + i, new ByteSequence(str.getBytes()), "", time, 1000, -1); + if (i == COUNT / 2) { + scheduler.schedule(test, new ByteSequence(test.getBytes()), "", time, 1000, -1); + } + } - int size = scheduler.getAllJobs().size(); - assertEquals(size, COUNT + 1); - scheduler.remove(test); - size = scheduler.getAllJobs().size(); - assertEquals(size, COUNT); - } + int size = scheduler.getAllJobs().size(); + assertEquals(size, COUNT + 1); + scheduler.remove(test); + size = scheduler.getAllJobs().size(); + assertEquals(size, COUNT); + } - @Test - public void testGetExecutionCount() throws Exception { - final String jobId = "Job-1"; - long time = 10000; - final CountDownLatch done = new CountDownLatch(10); + @Test + public void testGetExecutionCount() throws Exception { + final String jobId = "Job-1"; + long time = 10000; + final CountDownLatch done = new CountDownLatch(10); - String str = new String("test"); - scheduler.schedule(jobId, new ByteSequence(str.getBytes()), "", time, 1000, 10); + String str = new String("test"); + scheduler.schedule(jobId, new ByteSequence(str.getBytes()), "", time, 1000, 10); - int size = scheduler.getAllJobs().size(); - assertEquals(size, 1); + int size = scheduler.getAllJobs().size(); + assertEquals(size, 1); - scheduler.addListener(new JobListener() { - @Override - public void scheduledJob(String id, ByteSequence job) { - LOG.info("Job executed: {}", 11 - done.getCount()); - done.countDown(); - } - }); + scheduler.addListener(new JobListener() { + @Override + public void scheduledJob(String id, ByteSequence job) { + LOG.info("Job executed: {}", 11 - done.getCount()); + done.countDown(); + } + }); - List jobs = scheduler.getNextScheduleJobs(); - assertEquals(1, jobs.size()); - Job job = jobs.get(0); - assertEquals(jobId, job.getJobId()); - assertEquals(0, job.getExecutionCount()); - assertTrue("Should have fired ten times.", done.await(60, TimeUnit.SECONDS)); - // The job is not updated on the last firing as it is removed from the store following - // it's last execution so the count will always be one less than the max firings. - assertTrue(job.getExecutionCount() >= 9); - } + List jobs = scheduler.getNextScheduleJobs(); + assertEquals(1, jobs.size()); + Job job = jobs.get(0); + assertEquals(jobId, job.getJobId()); + assertEquals(0, job.getExecutionCount()); + assertTrue("Should have fired ten times.", done.await(60, TimeUnit.SECONDS)); + // The job is not updated on the last firing as it is removed from the store following + // it's last execution so the count will always be one less than the max firings. + assertTrue(job.getExecutionCount() >= 9); + } - @Test - public void testgetAllJobs() throws Exception { - final int COUNT = 10; - final String ID = "id:"; - long time = 20000; + @Test + public void testgetAllJobs() throws Exception { + final int COUNT = 10; + final String ID = "id:"; + long time = 20000; - for (int i = 0; i < COUNT; i++) { - String str = new String("test" + i); - scheduler.schedule(ID + i, new ByteSequence(str.getBytes()), "", time, 10 + i, -1); - } + for (int i = 0; i < COUNT; i++) { + String str = new String("test" + i); + scheduler.schedule(ID + i, new ByteSequence(str.getBytes()), "", time, 10 + i, -1); + } - List list = scheduler.getAllJobs(); + List list = scheduler.getAllJobs(); - assertEquals(list.size(), COUNT); - int count = 0; - for (Job job : list) { - assertEquals(job.getJobId(), ID + count); - count++; - } - } + assertEquals(list.size(), COUNT); + int count = 0; + for (Job job : list) { + assertEquals(job.getJobId(), ID + count); + count++; + } + } - @Test - public void testgetAllJobsInRange() throws Exception { - final int COUNT = 10; - final String ID = "id:"; - long start = 10000; + @Test + public void testgetAllJobsInRange() throws Exception { + final int COUNT = 10; + final String ID = "id:"; + long start = 10000; - for (int i = 0; i < COUNT; i++) { - String str = new String("test" + i); - scheduler.schedule(ID + i, new ByteSequence(str.getBytes()), "", start + (i * 1000), 10000 + i, 0); - } + for (int i = 0; i < COUNT; i++) { + String str = new String("test" + i); + scheduler.schedule(ID + i, new ByteSequence(str.getBytes()), "", start + (i * 1000), 10000 + i, 0); + } - start = System.currentTimeMillis(); - long finish = start + 12000 + (COUNT * 1000); - List list = scheduler.getAllJobs(start, finish); + start = System.currentTimeMillis(); + long finish = start + 12000 + (COUNT * 1000); + List list = scheduler.getAllJobs(start, finish); - assertEquals(COUNT, list.size()); - int count = 0; - for (Job job : list) { - assertEquals(job.getJobId(), ID + count); - count++; - } - } + assertEquals(COUNT, list.size()); + int count = 0; + for (Job job : list) { + assertEquals(job.getJobId(), ID + count); + count++; + } + } - @Test - public void testRemoveAllJobsInRange() throws Exception { - final int COUNT = 10; - final String ID = "id:"; - long start = 10000; + @Test + public void testRemoveAllJobsInRange() throws Exception { + final int COUNT = 10; + final String ID = "id:"; + long start = 10000; - for (int i = 0; i < COUNT; i++) { - String str = new String("test" + i); - scheduler.schedule(ID + i, new ByteSequence(str.getBytes()), "", start + (i * 1000), 10000 + i, 0); - } - start = System.currentTimeMillis(); - long finish = start + 12000 + (COUNT * 1000); - scheduler.removeAllJobs(start, finish); + for (int i = 0; i < COUNT; i++) { + String str = new String("test" + i); + scheduler.schedule(ID + i, new ByteSequence(str.getBytes()), "", start + (i * 1000), 10000 + i, 0); + } + start = System.currentTimeMillis(); + long finish = start + 12000 + (COUNT * 1000); + scheduler.removeAllJobs(start, finish); - assertTrue(scheduler.getAllJobs().isEmpty()); - } + assertTrue(scheduler.getAllJobs().isEmpty()); + } - @Before - public void setUp() throws Exception { - File directory = new File("target/test/ScheduledJobsDB"); - IOHelper.mkdirs(directory); - IOHelper.deleteChildren(directory); - startStore(directory); - } + @Before + public void setUp() throws Exception { + File directory = new File("target/test/ScheduledJobsDB"); + IOHelper.mkdirs(directory); + IOHelper.deleteChildren(directory); + startStore(directory); + } - protected JobSchedulerStore createJobSchedulerStore() throws Exception { - return new JobSchedulerStoreImpl(); - } + protected JobSchedulerStore createJobSchedulerStore() throws Exception { + return new JobSchedulerStoreImpl(); + } - protected void startStore(File directory) throws Exception { - store = createJobSchedulerStore(); - store.setDirectory(directory); - store.start(); - scheduler = store.getJobScheduler("test"); - scheduler.startDispatching(); - } + protected void startStore(File directory) throws Exception { + store = createJobSchedulerStore(); + store.setDirectory(directory); + store.start(); + scheduler = store.getJobScheduler("test"); + scheduler.startDispatching(); + } - @After - public void tearDown() throws Exception { - scheduler.stopDispatching(); - store.stop(); - } + @After + public void tearDown() throws Exception { + scheduler.stopDispatching(); + store.stop(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerTestSupport.java index 5bf8d8c45a..6e2933602b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerTestSupport.java @@ -39,78 +39,78 @@ import org.junit.rules.TestName; */ public class JobSchedulerTestSupport { - @Rule public TestName name = new TestName(); + @Rule + public TestName name = new TestName(); - protected String connectionUri; - protected BrokerService broker; - protected JobScheduler jobScheduler; - protected Queue destination; + protected String connectionUri; + protected BrokerService broker; + protected JobScheduler jobScheduler; + protected Queue destination; - @Before - public void setUp() throws Exception { - connectionUri = "vm://localhost"; - destination = new ActiveMQQueue(name.getMethodName()); + @Before + public void setUp() throws Exception { + connectionUri = "vm://localhost"; + destination = new ActiveMQQueue(name.getMethodName()); - broker = createBroker(); - broker.start(); - broker.waitUntilStarted(); + broker = createBroker(); + broker.start(); + broker.waitUntilStarted(); - jobScheduler = broker.getJobSchedulerStore().getJobScheduler("JMS"); - } + jobScheduler = broker.getJobSchedulerStore().getJobScheduler("JMS"); + } - @After - public void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - } + @After + public void tearDown() throws Exception { + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + } - protected Connection createConnection() throws Exception { - return createConnectionFactory().createConnection(); - } + protected Connection createConnection() throws Exception { + return createConnectionFactory().createConnection(); + } - protected ConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(connectionUri); - } + protected ConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory(connectionUri); + } - protected BrokerService createBroker() throws Exception { - return createBroker(true); - } + protected BrokerService createBroker() throws Exception { + return createBroker(true); + } - protected boolean isUseJmx() { - return false; - } + protected boolean isUseJmx() { + return false; + } - protected boolean isPersistent() { - return true; - } + protected boolean isPersistent() { + return true; + } - protected JobSchedulerViewMBean getJobSchedulerMBean() throws Exception { - ObjectName objectName = broker.getAdminView().getJMSJobScheduler(); - JobSchedulerViewMBean scheduler = null; - if (objectName != null) { - scheduler = (JobSchedulerViewMBean) broker.getManagementContext() - .newProxyInstance(objectName, JobSchedulerViewMBean.class, true); - } + protected JobSchedulerViewMBean getJobSchedulerMBean() throws Exception { + ObjectName objectName = broker.getAdminView().getJMSJobScheduler(); + JobSchedulerViewMBean scheduler = null; + if (objectName != null) { + scheduler = (JobSchedulerViewMBean) broker.getManagementContext().newProxyInstance(objectName, JobSchedulerViewMBean.class, true); + } - return scheduler; - } + return scheduler; + } - protected BrokerService createBroker(boolean delete) throws Exception { - File schedulerDirectory = new File("target/scheduler"); - if (delete) { - IOHelper.mkdirs(schedulerDirectory); - IOHelper.deleteChildren(schedulerDirectory); - } + protected BrokerService createBroker(boolean delete) throws Exception { + File schedulerDirectory = new File("target/scheduler"); + if (delete) { + IOHelper.mkdirs(schedulerDirectory); + IOHelper.deleteChildren(schedulerDirectory); + } - BrokerService answer = new BrokerService(); - answer.setPersistent(isPersistent()); - answer.setDeleteAllMessagesOnStartup(true); - answer.setDataDirectory("target"); - answer.setSchedulerDirectoryFile(schedulerDirectory); - answer.setSchedulerSupport(true); - answer.setUseJmx(isUseJmx()); - return answer; - } + BrokerService answer = new BrokerService(); + answer.setPersistent(isPersistent()); + answer.setDeleteAllMessagesOnStartup(true); + answer.setDataDirectory("target"); + answer.setSchedulerDirectoryFile(schedulerDirectory); + answer.setSchedulerSupport(true); + answer.setUseJmx(isUseJmx()); + return answer; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerTxTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerTxTest.java index 996cc55b1a..3e9769e80d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerTxTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerTxTest.java @@ -35,73 +35,73 @@ import org.junit.Test; public class JobSchedulerTxTest extends JobSchedulerTestSupport { - @Test - public void testTxSendWithRollback() throws Exception { - final int COUNT = 10; - Connection connection = createConnection(); + @Test + public void testTxSendWithRollback() throws Exception { + final int COUNT = 10; + Connection connection = createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); - final CountDownLatch latch = new CountDownLatch(COUNT); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - latch.countDown(); - } - }); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(destination); + final CountDownLatch latch = new CountDownLatch(COUNT); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + latch.countDown(); + } + }); - connection.start(); - long time = 5000; - Session producerSession = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageProducer producer = producerSession.createProducer(destination); + connection.start(); + long time = 5000; + Session producerSession = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageProducer producer = producerSession.createProducer(destination); - for (int i = 0; i < COUNT; ++i) { - TextMessage message = session.createTextMessage("test msg"); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - producer.send(message); - } - producer.close(); - producerSession.rollback(); + for (int i = 0; i < COUNT; ++i) { + TextMessage message = session.createTextMessage("test msg"); + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); + producer.send(message); + } + producer.close(); + producerSession.rollback(); - // make sure the message isn't delivered early - Thread.sleep(2000); - assertEquals(COUNT, latch.getCount()); - latch.await(5, TimeUnit.SECONDS); - assertEquals(COUNT, latch.getCount()); - } + // make sure the message isn't delivered early + Thread.sleep(2000); + assertEquals(COUNT, latch.getCount()); + latch.await(5, TimeUnit.SECONDS); + assertEquals(COUNT, latch.getCount()); + } - @Test - public void testTxSendWithCommit() throws Exception { - final int COUNT = 10; - Connection connection = createConnection(); + @Test + public void testTxSendWithCommit() throws Exception { + final int COUNT = 10; + Connection connection = createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); - final CountDownLatch latch = new CountDownLatch(COUNT); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - latch.countDown(); - } - }); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(destination); + final CountDownLatch latch = new CountDownLatch(COUNT); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + latch.countDown(); + } + }); - connection.start(); - long time = 5000; - Session producerSession = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageProducer producer = producerSession.createProducer(destination); + connection.start(); + long time = 5000; + Session producerSession = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageProducer producer = producerSession.createProducer(destination); - for (int i = 0; i < COUNT; ++i) { - TextMessage message = session.createTextMessage("test msg"); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - producer.send(message); - } - producer.close(); - producerSession.commit(); + for (int i = 0; i < COUNT; ++i) { + TextMessage message = session.createTextMessage("test msg"); + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); + producer.send(message); + } + producer.close(); + producerSession.commit(); - // make sure the message isn't delivered early - Thread.sleep(2000); - assertEquals(COUNT, latch.getCount()); - latch.await(5, TimeUnit.SECONDS); - assertEquals(0, latch.getCount()); - } + // make sure the message isn't delivered early + Thread.sleep(2000); + assertEquals(COUNT, latch.getCount()); + latch.await(5, TimeUnit.SECONDS); + assertEquals(0, latch.getCount()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/KahaDBSchedulerIndexRebuildTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/KahaDBSchedulerIndexRebuildTest.java index 03e5c84c81..3d6ee1682d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/KahaDBSchedulerIndexRebuildTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/KahaDBSchedulerIndexRebuildTest.java @@ -45,151 +45,153 @@ import org.slf4j.LoggerFactory; public class KahaDBSchedulerIndexRebuildTest { - static final Logger LOG = LoggerFactory.getLogger(KahaDBSchedulerIndexRebuildTest.class); + static final Logger LOG = LoggerFactory.getLogger(KahaDBSchedulerIndexRebuildTest.class); - private BrokerService broker = null; - private final int NUM_JOBS = 50; + private BrokerService broker = null; + private final int NUM_JOBS = 50; - static String basedir; - static { - try { - ProtectionDomain protectionDomain = SchedulerDBVersionTest.class.getProtectionDomain(); - basedir = new File(new File(protectionDomain.getCodeSource().getLocation().getPath()), "../.").getCanonicalPath(); - } catch (IOException e) { - basedir = "."; - } - } + static String basedir; - private final File schedulerStoreDir = new File(basedir, "activemq-data/store/scheduler"); - private final File storeDir = new File(basedir, "activemq-data/store/"); + static { + try { + ProtectionDomain protectionDomain = SchedulerDBVersionTest.class.getProtectionDomain(); + basedir = new File(new File(protectionDomain.getCodeSource().getLocation().getPath()), "../.").getCanonicalPath(); + } + catch (IOException e) { + basedir = "."; + } + } - @Before - public void setUp() throws Exception { - LOG.info("Test Dir = {}", schedulerStoreDir); - } + private final File schedulerStoreDir = new File(basedir, "activemq-data/store/scheduler"); + private final File storeDir = new File(basedir, "activemq-data/store/"); - @After - public void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - } - } + @Before + public void setUp() throws Exception { + LOG.info("Test Dir = {}", schedulerStoreDir); + } - @Test - public void testIndexRebuilds() throws Exception { - IOHelper.deleteFile(schedulerStoreDir); + @After + public void tearDown() throws Exception { + if (broker != null) { + broker.stop(); + } + } - JobSchedulerStoreImpl schedulerStore = createScheduler(); - broker = createBroker(schedulerStore); - broker.start(); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = cf.createConnection(); - connection.start(); - for (int i = 0; i < NUM_JOBS; ++i) { - scheduleRepeating(connection); - } - connection.close(); + @Test + public void testIndexRebuilds() throws Exception { + IOHelper.deleteFile(schedulerStoreDir); - JobScheduler scheduler = schedulerStore.getJobScheduler("JMS"); - assertNotNull(scheduler); - assertEquals(NUM_JOBS, scheduler.getAllJobs().size()); + JobSchedulerStoreImpl schedulerStore = createScheduler(); + broker = createBroker(schedulerStore); + broker.start(); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); + Connection connection = cf.createConnection(); + connection.start(); + for (int i = 0; i < NUM_JOBS; ++i) { + scheduleRepeating(connection); + } + connection.close(); - broker.stop(); + JobScheduler scheduler = schedulerStore.getJobScheduler("JMS"); + assertNotNull(scheduler); + assertEquals(NUM_JOBS, scheduler.getAllJobs().size()); - IOHelper.delete(new File(schedulerStoreDir, "scheduleDB.data")); + broker.stop(); - schedulerStore = createScheduler(); - broker = createBroker(schedulerStore); - broker.start(); + IOHelper.delete(new File(schedulerStoreDir, "scheduleDB.data")); - scheduler = schedulerStore.getJobScheduler("JMS"); - assertNotNull(scheduler); - assertEquals(NUM_JOBS, scheduler.getAllJobs().size()); - } + schedulerStore = createScheduler(); + broker = createBroker(schedulerStore); + broker.start(); - @Test - public void testIndexRebuildsAfterSomeJobsExpire() throws Exception { - IOHelper.deleteFile(schedulerStoreDir); + scheduler = schedulerStore.getJobScheduler("JMS"); + assertNotNull(scheduler); + assertEquals(NUM_JOBS, scheduler.getAllJobs().size()); + } - JobSchedulerStoreImpl schedulerStore = createScheduler(); - broker = createBroker(schedulerStore); - broker.start(); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = cf.createConnection(); - connection.start(); - for (int i = 0; i < NUM_JOBS; ++i) { - scheduleRepeating(connection); - scheduleOneShot(connection); - } - connection.close(); + @Test + public void testIndexRebuildsAfterSomeJobsExpire() throws Exception { + IOHelper.deleteFile(schedulerStoreDir); - JobScheduler scheduler = schedulerStore.getJobScheduler("JMS"); - assertNotNull(scheduler); - assertEquals(NUM_JOBS * 2, scheduler.getAllJobs().size()); + JobSchedulerStoreImpl schedulerStore = createScheduler(); + broker = createBroker(schedulerStore); + broker.start(); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); + Connection connection = cf.createConnection(); + connection.start(); + for (int i = 0; i < NUM_JOBS; ++i) { + scheduleRepeating(connection); + scheduleOneShot(connection); + } + connection.close(); - final JobScheduler awaitingOneShotTimeout = scheduler; - assertTrue("One shot jobs should time out", Wait.waitFor(new Wait.Condition() { + JobScheduler scheduler = schedulerStore.getJobScheduler("JMS"); + assertNotNull(scheduler); + assertEquals(NUM_JOBS * 2, scheduler.getAllJobs().size()); - @Override - public boolean isSatisified() throws Exception { - return awaitingOneShotTimeout.getAllJobs().size() == NUM_JOBS; - } - }, TimeUnit.MINUTES.toMillis(2))); + final JobScheduler awaitingOneShotTimeout = scheduler; + assertTrue("One shot jobs should time out", Wait.waitFor(new Wait.Condition() { - broker.stop(); + @Override + public boolean isSatisified() throws Exception { + return awaitingOneShotTimeout.getAllJobs().size() == NUM_JOBS; + } + }, TimeUnit.MINUTES.toMillis(2))); - IOHelper.delete(new File(schedulerStoreDir, "scheduleDB.data")); + broker.stop(); - schedulerStore = createScheduler(); - broker = createBroker(schedulerStore); - broker.start(); + IOHelper.delete(new File(schedulerStoreDir, "scheduleDB.data")); - scheduler = schedulerStore.getJobScheduler("JMS"); - assertNotNull(scheduler); - assertEquals(NUM_JOBS, scheduler.getAllJobs().size()); - } + schedulerStore = createScheduler(); + broker = createBroker(schedulerStore); + broker.start(); - private void scheduleRepeating(Connection connection) throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createQueue("test.queue"); - MessageProducer producer = session.createProducer(queue); + scheduler = schedulerStore.getJobScheduler("JMS"); + assertNotNull(scheduler); + assertEquals(NUM_JOBS, scheduler.getAllJobs().size()); + } - TextMessage message = session.createTextMessage("test msg"); - long time = 360 * 1000; - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, 500); - message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, -1); - producer.send(message); - producer.close(); - } + private void scheduleRepeating(Connection connection) throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = session.createQueue("test.queue"); + MessageProducer producer = session.createProducer(queue); - private void scheduleOneShot(Connection connection) throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createQueue("test.queue"); - MessageProducer producer = session.createProducer(queue); + TextMessage message = session.createTextMessage("test msg"); + long time = 360 * 1000; + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, 500); + message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, -1); + producer.send(message); + producer.close(); + } - TextMessage message = session.createTextMessage("test msg"); - long time = TimeUnit.SECONDS.toMillis(30); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, 0); - producer.send(message); - producer.close(); - } + private void scheduleOneShot(Connection connection) throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = session.createQueue("test.queue"); + MessageProducer producer = session.createProducer(queue); - protected JobSchedulerStoreImpl createScheduler() { - JobSchedulerStoreImpl scheduler = new JobSchedulerStoreImpl(); - scheduler.setDirectory(schedulerStoreDir); - scheduler.setJournalMaxFileLength(10 * 1024); - return scheduler; - } + TextMessage message = session.createTextMessage("test msg"); + long time = TimeUnit.SECONDS.toMillis(30); + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); + message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, 0); + producer.send(message); + producer.close(); + } - protected BrokerService createBroker(JobSchedulerStoreImpl scheduler) throws Exception { - BrokerService answer = new BrokerService(); - answer.setJobSchedulerStore(scheduler); - answer.setPersistent(true); - answer.setDataDirectory(storeDir.getAbsolutePath()); - answer.setSchedulerSupport(true); - answer.setUseJmx(false); - return answer; - } + protected JobSchedulerStoreImpl createScheduler() { + JobSchedulerStoreImpl scheduler = new JobSchedulerStoreImpl(); + scheduler.setDirectory(schedulerStoreDir); + scheduler.setJournalMaxFileLength(10 * 1024); + return scheduler; + } + + protected BrokerService createBroker(JobSchedulerStoreImpl scheduler) throws Exception { + BrokerService answer = new BrokerService(); + answer.setJobSchedulerStore(scheduler); + answer.setPersistent(true); + answer.setDataDirectory(storeDir.getAbsolutePath()); + answer.setSchedulerSupport(true); + answer.setUseJmx(false); + return answer; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/KahaDBSchedulerMissingJournalLogsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/KahaDBSchedulerMissingJournalLogsTest.java index 30da10dfb7..852d4c62e6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/KahaDBSchedulerMissingJournalLogsTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/KahaDBSchedulerMissingJournalLogsTest.java @@ -46,159 +46,162 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - *Test that the store recovers even if some log files are missing. + * Test that the store recovers even if some log files are missing. */ public class KahaDBSchedulerMissingJournalLogsTest { - static final Logger LOG = LoggerFactory.getLogger(KahaDBSchedulerIndexRebuildTest.class); + static final Logger LOG = LoggerFactory.getLogger(KahaDBSchedulerIndexRebuildTest.class); - private BrokerService broker = null; - private JobSchedulerStoreImpl schedulerStore = null; + private BrokerService broker = null; + private JobSchedulerStoreImpl schedulerStore = null; - private final int NUM_LOGS = 6; + private final int NUM_LOGS = 6; - static String basedir; - static { - try { - ProtectionDomain protectionDomain = SchedulerDBVersionTest.class.getProtectionDomain(); - basedir = new File(new File(protectionDomain.getCodeSource().getLocation().getPath()), "../.").getCanonicalPath(); - } catch (IOException e) { - basedir = "."; - } - } + static String basedir; - private final File schedulerStoreDir = new File(basedir, "activemq-data/store/scheduler"); - private final File storeDir = new File(basedir, "activemq-data/store/"); + static { + try { + ProtectionDomain protectionDomain = SchedulerDBVersionTest.class.getProtectionDomain(); + basedir = new File(new File(protectionDomain.getCodeSource().getLocation().getPath()), "../.").getCanonicalPath(); + } + catch (IOException e) { + basedir = "."; + } + } - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - IOHelper.deleteFile(schedulerStoreDir); - LOG.info("Test Dir = {}", schedulerStoreDir); + private final File schedulerStoreDir = new File(basedir, "activemq-data/store/scheduler"); + private final File storeDir = new File(basedir, "activemq-data/store/"); - createBroker(); - broker.start(); - broker.waitUntilStarted(); + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + IOHelper.deleteFile(schedulerStoreDir); + LOG.info("Test Dir = {}", schedulerStoreDir); - schedulerStore = (JobSchedulerStoreImpl) broker.getJobSchedulerStore(); - } + createBroker(); + broker.start(); + broker.waitUntilStarted(); - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - } + schedulerStore = (JobSchedulerStoreImpl) broker.getJobSchedulerStore(); + } - @Test(timeout=120 * 1000) - public void testMissingLogsCausesBrokerToFail() throws Exception { - fillUpSomeLogFiles(); + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception { + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + } - int jobCount = schedulerStore.getJobScheduler("JMS").getAllJobs().size(); - LOG.info("There are {} jobs in the store.", jobCount); + @Test(timeout = 120 * 1000) + public void testMissingLogsCausesBrokerToFail() throws Exception { + fillUpSomeLogFiles(); - List toDelete = new ArrayList(); - Map files = schedulerStore.getJournal().getFileMap(); - for (int i = files.size(); i > files.size() / 2; i--) { - toDelete.add(files.get(i).getFile()); - } + int jobCount = schedulerStore.getJobScheduler("JMS").getAllJobs().size(); + LOG.info("There are {} jobs in the store.", jobCount); - broker.stop(); - broker.waitUntilStopped(); + List toDelete = new ArrayList(); + Map files = schedulerStore.getJournal().getFileMap(); + for (int i = files.size(); i > files.size() / 2; i--) { + toDelete.add(files.get(i).getFile()); + } - for (File file : toDelete) { - LOG.info("File to delete: {}", file); - IOHelper.delete(file); - } + broker.stop(); + broker.waitUntilStopped(); - try { - createBroker(); - fail("Should not start when logs are missing."); - } catch (Exception e) { - } - } + for (File file : toDelete) { + LOG.info("File to delete: {}", file); + IOHelper.delete(file); + } - @Test(timeout=120 * 1000) - public void testRecoverWhenSomeLogsAreMissing() throws Exception { - fillUpSomeLogFiles(); + try { + createBroker(); + fail("Should not start when logs are missing."); + } + catch (Exception e) { + } + } - int jobCount = schedulerStore.getJobScheduler("JMS").getAllJobs().size(); - LOG.info("There are {} jobs in the store.", jobCount); + @Test(timeout = 120 * 1000) + public void testRecoverWhenSomeLogsAreMissing() throws Exception { + fillUpSomeLogFiles(); - List toDelete = new ArrayList(); - Map files = schedulerStore.getJournal().getFileMap(); - for (int i = files.size() - 1; i > files.size() / 2; i--) { - toDelete.add(files.get(i).getFile()); - } + int jobCount = schedulerStore.getJobScheduler("JMS").getAllJobs().size(); + LOG.info("There are {} jobs in the store.", jobCount); - broker.stop(); - broker.waitUntilStopped(); + List toDelete = new ArrayList(); + Map files = schedulerStore.getJournal().getFileMap(); + for (int i = files.size() - 1; i > files.size() / 2; i--) { + toDelete.add(files.get(i).getFile()); + } - for (File file : toDelete) { - LOG.info("File to delete: {}", file); - IOHelper.delete(file); - } + broker.stop(); + broker.waitUntilStopped(); - schedulerStore = createScheduler(); - schedulerStore.setIgnoreMissingJournalfiles(true); + for (File file : toDelete) { + LOG.info("File to delete: {}", file); + IOHelper.delete(file); + } - createBroker(schedulerStore); - broker.start(); - broker.waitUntilStarted(); + schedulerStore = createScheduler(); + schedulerStore.setIgnoreMissingJournalfiles(true); - int postRecoverJobCount = schedulerStore.getJobScheduler("JMS").getAllJobs().size(); - assertTrue(postRecoverJobCount > 0); - assertTrue(postRecoverJobCount < jobCount); - } + createBroker(schedulerStore); + broker.start(); + broker.waitUntilStarted(); - private void fillUpSomeLogFiles() throws Exception { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = cf.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createQueue("test.queue"); - MessageProducer producer = session.createProducer(queue); - connection.start(); - while (true) { - scheduleRepeating(session, producer); - if (schedulerStore.getJournal().getFileMap().size() == NUM_LOGS) { - break; - } - } - connection.close(); - } + int postRecoverJobCount = schedulerStore.getJobScheduler("JMS").getAllJobs().size(); + assertTrue(postRecoverJobCount > 0); + assertTrue(postRecoverJobCount < jobCount); + } - private void scheduleRepeating(Session session, MessageProducer producer) throws Exception { - TextMessage message = session.createTextMessage("test msg"); - long time = 360 * 1000; - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, 500); - message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, -1); - producer.send(message); - } + private void fillUpSomeLogFiles() throws Exception { + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); + Connection connection = cf.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = session.createQueue("test.queue"); + MessageProducer producer = session.createProducer(queue); + connection.start(); + while (true) { + scheduleRepeating(session, producer); + if (schedulerStore.getJournal().getFileMap().size() == NUM_LOGS) { + break; + } + } + connection.close(); + } - protected JobSchedulerStoreImpl createScheduler() { - JobSchedulerStoreImpl scheduler = new JobSchedulerStoreImpl(); - scheduler.setDirectory(schedulerStoreDir); - scheduler.setJournalMaxFileLength(10 * 1024); - return scheduler; - } + private void scheduleRepeating(Session session, MessageProducer producer) throws Exception { + TextMessage message = session.createTextMessage("test msg"); + long time = 360 * 1000; + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, 500); + message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, -1); + producer.send(message); + } - protected void createBroker() throws Exception { - createBroker(createScheduler()); - } + protected JobSchedulerStoreImpl createScheduler() { + JobSchedulerStoreImpl scheduler = new JobSchedulerStoreImpl(); + scheduler.setDirectory(schedulerStoreDir); + scheduler.setJournalMaxFileLength(10 * 1024); + return scheduler; + } - protected void createBroker(JobSchedulerStoreImpl scheduler) throws Exception { - broker = new BrokerService(); - broker.setJobSchedulerStore(scheduler); - broker.setPersistent(true); - broker.setDataDirectory(storeDir.getAbsolutePath()); - broker.setSchedulerSupport(true); - broker.setUseJmx(false); - } + protected void createBroker() throws Exception { + createBroker(createScheduler()); + } + + protected void createBroker(JobSchedulerStoreImpl scheduler) throws Exception { + broker = new BrokerService(); + broker.setJobSchedulerStore(scheduler); + broker.setPersistent(true); + broker.setDataDirectory(storeDir.getAbsolutePath()); + broker.setSchedulerSupport(true); + broker.setUseJmx(false); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/LostScheduledMessagesTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/LostScheduledMessagesTest.java index 53588b5b69..7b31771f87 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/LostScheduledMessagesTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/LostScheduledMessagesTest.java @@ -43,111 +43,111 @@ import org.junit.Test; public class LostScheduledMessagesTest { - private BrokerService broker; + private BrokerService broker; - private static final File schedulerDirectory = new File("target/test/ScheduledDB"); - private static final File messageDirectory = new File("target/test/MessageDB"); - private static final String QUEUE_NAME = "test"; + private static final File schedulerDirectory = new File("target/test/ScheduledDB"); + private static final File messageDirectory = new File("target/test/MessageDB"); + private static final String QUEUE_NAME = "test"; - @Before - public void setup() throws Exception { - IOHelper.mkdirs(schedulerDirectory); - IOHelper.deleteChildren(schedulerDirectory); + @Before + public void setup() throws Exception { + IOHelper.mkdirs(schedulerDirectory); + IOHelper.deleteChildren(schedulerDirectory); - IOHelper.mkdirs(messageDirectory); - IOHelper.deleteChildren(messageDirectory); - } + IOHelper.mkdirs(messageDirectory); + IOHelper.deleteChildren(messageDirectory); + } - private void startBroker() throws Exception { - broker = new BrokerService(); - broker.setSchedulerSupport(true); - broker.setPersistent(true); - broker.setDeleteAllMessagesOnStartup(false); - broker.setDataDirectory("target"); - broker.setSchedulerDirectoryFile(schedulerDirectory); - broker.setDataDirectoryFile(messageDirectory); - broker.setUseJmx(false); - broker.addConnector("vm://localhost"); - broker.start(); - } + private void startBroker() throws Exception { + broker = new BrokerService(); + broker.setSchedulerSupport(true); + broker.setPersistent(true); + broker.setDeleteAllMessagesOnStartup(false); + broker.setDataDirectory("target"); + broker.setSchedulerDirectoryFile(schedulerDirectory); + broker.setDataDirectoryFile(messageDirectory); + broker.setUseJmx(false); + broker.addConnector("vm://localhost"); + broker.start(); + } - @After - public void tearDown() throws Exception { - broker.stop(); - BasicConfigurator.resetConfiguration(); - } + @After + public void tearDown() throws Exception { + broker.stop(); + BasicConfigurator.resetConfiguration(); + } - @Test - public void MessagePassedNotUsingScheduling() throws Exception { - doTest(false); - } + @Test + public void MessagePassedNotUsingScheduling() throws Exception { + doTest(false); + } - @Test - public void MessageLostWhenUsingScheduling() throws Exception { - doTest(true); - } + @Test + public void MessageLostWhenUsingScheduling() throws Exception { + doTest(true); + } - private void doTest(boolean useScheduling) throws Exception { + private void doTest(boolean useScheduling) throws Exception { - int DELIVERY_DELAY_MS = 5000; + int DELIVERY_DELAY_MS = 5000; - startBroker(); + startBroker(); - long startTime = System.currentTimeMillis(); + long startTime = System.currentTimeMillis(); - // Send a message scheduled for delivery in 5 seconds - ConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = cf.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(session.createQueue(QUEUE_NAME)); - Message message = session.createTextMessage("test"); - if (useScheduling) { - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, DELIVERY_DELAY_MS); - } - producer.send(message); + // Send a message scheduled for delivery in 5 seconds + ConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); + Connection connection = cf.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(session.createQueue(QUEUE_NAME)); + Message message = session.createTextMessage("test"); + if (useScheduling) { + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, DELIVERY_DELAY_MS); + } + producer.send(message); - session.close(); - connection.close(); + session.close(); + connection.close(); - broker.getServices(); + broker.getServices(); - // shut down broker - broker.stop(); - broker.waitUntilStopped(); + // shut down broker + broker.stop(); + broker.waitUntilStopped(); - // Make sure that broker have stopped within delivery delay - long shutdownTime = System.currentTimeMillis(); - assertTrue("Failed to shut down broker in expected time. Test results inconclusive", shutdownTime - startTime < DELIVERY_DELAY_MS); + // Make sure that broker have stopped within delivery delay + long shutdownTime = System.currentTimeMillis(); + assertTrue("Failed to shut down broker in expected time. Test results inconclusive", shutdownTime - startTime < DELIVERY_DELAY_MS); - // make sure that delivery falls into down time window - TimeUnit.MILLISECONDS.sleep(DELIVERY_DELAY_MS); + // make sure that delivery falls into down time window + TimeUnit.MILLISECONDS.sleep(DELIVERY_DELAY_MS); - // Start new broker instance - startBroker(); + // Start new broker instance + startBroker(); - final AtomicLong receiveCounter = new AtomicLong(); + final AtomicLong receiveCounter = new AtomicLong(); - cf = new ActiveMQConnectionFactory("vm://localhost"); - connection = cf.createConnection(); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + cf = new ActiveMQConnectionFactory("vm://localhost"); + connection = cf.createConnection(); + connection.start(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME)); - consumer.setMessageListener(new MessageListener() { + MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME)); + consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - receiveCounter.incrementAndGet(); - } - }); + @Override + public void onMessage(Message message) { + receiveCounter.incrementAndGet(); + } + }); - // Wait for a while to let MQ process the message - TimeUnit.MILLISECONDS.sleep(DELIVERY_DELAY_MS * 2); + // Wait for a while to let MQ process the message + TimeUnit.MILLISECONDS.sleep(DELIVERY_DELAY_MS * 2); - session.close(); - connection.close(); + session.close(); + connection.close(); - assertEquals(1, receiveCounter.get()); - } + assertEquals(1, receiveCounter.get()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/SchedulerDBVersionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/SchedulerDBVersionTest.java index 721f41702d..db2d9ed00c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/SchedulerDBVersionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/SchedulerDBVersionTest.java @@ -46,119 +46,121 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SchedulerDBVersionTest { - static String basedir; - static { - try { - ProtectionDomain protectionDomain = SchedulerDBVersionTest.class.getProtectionDomain(); - basedir = new File(new File(protectionDomain.getCodeSource().getLocation().getPath()), "../..").getCanonicalPath(); - } catch (IOException e) { - basedir = "."; - } - } - static final Logger LOG = LoggerFactory.getLogger(SchedulerDBVersionTest.class); - final static File VERSION_LEGACY_JMS = - new File(basedir + "/src/test/resources/org/apache/activemq/store/schedulerDB/legacy"); + static String basedir; - BrokerService broker = null; + static { + try { + ProtectionDomain protectionDomain = SchedulerDBVersionTest.class.getProtectionDomain(); + basedir = new File(new File(protectionDomain.getCodeSource().getLocation().getPath()), "../..").getCanonicalPath(); + } + catch (IOException e) { + basedir = "."; + } + } - protected BrokerService createBroker(JobSchedulerStoreImpl scheduler) throws Exception { - BrokerService answer = new BrokerService(); - answer.setJobSchedulerStore(scheduler); - answer.setPersistent(true); - answer.setDataDirectory("target"); - answer.setSchedulerSupport(true); - answer.setUseJmx(false); - return answer; - } + static final Logger LOG = LoggerFactory.getLogger(SchedulerDBVersionTest.class); + final static File VERSION_LEGACY_JMS = new File(basedir + "/src/test/resources/org/apache/activemq/store/schedulerDB/legacy"); - @After - public void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - } - } + BrokerService broker = null; - @Ignore("Used only when a new version of the store needs to archive it's test data.") - @Test - public void testCreateStore() throws Exception { - JobSchedulerStoreImpl scheduler = new JobSchedulerStoreImpl(); - File dir = new File("src/test/resources/org/apache/activemq/store/schedulerDB/legacy"); - IOHelper.deleteFile(dir); - scheduler.setDirectory(dir); - scheduler.setJournalMaxFileLength(1024 * 1024); - broker = createBroker(scheduler); - broker.start(); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = cf.createConnection(); - connection.start(); - scheduleRepeating(connection); - connection.close(); - broker.stop(); - } + protected BrokerService createBroker(JobSchedulerStoreImpl scheduler) throws Exception { + BrokerService answer = new BrokerService(); + answer.setJobSchedulerStore(scheduler); + answer.setPersistent(true); + answer.setDataDirectory("target"); + answer.setSchedulerSupport(true); + answer.setUseJmx(false); + return answer; + } - private void scheduleRepeating(Connection connection) throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createQueue("test.queue"); - MessageProducer producer = session.createProducer(queue); + @After + public void tearDown() throws Exception { + if (broker != null) { + broker.stop(); + } + } - TextMessage message = session.createTextMessage("test msg"); - long time = 1000; - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, 500); - message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, -1); - producer.send(message); - producer.close(); - } + @Ignore("Used only when a new version of the store needs to archive it's test data.") + @Test + public void testCreateStore() throws Exception { + JobSchedulerStoreImpl scheduler = new JobSchedulerStoreImpl(); + File dir = new File("src/test/resources/org/apache/activemq/store/schedulerDB/legacy"); + IOHelper.deleteFile(dir); + scheduler.setDirectory(dir); + scheduler.setJournalMaxFileLength(1024 * 1024); + broker = createBroker(scheduler); + broker.start(); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); + Connection connection = cf.createConnection(); + connection.start(); + scheduleRepeating(connection); + connection.close(); + broker.stop(); + } - @Test - public void testLegacyStoreConversion() throws Exception { - doTestScheduleRepeated(VERSION_LEGACY_JMS); - } + private void scheduleRepeating(Connection connection) throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = session.createQueue("test.queue"); + MessageProducer producer = session.createProducer(queue); - public void doTestScheduleRepeated(File existingStore) throws Exception { - File testDir = new File("target/activemq-data/store/scheduler/versionDB"); - IOHelper.deleteFile(testDir); - IOHelper.copyFile(existingStore, testDir); + TextMessage message = session.createTextMessage("test msg"); + long time = 1000; + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, 500); + message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, -1); + producer.send(message); + producer.close(); + } - final int NUMBER = 10; - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); + @Test + public void testLegacyStoreConversion() throws Exception { + doTestScheduleRepeated(VERSION_LEGACY_JMS); + } - for (int i = 0; i < 3; ++i) { - JobSchedulerStoreImpl scheduler = new JobSchedulerStoreImpl(); - scheduler.setDirectory(testDir); - scheduler.setJournalMaxFileLength(1024 * 1024); - BrokerService broker = createBroker(scheduler); - broker.start(); - broker.waitUntilStarted(); + public void doTestScheduleRepeated(File existingStore) throws Exception { + File testDir = new File("target/activemq-data/store/scheduler/versionDB"); + IOHelper.deleteFile(testDir); + IOHelper.copyFile(existingStore, testDir); - final AtomicInteger count = new AtomicInteger(); - Connection connection = cf.createConnection(); + final int NUMBER = 10; + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createQueue("test.queue"); + for (int i = 0; i < 3; ++i) { + JobSchedulerStoreImpl scheduler = new JobSchedulerStoreImpl(); + scheduler.setDirectory(testDir); + scheduler.setJournalMaxFileLength(1024 * 1024); + BrokerService broker = createBroker(scheduler); + broker.start(); + broker.waitUntilStarted(); - MessageConsumer consumer = session.createConsumer(queue); + final AtomicInteger count = new AtomicInteger(); + Connection connection = cf.createConnection(); - final CountDownLatch latch = new CountDownLatch(NUMBER); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - LOG.info("Received scheduled message: {}", message); - latch.countDown(); - count.incrementAndGet(); - } - }); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = session.createQueue("test.queue"); - connection.start(); - assertEquals(latch.getCount(), NUMBER); - latch.await(30, TimeUnit.SECONDS); + MessageConsumer consumer = session.createConsumer(queue); - connection.close(); - broker.stop(); - broker.waitUntilStopped(); + final CountDownLatch latch = new CountDownLatch(NUMBER); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + LOG.info("Received scheduled message: {}", message); + latch.countDown(); + count.incrementAndGet(); + } + }); - assertEquals(0, latch.getCount()); - } - } + connection.start(); + assertEquals(latch.getCount(), NUMBER); + latch.await(30, TimeUnit.SECONDS); + + connection.close(); + broker.stop(); + broker.waitUntilStopped(); + + assertEquals(0, latch.getCount()); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemeoryJmsSchedulerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemeoryJmsSchedulerTest.java index 5144203e72..8d72dfb297 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemeoryJmsSchedulerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemeoryJmsSchedulerTest.java @@ -23,18 +23,18 @@ import org.apache.activemq.broker.scheduler.JmsSchedulerTest; */ public class InMemeoryJmsSchedulerTest extends JmsSchedulerTest { - @Override - protected boolean isPersistent() { - return false; - } + @Override + protected boolean isPersistent() { + return false; + } - @Override - public void testScheduleRestart() throws Exception { - // No persistence so scheduled jobs don't survive restart. - } + @Override + public void testScheduleRestart() throws Exception { + // No persistence so scheduled jobs don't survive restart. + } - @Override - public void testJobSchedulerStoreUsage() throws Exception { - // No store usage numbers for in-memory store. - } + @Override + public void testJobSchedulerStoreUsage() throws Exception { + // No store usage numbers for in-memory store. + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJmsCronSchedulerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJmsCronSchedulerTest.java index a3b7d04688..bad8368080 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJmsCronSchedulerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJmsCronSchedulerTest.java @@ -23,8 +23,8 @@ import org.apache.activemq.broker.scheduler.JmsCronSchedulerTest; */ public class InMemoryJmsCronSchedulerTest extends JmsCronSchedulerTest { - @Override - protected boolean isPersistent() { - return false; - } + @Override + protected boolean isPersistent() { + return false; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerJmxManagementTests.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerJmxManagementTests.java index 46f55404af..2bd923e7de 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerJmxManagementTests.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerJmxManagementTests.java @@ -23,8 +23,8 @@ import org.apache.activemq.broker.scheduler.JobSchedulerJmxManagementTests; */ public class InMemoryJobSchedulerJmxManagementTests extends JobSchedulerJmxManagementTests { - @Override - protected boolean isPersistent() { - return false; - } + @Override + protected boolean isPersistent() { + return false; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerManagementTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerManagementTest.java index e65d819e5c..d305321c8d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerManagementTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerManagementTest.java @@ -23,8 +23,8 @@ import org.apache.activemq.broker.scheduler.JobSchedulerManagementTest; */ public class InMemoryJobSchedulerManagementTest extends JobSchedulerManagementTest { - @Override - protected boolean isPersistent() { - return false; - } + @Override + protected boolean isPersistent() { + return false; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerStoreTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerStoreTest.java index ac90070d1f..06146a6fa4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerStoreTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerStoreTest.java @@ -35,40 +35,40 @@ import org.slf4j.LoggerFactory; */ public class InMemoryJobSchedulerStoreTest { - private static final Logger LOG = LoggerFactory.getLogger(InMemoryJobSchedulerStoreTest.class); + private static final Logger LOG = LoggerFactory.getLogger(InMemoryJobSchedulerStoreTest.class); - @Test(timeout = 120 * 1000) - public void testRestart() throws Exception { - InMemoryJobSchedulerStore store = new InMemoryJobSchedulerStore(); - File directory = new File("target/test/ScheduledDB"); - IOHelper.mkdirs(directory); - IOHelper.deleteChildren(directory); - store.setDirectory(directory); - final int NUMBER = 1000; - store.start(); - List list = new ArrayList(); - for (int i = 0; i < NUMBER; i++) { - ByteSequence buff = new ByteSequence(new String("testjob" + i).getBytes()); - list.add(buff); - } + @Test(timeout = 120 * 1000) + public void testRestart() throws Exception { + InMemoryJobSchedulerStore store = new InMemoryJobSchedulerStore(); + File directory = new File("target/test/ScheduledDB"); + IOHelper.mkdirs(directory); + IOHelper.deleteChildren(directory); + store.setDirectory(directory); + final int NUMBER = 1000; + store.start(); + List list = new ArrayList(); + for (int i = 0; i < NUMBER; i++) { + ByteSequence buff = new ByteSequence(new String("testjob" + i).getBytes()); + list.add(buff); + } - JobScheduler js = store.getJobScheduler("test"); - js.startDispatching(); - int count = 0; - long startTime = 10 * 60 * 1000; - long period = startTime; - for (ByteSequence job : list) { - js.schedule("id:" + (count++), job, "", startTime, period, -1); - } + JobScheduler js = store.getJobScheduler("test"); + js.startDispatching(); + int count = 0; + long startTime = 10 * 60 * 1000; + long period = startTime; + for (ByteSequence job : list) { + js.schedule("id:" + (count++), job, "", startTime, period, -1); + } - List test = js.getAllJobs(); - LOG.debug("Found {} jobs in the store before restart", test.size()); - assertEquals(list.size(), test.size()); - store.stop(); - store.start(); - js = store.getJobScheduler("test"); - test = js.getAllJobs(); - LOG.debug("Found {} jobs in the store after restart", test.size()); - assertEquals(0, test.size()); - } + List test = js.getAllJobs(); + LOG.debug("Found {} jobs in the store before restart", test.size()); + assertEquals(list.size(), test.size()); + store.stop(); + store.start(); + js = store.getJobScheduler("test"); + test = js.getAllJobs(); + LOG.debug("Found {} jobs in the store after restart", test.size()); + assertEquals(0, test.size()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerTest.java index 36771b0352..0cce465240 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerTest.java @@ -24,13 +24,13 @@ import org.apache.activemq.broker.scheduler.JobSchedulerTest; */ public class InMemoryJobSchedulerTest extends JobSchedulerTest { - @Override - public void testAddStopThenDeliver() throws Exception { - // In Memory store that's stopped doesn't retain the jobs. - } + @Override + public void testAddStopThenDeliver() throws Exception { + // In Memory store that's stopped doesn't retain the jobs. + } - @Override - protected JobSchedulerStore createJobSchedulerStore() throws Exception { - return new InMemoryJobSchedulerStore(); - } + @Override + protected JobSchedulerStore createJobSchedulerStore() throws Exception { + return new InMemoryJobSchedulerStore(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerTxTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerTxTest.java index fb87905881..ab9e8095d8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerTxTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerTxTest.java @@ -23,8 +23,8 @@ import org.apache.activemq.broker.scheduler.JobSchedulerTxTest; */ public class InMemoryJobSchedulerTxTest extends JobSchedulerTxTest { - @Override - protected boolean isPersistent() { - return false; - } + @Override + protected boolean isPersistent() { + return false; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/DefaultStoreBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/DefaultStoreBrokerTest.java index 1e9633af22..8d030e03a8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/DefaultStoreBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/DefaultStoreBrokerTest.java @@ -26,25 +26,23 @@ import org.apache.activemq.broker.BrokerTest; /** * Once the wire format is completed we can test against real persistence storage. - * - * */ public class DefaultStoreBrokerTest extends BrokerTest { - protected BrokerService createBroker() throws Exception { - return BrokerFactory.createBroker(new URI("broker://()/localhost?deleteAllMessagesOnStartup=true")); - } - - protected BrokerService createRestartedBroker() throws Exception { - return BrokerFactory.createBroker(new URI("broker://()/localhost")); - } - - public static Test suite() { - return suite(DefaultStoreBrokerTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + protected BrokerService createBroker() throws Exception { + return BrokerFactory.createBroker(new URI("broker://()/localhost?deleteAllMessagesOnStartup=true")); + } + + protected BrokerService createRestartedBroker() throws Exception { + return BrokerFactory.createBroker(new URI("broker://()/localhost")); + } + + public static Test suite() { + return suite(DefaultStoreBrokerTest.class); + } + + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/DefaultStoreRecoveryBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/DefaultStoreRecoveryBrokerTest.java index e89ca04a24..f75373d73b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/DefaultStoreRecoveryBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/DefaultStoreRecoveryBrokerTest.java @@ -25,26 +25,24 @@ import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.RecoveryBrokerTest; /** - * Used to verify that recovery works correctly against - * - * + * Used to verify that recovery works correctly against */ public class DefaultStoreRecoveryBrokerTest extends RecoveryBrokerTest { - protected BrokerService createBroker() throws Exception { - return BrokerFactory.createBroker(new URI("broker://()/localhost?deleteAllMessagesOnStartup=true")); - } - - protected BrokerService createRestartedBroker() throws Exception { - return BrokerFactory.createBroker(new URI("broker://()/localhost")); - } - - public static Test suite() { - return suite(DefaultStoreRecoveryBrokerTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + protected BrokerService createBroker() throws Exception { + return BrokerFactory.createBroker(new URI("broker://()/localhost?deleteAllMessagesOnStartup=true")); + } + + protected BrokerService createRestartedBroker() throws Exception { + return BrokerFactory.createBroker(new URI("broker://()/localhost")); + } + + public static Test suite() { + return suite(DefaultStoreRecoveryBrokerTest.class); + } + + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/LoadTester.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/LoadTester.java index a6d78b4a60..212c955370 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/LoadTester.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/LoadTester.java @@ -44,67 +44,66 @@ import org.slf4j.LoggerFactory; */ public class LoadTester extends JmsTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(LoadTester.class); + private static final Logger LOG = LoggerFactory.getLogger(LoadTester.class); - protected int messageSize = 1024 * 64; - protected int produceCount = 10000; + protected int messageSize = 1024 * 64; + protected int produceCount = 10000; - @Override - protected BrokerService createBroker() throws Exception { - return BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/broker/store/loadtester.xml")); - } + @Override + protected BrokerService createBroker() throws Exception { + return BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/broker/store/loadtester.xml")); + } - @Override - protected ConnectionFactory createConnectionFactory() throws URISyntaxException, IOException { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getServer().getConnectURI()); - factory.setUseAsyncSend(true); - return factory; - } + @Override + protected ConnectionFactory createConnectionFactory() throws URISyntaxException, IOException { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getServer().getConnectURI()); + factory.setUseAsyncSend(true); + return factory; + } - public void testQueueSendThenAddConsumer() throws Exception { - ProgressPrinter printer = new ProgressPrinter(produceCount, 20); + public void testQueueSendThenAddConsumer() throws Exception { + ProgressPrinter printer = new ProgressPrinter(produceCount, 20); - ActiveMQDestination destination = new ActiveMQQueue("TEST"); + ActiveMQDestination destination = new ActiveMQQueue("TEST"); - connection.setUseCompression(false); - connection.getPrefetchPolicy().setAll(10); - connection.start(); - Session session = connection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); + connection.setUseCompression(false); + connection.getPrefetchPolicy().setAll(10); + connection.start(); + Session session = connection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); - LOG.info("Sending " + produceCount + " messages that are " + (messageSize / 1024.0) + "k large, for a total of " + (produceCount * messageSize / (1024.0 * 1024.0)) - + " megs of data."); - // Send a message to the broker. - long start = System.currentTimeMillis(); - for (int i = 0; i < produceCount; i++) { - printer.increment(); - BytesMessage msg = session.createBytesMessage(); - msg.writeBytes(new byte[messageSize]); - producer.send(msg); - } - long end1 = System.currentTimeMillis(); + LOG.info("Sending " + produceCount + " messages that are " + (messageSize / 1024.0) + "k large, for a total of " + (produceCount * messageSize / (1024.0 * 1024.0)) + " megs of data."); + // Send a message to the broker. + long start = System.currentTimeMillis(); + for (int i = 0; i < produceCount; i++) { + printer.increment(); + BytesMessage msg = session.createBytesMessage(); + msg.writeBytes(new byte[messageSize]); + producer.send(msg); + } + long end1 = System.currentTimeMillis(); - LOG.info("Produced messages/sec: " + (produceCount * 1000.0 / (end1 - start))); + LOG.info("Produced messages/sec: " + (produceCount * 1000.0 / (end1 - start))); - printer = new ProgressPrinter(produceCount, 10); - start = System.currentTimeMillis(); - MessageConsumer consumer = session.createConsumer(destination); - for (int i = 0; i < produceCount; i++) { - printer.increment(); - assertNotNull("Getting message: " + i, consumer.receive(20000)); - } - end1 = System.currentTimeMillis(); - LOG.info("Consumed messages/sec: " + (produceCount * 1000.0 / (end1 - start))); + printer = new ProgressPrinter(produceCount, 10); + start = System.currentTimeMillis(); + MessageConsumer consumer = session.createConsumer(destination); + for (int i = 0; i < produceCount; i++) { + printer.increment(); + assertNotNull("Getting message: " + i, consumer.receive(20000)); + } + end1 = System.currentTimeMillis(); + LOG.info("Consumed messages/sec: " + (produceCount * 1000.0 / (end1 - start))); - } + } - public static Test suite() { - return suite(LoadTester.class); - } + public static Test suite() { + return suite(LoadTester.class); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/RecoverExpiredMessagesTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/RecoverExpiredMessagesTest.java index fb0296c4ce..0ec435a5f6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/RecoverExpiredMessagesTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/RecoverExpiredMessagesTest.java @@ -19,7 +19,9 @@ package org.apache.activemq.broker.store; import java.io.File; import java.util.ArrayList; import java.util.concurrent.TimeUnit; + import junit.framework.Test; + import org.apache.activemq.broker.BrokerRestartTestSupport; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.StubConnection; @@ -42,103 +44,100 @@ import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; import org.apache.activemq.util.IOHelper; public class RecoverExpiredMessagesTest extends BrokerRestartTestSupport { - final ArrayList expected = new ArrayList(); - final ActiveMQDestination destination = new ActiveMQQueue("TEST"); - public PendingQueueMessageStoragePolicy queuePendingPolicy; - @Override - protected void setUp() throws Exception { - setAutoFail(true); - super.setUp(); - } + final ArrayList expected = new ArrayList(); + final ActiveMQDestination destination = new ActiveMQQueue("TEST"); + public PendingQueueMessageStoragePolicy queuePendingPolicy; - public void initCombosForTestRecovery() throws Exception { - addCombinationValues("queuePendingPolicy", new PendingQueueMessageStoragePolicy[] {new FilePendingQueueMessageStoragePolicy(), new VMPendingQueueMessageStoragePolicy()}); - PersistenceAdapter[] persistenceAdapters = new PersistenceAdapter[] { - new KahaDBPersistenceAdapter(), - new JDBCPersistenceAdapter(JDBCPersistenceAdapter.createDataSource(IOHelper.getDefaultDataDirectory()), new OpenWireFormat()) - }; - for (PersistenceAdapter adapter : persistenceAdapters) { - adapter.setDirectory(new File(IOHelper.getDefaultDataDirectory())); - } - addCombinationValues("persistenceAdapter", persistenceAdapters); - } + @Override + protected void setUp() throws Exception { + setAutoFail(true); + super.setUp(); + } - public void testRecovery() throws Exception { - sendSomeMessagesThatWillExpireIn5AndThenOne(); + public void initCombosForTestRecovery() throws Exception { + addCombinationValues("queuePendingPolicy", new PendingQueueMessageStoragePolicy[]{new FilePendingQueueMessageStoragePolicy(), new VMPendingQueueMessageStoragePolicy()}); + PersistenceAdapter[] persistenceAdapters = new PersistenceAdapter[]{new KahaDBPersistenceAdapter(), new JDBCPersistenceAdapter(JDBCPersistenceAdapter.createDataSource(IOHelper.getDefaultDataDirectory()), new OpenWireFormat())}; + for (PersistenceAdapter adapter : persistenceAdapters) { + adapter.setDirectory(new File(IOHelper.getDefaultDataDirectory())); + } + addCombinationValues("persistenceAdapter", persistenceAdapters); + } - broker.stop(); - broker.waitUntilStopped(); - TimeUnit.SECONDS.sleep(6); - broker = createRestartedBroker(); - broker.start(); + public void testRecovery() throws Exception { + sendSomeMessagesThatWillExpireIn5AndThenOne(); - consumeExpected(); - } + broker.stop(); + broker.waitUntilStopped(); + TimeUnit.SECONDS.sleep(6); + broker = createRestartedBroker(); + broker.start(); - private void consumeExpected() throws Exception { - // Setup the consumer and receive the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); + consumeExpected(); + } - Message m = receiveMessage(connection); - assertNotNull("Should have received message " + expected.get(0) + " by now!", m); - assertEquals(expected.get(0), m.getMessageId().toString()); - MessageAck ack = createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE); - connection.send(ack); + private void consumeExpected() throws Exception { + // Setup the consumer and receive the message. + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); - assertNoMessagesLeft(connection); - connection.request(closeConnectionInfo(connectionInfo)); - } + Message m = receiveMessage(connection); + assertNotNull("Should have received message " + expected.get(0) + " by now!", m); + assertEquals(expected.get(0), m.getMessageId().toString()); + MessageAck ack = createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE); + connection.send(ack); - private void sendSomeMessagesThatWillExpireIn5AndThenOne() throws Exception { + assertNoMessagesLeft(connection); + connection.request(closeConnectionInfo(connectionInfo)); + } - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); + private void sendSomeMessagesThatWillExpireIn5AndThenOne() throws Exception { + // Setup the producer and send the message. + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); - int MESSAGE_COUNT = 10; - for(int i=0; i < MESSAGE_COUNT; i++) { - Message message = createMessage(producerInfo, destination); - message.setExpiration(System.currentTimeMillis()+5000); - message.setPersistent(true); - connection.send(message); - } - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - expected.add(message.getMessageId().toString()); + int MESSAGE_COUNT = 10; + for (int i = 0; i < MESSAGE_COUNT; i++) { + Message message = createMessage(producerInfo, destination); + message.setExpiration(System.currentTimeMillis() + 5000); + message.setPersistent(true); + connection.send(message); + } + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + connection.send(message); + expected.add(message.getMessageId().toString()); - connection.request(closeConnectionInfo(connectionInfo)); - } + connection.request(closeConnectionInfo(connectionInfo)); + } - @Override - protected PolicyEntry getDefaultPolicy() { - PolicyEntry policy = super.getDefaultPolicy(); - policy.setPendingQueuePolicy(queuePendingPolicy); - policy.setExpireMessagesPeriod(0); - return policy; - } + @Override + protected PolicyEntry getDefaultPolicy() { + PolicyEntry policy = super.getDefaultPolicy(); + policy.setPendingQueuePolicy(queuePendingPolicy); + policy.setExpireMessagesPeriod(0); + return policy; + } - @Override - protected void configureBroker(BrokerService broker) throws Exception { - super.configureBroker(broker); - broker.setPersistenceAdapter(persistenceAdapter); - } + @Override + protected void configureBroker(BrokerService broker) throws Exception { + super.configureBroker(broker); + broker.setPersistenceAdapter(persistenceAdapter); + } - public static Test suite() { - return suite(RecoverExpiredMessagesTest.class); - } + public static Test suite() { + return suite(RecoverExpiredMessagesTest.class); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/DestinationsPluginTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/DestinationsPluginTest.java index d08fc5e076..9f65a3c1e0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/DestinationsPluginTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/DestinationsPluginTest.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.broker.util; - import org.apache.activemq.broker.BrokerPlugin; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.jmx.BrokerView; @@ -27,54 +26,52 @@ import org.junit.Test; import static org.junit.Assert.*; - public class DestinationsPluginTest { - BrokerService broker; + BrokerService broker; - @Before - public void setUp() throws Exception { - broker = createBroker(); - broker.start(); - broker.waitUntilStarted(); - } + @Before + public void setUp() throws Exception { + broker = createBroker(); + broker.start(); + broker.waitUntilStarted(); + } - @After - public void shutdown() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } + @After + public void shutdown() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + } - protected BrokerService createBroker() { - BrokerService broker = new BrokerService(); - broker.setPersistent(false); - broker.setUseJmx(true); - broker.setPlugins(new BrokerPlugin[]{new DestinationsPlugin()}); - broker.setDataDirectory("target/test"); - return broker; - } + protected BrokerService createBroker() { + BrokerService broker = new BrokerService(); + broker.setPersistent(false); + broker.setUseJmx(true); + broker.setPlugins(new BrokerPlugin[]{new DestinationsPlugin()}); + broker.setDataDirectory("target/test"); + return broker; + } - @Test - public void testDestinationSave() throws Exception { + @Test + public void testDestinationSave() throws Exception { - BrokerView brokerView = broker.getAdminView(); - brokerView.addQueue("test-queue"); + BrokerView brokerView = broker.getAdminView(); + brokerView.addQueue("test-queue"); - broker.stop(); - broker.waitUntilStopped(); + broker.stop(); + broker.waitUntilStopped(); - broker = createBroker(); - broker.start(); - broker.waitUntilStarted(); + broker = createBroker(); + broker.start(); + broker.waitUntilStarted(); + ActiveMQDestination[] destinations = broker.getRegionBroker().getDestinations(); + for (ActiveMQDestination destination : destinations) { + if (destination.isQueue()) { + assertEquals("test-queue", destination.getPhysicalName()); + } + } - ActiveMQDestination[] destinations = broker.getRegionBroker().getDestinations(); - for (ActiveMQDestination destination : destinations) { - if (destination.isQueue()) { - assertEquals("test-queue", destination.getPhysicalName()); - } - } - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/PluginBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/PluginBrokerTest.java index 93618599da..a0e5abd646 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/PluginBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/PluginBrokerTest.java @@ -29,60 +29,64 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * - * + * + * */ public class PluginBrokerTest extends JmsTopicSendReceiveTest { - private static final Logger LOG = LoggerFactory.getLogger(PluginBrokerTest.class); - private BrokerService broker; - protected void setUp() throws Exception { - broker = createBroker(); - super.setUp(); - } + private static final Logger LOG = LoggerFactory.getLogger(PluginBrokerTest.class); + private BrokerService broker; - protected void tearDown() throws Exception { - super.tearDown(); - if (broker != null) { - broker.stop(); - } - } + protected void setUp() throws Exception { + broker = createBroker(); + super.setUp(); + } - protected BrokerService createBroker() throws Exception { - return createBroker("org/apache/activemq/util/plugin-broker.xml"); - } + protected void tearDown() throws Exception { + super.tearDown(); + if (broker != null) { + broker.stop(); + } + } - protected BrokerService createBroker(String uri) throws Exception { - LOG.info("Loading broker configuration from the classpath with URI: " + uri); - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } + protected BrokerService createBroker() throws Exception { + return createBroker("org/apache/activemq/util/plugin-broker.xml"); + } + + protected BrokerService createBroker(String uri) throws Exception { + LOG.info("Loading broker configuration from the classpath with URI: " + uri); + return BrokerFactory.createBroker(new URI("xbean:" + uri)); + } + + protected void assertMessageValid(int index, Message message) throws JMSException { + // check if broker path has been set + assertEquals("localhost", message.getStringProperty("BrokerPath")); + ActiveMQMessage amqMsg = (ActiveMQMessage) message; + if (index == 7) { + // check custom expiration + assertTrue("expiration is in range, depends on two distinct calls to System.currentTimeMillis", 1500 < amqMsg.getExpiration() - amqMsg.getTimestamp()); + } + else if (index == 9) { + // check ceiling + assertTrue("expiration ceeling is in range, depends on two distinct calls to System.currentTimeMillis", 59500 < amqMsg.getExpiration() - amqMsg.getTimestamp()); + } + else { + // check default expiration + assertEquals(1000, amqMsg.getExpiration() - amqMsg.getTimestamp()); + } + super.assertMessageValid(index, message); + } + + protected void sendMessage(int index, Message message) throws Exception { + if (index == 7) { + producer.send(producerDestination, message, Message.DEFAULT_DELIVERY_MODE, Message.DEFAULT_PRIORITY, 2000); + } + else if (index == 9) { + producer.send(producerDestination, message, Message.DEFAULT_DELIVERY_MODE, Message.DEFAULT_PRIORITY, 200000); + } + else { + super.sendMessage(index, message); + } + } - protected void assertMessageValid(int index, Message message) - throws JMSException { - // check if broker path has been set - assertEquals("localhost", message.getStringProperty("BrokerPath")); - ActiveMQMessage amqMsg = (ActiveMQMessage)message; - if (index == 7) { - // check custom expiration - assertTrue("expiration is in range, depends on two distinct calls to System.currentTimeMillis", 1500 < amqMsg.getExpiration() - amqMsg.getTimestamp()); - } else if (index == 9) { - // check ceiling - assertTrue("expiration ceeling is in range, depends on two distinct calls to System.currentTimeMillis", 59500 < amqMsg.getExpiration() - amqMsg.getTimestamp()); - } else { - // check default expiration - assertEquals(1000, amqMsg.getExpiration() - amqMsg.getTimestamp()); - } - super.assertMessageValid(index, message); - } - - protected void sendMessage(int index, Message message) throws Exception { - if (index == 7) { - producer.send(producerDestination, message, Message.DEFAULT_DELIVERY_MODE, Message.DEFAULT_PRIORITY, 2000); - } else if (index == 9) { - producer.send(producerDestination, message, Message.DEFAULT_DELIVERY_MODE, Message.DEFAULT_PRIORITY, 200000); - } else { - super.sendMessage(index, message); - } - } - } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/RedeliveryPluginTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/RedeliveryPluginTest.java index dd12768f6d..06e3ab868b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/RedeliveryPluginTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/RedeliveryPluginTest.java @@ -17,6 +17,7 @@ package org.apache.activemq.broker.util; import junit.framework.TestCase; + import org.apache.activemq.RedeliveryPolicy; import org.apache.activemq.broker.Broker; import org.apache.activemq.broker.BrokerService; @@ -26,48 +27,52 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RedeliveryPluginTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(RedeliveryPluginTest.class); - RedeliveryPlugin underTest = new RedeliveryPlugin(); - public void testInstallPluginValidation() throws Exception { - RedeliveryPolicyMap redeliveryPolicyMap = new RedeliveryPolicyMap(); - RedeliveryPolicy defaultEntry = new RedeliveryPolicy(); - defaultEntry.setInitialRedeliveryDelay(500); - redeliveryPolicyMap.setDefaultEntry(defaultEntry); - underTest.setRedeliveryPolicyMap(redeliveryPolicyMap); + private static final Logger LOG = LoggerFactory.getLogger(RedeliveryPluginTest.class); + RedeliveryPlugin underTest = new RedeliveryPlugin(); - final BrokerService brokerService = new BrokerService(); - brokerService.setSchedulerSupport(false); - Broker broker = new ErrorBroker("hi") { - @Override - public BrokerService getBrokerService() { - return brokerService; - } - }; + public void testInstallPluginValidation() throws Exception { + RedeliveryPolicyMap redeliveryPolicyMap = new RedeliveryPolicyMap(); + RedeliveryPolicy defaultEntry = new RedeliveryPolicy(); + defaultEntry.setInitialRedeliveryDelay(500); + redeliveryPolicyMap.setDefaultEntry(defaultEntry); + underTest.setRedeliveryPolicyMap(redeliveryPolicyMap); - try { - underTest.installPlugin(broker); - fail("expect exception on no scheduler support"); - } catch (Exception expected) { - LOG.info("expected: " + expected); - } + final BrokerService brokerService = new BrokerService(); + brokerService.setSchedulerSupport(false); + Broker broker = new ErrorBroker("hi") { + @Override + public BrokerService getBrokerService() { + return brokerService; + } + }; - brokerService.setSchedulerSupport(true); - try { - underTest.installPlugin(broker); - fail("expect exception on small initial delay"); - } catch (Exception expected) { - LOG.info("expected: " + expected); - } + try { + underTest.installPlugin(broker); + fail("expect exception on no scheduler support"); + } + catch (Exception expected) { + LOG.info("expected: " + expected); + } - defaultEntry.setInitialRedeliveryDelay(5000); - defaultEntry.setRedeliveryDelay(500); - brokerService.setSchedulerSupport(true); - try { - underTest.installPlugin(broker); - fail("expect exception on small redelivery delay"); - } catch (Exception expected) { - LOG.info("expected: " + expected); - } - } + brokerService.setSchedulerSupport(true); + try { + underTest.installPlugin(broker); + fail("expect exception on small initial delay"); + } + catch (Exception expected) { + LOG.info("expected: " + expected); + } + + defaultEntry.setInitialRedeliveryDelay(5000); + defaultEntry.setRedeliveryDelay(500); + brokerService.setSchedulerSupport(true); + try { + underTest.installPlugin(broker); + fail("expect exception on small redelivery delay"); + } + catch (Exception expected) { + LOG.info("expected: " + expected); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/TimeStampingBrokerPluginTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/TimeStampingBrokerPluginTest.java index 1a91f88dee..0d1cbbc0f8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/TimeStampingBrokerPluginTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/TimeStampingBrokerPluginTest.java @@ -23,7 +23,9 @@ import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; + import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerPlugin; import org.apache.activemq.broker.BrokerService; @@ -38,160 +40,161 @@ import org.junit.Test; public class TimeStampingBrokerPluginTest extends TestCase { - BrokerService broker; - TransportConnector tcpConnector; - MessageProducer producer; - MessageConsumer consumer; - Connection connection; - Session session; - Destination destination; - String queue = "TEST.FOO"; - long expiry = 500; - - @Before - public void setUp() throws Exception { - TimeStampingBrokerPlugin tsbp = new TimeStampingBrokerPlugin(); - tsbp.setZeroExpirationOverride(expiry); - tsbp.setTtlCeiling(expiry); - - broker = new BrokerService(); - broker.setPersistent(false); - broker.setUseJmx(true); - broker.setPlugins(new BrokerPlugin[] {tsbp}); - tcpConnector = broker.addConnector("tcp://localhost:0"); - - // Add policy and individual DLQ strategy - PolicyEntry policy = new PolicyEntry(); - DeadLetterStrategy strategy = new IndividualDeadLetterStrategy(); - strategy.setProcessExpired(true); - ((IndividualDeadLetterStrategy)strategy).setUseQueueForQueueMessages(true); - ((IndividualDeadLetterStrategy)strategy).setQueuePrefix("DLQ."); - strategy.setProcessNonPersistent(true); - policy.setDeadLetterStrategy(strategy); + BrokerService broker; + TransportConnector tcpConnector; + MessageProducer producer; + MessageConsumer consumer; + Connection connection; + Session session; + Destination destination; + String queue = "TEST.FOO"; + long expiry = 500; - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); + @Before + public void setUp() throws Exception { + TimeStampingBrokerPlugin tsbp = new TimeStampingBrokerPlugin(); + tsbp.setZeroExpirationOverride(expiry); + tsbp.setTtlCeiling(expiry); - broker.setDestinationPolicy(pMap); - - broker.start(); - // Create a ConnectionFactory - ActiveMQConnectionFactory connectionFactory = - new ActiveMQConnectionFactory(tcpConnector.getConnectUri()); + broker = new BrokerService(); + broker.setPersistent(false); + broker.setUseJmx(true); + broker.setPlugins(new BrokerPlugin[]{tsbp}); + tcpConnector = broker.addConnector("tcp://localhost:0"); - // Create a Connection - connection = connectionFactory.createConnection(); - connection.start(); + // Add policy and individual DLQ strategy + PolicyEntry policy = new PolicyEntry(); + DeadLetterStrategy strategy = new IndividualDeadLetterStrategy(); + strategy.setProcessExpired(true); + ((IndividualDeadLetterStrategy) strategy).setUseQueueForQueueMessages(true); + ((IndividualDeadLetterStrategy) strategy).setQueuePrefix("DLQ."); + strategy.setProcessNonPersistent(true); + policy.setDeadLetterStrategy(strategy); - // Create a Session - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); - // Create the destination Queue - destination = session.createQueue(queue); + broker.setDestinationPolicy(pMap); - // Create a MessageProducer from the Session to the Topic or Queue - producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - } - - @After - public void tearDown() throws Exception { - // Clean up - producer.close(); - consumer.close(); - session.close(); - connection.close(); - broker.stop(); - } - @Test - public void testExpirationSet() throws Exception { - - // Create a messages - Message sentMessage = session.createMessage(); + broker.start(); + // Create a ConnectionFactory + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(tcpConnector.getConnectUri()); - // Tell the producer to send the message - long beforeSend = System.currentTimeMillis(); - producer.send(sentMessage); + // Create a Connection + connection = connectionFactory.createConnection(); + connection.start(); - // Create a MessageConsumer from the Session to the Topic or Queue - consumer = session.createConsumer(destination); + // Create a Session + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - // Wait for a message - Message receivedMessage = consumer.receive(1000); + // Create the destination Queue + destination = session.createQueue(queue); - // assert we got the same message ID we sent - assertEquals(sentMessage.getJMSMessageID(), receivedMessage.getJMSMessageID()); - - // assert message timestamp is in window - assertTrue("Expiration should be not null" + receivedMessage.getJMSExpiration() + "\n", Long.valueOf(receivedMessage.getJMSExpiration()) != null); + // Create a MessageProducer from the Session to the Topic or Queue + producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + } - // assert message expiration is in window - assertTrue("Before send: " + beforeSend + " Msg ts: " + receivedMessage.getJMSTimestamp() + " Msg Expiry: " + receivedMessage.getJMSExpiration(), beforeSend <= receivedMessage.getJMSExpiration() && receivedMessage.getJMSExpiration() <= (receivedMessage.getJMSTimestamp() + expiry)); - } - @Test - public void testExpirationCelingSet() throws Exception { - - // Create a messages - Message sentMessage = session.createMessage(); - // Tell the producer to send the message - long beforeSend = System.currentTimeMillis(); - long sendExpiry = beforeSend + (expiry*22); - sentMessage.setJMSExpiration(sendExpiry); + @After + public void tearDown() throws Exception { + // Clean up + producer.close(); + consumer.close(); + session.close(); + connection.close(); + broker.stop(); + } - producer.send(sentMessage); + @Test + public void testExpirationSet() throws Exception { - // Create a MessageConsumer from the Session to the Topic or Queue - consumer = session.createConsumer(destination); + // Create a messages + Message sentMessage = session.createMessage(); - // Wait for a message - Message receivedMessage = consumer.receive(1000); + // Tell the producer to send the message + long beforeSend = System.currentTimeMillis(); + producer.send(sentMessage); - // assert we got the same message ID we sent - assertEquals(sentMessage.getJMSMessageID(), receivedMessage.getJMSMessageID()); - - // assert message timestamp is in window - assertTrue("Expiration should be not null" + receivedMessage.getJMSExpiration() + "\n", Long.valueOf(receivedMessage.getJMSExpiration()) != null); + // Create a MessageConsumer from the Session to the Topic or Queue + consumer = session.createConsumer(destination); - // assert message expiration is in window - assertTrue("Sent expiry: " + sendExpiry + " Recv ts: " + receivedMessage.getJMSTimestamp() + " Recv expiry: " + receivedMessage.getJMSExpiration(), beforeSend <= receivedMessage.getJMSExpiration() && receivedMessage.getJMSExpiration() <= (receivedMessage.getJMSTimestamp() + expiry)); - } - - @Test - public void testExpirationDLQ() throws Exception { - - // Create a messages - Message sentMessage = session.createMessage(); - // Tell the producer to send the message - long beforeSend = System.currentTimeMillis(); - long sendExpiry = beforeSend + expiry; - sentMessage.setJMSExpiration(sendExpiry); + // Wait for a message + Message receivedMessage = consumer.receive(1000); - producer.send(sentMessage); + // assert we got the same message ID we sent + assertEquals(sentMessage.getJMSMessageID(), receivedMessage.getJMSMessageID()); - // Create a MessageConsumer from the Session to the Topic or Queue - consumer = session.createConsumer(destination); + // assert message timestamp is in window + assertTrue("Expiration should be not null" + receivedMessage.getJMSExpiration() + "\n", Long.valueOf(receivedMessage.getJMSExpiration()) != null); - Thread.sleep(expiry+250); - - // Wait for a message - Message receivedMessage = consumer.receive(1000); + // assert message expiration is in window + assertTrue("Before send: " + beforeSend + " Msg ts: " + receivedMessage.getJMSTimestamp() + " Msg Expiry: " + receivedMessage.getJMSExpiration(), beforeSend <= receivedMessage.getJMSExpiration() && receivedMessage.getJMSExpiration() <= (receivedMessage.getJMSTimestamp() + expiry)); + } - // Message should roll to DLQ - assertNull(receivedMessage); - - // Close old consumer, setup DLQ listener - consumer.close(); - consumer = session.createConsumer(session.createQueue("DLQ."+queue)); - - // Get mesage from DLQ - receivedMessage = consumer.receive(1000); + @Test + public void testExpirationCelingSet() throws Exception { - // assert we got the same message ID we sent - assertEquals(sentMessage.getJMSMessageID(), receivedMessage.getJMSMessageID()); - - // assert message timestamp is in window - //System.out.println("Recv: " + receivedMessage.getJMSExpiration()); - assertEquals("Expiration should be zero" + receivedMessage.getJMSExpiration() + "\n", receivedMessage.getJMSExpiration(), 0); - - } + // Create a messages + Message sentMessage = session.createMessage(); + // Tell the producer to send the message + long beforeSend = System.currentTimeMillis(); + long sendExpiry = beforeSend + (expiry * 22); + sentMessage.setJMSExpiration(sendExpiry); + + producer.send(sentMessage); + + // Create a MessageConsumer from the Session to the Topic or Queue + consumer = session.createConsumer(destination); + + // Wait for a message + Message receivedMessage = consumer.receive(1000); + + // assert we got the same message ID we sent + assertEquals(sentMessage.getJMSMessageID(), receivedMessage.getJMSMessageID()); + + // assert message timestamp is in window + assertTrue("Expiration should be not null" + receivedMessage.getJMSExpiration() + "\n", Long.valueOf(receivedMessage.getJMSExpiration()) != null); + + // assert message expiration is in window + assertTrue("Sent expiry: " + sendExpiry + " Recv ts: " + receivedMessage.getJMSTimestamp() + " Recv expiry: " + receivedMessage.getJMSExpiration(), beforeSend <= receivedMessage.getJMSExpiration() && receivedMessage.getJMSExpiration() <= (receivedMessage.getJMSTimestamp() + expiry)); + } + + @Test + public void testExpirationDLQ() throws Exception { + + // Create a messages + Message sentMessage = session.createMessage(); + // Tell the producer to send the message + long beforeSend = System.currentTimeMillis(); + long sendExpiry = beforeSend + expiry; + sentMessage.setJMSExpiration(sendExpiry); + + producer.send(sentMessage); + + // Create a MessageConsumer from the Session to the Topic or Queue + consumer = session.createConsumer(destination); + + Thread.sleep(expiry + 250); + + // Wait for a message + Message receivedMessage = consumer.receive(1000); + + // Message should roll to DLQ + assertNull(receivedMessage); + + // Close old consumer, setup DLQ listener + consumer.close(); + consumer = session.createConsumer(session.createQueue("DLQ." + queue)); + + // Get mesage from DLQ + receivedMessage = consumer.receive(1000); + + // assert we got the same message ID we sent + assertEquals(sentMessage.getJMSMessageID(), receivedMessage.getJMSMessageID()); + + // assert message timestamp is in window + //System.out.println("Recv: " + receivedMessage.getJMSExpiration()); + assertEquals("Expiration should be zero" + receivedMessage.getJMSExpiration() + "\n", receivedMessage.getJMSExpiration(), 0); + + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/TraceBrokerPathPluginTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/TraceBrokerPathPluginTest.java index 35e9cdb840..b385c5aa6c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/TraceBrokerPathPluginTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/TraceBrokerPathPluginTest.java @@ -13,7 +13,7 @@ * 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.broker.util; @@ -36,94 +36,94 @@ import org.junit.Test; /** * Tests TraceBrokerPathPlugin by creating two brokers linked by a network connector, and checking to see if the consuming end receives the expected value in the trace property - * @author Raul Kripalani * + * @author Raul Kripalani */ public class TraceBrokerPathPluginTest extends TestCase { - BrokerService brokerA; - BrokerService brokerB; - TransportConnector tcpConnectorA; - TransportConnector tcpConnectorB; - MessageProducer producer; - MessageConsumer consumer; - Connection connectionA; - Connection connectionB; - Session sessionA; - Session sessionB; - String queue = "TEST.FOO"; - String traceProperty = "BROKER_PATH"; - - @Before - public void setUp() throws Exception { - TraceBrokerPathPlugin tbppA = new TraceBrokerPathPlugin(); - tbppA.setStampProperty(traceProperty); - - TraceBrokerPathPlugin tbppB = new TraceBrokerPathPlugin(); - tbppB.setStampProperty(traceProperty); - - brokerA = new BrokerService(); - brokerA.setBrokerName("brokerA"); - brokerA.setPersistent(false); - brokerA.setUseJmx(true); - brokerA.setPlugins(new BrokerPlugin[] {tbppA}); - tcpConnectorA = brokerA.addConnector("tcp://localhost:0"); + BrokerService brokerA; + BrokerService brokerB; + TransportConnector tcpConnectorA; + TransportConnector tcpConnectorB; + MessageProducer producer; + MessageConsumer consumer; + Connection connectionA; + Connection connectionB; + Session sessionA; + Session sessionB; + String queue = "TEST.FOO"; + String traceProperty = "BROKER_PATH"; - brokerB = new BrokerService(); - brokerB.setBrokerName("brokerB"); - brokerB.setPersistent(false); - brokerB.setUseJmx(true); - brokerB.setPlugins(new BrokerPlugin[] {tbppB}); - tcpConnectorB = brokerB.addConnector("tcp://localhost:0"); - - brokerA.addNetworkConnector("static:(" + tcpConnectorB.getConnectUri().toString() + ")"); - - brokerB.start(); - brokerB.waitUntilStarted(); - brokerA.start(); - brokerA.waitUntilStarted(); - - // Initialise connection to A and MessageProducer - connectionA = new ActiveMQConnectionFactory(tcpConnectorA.getConnectUri()).createConnection(); - connectionA.start(); - sessionA = connectionA.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = sessionA.createProducer(sessionA.createQueue(queue)); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - - // Initialise connection to B and MessageConsumer - connectionB = new ActiveMQConnectionFactory(tcpConnectorB.getConnectUri()).createConnection(); - connectionB.start(); - sessionB = connectionB.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = sessionB.createConsumer(sessionB.createQueue(queue)); - - } - - @After - public void tearDown() throws Exception { - // Clean up - producer.close(); - consumer.close(); - sessionA.close(); - sessionB.close(); - connectionA.close(); - connectionB.close(); - brokerA.stop(); - brokerB.stop(); - } - - @Test - public void testTraceBrokerPathPlugin() throws Exception { - Message sentMessage = sessionA.createMessage(); - producer.send(sentMessage); - Message receivedMessage = consumer.receive(1000); + @Before + public void setUp() throws Exception { + TraceBrokerPathPlugin tbppA = new TraceBrokerPathPlugin(); + tbppA.setStampProperty(traceProperty); - // assert we got the message - assertNotNull(receivedMessage); - - // assert we got the same message ID we sent - assertEquals(sentMessage.getJMSMessageID(), receivedMessage.getJMSMessageID()); - - assertEquals("brokerA,brokerB", receivedMessage.getStringProperty(traceProperty)); - - } + TraceBrokerPathPlugin tbppB = new TraceBrokerPathPlugin(); + tbppB.setStampProperty(traceProperty); + + brokerA = new BrokerService(); + brokerA.setBrokerName("brokerA"); + brokerA.setPersistent(false); + brokerA.setUseJmx(true); + brokerA.setPlugins(new BrokerPlugin[]{tbppA}); + tcpConnectorA = brokerA.addConnector("tcp://localhost:0"); + + brokerB = new BrokerService(); + brokerB.setBrokerName("brokerB"); + brokerB.setPersistent(false); + brokerB.setUseJmx(true); + brokerB.setPlugins(new BrokerPlugin[]{tbppB}); + tcpConnectorB = brokerB.addConnector("tcp://localhost:0"); + + brokerA.addNetworkConnector("static:(" + tcpConnectorB.getConnectUri().toString() + ")"); + + brokerB.start(); + brokerB.waitUntilStarted(); + brokerA.start(); + brokerA.waitUntilStarted(); + + // Initialise connection to A and MessageProducer + connectionA = new ActiveMQConnectionFactory(tcpConnectorA.getConnectUri()).createConnection(); + connectionA.start(); + sessionA = connectionA.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer = sessionA.createProducer(sessionA.createQueue(queue)); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + + // Initialise connection to B and MessageConsumer + connectionB = new ActiveMQConnectionFactory(tcpConnectorB.getConnectUri()).createConnection(); + connectionB.start(); + sessionB = connectionB.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumer = sessionB.createConsumer(sessionB.createQueue(queue)); + + } + + @After + public void tearDown() throws Exception { + // Clean up + producer.close(); + consumer.close(); + sessionA.close(); + sessionB.close(); + connectionA.close(); + connectionB.close(); + brokerA.stop(); + brokerB.stop(); + } + + @Test + public void testTraceBrokerPathPlugin() throws Exception { + Message sentMessage = sessionA.createMessage(); + producer.send(sentMessage); + Message receivedMessage = consumer.receive(1000); + + // assert we got the message + assertNotNull(receivedMessage); + + // assert we got the same message ID we sent + assertEquals(sentMessage.getJMSMessageID(), receivedMessage.getJMSMessageID()); + + assertEquals("brokerA,brokerB", receivedMessage.getStringProperty(traceProperty)); + + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/CompositeQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/CompositeQueueTest.java index 3621a14eec..4a0f7ccdb5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/CompositeQueueTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/CompositeQueueTest.java @@ -36,97 +36,97 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * - * + * + * */ public class CompositeQueueTest extends EmbeddedBrokerTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(CompositeQueueTest.class); - - protected int total = 10; - protected Connection connection; - public String messageSelector1, messageSelector2 = null; + private static final Logger LOG = LoggerFactory.getLogger(CompositeQueueTest.class); + protected int total = 10; + protected Connection connection; + public String messageSelector1, messageSelector2 = null; - public void testVirtualTopicCreation() throws Exception { - if (connection == null) { - connection = createConnection(); - } - connection.start(); + public void testVirtualTopicCreation() throws Exception { + if (connection == null) { + connection = createConnection(); + } + connection.start(); - ConsumerBean messageList1 = new ConsumerBean(); - ConsumerBean messageList2 = new ConsumerBean(); - messageList1.setVerbose(true); - messageList2.setVerbose(true); + ConsumerBean messageList1 = new ConsumerBean(); + ConsumerBean messageList2 = new ConsumerBean(); + messageList1.setVerbose(true); + messageList2.setVerbose(true); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - Destination producerDestination = getProducerDestination(); - Destination destination1 = getConsumer1Dsetination(); - Destination destination2 = getConsumer2Dsetination(); - - LOG.info("Sending to: " + producerDestination); - LOG.info("Consuming from: " + destination1 + " and " + destination2); - - MessageConsumer c1 = session.createConsumer(destination1, messageSelector1); - MessageConsumer c2 = session.createConsumer(destination2, messageSelector2); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - c1.setMessageListener(messageList1); - c2.setMessageListener(messageList2); + Destination producerDestination = getProducerDestination(); + Destination destination1 = getConsumer1Dsetination(); + Destination destination2 = getConsumer2Dsetination(); - // create topic producer - MessageProducer producer = session.createProducer(producerDestination); - assertNotNull(producer); + LOG.info("Sending to: " + producerDestination); + LOG.info("Consuming from: " + destination1 + " and " + destination2); - for (int i = 0; i < total; i++) { - producer.send(createMessage(session, i)); - } + MessageConsumer c1 = session.createConsumer(destination1, messageSelector1); + MessageConsumer c2 = session.createConsumer(destination2, messageSelector2); - assertMessagesArrived(messageList1, messageList2); - } + c1.setMessageListener(messageList1); + c2.setMessageListener(messageList2); - protected void assertMessagesArrived(ConsumerBean messageList1, ConsumerBean messageList2) { - messageList1.assertMessagesArrived(total); - messageList2.assertMessagesArrived(total); - } + // create topic producer + MessageProducer producer = session.createProducer(producerDestination); + assertNotNull(producer); - protected TextMessage createMessage(Session session, int i) throws JMSException { - TextMessage textMessage = session.createTextMessage("message: " + i); - if (i % 2 != 0) { - textMessage.setStringProperty("odd", "yes"); - } else { - textMessage.setStringProperty("odd", "no"); - } - textMessage.setIntProperty("i", i); - return textMessage; - } + for (int i = 0; i < total; i++) { + producer.send(createMessage(session, i)); + } - protected Destination getConsumer1Dsetination() { - return new ActiveMQQueue("FOO"); - } + assertMessagesArrived(messageList1, messageList2); + } - protected Destination getConsumer2Dsetination() { - return new ActiveMQTopic("BAR"); - } + protected void assertMessagesArrived(ConsumerBean messageList1, ConsumerBean messageList2) { + messageList1.assertMessagesArrived(total); + messageList2.assertMessagesArrived(total); + } - protected Destination getProducerDestination() { - return new ActiveMQQueue("MY.QUEUE"); - } + protected TextMessage createMessage(Session session, int i) throws JMSException { + TextMessage textMessage = session.createTextMessage("message: " + i); + if (i % 2 != 0) { + textMessage.setStringProperty("odd", "yes"); + } + else { + textMessage.setStringProperty("odd", "no"); + } + textMessage.setIntProperty("i", i); + return textMessage; + } - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - super.tearDown(); - } + protected Destination getConsumer1Dsetination() { + return new ActiveMQQueue("FOO"); + } - protected BrokerService createBroker() throws Exception { - XBeanBrokerFactory factory = new XBeanBrokerFactory(); - BrokerService answer = factory.createBroker(new URI(getBrokerConfigUri())); - return answer; - } + protected Destination getConsumer2Dsetination() { + return new ActiveMQTopic("BAR"); + } - protected String getBrokerConfigUri() { - return "org/apache/activemq/broker/virtual/composite-queue.xml"; - } + protected Destination getProducerDestination() { + return new ActiveMQQueue("MY.QUEUE"); + } + + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + } + super.tearDown(); + } + + protected BrokerService createBroker() throws Exception { + XBeanBrokerFactory factory = new XBeanBrokerFactory(); + BrokerService answer = factory.createBroker(new URI(getBrokerConfigUri())); + return answer; + } + + protected String getBrokerConfigUri() { + return "org/apache/activemq/broker/virtual/composite-queue.xml"; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/CompositeTopicTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/CompositeTopicTest.java index 991e3a56e0..0035fe3fac 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/CompositeTopicTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/CompositeTopicTest.java @@ -23,23 +23,23 @@ import org.apache.activemq.command.ActiveMQTopic; /** * - * + * */ public class CompositeTopicTest extends CompositeQueueTest { - - protected Destination getConsumer1Dsetination() { - return new ActiveMQQueue("FOO"); - } - protected Destination getConsumer2Dsetination() { - return new ActiveMQTopic("BAR"); - } + protected Destination getConsumer1Dsetination() { + return new ActiveMQQueue("FOO"); + } - protected Destination getProducerDestination() { - return new ActiveMQTopic("MY.TOPIC"); - } + protected Destination getConsumer2Dsetination() { + return new ActiveMQTopic("BAR"); + } - protected String getBrokerConfigUri() { - return "org/apache/activemq/broker/virtual/composite-topic.xml"; - } + protected Destination getProducerDestination() { + return new ActiveMQTopic("MY.TOPIC"); + } + + protected String getBrokerConfigUri() { + return "org/apache/activemq/broker/virtual/composite-topic.xml"; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/DestinationInterceptorDurableSubTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/DestinationInterceptorDurableSubTest.java index b6ba22d075..fb001ee924 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/DestinationInterceptorDurableSubTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/DestinationInterceptorDurableSubTest.java @@ -47,236 +47,231 @@ import org.apache.activemq.xbean.XBeanBrokerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - /** * Test for AMQ-4571. - * checks that durable subscription is fully unregistered + * checks that durable subscription is fully unregistered * when using nested destination interceptors. */ public class DestinationInterceptorDurableSubTest extends EmbeddedBrokerTestSupport { - private static final transient Logger LOG = LoggerFactory.getLogger(DestinationInterceptorDurableSubTest.class); - private MBeanServerConnection mbsc = null; - public static final String JMX_CONTEXT_BASE_NAME = "org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Topic,destinationName="; + private static final transient Logger LOG = LoggerFactory.getLogger(DestinationInterceptorDurableSubTest.class); + private MBeanServerConnection mbsc = null; + public static final String JMX_CONTEXT_BASE_NAME = "org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Topic,destinationName="; - /** - * Tests AMQ-4571. - * @throws Exception - */ - public void testVirtualTopicRemoval() throws Exception { + /** + * Tests AMQ-4571. + * + * @throws Exception + */ + public void testVirtualTopicRemoval() throws Exception { - LOG.debug("Running testVirtualTopicRemoval()"); - String clientId1 = "myId1"; - String clientId2 = "myId2"; + LOG.debug("Running testVirtualTopicRemoval()"); + String clientId1 = "myId1"; + String clientId2 = "myId2"; - Connection conn = null; - Session session = null; + Connection conn = null; + Session session = null; - try { - assertTrue(broker.isStarted()); + try { + assertTrue(broker.isStarted()); - // create durable sub 1 - conn = createConnection(); - conn.setClientID(clientId1); - conn.start(); - session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - // Topic topic = session.createTopic(destination.getPhysicalName()); - TopicSubscriber sub1 = session.createDurableSubscriber((Topic) destination, clientId1); + // create durable sub 1 + conn = createConnection(); + conn.setClientID(clientId1); + conn.start(); + session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + // Topic topic = session.createTopic(destination.getPhysicalName()); + TopicSubscriber sub1 = session.createDurableSubscriber((Topic) destination, clientId1); - // create durable sub 2 - TopicSubscriber sub2 = session.createDurableSubscriber((Topic) destination, clientId2); + // create durable sub 2 + TopicSubscriber sub2 = session.createDurableSubscriber((Topic) destination, clientId2); - // verify two subs registered in JMX - assertSubscriptionCount(destination.getPhysicalName(), 2); - assertTrue(isSubRegisteredInJmx(destination.getPhysicalName(), clientId1)); - assertTrue(isSubRegisteredInJmx(destination.getPhysicalName(), clientId2)); + // verify two subs registered in JMX + assertSubscriptionCount(destination.getPhysicalName(), 2); + assertTrue(isSubRegisteredInJmx(destination.getPhysicalName(), clientId1)); + assertTrue(isSubRegisteredInJmx(destination.getPhysicalName(), clientId2)); - // delete sub 1 - sub1.close(); - session.unsubscribe(clientId1); + // delete sub 1 + sub1.close(); + session.unsubscribe(clientId1); - // verify only one sub registered in JMX - assertSubscriptionCount(destination.getPhysicalName(), 1); - assertFalse(isSubRegisteredInJmx(destination.getPhysicalName(), clientId1)); - assertTrue(isSubRegisteredInJmx(destination.getPhysicalName(), clientId2)); + // verify only one sub registered in JMX + assertSubscriptionCount(destination.getPhysicalName(), 1); + assertFalse(isSubRegisteredInJmx(destination.getPhysicalName(), clientId1)); + assertTrue(isSubRegisteredInJmx(destination.getPhysicalName(), clientId2)); - // delete sub 2 - sub2.close(); - session.unsubscribe(clientId2); + // delete sub 2 + sub2.close(); + session.unsubscribe(clientId2); - // verify no sub registered in JMX - assertSubscriptionCount(destination.getPhysicalName(), 0); - assertFalse(isSubRegisteredInJmx(destination.getPhysicalName(), clientId1)); - assertFalse(isSubRegisteredInJmx(destination.getPhysicalName(), clientId2)); - } finally { - session.close(); - conn.close(); - } - } + // verify no sub registered in JMX + assertSubscriptionCount(destination.getPhysicalName(), 0); + assertFalse(isSubRegisteredInJmx(destination.getPhysicalName(), clientId1)); + assertFalse(isSubRegisteredInJmx(destination.getPhysicalName(), clientId2)); + } + finally { + session.close(); + conn.close(); + } + } + /** + * Connects to broker using JMX + * + * @return The JMX connection + * @throws IOException in case of any errors + */ + protected MBeanServerConnection connectJMXBroker() throws IOException { + // connect to broker via JMX + JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:1299/jmxrmi"); + JMXConnector jmxc = JMXConnectorFactory.connect(url, null); + MBeanServerConnection mbsc = jmxc.getMBeanServerConnection(); + LOG.debug("JMX connection established"); + return mbsc; + } - /** - * Connects to broker using JMX - * @return The JMX connection - * @throws IOException in case of any errors - */ - protected MBeanServerConnection connectJMXBroker() throws IOException { - // connect to broker via JMX - JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:1299/jmxrmi"); - JMXConnector jmxc = JMXConnectorFactory.connect(url, null); - MBeanServerConnection mbsc = jmxc.getMBeanServerConnection(); - LOG.debug("JMX connection established"); - return mbsc; - } + /** + * Asserts that the Subscriptions JMX attribute of a topic has the expected + * count. + * + * @param topicName name of the topic destination + * @param expectedCount expected number of subscriptions + * @return + */ + protected boolean assertSubscriptionCount(String topicName, int expectedCount) { + try { + if (mbsc == null) { + mbsc = connectJMXBroker(); + } + // query broker queue size + ObjectName[] tmp = (ObjectName[]) mbsc.getAttribute(new ObjectName(JMX_CONTEXT_BASE_NAME + topicName), "Subscriptions"); + assertEquals(expectedCount, tmp.length); + } + catch (Exception ex) { + LOG.error(ex.getMessage()); + return false; + } + return true; + } - /** - * Asserts that the Subscriptions JMX attribute of a topic has the expected - * count. - * @param topicName name of the topic destination - * @param expectedCount expected number of subscriptions - * @return - */ - protected boolean assertSubscriptionCount(String topicName, int expectedCount) { - try { - if (mbsc == null) { - mbsc = connectJMXBroker(); - } - // query broker queue size - ObjectName[] tmp = (ObjectName[])mbsc.getAttribute(new ObjectName(JMX_CONTEXT_BASE_NAME + topicName), "Subscriptions"); - assertEquals(expectedCount, tmp.length); - } catch (Exception ex) { - LOG.error(ex.getMessage()); + /** + * Checks if a subscriptions for topic topicName with subName is registered in JMX + * + * @param topicName physical name of topic destination (excluding prefix 'topic://') + * @param subName name of the durable subscription + * @return true if registered, false otherwise + */ + protected boolean isSubRegisteredInJmx(String topicName, String subName) { + + try { + if (mbsc == null) { + mbsc = connectJMXBroker(); + } + + // A durable sub is registered under the Subscriptions JMX attribute of the topic and + // as its own ObjectInstance under the topic's Consumer namespace. + // AMQ-4571 only removed the latter not the former on unsubscribe(), so we need + // to check against both. + ObjectName[] names = (ObjectName[]) mbsc.getAttribute(new ObjectName(JMX_CONTEXT_BASE_NAME + topicName), "Subscriptions"); + ObjectInstance instance = (ObjectInstance) mbsc.getObjectInstance(new ObjectName(JMX_CONTEXT_BASE_NAME + + topicName + + ",endpoint=Consumer,clientId=myId1,consumerId=Durable(myId1_" + + subName + + ")")); + + if (instance == null) return false; - } - return true; - } - /** - * Checks if a subscriptions for topic topicName with subName is registered in JMX - * - * @param topicName physical name of topic destination (excluding prefix 'topic://') - * @param subName name of the durable subscription - * @return true if registered, false otherwise - */ - protected boolean isSubRegisteredInJmx(String topicName, String subName) { + for (int i = 0; i < names.length; i++) { + if (names[i].toString().contains(subName)) + return true; + } + } + catch (InstanceNotFoundException ine) { + //this may be expected so log at info level + LOG.info(ine.toString()); + return false; + } + catch (Exception ex) { + LOG.error(ex.toString()); + return false; + } + return false; + } - try { - if (mbsc == null) { - mbsc = connectJMXBroker(); - } + protected void tearDown() throws Exception { + super.tearDown(); + } - // A durable sub is registered under the Subscriptions JMX attribute of the topic and - // as its own ObjectInstance under the topic's Consumer namespace. - // AMQ-4571 only removed the latter not the former on unsubscribe(), so we need - // to check against both. - ObjectName[] names = (ObjectName[])mbsc.getAttribute(new ObjectName(JMX_CONTEXT_BASE_NAME + topicName), "Subscriptions"); - ObjectInstance instance = (ObjectInstance)mbsc.getObjectInstance( - new ObjectName(JMX_CONTEXT_BASE_NAME + - topicName + - ",endpoint=Consumer,clientId=myId1,consumerId=Durable(myId1_" + - subName + - ")") - ); + protected BrokerService createBroker() throws Exception { + XBeanBrokerFactory factory = new XBeanBrokerFactory(); + BrokerService answer = factory.createBroker(new URI(getBrokerConfigUri())); - if (instance == null) - return false; + // lets disable persistence as we are a test + answer.setPersistent(false); + useTopic = true; + return answer; + } - for (int i=0; i < names.length; i++) { - if (names[i].toString().contains(subName)) - return true; - } - } catch (InstanceNotFoundException ine) { - //this may be expected so log at info level - LOG.info(ine.toString()); - return false; - } - catch (Exception ex) { - LOG.error(ex.toString()); - return false; - } - return false; - } + protected String getBrokerConfigUri() { + return "org/apache/activemq/broker/virtual/virtual-topics-and-interceptor.xml"; + } + /** + * Simple but custom topic interceptor. + * To be used for testing nested interceptors in conjunction with + * virtual topic interceptor. + */ + public static class SimpleDestinationInterceptor implements DestinationInterceptor { - protected void tearDown() throws Exception { - super.tearDown(); - } + private final Logger LOG = LoggerFactory.getLogger(SimpleDestinationInterceptor.class); + private BrokerService broker; + public SimpleDestinationInterceptor() { + } - protected BrokerService createBroker() throws Exception { - XBeanBrokerFactory factory = new XBeanBrokerFactory(); - BrokerService answer = factory.createBroker(new URI(getBrokerConfigUri())); + /* (non-Javadoc) + * @see org.apache.activemq.broker.BrokerServiceAware#setBrokerService(org.apache.activemq.broker.BrokerService) + */ + public void setBrokerService(BrokerService brokerService) { + LOG.info("setBrokerService()"); + this.broker = brokerService; + } - // lets disable persistence as we are a test - answer.setPersistent(false); - useTopic = true; - return answer; - } + /* (non-Javadoc) + * @see org.apache.activemq.broker.region.DestinationInterceptor#intercept(org.apache.activemq.broker.region.Destination) + */ + public Destination intercept(final Destination destination) { + LOG.info("intercept({})", destination.getName()); - - protected String getBrokerConfigUri() { - return "org/apache/activemq/broker/virtual/virtual-topics-and-interceptor.xml"; - } - - - /** - * Simple but custom topic interceptor. - * To be used for testing nested interceptors in conjunction with - * virtual topic interceptor. - */ - public static class SimpleDestinationInterceptor implements DestinationInterceptor { - - private final Logger LOG = LoggerFactory.getLogger(SimpleDestinationInterceptor.class); - private BrokerService broker; - - public SimpleDestinationInterceptor() { - } - - /* (non-Javadoc) - * @see org.apache.activemq.broker.BrokerServiceAware#setBrokerService(org.apache.activemq.broker.BrokerService) - */ - public void setBrokerService(BrokerService brokerService) { - LOG.info("setBrokerService()"); - this.broker = brokerService; - } - - /* (non-Javadoc) - * @see org.apache.activemq.broker.region.DestinationInterceptor#intercept(org.apache.activemq.broker.region.Destination) - */ - public Destination intercept(final Destination destination) { - LOG.info("intercept({})", destination.getName()); - - if (!destination.getActiveMQDestination().getPhysicalName().startsWith("ActiveMQ")) { - return new DestinationFilter(destination) { - public void send(ProducerBrokerExchange context, Message message) throws Exception { - // Send message to Destination - if (LOG.isDebugEnabled()) { - LOG.debug("SimpleDestinationInterceptor: Sending message to destination:" - + this.getActiveMQDestination().getPhysicalName()); - } - // message.setDestination(destination.getActiveMQDestination()); - super.send(context, message); + if (!destination.getActiveMQDestination().getPhysicalName().startsWith("ActiveMQ")) { + return new DestinationFilter(destination) { + public void send(ProducerBrokerExchange context, Message message) throws Exception { + // Send message to Destination + if (LOG.isDebugEnabled()) { + LOG.debug("SimpleDestinationInterceptor: Sending message to destination:" + this.getActiveMQDestination().getPhysicalName()); } - }; - } - return destination; - } + // message.setDestination(destination.getActiveMQDestination()); + super.send(context, message); + } + }; + } + return destination; + } + /* (non-Javadoc) + * @see org.apache.activemq.broker.region.DestinationInterceptor#remove(org.apache.activemq.broker.region.Destination) + */ + public void remove(Destination destination) { + LOG.info("remove({})", destination.getName()); + this.broker = null; + } - /* (non-Javadoc) - * @see org.apache.activemq.broker.region.DestinationInterceptor#remove(org.apache.activemq.broker.region.Destination) - */ - public void remove(Destination destination) { - LOG.info("remove({})", destination.getName()); - this.broker = null; - } - - - /* (non-Javadoc) - * @see org.apache.activemq.broker.region.DestinationInterceptor#create(org.apache.activemq.broker.Broker, org.apache.activemq.broker.ConnectionContext, org.apache.activemq.command.ActiveMQDestination) - */ - public void create(Broker broker, ConnectionContext context, ActiveMQDestination destination) throws Exception { - LOG.info("create("+ broker.getBrokerName() + ", " + context.toString() + ", " + destination.getPhysicalName()); - } - } + /* (non-Javadoc) + * @see org.apache.activemq.broker.region.DestinationInterceptor#create(org.apache.activemq.broker.Broker, org.apache.activemq.broker.ConnectionContext, org.apache.activemq.command.ActiveMQDestination) + */ + public void create(Broker broker, ConnectionContext context, ActiveMQDestination destination) throws Exception { + LOG.info("create(" + broker.getBrokerName() + ", " + context.toString() + ", " + destination.getPhysicalName()); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/FilteredQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/FilteredQueueTest.java index 17a870638c..e91ae4b881 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/FilteredQueueTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/FilteredQueueTest.java @@ -19,18 +19,18 @@ package org.apache.activemq.broker.virtual; import org.apache.activemq.spring.ConsumerBean; /** - * + * */ public class FilteredQueueTest extends CompositeQueueTest { - @Override - protected String getBrokerConfigUri() { - return "org/apache/activemq/broker/virtual/filtered-queue.xml"; - } + @Override + protected String getBrokerConfigUri() { + return "org/apache/activemq/broker/virtual/filtered-queue.xml"; + } - @Override - protected void assertMessagesArrived(ConsumerBean messageList1, ConsumerBean messageList2) { - messageList1.assertMessagesArrived(total / 2); - messageList2.assertMessagesArrived(1); - } + @Override + protected void assertMessagesArrived(ConsumerBean messageList1, ConsumerBean messageList2) { + messageList1.assertMessagesArrived(total / 2); + messageList2.assertMessagesArrived(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/MirroredQueueCorrectMemoryUsageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/MirroredQueueCorrectMemoryUsageTest.java index 4c19c7b254..3b0c03d259 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/MirroredQueueCorrectMemoryUsageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/MirroredQueueCorrectMemoryUsageTest.java @@ -61,105 +61,105 @@ import org.springframework.util.Assert; */ public class MirroredQueueCorrectMemoryUsageTest extends EmbeddedBrokerTestSupport { - private static final Logger logger = LoggerFactory.getLogger(MirroredQueueCorrectMemoryUsageTest.class); + private static final Logger logger = LoggerFactory.getLogger(MirroredQueueCorrectMemoryUsageTest.class); - private static final long ONE_MB = 0x0100000; - private static final long TEN_MB = ONE_MB * 10; - private static final long TWENTY_MB = TEN_MB * 2; + private static final long ONE_MB = 0x0100000; + private static final long TEN_MB = ONE_MB * 10; + private static final long TWENTY_MB = TEN_MB * 2; - private static final String CREATED_STATIC_FOR_PERSISTENT = "created.static.for.persistent"; + private static final String CREATED_STATIC_FOR_PERSISTENT = "created.static.for.persistent"; - @Override - protected boolean isPersistent() { - return true; - } + @Override + protected boolean isPersistent() { + return true; + } - @Override - protected BrokerService createBroker() throws Exception { - // Create the broker service instance.... - BrokerService broker = super.createBroker(); - // Create and add the mirrored queue destination interceptor .... - DestinationInterceptor[] destinationInterceptors = new DestinationInterceptor[1]; - MirroredQueue mq = new MirroredQueue(); - mq.setCopyMessage(true); - mq.setPrefix(""); - mq.setPostfix(".qmirror"); - destinationInterceptors[0] = mq; - broker.setDestinationInterceptors(destinationInterceptors); - // Create the destination policy for the topics and queues - PolicyMap policyMap = new PolicyMap(); - List entries = new LinkedList(); - // Create Topic policy entry - PolicyEntry policyEntry = new PolicyEntry(); - super.useTopic = true; - ActiveMQDestination destination = super.createDestination(">"); - Assert.isTrue(destination.isTopic(), "Created destination was not a topic"); - policyEntry.setDestination(destination); - policyEntry.setProducerFlowControl(true); - policyEntry.setMemoryLimit(ONE_MB); // x10 - entries.add(policyEntry); - // Create Queue policy entry - policyEntry = new PolicyEntry(); - super.useTopic = false; - destination = super.createDestination(CREATED_STATIC_FOR_PERSISTENT); - Assert.isTrue(destination.isQueue(), "Created destination was not a queue"); - policyEntry.setDestination(destination); - policyEntry.setProducerFlowControl(true); - policyEntry.setMemoryLimit(TEN_MB); - entries.add(policyEntry); - policyMap.setPolicyEntries(entries); - broker.setDestinationPolicy(policyMap); - // Set destinations - broker.setDestinations(new ActiveMQDestination[] { destination }); - // Set system usage - SystemUsage memoryManager = new SystemUsage(); - MemoryUsage memoryUsage = new MemoryUsage(); - memoryUsage.setLimit(TEN_MB); - memoryManager.setMemoryUsage(memoryUsage); - StoreUsage storeUsage = new StoreUsage(); - storeUsage.setLimit(TWENTY_MB); - memoryManager.setStoreUsage(storeUsage); - TempUsage tempDiskUsage = new TempUsage(); - tempDiskUsage.setLimit(TEN_MB); - memoryManager.setTempUsage(tempDiskUsage); - broker.setSystemUsage(memoryManager); - // Set the persistent adapter - KahaDBPersistenceAdapter persistenceAdapter = new KahaDBPersistenceAdapter(); - persistenceAdapter.setJournalMaxFileLength((int)TEN_MB); - // Delete all current messages... - IOHelper.deleteFile(persistenceAdapter.getDirectory()); - broker.setPersistenceAdapter(persistenceAdapter); - return broker; - } + @Override + protected BrokerService createBroker() throws Exception { + // Create the broker service instance.... + BrokerService broker = super.createBroker(); + // Create and add the mirrored queue destination interceptor .... + DestinationInterceptor[] destinationInterceptors = new DestinationInterceptor[1]; + MirroredQueue mq = new MirroredQueue(); + mq.setCopyMessage(true); + mq.setPrefix(""); + mq.setPostfix(".qmirror"); + destinationInterceptors[0] = mq; + broker.setDestinationInterceptors(destinationInterceptors); + // Create the destination policy for the topics and queues + PolicyMap policyMap = new PolicyMap(); + List entries = new LinkedList(); + // Create Topic policy entry + PolicyEntry policyEntry = new PolicyEntry(); + super.useTopic = true; + ActiveMQDestination destination = super.createDestination(">"); + Assert.isTrue(destination.isTopic(), "Created destination was not a topic"); + policyEntry.setDestination(destination); + policyEntry.setProducerFlowControl(true); + policyEntry.setMemoryLimit(ONE_MB); // x10 + entries.add(policyEntry); + // Create Queue policy entry + policyEntry = new PolicyEntry(); + super.useTopic = false; + destination = super.createDestination(CREATED_STATIC_FOR_PERSISTENT); + Assert.isTrue(destination.isQueue(), "Created destination was not a queue"); + policyEntry.setDestination(destination); + policyEntry.setProducerFlowControl(true); + policyEntry.setMemoryLimit(TEN_MB); + entries.add(policyEntry); + policyMap.setPolicyEntries(entries); + broker.setDestinationPolicy(policyMap); + // Set destinations + broker.setDestinations(new ActiveMQDestination[]{destination}); + // Set system usage + SystemUsage memoryManager = new SystemUsage(); + MemoryUsage memoryUsage = new MemoryUsage(); + memoryUsage.setLimit(TEN_MB); + memoryManager.setMemoryUsage(memoryUsage); + StoreUsage storeUsage = new StoreUsage(); + storeUsage.setLimit(TWENTY_MB); + memoryManager.setStoreUsage(storeUsage); + TempUsage tempDiskUsage = new TempUsage(); + tempDiskUsage.setLimit(TEN_MB); + memoryManager.setTempUsage(tempDiskUsage); + broker.setSystemUsage(memoryManager); + // Set the persistent adapter + KahaDBPersistenceAdapter persistenceAdapter = new KahaDBPersistenceAdapter(); + persistenceAdapter.setJournalMaxFileLength((int) TEN_MB); + // Delete all current messages... + IOHelper.deleteFile(persistenceAdapter.getDirectory()); + broker.setPersistenceAdapter(persistenceAdapter); + return broker; + } - @Before - protected void setUp() throws Exception { - super.setUp(); - } + @Before + protected void setUp() throws Exception { + super.setUp(); + } - @After - protected void tearDown() throws Exception { - super.tearDown(); - } + @After + protected void tearDown() throws Exception { + super.tearDown(); + } - @Test(timeout=40000) - public void testNoMemoryUsageIncreaseForTopic() throws Exception { - Connection connection = super.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Destination destination = session.createQueue(CREATED_STATIC_FOR_PERSISTENT); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - char[] m = new char[1024]; - Arrays.fill(m, 'x'); - // create some messages that have 1k each - for (int i = 1; i < 12000; i++) { - producer.send(session.createTextMessage(new String(m))); - logger.debug("Sent message: " + i); - } - producer.close(); - session.close(); - connection.stop(); - connection.close(); - } + @Test(timeout = 40000) + public void testNoMemoryUsageIncreaseForTopic() throws Exception { + Connection connection = super.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Destination destination = session.createQueue(CREATED_STATIC_FOR_PERSISTENT); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + char[] m = new char[1024]; + Arrays.fill(m, 'x'); + // create some messages that have 1k each + for (int i = 1; i < 12000; i++) { + producer.send(session.createTextMessage(new String(m))); + logger.debug("Sent message: " + i); + } + producer.close(); + session.close(); + connection.stop(); + connection.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/MirroredQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/MirroredQueueTest.java index acbe3b99a6..127f04c49b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/MirroredQueueTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/MirroredQueueTest.java @@ -36,81 +36,81 @@ import org.slf4j.LoggerFactory; * */ public class MirroredQueueTest extends EmbeddedBrokerTestSupport { - private static final transient Logger LOG = LoggerFactory.getLogger(MirroredQueueTest.class); - private Connection connection; - public void testSendingToQueueIsMirrored() throws Exception { - if (connection == null) { - connection = createConnection(); - } - connection.start(); + private static final transient Logger LOG = LoggerFactory.getLogger(MirroredQueueTest.class); + private Connection connection; - ConsumerBean messageList = new ConsumerBean(); - messageList.setVerbose(true); + public void testSendingToQueueIsMirrored() throws Exception { + if (connection == null) { + connection = createConnection(); + } + connection.start(); - Destination consumeDestination = createConsumeDestination(); + ConsumerBean messageList = new ConsumerBean(); + messageList.setVerbose(true); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - LOG.info("Consuming from: " + consumeDestination); + Destination consumeDestination = createConsumeDestination(); - MessageConsumer c1 = session.createConsumer(consumeDestination); - c1.setMessageListener(messageList); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + LOG.info("Consuming from: " + consumeDestination); - // create topic producer - ActiveMQQueue sendDestination = new ActiveMQQueue(getQueueName()); - LOG.info("Sending to: " + sendDestination); + MessageConsumer c1 = session.createConsumer(consumeDestination); + c1.setMessageListener(messageList); - MessageProducer producer = session.createProducer(sendDestination); - assertNotNull(producer); + // create topic producer + ActiveMQQueue sendDestination = new ActiveMQQueue(getQueueName()); + LOG.info("Sending to: " + sendDestination); - int total = 10; - for (int i = 0; i < total; i++) { - producer.send(session.createTextMessage("message: " + i)); - } + MessageProducer producer = session.createProducer(sendDestination); + assertNotNull(producer); - ///Thread.sleep(1000000); + int total = 10; + for (int i = 0; i < total; i++) { + producer.send(session.createTextMessage("message: " + i)); + } - messageList.assertMessagesArrived(total); + ///Thread.sleep(1000000); - LOG.info("Received: " + messageList); - } + messageList.assertMessagesArrived(total); - public void testTempMirroredQueuesClearDown() throws Exception{ - if (connection == null) { - connection = createConnection(); - } - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TemporaryQueue tempQueue = session.createTemporaryQueue(); - RegionBroker rb = (RegionBroker) broker.getBroker().getAdaptor( - RegionBroker.class); - assertTrue(rb.getDestinationMap().size()==5); - tempQueue.delete(); - assertTrue(rb.getDestinationMap().size()==4); - } + LOG.info("Received: " + messageList); + } - protected Destination createConsumeDestination() { - return new ActiveMQTopic("VirtualTopic.Mirror." + getQueueName()); - } + public void testTempMirroredQueuesClearDown() throws Exception { + if (connection == null) { + connection = createConnection(); + } + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + TemporaryQueue tempQueue = session.createTemporaryQueue(); + RegionBroker rb = (RegionBroker) broker.getBroker().getAdaptor(RegionBroker.class); + assertTrue(rb.getDestinationMap().size() == 5); + tempQueue.delete(); + assertTrue(rb.getDestinationMap().size() == 4); + } - protected String getQueueName() { - return "My.Queue"; - } + protected Destination createConsumeDestination() { + return new ActiveMQTopic("VirtualTopic.Mirror." + getQueueName()); + } - @Override - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setUseMirroredQueues(true); - answer.setPersistent(isPersistent()); - answer.addConnector(bindAddress); - return answer; - } + protected String getQueueName() { + return "My.Queue"; + } - @Override - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - super.tearDown(); - } + @Override + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + answer.setUseMirroredQueues(true); + answer.setPersistent(isPersistent()); + answer.addConnector(bindAddress); + return answer; + } + + @Override + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + } + super.tearDown(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/MirroredQueueUsingVirtualTopicQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/MirroredQueueUsingVirtualTopicQueueTest.java index f8cccf495f..6acaad1e5f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/MirroredQueueUsingVirtualTopicQueueTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/MirroredQueueUsingVirtualTopicQueueTest.java @@ -22,13 +22,13 @@ import org.apache.activemq.command.ActiveMQQueue; /** * - * + * */ public class MirroredQueueUsingVirtualTopicQueueTest extends MirroredQueueTest { - @Override - protected Destination createConsumeDestination() { - String queueName = "Consumer.A.VirtualTopic.Mirror." + getQueueName(); - return new ActiveMQQueue(queueName); - } + @Override + protected Destination createConsumeDestination() { + String queueName = "Consumer.A.VirtualTopic.Mirror." + getQueueName(); + return new ActiveMQQueue(queueName); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualDestPerfTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualDestPerfTest.java index b822f5dca9..bcbf28bcc3 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualDestPerfTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualDestPerfTest.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.broker.virtual; - import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; @@ -29,6 +28,7 @@ import javax.jms.DeliveryMode; import javax.jms.MessageProducer; import javax.jms.Session; import javax.management.ObjectName; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.jmx.QueueViewMBean; @@ -49,161 +49,155 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; - public class VirtualDestPerfTest { - private static final Logger LOG = LoggerFactory.getLogger(VirtualDestPerfTest.class); - public int messageSize = 5*1024; - public int messageCount = 10000; - ActiveMQTopic target = new ActiveMQTopic("target"); - BrokerService brokerService; - ActiveMQConnectionFactory connectionFactory; + private static final Logger LOG = LoggerFactory.getLogger(VirtualDestPerfTest.class); + public int messageSize = 5 * 1024; + public int messageCount = 10000; + ActiveMQTopic target = new ActiveMQTopic("target"); + BrokerService brokerService; + ActiveMQConnectionFactory connectionFactory; - @Test - @Ignore("comparison test - 'new' no wait on future with async send broker side is always on") - public void testAsyncSendBurstToFillCache() throws Exception { - startBroker(4, true, true); - connectionFactory.setUseAsyncSend(true); + @Test + @Ignore("comparison test - 'new' no wait on future with async send broker side is always on") + public void testAsyncSendBurstToFillCache() throws Exception { + startBroker(4, true, true); + connectionFactory.setUseAsyncSend(true); - // a burst of messages to fill the cache - messageCount = 22000; - messageSize = 10*1024; + // a burst of messages to fill the cache + messageCount = 22000; + messageSize = 10 * 1024; - LinkedHashMap results = new LinkedHashMap(); + LinkedHashMap results = new LinkedHashMap(); + + final ActiveMQQueue queue = new ActiveMQQueue("targetQ"); + for (Integer numThreads : new Integer[]{1, 2}) { + ExecutorService executor = Executors.newFixedThreadPool(numThreads); + final AtomicLong numMessagesToSend = new AtomicLong(messageCount); + purge(); + long startTime = System.currentTimeMillis(); + for (int i = 0; i < numThreads; i++) { + executor.execute(new Runnable() { + @Override + public void run() { + try { + produceMessages(numMessagesToSend, queue); + } + catch (Exception e) { + e.printStackTrace(); + } + } + }); + } + executor.shutdown(); + executor.awaitTermination(5, TimeUnit.MINUTES); + long endTime = System.currentTimeMillis(); + long seconds = (endTime - startTime) / 1000; + LOG.info("For numThreads {} duration {}", numThreads.intValue(), seconds); + results.put(numThreads, seconds); + LOG.info("Broker got {} messages", brokerService.getAdminView().getTotalEnqueueCount()); + } + + brokerService.stop(); + brokerService.waitUntilStopped(); + LOG.info("Results: {}", results); + } + + private void purge() throws Exception { + ObjectName[] queues = brokerService.getAdminView().getQueues(); + if (queues.length == 1) { + QueueViewMBean queueViewMBean = (QueueViewMBean) brokerService.getManagementContext().newProxyInstance(queues[0], QueueViewMBean.class, false); + queueViewMBean.purge(); + } + } + + @Test + @Ignore("comparison test - takes too long and really needs a peek at the graph") + public void testPerf() throws Exception { + LinkedHashMap resultsT = new LinkedHashMap(); + LinkedHashMap resultsF = new LinkedHashMap(); + + for (int i = 2; i < 11; i++) { + for (Boolean concurrent : new Boolean[]{true, false}) { + startBroker(i, concurrent, false); - final ActiveMQQueue queue = new ActiveMQQueue("targetQ"); - for (Integer numThreads : new Integer[]{1, 2}) { - ExecutorService executor = Executors.newFixedThreadPool(numThreads); - final AtomicLong numMessagesToSend = new AtomicLong(messageCount); - purge(); long startTime = System.currentTimeMillis(); - for (int i=0;i resultsT = new LinkedHashMap(); - LinkedHashMap resultsF = new LinkedHashMap(); - - for (int i=2;i<11;i++) { - for (Boolean concurrent : new Boolean[]{true, false}) { - startBroker(i, concurrent, false); - - long startTime = System.currentTimeMillis(); - produceMessages(new AtomicLong(messageCount), target); - long endTime = System.currentTimeMillis(); - long seconds = (endTime - startTime) / 1000; - LOG.info("For routes {} duration {}", i, seconds); - if (concurrent) { - resultsT.put(i, seconds); - } else { - resultsF.put(i, seconds); - } - brokerService.stop(); - brokerService.waitUntilStopped(); + LOG.info("For routes {} duration {}", i, seconds); + if (concurrent) { + resultsT.put(i, seconds); } - } - LOG.info("results T{} F{}", resultsT, resultsF); - LOG.info("http://www.chartgo.com/samples.do?chart=line&border=1&show3d=0&width=600&height=500&roundedge=1&transparency=1&legend=1&title=Send:10k::Concurrent-v-Serial&xtitle=routes&ytitle=Duration(seconds)&chrtbkgndcolor=white&threshold=0.0&lang=en" - + "&xaxis1=" + toStr(resultsT.keySet()) - + "&yaxis1=" + toStr(resultsT.values()) - + "&group1=concurrent" - + "&xaxis2=" + toStr(resultsF.keySet()) - + "&yaxis2=" + toStr(resultsF.values()) - + "&group2=serial" - + "&from=linejsp"); - } + else { + resultsF.put(i, seconds); + } + brokerService.stop(); + brokerService.waitUntilStopped(); + } + } + LOG.info("results T{} F{}", resultsT, resultsF); + LOG.info("http://www.chartgo.com/samples.do?chart=line&border=1&show3d=0&width=600&height=500&roundedge=1&transparency=1&legend=1&title=Send:10k::Concurrent-v-Serial&xtitle=routes&ytitle=Duration(seconds)&chrtbkgndcolor=white&threshold=0.0&lang=en" + "&xaxis1=" + toStr(resultsT.keySet()) + "&yaxis1=" + toStr(resultsT.values()) + "&group1=concurrent" + "&xaxis2=" + toStr(resultsF.keySet()) + "&yaxis2=" + toStr(resultsF.values()) + "&group2=serial" + "&from=linejsp"); + } - private String toStr(Collection set) { - return set.toString().replace(",","%0D%0A").replace("[","").replace("]","").replace(" ", ""); - } + private String toStr(Collection set) { + return set.toString().replace(",", "%0D%0A").replace("[", "").replace("]", "").replace(" ", ""); + } - protected void produceMessages(AtomicLong messageCount, ActiveMQDestination destination) throws Exception { - final ByteSequence payLoad = new ByteSequence(new byte[messageSize]); - Connection connection = connectionFactory.createConnection(); - MessageProducer messageProducer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE).createProducer(destination); - messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT); - ActiveMQBytesMessage message = new ActiveMQBytesMessage(); - message.setContent(payLoad); - while (messageCount.decrementAndGet() >= 0) { - messageProducer.send(message); - } - connection.close(); - } + protected void produceMessages(AtomicLong messageCount, ActiveMQDestination destination) throws Exception { + final ByteSequence payLoad = new ByteSequence(new byte[messageSize]); + Connection connection = connectionFactory.createConnection(); + MessageProducer messageProducer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE).createProducer(destination); + messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT); + ActiveMQBytesMessage message = new ActiveMQBytesMessage(); + message.setContent(payLoad); + while (messageCount.decrementAndGet() >= 0) { + messageProducer.send(message); + } + connection.close(); + } - private void startBroker(int fanoutCount, boolean concurrentSend, boolean concurrentStoreAndDispatchQueues) throws Exception { - brokerService = new BrokerService(); - brokerService.setDeleteAllMessagesOnStartup(true); - brokerService.setUseVirtualTopics(true); - brokerService.addConnector("tcp://0.0.0.0:0"); - brokerService.setAdvisorySupport(false); - PolicyMap destPolicyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setExpireMessagesPeriod(0); - defaultEntry.setOptimizedDispatch(true); - defaultEntry.setCursorMemoryHighWaterMark(110); - destPolicyMap.setDefaultEntry(defaultEntry); - brokerService.setDestinationPolicy(destPolicyMap); + private void startBroker(int fanoutCount, + boolean concurrentSend, + boolean concurrentStoreAndDispatchQueues) throws Exception { + brokerService = new BrokerService(); + brokerService.setDeleteAllMessagesOnStartup(true); + brokerService.setUseVirtualTopics(true); + brokerService.addConnector("tcp://0.0.0.0:0"); + brokerService.setAdvisorySupport(false); + PolicyMap destPolicyMap = new PolicyMap(); + PolicyEntry defaultEntry = new PolicyEntry(); + defaultEntry.setExpireMessagesPeriod(0); + defaultEntry.setOptimizedDispatch(true); + defaultEntry.setCursorMemoryHighWaterMark(110); + destPolicyMap.setDefaultEntry(defaultEntry); + brokerService.setDestinationPolicy(destPolicyMap); - CompositeTopic route = new CompositeTopic(); - route.setName("target"); - route.setForwardOnly(true); - route.setConcurrentSend(concurrentSend); - Collection routes = new ArrayList(); - for (int i=0; i routes = new ArrayList(); + for (int i = 0; i < fanoutCount; i++) { + routes.add(new ActiveMQQueue("route." + i)); + } + route.setForwardTo(routes); + VirtualDestinationInterceptor interceptor = new VirtualDestinationInterceptor(); + interceptor.setVirtualDestinations(new VirtualDestination[]{route}); + brokerService.setDestinationInterceptors(new DestinationInterceptor[]{interceptor}); + brokerService.start(); - connectionFactory = new ActiveMQConnectionFactory(brokerService.getTransportConnectors().get(0).getPublishableConnectString()); - connectionFactory.setWatchTopicAdvisories(false); - if (brokerService.getPersistenceAdapter() instanceof KahaDBPersistenceAdapter) { + connectionFactory = new ActiveMQConnectionFactory(brokerService.getTransportConnectors().get(0).getPublishableConnectString()); + connectionFactory.setWatchTopicAdvisories(false); + if (brokerService.getPersistenceAdapter() instanceof KahaDBPersistenceAdapter) { - //with parallel sends and no consumers, concurrentStoreAnd dispatch, which uses a single thread by default - // will stop/impeed write batching. The num threads will need tweaking when consumers are in the mix but may introduce - // order issues - ((KahaDBPersistenceAdapter)brokerService.getPersistenceAdapter()).setConcurrentStoreAndDispatchQueues(concurrentStoreAndDispatchQueues); - } - } + //with parallel sends and no consumers, concurrentStoreAnd dispatch, which uses a single thread by default + // will stop/impeed write batching. The num threads will need tweaking when consumers are in the mix but may introduce + // order issues + ((KahaDBPersistenceAdapter) brokerService.getPersistenceAdapter()).setConcurrentStoreAndDispatchQueues(concurrentStoreAndDispatchQueues); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualTopicDLQTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualTopicDLQTest.java index f81ca71991..9abcbc71f1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualTopicDLQTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualTopicDLQTest.java @@ -50,366 +50,378 @@ import org.slf4j.LoggerFactory; /** * Unit test for virtual topics and DLQ messaging. See individual test for more * detail - * */ public class VirtualTopicDLQTest extends TestCase { - private static BrokerService broker; - private static final Logger LOG = LoggerFactory.getLogger(VirtualTopicDLQTest.class); + private static BrokerService broker; - static final String jmsConnectionURI = "failover:(vm://localhost)"; + private static final Logger LOG = LoggerFactory.getLogger(VirtualTopicDLQTest.class); - // Virtual Topic that the test publishes 10 messages to - private static final String virtualTopicName = "VirtualTopic.Test"; + static final String jmsConnectionURI = "failover:(vm://localhost)"; - // Queues that receive all the messages send to the virtual topic - private static final String consumer1Prefix = "Consumer.A."; - private static final String consumer2Prefix = "Consumer.B."; - private static final String consumer3Prefix = "Consumer.C."; + // Virtual Topic that the test publishes 10 messages to + private static final String virtualTopicName = "VirtualTopic.Test"; - // Expected Individual Dead Letter Queue names that are tied to the - // Subscriber Queues - private static final String dlqPrefix = "ActiveMQ.DLQ.Topic."; + // Queues that receive all the messages send to the virtual topic + private static final String consumer1Prefix = "Consumer.A."; + private static final String consumer2Prefix = "Consumer.B."; + private static final String consumer3Prefix = "Consumer.C."; - // Number of messages - private static final int numberMessages = 6; + // Expected Individual Dead Letter Queue names that are tied to the + // Subscriber Queues + private static final String dlqPrefix = "ActiveMQ.DLQ.Topic."; - @Before - public void setUp() throws Exception { - try { - broker = BrokerFactory.createBroker("xbean:org/apache/activemq/broker/virtual/virtual-individual-dlq.xml", true); - broker.start(); - broker.waitUntilStarted(); - } catch (Exception e) { + // Number of messages + private static final int numberMessages = 6; + + @Before + public void setUp() throws Exception { + try { + broker = BrokerFactory.createBroker("xbean:org/apache/activemq/broker/virtual/virtual-individual-dlq.xml", true); + broker.start(); + broker.waitUntilStarted(); + } + catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @After + public void tearDown() throws Exception { + try { + // Purge the DLQ's so counts are correct for next run + purgeDestination(dlqPrefix + consumer1Prefix + virtualTopicName); + purgeDestination(dlqPrefix + consumer2Prefix + virtualTopicName); + purgeDestination(dlqPrefix + consumer3Prefix + virtualTopicName); + } + catch (Exception e) { + e.printStackTrace(); + } + + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + broker = null; + } + } + + /* + * This test verifies that all undelivered messages sent to a consumers + * listening on a queue associated with a virtual topic with be forwarded to + * separate DLQ's. + * + * Note that the broker config, deadLetterStrategy need to have the enable + * audit set to false so that duplicate message sent from a topic to + * individual consumers are forwarded to the DLQ + * + * + * + * + * + */ + @Test + public void testVirtualTopicSubscriberDeadLetterQueue() throws Exception { + + TestConsumer consumer1 = null; + TestConsumer consumer2 = null; + TestConsumer consumer3 = null; + TestConsumer dlqConsumer1 = null; + TestConsumer dlqConsumer2 = null; + TestConsumer dlqConsumer3 = null; + + try { + + // The first 2 consumers will rollback, ultimately causing messages + // to land on the DLQ + consumer1 = new TestConsumer(consumer1Prefix + virtualTopicName, false, numberMessages, true); + thread(consumer1, false); + + consumer2 = new TestConsumer(consumer2Prefix + virtualTopicName, false, numberMessages, true); + thread(consumer2, false); + + // TestConsumer that does not throw exceptions, messages should not + // land on DLQ + consumer3 = new TestConsumer(consumer3Prefix + virtualTopicName, false, numberMessages, false); + thread(consumer3, false); + + // TestConsumer to read the expected Dead Letter Queue + dlqConsumer1 = new TestConsumer(dlqPrefix + consumer1Prefix + virtualTopicName, false, numberMessages, false); + thread(dlqConsumer1, false); + + dlqConsumer2 = new TestConsumer(dlqPrefix + consumer2Prefix + virtualTopicName, false, numberMessages, false); + thread(dlqConsumer2, false); + + dlqConsumer3 = new TestConsumer(dlqPrefix + consumer3Prefix + virtualTopicName, false, numberMessages, false); + thread(dlqConsumer3, false); + + // Give the consumers a second to start + Thread.sleep(1000); + + // Start the producer + TestProducer producer = new TestProducer(virtualTopicName, true, numberMessages); + thread(producer, false); + + assertTrue("sent all producer messages in time, count is: " + producer.getLatch().getCount(), producer.getLatch().await(10, TimeUnit.SECONDS)); + LOG.info("producer successful, count = " + producer.getLatch().getCount()); + + assertTrue("remaining consumer1 count should be zero, is: " + consumer1.getLatch().getCount(), consumer1.getLatch().await(10, TimeUnit.SECONDS)); + LOG.info("consumer1 successful, count = " + consumer1.getLatch().getCount()); + + assertTrue("remaining consumer2 count should be zero, is: " + consumer2.getLatch().getCount(), consumer2.getLatch().await(10, TimeUnit.SECONDS)); + LOG.info("consumer2 successful, count = " + consumer2.getLatch().getCount()); + + assertTrue("remaining consumer3 count should be zero, is: " + consumer3.getLatch().getCount(), consumer3.getLatch().await(10, TimeUnit.SECONDS)); + LOG.info("consumer3 successful, count = " + consumer3.getLatch().getCount()); + + assertTrue("remaining dlqConsumer1 count should be zero, is: " + dlqConsumer1.getLatch().getCount(), dlqConsumer1.getLatch().await(10, TimeUnit.SECONDS)); + LOG.info("dlqConsumer1 successful, count = " + dlqConsumer1.getLatch().getCount()); + + assertTrue("remaining dlqConsumer2 count should be zero, is: " + dlqConsumer2.getLatch().getCount(), dlqConsumer2.getLatch().await(10, TimeUnit.SECONDS)); + LOG.info("dlqConsumer2 successful, count = " + dlqConsumer2.getLatch().getCount()); + + assertTrue("remaining dlqConsumer3 count should be " + numberMessages + ", is: " + dlqConsumer3.getLatch().getCount(), dlqConsumer3.getLatch().getCount() == numberMessages); + LOG.info("dlqConsumer2 successful, count = " + dlqConsumer2.getLatch().getCount()); + + } + catch (Exception e) { + e.printStackTrace(); + throw e; + } + finally { + // Tell consumers to stop (don't read any more messages after this) + if (consumer1 != null) + consumer1.setStop(true); + if (consumer2 != null) + consumer2.setStop(true); + if (consumer3 != null) + consumer3.setStop(true); + if (dlqConsumer1 != null) + dlqConsumer1.setStop(true); + if (dlqConsumer2 != null) + dlqConsumer2.setStop(true); + if (dlqConsumer3 != null) + dlqConsumer3.setStop(true); + } + } + + private static Thread thread(Runnable runnable, boolean daemon) { + Thread brokerThread = new Thread(runnable); + brokerThread.setDaemon(daemon); + brokerThread.start(); + return brokerThread; + } + + private class TestProducer implements Runnable { + + private String destinationName = null; + private boolean isTopic = true; + private int numberMessages = 0; + private CountDownLatch latch = null; + + public TestProducer(String destinationName, boolean isTopic, int numberMessages) { + this.destinationName = destinationName; + this.isTopic = isTopic; + this.numberMessages = numberMessages; + latch = new CountDownLatch(numberMessages); + } + + public CountDownLatch getLatch() { + return latch; + } + + public void run() { + ActiveMQConnectionFactory connectionFactory = null; + ActiveMQConnection connection = null; + ActiveMQSession session = null; + Destination destination = null; + + try { + LOG.info("Started TestProducer for destination (" + destinationName + ")"); + + connectionFactory = new ActiveMQConnectionFactory(jmsConnectionURI); + connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.start(); + session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + if (isTopic) { + destination = session.createTopic(this.destinationName); + } + else { + destination = session.createQueue(this.destinationName); + } + + // Create a MessageProducer from the Session to the Topic or + // Queue + ActiveMQMessageProducer producer = (ActiveMQMessageProducer) session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + + for (int i = 0; i < numberMessages; i++) { + TextMessage message = (TextMessage) session.createTextMessage("I am a message :: " + String.valueOf(i)); + try { + producer.send(message); + + } + catch (Exception deeperException) { + LOG.info("Producer for destination (" + destinationName + ") Caught: " + deeperException); + } + + latch.countDown(); + Thread.sleep(1000); + } + + LOG.info("Finished TestProducer for destination (" + destinationName + ")"); + + } + catch (Exception e) { + LOG.error("Terminating TestProducer(" + destinationName + ")Caught: " + e); e.printStackTrace(); - throw e; - } - } - @After - public void tearDown() throws Exception { - try { - // Purge the DLQ's so counts are correct for next run - purgeDestination(dlqPrefix + consumer1Prefix + virtualTopicName); - purgeDestination(dlqPrefix + consumer2Prefix + virtualTopicName); - purgeDestination(dlqPrefix + consumer3Prefix + virtualTopicName); - } catch (Exception e) { - e.printStackTrace(); - } + } + finally { + try { + // Clean up + if (session != null) + session.close(); + if (connection != null) + connection.close(); - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - broker = null; - } - } + } + catch (Exception e) { + e.printStackTrace(); + LOG.error("Closing connection/session (" + destinationName + ")Caught: " + e); + } + } + } + } - /* - * This test verifies that all undelivered messages sent to a consumers - * listening on a queue associated with a virtual topic with be forwarded to - * separate DLQ's. - * - * Note that the broker config, deadLetterStrategy need to have the enable - * audit set to false so that duplicate message sent from a topic to - * individual consumers are forwarded to the DLQ - * - * - * - * - * - */ - @Test - public void testVirtualTopicSubscriberDeadLetterQueue() throws Exception { + private class TestConsumer implements Runnable, ExceptionListener, MessageListener { - TestConsumer consumer1 = null; - TestConsumer consumer2 = null; - TestConsumer consumer3 = null; - TestConsumer dlqConsumer1 = null; - TestConsumer dlqConsumer2 = null; - TestConsumer dlqConsumer3 = null; + private String destinationName = null; + private boolean isTopic = true; + private CountDownLatch latch = null; + private int maxRedeliveries = 0; + private int receivedMessageCounter = 0; + private boolean bFakeFail = false; + private boolean bStop = false; - try { + private ActiveMQConnectionFactory connectionFactory = null; + private ActiveMQConnection connection = null; + private Session session = null; + private MessageConsumer consumer = null; - // The first 2 consumers will rollback, ultimately causing messages - // to land on the DLQ - consumer1 = new TestConsumer(consumer1Prefix + virtualTopicName, false, numberMessages, true); - thread(consumer1, false); + public TestConsumer(String destinationName, boolean isTopic, int expectedNumberMessages, boolean bFakeFail) { + this.destinationName = destinationName; + this.isTopic = isTopic; + latch = new CountDownLatch(expectedNumberMessages * (this.bFakeFail ? (maxRedeliveries + 1) : 1)); + this.bFakeFail = bFakeFail; + } - consumer2 = new TestConsumer(consumer2Prefix + virtualTopicName, false, numberMessages, true); - thread(consumer2, false); + public CountDownLatch getLatch() { + return latch; + } - // TestConsumer that does not throw exceptions, messages should not - // land on DLQ - consumer3 = new TestConsumer(consumer3Prefix + virtualTopicName, false, numberMessages, false); - thread(consumer3, false); + public void run() { - // TestConsumer to read the expected Dead Letter Queue - dlqConsumer1 = new TestConsumer(dlqPrefix + consumer1Prefix + virtualTopicName, false, numberMessages, false); - thread(dlqConsumer1, false); + try { + LOG.info("Started TestConsumer for destination (" + destinationName + ")"); - dlqConsumer2 = new TestConsumer(dlqPrefix + consumer2Prefix + virtualTopicName, false, numberMessages, false); - thread(dlqConsumer2, false); + connectionFactory = new ActiveMQConnectionFactory(jmsConnectionURI); + connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.start(); + session = connection.createSession(true, Session.SESSION_TRANSACTED); - dlqConsumer3 = new TestConsumer(dlqPrefix + consumer3Prefix + virtualTopicName, false, numberMessages, false); - thread(dlqConsumer3, false); + RedeliveryPolicy policy = connection.getRedeliveryPolicy(); + policy.setInitialRedeliveryDelay(1); + policy.setUseExponentialBackOff(false); + policy.setMaximumRedeliveries(maxRedeliveries); - // Give the consumers a second to start - Thread.sleep(1000); + connection.setExceptionListener(this); - // Start the producer - TestProducer producer = new TestProducer(virtualTopicName, true, numberMessages); - thread(producer, false); - - assertTrue("sent all producer messages in time, count is: " + producer.getLatch().getCount(), producer.getLatch().await(10, TimeUnit.SECONDS)); - LOG.info("producer successful, count = " + producer.getLatch().getCount()); - - assertTrue("remaining consumer1 count should be zero, is: " + consumer1.getLatch().getCount(), consumer1.getLatch().await(10, TimeUnit.SECONDS)); - LOG.info("consumer1 successful, count = " + consumer1.getLatch().getCount()); - - assertTrue("remaining consumer2 count should be zero, is: " + consumer2.getLatch().getCount(), consumer2.getLatch().await(10, TimeUnit.SECONDS)); - LOG.info("consumer2 successful, count = " + consumer2.getLatch().getCount()); - - assertTrue("remaining consumer3 count should be zero, is: " + consumer3.getLatch().getCount(), consumer3.getLatch().await(10, TimeUnit.SECONDS)); - LOG.info("consumer3 successful, count = " + consumer3.getLatch().getCount()); - - assertTrue("remaining dlqConsumer1 count should be zero, is: " + dlqConsumer1.getLatch().getCount(), - dlqConsumer1.getLatch().await(10, TimeUnit.SECONDS)); - LOG.info("dlqConsumer1 successful, count = " + dlqConsumer1.getLatch().getCount()); - - assertTrue("remaining dlqConsumer2 count should be zero, is: " + dlqConsumer2.getLatch().getCount(), - dlqConsumer2.getLatch().await(10, TimeUnit.SECONDS)); - LOG.info("dlqConsumer2 successful, count = " + dlqConsumer2.getLatch().getCount()); - - assertTrue("remaining dlqConsumer3 count should be " + numberMessages + ", is: " + dlqConsumer3.getLatch().getCount(), dlqConsumer3.getLatch() - .getCount() == numberMessages); - LOG.info("dlqConsumer2 successful, count = " + dlqConsumer2.getLatch().getCount()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - // Tell consumers to stop (don't read any more messages after this) - if (consumer1 != null) - consumer1.setStop(true); - if (consumer2 != null) - consumer2.setStop(true); - if (consumer3 != null) - consumer3.setStop(true); - if (dlqConsumer1 != null) - dlqConsumer1.setStop(true); - if (dlqConsumer2 != null) - dlqConsumer2.setStop(true); - if (dlqConsumer3 != null) - dlqConsumer3.setStop(true); - } - } - - private static Thread thread(Runnable runnable, boolean daemon) { - Thread brokerThread = new Thread(runnable); - brokerThread.setDaemon(daemon); - brokerThread.start(); - return brokerThread; - } - - private class TestProducer implements Runnable { - private String destinationName = null; - private boolean isTopic = true; - private int numberMessages = 0; - private CountDownLatch latch = null; - - public TestProducer(String destinationName, boolean isTopic, int numberMessages) { - this.destinationName = destinationName; - this.isTopic = isTopic; - this.numberMessages = numberMessages; - latch = new CountDownLatch(numberMessages); - } - - public CountDownLatch getLatch() { - return latch; - } - - public void run() { - ActiveMQConnectionFactory connectionFactory = null; - ActiveMQConnection connection = null; - ActiveMQSession session = null; Destination destination = null; - - try { - LOG.info("Started TestProducer for destination (" + destinationName + ")"); - - connectionFactory = new ActiveMQConnectionFactory(jmsConnectionURI); - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); - session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - if (isTopic) { - destination = session.createTopic(this.destinationName); - } else { - destination = session.createQueue(this.destinationName); - } - - // Create a MessageProducer from the Session to the Topic or - // Queue - ActiveMQMessageProducer producer = (ActiveMQMessageProducer) session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - - for (int i = 0; i < numberMessages; i++) { - TextMessage message = (TextMessage) session.createTextMessage("I am a message :: " + String.valueOf(i)); - try { - producer.send(message); - - } catch (Exception deeperException) { - LOG.info("Producer for destination (" + destinationName + ") Caught: " + deeperException); - } - - latch.countDown(); - Thread.sleep(1000); - } - - LOG.info("Finished TestProducer for destination (" + destinationName + ")"); - - } catch (Exception e) { - LOG.error("Terminating TestProducer(" + destinationName + ")Caught: " + e); - e.printStackTrace(); - - } finally { - try { - // Clean up - if (session != null) - session.close(); - if (connection != null) - connection.close(); - - } catch (Exception e) { - e.printStackTrace(); - LOG.error("Closing connection/session (" + destinationName + ")Caught: " + e); - } + if (isTopic) { + destination = session.createTopic(destinationName); } - } - } - - private class TestConsumer implements Runnable, ExceptionListener, MessageListener { - private String destinationName = null; - private boolean isTopic = true; - private CountDownLatch latch = null; - private int maxRedeliveries = 0; - private int receivedMessageCounter = 0; - private boolean bFakeFail = false; - private boolean bStop = false; - - private ActiveMQConnectionFactory connectionFactory = null; - private ActiveMQConnection connection = null; - private Session session = null; - private MessageConsumer consumer = null; - - public TestConsumer(String destinationName, boolean isTopic, int expectedNumberMessages, boolean bFakeFail) { - this.destinationName = destinationName; - this.isTopic = isTopic; - latch = new CountDownLatch(expectedNumberMessages * (this.bFakeFail ? (maxRedeliveries + 1) : 1)); - this.bFakeFail = bFakeFail; - } - - public CountDownLatch getLatch() { - return latch; - } - - public void run() { - - try { - LOG.info("Started TestConsumer for destination (" + destinationName + ")"); - - connectionFactory = new ActiveMQConnectionFactory(jmsConnectionURI); - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); - session = connection.createSession(true, Session.SESSION_TRANSACTED); - - RedeliveryPolicy policy = connection.getRedeliveryPolicy(); - policy.setInitialRedeliveryDelay(1); - policy.setUseExponentialBackOff(false); - policy.setMaximumRedeliveries(maxRedeliveries); - - connection.setExceptionListener(this); - - Destination destination = null; - if (isTopic) { - destination = session.createTopic(destinationName); - } else { - destination = session.createQueue(destinationName); - } - - consumer = session.createConsumer(destination); - consumer.setMessageListener(this); - - while (!bStop) { - Thread.sleep(100); - } - - LOG.info("Finished TestConsumer for destination name (" + destinationName + ") remaining " + this.latch.getCount() + " messages " - + this.toString()); - - } catch (Exception e) { - LOG.error("Consumer (" + destinationName + ") Caught: " + e); - e.printStackTrace(); - } finally { - try { - // Clean up - if (consumer != null) - consumer.close(); - if (session != null) - session.close(); - if (connection != null) - connection.close(); - - } catch (Exception e) { - e.printStackTrace(); - LOG.error("Closing connection/session (" + destinationName + ")Caught: " + e); - } + else { + destination = session.createQueue(destinationName); } - } - public synchronized void onException(JMSException ex) { + consumer = session.createConsumer(destination); + consumer.setMessageListener(this); + + while (!bStop) { + Thread.sleep(100); + } + + LOG.info("Finished TestConsumer for destination name (" + destinationName + ") remaining " + this.latch.getCount() + " messages " + this.toString()); + + } + catch (Exception e) { + LOG.error("Consumer (" + destinationName + ") Caught: " + e); + e.printStackTrace(); + } + finally { + try { + // Clean up + if (consumer != null) + consumer.close(); + if (session != null) + session.close(); + if (connection != null) + connection.close(); + + } + catch (Exception e) { + e.printStackTrace(); + LOG.error("Closing connection/session (" + destinationName + ")Caught: " + e); + } + } + } + + public synchronized void onException(JMSException ex) { + ex.printStackTrace(); + LOG.error("Consumer for destination, (" + destinationName + "), JMS Exception occurred. Shutting down client."); + } + + public synchronized void setStop(boolean bStop) { + this.bStop = bStop; + } + + public synchronized void onMessage(Message message) { + receivedMessageCounter++; + latch.countDown(); + + LOG.info("Consumer for destination (" + destinationName + ") latch countdown: " + latch.getCount() + " :: Number messages received " + this.receivedMessageCounter); + + try { + LOG.info("Consumer for destination (" + destinationName + ") Received message id :: " + message.getJMSMessageID()); + + if (!bFakeFail) { + LOG.info("Consumer on destination " + destinationName + " committing JMS Session for message: " + message.toString()); + session.commit(); + } + else { + LOG.info("Consumer on destination " + destinationName + " rolling back JMS Session for message: " + message.toString()); + session.rollback(); // rolls back all the consumed messages + // on the session to + } + + } + catch (JMSException ex) { ex.printStackTrace(); - LOG.error("Consumer for destination, (" + destinationName + "), JMS Exception occurred. Shutting down client."); - } + LOG.error("Error reading JMS Message from destination " + destinationName + "."); + } + } + } - public synchronized void setStop(boolean bStop) { - this.bStop = bStop; - } - - public synchronized void onMessage(Message message) { - receivedMessageCounter++; - latch.countDown(); - - LOG.info("Consumer for destination (" + destinationName + ") latch countdown: " + latch.getCount() + " :: Number messages received " - + this.receivedMessageCounter); - - try { - LOG.info("Consumer for destination (" + destinationName + ") Received message id :: " + message.getJMSMessageID()); - - if (!bFakeFail) { - LOG.info("Consumer on destination " + destinationName + " committing JMS Session for message: " + message.toString()); - session.commit(); - } else { - LOG.info("Consumer on destination " + destinationName + " rolling back JMS Session for message: " + message.toString()); - session.rollback(); // rolls back all the consumed messages - // on the session to - } - - } catch (JMSException ex) { - ex.printStackTrace(); - LOG.error("Error reading JMS Message from destination " + destinationName + "."); - } - } - } - - private static void purgeDestination(String destination) throws Exception { - final Queue dest = (Queue) ((RegionBroker) broker.getRegionBroker()).getQueueRegion().getDestinationMap().get(new ActiveMQQueue(destination)); - dest.purge(); - assertEquals(0, dest.getDestinationStatistics().getMessages().getCount()); - } + private static void purgeDestination(String destination) throws Exception { + final Queue dest = (Queue) ((RegionBroker) broker.getRegionBroker()).getQueueRegion().getDestinationMap().get(new ActiveMQQueue(destination)); + dest.purge(); + assertEquals(0, dest.getDestinationStatistics().getMessages().getCount()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualTopicDisconnectSelectorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualTopicDisconnectSelectorTest.java index 8b95345523..7b5fc7b3e8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualTopicDisconnectSelectorTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualTopicDisconnectSelectorTest.java @@ -27,6 +27,7 @@ import javax.jms.MessageListener; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; + import org.apache.activemq.EmbeddedBrokerTestSupport; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.command.ActiveMQQueue; @@ -42,144 +43,143 @@ import org.slf4j.LoggerFactory; public class VirtualTopicDisconnectSelectorTest extends EmbeddedBrokerTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(VirtualTopicDisconnectSelectorTest.class); - protected Connection connection; + private static final Logger LOG = LoggerFactory.getLogger(VirtualTopicDisconnectSelectorTest.class); + protected Connection connection; - public void testVirtualTopicSelectorDisconnect() throws Exception { - testVirtualTopicDisconnect("odd = 'no'", 3000, 1500); - } + public void testVirtualTopicSelectorDisconnect() throws Exception { + testVirtualTopicDisconnect("odd = 'no'", 3000, 1500); + } - public void testVirtualTopicNoSelectorDisconnect() throws Exception { - testVirtualTopicDisconnect(null, 3000, 3000); - } + public void testVirtualTopicNoSelectorDisconnect() throws Exception { + testVirtualTopicDisconnect(null, 3000, 3000); + } - public void testVirtualTopicDisconnect(String messageSelector, int total , int expected) throws Exception { - if (connection == null) { - connection = createConnection(); - } - connection.start(); + public void testVirtualTopicDisconnect(String messageSelector, int total, int expected) throws Exception { + if (connection == null) { + connection = createConnection(); + } + connection.start(); - final ConsumerBean messageList = new ConsumerBean(); + final ConsumerBean messageList = new ConsumerBean(); - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Destination producerDestination = getProducerDestination(); - Destination destination = getConsumerDsetination(); + Destination producerDestination = getProducerDestination(); + Destination destination = getConsumerDsetination(); - LOG.info("Sending to: " + producerDestination); - LOG.info("Consuming from: " + destination ); + LOG.info("Sending to: " + producerDestination); + LOG.info("Consuming from: " + destination); - MessageConsumer consumer = createConsumer(session, destination, messageSelector); + MessageConsumer consumer = createConsumer(session, destination, messageSelector); - MessageListener listener = new MessageListener(){ - public void onMessage(Message message){ - messageList.onMessage(message); - try { - message.acknowledge(); - } catch (JMSException e) { - e.printStackTrace(); - } + MessageListener listener = new MessageListener() { + public void onMessage(Message message) { + messageList.onMessage(message); + try { + message.acknowledge(); } - }; - - consumer.setMessageListener(listener); - - - // create topic producer - MessageProducer producer = session.createProducer(producerDestination); - assertNotNull(producer); - - int disconnectCount = total/3; - int reconnectCount = (total * 2)/3; - - for (int i = 0; i < total; i++) { - producer.send(createMessage(session, i)); - - if (i==disconnectCount){ - consumer.close(); + catch (JMSException e) { + e.printStackTrace(); } - if (i==reconnectCount){ - consumer = createConsumer(session, destination, messageSelector); - consumer.setMessageListener(listener); - } - } + } + }; - assertMessagesArrived(messageList, expected ,10000); - } - - protected Destination getConsumerDsetination() { - return new ActiveMQQueue("Consumer.VirtualTopic.TEST"); - } + consumer.setMessageListener(listener); + // create topic producer + MessageProducer producer = session.createProducer(producerDestination); + assertNotNull(producer); - protected Destination getProducerDestination() { - return new ActiveMQTopic("VirtualTopic.TEST"); - } + int disconnectCount = total / 3; + int reconnectCount = (total * 2) / 3; - protected void setUp() throws Exception { - super.setUp(); - } + for (int i = 0; i < total; i++) { + producer.send(createMessage(session, i)); - protected MessageConsumer createConsumer(Session session, Destination destination, String messageSelector) throws JMSException { - if (messageSelector != null) { - return session.createConsumer(destination, messageSelector); - } else { - return session.createConsumer(destination); - } - } + if (i == disconnectCount) { + consumer.close(); + } + if (i == reconnectCount) { + consumer = createConsumer(session, destination, messageSelector); + consumer.setMessageListener(listener); + } + } - protected TextMessage createMessage(Session session, int i) throws JMSException { - TextMessage textMessage = session.createTextMessage("message: " + i); - if (i % 2 != 0) { - textMessage.setStringProperty("odd", "yes"); - } else { - textMessage.setStringProperty("odd", "no"); - } - textMessage.setIntProperty("i", i); - return textMessage; - } + assertMessagesArrived(messageList, expected, 10000); + } + protected Destination getConsumerDsetination() { + return new ActiveMQQueue("Consumer.VirtualTopic.TEST"); + } + protected Destination getProducerDestination() { + return new ActiveMQTopic("VirtualTopic.TEST"); + } - protected void assertMessagesArrived(ConsumerBean messageList, int expected, long timeout) { - messageList.assertMessagesArrived(expected,timeout); + protected void setUp() throws Exception { + super.setUp(); + } - messageList.flushMessages(); + protected MessageConsumer createConsumer(Session session, + Destination destination, + String messageSelector) throws JMSException { + if (messageSelector != null) { + return session.createConsumer(destination, messageSelector); + } + else { + return session.createConsumer(destination); + } + } - - LOG.info("validate no other messages on queues"); - try { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - Destination destination1 = getConsumerDsetination(); + protected TextMessage createMessage(Session session, int i) throws JMSException { + TextMessage textMessage = session.createTextMessage("message: " + i); + if (i % 2 != 0) { + textMessage.setStringProperty("odd", "yes"); + } + else { + textMessage.setStringProperty("odd", "no"); + } + textMessage.setIntProperty("i", i); + return textMessage; + } - MessageConsumer c1 = session.createConsumer(destination1, null); - c1.setMessageListener(messageList); + protected void assertMessagesArrived(ConsumerBean messageList, int expected, long timeout) { + messageList.assertMessagesArrived(expected, timeout); - - LOG.info("send one simple message that should go to both consumers"); - MessageProducer producer = session.createProducer(getProducerDestination()); - assertNotNull(producer); - - producer.send(session.createTextMessage("Last Message")); - - messageList.assertMessagesArrived(1); + messageList.flushMessages(); - } catch (JMSException e) { - e.printStackTrace(); - fail("unexpeced ex while waiting for last messages: " + e); - } - } + LOG.info("validate no other messages on queues"); + try { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination1 = getConsumerDsetination(); - protected String getBrokerConfigUri() { - return "org/apache/activemq/broker/virtual/disconnected-selector.xml"; - } + MessageConsumer c1 = session.createConsumer(destination1, null); + c1.setMessageListener(messageList); - protected BrokerService createBroker() throws Exception { - XBeanBrokerFactory factory = new XBeanBrokerFactory(); - BrokerService answer = factory.createBroker(new URI(getBrokerConfigUri())); - return answer; - } + LOG.info("send one simple message that should go to both consumers"); + MessageProducer producer = session.createProducer(getProducerDestination()); + assertNotNull(producer); + + producer.send(session.createTextMessage("Last Message")); + + messageList.assertMessagesArrived(1); + + } + catch (JMSException e) { + e.printStackTrace(); + fail("unexpeced ex while waiting for last messages: " + e); + } + } + + protected String getBrokerConfigUri() { + return "org/apache/activemq/broker/virtual/disconnected-selector.xml"; + } + + protected BrokerService createBroker() throws Exception { + XBeanBrokerFactory factory = new XBeanBrokerFactory(); + BrokerService answer = factory.createBroker(new URI(getBrokerConfigUri())); + return answer; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualTopicPubSubTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualTopicPubSubTest.java index 42e6e60e7c..0fcbf0b41c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualTopicPubSubTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualTopicPubSubTest.java @@ -34,96 +34,96 @@ import org.apache.activemq.spring.ConsumerBean; /** * - * + * */ public class VirtualTopicPubSubTest extends EmbeddedBrokerTestSupport { - private Vector connections = new Vector(); - public int ackMode = Session.AUTO_ACKNOWLEDGE; + private Vector connections = new Vector(); + public int ackMode = Session.AUTO_ACKNOWLEDGE; - public static Test suite() { - return suite(VirtualTopicPubSubTest.class); - } + public static Test suite() { + return suite(VirtualTopicPubSubTest.class); + } - public void initCombosForTestVirtualTopicCreation() { - addCombinationValues("ackMode", new Object[] {new Integer(Session.AUTO_ACKNOWLEDGE), new Integer(Session.CLIENT_ACKNOWLEDGE) }); - } + public void initCombosForTestVirtualTopicCreation() { + addCombinationValues("ackMode", new Object[]{new Integer(Session.AUTO_ACKNOWLEDGE), new Integer(Session.CLIENT_ACKNOWLEDGE)}); + } - private boolean doneTwice = false; + private boolean doneTwice = false; - public void testVirtualTopicCreation() throws Exception { - doTestVirtualTopicCreation(10); - } + public void testVirtualTopicCreation() throws Exception { + doTestVirtualTopicCreation(10); + } - public void doTestVirtualTopicCreation(int total) throws Exception { - - ConsumerBean messageList = new ConsumerBean() { - public synchronized void onMessage(Message message) { - super.onMessage(message); - if (ackMode == Session.CLIENT_ACKNOWLEDGE) { - try { - message.acknowledge(); - } catch (JMSException e) { - e.printStackTrace(); - } - } + public void doTestVirtualTopicCreation(int total) throws Exception { + ConsumerBean messageList = new ConsumerBean() { + public synchronized void onMessage(Message message) { + super.onMessage(message); + if (ackMode == Session.CLIENT_ACKNOWLEDGE) { + try { + message.acknowledge(); + } + catch (JMSException e) { + e.printStackTrace(); + } } - }; - messageList.setVerbose(true); - String queueAName = getVirtualTopicConsumerName(); - // create consumer 'cluster' - ActiveMQQueue queue1 = new ActiveMQQueue(queueAName); - ActiveMQQueue queue2 = new ActiveMQQueue(queueAName); - - Session session = createStartAndTrackConnection().createSession(false, ackMode); - MessageConsumer c1 = session.createConsumer(queue1); - - session = createStartAndTrackConnection().createSession(false, ackMode); - MessageConsumer c2 = session.createConsumer(queue2); + } + }; + messageList.setVerbose(true); - c1.setMessageListener(messageList); - c2.setMessageListener(messageList); + String queueAName = getVirtualTopicConsumerName(); + // create consumer 'cluster' + ActiveMQQueue queue1 = new ActiveMQQueue(queueAName); + ActiveMQQueue queue2 = new ActiveMQQueue(queueAName); - // create topic producer - Session producerSession = createStartAndTrackConnection().createSession(false, ackMode); - MessageProducer producer = producerSession.createProducer(new ActiveMQTopic(getVirtualTopicName())); - assertNotNull(producer); + Session session = createStartAndTrackConnection().createSession(false, ackMode); + MessageConsumer c1 = session.createConsumer(queue1); - for (int i = 0; i < total; i++) { - producer.send(producerSession.createTextMessage("message: " + i)); - } + session = createStartAndTrackConnection().createSession(false, ackMode); + MessageConsumer c2 = session.createConsumer(queue2); - messageList.assertMessagesArrived(total); + c1.setMessageListener(messageList); + c2.setMessageListener(messageList); - // do twice so we confirm messages do not get redelivered after client acknowledgement - if( doneTwice == false ) { - doneTwice = true; - doTestVirtualTopicCreation(0); - } - } + // create topic producer + Session producerSession = createStartAndTrackConnection().createSession(false, ackMode); + MessageProducer producer = producerSession.createProducer(new ActiveMQTopic(getVirtualTopicName())); + assertNotNull(producer); - private Connection createStartAndTrackConnection() throws Exception { - Connection connection = createConnection(); - connection.start(); - connections.add(connection); - return connection; - } + for (int i = 0; i < total; i++) { + producer.send(producerSession.createTextMessage("message: " + i)); + } - protected String getVirtualTopicName() { - return "VirtualTopic.TEST"; - } + messageList.assertMessagesArrived(total); - protected String getVirtualTopicConsumerName() { - return "Consumer.A.VirtualTopic.TEST"; - } + // do twice so we confirm messages do not get redelivered after client acknowledgement + if (doneTwice == false) { + doneTwice = true; + doTestVirtualTopicCreation(0); + } + } + private Connection createStartAndTrackConnection() throws Exception { + Connection connection = createConnection(); + connection.start(); + connections.add(connection); + return connection; + } - protected void tearDown() throws Exception { - for (Connection connection: connections) { - connection.close(); - } - super.tearDown(); - } + protected String getVirtualTopicName() { + return "VirtualTopic.TEST"; + } + + protected String getVirtualTopicConsumerName() { + return "Consumer.A.VirtualTopic.TEST"; + } + + protected void tearDown() throws Exception { + for (Connection connection : connections) { + connection.close(); + } + super.tearDown(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualTopicPubSubUsingXBeanTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualTopicPubSubUsingXBeanTest.java index 69523313d5..3c1c09298f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualTopicPubSubUsingXBeanTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualTopicPubSubUsingXBeanTest.java @@ -23,30 +23,30 @@ import org.apache.activemq.xbean.XBeanBrokerFactory; /** * - * + * */ public class VirtualTopicPubSubUsingXBeanTest extends VirtualTopicPubSubTest { - protected String getVirtualTopicConsumerName() { - return "VirtualTopicConsumers.ConsumerNumberOne.FOO"; - } + protected String getVirtualTopicConsumerName() { + return "VirtualTopicConsumers.ConsumerNumberOne.FOO"; + } - protected String getVirtualTopicName() { - return "FOO"; - } + protected String getVirtualTopicName() { + return "FOO"; + } - protected BrokerService createBroker() throws Exception { - XBeanBrokerFactory factory = new XBeanBrokerFactory(); - BrokerService answer = factory.createBroker(new URI(getBrokerConfigUri())); - - // lets disable persistence as we are a test - answer.setPersistent(false); - - return answer; - } + protected BrokerService createBroker() throws Exception { + XBeanBrokerFactory factory = new XBeanBrokerFactory(); + BrokerService answer = factory.createBroker(new URI(getBrokerConfigUri())); - protected String getBrokerConfigUri() { - return "org/apache/activemq/broker/virtual/global-virtual-topics.xml"; - } + // lets disable persistence as we are a test + answer.setPersistent(false); + + return answer; + } + + protected String getBrokerConfigUri() { + return "org/apache/activemq/broker/virtual/global-virtual-topics.xml"; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualTopicSelectorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualTopicSelectorTest.java index 3287bab029..f8a95a2491 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualTopicSelectorTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualTopicSelectorTest.java @@ -35,71 +35,71 @@ import org.slf4j.LoggerFactory; public class VirtualTopicSelectorTest extends CompositeTopicTest { - private static final Logger LOG = LoggerFactory.getLogger(VirtualTopicSelectorTest.class); - - protected Destination getConsumer1Dsetination() { - return new ActiveMQQueue("Consumer.1.VirtualTopic.TEST"); - } + private static final Logger LOG = LoggerFactory.getLogger(VirtualTopicSelectorTest.class); - protected Destination getConsumer2Dsetination() { - return new ActiveMQQueue("Consumer.2.VirtualTopic.TEST"); - } - - protected Destination getProducerDestination() { - return new ActiveMQTopic("VirtualTopic.TEST"); - } - - @Override - protected void assertMessagesArrived(ConsumerBean messageList1, ConsumerBean messageList2) { - messageList1.assertMessagesArrived(total/2); - messageList2.assertMessagesArrived(total/2); - - messageList1.flushMessages(); - messageList2.flushMessages(); - - LOG.info("validate no other messages on queues"); - try { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - Destination destination1 = getConsumer1Dsetination(); - Destination destination2 = getConsumer2Dsetination(); - MessageConsumer c1 = session.createConsumer(destination1, null); - MessageConsumer c2 = session.createConsumer(destination2, null); - c1.setMessageListener(messageList1); - c2.setMessageListener(messageList2); - - - LOG.info("send one simple message that should go to both consumers"); - MessageProducer producer = session.createProducer(getProducerDestination()); - assertNotNull(producer); - - producer.send(session.createTextMessage("Last Message")); - - messageList1.assertMessagesArrived(1); - messageList2.assertMessagesArrived(1); - - } catch (JMSException e) { - e.printStackTrace(); - fail("unexpeced ex while waiting for last messages: " + e); - } - } - - @Override - protected BrokerService createBroker() throws Exception { - // use message selectors on consumers that need to propagate up to the virtual - // topic dispatch so that un matched messages do not linger on subscription queues - messageSelector1 = "odd = 'yes'"; - messageSelector2 = "odd = 'no'"; - - BrokerService broker = new BrokerService(); - broker.setPersistent(false); + protected Destination getConsumer1Dsetination() { + return new ActiveMQQueue("Consumer.1.VirtualTopic.TEST"); + } - VirtualTopic virtualTopic = new VirtualTopic(); - // the new config that enables selectors on the intercepter - virtualTopic.setSelectorAware(true); - VirtualDestinationInterceptor interceptor = new VirtualDestinationInterceptor(); - interceptor.setVirtualDestinations(new VirtualDestination[]{virtualTopic}); - broker.setDestinationInterceptors(new DestinationInterceptor[]{interceptor}); - return broker; - } + protected Destination getConsumer2Dsetination() { + return new ActiveMQQueue("Consumer.2.VirtualTopic.TEST"); + } + + protected Destination getProducerDestination() { + return new ActiveMQTopic("VirtualTopic.TEST"); + } + + @Override + protected void assertMessagesArrived(ConsumerBean messageList1, ConsumerBean messageList2) { + messageList1.assertMessagesArrived(total / 2); + messageList2.assertMessagesArrived(total / 2); + + messageList1.flushMessages(); + messageList2.flushMessages(); + + LOG.info("validate no other messages on queues"); + try { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + Destination destination1 = getConsumer1Dsetination(); + Destination destination2 = getConsumer2Dsetination(); + MessageConsumer c1 = session.createConsumer(destination1, null); + MessageConsumer c2 = session.createConsumer(destination2, null); + c1.setMessageListener(messageList1); + c2.setMessageListener(messageList2); + + LOG.info("send one simple message that should go to both consumers"); + MessageProducer producer = session.createProducer(getProducerDestination()); + assertNotNull(producer); + + producer.send(session.createTextMessage("Last Message")); + + messageList1.assertMessagesArrived(1); + messageList2.assertMessagesArrived(1); + + } + catch (JMSException e) { + e.printStackTrace(); + fail("unexpeced ex while waiting for last messages: " + e); + } + } + + @Override + protected BrokerService createBroker() throws Exception { + // use message selectors on consumers that need to propagate up to the virtual + // topic dispatch so that un matched messages do not linger on subscription queues + messageSelector1 = "odd = 'yes'"; + messageSelector2 = "odd = 'no'"; + + BrokerService broker = new BrokerService(); + broker.setPersistent(false); + + VirtualTopic virtualTopic = new VirtualTopic(); + // the new config that enables selectors on the intercepter + virtualTopic.setSelectorAware(true); + VirtualDestinationInterceptor interceptor = new VirtualDestinationInterceptor(); + interceptor.setVirtualDestinations(new VirtualDestination[]{virtualTopic}); + broker.setDestinationInterceptors(new DestinationInterceptor[]{interceptor}); + return broker; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualTopicsAndDurableSubsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualTopicsAndDurableSubsTest.java index d1e709f904..2587cda7ba 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualTopicsAndDurableSubsTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/virtual/VirtualTopicsAndDurableSubsTest.java @@ -28,76 +28,84 @@ import org.apache.activemq.spring.ConsumerBean; public class VirtualTopicsAndDurableSubsTest extends MBeanTest { - private Connection connection; + private Connection connection; - public void testVirtualTopicCreationAndDurableSubs() throws Exception { - if (connection == null) { - connection = createConnection(); - } - connection.setClientID(getAClientID()); - connection.start(); + public void testVirtualTopicCreationAndDurableSubs() throws Exception { + if (connection == null) { + connection = createConnection(); + } + connection.setClientID(getAClientID()); + connection.start(); - ConsumerBean messageList = new ConsumerBean(); - messageList.setVerbose(true); - - String queueAName = getVirtualTopicConsumerName(); - // create consumer 'cluster' - ActiveMQQueue queue1 = new ActiveMQQueue(queueAName); - ActiveMQQueue queue2 = new ActiveMQQueue(queueAName); + ConsumerBean messageList = new ConsumerBean(); + messageList.setVerbose(true); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer c1 = session.createConsumer(queue1); - MessageConsumer c2 = session.createConsumer(queue2); + String queueAName = getVirtualTopicConsumerName(); + // create consumer 'cluster' + ActiveMQQueue queue1 = new ActiveMQQueue(queueAName); + ActiveMQQueue queue2 = new ActiveMQQueue(queueAName); - c1.setMessageListener(messageList); - c2.setMessageListener(messageList); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer c1 = session.createConsumer(queue1); + MessageConsumer c2 = session.createConsumer(queue2); - // create topic producer - MessageProducer producer = session.createProducer(new ActiveMQTopic(getVirtualTopicName())); - assertNotNull(producer); + c1.setMessageListener(messageList); + c2.setMessageListener(messageList); - int total = 10; - for (int i = 0; i < total; i++) { - producer.send(session.createTextMessage("message: " + i)); - } - messageList.assertMessagesArrived(total); - - //Add and remove durable subscriber after using VirtualTopics - assertCreateAndDestroyDurableSubscriptions(); - } + // create topic producer + MessageProducer producer = session.createProducer(new ActiveMQTopic(getVirtualTopicName())); + assertNotNull(producer); - protected String getAClientID(){ - return "VirtualTopicCreationAndDurableSubs"; - } + int total = 10; + for (int i = 0; i < total; i++) { + producer.send(session.createTextMessage("message: " + i)); + } + messageList.assertMessagesArrived(total); - protected String getVirtualTopicName() { - return "VirtualTopic.TEST"; - } + //Add and remove durable subscriber after using VirtualTopics + assertCreateAndDestroyDurableSubscriptions(); + } + protected String getAClientID() { + return "VirtualTopicCreationAndDurableSubs"; + } - protected String getVirtualTopicConsumerName() { - return "Consumer.A.VirtualTopic.TEST"; - } + protected String getVirtualTopicName() { + return "VirtualTopic.TEST"; + } - protected String getDurableSubscriberName(){ - return "Sub1"; - } - - protected String getDurableSubscriberTopicName(){ - return "simple.topic"; - } + protected String getVirtualTopicConsumerName() { + return "Consumer.A.VirtualTopic.TEST"; + } - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - super.tearDown(); - } - - //Overrides test cases from MBeanTest to avoid having them run. - public void testMBeans() throws Exception {} - public void testMoveMessages() throws Exception {} - public void testRetryMessages() throws Exception {} - public void testMoveMessagesBySelector() throws Exception {} - public void testCopyMessagesBySelector() throws Exception {} + protected String getDurableSubscriberName() { + return "Sub1"; + } + + protected String getDurableSubscriberTopicName() { + return "simple.topic"; + } + + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + } + super.tearDown(); + } + + //Overrides test cases from MBeanTest to avoid having them run. + public void testMBeans() throws Exception { + } + + public void testMoveMessages() throws Exception { + } + + public void testRetryMessages() throws Exception { + } + + public void testMoveMessagesBySelector() throws Exception { + } + + public void testCopyMessagesBySelector() throws Exception { + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1282.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1282.java index 9cd240f029..0568757553 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1282.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1282.java @@ -30,159 +30,177 @@ import org.apache.activemq.ActiveMQConnectionFactory; * An AMQ-1282 Test */ public class AMQ1282 extends TestCase { - private ConnectionFactory factory; - private Connection connection; - private MapMessage message; - @Override - protected void setUp() throws Exception { - factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); - connection = factory.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - message = session.createMapMessage(); - super.setUp(); - } + private ConnectionFactory factory; + private Connection connection; + private MapMessage message; - @Override - protected void tearDown() throws Exception { - connection.close(); - super.tearDown(); - } + @Override + protected void setUp() throws Exception { + factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); + connection = factory.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + message = session.createMapMessage(); + super.setUp(); + } - public void testUnmappedBooleanMessage() throws JMSException { - Object expected; - try { - expected = Boolean.valueOf(null); - } catch (Exception ex) { - expected = ex; - } - try { - Boolean actual = message.getBoolean("foo"); - assertEquals(expected, actual); - } catch (Exception ex) { - assertEquals(expected, ex); - } - } + @Override + protected void tearDown() throws Exception { + connection.close(); + super.tearDown(); + } - public void testUnmappedIntegerMessage() throws JMSException { - Object expected; - try { - expected = Integer.valueOf(null); - } catch (Exception ex) { - expected = ex; - } - try { - Integer actual = message.getInt("foo"); - assertEquals(expected, actual); - } catch (Exception ex) { - Class aClass = expected.getClass(); - assertTrue(aClass.isInstance(ex)); - } - } + public void testUnmappedBooleanMessage() throws JMSException { + Object expected; + try { + expected = Boolean.valueOf(null); + } + catch (Exception ex) { + expected = ex; + } + try { + Boolean actual = message.getBoolean("foo"); + assertEquals(expected, actual); + } + catch (Exception ex) { + assertEquals(expected, ex); + } + } - public void testUnmappedShortMessage() throws JMSException { - Object expected; - try { - expected = Short.valueOf(null); - } catch (Exception ex) { - expected = ex; - } - try { - Short actual = message.getShort("foo"); - assertEquals(expected, actual); - } catch (Exception ex) { - Class aClass = expected.getClass(); - assertTrue(aClass.isInstance(ex)); - } - } + public void testUnmappedIntegerMessage() throws JMSException { + Object expected; + try { + expected = Integer.valueOf(null); + } + catch (Exception ex) { + expected = ex; + } + try { + Integer actual = message.getInt("foo"); + assertEquals(expected, actual); + } + catch (Exception ex) { + Class aClass = expected.getClass(); + assertTrue(aClass.isInstance(ex)); + } + } - public void testUnmappedLongMessage() throws JMSException { - Object expected; - try { - expected = Long.valueOf(null); - } catch (Exception ex) { - expected = ex; - } - try { - Long actual = message.getLong("foo"); - assertEquals(expected, actual); - } catch (Exception ex) { - Class aClass = expected.getClass(); - assertTrue(aClass.isInstance(ex)); - } - } + public void testUnmappedShortMessage() throws JMSException { + Object expected; + try { + expected = Short.valueOf(null); + } + catch (Exception ex) { + expected = ex; + } + try { + Short actual = message.getShort("foo"); + assertEquals(expected, actual); + } + catch (Exception ex) { + Class aClass = expected.getClass(); + assertTrue(aClass.isInstance(ex)); + } + } - public void testUnmappedStringMessage() throws JMSException { - Object expected; - try { - expected = String.valueOf(null); - } catch (Exception ex) { - expected = ex; - } - try { - String actual = message.getString("foo"); - assertEquals(expected, actual); - } catch (Exception ex) { - Class aClass = expected.getClass(); - assertTrue(aClass.isInstance(ex)); - } - } + public void testUnmappedLongMessage() throws JMSException { + Object expected; + try { + expected = Long.valueOf(null); + } + catch (Exception ex) { + expected = ex; + } + try { + Long actual = message.getLong("foo"); + assertEquals(expected, actual); + } + catch (Exception ex) { + Class aClass = expected.getClass(); + assertTrue(aClass.isInstance(ex)); + } + } - public void testUnmappedCharMessage() throws JMSException { - try { - message.getChar("foo"); - fail("should have thrown NullPointerException"); - } catch (NullPointerException success) { - assertNotNull(success); - } - } + public void testUnmappedStringMessage() throws JMSException { + Object expected; + try { + expected = String.valueOf(null); + } + catch (Exception ex) { + expected = ex; + } + try { + String actual = message.getString("foo"); + assertEquals(expected, actual); + } + catch (Exception ex) { + Class aClass = expected.getClass(); + assertTrue(aClass.isInstance(ex)); + } + } - public void testUnmappedByteMessage() throws JMSException { - Object expected; - try { - expected = Byte.valueOf(null); - } catch (Exception ex) { - expected = ex; - } - try { - Byte actual = message.getByte("foo"); - assertEquals(expected, actual); - } catch (Exception ex) { - Class aClass = expected.getClass(); - assertTrue(aClass.isInstance(ex)); - } - } + public void testUnmappedCharMessage() throws JMSException { + try { + message.getChar("foo"); + fail("should have thrown NullPointerException"); + } + catch (NullPointerException success) { + assertNotNull(success); + } + } - public void testUnmappedDoubleMessage() throws JMSException { - Object expected; - try { - expected = Double.valueOf(null); - } catch (Exception ex) { - expected = ex; - } - try { - Double actual = message.getDouble("foo"); - assertEquals(expected, actual); - } catch (Exception ex) { - Class aClass = expected.getClass(); - assertTrue(aClass.isInstance(ex)); - } - } + public void testUnmappedByteMessage() throws JMSException { + Object expected; + try { + expected = Byte.valueOf(null); + } + catch (Exception ex) { + expected = ex; + } + try { + Byte actual = message.getByte("foo"); + assertEquals(expected, actual); + } + catch (Exception ex) { + Class aClass = expected.getClass(); + assertTrue(aClass.isInstance(ex)); + } + } - public void testUnmappedFloatMessage() throws JMSException { - Object expected; - try { - expected = Float.valueOf(null); - } catch (Exception ex) { - expected = ex; - } - try { - Float actual = message.getFloat("foo"); - assertEquals(expected, actual); - } catch (Exception ex) { - Class aClass = expected.getClass(); - assertTrue(aClass.isInstance(ex)); - } - } + public void testUnmappedDoubleMessage() throws JMSException { + Object expected; + try { + expected = Double.valueOf(null); + } + catch (Exception ex) { + expected = ex; + } + try { + Double actual = message.getDouble("foo"); + assertEquals(expected, actual); + } + catch (Exception ex) { + Class aClass = expected.getClass(); + assertTrue(aClass.isInstance(ex)); + } + } + + public void testUnmappedFloatMessage() throws JMSException { + Object expected; + try { + expected = Float.valueOf(null); + } + catch (Exception ex) { + expected = ex; + } + try { + Float actual = message.getFloat("foo"); + assertEquals(expected, actual); + } + catch (Exception ex) { + Class aClass = expected.getClass(); + assertTrue(aClass.isInstance(ex)); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1687Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1687Test.java index 8e636d0024..0366b6c848 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1687Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1687Test.java @@ -34,71 +34,71 @@ import org.apache.activemq.spring.ConsumerBean; */ public class AMQ1687Test extends EmbeddedBrokerTestSupport { - private Connection connection; + private Connection connection; - @Override - protected ConnectionFactory createConnectionFactory() throws Exception { - //prefetch change is not required, but test will not fail w/o it, only spew errors in the AMQ log. - return new ActiveMQConnectionFactory( - broker.getTransportConnectors().get(0).getPublishableConnectString() +"?jms.prefetchPolicy.all=5"); - } + @Override + protected ConnectionFactory createConnectionFactory() throws Exception { + //prefetch change is not required, but test will not fail w/o it, only spew errors in the AMQ log. + return new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString() + "?jms.prefetchPolicy.all=5"); + } - public void testVirtualTopicCreation() throws Exception { - if (connection == null) { - connection = createConnection(); - } - connection.start(); + public void testVirtualTopicCreation() throws Exception { + if (connection == null) { + connection = createConnection(); + } + connection.start(); - ConsumerBean messageList = new ConsumerBean(); - messageList.setVerbose(true); + ConsumerBean messageList = new ConsumerBean(); + messageList.setVerbose(true); - String queueAName = getVirtualTopicConsumerName(); - String queueBName = getVirtualTopicConsumerNameB(); + String queueAName = getVirtualTopicConsumerName(); + String queueBName = getVirtualTopicConsumerNameB(); - // create consumer 'cluster' - ActiveMQQueue queue1 = new ActiveMQQueue(queueAName); - ActiveMQQueue queue2 = new ActiveMQQueue(queueBName); + // create consumer 'cluster' + ActiveMQQueue queue1 = new ActiveMQQueue(queueAName); + ActiveMQQueue queue2 = new ActiveMQQueue(queueBName); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer c1 = session.createConsumer(queue1); - MessageConsumer c2 = session.createConsumer(queue2); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer c1 = session.createConsumer(queue1); + MessageConsumer c2 = session.createConsumer(queue2); - c1.setMessageListener(messageList); - c2.setMessageListener(messageList); + c1.setMessageListener(messageList); + c2.setMessageListener(messageList); - // create topic producer - ActiveMQTopic topic = new ActiveMQTopic(getVirtualTopicName()); - MessageProducer producer = session.createProducer(topic); - assertNotNull(producer); + // create topic producer + ActiveMQTopic topic = new ActiveMQTopic(getVirtualTopicName()); + MessageProducer producer = session.createProducer(topic); + assertNotNull(producer); - int total = 100; - for (int i = 0; i < total; i++) { - producer.send(session.createTextMessage("message: " + i)); - } + int total = 100; + for (int i = 0; i < total; i++) { + producer.send(session.createTextMessage("message: " + i)); + } - messageList.assertMessagesArrived(total*2); - } + messageList.assertMessagesArrived(total * 2); + } - protected String getVirtualTopicName() { - return "VirtualTopic.TEST"; - } + protected String getVirtualTopicName() { + return "VirtualTopic.TEST"; + } - protected String getVirtualTopicConsumerName() { - return "Consumer.A.VirtualTopic.TEST"; - } + protected String getVirtualTopicConsumerName() { + return "Consumer.A.VirtualTopic.TEST"; + } - protected String getVirtualTopicConsumerNameB() { - return "Consumer.B.VirtualTopic.TEST"; - } + protected String getVirtualTopicConsumerNameB() { + return "Consumer.B.VirtualTopic.TEST"; + } - protected void setUp() throws Exception { - this.bindAddress="tcp://localhost:0"; - super.setUp(); - } - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - super.tearDown(); - } + protected void setUp() throws Exception { + this.bindAddress = "tcp://localhost:0"; + super.setUp(); + } + + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + } + super.tearDown(); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1853Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1853Test.java index 51693483c4..6d378d6a39 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1853Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1853Test.java @@ -56,313 +56,319 @@ import org.slf4j.LoggerFactory; * or sent to the DLQ. */ public class AMQ1853Test { - private static BrokerService broker; - private static final Logger LOG = LoggerFactory.getLogger(AMQ1853Test.class); - static final String jmsConnectionURI = "failover:(vm://localhost)"; + private static BrokerService broker; - // Virtual Topic that the test publishes 10 messages to - private static final String queueFail = "Queue.BlockingConsumer.QueueFail"; + private static final Logger LOG = LoggerFactory.getLogger(AMQ1853Test.class); + static final String jmsConnectionURI = "failover:(vm://localhost)"; - // Number of messages + // Virtual Topic that the test publishes 10 messages to + private static final String queueFail = "Queue.BlockingConsumer.QueueFail"; - private final int producerMessages = 5; - private final int totalNumberMessages = producerMessages * 2; - private final int maxRedeliveries = 2; - private final int redeliveryDelay = 1000; + // Number of messages - private Map messageList = null; + private final int producerMessages = 5; + private final int totalNumberMessages = producerMessages * 2; + private final int maxRedeliveries = 2; + private final int redeliveryDelay = 1000; - @Before - public void setUp() throws Exception { - broker = BrokerFactory.createBroker(new URI("broker:()/localhost?persistent=false")); - broker.setUseJmx(false); - broker.setDeleteAllMessagesOnStartup(true); - broker.start(); - broker.waitUntilStarted(); - } + private Map messageList = null; - @After - public void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - broker = null; - } - } + @Before + public void setUp() throws Exception { + broker = BrokerFactory.createBroker(new URI("broker:()/localhost?persistent=false")); + broker.setUseJmx(false); + broker.setDeleteAllMessagesOnStartup(true); + broker.start(); + broker.waitUntilStarted(); + } - @Test - public void testConsumerMessagesAreNotOrdered() throws Exception { + @After + public void tearDown() throws Exception { + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + broker = null; + } + } - TestConsumer consumerAllFail = null; - messageList = new Hashtable(); + @Test + public void testConsumerMessagesAreNotOrdered() throws Exception { - try { + TestConsumer consumerAllFail = null; + messageList = new Hashtable(); - // The first 2 consumers will rollback, ultimately causing messages to land on the DLQ + try { - TestProducer producerAllFail = new TestProducer(queueFail); - thread(producerAllFail, false); + // The first 2 consumers will rollback, ultimately causing messages to land on the DLQ - consumerAllFail = new TestConsumer(queueFail, true); - thread(consumerAllFail, false); + TestProducer producerAllFail = new TestProducer(queueFail); + thread(producerAllFail, false); - // Give the consumers a second to start - Thread.sleep(1000); + consumerAllFail = new TestConsumer(queueFail, true); + thread(consumerAllFail, false); - thread(producerAllFail, false); + // Give the consumers a second to start + Thread.sleep(1000); - // Give the consumers a second to start - Thread.sleep(1000); + thread(producerAllFail, false); - producerAllFail.getLatch().await(); + // Give the consumers a second to start + Thread.sleep(1000); - LOG.info("producer successful, count = " + producerAllFail.getLatch().getCount()); - LOG.info("final message list size = " + messageList.size()); + producerAllFail.getLatch().await(); - assertTrue("message list size = " + messageList.size() + " exptected:" + totalNumberMessages, - Wait.waitFor(new Condition() { - @Override - public boolean isSatisified() throws Exception { - return totalNumberMessages == messageList.size(); - } - })); + LOG.info("producer successful, count = " + producerAllFail.getLatch().getCount()); + LOG.info("final message list size = " + messageList.size()); - consumerAllFail.getLatch().await(); + assertTrue("message list size = " + messageList.size() + " exptected:" + totalNumberMessages, Wait.waitFor(new Condition() { + @Override + public boolean isSatisified() throws Exception { + return totalNumberMessages == messageList.size(); + } + })); - LOG.info("consumerAllFail successful, count = " + consumerAllFail.getLatch().getCount()); + consumerAllFail.getLatch().await(); - Iterator keys = messageList.keySet().iterator(); - for (AtomicInteger counter : messageList.values()) { - String message = keys.next(); - LOG.info("final count for message " + message + " counter = " + counter.get()); - assertTrue("for message " + message + " counter = " + counter.get(), counter.get() == maxRedeliveries + 1); + LOG.info("consumerAllFail successful, count = " + consumerAllFail.getLatch().getCount()); + + Iterator keys = messageList.keySet().iterator(); + for (AtomicInteger counter : messageList.values()) { + String message = keys.next(); + LOG.info("final count for message " + message + " counter = " + counter.get()); + assertTrue("for message " + message + " counter = " + counter.get(), counter.get() == maxRedeliveries + 1); + } + + assertFalse(consumerAllFail.messageReceiptIsOrdered()); + } + finally { + if (consumerAllFail != null) { + consumerAllFail.setStop(true); + } + } + } + + private static Thread thread(Runnable runnable, boolean daemon) { + Thread brokerThread = new Thread(runnable); + brokerThread.setDaemon(daemon); + brokerThread.start(); + return brokerThread; + } + + private class TestProducer implements Runnable { + + private CountDownLatch latch = null; + private String destinationName = null; + + public TestProducer(String destinationName) { + this.destinationName = destinationName; + // We run the producer 2 times + latch = new CountDownLatch(totalNumberMessages); + } + + public CountDownLatch getLatch() { + return latch; + } + + public void run() { + + ActiveMQConnectionFactory connectionFactory = null; + ActiveMQConnection connection = null; + ActiveMQSession session = null; + Destination destination = null; + + try { + LOG.info("Started TestProducer for destination (" + destinationName + ")"); + + connectionFactory = new ActiveMQConnectionFactory(jmsConnectionURI); + connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.setCopyMessageOnSend(false); + connection.start(); + session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + destination = session.createQueue(this.destinationName); + + // Create a MessageProducer from the Session to the Topic or Queue + ActiveMQMessageProducer producer = (ActiveMQMessageProducer) session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + + for (int i = 0; i < (producerMessages); i++) { + TextMessage message = (TextMessage) session.createTextMessage(); + message.setLongProperty("TestTime", (System.currentTimeMillis())); + try { + producer.send(message); + LOG.info("Producer (" + destinationName + ")\n" + message.getJMSMessageID() + " = sent messageId\n"); + + latch.countDown(); + LOG.info(" Latch count " + latch.getCount()); + LOG.info("Producer message list size = " + messageList.keySet().size()); + messageList.put(message.getJMSMessageID(), new AtomicInteger(0)); + LOG.info("Producer message list size = " + messageList.keySet().size()); + + } + catch (Exception deeperException) { + LOG.info("Producer for destination (" + destinationName + ") Caught: " + deeperException); + } + + Thread.sleep(1000); } - assertFalse(consumerAllFail.messageReceiptIsOrdered()); - } finally { - if (consumerAllFail != null) { - consumerAllFail.setStop(true); - } - } - } - - private static Thread thread(Runnable runnable, boolean daemon) { - Thread brokerThread = new Thread(runnable); - brokerThread.setDaemon(daemon); - brokerThread.start(); - return brokerThread; - } - - private class TestProducer implements Runnable { - - private CountDownLatch latch = null; - private String destinationName = null; - - public TestProducer(String destinationName) { - this.destinationName = destinationName; - // We run the producer 2 times - latch = new CountDownLatch(totalNumberMessages); - } - - public CountDownLatch getLatch() { - return latch; - } - - public void run() { - - ActiveMQConnectionFactory connectionFactory = null; - ActiveMQConnection connection = null; - ActiveMQSession session = null; - Destination destination = null; + LOG.info("Finished TestProducer for destination (" + destinationName + ")"); + } + catch (Exception e) { + LOG.error("Terminating TestProducer(" + destinationName + ")Caught: " + e); + } + finally { try { - LOG.info("Started TestProducer for destination (" + destinationName + ")"); - - connectionFactory = new ActiveMQConnectionFactory(jmsConnectionURI); - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.setCopyMessageOnSend(false); - connection.start(); - session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - destination = session.createQueue(this.destinationName); - - // Create a MessageProducer from the Session to the Topic or Queue - ActiveMQMessageProducer producer = (ActiveMQMessageProducer) session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - - for (int i = 0; i < (producerMessages); i++) { - TextMessage message = (TextMessage) session.createTextMessage(); - message.setLongProperty("TestTime", (System.currentTimeMillis())); - try { - producer.send(message); - LOG.info("Producer (" + destinationName + ")\n" + message.getJMSMessageID() + " = sent messageId\n"); - - latch.countDown(); - LOG.info(" Latch count " + latch.getCount()); - LOG.info("Producer message list size = " + messageList.keySet().size()); - messageList.put(message.getJMSMessageID(), new AtomicInteger(0)); - LOG.info("Producer message list size = " + messageList.keySet().size()); - - } catch (Exception deeperException) { - LOG.info("Producer for destination (" + destinationName + ") Caught: " + deeperException); - } - - Thread.sleep(1000); - } - - LOG.info("Finished TestProducer for destination (" + destinationName + ")"); - - } catch (Exception e) { - LOG.error("Terminating TestProducer(" + destinationName + ")Caught: " + e); - } finally { - try { - if (session != null) { - session.close(); - } - if (connection != null) { - connection.close(); - } - } catch (Exception e) { - LOG.error("Closing connection/session (" + destinationName + ")Caught: " + e); - } + if (session != null) { + session.close(); + } + if (connection != null) { + connection.close(); + } } - } - } + catch (Exception e) { + LOG.error("Closing connection/session (" + destinationName + ")Caught: " + e); + } + } + } + } - private class TestConsumer implements Runnable, ExceptionListener, MessageListener { + private class TestConsumer implements Runnable, ExceptionListener, MessageListener { - private CountDownLatch latch = null; - private int receivedMessageCounter = 0; - private boolean bFakeFail = false; - String destinationName = null; - boolean bMessageReceiptIsOrdered = true; - boolean bStop = false; - String previousMessageId = null; + private CountDownLatch latch = null; + private int receivedMessageCounter = 0; + private boolean bFakeFail = false; + String destinationName = null; + boolean bMessageReceiptIsOrdered = true; + boolean bStop = false; + String previousMessageId = null; - private ActiveMQConnectionFactory connectionFactory = null; - private ActiveMQConnection connection = null; - private Session session = null; - private MessageConsumer consumer = null; + private ActiveMQConnectionFactory connectionFactory = null; + private ActiveMQConnection connection = null; + private Session session = null; + private MessageConsumer consumer = null; - public TestConsumer(String destinationName, boolean bFakeFail) { - this.bFakeFail = bFakeFail; - latch = new CountDownLatch(totalNumberMessages * (this.bFakeFail ? (maxRedeliveries + 1) : 1)); - this.destinationName = destinationName; - } + public TestConsumer(String destinationName, boolean bFakeFail) { + this.bFakeFail = bFakeFail; + latch = new CountDownLatch(totalNumberMessages * (this.bFakeFail ? (maxRedeliveries + 1) : 1)); + this.destinationName = destinationName; + } - public CountDownLatch getLatch() { - return latch; - } + public CountDownLatch getLatch() { + return latch; + } - public boolean messageReceiptIsOrdered() { - return bMessageReceiptIsOrdered; - } + public boolean messageReceiptIsOrdered() { + return bMessageReceiptIsOrdered; + } - public void run() { + public void run() { + try { + LOG.info("Started TestConsumer for destination (" + destinationName + ")"); + + connectionFactory = new ActiveMQConnectionFactory(jmsConnectionURI); + connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.setNonBlockingRedelivery(true); + session = connection.createSession(true, Session.SESSION_TRANSACTED); + + RedeliveryPolicy policy = connection.getRedeliveryPolicy(); + policy.setInitialRedeliveryDelay(redeliveryDelay); + policy.setBackOffMultiplier(-1); + policy.setRedeliveryDelay(redeliveryDelay); + policy.setMaximumRedeliveryDelay(-1); + policy.setUseExponentialBackOff(false); + policy.setMaximumRedeliveries(maxRedeliveries); + + connection.setExceptionListener(this); + Destination destination = session.createQueue(destinationName); + consumer = session.createConsumer(destination); + consumer.setMessageListener(this); + + connection.start(); + + while (!bStop) { + Thread.sleep(100); + } + + LOG.info("Finished TestConsumer for destination name (" + destinationName + ") remaining " + this.latch.getCount() + " messages " + this.toString()); + + } + catch (Exception e) { + LOG.error("Consumer (" + destinationName + ") Caught: " + e); + } + finally { try { - LOG.info("Started TestConsumer for destination (" + destinationName + ")"); - - connectionFactory = new ActiveMQConnectionFactory(jmsConnectionURI); - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.setNonBlockingRedelivery(true); - session = connection.createSession(true, Session.SESSION_TRANSACTED); - - RedeliveryPolicy policy = connection.getRedeliveryPolicy(); - policy.setInitialRedeliveryDelay(redeliveryDelay); - policy.setBackOffMultiplier(-1); - policy.setRedeliveryDelay(redeliveryDelay); - policy.setMaximumRedeliveryDelay(-1); - policy.setUseExponentialBackOff(false); - policy.setMaximumRedeliveries(maxRedeliveries); - - connection.setExceptionListener(this); - Destination destination = session.createQueue(destinationName); - consumer = session.createConsumer(destination); - consumer.setMessageListener(this); - - connection.start(); - - while (!bStop) { - Thread.sleep(100); - } - - LOG.info("Finished TestConsumer for destination name (" + destinationName + ") remaining " + this.latch.getCount() - + " messages " + this.toString()); - - } catch (Exception e) { - LOG.error("Consumer (" + destinationName + ") Caught: " + e); - } finally { - try { - if (consumer != null) { - consumer.close(); - } - if (session != null) { - session.close(); - } - if (connection != null) { - connection.close(); - } - } catch (Exception e) { - LOG.error("Closing connection/session (" + destinationName + ")Caught: " + e); - } + if (consumer != null) { + consumer.close(); + } + if (session != null) { + session.close(); + } + if (connection != null) { + connection.close(); + } } - } + catch (Exception e) { + LOG.error("Closing connection/session (" + destinationName + ")Caught: " + e); + } + } + } - public synchronized void onException(JMSException ex) { - LOG.error("Consumer for destination, (" + destinationName + "), JMS Exception occurred. Shutting down client."); - } + public synchronized void onException(JMSException ex) { + LOG.error("Consumer for destination, (" + destinationName + "), JMS Exception occurred. Shutting down client."); + } - public synchronized void setStop(boolean bStop) { - this.bStop = bStop; - } + public synchronized void setStop(boolean bStop) { + this.bStop = bStop; + } - public synchronized void onMessage(Message message) { - receivedMessageCounter++; - latch.countDown(); + public synchronized void onMessage(Message message) { + receivedMessageCounter++; + latch.countDown(); - LOG.info("Consumer for destination (" + destinationName + ") latch countdown: " + latch.getCount() + + LOG.info("Consumer for destination (" + destinationName + ") latch countdown: " + latch.getCount() + " :: Number messages received " + this.receivedMessageCounter); - try { + try { - if (receivedMessageCounter % (maxRedeliveries + 1) == 1) { - previousMessageId = message.getJMSMessageID(); - } - - if (bMessageReceiptIsOrdered) { - bMessageReceiptIsOrdered = previousMessageId.trim().equals(message.getJMSMessageID()); - } - - final String jmsMessageId = message.getJMSMessageID(); - assertTrue("Did not find expected ", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return messageList.containsKey(jmsMessageId); - } - })); - - AtomicInteger counter = messageList.get(jmsMessageId); - counter.incrementAndGet(); - - LOG.info("Consumer for destination (" + destinationName + ")\n" + message.getJMSMessageID() + " = currentMessageId\n" - + previousMessageId + " = previousMessageId\n" + bMessageReceiptIsOrdered + "= bMessageReceiptIsOrdered\n" - + ">>LATENCY " + (System.currentTimeMillis() - message.getLongProperty("TestTime")) + "\n" + "message counter = " - + counter.get()); - - if (!bFakeFail) { - LOG.debug("Consumer on destination " + destinationName + " committing JMS Session for message: " + message.toString()); - session.commit(); - } else { - LOG.debug("Consumer on destination " + destinationName + " rolling back JMS Session for message: " + message.toString()); - session.rollback(); // rolls back all the consumed messages on the session to - } - - } catch (Exception ex) { - ex.printStackTrace(); - LOG.error("Error reading JMS Message from destination " + destinationName + "."); + if (receivedMessageCounter % (maxRedeliveries + 1) == 1) { + previousMessageId = message.getJMSMessageID(); } - } - } + + if (bMessageReceiptIsOrdered) { + bMessageReceiptIsOrdered = previousMessageId.trim().equals(message.getJMSMessageID()); + } + + final String jmsMessageId = message.getJMSMessageID(); + assertTrue("Did not find expected ", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return messageList.containsKey(jmsMessageId); + } + })); + + AtomicInteger counter = messageList.get(jmsMessageId); + counter.incrementAndGet(); + + LOG.info("Consumer for destination (" + destinationName + ")\n" + message.getJMSMessageID() + " = currentMessageId\n" + previousMessageId + " = previousMessageId\n" + bMessageReceiptIsOrdered + "= bMessageReceiptIsOrdered\n" + ">>LATENCY " + (System.currentTimeMillis() - message.getLongProperty("TestTime")) + "\n" + "message counter = " + counter.get()); + + if (!bFakeFail) { + LOG.debug("Consumer on destination " + destinationName + " committing JMS Session for message: " + message.toString()); + session.commit(); + } + else { + LOG.debug("Consumer on destination " + destinationName + " rolling back JMS Session for message: " + message.toString()); + session.rollback(); // rolls back all the consumed messages on the session to + } + + } + catch (Exception ex) { + ex.printStackTrace(); + LOG.error("Error reading JMS Message from destination " + destinationName + "."); + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1866.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1866.java index 1bdd72e6af..9a3aab2b82 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1866.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1866.java @@ -47,178 +47,186 @@ import org.slf4j.LoggerFactory; */ public class AMQ1866 extends TestCase { - private static final Logger log = LoggerFactory.getLogger(ConsumerThread.class); - private BrokerService brokerService; - private ArrayList threads = new ArrayList(); + private static final Logger log = LoggerFactory.getLogger(ConsumerThread.class); + private BrokerService brokerService; + private ArrayList threads = new ArrayList(); - private final String ACTIVEMQ_BROKER_BIND = "tcp://localhost:0"; - private String ACTIVEMQ_BROKER_URI; + private final String ACTIVEMQ_BROKER_BIND = "tcp://localhost:0"; + private String ACTIVEMQ_BROKER_URI; - AtomicBoolean shutdown = new AtomicBoolean(); - private ActiveMQQueue destination; + AtomicBoolean shutdown = new AtomicBoolean(); + private ActiveMQQueue destination; - @Override - protected void setUp() throws Exception { - // Start an embedded broker up. - brokerService = new BrokerService(); - LevelDBStore adaptor = new LevelDBStore(); - brokerService.setPersistenceAdapter(adaptor); - brokerService.deleteAllMessages(); + @Override + protected void setUp() throws Exception { + // Start an embedded broker up. + brokerService = new BrokerService(); + LevelDBStore adaptor = new LevelDBStore(); + brokerService.setPersistenceAdapter(adaptor); + brokerService.deleteAllMessages(); - // A small max page size makes this issue occur faster. - PolicyMap policyMap = new PolicyMap(); - PolicyEntry pe = new PolicyEntry(); - pe.setMaxPageSize(1); - policyMap.put(new ActiveMQQueue(">"), pe); - brokerService.setDestinationPolicy(policyMap); + // A small max page size makes this issue occur faster. + PolicyMap policyMap = new PolicyMap(); + PolicyEntry pe = new PolicyEntry(); + pe.setMaxPageSize(1); + policyMap.put(new ActiveMQQueue(">"), pe); + brokerService.setDestinationPolicy(policyMap); - brokerService.addConnector(ACTIVEMQ_BROKER_BIND); - brokerService.start(); + brokerService.addConnector(ACTIVEMQ_BROKER_BIND); + brokerService.start(); - ACTIVEMQ_BROKER_URI = brokerService.getTransportConnectors().get(0).getPublishableConnectString(); - destination = new ActiveMQQueue(getName()); - } + ACTIVEMQ_BROKER_URI = brokerService.getTransportConnectors().get(0).getPublishableConnectString(); + destination = new ActiveMQQueue(getName()); + } - @Override - protected void tearDown() throws Exception { - // Stop any running threads. - shutdown.set(true); - for (Thread t : threads) { - t.interrupt(); - t.join(); - } - brokerService.stop(); - } + @Override + protected void tearDown() throws Exception { + // Stop any running threads. + shutdown.set(true); + for (Thread t : threads) { + t.interrupt(); + t.join(); + } + brokerService.stop(); + } - public void testConsumerSlowDownPrefetch0() throws Exception { - ACTIVEMQ_BROKER_URI = ACTIVEMQ_BROKER_URI + "?jms.prefetchPolicy.queuePrefetch=0"; - doTestConsumerSlowDown(); - } + public void testConsumerSlowDownPrefetch0() throws Exception { + ACTIVEMQ_BROKER_URI = ACTIVEMQ_BROKER_URI + "?jms.prefetchPolicy.queuePrefetch=0"; + doTestConsumerSlowDown(); + } - public void testConsumerSlowDownPrefetch10() throws Exception { - ACTIVEMQ_BROKER_URI = ACTIVEMQ_BROKER_URI + "?jms.prefetchPolicy.queuePrefetch=10"; - doTestConsumerSlowDown(); - } + public void testConsumerSlowDownPrefetch10() throws Exception { + ACTIVEMQ_BROKER_URI = ACTIVEMQ_BROKER_URI + "?jms.prefetchPolicy.queuePrefetch=10"; + doTestConsumerSlowDown(); + } - public void testConsumerSlowDownDefaultPrefetch() throws Exception { - doTestConsumerSlowDown(); - } + public void testConsumerSlowDownDefaultPrefetch() throws Exception { + doTestConsumerSlowDown(); + } - public void doTestConsumerSlowDown() throws Exception { + public void doTestConsumerSlowDown() throws Exception { - // Preload the queue. - produce(20000); + // Preload the queue. + produce(20000); - Thread producer = new Thread() { - @Override - public void run() { - try { - while(!shutdown.get()) { - produce(1000); - } - } catch (Exception e) { - } + Thread producer = new Thread() { + @Override + public void run() { + try { + while (!shutdown.get()) { + produce(1000); + } } - }; - threads.add(producer); - producer.start(); - - // This is the slow consumer. - ConsumerThread c1 = new ConsumerThread("Consumer-1"); - threads.add(c1); - c1.start(); - - // Wait a bit so that the slow consumer gets assigned most of the messages. - Thread.sleep(500); - ConsumerThread c2 = new ConsumerThread("Consumer-2"); - threads.add(c2); - c2.start(); - - int totalReceived = 0; - for ( int i=0; i < 30; i++) { - Thread.sleep(1000); - long c1Counter = c1.counter.getAndSet(0); - long c2Counter = c2.counter.getAndSet(0); - log.debug("c1: "+c1Counter+", c2: "+c2Counter); - totalReceived += c1Counter; - totalReceived += c2Counter; - - // Once message have been flowing for a few seconds, start asserting that c2 always gets messages. It should be receiving about 100 / sec - if( i > 10 ) { - assertTrue("Total received=" + totalReceived + ", Consumer 2 should be receiving new messages every second.", c2Counter > 0); + catch (Exception e) { } - } - } + } + }; + threads.add(producer); + producer.start(); + + // This is the slow consumer. + ConsumerThread c1 = new ConsumerThread("Consumer-1"); + threads.add(c1); + c1.start(); + + // Wait a bit so that the slow consumer gets assigned most of the messages. + Thread.sleep(500); + ConsumerThread c2 = new ConsumerThread("Consumer-2"); + threads.add(c2); + c2.start(); + + int totalReceived = 0; + for (int i = 0; i < 30; i++) { + Thread.sleep(1000); + long c1Counter = c1.counter.getAndSet(0); + long c2Counter = c2.counter.getAndSet(0); + log.debug("c1: " + c1Counter + ", c2: " + c2Counter); + totalReceived += c1Counter; + totalReceived += c2Counter; + + // Once message have been flowing for a few seconds, start asserting that c2 always gets messages. It should be receiving about 100 / sec + if (i > 10) { + assertTrue("Total received=" + totalReceived + ", Consumer 2 should be receiving new messages every second.", c2Counter > 0); + } + } + } + + public void produce(int count) throws Exception { + Connection connection = null; + try { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(ACTIVEMQ_BROKER_URI); + factory.setDispatchAsync(true); + + connection = factory.createConnection(); + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + connection.start(); + + for (int i = 0; i < count; i++) { + producer.send(session.createTextMessage(getName() + " Message " + (++i))); + } + + } + finally { + try { + connection.close(); + } + catch (Throwable e) { + } + } + } + + public class ConsumerThread extends Thread { + + final AtomicLong counter = new AtomicLong(); + + public ConsumerThread(String threadId) { + super(threadId); + } + + public void run() { + Connection connection = null; + try { + log.debug(getName() + ": is running"); - public void produce(int count) throws Exception { - Connection connection=null; - try { ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(ACTIVEMQ_BROKER_URI); factory.setDispatchAsync(true); connection = factory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); + MessageConsumer consumer = session.createConsumer(destination); connection.start(); - for( int i=0 ; i< count; i++ ) { - producer.send(session.createTextMessage(getName()+" Message "+(++i))); + while (!shutdown.get()) { + TextMessage msg = (TextMessage) consumer.receive(1000); + if (msg != null) { + int sleepingTime; + if (getName().equals("Consumer-1")) { + sleepingTime = 1000 * 1000; + } + else { + sleepingTime = 1; + } + counter.incrementAndGet(); + Thread.sleep(sleepingTime); + } } - } finally { + } + catch (Exception e) { + } + finally { + log.debug(getName() + ": is stopping"); try { - connection.close(); - } catch (Throwable e) { + connection.close(); } - } - } - - public class ConsumerThread extends Thread { - final AtomicLong counter = new AtomicLong(); - - public ConsumerThread(String threadId) { - super(threadId); - } - - public void run() { - Connection connection=null; - try { - log.debug(getName() + ": is running"); - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(ACTIVEMQ_BROKER_URI); - factory.setDispatchAsync(true); - - connection = factory.createConnection(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); - connection.start(); - - while (!shutdown.get()) { - TextMessage msg = (TextMessage)consumer.receive(1000); - if ( msg!=null ) { - int sleepingTime; - if (getName().equals("Consumer-1")) { - sleepingTime = 1000 * 1000; - } else { - sleepingTime = 1; - } - counter.incrementAndGet(); - Thread.sleep(sleepingTime); - } - } - - } catch (Exception e) { - } finally { - log.debug(getName() + ": is stopping"); - try { - connection.close(); - } catch (Throwable e) { - } + catch (Throwable e) { } - } + } + } - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1893Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1893Test.java index f5ccd50269..701b2f1525 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1893Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1893Test.java @@ -17,6 +17,7 @@ package org.apache.activemq.bugs; import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.command.ActiveMQQueue; @@ -40,157 +41,151 @@ import java.util.concurrent.atomic.AtomicInteger; public class AMQ1893Test extends TestCase { - private static final Logger log = LoggerFactory.getLogger(AMQ1893Test.class); + private static final Logger log = LoggerFactory.getLogger(AMQ1893Test.class); - static final String QUEUE_NAME = "TEST"; + static final String QUEUE_NAME = "TEST"; - static final int MESSAGE_COUNT_OF_ONE_GROUP = 10000; + static final int MESSAGE_COUNT_OF_ONE_GROUP = 10000; - static final int[] PRIORITIES = new int[]{0, 5, 10}; + static final int[] PRIORITIES = new int[]{0, 5, 10}; - static final boolean debug = false; + static final boolean debug = false; - private BrokerService brokerService; + private BrokerService brokerService; - private ActiveMQQueue destination; + private ActiveMQQueue destination; - @Override - protected void setUp() throws Exception { - brokerService = new BrokerService(); - brokerService.setDeleteAllMessagesOnStartup(true); - brokerService.addConnector("tcp://localhost:0"); - brokerService.start(); - destination = new ActiveMQQueue(QUEUE_NAME); - } + @Override + protected void setUp() throws Exception { + brokerService = new BrokerService(); + brokerService.setDeleteAllMessagesOnStartup(true); + brokerService.addConnector("tcp://localhost:0"); + brokerService.start(); + destination = new ActiveMQQueue(QUEUE_NAME); + } - @Override - protected void tearDown() throws Exception { - // Stop any running threads. - brokerService.stop(); - } + @Override + protected void tearDown() throws Exception { + // Stop any running threads. + brokerService.stop(); + } + public void testProduceConsumeWithSelector() throws Exception { + new TestProducer().produceMessages(); + new TestConsumer().consume(); + } - public void testProduceConsumeWithSelector() throws Exception { - new TestProducer().produceMessages(); - new TestConsumer().consume(); - } + class TestProducer { - - class TestProducer { + public void produceMessages() throws Exception { + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerService.getTransportConnectors().get(0).getConnectUri().toString()); + Connection connection = connectionFactory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue(QUEUE_NAME); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); - public void produceMessages() throws Exception { - ConnectionFactory connectionFactory = new ActiveMQConnectionFactory( - brokerService.getTransportConnectors().get(0).getConnectUri().toString() - ); - Connection connection = connectionFactory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(QUEUE_NAME); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); + long start = System.currentTimeMillis(); - long start = System.currentTimeMillis(); + for (int priority : PRIORITIES) { - for (int priority : PRIORITIES) { - - String name = null; - if (priority == 10) { - name = "high"; - } else if (priority == 5) { - name = "mid"; - } else { - name = "low"; - } - - for (int i = 1; i <= MESSAGE_COUNT_OF_ONE_GROUP; i++) { - - TextMessage message = session.createTextMessage(name + "_" + i); - message.setIntProperty("priority", priority); - - producer.send(message); - } + String name = null; + if (priority == 10) { + name = "high"; + } + else if (priority == 5) { + name = "mid"; + } + else { + name = "low"; } - long end = System.currentTimeMillis(); + for (int i = 1; i <= MESSAGE_COUNT_OF_ONE_GROUP; i++) { - log.info("sent " + (MESSAGE_COUNT_OF_ONE_GROUP * 3) + " messages in " + (end - start) + " ms"); + TextMessage message = session.createTextMessage(name + "_" + i); + message.setIntProperty("priority", priority); - producer.close(); + producer.send(message); + } + } + + long end = System.currentTimeMillis(); + + log.info("sent " + (MESSAGE_COUNT_OF_ONE_GROUP * 3) + " messages in " + (end - start) + " ms"); + + producer.close(); + session.close(); + connection.close(); + } + } + + class TestConsumer { + + private CountDownLatch finishLatch = new CountDownLatch(1); + + public void consume() throws Exception { + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerService.getTransportConnectors().get(0).getConnectUri().toString()); + + final int totalMessageCount = MESSAGE_COUNT_OF_ONE_GROUP * PRIORITIES.length; + final AtomicInteger counter = new AtomicInteger(); + final MessageListener listener = new MessageListener() { + public void onMessage(Message message) { + + if (debug) { + try { + log.info(((TextMessage) message).getText()); + } + catch (JMSException e) { + e.printStackTrace(); + } + } + + if (counter.incrementAndGet() == totalMessageCount) { + + finishLatch.countDown(); + + } + } + }; + + int consumerCount = PRIORITIES.length; + Connection[] connections = new Connection[consumerCount]; + Session[] sessions = new Session[consumerCount]; + MessageConsumer[] consumers = new MessageConsumer[consumerCount]; + + for (int i = 0; i < consumerCount; i++) { + String selector = "priority = " + PRIORITIES[i]; + + connections[i] = connectionFactory.createConnection(); + sessions[i] = connections[i].createSession(false, Session.AUTO_ACKNOWLEDGE); + + consumers[i] = sessions[i].createConsumer(destination, selector); + consumers[i].setMessageListener(listener); + } + + for (Connection connection : connections) { + connection.start(); + } + + log.info("received " + counter.get() + " messages"); + + assertTrue("got all messages in time", finishLatch.await(60, TimeUnit.SECONDS)); + + log.info("received " + counter.get() + " messages"); + + for (MessageConsumer consumer : consumers) { + consumer.close(); + } + + for (Session session : sessions) { session.close(); + } + + for (Connection connection : connections) { connection.close(); - } - } + } + } - class TestConsumer { - - private CountDownLatch finishLatch = new CountDownLatch(1); - - - - public void consume() throws Exception { - ConnectionFactory connectionFactory = new ActiveMQConnectionFactory( - brokerService.getTransportConnectors().get(0).getConnectUri().toString() - ); - - - final int totalMessageCount = MESSAGE_COUNT_OF_ONE_GROUP * PRIORITIES.length; - final AtomicInteger counter = new AtomicInteger(); - final MessageListener listener = new MessageListener() { - public void onMessage(Message message) { - - if (debug) { - try { - log.info(((TextMessage) message).getText()); - } catch (JMSException e) { - e.printStackTrace(); - } - } - - if (counter.incrementAndGet() == totalMessageCount) { - - finishLatch.countDown(); - - } - } - }; - - int consumerCount = PRIORITIES.length; - Connection[] connections = new Connection[consumerCount]; - Session[] sessions = new Session[consumerCount]; - MessageConsumer[] consumers = new MessageConsumer[consumerCount]; - - for (int i = 0; i < consumerCount; i++) { - String selector = "priority = " + PRIORITIES[i]; - - connections[i] = connectionFactory.createConnection(); - sessions[i] = connections[i].createSession(false, Session.AUTO_ACKNOWLEDGE); - - consumers[i] = sessions[i].createConsumer(destination, selector); - consumers[i].setMessageListener(listener); - } - - for (Connection connection : connections) { - connection.start(); - } - - log.info("received " + counter.get() + " messages"); - - assertTrue("got all messages in time", finishLatch.await(60, TimeUnit.SECONDS)); - - log.info("received " + counter.get() + " messages"); - - for (MessageConsumer consumer : consumers) { - consumer.close(); - } - - for (Session session : sessions) { - session.close(); - } - - for (Connection connection : connections) { - connection.close(); - } - } - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1917Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1917Test.java index ad9970757d..abb331c6e5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1917Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1917Test.java @@ -17,6 +17,7 @@ package org.apache.activemq.bugs; import junit.framework.TestCase; + import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; @@ -38,191 +39,186 @@ import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.command.ActiveMQDestination; - public class AMQ1917Test extends TestCase { - private static final int NUM_MESSAGES = 4000; - private static final int NUM_THREADS = 10; - private static final String REQUEST_QUEUE = "mock.in.queue"; - private static final String REPLY_QUEUE = "mock.out.queue"; + private static final int NUM_MESSAGES = 4000; + private static final int NUM_THREADS = 10; + private static final String REQUEST_QUEUE = "mock.in.queue"; + private static final String REPLY_QUEUE = "mock.out.queue"; - private Destination requestDestination = ActiveMQDestination.createDestination( - REQUEST_QUEUE, ActiveMQDestination.QUEUE_TYPE); - private Destination replyDestination = ActiveMQDestination.createDestination( - REPLY_QUEUE, ActiveMQDestination.QUEUE_TYPE); + private Destination requestDestination = ActiveMQDestination.createDestination(REQUEST_QUEUE, ActiveMQDestination.QUEUE_TYPE); + private Destination replyDestination = ActiveMQDestination.createDestination(REPLY_QUEUE, ActiveMQDestination.QUEUE_TYPE); - private CountDownLatch roundTripLatch = new CountDownLatch(NUM_MESSAGES); - private CountDownLatch errorLatch = new CountDownLatch(1); - private ThreadPoolExecutor tpe; - private final String BROKER_URL = "tcp://localhost:0"; - private String connectionUri; - private BrokerService broker = null; - private boolean working = true; + private CountDownLatch roundTripLatch = new CountDownLatch(NUM_MESSAGES); + private CountDownLatch errorLatch = new CountDownLatch(1); + private ThreadPoolExecutor tpe; + private final String BROKER_URL = "tcp://localhost:0"; + private String connectionUri; + private BrokerService broker = null; + private boolean working = true; - // trival session/producer pool - final Session[] sessions = new Session[NUM_THREADS]; - final MessageProducer[] producers = new MessageProducer[NUM_THREADS]; + // trival session/producer pool + final Session[] sessions = new Session[NUM_THREADS]; + final MessageProducer[] producers = new MessageProducer[NUM_THREADS]; - public void setUp() throws Exception { - broker = new BrokerService(); - broker.setPersistent(false); - broker.addConnector(BROKER_URL); - broker.start(); + public void setUp() throws Exception { + broker = new BrokerService(); + broker.setPersistent(false); + broker.addConnector(BROKER_URL); + broker.start(); - connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); + connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); - BlockingQueue queue = new ArrayBlockingQueue(10000); - tpe = new ThreadPoolExecutor(NUM_THREADS, NUM_THREADS, 60000, - TimeUnit.MILLISECONDS, queue); - ThreadFactory limitedthreadFactory = new LimitedThreadFactory(tpe.getThreadFactory()); - tpe.setThreadFactory(limitedthreadFactory); - } + BlockingQueue queue = new ArrayBlockingQueue(10000); + tpe = new ThreadPoolExecutor(NUM_THREADS, NUM_THREADS, 60000, TimeUnit.MILLISECONDS, queue); + ThreadFactory limitedthreadFactory = new LimitedThreadFactory(tpe.getThreadFactory()); + tpe.setThreadFactory(limitedthreadFactory); + } - public void tearDown() throws Exception { - broker.stop(); - tpe.shutdown(); - } + public void tearDown() throws Exception { + broker.stop(); + tpe.shutdown(); + } - public void testLoadedSendReceiveWithCorrelationId() throws Exception { + public void testLoadedSendReceiveWithCorrelationId() throws Exception { - ActiveMQConnectionFactory connectionFactory = new org.apache.activemq.ActiveMQConnectionFactory(); - connectionFactory.setBrokerURL(connectionUri); - Connection connection = connectionFactory.createConnection(); - setupReceiver(connection); + ActiveMQConnectionFactory connectionFactory = new org.apache.activemq.ActiveMQConnectionFactory(); + connectionFactory.setBrokerURL(connectionUri); + Connection connection = connectionFactory.createConnection(); + setupReceiver(connection); - connection = connectionFactory.createConnection(); - connection.start(); + connection = connectionFactory.createConnection(); + connection.start(); - // trival session/producer pool - for (int i=0; i NUM_THREADS) { - errorLatch.countDown(); - fail("too many threads requested"); - } - return factory.newThread(arg0); - } - } - } + public Thread newThread(Runnable arg0) { + if (++threadCount > NUM_THREADS) { + errorLatch.countDown(); + fail("too many threads requested"); + } + return factory.newThread(arg0); + } + } +} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1936Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1936Test.java index 16cbcc0335..d96fbfc931 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1936Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ1936Test.java @@ -46,265 +46,275 @@ import org.apache.log4j.Logger; /** * AMQ1936Test - * */ public class AMQ1936Test extends TestCase { - private final static Logger logger = Logger.getLogger(AMQ1936Test.class); - private final static String TEST_QUEUE_NAME = "dynamicQueues/duplicate.message.test.queue"; - // //-- - // - private final static long TEST_MESSAGE_COUNT = 6000; // The number of test messages to use - // - // //-- - private final static int CONSUMER_COUNT = 2; // The number of message receiver instances - private final static boolean TRANSACTED_RECEIVE = true; // Flag used by receiver which indicates messages should be - // processed within a JMS transaction - private final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(CONSUMER_COUNT, CONSUMER_COUNT, Long.MAX_VALUE, TimeUnit.SECONDS, - new LinkedBlockingQueue()); - private final ThreadedMessageReceiver[] receivers = new ThreadedMessageReceiver[CONSUMER_COUNT]; - private BrokerService broker = null; - static QueueConnectionFactory connectionFactory = null; + private final static Logger logger = Logger.getLogger(AMQ1936Test.class); + private final static String TEST_QUEUE_NAME = "dynamicQueues/duplicate.message.test.queue"; + // //-- + // + private final static long TEST_MESSAGE_COUNT = 6000; // The number of test messages to use + // + // //-- + private final static int CONSUMER_COUNT = 2; // The number of message receiver instances + private final static boolean TRANSACTED_RECEIVE = true; // Flag used by receiver which indicates messages should be + // processed within a JMS transaction - @Override - protected void setUp() throws Exception { - super.setUp(); + private final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(CONSUMER_COUNT, CONSUMER_COUNT, Long.MAX_VALUE, TimeUnit.SECONDS, new LinkedBlockingQueue()); + private final ThreadedMessageReceiver[] receivers = new ThreadedMessageReceiver[CONSUMER_COUNT]; + private BrokerService broker = null; + static QueueConnectionFactory connectionFactory = null; - broker = new BrokerService(); - broker.getSystemUsage().getMemoryUsage().setLimit(5 * 1024 * 1024); - broker.setBrokerName("test"); - broker.setDeleteAllMessagesOnStartup(true); - broker.start(); - connectionFactory = new ActiveMQConnectionFactory("vm://test"); - ; - } + @Override + protected void setUp() throws Exception { + super.setUp(); - @Override - protected void tearDown() throws Exception { - super.tearDown(); + broker = new BrokerService(); + broker.getSystemUsage().getMemoryUsage().setLimit(5 * 1024 * 1024); + broker.setBrokerName("test"); + broker.setDeleteAllMessagesOnStartup(true); + broker.start(); + connectionFactory = new ActiveMQConnectionFactory("vm://test"); + ; + } - if (threadPool != null) { - // signal receivers to stop - for (ThreadedMessageReceiver receiver : receivers) { - receiver.setShouldStop(true); - } + @Override + protected void tearDown() throws Exception { + super.tearDown(); - logger.info("Waiting for receivers to shutdown.."); - if (!threadPool.awaitTermination(10, TimeUnit.SECONDS)) { - logger.warn("Not all receivers completed shutdown."); - } else { - logger.info("All receivers shutdown successfully.."); - } - } + if (threadPool != null) { + // signal receivers to stop + for (ThreadedMessageReceiver receiver : receivers) { + receiver.setShouldStop(true); + } - logger.debug("Stoping the broker."); + logger.info("Waiting for receivers to shutdown.."); + if (!threadPool.awaitTermination(10, TimeUnit.SECONDS)) { + logger.warn("Not all receivers completed shutdown."); + } + else { + logger.info("All receivers shutdown successfully.."); + } + } - if (broker != null) { - broker.stop(); - } - } + logger.debug("Stoping the broker."); - private void sendTextMessage(String queueName, int i) throws JMSException, NamingException { - QueueConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://test"); - QueueConnection queueConnection = null; - QueueSession session = null; - QueueSender sender = null; - Queue queue = null; - TextMessage message = null; + if (broker != null) { + broker.stop(); + } + } - try { + private void sendTextMessage(String queueName, int i) throws JMSException, NamingException { + QueueConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://test"); + QueueConnection queueConnection = null; + QueueSession session = null; + QueueSender sender = null; + Queue queue = null; + TextMessage message = null; - // Create the queue connection - queueConnection = connectionFactory.createQueueConnection(); + try { - session = queueConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE); - queue = session.createQueue(TEST_QUEUE_NAME); - sender = session.createSender(queue); - sender.setDeliveryMode(DeliveryMode.PERSISTENT); + // Create the queue connection + queueConnection = connectionFactory.createQueueConnection(); - message = session.createTextMessage(String.valueOf(i)); + session = queueConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE); + queue = session.createQueue(TEST_QUEUE_NAME); + sender = session.createSender(queue); + sender.setDeliveryMode(DeliveryMode.PERSISTENT); - // send the message - sender.send(message); + message = session.createTextMessage(String.valueOf(i)); - if (session.getTransacted()) { - session.commit(); - } - if (i % 1000 == 0) { - logger.info("Message successfully sent to : " + queue.getQueueName() + " messageid: " + message.getJMSMessageID() + " content:" - + message.getText()); - } - } finally { - if (sender != null) { - sender.close(); - } - if (session != null) { - session.close(); - } - if (queueConnection != null) { - queueConnection.close(); - } - } - } + // send the message + sender.send(message); - public void testForDuplicateMessages() throws Exception { - final ConcurrentHashMap messages = new ConcurrentHashMap(); - final Object lock = new Object(); - final CountDownLatch duplicateSignal = new CountDownLatch(1); - final AtomicInteger messageCount = new AtomicInteger(0); + if (session.getTransacted()) { + session.commit(); + } + if (i % 1000 == 0) { + logger.info("Message successfully sent to : " + queue.getQueueName() + " messageid: " + message.getJMSMessageID() + " content:" + message.getText()); + } + } + finally { + if (sender != null) { + sender.close(); + } + if (session != null) { + session.close(); + } + if (queueConnection != null) { + queueConnection.close(); + } + } + } - // add 1/2 the number of our total messages - for (int i = 0; i < TEST_MESSAGE_COUNT / 2; i++) { - if (duplicateSignal.getCount() == 0) { - fail("Duplicate message id detected"); - } - sendTextMessage(TEST_QUEUE_NAME, i); - } + public void testForDuplicateMessages() throws Exception { + final ConcurrentHashMap messages = new ConcurrentHashMap(); + final Object lock = new Object(); + final CountDownLatch duplicateSignal = new CountDownLatch(1); + final AtomicInteger messageCount = new AtomicInteger(0); - // create a number of consumers to read of the messages and start them with a handler which simply stores the - // message ids - // in a Map and checks for a duplicate - for (int i = 0; i < CONSUMER_COUNT; i++) { - receivers[i] = new ThreadedMessageReceiver(TEST_QUEUE_NAME, new IMessageHandler() { + // add 1/2 the number of our total messages + for (int i = 0; i < TEST_MESSAGE_COUNT / 2; i++) { + if (duplicateSignal.getCount() == 0) { + fail("Duplicate message id detected"); + } + sendTextMessage(TEST_QUEUE_NAME, i); + } - @Override - public void onMessage(Message message) throws Exception { - synchronized (lock) { - int current = messageCount.incrementAndGet(); - if (current % 1000 == 0) { - logger.info("Received message:" + message.getJMSMessageID() + " with content: " + ((TextMessage) message).getText()); - } - if (messages.containsKey(message.getJMSMessageID())) { - duplicateSignal.countDown(); - logger.fatal("duplicate message id detected:" + message.getJMSMessageID()); - fail("Duplicate message id detected:" + message.getJMSMessageID()); - } else { - messages.put(message.getJMSMessageID(), message.getJMSMessageID()); - } - } - } - }); - threadPool.submit(receivers[i]); - } + // create a number of consumers to read of the messages and start them with a handler which simply stores the + // message ids + // in a Map and checks for a duplicate + for (int i = 0; i < CONSUMER_COUNT; i++) { + receivers[i] = new ThreadedMessageReceiver(TEST_QUEUE_NAME, new IMessageHandler() { - // starting adding the remaining messages - for (int i = 0; i < TEST_MESSAGE_COUNT / 2; i++) { - if (duplicateSignal.getCount() == 0) { - fail("Duplicate message id detected"); - } - sendTextMessage(TEST_QUEUE_NAME, i); - } - - logger.info("sent all " + TEST_MESSAGE_COUNT + " messages"); - - // allow some time for messages to be delivered to receivers. - boolean ok = Wait.waitFor(new Wait.Condition() { @Override - public boolean isSatisified() throws Exception { - return TEST_MESSAGE_COUNT == messages.size(); + public void onMessage(Message message) throws Exception { + synchronized (lock) { + int current = messageCount.incrementAndGet(); + if (current % 1000 == 0) { + logger.info("Received message:" + message.getJMSMessageID() + " with content: " + ((TextMessage) message).getText()); + } + if (messages.containsKey(message.getJMSMessageID())) { + duplicateSignal.countDown(); + logger.fatal("duplicate message id detected:" + message.getJMSMessageID()); + fail("Duplicate message id detected:" + message.getJMSMessageID()); + } + else { + messages.put(message.getJMSMessageID(), message.getJMSMessageID()); + } + } } - }, TimeUnit.MINUTES.toMillis(7)); - if (!ok) { - AutoFailTestSupport.dumpAllThreads("--STUCK?--"); - } - assertEquals("Number of messages received does not match the number sent", TEST_MESSAGE_COUNT, messages.size()); - assertEquals(TEST_MESSAGE_COUNT, messageCount.get()); - } + }); + threadPool.submit(receivers[i]); + } - private final static class ThreadedMessageReceiver implements Runnable { + // starting adding the remaining messages + for (int i = 0; i < TEST_MESSAGE_COUNT / 2; i++) { + if (duplicateSignal.getCount() == 0) { + fail("Duplicate message id detected"); + } + sendTextMessage(TEST_QUEUE_NAME, i); + } - private IMessageHandler handler = null; - private final AtomicBoolean shouldStop = new AtomicBoolean(false); + logger.info("sent all " + TEST_MESSAGE_COUNT + " messages"); - public ThreadedMessageReceiver(String queueName, IMessageHandler handler) { - this.handler = handler; - } + // allow some time for messages to be delivered to receivers. + boolean ok = Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return TEST_MESSAGE_COUNT == messages.size(); + } + }, TimeUnit.MINUTES.toMillis(7)); + if (!ok) { + AutoFailTestSupport.dumpAllThreads("--STUCK?--"); + } + assertEquals("Number of messages received does not match the number sent", TEST_MESSAGE_COUNT, messages.size()); + assertEquals(TEST_MESSAGE_COUNT, messageCount.get()); + } - @Override - public void run() { + private final static class ThreadedMessageReceiver implements Runnable { - QueueConnection queueConnection = null; - QueueSession session = null; - QueueReceiver receiver = null; - Queue queue = null; - Message message = null; + private IMessageHandler handler = null; + private final AtomicBoolean shouldStop = new AtomicBoolean(false); + + public ThreadedMessageReceiver(String queueName, IMessageHandler handler) { + this.handler = handler; + } + + @Override + public void run() { + + QueueConnection queueConnection = null; + QueueSession session = null; + QueueReceiver receiver = null; + Queue queue = null; + Message message = null; + try { try { - try { - queueConnection = connectionFactory.createQueueConnection(); - // create a transacted session - session = queueConnection.createQueueSession(TRANSACTED_RECEIVE, QueueSession.AUTO_ACKNOWLEDGE); - queue = session.createQueue(TEST_QUEUE_NAME); - receiver = session.createReceiver(queue); + queueConnection = connectionFactory.createQueueConnection(); + // create a transacted session + session = queueConnection.createQueueSession(TRANSACTED_RECEIVE, QueueSession.AUTO_ACKNOWLEDGE); + queue = session.createQueue(TEST_QUEUE_NAME); + receiver = session.createReceiver(queue); - // start the connection - queueConnection.start(); + // start the connection + queueConnection.start(); - logger.info("Receiver " + Thread.currentThread().getName() + " connected."); + logger.info("Receiver " + Thread.currentThread().getName() + " connected."); - // start receive loop - while (!(shouldStop.get() || Thread.currentThread().isInterrupted())) { - try { - message = receiver.receive(200); - } catch (Exception e) { - // - // ignore interrupted exceptions - // - if (e instanceof InterruptedException || e.getCause() instanceof InterruptedException) { + // start receive loop + while (!(shouldStop.get() || Thread.currentThread().isInterrupted())) { + try { + message = receiver.receive(200); + } + catch (Exception e) { + // + // ignore interrupted exceptions + // + if (e instanceof InterruptedException || e.getCause() instanceof InterruptedException) { /* ignore */ - } else { - throw e; - } - } + } + else { + throw e; + } + } - if (message != null && this.handler != null) { - this.handler.onMessage(message); - } + if (message != null && this.handler != null) { + this.handler.onMessage(message); + } - // commit session on successful handling of message - if (session.getTransacted()) { - session.commit(); - } - } + // commit session on successful handling of message + if (session.getTransacted()) { + session.commit(); + } + } - logger.info("Receiver " + Thread.currentThread().getName() + " shutting down."); + logger.info("Receiver " + Thread.currentThread().getName() + " shutting down."); - } finally { - if (receiver != null) { - try { - receiver.close(); - } catch (JMSException e) { - logger.warn(e); - } - } - if (session != null) { - try { - session.close(); - } catch (JMSException e) { - logger.warn(e); - } - } - if (queueConnection != null) { - queueConnection.close(); - } - } - } catch (JMSException e) { - logger.error(e); - e.printStackTrace(); - } catch (NamingException e) { - logger.error(e); - } catch (Exception e) { - logger.error(e); - e.printStackTrace(); } - } + finally { + if (receiver != null) { + try { + receiver.close(); + } + catch (JMSException e) { + logger.warn(e); + } + } + if (session != null) { + try { + session.close(); + } + catch (JMSException e) { + logger.warn(e); + } + } + if (queueConnection != null) { + queueConnection.close(); + } + } + } + catch (JMSException e) { + logger.error(e); + e.printStackTrace(); + } + catch (NamingException e) { + logger.error(e); + } + catch (Exception e) { + logger.error(e); + e.printStackTrace(); + } + } - public void setShouldStop(Boolean shouldStop) { - this.shouldStop.set(shouldStop); - } - } + public void setShouldStop(Boolean shouldStop) { + this.shouldStop.set(shouldStop); + } + } - public interface IMessageHandler { - void onMessage(Message message) throws Exception; - } + public interface IMessageHandler { + + void onMessage(Message message) throws Exception; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2021Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2021Test.java index 9abab3f607..b2f9495758 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2021Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2021Test.java @@ -55,213 +55,221 @@ import org.slf4j.LoggerFactory; */ public class AMQ2021Test implements ExceptionListener, UncaughtExceptionHandler { - private static final Logger log = LoggerFactory.getLogger(AMQ2021Test.class); - BrokerService brokerService; - ArrayList threads = new ArrayList(); - Vector exceptions; + private static final Logger log = LoggerFactory.getLogger(AMQ2021Test.class); + BrokerService brokerService; + ArrayList threads = new ArrayList(); + Vector exceptions; - @Rule - public TestName name = new TestName(); + @Rule + public TestName name = new TestName(); - AMQ2021Test testCase; + AMQ2021Test testCase; - private final String ACTIVEMQ_BROKER_BIND = "tcp://localhost:0"; - private String CONSUMER_BROKER_URL = "?jms.redeliveryPolicy.maximumRedeliveries=1&jms.redeliveryPolicy.initialRedeliveryDelay=0"; - private String PRODUCER_BROKER_URL; + private final String ACTIVEMQ_BROKER_BIND = "tcp://localhost:0"; + private String CONSUMER_BROKER_URL = "?jms.redeliveryPolicy.maximumRedeliveries=1&jms.redeliveryPolicy.initialRedeliveryDelay=0"; + private String PRODUCER_BROKER_URL; - private final int numMessages = 1000; - private final int numConsumers = 2; - private final int dlqMessages = numMessages / 2; + private final int numMessages = 1000; + private final int numConsumers = 2; + private final int dlqMessages = numMessages / 2; - private CountDownLatch receivedLatch; - private ActiveMQTopic destination; - private CountDownLatch started; + private CountDownLatch receivedLatch; + private ActiveMQTopic destination; + private CountDownLatch started; - @Before - public void setUp() throws Exception { - Thread.setDefaultUncaughtExceptionHandler(this); - testCase = this; + @Before + public void setUp() throws Exception { + Thread.setDefaultUncaughtExceptionHandler(this); + testCase = this; - // Start an embedded broker up. - brokerService = new BrokerService(); - brokerService.setDeleteAllMessagesOnStartup(true); - brokerService.addConnector(ACTIVEMQ_BROKER_BIND); - brokerService.start(); - destination = new ActiveMQTopic(name.getMethodName()); - exceptions = new Vector(); + // Start an embedded broker up. + brokerService = new BrokerService(); + brokerService.setDeleteAllMessagesOnStartup(true); + brokerService.addConnector(ACTIVEMQ_BROKER_BIND); + brokerService.start(); + destination = new ActiveMQTopic(name.getMethodName()); + exceptions = new Vector(); - CONSUMER_BROKER_URL = brokerService.getTransportConnectors().get(0).getPublishableConnectString() + CONSUMER_BROKER_URL; - PRODUCER_BROKER_URL = brokerService.getTransportConnectors().get(0).getPublishableConnectString(); + CONSUMER_BROKER_URL = brokerService.getTransportConnectors().get(0).getPublishableConnectString() + CONSUMER_BROKER_URL; + PRODUCER_BROKER_URL = brokerService.getTransportConnectors().get(0).getPublishableConnectString(); - receivedLatch = new CountDownLatch(numConsumers * (numMessages + dlqMessages)); - started = new CountDownLatch(1); - } + receivedLatch = new CountDownLatch(numConsumers * (numMessages + dlqMessages)); + started = new CountDownLatch(1); + } - @After - public void tearDown() throws Exception { - for (Thread t : threads) { - t.interrupt(); - t.join(); - } - brokerService.stop(); - } + @After + public void tearDown() throws Exception { + for (Thread t : threads) { + t.interrupt(); + t.join(); + } + brokerService.stop(); + } - @Test(timeout=240000) - public void testConcurrentTopicResendToDLQ() throws Exception { + @Test(timeout = 240000) + public void testConcurrentTopicResendToDLQ() throws Exception { - for (int i = 0; i < numConsumers; i++) { - ConsumerThread c1 = new ConsumerThread("Consumer-" + i); - threads.add(c1); - c1.start(); - } + for (int i = 0; i < numConsumers; i++) { + ConsumerThread c1 = new ConsumerThread("Consumer-" + i); + threads.add(c1); + c1.start(); + } - assertTrue(started.await(10, TimeUnit.SECONDS)); + assertTrue(started.await(10, TimeUnit.SECONDS)); - Thread producer = new Thread() { - @Override - public void run() { - try { - produce(numMessages); - } catch (Exception e) { - } + Thread producer = new Thread() { + @Override + public void run() { + try { + produce(numMessages); } - }; - threads.add(producer); - producer.start(); - - boolean allGood = receivedLatch.await(90, TimeUnit.SECONDS); - for (Throwable t : exceptions) { - log.error("failing test with first exception", t); - fail("exception during test : " + t); - } - assertTrue("excepted messages received within time limit", allGood); - - assertEquals(0, exceptions.size()); - - for (int i = 0; i < numConsumers; i++) { - // last recovery sends message to deq so is not received again - assertEquals(dlqMessages * 2, ((ConsumerThread) threads.get(i)).recoveries); - assertEquals(numMessages + dlqMessages, ((ConsumerThread) threads.get(i)).counter); - } - - // half of the messages for each consumer should go to the dlq but duplicates will - // be suppressed - consumeFromDLQ(dlqMessages); - - } - - private void consumeFromDLQ(int messageCount) throws Exception { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(CONSUMER_BROKER_URL); - Connection connection = connectionFactory.createConnection(); - connection.start(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer dlqConsumer = session.createConsumer(new ActiveMQQueue("ActiveMQ.DLQ")); - int count = 0; - for (int i = 0; i < messageCount; i++) { - if (dlqConsumer.receive(1000) == null) { - break; + catch (Exception e) { } - count++; - } - assertEquals(messageCount, count); - } + } + }; + threads.add(producer); + producer.start(); - public void produce(int count) throws Exception { - Connection connection = null; - try { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(PRODUCER_BROKER_URL); - connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - producer.setTimeToLive(0); + boolean allGood = receivedLatch.await(90, TimeUnit.SECONDS); + for (Throwable t : exceptions) { + log.error("failing test with first exception", t); + fail("exception during test : " + t); + } + assertTrue("excepted messages received within time limit", allGood); + + assertEquals(0, exceptions.size()); + + for (int i = 0; i < numConsumers; i++) { + // last recovery sends message to deq so is not received again + assertEquals(dlqMessages * 2, ((ConsumerThread) threads.get(i)).recoveries); + assertEquals(numMessages + dlqMessages, ((ConsumerThread) threads.get(i)).counter); + } + + // half of the messages for each consumer should go to the dlq but duplicates will + // be suppressed + consumeFromDLQ(dlqMessages); + + } + + private void consumeFromDLQ(int messageCount) throws Exception { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(CONSUMER_BROKER_URL); + Connection connection = connectionFactory.createConnection(); + connection.start(); + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer dlqConsumer = session.createConsumer(new ActiveMQQueue("ActiveMQ.DLQ")); + int count = 0; + for (int i = 0; i < messageCount; i++) { + if (dlqConsumer.receive(1000) == null) { + break; + } + count++; + } + assertEquals(messageCount, count); + } + + public void produce(int count) throws Exception { + Connection connection = null; + try { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(PRODUCER_BROKER_URL); + connection = factory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + producer.setTimeToLive(0); + connection.start(); + + for (int i = 0; i < count; i++) { + int id = i + 1; + TextMessage message = session.createTextMessage(name.getMethodName() + " Message " + id); + message.setIntProperty("MsgNumber", id); + producer.send(message); + + if (id % 500 == 0) { + log.info("sent " + id + ", ith " + message); + } + } + } + catch (JMSException e) { + log.error("unexpected ex on produce", e); + exceptions.add(e); + } + finally { + try { + if (connection != null) { + connection.close(); + } + } + catch (Throwable e) { + } + } + } + + public class ConsumerThread extends Thread implements MessageListener { + + public long counter = 0; + public long recoveries = 0; + private Session session; + + public ConsumerThread(String threadId) { + super(threadId); + } + + @Override + public void run() { + try { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(CONSUMER_BROKER_URL); + Connection connection = connectionFactory.createConnection(); + connection.setExceptionListener(testCase); + connection.setClientID(getName()); + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + MessageConsumer consumer = session.createDurableSubscriber(destination, getName()); + consumer.setMessageListener(this); connection.start(); - for (int i = 0; i < count; i++) { - int id = i + 1; - TextMessage message = session.createTextMessage(name.getMethodName() + " Message " + id); - message.setIntProperty("MsgNumber", id); - producer.send(message); + started.countDown(); - if (id % 500 == 0) { - log.info("sent " + id + ", ith " + message); - } + } + catch (JMSException exception) { + log.error("unexpected ex in consumer run", exception); + exceptions.add(exception); + } + } + + @Override + public void onMessage(Message message) { + try { + counter++; + int messageNumber = message.getIntProperty("MsgNumber"); + if (messageNumber % 2 == 0) { + session.recover(); + recoveries++; } - } catch (JMSException e) { - log.error("unexpected ex on produce", e); + else { + message.acknowledge(); + } + + if (counter % 200 == 0) { + log.info("recoveries:" + recoveries + ", Received " + counter + ", counter'th " + message); + } + receivedLatch.countDown(); + } + catch (Exception e) { + log.error("unexpected ex on onMessage", e); exceptions.add(e); - } finally { - try { - if (connection != null) { - connection.close(); - } - } catch (Throwable e) { - } - } - } + } + } - public class ConsumerThread extends Thread implements MessageListener { - public long counter = 0; - public long recoveries = 0; - private Session session; + } - public ConsumerThread(String threadId) { - super(threadId); - } + @Override + public void onException(JMSException exception) { + log.info("Unexpected JMSException", exception); + exceptions.add(exception); + } - @Override - public void run() { - try { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(CONSUMER_BROKER_URL); - Connection connection = connectionFactory.createConnection(); - connection.setExceptionListener(testCase); - connection.setClientID(getName()); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(destination, getName()); - consumer.setMessageListener(this); - connection.start(); - - started.countDown(); - - } catch (JMSException exception) { - log.error("unexpected ex in consumer run", exception); - exceptions.add(exception); - } - } - - @Override - public void onMessage(Message message) { - try { - counter++; - int messageNumber = message.getIntProperty("MsgNumber"); - if (messageNumber % 2 == 0) { - session.recover(); - recoveries++; - } else { - message.acknowledge(); - } - - if (counter % 200 == 0) { - log.info("recoveries:" + recoveries + ", Received " + counter + ", counter'th " + message); - } - receivedLatch.countDown(); - } catch (Exception e) { - log.error("unexpected ex on onMessage", e); - exceptions.add(e); - } - } - - } - - @Override - public void onException(JMSException exception) { - log.info("Unexpected JMSException", exception); - exceptions.add(exception); - } - - @Override - public void uncaughtException(Thread thread, Throwable exception) { - log.info("Unexpected exception from thread " + thread + ", ex: " + exception); - exceptions.add(exception); - } + @Override + public void uncaughtException(Thread thread, Throwable exception) { + log.info("Unexpected exception from thread " + thread + ", ex: " + exception); + exceptions.add(exception); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2084Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2084Test.java index 1f31864a15..8009699326 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2084Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2084Test.java @@ -49,133 +49,138 @@ import org.slf4j.LoggerFactory; public class AMQ2084Test { - private static final Logger LOG = LoggerFactory.getLogger(AMQ2084Test.class); - BrokerService broker; - CountDownLatch qreceived; - String connectionUri; + private static final Logger LOG = LoggerFactory.getLogger(AMQ2084Test.class); + BrokerService broker; + CountDownLatch qreceived; + String connectionUri; - @Before - public void startBroker() throws Exception { - broker = new BrokerService(); - broker.setPersistent(false); - connectionUri = broker.addConnector("tcp://localhost:0").getPublishableConnectString(); - broker.start(); + @Before + public void startBroker() throws Exception { + broker = new BrokerService(); + broker.setPersistent(false); + connectionUri = broker.addConnector("tcp://localhost:0").getPublishableConnectString(); + broker.start(); - qreceived = new CountDownLatch(1); - } + qreceived = new CountDownLatch(1); + } - @After - public void stopBroker() throws Exception { - if (broker != null) { - broker.stop(); - } - } + @After + public void stopBroker() throws Exception { + if (broker != null) { + broker.stop(); + } + } - public void listenQueue(final String queueName, final String selectors) { - try { - Properties props = new Properties(); - props.put("java.naming.factory.initial", "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); - props.put("java.naming.provider.url", connectionUri); - props.put("queue.queueName", queueName); + public void listenQueue(final String queueName, final String selectors) { + try { + Properties props = new Properties(); + props.put("java.naming.factory.initial", "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); + props.put("java.naming.provider.url", connectionUri); + props.put("queue.queueName", queueName); - javax.naming.Context ctx = new InitialContext(props); - QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup("ConnectionFactory"); - QueueConnection conn = factory.createQueueConnection(); - final Queue queue = (Queue) ctx.lookup("queueName"); - QueueSession session = conn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); - QueueReceiver receiver = session.createReceiver(queue, selectors); - System.out.println("Message Selector: " + receiver.getMessageSelector()); - receiver.setMessageListener(new MessageListener() { - public void onMessage(Message message) { - try { - if (message instanceof TextMessage) { - TextMessage txtMsg = (TextMessage) message; - String msg = txtMsg.getText(); - LOG.info("Queue Message Received: " + queueName + " - " + msg); - qreceived.countDown(); + javax.naming.Context ctx = new InitialContext(props); + QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup("ConnectionFactory"); + QueueConnection conn = factory.createQueueConnection(); + final Queue queue = (Queue) ctx.lookup("queueName"); + QueueSession session = conn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); + QueueReceiver receiver = session.createReceiver(queue, selectors); + System.out.println("Message Selector: " + receiver.getMessageSelector()); + receiver.setMessageListener(new MessageListener() { + public void onMessage(Message message) { + try { + if (message instanceof TextMessage) { + TextMessage txtMsg = (TextMessage) message; + String msg = txtMsg.getText(); + LOG.info("Queue Message Received: " + queueName + " - " + msg); + qreceived.countDown(); - } - message.acknowledge(); - } catch (Throwable e) { - e.printStackTrace(); - } - } - }); - conn.start(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public void listenTopic(final String topicName, final String selectors) { - try { - Properties props = new Properties(); - props.put("java.naming.factory.initial", "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); - props.put("java.naming.provider.url", connectionUri); - props.put("topic.topicName", topicName); - - javax.naming.Context ctx = new InitialContext(props); - TopicConnectionFactory factory = (TopicConnectionFactory) ctx.lookup("ConnectionFactory"); - TopicConnection conn = factory.createTopicConnection(); - final Topic topic = (Topic) ctx.lookup("topicName"); - TopicSession session = conn.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber receiver = session.createSubscriber(topic, selectors, false); - - receiver.setMessageListener(new MessageListener() { - public void onMessage(Message message) { - try { - if (message instanceof TextMessage) { - TextMessage txtMsg = (TextMessage) message; - String msg = txtMsg.getText(); - LOG.info("Topic Message Received: " + topicName + " - " + msg); - } - message.acknowledge(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - conn.start(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public void publish(String topicName, String message) { - try { - Properties props = new Properties(); - props.put("java.naming.factory.initial", "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); - props.put("java.naming.provider.url", connectionUri); - props.put("topic.topicName", topicName); - javax.naming.Context ctx = new InitialContext(props); - TopicConnectionFactory factory = (TopicConnectionFactory) ctx.lookup("ConnectionFactory"); - TopicConnection conn = factory.createTopicConnection(); - Topic topic = (Topic) ctx.lookup("topicName"); - TopicSession session = conn.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - TopicPublisher publisher = session.createPublisher(topic); - if (message != null) { - Message msg = session.createTextMessage(message); - publisher.send(msg); + } + message.acknowledge(); + } + catch (Throwable e) { + e.printStackTrace(); + } } - } catch (Exception e) { - e.printStackTrace(); - } - } + }); + conn.start(); + } + catch (Exception e) { + e.printStackTrace(); + } + } - @Test - public void tryXpathSelectorMatch() throws Exception { - String xPath = "XPATH '//books//book[@lang=''en'']'"; - listenQueue("Consumer.Sample.VirtualTopic.TestXpath", xPath); - publish("VirtualTopic.TestXpath", "ABC"); - assertTrue("topic received: ", qreceived.await(20, TimeUnit.SECONDS)); - } + public void listenTopic(final String topicName, final String selectors) { + try { + Properties props = new Properties(); + props.put("java.naming.factory.initial", "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); + props.put("java.naming.provider.url", connectionUri); + props.put("topic.topicName", topicName); - @Test - public void tryXpathSelectorNoMatch() throws Exception { - String xPath = "XPATH '//books//book[@lang=''es'']'"; - listenQueue("Consumer.Sample.VirtualTopic.TestXpath", xPath); - publish("VirtualTopic.TestXpath", "ABC"); - assertFalse("topic did not receive unmatched", qreceived.await(5, TimeUnit.SECONDS)); - } + javax.naming.Context ctx = new InitialContext(props); + TopicConnectionFactory factory = (TopicConnectionFactory) ctx.lookup("ConnectionFactory"); + TopicConnection conn = factory.createTopicConnection(); + final Topic topic = (Topic) ctx.lookup("topicName"); + TopicSession session = conn.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); + TopicSubscriber receiver = session.createSubscriber(topic, selectors, false); + + receiver.setMessageListener(new MessageListener() { + public void onMessage(Message message) { + try { + if (message instanceof TextMessage) { + TextMessage txtMsg = (TextMessage) message; + String msg = txtMsg.getText(); + LOG.info("Topic Message Received: " + topicName + " - " + msg); + } + message.acknowledge(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + }); + conn.start(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + public void publish(String topicName, String message) { + try { + Properties props = new Properties(); + props.put("java.naming.factory.initial", "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); + props.put("java.naming.provider.url", connectionUri); + props.put("topic.topicName", topicName); + javax.naming.Context ctx = new InitialContext(props); + TopicConnectionFactory factory = (TopicConnectionFactory) ctx.lookup("ConnectionFactory"); + TopicConnection conn = factory.createTopicConnection(); + Topic topic = (Topic) ctx.lookup("topicName"); + TopicSession session = conn.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); + TopicPublisher publisher = session.createPublisher(topic); + if (message != null) { + Message msg = session.createTextMessage(message); + publisher.send(msg); + } + } + catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void tryXpathSelectorMatch() throws Exception { + String xPath = "XPATH '//books//book[@lang=''en'']'"; + listenQueue("Consumer.Sample.VirtualTopic.TestXpath", xPath); + publish("VirtualTopic.TestXpath", "ABC"); + assertTrue("topic received: ", qreceived.await(20, TimeUnit.SECONDS)); + } + + @Test + public void tryXpathSelectorNoMatch() throws Exception { + String xPath = "XPATH '//books//book[@lang=''es'']'"; + listenQueue("Consumer.Sample.VirtualTopic.TestXpath", xPath); + publish("VirtualTopic.TestXpath", "ABC"); + assertFalse("topic did not receive unmatched", qreceived.await(5, TimeUnit.SECONDS)); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2103Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2103Test.java index 8a952fd699..2cb6ad09b2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2103Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2103Test.java @@ -21,7 +21,9 @@ import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; + import junit.framework.Test; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQSession; import org.apache.activemq.broker.BrokerTestSupport; @@ -34,96 +36,96 @@ import org.apache.activemq.command.ActiveMQTextMessage; import org.apache.activemq.usecases.MyObject; public class AMQ2103Test extends BrokerTestSupport { - static PolicyEntry reduceMemoryFootprint = new PolicyEntry(); - static { - reduceMemoryFootprint.setReduceMemoryFootprint(true); - } - public PolicyEntry defaultPolicy = reduceMemoryFootprint; + static PolicyEntry reduceMemoryFootprint = new PolicyEntry(); - @Override - protected PolicyEntry getDefaultPolicy() { - return defaultPolicy; - } + static { + reduceMemoryFootprint.setReduceMemoryFootprint(true); + } - public void initCombosForTestVerifyMarshalledStateIsCleared() throws Exception { - addCombinationValues("defaultPolicy", new Object[]{defaultPolicy, null}); - } + public PolicyEntry defaultPolicy = reduceMemoryFootprint; - public static Test suite() { - return suite(AMQ2103Test.class); - } + @Override + protected PolicyEntry getDefaultPolicy() { + return defaultPolicy; + } - /** - * use mem persistence so no marshaling, - * reduceMemoryFootprint on/off that will reduce memory by whacking the marshaled state - * With vm transport and deferred serialisation and no persistence (mem persistence), - * we see the message as sent by the client so we can validate the contents against - * the policy - * @throws Exception - */ - public void testVerifyMarshalledStateIsCleared() throws Exception { + public void initCombosForTestVerifyMarshalledStateIsCleared() throws Exception { + addCombinationValues("defaultPolicy", new Object[]{defaultPolicy, null}); + } - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - factory.setOptimizedMessageDispatch(true); - factory.setObjectMessageSerializationDefered(true); - factory.setCopyMessageOnSend(false); + public static Test suite() { + return suite(AMQ2103Test.class); + } - Connection connection = factory.createConnection(); - Session session = (ActiveMQSession)connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination = new ActiveMQQueue("testQ"); - MessageConsumer consumer = session.createConsumer(destination); - connection.start(); + /** + * use mem persistence so no marshaling, + * reduceMemoryFootprint on/off that will reduce memory by whacking the marshaled state + * With vm transport and deferred serialisation and no persistence (mem persistence), + * we see the message as sent by the client so we can validate the contents against + * the policy + * + * @throws Exception + */ + public void testVerifyMarshalledStateIsCleared() throws Exception { - MessageProducer producer = session.createProducer(destination); - final MyObject obj = new MyObject("A message"); - ActiveMQObjectMessage m1 = (ActiveMQObjectMessage)session.createObjectMessage(); - m1.setObject(obj); - producer.send(m1); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + factory.setOptimizedMessageDispatch(true); + factory.setObjectMessageSerializationDefered(true); + factory.setCopyMessageOnSend(false); - ActiveMQTextMessage m2 = new ActiveMQTextMessage(); - m2.setText("Test Message Payload."); - producer.send(m2); + Connection connection = factory.createConnection(); + Session session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQDestination destination = new ActiveMQQueue("testQ"); + MessageConsumer consumer = session.createConsumer(destination); + connection.start(); - ActiveMQMapMessage m3 = new ActiveMQMapMessage(); - m3.setString("text", "my message"); - producer.send(m3); + MessageProducer producer = session.createProducer(destination); + final MyObject obj = new MyObject("A message"); + ActiveMQObjectMessage m1 = (ActiveMQObjectMessage) session.createObjectMessage(); + m1.setObject(obj); + producer.send(m1); - Message m = consumer.receive(maxWait); - assertNotNull(m); - assertEquals(m1.getMessageId().toString(), m.getJMSMessageID()); - assertTrue(m instanceof ActiveMQObjectMessage); + ActiveMQTextMessage m2 = new ActiveMQTextMessage(); + m2.setText("Test Message Payload."); + producer.send(m2); - if (getDefaultPolicy() != null) { - assertNull("object data cleared by reduceMemoryFootprint (and never marshalled as using mem persistence)", - ((ActiveMQObjectMessage)m).getObject()); - } + ActiveMQMapMessage m3 = new ActiveMQMapMessage(); + m3.setString("text", "my message"); + producer.send(m3); - // verify no serialisation via vm transport - assertEquals("writeObject called", 0, obj.getWriteObjectCalled()); - assertEquals("readObject called", 0, obj.getReadObjectCalled()); - assertEquals("readObjectNoData called", 0, obj.getReadObjectNoDataCalled()); + Message m = consumer.receive(maxWait); + assertNotNull(m); + assertEquals(m1.getMessageId().toString(), m.getJMSMessageID()); + assertTrue(m instanceof ActiveMQObjectMessage); - m = consumer.receive(maxWait); - assertNotNull(m); - assertEquals(m2.getMessageId().toString(), m.getJMSMessageID()); - assertTrue(m instanceof ActiveMQTextMessage); + if (getDefaultPolicy() != null) { + assertNull("object data cleared by reduceMemoryFootprint (and never marshalled as using mem persistence)", ((ActiveMQObjectMessage) m).getObject()); + } - if (getDefaultPolicy() != null) { - assertNull("text cleared by reduceMemoryFootprint (and never marshalled as using mem persistence)", - ((ActiveMQTextMessage)m).getText()); - } + // verify no serialisation via vm transport + assertEquals("writeObject called", 0, obj.getWriteObjectCalled()); + assertEquals("readObject called", 0, obj.getReadObjectCalled()); + assertEquals("readObjectNoData called", 0, obj.getReadObjectNoDataCalled()); - m = consumer.receive(maxWait); - assertNotNull(m); - assertEquals(m3.getMessageId().toString(), m.getJMSMessageID()); - assertTrue(m instanceof ActiveMQMapMessage); + m = consumer.receive(maxWait); + assertNotNull(m); + assertEquals(m2.getMessageId().toString(), m.getJMSMessageID()); + assertTrue(m instanceof ActiveMQTextMessage); - if (getDefaultPolicy() != null) { - assertNull("text cleared by reduceMemoryFootprint (and never marshalled as using mem persistence)", - ((ActiveMQMapMessage)m).getStringProperty("text")); - } + if (getDefaultPolicy() != null) { + assertNull("text cleared by reduceMemoryFootprint (and never marshalled as using mem persistence)", ((ActiveMQTextMessage) m).getText()); + } - connection.close(); - } + m = consumer.receive(maxWait); + assertNotNull(m); + assertEquals(m3.getMessageId().toString(), m.getJMSMessageID()); + assertTrue(m instanceof ActiveMQMapMessage); + + if (getDefaultPolicy() != null) { + assertNull("text cleared by reduceMemoryFootprint (and never marshalled as using mem persistence)", ((ActiveMQMapMessage) m).getStringProperty("text")); + } + + connection.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2149LevelDBTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2149LevelDBTest.java index 1ad8b68991..8cda3ef842 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2149LevelDBTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2149LevelDBTest.java @@ -21,10 +21,10 @@ import org.apache.activemq.leveldb.LevelDBStore; public class AMQ2149LevelDBTest extends AMQ2149Test { - @Override - protected void configurePersistenceAdapter(BrokerService brokerService) throws Exception { - LevelDBStore persistenceFactory = new LevelDBStore(); - persistenceFactory.setDirectory(dataDirFile); - brokerService.setPersistenceAdapter(persistenceFactory); - } + @Override + protected void configurePersistenceAdapter(BrokerService brokerService) throws Exception { + LevelDBStore persistenceFactory = new LevelDBStore(); + persistenceFactory.setDirectory(dataDirFile); + brokerService.setPersistenceAdapter(persistenceFactory); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2149Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2149Test.java index 49903ef8f4..bc610de994 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2149Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2149Test.java @@ -54,543 +54,552 @@ import org.slf4j.LoggerFactory; import static org.junit.Assert.*; interface Configurer { - public void configure(BrokerService broker) throws Exception; + + public void configure(BrokerService broker) throws Exception; } public class AMQ2149Test { - private static final Logger LOG = LoggerFactory.getLogger(AMQ2149Test.class); - @Rule - public TestName testName = new TestName(); + private static final Logger LOG = LoggerFactory.getLogger(AMQ2149Test.class); + @Rule + public TestName testName = new TestName(); - private static final String BROKER_CONNECTOR = "tcp://localhost:61617"; - private static final String DEFAULT_BROKER_URL = "failover:("+ BROKER_CONNECTOR - +")?maxReconnectDelay=1000&useExponentialBackOff=false"; + private static final String BROKER_CONNECTOR = "tcp://localhost:61617"; + private static final String DEFAULT_BROKER_URL = "failover:(" + BROKER_CONNECTOR + ")?maxReconnectDelay=1000&useExponentialBackOff=false"; - private final String SEQ_NUM_PROPERTY = "seqNum"; + private final String SEQ_NUM_PROPERTY = "seqNum"; - final int MESSAGE_LENGTH_BYTES = 75 * 1024; - final long SLEEP_BETWEEN_SEND_MS = 25; - final int NUM_SENDERS_AND_RECEIVERS = 10; - final Object brokerLock = new Object(); + final int MESSAGE_LENGTH_BYTES = 75 * 1024; + final long SLEEP_BETWEEN_SEND_MS = 25; + final int NUM_SENDERS_AND_RECEIVERS = 10; + final Object brokerLock = new Object(); - private static final long DEFAULT_BROKER_STOP_PERIOD = 10 * 1000; - private static final long DEFAULT_NUM_TO_SEND = 1400; + private static final long DEFAULT_BROKER_STOP_PERIOD = 10 * 1000; + private static final long DEFAULT_NUM_TO_SEND = 1400; - long brokerStopPeriod = DEFAULT_BROKER_STOP_PERIOD; - long numtoSend = DEFAULT_NUM_TO_SEND; - long sleepBetweenSend = SLEEP_BETWEEN_SEND_MS; - String brokerURL = DEFAULT_BROKER_URL; + long brokerStopPeriod = DEFAULT_BROKER_STOP_PERIOD; + long numtoSend = DEFAULT_NUM_TO_SEND; + long sleepBetweenSend = SLEEP_BETWEEN_SEND_MS; + String brokerURL = DEFAULT_BROKER_URL; - int numBrokerRestarts = 0; - final static int MAX_BROKER_RESTARTS = 4; - BrokerService broker; - Vector exceptions = new Vector(); + int numBrokerRestarts = 0; + final static int MAX_BROKER_RESTARTS = 4; + BrokerService broker; + Vector exceptions = new Vector(); - protected File dataDirFile; - final LoggingBrokerPlugin[] plugins = new LoggingBrokerPlugin[]{new LoggingBrokerPlugin()}; + protected File dataDirFile; + final LoggingBrokerPlugin[] plugins = new LoggingBrokerPlugin[]{new LoggingBrokerPlugin()}; + public void createBroker(Configurer configurer) throws Exception { + broker = new BrokerService(); + configurePersistenceAdapter(broker); - public void createBroker(Configurer configurer) throws Exception { - broker = new BrokerService(); - configurePersistenceAdapter(broker); + broker.getSystemUsage().getMemoryUsage().setLimit(MESSAGE_LENGTH_BYTES * 200 * NUM_SENDERS_AND_RECEIVERS); - broker.getSystemUsage().getMemoryUsage().setLimit(MESSAGE_LENGTH_BYTES * 200 * NUM_SENDERS_AND_RECEIVERS); + broker.addConnector(BROKER_CONNECTOR); + broker.setBrokerName(testName.getMethodName()); + broker.setDataDirectoryFile(dataDirFile); + if (configurer != null) { + configurer.configure(broker); + } + broker.start(); + } - broker.addConnector(BROKER_CONNECTOR); - broker.setBrokerName(testName.getMethodName()); - broker.setDataDirectoryFile(dataDirFile); - if (configurer != null) { - configurer.configure(broker); - } - broker.start(); - } + protected void configurePersistenceAdapter(BrokerService brokerService) throws Exception { + } - protected void configurePersistenceAdapter(BrokerService brokerService) throws Exception { - } + @Before + public void setUp() throws Exception { + LOG.debug("Starting test {}", testName.getMethodName()); + dataDirFile = new File("target/" + testName.getMethodName()); + numtoSend = DEFAULT_NUM_TO_SEND; + brokerStopPeriod = DEFAULT_BROKER_STOP_PERIOD; + sleepBetweenSend = SLEEP_BETWEEN_SEND_MS; + brokerURL = DEFAULT_BROKER_URL; + } - @Before - public void setUp() throws Exception { - LOG.debug("Starting test {}", testName.getMethodName()); - dataDirFile = new File("target/"+ testName.getMethodName()); - numtoSend = DEFAULT_NUM_TO_SEND; - brokerStopPeriod = DEFAULT_BROKER_STOP_PERIOD; - sleepBetweenSend = SLEEP_BETWEEN_SEND_MS; - brokerURL = DEFAULT_BROKER_URL; - } + @After + public void tearDown() throws Exception { + ExecutorService executor = Executors.newSingleThreadExecutor(); + Future future = executor.submit(new TeardownTask(brokerLock, broker)); + try { + LOG.debug("Teardown started."); + long start = System.currentTimeMillis(); + Boolean result = future.get(30, TimeUnit.SECONDS); + long finish = System.currentTimeMillis(); + LOG.debug("Result of teardown: {} after {} ms ", result, (finish - start)); + } + catch (TimeoutException e) { + fail("Teardown timed out"); + AutoFailTestSupport.dumpAllThreads(testName.getMethodName()); + } + executor.shutdownNow(); + exceptions.clear(); + } - @After - public void tearDown() throws Exception { - ExecutorService executor = Executors.newSingleThreadExecutor(); - Future future = executor.submit(new TeardownTask(brokerLock, broker)); - try { - LOG.debug("Teardown started."); - long start = System.currentTimeMillis(); - Boolean result = future.get(30, TimeUnit.SECONDS); - long finish = System.currentTimeMillis(); - LOG.debug("Result of teardown: {} after {} ms ", result, (finish - start)); - } catch (TimeoutException e) { - fail("Teardown timed out"); - AutoFailTestSupport.dumpAllThreads(testName.getMethodName()); - } - executor.shutdownNow(); - exceptions.clear(); - } + private String buildLongString() { + final StringBuilder stringBuilder = new StringBuilder(MESSAGE_LENGTH_BYTES); + for (int i = 0; i < MESSAGE_LENGTH_BYTES; ++i) { + stringBuilder.append((int) (Math.random() * 10)); + } + return stringBuilder.toString(); + } - private String buildLongString() { - final StringBuilder stringBuilder = new StringBuilder( - MESSAGE_LENGTH_BYTES); - for (int i = 0; i < MESSAGE_LENGTH_BYTES; ++i) { - stringBuilder.append((int) (Math.random() * 10)); - } - return stringBuilder.toString(); - } + HashSet connections = new HashSet(); - HashSet connections = new HashSet(); - private class Receiver implements MessageListener { + private class Receiver implements MessageListener { - private final javax.jms.Destination dest; + private final javax.jms.Destination dest; - private final Connection connection; + private final Connection connection; - private final Session session; + private final Session session; - private final MessageConsumer messageConsumer; + private final MessageConsumer messageConsumer; - private AtomicLong nextExpectedSeqNum = new AtomicLong(); + private AtomicLong nextExpectedSeqNum = new AtomicLong(); - private final boolean transactional; + private final boolean transactional; - private String lastId = null; + private String lastId = null; - public Receiver(javax.jms.Destination dest, boolean transactional) throws JMSException { - this.dest = dest; - this.transactional = transactional; - connection = new ActiveMQConnectionFactory(brokerURL) - .createConnection(); - connection.setClientID(dest.toString()); - session = connection.createSession(transactional, transactional ? Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE); - if (ActiveMQDestination.transform(dest).isTopic()) { - messageConsumer = session.createDurableSubscriber((Topic) dest, dest.toString()); - } else { - messageConsumer = session.createConsumer(dest); + public Receiver(javax.jms.Destination dest, boolean transactional) throws JMSException { + this.dest = dest; + this.transactional = transactional; + connection = new ActiveMQConnectionFactory(brokerURL).createConnection(); + connection.setClientID(dest.toString()); + session = connection.createSession(transactional, transactional ? Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE); + if (ActiveMQDestination.transform(dest).isTopic()) { + messageConsumer = session.createDurableSubscriber((Topic) dest, dest.toString()); + } + else { + messageConsumer = session.createConsumer(dest); + } + messageConsumer.setMessageListener(this); + connection.start(); + connections.add(connection); + } + + public void close() throws JMSException { + connection.close(); + } + + public long getNextExpectedSeqNo() { + return nextExpectedSeqNum.get(); + } + + final int TRANSACITON_BATCH = 500; + boolean resumeOnNextOrPreviousIsOk = false; + + public void onMessage(Message message) { + try { + final long seqNum = message.getLongProperty(SEQ_NUM_PROPERTY); + if ((seqNum % TRANSACITON_BATCH) == 0) { + LOG.info(dest + " received " + seqNum); + + if (transactional) { + LOG.info("committing.."); + session.commit(); + } + } + if (resumeOnNextOrPreviousIsOk) { + // after an indoubt commit we need to accept what we get (within reason) + if (seqNum != nextExpectedSeqNum.get()) { + final long l = nextExpectedSeqNum.get(); + if (seqNum == l - (TRANSACITON_BATCH - 1)) { + nextExpectedSeqNum.compareAndSet(l, l - (TRANSACITON_BATCH - 1)); + LOG.info("In doubt commit failed, getting replay at:" + nextExpectedSeqNum); + } + } + resumeOnNextOrPreviousIsOk = false; + } + if (seqNum != nextExpectedSeqNum.get()) { + LOG.warn(dest + " received " + seqNum + " in msg: " + message.getJMSMessageID() + " expected " + nextExpectedSeqNum + ", lastId: " + lastId + ", message:" + message); + fail(dest + " received " + seqNum + " expected " + nextExpectedSeqNum); + } + nextExpectedSeqNum.incrementAndGet(); + lastId = message.getJMSMessageID(); + } + catch (TransactionRolledBackException expectedSometimesOnFailoverRecovery) { + LOG.info("got rollback: " + expectedSometimesOnFailoverRecovery); + if (expectedSometimesOnFailoverRecovery.getMessage().contains("completion in doubt")) { + // in doubt - either commit command or reply missing + // don't know if we will get a replay + resumeOnNextOrPreviousIsOk = true; + nextExpectedSeqNum.incrementAndGet(); + LOG.info("in doubt transaction completion: ok to get next or previous batch. next:" + nextExpectedSeqNum); + } + else { + resumeOnNextOrPreviousIsOk = false; + // batch will be replayed + nextExpectedSeqNum.addAndGet(-(TRANSACITON_BATCH - 1)); } - messageConsumer.setMessageListener(this); - connection.start(); - connections.add(connection); - } - public void close() throws JMSException { + } + catch (Throwable e) { + LOG.error(dest + " onMessage error", e); + exceptions.add(e); + } + } + + } + + private class Sender implements Runnable { + + private final javax.jms.Destination dest; + + private final Connection connection; + + private final Session session; + + private final MessageProducer messageProducer; + + private volatile long nextSequenceNumber = 0; + private final Object guard = new Object(); + + public Sender(javax.jms.Destination dest) throws JMSException { + this.dest = dest; + connection = new ActiveMQConnectionFactory(brokerURL).createConnection(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + messageProducer = session.createProducer(dest); + messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT); + connection.start(); + connections.add(connection); + } + + public void run() { + final String longString = buildLongString(); + long nextSequenceNumber = this.nextSequenceNumber; + while (nextSequenceNumber < numtoSend) { + try { + final Message message = session.createTextMessage(longString); + message.setLongProperty(SEQ_NUM_PROPERTY, nextSequenceNumber); + synchronized (guard) { + if (nextSequenceNumber == this.nextSequenceNumber) { + this.nextSequenceNumber = nextSequenceNumber + 1; + messageProducer.send(message); + } + else { + continue; + } + } + + if ((nextSequenceNumber % 500) == 0) { + LOG.info(dest + " sent " + nextSequenceNumber); + } + + } + catch (javax.jms.IllegalStateException e) { + LOG.error(dest + " bailing on send error", e); + exceptions.add(e); + break; + } + catch (Exception e) { + LOG.error(dest + " send error", e); + exceptions.add(e); + } + if (sleepBetweenSend > 0) { + try { + Thread.sleep(sleepBetweenSend); + } + catch (InterruptedException e) { + LOG.warn(dest + " sleep interrupted", e); + } + } + } + try { connection.close(); - } + } + catch (JMSException ignored) { + } + } + } - public long getNextExpectedSeqNo() { - return nextExpectedSeqNum.get(); - } + // attempt to simply replicate leveldb failure. no joy yet + public void x_testRestartReReceive() throws Exception { + createBroker(new Configurer() { + public void configure(BrokerService broker) throws Exception { + broker.deleteAllMessages(); + } + }); - final int TRANSACITON_BATCH = 500; - boolean resumeOnNextOrPreviousIsOk = false; - public void onMessage(Message message) { - try { - final long seqNum = message.getLongProperty(SEQ_NUM_PROPERTY); - if ((seqNum % TRANSACITON_BATCH) == 0) { - LOG.info(dest + " received " + seqNum); + final javax.jms.Destination destination = ActiveMQDestination.createDestination("test.dest.X", ActiveMQDestination.QUEUE_TYPE); + Thread thread = new Thread(new Sender(destination)); + thread.start(); + thread.join(); - if (transactional) { - LOG.info("committing.."); - session.commit(); - } - } - if (resumeOnNextOrPreviousIsOk) { - // after an indoubt commit we need to accept what we get (within reason) - if (seqNum != nextExpectedSeqNum.get()) { - final long l = nextExpectedSeqNum.get(); - if (seqNum == l - (TRANSACITON_BATCH -1)) { - nextExpectedSeqNum.compareAndSet(l, l - (TRANSACITON_BATCH -1) ); - LOG.info("In doubt commit failed, getting replay at:" + nextExpectedSeqNum); - } - } - resumeOnNextOrPreviousIsOk = false; - } - if (seqNum != nextExpectedSeqNum.get()) { - LOG.warn(dest + " received " + seqNum - + " in msg: " + message.getJMSMessageID() - + " expected " - + nextExpectedSeqNum - + ", lastId: " + lastId - + ", message:" + message); - fail(dest + " received " + seqNum + " expected " - + nextExpectedSeqNum); - } - nextExpectedSeqNum.incrementAndGet(); - lastId = message.getJMSMessageID(); - } catch (TransactionRolledBackException expectedSometimesOnFailoverRecovery) { - LOG.info("got rollback: " + expectedSometimesOnFailoverRecovery); - if (expectedSometimesOnFailoverRecovery.getMessage().contains("completion in doubt")) { - // in doubt - either commit command or reply missing - // don't know if we will get a replay - resumeOnNextOrPreviousIsOk = true; - nextExpectedSeqNum.incrementAndGet(); - LOG.info("in doubt transaction completion: ok to get next or previous batch. next:" + nextExpectedSeqNum); - } else { - resumeOnNextOrPreviousIsOk = false; - // batch will be replayed - nextExpectedSeqNum.addAndGet(-(TRANSACITON_BATCH - 1)); - } + Connection connection = new ActiveMQConnectionFactory(brokerURL).createConnection(); + connection.setClientID(destination.toString()); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageConsumer messageConsumer = session.createConsumer(destination); + connection.start(); - } catch (Throwable e) { - LOG.error(dest + " onMessage error", e); - exceptions.add(e); + int batch = 200; + long expectedSeq; + + final TimerTask restartTask = scheduleRestartTask(null, new Configurer() { + public void configure(BrokerService broker) throws Exception { + } + }); + + expectedSeq = 0; + for (int s = 0; s < 4; s++) { + for (int i = 0; i < batch; i++) { + Message message = messageConsumer.receive(20000); + assertNotNull("s:" + s + ", i:" + i, message); + final long seqNum = message.getLongProperty(SEQ_NUM_PROPERTY); + assertEquals("expected order s:" + s, expectedSeq++, seqNum); + + if (i > 0 && i % 600 == 0) { + LOG.info("Commit on %5"); + // session.commit(); } - } + } + restartTask.run(); + } - } + } - private class Sender implements Runnable { + // no need to run this unless there are some issues with the others + public void vanilaVerify_testOrder() throws Exception { - private final javax.jms.Destination dest; + createBroker(new Configurer() { + public void configure(BrokerService broker) throws Exception { + broker.deleteAllMessages(); + } + }); - private final Connection connection; + verifyOrderedMessageReceipt(); + verifyStats(false); + } - private final Session session; + @Test(timeout = 5 * 60 * 1000) + public void testOrderWithRestart() throws Exception { + createBroker(new Configurer() { + public void configure(BrokerService broker) throws Exception { + broker.deleteAllMessages(); + } + }); - private final MessageProducer messageProducer; + final Timer timer = new Timer(); + scheduleRestartTask(timer, new Configurer() { + public void configure(BrokerService broker) throws Exception { + } + }); - private volatile long nextSequenceNumber = 0; - private final Object guard = new Object(); + try { + verifyOrderedMessageReceipt(); + } + finally { + timer.cancel(); + } - public Sender(javax.jms.Destination dest) throws JMSException { - this.dest = dest; - connection = new ActiveMQConnectionFactory(brokerURL) - .createConnection(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - messageProducer = session.createProducer(dest); - messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT); - connection.start(); - connections.add(connection); - } + verifyStats(true); + } - public void run() { - final String longString = buildLongString(); - long nextSequenceNumber = this.nextSequenceNumber; - while (nextSequenceNumber < numtoSend) { - try { - final Message message = session - .createTextMessage(longString); - message.setLongProperty(SEQ_NUM_PROPERTY, - nextSequenceNumber); - synchronized (guard) - { - if (nextSequenceNumber == this.nextSequenceNumber) - { - this.nextSequenceNumber = nextSequenceNumber + 1; - messageProducer.send(message); - } else { - continue; - } - } + @Test(timeout = 5 * 60 * 1000) + public void testTopicOrderWithRestart() throws Exception { + createBroker(new Configurer() { + public void configure(BrokerService broker) throws Exception { + broker.deleteAllMessages(); + } + }); - if ((nextSequenceNumber % 500) == 0) { - LOG.info(dest + " sent " + nextSequenceNumber); - } + final Timer timer = new Timer(); + scheduleRestartTask(timer, null); - } catch (javax.jms.IllegalStateException e) { - LOG.error(dest + " bailing on send error", e); - exceptions.add(e); - break; - } catch (Exception e) { - LOG.error(dest + " send error", e); - exceptions.add(e); - } - if (sleepBetweenSend > 0) { - try { - Thread.sleep(sleepBetweenSend); - } catch (InterruptedException e) { - LOG.warn(dest + " sleep interrupted", e); - } - } + try { + verifyOrderedMessageReceipt(ActiveMQDestination.TOPIC_TYPE); + } + finally { + timer.cancel(); + } + + verifyStats(true); + } + + @Test(timeout = 5 * 60 * 1000) + public void testQueueTransactionalOrderWithRestart() throws Exception { + doTestTransactionalOrderWithRestart(ActiveMQDestination.QUEUE_TYPE); + } + + @Test(timeout = 5 * 60 * 1000) + public void testTopicTransactionalOrderWithRestart() throws Exception { + doTestTransactionalOrderWithRestart(ActiveMQDestination.TOPIC_TYPE); + } + + public void doTestTransactionalOrderWithRestart(byte destinationType) throws Exception { + numtoSend = 10000; + sleepBetweenSend = 3; + brokerStopPeriod = 10 * 1000; + + createBroker(new Configurer() { + public void configure(BrokerService broker) throws Exception { + broker.deleteAllMessages(); + } + }); + + final Timer timer = new Timer(); + scheduleRestartTask(timer, null); + + try { + verifyOrderedMessageReceipt(destinationType, 1, true); + } + finally { + timer.cancel(); + } + + verifyStats(true); + } + + private void verifyStats(boolean brokerRestarts) throws Exception { + RegionBroker regionBroker = (RegionBroker) broker.getRegionBroker(); + + for (Destination dest : regionBroker.getQueueRegion().getDestinationMap().values()) { + DestinationStatistics stats = dest.getDestinationStatistics(); + if (brokerRestarts) { + // all bets are off w.r.t stats as there may be duplicate sends and duplicate + // dispatches, all of which will be suppressed - either by the reference store + // not allowing duplicate references or consumers acking duplicates + LOG.info("with restart: not asserting qneue/dequeue stat match for: " + dest.getName() + " " + stats.getEnqueues().getCount() + " <= " + stats.getDequeues().getCount()); + } + else { + assertEquals("qneue/dequeue match for: " + dest.getName(), stats.getEnqueues().getCount(), stats.getDequeues().getCount()); + } + } + } + + private TimerTask scheduleRestartTask(final Timer timer, final Configurer configurer) { + class RestartTask extends TimerTask { + + public void run() { + synchronized (brokerLock) { + LOG.info("stopping broker.."); + try { + broker.stop(); + broker.waitUntilStopped(); + } + catch (Exception e) { + LOG.error("ex on broker stop", e); + exceptions.add(e); + } + LOG.info("restarting broker"); + try { + createBroker(configurer); + broker.waitUntilStarted(); + } + catch (Exception e) { + LOG.error("ex on broker restart", e); + exceptions.add(e); + } } - try { - connection.close(); - } catch (JMSException ignored) { + if (++numBrokerRestarts < MAX_BROKER_RESTARTS && timer != null) { + // do it again + try { + timer.schedule(new RestartTask(), brokerStopPeriod); + } + catch (IllegalStateException ignore_alreadyCancelled) { + } } - } - } - - // attempt to simply replicate leveldb failure. no joy yet - public void x_testRestartReReceive() throws Exception { - createBroker(new Configurer() { - public void configure(BrokerService broker) throws Exception { - broker.deleteAllMessages(); + else { + LOG.info("no longer stopping broker on reaching Max restarts: " + MAX_BROKER_RESTARTS); } - }); + } + } + RestartTask task = new RestartTask(); + if (timer != null) { + timer.schedule(task, brokerStopPeriod); + } + return task; + } - final javax.jms.Destination destination = - ActiveMQDestination.createDestination("test.dest.X", ActiveMQDestination.QUEUE_TYPE); - Thread thread = new Thread(new Sender(destination)); - thread.start(); - thread.join(); + private void verifyOrderedMessageReceipt(byte destinationType) throws Exception { + verifyOrderedMessageReceipt(destinationType, NUM_SENDERS_AND_RECEIVERS, false); + } - Connection connection = new ActiveMQConnectionFactory(brokerURL).createConnection(); - connection.setClientID(destination.toString()); - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageConsumer messageConsumer = session.createConsumer(destination); - connection.start(); + private void verifyOrderedMessageReceipt() throws Exception { + verifyOrderedMessageReceipt(ActiveMQDestination.QUEUE_TYPE, NUM_SENDERS_AND_RECEIVERS, false); + } - int batch = 200; - long expectedSeq; + private void verifyOrderedMessageReceipt(byte destinationType, + int concurrentPairs, + boolean transactional) throws Exception { - final TimerTask restartTask = scheduleRestartTask(null, new Configurer() { - public void configure(BrokerService broker) throws Exception { - } - }); + Vector threads = new Vector(); + Vector receivers = new Vector(); - expectedSeq = 0; - for (int s = 0; s < 4; s++) { - for (int i = 0; i < batch; i++) { - Message message = messageConsumer.receive(20000); - assertNotNull("s:" + s + ", i:" + i, message); - final long seqNum = message.getLongProperty(SEQ_NUM_PROPERTY); - assertEquals("expected order s:" + s, expectedSeq++, seqNum); + for (int i = 0; i < concurrentPairs; ++i) { + final javax.jms.Destination destination = ActiveMQDestination.createDestination("test.dest." + i, destinationType); + receivers.add(new Receiver(destination, transactional)); + Thread thread = new Thread(new Sender(destination)); + thread.start(); + threads.add(thread); + } - if (i > 0 && i%600 == 0) { - LOG.info("Commit on %5"); - // session.commit(); - } - } - restartTask.run(); - } + final long expiry = System.currentTimeMillis() + 1000 * 60 * 4; + while (!threads.isEmpty() && exceptions.isEmpty() && System.currentTimeMillis() < expiry) { + Thread sendThread = threads.firstElement(); + sendThread.join(1000 * 30); + if (!sendThread.isAlive()) { + threads.remove(sendThread); + } + else { + AutoFailTestSupport.dumpAllThreads("Send blocked"); + } + } + LOG.info("senders done..." + threads); - } + while (!receivers.isEmpty() && System.currentTimeMillis() < expiry) { + Receiver receiver = receivers.firstElement(); + if (receiver.getNextExpectedSeqNo() >= numtoSend || !exceptions.isEmpty()) { + receiver.close(); + receivers.remove(receiver); + } + } - // no need to run this unless there are some issues with the others - public void vanilaVerify_testOrder() throws Exception { + for (Connection connection : connections) { + try { + connection.close(); + } + catch (Exception ignored) { + } + } + connections.clear(); - createBroker(new Configurer() { - public void configure(BrokerService broker) throws Exception { - broker.deleteAllMessages(); - } - }); + assertTrue("No timeout waiting for senders/receivers to complete", System.currentTimeMillis() < expiry); + if (!exceptions.isEmpty()) { + exceptions.get(0).printStackTrace(); + } - verifyOrderedMessageReceipt(); - verifyStats(false); - } + LOG.info("Dangling threads: " + threads); + for (Thread dangling : threads) { + dangling.interrupt(); + dangling.join(10 * 1000); + } - @Test(timeout = 5 * 60 * 1000) - public void testOrderWithRestart() throws Exception { - createBroker(new Configurer() { - public void configure(BrokerService broker) throws Exception { - broker.deleteAllMessages(); - } - }); - - final Timer timer = new Timer(); - scheduleRestartTask(timer, new Configurer() { - public void configure(BrokerService broker) throws Exception { - } - }); - - try { - verifyOrderedMessageReceipt(); - } finally { - timer.cancel(); - } - - verifyStats(true); - } - - @Test(timeout = 5 * 60 * 1000) - public void testTopicOrderWithRestart() throws Exception { - createBroker(new Configurer() { - public void configure(BrokerService broker) throws Exception { - broker.deleteAllMessages(); - } - }); - - final Timer timer = new Timer(); - scheduleRestartTask(timer, null); - - try { - verifyOrderedMessageReceipt(ActiveMQDestination.TOPIC_TYPE); - } finally { - timer.cancel(); - } - - verifyStats(true); - } - - @Test(timeout = 5 * 60 * 1000) - public void testQueueTransactionalOrderWithRestart() throws Exception { - doTestTransactionalOrderWithRestart(ActiveMQDestination.QUEUE_TYPE); - } - - @Test(timeout = 5 * 60 * 1000) - public void testTopicTransactionalOrderWithRestart() throws Exception { - doTestTransactionalOrderWithRestart(ActiveMQDestination.TOPIC_TYPE); - } - - public void doTestTransactionalOrderWithRestart(byte destinationType) throws Exception { - numtoSend = 10000; - sleepBetweenSend = 3; - brokerStopPeriod = 10 * 1000; - - createBroker(new Configurer() { - public void configure(BrokerService broker) throws Exception { - broker.deleteAllMessages(); - } - }); - - final Timer timer = new Timer(); - scheduleRestartTask(timer, null); - - try { - verifyOrderedMessageReceipt(destinationType, 1, true); - } finally { - timer.cancel(); - } - - verifyStats(true); - } - - private void verifyStats(boolean brokerRestarts) throws Exception { - RegionBroker regionBroker = (RegionBroker) broker.getRegionBroker(); - - for (Destination dest : regionBroker.getQueueRegion().getDestinationMap().values()) { - DestinationStatistics stats = dest.getDestinationStatistics(); - if (brokerRestarts) { - // all bets are off w.r.t stats as there may be duplicate sends and duplicate - // dispatches, all of which will be suppressed - either by the reference store - // not allowing duplicate references or consumers acking duplicates - LOG.info("with restart: not asserting qneue/dequeue stat match for: " + dest.getName() - + " " + stats.getEnqueues().getCount() + " <= " +stats.getDequeues().getCount()); - } else { - assertEquals("qneue/dequeue match for: " + dest.getName(), - stats.getEnqueues().getCount(), stats.getDequeues().getCount()); - } - } - } - - private TimerTask scheduleRestartTask(final Timer timer, final Configurer configurer) { - class RestartTask extends TimerTask { - public void run() { - synchronized (brokerLock) { - LOG.info("stopping broker.."); - try { - broker.stop(); - broker.waitUntilStopped(); - } catch (Exception e) { - LOG.error("ex on broker stop", e); - exceptions.add(e); - } - LOG.info("restarting broker"); - try { - createBroker(configurer); - broker.waitUntilStarted(); - } catch (Exception e) { - LOG.error("ex on broker restart", e); - exceptions.add(e); - } - } - if (++numBrokerRestarts < MAX_BROKER_RESTARTS && timer != null) { - // do it again - try { - timer.schedule(new RestartTask(), brokerStopPeriod); - } catch (IllegalStateException ignore_alreadyCancelled) { - } - } else { - LOG.info("no longer stopping broker on reaching Max restarts: " + MAX_BROKER_RESTARTS); - } - } - } - RestartTask task = new RestartTask(); - if (timer != null) { - timer.schedule(task, brokerStopPeriod); - } - return task; - } - - private void verifyOrderedMessageReceipt(byte destinationType) throws Exception { - verifyOrderedMessageReceipt(destinationType, NUM_SENDERS_AND_RECEIVERS, false); - } - - private void verifyOrderedMessageReceipt() throws Exception { - verifyOrderedMessageReceipt(ActiveMQDestination.QUEUE_TYPE, NUM_SENDERS_AND_RECEIVERS, false); - } - - private void verifyOrderedMessageReceipt(byte destinationType, int concurrentPairs, boolean transactional) throws Exception { - - Vector threads = new Vector(); - Vector receivers = new Vector(); - - for (int i = 0; i < concurrentPairs; ++i) { - final javax.jms.Destination destination = - ActiveMQDestination.createDestination("test.dest." + i, destinationType); - receivers.add(new Receiver(destination, transactional)); - Thread thread = new Thread(new Sender(destination)); - thread.start(); - threads.add(thread); - } - - final long expiry = System.currentTimeMillis() + 1000 * 60 * 4; - while(!threads.isEmpty() && exceptions.isEmpty() && System.currentTimeMillis() < expiry) { - Thread sendThread = threads.firstElement(); - sendThread.join(1000*30); - if (!sendThread.isAlive()) { - threads.remove(sendThread); - } else { - AutoFailTestSupport.dumpAllThreads("Send blocked"); - } - } - LOG.info("senders done..." + threads); - - while(!receivers.isEmpty() && System.currentTimeMillis() < expiry) { - Receiver receiver = receivers.firstElement(); - if (receiver.getNextExpectedSeqNo() >= numtoSend || !exceptions.isEmpty()) { - receiver.close(); - receivers.remove(receiver); - } - } - - for (Connection connection : connections) { - try { - connection.close(); - } catch (Exception ignored) {} - } - connections.clear(); - - assertTrue("No timeout waiting for senders/receivers to complete", System.currentTimeMillis() < expiry); - if (!exceptions.isEmpty()) { - exceptions.get(0).printStackTrace(); - } - - LOG.info("Dangling threads: " + threads); - for (Thread dangling : threads) { - dangling.interrupt(); - dangling.join(10*1000); - } - - assertTrue("No exceptions", exceptions.isEmpty()); - } + assertTrue("No exceptions", exceptions.isEmpty()); + } } class TeardownTask implements Callable { - private final Object brokerLock; - private BrokerService broker; - public TeardownTask(Object brokerLock, BrokerService broker) { - this.brokerLock = brokerLock; - this.broker = broker; - } + private final Object brokerLock; + private BrokerService broker; - @Override - public Boolean call() throws Exception { - synchronized(brokerLock) { - if (broker!= null) { - broker.stop(); - broker.waitUntilStopped(); - } - } - return Boolean.TRUE; - } + public TeardownTask(Object brokerLock, BrokerService broker) { + this.brokerLock = brokerLock; + this.broker = broker; + } + + @Override + public Boolean call() throws Exception { + synchronized (brokerLock) { + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + } + return Boolean.TRUE; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2171Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2171Test.java index f23f758916..80dd0134c7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2171Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2171Test.java @@ -34,113 +34,117 @@ import static org.junit.Assert.*; public class AMQ2171Test implements Thread.UncaughtExceptionHandler { - private static final Logger LOG = LoggerFactory.getLogger(AMQ2171Test.class); - private static final String BROKER_URL = "tcp://localhost:0"; - private static final int QUEUE_SIZE = 100; + private static final Logger LOG = LoggerFactory.getLogger(AMQ2171Test.class); + private static final String BROKER_URL = "tcp://localhost:0"; + private static final int QUEUE_SIZE = 100; - private static BrokerService brokerService; - private static Queue destination; + private static BrokerService brokerService; + private static Queue destination; - private String brokerUri; - private String brokerUriNoPrefetch; - private Collection exceptions = new CopyOnWriteArrayList(); + private String brokerUri; + private String brokerUriNoPrefetch; + private Collection exceptions = new CopyOnWriteArrayList(); - @Before - public void setUp() throws Exception { - // Start an embedded broker up. - brokerService = new BrokerService(); - brokerService.setDeleteAllMessagesOnStartup(true); - brokerService.addConnector(BROKER_URL); - brokerService.start(); + @Before + public void setUp() throws Exception { + // Start an embedded broker up. + brokerService = new BrokerService(); + brokerService.setDeleteAllMessagesOnStartup(true); + brokerService.addConnector(BROKER_URL); + brokerService.start(); - brokerUri = brokerService.getTransportConnectors().get(0).getPublishableConnectString().toString(); - brokerUriNoPrefetch = brokerUri + "?jms.prefetchPolicy.all=0"; + brokerUri = brokerService.getTransportConnectors().get(0).getPublishableConnectString().toString(); + brokerUriNoPrefetch = brokerUri + "?jms.prefetchPolicy.all=0"; - destination = new ActiveMQQueue("Test"); - produce(brokerUri, QUEUE_SIZE); - } + destination = new ActiveMQQueue("Test"); + produce(brokerUri, QUEUE_SIZE); + } - @Before - public void addHandler() { - Thread.setDefaultUncaughtExceptionHandler(this); - } + @Before + public void addHandler() { + Thread.setDefaultUncaughtExceptionHandler(this); + } - @After - public void tearDown() throws Exception { - brokerService.stop(); - } + @After + public void tearDown() throws Exception { + brokerService.stop(); + } - @Test(timeout = 10000) - public void testBrowsePrefetch() throws Exception { - runTest(brokerUri); - } + @Test(timeout = 10000) + public void testBrowsePrefetch() throws Exception { + runTest(brokerUri); + } - @Test(timeout = 10000) - public void testBrowseNoPrefetch() throws Exception { - runTest(brokerUriNoPrefetch); - } + @Test(timeout = 10000) + public void testBrowseNoPrefetch() throws Exception { + runTest(brokerUriNoPrefetch); + } - private void runTest(String brokerURL) throws Exception { + private void runTest(String brokerURL) throws Exception { - Connection connection = new ActiveMQConnectionFactory(brokerURL).createConnection(); + Connection connection = new ActiveMQConnectionFactory(brokerURL).createConnection(); - try { - connection.start(); + try { + connection.start(); - Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE); - @SuppressWarnings("unchecked") - Enumeration unread = (Enumeration) session.createBrowser(destination).getEnumeration(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + @SuppressWarnings("unchecked") + Enumeration unread = (Enumeration) session.createBrowser(destination).getEnumeration(); - int count = 0; - while (unread.hasMoreElements()) { - unread.nextElement(); - count++; + int count = 0; + while (unread.hasMoreElements()) { + unread.nextElement(); + count++; + } + + assertEquals(QUEUE_SIZE, count); + assertTrue(exceptions.isEmpty()); + } + finally { + try { + connection.close(); + } + catch (JMSException e) { + exceptions.add(e); + } + } + } + + private static void produce(String brokerURL, int count) throws Exception { + Connection connection = null; + + try { + + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURL); + connection = factory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + producer.setTimeToLive(0); + connection.start(); + + for (int i = 0; i < count; i++) { + int id = i + 1; + TextMessage message = session.createTextMessage("Message " + id); + message.setIntProperty("MsgNumber", id); + producer.send(message); + + if (id % 500 == 0) { + LOG.info("sent " + id + ", ith " + message); } - - assertEquals(QUEUE_SIZE, count); - assertTrue(exceptions.isEmpty()); - } finally { - try { - connection.close(); - } catch (JMSException e) { - exceptions.add(e); + } + } + finally { + try { + if (connection != null) { + connection.close(); } - } - } + } + catch (Throwable e) { + } + } + } - private static void produce(String brokerURL, int count) throws Exception { - Connection connection = null; - - try { - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURL); - connection = factory.createConnection(); - Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - producer.setTimeToLive(0); - connection.start(); - - for (int i = 0; i < count; i++) { - int id = i + 1; - TextMessage message = session.createTextMessage("Message " + id); - message.setIntProperty("MsgNumber", id); - producer.send(message); - - if (id % 500 == 0) { - LOG.info("sent " + id + ", ith " + message); - } - } - } finally { - try { - if (connection != null) { - connection.close(); - } - } catch (Throwable e) { - } - } - } - - public void uncaughtException(Thread t, Throwable e) { - exceptions.add(e); - } + public void uncaughtException(Thread t, Throwable e) { + exceptions.add(e); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2200Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2200Test.java index 0903e56fad..d6b4aaa37e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2200Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2200Test.java @@ -17,6 +17,7 @@ package org.apache.activemq.bugs; import static org.junit.Assert.*; + import java.io.File; import java.util.concurrent.TimeUnit; @@ -36,65 +37,64 @@ import org.junit.Test; public class AMQ2200Test { - private static final String bindAddress = "tcp://0.0.0.0:0"; - private BrokerService broker; - private ActiveMQConnectionFactory cf; + private static final String bindAddress = "tcp://0.0.0.0:0"; + private BrokerService broker; + private ActiveMQConnectionFactory cf; - @Before - public void setUp() throws Exception { - broker = new BrokerService(); - broker.setDataDirectory("target" + File.separator + "activemq-data"); - broker.setPersistent(true); - broker.setUseJmx(true); - broker.setAdvisorySupport(false); - broker.setDeleteAllMessagesOnStartup(true); - broker.addConnector(bindAddress); - String address = broker.getTransportConnectors().get(0).getPublishableConnectString(); - broker.start(); - broker.waitUntilStarted(); + @Before + public void setUp() throws Exception { + broker = new BrokerService(); + broker.setDataDirectory("target" + File.separator + "activemq-data"); + broker.setPersistent(true); + broker.setUseJmx(true); + broker.setAdvisorySupport(false); + broker.setDeleteAllMessagesOnStartup(true); + broker.addConnector(bindAddress); + String address = broker.getTransportConnectors().get(0).getPublishableConnectString(); + broker.start(); + broker.waitUntilStarted(); - cf = new ActiveMQConnectionFactory(address); - } + cf = new ActiveMQConnectionFactory(address); + } - @After - public void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - } + @After + public void tearDown() throws Exception { + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + } - @Test - public void testTopicSubscriptionView() throws Exception { - TopicConnection connection = cf.createTopicConnection(); - TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); + @Test + public void testTopicSubscriptionView() throws Exception { + TopicConnection connection = cf.createTopicConnection(); + TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - Topic destination = session.createTopic("TopicViewTestTopic"); - MessageConsumer consumer = session.createConsumer(destination); - assertNotNull(consumer); - TimeUnit.SECONDS.sleep(1); + Topic destination = session.createTopic("TopicViewTestTopic"); + MessageConsumer consumer = session.createConsumer(destination); + assertNotNull(consumer); + TimeUnit.SECONDS.sleep(1); - ObjectName subscriptionNames[] = broker.getAdminView().getTopicSubscribers(); - assertTrue(subscriptionNames.length > 0); + ObjectName subscriptionNames[] = broker.getAdminView().getTopicSubscribers(); + assertTrue(subscriptionNames.length > 0); - boolean fail = true; - for(ObjectName name : subscriptionNames) { - if (name.toString().contains("TopicViewTestTopic")) { - TopicSubscriptionViewMBean sub = (TopicSubscriptionViewMBean) - broker.getManagementContext().newProxyInstance(name, TopicSubscriptionViewMBean.class, true); - assertNotNull(sub); - assertTrue(sub.getSessionId() != -1); - // Check that its the default value then configure something new. - assertTrue(sub.getMaximumPendingQueueSize() == -1); - sub.setMaximumPendingQueueSize(1000); - assertTrue(sub.getMaximumPendingQueueSize() != -1); - fail = false; - } - } + boolean fail = true; + for (ObjectName name : subscriptionNames) { + if (name.toString().contains("TopicViewTestTopic")) { + TopicSubscriptionViewMBean sub = (TopicSubscriptionViewMBean) broker.getManagementContext().newProxyInstance(name, TopicSubscriptionViewMBean.class, true); + assertNotNull(sub); + assertTrue(sub.getSessionId() != -1); + // Check that its the default value then configure something new. + assertTrue(sub.getMaximumPendingQueueSize() == -1); + sub.setMaximumPendingQueueSize(1000); + assertTrue(sub.getMaximumPendingQueueSize() != -1); + fail = false; + } + } - if (fail) { - fail("Didn't find the TopicSubscriptionView"); - } - } + if (fail) { + fail("Didn't find the TopicSubscriptionView"); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2213Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2213Test.java index f267a9933a..2152e1233f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2213Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2213Test.java @@ -36,69 +36,66 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -public class AMQ2213Test -{ - BrokerService broker; - ConnectionFactory factory; - Connection connection; - Session session; - Queue queue; - MessageConsumer consumer; +public class AMQ2213Test { - public void createBroker(boolean deleteAll) throws Exception { - broker = new BrokerService(); - broker.setDeleteAllMessagesOnStartup(deleteAll); - broker.setDataDirectory("target/AMQ3145Test"); - broker.setUseJmx(true); - broker.getManagementContext().setCreateConnector(false); - broker.addConnector("tcp://localhost:0"); - broker.start(); - broker.waitUntilStarted(); - factory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri().toString()); - connection = factory.createConnection(); - connection.start(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - } + BrokerService broker; + ConnectionFactory factory; + Connection connection; + Session session; + Queue queue; + MessageConsumer consumer; - @Before - public void createBroker() throws Exception { - createBroker(true); - } + public void createBroker(boolean deleteAll) throws Exception { + broker = new BrokerService(); + broker.setDeleteAllMessagesOnStartup(deleteAll); + broker.setDataDirectory("target/AMQ3145Test"); + broker.setUseJmx(true); + broker.getManagementContext().setCreateConnector(false); + broker.addConnector("tcp://localhost:0"); + broker.start(); + broker.waitUntilStarted(); + factory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri().toString()); + connection = factory.createConnection(); + connection.start(); + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + } - @After - public void tearDown() throws Exception { - if (consumer != null) { - consumer.close(); - } - session.close(); - connection.stop(); - connection.close(); - broker.stop(); - } + @Before + public void createBroker() throws Exception { + createBroker(true); + } - @Test - public void testEqualsGenericSession() throws JMSException - { - assertNotNull(this.connection); - Session sess = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - assertTrue(sess.equals(sess)); - } + @After + public void tearDown() throws Exception { + if (consumer != null) { + consumer.close(); + } + session.close(); + connection.stop(); + connection.close(); + broker.stop(); + } - @Test - public void testEqualsTopicSession() throws JMSException - { - assertNotNull(this.connection); - assertTrue(this.connection instanceof TopicConnection); - TopicSession sess = ((TopicConnection)this.connection).createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - assertTrue(sess.equals(sess)); - } + @Test + public void testEqualsGenericSession() throws JMSException { + assertNotNull(this.connection); + Session sess = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + assertTrue(sess.equals(sess)); + } - @Test - public void testEqualsQueueSession() throws JMSException - { - assertNotNull(this.connection); - assertTrue(this.connection instanceof QueueConnection); - QueueSession sess = ((QueueConnection)this.connection).createQueueSession(false, Session.AUTO_ACKNOWLEDGE); - assertTrue(sess.equals(sess)); - } + @Test + public void testEqualsTopicSession() throws JMSException { + assertNotNull(this.connection); + assertTrue(this.connection instanceof TopicConnection); + TopicSession sess = ((TopicConnection) this.connection).createTopicSession(false, Session.AUTO_ACKNOWLEDGE); + assertTrue(sess.equals(sess)); + } + + @Test + public void testEqualsQueueSession() throws JMSException { + assertNotNull(this.connection); + assertTrue(this.connection instanceof QueueConnection); + QueueSession sess = ((QueueConnection) this.connection).createQueueSession(false, Session.AUTO_ACKNOWLEDGE); + assertTrue(sess.equals(sess)); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2314Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2314Test.java index 08be5db1e6..a0baf1d341 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2314Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2314Test.java @@ -40,136 +40,137 @@ import org.slf4j.LoggerFactory; public class AMQ2314Test extends CombinationTestSupport { - public boolean consumeAll = false; - public int deliveryMode = DeliveryMode.NON_PERSISTENT; + public boolean consumeAll = false; + public int deliveryMode = DeliveryMode.NON_PERSISTENT; - private static final Logger LOG = LoggerFactory.getLogger(AMQ2314Test.class); - private static final int MESSAGES_COUNT = 30000; - private static byte[] buf = new byte[1024]; - private BrokerService broker; - private String connectionUri; + private static final Logger LOG = LoggerFactory.getLogger(AMQ2314Test.class); + private static final int MESSAGES_COUNT = 30000; + private static byte[] buf = new byte[1024]; + private BrokerService broker; + private String connectionUri; - private static final long messageReceiveTimeout = 500L; + private static final long messageReceiveTimeout = 500L; - Destination destination = new ActiveMQTopic("FooTwo"); + Destination destination = new ActiveMQTopic("FooTwo"); - public void testRemoveSlowSubscriberWhacksTempStore() throws Exception { - runProducerWithHungConsumer(); - } + public void testRemoveSlowSubscriberWhacksTempStore() throws Exception { + runProducerWithHungConsumer(); + } - public void testMemoryUsageReleasedOnAllConsumed() throws Exception { - consumeAll = true; - runProducerWithHungConsumer(); - // do it again to ensure memory limits are decreased - runProducerWithHungConsumer(); - } + public void testMemoryUsageReleasedOnAllConsumed() throws Exception { + consumeAll = true; + runProducerWithHungConsumer(); + // do it again to ensure memory limits are decreased + runProducerWithHungConsumer(); + } - public void runProducerWithHungConsumer() throws Exception { + public void runProducerWithHungConsumer() throws Exception { - final CountDownLatch consumerContinue = new CountDownLatch(1); - final CountDownLatch consumerReady = new CountDownLatch(1); + final CountDownLatch consumerContinue = new CountDownLatch(1); + final CountDownLatch consumerReady = new CountDownLatch(1); - final long origTempUsage = broker.getSystemUsage().getTempUsage().getUsage(); + final long origTempUsage = broker.getSystemUsage().getTempUsage().getUsage(); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - factory.setAlwaysSyncSend(true); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); + factory.setAlwaysSyncSend(true); - // ensure messages are spooled to disk for this consumer - ActiveMQPrefetchPolicy prefetch = new ActiveMQPrefetchPolicy(); - prefetch.setTopicPrefetch(500); - factory.setPrefetchPolicy(prefetch); - final Connection connection = factory.createConnection(); - connection.start(); + // ensure messages are spooled to disk for this consumer + ActiveMQPrefetchPolicy prefetch = new ActiveMQPrefetchPolicy(); + prefetch.setTopicPrefetch(500); + factory.setPrefetchPolicy(prefetch); + final Connection connection = factory.createConnection(); + connection.start(); - Thread producingThread = new Thread("Producing thread") { - public void run() { - try { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(deliveryMode); - for (int idx = 0; idx < MESSAGES_COUNT; ++idx) { - Message message = session.createTextMessage(new String(buf) + idx); - producer.send(message); - } - producer.close(); - session.close(); - } catch (Throwable ex) { - ex.printStackTrace(); - } + Thread producingThread = new Thread("Producing thread") { + public void run() { + try { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(deliveryMode); + for (int idx = 0; idx < MESSAGES_COUNT; ++idx) { + Message message = session.createTextMessage(new String(buf) + idx); + producer.send(message); + } + producer.close(); + session.close(); } - }; - - Thread consumingThread = new Thread("Consuming thread") { - public void run() { - try { - int count = 0; - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); - - while (consumer.receive(messageReceiveTimeout) == null) { - consumerReady.countDown(); - } - count++; - LOG.info("Received one... waiting"); - consumerContinue.await(); - if (consumeAll) { - LOG.info("Consuming the rest of the messages..."); - while (consumer.receive(messageReceiveTimeout) != null) { - count++; - } - } - LOG.info("consumer session closing: consumed count: " + count); - session.close(); - } catch (Throwable ex) { - ex.printStackTrace(); - } + catch (Throwable ex) { + ex.printStackTrace(); } - }; - consumingThread.start(); - consumerReady.await(); + } + }; - producingThread.start(); - producingThread.join(); + Thread consumingThread = new Thread("Consuming thread") { + public void run() { + try { + int count = 0; + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(destination); - final long tempUsageBySubscription = broker.getSystemUsage().getTempUsage().getUsage(); - LOG.info("Orig Usage: " + origTempUsage + ", currentUsage: " + tempUsageBySubscription); - assertTrue("some temp store has been used", tempUsageBySubscription != origTempUsage); - consumerContinue.countDown(); - consumingThread.join(); - connection.close(); - - LOG.info("Subscription Usage: " + tempUsageBySubscription + ", endUsage: " - + broker.getSystemUsage().getTempUsage().getUsage()); - - assertTrue("temp usage decreased with removed sub", Wait.waitFor(new Wait.Condition(){ - public boolean isSatisified() throws Exception { - return broker.getSystemUsage().getTempUsage().getUsage() < tempUsageBySubscription; + while (consumer.receive(messageReceiveTimeout) == null) { + consumerReady.countDown(); + } + count++; + LOG.info("Received one... waiting"); + consumerContinue.await(); + if (consumeAll) { + LOG.info("Consuming the rest of the messages..."); + while (consumer.receive(messageReceiveTimeout) != null) { + count++; + } + } + LOG.info("consumer session closing: consumed count: " + count); + session.close(); } - })); - } + catch (Throwable ex) { + ex.printStackTrace(); + } + } + }; + consumingThread.start(); + consumerReady.await(); - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - broker = new BrokerService(); - broker.setDataDirectory("target" + File.separator + "activemq-data"); - broker.setPersistent(true); - broker.setUseJmx(true); - broker.setAdvisorySupport(false); - broker.setDeleteAllMessagesOnStartup(true); - broker.getSystemUsage().getMemoryUsage().setLimit(1024L*1024*64); + producingThread.start(); + producingThread.join(); - broker.addConnector("tcp://localhost:0").setName("Default"); - broker.start(); + final long tempUsageBySubscription = broker.getSystemUsage().getTempUsage().getUsage(); + LOG.info("Orig Usage: " + origTempUsage + ", currentUsage: " + tempUsageBySubscription); + assertTrue("some temp store has been used", tempUsageBySubscription != origTempUsage); + consumerContinue.countDown(); + consumingThread.join(); + connection.close(); - connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); - } + LOG.info("Subscription Usage: " + tempUsageBySubscription + ", endUsage: " + broker.getSystemUsage().getTempUsage().getUsage()); - public void tearDown() throws Exception { - broker.stop(); - } + assertTrue("temp usage decreased with removed sub", Wait.waitFor(new Wait.Condition() { + public boolean isSatisified() throws Exception { + return broker.getSystemUsage().getTempUsage().getUsage() < tempUsageBySubscription; + } + })); + } - public static Test suite() { - return suite(AMQ2314Test.class); - } + public void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); + broker = new BrokerService(); + broker.setDataDirectory("target" + File.separator + "activemq-data"); + broker.setPersistent(true); + broker.setUseJmx(true); + broker.setAdvisorySupport(false); + broker.setDeleteAllMessagesOnStartup(true); + broker.getSystemUsage().getMemoryUsage().setLimit(1024L * 1024 * 64); + + broker.addConnector("tcp://localhost:0").setName("Default"); + broker.start(); + + connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); + } + + public void tearDown() throws Exception { + broker.stop(); + } + + public static Test suite() { + return suite(AMQ2314Test.class); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2356Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2356Test.java index fb6169db6c..2f9bb84d73 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2356Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2356Test.java @@ -60,131 +60,133 @@ import org.apache.activemq.store.kahadb.KahaDBStore; deadlocked at less than 30 messages each. */ public class AMQ2356Test extends TestCase { - protected static final int MESSAGE_COUNT = 1000; - protected static final int NUMBER_OF_PAIRS = 10; - protected BrokerService broker; - protected String brokerURL = ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL; - protected int destinationCount; - public void testScenario() throws Exception { - for (int i = 0; i < NUMBER_OF_PAIRS; i++) { - ActiveMQQueue queue = new ActiveMQQueue(getClass().getName() + ":" + i); - ProducerConsumerPair cp = new ProducerConsumerPair(); - cp.start(this.brokerURL, queue, MESSAGE_COUNT); - cp.testRun(); - cp.stop(); - } - } + protected static final int MESSAGE_COUNT = 1000; + protected static final int NUMBER_OF_PAIRS = 10; + protected BrokerService broker; + protected String brokerURL = ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL; + protected int destinationCount; - protected Destination getDestination(Session session) throws JMSException { - String destinationName = getClass().getName() + "." + destinationCount++; - return session.createQueue(destinationName); - } + public void testScenario() throws Exception { + for (int i = 0; i < NUMBER_OF_PAIRS; i++) { + ActiveMQQueue queue = new ActiveMQQueue(getClass().getName() + ":" + i); + ProducerConsumerPair cp = new ProducerConsumerPair(); + cp.start(this.brokerURL, queue, MESSAGE_COUNT); + cp.testRun(); + cp.stop(); + } + } - @Override - protected void setUp() throws Exception { - if (broker == null) { - broker = createBroker(); - } - super.setUp(); - } + protected Destination getDestination(Session session) throws JMSException { + String destinationName = getClass().getName() + "." + destinationCount++; + return session.createQueue(destinationName); + } - @Override - protected void tearDown() throws Exception { - super.tearDown(); - if (broker != null) { - broker.stop(); - } - } + @Override + protected void setUp() throws Exception { + if (broker == null) { + broker = createBroker(); + } + super.setUp(); + } - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - configureBroker(answer); - answer.start(); - return answer; - } + @Override + protected void tearDown() throws Exception { + super.tearDown(); + if (broker != null) { + broker.stop(); + } + } - protected void configureBroker(BrokerService answer) throws Exception { - File dataFileDir = new File("target/test-amq-data/bugs/AMQ2356/kahadb"); - KahaDBStore kaha = new KahaDBStore(); - kaha.setDirectory(dataFileDir); - answer.setUseJmx(false); - // Setup a destination policy where it takes only 1 message at a time. - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policy = new PolicyEntry(); - policy.setOptimizedDispatch(true); - policyMap.setDefaultEntry(policy); - answer.setDestinationPolicy(policyMap); + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + configureBroker(answer); + answer.start(); + return answer; + } - answer.setAdvisorySupport(false); - answer.setEnableStatistics(false); - answer.setDeleteAllMessagesOnStartup(true); - answer.addConnector(brokerURL); + protected void configureBroker(BrokerService answer) throws Exception { + File dataFileDir = new File("target/test-amq-data/bugs/AMQ2356/kahadb"); + KahaDBStore kaha = new KahaDBStore(); + kaha.setDirectory(dataFileDir); + answer.setUseJmx(false); + // Setup a destination policy where it takes only 1 message at a time. + PolicyMap policyMap = new PolicyMap(); + PolicyEntry policy = new PolicyEntry(); + policy.setOptimizedDispatch(true); + policyMap.setDefaultEntry(policy); + answer.setDestinationPolicy(policyMap); - } + answer.setAdvisorySupport(false); + answer.setEnableStatistics(false); + answer.setDeleteAllMessagesOnStartup(true); + answer.addConnector(brokerURL); - static class ProducerConsumerPair { - private Destination destination; - private MessageProducer producer; - private MessageConsumer consumer; - private Connection producerConnection; - private Connection consumerConnection; - private int numberOfMessages; + } - ProducerConsumerPair() { + static class ProducerConsumerPair { - } + private Destination destination; + private MessageProducer producer; + private MessageConsumer consumer; + private Connection producerConnection; + private Connection consumerConnection; + private int numberOfMessages; - void start(String brokerURL, final Destination dest, int msgNum) throws Exception { - this.destination = dest; - this.numberOfMessages = msgNum; - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(brokerURL); - this.producerConnection = cf.createConnection(); - this.producerConnection.start(); - this.consumerConnection = cf.createConnection(); - this.consumerConnection.start(); - this.producer = createProducer(this.producerConnection); - this.consumer = createConsumer(this.consumerConnection); - } + ProducerConsumerPair() { - void testRun() throws Exception { + } - Session s = this.producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - for (int i = 0; i < this.numberOfMessages; i++) { - BytesMessage msg = s.createBytesMessage(); - msg.writeBytes(new byte[1024]); - this.producer.send(msg); - } - int received = 0; - for (int i = 0; i < this.numberOfMessages; i++) { - Message msg = this.consumer.receive(); - assertNotNull(msg); - received++; - } - assertEquals("Messages received on " + this.destination, this.numberOfMessages, received); + void start(String brokerURL, final Destination dest, int msgNum) throws Exception { + this.destination = dest; + this.numberOfMessages = msgNum; + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(brokerURL); + this.producerConnection = cf.createConnection(); + this.producerConnection.start(); + this.consumerConnection = cf.createConnection(); + this.consumerConnection.start(); + this.producer = createProducer(this.producerConnection); + this.consumer = createConsumer(this.consumerConnection); + } - } + void testRun() throws Exception { - void stop() throws Exception { - if (this.producerConnection != null) { - this.producerConnection.close(); - } - if (this.consumerConnection != null) { - this.consumerConnection.close(); - } - } + Session s = this.producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + for (int i = 0; i < this.numberOfMessages; i++) { + BytesMessage msg = s.createBytesMessage(); + msg.writeBytes(new byte[1024]); + this.producer.send(msg); + } + int received = 0; + for (int i = 0; i < this.numberOfMessages; i++) { + Message msg = this.consumer.receive(); + assertNotNull(msg); + received++; + } + assertEquals("Messages received on " + this.destination, this.numberOfMessages, received); - private MessageProducer createProducer(Connection connection) throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer result = session.createProducer(this.destination); - return result; - } + } - private MessageConsumer createConsumer(Connection connection) throws Exception { + void stop() throws Exception { + if (this.producerConnection != null) { + this.producerConnection.close(); + } + if (this.consumerConnection != null) { + this.consumerConnection.close(); + } + } - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer result = session.createConsumer(this.destination); - return result; - } - } + private MessageProducer createProducer(Connection connection) throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer result = session.createProducer(this.destination); + return result; + } + + private MessageConsumer createConsumer(Connection connection) throws Exception { + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer result = session.createConsumer(this.destination); + return result; + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2364Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2364Test.java index 15d24d5cd4..5f79b6cbe2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2364Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2364Test.java @@ -45,69 +45,69 @@ import org.apache.activemq.transport.ResponseCorrelator; import org.apache.activemq.transport.failover.FailoverTransport; import org.junit.Test; - public class AMQ2364Test { - @SuppressWarnings("unchecked") - @Test - public void testRollbackLeak() throws Exception { + @SuppressWarnings("unchecked") + @Test + public void testRollbackLeak() throws Exception { - int messageCount = 1000; - URI failoverUri = new URI("failover:(vm://localhost)?jms.redeliveryPolicy.maximumRedeliveries=0"); + int messageCount = 1000; + URI failoverUri = new URI("failover:(vm://localhost)?jms.redeliveryPolicy.maximumRedeliveries=0"); - Destination dest = new ActiveMQQueue("Failover.Leak"); + Destination dest = new ActiveMQQueue("Failover.Leak"); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(failoverUri); - ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection(); - connection.start(); - final Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(failoverUri); + ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection(); + connection.start(); + final Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageProducer producer = session.createProducer(dest); + MessageProducer producer = session.createProducer(dest); - for (int i = 0; i < messageCount; ++i) - producer.send(session.createTextMessage("Test message #" + i)); - producer.close(); - session.commit(); + for (int i = 0; i < messageCount; ++i) + producer.send(session.createTextMessage("Test message #" + i)); + producer.close(); + session.commit(); - MessageConsumer consumer = session.createConsumer(dest); + MessageConsumer consumer = session.createConsumer(dest); - final CountDownLatch latch = new CountDownLatch(messageCount); - consumer.setMessageListener(new MessageListener() { + final CountDownLatch latch = new CountDownLatch(messageCount); + consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message msg) { - try { - session.rollback(); - } catch (JMSException e) { - e.printStackTrace(); - } finally { - latch.countDown(); - } + @Override + public void onMessage(Message msg) { + try { + session.rollback(); } - }); + catch (JMSException e) { + e.printStackTrace(); + } + finally { + latch.countDown(); + } + } + }); - latch.await(); - consumer.close(); - session.close(); + latch.await(); + consumer.close(); + session.close(); - ResponseCorrelator respCorr = (ResponseCorrelator) connection.getTransport(); - MutexTransport mutexTrans = (MutexTransport) respCorr.getNext(); - FailoverTransport failoverTrans = (FailoverTransport) mutexTrans.getNext(); - Field stateTrackerField = FailoverTransport.class.getDeclaredField("stateTracker"); - stateTrackerField.setAccessible(true); - ConnectionStateTracker stateTracker = (ConnectionStateTracker) stateTrackerField.get(failoverTrans); - Field statesField = ConnectionStateTracker.class.getDeclaredField("connectionStates"); - statesField.setAccessible(true); - ConcurrentHashMap states = - (ConcurrentHashMap) statesField.get(stateTracker); + ResponseCorrelator respCorr = (ResponseCorrelator) connection.getTransport(); + MutexTransport mutexTrans = (MutexTransport) respCorr.getNext(); + FailoverTransport failoverTrans = (FailoverTransport) mutexTrans.getNext(); + Field stateTrackerField = FailoverTransport.class.getDeclaredField("stateTracker"); + stateTrackerField.setAccessible(true); + ConnectionStateTracker stateTracker = (ConnectionStateTracker) stateTrackerField.get(failoverTrans); + Field statesField = ConnectionStateTracker.class.getDeclaredField("connectionStates"); + statesField.setAccessible(true); + ConcurrentHashMap states = (ConcurrentHashMap) statesField.get(stateTracker); - ConnectionState state = states.get(connection.getConnectionInfo().getConnectionId()); + ConnectionState state = states.get(connection.getConnectionInfo().getConnectionId()); - Collection transactionStates = state.getTransactionStates(); + Collection transactionStates = state.getTransactionStates(); - connection.stop(); - connection.close(); + connection.stop(); + connection.close(); - assertEquals("Transaction states not cleaned up", 0,transactionStates.size()); - } + assertEquals("Transaction states not cleaned up", 0, transactionStates.size()); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2383Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2383Test.java index 49c2366cf9..4fdfea4382 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2383Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2383Test.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.bugs; - import static org.junit.Assert.*; import javax.jms.Connection; @@ -33,31 +32,30 @@ import org.junit.Test; public class AMQ2383Test { - @Test - public void activeMQTest() throws Exception { - Destination dest = ActiveMQQueue.createDestination("testQueue", ActiveMQQueue.QUEUE_TYPE); - ConnectionFactory factory = new ActiveMQConnectionFactory( - "vm://localhost?broker.useJmx=false&broker.persistent=false"); - Connection producerConnection = factory.createConnection(); - producerConnection.start(); - Connection consumerConnection = factory.createConnection(); - consumerConnection.start(); + @Test + public void activeMQTest() throws Exception { + Destination dest = ActiveMQQueue.createDestination("testQueue", ActiveMQQueue.QUEUE_TYPE); + ConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?broker.useJmx=false&broker.persistent=false"); + Connection producerConnection = factory.createConnection(); + producerConnection.start(); + Connection consumerConnection = factory.createConnection(); + consumerConnection.start(); - Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = producerSession.createProducer(dest); - TextMessage sentMsg = producerSession.createTextMessage("test..."); - producer.send(sentMsg); - producerSession.close(); + Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = producerSession.createProducer(dest); + TextMessage sentMsg = producerSession.createTextMessage("test..."); + producer.send(sentMsg); + producerSession.close(); - Session consumerSession = consumerConnection.createSession(true, Session.SESSION_TRANSACTED); - MessageConsumer consumer = consumerSession.createConsumer(dest); - TextMessage receivedMsg = (TextMessage)consumer.receive(); - consumerSession.rollback(); - consumerSession.close(); + Session consumerSession = consumerConnection.createSession(true, Session.SESSION_TRANSACTED); + MessageConsumer consumer = consumerSession.createConsumer(dest); + TextMessage receivedMsg = (TextMessage) consumer.receive(); + consumerSession.rollback(); + consumerSession.close(); - assertEquals(sentMsg, receivedMsg); + assertEquals(sentMsg, receivedMsg); - producerConnection.close(); - consumerConnection.close(); - } + producerConnection.close(); + consumerConnection.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2401Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2401Test.java index 74f920fb85..c0979aaacc 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2401Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2401Test.java @@ -46,192 +46,203 @@ import org.slf4j.LoggerFactory; * An AMQ-2401 Test */ public class AMQ2401Test extends TestCase implements MessageListener { - private BrokerService broker; - private ActiveMQConnectionFactory factory; - private static final int SEND_COUNT = 500; - private static final int CONSUMER_COUNT = 50; - private static final int PRODUCER_COUNT = 1; - private static final int LOG_INTERVAL = 10; - private static final Logger LOG = LoggerFactory.getLogger(AMQ2401Test.class); + private BrokerService broker; + private ActiveMQConnectionFactory factory; + private static final int SEND_COUNT = 500; + private static final int CONSUMER_COUNT = 50; + private static final int PRODUCER_COUNT = 1; + private static final int LOG_INTERVAL = 10; - private final ArrayList services = new ArrayList(CONSUMER_COUNT + PRODUCER_COUNT); - private int count = 0; - private CountDownLatch latch; + private static final Logger LOG = LoggerFactory.getLogger(AMQ2401Test.class); - @Override - protected void setUp() throws Exception { - broker = new BrokerService(); - broker.setDataDirectory("target" + File.separator + "test-data" + File.separator + "AMQ2401Test"); - broker.setDeleteAllMessagesOnStartup(true); - String connectionUri = broker.addConnector("tcp://0.0.0.0:0").getPublishableConnectString(); - PolicyMap policies = new PolicyMap(); - PolicyEntry entry = new PolicyEntry(); - entry.setMemoryLimit(1024 * 100); - entry.setProducerFlowControl(true); - entry.setPendingQueuePolicy(new VMPendingQueueMessageStoragePolicy()); - entry.setQueue(">"); - policies.setDefaultEntry(entry); - broker.setDestinationPolicy(policies); - broker.setUseJmx(false); - broker.start(); - broker.waitUntilStarted(); + private final ArrayList services = new ArrayList(CONSUMER_COUNT + PRODUCER_COUNT); + private int count = 0; + private CountDownLatch latch; - factory = new ActiveMQConnectionFactory(connectionUri); - super.setUp(); - } + @Override + protected void setUp() throws Exception { + broker = new BrokerService(); + broker.setDataDirectory("target" + File.separator + "test-data" + File.separator + "AMQ2401Test"); + broker.setDeleteAllMessagesOnStartup(true); + String connectionUri = broker.addConnector("tcp://0.0.0.0:0").getPublishableConnectString(); + PolicyMap policies = new PolicyMap(); + PolicyEntry entry = new PolicyEntry(); + entry.setMemoryLimit(1024 * 100); + entry.setProducerFlowControl(true); + entry.setPendingQueuePolicy(new VMPendingQueueMessageStoragePolicy()); + entry.setQueue(">"); + policies.setDefaultEntry(entry); + broker.setDestinationPolicy(policies); + broker.setUseJmx(false); + broker.start(); + broker.waitUntilStarted(); - @Override - protected void tearDown() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } + factory = new ActiveMQConnectionFactory(connectionUri); + super.setUp(); + } - public void testDupsOk() throws Exception { + @Override + protected void tearDown() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + } - TestProducer p = null; - TestConsumer c = null; - try { - latch = new CountDownLatch(SEND_COUNT); + public void testDupsOk() throws Exception { - for (int i = 0; i < CONSUMER_COUNT; i++) { - TestConsumer consumer = new TestConsumer(); - consumer.start(); - services.add(consumer); - } - for (int i = 0; i < PRODUCER_COUNT; i++) { - TestProducer producer = new TestProducer(); - producer.start(); - services.add(producer); - } + TestProducer p = null; + TestConsumer c = null; + try { + latch = new CountDownLatch(SEND_COUNT); - waitForMessageReceipt(TimeUnit.SECONDS.toMillis(30)); - } finally { - if (p != null) { - p.close(); - } + for (int i = 0; i < CONSUMER_COUNT; i++) { + TestConsumer consumer = new TestConsumer(); + consumer.start(); + services.add(consumer); + } + for (int i = 0; i < PRODUCER_COUNT; i++) { + TestProducer producer = new TestProducer(); + producer.start(); + services.add(producer); + } - if (c != null) { - c.close(); - } - } - } + waitForMessageReceipt(TimeUnit.SECONDS.toMillis(30)); + } + finally { + if (p != null) { + p.close(); + } - @Override - public void onMessage(Message message) { - latch.countDown(); - if (++count % LOG_INTERVAL == 0) { - LOG.debug("Received message " + count); - } + if (c != null) { + c.close(); + } + } + } - try { - Thread.sleep(1); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - } + @Override + public void onMessage(Message message) { + latch.countDown(); + if (++count % LOG_INTERVAL == 0) { + LOG.debug("Received message " + count); + } - /** - * @throws InterruptedException - * @throws TimeoutException - */ - private void waitForMessageReceipt(long timeout) throws InterruptedException, TimeoutException { - if (!latch.await(timeout, TimeUnit.MILLISECONDS)) { - throw new TimeoutException(String.format("Consumner didn't receive expected # of messages, %d of %d received.", latch.getCount(), SEND_COUNT)); - } - } + try { + Thread.sleep(1); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } - private interface Service { - public void start() throws Exception; - public void close(); - } + /** + * @throws InterruptedException + * @throws TimeoutException + */ + private void waitForMessageReceipt(long timeout) throws InterruptedException, TimeoutException { + if (!latch.await(timeout, TimeUnit.MILLISECONDS)) { + throw new TimeoutException(String.format("Consumner didn't receive expected # of messages, %d of %d received.", latch.getCount(), SEND_COUNT)); + } + } - private class TestProducer implements Runnable, Service { - Thread thread; - BytesMessage message; + private interface Service { - Connection connection; - Session session; - MessageProducer producer; + public void start() throws Exception; - TestProducer() throws Exception { - thread = new Thread(this, "TestProducer"); - connection = factory.createConnection(); - connection.start(); - session = connection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE); - producer = session.createProducer(session.createQueue("AMQ2401Test")); - } + public void close(); + } - @Override - public void start() { - thread.start(); - } + private class TestProducer implements Runnable, Service { - @Override - public void run() { + Thread thread; + BytesMessage message; - int count = SEND_COUNT / PRODUCER_COUNT; - for (int i = 1; i <= count; i++) { - try { - if ((i % LOG_INTERVAL) == 0) { - LOG.debug("Sending: " + i); - } - message = session.createBytesMessage(); - message.writeBytes(new byte[1024]); - producer.send(message); - } catch (JMSException jmse) { - jmse.printStackTrace(); - break; - } - } - } + Connection connection; + Session session; + MessageProducer producer; - @Override - public void close() { + TestProducer() throws Exception { + thread = new Thread(this, "TestProducer"); + connection = factory.createConnection(); + connection.start(); + session = connection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE); + producer = session.createProducer(session.createQueue("AMQ2401Test")); + } + + @Override + public void start() { + thread.start(); + } + + @Override + public void run() { + + int count = SEND_COUNT / PRODUCER_COUNT; + for (int i = 1; i <= count; i++) { try { - connection.close(); - } catch (JMSException e) { + if ((i % LOG_INTERVAL) == 0) { + LOG.debug("Sending: " + i); + } + message = session.createBytesMessage(); + message.writeBytes(new byte[1024]); + producer.send(message); } - } - } + catch (JMSException jmse) { + jmse.printStackTrace(); + break; + } + } + } - private class TestConsumer implements Runnable, Service { - ActiveMQConnection connection; - Session session; - MessageConsumer consumer; + @Override + public void close() { + try { + connection.close(); + } + catch (JMSException e) { + } + } + } - TestConsumer() throws Exception { - factory.setOptimizeAcknowledge(false); - connection = (ActiveMQConnection) factory.createConnection(); + private class TestConsumer implements Runnable, Service { - session = connection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE); - consumer = session.createConsumer(session.createQueue("AMQ2401Test")); + ActiveMQConnection connection; + Session session; + MessageConsumer consumer; - consumer.setMessageListener(AMQ2401Test.this); - } + TestConsumer() throws Exception { + factory.setOptimizeAcknowledge(false); + connection = (ActiveMQConnection) factory.createConnection(); - @Override - public void start() throws Exception { - connection.start(); - } + session = connection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE); + consumer = session.createConsumer(session.createQueue("AMQ2401Test")); - @Override - public void close() { + consumer.setMessageListener(AMQ2401Test.this); + } + + @Override + public void start() throws Exception { + connection.start(); + } + + @Override + public void close() { + try { + connection.close(); + } + catch (JMSException e) { + } + } + + @Override + public void run() { + while (latch.getCount() > 0) { try { - connection.close(); - } catch (JMSException e) { + onMessage(consumer.receive()); } - } - - @Override - public void run() { - while (latch.getCount() > 0) { - try { - onMessage(consumer.receive()); - } catch (Exception e) { - e.printStackTrace(); - } + catch (Exception e) { + e.printStackTrace(); } - } - } + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2413Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2413Test.java index 25a95bcb43..ac5ecdb7b4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2413Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2413Test.java @@ -52,295 +52,307 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AMQ2413Test extends CombinationTestSupport implements MessageListener { - private static final Logger LOG = LoggerFactory.getLogger(AMQ2413Test.class); - BrokerService broker; - private ActiveMQConnectionFactory factory; - private static final int HANG_THRESHOLD = 60; - private static final int SEND_COUNT = 1000; - private static final int RECEIVER_THINK_TIME = 1; - private static final int CONSUMER_COUNT = 1; - private static final int PRODUCER_COUNT = 50; - private static final int TO_SEND = SEND_COUNT / PRODUCER_COUNT; + private static final Logger LOG = LoggerFactory.getLogger(AMQ2413Test.class); + BrokerService broker; + private ActiveMQConnectionFactory factory; - public int deliveryMode = DeliveryMode.NON_PERSISTENT; - public int ackMode = Session.DUPS_OK_ACKNOWLEDGE; - public boolean useVMCursor = false; - public boolean useOptimizeAcks = false; + private static final int HANG_THRESHOLD = 60; + private static final int SEND_COUNT = 1000; + private static final int RECEIVER_THINK_TIME = 1; + private static final int CONSUMER_COUNT = 1; + private static final int PRODUCER_COUNT = 50; + private static final int TO_SEND = SEND_COUNT / PRODUCER_COUNT; - private final ArrayList services = new ArrayList(CONSUMER_COUNT + PRODUCER_COUNT); - AtomicInteger count = new AtomicInteger(0); - Semaphore receivedMessages; - AtomicBoolean running = new AtomicBoolean(false); + public int deliveryMode = DeliveryMode.NON_PERSISTENT; + public int ackMode = Session.DUPS_OK_ACKNOWLEDGE; + public boolean useVMCursor = false; + public boolean useOptimizeAcks = false; - public void initCombos() { - addCombinationValues("deliveryMode", new Object[] { DeliveryMode.PERSISTENT, DeliveryMode.NON_PERSISTENT }); - addCombinationValues("ackMode", new Object[] { Session.DUPS_OK_ACKNOWLEDGE, Session.AUTO_ACKNOWLEDGE }); - addCombinationValues("useVMCursor", new Object[] { true, false }); - // addCombinationValues("useOptimizeAcks", new Object[] {true, false}); - } + private final ArrayList services = new ArrayList(CONSUMER_COUNT + PRODUCER_COUNT); + AtomicInteger count = new AtomicInteger(0); + Semaphore receivedMessages; + AtomicBoolean running = new AtomicBoolean(false); - @Override - protected void setUp() throws Exception { - broker = new BrokerService(); - broker.setDataDirectory("target" + File.separator + "test-data" + File.separator + "AMQ2401Test"); - broker.setDeleteAllMessagesOnStartup(true); + public void initCombos() { + addCombinationValues("deliveryMode", new Object[]{DeliveryMode.PERSISTENT, DeliveryMode.NON_PERSISTENT}); + addCombinationValues("ackMode", new Object[]{Session.DUPS_OK_ACKNOWLEDGE, Session.AUTO_ACKNOWLEDGE}); + addCombinationValues("useVMCursor", new Object[]{true, false}); + // addCombinationValues("useOptimizeAcks", new Object[] {true, false}); + } - KahaDBPersistenceAdapter kahaDb = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); - kahaDb.setConcurrentStoreAndDispatchQueues(false); - broker.addConnector("tcp://0.0.0.0:2401"); - PolicyMap policies = new PolicyMap(); - PolicyEntry entry = new PolicyEntry(); - entry.setMemoryLimit(1024 * 1024); - entry.setProducerFlowControl(true); - if (useVMCursor) { - entry.setPendingQueuePolicy(new VMPendingQueueMessageStoragePolicy()); - } - entry.setQueue(">"); - policies.setDefaultEntry(entry); - broker.setDestinationPolicy(policies); - broker.start(); - broker.waitUntilStarted(); + @Override + protected void setUp() throws Exception { + broker = new BrokerService(); + broker.setDataDirectory("target" + File.separator + "test-data" + File.separator + "AMQ2401Test"); + broker.setDeleteAllMessagesOnStartup(true); - count.set(0); - receivedMessages = new Semaphore(0); + KahaDBPersistenceAdapter kahaDb = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); + kahaDb.setConcurrentStoreAndDispatchQueues(false); + broker.addConnector("tcp://0.0.0.0:2401"); + PolicyMap policies = new PolicyMap(); + PolicyEntry entry = new PolicyEntry(); + entry.setMemoryLimit(1024 * 1024); + entry.setProducerFlowControl(true); + if (useVMCursor) { + entry.setPendingQueuePolicy(new VMPendingQueueMessageStoragePolicy()); + } + entry.setQueue(">"); + policies.setDefaultEntry(entry); + broker.setDestinationPolicy(policies); + broker.start(); + broker.waitUntilStarted(); - factory = new ActiveMQConnectionFactory("tcp://0.0.0.0:2401"); - // factory = new ActiveMQConnectionFactory("vm://localhost?broker.useJmx=false&broker.persistent=false"); - setAutoFail(true); - super.setUp(); - } + count.set(0); + receivedMessages = new Semaphore(0); - @Override - protected void tearDown() throws Exception { - running.set(false); - for (Service service : services) { - service.close(); - } + factory = new ActiveMQConnectionFactory("tcp://0.0.0.0:2401"); + // factory = new ActiveMQConnectionFactory("vm://localhost?broker.useJmx=false&broker.persistent=false"); + setAutoFail(true); + super.setUp(); + } - broker.stop(); - broker.waitUntilStopped(); + @Override + protected void tearDown() throws Exception { + running.set(false); + for (Service service : services) { + service.close(); + } - super.tearDown(); - } + broker.stop(); + broker.waitUntilStopped(); - public void testReceipt() throws Exception { + super.tearDown(); + } - running.set(true); - TestProducer p = null; - TestConsumer c = null; - try { + public void testReceipt() throws Exception { - for (int i = 0; i < CONSUMER_COUNT; i++) { - TestConsumer consumer = new TestConsumer(); - consumer.start(); - services.add(consumer); + running.set(true); + TestProducer p = null; + TestConsumer c = null; + try { + + for (int i = 0; i < CONSUMER_COUNT; i++) { + TestConsumer consumer = new TestConsumer(); + consumer.start(); + services.add(consumer); + } + for (int i = 0; i < PRODUCER_COUNT; i++) { + TestProducer producer = new TestProducer(i); + producer.start(); + services.add(producer); + } + waitForMessageReceipt(); + + } + finally { + if (p != null) { + p.close(); + } + + if (c != null) { + c.close(); + } + } + + } + + /* + * (non-Javadoc) + * + * @see javax.jms.MessageListener#onMessage(javax.jms.Message) + */ + @Override + public void onMessage(Message message) { + receivedMessages.release(); + if (count.incrementAndGet() % 100 == 0) { + LOG.info("Received message " + count); + } + track(message); + if (RECEIVER_THINK_TIME > 0) { + try { + Thread.sleep(RECEIVER_THINK_TIME); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + } + + HashMap tracker = new HashMap(); + + private synchronized void track(Message message) { + try { + MessageId id = new MessageId(message.getJMSMessageID()); + ProducerId pid = id.getProducerId(); + int seq = (int) id.getProducerSequenceId(); + boolean[] ids = tracker.get(pid); + if (ids == null) { + ids = new boolean[TO_SEND + 1]; + ids[seq] = true; + tracker.put(pid, ids); + } + else { + assertTrue("not already received: " + id, !ids[seq]); + ids[seq] = true; + } + } + catch (Exception e) { + LOG.error(e.toString()); + } + } + + /** + * @throws InterruptedException + * @throws TimeoutException + */ + private void waitForMessageReceipt() throws InterruptedException, TimeoutException { + try { + while (count.get() < SEND_COUNT) { + if (!receivedMessages.tryAcquire(HANG_THRESHOLD, TimeUnit.SECONDS)) { + if (count.get() == SEND_COUNT) + break; + verifyTracking(); + throw new TimeoutException("@count=" + count.get() + " Message not received for more than " + HANG_THRESHOLD + " seconds"); } - for (int i = 0; i < PRODUCER_COUNT; i++) { - TestProducer producer = new TestProducer(i); - producer.start(); - services.add(producer); + } + } + finally { + running.set(false); + } + } + + private void verifyTracking() { + Vector missing = new Vector(); + for (ProducerId pid : tracker.keySet()) { + boolean[] ids = tracker.get(pid); + for (int i = 1; i < TO_SEND + 1; i++) { + if (!ids[i]) { + missing.add(new MessageId(pid, i)); } - waitForMessageReceipt(); + } + } + assertTrue("No missing messages: " + missing, missing.isEmpty()); + } - } finally { - if (p != null) { - p.close(); - } + private interface Service { - if (c != null) { - c.close(); - } - } + public void start() throws Exception; - } + public void close(); + } - /* - * (non-Javadoc) - * - * @see javax.jms.MessageListener#onMessage(javax.jms.Message) - */ - @Override - public void onMessage(Message message) { - receivedMessages.release(); - if (count.incrementAndGet() % 100 == 0) { - LOG.info("Received message " + count); - } - track(message); - if (RECEIVER_THINK_TIME > 0) { + private class TestProducer implements Runnable, Service { + + Thread thread; + BytesMessage message; + Connection connection; + Session session; + MessageProducer producer; + + TestProducer(int id) throws Exception { + thread = new Thread(this, "TestProducer-" + id); + connection = factory.createConnection(); + connection.start(); + session = connection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE); + producer = session.createProducer(session.createQueue("AMQ2401Test")); + } + + @Override + public void start() { + thread.start(); + } + + @Override + public void run() { + + int i = 1; + for (; i <= TO_SEND; i++) { try { - Thread.sleep(RECEIVER_THINK_TIME); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); + + if (+i % 100 == 0) { + LOG.info(Thread.currentThread().getName() + " Sending message " + i); + } + message = session.createBytesMessage(); + message.writeBytes(new byte[1024]); + producer.setDeliveryMode(deliveryMode); + producer.send(message); } - } - - } - - HashMap tracker = new HashMap(); - - private synchronized void track(Message message) { - try { - MessageId id = new MessageId(message.getJMSMessageID()); - ProducerId pid = id.getProducerId(); - int seq = (int) id.getProducerSequenceId(); - boolean[] ids = tracker.get(pid); - if (ids == null) { - ids = new boolean[TO_SEND + 1]; - ids[seq] = true; - tracker.put(pid, ids); - } else { - assertTrue("not already received: " + id, !ids[seq]); - ids[seq] = true; + catch (JMSException jmse) { + jmse.printStackTrace(); + break; } - } catch (Exception e) { - LOG.error(e.toString()); - } - } + } + LOG.info(Thread.currentThread().getName() + " Sent: " + (i - 1)); + } - /** - * @throws InterruptedException - * @throws TimeoutException - * - */ - private void waitForMessageReceipt() throws InterruptedException, TimeoutException { - try { - while (count.get() < SEND_COUNT) { - if (!receivedMessages.tryAcquire(HANG_THRESHOLD, TimeUnit.SECONDS)) { - if (count.get() == SEND_COUNT) - break; - verifyTracking(); - throw new TimeoutException("@count=" + count.get() + " Message not received for more than " + HANG_THRESHOLD + " seconds"); - } - } - } finally { - running.set(false); - } - } + @Override + public void close() { + try { + connection.close(); + } + catch (JMSException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } - private void verifyTracking() { - Vector missing = new Vector(); - for (ProducerId pid : tracker.keySet()) { - boolean[] ids = tracker.get(pid); - for (int i = 1; i < TO_SEND + 1; i++) { - if (!ids[i]) { - missing.add(new MessageId(pid, i)); - } - } - } - assertTrue("No missing messages: " + missing, missing.isEmpty()); - } + private class TestConsumer implements Runnable, Service { - private interface Service { - public void start() throws Exception; + ActiveMQConnection connection; + Session session; + MessageConsumer consumer; - public void close(); - } + TestConsumer() throws Exception { + factory.setOptimizeAcknowledge(false); + connection = (ActiveMQConnection) factory.createConnection(); + if (useOptimizeAcks) { + connection.setOptimizeAcknowledge(true); + } - private class TestProducer implements Runnable, Service { - Thread thread; - BytesMessage message; - Connection connection; - Session session; - MessageProducer producer; + session = connection.createSession(false, ackMode); + consumer = session.createConsumer(session.createQueue("AMQ2401Test")); - TestProducer(int id) throws Exception { - thread = new Thread(this, "TestProducer-" + id); - connection = factory.createConnection(); - connection.start(); - session = connection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE); - producer = session.createProducer(session.createQueue("AMQ2401Test")); - } + consumer.setMessageListener(AMQ2413Test.this); + } - @Override - public void start() { - thread.start(); - } + @Override + public void start() throws Exception { + connection.start(); + } - @Override - public void run() { + @Override + public void close() { + try { + connection.close(); + } + catch (JMSException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - int i = 1; - for (; i <= TO_SEND; i++) { - try { - - if (+i % 100 == 0) { - LOG.info(Thread.currentThread().getName() + " Sending message " + i); - } - message = session.createBytesMessage(); - message.writeBytes(new byte[1024]); - producer.setDeliveryMode(deliveryMode); - producer.send(message); - } catch (JMSException jmse) { - jmse.printStackTrace(); - break; - } - } - LOG.info(Thread.currentThread().getName() + " Sent: " + (i - 1)); - } - - @Override - public void close() { + /* + * (non-Javadoc) + * + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + while (running.get()) { try { - connection.close(); - } catch (JMSException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + onMessage(consumer.receive()); } - } - } - - private class TestConsumer implements Runnable, Service { - ActiveMQConnection connection; - Session session; - MessageConsumer consumer; - - TestConsumer() throws Exception { - factory.setOptimizeAcknowledge(false); - connection = (ActiveMQConnection) factory.createConnection(); - if (useOptimizeAcks) { - connection.setOptimizeAcknowledge(true); + catch (Exception e) { + e.printStackTrace(); } + } + } + } - session = connection.createSession(false, ackMode); - consumer = session.createConsumer(session.createQueue("AMQ2401Test")); - - consumer.setMessageListener(AMQ2413Test.this); - } - - @Override - public void start() throws Exception { - connection.start(); - } - - @Override - public void close() { - try { - connection.close(); - } catch (JMSException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - /* - * (non-Javadoc) - * - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - while (running.get()) { - try { - onMessage(consumer.receive()); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - } - - public static Test suite() { - return suite(AMQ2413Test.class); - } + public static Test suite() { + return suite(AMQ2413Test.class); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2439Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2439Test.java index cd447f4108..67b5c43c70 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2439Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2439Test.java @@ -32,61 +32,61 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AMQ2439Test extends JmsMultipleBrokersTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(AMQ2439Test.class); - Destination dest; - - public void testDuplicatesThroughNetwork() throws Exception { - assertEquals("received expected amount", 500, receiveExactMessages("BrokerB", 500)); - assertEquals("received expected amount", 500, receiveExactMessages("BrokerB", 500)); - validateQueueStats(); - } - - private void validateQueueStats() throws Exception { - final BrokerView brokerView = brokers.get("BrokerA").broker.getAdminView(); - assertEquals("enequeue is correct", 1000, brokerView.getTotalEnqueueCount()); - - assertTrue("dequeue is correct", Wait.waitFor(new Wait.Condition() { - public boolean isSatisified() throws Exception { - LOG.info("dequeue count (want 1000), is : " + brokerView.getTotalDequeueCount()); - return 1000 == brokerView.getTotalDequeueCount(); - } - })); - } + private static final Logger LOG = LoggerFactory.getLogger(AMQ2439Test.class); + Destination dest; - protected int receiveExactMessages(String brokerName, int msgCount) throws Exception { - - BrokerItem brokerItem = brokers.get(brokerName); - Connection connection = brokerItem.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(dest); - - Message msg; - int i; - for (i = 0; i < msgCount; i++) { - msg = consumer.receive(1000); - if (msg == null) { - break; - } - } + public void testDuplicatesThroughNetwork() throws Exception { + assertEquals("received expected amount", 500, receiveExactMessages("BrokerB", 500)); + assertEquals("received expected amount", 500, receiveExactMessages("BrokerB", 500)); + validateQueueStats(); + } - connection.close(); - brokerItem.connections.remove(connection); - - return i; - } - - public void setUp() throws Exception { - super.setUp(); - createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=true&deleteAllMessagesOnStartup=true&advisorySupport=false")); - createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=true&deleteAllMessagesOnStartup=true&useJmx=false")); - bridgeBrokers("BrokerA", "BrokerB"); - - startAllBrokers(); - - // Create queue - dest = createDestination("TEST.FOO", false); - sendMessages("BrokerA", dest, 1000); - } + private void validateQueueStats() throws Exception { + final BrokerView brokerView = brokers.get("BrokerA").broker.getAdminView(); + assertEquals("enequeue is correct", 1000, brokerView.getTotalEnqueueCount()); + + assertTrue("dequeue is correct", Wait.waitFor(new Wait.Condition() { + public boolean isSatisified() throws Exception { + LOG.info("dequeue count (want 1000), is : " + brokerView.getTotalDequeueCount()); + return 1000 == brokerView.getTotalDequeueCount(); + } + })); + } + + protected int receiveExactMessages(String brokerName, int msgCount) throws Exception { + + BrokerItem brokerItem = brokers.get(brokerName); + Connection connection = brokerItem.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(dest); + + Message msg; + int i; + for (i = 0; i < msgCount; i++) { + msg = consumer.receive(1000); + if (msg == null) { + break; + } + } + + connection.close(); + brokerItem.connections.remove(connection); + + return i; + } + + public void setUp() throws Exception { + super.setUp(); + createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=true&deleteAllMessagesOnStartup=true&advisorySupport=false")); + createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=true&deleteAllMessagesOnStartup=true&useJmx=false")); + bridgeBrokers("BrokerA", "BrokerB"); + + startAllBrokers(); + + // Create queue + dest = createDestination("TEST.FOO", false); + sendMessages("BrokerA", dest, 1000); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2489Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2489Test.java index b581e6deb8..423285e6bd 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2489Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2489Test.java @@ -46,181 +46,183 @@ import org.apache.activemq.command.ActiveMQQueue; *

    * {@code javax.jms.JMSException: Could not correlate acknowledgment with * dispatched message: MessageAck} - * + * * @author daroo */ public class AMQ2489Test extends TestSupport { - private final static String SEQ_NUM_PROPERTY = "seqNum"; - private final static int TOTAL_MESSAGES_CNT = 2; - private final static int CONSUMERS_CNT = 2; + private final static String SEQ_NUM_PROPERTY = "seqNum"; - private final CountDownLatch LATCH = new CountDownLatch(TOTAL_MESSAGES_CNT); + private final static int TOTAL_MESSAGES_CNT = 2; + private final static int CONSUMERS_CNT = 2; - private Connection connection; + private final CountDownLatch LATCH = new CountDownLatch(TOTAL_MESSAGES_CNT); - protected void setUp() throws Exception { - super.setUp(); - connection = createConnection(); - } + private Connection connection; - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - connection = null; - } - super.tearDown(); - } + protected void setUp() throws Exception { + super.setUp(); + connection = createConnection(); + } - public void testUnorderedClientAcknowledge() throws Exception { - doUnorderedAck(Session.CLIENT_ACKNOWLEDGE); - } + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + connection = null; + } + super.tearDown(); + } - public void testUnorderedIndividualAcknowledge() throws Exception { - doUnorderedAck(ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE); - } + public void testUnorderedClientAcknowledge() throws Exception { + doUnorderedAck(Session.CLIENT_ACKNOWLEDGE); + } - /** - * Main test method - * - * @param acknowledgmentMode - * - ACK mode to be used by consumers - * @throws Exception - */ - protected void doUnorderedAck(int acknowledgmentMode) throws Exception { - List consumers = null; - Session producerSession = null; + public void testUnorderedIndividualAcknowledge() throws Exception { + doUnorderedAck(ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE); + } - connection.start(); - // Because exception is thrown on broker side only, let's set up - // exception listener to get it - final TestExceptionListener exceptionListener = new TestExceptionListener(); - connection.setExceptionListener(exceptionListener); - try { - consumers = new ArrayList(); - // start customers - for (int i = 0; i < CONSUMERS_CNT; i++) { - consumers.add(new Consumer(acknowledgmentMode)); + /** + * Main test method + * + * @param acknowledgmentMode - ACK mode to be used by consumers + * @throws Exception + */ + protected void doUnorderedAck(int acknowledgmentMode) throws Exception { + List consumers = null; + Session producerSession = null; + + connection.start(); + // Because exception is thrown on broker side only, let's set up + // exception listener to get it + final TestExceptionListener exceptionListener = new TestExceptionListener(); + connection.setExceptionListener(exceptionListener); + try { + consumers = new ArrayList(); + // start customers + for (int i = 0; i < CONSUMERS_CNT; i++) { + consumers.add(new Consumer(acknowledgmentMode)); + } + + // produce few test messages + producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final MessageProducer producer = producerSession.createProducer(new ActiveMQQueue(getQueueName())); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + for (int i = 0; i < TOTAL_MESSAGES_CNT; i++) { + final Message message = producerSession.createTextMessage("test"); + // assign each message sequence number + message.setIntProperty(SEQ_NUM_PROPERTY, i); + producer.send(message); + } + + // during each onMessage() calls consumers decreases the LATCH + // counter. + // + // so, let's wait till all messages are consumed. + // + LATCH.await(); + + // wait a bit more to give exception listener a chance be populated + // with + // broker's error + TimeUnit.SECONDS.sleep(1); + + assertFalse(exceptionListener.getStatusText(), exceptionListener.hasExceptions()); + + } + finally { + if (producerSession != null) + producerSession.close(); + + if (consumers != null) { + for (Consumer c : consumers) { + c.close(); + } + } + } + } + + protected String getQueueName() { + return getClass().getName() + "." + getName(); + } + + public final class Consumer implements MessageListener { + + final Session session; + + private Consumer(int acknowledgmentMode) { + try { + session = connection.createSession(false, acknowledgmentMode); + final Queue queue = session.createQueue(getQueueName() + "?consumer.prefetchSize=1"); + final MessageConsumer consumer = session.createConsumer(queue); + consumer.setMessageListener(this); + } + catch (JMSException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + public void onMessage(Message message) { + try { + // retrieve sequence number assigned by producer... + final int seqNum = message.getIntProperty(SEQ_NUM_PROPERTY); + + // ...and let's delay every second message a little bit before + // acknowledgment + if ((seqNum % 2) == 0) { + System.out.println("Delayed message sequence numeber: " + seqNum); + try { + TimeUnit.SECONDS.sleep(1); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } } - // produce few test messages - producerSession = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); - final MessageProducer producer = producerSession - .createProducer(new ActiveMQQueue(getQueueName())); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - for (int i = 0; i < TOTAL_MESSAGES_CNT; i++) { - final Message message = producerSession - .createTextMessage("test"); - // assign each message sequence number - message.setIntProperty(SEQ_NUM_PROPERTY, i); - producer.send(message); - } + message.acknowledge(); + } + catch (JMSException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + finally { + // decrease LATCH counter in the main test method. + LATCH.countDown(); + } + } - // during each onMessage() calls consumers decreases the LATCH - // counter. - // - // so, let's wait till all messages are consumed. - // - LATCH.await(); - - // wait a bit more to give exception listener a chance be populated - // with - // broker's error - TimeUnit.SECONDS.sleep(1); - - assertFalse(exceptionListener.getStatusText(), exceptionListener.hasExceptions()); - - } finally { - if (producerSession != null) - producerSession.close(); - - if (consumers != null) { - for (Consumer c : consumers) { - c.close(); - } - } - } - } - - protected String getQueueName() { - return getClass().getName() + "." + getName(); - } - - public final class Consumer implements MessageListener { - final Session session; - - private Consumer(int acknowledgmentMode) { + private void close() { + if (session != null) { try { - session = connection.createSession(false, acknowledgmentMode); - final Queue queue = session.createQueue(getQueueName() - + "?consumer.prefetchSize=1"); - final MessageConsumer consumer = session.createConsumer(queue); - consumer.setMessageListener(this); - } catch (JMSException e) { - e.printStackTrace(); - throw new RuntimeException(e); + session.close(); } - } - - public void onMessage(Message message) { - try { - // retrieve sequence number assigned by producer... - final int seqNum = message.getIntProperty(SEQ_NUM_PROPERTY); - - // ...and let's delay every second message a little bit before - // acknowledgment - if ((seqNum % 2) == 0) { - System.out.println("Delayed message sequence numeber: " - + seqNum); - try { - TimeUnit.SECONDS.sleep(1); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - } - - message.acknowledge(); - } catch (JMSException e) { - e.printStackTrace(); - throw new RuntimeException(e); - } finally { - // decrease LATCH counter in the main test method. - LATCH.countDown(); + catch (JMSException e) { + e.printStackTrace(); + throw new RuntimeException(e); } - } + } + } + } - private void close() { - if (session != null) { - try { - session.close(); - } catch (JMSException e) { - e.printStackTrace(); - throw new RuntimeException(e); - } - } - } - } + public final class TestExceptionListener implements ExceptionListener { - public final class TestExceptionListener implements ExceptionListener { - private final java.util.Queue exceptions = new ConcurrentLinkedQueue(); + private final java.util.Queue exceptions = new ConcurrentLinkedQueue(); - public void onException(JMSException e) { - exceptions.add(e); - } + public void onException(JMSException e) { + exceptions.add(e); + } - public boolean hasExceptions() { - return exceptions.isEmpty() == false; - } + public boolean hasExceptions() { + return exceptions.isEmpty() == false; + } - public String getStatusText() { - final StringBuilder str = new StringBuilder(); - str.append("Exceptions count on broker side: " + exceptions.size() - + ".\nMessages:\n"); - for (Exception e : exceptions) { - str.append(e.getMessage() + "\n\n"); - } - return str.toString(); - } - } + public String getStatusText() { + final StringBuilder str = new StringBuilder(); + str.append("Exceptions count on broker side: " + exceptions.size() + ".\nMessages:\n"); + for (Exception e : exceptions) { + str.append(e.getMessage() + "\n\n"); + } + return str.toString(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2512Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2512Test.java index 669066e1ee..2d3c06d128 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2512Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2512Test.java @@ -33,6 +33,7 @@ import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; import javax.jms.TextMessage; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.EmbeddedBrokerTestSupport; import org.apache.activemq.broker.BrokerService; @@ -40,135 +41,138 @@ import org.apache.activemq.store.kahadb.KahaDBStore; import org.apache.activemq.util.IOHelper; public class AMQ2512Test extends EmbeddedBrokerTestSupport { - private static Connection connection; - private final static String QUEUE_NAME = "dee.q"; - private final static int INITIAL_MESSAGES_CNT = 1000; - private final static int WORKER_INTERNAL_ITERATIONS = 100; - private final static int TOTAL_MESSAGES_CNT = INITIAL_MESSAGES_CNT * WORKER_INTERNAL_ITERATIONS - + INITIAL_MESSAGES_CNT; - private final static byte[] payload = new byte[5 * 1024]; - private final static String TEXT = new String(payload); - private final static String PRP_INITIAL_ID = "initial-id"; - private final static String PRP_WORKER_ID = "worker-id"; + private static Connection connection; + private final static String QUEUE_NAME = "dee.q"; + private final static int INITIAL_MESSAGES_CNT = 1000; + private final static int WORKER_INTERNAL_ITERATIONS = 100; + private final static int TOTAL_MESSAGES_CNT = INITIAL_MESSAGES_CNT * WORKER_INTERNAL_ITERATIONS + INITIAL_MESSAGES_CNT; + private final static byte[] payload = new byte[5 * 1024]; + private final static String TEXT = new String(payload); - private final static CountDownLatch LATCH = new CountDownLatch(TOTAL_MESSAGES_CNT); + private final static String PRP_INITIAL_ID = "initial-id"; + private final static String PRP_WORKER_ID = "worker-id"; - private final static AtomicInteger ON_MSG_COUNTER = new AtomicInteger(); + private final static CountDownLatch LATCH = new CountDownLatch(TOTAL_MESSAGES_CNT); - public void testKahaDBFailure() throws Exception { - final ConnectionFactory fac = new ActiveMQConnectionFactory(this.bindAddress); - connection = fac.createConnection(); - final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final Queue queue = session.createQueue(QUEUE_NAME); - final MessageProducer producer = session.createProducer(queue); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - connection.start(); + private final static AtomicInteger ON_MSG_COUNTER = new AtomicInteger(); - final long startTime = System.nanoTime(); + public void testKahaDBFailure() throws Exception { + final ConnectionFactory fac = new ActiveMQConnectionFactory(this.bindAddress); + connection = fac.createConnection(); + final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final Queue queue = session.createQueue(QUEUE_NAME); + final MessageProducer producer = session.createProducer(queue); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + connection.start(); - final List consumers = new ArrayList(); - for (int i = 0; i < 20; i++) { - consumers.add(new Consumer("worker-" + i)); - } + final long startTime = System.nanoTime(); - for (int i = 0; i < INITIAL_MESSAGES_CNT; i++) { - final TextMessage msg = session.createTextMessage(TEXT); - msg.setStringProperty(PRP_INITIAL_ID, "initial-" + i); - producer.send(msg); - } + final List consumers = new ArrayList(); + for (int i = 0; i < 20; i++) { + consumers.add(new Consumer("worker-" + i)); + } - LATCH.await(); - final long endTime = System.nanoTime(); - System.out.println("Total execution time = " - + TimeUnit.MILLISECONDS.convert(endTime - startTime, TimeUnit.NANOSECONDS) + " [ms]."); - System.out.println("Rate = " + TOTAL_MESSAGES_CNT - / TimeUnit.SECONDS.convert(endTime - startTime, TimeUnit.NANOSECONDS) + " [msg/s]."); + for (int i = 0; i < INITIAL_MESSAGES_CNT; i++) { + final TextMessage msg = session.createTextMessage(TEXT); + msg.setStringProperty(PRP_INITIAL_ID, "initial-" + i); + producer.send(msg); + } - for (Consumer c : consumers) { - c.close(); - } - connection.close(); - } + LATCH.await(); + final long endTime = System.nanoTime(); + System.out.println("Total execution time = " + TimeUnit.MILLISECONDS.convert(endTime - startTime, TimeUnit.NANOSECONDS) + " [ms]."); + System.out.println("Rate = " + TOTAL_MESSAGES_CNT / TimeUnit.SECONDS.convert(endTime - startTime, TimeUnit.NANOSECONDS) + " [msg/s]."); - private final static class Consumer implements MessageListener { - private final String name; - private final Session session; - private final MessageProducer producer; + for (Consumer c : consumers) { + c.close(); + } + connection.close(); + } - private Consumer(String name) { - this.name = name; + private final static class Consumer implements MessageListener { + + private final String name; + private final Session session; + private final MessageProducer producer; + + private Consumer(String name) { + this.name = name; + try { + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + final Queue queue = session.createQueue(QUEUE_NAME + "?consumer.prefetchSize=10"); + producer = session.createProducer(queue); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + final MessageConsumer consumer = session.createConsumer(queue); + consumer.setMessageListener(this); + } + catch (JMSException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + public void onMessage(Message message) { + final TextMessage msg = (TextMessage) message; + try { + if (!msg.propertyExists(PRP_WORKER_ID)) { + for (int i = 0; i < WORKER_INTERNAL_ITERATIONS; i++) { + final TextMessage newMsg = session.createTextMessage(msg.getText()); + newMsg.setStringProperty(PRP_WORKER_ID, name + "-" + i); + newMsg.setStringProperty(PRP_INITIAL_ID, msg.getStringProperty(PRP_INITIAL_ID)); + producer.send(newMsg); + } + } + msg.acknowledge(); + + } + catch (JMSException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + finally { + final int onMsgCounter = ON_MSG_COUNTER.getAndIncrement(); + if (onMsgCounter % 1000 == 0) { + System.out.println("message received: " + onMsgCounter); + } + LATCH.countDown(); + } + } + + private void close() { + if (session != null) { try { - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - final Queue queue = session.createQueue(QUEUE_NAME + "?consumer.prefetchSize=10"); - producer = session.createProducer(queue); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - final MessageConsumer consumer = session.createConsumer(queue); - consumer.setMessageListener(this); - } catch (JMSException e) { - e.printStackTrace(); - throw new RuntimeException(e); + session.close(); } - } - - public void onMessage(Message message) { - final TextMessage msg = (TextMessage) message; - try { - if (!msg.propertyExists(PRP_WORKER_ID)) { - for (int i = 0; i < WORKER_INTERNAL_ITERATIONS; i++) { - final TextMessage newMsg = session.createTextMessage(msg.getText()); - newMsg.setStringProperty(PRP_WORKER_ID, name + "-" + i); - newMsg.setStringProperty(PRP_INITIAL_ID, msg.getStringProperty(PRP_INITIAL_ID)); - producer.send(newMsg); - } - } - msg.acknowledge(); - - } catch (JMSException e) { - e.printStackTrace(); - throw new RuntimeException(e); - } finally { - final int onMsgCounter = ON_MSG_COUNTER.getAndIncrement(); - if (onMsgCounter % 1000 == 0) { - System.out.println("message received: " + onMsgCounter); - } - LATCH.countDown(); + catch (JMSException e) { + e.printStackTrace(); + throw new RuntimeException(e); } - } + } + } + } - private void close() { - if (session != null) { - try { - session.close(); - } catch (JMSException e) { - e.printStackTrace(); - throw new RuntimeException(e); - } - } - } - } + @Override + protected void setUp() throws Exception { + bindAddress = "tcp://0.0.0.0:61617"; + super.setUp(); + } - @Override - protected void setUp() throws Exception { - bindAddress = "tcp://0.0.0.0:61617"; - super.setUp(); - } + @Override + protected BrokerService createBroker() throws Exception { + File dataFileDir = new File("target/test-amq-2512/datadb"); + IOHelper.mkdirs(dataFileDir); + IOHelper.deleteChildren(dataFileDir); + KahaDBStore kaha = new KahaDBStore(); + kaha.setDirectory(dataFileDir); + BrokerService answer = new BrokerService(); + answer.setPersistenceAdapter(kaha); - @Override - protected BrokerService createBroker() throws Exception { - File dataFileDir = new File("target/test-amq-2512/datadb"); - IOHelper.mkdirs(dataFileDir); - IOHelper.deleteChildren(dataFileDir); - KahaDBStore kaha = new KahaDBStore(); - kaha.setDirectory(dataFileDir); - BrokerService answer = new BrokerService(); - answer.setPersistenceAdapter(kaha); - - kaha.setEnableJournalDiskSyncs(false); - //kaha.setIndexCacheSize(10); - answer.setDataDirectoryFile(dataFileDir); - answer.setUseJmx(false); - answer.addConnector(bindAddress); - return answer; - } + kaha.setEnableJournalDiskSyncs(false); + //kaha.setIndexCacheSize(10); + answer.setDataDirectoryFile(dataFileDir); + answer.setUseJmx(false); + answer.addConnector(bindAddress); + return answer; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2513Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2513Test.java index b9cfbd9c3c..eb25bdd6ac 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2513Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2513Test.java @@ -33,75 +33,73 @@ import org.apache.activemq.broker.jmx.ManagementContext; * This unit test verifies an issue when * javax.management.InstanceNotFoundException is thrown after subsequent startups when * managementContext createConnector="false" - * */ public class AMQ2513Test extends TestCase { - private BrokerService broker; - private String connectionUri; + private BrokerService broker; + private String connectionUri; - void createBroker(boolean deleteAllMessagesOnStartup) throws Exception { - broker = new BrokerService(); - broker.setBrokerName("localhost"); - broker.setUseJmx(true); - broker.setDeleteAllMessagesOnStartup(deleteAllMessagesOnStartup); - broker.addConnector("tcp://localhost:0"); + void createBroker(boolean deleteAllMessagesOnStartup) throws Exception { + broker = new BrokerService(); + broker.setBrokerName("localhost"); + broker.setUseJmx(true); + broker.setDeleteAllMessagesOnStartup(deleteAllMessagesOnStartup); + broker.addConnector("tcp://localhost:0"); - ManagementContext ctx = new ManagementContext(); - //if createConnector == true everything is fine - ctx.setCreateConnector(false); - broker.setManagementContext(ctx); + ManagementContext ctx = new ManagementContext(); + //if createConnector == true everything is fine + ctx.setCreateConnector(false); + broker.setManagementContext(ctx); - broker.start(); - broker.waitUntilStarted(); + broker.start(); + broker.waitUntilStarted(); - connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); - } + connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); + } - public void testJmx() throws Exception{ - createBroker(true); + public void testJmx() throws Exception { + createBroker(true); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(session.createQueue("test")); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - connection.start(); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); + Connection connection = factory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(session.createQueue("test")); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + connection.start(); - producer.send(session.createTextMessage("test123")); + producer.send(session.createTextMessage("test123")); - DestinationViewMBean dv = createView(); - assertTrue(dv.getQueueSize() > 0); + DestinationViewMBean dv = createView(); + assertTrue(dv.getQueueSize() > 0); - connection.close(); + connection.close(); - broker.stop(); - broker.waitUntilStopped(); + broker.stop(); + broker.waitUntilStopped(); - createBroker(false); - factory = new ActiveMQConnectionFactory(connectionUri); - connection = factory.createConnection(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(session.createQueue("test")); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - connection.start(); - producer.send(session.createTextMessage("test123")); - connection.close(); + createBroker(false); + factory = new ActiveMQConnectionFactory(connectionUri); + connection = factory.createConnection(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer = session.createProducer(session.createQueue("test")); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + connection.start(); + producer.send(session.createTextMessage("test123")); + connection.close(); - dv = createView(); - assertTrue(dv.getQueueSize() > 0); + dv = createView(); + assertTrue(dv.getQueueSize() > 0); - broker.stop(); - broker.waitUntilStopped(); + broker.stop(); + broker.waitUntilStopped(); - } + } - DestinationViewMBean createView() throws Exception { - String domain = "org.apache.activemq"; - ObjectName name = new ObjectName(domain + ":type=Broker,brokerName=localhost," + - "destinationType=Queue,destinationName=test"); - return (DestinationViewMBean) broker.getManagementContext().newProxyInstance(name, DestinationViewMBean.class, - true); - } + DestinationViewMBean createView() throws Exception { + String domain = "org.apache.activemq"; + ObjectName name = new ObjectName(domain + ":type=Broker,brokerName=localhost," + + "destinationType=Queue,destinationName=test"); + return (DestinationViewMBean) broker.getManagementContext().newProxyInstance(name, DestinationViewMBean.class, true); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2528Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2528Test.java index 80c036f0cb..f6f0b24733 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2528Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2528Test.java @@ -32,50 +32,47 @@ import org.junit.Assert; */ public class AMQ2528Test extends EmbeddedBrokerTestSupport { - /** - * Setup the test so that the destination is a queue. - */ - protected void setUp() throws Exception { - useTopic = false; - super.setUp(); - } + /** + * Setup the test so that the destination is a queue. + */ + protected void setUp() throws Exception { + useTopic = false; + super.setUp(); + } - /** - * This test enqueues test messages to destination and then verifies that - * {@link Queue#removeMatchingMessages("")} removes all the messages. - */ - public void testRemoveMatchingMessages() throws Exception { - final int NUM_MESSAGES = 100; - final String MESSAGE_ID = "id"; + /** + * This test enqueues test messages to destination and then verifies that + * {@link Queue#removeMatchingMessages("")} removes all the messages. + */ + public void testRemoveMatchingMessages() throws Exception { + final int NUM_MESSAGES = 100; + final String MESSAGE_ID = "id"; - // Enqueue the test messages. - Connection conn = createConnection(); - try { - conn.start(); - Session session = conn.createSession(false, - Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - for (int id = 0; id < NUM_MESSAGES; id++) { - Message message = session.createMessage(); - message.setIntProperty(MESSAGE_ID, id); - producer.send(message); - } - producer.close(); - session.close(); - } finally { - conn.close(); - } + // Enqueue the test messages. + Connection conn = createConnection(); + try { + conn.start(); + Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + for (int id = 0; id < NUM_MESSAGES; id++) { + Message message = session.createMessage(); + message.setIntProperty(MESSAGE_ID, id); + producer.send(message); + } + producer.close(); + session.close(); + } + finally { + conn.close(); + } - // Verify that half of the messages can be removed by selector. - Queue queue = (Queue) broker.getRegionBroker().getDestinations( - destination).iterator().next(); + // Verify that half of the messages can be removed by selector. + Queue queue = (Queue) broker.getRegionBroker().getDestinations(destination).iterator().next(); - Assert.assertEquals(NUM_MESSAGES / 2, queue - .removeMatchingMessages(MESSAGE_ID + " < " + NUM_MESSAGES / 2)); + Assert.assertEquals(NUM_MESSAGES / 2, queue.removeMatchingMessages(MESSAGE_ID + " < " + NUM_MESSAGES / 2)); - // Verify that the remainder of the messages can be removed by empty - // selector. - Assert.assertEquals(NUM_MESSAGES - NUM_MESSAGES / 2, queue - .removeMatchingMessages("")); - } + // Verify that the remainder of the messages can be removed by empty + // selector. + Assert.assertEquals(NUM_MESSAGES - NUM_MESSAGES / 2, queue.removeMatchingMessages("")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2571Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2571Test.java index 533ae0c939..1e4d4400df 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2571Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2571Test.java @@ -23,88 +23,92 @@ import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TemporaryQueue; import javax.jms.TextMessage; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.EmbeddedBrokerTestSupport; import org.apache.activemq.broker.BrokerService; public class AMQ2571Test extends EmbeddedBrokerTestSupport { - public void testTempQueueClosing() { - try { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(this.bindAddress); - connectionFactory.setAlwaysSyncSend(true); + public void testTempQueueClosing() { + try { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(this.bindAddress); + connectionFactory.setAlwaysSyncSend(true); - // First create session that will own the TempQueue - Connection connectionA = connectionFactory.createConnection(); - connectionA.start(); + // First create session that will own the TempQueue + Connection connectionA = connectionFactory.createConnection(); + connectionA.start(); - Session sessionA = connectionA.createSession(false, Session.AUTO_ACKNOWLEDGE); + Session sessionA = connectionA.createSession(false, Session.AUTO_ACKNOWLEDGE); - TemporaryQueue tempQueue = sessionA.createTemporaryQueue(); + TemporaryQueue tempQueue = sessionA.createTemporaryQueue(); - // Next, create session that will put messages on the queue. - Connection connectionB = connectionFactory.createConnection(); - connectionB.start(); + // Next, create session that will put messages on the queue. + Connection connectionB = connectionFactory.createConnection(); + connectionB.start(); - Session sessionB = connectionB.createSession(false, Session.AUTO_ACKNOWLEDGE); + Session sessionB = connectionB.createSession(false, Session.AUTO_ACKNOWLEDGE); - // Create a producer for connection B. - final MessageProducer producerB = sessionB.createProducer(tempQueue); - producerB.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + // Create a producer for connection B. + final MessageProducer producerB = sessionB.createProducer(tempQueue); + producerB.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - final TextMessage message = sessionB.createTextMessage("Testing AMQ TempQueue."); + final TextMessage message = sessionB.createTextMessage("Testing AMQ TempQueue."); - Thread sendingThread = new Thread(new Runnable() { - public void run() { - try { - long end = System.currentTimeMillis() + 5*60*1000; - // wait for exception on send - while (System.currentTimeMillis() < end) { - producerB.send(message); - } - } catch (JMSException e) { - e.printStackTrace(); - } - } - }); - - // Send 5000 messages. - sendingThread.start(); - // Now close connection A. This will remove the TempQueue. - connectionA.close(); - // Wait for the thread to finish. - sendingThread.join(5*60*1000); - - // Sleep for a while to make sure that we should know that the - // TempQueue is gone. - //Thread.sleep(50); - - // Now we test if we are able to send again. - try { - producerB.send(message); - fail("Involuntary recreated temporary queue."); - } catch (JMSException e) { - // Got exception, just as we wanted because the creator of - // the TempQueue had closed the connection prior to the send. - assertTrue("TempQueue does not exist anymore.", true); + Thread sendingThread = new Thread(new Runnable() { + public void run() { + try { + long end = System.currentTimeMillis() + 5 * 60 * 1000; + // wait for exception on send + while (System.currentTimeMillis() < end) { + producerB.send(message); + } + } + catch (JMSException e) { + e.printStackTrace(); + } } - } catch (Exception e) { - fail("Unexpected exception " + e); - } - } + }); - @Override - protected void setUp() throws Exception { - bindAddress = "vm://localhost"; - setAutoFail(true); - super.setUp(); - } + // Send 5000 messages. + sendingThread.start(); + // Now close connection A. This will remove the TempQueue. + connectionA.close(); + // Wait for the thread to finish. + sendingThread.join(5 * 60 * 1000); - @Override - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setPersistent(false); - answer.setUseJmx(false); - return answer; - } + // Sleep for a while to make sure that we should know that the + // TempQueue is gone. + //Thread.sleep(50); + + // Now we test if we are able to send again. + try { + producerB.send(message); + fail("Involuntary recreated temporary queue."); + } + catch (JMSException e) { + // Got exception, just as we wanted because the creator of + // the TempQueue had closed the connection prior to the send. + assertTrue("TempQueue does not exist anymore.", true); + } + } + catch (Exception e) { + fail("Unexpected exception " + e); + } + } + + @Override + protected void setUp() throws Exception { + bindAddress = "vm://localhost"; + setAutoFail(true); + super.setUp(); + } + + @Override + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + answer.setPersistent(false); + answer.setUseJmx(false); + return answer; + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2580Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2580Test.java index 2bcb983b6a..2b295fc15a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2580Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2580Test.java @@ -17,8 +17,9 @@ package org.apache.activemq.bugs; import junit.framework.Test; + import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.ActiveMQPrefetchPolicy; +import org.apache.activemq.ActiveMQPrefetchPolicy; import org.apache.activemq.TestSupport; import org.apache.activemq.broker.BrokerService; import org.slf4j.Logger; @@ -36,166 +37,157 @@ import javax.jms.TopicSession; public class AMQ2580Test extends TestSupport { - private static final Logger LOG = LoggerFactory.getLogger(AMQ2580Test.class); + private static final Logger LOG = LoggerFactory.getLogger(AMQ2580Test.class); - private static final String TOPIC_NAME = "topicName"; - private static final String CLIENT_ID = "client_id"; - private static final String textOfSelectedMsg = "good_message"; + private static final String TOPIC_NAME = "topicName"; + private static final String CLIENT_ID = "client_id"; + private static final String textOfSelectedMsg = "good_message"; - protected TopicConnection connection; + protected TopicConnection connection; - private Topic topic; - private Session session; - private MessageProducer producer; - private ConnectionFactory connectionFactory; - private BrokerService service; + private Topic topic; + private Session session; + private MessageProducer producer; + private ConnectionFactory connectionFactory; + private BrokerService service; - public static Test suite() { - return suite(AMQ2580Test.class); - } + public static Test suite() { + return suite(AMQ2580Test.class); + } - protected void setUp() throws Exception { - super.setUp(); - initDurableBroker(); - initConnectionFactory(); - initTopic(); - } + protected void setUp() throws Exception { + super.setUp(); + initDurableBroker(); + initConnectionFactory(); + initTopic(); + } - protected void tearDown() throws Exception { - shutdownClient(); - service.stop(); - super.tearDown(); - } + protected void tearDown() throws Exception { + shutdownClient(); + service.stop(); + super.tearDown(); + } - private void initConnection() throws JMSException { - if (connection == null) { - LOG.info("Initializing connection"); + private void initConnection() throws JMSException { + if (connection == null) { + LOG.info("Initializing connection"); - connection = (TopicConnection) connectionFactory.createConnection(); - connection.start(); - } - } + connection = (TopicConnection) connectionFactory.createConnection(); + connection.start(); + } + } - public void initCombosForTestTopicIsDurableSmokeTest() throws Exception { - addCombinationValues("defaultPersistenceAdapter", PersistenceAdapterChoice.values()); - } + public void initCombosForTestTopicIsDurableSmokeTest() throws Exception { + addCombinationValues("defaultPersistenceAdapter", PersistenceAdapterChoice.values()); + } - public void testTopicIsDurableSmokeTest() throws Exception { + public void testTopicIsDurableSmokeTest() throws Exception { - initClient(); - MessageConsumer consumer = createMessageConsumer(); - LOG.info("Consuming message"); - assertNull(consumer.receive(1)); - shutdownClient(); - consumer.close(); + initClient(); + MessageConsumer consumer = createMessageConsumer(); + LOG.info("Consuming message"); + assertNull(consumer.receive(1)); + shutdownClient(); + consumer.close(); - sendMessages(); - shutdownClient(); + sendMessages(); + shutdownClient(); - initClient(); - consumer = createMessageConsumer(); + initClient(); + consumer = createMessageConsumer(); - LOG.info("Consuming message"); - TextMessage answer1 = (TextMessage) consumer.receive(1000); - assertNotNull("we got our message", answer1); + LOG.info("Consuming message"); + TextMessage answer1 = (TextMessage) consumer.receive(1000); + assertNotNull("we got our message", answer1); - consumer.close(); - } + consumer.close(); + } - private MessageConsumer createMessageConsumer() throws JMSException { - LOG.info("creating durable subscriber"); - return session.createDurableSubscriber(topic, - TOPIC_NAME, - "name='value'", - false); - } + private MessageConsumer createMessageConsumer() throws JMSException { + LOG.info("creating durable subscriber"); + return session.createDurableSubscriber(topic, TOPIC_NAME, "name='value'", false); + } - private void initClient() throws JMSException { - LOG.info("Initializing client"); + private void initClient() throws JMSException { + LOG.info("Initializing client"); - initConnection(); - initSession(); - } + initConnection(); + initSession(); + } - private void shutdownClient() - throws JMSException { - LOG.info("Closing session and connection"); - session.close(); - connection.close(); - session = null; - connection = null; - } + private void shutdownClient() throws JMSException { + LOG.info("Closing session and connection"); + session.close(); + connection.close(); + session = null; + connection = null; + } - private void sendMessages() - throws JMSException { - initConnection(); + private void sendMessages() throws JMSException { + initConnection(); - initSession(); + initSession(); - LOG.info("Creating producer"); - producer = session.createProducer(topic); + LOG.info("Creating producer"); + producer = session.createProducer(topic); - sendMessageThatFailsSelection(); + sendMessageThatFailsSelection(); - sendMessage(textOfSelectedMsg, "value"); - } + sendMessage(textOfSelectedMsg, "value"); + } - private void initSession() throws JMSException { - LOG.info("Initializing session"); - session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - } + private void initSession() throws JMSException { + LOG.info("Initializing session"); + session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); + } - private void sendMessageThatFailsSelection() throws JMSException { - for (int i = 0; i < 5; i++) { - String textOfNotSelectedMsg = "Msg_" + i; - sendMessage(textOfNotSelectedMsg, "not_value"); - LOG.info("#"); - } - } + private void sendMessageThatFailsSelection() throws JMSException { + for (int i = 0; i < 5; i++) { + String textOfNotSelectedMsg = "Msg_" + i; + sendMessage(textOfNotSelectedMsg, "not_value"); + LOG.info("#"); + } + } - private void sendMessage( - String msgText, - String propertyValue) throws JMSException { - LOG.info("Creating message: " + msgText); - TextMessage messageToSelect = session.createTextMessage(msgText); - messageToSelect.setStringProperty("name", propertyValue); - LOG.info("Sending message"); - producer.send(messageToSelect); - } + private void sendMessage(String msgText, String propertyValue) throws JMSException { + LOG.info("Creating message: " + msgText); + TextMessage messageToSelect = session.createTextMessage(msgText); + messageToSelect.setStringProperty("name", propertyValue); + LOG.info("Sending message"); + producer.send(messageToSelect); + } - protected void initConnectionFactory() throws Exception { - ActiveMQConnectionFactory activeMqConnectionFactory = createActiveMqConnectionFactory(); - connectionFactory = activeMqConnectionFactory; - } + protected void initConnectionFactory() throws Exception { + ActiveMQConnectionFactory activeMqConnectionFactory = createActiveMqConnectionFactory(); + connectionFactory = activeMqConnectionFactory; + } + private ActiveMQConnectionFactory createActiveMqConnectionFactory() throws Exception { + ActiveMQConnectionFactory activeMqConnectionFactory = new ActiveMQConnectionFactory("failover:" + service.getTransportConnectors().get(0).getConnectUri().toString()); + activeMqConnectionFactory.setWatchTopicAdvisories(false); + ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); + prefetchPolicy.setDurableTopicPrefetch(2); + prefetchPolicy.setOptimizeDurableTopicPrefetch(2); + activeMqConnectionFactory.setPrefetchPolicy(prefetchPolicy); + activeMqConnectionFactory.setClientID(CLIENT_ID); + return activeMqConnectionFactory; + } - private ActiveMQConnectionFactory createActiveMqConnectionFactory() throws Exception { - ActiveMQConnectionFactory activeMqConnectionFactory = new ActiveMQConnectionFactory( - "failover:" + service.getTransportConnectors().get(0).getConnectUri().toString()); - activeMqConnectionFactory.setWatchTopicAdvisories(false); - ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); - prefetchPolicy.setDurableTopicPrefetch(2); - prefetchPolicy.setOptimizeDurableTopicPrefetch(2); - activeMqConnectionFactory.setPrefetchPolicy(prefetchPolicy); - activeMqConnectionFactory.setClientID(CLIENT_ID); - return activeMqConnectionFactory; - } + private void initDurableBroker() throws Exception { + service = new BrokerService(); + setDefaultPersistenceAdapter(service); + service.setDeleteAllMessagesOnStartup(true); + service.setAdvisorySupport(false); + service.setTransportConnectorURIs(new String[]{"tcp://localhost:0"}); + service.setPersistent(true); + service.setUseJmx(false); + service.start(); - private void initDurableBroker() throws Exception { - service = new BrokerService(); - setDefaultPersistenceAdapter(service); - service.setDeleteAllMessagesOnStartup(true); - service.setAdvisorySupport(false); - service.setTransportConnectorURIs(new String[]{"tcp://localhost:0"}); - service.setPersistent(true); - service.setUseJmx(false); - service.start(); + } - } - - private void initTopic() throws JMSException { - initConnection(); - TopicSession topicSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - topic = topicSession.createTopic(TOPIC_NAME); - } + private void initTopic() throws JMSException { + initConnection(); + TopicSession topicSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); + topic = topicSession.createTopic(TOPIC_NAME); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2584ConcurrentDlqTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2584ConcurrentDlqTest.java index 3e41dc9a54..62d73f19ce 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2584ConcurrentDlqTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2584ConcurrentDlqTest.java @@ -31,6 +31,7 @@ import javax.jms.MessageListener; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TopicSubscriber; + import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; @@ -50,217 +51,214 @@ import org.slf4j.LoggerFactory; // the audit needs to be disabled to allow these dupes to be consumed public class AMQ2584ConcurrentDlqTest extends org.apache.activemq.TestSupport { - static final Logger LOG = LoggerFactory.getLogger(AMQ2584ConcurrentDlqTest.class); - BrokerService broker = null; - ActiveMQTopic topic; + static final Logger LOG = LoggerFactory.getLogger(AMQ2584ConcurrentDlqTest.class); + BrokerService broker = null; + ActiveMQTopic topic; - ActiveMQConnection consumerConnection = null, producerConnection = null, dlqConnection = null; - Session consumerSession; - Session producerSession; - MessageProducer producer; - Vector duralbeSubs = new Vector(); - final int numMessages = 1000; - final int numDurableSubs = 2; + ActiveMQConnection consumerConnection = null, producerConnection = null, dlqConnection = null; + Session consumerSession; + Session producerSession; + MessageProducer producer; + Vector duralbeSubs = new Vector(); + final int numMessages = 1000; + final int numDurableSubs = 2; - String data; - private long dlqConsumerLastReceivedTimeStamp; - private AtomicLong dlqReceivedCount = new AtomicLong(0); + String data; + private long dlqConsumerLastReceivedTimeStamp; + private AtomicLong dlqReceivedCount = new AtomicLong(0); - // 2 deliveries of each message, 3 producers - CountDownLatch redeliveryConsumerLatch = new CountDownLatch(((2 * numMessages) * numDurableSubs) - 1); - // should get at least numMessages, possibly more - CountDownLatch dlqConsumerLatch = new CountDownLatch((numMessages - 1)); + // 2 deliveries of each message, 3 producers + CountDownLatch redeliveryConsumerLatch = new CountDownLatch(((2 * numMessages) * numDurableSubs) - 1); + // should get at least numMessages, possibly more + CountDownLatch dlqConsumerLatch = new CountDownLatch((numMessages - 1)); - public void testSize() throws Exception { - openConsumer(redeliveryConsumerLatch); - openDlqConsumer(dlqConsumerLatch); + public void testSize() throws Exception { + openConsumer(redeliveryConsumerLatch); + openDlqConsumer(dlqConsumerLatch); + assertEquals(0, broker.getAdminView().getStorePercentUsage()); - assertEquals(0, broker.getAdminView().getStorePercentUsage()); + for (int i = 0; i < numMessages; i++) { + sendMessage(false); + } - for (int i = 0; i < numMessages; i++) { - sendMessage(false); - } + final BrokerView brokerView = broker.getAdminView(); - final BrokerView brokerView = broker.getAdminView(); + broker.getSystemUsage().getStoreUsage().isFull(); + LOG.info("store percent usage: " + brokerView.getStorePercentUsage()); + assertTrue("redelivery consumer got all it needs, remaining: " + redeliveryConsumerLatch.getCount(), redeliveryConsumerLatch.await(60, TimeUnit.SECONDS)); + assertTrue("dql consumer got all it needs", dlqConsumerLatch.await(60, TimeUnit.SECONDS)); + closeConsumer(); - broker.getSystemUsage().getStoreUsage().isFull(); - LOG.info("store percent usage: " + brokerView.getStorePercentUsage()); - assertTrue("redelivery consumer got all it needs, remaining: " - + redeliveryConsumerLatch.getCount(), redeliveryConsumerLatch.await(60, TimeUnit.SECONDS)); - assertTrue("dql consumer got all it needs", dlqConsumerLatch.await(60, TimeUnit.SECONDS)); - closeConsumer(); + LOG.info("Giving dlq a chance to clear down once topic consumer is closed"); - LOG.info("Giving dlq a chance to clear down once topic consumer is closed"); + // consumer all of the duplicates that arrived after the first ack + closeDlqConsumer(); - // consumer all of the duplicates that arrived after the first ack - closeDlqConsumer(); + //get broker a chance to clean obsolete messages, wait 2*cleanupInterval + Thread.sleep(5000); - //get broker a chance to clean obsolete messages, wait 2*cleanupInterval - Thread.sleep(5000); + FilenameFilter justLogFiles = new FilenameFilter() { + public boolean accept(File file, String s) { + return s.endsWith(".log"); + } + }; + int numFiles = ((KahaDBPersistenceAdapter) broker.getPersistenceAdapter()).getDirectory().list(justLogFiles).length; + if (numFiles > 2) { + LOG.info(Arrays.toString(((KahaDBPersistenceAdapter) broker.getPersistenceAdapter()).getDirectory().list(justLogFiles))); + } + LOG.info("num files: " + numFiles); + assertEquals("kahaDB dir should contain 1 db file,is: " + numFiles, 1, numFiles); + } - FilenameFilter justLogFiles = new FilenameFilter() { - public boolean accept(File file, String s) { - return s.endsWith(".log"); + private void openConsumer(final CountDownLatch latch) throws Exception { + consumerConnection = (ActiveMQConnection) createConnection(); + consumerConnection.setClientID("cliID"); + consumerConnection.start(); + consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + MessageListener listener = new MessageListener() { + public void onMessage(Message message) { + latch.countDown(); + try { + consumerSession.recover(); } - }; - int numFiles = ((KahaDBPersistenceAdapter) broker.getPersistenceAdapter()).getDirectory().list(justLogFiles).length; - if (numFiles > 2) { - LOG.info(Arrays.toString(((KahaDBPersistenceAdapter) broker.getPersistenceAdapter()).getDirectory().list(justLogFiles))); - } - LOG.info("num files: " + numFiles); - assertEquals("kahaDB dir should contain 1 db file,is: " + numFiles, 1, numFiles); - } - - private void openConsumer(final CountDownLatch latch) throws Exception { - consumerConnection = (ActiveMQConnection) createConnection(); - consumerConnection.setClientID("cliID"); - consumerConnection.start(); - consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageListener listener = new MessageListener() { - public void onMessage(Message message) { - latch.countDown(); - try { - consumerSession.recover(); - } catch (Exception ignored) { - ignored.printStackTrace(); - } + catch (Exception ignored) { + ignored.printStackTrace(); } - }; + } + }; - for (int i = 1; i <= numDurableSubs; i++) { - TopicSubscriber sub = consumerSession.createDurableSubscriber(topic, "subName" + i); - sub.setMessageListener(listener); - duralbeSubs.add(sub); - } - } + for (int i = 1; i <= numDurableSubs; i++) { + TopicSubscriber sub = consumerSession.createDurableSubscriber(topic, "subName" + i); + sub.setMessageListener(listener); + duralbeSubs.add(sub); + } + } - private void openDlqConsumer(final CountDownLatch received) throws Exception { + private void openDlqConsumer(final CountDownLatch received) throws Exception { - dlqConnection = (ActiveMQConnection) createConnection(); - Session dlqSession = dlqConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer dlqConsumer = dlqSession.createConsumer(new ActiveMQQueue("ActiveMQ.DLQ")); - dlqConsumer.setMessageListener(new MessageListener() { - public void onMessage(Message message) { - if (received.getCount() > 0 && received.getCount() % 200 == 0) { - LOG.info("remaining on DLQ: " + received.getCount()); - } - received.countDown(); - dlqConsumerLastReceivedTimeStamp = System.currentTimeMillis(); - dlqReceivedCount.incrementAndGet(); + dlqConnection = (ActiveMQConnection) createConnection(); + Session dlqSession = dlqConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer dlqConsumer = dlqSession.createConsumer(new ActiveMQQueue("ActiveMQ.DLQ")); + dlqConsumer.setMessageListener(new MessageListener() { + public void onMessage(Message message) { + if (received.getCount() > 0 && received.getCount() % 200 == 0) { + LOG.info("remaining on DLQ: " + received.getCount()); } - }); - dlqConnection.start(); - } + received.countDown(); + dlqConsumerLastReceivedTimeStamp = System.currentTimeMillis(); + dlqReceivedCount.incrementAndGet(); + } + }); + dlqConnection.start(); + } + private void closeConsumer() throws JMSException { + for (TopicSubscriber sub : duralbeSubs) { + sub.close(); + } + if (consumerSession != null) { + for (int i = 1; i <= numDurableSubs; i++) { + consumerSession.unsubscribe("subName" + i); + } + } + if (consumerConnection != null) { + consumerConnection.close(); + consumerConnection = null; + } + } - private void closeConsumer() throws JMSException { - for (TopicSubscriber sub : duralbeSubs) { - sub.close(); - } - if (consumerSession != null) { - for (int i = 1; i <= numDurableSubs; i++) { - consumerSession.unsubscribe("subName" + i); - } - } - if (consumerConnection != null) { - consumerConnection.close(); - consumerConnection = null; - } - } + private void closeDlqConsumer() throws JMSException, InterruptedException { + final long limit = System.currentTimeMillis() + 30 * 1000; + if (dlqConsumerLastReceivedTimeStamp > 0) { + while (System.currentTimeMillis() < dlqConsumerLastReceivedTimeStamp + 5000 && System.currentTimeMillis() < limit) { + LOG.info("waiting for DLQ do drain, receivedCount: " + dlqReceivedCount); + TimeUnit.SECONDS.sleep(1); + } + } + if (dlqConnection != null) { + dlqConnection.close(); + dlqConnection = null; + } + } - private void closeDlqConsumer() throws JMSException, InterruptedException { - final long limit = System.currentTimeMillis() + 30 * 1000; - if (dlqConsumerLastReceivedTimeStamp > 0) { - while (System.currentTimeMillis() < dlqConsumerLastReceivedTimeStamp + 5000 - && System.currentTimeMillis() < limit) { - LOG.info("waiting for DLQ do drain, receivedCount: " + dlqReceivedCount); - TimeUnit.SECONDS.sleep(1); - } - } - if (dlqConnection != null) { - dlqConnection.close(); - dlqConnection = null; - } - } + private void sendMessage(boolean filter) throws Exception { + if (producerConnection == null) { + producerConnection = (ActiveMQConnection) createConnection(); + producerConnection.start(); + producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer = producerSession.createProducer(topic); + } - private void sendMessage(boolean filter) throws Exception { - if (producerConnection == null) { - producerConnection = (ActiveMQConnection) createConnection(); - producerConnection.start(); - producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = producerSession.createProducer(topic); - } + Message message = producerSession.createMessage(); + message.setStringProperty("data", data); + producer.send(message); + } - Message message = producerSession.createMessage(); - message.setStringProperty("data", data); - producer.send(message); - } + private void startBroker(boolean deleteMessages) throws Exception { + broker = new BrokerService(); + broker.setAdvisorySupport(false); + broker.setBrokerName("testStoreSize"); - private void startBroker(boolean deleteMessages) throws Exception { - broker = new BrokerService(); - broker.setAdvisorySupport(false); - broker.setBrokerName("testStoreSize"); + PolicyMap map = new PolicyMap(); + PolicyEntry entry = new PolicyEntry(); + entry.setEnableAudit(false); + map.setDefaultEntry(entry); + broker.setDestinationPolicy(map); - PolicyMap map = new PolicyMap(); - PolicyEntry entry = new PolicyEntry(); - entry.setEnableAudit(false); - map.setDefaultEntry(entry); - broker.setDestinationPolicy(map); + if (deleteMessages) { + broker.setDeleteAllMessagesOnStartup(true); + } + configurePersistenceAdapter(broker.getPersistenceAdapter()); + broker.getSystemUsage().getStoreUsage().setLimit(200 * 1000 * 1000); + broker.start(); + } - if (deleteMessages) { - broker.setDeleteAllMessagesOnStartup(true); - } - configurePersistenceAdapter(broker.getPersistenceAdapter()); - broker.getSystemUsage().getStoreUsage().setLimit(200 * 1000 * 1000); - broker.start(); - } + private void configurePersistenceAdapter(PersistenceAdapter persistenceAdapter) { + Properties properties = new Properties(); + String maxFileLengthVal = String.valueOf(2 * 1024 * 1024); + properties.put("journalMaxFileLength", maxFileLengthVal); + properties.put("maxFileLength", maxFileLengthVal); + properties.put("cleanupInterval", "2000"); + properties.put("checkpointInterval", "2000"); + // there are problems with duplicate dispatch in the cursor, which maintain + // a map of messages. A dup dispatch can be dropped. + // see: org.apache.activemq.broker.region.cursors.OrderedPendingList + // Adding duplicate detection to the default DLQ strategy removes the problem + // which means we can leave the default for concurrent store and dispatch q + //properties.put("concurrentStoreAndDispatchQueues", "false"); - private void configurePersistenceAdapter(PersistenceAdapter persistenceAdapter) { - Properties properties = new Properties(); - String maxFileLengthVal = String.valueOf(2 * 1024 * 1024); - properties.put("journalMaxFileLength", maxFileLengthVal); - properties.put("maxFileLength", maxFileLengthVal); - properties.put("cleanupInterval", "2000"); - properties.put("checkpointInterval", "2000"); - // there are problems with duplicate dispatch in the cursor, which maintain - // a map of messages. A dup dispatch can be dropped. - // see: org.apache.activemq.broker.region.cursors.OrderedPendingList - // Adding duplicate detection to the default DLQ strategy removes the problem - // which means we can leave the default for concurrent store and dispatch q - //properties.put("concurrentStoreAndDispatchQueues", "false"); + IntrospectionSupport.setProperties(persistenceAdapter, properties); + } - IntrospectionSupport.setProperties(persistenceAdapter, properties); - } + private void stopBroker() throws Exception { + if (broker != null) + broker.stop(); + broker = null; + } - private void stopBroker() throws Exception { - if (broker != null) - broker.stop(); - broker = null; - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory("vm://testStoreSize?jms.watchTopicAdvisories=false&jms.redeliveryPolicy.maximumRedeliveries=1&jms.redeliveryPolicy.initialRedeliveryDelay=0&waitForStart=5000&create=false"); + } - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://testStoreSize?jms.watchTopicAdvisories=false&jms.redeliveryPolicy.maximumRedeliveries=1&jms.redeliveryPolicy.initialRedeliveryDelay=0&waitForStart=5000&create=false"); - } + @Override + protected void setUp() throws Exception { + super.setUp(); - @Override - protected void setUp() throws Exception { - super.setUp(); + StringBuilder sb = new StringBuilder(5000); + for (int i = 0; i < 5000; i++) { + sb.append('a'); + } + data = sb.toString(); - StringBuilder sb = new StringBuilder(5000); - for (int i = 0; i < 5000; i++) { - sb.append('a'); - } - data = sb.toString(); + startBroker(true); + topic = (ActiveMQTopic) createDestination(); + } - startBroker(true); - topic = (ActiveMQTopic) createDestination(); - } - - @Override - protected void tearDown() throws Exception { - stopBroker(); - super.tearDown(); - } + @Override + protected void tearDown() throws Exception { + stopBroker(); + super.tearDown(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2584Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2584Test.java index b84b9abc93..e772fe8a7d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2584Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2584Test.java @@ -51,183 +51,183 @@ import org.slf4j.LoggerFactory; @RunWith(value = Parameterized.class) public class AMQ2584Test extends org.apache.activemq.TestSupport { - static final Logger LOG = LoggerFactory.getLogger(AMQ2584Test.class); - BrokerService broker = null; - ActiveMQTopic topic; + static final Logger LOG = LoggerFactory.getLogger(AMQ2584Test.class); + BrokerService broker = null; + ActiveMQTopic topic; - ActiveMQConnection consumerConnection = null, producerConnection = null; - Session producerSession; - MessageProducer producer; - final int minPercentUsageForStore = 3; - String data; + ActiveMQConnection consumerConnection = null, producerConnection = null; + Session producerSession; + MessageProducer producer; + final int minPercentUsageForStore = 3; + String data; - private final TestSupport.PersistenceAdapterChoice persistenceAdapterChoice; + private final TestSupport.PersistenceAdapterChoice persistenceAdapterChoice; - @Parameterized.Parameters(name="{0}") - public static Collection getTestParameters() { - TestSupport.PersistenceAdapterChoice[] kahaDb = {TestSupport.PersistenceAdapterChoice.KahaDB}; - TestSupport.PersistenceAdapterChoice[] levelDb = {TestSupport.PersistenceAdapterChoice.LevelDB}; - List choices = new ArrayList(); - choices.add(kahaDb); - choices.add(levelDb); + @Parameterized.Parameters(name = "{0}") + public static Collection getTestParameters() { + TestSupport.PersistenceAdapterChoice[] kahaDb = {TestSupport.PersistenceAdapterChoice.KahaDB}; + TestSupport.PersistenceAdapterChoice[] levelDb = {TestSupport.PersistenceAdapterChoice.LevelDB}; + List choices = new ArrayList(); + choices.add(kahaDb); + choices.add(levelDb); - return choices; - } + return choices; + } - public AMQ2584Test(TestSupport.PersistenceAdapterChoice choice) { - this.persistenceAdapterChoice = choice; - } + public AMQ2584Test(TestSupport.PersistenceAdapterChoice choice) { + this.persistenceAdapterChoice = choice; + } - @Test(timeout = 120000) - public void testSize() throws Exception { - int messages = 1000; - CountDownLatch redeliveryConsumerLatch = new CountDownLatch((messages*3)); - openConsumer(redeliveryConsumerLatch); + @Test(timeout = 120000) + public void testSize() throws Exception { + int messages = 1000; + CountDownLatch redeliveryConsumerLatch = new CountDownLatch((messages * 3)); + openConsumer(redeliveryConsumerLatch); - assertEquals(0, broker.getAdminView().getStorePercentUsage()); + assertEquals(0, broker.getAdminView().getStorePercentUsage()); - for (int i = 0; i < messages; i++) { - sendMessage(false); - } + for (int i = 0; i < messages; i++) { + sendMessage(false); + } - final BrokerView brokerView = broker.getAdminView(); + final BrokerView brokerView = broker.getAdminView(); - broker.getSystemUsage().getStoreUsage().isFull(); - LOG.info("store percent usage: "+brokerView.getStorePercentUsage()); - int storePercentUsage = broker.getAdminView().getStorePercentUsage(); - assertTrue("some store in use", storePercentUsage > minPercentUsageForStore); + broker.getSystemUsage().getStoreUsage().isFull(); + LOG.info("store percent usage: " + brokerView.getStorePercentUsage()); + int storePercentUsage = broker.getAdminView().getStorePercentUsage(); + assertTrue("some store in use", storePercentUsage > minPercentUsageForStore); - assertTrue("redelivery consumer got all it needs", redeliveryConsumerLatch.await(60, TimeUnit.SECONDS)); - closeConsumer(); + assertTrue("redelivery consumer got all it needs", redeliveryConsumerLatch.await(60, TimeUnit.SECONDS)); + closeConsumer(); - // consume from DLQ - final CountDownLatch received = new CountDownLatch(messages); - consumerConnection = (ActiveMQConnection) createConnection(); - Session dlqSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer dlqConsumer = dlqSession.createConsumer(new ActiveMQQueue("ActiveMQ.DLQ")); - dlqConsumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - if (received.getCount() % 500 == 0) { - LOG.info("remaining on DLQ: " + received.getCount()); - } - received.countDown(); + // consume from DLQ + final CountDownLatch received = new CountDownLatch(messages); + consumerConnection = (ActiveMQConnection) createConnection(); + Session dlqSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer dlqConsumer = dlqSession.createConsumer(new ActiveMQQueue("ActiveMQ.DLQ")); + dlqConsumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + if (received.getCount() % 500 == 0) { + LOG.info("remaining on DLQ: " + received.getCount()); } - }); - consumerConnection.start(); + received.countDown(); + } + }); + consumerConnection.start(); - assertTrue("Not all messages reached the DLQ", received.await(60, TimeUnit.SECONDS)); + assertTrue("Not all messages reached the DLQ", received.await(60, TimeUnit.SECONDS)); - assertTrue("Store usage exceeds expected usage", - Wait.waitFor(new Wait.Condition() { + assertTrue("Store usage exceeds expected usage", Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisified() throws Exception { - broker.getSystemUsage().getStoreUsage().isFull(); - LOG.info("store precent usage: "+brokerView.getStorePercentUsage()); - return broker.getAdminView().getStorePercentUsage() < minPercentUsageForStore; + broker.getSystemUsage().getStoreUsage().isFull(); + LOG.info("store precent usage: " + brokerView.getStorePercentUsage()); + return broker.getAdminView().getStorePercentUsage() < minPercentUsageForStore; } - })); + })); - closeConsumer(); + closeConsumer(); - } + } - private void openConsumer(final CountDownLatch latch) throws Exception { - consumerConnection = (ActiveMQConnection) createConnection(); - consumerConnection.setClientID("cliID"); - consumerConnection.start(); - final Session session = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageListener listener = new MessageListener() { - @Override - public void onMessage(Message message) { - latch.countDown(); - try { - session.recover(); - } catch (Exception ignored) { - ignored.printStackTrace(); - } + private void openConsumer(final CountDownLatch latch) throws Exception { + consumerConnection = (ActiveMQConnection) createConnection(); + consumerConnection.setClientID("cliID"); + consumerConnection.start(); + final Session session = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageListener listener = new MessageListener() { + @Override + public void onMessage(Message message) { + latch.countDown(); + try { + session.recover(); + } + catch (Exception ignored) { + ignored.printStackTrace(); } - }; - session.createDurableSubscriber(topic, "subName1").setMessageListener(listener); - session.createDurableSubscriber(topic, "subName2").setMessageListener(listener); - session.createDurableSubscriber(topic, "subName3").setMessageListener(listener); - } + } + }; - private void closeConsumer() throws JMSException { - if (consumerConnection != null) - consumerConnection.close(); - consumerConnection = null; - } + session.createDurableSubscriber(topic, "subName1").setMessageListener(listener); + session.createDurableSubscriber(topic, "subName2").setMessageListener(listener); + session.createDurableSubscriber(topic, "subName3").setMessageListener(listener); + } - private void sendMessage(boolean filter) throws Exception { - if (producerConnection == null) { - producerConnection = (ActiveMQConnection) createConnection(); - producerConnection.start(); - producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = producerSession.createProducer(topic); - } + private void closeConsumer() throws JMSException { + if (consumerConnection != null) + consumerConnection.close(); + consumerConnection = null; + } - Message message = producerSession.createMessage(); - message.setStringProperty("data", data); - producer.send(message); - } + private void sendMessage(boolean filter) throws Exception { + if (producerConnection == null) { + producerConnection = (ActiveMQConnection) createConnection(); + producerConnection.start(); + producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer = producerSession.createProducer(topic); + } - private void startBroker(boolean deleteMessages) throws Exception { - broker = new BrokerService(); - broker.setAdvisorySupport(false); - broker.setBrokerName("testStoreSize"); + Message message = producerSession.createMessage(); + message.setStringProperty("data", data); + producer.send(message); + } - if (deleteMessages) { - broker.setDeleteAllMessagesOnStartup(true); - } - LOG.info("Starting broker with persistenceAdapterChoice " + persistenceAdapterChoice.toString()); - setPersistenceAdapter(broker, persistenceAdapterChoice); - configurePersistenceAdapter(broker.getPersistenceAdapter()); - broker.getSystemUsage().getStoreUsage().setLimit(200 * 1000 * 1000); - broker.start(); - } + private void startBroker(boolean deleteMessages) throws Exception { + broker = new BrokerService(); + broker.setAdvisorySupport(false); + broker.setBrokerName("testStoreSize"); - private void configurePersistenceAdapter(PersistenceAdapter persistenceAdapter) { - Properties properties = new Properties(); - String maxFileLengthVal = String.valueOf(1 * 1024 * 1024); - properties.put("journalMaxFileLength", maxFileLengthVal); - properties.put("maxFileLength", maxFileLengthVal); - properties.put("cleanupInterval", "2000"); - properties.put("checkpointInterval", "2000"); + if (deleteMessages) { + broker.setDeleteAllMessagesOnStartup(true); + } + LOG.info("Starting broker with persistenceAdapterChoice " + persistenceAdapterChoice.toString()); + setPersistenceAdapter(broker, persistenceAdapterChoice); + configurePersistenceAdapter(broker.getPersistenceAdapter()); + broker.getSystemUsage().getStoreUsage().setLimit(200 * 1000 * 1000); + broker.start(); + } - IntrospectionSupport.setProperties(persistenceAdapter, properties); - } + private void configurePersistenceAdapter(PersistenceAdapter persistenceAdapter) { + Properties properties = new Properties(); + String maxFileLengthVal = String.valueOf(1 * 1024 * 1024); + properties.put("journalMaxFileLength", maxFileLengthVal); + properties.put("maxFileLength", maxFileLengthVal); + properties.put("cleanupInterval", "2000"); + properties.put("checkpointInterval", "2000"); - private void stopBroker() throws Exception { - if (broker != null) - broker.stop(); - broker = null; - } + IntrospectionSupport.setProperties(persistenceAdapter, properties); + } - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://testStoreSize?jms.watchTopicAdvisories=false&jms.redeliveryPolicy.maximumRedeliveries=0&jms.closeTimeout=60000&waitForStart=5000&create=false"); - } + private void stopBroker() throws Exception { + if (broker != null) + broker.stop(); + broker = null; + } - @Override - @Before - public void setUp() throws Exception { - StringBuilder sb = new StringBuilder(5000); - for (int i = 0; i < 5000; i++) { - sb.append('a'); - } - data = sb.toString(); + @Override + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory("vm://testStoreSize?jms.watchTopicAdvisories=false&jms.redeliveryPolicy.maximumRedeliveries=0&jms.closeTimeout=60000&waitForStart=5000&create=false"); + } - startBroker(true); - topic = (ActiveMQTopic) createDestination(); - } + @Override + @Before + public void setUp() throws Exception { + StringBuilder sb = new StringBuilder(5000); + for (int i = 0; i < 5000; i++) { + sb.append('a'); + } + data = sb.toString(); - @Override - @After - public void tearDown() throws Exception { - stopBroker(); - } + startBroker(true); + topic = (ActiveMQTopic) createDestination(); + } + + @Override + @After + public void tearDown() throws Exception { + stopBroker(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2585Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2585Test.java index 3f515d9031..71cb2a80fd 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2585Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2585Test.java @@ -31,53 +31,52 @@ import org.apache.activemq.command.Message; import org.apache.activemq.spring.ConsumerBean; public class AMQ2585Test extends EmbeddedBrokerAndConnectionTestSupport { - private final Destination destination = new ActiveMQQueue("MyQueue"); - final static String LENGTH10STRING = "1234567890"; - private Session session; - private MessageProducer producer; - private ConsumerBean messageList; - public void testOneMessageWithProperties() throws Exception { - TextMessage message = session.createTextMessage(LENGTH10STRING); - message.setStringProperty(LENGTH10STRING, LENGTH10STRING); - producer.send(message); + private final Destination destination = new ActiveMQQueue("MyQueue"); + final static String LENGTH10STRING = "1234567890"; + private Session session; + private MessageProducer producer; + private ConsumerBean messageList; - messageList.assertMessagesArrived(1); + public void testOneMessageWithProperties() throws Exception { + TextMessage message = session.createTextMessage(LENGTH10STRING); + message.setStringProperty(LENGTH10STRING, LENGTH10STRING); + producer.send(message); - ActiveMQTextMessage received = ((ActiveMQTextMessage) messageList - .flushMessages().get(0)); + messageList.assertMessagesArrived(1); - assertEquals(LENGTH10STRING, received.getText()); - assertTrue(received.getProperties().size() > 0); - assertTrue(received.propertyExists(LENGTH10STRING)); - assertEquals(LENGTH10STRING, received.getStringProperty(LENGTH10STRING)); + ActiveMQTextMessage received = ((ActiveMQTextMessage) messageList.flushMessages().get(0)); - /** - * As specified by getSize(), the size (memory usage) of the body should - * be length of text * 2. Unsure of how memory usage is calculated for - * properties, but should probably not be less than the sum of (string) - * lengths for the key name and value. - */ + assertEquals(LENGTH10STRING, received.getText()); + assertTrue(received.getProperties().size() > 0); + assertTrue(received.propertyExists(LENGTH10STRING)); + assertEquals(LENGTH10STRING, received.getStringProperty(LENGTH10STRING)); - final int sizeShouldBeNoLessThan = LENGTH10STRING.length() * 4 + Message.DEFAULT_MINIMUM_MESSAGE_SIZE; - assertTrue("Message size was smaller than expected: " + received.getSize(), - received.getSize() >= sizeShouldBeNoLessThan); - assertFalse(LENGTH10STRING.length() * 2 == received.getSize()); - } + /** + * As specified by getSize(), the size (memory usage) of the body should + * be length of text * 2. Unsure of how memory usage is calculated for + * properties, but should probably not be less than the sum of (string) + * lengths for the key name and value. + */ - @Override - protected void setUp() throws Exception { - bindAddress = bindAddress + "?marshal=true"; - super.setUp(); - messageList = new ConsumerBean(); - messageList.setVerbose(true); + final int sizeShouldBeNoLessThan = LENGTH10STRING.length() * 4 + Message.DEFAULT_MINIMUM_MESSAGE_SIZE; + assertTrue("Message size was smaller than expected: " + received.getSize(), received.getSize() >= sizeShouldBeNoLessThan); + assertFalse(LENGTH10STRING.length() * 2 == received.getSize()); + } - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + @Override + protected void setUp() throws Exception { + bindAddress = bindAddress + "?marshal=true"; + super.setUp(); + messageList = new ConsumerBean(); + messageList.setVerbose(true); - MessageConsumer messageConsumer = session.createConsumer(destination); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - messageConsumer.setMessageListener(messageList); + MessageConsumer messageConsumer = session.createConsumer(destination); - producer = session.createProducer(destination); - } + messageConsumer.setMessageListener(messageList); + + producer = session.createProducer(destination); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2616Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2616Test.java index 4f6f16816e..3181e4bdb7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2616Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2616Test.java @@ -24,7 +24,9 @@ import javax.jms.Connection; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; + import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.region.policy.FilePendingQueueMessageStoragePolicy; @@ -35,82 +37,82 @@ import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; import org.apache.activemq.util.IOHelper; public class AMQ2616Test extends TestCase { - private static final int NUMBER = 2000; - private BrokerService brokerService; - private final ArrayList threads = new ArrayList(); - private final String ACTIVEMQ_BROKER_BIND = "tcp://0.0.0.0:0"; - private final AtomicBoolean shutdown = new AtomicBoolean(); - private String connectionUri; + private static final int NUMBER = 2000; + private BrokerService brokerService; + private final ArrayList threads = new ArrayList(); + private final String ACTIVEMQ_BROKER_BIND = "tcp://0.0.0.0:0"; + private final AtomicBoolean shutdown = new AtomicBoolean(); - public void testQueueResourcesReleased() throws Exception{ - ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory(connectionUri); - Connection tempConnection = fac.createConnection(); - tempConnection.start(); - Session tempSession = tempConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue tempQueue = tempSession.createTemporaryQueue(); + private String connectionUri; - Connection testConnection = fac.createConnection(); - long startUsage = brokerService.getSystemUsage().getMemoryUsage().getUsage(); - Session testSession = testConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer testProducer = testSession.createProducer(tempQueue); - byte[] payload = new byte[1024*4]; - for (int i = 0; i < NUMBER; i++ ) { - BytesMessage msg = testSession.createBytesMessage(); - msg.writeBytes(payload); - testProducer.send(msg); - } - long endUsage = brokerService.getSystemUsage().getMemoryUsage().getUsage(); - assertFalse(startUsage==endUsage); - tempConnection.close(); - Thread.sleep(1000); - endUsage = brokerService.getSystemUsage().getMemoryUsage().getUsage(); - assertEquals(startUsage,endUsage); - } + public void testQueueResourcesReleased() throws Exception { + ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory(connectionUri); + Connection tempConnection = fac.createConnection(); + tempConnection.start(); + Session tempSession = tempConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue tempQueue = tempSession.createTemporaryQueue(); + Connection testConnection = fac.createConnection(); + long startUsage = brokerService.getSystemUsage().getMemoryUsage().getUsage(); + Session testSession = testConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer testProducer = testSession.createProducer(tempQueue); + byte[] payload = new byte[1024 * 4]; + for (int i = 0; i < NUMBER; i++) { + BytesMessage msg = testSession.createBytesMessage(); + msg.writeBytes(payload); + testProducer.send(msg); + } + long endUsage = brokerService.getSystemUsage().getMemoryUsage().getUsage(); + assertFalse(startUsage == endUsage); + tempConnection.close(); + Thread.sleep(1000); + endUsage = brokerService.getSystemUsage().getMemoryUsage().getUsage(); + assertEquals(startUsage, endUsage); + } - @Override - protected void setUp() throws Exception { - // Start an embedded broker up. - brokerService = new BrokerService(); + @Override + protected void setUp() throws Exception { + // Start an embedded broker up. + brokerService = new BrokerService(); - KahaDBPersistenceAdapter adaptor = new KahaDBPersistenceAdapter(); - adaptor.setEnableJournalDiskSyncs(false); - File file = new File("target/AMQ2616Test"); - IOHelper.mkdirs(file); - IOHelper.deleteChildren(file); - adaptor.setDirectory(file); - brokerService.setPersistenceAdapter(adaptor); + KahaDBPersistenceAdapter adaptor = new KahaDBPersistenceAdapter(); + adaptor.setEnableJournalDiskSyncs(false); + File file = new File("target/AMQ2616Test"); + IOHelper.mkdirs(file); + IOHelper.deleteChildren(file); + adaptor.setDirectory(file); + brokerService.setPersistenceAdapter(adaptor); - PolicyMap policyMap = new PolicyMap(); - PolicyEntry pe = new PolicyEntry(); - pe.setMemoryLimit(10 * 1024 * 1024); - pe.setOptimizedDispatch(true); - pe.setProducerFlowControl(false); - pe.setExpireMessagesPeriod(1000); - pe.setPendingQueuePolicy(new FilePendingQueueMessageStoragePolicy()); - policyMap.put(new ActiveMQQueue(">"), pe); - brokerService.setDestinationPolicy(policyMap); - brokerService.getSystemUsage().getMemoryUsage().setLimit(20 * 1024 * 1024); - brokerService.getSystemUsage().getTempUsage().setLimit(200 * 1024 * 1024); - brokerService.addConnector(ACTIVEMQ_BROKER_BIND); - brokerService.start(); - brokerService.waitUntilStarted(); + PolicyMap policyMap = new PolicyMap(); + PolicyEntry pe = new PolicyEntry(); + pe.setMemoryLimit(10 * 1024 * 1024); + pe.setOptimizedDispatch(true); + pe.setProducerFlowControl(false); + pe.setExpireMessagesPeriod(1000); + pe.setPendingQueuePolicy(new FilePendingQueueMessageStoragePolicy()); + policyMap.put(new ActiveMQQueue(">"), pe); + brokerService.setDestinationPolicy(policyMap); + brokerService.getSystemUsage().getMemoryUsage().setLimit(20 * 1024 * 1024); + brokerService.getSystemUsage().getTempUsage().setLimit(200 * 1024 * 1024); + brokerService.addConnector(ACTIVEMQ_BROKER_BIND); + brokerService.start(); + brokerService.waitUntilStarted(); - connectionUri = brokerService.getTransportConnectors().get(0).getPublishableConnectString(); + connectionUri = brokerService.getTransportConnectors().get(0).getPublishableConnectString(); - new ActiveMQQueue(getName()); - } + new ActiveMQQueue(getName()); + } - @Override - protected void tearDown() throws Exception { - // Stop any running threads. - shutdown.set(true); - for (Thread t : threads) { - t.interrupt(); - t.join(); - } - brokerService.stop(); - } + @Override + protected void tearDown() throws Exception { + // Stop any running threads. + shutdown.set(true); + for (Thread t : threads) { + t.interrupt(); + t.join(); + } + brokerService.stop(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2645Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2645Test.java index 2ac6ff3f37..6f7c5da2db 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2645Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2645Test.java @@ -36,74 +36,76 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AMQ2645Test extends EmbeddedBrokerTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(AMQ2645Test.class); - private final static String QUEUE_NAME = "test.daroo.q"; - public void testWaitForTransportInterruptionProcessingHang() - throws Exception { - final ConnectionFactory fac = new ActiveMQConnectionFactory( - "failover:(" + this.bindAddress + ")"); - final Connection connection = fac.createConnection(); - try { - final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final Queue queue = session.createQueue(QUEUE_NAME); - final MessageProducer producer = session.createProducer(queue); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - connection.start(); + private static final Logger LOG = LoggerFactory.getLogger(AMQ2645Test.class); + private final static String QUEUE_NAME = "test.daroo.q"; - producer.send(session.createTextMessage("test")); + public void testWaitForTransportInterruptionProcessingHang() throws Exception { + final ConnectionFactory fac = new ActiveMQConnectionFactory("failover:(" + this.bindAddress + ")"); + final Connection connection = fac.createConnection(); + try { + final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final Queue queue = session.createQueue(QUEUE_NAME); + final MessageProducer producer = session.createProducer(queue); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + connection.start(); - final CountDownLatch afterRestart = new CountDownLatch(1); - final CountDownLatch twoNewMessages = new CountDownLatch(1); - final CountDownLatch thirdMessageReceived = new CountDownLatch(1); + producer.send(session.createTextMessage("test")); - final MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME)); - consumer.setMessageListener(new MessageListener() { - public void onMessage(Message message) { - try { - afterRestart.await(); + final CountDownLatch afterRestart = new CountDownLatch(1); + final CountDownLatch twoNewMessages = new CountDownLatch(1); + final CountDownLatch thirdMessageReceived = new CountDownLatch(1); - final TextMessage txtMsg = (TextMessage) message; - if (txtMsg.getText().equals("test")) { - producer.send(session.createTextMessage("test 1")); - TimeUnit.SECONDS.sleep(5); - // THIS SECOND send() WILL CAUSE CONSUMER DEADLOCK - producer.send(session.createTextMessage("test 2")); - LOG.info("Two new messages produced."); - twoNewMessages.countDown(); - } else if (txtMsg.getText().equals("test 3")) { - thirdMessageReceived.countDown(); - } - } catch (Exception e) { - LOG.error(e.toString()); - throw new RuntimeException(e); - } - } - }); + final MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME)); + consumer.setMessageListener(new MessageListener() { + public void onMessage(Message message) { + try { + afterRestart.await(); - LOG.info("Stopping broker...."); - broker.stop(); + final TextMessage txtMsg = (TextMessage) message; + if (txtMsg.getText().equals("test")) { + producer.send(session.createTextMessage("test 1")); + TimeUnit.SECONDS.sleep(5); + // THIS SECOND send() WILL CAUSE CONSUMER DEADLOCK + producer.send(session.createTextMessage("test 2")); + LOG.info("Two new messages produced."); + twoNewMessages.countDown(); + } + else if (txtMsg.getText().equals("test 3")) { + thirdMessageReceived.countDown(); + } + } + catch (Exception e) { + LOG.error(e.toString()); + throw new RuntimeException(e); + } + } + }); - LOG.info("Creating new broker..."); - broker = createBroker(); - startBroker(); - broker.waitUntilStarted(); + LOG.info("Stopping broker...."); + broker.stop(); - afterRestart.countDown(); - assertTrue("Consumer is deadlocked!", twoNewMessages.await(60, TimeUnit.SECONDS)); + LOG.info("Creating new broker..."); + broker = createBroker(); + startBroker(); + broker.waitUntilStarted(); - producer.send(session.createTextMessage("test 3")); - assertTrue("Consumer got third message after block", thirdMessageReceived.await(60, TimeUnit.SECONDS)); + afterRestart.countDown(); + assertTrue("Consumer is deadlocked!", twoNewMessages.await(60, TimeUnit.SECONDS)); - } finally { - broker.stop(); - } + producer.send(session.createTextMessage("test 3")); + assertTrue("Consumer got third message after block", thirdMessageReceived.await(60, TimeUnit.SECONDS)); - } + } + finally { + broker.stop(); + } - @Override - protected void setUp() throws Exception { - bindAddress = "tcp://0.0.0.0:61617"; - super.setUp(); - } + } + + @Override + protected void setUp() throws Exception { + bindAddress = "tcp://0.0.0.0:61617"; + super.setUp(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2736Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2736Test.java index e5845725ad..533b8277dd 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2736Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2736Test.java @@ -19,6 +19,7 @@ package org.apache.activemq.bugs; import javax.jms.Connection; import javax.jms.MessageProducer; import javax.jms.Session; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.command.ActiveMQQueue; @@ -28,69 +29,70 @@ import org.apache.activemq.util.DefaultIOExceptionHandler; import org.junit.After; import org.junit.Test; - import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; public class AMQ2736Test { - BrokerService broker; - @Test - public void testRollbackOnRecover() throws Exception { - broker = createAndStartBroker(true); - DefaultIOExceptionHandler ignoreAllExceptionsIOExHandler = new DefaultIOExceptionHandler(); - ignoreAllExceptionsIOExHandler.setIgnoreAllErrors(true); - broker.setIoExceptionHandler(ignoreAllExceptionsIOExHandler); + BrokerService broker; - ActiveMQConnectionFactory f = new ActiveMQConnectionFactory("vm://localhost?async=false"); - f.setAlwaysSyncSend(true); - Connection c = f.createConnection(); - c.start(); - Session s = c.createSession(true, Session.SESSION_TRANSACTED); - MessageProducer p = s.createProducer(new ActiveMQQueue("Tx")); - p.send(s.createTextMessage("aa")); + @Test + public void testRollbackOnRecover() throws Exception { + broker = createAndStartBroker(true); + DefaultIOExceptionHandler ignoreAllExceptionsIOExHandler = new DefaultIOExceptionHandler(); + ignoreAllExceptionsIOExHandler.setIgnoreAllErrors(true); + broker.setIoExceptionHandler(ignoreAllExceptionsIOExHandler); - // kill journal without commit - KahaDBPersistenceAdapter pa = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); - KahaDBStore store = pa.getStore(); + ActiveMQConnectionFactory f = new ActiveMQConnectionFactory("vm://localhost?async=false"); + f.setAlwaysSyncSend(true); + Connection c = f.createConnection(); + c.start(); + Session s = c.createSession(true, Session.SESSION_TRANSACTED); + MessageProducer p = s.createProducer(new ActiveMQQueue("Tx")); + p.send(s.createTextMessage("aa")); - assertNotNull("last tx location is present " + store.getInProgressTxLocationRange()[1]); + // kill journal without commit + KahaDBPersistenceAdapter pa = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); + KahaDBStore store = pa.getStore(); - // test hack, close the journal to ensure no further journal updates when broker stops - // mimic kill -9 in terms of no normal shutdown sequence - store.getJournal().close(); - try { - store.close(); - } catch (Exception expectedLotsAsJournalBorked) { - } + assertNotNull("last tx location is present " + store.getInProgressTxLocationRange()[1]); - broker.stop(); - broker.waitUntilStopped(); + // test hack, close the journal to ensure no further journal updates when broker stops + // mimic kill -9 in terms of no normal shutdown sequence + store.getJournal().close(); + try { + store.close(); + } + catch (Exception expectedLotsAsJournalBorked) { + } - // restart with recovery - broker = createAndStartBroker(false); + broker.stop(); + broker.waitUntilStopped(); - pa = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); - store = pa.getStore(); + // restart with recovery + broker = createAndStartBroker(false); - // inflight non xa tx should be rolledback on recovery - assertNull("in progress tx location is present ", store.getInProgressTxLocationRange()[0]); + pa = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); + store = pa.getStore(); - } + // inflight non xa tx should be rolledback on recovery + assertNull("in progress tx location is present ", store.getInProgressTxLocationRange()[0]); - @After - public void stopBroker() throws Exception { - if (broker != null) { - broker.stop(); - } - } + } - private BrokerService createAndStartBroker(boolean deleteAll) throws Exception { - BrokerService broker = new BrokerService(); - broker.setDeleteAllMessagesOnStartup(deleteAll); - broker.setUseJmx(false); - broker.getManagementContext().setCreateConnector(false); - broker.start(); - return broker; - } + @After + public void stopBroker() throws Exception { + if (broker != null) { + broker.stop(); + } + } + + private BrokerService createAndStartBroker(boolean deleteAll) throws Exception { + BrokerService broker = new BrokerService(); + broker.setDeleteAllMessagesOnStartup(deleteAll); + broker.setUseJmx(false); + broker.getManagementContext().setCreateConnector(false); + broker.start(); + return broker; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2751Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2751Test.java index b52f5c0dac..80b6cfa9e7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2751Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2751Test.java @@ -34,61 +34,63 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AMQ2751Test extends EmbeddedBrokerTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(AMQ2751Test.class); - private static String clientIdPrefix = "consumer"; - private static String queueName = "FOO"; + private static final Logger LOG = LoggerFactory.getLogger(AMQ2751Test.class); - public void testRecoverRedelivery() throws Exception { + private static String clientIdPrefix = "consumer"; + private static String queueName = "FOO"; - final CountDownLatch redelivery = new CountDownLatch(6); - final ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory( - "failover:(" + broker.getTransportConnectors().get(0).getConnectUri() + ")"); - try { + public void testRecoverRedelivery() throws Exception { - Connection connection = factory.createConnection(); - String clientId = clientIdPrefix; - connection.setClientID(clientId); + final CountDownLatch redelivery = new CountDownLatch(6); + final ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("failover:(" + broker.getTransportConnectors().get(0).getConnectUri() + ")"); + try { - final Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Connection connection = factory.createConnection(); + String clientId = clientIdPrefix; + connection.setClientID(clientId); - Queue queue = session.createQueue(queueName); + final Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(queue); + Queue queue = session.createQueue(queueName); - consumer.setMessageListener(new MessageListener() { - public void onMessage(Message message) { - try { - LOG.info("Got message: " + message.getJMSMessageID()); - if (message.getJMSRedelivered()) { - LOG.info("It's a redelivery."); - redelivery.countDown(); - } - LOG.info("calling recover() on the session to force redelivery."); - session.recover(); - } catch (JMSException e) { - e.printStackTrace(); - } - } - }); + MessageConsumer consumer = session.createConsumer(queue); - System.out.println("Created queue consumer with clientId " + clientId); - connection.start(); + consumer.setMessageListener(new MessageListener() { + public void onMessage(Message message) { + try { + LOG.info("Got message: " + message.getJMSMessageID()); + if (message.getJMSRedelivered()) { + LOG.info("It's a redelivery."); + redelivery.countDown(); + } + LOG.info("calling recover() on the session to force redelivery."); + session.recover(); + } + catch (JMSException e) { + e.printStackTrace(); + } + } + }); - MessageProducer producer = session.createProducer(queue); - producer.send(session.createTextMessage("test")); + System.out.println("Created queue consumer with clientId " + clientId); + connection.start(); - assertTrue("we got 6 redeliveries", redelivery.await(20, TimeUnit.SECONDS)); + MessageProducer producer = session.createProducer(queue); + producer.send(session.createTextMessage("test")); - } finally { - broker.stop(); - } + assertTrue("we got 6 redeliveries", redelivery.await(20, TimeUnit.SECONDS)); - } + } + finally { + broker.stop(); + } - @Override - protected void setUp() throws Exception { - bindAddress = "tcp://localhost:0"; - super.setUp(); - } + } + + @Override + protected void setUp() throws Exception { + bindAddress = "tcp://localhost:0"; + super.setUp(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2801Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2801Test.java index a1d0bc1cdf..02b28117ae 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2801Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2801Test.java @@ -47,155 +47,153 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class AMQ2801Test -{ - private static final Logger LOG = LoggerFactory.getLogger(AMQ2801Test.class); +public class AMQ2801Test { - private static final String TOPICNAME = "InvalidPendingQueueTest"; - private static final String SELECTOR1 = "JMS_ID" + " = '" + "TEST" + "'"; - private static final String SELECTOR2 = "JMS_ID" + " = '" + "TEST2" + "'"; - private static final String SUBSCRIPTION1 = "InvalidPendingQueueTest_1"; - private static final String SUBSCRIPTION2 = "InvalidPendingQueueTest_2"; - private static final int MSG_COUNT = 2500; - private Session session1; - private Connection conn1; - private Topic topic1; - private MessageConsumer consumer1; - private Session session2; - private Connection conn2; - private Topic topic2; - private MessageConsumer consumer2; - private BrokerService broker; - private String connectionUri; + private static final Logger LOG = LoggerFactory.getLogger(AMQ2801Test.class); - @Before - public void setUp() throws Exception { - broker = new BrokerService(); - broker.setDataDirectory("target" + File.separator + "activemq-data"); - broker.setPersistent(true); - broker.setUseJmx(true); - broker.setAdvisorySupport(false); - broker.setDeleteAllMessagesOnStartup(true); - broker.addConnector("tcp://localhost:0").setName("Default"); - applyMemoryLimitPolicy(broker); - broker.start(); + private static final String TOPICNAME = "InvalidPendingQueueTest"; + private static final String SELECTOR1 = "JMS_ID" + " = '" + "TEST" + "'"; + private static final String SELECTOR2 = "JMS_ID" + " = '" + "TEST2" + "'"; + private static final String SUBSCRIPTION1 = "InvalidPendingQueueTest_1"; + private static final String SUBSCRIPTION2 = "InvalidPendingQueueTest_2"; + private static final int MSG_COUNT = 2500; + private Session session1; + private Connection conn1; + private Topic topic1; + private MessageConsumer consumer1; + private Session session2; + private Connection conn2; + private Topic topic2; + private MessageConsumer consumer2; + private BrokerService broker; + private String connectionUri; - connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); - } + @Before + public void setUp() throws Exception { + broker = new BrokerService(); + broker.setDataDirectory("target" + File.separator + "activemq-data"); + broker.setPersistent(true); + broker.setUseJmx(true); + broker.setAdvisorySupport(false); + broker.setDeleteAllMessagesOnStartup(true); + broker.addConnector("tcp://localhost:0").setName("Default"); + applyMemoryLimitPolicy(broker); + broker.start(); - private void applyMemoryLimitPolicy(BrokerService broker) { - final SystemUsage memoryManager = new SystemUsage(); - memoryManager.getMemoryUsage().setLimit(5818230784L); - memoryManager.getStoreUsage().setLimit(6442450944L); - memoryManager.getTempUsage().setLimit(3221225472L); - broker.setSystemUsage(memoryManager); + connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); + } - final List policyEntries = new ArrayList(); - final PolicyEntry entry = new PolicyEntry(); - entry.setQueue(">"); - entry.setProducerFlowControl(false); - entry.setMemoryLimit(504857608); - entry.setPendingQueuePolicy(new FilePendingQueueMessageStoragePolicy()); - policyEntries.add(entry); + private void applyMemoryLimitPolicy(BrokerService broker) { + final SystemUsage memoryManager = new SystemUsage(); + memoryManager.getMemoryUsage().setLimit(5818230784L); + memoryManager.getStoreUsage().setLimit(6442450944L); + memoryManager.getTempUsage().setLimit(3221225472L); + broker.setSystemUsage(memoryManager); - final PolicyMap policyMap = new PolicyMap(); - policyMap.setPolicyEntries(policyEntries); - broker.setDestinationPolicy(policyMap); - } + final List policyEntries = new ArrayList(); + final PolicyEntry entry = new PolicyEntry(); + entry.setQueue(">"); + entry.setProducerFlowControl(false); + entry.setMemoryLimit(504857608); + entry.setPendingQueuePolicy(new FilePendingQueueMessageStoragePolicy()); + policyEntries.add(entry); - @After - public void tearDown() throws Exception { - conn1.close(); - conn2.close(); - if (broker != null) { - broker.stop(); - } - } + final PolicyMap policyMap = new PolicyMap(); + policyMap.setPolicyEntries(policyEntries); + broker.setDestinationPolicy(policyMap); + } - private void produceMessages() throws Exception { - TopicConnection connection = createConnection(); - TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic(TOPICNAME); - TopicPublisher producer = session.createPublisher(topic); - connection.start(); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - long tStamp = System.currentTimeMillis(); - BytesMessage message = session2.createBytesMessage(); - for (int i = 1; i <= MSG_COUNT; i++) - { - message.setStringProperty("JMS_ID", "TEST"); - message.setIntProperty("Type", i); - producer.publish(message); - if (i%100 == 0) { - LOG.info("sent: " + i + " @ " + ((System.currentTimeMillis() - tStamp) / 100) + "m/ms"); - tStamp = System.currentTimeMillis() ; - } - } - } + @After + public void tearDown() throws Exception { + conn1.close(); + conn2.close(); + if (broker != null) { + broker.stop(); + } + } - private void activeateSubscribers() throws Exception { - // First consumer - conn1 = createConnection(); - conn1.setClientID(SUBSCRIPTION1); - session1 = conn1.createSession(true, Session.SESSION_TRANSACTED); - topic1 = session1.createTopic(TOPICNAME); - consumer1 = session1.createDurableSubscriber(topic1, SUBSCRIPTION1, SELECTOR1, false); - conn1.start(); + private void produceMessages() throws Exception { + TopicConnection connection = createConnection(); + TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); + Topic topic = session.createTopic(TOPICNAME); + TopicPublisher producer = session.createPublisher(topic); + connection.start(); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + long tStamp = System.currentTimeMillis(); + BytesMessage message = session2.createBytesMessage(); + for (int i = 1; i <= MSG_COUNT; i++) { + message.setStringProperty("JMS_ID", "TEST"); + message.setIntProperty("Type", i); + producer.publish(message); + if (i % 100 == 0) { + LOG.info("sent: " + i + " @ " + ((System.currentTimeMillis() - tStamp) / 100) + "m/ms"); + tStamp = System.currentTimeMillis(); + } + } + } - // Second consumer that just exists - conn2 = createConnection(); - conn2.setClientID(SUBSCRIPTION2); - session2 = conn2.createSession(true, Session.SESSION_TRANSACTED); - topic2 = session2.createTopic(TOPICNAME); - consumer2 = session2.createDurableSubscriber(topic2, SUBSCRIPTION2, SELECTOR2, false); - conn2.start(); - } + private void activeateSubscribers() throws Exception { + // First consumer + conn1 = createConnection(); + conn1.setClientID(SUBSCRIPTION1); + session1 = conn1.createSession(true, Session.SESSION_TRANSACTED); + topic1 = session1.createTopic(TOPICNAME); + consumer1 = session1.createDurableSubscriber(topic1, SUBSCRIPTION1, SELECTOR1, false); + conn1.start(); - @Test - public void testInvalidPendingQueue() throws Exception { + // Second consumer that just exists + conn2 = createConnection(); + conn2.setClientID(SUBSCRIPTION2); + session2 = conn2.createSession(true, Session.SESSION_TRANSACTED); + topic2 = session2.createTopic(TOPICNAME); + consumer2 = session2.createDurableSubscriber(topic2, SUBSCRIPTION2, SELECTOR2, false); + conn2.start(); + } - activeateSubscribers(); + @Test + public void testInvalidPendingQueue() throws Exception { - assertNotNull(consumer1); - assertNotNull(consumer2); + activeateSubscribers(); - produceMessages(); - LOG.debug("Sent messages to a single subscriber"); - Thread.sleep(2000); + assertNotNull(consumer1); + assertNotNull(consumer2); - LOG.debug("Closing durable subscriber connections"); - conn1.close(); - conn2.close(); - LOG.debug("Closed durable subscriber connections"); + produceMessages(); + LOG.debug("Sent messages to a single subscriber"); + Thread.sleep(2000); - Thread.sleep(2000); - LOG.debug("Re-starting durable subscriber connections"); + LOG.debug("Closing durable subscriber connections"); + conn1.close(); + conn2.close(); + LOG.debug("Closed durable subscriber connections"); - activeateSubscribers(); - LOG.debug("Started up durable subscriber connections - now view activemq console to see pending queue size on the other subscriber"); + Thread.sleep(2000); + LOG.debug("Re-starting durable subscriber connections"); - ObjectName[] subs = broker.getAdminView().getDurableTopicSubscribers(); + activeateSubscribers(); + LOG.debug("Started up durable subscriber connections - now view activemq console to see pending queue size on the other subscriber"); - for (int i = 0; i < subs.length; i++) { - ObjectName subName = subs[i]; - DurableSubscriptionViewMBean sub = (DurableSubscriptionViewMBean) - broker.getManagementContext().newProxyInstance(subName, DurableSubscriptionViewMBean.class, true); + ObjectName[] subs = broker.getAdminView().getDurableTopicSubscribers(); - LOG.info(sub.getSubscriptionName() + ": pending = " + sub.getPendingQueueSize() + ", dispatched: " + sub.getDispatchedQueueSize()); - if(sub.getSubscriptionName().equals(SUBSCRIPTION1)) { - assertEquals("Incorrect number of pending messages", MSG_COUNT, sub.getPendingQueueSize() + sub.getDispatchedQueueSize()); - } else { - assertEquals("Incorrect number of pending messages", 0, sub.getPendingQueueSize()); - } - } - } + for (int i = 0; i < subs.length; i++) { + ObjectName subName = subs[i]; + DurableSubscriptionViewMBean sub = (DurableSubscriptionViewMBean) broker.getManagementContext().newProxyInstance(subName, DurableSubscriptionViewMBean.class, true); - private TopicConnection createConnection() throws Exception - { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); - connectionFactory.setBrokerURL(connectionUri); - TopicConnection conn = connectionFactory.createTopicConnection(); - return conn; - } + LOG.info(sub.getSubscriptionName() + ": pending = " + sub.getPendingQueueSize() + ", dispatched: " + sub.getDispatchedQueueSize()); + if (sub.getSubscriptionName().equals(SUBSCRIPTION1)) { + assertEquals("Incorrect number of pending messages", MSG_COUNT, sub.getPendingQueueSize() + sub.getDispatchedQueueSize()); + } + else { + assertEquals("Incorrect number of pending messages", 0, sub.getPendingQueueSize()); + } + } + } + + private TopicConnection createConnection() throws Exception { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); + connectionFactory.setBrokerURL(connectionUri); + TopicConnection conn = connectionFactory.createTopicConnection(); + return conn; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2832Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2832Test.java index 0bec264568..f089941c88 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2832Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2832Test.java @@ -52,71 +52,71 @@ import org.slf4j.LoggerFactory; public class AMQ2832Test { - private static final Logger LOG = LoggerFactory.getLogger(AMQ2832Test.class); + private static final Logger LOG = LoggerFactory.getLogger(AMQ2832Test.class); - BrokerService broker = null; - private ActiveMQConnectionFactory cf; - private final Destination destination = new ActiveMQQueue("AMQ2832Test"); - private String connectionUri; + BrokerService broker = null; + private ActiveMQConnectionFactory cf; + private final Destination destination = new ActiveMQQueue("AMQ2832Test"); + private String connectionUri; - protected void startBroker() throws Exception { - doStartBroker(true, false); - } + protected void startBroker() throws Exception { + doStartBroker(true, false); + } - protected void restartBroker() throws Exception { - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - doStartBroker(false, false); - } + protected void restartBroker() throws Exception { + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + doStartBroker(false, false); + } - protected void recoverBroker() throws Exception { - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - doStartBroker(false, true); - } + protected void recoverBroker() throws Exception { + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + doStartBroker(false, true); + } - private void doStartBroker(boolean delete, boolean recover) throws Exception { - broker = new BrokerService(); - broker.setDeleteAllMessagesOnStartup(delete); - broker.setPersistent(true); - broker.setUseJmx(true); - broker.addConnector("tcp://localhost:0"); + private void doStartBroker(boolean delete, boolean recover) throws Exception { + broker = new BrokerService(); + broker.setDeleteAllMessagesOnStartup(delete); + broker.setPersistent(true); + broker.setUseJmx(true); + broker.addConnector("tcp://localhost:0"); - configurePersistence(broker, recover); + configurePersistence(broker, recover); - connectionUri = "vm://localhost?create=false"; - cf = new ActiveMQConnectionFactory(connectionUri); + connectionUri = "vm://localhost?create=false"; + cf = new ActiveMQConnectionFactory(connectionUri); - broker.start(); - LOG.info("Starting broker.."); - } + broker.start(); + LOG.info("Starting broker.."); + } - protected void configurePersistence(BrokerService brokerService, boolean recover) throws Exception { - KahaDBPersistenceAdapter adapter = (KahaDBPersistenceAdapter) brokerService.getPersistenceAdapter(); + protected void configurePersistence(BrokerService brokerService, boolean recover) throws Exception { + KahaDBPersistenceAdapter adapter = (KahaDBPersistenceAdapter) brokerService.getPersistenceAdapter(); - // ensure there are a bunch of data files but multiple entries in each - adapter.setJournalMaxFileLength(1024 * 20); + // ensure there are a bunch of data files but multiple entries in each + adapter.setJournalMaxFileLength(1024 * 20); - // speed up the test case, checkpoint and cleanup early and often - adapter.setCheckpointInterval(5000); - adapter.setCleanupInterval(5000); + // speed up the test case, checkpoint and cleanup early and often + adapter.setCheckpointInterval(5000); + adapter.setCleanupInterval(5000); - if (recover) { - adapter.setForceRecoverIndex(true); - } - } + if (recover) { + adapter.setForceRecoverIndex(true); + } + } - @After - public void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - } + @After + public void tearDown() throws Exception { + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + } /** * Scenario: @@ -129,36 +129,36 @@ public class AMQ2832Test { * * @throws Exception */ - @Test - public void testAckChain() throws Exception { - startBroker(); + @Test + public void testAckChain() throws Exception { + startBroker(); - StagedConsumer consumer = new StagedConsumer(); - // file #1 - produceMessagesToConsumeMultipleDataFiles(5); - // acknowledge first 2 messages and leave the 3rd one unacknowledged blocking db-1.log - consumer.receive(3); + StagedConsumer consumer = new StagedConsumer(); + // file #1 + produceMessagesToConsumeMultipleDataFiles(5); + // acknowledge first 2 messages and leave the 3rd one unacknowledged blocking db-1.log + consumer.receive(3); - // send messages by consuming and acknowledging every message right after sent in order to get KahadbAdd and Remove command to be saved together - // this is necessary in order to get KahaAddMessageCommand to be saved in one db file and the corresponding KahaRemoveMessageCommand in the next one - produceAndConsumeImmediately(20, consumer); - consumer.receive(2).acknowledge(); // consume and ack the last 2 unconsumed + // send messages by consuming and acknowledging every message right after sent in order to get KahadbAdd and Remove command to be saved together + // this is necessary in order to get KahaAddMessageCommand to be saved in one db file and the corresponding KahaRemoveMessageCommand in the next one + produceAndConsumeImmediately(20, consumer); + consumer.receive(2).acknowledge(); // consume and ack the last 2 unconsumed - // now we have 3 files written and started with #4 - consumer.close(); + // now we have 3 files written and started with #4 + consumer.close(); - broker.stop(); - broker.waitUntilStopped(); + broker.stop(); + broker.waitUntilStopped(); - recoverBroker(); + recoverBroker(); - consumer = new StagedConsumer(); - Message message = consumer.receive(1); - assertNotNull("One message stays unacked from db-1.log", message); - message.acknowledge(); - message = consumer.receive(1); - assertNull("There should not be any unconsumed messages any more", message); - consumer.close(); + consumer = new StagedConsumer(); + Message message = consumer.receive(1); + assertNotNull("One message stays unacked from db-1.log", message); + message.acknowledge(); + message = consumer.receive(1); + assertNull("There should not be any unconsumed messages any more", message); + consumer.close(); } private void produceAndConsumeImmediately(int numOfMsgs, StagedConsumer consumer) throws Exception { @@ -169,212 +169,211 @@ public class AMQ2832Test { } @Test - public void testAckRemovedMessageReplayedAfterRecovery() throws Exception { + public void testAckRemovedMessageReplayedAfterRecovery() throws Exception { - startBroker(); + startBroker(); - StagedConsumer consumer = new StagedConsumer(); - int numMessagesAvailable = produceMessagesToConsumeMultipleDataFiles(20); - // this will block the reclaiming of one data file - Message firstUnacked = consumer.receive(10); - LOG.info("first unacked: " + firstUnacked.getJMSMessageID()); - Message secondUnacked = consumer.receive(1); - LOG.info("second unacked: " + secondUnacked.getJMSMessageID()); - numMessagesAvailable -= 11; + StagedConsumer consumer = new StagedConsumer(); + int numMessagesAvailable = produceMessagesToConsumeMultipleDataFiles(20); + // this will block the reclaiming of one data file + Message firstUnacked = consumer.receive(10); + LOG.info("first unacked: " + firstUnacked.getJMSMessageID()); + Message secondUnacked = consumer.receive(1); + LOG.info("second unacked: " + secondUnacked.getJMSMessageID()); + numMessagesAvailable -= 11; - numMessagesAvailable += produceMessagesToConsumeMultipleDataFiles(10); - // ensure ack is another data file - LOG.info("Acking firstUnacked: " + firstUnacked.getJMSMessageID()); - firstUnacked.acknowledge(); + numMessagesAvailable += produceMessagesToConsumeMultipleDataFiles(10); + // ensure ack is another data file + LOG.info("Acking firstUnacked: " + firstUnacked.getJMSMessageID()); + firstUnacked.acknowledge(); - numMessagesAvailable += produceMessagesToConsumeMultipleDataFiles(10); + numMessagesAvailable += produceMessagesToConsumeMultipleDataFiles(10); - consumer.receive(numMessagesAvailable).acknowledge(); + consumer.receive(numMessagesAvailable).acknowledge(); - // second unacked should keep first data file available but journal with the first ack - // may get whacked - consumer.close(); + // second unacked should keep first data file available but journal with the first ack + // may get whacked + consumer.close(); - broker.stop(); - broker.waitUntilStopped(); + broker.stop(); + broker.waitUntilStopped(); - recoverBroker(); + recoverBroker(); - consumer = new StagedConsumer(); - // need to force recovery? + consumer = new StagedConsumer(); + // need to force recovery? - Message msg = consumer.receive(1, 5); - assertNotNull("One messages left after recovery", msg); - msg.acknowledge(); + Message msg = consumer.receive(1, 5); + assertNotNull("One messages left after recovery", msg); + msg.acknowledge(); - // should be no more messages - msg = consumer.receive(1, 5); - assertEquals("Only one messages left after recovery: " + msg, null, msg); - consumer.close(); - } + // should be no more messages + msg = consumer.receive(1, 5); + assertEquals("Only one messages left after recovery: " + msg, null, msg); + consumer.close(); + } - @Test - public void testAlternateLossScenario() throws Exception { + @Test + public void testAlternateLossScenario() throws Exception { - startBroker(); - PersistenceAdapter pa = broker.getPersistenceAdapter(); - if (pa instanceof LevelDBStore) { - return; - } + startBroker(); + PersistenceAdapter pa = broker.getPersistenceAdapter(); + if (pa instanceof LevelDBStore) { + return; + } - ActiveMQQueue queue = new ActiveMQQueue("MyQueue"); - ActiveMQQueue disposable = new ActiveMQQueue("MyDisposableQueue"); - ActiveMQTopic topic = new ActiveMQTopic("MyDurableTopic"); + ActiveMQQueue queue = new ActiveMQQueue("MyQueue"); + ActiveMQQueue disposable = new ActiveMQQueue("MyDisposableQueue"); + ActiveMQTopic topic = new ActiveMQTopic("MyDurableTopic"); - // This ensure that data file 1 never goes away. - createInactiveDurableSub(topic); - assertEquals(1, getNumberOfJournalFiles()); + // This ensure that data file 1 never goes away. + createInactiveDurableSub(topic); + assertEquals(1, getNumberOfJournalFiles()); - // One Queue Message that will be acked in another data file. - produceMessages(queue, 1); - assertEquals(1, getNumberOfJournalFiles()); + // One Queue Message that will be acked in another data file. + produceMessages(queue, 1); + assertEquals(1, getNumberOfJournalFiles()); - // Add some messages to consume space - produceMessages(disposable, 50); + // Add some messages to consume space + produceMessages(disposable, 50); - int dataFilesCount = getNumberOfJournalFiles(); - assertTrue(dataFilesCount > 1); + int dataFilesCount = getNumberOfJournalFiles(); + assertTrue(dataFilesCount > 1); - // Create an ack for the single message on this queue - drainQueue(queue); + // Create an ack for the single message on this queue + drainQueue(queue); - // Add some more messages to consume space beyond tha data file with the ack - produceMessages(disposable, 50); + // Add some more messages to consume space beyond tha data file with the ack + produceMessages(disposable, 50); - assertTrue(dataFilesCount < getNumberOfJournalFiles()); - dataFilesCount = getNumberOfJournalFiles(); + assertTrue(dataFilesCount < getNumberOfJournalFiles()); + dataFilesCount = getNumberOfJournalFiles(); - restartBroker(); + restartBroker(); - // Clear out all queue data - broker.getAdminView().removeQueue(disposable.getQueueName()); + // Clear out all queue data + broker.getAdminView().removeQueue(disposable.getQueueName()); - // Once this becomes true our ack could be lost. - assertTrue("Less than three journal file expected, was " + getNumberOfJournalFiles(), Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return getNumberOfJournalFiles() <= 3; + // Once this becomes true our ack could be lost. + assertTrue("Less than three journal file expected, was " + getNumberOfJournalFiles(), Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return getNumberOfJournalFiles() <= 3; + } + }, TimeUnit.MINUTES.toMillis(3))); + + // Recover and the Message should not be replayed but if the old MessageAck is lost + // then it could be. + recoverBroker(); + + assertTrue(drainQueue(queue) == 0); + } + + private int getNumberOfJournalFiles() throws IOException { + + Collection files = ((KahaDBPersistenceAdapter) broker.getPersistenceAdapter()).getStore().getJournal().getFileMap().values(); + int reality = 0; + for (DataFile file : files) { + if (file != null) { + reality++; + } + } + + return reality; + } + + private void createInactiveDurableSub(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"); + consumer.close(); + connection.close(); + produceMessages(topic, 1); + } + + private int drainQueue(Queue queue) throws Exception { + Connection connection = cf.createConnection(); + connection.setClientID("Inactive"); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(queue); + int count = 0; + while (consumer.receive(5000) != null) { + count++; + } + consumer.close(); + connection.close(); + return count; + } + + private int produceMessages(Destination destination, int numToSend) throws Exception { + int sent = 0; + Connection connection = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri()).createConnection(); + connection.start(); + try { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + for (int i = 0; i < numToSend; i++) { + producer.send(createMessage(session, i)); + sent++; + } + } + finally { + connection.close(); + } + + return sent; + } + + private int produceMessagesToConsumeMultipleDataFiles(int numToSend) throws Exception { + return produceMessages(destination, numToSend); + } + + final String payload = new String(new byte[1024]); + + private Message createMessage(Session session, int i) throws Exception { + return session.createTextMessage(payload + "::" + i); + } + + private class StagedConsumer { + + Connection connection; + MessageConsumer consumer; + + StagedConsumer() throws Exception { + connection = new ActiveMQConnectionFactory("failover://" + broker.getTransportConnectors().get(0).getConnectUri().toString()).createConnection(); + connection.start(); + consumer = connection.createSession(false, ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE).createConsumer(destination); + } + + public Message receive(int numToReceive) throws Exception { + return receive(numToReceive, 2); + } + + public Message receive(int numToReceive, int timeoutInSeconds) throws Exception { + Message msg = null; + for (; numToReceive > 0; numToReceive--) { + + do { + msg = consumer.receive(1 * 1000); + } while (msg == null && --timeoutInSeconds > 0); + + if (numToReceive > 1) { + msg.acknowledge(); } - }, TimeUnit.MINUTES.toMillis(3))); - // Recover and the Message should not be replayed but if the old MessageAck is lost - // then it could be. - recoverBroker(); - - assertTrue(drainQueue(queue) == 0); - } - - private int getNumberOfJournalFiles() throws IOException { - - Collection files = - ((KahaDBPersistenceAdapter) broker.getPersistenceAdapter()).getStore().getJournal().getFileMap().values(); - int reality = 0; - for (DataFile file : files) { - if (file != null) { - reality++; + if (msg != null) { + LOG.debug("received: " + msg.getJMSMessageID()); } - } + } + // last message, unacked + return msg; + } - return reality; - } - - private void createInactiveDurableSub(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"); - consumer.close(); - connection.close(); - produceMessages(topic, 1); - } - - private int drainQueue(Queue queue) throws Exception { - Connection connection = cf.createConnection(); - connection.setClientID("Inactive"); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(queue); - int count = 0; - while (consumer.receive(5000) != null) { - count++; - } - consumer.close(); - connection.close(); - return count; - } - - private int produceMessages(Destination destination, int numToSend) throws Exception { - int sent = 0; - Connection connection = new ActiveMQConnectionFactory( - broker.getTransportConnectors().get(0).getConnectUri()).createConnection(); - connection.start(); - try { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - for (int i = 0; i < numToSend; i++) { - producer.send(createMessage(session, i)); - sent++; - } - } finally { - connection.close(); - } - - return sent; - } - - private int produceMessagesToConsumeMultipleDataFiles(int numToSend) throws Exception { - return produceMessages(destination, numToSend); - } - - final String payload = new String(new byte[1024]); - - private Message createMessage(Session session, int i) throws Exception { - return session.createTextMessage(payload + "::" + i); - } - - private class StagedConsumer { - Connection connection; - MessageConsumer consumer; - - StagedConsumer() throws Exception { - connection = new ActiveMQConnectionFactory("failover://" + - broker.getTransportConnectors().get(0).getConnectUri().toString()).createConnection(); - connection.start(); - consumer = connection.createSession(false, ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE).createConsumer(destination); - } - - public Message receive(int numToReceive) throws Exception { - return receive(numToReceive, 2); - } - - public Message receive(int numToReceive, int timeoutInSeconds) throws Exception { - Message msg = null; - for (; numToReceive > 0; numToReceive--) { - - do { - msg = consumer.receive(1*1000); - } while (msg == null && --timeoutInSeconds > 0); - - if (numToReceive > 1) { - msg.acknowledge(); - } - - if (msg != null) { - LOG.debug("received: " + msg.getJMSMessageID()); - } - } - // last message, unacked - return msg; - } - - void close() throws JMSException { - consumer.close(); - connection.close(); - } - } + void close() throws JMSException { + consumer.close(); + connection.close(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2870Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2870Test.java index 8bb6bff7ec..fc3ae3b3db 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2870Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2870Test.java @@ -45,186 +45,183 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RunWith(value = Parameterized.class) -public class AMQ2870Test extends org.apache.activemq.TestSupport { +public class AMQ2870Test extends org.apache.activemq.TestSupport { - static final Logger LOG = LoggerFactory.getLogger(AMQ2870Test.class); - BrokerService broker = null; - ActiveMQTopic topic; + static final Logger LOG = LoggerFactory.getLogger(AMQ2870Test.class); + BrokerService broker = null; + ActiveMQTopic topic; - ActiveMQConnection consumerConnection = null, producerConnection = null; - Session producerSession; - MessageProducer producer; - final int minPercentUsageForStore = 10; - String data; + ActiveMQConnection consumerConnection = null, producerConnection = null; + Session producerSession; + MessageProducer producer; + final int minPercentUsageForStore = 10; + String data; - private final PersistenceAdapterChoice persistenceAdapterChoice; + private final PersistenceAdapterChoice persistenceAdapterChoice; - @Parameterized.Parameters - public static Collection getTestParameters() { - String osName = System.getProperty("os.name"); - LOG.info("Running on [" + osName + "]"); - PersistenceAdapterChoice[] kahaDb = {PersistenceAdapterChoice.KahaDB}; - PersistenceAdapterChoice[] levelDb = {PersistenceAdapterChoice.LevelDB}; - List choices = new ArrayList(); - choices.add(kahaDb); - if (!osName.equalsIgnoreCase("AIX") && !osName.equalsIgnoreCase("SunOS")) { - choices.add(levelDb); - } + @Parameterized.Parameters + public static Collection getTestParameters() { + String osName = System.getProperty("os.name"); + LOG.info("Running on [" + osName + "]"); + PersistenceAdapterChoice[] kahaDb = {PersistenceAdapterChoice.KahaDB}; + PersistenceAdapterChoice[] levelDb = {PersistenceAdapterChoice.LevelDB}; + List choices = new ArrayList(); + choices.add(kahaDb); + if (!osName.equalsIgnoreCase("AIX") && !osName.equalsIgnoreCase("SunOS")) { + choices.add(levelDb); + } - return choices; - } + return choices; + } - public AMQ2870Test(PersistenceAdapterChoice choice) { - this.persistenceAdapterChoice = choice; - } + public AMQ2870Test(PersistenceAdapterChoice choice) { + this.persistenceAdapterChoice = choice; + } - @Test(timeout = 300000) - public void testSize() throws Exception { - openConsumer(); + @Test(timeout = 300000) + public void testSize() throws Exception { + openConsumer(); - assertEquals(0, broker.getAdminView().getStorePercentUsage()); + assertEquals(0, broker.getAdminView().getStorePercentUsage()); - for (int i = 0; i < 5000; i++) { - sendMessage(false); - } + for (int i = 0; i < 5000; i++) { + sendMessage(false); + } - final BrokerView brokerView = broker.getAdminView(); + final BrokerView brokerView = broker.getAdminView(); - // wait for reclaim - assertTrue("in range with consumer", - Wait.waitFor(new Wait.Condition() { + // wait for reclaim + assertTrue("in range with consumer", Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisified() throws Exception { - // usage percent updated only on send check for isFull so once - // sends complete it is no longer updated till next send via a call to isFull - // this is optimal as it is only used to block producers - broker.getSystemUsage().getStoreUsage().isFull(); - LOG.info("store percent usage: "+brokerView.getStorePercentUsage()); - return broker.getAdminView().getStorePercentUsage() < minPercentUsageForStore; + // usage percent updated only on send check for isFull so once + // sends complete it is no longer updated till next send via a call to isFull + // this is optimal as it is only used to block producers + broker.getSystemUsage().getStoreUsage().isFull(); + LOG.info("store percent usage: " + brokerView.getStorePercentUsage()); + return broker.getAdminView().getStorePercentUsage() < minPercentUsageForStore; } - })); + })); - closeConsumer(); + closeConsumer(); - assertTrue("in range with closed consumer", - Wait.waitFor(new Wait.Condition() { + assertTrue("in range with closed consumer", Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisified() throws Exception { - broker.getSystemUsage().getStoreUsage().isFull(); - LOG.info("store precent usage: "+brokerView.getStorePercentUsage()); - return broker.getAdminView().getStorePercentUsage() < minPercentUsageForStore; + broker.getSystemUsage().getStoreUsage().isFull(); + LOG.info("store precent usage: " + brokerView.getStorePercentUsage()); + return broker.getAdminView().getStorePercentUsage() < minPercentUsageForStore; } - })); + })); - for (int i = 0; i < 5000; i++) { - sendMessage(false); - } + for (int i = 0; i < 5000; i++) { + sendMessage(false); + } - // What if i drop the subscription? - broker.getAdminView().destroyDurableSubscriber("cliID", "subName"); + // What if i drop the subscription? + broker.getAdminView().destroyDurableSubscriber("cliID", "subName"); - assertTrue("in range after send with consumer", - Wait.waitFor(new Wait.Condition() { + assertTrue("in range after send with consumer", Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisified() throws Exception { - broker.getSystemUsage().getStoreUsage().isFull(); - LOG.info("store precent usage: "+brokerView.getStorePercentUsage()); - return broker.getAdminView().getStorePercentUsage() < minPercentUsageForStore; + broker.getSystemUsage().getStoreUsage().isFull(); + LOG.info("store precent usage: " + brokerView.getStorePercentUsage()); + return broker.getAdminView().getStorePercentUsage() < minPercentUsageForStore; } - })); - } + })); + } - private void openConsumer() throws Exception { - consumerConnection = (ActiveMQConnection) createConnection(); - consumerConnection.setClientID("cliID"); - consumerConnection.start(); - Session session = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber subscriber = session.createDurableSubscriber(topic, "subName", "filter=true", false); + private void openConsumer() throws Exception { + consumerConnection = (ActiveMQConnection) createConnection(); + consumerConnection.setClientID("cliID"); + consumerConnection.start(); + Session session = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + TopicSubscriber subscriber = session.createDurableSubscriber(topic, "subName", "filter=true", false); - subscriber.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - // received++; - } - }); - } + subscriber.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + // received++; + } + }); + } - private void closeConsumer() throws JMSException { - if (consumerConnection != null) - consumerConnection.close(); - consumerConnection = null; - } + private void closeConsumer() throws JMSException { + if (consumerConnection != null) + consumerConnection.close(); + consumerConnection = null; + } - private void sendMessage(boolean filter) throws Exception { - if (producerConnection == null) { - producerConnection = (ActiveMQConnection) createConnection(); - producerConnection.start(); - producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = producerSession.createProducer(topic); - } + private void sendMessage(boolean filter) throws Exception { + if (producerConnection == null) { + producerConnection = (ActiveMQConnection) createConnection(); + producerConnection.start(); + producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer = producerSession.createProducer(topic); + } - Message message = producerSession.createMessage(); - message.setBooleanProperty("filter", filter); - message.setStringProperty("data", data); - producer.send(message); - } + Message message = producerSession.createMessage(); + message.setBooleanProperty("filter", filter); + message.setStringProperty("data", data); + producer.send(message); + } - private void startBroker(boolean deleteMessages) throws Exception { - broker = new BrokerService(); - broker.setAdvisorySupport(false); - broker.setBrokerName("testStoreSize"); + private void startBroker(boolean deleteMessages) throws Exception { + broker = new BrokerService(); + broker.setAdvisorySupport(false); + broker.setBrokerName("testStoreSize"); - if (deleteMessages) { - broker.setDeleteAllMessagesOnStartup(true); - } - LOG.info("Starting broker with persistenceAdapterChoice " + persistenceAdapterChoice.toString()); - setPersistenceAdapter(broker, persistenceAdapterChoice); - configurePersistenceAdapter(broker.getPersistenceAdapter()); - broker.getSystemUsage().getStoreUsage().setLimit(100 * 1000 * 1000); - broker.start(); - } + if (deleteMessages) { + broker.setDeleteAllMessagesOnStartup(true); + } + LOG.info("Starting broker with persistenceAdapterChoice " + persistenceAdapterChoice.toString()); + setPersistenceAdapter(broker, persistenceAdapterChoice); + configurePersistenceAdapter(broker.getPersistenceAdapter()); + broker.getSystemUsage().getStoreUsage().setLimit(100 * 1000 * 1000); + broker.start(); + } - private void configurePersistenceAdapter(PersistenceAdapter persistenceAdapter) { - Properties properties = new Properties(); - String maxFileLengthVal = String.valueOf(2 * 1024 * 1024); - properties.put("journalMaxFileLength", maxFileLengthVal); - properties.put("maxFileLength", maxFileLengthVal); - properties.put("cleanupInterval", "2000"); - properties.put("checkpointInterval", "2000"); + private void configurePersistenceAdapter(PersistenceAdapter persistenceAdapter) { + Properties properties = new Properties(); + String maxFileLengthVal = String.valueOf(2 * 1024 * 1024); + properties.put("journalMaxFileLength", maxFileLengthVal); + properties.put("maxFileLength", maxFileLengthVal); + properties.put("cleanupInterval", "2000"); + properties.put("checkpointInterval", "2000"); - // leveldb - properties.put("logSize", maxFileLengthVal); + // leveldb + properties.put("logSize", maxFileLengthVal); - IntrospectionSupport.setProperties(persistenceAdapter, properties); - } + IntrospectionSupport.setProperties(persistenceAdapter, properties); + } - private void stopBroker() throws Exception { - if (broker != null) - broker.stop(); - broker = null; - } + private void stopBroker() throws Exception { + if (broker != null) + broker.stop(); + broker = null; + } - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://testStoreSize?jms.watchTopicAdvisories=false&waitForStart=5000&create=false"); - } + @Override + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory("vm://testStoreSize?jms.watchTopicAdvisories=false&waitForStart=5000&create=false"); + } - @Override - @Before - public void setUp() throws Exception { - StringBuilder sb = new StringBuilder(5000); - for (int i = 0; i < 5000; i++) { - sb.append('a'); - } - data = sb.toString(); + @Override + @Before + public void setUp() throws Exception { + StringBuilder sb = new StringBuilder(5000); + for (int i = 0; i < 5000; i++) { + sb.append('a'); + } + data = sb.toString(); - startBroker(true); - topic = (ActiveMQTopic) createDestination(); - } + startBroker(true); + topic = (ActiveMQTopic) createDestination(); + } - @Override - @After - public void tearDown() throws Exception { - stopBroker(); - } + @Override + @After + public void tearDown() throws Exception { + stopBroker(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2902Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2902Test.java index 3c38186f8b..798d32faab 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2902Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2902Test.java @@ -35,64 +35,62 @@ import org.apache.log4j.spi.LoggingEvent; import org.slf4j.LoggerFactory; public class AMQ2902Test extends TestCase { - private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(AMQ2580Test.class); - final AtomicBoolean gotExceptionInLog = new AtomicBoolean(Boolean.FALSE); - final AtomicBoolean failedToFindMDC = new AtomicBoolean(Boolean.FALSE); + private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(AMQ2580Test.class); - Appender appender = new DefaultTestAppender() { - @Override - public void doAppend(LoggingEvent event) { - if (event.getThrowableInformation() != null - && event.getThrowableInformation().getThrowable() instanceof TransportDisposedIOException) { + final AtomicBoolean gotExceptionInLog = new AtomicBoolean(Boolean.FALSE); + final AtomicBoolean failedToFindMDC = new AtomicBoolean(Boolean.FALSE); - // Prevent StackOverflowException so we can see a sane stack trace. - if (gotExceptionInLog.get()) { - return; - } + Appender appender = new DefaultTestAppender() { + @Override + public void doAppend(LoggingEvent event) { + if (event.getThrowableInformation() != null && event.getThrowableInformation().getThrowable() instanceof TransportDisposedIOException) { - gotExceptionInLog.set(Boolean.TRUE); - LOG.error("got event: " + event + ", ex:" + event.getThrowableInformation().getThrowable(), event.getThrowableInformation().getThrowable()); - LOG.error("Event source: ", new Throwable("Here")); + // Prevent StackOverflowException so we can see a sane stack trace. + if (gotExceptionInLog.get()) { + return; } - if( !"Loaded the Bouncy Castle security provider.".equals(event.getMessage()) ) { - if (event.getMDC("activemq.broker") == null) { - failedToFindMDC.set(Boolean.TRUE); - } + + gotExceptionInLog.set(Boolean.TRUE); + LOG.error("got event: " + event + ", ex:" + event.getThrowableInformation().getThrowable(), event.getThrowableInformation().getThrowable()); + LOG.error("Event source: ", new Throwable("Here")); + } + if (!"Loaded the Bouncy Castle security provider.".equals(event.getMessage())) { + if (event.getMDC("activemq.broker") == null) { + failedToFindMDC.set(Boolean.TRUE); } - return; - } - }; + } + return; + } + }; - public void testNoExceptionOnClosewithStartStop() throws JMSException { - ConnectionFactory connectionFactory = new ActiveMQConnectionFactory( - "vm://localhost?broker.persistent=false"); - Connection connection = connectionFactory.createConnection(); - connection.start(); - connection.stop(); - connection.close(); - } + public void testNoExceptionOnClosewithStartStop() throws JMSException { + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); + Connection connection = connectionFactory.createConnection(); + connection.start(); + connection.stop(); + connection.close(); + } - public void testNoExceptionOnClose() throws JMSException { - ConnectionFactory connectionFactory = new ActiveMQConnectionFactory( - "vm://localhost?broker.persistent=false"); - Connection connection = connectionFactory.createConnection(); - connection.close(); - } + public void testNoExceptionOnClose() throws JMSException { + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); + Connection connection = connectionFactory.createConnection(); + connection.close(); + } - @Override - public void setUp() throws Exception { - gotExceptionInLog.set(Boolean.FALSE); - failedToFindMDC.set(Boolean.FALSE); - Logger.getRootLogger().addAppender(appender); - Logger.getLogger(TransportConnection.class.getName() + ".Transport").setLevel(Level.DEBUG); - Logger.getLogger(TransportConnection.class.getName()).setLevel(Level.DEBUG); - } + @Override + public void setUp() throws Exception { + gotExceptionInLog.set(Boolean.FALSE); + failedToFindMDC.set(Boolean.FALSE); + Logger.getRootLogger().addAppender(appender); + Logger.getLogger(TransportConnection.class.getName() + ".Transport").setLevel(Level.DEBUG); + Logger.getLogger(TransportConnection.class.getName()).setLevel(Level.DEBUG); + } - @Override - public void tearDown() throws Exception { - Logger.getRootLogger().removeAppender(appender); - assertFalse("got unexpected ex in log on graceful close", gotExceptionInLog.get()); - assertFalse("MDC is there", failedToFindMDC.get()); - } + @Override + public void tearDown() throws Exception { + Logger.getRootLogger().removeAppender(appender); + assertFalse("got unexpected ex in log on graceful close", gotExceptionInLog.get()); + assertFalse("MDC is there", failedToFindMDC.get()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2910Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2910Test.java index f665431fab..5205fbf5a5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2910Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ2910Test.java @@ -37,93 +37,94 @@ import static org.junit.Assert.assertTrue; @RunWith(BlockJUnit4ClassRunner.class) public class AMQ2910Test extends JmsMultipleClientsTestSupport { - final int maxConcurrency = 60; - final int msgCount = 200; - final Vector exceptions = new Vector(); + final int maxConcurrency = 60; + final int msgCount = 200; + final Vector exceptions = new Vector(); - @Override - protected BrokerService createBroker() throws Exception { - //persistent = true; - BrokerService broker = new BrokerService(); - broker.setDeleteAllMessagesOnStartup(true); - broker.addConnector("tcp://localhost:0"); - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setPendingQueuePolicy(new FilePendingQueueMessageStoragePolicy()); - defaultEntry.setCursorMemoryHighWaterMark(50); - defaultEntry.setMemoryLimit(500*1024); - defaultEntry.setProducerFlowControl(false); - policyMap.setDefaultEntry(defaultEntry); - broker.setDestinationPolicy(policyMap); + @Override + protected BrokerService createBroker() throws Exception { + //persistent = true; + BrokerService broker = new BrokerService(); + broker.setDeleteAllMessagesOnStartup(true); + broker.addConnector("tcp://localhost:0"); + PolicyMap policyMap = new PolicyMap(); + PolicyEntry defaultEntry = new PolicyEntry(); + defaultEntry.setPendingQueuePolicy(new FilePendingQueueMessageStoragePolicy()); + defaultEntry.setCursorMemoryHighWaterMark(50); + defaultEntry.setMemoryLimit(500 * 1024); + defaultEntry.setProducerFlowControl(false); + policyMap.setDefaultEntry(defaultEntry); + broker.setDestinationPolicy(policyMap); - broker.getSystemUsage().getMemoryUsage().setLimit(1000 * 1024); + broker.getSystemUsage().getMemoryUsage().setLimit(1000 * 1024); - return broker; - } + return broker; + } - @Test(timeout = 30 * 1000) - public void testConcurrentSendToPendingCursor() throws Exception { - final ActiveMQConnectionFactory factory = - new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri()); - factory.setCloseTimeout(30000); - ExecutorService executor = Executors.newCachedThreadPool(); - for (int i=0; i consumerThreads = new ArrayList(); - for (int i = 0; i < MAX_CONSUMER; i++) { - ConsumerThread thread = new ConsumerThread(); - thread.start(); - consumerThreads.add(thread); - } - sendMessages(); + @Test + public void testNoStickyKahaDbLogFilesOnConcurrentTransactionalConsumer() throws Exception { - boolean allMessagesReceived = messageCountDown.await(60, TimeUnit.SECONDS); - assertTrue(allMessagesReceived); + List consumerThreads = new ArrayList(); + for (int i = 0; i < MAX_CONSUMER; i++) { + ConsumerThread thread = new ConsumerThread(); + thread.start(); + consumerThreads.add(thread); + } + sendMessages(); - for (Thread thread : consumerThreads) { - thread.join(TimeUnit.MILLISECONDS.convert(60, TimeUnit.SECONDS)); - assertFalse(thread.isAlive()); - } - kahaDB.forceCleanup(); - assertEquals("Expect only one active KahaDB log file after cleanup", 1, kahaDB.getFileMapSize()); - } + boolean allMessagesReceived = messageCountDown.await(60, TimeUnit.SECONDS); + assertTrue(allMessagesReceived); - private void sendMessages() throws Exception { - ConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = factory.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(session.createQueue(QUEUE_NAME)); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - for (int i = 0; i < MAX_MESSAGES; i++) { - BytesMessage message = session.createBytesMessage(); - message.writeBytes(new byte[200]); - producer.send(message); - } - producer.close(); - session.close(); - connection.close(); - } + for (Thread thread : consumerThreads) { + thread.join(TimeUnit.MILLISECONDS.convert(60, TimeUnit.SECONDS)); + assertFalse(thread.isAlive()); + } + kahaDB.forceCleanup(); + assertEquals("Expect only one active KahaDB log file after cleanup", 1, kahaDB.getFileMapSize()); + } + + private void sendMessages() throws Exception { + ConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + Connection connection = factory.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(session.createQueue(QUEUE_NAME)); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + for (int i = 0; i < MAX_MESSAGES; i++) { + BytesMessage message = session.createBytesMessage(); + message.writeBytes(new byte[200]); + producer.send(message); + } + producer.close(); + session.close(); + connection.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3014Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3014Test.java index 5f1c3e9f66..b3908d634d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3014Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3014Test.java @@ -44,165 +44,157 @@ import org.junit.Test; * transferred once the local broker's ID is known to the bridge support. */ public class AMQ3014Test { - // Change this URL to be an unused port. - private static final String BROKER_URL = "tcp://localhost:0"; - private List remoteBrokerInfos = Collections - .synchronizedList(new ArrayList()); + // Change this URL to be an unused port. + private static final String BROKER_URL = "tcp://localhost:0"; - private BrokerService localBroker = new BrokerService(); + private List remoteBrokerInfos = Collections.synchronizedList(new ArrayList()); - // Override the "remote" broker so that it records all (remote) BrokerInfos - // that it receives. - private BrokerService remoteBroker = new BrokerService() { - @Override - protected TransportConnector createTransportConnector(URI brokerURI) - throws Exception { - TransportServer transport = TransportFactorySupport.bind(this, brokerURI); - return new TransportConnector(transport) { - @Override - protected Connection createConnection(Transport transport) - throws IOException { - Connection connection = super.createConnection(transport); - final TransportListener proxiedListener = transport - .getTransportListener(); - transport.setTransportListener(new TransportListener() { + private BrokerService localBroker = new BrokerService(); - @Override - public void onCommand(Object command) { - if (command instanceof BrokerInfo) { - remoteBrokerInfos.add((BrokerInfo) command); - } - proxiedListener.onCommand(command); - } + // Override the "remote" broker so that it records all (remote) BrokerInfos + // that it receives. + private BrokerService remoteBroker = new BrokerService() { + @Override + protected TransportConnector createTransportConnector(URI brokerURI) throws Exception { + TransportServer transport = TransportFactorySupport.bind(this, brokerURI); + return new TransportConnector(transport) { + @Override + protected Connection createConnection(Transport transport) throws IOException { + Connection connection = super.createConnection(transport); + final TransportListener proxiedListener = transport.getTransportListener(); + transport.setTransportListener(new TransportListener() { - @Override - public void onException(IOException error) { - proxiedListener.onException(error); - } + @Override + public void onCommand(Object command) { + if (command instanceof BrokerInfo) { + remoteBrokerInfos.add((BrokerInfo) command); + } + proxiedListener.onCommand(command); + } - @Override - public void transportInterupted() { - proxiedListener.transportInterupted(); - } + @Override + public void onException(IOException error) { + proxiedListener.onException(error); + } - @Override - public void transportResumed() { - proxiedListener.transportResumed(); - } - }); - return connection; - } + @Override + public void transportInterupted() { + proxiedListener.transportInterupted(); + } - }; - } - }; - - @Before - public void init() throws Exception { - localBroker.setBrokerName("localBroker"); - localBroker.setPersistent(false); - localBroker.setUseJmx(false); - localBroker.setSchedulerSupport(false); - - remoteBroker.setBrokerName("remoteBroker"); - remoteBroker.setPersistent(false); - remoteBroker.setUseJmx(false); - remoteBroker.addConnector(BROKER_URL); - remoteBroker.setSchedulerSupport(false); - } - - @After - public void cleanup() throws Exception { - try { - localBroker.stop(); - } finally { - remoteBroker.stop(); - } - } - - /** - * This test verifies that the local broker's ID is typically known by the - * bridge support before the local broker's BrokerInfo is sent to the remote - * broker. - */ - @Test - public void NormalCaseTest() throws Exception { - runTest(0, 3000); - } - - /** - * This test verifies that timing can arise under which the local broker's - * ID is not known by the bridge support before the local broker's - * BrokerInfo is sent to the remote broker. - */ - @Test - public void DelayedCaseTest() throws Exception { - runTest(500, 3000); - } - - private void runTest(final long taskRunnerDelay, long timeout) - throws Exception { - // Add a network connector to the local broker that will create a bridge - // to the remote broker. - DiscoveryNetworkConnector dnc = new DiscoveryNetworkConnector(); - SimpleDiscoveryAgent da = new SimpleDiscoveryAgent(); - da.setServices(remoteBroker.getTransportConnectors().get(0).getPublishableConnectString()); - dnc.setDiscoveryAgent(da); - localBroker.addNetworkConnector(dnc); - - // Before starting the local broker, intercept the task runner factory - // so that the - // local VMTransport dispatcher is artificially delayed. - final TaskRunnerFactory realTaskRunnerFactory = localBroker - .getTaskRunnerFactory(); - localBroker.setTaskRunnerFactory(new TaskRunnerFactory() { - public TaskRunner createTaskRunner(Task task, String name) { - final TaskRunner realTaskRunner = realTaskRunnerFactory - .createTaskRunner(task, name); - if (name.startsWith("ActiveMQ Connection Dispatcher: ")) { - return new TaskRunner() { - @Override - public void shutdown() throws InterruptedException { - realTaskRunner.shutdown(); - } - - @Override - public void shutdown(long timeout) - throws InterruptedException { - realTaskRunner.shutdown(timeout); - } - - @Override - public void wakeup() throws InterruptedException { - Thread.sleep(taskRunnerDelay); - realTaskRunner.wakeup(); - } - }; - } else { - return realTaskRunnerFactory.createTaskRunner(task, name); - } + @Override + public void transportResumed() { + proxiedListener.transportResumed(); + } + }); + return connection; } - }); - // Start the brokers and wait for the bridge to be created; the remote - // broker is started first to ensure it is available for the local - // broker to connect to. - remoteBroker.start(); - localBroker.start(); + }; + } + }; - // Wait for the remote broker to receive the local broker's BrokerInfo - // and then verify the local broker's ID is known. - long startTimeMillis = System.currentTimeMillis(); - while (remoteBrokerInfos.isEmpty() - && (System.currentTimeMillis() - startTimeMillis) < timeout) { - Thread.sleep(100); - } + @Before + public void init() throws Exception { + localBroker.setBrokerName("localBroker"); + localBroker.setPersistent(false); + localBroker.setUseJmx(false); + localBroker.setSchedulerSupport(false); - Assert.assertFalse("Timed out waiting for bridge to form.", - remoteBrokerInfos.isEmpty()); - ; - Assert.assertNotNull("Local broker ID is null.", remoteBrokerInfos.get( - 0).getBrokerId()); - } + remoteBroker.setBrokerName("remoteBroker"); + remoteBroker.setPersistent(false); + remoteBroker.setUseJmx(false); + remoteBroker.addConnector(BROKER_URL); + remoteBroker.setSchedulerSupport(false); + } + + @After + public void cleanup() throws Exception { + try { + localBroker.stop(); + } + finally { + remoteBroker.stop(); + } + } + + /** + * This test verifies that the local broker's ID is typically known by the + * bridge support before the local broker's BrokerInfo is sent to the remote + * broker. + */ + @Test + public void NormalCaseTest() throws Exception { + runTest(0, 3000); + } + + /** + * This test verifies that timing can arise under which the local broker's + * ID is not known by the bridge support before the local broker's + * BrokerInfo is sent to the remote broker. + */ + @Test + public void DelayedCaseTest() throws Exception { + runTest(500, 3000); + } + + private void runTest(final long taskRunnerDelay, long timeout) throws Exception { + // Add a network connector to the local broker that will create a bridge + // to the remote broker. + DiscoveryNetworkConnector dnc = new DiscoveryNetworkConnector(); + SimpleDiscoveryAgent da = new SimpleDiscoveryAgent(); + da.setServices(remoteBroker.getTransportConnectors().get(0).getPublishableConnectString()); + dnc.setDiscoveryAgent(da); + localBroker.addNetworkConnector(dnc); + + // Before starting the local broker, intercept the task runner factory + // so that the + // local VMTransport dispatcher is artificially delayed. + final TaskRunnerFactory realTaskRunnerFactory = localBroker.getTaskRunnerFactory(); + localBroker.setTaskRunnerFactory(new TaskRunnerFactory() { + public TaskRunner createTaskRunner(Task task, String name) { + final TaskRunner realTaskRunner = realTaskRunnerFactory.createTaskRunner(task, name); + if (name.startsWith("ActiveMQ Connection Dispatcher: ")) { + return new TaskRunner() { + @Override + public void shutdown() throws InterruptedException { + realTaskRunner.shutdown(); + } + + @Override + public void shutdown(long timeout) throws InterruptedException { + realTaskRunner.shutdown(timeout); + } + + @Override + public void wakeup() throws InterruptedException { + Thread.sleep(taskRunnerDelay); + realTaskRunner.wakeup(); + } + }; + } + else { + return realTaskRunnerFactory.createTaskRunner(task, name); + } + } + }); + + // Start the brokers and wait for the bridge to be created; the remote + // broker is started first to ensure it is available for the local + // broker to connect to. + remoteBroker.start(); + localBroker.start(); + + // Wait for the remote broker to receive the local broker's BrokerInfo + // and then verify the local broker's ID is known. + long startTimeMillis = System.currentTimeMillis(); + while (remoteBrokerInfos.isEmpty() && (System.currentTimeMillis() - startTimeMillis) < timeout) { + Thread.sleep(100); + } + + Assert.assertFalse("Timed out waiting for bridge to form.", remoteBrokerInfos.isEmpty()); + ; + Assert.assertNotNull("Local broker ID is null.", remoteBrokerInfos.get(0).getBrokerId()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3120Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3120Test.java index f61883b146..88a0db86dd 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3120Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3120Test.java @@ -36,113 +36,112 @@ import static org.junit.Assert.assertEquals; public class AMQ3120Test { - private static final Logger LOG = LoggerFactory.getLogger(AMQ3120Test.class); + private static final Logger LOG = LoggerFactory.getLogger(AMQ3120Test.class); - BrokerService broker = null; - File kahaDbDir = null; - private final Destination destination = new ActiveMQQueue("AMQ3120Test"); - final String payload = new String(new byte[1024]); + BrokerService broker = null; + File kahaDbDir = null; + private final Destination destination = new ActiveMQQueue("AMQ3120Test"); + final String payload = new String(new byte[1024]); - protected void startBroker(boolean delete) throws Exception { - broker = new BrokerService(); + protected void startBroker(boolean delete) throws Exception { + broker = new BrokerService(); - //Start with a clean directory - kahaDbDir = new File(broker.getBrokerDataDirectory(), "KahaDB"); - deleteDir(kahaDbDir); + //Start with a clean directory + kahaDbDir = new File(broker.getBrokerDataDirectory(), "KahaDB"); + deleteDir(kahaDbDir); - broker.setSchedulerSupport(false); - broker.setDeleteAllMessagesOnStartup(delete); - broker.setPersistent(true); - broker.setUseJmx(false); - broker.addConnector("tcp://localhost:0"); + broker.setSchedulerSupport(false); + broker.setDeleteAllMessagesOnStartup(delete); + broker.setPersistent(true); + broker.setUseJmx(false); + broker.addConnector("tcp://localhost:0"); - PolicyMap map = new PolicyMap(); - PolicyEntry entry = new PolicyEntry(); - entry.setUseCache(false); - map.setDefaultEntry(entry); - broker.setDestinationPolicy(map); + PolicyMap map = new PolicyMap(); + PolicyEntry entry = new PolicyEntry(); + entry.setUseCache(false); + map.setDefaultEntry(entry); + broker.setDestinationPolicy(map); - configurePersistence(broker, delete); + configurePersistence(broker, delete); - broker.start(); - LOG.info("Starting broker.."); - } + broker.start(); + LOG.info("Starting broker.."); + } - protected void configurePersistence(BrokerService brokerService, boolean deleteAllOnStart) throws Exception { - KahaDBPersistenceAdapter adapter = (KahaDBPersistenceAdapter) brokerService.getPersistenceAdapter(); + protected void configurePersistence(BrokerService brokerService, boolean deleteAllOnStart) throws Exception { + KahaDBPersistenceAdapter adapter = (KahaDBPersistenceAdapter) brokerService.getPersistenceAdapter(); - // ensure there are a bunch of data files but multiple entries in each - adapter.setJournalMaxFileLength(1024 * 20); + // ensure there are a bunch of data files but multiple entries in each + adapter.setJournalMaxFileLength(1024 * 20); - // speed up the test case, checkpoint and cleanup early and often - adapter.setCheckpointInterval(500); - adapter.setCleanupInterval(500); + // speed up the test case, checkpoint and cleanup early and often + adapter.setCheckpointInterval(500); + adapter.setCleanupInterval(500); - if (!deleteAllOnStart) { - adapter.setForceRecoverIndex(true); - } + if (!deleteAllOnStart) { + adapter.setForceRecoverIndex(true); + } - } + } - private boolean deleteDir(File dir) { - if (dir.isDirectory()) { - String[] children = dir.list(); - for (int i = 0; i < children.length; i++) { - boolean success = deleteDir(new File(dir, children[i])); - if (!success) { - return false; - } + private boolean deleteDir(File dir) { + if (dir.isDirectory()) { + String[] children = dir.list(); + for (int i = 0; i < children.length; i++) { + boolean success = deleteDir(new File(dir, children[i])); + if (!success) { + return false; } - } + } + } - return dir.delete(); - } + return dir.delete(); + } - private int getFileCount(File dir){ - if (dir.isDirectory()) { - String[] children = dir.list(); - return children.length; - } + private int getFileCount(File dir) { + if (dir.isDirectory()) { + String[] children = dir.list(); + return children.length; + } - return 0; - } + return 0; + } - @Test - public void testCleanupOfFiles() throws Exception { - final int messageCount = 500; - startBroker(true); - int fileCount = getFileCount(kahaDbDir); - assertEquals(4, fileCount); + @Test + public void testCleanupOfFiles() throws Exception { + final int messageCount = 500; + startBroker(true); + int fileCount = getFileCount(kahaDbDir); + assertEquals(4, fileCount); - Connection connection = new ActiveMQConnectionFactory( - broker.getTransportConnectors().get(0).getConnectUri()).createConnection(); - connection.start(); - Session producerSess = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Session consumerSess = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Connection connection = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri()).createConnection(); + connection.start(); + Session producerSess = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Session consumerSess = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ProducerThread producer = new ProducerThread(producerSess, destination) { - @Override - protected Message createMessage(int i) throws Exception { - return sess.createTextMessage(payload + "::" + i); - } - }; - producer.setSleep(650); - producer.setMessageCount(messageCount); - ConsumerThread consumer = new ConsumerThread(consumerSess, destination); - consumer.setBreakOnNull(false); - consumer.setMessageCount(messageCount); + ProducerThread producer = new ProducerThread(producerSess, destination) { + @Override + protected Message createMessage(int i) throws Exception { + return sess.createTextMessage(payload + "::" + i); + } + }; + producer.setSleep(650); + producer.setMessageCount(messageCount); + ConsumerThread consumer = new ConsumerThread(consumerSess, destination); + consumer.setBreakOnNull(false); + consumer.setMessageCount(messageCount); - producer.start(); - consumer.start(); + producer.start(); + consumer.start(); - producer.join(); - consumer.join(); + producer.join(); + consumer.join(); - assertEquals("consumer got all produced messages", producer.getMessageCount(), consumer.getReceived()); + assertEquals("consumer got all produced messages", producer.getMessageCount(), consumer.getReceived()); - broker.stop(); - broker.waitUntilStopped(); + broker.stop(); + broker.waitUntilStopped(); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3140Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3140Test.java index fd71558cf9..edc7bd8291 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3140Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3140Test.java @@ -44,102 +44,103 @@ import org.junit.Test; public class AMQ3140Test { - private static final int MESSAGES_PER_THREAD = 100; + private static final int MESSAGES_PER_THREAD = 100; - private static final int THREAD_COUNT = 10; + private static final int THREAD_COUNT = 10; - private BrokerService broker; + private BrokerService broker; - private static final String QUEUE_NAME = "test"; + private static final String QUEUE_NAME = "test"; - private static class Sender extends Thread { + private static class Sender extends Thread { - private static final int DELAY = 3000; + private static final int DELAY = 3000; - @Override - public void run() { - try { - ConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = cf.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(session.createQueue(QUEUE_NAME)); - Message message = session.createTextMessage("test"); - for (int i = 0; i < MESSAGES_PER_THREAD; i++) { - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, DELAY); - producer.send(message); - } - session.close(); - connection.close(); - } catch (JMSException e) { - fail(e.getMessage()); + @Override + public void run() { + try { + ConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); + Connection connection = cf.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(session.createQueue(QUEUE_NAME)); + Message message = session.createTextMessage("test"); + for (int i = 0; i < MESSAGES_PER_THREAD; i++) { + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, DELAY); + producer.send(message); } - } - } + session.close(); + connection.close(); + } + catch (JMSException e) { + fail(e.getMessage()); + } + } + } - @Before - public void setup() throws Exception { - File schedulerDirectory = new File("target/test/ScheduledDB"); + @Before + public void setup() throws Exception { + File schedulerDirectory = new File("target/test/ScheduledDB"); - IOHelper.mkdirs(schedulerDirectory); - IOHelper.deleteChildren(schedulerDirectory); + IOHelper.mkdirs(schedulerDirectory); + IOHelper.deleteChildren(schedulerDirectory); - broker = new BrokerService(); - broker.setSchedulerSupport(true); - broker.setPersistent(true); - broker.setDeleteAllMessagesOnStartup(true); - broker.setDataDirectory("target"); - broker.setSchedulerDirectoryFile(schedulerDirectory); - broker.setUseJmx(false); - broker.addConnector("vm://localhost"); + broker = new BrokerService(); + broker.setSchedulerSupport(true); + broker.setPersistent(true); + broker.setDeleteAllMessagesOnStartup(true); + broker.setDataDirectory("target"); + broker.setSchedulerDirectoryFile(schedulerDirectory); + broker.setUseJmx(false); + broker.addConnector("vm://localhost"); - broker.start(); - broker.waitUntilStarted(); - } + broker.start(); + broker.waitUntilStarted(); + } - @After - public void tearDown() throws Exception { - broker.stop(); - } + @After + public void tearDown() throws Exception { + broker.stop(); + } - @Test - public void noMessageLostOnConcurrentScheduling() throws JMSException, InterruptedException { + @Test + public void noMessageLostOnConcurrentScheduling() throws JMSException, InterruptedException { - final AtomicLong receiveCounter = new AtomicLong(); + final AtomicLong receiveCounter = new AtomicLong(); - ConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = cf.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); + Connection connection = cf.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME)); - consumer.setMessageListener(new MessageListener() { + MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME)); + consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - receiveCounter.incrementAndGet(); - } - }); + @Override + public void onMessage(Message message) { + receiveCounter.incrementAndGet(); + } + }); - List senderThreads = new ArrayList(); - for (int i = 0; i < THREAD_COUNT; i++) { - Sender sender = new Sender(); - senderThreads.add(sender); - } - for (Sender sender : senderThreads) { - sender.start(); - } - for (Sender sender : senderThreads) { - sender.join(); - } + List senderThreads = new ArrayList(); + for (int i = 0; i < THREAD_COUNT; i++) { + Sender sender = new Sender(); + senderThreads.add(sender); + } + for (Sender sender : senderThreads) { + sender.start(); + } + for (Sender sender : senderThreads) { + sender.join(); + } - // wait until all scheduled messages has been received - TimeUnit.MINUTES.sleep(2); + // wait until all scheduled messages has been received + TimeUnit.MINUTES.sleep(2); - session.close(); - connection.close(); + session.close(); + connection.close(); - assertEquals(MESSAGES_PER_THREAD * THREAD_COUNT, receiveCounter.get()); - } + assertEquals(MESSAGES_PER_THREAD * THREAD_COUNT, receiveCounter.get()); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3141Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3141Test.java index 1209bd7a59..49db143ed3 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3141Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3141Test.java @@ -40,78 +40,78 @@ import org.junit.Test; public class AMQ3141Test { - private static final int MAX_MESSAGES = 100; + private static final int MAX_MESSAGES = 100; - private static final long DELAY_IN_MS = 100; + private static final long DELAY_IN_MS = 100; - private static final String QUEUE_NAME = "target.queue"; + private static final String QUEUE_NAME = "target.queue"; - private BrokerService broker; + private BrokerService broker; - private final CountDownLatch messageCountDown = new CountDownLatch(MAX_MESSAGES); + private final CountDownLatch messageCountDown = new CountDownLatch(MAX_MESSAGES); - private ConnectionFactory factory; + private ConnectionFactory factory; - @Before - public void setup() throws Exception { + @Before + public void setup() throws Exception { - broker = new BrokerService(); - broker.setPersistent(true); - broker.setSchedulerSupport(true); - broker.setDataDirectory("target"); - broker.setUseJmx(false); - broker.addConnector("vm://localhost"); + broker = new BrokerService(); + broker.setPersistent(true); + broker.setSchedulerSupport(true); + broker.setDataDirectory("target"); + broker.setUseJmx(false); + broker.addConnector("vm://localhost"); - File schedulerDirectory = new File("target/test/ScheduledDB"); - IOHelper.mkdirs(schedulerDirectory); - IOHelper.deleteChildren(schedulerDirectory); - broker.setSchedulerDirectoryFile(schedulerDirectory); + File schedulerDirectory = new File("target/test/ScheduledDB"); + IOHelper.mkdirs(schedulerDirectory); + IOHelper.deleteChildren(schedulerDirectory); + broker.setSchedulerDirectoryFile(schedulerDirectory); - broker.start(); - broker.waitUntilStarted(); + broker.start(); + broker.waitUntilStarted(); - factory = new ActiveMQConnectionFactory("vm://localhost"); - } + factory = new ActiveMQConnectionFactory("vm://localhost"); + } - private void sendMessages() throws Exception { - Connection connection = factory.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(session.createQueue(QUEUE_NAME)); - for (int i = 0; i < MAX_MESSAGES; i++) { - Message message = session.createTextMessage(); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, DELAY_IN_MS); - producer.send(message); - } - connection.close(); - } + private void sendMessages() throws Exception { + Connection connection = factory.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(session.createQueue(QUEUE_NAME)); + for (int i = 0; i < MAX_MESSAGES; i++) { + Message message = session.createTextMessage(); + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, DELAY_IN_MS); + producer.send(message); + } + connection.close(); + } - @Test - public void testNoMissingMessagesOnShortScheduleDelay() throws Exception { + @Test + public void testNoMissingMessagesOnShortScheduleDelay() throws Exception { - Connection connection = factory.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME)); + Connection connection = factory.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME)); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - messageCountDown.countDown(); - } - }); - sendMessages(); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + messageCountDown.countDown(); + } + }); + sendMessages(); - boolean receiveComplete = messageCountDown.await(5, TimeUnit.SECONDS); + boolean receiveComplete = messageCountDown.await(5, TimeUnit.SECONDS); - connection.close(); + connection.close(); - assertTrue("expect all messages received but " + messageCountDown.getCount() + " are missing", receiveComplete); - } + assertTrue("expect all messages received but " + messageCountDown.getCount() + " are missing", receiveComplete); + } - @After - public void tearDown() throws Exception { - broker.stop(); - } + @After + public void tearDown() throws Exception { + broker.stop(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3145Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3145Test.java index 81128bdac0..7e7c9598ca 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3145Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3145Test.java @@ -41,93 +41,89 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AMQ3145Test { - private static final Logger LOG = LoggerFactory.getLogger(AMQ3145Test.class); - private final String MESSAGE_TEXT = new String(new byte[1024]); - BrokerService broker; - ConnectionFactory factory; - Connection connection; - Session session; - Queue queue; - MessageConsumer consumer; - @Before - public void createBroker() throws Exception { - createBroker(true); - } + private static final Logger LOG = LoggerFactory.getLogger(AMQ3145Test.class); + private final String MESSAGE_TEXT = new String(new byte[1024]); + BrokerService broker; + ConnectionFactory factory; + Connection connection; + Session session; + Queue queue; + MessageConsumer consumer; - public void createBroker(boolean deleteAll) throws Exception { - broker = new BrokerService(); - broker.setDeleteAllMessagesOnStartup(deleteAll); - broker.setDataDirectory("target/AMQ3145Test"); - broker.setUseJmx(true); - broker.getManagementContext().setCreateConnector(false); - broker.addConnector("tcp://localhost:0"); - broker.start(); - broker.waitUntilStarted(); - factory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri().toString()); - connection = factory.createConnection(); - connection.start(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - } + @Before + public void createBroker() throws Exception { + createBroker(true); + } - @After - public void tearDown() throws Exception { - if (consumer != null) { - consumer.close(); - } - session.close(); - connection.stop(); - connection.close(); - broker.stop(); - } + public void createBroker(boolean deleteAll) throws Exception { + broker = new BrokerService(); + broker.setDeleteAllMessagesOnStartup(deleteAll); + broker.setDataDirectory("target/AMQ3145Test"); + broker.setUseJmx(true); + broker.getManagementContext().setCreateConnector(false); + broker.addConnector("tcp://localhost:0"); + broker.start(); + broker.waitUntilStarted(); + factory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri().toString()); + connection = factory.createConnection(); + connection.start(); + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + } - @Test - public void testCacheDisableReEnable() throws Exception { - createProducerAndSendMessages(1); - QueueViewMBean proxy = getProxyToQueueViewMBean(); - assertTrue("cache is enabled", proxy.isCacheEnabled()); - tearDown(); - createBroker(false); - proxy = getProxyToQueueViewMBean(); - assertEquals("one pending message", 1, proxy.getQueueSize()); - assertTrue("cache is disabled when there is a pending message", !proxy.isCacheEnabled()); + @After + public void tearDown() throws Exception { + if (consumer != null) { + consumer.close(); + } + session.close(); + connection.stop(); + connection.close(); + broker.stop(); + } - createConsumer(1); - createProducerAndSendMessages(1); - assertTrue("cache is enabled again on next send when there are no messages", proxy.isCacheEnabled()); - } + @Test + public void testCacheDisableReEnable() throws Exception { + createProducerAndSendMessages(1); + QueueViewMBean proxy = getProxyToQueueViewMBean(); + assertTrue("cache is enabled", proxy.isCacheEnabled()); + tearDown(); + createBroker(false); + proxy = getProxyToQueueViewMBean(); + assertEquals("one pending message", 1, proxy.getQueueSize()); + assertTrue("cache is disabled when there is a pending message", !proxy.isCacheEnabled()); - private QueueViewMBean getProxyToQueueViewMBean() - throws MalformedObjectNameException, JMSException { - ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq" - + ":destinationType=Queue,destinationName=" + queue.getQueueName() - + ",type=Broker,brokerName=localhost"); - QueueViewMBean proxy = (QueueViewMBean) broker.getManagementContext() - .newProxyInstance(queueViewMBeanName, - QueueViewMBean.class, true); - return proxy; - } + createConsumer(1); + createProducerAndSendMessages(1); + assertTrue("cache is enabled again on next send when there are no messages", proxy.isCacheEnabled()); + } - private void createProducerAndSendMessages(int numToSend) throws Exception { - queue = session.createQueue("test1"); - MessageProducer producer = session.createProducer(queue); - for (int i = 0; i < numToSend; i++) { - TextMessage message = session.createTextMessage(MESSAGE_TEXT + i); - if (i != 0 && i % 50000 == 0) { - LOG.info("sent: " + i); - } - producer.send(message); - } - producer.close(); - } + private QueueViewMBean getProxyToQueueViewMBean() throws MalformedObjectNameException, JMSException { + ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq" + ":destinationType=Queue,destinationName=" + queue.getQueueName() + ",type=Broker,brokerName=localhost"); + QueueViewMBean proxy = (QueueViewMBean) broker.getManagementContext().newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); + return proxy; + } - private void createConsumer(int numToConsume) throws Exception { - consumer = session.createConsumer(queue); - // wait for buffer fill out - for (int i = 0; i < numToConsume; ++i) { - Message message = consumer.receive(2000); - message.acknowledge(); - } - consumer.close(); - } + private void createProducerAndSendMessages(int numToSend) throws Exception { + queue = session.createQueue("test1"); + MessageProducer producer = session.createProducer(queue); + for (int i = 0; i < numToSend; i++) { + TextMessage message = session.createTextMessage(MESSAGE_TEXT + i); + if (i != 0 && i % 50000 == 0) { + LOG.info("sent: " + i); + } + producer.send(message); + } + producer.close(); + } + + private void createConsumer(int numToConsume) throws Exception { + consumer = session.createConsumer(queue); + // wait for buffer fill out + for (int i = 0; i < numToConsume; ++i) { + Message message = consumer.receive(2000); + message.acknowledge(); + } + consumer.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3157Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3157Test.java index f18af6ffc1..d0dcafd9f4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3157Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3157Test.java @@ -42,134 +42,133 @@ import org.slf4j.LoggerFactory; public class AMQ3157Test extends EmbeddedBrokerTestSupport { - private static final transient Logger LOG = LoggerFactory.getLogger(AMQ3157Test.class); - private Connection connection; + private static final transient Logger LOG = LoggerFactory.getLogger(AMQ3157Test.class); + private Connection connection; - public void testInactiveMirroredQueueIsCleanedUp() throws Exception { + public void testInactiveMirroredQueueIsCleanedUp() throws Exception { - if (connection == null) { - connection = createConnection(); - } - connection.start(); + if (connection == null) { + connection = createConnection(); + } + connection.start(); - ConsumerBean messageList = new ConsumerBean(); - messageList.setVerbose(true); + ConsumerBean messageList = new ConsumerBean(); + messageList.setVerbose(true); - ActiveMQDestination consumeDestination = createConsumeDestination(); + ActiveMQDestination consumeDestination = createConsumeDestination(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - LOG.info("Consuming from: " + consumeDestination); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + LOG.info("Consuming from: " + consumeDestination); - MessageConsumer c1 = session.createConsumer(consumeDestination); - c1.setMessageListener(messageList); + MessageConsumer c1 = session.createConsumer(consumeDestination); + c1.setMessageListener(messageList); - // create topic producer - ActiveMQQueue sendDestination = new ActiveMQQueue(getQueueName()); - LOG.info("Sending to: " + sendDestination); + // create topic producer + ActiveMQQueue sendDestination = new ActiveMQQueue(getQueueName()); + LOG.info("Sending to: " + sendDestination); - MessageProducer producer = session.createProducer(sendDestination); - assertNotNull(producer); + MessageProducer producer = session.createProducer(sendDestination); + assertNotNull(producer); - final int total = 10; - for (int i = 0; i < total; i++) { - producer.send(session.createTextMessage("message: " + i)); - } + final int total = 10; + for (int i = 0; i < total; i++) { + producer.send(session.createTextMessage("message: " + i)); + } - messageList.assertMessagesArrived(total); - LOG.info("Received: " + messageList); - messageList.flushMessages(); + messageList.assertMessagesArrived(total); + LOG.info("Received: " + messageList); + messageList.flushMessages(); - MessageConsumer c2 = session.createConsumer(sendDestination); - c2.setMessageListener(messageList); - messageList.assertMessagesArrived(total); - LOG.info("Q Received: " + messageList); + MessageConsumer c2 = session.createConsumer(sendDestination); + c2.setMessageListener(messageList); + messageList.assertMessagesArrived(total); + LOG.info("Q Received: " + messageList); - connection.close(); + connection.close(); - List topics = Arrays.asList(broker.getAdminView().getTopics()); - assertTrue(topics.contains(createObjectName(consumeDestination))); - List queues = Arrays.asList(broker.getAdminView().getQueues()); - assertTrue(queues.contains(createObjectName(sendDestination))); + List topics = Arrays.asList(broker.getAdminView().getTopics()); + assertTrue(topics.contains(createObjectName(consumeDestination))); + List queues = Arrays.asList(broker.getAdminView().getQueues()); + assertTrue(queues.contains(createObjectName(sendDestination))); - Thread.sleep(TimeUnit.SECONDS.toMillis(10)); + Thread.sleep(TimeUnit.SECONDS.toMillis(10)); - topics = Arrays.asList(broker.getAdminView().getTopics()); - if (topics != null) { - assertFalse("Virtual Topic Desination did not get cleaned up.", - topics.contains(createObjectName(consumeDestination))); - } - queues = Arrays.asList(broker.getAdminView().getQueues()); - if (queues != null) { - assertFalse("Mirrored Queue Desination did not get cleaned up.", - queues.contains(createObjectName(sendDestination))); - } - } + topics = Arrays.asList(broker.getAdminView().getTopics()); + if (topics != null) { + assertFalse("Virtual Topic Desination did not get cleaned up.", topics.contains(createObjectName(consumeDestination))); + } + queues = Arrays.asList(broker.getAdminView().getQueues()); + if (queues != null) { + assertFalse("Mirrored Queue Desination did not get cleaned up.", queues.contains(createObjectName(sendDestination))); + } + } - protected ActiveMQDestination createConsumeDestination() { - return new ActiveMQTopic("VirtualTopic.Mirror." + getQueueName()); - } + protected ActiveMQDestination createConsumeDestination() { + return new ActiveMQTopic("VirtualTopic.Mirror." + getQueueName()); + } - protected String getQueueName() { - return "My.Queue"; - } + protected String getQueueName() { + return "My.Queue"; + } - @Override - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setUseMirroredQueues(true); - answer.setPersistent(isPersistent()); - answer.setSchedulePeriodForDestinationPurge(1000); + @Override + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + answer.setUseMirroredQueues(true); + answer.setPersistent(isPersistent()); + answer.setSchedulePeriodForDestinationPurge(1000); - PolicyEntry entry = new PolicyEntry(); - entry.setGcInactiveDestinations(true); - entry.setInactiveTimoutBeforeGC(5000); - entry.setProducerFlowControl(true); - PolicyMap map = new PolicyMap(); - map.setDefaultEntry(entry); + PolicyEntry entry = new PolicyEntry(); + entry.setGcInactiveDestinations(true); + entry.setInactiveTimoutBeforeGC(5000); + entry.setProducerFlowControl(true); + PolicyMap map = new PolicyMap(); + map.setDefaultEntry(entry); - MirroredQueue mirrorQ = new MirroredQueue(); - mirrorQ.setCopyMessage(true); - DestinationInterceptor[] destinationInterceptors = new DestinationInterceptor[]{mirrorQ}; - answer.setDestinationInterceptors(destinationInterceptors); + MirroredQueue mirrorQ = new MirroredQueue(); + mirrorQ.setCopyMessage(true); + DestinationInterceptor[] destinationInterceptors = new DestinationInterceptor[]{mirrorQ}; + answer.setDestinationInterceptors(destinationInterceptors); - answer.setDestinationPolicy(map); - answer.addConnector(bindAddress); + answer.setDestinationPolicy(map); + answer.addConnector(bindAddress); - return answer; - } + return answer; + } - protected DestinationViewMBean createView(ActiveMQDestination destination) throws Exception { - String domain = "org.apache.activemq"; - ObjectName name; - if (destination.isQueue()) { - name = new ObjectName(domain + ":BrokerName=localhost,Type=Queue,Destination=" + destination.getPhysicalName()); - } else { - name = new ObjectName(domain + ":BrokerName=localhost,Type=Topic,Destination=" + destination.getPhysicalName()); - } - return (DestinationViewMBean) broker.getManagementContext().newProxyInstance(name, DestinationViewMBean.class, - true); - } + protected DestinationViewMBean createView(ActiveMQDestination destination) throws Exception { + String domain = "org.apache.activemq"; + ObjectName name; + if (destination.isQueue()) { + name = new ObjectName(domain + ":BrokerName=localhost,Type=Queue,Destination=" + destination.getPhysicalName()); + } + else { + name = new ObjectName(domain + ":BrokerName=localhost,Type=Topic,Destination=" + destination.getPhysicalName()); + } + return (DestinationViewMBean) broker.getManagementContext().newProxyInstance(name, DestinationViewMBean.class, true); + } - protected ObjectName createObjectName(ActiveMQDestination destination) throws Exception { - String domain = "org.apache.activemq"; - ObjectName name; - if (destination.isQueue()) { - name = new ObjectName(domain + ":type=Broker,brokerName=localhost," + + protected ObjectName createObjectName(ActiveMQDestination destination) throws Exception { + String domain = "org.apache.activemq"; + ObjectName name; + if (destination.isQueue()) { + name = new ObjectName(domain + ":type=Broker,brokerName=localhost," + "destinationType=Queue,destinationName=" + destination.getPhysicalName()); - } else { - name = new ObjectName(domain + ":type=Broker,brokerName=localhost," + + } + else { + name = new ObjectName(domain + ":type=Broker,brokerName=localhost," + "destinationType=Topic,destinationName=" + destination.getPhysicalName()); - } + } - return name; - } + return name; + } - @Override - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - super.tearDown(); - } + @Override + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + } + super.tearDown(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3167Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3167Test.java index 1a633d2c38..c0855abdec 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3167Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3167Test.java @@ -54,409 +54,418 @@ import org.junit.Test; */ public class AMQ3167Test { - protected BrokerService embeddedBroker; - protected static final int MEMORY_LIMIT = 16 * 1024; + protected BrokerService embeddedBroker; - protected static boolean Debug_f = false; + protected static final int MEMORY_LIMIT = 16 * 1024; - protected long Producer_stop_time = 0; - protected long Consumer_stop_time = 0; - protected long Consumer_startup_delay_ms = 2000; - protected boolean Stop_after_error = true; + protected static boolean Debug_f = false; - protected Connection JMS_conn; - protected long Num_error = 0; + protected long Producer_stop_time = 0; + protected long Consumer_stop_time = 0; + protected long Consumer_startup_delay_ms = 2000; + protected boolean Stop_after_error = true; - // // //// - // // UTILITIES //// - // // //// + protected Connection JMS_conn; + protected long Num_error = 0; - /** - * Create a new, unsecured, client connection to the test broker using the given username and password. This - * connection bypasses all security. - *
    - * Don't forget to start the connection or no messages will be received by consumers even though producers will work - * fine. - * - * @username name of the JMS user for the connection; may be null. - * @password Password for the JMS user; may be null. - */ + // // //// + // // UTILITIES //// + // // //// - protected Connection createUnsecuredConnection(String username, String password) throws javax.jms.JMSException { - ActiveMQConnectionFactory conn_fact; + /** + * Create a new, unsecured, client connection to the test broker using the given username and password. This + * connection bypasses all security. + *
    + * Don't forget to start the connection or no messages will be received by consumers even though producers will work + * fine. + * + * @username name of the JMS user for the connection; may be null. + * @password Password for the JMS user; may be null. + */ - conn_fact = new ActiveMQConnectionFactory(embeddedBroker.getVmConnectorURI()); + protected Connection createUnsecuredConnection(String username, String password) throws javax.jms.JMSException { + ActiveMQConnectionFactory conn_fact; - return conn_fact.createConnection(username, password); - } + conn_fact = new ActiveMQConnectionFactory(embeddedBroker.getVmConnectorURI()); - // // //// - // // TEST FUNCTIONALITY //// - // // //// + return conn_fact.createConnection(username, password); + } - @Before - public void testPrep() throws Exception { - embeddedBroker = new BrokerService(); - configureBroker(embeddedBroker); - embeddedBroker.start(); - embeddedBroker.waitUntilStarted(); + // // //// + // // TEST FUNCTIONALITY //// + // // //// - // Prepare the connection - JMS_conn = createUnsecuredConnection(null, null); - JMS_conn.start(); - } + @Before + public void testPrep() throws Exception { + embeddedBroker = new BrokerService(); + configureBroker(embeddedBroker); + embeddedBroker.start(); + embeddedBroker.waitUntilStarted(); - @After - public void testCleanup() throws java.lang.Exception { - JMS_conn.stop(); - embeddedBroker.stop(); - } + // Prepare the connection + JMS_conn = createUnsecuredConnection(null, null); + JMS_conn.start(); + } - protected void configureBroker(BrokerService broker_svc) throws Exception { + @After + public void testCleanup() throws java.lang.Exception { + JMS_conn.stop(); + embeddedBroker.stop(); + } - broker_svc.setBrokerName("testbroker1"); + protected void configureBroker(BrokerService broker_svc) throws Exception { - broker_svc.setUseJmx(false); - broker_svc.setPersistent(true); - broker_svc.setDataDirectory("target/AMQ3167Test"); - configureDestinationPolicy(broker_svc); - } + broker_svc.setBrokerName("testbroker1"); - /** - * NOTE: overrides any prior policy map defined for the broker service. - */ + broker_svc.setUseJmx(false); + broker_svc.setPersistent(true); + broker_svc.setDataDirectory("target/AMQ3167Test"); + configureDestinationPolicy(broker_svc); + } - protected void configureDestinationPolicy(BrokerService broker_svc) { - PolicyMap pol_map; - PolicyEntry pol_ent; - ArrayList ent_list; + /** + * NOTE: overrides any prior policy map defined for the broker service. + */ - ent_list = new ArrayList(); + protected void configureDestinationPolicy(BrokerService broker_svc) { + PolicyMap pol_map; + PolicyEntry pol_ent; + ArrayList ent_list; - // - // QUEUES - // + ent_list = new ArrayList(); - pol_ent = new PolicyEntry(); - pol_ent.setQueue(">"); - pol_ent.setMemoryLimit(MEMORY_LIMIT); - pol_ent.setProducerFlowControl(false); - ent_list.add(pol_ent); + // + // QUEUES + // - // - // COMPLETE POLICY MAP - // + pol_ent = new PolicyEntry(); + pol_ent.setQueue(">"); + pol_ent.setMemoryLimit(MEMORY_LIMIT); + pol_ent.setProducerFlowControl(false); + ent_list.add(pol_ent); - pol_map = new PolicyMap(); - pol_map.setPolicyEntries(ent_list); + // + // COMPLETE POLICY MAP + // - broker_svc.setDestinationPolicy(pol_map); - } + pol_map = new PolicyMap(); + pol_map.setPolicyEntries(ent_list); - // // //// - // // TEST //// - // // //// + broker_svc.setDestinationPolicy(pol_map); + } - @Test - public void testQueueLostMessage() throws Exception { - Destination dest; + // // //// + // // TEST //// + // // //// - dest = ActiveMQDestination.createDestination("lostmsgtest.queue", ActiveMQDestination.QUEUE_TYPE); + @Test + public void testQueueLostMessage() throws Exception { + Destination dest; - // 10 seconds from now - Producer_stop_time = java.lang.System.nanoTime() + (10L * 1000000000L); + dest = ActiveMQDestination.createDestination("lostmsgtest.queue", ActiveMQDestination.QUEUE_TYPE); - // 15 seconds from now - Consumer_stop_time = Producer_stop_time + (5L * 1000000000L); + // 10 seconds from now + Producer_stop_time = java.lang.System.nanoTime() + (10L * 1000000000L); - runLostMsgTest(dest, 1000000, 1, 1, false); + // 15 seconds from now + Consumer_stop_time = Producer_stop_time + (5L * 1000000000L); - // Make sure failures in the threads are thoroughly reported in the JUnit framework. - assertTrue(Num_error == 0); - } + runLostMsgTest(dest, 1000000, 1, 1, false); - /** - * - */ + // Make sure failures in the threads are thoroughly reported in the JUnit framework. + assertTrue(Num_error == 0); + } - protected static void log(String msg) { - if (Debug_f) - java.lang.System.err.println(msg); - } + /** + * + */ - /** - * Main body of the lost-message test. - */ + protected static void log(String msg) { + if (Debug_f) + java.lang.System.err.println(msg); + } - protected void runLostMsgTest(Destination dest, int num_msg, int num_send_per_sess, int num_recv_per_sess, boolean topic_f) throws Exception { - Thread prod_thread; - Thread cons_thread; - String tag; - Session sess; - MessageProducer prod; - MessageConsumer cons; - int ack_mode; + /** + * Main body of the lost-message test. + */ - // - // Start the producer - // + protected void runLostMsgTest(Destination dest, + int num_msg, + int num_send_per_sess, + int num_recv_per_sess, + boolean topic_f) throws Exception { + Thread prod_thread; + Thread cons_thread; + String tag; + Session sess; + MessageProducer prod; + MessageConsumer cons; + int ack_mode; - tag = "prod"; - log(">> Starting producer " + tag); + // + // Start the producer + // - sess = JMS_conn.createSession((num_send_per_sess > 1), Session.AUTO_ACKNOWLEDGE); - prod = sess.createProducer(dest); + tag = "prod"; + log(">> Starting producer " + tag); - prod_thread = new producerThread(sess, prod, tag, num_msg, num_send_per_sess); - prod_thread.start(); - log("Started producer " + tag); + sess = JMS_conn.createSession((num_send_per_sess > 1), Session.AUTO_ACKNOWLEDGE); + prod = sess.createProducer(dest); - // - // Delay before starting consumers - // + prod_thread = new producerThread(sess, prod, tag, num_msg, num_send_per_sess); + prod_thread.start(); + log("Started producer " + tag); - log("Waiting before starting consumers"); - java.lang.Thread.sleep(Consumer_startup_delay_ms); + // + // Delay before starting consumers + // - // - // Now create and start the consumer - // + log("Waiting before starting consumers"); + java.lang.Thread.sleep(Consumer_startup_delay_ms); - tag = "cons"; - log(">> Starting consumer"); + // + // Now create and start the consumer + // - if (num_recv_per_sess > 1) - ack_mode = Session.CLIENT_ACKNOWLEDGE; - else - ack_mode = Session.AUTO_ACKNOWLEDGE; + tag = "cons"; + log(">> Starting consumer"); - sess = JMS_conn.createSession(false, ack_mode); - cons = sess.createConsumer(dest); + if (num_recv_per_sess > 1) + ack_mode = Session.CLIENT_ACKNOWLEDGE; + else + ack_mode = Session.AUTO_ACKNOWLEDGE; - cons_thread = new consumerThread(sess, cons, tag, num_msg, num_recv_per_sess); - cons_thread.start(); - log("Started consumer " + tag); + sess = JMS_conn.createSession(false, ack_mode); + cons = sess.createConsumer(dest); - // - // Wait for the producer and consumer to finish. - // + cons_thread = new consumerThread(sess, cons, tag, num_msg, num_recv_per_sess); + cons_thread.start(); + log("Started consumer " + tag); - log("< waiting for producer."); - prod_thread.join(); + // + // Wait for the producer and consumer to finish. + // - log("< waiting for consumer."); - cons_thread.join(); + log("< waiting for producer."); + prod_thread.join(); - log("Shutting down"); - } + log("< waiting for consumer."); + cons_thread.join(); - // // //// - // // INTERNAL CLASSES //// - // // //// + log("Shutting down"); + } - /** - * Producer thread - runs a single producer until the maximum number of messages is sent, the producer stop time is - * reached, or a test error is detected. - */ + // // //// + // // INTERNAL CLASSES //// + // // //// - protected class producerThread extends Thread { - protected Session msgSess; - protected MessageProducer msgProd; - protected String producerTag; - protected int numMsg; - protected int numPerSess; - protected long producer_stop_time; + /** + * Producer thread - runs a single producer until the maximum number of messages is sent, the producer stop time is + * reached, or a test error is detected. + */ - producerThread(Session sess, MessageProducer prod, String tag, int num_msg, int sess_size) { - super(); + protected class producerThread extends Thread { - producer_stop_time = 0; - msgSess = sess; - msgProd = prod; - producerTag = tag; - numMsg = num_msg; - numPerSess = sess_size; - } + protected Session msgSess; + protected MessageProducer msgProd; + protected String producerTag; + protected int numMsg; + protected int numPerSess; + protected long producer_stop_time; - public void execTest() throws Exception { - Message msg; - int sess_start; - int cur; + producerThread(Session sess, MessageProducer prod, String tag, int num_msg, int sess_size) { + super(); - sess_start = 0; - cur = 0; - while ((cur < numMsg) && (!didTimeOut()) && ((!Stop_after_error) || (Num_error == 0))) { - msg = msgSess.createTextMessage("test message from " + producerTag); - msg.setStringProperty("testprodtag", producerTag); - msg.setIntProperty("seq", cur); + producer_stop_time = 0; + msgSess = sess; + msgProd = prod; + producerTag = tag; + numMsg = num_msg; + numPerSess = sess_size; + } - if (msg instanceof ActiveMQMessage) { - ((ActiveMQMessage) msg).setResponseRequired(true); - } + public void execTest() throws Exception { + Message msg; + int sess_start; + int cur; - // - // Send the message. - // + sess_start = 0; + cur = 0; + while ((cur < numMsg) && (!didTimeOut()) && ((!Stop_after_error) || (Num_error == 0))) { + msg = msgSess.createTextMessage("test message from " + producerTag); + msg.setStringProperty("testprodtag", producerTag); + msg.setIntProperty("seq", cur); - msgProd.send(msg); - cur++; - - // - // Commit if the number of messages per session has been reached, and - // transactions are being used (only when > 1 msg per sess). - // - - if ((numPerSess > 1) && ((cur - sess_start) >= numPerSess)) { - msgSess.commit(); - sess_start = cur; - } + if (msg instanceof ActiveMQMessage) { + ((ActiveMQMessage) msg).setResponseRequired(true); } - // Make sure to send the final commit, if there were sends since the last commit. - if ((numPerSess > 1) && ((cur - sess_start) > 0)) - msgSess.commit(); + // + // Send the message. + // - if (cur < numMsg) - log("* Producer " + producerTag + " timed out at " + java.lang.System.nanoTime() + " (stop time " + producer_stop_time + ")"); - } + msgProd.send(msg); + cur++; - /** - * Check whether it is time for the producer to terminate. - */ + // + // Commit if the number of messages per session has been reached, and + // transactions are being used (only when > 1 msg per sess). + // - protected boolean didTimeOut() { - if ((Producer_stop_time > 0) && (java.lang.System.nanoTime() >= Producer_stop_time)) - return true; - - return false; - } - - /** - * Run the producer. - */ - - @Override - public void run() { - try { - log("- running producer " + producerTag); - execTest(); - log("- finished running producer " + producerTag); - } catch (Throwable thrown) { - Num_error++; - fail("producer " + producerTag + " failed: " + thrown.getMessage()); - throw new Error("producer " + producerTag + " failed", thrown); + if ((numPerSess > 1) && ((cur - sess_start) >= numPerSess)) { + msgSess.commit(); + sess_start = cur; } - } + } - @Override - public String toString() { - return producerTag; - } - } + // Make sure to send the final commit, if there were sends since the last commit. + if ((numPerSess > 1) && ((cur - sess_start) > 0)) + msgSess.commit(); - /** - * Producer thread - runs a single consumer until the maximum number of messages is received, the consumer stop time - * is reached, or a test error is detected. - */ + if (cur < numMsg) + log("* Producer " + producerTag + " timed out at " + java.lang.System.nanoTime() + " (stop time " + producer_stop_time + ")"); + } - protected class consumerThread extends Thread { - protected Session msgSess; - protected MessageConsumer msgCons; - protected String consumerTag; - protected int numMsg; - protected int numPerSess; + /** + * Check whether it is time for the producer to terminate. + */ - consumerThread(Session sess, MessageConsumer cons, String tag, int num_msg, int sess_size) { - super(); + protected boolean didTimeOut() { + if ((Producer_stop_time > 0) && (java.lang.System.nanoTime() >= Producer_stop_time)) + return true; - msgSess = sess; - msgCons = cons; - consumerTag = tag; - numMsg = num_msg; - numPerSess = sess_size; - } + return false; + } - public void execTest() throws Exception { - Message msg; - int sess_start; - int cur; + /** + * Run the producer. + */ - msg = null; - sess_start = 0; - cur = 0; + @Override + public void run() { + try { + log("- running producer " + producerTag); + execTest(); + log("- finished running producer " + producerTag); + } + catch (Throwable thrown) { + Num_error++; + fail("producer " + producerTag + " failed: " + thrown.getMessage()); + throw new Error("producer " + producerTag + " failed", thrown); + } + } - while ((cur < numMsg) && (!didTimeOut()) && ((!Stop_after_error) || (Num_error == 0))) { - // - // Use a timeout of 1 second to periodically check the consumer timeout. - // - msg = msgCons.receive(1000); - if (msg != null) { - checkMessage(msg, cur); - cur++; + @Override + public String toString() { + return producerTag; + } + } - if ((numPerSess > 1) && ((cur - sess_start) >= numPerSess)) { - msg.acknowledge(); - sess_start = cur; - } - } + /** + * Producer thread - runs a single consumer until the maximum number of messages is received, the consumer stop time + * is reached, or a test error is detected. + */ + + protected class consumerThread extends Thread { + + protected Session msgSess; + protected MessageConsumer msgCons; + protected String consumerTag; + protected int numMsg; + protected int numPerSess; + + consumerThread(Session sess, MessageConsumer cons, String tag, int num_msg, int sess_size) { + super(); + + msgSess = sess; + msgCons = cons; + consumerTag = tag; + numMsg = num_msg; + numPerSess = sess_size; + } + + public void execTest() throws Exception { + Message msg; + int sess_start; + int cur; + + msg = null; + sess_start = 0; + cur = 0; + + while ((cur < numMsg) && (!didTimeOut()) && ((!Stop_after_error) || (Num_error == 0))) { + // + // Use a timeout of 1 second to periodically check the consumer timeout. + // + msg = msgCons.receive(1000); + if (msg != null) { + checkMessage(msg, cur); + cur++; + + if ((numPerSess > 1) && ((cur - sess_start) >= numPerSess)) { + msg.acknowledge(); + sess_start = cur; + } } + } - // Acknowledge the last messages, if they were not yet acknowledged. - if ((numPerSess > 1) && ((cur - sess_start) > 0)) - msg.acknowledge(); + // Acknowledge the last messages, if they were not yet acknowledged. + if ((numPerSess > 1) && ((cur - sess_start) > 0)) + msg.acknowledge(); - if (cur < numMsg) - log("* Consumer " + consumerTag + " timed out"); - } + if (cur < numMsg) + log("* Consumer " + consumerTag + " timed out"); + } - /** - * Check whether it is time for the consumer to terminate. - */ + /** + * Check whether it is time for the consumer to terminate. + */ - protected boolean didTimeOut() { - if ((Consumer_stop_time > 0) && (java.lang.System.nanoTime() >= Consumer_stop_time)) - return true; + protected boolean didTimeOut() { + if ((Consumer_stop_time > 0) && (java.lang.System.nanoTime() >= Consumer_stop_time)) + return true; - return false; - } + return false; + } - /** - * Verify the message received. Sequence numbers are checked and are expected to exactly match the message - * number (starting at 0). - */ + /** + * Verify the message received. Sequence numbers are checked and are expected to exactly match the message + * number (starting at 0). + */ - protected void checkMessage(Message msg, int exp_seq) throws javax.jms.JMSException { - int seq; + protected void checkMessage(Message msg, int exp_seq) throws javax.jms.JMSException { + int seq; - seq = msg.getIntProperty("seq"); + seq = msg.getIntProperty("seq"); - if (exp_seq != seq) { - Num_error++; - fail("*** Consumer " + consumerTag + " expected seq " + exp_seq + "; received " + seq); - } - } + if (exp_seq != seq) { + Num_error++; + fail("*** Consumer " + consumerTag + " expected seq " + exp_seq + "; received " + seq); + } + } - /** - * Run the consumer. - */ + /** + * Run the consumer. + */ - @Override - public void run() { - try { - log("- running consumer " + consumerTag); - execTest(); - log("- running consumer " + consumerTag); - } catch (Throwable thrown) { - Num_error++; - fail("consumer " + consumerTag + " failed: " + thrown.getMessage()); - throw new Error("consumer " + consumerTag + " failed", thrown); - } - } + @Override + public void run() { + try { + log("- running consumer " + consumerTag); + execTest(); + log("- running consumer " + consumerTag); + } + catch (Throwable thrown) { + Num_error++; + fail("consumer " + consumerTag + " failed: " + thrown.getMessage()); + throw new Error("consumer " + consumerTag + " failed", thrown); + } + } - @Override - public String toString() { - return consumerTag; - } - } + @Override + public String toString() { + return consumerTag; + } + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3274Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3274Test.java index 48c5cbb937..cdfe17ba20 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3274Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3274Test.java @@ -45,690 +45,715 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AMQ3274Test { - private static final transient Logger LOG = LoggerFactory.getLogger(AMQ3274Test.class); - protected static int Next_broker_num = 0; - protected EmbeddedTcpBroker broker1; - protected EmbeddedTcpBroker broker2; + private static final transient Logger LOG = LoggerFactory.getLogger(AMQ3274Test.class); + + protected static int Next_broker_num = 0; + protected EmbeddedTcpBroker broker1; + protected EmbeddedTcpBroker broker2; - protected int nextEchoId = 0; - protected boolean testError = false; + protected int nextEchoId = 0; + protected boolean testError = false; + + protected int echoResponseFill = 0; // Number of "filler" response messages per request + + public AMQ3274Test() throws Exception { + broker1 = new EmbeddedTcpBroker(); + broker2 = new EmbeddedTcpBroker(); + + broker1.coreConnectTo(broker2, true); + broker2.coreConnectTo(broker1, true); + } + + public void logMessage(String msg) { + System.out.println(msg); + System.out.flush(); + } + + public void testMessages(Session sess, + MessageProducer req_prod, + Destination resp_dest, + int num_msg) throws Exception { + MessageConsumer resp_cons; + TextMessage msg; + MessageClient cons_client; + int cur; + int tot_expected; - protected int echoResponseFill = 0; // Number of "filler" response messages per request + resp_cons = sess.createConsumer(resp_dest); - public AMQ3274Test() throws Exception { - broker1 = new EmbeddedTcpBroker(); - broker2 = new EmbeddedTcpBroker(); + cons_client = new MessageClient(resp_cons, num_msg); + cons_client.start(); - broker1.coreConnectTo(broker2, true); - broker2.coreConnectTo(broker1, true); - } + cur = 0; + while ((cur < num_msg) && (!testError)) { + msg = sess.createTextMessage("MSG AAAA " + cur); + msg.setIntProperty("SEQ", 100 + cur); + msg.setStringProperty("TEST", "TOPO"); + msg.setJMSReplyTo(resp_dest); - public void logMessage(String msg) { - System.out.println(msg); - System.out.flush(); - } + if (cur == (num_msg - 1)) + msg.setBooleanProperty("end-of-response", true); - public void testMessages(Session sess, MessageProducer req_prod, Destination resp_dest, int num_msg) throws Exception { - MessageConsumer resp_cons; - TextMessage msg; - MessageClient cons_client; - int cur; - int tot_expected; + req_prod.send(msg); + + cur++; + } - resp_cons = sess.createConsumer(resp_dest); + cons_client.waitShutdown(5000); - cons_client = new MessageClient(resp_cons, num_msg); - cons_client.start(); + if (cons_client.shutdown()) { + LOG.debug("Consumer client shutdown complete"); + } + else { + LOG.debug("Consumer client shutdown incomplete!!!"); + } - cur = 0; - while ((cur < num_msg) && (!testError)) { - msg = sess.createTextMessage("MSG AAAA " + cur); - msg.setIntProperty("SEQ", 100 + cur); - msg.setStringProperty("TEST", "TOPO"); - msg.setJMSReplyTo(resp_dest); + tot_expected = num_msg * (echoResponseFill + 1); - if (cur == (num_msg - 1)) - msg.setBooleanProperty("end-of-response", true); + if (cons_client.getNumMsgReceived() == tot_expected) { + LOG.info("Have " + tot_expected + " messages, as-expected"); + } + else { + LOG.error("Have " + cons_client.getNumMsgReceived() + " messages; expected " + tot_expected); + testError = true; + } - req_prod.send(msg); + resp_cons.close(); + } - cur++; - } + /** + * Test one destination between the given "producer broker" and + * "consumer broker" specified. + */ + public void testOneDest(Connection conn, + Session sess, + Destination cons_dest, + String prod_broker_url, + String cons_broker_url, + int num_msg) throws Exception { + int echo_id; - cons_client.waitShutdown(5000); + EchoService echo_svc; + String echo_queue_name; + Destination prod_dest; + MessageProducer msg_prod; - if (cons_client.shutdown()) { - LOG.debug("Consumer client shutdown complete"); - } else { - LOG.debug("Consumer client shutdown incomplete!!!"); - } + synchronized (this) { + echo_id = this.nextEchoId; + this.nextEchoId++; + } - tot_expected = num_msg * (echoResponseFill + 1); + echo_queue_name = "echo.queue." + echo_id; - if (cons_client.getNumMsgReceived() == tot_expected) { - LOG.info("Have " + tot_expected + " messages, as-expected"); - } else { - LOG.error("Have " + cons_client.getNumMsgReceived() + " messages; expected " + tot_expected); - testError = true; - } + LOG.trace("destroying the echo queue in case an old one exists"); + removeQueue(conn, echo_queue_name); - resp_cons.close(); - } + echo_svc = new EchoService(echo_queue_name, prod_broker_url); + echo_svc.start(); - /** - * Test one destination between the given "producer broker" and - * "consumer broker" specified. - */ - public void testOneDest(Connection conn, Session sess, Destination cons_dest, String prod_broker_url, String cons_broker_url, int num_msg) throws Exception { - int echo_id; + LOG.trace("Creating echo queue and producer"); + prod_dest = sess.createQueue(echo_queue_name); + msg_prod = sess.createProducer(prod_dest); - EchoService echo_svc; - String echo_queue_name; - Destination prod_dest; - MessageProducer msg_prod; + testMessages(sess, msg_prod, cons_dest, num_msg); - synchronized (this) { - echo_id = this.nextEchoId; - this.nextEchoId++; - } + echo_svc.shutdown(); + msg_prod.close(); + } - echo_queue_name = "echo.queue." + echo_id; + /** + * TEST TEMPORARY TOPICS + */ + public void testTempTopic(String prod_broker_url, String cons_broker_url) throws Exception { + Connection conn; + Session sess; + Destination cons_dest; + int num_msg; - LOG.trace("destroying the echo queue in case an old one exists"); - removeQueue(conn, echo_queue_name); + num_msg = 5; - echo_svc = new EchoService(echo_queue_name, prod_broker_url); - echo_svc.start(); + LOG.info("TESTING TEMP TOPICS " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)"); - LOG.trace("Creating echo queue and producer"); - prod_dest = sess.createQueue(echo_queue_name); - msg_prod = sess.createProducer(prod_dest); + conn = createConnection(cons_broker_url); + conn.start(); + sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - testMessages(sess, msg_prod, cons_dest, num_msg); + LOG.trace("Creating destination"); + cons_dest = sess.createTemporaryTopic(); - echo_svc.shutdown(); - msg_prod.close(); - } + testOneDest(conn, sess, cons_dest, prod_broker_url, cons_broker_url, num_msg); - /** - * TEST TEMPORARY TOPICS - */ - public void testTempTopic(String prod_broker_url, String cons_broker_url) throws Exception { - Connection conn; - Session sess; - Destination cons_dest; - int num_msg; + sess.close(); + conn.close(); + } - num_msg = 5; + /** + * TEST TOPICS + */ + public void testTopic(String prod_broker_url, String cons_broker_url) throws Exception { + int num_msg; - LOG.info("TESTING TEMP TOPICS " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)"); + Connection conn; + Session sess; + String topic_name; - conn = createConnection(cons_broker_url); - conn.start(); - sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination cons_dest; - LOG.trace("Creating destination"); - cons_dest = sess.createTemporaryTopic(); + num_msg = 5; - testOneDest(conn, sess, cons_dest, prod_broker_url, cons_broker_url, num_msg); + LOG.info("TESTING TOPICS " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)"); - sess.close(); - conn.close(); - } + conn = createConnection(cons_broker_url); + conn.start(); + sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - /** - * TEST TOPICS - */ - public void testTopic(String prod_broker_url, String cons_broker_url) throws Exception { - int num_msg; + topic_name = "topotest2.perm.topic"; + LOG.trace("Removing existing Topic"); + removeTopic(conn, topic_name); + LOG.trace("Creating Topic, " + topic_name); + cons_dest = sess.createTopic(topic_name); - Connection conn; - Session sess; - String topic_name; + testOneDest(conn, sess, cons_dest, prod_broker_url, cons_broker_url, num_msg); - Destination cons_dest; + removeTopic(conn, topic_name); + sess.close(); + conn.close(); + } - num_msg = 5; + /** + * TEST TEMPORARY QUEUES + */ + public void testTempQueue(String prod_broker_url, String cons_broker_url) throws Exception { + int num_msg; - LOG.info("TESTING TOPICS " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)"); + Connection conn; + Session sess; - conn = createConnection(cons_broker_url); - conn.start(); - sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination cons_dest; - topic_name = "topotest2.perm.topic"; - LOG.trace("Removing existing Topic"); - removeTopic(conn, topic_name); - LOG.trace("Creating Topic, " + topic_name); - cons_dest = sess.createTopic(topic_name); + num_msg = 5; - testOneDest(conn, sess, cons_dest, prod_broker_url, cons_broker_url, num_msg); + LOG.info("TESTING TEMP QUEUES " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)"); - removeTopic(conn, topic_name); - sess.close(); - conn.close(); - } + conn = createConnection(cons_broker_url); + conn.start(); + sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - /** - * TEST TEMPORARY QUEUES - */ - public void testTempQueue(String prod_broker_url, String cons_broker_url) throws Exception { - int num_msg; + LOG.trace("Creating destination"); + cons_dest = sess.createTemporaryQueue(); - Connection conn; - Session sess; + testOneDest(conn, sess, cons_dest, prod_broker_url, cons_broker_url, num_msg); - Destination cons_dest; + sess.close(); + conn.close(); + } - num_msg = 5; + /** + * TEST QUEUES + */ + public void testQueue(String prod_broker_url, String cons_broker_url) throws Exception { + int num_msg; - LOG.info("TESTING TEMP QUEUES " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)"); + Connection conn; + Session sess; + String queue_name; - conn = createConnection(cons_broker_url); - conn.start(); - sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination cons_dest; - LOG.trace("Creating destination"); - cons_dest = sess.createTemporaryQueue(); + num_msg = 5; - testOneDest(conn, sess, cons_dest, prod_broker_url, cons_broker_url, num_msg); + LOG.info("TESTING QUEUES " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)"); - sess.close(); - conn.close(); - } + conn = createConnection(cons_broker_url); + conn.start(); + sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - /** - * TEST QUEUES - */ - public void testQueue(String prod_broker_url, String cons_broker_url) throws Exception { - int num_msg; + queue_name = "topotest2.perm.queue"; + LOG.trace("Removing existing Queue"); + removeQueue(conn, queue_name); + LOG.trace("Creating Queue, " + queue_name); + cons_dest = sess.createQueue(queue_name); - Connection conn; - Session sess; - String queue_name; + testOneDest(conn, sess, cons_dest, prod_broker_url, cons_broker_url, num_msg); - Destination cons_dest; + removeQueue(conn, queue_name); + sess.close(); + conn.close(); + } - num_msg = 5; + @Test + public void run() throws Exception { + Thread start1; + Thread start2; - LOG.info("TESTING QUEUES " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)"); + testError = false; - conn = createConnection(cons_broker_url); - conn.start(); - sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + // Use threads to avoid startup deadlock since the first broker started waits until + // it knows the name of the remote broker before finishing its startup, which means + // the remote must already be running. - queue_name = "topotest2.perm.queue"; - LOG.trace("Removing existing Queue"); - removeQueue(conn, queue_name); - LOG.trace("Creating Queue, " + queue_name); - cons_dest = sess.createQueue(queue_name); - - testOneDest(conn, sess, cons_dest, prod_broker_url, cons_broker_url, num_msg); - - removeQueue(conn, queue_name); - sess.close(); - conn.close(); - } - - @Test - public void run() throws Exception { - Thread start1; - Thread start2; - - testError = false; - - // Use threads to avoid startup deadlock since the first broker started waits until - // it knows the name of the remote broker before finishing its startup, which means - // the remote must already be running. - - start1 = new Thread() { - public void run() { - try { - broker1.start(); - } catch (Exception ex) { - LOG.error(null, ex); - } + start1 = new Thread() { + public void run() { + try { + broker1.start(); } - }; - - start2 = new Thread() { - public void run() { - try { - broker2.start(); - } catch (Exception ex) { - LOG.error(null, ex); - } + catch (Exception ex) { + LOG.error(null, ex); } - }; + } + }; - start1.start(); - start2.start(); + start2 = new Thread() { + public void run() { + try { + broker2.start(); + } + catch (Exception ex) { + LOG.error(null, ex); + } + } + }; - start1.join(); - start2.join(); + start1.start(); + start2.start(); - if (!testError) { - this.testTempTopic(broker1.getConnectionUrl(), broker2.getConnectionUrl()); - } - if (!testError) { - this.testTempQueue(broker1.getConnectionUrl(), broker2.getConnectionUrl()); - } - if (!testError) { - this.testTopic(broker1.getConnectionUrl(), broker2.getConnectionUrl()); - } - if (!testError) { - this.testQueue(broker1.getConnectionUrl(), broker2.getConnectionUrl()); - } - Thread.sleep(100); + start1.join(); + start2.join(); - shutdown(); + if (!testError) { + this.testTempTopic(broker1.getConnectionUrl(), broker2.getConnectionUrl()); + } + if (!testError) { + this.testTempQueue(broker1.getConnectionUrl(), broker2.getConnectionUrl()); + } + if (!testError) { + this.testTopic(broker1.getConnectionUrl(), broker2.getConnectionUrl()); + } + if (!testError) { + this.testQueue(broker1.getConnectionUrl(), broker2.getConnectionUrl()); + } + Thread.sleep(100); - assertTrue(!testError); - } + shutdown(); - public void shutdown() throws Exception { - broker1.stop(); - broker2.stop(); - } + assertTrue(!testError); + } - /** - * @param args - * the command line arguments - */ - public static void main(String[] args) { - AMQ3274Test main_obj; + public void shutdown() throws Exception { + broker1.stop(); + broker2.stop(); + } - try { - main_obj = new AMQ3274Test(); - main_obj.run(); - } catch (Exception ex) { - ex.printStackTrace(); + /** + * @param args the command line arguments + */ + public static void main(String[] args) { + AMQ3274Test main_obj; + + try { + main_obj = new AMQ3274Test(); + main_obj.run(); + } + catch (Exception ex) { + ex.printStackTrace(); + LOG.error(null, ex); + System.exit(0); + } + } + + protected Connection createConnection(String url) throws Exception { + return org.apache.activemq.ActiveMQConnection.makeConnection(url); + } + + protected static void removeQueue(Connection conn, String dest_name) throws java.lang.Exception { + org.apache.activemq.command.ActiveMQDestination dest; + + if (conn instanceof org.apache.activemq.ActiveMQConnection) { + dest = org.apache.activemq.command.ActiveMQDestination.createDestination(dest_name, (byte) org.apache.activemq.command.ActiveMQDestination.QUEUE_TYPE); + ((org.apache.activemq.ActiveMQConnection) conn).destroyDestination(dest); + } + } + + protected static void removeTopic(Connection conn, String dest_name) throws java.lang.Exception { + org.apache.activemq.command.ActiveMQDestination dest; + + if (conn instanceof org.apache.activemq.ActiveMQConnection) { + dest = org.apache.activemq.command.ActiveMQDestination.createDestination(dest_name, (byte) org.apache.activemq.command.ActiveMQDestination.TOPIC_TYPE); + ((org.apache.activemq.ActiveMQConnection) conn).destroyDestination(dest); + } + } + + @SuppressWarnings("rawtypes") + public static String fmtMsgInfo(Message msg) throws Exception { + StringBuilder msg_desc; + String prop; + Enumeration prop_enum; + + msg_desc = new StringBuilder(); + msg_desc = new StringBuilder(); + + if (msg instanceof TextMessage) { + msg_desc.append(((TextMessage) msg).getText()); + } + else { + msg_desc.append("["); + msg_desc.append(msg.getClass().getName()); + msg_desc.append("]"); + } + + prop_enum = msg.getPropertyNames(); + while (prop_enum.hasMoreElements()) { + prop = (String) prop_enum.nextElement(); + msg_desc.append("; "); + msg_desc.append(prop); + msg_desc.append("="); + msg_desc.append(msg.getStringProperty(prop)); + } + + return msg_desc.toString(); + } + + // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // /////////////////////////////////////////////// INTERNAL CLASSES + // ///////////////////////////////////////////////// + // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + protected class EmbeddedTcpBroker { + + protected BrokerService brokerSvc; + protected int brokerNum; + protected String brokerName; + protected String brokerId; + protected int port; + protected String tcpUrl; + + public EmbeddedTcpBroker() throws Exception { + brokerSvc = new BrokerService(); + + synchronized (this.getClass()) { + brokerNum = Next_broker_num; + Next_broker_num++; + } + + brokerName = "broker" + brokerNum; + brokerId = "b" + brokerNum; + + brokerSvc.setBrokerName(brokerName); + brokerSvc.setBrokerId(brokerId); + brokerSvc.setPersistent(false); + brokerSvc.setUseJmx(false); + tcpUrl = brokerSvc.addConnector("tcp://localhost:0").getPublishableConnectString(); + } + + public Connection createConnection() throws URISyntaxException, JMSException { + Connection result; + + result = org.apache.activemq.ActiveMQConnection.makeConnection(this.tcpUrl); + + return result; + } + + public String getConnectionUrl() { + return this.tcpUrl; + } + + /** + * Create network connections to the given broker using the + * network-connector configuration of CORE brokers (e.g. + * core1.bus.dev1.coresys.tmcs) + * + * @param other + * @param duplex_f + */ + public void coreConnectTo(EmbeddedTcpBroker other, boolean duplex_f) throws Exception { + this.makeConnectionTo(other, duplex_f, true); + this.makeConnectionTo(other, duplex_f, false); + } + + public void start() throws Exception { + brokerSvc.start(); + } + + public void stop() throws Exception { + brokerSvc.stop(); + } + + /** + * Make one connection to the other embedded broker, of the specified + * type (queue or topic) using the standard CORE broker networking. + * + * @param other + * @param duplex_f + * @param queue_f + * @throws Exception + */ + protected void makeConnectionTo(EmbeddedTcpBroker other, boolean duplex_f, boolean queue_f) throws Exception { + NetworkConnector nw_conn; + String prefix; + ActiveMQDestination excl_dest; + ArrayList excludes; + + nw_conn = new DiscoveryNetworkConnector(new URI("static:(" + other.tcpUrl + ")")); + nw_conn.setDuplex(duplex_f); + + if (queue_f) + nw_conn.setConduitSubscriptions(false); + else + nw_conn.setConduitSubscriptions(true); + + nw_conn.setNetworkTTL(5); + nw_conn.setSuppressDuplicateQueueSubscriptions(true); + nw_conn.setDecreaseNetworkConsumerPriority(true); + nw_conn.setBridgeTempDestinations(true); + + if (queue_f) { + prefix = "queue"; + excl_dest = ActiveMQDestination.createDestination(">", ActiveMQDestination.QUEUE_TYPE); + } + else { + prefix = "topic"; + excl_dest = ActiveMQDestination.createDestination(">", ActiveMQDestination.TOPIC_TYPE); + } + + excludes = new ArrayList(); + excludes.add(excl_dest); + nw_conn.setExcludedDestinations(excludes); + + if (duplex_f) + nw_conn.setName(this.brokerId + "<-" + prefix + "->" + other.brokerId); + else + nw_conn.setName(this.brokerId + "-" + prefix + "->" + other.brokerId); + + brokerSvc.addNetworkConnector(nw_conn); + } + } + + protected class MessageClient extends java.lang.Thread { + + protected MessageConsumer msgCons; + protected boolean shutdownInd; + protected int expectedCount; + protected int lastSeq = 0; + protected int msgCount = 0; + protected boolean haveFirstSeq; + protected CountDownLatch shutdownLatch; + + public MessageClient(MessageConsumer cons, int num_to_expect) { + msgCons = cons; + expectedCount = (num_to_expect * (echoResponseFill + 1)); + shutdownLatch = new CountDownLatch(1); + } + + public void run() { + CountDownLatch latch; + + try { + synchronized (this) { + latch = shutdownLatch; + } + + shutdownInd = false; + processMessages(); + + latch.countDown(); + } + catch (Exception exc) { + LOG.error("message client error", exc); + } + } + + public void waitShutdown(long timeout) { + CountDownLatch latch; + + try { + synchronized (this) { + latch = shutdownLatch; + } + + if (latch != null) + latch.await(timeout, TimeUnit.MILLISECONDS); + else + LOG.info("echo client shutdown: client does not appear to be active"); + } + catch (InterruptedException int_exc) { + LOG.warn("wait for message client shutdown interrupted", int_exc); + } + } + + public boolean shutdown() { + boolean down_ind; + + if (!shutdownInd) { + shutdownInd = true; + } + + waitShutdown(200); + + synchronized (this) { + if ((shutdownLatch == null) || (shutdownLatch.getCount() == 0)) + down_ind = true; + else + down_ind = false; + } + + return down_ind; + } + + public int getNumMsgReceived() { + return msgCount; + } + + protected void processMessages() throws Exception { + Message in_msg; + + haveFirstSeq = false; + while ((!shutdownInd) && (!testError)) { + in_msg = msgCons.receive(100); + + if (in_msg != null) { + msgCount++; + checkMessage(in_msg); + } + } + } + + protected void checkMessage(Message in_msg) throws Exception { + int seq; + + LOG.debug("received message " + fmtMsgInfo(in_msg)); + + if (in_msg.propertyExists("SEQ")) { + seq = in_msg.getIntProperty("SEQ"); + + if ((haveFirstSeq) && (seq != (lastSeq + 1))) { + LOG.error("***ERROR*** incorrect sequence number; expected " + Integer.toString(lastSeq + 1) + " but have " + Integer.toString(seq)); + + testError = true; + } + + lastSeq = seq; + + if (msgCount > expectedCount) { + LOG.warn("*** have more messages than expected; have " + msgCount + "; expect " + expectedCount); + + testError = true; + } + } + + if (in_msg.propertyExists("end-of-response")) { + LOG.trace("received end-of-response message"); + shutdownInd = true; + } + } + } + + protected class EchoService extends java.lang.Thread { + + protected String destName; + protected Connection jmsConn; + protected Session sess; + protected MessageConsumer msg_cons; + protected boolean Shutdown_ind; + + protected Destination req_dest; + protected Destination resp_dest; + protected MessageProducer msg_prod; + + protected CountDownLatch waitShutdown; + + public EchoService(String dest, Connection broker_conn) throws Exception { + destName = dest; + jmsConn = broker_conn; + + Shutdown_ind = false; + + sess = jmsConn.createSession(false, Session.AUTO_ACKNOWLEDGE); + req_dest = sess.createQueue(destName); + msg_cons = sess.createConsumer(req_dest); + + jmsConn.start(); + + waitShutdown = new CountDownLatch(1); + } + + public EchoService(String dest, String broker_url) throws Exception { + this(dest, ActiveMQConnection.makeConnection(broker_url)); + } + + public void run() { + Message req; + + try { + LOG.info("STARTING ECHO SERVICE"); + + while (!Shutdown_ind) { + req = msg_cons.receive(100); + if (req != null) { + if (LOG.isDebugEnabled()) + LOG.debug("ECHO request message " + req.toString()); + + resp_dest = req.getJMSReplyTo(); + if (resp_dest != null) { + msg_prod = sess.createProducer(resp_dest); + msg_prod.send(req); + msg_prod.close(); + msg_prod = null; + } + else { + LOG.warn("invalid request: no reply-to destination given"); + } + } + } + } + catch (Exception ex) { LOG.error(null, ex); - System.exit(0); - } - } - - protected Connection createConnection(String url) throws Exception { - return org.apache.activemq.ActiveMQConnection.makeConnection(url); - } - - protected static void removeQueue(Connection conn, String dest_name) throws java.lang.Exception { - org.apache.activemq.command.ActiveMQDestination dest; - - if (conn instanceof org.apache.activemq.ActiveMQConnection) { - dest = org.apache.activemq.command.ActiveMQDestination.createDestination(dest_name, - (byte) org.apache.activemq.command.ActiveMQDestination.QUEUE_TYPE); - ((org.apache.activemq.ActiveMQConnection) conn).destroyDestination(dest); - } - } - - protected static void removeTopic(Connection conn, String dest_name) throws java.lang.Exception { - org.apache.activemq.command.ActiveMQDestination dest; - - if (conn instanceof org.apache.activemq.ActiveMQConnection) { - dest = org.apache.activemq.command.ActiveMQDestination.createDestination(dest_name, - (byte) org.apache.activemq.command.ActiveMQDestination.TOPIC_TYPE); - ((org.apache.activemq.ActiveMQConnection) conn).destroyDestination(dest); - } - } - - @SuppressWarnings("rawtypes") - public static String fmtMsgInfo(Message msg) throws Exception { - StringBuilder msg_desc; - String prop; - Enumeration prop_enum; - - msg_desc = new StringBuilder(); - msg_desc = new StringBuilder(); - - if (msg instanceof TextMessage) { - msg_desc.append(((TextMessage) msg).getText()); - } else { - msg_desc.append("["); - msg_desc.append(msg.getClass().getName()); - msg_desc.append("]"); - } - - prop_enum = msg.getPropertyNames(); - while (prop_enum.hasMoreElements()) { - prop = (String) prop_enum.nextElement(); - msg_desc.append("; "); - msg_desc.append(prop); - msg_desc.append("="); - msg_desc.append(msg.getStringProperty(prop)); - } - - return msg_desc.toString(); - } - - // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // /////////////////////////////////////////////// INTERNAL CLASSES - // ///////////////////////////////////////////////// - // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - protected class EmbeddedTcpBroker { - protected BrokerService brokerSvc; - protected int brokerNum; - protected String brokerName; - protected String brokerId; - protected int port; - protected String tcpUrl; - - public EmbeddedTcpBroker() throws Exception { - brokerSvc = new BrokerService(); - - synchronized (this.getClass()) { - brokerNum = Next_broker_num; - Next_broker_num++; - } - - brokerName = "broker" + brokerNum; - brokerId = "b" + brokerNum; - - brokerSvc.setBrokerName(brokerName); - brokerSvc.setBrokerId(brokerId); - brokerSvc.setPersistent(false); - brokerSvc.setUseJmx(false); - tcpUrl = brokerSvc.addConnector("tcp://localhost:0").getPublishableConnectString(); - } - - public Connection createConnection() throws URISyntaxException, JMSException { - Connection result; - - result = org.apache.activemq.ActiveMQConnection.makeConnection(this.tcpUrl); - - return result; - } - - public String getConnectionUrl() { - return this.tcpUrl; - } - - /** - * Create network connections to the given broker using the - * network-connector configuration of CORE brokers (e.g. - * core1.bus.dev1.coresys.tmcs) - * - * @param other - * @param duplex_f - */ - public void coreConnectTo(EmbeddedTcpBroker other, boolean duplex_f) throws Exception { - this.makeConnectionTo(other, duplex_f, true); - this.makeConnectionTo(other, duplex_f, false); - } - - public void start() throws Exception { - brokerSvc.start(); - } - - public void stop() throws Exception { - brokerSvc.stop(); - } - - /** - * Make one connection to the other embedded broker, of the specified - * type (queue or topic) using the standard CORE broker networking. - * - * @param other - * @param duplex_f - * @param queue_f - * @throws Exception - */ - protected void makeConnectionTo(EmbeddedTcpBroker other, boolean duplex_f, boolean queue_f) throws Exception { - NetworkConnector nw_conn; - String prefix; - ActiveMQDestination excl_dest; - ArrayList excludes; - - nw_conn = new DiscoveryNetworkConnector(new URI("static:(" + other.tcpUrl + ")")); - nw_conn.setDuplex(duplex_f); - - if (queue_f) - nw_conn.setConduitSubscriptions(false); - else - nw_conn.setConduitSubscriptions(true); - - nw_conn.setNetworkTTL(5); - nw_conn.setSuppressDuplicateQueueSubscriptions(true); - nw_conn.setDecreaseNetworkConsumerPriority(true); - nw_conn.setBridgeTempDestinations(true); - - if (queue_f) { - prefix = "queue"; - excl_dest = ActiveMQDestination.createDestination(">", ActiveMQDestination.QUEUE_TYPE); - } else { - prefix = "topic"; - excl_dest = ActiveMQDestination.createDestination(">", ActiveMQDestination.TOPIC_TYPE); - } - - excludes = new ArrayList(); - excludes.add(excl_dest); - nw_conn.setExcludedDestinations(excludes); - - if (duplex_f) - nw_conn.setName(this.brokerId + "<-" + prefix + "->" + other.brokerId); - else - nw_conn.setName(this.brokerId + "-" + prefix + "->" + other.brokerId); - - brokerSvc.addNetworkConnector(nw_conn); - } - } - - protected class MessageClient extends java.lang.Thread { - protected MessageConsumer msgCons; - protected boolean shutdownInd; - protected int expectedCount; - protected int lastSeq = 0; - protected int msgCount = 0; - protected boolean haveFirstSeq; - protected CountDownLatch shutdownLatch; - - public MessageClient(MessageConsumer cons, int num_to_expect) { - msgCons = cons; - expectedCount = (num_to_expect * (echoResponseFill + 1)); - shutdownLatch = new CountDownLatch(1); - } - - public void run() { - CountDownLatch latch; + } + finally { + LOG.info("shutting down test echo service"); try { - synchronized (this) { - latch = shutdownLatch; - } - - shutdownInd = false; - processMessages(); - - latch.countDown(); - } catch (Exception exc) { - LOG.error("message client error", exc); + jmsConn.stop(); } - } - - public void waitShutdown(long timeout) { - CountDownLatch latch; - - try { - synchronized (this) { - latch = shutdownLatch; - } - - if (latch != null) - latch.await(timeout, TimeUnit.MILLISECONDS); - else - LOG.info("echo client shutdown: client does not appear to be active"); - } catch (InterruptedException int_exc) { - LOG.warn("wait for message client shutdown interrupted", int_exc); + catch (javax.jms.JMSException jms_exc) { + LOG.warn("error on shutting down JMS connection", jms_exc); } - } - - public boolean shutdown() { - boolean down_ind; - - if (!shutdownInd) { - shutdownInd = true; - } - - waitShutdown(200); synchronized (this) { - if ((shutdownLatch == null) || (shutdownLatch.getCount() == 0)) - down_ind = true; - else - down_ind = false; + waitShutdown.countDown(); } + } + } - return down_ind; - } + /** + * Shut down the service, waiting up to 3 seconds for the service to + * terminate. + */ + public void shutdown() { + CountDownLatch wait_l; - public int getNumMsgReceived() { - return msgCount; - } + synchronized (this) { + wait_l = waitShutdown; + } - protected void processMessages() throws Exception { - Message in_msg; + Shutdown_ind = true; - haveFirstSeq = false; - while ((!shutdownInd) && (!testError)) { - in_msg = msgCons.receive(100); - - if (in_msg != null) { - msgCount++; - checkMessage(in_msg); - } + try { + if (wait_l != null) { + if (wait_l.await(3000, TimeUnit.MILLISECONDS)) { + LOG.info("echo service shutdown complete"); + } + else { + LOG.warn("timeout waiting for echo service shutdown"); + } } - } - - protected void checkMessage(Message in_msg) throws Exception { - int seq; - - LOG.debug("received message " + fmtMsgInfo(in_msg)); - - if (in_msg.propertyExists("SEQ")) { - seq = in_msg.getIntProperty("SEQ"); - - if ((haveFirstSeq) && (seq != (lastSeq + 1))) { - LOG.error("***ERROR*** incorrect sequence number; expected " + Integer.toString(lastSeq + 1) + " but have " + Integer.toString(seq)); - - testError = true; - } - - lastSeq = seq; - - if (msgCount > expectedCount) { - LOG.warn("*** have more messages than expected; have " + msgCount + "; expect " + expectedCount); - - testError = true; - } + else { + LOG.info("echo service shutdown: service does not appear to be active"); } - - if (in_msg.propertyExists("end-of-response")) { - LOG.trace("received end-of-response message"); - shutdownInd = true; - } - } - } - - protected class EchoService extends java.lang.Thread { - protected String destName; - protected Connection jmsConn; - protected Session sess; - protected MessageConsumer msg_cons; - protected boolean Shutdown_ind; - - protected Destination req_dest; - protected Destination resp_dest; - protected MessageProducer msg_prod; - - protected CountDownLatch waitShutdown; - - public EchoService(String dest, Connection broker_conn) throws Exception { - destName = dest; - jmsConn = broker_conn; - - Shutdown_ind = false; - - sess = jmsConn.createSession(false, Session.AUTO_ACKNOWLEDGE); - req_dest = sess.createQueue(destName); - msg_cons = sess.createConsumer(req_dest); - - jmsConn.start(); - - waitShutdown = new CountDownLatch(1); - } - - public EchoService(String dest, String broker_url) throws Exception { - this(dest, ActiveMQConnection.makeConnection(broker_url)); - } - - public void run() { - Message req; - - try { - LOG.info("STARTING ECHO SERVICE"); - - while (!Shutdown_ind) { - req = msg_cons.receive(100); - if (req != null) { - if (LOG.isDebugEnabled()) - LOG.debug("ECHO request message " + req.toString()); - - resp_dest = req.getJMSReplyTo(); - if (resp_dest != null) { - msg_prod = sess.createProducer(resp_dest); - msg_prod.send(req); - msg_prod.close(); - msg_prod = null; - } else { - LOG.warn("invalid request: no reply-to destination given"); - } - } - } - } catch (Exception ex) { - LOG.error(null, ex); - } finally { - LOG.info("shutting down test echo service"); - - try { - jmsConn.stop(); - } catch (javax.jms.JMSException jms_exc) { - LOG.warn("error on shutting down JMS connection", jms_exc); - } - - synchronized (this) { - waitShutdown.countDown(); - } - } - } - - /** - * Shut down the service, waiting up to 3 seconds for the service to - * terminate. - */ - public void shutdown() { - CountDownLatch wait_l; - - synchronized (this) { - wait_l = waitShutdown; - } - - Shutdown_ind = true; - - try { - if (wait_l != null) { - if (wait_l.await(3000, TimeUnit.MILLISECONDS)) { - LOG.info("echo service shutdown complete"); - } else { - LOG.warn("timeout waiting for echo service shutdown"); - } - } else { - LOG.info("echo service shutdown: service does not appear to be active"); - } - } catch (InterruptedException int_exc) { - LOG.warn("interrupted while waiting for echo service shutdown"); - } - } - } + } + catch (InterruptedException int_exc) { + LOG.warn("interrupted while waiting for echo service shutdown"); + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3324Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3324Test.java index a1e9b93141..40761f40da 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3324Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3324Test.java @@ -45,104 +45,104 @@ import org.slf4j.LoggerFactory; public class AMQ3324Test { - private static final transient Logger LOG = LoggerFactory.getLogger(AMQ3324Test.class); + private static final transient Logger LOG = LoggerFactory.getLogger(AMQ3324Test.class); - private static final String bindAddress = "tcp://0.0.0.0:0"; - private BrokerService broker; - private ActiveMQConnectionFactory cf; + private static final String bindAddress = "tcp://0.0.0.0:0"; + private BrokerService broker; + private ActiveMQConnectionFactory cf; - private static final int MESSAGE_COUNT = 100; + private static final int MESSAGE_COUNT = 100; - @Before - public void setUp() throws Exception { - broker = this.createBroker(); - String address = broker.getTransportConnectors().get(0).getPublishableConnectString(); - broker.start(); - broker.waitUntilStarted(); + @Before + public void setUp() throws Exception { + broker = this.createBroker(); + String address = broker.getTransportConnectors().get(0).getPublishableConnectString(); + broker.start(); + broker.waitUntilStarted(); - cf = new ActiveMQConnectionFactory(address); - } + cf = new ActiveMQConnectionFactory(address); + } - @After - public void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - } + @After + public void tearDown() throws Exception { + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + } - @Test - public void testTempMessageConsumedAdvisoryConnectionClose() throws Exception { + @Test + public void testTempMessageConsumedAdvisoryConnectionClose() throws Exception { - Connection connection = cf.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Connection connection = cf.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final TemporaryQueue queue = session.createTemporaryQueue(); - MessageConsumer consumer = session.createConsumer(queue); + final TemporaryQueue queue = session.createTemporaryQueue(); + MessageConsumer consumer = session.createConsumer(queue); - final Topic advisoryTopic = AdvisorySupport.getMessageConsumedAdvisoryTopic((ActiveMQDestination) queue); + final Topic advisoryTopic = AdvisorySupport.getMessageConsumedAdvisoryTopic((ActiveMQDestination) queue); - MessageConsumer advisoryConsumer = session.createConsumer(advisoryTopic); - MessageProducer producer = session.createProducer(queue); + MessageConsumer advisoryConsumer = session.createConsumer(advisoryTopic); + MessageProducer producer = session.createProducer(queue); - // send lots of messages to the tempQueue - for (int i = 0; i < MESSAGE_COUNT; i++) { - BytesMessage m = session.createBytesMessage(); - m.writeBytes(new byte[1024]); - producer.send(m); - } + // send lots of messages to the tempQueue + for (int i = 0; i < MESSAGE_COUNT; i++) { + BytesMessage m = session.createBytesMessage(); + m.writeBytes(new byte[1024]); + producer.send(m); + } - // consume one message from tempQueue - Message msg = consumer.receive(5000); - assertNotNull(msg); + // consume one message from tempQueue + Message msg = consumer.receive(5000); + assertNotNull(msg); - // check one advisory message has produced on the advisoryTopic - Message advCmsg = advisoryConsumer.receive(5000); - assertNotNull(advCmsg); + // check one advisory message has produced on the advisoryTopic + Message advCmsg = advisoryConsumer.receive(5000); + assertNotNull(advCmsg); - connection.close(); - LOG.debug("Connection closed, destinations should now become inactive."); + connection.close(); + LOG.debug("Connection closed, destinations should now become inactive."); - assertTrue("The destination " + advisoryTopic + "was not removed. ", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return broker.getAdminView().getTopics().length == 0; - } - })); + assertTrue("The destination " + advisoryTopic + "was not removed. ", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return broker.getAdminView().getTopics().length == 0; + } + })); - assertTrue("The destination " + queue + " was not removed. ", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return broker.getAdminView().getTemporaryQueues().length == 0; - } - })); - } + assertTrue("The destination " + queue + " was not removed. ", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return broker.getAdminView().getTemporaryQueues().length == 0; + } + })); + } - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setUseMirroredQueues(true); - answer.setPersistent(false); - answer.setSchedulePeriodForDestinationPurge(1000); + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + answer.setUseMirroredQueues(true); + answer.setPersistent(false); + answer.setSchedulePeriodForDestinationPurge(1000); - PolicyEntry entry = new PolicyEntry(); - entry.setGcInactiveDestinations(true); - entry.setInactiveTimoutBeforeGC(2000); - entry.setProducerFlowControl(true); - entry.setAdvisoryForConsumed(true); - entry.setAdvisoryForFastProducers(true); - entry.setAdvisoryForDelivery(true); - PolicyMap map = new PolicyMap(); - map.setDefaultEntry(entry); + PolicyEntry entry = new PolicyEntry(); + entry.setGcInactiveDestinations(true); + entry.setInactiveTimoutBeforeGC(2000); + entry.setProducerFlowControl(true); + entry.setAdvisoryForConsumed(true); + entry.setAdvisoryForFastProducers(true); + entry.setAdvisoryForDelivery(true); + PolicyMap map = new PolicyMap(); + map.setDefaultEntry(entry); - MirroredQueue mirrorQ = new MirroredQueue(); - mirrorQ.setCopyMessage(true); - DestinationInterceptor[] destinationInterceptors = new DestinationInterceptor[]{mirrorQ}; - answer.setDestinationInterceptors(destinationInterceptors); + MirroredQueue mirrorQ = new MirroredQueue(); + mirrorQ.setCopyMessage(true); + DestinationInterceptor[] destinationInterceptors = new DestinationInterceptor[]{mirrorQ}; + answer.setDestinationInterceptors(destinationInterceptors); - answer.setDestinationPolicy(map); - answer.addConnector(bindAddress); + answer.setDestinationPolicy(map); + answer.addConnector(bindAddress); - return answer; - } + return answer; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3352Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3352Test.java index aa84d2d541..6f27bdd9c0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3352Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3352Test.java @@ -28,48 +28,47 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -public class AMQ3352Test -{ - TransportConnector connector; - BrokerService brokerService; +public class AMQ3352Test { - @Before - public void startBroker() throws Exception { - brokerService = new BrokerService(); - brokerService.setDeleteAllMessagesOnStartup(true); - connector = brokerService.addConnector("tcp://0.0.0.0:0"); - brokerService.start(); - } + TransportConnector connector; + BrokerService brokerService; - @After - public void stopBroker() throws Exception { - brokerService.stop(); - } + @Before + public void startBroker() throws Exception { + brokerService = new BrokerService(); + brokerService.setDeleteAllMessagesOnStartup(true); + connector = brokerService.addConnector("tcp://0.0.0.0:0"); + brokerService.start(); + } + + @After + public void stopBroker() throws Exception { + brokerService.stop(); + } @Test public void verifyEnqueueLargeNumWithStateTracker() throws Exception { - String url = "failover:(" + connector.getPublishableConnectString() + ")?jms.useAsyncSend=true&trackMessages=true&maxCacheSize=131072"; + String url = "failover:(" + connector.getPublishableConnectString() + ")?jms.useAsyncSend=true&trackMessages=true&maxCacheSize=131072"; - ActiveMQConnection conn = (ActiveMQConnection)new ActiveMQConnectionFactory(url).createConnection(null, null); + ActiveMQConnection conn = (ActiveMQConnection) new ActiveMQConnectionFactory(url).createConnection(null, null); - Session session = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Session session = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(session.createQueue("EVENTQ")); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - producer.setDisableMessageID(true); - producer.setDisableMessageTimestamp(true); + MessageProducer producer = session.createProducer(session.createQueue("EVENTQ")); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + producer.setDisableMessageID(true); + producer.setDisableMessageTimestamp(true); - StringBuffer buffer = new StringBuffer(); - for (int i=0;i<1024;i++) - { - buffer.append(String.valueOf(Math.random())); - } - String payload = buffer.toString(); + StringBuffer buffer = new StringBuffer(); + for (int i = 0; i < 1024; i++) { + buffer.append(String.valueOf(Math.random())); + } + String payload = buffer.toString(); - for (int i=0; i<10000; i++) { - StringBuffer buff = new StringBuffer("x"); - buff.append(payload); - producer.send(session.createTextMessage(buff.toString())); - } - } + for (int i = 0; i < 10000; i++) { + StringBuffer buff = new StringBuffer("x"); + buff.append(payload); + producer.send(session.createTextMessage(buff.toString())); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3405Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3405Test.java index 9711d06361..39cf640637 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3405Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3405Test.java @@ -48,233 +48,236 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AMQ3405Test extends TestSupport { - private static final Logger LOG = LoggerFactory.getLogger(AMQ3405Test.class); - private Connection connection; - private Session session; - private MessageConsumer consumer; - private MessageProducer producer; - private int deliveryMode = DeliveryMode.PERSISTENT; - private Destination dlqDestination; - private MessageConsumer dlqConsumer; - private BrokerService broker; + private static final Logger LOG = LoggerFactory.getLogger(AMQ3405Test.class); - private int messageCount; - private Destination destination; - private int rollbackCount; - private Session dlqSession; - private final Error[] error = new Error[1]; - private boolean topic = true; - private boolean durableSubscriber = true; + private Connection connection; + private Session session; + private MessageConsumer consumer; + private MessageProducer producer; + private int deliveryMode = DeliveryMode.PERSISTENT; + private Destination dlqDestination; + private MessageConsumer dlqConsumer; + private BrokerService broker; - public void testTransientTopicMessage() throws Exception { - topic = true; - deliveryMode = DeliveryMode.NON_PERSISTENT; - durableSubscriber = true; - doTest(); - } + private int messageCount; + private Destination destination; + private int rollbackCount; + private Session dlqSession; + private final Error[] error = new Error[1]; + private boolean topic = true; + private boolean durableSubscriber = true; - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setPersistent(false); - PolicyEntry policy = new PolicyEntry(); - DeadLetterStrategy defaultDeadLetterStrategy = policy.getDeadLetterStrategy(); - if(defaultDeadLetterStrategy!=null) { - defaultDeadLetterStrategy.setProcessNonPersistent(true); - } - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - broker.setDestinationPolicy(pMap); - return broker; - } + public void testTransientTopicMessage() throws Exception { + topic = true; + deliveryMode = DeliveryMode.NON_PERSISTENT; + durableSubscriber = true; + doTest(); + } - protected void doTest() throws Exception { - messageCount = 200; - connection.start(); + protected BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setPersistent(false); + PolicyEntry policy = new PolicyEntry(); + DeadLetterStrategy defaultDeadLetterStrategy = policy.getDeadLetterStrategy(); + if (defaultDeadLetterStrategy != null) { + defaultDeadLetterStrategy.setProcessNonPersistent(true); + } + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); + broker.setDestinationPolicy(pMap); + return broker; + } - final QueueViewMBean dlqView = getProxyToDLQ(); + protected void doTest() throws Exception { + messageCount = 200; + connection.start(); - ActiveMQConnection amqConnection = (ActiveMQConnection) connection; - rollbackCount = amqConnection.getRedeliveryPolicy().getMaximumRedeliveries() + 1; - LOG.info("Will redeliver messages: " + rollbackCount + " times"); + final QueueViewMBean dlqView = getProxyToDLQ(); - makeConsumer(); - makeDlqConsumer(); - dlqConsumer.close(); + ActiveMQConnection amqConnection = (ActiveMQConnection) connection; + rollbackCount = amqConnection.getRedeliveryPolicy().getMaximumRedeliveries() + 1; + LOG.info("Will redeliver messages: " + rollbackCount + " times"); - sendMessages(); + makeConsumer(); + makeDlqConsumer(); + dlqConsumer.close(); - // now lets receive and rollback N times - int maxRollbacks = messageCount * rollbackCount; + sendMessages(); - consumer.setMessageListener(new RollbackMessageListener(maxRollbacks, rollbackCount)); + // now lets receive and rollback N times + int maxRollbacks = messageCount * rollbackCount; - // We receive and rollback into the DLQ N times moving the DLQ messages back to their - // original Q to test that they are continually placed back in the DLQ. - for (int i = 0; i < 2; ++i) { + consumer.setMessageListener(new RollbackMessageListener(maxRollbacks, rollbackCount)); - assertTrue("DLQ was not filled as expected", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return dlqView.getQueueSize() == messageCount; - } - })); + // We receive and rollback into the DLQ N times moving the DLQ messages back to their + // original Q to test that they are continually placed back in the DLQ. + for (int i = 0; i < 2; ++i) { - connection.stop(); - - assertEquals("DLQ should be full now.", messageCount, dlqView.getQueueSize()); - - String moveTo; - if (topic) { - moveTo = "topic://" + ((Topic) getDestination()).getTopicName(); - } else { - moveTo = "queue://" + ((Queue) getDestination()).getQueueName(); + assertTrue("DLQ was not filled as expected", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return dlqView.getQueueSize() == messageCount; } + })); - LOG.debug("Moving " + messageCount + " messages from ActiveMQ.DLQ to " + moveTo); - dlqView.moveMatchingMessagesTo("", moveTo); + connection.stop(); - assertTrue("DLQ was not emptied as expected", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return dlqView.getQueueSize() == 0; - } - })); + assertEquals("DLQ should be full now.", messageCount, dlqView.getQueueSize()); - connection.start(); - } - } + String moveTo; + if (topic) { + moveTo = "topic://" + ((Topic) getDestination()).getTopicName(); + } + else { + moveTo = "queue://" + ((Queue) getDestination()).getQueueName(); + } - protected void makeConsumer() throws JMSException { - Destination destination = getDestination(); - LOG.info("Consuming from: " + destination); - if (durableSubscriber) { - consumer = session.createDurableSubscriber((Topic)destination, destination.toString()); - } else { - consumer = session.createConsumer(destination); - } - } + LOG.debug("Moving " + messageCount + " messages from ActiveMQ.DLQ to " + moveTo); + dlqView.moveMatchingMessagesTo("", moveTo); - protected void makeDlqConsumer() throws JMSException { - dlqDestination = createDlqDestination(); - - LOG.info("Consuming from dead letter on: " + dlqDestination); - dlqConsumer = dlqSession.createConsumer(dlqDestination); - } - - @Override - protected void setUp() throws Exception { - broker = createBroker(); - broker.start(); - broker.waitUntilStarted(); - - connection = createConnection(); - connection.setClientID(createClientId()); - - session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - connection.start(); - - dlqSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } - - @Override - protected void tearDown() throws Exception { - dlqConsumer.close(); - dlqSession.close(); - session.close(); - - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - }; - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() - throws Exception { - ActiveMQConnectionFactory answer = super.createConnectionFactory(); - RedeliveryPolicy policy = new RedeliveryPolicy(); - policy.setMaximumRedeliveries(3); - policy.setBackOffMultiplier((short) 1); - policy.setRedeliveryDelay(0); - policy.setInitialRedeliveryDelay(0); - policy.setUseExponentialBackOff(false); - answer.setRedeliveryPolicy(policy); - return answer; - } - - protected void sendMessages() throws JMSException { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(getDestination()); - producer.setDeliveryMode(deliveryMode); - - LOG.info("Sending " + messageCount + " messages to: " + getDestination()); - for (int i = 0; i < messageCount; i++) { - Message message = createMessage(session, i); - producer.send(message); - } - } - - protected TextMessage createMessage(Session session, int i) throws JMSException { - return session.createTextMessage(getMessageText(i)); - } - - protected String getMessageText(int i) { - return "message: " + i; - } - - protected Destination createDlqDestination() { - return new ActiveMQQueue("ActiveMQ.DLQ"); - } - - private QueueViewMBean getProxyToDLQ() throws MalformedObjectNameException, JMSException { - ObjectName queueViewMBeanName = new ObjectName( - "org.apache.activemq:type=Broker,brokerName=localhost," + - "destinationType=Queue,destinationName=ActiveMQ.DLQ"); - QueueViewMBean proxy = (QueueViewMBean) broker.getManagementContext() - .newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); - return proxy; - } - - protected Destination getDestination() { - if (destination == null) { - destination = createDestination(); - } - return destination; - } - - protected String createClientId() { - return toString(); - } - - class RollbackMessageListener implements MessageListener { - - final int maxRollbacks; - final int deliveryCount; - final AtomicInteger rollbacks = new AtomicInteger(); - - RollbackMessageListener(int c, int delvery) { - maxRollbacks = c; - deliveryCount = delvery; - } - - @Override - public void onMessage(Message message) { - try { - int expectedMessageId = rollbacks.get() / deliveryCount; - LOG.info("expecting messageId: " + expectedMessageId); - rollbacks.incrementAndGet(); - session.rollback(); - } catch (Throwable e) { - LOG.error("unexpected exception:" + e, e); - // propagating assertError to execution task will cause a hang - // at shutdown - if (e instanceof Error) { - error[0] = (Error) e; - } else { - fail("unexpected exception: " + e); - } + assertTrue("DLQ was not emptied as expected", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return dlqView.getQueueSize() == 0; } - } - } + })); + + connection.start(); + } + } + + protected void makeConsumer() throws JMSException { + Destination destination = getDestination(); + LOG.info("Consuming from: " + destination); + if (durableSubscriber) { + consumer = session.createDurableSubscriber((Topic) destination, destination.toString()); + } + else { + consumer = session.createConsumer(destination); + } + } + + protected void makeDlqConsumer() throws JMSException { + dlqDestination = createDlqDestination(); + + LOG.info("Consuming from dead letter on: " + dlqDestination); + dlqConsumer = dlqSession.createConsumer(dlqDestination); + } + + @Override + protected void setUp() throws Exception { + broker = createBroker(); + broker.start(); + broker.waitUntilStarted(); + + connection = createConnection(); + connection.setClientID(createClientId()); + + session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + connection.start(); + + dlqSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + } + + @Override + protected void tearDown() throws Exception { + dlqConsumer.close(); + dlqSession.close(); + session.close(); + + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + } + + ; + + @Override + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory answer = super.createConnectionFactory(); + RedeliveryPolicy policy = new RedeliveryPolicy(); + policy.setMaximumRedeliveries(3); + policy.setBackOffMultiplier((short) 1); + policy.setRedeliveryDelay(0); + policy.setInitialRedeliveryDelay(0); + policy.setUseExponentialBackOff(false); + answer.setRedeliveryPolicy(policy); + return answer; + } + + protected void sendMessages() throws JMSException { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer = session.createProducer(getDestination()); + producer.setDeliveryMode(deliveryMode); + + LOG.info("Sending " + messageCount + " messages to: " + getDestination()); + for (int i = 0; i < messageCount; i++) { + Message message = createMessage(session, i); + producer.send(message); + } + } + + protected TextMessage createMessage(Session session, int i) throws JMSException { + return session.createTextMessage(getMessageText(i)); + } + + protected String getMessageText(int i) { + return "message: " + i; + } + + protected Destination createDlqDestination() { + return new ActiveMQQueue("ActiveMQ.DLQ"); + } + + private QueueViewMBean getProxyToDLQ() throws MalformedObjectNameException, JMSException { + ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost," + "destinationType=Queue,destinationName=ActiveMQ.DLQ"); + QueueViewMBean proxy = (QueueViewMBean) broker.getManagementContext().newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); + return proxy; + } + + protected Destination getDestination() { + if (destination == null) { + destination = createDestination(); + } + return destination; + } + + protected String createClientId() { + return toString(); + } + + class RollbackMessageListener implements MessageListener { + + final int maxRollbacks; + final int deliveryCount; + final AtomicInteger rollbacks = new AtomicInteger(); + + RollbackMessageListener(int c, int delvery) { + maxRollbacks = c; + deliveryCount = delvery; + } + + @Override + public void onMessage(Message message) { + try { + int expectedMessageId = rollbacks.get() / deliveryCount; + LOG.info("expecting messageId: " + expectedMessageId); + rollbacks.incrementAndGet(); + session.rollback(); + } + catch (Throwable e) { + LOG.error("unexpected exception:" + e, e); + // propagating assertError to execution task will cause a hang + // at shutdown + if (e instanceof Error) { + error[0] = (Error) e; + } + else { + fail("unexpected exception: " + e); + } + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3436Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3436Test.java index 65e0783487..05827d2c4a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3436Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3436Test.java @@ -46,157 +46,157 @@ import org.slf4j.LoggerFactory; public class AMQ3436Test { - protected static final Logger LOG = LoggerFactory.getLogger(AMQ3436Test.class); + protected static final Logger LOG = LoggerFactory.getLogger(AMQ3436Test.class); - private BrokerService broker; - private PersistenceAdapter adapter; - private boolean useCache = true; - private boolean prioritizeMessages = true; + private BrokerService broker; + private PersistenceAdapter adapter; + private boolean useCache = true; + private boolean prioritizeMessages = true; - protected PersistenceAdapter createPersistenceAdapter(boolean delete) throws Exception { - KahaDBPersistenceAdapter adapter = new KahaDBPersistenceAdapter(); - adapter.setConcurrentStoreAndDispatchQueues(false); - adapter.setConcurrentStoreAndDispatchTopics(false); - adapter.deleteAllMessages(); - return adapter; - } + protected PersistenceAdapter createPersistenceAdapter(boolean delete) throws Exception { + KahaDBPersistenceAdapter adapter = new KahaDBPersistenceAdapter(); + adapter.setConcurrentStoreAndDispatchQueues(false); + adapter.setConcurrentStoreAndDispatchTopics(false); + adapter.deleteAllMessages(); + return adapter; + } - @Before - public void setUp() throws Exception { - broker = new BrokerService(); - broker.setBrokerName("priorityTest"); - broker.setAdvisorySupport(false); - broker.setUseJmx(false); - adapter = createPersistenceAdapter(true); - broker.setPersistenceAdapter(adapter); - PolicyEntry policy = new PolicyEntry(); - policy.setPrioritizedMessages(prioritizeMessages); - policy.setUseCache(useCache); - policy.setProducerFlowControl(false); - PolicyMap policyMap = new PolicyMap(); - policyMap.put(new ActiveMQQueue("TEST"), policy); + @Before + public void setUp() throws Exception { + broker = new BrokerService(); + broker.setBrokerName("priorityTest"); + broker.setAdvisorySupport(false); + broker.setUseJmx(false); + adapter = createPersistenceAdapter(true); + broker.setPersistenceAdapter(adapter); + PolicyEntry policy = new PolicyEntry(); + policy.setPrioritizedMessages(prioritizeMessages); + policy.setUseCache(useCache); + policy.setProducerFlowControl(false); + PolicyMap policyMap = new PolicyMap(); + policyMap.put(new ActiveMQQueue("TEST"), policy); - // do not process expired for one test - PolicyEntry ignoreExpired = new PolicyEntry(); - SharedDeadLetterStrategy ignoreExpiredStrategy = new SharedDeadLetterStrategy(); - ignoreExpiredStrategy.setProcessExpired(false); - ignoreExpired.setDeadLetterStrategy(ignoreExpiredStrategy); + // do not process expired for one test + PolicyEntry ignoreExpired = new PolicyEntry(); + SharedDeadLetterStrategy ignoreExpiredStrategy = new SharedDeadLetterStrategy(); + ignoreExpiredStrategy.setProcessExpired(false); + ignoreExpired.setDeadLetterStrategy(ignoreExpiredStrategy); - broker.setDestinationPolicy(policyMap); - broker.start(); - broker.waitUntilStarted(); - } + broker.setDestinationPolicy(policyMap); + broker.start(); + broker.waitUntilStarted(); + } - protected void tearDown() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } + protected void tearDown() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + } - @Test - public void testPriorityWhenConsumerCreatedBeforeProduction() throws Exception { + @Test + public void testPriorityWhenConsumerCreatedBeforeProduction() throws Exception { - int messageCount = 200; - URI failoverUri = new URI("vm://priorityTest?jms.prefetchPolicy.all=1"); + int messageCount = 200; + URI failoverUri = new URI("vm://priorityTest?jms.prefetchPolicy.all=1"); - ActiveMQQueue dest = new ActiveMQQueue("TEST?consumer.dispatchAsync=false"); + ActiveMQQueue dest = new ActiveMQQueue("TEST?consumer.dispatchAsync=false"); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(failoverUri); - cf.setDispatchAsync(false); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(failoverUri); + cf.setDispatchAsync(false); - // Create producer - ActiveMQConnection producerConnection = (ActiveMQConnection) cf.createConnection(); - producerConnection.setMessagePrioritySupported(true); - producerConnection.start(); - final Session producerSession = producerConnection.createSession(true, Session.SESSION_TRANSACTED); - MessageProducer producer = producerSession.createProducer(dest); + // Create producer + ActiveMQConnection producerConnection = (ActiveMQConnection) cf.createConnection(); + producerConnection.setMessagePrioritySupported(true); + producerConnection.start(); + final Session producerSession = producerConnection.createSession(true, Session.SESSION_TRANSACTED); + MessageProducer producer = producerSession.createProducer(dest); - ActiveMQMessageConsumer consumer; + ActiveMQMessageConsumer consumer; - // Create consumer on separate connection - ActiveMQConnection consumerConnection = (ActiveMQConnection) cf.createConnection(); - consumerConnection.setMessagePrioritySupported(true); - consumerConnection.start(); - final ActiveMQSession consumerSession = (ActiveMQSession) consumerConnection.createSession(true, - Session.SESSION_TRANSACTED); - consumer = (ActiveMQMessageConsumer) consumerSession.createConsumer(dest); + // Create consumer on separate connection + ActiveMQConnection consumerConnection = (ActiveMQConnection) cf.createConnection(); + consumerConnection.setMessagePrioritySupported(true); + consumerConnection.start(); + final ActiveMQSession consumerSession = (ActiveMQSession) consumerConnection.createSession(true, Session.SESSION_TRANSACTED); + consumer = (ActiveMQMessageConsumer) consumerSession.createConsumer(dest); - // Produce X number of messages with a session commit after each message - Random random = new Random(); - for (int i = 0; i < messageCount; ++i) { + // Produce X number of messages with a session commit after each message + Random random = new Random(); + for (int i = 0; i < messageCount; ++i) { - Message message = producerSession.createTextMessage("Test message #" + i); - producer.send(message, DeliveryMode.PERSISTENT, random.nextInt(10), 45*1000); - producerSession.commit(); - } - producer.close(); + Message message = producerSession.createTextMessage("Test message #" + i); + producer.send(message, DeliveryMode.PERSISTENT, random.nextInt(10), 45 * 1000); + producerSession.commit(); + } + producer.close(); - // *************************************************** - // If we create the consumer here instead of above, the - // the messages will be consumed in priority order - // *************************************************** - //consumer = (ActiveMQMessageConsumer) consumerSession.createConsumer(dest); + // *************************************************** + // If we create the consumer here instead of above, the + // the messages will be consumed in priority order + // *************************************************** + //consumer = (ActiveMQMessageConsumer) consumerSession.createConsumer(dest); - // Consume all of the messages we produce using a listener. - // Don't exit until we get all the messages. - final CountDownLatch latch = new CountDownLatch(messageCount); - final StringBuffer failureMessage = new StringBuffer(); - consumer.setMessageListener(new MessageListener() { - int lowestPrioritySeen = 10; + // Consume all of the messages we produce using a listener. + // Don't exit until we get all the messages. + final CountDownLatch latch = new CountDownLatch(messageCount); + final StringBuffer failureMessage = new StringBuffer(); + consumer.setMessageListener(new MessageListener() { + int lowestPrioritySeen = 10; - boolean firstMessage = true; + boolean firstMessage = true; - public void onMessage(Message msg) { - try { + public void onMessage(Message msg) { + try { - int currentPriority = msg.getJMSPriority(); - LOG.debug(currentPriority + "<=" + lowestPrioritySeen); + int currentPriority = msg.getJMSPriority(); + LOG.debug(currentPriority + "<=" + lowestPrioritySeen); - // Ignore the first message priority since it is prefetched - // and is out of order by design - if (firstMessage == true) { - firstMessage = false; - LOG.debug("Ignoring first message since it was prefetched"); + // Ignore the first message priority since it is prefetched + // and is out of order by design + if (firstMessage == true) { + firstMessage = false; + LOG.debug("Ignoring first message since it was prefetched"); - } else { + } + else { - // Verify that we never see a priority higher than the - // lowest - // priority seen - if (lowestPrioritySeen > currentPriority) { - lowestPrioritySeen = currentPriority; - } - if (lowestPrioritySeen < currentPriority) { - failureMessage.append("Incorrect priority seen (Lowest Priority = " + lowestPrioritySeen - + " Current Priority = " + currentPriority + ")" - + System.getProperty("line.separator")); - } - } + // Verify that we never see a priority higher than the + // lowest + // priority seen + if (lowestPrioritySeen > currentPriority) { + lowestPrioritySeen = currentPriority; + } + if (lowestPrioritySeen < currentPriority) { + failureMessage.append("Incorrect priority seen (Lowest Priority = " + lowestPrioritySeen + " Current Priority = " + currentPriority + ")" + System.getProperty("line.separator")); + } + } - } catch (JMSException e) { - e.printStackTrace(); - } finally { - latch.countDown(); - LOG.debug("Messages remaining = " + latch.getCount()); - } } - }); + catch (JMSException e) { + e.printStackTrace(); + } + finally { + latch.countDown(); + LOG.debug("Messages remaining = " + latch.getCount()); + } + } + }); - latch.await(); - consumer.close(); + latch.await(); + consumer.close(); - // Cleanup producer resources - producerSession.close(); - producerConnection.stop(); - producerConnection.close(); + // Cleanup producer resources + producerSession.close(); + producerConnection.stop(); + producerConnection.close(); - // Cleanup consumer resources - consumerSession.close(); - consumerConnection.stop(); - consumerConnection.close(); + // Cleanup consumer resources + consumerSession.close(); + consumerConnection.stop(); + consumerConnection.close(); - // Report the failure if found - if (failureMessage.length() > 0) { - Assert.fail(failureMessage.toString()); - } - } + // Report the failure if found + if (failureMessage.length() > 0) { + Assert.fail(failureMessage.toString()); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3445Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3445Test.java index 73035e2221..d36faf9eb9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3445Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3445Test.java @@ -36,115 +36,113 @@ import org.junit.Test; public class AMQ3445Test { - private ConnectionFactory connectionFactory; - private BrokerService broker; - private String connectionUri; + private ConnectionFactory connectionFactory; + private BrokerService broker; + private String connectionUri; - private final String queueName = "Consumer.MyApp.VirtualTopic.FOO"; - private final String topicName = "VirtualTopic.FOO"; + private final String queueName = "Consumer.MyApp.VirtualTopic.FOO"; + private final String topicName = "VirtualTopic.FOO"; - @Before - public void startBroker() throws Exception { - createBroker(true); - } + @Before + public void startBroker() throws Exception { + createBroker(true); + } - private void createBroker(boolean deleteMessages) throws Exception { - broker = new BrokerService(); - broker.setDeleteAllMessagesOnStartup(deleteMessages); - broker.setPersistenceAdapter(new JDBCPersistenceAdapter()); - broker.setAdvisorySupport(false); - broker.addConnector("tcp://0.0.0.0:0"); - broker.start(); - broker.waitUntilStarted(); - connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); - connectionFactory = new ActiveMQConnectionFactory(connectionUri); - } + private void createBroker(boolean deleteMessages) throws Exception { + broker = new BrokerService(); + broker.setDeleteAllMessagesOnStartup(deleteMessages); + broker.setPersistenceAdapter(new JDBCPersistenceAdapter()); + broker.setAdvisorySupport(false); + broker.addConnector("tcp://0.0.0.0:0"); + broker.start(); + broker.waitUntilStarted(); + connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); + connectionFactory = new ActiveMQConnectionFactory(connectionUri); + } - private void restartBroker() throws Exception { - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } + private void restartBroker() throws Exception { + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } - createBroker(false); - } + createBroker(false); + } - @After - public void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - } + @After + public void tearDown() throws Exception { + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + } - @Test - public void testJDBCRetiansDestinationAfterRestart() throws Exception { + @Test + public void testJDBCRetiansDestinationAfterRestart() throws Exception { - broker.getAdminView().addQueue(queueName); - broker.getAdminView().addTopic(topicName); + broker.getAdminView().addQueue(queueName); + broker.getAdminView().addTopic(topicName); - assertTrue(findDestination(queueName, false)); - assertTrue(findDestination(topicName, true)); + assertTrue(findDestination(queueName, false)); + assertTrue(findDestination(topicName, true)); - QueueViewMBean queue = getProxyToQueueViewMBean(); - assertEquals(0, queue.getQueueSize()); + QueueViewMBean queue = getProxyToQueueViewMBean(); + assertEquals(0, queue.getQueueSize()); - restartBroker(); + restartBroker(); - assertTrue(findDestination(queueName, false)); - queue = getProxyToQueueViewMBean(); - assertEquals(0, queue.getQueueSize()); + assertTrue(findDestination(queueName, false)); + queue = getProxyToQueueViewMBean(); + assertEquals(0, queue.getQueueSize()); - sendMessage(); - restartBroker(); - assertTrue(findDestination(queueName, false)); + sendMessage(); + restartBroker(); + assertTrue(findDestination(queueName, false)); - queue = getProxyToQueueViewMBean(); - assertEquals(1, queue.getQueueSize()); - sendMessage(); - assertEquals(2, queue.getQueueSize()); + queue = getProxyToQueueViewMBean(); + assertEquals(1, queue.getQueueSize()); + sendMessage(); + assertEquals(2, queue.getQueueSize()); - restartBroker(); - assertTrue(findDestination(queueName, false)); - queue = getProxyToQueueViewMBean(); - assertEquals(2, queue.getQueueSize()); - } + restartBroker(); + assertTrue(findDestination(queueName, false)); + queue = getProxyToQueueViewMBean(); + assertEquals(2, queue.getQueueSize()); + } - private void sendMessage() throws Exception { - Connection connection = connectionFactory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(session.createTopic(topicName)); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - producer.send(session.createTextMessage("Testing")); - producer.close(); - connection.close(); - } + private void sendMessage() throws Exception { + Connection connection = connectionFactory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(session.createTopic(topicName)); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + producer.send(session.createTextMessage("Testing")); + producer.close(); + connection.close(); + } - private QueueViewMBean getProxyToQueueViewMBean() throws Exception { - ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq" - + ":destinationType=Queue,destinationName=" + queueName - + ",type=Broker,brokerName=localhost"); - QueueViewMBean proxy = (QueueViewMBean) broker.getManagementContext() - .newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); - return proxy; - } + private QueueViewMBean getProxyToQueueViewMBean() throws Exception { + ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq" + ":destinationType=Queue,destinationName=" + queueName + ",type=Broker,brokerName=localhost"); + QueueViewMBean proxy = (QueueViewMBean) broker.getManagementContext().newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); + return proxy; + } - private boolean findDestination(String name, boolean topic) throws Exception { + private boolean findDestination(String name, boolean topic) throws Exception { - ObjectName[] destinations; + ObjectName[] destinations; - if (topic) { - destinations = broker.getAdminView().getTopics(); - } else { - destinations = broker.getAdminView().getQueues(); - } + if (topic) { + destinations = broker.getAdminView().getTopics(); + } + else { + destinations = broker.getAdminView().getQueues(); + } - for (ObjectName destination : destinations) { - if (destination.toString().contains(name)) { - return true; - } - } + for (ObjectName destination : destinations) { + if (destination.toString().contains(name)) { + return true; + } + } - return false; - } + return false; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3454Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3454Test.java index 99c12fc459..96f0c2ca52 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3454Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3454Test.java @@ -20,7 +20,9 @@ import javax.jms.Connection; import javax.jms.Message; import javax.jms.MessageProducer; import javax.jms.Session; + import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.command.ActiveMQDestination; @@ -30,45 +32,44 @@ import org.slf4j.LoggerFactory; public class AMQ3454Test extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(AMQ3454Test.class); - private static final int MESSAGES_COUNT = 10000; + private static final Logger LOG = LoggerFactory.getLogger(AMQ3454Test.class); + private static final int MESSAGES_COUNT = 10000; - public void testSendWithLotsOfDestinations() throws Exception { - final BrokerService broker = new BrokerService(); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.setDeleteAllMessagesOnStartup(true); + public void testSendWithLotsOfDestinations() throws Exception { + final BrokerService broker = new BrokerService(); + broker.setPersistent(false); + broker.setUseJmx(false); + broker.setDeleteAllMessagesOnStartup(true); - broker.addConnector("tcp://localhost:0"); + broker.addConnector("tcp://localhost:0"); - // populate a bunch of destinations, validate the impact on a call to send - ActiveMQDestination[] destinations = new ActiveMQDestination[MESSAGES_COUNT]; - for (int idx = 0; idx < MESSAGES_COUNT; ++idx) { - destinations[idx] = new ActiveMQQueue(getDestinationName() + "-" + idx); - } - broker.setDestinations(destinations); - broker.start(); + // populate a bunch of destinations, validate the impact on a call to send + ActiveMQDestination[] destinations = new ActiveMQDestination[MESSAGES_COUNT]; + for (int idx = 0; idx < MESSAGES_COUNT; ++idx) { + destinations[idx] = new ActiveMQQueue(getDestinationName() + "-" + idx); + } + broker.setDestinations(destinations); + broker.start(); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory( - broker.getTransportConnectors().get(0).getPublishableConnectString()); - final Connection connection = factory.createConnection(); - connection.start(); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString()); + final Connection connection = factory.createConnection(); + connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(new ActiveMQQueue(getDestinationName())); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(new ActiveMQQueue(getDestinationName())); - long start = System.currentTimeMillis(); - for (int idx = 0; idx < MESSAGES_COUNT; ++idx) { - Message message = session.createTextMessage("" + idx); - producer.send(message); - } - LOG.info("Duration: " + (System.currentTimeMillis() - start) + " millis"); - producer.close(); - session.close(); + long start = System.currentTimeMillis(); + for (int idx = 0; idx < MESSAGES_COUNT; ++idx) { + Message message = session.createTextMessage("" + idx); + producer.send(message); + } + LOG.info("Duration: " + (System.currentTimeMillis() - start) + " millis"); + producer.close(); + session.close(); - } + } - protected String getDestinationName() { - return getClass().getName() + "." + getName(); - } + protected String getDestinationName() { + return getClass().getName() + "." + getName(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3465Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3465Test.java index bac3829bb0..1d3d9edade 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3465Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3465Test.java @@ -46,150 +46,150 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -public class AMQ3465Test -{ - private final String xaDestinationName = "DestinationXA"; - private final String destinationName = "Destination"; - private BrokerService broker; - private String connectionUri; - private long txGenerator = System.currentTimeMillis(); +public class AMQ3465Test { - private XAConnectionFactory xaConnectionFactory; - private ConnectionFactory connectionFactory; + private final String xaDestinationName = "DestinationXA"; + private final String destinationName = "Destination"; + private BrokerService broker; + private String connectionUri; + private long txGenerator = System.currentTimeMillis(); - @Before - public void startBroker() throws Exception { - broker = new BrokerService(); - broker.setDeleteAllMessagesOnStartup(true); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.addConnector("tcp://0.0.0.0:0"); - broker.start(); - broker.waitUntilStarted(); + private XAConnectionFactory xaConnectionFactory; + private ConnectionFactory connectionFactory; - connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); + @Before + public void startBroker() throws Exception { + broker = new BrokerService(); + broker.setDeleteAllMessagesOnStartup(true); + broker.setPersistent(false); + broker.setUseJmx(false); + broker.addConnector("tcp://0.0.0.0:0"); + broker.start(); + broker.waitUntilStarted(); - connectionFactory = new ActiveMQConnectionFactory(connectionUri); - xaConnectionFactory = new ActiveMQXAConnectionFactory(connectionUri); - } + connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); - @After - public void stopBroker() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } + connectionFactory = new ActiveMQConnectionFactory(connectionUri); + xaConnectionFactory = new ActiveMQXAConnectionFactory(connectionUri); + } + + @After + public void stopBroker() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + } @Test public void testMixedXAandNonXAorTXSessions() throws Exception { - XAConnection xaConnection = xaConnectionFactory.createXAConnection(); - xaConnection.start(); - XASession session = xaConnection.createXASession(); - XAResource resource = session.getXAResource(); - Destination dest = new ActiveMQQueue(xaDestinationName); + XAConnection xaConnection = xaConnectionFactory.createXAConnection(); + xaConnection.start(); + XASession session = xaConnection.createXASession(); + XAResource resource = session.getXAResource(); + Destination dest = new ActiveMQQueue(xaDestinationName); - // publish a message - Xid tid = createXid(); - resource.start(tid, XAResource.TMNOFLAGS); - MessageProducer producer = session.createProducer(dest); - ActiveMQTextMessage message = new ActiveMQTextMessage(); - message.setText("Some Text"); - producer.send(message); - resource.end(tid, XAResource.TMSUCCESS); - resource.commit(tid, true); - session.close(); + // publish a message + Xid tid = createXid(); + resource.start(tid, XAResource.TMNOFLAGS); + MessageProducer producer = session.createProducer(dest); + ActiveMQTextMessage message = new ActiveMQTextMessage(); + message.setText("Some Text"); + producer.send(message); + resource.end(tid, XAResource.TMSUCCESS); + resource.commit(tid, true); + session.close(); - session = xaConnection.createXASession(); - MessageConsumer consumer = session.createConsumer(dest); - tid = createXid(); - resource = session.getXAResource(); - resource.start(tid, XAResource.TMNOFLAGS); - TextMessage receivedMessage = (TextMessage) consumer.receive(1000); - assertNotNull(receivedMessage); - assertEquals("Some Text", receivedMessage.getText()); - resource.end(tid, XAResource.TMSUCCESS); + session = xaConnection.createXASession(); + MessageConsumer consumer = session.createConsumer(dest); + tid = createXid(); + resource = session.getXAResource(); + resource.start(tid, XAResource.TMNOFLAGS); + TextMessage receivedMessage = (TextMessage) consumer.receive(1000); + assertNotNull(receivedMessage); + assertEquals("Some Text", receivedMessage.getText()); + resource.end(tid, XAResource.TMSUCCESS); - // Test that a normal session doesn't operate on XASession state. - Connection connection2 = connectionFactory.createConnection(); - connection2.start(); - ActiveMQSession session2 = (ActiveMQSession) connection2.createSession(false, Session.AUTO_ACKNOWLEDGE); + // Test that a normal session doesn't operate on XASession state. + Connection connection2 = connectionFactory.createConnection(); + connection2.start(); + ActiveMQSession session2 = (ActiveMQSession) connection2.createSession(false, Session.AUTO_ACKNOWLEDGE); - if (session2.isTransacted()) { - session2.rollback(); - } + if (session2.isTransacted()) { + session2.rollback(); + } - session2.close(); + session2.close(); - resource.commit(tid, true); + resource.commit(tid, true); } @Test public void testMixedXAandNonXALocalTXSessions() throws Exception { - XAConnection xaConnection = xaConnectionFactory.createXAConnection(); - xaConnection.start(); - XASession session = xaConnection.createXASession(); - XAResource resource = session.getXAResource(); - Destination dest = new ActiveMQQueue(xaDestinationName); + XAConnection xaConnection = xaConnectionFactory.createXAConnection(); + xaConnection.start(); + XASession session = xaConnection.createXASession(); + XAResource resource = session.getXAResource(); + Destination dest = new ActiveMQQueue(xaDestinationName); - // publish a message - Xid tid = createXid(); - resource.start(tid, XAResource.TMNOFLAGS); - MessageProducer producer = session.createProducer(dest); - ActiveMQTextMessage message = new ActiveMQTextMessage(); - message.setText("Some Text"); - producer.send(message); - resource.end(tid, XAResource.TMSUCCESS); - resource.commit(tid, true); - session.close(); + // publish a message + Xid tid = createXid(); + resource.start(tid, XAResource.TMNOFLAGS); + MessageProducer producer = session.createProducer(dest); + ActiveMQTextMessage message = new ActiveMQTextMessage(); + message.setText("Some Text"); + producer.send(message); + resource.end(tid, XAResource.TMSUCCESS); + resource.commit(tid, true); + session.close(); - session = xaConnection.createXASession(); - MessageConsumer consumer = session.createConsumer(dest); - tid = createXid(); - resource = session.getXAResource(); - resource.start(tid, XAResource.TMNOFLAGS); - TextMessage receivedMessage = (TextMessage) consumer.receive(1000); - assertNotNull(receivedMessage); - assertEquals("Some Text", receivedMessage.getText()); - resource.end(tid, XAResource.TMSUCCESS); + session = xaConnection.createXASession(); + MessageConsumer consumer = session.createConsumer(dest); + tid = createXid(); + resource = session.getXAResource(); + resource.start(tid, XAResource.TMNOFLAGS); + TextMessage receivedMessage = (TextMessage) consumer.receive(1000); + assertNotNull(receivedMessage); + assertEquals("Some Text", receivedMessage.getText()); + resource.end(tid, XAResource.TMSUCCESS); - // Test that a normal session doesn't operate on XASession state. - Connection connection2 = connectionFactory.createConnection(); - connection2.start(); - ActiveMQSession session2 = (ActiveMQSession) connection2.createSession(true, Session.AUTO_ACKNOWLEDGE); - Destination destination = new ActiveMQQueue(destinationName); - ActiveMQMessageProducer producer2 = (ActiveMQMessageProducer) session2.createProducer(destination); - producer2.send(session2.createTextMessage("Local-TX")); + // Test that a normal session doesn't operate on XASession state. + Connection connection2 = connectionFactory.createConnection(); + connection2.start(); + ActiveMQSession session2 = (ActiveMQSession) connection2.createSession(true, Session.AUTO_ACKNOWLEDGE); + Destination destination = new ActiveMQQueue(destinationName); + ActiveMQMessageProducer producer2 = (ActiveMQMessageProducer) session2.createProducer(destination); + producer2.send(session2.createTextMessage("Local-TX")); - if (session2.isTransacted()) { - session2.rollback(); - } + if (session2.isTransacted()) { + session2.rollback(); + } - session2.close(); + session2.close(); - resource.commit(tid, true); + resource.commit(tid, true); } public Xid createXid() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream os = new DataOutputStream(baos); - os.writeLong(++txGenerator); - os.close(); - final byte[] bs = baos.toByteArray(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream os = new DataOutputStream(baos); + os.writeLong(++txGenerator); + os.close(); + final byte[] bs = baos.toByteArray(); - return new Xid() { - public int getFormatId() { - return 86; - } + return new Xid() { + public int getFormatId() { + return 86; + } - public byte[] getGlobalTransactionId() { - return bs; - } + public byte[] getGlobalTransactionId() { + return bs; + } - public byte[] getBranchQualifier() { - return bs; - } - }; + public byte[] getBranchQualifier() { + return bs; + } + }; } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3529Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3529Test.java index 7e8b9d0116..3d9d2d4070 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3529Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3529Test.java @@ -43,135 +43,143 @@ import org.slf4j.LoggerFactory; public class AMQ3529Test { - private static Logger LOG = LoggerFactory.getLogger(AMQ3529Test.class); + private static Logger LOG = LoggerFactory.getLogger(AMQ3529Test.class); - private ConnectionFactory connectionFactory; - private Connection connection; - private Session session; - private BrokerService broker; - private String connectionUri; - private MessageConsumer consumer; - private Context ctx = null; + private ConnectionFactory connectionFactory; + private Connection connection; + private Session session; + private BrokerService broker; + private String connectionUri; + private MessageConsumer consumer; + private Context ctx = null; - @Before - public void startBroker() throws Exception { - broker = new BrokerService(); - broker.setDeleteAllMessagesOnStartup(true); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.addConnector("tcp://0.0.0.0:0"); - broker.start(); - broker.waitUntilStarted(); + @Before + public void startBroker() throws Exception { + broker = new BrokerService(); + broker.setDeleteAllMessagesOnStartup(true); + broker.setPersistent(false); + broker.setUseJmx(false); + broker.addConnector("tcp://0.0.0.0:0"); + broker.start(); + broker.waitUntilStarted(); - connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); + connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); - connectionFactory = new ActiveMQConnectionFactory(connectionUri); - } + connectionFactory = new ActiveMQConnectionFactory(connectionUri); + } - @After - public void stopBroker() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } + @After + public void stopBroker() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + } - @Test(timeout = 60000) - public void testInterruptionAffects() throws Exception { - ThreadGroup tg = new ThreadGroup("tg"); + @Test(timeout = 60000) + public void testInterruptionAffects() throws Exception { + ThreadGroup tg = new ThreadGroup("tg"); - assertEquals(0, tg.activeCount()); + assertEquals(0, tg.activeCount()); - Thread client = new Thread(tg, "client") { + Thread client = new Thread(tg, "client") { - @Override - public void run() { - try { - connection = connectionFactory.createConnection(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - assertNotNull(session); + @Override + public void run() { + try { + connection = connectionFactory.createConnection(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + assertNotNull(session); - Properties props = new Properties(); - props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); - props.setProperty(Context.PROVIDER_URL, "tcp://0.0.0.0:0"); - ctx = null; - try { - ctx = new InitialContext(props); - } catch (NoClassDefFoundError e) { - throw new NamingException(e.toString()); - } catch (Exception e) { - throw new NamingException(e.toString()); - } - Destination destination = (Destination) ctx.lookup("dynamicTopics/example.C"); - consumer = session.createConsumer(destination); - consumer.receive(10000); - } catch (Exception e) { - // Expect an exception here from the interrupt. - } finally { - // next line is the nature of the test, if I remove this - // line, everything works OK - try { - consumer.close(); - } catch (JMSException e) { - fail("Consumer Close failed with" + e.getMessage()); - } - try { - session.close(); - } catch (JMSException e) { - fail("Session Close failed with" + e.getMessage()); - } - try { - connection.close(); - } catch (JMSException e) { - fail("Connection Close failed with" + e.getMessage()); - } - try { - ctx.close(); - } catch (Exception e) { - fail("Connection Close failed with" + e.getMessage()); - } - } + Properties props = new Properties(); + props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); + props.setProperty(Context.PROVIDER_URL, "tcp://0.0.0.0:0"); + ctx = null; + try { + ctx = new InitialContext(props); + } + catch (NoClassDefFoundError e) { + throw new NamingException(e.toString()); + } + catch (Exception e) { + throw new NamingException(e.toString()); + } + Destination destination = (Destination) ctx.lookup("dynamicTopics/example.C"); + consumer = session.createConsumer(destination); + consumer.receive(10000); } - }; - client.start(); - Thread.sleep(5000); - client.interrupt(); - client.join(); - Thread.sleep(2000); - Thread[] remainThreads = new Thread[tg.activeCount()]; - tg.enumerate(remainThreads); - for (Thread t : remainThreads) { - if (t.isAlive() && !t.isDaemon()) - fail("Remaining thread: " + t.toString()); - } + catch (Exception e) { + // Expect an exception here from the interrupt. + } + finally { + // next line is the nature of the test, if I remove this + // line, everything works OK + try { + consumer.close(); + } + catch (JMSException e) { + fail("Consumer Close failed with" + e.getMessage()); + } + try { + session.close(); + } + catch (JMSException e) { + fail("Session Close failed with" + e.getMessage()); + } + try { + connection.close(); + } + catch (JMSException e) { + fail("Connection Close failed with" + e.getMessage()); + } + try { + ctx.close(); + } + catch (Exception e) { + fail("Connection Close failed with" + e.getMessage()); + } + } + } + }; + client.start(); + Thread.sleep(5000); + client.interrupt(); + client.join(); + Thread.sleep(2000); + Thread[] remainThreads = new Thread[tg.activeCount()]; + tg.enumerate(remainThreads); + for (Thread t : remainThreads) { + if (t.isAlive() && !t.isDaemon()) + fail("Remaining thread: " + t.toString()); + } - ThreadGroup root = Thread.currentThread().getThreadGroup().getParent(); - while (root.getParent() != null) { - root = root.getParent(); - } - visit(root, 0); - } + ThreadGroup root = Thread.currentThread().getThreadGroup().getParent(); + while (root.getParent() != null) { + root = root.getParent(); + } + visit(root, 0); + } - // This method recursively visits all thread groups under `group'. - public static void visit(ThreadGroup group, int level) { - // Get threads in `group' - int numThreads = group.activeCount(); - Thread[] threads = new Thread[numThreads * 2]; - numThreads = group.enumerate(threads, false); + // This method recursively visits all thread groups under `group'. + public static void visit(ThreadGroup group, int level) { + // Get threads in `group' + int numThreads = group.activeCount(); + Thread[] threads = new Thread[numThreads * 2]; + numThreads = group.enumerate(threads, false); - // Enumerate each thread in `group' - for (int i = 0; i < numThreads; i++) { - // Get thread - Thread thread = threads[i]; - LOG.debug("Thread:" + thread.getName() + " is still running"); - } + // Enumerate each thread in `group' + for (int i = 0; i < numThreads; i++) { + // Get thread + Thread thread = threads[i]; + LOG.debug("Thread:" + thread.getName() + " is still running"); + } - // Get thread subgroups of `group' - int numGroups = group.activeGroupCount(); - ThreadGroup[] groups = new ThreadGroup[numGroups * 2]; - numGroups = group.enumerate(groups, false); + // Get thread subgroups of `group' + int numGroups = group.activeGroupCount(); + ThreadGroup[] groups = new ThreadGroup[numGroups * 2]; + numGroups = group.enumerate(groups, false); - // Recursively visit each subgroup - for (int i = 0; i < numGroups; i++) { - visit(groups[i], level + 1); - } - } + // Recursively visit each subgroup + for (int i = 0; i < numGroups; i++) { + visit(groups[i], level + 1); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3537Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3537Test.java index fe8e3fd405..614631ff40 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3537Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3537Test.java @@ -45,60 +45,61 @@ import org.junit.Test; * See AMQ-3537 * * @author jason.yankus - * */ -@SuppressWarnings({ "rawtypes", "unchecked" }) +@SuppressWarnings({"rawtypes", "unchecked"}) public class AMQ3537Test implements InvocationHandler, Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - /** - * If the first and second element in this array are swapped, the test will - * fail. - */ - public static final Class[] TEST_CLASSES = new Class[] { List.class, NonJDKList.class, Serializable.class }; + /** + * If the first and second element in this array are swapped, the test will + * fail. + */ + public static final Class[] TEST_CLASSES = new Class[]{List.class, NonJDKList.class, Serializable.class}; - /** Underlying list */ - private final List l = new ArrayList(); + /** + * Underlying list + */ + private final List l = new ArrayList(); - @Before - public void setUp() throws Exception { - l.add("foo"); - } + @Before + public void setUp() throws Exception { + l.add("foo"); + } - @Test - public void testDeserializeProxy() throws Exception { - // create the proxy - List proxy = (List) java.lang.reflect.Proxy.newProxyInstance(this.getClass().getClassLoader(), TEST_CLASSES, this); + @Test + public void testDeserializeProxy() throws Exception { + // create the proxy + List proxy = (List) java.lang.reflect.Proxy.newProxyInstance(this.getClass().getClassLoader(), TEST_CLASSES, this); - // serialize it - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(proxy); - byte[] serializedProxy = baos.toByteArray(); - oos.close(); - baos.close(); + // serialize it + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(proxy); + byte[] serializedProxy = baos.toByteArray(); + oos.close(); + baos.close(); - // deserialize the proxy - ClassLoadingAwareObjectInputStream claois = - new ClassLoadingAwareObjectInputStream(new ByteArrayInputStream(serializedProxy)); + // deserialize the proxy + ClassLoadingAwareObjectInputStream claois = new ClassLoadingAwareObjectInputStream(new ByteArrayInputStream(serializedProxy)); - // this is where it fails due to the rudimentary classloader selection - // in ClassLoadingAwareObjectInputStream - List deserializedProxy = (List) claois.readObject(); + // this is where it fails due to the rudimentary classloader selection + // in ClassLoadingAwareObjectInputStream + List deserializedProxy = (List) claois.readObject(); - claois.close(); + claois.close(); - // assert the invocation worked - assertEquals("foo", deserializedProxy.get(0)); - } + // assert the invocation worked + assertEquals("foo", deserializedProxy.get(0)); + } - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - return method.invoke(l, args); - } + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + return method.invoke(l, args); + } - public interface NonJDKList { - int size(); - } + public interface NonJDKList { + + int size(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3567Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3567Test.java index b4ce82fce1..c567eb3dc4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3567Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3567Test.java @@ -43,166 +43,170 @@ import org.slf4j.LoggerFactory; /** * @author Claudio Corsi - * */ public class AMQ3567Test { - private static Logger logger = LoggerFactory.getLogger(AMQ3567Test.class); + private static Logger logger = LoggerFactory.getLogger(AMQ3567Test.class); - private ActiveMQConnectionFactory factory; - private Connection connection; - private Session sessionWithListener, session; - private Queue destination; - private MessageConsumer consumer; - private Thread thread; - private BrokerService broker; - private String connectionUri; + private ActiveMQConnectionFactory factory; + private Connection connection; + private Session sessionWithListener, session; + private Queue destination; + private MessageConsumer consumer; + private Thread thread; + private BrokerService broker; + private String connectionUri; - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - startBroker(); - initializeConsumer(); - startConsumer(); - } + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + startBroker(); + initializeConsumer(); + startConsumer(); + } - @Test - public void runTest() throws Exception { - produceSingleMessage(); - org.apache.log4j.Logger log4jLogger = org.apache.log4j.Logger.getLogger("org.apache.activemq.util.ServiceSupport"); - final AtomicBoolean failed = new AtomicBoolean(false); + @Test + public void runTest() throws Exception { + produceSingleMessage(); + org.apache.log4j.Logger log4jLogger = org.apache.log4j.Logger.getLogger("org.apache.activemq.util.ServiceSupport"); + final AtomicBoolean failed = new AtomicBoolean(false); - Appender appender = new DefaultTestAppender() { - @Override - public void doAppend(LoggingEvent event) { - if (event.getThrowableInformation() != null) { - if (event.getThrowableInformation().getThrowable() instanceof InterruptedException) { - InterruptedException ie = (InterruptedException)event.getThrowableInformation().getThrowable(); - if (ie.getMessage().startsWith("Could not stop service:")) { - logger.info("Received an interrupted exception : ", ie); - failed.set(true); - } - } - } + Appender appender = new DefaultTestAppender() { + @Override + public void doAppend(LoggingEvent event) { + if (event.getThrowableInformation() != null) { + if (event.getThrowableInformation().getThrowable() instanceof InterruptedException) { + InterruptedException ie = (InterruptedException) event.getThrowableInformation().getThrowable(); + if (ie.getMessage().startsWith("Could not stop service:")) { + logger.info("Received an interrupted exception : ", ie); + failed.set(true); + } + } } - }; - log4jLogger.addAppender(appender); + } + }; + log4jLogger.addAppender(appender); - Level level = log4jLogger.getLevel(); - log4jLogger.setLevel(Level.DEBUG); + Level level = log4jLogger.getLevel(); + log4jLogger.setLevel(Level.DEBUG); - try { - stopConsumer(); - stopBroker(); - if (failed.get()) { - fail("An Interrupt exception was generated"); + try { + stopConsumer(); + stopBroker(); + if (failed.get()) { + fail("An Interrupt exception was generated"); + } + + } + finally { + log4jLogger.setLevel(level); + log4jLogger.removeAppender(appender); + } + } + + private void startBroker() throws Exception { + broker = new BrokerService(); + broker.setDataDirectory("target/data"); + connectionUri = broker.addConnector("tcp://localhost:0?wireFormat.maxInactivityDuration=30000&transport.closeAsync=false&transport.threadName&soTimeout=60000&transport.keepAlive=false&transport.useInactivityMonitor=false").getPublishableConnectString(); + broker.start(true); + broker.waitUntilStarted(); + } + + private void stopBroker() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + } + + private void initializeConsumer() throws JMSException { + logger.info("Initializing the consumer messagor that will just not do anything...."); + factory = new ActiveMQConnectionFactory(); + factory.setBrokerURL("failover:(" + connectionUri + "?wireFormat.maxInactivityDuration=30000&keepAlive=true&soTimeout=60000)?jms.watchTopicAdvisories=false&jms.useAsyncSend=false&jms.dispatchAsync=true&jms.producerWindowSize=10485760&jms.copyMessageOnSend=false&jms.disableTimeStampsByDefault=true&InitialReconnectDelay=1000&maxReconnectDelay=10000&maxReconnectAttempts=400&useExponentialBackOff=true"); + connection = factory.createConnection(); + connection.start(); + sessionWithListener = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + destination = sessionWithListener.createQueue("EMPTY.QUEUE"); + } + + private void startConsumer() throws Exception { + logger.info("Starting the consumer"); + consumer = sessionWithListener.createConsumer(destination); + consumer.setMessageListener(new MessageListener() { + + @Override + public void onMessage(Message message) { + logger.info("Received a message: " + message); + } + + }); + + thread = new Thread(new Runnable() { + + private Session session; + + @Override + public void run() { + try { + destination = session.createQueue("EMPTY.QUEUE"); + MessageConsumer consumer = session.createConsumer(destination); + for (int cnt = 0; cnt < 2; cnt++) { + Message message = consumer.receive(50000); + logger.info("Received message: " + message); + } } - - } finally { - log4jLogger.setLevel(level); - log4jLogger.removeAppender(appender); - } - } - - private void startBroker() throws Exception { - broker = new BrokerService(); - broker.setDataDirectory("target/data"); - connectionUri = broker.addConnector("tcp://localhost:0?wireFormat.maxInactivityDuration=30000&transport.closeAsync=false&transport.threadName&soTimeout=60000&transport.keepAlive=false&transport.useInactivityMonitor=false").getPublishableConnectString(); - broker.start(true); - broker.waitUntilStarted(); - } - - private void stopBroker() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } - - private void initializeConsumer() throws JMSException { - logger.info("Initializing the consumer messagor that will just not do anything...."); - factory = new ActiveMQConnectionFactory(); - factory.setBrokerURL("failover:("+connectionUri+"?wireFormat.maxInactivityDuration=30000&keepAlive=true&soTimeout=60000)?jms.watchTopicAdvisories=false&jms.useAsyncSend=false&jms.dispatchAsync=true&jms.producerWindowSize=10485760&jms.copyMessageOnSend=false&jms.disableTimeStampsByDefault=true&InitialReconnectDelay=1000&maxReconnectDelay=10000&maxReconnectAttempts=400&useExponentialBackOff=true"); - connection = factory.createConnection(); - connection.start(); - sessionWithListener = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - destination = sessionWithListener.createQueue("EMPTY.QUEUE"); - } - - private void startConsumer() throws Exception { - logger.info("Starting the consumer"); - consumer = sessionWithListener.createConsumer(destination); - consumer.setMessageListener(new MessageListener() { - - @Override - public void onMessage(Message message) { - logger.info("Received a message: " + message); + catch (JMSException e) { + logger.debug("Received an exception while processing messages", e); } - - }); - - thread = new Thread(new Runnable() { - - private Session session; - - @Override - public void run() { - try { - destination = session.createQueue("EMPTY.QUEUE"); - MessageConsumer consumer = session.createConsumer(destination); - for (int cnt = 0; cnt < 2; cnt++) { - Message message = consumer.receive(50000); - logger.info("Received message: " + message); - } - } catch (JMSException e) { - logger.debug("Received an exception while processing messages", e); - } finally { - try { - session.close(); - } catch (JMSException e) { - logger.debug("Received an exception while closing session", e); - } - } + finally { + try { + session.close(); + } + catch (JMSException e) { + logger.debug("Received an exception while closing session", e); + } } + } - public Runnable setSession(Session session) { - this.session = session; - return this; - } + public Runnable setSession(Session session) { + this.session = session; + return this; + } - }.setSession(session)) { - { - start(); - } - }; - } + }.setSession(session)) { + { + start(); + } + }; + } - private void stopConsumer() throws JMSException { - logger.info("Stopping the consumer"); - try { - thread.join(); - } catch (InterruptedException e) { - logger.debug("Received an exception while waiting for thread to complete", e); - } - if (sessionWithListener != null) { - sessionWithListener.close(); - } - if (connection != null) { - connection.stop(); - } - } + private void stopConsumer() throws JMSException { + logger.info("Stopping the consumer"); + try { + thread.join(); + } + catch (InterruptedException e) { + logger.debug("Received an exception while waiting for thread to complete", e); + } + if (sessionWithListener != null) { + sessionWithListener.close(); + } + if (connection != null) { + connection.stop(); + } + } - private void produceSingleMessage() throws JMSException { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(); - factory.setBrokerURL(connectionUri); - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue("EMPTY.QUEUE"); - MessageProducer producer = session.createProducer(destination); - producer.send(session.createTextMessage("Single Message")); - producer.close(); - session.close(); - connection.close(); - } + private void produceSingleMessage() throws JMSException { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(); + factory.setBrokerURL(connectionUri); + Connection connection = factory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue("EMPTY.QUEUE"); + MessageProducer producer = session.createProducer(destination); + producer.send(session.createTextMessage("Single Message")); + producer.close(); + session.close(); + connection.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3622Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3622Test.java index e08279cce8..7abe33f1ca 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3622Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3622Test.java @@ -40,70 +40,70 @@ import org.junit.Test; public class AMQ3622Test { - protected BrokerService broker; - protected AtomicBoolean failed = new AtomicBoolean(false); - protected String connectionUri; - protected Appender appender = new DefaultTestAppender() { + protected BrokerService broker; + protected AtomicBoolean failed = new AtomicBoolean(false); + protected String connectionUri; + protected Appender appender = new DefaultTestAppender() { - @Override - public void doAppend(LoggingEvent event) { - System.err.println(event.getMessage()); - if (event.getThrowableInformation() != null) { - if (event.getThrowableInformation().getThrowable() instanceof NullPointerException) { - failed.set(true); - } + @Override + public void doAppend(LoggingEvent event) { + System.err.println(event.getMessage()); + if (event.getThrowableInformation() != null) { + if (event.getThrowableInformation().getThrowable() instanceof NullPointerException) { + failed.set(true); } - } - }; + } + } + }; - @Before - public void before() throws Exception { - Logger.getRootLogger().addAppender(appender); + @Before + public void before() throws Exception { + Logger.getRootLogger().addAppender(appender); - broker = new BrokerService(); - broker.setDataDirectory("target" + File.separator + "activemq-data"); - broker.setPersistent(true); - broker.setDeleteAllMessagesOnStartup(true); - PolicyEntry policy = new PolicyEntry(); - policy.setTopic(">"); - policy.setProducerFlowControl(false); - policy.setMemoryLimit(1 * 1024 * 1024); - policy.setPendingSubscriberPolicy(new FilePendingSubscriberMessageStoragePolicy()); - policy.setSubscriptionRecoveryPolicy(new LastImageSubscriptionRecoveryPolicy()); - policy.setExpireMessagesPeriod(500); - List entries = new ArrayList(); + broker = new BrokerService(); + broker.setDataDirectory("target" + File.separator + "activemq-data"); + broker.setPersistent(true); + broker.setDeleteAllMessagesOnStartup(true); + PolicyEntry policy = new PolicyEntry(); + policy.setTopic(">"); + policy.setProducerFlowControl(false); + policy.setMemoryLimit(1 * 1024 * 1024); + policy.setPendingSubscriberPolicy(new FilePendingSubscriberMessageStoragePolicy()); + policy.setSubscriptionRecoveryPolicy(new LastImageSubscriptionRecoveryPolicy()); + policy.setExpireMessagesPeriod(500); + List entries = new ArrayList(); - entries.add(policy); - PolicyMap pMap = new PolicyMap(); - pMap.setPolicyEntries(entries); - broker.setDestinationPolicy(pMap); + entries.add(policy); + PolicyMap pMap = new PolicyMap(); + pMap.setPolicyEntries(entries); + broker.setDestinationPolicy(pMap); - connectionUri = broker.addConnector("stomp://localhost:0").getPublishableConnectString(); + connectionUri = broker.addConnector("stomp://localhost:0").getPublishableConnectString(); - broker.start(); - broker.waitUntilStarted(); - } + broker.start(); + broker.waitUntilStarted(); + } - @After - public void after() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - Logger.getRootLogger().removeAppender(appender); - } + @After + public void after() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + Logger.getRootLogger().removeAppender(appender); + } - @Test - public void go() throws Exception { - StompConnection connection = new StompConnection(); - Integer port = Integer.parseInt(connectionUri.split(":")[2]); - connection.open("localhost", port); - connection.connect("", ""); - connection.subscribe("/topic/foobar", Stomp.Headers.Subscribe.AckModeValues.CLIENT); - connection.disconnect(); - Thread.sleep(1000); + @Test + public void go() throws Exception { + StompConnection connection = new StompConnection(); + Integer port = Integer.parseInt(connectionUri.split(":")[2]); + connection.open("localhost", port); + connection.connect("", ""); + connection.subscribe("/topic/foobar", Stomp.Headers.Subscribe.AckModeValues.CLIENT); + connection.disconnect(); + Thread.sleep(1000); - if (failed.get()) { - fail("Received NullPointerException"); - } - } + if (failed.get()) { + fail("Received NullPointerException"); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3625Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3625Test.java index a386202ef0..919027dc42 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3625Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3625Test.java @@ -37,75 +37,75 @@ import static org.junit.Assert.assertTrue; */ public class AMQ3625Test { - - protected BrokerService broker1; - protected BrokerService broker2; - - protected AtomicBoolean authenticationFailed = new AtomicBoolean(false); - protected AtomicBoolean gotNPE = new AtomicBoolean(false); - protected String java_security_auth_login_config = "java.security.auth.login.config"; - protected String xbean = "xbean:"; - protected String base = "src/test/resources/org/apache/activemq/bugs/amq3625"; - protected String conf = "conf"; - protected String keys = "keys"; - protected String JaasStompSSLBroker1_xml = "JaasStompSSLBroker1.xml"; - protected String JaasStompSSLBroker2_xml = "JaasStompSSLBroker2.xml"; - - protected String oldLoginConf = null; + protected BrokerService broker1; + protected BrokerService broker2; - @Before - public void before() throws Exception { - if (System.getProperty(java_security_auth_login_config) != null) { - oldLoginConf = System.getProperty(java_security_auth_login_config); - } - System.setProperty(java_security_auth_login_config, base + "/" + conf + "/" + "login.config"); - broker1 = BrokerFactory.createBroker(xbean + base + "/" + conf + "/" + JaasStompSSLBroker1_xml); - broker2 = BrokerFactory.createBroker(xbean + base + "/" + conf + "/" + JaasStompSSLBroker2_xml); - - broker1.start(); - broker1.waitUntilStarted(); - broker2.start(); - broker2.waitUntilStarted(); - } + protected AtomicBoolean authenticationFailed = new AtomicBoolean(false); + protected AtomicBoolean gotNPE = new AtomicBoolean(false); - @After - public void after() throws Exception { - broker1.stop(); - broker2.stop(); - - if (oldLoginConf != null) { - System.setProperty(java_security_auth_login_config, oldLoginConf); - } - } - - @Test - public void go() throws Exception { - Appender appender = new DefaultTestAppender() { - @Override - public void doAppend(LoggingEvent event) { - if (event.getThrowableInformation() != null) { - Throwable t = event.getThrowableInformation().getThrowable(); - if (t instanceof SecurityException) { - authenticationFailed.set(true); - } - if (t instanceof NullPointerException) { - gotNPE.set(true); - } - } + protected String java_security_auth_login_config = "java.security.auth.login.config"; + protected String xbean = "xbean:"; + protected String base = "src/test/resources/org/apache/activemq/bugs/amq3625"; + protected String conf = "conf"; + protected String keys = "keys"; + protected String JaasStompSSLBroker1_xml = "JaasStompSSLBroker1.xml"; + protected String JaasStompSSLBroker2_xml = "JaasStompSSLBroker2.xml"; + + protected String oldLoginConf = null; + + @Before + public void before() throws Exception { + if (System.getProperty(java_security_auth_login_config) != null) { + oldLoginConf = System.getProperty(java_security_auth_login_config); + } + System.setProperty(java_security_auth_login_config, base + "/" + conf + "/" + "login.config"); + broker1 = BrokerFactory.createBroker(xbean + base + "/" + conf + "/" + JaasStompSSLBroker1_xml); + broker2 = BrokerFactory.createBroker(xbean + base + "/" + conf + "/" + JaasStompSSLBroker2_xml); + + broker1.start(); + broker1.waitUntilStarted(); + broker2.start(); + broker2.waitUntilStarted(); + } + + @After + public void after() throws Exception { + broker1.stop(); + broker2.stop(); + + if (oldLoginConf != null) { + System.setProperty(java_security_auth_login_config, oldLoginConf); + } + } + + @Test + public void go() throws Exception { + Appender appender = new DefaultTestAppender() { + @Override + public void doAppend(LoggingEvent event) { + if (event.getThrowableInformation() != null) { + Throwable t = event.getThrowableInformation().getThrowable(); + if (t instanceof SecurityException) { + authenticationFailed.set(true); + } + if (t instanceof NullPointerException) { + gotNPE.set(true); + } } - }; - Logger.getRootLogger().addAppender(appender); - - String connectURI = broker1.getConnectorByName("openwire").getConnectUri().toString(); - connectURI = connectURI.replace("?needClientAuth=true", ""); - broker2.addNetworkConnector("static:(" + connectURI + ")").start(); - - Thread.sleep(10 * 1000); - - Logger.getRootLogger().removeAppender(appender); - - assertTrue(authenticationFailed.get()); - assertFalse(gotNPE.get()); - } + } + }; + Logger.getRootLogger().addAppender(appender); + + String connectURI = broker1.getConnectorByName("openwire").getConnectUri().toString(); + connectURI = connectURI.replace("?needClientAuth=true", ""); + broker2.addNetworkConnector("static:(" + connectURI + ")").start(); + + Thread.sleep(10 * 1000); + + Logger.getRootLogger().removeAppender(appender); + + assertTrue(authenticationFailed.get()); + assertFalse(gotNPE.get()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3674Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3674Test.java index 026bf110d6..8fc15dc222 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3674Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3674Test.java @@ -39,82 +39,84 @@ import org.slf4j.LoggerFactory; public class AMQ3674Test { - private static Logger LOG = LoggerFactory.getLogger(AMQ3674Test.class); + private static Logger LOG = LoggerFactory.getLogger(AMQ3674Test.class); - private final static int deliveryMode = DeliveryMode.NON_PERSISTENT; - private final static ActiveMQTopic destination = new ActiveMQTopic("XYZ"); + private final static int deliveryMode = DeliveryMode.NON_PERSISTENT; + private final static ActiveMQTopic destination = new ActiveMQTopic("XYZ"); - private ActiveMQConnectionFactory factory; - private BrokerService broker; + private ActiveMQConnectionFactory factory; + private BrokerService broker; - @Test - public void removeSubscription() throws Exception { + @Test + public void removeSubscription() throws Exception { - final Connection producerConnection = factory.createConnection(); - producerConnection.start(); - final Connection consumerConnection = factory.createConnection(); + final Connection producerConnection = factory.createConnection(); + producerConnection.start(); + final Connection consumerConnection = factory.createConnection(); - consumerConnection.setClientID("subscriber1"); - Session consumerMQSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - TopicSubscriber activeConsumer = (TopicSubscriber) consumerMQSession.createDurableSubscriber(destination, "myTopic"); - consumerConnection.start(); + consumerConnection.setClientID("subscriber1"); + Session consumerMQSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + TopicSubscriber activeConsumer = (TopicSubscriber) consumerMQSession.createDurableSubscriber(destination, "myTopic"); + consumerConnection.start(); - Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(deliveryMode); + Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(deliveryMode); - final BrokerView brokerView = broker.getAdminView(); + final BrokerView brokerView = broker.getAdminView(); - assertEquals(1, brokerView.getDurableTopicSubscribers().length); + assertEquals(1, brokerView.getDurableTopicSubscribers().length); - LOG.info("Current Durable Topic Subscriptions: " + brokerView.getDurableTopicSubscribers().length); + LOG.info("Current Durable Topic Subscriptions: " + brokerView.getDurableTopicSubscribers().length); - try { - brokerView.destroyDurableSubscriber("subscriber1", "myTopic"); - fail("Expected Exception for Durable consumer is in use"); - } catch(Exception e) { - LOG.info("Received expected exception: " + e.getMessage()); - } + try { + brokerView.destroyDurableSubscriber("subscriber1", "myTopic"); + fail("Expected Exception for Durable consumer is in use"); + } + catch (Exception e) { + LOG.info("Received expected exception: " + e.getMessage()); + } - LOG.info("Current Durable Topic Subscriptions: " + brokerView.getDurableTopicSubscribers().length); + LOG.info("Current Durable Topic Subscriptions: " + brokerView.getDurableTopicSubscribers().length); - assertEquals(1, brokerView.getDurableTopicSubscribers().length); + assertEquals(1, brokerView.getDurableTopicSubscribers().length); - activeConsumer.close(); - consumerConnection.stop(); + activeConsumer.close(); + consumerConnection.stop(); - assertTrue("The subscription should be in the inactive state.", Wait.waitFor(new Wait.Condition() { + assertTrue("The subscription should be in the inactive state.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return brokerView.getInactiveDurableTopicSubscribers().length == 1; - } - })); + @Override + public boolean isSatisified() throws Exception { + return brokerView.getInactiveDurableTopicSubscribers().length == 1; + } + })); - try { - brokerView.destroyDurableSubscriber("subscriber1", "myTopic"); - } finally { - producer.close(); - producerConnection.close(); - } - } + try { + brokerView.destroyDurableSubscriber("subscriber1", "myTopic"); + } + finally { + producer.close(); + producerConnection.close(); + } + } - @Before - public void setUp() throws Exception { - broker = new BrokerService(); - broker.setPersistent(false); - broker.setUseJmx(true); - broker.setDeleteAllMessagesOnStartup(true); - TransportConnector connector = broker.addConnector("tcp://localhost:0"); - broker.start(); + @Before + public void setUp() throws Exception { + broker = new BrokerService(); + broker.setPersistent(false); + broker.setUseJmx(true); + broker.setDeleteAllMessagesOnStartup(true); + TransportConnector connector = broker.addConnector("tcp://localhost:0"); + broker.start(); - factory = new ActiveMQConnectionFactory(connector.getPublishableConnectString()); - factory.setAlwaysSyncSend(true); - factory.setDispatchAsync(false); - } + factory = new ActiveMQConnectionFactory(connector.getPublishableConnectString()); + factory.setAlwaysSyncSend(true); + factory.setDispatchAsync(false); + } - @After - public void tearDown() throws Exception { - broker.stop(); - } + @After + public void tearDown() throws Exception { + broker.stop(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3675Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3675Test.java index c8e4bf4759..68159238ad 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3675Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3675Test.java @@ -41,121 +41,122 @@ import org.slf4j.LoggerFactory; public class AMQ3675Test { - private static Logger LOG = LoggerFactory.getLogger(AMQ3675Test.class); + private static Logger LOG = LoggerFactory.getLogger(AMQ3675Test.class); - private final static int deliveryMode = DeliveryMode.NON_PERSISTENT; - private final static ActiveMQTopic destination = new ActiveMQTopic("XYZ"); + private final static int deliveryMode = DeliveryMode.NON_PERSISTENT; + private final static ActiveMQTopic destination = new ActiveMQTopic("XYZ"); - private ActiveMQConnectionFactory factory; - private BrokerService broker; + private ActiveMQConnectionFactory factory; + private BrokerService broker; - public TopicViewMBean getTopicView() throws Exception { - ObjectName destinationName = broker.getAdminView().getTopics()[0]; - TopicViewMBean topicView = (TopicViewMBean) broker.getManagementContext().newProxyInstance(destinationName, TopicViewMBean.class, true); - return topicView; - } + public TopicViewMBean getTopicView() throws Exception { + ObjectName destinationName = broker.getAdminView().getTopics()[0]; + TopicViewMBean topicView = (TopicViewMBean) broker.getManagementContext().newProxyInstance(destinationName, TopicViewMBean.class, true); + return topicView; + } - @Test - public void countConsumers() throws Exception { + @Test + public void countConsumers() throws Exception { - final Connection producerConnection = factory.createConnection(); - producerConnection.start(); - final Connection consumerConnection = factory.createConnection(); + final Connection producerConnection = factory.createConnection(); + producerConnection.start(); + final Connection consumerConnection = factory.createConnection(); - consumerConnection.setClientID("subscriber1"); - Session consumerMQSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - TopicSubscriber consumer = consumerMQSession.createDurableSubscriber(destination, "myTopic"); - consumerConnection.start(); + consumerConnection.setClientID("subscriber1"); + Session consumerMQSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + TopicSubscriber consumer = consumerMQSession.createDurableSubscriber(destination, "myTopic"); + consumerConnection.start(); - Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(deliveryMode); + Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(deliveryMode); - final BrokerView brokerView = broker.getAdminView(); - final TopicViewMBean topicView = getTopicView(); + final BrokerView brokerView = broker.getAdminView(); + final TopicViewMBean topicView = getTopicView(); - assertTrue("Should have one consumer on topic: ", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return topicView.getConsumerCount() == 1; - } - })); + assertTrue("Should have one consumer on topic: ", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return topicView.getConsumerCount() == 1; + } + })); - consumer.close(); + consumer.close(); - assertTrue("Durable consumer should now be inactive.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return brokerView.getInactiveDurableTopicSubscribers().length == 1; - } - })); + assertTrue("Durable consumer should now be inactive.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return brokerView.getInactiveDurableTopicSubscribers().length == 1; + } + })); - try { - brokerView.removeTopic(destination.getTopicName()); - } catch (Exception e1) { - fail("Unable to remove destination:" + destination.getPhysicalName()); - } + try { + brokerView.removeTopic(destination.getTopicName()); + } + catch (Exception e1) { + fail("Unable to remove destination:" + destination.getPhysicalName()); + } - assertTrue("Should have no topics on the broker", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return brokerView.getTopics().length == 0; - } - })); + assertTrue("Should have no topics on the broker", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return brokerView.getTopics().length == 0; + } + })); - try { - brokerView.destroyDurableSubscriber("subscriber1", "myTopic"); - } catch(Exception e) { - fail("Exception not expected when attempting to delete Durable consumer."); - } + try { + brokerView.destroyDurableSubscriber("subscriber1", "myTopic"); + } + catch (Exception e) { + fail("Exception not expected when attempting to delete Durable consumer."); + } - assertTrue("Should be no durable consumers active or inactive.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return brokerView.getInactiveDurableTopicSubscribers().length == 0 && - brokerView.getDurableTopicSubscribers().length == 0; - } - })); + assertTrue("Should be no durable consumers active or inactive.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return brokerView.getInactiveDurableTopicSubscribers().length == 0 && brokerView.getDurableTopicSubscribers().length == 0; + } + })); - consumer = consumerMQSession.createDurableSubscriber(destination, "myTopic"); + consumer = consumerMQSession.createDurableSubscriber(destination, "myTopic"); - consumer.close(); + consumer.close(); - assertTrue("Should be one consumer on the Topic.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("Number of inactive consumers: " + brokerView.getInactiveDurableTopicSubscribers().length); - return brokerView.getInactiveDurableTopicSubscribers().length == 1; - } - })); + assertTrue("Should be one consumer on the Topic.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("Number of inactive consumers: " + brokerView.getInactiveDurableTopicSubscribers().length); + return brokerView.getInactiveDurableTopicSubscribers().length == 1; + } + })); - final TopicViewMBean recreatedTopicView = getTopicView(); + final TopicViewMBean recreatedTopicView = getTopicView(); - assertTrue("Should have one consumer on topic: ", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return recreatedTopicView.getConsumerCount() == 1; - } - })); - } + assertTrue("Should have one consumer on topic: ", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return recreatedTopicView.getConsumerCount() == 1; + } + })); + } - @Before - public void setUp() throws Exception { - broker = new BrokerService(); - broker.setPersistent(false); - broker.setUseJmx(true); - broker.setAdvisorySupport(false); - broker.setDeleteAllMessagesOnStartup(true); - TransportConnector connector = broker.addConnector("tcp://localhost:0"); - broker.start(); + @Before + public void setUp() throws Exception { + broker = new BrokerService(); + broker.setPersistent(false); + broker.setUseJmx(true); + broker.setAdvisorySupport(false); + broker.setDeleteAllMessagesOnStartup(true); + TransportConnector connector = broker.addConnector("tcp://localhost:0"); + broker.start(); - factory = new ActiveMQConnectionFactory(connector.getPublishableConnectString()); - factory.setAlwaysSyncSend(true); - factory.setDispatchAsync(false); - } + factory = new ActiveMQConnectionFactory(connector.getPublishableConnectString()); + factory.setAlwaysSyncSend(true); + factory.setDispatchAsync(false); + } - @After - public void tearDown() throws Exception { - broker.stop(); - } + @After + public void tearDown() throws Exception { + broker.stop(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3678Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3678Test.java index 3c79fcff79..92ae7d6c13 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3678Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3678Test.java @@ -31,6 +31,7 @@ import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.MessageProducer; import javax.jms.Session; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQTopicSubscriber; import org.apache.activemq.broker.BrokerService; @@ -39,182 +40,176 @@ import org.apache.activemq.command.ActiveMQTopic; import org.junit.After; import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.fail; +import static org.junit.Assert.fail; public class AMQ3678Test implements MessageListener { - public int deliveryMode = DeliveryMode.NON_PERSISTENT; + public int deliveryMode = DeliveryMode.NON_PERSISTENT; + private BrokerService broker; - private BrokerService broker; + AtomicInteger messagesSent = new AtomicInteger(0); + AtomicInteger messagesReceived = new AtomicInteger(0); - AtomicInteger messagesSent = new AtomicInteger(0); - AtomicInteger messagesReceived = new AtomicInteger(0); + ActiveMQTopic destination = new ActiveMQTopic("XYZ"); - ActiveMQTopic destination = new ActiveMQTopic("XYZ"); + int port; + int jmxport; - int port; - int jmxport; + final CountDownLatch latch = new CountDownLatch(2); + public static void main(String[] args) throws Exception { - final CountDownLatch latch = new CountDownLatch(2); + } + public static int findFreePort() throws IOException { + ServerSocket socket = null; - public static void main(String[] args) throws Exception { + try { + // 0 is open a socket on any free port + socket = new ServerSocket(0); + return socket.getLocalPort(); + } + finally { + if (socket != null) { + socket.close(); + } + } + } - } + @Test + public void countConsumers() throws JMSException { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:" + port); + factory.setAlwaysSyncSend(true); + factory.setDispatchAsync(false); + final Connection producerConnection = factory.createConnection(); + producerConnection.start(); - public static int findFreePort() throws IOException { - ServerSocket socket = null; + final Connection consumerConnection = factory.createConnection(); - try { - // 0 is open a socket on any free port - socket = new ServerSocket(0); - return socket.getLocalPort(); - } finally { - if (socket != null) { - socket.close(); + consumerConnection.setClientID("subscriber1"); + Session consumerMQSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + + ActiveMQTopicSubscriber activeConsumer = (ActiveMQTopicSubscriber) consumerMQSession.createDurableSubscriber(destination, "myTopic?consumer.prefetchSize=1"); + + activeConsumer.setMessageListener(this); + + consumerConnection.start(); + + final Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final MessageProducer producer = producerSession.createProducer(destination); + producer.setDeliveryMode(deliveryMode); + + Thread t = new Thread(new Runnable() { + + private boolean done = false; + + public void run() { + while (!done) { + if (messagesSent.get() == 50) { + try { + broker.getAdminView().removeTopic(destination.getTopicName()); + } + catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + System.err.flush(); + fail("Unable to remove destination:" + destination.getPhysicalName()); + } + } + + try { + producer.send(producerSession.createTextMessage()); + int val = messagesSent.incrementAndGet(); + + System.out.println("sent message (" + val + ")"); + System.out.flush(); + + if (val == 100) { + done = true; + latch.countDown(); + producer.close(); + producerSession.close(); + + } + } + catch (JMSException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } } - } - } + } + }); + t.start(); - @Test - public void countConsumers() throws JMSException { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:" + port); - factory.setAlwaysSyncSend(true); - factory.setDispatchAsync(false); + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + fail("did not receive all the messages"); + } + } + catch (InterruptedException e) { + // TODO Auto-generated catch block + fail("did not receive all the messages, exception waiting for latch"); + e.printStackTrace(); + } - final Connection producerConnection = factory.createConnection(); - producerConnection.start(); + // - final Connection consumerConnection = factory.createConnection(); + } - consumerConnection.setClientID("subscriber1"); - Session consumerMQSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + @Before + public void setUp() throws Exception { - ActiveMQTopicSubscriber activeConsumer = (ActiveMQTopicSubscriber) consumerMQSession.createDurableSubscriber(destination, "myTopic?consumer.prefetchSize=1"); + try { + port = findFreePort(); + jmxport = findFreePort(); + } + catch (Exception e) { + fail("Unable to obtain a free port on which to start the broker"); + } - activeConsumer.setMessageListener(this); + System.out.println("Starting broker"); + System.out.flush(); + broker = new BrokerService(); + broker.setPersistent(false); + ManagementContext ctx = new ManagementContext(ManagementFactory.getPlatformMBeanServer()); + ctx.setConnectorPort(jmxport); + broker.setManagementContext(ctx); + broker.setUseJmx(true); + // broker.setAdvisorySupport(false); + // broker.setDeleteAllMessagesOnStartup(true); - consumerConnection.start(); + broker.addConnector("tcp://localhost:" + port).setName("Default"); + broker.start(); + System.out.println("End of Broker Setup"); + System.out.flush(); + } - final Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageProducer producer = producerSession.createProducer(destination); - producer.setDeliveryMode(deliveryMode); + @After + public void tearDown() throws Exception { + broker.stop(); + } - Thread t = new Thread(new Runnable() { - - private boolean done = false; - - public void run() { - while (!done) { - if (messagesSent.get() == 50) { - try { - broker.getAdminView().removeTopic(destination.getTopicName()); - } catch (Exception e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - System.err.flush(); - fail("Unable to remove destination:" - + destination.getPhysicalName()); - } - } - - try { - producer.send(producerSession.createTextMessage()); - int val = messagesSent.incrementAndGet(); - - System.out.println("sent message (" + val + ")"); - System.out.flush(); - - if (val == 100) { - done = true; - latch.countDown(); - producer.close(); - producerSession.close(); - - } - } catch (JMSException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - }); - - t.start(); - - try { - if (!latch.await(10, TimeUnit.SECONDS)) { - fail("did not receive all the messages"); - } - } catch (InterruptedException e) { - // TODO Auto-generated catch block - fail("did not receive all the messages, exception waiting for latch"); - e.printStackTrace(); - } - - -// - - - } - - @Before - public void setUp() throws Exception { - - try { - port = findFreePort(); - jmxport = findFreePort(); - } catch (Exception e) { - fail("Unable to obtain a free port on which to start the broker"); - } - - System.out.println("Starting broker"); - System.out.flush(); - broker = new BrokerService(); - broker.setPersistent(false); - ManagementContext ctx = new ManagementContext(ManagementFactory.getPlatformMBeanServer()); - ctx.setConnectorPort(jmxport); - broker.setManagementContext(ctx); - broker.setUseJmx(true); -// broker.setAdvisorySupport(false); -// broker.setDeleteAllMessagesOnStartup(true); - - broker.addConnector("tcp://localhost:" + port).setName("Default"); - broker.start(); - - - System.out.println("End of Broker Setup"); - System.out.flush(); - } - - @After - public void tearDown() throws Exception { - broker.stop(); - } - - - @Override - public void onMessage(Message message) { - try { - message.acknowledge(); - int val = messagesReceived.incrementAndGet(); - System.out.println("received message (" + val + ")"); - System.out.flush(); - if (messagesReceived.get() == 100) { - latch.countDown(); - } - } catch (JMSException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } + @Override + public void onMessage(Message message) { + try { + message.acknowledge(); + int val = messagesReceived.incrementAndGet(); + System.out.println("received message (" + val + ")"); + System.out.flush(); + if (messagesReceived.get() == 100) { + latch.countDown(); + } + } + catch (JMSException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3732Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3732Test.java index 601901be83..e7028045b3 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3732Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3732Test.java @@ -41,134 +41,138 @@ import org.slf4j.LoggerFactory; public class AMQ3732Test { - private static Logger LOG = LoggerFactory.getLogger(AMQ3732Test.class); + private static Logger LOG = LoggerFactory.getLogger(AMQ3732Test.class); - private ActiveMQConnectionFactory connectionFactory; - private Connection connection; - private Session session; - private BrokerService broker; - private String connectionUri; + private ActiveMQConnectionFactory connectionFactory; + private Connection connection; + private Session session; + private BrokerService broker; + private String connectionUri; - private final Random pause = new Random(); - private final long NUM_MESSAGES = 25000; - private final AtomicLong totalConsumed = new AtomicLong(); + private final Random pause = new Random(); + private final long NUM_MESSAGES = 25000; + private final AtomicLong totalConsumed = new AtomicLong(); - @Before - public void startBroker() throws Exception { - broker = new BrokerService(); - broker.setDeleteAllMessagesOnStartup(true); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.addConnector("tcp://0.0.0.0:0"); - broker.start(); - broker.waitUntilStarted(); + @Before + public void startBroker() throws Exception { + broker = new BrokerService(); + broker.setDeleteAllMessagesOnStartup(true); + broker.setPersistent(false); + broker.setUseJmx(false); + broker.addConnector("tcp://0.0.0.0:0"); + broker.start(); + broker.waitUntilStarted(); - connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); + connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); - connectionFactory = new ActiveMQConnectionFactory(connectionUri); - connectionFactory.getPrefetchPolicy().setAll(0); - } + connectionFactory = new ActiveMQConnectionFactory(connectionUri); + connectionFactory.getPrefetchPolicy().setAll(0); + } - @After - public void stopBroker() throws Exception { - connection.close(); + @After + public void stopBroker() throws Exception { + connection.close(); - broker.stop(); - broker.waitUntilStopped(); - } + broker.stop(); + broker.waitUntilStopped(); + } - @Test(timeout = 1200000) - public void testInterruptionAffects() throws Exception { + @Test(timeout = 1200000) + public void testInterruptionAffects() throws Exception { - connection = connectionFactory.createConnection(); - connection.start(); - session = connection.createSession(false, ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE); + connection = connectionFactory.createConnection(); + connection.start(); + session = connection.createSession(false, ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE); - Queue queue = session.createQueue("AMQ3732Test"); + Queue queue = session.createQueue("AMQ3732Test"); - final LinkedBlockingQueue workQueue = new LinkedBlockingQueue(); + final LinkedBlockingQueue workQueue = new LinkedBlockingQueue(); - final MessageConsumer consumer1 = session.createConsumer(queue); - final MessageConsumer consumer2 = session.createConsumer(queue); - final MessageProducer producer = session.createProducer(queue); + final MessageConsumer consumer1 = session.createConsumer(queue); + final MessageConsumer consumer2 = session.createConsumer(queue); + final MessageProducer producer = session.createProducer(queue); - Thread consumer1Thread = new Thread(new Runnable() { + Thread consumer1Thread = new Thread(new Runnable() { - @Override - public void run() { - try { - while (totalConsumed.get() < NUM_MESSAGES) { - Message message = consumer1.receiveNoWait(); - if (message != null) { - workQueue.add(message); - } - } - } catch(Exception e) { - LOG.error("Caught an unexpected error: ", e); - } + @Override + public void run() { + try { + while (totalConsumed.get() < NUM_MESSAGES) { + Message message = consumer1.receiveNoWait(); + if (message != null) { + workQueue.add(message); + } + } } - }); - consumer1Thread.start(); - - Thread consumer2Thread = new Thread(new Runnable() { - - @Override - public void run() { - try { - while (totalConsumed.get() < NUM_MESSAGES) { - Message message = consumer2.receive(50); - if (message != null) { - workQueue.add(message); - } - } - } catch(Exception e) { - LOG.error("Caught an unexpected error: ", e); - } + catch (Exception e) { + LOG.error("Caught an unexpected error: ", e); } - }); - consumer2Thread.start(); + } + }); + consumer1Thread.start(); - Thread producerThread = new Thread(new Runnable() { + Thread consumer2Thread = new Thread(new Runnable() { - @Override - public void run() { - try { - for (int i = 0; i < NUM_MESSAGES; ++i) { - producer.send(session.createTextMessage("TEST")); - TimeUnit.MILLISECONDS.sleep(pause.nextInt(10)); - } - } catch(Exception e) { - LOG.error("Caught an unexpected error: ", e); - } + @Override + public void run() { + try { + while (totalConsumed.get() < NUM_MESSAGES) { + Message message = consumer2.receive(50); + if (message != null) { + workQueue.add(message); + } + } } - }); - producerThread.start(); - - Thread ackingThread = new Thread(new Runnable() { - - @Override - public void run() { - try { - while (totalConsumed.get() < NUM_MESSAGES) { - Message message = workQueue.take(); - message.acknowledge(); - totalConsumed.incrementAndGet(); - if ((totalConsumed.get() % 100) == 0) { - LOG.info("Consumed " + totalConsumed.get() + " messages so far."); - } - } - } catch(Exception e) { - LOG.error("Caught an unexpected error: ", e); - } + catch (Exception e) { + LOG.error("Caught an unexpected error: ", e); } - }); - ackingThread.start(); + } + }); + consumer2Thread.start(); - producerThread.join(); - consumer1Thread.join(); - consumer2Thread.join(); - ackingThread.join(); + Thread producerThread = new Thread(new Runnable() { - assertEquals(NUM_MESSAGES, totalConsumed.get()); - } + @Override + public void run() { + try { + for (int i = 0; i < NUM_MESSAGES; ++i) { + producer.send(session.createTextMessage("TEST")); + TimeUnit.MILLISECONDS.sleep(pause.nextInt(10)); + } + } + catch (Exception e) { + LOG.error("Caught an unexpected error: ", e); + } + } + }); + producerThread.start(); + + Thread ackingThread = new Thread(new Runnable() { + + @Override + public void run() { + try { + while (totalConsumed.get() < NUM_MESSAGES) { + Message message = workQueue.take(); + message.acknowledge(); + totalConsumed.incrementAndGet(); + if ((totalConsumed.get() % 100) == 0) { + LOG.info("Consumed " + totalConsumed.get() + " messages so far."); + } + } + } + catch (Exception e) { + LOG.error("Caught an unexpected error: ", e); + } + } + }); + ackingThread.start(); + + producerThread.join(); + consumer1Thread.join(); + consumer2Thread.join(); + ackingThread.join(); + + assertEquals(NUM_MESSAGES, totalConsumed.get()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3779Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3779Test.java index c7a486f60f..fa354c9b97 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3779Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3779Test.java @@ -22,6 +22,7 @@ import javax.jms.Connection; import javax.jms.DeliveryMode; import javax.jms.MessageProducer; import javax.jms.Session; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.AutoFailTestSupport; import org.apache.activemq.broker.BrokerService; @@ -33,44 +34,44 @@ import org.apache.log4j.spi.LoggingEvent; public class AMQ3779Test extends AutoFailTestSupport { - private static final Logger logger = Logger.getLogger(AMQ3779Test.class); - private static final String qName = "QNameToFind"; + private static final Logger logger = Logger.getLogger(AMQ3779Test.class); + private static final String qName = "QNameToFind"; - public void testLogPerDest() throws Exception { + public void testLogPerDest() throws Exception { - final AtomicBoolean ok = new AtomicBoolean(false); - Appender appender = new DefaultTestAppender() { - @Override - public void doAppend(LoggingEvent event) { - if (event.getLoggerName().toString().contains(qName)) { - ok.set(true); - } + final AtomicBoolean ok = new AtomicBoolean(false); + Appender appender = new DefaultTestAppender() { + @Override + public void doAppend(LoggingEvent event) { + if (event.getLoggerName().toString().contains(qName)) { + ok.set(true); } - }; - Logger.getRootLogger().addAppender(appender); + } + }; + Logger.getRootLogger().addAppender(appender); - try { + try { - BrokerService broker = new BrokerService(); - LoggingBrokerPlugin loggingBrokerPlugin = new LoggingBrokerPlugin(); - loggingBrokerPlugin.setPerDestinationLogger(true); - loggingBrokerPlugin.setLogAll(true); - broker.setPlugins(new LoggingBrokerPlugin[]{loggingBrokerPlugin}); - broker.start(); + BrokerService broker = new BrokerService(); + LoggingBrokerPlugin loggingBrokerPlugin = new LoggingBrokerPlugin(); + loggingBrokerPlugin.setPerDestinationLogger(true); + loggingBrokerPlugin.setLogAll(true); + broker.setPlugins(new LoggingBrokerPlugin[]{loggingBrokerPlugin}); + broker.start(); + Connection connection = new ActiveMQConnectionFactory(broker.getVmConnectorURI()).createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer messageProducer = session.createProducer(session.createQueue(qName)); + messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT); + connection.start(); - Connection connection = new ActiveMQConnectionFactory(broker.getVmConnectorURI()).createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer messageProducer = session.createProducer(session.createQueue(qName)); - messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT); - connection.start(); + messageProducer.send(session.createTextMessage("Hi")); + connection.close(); - messageProducer.send(session.createTextMessage("Hi")); - connection.close(); - - assertTrue("got expected log message", ok.get()); - } finally { - logger.removeAppender(appender); - } - } + assertTrue("got expected log message", ok.get()); + } + finally { + logger.removeAppender(appender); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3841Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3841Test.java index 449d5e5539..ca198699fb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3841Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3841Test.java @@ -37,84 +37,83 @@ import org.slf4j.LoggerFactory; public class AMQ3841Test { - static final Logger LOG = LoggerFactory.getLogger(AMQ3841Test.class); - private final static int maxFileLength = 1024*1024*32; - private final static String destinationName = "TEST.QUEUE"; - BrokerService broker; + static final Logger LOG = LoggerFactory.getLogger(AMQ3841Test.class); + private final static int maxFileLength = 1024 * 1024 * 32; + private final static String destinationName = "TEST.QUEUE"; + BrokerService broker; - @Before - public void setUp() throws Exception { - prepareBrokerWithMultiStore(true); - broker.start(); - broker.waitUntilStarted(); - } + @Before + public void setUp() throws Exception { + prepareBrokerWithMultiStore(true); + broker.start(); + broker.waitUntilStarted(); + } - @After - public void tearDown() throws Exception { - broker.stop(); - } + @After + public void tearDown() throws Exception { + broker.stop(); + } - protected BrokerService createBroker(PersistenceAdapter kaha) throws Exception { - BrokerService broker = new BrokerService(); - broker.setUseJmx(true); - broker.setBrokerName("localhost"); - broker.setPersistenceAdapter(kaha); - return broker; - } + protected BrokerService createBroker(PersistenceAdapter kaha) throws Exception { + BrokerService broker = new BrokerService(); + broker.setUseJmx(true); + broker.setBrokerName("localhost"); + broker.setPersistenceAdapter(kaha); + return broker; + } - @Test - public void testRestartAfterQueueDelete() throws Exception { + @Test + public void testRestartAfterQueueDelete() throws Exception { - // Ensure we have an Admin View. - assertTrue("Broker doesn't have an Admin View.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return (broker.getAdminView()) != null; - } - })); + // Ensure we have an Admin View. + assertTrue("Broker doesn't have an Admin View.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return (broker.getAdminView()) != null; + } + })); + broker.getAdminView().addQueue(destinationName); - broker.getAdminView().addQueue(destinationName); + assertNotNull(broker.getDestination(new ActiveMQQueue(destinationName))); - assertNotNull(broker.getDestination(new ActiveMQQueue(destinationName))); + broker.getAdminView().removeQueue(destinationName); - broker.getAdminView().removeQueue(destinationName); + broker.stop(); + broker.waitUntilStopped(); - broker.stop(); - broker.waitUntilStopped(); + prepareBrokerWithMultiStore(false); + broker.start(); - prepareBrokerWithMultiStore(false); - broker.start(); + broker.getAdminView().addQueue(destinationName); + assertNotNull(broker.getDestination(new ActiveMQQueue(destinationName))); - broker.getAdminView().addQueue(destinationName); - assertNotNull(broker.getDestination(new ActiveMQQueue(destinationName))); + } - } + protected KahaDBPersistenceAdapter createStore(boolean delete) throws IOException { + KahaDBPersistenceAdapter kaha = new KahaDBPersistenceAdapter(); + kaha.setJournalMaxFileLength(maxFileLength); + kaha.setCleanupInterval(5000); + if (delete) { + kaha.deleteAllMessages(); + } + return kaha; + } - protected KahaDBPersistenceAdapter createStore(boolean delete) throws IOException { - KahaDBPersistenceAdapter kaha = new KahaDBPersistenceAdapter(); - kaha.setJournalMaxFileLength(maxFileLength); - kaha.setCleanupInterval(5000); - if (delete) { - kaha.deleteAllMessages(); - } - return kaha; - } + public void prepareBrokerWithMultiStore(boolean deleteAllMessages) throws Exception { - public void prepareBrokerWithMultiStore(boolean deleteAllMessages) throws Exception { + MultiKahaDBPersistenceAdapter multiKahaDBPersistenceAdapter = new MultiKahaDBPersistenceAdapter(); + if (deleteAllMessages) { + multiKahaDBPersistenceAdapter.deleteAllMessages(); + } + ArrayList adapters = new ArrayList(); - MultiKahaDBPersistenceAdapter multiKahaDBPersistenceAdapter = new MultiKahaDBPersistenceAdapter(); - if (deleteAllMessages) { - multiKahaDBPersistenceAdapter.deleteAllMessages(); - } - ArrayList adapters = new ArrayList(); + FilteredKahaDBPersistenceAdapter template = new FilteredKahaDBPersistenceAdapter(); + template.setPersistenceAdapter(createStore(deleteAllMessages)); + template.setPerDestination(true); + adapters.add(template); - FilteredKahaDBPersistenceAdapter template = new FilteredKahaDBPersistenceAdapter(); - template.setPersistenceAdapter(createStore(deleteAllMessages)); - template.setPerDestination(true); - adapters.add(template); - - multiKahaDBPersistenceAdapter.setFilteredPersistenceAdapters(adapters); - broker = createBroker(multiKahaDBPersistenceAdapter); - } + multiKahaDBPersistenceAdapter.setFilteredPersistenceAdapters(adapters); + broker = createBroker(multiKahaDBPersistenceAdapter); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3879Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3879Test.java index f2bdc480d3..071897cbf0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3879Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3879Test.java @@ -36,77 +36,78 @@ import org.slf4j.LoggerFactory; public class AMQ3879Test { - static final Logger LOG = LoggerFactory.getLogger(AMQ3841Test.class); - private BrokerService broker; + static final Logger LOG = LoggerFactory.getLogger(AMQ3841Test.class); + private BrokerService broker; - private ActiveMQConnectionFactory factory; + private ActiveMQConnectionFactory factory; - @Before - public void setUp() throws Exception { - broker = createBroker(); - broker.start(); - broker.waitUntilStarted(); + @Before + public void setUp() throws Exception { + broker = createBroker(); + broker.start(); + broker.waitUntilStarted(); - factory = new ActiveMQConnectionFactory("vm://localhost"); - factory.setAlwaysSyncSend(true); - } + factory = new ActiveMQConnectionFactory("vm://localhost"); + factory.setAlwaysSyncSend(true); + } - @After - public void tearDown() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - broker = null; - } + @After + public void tearDown() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + broker = null; + } - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setDeleteAllMessagesOnStartup(true); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.setBrokerName("localhost"); - broker.addConnector("vm://localhost"); - return broker; - } + protected BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setDeleteAllMessagesOnStartup(true); + broker.setPersistent(false); + broker.setUseJmx(false); + broker.setBrokerName("localhost"); + broker.addConnector("vm://localhost"); + return broker; + } - @Test - public void testConnectionDletesWrongTempDests() throws Exception { + @Test + public void testConnectionDletesWrongTempDests() throws Exception { - final Connection connection1 = factory.createConnection(); - final Connection connection2 = factory.createConnection(); + final Connection connection1 = factory.createConnection(); + final Connection connection2 = factory.createConnection(); - Session session1 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE); - Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE); + Session session1 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE); + Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination tempDestAdvisory = AdvisorySupport.TEMP_QUEUE_ADVISORY_TOPIC; + Destination tempDestAdvisory = AdvisorySupport.TEMP_QUEUE_ADVISORY_TOPIC; - MessageConsumer advisoryConsumer = session1.createConsumer(tempDestAdvisory); - connection1.start(); + MessageConsumer advisoryConsumer = session1.createConsumer(tempDestAdvisory); + connection1.start(); - Destination tempQueue = session2.createTemporaryQueue(); - MessageProducer tempProducer = session2.createProducer(tempQueue); + Destination tempQueue = session2.createTemporaryQueue(); + MessageProducer tempProducer = session2.createProducer(tempQueue); - assertNotNull(advisoryConsumer.receive(5000)); + assertNotNull(advisoryConsumer.receive(5000)); - Thread t = new Thread(new Runnable() { + Thread t = new Thread(new Runnable() { - @Override - public void run() { - try { - Thread.sleep(20); - connection1.close(); - } catch (Exception e) { - } + @Override + public void run() { + try { + Thread.sleep(20); + connection1.close(); } - }); + catch (Exception e) { + } + } + }); - t.start(); + t.start(); - for (int i = 0; i < 256; ++i) { - Message msg = session2.createTextMessage("Temp Data"); - tempProducer.send(msg); - Thread.sleep(2); - } + for (int i = 0; i < 256; ++i) { + Message msg = session2.createTextMessage("Temp Data"); + tempProducer.send(msg); + Thread.sleep(2); + } - t.join(); - } + t.join(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3903Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3903Test.java index c633103176..c7b4bdb9d8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3903Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3903Test.java @@ -43,99 +43,102 @@ import org.slf4j.LoggerFactory; public class AMQ3903Test { - private static final transient Logger LOG = LoggerFactory.getLogger(AMQ3903Test.class); + private static final transient Logger LOG = LoggerFactory.getLogger(AMQ3903Test.class); - private static final String bindAddress = "tcp://0.0.0.0:0"; - private BrokerService broker; - private ActiveMQConnectionFactory cf; + private static final String bindAddress = "tcp://0.0.0.0:0"; + private BrokerService broker; + private ActiveMQConnectionFactory cf; - private static final int MESSAGE_COUNT = 100; + private static final int MESSAGE_COUNT = 100; - @Before - public void setUp() throws Exception { - broker = this.createBroker(); - String address = broker.getTransportConnectors().get(0).getPublishableConnectString(); - broker.start(); - broker.waitUntilStarted(); + @Before + public void setUp() throws Exception { + broker = this.createBroker(); + String address = broker.getTransportConnectors().get(0).getPublishableConnectString(); + broker.start(); + broker.waitUntilStarted(); - cf = new ActiveMQConnectionFactory(address); - } + cf = new ActiveMQConnectionFactory(address); + } - @After - public void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - } + @After + public void tearDown() throws Exception { + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + } - @Test - public void testAdvisoryForFastGenericProducer() throws Exception { - doTestAdvisoryForFastProducer(true); - } + @Test + public void testAdvisoryForFastGenericProducer() throws Exception { + doTestAdvisoryForFastProducer(true); + } - @Test - public void testAdvisoryForFastDedicatedProducer() throws Exception { - doTestAdvisoryForFastProducer(false); - } + @Test + public void testAdvisoryForFastDedicatedProducer() throws Exception { + doTestAdvisoryForFastProducer(false); + } - public void doTestAdvisoryForFastProducer(boolean genericProducer) throws Exception { + public void doTestAdvisoryForFastProducer(boolean genericProducer) throws Exception { - Connection connection = cf.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Connection connection = cf.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final TemporaryQueue queue = session.createTemporaryQueue(); + final TemporaryQueue queue = session.createTemporaryQueue(); - final Topic advisoryTopic = AdvisorySupport.getFastProducerAdvisoryTopic((ActiveMQDestination) queue); - final Topic advisoryWhenFullTopic = AdvisorySupport.getFullAdvisoryTopic((ActiveMQDestination) queue); + final Topic advisoryTopic = AdvisorySupport.getFastProducerAdvisoryTopic((ActiveMQDestination) queue); + final Topic advisoryWhenFullTopic = AdvisorySupport.getFullAdvisoryTopic((ActiveMQDestination) queue); - MessageConsumer advisoryConsumer = session.createConsumer(advisoryTopic); - MessageConsumer advisoryWhenFullConsumer = session.createConsumer(advisoryWhenFullTopic); + MessageConsumer advisoryConsumer = session.createConsumer(advisoryTopic); + MessageConsumer advisoryWhenFullConsumer = session.createConsumer(advisoryWhenFullTopic); - MessageProducer producer = session.createProducer(genericProducer ? null : queue); + MessageProducer producer = session.createProducer(genericProducer ? null : queue); - try { - // send lots of messages to the tempQueue - for (int i = 0; i < MESSAGE_COUNT; i++) { - BytesMessage m = session.createBytesMessage(); - m.writeBytes(new byte[1024]); - if (genericProducer) { - producer.send(queue, m, DeliveryMode.PERSISTENT, 4, 0); - } else { - producer.send(m); - } + try { + // send lots of messages to the tempQueue + for (int i = 0; i < MESSAGE_COUNT; i++) { + BytesMessage m = session.createBytesMessage(); + m.writeBytes(new byte[1024]); + if (genericProducer) { + producer.send(queue, m, DeliveryMode.PERSISTENT, 4, 0); } - } catch (ResourceAllocationException expectedOnLimitReachedAfterFastAdvisory) {} + else { + producer.send(m); + } + } + } + catch (ResourceAllocationException expectedOnLimitReachedAfterFastAdvisory) { + } - // check one advisory message has produced on the advisoryTopic - Message advCmsg = advisoryConsumer.receive(4000); - assertNotNull(advCmsg); + // check one advisory message has produced on the advisoryTopic + Message advCmsg = advisoryConsumer.receive(4000); + assertNotNull(advCmsg); - advCmsg = advisoryWhenFullConsumer.receive(4000); - assertNotNull(advCmsg); + advCmsg = advisoryWhenFullConsumer.receive(4000); + assertNotNull(advCmsg); - connection.close(); - LOG.debug("Connection closed, destinations should now become inactive."); - } + connection.close(); + LOG.debug("Connection closed, destinations should now become inactive."); + } - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setPersistent(false); - answer.setUseJmx(false); + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + answer.setPersistent(false); + answer.setUseJmx(false); - PolicyEntry entry = new PolicyEntry(); - entry.setAdvisoryForFastProducers(true); - entry.setAdvisoryWhenFull(true); - entry.setMemoryLimit(10000); - PolicyMap map = new PolicyMap(); - map.setDefaultEntry(entry); + PolicyEntry entry = new PolicyEntry(); + entry.setAdvisoryForFastProducers(true); + entry.setAdvisoryWhenFull(true); + entry.setMemoryLimit(10000); + PolicyMap map = new PolicyMap(); + map.setDefaultEntry(entry); - answer.setDestinationPolicy(map); - answer.addConnector(bindAddress); + answer.setDestinationPolicy(map); + answer.addConnector(bindAddress); - answer.getSystemUsage().setSendFailIfNoSpace(true); + answer.getSystemUsage().setSendFailIfNoSpace(true); - return answer; - } + return answer; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3932Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3932Test.java index 78017a6c58..d42733dd73 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3932Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3932Test.java @@ -40,119 +40,122 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AMQ3932Test { - static final Logger LOG = LoggerFactory.getLogger(AMQ3932Test.class); - private Connection connection; - private BrokerService broker; - @Before - public void setUp() throws Exception { - broker = new BrokerService(); - broker.setPersistent(false); - broker.setUseJmx(false); - TransportConnector tcpConnector = broker.addConnector("tcp://localhost:0"); - broker.start(); + static final Logger LOG = LoggerFactory.getLogger(AMQ3932Test.class); + private Connection connection; + private BrokerService broker; - ConnectionFactory factory = new ActiveMQConnectionFactory( - "failover:("+ tcpConnector.getPublishableConnectString() +")?jms.prefetchPolicy.queuePrefetch=0"); - connection = factory.createConnection(); - connection.start(); - } + @Before + public void setUp() throws Exception { + broker = new BrokerService(); + broker.setPersistent(false); + broker.setUseJmx(false); + TransportConnector tcpConnector = broker.addConnector("tcp://localhost:0"); + broker.start(); - @After - public void tearDown() throws Exception { - connection.close(); + ConnectionFactory factory = new ActiveMQConnectionFactory("failover:(" + tcpConnector.getPublishableConnectString() + ")?jms.prefetchPolicy.queuePrefetch=0"); + connection = factory.createConnection(); + connection.start(); + } - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - broker = null; - } - } + @After + public void tearDown() throws Exception { + connection.close(); - @Test - public void testPlainReceiveBlocks() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageConsumer consumer = session.createConsumer(session.createQueue(getClass().getName())); + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + broker = null; + } + } - broker.stop(); - broker.waitUntilStopped(); - broker = null; + @Test + public void testPlainReceiveBlocks() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final MessageConsumer consumer = session.createConsumer(session.createQueue(getClass().getName())); - final CountDownLatch done = new CountDownLatch(1); - final CountDownLatch started = new CountDownLatch(1); - ExecutorService executor = Executors.newSingleThreadExecutor(); + broker.stop(); + broker.waitUntilStopped(); + broker = null; - executor.execute(new Runnable() { - public void run() { - try { - started.countDown(); - LOG.info("Entering into a Sync receive call"); - consumer.receive(); - } catch (JMSException e) { - } - done.countDown(); + final CountDownLatch done = new CountDownLatch(1); + final CountDownLatch started = new CountDownLatch(1); + ExecutorService executor = Executors.newSingleThreadExecutor(); + + executor.execute(new Runnable() { + public void run() { + try { + started.countDown(); + LOG.info("Entering into a Sync receive call"); + consumer.receive(); } - }); - - assertTrue(started.await(10, TimeUnit.SECONDS)); - assertFalse(done.await(20, TimeUnit.SECONDS)); - } - - @Test - public void testHungReceiveNoWait() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageConsumer consumer = session.createConsumer(session.createQueue(getClass().getName())); - - broker.stop(); - broker.waitUntilStopped(); - broker = null; - - final CountDownLatch done = new CountDownLatch(1); - final CountDownLatch started = new CountDownLatch(1); - ExecutorService executor = Executors.newSingleThreadExecutor(); - - executor.execute(new Runnable() { - public void run() { - try { - started.countDown(); - LOG.info("Entering into a Sync receiveNoWait call"); - consumer.receiveNoWait(); - } catch (JMSException e) { - } - done.countDown(); + catch (JMSException e) { } - }); + done.countDown(); + } + }); - assertTrue(started.await(10, TimeUnit.SECONDS)); - assertTrue(done.await(20, TimeUnit.SECONDS)); - } + assertTrue(started.await(10, TimeUnit.SECONDS)); + assertFalse(done.await(20, TimeUnit.SECONDS)); + } - @Test - public void testHungReceiveTimed() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageConsumer consumer = session.createConsumer(session.createQueue(getClass().getName())); + @Test + public void testHungReceiveNoWait() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final MessageConsumer consumer = session.createConsumer(session.createQueue(getClass().getName())); - broker.stop(); - broker.waitUntilStopped(); - broker = null; + broker.stop(); + broker.waitUntilStopped(); + broker = null; - final CountDownLatch done = new CountDownLatch(1); - final CountDownLatch started = new CountDownLatch(1); - ExecutorService executor = Executors.newSingleThreadExecutor(); + final CountDownLatch done = new CountDownLatch(1); + final CountDownLatch started = new CountDownLatch(1); + ExecutorService executor = Executors.newSingleThreadExecutor(); - executor.execute(new Runnable() { - public void run() { - try { - started.countDown(); - LOG.info("Entering into a timed Sync receive call"); - consumer.receive(10); - } catch (JMSException e) { - } - done.countDown(); + executor.execute(new Runnable() { + public void run() { + try { + started.countDown(); + LOG.info("Entering into a Sync receiveNoWait call"); + consumer.receiveNoWait(); } - }); + catch (JMSException e) { + } + done.countDown(); + } + }); - assertTrue(started.await(10, TimeUnit.SECONDS)); - assertTrue(done.await(20, TimeUnit.SECONDS)); - } + assertTrue(started.await(10, TimeUnit.SECONDS)); + assertTrue(done.await(20, TimeUnit.SECONDS)); + } + + @Test + public void testHungReceiveTimed() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final MessageConsumer consumer = session.createConsumer(session.createQueue(getClass().getName())); + + broker.stop(); + broker.waitUntilStopped(); + broker = null; + + final CountDownLatch done = new CountDownLatch(1); + final CountDownLatch started = new CountDownLatch(1); + ExecutorService executor = Executors.newSingleThreadExecutor(); + + executor.execute(new Runnable() { + public void run() { + try { + started.countDown(); + LOG.info("Entering into a timed Sync receive call"); + consumer.receive(10); + } + catch (JMSException e) { + } + done.countDown(); + } + }); + + assertTrue(started.await(10, TimeUnit.SECONDS)); + assertTrue(done.await(20, TimeUnit.SECONDS)); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3934Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3934Test.java index 80a2fa3924..3287085501 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3934Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3934Test.java @@ -26,6 +26,7 @@ import javax.jms.Session; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import javax.management.openmbean.CompositeData; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.jmx.QueueViewMBean; @@ -35,71 +36,71 @@ import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; public class AMQ3934Test { - private static final transient Logger LOG = LoggerFactory.getLogger(AMQ3934Test.class); - private static BrokerService brokerService; - private static String TEST_QUEUE = "testQueue"; - private static ActiveMQQueue queue = new ActiveMQQueue(TEST_QUEUE); - private static String BROKER_ADDRESS = "tcp://localhost:0"; + private static final transient Logger LOG = LoggerFactory.getLogger(AMQ3934Test.class); + private static BrokerService brokerService; + private static String TEST_QUEUE = "testQueue"; + private static ActiveMQQueue queue = new ActiveMQQueue(TEST_QUEUE); + private static String BROKER_ADDRESS = "tcp://localhost:0"; - private ActiveMQConnectionFactory connectionFactory; - private String connectionUri; - private String messageID; + private ActiveMQConnectionFactory connectionFactory; + private String connectionUri; + private String messageID; - @Before - public void setUp() throws Exception { - brokerService = new BrokerService(); - brokerService.setPersistent(false); - brokerService.setUseJmx(true); - connectionUri = brokerService.addConnector(BROKER_ADDRESS).getPublishableConnectString(); - brokerService.start(); - brokerService.waitUntilStarted(); + @Before + public void setUp() throws Exception { + brokerService = new BrokerService(); + brokerService.setPersistent(false); + brokerService.setUseJmx(true); + connectionUri = brokerService.addConnector(BROKER_ADDRESS).getPublishableConnectString(); + brokerService.start(); + brokerService.waitUntilStarted(); - connectionFactory = new ActiveMQConnectionFactory(connectionUri); - sendMessage(); - } + connectionFactory = new ActiveMQConnectionFactory(connectionUri); + sendMessage(); + } - public void sendMessage() throws Exception { - final Connection conn = connectionFactory.createConnection(); - try { - conn.start(); - final Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - final Destination queue = session.createQueue(TEST_QUEUE); - final Message toSend = session.createMessage(); - final MessageProducer producer = session.createProducer(queue); - producer.send(queue, toSend); - } finally { - conn.close(); - } - } + public void sendMessage() throws Exception { + final Connection conn = connectionFactory.createConnection(); + try { + conn.start(); + final Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + final Destination queue = session.createQueue(TEST_QUEUE); + final Message toSend = session.createMessage(); + final MessageProducer producer = session.createProducer(queue); + producer.send(queue, toSend); + } + finally { + conn.close(); + } + } - @After - public void tearDown() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - } + @After + public void tearDown() throws Exception { + brokerService.stop(); + brokerService.waitUntilStopped(); + } - @Test - public void getMessage() throws Exception { - final QueueViewMBean queueView = getProxyToQueueViewMBean(); - final CompositeData messages[] = queueView.browse(); - messageID = (String) messages[0].get("JMSMessageID"); - assertNotNull(messageID); - assertNotNull(queueView.getMessage(messageID)); - LOG.debug("Attempting to remove message ID: " + messageID); - queueView.removeMessage(messageID); - assertNull(queueView.getMessage(messageID)); - } + @Test + public void getMessage() throws Exception { + final QueueViewMBean queueView = getProxyToQueueViewMBean(); + final CompositeData messages[] = queueView.browse(); + messageID = (String) messages[0].get("JMSMessageID"); + assertNotNull(messageID); + assertNotNull(queueView.getMessage(messageID)); + LOG.debug("Attempting to remove message ID: " + messageID); + queueView.removeMessage(messageID); + assertNull(queueView.getMessage(messageID)); + } - private QueueViewMBean getProxyToQueueViewMBean() throws MalformedObjectNameException, NullPointerException, - JMSException { - final ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + queue.getQueueName()); - final QueueViewMBean proxy = (QueueViewMBean) brokerService.getManagementContext().newProxyInstance( - queueViewMBeanName, QueueViewMBean.class, true); - return proxy; - } + private QueueViewMBean getProxyToQueueViewMBean() throws MalformedObjectNameException, NullPointerException, JMSException { + final ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + queue.getQueueName()); + final QueueViewMBean proxy = (QueueViewMBean) brokerService.getManagementContext().newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); + return proxy; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3961Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3961Test.java index 8afcaa9719..df7a942c0a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3961Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3961Test.java @@ -43,143 +43,143 @@ import org.junit.Test; public class AMQ3961Test { - private static BrokerService brokerService; - private static String BROKER_ADDRESS = "tcp://localhost:0"; + private static BrokerService brokerService; + private static String BROKER_ADDRESS = "tcp://localhost:0"; - private ActiveMQConnectionFactory connectionFactory; - private String connectionUri; + private ActiveMQConnectionFactory connectionFactory; + private String connectionUri; - @Before - public void setUp() throws Exception { - brokerService = new BrokerService(); - brokerService.setPersistent(false); - brokerService.setUseJmx(true); - brokerService.setDeleteAllMessagesOnStartup(true); - connectionUri = brokerService.addConnector(BROKER_ADDRESS).getPublishableConnectString(); - brokerService.start(); - brokerService.waitUntilStarted(); + @Before + public void setUp() throws Exception { + brokerService = new BrokerService(); + brokerService.setPersistent(false); + brokerService.setUseJmx(true); + brokerService.setDeleteAllMessagesOnStartup(true); + connectionUri = brokerService.addConnector(BROKER_ADDRESS).getPublishableConnectString(); + brokerService.start(); + brokerService.waitUntilStarted(); - connectionFactory = new ActiveMQConnectionFactory(connectionUri); - } + connectionFactory = new ActiveMQConnectionFactory(connectionUri); + } - @After - public void tearDown() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - } + @After + public void tearDown() throws Exception { + brokerService.stop(); + brokerService.waitUntilStopped(); + } - public class TestServerSessionPool implements ServerSessionPool { + public class TestServerSessionPool implements ServerSessionPool { - private final TopicConnection connection; + private final TopicConnection connection; - public TestServerSessionPool(final TopicConnection connection) { - this.connection = connection; - } + public TestServerSessionPool(final TopicConnection connection) { + this.connection = connection; + } - @Override - public ServerSession getServerSession() throws JMSException { - final TopicSession topicSession = connection.createTopicSession(true, Session.AUTO_ACKNOWLEDGE); - return new TestServerSession(topicSession); - } - } + @Override + public ServerSession getServerSession() throws JMSException { + final TopicSession topicSession = connection.createTopicSession(true, Session.AUTO_ACKNOWLEDGE); + return new TestServerSession(topicSession); + } + } - public class TestServerSession implements ServerSession, MessageListener { + public class TestServerSession implements ServerSession, MessageListener { - private final TopicSession session; + private final TopicSession session; - public TestServerSession(final TopicSession session) throws JMSException { - this.session = session; - session.setMessageListener(this); - } + public TestServerSession(final TopicSession session) throws JMSException { + this.session = session; + session.setMessageListener(this); + } - @Override - public Session getSession() throws JMSException { - return session; - } + @Override + public Session getSession() throws JMSException { + return session; + } - @Override - public void start() throws JMSException { - session.run(); - } + @Override + public void start() throws JMSException { + session.run(); + } - @Override - public void onMessage(final Message message) { + @Override + public void onMessage(final Message message) { + synchronized (processedSessions) { + processedSessions.add(this); + } + } + } + + public static final int MESSAGE_COUNT = 16; + private final List processedSessions = new LinkedList(); + private final List committedSessions = new LinkedList(); + + @Test + public void testPrefetchInDurableSubscription() throws Exception { + final ActiveMQTopic topic = new ActiveMQTopic("TestTopic"); + + final TopicConnection initialSubConnection = connectionFactory.createTopicConnection(); + initialSubConnection.setClientID("TestClient"); + initialSubConnection.start(); + final TopicSession initialSubSession = initialSubConnection.createTopicSession(false, Session.CLIENT_ACKNOWLEDGE); + final TopicSubscriber initialSubscriber = initialSubSession.createDurableSubscriber(topic, "TestSubscriber"); + + initialSubscriber.close(); + initialSubSession.close(); + initialSubConnection.close(); + + final TopicConnection publisherConnection = connectionFactory.createTopicConnection(); + publisherConnection.start(); + final TopicSession publisherSession = publisherConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); + final TopicPublisher publisher = publisherSession.createPublisher(topic); + for (int i = 1; i <= MESSAGE_COUNT; i++) { + final Message msg = publisherSession.createTextMessage("Message #" + i); + publisher.publish(msg); + } + publisher.close(); + publisherSession.close(); + publisherConnection.close(); + + final TopicConnection connection = connectionFactory.createTopicConnection(); + connection.setClientID("TestClient"); + connection.start(); + final TestServerSessionPool pool = new TestServerSessionPool(connection); + final ConnectionConsumer connectionConsumer = connection.createDurableConnectionConsumer(topic, "TestSubscriber", null, pool, 1); + while (true) { + int lastMsgCount = 0; + int msgCount = 0; + do { + lastMsgCount = msgCount; + Thread.sleep(200L); synchronized (processedSessions) { - processedSessions.add(this); + msgCount = processedSessions.size(); } - } - } + } while (lastMsgCount < msgCount); - public static final int MESSAGE_COUNT = 16; - private final List processedSessions = new LinkedList(); - private final List committedSessions = new LinkedList(); + if (lastMsgCount == 0) { + break; + } - @Test - public void testPrefetchInDurableSubscription() throws Exception { - final ActiveMQTopic topic = new ActiveMQTopic("TestTopic"); + final LinkedList collected; + synchronized (processedSessions) { + collected = new LinkedList(processedSessions); + processedSessions.clear(); + } - final TopicConnection initialSubConnection = connectionFactory.createTopicConnection(); - initialSubConnection.setClientID("TestClient"); - initialSubConnection.start(); - final TopicSession initialSubSession = initialSubConnection.createTopicSession(false, Session.CLIENT_ACKNOWLEDGE); - final TopicSubscriber initialSubscriber = initialSubSession.createDurableSubscriber(topic, "TestSubscriber"); + final Iterator sessions = collected.iterator(); + while (sessions.hasNext()) { + final TestServerSession session = sessions.next(); + committedSessions.add(session); + session.getSession().commit(); + session.getSession().close(); + } + } - initialSubscriber.close(); - initialSubSession.close(); - initialSubConnection.close(); - - final TopicConnection publisherConnection = connectionFactory.createTopicConnection(); - publisherConnection.start(); - final TopicSession publisherSession = publisherConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - final TopicPublisher publisher = publisherSession.createPublisher(topic); - for (int i = 1; i <= MESSAGE_COUNT; i++) { - final Message msg = publisherSession.createTextMessage("Message #" + i); - publisher.publish(msg); - } - publisher.close(); - publisherSession.close(); - publisherConnection.close(); - - final TopicConnection connection = connectionFactory.createTopicConnection(); - connection.setClientID("TestClient"); - connection.start(); - final TestServerSessionPool pool = new TestServerSessionPool(connection); - final ConnectionConsumer connectionConsumer = connection.createDurableConnectionConsumer(topic, "TestSubscriber", null, pool, 1); - while (true) { - int lastMsgCount = 0; - int msgCount = 0; - do { - lastMsgCount = msgCount; - Thread.sleep(200L); - synchronized (processedSessions) { - msgCount = processedSessions.size(); - } - } while (lastMsgCount < msgCount); - - if (lastMsgCount == 0) { - break; - } - - final LinkedList collected; - synchronized (processedSessions) { - collected = new LinkedList(processedSessions); - processedSessions.clear(); - } - - final Iterator sessions = collected.iterator(); - while (sessions.hasNext()) { - final TestServerSession session = sessions.next(); - committedSessions.add(session); - session.getSession().commit(); - session.getSession().close(); - } - } - - connectionConsumer.close(); - final TopicSession finalSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - finalSession.unsubscribe("TestSubscriber"); - finalSession.close(); - connection.close(); - assertEquals(MESSAGE_COUNT, committedSessions.size()); - } + connectionConsumer.close(); + final TopicSession finalSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); + finalSession.unsubscribe("TestSubscriber"); + finalSession.close(); + connection.close(); + assertEquals(MESSAGE_COUNT, committedSessions.size()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3992Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3992Test.java index c359c887c0..4fe8ba1306 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3992Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3992Test.java @@ -37,71 +37,70 @@ import org.slf4j.LoggerFactory; public class AMQ3992Test { - private static final transient Logger LOG = LoggerFactory.getLogger(AMQ3992Test.class); - private static BrokerService brokerService; - private static String BROKER_ADDRESS = "tcp://localhost:0"; + private static final transient Logger LOG = LoggerFactory.getLogger(AMQ3992Test.class); + private static BrokerService brokerService; + private static String BROKER_ADDRESS = "tcp://localhost:0"; - private String connectionUri; + private String connectionUri; - @Before - public void setUp() throws Exception { - brokerService = new BrokerService(); - brokerService.setPersistent(false); - brokerService.setUseJmx(true); - brokerService.setDeleteAllMessagesOnStartup(true); - connectionUri = brokerService.addConnector(BROKER_ADDRESS).getPublishableConnectString(); - brokerService.start(); - brokerService.waitUntilStarted(); - } + @Before + public void setUp() throws Exception { + brokerService = new BrokerService(); + brokerService.setPersistent(false); + brokerService.setUseJmx(true); + brokerService.setDeleteAllMessagesOnStartup(true); + connectionUri = brokerService.addConnector(BROKER_ADDRESS).getPublishableConnectString(); + brokerService.start(); + brokerService.waitUntilStarted(); + } - @After - public void tearDown() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - } + @After + public void tearDown() throws Exception { + brokerService.stop(); + brokerService.waitUntilStopped(); + } - @Test - public void testDurableConsumerEnqueueCountWithZeroPrefetch() throws Exception { + @Test + public void testDurableConsumerEnqueueCountWithZeroPrefetch() throws Exception { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionUri); - connectionFactory.getPrefetchPolicy().setAll(0); + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionUri); + connectionFactory.getPrefetchPolicy().setAll(0); - Connection connection = connectionFactory.createConnection(); - connection.setClientID(getClass().getName()); - connection.start(); + Connection connection = connectionFactory.createConnection(); + connection.setClientID(getClass().getName()); + connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createTopic("DurableTopic"); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createTopic("DurableTopic"); - MessageConsumer consumer = session.createDurableSubscriber((Topic) destination, "EnqueueSub"); + MessageConsumer consumer = session.createDurableSubscriber((Topic) destination, "EnqueueSub"); - BrokerView view = brokerService.getAdminView(); - view.getDurableTopicSubscribers(); + BrokerView view = brokerService.getAdminView(); + view.getDurableTopicSubscribers(); - ObjectName subName = view.getDurableTopicSubscribers()[0]; + ObjectName subName = view.getDurableTopicSubscribers()[0]; - DurableSubscriptionViewMBean sub = (DurableSubscriptionViewMBean) - brokerService.getManagementContext().newProxyInstance(subName, DurableSubscriptionViewMBean.class, true); + DurableSubscriptionViewMBean sub = (DurableSubscriptionViewMBean) brokerService.getManagementContext().newProxyInstance(subName, DurableSubscriptionViewMBean.class, true); - assertEquals(0, sub.getEnqueueCounter()); + assertEquals(0, sub.getEnqueueCounter()); - LOG.info("Enqueue counter for sub before pull requests: " + sub.getEnqueueCounter()); + LOG.info("Enqueue counter for sub before pull requests: " + sub.getEnqueueCounter()); - // Trigger some pull Timeouts. - consumer.receive(500); - consumer.receive(500); - consumer.receive(500); - consumer.receive(500); - consumer.receive(500); + // Trigger some pull Timeouts. + consumer.receive(500); + consumer.receive(500); + consumer.receive(500); + consumer.receive(500); + consumer.receive(500); - // Let them all timeout. - Thread.sleep(600); + // Let them all timeout. + Thread.sleep(600); - LOG.info("Enqueue counter for sub after pull requests: " + sub.getEnqueueCounter()); - assertEquals(0, sub.getEnqueueCounter()); + LOG.info("Enqueue counter for sub after pull requests: " + sub.getEnqueueCounter()); + assertEquals(0, sub.getEnqueueCounter()); - consumer.close(); - session.close(); - connection.close(); - } + consumer.close(); + session.close(); + connection.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4062Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4062Test.java index 2be0126b27..d2044dc052 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4062Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4062Test.java @@ -56,222 +56,226 @@ import org.junit.Test; public class AMQ4062Test { - private BrokerService service; - private PolicyEntry policy; - private ConcurrentMap durableSubscriptions; + private BrokerService service; + private PolicyEntry policy; + private ConcurrentMap durableSubscriptions; - private static final int PREFETCH_SIZE_5=5; - private String connectionUri; + private static final int PREFETCH_SIZE_5 = 5; + private String connectionUri; - @Before - public void startBroker() throws IOException, Exception { - service=new BrokerService(); - service.setPersistent(true); - service.setDeleteAllMessagesOnStartup(true); - service.setUseJmx(false); + @Before + public void startBroker() throws IOException, Exception { + service = new BrokerService(); + service.setPersistent(true); + service.setDeleteAllMessagesOnStartup(true); + service.setUseJmx(false); - KahaDBPersistenceAdapter pa=new KahaDBPersistenceAdapter(); - File dataFile=new File("createData"); - pa.setDirectory(dataFile); - pa.setJournalMaxFileLength(1024*1024*32); + KahaDBPersistenceAdapter pa = new KahaDBPersistenceAdapter(); + File dataFile = new File("createData"); + pa.setDirectory(dataFile); + pa.setJournalMaxFileLength(1024 * 1024 * 32); - service.setPersistenceAdapter(pa); + service.setPersistenceAdapter(pa); - policy = new PolicyEntry(); - policy.setTopic(">"); - policy.setDurableTopicPrefetch(PREFETCH_SIZE_5); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); + policy = new PolicyEntry(); + policy.setTopic(">"); + policy.setDurableTopicPrefetch(PREFETCH_SIZE_5); + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); - service.setDestinationPolicy(pMap); + service.setDestinationPolicy(pMap); - service.addConnector("tcp://localhost:0"); + service.addConnector("tcp://localhost:0"); - service.start(); - service.waitUntilStarted(); + service.start(); + service.waitUntilStarted(); - connectionUri = service.getTransportConnectors().get(0).getPublishableConnectString(); - } + connectionUri = service.getTransportConnectors().get(0).getPublishableConnectString(); + } - public void restartBroker() throws IOException, Exception { - service=new BrokerService(); - service.setPersistent(true); - service.setUseJmx(false); - service.setKeepDurableSubsActive(false); + public void restartBroker() throws IOException, Exception { + service = new BrokerService(); + service.setPersistent(true); + service.setUseJmx(false); + service.setKeepDurableSubsActive(false); - KahaDBPersistenceAdapter pa=new KahaDBPersistenceAdapter(); - File dataFile=new File("createData"); - pa.setDirectory(dataFile); - pa.setJournalMaxFileLength(1024*1024*32); + KahaDBPersistenceAdapter pa = new KahaDBPersistenceAdapter(); + File dataFile = new File("createData"); + pa.setDirectory(dataFile); + pa.setJournalMaxFileLength(1024 * 1024 * 32); - service.setPersistenceAdapter(pa); + service.setPersistenceAdapter(pa); - policy = new PolicyEntry(); - policy.setTopic(">"); - policy.setDurableTopicPrefetch(PREFETCH_SIZE_5); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); + policy = new PolicyEntry(); + policy.setTopic(">"); + policy.setDurableTopicPrefetch(PREFETCH_SIZE_5); + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); - service.setDestinationPolicy(pMap); - service.addConnector("tcp://localhost:0"); - service.start(); - service.waitUntilStarted(); + service.setDestinationPolicy(pMap); + service.addConnector("tcp://localhost:0"); + service.start(); + service.waitUntilStarted(); - connectionUri = service.getTransportConnectors().get(0).getPublishableConnectString(); - } + connectionUri = service.getTransportConnectors().get(0).getPublishableConnectString(); + } - @After - public void stopBroker() throws Exception { - service.stop(); - service.waitUntilStopped(); - service = null; - } + @After + public void stopBroker() throws Exception { + service.stop(); + service.waitUntilStopped(); + service = null; + } - @Test - public void testDirableSubPrefetchRecovered() throws Exception{ + @Test + public void testDirableSubPrefetchRecovered() throws Exception { - PrefetchConsumer consumer=new PrefetchConsumer(true, connectionUri); - consumer.receive(); - durableSubscriptions=getDurableSubscriptions(); - ConsumerInfo info=getConsumerInfo(durableSubscriptions); + PrefetchConsumer consumer = new PrefetchConsumer(true, connectionUri); + consumer.receive(); + durableSubscriptions = getDurableSubscriptions(); + ConsumerInfo info = getConsumerInfo(durableSubscriptions); - //check if the prefetchSize equals to the size we set in the PolicyEntry - assertEquals(PREFETCH_SIZE_5, info.getPrefetchSize()); + //check if the prefetchSize equals to the size we set in the PolicyEntry + assertEquals(PREFETCH_SIZE_5, info.getPrefetchSize()); - consumer.a.countDown(); - Producer p=new Producer(connectionUri); - p.send(); - p = null; + consumer.a.countDown(); + Producer p = new Producer(connectionUri); + p.send(); + p = null; - service.stop(); - service.waitUntilStopped(); - durableSubscriptions=null; + service.stop(); + service.waitUntilStopped(); + durableSubscriptions = null; - consumer = null; - stopBroker(); + consumer = null; + stopBroker(); - restartBroker(); + restartBroker(); - getDurableSubscriptions(); - info=null; - info = getConsumerInfo(durableSubscriptions); + getDurableSubscriptions(); + info = null; + info = getConsumerInfo(durableSubscriptions); - //check if the prefetchSize equals to 0 after persistent storage recovered - //assertEquals(0, info.getPrefetchSize()); + //check if the prefetchSize equals to 0 after persistent storage recovered + //assertEquals(0, info.getPrefetchSize()); - consumer=new PrefetchConsumer(false, connectionUri); - consumer.receive(); - consumer.a.countDown(); + consumer = new PrefetchConsumer(false, connectionUri); + consumer.receive(); + consumer.a.countDown(); - info=null; - info = getConsumerInfo(durableSubscriptions); + info = null; + info = getConsumerInfo(durableSubscriptions); - //check if the prefetchSize is the default size for durable consumer and the PolicyEntry - //we set earlier take no effect - //assertEquals(100, info.getPrefetchSize()); - //info.getPrefetchSize() is 100,it should be 5,because I set the PolicyEntry as follows, - //policy.setDurableTopicPrefetch(PREFETCH_SIZE_5); - assertEquals(5, info.getPrefetchSize()); - } + //check if the prefetchSize is the default size for durable consumer and the PolicyEntry + //we set earlier take no effect + //assertEquals(100, info.getPrefetchSize()); + //info.getPrefetchSize() is 100,it should be 5,because I set the PolicyEntry as follows, + //policy.setDurableTopicPrefetch(PREFETCH_SIZE_5); + assertEquals(5, info.getPrefetchSize()); + } - @SuppressWarnings("unchecked") - private ConcurrentMap getDurableSubscriptions() throws NoSuchFieldException, IllegalAccessException { - if(durableSubscriptions!=null) return durableSubscriptions; - RegionBroker regionBroker=(RegionBroker)service.getRegionBroker(); - TopicRegion region=(TopicRegion)regionBroker.getTopicRegion(); - Field field=TopicRegion.class.getDeclaredField("durableSubscriptions"); - field.setAccessible(true); - durableSubscriptions=(ConcurrentMap)field.get(region); - return durableSubscriptions; - } + @SuppressWarnings("unchecked") + private ConcurrentMap getDurableSubscriptions() throws NoSuchFieldException, IllegalAccessException { + if (durableSubscriptions != null) + return durableSubscriptions; + RegionBroker regionBroker = (RegionBroker) service.getRegionBroker(); + TopicRegion region = (TopicRegion) regionBroker.getTopicRegion(); + Field field = TopicRegion.class.getDeclaredField("durableSubscriptions"); + field.setAccessible(true); + durableSubscriptions = (ConcurrentMap) field.get(region); + return durableSubscriptions; + } - private ConsumerInfo getConsumerInfo(ConcurrentMap durableSubscriptions) { - ConsumerInfo info=null; - for(Iterator it=durableSubscriptions.values().iterator();it.hasNext();){ - Subscription sub = it.next(); - info=sub.getConsumerInfo(); - if(info.getSubscriptionName().equals(PrefetchConsumer.SUBSCRIPTION_NAME)){ - return info; - } - } - return null; - } + private ConsumerInfo getConsumerInfo(ConcurrentMap durableSubscriptions) { + ConsumerInfo info = null; + for (Iterator it = durableSubscriptions.values().iterator(); it.hasNext(); ) { + Subscription sub = it.next(); + info = sub.getConsumerInfo(); + if (info.getSubscriptionName().equals(PrefetchConsumer.SUBSCRIPTION_NAME)) { + return info; + } + } + return null; + } - public class PrefetchConsumer implements MessageListener{ - public static final String SUBSCRIPTION_NAME = "A_NAME_ABC_DEF"; - private final String user = ActiveMQConnection.DEFAULT_USER; - private final String password = ActiveMQConnection.DEFAULT_PASSWORD; - private final String uri; - private boolean transacted; - ActiveMQConnection connection; - Session session; - MessageConsumer consumer; - private boolean needAck=false; - CountDownLatch a=new CountDownLatch(1); + public class PrefetchConsumer implements MessageListener { - public PrefetchConsumer(boolean needAck, String uri){ - this.needAck=needAck; - this.uri = uri; - } + public static final String SUBSCRIPTION_NAME = "A_NAME_ABC_DEF"; + private final String user = ActiveMQConnection.DEFAULT_USER; + private final String password = ActiveMQConnection.DEFAULT_PASSWORD; + private final String uri; + private boolean transacted; + ActiveMQConnection connection; + Session session; + MessageConsumer consumer; + private boolean needAck = false; + CountDownLatch a = new CountDownLatch(1); - public void receive() throws Exception{ - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, uri); - connection = (ActiveMQConnection)connectionFactory.createConnection(); - connection.setClientID("3"); - connection.start(); + public PrefetchConsumer(boolean needAck, String uri) { + this.needAck = needAck; + this.uri = uri; + } - session = connection.createSession(transacted, Session.CLIENT_ACKNOWLEDGE); - Destination destination = session.createTopic("topic2"); - consumer = session.createDurableSubscriber((Topic)destination,SUBSCRIPTION_NAME); - consumer.setMessageListener(this); - } + public void receive() throws Exception { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, uri); + connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.setClientID("3"); + connection.start(); - @Override - public void onMessage(Message message) { + session = connection.createSession(transacted, Session.CLIENT_ACKNOWLEDGE); + Destination destination = session.createTopic("topic2"); + consumer = session.createDurableSubscriber((Topic) destination, SUBSCRIPTION_NAME); + consumer.setMessageListener(this); + } + + @Override + public void onMessage(Message message) { + try { + a.await(); + } + catch (InterruptedException e1) { + } + if (needAck) { try { - a.await(); - } catch (InterruptedException e1) { + message.acknowledge(); + consumer.close(); + session.close(); + connection.close(); } - if(needAck){ - try { - message.acknowledge(); - consumer.close(); - session.close(); - connection.close(); - } catch (JMSException e) { - } + catch (JMSException e) { } - } - } + } + } + } - public class Producer { + public class Producer { - protected final String user = ActiveMQConnection.DEFAULT_USER; + protected final String user = ActiveMQConnection.DEFAULT_USER; - private final String password = ActiveMQConnection.DEFAULT_PASSWORD; - private final String uri; - private boolean transacted; + private final String password = ActiveMQConnection.DEFAULT_PASSWORD; + private final String uri; + private boolean transacted; - public Producer(String uri) { - this.uri = uri; - } + public Producer(String uri) { + this.uri = uri; + } - public void send() throws Exception{ - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, uri); - ActiveMQConnection connection = (ActiveMQConnection)connectionFactory.createConnection(); - connection.start(); + public void send() throws Exception { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, uri); + ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.start(); - ActiveMQSession session = (ActiveMQSession)connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createTopic("topic2"); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - for(int i=0;i<100;i++){ - TextMessage om=session.createTextMessage("hello from producer"); - producer.send(om); - } - producer.close(); - session.close(); - connection.close(); - } - } + ActiveMQSession session = (ActiveMQSession) connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createTopic("topic2"); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + for (int i = 0; i < 100; i++) { + TextMessage om = session.createTextMessage("hello from producer"); + producer.send(om); + } + producer.close(); + session.close(); + connection.close(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4083Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4083Test.java index 389f1f613b..c554af2f5e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4083Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4083Test.java @@ -30,6 +30,7 @@ import javax.jms.MessageListener; import javax.jms.MessageProducer; import javax.jms.Session; import javax.management.ObjectName; + import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQPrefetchPolicy; @@ -42,467 +43,477 @@ import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class AMQ4083Test { - private static final transient Logger LOG = LoggerFactory.getLogger(AMQ3992Test.class); - private static BrokerService brokerService; - private static String BROKER_ADDRESS = "tcp://localhost:0"; - private static String TEST_QUEUE = "testQueue"; - private static ActiveMQQueue queue = new ActiveMQQueue(TEST_QUEUE); + private static final transient Logger LOG = LoggerFactory.getLogger(AMQ3992Test.class); + private static BrokerService brokerService; + private static String BROKER_ADDRESS = "tcp://localhost:0"; + private static String TEST_QUEUE = "testQueue"; + private static ActiveMQQueue queue = new ActiveMQQueue(TEST_QUEUE); - private final int messageCount = 100; + private final int messageCount = 100; - private String connectionUri; - private String[] data; + private String connectionUri; + private String[] data; - @Before - public void setUp() throws Exception { - brokerService = new BrokerService(); - brokerService.setPersistent(false); - brokerService.setUseJmx(true); - brokerService.setDeleteAllMessagesOnStartup(true); - connectionUri = brokerService.addConnector(BROKER_ADDRESS).getPublishableConnectString(); - brokerService.start(); - brokerService.waitUntilStarted(); + @Before + public void setUp() throws Exception { + brokerService = new BrokerService(); + brokerService.setPersistent(false); + brokerService.setUseJmx(true); + brokerService.setDeleteAllMessagesOnStartup(true); + connectionUri = brokerService.addConnector(BROKER_ADDRESS).getPublishableConnectString(); + brokerService.start(); + brokerService.waitUntilStarted(); - data = new String[messageCount]; + data = new String[messageCount]; - for (int i = 0; i < messageCount; i++) { - data[i] = "Text for message: " + i + " at " + new Date(); - } - } + for (int i = 0; i < messageCount; i++) { + data[i] = "Text for message: " + i + " at " + new Date(); + } + } - @After - public void tearDown() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - } + @After + public void tearDown() throws Exception { + brokerService.stop(); + brokerService.waitUntilStopped(); + } - @Test - public void testExpiredMsgsBeforeNonExpired() throws Exception { + @Test + public void testExpiredMsgsBeforeNonExpired() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); - connection.getPrefetchPolicy().setQueuePrefetch(400); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); + ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); + connection.getPrefetchPolicy().setQueuePrefetch(400); - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - connection.start(); + connection.start(); - MessageProducer producer = session.createProducer(queue); - MessageConsumer consumer = session.createConsumer(queue); + MessageProducer producer = session.createProducer(queue); + MessageConsumer consumer = session.createConsumer(queue); - // send a batch that expires in a short time. - for (int i = 0; i < 100; i++) { + // send a batch that expires in a short time. + for (int i = 0; i < 100; i++) { + producer.send(session.createTextMessage(), DeliveryMode.PERSISTENT, 4, 4000); + } + + // and send one that doesn't expire to we can ack it. + producer.send(session.createTextMessage()); + + // wait long enough so the first batch times out. + TimeUnit.SECONDS.sleep(5); + + final QueueViewMBean queueView = getProxyToQueueViewMBean(); + + assertEquals(101, queueView.getInFlightCount()); + + consumer.setMessageListener(new MessageListener() { + public void onMessage(Message message) { + try { + message.acknowledge(); + } + catch (JMSException e) { + } + } + }); + + TimeUnit.SECONDS.sleep(5); + + assertEquals(0, queueView.getInFlightCount()); + + for (int i = 0; i < 200; i++) { + producer.send(session.createTextMessage()); + } + + assertTrue("Inflight count should reach zero, currently: " + queueView.getInFlightCount(), Wait.waitFor(new Wait.Condition() { + + public boolean isSatisified() throws Exception { + return queueView.getInFlightCount() == 0; + } + })); + + LOG.info("Dequeued Count: {}", queueView.getDequeueCount()); + LOG.info("Dispatch Count: {}", queueView.getDispatchCount()); + LOG.info("Enqueue Count: {}", queueView.getEnqueueCount()); + LOG.info("Expired Count: {}", queueView.getExpiredCount()); + LOG.info("InFlight Count: {}", queueView.getInFlightCount()); + } + + @Test + public void testExpiredMsgsBeforeNonExpiredWithTX() throws Exception { + + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); + ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); + connection.getPrefetchPolicy().setQueuePrefetch(400); + + final Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + + connection.start(); + + MessageProducer producer = session.createProducer(queue); + MessageConsumer consumer = session.createConsumer(queue); + + // send a batch that expires in a short time. + for (int i = 0; i < 100; i++) { + producer.send(session.createTextMessage(), DeliveryMode.PERSISTENT, 4, 4000); + } + + // and send one that doesn't expire to we can ack it. + producer.send(session.createTextMessage()); + session.commit(); + + // wait long enough so the first batch times out. + TimeUnit.SECONDS.sleep(5); + + final QueueViewMBean queueView = getProxyToQueueViewMBean(); + + assertEquals(101, queueView.getInFlightCount()); + + consumer.setMessageListener(new MessageListener() { + public void onMessage(Message message) { + try { + session.commit(); + } + catch (JMSException e) { + } + } + }); + + TimeUnit.SECONDS.sleep(5); + + assertEquals(0, queueView.getInFlightCount()); + + for (int i = 0; i < 200; i++) { + producer.send(session.createTextMessage()); + } + session.commit(); + + assertTrue("Inflight count should reach zero, currently: " + queueView.getInFlightCount(), Wait.waitFor(new Wait.Condition() { + + @Override + public boolean isSatisified() throws Exception { + return queueView.getInFlightCount() == 0; + } + })); + + LOG.info("Dequeued Count: {}", queueView.getDequeueCount()); + LOG.info("Dispatch Count: {}", queueView.getDispatchCount()); + LOG.info("Enqueue Count: {}", queueView.getEnqueueCount()); + LOG.info("Expired Count: {}", queueView.getExpiredCount()); + LOG.info("InFlight Count: {}", queueView.getInFlightCount()); + } + + @Test + public void testExpiredMsgsInterleavedWithNonExpired() throws Exception { + + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); + ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); + connection.getPrefetchPolicy().setQueuePrefetch(400); + + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + + connection.start(); + + MessageProducer producer = session.createProducer(queue); + MessageConsumer consumer = session.createConsumer(queue); + + // send a batch that expires in a short time. + for (int i = 0; i < 200; i++) { + + if ((i % 2) == 0) { producer.send(session.createTextMessage(), DeliveryMode.PERSISTENT, 4, 4000); - } - - // and send one that doesn't expire to we can ack it. - producer.send(session.createTextMessage()); - - // wait long enough so the first batch times out. - TimeUnit.SECONDS.sleep(5); - - final QueueViewMBean queueView = getProxyToQueueViewMBean(); - - assertEquals(101, queueView.getInFlightCount()); - - consumer.setMessageListener(new MessageListener() { - public void onMessage(Message message) { - try { - message.acknowledge(); - } catch (JMSException e) { - } - } - }); - - TimeUnit.SECONDS.sleep(5); - - assertEquals(0, queueView.getInFlightCount()); - - for (int i = 0; i < 200; i++) { + } + else { producer.send(session.createTextMessage()); - } + } + } - assertTrue("Inflight count should reach zero, currently: " + queueView.getInFlightCount(), Wait.waitFor(new Wait.Condition() { + // wait long enough so the first batch times out. + TimeUnit.SECONDS.sleep(5); - public boolean isSatisified() throws Exception { - return queueView.getInFlightCount() == 0; + final QueueViewMBean queueView = getProxyToQueueViewMBean(); + + assertEquals(200, queueView.getInFlightCount()); + + consumer.setMessageListener(new MessageListener() { + + @Override + public void onMessage(Message message) { + try { + LOG.debug("Acking message: {}", message); + message.acknowledge(); } - })); + catch (JMSException e) { + } + } + }); - LOG.info("Dequeued Count: {}", queueView.getDequeueCount()); - LOG.info("Dispatch Count: {}", queueView.getDispatchCount()); - LOG.info("Enqueue Count: {}", queueView.getEnqueueCount()); - LOG.info("Expired Count: {}", queueView.getExpiredCount()); - LOG.info("InFlight Count: {}", queueView.getInFlightCount()); - } + TimeUnit.SECONDS.sleep(5); - @Test - public void testExpiredMsgsBeforeNonExpiredWithTX() throws Exception { + assertTrue("Inflight count should reach zero, currently: " + queueView.getInFlightCount(), Wait.waitFor(new Wait.Condition() { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); - connection.getPrefetchPolicy().setQueuePrefetch(400); + @Override + public boolean isSatisified() throws Exception { + return queueView.getInFlightCount() == 0; + } + })); - final Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + for (int i = 0; i < 200; i++) { + producer.send(session.createTextMessage()); + } - connection.start(); + assertTrue("Inflight count should reach zero, currently: " + queueView.getInFlightCount(), Wait.waitFor(new Wait.Condition() { - MessageProducer producer = session.createProducer(queue); - MessageConsumer consumer = session.createConsumer(queue); + @Override + public boolean isSatisified() throws Exception { + return queueView.getInFlightCount() == 0; + } + })); - // send a batch that expires in a short time. - for (int i = 0; i < 100; i++) { + LOG.info("Dequeued Count: {}", queueView.getDequeueCount()); + LOG.info("Dispatch Count: {}", queueView.getDispatchCount()); + LOG.info("Enqueue Count: {}", queueView.getEnqueueCount()); + LOG.info("Expired Count: {}", queueView.getExpiredCount()); + LOG.info("InFlight Count: {}", queueView.getInFlightCount()); + } + + @Test + public void testExpiredMsgsInterleavedWithNonExpiredCumulativeAck() throws Exception { + + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); + ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); + connection.getPrefetchPolicy().setQueuePrefetch(400); + + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + + connection.start(); + + MessageProducer producer = session.createProducer(queue); + MessageConsumer consumer = session.createConsumer(queue); + + // send a batch that expires in a short time. + for (int i = 0; i < 200; i++) { + + if ((i % 2) == 0) { producer.send(session.createTextMessage(), DeliveryMode.PERSISTENT, 4, 4000); - } - - // and send one that doesn't expire to we can ack it. - producer.send(session.createTextMessage()); - session.commit(); - - // wait long enough so the first batch times out. - TimeUnit.SECONDS.sleep(5); - - final QueueViewMBean queueView = getProxyToQueueViewMBean(); - - assertEquals(101, queueView.getInFlightCount()); - - consumer.setMessageListener(new MessageListener() { - public void onMessage(Message message) { - try { - session.commit(); - } catch (JMSException e) { - } - } - }); - - TimeUnit.SECONDS.sleep(5); - - assertEquals(0, queueView.getInFlightCount()); - - for (int i = 0; i < 200; i++) { + } + else { producer.send(session.createTextMessage()); - } - session.commit(); + } + } - assertTrue("Inflight count should reach zero, currently: " + queueView.getInFlightCount(), Wait.waitFor(new Wait.Condition() { + // wait long enough so the first batch times out. + TimeUnit.SECONDS.sleep(5); - @Override - public boolean isSatisified() throws Exception { - return queueView.getInFlightCount() == 0; + final QueueViewMBean queueView = getProxyToQueueViewMBean(); + + assertEquals(200, queueView.getInFlightCount()); + + final AtomicInteger msgCount = new AtomicInteger(); + + consumer.setMessageListener(new MessageListener() { + + @Override + public void onMessage(Message message) { + try { + if (msgCount.incrementAndGet() == 100) { + LOG.debug("Acking message: {}", message); + message.acknowledge(); + } } - })); - - LOG.info("Dequeued Count: {}", queueView.getDequeueCount()); - LOG.info("Dispatch Count: {}", queueView.getDispatchCount()); - LOG.info("Enqueue Count: {}", queueView.getEnqueueCount()); - LOG.info("Expired Count: {}", queueView.getExpiredCount()); - LOG.info("InFlight Count: {}", queueView.getInFlightCount()); - } - - @Test - public void testExpiredMsgsInterleavedWithNonExpired() throws Exception { - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); - connection.getPrefetchPolicy().setQueuePrefetch(400); - - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - - connection.start(); - - MessageProducer producer = session.createProducer(queue); - MessageConsumer consumer = session.createConsumer(queue); - - // send a batch that expires in a short time. - for (int i = 0; i < 200; i++) { - - if ((i % 2) == 0) { - producer.send(session.createTextMessage(), DeliveryMode.PERSISTENT, 4, 4000); - } else { - producer.send(session.createTextMessage()); + catch (JMSException e) { } - } + } + }); - // wait long enough so the first batch times out. - TimeUnit.SECONDS.sleep(5); + TimeUnit.SECONDS.sleep(5); - final QueueViewMBean queueView = getProxyToQueueViewMBean(); + assertTrue("Inflight count should reach zero, currently: " + queueView.getInFlightCount(), Wait.waitFor(new Wait.Condition() { - assertEquals(200, queueView.getInFlightCount()); + @Override + public boolean isSatisified() throws Exception { + return queueView.getInFlightCount() == 0; + } + })); - consumer.setMessageListener(new MessageListener() { + // Now we just ack each and see if our counters come out right in the end. + consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - try { - LOG.debug("Acking message: {}", message); - message.acknowledge(); - } catch (JMSException e) { - } + @Override + public void onMessage(Message message) { + try { + LOG.debug("Acking message: {}", message); + message.acknowledge(); } - }); - - TimeUnit.SECONDS.sleep(5); - - assertTrue("Inflight count should reach zero, currently: " + queueView.getInFlightCount(), Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - return queueView.getInFlightCount() == 0; + catch (JMSException e) { } - })); + } + }); - for (int i = 0; i < 200; i++) { - producer.send(session.createTextMessage()); - } + for (int i = 0; i < 200; i++) { + producer.send(session.createTextMessage()); + } - assertTrue("Inflight count should reach zero, currently: " + queueView.getInFlightCount(), Wait.waitFor(new Wait.Condition() { + assertTrue("Inflight count should reach zero, currently: " + queueView.getInFlightCount(), Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return queueView.getInFlightCount() == 0; + @Override + public boolean isSatisified() throws Exception { + return queueView.getInFlightCount() == 0; + } + })); + + LOG.info("Dequeued Count: {}", queueView.getDequeueCount()); + LOG.info("Dispatch Count: {}", queueView.getDispatchCount()); + LOG.info("Enqueue Count: {}", queueView.getEnqueueCount()); + LOG.info("Expired Count: {}", queueView.getExpiredCount()); + LOG.info("InFlight Count: {}", queueView.getInFlightCount()); + } + + @Test + public void testExpiredBatchBetweenNonExpiredMessages() throws Exception { + + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); + ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); + connection.getPrefetchPolicy().setQueuePrefetch(400); + + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + + connection.start(); + + MessageProducer producer = session.createProducer(queue); + MessageConsumer consumer = session.createConsumer(queue); + + // Send one that doesn't expire so we can ack it. + producer.send(session.createTextMessage()); + + // send a batch that expires in a short time. + for (int i = 0; i < 100; i++) { + producer.send(session.createTextMessage(), DeliveryMode.PERSISTENT, 4, 4000); + } + + // and send one that doesn't expire so we can ack it. + producer.send(session.createTextMessage()); + + // wait long enough so the first batch times out. + TimeUnit.SECONDS.sleep(5); + + final QueueViewMBean queueView = getProxyToQueueViewMBean(); + + assertEquals(102, queueView.getInFlightCount()); + + consumer.setMessageListener(new MessageListener() { + + @Override + public void onMessage(Message message) { + try { + message.acknowledge(); } - })); - - LOG.info("Dequeued Count: {}", queueView.getDequeueCount()); - LOG.info("Dispatch Count: {}", queueView.getDispatchCount()); - LOG.info("Enqueue Count: {}", queueView.getEnqueueCount()); - LOG.info("Expired Count: {}", queueView.getExpiredCount()); - LOG.info("InFlight Count: {}", queueView.getInFlightCount()); - } - - @Test - public void testExpiredMsgsInterleavedWithNonExpiredCumulativeAck() throws Exception { - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); - connection.getPrefetchPolicy().setQueuePrefetch(400); - - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - - connection.start(); - - MessageProducer producer = session.createProducer(queue); - MessageConsumer consumer = session.createConsumer(queue); - - // send a batch that expires in a short time. - for (int i = 0; i < 200; i++) { - - if ((i % 2) == 0) { - producer.send(session.createTextMessage(), DeliveryMode.PERSISTENT, 4, 4000); - } else { - producer.send(session.createTextMessage()); + catch (JMSException e) { } - } + } + }); - // wait long enough so the first batch times out. - TimeUnit.SECONDS.sleep(5); + TimeUnit.SECONDS.sleep(5); - final QueueViewMBean queueView = getProxyToQueueViewMBean(); + assertTrue("Inflight count should reach zero, currently: " + queueView.getInFlightCount(), Wait.waitFor(new Wait.Condition() { - assertEquals(200, queueView.getInFlightCount()); + @Override + public boolean isSatisified() throws Exception { + return queueView.getInFlightCount() == 0; + } + })); - final AtomicInteger msgCount = new AtomicInteger(); + for (int i = 0; i < 200; i++) { + producer.send(session.createTextMessage()); + } - consumer.setMessageListener(new MessageListener() { + assertTrue("Inflight count should reach zero, currently: " + queueView.getInFlightCount(), Wait.waitFor(new Wait.Condition() { - @Override - public void onMessage(Message message) { - try { - if (msgCount.incrementAndGet() == 100) { - LOG.debug("Acking message: {}", message); - message.acknowledge(); - } - } catch (JMSException e) { - } - } - }); + @Override + public boolean isSatisified() throws Exception { + return queueView.getInFlightCount() == 0; + } + })); - TimeUnit.SECONDS.sleep(5); + LOG.info("Dequeued Count: {}", queueView.getDequeueCount()); + LOG.info("Dispatch Count: {}", queueView.getDispatchCount()); + LOG.info("Enqueue Count: {}", queueView.getEnqueueCount()); + LOG.info("Expired Count: {}", queueView.getExpiredCount()); + LOG.info("InFlight Count: {}", queueView.getInFlightCount()); + } - assertTrue("Inflight count should reach zero, currently: " + queueView.getInFlightCount(), Wait.waitFor(new Wait.Condition() { + @Test + public void testConsumeExpiredQueueAndDlq() throws Exception { - @Override - public boolean isSatisified() throws Exception { - return queueView.getInFlightCount() == 0; - } - })); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); + Connection connection = factory.createConnection(); - // Now we just ack each and see if our counters come out right in the end. - consumer.setMessageListener(new MessageListener() { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - @Override - public void onMessage(Message message) { - try { - LOG.debug("Acking message: {}", message); - message.acknowledge(); - } catch (JMSException e) { - } - } - }); + MessageProducer producerNormal = session.createProducer(queue); + MessageProducer producerExpire = session.createProducer(queue); + producerExpire.setTimeToLive(500); - for (int i = 0; i < 200; i++) { - producer.send(session.createTextMessage()); - } + MessageConsumer dlqConsumer = session.createConsumer(session.createQueue("ActiveMQ.DLQ")); + connection.start(); - assertTrue("Inflight count should reach zero, currently: " + queueView.getInFlightCount(), Wait.waitFor(new Wait.Condition() { + Connection consumerConnection = factory.createConnection(); + ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); + prefetchPolicy.setAll(10); + ((ActiveMQConnection) consumerConnection).setPrefetchPolicy(prefetchPolicy); + Session consumerSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + MessageConsumer consumer = consumerSession.createConsumer(queue); + consumerConnection.start(); - @Override - public boolean isSatisified() throws Exception { - return queueView.getInFlightCount() == 0; - } - })); + String msgBody = new String(new byte[20 * 1024]); + for (int i = 0; i < data.length; i++) { + Message message = session.createTextMessage(msgBody); + producerExpire.send(queue, message); + } - LOG.info("Dequeued Count: {}", queueView.getDequeueCount()); - LOG.info("Dispatch Count: {}", queueView.getDispatchCount()); - LOG.info("Enqueue Count: {}", queueView.getEnqueueCount()); - LOG.info("Expired Count: {}", queueView.getExpiredCount()); - LOG.info("InFlight Count: {}", queueView.getInFlightCount()); - } + for (int i = 0; i < data.length; i++) { + Message message = session.createTextMessage(msgBody); + producerNormal.send(queue, message); + } - @Test - public void testExpiredBatchBetweenNonExpiredMessages() throws Exception { + ArrayList messages = new ArrayList(); + Message received; + while ((received = consumer.receive(1000)) != null) { + messages.add(received); + if (messages.size() == 1) { + TimeUnit.SECONDS.sleep(1); + } + received.acknowledge(); + } + ; - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); - connection.getPrefetchPolicy().setQueuePrefetch(400); + assertEquals("got messages", messageCount + 1, messages.size()); - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + ArrayList dlqMessages = new ArrayList(); + while ((received = dlqConsumer.receive(1000)) != null) { + dlqMessages.add(received); + } + ; - connection.start(); + assertEquals("got dlq messages", data.length - 1, dlqMessages.size()); - MessageProducer producer = session.createProducer(queue); - MessageConsumer consumer = session.createConsumer(queue); + final QueueViewMBean queueView = getProxyToQueueViewMBean(); - // Send one that doesn't expire so we can ack it. - producer.send(session.createTextMessage()); + LOG.info("Dequeued Count: {}", queueView.getDequeueCount()); + LOG.info("Dispatch Count: {}", queueView.getDispatchCount()); + LOG.info("Enqueue Count: {}", queueView.getEnqueueCount()); + LOG.info("Expired Count: {}", queueView.getExpiredCount()); + LOG.info("InFlight Count: {}", queueView.getInFlightCount()); + } - // send a batch that expires in a short time. - for (int i = 0; i < 100; i++) { - producer.send(session.createTextMessage(), DeliveryMode.PERSISTENT, 4, 4000); - } - - // and send one that doesn't expire so we can ack it. - producer.send(session.createTextMessage()); - - // wait long enough so the first batch times out. - TimeUnit.SECONDS.sleep(5); - - final QueueViewMBean queueView = getProxyToQueueViewMBean(); - - assertEquals(102, queueView.getInFlightCount()); - - consumer.setMessageListener(new MessageListener() { - - @Override - public void onMessage(Message message) { - try { - message.acknowledge(); - } catch (JMSException e) { - } - } - }); - - TimeUnit.SECONDS.sleep(5); - - assertTrue("Inflight count should reach zero, currently: " + queueView.getInFlightCount(), Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - return queueView.getInFlightCount() == 0; - } - })); - - for (int i = 0; i < 200; i++) { - producer.send(session.createTextMessage()); - } - - assertTrue("Inflight count should reach zero, currently: " + queueView.getInFlightCount(), Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - return queueView.getInFlightCount() == 0; - } - })); - - LOG.info("Dequeued Count: {}", queueView.getDequeueCount()); - LOG.info("Dispatch Count: {}", queueView.getDispatchCount()); - LOG.info("Enqueue Count: {}", queueView.getEnqueueCount()); - LOG.info("Expired Count: {}", queueView.getExpiredCount()); - LOG.info("InFlight Count: {}", queueView.getInFlightCount()); - } - - @Test - public void testConsumeExpiredQueueAndDlq() throws Exception { - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - Connection connection = factory.createConnection(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageProducer producerNormal = session.createProducer(queue); - MessageProducer producerExpire = session.createProducer(queue); - producerExpire.setTimeToLive(500); - - MessageConsumer dlqConsumer = session.createConsumer(session.createQueue("ActiveMQ.DLQ")); - connection.start(); - - Connection consumerConnection = factory.createConnection(); - ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); - prefetchPolicy.setAll(10); - ((ActiveMQConnection)consumerConnection).setPrefetchPolicy(prefetchPolicy); - Session consumerSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = consumerSession.createConsumer(queue); - consumerConnection.start(); - - String msgBody = new String(new byte[20*1024]); - for (int i = 0; i < data.length; i++) { - Message message = session.createTextMessage(msgBody); - producerExpire.send(queue, message); - } - - for (int i = 0; i < data.length; i++) { - Message message = session.createTextMessage(msgBody); - producerNormal.send(queue, message); - } - - ArrayList messages = new ArrayList(); - Message received; - while ((received = consumer.receive(1000)) != null) { - messages.add(received); - if (messages.size() == 1) { - TimeUnit.SECONDS.sleep(1); - } - received.acknowledge(); - }; - - assertEquals("got messages", messageCount + 1, messages.size()); - - ArrayList dlqMessages = new ArrayList(); - while ((received = dlqConsumer.receive(1000)) != null) { - dlqMessages.add(received); - }; - - assertEquals("got dlq messages", data.length - 1, dlqMessages.size()); - - final QueueViewMBean queueView = getProxyToQueueViewMBean(); - - LOG.info("Dequeued Count: {}", queueView.getDequeueCount()); - LOG.info("Dispatch Count: {}", queueView.getDispatchCount()); - LOG.info("Enqueue Count: {}", queueView.getEnqueueCount()); - LOG.info("Expired Count: {}", queueView.getExpiredCount()); - LOG.info("InFlight Count: {}", queueView.getInFlightCount()); - } - - private QueueViewMBean getProxyToQueueViewMBean() throws Exception { - final ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + queue.getQueueName()); - final QueueViewMBean proxy = (QueueViewMBean) brokerService.getManagementContext().newProxyInstance( - queueViewMBeanName, QueueViewMBean.class, true); - return proxy; - } + private QueueViewMBean getProxyToQueueViewMBean() throws Exception { + final ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + queue.getQueueName()); + final QueueViewMBean proxy = (QueueViewMBean) brokerService.getManagementContext().newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); + return proxy; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4092Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4092Test.java index e8c1cf0c47..3a072c240b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4092Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4092Test.java @@ -32,7 +32,9 @@ import javax.jms.MessageListener; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; + import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.command.ActiveMQQueue; @@ -42,197 +44,190 @@ import org.slf4j.LoggerFactory; public class AMQ4092Test extends TestCase { - private static final Logger log = LoggerFactory.getLogger(AMQ4092Test.class); + private static final Logger log = LoggerFactory.getLogger(AMQ4092Test.class); - static final String QUEUE_NAME = "TEST"; + static final String QUEUE_NAME = "TEST"; - // increase limits to expedite failure - static final int NUM_TO_SEND_PER_PRODUCER = 1000; // 10000 - static final int NUM_PRODUCERS = 5; // 40 + // increase limits to expedite failure + static final int NUM_TO_SEND_PER_PRODUCER = 1000; // 10000 + static final int NUM_PRODUCERS = 5; // 40 - static final ActiveMQQueue[] DESTINATIONS = new ActiveMQQueue[]{ - new ActiveMQQueue("A"), - new ActiveMQQueue("B") - // A/B seems to be sufficient for concurrentStoreAndDispatch=true - }; + static final ActiveMQQueue[] DESTINATIONS = new ActiveMQQueue[]{new ActiveMQQueue("A"), new ActiveMQQueue("B") + // A/B seems to be sufficient for concurrentStoreAndDispatch=true + }; - static final boolean debug = false; + static final boolean debug = false; - private BrokerService brokerService; + private BrokerService brokerService; - private ActiveMQQueue destination; - private HashMap exceptions = new HashMap(); - private ExceptionListener exceptionListener = new ExceptionListener() { - @Override - public void onException(JMSException exception) { - exception.printStackTrace(); - exceptions.put(Thread.currentThread(), exception); - } - }; + private ActiveMQQueue destination; + private HashMap exceptions = new HashMap(); + private ExceptionListener exceptionListener = new ExceptionListener() { + @Override + public void onException(JMSException exception) { + exception.printStackTrace(); + exceptions.put(Thread.currentThread(), exception); + } + }; - @Override - protected void setUp() throws Exception { - brokerService = new BrokerService(); - brokerService.setDeleteAllMessagesOnStartup(true); - ((KahaDBPersistenceAdapter)brokerService.getPersistenceAdapter()).setConcurrentStoreAndDispatchQueues(false); - brokerService.addConnector("tcp://localhost:0"); - brokerService.start(); - destination = new ActiveMQQueue(); - destination.setCompositeDestinations(DESTINATIONS); - Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { - @Override - public void uncaughtException(Thread t, Throwable e) { - exceptions.put(t, e); + @Override + protected void setUp() throws Exception { + brokerService = new BrokerService(); + brokerService.setDeleteAllMessagesOnStartup(true); + ((KahaDBPersistenceAdapter) brokerService.getPersistenceAdapter()).setConcurrentStoreAndDispatchQueues(false); + brokerService.addConnector("tcp://localhost:0"); + brokerService.start(); + destination = new ActiveMQQueue(); + destination.setCompositeDestinations(DESTINATIONS); + Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { + @Override + public void uncaughtException(Thread t, Throwable e) { + exceptions.put(t, e); + } + }); + } + + @Override + protected void tearDown() throws Exception { + // Stop any running threads. + brokerService.stop(); + } + + public void testConcurrentGroups() throws Exception { + ExecutorService executorService = Executors.newCachedThreadPool(); + executorService.submit(new TestConsumer()); + for (int i = 0; i < NUM_PRODUCERS; i++) { + executorService.submit(new TestProducer()); + } + executorService.shutdown(); + executorService.awaitTermination(5, TimeUnit.MINUTES); + assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); + } + + class TestProducer implements Runnable { + + public void produceMessages() throws Exception { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerService.getTransportConnectors().get(0).getConnectUri().toString()); + connectionFactory.setExceptionListener(exceptionListener); + connectionFactory.setUseAsyncSend(true); + Connection connection = connectionFactory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + + String name = new String(new byte[2 * 1024]); + for (int i = 1; i <= NUM_TO_SEND_PER_PRODUCER; i++) { + + TextMessage message = session.createTextMessage(name + "_" + i); + for (int j = 0; j < 100; j++) { + message.setStringProperty("Prop" + j, "" + j); } - }); - } + message.setStringProperty("JMSXGroupID", Thread.currentThread().getName() + i); + message.setIntProperty("JMSXGroupSeq", 1); + producer.send(message); + } - @Override - protected void tearDown() throws Exception { - // Stop any running threads. - brokerService.stop(); - } + producer.close(); + session.close(); + connection.close(); + } + @Override + public void run() { + try { + produceMessages(); + } + catch (Exception e) { + e.printStackTrace(); + exceptions.put(Thread.currentThread(), e); + } + } + } - public void testConcurrentGroups() throws Exception { - ExecutorService executorService = Executors.newCachedThreadPool(); - executorService.submit(new TestConsumer()); - for (int i=0; i 0); + // Commit, which ensures message is in queue and memory usage updated. + session.commit(); + Assert.assertTrue(physicalDestination.getMemoryUsage().getUsage() > 0); - // Consume the message and verify that the test queue is no longer using - // any memory. - MessageConsumer consumer = session.createConsumer(destination); - Message received = consumer.receive(); - Assert.assertNotNull(received); + // Consume the message and verify that the test queue is no longer using + // any memory. + MessageConsumer consumer = session.createConsumer(destination); + Message received = consumer.receive(); + Assert.assertNotNull(received); - // Commit, which ensures message is removed from queue and memory usage - // updated. - session.commit(); - Assert.assertEquals(0, physicalDestination.getMemoryUsage().getUsage()); + // Commit, which ensures message is removed from queue and memory usage + // updated. + session.commit(); + Assert.assertEquals(0, physicalDestination.getMemoryUsage().getUsage()); - // Resend the message to a different queue and verify that the original - // test queue is still not using any memory. - ActiveMQQueue secondDestination = new ActiveMQQueue(AMQ4116Test.class + ".second"); - MessageProducer secondPproducer = session.createProducer(secondDestination); + // Resend the message to a different queue and verify that the original + // test queue is still not using any memory. + ActiveMQQueue secondDestination = new ActiveMQQueue(AMQ4116Test.class + ".second"); + MessageProducer secondPproducer = session.createProducer(secondDestination); - secondPproducer.send(received); + secondPproducer.send(received); - // Commit, which ensures message is in queue and memory usage updated. - // NOTE: This assertion fails due to bug. - session.commit(); - Assert.assertEquals(0, physicalDestination.getMemoryUsage().getUsage()); + // Commit, which ensures message is in queue and memory usage updated. + // NOTE: This assertion fails due to bug. + session.commit(); + Assert.assertEquals(0, physicalDestination.getMemoryUsage().getUsage()); - conn.stop(); - } + conn.stop(); + } - /** - * Create an embedded broker that has both TCP and VM connectors. - */ - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - connectionUri = broker.addConnector(tcpAddr).getPublishableConnectString(); - return broker; - } + /** + * Create an embedded broker that has both TCP and VM connectors. + */ + @Override + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); + connectionUri = broker.addConnector(tcpAddr).getPublishableConnectString(); + return broker; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4126Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4126Test.java index 4d6d39c47d..d47c7c88b0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4126Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4126Test.java @@ -41,140 +41,141 @@ import org.junit.Test; */ public class AMQ4126Test { - protected BrokerService broker; + protected BrokerService broker; - protected String java_security_auth_login_config = "java.security.auth.login.config"; - protected String xbean = "xbean:"; - protected String confBase = "src/test/resources/org/apache/activemq/bugs/amq4126"; - protected String certBase = "src/test/resources/org/apache/activemq/security"; - protected String JaasStompSSLBroker_xml = "JaasStompSSLBroker.xml"; - protected StompConnection stompConnection = new StompConnection(); - private final static String destinationName = "TEST.QUEUE"; - protected String oldLoginConf = null; + protected String java_security_auth_login_config = "java.security.auth.login.config"; + protected String xbean = "xbean:"; + protected String confBase = "src/test/resources/org/apache/activemq/bugs/amq4126"; + protected String certBase = "src/test/resources/org/apache/activemq/security"; + protected String JaasStompSSLBroker_xml = "JaasStompSSLBroker.xml"; + protected StompConnection stompConnection = new StompConnection(); + private final static String destinationName = "TEST.QUEUE"; + protected String oldLoginConf = null; - @Before - public void before() throws Exception { - if (System.getProperty(java_security_auth_login_config) != null) { - oldLoginConf = System.getProperty(java_security_auth_login_config); - } - System.setProperty(java_security_auth_login_config, confBase + "/login.config"); - broker = BrokerFactory.createBroker(xbean + confBase + "/" + JaasStompSSLBroker_xml); + @Before + public void before() throws Exception { + if (System.getProperty(java_security_auth_login_config) != null) { + oldLoginConf = System.getProperty(java_security_auth_login_config); + } + System.setProperty(java_security_auth_login_config, confBase + "/login.config"); + broker = BrokerFactory.createBroker(xbean + confBase + "/" + JaasStompSSLBroker_xml); - broker.setDeleteAllMessagesOnStartup(true); - broker.setUseJmx(true); - broker.start(); - broker.waitUntilStarted(); - } + broker.setDeleteAllMessagesOnStartup(true); + broker.setUseJmx(true); + broker.start(); + broker.waitUntilStarted(); + } - @After - public void after() throws Exception { - broker.stop(); + @After + public void after() throws Exception { + broker.stop(); - if (oldLoginConf != null) { - System.setProperty(java_security_auth_login_config, oldLoginConf); - } - } + if (oldLoginConf != null) { + System.setProperty(java_security_auth_login_config, oldLoginConf); + } + } - public Socket createSocket(String host, int port) throws Exception { - System.setProperty("javax.net.ssl.trustStore", certBase + "/broker1.ks"); - System.setProperty("javax.net.ssl.trustStorePassword", "password"); - System.setProperty("javax.net.ssl.trustStoreType", "jks"); - System.setProperty("javax.net.ssl.keyStore", certBase + "/client.ks"); - System.setProperty("javax.net.ssl.keyStorePassword", "password"); - System.setProperty("javax.net.ssl.keyStoreType", "jks"); + public Socket createSocket(String host, int port) throws Exception { + System.setProperty("javax.net.ssl.trustStore", certBase + "/broker1.ks"); + System.setProperty("javax.net.ssl.trustStorePassword", "password"); + System.setProperty("javax.net.ssl.trustStoreType", "jks"); + System.setProperty("javax.net.ssl.keyStore", certBase + "/client.ks"); + System.setProperty("javax.net.ssl.keyStorePassword", "password"); + System.setProperty("javax.net.ssl.keyStoreType", "jks"); - SocketFactory factory = SSLSocketFactory.getDefault(); - return factory.createSocket(host, port); - } + SocketFactory factory = SSLSocketFactory.getDefault(); + return factory.createSocket(host, port); + } - public void stompConnectTo(String connectorName, String extraHeaders) throws Exception { - String host = broker.getConnectorByName(connectorName).getConnectUri().getHost(); - int port = broker.getConnectorByName(connectorName).getConnectUri().getPort(); - stompConnection.open(createSocket(host, port)); - String extra = extraHeaders != null ? extraHeaders : "\n"; - stompConnection.sendFrame("CONNECT\n" + extra + "\n" + Stomp.NULL); + public void stompConnectTo(String connectorName, String extraHeaders) throws Exception { + String host = broker.getConnectorByName(connectorName).getConnectUri().getHost(); + int port = broker.getConnectorByName(connectorName).getConnectUri().getPort(); + stompConnection.open(createSocket(host, port)); + String extra = extraHeaders != null ? extraHeaders : "\n"; + stompConnection.sendFrame("CONNECT\n" + extra + "\n" + Stomp.NULL); - StompFrame f = stompConnection.receive(); - TestCase.assertEquals(f.getBody(), "CONNECTED", f.getAction()); - stompConnection.close(); - } + StompFrame f = stompConnection.receive(); + TestCase.assertEquals(f.getBody(), "CONNECTED", f.getAction()); + stompConnection.close(); + } - @Test - public void testStompSSLWithUsernameAndPassword() throws Exception { - stompConnectTo("stomp+ssl", "login:system\n" + "passcode:manager\n"); - } + @Test + public void testStompSSLWithUsernameAndPassword() throws Exception { + stompConnectTo("stomp+ssl", "login:system\n" + "passcode:manager\n"); + } - @Test - public void testStompSSLWithCertificate() throws Exception { - stompConnectTo("stomp+ssl", null); - } + @Test + public void testStompSSLWithCertificate() throws Exception { + stompConnectTo("stomp+ssl", null); + } - @Test - public void testStompNIOSSLWithUsernameAndPassword() throws Exception { - stompConnectTo("stomp+nio+ssl", "login:system\n" + "passcode:manager\n"); - } + @Test + public void testStompNIOSSLWithUsernameAndPassword() throws Exception { + stompConnectTo("stomp+nio+ssl", "login:system\n" + "passcode:manager\n"); + } - @Test - public void testStompNIOSSLWithCertificate() throws Exception { - stompConnectTo("stomp+nio+ssl", null); - } + @Test + public void testStompNIOSSLWithCertificate() throws Exception { + stompConnectTo("stomp+nio+ssl", null); + } - public void openwireConnectTo(String connectorName, String username, String password) throws Exception { - URI brokerURI = broker.getConnectorByName(connectorName).getConnectUri(); - String uri = "ssl://" + brokerURI.getHost() + ":" + brokerURI.getPort(); - ActiveMQSslConnectionFactory cf = new ActiveMQSslConnectionFactory(uri); - cf.setTrustStore("org/apache/activemq/security/broker1.ks"); - cf.setTrustStorePassword("password"); - cf.setKeyStore("org/apache/activemq/security/client.ks"); - cf.setKeyStorePassword("password"); - ActiveMQConnection connection = null; - if (username != null || password != null) { - connection = (ActiveMQConnection)cf.createConnection(username, password); - } else { - connection = (ActiveMQConnection)cf.createConnection(); - } - TestCase.assertNotNull(connection); - connection.start(); - connection.stop(); - } + public void openwireConnectTo(String connectorName, String username, String password) throws Exception { + URI brokerURI = broker.getConnectorByName(connectorName).getConnectUri(); + String uri = "ssl://" + brokerURI.getHost() + ":" + brokerURI.getPort(); + ActiveMQSslConnectionFactory cf = new ActiveMQSslConnectionFactory(uri); + cf.setTrustStore("org/apache/activemq/security/broker1.ks"); + cf.setTrustStorePassword("password"); + cf.setKeyStore("org/apache/activemq/security/client.ks"); + cf.setKeyStorePassword("password"); + ActiveMQConnection connection = null; + if (username != null || password != null) { + connection = (ActiveMQConnection) cf.createConnection(username, password); + } + else { + connection = (ActiveMQConnection) cf.createConnection(); + } + TestCase.assertNotNull(connection); + connection.start(); + connection.stop(); + } - @Test - public void testOpenwireSSLWithUsernameAndPassword() throws Exception { - openwireConnectTo("openwire+ssl", "system", "manager"); - } + @Test + public void testOpenwireSSLWithUsernameAndPassword() throws Exception { + openwireConnectTo("openwire+ssl", "system", "manager"); + } - @Test - public void testOpenwireSSLWithCertificate() throws Exception { - openwireConnectTo("openwire+ssl", null, null); - } + @Test + public void testOpenwireSSLWithCertificate() throws Exception { + openwireConnectTo("openwire+ssl", null, null); + } - @Test - public void testOpenwireNIOSSLWithUsernameAndPassword() throws Exception { - openwireConnectTo("openwire+nio+ssl", "system", "mmanager"); - } + @Test + public void testOpenwireNIOSSLWithUsernameAndPassword() throws Exception { + openwireConnectTo("openwire+nio+ssl", "system", "mmanager"); + } - @Test - public void testOpenwireNIOSSLWithCertificate() throws Exception { - openwireConnectTo("openwire+nio+ssl", null, null); - } + @Test + public void testOpenwireNIOSSLWithCertificate() throws Exception { + openwireConnectTo("openwire+nio+ssl", null, null); + } - @Test - public void testJmx() throws Exception { - TestCase.assertFalse(findDestination(destinationName)); - broker.getAdminView().addQueue(destinationName); - TestCase.assertTrue(findDestination(destinationName)); - broker.getAdminView().removeQueue(destinationName); - TestCase.assertFalse(findDestination(destinationName)); - } + @Test + public void testJmx() throws Exception { + TestCase.assertFalse(findDestination(destinationName)); + broker.getAdminView().addQueue(destinationName); + TestCase.assertTrue(findDestination(destinationName)); + broker.getAdminView().removeQueue(destinationName); + TestCase.assertFalse(findDestination(destinationName)); + } - private boolean findDestination(String name) throws Exception { - ObjectName[] destinations = broker.getAdminView().getQueues(); - for (ObjectName destination : destinations) { - if (destination.toString().contains(name)) { - return true; - } - } - return false; - } + private boolean findDestination(String name) throws Exception { + ObjectName[] destinations = broker.getAdminView().getQueues(); + for (ObjectName destination : destinations) { + if (destination.toString().contains(name)) { + return true; + } + } + return false; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4133Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4133Test.java index 9ca08bb801..123413fec8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4133Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4133Test.java @@ -34,74 +34,74 @@ import org.junit.Test; public class AMQ4133Test { - protected String java_security_auth_login_config = "java.security.auth.login.config"; - protected String xbean = "xbean:"; - protected String confBase = "src/test/resources/org/apache/activemq/bugs/amq4126"; - protected String certBase = "src/test/resources/org/apache/activemq/security"; - protected String activemqXml = "InconsistentConnectorPropertiesBehaviour.xml"; - protected BrokerService broker; + protected String java_security_auth_login_config = "java.security.auth.login.config"; + protected String xbean = "xbean:"; + protected String confBase = "src/test/resources/org/apache/activemq/bugs/amq4126"; + protected String certBase = "src/test/resources/org/apache/activemq/security"; + protected String activemqXml = "InconsistentConnectorPropertiesBehaviour.xml"; + protected BrokerService broker; - protected String oldLoginConf = null; + protected String oldLoginConf = null; - @Before - public void before() throws Exception { - if (System.getProperty(java_security_auth_login_config) != null) { - oldLoginConf = System.getProperty(java_security_auth_login_config); - } - System.setProperty(java_security_auth_login_config, confBase + "/" + "login.config"); - broker = BrokerFactory.createBroker(xbean + confBase + "/" + activemqXml); + @Before + public void before() throws Exception { + if (System.getProperty(java_security_auth_login_config) != null) { + oldLoginConf = System.getProperty(java_security_auth_login_config); + } + System.setProperty(java_security_auth_login_config, confBase + "/" + "login.config"); + broker = BrokerFactory.createBroker(xbean + confBase + "/" + activemqXml); - broker.start(); - broker.waitUntilStarted(); - } + broker.start(); + broker.waitUntilStarted(); + } - @After - public void after() throws Exception { - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - } + @After + public void after() throws Exception { + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + } - @Test - public void stompSSLTransportNeedClientAuthTrue() throws Exception { - stompConnectTo("localhost", broker.getConnectorByName("stomp+ssl").getConnectUri().getPort()); - } + @Test + public void stompSSLTransportNeedClientAuthTrue() throws Exception { + stompConnectTo("localhost", broker.getConnectorByName("stomp+ssl").getConnectUri().getPort()); + } - @Test - public void stompSSLNeedClientAuthTrue() throws Exception { - stompConnectTo("localhost", broker.getConnectorByName("stomp+ssl+special").getConnectUri().getPort()); - } + @Test + public void stompSSLNeedClientAuthTrue() throws Exception { + stompConnectTo("localhost", broker.getConnectorByName("stomp+ssl+special").getConnectUri().getPort()); + } - @Test - public void stompNIOSSLTransportNeedClientAuthTrue() throws Exception { - stompConnectTo("localhost", broker.getConnectorByName("stomp+nio+ssl").getConnectUri().getPort()); - } + @Test + public void stompNIOSSLTransportNeedClientAuthTrue() throws Exception { + stompConnectTo("localhost", broker.getConnectorByName("stomp+nio+ssl").getConnectUri().getPort()); + } - @Test - public void stompNIOSSLNeedClientAuthTrue() throws Exception { - stompConnectTo("localhost", broker.getConnectorByName("stomp+nio+ssl+special").getConnectUri().getPort()); - } + @Test + public void stompNIOSSLNeedClientAuthTrue() throws Exception { + stompConnectTo("localhost", broker.getConnectorByName("stomp+nio+ssl+special").getConnectUri().getPort()); + } - public Socket createSocket(String host, int port) throws Exception { - System.setProperty("javax.net.ssl.trustStore", certBase + "/" + "broker1.ks"); - System.setProperty("javax.net.ssl.trustStorePassword", "password"); - System.setProperty("javax.net.ssl.trustStoreType", "jks"); - System.setProperty("javax.net.ssl.keyStore", certBase + "/" + "client.ks"); - System.setProperty("javax.net.ssl.keyStorePassword", "password"); - System.setProperty("javax.net.ssl.keyStoreType", "jks"); + public Socket createSocket(String host, int port) throws Exception { + System.setProperty("javax.net.ssl.trustStore", certBase + "/" + "broker1.ks"); + System.setProperty("javax.net.ssl.trustStorePassword", "password"); + System.setProperty("javax.net.ssl.trustStoreType", "jks"); + System.setProperty("javax.net.ssl.keyStore", certBase + "/" + "client.ks"); + System.setProperty("javax.net.ssl.keyStorePassword", "password"); + System.setProperty("javax.net.ssl.keyStoreType", "jks"); - SocketFactory factory = SSLSocketFactory.getDefault(); - return factory.createSocket(host, port); - } + SocketFactory factory = SSLSocketFactory.getDefault(); + return factory.createSocket(host, port); + } - public void stompConnectTo(String host, int port) throws Exception { - StompConnection stompConnection = new StompConnection(); - stompConnection.open(createSocket(host, port)); - stompConnection.sendFrame("CONNECT\n" + "\n" + Stomp.NULL); - StompFrame f = stompConnection.receive(); - TestCase.assertEquals(f.getBody(), "CONNECTED", f.getAction()); - stompConnection.close(); - } + public void stompConnectTo(String host, int port) throws Exception { + StompConnection stompConnection = new StompConnection(); + stompConnection.open(createSocket(host, port)); + stompConnection.sendFrame("CONNECT\n" + "\n" + Stomp.NULL); + StompFrame f = stompConnection.receive(); + TestCase.assertEquals(f.getBody(), "CONNECTED", f.getAction()); + stompConnection.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4147Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4147Test.java index cf7ca45fcf..d0096f1fc9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4147Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4147Test.java @@ -37,175 +37,174 @@ import org.apache.activemq.util.Wait; * manipulated by the remote broker. */ public class AMQ4147Test extends JmsMultipleBrokersTestSupport { - /** - * This test demonstrates the bug: namely, when a message is bridged over - * the VMTransport, its memory usage continues to refer to the originating - * broker. As a result, memory usage is never accounted for on the remote - * broker, and the local broker's memory usage is only decreased once the - * message is consumed on the remote broker. - */ - public void testVMTransportRemoteMemoryUsage() throws Exception { - BrokerService broker1 = createBroker(new URI( - "broker:(vm://broker1)/broker1?persistent=false")); - BrokerService broker2 = createBroker(new URI( - "broker:(vm://broker2)/broker2?persistent=false")); + /** + * This test demonstrates the bug: namely, when a message is bridged over + * the VMTransport, its memory usage continues to refer to the originating + * broker. As a result, memory usage is never accounted for on the remote + * broker, and the local broker's memory usage is only decreased once the + * message is consumed on the remote broker. + */ + public void testVMTransportRemoteMemoryUsage() throws Exception { + BrokerService broker1 = createBroker(new URI("broker:(vm://broker1)/broker1?persistent=false")); - startAllBrokers(); + BrokerService broker2 = createBroker(new URI("broker:(vm://broker2)/broker2?persistent=false")); - // Forward messages from broker1 to broker2 over the VM transport. - bridgeBrokers("broker1", "broker2").start(); + startAllBrokers(); - // Verify that broker1 and broker2's test queues have no memory usage. - ActiveMQDestination testQueue = createDestination( - AMQ4147Test.class.getSimpleName() + ".queue", false); - final Destination broker1TestQueue = broker1.getDestination(testQueue); - final Destination broker2TestQueue = broker2.getDestination(testQueue); + // Forward messages from broker1 to broker2 over the VM transport. + bridgeBrokers("broker1", "broker2").start(); - assertEquals(0, broker1TestQueue.getMemoryUsage().getUsage()); - assertEquals(0, broker2TestQueue.getMemoryUsage().getUsage()); + // Verify that broker1 and broker2's test queues have no memory usage. + ActiveMQDestination testQueue = createDestination(AMQ4147Test.class.getSimpleName() + ".queue", false); + final Destination broker1TestQueue = broker1.getDestination(testQueue); + final Destination broker2TestQueue = broker2.getDestination(testQueue); - // Produce a message to broker1's test queue and verify that broker1's - // memory usage has increased, but broker2 still has no memory usage. - sendMessages("broker1", testQueue, 1); - assertTrue(broker1TestQueue.getMemoryUsage().getUsage() > 0); - assertEquals(0, broker2TestQueue.getMemoryUsage().getUsage()); + assertEquals(0, broker1TestQueue.getMemoryUsage().getUsage()); + assertEquals(0, broker2TestQueue.getMemoryUsage().getUsage()); - // Create a consumer on broker2 that is synchronized to allow detection - // of "in flight" messages to the consumer. - MessageIdList broker2Messages = getBrokerMessages("broker2"); - final Semaphore consumerReady = new Semaphore(0); - final Semaphore consumerProceed = new Semaphore(0); + // Produce a message to broker1's test queue and verify that broker1's + // memory usage has increased, but broker2 still has no memory usage. + sendMessages("broker1", testQueue, 1); + assertTrue(broker1TestQueue.getMemoryUsage().getUsage() > 0); + assertEquals(0, broker2TestQueue.getMemoryUsage().getUsage()); - broker2Messages.setParent(new MessageListener() { - @Override - public void onMessage(Message message) { - consumerReady.release(); - try { - consumerProceed.acquire(); - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - } + // Create a consumer on broker2 that is synchronized to allow detection + // of "in flight" messages to the consumer. + MessageIdList broker2Messages = getBrokerMessages("broker2"); + final Semaphore consumerReady = new Semaphore(0); + final Semaphore consumerProceed = new Semaphore(0); + + broker2Messages.setParent(new MessageListener() { + @Override + public void onMessage(Message message) { + consumerReady.release(); + try { + consumerProceed.acquire(); } - }); + catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + } + }); - createConsumer("broker2", testQueue); + createConsumer("broker2", testQueue); - // Verify that when broker2's consumer receives the message, the memory - // usage has moved broker1 to broker2. The first assertion is expected - // to fail due to the bug; the try/finally ensures the consumer is - // released prior to failure so that the broker can shut down. - consumerReady.acquire(); + // Verify that when broker2's consumer receives the message, the memory + // usage has moved broker1 to broker2. The first assertion is expected + // to fail due to the bug; the try/finally ensures the consumer is + // released prior to failure so that the broker can shut down. + consumerReady.acquire(); - try { - assertTrue("Memory Usage Should be Zero: ", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return broker1TestQueue.getMemoryUsage().getUsage() == 0; - } - })); - assertTrue(broker2TestQueue.getMemoryUsage().getUsage() > 0); - } finally { - // Consume the message and verify that there is no more memory - // usage. - consumerProceed.release(); - } - - assertTrue("Memory Usage Should be Zero: ", Wait.waitFor(new Wait.Condition() { + try { + assertTrue("Memory Usage Should be Zero: ", Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisified() throws Exception { - return broker1TestQueue.getMemoryUsage().getUsage() == 0; + return broker1TestQueue.getMemoryUsage().getUsage() == 0; } - })); - assertTrue("Memory Usage Should be Zero: ", Wait.waitFor(new Wait.Condition() { + })); + assertTrue(broker2TestQueue.getMemoryUsage().getUsage() > 0); + } + finally { + // Consume the message and verify that there is no more memory + // usage. + consumerProceed.release(); + } + + assertTrue("Memory Usage Should be Zero: ", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return broker1TestQueue.getMemoryUsage().getUsage() == 0; + } + })); + assertTrue("Memory Usage Should be Zero: ", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return broker2TestQueue.getMemoryUsage().getUsage() == 0; + } + })); + } + + /** + * This test demonstrates that the bug is VMTransport-specific and does not + * occur when bridges occur using other protocols. + */ + public void testTcpTransportRemoteMemoryUsage() throws Exception { + BrokerService broker1 = createBroker(new URI("broker:(vm://broker1)/broker1?persistent=false")); + + BrokerService broker2 = createBroker(new URI("broker:(tcp://localhost:61616)/broker2?persistent=false")); + + startAllBrokers(); + + // Forward messages from broker1 to broker2 over the TCP transport. + bridgeBrokers("broker1", "broker2").start(); + + // Verify that broker1 and broker2's test queues have no memory usage. + ActiveMQDestination testQueue = createDestination(AMQ4147Test.class.getSimpleName() + ".queue", false); + final Destination broker1TestQueue = broker1.getDestination(testQueue); + final Destination broker2TestQueue = broker2.getDestination(testQueue); + + assertEquals(0, broker1TestQueue.getMemoryUsage().getUsage()); + assertEquals(0, broker2TestQueue.getMemoryUsage().getUsage()); + + // Produce a message to broker1's test queue and verify that broker1's + // memory usage has increased, but broker2 still has no memory usage. + sendMessages("broker1", testQueue, 1); + assertTrue(broker1TestQueue.getMemoryUsage().getUsage() > 0); + assertEquals(0, broker2TestQueue.getMemoryUsage().getUsage()); + + // Create a consumer on broker2 that is synchronized to allow detection + // of "in flight" messages to the consumer. + MessageIdList broker2Messages = getBrokerMessages("broker2"); + final Semaphore consumerReady = new Semaphore(0); + final Semaphore consumerProceed = new Semaphore(0); + + broker2Messages.setParent(new MessageListener() { + @Override + public void onMessage(Message message) { + consumerReady.release(); + try { + consumerProceed.acquire(); + } + catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + } + }); + + createConsumer("broker2", testQueue); + + // Verify that when broker2's consumer receives the message, the memory + // usage has moved broker1 to broker2. + consumerReady.acquire(); + + try { + assertTrue("Memory Usage Should be Zero: ", Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisified() throws Exception { - return broker2TestQueue.getMemoryUsage().getUsage() == 0; + return broker1TestQueue.getMemoryUsage().getUsage() == 0; } - })); - } + })); + assertTrue(broker2TestQueue.getMemoryUsage().getUsage() > 0); + } + finally { + // Consume the message and verify that there is no more memory + // usage. + consumerProceed.release(); + } - /** - * This test demonstrates that the bug is VMTransport-specific and does not - * occur when bridges occur using other protocols. - */ - public void testTcpTransportRemoteMemoryUsage() throws Exception { - BrokerService broker1 = createBroker(new URI( - "broker:(vm://broker1)/broker1?persistent=false")); - - BrokerService broker2 = createBroker(new URI( - "broker:(tcp://localhost:61616)/broker2?persistent=false")); - - startAllBrokers(); - - // Forward messages from broker1 to broker2 over the TCP transport. - bridgeBrokers("broker1", "broker2").start(); - - // Verify that broker1 and broker2's test queues have no memory usage. - ActiveMQDestination testQueue = createDestination( - AMQ4147Test.class.getSimpleName() + ".queue", false); - final Destination broker1TestQueue = broker1.getDestination(testQueue); - final Destination broker2TestQueue = broker2.getDestination(testQueue); - - assertEquals(0, broker1TestQueue.getMemoryUsage().getUsage()); - assertEquals(0, broker2TestQueue.getMemoryUsage().getUsage()); - - // Produce a message to broker1's test queue and verify that broker1's - // memory usage has increased, but broker2 still has no memory usage. - sendMessages("broker1", testQueue, 1); - assertTrue(broker1TestQueue.getMemoryUsage().getUsage() > 0); - assertEquals(0, broker2TestQueue.getMemoryUsage().getUsage()); - - // Create a consumer on broker2 that is synchronized to allow detection - // of "in flight" messages to the consumer. - MessageIdList broker2Messages = getBrokerMessages("broker2"); - final Semaphore consumerReady = new Semaphore(0); - final Semaphore consumerProceed = new Semaphore(0); - - broker2Messages.setParent(new MessageListener() { - @Override - public void onMessage(Message message) { - consumerReady.release(); - try { - consumerProceed.acquire(); - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - } - } - }); - - createConsumer("broker2", testQueue); - - // Verify that when broker2's consumer receives the message, the memory - // usage has moved broker1 to broker2. - consumerReady.acquire(); - - try { - assertTrue("Memory Usage Should be Zero: ", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return broker1TestQueue.getMemoryUsage().getUsage() == 0; - } - })); - assertTrue(broker2TestQueue.getMemoryUsage().getUsage() > 0); - } finally { - // Consume the message and verify that there is no more memory - // usage. - consumerProceed.release(); - } - - // Pause to allow ACK to be processed. - assertTrue("Memory Usage Should be Zero: ", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return broker1TestQueue.getMemoryUsage().getUsage() == 0; - } - })); - assertTrue("Memory Usage Should be Zero: ", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return broker2TestQueue.getMemoryUsage().getUsage() == 0; - } - })); - } + // Pause to allow ACK to be processed. + assertTrue("Memory Usage Should be Zero: ", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return broker1TestQueue.getMemoryUsage().getUsage() == 0; + } + })); + assertTrue("Memory Usage Should be Zero: ", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return broker2TestQueue.getMemoryUsage().getUsage() == 0; + } + })); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4148Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4148Test.java index 906131ef18..8558f48f6c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4148Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4148Test.java @@ -38,58 +38,56 @@ import org.junit.Assert; */ public class AMQ4148Test extends JmsMultipleBrokersTestSupport { - public void test() throws Exception { - // Create a hub-and-spoke network where each hub-spoke pair share - // messages on a test queue. - BrokerService hub = createBroker(new URI("broker:(vm://hub)/hub?persistent=false")); + public void test() throws Exception { + // Create a hub-and-spoke network where each hub-spoke pair share + // messages on a test queue. + BrokerService hub = createBroker(new URI("broker:(vm://hub)/hub?persistent=false")); - final BrokerService[] spokes = new BrokerService[4]; - for (int i = 0; i < spokes.length; i++) { - spokes[i] = createBroker(new URI("broker:(vm://spoke" + i + ")/spoke" + i + "?persistent=false")); + final BrokerService[] spokes = new BrokerService[4]; + for (int i = 0; i < spokes.length; i++) { + spokes[i] = createBroker(new URI("broker:(vm://spoke" + i + ")/spoke" + i + "?persistent=false")); - } - startAllBrokers(); + } + startAllBrokers(); - ActiveMQDestination testQueue = createDestination(AMQ4148Test.class.getSimpleName() + ".queue", false); + ActiveMQDestination testQueue = createDestination(AMQ4148Test.class.getSimpleName() + ".queue", false); - NetworkConnector[] ncs = new NetworkConnector[spokes.length]; - for (int i = 0; i < spokes.length; i++) { - NetworkConnector nc = bridgeBrokers("hub", "spoke" + i); - nc.setNetworkTTL(1); - nc.setDuplex(true); - nc.setConduitSubscriptions(false); - nc.setStaticallyIncludedDestinations(Arrays.asList(testQueue)); - nc.start(); + NetworkConnector[] ncs = new NetworkConnector[spokes.length]; + for (int i = 0; i < spokes.length; i++) { + NetworkConnector nc = bridgeBrokers("hub", "spoke" + i); + nc.setNetworkTTL(1); + nc.setDuplex(true); + nc.setConduitSubscriptions(false); + nc.setStaticallyIncludedDestinations(Arrays.asList(testQueue)); + nc.start(); - ncs[i] = nc; - } + ncs[i] = nc; + } - waitForBridgeFormation(); + waitForBridgeFormation(); - // Pause to allow subscriptions to be created. - TimeUnit.SECONDS.sleep(5); + // Pause to allow subscriptions to be created. + TimeUnit.SECONDS.sleep(5); - // Verify that the hub has a subscription from each spoke, but that each - // spoke has a single subscription from the hub (since the network TTL is 1). - final Destination hubTestQueue = hub.getDestination(testQueue); - assertTrue("Expecting {" + spokes.length + "} consumer but was {" + hubTestQueue.getConsumers().size() + "}", - Wait.waitFor(new Wait.Condition() { + // Verify that the hub has a subscription from each spoke, but that each + // spoke has a single subscription from the hub (since the network TTL is 1). + final Destination hubTestQueue = hub.getDestination(testQueue); + assertTrue("Expecting {" + spokes.length + "} consumer but was {" + hubTestQueue.getConsumers().size() + "}", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return spokes.length == hubTestQueue.getConsumers().size(); - } - }) - ); + @Override + public boolean isSatisified() throws Exception { + return spokes.length == hubTestQueue.getConsumers().size(); + } + })); - // Now check each spoke has exactly one consumer on the Queue. - for (int i = 0; i < 4; i++) { - Destination spokeTestQueue = spokes[i].getDestination(testQueue); - Assert.assertEquals(1, spokeTestQueue.getConsumers().size()); - } + // Now check each spoke has exactly one consumer on the Queue. + for (int i = 0; i < 4; i++) { + Destination spokeTestQueue = spokes[i].getDestination(testQueue); + Assert.assertEquals(1, spokeTestQueue.getConsumers().size()); + } - for (NetworkConnector nc : ncs) { - nc.stop(); - } - } + for (NetworkConnector nc : ncs) { + nc.stop(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4157Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4157Test.java index d29ec08234..d9caf7f6e5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4157Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4157Test.java @@ -44,132 +44,135 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - public class AMQ4157Test { - static final Logger LOG = LoggerFactory.getLogger(AMQ4157Test.class); - private BrokerService broker; - private ActiveMQConnectionFactory connectionFactory; - private final Destination destination = new ActiveMQQueue("Test"); - private final String payloadString = new String(new byte[8*1024]); - private final boolean useBytesMessage= true; - private final int parallelProducer = 20; - private final int parallelConsumer = 100; - private final Vector exceptions = new Vector(); - long toSend = 1000; + static final Logger LOG = LoggerFactory.getLogger(AMQ4157Test.class); + private BrokerService broker; + private ActiveMQConnectionFactory connectionFactory; + private final Destination destination = new ActiveMQQueue("Test"); + private final String payloadString = new String(new byte[8 * 1024]); + private final boolean useBytesMessage = true; + private final int parallelProducer = 20; + private final int parallelConsumer = 100; - @Test - public void testPublishCountsWithRollbackConsumer() throws Exception { + private final Vector exceptions = new Vector(); + long toSend = 1000; - startBroker(true); + @Test + public void testPublishCountsWithRollbackConsumer() throws Exception { - final AtomicLong sharedCount = new AtomicLong(toSend); - ExecutorService executorService = Executors.newCachedThreadPool(); + startBroker(true); - for (int i=0; i< parallelConsumer; i++) { - executorService.execute(new Runnable() { - @Override - public void run() { - try { - consumeOneAndRollback(); - } catch (Exception e) { - exceptions.add(e); - } - } - }); - } + final AtomicLong sharedCount = new AtomicLong(toSend); + ExecutorService executorService = Executors.newCachedThreadPool(); - for (int i=0; i< parallelProducer; i++) { - executorService.execute(new Runnable() { - @Override - public void run() { - try { - publishMessages(sharedCount, 0); - } catch (Exception e) { - exceptions.add(e); - } - } - }); - } - - executorService.shutdown(); - executorService.awaitTermination(30, TimeUnit.MINUTES); - assertTrue("Producers done in time", executorService.isTerminated()); - assertTrue("No exceptions: " + exceptions, exceptions.isEmpty()); - - restartBroker(500); - - LOG.info("Attempting consume of {} messages", toSend); - - consumeMessages(toSend); - } - - private void consumeOneAndRollback() throws Exception { - ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageConsumer consumer = session.createConsumer(destination); - Message message = null; - while (message == null) { - message = consumer.receive(1000); - } - session.rollback(); - connection.close(); - } - - private void consumeMessages(long count) throws Exception { - ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); - for (int i=0; i 0) { - Message message = null; - if (useBytesMessage) { - message = session.createBytesMessage(); - ((BytesMessage) message).writeBytes(payloadString.getBytes()); - } else { - message = session.createTextMessage(payloadString); + for (int i = 0; i < parallelConsumer; i++) { + executorService.execute(new Runnable() { + @Override + public void run() { + try { + consumeOneAndRollback(); + } + catch (Exception e) { + exceptions.add(e); + } } - producer.send(message, DeliveryMode.PERSISTENT, 5, expiry); - } - connection.syncSendPacket(new ConnectionControl()); - connection.close(); - } + }); + } - public void startBroker(boolean deleteAllMessages) throws Exception { - broker = new BrokerService(); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - broker.addConnector("tcp://0.0.0.0:0"); - broker.start(); + for (int i = 0; i < parallelProducer; i++) { + executorService.execute(new Runnable() { + @Override + public void run() { + try { + publishMessages(sharedCount, 0); + } + catch (Exception e) { + exceptions.add(e); + } + } + }); + } - String options = "?jms.redeliveryPolicy.maximumRedeliveries=-1&jms.prefetchPolicy.all=1000&jms.watchTopicAdvisories=false&jms.useAsyncSend=true&jms.alwaysSessionAsync=false&jms.dispatchAsync=false&socketBufferSize=131072&ioBufferSize=16384&wireFormat.tightEncodingEnabled=false&wireFormat.cacheSize=8192"; - connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri() + options); - } + executorService.shutdown(); + executorService.awaitTermination(30, TimeUnit.MINUTES); + assertTrue("Producers done in time", executorService.isTerminated()); + assertTrue("No exceptions: " + exceptions, exceptions.isEmpty()); + + restartBroker(500); + + LOG.info("Attempting consume of {} messages", toSend); + + consumeMessages(toSend); + } + + private void consumeOneAndRollback() throws Exception { + ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.start(); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageConsumer consumer = session.createConsumer(destination); + Message message = null; + while (message == null) { + message = consumer.receive(1000); + } + session.rollback(); + connection.close(); + } + + private void consumeMessages(long count) throws Exception { + ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(destination); + for (int i = 0; i < count; i++) { + assertNotNull("got message " + i, consumer.receive(20000)); + } + assertNull("none left over", consumer.receive(2000)); + } + + private void restartBroker(int restartDelay) throws Exception { + stopBroker(); + TimeUnit.MILLISECONDS.sleep(restartDelay); + startBroker(false); + } + + @After + public void stopBroker() throws Exception { + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + } + + private void publishMessages(AtomicLong count, int expiry) throws Exception { + ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.setWatchTopicAdvisories(false); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + MessageProducer producer = session.createProducer(destination); + while ((count.getAndDecrement()) > 0) { + Message message = null; + if (useBytesMessage) { + message = session.createBytesMessage(); + ((BytesMessage) message).writeBytes(payloadString.getBytes()); + } + else { + message = session.createTextMessage(payloadString); + } + producer.send(message, DeliveryMode.PERSISTENT, 5, expiry); + } + connection.syncSendPacket(new ConnectionControl()); + connection.close(); + } + + public void startBroker(boolean deleteAllMessages) throws Exception { + broker = new BrokerService(); + broker.setDeleteAllMessagesOnStartup(deleteAllMessages); + broker.addConnector("tcp://0.0.0.0:0"); + broker.start(); + + String options = "?jms.redeliveryPolicy.maximumRedeliveries=-1&jms.prefetchPolicy.all=1000&jms.watchTopicAdvisories=false&jms.useAsyncSend=true&jms.alwaysSessionAsync=false&jms.dispatchAsync=false&socketBufferSize=131072&ioBufferSize=16384&wireFormat.tightEncodingEnabled=false&wireFormat.cacheSize=8192"; + connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri() + options); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4160Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4160Test.java index 4867f28c6e..b32c76a60d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4160Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4160Test.java @@ -50,344 +50,329 @@ import org.junit.Assert; * being reported as active. */ public class AMQ4160Test extends JmsMultipleBrokersTestSupport { - final long MAX_TEST_TIME = TimeUnit.MINUTES.toMillis(2); - /** - * Since these tests involve wait conditions, protect against indefinite - * waits (due to unanticipated issues). - */ - public void setUp() throws Exception { - setAutoFail(true); - setMaxTestTime(MAX_TEST_TIME); - super.setUp(); - } + final long MAX_TEST_TIME = TimeUnit.MINUTES.toMillis(2); - /** - * This test demonstrates how concurrent attempts to establish a bridge to - * the same remote broker are allowed to occur. Connection uniqueness will - * cause whichever bridge creation attempt is second to fail. However, this - * failure erases the entry in - * {@link DiscoveryNetworkConnector#activeBridges()} that represents the - * successful first bridge creation attempt. - */ - public void testLostActiveBridge() throws Exception { - final long ATTEMPT_TO_CREATE_DELAY = TimeUnit.SECONDS.toMillis(15); + /** + * Since these tests involve wait conditions, protect against indefinite + * waits (due to unanticipated issues). + */ + public void setUp() throws Exception { + setAutoFail(true); + setMaxTestTime(MAX_TEST_TIME); + super.setUp(); + } - // Start two brokers with a bridge from broker1 to broker2. - BrokerService broker1 = createBroker(new URI( - "broker:(vm://broker1)/broker1?persistent=false")); - final BrokerService broker2 = createBroker(new URI( - "broker:(vm://broker2)/broker2?persistent=false")); + /** + * This test demonstrates how concurrent attempts to establish a bridge to + * the same remote broker are allowed to occur. Connection uniqueness will + * cause whichever bridge creation attempt is second to fail. However, this + * failure erases the entry in + * {@link DiscoveryNetworkConnector#activeBridges()} that represents the + * successful first bridge creation attempt. + */ + public void testLostActiveBridge() throws Exception { + final long ATTEMPT_TO_CREATE_DELAY = TimeUnit.SECONDS.toMillis(15); - // Allow the concurrent local bridge connections to be made even though - // they are duplicated; this prevents both of the bridge attempts from - // failing in the case that the local and remote bridges are established - // out-of-order. - BrokerPlugin ignoreAddConnectionPlugin = new BrokerPlugin() { - @Override - public Broker installPlugin(Broker broker) throws Exception { - return new BrokerFilter(broker) { - @Override - public void addConnection(ConnectionContext context, - ConnectionInfo info) throws Exception { - // ignore - } - }; + // Start two brokers with a bridge from broker1 to broker2. + BrokerService broker1 = createBroker(new URI("broker:(vm://broker1)/broker1?persistent=false")); + final BrokerService broker2 = createBroker(new URI("broker:(vm://broker2)/broker2?persistent=false")); + + // Allow the concurrent local bridge connections to be made even though + // they are duplicated; this prevents both of the bridge attempts from + // failing in the case that the local and remote bridges are established + // out-of-order. + BrokerPlugin ignoreAddConnectionPlugin = new BrokerPlugin() { + @Override + public Broker installPlugin(Broker broker) throws Exception { + return new BrokerFilter(broker) { + @Override + public void addConnection(ConnectionContext context, ConnectionInfo info) throws Exception { + // ignore + } + }; + } + }; + + broker1.setPlugins(new BrokerPlugin[]{ignoreAddConnectionPlugin}); + + startAllBrokers(); + + // Start a bridge from broker1 to broker2. The discovery agent attempts + // to create the bridge concurrently with two threads, and the + // synchronization in createBridge ensures that pre-patch both threads + // actually attempt to start bridges. Post-patch, only one thread is + // allowed to start the bridge. + final CountDownLatch attemptLatch = new CountDownLatch(2); + final CountDownLatch createLatch = new CountDownLatch(2); + + DiscoveryNetworkConnector nc = new DiscoveryNetworkConnector() { + @Override + public void onServiceAdd(DiscoveryEvent event) { + // Pre-and-post patch, two threads attempt to establish a bridge + // to the same remote broker. + attemptLatch.countDown(); + super.onServiceAdd(event); + } + + @Override + protected NetworkBridge createBridge(Transport localTransport, + Transport remoteTransport, + final DiscoveryEvent event) { + // Pre-patch, the two threads are allowed to create the bridge. + // Post-patch, only the first thread is allowed. Wait a + // reasonable delay once both attempts are detected to allow + // the two bridge creations to occur concurrently (pre-patch). + // Post-patch, the wait will timeout and allow the first (and + // only) bridge creation to occur. + try { + attemptLatch.await(); + createLatch.countDown(); + createLatch.await(ATTEMPT_TO_CREATE_DELAY, TimeUnit.MILLISECONDS); + return super.createBridge(localTransport, remoteTransport, event); } - }; - - broker1.setPlugins(new BrokerPlugin[] { ignoreAddConnectionPlugin }); - - startAllBrokers(); - - // Start a bridge from broker1 to broker2. The discovery agent attempts - // to create the bridge concurrently with two threads, and the - // synchronization in createBridge ensures that pre-patch both threads - // actually attempt to start bridges. Post-patch, only one thread is - // allowed to start the bridge. - final CountDownLatch attemptLatch = new CountDownLatch(2); - final CountDownLatch createLatch = new CountDownLatch(2); - - DiscoveryNetworkConnector nc = new DiscoveryNetworkConnector() { - @Override - public void onServiceAdd(DiscoveryEvent event) { - // Pre-and-post patch, two threads attempt to establish a bridge - // to the same remote broker. - attemptLatch.countDown(); - super.onServiceAdd(event); + catch (InterruptedException e) { + Thread.interrupted(); + return null; } + } + }; - @Override - protected NetworkBridge createBridge(Transport localTransport, - Transport remoteTransport, final DiscoveryEvent event) { - // Pre-patch, the two threads are allowed to create the bridge. - // Post-patch, only the first thread is allowed. Wait a - // reasonable delay once both attempts are detected to allow - // the two bridge creations to occur concurrently (pre-patch). - // Post-patch, the wait will timeout and allow the first (and - // only) bridge creation to occur. - try { - attemptLatch.await(); - createLatch.countDown(); - createLatch.await(ATTEMPT_TO_CREATE_DELAY, - TimeUnit.MILLISECONDS); - return super.createBridge(localTransport, remoteTransport, - event); - } catch (InterruptedException e) { - Thread.interrupted(); - return null; - } - } - }; + nc.setDiscoveryAgent(new DiscoveryAgent() { + TaskRunnerFactory taskRunner = new TaskRunnerFactory(); + DiscoveryListener listener; - nc.setDiscoveryAgent(new DiscoveryAgent() { - TaskRunnerFactory taskRunner = new TaskRunnerFactory(); - DiscoveryListener listener; + @Override + public void start() throws Exception { + taskRunner.init(); + taskRunner.execute(new Runnable() { + @Override + public void run() { + listener.onServiceAdd(new DiscoveryEvent(broker2.getVmConnectorURI().toString())); + } + }); + taskRunner.execute(new Runnable() { + @Override + public void run() { + listener.onServiceAdd(new DiscoveryEvent(broker2.getVmConnectorURI().toString())); + } + }); + } - @Override - public void start() throws Exception { - taskRunner.init(); - taskRunner.execute(new Runnable() { - @Override - public void run() { - listener.onServiceAdd(new DiscoveryEvent(broker2 - .getVmConnectorURI().toString())); - } - }); - taskRunner.execute(new Runnable() { - @Override - public void run() { - listener.onServiceAdd(new DiscoveryEvent(broker2 - .getVmConnectorURI().toString())); - } - }); - } + @Override + public void stop() throws Exception { + taskRunner.shutdown(); + } - @Override - public void stop() throws Exception { - taskRunner.shutdown(); - } + @Override + public void setDiscoveryListener(DiscoveryListener listener) { + this.listener = listener; + } - @Override - public void setDiscoveryListener(DiscoveryListener listener) { - this.listener = listener; - } + @Override + public void registerService(String name) throws IOException { + } - @Override - public void registerService(String name) throws IOException { - } + @Override + public void serviceFailed(DiscoveryEvent event) throws IOException { + listener.onServiceRemove(event); + } + }); - @Override - public void serviceFailed(DiscoveryEvent event) throws IOException { - listener.onServiceRemove(event); - } - }); + broker1.addNetworkConnector(nc); + nc.start(); - broker1.addNetworkConnector(nc); - nc.start(); + // Wait for the bridge to be formed by the first attempt. + waitForBridge(broker1.getBrokerName(), broker2.getBrokerName(), MAX_TEST_TIME, TimeUnit.MILLISECONDS); - // Wait for the bridge to be formed by the first attempt. - waitForBridge(broker1.getBrokerName(), broker2.getBrokerName(), - MAX_TEST_TIME, TimeUnit.MILLISECONDS); + // Pre-patch, the second bridge creation attempt fails and removes the + // first (successful) bridge creation attempt from the + // list of active bridges. Post-patch, the second bridge creation + // attempt is prevented, so the first bridge creation attempt + // remains "active". This assertion is expected to fail pre-patch and + // pass post-patch. + Assert.assertFalse(nc.activeBridges().isEmpty()); + } - // Pre-patch, the second bridge creation attempt fails and removes the - // first (successful) bridge creation attempt from the - // list of active bridges. Post-patch, the second bridge creation - // attempt is prevented, so the first bridge creation attempt - // remains "active". This assertion is expected to fail pre-patch and - // pass post-patch. - Assert.assertFalse(nc.activeBridges().isEmpty()); - } + /** + * This test demonstrates a race condition where a failed bridge can be + * removed from the list of active bridges in + * {@link DiscoveryNetworkConnector} before it has been added. Eventually, + * the failed bridge is added, but never removed, which causes subsequent + * bridge creation attempts to be ignored. The result is a network connector + * that thinks it has an active bridge, when in fact it doesn't. + */ + public void testInactiveBridgStillActive() throws Exception { + // Start two brokers with a bridge from broker1 to broker2. + BrokerService broker1 = createBroker(new URI("broker:(vm://broker1)/broker1?persistent=false")); + final BrokerService broker2 = createBroker(new URI("broker:(vm://broker2)/broker2?persistent=false")); - /** - * This test demonstrates a race condition where a failed bridge can be - * removed from the list of active bridges in - * {@link DiscoveryNetworkConnector} before it has been added. Eventually, - * the failed bridge is added, but never removed, which causes subsequent - * bridge creation attempts to be ignored. The result is a network connector - * that thinks it has an active bridge, when in fact it doesn't. - */ - public void testInactiveBridgStillActive() throws Exception { - // Start two brokers with a bridge from broker1 to broker2. - BrokerService broker1 = createBroker(new URI( - "broker:(vm://broker1)/broker1?persistent=false")); - final BrokerService broker2 = createBroker(new URI( - "broker:(vm://broker2)/broker2?persistent=false")); + // Force bridge failure by having broker1 disallow connections. + BrokerPlugin disallowAddConnectionPlugin = new BrokerPlugin() { + @Override + public Broker installPlugin(Broker broker) throws Exception { + return new BrokerFilter(broker) { + @Override + public void addConnection(ConnectionContext context, ConnectionInfo info) throws Exception { + throw new Exception("Test exception to force bridge failure"); + } + }; + } + }; - // Force bridge failure by having broker1 disallow connections. - BrokerPlugin disallowAddConnectionPlugin = new BrokerPlugin() { - @Override - public Broker installPlugin(Broker broker) throws Exception { - return new BrokerFilter(broker) { - @Override - public void addConnection(ConnectionContext context, - ConnectionInfo info) throws Exception { - throw new Exception( - "Test exception to force bridge failure"); - } - }; - } - }; + broker1.setPlugins(new BrokerPlugin[]{disallowAddConnectionPlugin}); - broker1.setPlugins(new BrokerPlugin[] { disallowAddConnectionPlugin }); + startAllBrokers(); - startAllBrokers(); + // Start a bridge from broker1 to broker2. The bridge delays returning + // from start until after the bridge failure has been processed; + // this leaves the first bridge creation attempt recorded as active, + // even though it failed. + final SimpleDiscoveryAgent da = new SimpleDiscoveryAgent(); + da.setServices(new URI[]{broker2.getVmConnectorURI()}); - // Start a bridge from broker1 to broker2. The bridge delays returning - // from start until after the bridge failure has been processed; - // this leaves the first bridge creation attempt recorded as active, - // even though it failed. - final SimpleDiscoveryAgent da = new SimpleDiscoveryAgent(); - da.setServices(new URI[] { broker2.getVmConnectorURI() }); + final CountDownLatch attemptLatch = new CountDownLatch(3); + final CountDownLatch removedLatch = new CountDownLatch(1); - final CountDownLatch attemptLatch = new CountDownLatch(3); - final CountDownLatch removedLatch = new CountDownLatch(1); + DiscoveryNetworkConnector nc = new DiscoveryNetworkConnector() { + @Override + public void onServiceAdd(DiscoveryEvent event) { + attemptLatch.countDown(); + super.onServiceAdd(event); + } - DiscoveryNetworkConnector nc = new DiscoveryNetworkConnector() { - @Override - public void onServiceAdd(DiscoveryEvent event) { - attemptLatch.countDown(); - super.onServiceAdd(event); - } + @Override + public void onServiceRemove(DiscoveryEvent event) { + super.onServiceRemove(event); + removedLatch.countDown(); + } - @Override - public void onServiceRemove(DiscoveryEvent event) { - super.onServiceRemove(event); - removedLatch.countDown(); - } + @Override + protected NetworkBridge createBridge(Transport localTransport, + Transport remoteTransport, + final DiscoveryEvent event) { + final NetworkBridge next = super.createBridge(localTransport, remoteTransport, event); + return new NetworkBridge() { - @Override - protected NetworkBridge createBridge(Transport localTransport, - Transport remoteTransport, final DiscoveryEvent event) { - final NetworkBridge next = super.createBridge(localTransport, - remoteTransport, event); - return new NetworkBridge() { + @Override + public void start() throws Exception { + next.start(); + // Delay returning until the failed service has been + // removed. + removedLatch.await(); + } - @Override - public void start() throws Exception { - next.start(); - // Delay returning until the failed service has been - // removed. - removedLatch.await(); - } + @Override + public void stop() throws Exception { + next.stop(); + } - @Override - public void stop() throws Exception { - next.stop(); - } + @Override + public void serviceRemoteException(Throwable error) { + next.serviceRemoteException(error); + } - @Override - public void serviceRemoteException(Throwable error) { - next.serviceRemoteException(error); - } + @Override + public void serviceLocalException(Throwable error) { + next.serviceLocalException(error); + } - @Override - public void serviceLocalException(Throwable error) { - next.serviceLocalException(error); - } + @Override + public void setNetworkBridgeListener(NetworkBridgeListener listener) { + next.setNetworkBridgeListener(listener); + } - @Override - public void setNetworkBridgeListener( - NetworkBridgeListener listener) { - next.setNetworkBridgeListener(listener); - } + @Override + public String getRemoteAddress() { + return next.getRemoteAddress(); + } - @Override - public String getRemoteAddress() { - return next.getRemoteAddress(); - } + @Override + public String getRemoteBrokerName() { + return next.getRemoteBrokerName(); + } - @Override - public String getRemoteBrokerName() { - return next.getRemoteBrokerName(); - } + @Override + public String getRemoteBrokerId() { + return next.getRemoteBrokerId(); + } - @Override - public String getRemoteBrokerId() { - return next.getRemoteBrokerId(); - } + @Override + public String getLocalAddress() { + return next.getLocalAddress(); + } - @Override - public String getLocalAddress() { - return next.getLocalAddress(); - } + @Override + public String getLocalBrokerName() { + return next.getLocalBrokerName(); + } - @Override - public String getLocalBrokerName() { - return next.getLocalBrokerName(); - } + @Override + public long getEnqueueCounter() { + return next.getEnqueueCounter(); + } - @Override - public long getEnqueueCounter() { - return next.getEnqueueCounter(); - } + @Override + public long getDequeueCounter() { + return next.getDequeueCounter(); + } - @Override - public long getDequeueCounter() { - return next.getDequeueCounter(); - } + @Override + public void setMbeanObjectName(ObjectName objectName) { + next.setMbeanObjectName(objectName); + } - @Override - public void setMbeanObjectName(ObjectName objectName) { - next.setMbeanObjectName(objectName); - } + @Override + public ObjectName getMbeanObjectName() { + return next.getMbeanObjectName(); + } - @Override - public ObjectName getMbeanObjectName() { - return next.getMbeanObjectName(); - } + public void resetStats() { + next.resetStats(); + } + }; + } + }; + nc.setDiscoveryAgent(da); - public void resetStats(){ - next.resetStats(); - } - }; - } - }; - nc.setDiscoveryAgent(da); + broker1.addNetworkConnector(nc); + nc.start(); - broker1.addNetworkConnector(nc); - nc.start(); + // All bridge attempts should fail, so the attempt latch should get + // triggered. However, because of the race condition, the first attempt + // is considered successful and causes further attempts to stop. + // Therefore, this wait will time out and cause the test to fail. + Assert.assertTrue(attemptLatch.await(30, TimeUnit.SECONDS)); + } - // All bridge attempts should fail, so the attempt latch should get - // triggered. However, because of the race condition, the first attempt - // is considered successful and causes further attempts to stop. - // Therefore, this wait will time out and cause the test to fail. - Assert.assertTrue(attemptLatch.await(30, TimeUnit.SECONDS)); - } + /** + * This test verifies that when a network connector is restarted, any + * bridges that were active at the time of the stop are allowed to be + * re-established (i.e., the "active events" data structure in + * {@link DiscoveryNetworkConnector} is reset. + */ + public void testAllowAttemptsAfterRestart() throws Exception { + final long STOP_DELAY = TimeUnit.SECONDS.toMillis(10); - /** - * This test verifies that when a network connector is restarted, any - * bridges that were active at the time of the stop are allowed to be - * re-established (i.e., the "active events" data structure in - * {@link DiscoveryNetworkConnector} is reset. - */ - public void testAllowAttemptsAfterRestart() throws Exception { - final long STOP_DELAY = TimeUnit.SECONDS.toMillis(10); + // Start two brokers with a bridge from broker1 to broker2. + BrokerService broker1 = createBroker(new URI("broker:(vm://broker1)/broker1?persistent=false")); + final BrokerService broker2 = createBroker(new URI("broker:(vm://broker2)/broker2?persistent=false")); - // Start two brokers with a bridge from broker1 to broker2. - BrokerService broker1 = createBroker(new URI( - "broker:(vm://broker1)/broker1?persistent=false")); - final BrokerService broker2 = createBroker(new URI( - "broker:(vm://broker2)/broker2?persistent=false")); + startAllBrokers(); - startAllBrokers(); + // Start a bridge from broker1 to broker2. + NetworkConnector nc = bridgeBrokers(broker1.getBrokerName(), broker2.getBrokerName()); + nc.start(); - // Start a bridge from broker1 to broker2. - NetworkConnector nc = bridgeBrokers(broker1.getBrokerName(), - broker2.getBrokerName()); - nc.start(); + waitForBridge(broker1.getBrokerName(), broker2.getBrokerName(), MAX_TEST_TIME, TimeUnit.MILLISECONDS); - waitForBridge(broker1.getBrokerName(), broker2.getBrokerName(), - MAX_TEST_TIME, TimeUnit.MILLISECONDS); + // Restart the network connector and verify that the bridge is + // re-established. The pause between start/stop is to account for the + // asynchronous closure. + nc.stop(); + Thread.sleep(STOP_DELAY); + nc.start(); - // Restart the network connector and verify that the bridge is - // re-established. The pause between start/stop is to account for the - // asynchronous closure. - nc.stop(); - Thread.sleep(STOP_DELAY); - nc.start(); - - waitForBridge(broker1.getBrokerName(), broker2.getBrokerName(), - MAX_TEST_TIME, TimeUnit.MILLISECONDS); - } + waitForBridge(broker1.getBrokerName(), broker2.getBrokerName(), MAX_TEST_TIME, TimeUnit.MILLISECONDS); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4212Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4212Test.java index 141a8810f0..3504c1fe9b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4212Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4212Test.java @@ -50,309 +50,308 @@ import org.slf4j.LoggerFactory; public class AMQ4212Test { - private static final Logger LOG = LoggerFactory.getLogger(AMQ4212Test.class); + private static final Logger LOG = LoggerFactory.getLogger(AMQ4212Test.class); - private BrokerService service; - private String connectionUri; - private ActiveMQConnectionFactory cf; + private BrokerService service; + private String connectionUri; + private ActiveMQConnectionFactory cf; - private final int MSG_COUNT = 256; + private final int MSG_COUNT = 256; - @Before - public void setUp() throws IOException, Exception { - createBroker(true, false); - } + @Before + public void setUp() throws IOException, Exception { + createBroker(true, false); + } - public void createBroker(boolean deleteAllMessages, boolean recover) throws Exception { - service = new BrokerService(); - service.setBrokerName("InactiveSubTest"); - service.setDeleteAllMessagesOnStartup(deleteAllMessages); - service.setAdvisorySupport(false); - service.setPersistent(true); - service.setUseJmx(true); - service.setKeepDurableSubsActive(false); + public void createBroker(boolean deleteAllMessages, boolean recover) throws Exception { + service = new BrokerService(); + service.setBrokerName("InactiveSubTest"); + service.setDeleteAllMessagesOnStartup(deleteAllMessages); + service.setAdvisorySupport(false); + service.setPersistent(true); + service.setUseJmx(true); + service.setKeepDurableSubsActive(false); - KahaDBPersistenceAdapter pa=new KahaDBPersistenceAdapter(); - File dataFile=new File("KahaDB"); - pa.setDirectory(dataFile); - pa.setJournalMaxFileLength(10*1024); - pa.setCheckpointInterval(TimeUnit.SECONDS.toMillis(5)); - pa.setCleanupInterval(TimeUnit.SECONDS.toMillis(5)); - pa.setForceRecoverIndex(recover); + KahaDBPersistenceAdapter pa = new KahaDBPersistenceAdapter(); + File dataFile = new File("KahaDB"); + pa.setDirectory(dataFile); + pa.setJournalMaxFileLength(10 * 1024); + pa.setCheckpointInterval(TimeUnit.SECONDS.toMillis(5)); + pa.setCleanupInterval(TimeUnit.SECONDS.toMillis(5)); + pa.setForceRecoverIndex(recover); - service.setPersistenceAdapter(pa); - service.start(); - service.waitUntilStarted(); + service.setPersistenceAdapter(pa); + service.start(); + service.waitUntilStarted(); - connectionUri = "vm://InactiveSubTest?create=false"; - cf = new ActiveMQConnectionFactory(connectionUri); - } + connectionUri = "vm://InactiveSubTest?create=false"; + cf = new ActiveMQConnectionFactory(connectionUri); + } - private void restartBroker() throws Exception { - stopBroker(); - createBroker(false, false); - } + private void restartBroker() throws Exception { + stopBroker(); + createBroker(false, false); + } - private void recoverBroker() throws Exception { - stopBroker(); - createBroker(false, true); - } + private void recoverBroker() throws Exception { + stopBroker(); + createBroker(false, true); + } - @After - public void stopBroker() throws Exception { - if (service != null) { - service.stop(); - service.waitUntilStopped(); - service = null; - } - } + @After + public void stopBroker() throws Exception { + if (service != null) { + service.stop(); + service.waitUntilStopped(); + service = null; + } + } - @Test - public void testDirableSubPrefetchRecovered() throws Exception { + @Test + public void testDirableSubPrefetchRecovered() throws Exception { - ActiveMQQueue queue = new ActiveMQQueue("MyQueue"); - ActiveMQTopic topic = new ActiveMQTopic("MyDurableTopic"); + ActiveMQQueue queue = new ActiveMQQueue("MyQueue"); + ActiveMQTopic topic = new ActiveMQTopic("MyDurableTopic"); - // Send to a Queue to create some journal files - sendMessages(queue); + // Send to a Queue to create some journal files + sendMessages(queue); - LOG.info("There are currently [{}] journal log files.", getNumberOfJournalFiles()); + LOG.info("There are currently [{}] journal log files.", getNumberOfJournalFiles()); - createInactiveDurableSub(topic); + createInactiveDurableSub(topic); - assertTrue("Should have an inactive durable sub", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - ObjectName[] subs = service.getAdminView().getInactiveDurableTopicSubscribers(); - return subs != null && subs.length == 1 ? true : false; - } - })); + assertTrue("Should have an inactive durable sub", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + ObjectName[] subs = service.getAdminView().getInactiveDurableTopicSubscribers(); + return subs != null && subs.length == 1 ? true : false; + } + })); - // Now send some more to the queue to create even more files. - sendMessages(queue); + // Now send some more to the queue to create even more files. + sendMessages(queue); - LOG.info("There are currently [{}] journal log files.", getNumberOfJournalFiles()); - assertTrue(getNumberOfJournalFiles() > 1); + LOG.info("There are currently [{}] journal log files.", getNumberOfJournalFiles()); + assertTrue(getNumberOfJournalFiles() > 1); - LOG.info("Restarting the broker."); - restartBroker(); - LOG.info("Restarted the broker."); + LOG.info("Restarting the broker."); + restartBroker(); + LOG.info("Restarted the broker."); - LOG.info("There are currently [{}] journal log files.", getNumberOfJournalFiles()); - assertTrue(getNumberOfJournalFiles() > 1); + LOG.info("There are currently [{}] journal log files.", getNumberOfJournalFiles()); + assertTrue(getNumberOfJournalFiles() > 1); - assertTrue("Should have an inactive durable sub", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - ObjectName[] subs = service.getAdminView().getInactiveDurableTopicSubscribers(); - return subs != null && subs.length == 1 ? true : false; - } - })); + assertTrue("Should have an inactive durable sub", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + ObjectName[] subs = service.getAdminView().getInactiveDurableTopicSubscribers(); + return subs != null && subs.length == 1 ? true : false; + } + })); - // Clear out all queue data - service.getAdminView().removeQueue(queue.getQueueName()); + // Clear out all queue data + service.getAdminView().removeQueue(queue.getQueueName()); - assertTrue("Less than two journal files expected, was " + getNumberOfJournalFiles(), Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return getNumberOfJournalFiles() <= 2; - } - }, TimeUnit.MINUTES.toMillis(2))); + assertTrue("Less than two journal files expected, was " + getNumberOfJournalFiles(), Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return getNumberOfJournalFiles() <= 2; + } + }, TimeUnit.MINUTES.toMillis(2))); - LOG.info("Sending {} Messages to the Topic.", MSG_COUNT); - // Send some messages to the inactive destination - sendMessages(topic); + LOG.info("Sending {} Messages to the Topic.", MSG_COUNT); + // Send some messages to the inactive destination + sendMessages(topic); - LOG.info("Attempt to consume {} messages from the Topic.", MSG_COUNT); - assertEquals(MSG_COUNT, consumeFromInactiveDurableSub(topic)); + LOG.info("Attempt to consume {} messages from the Topic.", MSG_COUNT); + assertEquals(MSG_COUNT, consumeFromInactiveDurableSub(topic)); - LOG.info("Recovering the broker."); - recoverBroker(); - LOG.info("Recovering the broker."); + LOG.info("Recovering the broker."); + recoverBroker(); + LOG.info("Recovering the broker."); - assertTrue("Should have an inactive durable sub", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - ObjectName[] subs = service.getAdminView().getInactiveDurableTopicSubscribers(); - return subs != null && subs.length == 1 ? true : false; - } - })); - } + assertTrue("Should have an inactive durable sub", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + ObjectName[] subs = service.getAdminView().getInactiveDurableTopicSubscribers(); + return subs != null && subs.length == 1 ? true : false; + } + })); + } - @Test - public void testDurableAcksNotDropped() throws Exception { + @Test + public void testDurableAcksNotDropped() throws Exception { - ActiveMQQueue queue = new ActiveMQQueue("MyQueue"); - ActiveMQTopic topic = new ActiveMQTopic("MyDurableTopic"); + ActiveMQQueue queue = new ActiveMQQueue("MyQueue"); + ActiveMQTopic topic = new ActiveMQTopic("MyDurableTopic"); - // Create durable sub in first data file. - createInactiveDurableSub(topic); + // Create durable sub in first data file. + createInactiveDurableSub(topic); - assertTrue("Should have an inactive durable sub", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - ObjectName[] subs = service.getAdminView().getInactiveDurableTopicSubscribers(); - return subs != null && subs.length == 1 ? true : false; - } - })); + assertTrue("Should have an inactive durable sub", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + ObjectName[] subs = service.getAdminView().getInactiveDurableTopicSubscribers(); + return subs != null && subs.length == 1 ? true : false; + } + })); - // Send to a Topic - sendMessages(topic, 1); + // Send to a Topic + sendMessages(topic, 1); - // Send to a Queue to create some journal files - sendMessages(queue); + // Send to a Queue to create some journal files + sendMessages(queue); - LOG.info("Before consume there are currently [{}] journal log files.", getNumberOfJournalFiles()); + LOG.info("Before consume there are currently [{}] journal log files.", getNumberOfJournalFiles()); - // Consume all the Messages leaving acks behind. - consumeDurableMessages(topic, 1); + // Consume all the Messages leaving acks behind. + consumeDurableMessages(topic, 1); - LOG.info("After consume there are currently [{}] journal log files.", getNumberOfJournalFiles()); + LOG.info("After consume there are currently [{}] journal log files.", getNumberOfJournalFiles()); - // Now send some more to the queue to create even more files. - sendMessages(queue); + // Now send some more to the queue to create even more files. + sendMessages(queue); - LOG.info("More Queued. There are currently [{}] journal log files.", getNumberOfJournalFiles()); - assertTrue(getNumberOfJournalFiles() > 1); + LOG.info("More Queued. There are currently [{}] journal log files.", getNumberOfJournalFiles()); + assertTrue(getNumberOfJournalFiles() > 1); - LOG.info("Restarting the broker."); - restartBroker(); - LOG.info("Restarted the broker."); + LOG.info("Restarting the broker."); + restartBroker(); + LOG.info("Restarted the broker."); - LOG.info("There are currently [{}] journal log files.", getNumberOfJournalFiles()); - assertTrue(getNumberOfJournalFiles() > 1); + LOG.info("There are currently [{}] journal log files.", getNumberOfJournalFiles()); + assertTrue(getNumberOfJournalFiles() > 1); - assertTrue("Should have an inactive durable sub", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - ObjectName[] subs = service.getAdminView().getInactiveDurableTopicSubscribers(); - return subs != null && subs.length == 1 ? true : false; - } - })); + assertTrue("Should have an inactive durable sub", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + ObjectName[] subs = service.getAdminView().getInactiveDurableTopicSubscribers(); + return subs != null && subs.length == 1 ? true : false; + } + })); - // Clear out all queue data - service.getAdminView().removeQueue(queue.getQueueName()); + // Clear out all queue data + service.getAdminView().removeQueue(queue.getQueueName()); - assertTrue("Less than three journal file expected, was " + getNumberOfJournalFiles(), Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return getNumberOfJournalFiles() <= 3; - } - }, TimeUnit.MINUTES.toMillis(3))); + assertTrue("Less than three journal file expected, was " + getNumberOfJournalFiles(), Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return getNumberOfJournalFiles() <= 3; + } + }, TimeUnit.MINUTES.toMillis(3))); - // See if we receive any message they should all be acked. - tryConsumeExpectNone(topic); + // See if we receive any message they should all be acked. + tryConsumeExpectNone(topic); - LOG.info("There are currently [{}] journal log files.", getNumberOfJournalFiles()); + LOG.info("There are currently [{}] journal log files.", getNumberOfJournalFiles()); - LOG.info("Recovering the broker."); - recoverBroker(); - LOG.info("Recovering the broker."); + LOG.info("Recovering the broker."); + recoverBroker(); + LOG.info("Recovering the broker."); - LOG.info("There are currently [{}] journal log files.", getNumberOfJournalFiles()); + LOG.info("There are currently [{}] journal log files.", getNumberOfJournalFiles()); - assertTrue("Should have an inactive durable sub", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - ObjectName[] subs = service.getAdminView().getInactiveDurableTopicSubscribers(); - return subs != null && subs.length == 1 ? true : false; - } - })); + assertTrue("Should have an inactive durable sub", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + ObjectName[] subs = service.getAdminView().getInactiveDurableTopicSubscribers(); + return subs != null && subs.length == 1 ? true : false; + } + })); - // See if we receive any message they should all be acked. - tryConsumeExpectNone(topic); + // See if we receive any message they should all be acked. + tryConsumeExpectNone(topic); - assertTrue("Less than three journal file expected, was " + getNumberOfJournalFiles(), Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return getNumberOfJournalFiles() == 1; - } - }, TimeUnit.MINUTES.toMillis(1))); - } + assertTrue("Less than three journal file expected, was " + getNumberOfJournalFiles(), Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return getNumberOfJournalFiles() == 1; + } + }, TimeUnit.MINUTES.toMillis(1))); + } - private int getNumberOfJournalFiles() throws IOException { - Collection files = - ((KahaDBPersistenceAdapter) service.getPersistenceAdapter()).getStore().getJournal().getFileMap().values(); - int reality = 0; - for (DataFile file : files) { - if (file != null) { - reality++; - } - } + private int getNumberOfJournalFiles() throws IOException { + Collection files = ((KahaDBPersistenceAdapter) service.getPersistenceAdapter()).getStore().getJournal().getFileMap().values(); + int reality = 0; + for (DataFile file : files) { + if (file != null) { + reality++; + } + } - return reality; - } + return reality; + } - private void createInactiveDurableSub(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"); - consumer.close(); - connection.close(); - } + private void createInactiveDurableSub(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"); + consumer.close(); + connection.close(); + } - private void consumeDurableMessages(Topic topic, int count) 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(); - for (int i = 0; i < count; ++i) { - if (consumer.receive(TimeUnit.SECONDS.toMillis(10)) == null) { - fail("should have received a message"); - } - } - consumer.close(); - connection.close(); - } + private void consumeDurableMessages(Topic topic, int count) 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(); + for (int i = 0; i < count; ++i) { + if (consumer.receive(TimeUnit.SECONDS.toMillis(10)) == null) { + fail("should have received a message"); + } + } + consumer.close(); + connection.close(); + } - 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(); - if (consumer.receive(TimeUnit.SECONDS.toMillis(10)) != null) { - fail("Should be no messages for this durable."); - } - consumer.close(); - connection.close(); - } + 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(); + if (consumer.receive(TimeUnit.SECONDS.toMillis(10)) != null) { + fail("Should be no messages for this durable."); + } + consumer.close(); + connection.close(); + } - private int consumeFromInactiveDurableSub(Topic topic) throws Exception { - Connection connection = cf.createConnection(); - connection.setClientID("Inactive"); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "Inactive"); + private int consumeFromInactiveDurableSub(Topic topic) throws Exception { + Connection connection = cf.createConnection(); + connection.setClientID("Inactive"); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createDurableSubscriber(topic, "Inactive"); - int count = 0; + int count = 0; - while (consumer.receive(10000) != null) { - count++; - } + while (consumer.receive(10000) != null) { + count++; + } - consumer.close(); - connection.close(); + consumer.close(); + connection.close(); - return count; - } + return count; + } - private void sendMessages(Destination destination) throws Exception { - sendMessages(destination, MSG_COUNT); - } + private void sendMessages(Destination destination) throws Exception { + sendMessages(destination, MSG_COUNT); + } - private void sendMessages(Destination destination, int count) throws Exception { - Connection connection = cf.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - for (int i = 0; i < count; ++i) { - TextMessage message = session.createTextMessage("Message #" + i + " for destination: " + destination); - producer.send(message); - } - connection.close(); - } + private void sendMessages(Destination destination, int count) throws Exception { + Connection connection = cf.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + for (int i = 0; i < count; ++i) { + TextMessage message = session.createTextMessage("Message #" + i + " for destination: " + destination); + producer.send(message); + } + connection.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4213Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4213Test.java index fddb6b12f0..c033e97956 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4213Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4213Test.java @@ -35,55 +35,54 @@ import org.junit.Test; public class AMQ4213Test { - private static BrokerService brokerService; - private static String BROKER_ADDRESS = "tcp://localhost:0"; - private static String TEST_QUEUE = "testQueue"; - private static ActiveMQQueue queue = new ActiveMQQueue(TEST_QUEUE); + private static BrokerService brokerService; + private static String BROKER_ADDRESS = "tcp://localhost:0"; + private static String TEST_QUEUE = "testQueue"; + private static ActiveMQQueue queue = new ActiveMQQueue(TEST_QUEUE); - private String connectionUri; + private String connectionUri; - @SuppressWarnings("unchecked") - @Before - public void setUp() throws Exception { - brokerService = new BrokerService(); - brokerService.setPersistent(false); - brokerService.setUseJmx(true); - brokerService.setDeleteAllMessagesOnStartup(true); - connectionUri = brokerService.addConnector(BROKER_ADDRESS).getPublishableConnectString(); + @SuppressWarnings("unchecked") + @Before + public void setUp() throws Exception { + brokerService = new BrokerService(); + brokerService.setPersistent(false); + brokerService.setUseJmx(true); + brokerService.setDeleteAllMessagesOnStartup(true); + connectionUri = brokerService.addConnector(BROKER_ADDRESS).getPublishableConnectString(); - brokerService.setPlugins(new BrokerPlugin[]{ - new BrokerPluginSupport() { + brokerService.setPlugins(new BrokerPlugin[]{new BrokerPluginSupport() { - @Override - public void addProducer(ConnectionContext context, ProducerInfo info) throws Exception { - throw new javax.jms.JMSSecurityException(connectionUri); - } - } - }); + @Override + public void addProducer(ConnectionContext context, ProducerInfo info) throws Exception { + throw new javax.jms.JMSSecurityException(connectionUri); + } + }}); - brokerService.start(); - brokerService.waitUntilStarted(); - } + brokerService.start(); + brokerService.waitUntilStarted(); + } - @After - public void tearDown() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - } + @After + public void tearDown() throws Exception { + brokerService.stop(); + brokerService.waitUntilStopped(); + } - @Test - public void testExceptionOnProducerCreateThrows() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); + @Test + public void testExceptionOnProducerCreateThrows() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); + ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - connection.start(); + connection.start(); - try { - session.createProducer(queue); - fail("Should not be able to create this producer."); - } catch (JMSException ex) { - } - } + try { + session.createProducer(queue); + fail("Should not be able to create this producer."); + } + catch (JMSException ex) { + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4220Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4220Test.java index 7084bde44c..3e1e8637ae 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4220Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4220Test.java @@ -37,84 +37,83 @@ import org.slf4j.LoggerFactory; public class AMQ4220Test { - static final Logger LOG = LoggerFactory.getLogger(AMQ4220Test.class); - private final static int maxFileLength = 1024*1024*32; - private final static String destinationName = "TEST.QUEUE"; - BrokerService broker; + static final Logger LOG = LoggerFactory.getLogger(AMQ4220Test.class); + private final static int maxFileLength = 1024 * 1024 * 32; + private final static String destinationName = "TEST.QUEUE"; + BrokerService broker; - @Before - public void setUp() throws Exception { - prepareBrokerWithMultiStore(true); - broker.start(); - broker.waitUntilStarted(); - } + @Before + public void setUp() throws Exception { + prepareBrokerWithMultiStore(true); + broker.start(); + broker.waitUntilStarted(); + } - @After - public void tearDown() throws Exception { - broker.stop(); - } + @After + public void tearDown() throws Exception { + broker.stop(); + } - protected BrokerService createBroker(PersistenceAdapter kaha) throws Exception { - BrokerService broker = new BrokerService(); - broker.setUseJmx(true); - broker.setBrokerName("localhost"); - broker.setPersistenceAdapter(kaha); - return broker; - } + protected BrokerService createBroker(PersistenceAdapter kaha) throws Exception { + BrokerService broker = new BrokerService(); + broker.setUseJmx(true); + broker.setBrokerName("localhost"); + broker.setPersistenceAdapter(kaha); + return broker; + } - @Test - public void testRestartAfterQueueDelete() throws Exception { + @Test + public void testRestartAfterQueueDelete() throws Exception { - // Ensure we have an Admin View. - assertTrue("Broker doesn't have an Admin View.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return (broker.getAdminView()) != null; - } - })); + // Ensure we have an Admin View. + assertTrue("Broker doesn't have an Admin View.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return (broker.getAdminView()) != null; + } + })); + LOG.info("Adding initial destination: {}", destinationName); - LOG.info("Adding initial destination: {}", destinationName); + broker.getAdminView().addQueue(destinationName); - broker.getAdminView().addQueue(destinationName); + assertNotNull(broker.getDestination(new ActiveMQQueue(destinationName))); - assertNotNull(broker.getDestination(new ActiveMQQueue(destinationName))); + LOG.info("Removing initial destination: {}", destinationName); - LOG.info("Removing initial destination: {}", destinationName); + broker.getAdminView().removeQueue(destinationName); - broker.getAdminView().removeQueue(destinationName); + LOG.info("Adding back destination: {}", destinationName); - LOG.info("Adding back destination: {}", destinationName); + broker.getAdminView().addQueue(destinationName); - broker.getAdminView().addQueue(destinationName); + assertNotNull(broker.getDestination(new ActiveMQQueue(destinationName))); + } - assertNotNull(broker.getDestination(new ActiveMQQueue(destinationName))); - } + protected KahaDBPersistenceAdapter createStore(boolean delete) throws IOException { + KahaDBPersistenceAdapter kaha = new KahaDBPersistenceAdapter(); + kaha.setJournalMaxFileLength(maxFileLength); + kaha.setCleanupInterval(5000); + if (delete) { + kaha.deleteAllMessages(); + } + return kaha; + } - protected KahaDBPersistenceAdapter createStore(boolean delete) throws IOException { - KahaDBPersistenceAdapter kaha = new KahaDBPersistenceAdapter(); - kaha.setJournalMaxFileLength(maxFileLength); - kaha.setCleanupInterval(5000); - if (delete) { - kaha.deleteAllMessages(); - } - return kaha; - } + public void prepareBrokerWithMultiStore(boolean deleteAllMessages) throws Exception { - public void prepareBrokerWithMultiStore(boolean deleteAllMessages) throws Exception { + MultiKahaDBPersistenceAdapter multiKahaDBPersistenceAdapter = new MultiKahaDBPersistenceAdapter(); + if (deleteAllMessages) { + multiKahaDBPersistenceAdapter.deleteAllMessages(); + } + ArrayList adapters = new ArrayList(); - MultiKahaDBPersistenceAdapter multiKahaDBPersistenceAdapter = new MultiKahaDBPersistenceAdapter(); - if (deleteAllMessages) { - multiKahaDBPersistenceAdapter.deleteAllMessages(); - } - ArrayList adapters = new ArrayList(); + FilteredKahaDBPersistenceAdapter template = new FilteredKahaDBPersistenceAdapter(); + template.setPersistenceAdapter(createStore(deleteAllMessages)); + template.setPerDestination(true); + adapters.add(template); - FilteredKahaDBPersistenceAdapter template = new FilteredKahaDBPersistenceAdapter(); - template.setPersistenceAdapter(createStore(deleteAllMessages)); - template.setPerDestination(true); - adapters.add(template); - - multiKahaDBPersistenceAdapter.setFilteredPersistenceAdapters(adapters); - broker = createBroker(multiKahaDBPersistenceAdapter); - } + multiKahaDBPersistenceAdapter.setFilteredPersistenceAdapters(adapters); + broker = createBroker(multiKahaDBPersistenceAdapter); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4221Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4221Test.java index 55e8027704..8bb4f9a16f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4221Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4221Test.java @@ -31,7 +31,9 @@ import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; + import junit.framework.Test; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQPrefetchPolicy; import org.apache.activemq.TestSupport; @@ -52,216 +54,220 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AMQ4221Test extends TestSupport { - private static final Logger LOG = LoggerFactory.getLogger(AMQ4221Test.class); - public int PAYLOAD_SIZE_BYTES = 4 * 1024; - public int NUM_TO_SEND = 60000; - public int NUM_CONCURRENT_PRODUCERS = 20; - public int QUEUE_COUNT = 1; - public int TMP_JOURNAL_MAX_FILE_SIZE = 10 * 1024 * 1024; - public int DLQ_PURGE_INTERVAL = 30000; + private static final Logger LOG = LoggerFactory.getLogger(AMQ4221Test.class); + public int PAYLOAD_SIZE_BYTES = 4 * 1024; + public int NUM_TO_SEND = 60000; + public int NUM_CONCURRENT_PRODUCERS = 20; + public int QUEUE_COUNT = 1; + public int TMP_JOURNAL_MAX_FILE_SIZE = 10 * 1024 * 1024; - public int MESSAGE_TIME_TO_LIVE = 20000; - public int EXPIRE_SWEEP_PERIOD = 200; - public int TMP_JOURNAL_GC_PERIOD = 50; - public int RECEIVE_POLL_PERIOD = 4000; - private int RECEIVE_BATCH = 5000; + public int DLQ_PURGE_INTERVAL = 30000; - final byte[] payload = new byte[PAYLOAD_SIZE_BYTES]; - final AtomicInteger counter = new AtomicInteger(0); - final HashSet exceptions = new HashSet(); - BrokerService brokerService; - private String brokerUrlString; - ExecutorService executorService = Executors.newCachedThreadPool(); - final AtomicBoolean done = new AtomicBoolean(false); + public int MESSAGE_TIME_TO_LIVE = 20000; + public int EXPIRE_SWEEP_PERIOD = 200; + public int TMP_JOURNAL_GC_PERIOD = 50; + public int RECEIVE_POLL_PERIOD = 4000; + private int RECEIVE_BATCH = 5000; - public static Test suite() { - return suite(AMQ4221Test.class); - } + final byte[] payload = new byte[PAYLOAD_SIZE_BYTES]; + final AtomicInteger counter = new AtomicInteger(0); + final HashSet exceptions = new HashSet(); + BrokerService brokerService; + private String brokerUrlString; + ExecutorService executorService = Executors.newCachedThreadPool(); + final AtomicBoolean done = new AtomicBoolean(false); - @Override - public void setUp() throws Exception { + public static Test suite() { + return suite(AMQ4221Test.class); + } - LogManager.getRootLogger().addAppender(new DefaultTestAppender() { + @Override + public void setUp() throws Exception { - @Override - public void doAppend(LoggingEvent event) { - if (event.getLevel().isGreaterOrEqual(Level.ERROR)) { - System.err.println("exit on error: " + event.getMessage()); - done.set(true); - new Thread() { - public void run() { - System.exit(787); - } - }.start(); - } + LogManager.getRootLogger().addAppender(new DefaultTestAppender() { + + @Override + public void doAppend(LoggingEvent event) { + if (event.getLevel().isGreaterOrEqual(Level.ERROR)) { + System.err.println("exit on error: " + event.getMessage()); + done.set(true); + new Thread() { + public void run() { + System.exit(787); + } + }.start(); } - }); + } + }); - done.set(false); - brokerService = new BrokerService(); - brokerService.setDeleteAllMessagesOnStartup(true); - brokerService.setDestinations(new ActiveMQDestination[]{new ActiveMQQueue("ActiveMQ.DLQ")}); + done.set(false); + brokerService = new BrokerService(); + brokerService.setDeleteAllMessagesOnStartup(true); + brokerService.setDestinations(new ActiveMQDestination[]{new ActiveMQQueue("ActiveMQ.DLQ")}); - PolicyEntry defaultPolicy = new PolicyEntry(); - defaultPolicy.setPendingQueuePolicy(new FilePendingQueueMessageStoragePolicy()); - defaultPolicy.setExpireMessagesPeriod(EXPIRE_SWEEP_PERIOD); - defaultPolicy.setProducerFlowControl(false); - defaultPolicy.setMemoryLimit(50 * 1024 * 1024); + PolicyEntry defaultPolicy = new PolicyEntry(); + defaultPolicy.setPendingQueuePolicy(new FilePendingQueueMessageStoragePolicy()); + defaultPolicy.setExpireMessagesPeriod(EXPIRE_SWEEP_PERIOD); + defaultPolicy.setProducerFlowControl(false); + defaultPolicy.setMemoryLimit(50 * 1024 * 1024); - brokerService.getSystemUsage().getMemoryUsage().setLimit(50 * 1024 * 1024); + brokerService.getSystemUsage().getMemoryUsage().setLimit(50 * 1024 * 1024); + PolicyMap destinationPolicyMap = new PolicyMap(); + destinationPolicyMap.setDefaultEntry(defaultPolicy); + brokerService.setDestinationPolicy(destinationPolicyMap); - PolicyMap destinationPolicyMap = new PolicyMap(); - destinationPolicyMap.setDefaultEntry(defaultPolicy); - brokerService.setDestinationPolicy(destinationPolicyMap); + PListStoreImpl tempDataStore = new PListStoreImpl(); + tempDataStore.setDirectory(brokerService.getTmpDataDirectory()); + tempDataStore.setJournalMaxFileLength(TMP_JOURNAL_MAX_FILE_SIZE); + tempDataStore.setCleanupInterval(TMP_JOURNAL_GC_PERIOD); + tempDataStore.setIndexPageSize(200); + tempDataStore.setIndexEnablePageCaching(false); + brokerService.setTempDataStore(tempDataStore); + brokerService.setAdvisorySupport(false); + TransportConnector tcp = brokerService.addConnector("tcp://localhost:0"); + brokerService.start(); + brokerUrlString = tcp.getPublishableConnectString(); + } - PListStoreImpl tempDataStore = new PListStoreImpl(); - tempDataStore.setDirectory(brokerService.getTmpDataDirectory()); - tempDataStore.setJournalMaxFileLength(TMP_JOURNAL_MAX_FILE_SIZE); - tempDataStore.setCleanupInterval(TMP_JOURNAL_GC_PERIOD); - tempDataStore.setIndexPageSize(200); - tempDataStore.setIndexEnablePageCaching(false); + @Override + public void tearDown() throws Exception { + brokerService.stop(); + brokerService.waitUntilStopped(); + executorService.shutdownNow(); + } - brokerService.setTempDataStore(tempDataStore); - brokerService.setAdvisorySupport(false); - TransportConnector tcp = brokerService.addConnector("tcp://localhost:0"); - brokerService.start(); - brokerUrlString = tcp.getPublishableConnectString(); - } + public void testProduceConsumeExpireHalf() throws Exception { - @Override - public void tearDown() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - executorService.shutdownNow(); - } + final org.apache.activemq.broker.region.Queue dlq = (org.apache.activemq.broker.region.Queue) getDestination(brokerService, new ActiveMQQueue("ActiveMQ.DLQ")); - public void testProduceConsumeExpireHalf() throws Exception { - - final org.apache.activemq.broker.region.Queue dlq = - (org.apache.activemq.broker.region.Queue) getDestination(brokerService, new ActiveMQQueue("ActiveMQ.DLQ")); - - if (DLQ_PURGE_INTERVAL > 0) { - executorService.execute(new Runnable() { - @Override - public void run() { - while (!done.get()) { - try { - Thread.sleep(DLQ_PURGE_INTERVAL); - LOG.info("Purge DLQ, current size: " + dlq.getDestinationStatistics().getMessages().getCount()); - dlq.purge(); - } catch (InterruptedException allDone) { - } catch (Throwable e) { - e.printStackTrace(); - exceptions.add(e); - } - } - } - }); - - } - - final CountDownLatch latch = new CountDownLatch(QUEUE_COUNT); - for (int i = 0; i < QUEUE_COUNT; i++) { - final int id = i; - executorService.execute(new Runnable() { - @Override - public void run() { - try { - doProduceConsumeExpireHalf(id, latch); - } catch (Throwable e) { - e.printStackTrace(); - exceptions.add(e); - } - } - }); - } - - while (!done.get()) { - done.set(latch.await(5, TimeUnit.SECONDS)); - } - executorService.shutdown(); - executorService.awaitTermination(5, TimeUnit.MINUTES); - - assertTrue("no exceptions:" + exceptions, exceptions.isEmpty()); - - } - - public void doProduceConsumeExpireHalf(int id, CountDownLatch latch) throws Exception { - - final ActiveMQQueue queue = new ActiveMQQueue("Q" + id); - - final ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerUrlString); - ActiveMQPrefetchPolicy prefecthPolicy = new ActiveMQPrefetchPolicy(); - prefecthPolicy.setAll(0); - factory.setPrefetchPolicy(prefecthPolicy); - Connection connection = factory.createConnection(); - connection.start(); - final MessageConsumer consumer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE).createConsumer(queue, "on = 'true'"); - - executorService.execute(new Runnable() { + if (DLQ_PURGE_INTERVAL > 0) { + executorService.execute(new Runnable() { @Override public void run() { - try { - while (!done.get()) { - Thread.sleep(RECEIVE_POLL_PERIOD); - for (int i = 0; i < RECEIVE_BATCH && !done.get(); i++) { - - Message message = consumer.receive(1000); - if (message != null) { - counter.incrementAndGet(); - if (counter.get() > 0 && counter.get() % 500 == 0) { - LOG.info("received: " + counter.get() + ", " + message.getJMSDestination().toString()); - } - } - } - } - } catch (JMSException ignored) { - - } catch (Exception e) { - e.printStackTrace(); - exceptions.add(e); - } + while (!done.get()) { + try { + Thread.sleep(DLQ_PURGE_INTERVAL); + LOG.info("Purge DLQ, current size: " + dlq.getDestinationStatistics().getMessages().getCount()); + dlq.purge(); + } + catch (InterruptedException allDone) { + } + catch (Throwable e) { + e.printStackTrace(); + exceptions.add(e); + } + } } - }); + }); - final AtomicInteger accumulator = new AtomicInteger(0); - final CountDownLatch producersDone = new CountDownLatch(NUM_CONCURRENT_PRODUCERS); + } - for (int i = 0; i < NUM_CONCURRENT_PRODUCERS; i++) { - executorService.execute(new Runnable() { - @Override - public void run() { - try { - Connection sendConnection = factory.createConnection(); - sendConnection.start(); - Session sendSession = sendConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = sendSession.createProducer(queue); - producer.setTimeToLive(MESSAGE_TIME_TO_LIVE); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + final CountDownLatch latch = new CountDownLatch(QUEUE_COUNT); + for (int i = 0; i < QUEUE_COUNT; i++) { + final int id = i; + executorService.execute(new Runnable() { + @Override + public void run() { + try { + doProduceConsumeExpireHalf(id, latch); + } + catch (Throwable e) { + e.printStackTrace(); + exceptions.add(e); + } + } + }); + } - while (accumulator.incrementAndGet() < NUM_TO_SEND && !done.get()) { - BytesMessage message = sendSession.createBytesMessage(); - message.writeBytes(payload); - message.setStringProperty("on", String.valueOf(accumulator.get() % 2 == 0)); - producer.send(message); + while (!done.get()) { + done.set(latch.await(5, TimeUnit.SECONDS)); + } + executorService.shutdown(); + executorService.awaitTermination(5, TimeUnit.MINUTES); + assertTrue("no exceptions:" + exceptions, exceptions.isEmpty()); + + } + + public void doProduceConsumeExpireHalf(int id, CountDownLatch latch) throws Exception { + + final ActiveMQQueue queue = new ActiveMQQueue("Q" + id); + + final ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerUrlString); + ActiveMQPrefetchPolicy prefecthPolicy = new ActiveMQPrefetchPolicy(); + prefecthPolicy.setAll(0); + factory.setPrefetchPolicy(prefecthPolicy); + Connection connection = factory.createConnection(); + connection.start(); + final MessageConsumer consumer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE).createConsumer(queue, "on = 'true'"); + + executorService.execute(new Runnable() { + @Override + public void run() { + try { + while (!done.get()) { + Thread.sleep(RECEIVE_POLL_PERIOD); + for (int i = 0; i < RECEIVE_BATCH && !done.get(); i++) { + + Message message = consumer.receive(1000); + if (message != null) { + counter.incrementAndGet(); + if (counter.get() > 0 && counter.get() % 500 == 0) { + LOG.info("received: " + counter.get() + ", " + message.getJMSDestination().toString()); } - producersDone.countDown(); - } catch (Exception e) { - e.printStackTrace(); - exceptions.add(e); - } - } - }); - } + } + } + } + } + catch (JMSException ignored) { - producersDone.await(10, TimeUnit.MINUTES); + } + catch (Exception e) { + e.printStackTrace(); + exceptions.add(e); + } + } + }); - final DestinationStatistics view = getDestinationStatistics(brokerService, queue); - LOG.info("total expired so far " + view.getExpired().getCount() + ", " + queue.getQueueName()); - latch.countDown(); - } + final AtomicInteger accumulator = new AtomicInteger(0); + final CountDownLatch producersDone = new CountDownLatch(NUM_CONCURRENT_PRODUCERS); + + for (int i = 0; i < NUM_CONCURRENT_PRODUCERS; i++) { + executorService.execute(new Runnable() { + @Override + public void run() { + try { + Connection sendConnection = factory.createConnection(); + sendConnection.start(); + Session sendSession = sendConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = sendSession.createProducer(queue); + producer.setTimeToLive(MESSAGE_TIME_TO_LIVE); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + + while (accumulator.incrementAndGet() < NUM_TO_SEND && !done.get()) { + BytesMessage message = sendSession.createBytesMessage(); + message.writeBytes(payload); + message.setStringProperty("on", String.valueOf(accumulator.get() % 2 == 0)); + producer.send(message); + + } + producersDone.countDown(); + } + catch (Exception e) { + e.printStackTrace(); + exceptions.add(e); + } + } + }); + } + + producersDone.await(10, TimeUnit.MINUTES); + + final DestinationStatistics view = getDestinationStatistics(brokerService, queue); + LOG.info("total expired so far " + view.getExpired().getCount() + ", " + queue.getQueueName()); + latch.countDown(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4222Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4222Test.java index d5e58355fa..adaf0e5469 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4222Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4222Test.java @@ -51,138 +51,137 @@ import org.slf4j.LoggerFactory; */ public class AMQ4222Test extends TestSupport { - private static final Logger LOG = LoggerFactory.getLogger(AMQ4222Test.class); + private static final Logger LOG = LoggerFactory.getLogger(AMQ4222Test.class); - protected BrokerService brokerService; + protected BrokerService brokerService; - @Override - protected void setUp() throws Exception { - super.setUp(); - topic = false; - brokerService = createBroker(); - } + @Override + protected void setUp() throws Exception { + super.setUp(); + topic = false; + brokerService = createBroker(); + } - @Override - protected void tearDown() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - } + @Override + protected void tearDown() throws Exception { + brokerService.stop(); + brokerService.waitUntilStopped(); + } - protected BrokerService createBroker() throws Exception { - BrokerService broker = BrokerFactory.createBroker(new URI("broker:()/localhost?persistent=false")); - broker.start(); - broker.waitUntilStarted(); - return broker; - } + protected BrokerService createBroker() throws Exception { + BrokerService broker = BrokerFactory.createBroker(new URI("broker:()/localhost?persistent=false")); + broker.start(); + broker.waitUntilStarted(); + return broker; + } - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://localhost"); - } + @Override + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory("vm://localhost"); + } - public void testTempQueueCleanedUp() throws Exception { + public void testTempQueueCleanedUp() throws Exception { - Destination requestQueue = createDestination(); + Destination requestQueue = createDestination(); - Connection producerConnection = createConnection(); - producerConnection.start(); - Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Connection producerConnection = createConnection(); + producerConnection.start(); + Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = producerSession.createProducer(requestQueue); - Destination replyTo = producerSession.createTemporaryQueue(); - MessageConsumer producerSessionConsumer = producerSession.createConsumer(replyTo); + MessageProducer producer = producerSession.createProducer(requestQueue); + Destination replyTo = producerSession.createTemporaryQueue(); + MessageConsumer producerSessionConsumer = producerSession.createConsumer(replyTo); - final CountDownLatch countDownLatch = new CountDownLatch(1); - // let's listen to the response on the queue - producerSessionConsumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - try { - if (message instanceof TextMessage) { - LOG.info("You got a message: " + ((TextMessage) message).getText()); - countDownLatch.countDown(); - } - } catch (JMSException e) { - e.printStackTrace(); - } + final CountDownLatch countDownLatch = new CountDownLatch(1); + // let's listen to the response on the queue + producerSessionConsumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + try { + if (message instanceof TextMessage) { + LOG.info("You got a message: " + ((TextMessage) message).getText()); + countDownLatch.countDown(); + } } - }); - - producer.send(createRequest(producerSession, replyTo)); - - Connection consumerConnection = createConnection(); - consumerConnection.start(); - Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = consumerSession.createConsumer(requestQueue); - final MessageProducer consumerProducer = consumerSession.createProducer(null); - - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - try { - consumerProducer.send(message.getJMSReplyTo(), message); - } catch (JMSException e) { - LOG.error("error sending a response on the temp queue"); - e.printStackTrace(); - } + catch (JMSException e) { + e.printStackTrace(); } - }); + } + }); - countDownLatch.await(2, TimeUnit.SECONDS); + producer.send(createRequest(producerSession, replyTo)); - // producer has not gone away yet... - org.apache.activemq.broker.region.Destination tempDestination = getDestination(brokerService, - (ActiveMQDestination) replyTo); - assertNotNull(tempDestination); + Connection consumerConnection = createConnection(); + consumerConnection.start(); + Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = consumerSession.createConsumer(requestQueue); + final MessageProducer consumerProducer = consumerSession.createProducer(null); - // clean up - producer.close(); - producerSession.close(); - producerConnection.close(); - - // producer has gone away.. so the temp queue should not exist anymore... let's see.. - // producer has not gone away yet... - tempDestination = getDestination(brokerService, - (ActiveMQDestination) replyTo); - assertNull(tempDestination); - - // now.. the connection on the broker side for the dude producing to the temp dest will - // still have a reference in his producerBrokerExchange.. this will keep the destination - // from being reclaimed by GC if there is never another send that producer makes... - // let's see if that reference is there... - final TransportConnector connector = VMTransportFactory.CONNECTORS.get("localhost"); - assertNotNull(connector); - assertTrue(Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return connector.getConnections().size() == 1; + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + try { + consumerProducer.send(message.getJMSReplyTo(), message); } - })); - TransportConnection transportConnection = connector.getConnections().get(0); - Map exchanges = getProducerExchangeFromConn(transportConnection); - assertEquals(1, exchanges.size()); - ProducerBrokerExchange exchange = exchanges.values().iterator().next(); + catch (JMSException e) { + LOG.error("error sending a response on the temp queue"); + e.printStackTrace(); + } + } + }); - // so this is the reason for the test... we don't want these exchanges to hold a reference - // to a region destination.. after a send is completed, the destination is not used anymore on - // a producer exchange - assertNull(exchange.getRegionDestination()); - assertNull(exchange.getRegion()); + countDownLatch.await(2, TimeUnit.SECONDS); - } + // producer has not gone away yet... + org.apache.activemq.broker.region.Destination tempDestination = getDestination(brokerService, (ActiveMQDestination) replyTo); + assertNotNull(tempDestination); - @SuppressWarnings("unchecked") - private Map getProducerExchangeFromConn(TransportConnection transportConnection) throws NoSuchFieldException, IllegalAccessException { - Field f = TransportConnection.class.getDeclaredField("producerExchanges"); - f.setAccessible(true); - Map producerExchanges = - (Map)f.get(transportConnection); - return producerExchanges; - } + // clean up + producer.close(); + producerSession.close(); + producerConnection.close(); - private Message createRequest(Session session, Destination replyTo) throws JMSException { - Message message = session.createTextMessage("Payload"); - message.setJMSReplyTo(replyTo); - return message; - } + // producer has gone away.. so the temp queue should not exist anymore... let's see.. + // producer has not gone away yet... + tempDestination = getDestination(brokerService, (ActiveMQDestination) replyTo); + assertNull(tempDestination); + + // now.. the connection on the broker side for the dude producing to the temp dest will + // still have a reference in his producerBrokerExchange.. this will keep the destination + // from being reclaimed by GC if there is never another send that producer makes... + // let's see if that reference is there... + final TransportConnector connector = VMTransportFactory.CONNECTORS.get("localhost"); + assertNotNull(connector); + assertTrue(Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return connector.getConnections().size() == 1; + } + })); + TransportConnection transportConnection = connector.getConnections().get(0); + Map exchanges = getProducerExchangeFromConn(transportConnection); + assertEquals(1, exchanges.size()); + ProducerBrokerExchange exchange = exchanges.values().iterator().next(); + + // so this is the reason for the test... we don't want these exchanges to hold a reference + // to a region destination.. after a send is completed, the destination is not used anymore on + // a producer exchange + assertNull(exchange.getRegionDestination()); + assertNull(exchange.getRegion()); + + } + + @SuppressWarnings("unchecked") + private Map getProducerExchangeFromConn(TransportConnection transportConnection) throws NoSuchFieldException, IllegalAccessException { + Field f = TransportConnection.class.getDeclaredField("producerExchanges"); + f.setAccessible(true); + Map producerExchanges = (Map) f.get(transportConnection); + return producerExchanges; + } + + private Message createRequest(Session session, Destination replyTo) throws JMSException { + Message message = session.createTextMessage("Payload"); + message.setJMSReplyTo(replyTo); + return message; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4323Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4323Test.java index 594e92f925..415dad6239 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4323Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4323Test.java @@ -21,6 +21,7 @@ import javax.jms.Connection; import javax.jms.Destination; import javax.jms.Message; import javax.jms.Session; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.region.policy.PolicyEntry; @@ -34,128 +35,126 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class AMQ4323Test { - private static final Logger LOG = LoggerFactory.getLogger(AMQ4323Test.class); + private static final Logger LOG = LoggerFactory.getLogger(AMQ4323Test.class); - BrokerService broker = null; - File kahaDbDir = null; - private final Destination destination = new ActiveMQQueue("q"); - final String payload = new String(new byte[1024]); + BrokerService broker = null; + File kahaDbDir = null; + private final Destination destination = new ActiveMQQueue("q"); + final String payload = new String(new byte[1024]); - protected void startBroker(boolean delete) throws Exception { - broker = new BrokerService(); + protected void startBroker(boolean delete) throws Exception { + broker = new BrokerService(); - //Start with a clean directory - kahaDbDir = new File(broker.getBrokerDataDirectory(), "KahaDB"); - deleteDir(kahaDbDir); + //Start with a clean directory + kahaDbDir = new File(broker.getBrokerDataDirectory(), "KahaDB"); + deleteDir(kahaDbDir); - broker.setSchedulerSupport(false); - broker.setDeleteAllMessagesOnStartup(delete); - broker.setPersistent(true); - broker.setUseJmx(false); - broker.addConnector("tcp://localhost:0"); + broker.setSchedulerSupport(false); + broker.setDeleteAllMessagesOnStartup(delete); + broker.setPersistent(true); + broker.setUseJmx(false); + broker.addConnector("tcp://localhost:0"); - PolicyMap map = new PolicyMap(); - PolicyEntry entry = new PolicyEntry(); - entry.setUseCache(false); - map.setDefaultEntry(entry); - broker.setDestinationPolicy(map); + PolicyMap map = new PolicyMap(); + PolicyEntry entry = new PolicyEntry(); + entry.setUseCache(false); + map.setDefaultEntry(entry); + broker.setDestinationPolicy(map); - configurePersistence(broker, delete); + configurePersistence(broker, delete); - broker.start(); - LOG.info("Starting broker.."); - } + broker.start(); + LOG.info("Starting broker.."); + } - protected void configurePersistence(BrokerService brokerService, boolean deleteAllOnStart) throws Exception { - KahaDBPersistenceAdapter adapter = (KahaDBPersistenceAdapter) brokerService.getPersistenceAdapter(); + protected void configurePersistence(BrokerService brokerService, boolean deleteAllOnStart) throws Exception { + KahaDBPersistenceAdapter adapter = (KahaDBPersistenceAdapter) brokerService.getPersistenceAdapter(); - // ensure there are a bunch of data files but multiple entries in each - adapter.setJournalMaxFileLength(1024 * 20); + // ensure there are a bunch of data files but multiple entries in each + adapter.setJournalMaxFileLength(1024 * 20); - // speed up the test case, checkpoint and cleanup early and often - adapter.setCheckpointInterval(500); - adapter.setCleanupInterval(500); + // speed up the test case, checkpoint and cleanup early and often + adapter.setCheckpointInterval(500); + adapter.setCleanupInterval(500); - if (!deleteAllOnStart) { - adapter.setForceRecoverIndex(true); - } + if (!deleteAllOnStart) { + adapter.setForceRecoverIndex(true); + } - } + } - private boolean deleteDir(File dir) { - if (dir.isDirectory()) { - String[] children = dir.list(); - for (int i = 0; i < children.length; i++) { - boolean success = deleteDir(new File(dir, children[i])); - if (!success) { - return false; - } + private boolean deleteDir(File dir) { + if (dir.isDirectory()) { + String[] children = dir.list(); + for (int i = 0; i < children.length; i++) { + boolean success = deleteDir(new File(dir, children[i])); + if (!success) { + return false; } - } + } + } - return dir.delete(); - } + return dir.delete(); + } - private int getFileCount(File dir){ - if (dir.isDirectory()) { - String[] children = dir.list(); - return children.length; - } + private int getFileCount(File dir) { + if (dir.isDirectory()) { + String[] children = dir.list(); + return children.length; + } - return 0; - } + return 0; + } - @Test - public void testCleanupOfFiles() throws Exception { - final int messageCount = 500; - startBroker(true); - int fileCount = getFileCount(kahaDbDir); - assertEquals(4, fileCount); + @Test + public void testCleanupOfFiles() throws Exception { + final int messageCount = 500; + startBroker(true); + int fileCount = getFileCount(kahaDbDir); + assertEquals(4, fileCount); - Connection connection = new ActiveMQConnectionFactory( - broker.getTransportConnectors().get(0).getConnectUri()).createConnection(); - connection.start(); - Session producerSess = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Session consumerSess = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Connection connection = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri()).createConnection(); + connection.start(); + Session producerSess = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Session consumerSess = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ProducerThread producer = new ProducerThread(producerSess, destination) { - @Override - protected Message createMessage(int i) throws Exception { - return sess.createTextMessage(payload + "::" + i); - } - }; - producer.setMessageCount(messageCount); - ConsumerThread consumer = new ConsumerThread(consumerSess, destination); - consumer.setBreakOnNull(false); - consumer.setMessageCount(messageCount); + ProducerThread producer = new ProducerThread(producerSess, destination) { + @Override + protected Message createMessage(int i) throws Exception { + return sess.createTextMessage(payload + "::" + i); + } + }; + producer.setMessageCount(messageCount); + ConsumerThread consumer = new ConsumerThread(consumerSess, destination); + consumer.setBreakOnNull(false); + consumer.setMessageCount(messageCount); - producer.start(); - producer.join(); + producer.start(); + producer.join(); - consumer.start(); - consumer.join(); + consumer.start(); + consumer.join(); - assertEquals("consumer got all produced messages", producer.getMessageCount(), consumer.getReceived()); + assertEquals("consumer got all produced messages", producer.getMessageCount(), consumer.getReceived()); - // verify cleanup - assertTrue("gc worked", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - int fileCount = getFileCount(kahaDbDir); - LOG.info("current filecount:" + fileCount); - return 4 == fileCount; - } - })); + // verify cleanup + assertTrue("gc worked", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + int fileCount = getFileCount(kahaDbDir); + LOG.info("current filecount:" + fileCount); + return 4 == fileCount; + } + })); - broker.stop(); - broker.waitUntilStopped(); + broker.stop(); + broker.waitUntilStopped(); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4356Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4356Test.java index aa3ac2c1a4..3d4ec84aa5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4356Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4356Test.java @@ -36,107 +36,107 @@ import org.junit.Test; public class AMQ4356Test { - private static BrokerService brokerService; - private static String BROKER_ADDRESS = "tcp://localhost:0"; + private static BrokerService brokerService; + private static String BROKER_ADDRESS = "tcp://localhost:0"; - private String connectionUri; - private ActiveMQConnectionFactory cf; - private final String CLIENT_ID = "AMQ4356Test"; - private final String SUBSCRIPTION_NAME = "AMQ4356Test"; + private String connectionUri; + private ActiveMQConnectionFactory cf; + private final String CLIENT_ID = "AMQ4356Test"; + private final String SUBSCRIPTION_NAME = "AMQ4356Test"; - private void createBroker(boolean deleteOnStart) throws Exception { - brokerService = new BrokerService(); - brokerService.setUseJmx(true); - brokerService.setDeleteAllMessagesOnStartup(deleteOnStart); - connectionUri = brokerService.addConnector(BROKER_ADDRESS).getPublishableConnectString(); - brokerService.start(); - brokerService.waitUntilStarted(); + private void createBroker(boolean deleteOnStart) throws Exception { + brokerService = new BrokerService(); + brokerService.setUseJmx(true); + brokerService.setDeleteAllMessagesOnStartup(deleteOnStart); + connectionUri = brokerService.addConnector(BROKER_ADDRESS).getPublishableConnectString(); + brokerService.start(); + brokerService.waitUntilStarted(); - } + } - private void startBroker() throws Exception { - createBroker(true); - } + private void startBroker() throws Exception { + createBroker(true); + } - private void restartBroker() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - createBroker(false); - } + private void restartBroker() throws Exception { + brokerService.stop(); + brokerService.waitUntilStopped(); + createBroker(false); + } - @Before - public void setUp() throws Exception { - startBroker(); - cf = new ActiveMQConnectionFactory(connectionUri); - } + @Before + public void setUp() throws Exception { + startBroker(); + cf = new ActiveMQConnectionFactory(connectionUri); + } - @After - public void tearDown() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - } + @After + public void tearDown() throws Exception { + brokerService.stop(); + brokerService.waitUntilStopped(); + } - @Test - public void testVirtualTopicUnsubDurable() throws Exception { - Connection connection = cf.createConnection(); - connection.setClientID(CLIENT_ID); - connection.start(); + @Test + public void testVirtualTopicUnsubDurable() throws Exception { + Connection connection = cf.createConnection(); + connection.setClientID(CLIENT_ID); + connection.start(); - // create consumer 'cluster' - ActiveMQQueue queue1 = new ActiveMQQueue(getVirtualTopicConsumerName()); - ActiveMQQueue queue2 = new ActiveMQQueue(getVirtualTopicConsumerName()); + // create consumer 'cluster' + ActiveMQQueue queue1 = new ActiveMQQueue(getVirtualTopicConsumerName()); + ActiveMQQueue queue2 = new ActiveMQQueue(getVirtualTopicConsumerName()); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer c1 = session.createConsumer(queue1); - c1.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - } - }); - MessageConsumer c2 = session.createConsumer(queue2); - c2.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - } - }); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer c1 = session.createConsumer(queue1); + c1.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + } + }); + MessageConsumer c2 = session.createConsumer(queue2); + c2.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + } + }); - ActiveMQTopic topic = new ActiveMQTopic(getVirtualTopicName()); - MessageConsumer c3 = session.createDurableSubscriber(topic, SUBSCRIPTION_NAME); + ActiveMQTopic topic = new ActiveMQTopic(getVirtualTopicName()); + MessageConsumer c3 = session.createDurableSubscriber(topic, SUBSCRIPTION_NAME); - assertEquals(1, brokerService.getAdminView().getDurableTopicSubscribers().length); - assertEquals(0, brokerService.getAdminView().getInactiveDurableTopicSubscribers().length); + assertEquals(1, brokerService.getAdminView().getDurableTopicSubscribers().length); + assertEquals(0, brokerService.getAdminView().getInactiveDurableTopicSubscribers().length); - c3.close(); + c3.close(); - // create topic producer - MessageProducer producer = session.createProducer(topic); - assertNotNull(producer); + // create topic producer + MessageProducer producer = session.createProducer(topic); + assertNotNull(producer); - int total = 10; - for (int i = 0; i < total; i++) { - producer.send(session.createTextMessage("message: " + i)); - } + int total = 10; + for (int i = 0; i < total; i++) { + producer.send(session.createTextMessage("message: " + i)); + } - assertEquals(0, brokerService.getAdminView().getDurableTopicSubscribers().length); - assertEquals(1, brokerService.getAdminView().getInactiveDurableTopicSubscribers().length); + assertEquals(0, brokerService.getAdminView().getDurableTopicSubscribers().length); + assertEquals(1, brokerService.getAdminView().getInactiveDurableTopicSubscribers().length); - session.unsubscribe(SUBSCRIPTION_NAME); - connection.close(); + session.unsubscribe(SUBSCRIPTION_NAME); + connection.close(); - assertEquals(0, brokerService.getAdminView().getDurableTopicSubscribers().length); - assertEquals(0, brokerService.getAdminView().getInactiveDurableTopicSubscribers().length); + assertEquals(0, brokerService.getAdminView().getDurableTopicSubscribers().length); + assertEquals(0, brokerService.getAdminView().getInactiveDurableTopicSubscribers().length); - restartBroker(); + restartBroker(); - assertEquals(0, brokerService.getAdminView().getDurableTopicSubscribers().length); - assertEquals(0, brokerService.getAdminView().getInactiveDurableTopicSubscribers().length); - } + assertEquals(0, brokerService.getAdminView().getDurableTopicSubscribers().length); + assertEquals(0, brokerService.getAdminView().getInactiveDurableTopicSubscribers().length); + } - protected String getVirtualTopicName() { - return "VirtualTopic.TEST"; - } + protected String getVirtualTopicName() { + return "VirtualTopic.TEST"; + } - protected String getVirtualTopicConsumerName() { - return "Consumer.A.VirtualTopic.TEST"; - } + protected String getVirtualTopicConsumerName() { + return "Consumer.A.VirtualTopic.TEST"; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4361Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4361Test.java index 0e1c46570c..69c1e1dbf2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4361Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4361Test.java @@ -45,113 +45,116 @@ import org.slf4j.LoggerFactory; public class AMQ4361Test { - private static final Logger LOG = LoggerFactory.getLogger(AMQ4361Test.class); + private static final Logger LOG = LoggerFactory.getLogger(AMQ4361Test.class); - private BrokerService service; - private String brokerUrlString; + private BrokerService service; + private String brokerUrlString; - @Before - public void setUp() throws Exception { - service = new BrokerService(); - service.setDeleteAllMessagesOnStartup(true); - service.setUseJmx(false); + @Before + public void setUp() throws Exception { + service = new BrokerService(); + service.setDeleteAllMessagesOnStartup(true); + service.setUseJmx(false); - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policy = new PolicyEntry(); - policy.setMemoryLimit(1); - policy.setPendingSubscriberPolicy(new VMPendingSubscriberMessageStoragePolicy()); - policy.setPendingQueuePolicy(new VMPendingQueueMessageStoragePolicy()); - policy.setProducerFlowControl(true); - policyMap.setDefaultEntry(policy); - service.setDestinationPolicy(policyMap); + PolicyMap policyMap = new PolicyMap(); + PolicyEntry policy = new PolicyEntry(); + policy.setMemoryLimit(1); + policy.setPendingSubscriberPolicy(new VMPendingSubscriberMessageStoragePolicy()); + policy.setPendingQueuePolicy(new VMPendingQueueMessageStoragePolicy()); + policy.setProducerFlowControl(true); + policyMap.setDefaultEntry(policy); + service.setDestinationPolicy(policyMap); - service.setAdvisorySupport(false); - brokerUrlString = service.addConnector("tcp://localhost:0").getPublishableConnectString(); - service.start(); - service.waitUntilStarted(); - } + service.setAdvisorySupport(false); + brokerUrlString = service.addConnector("tcp://localhost:0").getPublishableConnectString(); + service.start(); + service.waitUntilStarted(); + } - @After - public void tearDown() throws Exception { - if (service != null) { - service.stop(); - service.waitUntilStopped(); - } - } + @After + public void tearDown() throws Exception { + if (service != null) { + service.stop(); + service.waitUntilStopped(); + } + } - @Test - public void testCloseWhenHunk() throws Exception { + @Test + public void testCloseWhenHunk() throws Exception { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrlString); - connectionFactory.setProducerWindowSize(1024); + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrlString); + connectionFactory.setProducerWindowSize(1024); - // TINY QUEUE is flow controlled after 1024 bytes - final ActiveMQDestination destination = - ActiveMQDestination.createDestination("queue://TINY_QUEUE", (byte) 0xff); + // TINY QUEUE is flow controlled after 1024 bytes + final ActiveMQDestination destination = ActiveMQDestination.createDestination("queue://TINY_QUEUE", (byte) 0xff); - Connection connection = connectionFactory.createConnection(); - connection.start(); - final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageProducer producer = session.createProducer(destination); - producer.setTimeToLive(0); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + Connection connection = connectionFactory.createConnection(); + connection.start(); + final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final MessageProducer producer = session.createProducer(destination); + producer.setTimeToLive(0); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - final AtomicReference publishException = new AtomicReference(null); - final AtomicReference closeException = new AtomicReference(null); - final AtomicLong lastLoop = new AtomicLong(System.currentTimeMillis() + 100); + final AtomicReference publishException = new AtomicReference(null); + final AtomicReference closeException = new AtomicReference(null); + final AtomicLong lastLoop = new AtomicLong(System.currentTimeMillis() + 100); - Thread pubThread = new Thread(new Runnable() { - @Override - public void run() { - try { - byte[] data = new byte[1000]; - new Random(0xdeadbeef).nextBytes(data); - for (int i = 0; i < 10000; i++) { - lastLoop.set(System.currentTimeMillis()); - ObjectMessage objMsg = session.createObjectMessage(); - objMsg.setObject(data); - producer.send(destination, objMsg); - } - } catch (Exception e) { - publishException.set(e); - } + Thread pubThread = new Thread(new Runnable() { + @Override + public void run() { + try { + byte[] data = new byte[1000]; + new Random(0xdeadbeef).nextBytes(data); + for (int i = 0; i < 10000; i++) { + lastLoop.set(System.currentTimeMillis()); + ObjectMessage objMsg = session.createObjectMessage(); + objMsg.setObject(data); + producer.send(destination, objMsg); + } } - }, "PublishingThread"); - pubThread.start(); - - // wait for publisher to deadlock - while (System.currentTimeMillis() - lastLoop.get() < 2000) { - Thread.sleep(100); - } - LOG.info("Publisher deadlock detected."); - - Thread closeThread = new Thread(new Runnable() { - @Override - public void run() { - try { - LOG.info("Attempting close.."); - producer.close(); - } catch (Exception e) { - closeException.set(e); - } + catch (Exception e) { + publishException.set(e); } - }, "ClosingThread"); - closeThread.start(); + } + }, "PublishingThread"); + pubThread.start(); - try { - closeThread.join(30000); - } catch (InterruptedException ie) { - assertFalse("Closing thread didn't complete in 10 seconds", true); - } + // wait for publisher to deadlock + while (System.currentTimeMillis() - lastLoop.get() < 2000) { + Thread.sleep(100); + } + LOG.info("Publisher deadlock detected."); - try { - pubThread.join(30000); - } catch (InterruptedException ie) { - assertFalse("Publishing thread didn't complete in 10 seconds", true); - } + Thread closeThread = new Thread(new Runnable() { + @Override + public void run() { + try { + LOG.info("Attempting close.."); + producer.close(); + } + catch (Exception e) { + closeException.set(e); + } + } + }, "ClosingThread"); + closeThread.start(); - assertNull(closeException.get()); - assertNotNull(publishException.get()); - } + try { + closeThread.join(30000); + } + catch (InterruptedException ie) { + assertFalse("Closing thread didn't complete in 10 seconds", true); + } + + try { + pubThread.join(30000); + } + catch (InterruptedException ie) { + assertFalse("Publishing thread didn't complete in 10 seconds", true); + } + + assertNull(closeException.get()); + assertNotNull(publishException.get()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4368Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4368Test.java index 13e1cfb856..ef53a0ab44 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4368Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4368Test.java @@ -46,203 +46,211 @@ import org.slf4j.LoggerFactory; public class AMQ4368Test { - private static final Logger LOG = LoggerFactory.getLogger(AMQ4368Test.class); + private static final Logger LOG = LoggerFactory.getLogger(AMQ4368Test.class); - private BrokerService broker; - private ActiveMQConnectionFactory connectionFactory; - private final Destination destination = new ActiveMQQueue("large_message_queue"); - private String connectionUri; + private BrokerService broker; + private ActiveMQConnectionFactory connectionFactory; + private final Destination destination = new ActiveMQQueue("large_message_queue"); + private String connectionUri; - @Before - public void setUp() throws Exception { - broker = createBroker(); - connectionUri = broker.addConnector("tcp://localhost:0").getPublishableConnectString(); - broker.start(); - connectionFactory = new ActiveMQConnectionFactory(connectionUri); - } + @Before + public void setUp() throws Exception { + broker = createBroker(); + connectionUri = broker.addConnector("tcp://localhost:0").getPublishableConnectString(); + broker.start(); + connectionFactory = new ActiveMQConnectionFactory(connectionUri); + } - @After - public void tearDown() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } + @After + public void tearDown() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + } - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); + protected BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); - PolicyEntry policy = new PolicyEntry(); - policy.setUseCache(false); - broker.setDestinationPolicy(new PolicyMap()); - broker.getDestinationPolicy().setDefaultEntry(policy); + PolicyEntry policy = new PolicyEntry(); + policy.setUseCache(false); + broker.setDestinationPolicy(new PolicyMap()); + broker.getDestinationPolicy().setDefaultEntry(policy); - KahaDBPersistenceAdapter kahadb = new KahaDBPersistenceAdapter(); - kahadb.setCheckForCorruptJournalFiles(true); - kahadb.setCleanupInterval(1000); + KahaDBPersistenceAdapter kahadb = new KahaDBPersistenceAdapter(); + kahadb.setCheckForCorruptJournalFiles(true); + kahadb.setCleanupInterval(1000); - kahadb.deleteAllMessages(); - broker.setPersistenceAdapter(kahadb); - broker.getSystemUsage().getMemoryUsage().setLimit(1024*1024*100); - broker.setUseJmx(false); + kahadb.deleteAllMessages(); + broker.setPersistenceAdapter(kahadb); + broker.getSystemUsage().getMemoryUsage().setLimit(1024 * 1024 * 100); + broker.setUseJmx(false); - return broker; - } + return broker; + } - abstract class Client implements Runnable { - private final String name; - final AtomicBoolean done = new AtomicBoolean(); - CountDownLatch startedLatch; - CountDownLatch doneLatch = new CountDownLatch(1); - Connection connection; - Session session; - final AtomicLong size = new AtomicLong(); + abstract class Client implements Runnable { - Client(String name, CountDownLatch startedLatch) { - this.name = name; - this.startedLatch = startedLatch; - } + private final String name; + final AtomicBoolean done = new AtomicBoolean(); + CountDownLatch startedLatch; + CountDownLatch doneLatch = new CountDownLatch(1); + Connection connection; + Session session; + final AtomicLong size = new AtomicLong(); - public void start() { - LOG.info("Starting: " + name); - new Thread(this, name).start(); - } + Client(String name, CountDownLatch startedLatch) { + this.name = name; + this.startedLatch = startedLatch; + } - public void stopAsync() { - done.set(true); - } + public void start() { + LOG.info("Starting: " + name); + new Thread(this, name).start(); + } - public void stop() throws InterruptedException { - stopAsync(); - if (!doneLatch.await(20, TimeUnit.MILLISECONDS)) { - try { - connection.close(); - doneLatch.await(); - } catch (Exception e) { - } - } - } + public void stopAsync() { + done.set(true); + } - @Override - public void run() { + public void stop() throws InterruptedException { + stopAsync(); + if (!doneLatch.await(20, TimeUnit.MILLISECONDS)) { try { - connection = createConnection(); - connection.start(); - try { - session = createSession(); - work(); - } finally { - try { - connection.close(); - } catch (JMSException ignore) { - } - LOG.info("Stopped: " + name); - } - } catch (Exception e) { - e.printStackTrace(); - done.set(true); - } finally { - doneLatch.countDown(); + connection.close(); + doneLatch.await(); } - } - - protected Session createSession() throws JMSException { - return connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } - - protected Connection createConnection() throws JMSException { - return connectionFactory.createConnection(); - } - - abstract protected void work() throws Exception; - } - - class ProducingClient extends Client { - - ProducingClient(String name, CountDownLatch startedLatch) { - super(name, startedLatch); - } - - private String createMessage() { - StringBuffer stringBuffer = new StringBuffer(); - for (long i = 0; i < 1000000; i++) { - stringBuffer.append("1234567890"); + catch (Exception e) { } - return stringBuffer.toString(); - } + } + } - @Override - protected void work() throws Exception { - String data = createMessage(); - MessageProducer producer = session.createProducer(destination); - startedLatch.countDown(); - while (!done.get()) { - producer.send(session.createTextMessage(data)); - long i = size.incrementAndGet(); - if ((i % 1000) == 0) { - LOG.info("produced " + i + "."); - } + @Override + public void run() { + try { + connection = createConnection(); + connection.start(); + try { + session = createSession(); + work(); } - } - } - - class ConsumingClient extends Client { - public ConsumingClient(String name, CountDownLatch startedLatch) { - super(name, startedLatch); - } - - @Override - protected void work() throws Exception { - MessageConsumer consumer = session.createConsumer(destination); - startedLatch.countDown(); - while (!done.get()) { - Message msg = consumer.receive(100); - if (msg != null) { - size.incrementAndGet(); - } + finally { + try { + connection.close(); + } + catch (JMSException ignore) { + } + LOG.info("Stopped: " + name); } - } - } + } + catch (Exception e) { + e.printStackTrace(); + done.set(true); + } + finally { + doneLatch.countDown(); + } + } - @Test - public void testENTMQ220() throws Exception { - LOG.info("Start test."); - CountDownLatch producer1Started = new CountDownLatch(1); - CountDownLatch producer2Started = new CountDownLatch(1); - CountDownLatch listener1Started = new CountDownLatch(1); + protected Session createSession() throws JMSException { + return connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + } - final ProducingClient producer1 = new ProducingClient("1", producer1Started); - final ProducingClient producer2 = new ProducingClient("2", producer2Started); - final ConsumingClient listener1 = new ConsumingClient("subscriber-1", listener1Started); - final AtomicLong lastSize = new AtomicLong(); + protected Connection createConnection() throws JMSException { + return connectionFactory.createConnection(); + } - try { + abstract protected void work() throws Exception; + } - producer1.start(); - producer2.start(); - listener1.start(); + class ProducingClient extends Client { - producer1Started.await(15, TimeUnit.SECONDS); - producer2Started.await(15, TimeUnit.SECONDS); - listener1Started.await(15, TimeUnit.SECONDS); + ProducingClient(String name, CountDownLatch startedLatch) { + super(name, startedLatch); + } - lastSize.set(listener1.size.get()); - for (int i = 0; i < 10; i++) { - Wait.waitFor(new Wait.Condition() { + private String createMessage() { + StringBuffer stringBuffer = new StringBuffer(); + for (long i = 0; i < 1000000; i++) { + stringBuffer.append("1234567890"); + } + return stringBuffer.toString(); + } - @Override - public boolean isSatisified() throws Exception { - return listener1.size.get() > lastSize.get(); - } - }); - long size = listener1.size.get(); - LOG.info("Listener 1: consumed: " + (size - lastSize.get())); - assertTrue("No messages received on iteration: " + i, size > lastSize.get()); - lastSize.set(size); + @Override + protected void work() throws Exception { + String data = createMessage(); + MessageProducer producer = session.createProducer(destination); + startedLatch.countDown(); + while (!done.get()) { + producer.send(session.createTextMessage(data)); + long i = size.incrementAndGet(); + if ((i % 1000) == 0) { + LOG.info("produced " + i + "."); } - } finally { - LOG.info("Stopping clients"); - producer1.stop(); - producer2.stop(); - listener1.stop(); - } - } + } + } + } + + class ConsumingClient extends Client { + + public ConsumingClient(String name, CountDownLatch startedLatch) { + super(name, startedLatch); + } + + @Override + protected void work() throws Exception { + MessageConsumer consumer = session.createConsumer(destination); + startedLatch.countDown(); + while (!done.get()) { + Message msg = consumer.receive(100); + if (msg != null) { + size.incrementAndGet(); + } + } + } + } + + @Test + public void testENTMQ220() throws Exception { + LOG.info("Start test."); + CountDownLatch producer1Started = new CountDownLatch(1); + CountDownLatch producer2Started = new CountDownLatch(1); + CountDownLatch listener1Started = new CountDownLatch(1); + + final ProducingClient producer1 = new ProducingClient("1", producer1Started); + final ProducingClient producer2 = new ProducingClient("2", producer2Started); + final ConsumingClient listener1 = new ConsumingClient("subscriber-1", listener1Started); + final AtomicLong lastSize = new AtomicLong(); + + try { + + producer1.start(); + producer2.start(); + listener1.start(); + + producer1Started.await(15, TimeUnit.SECONDS); + producer2Started.await(15, TimeUnit.SECONDS); + listener1Started.await(15, TimeUnit.SECONDS); + + lastSize.set(listener1.size.get()); + for (int i = 0; i < 10; i++) { + Wait.waitFor(new Wait.Condition() { + + @Override + public boolean isSatisified() throws Exception { + return listener1.size.get() > lastSize.get(); + } + }); + long size = listener1.size.get(); + LOG.info("Listener 1: consumed: " + (size - lastSize.get())); + assertTrue("No messages received on iteration: " + i, size > lastSize.get()); + lastSize.set(size); + } + } + finally { + LOG.info("Stopping clients"); + producer1.stop(); + producer2.stop(); + listener1.stop(); + } + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4407Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4407Test.java index 73d6d69f3d..c0cf07af70 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4407Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4407Test.java @@ -45,133 +45,130 @@ import org.slf4j.LoggerFactory; public class AMQ4407Test { - static final Logger LOG = LoggerFactory.getLogger(AMQ4407Test.class); - private final static int maxFileLength = 1024*1024*32; + static final Logger LOG = LoggerFactory.getLogger(AMQ4407Test.class); + private final static int maxFileLength = 1024 * 1024 * 32; - private final static String PREFIX_DESTINATION_NAME = "queue"; + private final static String PREFIX_DESTINATION_NAME = "queue"; - private final static String DESTINATION_NAME = PREFIX_DESTINATION_NAME + ".test"; - private final static String DESTINATION_NAME_2 = PREFIX_DESTINATION_NAME + "2.test"; - private final static String DESTINATION_NAME_3 = PREFIX_DESTINATION_NAME + "3.test"; + private final static String DESTINATION_NAME = PREFIX_DESTINATION_NAME + ".test"; + private final static String DESTINATION_NAME_2 = PREFIX_DESTINATION_NAME + "2.test"; + private final static String DESTINATION_NAME_3 = PREFIX_DESTINATION_NAME + "3.test"; - BrokerService broker; + BrokerService broker; - @Before - public void setUp() throws Exception { - prepareBrokerWithMultiStore(true); - broker.start(); - broker.waitUntilStarted(); - } + @Before + public void setUp() throws Exception { + prepareBrokerWithMultiStore(true); + broker.start(); + broker.waitUntilStarted(); + } - @After - public void tearDown() throws Exception { - broker.stop(); - } + @After + public void tearDown() throws Exception { + broker.stop(); + } - protected BrokerService createBroker(PersistenceAdapter kaha) throws Exception { - BrokerService broker = new BrokerService(); - broker.setUseJmx(true); - broker.setBrokerName("localhost"); - broker.setPersistenceAdapter(kaha); - return broker; - } + protected BrokerService createBroker(PersistenceAdapter kaha) throws Exception { + BrokerService broker = new BrokerService(); + broker.setUseJmx(true); + broker.setBrokerName("localhost"); + broker.setPersistenceAdapter(kaha); + return broker; + } - @Test - public void testRestartAfterQueueDelete() throws Exception { + @Test + public void testRestartAfterQueueDelete() throws Exception { - // Ensure we have an Admin View. - assertTrue("Broker doesn't have an Admin View.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return (broker.getAdminView()) != null; - } - })); + // Ensure we have an Admin View. + assertTrue("Broker doesn't have an Admin View.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return (broker.getAdminView()) != null; + } + })); + LOG.info("Adding destinations: {}, {}, {}", new Object[]{DESTINATION_NAME, DESTINATION_NAME_3, DESTINATION_NAME_3}); + sendMessage(DESTINATION_NAME, "test 1"); + sendMessage(DESTINATION_NAME_2, "test 1"); + sendMessage(DESTINATION_NAME_3, "test 1"); - LOG.info("Adding destinations: {}, {}, {}", new Object[] {DESTINATION_NAME, DESTINATION_NAME_3, DESTINATION_NAME_3}); - sendMessage(DESTINATION_NAME, "test 1"); - sendMessage(DESTINATION_NAME_2, "test 1"); - sendMessage(DESTINATION_NAME_3, "test 1"); + assertNotNull(broker.getDestination(new ActiveMQQueue(DESTINATION_NAME))); + assertNotNull(broker.getDestination(new ActiveMQQueue(DESTINATION_NAME_2))); + assertNotNull(broker.getDestination(new ActiveMQQueue(DESTINATION_NAME_3))); - assertNotNull(broker.getDestination(new ActiveMQQueue(DESTINATION_NAME))); - assertNotNull(broker.getDestination(new ActiveMQQueue(DESTINATION_NAME_2))); - assertNotNull(broker.getDestination(new ActiveMQQueue(DESTINATION_NAME_3))); + LOG.info("Removing destination: {}", DESTINATION_NAME_2); + broker.getAdminView().removeQueue(DESTINATION_NAME_2); + LOG.info("Recreating destination: {}", DESTINATION_NAME_2); + sendMessage(DESTINATION_NAME_2, "test 1"); - LOG.info("Removing destination: {}", DESTINATION_NAME_2); - broker.getAdminView().removeQueue(DESTINATION_NAME_2); + Destination destination2 = broker.getDestination(new ActiveMQQueue(DESTINATION_NAME_2)); + assertNotNull(destination2); + assertEquals(1, destination2.getMessageStore().getMessageCount()); + } - LOG.info("Recreating destination: {}", DESTINATION_NAME_2); - sendMessage(DESTINATION_NAME_2, "test 1"); + protected KahaDBPersistenceAdapter createStore(boolean delete) throws IOException { + KahaDBPersistenceAdapter kaha = new KahaDBPersistenceAdapter(); + kaha.setJournalMaxFileLength(maxFileLength); + kaha.setCleanupInterval(5000); + if (delete) { + kaha.deleteAllMessages(); + } + return kaha; + } - Destination destination2 = broker.getDestination(new ActiveMQQueue(DESTINATION_NAME_2)); - assertNotNull(destination2); - assertEquals(1, destination2.getMessageStore().getMessageCount()); - } + public void prepareBrokerWithMultiStore(boolean deleteAllMessages) throws Exception { - protected KahaDBPersistenceAdapter createStore(boolean delete) throws IOException { - KahaDBPersistenceAdapter kaha = new KahaDBPersistenceAdapter(); - kaha.setJournalMaxFileLength(maxFileLength); - kaha.setCleanupInterval(5000); - if (delete) { - kaha.deleteAllMessages(); - } - return kaha; - } + MultiKahaDBPersistenceAdapter multiKahaDBPersistenceAdapter = new MultiKahaDBPersistenceAdapter(); + if (deleteAllMessages) { + multiKahaDBPersistenceAdapter.deleteAllMessages(); + } + ArrayList adapters = new ArrayList(); - public void prepareBrokerWithMultiStore(boolean deleteAllMessages) throws Exception { + adapters.add(createFilteredKahaDBByDestinationPrefix(PREFIX_DESTINATION_NAME, deleteAllMessages)); + adapters.add(createFilteredKahaDBByDestinationPrefix(PREFIX_DESTINATION_NAME + "2", deleteAllMessages)); + adapters.add(createFilteredKahaDBByDestinationPrefix(null, deleteAllMessages)); - MultiKahaDBPersistenceAdapter multiKahaDBPersistenceAdapter = new MultiKahaDBPersistenceAdapter(); - if (deleteAllMessages) { - multiKahaDBPersistenceAdapter.deleteAllMessages(); - } - ArrayList adapters = new ArrayList(); + multiKahaDBPersistenceAdapter.setFilteredPersistenceAdapters(adapters); + broker = createBroker(multiKahaDBPersistenceAdapter); + } - adapters.add(createFilteredKahaDBByDestinationPrefix(PREFIX_DESTINATION_NAME, deleteAllMessages)); - adapters.add(createFilteredKahaDBByDestinationPrefix(PREFIX_DESTINATION_NAME + "2", deleteAllMessages)); - adapters.add(createFilteredKahaDBByDestinationPrefix(null, deleteAllMessages)); + /** + * Create filtered KahaDB adapter by destination prefix. + * + * @param destinationPrefix + * @param deleteAllMessages + * @return + * @throws IOException + */ + private FilteredKahaDBPersistenceAdapter createFilteredKahaDBByDestinationPrefix(String destinationPrefix, + boolean deleteAllMessages) throws IOException { + FilteredKahaDBPersistenceAdapter template = new FilteredKahaDBPersistenceAdapter(); + template.setPersistenceAdapter(createStore(deleteAllMessages)); + if (destinationPrefix != null) { + template.setQueue(destinationPrefix + ".>"); + } + return template; + } - multiKahaDBPersistenceAdapter.setFilteredPersistenceAdapters(adapters); - broker = createBroker(multiKahaDBPersistenceAdapter); - } - - /** - * Create filtered KahaDB adapter by destination prefix. - * - * @param destinationPrefix - * @param deleteAllMessages - * @return - * @throws IOException - */ - private FilteredKahaDBPersistenceAdapter createFilteredKahaDBByDestinationPrefix(String destinationPrefix, boolean deleteAllMessages) - throws IOException { - FilteredKahaDBPersistenceAdapter template = new FilteredKahaDBPersistenceAdapter(); - template.setPersistenceAdapter(createStore(deleteAllMessages)); - if (destinationPrefix != null) { - template.setQueue(destinationPrefix + ".>"); - } - return template; - } - - - /** - * Send message to particular destination. - * - * @param destinationName - * @param message - * @throws JMSException - */ - private void sendMessage(String destinationName, String message) throws JMSException { - ActiveMQConnectionFactory f = new ActiveMQConnectionFactory("vm://localhost"); - f.setAlwaysSyncSend(true); - Connection c = f.createConnection(); - c.start(); - Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = s.createProducer(new ActiveMQQueue(destinationName)); - producer.send(s.createTextMessage(message)); - producer.close(); - s.close(); - c.stop(); - } + /** + * Send message to particular destination. + * + * @param destinationName + * @param message + * @throws JMSException + */ + private void sendMessage(String destinationName, String message) throws JMSException { + ActiveMQConnectionFactory f = new ActiveMQConnectionFactory("vm://localhost"); + f.setAlwaysSyncSend(true); + Connection c = f.createConnection(); + c.start(); + Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = s.createProducer(new ActiveMQQueue(destinationName)); + producer.send(s.createTextMessage(message)); + producer.close(); + s.close(); + c.stop(); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4413Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4413Test.java index ff973e916a..dab48cb355 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4413Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4413Test.java @@ -45,196 +45,202 @@ import org.slf4j.LoggerFactory; */ public class AMQ4413Test { - static final Logger LOG = LoggerFactory.getLogger(AMQ4413Test.class); + static final Logger LOG = LoggerFactory.getLogger(AMQ4413Test.class); - final String brokerUrl = "tcp://localhost:0"; - private String connectionUri; - final int numMsgsTriggeringReconnection = 2; - final int numMsgs = 30; - final int numTests = 75; - final ExecutorService threadPool = Executors.newCachedThreadPool(); + final String brokerUrl = "tcp://localhost:0"; + private String connectionUri; + final int numMsgsTriggeringReconnection = 2; + final int numMsgs = 30; + final int numTests = 75; + final ExecutorService threadPool = Executors.newCachedThreadPool(); - @Test - public void testDurableSubMessageLoss() throws Exception{ - // start embedded broker - BrokerService brokerService = new BrokerService(); - connectionUri = brokerService.addConnector(brokerUrl).getPublishableConnectString(); - brokerService.setPersistent(false); - brokerService.setUseJmx(false); - brokerService.setKeepDurableSubsActive(true); - brokerService.setAdvisorySupport(false); - brokerService.start(); - LOG.info("##### broker started"); + @Test + public void testDurableSubMessageLoss() throws Exception { + // start embedded broker + BrokerService brokerService = new BrokerService(); + connectionUri = brokerService.addConnector(brokerUrl).getPublishableConnectString(); + brokerService.setPersistent(false); + brokerService.setUseJmx(false); + brokerService.setKeepDurableSubsActive(true); + brokerService.setAdvisorySupport(false); + brokerService.start(); + LOG.info("##### broker started"); - // repeat test 50 times - try { - for (int i = 0; i < numTests; ++i) { - LOG.info("##### test " + i + " started"); - test(); + // repeat test 50 times + try { + for (int i = 0; i < numTests; ++i) { + LOG.info("##### test " + i + " started"); + test(); + } + + LOG.info("##### tests are done"); + } + catch (Exception e) { + e.printStackTrace(); + LOG.info("##### tests failed!"); + } + finally { + threadPool.shutdown(); + brokerService.stop(); + LOG.info("##### broker stopped"); + } + } + + private void test() throws Exception { + + final String topicName = "topic-" + UUID.randomUUID(); + final String clientId = "client-" + UUID.randomUUID(); + final String subName = "sub-" + UUID.randomUUID(); + + // create (and only create) subscription first + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); + factory.setWatchTopicAdvisories(false); + Connection connection = factory.createConnection(); + connection.setClientID(clientId); + connection.start(); + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Topic topic = session.createTopic(topicName); + TopicSubscriber durableSubscriptionCreator = session.createDurableSubscriber(topic, subName); + + connection.stop(); + durableSubscriptionCreator.close(); + session.close(); + connection.close(); + + // publisher task + Callable publisher = new Callable() { + @Override + public Boolean call() throws Exception { + Connection connection = null; + + try { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); + factory.setWatchTopicAdvisories(false); + connection = factory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Topic topic = session.createTopic(topicName); + + MessageProducer producer = session.createProducer(topic); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + producer.setPriority(Message.DEFAULT_PRIORITY); + producer.setTimeToLive(Message.DEFAULT_TIME_TO_LIVE); + + for (int seq = 1; seq <= numMsgs; ++seq) { + TextMessage msg = session.createTextMessage(String.valueOf(seq)); + producer.send(msg); + LOG.info("pub sent msg: " + seq); + Thread.sleep(1L); + } + + LOG.info("pub is done"); + } + finally { + if (connection != null) { + try { + connection.close(); + } + catch (JMSException e) { + e.printStackTrace(); + } + } + } + return Boolean.TRUE; + } + }; + + // subscriber task + Callable durableSubscriber = new Callable() { + ActiveMQConnectionFactory factory; + Connection connection; + Session session; + Topic topic; + TopicSubscriber consumer; + + @Override + public Boolean call() throws Exception { + factory = new ActiveMQConnectionFactory(connectionUri); + factory.setWatchTopicAdvisories(false); + + try { + connect(); + + for (int seqExpected = 1; seqExpected <= numMsgs; ++seqExpected) { + TextMessage msg = (TextMessage) consumer.receive(3000L); + if (msg == null) { + LOG.info("expected: " + seqExpected + ", actual: timed out", msg); + return Boolean.FALSE; + } + + int seq = Integer.parseInt(msg.getText()); + + LOG.info("sub received msg: " + seq); + + if (seqExpected != seq) { + LOG.info("expected: " + seqExpected + ", actual: " + seq); + return Boolean.FALSE; + } + + if (seq % numMsgsTriggeringReconnection == 0) { + close(false); + connect(); + + LOG.info("sub reconnected"); + } + } + + LOG.info("sub is done"); + } + finally { + try { + close(true); + } + catch (Exception e) { + e.printStackTrace(); + } } - LOG.info("##### tests are done"); - } catch (Exception e) { - e.printStackTrace(); - LOG.info("##### tests failed!"); - } finally { - threadPool.shutdown(); - brokerService.stop(); - LOG.info("##### broker stopped"); - } - } + return Boolean.TRUE; + } - private void test() throws Exception { + void connect() throws Exception { + connection = factory.createConnection(); + connection.setClientID(clientId); + connection.start(); - final String topicName = "topic-" + UUID.randomUUID(); - final String clientId = "client-" + UUID.randomUUID(); - final String subName = "sub-" + UUID.randomUUID(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + topic = session.createTopic(topicName); + consumer = session.createDurableSubscriber(topic, subName); + } - // create (and only create) subscription first - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - factory.setWatchTopicAdvisories(false); - Connection connection = factory.createConnection(); - connection.setClientID(clientId); - connection.start(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic(topicName); - TopicSubscriber durableSubscriptionCreator = session.createDurableSubscriber(topic, subName); - - connection.stop(); - durableSubscriptionCreator.close(); - session.close(); - connection.close(); - - // publisher task - Callable publisher = new Callable() { - @Override - public Boolean call() throws Exception { - Connection connection = null; - - try { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - factory.setWatchTopicAdvisories(false); - connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic(topicName); - - MessageProducer producer = session.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - producer.setPriority(Message.DEFAULT_PRIORITY); - producer.setTimeToLive(Message.DEFAULT_TIME_TO_LIVE); - - for (int seq = 1; seq <= numMsgs; ++seq) { - TextMessage msg = session.createTextMessage(String.valueOf(seq)); - producer.send(msg); - LOG.info("pub sent msg: " + seq); - Thread.sleep(1L); - } - - LOG.info("pub is done"); - } finally { - if (connection != null) { - try { - connection.close(); - } catch (JMSException e) { - e.printStackTrace(); - } - } - } - return Boolean.TRUE; - } - }; - - // subscriber task - Callable durableSubscriber = new Callable() { - ActiveMQConnectionFactory factory; - Connection connection; - Session session; - Topic topic; - TopicSubscriber consumer; - - @Override - public Boolean call() throws Exception { - factory = new ActiveMQConnectionFactory(connectionUri); - factory.setWatchTopicAdvisories(false); - - try { - connect(); - - for (int seqExpected = 1; seqExpected <= numMsgs; ++seqExpected) { - TextMessage msg = (TextMessage) consumer.receive(3000L); - if (msg == null) { - LOG.info("expected: " + seqExpected + ", actual: timed out", msg); - return Boolean.FALSE; - } - - int seq = Integer.parseInt(msg.getText()); - - LOG.info("sub received msg: " + seq); - - if (seqExpected != seq) { - LOG.info("expected: " + seqExpected + ", actual: " + seq); - return Boolean.FALSE; - } - - if (seq % numMsgsTriggeringReconnection == 0) { - close(false); - connect(); - - LOG.info("sub reconnected"); - } - } - - LOG.info("sub is done"); - } finally { - try { - close(true); - } catch (Exception e) { - e.printStackTrace(); - } - } - - return Boolean.TRUE; + void close(boolean unsubscribe) throws Exception { + if (connection != null) { + connection.stop(); } - void connect() throws Exception { - connection = factory.createConnection(); - connection.setClientID(clientId); - connection.start(); - - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - topic = session.createTopic(topicName); - consumer = session.createDurableSubscriber(topic, subName); + if (consumer != null) { + consumer.close(); } - void close(boolean unsubscribe) throws Exception { - if (connection != null) { - connection.stop(); - } - - if (consumer != null) { - consumer.close(); - } - - if (session != null) { - if (unsubscribe) { - session.unsubscribe(subName); - } - session.close(); - } - - if (connection != null) { - connection.close(); - } + if (session != null) { + if (unsubscribe) { + session.unsubscribe(subName); + } + session.close(); } - }; - ArrayList> results = new ArrayList>(); - results.add(threadPool.submit(publisher)); - results.add(threadPool.submit(durableSubscriber)); + if (connection != null) { + connection.close(); + } + } + }; - for (Future result : results) { - assertTrue(result.get()); - } - } + ArrayList> results = new ArrayList>(); + results.add(threadPool.submit(publisher)); + results.add(threadPool.submit(durableSubscriber)); + + for (Future result : results) { + assertTrue(result.get()); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4469Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4469Test.java index 2f7ae69f18..e80b05c757 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4469Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4469Test.java @@ -39,76 +39,75 @@ import org.springframework.jms.support.JmsUtils; public class AMQ4469Test { - private static final int maxConnections = 100; + private static final int maxConnections = 100; - private final ExecutorService executor = Executors.newCachedThreadPool(); - private String connectionUri; - private BrokerService service; - private TransportConnector connector; + private final ExecutorService executor = Executors.newCachedThreadPool(); + private String connectionUri; + private BrokerService service; + private TransportConnector connector; - @Before - public void setUp() throws Exception { - service = new BrokerService(); - service.setPersistent(false); - service.setUseJmx(false); - connector = service.addConnector("tcp://0.0.0.0:0?maximumConnections="+maxConnections); - connectionUri = connector.getPublishableConnectString(); - service.start(); - service.waitUntilStarted(); - } + @Before + public void setUp() throws Exception { + service = new BrokerService(); + service.setPersistent(false); + service.setUseJmx(false); + connector = service.addConnector("tcp://0.0.0.0:0?maximumConnections=" + maxConnections); + connectionUri = connector.getPublishableConnectString(); + service.start(); + service.waitUntilStarted(); + } - protected ConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(connectionUri); - } + protected ConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory(connectionUri); + } - @Test - public void testMaxConnectionControl() throws Exception { - final ConnectionFactory cf = createConnectionFactory(); - final CountDownLatch startupLatch = new CountDownLatch(1); - for(int i = 0; i < maxConnections + 20; i++) { - executor.submit(new Runnable() { - @Override - public void run() { - Connection conn = null; - try { - startupLatch.await(); - conn = cf.createConnection(); - conn.start(); - } catch (Exception e) { - e.printStackTrace(); - JmsUtils.closeConnection(conn); + @Test + public void testMaxConnectionControl() throws Exception { + final ConnectionFactory cf = createConnectionFactory(); + final CountDownLatch startupLatch = new CountDownLatch(1); + for (int i = 0; i < maxConnections + 20; i++) { + executor.submit(new Runnable() { + @Override + public void run() { + Connection conn = null; + try { + startupLatch.await(); + conn = cf.createConnection(); + conn.start(); + } + catch (Exception e) { + e.printStackTrace(); + JmsUtils.closeConnection(conn); + } + } + }); + } + + TcpTransportServer transportServer = (TcpTransportServer) connector.getServer(); + // ensure the max connections is in effect + assertEquals(maxConnections, transportServer.getMaximumConnections()); + // No connections at first + assertEquals(0, connector.getConnections().size()); + // Release the latch to set up connections in parallel + startupLatch.countDown(); + TimeUnit.SECONDS.sleep(5); + + final TransportConnector connector = this.connector; + + // Expect the max connections is created + assertTrue("Expected: " + maxConnections + " found: " + connector.getConnections().size(), Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return connector.getConnections().size() == maxConnections; } - } - }); - } + })); + } - TcpTransportServer transportServer = (TcpTransportServer)connector.getServer(); - // ensure the max connections is in effect - assertEquals(maxConnections, transportServer.getMaximumConnections()); - // No connections at first - assertEquals(0, connector.getConnections().size()); - // Release the latch to set up connections in parallel - startupLatch.countDown(); - TimeUnit.SECONDS.sleep(5); + @After + public void tearDown() throws Exception { + executor.shutdown(); - final TransportConnector connector = this.connector; - - // Expect the max connections is created - assertTrue("Expected: " + maxConnections + " found: " + connector.getConnections().size(), - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return connector.getConnections().size() == maxConnections; - } - }) - ); - } - - @After - public void tearDown() throws Exception { - executor.shutdown(); - - service.stop(); - service.waitUntilStopped(); - } + service.stop(); + service.waitUntilStopped(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4472Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4472Test.java index 42c391c85d..b7ae444723 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4472Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4472Test.java @@ -24,68 +24,73 @@ import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; + import org.apache.activemq.ActiveMQConnectionFactory; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; public class AMQ4472Test { - private static final Logger LOG = LoggerFactory.getLogger(AMQ4472Test.class); - @Test - public void testLostMessage() { - Connection connection = null; - try { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost?broker.useJmx=false"); - connection = connectionFactory.createConnection(); - connection.start(); + private static final Logger LOG = LoggerFactory.getLogger(AMQ4472Test.class); - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Destination test_data_destination = session.createQueue("test"+System.currentTimeMillis()); + @Test + public void testLostMessage() { + Connection connection = null; + try { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost?broker.useJmx=false"); + connection = connectionFactory.createConnection(); + connection.start(); - MessageConsumer consumer = session.createConsumer(test_data_destination); - LOG.info("Consumer 1 connected"); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + Destination test_data_destination = session.createQueue("test" + System.currentTimeMillis()); - MessageProducer producer = session.createProducer(test_data_destination); - producer.send(session.createTextMessage("Message 1")); + MessageConsumer consumer = session.createConsumer(test_data_destination); + LOG.info("Consumer 1 connected"); - // committing the session prior to the close + MessageProducer producer = session.createProducer(test_data_destination); + producer.send(session.createTextMessage("Message 1")); + + // committing the session prior to the close + session.commit(); + + // starting a new transaction + producer.send(session.createTextMessage("Message 2")); + + // in a new transaction, with prefetch>0, the message + // 1 will be pending till second commit + LOG.info("Closing consumer 1..."); + consumer.close(); + + // create a consumer + consumer = session.createConsumer(test_data_destination); + LOG.info("Consumer 2 connected"); + + // retrieve message previously committed to tmp queue + Message message = consumer.receive(10000); + if (message != null) { + LOG.info("Got message 1:", message); + assertEquals("expected message", "Message 1", ((TextMessage) message).getText()); session.commit(); - - // starting a new transaction - producer.send(session.createTextMessage("Message 2")); - - // in a new transaction, with prefetch>0, the message - // 1 will be pending till second commit - LOG.info("Closing consumer 1..."); - consumer.close(); - - // create a consumer - consumer = session.createConsumer(test_data_destination); - LOG.info("Consumer 2 connected"); - - // retrieve message previously committed to tmp queue - Message message = consumer.receive(10000); - if (message != null) { - LOG.info("Got message 1:", message); - assertEquals("expected message", "Message 1", ((TextMessage) message).getText()); - session.commit(); - } else { - LOG.error("Expected message but it never arrived"); - } - assertNotNull(message); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - connection.close(); - } catch (JMSException e) { - } - } - } + } + else { + LOG.error("Expected message but it never arrived"); + } + assertNotNull(message); + } + catch (Exception e) { + e.printStackTrace(); + } + finally { + try { + connection.close(); + } + catch (JMSException e) { + } + } + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4475Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4475Test.java index 3d11cef335..0e528bde39 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4475Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4475Test.java @@ -52,293 +52,310 @@ import org.junit.Test; public class AMQ4475Test { - private final Log LOG = LogFactory.getLog(AMQ4475Test.class); + private final Log LOG = LogFactory.getLog(AMQ4475Test.class); - private final int NUM_MSGS = 1000; - private final int MAX_THREADS = 20; + private final int NUM_MSGS = 1000; + private final int MAX_THREADS = 20; - private BrokerService broker; - private String connectionUri; + private BrokerService broker; + private String connectionUri; - private final ExecutorService executor = Executors.newFixedThreadPool(MAX_THREADS); - private final ActiveMQQueue original = new ActiveMQQueue("jms/AQueue"); - private final ActiveMQQueue rerouted = new ActiveMQQueue("jms/AQueue_proxy"); + private final ExecutorService executor = Executors.newFixedThreadPool(MAX_THREADS); + private final ActiveMQQueue original = new ActiveMQQueue("jms/AQueue"); + private final ActiveMQQueue rerouted = new ActiveMQQueue("jms/AQueue_proxy"); - @Before - public void setUp() throws Exception { - TimeStampingBrokerPlugin tsbp = new TimeStampingBrokerPlugin(); - tsbp.setZeroExpirationOverride(432000000); - tsbp.setTtlCeiling(432000000); - tsbp.setFutureOnly(true); + @Before + public void setUp() throws Exception { + TimeStampingBrokerPlugin tsbp = new TimeStampingBrokerPlugin(); + tsbp.setZeroExpirationOverride(432000000); + tsbp.setTtlCeiling(432000000); + tsbp.setFutureOnly(true); - broker = new BrokerService(); - broker.setPersistent(false); - broker.setUseJmx(true); - broker.setPlugins(new BrokerPlugin[] {tsbp}); - connectionUri = broker.addConnector("tcp://localhost:0").getPublishableConnectString(); + broker = new BrokerService(); + broker.setPersistent(false); + broker.setUseJmx(true); + broker.setPlugins(new BrokerPlugin[]{tsbp}); + connectionUri = broker.addConnector("tcp://localhost:0").getPublishableConnectString(); - // Configure Dead Letter Strategy - DeadLetterStrategy strategy = new IndividualDeadLetterStrategy(); - strategy.setProcessExpired(true); - ((IndividualDeadLetterStrategy)strategy).setUseQueueForQueueMessages(true); - ((IndividualDeadLetterStrategy)strategy).setQueuePrefix("DLQ."); - strategy.setProcessNonPersistent(true); + // Configure Dead Letter Strategy + DeadLetterStrategy strategy = new IndividualDeadLetterStrategy(); + strategy.setProcessExpired(true); + ((IndividualDeadLetterStrategy) strategy).setUseQueueForQueueMessages(true); + ((IndividualDeadLetterStrategy) strategy).setQueuePrefix("DLQ."); + strategy.setProcessNonPersistent(true); - // Add policy and individual DLQ strategy - PolicyEntry policy = new PolicyEntry(); - policy.setTimeBeforeDispatchStarts(3000); - policy.setDeadLetterStrategy(strategy); + // Add policy and individual DLQ strategy + PolicyEntry policy = new PolicyEntry(); + policy.setTimeBeforeDispatchStarts(3000); + policy.setDeadLetterStrategy(strategy); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); - broker.setDestinationPolicy(pMap); - broker.start(); - broker.waitUntilStarted(); - } + broker.setDestinationPolicy(pMap); + broker.start(); + broker.waitUntilStarted(); + } - @After - public void after() throws Exception { - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - } + @After + public void after() throws Exception { + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + } - @Test - public void testIndividualDeadLetterAndTimeStampPlugin() { - LOG.info("Starting test .."); + @Test + public void testIndividualDeadLetterAndTimeStampPlugin() { + LOG.info("Starting test .."); - long startTime = System.nanoTime(); + long startTime = System.nanoTime(); - // Produce to network - List> tasks = new ArrayList>(); + // Produce to network + List> tasks = new ArrayList>(); - for (int index = 0; index < 1; index++) { - ProducerTask p = new ProducerTask(connectionUri, original, NUM_MSGS); - Future future = executor.submit(p, p); - tasks.add(future); - } + for (int index = 0; index < 1; index++) { + ProducerTask p = new ProducerTask(connectionUri, original, NUM_MSGS); + Future future = executor.submit(p, p); + tasks.add(future); + } - ForwardingConsumerThread f1 = new ForwardingConsumerThread(original, rerouted, NUM_MSGS); - f1.start(); - ConsumerThread c1 = new ConsumerThread(connectionUri, rerouted, NUM_MSGS); - c1.start(); + ForwardingConsumerThread f1 = new ForwardingConsumerThread(original, rerouted, NUM_MSGS); + f1.start(); + ConsumerThread c1 = new ConsumerThread(connectionUri, rerouted, NUM_MSGS); + c1.start(); - LOG.info("Waiting on consumers and producers to exit"); + LOG.info("Waiting on consumers and producers to exit"); - try { - for (Future future : tasks) { - ProducerTask e = future.get(); - LOG.info("[Completed] " + e.dest.getPhysicalName()); + try { + for (Future future : tasks) { + ProducerTask e = future.get(); + LOG.info("[Completed] " + e.dest.getPhysicalName()); + } + executor.shutdown(); + LOG.info("Producing threads complete, waiting on ACKs"); + f1.join(TimeUnit.MINUTES.toMillis(2)); + c1.join(TimeUnit.MINUTES.toMillis(2)); + } + catch (ExecutionException e) { + LOG.warn("Caught unexpected exception: {}", e); + throw new RuntimeException(e); + } + catch (InterruptedException ie) { + LOG.warn("Caught unexpected exception: {}", ie); + throw new RuntimeException(ie); + } + + assertFalse(f1.isFailed()); + assertFalse(c1.isFailed()); + + long estimatedTime = System.nanoTime() - startTime; + + LOG.info("Testcase duration (seconds): " + estimatedTime / 1000000000.0); + LOG.info("Consumers and producers exited, all msgs received as expected"); + } + + public class ProducerTask implements Runnable { + + private final String uri; + private final ActiveMQQueue dest; + private final int count; + + public ProducerTask(String uri, ActiveMQQueue dest, int count) { + this.uri = uri; + this.dest = dest; + this.count = count; + } + + @Override + public void run() { + + Connection connection = null; + try { + String destName = ""; + + try { + destName = dest.getQueueName(); } - executor.shutdown(); - LOG.info("Producing threads complete, waiting on ACKs"); - f1.join(TimeUnit.MINUTES.toMillis(2)); - c1.join(TimeUnit.MINUTES.toMillis(2)); - } catch (ExecutionException e) { + catch (JMSException e) { + LOG.warn("Caught unexpected exception: {}", e); + } + + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(uri); + + connection = connectionFactory.createConnection(); + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(dest); + connection.start(); + + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + + String msg = "Test Message"; + + for (int i = 0; i < count; i++) { + producer.send(session.createTextMessage(msg + dest.getQueueName() + " " + i)); + } + + LOG.info("[" + destName + "] Sent " + count + " msgs"); + } + catch (Exception e) { LOG.warn("Caught unexpected exception: {}", e); - throw new RuntimeException(e); - } catch (InterruptedException ie) { - LOG.warn("Caught unexpected exception: {}", ie); - throw new RuntimeException(ie); - } - - assertFalse(f1.isFailed()); - assertFalse(c1.isFailed()); - - long estimatedTime = System.nanoTime() - startTime; - - LOG.info("Testcase duration (seconds): " + estimatedTime / 1000000000.0); - LOG.info("Consumers and producers exited, all msgs received as expected"); - } - - public class ProducerTask implements Runnable { - private final String uri; - private final ActiveMQQueue dest; - private final int count; - - public ProducerTask(String uri, ActiveMQQueue dest, int count) { - this.uri = uri; - this.dest = dest; - this.count = count; - } - - @Override - public void run() { - - Connection connection = null; + } + finally { try { - String destName = ""; - - try { - destName = dest.getQueueName(); - } catch (JMSException e) { - LOG.warn("Caught unexpected exception: {}", e); - } - - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(uri); - - connection = connectionFactory.createConnection(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(dest); - connection.start(); - - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - - String msg = "Test Message"; - - for (int i = 0; i < count; i++) { - producer.send(session.createTextMessage(msg + dest.getQueueName() + " " + i)); - } - - LOG.info("[" + destName + "] Sent " + count + " msgs"); - } catch (Exception e) { - LOG.warn("Caught unexpected exception: {}", e); - } finally { - try { - connection.close(); - } catch (Throwable e) { - LOG.warn("Caught unexpected exception: {}", e); - } + connection.close(); } - } - } + catch (Throwable e) { + LOG.warn("Caught unexpected exception: {}", e); + } + } + } + } - public class ForwardingConsumerThread extends Thread { + public class ForwardingConsumerThread extends Thread { - private final ActiveMQQueue original; - private final ActiveMQQueue forward; - private int blockSize = 0; - private final int PARALLEL = 1; - private boolean failed; + private final ActiveMQQueue original; + private final ActiveMQQueue forward; + private int blockSize = 0; + private final int PARALLEL = 1; + private boolean failed; - public ForwardingConsumerThread(ActiveMQQueue original, ActiveMQQueue forward, int total) { - this.original = original; - this.forward = forward; - this.blockSize = total / PARALLEL; - } + public ForwardingConsumerThread(ActiveMQQueue original, ActiveMQQueue forward, int total) { + this.original = original; + this.forward = forward; + this.blockSize = total / PARALLEL; + } - public boolean isFailed() { - return failed; - } + public boolean isFailed() { + return failed; + } - @Override - public void run() { - Connection connection = null; - try { + @Override + public void run() { + Connection connection = null; + try { - for (int index = 0; index < PARALLEL; index++) { + for (int index = 0; index < PARALLEL; index++) { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(original); - MessageProducer producer = session.createProducer(forward); - connection.start(); - int count = 0; + connection = factory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(original); + MessageProducer producer = session.createProducer(forward); + connection.start(); + int count = 0; - while (count < blockSize) { + while (count < blockSize) { - Message msg1 = consumer.receive(10000); - if (msg1 != null) { - if (msg1 instanceof ActiveMQTextMessage) { - if (count % 100 == 0) { - LOG.info("Consuming -> " + ((ActiveMQTextMessage) msg1).getDestination() + " count=" + count); - } - - producer.send(msg1); - - count++; - } else { - LOG.info("Skipping unknown msg type " + msg1); - } - } else { - break; + Message msg1 = consumer.receive(10000); + if (msg1 != null) { + if (msg1 instanceof ActiveMQTextMessage) { + if (count % 100 == 0) { + LOG.info("Consuming -> " + ((ActiveMQTextMessage) msg1).getDestination() + " count=" + count); } - } - LOG.info("[" + original.getQueueName() + "] completed segment (" + index + " of " + blockSize + ")"); - connection.close(); - } - } catch (Exception e) { - LOG.warn("Caught unexpected exception: {}", e); - } finally { - LOG.debug(getName() + ": is stopping"); - try { - connection.close(); - } catch (Throwable e) { - } + producer.send(msg1); + + count++; + } + else { + LOG.info("Skipping unknown msg type " + msg1); + } + } + else { + break; + } + } + + LOG.info("[" + original.getQueueName() + "] completed segment (" + index + " of " + blockSize + ")"); + connection.close(); } - } - } - - public class ConsumerThread extends Thread { - - private final String uri; - private final ActiveMQQueue dest; - private int blockSize = 0; - private final int PARALLEL = 1; - private boolean failed; - - public ConsumerThread(String uri, ActiveMQQueue dest, int total) { - this.uri = uri; - this.dest = dest; - this.blockSize = total / PARALLEL; - } - - public boolean isFailed() { - return failed; - } - - @Override - public void run() { - Connection connection = null; + } + catch (Exception e) { + LOG.warn("Caught unexpected exception: {}", e); + } + finally { + LOG.debug(getName() + ": is stopping"); try { - - for (int index = 0; index < PARALLEL; index++) { - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(uri); - - connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(dest); - connection.start(); - int count = 0; - - while (count < blockSize) { - - Object msg1 = consumer.receive(10000); - if (msg1 != null) { - if (msg1 instanceof ActiveMQTextMessage) { - if (count % 100 == 0) { - LOG.info("Consuming -> " + ((ActiveMQTextMessage) msg1).getDestination() + " count=" + count); - } - - count++; - } else { - LOG.info("Skipping unknown msg type " + msg1); - } - } else { - failed = true; - break; - } - } - - LOG.info("[" + dest.getQueueName() + "] completed segment (" + index + " of " + blockSize + ")"); - connection.close(); - } - } catch (Exception e) { - LOG.warn("Caught unexpected exception: {}", e); - } finally { - LOG.debug(getName() + ": is stopping"); - try { - connection.close(); - } catch (Throwable e) { - } + connection.close(); } - } - } + catch (Throwable e) { + } + } + } + } + + public class ConsumerThread extends Thread { + + private final String uri; + private final ActiveMQQueue dest; + private int blockSize = 0; + private final int PARALLEL = 1; + private boolean failed; + + public ConsumerThread(String uri, ActiveMQQueue dest, int total) { + this.uri = uri; + this.dest = dest; + this.blockSize = total / PARALLEL; + } + + public boolean isFailed() { + return failed; + } + + @Override + public void run() { + Connection connection = null; + try { + + for (int index = 0; index < PARALLEL; index++) { + + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(uri); + + connection = factory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(dest); + connection.start(); + int count = 0; + + while (count < blockSize) { + + Object msg1 = consumer.receive(10000); + if (msg1 != null) { + if (msg1 instanceof ActiveMQTextMessage) { + if (count % 100 == 0) { + LOG.info("Consuming -> " + ((ActiveMQTextMessage) msg1).getDestination() + " count=" + count); + } + + count++; + } + else { + LOG.info("Skipping unknown msg type " + msg1); + } + } + else { + failed = true; + break; + } + } + + LOG.info("[" + dest.getQueueName() + "] completed segment (" + index + " of " + blockSize + ")"); + connection.close(); + } + } + catch (Exception e) { + LOG.warn("Caught unexpected exception: {}", e); + } + finally { + LOG.debug(getName() + ": is stopping"); + try { + connection.close(); + } + catch (Throwable e) { + } + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4485LowLimitLevelDBTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4485LowLimitLevelDBTest.java index 5a485404c8..1a320c2c5a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4485LowLimitLevelDBTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4485LowLimitLevelDBTest.java @@ -17,22 +17,23 @@ package org.apache.activemq.bugs; import java.io.File; + import org.apache.activemq.broker.BrokerService; import org.apache.activemq.leveldb.LevelDBStore; public class AMQ4485LowLimitLevelDBTest extends AMQ4485LowLimitTest { - public AMQ4485LowLimitLevelDBTest() { - super(); - numBrokers = 2; - } + public AMQ4485LowLimitLevelDBTest() { + super(); + numBrokers = 2; + } - protected BrokerService createBroker(int brokerid, boolean addToNetwork) throws Exception { - BrokerService broker = super.createBroker(brokerid, addToNetwork); + protected BrokerService createBroker(int brokerid, boolean addToNetwork) throws Exception { + BrokerService broker = super.createBroker(brokerid, addToNetwork); - LevelDBStore levelDBStore = new LevelDBStore(); - levelDBStore.setDirectory(new File(broker.getBrokerDataDirectory(),"levelDB")); - broker.setPersistenceAdapter(levelDBStore); - return broker; - } + LevelDBStore levelDBStore = new LevelDBStore(); + levelDBStore.setDirectory(new File(broker.getBrokerDataDirectory(), "levelDB")); + broker.setPersistenceAdapter(levelDBStore); + return broker; + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4485LowLimitTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4485LowLimitTest.java index 7c549b4ba0..20c3b077f6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4485LowLimitTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4485LowLimitTest.java @@ -40,6 +40,7 @@ import javax.jms.QueueSession; import javax.jms.Session; import javax.jms.TextMessage; import javax.management.ObjectName; + import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.JmsMultipleBrokersTestSupport; @@ -61,406 +62,412 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AMQ4485LowLimitTest extends JmsMultipleBrokersTestSupport { - static final String payload = new String(new byte[10 * 1024]); - private static final Logger LOG = LoggerFactory.getLogger(AMQ4485LowLimitTest.class); - final int portBase = 61600; - int numBrokers = 8; - final int numProducers = 30; - final int numMessages = 1000; - final int consumerSleepTime = 40; - StringBuilder brokersUrl = new StringBuilder(); - HashMap accumulators = new HashMap(); - private ArrayList exceptions = new ArrayList(); - protected void buildUrlList() throws Exception { - for (int i = 0; i < numBrokers; i++) { - brokersUrl.append("tcp://localhost:" + (portBase + i)); - if (i != numBrokers - 1) { - brokersUrl.append(','); + static final String payload = new String(new byte[10 * 1024]); + private static final Logger LOG = LoggerFactory.getLogger(AMQ4485LowLimitTest.class); + final int portBase = 61600; + int numBrokers = 8; + final int numProducers = 30; + final int numMessages = 1000; + final int consumerSleepTime = 40; + StringBuilder brokersUrl = new StringBuilder(); + HashMap accumulators = new HashMap(); + private ArrayList exceptions = new ArrayList(); + + protected void buildUrlList() throws Exception { + for (int i = 0; i < numBrokers; i++) { + brokersUrl.append("tcp://localhost:" + (portBase + i)); + if (i != numBrokers - 1) { + brokersUrl.append(','); + } + } + } + + protected BrokerService createBroker(int brokerid) throws Exception { + return createBroker(brokerid, true); + } + + protected BrokerService createBroker(int brokerid, boolean addToNetwork) throws Exception { + + BrokerService broker = new BrokerService(); + broker.setPersistent(true); + broker.setDeleteAllMessagesOnStartup(true); + broker.getManagementContext().setCreateConnector(false); + + broker.setUseJmx(true); + broker.setBrokerName("B" + brokerid); + broker.addConnector(new URI("tcp://localhost:" + (portBase + brokerid))); + + if (addToNetwork) { + addNetworkConnector(broker); + } + broker.setSchedulePeriodForDestinationPurge(0); + broker.getSystemUsage().getMemoryUsage().setLimit(256 * 1024 * 1024L); + + PolicyMap policyMap = new PolicyMap(); + PolicyEntry policyEntry = new PolicyEntry(); + policyEntry.setExpireMessagesPeriod(0); + policyEntry.setQueuePrefetch(1000); + policyEntry.setMemoryLimit(2 * 1024 * 1024L); + policyEntry.setProducerFlowControl(false); + policyEntry.setEnableAudit(true); + policyEntry.setUseCache(true); + policyMap.put(new ActiveMQQueue("GW.>"), policyEntry); + + PolicyEntry inPolicyEntry = new PolicyEntry(); + inPolicyEntry.setExpireMessagesPeriod(0); + inPolicyEntry.setQueuePrefetch(1000); + inPolicyEntry.setMemoryLimit(5 * 1024 * 1024L); + inPolicyEntry.setProducerFlowControl(true); + inPolicyEntry.setEnableAudit(true); + inPolicyEntry.setUseCache(true); + policyMap.put(new ActiveMQQueue("IN"), inPolicyEntry); + + broker.setDestinationPolicy(policyMap); + + KahaDBPersistenceAdapter kahaDBPersistenceAdapter = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); + kahaDBPersistenceAdapter.setConcurrentStoreAndDispatchQueues(true); + + brokers.put(broker.getBrokerName(), new BrokerItem(broker)); + return broker; + } + + private void addNetworkConnector(BrokerService broker) throws Exception { + StringBuilder networkConnectorUrl = new StringBuilder("static:(").append(brokersUrl.toString()); + networkConnectorUrl.append(')'); + + for (int i = 0; i < 2; i++) { + NetworkConnector nc = new DiscoveryNetworkConnector(new URI(networkConnectorUrl.toString())); + nc.setName("Bridge-" + i); + nc.setNetworkTTL(1); + nc.setDecreaseNetworkConsumerPriority(true); + nc.setDynamicOnly(true); + nc.setPrefetchSize(100); + nc.setDynamicallyIncludedDestinations(Arrays.asList(new ActiveMQDestination[]{new ActiveMQQueue("GW.*")})); + broker.addNetworkConnector(nc); + } + } + + // used to explore contention with concurrentStoreandDispatch - sync commit and task queue reversing + // order of cursor add and sequence assignment + public void x_testInterleavedSend() throws Exception { + + BrokerService b = createBroker(0, false); + b.start(); + + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:" + (portBase + 0)); + connectionFactory.setWatchTopicAdvisories(false); + + QueueConnection c1 = connectionFactory.createQueueConnection(); + QueueConnection c2 = connectionFactory.createQueueConnection(); + QueueConnection c3 = connectionFactory.createQueueConnection(); + + c1.start(); + c2.start(); + c3.start(); + + ActiveMQQueue dest = new ActiveMQQueue("IN"); + final Session s1 = c1.createQueueSession(true, Session.SESSION_TRANSACTED); + final TextMessage txMessage = s1.createTextMessage("TX"); + final TextMessage noTxMessage = s1.createTextMessage("NO_TX"); + + final MessageProducer txProducer = s1.createProducer(dest); + final MessageProducer nonTxProducer = c2.createQueueSession(false, Session.AUTO_ACKNOWLEDGE).createProducer(dest); + + txProducer.send(txMessage); + + ExecutorService executorService = Executors.newFixedThreadPool(2); + executorService.execute(new Runnable() { + @Override + public void run() { + try { + s1.commit(); } - } - } + catch (JMSException e) { + e.printStackTrace(); + } + } + }); - protected BrokerService createBroker(int brokerid) throws Exception { - return createBroker(brokerid, true); - } + executorService.execute(new Runnable() { + @Override + public void run() { + try { + nonTxProducer.send(noTxMessage); + } + catch (JMSException e) { + e.printStackTrace(); + } + } + }); - protected BrokerService createBroker(int brokerid, boolean addToNetwork) throws Exception { + executorService.shutdown(); + executorService.awaitTermination(10, TimeUnit.MINUTES); - BrokerService broker = new BrokerService(); - broker.setPersistent(true); - broker.setDeleteAllMessagesOnStartup(true); - broker.getManagementContext().setCreateConnector(false); + } + public void testBrokers() throws Exception { - broker.setUseJmx(true); - broker.setBrokerName("B" + brokerid); - broker.addConnector(new URI("tcp://localhost:" + (portBase + brokerid))); + buildUrlList(); - if (addToNetwork) { - addNetworkConnector(broker); - } - broker.setSchedulePeriodForDestinationPurge(0); - broker.getSystemUsage().getMemoryUsage().setLimit(256 * 1024 * 1024L); + for (int i = 0; i < numBrokers; i++) { + createBroker(i); + } + startAllBrokers(); + waitForBridgeFormation(numBrokers - 1); - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policyEntry = new PolicyEntry(); - policyEntry.setExpireMessagesPeriod(0); - policyEntry.setQueuePrefetch(1000); - policyEntry.setMemoryLimit(2 * 1024 * 1024L); - policyEntry.setProducerFlowControl(false); - policyEntry.setEnableAudit(true); - policyEntry.setUseCache(true); - policyMap.put(new ActiveMQQueue("GW.>"), policyEntry); + verifyPeerBrokerInfos(numBrokers - 1); - PolicyEntry inPolicyEntry = new PolicyEntry(); - inPolicyEntry.setExpireMessagesPeriod(0); - inPolicyEntry.setQueuePrefetch(1000); - inPolicyEntry.setMemoryLimit(5 * 1024 * 1024L); - inPolicyEntry.setProducerFlowControl(true); - inPolicyEntry.setEnableAudit(true); - inPolicyEntry.setUseCache(true); - policyMap.put(new ActiveMQQueue("IN"), inPolicyEntry); + final List consumerStates = startAllGWConsumers(numBrokers); - broker.setDestinationPolicy(policyMap); + startAllGWFanoutConsumers(numBrokers); - KahaDBPersistenceAdapter kahaDBPersistenceAdapter = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); - kahaDBPersistenceAdapter.setConcurrentStoreAndDispatchQueues(true); + LOG.info("Waiting for percolation of consumers.."); + TimeUnit.SECONDS.sleep(5); - brokers.put(broker.getBrokerName(), new BrokerItem(broker)); - return broker; - } + LOG.info("Produce mesages.."); + long startTime = System.currentTimeMillis(); - private void addNetworkConnector(BrokerService broker) throws Exception { - StringBuilder networkConnectorUrl = new StringBuilder("static:(").append(brokersUrl.toString()); - networkConnectorUrl.append(')'); + // produce + produce(numMessages); - for (int i = 0; i < 2; i++) { - NetworkConnector nc = new DiscoveryNetworkConnector(new URI(networkConnectorUrl.toString())); - nc.setName("Bridge-" + i); - nc.setNetworkTTL(1); - nc.setDecreaseNetworkConsumerPriority(true); - nc.setDynamicOnly(true); - nc.setPrefetchSize(100); - nc.setDynamicallyIncludedDestinations( - Arrays.asList(new ActiveMQDestination[]{new ActiveMQQueue("GW.*")})); - broker.addNetworkConnector(nc); - } - } + assertTrue("Got all sent", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + for (ConsumerState tally : consumerStates) { + final int expected = numMessages * (tally.destination.isComposite() ? tally.destination.getCompositeDestinations().length : 1); + LOG.info("Tally for: " + tally.brokerName + ", dest: " + tally.destination + " - " + tally.accumulator.get()); + if (tally.accumulator.get() != expected) { + LOG.info("Tally for: " + tally.brokerName + ", dest: " + tally.destination + " - " + tally.accumulator.get() + " != " + expected + ", " + tally.expected); + if (tally.accumulator.get() > expected - 50) { + dumpQueueStat(null); + } + if (tally.expected.size() == 1) { + startConsumer(tally.brokerName, tally.destination); + } + ; + return false; + } + LOG.info("got tally on " + tally.brokerName); + } + return true; + } + }, 1000 * 60 * 1000L, 20 * 1000)); - // used to explore contention with concurrentStoreandDispatch - sync commit and task queue reversing - // order of cursor add and sequence assignment - public void x_testInterleavedSend() throws Exception { + assertTrue("No exceptions:" + exceptions, exceptions.isEmpty()); - BrokerService b = createBroker(0, false); - b.start(); + LOG.info("done"); + long duration = System.currentTimeMillis() - startTime; + LOG.info("Duration:" + TimeUtils.printDuration(duration)); - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:" + (portBase + 0)); - connectionFactory.setWatchTopicAdvisories(false); + assertEquals("nothing in the dlq's", 0, dumpQueueStat(new ActiveMQQueue("ActiveMQ.DLQ"))); - QueueConnection c1 = connectionFactory.createQueueConnection(); - QueueConnection c2 = connectionFactory.createQueueConnection(); - QueueConnection c3 = connectionFactory.createQueueConnection(); + } - c1.start(); - c2.start(); - c3.start(); + private void startConsumer(String brokerName, ActiveMQDestination destination) throws Exception { + int id = Integer.parseInt(brokerName.substring(1)); + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:" + (portBase + id)); + connectionFactory.setWatchTopicAdvisories(false); + QueueConnection queueConnection = connectionFactory.createQueueConnection(); + queueConnection.start(); - ActiveMQQueue dest = new ActiveMQQueue("IN"); - final Session s1 = c1.createQueueSession(true, Session.SESSION_TRANSACTED); - final TextMessage txMessage = s1.createTextMessage("TX"); - final TextMessage noTxMessage = s1.createTextMessage("NO_TX"); + queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE).createConsumer(destination); + queueConnection.close(); + } - final MessageProducer txProducer = s1.createProducer(dest); - final MessageProducer nonTxProducer = c2.createQueueSession(false, Session.AUTO_ACKNOWLEDGE).createProducer(dest); + private long dumpQueueStat(ActiveMQDestination destination) throws Exception { + long sumTotal = 0; + Collection brokerList = brokers.values(); + for (Iterator i = brokerList.iterator(); i.hasNext(); ) { + BrokerService brokerService = i.next().broker; + for (ObjectName objectName : brokerService.getAdminView().getQueues()) { + if (destination != null && objectName.toString().contains(destination.getPhysicalName())) { + QueueViewMBean qViewMBean = (QueueViewMBean) brokerService.getManagementContext().newProxyInstance(objectName, QueueViewMBean.class, false); + LOG.info(brokerService.getBrokerName() + ", " + qViewMBean.getName() + ", Enqueue:" + qViewMBean.getEnqueueCount() + ", Size: " + qViewMBean.getQueueSize()); + sumTotal += qViewMBean.getQueueSize(); + } + } + } + return sumTotal; + } - txProducer.send(txMessage); + private void startAllGWFanoutConsumers(int nBrokers) throws Exception { - ExecutorService executorService = Executors.newFixedThreadPool(2); - executorService.execute(new Runnable() { + StringBuffer compositeDest = new StringBuffer(); + for (int k = 0; k < nBrokers; k++) { + compositeDest.append("GW." + k); + if (k + 1 != nBrokers) { + compositeDest.append(','); + } + } + ActiveMQQueue compositeQ = new ActiveMQQueue(compositeDest.toString()); + + for (int id = 0; id < nBrokers; id++) { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(tcp://localhost:" + (portBase + id) + ")"); + connectionFactory.setWatchTopicAdvisories(false); + + QueueConnection queueConnection = connectionFactory.createQueueConnection(); + queueConnection.start(); + + final QueueSession queueSession = queueConnection.createQueueSession(true, Session.SESSION_TRANSACTED); + + final MessageProducer producer = queueSession.createProducer(compositeQ); + queueSession.createReceiver(new ActiveMQQueue("IN")).setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + try { + producer.send(message); + queueSession.commit(); + } + catch (Exception e) { + LOG.error("Failed to fanout to GW: " + message, e); + } + + } + }); + } + } + + private List startAllGWConsumers(int nBrokers) throws Exception { + List consumerStates = new LinkedList(); + for (int id = 0; id < nBrokers; id++) { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(tcp://localhost:" + (portBase + id) + ")"); + connectionFactory.setWatchTopicAdvisories(false); + + QueueConnection queueConnection = connectionFactory.createQueueConnection(); + queueConnection.start(); + + final QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); + + ActiveMQQueue destination = new ActiveMQQueue("GW." + id); + QueueReceiver queueReceiver = queueSession.createReceiver(destination); + + final ConsumerState consumerState = new ConsumerState(); + consumerState.brokerName = ((ActiveMQConnection) queueConnection).getBrokerName(); + consumerState.receiver = queueReceiver; + consumerState.destination = destination; + for (int j = 0; j < numMessages * (consumerState.destination.isComposite() ? consumerState.destination.getCompositeDestinations().length : 1); j++) { + consumerState.expected.add(j); + } + + if (!accumulators.containsKey(destination)) { + accumulators.put(destination, new AtomicInteger(0)); + } + consumerState.accumulator = accumulators.get(destination); + + queueReceiver.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + try { + if (consumerSleepTime > 0) { + TimeUnit.MILLISECONDS.sleep(consumerSleepTime); + } + } + catch (InterruptedException e) { + e.printStackTrace(); + } + try { + consumerState.accumulator.incrementAndGet(); + try { + consumerState.expected.remove(((ActiveMQMessage) message).getProperty("NUM")); + } + catch (IOException e) { + e.printStackTrace(); + } + //queueSession.commit(); + } + catch (Exception e) { + LOG.error("Failed to commit slow receipt of " + message, e); + } + } + }); + + consumerStates.add(consumerState); + + } + return consumerStates; + } + + private void produce(final int numMessages) throws Exception { + ExecutorService executorService = Executors.newFixedThreadPool(numProducers); + final AtomicInteger toSend = new AtomicInteger(numMessages); + for (int i = 1; i <= numProducers; i++) { + final int id = i % numBrokers; + executorService.execute(new Runnable() { @Override public void run() { - try { - s1.commit(); - } catch (JMSException e) { - e.printStackTrace(); - } + try { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(tcp://localhost:" + (portBase + id) + ")"); + connectionFactory.setWatchTopicAdvisories(false); + QueueConnection queueConnection = connectionFactory.createQueueConnection(); + queueConnection.start(); + QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = queueSession.createProducer(null); + int val = 0; + while ((val = toSend.decrementAndGet()) >= 0) { + + int id = numMessages - val - 1; + + ActiveMQQueue compositeQ = new ActiveMQQueue("IN"); + Message textMessage = queueSession.createTextMessage(((ActiveMQConnection) queueConnection).getBrokerName() + "->" + id + " payload:" + payload); + textMessage.setIntProperty("NUM", id); + producer.send(compositeQ, textMessage); + } + queueConnection.close(); + + } + catch (Throwable throwable) { + throwable.printStackTrace(); + exceptions.add(throwable); + } } - }); + }); + } + } - executorService.execute(new Runnable() { - @Override - public void run() { - try { - nonTxProducer.send(noTxMessage); - } catch (JMSException e) { - e.printStackTrace(); - } - } - }); + private void verifyPeerBrokerInfo(BrokerItem brokerItem, final int max) throws Exception { + final BrokerService broker = brokerItem.broker; + final RegionBroker regionBroker = (RegionBroker) broker.getRegionBroker(); + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("verify infos " + broker.getBrokerName() + ", len: " + regionBroker.getPeerBrokerInfos().length); + return max == regionBroker.getPeerBrokerInfos().length; + } + }); + LOG.info("verify infos " + broker.getBrokerName() + ", len: " + regionBroker.getPeerBrokerInfos().length); + List missing = new ArrayList(); + for (int i = 0; i < max; i++) { + missing.add("B" + i); + } + if (max != regionBroker.getPeerBrokerInfos().length) { + for (BrokerInfo info : regionBroker.getPeerBrokerInfos()) { + LOG.info(info.getBrokerName()); + missing.remove(info.getBrokerName()); + } + LOG.info("Broker infos off.." + missing); + } + assertEquals(broker.getBrokerName(), max, regionBroker.getPeerBrokerInfos().length); + } - executorService.shutdown(); - executorService.awaitTermination(10, TimeUnit.MINUTES); + private void verifyPeerBrokerInfos(final int max) throws Exception { + Collection brokerList = brokers.values(); + for (Iterator i = brokerList.iterator(); i.hasNext(); ) { + verifyPeerBrokerInfo(i.next(), max); + } + } - } + protected void tearDown() throws Exception { + super.tearDown(); + } - public void testBrokers() throws Exception { + class ConsumerState { - buildUrlList(); - - for (int i = 0; i < numBrokers; i++) { - createBroker(i); - } - - startAllBrokers(); - waitForBridgeFormation(numBrokers - 1); - - verifyPeerBrokerInfos(numBrokers - 1); - - - final List consumerStates = startAllGWConsumers(numBrokers); - - startAllGWFanoutConsumers(numBrokers); - - LOG.info("Waiting for percolation of consumers.."); - TimeUnit.SECONDS.sleep(5); - - LOG.info("Produce mesages.."); - long startTime = System.currentTimeMillis(); - - // produce - produce(numMessages); - - assertTrue("Got all sent", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - for (ConsumerState tally : consumerStates) { - final int expected = numMessages * (tally.destination.isComposite() ? tally.destination.getCompositeDestinations().length : 1); - LOG.info("Tally for: " + tally.brokerName + ", dest: " + tally.destination + " - " + tally.accumulator.get()); - if (tally.accumulator.get() != expected) { - LOG.info("Tally for: " + tally.brokerName + ", dest: " + tally.destination + " - " + tally.accumulator.get() + " != " + expected + ", " + tally.expected); - if (tally.accumulator.get() > expected - 50) { - dumpQueueStat(null); - } - if (tally.expected.size() == 1) { - startConsumer(tally.brokerName, tally.destination); - }; - return false; - } - LOG.info("got tally on " + tally.brokerName); - } - return true; - } - }, 1000 * 60 * 1000L, 20*1000)); - - assertTrue("No exceptions:" + exceptions, exceptions.isEmpty()); - - LOG.info("done"); - long duration = System.currentTimeMillis() - startTime; - LOG.info("Duration:" + TimeUtils.printDuration(duration)); - - assertEquals("nothing in the dlq's", 0, dumpQueueStat(new ActiveMQQueue("ActiveMQ.DLQ"))); - - } - - private void startConsumer(String brokerName, ActiveMQDestination destination) throws Exception { - int id = Integer.parseInt(brokerName.substring(1)); - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:" + (portBase + id)); - connectionFactory.setWatchTopicAdvisories(false); - QueueConnection queueConnection = connectionFactory.createQueueConnection(); - queueConnection.start(); - - queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE).createConsumer(destination); - queueConnection.close(); - } - - private long dumpQueueStat(ActiveMQDestination destination) throws Exception { - long sumTotal = 0; - Collection brokerList = brokers.values(); - for (Iterator i = brokerList.iterator(); i.hasNext(); ) { - BrokerService brokerService = i.next().broker; - for (ObjectName objectName : brokerService.getAdminView().getQueues()) { - if (destination != null && objectName.toString().contains(destination.getPhysicalName())) { - QueueViewMBean qViewMBean = (QueueViewMBean) brokerService.getManagementContext().newProxyInstance(objectName, QueueViewMBean.class, false); - LOG.info(brokerService.getBrokerName() + ", " + qViewMBean.getName() + ", Enqueue:" + qViewMBean.getEnqueueCount() + ", Size: " + qViewMBean.getQueueSize()); - sumTotal += qViewMBean.getQueueSize(); - } - } - } - return sumTotal; - } - - private void startAllGWFanoutConsumers(int nBrokers) throws Exception { - - StringBuffer compositeDest = new StringBuffer(); - for (int k = 0; k < nBrokers; k++) { - compositeDest.append("GW." + k); - if (k + 1 != nBrokers) { - compositeDest.append(','); - } - } - ActiveMQQueue compositeQ = new ActiveMQQueue(compositeDest.toString()); - - for (int id = 0; id < nBrokers; id++) { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(tcp://localhost:" + (portBase + id) + ")"); - connectionFactory.setWatchTopicAdvisories(false); - - QueueConnection queueConnection = connectionFactory.createQueueConnection(); - queueConnection.start(); - - final QueueSession queueSession = queueConnection.createQueueSession(true, Session.SESSION_TRANSACTED); - - final MessageProducer producer = queueSession.createProducer(compositeQ); - queueSession.createReceiver(new ActiveMQQueue("IN")).setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - try { - producer.send(message); - queueSession.commit(); - } catch (Exception e) { - LOG.error("Failed to fanout to GW: " + message, e); - } - - } - }); - } - } - - private List startAllGWConsumers(int nBrokers) throws Exception { - List consumerStates = new LinkedList(); - for (int id = 0; id < nBrokers; id++) { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(tcp://localhost:" + (portBase + id) + ")"); - connectionFactory.setWatchTopicAdvisories(false); - - QueueConnection queueConnection = connectionFactory.createQueueConnection(); - queueConnection.start(); - - final QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); - - ActiveMQQueue destination = new ActiveMQQueue("GW." + id); - QueueReceiver queueReceiver = queueSession.createReceiver(destination); - - final ConsumerState consumerState = new ConsumerState(); - consumerState.brokerName = ((ActiveMQConnection) queueConnection).getBrokerName(); - consumerState.receiver = queueReceiver; - consumerState.destination = destination; - for (int j = 0; j < numMessages * (consumerState.destination.isComposite() ? consumerState.destination.getCompositeDestinations().length : 1); j++) { - consumerState.expected.add(j); - } - - if (!accumulators.containsKey(destination)) { - accumulators.put(destination, new AtomicInteger(0)); - } - consumerState.accumulator = accumulators.get(destination); - - queueReceiver.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - try { - if (consumerSleepTime > 0) { - TimeUnit.MILLISECONDS.sleep(consumerSleepTime); - } - } catch (InterruptedException e) { - e.printStackTrace(); - } - try { - consumerState.accumulator.incrementAndGet(); - try { - consumerState.expected.remove(((ActiveMQMessage) message).getProperty("NUM")); - } catch (IOException e) { - e.printStackTrace(); - } - //queueSession.commit(); - } catch (Exception e) { - LOG.error("Failed to commit slow receipt of " + message, e); - } - } - }); - - consumerStates.add(consumerState); - - } - return consumerStates; - } - - private void produce(final int numMessages) throws Exception { - ExecutorService executorService = Executors.newFixedThreadPool(numProducers); - final AtomicInteger toSend = new AtomicInteger(numMessages); - for (int i = 1; i <= numProducers; i++) { - final int id = i % numBrokers; - executorService.execute(new Runnable() { - @Override - public void run() { - try { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(tcp://localhost:" + (portBase + id) + ")"); - connectionFactory.setWatchTopicAdvisories(false); - QueueConnection queueConnection = connectionFactory.createQueueConnection(); - queueConnection.start(); - QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = queueSession.createProducer(null); - int val = 0; - while ((val = toSend.decrementAndGet()) >= 0) { - - int id = numMessages - val - 1; - - ActiveMQQueue compositeQ = new ActiveMQQueue("IN"); - Message textMessage = queueSession.createTextMessage(((ActiveMQConnection) queueConnection).getBrokerName() + "->" + id + " payload:" + payload); - textMessage.setIntProperty("NUM", id); - producer.send(compositeQ, textMessage); - } - queueConnection.close(); - - } catch (Throwable throwable) { - throwable.printStackTrace(); - exceptions.add(throwable); - } - } - }); - } - } - - private void verifyPeerBrokerInfo(BrokerItem brokerItem, final int max) throws Exception { - final BrokerService broker = brokerItem.broker; - final RegionBroker regionBroker = (RegionBroker) broker.getRegionBroker(); - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("verify infos " + broker.getBrokerName() + ", len: " + regionBroker.getPeerBrokerInfos().length); - return max == regionBroker.getPeerBrokerInfos().length; - } - }); - LOG.info("verify infos " + broker.getBrokerName() + ", len: " + regionBroker.getPeerBrokerInfos().length); - List missing = new ArrayList(); - for (int i = 0; i < max; i++) { - missing.add("B" + i); - } - if (max != regionBroker.getPeerBrokerInfos().length) { - for (BrokerInfo info : regionBroker.getPeerBrokerInfos()) { - LOG.info(info.getBrokerName()); - missing.remove(info.getBrokerName()); - } - LOG.info("Broker infos off.." + missing); - } - assertEquals(broker.getBrokerName(), max, regionBroker.getPeerBrokerInfos().length); - } - - private void verifyPeerBrokerInfos(final int max) throws Exception { - Collection brokerList = brokers.values(); - for (Iterator i = brokerList.iterator(); i.hasNext(); ) { - verifyPeerBrokerInfo(i.next(), max); - } - } - - protected void tearDown() throws Exception { - super.tearDown(); - } - - class ConsumerState { - AtomicInteger accumulator; - String brokerName; - QueueReceiver receiver; - ActiveMQDestination destination; - ConcurrentLinkedQueue expected = new ConcurrentLinkedQueue(); - } + AtomicInteger accumulator; + String brokerName; + QueueReceiver receiver; + ActiveMQDestination destination; + ConcurrentLinkedQueue expected = new ConcurrentLinkedQueue(); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4485NetworkOfXBrokersWithNDestsFanoutTransactionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4485NetworkOfXBrokersWithNDestsFanoutTransactionTest.java index 8e4e4b7a96..40459bcb97 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4485NetworkOfXBrokersWithNDestsFanoutTransactionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4485NetworkOfXBrokersWithNDestsFanoutTransactionTest.java @@ -37,6 +37,7 @@ import javax.jms.QueueConnection; import javax.jms.QueueReceiver; import javax.jms.QueueSession; import javax.jms.Session; + import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.JmsMultipleBrokersTestSupport; @@ -57,297 +58,300 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AMQ4485NetworkOfXBrokersWithNDestsFanoutTransactionTest extends JmsMultipleBrokersTestSupport { - static final String payload = new String(new byte[10 * 1024]); - private static final Logger LOG = LoggerFactory.getLogger(AMQ4485NetworkOfXBrokersWithNDestsFanoutTransactionTest.class); - final int portBase = 61600; - final int numBrokers = 4; - final int numProducers = 10; - final int numMessages = 800; - final int consumerSleepTime = 20; - StringBuilder brokersUrl = new StringBuilder(); - HashMap accumulators = new HashMap(); - private ArrayList exceptions = new ArrayList(); - protected void buildUrlList() throws Exception { - for (int i = 0; i < numBrokers; i++) { - brokersUrl.append("tcp://localhost:" + (portBase + i)); - if (i != numBrokers - 1) { - brokersUrl.append(','); + static final String payload = new String(new byte[10 * 1024]); + private static final Logger LOG = LoggerFactory.getLogger(AMQ4485NetworkOfXBrokersWithNDestsFanoutTransactionTest.class); + final int portBase = 61600; + final int numBrokers = 4; + final int numProducers = 10; + final int numMessages = 800; + final int consumerSleepTime = 20; + StringBuilder brokersUrl = new StringBuilder(); + HashMap accumulators = new HashMap(); + private ArrayList exceptions = new ArrayList(); + + protected void buildUrlList() throws Exception { + for (int i = 0; i < numBrokers; i++) { + brokersUrl.append("tcp://localhost:" + (portBase + i)); + if (i != numBrokers - 1) { + brokersUrl.append(','); + } + } + } + + protected BrokerService createBroker(int brokerid) throws Exception { + BrokerService broker = new BrokerService(); + broker.setPersistent(true); + broker.setDeleteAllMessagesOnStartup(true); + broker.getManagementContext().setCreateConnector(false); + + broker.setUseJmx(true); + broker.setBrokerName("B" + brokerid); + broker.addConnector(new URI("tcp://localhost:" + (portBase + brokerid))); + + addNetworkConnector(broker); + broker.setSchedulePeriodForDestinationPurge(0); + broker.getSystemUsage().setSendFailIfNoSpace(true); + broker.getSystemUsage().getMemoryUsage().setLimit(512 * 1024 * 1024); + + PolicyMap policyMap = new PolicyMap(); + PolicyEntry policyEntry = new PolicyEntry(); + policyEntry.setExpireMessagesPeriod(0); + policyEntry.setQueuePrefetch(1000); + policyEntry.setMemoryLimit(1024 * 1024L); + policyEntry.setOptimizedDispatch(false); + policyEntry.setProducerFlowControl(false); + policyEntry.setEnableAudit(true); + policyEntry.setUseCache(true); + policyMap.put(new ActiveMQQueue("GW.>"), policyEntry); + broker.setDestinationPolicy(policyMap); + + KahaDBPersistenceAdapter kahaDBPersistenceAdapter = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); + kahaDBPersistenceAdapter.setConcurrentStoreAndDispatchQueues(false); + + brokers.put(broker.getBrokerName(), new BrokerItem(broker)); + return broker; + } + + private void addNetworkConnector(BrokerService broker) throws Exception { + StringBuilder networkConnectorUrl = new StringBuilder("static:(").append(brokersUrl.toString()); + networkConnectorUrl.append(')'); + + for (int i = 0; i < 2; i++) { + NetworkConnector nc = new DiscoveryNetworkConnector(new URI(networkConnectorUrl.toString())); + nc.setName("Bridge-" + i); + nc.setNetworkTTL(1); + nc.setDecreaseNetworkConsumerPriority(true); + nc.setDynamicOnly(true); + nc.setPrefetchSize(100); + nc.setDynamicallyIncludedDestinations(Arrays.asList(new ActiveMQDestination[]{new ActiveMQQueue("GW.*")})); + broker.addNetworkConnector(nc); + } + } + + public void testBrokers() throws Exception { + + buildUrlList(); + + for (int i = 0; i < numBrokers; i++) { + createBroker(i); + } + + startAllBrokers(); + waitForBridgeFormation(numBrokers - 1); + + verifyPeerBrokerInfos(numBrokers - 1); + + final List consumerStates = startAllGWConsumers(numBrokers); + + startAllGWFanoutConsumers(numBrokers); + + LOG.info("Waiting for percolation of consumers.."); + TimeUnit.SECONDS.sleep(5); + + LOG.info("Produce mesages.."); + long startTime = System.currentTimeMillis(); + + // produce + produce(numMessages); + + assertTrue("Got all sent", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + for (ConsumerState tally : consumerStates) { + final int expected = numMessages * (tally.destination.isComposite() ? tally.destination.getCompositeDestinations().length : 1); + LOG.info("Tally for: " + tally.brokerName + ", dest: " + tally.destination + " - " + tally.accumulator.get()); + if (tally.accumulator.get() != expected) { + LOG.info("Tally for: " + tally.brokerName + ", dest: " + tally.destination + " - " + tally.accumulator.get() + " != " + expected + ", " + tally.expected); + return false; + } + LOG.info("got tally on " + tally.brokerName); } - } - } + return true; + } + }, 1000 * 60 * 1000L)); - protected BrokerService createBroker(int brokerid) throws Exception { - BrokerService broker = new BrokerService(); - broker.setPersistent(true); - broker.setDeleteAllMessagesOnStartup(true); - broker.getManagementContext().setCreateConnector(false); + assertTrue("No exceptions:" + exceptions, exceptions.isEmpty()); + LOG.info("done"); + long duration = System.currentTimeMillis() - startTime; + LOG.info("Duration:" + TimeUtils.printDuration(duration)); + } - broker.setUseJmx(true); - broker.setBrokerName("B" + brokerid); - broker.addConnector(new URI("tcp://localhost:" + (portBase + brokerid))); + private void startAllGWFanoutConsumers(int nBrokers) throws Exception { - addNetworkConnector(broker); - broker.setSchedulePeriodForDestinationPurge(0); - broker.getSystemUsage().setSendFailIfNoSpace(true); - broker.getSystemUsage().getMemoryUsage().setLimit(512 * 1024 * 1024); + StringBuffer compositeDest = new StringBuffer(); + for (int k = 0; k < nBrokers; k++) { + compositeDest.append("GW." + k); + if (k + 1 != nBrokers) { + compositeDest.append(','); + } + } + ActiveMQQueue compositeQ = new ActiveMQQueue(compositeDest.toString()); + for (int id = 0; id < nBrokers; id++) { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(tcp://localhost:" + (portBase + id) + ")"); + connectionFactory.setWatchTopicAdvisories(false); - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policyEntry = new PolicyEntry(); - policyEntry.setExpireMessagesPeriod(0); - policyEntry.setQueuePrefetch(1000); - policyEntry.setMemoryLimit(1024 * 1024L); - policyEntry.setOptimizedDispatch(false); - policyEntry.setProducerFlowControl(false); - policyEntry.setEnableAudit(true); - policyEntry.setUseCache(true); - policyMap.put(new ActiveMQQueue("GW.>"), policyEntry); - broker.setDestinationPolicy(policyMap); + QueueConnection queueConnection = connectionFactory.createQueueConnection(); + queueConnection.start(); - KahaDBPersistenceAdapter kahaDBPersistenceAdapter = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); - kahaDBPersistenceAdapter.setConcurrentStoreAndDispatchQueues(false); + final QueueSession queueSession = queueConnection.createQueueSession(true, Session.SESSION_TRANSACTED); - brokers.put(broker.getBrokerName(), new BrokerItem(broker)); - return broker; - } - - private void addNetworkConnector(BrokerService broker) throws Exception { - StringBuilder networkConnectorUrl = new StringBuilder("static:(").append(brokersUrl.toString()); - networkConnectorUrl.append(')'); - - for (int i = 0; i < 2; i++) { - NetworkConnector nc = new DiscoveryNetworkConnector(new URI(networkConnectorUrl.toString())); - nc.setName("Bridge-" + i); - nc.setNetworkTTL(1); - nc.setDecreaseNetworkConsumerPriority(true); - nc.setDynamicOnly(true); - nc.setPrefetchSize(100); - nc.setDynamicallyIncludedDestinations( - Arrays.asList(new ActiveMQDestination[]{new ActiveMQQueue("GW.*")})); - broker.addNetworkConnector(nc); - } - } - - public void testBrokers() throws Exception { - - buildUrlList(); - - for (int i = 0; i < numBrokers; i++) { - createBroker(i); - } - - startAllBrokers(); - waitForBridgeFormation(numBrokers - 1); - - verifyPeerBrokerInfos(numBrokers - 1); - - - final List consumerStates = startAllGWConsumers(numBrokers); - - startAllGWFanoutConsumers(numBrokers); - - LOG.info("Waiting for percolation of consumers.."); - TimeUnit.SECONDS.sleep(5); - - LOG.info("Produce mesages.."); - long startTime = System.currentTimeMillis(); - - // produce - produce(numMessages); - - assertTrue("Got all sent", Wait.waitFor(new Wait.Condition() { + final MessageProducer producer = queueSession.createProducer(compositeQ); + queueSession.createReceiver(new ActiveMQQueue("IN")).setMessageListener(new MessageListener() { @Override - public boolean isSatisified() throws Exception { - for (ConsumerState tally : consumerStates) { - final int expected = numMessages * (tally.destination.isComposite() ? tally.destination.getCompositeDestinations().length : 1); - LOG.info("Tally for: " + tally.brokerName + ", dest: " + tally.destination + " - " + tally.accumulator.get()); - if (tally.accumulator.get() != expected) { - LOG.info("Tally for: " + tally.brokerName + ", dest: " + tally.destination + " - " + tally.accumulator.get() + " != " + expected + ", " + tally.expected); - return false; - } - LOG.info("got tally on " + tally.brokerName); - } - return true; + public void onMessage(Message message) { + try { + producer.send(message); + queueSession.commit(); + } + catch (Exception e) { + LOG.error("Failed to fanout to GW: " + message, e); + } + } - }, 1000 * 60 * 1000L)); + }); + } + } - assertTrue("No exceptions:" + exceptions, exceptions.isEmpty()); + private List startAllGWConsumers(int nBrokers) throws Exception { + List consumerStates = new LinkedList(); + for (int id = 0; id < nBrokers; id++) { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(tcp://localhost:" + (portBase + id) + ")"); + connectionFactory.setWatchTopicAdvisories(false); - LOG.info("done"); - long duration = System.currentTimeMillis() - startTime; - LOG.info("Duration:" + TimeUtils.printDuration(duration)); - } + QueueConnection queueConnection = connectionFactory.createQueueConnection(); + queueConnection.start(); - private void startAllGWFanoutConsumers(int nBrokers) throws Exception { + final QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); - StringBuffer compositeDest = new StringBuffer(); - for (int k = 0; k < nBrokers; k++) { - compositeDest.append("GW." + k); - if (k + 1 != nBrokers) { - compositeDest.append(','); - } - } - ActiveMQQueue compositeQ = new ActiveMQQueue(compositeDest.toString()); + ActiveMQQueue destination = new ActiveMQQueue("GW." + id); + QueueReceiver queueReceiver = queueSession.createReceiver(destination); - for (int id = 0; id < nBrokers; id++) { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(tcp://localhost:" + (portBase + id) + ")"); - connectionFactory.setWatchTopicAdvisories(false); + final ConsumerState consumerState = new ConsumerState(); + consumerState.brokerName = ((ActiveMQConnection) queueConnection).getBrokerName(); + consumerState.receiver = queueReceiver; + consumerState.destination = destination; + for (int j = 0; j < numMessages * (consumerState.destination.isComposite() ? consumerState.destination.getCompositeDestinations().length : 1); j++) { + consumerState.expected.add(j); + } - QueueConnection queueConnection = connectionFactory.createQueueConnection(); - queueConnection.start(); + if (!accumulators.containsKey(destination)) { + accumulators.put(destination, new AtomicInteger(0)); + } + consumerState.accumulator = accumulators.get(destination); - final QueueSession queueSession = queueConnection.createQueueSession(true, Session.SESSION_TRANSACTED); - - final MessageProducer producer = queueSession.createProducer(compositeQ); - queueSession.createReceiver(new ActiveMQQueue("IN")).setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - try { - producer.send(message); - queueSession.commit(); - } catch (Exception e) { - LOG.error("Failed to fanout to GW: " + message, e); - } - - } - }); - } - } - - private List startAllGWConsumers(int nBrokers) throws Exception { - List consumerStates = new LinkedList(); - for (int id = 0; id < nBrokers; id++) { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(tcp://localhost:" + (portBase + id) + ")"); - connectionFactory.setWatchTopicAdvisories(false); - - QueueConnection queueConnection = connectionFactory.createQueueConnection(); - queueConnection.start(); - - final QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); - - ActiveMQQueue destination = new ActiveMQQueue("GW." + id); - QueueReceiver queueReceiver = queueSession.createReceiver(destination); - - final ConsumerState consumerState = new ConsumerState(); - consumerState.brokerName = ((ActiveMQConnection) queueConnection).getBrokerName(); - consumerState.receiver = queueReceiver; - consumerState.destination = destination; - for (int j = 0; j < numMessages * (consumerState.destination.isComposite() ? consumerState.destination.getCompositeDestinations().length : 1); j++) { - consumerState.expected.add(j); - } - - if (!accumulators.containsKey(destination)) { - accumulators.put(destination, new AtomicInteger(0)); - } - consumerState.accumulator = accumulators.get(destination); - - queueReceiver.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - try { - if (consumerSleepTime > 0) { - TimeUnit.MILLISECONDS.sleep(consumerSleepTime); - } - } catch (InterruptedException e) { - e.printStackTrace(); - } - try { - consumerState.accumulator.incrementAndGet(); - try { - consumerState.expected.remove(((ActiveMQMessage) message).getProperty("NUM")); - } catch (IOException e) { - e.printStackTrace(); - } - } catch (Exception e) { - LOG.error("Failed to commit slow receipt of " + message, e); - } - } - }); - - consumerStates.add(consumerState); - - } - return consumerStates; - } - - private void produce(int numMessages) throws Exception { - ExecutorService executorService = Executors.newFixedThreadPool(numProducers); - final AtomicInteger toSend = new AtomicInteger(numMessages); - for (int i = 1; i <= numProducers; i++) { - final int id = i % numBrokers; - executorService.execute(new Runnable() { - @Override - public void run() { - try { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(tcp://localhost:" + (portBase + id) + ")"); - connectionFactory.setWatchTopicAdvisories(false); - QueueConnection queueConnection = connectionFactory.createQueueConnection(); - queueConnection.start(); - QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = queueSession.createProducer(null); - int val = 0; - while ((val = toSend.decrementAndGet()) >= 0) { - - ActiveMQQueue compositeQ = new ActiveMQQueue("IN"); - LOG.info("Send to: " + ((ActiveMQConnection) queueConnection).getBrokerName() + ", " + val + ", dest:" + compositeQ); - Message textMessage = queueSession.createTextMessage(((ActiveMQConnection) queueConnection).getBrokerName() + "->" + val + " payload:" + payload); - textMessage.setIntProperty("NUM", val); - producer.send(compositeQ, textMessage); - } - queueConnection.close(); - - } catch (Throwable throwable) { - throwable.printStackTrace(); - exceptions.add(throwable); - } - } - }); - } - } - - private void verifyPeerBrokerInfo(BrokerItem brokerItem, final int max) throws Exception { - final BrokerService broker = brokerItem.broker; - final RegionBroker regionBroker = (RegionBroker) broker.getRegionBroker(); - Wait.waitFor(new Wait.Condition() { + queueReceiver.setMessageListener(new MessageListener() { @Override - public boolean isSatisified() throws Exception { - LOG.info("verify infos " + broker.getBrokerName() + ", len: " + regionBroker.getPeerBrokerInfos().length); - return max == regionBroker.getPeerBrokerInfos().length; + public void onMessage(Message message) { + try { + if (consumerSleepTime > 0) { + TimeUnit.MILLISECONDS.sleep(consumerSleepTime); + } + } + catch (InterruptedException e) { + e.printStackTrace(); + } + try { + consumerState.accumulator.incrementAndGet(); + try { + consumerState.expected.remove(((ActiveMQMessage) message).getProperty("NUM")); + } + catch (IOException e) { + e.printStackTrace(); + } + } + catch (Exception e) { + LOG.error("Failed to commit slow receipt of " + message, e); + } } - }); - LOG.info("verify infos " + broker.getBrokerName() + ", len: " + regionBroker.getPeerBrokerInfos().length); - List missing = new ArrayList(); - for (int i = 0; i < max; i++) { - missing.add("B" + i); - } - if (max != regionBroker.getPeerBrokerInfos().length) { - for (BrokerInfo info : regionBroker.getPeerBrokerInfos()) { - LOG.info(info.getBrokerName()); - missing.remove(info.getBrokerName()); + }); + + consumerStates.add(consumerState); + + } + return consumerStates; + } + + private void produce(int numMessages) throws Exception { + ExecutorService executorService = Executors.newFixedThreadPool(numProducers); + final AtomicInteger toSend = new AtomicInteger(numMessages); + for (int i = 1; i <= numProducers; i++) { + final int id = i % numBrokers; + executorService.execute(new Runnable() { + @Override + public void run() { + try { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(tcp://localhost:" + (portBase + id) + ")"); + connectionFactory.setWatchTopicAdvisories(false); + QueueConnection queueConnection = connectionFactory.createQueueConnection(); + queueConnection.start(); + QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = queueSession.createProducer(null); + int val = 0; + while ((val = toSend.decrementAndGet()) >= 0) { + + ActiveMQQueue compositeQ = new ActiveMQQueue("IN"); + LOG.info("Send to: " + ((ActiveMQConnection) queueConnection).getBrokerName() + ", " + val + ", dest:" + compositeQ); + Message textMessage = queueSession.createTextMessage(((ActiveMQConnection) queueConnection).getBrokerName() + "->" + val + " payload:" + payload); + textMessage.setIntProperty("NUM", val); + producer.send(compositeQ, textMessage); + } + queueConnection.close(); + + } + catch (Throwable throwable) { + throwable.printStackTrace(); + exceptions.add(throwable); + } } - LOG.info("Broker infos off.." + missing); - } - assertEquals(broker.getBrokerName(), max, regionBroker.getPeerBrokerInfos().length); - } + }); + } + } - private void verifyPeerBrokerInfos(final int max) throws Exception { - Collection brokerList = brokers.values(); - for (Iterator i = brokerList.iterator(); i.hasNext(); ) { - verifyPeerBrokerInfo(i.next(), max); - } - } + private void verifyPeerBrokerInfo(BrokerItem brokerItem, final int max) throws Exception { + final BrokerService broker = brokerItem.broker; + final RegionBroker regionBroker = (RegionBroker) broker.getRegionBroker(); + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("verify infos " + broker.getBrokerName() + ", len: " + regionBroker.getPeerBrokerInfos().length); + return max == regionBroker.getPeerBrokerInfos().length; + } + }); + LOG.info("verify infos " + broker.getBrokerName() + ", len: " + regionBroker.getPeerBrokerInfos().length); + List missing = new ArrayList(); + for (int i = 0; i < max; i++) { + missing.add("B" + i); + } + if (max != regionBroker.getPeerBrokerInfos().length) { + for (BrokerInfo info : regionBroker.getPeerBrokerInfos()) { + LOG.info(info.getBrokerName()); + missing.remove(info.getBrokerName()); + } + LOG.info("Broker infos off.." + missing); + } + assertEquals(broker.getBrokerName(), max, regionBroker.getPeerBrokerInfos().length); + } - protected void tearDown() throws Exception { - super.tearDown(); - } + private void verifyPeerBrokerInfos(final int max) throws Exception { + Collection brokerList = brokers.values(); + for (Iterator i = brokerList.iterator(); i.hasNext(); ) { + verifyPeerBrokerInfo(i.next(), max); + } + } - class ConsumerState { - AtomicInteger accumulator; - String brokerName; - QueueReceiver receiver; - ActiveMQDestination destination; - Vector expected = new Vector(); - } + protected void tearDown() throws Exception { + super.tearDown(); + } + + class ConsumerState { + + AtomicInteger accumulator; + String brokerName; + QueueReceiver receiver; + ActiveMQDestination destination; + Vector expected = new Vector(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4485Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4485Test.java index 1126d310e3..98f50204f5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4485Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4485Test.java @@ -28,7 +28,9 @@ import javax.jms.Connection; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; + import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerPlugin; import org.apache.activemq.broker.BrokerPluginSupport; @@ -48,150 +50,147 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AMQ4485Test extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(AMQ4485Test.class); - BrokerService broker; - ActiveMQConnectionFactory factory; - final int messageCount = 20; - int memoryLimit = 40 * 1024; - final ActiveMQQueue destination = new ActiveMQQueue("QUEUE." + this.getClass().getName()); - final Vector exceptions = new Vector(); - final CountDownLatch slowSendResume = new CountDownLatch(1); + private static final Logger LOG = LoggerFactory.getLogger(AMQ4485Test.class); + BrokerService broker; + ActiveMQConnectionFactory factory; + final int messageCount = 20; + int memoryLimit = 40 * 1024; + final ActiveMQQueue destination = new ActiveMQQueue("QUEUE." + this.getClass().getName()); + final Vector exceptions = new Vector(); + final CountDownLatch slowSendResume = new CountDownLatch(1); - protected void configureBroker(long memoryLimit) throws Exception { - broker.setDeleteAllMessagesOnStartup(true); - broker.setAdvisorySupport(false); + protected void configureBroker(long memoryLimit) throws Exception { + broker.setDeleteAllMessagesOnStartup(true); + broker.setAdvisorySupport(false); - PolicyEntry policy = new PolicyEntry(); - policy.setExpireMessagesPeriod(0); - policy.setMemoryLimit(memoryLimit); - policy.setProducerFlowControl(false); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - broker.setDestinationPolicy(pMap); + PolicyEntry policy = new PolicyEntry(); + policy.setExpireMessagesPeriod(0); + policy.setMemoryLimit(memoryLimit); + policy.setProducerFlowControl(false); + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); + broker.setDestinationPolicy(pMap); - broker.setPlugins(new BrokerPlugin[] {new BrokerPluginSupport() { - @Override - public void send(ProducerBrokerExchange producerExchange, final Message messageSend) throws Exception { - if (messageSend.isInTransaction() && messageSend.getProperty("NUM") != null) { - final Integer num = (Integer) messageSend.getProperty("NUM"); - if (true) { - TransactionBroker transactionBroker = (TransactionBroker)broker.getBroker().getAdaptor(TransactionBroker.class); - transactionBroker.getTransaction(producerExchange.getConnectionContext(), messageSend.getTransactionId(), false).addSynchronization( - new Synchronization() { - public void afterCommit() throws Exception { - LOG.error("AfterCommit, NUM:" + num + ", " + messageSend.getMessageId() + ", tx: " + messageSend.getTransactionId()); - if (num == 5) { - // we want to add to cursor after usage is exhausted by message 20 and when - // all other messages have been processed - LOG.error("Pausing on latch in afterCommit for: " + num + ", " + messageSend.getMessageId()); - slowSendResume.await(20, TimeUnit.SECONDS); - LOG.error("resuming on latch afterCommit for: " + num + ", " + messageSend.getMessageId()); - } else if (messageCount + 1 == num) { - LOG.error("releasing latch. " + num + ", " + messageSend.getMessageId()); - slowSendResume.countDown(); - // for message X, we need to delay so message 5 can setBatch - TimeUnit.SECONDS.sleep(5); - LOG.error("resuming afterCommit for: " + num + ", " + messageSend.getMessageId()); - } - } - }); - } - } - super.send(producerExchange, messageSend); + broker.setPlugins(new BrokerPlugin[]{new BrokerPluginSupport() { + @Override + public void send(ProducerBrokerExchange producerExchange, final Message messageSend) throws Exception { + if (messageSend.isInTransaction() && messageSend.getProperty("NUM") != null) { + final Integer num = (Integer) messageSend.getProperty("NUM"); + if (true) { + TransactionBroker transactionBroker = (TransactionBroker) broker.getBroker().getAdaptor(TransactionBroker.class); + transactionBroker.getTransaction(producerExchange.getConnectionContext(), messageSend.getTransactionId(), false).addSynchronization(new Synchronization() { + public void afterCommit() throws Exception { + LOG.error("AfterCommit, NUM:" + num + ", " + messageSend.getMessageId() + ", tx: " + messageSend.getTransactionId()); + if (num == 5) { + // we want to add to cursor after usage is exhausted by message 20 and when + // all other messages have been processed + LOG.error("Pausing on latch in afterCommit for: " + num + ", " + messageSend.getMessageId()); + slowSendResume.await(20, TimeUnit.SECONDS); + LOG.error("resuming on latch afterCommit for: " + num + ", " + messageSend.getMessageId()); + } + else if (messageCount + 1 == num) { + LOG.error("releasing latch. " + num + ", " + messageSend.getMessageId()); + slowSendResume.countDown(); + // for message X, we need to delay so message 5 can setBatch + TimeUnit.SECONDS.sleep(5); + LOG.error("resuming afterCommit for: " + num + ", " + messageSend.getMessageId()); + } + } + }); + } } - } - }); + super.send(producerExchange, messageSend); + } + }}); - } + } + public void testOutOfOrderTransactionCompletionOnMemoryLimit() throws Exception { - public void testOutOfOrderTransactionCompletionOnMemoryLimit() throws Exception { + Set expected = new HashSet(); + final Vector sessionVector = new Vector(); + ExecutorService executorService = Executors.newCachedThreadPool(); + for (int i = 1; i <= messageCount; i++) { + sessionVector.add(send(i, 1, true)); + expected.add(i); + } - Set expected = new HashSet(); - final Vector sessionVector = new Vector(); - ExecutorService executorService = Executors.newCachedThreadPool(); - for (int i = 1; i <= messageCount; i++) { - sessionVector.add(send(i, 1, true)); - expected.add(i); - } + // get parallel commit so that the sync writes are batched + for (int i = 0; i < messageCount; i++) { + final int id = i; + executorService.submit(new Runnable() { + @Override + public void run() { + try { + sessionVector.get(id).commit(); + } + catch (Exception fail) { + exceptions.add(fail); + } + } + }); + } - // get parallel commit so that the sync writes are batched - for (int i = 0; i < messageCount; i++) { - final int id = i; - executorService.submit(new Runnable() { - @Override - public void run() { - try { - sessionVector.get(id).commit(); - } catch (Exception fail) { - exceptions.add(fail); - } - } - }); - } + final DestinationViewMBean queueViewMBean = (DestinationViewMBean) broker.getManagementContext().newProxyInstance(broker.getAdminView().getQueues()[0], DestinationViewMBean.class, false); - final DestinationViewMBean queueViewMBean = (DestinationViewMBean) - broker.getManagementContext().newProxyInstance(broker.getAdminView().getQueues()[0], DestinationViewMBean.class, false); - - // not sure how many messages will get enqueued - TimeUnit.SECONDS.sleep(3); - if (false) - assertTrue("all " + messageCount + " on the q", Wait.waitFor(new Wait.Condition() { + // not sure how many messages will get enqueued + TimeUnit.SECONDS.sleep(3); + if (false) + assertTrue("all " + messageCount + " on the q", Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisified() throws Exception { - LOG.info("enqueueCount: " + queueViewMBean.getEnqueueCount()); - return messageCount == queueViewMBean.getEnqueueCount(); + LOG.info("enqueueCount: " + queueViewMBean.getEnqueueCount()); + return messageCount == queueViewMBean.getEnqueueCount(); } - })); + })); - LOG.info("Big send to blow available destination usage before slow send resumes"); - send(messageCount + 1, 35*1024, true).commit(); + LOG.info("Big send to blow available destination usage before slow send resumes"); + send(messageCount + 1, 35 * 1024, true).commit(); + // consume and verify all received + Connection cosumerConnection = factory.createConnection(); + cosumerConnection.start(); + MessageConsumer consumer = cosumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE).createConsumer(destination); + for (int i = 1; i <= messageCount + 1; i++) { + BytesMessage bytesMessage = (BytesMessage) consumer.receive(10000); + assertNotNull("Got message: " + i + ", " + expected, bytesMessage); + MessageId mqMessageId = ((ActiveMQBytesMessage) bytesMessage).getMessageId(); + LOG.info("got: " + expected + ", " + mqMessageId + ", NUM=" + ((ActiveMQBytesMessage) bytesMessage).getProperty("NUM")); + expected.remove(((ActiveMQBytesMessage) bytesMessage).getProperty("NUM")); + } + } - // consume and verify all received - Connection cosumerConnection = factory.createConnection(); - cosumerConnection.start(); - MessageConsumer consumer = cosumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE).createConsumer(destination); - for (int i = 1; i <= messageCount + 1; i++) { - BytesMessage bytesMessage = (BytesMessage) consumer.receive(10000); - assertNotNull("Got message: " + i + ", " + expected, bytesMessage); - MessageId mqMessageId = ((ActiveMQBytesMessage) bytesMessage).getMessageId(); - LOG.info("got: " + expected + ", " + mqMessageId + ", NUM=" + ((ActiveMQBytesMessage) bytesMessage).getProperty("NUM")); - expected.remove(((ActiveMQBytesMessage) bytesMessage).getProperty("NUM")); - } - } + private Session send(int id, int messageSize, boolean transacted) throws Exception { + Connection connection = factory.createConnection(); + connection.start(); + Session session = connection.createSession(transacted, transacted ? Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + BytesMessage bytesMessage = session.createBytesMessage(); + bytesMessage.writeBytes(new byte[messageSize]); + bytesMessage.setIntProperty("NUM", id); + producer.send(bytesMessage); + LOG.info("Sent:" + bytesMessage.getJMSMessageID() + " session tx: " + ((ActiveMQBytesMessage) bytesMessage).getTransactionId()); + return session; + } - private Session send(int id, int messageSize, boolean transacted) throws Exception { - Connection connection = factory.createConnection(); - connection.start(); - Session session = connection.createSession(transacted, transacted ? Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - BytesMessage bytesMessage = session.createBytesMessage(); - bytesMessage.writeBytes(new byte[messageSize]); - bytesMessage.setIntProperty("NUM", id); - producer.send(bytesMessage); - LOG.info("Sent:" + bytesMessage.getJMSMessageID() + " session tx: " + ((ActiveMQBytesMessage) bytesMessage).getTransactionId()); - return session; - } + protected void setUp() throws Exception { + super.setUp(); + broker = new BrokerService(); + broker.setBrokerName("thisOne"); + configureBroker(memoryLimit); + broker.start(); + factory = new ActiveMQConnectionFactory("vm://thisOne?jms.alwaysSyncSend=true"); + factory.setWatchTopicAdvisories(false); - protected void setUp() throws Exception { - super.setUp(); - broker = new BrokerService(); - broker.setBrokerName("thisOne"); - configureBroker(memoryLimit); - broker.start(); - factory = new ActiveMQConnectionFactory("vm://thisOne?jms.alwaysSyncSend=true"); - factory.setWatchTopicAdvisories(false); + } - } - - protected void tearDown() throws Exception { - super.tearDown(); - if (broker != null) { - broker.stop(); - broker = null; - } - } + protected void tearDown() throws Exception { + super.tearDown(); + if (broker != null) { + broker.stop(); + broker = null; + } + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4487Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4487Test.java index 346650e7c1..7d3ee41c9b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4487Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4487Test.java @@ -40,96 +40,96 @@ import org.slf4j.LoggerFactory; public class AMQ4487Test { - private static final Logger LOG = LoggerFactory.getLogger(AMQ4487Test.class); + private static final Logger LOG = LoggerFactory.getLogger(AMQ4487Test.class); - private final String destinationName = "TEST.QUEUE"; - private BrokerService broker; - private ActiveMQConnectionFactory factory; + private final String destinationName = "TEST.QUEUE"; + private BrokerService broker; + private ActiveMQConnectionFactory factory; - @Before - public void startBroker() throws Exception { - broker = new BrokerService(); - broker.deleteAllMessages(); - broker.setUseJmx(false); - broker.setAdvisorySupport(false); + @Before + public void startBroker() throws Exception { + broker = new BrokerService(); + broker.deleteAllMessages(); + broker.setUseJmx(false); + broker.setAdvisorySupport(false); - PolicyEntry policy = new PolicyEntry(); - policy.setQueue(">"); - policy.setMaxProducersToAudit(75); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - broker.setDestinationPolicy(pMap); + PolicyEntry policy = new PolicyEntry(); + policy.setQueue(">"); + policy.setMaxProducersToAudit(75); + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); + broker.setDestinationPolicy(pMap); - broker.start(); - broker.waitUntilStarted(); - factory = new ActiveMQConnectionFactory("vm://localhost"); - } + broker.start(); + broker.waitUntilStarted(); + factory = new ActiveMQConnectionFactory("vm://localhost"); + } - @After - public void stopBroker() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } + @After + public void stopBroker() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + } - private void sendMessages(int messageToSend) throws Exception { - String data = ""; - for (int i = 0; i < 1024 * 2; i++) { - data += "x"; - } + private void sendMessages(int messageToSend) throws Exception { + String data = ""; + for (int i = 0; i < 1024 * 2; i++) { + data += "x"; + } - Connection connection = factory.createConnection(); - connection.start(); + Connection connection = factory.createConnection(); + connection.start(); - for (int i = 0; i < messageToSend; i++) { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createQueue(destinationName); - MessageProducer producer = session.createProducer(queue); - producer.send(session.createTextMessage(data)); - session.close(); - } + for (int i = 0; i < messageToSend; i++) { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = session.createQueue(destinationName); + MessageProducer producer = session.createProducer(queue); + producer.send(session.createTextMessage(data)); + session.close(); + } - connection.close(); - } + connection.close(); + } - @Test - public void testBrowsingWithLessThanMaxAuditDepth() throws Exception { - doTestBrowsing(75); - } + @Test + public void testBrowsingWithLessThanMaxAuditDepth() throws Exception { + doTestBrowsing(75); + } - @Test - public void testBrowsingWithMoreThanMaxAuditDepth() throws Exception { - doTestBrowsing(300); - } + @Test + public void testBrowsingWithMoreThanMaxAuditDepth() throws Exception { + doTestBrowsing(300); + } - @SuppressWarnings("rawtypes") - private void doTestBrowsing(int messagesToSend) throws Exception { + @SuppressWarnings("rawtypes") + private void doTestBrowsing(int messagesToSend) throws Exception { - Connection connection = factory.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createQueue(destinationName); + Connection connection = factory.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = session.createQueue(destinationName); - sendMessages(messagesToSend); + sendMessages(messagesToSend); - QueueBrowser browser = session.createBrowser(queue); - Enumeration enumeration = browser.getEnumeration(); - int received = 0; - while (enumeration.hasMoreElements()) { - Message m = (Message) enumeration.nextElement(); - assertNotNull(m); + QueueBrowser browser = session.createBrowser(queue); + Enumeration enumeration = browser.getEnumeration(); + int received = 0; + while (enumeration.hasMoreElements()) { + Message m = (Message) enumeration.nextElement(); + assertNotNull(m); - if (LOG.isDebugEnabled()) { - LOG.debug("Browsed Message: {}", m.getJMSMessageID()); - } + if (LOG.isDebugEnabled()) { + LOG.debug("Browsed Message: {}", m.getJMSMessageID()); + } - received++; - if (received > messagesToSend) { - break; - } - } + received++; + if (received > messagesToSend) { + break; + } + } - browser.close(); + browser.close(); - assertEquals(messagesToSend, received); - } + assertEquals(messagesToSend, received); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4504Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4504Test.java index 6041a890f5..a89aca2f53 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4504Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4504Test.java @@ -21,6 +21,7 @@ import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.command.ActiveMQQueue; @@ -29,54 +30,54 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; - import static org.junit.Assert.assertNotNull; public class AMQ4504Test { - BrokerService brokerService; + BrokerService brokerService; - @Before - public void setup() throws Exception { - brokerService = new BrokerService(); - brokerService.setPersistent(false); - brokerService.start(); - } + @Before + public void setup() throws Exception { + brokerService = new BrokerService(); + brokerService.setPersistent(false); + brokerService.start(); + } - @After - public void stop() throws Exception { - brokerService.stop(); - } + @After + public void stop() throws Exception { + brokerService.stop(); + } - @Test - public void testCompositeDestConsumer() throws Exception { + @Test + public void testCompositeDestConsumer() throws Exception { - final int numDests = 20; - final int numMessages = 200; - StringBuffer stringBuffer = new StringBuffer(); - for (int i=0; i"); - MessageConsumer consumer = session.createConsumer(dlqDestination); - consumer.setMessageListener(new MessageListener() { + final AtomicBoolean advised = new AtomicBoolean(false); + Connection connection = cf.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination dlqDestination = session.createTopic(AdvisorySupport.MESSAGE_DLQ_TOPIC_PREFIX + ">"); + MessageConsumer consumer = session.createConsumer(dlqDestination); + consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - advised.set(true); + @Override + public void onMessage(Message message) { + advised.set(true); + } + }); + connection.start(); + + ExecutorService service = Executors.newSingleThreadExecutor(); + + service.execute(new Runnable() { + @Override + public void run() { + try { + ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createTemporaryQueue(); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + producer.setTimeToLive(400); + producer.send(session.createTextMessage()); + producer.send(session.createTextMessage()); + TimeUnit.MILLISECONDS.sleep(500); + connection.close(); } - }); - connection.start(); - - ExecutorService service = Executors.newSingleThreadExecutor(); - - service.execute(new Runnable() { - @Override - public void run() { - try { - ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createTemporaryQueue(); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - producer.setTimeToLive(400); - producer.send(session.createTextMessage()); - producer.send(session.createTextMessage()); - TimeUnit.MILLISECONDS.sleep(500); - connection.close(); - } catch (Exception e) { - } + catch (Exception e) { } - }); + } + }); - service.shutdown(); - assertTrue(service.awaitTermination(1, TimeUnit.MINUTES)); - assertFalse("Should not get any Advisories for DLQ'd Messages", advised.get()); - } + service.shutdown(); + assertTrue(service.awaitTermination(1, TimeUnit.MINUTES)); + assertFalse("Should not get any Advisories for DLQ'd Messages", advised.get()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4518Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4518Test.java index e5446422ee..92021bf754 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4518Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4518Test.java @@ -47,82 +47,83 @@ import org.junit.Test; public class AMQ4518Test { - private BrokerService brokerService; - private String connectionUri; + private BrokerService brokerService; + private String connectionUri; - @Before - public void setup() throws Exception { - brokerService = new BrokerService(); + @Before + public void setup() throws Exception { + brokerService = new BrokerService(); - connectionUri = brokerService.addConnector("tcp://localhost:0").getPublishableConnectString(); + connectionUri = brokerService.addConnector("tcp://localhost:0").getPublishableConnectString(); - // Configure Dead Letter Strategy - DeadLetterStrategy strategy = new IndividualDeadLetterStrategy(); - ((IndividualDeadLetterStrategy)strategy).setUseQueueForQueueMessages(true); - ((IndividualDeadLetterStrategy)strategy).setQueuePrefix("DLQ."); - strategy.setProcessNonPersistent(false); - strategy.setProcessExpired(false); + // Configure Dead Letter Strategy + DeadLetterStrategy strategy = new IndividualDeadLetterStrategy(); + ((IndividualDeadLetterStrategy) strategy).setUseQueueForQueueMessages(true); + ((IndividualDeadLetterStrategy) strategy).setQueuePrefix("DLQ."); + strategy.setProcessNonPersistent(false); + strategy.setProcessExpired(false); - // Add policy and individual DLQ strategy - PolicyEntry policy = new PolicyEntry(); - policy.setTimeBeforeDispatchStarts(3000); - policy.setDeadLetterStrategy(strategy); + // Add policy and individual DLQ strategy + PolicyEntry policy = new PolicyEntry(); + policy.setTimeBeforeDispatchStarts(3000); + policy.setDeadLetterStrategy(strategy); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); - brokerService.setDestinationPolicy(pMap); - brokerService.setPersistent(false); - brokerService.start(); - } + brokerService.setDestinationPolicy(pMap); + brokerService.setPersistent(false); + brokerService.start(); + } - @After - public void stop() throws Exception { - brokerService.stop(); - } + @After + public void stop() throws Exception { + brokerService.stop(); + } - @Test(timeout=360000) - public void test() throws Exception { + @Test(timeout = 360000) + public void test() throws Exception { - final ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(connectionUri); + final ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(connectionUri); - final AtomicBoolean advised = new AtomicBoolean(false); - Connection connection = cf.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination dlqDestination = session.createTopic(AdvisorySupport.EXPIRED_QUEUE_MESSAGES_TOPIC_PREFIX + ">"); - MessageConsumer consumer = session.createConsumer(dlqDestination); - consumer.setMessageListener(new MessageListener() { + final AtomicBoolean advised = new AtomicBoolean(false); + Connection connection = cf.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination dlqDestination = session.createTopic(AdvisorySupport.EXPIRED_QUEUE_MESSAGES_TOPIC_PREFIX + ">"); + MessageConsumer consumer = session.createConsumer(dlqDestination); + consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - advised.set(true); + @Override + public void onMessage(Message message) { + advised.set(true); + } + }); + connection.start(); + + ExecutorService service = Executors.newSingleThreadExecutor(); + + service.execute(new Runnable() { + @Override + public void run() { + try { + ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createTemporaryQueue(); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + producer.setTimeToLive(400); + producer.send(session.createTextMessage()); + producer.send(session.createTextMessage()); + TimeUnit.MILLISECONDS.sleep(500); + connection.close(); } - }); - connection.start(); - - ExecutorService service = Executors.newSingleThreadExecutor(); - - service.execute(new Runnable() { - @Override - public void run() { - try { - ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createTemporaryQueue(); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - producer.setTimeToLive(400); - producer.send(session.createTextMessage()); - producer.send(session.createTextMessage()); - TimeUnit.MILLISECONDS.sleep(500); - connection.close(); - } catch (Exception e) { - } + catch (Exception e) { } - }); + } + }); - service.shutdown(); - assertTrue(service.awaitTermination(1, TimeUnit.MINUTES)); - assertFalse("Should not get any Advisories for Expired Messages", advised.get()); - } + service.shutdown(); + assertTrue(service.awaitTermination(1, TimeUnit.MINUTES)); + assertFalse("Should not get any Advisories for Expired Messages", advised.get()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4530Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4530Test.java index e8ab9f4299..d57501ef22 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4530Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4530Test.java @@ -46,71 +46,70 @@ import org.junit.Test; public class AMQ4530Test { - private static BrokerService brokerService; - private static String TEST_QUEUE = "testQueue"; - private static ActiveMQQueue queue = new ActiveMQQueue(TEST_QUEUE); - private static String BROKER_ADDRESS = "tcp://localhost:0"; - private static String KEY = "testproperty"; - private static String VALUE = "propvalue"; + private static BrokerService brokerService; + private static String TEST_QUEUE = "testQueue"; + private static ActiveMQQueue queue = new ActiveMQQueue(TEST_QUEUE); + private static String BROKER_ADDRESS = "tcp://localhost:0"; + private static String KEY = "testproperty"; + private static String VALUE = "propvalue"; - private ActiveMQConnectionFactory connectionFactory; - private String connectionUri; + private ActiveMQConnectionFactory connectionFactory; + private String connectionUri; - @Before - public void setUp() throws Exception { - brokerService = new BrokerService(); - brokerService.setPersistent(false); - brokerService.setUseJmx(true); - connectionUri = brokerService.addConnector(BROKER_ADDRESS).getPublishableConnectString(); - brokerService.start(); - brokerService.waitUntilStarted(); + @Before + public void setUp() throws Exception { + brokerService = new BrokerService(); + brokerService.setPersistent(false); + brokerService.setUseJmx(true); + connectionUri = brokerService.addConnector(BROKER_ADDRESS).getPublishableConnectString(); + brokerService.start(); + brokerService.waitUntilStarted(); - connectionFactory = new ActiveMQConnectionFactory(connectionUri); - sendMessage(); - } + connectionFactory = new ActiveMQConnectionFactory(connectionUri); + sendMessage(); + } - public void sendMessage() throws Exception { - final Connection conn = connectionFactory.createConnection(); - try { - conn.start(); - final Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - final Destination queue = session.createQueue(TEST_QUEUE); - final Message toSend = session.createMessage(); - toSend.setStringProperty(KEY, VALUE); - final MessageProducer producer = session.createProducer(queue); - producer.send(queue, toSend); - } finally { - conn.close(); - } - } + public void sendMessage() throws Exception { + final Connection conn = connectionFactory.createConnection(); + try { + conn.start(); + final Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + final Destination queue = session.createQueue(TEST_QUEUE); + final Message toSend = session.createMessage(); + toSend.setStringProperty(KEY, VALUE); + final MessageProducer producer = session.createProducer(queue); + producer.send(queue, toSend); + } + finally { + conn.close(); + } + } - @After - public void tearDown() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - } + @After + public void tearDown() throws Exception { + brokerService.stop(); + brokerService.waitUntilStopped(); + } - @SuppressWarnings("unchecked") - @Test - public void testStringPropertiesFromCompositeData() throws Exception { - final QueueViewMBean queueView = getProxyToQueueViewMBean(); - final CompositeData message = queueView.browse()[0]; - assertNotNull(message); - TabularDataSupport stringProperties = (TabularDataSupport) message.get(CompositeDataConstants.STRING_PROPERTIES); - assertNotNull(stringProperties); - assertThat(stringProperties.size(), is(greaterThan(0))); - Map.Entry compositeDataEntry = (Map.Entry) stringProperties.entrySet().toArray()[0]; - CompositeData stringEntry = (CompositeData) compositeDataEntry.getValue(); - assertThat(String.valueOf(stringEntry.get("key")), equalTo(KEY)); - assertThat(String.valueOf(stringEntry.get("value")), equalTo(VALUE)); - } + @SuppressWarnings("unchecked") + @Test + public void testStringPropertiesFromCompositeData() throws Exception { + final QueueViewMBean queueView = getProxyToQueueViewMBean(); + final CompositeData message = queueView.browse()[0]; + assertNotNull(message); + TabularDataSupport stringProperties = (TabularDataSupport) message.get(CompositeDataConstants.STRING_PROPERTIES); + assertNotNull(stringProperties); + assertThat(stringProperties.size(), is(greaterThan(0))); + Map.Entry compositeDataEntry = (Map.Entry) stringProperties.entrySet().toArray()[0]; + CompositeData stringEntry = (CompositeData) compositeDataEntry.getValue(); + assertThat(String.valueOf(stringEntry.get("key")), equalTo(KEY)); + assertThat(String.valueOf(stringEntry.get("value")), equalTo(VALUE)); + } - private QueueViewMBean getProxyToQueueViewMBean() throws MalformedObjectNameException, NullPointerException, - JMSException { - final ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + queue.getQueueName()); - final QueueViewMBean proxy = (QueueViewMBean) brokerService.getManagementContext().newProxyInstance( - queueViewMBeanName, QueueViewMBean.class, true); - return proxy; - } + private QueueViewMBean getProxyToQueueViewMBean() throws MalformedObjectNameException, NullPointerException, JMSException { + final ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + queue.getQueueName()); + final QueueViewMBean proxy = (QueueViewMBean) brokerService.getManagementContext().newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); + return proxy; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4531Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4531Test.java index 0be3226582..d30356194e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4531Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4531Test.java @@ -41,104 +41,106 @@ import org.slf4j.LoggerFactory; */ public class AMQ4531Test extends TestCase { - private final Logger LOG = LoggerFactory.getLogger(AMQ4531Test.class); + private final Logger LOG = LoggerFactory.getLogger(AMQ4531Test.class); - private String connectionURI; - private MBeanServer mbeanServer; - private BrokerService broker; + private String connectionURI; + private MBeanServer mbeanServer; + private BrokerService broker; - @Override - protected void setUp() throws Exception { - super.setUp(); - broker = new BrokerService(); - connectionURI = broker.addConnector("tcp://0.0.0.0:0?maximumConnections=1").getPublishableConnectString(); - broker.setPersistent(false); - broker.start(); - mbeanServer = ManagementFactory.getPlatformMBeanServer(); - } + @Override + protected void setUp() throws Exception { + super.setUp(); + broker = new BrokerService(); + connectionURI = broker.addConnector("tcp://0.0.0.0:0?maximumConnections=1").getPublishableConnectString(); + broker.setPersistent(false); + broker.start(); + mbeanServer = ManagementFactory.getPlatformMBeanServer(); + } - @Override - protected void tearDown() throws Exception { - broker.stop(); - super.tearDown(); - } + @Override + protected void tearDown() throws Exception { + broker.stop(); + super.tearDown(); + } - /** - * Create the test case - * - * @param testName - * name of the test case - */ - public AMQ4531Test(String testName) { - super(testName); - } + /** + * Create the test case + * + * @param testName name of the test case + */ + public AMQ4531Test(String testName) { + super(testName); + } - /** - * @return the suite of tests being tested - */ - public static Test suite() { - return new TestSuite(AMQ4531Test.class); - } + /** + * @return the suite of tests being tested + */ + public static Test suite() { + return new TestSuite(AMQ4531Test.class); + } - public void testFDSLeak() throws Exception { + public void testFDSLeak() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionURI); - ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); - connection.start(); - - int connections = 100; - final long original = openFileDescriptorCount(); - LOG.info("FD count: " + original); - final CountDownLatch done = new CountDownLatch(connections); - for (int i = 0; i < connections; i++) { - new Thread("worker: " + i) { - @Override - public void run() { - ActiveMQConnection connection = null; - try { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionURI); - connection = (ActiveMQConnection) factory.createConnection(); - connection.start(); - } catch (Exception e) { - LOG.debug(getStack(e)); - } finally { - try { - connection.close(); - } catch (Exception e) { - LOG.debug(getStack(e)); - } - done.countDown(); - LOG.debug("Latch count down called."); - } - } - }.start(); - } - - // Wait for all the clients to finish - LOG.info("Waiting for latch..."); - done.await(); - LOG.info("Latch complete."); - LOG.info("FD count: " + openFileDescriptorCount()); - - assertTrue("Too many open file descriptors: " + openFileDescriptorCount(), Wait.waitFor(new Wait.Condition() { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionURI); + ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); + connection.start(); + int connections = 100; + final long original = openFileDescriptorCount(); + LOG.info("FD count: " + original); + final CountDownLatch done = new CountDownLatch(connections); + for (int i = 0; i < connections; i++) { + new Thread("worker: " + i) { @Override - public boolean isSatisified() throws Exception { - long openFDs = openFileDescriptorCount(); - LOG.info("Current FD count [{}], original FD count[{}]", openFDs, original); - return (openFDs - original) < 10; + public void run() { + ActiveMQConnection connection = null; + try { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionURI); + connection = (ActiveMQConnection) factory.createConnection(); + connection.start(); + } + catch (Exception e) { + LOG.debug(getStack(e)); + } + finally { + try { + connection.close(); + } + catch (Exception e) { + LOG.debug(getStack(e)); + } + done.countDown(); + LOG.debug("Latch count down called."); + } } - })); - } + }.start(); + } - private long openFileDescriptorCount() throws Exception { - return ((Long) mbeanServer.getAttribute(new ObjectName("java.lang:type=OperatingSystem"), "OpenFileDescriptorCount")).longValue(); - } + // Wait for all the clients to finish + LOG.info("Waiting for latch..."); + done.await(); + LOG.info("Latch complete."); + LOG.info("FD count: " + openFileDescriptorCount()); - private String getStack(Throwable aThrowable) { - final Writer result = new StringWriter(); - final PrintWriter printWriter = new PrintWriter(result); - aThrowable.printStackTrace(printWriter); - return result.toString(); - } + assertTrue("Too many open file descriptors: " + openFileDescriptorCount(), Wait.waitFor(new Wait.Condition() { + + @Override + public boolean isSatisified() throws Exception { + long openFDs = openFileDescriptorCount(); + LOG.info("Current FD count [{}], original FD count[{}]", openFDs, original); + return (openFDs - original) < 10; + } + })); + } + + private long openFileDescriptorCount() throws Exception { + return ((Long) mbeanServer.getAttribute(new ObjectName("java.lang:type=OperatingSystem"), "OpenFileDescriptorCount")).longValue(); + } + + private String getStack(Throwable aThrowable) { + final Writer result = new StringWriter(); + final PrintWriter printWriter = new PrintWriter(result); + aThrowable.printStackTrace(printWriter); + return result.toString(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4554Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4554Test.java index 47ce6421ec..1113ee440e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4554Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4554Test.java @@ -37,71 +37,71 @@ import org.slf4j.LoggerFactory; */ public class AMQ4554Test extends TestCase { - private final Logger LOG = LoggerFactory.getLogger(AMQ4554Test.class); + private final Logger LOG = LoggerFactory.getLogger(AMQ4554Test.class); - private String connectionURI; - private BrokerService broker; + private String connectionURI; + private BrokerService broker; - @Override - protected void setUp() throws Exception { - super.setUp(); - broker = new BrokerService(); - connectionURI = broker.addConnector("tcp://0.0.0.0:0?maximumConnections=1").getPublishableConnectString(); - broker.setPersistent(false); - broker.start(); - } + @Override + protected void setUp() throws Exception { + super.setUp(); + broker = new BrokerService(); + connectionURI = broker.addConnector("tcp://0.0.0.0:0?maximumConnections=1").getPublishableConnectString(); + broker.setPersistent(false); + broker.start(); + } - @Override - protected void tearDown() throws Exception { - broker.stop(); - super.tearDown(); - } + @Override + protected void tearDown() throws Exception { + broker.stop(); + super.tearDown(); + } - /** - * Create the test case - * - * @param testName - * name of the test case - */ - public AMQ4554Test(String testName) { - super(testName); - } + /** + * Create the test case + * + * @param testName name of the test case + */ + public AMQ4554Test(String testName) { + super(testName); + } - /** - * @return the suite of tests being tested - */ - public static Test suite() { - return new TestSuite(AMQ4554Test.class); - } + /** + * @return the suite of tests being tested + */ + public static Test suite() { + return new TestSuite(AMQ4554Test.class); + } - public void testMSXProducerTXID() throws Exception { + public void testMSXProducerTXID() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionURI); - Connection connection = factory.createConnection(); - connection.start(); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionURI); + Connection connection = factory.createConnection(); + connection.start(); - Session producerSession = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageProducer producer = producerSession.createProducer(producerSession.createQueue("myQueue")); - TextMessage producerMessage = producerSession.createTextMessage("Test Message"); - producer.send(producerMessage); - producer.close(); - producerSession.commit(); - producerSession.close(); + Session producerSession = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageProducer producer = producerSession.createProducer(producerSession.createQueue("myQueue")); + TextMessage producerMessage = producerSession.createTextMessage("Test Message"); + producer.send(producerMessage); + producer.close(); + producerSession.commit(); + producerSession.close(); - Session consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageConsumer consumer = consumerSession.createConsumer(consumerSession.createQueue("myQueue")); - Message consumerMessage = consumer.receive(1000); - try { - String txId = consumerMessage.getStringProperty("JMSXProducerTXID"); - assertNotNull(txId); - } catch(Exception e) { - LOG.info("Caught Exception that was not expected:", e); - fail("Should not throw"); - } - consumer.close(); - consumerSession.commit(); - consumerSession.close(); - connection.close(); - } + Session consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageConsumer consumer = consumerSession.createConsumer(consumerSession.createQueue("myQueue")); + Message consumerMessage = consumer.receive(1000); + try { + String txId = consumerMessage.getStringProperty("JMSXProducerTXID"); + assertNotNull(txId); + } + catch (Exception e) { + LOG.info("Caught Exception that was not expected:", e); + fail("Should not throw"); + } + consumer.close(); + consumerSession.commit(); + consumerSession.close(); + connection.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4582Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4582Test.java index 1c34982098..9612a34828 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4582Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4582Test.java @@ -33,59 +33,63 @@ import org.slf4j.LoggerFactory; public class AMQ4582Test { - private static final transient Logger LOG = LoggerFactory.getLogger(AMQ4582Test.class); + private static final transient Logger LOG = LoggerFactory.getLogger(AMQ4582Test.class); - BrokerService broker; - Connection connection; - Session session; + BrokerService broker; + Connection connection; + Session session; - public static final String KEYSTORE_TYPE = "jks"; - public static final String PASSWORD = "password"; - public static final String SERVER_KEYSTORE = "src/test/resources/server.keystore"; - public static final String TRUST_KEYSTORE = "src/test/resources/client.keystore"; + public static final String KEYSTORE_TYPE = "jks"; + public static final String PASSWORD = "password"; + public static final String SERVER_KEYSTORE = "src/test/resources/server.keystore"; + public static final String TRUST_KEYSTORE = "src/test/resources/client.keystore"; - public static final int PRODUCER_COUNT = 10; - public static final int CONSUMER_COUNT = 10; - public static final int MESSAGE_COUNT = 1000; + public static final int PRODUCER_COUNT = 10; + public static final int CONSUMER_COUNT = 10; + public static final int MESSAGE_COUNT = 1000; - final ConsumerThread[] consumers = new ConsumerThread[CONSUMER_COUNT]; + final ConsumerThread[] consumers = new ConsumerThread[CONSUMER_COUNT]; - @Before - public void setUp() throws Exception { - System.setProperty("javax.net.ssl.trustStore", TRUST_KEYSTORE); - System.setProperty("javax.net.ssl.trustStorePassword", PASSWORD); - System.setProperty("javax.net.ssl.trustStoreType", KEYSTORE_TYPE); - System.setProperty("javax.net.ssl.keyStore", SERVER_KEYSTORE); - System.setProperty("javax.net.ssl.keyStoreType", KEYSTORE_TYPE); - System.setProperty("javax.net.ssl.keyStorePassword", PASSWORD); - } + @Before + public void setUp() throws Exception { + System.setProperty("javax.net.ssl.trustStore", TRUST_KEYSTORE); + System.setProperty("javax.net.ssl.trustStorePassword", PASSWORD); + System.setProperty("javax.net.ssl.trustStoreType", KEYSTORE_TYPE); + System.setProperty("javax.net.ssl.keyStore", SERVER_KEYSTORE); + System.setProperty("javax.net.ssl.keyStoreType", KEYSTORE_TYPE); + System.setProperty("javax.net.ssl.keyStorePassword", PASSWORD); + } - @After - public void tearDown() throws Exception { - if (broker != null) { - try { - broker.stop(); - } catch(Exception e) {} - } - } + @After + public void tearDown() throws Exception { + if (broker != null) { + try { + broker.stop(); + } + catch (Exception e) { + } + } + } - @Rule public ExpectedException thrown = ExpectedException.none(); - @Test - public void simpleTest() throws Exception { - thrown.expect(IOException.class); - thrown.expectMessage("enabledCipherSuites=BADSUITE"); + @Rule + public ExpectedException thrown = ExpectedException.none(); - broker = new BrokerService(); - broker.setPersistent(false); - broker.setUseJmx(false); - try { - broker.addConnector( - "ssl://localhost:0?transport.needClientAuth=true&transport.enabledCipherSuites=BADSUITE"); - broker.start(); - broker.waitUntilStarted(); - } catch (Exception e) { - LOG.info("BrokerService threw:", e); - throw e; - } - } + @Test + public void simpleTest() throws Exception { + thrown.expect(IOException.class); + thrown.expectMessage("enabledCipherSuites=BADSUITE"); + + broker = new BrokerService(); + broker.setPersistent(false); + broker.setUseJmx(false); + try { + broker.addConnector("ssl://localhost:0?transport.needClientAuth=true&transport.enabledCipherSuites=BADSUITE"); + broker.start(); + broker.waitUntilStarted(); + } + catch (Exception e) { + LOG.info("BrokerService threw:", e); + throw e; + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4595Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4595Test.java index 507e52e776..3c16baba75 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4595Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4595Test.java @@ -26,6 +26,7 @@ import javax.jms.MessageProducer; import javax.jms.QueueBrowser; import javax.jms.Session; import javax.jms.TextMessage; + import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; @@ -37,122 +38,121 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import static org.junit.Assert.assertEquals; public class AMQ4595Test { - private static final Logger LOG = LoggerFactory.getLogger(AMQ4595Test.class); + private static final Logger LOG = LoggerFactory.getLogger(AMQ4595Test.class); - private BrokerService broker; - private URI connectUri; - private ActiveMQConnectionFactory factory; + private BrokerService broker; + private URI connectUri; + private ActiveMQConnectionFactory factory; - @Before - public void startBroker() throws Exception { - broker = new BrokerService(); - TransportConnector connector = broker.addConnector("vm://localhost"); - broker.deleteAllMessages(); + @Before + public void startBroker() throws Exception { + broker = new BrokerService(); + TransportConnector connector = broker.addConnector("vm://localhost"); + broker.deleteAllMessages(); - //PolicyMap pMap = new PolicyMap(); - //PolicyEntry policyEntry = new PolicyEntry(); - //policyEntry.setMaxBrowsePageSize(10000); - //pMap.put(new ActiveMQQueue(">"), policyEntry); - // when no policy match, browserSub has maxMessages==0 - //broker.setDestinationPolicy(pMap); + //PolicyMap pMap = new PolicyMap(); + //PolicyEntry policyEntry = new PolicyEntry(); + //policyEntry.setMaxBrowsePageSize(10000); + //pMap.put(new ActiveMQQueue(">"), policyEntry); + // when no policy match, browserSub has maxMessages==0 + //broker.setDestinationPolicy(pMap); - broker.getSystemUsage().getMemoryUsage().setLimit(256 * 1024 * 1024); - broker.start(); - broker.waitUntilStarted(); - connectUri = connector.getConnectUri(); - factory = new ActiveMQConnectionFactory(connectUri); - } + broker.getSystemUsage().getMemoryUsage().setLimit(256 * 1024 * 1024); + broker.start(); + broker.waitUntilStarted(); + connectUri = connector.getConnectUri(); + factory = new ActiveMQConnectionFactory(connectUri); + } - @After - public void stopBroker() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } + @After + public void stopBroker() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + } - @Test(timeout=120000) - public void testBrowsingSmallBatch() throws JMSException { - doTestBrowsing(100); - } + @Test(timeout = 120000) + public void testBrowsingSmallBatch() throws JMSException { + doTestBrowsing(100); + } - @Test(timeout=160000) - public void testBrowsingMediumBatch() throws JMSException { - doTestBrowsing(1000); - } + @Test(timeout = 160000) + public void testBrowsingMediumBatch() throws JMSException { + doTestBrowsing(1000); + } - @Test(timeout=300000) - public void testBrowsingLargeBatch() throws JMSException { - doTestBrowsing(10000); - } + @Test(timeout = 300000) + public void testBrowsingLargeBatch() throws JMSException { + doTestBrowsing(10000); + } - private void doTestBrowsing(int messageToSend) throws JMSException { - ActiveMQQueue queue = new ActiveMQQueue("TEST"); + private void doTestBrowsing(int messageToSend) throws JMSException { + ActiveMQQueue queue = new ActiveMQQueue("TEST"); - // Send the messages to the Queue. - ActiveMQConnection producerConnection = (ActiveMQConnection) factory.createConnection(); - producerConnection.setUseAsyncSend(true); - producerConnection.start(); - Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = producerSession.createProducer(queue); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); + // Send the messages to the Queue. + ActiveMQConnection producerConnection = (ActiveMQConnection) factory.createConnection(); + producerConnection.setUseAsyncSend(true); + producerConnection.start(); + Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = producerSession.createProducer(queue); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); - for (int i = 1; i <= messageToSend; i++) { - String msgStr = provideMessageText(i, 8192); - producer.send(producerSession.createTextMessage(msgStr)); - if ((i % 1000) == 0) { - LOG.info("P&C: {}", msgStr.substring(0, 100)); - } - } - producerConnection.close(); + for (int i = 1; i <= messageToSend; i++) { + String msgStr = provideMessageText(i, 8192); + producer.send(producerSession.createTextMessage(msgStr)); + if ((i % 1000) == 0) { + LOG.info("P&C: {}", msgStr.substring(0, 100)); + } + } + producerConnection.close(); - LOG.info("Mem usage after producer done: " + broker.getSystemUsage().getMemoryUsage().getPercentUsage() + "%"); + LOG.info("Mem usage after producer done: " + broker.getSystemUsage().getMemoryUsage().getPercentUsage() + "%"); - // Browse the queue. - Connection connection = factory.createConnection(); - connection.start(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + // Browse the queue. + Connection connection = factory.createConnection(); + connection.start(); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - QueueBrowser browser = session.createBrowser(queue); - Enumeration enumeration = browser.getEnumeration(); - int browsed = 0; - while (enumeration.hasMoreElements()) { - TextMessage m = (TextMessage) enumeration.nextElement(); - browsed++; - if ((browsed % 1000) == 0) { - LOG.info("B[{}]: {}", browsed, m.getText().substring(0, 100)); - } - } - browser.close(); - session.close(); - connection.close(); + QueueBrowser browser = session.createBrowser(queue); + Enumeration enumeration = browser.getEnumeration(); + int browsed = 0; + while (enumeration.hasMoreElements()) { + TextMessage m = (TextMessage) enumeration.nextElement(); + browsed++; + if ((browsed % 1000) == 0) { + LOG.info("B[{}]: {}", browsed, m.getText().substring(0, 100)); + } + } + browser.close(); + session.close(); + connection.close(); - LOG.info("Mem usage after browser closed: " + broker.getSystemUsage().getMemoryUsage().getPercentUsage() + "%"); + LOG.info("Mem usage after browser closed: " + broker.getSystemUsage().getMemoryUsage().getPercentUsage() + "%"); - // The number of messages browsed should be equal to the number of messages sent. - assertEquals(messageToSend, browsed); + // The number of messages browsed should be equal to the number of messages sent. + assertEquals(messageToSend, browsed); - browser.close(); - } + browser.close(); + } - public String provideMessageText(int messageNumber, int messageSize) { - StringBuilder buf = new StringBuilder(); - buf.append("Message: "); - if (messageNumber > 0) { - buf.append(messageNumber); - } - buf.append(" sent at: ").append(new Date()); + public String provideMessageText(int messageNumber, int messageSize) { + StringBuilder buf = new StringBuilder(); + buf.append("Message: "); + if (messageNumber > 0) { + buf.append(messageNumber); + } + buf.append(" sent at: ").append(new Date()); - if (buf.length() > messageSize) { - return buf.substring(0, messageSize); - } - for (int i = buf.length(); i < messageSize; i++) { - buf.append(' '); - } - return buf.toString(); - } + if (buf.length() > messageSize) { + return buf.substring(0, messageSize); + } + for (int i = buf.length(); i < messageSize; i++) { + buf.append(' '); + } + return buf.toString(); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4607Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4607Test.java index b567c93c05..53a048e89b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4607Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4607Test.java @@ -25,7 +25,9 @@ import java.util.Map; import java.util.Map.Entry; import javax.jms.Destination; import javax.jms.MessageConsumer; + import junit.framework.Test; + import org.apache.activemq.JmsMultipleBrokersTestSupport; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.jmx.ManagementContext; @@ -39,208 +41,221 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AMQ4607Test extends JmsMultipleBrokersTestSupport implements UncaughtExceptionHandler { - private static final Logger LOG = LoggerFactory.getLogger(AMQ4607Test.class); - public static final int BROKER_COUNT = 3; - public static final int CONSUMER_COUNT = 1; - public static final int MESSAGE_COUNT = 0; - public static final boolean CONDUIT = true; - public static final int TIMEOUT = 20000; + private static final Logger LOG = LoggerFactory.getLogger(AMQ4607Test.class); - public boolean duplex = true; - protected Map consumerMap; - final Map unhandeledExceptions = new HashMap(); + public static final int BROKER_COUNT = 3; + public static final int CONSUMER_COUNT = 1; + public static final int MESSAGE_COUNT = 0; + public static final boolean CONDUIT = true; + public static final int TIMEOUT = 20000; - private void assertNoUnhandeledExceptions() { - for( Entry e: unhandeledExceptions.entrySet()) { - LOG.error("Thread:" + e.getKey() + " Had unexpected: " + e.getValue()); - } - assertTrue("There are no unhandelled exceptions, see: log for detail on: " + unhandeledExceptions, - unhandeledExceptions.isEmpty()); - } + public boolean duplex = true; + protected Map consumerMap; + final Map unhandeledExceptions = new HashMap(); - public NetworkConnector bridge(String from, String to) throws Exception { - NetworkConnector networkConnector = bridgeBrokers(from, to, true, -1, CONDUIT); - networkConnector.setSuppressDuplicateQueueSubscriptions(true); - networkConnector.setDecreaseNetworkConsumerPriority(true); - networkConnector.setConsumerTTL(1); - networkConnector.setDuplex(duplex); - return networkConnector; - } + private void assertNoUnhandeledExceptions() { + for (Entry e : unhandeledExceptions.entrySet()) { + LOG.error("Thread:" + e.getKey() + " Had unexpected: " + e.getValue()); + } + assertTrue("There are no unhandelled exceptions, see: log for detail on: " + unhandeledExceptions, unhandeledExceptions.isEmpty()); + } - public static Test suite() { - return suite(AMQ4607Test.class); - } + public NetworkConnector bridge(String from, String to) throws Exception { + NetworkConnector networkConnector = bridgeBrokers(from, to, true, -1, CONDUIT); + networkConnector.setSuppressDuplicateQueueSubscriptions(true); + networkConnector.setDecreaseNetworkConsumerPriority(true); + networkConnector.setConsumerTTL(1); + networkConnector.setDuplex(duplex); + return networkConnector; + } - public void initCombos() { - addCombinationValues("duplex", new Boolean[]{Boolean.TRUE, Boolean.FALSE}); - } + public static Test suite() { + return suite(AMQ4607Test.class); + } - public void testMigratingConsumer() throws Exception { - bridge("Broker0", "Broker1"); - if (!duplex) bridge("Broker1", "Broker0"); + public void initCombos() { + addCombinationValues("duplex", new Boolean[]{Boolean.TRUE, Boolean.FALSE}); + } - bridge("Broker1", "Broker2"); - if (!duplex) bridge("Broker2", "Broker1"); + public void testMigratingConsumer() throws Exception { + bridge("Broker0", "Broker1"); + if (!duplex) + bridge("Broker1", "Broker0"); - bridge("Broker0", "Broker2"); - if (!duplex) bridge("Broker2", "Broker0"); + bridge("Broker1", "Broker2"); + if (!duplex) + bridge("Broker2", "Broker1"); - startAllBrokers(); - this.waitForBridgeFormation(); + bridge("Broker0", "Broker2"); + if (!duplex) + bridge("Broker2", "Broker0"); - Destination dest = createDestination("TEST.FOO", false); - sendMessages("Broker0", dest, 1); + startAllBrokers(); + this.waitForBridgeFormation(); - for (int i=0; i< BROKER_COUNT; i++) { - MessageConsumer messageConsumer = createConsumer("Broker" + i, dest, "DoNotConsume = 'true'"); + Destination dest = createDestination("TEST.FOO", false); + sendMessages("Broker0", dest, 1); - for (int J = 0; J < BROKER_COUNT; J++) { - assertExactConsumersConnect("Broker" + J, dest, CONSUMER_COUNT, TIMEOUT); + for (int i = 0; i < BROKER_COUNT; i++) { + MessageConsumer messageConsumer = createConsumer("Broker" + i, dest, "DoNotConsume = 'true'"); + + for (int J = 0; J < BROKER_COUNT; J++) { + assertExactConsumersConnect("Broker" + J, dest, CONSUMER_COUNT, TIMEOUT); + } + + assertNoUnhandeledExceptions(); + + assertExactMessageCount("Broker" + i, dest, 1, TIMEOUT); + + messageConsumer.close(); + LOG.info("Check for no consumers.."); + for (int J = 0; J < BROKER_COUNT; J++) { + assertExactConsumersConnect("Broker" + J, dest, 0, TIMEOUT); + } + } + + // now consume the message + final String brokerId = "Broker2"; + MessageConsumer messageConsumer = createConsumer(brokerId, dest); + assertTrue("Consumed ok", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return brokers.get(brokerId).allMessages.getMessageIds().size() == 1; + } + })); + messageConsumer.close(); + + } + + public void testMigratingConsumerFullCircle() throws Exception { + bridge("Broker0", "Broker1"); + if (!duplex) + bridge("Broker1", "Broker0"); + + bridge("Broker1", "Broker2"); + if (!duplex) + bridge("Broker2", "Broker1"); + + bridge("Broker0", "Broker2"); + if (!duplex) + bridge("Broker2", "Broker0"); + + // allow full loop, immediate replay back to 0 from 2 + ConditionalNetworkBridgeFilterFactory conditionalNetworkBridgeFilterFactory = new ConditionalNetworkBridgeFilterFactory(); + conditionalNetworkBridgeFilterFactory.setReplayDelay(0); + conditionalNetworkBridgeFilterFactory.setReplayWhenNoConsumers(true); + brokers.get("Broker2").broker.getDestinationPolicy().getDefaultEntry().setNetworkBridgeFilterFactory(conditionalNetworkBridgeFilterFactory); + startAllBrokers(); + this.waitForBridgeFormation(); + + Destination dest = createDestination("TEST.FOO", false); + + sendMessages("Broker0", dest, 1); + + for (int i = 0; i < BROKER_COUNT; i++) { + MessageConsumer messageConsumer = createConsumer("Broker" + i, dest, "DoNotConsume = 'true'"); + + for (int J = 0; J < BROKER_COUNT; J++) { + assertExactConsumersConnect("Broker" + J, dest, CONSUMER_COUNT, TIMEOUT); + } + + assertNoUnhandeledExceptions(); + + // validate the message has been forwarded + assertExactMessageCount("Broker" + i, dest, 1, TIMEOUT); + + messageConsumer.close(); + LOG.info("Check for no consumers.."); + for (int J = 0; J < BROKER_COUNT; J++) { + assertExactConsumersConnect("Broker" + J, dest, 0, TIMEOUT); + } + } + + // now consume the message from the origin + LOG.info("Consume from origin..."); + final String brokerId = "Broker0"; + MessageConsumer messageConsumer = createConsumer(brokerId, dest); + assertTrue("Consumed ok", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return brokers.get(brokerId).allMessages.getMessageIds().size() == 1; + } + })); + messageConsumer.close(); + + } + + protected void assertExactMessageCount(final String brokerName, + Destination destination, + final int count, + long timeout) throws Exception { + ManagementContext context = brokers.get(brokerName).broker.getManagementContext(); + final QueueViewMBean queueViewMBean = (QueueViewMBean) context.newProxyInstance(brokers.get(brokerName).broker.getAdminView().getQueues()[0], QueueViewMBean.class, false); + assertTrue("Excepected queue depth: " + count + " on: " + brokerName, Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + long currentCount = queueViewMBean.getQueueSize(); + LOG.info("On " + brokerName + " current queue size for " + queueViewMBean + ", " + currentCount); + if (count != currentCount) { + LOG.info("Sub IDs: " + Arrays.asList(queueViewMBean.getSubscriptions())); } + return currentCount == count; + } + }, timeout)); + } - assertNoUnhandeledExceptions(); - - assertExactMessageCount("Broker" + i, dest, 1, TIMEOUT); - - messageConsumer.close(); - LOG.info("Check for no consumers.."); - for (int J = 0; J < BROKER_COUNT; J++) { - assertExactConsumersConnect("Broker" + J, dest, 0, TIMEOUT); + protected void assertExactConsumersConnect(final String brokerName, + Destination destination, + final int count, + long timeout) throws Exception { + final ManagementContext context = brokers.get(brokerName).broker.getManagementContext(); + assertTrue("Excepected consumers count: " + count + " on: " + brokerName, Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + try { + QueueViewMBean queueViewMBean = (QueueViewMBean) context.newProxyInstance(brokers.get(brokerName).broker.getAdminView().getQueues()[0], QueueViewMBean.class, false); + long currentCount = queueViewMBean.getConsumerCount(); + LOG.info("On " + brokerName + " current consumer count for " + queueViewMBean + ", " + currentCount); + if (count != currentCount) { + LOG.info("Sub IDs: " + Arrays.asList(queueViewMBean.getSubscriptions())); + } + return currentCount == count; } - } - - // now consume the message - final String brokerId = "Broker2"; - MessageConsumer messageConsumer = createConsumer(brokerId, dest); - assertTrue("Consumed ok", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return brokers.get(brokerId).allMessages.getMessageIds().size() == 1; + catch (Exception e) { + LOG.warn("Unexpected: " + e, e); + return false; } - })); - messageConsumer.close(); + } + }, timeout)); + } - } + public void setUp() throws Exception { + super.setUp(); - public void testMigratingConsumerFullCircle() throws Exception { - bridge("Broker0", "Broker1"); - if (!duplex) bridge("Broker1", "Broker0"); + unhandeledExceptions.clear(); + Thread.setDefaultUncaughtExceptionHandler(this); - bridge("Broker1", "Broker2"); - if (!duplex) bridge("Broker2", "Broker1"); + // Setup n brokers + for (int i = 0; i < BROKER_COUNT; i++) { + createBroker(new URI("broker:(tcp://localhost:6161" + i + ")/Broker" + i + "?persistent=false&useJmx=true")); + } - bridge("Broker0", "Broker2"); - if (!duplex) bridge("Broker2", "Broker0"); + consumerMap = new LinkedHashMap(); + } - // allow full loop, immediate replay back to 0 from 2 - ConditionalNetworkBridgeFilterFactory conditionalNetworkBridgeFilterFactory = new ConditionalNetworkBridgeFilterFactory(); - conditionalNetworkBridgeFilterFactory.setReplayDelay(0); - conditionalNetworkBridgeFilterFactory.setReplayWhenNoConsumers(true); - brokers.get("Broker2").broker.getDestinationPolicy().getDefaultEntry().setNetworkBridgeFilterFactory(conditionalNetworkBridgeFilterFactory); - startAllBrokers(); - this.waitForBridgeFormation(); + @Override + protected void configureBroker(BrokerService brokerService) { + PolicyEntry policyEntry = new PolicyEntry(); + policyEntry.setExpireMessagesPeriod(0); + PolicyMap policyMap = new PolicyMap(); + policyMap.setDefaultEntry(policyEntry); + brokerService.setDestinationPolicy(policyMap); + } - Destination dest = createDestination("TEST.FOO", false); - - sendMessages("Broker0", dest, 1); - - for (int i=0; i< BROKER_COUNT; i++) { - MessageConsumer messageConsumer = createConsumer("Broker" + i, dest, "DoNotConsume = 'true'"); - - for (int J = 0; J < BROKER_COUNT; J++) { - assertExactConsumersConnect("Broker" + J, dest, CONSUMER_COUNT, TIMEOUT); - } - - assertNoUnhandeledExceptions(); - - // validate the message has been forwarded - assertExactMessageCount("Broker" + i, dest, 1, TIMEOUT); - - messageConsumer.close(); - LOG.info("Check for no consumers.."); - for (int J = 0; J < BROKER_COUNT; J++) { - assertExactConsumersConnect("Broker" + J, dest, 0, TIMEOUT); - } - } - - // now consume the message from the origin - LOG.info("Consume from origin..."); - final String brokerId = "Broker0"; - MessageConsumer messageConsumer = createConsumer(brokerId, dest); - assertTrue("Consumed ok", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return brokers.get(brokerId).allMessages.getMessageIds().size() == 1; - } - })); - messageConsumer.close(); - - } - - protected void assertExactMessageCount(final String brokerName, Destination destination, final int count, long timeout) throws Exception { - ManagementContext context = brokers.get(brokerName).broker.getManagementContext(); - final QueueViewMBean queueViewMBean = (QueueViewMBean) context.newProxyInstance(brokers.get(brokerName).broker.getAdminView().getQueues()[0], QueueViewMBean.class, false); - assertTrue("Excepected queue depth: " + count + " on: " + brokerName, Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - long currentCount = queueViewMBean.getQueueSize(); - LOG.info("On " + brokerName + " current queue size for " + queueViewMBean + ", " + currentCount); - if (count != currentCount) { - LOG.info("Sub IDs: " + Arrays.asList(queueViewMBean.getSubscriptions())); - } - return currentCount == count; - } - }, timeout)); - } - - protected void assertExactConsumersConnect(final String brokerName, Destination destination, final int count, long timeout) throws Exception { - final ManagementContext context = brokers.get(brokerName).broker.getManagementContext(); - assertTrue("Excepected consumers count: " + count + " on: " + brokerName, Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - try { - QueueViewMBean queueViewMBean = (QueueViewMBean) context.newProxyInstance(brokers.get(brokerName).broker.getAdminView().getQueues()[0], QueueViewMBean.class, false); - long currentCount = queueViewMBean.getConsumerCount(); - LOG.info("On " + brokerName + " current consumer count for " + queueViewMBean + ", " + currentCount); - if (count != currentCount) { - LOG.info("Sub IDs: " + Arrays.asList(queueViewMBean.getSubscriptions())); - } - return currentCount == count; - } catch (Exception e) { - LOG.warn("Unexpected: " + e, e); - return false; - } - } - }, timeout)); - } - - public void setUp() throws Exception { - super.setUp(); - - unhandeledExceptions.clear(); - Thread.setDefaultUncaughtExceptionHandler(this); - - // Setup n brokers - for (int i = 0; i < BROKER_COUNT; i++) { - createBroker(new URI("broker:(tcp://localhost:6161" + i + ")/Broker" + i + "?persistent=false&useJmx=true")); - } - - consumerMap = new LinkedHashMap(); - } - - @Override - protected void configureBroker(BrokerService brokerService) { - PolicyEntry policyEntry = new PolicyEntry(); - policyEntry.setExpireMessagesPeriod(0); - PolicyMap policyMap = new PolicyMap(); - policyMap.setDefaultEntry(policyEntry); - brokerService.setDestinationPolicy(policyMap); - } - - public void uncaughtException(Thread t, Throwable e) { - synchronized(unhandeledExceptions) { - unhandeledExceptions.put(t,e); - } - } + public void uncaughtException(Thread t, Throwable e) { + synchronized (unhandeledExceptions) { + unhandeledExceptions.put(t, e); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4636Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4636Test.java index 1e0ccb9127..11241c634d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4636Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4636Test.java @@ -28,6 +28,7 @@ import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.Topic; import javax.jms.TopicSubscriber; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.region.policy.PolicyEntry; @@ -44,6 +45,7 @@ import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import static org.junit.Assert.fail; /** @@ -54,214 +56,207 @@ import static org.junit.Assert.fail; */ public class AMQ4636Test { - private static final String MY_TEST_TOPIC = "MY_TEST_TOPIC"; - private static final Logger LOG = LoggerFactory - .getLogger(AMQ4636Test.class); - private String transportUrl = "tcp://0.0.0.0:0"; - private BrokerService broker; - EmbeddedDataSource embeddedDataSource; - CountDownLatch throwSQLException = new CountDownLatch(0); + private static final String MY_TEST_TOPIC = "MY_TEST_TOPIC"; + private static final Logger LOG = LoggerFactory.getLogger(AMQ4636Test.class); + private String transportUrl = "tcp://0.0.0.0:0"; + private BrokerService broker; + EmbeddedDataSource embeddedDataSource; + CountDownLatch throwSQLException = new CountDownLatch(0); - @Before - public void startBroker() throws Exception { - broker = createBroker(); - broker.deleteAllMessages(); - broker.start(); - broker.waitUntilStarted(); - LOG.info("Broker started..."); - } + @Before + public void startBroker() throws Exception { + broker = createBroker(); + broker.deleteAllMessages(); + broker.start(); + broker.waitUntilStarted(); + LOG.info("Broker started..."); + } - @After - public void stopBroker() throws Exception { - if (broker != null) { - LOG.info("Stopping broker..."); - broker.stop(); - broker.waitUntilStopped(); - } - try { - if (embeddedDataSource != null) { - // ref http://svn.apache.org/viewvc/db/derby/code/trunk/java/testing/org/apache/derbyTesting/junit/JDBCDataSource.java?view=markup - embeddedDataSource.setShutdownDatabase("shutdown"); - embeddedDataSource.getConnection(); + @After + public void stopBroker() throws Exception { + if (broker != null) { + LOG.info("Stopping broker..."); + broker.stop(); + broker.waitUntilStopped(); + } + try { + if (embeddedDataSource != null) { + // ref http://svn.apache.org/viewvc/db/derby/code/trunk/java/testing/org/apache/derbyTesting/junit/JDBCDataSource.java?view=markup + embeddedDataSource.setShutdownDatabase("shutdown"); + embeddedDataSource.getConnection(); + } + } + catch (Exception ignored) { + } + finally { + embeddedDataSource.setShutdownDatabase(null); + } + } + + protected BrokerService createBroker() throws Exception { + + embeddedDataSource = (EmbeddedDataSource) DataSourceServiceSupport.createDataSource(IOHelper.getDefaultDataDirectory()); + embeddedDataSource.setCreateDatabase("create"); + embeddedDataSource.getConnection().close(); + + //wire in a TestTransactionContext (wrapper to TransactionContext) that has an executeBatch() + // method that can be configured to throw a SQL exception on demand + JDBCPersistenceAdapter jdbc = new TestJDBCPersistenceAdapter(); + jdbc.setDataSource(embeddedDataSource); + + jdbc.setLockKeepAlivePeriod(1000L); + LeaseDatabaseLocker leaseDatabaseLocker = new LeaseDatabaseLocker(); + leaseDatabaseLocker.setLockAcquireSleepInterval(2000L); + jdbc.setLocker(leaseDatabaseLocker); + + broker = new BrokerService(); + PolicyMap policyMap = new PolicyMap(); + PolicyEntry defaultEntry = new PolicyEntry(); + defaultEntry.setExpireMessagesPeriod(0); + policyMap.setDefaultEntry(defaultEntry); + broker.setDestinationPolicy(policyMap); + broker.setPersistenceAdapter(jdbc); + + broker.setIoExceptionHandler(new LeaseLockerIOExceptionHandler()); + + transportUrl = broker.addConnector(transportUrl).getPublishableConnectString(); + return broker; + } + + /** + * adding a TestTransactionContext (wrapper to TransactionContext) so an SQLException is triggered + * during TransactionContext.executeBatch() when called in the broker. + *
    + * Expectation: SQLException triggers a connection shutdown and failover should kick and try to redeliver the + * message. SQLException should NOT be returned to client + */ + @Test + public void testProducerWithDBShutdown() throws Exception { + + // failover but timeout in 1 seconds so the test does not hang + String failoverTransportURL = "failover:(" + transportUrl + ")?timeout=1000"; + + this.createDurableConsumer(MY_TEST_TOPIC, failoverTransportURL); + + this.sendMessage(MY_TEST_TOPIC, failoverTransportURL, false, false); + + } + + @Test + public void testTransactedProducerCommitWithDBShutdown() throws Exception { + + // failover but timeout in 1 seconds so the test does not hang + String failoverTransportURL = "failover:(" + transportUrl + ")?timeout=1000"; + + this.createDurableConsumer(MY_TEST_TOPIC, failoverTransportURL); + + try { + this.sendMessage(MY_TEST_TOPIC, failoverTransportURL, true, true); + fail("Expect rollback after failover - inddoubt commit"); + } + catch (javax.jms.TransactionRolledBackException expectedInDoubt) { + LOG.info("Got rollback after failover failed commit", expectedInDoubt); + } + } + + @Test + public void testTransactedProducerRollbackWithDBShutdown() throws Exception { + + // failover but timeout in 1 seconds so the test does not hang + String failoverTransportURL = "failover:(" + transportUrl + ")?timeout=1000"; + + this.createDurableConsumer(MY_TEST_TOPIC, failoverTransportURL); + + this.sendMessage(MY_TEST_TOPIC, failoverTransportURL, true, false); + } + + public void createDurableConsumer(String topic, String transportURL) throws JMSException { + Connection connection = null; + LOG.info("*** createDurableConsumer() called ..."); + + try { + + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(transportURL); + + connection = factory.createConnection(); + connection.setClientID("myconn1"); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createTopic(topic); + + TopicSubscriber topicSubscriber = session.createDurableSubscriber((Topic) destination, "MySub1"); + } + finally { + if (connection != null) { + connection.close(); + } + } + } + + public void sendMessage(String topic, String transportURL, boolean transacted, boolean commit) throws JMSException { + Connection connection = null; + + try { + + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(transportURL); + + connection = factory.createConnection(); + Session session = connection.createSession(transacted, transacted ? Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createTopic(topic); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + + Message m = session.createTextMessage("testMessage"); + LOG.info("*** send message to broker..."); + + // trigger SQL exception in transactionContext + throwSQLException = new CountDownLatch(1); + producer.send(m); + + if (transacted) { + if (commit) { + session.commit(); } - } catch (Exception ignored) { - } finally { - embeddedDataSource.setShutdownDatabase(null); - } - } - - protected BrokerService createBroker() throws Exception { - - embeddedDataSource = (EmbeddedDataSource) DataSourceServiceSupport.createDataSource(IOHelper.getDefaultDataDirectory()); - embeddedDataSource.setCreateDatabase("create"); - embeddedDataSource.getConnection().close(); - - //wire in a TestTransactionContext (wrapper to TransactionContext) that has an executeBatch() - // method that can be configured to throw a SQL exception on demand - JDBCPersistenceAdapter jdbc = new TestJDBCPersistenceAdapter(); - jdbc.setDataSource(embeddedDataSource); - - jdbc.setLockKeepAlivePeriod(1000L); - LeaseDatabaseLocker leaseDatabaseLocker = new LeaseDatabaseLocker(); - leaseDatabaseLocker.setLockAcquireSleepInterval(2000L); - jdbc.setLocker(leaseDatabaseLocker); - - broker = new BrokerService(); - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setExpireMessagesPeriod(0); - policyMap.setDefaultEntry(defaultEntry); - broker.setDestinationPolicy(policyMap); - broker.setPersistenceAdapter(jdbc); - - broker.setIoExceptionHandler(new LeaseLockerIOExceptionHandler()); - - transportUrl = broker.addConnector(transportUrl).getPublishableConnectString(); - return broker; - } - - /** - * adding a TestTransactionContext (wrapper to TransactionContext) so an SQLException is triggered - * during TransactionContext.executeBatch() when called in the broker. - *
    - * Expectation: SQLException triggers a connection shutdown and failover should kick and try to redeliver the - * message. SQLException should NOT be returned to client - */ - @Test - public void testProducerWithDBShutdown() throws Exception { - - // failover but timeout in 1 seconds so the test does not hang - String failoverTransportURL = "failover:(" + transportUrl - + ")?timeout=1000"; - - this.createDurableConsumer(MY_TEST_TOPIC, failoverTransportURL); - - this.sendMessage(MY_TEST_TOPIC, failoverTransportURL, false, false); - - } - - @Test - public void testTransactedProducerCommitWithDBShutdown() throws Exception { - - // failover but timeout in 1 seconds so the test does not hang - String failoverTransportURL = "failover:(" + transportUrl - + ")?timeout=1000"; - - this.createDurableConsumer(MY_TEST_TOPIC, failoverTransportURL); - - try { - this.sendMessage(MY_TEST_TOPIC, failoverTransportURL, true, true); - fail("Expect rollback after failover - inddoubt commit"); - } catch (javax.jms.TransactionRolledBackException expectedInDoubt) { - LOG.info("Got rollback after failover failed commit", expectedInDoubt); - } - } - - @Test - public void testTransactedProducerRollbackWithDBShutdown() throws Exception { - - // failover but timeout in 1 seconds so the test does not hang - String failoverTransportURL = "failover:(" + transportUrl - + ")?timeout=1000"; - - this.createDurableConsumer(MY_TEST_TOPIC, failoverTransportURL); - - this.sendMessage(MY_TEST_TOPIC, failoverTransportURL, true, false); - } - - public void createDurableConsumer(String topic, - String transportURL) throws JMSException { - Connection connection = null; - LOG.info("*** createDurableConsumer() called ..."); - - try { - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory( - transportURL); - - connection = factory.createConnection(); - connection.setClientID("myconn1"); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createTopic(topic); - - TopicSubscriber topicSubscriber = session.createDurableSubscriber( - (Topic) destination, "MySub1"); - } finally { - if (connection != null) { - connection.close(); + else { + session.rollback(); } - } - } + } - public void sendMessage(String topic, String transportURL, boolean transacted, boolean commit) - throws JMSException { - Connection connection = null; + LOG.info("*** Finished send message to broker"); - try { - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory( - transportURL); - - connection = factory.createConnection(); - Session session = connection.createSession(transacted, - transacted ? Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createTopic(topic); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - - Message m = session.createTextMessage("testMessage"); - LOG.info("*** send message to broker..."); - - // trigger SQL exception in transactionContext - throwSQLException = new CountDownLatch(1); - producer.send(m); - - if (transacted) { - if (commit) { - session.commit(); - } else { - session.rollback(); - } - } - - LOG.info("*** Finished send message to broker"); - - } finally { - if (connection != null) { - connection.close(); - } - } - } + } + finally { + if (connection != null) { + connection.close(); + } + } + } /* * Mock classes used for testing */ - public class TestJDBCPersistenceAdapter extends JDBCPersistenceAdapter { + public class TestJDBCPersistenceAdapter extends JDBCPersistenceAdapter { - public TransactionContext getTransactionContext() throws IOException { - return new TestTransactionContext(this); - } - } + public TransactionContext getTransactionContext() throws IOException { + return new TestTransactionContext(this); + } + } - public class TestTransactionContext extends TransactionContext { + public class TestTransactionContext extends TransactionContext { - public TestTransactionContext( - JDBCPersistenceAdapter jdbcPersistenceAdapter) - throws IOException { - super(jdbcPersistenceAdapter); - } + public TestTransactionContext(JDBCPersistenceAdapter jdbcPersistenceAdapter) throws IOException { + super(jdbcPersistenceAdapter); + } - @Override - public void executeBatch() throws SQLException { - if (throwSQLException.getCount() > 0) { - // only throw exception once - throwSQLException.countDown(); - throw new SQLException("TEST SQL EXCEPTION"); - } - super.executeBatch(); - } - } + @Override + public void executeBatch() throws SQLException { + if (throwSQLException.getCount() > 0) { + // only throw exception once + throwSQLException.countDown(); + throw new SQLException("TEST SQL EXCEPTION"); + } + super.executeBatch(); + } + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4656Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4656Test.java index fcdf23edd8..0fb900a917 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4656Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4656Test.java @@ -17,6 +17,7 @@ package org.apache.activemq.bugs; import java.util.Arrays; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -48,106 +49,105 @@ import org.slf4j.LoggerFactory; @RunWith(value = Parameterized.class) public class AMQ4656Test { - private static final transient Logger LOG = LoggerFactory.getLogger(AMQ4656Test.class); - private static BrokerService brokerService; - private static String BROKER_ADDRESS = "tcp://localhost:0"; + private static final transient Logger LOG = LoggerFactory.getLogger(AMQ4656Test.class); + private static BrokerService brokerService; + private static String BROKER_ADDRESS = "tcp://localhost:0"; - private String connectionUri; + private String connectionUri; - @Parameterized.Parameter - public PendingDurableSubscriberMessageStoragePolicy pendingDurableSubPolicy; + @Parameterized.Parameter + public PendingDurableSubscriberMessageStoragePolicy pendingDurableSubPolicy; - @Parameterized.Parameters(name="{0}") - public static Iterable getTestParameters() { - return Arrays.asList(new Object[][]{{new FilePendingDurableSubscriberMessageStoragePolicy()},{new StorePendingDurableSubscriberMessageStoragePolicy()}}); - } + @Parameterized.Parameters(name = "{0}") + public static Iterable getTestParameters() { + return Arrays.asList(new Object[][]{{new FilePendingDurableSubscriberMessageStoragePolicy()}, {new StorePendingDurableSubscriberMessageStoragePolicy()}}); + } - @Before - public void setUp() throws Exception { - brokerService = new BrokerService(); - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setPendingDurableSubscriberPolicy(pendingDurableSubPolicy); - policyMap.setDefaultEntry(defaultEntry); - brokerService.setDestinationPolicy(policyMap); - brokerService.setPersistent(false); - brokerService.setUseJmx(true); - brokerService.setDeleteAllMessagesOnStartup(true); - connectionUri = brokerService.addConnector(BROKER_ADDRESS).getPublishableConnectString(); - brokerService.start(); - brokerService.waitUntilStarted(); - } + @Before + public void setUp() throws Exception { + brokerService = new BrokerService(); + PolicyMap policyMap = new PolicyMap(); + PolicyEntry defaultEntry = new PolicyEntry(); + defaultEntry.setPendingDurableSubscriberPolicy(pendingDurableSubPolicy); + policyMap.setDefaultEntry(defaultEntry); + brokerService.setDestinationPolicy(policyMap); + brokerService.setPersistent(false); + brokerService.setUseJmx(true); + brokerService.setDeleteAllMessagesOnStartup(true); + connectionUri = brokerService.addConnector(BROKER_ADDRESS).getPublishableConnectString(); + brokerService.start(); + brokerService.waitUntilStarted(); + } - @After - public void tearDown() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - } + @After + public void tearDown() throws Exception { + brokerService.stop(); + brokerService.waitUntilStopped(); + } - @Test - public void testDurableConsumerEnqueueCountWithZeroPrefetch() throws Exception { + @Test + public void testDurableConsumerEnqueueCountWithZeroPrefetch() throws Exception { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionUri); + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionUri); - Connection connection = connectionFactory.createConnection(); - connection.setClientID(getClass().getName()); - connection.start(); + Connection connection = connectionFactory.createConnection(); + connection.setClientID(getClass().getName()); + connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createTopic("DurableTopic"); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createTopic("DurableTopic"); - MessageConsumer consumer = session.createDurableSubscriber((Topic) destination, "EnqueueSub"); + MessageConsumer consumer = session.createDurableSubscriber((Topic) destination, "EnqueueSub"); - BrokerView view = brokerService.getAdminView(); - view.getDurableTopicSubscribers(); + BrokerView view = brokerService.getAdminView(); + view.getDurableTopicSubscribers(); - ObjectName subName = view.getDurableTopicSubscribers()[0]; + ObjectName subName = view.getDurableTopicSubscribers()[0]; - DurableSubscriptionViewMBean sub = (DurableSubscriptionViewMBean) - brokerService.getManagementContext().newProxyInstance(subName, DurableSubscriptionViewMBean.class, true); + DurableSubscriptionViewMBean sub = (DurableSubscriptionViewMBean) brokerService.getManagementContext().newProxyInstance(subName, DurableSubscriptionViewMBean.class, true); - assertEquals(0, sub.getEnqueueCounter()); - assertEquals(0, sub.getDequeueCounter()); - assertEquals(0, sub.getPendingQueueSize()); - assertEquals(0, sub.getDispatchedCounter()); - assertEquals(0, sub.getDispatchedQueueSize()); + assertEquals(0, sub.getEnqueueCounter()); + assertEquals(0, sub.getDequeueCounter()); + assertEquals(0, sub.getPendingQueueSize()); + assertEquals(0, sub.getDispatchedCounter()); + assertEquals(0, sub.getDispatchedQueueSize()); - consumer.close(); + consumer.close(); - MessageProducer producer = session.createProducer(destination); - for (int i = 0; i < 20; i++) { - producer.send(session.createMessage()); - } - producer.close(); + MessageProducer producer = session.createProducer(destination); + for (int i = 0; i < 20; i++) { + producer.send(session.createMessage()); + } + producer.close(); - consumer = session.createDurableSubscriber((Topic) destination, "EnqueueSub"); + consumer = session.createDurableSubscriber((Topic) destination, "EnqueueSub"); - Thread.sleep(1000); + Thread.sleep(1000); - assertEquals(20, sub.getEnqueueCounter()); - assertEquals(0, sub.getDequeueCounter()); - assertEquals(0, sub.getPendingQueueSize()); - assertEquals(20, sub.getDispatchedCounter()); - assertEquals(20, sub.getDispatchedQueueSize()); + assertEquals(20, sub.getEnqueueCounter()); + assertEquals(0, sub.getDequeueCounter()); + assertEquals(0, sub.getPendingQueueSize()); + assertEquals(20, sub.getDispatchedCounter()); + assertEquals(20, sub.getDispatchedQueueSize()); - LOG.info("Pending Queue Size with no receives: {}", sub.getPendingQueueSize()); + LOG.info("Pending Queue Size with no receives: {}", sub.getPendingQueueSize()); - assertNotNull(consumer.receive(1000)); - assertNotNull(consumer.receive(1000)); + assertNotNull(consumer.receive(1000)); + assertNotNull(consumer.receive(1000)); - consumer.close(); + consumer.close(); - Thread.sleep(2000); + Thread.sleep(2000); - LOG.info("Pending Queue Size with two receives: {}", sub.getPendingQueueSize()); + LOG.info("Pending Queue Size with two receives: {}", sub.getPendingQueueSize()); - assertEquals(20, sub.getEnqueueCounter()); - assertEquals(2, sub.getDequeueCounter()); - assertEquals(18, sub.getPendingQueueSize()); - assertEquals(20, sub.getDispatchedCounter()); - assertEquals(0, sub.getDispatchedQueueSize()); + assertEquals(20, sub.getEnqueueCounter()); + assertEquals(2, sub.getDequeueCounter()); + assertEquals(18, sub.getPendingQueueSize()); + assertEquals(20, sub.getDispatchedCounter()); + assertEquals(0, sub.getDispatchedQueueSize()); - session.close(); - connection.close(); - } + session.close(); + connection.close(); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4671Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4671Test.java index b69ab4716e..562d978d92 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4671Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4671Test.java @@ -31,51 +31,53 @@ import org.slf4j.LoggerFactory; public class AMQ4671Test { - private static final transient Logger LOG = LoggerFactory.getLogger(AMQ4671Test.class); - private static BrokerService brokerService; - private static String BROKER_ADDRESS = "tcp://localhost:0"; + private static final transient Logger LOG = LoggerFactory.getLogger(AMQ4671Test.class); + private static BrokerService brokerService; + private static String BROKER_ADDRESS = "tcp://localhost:0"; - private String connectionUri; + private String connectionUri; - @Before - public void setUp() throws Exception { - brokerService = new BrokerService(); - brokerService.setPersistent(false); - brokerService.setUseJmx(true); - brokerService.setDeleteAllMessagesOnStartup(true); - connectionUri = brokerService.addConnector(BROKER_ADDRESS).getPublishableConnectString(); - connectionUri = connectionUri + "?trace=true"; - brokerService.start(); - brokerService.waitUntilStarted(); - } + @Before + public void setUp() throws Exception { + brokerService = new BrokerService(); + brokerService.setPersistent(false); + brokerService.setUseJmx(true); + brokerService.setDeleteAllMessagesOnStartup(true); + connectionUri = brokerService.addConnector(BROKER_ADDRESS).getPublishableConnectString(); + connectionUri = connectionUri + "?trace=true"; + brokerService.start(); + brokerService.waitUntilStarted(); + } - @After - public void tearDown() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - } + @After + public void tearDown() throws Exception { + brokerService.stop(); + brokerService.waitUntilStopped(); + } - @Test - public void testNonDurableSubscriberInvalidUnsubscribe() throws Exception { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionUri); + @Test + public void testNonDurableSubscriberInvalidUnsubscribe() throws Exception { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionUri); - Connection connection = connectionFactory.createConnection(); - connection.setClientID(getClass().getName()); - connection.start(); + Connection connection = connectionFactory.createConnection(); + connection.setClientID(getClass().getName()); + connection.start(); - try { - Session ts = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + try { + Session ts = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - try { - ts.unsubscribe("invalid-subscription-name"); - fail("this should fail"); - } catch (javax.jms.InvalidDestinationException e) { - LOG.info("Test caught correct invalid destination exception"); - } - } finally { - if (connection != null) { - connection.close(); - } - } - } + try { + ts.unsubscribe("invalid-subscription-name"); + fail("this should fail"); + } + catch (javax.jms.InvalidDestinationException e) { + LOG.info("Test caught correct invalid destination exception"); + } + } + finally { + if (connection != null) { + connection.close(); + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4677Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4677Test.java index fd80690f07..4bb3547af6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4677Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4677Test.java @@ -45,140 +45,140 @@ import org.slf4j.LoggerFactory; public class AMQ4677Test { - private static final transient Logger LOG = LoggerFactory.getLogger(AMQ4677Test.class); - private static BrokerService brokerService; + private static final transient Logger LOG = LoggerFactory.getLogger(AMQ4677Test.class); + private static BrokerService brokerService; - @Rule public TestName name = new TestName(); + @Rule + public TestName name = new TestName(); - private File dataDirFile; + private File dataDirFile; - @Before - public void setUp() throws Exception { + @Before + public void setUp() throws Exception { - dataDirFile = new File("target/LevelDBCleanupTest"); + dataDirFile = new File("target/LevelDBCleanupTest"); - brokerService = new BrokerService(); - brokerService.setBrokerName("LevelDBBroker"); - brokerService.setPersistent(true); - brokerService.setUseJmx(true); - brokerService.setAdvisorySupport(false); - brokerService.setDeleteAllMessagesOnStartup(true); - brokerService.setDataDirectoryFile(dataDirFile); + brokerService = new BrokerService(); + brokerService.setBrokerName("LevelDBBroker"); + brokerService.setPersistent(true); + brokerService.setUseJmx(true); + brokerService.setAdvisorySupport(false); + brokerService.setDeleteAllMessagesOnStartup(true); + brokerService.setDataDirectoryFile(dataDirFile); - LevelDBStore persistenceFactory = new LevelDBStore(); - persistenceFactory.setDirectory(dataDirFile); - brokerService.setPersistenceAdapter(persistenceFactory); - brokerService.start(); - brokerService.waitUntilStarted(); - } + LevelDBStore persistenceFactory = new LevelDBStore(); + persistenceFactory.setDirectory(dataDirFile); + brokerService.setPersistenceAdapter(persistenceFactory); + brokerService.start(); + brokerService.waitUntilStarted(); + } - @After - public void tearDown() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - } + @After + public void tearDown() throws Exception { + brokerService.stop(); + brokerService.waitUntilStopped(); + } - @Test - public void testSendAndReceiveAllMessages() throws Exception { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://LevelDBBroker"); + @Test + public void testSendAndReceiveAllMessages() throws Exception { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://LevelDBBroker"); - Connection connection = connectionFactory.createConnection(); - connection.setClientID(getClass().getName()); - connection.start(); + Connection connection = connectionFactory.createConnection(); + connection.setClientID(getClass().getName()); + connection.start(); - final Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(name.toString()); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); + final Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue(name.toString()); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); - final LevelDBStoreViewMBean levelDBView = getLevelDBStoreMBean(); - assertNotNull(levelDBView); - levelDBView.compact(); + final LevelDBStoreViewMBean levelDBView = getLevelDBStoreMBean(); + assertNotNull(levelDBView); + levelDBView.compact(); - final int SIZE = 6 * 1024 * 5; - final int MSG_COUNT = 60000; - final CountDownLatch done = new CountDownLatch(MSG_COUNT); + final int SIZE = 6 * 1024 * 5; + final int MSG_COUNT = 60000; + final CountDownLatch done = new CountDownLatch(MSG_COUNT); - byte buffer[] = new byte[SIZE]; - for (int i = 0; i < SIZE; ++i) { - buffer[i] = (byte) 128; - } + byte buffer[] = new byte[SIZE]; + for (int i = 0; i < SIZE; ++i) { + buffer[i] = (byte) 128; + } - for (int i = 0; i < MSG_COUNT; ++i) { - BytesMessage message = session.createBytesMessage(); - message.writeBytes(buffer); - producer.send(message); + for (int i = 0; i < MSG_COUNT; ++i) { + BytesMessage message = session.createBytesMessage(); + message.writeBytes(buffer); + producer.send(message); - if ((i % 1000) == 0) { - LOG.info("Sent message #{}", i); - session.commit(); + if ((i % 1000) == 0) { + LOG.info("Sent message #{}", i); + session.commit(); + } + } + + session.commit(); + + LOG.info("Finished sending all messages."); + + MessageConsumer consumer = session.createConsumer(destination); + consumer.setMessageListener(new MessageListener() { + + @Override + public void onMessage(Message message) { + if ((done.getCount() % 1000) == 0) { + try { + LOG.info("Received message #{}", MSG_COUNT - done.getCount()); + session.commit(); + } + catch (JMSException e) { + } } - } + done.countDown(); + } + }); - session.commit(); + done.await(15, TimeUnit.MINUTES); + session.commit(); + LOG.info("Finished receiving all messages."); - LOG.info("Finished sending all messages."); + assertTrue("Should < 3 logfiles left.", Wait.waitFor(new Wait.Condition() { - MessageConsumer consumer = session.createConsumer(destination); - consumer.setMessageListener(new MessageListener() { + @Override + public boolean isSatisified() throws Exception { + levelDBView.compact(); + return countLogFiles() < 3; + } + }, TimeUnit.MINUTES.toMillis(5), (int) TimeUnit.SECONDS.toMillis(30))); - @Override - public void onMessage(Message message) { - if ((done.getCount() % 1000) == 0) { - try { - LOG.info("Received message #{}", MSG_COUNT - done.getCount()); - session.commit(); - } catch (JMSException e) { - } - } - done.countDown(); + levelDBView.compact(); + LOG.info("Current number of logs {}", countLogFiles()); + } + + protected long countLogFiles() { + String[] logFiles = dataDirFile.list(new FilenameFilter() { + + @Override + public boolean accept(File dir, String name) { + if (name.endsWith("log")) { + return true; } - }); + return false; + } + }); - done.await(15, TimeUnit.MINUTES); - session.commit(); - LOG.info("Finished receiving all messages."); + LOG.info("Current number of logs {}", logFiles.length); + return logFiles.length; + } - assertTrue("Should < 3 logfiles left.", Wait.waitFor(new Wait.Condition() { + protected LevelDBStoreViewMBean getLevelDBStoreMBean() throws Exception { + ObjectName levelDbViewMBeanQuery = new ObjectName("org.apache.activemq:type=Broker,brokerName=LevelDBBroker,service=PersistenceAdapter,instanceName=LevelDB*"); - @Override - public boolean isSatisified() throws Exception { - levelDBView.compact(); - return countLogFiles() < 3; - } - }, TimeUnit.MINUTES.toMillis(5), (int)TimeUnit.SECONDS.toMillis(30))); + Set names = brokerService.getManagementContext().queryNames(null, levelDbViewMBeanQuery); + if (names.isEmpty() || names.size() > 1) { + throw new java.lang.IllegalStateException("Can't find levelDB store name."); + } - levelDBView.compact(); - LOG.info("Current number of logs {}", countLogFiles()); - } - - protected long countLogFiles() { - String[] logFiles = dataDirFile.list(new FilenameFilter() { - - @Override - public boolean accept(File dir, String name) { - if (name.endsWith("log")) { - return true; - } - return false; - } - }); - - LOG.info("Current number of logs {}", logFiles.length); - return logFiles.length; - } - - protected LevelDBStoreViewMBean getLevelDBStoreMBean() throws Exception { - ObjectName levelDbViewMBeanQuery = new ObjectName( - "org.apache.activemq:type=Broker,brokerName=LevelDBBroker,service=PersistenceAdapter,instanceName=LevelDB*"); - - Set names = brokerService.getManagementContext().queryNames(null, levelDbViewMBeanQuery); - if (names.isEmpty() || names.size() > 1) { - throw new java.lang.IllegalStateException("Can't find levelDB store name."); - } - - LevelDBStoreViewMBean proxy = (LevelDBStoreViewMBean) brokerService.getManagementContext() - .newProxyInstance(names.iterator().next(), LevelDBStoreViewMBean.class, true); - return proxy; - } + LevelDBStoreViewMBean proxy = (LevelDBStoreViewMBean) brokerService.getManagementContext().newProxyInstance(names.iterator().next(), LevelDBStoreViewMBean.class, true); + return proxy; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4853Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4853Test.java index a3472792ee..c6b3227291 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4853Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4853Test.java @@ -52,249 +52,253 @@ import org.slf4j.LoggerFactory; public class AMQ4853Test { - private static final transient Logger LOG = LoggerFactory.getLogger(AMQ4853Test.class); - private static BrokerService brokerService; - private static final String BROKER_ADDRESS = "tcp://localhost:0"; - private static final ActiveMQQueue DESTINATION = new ActiveMQQueue("TEST.QUEUE"); - private CountDownLatch cycleDoneLatch; + private static final transient Logger LOG = LoggerFactory.getLogger(AMQ4853Test.class); + private static BrokerService brokerService; + private static final String BROKER_ADDRESS = "tcp://localhost:0"; + private static final ActiveMQQueue DESTINATION = new ActiveMQQueue("TEST.QUEUE"); + private CountDownLatch cycleDoneLatch; - private String connectionUri; + private String connectionUri; - @Before - public void setUp() throws Exception { - brokerService = new BrokerService(); - brokerService.setPersistent(false); - brokerService.setUseJmx(false); - brokerService.setAdvisorySupport(true); - brokerService.setDeleteAllMessagesOnStartup(true); - connectionUri = brokerService.addConnector(BROKER_ADDRESS).getPublishableConnectString(); + @Before + public void setUp() throws Exception { + brokerService = new BrokerService(); + brokerService.setPersistent(false); + brokerService.setUseJmx(false); + brokerService.setAdvisorySupport(true); + brokerService.setDeleteAllMessagesOnStartup(true); + connectionUri = brokerService.addConnector(BROKER_ADDRESS).getPublishableConnectString(); - brokerService.start(); - brokerService.waitUntilStarted(); - } + brokerService.start(); + brokerService.waitUntilStarted(); + } - @After - public void tearDown() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - } + @After + public void tearDown() throws Exception { + brokerService.stop(); + brokerService.waitUntilStopped(); + } - /** - * Test to shows the performance of the removing consumers while other stay active. - * @throws Exception - */ - @Ignore - @Test - public void test() throws Exception { + /** + * Test to shows the performance of the removing consumers while other stay active. + * + * @throws Exception + */ + @Ignore + @Test + public void test() throws Exception { - // Create a stable set of consumers to fill in the advisory broker's consumer list. - ArrayList fixedConsumers = new ArrayList(100); - for (int i = 0; i < 200; ++i) { - fixedConsumers.add(new Consumer()); - } + // Create a stable set of consumers to fill in the advisory broker's consumer list. + ArrayList fixedConsumers = new ArrayList(100); + for (int i = 0; i < 200; ++i) { + fixedConsumers.add(new Consumer()); + } - // Create a set of consumers that comes online for a short time and then - // goes offline again. Cycles will repeat as each batch completes - final int fixedDelayConsumers = 300; - final int fixedDelayCycles = 25; + // Create a set of consumers that comes online for a short time and then + // goes offline again. Cycles will repeat as each batch completes + final int fixedDelayConsumers = 300; + final int fixedDelayCycles = 25; - final CountDownLatch fixedDelayCycleLatch = new CountDownLatch(fixedDelayCycles); + final CountDownLatch fixedDelayCycleLatch = new CountDownLatch(fixedDelayCycles); - // Update so done method can track state. - cycleDoneLatch = fixedDelayCycleLatch; + // Update so done method can track state. + cycleDoneLatch = fixedDelayCycleLatch; - CyclicBarrier barrier = new CyclicBarrier(fixedDelayConsumers, new Runnable() { - @Override - public void run() { - LOG.info("Fixed delay consumers cycle {} completed.", fixedDelayCycleLatch.getCount()); - fixedDelayCycleLatch.countDown(); - } - }); + CyclicBarrier barrier = new CyclicBarrier(fixedDelayConsumers, new Runnable() { + @Override + public void run() { + LOG.info("Fixed delay consumers cycle {} completed.", fixedDelayCycleLatch.getCount()); + fixedDelayCycleLatch.countDown(); + } + }); - for (int i = 0; i < fixedDelayConsumers; ++i) { - new Thread(new FixedDelyConsumer(barrier)).start(); - } + for (int i = 0; i < fixedDelayConsumers; ++i) { + new Thread(new FixedDelyConsumer(barrier)).start(); + } - fixedDelayCycleLatch.await(10, TimeUnit.MINUTES); + fixedDelayCycleLatch.await(10, TimeUnit.MINUTES); - // Clean up. + // Clean up. - for (Consumer consumer : fixedConsumers) { - consumer.close(); - } - fixedConsumers.clear(); - } + for (Consumer consumer : fixedConsumers) { + consumer.close(); + } + fixedConsumers.clear(); + } - private ConnectionInfo createConnectionInfo() { - ConnectionId id = new ConnectionId(); - id.setValue("ID:123456789:0:1"); + private ConnectionInfo createConnectionInfo() { + ConnectionId id = new ConnectionId(); + id.setValue("ID:123456789:0:1"); - ConnectionInfo info = new ConnectionInfo(); - info.setConnectionId(id); - return info; - } + ConnectionInfo info = new ConnectionInfo(); + info.setConnectionId(id); + return info; + } - private SessionInfo createSessionInfo(ConnectionInfo connection) { - SessionId id = new SessionId(connection.getConnectionId(), 1); + private SessionInfo createSessionInfo(ConnectionInfo connection) { + SessionId id = new SessionId(connection.getConnectionId(), 1); - SessionInfo info = new SessionInfo(); - info.setSessionId(id); + SessionInfo info = new SessionInfo(); + info.setSessionId(id); - return info; - } + return info; + } - public ConsumerInfo createConsumerInfo(SessionInfo session, int value, ActiveMQDestination destination) { - ConsumerId id = new ConsumerId(); - id.setConnectionId(session.getSessionId().getConnectionId()); - id.setSessionId(1); - id.setValue(value); + public ConsumerInfo createConsumerInfo(SessionInfo session, int value, ActiveMQDestination destination) { + ConsumerId id = new ConsumerId(); + id.setConnectionId(session.getSessionId().getConnectionId()); + id.setSessionId(1); + id.setValue(value); - ConsumerInfo info = new ConsumerInfo(); - info.setConsumerId(id); - info.setDestination(destination); - return info; - } + ConsumerInfo info = new ConsumerInfo(); + info.setConsumerId(id); + info.setDestination(destination); + return info; + } - /** - * Test to shows the performance impact of removing consumers in various scenarios. - * @throws Exception - */ - @Ignore - @Test - public void testPerformanceOfRemovals() throws Exception { - // setup - AdvisoryBroker testObj = (AdvisoryBroker) brokerService.getBroker().getAdaptor(AdvisoryBroker.class); - ActiveMQDestination destination = new ActiveMQQueue("foo"); - ConnectionInfo connectionInfo = createConnectionInfo(); - ConnectionContext connectionContext = new ConnectionContext(connectionInfo); - connectionContext.setBroker(brokerService.getBroker()); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); + /** + * Test to shows the performance impact of removing consumers in various scenarios. + * + * @throws Exception + */ + @Ignore + @Test + public void testPerformanceOfRemovals() throws Exception { + // setup + AdvisoryBroker testObj = (AdvisoryBroker) brokerService.getBroker().getAdaptor(AdvisoryBroker.class); + ActiveMQDestination destination = new ActiveMQQueue("foo"); + ConnectionInfo connectionInfo = createConnectionInfo(); + ConnectionContext connectionContext = new ConnectionContext(connectionInfo); + connectionContext.setBroker(brokerService.getBroker()); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); - long start = System.currentTimeMillis(); + long start = System.currentTimeMillis(); - for (int i = 0; i < 200; ++i) { + for (int i = 0; i < 200; ++i) { - for (int j = 1; j <= 500; j++) { - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, j, destination); - testObj.addConsumer(connectionContext, consumerInfo); - } - - for (int j = 500; j > 0; j--) { - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, j, destination); - testObj.removeConsumer(connectionContext, consumerInfo); - } - - for (int j = 1; j <= 500; j++) { - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, j, destination); - testObj.addConsumer(connectionContext, consumerInfo); - } - - for (int j = 1; j <= 500; j++) { - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, j, destination); - testObj.removeConsumer(connectionContext, consumerInfo); - } - } - - long finish = System.currentTimeMillis(); - - long totalTime = finish - start; - - LOG.info("Total test time: {} seconds", TimeUnit.MILLISECONDS.toSeconds(totalTime)); - - assertEquals(0, testObj.getAdvisoryConsumers().size()); - } - - @Test - public void testEqualsNeeded() throws Exception { - // setup - AdvisoryBroker testObj = (AdvisoryBroker) brokerService.getBroker().getAdaptor(AdvisoryBroker.class); - ActiveMQDestination destination = new ActiveMQQueue("foo"); - ConnectionInfo connectionInfo = createConnectionInfo(); - ConnectionContext connectionContext = new ConnectionContext(connectionInfo); - connectionContext.setBroker(brokerService.getBroker()); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - - for (int j = 1; j <= 5; j++) { + for (int j = 1; j <= 500; j++) { ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, j, destination); testObj.addConsumer(connectionContext, consumerInfo); - } + } - for (int j = 1; j <= 5; j++) { + for (int j = 500; j > 0; j--) { ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, j, destination); testObj.removeConsumer(connectionContext, consumerInfo); - } + } - assertEquals(0, testObj.getAdvisoryConsumers().size()); - } + for (int j = 1; j <= 500; j++) { + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, j, destination); + testObj.addConsumer(connectionContext, consumerInfo); + } - private boolean done() { - if (cycleDoneLatch == null) { - return true; - } - return cycleDoneLatch.getCount() == 0; - } + for (int j = 1; j <= 500; j++) { + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, j, destination); + testObj.removeConsumer(connectionContext, consumerInfo); + } + } - class Consumer implements MessageListener { + long finish = System.currentTimeMillis(); - Connection connection; - Session session; - Destination destination; - MessageConsumer consumer; + long totalTime = finish - start; - Consumer() throws JMSException { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - connection = factory.createConnection(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = session.createConsumer(DESTINATION); - consumer.setMessageListener(this); - connection.start(); - } + LOG.info("Total test time: {} seconds", TimeUnit.MILLISECONDS.toSeconds(totalTime)); - @Override - public void onMessage(Message message) { - } + assertEquals(0, testObj.getAdvisoryConsumers().size()); + } + + @Test + public void testEqualsNeeded() throws Exception { + // setup + AdvisoryBroker testObj = (AdvisoryBroker) brokerService.getBroker().getAdaptor(AdvisoryBroker.class); + ActiveMQDestination destination = new ActiveMQQueue("foo"); + ConnectionInfo connectionInfo = createConnectionInfo(); + ConnectionContext connectionContext = new ConnectionContext(connectionInfo); + connectionContext.setBroker(brokerService.getBroker()); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + + for (int j = 1; j <= 5; j++) { + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, j, destination); + testObj.addConsumer(connectionContext, consumerInfo); + } + + for (int j = 1; j <= 5; j++) { + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, j, destination); + testObj.removeConsumer(connectionContext, consumerInfo); + } + + assertEquals(0, testObj.getAdvisoryConsumers().size()); + } + + private boolean done() { + if (cycleDoneLatch == null) { + return true; + } + return cycleDoneLatch.getCount() == 0; + } + + class Consumer implements MessageListener { + + Connection connection; + Session session; + Destination destination; + MessageConsumer consumer; + + Consumer() throws JMSException { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); + connection = factory.createConnection(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumer = session.createConsumer(DESTINATION); + consumer.setMessageListener(this); + connection.start(); + } + + @Override + public void onMessage(Message message) { + } + + public void close() { + try { + connection.close(); + } + catch (Exception e) { + } + + connection = null; + session = null; + consumer = null; + } + } + + class FixedDelyConsumer implements Runnable { + + private final CyclicBarrier barrier; + private final int sleepInterval; + + public FixedDelyConsumer(CyclicBarrier barrier) { + this.barrier = barrier; + this.sleepInterval = 1000; + } + + public FixedDelyConsumer(CyclicBarrier barrier, int sleepInterval) { + this.barrier = barrier; + this.sleepInterval = sleepInterval; + } + + @Override + public void run() { + while (!done()) { - public void close() { try { - connection.close(); - } catch(Exception e) { + Consumer consumer = new Consumer(); + TimeUnit.MILLISECONDS.sleep(sleepInterval); + consumer.close(); + barrier.await(); } - - connection = null; - session = null; - consumer = null; - } - } - - class FixedDelyConsumer implements Runnable { - - private final CyclicBarrier barrier; - private final int sleepInterval; - - public FixedDelyConsumer(CyclicBarrier barrier) { - this.barrier = barrier; - this.sleepInterval = 1000; - } - - public FixedDelyConsumer(CyclicBarrier barrier, int sleepInterval) { - this.barrier = barrier; - this.sleepInterval = sleepInterval; - } - - @Override - public void run() { - while (!done()) { - - try { - Consumer consumer = new Consumer(); - TimeUnit.MILLISECONDS.sleep(sleepInterval); - consumer.close(); - barrier.await(); - } catch (Exception ex) { - return; - } + catch (Exception ex) { + return; } - } - } + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4887Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4887Test.java index cf33ecec70..657d7a2988 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4887Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4887Test.java @@ -38,128 +38,131 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AMQ4887Test { - private static final transient Logger LOG = LoggerFactory.getLogger(AMQ4887Test.class); - private static final Integer ITERATIONS = 10; - @Rule - public TestName name = new TestName(); + private static final transient Logger LOG = LoggerFactory.getLogger(AMQ4887Test.class); + private static final Integer ITERATIONS = 10; - @Test - public void testBytesMessageSetPropertyBeforeCopy() throws Exception { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost"); - ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); - doTestBytesMessageSetPropertyBeforeCopy(connection); - } + @Rule + public TestName name = new TestName(); - @Test - public void testBytesMessageSetPropertyBeforeCopyCompressed() throws Exception { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost"); - connectionFactory.setUseCompression(true); - ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); - doTestBytesMessageSetPropertyBeforeCopy(connection); - } + @Test + public void testBytesMessageSetPropertyBeforeCopy() throws Exception { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost"); + ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.start(); + doTestBytesMessageSetPropertyBeforeCopy(connection); + } - public void doTestBytesMessageSetPropertyBeforeCopy(Connection connection) throws Exception { + @Test + public void testBytesMessageSetPropertyBeforeCopyCompressed() throws Exception { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost"); + connectionFactory.setUseCompression(true); + ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.start(); + doTestBytesMessageSetPropertyBeforeCopy(connection); + } - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(name.toString()); - MessageConsumer consumer = session.createConsumer(destination); - MessageProducer producer = session.createProducer(destination); + public void doTestBytesMessageSetPropertyBeforeCopy(Connection connection) throws Exception { - BytesMessage message = session.createBytesMessage(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue(name.toString()); + MessageConsumer consumer = session.createConsumer(destination); + MessageProducer producer = session.createProducer(destination); - for (int i=0; i < ITERATIONS; i++) { + BytesMessage message = session.createBytesMessage(); - long sendTime = System.currentTimeMillis(); - message.setLongProperty("sendTime", sendTime); - producer.send(message); + for (int i = 0; i < ITERATIONS; i++) { - LOG.debug("Receiving message " + i); - Message receivedMessage = consumer.receive(5000); - assertNotNull("On message " + i, receivedMessage); - assertTrue("On message " + i, receivedMessage instanceof BytesMessage); + long sendTime = System.currentTimeMillis(); + message.setLongProperty("sendTime", sendTime); + producer.send(message); - BytesMessage receivedBytesMessage = (BytesMessage) receivedMessage; + LOG.debug("Receiving message " + i); + Message receivedMessage = consumer.receive(5000); + assertNotNull("On message " + i, receivedMessage); + assertTrue("On message " + i, receivedMessage instanceof BytesMessage); - int numElements = 0; - try { - while (true) { - receivedBytesMessage.readBoolean(); - numElements++; - } - } catch (Exception ex) { + BytesMessage receivedBytesMessage = (BytesMessage) receivedMessage; + + int numElements = 0; + try { + while (true) { + receivedBytesMessage.readBoolean(); + numElements++; } + } + catch (Exception ex) { + } - LOG.info("Iteration [{}]: Received Message contained {} boolean values.", i, numElements); - assertEquals(i, numElements); + LOG.info("Iteration [{}]: Received Message contained {} boolean values.", i, numElements); + assertEquals(i, numElements); - long receivedSendTime = receivedBytesMessage.getLongProperty("sendTime"); - assertEquals("On message " + i, receivedSendTime, sendTime); + long receivedSendTime = receivedBytesMessage.getLongProperty("sendTime"); + assertEquals("On message " + i, receivedSendTime, sendTime); - // Add a new bool value on each iteration. - message.writeBoolean(true); - } - } + // Add a new bool value on each iteration. + message.writeBoolean(true); + } + } - @Test - public void testStreamMessageSetPropertyBeforeCopy() throws Exception { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost"); - ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); - doTestStreamMessageSetPropertyBeforeCopy(connection); - } + @Test + public void testStreamMessageSetPropertyBeforeCopy() throws Exception { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost"); + ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.start(); + doTestStreamMessageSetPropertyBeforeCopy(connection); + } - @Test - public void testStreamMessageSetPropertyBeforeCopyCompressed() throws Exception { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost"); - connectionFactory.setUseCompression(true); - ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); - doTestStreamMessageSetPropertyBeforeCopy(connection); - } + @Test + public void testStreamMessageSetPropertyBeforeCopyCompressed() throws Exception { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost"); + connectionFactory.setUseCompression(true); + ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.start(); + doTestStreamMessageSetPropertyBeforeCopy(connection); + } - public void doTestStreamMessageSetPropertyBeforeCopy(Connection connection) throws Exception { + public void doTestStreamMessageSetPropertyBeforeCopy(Connection connection) throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(name.toString()); - MessageConsumer consumer = session.createConsumer(destination); - MessageProducer producer = session.createProducer(destination); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue(name.toString()); + MessageConsumer consumer = session.createConsumer(destination); + MessageProducer producer = session.createProducer(destination); - StreamMessage message = session.createStreamMessage(); + StreamMessage message = session.createStreamMessage(); - for (int i=0; i < ITERATIONS; i++) { + for (int i = 0; i < ITERATIONS; i++) { - long sendTime = System.currentTimeMillis(); - message.setLongProperty("sendTime", sendTime); - producer.send(message); + long sendTime = System.currentTimeMillis(); + message.setLongProperty("sendTime", sendTime); + producer.send(message); - LOG.debug("Receiving message " + i); - Message receivedMessage = consumer.receive(5000); - assertNotNull("On message " + i, receivedMessage); - assertTrue("On message " + i, receivedMessage instanceof StreamMessage); + LOG.debug("Receiving message " + i); + Message receivedMessage = consumer.receive(5000); + assertNotNull("On message " + i, receivedMessage); + assertTrue("On message " + i, receivedMessage instanceof StreamMessage); - StreamMessage receivedStreamMessage = (StreamMessage) receivedMessage; + StreamMessage receivedStreamMessage = (StreamMessage) receivedMessage; - int numElements = 0; - try { - while (true) { - receivedStreamMessage.readBoolean(); - numElements++; - } - } catch (Exception ex) { + int numElements = 0; + try { + while (true) { + receivedStreamMessage.readBoolean(); + numElements++; } + } + catch (Exception ex) { + } - LOG.info("Iteration [{}]: Received Message contained {} boolean values.", i, numElements); - assertEquals(i, numElements); + LOG.info("Iteration [{}]: Received Message contained {} boolean values.", i, numElements); + assertEquals(i, numElements); - long receivedSendTime = receivedStreamMessage.getLongProperty("sendTime"); - assertEquals("On message " + i, receivedSendTime, sendTime); + long receivedSendTime = receivedStreamMessage.getLongProperty("sendTime"); + assertEquals("On message " + i, receivedSendTime, sendTime); - // Add a new bool value on each iteration. - message.writeBoolean(true); - } - } + // Add a new bool value on each iteration. + message.writeBoolean(true); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4893Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4893Test.java index 026a4be42d..ba65ab73c0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4893Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4893Test.java @@ -31,56 +31,56 @@ import org.slf4j.LoggerFactory; public class AMQ4893Test { - private static final transient Logger LOG = LoggerFactory.getLogger(AMQ4893Test.class); + private static final transient Logger LOG = LoggerFactory.getLogger(AMQ4893Test.class); - @Test - public void testPropertiesInt() throws Exception { - ActiveMQObjectMessage message = new ActiveMQObjectMessage(); - message.setIntProperty("TestProp", 333); - fakeUnmarshal(message); - roundTripProperties(message); - } + @Test + public void testPropertiesInt() throws Exception { + ActiveMQObjectMessage message = new ActiveMQObjectMessage(); + message.setIntProperty("TestProp", 333); + fakeUnmarshal(message); + roundTripProperties(message); + } - @Test - public void testPropertiesString() throws Exception { - ActiveMQObjectMessage message = new ActiveMQObjectMessage(); - message.setStringProperty("TestProp", "Value"); - fakeUnmarshal(message); - roundTripProperties(message); - } + @Test + public void testPropertiesString() throws Exception { + ActiveMQObjectMessage message = new ActiveMQObjectMessage(); + message.setStringProperty("TestProp", "Value"); + fakeUnmarshal(message); + roundTripProperties(message); + } - @Test - public void testPropertiesObject() throws Exception { - ActiveMQObjectMessage message = new ActiveMQObjectMessage(); - message.setObjectProperty("TestProp", "Value"); - fakeUnmarshal(message); - roundTripProperties(message); - } + @Test + public void testPropertiesObject() throws Exception { + ActiveMQObjectMessage message = new ActiveMQObjectMessage(); + message.setObjectProperty("TestProp", "Value"); + fakeUnmarshal(message); + roundTripProperties(message); + } - @Test - public void testPropertiesObjectNoMarshalling() throws Exception { - ActiveMQObjectMessage message = new ActiveMQObjectMessage(); - message.setObjectProperty("TestProp", "Value"); - roundTripProperties(message); - } + @Test + public void testPropertiesObjectNoMarshalling() throws Exception { + ActiveMQObjectMessage message = new ActiveMQObjectMessage(); + message.setObjectProperty("TestProp", "Value"); + roundTripProperties(message); + } - private void roundTripProperties(ActiveMQObjectMessage message) throws IOException, JMSException { - ActiveMQObjectMessage copy = new ActiveMQObjectMessage(); - for (Map.Entry prop : message.getProperties().entrySet()) { - LOG.debug("{} -> {}", prop.getKey(), prop.getValue().getClass()); - copy.setObjectProperty(prop.getKey(), prop.getValue()); - } - } + private void roundTripProperties(ActiveMQObjectMessage message) throws IOException, JMSException { + ActiveMQObjectMessage copy = new ActiveMQObjectMessage(); + for (Map.Entry prop : message.getProperties().entrySet()) { + LOG.debug("{} -> {}", prop.getKey(), prop.getValue().getClass()); + copy.setObjectProperty(prop.getKey(), prop.getValue()); + } + } - private void fakeUnmarshal(ActiveMQObjectMessage message) throws IOException { - // we need to force the unmarshalled property field to be set so it - // gives us a hawtbuffer for the string - OpenWireFormat format = new OpenWireFormat(); - message.beforeMarshall(format); - message.afterMarshall(format); + private void fakeUnmarshal(ActiveMQObjectMessage message) throws IOException { + // we need to force the unmarshalled property field to be set so it + // gives us a hawtbuffer for the string + OpenWireFormat format = new OpenWireFormat(); + message.beforeMarshall(format); + message.afterMarshall(format); - ByteSequence seq = message.getMarshalledProperties(); - message.clearProperties(); - message.setMarshalledProperties(seq); - } + ByteSequence seq = message.getMarshalledProperties(); + message.clearProperties(); + message.setMarshalledProperties(seq); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4899Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4899Test.java index 81140ce8e8..fe336eb94b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4899Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4899Test.java @@ -47,146 +47,151 @@ import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; public class AMQ4899Test { - protected static final Logger LOG = LoggerFactory.getLogger(AMQ4899Test.class); - private static final String QUEUE_NAME="AMQ4899TestQueue"; - private static final String CONSUMER_QUEUE="Consumer.Orders.VirtualOrders." + QUEUE_NAME; - private static final String PRODUCER_DESTINATION_NAME = "VirtualOrders." + QUEUE_NAME; - private static final Integer MESSAGE_LIMIT = 20; - public static final String CONSUMER_A_SELECTOR = "Order < " + 10; - public static String CONSUMER_B_SELECTOR = "Order >= " + 10; - private CountDownLatch consumersStarted = new CountDownLatch(2); - private CountDownLatch consumerAtoConsumeCount= new CountDownLatch(10); - private CountDownLatch consumerBtoConsumeCount = new CountDownLatch(10); + protected static final Logger LOG = LoggerFactory.getLogger(AMQ4899Test.class); + private static final String QUEUE_NAME = "AMQ4899TestQueue"; + private static final String CONSUMER_QUEUE = "Consumer.Orders.VirtualOrders." + QUEUE_NAME; + private static final String PRODUCER_DESTINATION_NAME = "VirtualOrders." + QUEUE_NAME; - private BrokerService broker; + private static final Integer MESSAGE_LIMIT = 20; + public static final String CONSUMER_A_SELECTOR = "Order < " + 10; + public static String CONSUMER_B_SELECTOR = "Order >= " + 10; + private CountDownLatch consumersStarted = new CountDownLatch(2); + private CountDownLatch consumerAtoConsumeCount = new CountDownLatch(10); + private CountDownLatch consumerBtoConsumeCount = new CountDownLatch(10); - @Before - public void setUp() { - setupBroker("broker://()/localhost?"); - } + private BrokerService broker; - @After - public void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - } + @Before + public void setUp() { + setupBroker("broker://()/localhost?"); + } - @Test(timeout = 60 * 1000) - public void testVirtualTopicMultipleSelectors() throws Exception{ - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = factory.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + @After + public void tearDown() throws Exception { + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + } - Queue consumerQueue = session.createQueue(CONSUMER_QUEUE); + @Test(timeout = 60 * 1000) + public void testVirtualTopicMultipleSelectors() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + Connection connection = factory.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageListener listenerA = new AMQ4899Listener("A", consumersStarted, consumerAtoConsumeCount); - MessageConsumer consumerA = session.createConsumer(consumerQueue, CONSUMER_A_SELECTOR); - consumerA.setMessageListener(listenerA); + Queue consumerQueue = session.createQueue(CONSUMER_QUEUE); - MessageListener listenerB = new AMQ4899Listener("B", consumersStarted, consumerBtoConsumeCount); - MessageConsumer consumerB = session.createConsumer(consumerQueue, CONSUMER_B_SELECTOR); - consumerB.setMessageListener(listenerB); + MessageListener listenerA = new AMQ4899Listener("A", consumersStarted, consumerAtoConsumeCount); + MessageConsumer consumerA = session.createConsumer(consumerQueue, CONSUMER_A_SELECTOR); + consumerA.setMessageListener(listenerA); - consumersStarted.await(10, TimeUnit.SECONDS); - assertEquals("Not all consumers started in time", 0, consumersStarted.getCount()); + MessageListener listenerB = new AMQ4899Listener("B", consumersStarted, consumerBtoConsumeCount); + MessageConsumer consumerB = session.createConsumer(consumerQueue, CONSUMER_B_SELECTOR); + consumerB.setMessageListener(listenerB); - Destination producerDestination = session.createTopic(PRODUCER_DESTINATION_NAME); - MessageProducer producer = session.createProducer(producerDestination); - int messageIndex = 0; - for (int i=0; i < MESSAGE_LIMIT; i++) { - if (i==3) { - LOG.debug("Stopping consumerA"); - consumerA.close(); - } + consumersStarted.await(10, TimeUnit.SECONDS); + assertEquals("Not all consumers started in time", 0, consumersStarted.getCount()); - if (i == 14) { - LOG.debug("Stopping consumer B"); - consumerB.close(); - } - String messageText = "hello " + messageIndex++ + " sent at " + new java.util.Date().toString(); - TextMessage message = session.createTextMessage(messageText); - message.setIntProperty("Order", i); - LOG.debug("Sending message [{}]", messageText); - producer.send(message); - Thread.sleep(100); - } - Thread.sleep(1 * 1000); + Destination producerDestination = session.createTopic(PRODUCER_DESTINATION_NAME); + MessageProducer producer = session.createProducer(producerDestination); + int messageIndex = 0; + for (int i = 0; i < MESSAGE_LIMIT; i++) { + if (i == 3) { + LOG.debug("Stopping consumerA"); + consumerA.close(); + } - // restart consumerA - LOG.debug("Restarting consumerA"); - consumerA = session.createConsumer(consumerQueue, CONSUMER_A_SELECTOR); - consumerA.setMessageListener(listenerA); + if (i == 14) { + LOG.debug("Stopping consumer B"); + consumerB.close(); + } + String messageText = "hello " + messageIndex++ + " sent at " + new java.util.Date().toString(); + TextMessage message = session.createTextMessage(messageText); + message.setIntProperty("Order", i); + LOG.debug("Sending message [{}]", messageText); + producer.send(message); + Thread.sleep(100); + } + Thread.sleep(1 * 1000); - // restart consumerB - LOG.debug("restarting consumerB"); - consumerB = session.createConsumer(consumerQueue, CONSUMER_B_SELECTOR); - consumerB.setMessageListener(listenerB); + // restart consumerA + LOG.debug("Restarting consumerA"); + consumerA = session.createConsumer(consumerQueue, CONSUMER_A_SELECTOR); + consumerA.setMessageListener(listenerA); - consumerAtoConsumeCount.await(5, TimeUnit.SECONDS); - consumerBtoConsumeCount.await(5, TimeUnit.SECONDS); + // restart consumerB + LOG.debug("restarting consumerB"); + consumerB = session.createConsumer(consumerQueue, CONSUMER_B_SELECTOR); + consumerB.setMessageListener(listenerB); - LOG.debug("Unconsumed messages for consumerA {} consumerB {}", consumerAtoConsumeCount.getCount(), consumerBtoConsumeCount.getCount()); + consumerAtoConsumeCount.await(5, TimeUnit.SECONDS); + consumerBtoConsumeCount.await(5, TimeUnit.SECONDS); - assertEquals("Consumer A did not consume all messages", 0, consumerAtoConsumeCount.getCount()); - assertEquals("Consumer B did not consume all messages", 0, consumerBtoConsumeCount.getCount()); + LOG.debug("Unconsumed messages for consumerA {} consumerB {}", consumerAtoConsumeCount.getCount(), consumerBtoConsumeCount.getCount()); - connection.close(); - } + assertEquals("Consumer A did not consume all messages", 0, consumerAtoConsumeCount.getCount()); + assertEquals("Consumer B did not consume all messages", 0, consumerBtoConsumeCount.getCount()); - /** - * Setup broker with VirtualTopic configured - */ - private void setupBroker(String uri) { - try { - broker = BrokerFactory.createBroker(uri); + connection.close(); + } - VirtualDestinationInterceptor interceptor = new VirtualDestinationInterceptor(); - VirtualTopic virtualTopic = new VirtualTopic(); - virtualTopic.setName("VirtualOrders.>"); - virtualTopic.setSelectorAware(true); - VirtualDestination[] virtualDestinations = { virtualTopic }; - interceptor.setVirtualDestinations(virtualDestinations); - broker.setDestinationInterceptors(new DestinationInterceptor[]{interceptor}); + /** + * Setup broker with VirtualTopic configured + */ + private void setupBroker(String uri) { + try { + broker = BrokerFactory.createBroker(uri); - SubQueueSelectorCacheBrokerPlugin subQueueSelectorCacheBrokerPlugin = new SubQueueSelectorCacheBrokerPlugin(); - BrokerPlugin[] updatedPlugins = {subQueueSelectorCacheBrokerPlugin}; - broker.setPlugins(updatedPlugins); + VirtualDestinationInterceptor interceptor = new VirtualDestinationInterceptor(); + VirtualTopic virtualTopic = new VirtualTopic(); + virtualTopic.setName("VirtualOrders.>"); + virtualTopic.setSelectorAware(true); + VirtualDestination[] virtualDestinations = {virtualTopic}; + interceptor.setVirtualDestinations(virtualDestinations); + broker.setDestinationInterceptors(new DestinationInterceptor[]{interceptor}); - broker.start(); - broker.waitUntilStarted(); - } catch (Exception e) { - LOG.error("Failed creating broker", e); - } - } + SubQueueSelectorCacheBrokerPlugin subQueueSelectorCacheBrokerPlugin = new SubQueueSelectorCacheBrokerPlugin(); + BrokerPlugin[] updatedPlugins = {subQueueSelectorCacheBrokerPlugin}; + broker.setPlugins(updatedPlugins); + + broker.start(); + broker.waitUntilStarted(); + } + catch (Exception e) { + LOG.error("Failed creating broker", e); + } + } } class AMQ4899Listener implements MessageListener { - Logger LOG = LoggerFactory.getLogger(AMQ4899Listener.class); - CountDownLatch toConsume; - String id; - public AMQ4899Listener(String id, CountDownLatch started, CountDownLatch toConsume) { - this.id = id; - this.toConsume = toConsume; - started.countDown(); - } + Logger LOG = LoggerFactory.getLogger(AMQ4899Listener.class); + CountDownLatch toConsume; + String id; - @Override - public void onMessage(Message message) { - toConsume.countDown(); - try { - if (message instanceof TextMessage) { - TextMessage textMessage = (TextMessage) message; - LOG.debug("Listener {} received [{}]", id, textMessage.getText()); - } else { - LOG.error("Listener {} Expected a TextMessage, got {}", id, message.getClass().getCanonicalName()); - } - } catch (JMSException e) { - LOG.error("Unexpected JMSException in Listener " + id, e); - } - } + public AMQ4899Listener(String id, CountDownLatch started, CountDownLatch toConsume) { + this.id = id; + this.toConsume = toConsume; + started.countDown(); + } + + @Override + public void onMessage(Message message) { + toConsume.countDown(); + try { + if (message instanceof TextMessage) { + TextMessage textMessage = (TextMessage) message; + LOG.debug("Listener {} received [{}]", id, textMessage.getText()); + } + else { + LOG.error("Listener {} Expected a TextMessage, got {}", id, message.getClass().getCanonicalName()); + } + } + catch (JMSException e) { + LOG.error("Unexpected JMSException in Listener " + id, e); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4930Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4930Test.java index e65ad91f14..ad8cb287b8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4930Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4930Test.java @@ -21,7 +21,9 @@ import javax.jms.Connection; import javax.jms.DeliveryMode; import javax.jms.MessageProducer; import javax.jms.Session; + import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.jmx.QueueViewMBean; @@ -35,110 +37,109 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AMQ4930Test extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(AMQ4930Test.class); - final int messageCount = 150; - final int messageSize = 1024*1024; - final int maxBrowsePageSize = 50; - final ActiveMQQueue bigQueue = new ActiveMQQueue("BIG"); - BrokerService broker; - ActiveMQConnectionFactory factory; - protected void configureBroker() throws Exception { - broker.setDeleteAllMessagesOnStartup(true); - broker.setAdvisorySupport(false); - broker.getSystemUsage().getMemoryUsage().setLimit(1*1024*1024); + private static final Logger LOG = LoggerFactory.getLogger(AMQ4930Test.class); + final int messageCount = 150; + final int messageSize = 1024 * 1024; + final int maxBrowsePageSize = 50; + final ActiveMQQueue bigQueue = new ActiveMQQueue("BIG"); + BrokerService broker; + ActiveMQConnectionFactory factory; - PolicyMap pMap = new PolicyMap(); - PolicyEntry policy = new PolicyEntry(); - // disable expriy processing as this will call browse in parallel - policy.setExpireMessagesPeriod(0); - policy.setMaxPageSize(maxBrowsePageSize); - policy.setMaxBrowsePageSize(maxBrowsePageSize); - pMap.setDefaultEntry(policy); + protected void configureBroker() throws Exception { + broker.setDeleteAllMessagesOnStartup(true); + broker.setAdvisorySupport(false); + broker.getSystemUsage().getMemoryUsage().setLimit(1 * 1024 * 1024); - broker.setDestinationPolicy(pMap); - } + PolicyMap pMap = new PolicyMap(); + PolicyEntry policy = new PolicyEntry(); + // disable expriy processing as this will call browse in parallel + policy.setExpireMessagesPeriod(0); + policy.setMaxPageSize(maxBrowsePageSize); + policy.setMaxBrowsePageSize(maxBrowsePageSize); + pMap.setDefaultEntry(policy); - public void testBrowsePendingNonPersistent() throws Exception { - doTestBrowsePending(DeliveryMode.NON_PERSISTENT); - } + broker.setDestinationPolicy(pMap); + } - public void testBrowsePendingPersistent() throws Exception { - doTestBrowsePending(DeliveryMode.PERSISTENT); - } + public void testBrowsePendingNonPersistent() throws Exception { + doTestBrowsePending(DeliveryMode.NON_PERSISTENT); + } - public void testWithStatsDisabled() throws Exception { - ((RegionBroker)broker.getRegionBroker()).getDestinationStatistics().setEnabled(false); - doTestBrowsePending(DeliveryMode.PERSISTENT); - } + public void testBrowsePendingPersistent() throws Exception { + doTestBrowsePending(DeliveryMode.PERSISTENT); + } - public void doTestBrowsePending(int deliveryMode) throws Exception { + public void testWithStatsDisabled() throws Exception { + ((RegionBroker) broker.getRegionBroker()).getDestinationStatistics().setEnabled(false); + doTestBrowsePending(DeliveryMode.PERSISTENT); + } - Connection connection = factory.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(bigQueue); - producer.setDeliveryMode(deliveryMode); - BytesMessage bytesMessage = session.createBytesMessage(); - bytesMessage.writeBytes(new byte[messageSize]); + public void doTestBrowsePending(int deliveryMode) throws Exception { - for (int i = 0; i < messageCount; i++) { - producer.send(bigQueue, bytesMessage); - } + Connection connection = factory.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(bigQueue); + producer.setDeliveryMode(deliveryMode); + BytesMessage bytesMessage = session.createBytesMessage(); + bytesMessage.writeBytes(new byte[messageSize]); - final QueueViewMBean queueViewMBean = (QueueViewMBean) - broker.getManagementContext().newProxyInstance(broker.getAdminView().getQueues()[0], QueueViewMBean.class, false); + for (int i = 0; i < messageCount; i++) { + producer.send(bigQueue, bytesMessage); + } - LOG.info(queueViewMBean.getName() + " Size: " + queueViewMBean.getEnqueueCount()); + final QueueViewMBean queueViewMBean = (QueueViewMBean) broker.getManagementContext().newProxyInstance(broker.getAdminView().getQueues()[0], QueueViewMBean.class, false); - connection.close(); + LOG.info(queueViewMBean.getName() + " Size: " + queueViewMBean.getEnqueueCount()); - assertFalse("Cache disabled on q", queueViewMBean.isCacheEnabled()); + connection.close(); - // ensure repeated browse does now blow mem + assertFalse("Cache disabled on q", queueViewMBean.isCacheEnabled()); - final Queue underTest = (Queue) ((RegionBroker)broker.getRegionBroker()).getQueueRegion().getDestinationMap().get(bigQueue); + // ensure repeated browse does now blow mem - // do twice to attempt to pull in 2*maxBrowsePageSize which uses up the system memory limit - Message[] browsed = underTest.browse(); - LOG.info("Browsed: " + browsed.length); - assertEquals("maxBrowsePageSize", maxBrowsePageSize, browsed.length); - browsed = underTest.browse(); - LOG.info("Browsed: " + browsed.length); - assertEquals("maxBrowsePageSize", maxBrowsePageSize, browsed.length); - Runtime.getRuntime().gc(); - long free = Runtime.getRuntime().freeMemory()/1024; - LOG.info("free at start of check: " + free); - // check for memory growth - for (int i=0; i<10; i++) { - LOG.info("free: " + Runtime.getRuntime().freeMemory()/1024); - browsed = underTest.browse(); - LOG.info("Browsed: " + browsed.length); - assertEquals("maxBrowsePageSize", maxBrowsePageSize, browsed.length); - Runtime.getRuntime().gc(); - Runtime.getRuntime().gc(); - assertTrue("No growth: " + Runtime.getRuntime().freeMemory()/1024 + " >= " + (free - (free * 0.2)), Runtime.getRuntime().freeMemory()/1024 >= (free - (free * 0.2))); - } - } + final Queue underTest = (Queue) ((RegionBroker) broker.getRegionBroker()).getQueueRegion().getDestinationMap().get(bigQueue); + // do twice to attempt to pull in 2*maxBrowsePageSize which uses up the system memory limit + Message[] browsed = underTest.browse(); + LOG.info("Browsed: " + browsed.length); + assertEquals("maxBrowsePageSize", maxBrowsePageSize, browsed.length); + browsed = underTest.browse(); + LOG.info("Browsed: " + browsed.length); + assertEquals("maxBrowsePageSize", maxBrowsePageSize, browsed.length); + Runtime.getRuntime().gc(); + long free = Runtime.getRuntime().freeMemory() / 1024; + LOG.info("free at start of check: " + free); + // check for memory growth + for (int i = 0; i < 10; i++) { + LOG.info("free: " + Runtime.getRuntime().freeMemory() / 1024); + browsed = underTest.browse(); + LOG.info("Browsed: " + browsed.length); + assertEquals("maxBrowsePageSize", maxBrowsePageSize, browsed.length); + Runtime.getRuntime().gc(); + Runtime.getRuntime().gc(); + assertTrue("No growth: " + Runtime.getRuntime().freeMemory() / 1024 + " >= " + (free - (free * 0.2)), Runtime.getRuntime().freeMemory() / 1024 >= (free - (free * 0.2))); + } + } - protected void setUp() throws Exception { - super.setUp(); - broker = new BrokerService(); - broker.setBrokerName("thisOne"); - configureBroker(); - broker.start(); - factory = new ActiveMQConnectionFactory("vm://thisOne?jms.alwaysSyncSend=true"); - factory.setWatchTopicAdvisories(false); + protected void setUp() throws Exception { + super.setUp(); + broker = new BrokerService(); + broker.setBrokerName("thisOne"); + configureBroker(); + broker.start(); + factory = new ActiveMQConnectionFactory("vm://thisOne?jms.alwaysSyncSend=true"); + factory.setWatchTopicAdvisories(false); - } + } - protected void tearDown() throws Exception { - super.tearDown(); - if (broker != null) { - broker.stop(); - broker = null; - } - } + protected void tearDown() throws Exception { + super.tearDown(); + if (broker != null) { + broker.stop(); + broker = null; + } + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4950Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4950Test.java index acfc0f6e99..91d9b8d5bb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4950Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4950Test.java @@ -47,149 +47,148 @@ import org.apache.activemq.transport.failover.FailoverTransport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - /** * Test for AMQ-4950. * Simulates an error during XA prepare call. */ public class AMQ4950Test extends BrokerRestartTestSupport { - protected static final Logger LOG = LoggerFactory.getLogger(AMQ4950Test.class); - protected static final String simulatedExceptionMessage = "Simulating error inside tx prepare()."; - public boolean prioritySupport = false; - protected String connectionUri = null; + protected static final Logger LOG = LoggerFactory.getLogger(AMQ4950Test.class); + protected static final String simulatedExceptionMessage = "Simulating error inside tx prepare()."; + public boolean prioritySupport = false; + protected String connectionUri = null; - @Override - protected void configureBroker(BrokerService broker) throws Exception { - broker.setDestinationPolicy(policyMap); - broker.setDeleteAllMessagesOnStartup(true); - broker.setUseJmx(false); - connectionUri = broker.addConnector("tcp://localhost:0").getPublishableConnectString(); - broker.setPlugins(new BrokerPlugin[]{ - new BrokerPluginSupport() { + @Override + protected void configureBroker(BrokerService broker) throws Exception { + broker.setDestinationPolicy(policyMap); + broker.setDeleteAllMessagesOnStartup(true); + broker.setUseJmx(false); + connectionUri = broker.addConnector("tcp://localhost:0").getPublishableConnectString(); + broker.setPlugins(new BrokerPlugin[]{new BrokerPluginSupport() { - @Override - public int prepareTransaction(ConnectionContext context, TransactionId xid) throws Exception { - getNext().prepareTransaction(context, xid); - LOG.debug("BrokerPlugin.prepareTransaction() will throw an exception."); - throw new XAException(simulatedExceptionMessage); - } + @Override + public int prepareTransaction(ConnectionContext context, TransactionId xid) throws Exception { + getNext().prepareTransaction(context, xid); + LOG.debug("BrokerPlugin.prepareTransaction() will throw an exception."); + throw new XAException(simulatedExceptionMessage); + } - @Override - public void commitTransaction(ConnectionContext context, TransactionId xid, boolean onePhase) throws Exception { - LOG.debug("BrokerPlugin.commitTransaction()."); - super.commitTransaction(context, xid, onePhase); - } - } - }); + @Override + public void commitTransaction(ConnectionContext context, + TransactionId xid, + boolean onePhase) throws Exception { + LOG.debug("BrokerPlugin.commitTransaction()."); + super.commitTransaction(context, xid, onePhase); + } + }}); } - /** - * Creates XA transaction and invokes XA prepare(). - * Due to registered BrokerFilter prepare will be handled by broker - * but then throw an exception. - * Prior to fixing AMQ-4950, this resulted in a ClassCastException - * in ConnectionStateTracker.PrepareReadonlyTransactionAction.onResponse() - * causing the failover transport to reconnect and replay the XA prepare(). - */ - public void testXAPrepareFailure() throws Exception { + /** + * Creates XA transaction and invokes XA prepare(). + * Due to registered BrokerFilter prepare will be handled by broker + * but then throw an exception. + * Prior to fixing AMQ-4950, this resulted in a ClassCastException + * in ConnectionStateTracker.PrepareReadonlyTransactionAction.onResponse() + * causing the failover transport to reconnect and replay the XA prepare(). + */ + public void testXAPrepareFailure() throws Exception { - assertNotNull(connectionUri); - ActiveMQXAConnectionFactory cf = new ActiveMQXAConnectionFactory("failover:(" + connectionUri + ")"); - ActiveMQXAConnection xaConnection = (ActiveMQXAConnection)cf.createConnection(); - xaConnection.start(); - XASession session = xaConnection.createXASession(); - XAResource resource = session.getXAResource(); - Xid tid = createXid(); - resource.start(tid, XAResource.TMNOFLAGS); + assertNotNull(connectionUri); + ActiveMQXAConnectionFactory cf = new ActiveMQXAConnectionFactory("failover:(" + connectionUri + ")"); + ActiveMQXAConnection xaConnection = (ActiveMQXAConnection) cf.createConnection(); + xaConnection.start(); + XASession session = xaConnection.createXASession(); + XAResource resource = session.getXAResource(); + Xid tid = createXid(); + resource.start(tid, XAResource.TMNOFLAGS); - MessageProducer producer = session.createProducer(session.createQueue(this.getClass().getName())); - Message message = session.createTextMessage("Sample Message"); - producer.send(message); - resource.end(tid, XAResource.TMSUCCESS); - try { - LOG.debug("Calling XA prepare(), expecting an exception"); - int ret = resource.prepare(tid); - if (XAResource.XA_OK == ret) - resource.commit(tid, false); - } catch (XAException xae) { - LOG.info("Received excpected XAException: {}", xae.getMessage()); - LOG.info("Rolling back transaction {}", tid); - - // with bug AMQ-4950 the thrown error reads "Cannot call prepare now" - // we check that we receive the original exception message as - // thrown by the BrokerPlugin - assertEquals(simulatedExceptionMessage, xae.getMessage()); - resource.rollback(tid); - } - // couple of assertions - assertTransactionGoneFromBroker(tid); - assertTransactionGoneFromConnection(broker.getBrokerName(), xaConnection.getClientID(), xaConnection.getConnectionInfo().getConnectionId(), tid); - assertTransactionGoneFromFailoverState(xaConnection, tid); + MessageProducer producer = session.createProducer(session.createQueue(this.getClass().getName())); + Message message = session.createTextMessage("Sample Message"); + producer.send(message); + resource.end(tid, XAResource.TMSUCCESS); + try { + LOG.debug("Calling XA prepare(), expecting an exception"); + int ret = resource.prepare(tid); + if (XAResource.XA_OK == ret) + resource.commit(tid, false); + } + catch (XAException xae) { + LOG.info("Received excpected XAException: {}", xae.getMessage()); + LOG.info("Rolling back transaction {}", tid); - //cleanup - producer.close(); - session.close(); - xaConnection.close(); - LOG.debug("testXAPrepareFailure() finished."); - } + // with bug AMQ-4950 the thrown error reads "Cannot call prepare now" + // we check that we receive the original exception message as + // thrown by the BrokerPlugin + assertEquals(simulatedExceptionMessage, xae.getMessage()); + resource.rollback(tid); + } + // couple of assertions + assertTransactionGoneFromBroker(tid); + assertTransactionGoneFromConnection(broker.getBrokerName(), xaConnection.getClientID(), xaConnection.getConnectionInfo().getConnectionId(), tid); + assertTransactionGoneFromFailoverState(xaConnection, tid); + //cleanup + producer.close(); + session.close(); + xaConnection.close(); + LOG.debug("testXAPrepareFailure() finished."); + } - public Xid createXid() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream os = new DataOutputStream(baos); - os.writeLong(++txGenerator); - os.close(); - final byte[] bs = baos.toByteArray(); + public Xid createXid() throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream os = new DataOutputStream(baos); + os.writeLong(++txGenerator); + os.close(); + final byte[] bs = baos.toByteArray(); - return new Xid() { - public int getFormatId() { - return 86; + return new Xid() { + public int getFormatId() { + return 86; + } + + public byte[] getGlobalTransactionId() { + return bs; + } + + public byte[] getBranchQualifier() { + return bs; + } + }; + } + + private void assertTransactionGoneFromFailoverState(ActiveMQXAConnection connection1, Xid tid) throws Exception { + + FailoverTransport transport = (FailoverTransport) connection1.getTransport().narrow(FailoverTransport.class); + TransactionInfo info = new TransactionInfo(connection1.getConnectionInfo().getConnectionId(), new XATransactionId(tid), TransactionInfo.COMMIT_ONE_PHASE); + assertNull("transaction should not exist in the state tracker", transport.getStateTracker().processCommitTransactionOnePhase(info)); + } + + private void assertTransactionGoneFromBroker(Xid tid) throws Exception { + BrokerService broker = BrokerRegistry.getInstance().lookup("localhost"); + TransactionBroker transactionBroker = (TransactionBroker) broker.getBroker().getAdaptor(TransactionBroker.class); + try { + transactionBroker.getTransaction(null, new XATransactionId(tid), false); + fail("expected exception on tx not found"); + } + catch (XAException expectedOnNotFound) { + } + } + + private void assertTransactionGoneFromConnection(String brokerName, + String clientId, + ConnectionId connectionId, + Xid tid) throws Exception { + BrokerService broker = BrokerRegistry.getInstance().lookup(brokerName); + CopyOnWriteArrayList connections = broker.getTransportConnectors().get(0).getConnections(); + for (TransportConnection connection : connections) { + if (connection.getConnectionId().equals(clientId)) { + try { + connection.processPrepareTransaction(new TransactionInfo(connectionId, new XATransactionId(tid), TransactionInfo.PREPARE)); + fail("did not get expected excepton on missing transaction, it must be still there in error!"); } - - public byte[] getGlobalTransactionId() { - return bs; + catch (IllegalStateException expectedOnNoTransaction) { } - - public byte[] getBranchQualifier() { - return bs; - } - }; - } - - - private void assertTransactionGoneFromFailoverState( - ActiveMQXAConnection connection1, Xid tid) throws Exception { - - FailoverTransport transport = (FailoverTransport) connection1.getTransport().narrow(FailoverTransport.class); - TransactionInfo info = new TransactionInfo(connection1.getConnectionInfo().getConnectionId(), new XATransactionId(tid), TransactionInfo.COMMIT_ONE_PHASE); - assertNull("transaction should not exist in the state tracker", - transport.getStateTracker().processCommitTransactionOnePhase(info)); - } - - - private void assertTransactionGoneFromBroker(Xid tid) throws Exception { - BrokerService broker = BrokerRegistry.getInstance().lookup("localhost"); - TransactionBroker transactionBroker = (TransactionBroker)broker.getBroker().getAdaptor(TransactionBroker.class); - try { - transactionBroker.getTransaction(null, new XATransactionId(tid), false); - fail("expected exception on tx not found"); - } catch (XAException expectedOnNotFound) { - } - } - - - private void assertTransactionGoneFromConnection(String brokerName, String clientId, ConnectionId connectionId, Xid tid) throws Exception { - BrokerService broker = BrokerRegistry.getInstance().lookup(brokerName); - CopyOnWriteArrayList connections = broker.getTransportConnectors().get(0).getConnections(); - for (TransportConnection connection: connections) { - if (connection.getConnectionId().equals(clientId)) { - try { - connection.processPrepareTransaction(new TransactionInfo(connectionId, new XATransactionId(tid), TransactionInfo.PREPARE)); - fail("did not get expected excepton on missing transaction, it must be still there in error!"); - } catch (IllegalStateException expectedOnNoTransaction) { - } - } - } - } + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4952Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4952Test.java index 882bbaa41b..549f77b32c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4952Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4952Test.java @@ -102,404 +102,412 @@ import static org.junit.Assert.*; @RunWith(value = Parameterized.class) public class AMQ4952Test { - private static final Logger LOG = LoggerFactory.getLogger(AMQ4952Test.class); + private static final Logger LOG = LoggerFactory.getLogger(AMQ4952Test.class); - protected static final int MESSAGE_COUNT = 1; + protected static final int MESSAGE_COUNT = 1; - protected BrokerService consumerBroker; - protected BrokerService producerBroker; + protected BrokerService consumerBroker; + protected BrokerService producerBroker; - protected ActiveMQQueue QUEUE_NAME = new ActiveMQQueue("duptest.store"); + protected ActiveMQQueue QUEUE_NAME = new ActiveMQQueue("duptest.store"); - private final CountDownLatch stopConsumerBroker = new CountDownLatch(1); - private final CountDownLatch consumerBrokerRestarted = new CountDownLatch(1); - private final CountDownLatch consumerRestartedAndMessageForwarded = new CountDownLatch(1); + private final CountDownLatch stopConsumerBroker = new CountDownLatch(1); + private final CountDownLatch consumerBrokerRestarted = new CountDownLatch(1); + private final CountDownLatch consumerRestartedAndMessageForwarded = new CountDownLatch(1); - private EmbeddedDataSource localDataSource; + private EmbeddedDataSource localDataSource; - @Parameterized.Parameter(0) - public boolean enableCursorAudit; + @Parameterized.Parameter(0) + public boolean enableCursorAudit; - @Parameterized.Parameters(name = "enableAudit={0}") - public static Iterable getTestParameters() { - return Arrays.asList(new Object[][] { { Boolean.TRUE }, { Boolean.FALSE } }); - } + @Parameterized.Parameters(name = "enableAudit={0}") + public static Iterable getTestParameters() { + return Arrays.asList(new Object[][]{{Boolean.TRUE}, {Boolean.FALSE}}); + } - @Test - public void testConsumerBrokerRestart() throws Exception { + @Test + public void testConsumerBrokerRestart() throws Exception { - Callable consumeMessageTask = new Callable() { - @Override - public Object call() throws Exception { + Callable consumeMessageTask = new Callable() { + @Override + public Object call() throws Exception { - int receivedMessageCount = 0; + int receivedMessageCount = 0; - ActiveMQConnectionFactory consumerFactory = new ActiveMQConnectionFactory("failover:(tcp://localhost:2006)?randomize=false&backup=false"); - Connection consumerConnection = consumerFactory.createConnection(); + ActiveMQConnectionFactory consumerFactory = new ActiveMQConnectionFactory("failover:(tcp://localhost:2006)?randomize=false&backup=false"); + Connection consumerConnection = consumerFactory.createConnection(); - try { + try { - consumerConnection.setClientID("consumer"); - consumerConnection.start(); + consumerConnection.setClientID("consumer"); + consumerConnection.start(); - Session consumerSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer messageConsumer = consumerSession.createConsumer(QUEUE_NAME); + Session consumerSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + MessageConsumer messageConsumer = consumerSession.createConsumer(QUEUE_NAME); - while (true) { - TextMessage textMsg = (TextMessage) messageConsumer.receive(5000); + while (true) { + TextMessage textMsg = (TextMessage) messageConsumer.receive(5000); - if (textMsg == null) { - return receivedMessageCount; - } + if (textMsg == null) { + return receivedMessageCount; + } - receivedMessageCount++; - LOG.info("*** receivedMessageCount {} message has MessageID {} ", receivedMessageCount, textMsg.getJMSMessageID()); + receivedMessageCount++; + LOG.info("*** receivedMessageCount {} message has MessageID {} ", receivedMessageCount, textMsg.getJMSMessageID()); - // on first delivery ensure the message is pending an - // ack when it is resent from the producer broker - if (textMsg.getJMSMessageID().endsWith("1") && receivedMessageCount == 1) { - LOG.info("Waiting for restart..."); - consumerRestartedAndMessageForwarded.await(90, TimeUnit.SECONDS); - } + // on first delivery ensure the message is pending an + // ack when it is resent from the producer broker + if (textMsg.getJMSMessageID().endsWith("1") && receivedMessageCount == 1) { + LOG.info("Waiting for restart..."); + consumerRestartedAndMessageForwarded.await(90, TimeUnit.SECONDS); + } - textMsg.acknowledge(); - } - } finally { - consumerConnection.close(); - } + textMsg.acknowledge(); + } } - }; + finally { + consumerConnection.close(); + } + } + }; - Runnable consumerBrokerResetTask = new Runnable() { - @Override - public void run() { + Runnable consumerBrokerResetTask = new Runnable() { + @Override + public void run() { - try { - // wait for signal - stopConsumerBroker.await(); + try { + // wait for signal + stopConsumerBroker.await(); - LOG.info("********* STOPPING CONSUMER BROKER"); + LOG.info("********* STOPPING CONSUMER BROKER"); - consumerBroker.stop(); - consumerBroker.waitUntilStopped(); + consumerBroker.stop(); + consumerBroker.waitUntilStopped(); - LOG.info("***** STARTING CONSUMER BROKER"); - // do not delete messages on startup - consumerBroker = createConsumerBroker(false); + LOG.info("***** STARTING CONSUMER BROKER"); + // do not delete messages on startup + consumerBroker = createConsumerBroker(false); - LOG.info("***** CONSUMER BROKER STARTED!!"); - consumerBrokerRestarted.countDown(); + LOG.info("***** CONSUMER BROKER STARTED!!"); + consumerBrokerRestarted.countDown(); - assertTrue("message forwarded on time", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("ProducerBroker totalMessageCount: " + producerBroker.getAdminView().getTotalMessageCount()); - return producerBroker.getAdminView().getTotalMessageCount() == 0; - } - })); - consumerRestartedAndMessageForwarded.countDown(); - - } catch (Exception e) { - LOG.error("Exception when stopping/starting the consumerBroker ", e); - } + assertTrue("message forwarded on time", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("ProducerBroker totalMessageCount: " + producerBroker.getAdminView().getTotalMessageCount()); + return producerBroker.getAdminView().getTotalMessageCount() == 0; + } + })); + consumerRestartedAndMessageForwarded.countDown(); } - }; - - ExecutorService executor = Executors.newFixedThreadPool(2); - - // start consumerBroker start/stop task - executor.execute(consumerBrokerResetTask); - - // start consuming messages - Future numberOfConsumedMessage = executor.submit(consumeMessageTask); - - produceMessages(); - - // Wait for consumer to finish - int totalMessagesConsumed = numberOfConsumedMessage.get(); - - StringBuffer contents = new StringBuffer(); - boolean messageInStore = isMessageInJDBCStore(localDataSource, contents); - LOG.debug("****number of messages received " + totalMessagesConsumed); - - assertEquals("number of messages received", 2, totalMessagesConsumed); - assertEquals("messages left in store", true, messageInStore); - assertTrue("message is in dlq: " + contents.toString(), contents.toString().contains("DLQ")); - } - - private void produceMessages() throws JMSException { - - ActiveMQConnectionFactory producerFactory = new ActiveMQConnectionFactory("failover:(tcp://localhost:2003)?randomize=false&backup=false"); - Connection producerConnection = producerFactory.createConnection(); - - try { - producerConnection.setClientID("producer"); - producerConnection.start(); - - Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - final MessageProducer remoteProducer = producerSession.createProducer(QUEUE_NAME); - - int i = 0; - while (MESSAGE_COUNT > i) { - String payload = "test msg " + i; - TextMessage msg = producerSession.createTextMessage(payload); - remoteProducer.send(msg); - i++; + catch (Exception e) { + LOG.error("Exception when stopping/starting the consumerBroker ", e); } - } finally { - producerConnection.close(); - } - } + } + }; - @Before - public void setUp() throws Exception { - LOG.debug("Running with enableCursorAudit set to {}", this.enableCursorAudit); - doSetUp(); - } + ExecutorService executor = Executors.newFixedThreadPool(2); - @After - public void tearDown() throws Exception { - doTearDown(); - } + // start consumerBroker start/stop task + executor.execute(consumerBrokerResetTask); - protected void doTearDown() throws Exception { + // start consuming messages + Future numberOfConsumedMessage = executor.submit(consumeMessageTask); - try { - producerBroker.stop(); - } catch (Exception ex) { - } - try { - consumerBroker.stop(); - } catch (Exception ex) { - } - } + produceMessages(); - protected void doSetUp() throws Exception { - producerBroker = createProducerBroker(); - consumerBroker = createConsumerBroker(true); - } + // Wait for consumer to finish + int totalMessagesConsumed = numberOfConsumedMessage.get(); - /** - * Producer broker listens on localhost:2003 networks to consumerBroker - - * localhost:2006 - * - * @return - * @throws Exception - */ - protected BrokerService createProducerBroker() throws Exception { + StringBuffer contents = new StringBuffer(); + boolean messageInStore = isMessageInJDBCStore(localDataSource, contents); + LOG.debug("****number of messages received " + totalMessagesConsumed); - String networkToPorts[] = new String[] { "2006" }; - HashMap networkProps = new HashMap(); + assertEquals("number of messages received", 2, totalMessagesConsumed); + assertEquals("messages left in store", true, messageInStore); + assertTrue("message is in dlq: " + contents.toString(), contents.toString().contains("DLQ")); + } - networkProps.put("networkTTL", "10"); - networkProps.put("conduitSubscriptions", "true"); - networkProps.put("decreaseNetworkConsumerPriority", "true"); - networkProps.put("dynamicOnly", "true"); + private void produceMessages() throws JMSException { - BrokerService broker = new BrokerService(); - broker.getManagementContext().setCreateConnector(false); - broker.setDeleteAllMessagesOnStartup(true); - broker.setBrokerName("BP"); - broker.setAdvisorySupport(false); + ActiveMQConnectionFactory producerFactory = new ActiveMQConnectionFactory("failover:(tcp://localhost:2003)?randomize=false&backup=false"); + Connection producerConnection = producerFactory.createConnection(); - // lazy init listener on broker start - TransportConnector transportConnector = new TransportConnector(); - transportConnector.setUri(new URI("tcp://localhost:2003")); - List transportConnectors = new ArrayList(); - transportConnectors.add(transportConnector); - broker.setTransportConnectors(transportConnectors); + try { + producerConnection.setClientID("producer"); + producerConnection.start(); - // network to consumerBroker + Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - if (networkToPorts != null && networkToPorts.length > 0) { - StringBuilder builder = new StringBuilder("static:(failover:(tcp://localhost:2006)?maxReconnectAttempts=0)?useExponentialBackOff=false"); - NetworkConnector nc = broker.addNetworkConnector(builder.toString()); - if (networkProps != null) { - IntrospectionSupport.setProperties(nc, networkProps); + final MessageProducer remoteProducer = producerSession.createProducer(QUEUE_NAME); + + int i = 0; + while (MESSAGE_COUNT > i) { + String payload = "test msg " + i; + TextMessage msg = producerSession.createTextMessage(payload); + remoteProducer.send(msg); + i++; + } + + } + finally { + producerConnection.close(); + } + } + + @Before + public void setUp() throws Exception { + LOG.debug("Running with enableCursorAudit set to {}", this.enableCursorAudit); + doSetUp(); + } + + @After + public void tearDown() throws Exception { + doTearDown(); + } + + protected void doTearDown() throws Exception { + + try { + producerBroker.stop(); + } + catch (Exception ex) { + } + try { + consumerBroker.stop(); + } + catch (Exception ex) { + } + } + + protected void doSetUp() throws Exception { + producerBroker = createProducerBroker(); + consumerBroker = createConsumerBroker(true); + } + + /** + * Producer broker listens on localhost:2003 networks to consumerBroker - + * localhost:2006 + * + * @return + * @throws Exception + */ + protected BrokerService createProducerBroker() throws Exception { + + String networkToPorts[] = new String[]{"2006"}; + HashMap networkProps = new HashMap(); + + networkProps.put("networkTTL", "10"); + networkProps.put("conduitSubscriptions", "true"); + networkProps.put("decreaseNetworkConsumerPriority", "true"); + networkProps.put("dynamicOnly", "true"); + + BrokerService broker = new BrokerService(); + broker.getManagementContext().setCreateConnector(false); + broker.setDeleteAllMessagesOnStartup(true); + broker.setBrokerName("BP"); + broker.setAdvisorySupport(false); + + // lazy init listener on broker start + TransportConnector transportConnector = new TransportConnector(); + transportConnector.setUri(new URI("tcp://localhost:2003")); + List transportConnectors = new ArrayList(); + transportConnectors.add(transportConnector); + broker.setTransportConnectors(transportConnectors); + + // network to consumerBroker + + if (networkToPorts != null && networkToPorts.length > 0) { + StringBuilder builder = new StringBuilder("static:(failover:(tcp://localhost:2006)?maxReconnectAttempts=0)?useExponentialBackOff=false"); + NetworkConnector nc = broker.addNetworkConnector(builder.toString()); + if (networkProps != null) { + IntrospectionSupport.setProperties(nc, networkProps); + } + nc.setStaticallyIncludedDestinations(Arrays.asList(new ActiveMQQueue[]{QUEUE_NAME})); + } + + // Persistence adapter + + JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); + EmbeddedDataSource remoteDataSource = new EmbeddedDataSource(); + remoteDataSource.setDatabaseName("target/derbyDBRemoteBroker"); + remoteDataSource.setCreateDatabase("create"); + jdbc.setDataSource(remoteDataSource); + broker.setPersistenceAdapter(jdbc); + + // set Policy entries + PolicyEntry policy = new PolicyEntry(); + + policy.setQueue(">"); + policy.setEnableAudit(false); + policy.setUseCache(false); + policy.setExpireMessagesPeriod(0); + + // set replay with no consumers + ConditionalNetworkBridgeFilterFactory conditionalNetworkBridgeFilterFactory = new ConditionalNetworkBridgeFilterFactory(); + conditionalNetworkBridgeFilterFactory.setReplayWhenNoConsumers(true); + policy.setNetworkBridgeFilterFactory(conditionalNetworkBridgeFilterFactory); + + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); + broker.setDestinationPolicy(pMap); + + broker.start(); + broker.waitUntilStarted(); + + return broker; + } + + /** + * consumerBroker - listens on localhost:2006 + * + * @param deleteMessages - drop messages when broker instance is created + * @return + * @throws Exception + */ + protected BrokerService createConsumerBroker(boolean deleteMessages) throws Exception { + + String scheme = "tcp"; + String listenPort = "2006"; + + BrokerService broker = new BrokerService(); + broker.getManagementContext().setCreateConnector(false); + broker.setDeleteAllMessagesOnStartup(deleteMessages); + broker.setBrokerName("BC"); + // lazy init listener on broker start + TransportConnector transportConnector = new TransportConnector(); + transportConnector.setUri(new URI(scheme + "://localhost:" + listenPort)); + List transportConnectors = new ArrayList(); + transportConnectors.add(transportConnector); + broker.setTransportConnectors(transportConnectors); + + // policy entries + + PolicyEntry policy = new PolicyEntry(); + + policy.setQueue(">"); + policy.setEnableAudit(enableCursorAudit); + policy.setExpireMessagesPeriod(0); + + // set replay with no consumers + ConditionalNetworkBridgeFilterFactory conditionalNetworkBridgeFilterFactory = new ConditionalNetworkBridgeFilterFactory(); + conditionalNetworkBridgeFilterFactory.setReplayWhenNoConsumers(true); + policy.setNetworkBridgeFilterFactory(conditionalNetworkBridgeFilterFactory); + + PolicyMap pMap = new PolicyMap(); + + pMap.setDefaultEntry(policy); + broker.setDestinationPolicy(pMap); + + // Persistence adapter + JDBCPersistenceAdapter localJDBCPersistentAdapter = new JDBCPersistenceAdapter(); + EmbeddedDataSource localDataSource = new EmbeddedDataSource(); + localDataSource.setDatabaseName("target/derbyDBLocalBroker"); + localDataSource.setCreateDatabase("create"); + localJDBCPersistentAdapter.setDataSource(localDataSource); + broker.setPersistenceAdapter(localJDBCPersistentAdapter); + + if (deleteMessages) { + // no plugin on restart + broker.setPlugins(new BrokerPlugin[]{new MyTestPlugin()}); + } + + this.localDataSource = localDataSource; + + broker.start(); + broker.waitUntilStarted(); + + return broker; + } + + /** + * Query JDBC Store to see if messages are left + * + * @param dataSource + * @return + * @throws SQLException + */ + private boolean isMessageInJDBCStore(DataSource dataSource, StringBuffer stringBuffer) throws SQLException { + + boolean tableHasData = false; + String query = "select * from ACTIVEMQ_MSGS"; + + java.sql.Connection conn = dataSource.getConnection(); + PreparedStatement s = conn.prepareStatement(query); + + ResultSet set = null; + + try { + StringBuffer headers = new StringBuffer(); + set = s.executeQuery(); + ResultSetMetaData metaData = set.getMetaData(); + for (int i = 1; i <= metaData.getColumnCount(); i++) { + + if (i == 1) { + headers.append("||"); } - nc.setStaticallyIncludedDestinations(Arrays. asList(new ActiveMQQueue[] { QUEUE_NAME })); - } + headers.append(metaData.getColumnName(i) + "||"); + } + LOG.error(headers.toString()); - // Persistence adapter + while (set.next()) { + tableHasData = true; - JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); - EmbeddedDataSource remoteDataSource = new EmbeddedDataSource(); - remoteDataSource.setDatabaseName("target/derbyDBRemoteBroker"); - remoteDataSource.setCreateDatabase("create"); - jdbc.setDataSource(remoteDataSource); - broker.setPersistenceAdapter(jdbc); - - // set Policy entries - PolicyEntry policy = new PolicyEntry(); - - policy.setQueue(">"); - policy.setEnableAudit(false); - policy.setUseCache(false); - policy.setExpireMessagesPeriod(0); - - // set replay with no consumers - ConditionalNetworkBridgeFilterFactory conditionalNetworkBridgeFilterFactory = new ConditionalNetworkBridgeFilterFactory(); - conditionalNetworkBridgeFilterFactory.setReplayWhenNoConsumers(true); - policy.setNetworkBridgeFilterFactory(conditionalNetworkBridgeFilterFactory); - - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - broker.setDestinationPolicy(pMap); - - broker.start(); - broker.waitUntilStarted(); - - return broker; - } - - /** - * consumerBroker - listens on localhost:2006 - * - * @param deleteMessages - * - drop messages when broker instance is created - * @return - * @throws Exception - */ - protected BrokerService createConsumerBroker(boolean deleteMessages) throws Exception { - - String scheme = "tcp"; - String listenPort = "2006"; - - BrokerService broker = new BrokerService(); - broker.getManagementContext().setCreateConnector(false); - broker.setDeleteAllMessagesOnStartup(deleteMessages); - broker.setBrokerName("BC"); - // lazy init listener on broker start - TransportConnector transportConnector = new TransportConnector(); - transportConnector.setUri(new URI(scheme + "://localhost:" + listenPort)); - List transportConnectors = new ArrayList(); - transportConnectors.add(transportConnector); - broker.setTransportConnectors(transportConnectors); - - // policy entries - - PolicyEntry policy = new PolicyEntry(); - - policy.setQueue(">"); - policy.setEnableAudit(enableCursorAudit); - policy.setExpireMessagesPeriod(0); - - // set replay with no consumers - ConditionalNetworkBridgeFilterFactory conditionalNetworkBridgeFilterFactory = new ConditionalNetworkBridgeFilterFactory(); - conditionalNetworkBridgeFilterFactory.setReplayWhenNoConsumers(true); - policy.setNetworkBridgeFilterFactory(conditionalNetworkBridgeFilterFactory); - - PolicyMap pMap = new PolicyMap(); - - pMap.setDefaultEntry(policy); - broker.setDestinationPolicy(pMap); - - // Persistence adapter - JDBCPersistenceAdapter localJDBCPersistentAdapter = new JDBCPersistenceAdapter(); - EmbeddedDataSource localDataSource = new EmbeddedDataSource(); - localDataSource.setDatabaseName("target/derbyDBLocalBroker"); - localDataSource.setCreateDatabase("create"); - localJDBCPersistentAdapter.setDataSource(localDataSource); - broker.setPersistenceAdapter(localJDBCPersistentAdapter); - - if (deleteMessages) { - // no plugin on restart - broker.setPlugins(new BrokerPlugin[] { new MyTestPlugin() }); - } - - this.localDataSource = localDataSource; - - broker.start(); - broker.waitUntilStarted(); - - return broker; - } - - /** - * Query JDBC Store to see if messages are left - * - * @param dataSource - * @return - * @throws SQLException - */ - private boolean isMessageInJDBCStore(DataSource dataSource, StringBuffer stringBuffer) throws SQLException { - - boolean tableHasData = false; - String query = "select * from ACTIVEMQ_MSGS"; - - java.sql.Connection conn = dataSource.getConnection(); - PreparedStatement s = conn.prepareStatement(query); - - ResultSet set = null; - - try { - StringBuffer headers = new StringBuffer(); - set = s.executeQuery(); - ResultSetMetaData metaData = set.getMetaData(); for (int i = 1; i <= metaData.getColumnCount(); i++) { - - if (i == 1) { - headers.append("||"); - } - headers.append(metaData.getColumnName(i) + "||"); + if (i == 1) { + stringBuffer.append("|"); + } + stringBuffer.append(set.getString(i) + "|"); } - LOG.error(headers.toString()); + LOG.error(stringBuffer.toString()); + } + } + finally { + try { + set.close(); + } + catch (Throwable ignore) { + } + try { + s.close(); + } + catch (Throwable ignore) { + } - while (set.next()) { - tableHasData = true; + conn.close(); + } - for (int i = 1; i <= metaData.getColumnCount(); i++) { - if (i == 1) { - stringBuffer.append("|"); - } - stringBuffer.append(set.getString(i) + "|"); - } - LOG.error(stringBuffer.toString()); - } - } finally { - try { - set.close(); - } catch (Throwable ignore) { - } - try { - s.close(); - } catch (Throwable ignore) { - } + return tableHasData; + } - conn.close(); - } + /** + * plugin used to ensure consumerbroker is restared before the network + * message from producerBroker is acked + */ + class MyTestPlugin implements BrokerPlugin { - return tableHasData; - } + @Override + public Broker installPlugin(Broker broker) throws Exception { + return new MyTestBroker(broker); + } + } - /** - * plugin used to ensure consumerbroker is restared before the network - * message from producerBroker is acked - */ - class MyTestPlugin implements BrokerPlugin { + class MyTestBroker extends BrokerFilter { - @Override - public Broker installPlugin(Broker broker) throws Exception { - return new MyTestBroker(broker); - } - } + public MyTestBroker(Broker next) { + super(next); + } - class MyTestBroker extends BrokerFilter { + @Override + public void send(ProducerBrokerExchange producerExchange, + org.apache.activemq.command.Message messageSend) throws Exception { - public MyTestBroker(Broker next) { - super(next); - } - - @Override - public void send(ProducerBrokerExchange producerExchange, org.apache.activemq.command.Message messageSend) throws Exception { - - super.send(producerExchange, messageSend); - LOG.error("Stopping broker on send: " + messageSend.getMessageId().getProducerSequenceId()); - stopConsumerBroker.countDown(); - producerExchange.getConnectionContext().setDontSendReponse(true); - } - } + super.send(producerExchange, messageSend); + LOG.error("Stopping broker on send: " + messageSend.getMessageId().getProducerSequenceId()); + stopConsumerBroker.countDown(); + producerExchange.getConnectionContext().setDontSendReponse(true); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5035Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5035Test.java index 13ddd30c4f..beab4c3ecd 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5035Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5035Test.java @@ -35,49 +35,49 @@ import org.junit.Test; public class AMQ5035Test { - private static final String CLIENT_ID = "amq-test-client-id"; - private static final String DURABLE_SUB_NAME = "testDurable"; + private static final String CLIENT_ID = "amq-test-client-id"; + private static final String DURABLE_SUB_NAME = "testDurable"; - private final String xbean = "xbean:"; - private final String confBase = "src/test/resources/org/apache/activemq/bugs/amq5035"; + private final String xbean = "xbean:"; + private final String confBase = "src/test/resources/org/apache/activemq/bugs/amq5035"; - private static BrokerService brokerService; - private String connectionUri; + private static BrokerService brokerService; + private String connectionUri; - @Before - public void setUp() throws Exception { - brokerService = BrokerFactory.createBroker(xbean + confBase + "/activemq.xml"); - connectionUri = brokerService.getTransportConnectorByScheme("tcp").getPublishableConnectString(); - brokerService.setDeleteAllMessagesOnStartup(true); - brokerService.start(); - brokerService.waitUntilStarted(); - } + @Before + public void setUp() throws Exception { + brokerService = BrokerFactory.createBroker(xbean + confBase + "/activemq.xml"); + connectionUri = brokerService.getTransportConnectorByScheme("tcp").getPublishableConnectString(); + brokerService.setDeleteAllMessagesOnStartup(true); + brokerService.start(); + brokerService.waitUntilStarted(); + } - @After - public void tearDown() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - } + @After + public void tearDown() throws Exception { + brokerService.stop(); + brokerService.waitUntilStopped(); + } - @Test - public void testFoo() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - Connection connection = factory.createConnection(); - connection.setClientID(CLIENT_ID); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic("Test.Topic"); - MessageConsumer consumer = session.createDurableSubscriber(topic, DURABLE_SUB_NAME); - consumer.close(); + @Test + public void testFoo() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); + Connection connection = factory.createConnection(); + connection.setClientID(CLIENT_ID); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Topic topic = session.createTopic("Test.Topic"); + MessageConsumer consumer = session.createDurableSubscriber(topic, DURABLE_SUB_NAME); + consumer.close(); - BrokerViewMBean brokerView = getBrokerView(DURABLE_SUB_NAME); - brokerView.destroyDurableSubscriber(CLIENT_ID, DURABLE_SUB_NAME); - } + BrokerViewMBean brokerView = getBrokerView(DURABLE_SUB_NAME); + brokerView.destroyDurableSubscriber(CLIENT_ID, DURABLE_SUB_NAME); + } - private BrokerViewMBean getBrokerView(String testDurable) throws MalformedObjectNameException { - ObjectName brokerName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost"); - BrokerViewMBean view = (BrokerViewMBean) brokerService.getManagementContext().newProxyInstance(brokerName, BrokerViewMBean.class, true); - assertNotNull(view); - return view; - } + private BrokerViewMBean getBrokerView(String testDurable) throws MalformedObjectNameException { + ObjectName brokerName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost"); + BrokerViewMBean view = (BrokerViewMBean) brokerService.getManagementContext().newProxyInstance(brokerName, BrokerViewMBean.class, true); + assertNotNull(view); + return view; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5136Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5136Test.java index c2cb11edd0..8596683ee3 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5136Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5136Test.java @@ -23,6 +23,7 @@ import javax.jms.JMSException; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.Topic; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerRegistry; import org.apache.activemq.broker.BrokerService; @@ -32,64 +33,66 @@ import org.junit.Test; public class AMQ5136Test { - BrokerService brokerService; - @Before - public void startBroker() throws Exception { - brokerService = new BrokerService(); - brokerService.setPersistent(false); - brokerService.start(); - } + BrokerService brokerService; - @After - public void stopBroker() throws Exception { - brokerService.stop(); - } + @Before + public void startBroker() throws Exception { + brokerService = new BrokerService(); + brokerService.setPersistent(false); + brokerService.start(); + } - @Test - public void memoryUsageOnCommit() throws Exception { - sendMessagesAndAssertMemoryUsage(new TransactionHandler() { - @Override - public void finishTransaction(Session session) throws JMSException { - session.commit(); - } - }); - } + @After + public void stopBroker() throws Exception { + brokerService.stop(); + } - @Test - public void memoryUsageOnRollback() throws Exception { - sendMessagesAndAssertMemoryUsage(new TransactionHandler() { - @Override - public void finishTransaction(Session session) throws JMSException { - session.rollback(); - } - }); - } + @Test + public void memoryUsageOnCommit() throws Exception { + sendMessagesAndAssertMemoryUsage(new TransactionHandler() { + @Override + public void finishTransaction(Session session) throws JMSException { + session.commit(); + } + }); + } - private void sendMessagesAndAssertMemoryUsage(TransactionHandler transactionHandler) throws Exception { - ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = connectionFactory.createConnection(); - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Topic destination = session.createTopic("ActiveMQBug"); - MessageProducer producer = session.createProducer(destination); - for (int i = 0; i < 100; i++) { - BytesMessage message = session.createBytesMessage(); - message.writeBytes(generateBytes()); - producer.send(message); - transactionHandler.finishTransaction(session); - } - connection.close(); - org.junit.Assert.assertEquals(0, BrokerRegistry.getInstance().findFirst().getSystemUsage().getMemoryUsage().getPercentUsage()); - } + @Test + public void memoryUsageOnRollback() throws Exception { + sendMessagesAndAssertMemoryUsage(new TransactionHandler() { + @Override + public void finishTransaction(Session session) throws JMSException { + session.rollback(); + } + }); + } - private byte[] generateBytes() { - byte[] bytes = new byte[100000]; - for (int i = 0; i < 100000; i++) { - bytes[i] = (byte) i; - } - return bytes; - } + private void sendMessagesAndAssertMemoryUsage(TransactionHandler transactionHandler) throws Exception { + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost"); + Connection connection = connectionFactory.createConnection(); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + Topic destination = session.createTopic("ActiveMQBug"); + MessageProducer producer = session.createProducer(destination); + for (int i = 0; i < 100; i++) { + BytesMessage message = session.createBytesMessage(); + message.writeBytes(generateBytes()); + producer.send(message); + transactionHandler.finishTransaction(session); + } + connection.close(); + org.junit.Assert.assertEquals(0, BrokerRegistry.getInstance().findFirst().getSystemUsage().getMemoryUsage().getPercentUsage()); + } - private static interface TransactionHandler { - void finishTransaction(Session session) throws JMSException; - } + private byte[] generateBytes() { + byte[] bytes = new byte[100000]; + for (int i = 0; i < 100000; i++) { + bytes[i] = (byte) i; + } + return bytes; + } + + private static interface TransactionHandler { + + void finishTransaction(Session session) throws JMSException; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5212Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5212Test.java index 4c0765538e..dc37c79a33 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5212Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5212Test.java @@ -25,6 +25,7 @@ import java.util.concurrent.atomic.AtomicInteger; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.Session; + import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQMessageProducer; @@ -40,186 +41,185 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @RunWith(value = Parameterized.class) public class AMQ5212Test { - BrokerService brokerService; + BrokerService brokerService; - @Parameterized.Parameter(0) - public boolean concurrentStoreAndDispatchQ = true; + @Parameterized.Parameter(0) + public boolean concurrentStoreAndDispatchQ = true; - @Parameterized.Parameters(name = "concurrentStoreAndDispatch={0}") - public static Iterable getTestParameters() { - return Arrays.asList(new Object[][]{{Boolean.TRUE}, {Boolean.FALSE}}); - } + @Parameterized.Parameters(name = "concurrentStoreAndDispatch={0}") + public static Iterable getTestParameters() { + return Arrays.asList(new Object[][]{{Boolean.TRUE}, {Boolean.FALSE}}); + } - @Before - public void setUp() throws Exception { - start(true); - } + @Before + public void setUp() throws Exception { + start(true); + } - public void start(boolean deleteAllMessages) throws Exception { - brokerService = new BrokerService(); - if (deleteAllMessages) { - brokerService.deleteAllMessages(); - } - ((KahaDBPersistenceAdapter)brokerService.getPersistenceAdapter()).setConcurrentStoreAndDispatchQueues(concurrentStoreAndDispatchQ); - brokerService.addConnector("tcp://localhost:0"); - brokerService.setAdvisorySupport(false); - brokerService.start(); - } + public void start(boolean deleteAllMessages) throws Exception { + brokerService = new BrokerService(); + if (deleteAllMessages) { + brokerService.deleteAllMessages(); + } + ((KahaDBPersistenceAdapter) brokerService.getPersistenceAdapter()).setConcurrentStoreAndDispatchQueues(concurrentStoreAndDispatchQ); + brokerService.addConnector("tcp://localhost:0"); + brokerService.setAdvisorySupport(false); + brokerService.start(); + } - @After - public void tearDown() throws Exception { - brokerService.stop(); - } + @After + public void tearDown() throws Exception { + brokerService.stop(); + } - @Test - public void verifyDuplicateSuppressionWithConsumer() throws Exception { - doVerifyDuplicateSuppression(100, 100, true); - } + @Test + public void verifyDuplicateSuppressionWithConsumer() throws Exception { + doVerifyDuplicateSuppression(100, 100, true); + } - @Test - public void verifyDuplicateSuppression() throws Exception { - doVerifyDuplicateSuppression(100, 100, false); - } + @Test + public void verifyDuplicateSuppression() throws Exception { + doVerifyDuplicateSuppression(100, 100, false); + } - public void doVerifyDuplicateSuppression(final int numToSend, final int expectedTotalEnqueue, final boolean demand) throws Exception { - final ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerService.getTransportConnectors().get(0).getPublishableConnectString()); - connectionFactory.setCopyMessageOnSend(false); - connectionFactory.setWatchTopicAdvisories(false); + public void doVerifyDuplicateSuppression(final int numToSend, + final int expectedTotalEnqueue, + final boolean demand) throws Exception { + final ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerService.getTransportConnectors().get(0).getPublishableConnectString()); + connectionFactory.setCopyMessageOnSend(false); + connectionFactory.setWatchTopicAdvisories(false); - final int concurrency = 40; - final AtomicInteger workCount = new AtomicInteger(numToSend); - ExecutorService executorService = Executors.newFixedThreadPool(concurrency); - for (int i = 0; i < concurrency; i++) { - executorService.execute(new Runnable() { - @Override - public void run() { - try { - int i; - while ((i = workCount.getAndDecrement()) > 0) { - ActiveMQConnection activeMQConnection = (ActiveMQConnection) connectionFactory.createConnection(); - activeMQConnection.start(); - ActiveMQSession activeMQSession = (ActiveMQSession) activeMQConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - - ActiveMQQueue dest = new ActiveMQQueue("queue-" + i + "-" - + AMQ5212Test.class.getSimpleName()); - ActiveMQMessageProducer activeMQMessageProducer = (ActiveMQMessageProducer) activeMQSession.createProducer(dest); - if (demand) { - // create demand so page in will happen - activeMQSession.createConsumer(dest); - } - ActiveMQTextMessage message = new ActiveMQTextMessage(); - message.setDestination(dest); - activeMQMessageProducer.send(message, null); - - // send a duplicate - activeMQConnection.syncSendPacket(message); - activeMQConnection.close(); - - } - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - } - TimeUnit.SECONDS.sleep(1); - executorService.shutdown(); - executorService.awaitTermination(5, TimeUnit.MINUTES); - - Wait.waitFor(new Wait.Condition() { + final int concurrency = 40; + final AtomicInteger workCount = new AtomicInteger(numToSend); + ExecutorService executorService = Executors.newFixedThreadPool(concurrency); + for (int i = 0; i < concurrency; i++) { + executorService.execute(new Runnable() { @Override - public boolean isSatisified() throws Exception { - return expectedTotalEnqueue == brokerService.getAdminView().getTotalEnqueueCount(); + public void run() { + try { + int i; + while ((i = workCount.getAndDecrement()) > 0) { + ActiveMQConnection activeMQConnection = (ActiveMQConnection) connectionFactory.createConnection(); + activeMQConnection.start(); + ActiveMQSession activeMQSession = (ActiveMQSession) activeMQConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + + ActiveMQQueue dest = new ActiveMQQueue("queue-" + i + "-" + AMQ5212Test.class.getSimpleName()); + ActiveMQMessageProducer activeMQMessageProducer = (ActiveMQMessageProducer) activeMQSession.createProducer(dest); + if (demand) { + // create demand so page in will happen + activeMQSession.createConsumer(dest); + } + ActiveMQTextMessage message = new ActiveMQTextMessage(); + message.setDestination(dest); + activeMQMessageProducer.send(message, null); + + // send a duplicate + activeMQConnection.syncSendPacket(message); + activeMQConnection.close(); + + } + } + catch (Exception e) { + e.printStackTrace(); + } } - }); - assertEquals("total enqueue as expected", expectedTotalEnqueue, brokerService.getAdminView().getTotalEnqueueCount()); - } + }); + } + TimeUnit.SECONDS.sleep(1); + executorService.shutdown(); + executorService.awaitTermination(5, TimeUnit.MINUTES); - @Test - public void verifyConsumptionOnDuplicate() throws Exception { + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return expectedTotalEnqueue == brokerService.getAdminView().getTotalEnqueueCount(); + } + }); + assertEquals("total enqueue as expected", expectedTotalEnqueue, brokerService.getAdminView().getTotalEnqueueCount()); + } - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerService.getTransportConnectors().get(0).getPublishableConnectString()); - connectionFactory.setCopyMessageOnSend(false); - connectionFactory.setWatchTopicAdvisories(false); + @Test + public void verifyConsumptionOnDuplicate() throws Exception { - ActiveMQConnection activeMQConnection = (ActiveMQConnection) connectionFactory.createConnection(); - activeMQConnection.start(); - ActiveMQSession activeMQSession = (ActiveMQSession) activeMQConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerService.getTransportConnectors().get(0).getPublishableConnectString()); + connectionFactory.setCopyMessageOnSend(false); + connectionFactory.setWatchTopicAdvisories(false); - ActiveMQQueue dest = new ActiveMQQueue("Q"); - ActiveMQMessageProducer activeMQMessageProducer = (ActiveMQMessageProducer) activeMQSession.createProducer(dest); - ActiveMQTextMessage message = new ActiveMQTextMessage(); - message.setDestination(dest); - activeMQMessageProducer.send(message, null); + ActiveMQConnection activeMQConnection = (ActiveMQConnection) connectionFactory.createConnection(); + activeMQConnection.start(); + ActiveMQSession activeMQSession = (ActiveMQSession) activeMQConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - // send a duplicate - activeMQConnection.syncSendPacket(message); + ActiveMQQueue dest = new ActiveMQQueue("Q"); + ActiveMQMessageProducer activeMQMessageProducer = (ActiveMQMessageProducer) activeMQSession.createProducer(dest); + ActiveMQTextMessage message = new ActiveMQTextMessage(); + message.setDestination(dest); + activeMQMessageProducer.send(message, null); - activeMQConnection.close(); + // send a duplicate + activeMQConnection.syncSendPacket(message); - // verify original can be consumed after restart - brokerService.stop(); - brokerService.start(false); + activeMQConnection.close(); - connectionFactory = new ActiveMQConnectionFactory(brokerService.getTransportConnectors().get(0).getPublishableConnectString()); - connectionFactory.setCopyMessageOnSend(false); - connectionFactory.setWatchTopicAdvisories(false); + // verify original can be consumed after restart + brokerService.stop(); + brokerService.start(false); - activeMQConnection = (ActiveMQConnection) connectionFactory.createConnection(); - activeMQConnection.start(); - activeMQSession = (ActiveMQSession) activeMQConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + connectionFactory = new ActiveMQConnectionFactory(brokerService.getTransportConnectors().get(0).getPublishableConnectString()); + connectionFactory.setCopyMessageOnSend(false); + connectionFactory.setWatchTopicAdvisories(false); - MessageConsumer messageConsumer = activeMQSession.createConsumer(dest); - Message received = messageConsumer.receive(4000); - assertNotNull("Got message", received); - assertEquals("match", message.getJMSMessageID(), received.getJMSMessageID()); + activeMQConnection = (ActiveMQConnection) connectionFactory.createConnection(); + activeMQConnection.start(); + activeMQSession = (ActiveMQSession) activeMQConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - activeMQConnection.close(); - } + MessageConsumer messageConsumer = activeMQSession.createConsumer(dest); + Message received = messageConsumer.receive(4000); + assertNotNull("Got message", received); + assertEquals("match", message.getJMSMessageID(), received.getJMSMessageID()); - @Test - public void verifyClientAckConsumptionOnDuplicate() throws Exception { + activeMQConnection.close(); + } - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerService.getTransportConnectors().get(0).getPublishableConnectString()); - connectionFactory.setCopyMessageOnSend(false); - connectionFactory.setWatchTopicAdvisories(false); + @Test + public void verifyClientAckConsumptionOnDuplicate() throws Exception { - ActiveMQConnection activeMQConnection = (ActiveMQConnection) connectionFactory.createConnection(); - activeMQConnection.start(); - ActiveMQSession activeMQSession = (ActiveMQSession) activeMQConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerService.getTransportConnectors().get(0).getPublishableConnectString()); + connectionFactory.setCopyMessageOnSend(false); + connectionFactory.setWatchTopicAdvisories(false); - ActiveMQQueue dest = new ActiveMQQueue("Q"); + ActiveMQConnection activeMQConnection = (ActiveMQConnection) connectionFactory.createConnection(); + activeMQConnection.start(); + ActiveMQSession activeMQSession = (ActiveMQSession) activeMQConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer messageConsumer = activeMQSession.createConsumer(dest); + ActiveMQQueue dest = new ActiveMQQueue("Q"); - ActiveMQMessageProducer activeMQMessageProducer = (ActiveMQMessageProducer) activeMQSession.createProducer(dest); - ActiveMQTextMessage message = new ActiveMQTextMessage(); - message.setDestination(dest); - activeMQMessageProducer.send(message, null); + MessageConsumer messageConsumer = activeMQSession.createConsumer(dest); - // send a duplicate - activeMQConnection.syncSendPacket(message); + ActiveMQMessageProducer activeMQMessageProducer = (ActiveMQMessageProducer) activeMQSession.createProducer(dest); + ActiveMQTextMessage message = new ActiveMQTextMessage(); + message.setDestination(dest); + activeMQMessageProducer.send(message, null); + // send a duplicate + activeMQConnection.syncSendPacket(message); - Message received = messageConsumer.receive(4000); - assertNotNull("Got message", received); - assertEquals("match", message.getJMSMessageID(), received.getJMSMessageID()); - messageConsumer.close(); + Message received = messageConsumer.receive(4000); + assertNotNull("Got message", received); + assertEquals("match", message.getJMSMessageID(), received.getJMSMessageID()); + messageConsumer.close(); + messageConsumer = activeMQSession.createConsumer(dest); + received = messageConsumer.receive(4000); + assertNotNull("Got message", received); + assertEquals("match", message.getJMSMessageID(), received.getJMSMessageID()); + received.acknowledge(); - messageConsumer = activeMQSession.createConsumer(dest); - received = messageConsumer.receive(4000); - assertNotNull("Got message", received); - assertEquals("match", message.getJMSMessageID(), received.getJMSMessageID()); - received.acknowledge(); - - activeMQConnection.close(); - } + activeMQConnection.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5266SingleDestTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5266SingleDestTest.java index ba7ee4dd4d..3adc8f1019 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5266SingleDestTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5266SingleDestTest.java @@ -32,6 +32,7 @@ import javax.jms.Queue; import javax.jms.QueueConnection; import javax.jms.Session; import javax.jms.TextMessage; + import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.RedeliveryPolicy; @@ -51,552 +52,564 @@ import org.junit.runners.Parameterized; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import static org.junit.Assert.assertEquals; /** - Non transactional concurrent producer/consumer to single dest + * Non transactional concurrent producer/consumer to single dest */ @RunWith(Parameterized.class) public class AMQ5266SingleDestTest { - static Logger LOG = LoggerFactory.getLogger(AMQ5266SingleDestTest.class); - String activemqURL; - BrokerService brokerService; - public int numDests = 1; - public int messageSize = 10*1000; + static Logger LOG = LoggerFactory.getLogger(AMQ5266SingleDestTest.class); + String activemqURL; + BrokerService brokerService; - @Parameterized.Parameter(0) - public int publisherMessagesPerThread = 1000; + public int numDests = 1; + public int messageSize = 10 * 1000; - @Parameterized.Parameter(1) - public int publisherThreadCount = 20; + @Parameterized.Parameter(0) + public int publisherMessagesPerThread = 1000; - @Parameterized.Parameter(2) - public int consumerThreadsPerQueue = 5; + @Parameterized.Parameter(1) + public int publisherThreadCount = 20; - @Parameterized.Parameter(3) - public int destMemoryLimit = 50 * 1024; + @Parameterized.Parameter(2) + public int consumerThreadsPerQueue = 5; - @Parameterized.Parameter(4) - public boolean useCache = true; + @Parameterized.Parameter(3) + public int destMemoryLimit = 50 * 1024; - @Parameterized.Parameter(5) - public TestSupport.PersistenceAdapterChoice persistenceAdapterChoice = TestSupport.PersistenceAdapterChoice.KahaDB; + @Parameterized.Parameter(4) + public boolean useCache = true; - @Parameterized.Parameter(6) - public boolean optimizeDispatch = false; + @Parameterized.Parameter(5) + public TestSupport.PersistenceAdapterChoice persistenceAdapterChoice = TestSupport.PersistenceAdapterChoice.KahaDB; - @Parameterized.Parameters(name="#{0},producerThreads:{1},consumerThreads:{2},mL:{3},useCache:{4},useDefaultStore:{5},optimizedDispatch:{6}") - public static Iterable parameters() { - return Arrays.asList(new Object[][]{ - {1000, 40, 40, 1024*1024*1, true, TestSupport.PersistenceAdapterChoice.KahaDB, false}, - {1000, 40, 40, 1024*1024*1, true, TestSupport.PersistenceAdapterChoice.LevelDB, false}, - {1000, 40, 40, 1024*1024*1, true, TestSupport.PersistenceAdapterChoice.JDBC, false}, - }); - } + @Parameterized.Parameter(6) + public boolean optimizeDispatch = false; - public int consumerBatchSize = 25; + @Parameterized.Parameters(name = "#{0},producerThreads:{1},consumerThreads:{2},mL:{3},useCache:{4},useDefaultStore:{5},optimizedDispatch:{6}") + public static Iterable parameters() { + return Arrays.asList(new Object[][]{{1000, 40, 40, 1024 * 1024 * 1, true, TestSupport.PersistenceAdapterChoice.KahaDB, false}, {1000, 40, 40, 1024 * 1024 * 1, true, TestSupport.PersistenceAdapterChoice.LevelDB, false}, {1000, 40, 40, 1024 * 1024 * 1, true, TestSupport.PersistenceAdapterChoice.JDBC, false},}); + } - @BeforeClass - public static void derbyTestMode() throws Exception { - System.setProperty("derby.system.durability","test"); - } + public int consumerBatchSize = 25; - @Before - public void startBroker() throws Exception { - brokerService = new BrokerService(); + @BeforeClass + public static void derbyTestMode() throws Exception { + System.setProperty("derby.system.durability", "test"); + } - TestSupport.setPersistenceAdapter(brokerService, persistenceAdapterChoice); - brokerService.setDeleteAllMessagesOnStartup(true); - brokerService.setUseJmx(false); - brokerService.setAdvisorySupport(false); + @Before + public void startBroker() throws Exception { + brokerService = new BrokerService(); + TestSupport.setPersistenceAdapter(brokerService, persistenceAdapterChoice); + brokerService.setDeleteAllMessagesOnStartup(true); + brokerService.setUseJmx(false); + brokerService.setAdvisorySupport(false); - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setUseConsumerPriority(false); // java.lang.IllegalArgumentException: Comparison method violates its general contract! - defaultEntry.setMaxProducersToAudit(publisherThreadCount); - defaultEntry.setEnableAudit(true); - defaultEntry.setUseCache(useCache); - defaultEntry.setMaxPageSize(1000); - defaultEntry.setOptimizedDispatch(optimizeDispatch); - defaultEntry.setMemoryLimit(destMemoryLimit); - defaultEntry.setExpireMessagesPeriod(0); - policyMap.setDefaultEntry(defaultEntry); - brokerService.setDestinationPolicy(policyMap); + PolicyMap policyMap = new PolicyMap(); + PolicyEntry defaultEntry = new PolicyEntry(); + defaultEntry.setUseConsumerPriority(false); // java.lang.IllegalArgumentException: Comparison method violates its general contract! + defaultEntry.setMaxProducersToAudit(publisherThreadCount); + defaultEntry.setEnableAudit(true); + defaultEntry.setUseCache(useCache); + defaultEntry.setMaxPageSize(1000); + defaultEntry.setOptimizedDispatch(optimizeDispatch); + defaultEntry.setMemoryLimit(destMemoryLimit); + defaultEntry.setExpireMessagesPeriod(0); + policyMap.setDefaultEntry(defaultEntry); + brokerService.setDestinationPolicy(policyMap); - brokerService.getSystemUsage().getMemoryUsage().setLimit(64 * 1024 * 1024); + brokerService.getSystemUsage().getMemoryUsage().setLimit(64 * 1024 * 1024); - TransportConnector transportConnector = brokerService.addConnector("tcp://0.0.0.0:0"); - brokerService.start(); - activemqURL = transportConnector.getPublishableConnectString(); - activemqURL += "?jms.watchTopicAdvisories=false"; // ensure all messages are queue or dlq messages - } + TransportConnector transportConnector = brokerService.addConnector("tcp://0.0.0.0:0"); + brokerService.start(); + activemqURL = transportConnector.getPublishableConnectString(); + activemqURL += "?jms.watchTopicAdvisories=false"; // ensure all messages are queue or dlq messages + } - @After - public void stopBroker() throws Exception { - if (brokerService != null) { - brokerService.stop(); - } - } + @After + public void stopBroker() throws Exception { + if (brokerService != null) { + brokerService.stop(); + } + } - @Test - public void test() throws Exception { + @Test + public void test() throws Exception { - String activemqQueues = "activemq"; - for (int i=1;i> entry : consumer.getIDs().entrySet()) { + + List idList = entry.getValue(); + + int distinctConsumed = new TreeSet(idList).size(); + + StringBuilder sb = new StringBuilder(); + sb.append(" Queue: " + entry.getKey() + + " -> Total Messages Consumed: " + idList.size() + + ", Distinct IDs Consumed: " + distinctConsumed); + + int diff = distinctPublishedCount - distinctConsumed; + sb.append(" ( " + (diff > 0 ? diff : "NO") + " STUCK MESSAGES " + " ) "); + LOG.info(sb.toString()); + + assertEquals("expect to get all messages!", 0, diff); + + } + + // verify empty dlq + assertEquals("No pending messages", 0L, ((RegionBroker) brokerService.getRegionBroker()).getDestinationStatistics().getMessages().getCount()); + } + + public class ExportQueuePublisher { + + private final String amqUser = ActiveMQConnection.DEFAULT_USER; + private final String amqPassword = ActiveMQConnection.DEFAULT_PASSWORD; + private ActiveMQConnectionFactory connectionFactory = null; + private String activemqURL = null; + private String activemqQueues = null; + // Collection of distinct IDs that the publisher has published. + // After a message is published, its UUID will be written to this list for tracking. + // This list of IDs (or distinct count) will be used to compare to the consumed list of IDs. + //private Set ids = Collections.synchronizedSet(new TreeSet()); + private List ids = Collections.synchronizedList(new ArrayList()); + private List threads; + + public ExportQueuePublisher(String activemqURL, + String activemqQueues, + int messagesPerThread, + int threadCount) throws Exception { + + this.activemqURL = activemqURL; + this.activemqQueues = activemqQueues; + + threads = new ArrayList(); + + // Build the threads and tell them how many messages to publish + for (int i = 0; i < threadCount; i++) { + PublisherThread pt = new PublisherThread(messagesPerThread); + threads.add(pt); + } + } + + public List getIDs() { + return ids; + } + + // Kick off threads + public void start() throws Exception { + + for (PublisherThread pt : threads) { + pt.start(); + } + } + + // Wait for threads to complete. They will complete once they've published all of their messages. + public void waitForCompletion() throws Exception { + + for (PublisherThread pt : threads) { + pt.join(); + pt.close(); + } + } + + private Session newSession(QueueConnection queueConnection) throws Exception { + return queueConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + } + + private synchronized QueueConnection newQueueConnection() throws Exception { + + if (connectionFactory == null) { + connectionFactory = new ActiveMQConnectionFactory(amqUser, amqPassword, activemqURL); + } + + // Set the redelivery count to -1 (infinite), or else messages will start dropping + // after the queue has had a certain number of failures (default is 6) + RedeliveryPolicy policy = connectionFactory.getRedeliveryPolicy(); + policy.setMaximumRedeliveries(-1); + + QueueConnection amqConnection = connectionFactory.createQueueConnection(); + amqConnection.start(); + return amqConnection; + } + + private class PublisherThread extends Thread { + + private int count; + private QueueConnection qc; + private Session session; + private MessageProducer mp; + + private PublisherThread(int count) throws Exception { + + this.count = count; + + // Each Thread has its own Connection and Session, so no sync worries + qc = newQueueConnection(); + session = newSession(qc); + + // In our code, when publishing to multiple queues, + // we're using composite destinations like below + Queue q = new ActiveMQQueue(activemqQueues); + mp = session.createProducer(q); + } + + public void run() { - long endWait = System.currentTimeMillis() + consumerWaitForConsumption; - while (!consumer.completed() && System.currentTimeMillis() < endWait) { try { - int secs = (int) (endWait - System.currentTimeMillis()) / 1000; - LOG.info("Waiting For Consumer Completion. Time left: " + secs + " secs"); - Thread.sleep(1000); - } catch (Exception e) { + + // Loop until we've published enough messages + while (count-- > 0) { + + TextMessage tm = session.createTextMessage(getMessageText()); + String id = UUID.randomUUID().toString(); + tm.setStringProperty("KEY", id); + ids.add(id); // keep track of the key to compare against consumer + + mp.send(tm); + } } - } - - LOG.info("\nConsumer Complete: " + consumer.completed() +", Shutting Down."); - - LOG.info("Total duration: {}", TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - totalStart)); - - consumer.shutdown(); - - TimeUnit.SECONDS.sleep(2); - - LOG.info("Consumer Stats:"); - - for (Map.Entry> entry : consumer.getIDs().entrySet()) { - - List idList = entry.getValue(); - - int distinctConsumed = new TreeSet(idList).size(); - - StringBuilder sb = new StringBuilder(); - sb.append(" Queue: " + entry.getKey() + - " -> Total Messages Consumed: " + idList.size() + - ", Distinct IDs Consumed: " + distinctConsumed); - - int diff = distinctPublishedCount - distinctConsumed; - sb.append(" ( " + (diff > 0 ? diff : "NO") + " STUCK MESSAGES " + " ) "); - LOG.info(sb.toString()); - - assertEquals("expect to get all messages!", 0, diff); - - } - - // verify empty dlq - assertEquals("No pending messages", 0L, ((RegionBroker) brokerService.getRegionBroker()).getDestinationStatistics().getMessages().getCount()); - } - - public class ExportQueuePublisher { - - private final String amqUser = ActiveMQConnection.DEFAULT_USER; - private final String amqPassword = ActiveMQConnection.DEFAULT_PASSWORD; - private ActiveMQConnectionFactory connectionFactory = null; - private String activemqURL = null; - private String activemqQueues = null; - // Collection of distinct IDs that the publisher has published. - // After a message is published, its UUID will be written to this list for tracking. - // This list of IDs (or distinct count) will be used to compare to the consumed list of IDs. - //private Set ids = Collections.synchronizedSet(new TreeSet()); - private List ids = Collections.synchronizedList(new ArrayList()); - private List threads; - - public ExportQueuePublisher(String activemqURL, String activemqQueues, int messagesPerThread, int threadCount) throws Exception { - - this.activemqURL = activemqURL; - this.activemqQueues = activemqQueues; - - threads = new ArrayList(); - - // Build the threads and tell them how many messages to publish - for (int i = 0; i < threadCount; i++) { - PublisherThread pt = new PublisherThread(messagesPerThread); - threads.add(pt); + catch (Exception e) { + e.printStackTrace(); } - } + } - public List getIDs() { - return ids; - } + // Called by waitForCompletion + public void close() { - // Kick off threads - public void start() throws Exception { - - for (PublisherThread pt : threads) { - pt.start(); + try { + mp.close(); } - } - - // Wait for threads to complete. They will complete once they've published all of their messages. - public void waitForCompletion() throws Exception { - - for (PublisherThread pt : threads) { - pt.join(); - pt.close(); - } - } - - private Session newSession(QueueConnection queueConnection) throws Exception { - return queueConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } - - private synchronized QueueConnection newQueueConnection() throws Exception { - - if (connectionFactory == null) { - connectionFactory = new ActiveMQConnectionFactory(amqUser, amqPassword, activemqURL); + catch (Exception e) { } - // Set the redelivery count to -1 (infinite), or else messages will start dropping - // after the queue has had a certain number of failures (default is 6) - RedeliveryPolicy policy = connectionFactory.getRedeliveryPolicy(); - policy.setMaximumRedeliveries(-1); - - QueueConnection amqConnection = connectionFactory.createQueueConnection(); - amqConnection.start(); - return amqConnection; - } - - private class PublisherThread extends Thread { - - private int count; - private QueueConnection qc; - private Session session; - private MessageProducer mp; - - private PublisherThread(int count) throws Exception { - - this.count = count; - - // Each Thread has its own Connection and Session, so no sync worries - qc = newQueueConnection(); - session = newSession(qc); - - // In our code, when publishing to multiple queues, - // we're using composite destinations like below - Queue q = new ActiveMQQueue(activemqQueues); - mp = session.createProducer(q); + try { + session.close(); + } + catch (Exception e) { } - public void run() { + try { + qc.close(); + } + catch (Exception e) { + } + } + } - try { + } - // Loop until we've published enough messages - while (count-- > 0) { + String messageText; - TextMessage tm = session.createTextMessage(getMessageText()); - String id = UUID.randomUUID().toString(); - tm.setStringProperty("KEY", id); - ids.add(id); // keep track of the key to compare against consumer + private String getMessageText() { - mp.send(tm); - } - } catch (Exception e) { - e.printStackTrace(); - } + if (messageText == null) { + + synchronized (this) { + + if (messageText == null) { + + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < messageSize; i++) { + sb.append("X"); + } + messageText = sb.toString(); + } + } + } + + return messageText; + } + + public class ExportQueueConsumer { + + private final String amqUser = ActiveMQConnection.DEFAULT_USER; + private final String amqPassword = ActiveMQConnection.DEFAULT_PASSWORD; + private final int totalToExpect; + private ActiveMQConnectionFactory connectionFactory = null; + private String activemqURL = null; + private String activemqQueues = null; + private String[] queues = null; + // Map of IDs that were consumed, keyed by queue name. + // We'll compare these against what was published to know if any got stuck or dropped. + private Map> idsByQueue = new HashMap>(); + private Map> threads; + + public ExportQueueConsumer(String activemqURL, + String activemqQueues, + int threadsPerQueue, + int batchSize, + int totalToExpect) throws Exception { + + this.activemqURL = activemqURL; + this.activemqQueues = activemqQueues; + this.totalToExpect = totalToExpect; + + queues = this.activemqQueues.split(","); + + for (int i = 0; i < queues.length; i++) { + queues[i] = queues[i].trim(); + } + + threads = new HashMap>(); + + // For each queue, create a list of threads and set up the list of ids + for (String q : queues) { + + List list = new ArrayList(); + + idsByQueue.put(q, Collections.synchronizedList(new ArrayList())); + + for (int i = 0; i < threadsPerQueue; i++) { + list.add(new ConsumerThread(q, batchSize)); } - // Called by waitForCompletion - public void close() { + threads.put(q, list); + } + } - try { - mp.close(); - } catch (Exception e) { - } + public Map> getIDs() { + return idsByQueue; + } - try { - session.close(); - } catch (Exception e) { - } + // Start the threads + public void start() throws Exception { - try { - qc.close(); - } catch (Exception e) { - } + for (List list : threads.values()) { + + for (ConsumerThread ct : list) { + + ct.start(); } - } + } + } - } + // Tell the threads to stop + // Then wait for them to stop + public void shutdown() throws Exception { - String messageText; - private String getMessageText() { + for (List list : threads.values()) { - if (messageText == null) { + for (ConsumerThread ct : list) { - synchronized (this) { - - if (messageText == null) { - - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < messageSize; i++) { - sb.append("X"); - } - messageText = sb.toString(); - } + ct.shutdown(); } - } + } - return messageText; - } + for (List list : threads.values()) { + for (ConsumerThread ct : list) { - public class ExportQueueConsumer { - - private final String amqUser = ActiveMQConnection.DEFAULT_USER; - private final String amqPassword = ActiveMQConnection.DEFAULT_PASSWORD; - private final int totalToExpect; - private ActiveMQConnectionFactory connectionFactory = null; - private String activemqURL = null; - private String activemqQueues = null; - private String[] queues = null; - // Map of IDs that were consumed, keyed by queue name. - // We'll compare these against what was published to know if any got stuck or dropped. - private Map> idsByQueue = new HashMap>(); - private Map> threads; - - public ExportQueueConsumer(String activemqURL, String activemqQueues, int threadsPerQueue, int batchSize, int totalToExpect) throws Exception { - - this.activemqURL = activemqURL; - this.activemqQueues = activemqQueues; - this.totalToExpect = totalToExpect; - - queues = this.activemqQueues.split(","); - - for (int i = 0; i < queues.length; i++) { - queues[i] = queues[i].trim(); + ct.join(); } + } + } - threads = new HashMap>(); + private Session newSession(QueueConnection queueConnection) throws Exception { + return queueConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + } - // For each queue, create a list of threads and set up the list of ids - for (String q : queues) { + private synchronized QueueConnection newQueueConnection() throws Exception { - List list = new ArrayList(); + if (connectionFactory == null) { + connectionFactory = new ActiveMQConnectionFactory(amqUser, amqPassword, activemqURL); + } - idsByQueue.put(q, Collections.synchronizedList(new ArrayList())); + // Set the redelivery count to -1 (infinite), or else messages will start dropping + // after the queue has had a certain number of failures (default is 6) + RedeliveryPolicy policy = connectionFactory.getRedeliveryPolicy(); + policy.setMaximumRedeliveries(-1); - for (int i = 0; i < threadsPerQueue; i++) { - list.add(new ConsumerThread(q, batchSize)); - } + QueueConnection amqConnection = connectionFactory.createQueueConnection(); + amqConnection.start(); + return amqConnection; + } - threads.put(q, list); + public boolean completed() { + for (List list : threads.values()) { + + for (ConsumerThread ct : list) { + + if (ct.isAlive()) { + LOG.info("thread for {} is still alive.", ct.qName); + return false; + } } - } + } + return true; + } - public Map> getIDs() { - return idsByQueue; - } + private class ConsumerThread extends Thread { - // Start the threads - public void start() throws Exception { + private int batchSize; + private QueueConnection qc; + private Session session; + private MessageConsumer mc; + private List idList; + private boolean shutdown = false; + private String qName; - for (List list : threads.values()) { + private ConsumerThread(String queueName, int batchSize) throws Exception { - for (ConsumerThread ct : list) { + this.batchSize = batchSize; - ct.start(); - } - } - } + // Each thread has its own connection and session + qName = queueName; + qc = newQueueConnection(); + session = newSession(qc); + Queue q = session.createQueue(queueName + "?consumer.prefetchSize=" + batchSize); + mc = session.createConsumer(q); - // Tell the threads to stop - // Then wait for them to stop - public void shutdown() throws Exception { + idList = idsByQueue.get(queueName); + } - for (List list : threads.values()) { + public void run() { - for (ConsumerThread ct : list) { + try { - ct.shutdown(); - } - } + int count = 0; - for (List list : threads.values()) { + // Keep reading as long as it hasn't been told to shutdown + while (!shutdown) { - for (ConsumerThread ct : list) { + if (idList.size() >= totalToExpect) { + LOG.info("Got {} for q: {}", +idList.size(), qName); + break; + } + Message m = mc.receive(4000); - ct.join(); - } - } - } + if (m != null) { - private Session newSession(QueueConnection queueConnection) throws Exception { - return queueConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } + // We received a non-null message, add the ID to our list - private synchronized QueueConnection newQueueConnection() throws Exception { + idList.add(m.getStringProperty("KEY")); - if (connectionFactory == null) { - connectionFactory = new ActiveMQConnectionFactory(amqUser, amqPassword, activemqURL); - } + count++; - // Set the redelivery count to -1 (infinite), or else messages will start dropping - // after the queue has had a certain number of failures (default is 6) - RedeliveryPolicy policy = connectionFactory.getRedeliveryPolicy(); - policy.setMaximumRedeliveries(-1); + // If we've reached our batch size, commit the batch and reset the count - QueueConnection amqConnection = connectionFactory.createQueueConnection(); - amqConnection.start(); - return amqConnection; - } + if (count == batchSize) { + count = 0; + } + } + else { - public boolean completed() { - for (List list : threads.values()) { + // We didn't receive anything this time, commit any current batch and reset the count - for (ConsumerThread ct : list) { + count = 0; - if (ct.isAlive()) { - LOG.info("thread for {} is still alive.", ct.qName); - return false; - } - } - } - return true; - } + // Sleep a little before trying to read after not getting a message - private class ConsumerThread extends Thread { - - private int batchSize; - private QueueConnection qc; - private Session session; - private MessageConsumer mc; - private List idList; - private boolean shutdown = false; - private String qName; - - private ConsumerThread(String queueName, int batchSize) throws Exception { - - this.batchSize = batchSize; - - // Each thread has its own connection and session - qName = queueName; - qc = newQueueConnection(); - session = newSession(qc); - Queue q = session.createQueue(queueName + "?consumer.prefetchSize=" + batchSize); - mc = session.createConsumer(q); - - idList = idsByQueue.get(queueName); - } - - public void run() { - - try { - - int count = 0; - - // Keep reading as long as it hasn't been told to shutdown - while (!shutdown) { - - if (idList.size() >= totalToExpect) { - LOG.info("Got {} for q: {}", +idList.size(), qName); - break; + try { + if (idList.size() < totalToExpect) { + LOG.info("did not receive on {}, current count: {}", qName, idList.size()); } - Message m = mc.receive(4000); + //sleep(3000); + } + catch (Exception e) { + } + } + } + } + catch (Exception e) { + e.printStackTrace(); + } + finally { - if (m != null) { + // Once we exit, close everything + close(); + } + } - // We received a non-null message, add the ID to our list + public void shutdown() { + shutdown = true; + } - idList.add(m.getStringProperty("KEY")); + public void close() { - count++; - - // If we've reached our batch size, commit the batch and reset the count - - if (count == batchSize) { - count = 0; - } - } else { - - // We didn't receive anything this time, commit any current batch and reset the count - - count = 0; - - // Sleep a little before trying to read after not getting a message - - try { - if (idList.size() < totalToExpect) { - LOG.info("did not receive on {}, current count: {}", qName, idList.size()); - } - //sleep(3000); - } catch (Exception e) { - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - - // Once we exit, close everything - close(); - } + try { + mc.close(); + } + catch (Exception e) { } - public void shutdown() { - shutdown = true; + try { + session.close(); + } + catch (Exception e) { } - public void close() { - - try { - mc.close(); - } catch (Exception e) { - } - - try { - session.close(); - } catch (Exception e) { - } - - try { - qc.close(); - } catch (Exception e) { - - } + try { + qc.close(); } - } - } + catch (Exception e) { + + } + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5266StarvedConsumerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5266StarvedConsumerTest.java index f7409dd619..0c1d6a492e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5266StarvedConsumerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5266StarvedConsumerTest.java @@ -34,6 +34,7 @@ import javax.jms.Queue; import javax.jms.QueueConnection; import javax.jms.Session; import javax.jms.TextMessage; + import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.RedeliveryPolicy; @@ -56,7 +57,6 @@ import org.junit.runners.Parameterized; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import static org.junit.Assert.assertEquals; /* @@ -64,557 +64,567 @@ import static org.junit.Assert.assertEquals; */ @RunWith(Parameterized.class) public class AMQ5266StarvedConsumerTest { - static Logger LOG = LoggerFactory.getLogger(AMQ5266StarvedConsumerTest.class); - String activemqURL; - BrokerService brokerService; - public int messageSize = 1000; + static Logger LOG = LoggerFactory.getLogger(AMQ5266StarvedConsumerTest.class); + String activemqURL; + BrokerService brokerService; - @Parameterized.Parameter(0) - public int publisherMessagesPerThread = 1000; + public int messageSize = 1000; - @Parameterized.Parameter(1) - public int publisherThreadCount = 20; + @Parameterized.Parameter(0) + public int publisherMessagesPerThread = 1000; - @Parameterized.Parameter(2) - public int consumerThreadsPerQueue = 5; + @Parameterized.Parameter(1) + public int publisherThreadCount = 20; - @Parameterized.Parameter(3) - public int destMemoryLimit = 50 * 1024; + @Parameterized.Parameter(2) + public int consumerThreadsPerQueue = 5; - @Parameterized.Parameter(4) - public boolean useCache = true; + @Parameterized.Parameter(3) + public int destMemoryLimit = 50 * 1024; - @Parameterized.Parameter(5) - public TestSupport.PersistenceAdapterChoice persistenceAdapterChoice = TestSupport.PersistenceAdapterChoice.KahaDB; + @Parameterized.Parameter(4) + public boolean useCache = true; - @Parameterized.Parameter(6) - public boolean optimizeDispatch = false; - private AtomicBoolean didNotReceive = new AtomicBoolean(false); + @Parameterized.Parameter(5) + public TestSupport.PersistenceAdapterChoice persistenceAdapterChoice = TestSupport.PersistenceAdapterChoice.KahaDB; - @Parameterized.Parameters(name="#{0},producerThreads:{1},consumerThreads:{2},mL:{3},useCache:{4},store:{5},optimizedDispatch:{6}") - public static Iterable parameters() { - return Arrays.asList(new Object[][]{ - {1000, 40, 5, 1024*1024, false, TestSupport.PersistenceAdapterChoice.KahaDB, true}, - {1000, 40, 5, 1024*1024, false, TestSupport.PersistenceAdapterChoice.LevelDB, true}, - {1000, 40, 5, 1024*1024, false, TestSupport.PersistenceAdapterChoice.JDBC, true}, + @Parameterized.Parameter(6) + public boolean optimizeDispatch = false; + private AtomicBoolean didNotReceive = new AtomicBoolean(false); - {500, 20, 20, 1024*1024, false, TestSupport.PersistenceAdapterChoice.KahaDB, true}, - {500, 20, 20, 1024*1024, false, TestSupport.PersistenceAdapterChoice.LevelDB, true}, - {500, 20, 20, 1024*1024, false, TestSupport.PersistenceAdapterChoice.JDBC, true}, - }); - } + @Parameterized.Parameters(name = "#{0},producerThreads:{1},consumerThreads:{2},mL:{3},useCache:{4},store:{5},optimizedDispatch:{6}") + public static Iterable parameters() { + return Arrays.asList(new Object[][]{{1000, 40, 5, 1024 * 1024, false, TestSupport.PersistenceAdapterChoice.KahaDB, true}, {1000, 40, 5, 1024 * 1024, false, TestSupport.PersistenceAdapterChoice.LevelDB, true}, {1000, 40, 5, 1024 * 1024, false, TestSupport.PersistenceAdapterChoice.JDBC, true}, - public int consumerBatchSize = 5; + {500, 20, 20, 1024 * 1024, false, TestSupport.PersistenceAdapterChoice.KahaDB, true}, {500, 20, 20, 1024 * 1024, false, TestSupport.PersistenceAdapterChoice.LevelDB, true}, {500, 20, 20, 1024 * 1024, false, TestSupport.PersistenceAdapterChoice.JDBC, true},}); + } - @Before - public void startBroker() throws Exception { - brokerService = new BrokerService(); - TestSupport.setPersistenceAdapter(brokerService, persistenceAdapterChoice); - brokerService.setDeleteAllMessagesOnStartup(true); - brokerService.setUseJmx(false); - brokerService.setAdvisorySupport(false); + public int consumerBatchSize = 5; + @Before + public void startBroker() throws Exception { + brokerService = new BrokerService(); + TestSupport.setPersistenceAdapter(brokerService, persistenceAdapterChoice); + brokerService.setDeleteAllMessagesOnStartup(true); + brokerService.setUseJmx(false); + brokerService.setAdvisorySupport(false); - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setUseConsumerPriority(false); // java.lang.IllegalArgumentException: Comparison method violates its general contract! - defaultEntry.setMaxAuditDepth(publisherThreadCount); - defaultEntry.setEnableAudit(true); - defaultEntry.setUseCache(useCache); - defaultEntry.setMaxPageSize(1000); - defaultEntry.setOptimizedDispatch(optimizeDispatch); - defaultEntry.setMemoryLimit(destMemoryLimit); - defaultEntry.setExpireMessagesPeriod(0); - policyMap.setDefaultEntry(defaultEntry); - brokerService.setDestinationPolicy(policyMap); + PolicyMap policyMap = new PolicyMap(); + PolicyEntry defaultEntry = new PolicyEntry(); + defaultEntry.setUseConsumerPriority(false); // java.lang.IllegalArgumentException: Comparison method violates its general contract! + defaultEntry.setMaxAuditDepth(publisherThreadCount); + defaultEntry.setEnableAudit(true); + defaultEntry.setUseCache(useCache); + defaultEntry.setMaxPageSize(1000); + defaultEntry.setOptimizedDispatch(optimizeDispatch); + defaultEntry.setMemoryLimit(destMemoryLimit); + defaultEntry.setExpireMessagesPeriod(0); + policyMap.setDefaultEntry(defaultEntry); + brokerService.setDestinationPolicy(policyMap); - brokerService.getSystemUsage().getMemoryUsage().setLimit(512 * 1024 * 1024); + brokerService.getSystemUsage().getMemoryUsage().setLimit(512 * 1024 * 1024); - TransportConnector transportConnector = brokerService.addConnector("tcp://0.0.0.0:0"); - brokerService.start(); - activemqURL = transportConnector.getPublishableConnectString(); - } + TransportConnector transportConnector = brokerService.addConnector("tcp://0.0.0.0:0"); + brokerService.start(); + activemqURL = transportConnector.getPublishableConnectString(); + } - @After - public void stopBroker() throws Exception { - if (brokerService != null) { - brokerService.stop(); - } - } + @After + public void stopBroker() throws Exception { + if (brokerService != null) { + brokerService.stop(); + } + } + + CyclicBarrier globalProducerHalt = new CyclicBarrier(publisherThreadCount, new Runnable() { + @Override + public void run() { + // wait for queue size to go to zero + try { + while (((RegionBroker) brokerService.getRegionBroker()).getDestinationStatistics().getMessages().getCount() > 0) { + LOG.info("Total messageCount: " + ((RegionBroker) brokerService.getRegionBroker()).getDestinationStatistics().getMessages().getCount()); + TimeUnit.SECONDS.sleep(5); + } + } + catch (Exception ignored) { + ignored.printStackTrace(); + } + } + }); + + @Test(timeout = 30 * 60 * 1000) + public void test() throws Exception { + + String activemqQueues = "activemq,activemq2,activemq3,activemq4";//,activemq5,activemq6,activemq7,activemq8,activemq9"; + + int consumerWaitForConsumption = 5 * 60 * 1000; + + ExportQueuePublisher publisher = null; + ExportQueueConsumer consumer = null; + + LOG.info("Publisher will publish " + (publisherMessagesPerThread * publisherThreadCount) + " messages to each queue specified."); + LOG.info("\nBuilding Publisher..."); + + publisher = new ExportQueuePublisher(activemqURL, activemqQueues, publisherMessagesPerThread, publisherThreadCount); + + LOG.info("Building Consumer..."); + + consumer = new ExportQueueConsumer(activemqURL, activemqQueues, consumerThreadsPerQueue, consumerBatchSize, publisherMessagesPerThread * publisherThreadCount); + + LOG.info("Starting Publisher..."); + + publisher.start(); + + LOG.info("Starting Consumer..."); + + consumer.start(); + + int distinctPublishedCount = 0; + + LOG.info("Waiting For Publisher Completion..."); + + publisher.waitForCompletion(); + + List publishedIds = publisher.getIDs(); + distinctPublishedCount = new TreeSet(publishedIds).size(); + + LOG.info("Publisher Complete. Published: " + publishedIds.size() + ", Distinct IDs Published: " + distinctPublishedCount); + + long endWait = System.currentTimeMillis() + consumerWaitForConsumption; + while (!consumer.completed() && System.currentTimeMillis() < endWait) { + try { + int secs = (int) (endWait - System.currentTimeMillis()) / 1000; + LOG.info("Waiting For Consumer Completion. Time left: " + secs + " secs"); + Thread.sleep(10000); + } + catch (Exception e) { + } + } + + LOG.info("\nConsumer Complete: " + consumer.completed() + ", Shutting Down."); + + consumer.shutdown(); + + LOG.info("Consumer Stats:"); + + for (Map.Entry> entry : consumer.getIDs().entrySet()) { + + List idList = entry.getValue(); + + int distinctConsumed = new TreeSet(idList).size(); + + StringBuilder sb = new StringBuilder(); + sb.append(" Queue: " + entry.getKey() + + " -> Total Messages Consumed: " + idList.size() + + ", Distinct IDs Consumed: " + distinctConsumed); + + int diff = distinctPublishedCount - distinctConsumed; + sb.append(" ( " + (diff > 0 ? diff : "NO") + " STUCK MESSAGES " + " ) "); + LOG.info(sb.toString()); + + assertEquals("expect to get all messages!", 0, diff); + + } + } + + public class ExportQueuePublisher { + + private final String amqUser = ActiveMQConnection.DEFAULT_USER; + private final String amqPassword = ActiveMQConnection.DEFAULT_PASSWORD; + private ActiveMQConnectionFactory connectionFactory = null; + private String activemqURL = null; + private String activemqQueues = null; + // Collection of distinct IDs that the publisher has published. + // After a message is published, its UUID will be written to this list for tracking. + // This list of IDs (or distinct count) will be used to compare to the consumed list of IDs. + //private Set ids = Collections.synchronizedSet(new TreeSet()); + private List ids = Collections.synchronizedList(new ArrayList()); + private List threads; + + public ExportQueuePublisher(String activemqURL, + String activemqQueues, + int messagesPerThread, + int threadCount) throws Exception { + + this.activemqURL = activemqURL; + this.activemqQueues = activemqQueues; + + threads = new ArrayList(); + + // Build the threads and tell them how many messages to publish + for (int i = 0; i < threadCount; i++) { + PublisherThread pt = new PublisherThread(messagesPerThread); + threads.add(pt); + } + } + + public List getIDs() { + return ids; + } + + // Kick off threads + public void start() throws Exception { + + for (PublisherThread pt : threads) { + pt.start(); + } + } + + // Wait for threads to complete. They will complete once they've published all of their messages. + public void waitForCompletion() throws Exception { + + for (PublisherThread pt : threads) { + pt.join(); + pt.close(); + } + } + + private Session newSession(QueueConnection queueConnection) throws Exception { + return queueConnection.createSession(true, Session.SESSION_TRANSACTED); + } + + private synchronized QueueConnection newQueueConnection() throws Exception { + + if (connectionFactory == null) { + connectionFactory = new ActiveMQConnectionFactory(amqUser, amqPassword, activemqURL); + connectionFactory.setWatchTopicAdvisories(false); + } + + // Set the redelivery count to -1 (infinite), or else messages will start dropping + // after the queue has had a certain number of failures (default is 6) + RedeliveryPolicy policy = connectionFactory.getRedeliveryPolicy(); + policy.setMaximumRedeliveries(-1); + + QueueConnection amqConnection = connectionFactory.createQueueConnection(); + amqConnection.start(); + return amqConnection; + } + + private class PublisherThread extends Thread { + + private int count; + private QueueConnection qc; + private Session session; + private MessageProducer mp; + private Queue q; + + private PublisherThread(int count) throws Exception { + + this.count = count; + + // Each Thread has its own Connection and Session, so no sync worries + qc = newQueueConnection(); + session = newSession(qc); + + // In our code, when publishing to multiple queues, + // we're using composite destinations like below + q = new ActiveMQQueue(activemqQueues); + mp = session.createProducer(null); + } + + public void run() { - CyclicBarrier globalProducerHalt = new CyclicBarrier(publisherThreadCount, new Runnable() { - @Override - public void run() { - // wait for queue size to go to zero try { - while (((RegionBroker)brokerService.getRegionBroker()).getDestinationStatistics().getMessages().getCount() > 0) { - LOG.info("Total messageCount: " + ((RegionBroker)brokerService.getRegionBroker()).getDestinationStatistics().getMessages().getCount()); - TimeUnit.SECONDS.sleep(5); - } - } catch (Exception ignored) { - ignored.printStackTrace(); + + // Loop until we've published enough messages + while (count-- > 0) { + + TextMessage tm = session.createTextMessage(getMessageText()); + String id = UUID.randomUUID().toString(); + tm.setStringProperty("KEY", id); + ids.add(id); // keep track of the key to compare against consumer + + mp.send(q, tm); + session.commit(); + + if (didNotReceive.get()) { + globalProducerHalt.await(); + } + } } - } - }); + catch (Exception e) { + e.printStackTrace(); + } + } - @Test(timeout = 30 * 60 * 1000) - public void test() throws Exception { + // Called by waitForCompletion + public void close() { - String activemqQueues = "activemq,activemq2,activemq3,activemq4";//,activemq5,activemq6,activemq7,activemq8,activemq9"; - - int consumerWaitForConsumption = 5 * 60 * 1000; - - ExportQueuePublisher publisher = null; - ExportQueueConsumer consumer = null; - - LOG.info("Publisher will publish " + (publisherMessagesPerThread * publisherThreadCount) + " messages to each queue specified."); - LOG.info("\nBuilding Publisher..."); - - publisher = new ExportQueuePublisher(activemqURL, activemqQueues, publisherMessagesPerThread, publisherThreadCount); - - LOG.info("Building Consumer..."); - - consumer = new ExportQueueConsumer(activemqURL, activemqQueues, consumerThreadsPerQueue, consumerBatchSize, publisherMessagesPerThread * publisherThreadCount); - - - LOG.info("Starting Publisher..."); - - publisher.start(); - - LOG.info("Starting Consumer..."); - - consumer.start(); - - int distinctPublishedCount = 0; - - - LOG.info("Waiting For Publisher Completion..."); - - publisher.waitForCompletion(); - - List publishedIds = publisher.getIDs(); - distinctPublishedCount = new TreeSet(publishedIds).size(); - - LOG.info("Publisher Complete. Published: " + publishedIds.size() + ", Distinct IDs Published: " + distinctPublishedCount); - - - long endWait = System.currentTimeMillis() + consumerWaitForConsumption; - while (!consumer.completed() && System.currentTimeMillis() < endWait) { try { - int secs = (int) (endWait - System.currentTimeMillis()) / 1000; - LOG.info("Waiting For Consumer Completion. Time left: " + secs + " secs"); - Thread.sleep(10000); - } catch (Exception e) { + mp.close(); } - } - - LOG.info("\nConsumer Complete: " + consumer.completed() +", Shutting Down."); - - consumer.shutdown(); - - - LOG.info("Consumer Stats:"); - - for (Map.Entry> entry : consumer.getIDs().entrySet()) { - - List idList = entry.getValue(); - - int distinctConsumed = new TreeSet(idList).size(); - - StringBuilder sb = new StringBuilder(); - sb.append(" Queue: " + entry.getKey() + - " -> Total Messages Consumed: " + idList.size() + - ", Distinct IDs Consumed: " + distinctConsumed); - - int diff = distinctPublishedCount - distinctConsumed; - sb.append(" ( " + (diff > 0 ? diff : "NO") + " STUCK MESSAGES " + " ) "); - LOG.info(sb.toString()); - - assertEquals("expect to get all messages!", 0, diff); - - } - } - - public class ExportQueuePublisher { - - private final String amqUser = ActiveMQConnection.DEFAULT_USER; - private final String amqPassword = ActiveMQConnection.DEFAULT_PASSWORD; - private ActiveMQConnectionFactory connectionFactory = null; - private String activemqURL = null; - private String activemqQueues = null; - // Collection of distinct IDs that the publisher has published. - // After a message is published, its UUID will be written to this list for tracking. - // This list of IDs (or distinct count) will be used to compare to the consumed list of IDs. - //private Set ids = Collections.synchronizedSet(new TreeSet()); - private List ids = Collections.synchronizedList(new ArrayList()); - private List threads; - - public ExportQueuePublisher(String activemqURL, String activemqQueues, int messagesPerThread, int threadCount) throws Exception { - - this.activemqURL = activemqURL; - this.activemqQueues = activemqQueues; - - threads = new ArrayList(); - - // Build the threads and tell them how many messages to publish - for (int i = 0; i < threadCount; i++) { - PublisherThread pt = new PublisherThread(messagesPerThread); - threads.add(pt); - } - } - - public List getIDs() { - return ids; - } - - // Kick off threads - public void start() throws Exception { - - for (PublisherThread pt : threads) { - pt.start(); - } - } - - // Wait for threads to complete. They will complete once they've published all of their messages. - public void waitForCompletion() throws Exception { - - for (PublisherThread pt : threads) { - pt.join(); - pt.close(); - } - } - - private Session newSession(QueueConnection queueConnection) throws Exception { - return queueConnection.createSession(true, Session.SESSION_TRANSACTED); - } - - private synchronized QueueConnection newQueueConnection() throws Exception { - - if (connectionFactory == null) { - connectionFactory = new ActiveMQConnectionFactory(amqUser, amqPassword, activemqURL); - connectionFactory.setWatchTopicAdvisories(false); + catch (Exception e) { } - // Set the redelivery count to -1 (infinite), or else messages will start dropping - // after the queue has had a certain number of failures (default is 6) - RedeliveryPolicy policy = connectionFactory.getRedeliveryPolicy(); - policy.setMaximumRedeliveries(-1); - - QueueConnection amqConnection = connectionFactory.createQueueConnection(); - amqConnection.start(); - return amqConnection; - } - - private class PublisherThread extends Thread { - - private int count; - private QueueConnection qc; - private Session session; - private MessageProducer mp; - private Queue q; - - private PublisherThread(int count) throws Exception { - - this.count = count; - - // Each Thread has its own Connection and Session, so no sync worries - qc = newQueueConnection(); - session = newSession(qc); - - // In our code, when publishing to multiple queues, - // we're using composite destinations like below - q = new ActiveMQQueue(activemqQueues); - mp = session.createProducer(null); + try { + session.close(); + } + catch (Exception e) { } - public void run() { + try { + qc.close(); + } + catch (Exception e) { + } + } + } - try { + } - // Loop until we've published enough messages - while (count-- > 0) { + String messageText; - TextMessage tm = session.createTextMessage(getMessageText()); - String id = UUID.randomUUID().toString(); - tm.setStringProperty("KEY", id); - ids.add(id); // keep track of the key to compare against consumer + private String getMessageText() { - mp.send(q, tm); + if (messageText == null) { + + synchronized (this) { + + if (messageText == null) { + + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < messageSize; i++) { + sb.append("X"); + } + messageText = sb.toString(); + } + } + } + + return messageText; + } + + public class ExportQueueConsumer { + + private final String amqUser = ActiveMQConnection.DEFAULT_USER; + private final String amqPassword = ActiveMQConnection.DEFAULT_PASSWORD; + private final int totalToExpect; + private ActiveMQConnectionFactory connectionFactory = null; + private String activemqURL = null; + private String activemqQueues = null; + private String[] queues = null; + // Map of IDs that were consumed, keyed by queue name. + // We'll compare these against what was published to know if any got stuck or dropped. + private Map> idsByQueue = new HashMap>(); + private Map> threads; + + public ExportQueueConsumer(String activemqURL, + String activemqQueues, + int threadsPerQueue, + int batchSize, + int totalToExpect) throws Exception { + + this.activemqURL = activemqURL; + this.activemqQueues = activemqQueues; + this.totalToExpect = totalToExpect; + + queues = this.activemqQueues.split(","); + + for (int i = 0; i < queues.length; i++) { + queues[i] = queues[i].trim(); + } + + threads = new HashMap>(); + + // For each queue, create a list of threads and set up the list of ids + for (String q : queues) { + + List list = new ArrayList(); + + idsByQueue.put(q, Collections.synchronizedList(new ArrayList())); + + for (int i = 0; i < threadsPerQueue; i++) { + list.add(new ConsumerThread(q, batchSize)); + } + + threads.put(q, list); + } + } + + public Map> getIDs() { + return idsByQueue; + } + + // Start the threads + public void start() throws Exception { + + for (List list : threads.values()) { + + for (ConsumerThread ct : list) { + + ct.start(); + } + } + } + + // Tell the threads to stop + // Then wait for them to stop + public void shutdown() throws Exception { + + for (List list : threads.values()) { + + for (ConsumerThread ct : list) { + + ct.shutdown(); + } + } + + for (List list : threads.values()) { + + for (ConsumerThread ct : list) { + + ct.join(); + } + } + } + + private Session newSession(QueueConnection queueConnection) throws Exception { + return queueConnection.createSession(true, Session.SESSION_TRANSACTED); + } + + private synchronized QueueConnection newQueueConnection() throws Exception { + + if (connectionFactory == null) { + connectionFactory = new ActiveMQConnectionFactory(amqUser, amqPassword, activemqURL); + connectionFactory.setWatchTopicAdvisories(false); + } + + // Set the redelivery count to -1 (infinite), or else messages will start dropping + // after the queue has had a certain number of failures (default is 6) + RedeliveryPolicy policy = connectionFactory.getRedeliveryPolicy(); + policy.setMaximumRedeliveries(-1); + + QueueConnection amqConnection = connectionFactory.createQueueConnection(); + amqConnection.start(); + return amqConnection; + } + + public boolean completed() { + for (List list : threads.values()) { + + for (ConsumerThread ct : list) { + + if (ct.isAlive()) { + LOG.info("thread for {} is still alive.", ct.qName); + return false; + } + } + } + return true; + } + + private class ConsumerThread extends Thread { + + private int batchSize; + private QueueConnection qc; + private Session session; + private MessageConsumer mc; + private List idList; + private boolean shutdown = false; + private String qName; + + private ConsumerThread(String queueName, int batchSize) throws Exception { + + this.batchSize = batchSize; + + // Each thread has its own connection and session + qName = queueName; + qc = newQueueConnection(); + session = newSession(qc); + Queue q = session.createQueue(queueName + "?consumer.prefetchSize=" + batchSize); + mc = session.createConsumer(q); + + idList = idsByQueue.get(queueName); + } + + public void run() { + + try { + + int count = 0; + + // Keep reading as long as it hasn't been told to shutdown + while (!shutdown) { + + if (idList.size() >= totalToExpect) { + LOG.info("Got {} for q: {}", +idList.size(), qName); + session.commit(); + break; + } + Message m = mc.receive(4000); + + if (m != null) { + + // We received a non-null message, add the ID to our list + + idList.add(m.getStringProperty("KEY")); + + count++; + + // If we've reached our batch size, commit the batch and reset the count + + if (count == batchSize) { session.commit(); + count = 0; + } + } + else { - if (didNotReceive.get()) { - globalProducerHalt.await(); + // We didn't receive anything this time, commit any current batch and reset the count + + session.commit(); + count = 0; + + // Sleep a little before trying to read after not getting a message + + try { + if (idList.size() < totalToExpect) { + LOG.info("did not receive on {}, current count: {}", qName, idList.size()); + didNotReceive.set(true); } - } - } catch (Exception e) { - e.printStackTrace(); - } + //sleep(3000); + } + catch (Exception e) { + } + } + } + } + catch (Exception e) { + e.printStackTrace(); + } + finally { + + // Once we exit, close everything + close(); + } + } + + public void shutdown() { + shutdown = true; + } + + public void close() { + + try { + mc.close(); + } + catch (Exception e) { } - // Called by waitForCompletion - public void close() { - - try { - mp.close(); - } catch (Exception e) { - } - - try { - session.close(); - } catch (Exception e) { - } - - try { - qc.close(); - } catch (Exception e) { - } + try { + session.close(); } - } - - } - - String messageText; - private String getMessageText() { - - if (messageText == null) { - - synchronized (this) { - - if (messageText == null) { - - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < messageSize; i++) { - sb.append("X"); - } - messageText = sb.toString(); - } - } - } - - return messageText; - } - - - public class ExportQueueConsumer { - - private final String amqUser = ActiveMQConnection.DEFAULT_USER; - private final String amqPassword = ActiveMQConnection.DEFAULT_PASSWORD; - private final int totalToExpect; - private ActiveMQConnectionFactory connectionFactory = null; - private String activemqURL = null; - private String activemqQueues = null; - private String[] queues = null; - // Map of IDs that were consumed, keyed by queue name. - // We'll compare these against what was published to know if any got stuck or dropped. - private Map> idsByQueue = new HashMap>(); - private Map> threads; - - public ExportQueueConsumer(String activemqURL, String activemqQueues, int threadsPerQueue, int batchSize, int totalToExpect) throws Exception { - - this.activemqURL = activemqURL; - this.activemqQueues = activemqQueues; - this.totalToExpect = totalToExpect; - - queues = this.activemqQueues.split(","); - - for (int i = 0; i < queues.length; i++) { - queues[i] = queues[i].trim(); + catch (Exception e) { } - threads = new HashMap>(); - - // For each queue, create a list of threads and set up the list of ids - for (String q : queues) { - - List list = new ArrayList(); - - idsByQueue.put(q, Collections.synchronizedList(new ArrayList())); - - for (int i = 0; i < threadsPerQueue; i++) { - list.add(new ConsumerThread(q, batchSize)); - } - - threads.put(q, list); + try { + qc.close(); } - } + catch (Exception e) { - public Map> getIDs() { - return idsByQueue; - } - - // Start the threads - public void start() throws Exception { - - for (List list : threads.values()) { - - for (ConsumerThread ct : list) { - - ct.start(); - } } - } - - // Tell the threads to stop - // Then wait for them to stop - public void shutdown() throws Exception { - - for (List list : threads.values()) { - - for (ConsumerThread ct : list) { - - ct.shutdown(); - } - } - - for (List list : threads.values()) { - - for (ConsumerThread ct : list) { - - ct.join(); - } - } - } - - private Session newSession(QueueConnection queueConnection) throws Exception { - return queueConnection.createSession(true, Session.SESSION_TRANSACTED); - } - - private synchronized QueueConnection newQueueConnection() throws Exception { - - if (connectionFactory == null) { - connectionFactory = new ActiveMQConnectionFactory(amqUser, amqPassword, activemqURL); - connectionFactory.setWatchTopicAdvisories(false); - } - - // Set the redelivery count to -1 (infinite), or else messages will start dropping - // after the queue has had a certain number of failures (default is 6) - RedeliveryPolicy policy = connectionFactory.getRedeliveryPolicy(); - policy.setMaximumRedeliveries(-1); - - QueueConnection amqConnection = connectionFactory.createQueueConnection(); - amqConnection.start(); - return amqConnection; - } - - public boolean completed() { - for (List list : threads.values()) { - - for (ConsumerThread ct : list) { - - if (ct.isAlive()) { - LOG.info("thread for {} is still alive.", ct.qName); - return false; - } - } - } - return true; - } - - private class ConsumerThread extends Thread { - - private int batchSize; - private QueueConnection qc; - private Session session; - private MessageConsumer mc; - private List idList; - private boolean shutdown = false; - private String qName; - - private ConsumerThread(String queueName, int batchSize) throws Exception { - - this.batchSize = batchSize; - - // Each thread has its own connection and session - qName = queueName; - qc = newQueueConnection(); - session = newSession(qc); - Queue q = session.createQueue(queueName + "?consumer.prefetchSize=" + batchSize); - mc = session.createConsumer(q); - - idList = idsByQueue.get(queueName); - } - - public void run() { - - try { - - int count = 0; - - // Keep reading as long as it hasn't been told to shutdown - while (!shutdown) { - - if (idList.size() >= totalToExpect) { - LOG.info("Got {} for q: {}", +idList.size(), qName); - session.commit(); - break; - } - Message m = mc.receive(4000); - - if (m != null) { - - // We received a non-null message, add the ID to our list - - idList.add(m.getStringProperty("KEY")); - - count++; - - // If we've reached our batch size, commit the batch and reset the count - - if (count == batchSize) { - session.commit(); - count = 0; - } - } else { - - // We didn't receive anything this time, commit any current batch and reset the count - - session.commit(); - count = 0; - - // Sleep a little before trying to read after not getting a message - - try { - if (idList.size() < totalToExpect) { - LOG.info("did not receive on {}, current count: {}", qName, idList.size()); - didNotReceive.set(true); - } - //sleep(3000); - } catch (Exception e) { - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - - // Once we exit, close everything - close(); - } - } - - public void shutdown() { - shutdown = true; - } - - public void close() { - - try { - mc.close(); - } catch (Exception e) { - } - - try { - session.close(); - } catch (Exception e) { - } - - try { - qc.close(); - } catch (Exception e) { - - } - } - } - } + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5266Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5266Test.java index 1ddf605369..980a04e602 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5266Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5266Test.java @@ -32,6 +32,7 @@ import javax.jms.Queue; import javax.jms.QueueConnection; import javax.jms.Session; import javax.jms.TextMessage; + import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.RedeliveryPolicy; @@ -49,7 +50,6 @@ import org.junit.runners.Parameterized; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import static org.junit.Assert.assertEquals; /** @@ -59,543 +59,545 @@ import static org.junit.Assert.assertEquals; */ @RunWith(Parameterized.class) public class AMQ5266Test { - static Logger LOG = LoggerFactory.getLogger(AMQ5266Test.class); - String activemqURL = "tcp://localhost:61617"; - BrokerService brokerService; - public int messageSize = 1000; + static Logger LOG = LoggerFactory.getLogger(AMQ5266Test.class); + String activemqURL = "tcp://localhost:61617"; + BrokerService brokerService; - @Parameterized.Parameter(0) - public int publisherMessagesPerThread = 1000; + public int messageSize = 1000; - @Parameterized.Parameter(1) - public int publisherThreadCount = 20; + @Parameterized.Parameter(0) + public int publisherMessagesPerThread = 1000; - @Parameterized.Parameter(2) - public int consumerThreadsPerQueue = 5; + @Parameterized.Parameter(1) + public int publisherThreadCount = 20; - @Parameterized.Parameter(3) - public int destMemoryLimit = 50 * 1024; + @Parameterized.Parameter(2) + public int consumerThreadsPerQueue = 5; - @Parameterized.Parameter(4) - public boolean useCache = true; + @Parameterized.Parameter(3) + public int destMemoryLimit = 50 * 1024; - @Parameterized.Parameter(5) - public TestSupport.PersistenceAdapterChoice persistenceAdapterChoice = TestSupport.PersistenceAdapterChoice.KahaDB; + @Parameterized.Parameter(4) + public boolean useCache = true; - @Parameterized.Parameter(6) - public boolean optimizeDispatch = false; + @Parameterized.Parameter(5) + public TestSupport.PersistenceAdapterChoice persistenceAdapterChoice = TestSupport.PersistenceAdapterChoice.KahaDB; - @Parameterized.Parameters(name="#{0},producerThreads:{1},consumerThreads:{2},mL:{3},useCache:{4},store:{5},optimizedDispatch:{6}") - public static Iterable parameters() { - return Arrays.asList(new Object[][]{ - {1, 1, 1, 50*1024, false, TestSupport.PersistenceAdapterChoice.JDBC, true}, - {1000, 20, 5, 50*1024, true, TestSupport.PersistenceAdapterChoice.JDBC, false}, - {100, 20, 5, 50*1024, false, TestSupport.PersistenceAdapterChoice.JDBC, false}, - {1000, 5, 20, 50*1024, true, TestSupport.PersistenceAdapterChoice.JDBC, false}, - {1000, 20, 20, 1024*1024, true, TestSupport.PersistenceAdapterChoice.JDBC, false}, + @Parameterized.Parameter(6) + public boolean optimizeDispatch = false; - {1, 1, 1, 50*1024, false, TestSupport.PersistenceAdapterChoice.KahaDB, true}, - {100, 5, 5, 50*1024, false, TestSupport.PersistenceAdapterChoice.KahaDB, false}, - {1000, 20, 5, 50*1024, true, TestSupport.PersistenceAdapterChoice.KahaDB, false}, - {100, 20, 5, 50*1024, false, TestSupport.PersistenceAdapterChoice.KahaDB, false}, - {1000, 5, 20, 50*1024, true, TestSupport.PersistenceAdapterChoice.KahaDB, false}, - {1000, 20, 20, 1024*1024, true, TestSupport.PersistenceAdapterChoice.KahaDB, false}, + @Parameterized.Parameters(name = "#{0},producerThreads:{1},consumerThreads:{2},mL:{3},useCache:{4},store:{5},optimizedDispatch:{6}") + public static Iterable parameters() { + return Arrays.asList(new Object[][]{{1, 1, 1, 50 * 1024, false, TestSupport.PersistenceAdapterChoice.JDBC, true}, {1000, 20, 5, 50 * 1024, true, TestSupport.PersistenceAdapterChoice.JDBC, false}, {100, 20, 5, 50 * 1024, false, TestSupport.PersistenceAdapterChoice.JDBC, false}, {1000, 5, 20, 50 * 1024, true, TestSupport.PersistenceAdapterChoice.JDBC, false}, {1000, 20, 20, 1024 * 1024, true, TestSupport.PersistenceAdapterChoice.JDBC, false}, - {1, 1, 1, 50*1024, false, TestSupport.PersistenceAdapterChoice.LevelDB, true}, - {100, 5, 5, 50*1024, false, TestSupport.PersistenceAdapterChoice.LevelDB, false}, - {1000, 20, 5, 50*1024, true, TestSupport.PersistenceAdapterChoice.LevelDB, false}, - {100, 20, 5, 50*1024, false, TestSupport.PersistenceAdapterChoice.LevelDB, false}, - {1000, 5, 20, 50*1024, true, TestSupport.PersistenceAdapterChoice.LevelDB, false}, - {1000, 20, 20, 1024*1024, true, TestSupport.PersistenceAdapterChoice.LevelDB, false}, + {1, 1, 1, 50 * 1024, false, TestSupport.PersistenceAdapterChoice.KahaDB, true}, {100, 5, 5, 50 * 1024, false, TestSupport.PersistenceAdapterChoice.KahaDB, false}, {1000, 20, 5, 50 * 1024, true, TestSupport.PersistenceAdapterChoice.KahaDB, false}, {100, 20, 5, 50 * 1024, false, TestSupport.PersistenceAdapterChoice.KahaDB, false}, {1000, 5, 20, 50 * 1024, true, TestSupport.PersistenceAdapterChoice.KahaDB, false}, {1000, 20, 20, 1024 * 1024, true, TestSupport.PersistenceAdapterChoice.KahaDB, false}, - }); - } + {1, 1, 1, 50 * 1024, false, TestSupport.PersistenceAdapterChoice.LevelDB, true}, {100, 5, 5, 50 * 1024, false, TestSupport.PersistenceAdapterChoice.LevelDB, false}, {1000, 20, 5, 50 * 1024, true, TestSupport.PersistenceAdapterChoice.LevelDB, false}, {100, 20, 5, 50 * 1024, false, TestSupport.PersistenceAdapterChoice.LevelDB, false}, {1000, 5, 20, 50 * 1024, true, TestSupport.PersistenceAdapterChoice.LevelDB, false}, {1000, 20, 20, 1024 * 1024, true, TestSupport.PersistenceAdapterChoice.LevelDB, false}, - public int consumerBatchSize = 5; + }); + } - @Before - public void startBroker() throws Exception { - brokerService = new BrokerService(); - TestSupport.setPersistenceAdapter(brokerService, persistenceAdapterChoice); - brokerService.setDeleteAllMessagesOnStartup(true); - brokerService.setUseJmx(false); + public int consumerBatchSize = 5; - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setUseConsumerPriority(false); // java.lang.IllegalArgumentException: Comparison method violates its general contract! - defaultEntry.setMaxAuditDepth(publisherThreadCount); - defaultEntry.setEnableAudit(true); - defaultEntry.setUseCache(useCache); - defaultEntry.setMaxPageSize(1000); - defaultEntry.setOptimizedDispatch(optimizeDispatch); - defaultEntry.setMemoryLimit(destMemoryLimit); - defaultEntry.setExpireMessagesPeriod(0); - policyMap.setDefaultEntry(defaultEntry); - brokerService.setDestinationPolicy(policyMap); + @Before + public void startBroker() throws Exception { + brokerService = new BrokerService(); + TestSupport.setPersistenceAdapter(brokerService, persistenceAdapterChoice); + brokerService.setDeleteAllMessagesOnStartup(true); + brokerService.setUseJmx(false); - brokerService.getSystemUsage().getMemoryUsage().setLimit(512 * 1024 * 1024); + PolicyMap policyMap = new PolicyMap(); + PolicyEntry defaultEntry = new PolicyEntry(); + defaultEntry.setUseConsumerPriority(false); // java.lang.IllegalArgumentException: Comparison method violates its general contract! + defaultEntry.setMaxAuditDepth(publisherThreadCount); + defaultEntry.setEnableAudit(true); + defaultEntry.setUseCache(useCache); + defaultEntry.setMaxPageSize(1000); + defaultEntry.setOptimizedDispatch(optimizeDispatch); + defaultEntry.setMemoryLimit(destMemoryLimit); + defaultEntry.setExpireMessagesPeriod(0); + policyMap.setDefaultEntry(defaultEntry); + brokerService.setDestinationPolicy(policyMap); - TransportConnector transportConnector = brokerService.addConnector("tcp://0.0.0.0:0"); - brokerService.start(); - activemqURL = transportConnector.getPublishableConnectString(); - } + brokerService.getSystemUsage().getMemoryUsage().setLimit(512 * 1024 * 1024); - @After - public void stopBroker() throws Exception { - if (brokerService != null) { - brokerService.stop(); - } - } + TransportConnector transportConnector = brokerService.addConnector("tcp://0.0.0.0:0"); + brokerService.start(); + activemqURL = transportConnector.getPublishableConnectString(); + } - @Test - public void test() throws Exception { + @After + public void stopBroker() throws Exception { + if (brokerService != null) { + brokerService.stop(); + } + } - String activemqQueues = "activemq,activemq2";//,activemq3,activemq4,activemq5,activemq6,activemq7,activemq8,activemq9"; + @Test + public void test() throws Exception { - int consumerWaitForConsumption = 5 * 60 * 1000; + String activemqQueues = "activemq,activemq2";//,activemq3,activemq4,activemq5,activemq6,activemq7,activemq8,activemq9"; - ExportQueuePublisher publisher = null; - ExportQueueConsumer consumer = null; + int consumerWaitForConsumption = 5 * 60 * 1000; - LOG.info("Publisher will publish " + (publisherMessagesPerThread * publisherThreadCount) + " messages to each queue specified."); - LOG.info("\nBuilding Publisher..."); + ExportQueuePublisher publisher = null; + ExportQueueConsumer consumer = null; - publisher = new ExportQueuePublisher(activemqURL, activemqQueues, publisherMessagesPerThread, publisherThreadCount); + LOG.info("Publisher will publish " + (publisherMessagesPerThread * publisherThreadCount) + " messages to each queue specified."); + LOG.info("\nBuilding Publisher..."); - LOG.info("Building Consumer..."); + publisher = new ExportQueuePublisher(activemqURL, activemqQueues, publisherMessagesPerThread, publisherThreadCount); - consumer = new ExportQueueConsumer(activemqURL, activemqQueues, consumerThreadsPerQueue, consumerBatchSize, publisherMessagesPerThread * publisherThreadCount); + LOG.info("Building Consumer..."); + consumer = new ExportQueueConsumer(activemqURL, activemqQueues, consumerThreadsPerQueue, consumerBatchSize, publisherMessagesPerThread * publisherThreadCount); - LOG.info("Starting Publisher..."); + LOG.info("Starting Publisher..."); - publisher.start(); + publisher.start(); - LOG.info("Starting Consumer..."); + LOG.info("Starting Consumer..."); - consumer.start(); + consumer.start(); - int distinctPublishedCount = 0; + int distinctPublishedCount = 0; + LOG.info("Waiting For Publisher Completion..."); - LOG.info("Waiting For Publisher Completion..."); + publisher.waitForCompletion(); - publisher.waitForCompletion(); + List publishedIds = publisher.getIDs(); + distinctPublishedCount = new TreeSet(publishedIds).size(); - List publishedIds = publisher.getIDs(); - distinctPublishedCount = new TreeSet(publishedIds).size(); + LOG.info("Publisher Complete. Published: " + publishedIds.size() + ", Distinct IDs Published: " + distinctPublishedCount); - LOG.info("Publisher Complete. Published: " + publishedIds.size() + ", Distinct IDs Published: " + distinctPublishedCount); + long endWait = System.currentTimeMillis() + consumerWaitForConsumption; + while (!consumer.completed() && System.currentTimeMillis() < endWait) { + try { + int secs = (int) (endWait - System.currentTimeMillis()) / 1000; + LOG.info("Waiting For Consumer Completion. Time left: " + secs + " secs"); + Thread.sleep(10000); + } + catch (Exception e) { + } + } + LOG.info("\nConsumer Complete: " + consumer.completed() + ", Shutting Down."); + + consumer.shutdown(); + + LOG.info("Consumer Stats:"); + + for (Map.Entry> entry : consumer.getIDs().entrySet()) { + + List idList = entry.getValue(); + + int distinctConsumed = new TreeSet(idList).size(); + + StringBuilder sb = new StringBuilder(); + sb.append(" Queue: " + entry.getKey() + + " -> Total Messages Consumed: " + idList.size() + + ", Distinct IDs Consumed: " + distinctConsumed); + + int diff = distinctPublishedCount - distinctConsumed; + sb.append(" ( " + (diff > 0 ? diff : "NO") + " STUCK MESSAGES " + " ) "); + LOG.info(sb.toString()); + + assertEquals("expect to get all messages!", 0, diff); + + } + } + + public class ExportQueuePublisher { + + private final String amqUser = ActiveMQConnection.DEFAULT_USER; + private final String amqPassword = ActiveMQConnection.DEFAULT_PASSWORD; + private ActiveMQConnectionFactory connectionFactory = null; + private String activemqURL = null; + private String activemqQueues = null; + // Collection of distinct IDs that the publisher has published. + // After a message is published, its UUID will be written to this list for tracking. + // This list of IDs (or distinct count) will be used to compare to the consumed list of IDs. + //private Set ids = Collections.synchronizedSet(new TreeSet()); + private List ids = Collections.synchronizedList(new ArrayList()); + private List threads; + + public ExportQueuePublisher(String activemqURL, + String activemqQueues, + int messagesPerThread, + int threadCount) throws Exception { + + this.activemqURL = activemqURL; + this.activemqQueues = activemqQueues; + + threads = new ArrayList(); + + // Build the threads and tell them how many messages to publish + for (int i = 0; i < threadCount; i++) { + PublisherThread pt = new PublisherThread(messagesPerThread); + threads.add(pt); + } + } + + public List getIDs() { + return ids; + } + + // Kick off threads + public void start() throws Exception { + + for (PublisherThread pt : threads) { + pt.start(); + } + } + + // Wait for threads to complete. They will complete once they've published all of their messages. + public void waitForCompletion() throws Exception { + + for (PublisherThread pt : threads) { + pt.join(); + pt.close(); + } + } + + private Session newSession(QueueConnection queueConnection) throws Exception { + return queueConnection.createSession(true, Session.SESSION_TRANSACTED); + } + + private synchronized QueueConnection newQueueConnection() throws Exception { + + if (connectionFactory == null) { + connectionFactory = new ActiveMQConnectionFactory(amqUser, amqPassword, activemqURL); + } + + // Set the redelivery count to -1 (infinite), or else messages will start dropping + // after the queue has had a certain number of failures (default is 6) + RedeliveryPolicy policy = connectionFactory.getRedeliveryPolicy(); + policy.setMaximumRedeliveries(-1); + + QueueConnection amqConnection = connectionFactory.createQueueConnection(); + amqConnection.start(); + return amqConnection; + } + + private class PublisherThread extends Thread { + + private int count; + private QueueConnection qc; + private Session session; + private MessageProducer mp; + + private PublisherThread(int count) throws Exception { + + this.count = count; + + // Each Thread has its own Connection and Session, so no sync worries + qc = newQueueConnection(); + session = newSession(qc); + + // In our code, when publishing to multiple queues, + // we're using composite destinations like below + Queue q = new ActiveMQQueue(activemqQueues); + mp = session.createProducer(q); + } + + public void run() { - long endWait = System.currentTimeMillis() + consumerWaitForConsumption; - while (!consumer.completed() && System.currentTimeMillis() < endWait) { try { - int secs = (int) (endWait - System.currentTimeMillis()) / 1000; - LOG.info("Waiting For Consumer Completion. Time left: " + secs + " secs"); - Thread.sleep(10000); - } catch (Exception e) { + + // Loop until we've published enough messages + while (count-- > 0) { + + TextMessage tm = session.createTextMessage(getMessageText()); + String id = UUID.randomUUID().toString(); + tm.setStringProperty("KEY", id); + ids.add(id); // keep track of the key to compare against consumer + + mp.send(tm); + session.commit(); + } } - } - - LOG.info("\nConsumer Complete: " + consumer.completed() +", Shutting Down."); - - consumer.shutdown(); - - LOG.info("Consumer Stats:"); - - for (Map.Entry> entry : consumer.getIDs().entrySet()) { - - List idList = entry.getValue(); - - int distinctConsumed = new TreeSet(idList).size(); - - StringBuilder sb = new StringBuilder(); - sb.append(" Queue: " + entry.getKey() + - " -> Total Messages Consumed: " + idList.size() + - ", Distinct IDs Consumed: " + distinctConsumed); - - int diff = distinctPublishedCount - distinctConsumed; - sb.append(" ( " + (diff > 0 ? diff : "NO") + " STUCK MESSAGES " + " ) "); - LOG.info(sb.toString()); - - assertEquals("expect to get all messages!", 0, diff); - - } - } - - public class ExportQueuePublisher { - - private final String amqUser = ActiveMQConnection.DEFAULT_USER; - private final String amqPassword = ActiveMQConnection.DEFAULT_PASSWORD; - private ActiveMQConnectionFactory connectionFactory = null; - private String activemqURL = null; - private String activemqQueues = null; - // Collection of distinct IDs that the publisher has published. - // After a message is published, its UUID will be written to this list for tracking. - // This list of IDs (or distinct count) will be used to compare to the consumed list of IDs. - //private Set ids = Collections.synchronizedSet(new TreeSet()); - private List ids = Collections.synchronizedList(new ArrayList()); - private List threads; - - public ExportQueuePublisher(String activemqURL, String activemqQueues, int messagesPerThread, int threadCount) throws Exception { - - this.activemqURL = activemqURL; - this.activemqQueues = activemqQueues; - - threads = new ArrayList(); - - // Build the threads and tell them how many messages to publish - for (int i = 0; i < threadCount; i++) { - PublisherThread pt = new PublisherThread(messagesPerThread); - threads.add(pt); + catch (Exception e) { + e.printStackTrace(); } - } + } - public List getIDs() { - return ids; - } + // Called by waitForCompletion + public void close() { - // Kick off threads - public void start() throws Exception { - - for (PublisherThread pt : threads) { - pt.start(); + try { + mp.close(); } - } - - // Wait for threads to complete. They will complete once they've published all of their messages. - public void waitForCompletion() throws Exception { - - for (PublisherThread pt : threads) { - pt.join(); - pt.close(); - } - } - - private Session newSession(QueueConnection queueConnection) throws Exception { - return queueConnection.createSession(true, Session.SESSION_TRANSACTED); - } - - private synchronized QueueConnection newQueueConnection() throws Exception { - - if (connectionFactory == null) { - connectionFactory = new ActiveMQConnectionFactory(amqUser, amqPassword, activemqURL); + catch (Exception e) { } - // Set the redelivery count to -1 (infinite), or else messages will start dropping - // after the queue has had a certain number of failures (default is 6) - RedeliveryPolicy policy = connectionFactory.getRedeliveryPolicy(); - policy.setMaximumRedeliveries(-1); - - QueueConnection amqConnection = connectionFactory.createQueueConnection(); - amqConnection.start(); - return amqConnection; - } - - private class PublisherThread extends Thread { - - private int count; - private QueueConnection qc; - private Session session; - private MessageProducer mp; - - private PublisherThread(int count) throws Exception { - - this.count = count; - - // Each Thread has its own Connection and Session, so no sync worries - qc = newQueueConnection(); - session = newSession(qc); - - // In our code, when publishing to multiple queues, - // we're using composite destinations like below - Queue q = new ActiveMQQueue(activemqQueues); - mp = session.createProducer(q); + try { + session.close(); + } + catch (Exception e) { } - public void run() { + try { + qc.close(); + } + catch (Exception e) { + } + } + } - try { + } - // Loop until we've published enough messages - while (count-- > 0) { + String messageText; - TextMessage tm = session.createTextMessage(getMessageText()); - String id = UUID.randomUUID().toString(); - tm.setStringProperty("KEY", id); - ids.add(id); // keep track of the key to compare against consumer + private String getMessageText() { - mp.send(tm); + if (messageText == null) { + + synchronized (this) { + + if (messageText == null) { + + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < messageSize; i++) { + sb.append("X"); + } + messageText = sb.toString(); + } + } + } + + return messageText; + } + + public class ExportQueueConsumer { + + private final String amqUser = ActiveMQConnection.DEFAULT_USER; + private final String amqPassword = ActiveMQConnection.DEFAULT_PASSWORD; + private final int totalToExpect; + private ActiveMQConnectionFactory connectionFactory = null; + private String activemqURL = null; + private String activemqQueues = null; + private String[] queues = null; + // Map of IDs that were consumed, keyed by queue name. + // We'll compare these against what was published to know if any got stuck or dropped. + private Map> idsByQueue = new HashMap>(); + private Map> threads; + + public ExportQueueConsumer(String activemqURL, + String activemqQueues, + int threadsPerQueue, + int batchSize, + int totalToExpect) throws Exception { + + this.activemqURL = activemqURL; + this.activemqQueues = activemqQueues; + this.totalToExpect = totalToExpect; + + queues = this.activemqQueues.split(","); + + for (int i = 0; i < queues.length; i++) { + queues[i] = queues[i].trim(); + } + + threads = new HashMap>(); + + // For each queue, create a list of threads and set up the list of ids + for (String q : queues) { + + List list = new ArrayList(); + + idsByQueue.put(q, Collections.synchronizedList(new ArrayList())); + + for (int i = 0; i < threadsPerQueue; i++) { + list.add(new ConsumerThread(q, batchSize)); + } + + threads.put(q, list); + } + } + + public Map> getIDs() { + return idsByQueue; + } + + // Start the threads + public void start() throws Exception { + + for (List list : threads.values()) { + + for (ConsumerThread ct : list) { + + ct.start(); + } + } + } + + // Tell the threads to stop + // Then wait for them to stop + public void shutdown() throws Exception { + + for (List list : threads.values()) { + + for (ConsumerThread ct : list) { + + ct.shutdown(); + } + } + + for (List list : threads.values()) { + + for (ConsumerThread ct : list) { + + ct.join(); + } + } + } + + private Session newSession(QueueConnection queueConnection) throws Exception { + return queueConnection.createSession(true, Session.SESSION_TRANSACTED); + } + + private synchronized QueueConnection newQueueConnection() throws Exception { + + if (connectionFactory == null) { + connectionFactory = new ActiveMQConnectionFactory(amqUser, amqPassword, activemqURL); + } + + // Set the redelivery count to -1 (infinite), or else messages will start dropping + // after the queue has had a certain number of failures (default is 6) + RedeliveryPolicy policy = connectionFactory.getRedeliveryPolicy(); + policy.setMaximumRedeliveries(-1); + + QueueConnection amqConnection = connectionFactory.createQueueConnection(); + amqConnection.start(); + return amqConnection; + } + + public boolean completed() { + for (List list : threads.values()) { + + for (ConsumerThread ct : list) { + + if (ct.isAlive()) { + LOG.info("thread for {} is still alive.", ct.qName); + return false; + } + } + } + return true; + } + + private class ConsumerThread extends Thread { + + private int batchSize; + private QueueConnection qc; + private Session session; + private MessageConsumer mc; + private List idList; + private boolean shutdown = false; + private String qName; + + private ConsumerThread(String queueName, int batchSize) throws Exception { + + this.batchSize = batchSize; + + // Each thread has its own connection and session + qName = queueName; + qc = newQueueConnection(); + session = newSession(qc); + Queue q = session.createQueue(queueName + "?consumer.prefetchSize=" + batchSize); + mc = session.createConsumer(q); + + idList = idsByQueue.get(queueName); + } + + public void run() { + + try { + + int count = 0; + + // Keep reading as long as it hasn't been told to shutdown + while (!shutdown) { + + if (idList.size() >= totalToExpect) { + LOG.info("Got {} for q: {}", +idList.size(), qName); + session.commit(); + break; + } + Message m = mc.receive(4000); + + if (m != null) { + + // We received a non-null message, add the ID to our list + + idList.add(m.getStringProperty("KEY")); + + count++; + + // If we've reached our batch size, commit the batch and reset the count + + if (count == batchSize) { session.commit(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } + count = 0; + } + } + else { - // Called by waitForCompletion - public void close() { + // We didn't receive anything this time, commit any current batch and reset the count - try { - mp.close(); - } catch (Exception e) { - } + session.commit(); + count = 0; - try { - session.close(); - } catch (Exception e) { - } + // Sleep a little before trying to read after not getting a message - try { - qc.close(); - } catch (Exception e) { - } - } - } - - } - - String messageText; - private String getMessageText() { - - if (messageText == null) { - - synchronized (this) { - - if (messageText == null) { - - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < messageSize; i++) { - sb.append("X"); - } - messageText = sb.toString(); - } - } - } - - return messageText; - } - - - public class ExportQueueConsumer { - - private final String amqUser = ActiveMQConnection.DEFAULT_USER; - private final String amqPassword = ActiveMQConnection.DEFAULT_PASSWORD; - private final int totalToExpect; - private ActiveMQConnectionFactory connectionFactory = null; - private String activemqURL = null; - private String activemqQueues = null; - private String[] queues = null; - // Map of IDs that were consumed, keyed by queue name. - // We'll compare these against what was published to know if any got stuck or dropped. - private Map> idsByQueue = new HashMap>(); - private Map> threads; - - public ExportQueueConsumer(String activemqURL, String activemqQueues, int threadsPerQueue, int batchSize, int totalToExpect) throws Exception { - - this.activemqURL = activemqURL; - this.activemqQueues = activemqQueues; - this.totalToExpect = totalToExpect; - - queues = this.activemqQueues.split(","); - - for (int i = 0; i < queues.length; i++) { - queues[i] = queues[i].trim(); - } - - threads = new HashMap>(); - - // For each queue, create a list of threads and set up the list of ids - for (String q : queues) { - - List list = new ArrayList(); - - idsByQueue.put(q, Collections.synchronizedList(new ArrayList())); - - for (int i = 0; i < threadsPerQueue; i++) { - list.add(new ConsumerThread(q, batchSize)); - } - - threads.put(q, list); - } - } - - public Map> getIDs() { - return idsByQueue; - } - - // Start the threads - public void start() throws Exception { - - for (List list : threads.values()) { - - for (ConsumerThread ct : list) { - - ct.start(); - } - } - } - - // Tell the threads to stop - // Then wait for them to stop - public void shutdown() throws Exception { - - for (List list : threads.values()) { - - for (ConsumerThread ct : list) { - - ct.shutdown(); - } - } - - for (List list : threads.values()) { - - for (ConsumerThread ct : list) { - - ct.join(); - } - } - } - - private Session newSession(QueueConnection queueConnection) throws Exception { - return queueConnection.createSession(true, Session.SESSION_TRANSACTED); - } - - private synchronized QueueConnection newQueueConnection() throws Exception { - - if (connectionFactory == null) { - connectionFactory = new ActiveMQConnectionFactory(amqUser, amqPassword, activemqURL); - } - - // Set the redelivery count to -1 (infinite), or else messages will start dropping - // after the queue has had a certain number of failures (default is 6) - RedeliveryPolicy policy = connectionFactory.getRedeliveryPolicy(); - policy.setMaximumRedeliveries(-1); - - QueueConnection amqConnection = connectionFactory.createQueueConnection(); - amqConnection.start(); - return amqConnection; - } - - public boolean completed() { - for (List list : threads.values()) { - - for (ConsumerThread ct : list) { - - if (ct.isAlive()) { - LOG.info("thread for {} is still alive.", ct.qName); - return false; - } - } - } - return true; - } - - private class ConsumerThread extends Thread { - - private int batchSize; - private QueueConnection qc; - private Session session; - private MessageConsumer mc; - private List idList; - private boolean shutdown = false; - private String qName; - - private ConsumerThread(String queueName, int batchSize) throws Exception { - - this.batchSize = batchSize; - - // Each thread has its own connection and session - qName = queueName; - qc = newQueueConnection(); - session = newSession(qc); - Queue q = session.createQueue(queueName + "?consumer.prefetchSize=" + batchSize); - mc = session.createConsumer(q); - - idList = idsByQueue.get(queueName); - } - - public void run() { - - try { - - int count = 0; - - // Keep reading as long as it hasn't been told to shutdown - while (!shutdown) { - - if (idList.size() >= totalToExpect) { - LOG.info("Got {} for q: {}", +idList.size(), qName); - session.commit(); - break; + try { + if (idList.size() < totalToExpect) { + LOG.info("did not receive on {}, current count: {}", qName, idList.size()); } - Message m = mc.receive(4000); + //sleep(3000); + } + catch (Exception e) { + } + } + } + } + catch (Exception e) { + e.printStackTrace(); + } + finally { - if (m != null) { + // Once we exit, close everything + close(); + } + } - // We received a non-null message, add the ID to our list + public void shutdown() { + shutdown = true; + } - idList.add(m.getStringProperty("KEY")); + public void close() { - count++; - - // If we've reached our batch size, commit the batch and reset the count - - if (count == batchSize) { - session.commit(); - count = 0; - } - } else { - - // We didn't receive anything this time, commit any current batch and reset the count - - session.commit(); - count = 0; - - // Sleep a little before trying to read after not getting a message - - try { - if (idList.size() < totalToExpect) { - LOG.info("did not receive on {}, current count: {}", qName, idList.size()); - } - //sleep(3000); - } catch (Exception e) { - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - - // Once we exit, close everything - close(); - } + try { + mc.close(); + } + catch (Exception e) { } - public void shutdown() { - shutdown = true; + try { + session.close(); + } + catch (Exception e) { } - public void close() { - - try { - mc.close(); - } catch (Exception e) { - } - - try { - session.close(); - } catch (Exception e) { - } - - try { - qc.close(); - } catch (Exception e) { - - } + try { + qc.close(); } - } - } + catch (Exception e) { + + } + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5274Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5274Test.java index 4ba6526890..d4c02fb8b6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5274Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5274Test.java @@ -23,6 +23,7 @@ import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; + import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.RedeliveryPolicy; @@ -38,96 +39,95 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class AMQ5274Test { - static Logger LOG = LoggerFactory.getLogger(AMQ5274Test.class); - String activemqURL; - BrokerService brokerService; - ActiveMQQueue dest = new ActiveMQQueue("TestQ"); + static Logger LOG = LoggerFactory.getLogger(AMQ5274Test.class); + String activemqURL; + BrokerService brokerService; + ActiveMQQueue dest = new ActiveMQQueue("TestQ"); - @Before - public void startBroker() throws Exception { - brokerService = new BrokerService(); - brokerService.setPersistent(false); - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultPolicy = new PolicyEntry(); - defaultPolicy.setExpireMessagesPeriod(1000); - policyMap.setDefaultEntry(defaultPolicy); - brokerService.setDestinationPolicy(policyMap); - activemqURL = brokerService.addConnector("tcp://localhost:0").getPublishableConnectString(); - brokerService.start(); - } + @Before + public void startBroker() throws Exception { + brokerService = new BrokerService(); + brokerService.setPersistent(false); + PolicyMap policyMap = new PolicyMap(); + PolicyEntry defaultPolicy = new PolicyEntry(); + defaultPolicy.setExpireMessagesPeriod(1000); + policyMap.setDefaultEntry(defaultPolicy); + brokerService.setDestinationPolicy(policyMap); + activemqURL = brokerService.addConnector("tcp://localhost:0").getPublishableConnectString(); + brokerService.start(); + } - @After - public void stopBroker() throws Exception { - if (brokerService != null) { - brokerService.stop(); - } - } + @After + public void stopBroker() throws Exception { + if (brokerService != null) { + brokerService.stop(); + } + } - @Test - public void test() throws Exception { - LOG.info("Starting Test"); - assertTrue(brokerService.isStarted()); + @Test + public void test() throws Exception { + LOG.info("Starting Test"); + assertTrue(brokerService.isStarted()); - produce(); - consumeAndRollback(); + produce(); + consumeAndRollback(); - // check reported queue size using JMX - long queueSize = getQueueSize(); - assertEquals("Queue " + dest.getPhysicalName() + " not empty, reporting " + queueSize + " messages.", 0, queueSize); - } + // check reported queue size using JMX + long queueSize = getQueueSize(); + assertEquals("Queue " + dest.getPhysicalName() + " not empty, reporting " + queueSize + " messages.", 0, queueSize); + } - private void consumeAndRollback() throws JMSException, InterruptedException { - ActiveMQConnection connection = createConnection(); - RedeliveryPolicy noRedelivery = new RedeliveryPolicy(); - noRedelivery.setMaximumRedeliveries(0); - connection.setRedeliveryPolicy(noRedelivery); - connection.start(); - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageConsumer consumer = session.createConsumer(dest); - Message m; - while ( (m = consumer.receive(4000)) != null) { - LOG.info("Got:" + m); - TimeUnit.SECONDS.sleep(1); - session.rollback(); - } - connection.close(); - } + private void consumeAndRollback() throws JMSException, InterruptedException { + ActiveMQConnection connection = createConnection(); + RedeliveryPolicy noRedelivery = new RedeliveryPolicy(); + noRedelivery.setMaximumRedeliveries(0); + connection.setRedeliveryPolicy(noRedelivery); + connection.start(); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageConsumer consumer = session.createConsumer(dest); + Message m; + while ((m = consumer.receive(4000)) != null) { + LOG.info("Got:" + m); + TimeUnit.SECONDS.sleep(1); + session.rollback(); + } + connection.close(); + } - private void produce() throws Exception { - Connection connection = createConnection(); - connection.start(); + private void produce() throws Exception { + Connection connection = createConnection(); + connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(dest); - producer.setTimeToLive(10000); - for (int i=0;i<20;i++) { - producer.send(session.createTextMessage("i="+i)); - } - connection.close(); - } + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(dest); + producer.setTimeToLive(10000); + for (int i = 0; i < 20; i++) { + producer.send(session.createTextMessage("i=" + i)); + } + connection.close(); + } - private ActiveMQConnection createConnection() throws JMSException { - return (ActiveMQConnection) new ActiveMQConnectionFactory(activemqURL).createConnection(); - } + private ActiveMQConnection createConnection() throws JMSException { + return (ActiveMQConnection) new ActiveMQConnectionFactory(activemqURL).createConnection(); + } - - public long getQueueSize() throws Exception { - long queueSize = 0; - try { - QueueViewMBean queueViewMBean = (QueueViewMBean) brokerService.getManagementContext().newProxyInstance(BrokerMBeanSupport.createDestinationName(brokerService.getBrokerObjectName(), dest), QueueViewMBean.class, false); - queueSize = queueViewMBean.getQueueSize(); - LOG.info("QueueSize for destination {} is {}", dest, queueSize); - } catch (Exception ex) { - LOG.error("Error retrieving QueueSize from JMX ", ex); - throw ex; - } - return queueSize; - } + public long getQueueSize() throws Exception { + long queueSize = 0; + try { + QueueViewMBean queueViewMBean = (QueueViewMBean) brokerService.getManagementContext().newProxyInstance(BrokerMBeanSupport.createDestinationName(brokerService.getBrokerObjectName(), dest), QueueViewMBean.class, false); + queueSize = queueViewMBean.getQueueSize(); + LOG.info("QueueSize for destination {} is {}", dest, queueSize); + } + catch (Exception ex) { + LOG.error("Error retrieving QueueSize from JMX ", ex); + throw ex; + } + return queueSize; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5381Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5381Test.java index ff10b0dd36..a05d56d343 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5381Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5381Test.java @@ -42,141 +42,137 @@ import org.junit.rules.TestName; public class AMQ5381Test { - public static final byte[] ORIG_MSG_CONTENT = randomByteArray(); - public static final String AMQ5381_EXCEPTION_MESSAGE = "java.util.zip.DataFormatException: incorrect header check"; + public static final byte[] ORIG_MSG_CONTENT = randomByteArray(); + public static final String AMQ5381_EXCEPTION_MESSAGE = "java.util.zip.DataFormatException: incorrect header check"; - private BrokerService brokerService; - private String brokerURI; + private BrokerService brokerService; + private String brokerURI; - @Rule public TestName name = new TestName(); + @Rule + public TestName name = new TestName(); - @Before - public void startBroker() throws Exception { - brokerService = new BrokerService(); - brokerService.setPersistent(false); - brokerService.setUseJmx(false); - brokerService.addConnector("tcp://localhost:0"); - brokerService.start(); - brokerService.waitUntilStarted(); + @Before + public void startBroker() throws Exception { + brokerService = new BrokerService(); + brokerService.setPersistent(false); + brokerService.setUseJmx(false); + brokerService.addConnector("tcp://localhost:0"); + brokerService.start(); + brokerService.waitUntilStarted(); - brokerURI = brokerService.getTransportConnectorByScheme("tcp").getPublishableConnectString(); - } + brokerURI = brokerService.getTransportConnectorByScheme("tcp").getPublishableConnectString(); + } - @After - public void stopBroker() throws Exception { - if (brokerService != null) { - brokerService.stop(); - } - } + @After + public void stopBroker() throws Exception { + if (brokerService != null) { + brokerService.stop(); + } + } - private ActiveMQConnection createConnection(boolean useCompression) throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURI); - factory.setUseCompression(useCompression); - Connection connection = factory.createConnection(); - connection.start(); - return (ActiveMQConnection) connection; - } + private ActiveMQConnection createConnection(boolean useCompression) throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURI); + factory.setUseCompression(useCompression); + Connection connection = factory.createConnection(); + connection.start(); + return (ActiveMQConnection) connection; + } - @Test - public void amq5381Test() throws Exception { + @Test + public void amq5381Test() throws Exception { - // Consumer Configured for (useCompression=true) - final ActiveMQConnection consumerConnection = createConnection(true); - final Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final Queue consumerQueue = consumerSession.createQueue(name.getMethodName()); - final MessageConsumer consumer = consumerSession.createConsumer(consumerQueue); + // Consumer Configured for (useCompression=true) + final ActiveMQConnection consumerConnection = createConnection(true); + final Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final Queue consumerQueue = consumerSession.createQueue(name.getMethodName()); + final MessageConsumer consumer = consumerSession.createConsumer(consumerQueue); - // Producer Configured for (useCompression=false) - final ActiveMQConnection producerConnection = createConnection(false); - final Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final Queue producerQueue = producerSession.createQueue(name.getMethodName()); + // Producer Configured for (useCompression=false) + final ActiveMQConnection producerConnection = createConnection(false); + final Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final Queue producerQueue = producerSession.createQueue(name.getMethodName()); - try { + try { - final ActiveMQBytesMessage messageProduced = (ActiveMQBytesMessage) producerSession.createBytesMessage(); - messageProduced.writeBytes(ORIG_MSG_CONTENT); - Assert.assertFalse(messageProduced.isReadOnlyBody()); + final ActiveMQBytesMessage messageProduced = (ActiveMQBytesMessage) producerSession.createBytesMessage(); + messageProduced.writeBytes(ORIG_MSG_CONTENT); + Assert.assertFalse(messageProduced.isReadOnlyBody()); - Assert.assertFalse( - "Produced Message's 'compressed' flag should remain false until the message is sent (where it will be compressed, if necessary)", - messageProduced.isCompressed()); + Assert.assertFalse("Produced Message's 'compressed' flag should remain false until the message is sent (where it will be compressed, if necessary)", messageProduced.isCompressed()); - final MessageProducer producer = producerSession.createProducer(null); - producer.send(producerQueue, messageProduced); + final MessageProducer producer = producerSession.createProducer(null); + producer.send(producerQueue, messageProduced); - Assert.assertEquals("Once sent, the produced Message's 'compressed' flag should match its Connection's 'useCompression' flag", - producerConnection.isUseCompression(), messageProduced.isCompressed()); + Assert.assertEquals("Once sent, the produced Message's 'compressed' flag should match its Connection's 'useCompression' flag", producerConnection.isUseCompression(), messageProduced.isCompressed()); - final ActiveMQBytesMessage messageConsumed = (ActiveMQBytesMessage) consumer.receive(); - Assert.assertNotNull(messageConsumed); - Assert.assertTrue("Consumed Message should be read-only", messageConsumed.isReadOnlyBody()); - Assert.assertEquals("Consumed Message's 'compressed' flag should match the produced Message's 'compressed' flag", - messageProduced.isCompressed(), messageConsumed.isCompressed()); + final ActiveMQBytesMessage messageConsumed = (ActiveMQBytesMessage) consumer.receive(); + Assert.assertNotNull(messageConsumed); + Assert.assertTrue("Consumed Message should be read-only", messageConsumed.isReadOnlyBody()); + Assert.assertEquals("Consumed Message's 'compressed' flag should match the produced Message's 'compressed' flag", messageProduced.isCompressed(), messageConsumed.isCompressed()); - // ensure consumed message content matches what was originally set - final byte[] consumedMsgContent = new byte[(int) messageConsumed.getBodyLength()]; - messageConsumed.readBytes(consumedMsgContent); + // ensure consumed message content matches what was originally set + final byte[] consumedMsgContent = new byte[(int) messageConsumed.getBodyLength()]; + messageConsumed.readBytes(consumedMsgContent); - Assert.assertTrue("Consumed Message content should match the original Message content", Arrays.equals(ORIG_MSG_CONTENT, consumedMsgContent)); + Assert.assertTrue("Consumed Message content should match the original Message content", Arrays.equals(ORIG_MSG_CONTENT, consumedMsgContent)); - // make message writable so the consumer can modify and reuse it - makeWritable(messageConsumed); + // make message writable so the consumer can modify and reuse it + makeWritable(messageConsumed); - // modify message, attempt to trigger DataFormatException due - // to old incorrect compression logic - try { - messageConsumed.setStringProperty(this.getClass().getName(), "test"); - } catch (JMSException jmsE) { - if (AMQ5381_EXCEPTION_MESSAGE.equals(jmsE.getMessage())) { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - jmsE.printStackTrace(pw); + // modify message, attempt to trigger DataFormatException due + // to old incorrect compression logic + try { + messageConsumed.setStringProperty(this.getClass().getName(), "test"); + } + catch (JMSException jmsE) { + if (AMQ5381_EXCEPTION_MESSAGE.equals(jmsE.getMessage())) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + jmsE.printStackTrace(pw); - Assert.fail("AMQ5381 Error State Achieved: attempted to decompress BytesMessage contents that are not compressed\n" + sw.toString()); - } else { - throw jmsE; - } + Assert.fail("AMQ5381 Error State Achieved: attempted to decompress BytesMessage contents that are not compressed\n" + sw.toString()); } + else { + throw jmsE; + } + } - Assert.assertEquals( - "The consumed Message's 'compressed' flag should still match the produced Message's 'compressed' flag after it has been made writable", - messageProduced.isCompressed(), messageConsumed.isCompressed()); + Assert.assertEquals("The consumed Message's 'compressed' flag should still match the produced Message's 'compressed' flag after it has been made writable", messageProduced.isCompressed(), messageConsumed.isCompressed()); - // simulate re-publishing message - simulatePublish(messageConsumed); + // simulate re-publishing message + simulatePublish(messageConsumed); - // ensure consumed message content matches what was originally set - final byte[] modifiedMsgContent = new byte[(int) messageConsumed.getBodyLength()]; - messageConsumed.readBytes(modifiedMsgContent); + // ensure consumed message content matches what was originally set + final byte[] modifiedMsgContent = new byte[(int) messageConsumed.getBodyLength()]; + messageConsumed.readBytes(modifiedMsgContent); - Assert.assertTrue( - "After the message properties are modified and it is re-published, its message content should still match the original message content", - Arrays.equals(ORIG_MSG_CONTENT, modifiedMsgContent)); - } finally { - producerSession.close(); - producerConnection.close(); - consumerSession.close(); - consumerConnection.close(); - } - } + Assert.assertTrue("After the message properties are modified and it is re-published, its message content should still match the original message content", Arrays.equals(ORIG_MSG_CONTENT, modifiedMsgContent)); + } + finally { + producerSession.close(); + producerConnection.close(); + consumerSession.close(); + consumerConnection.close(); + } + } - protected static final int MAX_RANDOM_BYTE_ARRAY_SIZE_KB = 128; + protected static final int MAX_RANDOM_BYTE_ARRAY_SIZE_KB = 128; - protected static byte[] randomByteArray() { - final Random random = new Random(); - final byte[] byteArray = new byte[random.nextInt(MAX_RANDOM_BYTE_ARRAY_SIZE_KB * 1024)]; - random.nextBytes(byteArray); + protected static byte[] randomByteArray() { + final Random random = new Random(); + final byte[] byteArray = new byte[random.nextInt(MAX_RANDOM_BYTE_ARRAY_SIZE_KB * 1024)]; + random.nextBytes(byteArray); - return byteArray; - } + return byteArray; + } - protected static void makeWritable(final ActiveMQMessage message) { - message.setReadOnlyBody(false); - message.setReadOnlyProperties(false); - } + protected static void makeWritable(final ActiveMQMessage message) { + message.setReadOnlyBody(false); + message.setReadOnlyProperties(false); + } - protected static void simulatePublish(final ActiveMQBytesMessage message) throws JMSException { - message.reset(); - message.onSend(); - } + protected static void simulatePublish(final ActiveMQBytesMessage message) throws JMSException { + message.reset(); + message.onSend(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5421Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5421Test.java index 751d488214..0e9e3105ec 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5421Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5421Test.java @@ -42,78 +42,78 @@ import org.slf4j.LoggerFactory; public class AMQ5421Test { - private static final Logger LOG = LoggerFactory.getLogger(AMQ5421Test.class); + private static final Logger LOG = LoggerFactory.getLogger(AMQ5421Test.class); - private static final int DEST_COUNT = 1000; - private final Destination[] destination = new Destination[DEST_COUNT]; - private final MessageProducer[] producer = new MessageProducer[DEST_COUNT]; - private BrokerService brokerService; - private String connectionUri; + private static final int DEST_COUNT = 1000; + private final Destination[] destination = new Destination[DEST_COUNT]; + private final MessageProducer[] producer = new MessageProducer[DEST_COUNT]; + private BrokerService brokerService; + private String connectionUri; - protected ConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory conFactory = new ActiveMQConnectionFactory(connectionUri); - conFactory.setWatchTopicAdvisories(false); - return conFactory; - } + protected ConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory conFactory = new ActiveMQConnectionFactory(connectionUri); + conFactory.setWatchTopicAdvisories(false); + return conFactory; + } - protected AbortSlowAckConsumerStrategy createSlowConsumerStrategy() { - AbortSlowAckConsumerStrategy strategy = new AbortSlowAckConsumerStrategy(); - strategy.setCheckPeriod(2000); - strategy.setMaxTimeSinceLastAck(5000); - strategy.setIgnoreIdleConsumers(false); + protected AbortSlowAckConsumerStrategy createSlowConsumerStrategy() { + AbortSlowAckConsumerStrategy strategy = new AbortSlowAckConsumerStrategy(); + strategy.setCheckPeriod(2000); + strategy.setMaxTimeSinceLastAck(5000); + strategy.setIgnoreIdleConsumers(false); - return strategy; - } + return strategy; + } - @Before - public void setUp() throws Exception { - brokerService = BrokerFactory.createBroker(new URI("broker://()/localhost?persistent=false&useJmx=true")); - PolicyEntry policy = new PolicyEntry(); + @Before + public void setUp() throws Exception { + brokerService = BrokerFactory.createBroker(new URI("broker://()/localhost?persistent=false&useJmx=true")); + PolicyEntry policy = new PolicyEntry(); - policy.setSlowConsumerStrategy(createSlowConsumerStrategy()); - policy.setQueuePrefetch(10); - policy.setTopicPrefetch(10); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - brokerService.setDestinationPolicy(pMap); - brokerService.addConnector("tcp://0.0.0.0:0"); - brokerService.start(); + policy.setSlowConsumerStrategy(createSlowConsumerStrategy()); + policy.setQueuePrefetch(10); + policy.setTopicPrefetch(10); + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); + brokerService.setDestinationPolicy(pMap); + brokerService.addConnector("tcp://0.0.0.0:0"); + brokerService.start(); - connectionUri = brokerService.getTransportConnectorByScheme("tcp").getPublishableConnectString(); - } + connectionUri = brokerService.getTransportConnectorByScheme("tcp").getPublishableConnectString(); + } - @Test - public void testManyTempDestinations() throws Exception { - Connection connection = createConnectionFactory().createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + @Test + public void testManyTempDestinations() throws Exception { + Connection connection = createConnectionFactory().createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - for (int i = 0; i < DEST_COUNT; i++) { - destination[i] = session.createTemporaryQueue(); - LOG.debug("Created temp queue: [}", i); - } + for (int i = 0; i < DEST_COUNT; i++) { + destination[i] = session.createTemporaryQueue(); + LOG.debug("Created temp queue: [}", i); + } - for (int i = 0; i < DEST_COUNT; i++) { - producer[i] = session.createProducer(destination[i]); - LOG.debug("Created producer: {}", i); - TextMessage msg = session.createTextMessage(" testMessage " + i); - producer[i].send(msg); - LOG.debug("message sent: {}", i); - MessageConsumer consumer = session.createConsumer(destination[i]); - Message message = consumer.receive(1000); - Assert.assertTrue(message.equals(msg)); - } + for (int i = 0; i < DEST_COUNT; i++) { + producer[i] = session.createProducer(destination[i]); + LOG.debug("Created producer: {}", i); + TextMessage msg = session.createTextMessage(" testMessage " + i); + producer[i].send(msg); + LOG.debug("message sent: {}", i); + MessageConsumer consumer = session.createConsumer(destination[i]); + Message message = consumer.receive(1000); + Assert.assertTrue(message.equals(msg)); + } - for (int i = 0; i < DEST_COUNT; i++) { - producer[i].close(); - } + for (int i = 0; i < DEST_COUNT; i++) { + producer[i].close(); + } - connection.close(); - } + connection.close(); + } - @After - public void tearDown() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - } + @After + public void tearDown() throws Exception { + brokerService.stop(); + brokerService.waitUntilStopped(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5450Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5450Test.java index 6a2dc52c07..21380e58f9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5450Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5450Test.java @@ -23,6 +23,7 @@ import javax.jms.Connection; import javax.jms.JMSException; import javax.jms.MessageProducer; import javax.jms.Session; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.region.Destination; @@ -36,159 +37,160 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import static org.junit.Assert.*; public class AMQ5450Test { - static final Logger LOG = LoggerFactory.getLogger(AMQ5450Test.class); - private final static int maxFileLength = 1024*1024*32; + static final Logger LOG = LoggerFactory.getLogger(AMQ5450Test.class); + private final static int maxFileLength = 1024 * 1024 * 32; - private final static String POSTFIX_DESTINATION_NAME = ".dlq"; + private final static String POSTFIX_DESTINATION_NAME = ".dlq"; - private final static String DESTINATION_NAME = "test" + POSTFIX_DESTINATION_NAME; - private final static String DESTINATION_NAME_2 = "2.test" + POSTFIX_DESTINATION_NAME; - private final static String DESTINATION_NAME_3 = "3.2.test" + POSTFIX_DESTINATION_NAME; + private final static String DESTINATION_NAME = "test" + POSTFIX_DESTINATION_NAME; + private final static String DESTINATION_NAME_2 = "2.test" + POSTFIX_DESTINATION_NAME; + private final static String DESTINATION_NAME_3 = "3.2.test" + POSTFIX_DESTINATION_NAME; - private final static String[] DESTS = new String[] {DESTINATION_NAME, DESTINATION_NAME_2, DESTINATION_NAME_3, DESTINATION_NAME, DESTINATION_NAME}; + private final static String[] DESTS = new String[]{DESTINATION_NAME, DESTINATION_NAME_2, DESTINATION_NAME_3, DESTINATION_NAME, DESTINATION_NAME}; + BrokerService broker; + private HashMap adapters = new HashMap(); - BrokerService broker; - private HashMap adapters = new HashMap(); + @After + public void tearDown() throws Exception { + broker.stop(); + } - @After - public void tearDown() throws Exception { - broker.stop(); - } + protected BrokerService createAndStartBroker(PersistenceAdapter persistenceAdapter) throws Exception { + BrokerService broker = new BrokerService(); + broker.setUseJmx(false); + broker.setBrokerName("localhost"); + broker.setPersistenceAdapter(persistenceAdapter); + broker.setDeleteAllMessagesOnStartup(true); + broker.start(); + broker.waitUntilStarted(); + return broker; + } - protected BrokerService createAndStartBroker(PersistenceAdapter persistenceAdapter) throws Exception { - BrokerService broker = new BrokerService(); - broker.setUseJmx(false); - broker.setBrokerName("localhost"); - broker.setPersistenceAdapter(persistenceAdapter); - broker.setDeleteAllMessagesOnStartup(true); - broker.start(); - broker.waitUntilStarted(); - return broker; - } + @Test + public void testPostFixMatch() throws Exception { + doTestPostFixMatch(false); + } - @Test - public void testPostFixMatch() throws Exception { - doTestPostFixMatch(false); - } + @Test + public void testPostFixCompositeMatch() throws Exception { + doTestPostFixMatch(true); + } - @Test - public void testPostFixCompositeMatch() throws Exception { - doTestPostFixMatch(true); - } + private void doTestPostFixMatch(boolean useComposite) throws Exception { + prepareBrokerWithMultiStore(useComposite); - private void doTestPostFixMatch(boolean useComposite) throws Exception { - prepareBrokerWithMultiStore(useComposite); + sendMessage(DESTINATION_NAME, "test 1"); + sendMessage(DESTINATION_NAME_2, "test 1"); + sendMessage(DESTINATION_NAME_3, "test 1"); - sendMessage(DESTINATION_NAME, "test 1"); - sendMessage(DESTINATION_NAME_2, "test 1"); - sendMessage(DESTINATION_NAME_3, "test 1"); + assertNotNull(broker.getDestination(new ActiveMQQueue(DESTINATION_NAME))); + assertNotNull(broker.getDestination(new ActiveMQQueue(DESTINATION_NAME_2))); + assertNotNull(broker.getDestination(new ActiveMQQueue(DESTINATION_NAME_3))); - assertNotNull(broker.getDestination(new ActiveMQQueue(DESTINATION_NAME))); - assertNotNull(broker.getDestination(new ActiveMQQueue(DESTINATION_NAME_2))); - assertNotNull(broker.getDestination(new ActiveMQQueue(DESTINATION_NAME_3))); + for (String dest : DESTS) { + Destination destination2 = broker.getDestination(new ActiveMQQueue(dest)); + assertNotNull(destination2); + assertEquals(1, destination2.getMessageStore().getMessageCount()); + } - for (String dest: DESTS) { - Destination destination2 = broker.getDestination(new ActiveMQQueue(dest)); - assertNotNull(destination2); - assertEquals(1, destination2.getMessageStore().getMessageCount()); - } + HashMap numDests = new HashMap(); + for (PersistenceAdapter pa : adapters.values()) { + numDests.put(pa.getDestinations().size(), pa); + } - HashMap numDests = new HashMap(); - for (PersistenceAdapter pa : adapters.values()) { - numDests.put(pa.getDestinations().size(), pa); - } + // ensure wildcard does not match any + assertTrue("0 in wildcard matcher", adapters.get(null).getDestinations().isEmpty()); - // ensure wildcard does not match any - assertTrue("0 in wildcard matcher", adapters.get(null).getDestinations().isEmpty()); + assertEquals("only two values", 2, numDests.size()); + assertTrue("0 in others", numDests.containsKey(0)); - assertEquals("only two values", 2, numDests.size()); - assertTrue("0 in others", numDests.containsKey(0)); + if (useComposite) { + assertTrue("3 in one", numDests.containsKey(3)); + } + else { + assertTrue("1 in some", numDests.containsKey(1)); + } - if (useComposite) { - assertTrue("3 in one", numDests.containsKey(3)); - } else { - assertTrue("1 in some", numDests.containsKey(1)); - } + } - } + protected KahaDBPersistenceAdapter createStore(boolean delete) throws IOException { + KahaDBPersistenceAdapter kaha = new KahaDBPersistenceAdapter(); + kaha.setJournalMaxFileLength(maxFileLength); + kaha.setCleanupInterval(5000); + if (delete) { + kaha.deleteAllMessages(); + } + return kaha; + } - protected KahaDBPersistenceAdapter createStore(boolean delete) throws IOException { - KahaDBPersistenceAdapter kaha = new KahaDBPersistenceAdapter(); - kaha.setJournalMaxFileLength(maxFileLength); - kaha.setCleanupInterval(5000); - if (delete) { - kaha.deleteAllMessages(); - } - return kaha; - } + public void prepareBrokerWithMultiStore(boolean compositeMatch) throws Exception { - public void prepareBrokerWithMultiStore(boolean compositeMatch) throws Exception { + MultiKahaDBPersistenceAdapter multiKahaDBPersistenceAdapter = new MultiKahaDBPersistenceAdapter(); + multiKahaDBPersistenceAdapter.deleteAllMessages(); + ArrayList adapters = new ArrayList(); - MultiKahaDBPersistenceAdapter multiKahaDBPersistenceAdapter = new MultiKahaDBPersistenceAdapter(); - multiKahaDBPersistenceAdapter.deleteAllMessages(); - ArrayList adapters = new ArrayList(); - - if (compositeMatch) { - StringBuffer compositeDestBuf = new StringBuffer(); - for (int i=1; i<=DESTS.length;i++) { - for (int j=0;j DESTS.length)) { - compositeDestBuf.append(","); - } + if (compositeMatch) { + StringBuffer compositeDestBuf = new StringBuffer(); + for (int i = 1; i <= DESTS.length; i++) { + for (int j = 0; j < i; j++) { + compositeDestBuf.append("*"); + if ((j + 1 == i)) { + compositeDestBuf.append(POSTFIX_DESTINATION_NAME); + } + else { + compositeDestBuf.append("."); + } } - adapters.add(createFilteredKahaDBByDestinationPrefix(compositeDestBuf.toString(), true)); + if (!(i + 1 > DESTS.length)) { + compositeDestBuf.append(","); + } + } + adapters.add(createFilteredKahaDBByDestinationPrefix(compositeDestBuf.toString(), true)); - } else { - // destination map does not do post fix wild card matches on paths, so we need to cover - // each path length - adapters.add(createFilteredKahaDBByDestinationPrefix("*" + POSTFIX_DESTINATION_NAME, true)); - adapters.add(createFilteredKahaDBByDestinationPrefix("*.*" + POSTFIX_DESTINATION_NAME, true)); - adapters.add(createFilteredKahaDBByDestinationPrefix("*.*.*" + POSTFIX_DESTINATION_NAME, true)); - adapters.add(createFilteredKahaDBByDestinationPrefix("*.*.*.*" + POSTFIX_DESTINATION_NAME, true)); - } + } + else { + // destination map does not do post fix wild card matches on paths, so we need to cover + // each path length + adapters.add(createFilteredKahaDBByDestinationPrefix("*" + POSTFIX_DESTINATION_NAME, true)); + adapters.add(createFilteredKahaDBByDestinationPrefix("*.*" + POSTFIX_DESTINATION_NAME, true)); + adapters.add(createFilteredKahaDBByDestinationPrefix("*.*.*" + POSTFIX_DESTINATION_NAME, true)); + adapters.add(createFilteredKahaDBByDestinationPrefix("*.*.*.*" + POSTFIX_DESTINATION_NAME, true)); + } - // ensure wildcard matcher is there for other dests - adapters.add(createFilteredKahaDBByDestinationPrefix(null, true)); + // ensure wildcard matcher is there for other dests + adapters.add(createFilteredKahaDBByDestinationPrefix(null, true)); - multiKahaDBPersistenceAdapter.setFilteredPersistenceAdapters(adapters); - broker = createAndStartBroker(multiKahaDBPersistenceAdapter); - } + multiKahaDBPersistenceAdapter.setFilteredPersistenceAdapters(adapters); + broker = createAndStartBroker(multiKahaDBPersistenceAdapter); + } - private FilteredKahaDBPersistenceAdapter createFilteredKahaDBByDestinationPrefix(String destinationPrefix, boolean deleteAllMessages) - throws IOException { - FilteredKahaDBPersistenceAdapter template = new FilteredKahaDBPersistenceAdapter(); - template.setPersistenceAdapter(createStore(deleteAllMessages)); - if (destinationPrefix != null) { - template.setQueue(destinationPrefix); - } - adapters.put(destinationPrefix, template.getPersistenceAdapter()); - return template; - } + private FilteredKahaDBPersistenceAdapter createFilteredKahaDBByDestinationPrefix(String destinationPrefix, + boolean deleteAllMessages) throws IOException { + FilteredKahaDBPersistenceAdapter template = new FilteredKahaDBPersistenceAdapter(); + template.setPersistenceAdapter(createStore(deleteAllMessages)); + if (destinationPrefix != null) { + template.setQueue(destinationPrefix); + } + adapters.put(destinationPrefix, template.getPersistenceAdapter()); + return template; + } - private void sendMessage(String destinationName, String message) throws JMSException { - ActiveMQConnectionFactory f = new ActiveMQConnectionFactory("vm://localhost"); - f.setAlwaysSyncSend(true); - Connection c = f.createConnection(); - c.start(); - Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = s.createProducer(new ActiveMQQueue(destinationName)); - producer.send(s.createTextMessage(message)); - producer.close(); - s.close(); - c.stop(); - } + private void sendMessage(String destinationName, String message) throws JMSException { + ActiveMQConnectionFactory f = new ActiveMQConnectionFactory("vm://localhost"); + f.setAlwaysSyncSend(true); + Connection c = f.createConnection(); + c.start(); + Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = s.createProducer(new ActiveMQQueue(destinationName)); + producer.send(s.createTextMessage(message)); + producer.close(); + s.close(); + c.stop(); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5567Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5567Test.java index a8739ae2da..df1f80a35d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5567Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ5567Test.java @@ -22,7 +22,9 @@ import javax.jms.JMSException; import javax.jms.TextMessage; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; + import junit.framework.Test; + import org.apache.activemq.broker.BrokerRestartTestSupport; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.StubConnection; @@ -47,182 +49,167 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AMQ5567Test extends BrokerRestartTestSupport { - protected static final Logger LOG = LoggerFactory.getLogger(AMQ5567Test.class); - ActiveMQQueue destination = new ActiveMQQueue("Q"); - @Override - protected void configureBroker(BrokerService broker) throws Exception { - super.configureBroker(broker); - broker.setPersistenceAdapter(persistenceAdapter); - } + protected static final Logger LOG = LoggerFactory.getLogger(AMQ5567Test.class); + ActiveMQQueue destination = new ActiveMQQueue("Q"); - protected PolicyEntry getDefaultPolicy() { - PolicyEntry policy = new PolicyEntry(); - policy.setMemoryLimit(60*1024); - return policy; - } + @Override + protected void configureBroker(BrokerService broker) throws Exception { + super.configureBroker(broker); + broker.setPersistenceAdapter(persistenceAdapter); + } - public void initCombosForTestPreparedTransactionNotDispatched() throws Exception { - PersistenceAdapter[] persistenceAdapters = new PersistenceAdapter[]{ - new KahaDBPersistenceAdapter(), - new LevelDBPersistenceAdapter(), - new JDBCPersistenceAdapter(JDBCPersistenceAdapter.createDataSource(IOHelper.getDefaultDataDirectory()), new OpenWireFormat()) - }; - for (PersistenceAdapter adapter : persistenceAdapters) { - adapter.setDirectory(new File(IOHelper.getDefaultDataDirectory())); - } - addCombinationValues("persistenceAdapter", persistenceAdapters); - } + protected PolicyEntry getDefaultPolicy() { + PolicyEntry policy = new PolicyEntry(); + policy.setMemoryLimit(60 * 1024); + return policy; + } - public void testPreparedTransactionNotDispatched() throws Exception { + public void initCombosForTestPreparedTransactionNotDispatched() throws Exception { + PersistenceAdapter[] persistenceAdapters = new PersistenceAdapter[]{new KahaDBPersistenceAdapter(), new LevelDBPersistenceAdapter(), new JDBCPersistenceAdapter(JDBCPersistenceAdapter.createDataSource(IOHelper.getDefaultDataDirectory()), new OpenWireFormat())}; + for (PersistenceAdapter adapter : persistenceAdapters) { + adapter.setDirectory(new File(IOHelper.getDefaultDataDirectory())); + } + addCombinationValues("persistenceAdapter", persistenceAdapters); + } - ActiveMQDestination destination = new ActiveMQQueue("Q"); + public void testPreparedTransactionNotDispatched() throws Exception { - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); + ActiveMQDestination destination = new ActiveMQQueue("Q"); + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - message.setTransactionId(txid); - connection.send(message); + XATransactionId txid = createXATransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + message.setTransactionId(txid); + connection.send(message); - connection.send(createPrepareTransaction(connectionInfo, txid)); + connection.send(createPrepareTransaction(connectionInfo, txid)); + // send another non tx, will poke dispatch + message = createMessage(producerInfo, destination); + message.setPersistent(true); + connection.send(message); - // send another non tx, will poke dispatch - message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); + // Since prepared but not committed.. only one should get delivered + StubConnection connectionC = createConnection(); + ConnectionInfo connectionInfoC = createConnectionInfo(); + SessionInfo sessionInfoC = createSessionInfo(connectionInfoC); + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfoC, destination); + connectionC.send(connectionInfoC); + connectionC.send(sessionInfoC); + connectionC.send(consumerInfo); + Message m = receiveMessage(connectionC, TimeUnit.SECONDS.toMillis(10)); + LOG.info("received: " + m); + assertNotNull("Got message", m); + assertNull("Got non tx message", m.getTransactionId()); - // Since prepared but not committed.. only one should get delivered - StubConnection connectionC = createConnection(); - ConnectionInfo connectionInfoC = createConnectionInfo(); - SessionInfo sessionInfoC = createSessionInfo(connectionInfoC); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfoC, destination); - connectionC.send(connectionInfoC); - connectionC.send(sessionInfoC); - connectionC.send(consumerInfo); + // cannot get the prepared message till commit + assertNull(receiveMessage(connectionC)); + assertNoMessagesLeft(connectionC); - Message m = receiveMessage(connectionC, TimeUnit.SECONDS.toMillis(10)); - LOG.info("received: " + m); - assertNotNull("Got message", m); - assertNull("Got non tx message", m.getTransactionId()); + LOG.info("commit: " + txid); + connection.request(createCommitTransaction2Phase(connectionInfo, txid)); - // cannot get the prepared message till commit - assertNull(receiveMessage(connectionC)); - assertNoMessagesLeft(connectionC); + m = receiveMessage(connectionC, TimeUnit.SECONDS.toMillis(10)); + LOG.info("received: " + m); + assertNotNull("Got non null message", m); - LOG.info("commit: " + txid); - connection.request(createCommitTransaction2Phase(connectionInfo, txid)); + } - m = receiveMessage(connectionC, TimeUnit.SECONDS.toMillis(10)); - LOG.info("received: " + m); - assertNotNull("Got non null message", m); + public void initCombosForTestCursorStoreSync() throws Exception { + PersistenceAdapter[] persistenceAdapters = new PersistenceAdapter[]{new KahaDBPersistenceAdapter(), new LevelDBPersistenceAdapter(), new JDBCPersistenceAdapter(JDBCPersistenceAdapter.createDataSource(IOHelper.getDefaultDataDirectory()), new OpenWireFormat())}; + for (PersistenceAdapter adapter : persistenceAdapters) { + adapter.setDirectory(new File(IOHelper.getDefaultDataDirectory())); + } + addCombinationValues("persistenceAdapter", persistenceAdapters); + } - } + public void testCursorStoreSync() throws Exception { - public void initCombosForTestCursorStoreSync() throws Exception { - PersistenceAdapter[] persistenceAdapters = new PersistenceAdapter[]{ - new KahaDBPersistenceAdapter(), - new LevelDBPersistenceAdapter(), - new JDBCPersistenceAdapter(JDBCPersistenceAdapter.createDataSource(IOHelper.getDefaultDataDirectory()), new OpenWireFormat()) - }; - for (PersistenceAdapter adapter : persistenceAdapters) { - adapter.setDirectory(new File(IOHelper.getDefaultDataDirectory())); - } - addCombinationValues("persistenceAdapter", persistenceAdapters); - } + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); - public void testCursorStoreSync() throws Exception { + XATransactionId txid = createXATransaction(sessionInfo); + connection.send(createBeginTransaction(connectionInfo, txid)); + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + message.setTransactionId(txid); + connection.request(message); - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); + connection.request(createPrepareTransaction(connectionInfo, txid)); + QueueViewMBean proxy = getProxyToQueueViewMBean(); + assertTrue("cache is enabled", proxy.isCacheEnabled()); - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - message.setTransactionId(txid); - connection.request(message); + // send another non tx, will fill cursor + String payload = new String(new byte[10 * 1024]); + for (int i = 0; i < 6; i++) { + message = createMessage(producerInfo, destination); + message.setPersistent(true); + ((TextMessage) message).setText(payload); + connection.request(message); + } - connection.request(createPrepareTransaction(connectionInfo, txid)); + assertTrue("cache is disabled", !proxy.isCacheEnabled()); - QueueViewMBean proxy = getProxyToQueueViewMBean(); - assertTrue("cache is enabled", proxy.isCacheEnabled()); + StubConnection connectionC = createConnection(); + ConnectionInfo connectionInfoC = createConnectionInfo(); + SessionInfo sessionInfoC = createSessionInfo(connectionInfoC); + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfoC, destination); + connectionC.send(connectionInfoC); + connectionC.send(sessionInfoC); + connectionC.send(consumerInfo); - // send another non tx, will fill cursor - String payload = new String(new byte[10*1024]); - for (int i=0; i<6; i++) { - message = createMessage(producerInfo, destination); - message.setPersistent(true); - ((TextMessage)message).setText(payload); - connection.request(message); - } + Message m = null; + for (int i = 0; i < 3; i++) { + m = receiveMessage(connectionC, TimeUnit.SECONDS.toMillis(10)); + LOG.info("received: " + m); + assertNotNull("Got message", m); + assertNull("Got non tx message", m.getTransactionId()); + connectionC.request(createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE)); + } - assertTrue("cache is disabled", !proxy.isCacheEnabled()); + LOG.info("commit: " + txid); + connection.request(createCommitTransaction2Phase(connectionInfo, txid)); + // consume the rest including the 2pc send in TX - StubConnection connectionC = createConnection(); - ConnectionInfo connectionInfoC = createConnectionInfo(); - SessionInfo sessionInfoC = createSessionInfo(connectionInfoC); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfoC, destination); - connectionC.send(connectionInfoC); - connectionC.send(sessionInfoC); - connectionC.send(consumerInfo); - - Message m = null; - for (int i=0; i<3; i++) { - m = receiveMessage(connectionC, TimeUnit.SECONDS.toMillis(10)); - LOG.info("received: " + m); - assertNotNull("Got message", m); + for (int i = 0; i < 4; i++) { + m = receiveMessage(connectionC, TimeUnit.SECONDS.toMillis(10)); + LOG.info("received[" + i + "] " + m); + assertNotNull("Got message", m); + if (i == 3) { + assertNotNull("Got tx message", m.getTransactionId()); + } + else { assertNull("Got non tx message", m.getTransactionId()); - connectionC.request(createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE)); - } + } + connectionC.request(createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE)); + } + } - LOG.info("commit: " + txid); - connection.request(createCommitTransaction2Phase(connectionInfo, txid)); - // consume the rest including the 2pc send in TX + private QueueViewMBean getProxyToQueueViewMBean() throws MalformedObjectNameException, JMSException { + ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq" + ":destinationType=Queue,destinationName=" + destination.getQueueName() + ",type=Broker,brokerName=localhost"); + QueueViewMBean proxy = (QueueViewMBean) broker.getManagementContext().newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); + return proxy; + } - for (int i=0; i<4; i++) { - m = receiveMessage(connectionC, TimeUnit.SECONDS.toMillis(10)); - LOG.info("received[" + i + "] " + m); - assertNotNull("Got message", m); - if (i==3 ) { - assertNotNull("Got tx message", m.getTransactionId()); - } else { - assertNull("Got non tx message", m.getTransactionId()); - } - connectionC.request(createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE)); - } - } - - private QueueViewMBean getProxyToQueueViewMBean() - throws MalformedObjectNameException, JMSException { - ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq" - + ":destinationType=Queue,destinationName=" + destination.getQueueName() - + ",type=Broker,brokerName=localhost"); - QueueViewMBean proxy = (QueueViewMBean) broker.getManagementContext() - .newProxyInstance(queueViewMBeanName, - QueueViewMBean.class, true); - return proxy; - } - - public static Test suite() { - return suite(AMQ5567Test.class); - } + public static Test suite() { + return suite(AMQ5567Test.class); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/ActiveMQSlowConsumerManualTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/ActiveMQSlowConsumerManualTest.java index b32c7ad8ba..e8414d59d3 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/ActiveMQSlowConsumerManualTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/ActiveMQSlowConsumerManualTest.java @@ -30,6 +30,7 @@ import javax.jms.MessageListener; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.region.policy.ConstantPendingMessageLimitStrategy; @@ -45,188 +46,205 @@ import org.junit.Test; * https://issues.apache.org/jira/browse/AMQ-3607 */ public class ActiveMQSlowConsumerManualTest { - private static final int PORT = 12345; - private static final ActiveMQTopic TOPIC = new ActiveMQTopic("TOPIC"); - private static final String URL = "nio://localhost:" + PORT + "?socket.tcpNoDelay=true"; - @Test(timeout = 60000) - public void testDefaultSettings() throws Exception { - runTest("testDefaultSettings", 30, -1, -1, false, false, false, false); - } + private static final int PORT = 12345; + private static final ActiveMQTopic TOPIC = new ActiveMQTopic("TOPIC"); + private static final String URL = "nio://localhost:" + PORT + "?socket.tcpNoDelay=true"; - @Test(timeout = 60000) - public void testDefaultSettingsWithOptimiseAcknowledge() throws Exception { - runTest("testDefaultSettingsWithOptimiseAcknowledge", 30, -1, -1, false, false, true, false); - } + @Test(timeout = 60000) + public void testDefaultSettings() throws Exception { + runTest("testDefaultSettings", 30, -1, -1, false, false, false, false); + } - @Test(timeout = 60000) - public void testBounded() throws Exception { - runTest("testBounded", 30, 5, 25, false, false, false, false); - } + @Test(timeout = 60000) + public void testDefaultSettingsWithOptimiseAcknowledge() throws Exception { + runTest("testDefaultSettingsWithOptimiseAcknowledge", 30, -1, -1, false, false, true, false); + } - @Test(timeout = 60000) - public void testBoundedWithOptimiseAcknowledge() throws Exception { - runTest("testBoundedWithOptimiseAcknowledge", 30, 5, 25, false, false, true, false); - } + @Test(timeout = 60000) + public void testBounded() throws Exception { + runTest("testBounded", 30, 5, 25, false, false, false, false); + } - public void runTest(String name, int sendMessageCount, int prefetchLimit, int messageLimit, boolean evictOldestMessage, boolean disableFlowControl, boolean optimizeAcknowledge, boolean persistent) throws Exception { - BrokerService broker = createBroker(persistent); - broker.setDestinationPolicy(buildPolicy(TOPIC, prefetchLimit, messageLimit, evictOldestMessage, disableFlowControl)); - broker.start(); + @Test(timeout = 60000) + public void testBoundedWithOptimiseAcknowledge() throws Exception { + runTest("testBoundedWithOptimiseAcknowledge", 30, 5, 25, false, false, true, false); + } - // Slow consumer - Session slowConsumerSession = buildSession("SlowConsumer", URL, optimizeAcknowledge); - final CountDownLatch blockSlowConsumer = new CountDownLatch(1); - final AtomicInteger slowConsumerReceiveCount = new AtomicInteger(); - final List slowConsumerReceived = sendMessageCount <= 1000 ? new ArrayList() : null; - MessageConsumer slowConsumer = createSubscriber(slowConsumerSession, - new MessageListener() { - @Override - public void onMessage(Message message) { - try { - slowConsumerReceiveCount.incrementAndGet(); - int count = Integer.parseInt(((TextMessage) message).getText()); - if (slowConsumerReceived != null) slowConsumerReceived.add(count); - if (count % 10000 == 0) System.out.println("SlowConsumer: Receive " + count); - blockSlowConsumer.await(); - } catch (Exception ignored) { - } - } - } - ); + public void runTest(String name, + int sendMessageCount, + int prefetchLimit, + int messageLimit, + boolean evictOldestMessage, + boolean disableFlowControl, + boolean optimizeAcknowledge, + boolean persistent) throws Exception { + BrokerService broker = createBroker(persistent); + broker.setDestinationPolicy(buildPolicy(TOPIC, prefetchLimit, messageLimit, evictOldestMessage, disableFlowControl)); + broker.start(); - // Fast consumer - Session fastConsumerSession = buildSession("FastConsumer", URL, optimizeAcknowledge); - final AtomicInteger fastConsumerReceiveCount = new AtomicInteger(); - final List fastConsumerReceived = sendMessageCount <= 1000 ? new ArrayList() : null; - MessageConsumer fastConsumer = createSubscriber(fastConsumerSession, - new MessageListener() { - @Override - public void onMessage(Message message) { - try { - fastConsumerReceiveCount.incrementAndGet(); - TimeUnit.MILLISECONDS.sleep(5); - int count = Integer.parseInt(((TextMessage) message).getText()); - if (fastConsumerReceived != null) fastConsumerReceived.add(count); - if (count % 10000 == 0) System.out.println("FastConsumer: Receive " + count); - } catch (Exception ignored) { - } - } - } - ); + // Slow consumer + Session slowConsumerSession = buildSession("SlowConsumer", URL, optimizeAcknowledge); + final CountDownLatch blockSlowConsumer = new CountDownLatch(1); + final AtomicInteger slowConsumerReceiveCount = new AtomicInteger(); + final List slowConsumerReceived = sendMessageCount <= 1000 ? new ArrayList() : null; + MessageConsumer slowConsumer = createSubscriber(slowConsumerSession, new MessageListener() { + @Override + public void onMessage(Message message) { + try { + slowConsumerReceiveCount.incrementAndGet(); + int count = Integer.parseInt(((TextMessage) message).getText()); + if (slowConsumerReceived != null) + slowConsumerReceived.add(count); + if (count % 10000 == 0) + System.out.println("SlowConsumer: Receive " + count); + blockSlowConsumer.await(); + } + catch (Exception ignored) { + } + } + }); - // Wait for consumers to connect - Thread.sleep(500); + // Fast consumer + Session fastConsumerSession = buildSession("FastConsumer", URL, optimizeAcknowledge); + final AtomicInteger fastConsumerReceiveCount = new AtomicInteger(); + final List fastConsumerReceived = sendMessageCount <= 1000 ? new ArrayList() : null; + MessageConsumer fastConsumer = createSubscriber(fastConsumerSession, new MessageListener() { + @Override + public void onMessage(Message message) { + try { + fastConsumerReceiveCount.incrementAndGet(); + TimeUnit.MILLISECONDS.sleep(5); + int count = Integer.parseInt(((TextMessage) message).getText()); + if (fastConsumerReceived != null) + fastConsumerReceived.add(count); + if (count % 10000 == 0) + System.out.println("FastConsumer: Receive " + count); + } + catch (Exception ignored) { + } + } + }); - // Publisher - AtomicInteger sentCount = new AtomicInteger(); - List sent = sendMessageCount <= 1000 ? new ArrayList() : null; - Session publisherSession = buildSession("Publisher", URL, optimizeAcknowledge); - MessageProducer publisher = createPublisher(publisherSession); - for (int i = 0; i < sendMessageCount; i++) { - sentCount.incrementAndGet(); - if (sent != null) sent.add(i); - if (i % 10000 == 0) System.out.println("Publisher: Send " + i); - publisher.send(publisherSession.createTextMessage(Integer.toString(i))); - } + // Wait for consumers to connect + Thread.sleep(500); - // Wait for messages to arrive - Thread.sleep(500); + // Publisher + AtomicInteger sentCount = new AtomicInteger(); + List sent = sendMessageCount <= 1000 ? new ArrayList() : null; + Session publisherSession = buildSession("Publisher", URL, optimizeAcknowledge); + MessageProducer publisher = createPublisher(publisherSession); + for (int i = 0; i < sendMessageCount; i++) { + sentCount.incrementAndGet(); + if (sent != null) + sent.add(i); + if (i % 10000 == 0) + System.out.println("Publisher: Send " + i); + publisher.send(publisherSession.createTextMessage(Integer.toString(i))); + } - System.out.println(name + ": Publisher Sent: " + sentCount + " " + sent); - System.out.println(name + ": Whilst slow consumer blocked:"); - System.out.println("\t\t- SlowConsumer Received: " + slowConsumerReceiveCount + " " + slowConsumerReceived); - System.out.println("\t\t- FastConsumer Received: " + fastConsumerReceiveCount + " " + fastConsumerReceived); + // Wait for messages to arrive + Thread.sleep(500); - // Unblock slow consumer - blockSlowConsumer.countDown(); + System.out.println(name + ": Publisher Sent: " + sentCount + " " + sent); + System.out.println(name + ": Whilst slow consumer blocked:"); + System.out.println("\t\t- SlowConsumer Received: " + slowConsumerReceiveCount + " " + slowConsumerReceived); + System.out.println("\t\t- FastConsumer Received: " + fastConsumerReceiveCount + " " + fastConsumerReceived); - // Wait for messages to arrive - Thread.sleep(500); + // Unblock slow consumer + blockSlowConsumer.countDown(); - System.out.println(name + ": After slow consumer unblocked:"); - System.out.println("\t\t- SlowConsumer Received: " + slowConsumerReceiveCount + " " + slowConsumerReceived); - System.out.println("\t\t- FastConsumer Received: " + fastConsumerReceiveCount + " " + fastConsumerReceived); - System.out.println(); + // Wait for messages to arrive + Thread.sleep(500); - publisher.close(); - publisherSession.close(); - slowConsumer.close(); - slowConsumerSession.close(); - fastConsumer.close(); - fastConsumerSession.close(); - broker.stop(); + System.out.println(name + ": After slow consumer unblocked:"); + System.out.println("\t\t- SlowConsumer Received: " + slowConsumerReceiveCount + " " + slowConsumerReceived); + System.out.println("\t\t- FastConsumer Received: " + fastConsumerReceiveCount + " " + fastConsumerReceived); + System.out.println(); - Assert.assertEquals("Fast consumer missed messages whilst slow consumer was blocking", sent, fastConsumerReceived); - // this is too timine dependent as sometimes there is message eviction, would need to check the dlq - //Assert.assertEquals("Slow consumer received incorrect message count", Math.min(sendMessageCount, prefetchLimit + (messageLimit > 0 ? messageLimit : Integer.MAX_VALUE)), slowConsumerReceived.size()); - } + publisher.close(); + publisherSession.close(); + slowConsumer.close(); + slowConsumerSession.close(); + fastConsumer.close(); + fastConsumerSession.close(); + broker.stop(); - private static BrokerService createBroker(boolean persistent) throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("TestBroker"); - broker.setPersistent(persistent); - broker.addConnector(URL); - return broker; - } + Assert.assertEquals("Fast consumer missed messages whilst slow consumer was blocking", sent, fastConsumerReceived); + // this is too timine dependent as sometimes there is message eviction, would need to check the dlq + //Assert.assertEquals("Slow consumer received incorrect message count", Math.min(sendMessageCount, prefetchLimit + (messageLimit > 0 ? messageLimit : Integer.MAX_VALUE)), slowConsumerReceived.size()); + } - private static MessageConsumer createSubscriber(Session session, MessageListener messageListener) throws JMSException { - MessageConsumer consumer = session.createConsumer(TOPIC); - consumer.setMessageListener(messageListener); - return consumer; - } + private static BrokerService createBroker(boolean persistent) throws Exception { + BrokerService broker = new BrokerService(); + broker.setBrokerName("TestBroker"); + broker.setPersistent(persistent); + broker.addConnector(URL); + return broker; + } - private static MessageProducer createPublisher(Session session) throws JMSException { - MessageProducer producer = session.createProducer(TOPIC); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - return producer; - } + private static MessageConsumer createSubscriber(Session session, + MessageListener messageListener) throws JMSException { + MessageConsumer consumer = session.createConsumer(TOPIC); + consumer.setMessageListener(messageListener); + return consumer; + } - private static Session buildSession(String clientId, String url, boolean optimizeAcknowledge) throws JMSException { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url); + private static MessageProducer createPublisher(Session session) throws JMSException { + MessageProducer producer = session.createProducer(TOPIC); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + return producer; + } - connectionFactory.setCopyMessageOnSend(false); - connectionFactory.setDisableTimeStampsByDefault(true); - connectionFactory.setOptimizeAcknowledge(optimizeAcknowledge); - if (optimizeAcknowledge) { - connectionFactory.setOptimizeAcknowledgeTimeOut(1); - } + private static Session buildSession(String clientId, String url, boolean optimizeAcknowledge) throws JMSException { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url); - Connection connection = connectionFactory.createConnection(); - connection.setClientID(clientId); + connectionFactory.setCopyMessageOnSend(false); + connectionFactory.setDisableTimeStampsByDefault(true); + connectionFactory.setOptimizeAcknowledge(optimizeAcknowledge); + if (optimizeAcknowledge) { + connectionFactory.setOptimizeAcknowledgeTimeOut(1); + } - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Connection connection = connectionFactory.createConnection(); + connection.setClientID(clientId); - connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - return session; - } + connection.start(); - private static PolicyMap buildPolicy(ActiveMQTopic topic, int prefetchLimit, int messageLimit, boolean evictOldestMessage, boolean disableFlowControl) { - PolicyMap policyMap = new PolicyMap(); + return session; + } - PolicyEntry policyEntry = new PolicyEntry(); + private static PolicyMap buildPolicy(ActiveMQTopic topic, + int prefetchLimit, + int messageLimit, + boolean evictOldestMessage, + boolean disableFlowControl) { + PolicyMap policyMap = new PolicyMap(); - if (evictOldestMessage) { - policyEntry.setMessageEvictionStrategy(new OldestMessageEvictionStrategy()); - } + PolicyEntry policyEntry = new PolicyEntry(); - if (disableFlowControl) { - policyEntry.setProducerFlowControl(false); - } + if (evictOldestMessage) { + policyEntry.setMessageEvictionStrategy(new OldestMessageEvictionStrategy()); + } - if (prefetchLimit > 0) { - policyEntry.setTopicPrefetch(prefetchLimit); - } + if (disableFlowControl) { + policyEntry.setProducerFlowControl(false); + } - if (messageLimit > 0) { - ConstantPendingMessageLimitStrategy messageLimitStrategy = new ConstantPendingMessageLimitStrategy(); - messageLimitStrategy.setLimit(messageLimit); - policyEntry.setPendingMessageLimitStrategy(messageLimitStrategy); - } + if (prefetchLimit > 0) { + policyEntry.setTopicPrefetch(prefetchLimit); + } - policyMap.put(topic, policyEntry); + if (messageLimit > 0) { + ConstantPendingMessageLimitStrategy messageLimitStrategy = new ConstantPendingMessageLimitStrategy(); + messageLimitStrategy.setLimit(messageLimit); + policyEntry.setPendingMessageLimitStrategy(messageLimitStrategy); + } - return policyMap; - } + policyMap.put(topic, policyEntry); + + return policyMap; + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/ConnectionPerMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/ConnectionPerMessageTest.java index 8c580a9bc1..ca053257d0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/ConnectionPerMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/ConnectionPerMessageTest.java @@ -15,9 +15,8 @@ * limitations under the License. */ - - package org.apache.activemq.bugs; + import javax.jms.Connection; import javax.jms.DeliveryMode; import javax.jms.JMSException; @@ -34,71 +33,72 @@ import org.slf4j.LoggerFactory; public class ConnectionPerMessageTest extends EmbeddedBrokerTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(ConnectionPerMessageTest.class); - private static final int COUNT = 2000; - protected String bindAddress; + private static final Logger LOG = LoggerFactory.getLogger(ConnectionPerMessageTest.class); + private static final int COUNT = 2000; + protected String bindAddress; - public void testConnectionPerMessage() throws Exception { - final String topicName = "test.topic"; + public void testConnectionPerMessage() throws Exception { + final String topicName = "test.topic"; - LOG.info("Initializing connection factory for JMS to URL: " - + bindAddress); - final ActiveMQConnectionFactory normalFactory = new ActiveMQConnectionFactory(); - normalFactory.setBrokerURL(bindAddress); - for (int i = 0; i < COUNT; i++) { + LOG.info("Initializing connection factory for JMS to URL: " + bindAddress); + final ActiveMQConnectionFactory normalFactory = new ActiveMQConnectionFactory(); + normalFactory.setBrokerURL(bindAddress); + for (int i = 0; i < COUNT; i++) { - if (i % 100 == 0) { - LOG.info(new Integer(i).toString()); - } + if (i % 100 == 0) { + LOG.info(new Integer(i).toString()); + } - Connection conn = null; - try { + Connection conn = null; + try { - conn = normalFactory.createConnection(); - final Session session = conn.createSession(false, - Session.AUTO_ACKNOWLEDGE); - final Topic topic = session.createTopic(topicName); - final MessageProducer producer = session.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); + conn = normalFactory.createConnection(); + final Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + final Topic topic = session.createTopic(topicName); + final MessageProducer producer = session.createProducer(topic); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); - final MapMessage m = session.createMapMessage(); - m.setInt("hey", i); + final MapMessage m = session.createMapMessage(); + m.setInt("hey", i); - producer.send(m); + producer.send(m); - } catch (JMSException e) { - LOG.warn(e.getMessage(), e); - } finally { - if (conn != null) - try { - conn.close(); - } catch (JMSException e) { - LOG.warn(e.getMessage(), e); - } - } - } - } + } + catch (JMSException e) { + LOG.warn(e.getMessage(), e); + } + finally { + if (conn != null) + try { + conn.close(); + } + catch (JMSException e) { + LOG.warn(e.getMessage(), e); + } + } + } + } - protected void setUp() throws Exception { - bindAddress = "vm://localhost"; - super.setUp(); - } + protected void setUp() throws Exception { + bindAddress = "vm://localhost"; + super.setUp(); + } - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setDeleteAllMessagesOnStartup(true); - answer.setUseJmx(false); - answer.setPersistent(isPersistent()); - answer.addConnector(bindAddress); - return answer; - } + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + answer.setDeleteAllMessagesOnStartup(true); + answer.setUseJmx(false); + answer.setPersistent(isPersistent()); + answer.addConnector(bindAddress); + return answer; + } - protected boolean isPersistent() { - return true; - } + protected boolean isPersistent() { + return true; + } - protected void tearDown() throws Exception { - super.tearDown(); - } + protected void tearDown() throws Exception { + super.tearDown(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/CraigsBugTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/CraigsBugTest.java index d71a9e42a6..f2d245e759 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/CraigsBugTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/CraigsBugTest.java @@ -30,39 +30,41 @@ import java.util.concurrent.TimeUnit; public class CraigsBugTest extends EmbeddedBrokerTestSupport { - private String connectionUri; + private String connectionUri; - public void testConnectionFactory() throws Exception { - final ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(connectionUri); - final ActiveMQQueue queue = new ActiveMQQueue("testqueue"); - final Connection conn = cf.createConnection(); + public void testConnectionFactory() throws Exception { + final ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(connectionUri); + final ActiveMQQueue queue = new ActiveMQQueue("testqueue"); + final Connection conn = cf.createConnection(); - Runnable r = new Runnable() { - public void run() { - try { - Session session = conn.createSession(false, 1); - MessageConsumer consumer = session.createConsumer(queue, null); - consumer.receive(1000); - } catch (JMSException e) { - e.printStackTrace(); - } + Runnable r = new Runnable() { + public void run() { + try { + Session session = conn.createSession(false, 1); + MessageConsumer consumer = session.createConsumer(queue, null); + consumer.receive(1000); } - }; - new Thread(r).start(); - conn.start(); + catch (JMSException e) { + e.printStackTrace(); + } + } + }; + new Thread(r).start(); + conn.start(); - try { - new CountDownLatch(1).await(3, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } + try { + new CountDownLatch(1).await(3, TimeUnit.SECONDS); + } + catch (InterruptedException e) { + e.printStackTrace(); + } + } - protected void setUp() throws Exception { - bindAddress = "tcp://localhost:0"; - super.setUp(); + protected void setUp() throws Exception { + bindAddress = "tcp://localhost:0"; + super.setUp(); - connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); - } + connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/DoubleExpireTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/DoubleExpireTest.java index bb669434e2..f493eb9557 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/DoubleExpireTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/DoubleExpireTest.java @@ -32,114 +32,102 @@ import org.junit.Assert; public class DoubleExpireTest extends EmbeddedBrokerTestSupport { - private static final long MESSAGE_TTL_MILLIS = 1000; - private static final long MAX_TEST_TIME_MILLIS = 60000; + private static final long MESSAGE_TTL_MILLIS = 1000; + private static final long MAX_TEST_TIME_MILLIS = 60000; - public void setUp() throws Exception { - setAutoFail(true); - setMaxTestTime(MAX_TEST_TIME_MILLIS); - super.setUp(); - } + public void setUp() throws Exception { + setAutoFail(true); + setMaxTestTime(MAX_TEST_TIME_MILLIS); + super.setUp(); + } - /** - * This test verifies that a message that expires can be be resent to queue - * with a new expiration and that it will be processed as a new message and - * allowed to re-expire. - *

    - * NOTE: This test fails on AMQ 5.4.2 because the originalExpiration - * timestamp is not cleared when the message is resent. - */ - public void testDoubleExpireWithoutMove() throws Exception { - // Create the default dead letter queue. - final ActiveMQDestination DLQ = createDestination("ActiveMQ.DLQ"); + /** + * This test verifies that a message that expires can be be resent to queue + * with a new expiration and that it will be processed as a new message and + * allowed to re-expire. + *

    + * NOTE: This test fails on AMQ 5.4.2 because the originalExpiration + * timestamp is not cleared when the message is resent. + */ + public void testDoubleExpireWithoutMove() throws Exception { + // Create the default dead letter queue. + final ActiveMQDestination DLQ = createDestination("ActiveMQ.DLQ"); - Connection conn = createConnection(); - try { - conn.start(); - Session session = conn.createSession(false, - Session.AUTO_ACKNOWLEDGE); + Connection conn = createConnection(); + try { + conn.start(); + Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - // Verify that the test queue and DLQ are empty. - Assert.assertEquals(0, getSize(destination)); - Assert.assertEquals(0, getSize(DLQ)); + // Verify that the test queue and DLQ are empty. + Assert.assertEquals(0, getSize(destination)); + Assert.assertEquals(0, getSize(DLQ)); - // Enqueue a message to the test queue that will expire after 1s. - MessageProducer producer = session.createProducer(destination); - Message testMessage = session.createTextMessage("test message"); - producer.send(testMessage, Message.DEFAULT_DELIVERY_MODE, - Message.DEFAULT_PRIORITY, MESSAGE_TTL_MILLIS); - Assert.assertEquals(1, getSize(destination)); + // Enqueue a message to the test queue that will expire after 1s. + MessageProducer producer = session.createProducer(destination); + Message testMessage = session.createTextMessage("test message"); + producer.send(testMessage, Message.DEFAULT_DELIVERY_MODE, Message.DEFAULT_PRIORITY, MESSAGE_TTL_MILLIS); + Assert.assertEquals(1, getSize(destination)); - // Wait for the message to expire. - waitForSize(destination, 0, MAX_TEST_TIME_MILLIS); - Assert.assertEquals(1, getSize(DLQ)); + // Wait for the message to expire. + waitForSize(destination, 0, MAX_TEST_TIME_MILLIS); + Assert.assertEquals(1, getSize(DLQ)); - // Consume the message from the DLQ and re-enqueue it to the test - // queue so that it expires after 1s. - MessageConsumer consumer = session.createConsumer(DLQ); - Message expiredMessage = consumer.receive(); - Assert.assertEquals(testMessage.getJMSMessageID(), expiredMessage - .getJMSMessageID()); + // Consume the message from the DLQ and re-enqueue it to the test + // queue so that it expires after 1s. + MessageConsumer consumer = session.createConsumer(DLQ); + Message expiredMessage = consumer.receive(); + Assert.assertEquals(testMessage.getJMSMessageID(), expiredMessage.getJMSMessageID()); - producer.send(expiredMessage, Message.DEFAULT_DELIVERY_MODE, - Message.DEFAULT_PRIORITY, MESSAGE_TTL_MILLIS); - Assert.assertEquals(1, getSize(destination)); - Assert.assertEquals(0, getSize(DLQ)); + producer.send(expiredMessage, Message.DEFAULT_DELIVERY_MODE, Message.DEFAULT_PRIORITY, MESSAGE_TTL_MILLIS); + Assert.assertEquals(1, getSize(destination)); + Assert.assertEquals(0, getSize(DLQ)); - // Verify that the resent message is "different" in that it has - // another ID. - Assert.assertNotSame(testMessage.getJMSMessageID(), expiredMessage - .getJMSMessageID()); + // Verify that the resent message is "different" in that it has + // another ID. + Assert.assertNotSame(testMessage.getJMSMessageID(), expiredMessage.getJMSMessageID()); - // Wait for the message to re-expire. - waitForSize(destination, 0, MAX_TEST_TIME_MILLIS); - Assert.assertEquals(1, getSize(DLQ)); + // Wait for the message to re-expire. + waitForSize(destination, 0, MAX_TEST_TIME_MILLIS); + Assert.assertEquals(1, getSize(DLQ)); - // Re-consume the message from the DLQ. - Message reexpiredMessage = consumer.receive(); - Assert.assertEquals(expiredMessage.getJMSMessageID(), reexpiredMessage - .getJMSMessageID()); - } finally { - conn.close(); - } - } + // Re-consume the message from the DLQ. + Message reexpiredMessage = consumer.receive(); + Assert.assertEquals(expiredMessage.getJMSMessageID(), reexpiredMessage.getJMSMessageID()); + } + finally { + conn.close(); + } + } - /** - * A helper method that returns the embedded broker's implementation of a - * JMS queue. - */ - private Queue getPhysicalDestination(ActiveMQDestination destination) - throws Exception { - return (Queue) broker.getAdminView().getBroker().getDestinationMap() - .get(destination); - } + /** + * A helper method that returns the embedded broker's implementation of a + * JMS queue. + */ + private Queue getPhysicalDestination(ActiveMQDestination destination) throws Exception { + return (Queue) broker.getAdminView().getBroker().getDestinationMap().get(destination); + } - /** - * A helper method that returns the size of the specified queue/topic. - */ - private long getSize(ActiveMQDestination destination) throws Exception { - return getPhysicalDestination(destination) != null ? getPhysicalDestination( - destination).getDestinationStatistics().getMessages() - .getCount() - : 0; - } + /** + * A helper method that returns the size of the specified queue/topic. + */ + private long getSize(ActiveMQDestination destination) throws Exception { + return getPhysicalDestination(destination) != null ? getPhysicalDestination(destination).getDestinationStatistics().getMessages().getCount() : 0; + } - /** - * A helper method that waits for a destination to reach a certain size. - */ - private void waitForSize(ActiveMQDestination destination, int size, - long timeoutMillis) throws Exception, TimeoutException { - long startTimeMillis = System.currentTimeMillis(); + /** + * A helper method that waits for a destination to reach a certain size. + */ + private void waitForSize(ActiveMQDestination destination, + int size, + long timeoutMillis) throws Exception, TimeoutException { + long startTimeMillis = System.currentTimeMillis(); - while (getSize(destination) != size - && System.currentTimeMillis() < (startTimeMillis + timeoutMillis)) { - Thread.sleep(250); - } + while (getSize(destination) != size && System.currentTimeMillis() < (startTimeMillis + timeoutMillis)) { + Thread.sleep(250); + } - if (getSize(destination) != size) { - throw new TimeoutException("Destination " - + destination.getPhysicalName() + " did not reach size " - + size + " within " + timeoutMillis + "ms."); - } - } + if (getSize(destination) != size) { + throw new TimeoutException("Destination " + destination.getPhysicalName() + " did not reach size " + size + " within " + timeoutMillis + "ms."); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/DurableConsumerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/DurableConsumerTest.java index eeee82b543..06c3568ee6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/DurableConsumerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/DurableConsumerTest.java @@ -43,7 +43,9 @@ import javax.jms.TopicPublisher; import javax.jms.TopicSession; import javax.jms.TopicSubscriber; import javax.management.ObjectName; + import junit.framework.Test; + import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.CombinationTestSupport; @@ -59,405 +61,413 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * A Test case for AMQ-1479 + * A Test case for AMQ-1479 */ -public class DurableConsumerTest extends CombinationTestSupport{ - private static final Logger LOG = LoggerFactory.getLogger(DurableConsumerTest.class); - private static int COUNT = 1024; - private static String CONSUMER_NAME = "DURABLE_TEST"; - protected BrokerService broker; - - protected String bindAddress = "tcp://localhost:61616"; - - protected byte[] payload = new byte[1024 * 32]; - protected ConnectionFactory factory; - protected Vector exceptions = new Vector(); - - private static final String TOPIC_NAME = "failoverTopic"; - private static final String CONNECTION_URL = "failover:(tcp://localhost:61616,tcp://localhost:61617)"; - public boolean useDedicatedTaskRunner = false; - - private class SimpleTopicSubscriber implements MessageListener,ExceptionListener{ - - private TopicConnection topicConnection = null; - - public SimpleTopicSubscriber(String connectionURL,String clientId,String topicName) { - - ActiveMQConnectionFactory topicConnectionFactory = null; - TopicSession topicSession = null; - Topic topic = null; - TopicSubscriber topicSubscriber = null; - - topicConnectionFactory = new ActiveMQConnectionFactory(connectionURL); +public class DurableConsumerTest extends CombinationTestSupport { + + private static final Logger LOG = LoggerFactory.getLogger(DurableConsumerTest.class); + private static int COUNT = 1024; + private static String CONSUMER_NAME = "DURABLE_TEST"; + protected BrokerService broker; + + protected String bindAddress = "tcp://localhost:61616"; + + protected byte[] payload = new byte[1024 * 32]; + protected ConnectionFactory factory; + protected Vector exceptions = new Vector(); + + private static final String TOPIC_NAME = "failoverTopic"; + private static final String CONNECTION_URL = "failover:(tcp://localhost:61616,tcp://localhost:61617)"; + public boolean useDedicatedTaskRunner = false; + + private class SimpleTopicSubscriber implements MessageListener, ExceptionListener { + + private TopicConnection topicConnection = null; + + public SimpleTopicSubscriber(String connectionURL, String clientId, String topicName) { + + ActiveMQConnectionFactory topicConnectionFactory = null; + TopicSession topicSession = null; + Topic topic = null; + TopicSubscriber topicSubscriber = null; + + topicConnectionFactory = new ActiveMQConnectionFactory(connectionURL); + try { + + topic = new ActiveMQTopic(topicName); + topicConnection = topicConnectionFactory.createTopicConnection(); + topicConnection.setClientID((clientId)); + topicConnection.start(); + + topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); + topicSubscriber = topicSession.createDurableSubscriber(topic, (clientId)); + topicSubscriber.setMessageListener(this); + + } + catch (JMSException e) { + e.printStackTrace(); + } + } + + public void onMessage(Message arg0) { + } + + public void closeConnection() { + if (topicConnection != null) { try { - - topic = new ActiveMQTopic(topicName); - topicConnection = topicConnectionFactory.createTopicConnection(); - topicConnection.setClientID((clientId)); - topicConnection.start(); - - topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - topicSubscriber = topicSession.createDurableSubscriber(topic, (clientId)); - topicSubscriber.setMessageListener(this); - - } catch (JMSException e) { - e.printStackTrace(); + topicConnection.close(); } - } - - public void onMessage(Message arg0){ - } - - public void closeConnection(){ - if (topicConnection != null) { - try { - topicConnection.close(); - } catch (JMSException e) { - } + catch (JMSException e) { } - } - - public void onException(JMSException exception){ - exceptions.add(exception); - } - } - - private class MessagePublisher implements Runnable{ - private final boolean shouldPublish = true; - - public void run(){ - TopicConnectionFactory topicConnectionFactory = null; - TopicConnection topicConnection = null; - TopicSession topicSession = null; - Topic topic = null; - TopicPublisher topicPublisher = null; - Message message = null; - - topicConnectionFactory = new ActiveMQConnectionFactory(CONNECTION_URL); + } + } + + public void onException(JMSException exception) { + exceptions.add(exception); + } + } + + private class MessagePublisher implements Runnable { + + private final boolean shouldPublish = true; + + public void run() { + TopicConnectionFactory topicConnectionFactory = null; + TopicConnection topicConnection = null; + TopicSession topicSession = null; + Topic topic = null; + TopicPublisher topicPublisher = null; + Message message = null; + + topicConnectionFactory = new ActiveMQConnectionFactory(CONNECTION_URL); + try { + topic = new ActiveMQTopic(TOPIC_NAME); + topicConnection = topicConnectionFactory.createTopicConnection(); + topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); + topicPublisher = topicSession.createPublisher(topic); + message = topicSession.createMessage(); + } + catch (Exception ex) { + exceptions.add(ex); + } + while (shouldPublish) { try { - topic = new ActiveMQTopic(TOPIC_NAME); - topicConnection = topicConnectionFactory.createTopicConnection(); - topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - topicPublisher = topicSession.createPublisher(topic); - message = topicSession.createMessage(); - } catch (Exception ex) { - exceptions.add(ex); + topicPublisher.publish(message, DeliveryMode.PERSISTENT, 1, 2 * 60 * 60 * 1000); } - while (shouldPublish) { - try { - topicPublisher.publish(message, DeliveryMode.PERSISTENT, 1, 2 * 60 * 60 * 1000); - } catch (JMSException ex) { - exceptions.add(ex); - } - try { - Thread.sleep(1); - } catch (Exception ex) { - } + catch (JMSException ex) { + exceptions.add(ex); } - } - } - - private void configurePersistence(BrokerService broker) throws Exception{ - File dataDirFile = new File("target/" + getName()); - KahaDBPersistenceAdapter kahaDBAdapter = new KahaDBPersistenceAdapter(); - kahaDBAdapter.setDirectory(dataDirFile); - broker.setPersistenceAdapter(kahaDBAdapter); - } - - public void testFailover() throws Exception{ - - configurePersistence(broker); - broker.start(); - - Thread publisherThread = new Thread(new MessagePublisher()); - publisherThread.start(); - final int numSubs = 100; - final List list = new ArrayList(numSubs); - for (int i = 0; i < numSubs; i++) { - - final int id = i; - Thread thread = new Thread(new Runnable(){ - public void run(){ - SimpleTopicSubscriber s =new SimpleTopicSubscriber(CONNECTION_URL, System.currentTimeMillis() + "-" + id, TOPIC_NAME); - list.add(s); - } - }); - thread.start(); - - } + try { + Thread.sleep(1); + } + catch (Exception ex) { + } + } + } + } - Wait.waitFor(new Wait.Condition(){ - @Override - public boolean isSatisified() throws Exception { - return numSubs == list.size(); - } - }); + private void configurePersistence(BrokerService broker) throws Exception { + File dataDirFile = new File("target/" + getName()); + KahaDBPersistenceAdapter kahaDBAdapter = new KahaDBPersistenceAdapter(); + kahaDBAdapter.setDirectory(dataDirFile); + broker.setPersistenceAdapter(kahaDBAdapter); + } - broker.stop(); - broker = createBroker(false); - configurePersistence(broker); - broker.start(); - Thread.sleep(10000); - for (SimpleTopicSubscriber s:list) { - s.closeConnection(); - } - assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); - } - - // makes heavy use of threads and can demonstrate https://issues.apache.org/activemq/browse/AMQ-2028 - // with use dedicatedTaskRunner=true and produce OOM - public void initCombosForTestConcurrentDurableConsumer(){ - addCombinationValues("useDedicatedTaskRunner", new Object[] { Boolean.TRUE, Boolean.FALSE }); - } - - public void testConcurrentDurableConsumer() throws Exception{ - - broker.start(); - broker.waitUntilStarted(); - - factory = createConnectionFactory(); - final String topicName = getName(); - final int numMessages = 500; - int numConsumers = 1; - final CountDownLatch counsumerStarted = new CountDownLatch(numConsumers); - final AtomicInteger receivedCount = new AtomicInteger(); - Runnable consumer = new Runnable(){ - public void run(){ - final String consumerName = Thread.currentThread().getName(); - int acked = 0; - int received = 0; - - try { - while (acked < numMessages / 2) { - // take one message and close, ack on occasion - Connection consumerConnection = factory.createConnection(); - ((ActiveMQConnection) consumerConnection).setWatchTopicAdvisories(false); - consumerConnection.setClientID(consumerName); - Session consumerSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Topic topic = consumerSession.createTopic(topicName); - consumerConnection.start(); - - MessageConsumer consumer = consumerSession.createDurableSubscriber(topic, consumerName); - - counsumerStarted.countDown(); - Message msg = null; - do { - msg = consumer.receive(5000); - if (msg != null) { - receivedCount.incrementAndGet(); - if (received != 0 && received % 100 == 0) { - LOG.info("Received msg: " + msg.getJMSMessageID()); - } - if (++received % 2 == 0) { - msg.acknowledge(); - acked++; - } - } - } while (msg == null); + public void testFailover() throws Exception { - consumerConnection.close(); - } - assertTrue(received >= acked); - } catch (Exception e) { - e.printStackTrace(); - exceptions.add(e); - } - } - }; - - ExecutorService executor = Executors.newFixedThreadPool(numConsumers); - - for (int i = 0; i < numConsumers; i++) { - executor.execute(consumer); - } - - assertTrue(counsumerStarted.await(30, TimeUnit.SECONDS)); - - Connection producerConnection = factory.createConnection(); - ((ActiveMQConnection) producerConnection).setWatchTopicAdvisories(false); - Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic = producerSession.createTopic(topicName); - MessageProducer producer = producerSession.createProducer(topic); - producerConnection.start(); - for (int i = 0; i < numMessages; i++) { - BytesMessage msg = producerSession.createBytesMessage(); - msg.writeBytes(payload); - producer.send(msg); - if (i != 0 && i % 100 == 0) { - LOG.info("Sent msg " + i); - } - } - - executor.shutdown(); - executor.awaitTermination(30, TimeUnit.SECONDS); - - Wait.waitFor(new Wait.Condition(){ - public boolean isSatisified() throws Exception{ - LOG.info("receivedCount: " + receivedCount.get()); - return receivedCount.get() == numMessages; - } - }, 360 * 1000); - assertEquals("got required some messages", numMessages, receivedCount.get()); - assertTrue("no exceptions, but: " + exceptions, exceptions.isEmpty()); - } - - public void testConsumerRecover() throws Exception{ - doTestConsumer(true); - } - - public void testConsumer() throws Exception{ - doTestConsumer(false); - } + configurePersistence(broker); + broker.start(); - public void testPrefetchViaBrokerConfig() throws Exception { + Thread publisherThread = new Thread(new MessagePublisher()); + publisherThread.start(); + final int numSubs = 100; + final List list = new ArrayList(numSubs); + for (int i = 0; i < numSubs; i++) { - Integer prefetchVal = new Integer(150); - PolicyEntry policyEntry = new PolicyEntry(); - policyEntry.setDurableTopicPrefetch(prefetchVal.intValue()); - policyEntry.setPrioritizedMessages(true); - PolicyMap policyMap = new PolicyMap(); - policyMap.setDefaultEntry(policyEntry); - broker.setDestinationPolicy(policyMap); - broker.start(); - - factory = createConnectionFactory(); - Connection consumerConnection = factory.createConnection(); - consumerConnection.setClientID(CONSUMER_NAME); - Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic = consumerSession.createTopic(getClass().getName()); - MessageConsumer consumer = consumerSession.createDurableSubscriber(topic, CONSUMER_NAME); - consumerConnection.start(); - - ObjectName activeSubscriptionObjectName = broker.getAdminView().getDurableTopicSubscribers()[0]; - Object prefetchFromSubView = broker.getManagementContext().getAttribute(activeSubscriptionObjectName, "PrefetchSize"); - assertEquals(prefetchVal, prefetchFromSubView); - } - - public void doTestConsumer(boolean forceRecover) throws Exception{ - - if (forceRecover) { - configurePersistence(broker); - } - broker.start(); - - factory = createConnectionFactory(); - Connection consumerConnection = factory.createConnection(); - consumerConnection.setClientID(CONSUMER_NAME); - Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic = consumerSession.createTopic(getClass().getName()); - MessageConsumer consumer = consumerSession.createDurableSubscriber(topic, CONSUMER_NAME); - consumerConnection.start(); - consumerConnection.close(); - broker.stop(); - broker = createBroker(false); - if (forceRecover) { - configurePersistence(broker); - } - broker.start(); - - Connection producerConnection = factory.createConnection(); - - Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageProducer producer = producerSession.createProducer(topic); - producerConnection.start(); - for (int i = 0; i < COUNT; i++) { - BytesMessage msg = producerSession.createBytesMessage(); - msg.writeBytes(payload); - producer.send(msg); - if (i != 0 && i % 1000 == 0) { - LOG.info("Sent msg " + i); + final int id = i; + Thread thread = new Thread(new Runnable() { + public void run() { + SimpleTopicSubscriber s = new SimpleTopicSubscriber(CONNECTION_URL, System.currentTimeMillis() + "-" + id, TOPIC_NAME); + list.add(s); } - } - producerConnection.close(); - broker.stop(); - broker = createBroker(false); - if (forceRecover) { - configurePersistence(broker); - } - broker.start(); - - consumerConnection = factory.createConnection(); - consumerConnection.setClientID(CONSUMER_NAME); - consumerConnection.start(); - consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - consumer = consumerSession.createDurableSubscriber(topic, CONSUMER_NAME); - for (int i = 0; i < COUNT; i++) { - Message msg = consumer.receive(10000); - assertNotNull("Missing message: " + i, msg); - if (i != 0 && i % 1000 == 0) { - LOG.info("Received msg " + i); + }); + thread.start(); + + } + + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return numSubs == list.size(); + } + }); + + broker.stop(); + broker = createBroker(false); + configurePersistence(broker); + broker.start(); + Thread.sleep(10000); + for (SimpleTopicSubscriber s : list) { + s.closeConnection(); + } + assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); + } + + // makes heavy use of threads and can demonstrate https://issues.apache.org/activemq/browse/AMQ-2028 + // with use dedicatedTaskRunner=true and produce OOM + public void initCombosForTestConcurrentDurableConsumer() { + addCombinationValues("useDedicatedTaskRunner", new Object[]{Boolean.TRUE, Boolean.FALSE}); + } + + public void testConcurrentDurableConsumer() throws Exception { + + broker.start(); + broker.waitUntilStarted(); + + factory = createConnectionFactory(); + final String topicName = getName(); + final int numMessages = 500; + int numConsumers = 1; + final CountDownLatch counsumerStarted = new CountDownLatch(numConsumers); + final AtomicInteger receivedCount = new AtomicInteger(); + Runnable consumer = new Runnable() { + public void run() { + final String consumerName = Thread.currentThread().getName(); + int acked = 0; + int received = 0; + + try { + while (acked < numMessages / 2) { + // take one message and close, ack on occasion + Connection consumerConnection = factory.createConnection(); + ((ActiveMQConnection) consumerConnection).setWatchTopicAdvisories(false); + consumerConnection.setClientID(consumerName); + Session consumerSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Topic topic = consumerSession.createTopic(topicName); + consumerConnection.start(); + + MessageConsumer consumer = consumerSession.createDurableSubscriber(topic, consumerName); + + counsumerStarted.countDown(); + Message msg = null; + do { + msg = consumer.receive(5000); + if (msg != null) { + receivedCount.incrementAndGet(); + if (received != 0 && received % 100 == 0) { + LOG.info("Received msg: " + msg.getJMSMessageID()); + } + if (++received % 2 == 0) { + msg.acknowledge(); + acked++; + } + } + } while (msg == null); + + consumerConnection.close(); + } + assertTrue(received >= acked); } - - } - consumerConnection.close(); - - } - - @Override - protected void setUp() throws Exception{ - if (broker == null) { - broker = createBroker(true); - } - - super.setUp(); - } - - @Override - protected void tearDown() throws Exception{ - super.tearDown(); - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - broker = null; - } - } - - protected Topic creatTopic(Session s,String destinationName) throws JMSException{ - return s.createTopic(destinationName); - } - - /** - * Factory method to create a new broker - * - * @throws Exception - */ - protected BrokerService createBroker(boolean deleteStore) throws Exception{ - BrokerService answer = new BrokerService(); - configureBroker(answer, deleteStore); - return answer; - } - - protected void configureBroker(BrokerService answer,boolean deleteStore) throws Exception{ - answer.setDeleteAllMessagesOnStartup(deleteStore); - KahaDBStore kaha = new KahaDBStore(); - //kaha.setConcurrentStoreAndDispatchTopics(false); - File directory = new File("target/activemq-data/kahadb"); - if (deleteStore) { - IOHelper.deleteChildren(directory); - } - kaha.setDirectory(directory); - //kaha.setMaxAsyncJobs(10); - - answer.setPersistenceAdapter(kaha); - answer.addConnector(bindAddress); - answer.setUseShutdownHook(false); - answer.setAdvisorySupport(false); - answer.setDedicatedTaskRunner(useDedicatedTaskRunner); - } - - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception{ - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(bindAddress); - factory.setUseDedicatedTaskRunner(useDedicatedTaskRunner); - return factory; - } - - public static Test suite(){ - return suite(DurableConsumerTest.class); - } - - public static void main(String[] args){ - junit.textui.TestRunner.run(suite()); - } + catch (Exception e) { + e.printStackTrace(); + exceptions.add(e); + } + } + }; + + ExecutorService executor = Executors.newFixedThreadPool(numConsumers); + + for (int i = 0; i < numConsumers; i++) { + executor.execute(consumer); + } + + assertTrue(counsumerStarted.await(30, TimeUnit.SECONDS)); + + Connection producerConnection = factory.createConnection(); + ((ActiveMQConnection) producerConnection).setWatchTopicAdvisories(false); + Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Topic topic = producerSession.createTopic(topicName); + MessageProducer producer = producerSession.createProducer(topic); + producerConnection.start(); + for (int i = 0; i < numMessages; i++) { + BytesMessage msg = producerSession.createBytesMessage(); + msg.writeBytes(payload); + producer.send(msg); + if (i != 0 && i % 100 == 0) { + LOG.info("Sent msg " + i); + } + } + + executor.shutdown(); + executor.awaitTermination(30, TimeUnit.SECONDS); + + Wait.waitFor(new Wait.Condition() { + public boolean isSatisified() throws Exception { + LOG.info("receivedCount: " + receivedCount.get()); + return receivedCount.get() == numMessages; + } + }, 360 * 1000); + assertEquals("got required some messages", numMessages, receivedCount.get()); + assertTrue("no exceptions, but: " + exceptions, exceptions.isEmpty()); + } + + public void testConsumerRecover() throws Exception { + doTestConsumer(true); + } + + public void testConsumer() throws Exception { + doTestConsumer(false); + } + + public void testPrefetchViaBrokerConfig() throws Exception { + + Integer prefetchVal = new Integer(150); + PolicyEntry policyEntry = new PolicyEntry(); + policyEntry.setDurableTopicPrefetch(prefetchVal.intValue()); + policyEntry.setPrioritizedMessages(true); + PolicyMap policyMap = new PolicyMap(); + policyMap.setDefaultEntry(policyEntry); + broker.setDestinationPolicy(policyMap); + broker.start(); + + factory = createConnectionFactory(); + Connection consumerConnection = factory.createConnection(); + consumerConnection.setClientID(CONSUMER_NAME); + Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Topic topic = consumerSession.createTopic(getClass().getName()); + MessageConsumer consumer = consumerSession.createDurableSubscriber(topic, CONSUMER_NAME); + consumerConnection.start(); + + ObjectName activeSubscriptionObjectName = broker.getAdminView().getDurableTopicSubscribers()[0]; + Object prefetchFromSubView = broker.getManagementContext().getAttribute(activeSubscriptionObjectName, "PrefetchSize"); + assertEquals(prefetchVal, prefetchFromSubView); + } + + public void doTestConsumer(boolean forceRecover) throws Exception { + + if (forceRecover) { + configurePersistence(broker); + } + broker.start(); + + factory = createConnectionFactory(); + Connection consumerConnection = factory.createConnection(); + consumerConnection.setClientID(CONSUMER_NAME); + Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Topic topic = consumerSession.createTopic(getClass().getName()); + MessageConsumer consumer = consumerSession.createDurableSubscriber(topic, CONSUMER_NAME); + consumerConnection.start(); + consumerConnection.close(); + broker.stop(); + broker = createBroker(false); + if (forceRecover) { + configurePersistence(broker); + } + broker.start(); + + Connection producerConnection = factory.createConnection(); + + Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + MessageProducer producer = producerSession.createProducer(topic); + producerConnection.start(); + for (int i = 0; i < COUNT; i++) { + BytesMessage msg = producerSession.createBytesMessage(); + msg.writeBytes(payload); + producer.send(msg); + if (i != 0 && i % 1000 == 0) { + LOG.info("Sent msg " + i); + } + } + producerConnection.close(); + broker.stop(); + broker = createBroker(false); + if (forceRecover) { + configurePersistence(broker); + } + broker.start(); + + consumerConnection = factory.createConnection(); + consumerConnection.setClientID(CONSUMER_NAME); + consumerConnection.start(); + consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + consumer = consumerSession.createDurableSubscriber(topic, CONSUMER_NAME); + for (int i = 0; i < COUNT; i++) { + Message msg = consumer.receive(10000); + assertNotNull("Missing message: " + i, msg); + if (i != 0 && i % 1000 == 0) { + LOG.info("Received msg " + i); + } + + } + consumerConnection.close(); + + } + + @Override + protected void setUp() throws Exception { + if (broker == null) { + broker = createBroker(true); + } + + super.setUp(); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + broker = null; + } + } + + protected Topic creatTopic(Session s, String destinationName) throws JMSException { + return s.createTopic(destinationName); + } + + /** + * Factory method to create a new broker + * + * @throws Exception + */ + protected BrokerService createBroker(boolean deleteStore) throws Exception { + BrokerService answer = new BrokerService(); + configureBroker(answer, deleteStore); + return answer; + } + + protected void configureBroker(BrokerService answer, boolean deleteStore) throws Exception { + answer.setDeleteAllMessagesOnStartup(deleteStore); + KahaDBStore kaha = new KahaDBStore(); + //kaha.setConcurrentStoreAndDispatchTopics(false); + File directory = new File("target/activemq-data/kahadb"); + if (deleteStore) { + IOHelper.deleteChildren(directory); + } + kaha.setDirectory(directory); + //kaha.setMaxAsyncJobs(10); + + answer.setPersistenceAdapter(kaha); + answer.addConnector(bindAddress); + answer.setUseShutdownHook(false); + answer.setAdvisorySupport(false); + answer.setDedicatedTaskRunner(useDedicatedTaskRunner); + } + + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(bindAddress); + factory.setUseDedicatedTaskRunner(useDedicatedTaskRunner); + return factory; + } + + public static Test suite() { + return suite(DurableConsumerTest.class); + } + + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/JMSDurableTopicNoLocalTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/JMSDurableTopicNoLocalTest.java index 80c4e9fc50..750bbc8baa 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/JMSDurableTopicNoLocalTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/JMSDurableTopicNoLocalTest.java @@ -26,58 +26,59 @@ import javax.jms.Session; import javax.jms.TextMessage; import javax.jms.Topic; import javax.jms.TopicSubscriber; + import org.apache.activemq.EmbeddedBrokerTestSupport; import org.apache.activemq.broker.BrokerService; /** - * + * */ public class JMSDurableTopicNoLocalTest extends EmbeddedBrokerTestSupport { - protected String bindAddress; - public void testConsumeNoLocal() throws Exception { - final String TEST_NAME = getClass().getName(); - Connection connection = createConnection(); - connection.setClientID(TEST_NAME); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - TopicSubscriber subscriber = session.createDurableSubscriber((Topic) destination, "topicUser2", null, true); - - - final CountDownLatch latch = new CountDownLatch(1); - subscriber.setMessageListener(new MessageListener() { - public void onMessage(Message message) { - System.out.println("Receive a message " + message); - latch.countDown(); - } - }); - - connection.start(); - - MessageProducer producer = session.createProducer(destination); - TextMessage message = session.createTextMessage("THIS IS A TEST"); - producer.send(message); - producer.close(); - latch.await(5,TimeUnit.SECONDS); - assertEquals(latch.getCount(),1); - } + protected String bindAddress; - @Override - protected void setUp() throws Exception { - bindAddress = "vm://localhost"; - useTopic=true; - super.setUp(); - } + public void testConsumeNoLocal() throws Exception { + final String TEST_NAME = getClass().getName(); + Connection connection = createConnection(); + connection.setClientID(TEST_NAME); - @Override - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setUseJmx(false); - answer.setPersistent(true); - answer.setDeleteAllMessagesOnStartup(true); - answer.addConnector(bindAddress); - return answer; - } + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + TopicSubscriber subscriber = session.createDurableSubscriber((Topic) destination, "topicUser2", null, true); + + final CountDownLatch latch = new CountDownLatch(1); + subscriber.setMessageListener(new MessageListener() { + public void onMessage(Message message) { + System.out.println("Receive a message " + message); + latch.countDown(); + } + }); + + connection.start(); + + MessageProducer producer = session.createProducer(destination); + TextMessage message = session.createTextMessage("THIS IS A TEST"); + producer.send(message); + producer.close(); + latch.await(5, TimeUnit.SECONDS); + assertEquals(latch.getCount(), 1); + } + + @Override + protected void setUp() throws Exception { + bindAddress = "vm://localhost"; + useTopic = true; + super.setUp(); + } + + @Override + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + answer.setUseJmx(false); + answer.setPersistent(true); + answer.setDeleteAllMessagesOnStartup(true); + answer.addConnector(bindAddress); + return answer; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/JmsDurableTopicSlowReceiveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/JmsDurableTopicSlowReceiveTest.java index 05a8c1d2c3..65d3c9bf75 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/JmsDurableTopicSlowReceiveTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/JmsDurableTopicSlowReceiveTest.java @@ -35,146 +35,147 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class JmsDurableTopicSlowReceiveTest extends JmsTopicSendReceiveTest { - - static final int NMSG = 200; - static final int MSIZE = 256000; - private static final transient Logger LOG = LoggerFactory.getLogger(JmsDurableTopicSlowReceiveTest.class); - private static final String COUNT_PROPERY_NAME = "count"; - protected Connection connection2; - protected Session session2; - protected Session consumeSession2; - protected MessageConsumer consumer2; - protected MessageProducer producer2; - protected Destination consumerDestination2; - BrokerService broker; - private Connection connection3; - private Session consumeSession3; - private TopicSubscriber consumer3; + static final int NMSG = 200; + static final int MSIZE = 256000; + private static final transient Logger LOG = LoggerFactory.getLogger(JmsDurableTopicSlowReceiveTest.class); + private static final String COUNT_PROPERY_NAME = "count"; - /** - * Set up a durable suscriber test. - * - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception { - this.durable = true; - broker = createBroker(); - super.setUp(); - } + protected Connection connection2; + protected Session session2; + protected Session consumeSession2; + protected MessageConsumer consumer2; + protected MessageProducer producer2; + protected Destination consumerDestination2; + BrokerService broker; + private Connection connection3; + private Session consumeSession3; + private TopicSubscriber consumer3; - protected void tearDown() throws Exception { - super.tearDown(); - broker.stop(); - } + /** + * Set up a durable suscriber test. + * + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + this.durable = true; + broker = createBroker(); + super.setUp(); + } - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory result = new ActiveMQConnectionFactory("vm://localhost?async=false"); - Properties props = new Properties(); - props.put("prefetchPolicy.durableTopicPrefetch", "5"); - props.put("prefetchPolicy.optimizeDurableTopicPrefetch", "5"); - result.setProperties(props); - return result; - } + protected void tearDown() throws Exception { + super.tearDown(); + broker.stop(); + } - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - configureBroker(answer); - answer.start(); - return answer; - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory result = new ActiveMQConnectionFactory("vm://localhost?async=false"); + Properties props = new Properties(); + props.put("prefetchPolicy.durableTopicPrefetch", "5"); + props.put("prefetchPolicy.optimizeDurableTopicPrefetch", "5"); + result.setProperties(props); + return result; + } - protected void configureBroker(BrokerService answer) throws Exception { - answer.setDeleteAllMessagesOnStartup(true); - } + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + configureBroker(answer); + answer.start(); + return answer; + } - /** - * Test if all the messages sent are being received. - * - * @throws Exception - */ - public void testSlowReceiver() throws Exception { - connection2 = createConnection(); - connection2.setClientID("test"); - connection2.start(); - consumeSession2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE); - session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumerDestination2 = session2.createTopic(getConsumerSubject() + "2"); - consumer2 = consumeSession2.createDurableSubscriber((Topic)consumerDestination2, getName()); + protected void configureBroker(BrokerService answer) throws Exception { + answer.setDeleteAllMessagesOnStartup(true); + } - consumer2.close(); - connection2.close(); - new Thread(new Runnable() { + /** + * Test if all the messages sent are being received. + * + * @throws Exception + */ + public void testSlowReceiver() throws Exception { + connection2 = createConnection(); + connection2.setClientID("test"); + connection2.start(); + consumeSession2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE); + session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumerDestination2 = session2.createTopic(getConsumerSubject() + "2"); + consumer2 = consumeSession2.createDurableSubscriber((Topic) consumerDestination2, getName()); - public void run() { - try { - int count = 0; - for (int loop = 0; loop < 4; loop++) { - connection2 = createConnection(); - connection2.start(); - session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer2 = session2.createProducer(null); - producer2.setDeliveryMode(deliveryMode); - Thread.sleep(1000); - for (int i = 0; i < NMSG / 4; i++) { - BytesMessage message = session2.createBytesMessage(); - message.writeBytes(new byte[MSIZE]); - message.setStringProperty("test", "test"); - message.setIntProperty(COUNT_PROPERY_NAME, count); - message.setJMSType("test"); - producer2.send(consumerDestination2, message); - Thread.sleep(50); - if (verbose) { - LOG.debug("Sent(" + loop + "): " + i); - } - count++; - } - producer2.close(); - connection2.stop(); - connection2.close(); - } - } catch (Throwable e) { - e.printStackTrace(); - } + consumer2.close(); + connection2.close(); + new Thread(new Runnable() { + + public void run() { + try { + int count = 0; + for (int loop = 0; loop < 4; loop++) { + connection2 = createConnection(); + connection2.start(); + session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer2 = session2.createProducer(null); + producer2.setDeliveryMode(deliveryMode); + Thread.sleep(1000); + for (int i = 0; i < NMSG / 4; i++) { + BytesMessage message = session2.createBytesMessage(); + message.writeBytes(new byte[MSIZE]); + message.setStringProperty("test", "test"); + message.setIntProperty(COUNT_PROPERY_NAME, count); + message.setJMSType("test"); + producer2.send(consumerDestination2, message); + Thread.sleep(50); + if (verbose) { + LOG.debug("Sent(" + loop + "): " + i); + } + count++; + } + producer2.close(); + connection2.stop(); + connection2.close(); + } } - }, "SENDER Thread").start(); - connection3 = createConnection(); - connection3.setClientID("test"); - connection3.start(); - consumeSession3 = connection3.createSession(false, Session.CLIENT_ACKNOWLEDGE); - consumer3 = consumeSession3.createDurableSubscriber((Topic)consumerDestination2, getName()); - connection3.close(); - int count = 0; - for (int loop = 0; loop < 4; ++loop) { - connection3 = createConnection(); - connection3.setClientID("test"); - connection3.start(); - consumeSession3 = connection3.createSession(false, Session.CLIENT_ACKNOWLEDGE); - consumer3 = consumeSession3.createDurableSubscriber((Topic)consumerDestination2, getName()); - Message msg = null; - int i; - for (i = 0; i < NMSG / 4; i++) { - msg = consumer3.receive(10000); - if (msg == null) { - break; - } - if (verbose) { - LOG.debug("Received(" + loop + "): " + i + " count = " + msg.getIntProperty(COUNT_PROPERY_NAME)); - } - assertNotNull(msg); - assertEquals(msg.getJMSType(), "test"); - assertEquals(msg.getStringProperty("test"), "test"); - assertEquals("Messages received out of order", count, msg.getIntProperty(COUNT_PROPERY_NAME)); - Thread.sleep(500); - msg.acknowledge(); - count++; + catch (Throwable e) { + e.printStackTrace(); } - consumer3.close(); - assertEquals("Receiver " + loop, NMSG / 4, i); - connection3.close(); - } - } + } + }, "SENDER Thread").start(); + connection3 = createConnection(); + connection3.setClientID("test"); + connection3.start(); + consumeSession3 = connection3.createSession(false, Session.CLIENT_ACKNOWLEDGE); + consumer3 = consumeSession3.createDurableSubscriber((Topic) consumerDestination2, getName()); + connection3.close(); + int count = 0; + for (int loop = 0; loop < 4; ++loop) { + connection3 = createConnection(); + connection3.setClientID("test"); + connection3.start(); + consumeSession3 = connection3.createSession(false, Session.CLIENT_ACKNOWLEDGE); + consumer3 = consumeSession3.createDurableSubscriber((Topic) consumerDestination2, getName()); + Message msg = null; + int i; + for (i = 0; i < NMSG / 4; i++) { + msg = consumer3.receive(10000); + if (msg == null) { + break; + } + if (verbose) { + LOG.debug("Received(" + loop + "): " + i + " count = " + msg.getIntProperty(COUNT_PROPERY_NAME)); + } + assertNotNull(msg); + assertEquals(msg.getJMSType(), "test"); + assertEquals(msg.getStringProperty("test"), "test"); + assertEquals("Messages received out of order", count, msg.getIntProperty(COUNT_PROPERY_NAME)); + Thread.sleep(500); + msg.acknowledge(); + count++; + } + consumer3.close(); + assertEquals("Receiver " + loop, NMSG / 4, i); + connection3.close(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/JmsTimeoutTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/JmsTimeoutTest.java index 2858302425..abc90d5d18 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/JmsTimeoutTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/JmsTimeoutTest.java @@ -36,123 +36,128 @@ import org.slf4j.LoggerFactory; public class JmsTimeoutTest extends EmbeddedBrokerTestSupport { - static final Logger LOG = LoggerFactory.getLogger(JmsTimeoutTest.class); + static final Logger LOG = LoggerFactory.getLogger(JmsTimeoutTest.class); - private final int messageSize=1024*64; - private final int messageCount=10000; - private final AtomicInteger exceptionCount = new AtomicInteger(0); + private final int messageSize = 1024 * 64; + private final int messageCount = 10000; + private final AtomicInteger exceptionCount = new AtomicInteger(0); - /** - * Test the case where the broker is blocked due to a memory limit - * and a producer timeout is set on the connection. - * @throws Exception - */ - public void testBlockedProducerConnectionTimeout() throws Exception { - final ActiveMQConnection cx = (ActiveMQConnection)createConnection(); - final ActiveMQDestination queue = createDestination("testqueue"); + /** + * Test the case where the broker is blocked due to a memory limit + * and a producer timeout is set on the connection. + * + * @throws Exception + */ + public void testBlockedProducerConnectionTimeout() throws Exception { + final ActiveMQConnection cx = (ActiveMQConnection) createConnection(); + final ActiveMQDestination queue = createDestination("testqueue"); - // we should not take longer than 10 seconds to return from send - cx.setSendTimeout(10000); + // we should not take longer than 10 seconds to return from send + cx.setSendTimeout(10000); - Runnable r = new Runnable() { - public void run() { - try { - LOG.info("Sender thread starting"); - Session session = cx.createSession(false, 1); - MessageProducer producer = session.createProducer(queue); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - - TextMessage message = session.createTextMessage(createMessageText()); - for(int count=0; count 0); - } - - /** - * Test the case where the broker is blocked due to a memory limit - * with a fail timeout - * @throws Exception - */ - public void testBlockedProducerUsageSendFailTimeout() throws Exception { - final ActiveMQConnection cx = (ActiveMQConnection)createConnection(); - final ActiveMQDestination queue = createDestination("testqueue"); - - broker.getSystemUsage().setSendFailIfNoSpaceAfterTimeout(5000); - Runnable r = new Runnable() { - public void run() { - try { - LOG.info("Sender thread starting"); - Session session = cx.createSession(false, 1); - MessageProducer producer = session.createProducer(queue); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - - TextMessage message = session.createTextMessage(createMessageText()); - for(int count=0; count 0); - } - protected void setUp() throws Exception { - exceptionCount.set(0); - bindAddress = "tcp://localhost:0"; - broker = createBroker(); - broker.setDeleteAllMessagesOnStartup(true); - broker.getSystemUsage().getMemoryUsage().setLimit(5*1024*1024); + } + }; + cx.start(); + Thread producerThread = new Thread(r); + producerThread.start(); + producerThread.join(30000); + cx.close(); + // We should have a few timeout exceptions as memory store will fill up + assertTrue("No exception from the broker", exceptionCount.get() > 0); + } - super.setUp(); - } + /** + * Test the case where the broker is blocked due to a memory limit + * with a fail timeout + * + * @throws Exception + */ + public void testBlockedProducerUsageSendFailTimeout() throws Exception { + final ActiveMQConnection cx = (ActiveMQConnection) createConnection(); + final ActiveMQDestination queue = createDestination("testqueue"); - @Override - protected ConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory( - broker.getTransportConnectors().get(0).getPublishableConnectString()); - } + broker.getSystemUsage().setSendFailIfNoSpaceAfterTimeout(5000); + Runnable r = new Runnable() { + public void run() { + try { + LOG.info("Sender thread starting"); + Session session = cx.createSession(false, 1); + MessageProducer producer = session.createProducer(queue); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); - private String createMessageText() { - StringBuffer buffer = new StringBuffer(); - buffer.append(""); - for (int i = buffer.length(); i < messageSize; i++) { - buffer.append('X'); - } - buffer.append(""); - return buffer.toString(); - } + TextMessage message = session.createTextMessage(createMessageText()); + for (int count = 0; count < messageCount; count++) { + producer.send(message); + } + LOG.info("Done sending.."); + } + catch (JMSException e) { + if (e instanceof ResourceAllocationException || e.getCause() instanceof RequestTimedOutIOException) { + exceptionCount.incrementAndGet(); + } + else { + e.printStackTrace(); + } + return; + } + } + }; + cx.start(); + Thread producerThread = new Thread(r); + producerThread.start(); + producerThread.join(30000); + cx.close(); + // We should have a few timeout exceptions as memory store will fill up + assertTrue("No exception from the broker", exceptionCount.get() > 0); + } + + protected void setUp() throws Exception { + exceptionCount.set(0); + bindAddress = "tcp://localhost:0"; + broker = createBroker(); + broker.setDeleteAllMessagesOnStartup(true); + broker.getSystemUsage().getMemoryUsage().setLimit(5 * 1024 * 1024); + + super.setUp(); + } + + @Override + protected ConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString()); + } + + private String createMessageText() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + for (int i = buffer.length(); i < messageSize; i++) { + buffer.append('X'); + } + buffer.append(""); + return buffer.toString(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/MemoryUsageBlockResumeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/MemoryUsageBlockResumeTest.java index 5ac2dc0f68..84ed4d5099 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/MemoryUsageBlockResumeTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/MemoryUsageBlockResumeTest.java @@ -46,179 +46,178 @@ import org.slf4j.LoggerFactory; import static org.junit.Assert.*; - @RunWith(BlockJUnit4ClassRunner.class) public class MemoryUsageBlockResumeTest extends TestSupport implements Thread.UncaughtExceptionHandler { - public int deliveryMode = DeliveryMode.PERSISTENT; + public int deliveryMode = DeliveryMode.PERSISTENT; - private static final Logger LOG = LoggerFactory.getLogger(MemoryUsageBlockResumeTest.class); - private static byte[] buf = new byte[4 * 1024]; - private static byte[] bigBuf = new byte[48 * 1024]; + private static final Logger LOG = LoggerFactory.getLogger(MemoryUsageBlockResumeTest.class); + private static byte[] buf = new byte[4 * 1024]; + private static byte[] bigBuf = new byte[48 * 1024]; - private BrokerService broker; - AtomicInteger messagesSent = new AtomicInteger(0); - AtomicInteger messagesConsumed = new AtomicInteger(0); + private BrokerService broker; + AtomicInteger messagesSent = new AtomicInteger(0); + AtomicInteger messagesConsumed = new AtomicInteger(0); - protected long messageReceiveTimeout = 10000L; + protected long messageReceiveTimeout = 10000L; - Destination destination = new ActiveMQQueue("FooTwo"); - Destination bigDestination = new ActiveMQQueue("FooTwoBig"); + Destination destination = new ActiveMQQueue("FooTwo"); + Destination bigDestination = new ActiveMQQueue("FooTwoBig"); - private String connectionUri; - private final Vector exceptions = new Vector(); + private String connectionUri; + private final Vector exceptions = new Vector(); - @Test(timeout = 60 * 1000) - public void testBlockByOtherResumeNoException() throws Exception { + @Test(timeout = 60 * 1000) + public void testBlockByOtherResumeNoException() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - // ensure more than on message can be pending when full - factory.setProducerWindowSize(48*1024); - // ensure messages are spooled to disk for this consumer - ActiveMQPrefetchPolicy prefetch = new ActiveMQPrefetchPolicy(); - prefetch.setTopicPrefetch(10); - factory.setPrefetchPolicy(prefetch); - Connection consumerConnection = factory.createConnection(); - consumerConnection.start(); + // ensure more than on message can be pending when full + factory.setProducerWindowSize(48 * 1024); + // ensure messages are spooled to disk for this consumer + ActiveMQPrefetchPolicy prefetch = new ActiveMQPrefetchPolicy(); + prefetch.setTopicPrefetch(10); + factory.setPrefetchPolicy(prefetch); + Connection consumerConnection = factory.createConnection(); + consumerConnection.start(); - Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = consumerSession.createConsumer(bigDestination); + Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = consumerSession.createConsumer(bigDestination); - final Connection producerConnection = factory.createConnection(); - producerConnection.start(); + final Connection producerConnection = factory.createConnection(); + producerConnection.start(); - final int fillWithBigCount = 10; - Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); - producer.setDeliveryMode(deliveryMode); - for (int idx = 0; idx < fillWithBigCount; ++idx) { - Message message = session.createTextMessage(new String(bigBuf) + idx); - producer.send(bigDestination, message); - messagesSent.incrementAndGet(); - LOG.info("After big: " + idx + ", System Memory Usage " + broker.getSystemUsage().getMemoryUsage().getPercentUsage()); - } + final int fillWithBigCount = 10; + Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(null); + producer.setDeliveryMode(deliveryMode); + for (int idx = 0; idx < fillWithBigCount; ++idx) { + Message message = session.createTextMessage(new String(bigBuf) + idx); + producer.send(bigDestination, message); + messagesSent.incrementAndGet(); + LOG.info("After big: " + idx + ", System Memory Usage " + broker.getSystemUsage().getMemoryUsage().getPercentUsage()); + } - // will block on pfc - final int toSend = 20; - Thread producingThread = new Thread("Producing thread") { - @Override - public void run() { - try { - Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(deliveryMode); - for (int idx = 0; idx < toSend; ++idx) { - Message message = session.createTextMessage(new String(buf) + idx); - producer.send(destination, message); - messagesSent.incrementAndGet(); - LOG.info("After little:" + idx + ", System Memory Usage " + broker.getSystemUsage().getMemoryUsage().getPercentUsage()); - } - } catch (Throwable ex) { - ex.printStackTrace(); - } + // will block on pfc + final int toSend = 20; + Thread producingThread = new Thread("Producing thread") { + @Override + public void run() { + try { + Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(deliveryMode); + for (int idx = 0; idx < toSend; ++idx) { + Message message = session.createTextMessage(new String(buf) + idx); + producer.send(destination, message); + messagesSent.incrementAndGet(); + LOG.info("After little:" + idx + ", System Memory Usage " + broker.getSystemUsage().getMemoryUsage().getPercentUsage()); + } } - }; - producingThread.start(); - - Thread producingThreadTwo = new Thread("Producing thread") { - @Override - public void run() { - try { - Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(deliveryMode); - for (int idx = 0; idx < toSend; ++idx) { - Message message = session.createTextMessage(new String(buf) + idx); - producer.send(destination, message); - messagesSent.incrementAndGet(); - LOG.info("After little:" + idx + ", System Memory Usage " + broker.getSystemUsage().getMemoryUsage().getPercentUsage()); - } - } catch (Throwable ex) { - ex.printStackTrace(); - } + catch (Throwable ex) { + ex.printStackTrace(); } - }; - producingThreadTwo.start(); + } + }; + producingThread.start(); - assertTrue("producer has sent x in a reasonable time", Wait.waitFor(new Wait.Condition() - { - @Override - public boolean isSatisified() throws Exception { - LOG.info("Checking for : X sent, System Memory Usage " + broker.getSystemUsage().getMemoryUsage().getPercentUsage() + ", sent: " + messagesSent); - return messagesSent.get() > 20; + Thread producingThreadTwo = new Thread("Producing thread") { + @Override + public void run() { + try { + Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(deliveryMode); + for (int idx = 0; idx < toSend; ++idx) { + Message message = session.createTextMessage(new String(buf) + idx); + producer.send(destination, message); + messagesSent.incrementAndGet(); + LOG.info("After little:" + idx + ", System Memory Usage " + broker.getSystemUsage().getMemoryUsage().getPercentUsage()); + } } - })); + catch (Throwable ex) { + ex.printStackTrace(); + } + } + }; + producingThreadTwo.start(); + assertTrue("producer has sent x in a reasonable time", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("Checking for : X sent, System Memory Usage " + broker.getSystemUsage().getMemoryUsage().getPercentUsage() + ", sent: " + messagesSent); + return messagesSent.get() > 20; + } + })); - LOG.info("Consuming from big q to allow delivery to smaller q from pending"); - int count = 0; + LOG.info("Consuming from big q to allow delivery to smaller q from pending"); + int count = 0; - Message m = null; + Message m = null; - for (;count < 10; count++) { - assertTrue((m = consumer.receive(messageReceiveTimeout)) != null); - LOG.info("Received Message (" + count + "):" + m + ", System Memory Usage " + broker.getSystemUsage().getMemoryUsage().getPercentUsage()); - messagesConsumed.incrementAndGet(); - } - consumer.close(); + for (; count < 10; count++) { + assertTrue((m = consumer.receive(messageReceiveTimeout)) != null); + LOG.info("Received Message (" + count + "):" + m + ", System Memory Usage " + broker.getSystemUsage().getMemoryUsage().getPercentUsage()); + messagesConsumed.incrementAndGet(); + } + consumer.close(); - producingThread.join(); - producingThreadTwo.join(); + producingThread.join(); + producingThreadTwo.join(); - assertEquals("Incorrect number of Messages Sent: " + messagesSent.get(), messagesSent.get(), fillWithBigCount + toSend*2); + assertEquals("Incorrect number of Messages Sent: " + messagesSent.get(), messagesSent.get(), fillWithBigCount + toSend * 2); - // consume all little messages - consumer = consumerSession.createConsumer(destination); - for (count = 0;count < toSend*2; count++) { - assertTrue((m = consumer.receive(messageReceiveTimeout)) != null); - LOG.info("Received Message (" + count + "):" + m + ", System Memory Usage " + broker.getSystemUsage().getMemoryUsage().getPercentUsage() ); - messagesConsumed.incrementAndGet(); - } + // consume all little messages + consumer = consumerSession.createConsumer(destination); + for (count = 0; count < toSend * 2; count++) { + assertTrue((m = consumer.receive(messageReceiveTimeout)) != null); + LOG.info("Received Message (" + count + "):" + m + ", System Memory Usage " + broker.getSystemUsage().getMemoryUsage().getPercentUsage()); + messagesConsumed.incrementAndGet(); + } - assertEquals("Incorrect number of Messages consumed: " + messagesConsumed.get(), messagesSent.get(), messagesConsumed.get()); + assertEquals("Incorrect number of Messages consumed: " + messagesConsumed.get(), messagesSent.get(), messagesConsumed.get()); - //assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); - } + //assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); + } - @Override - @Before - public void setUp() throws Exception { + @Override + @Before + public void setUp() throws Exception { - Thread.setDefaultUncaughtExceptionHandler(this); - broker = new BrokerService(); - broker.setDataDirectory("target" + File.separator + "activemq-data"); - broker.setPersistent(true); - broker.setUseJmx(false); - broker.setAdvisorySupport(false); - broker.setDeleteAllMessagesOnStartup(true); + Thread.setDefaultUncaughtExceptionHandler(this); + broker = new BrokerService(); + broker.setDataDirectory("target" + File.separator + "activemq-data"); + broker.setPersistent(true); + broker.setUseJmx(false); + broker.setAdvisorySupport(false); + broker.setDeleteAllMessagesOnStartup(true); - setDefaultPersistenceAdapter(broker); - broker.getSystemUsage().getMemoryUsage().setLimit((30 * 16 * 1024)); + setDefaultPersistenceAdapter(broker); + broker.getSystemUsage().getMemoryUsage().setLimit((30 * 16 * 1024)); - PolicyEntry defaultPolicy = new PolicyEntry(); - defaultPolicy.setOptimizedDispatch(true); - PolicyMap policyMap = new PolicyMap(); - policyMap.setDefaultEntry(defaultPolicy); - broker.setDestinationPolicy(policyMap); + PolicyEntry defaultPolicy = new PolicyEntry(); + defaultPolicy.setOptimizedDispatch(true); + PolicyMap policyMap = new PolicyMap(); + policyMap.setDefaultEntry(defaultPolicy); + broker.setDestinationPolicy(policyMap); - broker.addConnector("tcp://localhost:0"); - broker.start(); + broker.addConnector("tcp://localhost:0"); + broker.start(); - connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); - } + connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); + } - @Override - @After - public void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - } - } + @Override + @After + public void tearDown() throws Exception { + if (broker != null) { + broker.stop(); + } + } - @Override - public void uncaughtException(Thread t, Throwable e) { - LOG.error("Unexpected Unhandeled ex on: " + t, e); - exceptions.add(e); - } + @Override + public void uncaughtException(Thread t, Throwable e) { + LOG.error("Unexpected Unhandeled ex on: " + t, e); + exceptions.add(e); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/MemoryUsageBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/MemoryUsageBrokerTest.java index b229e0e8f0..26df39487d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/MemoryUsageBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/MemoryUsageBrokerTest.java @@ -29,62 +29,63 @@ import javax.jms.*; import java.io.File; public class MemoryUsageBrokerTest extends BrokerTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(MemoryUsageBrokerTest.class); - protected void setUp() throws Exception { - this.setAutoFail(true); - super.setUp(); - } + private static final Logger LOG = LoggerFactory.getLogger(MemoryUsageBrokerTest.class); - @Override - protected PolicyEntry getDefaultPolicy() { - PolicyEntry policy = super.getDefaultPolicy(); - // Disable PFC and assign a large memory limit that's larger than the default broker memory limit for queues - policy.setProducerFlowControl(false); - policy.setQueue(">"); - policy.setMemoryLimit(128 * 1024 * 1024); - return policy; - } + protected void setUp() throws Exception { + this.setAutoFail(true); + super.setUp(); + } - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - KahaDBStore kaha = new KahaDBStore(); - File directory = new File("target/activemq-data/kahadb"); - IOHelper.deleteChildren(directory); - kaha.setDirectory(directory); - kaha.deleteAllMessages(); - broker.setPersistenceAdapter(kaha); - return broker; - } + @Override + protected PolicyEntry getDefaultPolicy() { + PolicyEntry policy = super.getDefaultPolicy(); + // Disable PFC and assign a large memory limit that's larger than the default broker memory limit for queues + policy.setProducerFlowControl(false); + policy.setQueue(">"); + policy.setMemoryLimit(128 * 1024 * 1024); + return policy; + } - protected ConnectionFactory createConnectionFactory() { - return new ActiveMQConnectionFactory(broker.getVmConnectorURI()); - } + protected BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); + KahaDBStore kaha = new KahaDBStore(); + File directory = new File("target/activemq-data/kahadb"); + IOHelper.deleteChildren(directory); + kaha.setDirectory(directory); + kaha.deleteAllMessages(); + broker.setPersistenceAdapter(kaha); + return broker; + } - protected Connection createJmsConnection() throws JMSException { - return createConnectionFactory().createConnection(); - } + protected ConnectionFactory createConnectionFactory() { + return new ActiveMQConnectionFactory(broker.getVmConnectorURI()); + } - public void testMemoryUsage() throws Exception { - Connection conn = createJmsConnection(); - Session session = conn.createSession(true, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createQueue("queue.a.b"); - MessageProducer producer = session.createProducer(queue); - for (int i = 0; i < 100000; i++) { - BytesMessage bm = session.createBytesMessage(); - bm.writeBytes(new byte[1024]); - producer.send(bm); - if ((i + 1) % 100 == 0) { - session.commit(); - int memoryUsagePercent = broker.getSystemUsage().getMemoryUsage().getPercentUsage(); - LOG.info((i + 1) + " messages have been sent; broker memory usage " + memoryUsagePercent + "%"); - assertTrue("Used more than available broker memory", memoryUsagePercent <= 100); - } - } - session.commit(); - producer.close(); - session.close(); - conn.close(); - } + protected Connection createJmsConnection() throws JMSException { + return createConnectionFactory().createConnection(); + } + + public void testMemoryUsage() throws Exception { + Connection conn = createJmsConnection(); + Session session = conn.createSession(true, Session.AUTO_ACKNOWLEDGE); + Queue queue = session.createQueue("queue.a.b"); + MessageProducer producer = session.createProducer(queue); + for (int i = 0; i < 100000; i++) { + BytesMessage bm = session.createBytesMessage(); + bm.writeBytes(new byte[1024]); + producer.send(bm); + if ((i + 1) % 100 == 0) { + session.commit(); + int memoryUsagePercent = broker.getSystemUsage().getMemoryUsage().getPercentUsage(); + LOG.info((i + 1) + " messages have been sent; broker memory usage " + memoryUsagePercent + "%"); + assertTrue("Used more than available broker memory", memoryUsagePercent <= 100); + } + } + session.commit(); + producer.close(); + session.close(); + conn.close(); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/MemoryUsageCleanupTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/MemoryUsageCleanupTest.java index 017e070cb3..e89c93f50f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/MemoryUsageCleanupTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/MemoryUsageCleanupTest.java @@ -49,207 +49,210 @@ import org.slf4j.LoggerFactory; public class MemoryUsageCleanupTest { - private static final Logger LOG = LoggerFactory.getLogger(MemoryUsageCleanupTest.class); - private static final String QUEUE_NAME = MemoryUsageCleanupTest.class.getName() + "Queue"; + private static final Logger LOG = LoggerFactory.getLogger(MemoryUsageCleanupTest.class); + private static final String QUEUE_NAME = MemoryUsageCleanupTest.class.getName() + "Queue"; - private final String str = new String( - "QAa0bcLdUK2eHfJgTP8XhiFj61DOklNm9nBoI5pGqYVrs3CtSuMZvwWx4yE7zR"); + private final String str = new String("QAa0bcLdUK2eHfJgTP8XhiFj61DOklNm9nBoI5pGqYVrs3CtSuMZvwWx4yE7zR"); - private BrokerService broker; - private String connectionUri; - private ExecutorService pool; - private String queueName; - private Random r = new Random(); + private BrokerService broker; + private String connectionUri; + private ExecutorService pool; + private String queueName; + private Random r = new Random(); - @Before - public void setUp() throws Exception { + @Before + public void setUp() throws Exception { - broker = new BrokerService(); - broker.setDataDirectory("target" + File.separator + "activemq-data"); - broker.setPersistent(true); - broker.setUseJmx(true); - broker.setDedicatedTaskRunner(false); - broker.setAdvisorySupport(false); - broker.setDeleteAllMessagesOnStartup(true); + broker = new BrokerService(); + broker.setDataDirectory("target" + File.separator + "activemq-data"); + broker.setPersistent(true); + broker.setUseJmx(true); + broker.setDedicatedTaskRunner(false); + broker.setAdvisorySupport(false); + broker.setDeleteAllMessagesOnStartup(true); - SharedDeadLetterStrategy strategy = new SharedDeadLetterStrategy(); - strategy.setProcessExpired(false); - strategy.setProcessNonPersistent(false); + SharedDeadLetterStrategy strategy = new SharedDeadLetterStrategy(); + strategy.setProcessExpired(false); + strategy.setProcessNonPersistent(false); - PolicyEntry defaultPolicy = new PolicyEntry(); - defaultPolicy.setQueue(">"); - defaultPolicy.setOptimizedDispatch(true); - defaultPolicy.setDeadLetterStrategy(strategy); - defaultPolicy.setMemoryLimit(300000000); + PolicyEntry defaultPolicy = new PolicyEntry(); + defaultPolicy.setQueue(">"); + defaultPolicy.setOptimizedDispatch(true); + defaultPolicy.setDeadLetterStrategy(strategy); + defaultPolicy.setMemoryLimit(300000000); - PolicyMap policyMap = new PolicyMap(); - policyMap.setDefaultEntry(defaultPolicy); + PolicyMap policyMap = new PolicyMap(); + policyMap.setDefaultEntry(defaultPolicy); - broker.setDestinationPolicy(policyMap); + broker.setDestinationPolicy(policyMap); - broker.getSystemUsage().getMemoryUsage().setLimit(300000000L); + broker.getSystemUsage().getMemoryUsage().setLimit(300000000L); - broker.addConnector("tcp://localhost:0").setName("Default"); - broker.start(); - broker.waitUntilStarted(); + broker.addConnector("tcp://localhost:0").setName("Default"); + broker.start(); + broker.waitUntilStarted(); - connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); - pool = Executors.newFixedThreadPool(10); - } + connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); + pool = Executors.newFixedThreadPool(10); + } - @After - public void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } + @After + public void tearDown() throws Exception { + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } - if (pool != null) { - pool.shutdown(); - } - } + if (pool != null) { + pool.shutdown(); + } + } - @Test - public void testIt() throws Exception { + @Test + public void testIt() throws Exception { - final int startPercentage = broker.getAdminView().getMemoryPercentUsage(); - LOG.info("MemoryUsage at test start = " + startPercentage); + final int startPercentage = broker.getAdminView().getMemoryPercentUsage(); + LOG.info("MemoryUsage at test start = " + startPercentage); - for (int i = 0; i < 2; i++) { - LOG.info("Started the test iteration: " + i + " using queueName = " + queueName); - queueName = QUEUE_NAME + i; - final CountDownLatch latch = new CountDownLatch(11); - - pool.execute(new Runnable() { - @Override - public void run() { - receiveAndDiscard100messages(latch); - } - }); - - for (int j = 0; j < 10; j++) { - pool.execute(new Runnable() { - @Override - public void run() { - send10000messages(latch); - } - }); - } - - LOG.info("Waiting on the send / receive latch"); - latch.await(5, TimeUnit.MINUTES); - LOG.info("Resumed"); - - destroyQueue(); - TimeUnit.SECONDS.sleep(2); - } - - LOG.info("MemoryUsage before awaiting temp store cleanup = " + broker.getAdminView().getMemoryPercentUsage()); - - assertTrue("MemoryUsage should return to: " + startPercentage + - "% but was " + broker.getAdminView().getMemoryPercentUsage() + "%", Wait.waitFor(new Wait.Condition() { + for (int i = 0; i < 2; i++) { + LOG.info("Started the test iteration: " + i + " using queueName = " + queueName); + queueName = QUEUE_NAME + i; + final CountDownLatch latch = new CountDownLatch(11); + pool.execute(new Runnable() { @Override - public boolean isSatisified() throws Exception { - return broker.getAdminView().getMemoryPercentUsage() <= startPercentage + 1; + public void run() { + receiveAndDiscard100messages(latch); } - })); + }); - int endPercentage = broker.getAdminView().getMemoryPercentUsage(); - LOG.info("MemoryUsage at test end = " + endPercentage); - } + for (int j = 0; j < 10; j++) { + pool.execute(new Runnable() { + @Override + public void run() { + send10000messages(latch); + } + }); + } - public void destroyQueue() { - try { - Broker broker = this.broker.getBroker(); - if (!broker.isStopped()) { - LOG.info("Removing: " + queueName); - broker.removeDestination(this.broker.getAdminConnectionContext(), new ActiveMQQueue(queueName), 10); + LOG.info("Waiting on the send / receive latch"); + latch.await(5, TimeUnit.MINUTES); + LOG.info("Resumed"); + + destroyQueue(); + TimeUnit.SECONDS.sleep(2); + } + + LOG.info("MemoryUsage before awaiting temp store cleanup = " + broker.getAdminView().getMemoryPercentUsage()); + + assertTrue("MemoryUsage should return to: " + startPercentage + + "% but was " + broker.getAdminView().getMemoryPercentUsage() + "%", Wait.waitFor(new Wait.Condition() { + + @Override + public boolean isSatisified() throws Exception { + return broker.getAdminView().getMemoryPercentUsage() <= startPercentage + 1; + } + })); + + int endPercentage = broker.getAdminView().getMemoryPercentUsage(); + LOG.info("MemoryUsage at test end = " + endPercentage); + } + + public void destroyQueue() { + try { + Broker broker = this.broker.getBroker(); + if (!broker.isStopped()) { + LOG.info("Removing: " + queueName); + broker.removeDestination(this.broker.getAdminConnectionContext(), new ActiveMQQueue(queueName), 10); + } + } + catch (Exception e) { + LOG.warn("Got an error while removing the test queue", e); + } + } + + private void send10000messages(CountDownLatch latch) { + ActiveMQConnection activeMQConnection = null; + try { + activeMQConnection = createConnection(null); + Session session = activeMQConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(session.createQueue(queueName)); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + activeMQConnection.start(); + for (int i = 0; i < 10000; i++) { + TextMessage textMessage = session.createTextMessage(); + textMessage.setText(generateBody(1000)); + textMessage.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT); + producer.send(textMessage); + try { + Thread.sleep(10); } - } catch (Exception e) { - LOG.warn("Got an error while removing the test queue", e); - } - } - - private void send10000messages(CountDownLatch latch) { - ActiveMQConnection activeMQConnection = null; - try { - activeMQConnection = createConnection(null); - Session session = activeMQConnection.createSession(false, - Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(session - .createQueue(queueName)); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - activeMQConnection.start(); - for (int i = 0; i < 10000; i++) { - TextMessage textMessage = session.createTextMessage(); - textMessage.setText(generateBody(1000)); - textMessage.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT); - producer.send(textMessage); - try { - Thread.sleep(10); - } catch (InterruptedException e) { - } + catch (InterruptedException e) { } - producer.close(); - } catch (JMSException e) { - LOG.warn("Got an error while sending the messages", e); - } finally { - if (activeMQConnection != null) { - try { - activeMQConnection.close(); - } catch (JMSException e) { - } + } + producer.close(); + } + catch (JMSException e) { + LOG.warn("Got an error while sending the messages", e); + } + finally { + if (activeMQConnection != null) { + try { + activeMQConnection.close(); } - } - latch.countDown(); - } - - private void receiveAndDiscard100messages(CountDownLatch latch) { - ActiveMQConnection activeMQConnection = null; - try { - activeMQConnection = createConnection(null); - Session session = activeMQConnection.createSession(false, - Session.AUTO_ACKNOWLEDGE); - MessageConsumer messageConsumer = session.createConsumer( - session.createQueue(queueName)); - activeMQConnection.start(); - for (int i = 0; i < 100; i++) { - messageConsumer.receive(); + catch (JMSException e) { } - messageConsumer.close(); - LOG.info("Created and disconnected"); - } catch (JMSException e) { - LOG.warn("Got an error while receiving the messages", e); - } finally { - if (activeMQConnection != null) { - try { - activeMQConnection.close(); - } catch (JMSException e) { - } + } + } + latch.countDown(); + } + + private void receiveAndDiscard100messages(CountDownLatch latch) { + ActiveMQConnection activeMQConnection = null; + try { + activeMQConnection = createConnection(null); + Session session = activeMQConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer messageConsumer = session.createConsumer(session.createQueue(queueName)); + activeMQConnection.start(); + for (int i = 0; i < 100; i++) { + messageConsumer.receive(); + } + messageConsumer.close(); + LOG.info("Created and disconnected"); + } + catch (JMSException e) { + LOG.warn("Got an error while receiving the messages", e); + } + finally { + if (activeMQConnection != null) { + try { + activeMQConnection.close(); } - } - latch.countDown(); - } + catch (JMSException e) { + } + } + } + latch.countDown(); + } - private ActiveMQConnection createConnection(String id) throws JMSException { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - if (id != null) { - factory.setClientID(id); - } + private ActiveMQConnection createConnection(String id) throws JMSException { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); + if (id != null) { + factory.setClientID(id); + } - ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); - return connection; - } + ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); + return connection; + } - private String generateBody(int length) { + private String generateBody(int length) { - StringBuilder sb = new StringBuilder(); - int te = 0; - for (int i = 1; i <= length; i++) { - te = r.nextInt(62); - sb.append(str.charAt(te)); - } - return sb.toString(); - } + StringBuilder sb = new StringBuilder(); + int te = 0; + for (int i = 1; i <= length; i++) { + te = r.nextInt(62); + sb.append(str.charAt(te)); + } + return sb.toString(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/MessageExpirationReaperTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/MessageExpirationReaperTest.java index 4c8527a52c..3cdd0d6cc9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/MessageExpirationReaperTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/MessageExpirationReaperTest.java @@ -40,146 +40,146 @@ import org.junit.Test; */ public class MessageExpirationReaperTest { - private BrokerService broker; - private ConnectionFactory factory; - private ActiveMQConnection connection; - private final String destinationName = "TEST.Q"; - private final String brokerUrl = "tcp://localhost:0"; - private final String brokerName = "testBroker"; - private String connectionUri; + private BrokerService broker; + private ConnectionFactory factory; + private ActiveMQConnection connection; + private final String destinationName = "TEST.Q"; + private final String brokerUrl = "tcp://localhost:0"; + private final String brokerName = "testBroker"; + private String connectionUri; - @Before - public void init() throws Exception { - createBroker(); + @Before + public void init() throws Exception { + createBroker(); - connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); + connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); - factory = createConnectionFactory(); - connection = (ActiveMQConnection) factory.createConnection(); - connection.setClientID("test-connection"); - connection.start(); - } + factory = createConnectionFactory(); + connection = (ActiveMQConnection) factory.createConnection(); + connection.setClientID("test-connection"); + connection.start(); + } - @After - public void cleanUp() throws Exception { - connection.close(); - broker.stop(); - } + @After + public void cleanUp() throws Exception { + connection.close(); + broker.stop(); + } - protected void createBroker() throws Exception { - broker = new BrokerService(); - broker.setDeleteAllMessagesOnStartup(true); - broker.setBrokerName(brokerName); - broker.addConnector(brokerUrl); + protected void createBroker() throws Exception { + broker = new BrokerService(); + broker.setDeleteAllMessagesOnStartup(true); + broker.setBrokerName(brokerName); + broker.addConnector(brokerUrl); - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setExpireMessagesPeriod(500); - policyMap.setDefaultEntry(defaultEntry); - broker.setDestinationPolicy(policyMap); + PolicyMap policyMap = new PolicyMap(); + PolicyEntry defaultEntry = new PolicyEntry(); + defaultEntry.setExpireMessagesPeriod(500); + policyMap.setDefaultEntry(defaultEntry); + broker.setDestinationPolicy(policyMap); - broker.start(); - } + broker.start(); + } - protected ConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(connectionUri); - } + protected ConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory(connectionUri); + } - protected Session createSession() throws Exception { - return connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } + protected Session createSession() throws Exception { + return connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + } - @Test - public void testExpiredMessageReaping() throws Exception { + @Test + public void testExpiredMessageReaping() throws Exception { - Session producerSession = createSession(); - ActiveMQDestination destination = (ActiveMQDestination) producerSession.createQueue(destinationName); - MessageProducer producer = producerSession.createProducer(destination); - producer.setTimeToLive(1000); + Session producerSession = createSession(); + ActiveMQDestination destination = (ActiveMQDestination) producerSession.createQueue(destinationName); + MessageProducer producer = producerSession.createProducer(destination); + producer.setTimeToLive(1000); - final int count = 3; - // Send some messages with an expiration - for (int i = 0; i < count; i++) { - TextMessage message = producerSession.createTextMessage("" + i); - producer.send(message); - } + final int count = 3; + // Send some messages with an expiration + for (int i = 0; i < count; i++) { + TextMessage message = producerSession.createTextMessage("" + i); + producer.send(message); + } - // Let the messages expire - Thread.sleep(2000); + // Let the messages expire + Thread.sleep(2000); - DestinationViewMBean view = createView(destination); + DestinationViewMBean view = createView(destination); - assertEquals("Incorrect inflight count: " + view.getInFlightCount(), 0, view.getInFlightCount()); - assertEquals("Incorrect queue size count", 0, view.getQueueSize()); - assertEquals("Incorrect expired size count", view.getEnqueueCount(), view.getExpiredCount()); + assertEquals("Incorrect inflight count: " + view.getInFlightCount(), 0, view.getInFlightCount()); + assertEquals("Incorrect queue size count", 0, view.getQueueSize()); + assertEquals("Incorrect expired size count", view.getEnqueueCount(), view.getExpiredCount()); - // Send more messages with an expiration - for (int i = 0; i < count; i++) { - TextMessage message = producerSession.createTextMessage("" + i); - producer.send(message); - } + // Send more messages with an expiration + for (int i = 0; i < count; i++) { + TextMessage message = producerSession.createTextMessage("" + i); + producer.send(message); + } - // Let the messages expire - Thread.sleep(2000); + // Let the messages expire + Thread.sleep(2000); - // Simply browse the queue - Session browserSession = createSession(); - QueueBrowser browser = browserSession.createBrowser((Queue) destination); - assertFalse("no message in the browser", browser.getEnumeration().hasMoreElements()); + // Simply browse the queue + Session browserSession = createSession(); + QueueBrowser browser = browserSession.createBrowser((Queue) destination); + assertFalse("no message in the browser", browser.getEnumeration().hasMoreElements()); - // The messages expire and should be reaped because of the presence of - // the queue browser - assertEquals("Wrong inFlightCount: " + view.getInFlightCount(), 0, view.getInFlightCount()); - } + // The messages expire and should be reaped because of the presence of + // the queue browser + assertEquals("Wrong inFlightCount: " + view.getInFlightCount(), 0, view.getInFlightCount()); + } - @Test - public void testExpiredMessagesOnTopic() throws Exception{ - Session session = createSession(); + @Test + public void testExpiredMessagesOnTopic() throws Exception { + Session session = createSession(); - // use a zero prefetch so messages don't go inflight - ActiveMQTopic destination = new ActiveMQTopic(destinationName + "?consumer.prefetchSize=0"); + // use a zero prefetch so messages don't go inflight + ActiveMQTopic destination = new ActiveMQTopic(destinationName + "?consumer.prefetchSize=0"); - MessageProducer producer = session.createProducer(destination); + MessageProducer producer = session.createProducer(destination); - // should have a durable sub because it's a little tricky to get messages to expire in - // non-durable subs.. with durable subs, we can just expire in the topic using the expire - // period.. also.. durable sub has to be "inactive" for the expire checker to actually - // expire the messages - MessageConsumer consumer = session.createDurableSubscriber(destination, "test-durable"); + // should have a durable sub because it's a little tricky to get messages to expire in + // non-durable subs.. with durable subs, we can just expire in the topic using the expire + // period.. also.. durable sub has to be "inactive" for the expire checker to actually + // expire the messages + MessageConsumer consumer = session.createDurableSubscriber(destination, "test-durable"); - producer.setTimeToLive(500); + producer.setTimeToLive(500); - final int count = 3; - // Send some messages with an expiration - for (int i = 0; i < count; i++) { - TextMessage message = session.createTextMessage("" + i); - producer.send(message); - } + final int count = 3; + // Send some messages with an expiration + for (int i = 0; i < count; i++) { + TextMessage message = session.createTextMessage("" + i); + producer.send(message); + } - DestinationViewMBean view = createView(destination); - // not expired yet... - assertEquals("Incorrect enqueue count", 3, view.getEnqueueCount() ); + DestinationViewMBean view = createView(destination); + // not expired yet... + assertEquals("Incorrect enqueue count", 3, view.getEnqueueCount()); - // close consumer so topic thinks consumer is inactive - consumer.close(); + // close consumer so topic thinks consumer is inactive + consumer.close(); - // Let the messages reach an expiry time - Thread.sleep(2000); + // Let the messages reach an expiry time + Thread.sleep(2000); - assertEquals("Incorrect inflight count: " + view.getInFlightCount(), 0, view.getInFlightCount()); - assertEquals("Incorrect queue size count", 0, view.getQueueSize()); - assertEquals("Incorrect expired size count", view.getEnqueueCount(), view.getExpiredCount()); - } + assertEquals("Incorrect inflight count: " + view.getInFlightCount(), 0, view.getInFlightCount()); + assertEquals("Incorrect queue size count", 0, view.getQueueSize()); + assertEquals("Incorrect expired size count", view.getEnqueueCount(), view.getExpiredCount()); + } - protected DestinationViewMBean createView(ActiveMQDestination destination) throws Exception { - String domain = "org.apache.activemq"; - ObjectName name; - if (destination.isQueue()) { - name = new ObjectName(domain + ":type=Broker,brokerName=" + brokerName + ",destinationType=Queue,destinationName=" + destinationName); - } else { - name = new ObjectName(domain + ":type=Broker,brokerName=" + brokerName + ",destinationType=Topic,destinationName=" + destinationName); - } - return (DestinationViewMBean) broker.getManagementContext().newProxyInstance(name, DestinationViewMBean.class, - true); - } + protected DestinationViewMBean createView(ActiveMQDestination destination) throws Exception { + String domain = "org.apache.activemq"; + ObjectName name; + if (destination.isQueue()) { + name = new ObjectName(domain + ":type=Broker,brokerName=" + brokerName + ",destinationType=Queue,destinationName=" + destinationName); + } + else { + name = new ObjectName(domain + ":type=Broker,brokerName=" + brokerName + ",destinationType=Topic,destinationName=" + destinationName); + } + return (DestinationViewMBean) broker.getManagementContext().newProxyInstance(name, DestinationViewMBean.class, true); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/MessageSender.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/MessageSender.java index f85bdba8d9..e7d22b1574 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/MessageSender.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/MessageSender.java @@ -22,24 +22,28 @@ import javax.jms.ObjectMessage; import javax.jms.Session; public class MessageSender { - private MessageProducer producer; - private Session session; - public MessageSender(String queueName, Connection connection, boolean useTransactedSession, boolean topic) throws Exception { - session = useTransactedSession ? connection.createSession(true, Session.SESSION_TRANSACTED) : connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(topic ? session.createTopic(queueName) : session.createQueue(queueName)); - } + private MessageProducer producer; + private Session session; - public void send(String payload) throws Exception { - ObjectMessage message = session.createObjectMessage(); - message.setObject(payload); - producer.send(message); - if (session.getTransacted()) { - session.commit(); - } - } - - public MessageProducer getProducer() { - return producer; - } + public MessageSender(String queueName, + Connection connection, + boolean useTransactedSession, + boolean topic) throws Exception { + session = useTransactedSession ? connection.createSession(true, Session.SESSION_TRANSACTED) : connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer = session.createProducer(topic ? session.createTopic(queueName) : session.createQueue(queueName)); + } + + public void send(String payload) throws Exception { + ObjectMessage message = session.createObjectMessage(); + message.setObject(payload); + producer.send(message); + if (session.getTransacted()) { + session.commit(); + } + } + + public MessageProducer getProducer() { + return producer; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/MissingDataFileTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/MissingDataFileTest.java index 68055bbbe9..b278dc9328 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/MissingDataFileTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/MissingDataFileTest.java @@ -43,281 +43,291 @@ import org.slf4j.LoggerFactory; public class MissingDataFileTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(MissingDataFileTest.class); + private static final Logger LOG = LoggerFactory.getLogger(MissingDataFileTest.class); - private static int counter = 500; + private static int counter = 500; - private static int hectorToHaloCtr; - private static int xenaToHaloCtr; - private static int troyToHaloCtr; + private static int hectorToHaloCtr; + private static int xenaToHaloCtr; + private static int troyToHaloCtr; - private static int haloToHectorCtr; - private static int haloToXenaCtr; - private static int haloToTroyCtr; + private static int haloToHectorCtr; + private static int haloToXenaCtr; + private static int haloToTroyCtr; - private final String hectorToHalo = "hectorToHalo"; - private final String xenaToHalo = "xenaToHalo"; - private final String troyToHalo = "troyToHalo"; + private final String hectorToHalo = "hectorToHalo"; + private final String xenaToHalo = "xenaToHalo"; + private final String troyToHalo = "troyToHalo"; - private final String haloToHector = "haloToHector"; - private final String haloToXena = "haloToXena"; - private final String haloToTroy = "haloToTroy"; + private final String haloToHector = "haloToHector"; + private final String haloToXena = "haloToXena"; + private final String haloToTroy = "haloToTroy"; + private BrokerService broker; - private BrokerService broker; + private Connection hectorConnection; + private Connection xenaConnection; + private Connection troyConnection; + private Connection haloConnection; - private Connection hectorConnection; - private Connection xenaConnection; - private Connection troyConnection; - private Connection haloConnection; + private final Object lock = new Object(); + final boolean useTopic = false; + final boolean useSleep = true; - private final Object lock = new Object(); - final boolean useTopic = false; - final boolean useSleep = true; + protected static final String payload = new String(new byte[500]); - protected static final String payload = new String(new byte[500]); + public Connection createConnection() throws JMSException { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); + return factory.createConnection(); + } - public Connection createConnection() throws JMSException { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); - return factory.createConnection(); - } + public Session createSession(Connection connection, boolean transacted) throws JMSException { + return connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE); + } - public Session createSession(Connection connection, boolean transacted) throws JMSException { - return connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE); - } + public void startBroker() throws Exception { + broker = new BrokerService(); + broker.setDeleteAllMessagesOnStartup(true); + broker.setPersistent(true); + broker.setUseJmx(true); + broker.addConnector("tcp://localhost:61616").setName("Default"); - public void startBroker() throws Exception { - broker = new BrokerService(); - broker.setDeleteAllMessagesOnStartup(true); - broker.setPersistent(true); - broker.setUseJmx(true); - broker.addConnector("tcp://localhost:61616").setName("Default"); + SystemUsage systemUsage; + systemUsage = new SystemUsage(); + systemUsage.getMemoryUsage().setLimit(10 * 1024 * 1024); // Just a few messags + broker.setSystemUsage(systemUsage); - SystemUsage systemUsage; - systemUsage = new SystemUsage(); - systemUsage.getMemoryUsage().setLimit(10 * 1024 * 1024); // Just a few messags - broker.setSystemUsage(systemUsage); + KahaDBPersistenceAdapter kahaDBPersistenceAdapter = new KahaDBPersistenceAdapter(); + kahaDBPersistenceAdapter.setJournalMaxFileLength(16 * 1024); + kahaDBPersistenceAdapter.setCleanupInterval(500); + broker.setPersistenceAdapter(kahaDBPersistenceAdapter); - KahaDBPersistenceAdapter kahaDBPersistenceAdapter = new KahaDBPersistenceAdapter(); - kahaDBPersistenceAdapter.setJournalMaxFileLength(16*1024); - kahaDBPersistenceAdapter.setCleanupInterval(500); - broker.setPersistenceAdapter(kahaDBPersistenceAdapter); + broker.start(); + LOG.info("Starting broker.."); + } - broker.start(); - LOG.info("Starting broker.."); - } + @Override + public void tearDown() throws Exception { + hectorConnection.close(); + xenaConnection.close(); + troyConnection.close(); + haloConnection.close(); + broker.stop(); + } - @Override - public void tearDown() throws Exception { - hectorConnection.close(); - xenaConnection.close(); - troyConnection.close(); - haloConnection.close(); - broker.stop(); - } + public void testForNoDataFoundError() throws Exception { - public void testForNoDataFoundError() throws Exception { - - startBroker(); - hectorConnection = createConnection(); - Thread hectorThread = buildProducer(hectorConnection, hectorToHalo, false, useTopic); - Receiver hHectorReceiver = new Receiver() { - @Override - public void receive(String s) throws Exception { - haloToHectorCtr++; - if (haloToHectorCtr >= counter) { - synchronized (lock) { - lock.notifyAll(); - } - } - possiblySleep(haloToHectorCtr); + startBroker(); + hectorConnection = createConnection(); + Thread hectorThread = buildProducer(hectorConnection, hectorToHalo, false, useTopic); + Receiver hHectorReceiver = new Receiver() { + @Override + public void receive(String s) throws Exception { + haloToHectorCtr++; + if (haloToHectorCtr >= counter) { + synchronized (lock) { + lock.notifyAll(); + } } - }; - buildReceiver(hectorConnection, haloToHector, false, hHectorReceiver, useTopic); + possiblySleep(haloToHectorCtr); + } + }; + buildReceiver(hectorConnection, haloToHector, false, hHectorReceiver, useTopic); - troyConnection = createConnection(); - Thread troyThread = buildProducer(troyConnection, troyToHalo); - Receiver hTroyReceiver = new Receiver() { - @Override - public void receive(String s) throws Exception { - haloToTroyCtr++; - if (haloToTroyCtr >= counter) { - synchronized (lock) { - lock.notifyAll(); - } - } - possiblySleep(haloToTroyCtr); + troyConnection = createConnection(); + Thread troyThread = buildProducer(troyConnection, troyToHalo); + Receiver hTroyReceiver = new Receiver() { + @Override + public void receive(String s) throws Exception { + haloToTroyCtr++; + if (haloToTroyCtr >= counter) { + synchronized (lock) { + lock.notifyAll(); + } } - }; - buildReceiver(hectorConnection, haloToTroy, false, hTroyReceiver, false); + possiblySleep(haloToTroyCtr); + } + }; + buildReceiver(hectorConnection, haloToTroy, false, hTroyReceiver, false); - xenaConnection = createConnection(); - Thread xenaThread = buildProducer(xenaConnection, xenaToHalo); - Receiver hXenaReceiver = new Receiver() { - @Override - public void receive(String s) throws Exception { - haloToXenaCtr++; - if (haloToXenaCtr >= counter) { - synchronized (lock) { - lock.notifyAll(); - } - } - possiblySleep(haloToXenaCtr); + xenaConnection = createConnection(); + Thread xenaThread = buildProducer(xenaConnection, xenaToHalo); + Receiver hXenaReceiver = new Receiver() { + @Override + public void receive(String s) throws Exception { + haloToXenaCtr++; + if (haloToXenaCtr >= counter) { + synchronized (lock) { + lock.notifyAll(); + } } - }; - buildReceiver(xenaConnection, haloToXena, false, hXenaReceiver, false); + possiblySleep(haloToXenaCtr); + } + }; + buildReceiver(xenaConnection, haloToXena, false, hXenaReceiver, false); - haloConnection = createConnection(); - final MessageSender hectorSender = buildTransactionalProducer(haloToHector, haloConnection, false); - final MessageSender troySender = buildTransactionalProducer(haloToTroy, haloConnection, false); - final MessageSender xenaSender = buildTransactionalProducer(haloToXena, haloConnection, false); - Receiver hectorReceiver = new Receiver() { - @Override - public void receive(String s) throws Exception { - hectorToHaloCtr++; - troySender.send(payload); - if (hectorToHaloCtr >= counter) { - synchronized (lock) { - lock.notifyAll(); - } - possiblySleep(hectorToHaloCtr); - } + haloConnection = createConnection(); + final MessageSender hectorSender = buildTransactionalProducer(haloToHector, haloConnection, false); + final MessageSender troySender = buildTransactionalProducer(haloToTroy, haloConnection, false); + final MessageSender xenaSender = buildTransactionalProducer(haloToXena, haloConnection, false); + Receiver hectorReceiver = new Receiver() { + @Override + public void receive(String s) throws Exception { + hectorToHaloCtr++; + troySender.send(payload); + if (hectorToHaloCtr >= counter) { + synchronized (lock) { + lock.notifyAll(); + } + possiblySleep(hectorToHaloCtr); } - }; - Receiver xenaReceiver = new Receiver() { - @Override - public void receive(String s) throws Exception { - xenaToHaloCtr++; - hectorSender.send(payload); - if (xenaToHaloCtr >= counter) { - synchronized (lock) { - lock.notifyAll(); - } - } - possiblySleep(xenaToHaloCtr); + } + }; + Receiver xenaReceiver = new Receiver() { + @Override + public void receive(String s) throws Exception { + xenaToHaloCtr++; + hectorSender.send(payload); + if (xenaToHaloCtr >= counter) { + synchronized (lock) { + lock.notifyAll(); + } } - }; - Receiver troyReceiver = new Receiver() { - @Override - public void receive(String s) throws Exception { - troyToHaloCtr++; - xenaSender.send(payload); - if (troyToHaloCtr >= counter) { - synchronized (lock) { - lock.notifyAll(); - } - } + possiblySleep(xenaToHaloCtr); + } + }; + Receiver troyReceiver = new Receiver() { + @Override + public void receive(String s) throws Exception { + troyToHaloCtr++; + xenaSender.send(payload); + if (troyToHaloCtr >= counter) { + synchronized (lock) { + lock.notifyAll(); + } } - }; - buildReceiver(haloConnection, hectorToHalo, true, hectorReceiver, false); - buildReceiver(haloConnection, xenaToHalo, true, xenaReceiver, false); - buildReceiver(haloConnection, troyToHalo, true, troyReceiver, false); + } + }; + buildReceiver(haloConnection, hectorToHalo, true, hectorReceiver, false); + buildReceiver(haloConnection, xenaToHalo, true, xenaReceiver, false); + buildReceiver(haloConnection, troyToHalo, true, troyReceiver, false); - haloConnection.start(); + haloConnection.start(); - troyConnection.start(); - troyThread.start(); + troyConnection.start(); + troyThread.start(); - xenaConnection.start(); - xenaThread.start(); + xenaConnection.start(); + xenaThread.start(); - hectorConnection.start(); - hectorThread.start(); - waitForMessagesToBeDelivered(); - // number of messages received should match messages sent - assertEquals(hectorToHaloCtr, counter); - LOG.info("hectorToHalo received " + hectorToHaloCtr + " messages"); - assertEquals(xenaToHaloCtr, counter); - LOG.info("xenaToHalo received " + xenaToHaloCtr + " messages"); - assertEquals(troyToHaloCtr, counter); - LOG.info("troyToHalo received " + troyToHaloCtr + " messages"); - assertEquals(haloToHectorCtr, counter); - LOG.info("haloToHector received " + haloToHectorCtr + " messages"); - assertEquals(haloToXenaCtr, counter); - LOG.info("haloToXena received " + haloToXenaCtr + " messages"); - assertEquals(haloToTroyCtr, counter); - LOG.info("haloToTroy received " + haloToTroyCtr + " messages"); + hectorConnection.start(); + hectorThread.start(); + waitForMessagesToBeDelivered(); + // number of messages received should match messages sent + assertEquals(hectorToHaloCtr, counter); + LOG.info("hectorToHalo received " + hectorToHaloCtr + " messages"); + assertEquals(xenaToHaloCtr, counter); + LOG.info("xenaToHalo received " + xenaToHaloCtr + " messages"); + assertEquals(troyToHaloCtr, counter); + LOG.info("troyToHalo received " + troyToHaloCtr + " messages"); + assertEquals(haloToHectorCtr, counter); + LOG.info("haloToHector received " + haloToHectorCtr + " messages"); + assertEquals(haloToXenaCtr, counter); + LOG.info("haloToXena received " + haloToXenaCtr + " messages"); + assertEquals(haloToTroyCtr, counter); + LOG.info("haloToTroy received " + haloToTroyCtr + " messages"); - } + } - protected void possiblySleep(int count) throws InterruptedException { - if (useSleep) { - if (count % 100 == 0) { - Thread.sleep(5000); + protected void possiblySleep(int count) throws InterruptedException { + if (useSleep) { + if (count % 100 == 0) { + Thread.sleep(5000); + } + } + + } + + protected void waitForMessagesToBeDelivered() { + // let's give the listeners enough time to read all messages + long maxWaitTime = counter * 1000; + long waitTime = maxWaitTime; + long start = (maxWaitTime <= 0) ? 0 : System.currentTimeMillis(); + + synchronized (lock) { + boolean hasMessages = true; + while (hasMessages && waitTime >= 0) { + try { + lock.wait(200); } - } - - } - - protected void waitForMessagesToBeDelivered() { - // let's give the listeners enough time to read all messages - long maxWaitTime = counter * 1000; - long waitTime = maxWaitTime; - long start = (maxWaitTime <= 0) ? 0 : System.currentTimeMillis(); - - synchronized (lock) { - boolean hasMessages = true; - while (hasMessages && waitTime >= 0) { - try { - lock.wait(200); - } catch (InterruptedException e) { - LOG.error(e.toString()); - } - // check if all messages have been received - hasMessages = hectorToHaloCtr < counter || xenaToHaloCtr < counter || troyToHaloCtr < counter || haloToHectorCtr < counter || haloToXenaCtr < counter - || haloToTroyCtr < counter; - waitTime = maxWaitTime - (System.currentTimeMillis() - start); + catch (InterruptedException e) { + LOG.error(e.toString()); } - } - } + // check if all messages have been received + hasMessages = hectorToHaloCtr < counter || xenaToHaloCtr < counter || troyToHaloCtr < counter || haloToHectorCtr < counter || haloToXenaCtr < counter || haloToTroyCtr < counter; + waitTime = maxWaitTime - (System.currentTimeMillis() - start); + } + } + } - public MessageSender buildTransactionalProducer(String queueName, Connection connection, boolean isTopic) throws Exception { + public MessageSender buildTransactionalProducer(String queueName, + Connection connection, + boolean isTopic) throws Exception { - return new MessageSender(queueName, connection, true, isTopic); - } + return new MessageSender(queueName, connection, true, isTopic); + } - public Thread buildProducer(Connection connection, final String queueName) throws Exception { - return buildProducer(connection, queueName, false, false); - } + public Thread buildProducer(Connection connection, final String queueName) throws Exception { + return buildProducer(connection, queueName, false, false); + } - public Thread buildProducer(Connection connection, final String queueName, boolean transacted, boolean isTopic) throws Exception { - final MessageSender producer = new MessageSender(queueName, connection, transacted, isTopic); - Thread thread = new Thread() { - @Override - public synchronized void run() { - for (int i = 0; i < counter; i++) { - try { - producer.send(payload ); - } catch (Exception e) { - throw new RuntimeException("on " + queueName + " send", e); - } - } + public Thread buildProducer(Connection connection, + final String queueName, + boolean transacted, + boolean isTopic) throws Exception { + final MessageSender producer = new MessageSender(queueName, connection, transacted, isTopic); + Thread thread = new Thread() { + @Override + public synchronized void run() { + for (int i = 0; i < counter; i++) { + try { + producer.send(payload); + } + catch (Exception e) { + throw new RuntimeException("on " + queueName + " send", e); + } } - }; - return thread; - } + } + }; + return thread; + } - public void buildReceiver(Connection connection, final String queueName, boolean transacted, final Receiver receiver, boolean isTopic) throws Exception { - final Session session = transacted ? connection.createSession(true, Session.SESSION_TRANSACTED) : connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer inputMessageConsumer = session.createConsumer(isTopic ? session.createTopic(queueName) : session.createQueue(queueName)); - MessageListener messageListener = new MessageListener() { + public void buildReceiver(Connection connection, + final String queueName, + boolean transacted, + final Receiver receiver, + boolean isTopic) throws Exception { + final Session session = transacted ? connection.createSession(true, Session.SESSION_TRANSACTED) : connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer inputMessageConsumer = session.createConsumer(isTopic ? session.createTopic(queueName) : session.createQueue(queueName)); + MessageListener messageListener = new MessageListener() { - @Override - public void onMessage(Message message) { - try { - ObjectMessage objectMessage = (ObjectMessage)message; - String s = (String)objectMessage.getObject(); - receiver.receive(s); - if (session.getTransacted()) { - session.commit(); - } + @Override + public void onMessage(Message message) { + try { + ObjectMessage objectMessage = (ObjectMessage) message; + String s = (String) objectMessage.getObject(); + receiver.receive(s); + if (session.getTransacted()) { + session.commit(); + } - } catch (Exception e) { - e.printStackTrace(); - } } - }; - inputMessageConsumer.setMessageListener(messageListener); - } + catch (Exception e) { + e.printStackTrace(); + } + } + }; + inputMessageConsumer.setMessageListener(messageListener); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/OptimizeAcknowledgeWithExpiredMsgsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/OptimizeAcknowledgeWithExpiredMsgsTest.java index 43f332b7c6..88426db44f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/OptimizeAcknowledgeWithExpiredMsgsTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/OptimizeAcknowledgeWithExpiredMsgsTest.java @@ -47,266 +47,261 @@ import org.slf4j.LoggerFactory; * A consumer may be stalled in case it uses optimizeAcknowledge and receives * a number of messages that expire before being dispatched to application code. * See for more details. - * */ public class OptimizeAcknowledgeWithExpiredMsgsTest { - private final static Logger LOG = LoggerFactory.getLogger(OptimizeAcknowledgeWithExpiredMsgsTest.class); + private final static Logger LOG = LoggerFactory.getLogger(OptimizeAcknowledgeWithExpiredMsgsTest.class); - private BrokerService broker = null; + private BrokerService broker = null; - private String connectionUri; + private String connectionUri; - /** - * Creates a broker instance but does not start it. - * - * @param brokerUri - transport uri of broker - * @param brokerName - name for the broker - * @return a BrokerService instance with transport uri and broker name set - * @throws Exception - */ - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setPersistent(false); - broker.setDeleteAllMessagesOnStartup(true); - broker.setUseJmx(false); - connectionUri = broker.addConnector("tcp://localhost:0").getPublishableConnectString(); - return broker; - } + /** + * Creates a broker instance but does not start it. + * + * @param brokerUri - transport uri of broker + * @param brokerName - name for the broker + * @return a BrokerService instance with transport uri and broker name set + * @throws Exception + */ + protected BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setPersistent(false); + broker.setDeleteAllMessagesOnStartup(true); + broker.setUseJmx(false); + connectionUri = broker.addConnector("tcp://localhost:0").getPublishableConnectString(); + return broker; + } - @Before - public void setUp() throws Exception { - broker = createBroker(); - broker.start(); - broker.waitUntilStarted(); - } + @Before + public void setUp() throws Exception { + broker = createBroker(); + broker.start(); + broker.waitUntilStarted(); + } - @After - public void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - broker = null; - } - } + @After + public void tearDown() throws Exception { + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + broker = null; + } + } - /** - * Tests for AMQ-3965 - * Creates connection into broker using optimzeAcknowledge and prefetch=100 - * Creates producer and consumer. Producer sends 45 msgs that will expire - * at consumer (but before being dispatched to app code). - * Producer then sends 60 msgs without expiry. - * - * Consumer receives msgs using a MessageListener and increments a counter. - * Main thread sleeps for 5 seconds and checks the counter value. - * If counter != 60 msgs (the number of msgs that should get dispatched - * to consumer) the test fails. - */ - @Test - public void testOptimizedAckWithExpiredMsgs() throws Exception - { - ActiveMQConnectionFactory connectionFactory = - new ActiveMQConnectionFactory(connectionUri + "?jms.optimizeAcknowledge=true&jms.prefetchPolicy.all=100"); + /** + * Tests for AMQ-3965 + * Creates connection into broker using optimzeAcknowledge and prefetch=100 + * Creates producer and consumer. Producer sends 45 msgs that will expire + * at consumer (but before being dispatched to app code). + * Producer then sends 60 msgs without expiry. + * + * Consumer receives msgs using a MessageListener and increments a counter. + * Main thread sleeps for 5 seconds and checks the counter value. + * If counter != 60 msgs (the number of msgs that should get dispatched + * to consumer) the test fails. + */ + @Test + public void testOptimizedAckWithExpiredMsgs() throws Exception { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionUri + "?jms.optimizeAcknowledge=true&jms.prefetchPolicy.all=100"); - // Create JMS resources - Connection connection = connectionFactory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue("TEST.FOO"); + // Create JMS resources + Connection connection = connectionFactory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue("TEST.FOO"); - // ***** Consumer code ***** - MessageConsumer consumer = session.createConsumer(destination); + // ***** Consumer code ***** + MessageConsumer consumer = session.createConsumer(destination); - final MyMessageListener listener = new MyMessageListener(); - connection.setExceptionListener((ExceptionListener) listener); + final MyMessageListener listener = new MyMessageListener(); + connection.setExceptionListener((ExceptionListener) listener); - // ***** Producer Code ***** - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + // ***** Producer Code ***** + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - String text = "Hello world! From: " + Thread.currentThread().getName() + " : " + this.hashCode(); - TextMessage message; + String text = "Hello world! From: " + Thread.currentThread().getName() + " : " + this.hashCode(); + TextMessage message; - // Produce msgs that will expire quickly - for (int i=0; i<45; i++) { - message = session.createTextMessage(text); - producer.send(message,1,1,100); - LOG.trace("Sent message: "+ message.getJMSMessageID() + - " with expiry 10 msec"); - } - // Produce msgs that don't expire - for (int i=0; i<60; i++) { - message = session.createTextMessage(text); - producer.send(message,1,1,60000); - // producer.send(message); - LOG.trace("Sent message: "+ message.getJMSMessageID() + - " with expiry 30 sec"); - } - consumer.setMessageListener(listener); + // Produce msgs that will expire quickly + for (int i = 0; i < 45; i++) { + message = session.createTextMessage(text); + producer.send(message, 1, 1, 100); + LOG.trace("Sent message: " + message.getJMSMessageID() + + " with expiry 10 msec"); + } + // Produce msgs that don't expire + for (int i = 0; i < 60; i++) { + message = session.createTextMessage(text); + producer.send(message, 1, 1, 60000); + // producer.send(message); + LOG.trace("Sent message: " + message.getJMSMessageID() + + " with expiry 30 sec"); + } + consumer.setMessageListener(listener); - sleep(1000); // let the batch of 45 expire. + sleep(1000); // let the batch of 45 expire. - connection.start(); + connection.start(); - assertTrue("Should receive all expected messages, counter at " + listener.getCounter(), Wait.waitFor(new Wait.Condition() { + assertTrue("Should receive all expected messages, counter at " + listener.getCounter(), Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return listener.getCounter() == 60; - } - })); + @Override + public boolean isSatisified() throws Exception { + return listener.getCounter() == 60; + } + })); - LOG.info("Received all expected messages with counter at: " + listener.getCounter()); + LOG.info("Received all expected messages with counter at: " + listener.getCounter()); - // Cleanup - producer.close(); - consumer.close(); - session.close(); - connection.close(); - } + // Cleanup + producer.close(); + consumer.close(); + session.close(); + connection.close(); + } - @Test - public void testOptimizedAckWithExpiredMsgsSync() throws Exception - { - ActiveMQConnectionFactory connectionFactory = - new ActiveMQConnectionFactory(connectionUri + "?jms.optimizeAcknowledge=true&jms.prefetchPolicy.all=100"); + @Test + public void testOptimizedAckWithExpiredMsgsSync() throws Exception { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionUri + "?jms.optimizeAcknowledge=true&jms.prefetchPolicy.all=100"); - // Create JMS resources - Connection connection = connectionFactory.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue("TEST.FOO"); + // Create JMS resources + Connection connection = connectionFactory.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue("TEST.FOO"); - // ***** Consumer code ***** - MessageConsumer consumer = session.createConsumer(destination); + // ***** Consumer code ***** + MessageConsumer consumer = session.createConsumer(destination); - // ***** Producer Code ***** - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + // ***** Producer Code ***** + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - String text = "Hello world! From: " + Thread.currentThread().getName() + " : " + this.hashCode(); - TextMessage message; + String text = "Hello world! From: " + Thread.currentThread().getName() + " : " + this.hashCode(); + TextMessage message; - // Produce msgs that will expire quickly - for (int i=0; i<45; i++) { - message = session.createTextMessage(text); - producer.send(message,1,1,10); - LOG.trace("Sent message: "+ message.getJMSMessageID() + - " with expiry 10 msec"); - } - // Produce msgs that don't expire - for (int i=0; i<60; i++) { - message = session.createTextMessage(text); - producer.send(message,1,1,30000); - // producer.send(message); - LOG.trace("Sent message: "+ message.getJMSMessageID() + - " with expiry 30 sec"); - } - sleep(200); + // Produce msgs that will expire quickly + for (int i = 0; i < 45; i++) { + message = session.createTextMessage(text); + producer.send(message, 1, 1, 10); + LOG.trace("Sent message: " + message.getJMSMessageID() + + " with expiry 10 msec"); + } + // Produce msgs that don't expire + for (int i = 0; i < 60; i++) { + message = session.createTextMessage(text); + producer.send(message, 1, 1, 30000); + // producer.send(message); + LOG.trace("Sent message: " + message.getJMSMessageID() + + " with expiry 30 sec"); + } + sleep(200); - int counter = 1; - for (; counter <= 60; ++counter) { - assertNotNull(consumer.receive(2000)); - LOG.info("counter at " + counter); - } - LOG.info("Received all expected messages with counter at: " + counter); + int counter = 1; + for (; counter <= 60; ++counter) { + assertNotNull(consumer.receive(2000)); + LOG.info("counter at " + counter); + } + LOG.info("Received all expected messages with counter at: " + counter); - // Cleanup - producer.close(); - consumer.close(); - session.close(); - connection.close(); - } + // Cleanup + producer.close(); + consumer.close(); + session.close(); + connection.close(); + } - @Test - public void testOptimizedAckWithExpiredMsgsSync2() throws Exception - { - ActiveMQConnectionFactory connectionFactory = - new ActiveMQConnectionFactory(connectionUri + "?jms.optimizeAcknowledge=true&jms.prefetchPolicy.all=100"); + @Test + public void testOptimizedAckWithExpiredMsgsSync2() throws Exception { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionUri + "?jms.optimizeAcknowledge=true&jms.prefetchPolicy.all=100"); - // Create JMS resources - Connection connection = connectionFactory.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue("TEST.FOO"); + // Create JMS resources + Connection connection = connectionFactory.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue("TEST.FOO"); - // ***** Consumer code ***** - MessageConsumer consumer = session.createConsumer(destination); + // ***** Consumer code ***** + MessageConsumer consumer = session.createConsumer(destination); - // ***** Producer Code ***** - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + // ***** Producer Code ***** + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - String text = "Hello world! From: " + Thread.currentThread().getName() + " : " + this.hashCode(); - TextMessage message; + String text = "Hello world! From: " + Thread.currentThread().getName() + " : " + this.hashCode(); + TextMessage message; - // Produce msgs that don't expire - for (int i=0; i<56; i++) { - message = session.createTextMessage(text); - producer.send(message,1,1,30000); - // producer.send(message); - LOG.trace("Sent message: "+ message.getJMSMessageID() + - " with expiry 30 sec"); - } - // Produce msgs that will expire quickly - for (int i=0; i<44; i++) { - message = session.createTextMessage(text); - producer.send(message,1,1,10); - LOG.trace("Sent message: "+ message.getJMSMessageID() + - " with expiry 10 msec"); - } - // Produce some moremsgs that don't expire - for (int i=0; i<4; i++) { - message = session.createTextMessage(text); - producer.send(message,1,1,30000); - // producer.send(message); - LOG.trace("Sent message: "+ message.getJMSMessageID() + - " with expiry 30 sec"); - } + // Produce msgs that don't expire + for (int i = 0; i < 56; i++) { + message = session.createTextMessage(text); + producer.send(message, 1, 1, 30000); + // producer.send(message); + LOG.trace("Sent message: " + message.getJMSMessageID() + + " with expiry 30 sec"); + } + // Produce msgs that will expire quickly + for (int i = 0; i < 44; i++) { + message = session.createTextMessage(text); + producer.send(message, 1, 1, 10); + LOG.trace("Sent message: " + message.getJMSMessageID() + + " with expiry 10 msec"); + } + // Produce some moremsgs that don't expire + for (int i = 0; i < 4; i++) { + message = session.createTextMessage(text); + producer.send(message, 1, 1, 30000); + // producer.send(message); + LOG.trace("Sent message: " + message.getJMSMessageID() + + " with expiry 30 sec"); + } - sleep(200); + sleep(200); - int counter = 1; - for (; counter <= 60; ++counter) { - assertNotNull(consumer.receive(2000)); - LOG.info("counter at " + counter); - } - LOG.info("Received all expected messages with counter at: " + counter); + int counter = 1; + for (; counter <= 60; ++counter) { + assertNotNull(consumer.receive(2000)); + LOG.info("counter at " + counter); + } + LOG.info("Received all expected messages with counter at: " + counter); - // Cleanup - producer.close(); - consumer.close(); - session.close(); - connection.close(); - } + // Cleanup + producer.close(); + consumer.close(); + session.close(); + connection.close(); + } - private void sleep(int milliSecondTime) { - try { - Thread.sleep(milliSecondTime); - } catch (InterruptedException igonred) { - } - } + private void sleep(int milliSecondTime) { + try { + Thread.sleep(milliSecondTime); + } + catch (InterruptedException igonred) { + } + } - /** - * Standard JMS MessageListener - */ - private class MyMessageListener implements MessageListener, ExceptionListener { + /** + * Standard JMS MessageListener + */ + private class MyMessageListener implements MessageListener, ExceptionListener { - private AtomicInteger counter = new AtomicInteger(0); + private AtomicInteger counter = new AtomicInteger(0); - public void onMessage(final Message message) { - try { - LOG.trace("Got Message " + message.getJMSMessageID()); - LOG.info("counter at " + counter.incrementAndGet()); - } catch (final Exception e) { - } - } + public void onMessage(final Message message) { + try { + LOG.trace("Got Message " + message.getJMSMessageID()); + LOG.info("counter at " + counter.incrementAndGet()); + } + catch (final Exception e) { + } + } - public int getCounter() { - return counter.get(); - } + public int getCounter() { + return counter.get(); + } - public synchronized void onException(JMSException ex) { - LOG.error("JMS Exception occurred. Shutting down client."); - } - } + public synchronized void onException(JMSException ex) { + LOG.error("JMS Exception occurred. Shutting down client."); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/OutOfOrderTestCase.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/OutOfOrderTestCase.java index 34e3866749..88d552af1c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/OutOfOrderTestCase.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/OutOfOrderTestCase.java @@ -36,96 +36,96 @@ import org.slf4j.LoggerFactory; public class OutOfOrderTestCase extends TestCase { - private static final Logger log = LoggerFactory.getLogger(OutOfOrderTestCase.class); + private static final Logger log = LoggerFactory.getLogger(OutOfOrderTestCase.class); - private static final String BROKER_URL = "tcp://localhost:0"; - private static final int PREFETCH = 10; - private static final String CONNECTION_URL_OPTIONS = "?jms.prefetchPolicy.all=" + PREFETCH; + private static final String BROKER_URL = "tcp://localhost:0"; + private static final int PREFETCH = 10; + private static final String CONNECTION_URL_OPTIONS = "?jms.prefetchPolicy.all=" + PREFETCH; - private static final String DESTINATION = "QUEUE?consumer.exclusive=true"; + private static final String DESTINATION = "QUEUE?consumer.exclusive=true"; - private BrokerService brokerService; - private Session session; - private Connection connection; - private String connectionUri; + private BrokerService brokerService; + private Session session; + private Connection connection; + private String connectionUri; - private int seq = 0; + private int seq = 0; - public void setUp() throws Exception { - brokerService = new BrokerService(); - brokerService.setUseJmx(true); - brokerService.addConnector(BROKER_URL); - brokerService.deleteAllMessages(); - brokerService.start(); - brokerService.waitUntilStarted(); + public void setUp() throws Exception { + brokerService = new BrokerService(); + brokerService.setUseJmx(true); + brokerService.addConnector(BROKER_URL); + brokerService.deleteAllMessages(); + brokerService.start(); + brokerService.waitUntilStarted(); - connectionUri = brokerService.getTransportConnectors().get(0).getPublishableConnectString(); + connectionUri = brokerService.getTransportConnectors().get(0).getPublishableConnectString(); - ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionUri + CONNECTION_URL_OPTIONS); - connection = connectionFactory.createConnection(); - connection.start(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - } + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionUri + CONNECTION_URL_OPTIONS); + connection = connectionFactory.createConnection(); + connection.start(); + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + } - protected void tearDown() throws Exception { - session.close(); - connection.close(); - brokerService.stop(); - } + protected void tearDown() throws Exception { + session.close(); + connection.close(); + brokerService.stop(); + } - public void testOrder() throws Exception { + public void testOrder() throws Exception { - log.info("Producing messages 0-29 . . ."); - Destination destination = session.createQueue(DESTINATION); - final MessageProducer messageProducer = session - .createProducer(destination); - try { - for (int i = 0; i < 30; ++i) { - final Message message = session - .createTextMessage(createMessageText(i)); - message.setStringProperty("JMSXGroupID", "FOO"); + log.info("Producing messages 0-29 . . ."); + Destination destination = session.createQueue(DESTINATION); + final MessageProducer messageProducer = session.createProducer(destination); + try { + for (int i = 0; i < 30; ++i) { + final Message message = session.createTextMessage(createMessageText(i)); + message.setStringProperty("JMSXGroupID", "FOO"); - messageProducer.send(message); - log.info("sent " + toString(message)); - } - } finally { - messageProducer.close(); - } + messageProducer.send(message); + log.info("sent " + toString(message)); + } + } + finally { + messageProducer.close(); + } - log.info("Consuming messages 0-9 . . ."); - consumeBatch(); + log.info("Consuming messages 0-9 . . ."); + consumeBatch(); - log.info("Consuming messages 10-19 . . ."); - consumeBatch(); + log.info("Consuming messages 10-19 . . ."); + consumeBatch(); - log.info("Consuming messages 20-29 . . ."); - consumeBatch(); - } + log.info("Consuming messages 20-29 . . ."); + consumeBatch(); + } - protected void consumeBatch() throws Exception { - Destination destination = session.createQueue(DESTINATION); - final MessageConsumer messageConsumer = session.createConsumer(destination); - try { - for (int i = 0; i < 10; ++i) { - final Message message = messageConsumer.receive(1000L); - log.info("received " + toString(message)); - assertEquals("Message out of order", createMessageText(seq++), ((TextMessage) message).getText()); - message.acknowledge(); - } - } finally { - messageConsumer.close(); - } - } + protected void consumeBatch() throws Exception { + Destination destination = session.createQueue(DESTINATION); + final MessageConsumer messageConsumer = session.createConsumer(destination); + try { + for (int i = 0; i < 10; ++i) { + final Message message = messageConsumer.receive(1000L); + log.info("received " + toString(message)); + assertEquals("Message out of order", createMessageText(seq++), ((TextMessage) message).getText()); + message.acknowledge(); + } + } + finally { + messageConsumer.close(); + } + } - private String toString(final Message message) throws JMSException { - String ret = "received message '" + ((TextMessage) message).getText() + "' - " + message.getJMSMessageID(); - if (message.getJMSRedelivered()) - ret += " (redelivered)"; - return ret; + private String toString(final Message message) throws JMSException { + String ret = "received message '" + ((TextMessage) message).getText() + "' - " + message.getJMSMessageID(); + if (message.getJMSRedelivered()) + ret += " (redelivered)"; + return ret; - } + } - private static String createMessageText(final int index) { - return "message #" + index; - } + private static String createMessageText(final int index) { + return "message #" + index; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/QueueWorkerPrefetchTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/QueueWorkerPrefetchTest.java index 80adaed328..74b52d51d0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/QueueWorkerPrefetchTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/QueueWorkerPrefetchTest.java @@ -34,6 +34,7 @@ import javax.jms.Queue; import javax.jms.Session; import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQPrefetchPolicy; import org.apache.activemq.broker.BrokerService; @@ -44,205 +45,219 @@ import org.slf4j.LoggerFactory; * Test case demonstrating situation where messages are not delivered to * consumers. */ -public class QueueWorkerPrefetchTest extends TestCase implements - MessageListener { - private static final Logger LOG = LoggerFactory - .getLogger(QueueWorkerPrefetchTest.class); - private static final int BATCH_SIZE = 10; - private static final long WAIT_TIMEOUT = 1000 * 10; +public class QueueWorkerPrefetchTest extends TestCase implements MessageListener { - /** The connection URL. */ - private static final String BROKER_BIND_ADDRESS = "tcp://localhost:0"; + private static final Logger LOG = LoggerFactory.getLogger(QueueWorkerPrefetchTest.class); + private static final int BATCH_SIZE = 10; + private static final long WAIT_TIMEOUT = 1000 * 10; - /** - * The queue prefetch size to use. A value greater than 1 seems to make - * things work. - */ - private static final int QUEUE_PREFETCH_SIZE = 1; + /** + * The connection URL. + */ + private static final String BROKER_BIND_ADDRESS = "tcp://localhost:0"; - /** - * The number of workers to use. A single worker with a prefetch of 1 works. - */ - private static final int NUM_WORKERS = 2; + /** + * The queue prefetch size to use. A value greater than 1 seems to make + * things work. + */ + private static final int QUEUE_PREFETCH_SIZE = 1; - /** Embedded JMS broker. */ - private BrokerService broker; + /** + * The number of workers to use. A single worker with a prefetch of 1 works. + */ + private static final int NUM_WORKERS = 2; - /** The master's producer object for creating work items. */ - private MessageProducer workItemProducer; + /** + * Embedded JMS broker. + */ + private BrokerService broker; - /** The master's consumer object for consuming ack messages from workers. */ - private MessageConsumer masterItemConsumer; + /** + * The master's producer object for creating work items. + */ + private MessageProducer workItemProducer; - /** The number of acks received by the master. */ - private final AtomicLong acksReceived = new AtomicLong(0); + /** + * The master's consumer object for consuming ack messages from workers. + */ + private MessageConsumer masterItemConsumer; - private final AtomicReference latch = new AtomicReference(); + /** + * The number of acks received by the master. + */ + private final AtomicLong acksReceived = new AtomicLong(0); - private String connectionUri; + private final AtomicReference latch = new AtomicReference(); - /** Messages sent to the work-item queue. */ - private static class WorkMessage implements Serializable { - private static final long serialVersionUID = 1L; - private final int id; + private String connectionUri; - public WorkMessage(int id) { - this.id = id; - } + /** + * Messages sent to the work-item queue. + */ + private static class WorkMessage implements Serializable { - @Override - public String toString() { - return "Work: " + id; - } - } + private static final long serialVersionUID = 1L; + private final int id; - /** - * The worker process. Consume messages from the work-item queue, possibly - * creating more messages to submit to the work-item queue. For each work - * item, send an ack to the master. - */ - private static class Worker implements MessageListener { - /** - * Counter shared between workers to decided when new work-item messages - * are created. - */ - private static AtomicInteger counter = new AtomicInteger(0); + public WorkMessage(int id) { + this.id = id; + } - /** Session to use. */ - private Session session; + @Override + public String toString() { + return "Work: " + id; + } + } - /** Producer for sending ack messages to the master. */ - private MessageProducer masterItemProducer; + /** + * The worker process. Consume messages from the work-item queue, possibly + * creating more messages to submit to the work-item queue. For each work + * item, send an ack to the master. + */ + private static class Worker implements MessageListener { - /** Producer for sending new work items to the work-items queue. */ - private MessageProducer workItemProducer; + /** + * Counter shared between workers to decided when new work-item messages + * are created. + */ + private static AtomicInteger counter = new AtomicInteger(0); - public Worker(Session session) throws JMSException { - this.session = session; - masterItemProducer = session.createProducer(session - .createQueue("master-item")); - Queue workItemQueue = session.createQueue("work-item"); - workItemProducer = session.createProducer(workItemQueue); - MessageConsumer workItemConsumer = session - .createConsumer(workItemQueue); - workItemConsumer.setMessageListener(this); - } + /** + * Session to use. + */ + private Session session; - public void onMessage(javax.jms.Message message) { - try { - WorkMessage work = (WorkMessage) ((ObjectMessage) message) - .getObject(); + /** + * Producer for sending ack messages to the master. + */ + private MessageProducer masterItemProducer; - long c = counter.incrementAndGet(); + /** + * Producer for sending new work items to the work-items queue. + */ + private MessageProducer workItemProducer; - // Don't create a new work item for every BATCH_SIZE message. */ - if (c % BATCH_SIZE != 0) { - // Send new work item to work-item queue. - workItemProducer.send(session - .createObjectMessage(new WorkMessage(work.id + 1))); - } + public Worker(Session session) throws JMSException { + this.session = session; + masterItemProducer = session.createProducer(session.createQueue("master-item")); + Queue workItemQueue = session.createQueue("work-item"); + workItemProducer = session.createProducer(workItemQueue); + MessageConsumer workItemConsumer = session.createConsumer(workItemQueue); + workItemConsumer.setMessageListener(this); + } - // Send ack to master. - masterItemProducer.send(session.createObjectMessage(work)); - } catch (JMSException e) { - throw new IllegalStateException("Something has gone wrong", e); + public void onMessage(javax.jms.Message message) { + try { + WorkMessage work = (WorkMessage) ((ObjectMessage) message).getObject(); + + long c = counter.incrementAndGet(); + + // Don't create a new work item for every BATCH_SIZE message. */ + if (c % BATCH_SIZE != 0) { + // Send new work item to work-item queue. + workItemProducer.send(session.createObjectMessage(new WorkMessage(work.id + 1))); } - } - /** Close of JMS resources used by worker. */ - public void close() throws JMSException { - masterItemProducer.close(); - workItemProducer.close(); - session.close(); - } - } + // Send ack to master. + masterItemProducer.send(session.createObjectMessage(work)); + } + catch (JMSException e) { + throw new IllegalStateException("Something has gone wrong", e); + } + } - /** Master message handler. Process ack messages. */ - public void onMessage(javax.jms.Message message) { - long acks = acksReceived.incrementAndGet(); - latch.get().countDown(); - if (acks % 1 == 0) { - LOG.info("Master now has ack count of: " + acksReceived); - } - } + /** + * Close of JMS resources used by worker. + */ + public void close() throws JMSException { + masterItemProducer.close(); + workItemProducer.close(); + session.close(); + } + } - protected void setUp() throws Exception { - // Create the message broker. - super.setUp(); - broker = new BrokerService(); - broker.setPersistent(false); - broker.setUseJmx(true); - broker.addConnector(BROKER_BIND_ADDRESS); - broker.start(); - broker.waitUntilStarted(); + /** + * Master message handler. Process ack messages. + */ + public void onMessage(javax.jms.Message message) { + long acks = acksReceived.incrementAndGet(); + latch.get().countDown(); + if (acks % 1 == 0) { + LOG.info("Master now has ack count of: " + acksReceived); + } + } - connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); - } + protected void setUp() throws Exception { + // Create the message broker. + super.setUp(); + broker = new BrokerService(); + broker.setPersistent(false); + broker.setUseJmx(true); + broker.addConnector(BROKER_BIND_ADDRESS); + broker.start(); + broker.waitUntilStarted(); - protected void tearDown() throws Exception { - // Shut down the message broker. - broker.deleteAllMessages(); - broker.stop(); - super.tearDown(); - } + connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); + } - public void testActiveMQ() throws Exception { - // Create the connection to the broker. - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionUri); - ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); - prefetchPolicy.setQueuePrefetch(QUEUE_PREFETCH_SIZE); - connectionFactory.setPrefetchPolicy(prefetchPolicy); - Connection connection = connectionFactory.createConnection(); - connection.start(); + protected void tearDown() throws Exception { + // Shut down the message broker. + broker.deleteAllMessages(); + broker.stop(); + super.tearDown(); + } - Session masterSession = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); - workItemProducer = masterSession.createProducer(masterSession - .createQueue("work-item")); - masterItemConsumer = masterSession.createConsumer(masterSession - .createQueue("master-item")); - masterItemConsumer.setMessageListener(this); + public void testActiveMQ() throws Exception { + // Create the connection to the broker. + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionUri); + ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); + prefetchPolicy.setQueuePrefetch(QUEUE_PREFETCH_SIZE); + connectionFactory.setPrefetchPolicy(prefetchPolicy); + Connection connection = connectionFactory.createConnection(); + connection.start(); - // Create the workers. - Worker[] workers = new Worker[NUM_WORKERS]; - for (int i = 0; i < NUM_WORKERS; i++) { - workers[i] = new Worker(connection.createSession(false, - Session.AUTO_ACKNOWLEDGE)); - } + Session masterSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + workItemProducer = masterSession.createProducer(masterSession.createQueue("work-item")); + masterItemConsumer = masterSession.createConsumer(masterSession.createQueue("master-item")); + masterItemConsumer.setMessageListener(this); - // Send a message to the work queue, and wait for the BATCH_SIZE acks - // from the workers. - acksReceived.set(0); - latch.set(new CountDownLatch(BATCH_SIZE)); - workItemProducer.send(masterSession - .createObjectMessage(new WorkMessage(1))); + // Create the workers. + Worker[] workers = new Worker[NUM_WORKERS]; + for (int i = 0; i < NUM_WORKERS; i++) { + workers[i] = new Worker(connection.createSession(false, Session.AUTO_ACKNOWLEDGE)); + } - if (!latch.get().await(WAIT_TIMEOUT, TimeUnit.MILLISECONDS)) { - fail("First batch only received " + acksReceived + " messages"); - } + // Send a message to the work queue, and wait for the BATCH_SIZE acks + // from the workers. + acksReceived.set(0); + latch.set(new CountDownLatch(BATCH_SIZE)); + workItemProducer.send(masterSession.createObjectMessage(new WorkMessage(1))); - LOG.info("First batch received"); + if (!latch.get().await(WAIT_TIMEOUT, TimeUnit.MILLISECONDS)) { + fail("First batch only received " + acksReceived + " messages"); + } - // Send another message to the work queue, and wait for the next 1000 acks. It is - // at this point where the workers never get notified of this message, as they - // have a large pending queue. Creating a new worker at this point however will - // receive this new message. - acksReceived.set(0); - latch.set(new CountDownLatch(BATCH_SIZE)); - workItemProducer.send(masterSession - .createObjectMessage(new WorkMessage(1))); + LOG.info("First batch received"); - if (!latch.get().await(WAIT_TIMEOUT, TimeUnit.MILLISECONDS)) { - fail("Second batch only received " + acksReceived + " messages"); - } + // Send another message to the work queue, and wait for the next 1000 acks. It is + // at this point where the workers never get notified of this message, as they + // have a large pending queue. Creating a new worker at this point however will + // receive this new message. + acksReceived.set(0); + latch.set(new CountDownLatch(BATCH_SIZE)); + workItemProducer.send(masterSession.createObjectMessage(new WorkMessage(1))); - LOG.info("Second batch received"); + if (!latch.get().await(WAIT_TIMEOUT, TimeUnit.MILLISECONDS)) { + fail("Second batch only received " + acksReceived + " messages"); + } - // Cleanup all JMS resources. - for (int i = 0; i < NUM_WORKERS; i++) { - workers[i].close(); - } - masterSession.close(); - connection.close(); - } + LOG.info("Second batch received"); + + // Cleanup all JMS resources. + for (int i = 0; i < NUM_WORKERS; i++) { + workers[i].close(); + } + masterSession.close(); + connection.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/RawRollbackSharedConsumerTests.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/RawRollbackSharedConsumerTests.java index 4790e42aaa..56f0f6e873 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/RawRollbackSharedConsumerTests.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/RawRollbackSharedConsumerTests.java @@ -41,94 +41,94 @@ import org.junit.BeforeClass; import org.junit.Test; public class RawRollbackSharedConsumerTests { - - private static ConnectionFactory connectionFactory; - private static Destination queue; - private static BrokerService broker; - @BeforeClass - public static void clean() throws Exception { - broker = new BrokerService(); - broker.setDeleteAllMessagesOnStartup(true); - broker.setUseJmx(true); - broker.start(); - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); - connectionFactory.setBrokerURL("vm://localhost?async=false"); - RawRollbackSharedConsumerTests.connectionFactory = connectionFactory; - queue = new ActiveMQQueue("queue"); - } + private static ConnectionFactory connectionFactory; + private static Destination queue; + private static BrokerService broker; - @AfterClass - public static void close() throws Exception { - broker.stop(); - } + @BeforeClass + public static void clean() throws Exception { + broker = new BrokerService(); + broker.setDeleteAllMessagesOnStartup(true); + broker.setUseJmx(true); + broker.start(); + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); + connectionFactory.setBrokerURL("vm://localhost?async=false"); + RawRollbackSharedConsumerTests.connectionFactory = connectionFactory; + queue = new ActiveMQQueue("queue"); + } - @Before - public void clearData() throws Exception { - getMessages(false); // drain queue - convertAndSend("foo"); - convertAndSend("bar"); - } + @AfterClass + public static void close() throws Exception { + broker.stop(); + } + @Before + public void clearData() throws Exception { + getMessages(false); // drain queue + convertAndSend("foo"); + convertAndSend("bar"); + } - @After - public void checkPostConditions() throws Exception { + @After + public void checkPostConditions() throws Exception { - Thread.sleep(1000L); - List list = getMessages(false); - assertEquals(2, list.size()); + Thread.sleep(1000L); + List list = getMessages(false); + assertEquals(2, list.size()); - } + } - @Test - public void testReceiveMessages() throws Exception { + @Test + public void testReceiveMessages() throws Exception { - List list = getMessages(true); - assertEquals(2, list.size()); - assertTrue(list.contains("foo")); + List list = getMessages(true); + assertEquals(2, list.size()); + assertTrue(list.contains("foo")); - } - - private void convertAndSend(String msg) throws Exception { - Connection connection = connectionFactory.createConnection(); - connection.start(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(queue); - producer.send(session.createTextMessage(msg)); - producer.close(); - session.commit(); - session.close(); - connection.close(); - } + } - private List getMessages(boolean rollback) throws Exception { - Connection connection = connectionFactory.createConnection(); - connection.start(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - String next = ""; - List msgs = new ArrayList(); - MessageConsumer consumer = session.createConsumer(queue); - while (next != null) { - next = (String) receiveAndConvert(consumer); - if (next != null) - msgs.add(next); - } - consumer.close(); - if (rollback) { - session.rollback(); - } else { - session.commit(); - } - session.close(); - connection.close(); - return msgs; - } + private void convertAndSend(String msg) throws Exception { + Connection connection = connectionFactory.createConnection(); + connection.start(); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(queue); + producer.send(session.createTextMessage(msg)); + producer.close(); + session.commit(); + session.close(); + connection.close(); + } - private String receiveAndConvert(MessageConsumer consumer) throws Exception { - Message message = consumer.receive(100L); - if (message==null) { - return null; - } - return ((TextMessage)message).getText(); - } + private List getMessages(boolean rollback) throws Exception { + Connection connection = connectionFactory.createConnection(); + connection.start(); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + String next = ""; + List msgs = new ArrayList(); + MessageConsumer consumer = session.createConsumer(queue); + while (next != null) { + next = (String) receiveAndConvert(consumer); + if (next != null) + msgs.add(next); + } + consumer.close(); + if (rollback) { + session.rollback(); + } + else { + session.commit(); + } + session.close(); + connection.close(); + return msgs; + } + + private String receiveAndConvert(MessageConsumer consumer) throws Exception { + Message message = consumer.receive(100L); + if (message == null) { + return null; + } + return ((TextMessage) message).getText(); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/RawRollbackTests.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/RawRollbackTests.java index 93abb28fa0..f3a48acadf 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/RawRollbackTests.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/RawRollbackTests.java @@ -42,94 +42,94 @@ import org.junit.BeforeClass; import org.junit.Test; public class RawRollbackTests { - - private static ConnectionFactory connectionFactory; - private static Destination queue; - private static BrokerService broker; - @BeforeClass - public static void clean() throws Exception { - broker = new BrokerService(); - broker.setDeleteAllMessagesOnStartup(true); - broker.setUseJmx(true); - broker.start(); - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); - connectionFactory.setBrokerURL("vm://localhost?async=false&waitForStart=5000&jms.prefetchPolicy.all=0"); - RawRollbackTests.connectionFactory = connectionFactory; - queue = new ActiveMQQueue("queue"); - } + private static ConnectionFactory connectionFactory; + private static Destination queue; + private static BrokerService broker; - @AfterClass - public static void close() throws Exception { - broker.stop(); - } + @BeforeClass + public static void clean() throws Exception { + broker = new BrokerService(); + broker.setDeleteAllMessagesOnStartup(true); + broker.setUseJmx(true); + broker.start(); + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); + connectionFactory.setBrokerURL("vm://localhost?async=false&waitForStart=5000&jms.prefetchPolicy.all=0"); + RawRollbackTests.connectionFactory = connectionFactory; + queue = new ActiveMQQueue("queue"); + } - @Before - public void clearData() throws Exception { - getMessages(false); // drain queue - convertAndSend("foo"); - convertAndSend("bar"); - } + @AfterClass + public static void close() throws Exception { + broker.stop(); + } + @Before + public void clearData() throws Exception { + getMessages(false); // drain queue + convertAndSend("foo"); + convertAndSend("bar"); + } - @After - public void checkPostConditions() throws Exception { + @After + public void checkPostConditions() throws Exception { - Thread.sleep(1000L); - List list = getMessages(false); - assertEquals(2, list.size()); + Thread.sleep(1000L); + List list = getMessages(false); + assertEquals(2, list.size()); - } + } - @Test - public void testReceiveMessages() throws Exception { + @Test + public void testReceiveMessages() throws Exception { - List list = getMessages(true); - assertEquals(2, list.size()); - assertTrue(list.contains("foo")); + List list = getMessages(true); + assertEquals(2, list.size()); + assertTrue(list.contains("foo")); - } - - private void convertAndSend(String msg) throws Exception { - Connection connection = connectionFactory.createConnection(); - connection.start(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(queue); - producer.send(session.createTextMessage(msg)); - producer.close(); - session.commit(); - session.close(); - connection.close(); - } + } - private List getMessages(boolean rollback) throws Exception { - Connection connection = connectionFactory.createConnection(); - connection.start(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - String next = ""; - List msgs = new ArrayList(); - while (next != null) { - next = (String) receiveAndConvert(session); - if (next != null) - msgs.add(next); - } - if (rollback) { - session.rollback(); - } else { - session.commit(); - } - session.close(); - connection.close(); - return msgs; - } + private void convertAndSend(String msg) throws Exception { + Connection connection = connectionFactory.createConnection(); + connection.start(); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(queue); + producer.send(session.createTextMessage(msg)); + producer.close(); + session.commit(); + session.close(); + connection.close(); + } - private String receiveAndConvert(Session session) throws Exception { - MessageConsumer consumer = session.createConsumer(queue); - Message message = consumer.receive(100L); - consumer.close(); - if (message==null) { - return null; - } - return ((TextMessage)message).getText(); - } + private List getMessages(boolean rollback) throws Exception { + Connection connection = connectionFactory.createConnection(); + connection.start(); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + String next = ""; + List msgs = new ArrayList(); + while (next != null) { + next = (String) receiveAndConvert(session); + if (next != null) + msgs.add(next); + } + if (rollback) { + session.rollback(); + } + else { + session.commit(); + } + session.close(); + connection.close(); + return msgs; + } + + private String receiveAndConvert(Session session) throws Exception { + MessageConsumer consumer = session.createConsumer(queue); + Message message = consumer.receive(100L); + consumer.close(); + if (message == null) { + return null; + } + return ((TextMessage) message).getText(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/Receiver.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/Receiver.java index 65f30e3337..e6d1d4050b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/Receiver.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/Receiver.java @@ -17,5 +17,6 @@ package org.apache.activemq.bugs; public interface Receiver { - void receive(String s) throws Exception; + + void receive(String s) throws Exception; } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/RedeliveryPluginHeaderTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/RedeliveryPluginHeaderTest.java index 414b70d7d8..62723afaf4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/RedeliveryPluginHeaderTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/RedeliveryPluginHeaderTest.java @@ -25,7 +25,9 @@ import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; + import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.RedeliveryPolicy; import org.apache.activemq.broker.BrokerPlugin; @@ -44,124 +46,121 @@ import org.slf4j.LoggerFactory; public class RedeliveryPluginHeaderTest extends TestCase { - private static final String TEST_QUEUE_ONE = "TEST_QUEUE_ONE"; - private static final String TEST_QUEUE_TWO = "TEST_QUEUE_TWO"; - private static final Logger LOG = LoggerFactory - .getLogger(RedeliveryPluginHeaderTest.class); - private String transportURL; - private BrokerService broker; + private static final String TEST_QUEUE_ONE = "TEST_QUEUE_ONE"; + private static final String TEST_QUEUE_TWO = "TEST_QUEUE_TWO"; + private static final Logger LOG = LoggerFactory.getLogger(RedeliveryPluginHeaderTest.class); + private String transportURL; + private BrokerService broker; - /** - * Test - * - consumes message from Queue1 - * - rolls back message to Queue1 and message is scheduled for redelivery to Queue1 by brokers plugin - * - consumes message from Queue1 again - * - sends same message to Queue2 - * - expects to consume message from Queue2 immediately - */ + /** + * Test + * - consumes message from Queue1 + * - rolls back message to Queue1 and message is scheduled for redelivery to Queue1 by brokers plugin + * - consumes message from Queue1 again + * - sends same message to Queue2 + * - expects to consume message from Queue2 immediately + */ - public void testSendAfterRedelivery() throws Exception { - broker = this.createBroker(false); - broker.start(); - broker.waitUntilStarted(); + public void testSendAfterRedelivery() throws Exception { + broker = this.createBroker(false); + broker.start(); + broker.waitUntilStarted(); - LOG.info("***Broker started..."); + LOG.info("***Broker started..."); - //pushed message to broker + //pushed message to broker - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory( - transportURL + "?trace=true&jms.redeliveryPolicy.maximumRedeliveries=0"); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(transportURL + "?trace=true&jms.redeliveryPolicy.maximumRedeliveries=0"); - Connection connection = factory.createConnection(); - connection.start(); + Connection connection = factory.createConnection(); + connection.start(); - try { + try { - Session session = connection.createSession(true, - Session.SESSION_TRANSACTED); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Destination destinationQ1 = session.createQueue(TEST_QUEUE_ONE); - Destination destinationQ2 = session.createQueue(TEST_QUEUE_TWO); + Destination destinationQ1 = session.createQueue(TEST_QUEUE_ONE); + Destination destinationQ2 = session.createQueue(TEST_QUEUE_TWO); - MessageProducer producerQ1 = session.createProducer(destinationQ1); - producerQ1.setDeliveryMode(DeliveryMode.PERSISTENT); + MessageProducer producerQ1 = session.createProducer(destinationQ1); + producerQ1.setDeliveryMode(DeliveryMode.PERSISTENT); - Message m = session.createTextMessage("testMessage"); - LOG.info("*** send message to broker..."); - producerQ1.send(m); - session.commit(); + Message m = session.createTextMessage("testMessage"); + LOG.info("*** send message to broker..."); + producerQ1.send(m); + session.commit(); - //consume message from Q1 and rollback to get it redelivered - MessageConsumer consumerQ1 = session.createConsumer(destinationQ1); + //consume message from Q1 and rollback to get it redelivered + MessageConsumer consumerQ1 = session.createConsumer(destinationQ1); - LOG.info("*** consume message from Q1 and rolled back.."); + LOG.info("*** consume message from Q1 and rolled back.."); - TextMessage textMessage = (TextMessage) consumerQ1.receive(); - LOG.info("got redelivered: " + textMessage); - assertFalse("JMSRedelivered flag is not set", textMessage.getJMSRedelivered()); - session.rollback(); + TextMessage textMessage = (TextMessage) consumerQ1.receive(); + LOG.info("got redelivered: " + textMessage); + assertFalse("JMSRedelivered flag is not set", textMessage.getJMSRedelivered()); + session.rollback(); - LOG.info("*** consumed message from Q1 again and sending to Q2.."); - TextMessage textMessage2 = (TextMessage) consumerQ1.receive(); - LOG.info("got: " + textMessage2); - session.commit(); - assertTrue("JMSRedelivered flag is set", textMessage2.getJMSRedelivered()); + LOG.info("*** consumed message from Q1 again and sending to Q2.."); + TextMessage textMessage2 = (TextMessage) consumerQ1.receive(); + LOG.info("got: " + textMessage2); + session.commit(); + assertTrue("JMSRedelivered flag is set", textMessage2.getJMSRedelivered()); - //send message to Q2 and consume from Q2 - MessageConsumer consumerQ2 = session.createConsumer(destinationQ2); - MessageProducer producer_two = session.createProducer(destinationQ2); - producer_two.send(textMessage2); - session.commit(); + //send message to Q2 and consume from Q2 + MessageConsumer consumerQ2 = session.createConsumer(destinationQ2); + MessageProducer producer_two = session.createProducer(destinationQ2); + producer_two.send(textMessage2); + session.commit(); - //Message should be available straight away on the queue_two - Message textMessage3 = consumerQ2.receive(1000); - assertNotNull("should have consumed a message from TEST_QUEUE_TWO", textMessage3); - assertFalse("JMSRedelivered flag is not set", textMessage3.getJMSRedelivered()); - session.commit(); + //Message should be available straight away on the queue_two + Message textMessage3 = consumerQ2.receive(1000); + assertNotNull("should have consumed a message from TEST_QUEUE_TWO", textMessage3); + assertFalse("JMSRedelivered flag is not set", textMessage3.getJMSRedelivered()); + session.commit(); - } finally { + } + finally { - if (connection != null) { - connection.close(); - } + if (connection != null) { + connection.close(); + } - if (broker != null) { - broker.stop(); - } + if (broker != null) { + broker.stop(); + } - } + } - } + } - protected BrokerService createBroker(boolean withJMX) throws Exception { - File schedulerDirectory = new File("target/scheduler"); - IOHelper.mkdirs(schedulerDirectory); - IOHelper.deleteChildren(schedulerDirectory); + protected BrokerService createBroker(boolean withJMX) throws Exception { + File schedulerDirectory = new File("target/scheduler"); + IOHelper.mkdirs(schedulerDirectory); + IOHelper.deleteChildren(schedulerDirectory); - BrokerService answer = new BrokerService(); - answer.setAdvisorySupport(false); - answer.setDataDirectory("target"); - answer.setSchedulerDirectoryFile(schedulerDirectory); - answer.setSchedulerSupport(true); - answer.setPersistent(true); - answer.setDeleteAllMessagesOnStartup(true); - answer.setUseJmx(withJMX); + BrokerService answer = new BrokerService(); + answer.setAdvisorySupport(false); + answer.setDataDirectory("target"); + answer.setSchedulerDirectoryFile(schedulerDirectory); + answer.setSchedulerSupport(true); + answer.setPersistent(true); + answer.setDeleteAllMessagesOnStartup(true); + answer.setUseJmx(withJMX); - RedeliveryPlugin redeliveryPlugin = new RedeliveryPlugin(); - RedeliveryPolicyMap redeliveryPolicyMap = new RedeliveryPolicyMap(); - RedeliveryPolicy defaultEntry = new RedeliveryPolicy(); - defaultEntry.setInitialRedeliveryDelay(5000); - defaultEntry.setMaximumRedeliveries(5); - redeliveryPolicyMap.setDefaultEntry(defaultEntry); - redeliveryPlugin.setRedeliveryPolicyMap(redeliveryPolicyMap); + RedeliveryPlugin redeliveryPlugin = new RedeliveryPlugin(); + RedeliveryPolicyMap redeliveryPolicyMap = new RedeliveryPolicyMap(); + RedeliveryPolicy defaultEntry = new RedeliveryPolicy(); + defaultEntry.setInitialRedeliveryDelay(5000); + defaultEntry.setMaximumRedeliveries(5); + redeliveryPolicyMap.setDefaultEntry(defaultEntry); + redeliveryPlugin.setRedeliveryPolicyMap(redeliveryPolicyMap); - answer.setPlugins(new BrokerPlugin[] {redeliveryPlugin}); - TransportConnector transportConnector = - answer.addConnector("tcp://localhost:0"); + answer.setPlugins(new BrokerPlugin[]{redeliveryPlugin}); + TransportConnector transportConnector = answer.addConnector("tcp://localhost:0"); - transportURL = transportConnector.getConnectUri().toASCIIString(); + transportURL = transportConnector.getConnectUri().toASCIIString(); - return answer; - } + return answer; + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/SlowConsumerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/SlowConsumerTest.java index a2c117e23c..c3c2bac2fa 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/SlowConsumerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/SlowConsumerTest.java @@ -30,6 +30,7 @@ import javax.jms.Session; import javax.jms.TextMessage; import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.command.ActiveMQQueue; @@ -38,122 +39,125 @@ import org.slf4j.LoggerFactory; public class SlowConsumerTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(SlowConsumerTest.class); - private static final int MESSAGES_COUNT = 10000; + private static final Logger LOG = LoggerFactory.getLogger(SlowConsumerTest.class); + private static final int MESSAGES_COUNT = 10000; - private final int messageLogFrequency = 2500; - private final long messageReceiveTimeout = 10000L; + private final int messageLogFrequency = 2500; + private final long messageReceiveTimeout = 10000L; - private Socket stompSocket; - private ByteArrayOutputStream inputBuffer; - private int messagesCount; + private Socket stompSocket; + private ByteArrayOutputStream inputBuffer; + private int messagesCount; - /** - * @param args - * @throws Exception - */ - public void testRemoveSubscriber() throws Exception { - final BrokerService broker = new BrokerService(); - broker.setPersistent(true); - broker.setUseJmx(true); - broker.setDeleteAllMessagesOnStartup(true); + /** + * @param args + * @throws Exception + */ + public void testRemoveSubscriber() throws Exception { + final BrokerService broker = new BrokerService(); + broker.setPersistent(true); + broker.setUseJmx(true); + broker.setDeleteAllMessagesOnStartup(true); - broker.addConnector("tcp://localhost:0").setName("Default"); - broker.start(); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory( - broker.getTransportConnectors().get(0).getPublishableConnectString()); - final Connection connection = factory.createConnection(); - connection.start(); + broker.addConnector("tcp://localhost:0").setName("Default"); + broker.start(); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString()); + final Connection connection = factory.createConnection(); + connection.start(); - Thread producingThread = new Thread("Producing thread") { - public void run() { - try { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(new ActiveMQQueue(getDestinationName())); - for (int idx = 0; idx < MESSAGES_COUNT; ++idx) { - Message message = session.createTextMessage("" + idx); - producer.send(message); - LOG.debug("Sending: " + idx); - } - producer.close(); - session.close(); - } catch (Throwable ex) { - ex.printStackTrace(); - } + Thread producingThread = new Thread("Producing thread") { + public void run() { + try { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(new ActiveMQQueue(getDestinationName())); + for (int idx = 0; idx < MESSAGES_COUNT; ++idx) { + Message message = session.createTextMessage("" + idx); + producer.send(message); + LOG.debug("Sending: " + idx); + } + producer.close(); + session.close(); } - }; - producingThread.setPriority(Thread.MAX_PRIORITY); - producingThread.start(); - Thread.sleep(1000); - - Thread consumingThread = new Thread("Consuming thread") { - - public void run() { - try { - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(new ActiveMQQueue(getDestinationName())); - int diff = 0; - while (messagesCount != MESSAGES_COUNT) { - Message msg = consumer.receive(messageReceiveTimeout); - if (msg == null) { - LOG.warn("Got null message at count: " + messagesCount + ". Continuing..."); - break; - } - String text = ((TextMessage)msg).getText(); - int currentMsgIdx = Integer.parseInt(text); - LOG.debug("Received: " + text + " messageCount: " + messagesCount); - msg.acknowledge(); - if ((messagesCount + diff) != currentMsgIdx) { - LOG.debug("Message(s) skipped!! Should be message no.: " + messagesCount + " but got: " + currentMsgIdx); - diff = currentMsgIdx - messagesCount; - } - ++messagesCount; - if (messagesCount % messageLogFrequency == 0) { - LOG.info("Received: " + messagesCount + " messages so far"); - } - // Thread.sleep(70); - } - } catch (Throwable ex) { - ex.printStackTrace(); - } + catch (Throwable ex) { + ex.printStackTrace(); } - }; - consumingThread.start(); - consumingThread.join(); + } + }; + producingThread.setPriority(Thread.MAX_PRIORITY); + producingThread.start(); + Thread.sleep(1000); - assertEquals(MESSAGES_COUNT, messagesCount); + Thread consumingThread = new Thread("Consuming thread") { - } + public void run() { + try { + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(new ActiveMQQueue(getDestinationName())); + int diff = 0; + while (messagesCount != MESSAGES_COUNT) { + Message msg = consumer.receive(messageReceiveTimeout); + if (msg == null) { + LOG.warn("Got null message at count: " + messagesCount + ". Continuing..."); + break; + } + String text = ((TextMessage) msg).getText(); + int currentMsgIdx = Integer.parseInt(text); + LOG.debug("Received: " + text + " messageCount: " + messagesCount); + msg.acknowledge(); + if ((messagesCount + diff) != currentMsgIdx) { + LOG.debug("Message(s) skipped!! Should be message no.: " + messagesCount + " but got: " + currentMsgIdx); + diff = currentMsgIdx - messagesCount; + } + ++messagesCount; + if (messagesCount % messageLogFrequency == 0) { + LOG.info("Received: " + messagesCount + " messages so far"); + } + // Thread.sleep(70); + } + } + catch (Throwable ex) { + ex.printStackTrace(); + } + } + }; + consumingThread.start(); + consumingThread.join(); - public void sendFrame(String data) throws Exception { - byte[] bytes = data.getBytes("UTF-8"); - OutputStream outputStream = stompSocket.getOutputStream(); - for (int i = 0; i < bytes.length; i++) { - outputStream.write(bytes[i]); - } - outputStream.flush(); - } + assertEquals(MESSAGES_COUNT, messagesCount); - public String receiveFrame(long timeOut) throws Exception { - stompSocket.setSoTimeout((int)timeOut); - InputStream is = stompSocket.getInputStream(); - int c = 0; - for (;;) { + } + + public void sendFrame(String data) throws Exception { + byte[] bytes = data.getBytes("UTF-8"); + OutputStream outputStream = stompSocket.getOutputStream(); + for (int i = 0; i < bytes.length; i++) { + outputStream.write(bytes[i]); + } + outputStream.flush(); + } + + public String receiveFrame(long timeOut) throws Exception { + stompSocket.setSoTimeout((int) timeOut); + InputStream is = stompSocket.getInputStream(); + int c = 0; + for (;;) { + c = is.read(); + if (c < 0) { + throw new IOException("socket closed."); + } + else if (c == 0) { c = is.read(); - if (c < 0) { - throw new IOException("socket closed."); - } else if (c == 0) { - c = is.read(); - byte[] ba = inputBuffer.toByteArray(); - inputBuffer.reset(); - return new String(ba, "UTF-8"); - } else { - inputBuffer.write(c); - } - } - } + byte[] ba = inputBuffer.toByteArray(); + inputBuffer.reset(); + return new String(ba, "UTF-8"); + } + else { + inputBuffer.write(c); + } + } + } - protected String getDestinationName() { - return getClass().getName() + "." + getName(); - } + protected String getDestinationName() { + return getClass().getName() + "." + getName(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/SparseAckReplayAfterStoreCleanupLevelDBStoreTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/SparseAckReplayAfterStoreCleanupLevelDBStoreTest.java index ba15941a47..3e22dc2bf6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/SparseAckReplayAfterStoreCleanupLevelDBStoreTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/SparseAckReplayAfterStoreCleanupLevelDBStoreTest.java @@ -19,12 +19,12 @@ package org.apache.activemq.bugs; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.leveldb.LevelDBStore; - public class SparseAckReplayAfterStoreCleanupLevelDBStoreTest extends AMQ2832Test { - @Override - protected void configurePersistence(BrokerService brokerService, boolean deleteAllOnStart) throws Exception { - LevelDBStore store = new LevelDBStore(); - store.setFlushDelay(0); - brokerService.setPersistenceAdapter(store); - } + + @Override + protected void configurePersistence(BrokerService brokerService, boolean deleteAllOnStart) throws Exception { + LevelDBStore store = new LevelDBStore(); + store.setFlushDelay(0); + brokerService.setPersistenceAdapter(store); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TempQueueDeleteOnCloseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TempQueueDeleteOnCloseTest.java index 44e7f5d8ab..f521d40fe0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TempQueueDeleteOnCloseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TempQueueDeleteOnCloseTest.java @@ -30,25 +30,25 @@ import org.junit.Test; */ public class TempQueueDeleteOnCloseTest { - @Test - public void test() throws Exception { - ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost"); + @Test + public void test() throws Exception { + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost"); - // create a connection and session with a temporary queue - Connection connectionA = connectionFactory.createConnection(); - connectionA.setClientID("ConnectionA"); - Session sessionA = connectionA.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination tempQueueA = sessionA.createTemporaryQueue(); - MessageConsumer consumer = sessionA.createConsumer(tempQueueA); - connectionA.start(); + // create a connection and session with a temporary queue + Connection connectionA = connectionFactory.createConnection(); + connectionA.setClientID("ConnectionA"); + Session sessionA = connectionA.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination tempQueueA = sessionA.createTemporaryQueue(); + MessageConsumer consumer = sessionA.createConsumer(tempQueueA); + connectionA.start(); - // start and stop another connection - Connection connectionB = connectionFactory.createConnection(); - connectionB.setClientID("ConnectionB"); - connectionB.start(); - connectionB.close(); + // start and stop another connection + Connection connectionB = connectionFactory.createConnection(); + connectionB.setClientID("ConnectionB"); + connectionB.start(); + connectionB.close(); - consumer.close(); - connectionA.close(); - } + consumer.close(); + connectionA.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TempStorageBlockedBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TempStorageBlockedBrokerTest.java index b78cd77746..dc15f87218 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TempStorageBlockedBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TempStorageBlockedBrokerTest.java @@ -28,6 +28,7 @@ import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.ResourceAllocationException; import javax.jms.Session; + import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQPrefetchPolicy; @@ -47,220 +48,219 @@ import org.slf4j.LoggerFactory; public class TempStorageBlockedBrokerTest extends TestSupport { - public int deliveryMode = DeliveryMode.PERSISTENT; + public int deliveryMode = DeliveryMode.PERSISTENT; - private static final Logger LOG = LoggerFactory.getLogger(TempStorageBlockedBrokerTest.class); - private static final int MESSAGES_COUNT = 1000; - private static byte[] buf = new byte[4 * 1024]; - private BrokerService broker; - AtomicInteger messagesSent = new AtomicInteger(0); - AtomicInteger messagesConsumed = new AtomicInteger(0); + private static final Logger LOG = LoggerFactory.getLogger(TempStorageBlockedBrokerTest.class); + private static final int MESSAGES_COUNT = 1000; + private static byte[] buf = new byte[4 * 1024]; + private BrokerService broker; + AtomicInteger messagesSent = new AtomicInteger(0); + AtomicInteger messagesConsumed = new AtomicInteger(0); - protected long messageReceiveTimeout = 10000L; + protected long messageReceiveTimeout = 10000L; - Destination destination = new ActiveMQTopic("FooTwo"); + Destination destination = new ActiveMQTopic("FooTwo"); - private String connectionUri; + private String connectionUri; - public void testRunProducerWithHungConsumer() throws Exception { + public void testRunProducerWithHungConsumer() throws Exception { - final long origTempUsage = broker.getSystemUsage().getTempUsage().getUsage(); + final long origTempUsage = broker.getSystemUsage().getTempUsage().getUsage(); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - // ensure messages are spooled to disk for this consumer - ActiveMQPrefetchPolicy prefetch = new ActiveMQPrefetchPolicy(); - prefetch.setTopicPrefetch(10); - factory.setPrefetchPolicy(prefetch); - Connection consumerConnection = factory.createConnection(); - consumerConnection.start(); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); + // ensure messages are spooled to disk for this consumer + ActiveMQPrefetchPolicy prefetch = new ActiveMQPrefetchPolicy(); + prefetch.setTopicPrefetch(10); + factory.setPrefetchPolicy(prefetch); + Connection consumerConnection = factory.createConnection(); + consumerConnection.start(); - Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = consumerSession.createConsumer(destination); + Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = consumerSession.createConsumer(destination); - final Connection producerConnection = factory.createConnection(); - producerConnection.start(); + final Connection producerConnection = factory.createConnection(); + producerConnection.start(); - final CountDownLatch producerHasSentTenMessages = new CountDownLatch(10); - Thread producingThread = new Thread("Producing thread") { - @Override - public void run() { - try { - Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(deliveryMode); - for (int idx = 0; idx < MESSAGES_COUNT; ++idx) { - Message message = session.createTextMessage(new String(buf) + idx); - - producer.send(message); - messagesSent.incrementAndGet(); - producerHasSentTenMessages.countDown(); - Thread.sleep(10); - if (idx != 0 && idx%100 == 0) { - LOG.info("Sent Message " + idx); - LOG.info("Temp Store Usage " + broker.getSystemUsage().getTempUsage().getUsage()); - } - } - producer.close(); - session.close(); - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - }; - producingThread.start(); - - assertTrue("producer has sent 10 in a reasonable time", producerHasSentTenMessages.await(30, TimeUnit.SECONDS)); - - int count = 0; - - Message m = null; - while ((m = consumer.receive(messageReceiveTimeout)) != null) { - count++; - if (count != 0 && count%10 == 0) { - LOG.info("Received Message (" + count + "):" + m); - } - messagesConsumed.incrementAndGet(); + final CountDownLatch producerHasSentTenMessages = new CountDownLatch(10); + Thread producingThread = new Thread("Producing thread") { + @Override + public void run() { try { - Thread.sleep(100); - } catch (Exception e) { - LOG.info("error sleeping"); + Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(deliveryMode); + for (int idx = 0; idx < MESSAGES_COUNT; ++idx) { + Message message = session.createTextMessage(new String(buf) + idx); + + producer.send(message); + messagesSent.incrementAndGet(); + producerHasSentTenMessages.countDown(); + Thread.sleep(10); + if (idx != 0 && idx % 100 == 0) { + LOG.info("Sent Message " + idx); + LOG.info("Temp Store Usage " + broker.getSystemUsage().getTempUsage().getUsage()); + } + } + producer.close(); + session.close(); } - } - - LOG.info("Connection Timeout: Retrying.. count: " + count); - - while ((m = consumer.receive(messageReceiveTimeout)) != null) { - count++; - if (count != 0 && count%100 == 0) { - LOG.info("Received Message (" + count + "):" + m); + catch (Throwable ex) { + ex.printStackTrace(); } - messagesConsumed.incrementAndGet(); - try { - Thread.sleep(100); - } catch (Exception e) { - LOG.info("error sleeping"); + } + }; + producingThread.start(); + + assertTrue("producer has sent 10 in a reasonable time", producerHasSentTenMessages.await(30, TimeUnit.SECONDS)); + + int count = 0; + + Message m = null; + while ((m = consumer.receive(messageReceiveTimeout)) != null) { + count++; + if (count != 0 && count % 10 == 0) { + LOG.info("Received Message (" + count + "):" + m); + } + messagesConsumed.incrementAndGet(); + try { + Thread.sleep(100); + } + catch (Exception e) { + LOG.info("error sleeping"); + } + } + + LOG.info("Connection Timeout: Retrying.. count: " + count); + + while ((m = consumer.receive(messageReceiveTimeout)) != null) { + count++; + if (count != 0 && count % 100 == 0) { + LOG.info("Received Message (" + count + "):" + m); + } + messagesConsumed.incrementAndGet(); + try { + Thread.sleep(100); + } + catch (Exception e) { + LOG.info("error sleeping"); + } + } + + LOG.info("consumer session closing: consumed count: " + count); + + consumerSession.close(); + + producingThread.join(); + + final long tempUsageBySubscription = broker.getSystemUsage().getTempUsage().getUsage(); + LOG.info("Orig Usage: " + origTempUsage + ", currentUsage: " + tempUsageBySubscription); + + producerConnection.close(); + consumerConnection.close(); + + LOG.info("Subscrition Usage: " + tempUsageBySubscription + ", endUsage: " + broker.getSystemUsage().getTempUsage().getUsage()); + + // do a cleanup + ((PListStoreImpl) broker.getTempDataStore()).run(); + LOG.info("Subscrition Usage: " + tempUsageBySubscription + ", endUsage: " + broker.getSystemUsage().getTempUsage().getUsage()); + + assertEquals("Incorrect number of Messages Sent: " + messagesSent.get(), messagesSent.get(), MESSAGES_COUNT); + assertEquals("Incorrect number of Messages Consumed: " + messagesConsumed.get(), messagesConsumed.get(), MESSAGES_COUNT); + } + + public void testFillTempAndConsume() throws Exception { + + broker.getSystemUsage().setSendFailIfNoSpace(true); + destination = new ActiveMQQueue("Foo"); + + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); + final ActiveMQConnection producerConnection = (ActiveMQConnection) factory.createConnection(); + // so we can easily catch the ResourceAllocationException on send + producerConnection.setAlwaysSyncSend(true); + producerConnection.start(); + + Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + + try { + while (true) { + Message message = session.createTextMessage(new String(buf) + messagesSent.toString()); + producer.send(message); + messagesSent.incrementAndGet(); + if (messagesSent.get() % 100 == 0) { + LOG.info("Sent Message " + messagesSent.get()); + LOG.info("Temp Store Usage " + broker.getSystemUsage().getTempUsage().getUsage()); } - } + } + } + catch (ResourceAllocationException ex) { + LOG.info("Got resource exception : " + ex + ", after sent: " + messagesSent.get()); + } - LOG.info("consumer session closing: consumed count: " + count); + // consume all sent + Connection consumerConnection = factory.createConnection(); + consumerConnection.start(); - consumerSession.close(); + Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = consumerSession.createConsumer(destination); - producingThread.join(); + while (consumer.receive(messageReceiveTimeout) != null) { + messagesConsumed.incrementAndGet(); + if (messagesConsumed.get() % 1000 == 0) { + LOG.info("received Message " + messagesConsumed.get()); + LOG.info("Temp Store Usage " + broker.getSystemUsage().getTempUsage().getUsage()); + } + } - final long tempUsageBySubscription = broker.getSystemUsage().getTempUsage().getUsage(); - LOG.info("Orig Usage: " + origTempUsage + ", currentUsage: " + tempUsageBySubscription); + assertEquals("Incorrect number of Messages Consumed: " + messagesConsumed.get(), messagesConsumed.get(), messagesSent.get()); + } - producerConnection.close(); - consumerConnection.close(); + @Override + public void setUp() throws Exception { - LOG.info("Subscrition Usage: " + tempUsageBySubscription + ", endUsage: " - + broker.getSystemUsage().getTempUsage().getUsage()); + broker = new BrokerService(); + broker.setDataDirectory("target" + File.separator + "activemq-data"); + broker.setPersistent(true); + broker.setUseJmx(true); + broker.setAdvisorySupport(false); + broker.setDeleteAllMessagesOnStartup(true); - // do a cleanup - ((PListStoreImpl)broker.getTempDataStore()).run(); - LOG.info("Subscrition Usage: " + tempUsageBySubscription + ", endUsage: " - + broker.getSystemUsage().getTempUsage().getUsage()); + setDefaultPersistenceAdapter(broker); + SystemUsage sysUsage = broker.getSystemUsage(); + MemoryUsage memUsage = new MemoryUsage(); + memUsage.setLimit((1024 * 1024)); + StoreUsage storeUsage = new StoreUsage(); + storeUsage.setLimit((1024 * 1024) * 38); + TempUsage tmpUsage = new TempUsage(); + tmpUsage.setLimit((1024 * 1024) * 38); - assertEquals("Incorrect number of Messages Sent: " + messagesSent.get(), messagesSent.get(), MESSAGES_COUNT); - assertEquals("Incorrect number of Messages Consumed: " + messagesConsumed.get(), messagesConsumed.get(), - MESSAGES_COUNT); - } + PolicyEntry defaultPolicy = new PolicyEntry(); + // defaultPolicy.setTopic("FooTwo"); + defaultPolicy.setProducerFlowControl(false); + defaultPolicy.setMemoryLimit(10 * 1024); - public void testFillTempAndConsume() throws Exception { + PolicyMap policyMap = new PolicyMap(); + policyMap.setDefaultEntry(defaultPolicy); - broker.getSystemUsage().setSendFailIfNoSpace(true); - destination = new ActiveMQQueue("Foo"); + sysUsage.setMemoryUsage(memUsage); + sysUsage.setStoreUsage(storeUsage); + sysUsage.setTempUsage(tmpUsage); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - final ActiveMQConnection producerConnection = (ActiveMQConnection) factory.createConnection(); - // so we can easily catch the ResourceAllocationException on send - producerConnection.setAlwaysSyncSend(true); - producerConnection.start(); + broker.setDestinationPolicy(policyMap); + broker.setSystemUsage(sysUsage); - Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + broker.addConnector("tcp://localhost:0").setName("Default"); + broker.start(); - try { - while (true) { - Message message = session.createTextMessage(new String(buf) + messagesSent.toString()); - producer.send(message); - messagesSent.incrementAndGet(); - if (messagesSent.get() % 100 == 0) { - LOG.info("Sent Message " + messagesSent.get()); - LOG.info("Temp Store Usage " + broker.getSystemUsage().getTempUsage().getUsage()); - } - } - } catch (ResourceAllocationException ex) { - LOG.info("Got resource exception : " + ex + ", after sent: " + messagesSent.get()); - } + connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); + } - // consume all sent - Connection consumerConnection = factory.createConnection(); - consumerConnection.start(); - - Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = consumerSession.createConsumer(destination); - - - while (consumer.receive(messageReceiveTimeout) != null) { - messagesConsumed.incrementAndGet(); - if (messagesConsumed.get() % 1000 == 0) { - LOG.info("received Message " + messagesConsumed.get()); - LOG.info("Temp Store Usage " + broker.getSystemUsage().getTempUsage().getUsage()); - } - } - - assertEquals("Incorrect number of Messages Consumed: " + messagesConsumed.get(), messagesConsumed.get(), - messagesSent.get()); - } - - @Override - public void setUp() throws Exception { - - broker = new BrokerService(); - broker.setDataDirectory("target" + File.separator + "activemq-data"); - broker.setPersistent(true); - broker.setUseJmx(true); - broker.setAdvisorySupport(false); - broker.setDeleteAllMessagesOnStartup(true); - - setDefaultPersistenceAdapter(broker); - SystemUsage sysUsage = broker.getSystemUsage(); - MemoryUsage memUsage = new MemoryUsage(); - memUsage.setLimit((1024 * 1024)); - StoreUsage storeUsage = new StoreUsage(); - storeUsage.setLimit((1024 * 1024) * 38); - TempUsage tmpUsage = new TempUsage(); - tmpUsage.setLimit((1024 * 1024) * 38); - - PolicyEntry defaultPolicy = new PolicyEntry(); - // defaultPolicy.setTopic("FooTwo"); - defaultPolicy.setProducerFlowControl(false); - defaultPolicy.setMemoryLimit(10 * 1024); - - PolicyMap policyMap = new PolicyMap(); - policyMap.setDefaultEntry(defaultPolicy); - - sysUsage.setMemoryUsage(memUsage); - sysUsage.setStoreUsage(storeUsage); - sysUsage.setTempUsage(tmpUsage); - - broker.setDestinationPolicy(policyMap); - broker.setSystemUsage(sysUsage); - - broker.addConnector("tcp://localhost:0").setName("Default"); - broker.start(); - - connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); - } - - @Override - public void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - } - } + @Override + public void tearDown() throws Exception { + if (broker != null) { + broker.stop(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TempStorageConfigBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TempStorageConfigBrokerTest.java index 1061346c1a..d04cc3f3bd 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TempStorageConfigBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TempStorageConfigBrokerTest.java @@ -52,169 +52,169 @@ import org.slf4j.LoggerFactory; */ public class TempStorageConfigBrokerTest { - public int deliveryMode = DeliveryMode.PERSISTENT; + public int deliveryMode = DeliveryMode.PERSISTENT; - private static final Logger LOG = LoggerFactory.getLogger(TempStorageConfigBrokerTest.class); - private static byte[] buf = new byte[4 * 1024]; - private BrokerService broker; - private AtomicInteger messagesSent = new AtomicInteger(0); - private AtomicInteger messagesConsumed = new AtomicInteger(0); + private static final Logger LOG = LoggerFactory.getLogger(TempStorageConfigBrokerTest.class); + private static byte[] buf = new byte[4 * 1024]; + private BrokerService broker; + private AtomicInteger messagesSent = new AtomicInteger(0); + private AtomicInteger messagesConsumed = new AtomicInteger(0); - private String brokerUri; - private long messageReceiveTimeout = 10000L; - private Destination destination = new ActiveMQTopic("FooTwo"); + private String brokerUri; + private long messageReceiveTimeout = 10000L; + private Destination destination = new ActiveMQTopic("FooTwo"); - @Test(timeout=360000) - @Ignore("blocks in hudson, needs investigation") - public void testFillTempAndConsumeWithBadTempStoreConfig() throws Exception { + @Test(timeout = 360000) + @Ignore("blocks in hudson, needs investigation") + public void testFillTempAndConsumeWithBadTempStoreConfig() throws Exception { - createBrokerWithInvalidTempStoreConfig(); + createBrokerWithInvalidTempStoreConfig(); - broker.getSystemUsage().setSendFailIfNoSpace(true); - destination = new ActiveMQQueue("Foo"); + broker.getSystemUsage().setSendFailIfNoSpace(true); + destination = new ActiveMQQueue("Foo"); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerUri); - final ActiveMQConnection producerConnection = (ActiveMQConnection) factory.createConnection(); - // so we can easily catch the ResourceAllocationException on send - producerConnection.setAlwaysSyncSend(true); - producerConnection.start(); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerUri); + final ActiveMQConnection producerConnection = (ActiveMQConnection) factory.createConnection(); + // so we can easily catch the ResourceAllocationException on send + producerConnection.setAlwaysSyncSend(true); + producerConnection.start(); - Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - try { - while (true) { - Message message = session.createTextMessage(new String(buf) + messagesSent.toString()); - producer.send(message); - messagesSent.incrementAndGet(); - if (messagesSent.get() % 100 == 0) { - LOG.info("Sent Message " + messagesSent.get()); - LOG.info("Temp Store Usage " + broker.getSystemUsage().getTempUsage().getUsage()); - } + try { + while (true) { + Message message = session.createTextMessage(new String(buf) + messagesSent.toString()); + producer.send(message); + messagesSent.incrementAndGet(); + if (messagesSent.get() % 100 == 0) { + LOG.info("Sent Message " + messagesSent.get()); + LOG.info("Temp Store Usage " + broker.getSystemUsage().getTempUsage().getUsage()); } - } catch (ResourceAllocationException ex) { - assertTrue("Should not be able to send 100 messages: ", messagesSent.get() < 100); - LOG.info("Got resource exception : " + ex + ", after sent: " + messagesSent.get()); - } - } + } + } + catch (ResourceAllocationException ex) { + assertTrue("Should not be able to send 100 messages: ", messagesSent.get() < 100); + LOG.info("Got resource exception : " + ex + ", after sent: " + messagesSent.get()); + } + } - @Test(timeout=360000) - @Ignore("blocks in hudson, needs investigation") - public void testFillTempAndConsumeWithGoodTempStoreConfig() throws Exception { + @Test(timeout = 360000) + @Ignore("blocks in hudson, needs investigation") + public void testFillTempAndConsumeWithGoodTempStoreConfig() throws Exception { - createBrokerWithValidTempStoreConfig(); + createBrokerWithValidTempStoreConfig(); - broker.getSystemUsage().setSendFailIfNoSpace(true); - destination = new ActiveMQQueue("Foo"); + broker.getSystemUsage().setSendFailIfNoSpace(true); + destination = new ActiveMQQueue("Foo"); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerUri); - final ActiveMQConnection producerConnection = (ActiveMQConnection) factory.createConnection(); - // so we can easily catch the ResourceAllocationException on send - producerConnection.setAlwaysSyncSend(true); - producerConnection.start(); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerUri); + final ActiveMQConnection producerConnection = (ActiveMQConnection) factory.createConnection(); + // so we can easily catch the ResourceAllocationException on send + producerConnection.setAlwaysSyncSend(true); + producerConnection.start(); - Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - try { - while (true) { - Message message = session.createTextMessage(new String(buf) + messagesSent.toString()); - producer.send(message); - messagesSent.incrementAndGet(); - if (messagesSent.get() % 100 == 0) { - LOG.info("Sent Message " + messagesSent.get()); - LOG.info("Temp Store Usage " + broker.getSystemUsage().getTempUsage().getUsage()); - } + try { + while (true) { + Message message = session.createTextMessage(new String(buf) + messagesSent.toString()); + producer.send(message); + messagesSent.incrementAndGet(); + if (messagesSent.get() % 100 == 0) { + LOG.info("Sent Message " + messagesSent.get()); + LOG.info("Temp Store Usage " + broker.getSystemUsage().getTempUsage().getUsage()); } - } catch (ResourceAllocationException ex) { - assertTrue("Should be able to send at least 200 messages but was: " + messagesSent.get(), - messagesSent.get() > 200); - LOG.info("Got resource exception : " + ex + ", after sent: " + messagesSent.get()); - } + } + } + catch (ResourceAllocationException ex) { + assertTrue("Should be able to send at least 200 messages but was: " + messagesSent.get(), messagesSent.get() > 200); + LOG.info("Got resource exception : " + ex + ", after sent: " + messagesSent.get()); + } - // consume all sent - Connection consumerConnection = factory.createConnection(); - consumerConnection.start(); + // consume all sent + Connection consumerConnection = factory.createConnection(); + consumerConnection.start(); - Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = consumerSession.createConsumer(destination); + Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = consumerSession.createConsumer(destination); - while (consumer.receive(messageReceiveTimeout) != null) { - messagesConsumed.incrementAndGet(); - if (messagesConsumed.get() % 1000 == 0) { - LOG.info("received Message " + messagesConsumed.get()); - LOG.info("Temp Store Usage " + broker.getSystemUsage().getTempUsage().getUsage()); - } - } + while (consumer.receive(messageReceiveTimeout) != null) { + messagesConsumed.incrementAndGet(); + if (messagesConsumed.get() % 1000 == 0) { + LOG.info("received Message " + messagesConsumed.get()); + LOG.info("Temp Store Usage " + broker.getSystemUsage().getTempUsage().getUsage()); + } + } - assertEquals("Incorrect number of Messages Consumed: " + messagesConsumed.get(), - messagesConsumed.get(), messagesSent.get()); - } + assertEquals("Incorrect number of Messages Consumed: " + messagesConsumed.get(), messagesConsumed.get(), messagesSent.get()); + } - private void createBrokerWithValidTempStoreConfig() throws Exception { - broker = new BrokerService(); - broker.setDataDirectory("target" + File.separator + "activemq-data"); - broker.setPersistent(true); - broker.setUseJmx(true); - broker.setAdvisorySupport(false); - broker.setDeleteAllMessagesOnStartup(true); - broker.setPersistenceAdapter(new KahaDBPersistenceAdapter()); + private void createBrokerWithValidTempStoreConfig() throws Exception { + broker = new BrokerService(); + broker.setDataDirectory("target" + File.separator + "activemq-data"); + broker.setPersistent(true); + broker.setUseJmx(true); + broker.setAdvisorySupport(false); + broker.setDeleteAllMessagesOnStartup(true); + broker.setPersistenceAdapter(new KahaDBPersistenceAdapter()); - broker.getSystemUsage().setSendFailIfNoSpace(true); - broker.getSystemUsage().getMemoryUsage().setLimit(1048576); - broker.getSystemUsage().getTempUsage().setLimit(2*1048576); - ((PListStoreImpl)broker.getSystemUsage().getTempUsage().getStore()).setJournalMaxFileLength(2 * 1048576); - broker.getSystemUsage().getStoreUsage().setLimit(20*1048576); + broker.getSystemUsage().setSendFailIfNoSpace(true); + broker.getSystemUsage().getMemoryUsage().setLimit(1048576); + broker.getSystemUsage().getTempUsage().setLimit(2 * 1048576); + ((PListStoreImpl) broker.getSystemUsage().getTempUsage().getStore()).setJournalMaxFileLength(2 * 1048576); + broker.getSystemUsage().getStoreUsage().setLimit(20 * 1048576); - PolicyEntry defaultPolicy = new PolicyEntry(); - defaultPolicy.setProducerFlowControl(false); - defaultPolicy.setMemoryLimit(10 * 1024); + PolicyEntry defaultPolicy = new PolicyEntry(); + defaultPolicy.setProducerFlowControl(false); + defaultPolicy.setMemoryLimit(10 * 1024); - PolicyMap policyMap = new PolicyMap(); - policyMap.setDefaultEntry(defaultPolicy); + PolicyMap policyMap = new PolicyMap(); + policyMap.setDefaultEntry(defaultPolicy); - broker.setDestinationPolicy(policyMap); - broker.addConnector("tcp://localhost:0").setName("Default"); - broker.start(); + broker.setDestinationPolicy(policyMap); + broker.addConnector("tcp://localhost:0").setName("Default"); + broker.start(); - brokerUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); - } + brokerUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); + } - private void createBrokerWithInvalidTempStoreConfig() throws Exception { - broker = new BrokerService(); - broker.setDataDirectory("target" + File.separator + "activemq-data"); - broker.setPersistent(true); - broker.setUseJmx(true); - broker.setAdvisorySupport(false); - broker.setDeleteAllMessagesOnStartup(true); - broker.setPersistenceAdapter(new KahaDBPersistenceAdapter()); + private void createBrokerWithInvalidTempStoreConfig() throws Exception { + broker = new BrokerService(); + broker.setDataDirectory("target" + File.separator + "activemq-data"); + broker.setPersistent(true); + broker.setUseJmx(true); + broker.setAdvisorySupport(false); + broker.setDeleteAllMessagesOnStartup(true); + broker.setPersistenceAdapter(new KahaDBPersistenceAdapter()); - broker.getSystemUsage().setSendFailIfNoSpace(true); - broker.getSystemUsage().getMemoryUsage().setLimit(1048576); - broker.getSystemUsage().getTempUsage().setLimit(2*1048576); - broker.getSystemUsage().getStoreUsage().setLimit(2*1048576); + broker.getSystemUsage().setSendFailIfNoSpace(true); + broker.getSystemUsage().getMemoryUsage().setLimit(1048576); + broker.getSystemUsage().getTempUsage().setLimit(2 * 1048576); + broker.getSystemUsage().getStoreUsage().setLimit(2 * 1048576); - PolicyEntry defaultPolicy = new PolicyEntry(); - defaultPolicy.setProducerFlowControl(false); - defaultPolicy.setMemoryLimit(10 * 1024); + PolicyEntry defaultPolicy = new PolicyEntry(); + defaultPolicy.setProducerFlowControl(false); + defaultPolicy.setMemoryLimit(10 * 1024); - PolicyMap policyMap = new PolicyMap(); - policyMap.setDefaultEntry(defaultPolicy); + PolicyMap policyMap = new PolicyMap(); + policyMap.setDefaultEntry(defaultPolicy); - broker.setDestinationPolicy(policyMap); - broker.addConnector("tcp://localhost:0").setName("Default"); - broker.start(); + broker.setDestinationPolicy(policyMap); + broker.addConnector("tcp://localhost:0").setName("Default"); + broker.start(); - brokerUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); - } + brokerUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); + } - @After - public void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - } - } + @After + public void tearDown() throws Exception { + if (broker != null) { + broker.stop(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TempStoreDataCleanupTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TempStoreDataCleanupTest.java index 455f6bab1a..8051a59798 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TempStoreDataCleanupTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TempStoreDataCleanupTest.java @@ -51,211 +51,212 @@ import org.slf4j.LoggerFactory; public class TempStoreDataCleanupTest { - private static final Logger LOG = LoggerFactory.getLogger(TempStoreDataCleanupTest.class); - private static final String QUEUE_NAME = TempStoreDataCleanupTest.class.getName() + "Queue"; + private static final Logger LOG = LoggerFactory.getLogger(TempStoreDataCleanupTest.class); + private static final String QUEUE_NAME = TempStoreDataCleanupTest.class.getName() + "Queue"; - private final String str = new String( - "QAa0bcLdUK2eHfJgTP8XhiFj61DOklNm9nBoI5pGqYVrs3CtSuMZvwWx4yE7zR"); + private final String str = new String("QAa0bcLdUK2eHfJgTP8XhiFj61DOklNm9nBoI5pGqYVrs3CtSuMZvwWx4yE7zR"); - private BrokerService broker; - private String connectionUri; - private ExecutorService pool; - private String queueName; - private Random r = new Random(); + private BrokerService broker; + private String connectionUri; + private ExecutorService pool; + private String queueName; + private Random r = new Random(); - @Before - public void setUp() throws Exception { + @Before + public void setUp() throws Exception { - broker = new BrokerService(); - broker.setDataDirectory("target" + File.separator + "activemq-data"); - broker.setPersistent(true); - broker.setUseJmx(true); - broker.setDedicatedTaskRunner(false); - broker.setAdvisorySupport(false); - broker.setDeleteAllMessagesOnStartup(true); + broker = new BrokerService(); + broker.setDataDirectory("target" + File.separator + "activemq-data"); + broker.setPersistent(true); + broker.setUseJmx(true); + broker.setDedicatedTaskRunner(false); + broker.setAdvisorySupport(false); + broker.setDeleteAllMessagesOnStartup(true); - SharedDeadLetterStrategy strategy = new SharedDeadLetterStrategy(); - strategy.setProcessExpired(false); - strategy.setProcessNonPersistent(false); + SharedDeadLetterStrategy strategy = new SharedDeadLetterStrategy(); + strategy.setProcessExpired(false); + strategy.setProcessNonPersistent(false); - PolicyEntry defaultPolicy = new PolicyEntry(); - defaultPolicy.setQueue(">"); - defaultPolicy.setOptimizedDispatch(true); - defaultPolicy.setDeadLetterStrategy(strategy); - defaultPolicy.setMemoryLimit(9000000); + PolicyEntry defaultPolicy = new PolicyEntry(); + defaultPolicy.setQueue(">"); + defaultPolicy.setOptimizedDispatch(true); + defaultPolicy.setDeadLetterStrategy(strategy); + defaultPolicy.setMemoryLimit(9000000); - PolicyMap policyMap = new PolicyMap(); - policyMap.setDefaultEntry(defaultPolicy); + PolicyMap policyMap = new PolicyMap(); + policyMap.setDefaultEntry(defaultPolicy); - broker.setDestinationPolicy(policyMap); + broker.setDestinationPolicy(policyMap); - broker.getSystemUsage().getMemoryUsage().setLimit(300000000L); + broker.getSystemUsage().getMemoryUsage().setLimit(300000000L); - broker.addConnector("tcp://localhost:0").setName("Default"); - broker.start(); - broker.waitUntilStarted(); + broker.addConnector("tcp://localhost:0").setName("Default"); + broker.start(); + broker.waitUntilStarted(); - connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); - pool = Executors.newFixedThreadPool(10); - } + connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); + pool = Executors.newFixedThreadPool(10); + } - @After - public void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } + @After + public void tearDown() throws Exception { + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } - if (pool != null) { - pool.shutdown(); - } - } + if (pool != null) { + pool.shutdown(); + } + } - @Test - public void testIt() throws Exception { + @Test + public void testIt() throws Exception { - int startPercentage = broker.getAdminView().getMemoryPercentUsage(); - LOG.info("MemoryUsage at test start = " + startPercentage); + int startPercentage = broker.getAdminView().getMemoryPercentUsage(); + LOG.info("MemoryUsage at test start = " + startPercentage); - for (int i = 0; i < 2; i++) { - LOG.info("Started the test iteration: " + i + " using queueName = " + queueName); - queueName = QUEUE_NAME + i; - final CountDownLatch latch = new CountDownLatch(11); + for (int i = 0; i < 2; i++) { + LOG.info("Started the test iteration: " + i + " using queueName = " + queueName); + queueName = QUEUE_NAME + i; + final CountDownLatch latch = new CountDownLatch(11); + pool.execute(new Runnable() { + @Override + public void run() { + receiveAndDiscard100messages(latch); + } + }); + + for (int j = 0; j < 10; j++) { pool.execute(new Runnable() { - @Override - public void run() { - receiveAndDiscard100messages(latch); - } + @Override + public void run() { + send10000messages(latch); + } }); + } + + LOG.info("Waiting on the send / receive latch"); + latch.await(5, TimeUnit.MINUTES); + LOG.info("Resumed"); + + destroyQueue(); + TimeUnit.SECONDS.sleep(2); + } + + LOG.info("MemoryUsage before awaiting temp store cleanup = " + broker.getAdminView().getMemoryPercentUsage()); + + final PListStoreImpl pa = (PListStoreImpl) broker.getTempDataStore(); + assertTrue("only one journal file should be left: " + pa.getJournal().getFileMap().size(), Wait.waitFor(new Wait.Condition() { - for (int j = 0; j < 10; j++) { - pool.execute(new Runnable() { @Override - public void run() { - send10000messages(latch); + public boolean isSatisified() throws Exception { + return pa.getJournal().getFileMap().size() == 1; } - }); + }, TimeUnit.MINUTES.toMillis(3))); + + int endPercentage = broker.getAdminView().getMemoryPercentUsage(); + LOG.info("MemoryUsage at test end = " + endPercentage); + + assertEquals(startPercentage, endPercentage); + } + + public void destroyQueue() { + try { + Broker broker = this.broker.getBroker(); + if (!broker.isStopped()) { + LOG.info("Removing: " + queueName); + broker.removeDestination(this.broker.getAdminConnectionContext(), new ActiveMQQueue(queueName), 10); + } + } + catch (Exception e) { + LOG.warn("Got an error while removing the test queue", e); + } + } + + private void send10000messages(CountDownLatch latch) { + ActiveMQConnection activeMQConnection = null; + try { + activeMQConnection = createConnection(null); + Session session = activeMQConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(session.createQueue(queueName)); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + activeMQConnection.start(); + for (int i = 0; i < 10000; i++) { + TextMessage textMessage = session.createTextMessage(); + textMessage.setText(generateBody(1000)); + textMessage.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT); + producer.send(textMessage); + try { + Thread.sleep(10); } - - LOG.info("Waiting on the send / receive latch"); - latch.await(5, TimeUnit.MINUTES); - LOG.info("Resumed"); - - destroyQueue(); - TimeUnit.SECONDS.sleep(2); - } - - LOG.info("MemoryUsage before awaiting temp store cleanup = " + broker.getAdminView().getMemoryPercentUsage()); - - final PListStoreImpl pa = (PListStoreImpl) broker.getTempDataStore(); - assertTrue("only one journal file should be left: " + pa.getJournal().getFileMap().size(), - Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - return pa.getJournal().getFileMap().size() == 1; - } - }, TimeUnit.MINUTES.toMillis(3)) - ); - - int endPercentage = broker.getAdminView().getMemoryPercentUsage(); - LOG.info("MemoryUsage at test end = " + endPercentage); - - assertEquals(startPercentage, endPercentage); - } - - public void destroyQueue() { - try { - Broker broker = this.broker.getBroker(); - if (!broker.isStopped()) { - LOG.info("Removing: " + queueName); - broker.removeDestination(this.broker.getAdminConnectionContext(), new ActiveMQQueue(queueName), 10); + catch (InterruptedException e) { } - } catch (Exception e) { - LOG.warn("Got an error while removing the test queue", e); - } - } - - private void send10000messages(CountDownLatch latch) { - ActiveMQConnection activeMQConnection = null; - try { - activeMQConnection = createConnection(null); - Session session = activeMQConnection.createSession(false, - Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(session - .createQueue(queueName)); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - activeMQConnection.start(); - for (int i = 0; i < 10000; i++) { - TextMessage textMessage = session.createTextMessage(); - textMessage.setText(generateBody(1000)); - textMessage.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT); - producer.send(textMessage); - try { - Thread.sleep(10); - } catch (InterruptedException e) { - } + } + producer.close(); + } + catch (JMSException e) { + LOG.warn("Got an error while sending the messages", e); + } + finally { + if (activeMQConnection != null) { + try { + activeMQConnection.close(); } - producer.close(); - } catch (JMSException e) { - LOG.warn("Got an error while sending the messages", e); - } finally { - if (activeMQConnection != null) { - try { - activeMQConnection.close(); - } catch (JMSException e) { - } + catch (JMSException e) { } - } - latch.countDown(); - } + } + } + latch.countDown(); + } - private void receiveAndDiscard100messages(CountDownLatch latch) { - ActiveMQConnection activeMQConnection = null; - try { - activeMQConnection = createConnection(null); - Session session = activeMQConnection.createSession(false, - Session.AUTO_ACKNOWLEDGE); - MessageConsumer messageConsumer = session.createConsumer( - session.createQueue(queueName)); - activeMQConnection.start(); - for (int i = 0; i < 100; i++) { - messageConsumer.receive(); + private void receiveAndDiscard100messages(CountDownLatch latch) { + ActiveMQConnection activeMQConnection = null; + try { + activeMQConnection = createConnection(null); + Session session = activeMQConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer messageConsumer = session.createConsumer(session.createQueue(queueName)); + activeMQConnection.start(); + for (int i = 0; i < 100; i++) { + messageConsumer.receive(); + } + messageConsumer.close(); + LOG.info("Created and disconnected"); + } + catch (JMSException e) { + LOG.warn("Got an error while receiving the messages", e); + } + finally { + if (activeMQConnection != null) { + try { + activeMQConnection.close(); } - messageConsumer.close(); - LOG.info("Created and disconnected"); - } catch (JMSException e) { - LOG.warn("Got an error while receiving the messages", e); - } finally { - if (activeMQConnection != null) { - try { - activeMQConnection.close(); - } catch (JMSException e) { - } + catch (JMSException e) { } - } - latch.countDown(); - } + } + } + latch.countDown(); + } - private ActiveMQConnection createConnection(String id) throws JMSException { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - if (id != null) { - factory.setClientID(id); - } + private ActiveMQConnection createConnection(String id) throws JMSException { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); + if (id != null) { + factory.setClientID(id); + } - ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); - return connection; - } + ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); + return connection; + } - private String generateBody(int length) { + private String generateBody(int length) { - StringBuilder sb = new StringBuilder(); - int te = 0; - for (int i = 1; i <= length; i++) { - te = r.nextInt(62); - sb.append(str.charAt(te)); - } - return sb.toString(); - } + StringBuilder sb = new StringBuilder(); + int te = 0; + for (int i = 1; i <= length; i++) { + te = r.nextInt(62); + sb.append(str.charAt(te)); + } + return sb.toString(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TransactedStoreUsageSuspendResumeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TransactedStoreUsageSuspendResumeTest.java index 3d32867ff7..0358bde9a1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TransactedStoreUsageSuspendResumeTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TransactedStoreUsageSuspendResumeTest.java @@ -29,6 +29,7 @@ import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.TestSupport; import org.apache.activemq.broker.BrokerService; @@ -40,154 +41,156 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import static org.junit.Assert.assertTrue; // https://issues.apache.org/jira/browse/AMQ-4262 public class TransactedStoreUsageSuspendResumeTest { - private static final Logger LOG = LoggerFactory.getLogger(TransactedStoreUsageSuspendResumeTest.class); - private static final int MAX_MESSAGES = 10000; + private static final Logger LOG = LoggerFactory.getLogger(TransactedStoreUsageSuspendResumeTest.class); - private static final String QUEUE_NAME = "test.queue"; + private static final int MAX_MESSAGES = 10000; - private BrokerService broker; + private static final String QUEUE_NAME = "test.queue"; - private final CountDownLatch messagesReceivedCountDown = new CountDownLatch(MAX_MESSAGES); - private final CountDownLatch messagesSentCountDown = new CountDownLatch(MAX_MESSAGES); - private final CountDownLatch consumerStartLatch = new CountDownLatch(1); + private BrokerService broker; - private class ConsumerThread extends Thread { + private final CountDownLatch messagesReceivedCountDown = new CountDownLatch(MAX_MESSAGES); + private final CountDownLatch messagesSentCountDown = new CountDownLatch(MAX_MESSAGES); + private final CountDownLatch consumerStartLatch = new CountDownLatch(1); - @Override - public void run() { + private class ConsumerThread extends Thread { + + @Override + public void run() { + try { + + consumerStartLatch.await(30, TimeUnit.SECONDS); + + ConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + Connection connection = factory.createConnection(); + connection.start(); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + + // wait for producer to stop + long currentSendCount; + do { + currentSendCount = messagesSentCountDown.getCount(); + TimeUnit.SECONDS.sleep(5); + } while (currentSendCount != messagesSentCountDown.getCount()); + + LOG.info("Starting consumer at: " + currentSendCount); + + MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME)); + + do { + Message message = consumer.receive(5000); + if (message != null) { + session.commit(); + messagesReceivedCountDown.countDown(); + } + if (messagesReceivedCountDown.getCount() % 500 == 0) { + LOG.info("remaining to receive: " + messagesReceivedCountDown.getCount()); + } + } while (messagesReceivedCountDown.getCount() != 0); + consumer.close(); + session.close(); + connection.close(); + } + catch (Exception e) { + Assert.fail(e.getMessage()); + } + } + } + + @Before + public void setup() throws Exception { + + broker = new BrokerService(); + broker.setDeleteAllMessagesOnStartup(true); + broker.setPersistent(true); + + KahaDBPersistenceAdapter kahaDB = new KahaDBPersistenceAdapter(); + kahaDB.setJournalMaxFileLength(500 * 1024); + kahaDB.setCleanupInterval(10 * 1000); + broker.setPersistenceAdapter(kahaDB); + + broker.getSystemUsage().getStoreUsage().setLimit(7 * 1024 * 1024); + + broker.start(); + broker.waitUntilStarted(); + } + + @After + public void tearDown() throws Exception { + broker.stop(); + } + + @Test + public void testTransactedStoreUsageSuspendResume() throws Exception { + + ConsumerThread thread = new ConsumerThread(); + thread.start(); + ExecutorService sendExecutor = Executors.newSingleThreadExecutor(); + sendExecutor.execute(new Runnable() { + @Override + public void run() { try { - - consumerStartLatch.await(30, TimeUnit.SECONDS); - - ConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = factory.createConnection(); - connection.start(); - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - - // wait for producer to stop - long currentSendCount; - do { - currentSendCount = messagesSentCountDown.getCount(); - TimeUnit.SECONDS.sleep(5); - } while (currentSendCount != messagesSentCountDown.getCount()); - - LOG.info("Starting consumer at: " + currentSendCount); - - MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME)); - - do { - Message message = consumer.receive(5000); - if (message != null) { - session.commit(); - messagesReceivedCountDown.countDown(); - } - if (messagesReceivedCountDown.getCount() % 500 == 0) { - LOG.info("remaining to receive: " + messagesReceivedCountDown.getCount()); - } - } while (messagesReceivedCountDown.getCount() != 0); - consumer.close(); - session.close(); - connection.close(); - } catch (Exception e) { - Assert.fail(e.getMessage()); + sendMessages(); } - } - } - - @Before - public void setup() throws Exception { - - broker = new BrokerService(); - broker.setDeleteAllMessagesOnStartup(true); - broker.setPersistent(true); - - KahaDBPersistenceAdapter kahaDB = new KahaDBPersistenceAdapter(); - kahaDB.setJournalMaxFileLength(500 * 1024); - kahaDB.setCleanupInterval(10*1000); - broker.setPersistenceAdapter(kahaDB); - - broker.getSystemUsage().getStoreUsage().setLimit(7*1024*1024); - - broker.start(); - broker.waitUntilStarted(); - } - - @After - public void tearDown() throws Exception { - broker.stop(); - } - - @Test - public void testTransactedStoreUsageSuspendResume() throws Exception { - - ConsumerThread thread = new ConsumerThread(); - thread.start(); - ExecutorService sendExecutor = Executors.newSingleThreadExecutor(); - sendExecutor.execute(new Runnable() { - @Override - public void run() { - try { - sendMessages(); - } catch (Exception ignored) { - } + catch (Exception ignored) { } - }); - sendExecutor.shutdown(); - sendExecutor.awaitTermination(5, TimeUnit.MINUTES); + } + }); + sendExecutor.shutdown(); + sendExecutor.awaitTermination(5, TimeUnit.MINUTES); - boolean allMessagesReceived = messagesReceivedCountDown.await(10, TimeUnit.MINUTES); - if (!allMessagesReceived) { - TestSupport.dumpAllThreads("StuckConsumer!"); - } - assertTrue("Got all messages: " + messagesReceivedCountDown, allMessagesReceived); + boolean allMessagesReceived = messagesReceivedCountDown.await(10, TimeUnit.MINUTES); + if (!allMessagesReceived) { + TestSupport.dumpAllThreads("StuckConsumer!"); + } + assertTrue("Got all messages: " + messagesReceivedCountDown, allMessagesReceived); - // give consumers a chance to exit gracefully - TimeUnit.SECONDS.sleep(2); - } + // give consumers a chance to exit gracefully + TimeUnit.SECONDS.sleep(2); + } - private void sendMessages() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - factory.setAlwaysSyncSend(true); - Connection connection = factory.createConnection(); - connection.start(); - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Destination queue = session.createQueue(QUEUE_NAME); - Destination retainQueue = session.createQueue(QUEUE_NAME + "-retain"); - MessageProducer producer = session.createProducer(null); + private void sendMessages() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + factory.setAlwaysSyncSend(true); + Connection connection = factory.createConnection(); + connection.start(); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + Destination queue = session.createQueue(QUEUE_NAME); + Destination retainQueue = session.createQueue(QUEUE_NAME + "-retain"); + MessageProducer producer = session.createProducer(null); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - BytesMessage message = session.createBytesMessage(); - message.writeBytes(new byte[10]); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + BytesMessage message = session.createBytesMessage(); + message.writeBytes(new byte[10]); - for (int i=0; i<4240; i++) { - // mostly fill the store with retained messages - // so consumer only has a small bit of store usage to work with - producer.send(retainQueue, message); + for (int i = 0; i < 4240; i++) { + // mostly fill the store with retained messages + // so consumer only has a small bit of store usage to work with + producer.send(retainQueue, message); + session.commit(); + } + + consumerStartLatch.countDown(); + for (int i = 0; i < MAX_MESSAGES; i++) { + producer.send(queue, message); + if (i > 0 && i % 20 == 0) { session.commit(); - } + } + messagesSentCountDown.countDown(); + if (i > 0 && i % 500 == 0) { + LOG.info("Sent : " + i); + } - consumerStartLatch.countDown(); - for (int i = 0; i < MAX_MESSAGES; i++) { - producer.send(queue, message); - if (i>0 && i%20 == 0) { - session.commit(); - } - messagesSentCountDown.countDown(); - if (i>0 && i%500 == 0) { - LOG.info("Sent : " + i); - } - - } - session.commit(); - producer.close(); - session.close(); - connection.close(); - } + } + session.commit(); + producer.close(); + session.close(); + connection.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TransactionNotStartedErrorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TransactionNotStartedErrorTest.java index af2b992519..b21462f351 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TransactionNotStartedErrorTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TransactionNotStartedErrorTest.java @@ -25,6 +25,7 @@ import javax.jms.ObjectMessage; import javax.jms.Session; import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.slf4j.Logger; @@ -42,243 +43,247 @@ import org.slf4j.LoggerFactory; */ public class TransactionNotStartedErrorTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(TransactionNotStartedErrorTest.class); + private static final Logger LOG = LoggerFactory.getLogger(TransactionNotStartedErrorTest.class); - private static final int counter = 500; + private static final int counter = 500; - private static int hectorToHaloCtr; - private static int xenaToHaloCtr; - private static int troyToHaloCtr; + private static int hectorToHaloCtr; + private static int xenaToHaloCtr; + private static int troyToHaloCtr; - private static int haloToHectorCtr; - private static int haloToXenaCtr; - private static int haloToTroyCtr; + private static int haloToHectorCtr; + private static int haloToXenaCtr; + private static int haloToTroyCtr; - private final String hectorToHalo = "hectorToHalo"; - private final String xenaToHalo = "xenaToHalo"; - private final String troyToHalo = "troyToHalo"; + private final String hectorToHalo = "hectorToHalo"; + private final String xenaToHalo = "xenaToHalo"; + private final String troyToHalo = "troyToHalo"; - private final String haloToHector = "haloToHector"; - private final String haloToXena = "haloToXena"; - private final String haloToTroy = "haloToTroy"; + private final String haloToHector = "haloToHector"; + private final String haloToXena = "haloToXena"; + private final String haloToTroy = "haloToTroy"; - private BrokerService broker; + private BrokerService broker; - private Connection hectorConnection; - private Connection xenaConnection; - private Connection troyConnection; - private Connection haloConnection; + private Connection hectorConnection; + private Connection xenaConnection; + private Connection troyConnection; + private Connection haloConnection; - private final Object lock = new Object(); + private final Object lock = new Object(); - public Connection createConnection() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory( - broker.getTransportConnectors().get(0).getPublishableConnectString()); - return factory.createConnection(); - } + public Connection createConnection() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString()); + return factory.createConnection(); + } - public Session createSession(Connection connection, boolean transacted) throws JMSException { - return connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE); - } + public Session createSession(Connection connection, boolean transacted) throws JMSException { + return connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE); + } - public void startBroker() throws Exception { - broker = new BrokerService(); - broker.setDeleteAllMessagesOnStartup(true); - broker.setPersistent(true); - broker.setUseJmx(true); - broker.addConnector("tcp://localhost:0").setName("Default"); - broker.start(); - LOG.info("Starting broker.."); - } + public void startBroker() throws Exception { + broker = new BrokerService(); + broker.setDeleteAllMessagesOnStartup(true); + broker.setPersistent(true); + broker.setUseJmx(true); + broker.addConnector("tcp://localhost:0").setName("Default"); + broker.start(); + LOG.info("Starting broker.."); + } - public void tearDown() throws Exception { - hectorConnection.close(); - xenaConnection.close(); - troyConnection.close(); - haloConnection.close(); - broker.stop(); - } + public void tearDown() throws Exception { + hectorConnection.close(); + xenaConnection.close(); + troyConnection.close(); + haloConnection.close(); + broker.stop(); + } - public void testTransactionNotStartedError() throws Exception { - startBroker(); - hectorConnection = createConnection(); - Thread hectorThread = buildProducer(hectorConnection, hectorToHalo); - Receiver hHectorReceiver = new Receiver() { - public void receive(String s) throws Exception { - haloToHectorCtr++; - if (haloToHectorCtr >= counter) { - synchronized (lock) { - lock.notifyAll(); - } - } + public void testTransactionNotStartedError() throws Exception { + startBroker(); + hectorConnection = createConnection(); + Thread hectorThread = buildProducer(hectorConnection, hectorToHalo); + Receiver hHectorReceiver = new Receiver() { + public void receive(String s) throws Exception { + haloToHectorCtr++; + if (haloToHectorCtr >= counter) { + synchronized (lock) { + lock.notifyAll(); + } } - }; - buildReceiver(hectorConnection, haloToHector, false, hHectorReceiver); + } + }; + buildReceiver(hectorConnection, haloToHector, false, hHectorReceiver); - troyConnection = createConnection(); - Thread troyThread = buildProducer(troyConnection, troyToHalo); - Receiver hTroyReceiver = new Receiver() { - public void receive(String s) throws Exception { - haloToTroyCtr++; - if (haloToTroyCtr >= counter) { - synchronized (lock) { - lock.notifyAll(); - } - } + troyConnection = createConnection(); + Thread troyThread = buildProducer(troyConnection, troyToHalo); + Receiver hTroyReceiver = new Receiver() { + public void receive(String s) throws Exception { + haloToTroyCtr++; + if (haloToTroyCtr >= counter) { + synchronized (lock) { + lock.notifyAll(); + } } - }; - buildReceiver(hectorConnection, haloToTroy, false, hTroyReceiver); + } + }; + buildReceiver(hectorConnection, haloToTroy, false, hTroyReceiver); - xenaConnection = createConnection(); - Thread xenaThread = buildProducer(xenaConnection, xenaToHalo); - Receiver hXenaReceiver = new Receiver() { - public void receive(String s) throws Exception { - haloToXenaCtr++; - if (haloToXenaCtr >= counter) { - synchronized (lock) { - lock.notifyAll(); - } - } + xenaConnection = createConnection(); + Thread xenaThread = buildProducer(xenaConnection, xenaToHalo); + Receiver hXenaReceiver = new Receiver() { + public void receive(String s) throws Exception { + haloToXenaCtr++; + if (haloToXenaCtr >= counter) { + synchronized (lock) { + lock.notifyAll(); + } } - }; - buildReceiver(xenaConnection, haloToXena, false, hXenaReceiver); + } + }; + buildReceiver(xenaConnection, haloToXena, false, hXenaReceiver); - haloConnection = createConnection(); - final MessageSender hectorSender = buildTransactionalProducer(haloToHector, haloConnection); - final MessageSender troySender = buildTransactionalProducer(haloToTroy, haloConnection); - final MessageSender xenaSender = buildTransactionalProducer(haloToXena, haloConnection); - Receiver hectorReceiver = new Receiver() { - public void receive(String s) throws Exception { - hectorToHaloCtr++; - troySender.send("halo to troy because of hector"); - if (hectorToHaloCtr >= counter) { - synchronized (lock) { - lock.notifyAll(); - } - } + haloConnection = createConnection(); + final MessageSender hectorSender = buildTransactionalProducer(haloToHector, haloConnection); + final MessageSender troySender = buildTransactionalProducer(haloToTroy, haloConnection); + final MessageSender xenaSender = buildTransactionalProducer(haloToXena, haloConnection); + Receiver hectorReceiver = new Receiver() { + public void receive(String s) throws Exception { + hectorToHaloCtr++; + troySender.send("halo to troy because of hector"); + if (hectorToHaloCtr >= counter) { + synchronized (lock) { + lock.notifyAll(); + } } - }; - Receiver xenaReceiver = new Receiver() { - public void receive(String s) throws Exception { - xenaToHaloCtr++; - hectorSender.send("halo to hector because of xena"); - if (xenaToHaloCtr >= counter) { - synchronized (lock) { - lock.notifyAll(); - } - } + } + }; + Receiver xenaReceiver = new Receiver() { + public void receive(String s) throws Exception { + xenaToHaloCtr++; + hectorSender.send("halo to hector because of xena"); + if (xenaToHaloCtr >= counter) { + synchronized (lock) { + lock.notifyAll(); + } } - }; - Receiver troyReceiver = new Receiver() { - public void receive(String s) throws Exception { - troyToHaloCtr++; - xenaSender.send("halo to xena because of troy"); - if (troyToHaloCtr >= counter) { - synchronized (lock) { - lock.notifyAll(); - } - } + } + }; + Receiver troyReceiver = new Receiver() { + public void receive(String s) throws Exception { + troyToHaloCtr++; + xenaSender.send("halo to xena because of troy"); + if (troyToHaloCtr >= counter) { + synchronized (lock) { + lock.notifyAll(); + } } - }; - buildReceiver(haloConnection, hectorToHalo, true, hectorReceiver); - buildReceiver(haloConnection, xenaToHalo, true, xenaReceiver); - buildReceiver(haloConnection, troyToHalo, true, troyReceiver); + } + }; + buildReceiver(haloConnection, hectorToHalo, true, hectorReceiver); + buildReceiver(haloConnection, xenaToHalo, true, xenaReceiver); + buildReceiver(haloConnection, troyToHalo, true, troyReceiver); - haloConnection.start(); + haloConnection.start(); - troyConnection.start(); - troyThread.start(); + troyConnection.start(); + troyThread.start(); - xenaConnection.start(); - xenaThread.start(); + xenaConnection.start(); + xenaThread.start(); - hectorConnection.start(); - hectorThread.start(); - waitForMessagesToBeDelivered(); - // number of messages received should match messages sent - assertEquals(hectorToHaloCtr, counter); - LOG.info("hectorToHalo received " + hectorToHaloCtr + " messages"); - assertEquals(xenaToHaloCtr, counter); - LOG.info("xenaToHalo received " + xenaToHaloCtr + " messages"); - assertEquals(troyToHaloCtr, counter); - LOG.info("troyToHalo received " + troyToHaloCtr + " messages"); - assertEquals(haloToHectorCtr, counter); - LOG.info("haloToHector received " + haloToHectorCtr + " messages"); - assertEquals(haloToXenaCtr, counter); - LOG.info("haloToXena received " + haloToXenaCtr + " messages"); - assertEquals(haloToTroyCtr, counter); - LOG.info("haloToTroy received " + haloToTroyCtr + " messages"); + hectorConnection.start(); + hectorThread.start(); + waitForMessagesToBeDelivered(); + // number of messages received should match messages sent + assertEquals(hectorToHaloCtr, counter); + LOG.info("hectorToHalo received " + hectorToHaloCtr + " messages"); + assertEquals(xenaToHaloCtr, counter); + LOG.info("xenaToHalo received " + xenaToHaloCtr + " messages"); + assertEquals(troyToHaloCtr, counter); + LOG.info("troyToHalo received " + troyToHaloCtr + " messages"); + assertEquals(haloToHectorCtr, counter); + LOG.info("haloToHector received " + haloToHectorCtr + " messages"); + assertEquals(haloToXenaCtr, counter); + LOG.info("haloToXena received " + haloToXenaCtr + " messages"); + assertEquals(haloToTroyCtr, counter); + LOG.info("haloToTroy received " + haloToTroyCtr + " messages"); - } + } - protected void waitForMessagesToBeDelivered() { - // let's give the listeners enough time to read all messages - long maxWaitTime = counter * 3000; - long waitTime = maxWaitTime; - long start = (maxWaitTime <= 0) ? 0 : System.currentTimeMillis(); + protected void waitForMessagesToBeDelivered() { + // let's give the listeners enough time to read all messages + long maxWaitTime = counter * 3000; + long waitTime = maxWaitTime; + long start = (maxWaitTime <= 0) ? 0 : System.currentTimeMillis(); - synchronized (lock) { - boolean hasMessages = true; - while (hasMessages && waitTime >= 0) { - try { - lock.wait(200); - } catch (InterruptedException e) { - LOG.error(e.toString()); - } - // check if all messages have been received - hasMessages = hectorToHaloCtr < counter || xenaToHaloCtr < counter || troyToHaloCtr < counter || haloToHectorCtr < counter || haloToXenaCtr < counter - || haloToTroyCtr < counter; - waitTime = maxWaitTime - (System.currentTimeMillis() - start); + synchronized (lock) { + boolean hasMessages = true; + while (hasMessages && waitTime >= 0) { + try { + lock.wait(200); } - } - } - - public MessageSender buildTransactionalProducer(String queueName, Connection connection) throws Exception { - return new MessageSender(queueName, connection, true, false); - } - - public Thread buildProducer(Connection connection, final String queueName) throws Exception { - final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageSender producer = new MessageSender(queueName, connection, false, false); - Thread thread = new Thread() { - - public synchronized void run() { - for (int i = 0; i < counter; i++) { - try { - producer.send(queueName); - if (session.getTransacted()) { - session.commit(); - } - - } catch (Exception e) { - throw new RuntimeException("on " + queueName + " send", e); - } - } + catch (InterruptedException e) { + LOG.error(e.toString()); } - }; - return thread; - } + // check if all messages have been received + hasMessages = hectorToHaloCtr < counter || xenaToHaloCtr < counter || troyToHaloCtr < counter || haloToHectorCtr < counter || haloToXenaCtr < counter || haloToTroyCtr < counter; + waitTime = maxWaitTime - (System.currentTimeMillis() - start); + } + } + } - public void buildReceiver(Connection connection, final String queueName, boolean transacted, final Receiver receiver) throws Exception { - final Session session = transacted ? connection.createSession(true, Session.SESSION_TRANSACTED) : connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer inputMessageConsumer = session.createConsumer(session.createQueue(queueName)); - MessageListener messageListener = new MessageListener() { + public MessageSender buildTransactionalProducer(String queueName, Connection connection) throws Exception { + return new MessageSender(queueName, connection, true, false); + } - public void onMessage(Message message) { - try { - ObjectMessage objectMessage = (ObjectMessage)message; - String s = (String)objectMessage.getObject(); - receiver.receive(s); - if (session.getTransacted()) { - session.commit(); - } + public Thread buildProducer(Connection connection, final String queueName) throws Exception { + final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final MessageSender producer = new MessageSender(queueName, connection, false, false); + Thread thread = new Thread() { - } catch (Exception e) { - e.printStackTrace(); - } + public synchronized void run() { + for (int i = 0; i < counter; i++) { + try { + producer.send(queueName); + if (session.getTransacted()) { + session.commit(); + } + + } + catch (Exception e) { + throw new RuntimeException("on " + queueName + " send", e); + } } - }; - inputMessageConsumer.setMessageListener(messageListener); - } + } + }; + return thread; + } + + public void buildReceiver(Connection connection, + final String queueName, + boolean transacted, + final Receiver receiver) throws Exception { + final Session session = transacted ? connection.createSession(true, Session.SESSION_TRANSACTED) : connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer inputMessageConsumer = session.createConsumer(session.createQueue(queueName)); + MessageListener messageListener = new MessageListener() { + + public void onMessage(Message message) { + try { + ObjectMessage objectMessage = (ObjectMessage) message; + String s = (String) objectMessage.getObject(); + receiver.receive(s); + if (session.getTransacted()) { + session.commit(); + } + + } + catch (Exception e) { + e.printStackTrace(); + } + } + }; + inputMessageConsumer.setMessageListener(messageListener); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TrapMessageInJDBCStoreTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TrapMessageInJDBCStoreTest.java index ad6df7fc00..dfda2993f0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TrapMessageInJDBCStoreTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/TrapMessageInJDBCStoreTest.java @@ -33,7 +33,9 @@ import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; + import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.store.jdbc.DataSourceServiceSupport; @@ -53,239 +55,224 @@ import org.slf4j.LoggerFactory; * The test throws issues the commit to the DB but throws * an exception back to the broker. This scenario could happen when a network * cable is disconnected - message is committed to DB but broker does not know. - * - * */ public class TrapMessageInJDBCStoreTest extends TestCase { - private static final String MY_TEST_Q = "MY_TEST_Q"; - private static final Logger LOG = LoggerFactory - .getLogger(TrapMessageInJDBCStoreTest.class); - private String transportUrl = "tcp://127.0.0.1:0"; - private BrokerService broker; - private TestTransactionContext testTransactionContext; - private TestJDBCPersistenceAdapter jdbc; + private static final String MY_TEST_Q = "MY_TEST_Q"; + private static final Logger LOG = LoggerFactory.getLogger(TrapMessageInJDBCStoreTest.class); + private String transportUrl = "tcp://127.0.0.1:0"; + private BrokerService broker; + private TestTransactionContext testTransactionContext; + private TestJDBCPersistenceAdapter jdbc; - protected BrokerService createBroker(boolean withJMX) throws Exception { - BrokerService broker = new BrokerService(); + protected BrokerService createBroker(boolean withJMX) throws Exception { + BrokerService broker = new BrokerService(); - broker.setUseJmx(withJMX); + broker.setUseJmx(withJMX); - EmbeddedDataSource embeddedDataSource = (EmbeddedDataSource) DataSourceServiceSupport.createDataSource(IOHelper.getDefaultDataDirectory()); - embeddedDataSource.setCreateDatabase("create"); + EmbeddedDataSource embeddedDataSource = (EmbeddedDataSource) DataSourceServiceSupport.createDataSource(IOHelper.getDefaultDataDirectory()); + embeddedDataSource.setCreateDatabase("create"); - //wire in a TestTransactionContext (wrapper to TransactionContext) that has an executeBatch() - // method that can be configured to throw a SQL exception on demand - jdbc = new TestJDBCPersistenceAdapter(); - jdbc.setDataSource(embeddedDataSource); - jdbc.setCleanupPeriod(0); - testTransactionContext = new TestTransactionContext(jdbc); + //wire in a TestTransactionContext (wrapper to TransactionContext) that has an executeBatch() + // method that can be configured to throw a SQL exception on demand + jdbc = new TestJDBCPersistenceAdapter(); + jdbc.setDataSource(embeddedDataSource); + jdbc.setCleanupPeriod(0); + testTransactionContext = new TestTransactionContext(jdbc); - jdbc.setLockKeepAlivePeriod(1000L); - LeaseDatabaseLocker leaseDatabaseLocker = new LeaseDatabaseLocker(); - leaseDatabaseLocker.setLockAcquireSleepInterval(2000L); - jdbc.setLocker(leaseDatabaseLocker); + jdbc.setLockKeepAlivePeriod(1000L); + LeaseDatabaseLocker leaseDatabaseLocker = new LeaseDatabaseLocker(); + leaseDatabaseLocker.setLockAcquireSleepInterval(2000L); + jdbc.setLocker(leaseDatabaseLocker); - broker.setPersistenceAdapter(jdbc); + broker.setPersistenceAdapter(jdbc); - broker.setIoExceptionHandler(new LeaseLockerIOExceptionHandler()); + broker.setIoExceptionHandler(new LeaseLockerIOExceptionHandler()); - transportUrl = broker.addConnector(transportUrl).getPublishableConnectString(); - return broker; - } + transportUrl = broker.addConnector(transportUrl).getPublishableConnectString(); + return broker; + } - /** - * - * sends 3 messages to the queue. When the second message is being committed to the JDBCStore, $ - * it throws a dummy SQL exception - the message has been committed to the embedded DB before the exception - * is thrown - * - * Excepted correct outcome: receive 3 messages and the DB should contain no messages - * - * @throws Exception - */ + /** + * sends 3 messages to the queue. When the second message is being committed to the JDBCStore, $ + * it throws a dummy SQL exception - the message has been committed to the embedded DB before the exception + * is thrown + * + * Excepted correct outcome: receive 3 messages and the DB should contain no messages + * + * @throws Exception + */ - public void testDBCommitException() throws Exception { + public void testDBCommitException() throws Exception { - broker = this.createBroker(false); - broker.deleteAllMessages(); - broker.start(); - broker.waitUntilStarted(); + broker = this.createBroker(false); + broker.deleteAllMessages(); + broker.start(); + broker.waitUntilStarted(); - LOG.info("***Broker started..."); + LOG.info("***Broker started..."); - // failover but timeout in 5 seconds so the test does not hang - String failoverTransportURL = "failover:(" + transportUrl - + ")?timeout=5000"; + // failover but timeout in 5 seconds so the test does not hang + String failoverTransportURL = "failover:(" + transportUrl + ")?timeout=5000"; + sendMessage(MY_TEST_Q, failoverTransportURL); - sendMessage(MY_TEST_Q, failoverTransportURL); + //check db contents + ArrayList dbSeq = dbMessageCount(); + LOG.info("*** after send: db contains message seq " + dbSeq); - //check db contents - ArrayList dbSeq = dbMessageCount(); - LOG.info("*** after send: db contains message seq " +dbSeq ); + List consumedMessages = consumeMessages(MY_TEST_Q, failoverTransportURL); - List consumedMessages = consumeMessages(MY_TEST_Q,failoverTransportURL); + assertEquals("number of consumed messages", 3, consumedMessages.size()); - assertEquals("number of consumed messages",3,consumedMessages.size()); + //check db contents + dbSeq = dbMessageCount(); + LOG.info("*** after consume - db contains message seq " + dbSeq); - //check db contents - dbSeq = dbMessageCount(); - LOG.info("*** after consume - db contains message seq " + dbSeq); + assertEquals("number of messages in DB after test", 0, dbSeq.size()); - assertEquals("number of messages in DB after test",0,dbSeq.size()); + broker.stop(); + broker.waitUntilStopped(); + } - broker.stop(); - broker.waitUntilStopped(); - } + public List consumeMessages(String queue, String transportURL) throws JMSException { + Connection connection = null; + LOG.debug("*** consumeMessages() called ..."); + try { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(transportURL); - public List consumeMessages(String queue, - String transportURL) throws JMSException { - Connection connection = null; - LOG.debug("*** consumeMessages() called ..."); + connection = factory.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue(queue); - try { + ArrayList consumedMessages = new ArrayList(); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory( - transportURL); + MessageConsumer messageConsumer = session.createConsumer(destination); - connection = factory.createConnection(); - connection.start(); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(queue); + while (true) { + TextMessage textMessage = (TextMessage) messageConsumer.receive(4000); + LOG.debug("*** consumed Messages :" + textMessage); - ArrayList consumedMessages = new ArrayList(); - - MessageConsumer messageConsumer = session.createConsumer(destination); - - while(true){ - TextMessage textMessage= (TextMessage) messageConsumer.receive(4000); - LOG.debug("*** consumed Messages :"+textMessage); - - if(textMessage==null){ - return consumedMessages; - } - consumedMessages.add(textMessage); + if (textMessage == null) { + return consumedMessages; } + consumedMessages.add(textMessage); + } + } + finally { + if (connection != null) { + connection.close(); + } + } + } - } finally { - if (connection != null) { - connection.close(); - } - } - } + public void sendMessage(String queue, String transportURL) throws Exception { + Connection connection = null; - public void sendMessage(String queue, String transportURL) - throws Exception { - Connection connection = null; + try { - try { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(transportURL); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory( - transportURL); + connection = factory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue(queue); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); - connection = factory.createConnection(); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(queue); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); + TextMessage m = session.createTextMessage("1"); - TextMessage m = session.createTextMessage("1"); + LOG.debug("*** send message 1 to broker..."); + producer.send(m); - LOG.debug("*** send message 1 to broker..."); - producer.send(m); + // trigger SQL exception in transactionContext + LOG.debug("*** send message 2 to broker"); + m.setText("2"); + producer.send(m); - // trigger SQL exception in transactionContext - LOG.debug("*** send message 2 to broker"); - m.setText("2"); - producer.send(m); + //check db contents + ArrayList dbSeq = dbMessageCount(); + LOG.info("*** after send 2 - db contains message seq " + dbSeq); + assertEquals("number of messages in DB after send 2", 2, dbSeq.size()); - //check db contents - ArrayList dbSeq = dbMessageCount(); - LOG.info("*** after send 2 - db contains message seq " + dbSeq); - assertEquals("number of messages in DB after send 2",2,dbSeq.size()); + LOG.debug("*** send message 3 to broker"); + m.setText("3"); + producer.send(m); + LOG.debug("*** Finished sending messages to broker"); - LOG.debug("*** send message 3 to broker"); - m.setText("3"); - producer.send(m); - LOG.debug("*** Finished sending messages to broker"); + } + finally { + if (connection != null) { + connection.close(); + } + } + } - } finally { - if (connection != null) { - connection.close(); - } - } - } + /** + * query the DB to see what messages are left in the store + * + * @return + * @throws SQLException + * @throws IOException + */ + private ArrayList dbMessageCount() throws SQLException, IOException { + java.sql.Connection conn = ((JDBCPersistenceAdapter) broker.getPersistenceAdapter()).getDataSource().getConnection(); + PreparedStatement statement = conn.prepareStatement("SELECT MSGID_SEQ FROM ACTIVEMQ_MSGS"); - /** - * query the DB to see what messages are left in the store - * @return - * @throws SQLException - * @throws IOException - */ - private ArrayList dbMessageCount() throws SQLException, IOException { - java.sql.Connection conn = ((JDBCPersistenceAdapter) broker.getPersistenceAdapter()).getDataSource().getConnection(); - PreparedStatement statement = conn.prepareStatement("SELECT MSGID_SEQ FROM ACTIVEMQ_MSGS"); + try { - try{ + ResultSet result = statement.executeQuery(); + ArrayList dbSeq = new ArrayList(); - ResultSet result = statement.executeQuery(); - ArrayList dbSeq = new ArrayList(); + while (result.next()) { + dbSeq.add(result.getLong(1)); + } - while (result.next()){ - dbSeq.add(result.getLong(1)); - } + return dbSeq; - return dbSeq; + } + finally { + statement.close(); + conn.close(); - }finally{ - statement.close(); - conn.close(); + } - } - - } + } /* * Mock classes used for testing */ - public class TestJDBCPersistenceAdapter extends JDBCPersistenceAdapter { - public TransactionContext getTransactionContext() throws IOException { - return testTransactionContext; - } - } + public class TestJDBCPersistenceAdapter extends JDBCPersistenceAdapter { - public class TestTransactionContext extends TransactionContext { + public TransactionContext getTransactionContext() throws IOException { + return testTransactionContext; + } + } - private int count; + public class TestTransactionContext extends TransactionContext { - public TestTransactionContext( - JDBCPersistenceAdapter jdbcPersistenceAdapter) - throws IOException { - super(jdbcPersistenceAdapter); - } + private int count; - public void executeBatch() throws SQLException { - super.executeBatch(); - count++; - LOG.debug("ExecuteBatchOverride: count:" + count, new RuntimeException("executeBatch")); + public TestTransactionContext(JDBCPersistenceAdapter jdbcPersistenceAdapter) throws IOException { + super(jdbcPersistenceAdapter); + } - // throw on second add message - if (count == 16){ - throw new SQLException("TEST SQL EXCEPTION from executeBatch after super.execution: count:" + count); - } - } + public void executeBatch() throws SQLException { + super.executeBatch(); + count++; + LOG.debug("ExecuteBatchOverride: count:" + count, new RuntimeException("executeBatch")); + // throw on second add message + if (count == 16) { + throw new SQLException("TEST SQL EXCEPTION from executeBatch after super.execution: count:" + count); + } + } - - - } + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/VMTransportClosureTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/VMTransportClosureTest.java index 6a96a147a5..577464bf40 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/VMTransportClosureTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/VMTransportClosureTest.java @@ -33,99 +33,98 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class VMTransportClosureTest extends EmbeddedBrokerTestSupport { - private static final Log LOG = LogFactory - .getLog(VMTransportClosureTest.class); - private static final long MAX_TEST_TIME_MILLIS = 300000; // 5min - private static final int NUM_ATTEMPTS = 100000; - public void setUp() throws Exception { - setAutoFail(true); - setMaxTestTime(MAX_TEST_TIME_MILLIS); - super.setUp(); - } + private static final Log LOG = LogFactory.getLog(VMTransportClosureTest.class); + private static final long MAX_TEST_TIME_MILLIS = 300000; // 5min + private static final int NUM_ATTEMPTS = 100000; - /** - * EmbeddedBrokerTestSupport.createBroker() binds the broker to a VM - * transport address, which results in a call to - * VMTransportFactory.doBind(location): - *

    - * - * public TransportServer doBind(URI location) throws IOException { - * return bind(location, false); - *} - * - *

    - * As a result, VMTransportServer.disposeOnDisconnect is false. - * To expose the bug, we need to have VMTransportServer.disposeOnDisconnect - * true, which is the case when the VMTransportServer is not - * already bound when the first connection is made. - */ - @Override - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setPersistent(isPersistent()); - // answer.addConnector(bindAddress); - return answer; - } + public void setUp() throws Exception { + setAutoFail(true); + setMaxTestTime(MAX_TEST_TIME_MILLIS); + super.setUp(); + } - /** - * This test demonstrates how the "disposeOnDisonnect" feature of - * VMTransportServer can incorrectly close all VM connections to the local - * broker. - */ - public void testPrematureClosure() throws Exception { + /** + * EmbeddedBrokerTestSupport.createBroker() binds the broker to a VM + * transport address, which results in a call to + * VMTransportFactory.doBind(location): + *

    + * + * public TransportServer doBind(URI location) throws IOException { + * return bind(location, false); + * } + * + *

    + * As a result, VMTransportServer.disposeOnDisconnect is false. + * To expose the bug, we need to have VMTransportServer.disposeOnDisconnect + * true, which is the case when the VMTransportServer is not + * already bound when the first connection is made. + */ + @Override + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + answer.setPersistent(isPersistent()); + // answer.addConnector(bindAddress); + return answer; + } - // Open a persistent connection to the local broker. The persistent - // connection is maintained through the test and should prevent the - // VMTransportServer from stopping itself when the local transport is - // closed. - ActiveMQConnection persistentConn = (ActiveMQConnection) createConnection(); - persistentConn.start(); - Session session = persistentConn.createSession(true, - Session.SESSION_TRANSACTED); - MessageProducer producer = session.createProducer(destination); + /** + * This test demonstrates how the "disposeOnDisonnect" feature of + * VMTransportServer can incorrectly close all VM connections to the local + * broker. + */ + public void testPrematureClosure() throws Exception { - for (int i = 0; i < NUM_ATTEMPTS; i++) { - LOG.info("Attempt: " + i); + // Open a persistent connection to the local broker. The persistent + // connection is maintained through the test and should prevent the + // VMTransportServer from stopping itself when the local transport is + // closed. + ActiveMQConnection persistentConn = (ActiveMQConnection) createConnection(); + persistentConn.start(); + Session session = persistentConn.createSession(true, Session.SESSION_TRANSACTED); + MessageProducer producer = session.createProducer(destination); - // Open and close a local transport connection. As is done by by - // most users of the transport, ensure that the transport is stopped - // when closed by the peer (via ShutdownInfo). Closing the local - // transport should not affect the persistent connection. - final Transport localTransport = TransportFactory.connect(broker - .getVmConnectorURI()); - localTransport.setTransportListener(new TransportListener() { - public void onCommand(Object command) { - if (command instanceof ShutdownInfo) { - try { - localTransport.stop(); - } catch (Exception ex) { - throw new RuntimeException(ex); - } - } - } + for (int i = 0; i < NUM_ATTEMPTS; i++) { + LOG.info("Attempt: " + i); - public void onException(IOException error) { - // ignore - } + // Open and close a local transport connection. As is done by by + // most users of the transport, ensure that the transport is stopped + // when closed by the peer (via ShutdownInfo). Closing the local + // transport should not affect the persistent connection. + final Transport localTransport = TransportFactory.connect(broker.getVmConnectorURI()); + localTransport.setTransportListener(new TransportListener() { + public void onCommand(Object command) { + if (command instanceof ShutdownInfo) { + try { + localTransport.stop(); + } + catch (Exception ex) { + throw new RuntimeException(ex); + } + } + } - public void transportInterupted() { - // ignore - } + public void onException(IOException error) { + // ignore + } - public void transportResumed() { - // ignore - } - }); + public void transportInterupted() { + // ignore + } - localTransport.start(); - localTransport.stop(); + public void transportResumed() { + // ignore + } + }); - // Ensure that the persistent connection is still usable. - producer.send(session.createMessage()); - session.rollback(); - } + localTransport.start(); + localTransport.stop(); - persistentConn.close(); - } + // Ensure that the persistent connection is still usable. + producer.send(session.createMessage()); + session.rollback(); + } + + persistentConn.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/VerifySteadyEnqueueRate.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/VerifySteadyEnqueueRate.java index 79394531e1..80ab8e14bb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/VerifySteadyEnqueueRate.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/VerifySteadyEnqueueRate.java @@ -17,6 +17,7 @@ package org.apache.activemq.bugs; import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.store.kahadb.KahaDBStore; @@ -34,120 +35,114 @@ import java.util.concurrent.atomic.AtomicLong; public class VerifySteadyEnqueueRate extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(VerifySteadyEnqueueRate.class); + private static final Logger LOG = LoggerFactory.getLogger(VerifySteadyEnqueueRate.class); - private static int max_messages = 1000000; - private final String destinationName = getName() + "_Queue"; - private BrokerService broker; - final boolean useTopic = false; + private static int max_messages = 1000000; + private final String destinationName = getName() + "_Queue"; + private BrokerService broker; + final boolean useTopic = false; - protected static final String payload = new String(new byte[24]); + protected static final String payload = new String(new byte[24]); - @Override - public void setUp() throws Exception { - startBroker(); - } + @Override + public void setUp() throws Exception { + startBroker(); + } - @Override - public void tearDown() throws Exception { - broker.stop(); - } + @Override + public void tearDown() throws Exception { + broker.stop(); + } - @SuppressWarnings("unused") - public void testEnqueueRateCanMeetSLA() throws Exception { - if (true) { - return; - } - doTestEnqueue(false); - } + @SuppressWarnings("unused") + public void testEnqueueRateCanMeetSLA() throws Exception { + if (true) { + return; + } + doTestEnqueue(false); + } - private void doTestEnqueue(final boolean transacted) throws Exception { - final long min = 100; - final AtomicLong total = new AtomicLong(0); - final AtomicLong slaViolations = new AtomicLong(0); - final AtomicLong max = new AtomicLong(0); - final int numThreads = 6; + private void doTestEnqueue(final boolean transacted) throws Exception { + final long min = 100; + final AtomicLong total = new AtomicLong(0); + final AtomicLong slaViolations = new AtomicLong(0); + final AtomicLong max = new AtomicLong(0); + final int numThreads = 6; - Runnable runner = new Runnable() { + Runnable runner = new Runnable() { - @Override - public void run() { - try { - MessageSender producer = new MessageSender(destinationName, - createConnection(), transacted, useTopic); + @Override + public void run() { + try { + MessageSender producer = new MessageSender(destinationName, createConnection(), transacted, useTopic); - for (int i = 0; i < max_messages; i++) { - long startT = System.currentTimeMillis(); - producer.send(payload); - long endT = System.currentTimeMillis(); - long duration = endT - startT; + for (int i = 0; i < max_messages; i++) { + long startT = System.currentTimeMillis(); + producer.send(payload); + long endT = System.currentTimeMillis(); + long duration = endT - startT; - total.incrementAndGet(); + total.incrementAndGet(); - if (duration > max.get()) { - max.set(duration); - } + if (duration > max.get()) { + max.set(duration); + } - if (duration > min) { - slaViolations.incrementAndGet(); - System.err.println("SLA violation @ "+Thread.currentThread().getName() - + " " - + DateFormat.getTimeInstance().format( - new Date(startT)) + " at message " - + i + " send time=" + duration - + " - Total SLA violations: "+slaViolations.get()+"/"+total.get()+" ("+String.format("%.6f", 100.0*slaViolations.get()/total.get())+"%)"); - } - } + if (duration > min) { + slaViolations.incrementAndGet(); + System.err.println("SLA violation @ " + Thread.currentThread().getName() + " " + DateFormat.getTimeInstance().format(new Date(startT)) + " at message " + i + " send time=" + duration + " - Total SLA violations: " + slaViolations.get() + "/" + total.get() + " (" + String.format("%.6f", 100.0 * slaViolations.get() / total.get()) + "%)"); + } + } - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - System.out.println("Max Violation = " + max + " - Total SLA violations: "+slaViolations.get()+"/"+total.get()+" ("+String.format("%.6f", 100.0*slaViolations.get()/total.get())+"%)"); } - }; - ExecutorService executor = Executors.newCachedThreadPool(); + catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + System.out.println("Max Violation = " + max + " - Total SLA violations: " + slaViolations.get() + "/" + total.get() + " (" + String.format("%.6f", 100.0 * slaViolations.get() / total.get()) + "%)"); + } + }; + ExecutorService executor = Executors.newCachedThreadPool(); - for (int i = 0; i < numThreads; i++) { - executor.execute(runner); - } + for (int i = 0; i < numThreads; i++) { + executor.execute(runner); + } - executor.shutdown(); - while(!executor.isTerminated()) { - executor.awaitTermination(10, TimeUnit.SECONDS); - } - } + executor.shutdown(); + while (!executor.isTerminated()) { + executor.awaitTermination(10, TimeUnit.SECONDS); + } + } - private Connection createConnection() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory( - broker.getTransportConnectors().get(0).getConnectUri()); - return factory.createConnection(); - } + private Connection createConnection() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri()); + return factory.createConnection(); + } - private void startBroker() throws Exception { - broker = new BrokerService(); - //broker.setDeleteAllMessagesOnStartup(true); - broker.setPersistent(true); - broker.setUseJmx(true); + private void startBroker() throws Exception { + broker = new BrokerService(); + //broker.setDeleteAllMessagesOnStartup(true); + broker.setPersistent(true); + broker.setUseJmx(true); - KahaDBStore kaha = new KahaDBStore(); - kaha.setDirectory(new File("target/activemq-data/kahadb")); - // The setEnableJournalDiskSyncs(false) setting is a little dangerous right now, as I have not verified - // what happens if the index is updated but a journal update is lost. - // Index is going to be in consistent, but can it be repaired? - kaha.setEnableJournalDiskSyncs(false); - // Using a bigger journal file size makes he take fewer spikes as it is not switching files as often. - kaha.setJournalMaxFileLength(1024*1024*100); + KahaDBStore kaha = new KahaDBStore(); + kaha.setDirectory(new File("target/activemq-data/kahadb")); + // The setEnableJournalDiskSyncs(false) setting is a little dangerous right now, as I have not verified + // what happens if the index is updated but a journal update is lost. + // Index is going to be in consistent, but can it be repaired? + kaha.setEnableJournalDiskSyncs(false); + // Using a bigger journal file size makes he take fewer spikes as it is not switching files as often. + kaha.setJournalMaxFileLength(1024 * 1024 * 100); - // small batch means more frequent and smaller writes - kaha.setIndexWriteBatchSize(100); - // do the index write in a separate thread - kaha.setEnableIndexWriteAsync(true); + // small batch means more frequent and smaller writes + kaha.setIndexWriteBatchSize(100); + // do the index write in a separate thread + kaha.setEnableIndexWriteAsync(true); - broker.setPersistenceAdapter(kaha); + broker.setPersistenceAdapter(kaha); - broker.addConnector("tcp://localhost:0").setName("Default"); - broker.start(); - LOG.info("Starting broker.."); - } + broker.addConnector("tcp://localhost:0").setName("Default"); + broker.start(); + LOG.info("Starting broker.."); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/amq1095/ActiveMQTestCase.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/amq1095/ActiveMQTestCase.java index 01ecdb1a64..cd0a1c489b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/amq1095/ActiveMQTestCase.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/amq1095/ActiveMQTestCase.java @@ -46,121 +46,113 @@ import org.apache.activemq.command.ActiveMQTopic; * * @author Rainer Klute <rainer.klute@dp-itsolutions.de> - * @since 2007-08-10 * @version $Id: ActiveMQTestCase.java 12 2007-08-14 12:02:02Z rke $ + * @since 2007-08-10 */ -public class ActiveMQTestCase extends TestCase -{ - private Context context; - private BrokerService broker; - protected Connection connection; - protected Destination destination; - private final List consumersToEmpty = new LinkedList(); - protected final long RECEIVE_TIMEOUT = 500; +public class ActiveMQTestCase extends TestCase { + private Context context; + private BrokerService broker; + protected Connection connection; + protected Destination destination; + private final List consumersToEmpty = new LinkedList(); + protected final long RECEIVE_TIMEOUT = 500; - /**

    Constructor

    */ - public ActiveMQTestCase() - {} + /** + *

    Constructor

    + */ + public ActiveMQTestCase() { + } - /**

    Constructor

    - * @param name the test case's name - */ - public ActiveMQTestCase(final String name) - { - super(name); - } + /** + *

    Constructor

    + * + * @param name the test case's name + */ + public ActiveMQTestCase(final String name) { + super(name); + } - /** - *

    Sets up the JUnit testing environment. - */ - @Override - protected void setUp() - { - URI uri; - try - { + /** + *

    Sets up the JUnit testing environment. + */ + @Override + protected void setUp() { + URI uri; + try { /* Copy all system properties starting with "java.naming." to the initial context. */ - final Properties systemProperties = System.getProperties(); - final Properties jndiProperties = new Properties(); - for (final Iterator i = systemProperties.keySet().iterator(); i.hasNext();) - { - final String key = (String) i.next(); - if (key.startsWith("java.naming.") || key.startsWith("topic.") || - key.startsWith("queue.")) - { - final String value = (String) systemProperties.get(key); - jndiProperties.put(key, value); - } + final Properties systemProperties = System.getProperties(); + final Properties jndiProperties = new Properties(); + for (final Iterator i = systemProperties.keySet().iterator(); i.hasNext(); ) { + final String key = (String) i.next(); + if (key.startsWith("java.naming.") || key.startsWith("topic.") || + key.startsWith("queue.")) { + final String value = (String) systemProperties.get(key); + jndiProperties.put(key, value); } - context = new InitialContext(jndiProperties); - uri = new URI("xbean:org/apache/activemq/bugs/amq1095/activemq.xml"); - broker = BrokerFactory.createBroker(uri); - broker.start(); - } - catch (Exception ex) - { - throw new RuntimeException(ex); - } + } + context = new InitialContext(jndiProperties); + uri = new URI("xbean:org/apache/activemq/bugs/amq1095/activemq.xml"); + broker = BrokerFactory.createBroker(uri); + broker.start(); + } + catch (Exception ex) { + throw new RuntimeException(ex); + } - final ConnectionFactory connectionFactory; - try - { + final ConnectionFactory connectionFactory; + try { /* Lookup the connection factory. */ - connectionFactory = (ConnectionFactory) context.lookup("TopicConnectionFactory"); + connectionFactory = (ConnectionFactory) context.lookup("TopicConnectionFactory"); - destination = new ActiveMQTopic("TestTopic"); + destination = new ActiveMQTopic("TestTopic"); /* Create a connection: */ - connection = connectionFactory.createConnection(); - connection.setClientID("sampleClientID"); - } - catch (JMSException ex1) - { - ex1.printStackTrace(); - fail(ex1.toString()); - } - catch (NamingException ex2) { - ex2.printStackTrace(); - fail(ex2.toString()); - } - catch (Throwable ex3) { - ex3.printStackTrace(); - fail(ex3.toString()); - } - } + connection = connectionFactory.createConnection(); + connection.setClientID("sampleClientID"); + } + catch (JMSException ex1) { + ex1.printStackTrace(); + fail(ex1.toString()); + } + catch (NamingException ex2) { + ex2.printStackTrace(); + fail(ex2.toString()); + } + catch (Throwable ex3) { + ex3.printStackTrace(); + fail(ex3.toString()); + } + } + /** + *

    + * Tear down the testing environment by receiving any messages that might be + * left in the topic after a failure and shutting down the broker properly. + * This is quite important for subsequent test cases that assume the topic + * to be empty. + *

    + */ + @Override + protected void tearDown() throws Exception { + TextMessage msg; + try { + for (final Iterator i = consumersToEmpty.iterator(); i.hasNext(); ) { + final MessageConsumer consumer = i.next(); + if (consumer != null) + do + msg = (TextMessage) consumer.receive(RECEIVE_TIMEOUT); while (msg != null); + } + } + catch (Exception e) { + } + if (connection != null) { + connection.stop(); + } + broker.stop(); + } - /** - *

    - * Tear down the testing environment by receiving any messages that might be - * left in the topic after a failure and shutting down the broker properly. - * This is quite important for subsequent test cases that assume the topic - * to be empty. - *

    - */ - @Override - protected void tearDown() throws Exception { - TextMessage msg; - try { - for (final Iterator i = consumersToEmpty.iterator(); i.hasNext();) - { - final MessageConsumer consumer = i.next(); - if (consumer != null) - do - msg = (TextMessage) consumer.receive(RECEIVE_TIMEOUT); - while (msg != null); - } - } catch (Exception e) { - } - if (connection != null) { - connection.stop(); - } - broker.stop(); - } - - protected void registerToBeEmptiedOnShutdown(final MessageConsumer consumer) - { - consumersToEmpty.add(consumer); - } + protected void registerToBeEmptiedOnShutdown(final MessageConsumer consumer) { + consumersToEmpty.add(consumer); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/amq1095/MessageSelectorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/amq1095/MessageSelectorTest.java index e9aa3cab02..49b704b361 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/amq1095/MessageSelectorTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/amq1095/MessageSelectorTest.java @@ -50,178 +50,169 @@ import javax.jms.Topic; * * @author Rainer Klute <rainer.klute@dp-itsolutions.de> - * @since 2007-08-09 * @version $Id: MessageSelectorTest.java 12 2007-08-14 12:02:02Z rke $ + * @since 2007-08-09 */ public class MessageSelectorTest extends ActiveMQTestCase { - private MessageConsumer consumer1; - private MessageConsumer consumer2; + private MessageConsumer consumer1; + private MessageConsumer consumer2; - /**

    Constructor

    */ - public MessageSelectorTest() - {} + /** + *

    Constructor

    + */ + public MessageSelectorTest() { + } - /**

    Constructor

    - * @param name the test case's name - */ - public MessageSelectorTest(final String name) - { - super(name); - } + /** + *

    Constructor

    + * + * @param name the test case's name + */ + public MessageSelectorTest(final String name) { + super(name); + } - /** - *

    - * Tests whether message selectors work for durable subscribers. - *

    - */ - public void testMessageSelectorForDurableSubscribersRunA() - { - runMessageSelectorTest(true); - } + /** + *

    + * Tests whether message selectors work for durable subscribers. + *

    + */ + public void testMessageSelectorForDurableSubscribersRunA() { + runMessageSelectorTest(true); + } - /** - *

    - * Tests whether message selectors work for durable subscribers. - *

    - */ - public void testMessageSelectorForDurableSubscribersRunB() - { - runMessageSelectorTest(true); - } + /** + *

    + * Tests whether message selectors work for durable subscribers. + *

    + */ + public void testMessageSelectorForDurableSubscribersRunB() { + runMessageSelectorTest(true); + } - /** - *

    - * Tests whether message selectors work for non-durable subscribers. - *

    - */ - public void testMessageSelectorForNonDurableSubscribers() - { - runMessageSelectorTest(false); - } + /** + *

    + * Tests whether message selectors work for non-durable subscribers. + *

    + */ + public void testMessageSelectorForNonDurableSubscribers() { + runMessageSelectorTest(false); + } - /** - *

    - * Tests whether message selectors work. This is done by sending two - * messages to a topic. Both have an int property with different values. Two - * subscribers use message selectors to receive the messages. Each one - * should receive exactly one of the messages. - *

    - */ - private void runMessageSelectorTest(final boolean isDurableSubscriber) - { - try - { - final String PROPERTY_CONSUMER = "consumer"; - final String CONSUMER_1 = "Consumer 1"; - final String CONSUMER_2 = "Consumer 2"; - final String MESSAGE_1 = "Message to " + CONSUMER_1; - final String MESSAGE_2 = "Message to " + CONSUMER_2; + /** + *

    + * Tests whether message selectors work. This is done by sending two + * messages to a topic. Both have an int property with different values. Two + * subscribers use message selectors to receive the messages. Each one + * should receive exactly one of the messages. + *

    + */ + private void runMessageSelectorTest(final boolean isDurableSubscriber) { + try { + final String PROPERTY_CONSUMER = "consumer"; + final String CONSUMER_1 = "Consumer 1"; + final String CONSUMER_2 = "Consumer 2"; + final String MESSAGE_1 = "Message to " + CONSUMER_1; + final String MESSAGE_2 = "Message to " + CONSUMER_2; - assertNotNull(connection); - assertNotNull(destination); + assertNotNull(connection); + assertNotNull(destination); - final Session producingSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageProducer producer = producingSession.createProducer(destination); + final Session producingSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final MessageProducer producer = producingSession.createProducer(destination); - final Session consumingSession1 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final Session consumingSession2 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final Session consumingSession1 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final Session consumingSession2 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - if (isDurableSubscriber) - { - consumer1 = consumingSession1.createDurableSubscriber - ((Topic) destination, CONSUMER_1, PROPERTY_CONSUMER + " = 1", false); - consumer2 = consumingSession2.createDurableSubscriber - ((Topic) destination, CONSUMER_2, PROPERTY_CONSUMER + " = 2", false); - } - else - { - consumer1 = consumingSession1.createConsumer(destination, PROPERTY_CONSUMER + " = 1"); - consumer2 = consumingSession2.createConsumer(destination, PROPERTY_CONSUMER + " = 2"); - } - registerToBeEmptiedOnShutdown(consumer1); - registerToBeEmptiedOnShutdown(consumer2); + if (isDurableSubscriber) { + consumer1 = consumingSession1.createDurableSubscriber((Topic) destination, CONSUMER_1, PROPERTY_CONSUMER + " = 1", false); + consumer2 = consumingSession2.createDurableSubscriber((Topic) destination, CONSUMER_2, PROPERTY_CONSUMER + " = 2", false); + } + else { + consumer1 = consumingSession1.createConsumer(destination, PROPERTY_CONSUMER + " = 1"); + consumer2 = consumingSession2.createConsumer(destination, PROPERTY_CONSUMER + " = 2"); + } + registerToBeEmptiedOnShutdown(consumer1); + registerToBeEmptiedOnShutdown(consumer2); - connection.start(); + connection.start(); - TextMessage msg1; - TextMessage msg2; - int propertyValue; - String contents; + TextMessage msg1; + TextMessage msg2; + int propertyValue; + String contents; /* Try to receive any messages from the consumers. There shouldn't be any yet. */ - msg1 = (TextMessage) consumer1.receive(RECEIVE_TIMEOUT); - if (msg1 != null) + msg1 = (TextMessage) consumer1.receive(RECEIVE_TIMEOUT); + if (msg1 != null) { + final StringBuffer msg = new StringBuffer("The consumer read a message that was left over from a former ActiveMQ broker run."); + propertyValue = msg1.getIntProperty(PROPERTY_CONSUMER); + contents = msg1.getText(); + if (propertyValue != 1) // Is the property value as expected? { - final StringBuffer msg = new StringBuffer("The consumer read a message that was left over from a former ActiveMQ broker run."); - propertyValue = msg1.getIntProperty(PROPERTY_CONSUMER); - contents = msg1.getText(); - if (propertyValue != 1) // Is the property value as expected? - { - msg.append(" That message does not match the consumer's message selector."); - fail(msg.toString()); - } - assertEquals(1, propertyValue); - assertEquals(MESSAGE_1, contents); + msg.append(" That message does not match the consumer's message selector."); + fail(msg.toString()); } - msg2 = (TextMessage) consumer2.receive(RECEIVE_TIMEOUT); - if (msg2 != null) + assertEquals(1, propertyValue); + assertEquals(MESSAGE_1, contents); + } + msg2 = (TextMessage) consumer2.receive(RECEIVE_TIMEOUT); + if (msg2 != null) { + final StringBuffer msg = new StringBuffer("The consumer read a message that was left over from a former ActiveMQ broker run."); + propertyValue = msg2.getIntProperty(PROPERTY_CONSUMER); + contents = msg2.getText(); + if (propertyValue != 2) // Is the property value as expected? { - final StringBuffer msg = new StringBuffer("The consumer read a message that was left over from a former ActiveMQ broker run."); - propertyValue = msg2.getIntProperty(PROPERTY_CONSUMER); - contents = msg2.getText(); - if (propertyValue != 2) // Is the property value as expected? - { - msg.append(" That message does not match the consumer's message selector."); - fail(msg.toString()); - } - assertEquals(2, propertyValue); - assertEquals(MESSAGE_2, contents); + msg.append(" That message does not match the consumer's message selector."); + fail(msg.toString()); } + assertEquals(2, propertyValue); + assertEquals(MESSAGE_2, contents); + } /* Send two messages. Each is targeted at one of the consumers. */ - TextMessage msg; - msg = producingSession.createTextMessage(); - msg.setText(MESSAGE_1); - msg.setIntProperty(PROPERTY_CONSUMER, 1); - producer.send(msg); + TextMessage msg; + msg = producingSession.createTextMessage(); + msg.setText(MESSAGE_1); + msg.setIntProperty(PROPERTY_CONSUMER, 1); + producer.send(msg); - msg = producingSession.createTextMessage(); - msg.setText(MESSAGE_2); - msg.setIntProperty(PROPERTY_CONSUMER, 2); - producer.send(msg); + msg = producingSession.createTextMessage(); + msg.setText(MESSAGE_2); + msg.setIntProperty(PROPERTY_CONSUMER, 2); + producer.send(msg); /* Receive the messages that have just been sent. */ /* Use consumer 1 to receive one of the messages. The receive() * method is called twice to make sure there is nothing else in * stock for this consumer. */ - msg1 = (TextMessage) consumer1.receive(RECEIVE_TIMEOUT); - assertNotNull(msg1); - propertyValue = msg1.getIntProperty(PROPERTY_CONSUMER); - contents = msg1.getText(); - assertEquals(1, propertyValue); - assertEquals(MESSAGE_1, contents); - msg1 = (TextMessage) consumer1.receive(RECEIVE_TIMEOUT); - assertNull(msg1); + msg1 = (TextMessage) consumer1.receive(RECEIVE_TIMEOUT); + assertNotNull(msg1); + propertyValue = msg1.getIntProperty(PROPERTY_CONSUMER); + contents = msg1.getText(); + assertEquals(1, propertyValue); + assertEquals(MESSAGE_1, contents); + msg1 = (TextMessage) consumer1.receive(RECEIVE_TIMEOUT); + assertNull(msg1); /* Use consumer 2 to receive the other message. The receive() * method is called twice to make sure there is nothing else in * stock for this consumer. */ - msg2 = (TextMessage) consumer2.receive(RECEIVE_TIMEOUT); - assertNotNull(msg2); - propertyValue = msg2.getIntProperty(PROPERTY_CONSUMER); - contents = msg2.getText(); - assertEquals(2, propertyValue); - assertEquals(MESSAGE_2, contents); - msg2 = (TextMessage) consumer2.receive(RECEIVE_TIMEOUT); - assertNull(msg2); - } - catch (JMSException ex) - { - ex.printStackTrace(); - fail(); - } - } + msg2 = (TextMessage) consumer2.receive(RECEIVE_TIMEOUT); + assertNotNull(msg2); + propertyValue = msg2.getIntProperty(PROPERTY_CONSUMER); + contents = msg2.getText(); + assertEquals(2, propertyValue); + assertEquals(MESSAGE_2, contents); + msg2 = (TextMessage) consumer2.receive(RECEIVE_TIMEOUT); + assertNull(msg2); + } + catch (JMSException ex) { + ex.printStackTrace(); + fail(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/amq1974/TryJmsClient.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/amq1974/TryJmsClient.java index 1f25109d5c..cdda13a4dc 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/amq1974/TryJmsClient.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/amq1974/TryJmsClient.java @@ -27,97 +27,98 @@ import java.io.File; import java.net.URISyntaxException; import java.util.concurrent.CountDownLatch; -public class TryJmsClient -{ - private final BrokerService broker = new BrokerService(); +public class TryJmsClient { - public static void main(String[] args) throws Exception { - new TryJmsClient().start(); - } + private final BrokerService broker = new BrokerService(); - private void start() throws Exception { + public static void main(String[] args) throws Exception { + new TryJmsClient().start(); + } - broker.setUseJmx(false); - broker.setPersistent(true); - broker.setBrokerName("TestBroker"); - broker.getSystemUsage().setSendFailIfNoSpace(true); + private void start() throws Exception { - broker.getSystemUsage().getMemoryUsage().setLimit(10 * 1024 * 1024); + broker.setUseJmx(false); + broker.setPersistent(true); + broker.setBrokerName("TestBroker"); + broker.getSystemUsage().setSendFailIfNoSpace(true); - LevelDBStore persist = new LevelDBStore(); - persist.setDirectory(new File("/tmp/broker2")); - persist.setLogSize(20 * 1024 * 1024); - broker.setPersistenceAdapter(persist); + broker.getSystemUsage().getMemoryUsage().setLimit(10 * 1024 * 1024); - String brokerUrl = "tcp://localhost:4501"; - broker.addConnector(brokerUrl); + LevelDBStore persist = new LevelDBStore(); + persist.setDirectory(new File("/tmp/broker2")); + persist.setLogSize(20 * 1024 * 1024); + broker.setPersistenceAdapter(persist); - broker.start(); + String brokerUrl = "tcp://localhost:4501"; + broker.addConnector(brokerUrl); - addNetworkBroker(); + broker.start(); - startUsageMonitor(broker); + addNetworkBroker(); - startMessageSend(); + startUsageMonitor(broker); - new CountDownLatch(1).await(); - } + startMessageSend(); - private void startUsageMonitor(final BrokerService brokerService) { - new Thread(new Runnable() { - public void run() { - while (true) { - try { - Thread.sleep(10000); - } catch (InterruptedException e) { - e.printStackTrace(); - } + new CountDownLatch(1).await(); + } - System.out.println("ActiveMQ memeory " + brokerService.getSystemUsage().getMemoryUsage().getPercentUsage() - + " " + brokerService.getSystemUsage().getMemoryUsage().getUsage()); - System.out.println("ActiveMQ message store " + brokerService.getSystemUsage().getStoreUsage().getPercentUsage()); - System.out.println("ActiveMQ temp space " + brokerService.getSystemUsage().getTempUsage().getPercentUsage()); - } + private void startUsageMonitor(final BrokerService brokerService) { + new Thread(new Runnable() { + public void run() { + while (true) { + try { + Thread.sleep(10000); + } + catch (InterruptedException e) { + e.printStackTrace(); + } + + System.out.println("ActiveMQ memeory " + brokerService.getSystemUsage().getMemoryUsage().getPercentUsage() + " " + brokerService.getSystemUsage().getMemoryUsage().getUsage()); + System.out.println("ActiveMQ message store " + brokerService.getSystemUsage().getStoreUsage().getPercentUsage()); + System.out.println("ActiveMQ temp space " + brokerService.getSystemUsage().getTempUsage().getPercentUsage()); } - }).start(); - } + } + }).start(); + } - private void addNetworkBroker() throws Exception { + private void addNetworkBroker() throws Exception { - DiscoveryNetworkConnector dnc = new DiscoveryNetworkConnector(); - dnc.setNetworkTTL(1); - dnc.setBrokerName("TestBroker"); - dnc.setName("Broker1Connector"); - dnc.setDynamicOnly(true); + DiscoveryNetworkConnector dnc = new DiscoveryNetworkConnector(); + dnc.setNetworkTTL(1); + dnc.setBrokerName("TestBroker"); + dnc.setName("Broker1Connector"); + dnc.setDynamicOnly(true); - SimpleDiscoveryAgent discoveryAgent = new SimpleDiscoveryAgent(); - String remoteUrl = "tcp://localhost:4500"; - discoveryAgent.setServices(remoteUrl); + SimpleDiscoveryAgent discoveryAgent = new SimpleDiscoveryAgent(); + String remoteUrl = "tcp://localhost:4500"; + discoveryAgent.setServices(remoteUrl); - dnc.setDiscoveryAgent(discoveryAgent); + dnc.setDiscoveryAgent(discoveryAgent); - broker.addNetworkConnector(dnc); - dnc.start(); - } + broker.addNetworkConnector(dnc); + dnc.start(); + } - private void startMessageSend() { - new Thread(new MessageSend()).start(); - } + private void startMessageSend() { + new Thread(new MessageSend()).start(); + } - private class MessageSend implements Runnable { - public void run() { - try { - String url = "vm://TestBroker"; - ActiveMQConnection connection = ActiveMQConnection.makeConnection(url); - connection.setDispatchAsync(true); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination dest = session.createTopic("TestDestination"); + private class MessageSend implements Runnable { - MessageProducer producer = session.createProducer(dest); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); + public void run() { + try { + String url = "vm://TestBroker"; + ActiveMQConnection connection = ActiveMQConnection.makeConnection(url); + connection.setDispatchAsync(true); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination dest = session.createTopic("TestDestination"); - for(int i = 0; i < 99999999; i++) { - TextMessage message = session.createTextMessage("test" + i); + MessageProducer producer = session.createProducer(dest); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + + for (int i = 0; i < 99999999; i++) { + TextMessage message = session.createTextMessage("test" + i); /* try { @@ -127,23 +128,26 @@ public class TryJmsClient } */ - try { - producer.send(message); - } catch (Exception e ) { - e.printStackTrace(); - System.out.println("TOTAL number of messages sent " + i); - break; - } + try { + producer.send(message); + } + catch (Exception e) { + e.printStackTrace(); + System.out.println("TOTAL number of messages sent " + i); + break; + } - if (i % 1000 == 0) { - System.out.println("sent message " + message.getJMSMessageID()); - } - } - } catch (JMSException e) { - e.printStackTrace(); - } catch (URISyntaxException e) { - e.printStackTrace(); + if (i % 1000 == 0) { + System.out.println("sent message " + message.getJMSMessageID()); + } } - } - } + } + catch (JMSException e) { + e.printStackTrace(); + } + catch (URISyntaxException e) { + e.printStackTrace(); + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/amq1974/TryJmsManager.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/amq1974/TryJmsManager.java index c8eb7b34d8..fe2ceaa3b2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/amq1974/TryJmsManager.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/amq1974/TryJmsManager.java @@ -29,95 +29,95 @@ import java.util.concurrent.CountDownLatch; public class TryJmsManager { - private final BrokerService broker = new BrokerService(); + private final BrokerService broker = new BrokerService(); - public static void main(String[] args) throws Exception { - new TryJmsManager().start(); - } + public static void main(String[] args) throws Exception { + new TryJmsManager().start(); + } - private void start() throws Exception { + private void start() throws Exception { - broker.setUseJmx(false); - broker.setPersistent(true); - broker.setBrokerName("TestBroker"); - broker.getSystemUsage().setSendFailIfNoSpace(true); + broker.setUseJmx(false); + broker.setPersistent(true); + broker.setBrokerName("TestBroker"); + broker.getSystemUsage().setSendFailIfNoSpace(true); - broker.getSystemUsage().getMemoryUsage().setLimit(10 * 1024 * 1024); + broker.getSystemUsage().getMemoryUsage().setLimit(10 * 1024 * 1024); - LevelDBStore persist = new LevelDBStore(); - persist.setDirectory(new File("/tmp/broker1")); - persist.setLogSize(20 * 1024 * 1024); - broker.setPersistenceAdapter(persist); + LevelDBStore persist = new LevelDBStore(); + persist.setDirectory(new File("/tmp/broker1")); + persist.setLogSize(20 * 1024 * 1024); + broker.setPersistenceAdapter(persist); - String brokerUrl = "tcp://localhost:4500"; - broker.addConnector(brokerUrl); + String brokerUrl = "tcp://localhost:4500"; + broker.addConnector(brokerUrl); - broker.start(); + broker.start(); - addNetworkBroker(); + addNetworkBroker(); - startUsageMonitor(broker); + startUsageMonitor(broker); - startMessageConsumer(); + startMessageConsumer(); - new CountDownLatch(1).await(); - } + new CountDownLatch(1).await(); + } - private void startUsageMonitor(final BrokerService brokerService) { - new Thread(new Runnable() { - public void run() { - while (true) { - try { - Thread.sleep(10000); - } catch (InterruptedException e) { - e.printStackTrace(); - } + private void startUsageMonitor(final BrokerService brokerService) { + new Thread(new Runnable() { + public void run() { + while (true) { + try { + Thread.sleep(10000); + } + catch (InterruptedException e) { + e.printStackTrace(); + } - System.out.println("ActiveMQ memeory " + brokerService.getSystemUsage().getMemoryUsage().getPercentUsage() - + " " + brokerService.getSystemUsage().getMemoryUsage().getUsage()); - System.out.println("ActiveMQ message store " + brokerService.getSystemUsage().getStoreUsage().getPercentUsage()); - System.out.println("ActiveMQ temp space " + brokerService.getSystemUsage().getTempUsage().getPercentUsage()); - } + System.out.println("ActiveMQ memeory " + brokerService.getSystemUsage().getMemoryUsage().getPercentUsage() + " " + brokerService.getSystemUsage().getMemoryUsage().getUsage()); + System.out.println("ActiveMQ message store " + brokerService.getSystemUsage().getStoreUsage().getPercentUsage()); + System.out.println("ActiveMQ temp space " + brokerService.getSystemUsage().getTempUsage().getPercentUsage()); } - }).start(); - } + } + }).start(); + } - private void addNetworkBroker() throws Exception { - DiscoveryNetworkConnector dnc = new DiscoveryNetworkConnector(); - dnc.setNetworkTTL(1); - dnc.setBrokerName("TestBroker"); - dnc.setName("Broker1Connector"); - dnc.setDynamicOnly(true); + private void addNetworkBroker() throws Exception { + DiscoveryNetworkConnector dnc = new DiscoveryNetworkConnector(); + dnc.setNetworkTTL(1); + dnc.setBrokerName("TestBroker"); + dnc.setName("Broker1Connector"); + dnc.setDynamicOnly(true); - SimpleDiscoveryAgent discoveryAgent = new SimpleDiscoveryAgent(); - String remoteUrl = "tcp://localhost:4501"; - discoveryAgent.setServices(remoteUrl); + SimpleDiscoveryAgent discoveryAgent = new SimpleDiscoveryAgent(); + String remoteUrl = "tcp://localhost:4501"; + discoveryAgent.setServices(remoteUrl); - dnc.setDiscoveryAgent(discoveryAgent); + dnc.setDiscoveryAgent(discoveryAgent); - broker.addNetworkConnector(dnc); - dnc.start(); - } + broker.addNetworkConnector(dnc); + dnc.start(); + } - private void startMessageConsumer() throws JMSException, URISyntaxException { - String url = "vm://TestBroker"; - ActiveMQConnection connection = ActiveMQConnection.makeConnection(url); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination dest = session.createTopic("TestDestination"); + private void startMessageConsumer() throws JMSException, URISyntaxException { + String url = "vm://TestBroker"; + ActiveMQConnection connection = ActiveMQConnection.makeConnection(url); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination dest = session.createTopic("TestDestination"); - MessageConsumer consumer = session.createConsumer(dest); - consumer.setMessageListener(new MessageListener() { + MessageConsumer consumer = session.createConsumer(dest); + consumer.setMessageListener(new MessageListener() { - public void onMessage(Message message) { - try { - System.out.println("got message " + message.getJMSMessageID()); - } catch (JMSException e) { - e.printStackTrace(); - } - } - } - ); + public void onMessage(Message message) { + try { + System.out.println("got message " + message.getJMSMessageID()); + } + catch (JMSException e) { + e.printStackTrace(); + } + } + }); - connection.start(); - } + connection.start(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/embedded/EmbeddedActiveMQ.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/embedded/EmbeddedActiveMQ.java index 3b4f2fd50f..385564e9c0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/embedded/EmbeddedActiveMQ.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/embedded/EmbeddedActiveMQ.java @@ -24,91 +24,81 @@ import javax.jms.Destination; import javax.jms.Message; import javax.jms.MessageProducer; import javax.jms.Session; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.log4j.Logger; -public class EmbeddedActiveMQ -{ - - private static Logger logger = Logger.getLogger(EmbeddedActiveMQ.class); - - public static void main(String[] args) - { - - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - BrokerService brokerService = null; - Connection connection = null; - - logger.info("Start..."); - try - { - brokerService = new BrokerService(); - brokerService.setBrokerName("TestMQ"); - brokerService.setUseJmx(true); - logger.info("Broker '" + brokerService.getBrokerName() + "' is starting........"); - brokerService.start(); - ConnectionFactory fac = new ActiveMQConnectionFactory("vm://TestMQ"); - connection = fac.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination queue = session.createQueue("TEST.QUEUE"); - MessageProducer producer = session.createProducer(queue); - for (int i = 0; i < 1000;i++) { - Message msg = session.createTextMessage("test"+i); - producer.send(msg); - } - logger.info(ThreadExplorer.show("Active threads after start:")); - System.out.println("Press return to stop........"); - String key = br.readLine(); - } - - catch (Exception e) - { - e.printStackTrace(); - } - finally - { - try - { - br.close(); - logger.info("Broker '" + brokerService.getBrokerName() + "' is stopping........"); - connection.close(); - brokerService.stop(); - sleep(8); - logger.info(ThreadExplorer.show("Active threads after stop:")); - - } - catch (Exception e) - { - e.printStackTrace(); - } - } - - logger.info("Waiting for list theads is greater then 1 ..."); - int numTh = ThreadExplorer.active(); - - while (numTh > 2) - { - sleep(3); - numTh = ThreadExplorer.active(); - logger.info(ThreadExplorer.show("Still active threads:")); - } - - System.out.println("Stop..."); - } - - private static void sleep(int second) - { - try - { - logger.info("Waiting for " + second + "s..."); - Thread.sleep(second * 1000L); - } - catch (InterruptedException e) - { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - +public class EmbeddedActiveMQ { + + private static Logger logger = Logger.getLogger(EmbeddedActiveMQ.class); + + public static void main(String[] args) { + + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + BrokerService brokerService = null; + Connection connection = null; + + logger.info("Start..."); + try { + brokerService = new BrokerService(); + brokerService.setBrokerName("TestMQ"); + brokerService.setUseJmx(true); + logger.info("Broker '" + brokerService.getBrokerName() + "' is starting........"); + brokerService.start(); + ConnectionFactory fac = new ActiveMQConnectionFactory("vm://TestMQ"); + connection = fac.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination queue = session.createQueue("TEST.QUEUE"); + MessageProducer producer = session.createProducer(queue); + for (int i = 0; i < 1000; i++) { + Message msg = session.createTextMessage("test" + i); + producer.send(msg); + } + logger.info(ThreadExplorer.show("Active threads after start:")); + System.out.println("Press return to stop........"); + String key = br.readLine(); + } + + catch (Exception e) { + e.printStackTrace(); + } + finally { + try { + br.close(); + logger.info("Broker '" + brokerService.getBrokerName() + "' is stopping........"); + connection.close(); + brokerService.stop(); + sleep(8); + logger.info(ThreadExplorer.show("Active threads after stop:")); + + } + catch (Exception e) { + e.printStackTrace(); + } + } + + logger.info("Waiting for list theads is greater then 1 ..."); + int numTh = ThreadExplorer.active(); + + while (numTh > 2) { + sleep(3); + numTh = ThreadExplorer.active(); + logger.info(ThreadExplorer.show("Still active threads:")); + } + + System.out.println("Stop..."); + } + + private static void sleep(int second) { + try { + logger.info("Waiting for " + second + "s..."); + Thread.sleep(second * 1000L); + } + catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/embedded/ThreadExplorer.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/embedded/ThreadExplorer.java index eab5fd148f..4f500c4260 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/embedded/ThreadExplorer.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/bugs/embedded/ThreadExplorer.java @@ -18,151 +18,131 @@ package org.apache.activemq.bugs.embedded; import java.util.regex.Matcher; import java.util.regex.Pattern; + import org.apache.log4j.Logger; -public class ThreadExplorer -{ - static Logger logger = Logger.getLogger(ThreadExplorer.class); +public class ThreadExplorer { - public static Thread[] listThreads() - { + static Logger logger = Logger.getLogger(ThreadExplorer.class); - int nThreads = Thread.activeCount(); - Thread ret[] = new Thread[nThreads]; + public static Thread[] listThreads() { - Thread.enumerate(ret); + int nThreads = Thread.activeCount(); + Thread ret[] = new Thread[nThreads]; - return ret; + Thread.enumerate(ret); - } + return ret; - /** - * Helper function to access a thread per name (ignoring case) - * - * @param name - * @return - */ - public static Thread fetchThread(String name) - { - Thread[] threadArray = listThreads(); - // for (Thread t : threadArray) - for (int i = 0; i < threadArray.length; i++) - { - Thread t = threadArray[i]; - if (t.getName().equalsIgnoreCase(name)) - return t; - } - return null; - } + } - /** - * Allow for killing threads - * - * @param threadName - * @param isStarredExp - * (regular expressions with *) - */ - @SuppressWarnings("deprecation") - public static int kill(String threadName, boolean isStarredExp, String motivation) - { - String me = "ThreadExplorer.kill: "; - if (logger.isDebugEnabled()) - { - logger.debug("Entering " + me + " with " + threadName + " isStarred: " + isStarredExp); - } - int ret = 0; - Pattern mypattern = null; - if (isStarredExp) - { - String realreg = threadName.toLowerCase().replaceAll("\\*", "\\.\\*"); - mypattern = Pattern.compile(realreg); + /** + * Helper function to access a thread per name (ignoring case) + * + * @param name + * @return + */ + public static Thread fetchThread(String name) { + Thread[] threadArray = listThreads(); + // for (Thread t : threadArray) + for (int i = 0; i < threadArray.length; i++) { + Thread t = threadArray[i]; + if (t.getName().equalsIgnoreCase(name)) + return t; + } + return null; + } - } - Thread[] threads = listThreads(); - for (int i = 0; i < threads.length; i++) - { - Thread thread = threads[i]; - if (thread == null) - continue; - // kill the thread unless it is not current thread - boolean matches = false; + /** + * Allow for killing threads + * + * @param threadName + * @param isStarredExp (regular expressions with *) + */ + @SuppressWarnings("deprecation") + public static int kill(String threadName, boolean isStarredExp, String motivation) { + String me = "ThreadExplorer.kill: "; + if (logger.isDebugEnabled()) { + logger.debug("Entering " + me + " with " + threadName + " isStarred: " + isStarredExp); + } + int ret = 0; + Pattern mypattern = null; + if (isStarredExp) { + String realreg = threadName.toLowerCase().replaceAll("\\*", "\\.\\*"); + mypattern = Pattern.compile(realreg); - if (isStarredExp) - { - Matcher matcher = mypattern.matcher(thread.getName().toLowerCase()); - matches = matcher.matches(); + } + Thread[] threads = listThreads(); + for (int i = 0; i < threads.length; i++) { + Thread thread = threads[i]; + if (thread == null) + continue; + // kill the thread unless it is not current thread + boolean matches = false; + + if (isStarredExp) { + Matcher matcher = mypattern.matcher(thread.getName().toLowerCase()); + matches = matcher.matches(); + } + else { + matches = (thread.getName().equalsIgnoreCase(threadName)); + } + if (matches && (Thread.currentThread() != thread) && !thread.getName().equals("main")) { + if (logger.isInfoEnabled()) + logger.info("Killing thread named [" + thread.getName() + "]"); // , removing its uncaught + // exception handler to + // avoid ThreadDeath + // exception tracing + // "+motivation ); + + ret++; + + // PK leaving uncaught exception handler otherwise master push + // cannot recover from this error + // thread.setUncaughtExceptionHandler(null); + try { + thread.stop(); } - else - { - matches = (thread.getName().equalsIgnoreCase(threadName)); - } - if (matches && (Thread.currentThread() != thread) && !thread.getName().equals("main")) - { - if (logger.isInfoEnabled()) - logger.info("Killing thread named [" + thread.getName() + "]"); // , removing its uncaught - // exception handler to - // avoid ThreadDeath - // exception tracing - // "+motivation ); - - ret++; - - // PK leaving uncaught exception handler otherwise master push - // cannot recover from this error - // thread.setUncaughtExceptionHandler(null); - try - { - thread.stop(); - } - catch (ThreadDeath e) - { - logger.warn("Thread already death.", e); - } - - } - } - return ret; - } - - public static String show(String title) - { - StringBuffer out = new StringBuffer(); - Thread[] threadArray = ThreadExplorer.listThreads(); - - out.append(title + "\n"); - for (int i = 0; i < threadArray.length; i++) - { - Thread thread = threadArray[i]; - - if (thread != null) - { - out.append("* [" + thread.getName() + "] " + (thread.isDaemon() ? "(Daemon)" : "") - + " Group: " + thread.getThreadGroup().getName() + "\n"); - } - else - { - out.append("* ThreadDeath: " + thread + "\n"); + catch (ThreadDeath e) { + logger.warn("Thread already death.", e); } - } - return out.toString(); - } + } + } + return ret; + } - public static int active() - { - int count = 0; - Thread[] threadArray = ThreadExplorer.listThreads(); + public static String show(String title) { + StringBuffer out = new StringBuffer(); + Thread[] threadArray = ThreadExplorer.listThreads(); - for (int i = 0; i < threadArray.length; i++) - { - Thread thread = threadArray[i]; - if (thread != null) - { - count++; - } - } + out.append(title + "\n"); + for (int i = 0; i < threadArray.length; i++) { + Thread thread = threadArray[i]; - return count; - } + if (thread != null) { + out.append("* [" + thread.getName() + "] " + (thread.isDaemon() ? "(Daemon)" : "") + " Group: " + thread.getThreadGroup().getName() + "\n"); + } + else { + out.append("* ThreadDeath: " + thread + "\n"); + } + + } + return out.toString(); + } + + public static int active() { + int count = 0; + Thread[] threadArray = ThreadExplorer.listThreads(); + + for (int i = 0; i < threadArray.length; i++) { + Thread thread = threadArray[i]; + if (thread != null) { + count++; + } + } + + return count; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQBytesMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQBytesMessageTest.java index 0219815688..9d51fea44d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQBytesMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQBytesMessageTest.java @@ -24,465 +24,514 @@ import javax.jms.MessageNotWriteableException; import junit.framework.TestCase; /** - * + * */ public class ActiveMQBytesMessageTest extends TestCase { - public ActiveMQBytesMessageTest(String name) { - super(name); - } + public ActiveMQBytesMessageTest(String name) { + super(name); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(ActiveMQBytesMessageTest.class); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(ActiveMQBytesMessageTest.class); + } - /* - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - } + /* + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + } - /* - * @see TestCase#tearDown() - */ - protected void tearDown() throws Exception { - super.tearDown(); - } + /* + * @see TestCase#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + } - public void testGetDataStructureType() { - ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); - assertEquals(msg.getDataStructureType(), CommandTypes.ACTIVEMQ_BYTES_MESSAGE); - } + public void testGetDataStructureType() { + ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); + assertEquals(msg.getDataStructureType(), CommandTypes.ACTIVEMQ_BYTES_MESSAGE); + } - public void testGetBodyLength() { - ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); - int len = 10; - try { - for (int i = 0; i < len; i++) { - msg.writeLong(5L); - } - } catch (JMSException ex) { - ex.printStackTrace(); - } - try { - msg.reset(); - assertTrue(msg.getBodyLength() == (len * 8)); - } catch (Throwable e) { - e.printStackTrace(); - assertTrue(false); - } - } + public void testGetBodyLength() { + ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); + int len = 10; + try { + for (int i = 0; i < len; i++) { + msg.writeLong(5L); + } + } + catch (JMSException ex) { + ex.printStackTrace(); + } + try { + msg.reset(); + assertTrue(msg.getBodyLength() == (len * 8)); + } + catch (Throwable e) { + e.printStackTrace(); + assertTrue(false); + } + } - public void testReadBoolean() { - ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); - try { - msg.writeBoolean(true); - msg.reset(); - assertTrue(msg.readBoolean()); - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } + public void testReadBoolean() { + ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); + try { + msg.writeBoolean(true); + msg.reset(); + assertTrue(msg.readBoolean()); + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } - public void testReadByte() { - ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); - try { - msg.writeByte((byte) 2); - msg.reset(); - assertTrue(msg.readByte() == 2); - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } + public void testReadByte() { + ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); + try { + msg.writeByte((byte) 2); + msg.reset(); + assertTrue(msg.readByte() == 2); + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } - public void testReadUnsignedByte() { - ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); - try { - msg.writeByte((byte) 2); - msg.reset(); - assertTrue(msg.readUnsignedByte() == 2); - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } + public void testReadUnsignedByte() { + ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); + try { + msg.writeByte((byte) 2); + msg.reset(); + assertTrue(msg.readUnsignedByte() == 2); + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } - public void testReadShort() { - ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); - try { - msg.writeShort((short) 3000); - msg.reset(); - assertTrue(msg.readShort() == 3000); - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } + public void testReadShort() { + ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); + try { + msg.writeShort((short) 3000); + msg.reset(); + assertTrue(msg.readShort() == 3000); + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } - public void testReadUnsignedShort() { - ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); - try { - msg.writeShort((short) 3000); - msg.reset(); - assertTrue(msg.readUnsignedShort() == 3000); - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } + public void testReadUnsignedShort() { + ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); + try { + msg.writeShort((short) 3000); + msg.reset(); + assertTrue(msg.readUnsignedShort() == 3000); + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } - public void testReadChar() { - ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); - try { - msg.writeChar('a'); - msg.reset(); - assertTrue(msg.readChar() == 'a'); - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } + public void testReadChar() { + ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); + try { + msg.writeChar('a'); + msg.reset(); + assertTrue(msg.readChar() == 'a'); + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } - public void testReadInt() { - ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); - try { - msg.writeInt(3000); - msg.reset(); - assertTrue(msg.readInt() == 3000); - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } + public void testReadInt() { + ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); + try { + msg.writeInt(3000); + msg.reset(); + assertTrue(msg.readInt() == 3000); + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } - public void testReadLong() { - ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); - try { - msg.writeLong(3000); - msg.reset(); - assertTrue(msg.readLong() == 3000); - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } + public void testReadLong() { + ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); + try { + msg.writeLong(3000); + msg.reset(); + assertTrue(msg.readLong() == 3000); + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } - public void testReadFloat() { - ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); - try { - msg.writeFloat(3.3f); - msg.reset(); - assertTrue(msg.readFloat() == 3.3f); - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } + public void testReadFloat() { + ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); + try { + msg.writeFloat(3.3f); + msg.reset(); + assertTrue(msg.readFloat() == 3.3f); + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } - public void testReadDouble() { - ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); - try { - msg.writeDouble(3.3d); - msg.reset(); - assertTrue(msg.readDouble() == 3.3d); - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } + public void testReadDouble() { + ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); + try { + msg.writeDouble(3.3d); + msg.reset(); + assertTrue(msg.readDouble() == 3.3d); + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } - public void testReadUTF() { - ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); - try { - String str = "this is a test"; - msg.writeUTF(str); - msg.reset(); - assertTrue(msg.readUTF().equals(str)); - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } + public void testReadUTF() { + ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); + try { + String str = "this is a test"; + msg.writeUTF(str); + msg.reset(); + assertTrue(msg.readUTF().equals(str)); + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } - /* - * Class to test for int readBytes(byte[]) - */ - public void testReadBytesbyteArray() { - ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); - try { - byte[] data = new byte[50]; - for (int i = 0; i < data.length; i++) { - data[i] = (byte) i; - } - msg.writeBytes(data); - msg.reset(); - byte[] test = new byte[data.length]; - msg.readBytes(test); - for (int i = 0; i < test.length; i++) { - assertTrue(test[i] == i); - } - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } + /* + * Class to test for int readBytes(byte[]) + */ + public void testReadBytesbyteArray() { + ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); + try { + byte[] data = new byte[50]; + for (int i = 0; i < data.length; i++) { + data[i] = (byte) i; + } + msg.writeBytes(data); + msg.reset(); + byte[] test = new byte[data.length]; + msg.readBytes(test); + for (int i = 0; i < test.length; i++) { + assertTrue(test[i] == i); + } + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } - public void testWriteObject() throws JMSException { - ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); - try { - msg.writeObject("fred"); - msg.writeObject(Boolean.TRUE); - msg.writeObject(Character.valueOf('q')); - msg.writeObject(Byte.valueOf((byte) 1)); - msg.writeObject(Short.valueOf((short) 3)); - msg.writeObject(Integer.valueOf(3)); - msg.writeObject(Long.valueOf(300L)); - msg.writeObject(new Float(3.3f)); - msg.writeObject(new Double(3.3)); - msg.writeObject(new byte[3]); - } catch (MessageFormatException mfe) { - fail("objectified primitives should be allowed"); - } - try { - msg.writeObject(new Object()); - fail("only objectified primitives are allowed"); - } catch (MessageFormatException mfe) { - } - } + public void testWriteObject() throws JMSException { + ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); + try { + msg.writeObject("fred"); + msg.writeObject(Boolean.TRUE); + msg.writeObject(Character.valueOf('q')); + msg.writeObject(Byte.valueOf((byte) 1)); + msg.writeObject(Short.valueOf((short) 3)); + msg.writeObject(Integer.valueOf(3)); + msg.writeObject(Long.valueOf(300L)); + msg.writeObject(new Float(3.3f)); + msg.writeObject(new Double(3.3)); + msg.writeObject(new byte[3]); + } + catch (MessageFormatException mfe) { + fail("objectified primitives should be allowed"); + } + try { + msg.writeObject(new Object()); + fail("only objectified primitives are allowed"); + } + catch (MessageFormatException mfe) { + } + } + /* new */ + public void testClearBody() throws JMSException { + ActiveMQBytesMessage bytesMessage = new ActiveMQBytesMessage(); + try { + bytesMessage.writeInt(1); + bytesMessage.clearBody(); + assertFalse(bytesMessage.isReadOnlyBody()); + bytesMessage.writeInt(1); + bytesMessage.readInt(); + } + catch (MessageNotReadableException mnwe) { + } + catch (MessageNotWriteableException mnwe) { + assertTrue(false); + } + } - /* new */ - public void testClearBody() throws JMSException { - ActiveMQBytesMessage bytesMessage = new ActiveMQBytesMessage(); - try { - bytesMessage.writeInt(1); - bytesMessage.clearBody(); - assertFalse(bytesMessage.isReadOnlyBody()); - bytesMessage.writeInt(1); - bytesMessage.readInt(); - } catch (MessageNotReadableException mnwe) { - } catch (MessageNotWriteableException mnwe) { - assertTrue(false); - } - } + public void testReset() throws JMSException { + ActiveMQBytesMessage message = new ActiveMQBytesMessage(); + try { + message.writeDouble(24.5); + message.writeLong(311); + } + catch (MessageNotWriteableException mnwe) { + fail("should be writeable"); + } + message.reset(); + try { + assertTrue(message.isReadOnlyBody()); + assertEquals(message.readDouble(), 24.5, 0); + assertEquals(message.readLong(), 311); + } + catch (MessageNotReadableException mnre) { + fail("should be readable"); + } + try { + message.writeInt(33); + fail("should throw exception"); + } + catch (MessageNotWriteableException mnwe) { + } + } - public void testReset() throws JMSException { - ActiveMQBytesMessage message = new ActiveMQBytesMessage(); - try { - message.writeDouble(24.5); - message.writeLong(311); - } catch (MessageNotWriteableException mnwe) { - fail("should be writeable"); - } - message.reset(); - try { - assertTrue(message.isReadOnlyBody()); - assertEquals(message.readDouble(), 24.5, 0); - assertEquals(message.readLong(), 311); - } catch (MessageNotReadableException mnre) { - fail("should be readable"); - } - try { - message.writeInt(33); - fail("should throw exception"); - } catch (MessageNotWriteableException mnwe) { - } - } + public void testReadOnlyBody() throws JMSException { + ActiveMQBytesMessage message = new ActiveMQBytesMessage(); + try { + message.writeBoolean(true); + message.writeByte((byte) 1); + message.writeByte((byte) 1); + message.writeBytes(new byte[1]); + message.writeBytes(new byte[3], 0, 2); + message.writeChar('a'); + message.writeDouble(1.5); + message.writeFloat((float) 1.5); + message.writeInt(1); + message.writeLong(1); + message.writeObject("stringobj"); + message.writeShort((short) 1); + message.writeShort((short) 1); + message.writeUTF("utfstring"); + } + catch (MessageNotWriteableException mnwe) { + fail("Should be writeable"); + } + message.reset(); + try { + message.readBoolean(); + message.readByte(); + message.readUnsignedByte(); + message.readBytes(new byte[1]); + message.readBytes(new byte[2], 2); + message.readChar(); + message.readDouble(); + message.readFloat(); + message.readInt(); + message.readLong(); + message.readUTF(); + message.readShort(); + message.readUnsignedShort(); + message.readUTF(); + } + catch (MessageNotReadableException mnwe) { + fail("Should be readable"); + } + try { + message.writeBoolean(true); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + message.writeByte((byte) 1); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + message.writeBytes(new byte[1]); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + message.writeBytes(new byte[3], 0, 2); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + message.writeChar('a'); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + message.writeDouble(1.5); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + message.writeFloat((float) 1.5); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + message.writeInt(1); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + message.writeLong(1); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + message.writeObject("stringobj"); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + message.writeShort((short) 1); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + message.writeUTF("utfstring"); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException mnwe) { + } + } - public void testReadOnlyBody() throws JMSException { - ActiveMQBytesMessage message = new ActiveMQBytesMessage(); - try { - message.writeBoolean(true); - message.writeByte((byte) 1); - message.writeByte((byte) 1); - message.writeBytes(new byte[1]); - message.writeBytes(new byte[3], 0, 2); - message.writeChar('a'); - message.writeDouble(1.5); - message.writeFloat((float) 1.5); - message.writeInt(1); - message.writeLong(1); - message.writeObject("stringobj"); - message.writeShort((short) 1); - message.writeShort((short) 1); - message.writeUTF("utfstring"); - } catch (MessageNotWriteableException mnwe) { - fail("Should be writeable"); - } - message.reset(); - try { - message.readBoolean(); - message.readByte(); - message.readUnsignedByte(); - message.readBytes(new byte[1]); - message.readBytes(new byte[2], 2); - message.readChar(); - message.readDouble(); - message.readFloat(); - message.readInt(); - message.readLong(); - message.readUTF(); - message.readShort(); - message.readUnsignedShort(); - message.readUTF(); - } catch (MessageNotReadableException mnwe) { - fail("Should be readable"); - } - try { - message.writeBoolean(true); - fail("Should have thrown exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - message.writeByte((byte) 1); - fail("Should have thrown exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - message.writeBytes(new byte[1]); - fail("Should have thrown exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - message.writeBytes(new byte[3], 0, 2); - fail("Should have thrown exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - message.writeChar('a'); - fail("Should have thrown exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - message.writeDouble(1.5); - fail("Should have thrown exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - message.writeFloat((float) 1.5); - fail("Should have thrown exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - message.writeInt(1); - fail("Should have thrown exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - message.writeLong(1); - fail("Should have thrown exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - message.writeObject("stringobj"); - fail("Should have thrown exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - message.writeShort((short) 1); - fail("Should have thrown exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - message.writeUTF("utfstring"); - fail("Should have thrown exception"); - } catch (MessageNotWriteableException mnwe) { - } - } - - public void testWriteOnlyBody() throws JMSException { - ActiveMQBytesMessage message = new ActiveMQBytesMessage(); - message.clearBody(); - try { - message.writeBoolean(true); - message.writeByte((byte) 1); - message.writeByte((byte) 1); - message.writeBytes(new byte[1]); - message.writeBytes(new byte[3], 0, 2); - message.writeChar('a'); - message.writeDouble(1.5); - message.writeFloat((float) 1.5); - message.writeInt(1); - message.writeLong(1); - message.writeObject("stringobj"); - message.writeShort((short) 1); - message.writeShort((short) 1); - message.writeUTF("utfstring"); - } catch (MessageNotWriteableException mnwe) { - fail("Should be writeable"); - } - try { - message.readBoolean(); - fail("Should have thrown exception"); - } catch (MessageNotReadableException mnwe) { - } - try { - message.readByte(); - fail("Should have thrown exception"); - } catch (MessageNotReadableException e) { - } - try { - message.readUnsignedByte(); - fail("Should have thrown exception"); - } catch (MessageNotReadableException e) { - } - try { - message.readBytes(new byte[1]); - fail("Should have thrown exception"); - } catch (MessageNotReadableException e) { - } - try { - message.readBytes(new byte[2], 2); - fail("Should have thrown exception"); - } catch (MessageNotReadableException e) { - } - try { - message.readChar(); - fail("Should have thrown exception"); - } catch (MessageNotReadableException e) { - } - try { - message.readDouble(); - fail("Should have thrown exception"); - } catch (MessageNotReadableException e) { - } - try { - message.readFloat(); - fail("Should have thrown exception"); - } catch (MessageNotReadableException e) { - } - try { - message.readInt(); - fail("Should have thrown exception"); - } catch (MessageNotReadableException e) { - } - try { - message.readLong(); - fail("Should have thrown exception"); - } catch (MessageNotReadableException e) { - } - try { - message.readUTF(); - fail("Should have thrown exception"); - } catch (MessageNotReadableException e) { - } - try { - message.readShort(); - fail("Should have thrown exception"); - } catch (MessageNotReadableException e) { - } - try { - message.readUnsignedShort(); - fail("Should have thrown exception"); - } catch (MessageNotReadableException e) { - } - try { - message.readUTF(); - fail("Should have thrown exception"); - } catch (MessageNotReadableException e) { - } - } + public void testWriteOnlyBody() throws JMSException { + ActiveMQBytesMessage message = new ActiveMQBytesMessage(); + message.clearBody(); + try { + message.writeBoolean(true); + message.writeByte((byte) 1); + message.writeByte((byte) 1); + message.writeBytes(new byte[1]); + message.writeBytes(new byte[3], 0, 2); + message.writeChar('a'); + message.writeDouble(1.5); + message.writeFloat((float) 1.5); + message.writeInt(1); + message.writeLong(1); + message.writeObject("stringobj"); + message.writeShort((short) 1); + message.writeShort((short) 1); + message.writeUTF("utfstring"); + } + catch (MessageNotWriteableException mnwe) { + fail("Should be writeable"); + } + try { + message.readBoolean(); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException mnwe) { + } + try { + message.readByte(); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException e) { + } + try { + message.readUnsignedByte(); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException e) { + } + try { + message.readBytes(new byte[1]); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException e) { + } + try { + message.readBytes(new byte[2], 2); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException e) { + } + try { + message.readChar(); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException e) { + } + try { + message.readDouble(); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException e) { + } + try { + message.readFloat(); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException e) { + } + try { + message.readInt(); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException e) { + } + try { + message.readLong(); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException e) { + } + try { + message.readUTF(); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException e) { + } + try { + message.readShort(); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException e) { + } + try { + message.readUnsignedShort(); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException e) { + } + try { + message.readUTF(); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException e) { + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQDestinationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQDestinationTest.java index 844be349ad..9fa4e393cd 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQDestinationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQDestinationTest.java @@ -34,112 +34,103 @@ import junit.framework.Test; public class ActiveMQDestinationTest extends DataStructureTestSupport { - public ActiveMQDestination destination; + public ActiveMQDestination destination; - public void initCombosForTestDestinationMarshaling() { - addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST"), - new ActiveMQTopic("TEST"), - new ActiveMQTempQueue("TEST:1"), - new ActiveMQTempTopic("TEST:1"), - new ActiveMQTempQueue("TEST"), - new ActiveMQTempTopic("TEST"), - new ActiveMQQueue("TEST?option=value"), - new ActiveMQTopic("TEST?option=value"), - new ActiveMQTempQueue("TEST:1?option=value"), - new ActiveMQTempTopic("TEST:1?option=value")}); - } + public void initCombosForTestDestinationMarshaling() { + addCombinationValues("destination", new Object[]{new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST"), new ActiveMQTempQueue("TEST:1"), new ActiveMQTempTopic("TEST:1"), new ActiveMQTempQueue("TEST"), new ActiveMQTempTopic("TEST"), new ActiveMQQueue("TEST?option=value"), new ActiveMQTopic("TEST?option=value"), new ActiveMQTempQueue("TEST:1?option=value"), new ActiveMQTempTopic("TEST:1?option=value")}); + } - public void testDestinationMarshaling() throws IOException { - assertBeanMarshalls(destination); - } + public void testDestinationMarshaling() throws IOException { + assertBeanMarshalls(destination); + } - public void initCombosForTestDestinationOptions() { - addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST?k1=v1&k2=v2"), - new ActiveMQTopic("TEST?k1=v1&k2=v2"), - new ActiveMQTempQueue("TEST:1?k1=v1&k2=v2"), - new ActiveMQTempTopic("TEST:1?k1=v1&k2=v2")}); - } + public void initCombosForTestDestinationOptions() { + addCombinationValues("destination", new Object[]{new ActiveMQQueue("TEST?k1=v1&k2=v2"), new ActiveMQTopic("TEST?k1=v1&k2=v2"), new ActiveMQTempQueue("TEST:1?k1=v1&k2=v2"), new ActiveMQTempTopic("TEST:1?k1=v1&k2=v2")}); + } - public void testDestinationOptions() throws IOException { - Map options = destination.getOptions(); - assertNotNull(options); - assertEquals("v1", options.get("k1")); - assertEquals("v2", options.get("k2")); - } + public void testDestinationOptions() throws IOException { + Map options = destination.getOptions(); + assertNotNull(options); + assertEquals("v1", options.get("k1")); + assertEquals("v2", options.get("k2")); + } - public void testSorting() throws Exception { - SortedSet set = new TreeSet(); - ActiveMQDestination[] destinations = {new ActiveMQQueue("A"), new ActiveMQQueue("B"), - new ActiveMQTopic("A"), new ActiveMQTopic("B")}; - List expected = Arrays.asList(destinations); - set.addAll(expected); - List actual = new ArrayList(set); - assertEquals("Sorted order", expected, actual); - } + public void testSorting() throws Exception { + SortedSet set = new TreeSet(); + ActiveMQDestination[] destinations = {new ActiveMQQueue("A"), new ActiveMQQueue("B"), new ActiveMQTopic("A"), new ActiveMQTopic("B")}; + List expected = Arrays.asList(destinations); + set.addAll(expected); + List actual = new ArrayList(set); + assertEquals("Sorted order", expected, actual); + } - // https://issues.apache.org/activemq/browse/AMQ-2630 - class CombyDest implements Queue, Topic, TemporaryQueue, TemporaryTopic { + // https://issues.apache.org/activemq/browse/AMQ-2630 + class CombyDest implements Queue, Topic, TemporaryQueue, TemporaryTopic { - private final String qName; - private final String topicName; + private final String qName; + private final String topicName; - public CombyDest(String qName, String topicName) { - this.qName = qName; - this.topicName = topicName; - } - - public void delete() throws JMSException { - } + public CombyDest(String qName, String topicName) { + this.qName = qName; + this.topicName = topicName; + } - public String getTopicName() throws JMSException { - return topicName; - } + public void delete() throws JMSException { + } - public String getQueueName() throws JMSException { - return qName; - } - } - - public void testTransformPollymorphic() throws Exception { - ActiveMQQueue queue = new ActiveMQQueue("TEST"); - assertEquals(ActiveMQDestination.transform(queue), queue); - assertTrue("is a q", ActiveMQDestination.transform(new CombyDest(null, "Topic")) instanceof ActiveMQTopic); - assertTrue("is a q", ActiveMQDestination.transform(new CombyDest("Q", null)) instanceof ActiveMQQueue); - try { - ActiveMQDestination.transform(new CombyDest(null, null)); - fail("expect ex as cannot disambiguate"); - } catch (JMSException expected) { - } - try { - ActiveMQDestination.transform(new CombyDest("Q", "T")); - fail("expect ex as cannot disambiguate"); - } catch (JMSException expected) { - } - } - - public static Test suite() { - return suite(ActiveMQDestinationTest.class); - } + public String getTopicName() throws JMSException { + return topicName; + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public String getQueueName() throws JMSException { + return qName; + } + } - public void testEmptyQueueName() { - try { - new ActiveMQQueue(""); - fail("Should have thrown IllegalArgumentException"); - } catch (IllegalArgumentException e) { + public void testTransformPollymorphic() throws Exception { + ActiveMQQueue queue = new ActiveMQQueue("TEST"); + assertEquals(ActiveMQDestination.transform(queue), queue); + assertTrue("is a q", ActiveMQDestination.transform(new CombyDest(null, "Topic")) instanceof ActiveMQTopic); + assertTrue("is a q", ActiveMQDestination.transform(new CombyDest("Q", null)) instanceof ActiveMQQueue); + try { + ActiveMQDestination.transform(new CombyDest(null, null)); + fail("expect ex as cannot disambiguate"); + } + catch (JMSException expected) { + } + try { + ActiveMQDestination.transform(new CombyDest("Q", "T")); + fail("expect ex as cannot disambiguate"); + } + catch (JMSException expected) { + } + } - } - } + public static Test suite() { + return suite(ActiveMQDestinationTest.class); + } - public void testEmptyTopicName() { - try { - new ActiveMQTopic(""); - fail("Should have thrown IllegalArgumentException"); - } catch (IllegalArgumentException e) { + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - } - } + public void testEmptyQueueName() { + try { + new ActiveMQQueue(""); + fail("Should have thrown IllegalArgumentException"); + } + catch (IllegalArgumentException e) { + + } + } + + public void testEmptyTopicName() { + try { + new ActiveMQTopic(""); + fail("Should have thrown IllegalArgumentException"); + } + catch (IllegalArgumentException e) { + + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQMapMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQMapMessageTest.java index 5b82b2939b..117c85295c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQMapMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQMapMessageTest.java @@ -29,464 +29,489 @@ import javax.jms.MessageNotReadableException; import javax.jms.MessageNotWriteableException; import junit.framework.TestCase; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class ActiveMQMapMessageTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(ActiveMQMapMessageTest.class); - private String name = "testName"; + private static final Logger LOG = LoggerFactory.getLogger(ActiveMQMapMessageTest.class); - /** - * Constructor for ActiveMQMapMessageTest. - * - * @param name - */ - public ActiveMQMapMessageTest(String name) { - super(name); - } + private String name = "testName"; - public static void main(String[] args) { - junit.textui.TestRunner.run(ActiveMQMapMessageTest.class); - } + /** + * Constructor for ActiveMQMapMessageTest. + * + * @param name + */ + public ActiveMQMapMessageTest(String name) { + super(name); + } - /* - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(ActiveMQMapMessageTest.class); + } - /* - * @see TestCase#tearDown() - */ - protected void tearDown() throws Exception { - super.tearDown(); - } + /* + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + } - public void testBytesConversion() throws JMSException, IOException { - ActiveMQMapMessage msg = new ActiveMQMapMessage(); - msg.setBoolean("boolean", true); - msg.setByte("byte", (byte)1); - msg.setBytes("bytes", new byte[1]); - msg.setChar("char", 'a'); - msg.setDouble("double", 1.5); - msg.setFloat("float", 1.5f); - msg.setInt("int", 1); - msg.setLong("long", 1); - msg.setObject("object", "stringObj"); - msg.setShort("short", (short)1); - msg.setString("string", "string"); + /* + * @see TestCase#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + } - // Test with a 1Meg String - StringBuffer bigSB = new StringBuffer(1024 * 1024); - for (int i = 0; i < 1024 * 1024; i++) { - bigSB.append((char)'a' + i % 26); - } - String bigString = bigSB.toString(); + public void testBytesConversion() throws JMSException, IOException { + ActiveMQMapMessage msg = new ActiveMQMapMessage(); + msg.setBoolean("boolean", true); + msg.setByte("byte", (byte) 1); + msg.setBytes("bytes", new byte[1]); + msg.setChar("char", 'a'); + msg.setDouble("double", 1.5); + msg.setFloat("float", 1.5f); + msg.setInt("int", 1); + msg.setLong("long", 1); + msg.setObject("object", "stringObj"); + msg.setShort("short", (short) 1); + msg.setString("string", "string"); - msg.setString("bigString", bigString); + // Test with a 1Meg String + StringBuffer bigSB = new StringBuffer(1024 * 1024); + for (int i = 0; i < 1024 * 1024; i++) { + bigSB.append((char) 'a' + i % 26); + } + String bigString = bigSB.toString(); - msg = (ActiveMQMapMessage)msg.copy(); + msg.setString("bigString", bigString); - assertEquals(msg.getBoolean("boolean"), true); - assertEquals(msg.getByte("byte"), (byte)1); - assertEquals(msg.getBytes("bytes").length, 1); - assertEquals(msg.getChar("char"), 'a'); - assertEquals(msg.getDouble("double"), 1.5, 0); - assertEquals(msg.getFloat("float"), 1.5f, 0); - assertEquals(msg.getInt("int"), 1); - assertEquals(msg.getLong("long"), 1); - assertEquals(msg.getObject("object"), "stringObj"); - assertEquals(msg.getShort("short"), (short)1); - assertEquals(msg.getString("string"), "string"); - assertEquals(msg.getString("bigString"), bigString); - } + msg = (ActiveMQMapMessage) msg.copy(); - public void testGetBoolean() throws JMSException { - ActiveMQMapMessage msg = new ActiveMQMapMessage(); - msg.setBoolean(name, true); - msg.setReadOnlyBody(true); - assertTrue(msg.getBoolean(name)); - msg.clearBody(); - msg.setString(name, "true"); + assertEquals(msg.getBoolean("boolean"), true); + assertEquals(msg.getByte("byte"), (byte) 1); + assertEquals(msg.getBytes("bytes").length, 1); + assertEquals(msg.getChar("char"), 'a'); + assertEquals(msg.getDouble("double"), 1.5, 0); + assertEquals(msg.getFloat("float"), 1.5f, 0); + assertEquals(msg.getInt("int"), 1); + assertEquals(msg.getLong("long"), 1); + assertEquals(msg.getObject("object"), "stringObj"); + assertEquals(msg.getShort("short"), (short) 1); + assertEquals(msg.getString("string"), "string"); + assertEquals(msg.getString("bigString"), bigString); + } - msg = (ActiveMQMapMessage)msg.copy(); + public void testGetBoolean() throws JMSException { + ActiveMQMapMessage msg = new ActiveMQMapMessage(); + msg.setBoolean(name, true); + msg.setReadOnlyBody(true); + assertTrue(msg.getBoolean(name)); + msg.clearBody(); + msg.setString(name, "true"); - assertTrue(msg.getBoolean(name)); - } + msg = (ActiveMQMapMessage) msg.copy(); - public void testGetByte() throws JMSException { - ActiveMQMapMessage msg = new ActiveMQMapMessage(); - msg.setByte(this.name, (byte)1); - msg = (ActiveMQMapMessage)msg.copy(); - assertTrue(msg.getByte(this.name) == (byte)1); - } + assertTrue(msg.getBoolean(name)); + } - public void testGetShort() { - ActiveMQMapMessage msg = new ActiveMQMapMessage(); - try { - msg.setShort(this.name, (short)1); - msg = (ActiveMQMapMessage)msg.copy(); - assertTrue(msg.getShort(this.name) == (short)1); - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } + public void testGetByte() throws JMSException { + ActiveMQMapMessage msg = new ActiveMQMapMessage(); + msg.setByte(this.name, (byte) 1); + msg = (ActiveMQMapMessage) msg.copy(); + assertTrue(msg.getByte(this.name) == (byte) 1); + } - public void testGetChar() { - ActiveMQMapMessage msg = new ActiveMQMapMessage(); - try { - msg.setChar(this.name, 'a'); - msg = (ActiveMQMapMessage)msg.copy(); - assertTrue(msg.getChar(this.name) == 'a'); - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } + public void testGetShort() { + ActiveMQMapMessage msg = new ActiveMQMapMessage(); + try { + msg.setShort(this.name, (short) 1); + msg = (ActiveMQMapMessage) msg.copy(); + assertTrue(msg.getShort(this.name) == (short) 1); + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } - public void testGetInt() { - ActiveMQMapMessage msg = new ActiveMQMapMessage(); - try { - msg.setInt(this.name, 1); - msg = (ActiveMQMapMessage)msg.copy(); - assertTrue(msg.getInt(this.name) == 1); - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } + public void testGetChar() { + ActiveMQMapMessage msg = new ActiveMQMapMessage(); + try { + msg.setChar(this.name, 'a'); + msg = (ActiveMQMapMessage) msg.copy(); + assertTrue(msg.getChar(this.name) == 'a'); + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } - public void testGetLong() { - ActiveMQMapMessage msg = new ActiveMQMapMessage(); - try { - msg.setLong(this.name, 1); - msg = (ActiveMQMapMessage)msg.copy(); - assertTrue(msg.getLong(this.name) == 1); - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } + public void testGetInt() { + ActiveMQMapMessage msg = new ActiveMQMapMessage(); + try { + msg.setInt(this.name, 1); + msg = (ActiveMQMapMessage) msg.copy(); + assertTrue(msg.getInt(this.name) == 1); + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } - public void testGetFloat() { - ActiveMQMapMessage msg = new ActiveMQMapMessage(); - try { - msg.setFloat(this.name, 1.5f); - msg = (ActiveMQMapMessage)msg.copy(); - assertTrue(msg.getFloat(this.name) == 1.5f); - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } + public void testGetLong() { + ActiveMQMapMessage msg = new ActiveMQMapMessage(); + try { + msg.setLong(this.name, 1); + msg = (ActiveMQMapMessage) msg.copy(); + assertTrue(msg.getLong(this.name) == 1); + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } - public void testGetDouble() { - ActiveMQMapMessage msg = new ActiveMQMapMessage(); - try { - msg.setDouble(this.name, 1.5); - msg = (ActiveMQMapMessage)msg.copy(); - assertTrue(msg.getDouble(this.name) == 1.5); - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } + public void testGetFloat() { + ActiveMQMapMessage msg = new ActiveMQMapMessage(); + try { + msg.setFloat(this.name, 1.5f); + msg = (ActiveMQMapMessage) msg.copy(); + assertTrue(msg.getFloat(this.name) == 1.5f); + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } - public void testGetString() { - ActiveMQMapMessage msg = new ActiveMQMapMessage(); - try { - String str = "test"; - msg.setString(this.name, str); - msg = (ActiveMQMapMessage)msg.copy(); - assertEquals(msg.getString(this.name), str); - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } + public void testGetDouble() { + ActiveMQMapMessage msg = new ActiveMQMapMessage(); + try { + msg.setDouble(this.name, 1.5); + msg = (ActiveMQMapMessage) msg.copy(); + assertTrue(msg.getDouble(this.name) == 1.5); + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } - public void testGetBytes() { - ActiveMQMapMessage msg = new ActiveMQMapMessage(); - try { - byte[] bytes1 = new byte[3]; - byte[] bytes2 = new byte[2]; - System.arraycopy(bytes1, 0, bytes2, 0, 2); - msg.setBytes(this.name, bytes1); - msg.setBytes(this.name + "2", bytes1, 0, 2); - msg = (ActiveMQMapMessage)msg.copy(); - assertTrue(Arrays.equals(msg.getBytes(this.name), bytes1)); - assertEquals(msg.getBytes(this.name + "2").length, bytes2.length); - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } + public void testGetString() { + ActiveMQMapMessage msg = new ActiveMQMapMessage(); + try { + String str = "test"; + msg.setString(this.name, str); + msg = (ActiveMQMapMessage) msg.copy(); + assertEquals(msg.getString(this.name), str); + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } - public void testGetObject() throws JMSException { - ActiveMQMapMessage msg = new ActiveMQMapMessage(); - Boolean booleanValue = Boolean.TRUE; - Byte byteValue = Byte.valueOf("1"); - byte[] bytesValue = new byte[3]; - Character charValue = new Character('a'); - Double doubleValue = Double.valueOf("1.5"); - Float floatValue = Float.valueOf("1.5"); - Integer intValue = Integer.valueOf("1"); - Long longValue = Long.valueOf("1"); - Short shortValue = Short.valueOf("1"); - String stringValue = "string"; + public void testGetBytes() { + ActiveMQMapMessage msg = new ActiveMQMapMessage(); + try { + byte[] bytes1 = new byte[3]; + byte[] bytes2 = new byte[2]; + System.arraycopy(bytes1, 0, bytes2, 0, 2); + msg.setBytes(this.name, bytes1); + msg.setBytes(this.name + "2", bytes1, 0, 2); + msg = (ActiveMQMapMessage) msg.copy(); + assertTrue(Arrays.equals(msg.getBytes(this.name), bytes1)); + assertEquals(msg.getBytes(this.name + "2").length, bytes2.length); + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } - try { - msg.setObject("boolean", booleanValue); - msg.setObject("byte", byteValue); - msg.setObject("bytes", bytesValue); - msg.setObject("char", charValue); - msg.setObject("double", doubleValue); - msg.setObject("float", floatValue); - msg.setObject("int", intValue); - msg.setObject("long", longValue); - msg.setObject("short", shortValue); - msg.setObject("string", stringValue); - } catch (MessageFormatException mfe) { - LOG.warn("Caught: " + mfe); - mfe.printStackTrace(); - fail("object formats should be correct"); - } + public void testGetObject() throws JMSException { + ActiveMQMapMessage msg = new ActiveMQMapMessage(); + Boolean booleanValue = Boolean.TRUE; + Byte byteValue = Byte.valueOf("1"); + byte[] bytesValue = new byte[3]; + Character charValue = new Character('a'); + Double doubleValue = Double.valueOf("1.5"); + Float floatValue = Float.valueOf("1.5"); + Integer intValue = Integer.valueOf("1"); + Long longValue = Long.valueOf("1"); + Short shortValue = Short.valueOf("1"); + String stringValue = "string"; - msg = (ActiveMQMapMessage)msg.copy(); + try { + msg.setObject("boolean", booleanValue); + msg.setObject("byte", byteValue); + msg.setObject("bytes", bytesValue); + msg.setObject("char", charValue); + msg.setObject("double", doubleValue); + msg.setObject("float", floatValue); + msg.setObject("int", intValue); + msg.setObject("long", longValue); + msg.setObject("short", shortValue); + msg.setObject("string", stringValue); + } + catch (MessageFormatException mfe) { + LOG.warn("Caught: " + mfe); + mfe.printStackTrace(); + fail("object formats should be correct"); + } - assertTrue(msg.getObject("boolean") instanceof Boolean); - assertEquals(msg.getObject("boolean"), booleanValue); - assertEquals(msg.getBoolean("boolean"), booleanValue.booleanValue()); - assertTrue(msg.getObject("byte") instanceof Byte); - assertEquals(msg.getObject("byte"), byteValue); - assertEquals(msg.getByte("byte"), byteValue.byteValue()); - assertTrue(msg.getObject("bytes") instanceof byte[]); - assertEquals(((byte[])msg.getObject("bytes")).length, bytesValue.length); - assertEquals(msg.getBytes("bytes").length, bytesValue.length); - assertTrue(msg.getObject("char") instanceof Character); - assertEquals(msg.getObject("char"), charValue); - assertEquals(msg.getChar("char"), charValue.charValue()); - assertTrue(msg.getObject("double") instanceof Double); - assertEquals(msg.getObject("double"), doubleValue); - assertEquals(msg.getDouble("double"), doubleValue.doubleValue(), 0); - assertTrue(msg.getObject("float") instanceof Float); - assertEquals(msg.getObject("float"), floatValue); - assertEquals(msg.getFloat("float"), floatValue.floatValue(), 0); - assertTrue(msg.getObject("int") instanceof Integer); - assertEquals(msg.getObject("int"), intValue); - assertEquals(msg.getInt("int"), intValue.intValue()); - assertTrue(msg.getObject("long") instanceof Long); - assertEquals(msg.getObject("long"), longValue); - assertEquals(msg.getLong("long"), longValue.longValue()); - assertTrue(msg.getObject("short") instanceof Short); - assertEquals(msg.getObject("short"), shortValue); - assertEquals(msg.getShort("short"), shortValue.shortValue()); - assertTrue(msg.getObject("string") instanceof String); - assertEquals(msg.getObject("string"), stringValue); - assertEquals(msg.getString("string"), stringValue); + msg = (ActiveMQMapMessage) msg.copy(); - msg.clearBody(); - try { - msg.setObject("object", new Object()); - fail("should have thrown exception"); - } catch (MessageFormatException e) { - } + assertTrue(msg.getObject("boolean") instanceof Boolean); + assertEquals(msg.getObject("boolean"), booleanValue); + assertEquals(msg.getBoolean("boolean"), booleanValue.booleanValue()); + assertTrue(msg.getObject("byte") instanceof Byte); + assertEquals(msg.getObject("byte"), byteValue); + assertEquals(msg.getByte("byte"), byteValue.byteValue()); + assertTrue(msg.getObject("bytes") instanceof byte[]); + assertEquals(((byte[]) msg.getObject("bytes")).length, bytesValue.length); + assertEquals(msg.getBytes("bytes").length, bytesValue.length); + assertTrue(msg.getObject("char") instanceof Character); + assertEquals(msg.getObject("char"), charValue); + assertEquals(msg.getChar("char"), charValue.charValue()); + assertTrue(msg.getObject("double") instanceof Double); + assertEquals(msg.getObject("double"), doubleValue); + assertEquals(msg.getDouble("double"), doubleValue.doubleValue(), 0); + assertTrue(msg.getObject("float") instanceof Float); + assertEquals(msg.getObject("float"), floatValue); + assertEquals(msg.getFloat("float"), floatValue.floatValue(), 0); + assertTrue(msg.getObject("int") instanceof Integer); + assertEquals(msg.getObject("int"), intValue); + assertEquals(msg.getInt("int"), intValue.intValue()); + assertTrue(msg.getObject("long") instanceof Long); + assertEquals(msg.getObject("long"), longValue); + assertEquals(msg.getLong("long"), longValue.longValue()); + assertTrue(msg.getObject("short") instanceof Short); + assertEquals(msg.getObject("short"), shortValue); + assertEquals(msg.getShort("short"), shortValue.shortValue()); + assertTrue(msg.getObject("string") instanceof String); + assertEquals(msg.getObject("string"), stringValue); + assertEquals(msg.getString("string"), stringValue); - } + msg.clearBody(); + try { + msg.setObject("object", new Object()); + fail("should have thrown exception"); + } + catch (MessageFormatException e) { + } - public void testGetMapNames() throws JMSException { - ActiveMQMapMessage msg = new ActiveMQMapMessage(); - msg.setBoolean("boolean", true); - msg.setByte("byte", (byte)1); - msg.setBytes("bytes1", new byte[1]); - msg.setBytes("bytes2", new byte[3], 0, 2); - msg.setChar("char", 'a'); - msg.setDouble("double", 1.5); - msg.setFloat("float", 1.5f); - msg.setInt("int", 1); - msg.setLong("long", 1); - msg.setObject("object", "stringObj"); - msg.setShort("short", (short)1); - msg.setString("string", "string"); + } - msg = (ActiveMQMapMessage)msg.copy(); + public void testGetMapNames() throws JMSException { + ActiveMQMapMessage msg = new ActiveMQMapMessage(); + msg.setBoolean("boolean", true); + msg.setByte("byte", (byte) 1); + msg.setBytes("bytes1", new byte[1]); + msg.setBytes("bytes2", new byte[3], 0, 2); + msg.setChar("char", 'a'); + msg.setDouble("double", 1.5); + msg.setFloat("float", 1.5f); + msg.setInt("int", 1); + msg.setLong("long", 1); + msg.setObject("object", "stringObj"); + msg.setShort("short", (short) 1); + msg.setString("string", "string"); - Enumeration mapNamesEnum = msg.getMapNames(); - List mapNamesList = Collections.list(mapNamesEnum); + msg = (ActiveMQMapMessage) msg.copy(); - assertEquals(mapNamesList.size(), 12); - assertTrue(mapNamesList.contains("boolean")); - assertTrue(mapNamesList.contains("byte")); - assertTrue(mapNamesList.contains("bytes1")); - assertTrue(mapNamesList.contains("bytes2")); - assertTrue(mapNamesList.contains("char")); - assertTrue(mapNamesList.contains("double")); - assertTrue(mapNamesList.contains("float")); - assertTrue(mapNamesList.contains("int")); - assertTrue(mapNamesList.contains("long")); - assertTrue(mapNamesList.contains("object")); - assertTrue(mapNamesList.contains("short")); - assertTrue(mapNamesList.contains("string")); - } + Enumeration mapNamesEnum = msg.getMapNames(); + List mapNamesList = Collections.list(mapNamesEnum); - public void testItemExists() throws JMSException { - ActiveMQMapMessage mapMessage = new ActiveMQMapMessage(); + assertEquals(mapNamesList.size(), 12); + assertTrue(mapNamesList.contains("boolean")); + assertTrue(mapNamesList.contains("byte")); + assertTrue(mapNamesList.contains("bytes1")); + assertTrue(mapNamesList.contains("bytes2")); + assertTrue(mapNamesList.contains("char")); + assertTrue(mapNamesList.contains("double")); + assertTrue(mapNamesList.contains("float")); + assertTrue(mapNamesList.contains("int")); + assertTrue(mapNamesList.contains("long")); + assertTrue(mapNamesList.contains("object")); + assertTrue(mapNamesList.contains("short")); + assertTrue(mapNamesList.contains("string")); + } - mapMessage.setString("exists", "test"); + public void testItemExists() throws JMSException { + ActiveMQMapMessage mapMessage = new ActiveMQMapMessage(); - mapMessage = (ActiveMQMapMessage)mapMessage.copy(); + mapMessage.setString("exists", "test"); - assertTrue(mapMessage.itemExists("exists")); - assertFalse(mapMessage.itemExists("doesntExist")); - } + mapMessage = (ActiveMQMapMessage) mapMessage.copy(); - public void testClearBody() throws JMSException { - ActiveMQMapMessage mapMessage = new ActiveMQMapMessage(); - mapMessage.setString("String", "String"); - mapMessage.clearBody(); - assertFalse(mapMessage.isReadOnlyBody()); + assertTrue(mapMessage.itemExists("exists")); + assertFalse(mapMessage.itemExists("doesntExist")); + } - mapMessage.onSend(); - mapMessage.setContent(mapMessage.getContent()); - assertNull(mapMessage.getString("String")); - mapMessage.clearBody(); - mapMessage.setString("String", "String"); + public void testClearBody() throws JMSException { + ActiveMQMapMessage mapMessage = new ActiveMQMapMessage(); + mapMessage.setString("String", "String"); + mapMessage.clearBody(); + assertFalse(mapMessage.isReadOnlyBody()); - mapMessage = (ActiveMQMapMessage)mapMessage.copy(); + mapMessage.onSend(); + mapMessage.setContent(mapMessage.getContent()); + assertNull(mapMessage.getString("String")); + mapMessage.clearBody(); + mapMessage.setString("String", "String"); - mapMessage.getString("String"); - } + mapMessage = (ActiveMQMapMessage) mapMessage.copy(); - public void testReadOnlyBody() throws JMSException { - ActiveMQMapMessage msg = new ActiveMQMapMessage(); - msg.setBoolean("boolean", true); - msg.setByte("byte", (byte)1); - msg.setBytes("bytes", new byte[1]); - msg.setBytes("bytes2", new byte[3], 0, 2); - msg.setChar("char", 'a'); - msg.setDouble("double", 1.5); - msg.setFloat("float", 1.5f); - msg.setInt("int", 1); - msg.setLong("long", 1); - msg.setObject("object", "stringObj"); - msg.setShort("short", (short)1); - msg.setString("string", "string"); + mapMessage.getString("String"); + } - msg.setReadOnlyBody(true); + public void testReadOnlyBody() throws JMSException { + ActiveMQMapMessage msg = new ActiveMQMapMessage(); + msg.setBoolean("boolean", true); + msg.setByte("byte", (byte) 1); + msg.setBytes("bytes", new byte[1]); + msg.setBytes("bytes2", new byte[3], 0, 2); + msg.setChar("char", 'a'); + msg.setDouble("double", 1.5); + msg.setFloat("float", 1.5f); + msg.setInt("int", 1); + msg.setLong("long", 1); + msg.setObject("object", "stringObj"); + msg.setShort("short", (short) 1); + msg.setString("string", "string"); - try { - msg.getBoolean("boolean"); - msg.getByte("byte"); - msg.getBytes("bytes"); - msg.getChar("char"); - msg.getDouble("double"); - msg.getFloat("float"); - msg.getInt("int"); - msg.getLong("long"); - msg.getObject("object"); - msg.getShort("short"); - msg.getString("string"); - } catch (MessageNotReadableException mnre) { - fail("should be readable"); - } - try { - msg.setBoolean("boolean", true); - fail("should throw exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - msg.setByte("byte", (byte)1); - fail("should throw exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - msg.setBytes("bytes", new byte[1]); - fail("should throw exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - msg.setBytes("bytes2", new byte[3], 0, 2); - fail("should throw exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - msg.setChar("char", 'a'); - fail("should throw exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - msg.setDouble("double", 1.5); - fail("should throw exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - msg.setFloat("float", 1.5f); - fail("should throw exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - msg.setInt("int", 1); - fail("should throw exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - msg.setLong("long", 1); - fail("should throw exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - msg.setObject("object", "stringObj"); - fail("should throw exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - msg.setShort("short", (short)1); - fail("should throw exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - msg.setString("string", "string"); - fail("should throw exception"); - } catch (MessageNotWriteableException mnwe) { - } - } + msg.setReadOnlyBody(true); - public void testWriteOnlyBody() throws JMSException { - ActiveMQMapMessage msg = new ActiveMQMapMessage(); - msg.setReadOnlyBody(false); + try { + msg.getBoolean("boolean"); + msg.getByte("byte"); + msg.getBytes("bytes"); + msg.getChar("char"); + msg.getDouble("double"); + msg.getFloat("float"); + msg.getInt("int"); + msg.getLong("long"); + msg.getObject("object"); + msg.getShort("short"); + msg.getString("string"); + } + catch (MessageNotReadableException mnre) { + fail("should be readable"); + } + try { + msg.setBoolean("boolean", true); + fail("should throw exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + msg.setByte("byte", (byte) 1); + fail("should throw exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + msg.setBytes("bytes", new byte[1]); + fail("should throw exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + msg.setBytes("bytes2", new byte[3], 0, 2); + fail("should throw exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + msg.setChar("char", 'a'); + fail("should throw exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + msg.setDouble("double", 1.5); + fail("should throw exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + msg.setFloat("float", 1.5f); + fail("should throw exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + msg.setInt("int", 1); + fail("should throw exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + msg.setLong("long", 1); + fail("should throw exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + msg.setObject("object", "stringObj"); + fail("should throw exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + msg.setShort("short", (short) 1); + fail("should throw exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + msg.setString("string", "string"); + fail("should throw exception"); + } + catch (MessageNotWriteableException mnwe) { + } + } - msg.setBoolean("boolean", true); - msg.setByte("byte", (byte)1); - msg.setBytes("bytes", new byte[1]); - msg.setBytes("bytes2", new byte[3], 0, 2); - msg.setChar("char", 'a'); - msg.setDouble("double", 1.5); - msg.setFloat("float", 1.5f); - msg.setInt("int", 1); - msg.setLong("long", 1); - msg.setObject("object", "stringObj"); - msg.setShort("short", (short)1); - msg.setString("string", "string"); + public void testWriteOnlyBody() throws JMSException { + ActiveMQMapMessage msg = new ActiveMQMapMessage(); + msg.setReadOnlyBody(false); - msg.setReadOnlyBody(true); + msg.setBoolean("boolean", true); + msg.setByte("byte", (byte) 1); + msg.setBytes("bytes", new byte[1]); + msg.setBytes("bytes2", new byte[3], 0, 2); + msg.setChar("char", 'a'); + msg.setDouble("double", 1.5); + msg.setFloat("float", 1.5f); + msg.setInt("int", 1); + msg.setLong("long", 1); + msg.setObject("object", "stringObj"); + msg.setShort("short", (short) 1); + msg.setString("string", "string"); - msg.getBoolean("boolean"); - msg.getByte("byte"); - msg.getBytes("bytes"); - msg.getChar("char"); - msg.getDouble("double"); - msg.getFloat("float"); - msg.getInt("int"); - msg.getLong("long"); - msg.getObject("object"); - msg.getShort("short"); - msg.getString("string"); - } + msg.setReadOnlyBody(true); + + msg.getBoolean("boolean"); + msg.getByte("byte"); + msg.getBytes("bytes"); + msg.getChar("char"); + msg.getDouble("double"); + msg.getFloat("float"); + msg.getInt("int"); + msg.getLong("long"); + msg.getObject("object"); + msg.getShort("short"); + msg.getString("string"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQMessageTest.java index e1079a1628..4bca7eb8e5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQMessageTest.java @@ -37,956 +37,1022 @@ import org.slf4j.LoggerFactory; public class ActiveMQMessageTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(ActiveMQMessageTest.class); - - protected boolean readOnlyMessage; - - private String jmsMessageID; - private String jmsCorrelationID; - private ActiveMQDestination jmsDestination; - private ActiveMQDestination jmsReplyTo; - private int jmsDeliveryMode; - private boolean jmsRedelivered; - private String jmsType; - private long jmsExpiration; - private int jmsPriority; - private long jmsTimestamp; - private long[] consumerIDs; - - /** - * Constructor for ActiveMQMessageTest. - * - * @param name - */ - public ActiveMQMessageTest(String name) { - super(name); - } - - public static void main(String[] args) { - } - - /* - * @see TestCase#setUp() - */ - @Override - protected void setUp() throws Exception { - super.setUp(); - this.jmsMessageID = "ID:TEST-ID:0:0:0:1"; - this.jmsCorrelationID = "testcorrelationid"; - this.jmsDestination = new ActiveMQTopic("test.topic"); - this.jmsReplyTo = new ActiveMQTempTopic("test.replyto.topic:001"); - this.jmsDeliveryMode = Message.DEFAULT_DELIVERY_MODE; - this.jmsRedelivered = true; - this.jmsType = "test type"; - this.jmsExpiration = 100000; - this.jmsPriority = 5; - this.jmsTimestamp = System.currentTimeMillis(); - this.readOnlyMessage = false; - this.consumerIDs = new long[3]; - for (int i = 0; i < this.consumerIDs.length; i++) { - this.consumerIDs[i] = i; - } - } - - /* - * @see TestCase#tearDown() - */ - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } - - public void testGetDataStructureType() { - ActiveMQMessage msg = new ActiveMQMessage(); - assertEquals(msg.getDataStructureType(), CommandTypes.ACTIVEMQ_MESSAGE); - } - - public void testHashCode() throws Exception { - ActiveMQMessage msg = new ActiveMQMessage(); - msg.setJMSMessageID(this.jmsMessageID); - assertTrue(msg.getJMSMessageID().hashCode() == jmsMessageID.hashCode()); - } - - public void testSetReadOnly() { - ActiveMQMessage msg = new ActiveMQMessage(); - msg.setReadOnlyProperties(true); - boolean test = false; - try { - msg.setIntProperty("test", 1); - } catch (MessageNotWriteableException me) { - test = true; - } catch (JMSException e) { - e.printStackTrace(System.err); - test = false; - } - assertTrue(test); - } - - public void testSetToForeignJMSID() throws Exception { - ActiveMQMessage msg = new ActiveMQMessage(); - msg.setJMSMessageID("ID:EMS-SERVER.8B443C380083:429"); - } - - /* - * Class to test for boolean equals(Object) - */ - public void testEqualsObject() throws Exception { - ActiveMQMessage msg1 = new ActiveMQMessage(); - ActiveMQMessage msg2 = new ActiveMQMessage(); - msg1.setJMSMessageID(this.jmsMessageID); - assertTrue(!msg1.equals(msg2)); - msg2.setJMSMessageID(this.jmsMessageID); - assertTrue(msg1.equals(msg2)); - } - - public void testShallowCopy() throws Exception { - ActiveMQMessage msg1 = new ActiveMQMessage(); - msg1.setJMSMessageID(jmsMessageID); - ActiveMQMessage msg2 = (ActiveMQMessage) msg1.copy(); - assertTrue(msg1 != msg2 && msg1.equals(msg2)); - } - - public void testCopy() throws Exception { - this.jmsMessageID = "testid"; - this.jmsCorrelationID = "testcorrelationid"; - this.jmsDestination = new ActiveMQTopic("test.topic"); - this.jmsReplyTo = new ActiveMQTempTopic("test.replyto.topic:001"); - this.jmsDeliveryMode = Message.DEFAULT_DELIVERY_MODE; - this.jmsRedelivered = true; - this.jmsType = "test type"; - this.jmsExpiration = 100000; - this.jmsPriority = 5; - this.jmsTimestamp = System.currentTimeMillis(); - this.readOnlyMessage = false; - - ActiveMQMessage msg1 = new ActiveMQMessage(); - msg1.setJMSMessageID(this.jmsMessageID); - msg1.setJMSCorrelationID(this.jmsCorrelationID); - msg1.setJMSDestination(this.jmsDestination); - msg1.setJMSReplyTo(this.jmsReplyTo); - msg1.setJMSDeliveryMode(this.jmsDeliveryMode); - msg1.setJMSRedelivered(this.jmsRedelivered); - msg1.setJMSType(this.jmsType); - msg1.setJMSExpiration(this.jmsExpiration); - msg1.setJMSPriority(this.jmsPriority); - msg1.setJMSTimestamp(this.jmsTimestamp); - msg1.setReadOnlyProperties(true); - ActiveMQMessage msg2 = new ActiveMQMessage(); - msg1.copy(msg2); - assertEquals(msg1.getJMSMessageID(), msg2.getJMSMessageID()); - assertTrue(msg1.getJMSCorrelationID().equals(msg2.getJMSCorrelationID())); - assertTrue(msg1.getJMSDestination().equals(msg2.getJMSDestination())); - assertTrue(msg1.getJMSReplyTo().equals(msg2.getJMSReplyTo())); - assertTrue(msg1.getJMSDeliveryMode() == msg2.getJMSDeliveryMode()); - assertTrue(msg1.getJMSRedelivered() == msg2.getJMSRedelivered()); - assertTrue(msg1.getJMSType().equals(msg2.getJMSType())); - assertTrue(msg1.getJMSExpiration() == msg2.getJMSExpiration()); - assertTrue(msg1.getJMSPriority() == msg2.getJMSPriority()); - assertTrue(msg1.getJMSTimestamp() == msg2.getJMSTimestamp()); - - LOG.info("Message is: " + msg1); - } - - public void testGetAndSetJMSMessageID() throws Exception { - ActiveMQMessage msg = new ActiveMQMessage(); - msg.setJMSMessageID(this.jmsMessageID); - assertEquals(msg.getJMSMessageID(), this.jmsMessageID); - } - - public void testGetAndSetJMSTimestamp() { - ActiveMQMessage msg = new ActiveMQMessage(); - msg.setJMSTimestamp(this.jmsTimestamp); - assertTrue(msg.getJMSTimestamp() == this.jmsTimestamp); - } - - public void testGetJMSCorrelationIDAsBytes() throws Exception { - ActiveMQMessage msg = new ActiveMQMessage(); - msg.setJMSCorrelationID(this.jmsCorrelationID); - byte[] testbytes = msg.getJMSCorrelationIDAsBytes(); - String str2 = new String(testbytes); - assertTrue(this.jmsCorrelationID.equals(str2)); - } - - public void testSetJMSCorrelationIDAsBytes() throws Exception { - ActiveMQMessage msg = new ActiveMQMessage(); - byte[] testbytes = this.jmsCorrelationID.getBytes(); - msg.setJMSCorrelationIDAsBytes(testbytes); - testbytes = msg.getJMSCorrelationIDAsBytes(); - String str2 = new String(testbytes); - assertTrue(this.jmsCorrelationID.equals(str2)); - } - - public void testGetAndSetJMSCorrelationID() { - ActiveMQMessage msg = new ActiveMQMessage(); - msg.setJMSCorrelationID(this.jmsCorrelationID); - assertTrue(msg.getJMSCorrelationID().equals(this.jmsCorrelationID)); - } - - public void testGetAndSetJMSReplyTo() throws JMSException { - ActiveMQMessage msg = new ActiveMQMessage(); - msg.setJMSReplyTo(this.jmsReplyTo); - assertTrue(msg.getJMSReplyTo().equals(this.jmsReplyTo)); - } - - public void testGetAndSetJMSDestination() throws Exception { - ActiveMQMessage msg = new ActiveMQMessage(); - msg.setJMSDestination(this.jmsDestination); - assertTrue(msg.getJMSDestination().equals(this.jmsDestination)); - } - - public void testGetAndSetJMSDeliveryMode() { - ActiveMQMessage msg = new ActiveMQMessage(); - msg.setJMSDeliveryMode(this.jmsDeliveryMode); - assertTrue(msg.getJMSDeliveryMode() == this.jmsDeliveryMode); - } - - public void testGetAndSetMSRedelivered() { - ActiveMQMessage msg = new ActiveMQMessage(); - msg.setJMSRedelivered(this.jmsRedelivered); - assertTrue(msg.getJMSRedelivered() == this.jmsRedelivered); - } - - public void testGetAndSetJMSType() { - ActiveMQMessage msg = new ActiveMQMessage(); - msg.setJMSType(this.jmsType); - assertTrue(msg.getJMSType().equals(this.jmsType)); - } - - public void testGetAndSetJMSExpiration() { - ActiveMQMessage msg = new ActiveMQMessage(); - msg.setJMSExpiration(this.jmsExpiration); - assertTrue(msg.getJMSExpiration() == this.jmsExpiration); - } - - public void testGetAndSetJMSPriority() { - ActiveMQMessage msg = new ActiveMQMessage(); - msg.setJMSPriority(this.jmsPriority); - assertTrue(msg.getJMSPriority() == this.jmsPriority); - - msg.setJMSPriority(-90); - assertEquals(0, msg.getJMSPriority()); - - msg.setJMSPriority(90); - assertEquals(9, msg.getJMSPriority()); - } - - public void testClearProperties() throws JMSException { - ActiveMQMessage msg = new ActiveMQMessage(); - msg.setStringProperty("test", "test"); - msg.setContent(new ByteSequence(new byte[1], 0, 0)); - msg.setJMSMessageID(this.jmsMessageID); - msg.clearProperties(); - assertNull(msg.getStringProperty("test")); - assertNotNull(msg.getJMSMessageID()); - assertNotNull(msg.getContent()); - } - - public void testPropertyExists() throws JMSException { - ActiveMQMessage msg = new ActiveMQMessage(); - msg.setStringProperty("test", "test"); - assertTrue(msg.propertyExists("test")); - - msg.setIntProperty("JMSXDeliveryCount", 1); - assertTrue(msg.propertyExists("JMSXDeliveryCount")); - } - - public void testGetBooleanProperty() throws JMSException { - ActiveMQMessage msg = new ActiveMQMessage(); - String name = "booleanProperty"; - msg.setBooleanProperty(name, true); - assertTrue(msg.getBooleanProperty(name)); - } - - public void testGetByteProperty() throws JMSException { - ActiveMQMessage msg = new ActiveMQMessage(); - String name = "byteProperty"; - msg.setByteProperty(name, (byte) 1); - assertTrue(msg.getByteProperty(name) == 1); - } - - public void testGetShortProperty() throws JMSException { - ActiveMQMessage msg = new ActiveMQMessage(); - String name = "shortProperty"; - msg.setShortProperty(name, (short) 1); - assertTrue(msg.getShortProperty(name) == 1); - } - - public void testGetIntProperty() throws JMSException { - ActiveMQMessage msg = new ActiveMQMessage(); - String name = "intProperty"; - msg.setIntProperty(name, 1); - assertTrue(msg.getIntProperty(name) == 1); - } - - public void testGetLongProperty() throws JMSException { - ActiveMQMessage msg = new ActiveMQMessage(); - String name = "longProperty"; - msg.setLongProperty(name, 1); - assertTrue(msg.getLongProperty(name) == 1); - } - - public void testGetFloatProperty() throws JMSException { - ActiveMQMessage msg = new ActiveMQMessage(); - String name = "floatProperty"; - msg.setFloatProperty(name, 1.3f); - assertTrue(msg.getFloatProperty(name) == 1.3f); - } - - public void testGetDoubleProperty() throws JMSException { - ActiveMQMessage msg = new ActiveMQMessage(); - String name = "doubleProperty"; - msg.setDoubleProperty(name, 1.3d); - assertTrue(msg.getDoubleProperty(name) == 1.3); - } - - public void testGetStringProperty() throws JMSException { - ActiveMQMessage msg = new ActiveMQMessage(); - String name = "stringProperty"; - msg.setStringProperty(name, name); - assertTrue(msg.getStringProperty(name).equals(name)); - } - - public void testGetObjectProperty() throws JMSException { - ActiveMQMessage msg = new ActiveMQMessage(); - String name = "floatProperty"; - msg.setFloatProperty(name, 1.3f); - assertTrue(msg.getObjectProperty(name) instanceof Float); - assertTrue(((Float) msg.getObjectProperty(name)).floatValue() == 1.3f); - } - - public void testSetJMSDeliveryModeProperty() throws JMSException { - ActiveMQMessage message = new ActiveMQMessage(); - String propertyName = "JMSDeliveryMode"; - - // Set as Boolean - message.setObjectProperty(propertyName, Boolean.TRUE); - assertTrue(message.isPersistent()); - message.setObjectProperty(propertyName, Boolean.FALSE); - assertFalse(message.isPersistent()); - message.setBooleanProperty(propertyName, true); - assertTrue(message.isPersistent()); - message.setBooleanProperty(propertyName, false); - assertFalse(message.isPersistent()); - - // Set as Integer - message.setObjectProperty(propertyName, DeliveryMode.PERSISTENT); - assertTrue(message.isPersistent()); - message.setObjectProperty(propertyName, DeliveryMode.NON_PERSISTENT); - assertFalse(message.isPersistent()); - message.setIntProperty(propertyName, DeliveryMode.PERSISTENT); - assertTrue(message.isPersistent()); - message.setIntProperty(propertyName, DeliveryMode.NON_PERSISTENT); - assertFalse(message.isPersistent()); - - // Set as String - message.setObjectProperty(propertyName, "PERSISTENT"); - assertTrue(message.isPersistent()); - message.setObjectProperty(propertyName, "NON_PERSISTENT"); - assertFalse(message.isPersistent()); - message.setStringProperty(propertyName, "PERSISTENT"); - assertTrue(message.isPersistent()); - message.setStringProperty(propertyName, "NON_PERSISTENT"); - assertFalse(message.isPersistent()); - } - - @SuppressWarnings("rawtypes") - public void testGetPropertyNames() throws JMSException { - ActiveMQMessage msg = new ActiveMQMessage(); - String name1 = "floatProperty"; - msg.setFloatProperty(name1, 1.3f); - String name2 = "JMSXDeliveryCount"; - msg.setIntProperty(name2, 1); - String name3 = "JMSRedelivered"; - msg.setBooleanProperty(name3, false); - boolean found1 = false; - boolean found2 = false; - boolean found3 = false; - for (Enumeration iter = msg.getPropertyNames(); iter.hasMoreElements();) { - Object element = iter.nextElement(); - found1 |= element.equals(name1); - found2 |= element.equals(name2); - found3 |= element.equals(name3); - } - assertTrue("prop name1 found", found1); - // spec compliance, only non JMS (and JMSX) props returned - assertFalse("prop name2 not found", found2); - assertFalse("prop name4 not found", found3); - } - - @SuppressWarnings("rawtypes") - public void testGetAllPropertyNames() throws JMSException { - ActiveMQMessage msg = new ActiveMQMessage(); - String name1 = "floatProperty"; - msg.setFloatProperty(name1, 1.3f); - String name2 = "JMSXDeliveryCount"; - msg.setIntProperty(name2, 1); - String name3 = "JMSRedelivered"; - msg.setBooleanProperty(name3, false); - boolean found1 = false; - boolean found2 = false; - boolean found3 = false; - for (Enumeration iter = msg.getAllPropertyNames(); iter.hasMoreElements();) { - Object element = iter.nextElement(); - found1 |= element.equals(name1); - found2 |= element.equals(name2); - found3 |= element.equals(name3); - } - assertTrue("prop name1 found", found1); - assertTrue("prop name2 found", found2); - assertTrue("prop name4 found", found3); - } - - public void testSetObjectProperty() throws JMSException { - ActiveMQMessage msg = new ActiveMQMessage(); - String name = "property"; - - try { - msg.setObjectProperty(name, "string"); - msg.setObjectProperty(name, Byte.valueOf("1")); - msg.setObjectProperty(name, Short.valueOf("1")); - msg.setObjectProperty(name, Integer.valueOf("1")); - msg.setObjectProperty(name, Long.valueOf("1")); - msg.setObjectProperty(name, Float.valueOf("1.1f")); - msg.setObjectProperty(name, Double.valueOf("1.1")); - msg.setObjectProperty(name, Boolean.TRUE); - msg.setObjectProperty(name, null); - } catch (MessageFormatException e) { - fail("should accept object primitives and String"); - } - try { - msg.setObjectProperty(name, new byte[5]); - fail("should accept only object primitives and String"); - } catch (MessageFormatException e) { - } - try { - msg.setObjectProperty(name, new Object()); - fail("should accept only object primitives and String"); - } catch (MessageFormatException e) { - } - } - - public void testConvertProperties() throws Exception { - org.apache.activemq.command.Message msg = new org.apache.activemq.command.Message() { - @Override - public org.apache.activemq.command.Message copy() { - return null; - } - - @Override - public void beforeMarshall(WireFormat wireFormat) throws IOException { - super.beforeMarshall(wireFormat); - } - - @Override - public byte getDataStructureType() { - return 0; - } - - @Override - public Response visit(CommandVisitor visitor) throws Exception { - return null; - } - - @Override - public void clearBody() throws JMSException { - } - - @Override - public void storeContent() { - } - - @Override - public void storeContentAndClear() { - - } - }; - - msg.setProperty("stringProperty", "string"); - msg.setProperty("byteProperty", Byte.valueOf("1")); - msg.setProperty("shortProperty", Short.valueOf("1")); - msg.setProperty("intProperty", Integer.valueOf("1")); - msg.setProperty("longProperty", Long.valueOf("1")); - msg.setProperty("floatProperty", Float.valueOf("1.1f")); - msg.setProperty("doubleProperty", Double.valueOf("1.1")); - msg.setProperty("booleanProperty", Boolean.TRUE); - msg.setProperty("nullProperty", null); - - msg.beforeMarshall(new OpenWireFormat()); - - Map properties = msg.getProperties(); - assertEquals(properties.get("stringProperty"), "string"); - assertEquals(((Byte) properties.get("byteProperty")).byteValue(), 1); - assertEquals(((Short) properties.get("shortProperty")).shortValue(), 1); - assertEquals(((Integer) properties.get("intProperty")).intValue(), 1); - assertEquals(((Long) properties.get("longProperty")).longValue(), 1); - assertEquals(((Float) properties.get("floatProperty")).floatValue(), 1.1f, 0); - assertEquals(((Double) properties.get("doubleProperty")).doubleValue(), 1.1, 0); - assertEquals(((Boolean) properties.get("booleanProperty")).booleanValue(), true); - assertNull(properties.get("nullProperty")); - } - - public void testSetNullProperty() throws JMSException { - Message msg = new ActiveMQMessage(); - String name = "cheese"; - msg.setStringProperty(name, "Cheddar"); - assertEquals("Cheddar", msg.getStringProperty(name)); - - msg.setStringProperty(name, null); - assertEquals(null, msg.getStringProperty(name)); - } - - public void testSetNullPropertyName() throws JMSException { - Message msg = new ActiveMQMessage(); - - try { - msg.setStringProperty(null, "Cheese"); - fail("Should have thrown exception"); - } catch (IllegalArgumentException e) { - LOG.info("Worked, caught: " + e); - } - } - - public void testSetEmptyPropertyName() throws JMSException { - Message msg = new ActiveMQMessage(); - - try { - msg.setStringProperty("", "Cheese"); - fail("Should have thrown exception"); - } catch (IllegalArgumentException e) { - LOG.info("Worked, caught: " + e); - } - } - - public void testGetAndSetJMSXDeliveryCount() throws JMSException { - Message msg = new ActiveMQMessage(); - msg.setIntProperty("JMSXDeliveryCount", 1); - int count = msg.getIntProperty("JMSXDeliveryCount"); - assertTrue("expected delivery count = 1 - got: " + count, count == 1); - } - - public void testClearBody() throws JMSException { - ActiveMQBytesMessage message = new ActiveMQBytesMessage(); - message.clearBody(); - assertFalse(message.isReadOnlyBody()); - assertNull(message.getContent()); - } - - public void testBooleanPropertyConversion() throws JMSException { - ActiveMQMessage msg = new ActiveMQMessage(); - String propertyName = "property"; - msg.setBooleanProperty(propertyName, true); - - assertEquals(((Boolean) msg.getObjectProperty(propertyName)).booleanValue(), true); - assertTrue(msg.getBooleanProperty(propertyName)); - assertEquals(msg.getStringProperty(propertyName), "true"); - try { - msg.getByteProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getShortProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getIntProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getLongProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getFloatProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getDoubleProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - } - - public void testBytePropertyConversion() throws JMSException { - ActiveMQMessage msg = new ActiveMQMessage(); - String propertyName = "property"; - msg.setByteProperty(propertyName, (byte) 1); - - assertEquals(((Byte) msg.getObjectProperty(propertyName)).byteValue(), 1); - assertEquals(msg.getByteProperty(propertyName), 1); - assertEquals(msg.getShortProperty(propertyName), 1); - assertEquals(msg.getIntProperty(propertyName), 1); - assertEquals(msg.getLongProperty(propertyName), 1); - assertEquals(msg.getStringProperty(propertyName), "1"); - try { - msg.getBooleanProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getFloatProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getDoubleProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - } - - public void testShortPropertyConversion() throws JMSException { - ActiveMQMessage msg = new ActiveMQMessage(); - String propertyName = "property"; - msg.setShortProperty(propertyName, (short) 1); - - assertEquals(((Short) msg.getObjectProperty(propertyName)).shortValue(), 1); - assertEquals(msg.getShortProperty(propertyName), 1); - assertEquals(msg.getIntProperty(propertyName), 1); - assertEquals(msg.getLongProperty(propertyName), 1); - assertEquals(msg.getStringProperty(propertyName), "1"); - try { - msg.getBooleanProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getByteProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getFloatProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getDoubleProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - } - - public void testIntPropertyConversion() throws JMSException { - ActiveMQMessage msg = new ActiveMQMessage(); - String propertyName = "property"; - msg.setIntProperty(propertyName, 1); - - assertEquals(((Integer) msg.getObjectProperty(propertyName)).intValue(), 1); - assertEquals(msg.getIntProperty(propertyName), 1); - assertEquals(msg.getLongProperty(propertyName), 1); - assertEquals(msg.getStringProperty(propertyName), "1"); - try { - msg.getBooleanProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getByteProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getShortProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getFloatProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getDoubleProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - } - - public void testLongPropertyConversion() throws JMSException { - ActiveMQMessage msg = new ActiveMQMessage(); - String propertyName = "property"; - msg.setLongProperty(propertyName, 1); - - assertEquals(((Long) msg.getObjectProperty(propertyName)).longValue(), 1); - assertEquals(msg.getLongProperty(propertyName), 1); - assertEquals(msg.getStringProperty(propertyName), "1"); - try { - msg.getBooleanProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getByteProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getShortProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getIntProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getFloatProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getDoubleProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - } - - public void testFloatPropertyConversion() throws JMSException { - ActiveMQMessage msg = new ActiveMQMessage(); - String propertyName = "property"; - msg.setFloatProperty(propertyName, (float) 1.5); - assertEquals(((Float) msg.getObjectProperty(propertyName)).floatValue(), 1.5, 0); - assertEquals(msg.getFloatProperty(propertyName), 1.5, 0); - assertEquals(msg.getDoubleProperty(propertyName), 1.5, 0); - assertEquals(msg.getStringProperty(propertyName), "1.5"); - try { - msg.getBooleanProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getByteProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getShortProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getIntProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getLongProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - } - - public void testDoublePropertyConversion() throws JMSException { - ActiveMQMessage msg = new ActiveMQMessage(); - String propertyName = "property"; - msg.setDoubleProperty(propertyName, 1.5); - assertEquals(((Double) msg.getObjectProperty(propertyName)).doubleValue(), 1.5, 0); - assertEquals(msg.getDoubleProperty(propertyName), 1.5, 0); - assertEquals(msg.getStringProperty(propertyName), "1.5"); - try { - msg.getBooleanProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getByteProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getShortProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getIntProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getLongProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getFloatProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - } - - public void testStringPropertyConversion() throws JMSException { - ActiveMQMessage msg = new ActiveMQMessage(); - String propertyName = "property"; - String stringValue = "true"; - msg.setStringProperty(propertyName, stringValue); - assertEquals(msg.getStringProperty(propertyName), stringValue); - assertEquals((String) msg.getObjectProperty(propertyName), stringValue); - assertEquals(msg.getBooleanProperty(propertyName), true); - - stringValue = "1"; - msg.setStringProperty(propertyName, stringValue); - assertEquals(msg.getByteProperty(propertyName), 1); - assertEquals(msg.getShortProperty(propertyName), 1); - assertEquals(msg.getIntProperty(propertyName), 1); - assertEquals(msg.getLongProperty(propertyName), 1); - - stringValue = "1.5"; - msg.setStringProperty(propertyName, stringValue); - assertEquals(msg.getFloatProperty(propertyName), 1.5, 0); - assertEquals(msg.getDoubleProperty(propertyName), 1.5, 0); - - stringValue = "bad"; - msg.setStringProperty(propertyName, stringValue); - try { - msg.getByteProperty(propertyName); - fail("Should have thrown exception"); - } catch (NumberFormatException e) { - } - try { - msg.getShortProperty(propertyName); - fail("Should have thrown exception"); - } catch (NumberFormatException e) { - } - try { - msg.getIntProperty(propertyName); - fail("Should have thrown exception"); - } catch (NumberFormatException e) { - } - try { - msg.getLongProperty(propertyName); - fail("Should have thrown exception"); - } catch (NumberFormatException e) { - } - try { - msg.getFloatProperty(propertyName); - fail("Should have thrown exception"); - } catch (NumberFormatException e) { - } - try { - msg.getDoubleProperty(propertyName); - fail("Should have thrown exception"); - } catch (NumberFormatException e) { - } - assertFalse(msg.getBooleanProperty(propertyName)); - } - - public void testObjectPropertyConversion() throws JMSException { - ActiveMQMessage msg = new ActiveMQMessage(); - String propertyName = "property"; - Object obj = new Object(); - try { - ((org.apache.activemq.command.Message) msg).setProperty(propertyName, obj); // bypass - // object - // check - } catch (IOException e) { - } - try { - msg.getStringProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getBooleanProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getByteProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getShortProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getIntProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getLongProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getFloatProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - try { - msg.getDoubleProperty(propertyName); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - - } - - public void testReadOnlyProperties() throws JMSException { - ActiveMQMessage msg = new ActiveMQMessage(); - String propertyName = "property"; - msg.setReadOnlyProperties(true); - - try { - msg.setObjectProperty(propertyName, new Object()); - fail("Should have thrown exception"); - } catch (MessageNotWriteableException e) { - } - try { - msg.setStringProperty(propertyName, "test"); - fail("Should have thrown exception"); - } catch (MessageNotWriteableException e) { - } - try { - msg.setBooleanProperty(propertyName, true); - fail("Should have thrown exception"); - } catch (MessageNotWriteableException e) { - } - try { - msg.setByteProperty(propertyName, (byte) 1); - fail("Should have thrown exception"); - } catch (MessageNotWriteableException e) { - } - try { - msg.setShortProperty(propertyName, (short) 1); - fail("Should have thrown exception"); - } catch (MessageNotWriteableException e) { - } - try { - msg.setIntProperty(propertyName, 1); - fail("Should have thrown exception"); - } catch (MessageNotWriteableException e) { - } - try { - msg.setLongProperty(propertyName, 1); - fail("Should have thrown exception"); - } catch (MessageNotWriteableException e) { - } - try { - msg.setFloatProperty(propertyName, (float) 1.5); - fail("Should have thrown exception"); - } catch (MessageNotWriteableException e) { - } - try { - msg.setDoubleProperty(propertyName, 1.5); - fail("Should have thrown exception"); - } catch (MessageNotWriteableException e) { - } - } - - public void testIsExpired() { - ActiveMQMessage msg = new ActiveMQMessage(); - msg.setJMSExpiration(System.currentTimeMillis() - 1); - assertTrue(msg.isExpired()); - msg.setJMSExpiration(System.currentTimeMillis() + 10000); - assertFalse(msg.isExpired()); - } + private static final Logger LOG = LoggerFactory.getLogger(ActiveMQMessageTest.class); + + protected boolean readOnlyMessage; + + private String jmsMessageID; + private String jmsCorrelationID; + private ActiveMQDestination jmsDestination; + private ActiveMQDestination jmsReplyTo; + private int jmsDeliveryMode; + private boolean jmsRedelivered; + private String jmsType; + private long jmsExpiration; + private int jmsPriority; + private long jmsTimestamp; + private long[] consumerIDs; + + /** + * Constructor for ActiveMQMessageTest. + * + * @param name + */ + public ActiveMQMessageTest(String name) { + super(name); + } + + public static void main(String[] args) { + } + + /* + * @see TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + this.jmsMessageID = "ID:TEST-ID:0:0:0:1"; + this.jmsCorrelationID = "testcorrelationid"; + this.jmsDestination = new ActiveMQTopic("test.topic"); + this.jmsReplyTo = new ActiveMQTempTopic("test.replyto.topic:001"); + this.jmsDeliveryMode = Message.DEFAULT_DELIVERY_MODE; + this.jmsRedelivered = true; + this.jmsType = "test type"; + this.jmsExpiration = 100000; + this.jmsPriority = 5; + this.jmsTimestamp = System.currentTimeMillis(); + this.readOnlyMessage = false; + this.consumerIDs = new long[3]; + for (int i = 0; i < this.consumerIDs.length; i++) { + this.consumerIDs[i] = i; + } + } + + /* + * @see TestCase#tearDown() + */ + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testGetDataStructureType() { + ActiveMQMessage msg = new ActiveMQMessage(); + assertEquals(msg.getDataStructureType(), CommandTypes.ACTIVEMQ_MESSAGE); + } + + public void testHashCode() throws Exception { + ActiveMQMessage msg = new ActiveMQMessage(); + msg.setJMSMessageID(this.jmsMessageID); + assertTrue(msg.getJMSMessageID().hashCode() == jmsMessageID.hashCode()); + } + + public void testSetReadOnly() { + ActiveMQMessage msg = new ActiveMQMessage(); + msg.setReadOnlyProperties(true); + boolean test = false; + try { + msg.setIntProperty("test", 1); + } + catch (MessageNotWriteableException me) { + test = true; + } + catch (JMSException e) { + e.printStackTrace(System.err); + test = false; + } + assertTrue(test); + } + + public void testSetToForeignJMSID() throws Exception { + ActiveMQMessage msg = new ActiveMQMessage(); + msg.setJMSMessageID("ID:EMS-SERVER.8B443C380083:429"); + } + + /* + * Class to test for boolean equals(Object) + */ + public void testEqualsObject() throws Exception { + ActiveMQMessage msg1 = new ActiveMQMessage(); + ActiveMQMessage msg2 = new ActiveMQMessage(); + msg1.setJMSMessageID(this.jmsMessageID); + assertTrue(!msg1.equals(msg2)); + msg2.setJMSMessageID(this.jmsMessageID); + assertTrue(msg1.equals(msg2)); + } + + public void testShallowCopy() throws Exception { + ActiveMQMessage msg1 = new ActiveMQMessage(); + msg1.setJMSMessageID(jmsMessageID); + ActiveMQMessage msg2 = (ActiveMQMessage) msg1.copy(); + assertTrue(msg1 != msg2 && msg1.equals(msg2)); + } + + public void testCopy() throws Exception { + this.jmsMessageID = "testid"; + this.jmsCorrelationID = "testcorrelationid"; + this.jmsDestination = new ActiveMQTopic("test.topic"); + this.jmsReplyTo = new ActiveMQTempTopic("test.replyto.topic:001"); + this.jmsDeliveryMode = Message.DEFAULT_DELIVERY_MODE; + this.jmsRedelivered = true; + this.jmsType = "test type"; + this.jmsExpiration = 100000; + this.jmsPriority = 5; + this.jmsTimestamp = System.currentTimeMillis(); + this.readOnlyMessage = false; + + ActiveMQMessage msg1 = new ActiveMQMessage(); + msg1.setJMSMessageID(this.jmsMessageID); + msg1.setJMSCorrelationID(this.jmsCorrelationID); + msg1.setJMSDestination(this.jmsDestination); + msg1.setJMSReplyTo(this.jmsReplyTo); + msg1.setJMSDeliveryMode(this.jmsDeliveryMode); + msg1.setJMSRedelivered(this.jmsRedelivered); + msg1.setJMSType(this.jmsType); + msg1.setJMSExpiration(this.jmsExpiration); + msg1.setJMSPriority(this.jmsPriority); + msg1.setJMSTimestamp(this.jmsTimestamp); + msg1.setReadOnlyProperties(true); + ActiveMQMessage msg2 = new ActiveMQMessage(); + msg1.copy(msg2); + assertEquals(msg1.getJMSMessageID(), msg2.getJMSMessageID()); + assertTrue(msg1.getJMSCorrelationID().equals(msg2.getJMSCorrelationID())); + assertTrue(msg1.getJMSDestination().equals(msg2.getJMSDestination())); + assertTrue(msg1.getJMSReplyTo().equals(msg2.getJMSReplyTo())); + assertTrue(msg1.getJMSDeliveryMode() == msg2.getJMSDeliveryMode()); + assertTrue(msg1.getJMSRedelivered() == msg2.getJMSRedelivered()); + assertTrue(msg1.getJMSType().equals(msg2.getJMSType())); + assertTrue(msg1.getJMSExpiration() == msg2.getJMSExpiration()); + assertTrue(msg1.getJMSPriority() == msg2.getJMSPriority()); + assertTrue(msg1.getJMSTimestamp() == msg2.getJMSTimestamp()); + + LOG.info("Message is: " + msg1); + } + + public void testGetAndSetJMSMessageID() throws Exception { + ActiveMQMessage msg = new ActiveMQMessage(); + msg.setJMSMessageID(this.jmsMessageID); + assertEquals(msg.getJMSMessageID(), this.jmsMessageID); + } + + public void testGetAndSetJMSTimestamp() { + ActiveMQMessage msg = new ActiveMQMessage(); + msg.setJMSTimestamp(this.jmsTimestamp); + assertTrue(msg.getJMSTimestamp() == this.jmsTimestamp); + } + + public void testGetJMSCorrelationIDAsBytes() throws Exception { + ActiveMQMessage msg = new ActiveMQMessage(); + msg.setJMSCorrelationID(this.jmsCorrelationID); + byte[] testbytes = msg.getJMSCorrelationIDAsBytes(); + String str2 = new String(testbytes); + assertTrue(this.jmsCorrelationID.equals(str2)); + } + + public void testSetJMSCorrelationIDAsBytes() throws Exception { + ActiveMQMessage msg = new ActiveMQMessage(); + byte[] testbytes = this.jmsCorrelationID.getBytes(); + msg.setJMSCorrelationIDAsBytes(testbytes); + testbytes = msg.getJMSCorrelationIDAsBytes(); + String str2 = new String(testbytes); + assertTrue(this.jmsCorrelationID.equals(str2)); + } + + public void testGetAndSetJMSCorrelationID() { + ActiveMQMessage msg = new ActiveMQMessage(); + msg.setJMSCorrelationID(this.jmsCorrelationID); + assertTrue(msg.getJMSCorrelationID().equals(this.jmsCorrelationID)); + } + + public void testGetAndSetJMSReplyTo() throws JMSException { + ActiveMQMessage msg = new ActiveMQMessage(); + msg.setJMSReplyTo(this.jmsReplyTo); + assertTrue(msg.getJMSReplyTo().equals(this.jmsReplyTo)); + } + + public void testGetAndSetJMSDestination() throws Exception { + ActiveMQMessage msg = new ActiveMQMessage(); + msg.setJMSDestination(this.jmsDestination); + assertTrue(msg.getJMSDestination().equals(this.jmsDestination)); + } + + public void testGetAndSetJMSDeliveryMode() { + ActiveMQMessage msg = new ActiveMQMessage(); + msg.setJMSDeliveryMode(this.jmsDeliveryMode); + assertTrue(msg.getJMSDeliveryMode() == this.jmsDeliveryMode); + } + + public void testGetAndSetMSRedelivered() { + ActiveMQMessage msg = new ActiveMQMessage(); + msg.setJMSRedelivered(this.jmsRedelivered); + assertTrue(msg.getJMSRedelivered() == this.jmsRedelivered); + } + + public void testGetAndSetJMSType() { + ActiveMQMessage msg = new ActiveMQMessage(); + msg.setJMSType(this.jmsType); + assertTrue(msg.getJMSType().equals(this.jmsType)); + } + + public void testGetAndSetJMSExpiration() { + ActiveMQMessage msg = new ActiveMQMessage(); + msg.setJMSExpiration(this.jmsExpiration); + assertTrue(msg.getJMSExpiration() == this.jmsExpiration); + } + + public void testGetAndSetJMSPriority() { + ActiveMQMessage msg = new ActiveMQMessage(); + msg.setJMSPriority(this.jmsPriority); + assertTrue(msg.getJMSPriority() == this.jmsPriority); + + msg.setJMSPriority(-90); + assertEquals(0, msg.getJMSPriority()); + + msg.setJMSPriority(90); + assertEquals(9, msg.getJMSPriority()); + } + + public void testClearProperties() throws JMSException { + ActiveMQMessage msg = new ActiveMQMessage(); + msg.setStringProperty("test", "test"); + msg.setContent(new ByteSequence(new byte[1], 0, 0)); + msg.setJMSMessageID(this.jmsMessageID); + msg.clearProperties(); + assertNull(msg.getStringProperty("test")); + assertNotNull(msg.getJMSMessageID()); + assertNotNull(msg.getContent()); + } + + public void testPropertyExists() throws JMSException { + ActiveMQMessage msg = new ActiveMQMessage(); + msg.setStringProperty("test", "test"); + assertTrue(msg.propertyExists("test")); + + msg.setIntProperty("JMSXDeliveryCount", 1); + assertTrue(msg.propertyExists("JMSXDeliveryCount")); + } + + public void testGetBooleanProperty() throws JMSException { + ActiveMQMessage msg = new ActiveMQMessage(); + String name = "booleanProperty"; + msg.setBooleanProperty(name, true); + assertTrue(msg.getBooleanProperty(name)); + } + + public void testGetByteProperty() throws JMSException { + ActiveMQMessage msg = new ActiveMQMessage(); + String name = "byteProperty"; + msg.setByteProperty(name, (byte) 1); + assertTrue(msg.getByteProperty(name) == 1); + } + + public void testGetShortProperty() throws JMSException { + ActiveMQMessage msg = new ActiveMQMessage(); + String name = "shortProperty"; + msg.setShortProperty(name, (short) 1); + assertTrue(msg.getShortProperty(name) == 1); + } + + public void testGetIntProperty() throws JMSException { + ActiveMQMessage msg = new ActiveMQMessage(); + String name = "intProperty"; + msg.setIntProperty(name, 1); + assertTrue(msg.getIntProperty(name) == 1); + } + + public void testGetLongProperty() throws JMSException { + ActiveMQMessage msg = new ActiveMQMessage(); + String name = "longProperty"; + msg.setLongProperty(name, 1); + assertTrue(msg.getLongProperty(name) == 1); + } + + public void testGetFloatProperty() throws JMSException { + ActiveMQMessage msg = new ActiveMQMessage(); + String name = "floatProperty"; + msg.setFloatProperty(name, 1.3f); + assertTrue(msg.getFloatProperty(name) == 1.3f); + } + + public void testGetDoubleProperty() throws JMSException { + ActiveMQMessage msg = new ActiveMQMessage(); + String name = "doubleProperty"; + msg.setDoubleProperty(name, 1.3d); + assertTrue(msg.getDoubleProperty(name) == 1.3); + } + + public void testGetStringProperty() throws JMSException { + ActiveMQMessage msg = new ActiveMQMessage(); + String name = "stringProperty"; + msg.setStringProperty(name, name); + assertTrue(msg.getStringProperty(name).equals(name)); + } + + public void testGetObjectProperty() throws JMSException { + ActiveMQMessage msg = new ActiveMQMessage(); + String name = "floatProperty"; + msg.setFloatProperty(name, 1.3f); + assertTrue(msg.getObjectProperty(name) instanceof Float); + assertTrue(((Float) msg.getObjectProperty(name)).floatValue() == 1.3f); + } + + public void testSetJMSDeliveryModeProperty() throws JMSException { + ActiveMQMessage message = new ActiveMQMessage(); + String propertyName = "JMSDeliveryMode"; + + // Set as Boolean + message.setObjectProperty(propertyName, Boolean.TRUE); + assertTrue(message.isPersistent()); + message.setObjectProperty(propertyName, Boolean.FALSE); + assertFalse(message.isPersistent()); + message.setBooleanProperty(propertyName, true); + assertTrue(message.isPersistent()); + message.setBooleanProperty(propertyName, false); + assertFalse(message.isPersistent()); + + // Set as Integer + message.setObjectProperty(propertyName, DeliveryMode.PERSISTENT); + assertTrue(message.isPersistent()); + message.setObjectProperty(propertyName, DeliveryMode.NON_PERSISTENT); + assertFalse(message.isPersistent()); + message.setIntProperty(propertyName, DeliveryMode.PERSISTENT); + assertTrue(message.isPersistent()); + message.setIntProperty(propertyName, DeliveryMode.NON_PERSISTENT); + assertFalse(message.isPersistent()); + + // Set as String + message.setObjectProperty(propertyName, "PERSISTENT"); + assertTrue(message.isPersistent()); + message.setObjectProperty(propertyName, "NON_PERSISTENT"); + assertFalse(message.isPersistent()); + message.setStringProperty(propertyName, "PERSISTENT"); + assertTrue(message.isPersistent()); + message.setStringProperty(propertyName, "NON_PERSISTENT"); + assertFalse(message.isPersistent()); + } + + @SuppressWarnings("rawtypes") + public void testGetPropertyNames() throws JMSException { + ActiveMQMessage msg = new ActiveMQMessage(); + String name1 = "floatProperty"; + msg.setFloatProperty(name1, 1.3f); + String name2 = "JMSXDeliveryCount"; + msg.setIntProperty(name2, 1); + String name3 = "JMSRedelivered"; + msg.setBooleanProperty(name3, false); + boolean found1 = false; + boolean found2 = false; + boolean found3 = false; + for (Enumeration iter = msg.getPropertyNames(); iter.hasMoreElements(); ) { + Object element = iter.nextElement(); + found1 |= element.equals(name1); + found2 |= element.equals(name2); + found3 |= element.equals(name3); + } + assertTrue("prop name1 found", found1); + // spec compliance, only non JMS (and JMSX) props returned + assertFalse("prop name2 not found", found2); + assertFalse("prop name4 not found", found3); + } + + @SuppressWarnings("rawtypes") + public void testGetAllPropertyNames() throws JMSException { + ActiveMQMessage msg = new ActiveMQMessage(); + String name1 = "floatProperty"; + msg.setFloatProperty(name1, 1.3f); + String name2 = "JMSXDeliveryCount"; + msg.setIntProperty(name2, 1); + String name3 = "JMSRedelivered"; + msg.setBooleanProperty(name3, false); + boolean found1 = false; + boolean found2 = false; + boolean found3 = false; + for (Enumeration iter = msg.getAllPropertyNames(); iter.hasMoreElements(); ) { + Object element = iter.nextElement(); + found1 |= element.equals(name1); + found2 |= element.equals(name2); + found3 |= element.equals(name3); + } + assertTrue("prop name1 found", found1); + assertTrue("prop name2 found", found2); + assertTrue("prop name4 found", found3); + } + + public void testSetObjectProperty() throws JMSException { + ActiveMQMessage msg = new ActiveMQMessage(); + String name = "property"; + + try { + msg.setObjectProperty(name, "string"); + msg.setObjectProperty(name, Byte.valueOf("1")); + msg.setObjectProperty(name, Short.valueOf("1")); + msg.setObjectProperty(name, Integer.valueOf("1")); + msg.setObjectProperty(name, Long.valueOf("1")); + msg.setObjectProperty(name, Float.valueOf("1.1f")); + msg.setObjectProperty(name, Double.valueOf("1.1")); + msg.setObjectProperty(name, Boolean.TRUE); + msg.setObjectProperty(name, null); + } + catch (MessageFormatException e) { + fail("should accept object primitives and String"); + } + try { + msg.setObjectProperty(name, new byte[5]); + fail("should accept only object primitives and String"); + } + catch (MessageFormatException e) { + } + try { + msg.setObjectProperty(name, new Object()); + fail("should accept only object primitives and String"); + } + catch (MessageFormatException e) { + } + } + + public void testConvertProperties() throws Exception { + org.apache.activemq.command.Message msg = new org.apache.activemq.command.Message() { + @Override + public org.apache.activemq.command.Message copy() { + return null; + } + + @Override + public void beforeMarshall(WireFormat wireFormat) throws IOException { + super.beforeMarshall(wireFormat); + } + + @Override + public byte getDataStructureType() { + return 0; + } + + @Override + public Response visit(CommandVisitor visitor) throws Exception { + return null; + } + + @Override + public void clearBody() throws JMSException { + } + + @Override + public void storeContent() { + } + + @Override + public void storeContentAndClear() { + + } + }; + + msg.setProperty("stringProperty", "string"); + msg.setProperty("byteProperty", Byte.valueOf("1")); + msg.setProperty("shortProperty", Short.valueOf("1")); + msg.setProperty("intProperty", Integer.valueOf("1")); + msg.setProperty("longProperty", Long.valueOf("1")); + msg.setProperty("floatProperty", Float.valueOf("1.1f")); + msg.setProperty("doubleProperty", Double.valueOf("1.1")); + msg.setProperty("booleanProperty", Boolean.TRUE); + msg.setProperty("nullProperty", null); + + msg.beforeMarshall(new OpenWireFormat()); + + Map properties = msg.getProperties(); + assertEquals(properties.get("stringProperty"), "string"); + assertEquals(((Byte) properties.get("byteProperty")).byteValue(), 1); + assertEquals(((Short) properties.get("shortProperty")).shortValue(), 1); + assertEquals(((Integer) properties.get("intProperty")).intValue(), 1); + assertEquals(((Long) properties.get("longProperty")).longValue(), 1); + assertEquals(((Float) properties.get("floatProperty")).floatValue(), 1.1f, 0); + assertEquals(((Double) properties.get("doubleProperty")).doubleValue(), 1.1, 0); + assertEquals(((Boolean) properties.get("booleanProperty")).booleanValue(), true); + assertNull(properties.get("nullProperty")); + } + + public void testSetNullProperty() throws JMSException { + Message msg = new ActiveMQMessage(); + String name = "cheese"; + msg.setStringProperty(name, "Cheddar"); + assertEquals("Cheddar", msg.getStringProperty(name)); + + msg.setStringProperty(name, null); + assertEquals(null, msg.getStringProperty(name)); + } + + public void testSetNullPropertyName() throws JMSException { + Message msg = new ActiveMQMessage(); + + try { + msg.setStringProperty(null, "Cheese"); + fail("Should have thrown exception"); + } + catch (IllegalArgumentException e) { + LOG.info("Worked, caught: " + e); + } + } + + public void testSetEmptyPropertyName() throws JMSException { + Message msg = new ActiveMQMessage(); + + try { + msg.setStringProperty("", "Cheese"); + fail("Should have thrown exception"); + } + catch (IllegalArgumentException e) { + LOG.info("Worked, caught: " + e); + } + } + + public void testGetAndSetJMSXDeliveryCount() throws JMSException { + Message msg = new ActiveMQMessage(); + msg.setIntProperty("JMSXDeliveryCount", 1); + int count = msg.getIntProperty("JMSXDeliveryCount"); + assertTrue("expected delivery count = 1 - got: " + count, count == 1); + } + + public void testClearBody() throws JMSException { + ActiveMQBytesMessage message = new ActiveMQBytesMessage(); + message.clearBody(); + assertFalse(message.isReadOnlyBody()); + assertNull(message.getContent()); + } + + public void testBooleanPropertyConversion() throws JMSException { + ActiveMQMessage msg = new ActiveMQMessage(); + String propertyName = "property"; + msg.setBooleanProperty(propertyName, true); + + assertEquals(((Boolean) msg.getObjectProperty(propertyName)).booleanValue(), true); + assertTrue(msg.getBooleanProperty(propertyName)); + assertEquals(msg.getStringProperty(propertyName), "true"); + try { + msg.getByteProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getShortProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getIntProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getLongProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getFloatProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getDoubleProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + } + + public void testBytePropertyConversion() throws JMSException { + ActiveMQMessage msg = new ActiveMQMessage(); + String propertyName = "property"; + msg.setByteProperty(propertyName, (byte) 1); + + assertEquals(((Byte) msg.getObjectProperty(propertyName)).byteValue(), 1); + assertEquals(msg.getByteProperty(propertyName), 1); + assertEquals(msg.getShortProperty(propertyName), 1); + assertEquals(msg.getIntProperty(propertyName), 1); + assertEquals(msg.getLongProperty(propertyName), 1); + assertEquals(msg.getStringProperty(propertyName), "1"); + try { + msg.getBooleanProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getFloatProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getDoubleProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + } + + public void testShortPropertyConversion() throws JMSException { + ActiveMQMessage msg = new ActiveMQMessage(); + String propertyName = "property"; + msg.setShortProperty(propertyName, (short) 1); + + assertEquals(((Short) msg.getObjectProperty(propertyName)).shortValue(), 1); + assertEquals(msg.getShortProperty(propertyName), 1); + assertEquals(msg.getIntProperty(propertyName), 1); + assertEquals(msg.getLongProperty(propertyName), 1); + assertEquals(msg.getStringProperty(propertyName), "1"); + try { + msg.getBooleanProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getByteProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getFloatProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getDoubleProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + } + + public void testIntPropertyConversion() throws JMSException { + ActiveMQMessage msg = new ActiveMQMessage(); + String propertyName = "property"; + msg.setIntProperty(propertyName, 1); + + assertEquals(((Integer) msg.getObjectProperty(propertyName)).intValue(), 1); + assertEquals(msg.getIntProperty(propertyName), 1); + assertEquals(msg.getLongProperty(propertyName), 1); + assertEquals(msg.getStringProperty(propertyName), "1"); + try { + msg.getBooleanProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getByteProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getShortProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getFloatProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getDoubleProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + } + + public void testLongPropertyConversion() throws JMSException { + ActiveMQMessage msg = new ActiveMQMessage(); + String propertyName = "property"; + msg.setLongProperty(propertyName, 1); + + assertEquals(((Long) msg.getObjectProperty(propertyName)).longValue(), 1); + assertEquals(msg.getLongProperty(propertyName), 1); + assertEquals(msg.getStringProperty(propertyName), "1"); + try { + msg.getBooleanProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getByteProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getShortProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getIntProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getFloatProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getDoubleProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + } + + public void testFloatPropertyConversion() throws JMSException { + ActiveMQMessage msg = new ActiveMQMessage(); + String propertyName = "property"; + msg.setFloatProperty(propertyName, (float) 1.5); + assertEquals(((Float) msg.getObjectProperty(propertyName)).floatValue(), 1.5, 0); + assertEquals(msg.getFloatProperty(propertyName), 1.5, 0); + assertEquals(msg.getDoubleProperty(propertyName), 1.5, 0); + assertEquals(msg.getStringProperty(propertyName), "1.5"); + try { + msg.getBooleanProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getByteProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getShortProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getIntProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getLongProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + } + + public void testDoublePropertyConversion() throws JMSException { + ActiveMQMessage msg = new ActiveMQMessage(); + String propertyName = "property"; + msg.setDoubleProperty(propertyName, 1.5); + assertEquals(((Double) msg.getObjectProperty(propertyName)).doubleValue(), 1.5, 0); + assertEquals(msg.getDoubleProperty(propertyName), 1.5, 0); + assertEquals(msg.getStringProperty(propertyName), "1.5"); + try { + msg.getBooleanProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getByteProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getShortProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getIntProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getLongProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getFloatProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + } + + public void testStringPropertyConversion() throws JMSException { + ActiveMQMessage msg = new ActiveMQMessage(); + String propertyName = "property"; + String stringValue = "true"; + msg.setStringProperty(propertyName, stringValue); + assertEquals(msg.getStringProperty(propertyName), stringValue); + assertEquals((String) msg.getObjectProperty(propertyName), stringValue); + assertEquals(msg.getBooleanProperty(propertyName), true); + + stringValue = "1"; + msg.setStringProperty(propertyName, stringValue); + assertEquals(msg.getByteProperty(propertyName), 1); + assertEquals(msg.getShortProperty(propertyName), 1); + assertEquals(msg.getIntProperty(propertyName), 1); + assertEquals(msg.getLongProperty(propertyName), 1); + + stringValue = "1.5"; + msg.setStringProperty(propertyName, stringValue); + assertEquals(msg.getFloatProperty(propertyName), 1.5, 0); + assertEquals(msg.getDoubleProperty(propertyName), 1.5, 0); + + stringValue = "bad"; + msg.setStringProperty(propertyName, stringValue); + try { + msg.getByteProperty(propertyName); + fail("Should have thrown exception"); + } + catch (NumberFormatException e) { + } + try { + msg.getShortProperty(propertyName); + fail("Should have thrown exception"); + } + catch (NumberFormatException e) { + } + try { + msg.getIntProperty(propertyName); + fail("Should have thrown exception"); + } + catch (NumberFormatException e) { + } + try { + msg.getLongProperty(propertyName); + fail("Should have thrown exception"); + } + catch (NumberFormatException e) { + } + try { + msg.getFloatProperty(propertyName); + fail("Should have thrown exception"); + } + catch (NumberFormatException e) { + } + try { + msg.getDoubleProperty(propertyName); + fail("Should have thrown exception"); + } + catch (NumberFormatException e) { + } + assertFalse(msg.getBooleanProperty(propertyName)); + } + + public void testObjectPropertyConversion() throws JMSException { + ActiveMQMessage msg = new ActiveMQMessage(); + String propertyName = "property"; + Object obj = new Object(); + try { + ((org.apache.activemq.command.Message) msg).setProperty(propertyName, obj); // bypass + // object + // check + } + catch (IOException e) { + } + try { + msg.getStringProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getBooleanProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getByteProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getShortProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getIntProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getLongProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getFloatProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + try { + msg.getDoubleProperty(propertyName); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + + } + + public void testReadOnlyProperties() throws JMSException { + ActiveMQMessage msg = new ActiveMQMessage(); + String propertyName = "property"; + msg.setReadOnlyProperties(true); + + try { + msg.setObjectProperty(propertyName, new Object()); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException e) { + } + try { + msg.setStringProperty(propertyName, "test"); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException e) { + } + try { + msg.setBooleanProperty(propertyName, true); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException e) { + } + try { + msg.setByteProperty(propertyName, (byte) 1); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException e) { + } + try { + msg.setShortProperty(propertyName, (short) 1); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException e) { + } + try { + msg.setIntProperty(propertyName, 1); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException e) { + } + try { + msg.setLongProperty(propertyName, 1); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException e) { + } + try { + msg.setFloatProperty(propertyName, (float) 1.5); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException e) { + } + try { + msg.setDoubleProperty(propertyName, 1.5); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException e) { + } + } + + public void testIsExpired() { + ActiveMQMessage msg = new ActiveMQMessage(); + msg.setJMSExpiration(System.currentTimeMillis() - 1); + assertTrue(msg.isExpired()); + msg.setJMSExpiration(System.currentTimeMillis() + 10000); + assertFalse(msg.isExpired()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQObjectMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQObjectMessageTest.java index fc38a30e83..4a2f6bcd5d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQObjectMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQObjectMessageTest.java @@ -25,102 +25,108 @@ import javax.jms.MessageNotWriteableException; import junit.framework.TestCase; /** - * + * */ public class ActiveMQObjectMessageTest extends TestCase { - /** - * Constructor for ActiveMQObjectMessageTest. - * - * @param name - */ - public ActiveMQObjectMessageTest(String name) { - super(name); - } + /** + * Constructor for ActiveMQObjectMessageTest. + * + * @param name + */ + public ActiveMQObjectMessageTest(String name) { + super(name); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(ActiveMQObjectMessageTest.class); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(ActiveMQObjectMessageTest.class); + } - /* - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - } + /* + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + } - /* - * @see TestCase#tearDown() - */ - protected void tearDown() throws Exception { - super.tearDown(); - } + /* + * @see TestCase#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + } - public void testBytes() throws JMSException, IOException { - ActiveMQObjectMessage msg = new ActiveMQObjectMessage(); - String str = "testText"; - msg.setObject(str); - - msg = (ActiveMQObjectMessage) msg.copy(); - assertEquals(msg.getObject(), str); + public void testBytes() throws JMSException, IOException { + ActiveMQObjectMessage msg = new ActiveMQObjectMessage(); + String str = "testText"; + msg.setObject(str); - } + msg = (ActiveMQObjectMessage) msg.copy(); + assertEquals(msg.getObject(), str); - public void testSetObject() throws JMSException { - ActiveMQObjectMessage msg = new ActiveMQObjectMessage(); - String str = "testText"; - msg.setObject(str); - assertTrue(msg.getObject() == str); - } + } - public void testClearBody() throws JMSException { - ActiveMQObjectMessage objectMessage = new ActiveMQObjectMessage(); - try { - objectMessage.setObject("String"); - objectMessage.clearBody(); - assertFalse(objectMessage.isReadOnlyBody()); - assertNull(objectMessage.getObject()); - objectMessage.setObject("String"); - objectMessage.getObject(); - } catch (MessageNotWriteableException mnwe) { - fail("should be writeable"); - } - } + public void testSetObject() throws JMSException { + ActiveMQObjectMessage msg = new ActiveMQObjectMessage(); + String str = "testText"; + msg.setObject(str); + assertTrue(msg.getObject() == str); + } - public void testReadOnlyBody() throws JMSException { - ActiveMQObjectMessage msg = new ActiveMQObjectMessage(); - msg.setObject("test"); - msg.setReadOnlyBody(true); - try { - msg.getObject(); - } catch (MessageNotReadableException e) { - fail("should be readable"); - } - try { - msg.setObject("test"); - fail("should throw exception"); - } catch (MessageNotWriteableException e) { - } - } + public void testClearBody() throws JMSException { + ActiveMQObjectMessage objectMessage = new ActiveMQObjectMessage(); + try { + objectMessage.setObject("String"); + objectMessage.clearBody(); + assertFalse(objectMessage.isReadOnlyBody()); + assertNull(objectMessage.getObject()); + objectMessage.setObject("String"); + objectMessage.getObject(); + } + catch (MessageNotWriteableException mnwe) { + fail("should be writeable"); + } + } - public void testWriteOnlyBody() throws JMSException { // should always be readable - ActiveMQObjectMessage msg = new ActiveMQObjectMessage(); - msg.setReadOnlyBody(false); - try { - msg.setObject("test"); - msg.getObject(); - } catch (MessageNotReadableException e) { - fail("should be readable"); - } - msg.setReadOnlyBody(true); - try { - msg.getObject(); - msg.setObject("test"); - fail("should throw exception"); - } catch (MessageNotReadableException e) { - fail("should be readable"); - } catch (MessageNotWriteableException mnwe) { - } - } + public void testReadOnlyBody() throws JMSException { + ActiveMQObjectMessage msg = new ActiveMQObjectMessage(); + msg.setObject("test"); + msg.setReadOnlyBody(true); + try { + msg.getObject(); + } + catch (MessageNotReadableException e) { + fail("should be readable"); + } + try { + msg.setObject("test"); + fail("should throw exception"); + } + catch (MessageNotWriteableException e) { + } + } + + public void testWriteOnlyBody() throws JMSException { // should always be readable + ActiveMQObjectMessage msg = new ActiveMQObjectMessage(); + msg.setReadOnlyBody(false); + try { + msg.setObject("test"); + msg.getObject(); + } + catch (MessageNotReadableException e) { + fail("should be readable"); + } + msg.setReadOnlyBody(true); + try { + msg.getObject(); + msg.setObject("test"); + fail("should throw exception"); + } + catch (MessageNotReadableException e) { + fail("should be readable"); + } + catch (MessageNotWriteableException mnwe) { + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQStreamMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQStreamMessageTest.java index e042217ced..757fb7fa13 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQStreamMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQStreamMessageTest.java @@ -26,975 +26,1088 @@ import javax.jms.MessageNotWriteableException; import junit.framework.TestCase; /** - * + * */ public class ActiveMQStreamMessageTest extends TestCase { - /** - * Constructor for ActiveMQStreamMessageTest. - * - * @param name - */ - public ActiveMQStreamMessageTest(String name) { - super(name); - } + /** + * Constructor for ActiveMQStreamMessageTest. + * + * @param name + */ + public ActiveMQStreamMessageTest(String name) { + super(name); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(ActiveMQStreamMessageTest.class); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(ActiveMQStreamMessageTest.class); + } - /* - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - } + /* + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + } - /* - * @see TestCase#tearDown() - */ - protected void tearDown() throws Exception { - super.tearDown(); - } + /* + * @see TestCase#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + } - public void testGetDataStructureType() { - ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); - assertEquals(msg.getDataStructureType(), CommandTypes.ACTIVEMQ_STREAM_MESSAGE); - } + public void testGetDataStructureType() { + ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); + assertEquals(msg.getDataStructureType(), CommandTypes.ACTIVEMQ_STREAM_MESSAGE); + } - public void testReadBoolean() { - ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); - try { - msg.writeBoolean(true); - msg.reset(); - assertTrue(msg.readBoolean()); - msg.reset(); - assertTrue(msg.readString().equals("true")); - msg.reset(); - try { - msg.readByte(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readShort(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readInt(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readLong(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readFloat(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readDouble(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readChar(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readBytes(new byte[1]); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } - - public void testreadByte() { - ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); - try { - byte test = (byte)4; - msg.writeByte(test); - msg.reset(); - assertTrue(msg.readByte() == test); - msg.reset(); - assertTrue(msg.readShort() == test); - msg.reset(); - assertTrue(msg.readInt() == test); - msg.reset(); - assertTrue(msg.readLong() == test); - msg.reset(); - assertTrue(msg.readString().equals(new Byte(test).toString())); - msg.reset(); - try { - msg.readBoolean(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readFloat(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readDouble(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readChar(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readBytes(new byte[1]); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } - - public void testReadShort() { - ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); - try { - short test = (short)4; - msg.writeShort(test); - msg.reset(); - assertTrue(msg.readShort() == test); - msg.reset(); - assertTrue(msg.readInt() == test); - msg.reset(); - assertTrue(msg.readLong() == test); - msg.reset(); - assertTrue(msg.readString().equals(new Short(test).toString())); - msg.reset(); - try { - msg.readBoolean(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readByte(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readFloat(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readDouble(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readChar(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readBytes(new byte[1]); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } - - public void testReadChar() { - ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); - try { - char test = 'z'; - msg.writeChar(test); - msg.reset(); - assertTrue(msg.readChar() == test); - msg.reset(); - assertTrue(msg.readString().equals(new Character(test).toString())); - msg.reset(); - try { - msg.readBoolean(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readByte(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readShort(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readInt(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readLong(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readFloat(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readDouble(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readBytes(new byte[1]); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } - - public void testReadInt() { - ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); - try { - int test = 4; - msg.writeInt(test); - msg.reset(); - assertTrue(msg.readInt() == test); - msg.reset(); - assertTrue(msg.readLong() == test); - msg.reset(); - assertTrue(msg.readString().equals(new Integer(test).toString())); - msg.reset(); - try { - msg.readBoolean(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readByte(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readShort(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readFloat(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readDouble(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readChar(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readBytes(new byte[1]); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } - - public void testReadLong() { - ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); - try { - long test = 4L; - msg.writeLong(test); - msg.reset(); - assertTrue(msg.readLong() == test); - msg.reset(); - assertTrue(msg.readString().equals(Long.valueOf(test).toString())); - msg.reset(); - try { - msg.readBoolean(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readByte(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readShort(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readInt(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readFloat(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readDouble(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readChar(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readBytes(new byte[1]); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg = new ActiveMQStreamMessage(); - msg.writeObject(new Long("1")); - // reset so it's readable now - msg.reset(); - assertEquals(new Long("1"), msg.readObject()); - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } - - public void testReadFloat() { - ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); - try { - float test = 4.4f; - msg.writeFloat(test); - msg.reset(); - assertTrue(msg.readFloat() == test); - msg.reset(); - assertTrue(msg.readDouble() == test); - msg.reset(); - assertTrue(msg.readString().equals(new Float(test).toString())); - msg.reset(); - try { - msg.readBoolean(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readByte(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readShort(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readInt(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readLong(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readChar(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readBytes(new byte[1]); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } - - public void testReadDouble() { - ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); - try { - double test = 4.4d; - msg.writeDouble(test); - msg.reset(); - assertTrue(msg.readDouble() == test); - msg.reset(); - assertTrue(msg.readString().equals(new Double(test).toString())); - msg.reset(); - try { - msg.readBoolean(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readByte(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readShort(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readInt(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readLong(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readFloat(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readChar(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readBytes(new byte[1]); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - - } - - public void testReadString() { - ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); - try { - byte testByte = (byte)2; - msg.writeString(new Byte(testByte).toString()); - msg.reset(); - assertTrue(msg.readByte() == testByte); - msg.clearBody(); - short testShort = 3; - msg.writeString(new Short(testShort).toString()); - msg.reset(); - assertTrue(msg.readShort() == testShort); - msg.clearBody(); - int testInt = 4; - msg.writeString(new Integer(testInt).toString()); - msg.reset(); - assertTrue(msg.readInt() == testInt); - msg.clearBody(); - long testLong = 6L; - msg.writeString(new Long(testLong).toString()); - msg.reset(); - assertTrue(msg.readLong() == testLong); - msg.clearBody(); - float testFloat = 6.6f; - msg.writeString(new Float(testFloat).toString()); - msg.reset(); - assertTrue(msg.readFloat() == testFloat); - msg.clearBody(); - double testDouble = 7.7d; - msg.writeString(new Double(testDouble).toString()); - msg.reset(); - assertTrue(msg.readDouble() == testDouble); - msg.clearBody(); - msg.writeString("true"); - msg.reset(); - assertTrue(msg.readBoolean()); - msg.clearBody(); - msg.writeString("a"); - msg.reset(); - try { - msg.readChar(); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - msg.clearBody(); - msg.writeString("777"); - msg.reset(); - try { - msg.readBytes(new byte[3]); - fail("Should have thrown exception"); - } catch (MessageFormatException e) { - } - - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } - - public void testReadBigString() { - ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); - try { - // Test with a 1Meg String - StringBuffer bigSB = new StringBuffer(1024 * 1024); - for (int i = 0; i < 1024 * 1024; i++) { - bigSB.append((char)'a' + i % 26); - } - String bigString = bigSB.toString(); - - msg.writeString(bigString); - msg.reset(); - assertEquals(bigString, msg.readString()); - - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } - - public void testReadBytes() { - ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); - try { - byte[] test = new byte[50]; - for (int i = 0; i < test.length; i++) { - test[i] = (byte)i; - } - msg.writeBytes(test); - msg.reset(); - byte[] valid = new byte[test.length]; - msg.readBytes(valid); - for (int i = 0; i < valid.length; i++) { - assertTrue(valid[i] == test[i]); - } - msg.reset(); - try { - msg.readByte(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readShort(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readInt(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readLong(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readFloat(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readChar(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - msg.reset(); - try { - msg.readString(); - fail("Should have thrown exception"); - } catch (MessageFormatException mfe) { - } - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } - - public void testReadObject() { - ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); - try { - byte testByte = (byte)2; - msg.writeByte(testByte); - msg.reset(); - assertTrue(((Byte)msg.readObject()).byteValue() == testByte); - msg.clearBody(); - - short testShort = 3; - msg.writeShort(testShort); - msg.reset(); - assertTrue(((Short)msg.readObject()).shortValue() == testShort); - msg.clearBody(); - - int testInt = 4; - msg.writeInt(testInt); - msg.reset(); - assertTrue(((Integer)msg.readObject()).intValue() == testInt); - msg.clearBody(); - - long testLong = 6L; - msg.writeLong(testLong); - msg.reset(); - assertTrue(((Long)msg.readObject()).longValue() == testLong); - msg.clearBody(); - - float testFloat = 6.6f; - msg.writeFloat(testFloat); - msg.reset(); - assertTrue(((Float)msg.readObject()).floatValue() == testFloat); - msg.clearBody(); - - double testDouble = 7.7d; - msg.writeDouble(testDouble); - msg.reset(); - assertTrue(((Double)msg.readObject()).doubleValue() == testDouble); - msg.clearBody(); - - char testChar = 'z'; - msg.writeChar(testChar); - msg.reset(); - assertTrue(((Character)msg.readObject()).charValue() == testChar); - msg.clearBody(); - - byte[] data = new byte[50]; - for (int i = 0; i < data.length; i++) { - data[i] = (byte)i; - } - msg.writeBytes(data); - msg.reset(); - byte[] valid = (byte[])msg.readObject(); - assertTrue(valid.length == data.length); - for (int i = 0; i < valid.length; i++) { - assertTrue(valid[i] == data[i]); - } - msg.clearBody(); - msg.writeBoolean(true); - msg.reset(); - assertTrue(((Boolean)msg.readObject()).booleanValue()); - - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - assertTrue(false); - } - } - - public void testClearBody() throws JMSException { - ActiveMQStreamMessage streamMessage = new ActiveMQStreamMessage(); - try { - streamMessage.writeObject(new Long(2)); - streamMessage.clearBody(); - assertFalse(streamMessage.isReadOnlyBody()); - streamMessage.writeObject(new Long(2)); - streamMessage.readObject(); - fail("should throw exception"); - } catch (MessageNotReadableException mnwe) { - } catch (MessageNotWriteableException mnwe) { - fail("should be writeable"); - } - } - - public void testReset() throws JMSException { - ActiveMQStreamMessage streamMessage = new ActiveMQStreamMessage(); - try { - streamMessage.writeDouble(24.5); - streamMessage.writeLong(311); - } catch (MessageNotWriteableException mnwe) { - fail("should be writeable"); - } - streamMessage.reset(); - try { - assertTrue(streamMessage.isReadOnlyBody()); - assertEquals(streamMessage.readDouble(), 24.5, 0); - assertEquals(streamMessage.readLong(), 311); - } catch (MessageNotReadableException mnre) { - fail("should be readable"); - } - try { - streamMessage.writeInt(33); - fail("should throw exception"); - } catch (MessageNotWriteableException mnwe) { - } - } - - public void testReadOnlyBody() throws JMSException { - ActiveMQStreamMessage message = new ActiveMQStreamMessage(); - try { - message.writeBoolean(true); - message.writeByte((byte)1); - message.writeBytes(new byte[1]); - message.writeBytes(new byte[3], 0, 2); - message.writeChar('a'); - message.writeDouble(1.5); - message.writeFloat((float)1.5); - message.writeInt(1); - message.writeLong(1); - message.writeObject("stringobj"); - message.writeShort((short)1); - message.writeString("string"); - } catch (MessageNotWriteableException mnwe) { - fail("Should be writeable"); - } - message.reset(); - try { - message.readBoolean(); - message.readByte(); - assertEquals(1, message.readBytes(new byte[10])); - assertEquals(-1, message.readBytes(new byte[10])); - assertEquals(2, message.readBytes(new byte[10])); - assertEquals(-1, message.readBytes(new byte[10])); - message.readChar(); - message.readDouble(); - message.readFloat(); - message.readInt(); - message.readLong(); - message.readString(); - message.readShort(); - message.readString(); - } catch (MessageNotReadableException mnwe) { - fail("Should be readable"); - } - try { - message.writeBoolean(true); + public void testReadBoolean() { + ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); + try { + msg.writeBoolean(true); + msg.reset(); + assertTrue(msg.readBoolean()); + msg.reset(); + assertTrue(msg.readString().equals("true")); + msg.reset(); + try { + msg.readByte(); fail("Should have thrown exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - message.writeByte((byte)1); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readShort(); fail("Should have thrown exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - message.writeBytes(new byte[1]); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readInt(); fail("Should have thrown exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - message.writeBytes(new byte[3], 0, 2); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readLong(); fail("Should have thrown exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - message.writeChar('a'); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readFloat(); fail("Should have thrown exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - message.writeDouble(1.5); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readDouble(); fail("Should have thrown exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - message.writeFloat((float)1.5); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readChar(); fail("Should have thrown exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - message.writeInt(1); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readBytes(new byte[1]); fail("Should have thrown exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - message.writeLong(1); - fail("Should have thrown exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - message.writeObject("stringobj"); - fail("Should have thrown exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - message.writeShort((short)1); - fail("Should have thrown exception"); - } catch (MessageNotWriteableException mnwe) { - } - try { - message.writeString("string"); - fail("Should have thrown exception"); - } catch (MessageNotWriteableException mnwe) { - } - } + } + catch (MessageFormatException mfe) { + } + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } - public void testWriteOnlyBody() throws JMSException { - ActiveMQStreamMessage message = new ActiveMQStreamMessage(); - message.clearBody(); - try { - message.writeBoolean(true); - message.writeByte((byte)1); - message.writeBytes(new byte[1]); - message.writeBytes(new byte[3], 0, 2); - message.writeChar('a'); - message.writeDouble(1.5); - message.writeFloat((float)1.5); - message.writeInt(1); - message.writeLong(1); - message.writeObject("stringobj"); - message.writeShort((short)1); - message.writeString("string"); - } catch (MessageNotWriteableException mnwe) { - fail("Should be writeable"); - } - try { - message.readBoolean(); + public void testreadByte() { + ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); + try { + byte test = (byte) 4; + msg.writeByte(test); + msg.reset(); + assertTrue(msg.readByte() == test); + msg.reset(); + assertTrue(msg.readShort() == test); + msg.reset(); + assertTrue(msg.readInt() == test); + msg.reset(); + assertTrue(msg.readLong() == test); + msg.reset(); + assertTrue(msg.readString().equals(new Byte(test).toString())); + msg.reset(); + try { + msg.readBoolean(); fail("Should have thrown exception"); - } catch (MessageNotReadableException mnwe) { - } - try { - message.readByte(); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readFloat(); fail("Should have thrown exception"); - } catch (MessageNotReadableException e) { - } - try { - message.readBytes(new byte[1]); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readDouble(); fail("Should have thrown exception"); - } catch (MessageNotReadableException e) { - } - try { - message.readBytes(new byte[2]); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readChar(); fail("Should have thrown exception"); - } catch (MessageNotReadableException e) { - } - try { - message.readChar(); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readBytes(new byte[1]); fail("Should have thrown exception"); - } catch (MessageNotReadableException e) { - } - try { - message.readDouble(); + } + catch (MessageFormatException mfe) { + } + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } + + public void testReadShort() { + ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); + try { + short test = (short) 4; + msg.writeShort(test); + msg.reset(); + assertTrue(msg.readShort() == test); + msg.reset(); + assertTrue(msg.readInt() == test); + msg.reset(); + assertTrue(msg.readLong() == test); + msg.reset(); + assertTrue(msg.readString().equals(new Short(test).toString())); + msg.reset(); + try { + msg.readBoolean(); fail("Should have thrown exception"); - } catch (MessageNotReadableException e) { - } - try { - message.readFloat(); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readByte(); fail("Should have thrown exception"); - } catch (MessageNotReadableException e) { - } - try { - message.readInt(); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readFloat(); fail("Should have thrown exception"); - } catch (MessageNotReadableException e) { - } - try { - message.readLong(); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readDouble(); fail("Should have thrown exception"); - } catch (MessageNotReadableException e) { - } - try { - message.readString(); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readChar(); fail("Should have thrown exception"); - } catch (MessageNotReadableException e) { - } - try { - message.readShort(); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readBytes(new byte[1]); fail("Should have thrown exception"); - } catch (MessageNotReadableException e) { - } - try { - message.readString(); + } + catch (MessageFormatException mfe) { + } + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } + + public void testReadChar() { + ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); + try { + char test = 'z'; + msg.writeChar(test); + msg.reset(); + assertTrue(msg.readChar() == test); + msg.reset(); + assertTrue(msg.readString().equals(new Character(test).toString())); + msg.reset(); + try { + msg.readBoolean(); fail("Should have thrown exception"); - } catch (MessageNotReadableException e) { - } - } - - public void testWriteObject() { - try { - ActiveMQStreamMessage message = new ActiveMQStreamMessage(); - message.clearBody(); - message.writeObject("test"); - message.writeObject(new Character('a')); - message.writeObject(new Boolean(false)); - message.writeObject(new Byte((byte) 2)); - message.writeObject(new Short((short) 2)); - message.writeObject(new Integer(2)); - message.writeObject(new Long(2L)); - message.writeObject(new Float(2.0f)); - message.writeObject(new Double(2.0d)); - }catch(Exception e) { - fail(e.getMessage()); - } - try { - ActiveMQStreamMessage message = new ActiveMQStreamMessage(); - message.clearBody(); - message.writeObject(new Object()); - fail("should throw an exception"); - }catch(MessageFormatException e) { - - }catch(Exception e) { - fail(e.getMessage()); - } - } + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readByte(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readShort(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readInt(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readLong(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readFloat(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readDouble(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readBytes(new byte[1]); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } + + public void testReadInt() { + ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); + try { + int test = 4; + msg.writeInt(test); + msg.reset(); + assertTrue(msg.readInt() == test); + msg.reset(); + assertTrue(msg.readLong() == test); + msg.reset(); + assertTrue(msg.readString().equals(new Integer(test).toString())); + msg.reset(); + try { + msg.readBoolean(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readByte(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readShort(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readFloat(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readDouble(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readChar(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readBytes(new byte[1]); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } + + public void testReadLong() { + ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); + try { + long test = 4L; + msg.writeLong(test); + msg.reset(); + assertTrue(msg.readLong() == test); + msg.reset(); + assertTrue(msg.readString().equals(Long.valueOf(test).toString())); + msg.reset(); + try { + msg.readBoolean(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readByte(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readShort(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readInt(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readFloat(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readDouble(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readChar(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readBytes(new byte[1]); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg = new ActiveMQStreamMessage(); + msg.writeObject(new Long("1")); + // reset so it's readable now + msg.reset(); + assertEquals(new Long("1"), msg.readObject()); + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } + + public void testReadFloat() { + ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); + try { + float test = 4.4f; + msg.writeFloat(test); + msg.reset(); + assertTrue(msg.readFloat() == test); + msg.reset(); + assertTrue(msg.readDouble() == test); + msg.reset(); + assertTrue(msg.readString().equals(new Float(test).toString())); + msg.reset(); + try { + msg.readBoolean(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readByte(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readShort(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readInt(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readLong(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readChar(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readBytes(new byte[1]); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } + + public void testReadDouble() { + ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); + try { + double test = 4.4d; + msg.writeDouble(test); + msg.reset(); + assertTrue(msg.readDouble() == test); + msg.reset(); + assertTrue(msg.readString().equals(new Double(test).toString())); + msg.reset(); + try { + msg.readBoolean(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readByte(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readShort(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readInt(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readLong(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readFloat(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readChar(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readBytes(new byte[1]); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + + } + + public void testReadString() { + ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); + try { + byte testByte = (byte) 2; + msg.writeString(new Byte(testByte).toString()); + msg.reset(); + assertTrue(msg.readByte() == testByte); + msg.clearBody(); + short testShort = 3; + msg.writeString(new Short(testShort).toString()); + msg.reset(); + assertTrue(msg.readShort() == testShort); + msg.clearBody(); + int testInt = 4; + msg.writeString(new Integer(testInt).toString()); + msg.reset(); + assertTrue(msg.readInt() == testInt); + msg.clearBody(); + long testLong = 6L; + msg.writeString(new Long(testLong).toString()); + msg.reset(); + assertTrue(msg.readLong() == testLong); + msg.clearBody(); + float testFloat = 6.6f; + msg.writeString(new Float(testFloat).toString()); + msg.reset(); + assertTrue(msg.readFloat() == testFloat); + msg.clearBody(); + double testDouble = 7.7d; + msg.writeString(new Double(testDouble).toString()); + msg.reset(); + assertTrue(msg.readDouble() == testDouble); + msg.clearBody(); + msg.writeString("true"); + msg.reset(); + assertTrue(msg.readBoolean()); + msg.clearBody(); + msg.writeString("a"); + msg.reset(); + try { + msg.readChar(); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + msg.clearBody(); + msg.writeString("777"); + msg.reset(); + try { + msg.readBytes(new byte[3]); + fail("Should have thrown exception"); + } + catch (MessageFormatException e) { + } + + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } + + public void testReadBigString() { + ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); + try { + // Test with a 1Meg String + StringBuffer bigSB = new StringBuffer(1024 * 1024); + for (int i = 0; i < 1024 * 1024; i++) { + bigSB.append((char) 'a' + i % 26); + } + String bigString = bigSB.toString(); + + msg.writeString(bigString); + msg.reset(); + assertEquals(bigString, msg.readString()); + + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } + + public void testReadBytes() { + ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); + try { + byte[] test = new byte[50]; + for (int i = 0; i < test.length; i++) { + test[i] = (byte) i; + } + msg.writeBytes(test); + msg.reset(); + byte[] valid = new byte[test.length]; + msg.readBytes(valid); + for (int i = 0; i < valid.length; i++) { + assertTrue(valid[i] == test[i]); + } + msg.reset(); + try { + msg.readByte(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readShort(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readInt(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readLong(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readFloat(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readChar(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + msg.reset(); + try { + msg.readString(); + fail("Should have thrown exception"); + } + catch (MessageFormatException mfe) { + } + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } + + public void testReadObject() { + ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); + try { + byte testByte = (byte) 2; + msg.writeByte(testByte); + msg.reset(); + assertTrue(((Byte) msg.readObject()).byteValue() == testByte); + msg.clearBody(); + + short testShort = 3; + msg.writeShort(testShort); + msg.reset(); + assertTrue(((Short) msg.readObject()).shortValue() == testShort); + msg.clearBody(); + + int testInt = 4; + msg.writeInt(testInt); + msg.reset(); + assertTrue(((Integer) msg.readObject()).intValue() == testInt); + msg.clearBody(); + + long testLong = 6L; + msg.writeLong(testLong); + msg.reset(); + assertTrue(((Long) msg.readObject()).longValue() == testLong); + msg.clearBody(); + + float testFloat = 6.6f; + msg.writeFloat(testFloat); + msg.reset(); + assertTrue(((Float) msg.readObject()).floatValue() == testFloat); + msg.clearBody(); + + double testDouble = 7.7d; + msg.writeDouble(testDouble); + msg.reset(); + assertTrue(((Double) msg.readObject()).doubleValue() == testDouble); + msg.clearBody(); + + char testChar = 'z'; + msg.writeChar(testChar); + msg.reset(); + assertTrue(((Character) msg.readObject()).charValue() == testChar); + msg.clearBody(); + + byte[] data = new byte[50]; + for (int i = 0; i < data.length; i++) { + data[i] = (byte) i; + } + msg.writeBytes(data); + msg.reset(); + byte[] valid = (byte[]) msg.readObject(); + assertTrue(valid.length == data.length); + for (int i = 0; i < valid.length; i++) { + assertTrue(valid[i] == data[i]); + } + msg.clearBody(); + msg.writeBoolean(true); + msg.reset(); + assertTrue(((Boolean) msg.readObject()).booleanValue()); + + } + catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + assertTrue(false); + } + } + + public void testClearBody() throws JMSException { + ActiveMQStreamMessage streamMessage = new ActiveMQStreamMessage(); + try { + streamMessage.writeObject(new Long(2)); + streamMessage.clearBody(); + assertFalse(streamMessage.isReadOnlyBody()); + streamMessage.writeObject(new Long(2)); + streamMessage.readObject(); + fail("should throw exception"); + } + catch (MessageNotReadableException mnwe) { + } + catch (MessageNotWriteableException mnwe) { + fail("should be writeable"); + } + } + + public void testReset() throws JMSException { + ActiveMQStreamMessage streamMessage = new ActiveMQStreamMessage(); + try { + streamMessage.writeDouble(24.5); + streamMessage.writeLong(311); + } + catch (MessageNotWriteableException mnwe) { + fail("should be writeable"); + } + streamMessage.reset(); + try { + assertTrue(streamMessage.isReadOnlyBody()); + assertEquals(streamMessage.readDouble(), 24.5, 0); + assertEquals(streamMessage.readLong(), 311); + } + catch (MessageNotReadableException mnre) { + fail("should be readable"); + } + try { + streamMessage.writeInt(33); + fail("should throw exception"); + } + catch (MessageNotWriteableException mnwe) { + } + } + + public void testReadOnlyBody() throws JMSException { + ActiveMQStreamMessage message = new ActiveMQStreamMessage(); + try { + message.writeBoolean(true); + message.writeByte((byte) 1); + message.writeBytes(new byte[1]); + message.writeBytes(new byte[3], 0, 2); + message.writeChar('a'); + message.writeDouble(1.5); + message.writeFloat((float) 1.5); + message.writeInt(1); + message.writeLong(1); + message.writeObject("stringobj"); + message.writeShort((short) 1); + message.writeString("string"); + } + catch (MessageNotWriteableException mnwe) { + fail("Should be writeable"); + } + message.reset(); + try { + message.readBoolean(); + message.readByte(); + assertEquals(1, message.readBytes(new byte[10])); + assertEquals(-1, message.readBytes(new byte[10])); + assertEquals(2, message.readBytes(new byte[10])); + assertEquals(-1, message.readBytes(new byte[10])); + message.readChar(); + message.readDouble(); + message.readFloat(); + message.readInt(); + message.readLong(); + message.readString(); + message.readShort(); + message.readString(); + } + catch (MessageNotReadableException mnwe) { + fail("Should be readable"); + } + try { + message.writeBoolean(true); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + message.writeByte((byte) 1); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + message.writeBytes(new byte[1]); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + message.writeBytes(new byte[3], 0, 2); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + message.writeChar('a'); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + message.writeDouble(1.5); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + message.writeFloat((float) 1.5); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + message.writeInt(1); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + message.writeLong(1); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + message.writeObject("stringobj"); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + message.writeShort((short) 1); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException mnwe) { + } + try { + message.writeString("string"); + fail("Should have thrown exception"); + } + catch (MessageNotWriteableException mnwe) { + } + } + + public void testWriteOnlyBody() throws JMSException { + ActiveMQStreamMessage message = new ActiveMQStreamMessage(); + message.clearBody(); + try { + message.writeBoolean(true); + message.writeByte((byte) 1); + message.writeBytes(new byte[1]); + message.writeBytes(new byte[3], 0, 2); + message.writeChar('a'); + message.writeDouble(1.5); + message.writeFloat((float) 1.5); + message.writeInt(1); + message.writeLong(1); + message.writeObject("stringobj"); + message.writeShort((short) 1); + message.writeString("string"); + } + catch (MessageNotWriteableException mnwe) { + fail("Should be writeable"); + } + try { + message.readBoolean(); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException mnwe) { + } + try { + message.readByte(); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException e) { + } + try { + message.readBytes(new byte[1]); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException e) { + } + try { + message.readBytes(new byte[2]); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException e) { + } + try { + message.readChar(); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException e) { + } + try { + message.readDouble(); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException e) { + } + try { + message.readFloat(); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException e) { + } + try { + message.readInt(); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException e) { + } + try { + message.readLong(); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException e) { + } + try { + message.readString(); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException e) { + } + try { + message.readShort(); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException e) { + } + try { + message.readString(); + fail("Should have thrown exception"); + } + catch (MessageNotReadableException e) { + } + } + + public void testWriteObject() { + try { + ActiveMQStreamMessage message = new ActiveMQStreamMessage(); + message.clearBody(); + message.writeObject("test"); + message.writeObject(new Character('a')); + message.writeObject(new Boolean(false)); + message.writeObject(new Byte((byte) 2)); + message.writeObject(new Short((short) 2)); + message.writeObject(new Integer(2)); + message.writeObject(new Long(2L)); + message.writeObject(new Float(2.0f)); + message.writeObject(new Double(2.0d)); + } + catch (Exception e) { + fail(e.getMessage()); + } + try { + ActiveMQStreamMessage message = new ActiveMQStreamMessage(); + message.clearBody(); + message.writeObject(new Object()); + fail("should throw an exception"); + } + catch (MessageFormatException e) { + + } + catch (Exception e) { + fail(e.getMessage()); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQTextMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQTextMessageTest.java index 13c71847c5..cfbba33cb2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQTextMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/ActiveMQTextMessageTest.java @@ -24,6 +24,7 @@ import javax.jms.MessageNotReadableException; import javax.jms.MessageNotWriteableException; import junit.framework.TestCase; + import junit.textui.TestRunner; import org.apache.activemq.util.ByteArrayOutputStream; @@ -31,129 +32,137 @@ import org.apache.activemq.util.ByteSequence; import org.apache.activemq.util.MarshallingSupport; /** - * + * */ public class ActiveMQTextMessageTest extends TestCase { - public static void main(String[] args) { - TestRunner.run(ActiveMQTextMessageTest.class); - } + public static void main(String[] args) { + TestRunner.run(ActiveMQTextMessageTest.class); + } - public void testGetDataStructureType() { - ActiveMQTextMessage msg = new ActiveMQTextMessage(); - assertEquals(msg.getDataStructureType(), CommandTypes.ACTIVEMQ_TEXT_MESSAGE); - } + public void testGetDataStructureType() { + ActiveMQTextMessage msg = new ActiveMQTextMessage(); + assertEquals(msg.getDataStructureType(), CommandTypes.ACTIVEMQ_TEXT_MESSAGE); + } - public void testShallowCopy() throws JMSException { - ActiveMQTextMessage msg = new ActiveMQTextMessage(); - String string = "str"; - msg.setText(string); - Message copy = msg.copy(); - assertSame(msg.getText(), ((ActiveMQTextMessage) copy).getText()); - } + public void testShallowCopy() throws JMSException { + ActiveMQTextMessage msg = new ActiveMQTextMessage(); + String string = "str"; + msg.setText(string); + Message copy = msg.copy(); + assertSame(msg.getText(), ((ActiveMQTextMessage) copy).getText()); + } - public void testSetText() { - ActiveMQTextMessage msg = new ActiveMQTextMessage(); - String str = "testText"; - try { - msg.setText(str); - assertEquals(msg.getText(), str); - } catch (JMSException e) { - e.printStackTrace(); - } - } + public void testSetText() { + ActiveMQTextMessage msg = new ActiveMQTextMessage(); + String str = "testText"; + try { + msg.setText(str); + assertEquals(msg.getText(), str); + } + catch (JMSException e) { + e.printStackTrace(); + } + } - public void testGetBytes() throws JMSException, IOException { - ActiveMQTextMessage msg = new ActiveMQTextMessage(); - String str = "testText"; - msg.setText(str); - msg.beforeMarshall(null); - - ByteSequence bytes = msg.getContent(); - msg = new ActiveMQTextMessage(); - msg.setContent(bytes); - - assertEquals(msg.getText(), str); - } + public void testGetBytes() throws JMSException, IOException { + ActiveMQTextMessage msg = new ActiveMQTextMessage(); + String str = "testText"; + msg.setText(str); + msg.beforeMarshall(null); - public void testClearBody() throws JMSException, IOException { - ActiveMQTextMessage textMessage = new ActiveMQTextMessage(); - textMessage.setText("string"); - textMessage.clearBody(); - assertFalse(textMessage.isReadOnlyBody()); - assertNull(textMessage.getText()); - try { - textMessage.setText("String"); - textMessage.getText(); - } catch (MessageNotWriteableException mnwe) { - fail("should be writeable"); - } catch (MessageNotReadableException mnre) { - fail("should be readable"); - } - } + ByteSequence bytes = msg.getContent(); + msg = new ActiveMQTextMessage(); + msg.setContent(bytes); - public void testReadOnlyBody() throws JMSException { - ActiveMQTextMessage textMessage = new ActiveMQTextMessage(); - textMessage.setText("test"); - textMessage.setReadOnlyBody(true); - try { - textMessage.getText(); - } catch (MessageNotReadableException e) { - fail("should be readable"); - } - try { - textMessage.setText("test"); - fail("should throw exception"); - } catch (MessageNotWriteableException mnwe) { - } - } + assertEquals(msg.getText(), str); + } - public void testWriteOnlyBody() throws JMSException { // should always be readable - ActiveMQTextMessage textMessage = new ActiveMQTextMessage(); - textMessage.setReadOnlyBody(false); - try { - textMessage.setText("test"); - textMessage.getText(); - } catch (MessageNotReadableException e) { - fail("should be readable"); - } - textMessage.setReadOnlyBody(true); - try { - textMessage.getText(); - textMessage.setText("test"); - fail("should throw exception"); - } catch (MessageNotReadableException e) { - fail("should be readable"); - } catch (MessageNotWriteableException mnwe) { - } - } - - public void testShortText() throws Exception { - String shortText = "Content"; - ActiveMQTextMessage shortMessage = new ActiveMQTextMessage(); - setContent(shortMessage, shortText); - assertTrue(shortMessage.toString().contains("text = " + shortText)); - assertTrue(shortMessage.getText().equals(shortText)); - - String longText = "Very very very very veeeeeeery loooooooooooooooooooooooooooooooooong text"; - String longExpectedText = "Very very very very veeeeeeery looooooooooooo...ooooong text"; - ActiveMQTextMessage longMessage = new ActiveMQTextMessage(); - setContent(longMessage, longText); - assertTrue(longMessage.toString().contains("text = " + longExpectedText)); - assertTrue(longMessage.getText().equals(longText)); - } - - public void testNullText() throws Exception { - ActiveMQTextMessage nullMessage = new ActiveMQTextMessage(); - setContent(nullMessage, null); - assertTrue(nullMessage.toString().contains("text = null")); - } - - protected void setContent(Message message, String text) throws Exception { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream dataOut = new DataOutputStream(baos); - MarshallingSupport.writeUTF8(dataOut, text); - dataOut.close(); - message.setContent(baos.toByteSequence()); - } + public void testClearBody() throws JMSException, IOException { + ActiveMQTextMessage textMessage = new ActiveMQTextMessage(); + textMessage.setText("string"); + textMessage.clearBody(); + assertFalse(textMessage.isReadOnlyBody()); + assertNull(textMessage.getText()); + try { + textMessage.setText("String"); + textMessage.getText(); + } + catch (MessageNotWriteableException mnwe) { + fail("should be writeable"); + } + catch (MessageNotReadableException mnre) { + fail("should be readable"); + } + } + + public void testReadOnlyBody() throws JMSException { + ActiveMQTextMessage textMessage = new ActiveMQTextMessage(); + textMessage.setText("test"); + textMessage.setReadOnlyBody(true); + try { + textMessage.getText(); + } + catch (MessageNotReadableException e) { + fail("should be readable"); + } + try { + textMessage.setText("test"); + fail("should throw exception"); + } + catch (MessageNotWriteableException mnwe) { + } + } + + public void testWriteOnlyBody() throws JMSException { // should always be readable + ActiveMQTextMessage textMessage = new ActiveMQTextMessage(); + textMessage.setReadOnlyBody(false); + try { + textMessage.setText("test"); + textMessage.getText(); + } + catch (MessageNotReadableException e) { + fail("should be readable"); + } + textMessage.setReadOnlyBody(true); + try { + textMessage.getText(); + textMessage.setText("test"); + fail("should throw exception"); + } + catch (MessageNotReadableException e) { + fail("should be readable"); + } + catch (MessageNotWriteableException mnwe) { + } + } + + public void testShortText() throws Exception { + String shortText = "Content"; + ActiveMQTextMessage shortMessage = new ActiveMQTextMessage(); + setContent(shortMessage, shortText); + assertTrue(shortMessage.toString().contains("text = " + shortText)); + assertTrue(shortMessage.getText().equals(shortText)); + + String longText = "Very very very very veeeeeeery loooooooooooooooooooooooooooooooooong text"; + String longExpectedText = "Very very very very veeeeeeery looooooooooooo...ooooong text"; + ActiveMQTextMessage longMessage = new ActiveMQTextMessage(); + setContent(longMessage, longText); + assertTrue(longMessage.toString().contains("text = " + longExpectedText)); + assertTrue(longMessage.getText().equals(longText)); + } + + public void testNullText() throws Exception { + ActiveMQTextMessage nullMessage = new ActiveMQTextMessage(); + setContent(nullMessage, null); + assertTrue(nullMessage.toString().contains("text = null")); + } + + protected void setContent(Message message, String text) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dataOut = new DataOutputStream(baos); + MarshallingSupport.writeUTF8(dataOut, text); + dataOut.close(); + message.setContent(baos.toByteSequence()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/DataStructureTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/DataStructureTestSupport.java index fa977af07e..074ebe4bdc 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/DataStructureTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/DataStructureTestSupport.java @@ -23,136 +23,146 @@ import java.util.Arrays; import junit.framework.AssertionFailedError; import junit.framework.TestCase; + import org.apache.activemq.CombinationTestSupport; import org.apache.activemq.openwire.OpenWireFormat; import org.apache.activemq.util.ByteSequence; import org.apache.activemq.wireformat.WireFormat; public abstract class DataStructureTestSupport extends CombinationTestSupport { - public boolean cacheEnabled; - public WireFormat wireFormat; - public void assertBeanMarshalls(Object original) throws IOException { - Object o = marshalAndUnmarshall(original, wireFormat); - assertNotNull(o); - assertEquals(original, o); - // assertEquals(original.getClass(), o.getClass()); - // - // Method[] methods = original.getClass().getMethods(); - // for (int i = 0; i < methods.length; i++) { - // Method method = methods[i]; - // if( ( method.getName().startsWith("get") - // || method.getName().startsWith("is") - // ) - // && method.getParameterTypes().length==0 - // && method.getReturnType()!=null - // ) { - // try { - // Object expect = method.invoke(original, null); - // Object was = method.invoke(o, null); - // assertEquals(expect, was); - // } catch (IllegalArgumentException e) { - // } catch (IllegalAccessException e) { - // } catch (InvocationTargetException e) { - // } - // } - // } - } + public boolean cacheEnabled; + public WireFormat wireFormat; - public static void assertEquals(Object expect, Object was) { - if (expect == null ^ was == null) { - throw new AssertionFailedError("Not equals, expected: " + expect + ", was: " + was); - } - if (expect == null) { - return; - } - if (expect.getClass() != was.getClass()) { - throw new AssertionFailedError("Not equals, classes don't match. expected: " + expect.getClass() + ", was: " + was.getClass()); - } - if (expect.getClass().isArray()) { - Class componentType = expect.getClass().getComponentType(); - if (componentType.isPrimitive()) { - boolean ok = false; - if (componentType == byte.class) { - ok = Arrays.equals((byte[])expect, (byte[])was); - } - if (componentType == char.class) { - ok = Arrays.equals((char[])expect, (char[])was); - } - if (componentType == short.class) { - ok = Arrays.equals((short[])expect, (short[])was); - } - if (componentType == int.class) { - ok = Arrays.equals((int[])expect, (int[])was); - } - if (componentType == long.class) { - ok = Arrays.equals((long[])expect, (long[])was); - } - if (componentType == double.class) { - ok = Arrays.equals((double[])expect, (double[])was); - } - if (componentType == float.class) { - ok = Arrays.equals((float[])expect, (float[])was); - } - if (!ok) { - throw new AssertionFailedError("Arrays not equal"); - } - } else { - Object expectArray[] = (Object[])expect; - Object wasArray[] = (Object[])was; - if (expectArray.length != wasArray.length) { - throw new AssertionFailedError("Not equals, array lengths don't match. expected: " + expectArray.length + ", was: " + wasArray.length); - } - for (int i = 0; i < wasArray.length; i++) { - assertEquals(expectArray[i], wasArray[i]); - } + public void assertBeanMarshalls(Object original) throws IOException { + Object o = marshalAndUnmarshall(original, wireFormat); + assertNotNull(o); + assertEquals(original, o); + // assertEquals(original.getClass(), o.getClass()); + // + // Method[] methods = original.getClass().getMethods(); + // for (int i = 0; i < methods.length; i++) { + // Method method = methods[i]; + // if( ( method.getName().startsWith("get") + // || method.getName().startsWith("is") + // ) + // && method.getParameterTypes().length==0 + // && method.getReturnType()!=null + // ) { + // try { + // Object expect = method.invoke(original, null); + // Object was = method.invoke(o, null); + // assertEquals(expect, was); + // } catch (IllegalArgumentException e) { + // } catch (IllegalAccessException e) { + // } catch (InvocationTargetException e) { + // } + // } + // } + } + public static void assertEquals(Object expect, Object was) { + if (expect == null ^ was == null) { + throw new AssertionFailedError("Not equals, expected: " + expect + ", was: " + was); + } + if (expect == null) { + return; + } + if (expect.getClass() != was.getClass()) { + throw new AssertionFailedError("Not equals, classes don't match. expected: " + expect.getClass() + ", was: " + was.getClass()); + } + if (expect.getClass().isArray()) { + Class componentType = expect.getClass().getComponentType(); + if (componentType.isPrimitive()) { + boolean ok = false; + if (componentType == byte.class) { + ok = Arrays.equals((byte[]) expect, (byte[]) was); } - } else if (expect instanceof Command) { - assertEquals(expect.getClass(), was.getClass()); - Method[] methods = expect.getClass().getMethods(); - for (int i = 0; i < methods.length; i++) { - Method method = methods[i]; - if ((method.getName().startsWith("get") || method.getName().startsWith("is")) && method.getParameterTypes().length == 0 && method.getReturnType() != null) { - - // Check to see if there is a setter for the method. - try { - if (method.getName().startsWith("get")) { - expect.getClass().getMethod(method.getName().replaceFirst("get", "set"), new Class[] {method.getReturnType()}); - } else { - expect.getClass().getMethod(method.getName().replaceFirst("is", "set"), new Class[] {method.getReturnType()}); - } - } catch (Throwable ignore) { - continue; - } - - try { - assertEquals(method.invoke(expect, (Object)null), method.invoke(was, (Object)null)); - } catch (IllegalArgumentException e) { - } catch (IllegalAccessException e) { - } catch (InvocationTargetException e) { - } - } + if (componentType == char.class) { + ok = Arrays.equals((char[]) expect, (char[]) was); + } + if (componentType == short.class) { + ok = Arrays.equals((short[]) expect, (short[]) was); + } + if (componentType == int.class) { + ok = Arrays.equals((int[]) expect, (int[]) was); + } + if (componentType == long.class) { + ok = Arrays.equals((long[]) expect, (long[]) was); + } + if (componentType == double.class) { + ok = Arrays.equals((double[]) expect, (double[]) was); + } + if (componentType == float.class) { + ok = Arrays.equals((float[]) expect, (float[]) was); + } + if (!ok) { + throw new AssertionFailedError("Arrays not equal"); + } + } + else { + Object expectArray[] = (Object[]) expect; + Object wasArray[] = (Object[]) was; + if (expectArray.length != wasArray.length) { + throw new AssertionFailedError("Not equals, array lengths don't match. expected: " + expectArray.length + ", was: " + wasArray.length); + } + for (int i = 0; i < wasArray.length; i++) { + assertEquals(expectArray[i], wasArray[i]); } - } else { - TestCase.assertEquals(expect, was); - } - } - protected void setUp() throws Exception { - wireFormat = createWireFormat(); - super.setUp(); - } + } + } + else if (expect instanceof Command) { + assertEquals(expect.getClass(), was.getClass()); + Method[] methods = expect.getClass().getMethods(); + for (int i = 0; i < methods.length; i++) { + Method method = methods[i]; + if ((method.getName().startsWith("get") || method.getName().startsWith("is")) && method.getParameterTypes().length == 0 && method.getReturnType() != null) { - protected WireFormat createWireFormat() { - OpenWireFormat answer = new OpenWireFormat(); - answer.setCacheEnabled(cacheEnabled); - return answer; - } + // Check to see if there is a setter for the method. + try { + if (method.getName().startsWith("get")) { + expect.getClass().getMethod(method.getName().replaceFirst("get", "set"), new Class[]{method.getReturnType()}); + } + else { + expect.getClass().getMethod(method.getName().replaceFirst("is", "set"), new Class[]{method.getReturnType()}); + } + } + catch (Throwable ignore) { + continue; + } - protected Object marshalAndUnmarshall(Object original, WireFormat wireFormat) throws IOException { - ByteSequence packet = wireFormat.marshal(original); - return wireFormat.unmarshal(packet); - } + try { + assertEquals(method.invoke(expect, (Object) null), method.invoke(was, (Object) null)); + } + catch (IllegalArgumentException e) { + } + catch (IllegalAccessException e) { + } + catch (InvocationTargetException e) { + } + } + } + } + else { + TestCase.assertEquals(expect, was); + } + } + + protected void setUp() throws Exception { + wireFormat = createWireFormat(); + super.setUp(); + } + + protected WireFormat createWireFormat() { + OpenWireFormat answer = new OpenWireFormat(); + answer.setCacheEnabled(cacheEnabled); + return answer; + } + + protected Object marshalAndUnmarshall(Object original, WireFormat wireFormat) throws IOException { + ByteSequence packet = wireFormat.marshal(original); + return wireFormat.unmarshal(packet); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/MessageCompressionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/MessageCompressionTest.java index 4c77bfcdea..6b5cc45ff3 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/MessageCompressionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/MessageCompressionTest.java @@ -32,112 +32,103 @@ import org.apache.activemq.broker.BrokerService; public class MessageCompressionTest extends TestCase { - private static final String BROKER_URL = "tcp://localhost:0"; - // The following text should compress well - private static final String TEXT = "The quick red fox jumped over the lazy brown dog. " - + "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. " - + "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. " - + "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. " - + "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. " - + "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. " - + "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. " - + "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. " - + "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. "; + private static final String BROKER_URL = "tcp://localhost:0"; + // The following text should compress well + private static final String TEXT = "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. "; - private BrokerService broker; - private ActiveMQQueue queue; - private String connectionUri; + private BrokerService broker; + private ActiveMQQueue queue; + private String connectionUri; - protected void setUp() throws Exception { - broker = new BrokerService(); - connectionUri = broker.addConnector(BROKER_URL).getPublishableConnectString(); - broker.start(); - queue = new ActiveMQQueue("TEST." + System.currentTimeMillis()); - } + protected void setUp() throws Exception { + broker = new BrokerService(); + connectionUri = broker.addConnector(BROKER_URL).getPublishableConnectString(); + broker.start(); + queue = new ActiveMQQueue("TEST." + System.currentTimeMillis()); + } - protected void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - } - } + protected void tearDown() throws Exception { + if (broker != null) { + broker.stop(); + } + } - public void testTextMessageCompression() throws Exception { + public void testTextMessageCompression() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - factory.setUseCompression(true); - sendTestMessage(factory, TEXT); - ActiveMQTextMessage message = receiveTestMessage(factory); - int compressedSize = message.getContent().getLength(); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); + factory.setUseCompression(true); + sendTestMessage(factory, TEXT); + ActiveMQTextMessage message = receiveTestMessage(factory); + int compressedSize = message.getContent().getLength(); - factory = new ActiveMQConnectionFactory(connectionUri); - factory.setUseCompression(false); - sendTestMessage(factory, TEXT); - message = receiveTestMessage(factory); - int unCompressedSize = message.getContent().getLength(); + factory = new ActiveMQConnectionFactory(connectionUri); + factory.setUseCompression(false); + sendTestMessage(factory, TEXT); + message = receiveTestMessage(factory); + int unCompressedSize = message.getContent().getLength(); - assertTrue("expected: compressed Size '" + compressedSize + "' < unCompressedSize '" + unCompressedSize + "'", - compressedSize < unCompressedSize); - } + assertTrue("expected: compressed Size '" + compressedSize + "' < unCompressedSize '" + unCompressedSize + "'", compressedSize < unCompressedSize); + } - public void testBytesMessageCompression() throws Exception { + public void testBytesMessageCompression() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - factory.setUseCompression(true); - sendTestBytesMessage(factory, TEXT); - ActiveMQBytesMessage message = receiveTestBytesMessage(factory); - int compressedSize = message.getContent().getLength(); - byte[] bytes = new byte[TEXT.getBytes("UTF8").length]; - message.readBytes(bytes); - assertTrue(message.readBytes(new byte[255]) == -1); - String rcvString = new String(bytes, "UTF8"); - assertEquals(TEXT, rcvString); - assertTrue(message.isCompressed()); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); + factory.setUseCompression(true); + sendTestBytesMessage(factory, TEXT); + ActiveMQBytesMessage message = receiveTestBytesMessage(factory); + int compressedSize = message.getContent().getLength(); + byte[] bytes = new byte[TEXT.getBytes("UTF8").length]; + message.readBytes(bytes); + assertTrue(message.readBytes(new byte[255]) == -1); + String rcvString = new String(bytes, "UTF8"); + assertEquals(TEXT, rcvString); + assertTrue(message.isCompressed()); - factory = new ActiveMQConnectionFactory(connectionUri); - factory.setUseCompression(false); - sendTestBytesMessage(factory, TEXT); - message = receiveTestBytesMessage(factory); - int unCompressedSize = message.getContent().getLength(); + factory = new ActiveMQConnectionFactory(connectionUri); + factory.setUseCompression(false); + sendTestBytesMessage(factory, TEXT); + message = receiveTestBytesMessage(factory); + int unCompressedSize = message.getContent().getLength(); - assertTrue("expected: compressed Size '" + compressedSize + "' < unCompressedSize '" + unCompressedSize + "'", - compressedSize < unCompressedSize); - } + assertTrue("expected: compressed Size '" + compressedSize + "' < unCompressedSize '" + unCompressedSize + "'", compressedSize < unCompressedSize); + } - private void sendTestMessage(ActiveMQConnectionFactory factory, String message) throws JMSException { - ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(queue); - producer.send(session.createTextMessage(message)); - connection.close(); - } + private void sendTestMessage(ActiveMQConnectionFactory factory, String message) throws JMSException { + ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(queue); + producer.send(session.createTextMessage(message)); + connection.close(); + } - private ActiveMQTextMessage receiveTestMessage(ActiveMQConnectionFactory factory) throws JMSException { - ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(queue); - ActiveMQTextMessage rc = (ActiveMQTextMessage) consumer.receive(); - connection.close(); - return rc; - } + private ActiveMQTextMessage receiveTestMessage(ActiveMQConnectionFactory factory) throws JMSException { + ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(queue); + ActiveMQTextMessage rc = (ActiveMQTextMessage) consumer.receive(); + connection.close(); + return rc; + } - private void sendTestBytesMessage(ActiveMQConnectionFactory factory, String message) throws JMSException, UnsupportedEncodingException { - ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(queue); - BytesMessage bytesMessage = session.createBytesMessage(); - bytesMessage.writeBytes(message.getBytes("UTF8")); - producer.send(bytesMessage); - connection.close(); - } + private void sendTestBytesMessage(ActiveMQConnectionFactory factory, + String message) throws JMSException, UnsupportedEncodingException { + ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(queue); + BytesMessage bytesMessage = session.createBytesMessage(); + bytesMessage.writeBytes(message.getBytes("UTF8")); + producer.send(bytesMessage); + connection.close(); + } - private ActiveMQBytesMessage receiveTestBytesMessage(ActiveMQConnectionFactory factory) throws JMSException, UnsupportedEncodingException { - ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(queue); - ActiveMQBytesMessage rc = (ActiveMQBytesMessage) consumer.receive(); - connection.close(); - return rc; - } + private ActiveMQBytesMessage receiveTestBytesMessage(ActiveMQConnectionFactory factory) throws JMSException, UnsupportedEncodingException { + ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(queue); + ActiveMQBytesMessage rc = (ActiveMQBytesMessage) consumer.receive(); + connection.close(); + return rc; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/MessageSendTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/MessageSendTest.java index ec81800d0a..a436754cc8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/MessageSendTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/MessageSendTest.java @@ -25,54 +25,55 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MessageSendTest extends DataStructureTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(MessageSendTest.class); - public static Test suite() { - return suite(MessageSendTest.class); - } + private static final Logger LOG = LoggerFactory.getLogger(MessageSendTest.class); - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static Test suite() { + return suite(MessageSendTest.class); + } - public void initCombosForTestMessageSendMarshaling() { - addCombinationValues("cacheEnabled", new Object[] {Boolean.TRUE, Boolean.FALSE}); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - public void testMessageSendMarshaling() throws IOException { - ActiveMQMessage message = new ActiveMQMessage(); - message.setCommandId((short)1); - message.setDestination(new ActiveMQQueue("queue")); - message.setGroupID("group"); - message.setGroupSequence(4); - message.setCorrelationId("correlation"); - message.setMessageId(new MessageId("c1:1:1", 1)); + public void initCombosForTestMessageSendMarshaling() { + addCombinationValues("cacheEnabled", new Object[]{Boolean.TRUE, Boolean.FALSE}); + } - assertBeanMarshalls(message); - assertBeanMarshalls(message); + public void testMessageSendMarshaling() throws IOException { + ActiveMQMessage message = new ActiveMQMessage(); + message.setCommandId((short) 1); + message.setDestination(new ActiveMQQueue("queue")); + message.setGroupID("group"); + message.setGroupSequence(4); + message.setCorrelationId("correlation"); + message.setMessageId(new MessageId("c1:1:1", 1)); - } + assertBeanMarshalls(message); + assertBeanMarshalls(message); - public void xtestPerformance() throws IOException { - ActiveMQMessage message = new ActiveMQMessage(); - message.setProducerId(new ProducerId(new SessionId(new ConnectionId(new ConnectionId("test")), 1), 1)); - message.setMessageId(new MessageId(message.getProducerId(), 1)); - message.setCommandId((short)1); - message.setGroupID("group"); - message.setGroupSequence(4); - message.setCorrelationId("correlation"); - message.setContent(new ByteSequence(new byte[1024], 0, 1024)); - message.setTimestamp(System.currentTimeMillis()); - message.setDestination(new ActiveMQQueue("TEST")); + } - int p = 1000000; + public void xtestPerformance() throws IOException { + ActiveMQMessage message = new ActiveMQMessage(); + message.setProducerId(new ProducerId(new SessionId(new ConnectionId(new ConnectionId("test")), 1), 1)); + message.setMessageId(new MessageId(message.getProducerId(), 1)); + message.setCommandId((short) 1); + message.setGroupID("group"); + message.setGroupSequence(4); + message.setCorrelationId("correlation"); + message.setContent(new ByteSequence(new byte[1024], 0, 1024)); + message.setTimestamp(System.currentTimeMillis()); + message.setDestination(new ActiveMQQueue("TEST")); - long start = System.currentTimeMillis(); - for (int i = 0; i < p; i++) { - marshalAndUnmarshall(message, wireFormat); - } - long end = System.currentTimeMillis(); + int p = 1000000; - LOG.info("marshaled/unmarshaled: " + p + " msgs at " + (p * 1000f / (end - start)) + " msgs/sec"); - } + long start = System.currentTimeMillis(); + for (int i = 0; i < p; i++) { + marshalAndUnmarshall(message, wireFormat); + } + long end = System.currentTimeMillis(); + + LOG.info("marshaled/unmarshaled: " + p + " msgs at " + (p * 1000f / (end - start)) + " msgs/sec"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/MessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/MessageTest.java index f33c5b4524..b849849758 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/MessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/command/MessageTest.java @@ -19,82 +19,83 @@ package org.apache.activemq.command; import java.io.IOException; import junit.framework.Test; + import junit.textui.TestRunner; public class MessageTest extends DataStructureTestSupport { - public boolean cacheEnabled; + public boolean cacheEnabled; - public static Test suite() { - return suite(MessageTest.class); - } + public static Test suite() { + return suite(MessageTest.class); + } - public static void main(String[] args) { - TestRunner.run(suite()); - } + public static void main(String[] args) { + TestRunner.run(suite()); + } - public void initCombosForTestActiveMQMessageMarshaling() { - addCombinationValues("cacheEnabled", new Object[] {Boolean.TRUE, Boolean.FALSE}); - } + public void initCombosForTestActiveMQMessageMarshaling() { + addCombinationValues("cacheEnabled", new Object[]{Boolean.TRUE, Boolean.FALSE}); + } - public void testActiveMQMessageMarshaling() throws IOException { - ActiveMQMessage message = new ActiveMQMessage(); - message.setCommandId((short)1); - message.setOriginalDestination(new ActiveMQQueue("queue")); - message.setGroupID("group"); - message.setGroupSequence(4); - message.setCorrelationId("correlation"); - message.setMessageId(new MessageId("c1:1:1", 1)); - assertBeanMarshalls(message); - } + public void testActiveMQMessageMarshaling() throws IOException { + ActiveMQMessage message = new ActiveMQMessage(); + message.setCommandId((short) 1); + message.setOriginalDestination(new ActiveMQQueue("queue")); + message.setGroupID("group"); + message.setGroupSequence(4); + message.setCorrelationId("correlation"); + message.setMessageId(new MessageId("c1:1:1", 1)); + assertBeanMarshalls(message); + } - public void testActiveMQMessageMarshalingBigMessageId() throws IOException { - ActiveMQMessage message = new ActiveMQMessage(); - message.setCommandId((short)1); - message.setOriginalDestination(new ActiveMQQueue("queue")); - message.setGroupID("group"); - message.setGroupSequence(4); - message.setCorrelationId("correlation"); - message.setMessageId(new MessageId("c1:1:1", Short.MAX_VALUE)); - assertBeanMarshalls(message); - } + public void testActiveMQMessageMarshalingBigMessageId() throws IOException { + ActiveMQMessage message = new ActiveMQMessage(); + message.setCommandId((short) 1); + message.setOriginalDestination(new ActiveMQQueue("queue")); + message.setGroupID("group"); + message.setGroupSequence(4); + message.setCorrelationId("correlation"); + message.setMessageId(new MessageId("c1:1:1", Short.MAX_VALUE)); + assertBeanMarshalls(message); + } - public void testActiveMQMessageMarshalingBiggerMessageId() throws IOException { - ActiveMQMessage message = new ActiveMQMessage(); - message.setCommandId((short)1); - message.setOriginalDestination(new ActiveMQQueue("queue")); - message.setGroupID("group"); - message.setGroupSequence(4); - message.setCorrelationId("correlation"); - message.setMessageId(new MessageId("c1:1:1", Integer.MAX_VALUE)); - assertBeanMarshalls(message); - } + public void testActiveMQMessageMarshalingBiggerMessageId() throws IOException { + ActiveMQMessage message = new ActiveMQMessage(); + message.setCommandId((short) 1); + message.setOriginalDestination(new ActiveMQQueue("queue")); + message.setGroupID("group"); + message.setGroupSequence(4); + message.setCorrelationId("correlation"); + message.setMessageId(new MessageId("c1:1:1", Integer.MAX_VALUE)); + assertBeanMarshalls(message); + } - public void testActiveMQMessageMarshalingBiggestMessageId() throws IOException { - ActiveMQMessage message = new ActiveMQMessage(); - message.setCommandId((short)1); - message.setOriginalDestination(new ActiveMQQueue("queue")); - message.setGroupID("group"); - message.setGroupSequence(4); - message.setCorrelationId("correlation"); - message.setMessageId(new MessageId("c1:1:1", Long.MAX_VALUE)); - assertBeanMarshalls(message); - } + public void testActiveMQMessageMarshalingBiggestMessageId() throws IOException { + ActiveMQMessage message = new ActiveMQMessage(); + message.setCommandId((short) 1); + message.setOriginalDestination(new ActiveMQQueue("queue")); + message.setGroupID("group"); + message.setGroupSequence(4); + message.setCorrelationId("correlation"); + message.setMessageId(new MessageId("c1:1:1", Long.MAX_VALUE)); + assertBeanMarshalls(message); + } - public void testMessageIdMarshaling() throws IOException { - assertBeanMarshalls(new MessageId("c1:1:1", 1)); - } + public void testMessageIdMarshaling() throws IOException { + assertBeanMarshalls(new MessageId("c1:1:1", 1)); + } - public void testPropRemove() throws Exception { - ActiveMQMessage message = new ActiveMQMessage(); - message.setStringProperty("RM","RM"); + public void testPropRemove() throws Exception { + ActiveMQMessage message = new ActiveMQMessage(); + message.setStringProperty("RM", "RM"); - ActiveMQMessage unMarshalled = (ActiveMQMessage) marshalAndUnmarshall(message, wireFormat); + ActiveMQMessage unMarshalled = (ActiveMQMessage) marshalAndUnmarshall(message, wireFormat); - unMarshalled.getBooleanProperty("NA"); - unMarshalled.removeProperty("RM"); + unMarshalled.getBooleanProperty("NA"); + unMarshalled.removeProperty("RM"); - ActiveMQMessage unMarshalledAgain = (ActiveMQMessage) marshalAndUnmarshall(unMarshalled, wireFormat); - assertNull("Prop is gone", unMarshalledAgain.getProperty("RM")); - } + ActiveMQMessage unMarshalledAgain = (ActiveMQMessage) marshalAndUnmarshall(unMarshalled, wireFormat); + assertNull("Prop is gone", unMarshalledAgain.getProperty("RM")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/BrokerPropertiesTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/BrokerPropertiesTest.java index f8c3ec5725..f7744d3f2a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/BrokerPropertiesTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/BrokerPropertiesTest.java @@ -17,7 +17,9 @@ package org.apache.activemq.config; import javax.jms.Connection; + import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerFactory; import org.apache.activemq.broker.BrokerRegistry; @@ -26,35 +28,35 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class BrokerPropertiesTest extends TestCase { - private static final transient Logger LOG = LoggerFactory.getLogger(BrokerPropertiesTest.class); - - public void testPropertiesFile() throws Exception { - BrokerService broker = BrokerFactory.createBroker("properties:org/apache/activemq/config/broker.properties"); - LOG.info("Created broker: " + broker); - assertNotNull(broker); + private static final transient Logger LOG = LoggerFactory.getLogger(BrokerPropertiesTest.class); - assertEquals("isUseJmx()", false, broker.isUseJmx()); - assertEquals("isPersistent()", false, broker.isPersistent()); - assertEquals("getBrokerName()", "Cheese", broker.getBrokerName()); - broker.stop(); - } + public void testPropertiesFile() throws Exception { + BrokerService broker = BrokerFactory.createBroker("properties:org/apache/activemq/config/broker.properties"); + LOG.info("Created broker: " + broker); + assertNotNull(broker); - public void testVmBrokerPropertiesFile() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?brokerConfig=properties:org/apache/activemq/config/broker.properties"); - Connection connection = factory.createConnection(); - BrokerService broker = BrokerRegistry.getInstance().lookup("Cheese"); - LOG.info("Found broker : " + broker); - assertNotNull(broker); + assertEquals("isUseJmx()", false, broker.isUseJmx()); + assertEquals("isPersistent()", false, broker.isPersistent()); + assertEquals("getBrokerName()", "Cheese", broker.getBrokerName()); + broker.stop(); + } - assertEquals("isUseJmx()", false, broker.isUseJmx()); - assertEquals("isPersistent()", false, broker.isPersistent()); - assertEquals("getBrokerName()", "Cheese", broker.getBrokerName()); - connection.close(); - broker.stop(); - } + public void testVmBrokerPropertiesFile() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?brokerConfig=properties:org/apache/activemq/config/broker.properties"); + Connection connection = factory.createConnection(); + BrokerService broker = BrokerRegistry.getInstance().lookup("Cheese"); + LOG.info("Found broker : " + broker); + assertNotNull(broker); + + assertEquals("isUseJmx()", false, broker.isUseJmx()); + assertEquals("isPersistent()", false, broker.isPersistent()); + assertEquals("getBrokerName()", "Cheese", broker.getBrokerName()); + connection.close(); + broker.stop(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/BrokerXmlConfigFromJNDITest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/BrokerXmlConfigFromJNDITest.java index 936603c3b8..a1da8f5f4e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/BrokerXmlConfigFromJNDITest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/BrokerXmlConfigFromJNDITest.java @@ -29,25 +29,26 @@ import org.apache.activemq.test.JmsTopicSendReceiveWithTwoConnectionsTest; * */ public class BrokerXmlConfigFromJNDITest extends JmsTopicSendReceiveWithTwoConnectionsTest { - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - assertBaseDirectoryContainsSpaces(); - // we could put these properties into a jndi.properties - // on the classpath instead - Hashtable properties = new Hashtable(); - properties.put("java.naming.factory.initial", "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); + @Override + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + assertBaseDirectoryContainsSpaces(); - // configure the embedded broker using an XML config file - // which is either a URL or a resource on the classpath - File f = new File(System.getProperty("basedir", "."), "/src/test/resources/activemq.xml"); - properties.put(Context.PROVIDER_URL, "vm://localhost?brokerConfig=xbean:" + f.toURI()); + // we could put these properties into a jndi.properties + // on the classpath instead + Hashtable properties = new Hashtable(); + properties.put("java.naming.factory.initial", "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); - InitialContext context = new InitialContext(properties); - ActiveMQConnectionFactory connectionFactory = (ActiveMQConnectionFactory) context.lookup("ConnectionFactory"); + // configure the embedded broker using an XML config file + // which is either a URL or a resource on the classpath + File f = new File(System.getProperty("basedir", "."), "/src/test/resources/activemq.xml"); + properties.put(Context.PROVIDER_URL, "vm://localhost?brokerConfig=xbean:" + f.toURI()); - // END SNIPPET: example - return connectionFactory; - } + InitialContext context = new InitialContext(properties); + ActiveMQConnectionFactory connectionFactory = (ActiveMQConnectionFactory) context.lookup("ConnectionFactory"); + + // END SNIPPET: example + return connectionFactory; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/BrokerXmlConfigTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/BrokerXmlConfigTest.java index c392b121ed..0e52c78f7e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/BrokerXmlConfigTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/BrokerXmlConfigTest.java @@ -20,29 +20,30 @@ import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.test.JmsTopicSendReceiveWithTwoConnectionsTest; /** - * + * */ public class BrokerXmlConfigTest extends JmsTopicSendReceiveWithTwoConnectionsTest { - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - // START SNIPPET: bean - // configure the connection factory using - // normal Java Bean property methods - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + // START SNIPPET: bean - // configure the embedded broker using an XML config file - // which is either a URL or a resource on the classpath + // configure the connection factory using + // normal Java Bean property methods + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); - // TODO ... + // configure the embedded broker using an XML config file + // which is either a URL or a resource on the classpath - //connectionFactory.setBrokerXmlConfig("file:src/sample-conf/default.xml"); + // TODO ... - // you only need to configure the broker URL if you wish to change the - // default connection mechanism, which in this test case we do - connectionFactory.setBrokerURL("vm://localhost"); + //connectionFactory.setBrokerXmlConfig("file:src/sample-conf/default.xml"); - // END SNIPPET: bean - return connectionFactory; - } + // you only need to configure the broker URL if you wish to change the + // default connection mechanism, which in this test case we do + connectionFactory.setBrokerURL("vm://localhost"); + + // END SNIPPET: bean + return connectionFactory; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/ConfigTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/ConfigTest.java index 82b5ebec76..9ded99d8e6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/ConfigTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/ConfigTest.java @@ -66,19 +66,19 @@ import org.springframework.core.io.Resource; public class ConfigTest { - protected static final String JOURNAL_ROOT = "target/test-data/"; - protected static final String DERBY_ROOT = "target/test-data/"; - protected static final String CONF_ROOT = "src/test/resources/org/apache/activemq/config/sample-conf/"; - private static final Logger LOG = LoggerFactory.getLogger(ConfigTest.class); + protected static final String JOURNAL_ROOT = "target/test-data/"; + protected static final String DERBY_ROOT = "target/test-data/"; + protected static final String CONF_ROOT = "src/test/resources/org/apache/activemq/config/sample-conf/"; + private static final Logger LOG = LoggerFactory.getLogger(ConfigTest.class); - static { - System.setProperty("javax.net.ssl.trustStore", "src/test/resources/client.keystore"); - System.setProperty("javax.net.ssl.trustStorePassword", "password"); - System.setProperty("javax.net.ssl.trustStoreType", "jks"); - System.setProperty("javax.net.ssl.keyStore", "src/test/resources/server.keystore"); - System.setProperty("javax.net.ssl.keyStorePassword", "password"); - System.setProperty("javax.net.ssl.keyStoreType", "jks"); - } + static { + System.setProperty("javax.net.ssl.trustStore", "src/test/resources/client.keystore"); + System.setProperty("javax.net.ssl.trustStorePassword", "password"); + System.setProperty("javax.net.ssl.trustStoreType", "jks"); + System.setProperty("javax.net.ssl.keyStore", "src/test/resources/server.keystore"); + System.setProperty("javax.net.ssl.keyStorePassword", "password"); + System.setProperty("javax.net.ssl.keyStoreType", "jks"); + } /* * IMPORTANT NOTE: Assertions checking for the existence of the derby @@ -87,371 +87,377 @@ public class ConfigTest { * for succeeding creation. It uses the first created directory as the root. */ - /* - * This tests creating a journal persistence adapter using the persistence - * adapter factory bean - */ - @Test - public void testJournaledJDBCConfig() throws Exception { + /* + * This tests creating a journal persistence adapter using the persistence + * adapter factory bean + */ + @Test + public void testJournaledJDBCConfig() throws Exception { - File journalFile = new File(JOURNAL_ROOT + "testJournaledJDBCConfig/journal"); - recursiveDelete(journalFile); + File journalFile = new File(JOURNAL_ROOT + "testJournaledJDBCConfig/journal"); + recursiveDelete(journalFile); - File derbyFile = new File(DERBY_ROOT + "testJournaledJDBCConfig/derbydb"); // Default - recursiveDelete(derbyFile); + File derbyFile = new File(DERBY_ROOT + "testJournaledJDBCConfig/derbydb"); // Default + recursiveDelete(derbyFile); - BrokerService broker; - broker = createBroker(new FileSystemResource(CONF_ROOT + "journaledjdbc-example.xml")); - try { - assertEquals("Broker Config Error (brokerName)", "brokerJournaledJDBCConfigTest", broker.getBrokerName()); + BrokerService broker; + broker = createBroker(new FileSystemResource(CONF_ROOT + "journaledjdbc-example.xml")); + try { + assertEquals("Broker Config Error (brokerName)", "brokerJournaledJDBCConfigTest", broker.getBrokerName()); - PersistenceAdapter adapter = broker.getPersistenceAdapter(); + PersistenceAdapter adapter = broker.getPersistenceAdapter(); - assertTrue("Should have created a journal persistence adapter", adapter instanceof JournalPersistenceAdapter); - assertTrue("Should have created a derby directory at " + derbyFile.getAbsolutePath(), derbyFile.exists()); - assertTrue("Should have created a journal directory at " + journalFile.getAbsolutePath(), journalFile.exists()); + assertTrue("Should have created a journal persistence adapter", adapter instanceof JournalPersistenceAdapter); + assertTrue("Should have created a derby directory at " + derbyFile.getAbsolutePath(), derbyFile.exists()); + assertTrue("Should have created a journal directory at " + journalFile.getAbsolutePath(), journalFile.exists()); - // Check persistence factory configurations - broker.getPersistenceAdapter(); + // Check persistence factory configurations + broker.getPersistenceAdapter(); - assertTrue(broker.getSystemUsage().getStoreUsage().getStore() instanceof JournalPersistenceAdapter); + assertTrue(broker.getSystemUsage().getStoreUsage().getStore() instanceof JournalPersistenceAdapter); - LOG.info("Success"); - } finally { - if (broker != null) { - broker.stop(); + LOG.info("Success"); + } + finally { + if (broker != null) { + broker.stop(); + } + } + } + + @Test + public void testJdbcLockConfigOverride() throws Exception { + + JDBCPersistenceAdapter adapter = new JDBCPersistenceAdapter(); + Mockery context = new Mockery(); + final DataSource dataSource = context.mock(DataSource.class); + final Connection connection = context.mock(Connection.class); + final DatabaseMetaData metadata = context.mock(DatabaseMetaData.class); + final ResultSet result = context.mock(ResultSet.class); + adapter.setDataSource(dataSource); + adapter.setCreateTablesOnStartup(false); + + context.checking(new Expectations() {{ + allowing(dataSource).getConnection(); + will(returnValue(connection)); + allowing(connection).getMetaData(); + will(returnValue(metadata)); + allowing(connection); + allowing(metadata).getDriverName(); + will(returnValue("Microsoft_SQL_Server_2005_jdbc_driver")); + allowing(result).next(); + will(returnValue(true)); + }}); + + adapter.start(); + assertTrue("has the locker override", adapter.getLocker() instanceof TransactDatabaseLocker); + adapter.stop(); + } + + public void testJdbcLockConfigDefault() throws Exception { + + JDBCPersistenceAdapter adapter = new JDBCPersistenceAdapter(); + Mockery context = new Mockery(); + final DataSource dataSource = context.mock(DataSource.class); + final Connection connection = context.mock(Connection.class); + final DatabaseMetaData metadata = context.mock(DatabaseMetaData.class); + final ResultSet result = context.mock(ResultSet.class); + adapter.setDataSource(dataSource); + adapter.setCreateTablesOnStartup(false); + + context.checking(new Expectations() {{ + allowing(dataSource).getConnection(); + will(returnValue(connection)); + allowing(connection).getMetaData(); + will(returnValue(metadata)); + allowing(connection); + allowing(metadata).getDriverName(); + will(returnValue("Some_Unknown_driver")); + allowing(result).next(); + will(returnValue(true)); + }}); + + adapter.start(); + assertEquals("has the default locker", adapter.getLocker().getClass(), DefaultDatabaseLocker.class); + adapter.stop(); + } + + /* + * This tests configuring the different broker properties using + * xbeans-spring + */ + @Test + public void testBrokerConfig() throws Exception { + ActiveMQTopic dest; + BrokerService broker; + + File journalFile = new File(JOURNAL_ROOT); + recursiveDelete(journalFile); + + // Create broker from resource + // System.out.print("Creating broker... "); + broker = createBroker("org/apache/activemq/config/example.xml"); + LOG.info("Success"); + + try { + // Check broker configuration + // System.out.print("Checking broker configurations... "); + assertEquals("Broker Config Error (brokerName)", "brokerConfigTest", broker.getBrokerName()); + assertEquals("Broker Config Error (populateJMSXUserID)", false, broker.isPopulateJMSXUserID()); + assertEquals("Broker Config Error (useLoggingForShutdownErrors)", true, broker.isUseLoggingForShutdownErrors()); + assertEquals("Broker Config Error (useJmx)", true, broker.isUseJmx()); + assertEquals("Broker Config Error (persistent)", false, broker.isPersistent()); + assertEquals("Broker Config Error (useShutdownHook)", false, broker.isUseShutdownHook()); + assertEquals("Broker Config Error (deleteAllMessagesOnStartup)", true, broker.isDeleteAllMessagesOnStartup()); + LOG.info("Success"); + + // Check specific vm transport + // System.out.print("Checking vm connector... "); + assertEquals("Should have a specific VM Connector", "vm://javacoola", broker.getVmConnectorURI().toString()); + LOG.info("Success"); + + // Check transport connectors list + // System.out.print("Checking transport connectors... "); + List connectors = broker.getTransportConnectors(); + assertTrue("Should have created at least 3 connectors", connectors.size() >= 3); + assertTrue("1st connector should be TcpTransportServer", connectors.get(0).getServer() instanceof TcpTransportServer); + assertTrue("2nd connector should be TcpTransportServer", connectors.get(1).getServer() instanceof TcpTransportServer); + assertTrue("3rd connector should be TcpTransportServer", connectors.get(2).getServer() instanceof TcpTransportServer); + + // Check network connectors + // System.out.print("Checking network connectors... "); + List networkConnectors = broker.getNetworkConnectors(); + assertEquals("Should have a single network connector", 1, networkConnectors.size()); + LOG.info("Success"); + + // Check dispatch policy configuration + // System.out.print("Checking dispatch policies... "); + + dest = new ActiveMQTopic("Topic.SimpleDispatch"); + assertTrue("Should have a simple dispatch policy for " + dest.getTopicName(), broker.getDestinationPolicy().getEntryFor(dest).getDispatchPolicy() instanceof SimpleDispatchPolicy); + + dest = new ActiveMQTopic("Topic.RoundRobinDispatch"); + assertTrue("Should have a round robin dispatch policy for " + dest.getTopicName(), broker.getDestinationPolicy().getEntryFor(dest).getDispatchPolicy() instanceof RoundRobinDispatchPolicy); + + dest = new ActiveMQTopic("Topic.StrictOrderDispatch"); + assertTrue("Should have a strict order dispatch policy for " + dest.getTopicName(), broker.getDestinationPolicy().getEntryFor(dest).getDispatchPolicy() instanceof StrictOrderDispatchPolicy); + LOG.info("Success"); + + // Check subscription policy configuration + // System.out.print("Checking subscription recovery policies... "); + SubscriptionRecoveryPolicy subsPolicy; + + dest = new ActiveMQTopic("Topic.FixedSizedSubs"); + subsPolicy = broker.getDestinationPolicy().getEntryFor(dest).getSubscriptionRecoveryPolicy(); + assertTrue("Should have a fixed sized subscription recovery policy for " + dest.getTopicName(), subsPolicy instanceof FixedSizedSubscriptionRecoveryPolicy); + assertEquals("FixedSizedSubsPolicy Config Error (maximumSize)", 2000000, ((FixedSizedSubscriptionRecoveryPolicy) subsPolicy).getMaximumSize()); + assertEquals("FixedSizedSubsPolicy Config Error (useSharedBuffer)", false, ((FixedSizedSubscriptionRecoveryPolicy) subsPolicy).isUseSharedBuffer()); + + dest = new ActiveMQTopic("Topic.LastImageSubs"); + subsPolicy = broker.getDestinationPolicy().getEntryFor(dest).getSubscriptionRecoveryPolicy(); + assertTrue("Should have a last image subscription recovery policy for " + dest.getTopicName(), subsPolicy instanceof LastImageSubscriptionRecoveryPolicy); + + dest = new ActiveMQTopic("Topic.NoSubs"); + subsPolicy = broker.getDestinationPolicy().getEntryFor(dest).getSubscriptionRecoveryPolicy(); + assertTrue("Should have no subscription recovery policy for " + dest.getTopicName(), subsPolicy instanceof NoSubscriptionRecoveryPolicy); + + dest = new ActiveMQTopic("Topic.TimedSubs"); + subsPolicy = broker.getDestinationPolicy().getEntryFor(dest).getSubscriptionRecoveryPolicy(); + assertTrue("Should have a timed subscription recovery policy for " + dest.getTopicName(), subsPolicy instanceof TimedSubscriptionRecoveryPolicy); + assertEquals("TimedSubsPolicy Config Error (recoverDuration)", 25000, ((TimedSubscriptionRecoveryPolicy) subsPolicy).getRecoverDuration()); + LOG.info("Success"); + + // Check usage manager + // System.out.print("Checking memory manager configurations... "); + SystemUsage systemUsage = broker.getSystemUsage(); + assertTrue("Should have a SystemUsage", systemUsage != null); + assertEquals("SystemUsage Config Error (MemoryUsage.limit)", 1024 * 1024 * 10, systemUsage.getMemoryUsage().getLimit()); + assertEquals("SystemUsage Config Error (MemoryUsage.percentUsageMinDelta)", 20, systemUsage.getMemoryUsage().getPercentUsageMinDelta()); + assertEquals("SystemUsage Config Error (TempUsage.limit)", 1024 * 1024 * 100, systemUsage.getTempUsage().getLimit()); + assertEquals("SystemUsage Config Error (StoreUsage.limit)", 1024 * 1024 * 1024, systemUsage.getStoreUsage().getLimit()); + assertEquals("SystemUsage Config Error (StoreUsage.name)", "foo", systemUsage.getStoreUsage().getName()); + + assertNotNull(systemUsage.getStoreUsage().getStore()); + assertTrue(systemUsage.getStoreUsage().getStore() instanceof MemoryPersistenceAdapter); + + LOG.info("Success"); + + } + finally { + if (broker != null) { + broker.stop(); + } + } + } + + /* + * This tests creating a journal persistence adapter using xbeans-spring + */ + @Test + public void testJournalConfig() throws Exception { + File journalFile = new File(JOURNAL_ROOT + "testJournalConfig/journal"); + recursiveDelete(journalFile); + + BrokerService broker; + broker = createBroker(new FileSystemResource(CONF_ROOT + "journal-example.xml")); + try { + assertEquals("Broker Config Error (brokerName)", "brokerJournalConfigTest", broker.getBrokerName()); + + PersistenceAdapter adapter = broker.getPersistenceAdapter(); + + assertTrue("Should have created a journal persistence adapter", adapter instanceof JournalPersistenceAdapter); + assertTrue("Should have created a journal directory at " + journalFile.getAbsolutePath(), journalFile.exists()); + + LOG.info("Success"); + } + finally { + if (broker != null) { + broker.stop(); + } + } + } + + /* + * This tests creating a memory persistence adapter using xbeans-spring + */ + @Test + public void testMemoryConfig() throws Exception { + File journalFile = new File(JOURNAL_ROOT + "testMemoryConfig"); + recursiveDelete(journalFile); + + File derbyFile = new File(DERBY_ROOT + "testMemoryConfig"); + recursiveDelete(derbyFile); + + BrokerService broker; + broker = createBroker(new FileSystemResource(CONF_ROOT + "memory-example.xml")); + + try { + assertEquals("Broker Config Error (brokerName)", "brokerMemoryConfigTest", broker.getBrokerName()); + + PersistenceAdapter adapter = broker.getPersistenceAdapter(); + + assertTrue("Should have created a memory persistence adapter", adapter instanceof MemoryPersistenceAdapter); + assertTrue("Should have not created a derby directory at " + derbyFile.getAbsolutePath(), !derbyFile.exists()); + assertTrue("Should have not created a journal directory at " + journalFile.getAbsolutePath(), !journalFile.exists()); + + LOG.info("Success"); + } + finally { + if (broker != null) { + broker.stop(); + } + } + } + + @Test + public void testConnectorConfig() throws Exception { + + File journalFile = new File(JOURNAL_ROOT + "testMemoryConfig"); + recursiveDelete(journalFile); + + File derbyFile = new File(DERBY_ROOT + "testMemoryConfig"); + recursiveDelete(derbyFile); + + final int MAX_PRODUCERS = 5; + final int MAX_CONSUMERS = 10; + + BrokerService broker = createBroker(new FileSystemResource(CONF_ROOT + "connector-properties.xml")); + broker.start(); + try { + + assertEquals(broker.getTransportConnectorByScheme("tcp").getMaximumProducersAllowedPerConnection(), MAX_PRODUCERS); + assertEquals(broker.getTransportConnectorByScheme("tcp").getMaximumConsumersAllowedPerConnection(), MAX_CONSUMERS); + + ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61631"); + javax.jms.Connection connection = activeMQConnectionFactory.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Topic topic = session.createTopic("test.foo"); + + for (int i = 0; i < MAX_PRODUCERS; i++) { + session.createProducer(topic); + } + + try { + session.createProducer(topic); + fail("Should have got an exception on exceeding MAX_PRODUCERS"); + } + catch (JMSException expected) { + } + + try { + for (int i = 0; i < (MAX_CONSUMERS + 1); i++) { + MessageConsumer consumer = session.createConsumer(topic); + assertNotNull(consumer); } - } - } + fail("Should have caught an exception"); + } + catch (JMSException e) { + } - @Test - public void testJdbcLockConfigOverride() throws Exception { + LOG.info("Success"); + } + finally { + if (broker != null) { + broker.stop(); + } + } + } - JDBCPersistenceAdapter adapter = new JDBCPersistenceAdapter(); - Mockery context = new Mockery(); - final DataSource dataSource = context.mock(DataSource.class); - final Connection connection = context.mock(Connection.class); - final DatabaseMetaData metadata = context.mock(DatabaseMetaData.class); - final ResultSet result = context.mock(ResultSet.class); - adapter.setDataSource(dataSource); - adapter.setCreateTablesOnStartup(false); + @Test + public void testXmlConfigHelper() throws Exception { + BrokerService broker; - context.checking(new Expectations() {{ - allowing(dataSource).getConnection(); - will(returnValue(connection)); - allowing(connection).getMetaData(); - will(returnValue(metadata)); - allowing(connection); - allowing(metadata).getDriverName(); - will(returnValue("Microsoft_SQL_Server_2005_jdbc_driver")); - allowing(result).next(); - will(returnValue(true)); - }}); + broker = createBroker(new FileSystemResource(CONF_ROOT + "memory-example.xml")); + try { + assertEquals("Broker Config Error (brokerName)", "brokerMemoryConfigTest", broker.getBrokerName()); + } + finally { + if (broker != null) { + broker.stop(); + } + } - adapter.start(); - assertTrue("has the locker override", adapter.getLocker() instanceof TransactDatabaseLocker); - adapter.stop(); - } - - public void testJdbcLockConfigDefault() throws Exception { - - JDBCPersistenceAdapter adapter = new JDBCPersistenceAdapter(); - Mockery context = new Mockery(); - final DataSource dataSource = context.mock(DataSource.class); - final Connection connection = context.mock(Connection.class); - final DatabaseMetaData metadata = context.mock(DatabaseMetaData.class); - final ResultSet result = context.mock(ResultSet.class); - adapter.setDataSource(dataSource); - adapter.setCreateTablesOnStartup(false); - - context.checking(new Expectations() {{ - allowing(dataSource).getConnection(); - will(returnValue(connection)); - allowing(connection).getMetaData(); - will(returnValue(metadata)); - allowing(connection); - allowing(metadata).getDriverName(); - will(returnValue("Some_Unknown_driver")); - allowing(result).next(); - will(returnValue(true)); - }}); - - adapter.start(); - assertEquals("has the default locker", adapter.getLocker().getClass(), DefaultDatabaseLocker.class); - adapter.stop(); - } - - /* - * This tests configuring the different broker properties using - * xbeans-spring - */ - @Test - public void testBrokerConfig() throws Exception { - ActiveMQTopic dest; - BrokerService broker; - - File journalFile = new File(JOURNAL_ROOT); - recursiveDelete(journalFile); - - // Create broker from resource - // System.out.print("Creating broker... "); - broker = createBroker("org/apache/activemq/config/example.xml"); - LOG.info("Success"); - - try { - // Check broker configuration - // System.out.print("Checking broker configurations... "); - assertEquals("Broker Config Error (brokerName)", "brokerConfigTest", broker.getBrokerName()); - assertEquals("Broker Config Error (populateJMSXUserID)", false, broker.isPopulateJMSXUserID()); - assertEquals("Broker Config Error (useLoggingForShutdownErrors)", true, broker.isUseLoggingForShutdownErrors()); - assertEquals("Broker Config Error (useJmx)", true, broker.isUseJmx()); - assertEquals("Broker Config Error (persistent)", false, broker.isPersistent()); - assertEquals("Broker Config Error (useShutdownHook)", false, broker.isUseShutdownHook()); - assertEquals("Broker Config Error (deleteAllMessagesOnStartup)", true, broker.isDeleteAllMessagesOnStartup()); - LOG.info("Success"); - - // Check specific vm transport - // System.out.print("Checking vm connector... "); - assertEquals("Should have a specific VM Connector", "vm://javacoola", broker.getVmConnectorURI().toString()); - LOG.info("Success"); - - // Check transport connectors list - // System.out.print("Checking transport connectors... "); - List connectors = broker.getTransportConnectors(); - assertTrue("Should have created at least 3 connectors", connectors.size() >= 3); - assertTrue("1st connector should be TcpTransportServer", connectors.get(0).getServer() instanceof TcpTransportServer); - assertTrue("2nd connector should be TcpTransportServer", connectors.get(1).getServer() instanceof TcpTransportServer); - assertTrue("3rd connector should be TcpTransportServer", connectors.get(2).getServer() instanceof TcpTransportServer); - - // Check network connectors - // System.out.print("Checking network connectors... "); - List networkConnectors = broker.getNetworkConnectors(); - assertEquals("Should have a single network connector", 1, networkConnectors.size()); - LOG.info("Success"); - - // Check dispatch policy configuration - // System.out.print("Checking dispatch policies... "); - - dest = new ActiveMQTopic("Topic.SimpleDispatch"); - assertTrue("Should have a simple dispatch policy for " + dest.getTopicName(), - broker.getDestinationPolicy().getEntryFor(dest).getDispatchPolicy() instanceof SimpleDispatchPolicy); - - dest = new ActiveMQTopic("Topic.RoundRobinDispatch"); - assertTrue("Should have a round robin dispatch policy for " + dest.getTopicName(), - broker.getDestinationPolicy().getEntryFor(dest).getDispatchPolicy() instanceof RoundRobinDispatchPolicy); - - dest = new ActiveMQTopic("Topic.StrictOrderDispatch"); - assertTrue("Should have a strict order dispatch policy for " + dest.getTopicName(), - broker.getDestinationPolicy().getEntryFor(dest).getDispatchPolicy() instanceof StrictOrderDispatchPolicy); - LOG.info("Success"); - - // Check subscription policy configuration - // System.out.print("Checking subscription recovery policies... "); - SubscriptionRecoveryPolicy subsPolicy; - - dest = new ActiveMQTopic("Topic.FixedSizedSubs"); - subsPolicy = broker.getDestinationPolicy().getEntryFor(dest).getSubscriptionRecoveryPolicy(); - assertTrue("Should have a fixed sized subscription recovery policy for " + dest.getTopicName(), subsPolicy instanceof FixedSizedSubscriptionRecoveryPolicy); - assertEquals("FixedSizedSubsPolicy Config Error (maximumSize)", 2000000, ((FixedSizedSubscriptionRecoveryPolicy) subsPolicy).getMaximumSize()); - assertEquals("FixedSizedSubsPolicy Config Error (useSharedBuffer)", false, ((FixedSizedSubscriptionRecoveryPolicy) subsPolicy).isUseSharedBuffer()); - - dest = new ActiveMQTopic("Topic.LastImageSubs"); - subsPolicy = broker.getDestinationPolicy().getEntryFor(dest).getSubscriptionRecoveryPolicy(); - assertTrue("Should have a last image subscription recovery policy for " + dest.getTopicName(), subsPolicy instanceof LastImageSubscriptionRecoveryPolicy); - - dest = new ActiveMQTopic("Topic.NoSubs"); - subsPolicy = broker.getDestinationPolicy().getEntryFor(dest).getSubscriptionRecoveryPolicy(); - assertTrue("Should have no subscription recovery policy for " + dest.getTopicName(), subsPolicy instanceof NoSubscriptionRecoveryPolicy); - - dest = new ActiveMQTopic("Topic.TimedSubs"); - subsPolicy = broker.getDestinationPolicy().getEntryFor(dest).getSubscriptionRecoveryPolicy(); - assertTrue("Should have a timed subscription recovery policy for " + dest.getTopicName(), subsPolicy instanceof TimedSubscriptionRecoveryPolicy); - assertEquals("TimedSubsPolicy Config Error (recoverDuration)", 25000, ((TimedSubscriptionRecoveryPolicy) subsPolicy).getRecoverDuration()); - LOG.info("Success"); - - // Check usage manager - // System.out.print("Checking memory manager configurations... "); - SystemUsage systemUsage = broker.getSystemUsage(); - assertTrue("Should have a SystemUsage", systemUsage != null); - assertEquals("SystemUsage Config Error (MemoryUsage.limit)", 1024 * 1024 * 10, systemUsage.getMemoryUsage().getLimit()); - assertEquals("SystemUsage Config Error (MemoryUsage.percentUsageMinDelta)", 20, systemUsage.getMemoryUsage().getPercentUsageMinDelta()); - assertEquals("SystemUsage Config Error (TempUsage.limit)", 1024 * 1024 * 100, systemUsage.getTempUsage().getLimit()); - assertEquals("SystemUsage Config Error (StoreUsage.limit)", 1024 * 1024 * 1024, systemUsage.getStoreUsage().getLimit()); - assertEquals("SystemUsage Config Error (StoreUsage.name)", "foo", systemUsage.getStoreUsage().getName()); - - assertNotNull(systemUsage.getStoreUsage().getStore()); - assertTrue(systemUsage.getStoreUsage().getStore() instanceof MemoryPersistenceAdapter); - - LOG.info("Success"); - - } finally { - if (broker != null) { - broker.stop(); - } - } - } - - /* - * This tests creating a journal persistence adapter using xbeans-spring - */ - @Test - public void testJournalConfig() throws Exception { - File journalFile = new File(JOURNAL_ROOT + "testJournalConfig/journal"); - recursiveDelete(journalFile); - - BrokerService broker; - broker = createBroker(new FileSystemResource(CONF_ROOT + "journal-example.xml")); - try { - assertEquals("Broker Config Error (brokerName)", "brokerJournalConfigTest", broker.getBrokerName()); - - PersistenceAdapter adapter = broker.getPersistenceAdapter(); - - assertTrue("Should have created a journal persistence adapter", adapter instanceof JournalPersistenceAdapter); - assertTrue("Should have created a journal directory at " + journalFile.getAbsolutePath(), journalFile.exists()); - - LOG.info("Success"); - } finally { - if (broker != null) { - broker.stop(); - } - } - } - - /* - * This tests creating a memory persistence adapter using xbeans-spring - */ - @Test - public void testMemoryConfig() throws Exception { - File journalFile = new File(JOURNAL_ROOT + "testMemoryConfig"); - recursiveDelete(journalFile); - - File derbyFile = new File(DERBY_ROOT + "testMemoryConfig"); - recursiveDelete(derbyFile); - - BrokerService broker; - broker = createBroker(new FileSystemResource(CONF_ROOT + "memory-example.xml")); - - try { - assertEquals("Broker Config Error (brokerName)", "brokerMemoryConfigTest", broker.getBrokerName()); - - PersistenceAdapter adapter = broker.getPersistenceAdapter(); - - assertTrue("Should have created a memory persistence adapter", adapter instanceof MemoryPersistenceAdapter); - assertTrue("Should have not created a derby directory at " + derbyFile.getAbsolutePath(), !derbyFile.exists()); - assertTrue("Should have not created a journal directory at " + journalFile.getAbsolutePath(), !journalFile.exists()); - - LOG.info("Success"); - } finally { - if (broker != null) { - broker.stop(); - } - } - } - - @Test - public void testConnectorConfig() throws Exception { - - File journalFile = new File(JOURNAL_ROOT + "testMemoryConfig"); - recursiveDelete(journalFile); - - File derbyFile = new File(DERBY_ROOT + "testMemoryConfig"); - recursiveDelete(derbyFile); - - final int MAX_PRODUCERS = 5; - final int MAX_CONSUMERS = 10; - - BrokerService broker = createBroker(new FileSystemResource(CONF_ROOT + "connector-properties.xml")); - broker.start(); - try { - - assertEquals(broker.getTransportConnectorByScheme("tcp").getMaximumProducersAllowedPerConnection(), MAX_PRODUCERS); - assertEquals(broker.getTransportConnectorByScheme("tcp").getMaximumConsumersAllowedPerConnection(), MAX_CONSUMERS); - - ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61631"); - javax.jms.Connection connection = activeMQConnectionFactory.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic("test.foo"); - - for (int i = 0; i < MAX_PRODUCERS; i++) { - session.createProducer(topic); - } - - try { - session.createProducer(topic); - fail("Should have got an exception on exceeding MAX_PRODUCERS"); - } catch (JMSException expected) { - } - - try { - for (int i = 0; i < (MAX_CONSUMERS + 1); i++) { - MessageConsumer consumer = session.createConsumer(topic); - assertNotNull(consumer); - } - fail("Should have caught an exception"); - } catch (JMSException e) { - } - - LOG.info("Success"); - } finally { - if (broker != null) { - broker.stop(); - } - } - } - - @Test - public void testXmlConfigHelper() throws Exception { - BrokerService broker; - - broker = createBroker(new FileSystemResource(CONF_ROOT + "memory-example.xml")); - try { - assertEquals("Broker Config Error (brokerName)", "brokerMemoryConfigTest", broker.getBrokerName()); - } finally { - if (broker != null) { - broker.stop(); - } - } - - broker = createBroker("org/apache/activemq/config/config.xml"); - try { - assertEquals("Broker Config Error (brokerName)", "brokerXmlConfigHelper", broker.getBrokerName()); - } finally { - if (broker != null) { - broker.stop(); - } - } - } + broker = createBroker("org/apache/activemq/config/config.xml"); + try { + assertEquals("Broker Config Error (brokerName)", "brokerXmlConfigHelper", broker.getBrokerName()); + } + finally { + if (broker != null) { + broker.stop(); + } + } + } /* * TODO: Create additional tests for forwarding bridges */ - protected static void recursiveDelete(File file) { - if (file.isDirectory()) { - File[] files = file.listFiles(); - for (int i = 0; i < files.length; i++) { - recursiveDelete(files[i]); - } - } - file.delete(); - } + protected static void recursiveDelete(File file) { + if (file.isDirectory()) { + File[] files = file.listFiles(); + for (int i = 0; i < files.length; i++) { + recursiveDelete(files[i]); + } + } + file.delete(); + } - protected BrokerService createBroker(String resource) throws Exception { - return createBroker(new ClassPathResource(resource)); - } + protected BrokerService createBroker(String resource) throws Exception { + return createBroker(new ClassPathResource(resource)); + } - protected BrokerService createBroker(Resource resource) throws Exception { - BrokerFactoryBean factory = new BrokerFactoryBean(resource); - factory.afterPropertiesSet(); + protected BrokerService createBroker(Resource resource) throws Exception { + BrokerFactoryBean factory = new BrokerFactoryBean(resource); + factory.afterPropertiesSet(); - BrokerService broker = factory.getBroker(); + BrokerService broker = factory.getBroker(); - assertTrue("Should have a broker!", broker != null); + assertTrue("Should have a broker!", broker != null); - // Broker is already started by default when using the XML file - // broker.start(); + // Broker is already started by default when using the XML file + // broker.start(); - return broker; - } + return broker; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/ConfigUsingDestinationOptions.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/ConfigUsingDestinationOptions.java index 704e40852a..b85e6bc728 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/ConfigUsingDestinationOptions.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/ConfigUsingDestinationOptions.java @@ -28,45 +28,48 @@ import org.apache.activemq.ActiveMQMessageConsumer; import org.apache.activemq.command.ActiveMQQueue; public class ConfigUsingDestinationOptions extends TestCase { - public void testValidSelectorConfig() throws JMSException { - ActiveMQQueue queue = new ActiveMQQueue("TEST.FOO?consumer.selector=test=1"); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - Connection conn = factory.createConnection(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + public void testValidSelectorConfig() throws JMSException { + ActiveMQQueue queue = new ActiveMQQueue("TEST.FOO?consumer.selector=test=1"); - ActiveMQMessageConsumer cons; - // JMS selector should be priority - cons = (ActiveMQMessageConsumer) sess.createConsumer(queue, "test=2"); - assertEquals("test=2", cons.getMessageSelector()); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + Connection conn = factory.createConnection(); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - // Test setting using JMS destinations - cons = (ActiveMQMessageConsumer) sess.createConsumer(queue); - assertEquals("test=1", cons.getMessageSelector()); - } + ActiveMQMessageConsumer cons; + // JMS selector should be priority + cons = (ActiveMQMessageConsumer) sess.createConsumer(queue, "test=2"); + assertEquals("test=2", cons.getMessageSelector()); - public void testInvalidSelectorConfig() throws JMSException { - ActiveMQQueue queue = new ActiveMQQueue("TEST.FOO?consumer.selector=test||1"); + // Test setting using JMS destinations + cons = (ActiveMQMessageConsumer) sess.createConsumer(queue); + assertEquals("test=1", cons.getMessageSelector()); + } - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - Connection conn = factory.createConnection(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + public void testInvalidSelectorConfig() throws JMSException { + ActiveMQQueue queue = new ActiveMQQueue("TEST.FOO?consumer.selector=test||1"); - ActiveMQMessageConsumer cons; - // JMS selector should be priority - try { - cons = (ActiveMQMessageConsumer) sess.createConsumer(queue, "test||1"); - fail("Selector should be invalid" + cons); - } catch (InvalidSelectorException e) { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + Connection conn = factory.createConnection(); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - } + ActiveMQMessageConsumer cons; + // JMS selector should be priority + try { + cons = (ActiveMQMessageConsumer) sess.createConsumer(queue, "test||1"); + fail("Selector should be invalid" + cons); + } + catch (InvalidSelectorException e) { - // Test setting using JMS destinations - try { - cons = (ActiveMQMessageConsumer) sess.createConsumer(queue); - fail("Selector should be invalid" + cons); - } catch (InvalidSelectorException e) { + } - } - } + // Test setting using JMS destinations + try { + cons = (ActiveMQMessageConsumer) sess.createConsumer(queue); + fail("Selector should be invalid" + cons); + } + catch (InvalidSelectorException e) { + + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/JDBCConfigTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/JDBCConfigTest.java index e13f53d7f2..3b7b83ca77 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/JDBCConfigTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/JDBCConfigTest.java @@ -36,67 +36,68 @@ import org.springframework.core.io.Resource; public class JDBCConfigTest { - protected static final String JOURNAL_ROOT = "target/test-data/"; - protected static final String DERBY_ROOT = "target/test-data/"; - protected static final String CONF_ROOT = "src/test/resources/org/apache/activemq/config/sample-conf/"; - private static final Logger LOG = LoggerFactory.getLogger(JDBCConfigTest.class); + protected static final String JOURNAL_ROOT = "target/test-data/"; + protected static final String DERBY_ROOT = "target/test-data/"; + protected static final String CONF_ROOT = "src/test/resources/org/apache/activemq/config/sample-conf/"; + private static final Logger LOG = LoggerFactory.getLogger(JDBCConfigTest.class); - /* - * This tests creating a jdbc persistence adapter using xbeans-spring - */ - @Test - public void testJdbcConfig() throws Exception { - File journalFile = new File(JOURNAL_ROOT + "testJDBCConfig/journal"); - recursiveDelete(journalFile); + /* + * This tests creating a jdbc persistence adapter using xbeans-spring + */ + @Test + public void testJdbcConfig() throws Exception { + File journalFile = new File(JOURNAL_ROOT + "testJDBCConfig/journal"); + recursiveDelete(journalFile); - File derbyFile = new File(DERBY_ROOT + "testJDBCConfig/derbydb"); // Default - recursiveDelete(derbyFile); + File derbyFile = new File(DERBY_ROOT + "testJDBCConfig/derbydb"); // Default + recursiveDelete(derbyFile); - BrokerService broker; - broker = createBroker(new FileSystemResource(CONF_ROOT + "jdbc-example.xml")); - try { - assertEquals("Broker Config Error (brokerName)", "brokerJdbcConfigTest", broker.getBrokerName()); + BrokerService broker; + broker = createBroker(new FileSystemResource(CONF_ROOT + "jdbc-example.xml")); + try { + assertEquals("Broker Config Error (brokerName)", "brokerJdbcConfigTest", broker.getBrokerName()); - PersistenceAdapter adapter = broker.getPersistenceAdapter(); + PersistenceAdapter adapter = broker.getPersistenceAdapter(); - assertTrue("Should have created a jdbc persistence adapter", adapter instanceof JDBCPersistenceAdapter); - assertEquals("JDBC Adapter Config Error (cleanupPeriod)", 60000, ((JDBCPersistenceAdapter) adapter).getCleanupPeriod()); - assertTrue("Should have created an EmbeddedDataSource", ((JDBCPersistenceAdapter) adapter).getDataSource() instanceof EmbeddedDataSource); - assertTrue("Should have created a DefaultWireFormat", ((JDBCPersistenceAdapter) adapter).getWireFormat() instanceof ObjectStreamWireFormat); + assertTrue("Should have created a jdbc persistence adapter", adapter instanceof JDBCPersistenceAdapter); + assertEquals("JDBC Adapter Config Error (cleanupPeriod)", 60000, ((JDBCPersistenceAdapter) adapter).getCleanupPeriod()); + assertTrue("Should have created an EmbeddedDataSource", ((JDBCPersistenceAdapter) adapter).getDataSource() instanceof EmbeddedDataSource); + assertTrue("Should have created a DefaultWireFormat", ((JDBCPersistenceAdapter) adapter).getWireFormat() instanceof ObjectStreamWireFormat); - LOG.info("Success"); - } finally { - if (broker != null) { - broker.stop(); - } - } - } + LOG.info("Success"); + } + finally { + if (broker != null) { + broker.stop(); + } + } + } - protected static void recursiveDelete(File file) { - if (file.isDirectory()) { - File[] files = file.listFiles(); - for (int i = 0; i < files.length; i++) { - recursiveDelete(files[i]); - } - } - file.delete(); - } + protected static void recursiveDelete(File file) { + if (file.isDirectory()) { + File[] files = file.listFiles(); + for (int i = 0; i < files.length; i++) { + recursiveDelete(files[i]); + } + } + file.delete(); + } - protected BrokerService createBroker(String resource) throws Exception { - return createBroker(new ClassPathResource(resource)); - } + protected BrokerService createBroker(String resource) throws Exception { + return createBroker(new ClassPathResource(resource)); + } - protected BrokerService createBroker(Resource resource) throws Exception { - BrokerFactoryBean factory = new BrokerFactoryBean(resource); - factory.afterPropertiesSet(); + protected BrokerService createBroker(Resource resource) throws Exception { + BrokerFactoryBean factory = new BrokerFactoryBean(resource); + factory.afterPropertiesSet(); - BrokerService broker = factory.getBroker(); + BrokerService broker = factory.getBroker(); - assertTrue("Should have a broker!", broker != null); + assertTrue("Should have a broker!", broker != null); - // Broker is already started by default when using the XML file - // broker.start(); + // Broker is already started by default when using the XML file + // broker.start(); - return broker; - } + return broker; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/AMQ3410Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/AMQ3410Test.java index dadff34c8e..6be65ce447 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/AMQ3410Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/AMQ3410Test.java @@ -33,154 +33,152 @@ import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class AMQ3410Test extends TestCase { - @SuppressWarnings("unused") - private static final Logger LOG = LoggerFactory - .getLogger(PurgeCommandTest.class); - private static final Collection DEFAULT_OPTIONS = Arrays - .asList(new String[] { "--amqurl", "tcp://localhost:61616", }); - private static final Collection DEFAULT_TOKENS = Arrays - .asList(new String[] { "FOO.QUEUE" }); + @SuppressWarnings("unused") + private static final Logger LOG = LoggerFactory.getLogger(PurgeCommandTest.class); + private static final Collection DEFAULT_OPTIONS = Arrays.asList(new String[]{"--amqurl", "tcp://localhost:61616",}); - protected AbstractApplicationContext context; + private static final Collection DEFAULT_TOKENS = Arrays.asList(new String[]{"FOO.QUEUE"}); - protected void setUp() throws Exception { - super.setUp(); + protected AbstractApplicationContext context; - context = createApplicationContext(); + protected void setUp() throws Exception { + super.setUp(); - } + context = createApplicationContext(); - protected AbstractApplicationContext createApplicationContext() { - return new ClassPathXmlApplicationContext("org/apache/activemq/console/command/activemq.xml"); - } + } - protected void tearDown() throws Exception { - BrokerService broker = (BrokerService) context.getBean("localbroker"); - broker.stop(); - broker = (BrokerService) context.getBean("default"); - broker.stop(); - super.tearDown(); - } + protected AbstractApplicationContext createApplicationContext() { + return new ClassPathXmlApplicationContext("org/apache/activemq/console/command/activemq.xml"); + } - public void testNoFactorySet() throws Exception { - AmqBrowseCommand command = new AmqBrowseCommand(); - CommandContext context = new CommandContext(); + protected void tearDown() throws Exception { + BrokerService broker = (BrokerService) context.getBean("localbroker"); + broker.stop(); + broker = (BrokerService) context.getBean("default"); + broker.stop(); + super.tearDown(); + } - context.setFormatter(new CommandShellOutputFormatter(System.out)); + public void testNoFactorySet() throws Exception { + AmqBrowseCommand command = new AmqBrowseCommand(); + CommandContext context = new CommandContext(); - command.setCommandContext(context); + context.setFormatter(new CommandShellOutputFormatter(System.out)); - List tokens = new ArrayList(); - tokens.addAll(DEFAULT_OPTIONS); - tokens.addAll(DEFAULT_TOKENS); + command.setCommandContext(context); - command.execute(tokens); - assertNotNull(command.getConnectionFactory()); - assertTrue(command.getConnectionFactory() instanceof ActiveMQConnectionFactory); - } + List tokens = new ArrayList(); + tokens.addAll(DEFAULT_OPTIONS); + tokens.addAll(DEFAULT_TOKENS); - public void testFactorySet() throws Exception { - AmqBrowseCommand command = new AmqBrowseCommand(); - CommandContext context = new CommandContext(); + command.execute(tokens); + assertNotNull(command.getConnectionFactory()); + assertTrue(command.getConnectionFactory() instanceof ActiveMQConnectionFactory); + } - context.setFormatter(new CommandShellOutputFormatter(System.out)); + public void testFactorySet() throws Exception { + AmqBrowseCommand command = new AmqBrowseCommand(); + CommandContext context = new CommandContext(); - command.setCommandContext(context); + context.setFormatter(new CommandShellOutputFormatter(System.out)); - List tokens = new ArrayList(); - tokens.addAll(DEFAULT_OPTIONS); - tokens.add("--factory"); - tokens.add(DummyConnectionFactory.class.getCanonicalName()); - tokens.addAll(DEFAULT_TOKENS); + command.setCommandContext(context); - command.execute(tokens); + List tokens = new ArrayList(); + tokens.addAll(DEFAULT_OPTIONS); + tokens.add("--factory"); + tokens.add(DummyConnectionFactory.class.getCanonicalName()); + tokens.addAll(DEFAULT_TOKENS); - assertNotNull(command.getConnectionFactory()); - assertTrue("wrong instance returned: " - + command.getConnectionFactory().getClass().getName(), command - .getConnectionFactory() instanceof DummyConnectionFactory); - } + command.execute(tokens); - public void testFactorySetWrong1() throws Exception { - AmqBrowseCommand command = new AmqBrowseCommand(); - CommandContext context = new CommandContext(); + assertNotNull(command.getConnectionFactory()); + assertTrue("wrong instance returned: " + command.getConnectionFactory().getClass().getName(), command.getConnectionFactory() instanceof DummyConnectionFactory); + } - context.setFormatter(new CommandShellOutputFormatter(System.out)); + public void testFactorySetWrong1() throws Exception { + AmqBrowseCommand command = new AmqBrowseCommand(); + CommandContext context = new CommandContext(); - command.setCommandContext(context); + context.setFormatter(new CommandShellOutputFormatter(System.out)); - List tokens = new ArrayList(); - tokens.addAll(DEFAULT_OPTIONS); - tokens.add("--factory"); - tokens - .add("org.apache.activemq.console.command.TestAMQ3410.DoesntExistFactory"); - tokens.addAll(DEFAULT_TOKENS); + command.setCommandContext(context); - try { - command.execute(tokens); - } catch (Throwable cause) { - while (null != cause) { - if (cause instanceof java.lang.ClassNotFoundException) - return; - cause = cause.getCause(); - } - } - assertFalse("No exception caught", true); - } + List tokens = new ArrayList(); + tokens.addAll(DEFAULT_OPTIONS); + tokens.add("--factory"); + tokens.add("org.apache.activemq.console.command.TestAMQ3410.DoesntExistFactory"); + tokens.addAll(DEFAULT_TOKENS); - public void testFactorySetWrong2() throws Exception { - AmqBrowseCommand command = new AmqBrowseCommand(); - CommandContext context = new CommandContext(); + try { + command.execute(tokens); + } + catch (Throwable cause) { + while (null != cause) { + if (cause instanceof java.lang.ClassNotFoundException) + return; + cause = cause.getCause(); + } + } + assertFalse("No exception caught", true); + } - context.setFormatter(new CommandShellOutputFormatter(System.out)); + public void testFactorySetWrong2() throws Exception { + AmqBrowseCommand command = new AmqBrowseCommand(); + CommandContext context = new CommandContext(); - command.setCommandContext(context); + context.setFormatter(new CommandShellOutputFormatter(System.out)); - List tokens = new ArrayList(); - tokens.addAll(DEFAULT_OPTIONS); - tokens.add("--factory"); - tokens.add(InvalidConnectionFactory.class.getCanonicalName()); - tokens.addAll(DEFAULT_TOKENS); + command.setCommandContext(context); - try { - command.execute(tokens); - } catch (Throwable e) { - Throwable cause = e; - while (null != cause) { - if (cause instanceof java.lang.NoSuchMethodException) - return; - cause = cause.getCause(); - } - assertFalse(e.toString(), true); - } - assertFalse("No exception caught", true); - } + List tokens = new ArrayList(); + tokens.addAll(DEFAULT_OPTIONS); + tokens.add("--factory"); + tokens.add(InvalidConnectionFactory.class.getCanonicalName()); + tokens.addAll(DEFAULT_TOKENS); - public void testFactorySetWrong3() throws Exception { - AmqBrowseCommand command = new AmqBrowseCommand(); - CommandContext context = new CommandContext(); + try { + command.execute(tokens); + } + catch (Throwable e) { + Throwable cause = e; + while (null != cause) { + if (cause instanceof java.lang.NoSuchMethodException) + return; + cause = cause.getCause(); + } + assertFalse(e.toString(), true); + } + assertFalse("No exception caught", true); + } - context.setFormatter(new CommandShellOutputFormatter(System.out)); + public void testFactorySetWrong3() throws Exception { + AmqBrowseCommand command = new AmqBrowseCommand(); + CommandContext context = new CommandContext(); - command.setCommandContext(context); + context.setFormatter(new CommandShellOutputFormatter(System.out)); - List tokens = new ArrayList(); - tokens.addAll(DEFAULT_OPTIONS); - tokens.add("--factory"); - tokens.add("java.lang.Object"); - tokens.addAll(DEFAULT_TOKENS); + command.setCommandContext(context); - try { - command.execute(tokens); - } catch (Throwable cause) { - while (null != cause) { - if (cause instanceof java.lang.NoSuchMethodException) - return; - cause = cause.getCause(); - } - } - assertFalse(true); - } + List tokens = new ArrayList(); + tokens.addAll(DEFAULT_OPTIONS); + tokens.add("--factory"); + tokens.add("java.lang.Object"); + tokens.addAll(DEFAULT_TOKENS); + + try { + command.execute(tokens); + } + catch (Throwable cause) { + while (null != cause) { + if (cause instanceof java.lang.NoSuchMethodException) + return; + cause = cause.getCause(); + } + } + assertFalse(true); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/AMQ3411Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/AMQ3411Test.java index 8930b2c156..9db2af09f6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/AMQ3411Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/AMQ3411Test.java @@ -32,166 +32,165 @@ import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class AMQ3411Test extends TestCase { - @SuppressWarnings("unused") - private static final Logger LOG = LoggerFactory - .getLogger(AMQ3411Test.class); - private static final Collection DEFAULT_OPTIONS = Arrays - .asList(new String[] { "--amqurl", "tcp://localhost:61616", }); - private static final Collection DEFAULT_TOKENS = Arrays - .asList(new String[] { "FOO.QUEUE" }); - protected AbstractApplicationContext context; - protected static final String origPassword = "ABCDEFG"; + @SuppressWarnings("unused") + private static final Logger LOG = LoggerFactory.getLogger(AMQ3411Test.class); + private static final Collection DEFAULT_OPTIONS = Arrays.asList(new String[]{"--amqurl", "tcp://localhost:61616",}); - protected void setUp() throws Exception { - super.setUp(); + private static final Collection DEFAULT_TOKENS = Arrays.asList(new String[]{"FOO.QUEUE"}); + protected AbstractApplicationContext context; + protected static final String origPassword = "ABCDEFG"; - context = createApplicationContext(); + protected void setUp() throws Exception { + super.setUp(); - } + context = createApplicationContext(); - protected AbstractApplicationContext createApplicationContext() { - return new ClassPathXmlApplicationContext("org/apache/activemq/console/command/activemq.xml"); - } + } - protected void tearDown() throws Exception { - BrokerService broker = (BrokerService) context.getBean("localbroker"); - broker.stop(); - broker = (BrokerService) context.getBean("default"); - broker.stop(); - super.tearDown(); - } + protected AbstractApplicationContext createApplicationContext() { + return new ClassPathXmlApplicationContext("org/apache/activemq/console/command/activemq.xml"); + } - public void testNoFactorySet() throws Exception { - AmqBrowseCommand command = new AmqBrowseCommand(); - CommandContext context = new CommandContext(); + protected void tearDown() throws Exception { + BrokerService broker = (BrokerService) context.getBean("localbroker"); + broker.stop(); + broker = (BrokerService) context.getBean("default"); + broker.stop(); + super.tearDown(); + } - context.setFormatter(new CommandShellOutputFormatter(System.out)); + public void testNoFactorySet() throws Exception { + AmqBrowseCommand command = new AmqBrowseCommand(); + CommandContext context = new CommandContext(); - command.setCommandContext(context); + context.setFormatter(new CommandShellOutputFormatter(System.out)); - List tokens = new ArrayList(); - tokens.addAll(DEFAULT_OPTIONS); - tokens.addAll(DEFAULT_TOKENS); + command.setCommandContext(context); - command.execute(tokens); + List tokens = new ArrayList(); + tokens.addAll(DEFAULT_OPTIONS); + tokens.addAll(DEFAULT_TOKENS); - assertNotNull(command.getPasswordFactory()); - assertTrue(command.getPasswordFactory() instanceof DefaultPasswordFactory); - assertNull(command.getPassword()); - } + command.execute(tokens); - public void testUsernamePasswordSet() throws Exception { - AmqBrowseCommand command = new AmqBrowseCommand(); - CommandContext context = new CommandContext(); + assertNotNull(command.getPasswordFactory()); + assertTrue(command.getPasswordFactory() instanceof DefaultPasswordFactory); + assertNull(command.getPassword()); + } - String username = "user"; - String password = "password"; + public void testUsernamePasswordSet() throws Exception { + AmqBrowseCommand command = new AmqBrowseCommand(); + CommandContext context = new CommandContext(); - context.setFormatter(new CommandShellOutputFormatter(System.out)); + String username = "user"; + String password = "password"; - command.setCommandContext(context); + context.setFormatter(new CommandShellOutputFormatter(System.out)); - List tokens = new ArrayList(); - tokens.addAll(DEFAULT_OPTIONS); - tokens.add("--password"); - tokens.add(password); + command.setCommandContext(context); - tokens.add("--user"); - tokens.add(username); - tokens.addAll(DEFAULT_TOKENS); + List tokens = new ArrayList(); + tokens.addAll(DEFAULT_OPTIONS); + tokens.add("--password"); + tokens.add(password); - command.execute(tokens); + tokens.add("--user"); + tokens.add(username); + tokens.addAll(DEFAULT_TOKENS); - assertNotNull(command.getPasswordFactory()); - assertTrue(command.getPasswordFactory() instanceof DefaultPasswordFactory); - assertEquals(password, command.getPassword()); - assertEquals(username, command.getUsername()); - } + command.execute(tokens); - public void testFactorySet() throws Exception { - AmqBrowseCommand command = new AmqBrowseCommand(); - CommandContext context = new CommandContext(); + assertNotNull(command.getPasswordFactory()); + assertTrue(command.getPasswordFactory() instanceof DefaultPasswordFactory); + assertEquals(password, command.getPassword()); + assertEquals(username, command.getUsername()); + } - context.setFormatter(new CommandShellOutputFormatter(System.out)); + public void testFactorySet() throws Exception { + AmqBrowseCommand command = new AmqBrowseCommand(); + CommandContext context = new CommandContext(); - command.setCommandContext(context); + context.setFormatter(new CommandShellOutputFormatter(System.out)); - List tokens = new ArrayList(); - tokens.addAll(DEFAULT_OPTIONS); - tokens.add("--passwordFactory"); - tokens.add(LowercasingPasswordFactory.class.getCanonicalName()); - tokens.add("--password"); - tokens.add(origPassword); - tokens.addAll(DEFAULT_TOKENS); + command.setCommandContext(context); - command.execute(tokens); - assertNotNull(command.getPasswordFactory()); - assertTrue(command.getPasswordFactory() instanceof LowercasingPasswordFactory); + List tokens = new ArrayList(); + tokens.addAll(DEFAULT_OPTIONS); + tokens.add("--passwordFactory"); + tokens.add(LowercasingPasswordFactory.class.getCanonicalName()); + tokens.add("--password"); + tokens.add(origPassword); + tokens.addAll(DEFAULT_TOKENS); - // validate that the factory is indeed being used for the password. - assertEquals(origPassword.toLowerCase(), command.getPassword()); - } + command.execute(tokens); + assertNotNull(command.getPasswordFactory()); + assertTrue(command.getPasswordFactory() instanceof LowercasingPasswordFactory); - public void testFactorySetWrong1() throws Exception { - AmqBrowseCommand command = new AmqBrowseCommand(); - CommandContext context = new CommandContext(); + // validate that the factory is indeed being used for the password. + assertEquals(origPassword.toLowerCase(), command.getPassword()); + } - context.setFormatter(new CommandShellOutputFormatter(System.out)); + public void testFactorySetWrong1() throws Exception { + AmqBrowseCommand command = new AmqBrowseCommand(); + CommandContext context = new CommandContext(); - command.setCommandContext(context); + context.setFormatter(new CommandShellOutputFormatter(System.out)); - List tokens = new ArrayList(); - tokens.addAll(DEFAULT_OPTIONS); - tokens.add("--passwordFactory"); - tokens - .add("org.apache.activemq.console.command.TestAMQ3411.DoesntExistFactory"); - tokens.add("--password"); - tokens.add(origPassword); + command.setCommandContext(context); - tokens.addAll(DEFAULT_TOKENS); + List tokens = new ArrayList(); + tokens.addAll(DEFAULT_OPTIONS); + tokens.add("--passwordFactory"); + tokens.add("org.apache.activemq.console.command.TestAMQ3411.DoesntExistFactory"); + tokens.add("--password"); + tokens.add(origPassword); - try { - command.execute(tokens); - } catch (Throwable e) { - Throwable cause = e; - while (null != cause) { - if (cause instanceof java.lang.ClassNotFoundException) - return; - cause = cause.getCause(); - } - assertFalse(e.toString(), true); - } - assertFalse("No exception caught", true); - } + tokens.addAll(DEFAULT_TOKENS); - public void testFactorySetWrong2() throws Exception { - AmqBrowseCommand command = new AmqBrowseCommand(); - CommandContext context = new CommandContext(); + try { + command.execute(tokens); + } + catch (Throwable e) { + Throwable cause = e; + while (null != cause) { + if (cause instanceof java.lang.ClassNotFoundException) + return; + cause = cause.getCause(); + } + assertFalse(e.toString(), true); + } + assertFalse("No exception caught", true); + } - context.setFormatter(new CommandShellOutputFormatter(System.out)); + public void testFactorySetWrong2() throws Exception { + AmqBrowseCommand command = new AmqBrowseCommand(); + CommandContext context = new CommandContext(); - command.setCommandContext(context); + context.setFormatter(new CommandShellOutputFormatter(System.out)); - List tokens = new ArrayList(); - tokens.addAll(DEFAULT_OPTIONS); - tokens.add("--passwordFactory"); - tokens.add("java.lang.Object"); - tokens.add("--password"); - tokens.add(origPassword); - tokens.addAll(DEFAULT_TOKENS); + command.setCommandContext(context); - try { - command.execute(tokens); - } catch (Throwable e) { - Throwable cause = e; - while (null != cause) { - if (cause instanceof java.lang.ClassCastException) - return; - cause = cause.getCause(); - } - assertFalse(e.toString(), true); - } - assertFalse("No exception caught", true); - } + List tokens = new ArrayList(); + tokens.addAll(DEFAULT_OPTIONS); + tokens.add("--passwordFactory"); + tokens.add("java.lang.Object"); + tokens.add("--password"); + tokens.add(origPassword); + tokens.addAll(DEFAULT_TOKENS); + + try { + command.execute(tokens); + } + catch (Throwable e) { + Throwable cause = e; + while (null != cause) { + if (cause instanceof java.lang.ClassCastException) + return; + cause = cause.getCause(); + } + assertFalse(e.toString(), true); + } + assertFalse("No exception caught", true); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/DummyConnectionFactory.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/DummyConnectionFactory.java index 03f9fc5cc5..7af0facc2e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/DummyConnectionFactory.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/DummyConnectionFactory.java @@ -21,24 +21,25 @@ import org.apache.activemq.ActiveMQConnectionFactory; import java.net.URI; public class DummyConnectionFactory extends ActiveMQConnectionFactory { - public DummyConnectionFactory() { - super(); - } - public DummyConnectionFactory(String userName, String password, String brokerURL) { - super(userName, password, brokerURL); - } + public DummyConnectionFactory() { + super(); + } - public DummyConnectionFactory(String userName, String password, URI brokerURL) { - super(userName, password, brokerURL); - } + public DummyConnectionFactory(String userName, String password, String brokerURL) { + super(userName, password, brokerURL); + } - public DummyConnectionFactory(String brokerURL) { - super(brokerURL); - } + public DummyConnectionFactory(String userName, String password, URI brokerURL) { + super(userName, password, brokerURL); + } - public DummyConnectionFactory(URI brokerURL) { - super(brokerURL); - } + public DummyConnectionFactory(String brokerURL) { + super(brokerURL); + } + + public DummyConnectionFactory(URI brokerURL) { + super(brokerURL); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/LowercasingPasswordFactory.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/LowercasingPasswordFactory.java index a0f9b05ec7..f8e47957d9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/LowercasingPasswordFactory.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/LowercasingPasswordFactory.java @@ -17,9 +17,10 @@ package org.apache.activemq.console.command; public class LowercasingPasswordFactory implements PasswordFactory { - @Override - public String getPassword(String password) { - return password.toLowerCase(); - } + + @Override + public String getPassword(String password) { + return password.toLowerCase(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/PurgeCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/PurgeCommandTest.java index 57fffa0dfb..374fa01ba8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/PurgeCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/PurgeCommandTest.java @@ -52,389 +52,364 @@ import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class PurgeCommandTest extends TestCase { - private static final Logger LOG = LoggerFactory - .getLogger(PurgeCommandTest.class); - protected static final int MESSAGE_COUNT = 10; - protected static final String PROPERTY_NAME = "XTestProperty"; - protected static final String PROPERTY_VALUE = "1:1"; + private static final Logger LOG = LoggerFactory.getLogger(PurgeCommandTest.class); - // check for existence of property - protected static final String MSG_SEL_WITH_PROPERTY = PROPERTY_NAME - + " is not null"; + protected static final int MESSAGE_COUNT = 10; + protected static final String PROPERTY_NAME = "XTestProperty"; + protected static final String PROPERTY_VALUE = "1:1"; - // check for non-existence of property - protected static final String MSG_SEL_WITHOUT_PROPERTY = PROPERTY_NAME - + " is null"; + // check for existence of property + protected static final String MSG_SEL_WITH_PROPERTY = PROPERTY_NAME + " is not null"; - // complex message selector query using XTestProperty and JMSPriority - protected static final String MSG_SEL_COMPLEX = PROPERTY_NAME + "='" + - "1:1" + "',JMSPriority>3"; + // check for non-existence of property + protected static final String MSG_SEL_WITHOUT_PROPERTY = PROPERTY_NAME + " is null"; - // complex message selector query using XTestProperty AND JMSPriority - // but in SQL-92 syntax - protected static final String MSG_SEL_COMPLEX_SQL_AND = "(" + PROPERTY_NAME + "='" + - "1:1" + "') AND (JMSPriority>3)"; + // complex message selector query using XTestProperty and JMSPriority + protected static final String MSG_SEL_COMPLEX = PROPERTY_NAME + "='" + + "1:1" + "',JMSPriority>3"; - // complex message selector query using XTestProperty OR JMSPriority - // but in SQL-92 syntax - protected static final String MSG_SEL_COMPLEX_SQL_OR = "(" + PROPERTY_NAME + "='" + - "1:1" + "') OR (JMSPriority>3)"; + // complex message selector query using XTestProperty AND JMSPriority + // but in SQL-92 syntax + protected static final String MSG_SEL_COMPLEX_SQL_AND = "(" + PROPERTY_NAME + "='" + + "1:1" + "') AND (JMSPriority>3)"; + // complex message selector query using XTestProperty OR JMSPriority + // but in SQL-92 syntax + protected static final String MSG_SEL_COMPLEX_SQL_OR = "(" + PROPERTY_NAME + "='" + + "1:1" + "') OR (JMSPriority>3)"; - protected static final String QUEUE_NAME = "org.apache.activemq.network.jms.QueueBridgeTest"; + protected static final String QUEUE_NAME = "org.apache.activemq.network.jms.QueueBridgeTest"; - protected AbstractApplicationContext context; - protected QueueConnection localConnection; - protected QueueRequestor requestor; - protected QueueSession requestServerSession; - protected MessageConsumer requestServerConsumer; - protected MessageProducer requestServerProducer; - protected Queue theQueue; + protected AbstractApplicationContext context; + protected QueueConnection localConnection; + protected QueueRequestor requestor; + protected QueueSession requestServerSession; + protected MessageConsumer requestServerConsumer; + protected MessageProducer requestServerProducer; + protected Queue theQueue; - @Override - protected void setUp() throws Exception { - super.setUp(); + @Override + protected void setUp() throws Exception { + super.setUp(); - context = createApplicationContext(); + context = createApplicationContext(); - createConnections(); + createConnections(); - requestServerSession = localConnection.createQueueSession(false, - Session.AUTO_ACKNOWLEDGE); - theQueue = requestServerSession.createQueue(QUEUE_NAME); - requestServerConsumer = requestServerSession.createConsumer(theQueue); - requestServerProducer = requestServerSession.createProducer(null); + requestServerSession = localConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); + theQueue = requestServerSession.createQueue(QUEUE_NAME); + requestServerConsumer = requestServerSession.createConsumer(theQueue); + requestServerProducer = requestServerSession.createProducer(null); - QueueSession session = localConnection.createQueueSession(false, - Session.AUTO_ACKNOWLEDGE); - requestor = new QueueRequestor(session, theQueue); - } + QueueSession session = localConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); + requestor = new QueueRequestor(session, theQueue); + } - protected void createConnections() throws JMSException { - ActiveMQConnectionFactory fac = (ActiveMQConnectionFactory) context - .getBean("localFactory"); - localConnection = fac.createQueueConnection(); - localConnection.start(); - } + protected void createConnections() throws JMSException { + ActiveMQConnectionFactory fac = (ActiveMQConnectionFactory) context.getBean("localFactory"); + localConnection = fac.createQueueConnection(); + localConnection.start(); + } - protected AbstractApplicationContext createApplicationContext() { - return new ClassPathXmlApplicationContext("org/apache/activemq/console/command/activemq.xml"); - } + protected AbstractApplicationContext createApplicationContext() { + return new ClassPathXmlApplicationContext("org/apache/activemq/console/command/activemq.xml"); + } - @Override - protected void tearDown() throws Exception { - localConnection.close(); - BrokerService broker = (BrokerService) context.getBean("localbroker"); - broker.stop(); - broker = (BrokerService) context.getBean("default"); - broker.stop(); - super.tearDown(); - } + @Override + protected void tearDown() throws Exception { + localConnection.close(); + BrokerService broker = (BrokerService) context.getBean("localbroker"); + broker.stop(); + broker = (BrokerService) context.getBean("default"); + broker.stop(); + super.tearDown(); + } - public int getMessageCount(QueueBrowser browser, String prefix) throws JMSException { - Enumeration e = browser.getEnumeration(); - int with = 0; - while (e.hasMoreElements()) { - Object o = e.nextElement(); - System.out.println(prefix + o); - with++; - } - return with; - } + public int getMessageCount(QueueBrowser browser, String prefix) throws JMSException { + Enumeration e = browser.getEnumeration(); + int with = 0; + while (e.hasMoreElements()) { + Object o = e.nextElement(); + System.out.println(prefix + o); + with++; + } + return with; + } - public void cleanup() throws JMSException { - for (int i = 0; i < MESSAGE_COUNT * 2; i++) { - requestServerConsumer.receive(); - } - } + public void cleanup() throws JMSException { + for (int i = 0; i < MESSAGE_COUNT * 2; i++) { + requestServerConsumer.receive(); + } + } - protected MBeanServerConnection createJmxConnection() throws IOException { - return ManagementFactory.getPlatformMBeanServer(); - } + protected MBeanServerConnection createJmxConnection() throws IOException { + return ManagementFactory.getPlatformMBeanServer(); + } - @SuppressWarnings("unchecked") - public void purgeAllMessages() throws IOException, Exception { - List queueList = JmxMBeansUtil.queryMBeans( - createJmxConnection(), "type=Broker,brokerName=localbroker,destinationType=Queue,destinationName=*"); - for (ObjectInstance oi : queueList) { - ObjectName queueName = oi.getObjectName(); - LOG.info("Purging all messages in queue: " - + queueName.getKeyProperty("Destination")); - createJmxConnection().invoke(queueName, "purge", - new Object[] {}, new String[] {}); + @SuppressWarnings("unchecked") + public void purgeAllMessages() throws IOException, Exception { + List queueList = JmxMBeansUtil.queryMBeans(createJmxConnection(), "type=Broker,brokerName=localbroker,destinationType=Queue,destinationName=*"); + for (ObjectInstance oi : queueList) { + ObjectName queueName = oi.getObjectName(); + LOG.info("Purging all messages in queue: " + queueName.getKeyProperty("Destination")); + createJmxConnection().invoke(queueName, "purge", new Object[]{}, new String[]{}); + } + } + + public void addMessages() throws IOException, Exception { + // first clean out any messages that may exist. + purgeAllMessages(); + + for (int i = 0; i < MESSAGE_COUNT; i++) { + TextMessage msg = requestServerSession.createTextMessage("test msg: " + i); + msg.setStringProperty(PROPERTY_NAME, PROPERTY_VALUE); + requestServerProducer.send(theQueue, msg); + } + for (int i = 0; i < MESSAGE_COUNT; i++) { + TextMessage msg = requestServerSession.createTextMessage("test msg: " + i); + requestServerProducer.send(theQueue, msg); + } + + } + + public void validateCounts(int expectedWithCount, + int expectedWithoutCount, + int expectedAllCount) throws JMSException { + QueueBrowser withPropertyBrowser = requestServerSession.createBrowser(theQueue, MSG_SEL_WITH_PROPERTY); + QueueBrowser withoutPropertyBrowser = requestServerSession.createBrowser(theQueue, MSG_SEL_WITHOUT_PROPERTY); + QueueBrowser allBrowser = requestServerSession.createBrowser(theQueue); + + int withCount = getMessageCount(withPropertyBrowser, "withProperty "); + int withoutCount = getMessageCount(withoutPropertyBrowser, "withoutProperty "); + int allCount = getMessageCount(allBrowser, "allMessages "); + + withPropertyBrowser.close(); + withoutPropertyBrowser.close(); + allBrowser.close(); + + assertEquals("Expected withCount to be " + expectedWithCount + " was " + withCount, expectedWithCount, withCount); + assertEquals("Expected withoutCount to be " + expectedWithoutCount + " was " + withoutCount, expectedWithoutCount, withoutCount); + assertEquals("Expected allCount to be " + expectedAllCount + " was " + allCount, expectedAllCount, allCount); + LOG.info("withCount = " + withCount + "\n withoutCount = " + withoutCount + "\n allCount = " + allCount + "\n = " + "\n"); + } + + /** + * This test ensures that the queueViewMbean will work. + * + * @throws Exception + */ + @SuppressWarnings("unchecked") + public void testQueueViewMbean() throws Exception { + + try { + addMessages(); + + validateCounts(MESSAGE_COUNT, MESSAGE_COUNT, MESSAGE_COUNT * 2); + + List tokens = Arrays.asList(new String[]{"*"}); + for (String token : tokens) { + List queueList = JmxMBeansUtil.queryMBeans(createJmxConnection(), "type=Broker,brokerName=localbroker,destinationType=Queue,destinationName=" + token); + + for (ObjectInstance queue : queueList) { + ObjectName queueName = queue.getObjectName(); + QueueViewMBean proxy = MBeanServerInvocationHandler.newProxyInstance(createJmxConnection(), queueName, QueueViewMBean.class, true); + int removed = proxy.removeMatchingMessages(MSG_SEL_WITH_PROPERTY); + LOG.info("Removed: " + removed); } - } + } - public void addMessages() throws IOException, Exception { - // first clean out any messages that may exist. - purgeAllMessages(); + validateCounts(0, MESSAGE_COUNT, MESSAGE_COUNT); - for (int i = 0; i < MESSAGE_COUNT; i++) { - TextMessage msg = requestServerSession - .createTextMessage("test msg: " + i); - msg.setStringProperty(PROPERTY_NAME, PROPERTY_VALUE); - requestServerProducer.send(theQueue, msg); - } - for (int i = 0; i < MESSAGE_COUNT; i++) { - TextMessage msg = requestServerSession - .createTextMessage("test msg: " + i); - requestServerProducer.send(theQueue, msg); - } + } + finally { + purgeAllMessages(); + } + } - } + public void testPurgeCommandSimpleSelector() throws Exception { + try { + PurgeCommand purgeCommand = new PurgeCommand(); + CommandContext context = new CommandContext(); - public void validateCounts(int expectedWithCount, int expectedWithoutCount, - int expectedAllCount) throws JMSException { - QueueBrowser withPropertyBrowser = requestServerSession.createBrowser( - theQueue, MSG_SEL_WITH_PROPERTY); - QueueBrowser withoutPropertyBrowser = requestServerSession - .createBrowser(theQueue, MSG_SEL_WITHOUT_PROPERTY); - QueueBrowser allBrowser = requestServerSession.createBrowser(theQueue); + context.setFormatter(new CommandShellOutputFormatter(System.out)); - int withCount = getMessageCount(withPropertyBrowser, "withProperty "); - int withoutCount = getMessageCount(withoutPropertyBrowser, - "withoutProperty "); - int allCount = getMessageCount(allBrowser, "allMessages "); + purgeCommand.setCommandContext(context); + purgeCommand.setJmxUseLocal(true); - withPropertyBrowser.close(); - withoutPropertyBrowser.close(); - allBrowser.close(); + List tokens = new ArrayList(); + tokens.add("--msgsel"); + tokens.add(MSG_SEL_WITH_PROPERTY); - assertEquals("Expected withCount to be " + expectedWithCount + " was " - + withCount, expectedWithCount, withCount); - assertEquals("Expected withoutCount to be " + expectedWithoutCount - + " was " + withoutCount, expectedWithoutCount, withoutCount); - assertEquals("Expected allCount to be " + expectedAllCount + " was " - + allCount, expectedAllCount, allCount); - LOG.info("withCount = " + withCount + "\n withoutCount = " - + withoutCount + "\n allCount = " + allCount + "\n = " + "\n"); - } + addMessages(); + validateCounts(MESSAGE_COUNT, MESSAGE_COUNT, MESSAGE_COUNT * 2); - /** - * This test ensures that the queueViewMbean will work. - * - * @throws Exception - */ - @SuppressWarnings("unchecked") - public void testQueueViewMbean() throws Exception { + purgeCommand.execute(tokens); - try { - addMessages(); + validateCounts(0, MESSAGE_COUNT, MESSAGE_COUNT); + } + finally { + purgeAllMessages(); + } + } - validateCounts(MESSAGE_COUNT, MESSAGE_COUNT, MESSAGE_COUNT * 2); + public void testPurgeCommandComplexSelector() throws Exception { + try { + PurgeCommand purgeCommand = new PurgeCommand(); + CommandContext context = new CommandContext(); - List tokens = Arrays.asList(new String[] { "*" }); - for (String token : tokens) { - List queueList = JmxMBeansUtil.queryMBeans( - createJmxConnection(), "type=Broker,brokerName=localbroker,destinationType=Queue,destinationName=" - + token); + context.setFormatter(new CommandShellOutputFormatter(System.out)); - for (ObjectInstance queue : queueList) { - ObjectName queueName = queue - .getObjectName(); - QueueViewMBean proxy = MBeanServerInvocationHandler - .newProxyInstance(createJmxConnection(), queueName, - QueueViewMBean.class, true); - int removed = proxy - .removeMatchingMessages(MSG_SEL_WITH_PROPERTY); - LOG.info("Removed: " + removed); - } - } + purgeCommand.setCommandContext(context); + purgeCommand.setJmxUseLocal(true); - validateCounts(0, MESSAGE_COUNT, MESSAGE_COUNT); + List tokens = new ArrayList(); + tokens.add("--msgsel"); + tokens.add(MSG_SEL_COMPLEX); - } finally { - purgeAllMessages(); - } - } + addMessages(); + validateCounts(MESSAGE_COUNT, MESSAGE_COUNT, MESSAGE_COUNT * 2); - public void testPurgeCommandSimpleSelector() throws Exception { - try { - PurgeCommand purgeCommand = new PurgeCommand(); - CommandContext context = new CommandContext(); + purgeCommand.execute(tokens); - context.setFormatter(new CommandShellOutputFormatter(System.out)); + QueueBrowser withPropertyBrowser = requestServerSession.createBrowser(theQueue, MSG_SEL_COMPLEX); + QueueBrowser allBrowser = requestServerSession.createBrowser(theQueue); - purgeCommand.setCommandContext(context); - purgeCommand.setJmxUseLocal(true); + int withCount = getMessageCount(withPropertyBrowser, "withProperty "); + int allCount = getMessageCount(allBrowser, "allMessages "); - List tokens = new ArrayList(); - tokens.add("--msgsel"); - tokens.add(MSG_SEL_WITH_PROPERTY); + withPropertyBrowser.close(); + allBrowser.close(); - addMessages(); - validateCounts(MESSAGE_COUNT, MESSAGE_COUNT, MESSAGE_COUNT * 2); + assertEquals("Expected withCount to be " + "0" + " was " + withCount, 0, withCount); + assertEquals("Expected allCount to be " + MESSAGE_COUNT + " was " + allCount, MESSAGE_COUNT, allCount); + LOG.info("withCount = " + withCount + "\n allCount = " + + allCount + "\n = " + "\n"); + } + finally { + purgeAllMessages(); + } + } - purgeCommand.execute(tokens); + public void testPurgeCommandComplexSQLSelector_AND() throws Exception { + try { - validateCounts(0, MESSAGE_COUNT, MESSAGE_COUNT); - } finally { - purgeAllMessages(); - } - } - - public void testPurgeCommandComplexSelector() throws Exception { - try { - PurgeCommand purgeCommand = new PurgeCommand(); - CommandContext context = new CommandContext(); - - context.setFormatter(new CommandShellOutputFormatter(System.out)); - - purgeCommand.setCommandContext(context); - purgeCommand.setJmxUseLocal(true); - - List tokens = new ArrayList(); - tokens.add("--msgsel"); - tokens.add(MSG_SEL_COMPLEX); - - addMessages(); - validateCounts(MESSAGE_COUNT, MESSAGE_COUNT, MESSAGE_COUNT * 2); - - purgeCommand.execute(tokens); - - QueueBrowser withPropertyBrowser = requestServerSession.createBrowser( - theQueue, MSG_SEL_COMPLEX); - QueueBrowser allBrowser = requestServerSession.createBrowser(theQueue); - - int withCount = getMessageCount(withPropertyBrowser, "withProperty "); - int allCount = getMessageCount(allBrowser, "allMessages "); - - withPropertyBrowser.close(); - allBrowser.close(); - - assertEquals("Expected withCount to be " + "0" + " was " - + withCount, 0, withCount); - assertEquals("Expected allCount to be " + MESSAGE_COUNT + " was " - + allCount, MESSAGE_COUNT, allCount); - LOG.info("withCount = " + withCount + "\n allCount = " + - allCount + "\n = " + "\n"); - } finally { - purgeAllMessages(); - } - } - - public void testPurgeCommandComplexSQLSelector_AND() throws Exception { - try { - - String one = "ID:mac.fritz.box:1213242.3231.1:1:1:100"; - String two = "\\*:100"; - try { + String one = "ID:mac.fritz.box:1213242.3231.1:1:1:100"; + String two = "\\*:100"; + try { if (one.matches(two)) - LOG.info("String matches."); + LOG.info("String matches."); else - LOG.info("string does not match."); - } catch (Exception ex) { - LOG.error(ex.getMessage()); - } + LOG.info("string does not match."); + } + catch (Exception ex) { + LOG.error(ex.getMessage()); + } - PurgeCommand purgeCommand = new PurgeCommand(); - CommandContext context = new CommandContext(); + PurgeCommand purgeCommand = new PurgeCommand(); + CommandContext context = new CommandContext(); - context.setFormatter(new CommandShellOutputFormatter(System.out)); + context.setFormatter(new CommandShellOutputFormatter(System.out)); - purgeCommand.setCommandContext(context); - purgeCommand.setJmxUseLocal(true); + purgeCommand.setCommandContext(context); + purgeCommand.setJmxUseLocal(true); - List tokens = new ArrayList(); - tokens.add("--msgsel"); - tokens.add(MSG_SEL_COMPLEX_SQL_AND); + List tokens = new ArrayList(); + tokens.add("--msgsel"); + tokens.add(MSG_SEL_COMPLEX_SQL_AND); - addMessages(); - validateCounts(MESSAGE_COUNT, MESSAGE_COUNT, MESSAGE_COUNT * 2); + addMessages(); + validateCounts(MESSAGE_COUNT, MESSAGE_COUNT, MESSAGE_COUNT * 2); - purgeCommand.execute(tokens); + purgeCommand.execute(tokens); - QueueBrowser withPropertyBrowser = requestServerSession.createBrowser( - theQueue, MSG_SEL_COMPLEX_SQL_AND); - QueueBrowser allBrowser = requestServerSession.createBrowser(theQueue); + QueueBrowser withPropertyBrowser = requestServerSession.createBrowser(theQueue, MSG_SEL_COMPLEX_SQL_AND); + QueueBrowser allBrowser = requestServerSession.createBrowser(theQueue); - int withCount = getMessageCount(withPropertyBrowser, "withProperty "); - int allCount = getMessageCount(allBrowser, "allMessages "); + int withCount = getMessageCount(withPropertyBrowser, "withProperty "); + int allCount = getMessageCount(allBrowser, "allMessages "); - withPropertyBrowser.close(); - allBrowser.close(); + withPropertyBrowser.close(); + allBrowser.close(); - assertEquals("Expected withCount to be " + "0" + " was " - + withCount, 0, withCount); - assertEquals("Expected allCount to be " + MESSAGE_COUNT + " was " - + allCount, MESSAGE_COUNT, allCount); - LOG.info("withCount = " + withCount + "\n allCount = " + - allCount + "\n = " + "\n"); - } finally { - purgeAllMessages(); - } - } + assertEquals("Expected withCount to be " + "0" + " was " + withCount, 0, withCount); + assertEquals("Expected allCount to be " + MESSAGE_COUNT + " was " + allCount, MESSAGE_COUNT, allCount); + LOG.info("withCount = " + withCount + "\n allCount = " + + allCount + "\n = " + "\n"); + } + finally { + purgeAllMessages(); + } + } - public void testPurgeCommandComplexSQLSelector_OR() throws Exception { - try { - PurgeCommand purgeCommand = new PurgeCommand(); - CommandContext context = new CommandContext(); + public void testPurgeCommandComplexSQLSelector_OR() throws Exception { + try { + PurgeCommand purgeCommand = new PurgeCommand(); + CommandContext context = new CommandContext(); - context.setFormatter(new CommandShellOutputFormatter(System.out)); + context.setFormatter(new CommandShellOutputFormatter(System.out)); - purgeCommand.setCommandContext(context); - purgeCommand.setJmxUseLocal(true); + purgeCommand.setCommandContext(context); + purgeCommand.setJmxUseLocal(true); - List tokens = new ArrayList(); - tokens.add("--msgsel"); - tokens.add(MSG_SEL_COMPLEX_SQL_OR); + List tokens = new ArrayList(); + tokens.add("--msgsel"); + tokens.add(MSG_SEL_COMPLEX_SQL_OR); - addMessages(); - validateCounts(MESSAGE_COUNT, MESSAGE_COUNT, MESSAGE_COUNT * 2); + addMessages(); + validateCounts(MESSAGE_COUNT, MESSAGE_COUNT, MESSAGE_COUNT * 2); - purgeCommand.execute(tokens); + purgeCommand.execute(tokens); - QueueBrowser withPropertyBrowser = requestServerSession.createBrowser( - theQueue, MSG_SEL_COMPLEX_SQL_OR); - QueueBrowser allBrowser = requestServerSession.createBrowser(theQueue); + QueueBrowser withPropertyBrowser = requestServerSession.createBrowser(theQueue, MSG_SEL_COMPLEX_SQL_OR); + QueueBrowser allBrowser = requestServerSession.createBrowser(theQueue); - int withCount = getMessageCount(withPropertyBrowser, "withProperty "); - int allCount = getMessageCount(allBrowser, "allMessages "); + int withCount = getMessageCount(withPropertyBrowser, "withProperty "); + int allCount = getMessageCount(allBrowser, "allMessages "); - withPropertyBrowser.close(); - allBrowser.close(); + withPropertyBrowser.close(); + allBrowser.close(); - assertEquals("Expected withCount to be 0 but was " - + withCount, 0, withCount); - assertEquals("Expected allCount to be 0 but was " - + allCount, 0, allCount); - LOG.info("withCount = " + withCount + "\n allCount = " + - allCount + "\n = " + "\n"); - } finally { - purgeAllMessages(); - } - } + assertEquals("Expected withCount to be 0 but was " + withCount, 0, withCount); + assertEquals("Expected allCount to be 0 but was " + allCount, 0, allCount); + LOG.info("withCount = " + withCount + "\n allCount = " + + allCount + "\n = " + "\n"); + } + finally { + purgeAllMessages(); + } + } - public void testDummy() throws Exception { - try { + public void testDummy() throws Exception { + try { - String one = "ID:mac.fritz.box:1213242.3231.1:1:1:100"; - String two = "ID*:100"; - try { + String one = "ID:mac.fritz.box:1213242.3231.1:1:1:100"; + String two = "ID*:100"; + try { if (one.matches(two)) - LOG.info("String matches."); + LOG.info("String matches."); else - LOG.info("string does not match."); - } catch (Exception ex) { - LOG.error(ex.getMessage()); - } + LOG.info("string does not match."); + } + catch (Exception ex) { + LOG.error(ex.getMessage()); + } - PurgeCommand purgeCommand = new PurgeCommand(); - CommandContext context = new CommandContext(); + PurgeCommand purgeCommand = new PurgeCommand(); + CommandContext context = new CommandContext(); - context.setFormatter(new CommandShellOutputFormatter(System.out)); + context.setFormatter(new CommandShellOutputFormatter(System.out)); - purgeCommand.setCommandContext(context); - purgeCommand.setJmxUseLocal(true); + purgeCommand.setCommandContext(context); + purgeCommand.setJmxUseLocal(true); - List tokens = new ArrayList(); - tokens.add("--msgsel"); - tokens.add("(XTestProperty LIKE '1:*') AND (JMSPriority>3)"); + List tokens = new ArrayList(); + tokens.add("--msgsel"); + tokens.add("(XTestProperty LIKE '1:*') AND (JMSPriority>3)"); - addMessages(); + addMessages(); - purgeCommand.execute(tokens); + purgeCommand.execute(tokens); /* QueueBrowser withPropertyBrowser = requestServerSession.createBrowser( @@ -454,11 +429,10 @@ public class PurgeCommandTest extends TestCase { LOG.info("withCount = " + withCount + "\n allCount = " + allCount + "\n = " + "\n"); */ - } finally { - purgeAllMessages(); - } - } - - + } + finally { + purgeAllMessages(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/conversions/AmqpAndMqttTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/conversions/AmqpAndMqttTest.java index 3c0f474b8a..d9b7add1e8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/conversions/AmqpAndMqttTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/conversions/AmqpAndMqttTest.java @@ -34,87 +34,86 @@ import java.util.Arrays; */ public class AmqpAndMqttTest extends CombinationTestSupport { - protected BrokerService broker; - private TransportConnector amqpConnector; - private TransportConnector mqttConnector; + protected BrokerService broker; + private TransportConnector amqpConnector; + private TransportConnector mqttConnector; - @Override - protected void setUp() throws Exception { - super.setUp(); - broker = createBroker(); - broker.start(); - broker.waitUntilStarted(); - } + @Override + protected void setUp() throws Exception { + super.setUp(); + broker = createBroker(); + broker.start(); + broker.waitUntilStarted(); + } - @Override - protected void tearDown() throws Exception { - if( broker!=null ) { - broker.stop(); - broker.waitUntilStopped(); - broker = null; - } - super.tearDown(); - } + @Override + protected void tearDown() throws Exception { + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + broker = null; + } + super.tearDown(); + } - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setPersistent(false); - amqpConnector = broker.addConnector("amqp://0.0.0.0:0"); - mqttConnector = broker.addConnector("mqtt://0.0.0.0:0"); - return broker; - } + protected BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setPersistent(false); + amqpConnector = broker.addConnector("amqp://0.0.0.0:0"); + mqttConnector = broker.addConnector("mqtt://0.0.0.0:0"); + return broker; + } + public void testFromMqttToAmqp() throws Exception { + Connection amqp = createAmqpConnection(); + Session session = amqp.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(session.createTopic("topic://FOO")); - public void testFromMqttToAmqp() throws Exception { - Connection amqp = createAmqpConnection(); - Session session = amqp.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(session.createTopic("topic://FOO")); + final BlockingConnection mqtt = createMQTTConnection().blockingConnection(); + mqtt.connect(); + byte[] payload = bytes("Hello World"); + mqtt.publish("FOO", payload, QoS.AT_LEAST_ONCE, false); + mqtt.disconnect(); - final BlockingConnection mqtt = createMQTTConnection().blockingConnection(); - mqtt.connect(); - byte[] payload = bytes("Hello World"); - mqtt.publish("FOO", payload, QoS.AT_LEAST_ONCE, false); - mqtt.disconnect(); + Message msg = consumer.receive(1000 * 5); + assertNotNull(msg); + assertTrue(msg instanceof BytesMessage); - Message msg = consumer.receive(1000 * 5); - assertNotNull(msg); - assertTrue(msg instanceof BytesMessage); + BytesMessage bmsg = (BytesMessage) msg; + byte[] actual = new byte[(int) bmsg.getBodyLength()]; + bmsg.readBytes(actual); + assertTrue(Arrays.equals(actual, payload)); + amqp.close(); + } - BytesMessage bmsg = (BytesMessage) msg; - byte[] actual = new byte[(int) bmsg.getBodyLength()]; - bmsg.readBytes(actual); - assertTrue(Arrays.equals(actual, payload)); - amqp.close(); - } + private byte[] bytes(String value) { + try { + return value.getBytes("UTF-8"); + } + catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } - private byte[] bytes(String value) { - try { - return value.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - } + protected MQTT createMQTTConnection() throws Exception { + MQTT mqtt = new MQTT(); + mqtt.setConnectAttemptsMax(1); + mqtt.setReconnectAttemptsMax(0); + mqtt.setHost("localhost", mqttConnector.getConnectUri().getPort()); + return mqtt; + } - - protected MQTT createMQTTConnection() throws Exception { - MQTT mqtt = new MQTT(); - mqtt.setConnectAttemptsMax(1); - mqtt.setReconnectAttemptsMax(0); - mqtt.setHost("localhost", mqttConnector.getConnectUri().getPort()); - return mqtt; - } - - public Connection createAmqpConnection() throws Exception { - final ConnectionFactoryImpl factory = new ConnectionFactoryImpl("localhost", amqpConnector.getConnectUri().getPort(), "admin", "password"); - final Connection connection = factory.createConnection(); - connection.setExceptionListener(new ExceptionListener() { - @Override - public void onException(JMSException exception) { - exception.printStackTrace(); - } - }); - connection.start(); - return connection; - } + public Connection createAmqpConnection() throws Exception { + final ConnectionFactoryImpl factory = new ConnectionFactoryImpl("localhost", amqpConnector.getConnectUri().getPort(), "admin", "password"); + final Connection connection = factory.createConnection(); + connection.setExceptionListener(new ExceptionListener() { + @Override + public void onException(JMSException exception) { + exception.printStackTrace(); + } + }); + connection.start(); + return connection; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/demo/DefaultQueueSender.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/demo/DefaultQueueSender.java index 98ca666cb3..bef0550d25 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/demo/DefaultQueueSender.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/demo/DefaultQueueSender.java @@ -42,70 +42,71 @@ import org.slf4j.LoggerFactory; /** * A simple queue sender which does not use JNDI - * - * */ public final class DefaultQueueSender { - private static final Logger LOG = LoggerFactory.getLogger(DefaultQueueSender.class); + private static final Logger LOG = LoggerFactory.getLogger(DefaultQueueSender.class); - private DefaultQueueSender() { - } + private DefaultQueueSender() { + } - public static void main(String[] args) { + public static void main(String[] args) { - String uri = "tcp://localhost:61616"; - String text = "Hello World!"; + String uri = "tcp://localhost:61616"; + String text = "Hello World!"; - Connection connection = null; + Connection connection = null; - if (args.length < 1) { + if (args.length < 1) { + printUsage(); + System.exit(1); + } + + int idx = 0; + String arg = args[0]; + if (arg.equals("-uri")) { + if (args.length == 1) { printUsage(); System.exit(1); - } + } + uri = args[1]; + idx += 2; + } + String queueName = args[idx]; + LOG.info("Connecting to: " + uri); + LOG.info("Queue name is " + queueName); - int idx = 0; - String arg = args[0]; - if (arg.equals("-uri")) { - if (args.length == 1) { - printUsage(); - System.exit(1); + if (++idx < args.length) { + text = args[idx]; + } + + try { + ConnectionFactory factory = new ActiveMQConnectionFactory(uri); + connection = factory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue(queueName); + MessageProducer producer = session.createProducer(destination); + + Message message = session.createTextMessage(text); + producer.send(message); + } + catch (JMSException e) { + LOG.info("Exception occurred: " + e.toString()); + } + finally { + if (connection != null) { + try { + connection.close(); } - uri = args[1]; - idx += 2; - } - String queueName = args[idx]; - LOG.info("Connecting to: " + uri); - LOG.info("Queue name is " + queueName); - - if (++idx < args.length) { - text = args[idx]; - } - - try { - ConnectionFactory factory = new ActiveMQConnectionFactory(uri); - connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(queueName); - MessageProducer producer = session.createProducer(destination); - - Message message = session.createTextMessage(text); - producer.send(message); - } catch (JMSException e) { - LOG.info("Exception occurred: " + e.toString()); - } finally { - if (connection != null) { - try { - connection.close(); - } catch (JMSException e) { - } + catch (JMSException e) { } - } - } + } + } + } - protected static void printUsage() { - System.out.println("Usage: java DefaultQueueSender [-uri ] " + " []"); - } + protected static void printUsage() { + System.out.println("Usage: java DefaultQueueSender [-uri ] " + " []"); + } } // END SNIPPET: demo diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/demo/SimpleConsumer.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/demo/SimpleConsumer.java index 9b515ace24..ee8899b118 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/demo/SimpleConsumer.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/demo/SimpleConsumer.java @@ -39,59 +39,58 @@ import javax.naming.NamingException; /** * A simple polymorphic JMS consumer which can work with Queues or Topics which * uses JNDI to lookup the JMS connection factory and destination - * - * */ public final class SimpleConsumer { - private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory - .getLog(SimpleConsumer.class); + private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(SimpleConsumer.class); - private SimpleConsumer() { - } + private SimpleConsumer() { + } - /** - * @param args the queue used by the example - */ - public static void main(String[] args) { - String destinationName = null; - Context jndiContext = null; - ConnectionFactory connectionFactory = null; - Connection connection = null; - Session session = null; - Destination destination = null; - MessageConsumer consumer = null; + /** + * @param args the queue used by the example + */ + public static void main(String[] args) { + String destinationName = null; + Context jndiContext = null; + ConnectionFactory connectionFactory = null; + Connection connection = null; + Session session = null; + Destination destination = null; + MessageConsumer consumer = null; /* * Read destination name from command line and display it. */ - if (args.length != 1) { - LOG.info("Usage: java SimpleConsumer "); - System.exit(1); - } - destinationName = args[0]; - LOG.info("Destination name is " + destinationName); + if (args.length != 1) { + LOG.info("Usage: java SimpleConsumer "); + System.exit(1); + } + destinationName = args[0]; + LOG.info("Destination name is " + destinationName); /* * Create a JNDI API InitialContext object */ - try { - jndiContext = new InitialContext(); - } catch (NamingException e) { - LOG.info("Could not create JNDI API " + "context: " + e.toString()); - System.exit(1); - } + try { + jndiContext = new InitialContext(); + } + catch (NamingException e) { + LOG.info("Could not create JNDI API " + "context: " + e.toString()); + System.exit(1); + } /* * Look up connection factory and destination. */ - try { - connectionFactory = (ConnectionFactory)jndiContext.lookup("ConnectionFactory"); - destination = (Destination)jndiContext.lookup(destinationName); - } catch (NamingException e) { - LOG.info("JNDI API lookup failed: " + e.toString()); - System.exit(1); - } + try { + connectionFactory = (ConnectionFactory) jndiContext.lookup("ConnectionFactory"); + destination = (Destination) jndiContext.lookup(destinationName); + } + catch (NamingException e) { + LOG.info("JNDI API lookup failed: " + e.toString()); + System.exit(1); + } /* * Create connection. Create session from connection; false means @@ -100,31 +99,35 @@ public final class SimpleConsumer { * message is received indicating end of message stream. Close * connection. */ - try { - connection = connectionFactory.createConnection(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = session.createConsumer(destination); - connection.start(); - while (true) { - Message m = consumer.receive(1); - if (m != null) { - if (m instanceof TextMessage) { - TextMessage message = (TextMessage)m; - LOG.info("Reading message: " + message.getText()); - } else { - break; - } - } + try { + connection = connectionFactory.createConnection(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumer = session.createConsumer(destination); + connection.start(); + while (true) { + Message m = consumer.receive(1); + if (m != null) { + if (m instanceof TextMessage) { + TextMessage message = (TextMessage) m; + LOG.info("Reading message: " + message.getText()); + } + else { + break; + } } - } catch (JMSException e) { - LOG.info("Exception occurred: " + e); - } finally { - if (connection != null) { - try { - connection.close(); - } catch (JMSException e) { - } + } + } + catch (JMSException e) { + LOG.info("Exception occurred: " + e); + } + finally { + if (connection != null) { + try { + connection.close(); } - } - } + catch (JMSException e) { + } + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/demo/SimpleProducer.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/demo/SimpleProducer.java index 85061c847c..6e5fb4c051 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/demo/SimpleProducer.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/demo/SimpleProducer.java @@ -45,62 +45,63 @@ import org.slf4j.LoggerFactory; /** * A simple polymorphic JMS producer which can work with Queues or Topics which * uses JNDI to lookup the JMS connection factory and destination - * - * */ public final class SimpleProducer { - private static final Logger LOG = LoggerFactory.getLogger(SimpleProducer.class); + private static final Logger LOG = LoggerFactory.getLogger(SimpleProducer.class); - private SimpleProducer() { - } + private SimpleProducer() { + } - /** - * @param args the destination name to send to and optionally, the number of - * messages to send - */ - public static void main(String[] args) { - Context jndiContext = null; - ConnectionFactory connectionFactory = null; - Connection connection = null; - Session session = null; - Destination destination = null; - MessageProducer producer = null; - String destinationName = null; - final int numMsgs; + /** + * @param args the destination name to send to and optionally, the number of + * messages to send + */ + public static void main(String[] args) { + Context jndiContext = null; + ConnectionFactory connectionFactory = null; + Connection connection = null; + Session session = null; + Destination destination = null; + MessageProducer producer = null; + String destinationName = null; + final int numMsgs; - if ((args.length < 1) || (args.length > 2)) { - LOG.info("Usage: java SimpleProducer []"); - System.exit(1); - } - destinationName = args[0]; - LOG.info("Destination name is " + destinationName); - if (args.length == 2) { - numMsgs = (new Integer(args[1])).intValue(); - } else { - numMsgs = 1; - } + if ((args.length < 1) || (args.length > 2)) { + LOG.info("Usage: java SimpleProducer []"); + System.exit(1); + } + destinationName = args[0]; + LOG.info("Destination name is " + destinationName); + if (args.length == 2) { + numMsgs = (new Integer(args[1])).intValue(); + } + else { + numMsgs = 1; + } /* * Create a JNDI API InitialContext object */ - try { - jndiContext = new InitialContext(); - } catch (NamingException e) { - LOG.info("Could not create JNDI API context: " + e.toString()); - System.exit(1); - } + try { + jndiContext = new InitialContext(); + } + catch (NamingException e) { + LOG.info("Could not create JNDI API context: " + e.toString()); + System.exit(1); + } /* * Look up connection factory and destination. */ - try { - connectionFactory = (ConnectionFactory)jndiContext.lookup("ConnectionFactory"); - destination = (Destination)jndiContext.lookup(destinationName); - } catch (NamingException e) { - LOG.info("JNDI API lookup failed: " + e); - System.exit(1); - } + try { + connectionFactory = (ConnectionFactory) jndiContext.lookup("ConnectionFactory"); + destination = (Destination) jndiContext.lookup(destinationName); + } + catch (NamingException e) { + LOG.info("JNDI API lookup failed: " + e); + System.exit(1); + } /* * Create connection. Create session from connection; false means @@ -108,32 +109,35 @@ public final class SimpleProducer { * messages, varying text slightly. Send end-of-messages message. * Finally, close connection. */ - try { - connection = connectionFactory.createConnection(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(destination); - TextMessage message = session.createTextMessage(); - for (int i = 0; i < numMsgs; i++) { - message.setText("This is message " + (i + 1)); - LOG.info("Sending message: " + message.getText()); - producer.send(message); - } + try { + connection = connectionFactory.createConnection(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer = session.createProducer(destination); + TextMessage message = session.createTextMessage(); + for (int i = 0; i < numMsgs; i++) { + message.setText("This is message " + (i + 1)); + LOG.info("Sending message: " + message.getText()); + producer.send(message); + } /* * Send a non-text control message indicating end of messages. */ - producer.send(session.createMessage()); - } catch (JMSException e) { - LOG.info("Exception occurred: " + e); - } finally { - if (connection != null) { - try { - connection.close(); - } catch (JMSException e) { - } + producer.send(session.createMessage()); + } + catch (JMSException e) { + LOG.info("Exception occurred: " + e); + } + finally { + if (connection != null) { + try { + connection.close(); } - } - } + catch (JMSException e) { + } + } + } + } } // END SNIPPET: demo diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/demo/SimpleQueueReceiver.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/demo/SimpleQueueReceiver.java index 791efa1d18..73ee6b1326 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/demo/SimpleQueueReceiver.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/demo/SimpleQueueReceiver.java @@ -42,56 +42,58 @@ import org.slf4j.LoggerFactory; public final class SimpleQueueReceiver { - private static final Logger LOG = LoggerFactory.getLogger(SimpleQueueReceiver.class); + private static final Logger LOG = LoggerFactory.getLogger(SimpleQueueReceiver.class); - private SimpleQueueReceiver() { - } + private SimpleQueueReceiver() { + } - /** - * Main method. - * - * @param args the queue used by the example - */ - public static void main(String[] args) { - String queueName = null; - Context jndiContext = null; - QueueConnectionFactory queueConnectionFactory = null; - QueueConnection queueConnection = null; - QueueSession queueSession = null; - Queue queue = null; - QueueReceiver queueReceiver = null; - TextMessage message = null; + /** + * Main method. + * + * @param args the queue used by the example + */ + public static void main(String[] args) { + String queueName = null; + Context jndiContext = null; + QueueConnectionFactory queueConnectionFactory = null; + QueueConnection queueConnection = null; + QueueSession queueSession = null; + Queue queue = null; + QueueReceiver queueReceiver = null; + TextMessage message = null; /* * Read queue name from command line and display it. */ - if (args.length != 1) { - LOG.info("Usage: java " + "SimpleQueueReceiver "); - System.exit(1); - } - queueName = args[0]; - LOG.info("Queue name is " + queueName); + if (args.length != 1) { + LOG.info("Usage: java " + "SimpleQueueReceiver "); + System.exit(1); + } + queueName = args[0]; + LOG.info("Queue name is " + queueName); /* * Create a JNDI API InitialContext object if none exists yet. */ - try { - jndiContext = new InitialContext(); - } catch (NamingException e) { - LOG.info("Could not create JNDI API " + "context: " + e.toString()); - System.exit(1); - } + try { + jndiContext = new InitialContext(); + } + catch (NamingException e) { + LOG.info("Could not create JNDI API " + "context: " + e.toString()); + System.exit(1); + } /* * Look up connection factory and queue. If either does not exist, exit. */ - try { - queueConnectionFactory = (QueueConnectionFactory)jndiContext.lookup("QueueConnectionFactory"); - queue = (Queue)jndiContext.lookup(queueName); - } catch (NamingException e) { - LOG.info("JNDI API lookup failed: " + e.toString()); - System.exit(1); - } + try { + queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("QueueConnectionFactory"); + queue = (Queue) jndiContext.lookup(queueName); + } + catch (NamingException e) { + LOG.info("JNDI API lookup failed: " + e.toString()); + System.exit(1); + } /* * Create connection. Create session from connection; false means @@ -100,31 +102,35 @@ public final class SimpleQueueReceiver { * message is received indicating end of message stream. Close * connection. */ - try { - queueConnection = queueConnectionFactory.createQueueConnection(); - queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); - queueReceiver = queueSession.createReceiver(queue); - queueConnection.start(); - while (true) { - Message m = queueReceiver.receive(1); - if (m != null) { - if (m instanceof TextMessage) { - message = (TextMessage)m; - LOG.info("Reading message: " + message.getText()); - } else { - break; - } - } + try { + queueConnection = queueConnectionFactory.createQueueConnection(); + queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); + queueReceiver = queueSession.createReceiver(queue); + queueConnection.start(); + while (true) { + Message m = queueReceiver.receive(1); + if (m != null) { + if (m instanceof TextMessage) { + message = (TextMessage) m; + LOG.info("Reading message: " + message.getText()); + } + else { + break; + } } - } catch (JMSException e) { - LOG.info("Exception occurred: " + e.toString()); - } finally { - if (queueConnection != null) { - try { - queueConnection.close(); - } catch (JMSException e) { - } + } + } + catch (JMSException e) { + LOG.info("Exception occurred: " + e.toString()); + } + finally { + if (queueConnection != null) { + try { + queueConnection.close(); } - } - } + catch (JMSException e) { + } + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/demo/SimpleQueueSender.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/demo/SimpleQueueSender.java index 22ee403be8..59490ef7c8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/demo/SimpleQueueSender.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/demo/SimpleQueueSender.java @@ -45,60 +45,63 @@ import org.slf4j.LoggerFactory; public final class SimpleQueueSender { - private static final Logger LOG = LoggerFactory.getLogger(SimpleQueueSender.class); + private static final Logger LOG = LoggerFactory.getLogger(SimpleQueueSender.class); - private SimpleQueueSender() { - } + private SimpleQueueSender() { + } - /** - * Main method. - * - * @param args the queue used by the example and, optionally, the number of - * messages to send - */ - public static void main(String[] args) { - String queueName = null; - Context jndiContext = null; - QueueConnectionFactory queueConnectionFactory = null; - QueueConnection queueConnection = null; - QueueSession queueSession = null; - Queue queue = null; - QueueSender queueSender = null; - TextMessage message = null; - final int numMsgs; + /** + * Main method. + * + * @param args the queue used by the example and, optionally, the number of + * messages to send + */ + public static void main(String[] args) { + String queueName = null; + Context jndiContext = null; + QueueConnectionFactory queueConnectionFactory = null; + QueueConnection queueConnection = null; + QueueSession queueSession = null; + Queue queue = null; + QueueSender queueSender = null; + TextMessage message = null; + final int numMsgs; - if ((args.length < 1) || (args.length > 2)) { - LOG.info("Usage: java SimpleQueueSender " + " []"); - System.exit(1); - } - queueName = args[0]; - LOG.info("Queue name is " + queueName); - if (args.length == 2) { - numMsgs = (new Integer(args[1])).intValue(); - } else { - numMsgs = 1; - } + if ((args.length < 1) || (args.length > 2)) { + LOG.info("Usage: java SimpleQueueSender " + " []"); + System.exit(1); + } + queueName = args[0]; + LOG.info("Queue name is " + queueName); + if (args.length == 2) { + numMsgs = (new Integer(args[1])).intValue(); + } + else { + numMsgs = 1; + } /* * Create a JNDI API InitialContext object if none exists yet. */ - try { - jndiContext = new InitialContext(); - } catch (NamingException e) { - LOG.info("Could not create JNDI API context: " + e.toString()); - System.exit(1); - } + try { + jndiContext = new InitialContext(); + } + catch (NamingException e) { + LOG.info("Could not create JNDI API context: " + e.toString()); + System.exit(1); + } /* * Look up connection factory and queue. If either does not exist, exit. */ - try { - queueConnectionFactory = (QueueConnectionFactory)jndiContext.lookup("QueueConnectionFactory"); - queue = (Queue)jndiContext.lookup(queueName); - } catch (NamingException e) { - LOG.info("JNDI API lookup failed: " + e); - System.exit(1); - } + try { + queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("QueueConnectionFactory"); + queue = (Queue) jndiContext.lookup(queueName); + } + catch (NamingException e) { + LOG.info("JNDI API lookup failed: " + e); + System.exit(1); + } /* * Create connection. Create session from connection; false means @@ -106,32 +109,35 @@ public final class SimpleQueueSender { * messages, varying text slightly. Send end-of-messages message. * Finally, close connection. */ - try { - queueConnection = queueConnectionFactory.createQueueConnection(); - queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); - queueSender = queueSession.createSender(queue); - message = queueSession.createTextMessage(); - for (int i = 0; i < numMsgs; i++) { - message.setText("This is message " + (i + 1)); - LOG.info("Sending message: " + message.getText()); - queueSender.send(message); - } + try { + queueConnection = queueConnectionFactory.createQueueConnection(); + queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); + queueSender = queueSession.createSender(queue); + message = queueSession.createTextMessage(); + for (int i = 0; i < numMsgs; i++) { + message.setText("This is message " + (i + 1)); + LOG.info("Sending message: " + message.getText()); + queueSender.send(message); + } /* * Send a non-text control message indicating end of messages. */ - queueSender.send(queueSession.createMessage()); - } catch (JMSException e) { - LOG.info("Exception occurred: " + e.toString()); - } finally { - if (queueConnection != null) { - try { - queueConnection.close(); - } catch (JMSException e) { - } + queueSender.send(queueSession.createMessage()); + } + catch (JMSException e) { + LOG.info("Exception occurred: " + e.toString()); + } + finally { + if (queueConnection != null) { + try { + queueConnection.close(); } - } - } + catch (JMSException e) { + } + } + } + } } // END SNIPPET: demo diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationFilterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationFilterTest.java index 95af3942e9..c1899715f7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationFilterTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationFilterTest.java @@ -23,43 +23,43 @@ import junit.framework.TestCase; public class DestinationFilterTest extends TestCase { - public void testPrefixFilter() throws Exception { - DestinationFilter filter = DestinationFilter.parseFilter(new ActiveMQQueue(">")); - assertTrue("Filter not parsed well: " + filter.getClass(), filter instanceof PrefixDestinationFilter); - System.out.println(filter); - assertFalse("Filter matched wrong destination type", filter.matches(new ActiveMQTopic(">"))); - } + public void testPrefixFilter() throws Exception { + DestinationFilter filter = DestinationFilter.parseFilter(new ActiveMQQueue(">")); + assertTrue("Filter not parsed well: " + filter.getClass(), filter instanceof PrefixDestinationFilter); + System.out.println(filter); + assertFalse("Filter matched wrong destination type", filter.matches(new ActiveMQTopic(">"))); + } - public void testWildcardFilter() throws Exception { - DestinationFilter filter = DestinationFilter.parseFilter(new ActiveMQQueue("A.*")); - assertTrue("Filter not parsed well: " + filter.getClass(), filter instanceof WildcardDestinationFilter); - assertFalse("Filter matched wrong destination type", filter.matches(new ActiveMQTopic("A.B"))); - } + public void testWildcardFilter() throws Exception { + DestinationFilter filter = DestinationFilter.parseFilter(new ActiveMQQueue("A.*")); + assertTrue("Filter not parsed well: " + filter.getClass(), filter instanceof WildcardDestinationFilter); + assertFalse("Filter matched wrong destination type", filter.matches(new ActiveMQTopic("A.B"))); + } - public void testCompositeFilter() throws Exception { - DestinationFilter filter = DestinationFilter.parseFilter(new ActiveMQQueue("A.B,B.C")); - assertTrue("Filter not parsed well: " + filter.getClass(), filter instanceof CompositeDestinationFilter); - assertFalse("Filter matched wrong destination type", filter.matches(new ActiveMQTopic("A.B"))); - } + public void testCompositeFilter() throws Exception { + DestinationFilter filter = DestinationFilter.parseFilter(new ActiveMQQueue("A.B,B.C")); + assertTrue("Filter not parsed well: " + filter.getClass(), filter instanceof CompositeDestinationFilter); + assertFalse("Filter matched wrong destination type", filter.matches(new ActiveMQTopic("A.B"))); + } - public void testMatchesChild() throws Exception{ - DestinationFilter filter = DestinationFilter.parseFilter(new ActiveMQQueue("A.*.C")); - assertFalse("Filter matched wrong destination type", filter.matches(new ActiveMQTopic("A.B"))); - assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A.B.C"))); + public void testMatchesChild() throws Exception { + DestinationFilter filter = DestinationFilter.parseFilter(new ActiveMQQueue("A.*.C")); + assertFalse("Filter matched wrong destination type", filter.matches(new ActiveMQTopic("A.B"))); + assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A.B.C"))); - filter = DestinationFilter.parseFilter(new ActiveMQQueue("A.*")); - assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A.B"))); - assertFalse("Filter did match", filter.matches(new ActiveMQQueue("A"))); - } + filter = DestinationFilter.parseFilter(new ActiveMQQueue("A.*")); + assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A.B"))); + assertFalse("Filter did match", filter.matches(new ActiveMQQueue("A"))); + } - public void testMatchesAny() throws Exception{ - DestinationFilter filter = DestinationFilter.parseFilter(new ActiveMQQueue("A.>.>")); + public void testMatchesAny() throws Exception { + DestinationFilter filter = DestinationFilter.parseFilter(new ActiveMQQueue("A.>.>")); - assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A.C"))); + assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A.C"))); - assertFalse("Filter did match", filter.matches(new ActiveMQQueue("B"))); - assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A.B"))); - assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A.B.C.D.E.F"))); - assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A"))); - } + assertFalse("Filter did match", filter.matches(new ActiveMQQueue("B"))); + assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A.B"))); + assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A.B.C.D.E.F"))); + assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A"))); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationMapMemoryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationMapMemoryTest.java index 42edaf43fa..480a854e11 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationMapMemoryTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationMapMemoryTest.java @@ -17,36 +17,38 @@ package org.apache.activemq.filter; import junit.framework.TestCase; + import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQTopic; public class DestinationMapMemoryTest extends TestCase { - public void testLongDestinationPath() throws Exception { - ActiveMQTopic d1 = new ActiveMQTopic("1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18"); - DestinationMap map = new DestinationMap(); - map.put(d1, d1); - } + public void testLongDestinationPath() throws Exception { + ActiveMQTopic d1 = new ActiveMQTopic("1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18"); + DestinationMap map = new DestinationMap(); + map.put(d1, d1); + } - public void testVeryLongestinationPaths() throws Exception { + public void testVeryLongestinationPaths() throws Exception { - for (int i = 1; i < 100; i++) { - String name = "1"; - for (int j = 2; j <= i; j++) { - name += "." + j; - } - // System.out.println("Checking: " + name); - try { - ActiveMQDestination d1 = createDestination(name); - DestinationMap map = new DestinationMap(); - map.put(d1, d1); - } catch (Throwable e) { - fail("Destination name too long: " + name + " : " + e); - } - } - } + for (int i = 1; i < 100; i++) { + String name = "1"; + for (int j = 2; j <= i; j++) { + name += "." + j; + } + // System.out.println("Checking: " + name); + try { + ActiveMQDestination d1 = createDestination(name); + DestinationMap map = new DestinationMap(); + map.put(d1, d1); + } + catch (Throwable e) { + fail("Destination name too long: " + name + " : " + e); + } + } + } - protected ActiveMQDestination createDestination(String name) { - return new ActiveMQTopic(name); - } + protected ActiveMQDestination createDestination(String name) { + return new ActiveMQTopic(name); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationMapTempDestinationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationMapTempDestinationTest.java index 21dd60d946..2a2d2fcf01 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationMapTempDestinationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationMapTempDestinationTest.java @@ -26,20 +26,20 @@ import org.apache.activemq.util.IdGenerator; public class DestinationMapTempDestinationTest extends TestCase { - public void testtestTempDestinations() throws Exception { - ConnectionId id = new ConnectionId(new IdGenerator().generateId()); - DestinationMap map = new DestinationMap(); - Object value = new Object(); - int count = 1000; - for (int i = 0; i < count; i++) { - ActiveMQTempQueue queue = new ActiveMQTempQueue(id, i); - map.put(queue, value); - } - for (int i = 0; i < count; i++) { - ActiveMQTempQueue queue = new ActiveMQTempQueue(id, i); - map.remove(queue, value); - Set set = map.get(queue); - assertTrue(set.isEmpty()); - } - } + public void testtestTempDestinations() throws Exception { + ConnectionId id = new ConnectionId(new IdGenerator().generateId()); + DestinationMap map = new DestinationMap(); + Object value = new Object(); + int count = 1000; + for (int i = 0; i < count; i++) { + ActiveMQTempQueue queue = new ActiveMQTempQueue(id, i); + map.put(queue, value); + } + for (int i = 0; i < count; i++) { + ActiveMQTempQueue queue = new ActiveMQTempQueue(id, i); + map.remove(queue, value); + Set set = map.get(queue); + assertTrue(set.isEmpty()); + } + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationMapTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationMapTest.java index 2f0f92c0a4..2930fdf45f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationMapTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationMapTest.java @@ -26,389 +26,408 @@ import java.util.Set; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTopic; + import junit.framework.TestCase; public class DestinationMapTest extends TestCase { - protected DestinationMap map = new DestinationMap(); - - protected ActiveMQDestination d1 = createDestination("TEST.D1"); - protected ActiveMQDestination d2 = createDestination("TEST.BAR.D2"); - protected ActiveMQDestination d3 = createDestination("TEST.BAR.D3"); - protected ActiveMQDestination compositeDestination1 = createDestination("TEST.D1,TEST.BAR.D2"); - protected ActiveMQDestination compositeDestination2 = createDestination("TEST.D1,TEST.BAR.D3"); - - protected Object v1 = "value1"; - protected Object v2 = "value2"; - protected Object v3 = "value3"; - protected Object v4 = "value4"; - protected Object v5 = "value5"; - protected Object v6 = "value6"; - - public void testCompositeDestinations() throws Exception { - ActiveMQDestination d1 = createDestination("TEST.BAR.D2"); - ActiveMQDestination d2 = createDestination("TEST.BAR.D3"); - map.put(d1, d1); - map.put(d2, d2); - map.get(createDestination("TEST.BAR.D2,TEST.BAR.D3")); - } - - public void testSimpleDestinations() throws Exception { - map.put(d1, v1); - map.put(d2, v2); - map.put(d3, v3); - - assertMapValue(d1, v1); - assertMapValue(d2, v2); - assertMapValue(d3, v3); - } - - public void testQueueAndTopicWithSameName() throws Exception { - ActiveMQQueue q1 = new ActiveMQQueue("foo"); - ActiveMQTopic t1 = new ActiveMQTopic("foo"); - - map.put(q1, v1); - map.put(t1, v2); - - assertMapValue(q1, v1); - assertMapValue(t1, v2); - } - - public void testSimpleDestinationsWithMultipleValues() throws Exception { - map.put(d1, v1); - map.put(d2, v2); - map.put(d2, v3); - - assertMapValue(d1, v1); - assertMapValue("TEST.BAR.D2", v2, v3); - assertMapValue(d3, null); - } - - public void testSimpleAndCompositeDestinations() throws Exception { - map.put(d1, v1); - map.put(compositeDestination1, v2); - map.put(compositeDestination2, v3); - - assertMapValue("TEST.D1", v1, v2, v3); - assertMapValue(d2, v2); - assertMapValue(d3, v3); - assertMapValue(compositeDestination1.toString(), v1, v2, v3); - assertMapValue(compositeDestination2.toString(), v1, v2, v3); - - map.remove(compositeDestination1, v2); - map.remove(compositeDestination2, v3); - - assertMapValue("TEST.D1", v1); - } - - public void testLookupOneStepWildcardDestinations() throws Exception { - map.put(d1, v1); - map.put(d2, v2); - map.put(d3, v3); - - assertMapValue("TEST.D1", v1); - assertMapValue("TEST.*", v1); - assertMapValue("*.D1", v1); - assertMapValue("*.*", v1); - - assertMapValue("TEST.BAR.D2", v2); - assertMapValue("TEST.*.D2", v2); - assertMapValue("*.BAR.D2", v2); - assertMapValue("*.*.D2", v2); - - assertMapValue("TEST.BAR.D3", v3); - assertMapValue("TEST.*.D3", v3); - assertMapValue("*.BAR.D3", v3); - assertMapValue("*.*.D3", v3); - - assertMapValue("TEST.BAR.D4", null); - - assertMapValue("TEST.BAR.*", v2, v3); - } - - public void testLookupMultiStepWildcardDestinations() throws Exception { - map.put(d1, v1); - map.put(d2, v2); - map.put(d3, v3); - - List allValues = Arrays.asList(new Object[] {v1, v2, v3}); - - assertMapValue(">", allValues); - assertMapValue("TEST.>", allValues); - assertMapValue("*.>", allValues); - assertMapValue("TEST.*.>", allValues); - assertMapValue("TEST.*.*.>", v2,v3); - - assertMapValue("FOO.>", null); - } - - public void testStoreWildcardWithOneStepPath() throws Exception { - put("TEST.*", v1); - put("TEST.D1", v2); - put("TEST.BAR.*", v2); - put("TEST.BAR.D3", v3); - - assertMapValue("FOO", null); - assertMapValue("TEST.FOO", v1); - assertMapValue("TEST.D1", v1, v2); - - assertMapValue("TEST.FOO.FOO", null); - assertMapValue("TEST.BAR.FOO", v2); - assertMapValue("TEST.BAR.D3", v2, v3); - - assertMapValue("TEST.*", v1, v2); - assertMapValue("*.D1", v1, v2); - assertMapValue("*.*", v1, v2); - assertMapValue("TEST.*.*", v2, v3); - assertMapValue("TEST.BAR.*", v2, v3); - assertMapValue("*.*.*", v2, v3); - assertMapValue("*.BAR.*", v2, v3); - assertMapValue("*.BAR.D3", v2, v3); - assertMapValue("*.*.D3", v2, v3); - } - - public void testStoreWildcardInMiddleOfPath() throws Exception { - put("TEST.*", v1); - put("TEST.D1", v2); - put("TEST.BAR.*", v2); - put("TEST.XYZ.D3", v3); - put("TEST.XYZ.D4", v4); - put("TEST.BAR.D3", v5); - put("TEST.*.D2", v6); - - assertMapValue("TEST.*.D3", v2, v3, v5); - assertMapValue("TEST.*.D4", v2, v4); - - assertMapValue("TEST.*", v1, v2); - assertMapValue("TEST.*.*", v2, v3, v4, v5, v6); - assertMapValue("TEST.*.>", v1, v2, v3, v4, v5, v6); - assertMapValue("TEST.>", v1, v2, v3, v4, v5, v6); - assertMapValue("TEST.>.>", v1, v2, v3, v4, v5, v6); - assertMapValue("*.*.D3", v2, v3, v5); - assertMapValue("TEST.BAR.*", v2, v5, v6); - - assertMapValue("TEST.BAR.D2", v2, v6); - assertMapValue("TEST.*.D2", v2, v6); - assertMapValue("TEST.BAR.*", v2, v5, v6); - } - - public void testDoubleWildcardDoesNotMatchLongerPattern() throws Exception { - put("TEST.*", v1); - put("TEST.BAR.D3", v2); - - assertMapValue("*.*.D3", v2); - } - public void testWildcardAtEndOfPathAndAtBeginningOfSearch() throws Exception { - put("TEST.*", v1); + protected DestinationMap map = new DestinationMap(); + + protected ActiveMQDestination d1 = createDestination("TEST.D1"); + protected ActiveMQDestination d2 = createDestination("TEST.BAR.D2"); + protected ActiveMQDestination d3 = createDestination("TEST.BAR.D3"); + protected ActiveMQDestination compositeDestination1 = createDestination("TEST.D1,TEST.BAR.D2"); + protected ActiveMQDestination compositeDestination2 = createDestination("TEST.D1,TEST.BAR.D3"); + + protected Object v1 = "value1"; + protected Object v2 = "value2"; + protected Object v3 = "value3"; + protected Object v4 = "value4"; + protected Object v5 = "value5"; + protected Object v6 = "value6"; + + public void testCompositeDestinations() throws Exception { + ActiveMQDestination d1 = createDestination("TEST.BAR.D2"); + ActiveMQDestination d2 = createDestination("TEST.BAR.D3"); + map.put(d1, d1); + map.put(d2, d2); + map.get(createDestination("TEST.BAR.D2,TEST.BAR.D3")); + } + + public void testSimpleDestinations() throws Exception { + map.put(d1, v1); + map.put(d2, v2); + map.put(d3, v3); + + assertMapValue(d1, v1); + assertMapValue(d2, v2); + assertMapValue(d3, v3); + } + + public void testQueueAndTopicWithSameName() throws Exception { + ActiveMQQueue q1 = new ActiveMQQueue("foo"); + ActiveMQTopic t1 = new ActiveMQTopic("foo"); + + map.put(q1, v1); + map.put(t1, v2); + + assertMapValue(q1, v1); + assertMapValue(t1, v2); + } + + public void testSimpleDestinationsWithMultipleValues() throws Exception { + map.put(d1, v1); + map.put(d2, v2); + map.put(d2, v3); + + assertMapValue(d1, v1); + assertMapValue("TEST.BAR.D2", v2, v3); + assertMapValue(d3, null); + } + + public void testSimpleAndCompositeDestinations() throws Exception { + map.put(d1, v1); + map.put(compositeDestination1, v2); + map.put(compositeDestination2, v3); + + assertMapValue("TEST.D1", v1, v2, v3); + assertMapValue(d2, v2); + assertMapValue(d3, v3); + assertMapValue(compositeDestination1.toString(), v1, v2, v3); + assertMapValue(compositeDestination2.toString(), v1, v2, v3); + + map.remove(compositeDestination1, v2); + map.remove(compositeDestination2, v3); + + assertMapValue("TEST.D1", v1); + } + + public void testLookupOneStepWildcardDestinations() throws Exception { + map.put(d1, v1); + map.put(d2, v2); + map.put(d3, v3); + + assertMapValue("TEST.D1", v1); + assertMapValue("TEST.*", v1); + assertMapValue("*.D1", v1); + assertMapValue("*.*", v1); + + assertMapValue("TEST.BAR.D2", v2); + assertMapValue("TEST.*.D2", v2); + assertMapValue("*.BAR.D2", v2); + assertMapValue("*.*.D2", v2); + + assertMapValue("TEST.BAR.D3", v3); + assertMapValue("TEST.*.D3", v3); + assertMapValue("*.BAR.D3", v3); + assertMapValue("*.*.D3", v3); + + assertMapValue("TEST.BAR.D4", null); + + assertMapValue("TEST.BAR.*", v2, v3); + } + + public void testLookupMultiStepWildcardDestinations() throws Exception { + map.put(d1, v1); + map.put(d2, v2); + map.put(d3, v3); + + List allValues = Arrays.asList(new Object[]{v1, v2, v3}); + + assertMapValue(">", allValues); + assertMapValue("TEST.>", allValues); + assertMapValue("*.>", allValues); + assertMapValue("TEST.*.>", allValues); + assertMapValue("TEST.*.*.>", v2, v3); + + assertMapValue("FOO.>", null); + } + + public void testStoreWildcardWithOneStepPath() throws Exception { + put("TEST.*", v1); + put("TEST.D1", v2); + put("TEST.BAR.*", v2); + put("TEST.BAR.D3", v3); + + assertMapValue("FOO", null); + assertMapValue("TEST.FOO", v1); + assertMapValue("TEST.D1", v1, v2); + + assertMapValue("TEST.FOO.FOO", null); + assertMapValue("TEST.BAR.FOO", v2); + assertMapValue("TEST.BAR.D3", v2, v3); + + assertMapValue("TEST.*", v1, v2); + assertMapValue("*.D1", v1, v2); + assertMapValue("*.*", v1, v2); + assertMapValue("TEST.*.*", v2, v3); + assertMapValue("TEST.BAR.*", v2, v3); + assertMapValue("*.*.*", v2, v3); + assertMapValue("*.BAR.*", v2, v3); + assertMapValue("*.BAR.D3", v2, v3); + assertMapValue("*.*.D3", v2, v3); + } + + public void testStoreWildcardInMiddleOfPath() throws Exception { + put("TEST.*", v1); + put("TEST.D1", v2); + put("TEST.BAR.*", v2); + put("TEST.XYZ.D3", v3); + put("TEST.XYZ.D4", v4); + put("TEST.BAR.D3", v5); + put("TEST.*.D2", v6); + + assertMapValue("TEST.*.D3", v2, v3, v5); + assertMapValue("TEST.*.D4", v2, v4); + + assertMapValue("TEST.*", v1, v2); + assertMapValue("TEST.*.*", v2, v3, v4, v5, v6); + assertMapValue("TEST.*.>", v1, v2, v3, v4, v5, v6); + assertMapValue("TEST.>", v1, v2, v3, v4, v5, v6); + assertMapValue("TEST.>.>", v1, v2, v3, v4, v5, v6); + assertMapValue("*.*.D3", v2, v3, v5); + assertMapValue("TEST.BAR.*", v2, v5, v6); + + assertMapValue("TEST.BAR.D2", v2, v6); + assertMapValue("TEST.*.D2", v2, v6); + assertMapValue("TEST.BAR.*", v2, v5, v6); + } + + public void testDoubleWildcardDoesNotMatchLongerPattern() throws Exception { + put("TEST.*", v1); + put("TEST.BAR.D3", v2); + + assertMapValue("*.*.D3", v2); + } - assertMapValue("*.D1", v1); - } + public void testWildcardAtEndOfPathAndAtBeginningOfSearch() throws Exception { + put("TEST.*", v1); - public void testAnyPathWildcardInMap() throws Exception { - put("TEST.FOO.>", v1); + assertMapValue("*.D1", v1); + } - assertMapValue("TEST.FOO.BAR.WHANOT.A.B.C", v1); - assertMapValue("TEST.FOO.BAR.WHANOT", v1); - assertMapValue("TEST.FOO.BAR", v1); + public void testAnyPathWildcardInMap() throws Exception { + put("TEST.FOO.>", v1); - assertMapValue("TEST.*.*", v1); - assertMapValue("TEST.BAR", null); + assertMapValue("TEST.FOO.BAR.WHANOT.A.B.C", v1); + assertMapValue("TEST.FOO.BAR.WHANOT", v1); + assertMapValue("TEST.FOO.BAR", v1); - assertMapValue("TEST.FOO", v1); - } + assertMapValue("TEST.*.*", v1); + assertMapValue("TEST.BAR", null); - public void testSimpleAddRemove() throws Exception { - put("TEST.D1", v2); + assertMapValue("TEST.FOO", v1); + } - assertEquals("Root child count", 1, map.getTopicRootChildCount()); + public void testSimpleAddRemove() throws Exception { + put("TEST.D1", v2); - assertMapValue("TEST.D1", v2); + assertEquals("Root child count", 1, map.getTopicRootChildCount()); - remove("TEST.D1", v2); + assertMapValue("TEST.D1", v2); - assertEquals("Root child count", 0, map.getTopicRootChildCount()); - assertMapValue("TEST.D1", null); - } + remove("TEST.D1", v2); - public void testMQTTMappedWildcards() throws Exception { - put("TopicA", v1); - put(".TopicA", v2); - put("TopicA.", v3); - put(".", v4); - put("..TopicA", v5); - put("..", v6); + assertEquals("Root child count", 0, map.getTopicRootChildCount()); + assertMapValue("TEST.D1", null); + } - // test wildcard patterns "#", "+", "+/#", "/+", "+/", "+/+", "+/+/", "+/+/+" - assertMapValue(">", v1, v2, v3, v4, v5, v6); - assertMapValue("*", v1); - assertMapValue("*.>", v1, v2, v3, v4, v5, v6); - assertMapValue(".*", v2, v4); - assertMapValue("*.", v3, v4); - assertMapValue("*.*", v2, v3, v4); - assertMapValue("*.*.", v6); - assertMapValue("*.*.*", v5, v6); - } + public void testMQTTMappedWildcards() throws Exception { + put("TopicA", v1); + put(".TopicA", v2); + put("TopicA.", v3); + put(".", v4); + put("..TopicA", v5); + put("..", v6); - public void testStoreAndLookupAllWildcards() throws Exception { - loadSample2(); - - assertSample2(); - - // lets remove everything and add it back - remove("TEST.FOO", v1); - - assertMapValue("TEST.FOO", v2, v3, v4); - assertMapValue("TEST.*", v2, v3, v4, v6); - assertMapValue("*.*", v2, v3, v4, v6); + // test wildcard patterns "#", "+", "+/#", "/+", "+/", "+/+", "+/+/", "+/+/+" + assertMapValue(">", v1, v2, v3, v4, v5, v6); + assertMapValue("*", v1); + assertMapValue("*.>", v1, v2, v3, v4, v5, v6); + assertMapValue(".*", v2, v4); + assertMapValue("*.", v3, v4); + assertMapValue("*.*", v2, v3, v4); + assertMapValue("*.*.", v6); + assertMapValue("*.*.*", v5, v6); + } - remove("TEST.XYZ", v6); + public void testStoreAndLookupAllWildcards() throws Exception { + loadSample2(); + + assertSample2(); + + // lets remove everything and add it back + remove("TEST.FOO", v1); + + assertMapValue("TEST.FOO", v2, v3, v4); + assertMapValue("TEST.*", v2, v3, v4, v6); + assertMapValue("*.*", v2, v3, v4, v6); - assertMapValue("TEST.*", v2, v3, v4); - assertMapValue("*.*", v2, v3, v4); + remove("TEST.XYZ", v6); - remove("TEST.*", v2); + assertMapValue("TEST.*", v2, v3, v4); + assertMapValue("*.*", v2, v3, v4); - assertMapValue("TEST.*", v3, v4); - assertMapValue("*.*", v3, v4); + remove("TEST.*", v2); - remove(">", v4); + assertMapValue("TEST.*", v3, v4); + assertMapValue("*.*", v3, v4); - assertMapValue("TEST.*", v3); - assertMapValue("*.*", v3); + remove(">", v4); - remove("TEST.>", v3); - remove("TEST.FOO.BAR", v5); + assertMapValue("TEST.*", v3); + assertMapValue("*.*", v3); - assertMapValue("FOO", null); - assertMapValue("TEST.FOO", null); - assertMapValue("TEST.D1", null); + remove("TEST.>", v3); + remove("TEST.FOO.BAR", v5); - assertMapValue("TEST.FOO.FOO", null); - assertMapValue("TEST.BAR.FOO", null); - assertMapValue("TEST.FOO.BAR", null); - assertMapValue("TEST.BAR.D3", null); + assertMapValue("FOO", null); + assertMapValue("TEST.FOO", null); + assertMapValue("TEST.D1", null); - assertMapValue("TEST.*", null); - assertMapValue("*.*", null); - assertMapValue("*.D1", null); - assertMapValue("TEST.*.*", null); - assertMapValue("TEST.BAR.*", null); + assertMapValue("TEST.FOO.FOO", null); + assertMapValue("TEST.BAR.FOO", null); + assertMapValue("TEST.FOO.BAR", null); + assertMapValue("TEST.BAR.D3", null); - loadSample2(); + assertMapValue("TEST.*", null); + assertMapValue("*.*", null); + assertMapValue("*.D1", null); + assertMapValue("TEST.*.*", null); + assertMapValue("TEST.BAR.*", null); - assertSample2(); + loadSample2(); - remove(">", v4); - remove("TEST.*", v2); + assertSample2(); - assertMapValue("FOO", null); - assertMapValue("TEST.FOO", v1, v3); - assertMapValue("TEST.D1", v3); - - assertMapValue("TEST.FOO.FOO", v3); - assertMapValue("TEST.BAR.FOO", v3); - assertMapValue("TEST.FOO.BAR", v3, v5); - assertMapValue("TEST.BAR.D3", v3); - - assertMapValue("TEST.*", v1, v3, v6); - assertMapValue("*.*", v1, v3, v6); - assertMapValue("*.D1", v3); - assertMapValue("TEST.*.*", v3, v5); - assertMapValue("TEST.BAR.*", v3); - } - - public void testAddAndRemove() throws Exception { - - put("FOO.A", v1); - assertMapValue("FOO.>", v1); - - put("FOO.B", v2); - assertMapValue("FOO.>", v1, v2); - - map.removeAll(createDestination("FOO.A")); - - assertMapValue("FOO.>", v2); - } - - protected void loadSample2() { - put("TEST.FOO", v1); - put("TEST.*", v2); - put("TEST.>", v3); - put(">", v4); - put("TEST.FOO.BAR", v5); - put("TEST.XYZ", v6); - } - - protected void assertSample2() { - assertMapValue("FOO", v4); - assertMapValue("TEST.FOO", v1, v2, v3, v4); - assertMapValue("TEST.D1", v2, v3, v4); - - assertMapValue("TEST.FOO.FOO", v3, v4); - assertMapValue("TEST.BAR.FOO", v3, v4); - assertMapValue("TEST.FOO.BAR", v3, v4, v5); - assertMapValue("TEST.BAR.D3", v3, v4); - - assertMapValue("TEST.*", v1, v2, v3, v4, v6); - assertMapValue("*.*", v1, v2, v3, v4, v6); - assertMapValue("*.D1", v2, v3, v4); - assertMapValue("TEST.*.*", v3, v4, v5); - assertMapValue("TEST.BAR.*", v3, v4); - } - - protected void put(String name, Object value) { - map.put(createDestination(name), value); - } - - protected void remove(String name, Object value) { - ActiveMQDestination destination = createDestination(name); - map.remove(destination, value); - } - - protected void assertMapValue(String destinationName, Object expected) { - ActiveMQDestination destination = createDestination(destinationName); - assertMapValue(destination, expected); - } - - protected void assertMapValue(String destinationName, Object expected1, Object expected2) { - assertMapValue(destinationName, Arrays.asList(new Object[] {expected1, expected2})); - } - - protected void assertMapValue(String destinationName, Object expected1, Object expected2, Object expected3) { - assertMapValue(destinationName, Arrays.asList(new Object[] {expected1, expected2, expected3})); - } - - protected void assertMapValue(String destinationName, Object expected1, Object expected2, Object expected3, Object expected4) { - assertMapValue(destinationName, Arrays.asList(new Object[] {expected1, expected2, expected3, expected4})); - } - - protected void assertMapValue(String destinationName, Object expected1, Object expected2, Object expected3, Object expected4, Object expected5) { - assertMapValue(destinationName, Arrays.asList(new Object[] {expected1, expected2, expected3, expected4, expected5})); - } - - protected void assertMapValue(String destinationName, Object expected1, Object expected2, Object expected3, Object expected4, Object expected5, Object expected6) { - assertMapValue(destinationName, Arrays.asList(new Object[] {expected1, expected2, expected3, expected4, expected5, expected6})); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - protected void assertMapValue(ActiveMQDestination destination, Object expected) { - List expectedList = null; - if (expected == null) { - expectedList = Collections.EMPTY_LIST; - } else if (expected instanceof List) { - expectedList = (List)expected; - } else { - expectedList = new ArrayList(); - expectedList.add(expected); - } - Collections.sort(expectedList); - Set actualSet = map.get(destination); - List actual = new ArrayList(actualSet); - Collections.sort(actual); - assertEquals("map value for destinationName: " + destination, expectedList, actual); - } - - protected ActiveMQDestination createDestination(String name) { - return new ActiveMQTopic(name); - } + remove(">", v4); + remove("TEST.*", v2); + + assertMapValue("FOO", null); + assertMapValue("TEST.FOO", v1, v3); + assertMapValue("TEST.D1", v3); + + assertMapValue("TEST.FOO.FOO", v3); + assertMapValue("TEST.BAR.FOO", v3); + assertMapValue("TEST.FOO.BAR", v3, v5); + assertMapValue("TEST.BAR.D3", v3); + + assertMapValue("TEST.*", v1, v3, v6); + assertMapValue("*.*", v1, v3, v6); + assertMapValue("*.D1", v3); + assertMapValue("TEST.*.*", v3, v5); + assertMapValue("TEST.BAR.*", v3); + } + + public void testAddAndRemove() throws Exception { + + put("FOO.A", v1); + assertMapValue("FOO.>", v1); + + put("FOO.B", v2); + assertMapValue("FOO.>", v1, v2); + + map.removeAll(createDestination("FOO.A")); + + assertMapValue("FOO.>", v2); + } + + protected void loadSample2() { + put("TEST.FOO", v1); + put("TEST.*", v2); + put("TEST.>", v3); + put(">", v4); + put("TEST.FOO.BAR", v5); + put("TEST.XYZ", v6); + } + + protected void assertSample2() { + assertMapValue("FOO", v4); + assertMapValue("TEST.FOO", v1, v2, v3, v4); + assertMapValue("TEST.D1", v2, v3, v4); + + assertMapValue("TEST.FOO.FOO", v3, v4); + assertMapValue("TEST.BAR.FOO", v3, v4); + assertMapValue("TEST.FOO.BAR", v3, v4, v5); + assertMapValue("TEST.BAR.D3", v3, v4); + + assertMapValue("TEST.*", v1, v2, v3, v4, v6); + assertMapValue("*.*", v1, v2, v3, v4, v6); + assertMapValue("*.D1", v2, v3, v4); + assertMapValue("TEST.*.*", v3, v4, v5); + assertMapValue("TEST.BAR.*", v3, v4); + } + + protected void put(String name, Object value) { + map.put(createDestination(name), value); + } + + protected void remove(String name, Object value) { + ActiveMQDestination destination = createDestination(name); + map.remove(destination, value); + } + + protected void assertMapValue(String destinationName, Object expected) { + ActiveMQDestination destination = createDestination(destinationName); + assertMapValue(destination, expected); + } + + protected void assertMapValue(String destinationName, Object expected1, Object expected2) { + assertMapValue(destinationName, Arrays.asList(new Object[]{expected1, expected2})); + } + + protected void assertMapValue(String destinationName, Object expected1, Object expected2, Object expected3) { + assertMapValue(destinationName, Arrays.asList(new Object[]{expected1, expected2, expected3})); + } + + protected void assertMapValue(String destinationName, + Object expected1, + Object expected2, + Object expected3, + Object expected4) { + assertMapValue(destinationName, Arrays.asList(new Object[]{expected1, expected2, expected3, expected4})); + } + + protected void assertMapValue(String destinationName, + Object expected1, + Object expected2, + Object expected3, + Object expected4, + Object expected5) { + assertMapValue(destinationName, Arrays.asList(new Object[]{expected1, expected2, expected3, expected4, expected5})); + } + + protected void assertMapValue(String destinationName, + Object expected1, + Object expected2, + Object expected3, + Object expected4, + Object expected5, + Object expected6) { + assertMapValue(destinationName, Arrays.asList(new Object[]{expected1, expected2, expected3, expected4, expected5, expected6})); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + protected void assertMapValue(ActiveMQDestination destination, Object expected) { + List expectedList = null; + if (expected == null) { + expectedList = Collections.EMPTY_LIST; + } + else if (expected instanceof List) { + expectedList = (List) expected; + } + else { + expectedList = new ArrayList(); + expectedList.add(expected); + } + Collections.sort(expectedList); + Set actualSet = map.get(destination); + List actual = new ArrayList(actualSet); + Collections.sort(actual); + assertEquals("map value for destinationName: " + destination, expectedList, actual); + } + + protected ActiveMQDestination createDestination(String name) { + return new ActiveMQTopic(name); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationPathTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationPathTest.java index 397cccaadf..f3972a7035 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationPathTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationPathTest.java @@ -20,17 +20,17 @@ import org.apache.activemq.test.TestSupport; public class DestinationPathTest extends TestSupport { - public void testPathParse() { - assertParse("FOO", new String[]{"FOO"}); - assertParse("FOO.BAR", new String[]{"FOO", "BAR"}); - assertParse("FOO.*", new String[]{"FOO", "*"}); - assertParse("FOO.>", new String[]{"FOO", ">"}); - assertParse("FOO.BAR.XYZ", new String[]{"FOO", "BAR", "XYZ"}); - assertParse("FOO.BAR.", new String[]{"FOO", "BAR", ""}); - } + public void testPathParse() { + assertParse("FOO", new String[]{"FOO"}); + assertParse("FOO.BAR", new String[]{"FOO", "BAR"}); + assertParse("FOO.*", new String[]{"FOO", "*"}); + assertParse("FOO.>", new String[]{"FOO", ">"}); + assertParse("FOO.BAR.XYZ", new String[]{"FOO", "BAR", "XYZ"}); + assertParse("FOO.BAR.", new String[]{"FOO", "BAR", ""}); + } - protected void assertParse(String subject, String[] expected) { - String[] path = DestinationPath.getDestinationPaths(subject); - assertArrayEqual(subject, expected, path); - } + protected void assertParse(String subject, String[] expected) { + String[] path = DestinationPath.getDestinationPaths(subject); + assertArrayEqual(subject, expected, path); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DummyPolicy.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DummyPolicy.java index 3dde44fdea..e3cf9e8733 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DummyPolicy.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DummyPolicy.java @@ -20,21 +20,19 @@ import java.util.List; /** * Represents a destination based policy - * - * */ public class DummyPolicy extends DestinationMap { - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - protected Class getEntryClass() { - return DummyPolicyEntry.class; - } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + protected Class getEntryClass() { + return DummyPolicyEntry.class; + } - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public void setEntries(List entries) { - super.setEntries(entries); - } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void setEntries(List entries) { + super.setEntries(entries); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DummyPolicyEntry.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DummyPolicyEntry.java index d27158002f..b15ff38f12 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DummyPolicyEntry.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DummyPolicyEntry.java @@ -16,29 +16,28 @@ */ package org.apache.activemq.filter; - /** - * - * + * + * */ public class DummyPolicyEntry extends DestinationMapEntry { - private String description; + private String description; - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public Comparable getValue() { - return description; - } + public Comparable getValue() { + return description; + } - protected String getValuePropertyName() { - return "description"; - } + protected String getValuePropertyName() { + return "description"; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DummyPolicyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DummyPolicyTest.java index 5d71c54741..0b94174fa8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DummyPolicyTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DummyPolicyTest.java @@ -28,17 +28,17 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; */ public class DummyPolicyTest extends SpringTestSupport { - public void testPolicy() throws Exception { - DummyPolicy policy = (DummyPolicy)getBean("policy"); + public void testPolicy() throws Exception { + DummyPolicy policy = (DummyPolicy) getBean("policy"); - Set set = policy.get(new ActiveMQTopic("FOO.BAR")); + Set set = policy.get(new ActiveMQTopic("FOO.BAR")); - assertSetEquals("FOO.BAR set", new Object[] {"Edam", "Cheddar"}, set); - } + assertSetEquals("FOO.BAR set", new Object[]{"Edam", "Cheddar"}, set); + } - @Override - protected AbstractApplicationContext createApplicationContext() { - return new ClassPathXmlApplicationContext("org/apache/activemq/filter/dummyPolicy.xml"); - } + @Override + protected AbstractApplicationContext createApplicationContext() { + return new ClassPathXmlApplicationContext("org/apache/activemq/filter/dummyPolicy.xml"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jmx/JmxCreateNCTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jmx/JmxCreateNCTest.java index e96c5967ad..450ef33178 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jmx/JmxCreateNCTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jmx/JmxCreateNCTest.java @@ -34,34 +34,32 @@ import static org.junit.Assert.assertNotNull; */ public class JmxCreateNCTest { - private static final String BROKER_NAME = "jmx-broker"; + private static final String BROKER_NAME = "jmx-broker"; - @Test - public void testBridgeRegistration() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName(BROKER_NAME); - broker.setUseJmx(true); // explicitly set this so no funny issues - broker.start(); - broker.waitUntilStarted(); + @Test + public void testBridgeRegistration() throws Exception { + BrokerService broker = new BrokerService(); + broker.setBrokerName(BROKER_NAME); + broker.setUseJmx(true); // explicitly set this so no funny issues + broker.start(); + broker.waitUntilStarted(); - // now create network connector over JMX - ObjectName brokerObjectName = new ObjectName("org.apache.activemq:type=Broker,brokerName=" + BROKER_NAME); - BrokerViewMBean proxy = (BrokerViewMBean) broker.getManagementContext().newProxyInstance(brokerObjectName, - BrokerViewMBean.class, true); + // now create network connector over JMX + ObjectName brokerObjectName = new ObjectName("org.apache.activemq:type=Broker,brokerName=" + BROKER_NAME); + BrokerViewMBean proxy = (BrokerViewMBean) broker.getManagementContext().newProxyInstance(brokerObjectName, BrokerViewMBean.class, true); - assertNotNull("We could not retrieve the broker from JMX", proxy); + assertNotNull("We could not retrieve the broker from JMX", proxy); - // let's add the NC - String connectoName = proxy.addNetworkConnector("static:(tcp://localhost:61617)"); - assertEquals("NC", connectoName); + // let's add the NC + String connectoName = proxy.addNetworkConnector("static:(tcp://localhost:61617)"); + assertEquals("NC", connectoName); - // Make sure we can retrieve the NC through JMX - ObjectName networkConnectorObjectName = new ObjectName("org.apache.activemq:type=Broker,brokerName=" + BROKER_NAME + - ",connector=networkConnectors,networkConnectorName=" + connectoName); - NetworkConnectorViewMBean nc = (NetworkConnectorViewMBean) broker.getManagementContext().newProxyInstance(networkConnectorObjectName, - NetworkConnectorViewMBean.class, true); + // Make sure we can retrieve the NC through JMX + ObjectName networkConnectorObjectName = new ObjectName("org.apache.activemq:type=Broker,brokerName=" + BROKER_NAME + + ",connector=networkConnectors,networkConnectorName=" + connectoName); + NetworkConnectorViewMBean nc = (NetworkConnectorViewMBean) broker.getManagementContext().newProxyInstance(networkConnectorObjectName, NetworkConnectorViewMBean.class, true); - assertNotNull(nc); - assertEquals("NC", nc.getName()); - } + assertNotNull(nc); + assertEquals("NC", nc.getName()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jmx/OpenTypeSupportTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jmx/OpenTypeSupportTest.java index 7306dfd6f8..63d1b7102a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jmx/OpenTypeSupportTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jmx/OpenTypeSupportTest.java @@ -25,6 +25,7 @@ import javax.jms.Session; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import javax.management.openmbean.CompositeData; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.jmx.CompositeDataConstants; @@ -37,79 +38,81 @@ import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import static org.junit.Assert.assertEquals; public class OpenTypeSupportTest { - private static final Logger LOG = LoggerFactory.getLogger(OpenTypeSupportTest.class); - private static BrokerService brokerService; - private static String TESTQUEUE = "testQueue"; - private static ActiveMQConnectionFactory connectionFactory; - private static String BYTESMESSAGE_TEXT = "This is a short text"; - private static String BROKER_ADDRESS = "tcp://localhost:0"; - private static ActiveMQQueue queue = new ActiveMQQueue(TESTQUEUE); + private static final Logger LOG = LoggerFactory.getLogger(OpenTypeSupportTest.class); - private String connectionUri; + private static BrokerService brokerService; + private static String TESTQUEUE = "testQueue"; + private static ActiveMQConnectionFactory connectionFactory; + private static String BYTESMESSAGE_TEXT = "This is a short text"; + private static String BROKER_ADDRESS = "tcp://localhost:0"; + private static ActiveMQQueue queue = new ActiveMQQueue(TESTQUEUE); - @Before - public void setUp() throws Exception { - brokerService = new BrokerService(); - brokerService.setPersistent(false); - brokerService.setUseJmx(true); - connectionUri = brokerService.addConnector(BROKER_ADDRESS).getPublishableConnectString(); - brokerService.start(); - connectionFactory = new ActiveMQConnectionFactory(connectionUri); - sendMessage(); - } + private String connectionUri; - @After - public void tearDown() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - } + @Before + public void setUp() throws Exception { + brokerService = new BrokerService(); + brokerService.setPersistent(false); + brokerService.setUseJmx(true); + connectionUri = brokerService.addConnector(BROKER_ADDRESS).getPublishableConnectString(); + brokerService.start(); + connectionFactory = new ActiveMQConnectionFactory(connectionUri); + sendMessage(); + } - private static void sendMessage() throws JMSException { - Connection conn = connectionFactory.createConnection(); - try { - conn.start(); - Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination queue = session.createQueue(TESTQUEUE); - BytesMessage toSend = session.createBytesMessage(); - toSend.writeBytes(BYTESMESSAGE_TEXT.getBytes()); - MessageProducer producer = session.createProducer(queue); - producer.send(queue, toSend); - } finally { - conn.close(); - } - } + @After + public void tearDown() throws Exception { + brokerService.stop(); + brokerService.waitUntilStopped(); + } - @Test - public void bytesMessagePreview() throws Exception { - QueueViewMBean queue = getProxyToQueueViewMBean(); - assertEquals(extractText(queue.browse()[0]), extractText(queue.browse()[0])); - } + private static void sendMessage() throws JMSException { + Connection conn = connectionFactory.createConnection(); + try { + conn.start(); + Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination queue = session.createQueue(TESTQUEUE); + BytesMessage toSend = session.createBytesMessage(); + toSend.writeBytes(BYTESMESSAGE_TEXT.getBytes()); + MessageProducer producer = session.createProducer(queue); + producer.send(queue, toSend); + } + finally { + conn.close(); + } + } - @Test - public void testBrowseByteMessageFails() throws Exception { - ActiveMQBytesMessage bm = new ActiveMQBytesMessage(); - bm.writeBytes("123456".getBytes()); - Object result = OpenTypeSupport.convert(bm); - LOG.info("result : " + result); - } + @Test + public void bytesMessagePreview() throws Exception { + QueueViewMBean queue = getProxyToQueueViewMBean(); + assertEquals(extractText(queue.browse()[0]), extractText(queue.browse()[0])); + } - private String extractText(CompositeData message) { - Byte content[] = (Byte[]) message.get(CompositeDataConstants.BODY_PREVIEW); - byte out[] = new byte[content.length]; - for (int i = 0; i < content.length; i++) { - out[i] = content[i]; - } - return new String(out); - } + @Test + public void testBrowseByteMessageFails() throws Exception { + ActiveMQBytesMessage bm = new ActiveMQBytesMessage(); + bm.writeBytes("123456".getBytes()); + Object result = OpenTypeSupport.convert(bm); + LOG.info("result : " + result); + } - private QueueViewMBean getProxyToQueueViewMBean() throws MalformedObjectNameException, JMSException { - final ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + queue.getQueueName()); - QueueViewMBean proxy = (QueueViewMBean) - brokerService.getManagementContext().newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); - return proxy; - } + private String extractText(CompositeData message) { + Byte content[] = (Byte[]) message.get(CompositeDataConstants.BODY_PREVIEW); + byte out[] = new byte[content.length]; + for (int i = 0; i < content.length; i++) { + out[i] = content[i]; + } + return new String(out); + } + + private QueueViewMBean getProxyToQueueViewMBean() throws MalformedObjectNameException, JMSException { + final ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + queue.getQueueName()); + QueueViewMBean proxy = (QueueViewMBean) brokerService.getManagementContext().newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); + return proxy; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/ActiveMQInitialContextFactoryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/ActiveMQInitialContextFactoryTest.java index 86e5a43939..9ebd776c66 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/ActiveMQInitialContextFactoryTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/ActiveMQInitialContextFactoryTest.java @@ -23,53 +23,53 @@ import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTopic; /** - * + * */ public class ActiveMQInitialContextFactoryTest extends JNDITestSupport { - public void testConnectionFactoriesArePresent() throws NamingException { - String lookupName = getConnectionFactoryLookupName(); - assertConnectionFactoryPresent(lookupName); - } + public void testConnectionFactoriesArePresent() throws NamingException { + String lookupName = getConnectionFactoryLookupName(); + assertConnectionFactoryPresent(lookupName); + } - public void testDestinationsArePresent() throws NamingException { + public void testDestinationsArePresent() throws NamingException { - // Retrieving destinations context is not yet implemented on the broker. - // For this test, a jndi file properties will be used. + // Retrieving destinations context is not yet implemented on the broker. + // For this test, a jndi file properties will be used. - InitialContext context = new InitialContext(); + InitialContext context = new InitialContext(); - // make sure context is not null - assertTrue("Created context", context != null); + // make sure context is not null + assertTrue("Created context", context != null); - Object topicDestination = context.lookup("MyTopic"); + Object topicDestination = context.lookup("MyTopic"); - // check if MyTopic is an ActiveMQTopic - assertTrue("Should have found a topic but found: " + topicDestination, topicDestination instanceof ActiveMQTopic); + // check if MyTopic is an ActiveMQTopic + assertTrue("Should have found a topic but found: " + topicDestination, topicDestination instanceof ActiveMQTopic); - Object queueDestination = context.lookup("MyQueue"); + Object queueDestination = context.lookup("MyQueue"); - // check if MyQueue is an ActiveMQueue - assertTrue("Should have found a queue but found: " + queueDestination, queueDestination instanceof ActiveMQQueue); + // check if MyQueue is an ActiveMQueue + assertTrue("Should have found a queue but found: " + queueDestination, queueDestination instanceof ActiveMQQueue); - } + } - public void testDynamicallyGrowing() throws Exception { - Object answer = context.lookup("dynamicQueues/FOO.BAR"); - assertTrue("Should have found a queue but found: " + answer, answer instanceof ActiveMQQueue); + public void testDynamicallyGrowing() throws Exception { + Object answer = context.lookup("dynamicQueues/FOO.BAR"); + assertTrue("Should have found a queue but found: " + answer, answer instanceof ActiveMQQueue); - ActiveMQQueue queue = (ActiveMQQueue)answer; - assertEquals("queue name", "FOO.BAR", queue.getPhysicalName()); + ActiveMQQueue queue = (ActiveMQQueue) answer; + assertEquals("queue name", "FOO.BAR", queue.getPhysicalName()); - answer = context.lookup("dynamicTopics/A.B.C"); - assertTrue("Should have found a topic but found: " + answer, answer instanceof ActiveMQTopic); + answer = context.lookup("dynamicTopics/A.B.C"); + assertTrue("Should have found a topic but found: " + answer, answer instanceof ActiveMQTopic); - ActiveMQTopic topic = (ActiveMQTopic)answer; - assertEquals("topic name", "A.B.C", topic.getPhysicalName()); + ActiveMQTopic topic = (ActiveMQTopic) answer; + assertEquals("topic name", "A.B.C", topic.getPhysicalName()); - } + } - protected String getConnectionFactoryLookupName() { - return "ConnectionFactory"; - } + protected String getConnectionFactoryLookupName() { + return "ConnectionFactory"; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/ActiveMQWASInitialContextFactoryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/ActiveMQWASInitialContextFactoryTest.java index f9ce5b1903..2045534226 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/ActiveMQWASInitialContextFactoryTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/ActiveMQWASInitialContextFactoryTest.java @@ -22,22 +22,22 @@ import javax.naming.Context; public class ActiveMQWASInitialContextFactoryTest extends JNDITestSupport { - @SuppressWarnings("unchecked") - public void testTransformEnvironment() { - Hashtable originalEnvironment = new Hashtable(); - originalEnvironment.put("java.naming.connectionFactoryNames", "ConnectionFactory"); - originalEnvironment.put("java.naming.topic.jms.systemMessageTopic", "jms/systemMessageTopic"); - originalEnvironment.put(Context.PROVIDER_URL, "tcp://localhost:61616;tcp://localhost:61617"); - originalEnvironment.put("non-string", Integer.valueOf(43)); - originalEnvironment.put("java.naming.queue", "jms/systemMessageQueue"); + @SuppressWarnings("unchecked") + public void testTransformEnvironment() { + Hashtable originalEnvironment = new Hashtable(); + originalEnvironment.put("java.naming.connectionFactoryNames", "ConnectionFactory"); + originalEnvironment.put("java.naming.topic.jms.systemMessageTopic", "jms/systemMessageTopic"); + originalEnvironment.put(Context.PROVIDER_URL, "tcp://localhost:61616;tcp://localhost:61617"); + originalEnvironment.put("non-string", Integer.valueOf(43)); + originalEnvironment.put("java.naming.queue", "jms/systemMessageQueue"); - Hashtable transformedEnvironment = new ActiveMQWASInitialContextFactory().transformEnvironment(originalEnvironment); - assertEquals("ConnectionFactory", "ConnectionFactory", transformedEnvironment.get("connectionFactoryNames")); - assertEquals("topic.jm", "jms/systemMessageTopic", transformedEnvironment.get("topic.jms/systemMessageTopic")); - assertEquals("java.naming.provider.url", "tcp://localhost:61616,tcp://localhost:61617", transformedEnvironment.get("java.naming.provider.url")); - assertNull("non-string", transformedEnvironment.get("non-string")); + Hashtable transformedEnvironment = new ActiveMQWASInitialContextFactory().transformEnvironment(originalEnvironment); + assertEquals("ConnectionFactory", "ConnectionFactory", transformedEnvironment.get("connectionFactoryNames")); + assertEquals("topic.jm", "jms/systemMessageTopic", transformedEnvironment.get("topic.jms/systemMessageTopic")); + assertEquals("java.naming.provider.url", "tcp://localhost:61616,tcp://localhost:61617", transformedEnvironment.get("java.naming.provider.url")); + assertNull("non-string", transformedEnvironment.get("non-string")); - assertEquals("queue", "jms/systemMessageQueue", transformedEnvironment.get("java.naming.queue")); - } + assertEquals("queue", "jms/systemMessageQueue", transformedEnvironment.get("java.naming.queue")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/CustomConnectionFactoryNameTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/CustomConnectionFactoryNameTest.java index 517735b855..2395974ebb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/CustomConnectionFactoryNameTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/CustomConnectionFactoryNameTest.java @@ -22,35 +22,33 @@ import org.apache.activemq.ActiveMQConnectionFactory; /** * Test case for AMQ-141 - * - * */ public class CustomConnectionFactoryNameTest extends ActiveMQInitialContextFactoryTest { - @Override - public void testConnectionFactoriesArePresent() throws NamingException { - super.testConnectionFactoriesArePresent(); - assertConnectionFactoryPresent("jms/Connection"); - assertConnectionFactoryPresent("jms/DURABLE_SUB_CONNECTION_FACTORY"); - } + @Override + public void testConnectionFactoriesArePresent() throws NamingException { + super.testConnectionFactoriesArePresent(); + assertConnectionFactoryPresent("jms/Connection"); + assertConnectionFactoryPresent("jms/DURABLE_SUB_CONNECTION_FACTORY"); + } - public void testConnectionFactoriesAreConfigured() throws NamingException { - super.testConnectionFactoriesArePresent(); - ActiveMQConnectionFactory factory1 = (ActiveMQConnectionFactory) context.lookup("jms/Connection"); - assertNull(factory1.getClientID()); - ActiveMQConnectionFactory factory2 = (ActiveMQConnectionFactory) context.lookup("jms/DURABLE_SUB_CONNECTION_FACTORY"); - assertEquals("testclient", factory2.getClientID()); - } + public void testConnectionFactoriesAreConfigured() throws NamingException { + super.testConnectionFactoriesArePresent(); + ActiveMQConnectionFactory factory1 = (ActiveMQConnectionFactory) context.lookup("jms/Connection"); + assertNull(factory1.getClientID()); + ActiveMQConnectionFactory factory2 = (ActiveMQConnectionFactory) context.lookup("jms/DURABLE_SUB_CONNECTION_FACTORY"); + assertEquals("testclient", factory2.getClientID()); + } - @Override - protected String getConnectionFactoryLookupName() { - return "myConnectionFactory"; - } + @Override + protected String getConnectionFactoryLookupName() { + return "myConnectionFactory"; + } - @Override - protected void configureEnvironment() { - super.configureEnvironment(); - environment.put("connectionFactoryNames", " myConnectionFactory, jms/Connection, jms/DURABLE_SUB_CONNECTION_FACTORY"); - environment.put("connection.jms/DURABLE_SUB_CONNECTION_FACTORY.clientID", "testclient"); - } + @Override + protected void configureEnvironment() { + super.configureEnvironment(); + environment.put("connectionFactoryNames", " myConnectionFactory, jms/Connection, jms/DURABLE_SUB_CONNECTION_FACTORY"); + environment.put("connection.jms/DURABLE_SUB_CONNECTION_FACTORY.clientID", "testclient"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/DestinationNameWithSlashTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/DestinationNameWithSlashTest.java index 6e3e9da76e..8bdf2273d6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/DestinationNameWithSlashTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/DestinationNameWithSlashTest.java @@ -16,21 +16,19 @@ */ package org.apache.activemq.jndi; - /** * Test case for AMQ-140 - * - * */ public class DestinationNameWithSlashTest extends JNDITestSupport { - public void testNameWithSlash() throws Exception { - assertDestinationExists("jms/Queue"); - } + public void testNameWithSlash() throws Exception { + assertDestinationExists("jms/Queue"); - @Override - protected void configureEnvironment() { - super.configureEnvironment(); - environment.put("queue.jms/Queue", "example.myqueue"); - } + } + + @Override + protected void configureEnvironment() { + super.configureEnvironment(); + environment.put("queue.jms/Queue", "example.myqueue"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/InitialContextTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/InitialContextTest.java index 2c983a5a36..5903d3f9d1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/InitialContextTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/InitialContextTest.java @@ -22,76 +22,77 @@ import javax.naming.Context; import javax.naming.InitialContext; import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQXAConnectionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class InitialContextTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(InitialContextTest.class); + private static final Logger LOG = LoggerFactory.getLogger(InitialContextTest.class); - public void testInitialContext() throws Exception { - InitialContext context = new InitialContext(); - assertTrue("Created context", context != null); + public void testInitialContext() throws Exception { + InitialContext context = new InitialContext(); + assertTrue("Created context", context != null); - ActiveMQConnectionFactory connectionFactory = (ActiveMQConnectionFactory)context.lookup("ConnectionFactory"); + ActiveMQConnectionFactory connectionFactory = (ActiveMQConnectionFactory) context.lookup("ConnectionFactory"); - assertTrue("Should have created a ConnectionFactory", connectionFactory != null); + assertTrue("Should have created a ConnectionFactory", connectionFactory != null); - LOG.info("Created with brokerURL: " + connectionFactory.getBrokerURL()); + LOG.info("Created with brokerURL: " + connectionFactory.getBrokerURL()); - } + } - public void testInitialContextHasXA() throws Exception { - InitialContext context = new InitialContext(); - assertTrue("Created context", context != null); + public void testInitialContextHasXA() throws Exception { + InitialContext context = new InitialContext(); + assertTrue("Created context", context != null); - ActiveMQXAConnectionFactory connectionFactory = (ActiveMQXAConnectionFactory)context.lookup("XAConnectionFactory"); + ActiveMQXAConnectionFactory connectionFactory = (ActiveMQXAConnectionFactory) context.lookup("XAConnectionFactory"); - assertTrue("Should have created an XAConnectionFactory", connectionFactory != null); + assertTrue("Should have created an XAConnectionFactory", connectionFactory != null); - LOG.info("Created with brokerURL: " + connectionFactory.getBrokerURL()); + LOG.info("Created with brokerURL: " + connectionFactory.getBrokerURL()); - } + } - public void testUsingStandardJNDIKeys() throws Exception { - Properties properties = new Properties(); - properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); - String expected = "tcp://localhost:65432"; - properties.put(Context.PROVIDER_URL, expected); + public void testUsingStandardJNDIKeys() throws Exception { + Properties properties = new Properties(); + properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); + String expected = "tcp://localhost:65432"; + properties.put(Context.PROVIDER_URL, expected); - InitialContext context = new InitialContext(properties); - assertTrue("Created context", context != null); + InitialContext context = new InitialContext(properties); + assertTrue("Created context", context != null); - ActiveMQConnectionFactory connectionFactory = (ActiveMQConnectionFactory)context.lookup("ConnectionFactory"); + ActiveMQConnectionFactory connectionFactory = (ActiveMQConnectionFactory) context.lookup("ConnectionFactory"); - assertTrue("Should have created a ConnectionFactory", connectionFactory != null); + assertTrue("Should have created a ConnectionFactory", connectionFactory != null); - assertEquals("the brokerURL should match", expected, connectionFactory.getBrokerURL()); - } + assertEquals("the brokerURL should match", expected, connectionFactory.getBrokerURL()); + } - public void testConnectionFactoryPolicyConfig() throws Exception { + public void testConnectionFactoryPolicyConfig() throws Exception { - Properties properties = new Properties(); - properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); - properties.put(Context.PROVIDER_URL, "tcp://localhost:65432"); - properties.put("prefetchPolicy.queuePrefetch", "777"); - properties.put("redeliveryPolicy.maximumRedeliveries", "15"); - properties.put("redeliveryPolicy.backOffMultiplier", "32"); + Properties properties = new Properties(); + properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); + properties.put(Context.PROVIDER_URL, "tcp://localhost:65432"); + properties.put("prefetchPolicy.queuePrefetch", "777"); + properties.put("redeliveryPolicy.maximumRedeliveries", "15"); + properties.put("redeliveryPolicy.backOffMultiplier", "32"); - InitialContext context = new InitialContext(properties); - assertTrue("Created context", context != null); + InitialContext context = new InitialContext(properties); + assertTrue("Created context", context != null); - ActiveMQConnectionFactory connectionFactory = (ActiveMQConnectionFactory)context.lookup("ConnectionFactory"); + ActiveMQConnectionFactory connectionFactory = (ActiveMQConnectionFactory) context.lookup("ConnectionFactory"); - assertTrue("Should have created a ConnectionFactory", connectionFactory != null); + assertTrue("Should have created a ConnectionFactory", connectionFactory != null); - assertEquals(777, connectionFactory.getPrefetchPolicy().getQueuePrefetch()); - assertEquals(15, connectionFactory.getRedeliveryPolicy().getMaximumRedeliveries()); - assertEquals(32d, connectionFactory.getRedeliveryPolicy().getBackOffMultiplier()); - } + assertEquals(777, connectionFactory.getPrefetchPolicy().getQueuePrefetch()); + assertEquals(15, connectionFactory.getRedeliveryPolicy().getMaximumRedeliveries()); + assertEquals(32d, connectionFactory.getRedeliveryPolicy().getBackOffMultiplier()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/JNDITestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/JNDITestSupport.java index 13adbc458d..f1bb0cb34b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/JNDITestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/JNDITestSupport.java @@ -36,68 +36,65 @@ import org.apache.activemq.ActiveMQConnectionFactory; */ public abstract class JNDITestSupport extends TestCase { - private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory - .getLog(JNDITestSupport.class); + private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(JNDITestSupport.class); - protected Hashtable environment = new Hashtable(); - protected Context context; + protected Hashtable environment = new Hashtable(); + protected Context context; - protected void assertConnectionFactoryPresent(String lookupName) throws NamingException { - Object connectionFactory = context.lookup(lookupName); + protected void assertConnectionFactoryPresent(String lookupName) throws NamingException { + Object connectionFactory = context.lookup(lookupName); - assertTrue("Should have created a ConnectionFactory for key: " + lookupName - + " but got: " + connectionFactory, connectionFactory instanceof ConnectionFactory); - } + assertTrue("Should have created a ConnectionFactory for key: " + lookupName + " but got: " + connectionFactory, connectionFactory instanceof ConnectionFactory); + } - protected void assertBinding(Binding binding) throws NamingException { - Object object = binding.getObject(); - assertTrue("Should have got a child context but got: " + object, object instanceof Context); + protected void assertBinding(Binding binding) throws NamingException { + Object object = binding.getObject(); + assertTrue("Should have got a child context but got: " + object, object instanceof Context); - Context childContext = (Context) object; - NamingEnumeration iter = childContext.listBindings(""); - while (iter.hasMore()) { - Binding destinationBinding = iter.next(); - LOG.info("Found destination: " + destinationBinding.getName()); - Object destination = destinationBinding.getObject(); - assertTrue("Should have a Destination but got: " + destination, destination instanceof Destination); - } - } + Context childContext = (Context) object; + NamingEnumeration iter = childContext.listBindings(""); + while (iter.hasMore()) { + Binding destinationBinding = iter.next(); + LOG.info("Found destination: " + destinationBinding.getName()); + Object destination = destinationBinding.getObject(); + assertTrue("Should have a Destination but got: " + destination, destination instanceof Destination); + } + } - @Override - protected void setUp() throws Exception { - super.setUp(); + @Override + protected void setUp() throws Exception { + super.setUp(); - configureEnvironment(); + configureEnvironment(); - InitialContextFactory factory = new ActiveMQInitialContextFactory(); - context = factory.getInitialContext(environment); - assertTrue("No context created", context != null); - } + InitialContextFactory factory = new ActiveMQInitialContextFactory(); + context = factory.getInitialContext(environment); + assertTrue("No context created", context != null); + } - /** - * Stops all existing ActiveMQConnectionFactory in Context. - * - * @throws javax.naming.NamingException - */ - @Override - protected void tearDown() throws NamingException, JMSException { - NamingEnumeration iter = context.listBindings(""); - while (iter.hasMore()) { - Binding binding = iter.next(); - Object connFactory = binding.getObject(); - if (connFactory instanceof ActiveMQConnectionFactory) { - // ((ActiveMQConnectionFactory) connFactory).stop(); - } - } - } + /** + * Stops all existing ActiveMQConnectionFactory in Context. + * + * @throws javax.naming.NamingException + */ + @Override + protected void tearDown() throws NamingException, JMSException { + NamingEnumeration iter = context.listBindings(""); + while (iter.hasMore()) { + Binding binding = iter.next(); + Object connFactory = binding.getObject(); + if (connFactory instanceof ActiveMQConnectionFactory) { + // ((ActiveMQConnectionFactory) connFactory).stop(); + } + } + } - protected void configureEnvironment() { - environment.put("brokerURL", "vm://localhost"); - } + protected void configureEnvironment() { + environment.put("brokerURL", "vm://localhost"); + } - protected void assertDestinationExists(String name) throws NamingException { - Object object = context.lookup(name); - assertTrue("Should have received a Destination for name: " + name + " but instead found: " + object, - object instanceof Destination); - } + protected void assertDestinationExists(String name) throws NamingException { + Object object = context.lookup(name); + assertTrue("Should have received a Destination for name: " + name + " but instead found: " + object, object instanceof Destination); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/ObjectFactoryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/ObjectFactoryTest.java index c3891448b1..d322278170 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/ObjectFactoryTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/ObjectFactoryTest.java @@ -24,66 +24,66 @@ import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; public class ObjectFactoryTest extends CombinationTestSupport { - public void testConnectionFactory() throws Exception { - // Create sample connection factory - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(); - factory.setDispatchAsync(true); - factory.setBrokerURL("vm://test"); - factory.setClientID("test"); - factory.setCopyMessageOnSend(false); - factory.setDisableTimeStampsByDefault(true); - factory.setObjectMessageSerializationDefered(true); - factory.setOptimizedMessageDispatch(false); - factory.setPassword("pass"); - factory.setUseAsyncSend(true); - factory.setUseCompression(true); - factory.setUseRetroactiveConsumer(true); - factory.setUserName("user"); - factory.getPrefetchPolicy().setQueuePrefetch(777); - factory.getRedeliveryPolicy().setMaximumRedeliveries(15); - factory.getRedeliveryPolicy().setBackOffMultiplier((short) 32); - - // Create reference - Reference ref = JNDIReferenceFactory.createReference(factory.getClass().getName(), factory); + public void testConnectionFactory() throws Exception { + // Create sample connection factory + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(); + factory.setDispatchAsync(true); + factory.setBrokerURL("vm://test"); + factory.setClientID("test"); + factory.setCopyMessageOnSend(false); + factory.setDisableTimeStampsByDefault(true); + factory.setObjectMessageSerializationDefered(true); + factory.setOptimizedMessageDispatch(false); + factory.setPassword("pass"); + factory.setUseAsyncSend(true); + factory.setUseCompression(true); + factory.setUseRetroactiveConsumer(true); + factory.setUserName("user"); + factory.getPrefetchPolicy().setQueuePrefetch(777); + factory.getRedeliveryPolicy().setMaximumRedeliveries(15); + factory.getRedeliveryPolicy().setBackOffMultiplier((short) 32); - // Get object created based on reference - ActiveMQConnectionFactory temp; - JNDIReferenceFactory refFactory = new JNDIReferenceFactory(); - temp = (ActiveMQConnectionFactory)refFactory.getObjectInstance(ref, null, null, null); + // Create reference + Reference ref = JNDIReferenceFactory.createReference(factory.getClass().getName(), factory); - // Check settings - assertEquals(factory.isDispatchAsync(), temp.isDispatchAsync()); - assertEquals(factory.getBrokerURL(), temp.getBrokerURL()); - assertEquals(factory.getClientID(), temp.getClientID()); - assertEquals(factory.isCopyMessageOnSend(), temp.isCopyMessageOnSend()); - assertEquals(factory.isDisableTimeStampsByDefault(), temp.isDisableTimeStampsByDefault()); - assertEquals(factory.isObjectMessageSerializationDefered(), temp.isObjectMessageSerializationDefered()); - assertEquals(factory.isOptimizedMessageDispatch(), temp.isOptimizedMessageDispatch()); - assertEquals(factory.getPassword(), temp.getPassword()); - assertEquals(factory.isUseAsyncSend(), temp.isUseAsyncSend()); - assertEquals(factory.isUseCompression(), temp.isUseCompression()); - assertEquals(factory.isUseRetroactiveConsumer(), temp.isUseRetroactiveConsumer()); - assertEquals(factory.getUserName(), temp.getUserName()); - assertEquals(factory.getPrefetchPolicy().getQueuePrefetch(), temp.getPrefetchPolicy().getQueuePrefetch()); - assertEquals(factory.getRedeliveryPolicy().getMaximumRedeliveries(), temp.getRedeliveryPolicy().getMaximumRedeliveries()); - assertEquals(factory.getRedeliveryPolicy().getBackOffMultiplier(), temp.getRedeliveryPolicy().getBackOffMultiplier()); - } + // Get object created based on reference + ActiveMQConnectionFactory temp; + JNDIReferenceFactory refFactory = new JNDIReferenceFactory(); + temp = (ActiveMQConnectionFactory) refFactory.getObjectInstance(ref, null, null, null); - public void testDestination() throws Exception { - // Create sample destination - ActiveMQDestination dest = new ActiveMQQueue(); - dest.setPhysicalName("TEST.FOO"); + // Check settings + assertEquals(factory.isDispatchAsync(), temp.isDispatchAsync()); + assertEquals(factory.getBrokerURL(), temp.getBrokerURL()); + assertEquals(factory.getClientID(), temp.getClientID()); + assertEquals(factory.isCopyMessageOnSend(), temp.isCopyMessageOnSend()); + assertEquals(factory.isDisableTimeStampsByDefault(), temp.isDisableTimeStampsByDefault()); + assertEquals(factory.isObjectMessageSerializationDefered(), temp.isObjectMessageSerializationDefered()); + assertEquals(factory.isOptimizedMessageDispatch(), temp.isOptimizedMessageDispatch()); + assertEquals(factory.getPassword(), temp.getPassword()); + assertEquals(factory.isUseAsyncSend(), temp.isUseAsyncSend()); + assertEquals(factory.isUseCompression(), temp.isUseCompression()); + assertEquals(factory.isUseRetroactiveConsumer(), temp.isUseRetroactiveConsumer()); + assertEquals(factory.getUserName(), temp.getUserName()); + assertEquals(factory.getPrefetchPolicy().getQueuePrefetch(), temp.getPrefetchPolicy().getQueuePrefetch()); + assertEquals(factory.getRedeliveryPolicy().getMaximumRedeliveries(), temp.getRedeliveryPolicy().getMaximumRedeliveries()); + assertEquals(factory.getRedeliveryPolicy().getBackOffMultiplier(), temp.getRedeliveryPolicy().getBackOffMultiplier()); + } - // Create reference - Reference ref = JNDIReferenceFactory.createReference(dest.getClass().getName(), dest); + public void testDestination() throws Exception { + // Create sample destination + ActiveMQDestination dest = new ActiveMQQueue(); + dest.setPhysicalName("TEST.FOO"); - // Get object created based on reference - ActiveMQDestination temp; - JNDIReferenceFactory refFactory = new JNDIReferenceFactory(); - temp = (ActiveMQDestination)refFactory.getObjectInstance(ref, null, null, null); + // Create reference + Reference ref = JNDIReferenceFactory.createReference(dest.getClass().getName(), dest); - // Check settings - assertEquals(dest.getPhysicalName(), temp.getPhysicalName()); - } + // Get object created based on reference + ActiveMQDestination temp; + JNDIReferenceFactory refFactory = new JNDIReferenceFactory(); + temp = (ActiveMQDestination) refFactory.getObjectInstance(ref, null, null, null); + + // Check settings + assertEquals(dest.getPhysicalName(), temp.getPhysicalName()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/XAConnectionFactoryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/XAConnectionFactoryTest.java index cf7cca1707..df3c56448b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/XAConnectionFactoryTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/XAConnectionFactoryTest.java @@ -20,13 +20,13 @@ import javax.jms.XAConnectionFactory; import javax.naming.NamingException; public class XAConnectionFactoryTest extends ActiveMQInitialContextFactoryTest { - - public void testConnectionFactoriesIsXA() throws NamingException { - assertTrue("connection factory implements XA", context.lookup(getConnectionFactoryLookupName()) instanceof XAConnectionFactory); - } - - protected void configureEnvironment() { - environment.put("xa", "true"); - super.configureEnvironment(); - } + + public void testConnectionFactoriesIsXA() throws NamingException { + assertTrue("connection factory implements XA", context.lookup(getConnectionFactoryLookupName()) instanceof XAConnectionFactory); + } + + protected void configureEnvironment() { + environment.put("xa", "true"); + super.configureEnvironment(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/joramtests/ActiveMQAdmin.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/joramtests/ActiveMQAdmin.java index b20b9adf46..c8472c531e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/joramtests/ActiveMQAdmin.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/joramtests/ActiveMQAdmin.java @@ -33,118 +33,130 @@ import org.apache.activemq.command.ActiveMQTopic; import org.objectweb.jtests.jms.admin.Admin; /** - * * @author Hiram Chirino */ public class ActiveMQAdmin implements Admin { - Context context; - { - try { - // Use the jetty JNDI context since it's mutable. - final Hashtable env = new Hashtable(); - env.put("java.naming.factory.initial", "org.eclipse.jetty.jndi.InitialContextFactory"); - env.put("java.naming.factory.url.pkgs", "org.eclipse.jetty.jndi");; - context = new InitialContext(env); - } catch (NamingException e) { - throw new RuntimeException(e); - } - } + Context context; - protected BrokerService createBroker() throws Exception { - return BrokerFactory.createBroker(new URI("broker://()/localhost?persistent=false")); - } + { + try { + // Use the jetty JNDI context since it's mutable. + final Hashtable env = new Hashtable(); + env.put("java.naming.factory.initial", "org.eclipse.jetty.jndi.InitialContextFactory"); + env.put("java.naming.factory.url.pkgs", "org.eclipse.jetty.jndi"); + ; + context = new InitialContext(env); + } + catch (NamingException e) { + throw new RuntimeException(e); + } + } - public String getName() { - return getClass().getName(); - } + protected BrokerService createBroker() throws Exception { + return BrokerFactory.createBroker(new URI("broker://()/localhost?persistent=false")); + } - BrokerService broker; - public void startServer() throws Exception { - if (System.getProperty("basedir") == null) { - File file = new File("."); - System.setProperty("basedir", file.getAbsolutePath()); - } - broker = createBroker(); - broker.start(); - } + public String getName() { + return getClass().getName(); + } - public void stopServer() throws Exception { - broker.stop(); - } + BrokerService broker; - public void start() throws Exception { - } + public void startServer() throws Exception { + if (System.getProperty("basedir") == null) { + File file = new File("."); + System.setProperty("basedir", file.getAbsolutePath()); + } + broker = createBroker(); + broker.start(); + } - public void stop() throws Exception { - } + public void stopServer() throws Exception { + broker.stop(); + } - public Context createContext() throws NamingException { - return context; - } + public void start() throws Exception { + } - public void createQueue(String name) { - try { - context.bind(name, new ActiveMQQueue(name)); - } catch (NamingException e) { - throw new RuntimeException(e); - } - } + public void stop() throws Exception { + } - public void createTopic(String name) { - try { - context.bind(name, new ActiveMQTopic(name)); - } catch (NamingException e) { - throw new RuntimeException(e); - } - } + public Context createContext() throws NamingException { + return context; + } - public void deleteQueue(String name) { - // BrokerTestSupport.delete_queue((Broker)base.broker, name); - try { - context.unbind(name); - } catch (NamingException e) { - throw new RuntimeException(e); - } - } + public void createQueue(String name) { + try { + context.bind(name, new ActiveMQQueue(name)); + } + catch (NamingException e) { + throw new RuntimeException(e); + } + } - public void deleteTopic(String name) { - try { - context.unbind(name); - } catch (NamingException e) { - throw new RuntimeException(e); - } - } + public void createTopic(String name) { + try { + context.bind(name, new ActiveMQTopic(name)); + } + catch (NamingException e) { + throw new RuntimeException(e); + } + } - public void createConnectionFactory(String name) { - try { - final ConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - ((ActiveMQConnectionFactory) factory).setNestedMapAndListEnabled(false); - context.bind(name, factory); - } catch (NamingException e) { - throw new RuntimeException(e); - } - } + public void deleteQueue(String name) { + // BrokerTestSupport.delete_queue((Broker)base.broker, name); + try { + context.unbind(name); + } + catch (NamingException e) { + throw new RuntimeException(e); + } + } - public void deleteConnectionFactory(String name) { - try { - context.unbind(name); - } catch (NamingException e) { - throw new RuntimeException(e); - } - } + public void deleteTopic(String name) { + try { + context.unbind(name); + } + catch (NamingException e) { + throw new RuntimeException(e); + } + } - public void createQueueConnectionFactory(String name) { - createConnectionFactory(name); - } - public void createTopicConnectionFactory(String name) { - createConnectionFactory(name); - } - public void deleteQueueConnectionFactory(String name) { - deleteConnectionFactory(name); - } - public void deleteTopicConnectionFactory(String name) { - deleteConnectionFactory(name); - } + public void createConnectionFactory(String name) { + try { + final ConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + ((ActiveMQConnectionFactory) factory).setNestedMapAndListEnabled(false); + context.bind(name, factory); + } + catch (NamingException e) { + throw new RuntimeException(e); + } + } + + public void deleteConnectionFactory(String name) { + try { + context.unbind(name); + } + catch (NamingException e) { + throw new RuntimeException(e); + } + } + + public void createQueueConnectionFactory(String name) { + createConnectionFactory(name); + } + + public void createTopicConnectionFactory(String name) { + createConnectionFactory(name); + } + + public void deleteQueueConnectionFactory(String name) { + deleteConnectionFactory(name); + } + + public void deleteTopicConnectionFactory(String name) { + deleteConnectionFactory(name); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/joramtests/JoramJmsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/joramtests/JoramJmsTest.java index 00c5423a72..0955294bf1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/joramtests/JoramJmsTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/joramtests/JoramJmsTest.java @@ -44,31 +44,31 @@ import org.objectweb.jtests.jms.conform.topic.TemporaryTopicTest; */ public class JoramJmsTest extends TestCase { - public static Test suite() { - TestSuite suite = new TestSuite(); - suite.addTestSuite(SelectorTest.class); - suite.addTestSuite(ConnectionTest.class); - suite.addTestSuite(TopicConnectionTest.class); - suite.addTestSuite(MessageHeaderTest.class); - suite.addTestSuite(MessageBodyTest.class); - suite.addTestSuite(MessageDefaultTest.class); - suite.addTestSuite(MessageTypeTest.class); - suite.addTestSuite(JMSXPropertyTest.class); - suite.addTestSuite(MessagePropertyConversionTest.class); - suite.addTestSuite(TemporaryQueueTest.class); - suite.addTestSuite(SelectorSyntaxTest.class); - suite.addTestSuite(QueueSessionTest.class); - suite.addTestSuite(SessionTest.class); - suite.addTestSuite(TopicSessionTest.class); - suite.addTestSuite(TemporaryTopicTest.class); - suite.addTestSuite(UnifiedSessionTest.class); - suite.addTestSuite(QueueBrowserTest.class); - suite.addTestSuite(MessagePropertyTest.class); - return suite; - } + public static Test suite() { + TestSuite suite = new TestSuite(); + suite.addTestSuite(SelectorTest.class); + suite.addTestSuite(ConnectionTest.class); + suite.addTestSuite(TopicConnectionTest.class); + suite.addTestSuite(MessageHeaderTest.class); + suite.addTestSuite(MessageBodyTest.class); + suite.addTestSuite(MessageDefaultTest.class); + suite.addTestSuite(MessageTypeTest.class); + suite.addTestSuite(JMSXPropertyTest.class); + suite.addTestSuite(MessagePropertyConversionTest.class); + suite.addTestSuite(TemporaryQueueTest.class); + suite.addTestSuite(SelectorSyntaxTest.class); + suite.addTestSuite(QueueSessionTest.class); + suite.addTestSuite(SessionTest.class); + suite.addTestSuite(TopicSessionTest.class); + suite.addTestSuite(TemporaryTopicTest.class); + suite.addTestSuite(UnifiedSessionTest.class); + suite.addTestSuite(QueueBrowserTest.class); + suite.addTestSuite(MessagePropertyTest.class); + return suite; + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/leveldb/LevelDBStoreBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/leveldb/LevelDBStoreBrokerTest.java index 6f58586c8c..7854af035a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/leveldb/LevelDBStoreBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/leveldb/LevelDBStoreBrokerTest.java @@ -17,6 +17,7 @@ package org.apache.activemq.leveldb; import junit.framework.Test; + import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerTest; import org.apache.activemq.store.PersistenceAdapter; @@ -29,34 +30,34 @@ import java.io.IOException; */ public class LevelDBStoreBrokerTest extends BrokerTest { - public static Test suite() { - return suite(LevelDBStoreBrokerTest.class); - } + public static Test suite() { + return suite(LevelDBStoreBrokerTest.class); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setPersistenceAdapter(createPersistenceAdapter(true)); - return broker; - } + @Override + protected BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setPersistenceAdapter(createPersistenceAdapter(true)); + return broker; + } - protected PersistenceAdapter createPersistenceAdapter(boolean delete) { - LevelDBStore store = new LevelDBStore(); - store.setDirectory(new File("target/activemq-data/leveldb")); - if (delete) { - store.deleteAllMessages(); - } - return store; + protected PersistenceAdapter createPersistenceAdapter(boolean delete) { + LevelDBStore store = new LevelDBStore(); + store.setDirectory(new File("target/activemq-data/leveldb")); + if (delete) { + store.deleteAllMessages(); } + return store; + } - protected BrokerService createRestartedBroker() throws IOException { - BrokerService broker = new BrokerService(); - broker.setPersistenceAdapter(createPersistenceAdapter(false)); - return broker; - } + protected BrokerService createRestartedBroker() throws IOException { + BrokerService broker = new BrokerService(); + broker.setPersistenceAdapter(createPersistenceAdapter(false)); + return broker; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/leveldb/LevelDBXARecoveryBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/leveldb/LevelDBXARecoveryBrokerTest.java index 82cd7e4561..ca1a72a597 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/leveldb/LevelDBXARecoveryBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/leveldb/LevelDBXARecoveryBrokerTest.java @@ -29,40 +29,41 @@ import org.apache.commons.io.FileUtils; * @author Hiram Chirino */ public class LevelDBXARecoveryBrokerTest extends XARecoveryBrokerTest { - public static final String LEVELDB_DIR_BASE = "target/activemq-data/xahaleveldb"; - public static String levelDbDirectoryName; - @Override - protected void setUp() throws Exception { - levelDbDirectoryName = LEVELDB_DIR_BASE + "/" + System.currentTimeMillis(); - super.setUp(); - } + public static final String LEVELDB_DIR_BASE = "target/activemq-data/xahaleveldb"; + public static String levelDbDirectoryName; - @Override - protected void tearDown() throws Exception { - super.tearDown(); - try { - File levelDbDir = new File(levelDbDirectoryName); - FileUtils.deleteDirectory(levelDbDir); - } catch (IOException e) { - } - } + @Override + protected void setUp() throws Exception { + levelDbDirectoryName = LEVELDB_DIR_BASE + "/" + System.currentTimeMillis(); + super.setUp(); + } + @Override + protected void tearDown() throws Exception { + super.tearDown(); + try { + File levelDbDir = new File(levelDbDirectoryName); + FileUtils.deleteDirectory(levelDbDir); + } + catch (IOException e) { + } + } - public static Test suite() { - return suite(LevelDBXARecoveryBrokerTest.class); - } + public static Test suite() { + return suite(LevelDBXARecoveryBrokerTest.class); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - @Override - protected void configureBroker(BrokerService broker) throws Exception { - super.configureBroker(broker); - LevelDBStore store = new LevelDBStore(); - store.setDirectory(new File(levelDbDirectoryName)); - broker.setPersistenceAdapter(store); - } + @Override + protected void configureBroker(BrokerService broker) throws Exception { + super.configureBroker(broker); + LevelDBStore store = new LevelDBStore(); + store.setDirectory(new File(levelDbDirectoryName)); + broker.setPersistenceAdapter(store); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/load/LoadClient.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/load/LoadClient.java index 0f69567c62..e272f8fe02 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/load/LoadClient.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/load/LoadClient.java @@ -32,202 +32,176 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ -public class LoadClient implements Runnable{ - private static final Logger LOG = LoggerFactory.getLogger(LoadClient.class); - protected static int SLEEP_TIME = 2; - protected String name; - protected ConnectionFactory factory; - protected Connection connection; - protected Destination startDestination; - protected Destination nextDestination; - protected Session session; - protected MessageConsumer consumer; - protected MessageProducer producer; - protected PerfRate rate = new PerfRate(); - protected int deliveryMode = DeliveryMode.PERSISTENT; - protected ActiveMQMessageAudit audit = new ActiveMQMessageAudit(); - protected boolean connectionPerMessage = false; - protected boolean running; - protected int timeout = 10000; - +public class LoadClient implements Runnable { - public LoadClient(String name,ConnectionFactory factory) { - this.name=name; - this.factory = factory; - } + private static final Logger LOG = LoggerFactory.getLogger(LoadClient.class); + protected static int SLEEP_TIME = 2; + protected String name; + protected ConnectionFactory factory; + protected Connection connection; + protected Destination startDestination; + protected Destination nextDestination; + protected Session session; + protected MessageConsumer consumer; + protected MessageProducer producer; + protected PerfRate rate = new PerfRate(); + protected int deliveryMode = DeliveryMode.PERSISTENT; + protected ActiveMQMessageAudit audit = new ActiveMQMessageAudit(); + protected boolean connectionPerMessage = false; + protected boolean running; + protected int timeout = 10000; - + public LoadClient(String name, ConnectionFactory factory) { + this.name = name; + this.factory = factory; + } - public synchronized void start() throws JMSException { - if (!running) { - rate.reset(); - running = true; - if (!connectionPerMessage) { - connection = factory.createConnection(); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = session.createConsumer(getConsumeDestination()); - producer = session.createProducer(getSendDestination()); - producer.setDeliveryMode(this.deliveryMode); - - } - - Thread t = new Thread(this); - t.setName(name); - t.start(); - } - } + public synchronized void start() throws JMSException { + if (!running) { + rate.reset(); + running = true; + if (!connectionPerMessage) { + connection = factory.createConnection(); + connection.start(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumer = session.createConsumer(getConsumeDestination()); + producer = session.createProducer(getSendDestination()); + producer.setDeliveryMode(this.deliveryMode); - public void stop() throws JMSException, InterruptedException { - running = false; - if(connection != null) { - connection.stop(); - } - } + } - - public void run() { - try { - while (running) { - String result = consume(); - if(result != null) { - send(result); - rate.increment(); - } - else if (running) { - LOG.error(name + " Failed to consume!"); - } + Thread t = new Thread(this); + t.setName(name); + t.start(); + } + } + + public void stop() throws JMSException, InterruptedException { + running = false; + if (connection != null) { + connection.stop(); + } + } + + public void run() { + try { + while (running) { + String result = consume(); + if (result != null) { + send(result); + rate.increment(); } - } catch (Throwable e) { - e.printStackTrace(); - } - } - - protected String consume() throws Exception { - Connection con = null; - MessageConsumer c = consumer; - if (connectionPerMessage){ - con = factory.createConnection(); - con.start(); - Session s = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - c = s.createConsumer(getConsumeDestination()); - } - TextMessage result = (TextMessage) c.receive(timeout); - if (result != null) { - if (audit.isDuplicate(result.getJMSMessageID())) { - throw new JMSException("Received duplicate " + result.getText()); + else if (running) { + LOG.error(name + " Failed to consume!"); } - if (!audit.isInOrder(result.getJMSMessageID())) { - throw new JMSException("Out of order " + result.getText()); - } - - if (connectionPerMessage) { - Thread.sleep(SLEEP_TIME);//give the broker a chance - con.close(); - } - } - return result != null ? result.getText() : null; - } - - protected void send(String text) throws Exception { - Connection con = connection; - MessageProducer p = producer; - Session s = session; - if (connectionPerMessage){ - con = factory.createConnection(); - con.start(); - s = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - p = s.createProducer(getSendDestination()); - p.setDeliveryMode(deliveryMode); - } - TextMessage message = s.createTextMessage(text); - p.send(message); - if (connectionPerMessage) { + } + } + catch (Throwable e) { + e.printStackTrace(); + } + } + + protected String consume() throws Exception { + Connection con = null; + MessageConsumer c = consumer; + if (connectionPerMessage) { + con = factory.createConnection(); + con.start(); + Session s = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + c = s.createConsumer(getConsumeDestination()); + } + TextMessage result = (TextMessage) c.receive(timeout); + if (result != null) { + if (audit.isDuplicate(result.getJMSMessageID())) { + throw new JMSException("Received duplicate " + result.getText()); + } + if (!audit.isInOrder(result.getJMSMessageID())) { + throw new JMSException("Out of order " + result.getText()); + } + + if (connectionPerMessage) { Thread.sleep(SLEEP_TIME);//give the broker a chance con.close(); - } - } + } + } + return result != null ? result.getText() : null; + } + protected void send(String text) throws Exception { + Connection con = connection; + MessageProducer p = producer; + Session s = session; + if (connectionPerMessage) { + con = factory.createConnection(); + con.start(); + s = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + p = s.createProducer(getSendDestination()); + p.setDeliveryMode(deliveryMode); + } + TextMessage message = s.createTextMessage(text); + p.send(message); + if (connectionPerMessage) { + Thread.sleep(SLEEP_TIME);//give the broker a chance + con.close(); + } + } + public String getName() { + return name; + } - public String getName() { - return name; - } + public void setName(String name) { + this.name = name; + } + public Destination getStartDestination() { + return startDestination; + } + public void setStartDestination(Destination startDestination) { + this.startDestination = startDestination; + } - public void setName(String name) { - this.name = name; - } + public Destination getNextDestination() { + return nextDestination; + } + public void setNextDestination(Destination nextDestination) { + this.nextDestination = nextDestination; + } + public int getDeliveryMode() { + return deliveryMode; + } - public Destination getStartDestination() { - return startDestination; - } + public void setDeliveryMode(int deliveryMode) { + this.deliveryMode = deliveryMode; + } + public boolean isConnectionPerMessage() { + return connectionPerMessage; + } + public void setConnectionPerMessage(boolean connectionPerMessage) { + this.connectionPerMessage = connectionPerMessage; + } - public void setStartDestination(Destination startDestination) { - this.startDestination = startDestination; - } + public int getTimeout() { + return timeout; + } + public void setTimeout(int timeout) { + this.timeout = timeout; + } + protected Destination getSendDestination() { + return nextDestination; + } - public Destination getNextDestination() { - return nextDestination; - } - - - - public void setNextDestination(Destination nextDestination) { - this.nextDestination = nextDestination; - } - - - - public int getDeliveryMode() { - return deliveryMode; - } - - - - public void setDeliveryMode(int deliveryMode) { - this.deliveryMode = deliveryMode; - } - - - - public boolean isConnectionPerMessage() { - return connectionPerMessage; - } - - - - public void setConnectionPerMessage(boolean connectionPerMessage) { - this.connectionPerMessage = connectionPerMessage; - } - - - - public int getTimeout() { - return timeout; - } - - - - public void setTimeout(int timeout) { - this.timeout = timeout; - } - - protected Destination getSendDestination() { - return nextDestination; - } - - protected Destination getConsumeDestination() { - return startDestination; - } + protected Destination getConsumeDestination() { + return startDestination; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/load/LoadController.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/load/LoadController.java index 22b90642f5..31ea4c1f47 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/load/LoadController.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/load/LoadController.java @@ -26,78 +26,79 @@ import javax.jms.JMSException; /** * */ -public class LoadController extends LoadClient{ +public class LoadController extends LoadClient { - private int numberOfBatches=1; - private int batchSize =1000; - private int count; - private final CountDownLatch stopped = new CountDownLatch(1); + private int numberOfBatches = 1; + private int batchSize = 1000; + private int count; + private final CountDownLatch stopped = new CountDownLatch(1); - public LoadController(String name,ConnectionFactory factory) { - super(name,factory); - } + public LoadController(String name, ConnectionFactory factory) { + super(name, factory); + } + public int awaitTestComplete() throws InterruptedException { + stopped.await(60 * 5, TimeUnit.SECONDS); + return count; + } - public int awaitTestComplete() throws InterruptedException { - stopped.await(60*5,TimeUnit.SECONDS); - return count; - } + @Override + public void stop() throws JMSException, InterruptedException { + running = false; + stopped.countDown(); + if (connection != null) { + this.connection.stop(); + } + } - @Override - public void stop() throws JMSException, InterruptedException { - running = false; - stopped.countDown(); - if (connection != null) { - this.connection.stop(); - } - } - - @Override - public void run() { - try { - for (int i = 0; i < numberOfBatches; i++) { - for (int j = 0; j < batchSize; j++) { - String payLoad = "batch[" + i + "]no:" + j; - send(payLoad); - } - for (int j = 0; j < batchSize; j++) { - String result = consume(); - if (result != null) { - count++; - rate.increment(); - } - } + @Override + public void run() { + try { + for (int i = 0; i < numberOfBatches; i++) { + for (int j = 0; j < batchSize; j++) { + String payLoad = "batch[" + i + "]no:" + j; + send(payLoad); } - } catch (Throwable e) { - e.printStackTrace(); - } finally { - stopped.countDown(); - } - } + for (int j = 0; j < batchSize; j++) { + String result = consume(); + if (result != null) { + count++; + rate.increment(); + } + } + } + } + catch (Throwable e) { + e.printStackTrace(); + } + finally { + stopped.countDown(); + } + } - public int getNumberOfBatches() { - return numberOfBatches; - } + public int getNumberOfBatches() { + return numberOfBatches; + } - public void setNumberOfBatches(int numberOfBatches) { - this.numberOfBatches = numberOfBatches; - } + public void setNumberOfBatches(int numberOfBatches) { + this.numberOfBatches = numberOfBatches; + } - public int getBatchSize() { - return batchSize; - } + public int getBatchSize() { + return batchSize; + } - public void setBatchSize(int batchSize) { - this.batchSize = batchSize; - } + public void setBatchSize(int batchSize) { + this.batchSize = batchSize; + } - @Override - protected Destination getSendDestination() { - return startDestination; - } + @Override + protected Destination getSendDestination() { + return startDestination; + } - @Override - protected Destination getConsumeDestination() { - return nextDestination; - } + @Override + protected Destination getConsumeDestination() { + return nextDestination; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/load/LoadTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/load/LoadTest.java index ee1037b54a..9657522b81 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/load/LoadTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/load/LoadTest.java @@ -22,134 +22,135 @@ import javax.jms.DeliveryMode; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Session; + import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class LoadTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(LoadTest.class); - - protected BrokerService broker; - protected String bindAddress="tcp://localhost:61616"; - - protected LoadController controller; - protected LoadClient[] clients; - protected ConnectionFactory factory; - protected Destination destination; - protected int numberOfClients = 50; - protected int deliveryMode = DeliveryMode.PERSISTENT; - protected int batchSize = 1000; - protected int numberOfBatches = 10; - protected int timeout = Integer.MAX_VALUE; - protected boolean connectionPerMessage = false; - protected Connection managementConnection; - protected Session managementSession; + private static final Logger LOG = LoggerFactory.getLogger(LoadTest.class); - /** - * Sets up a test where the producer and consumer have their own connection. - * - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception { - if (broker == null) { - broker = createBroker(bindAddress); - } - factory = createConnectionFactory(bindAddress); - managementConnection = factory.createConnection(); - managementSession = managementConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - Destination startDestination = createDestination(managementSession, getClass()+".start"); - Destination endDestination = createDestination(managementSession, getClass()+".end"); - LOG.info("Running with " + numberOfClients + " clients - sending " - + numberOfBatches + " batches of " + batchSize + " messages"); - controller = new LoadController("Controller",factory); - controller.setBatchSize(batchSize); - controller.setNumberOfBatches(numberOfBatches); - controller.setDeliveryMode(deliveryMode); - controller.setConnectionPerMessage(connectionPerMessage); - controller.setStartDestination(startDestination); - controller.setNextDestination(endDestination); - controller.setTimeout(timeout); - clients = new LoadClient[numberOfClients]; - for (int i = 0; i < numberOfClients; i++) { - Destination inDestination = null; - if (i==0) { - inDestination = startDestination; - }else { - inDestination = createDestination(managementSession, getClass() + ".client."+(i)); - } - Destination outDestination = null; - if (i==(numberOfClients-1)) { - outDestination = endDestination; - }else { - outDestination = createDestination(managementSession, getClass() + ".client."+(i+1)); - } - LoadClient client = new LoadClient("client("+i+")",factory); - client.setTimeout(timeout); - client.setDeliveryMode(deliveryMode); - client.setConnectionPerMessage(connectionPerMessage); - client.setStartDestination(inDestination); - client.setNextDestination(outDestination); - clients[i] = client; - } - - super.setUp(); - } + protected BrokerService broker; + protected String bindAddress = "tcp://localhost:61616"; - protected void tearDown() throws Exception { - super.tearDown(); - managementConnection.close(); - for (int i = 0; i < numberOfClients; i++) { - clients[i].stop(); - } - controller.stop(); - if (broker != null) { - broker.stop(); - broker = null; - } - } + protected LoadController controller; + protected LoadClient[] clients; + protected ConnectionFactory factory; + protected Destination destination; + protected int numberOfClients = 50; + protected int deliveryMode = DeliveryMode.PERSISTENT; + protected int batchSize = 1000; + protected int numberOfBatches = 10; + protected int timeout = Integer.MAX_VALUE; + protected boolean connectionPerMessage = false; + protected Connection managementConnection; + protected Session managementSession; - protected Destination createDestination(Session s, String destinationName) throws JMSException { - return s.createQueue(destinationName); - } + /** + * Sets up a test where the producer and consumer have their own connection. + * + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + if (broker == null) { + broker = createBroker(bindAddress); + } + factory = createConnectionFactory(bindAddress); + managementConnection = factory.createConnection(); + managementSession = managementConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - /** - * Factory method to create a new broker - * - * @throws Exception - */ - protected BrokerService createBroker(String uri) throws Exception { - BrokerService answer = new BrokerService(); - configureBroker(answer,uri); - answer.start(); - return answer; - } + Destination startDestination = createDestination(managementSession, getClass() + ".start"); + Destination endDestination = createDestination(managementSession, getClass() + ".end"); + LOG.info("Running with " + numberOfClients + " clients - sending " + numberOfBatches + " batches of " + batchSize + " messages"); + controller = new LoadController("Controller", factory); + controller.setBatchSize(batchSize); + controller.setNumberOfBatches(numberOfBatches); + controller.setDeliveryMode(deliveryMode); + controller.setConnectionPerMessage(connectionPerMessage); + controller.setStartDestination(startDestination); + controller.setNextDestination(endDestination); + controller.setTimeout(timeout); + clients = new LoadClient[numberOfClients]; + for (int i = 0; i < numberOfClients; i++) { + Destination inDestination = null; + if (i == 0) { + inDestination = startDestination; + } + else { + inDestination = createDestination(managementSession, getClass() + ".client." + (i)); + } + Destination outDestination = null; + if (i == (numberOfClients - 1)) { + outDestination = endDestination; + } + else { + outDestination = createDestination(managementSession, getClass() + ".client." + (i + 1)); + } + LoadClient client = new LoadClient("client(" + i + ")", factory); + client.setTimeout(timeout); + client.setDeliveryMode(deliveryMode); + client.setConnectionPerMessage(connectionPerMessage); + client.setStartDestination(inDestination); + client.setNextDestination(outDestination); + clients[i] = client; + } - - - protected void configureBroker(BrokerService answer,String uri) throws Exception { - answer.setDeleteAllMessagesOnStartup(true); - answer.addConnector(uri); - answer.setUseShutdownHook(false); - } + super.setUp(); + } - protected ActiveMQConnectionFactory createConnectionFactory(String uri) throws Exception { - return new ActiveMQConnectionFactory(uri); - } + protected void tearDown() throws Exception { + super.tearDown(); + managementConnection.close(); + for (int i = 0; i < numberOfClients; i++) { + clients[i].stop(); + } + controller.stop(); + if (broker != null) { + broker.stop(); + broker = null; + } + } - public void testLoad() throws JMSException, InterruptedException { - for (int i = 0; i < numberOfClients; i++) { - clients[i].start(); - } - controller.start(); - assertEquals((batchSize* numberOfBatches),controller.awaitTestComplete()); - - } + protected Destination createDestination(Session s, String destinationName) throws JMSException { + return s.createQueue(destinationName); + } + + /** + * Factory method to create a new broker + * + * @throws Exception + */ + protected BrokerService createBroker(String uri) throws Exception { + BrokerService answer = new BrokerService(); + configureBroker(answer, uri); + answer.start(); + return answer; + } + + protected void configureBroker(BrokerService answer, String uri) throws Exception { + answer.setDeleteAllMessagesOnStartup(true); + answer.addConnector(uri); + answer.setUseShutdownHook(false); + } + + protected ActiveMQConnectionFactory createConnectionFactory(String uri) throws Exception { + return new ActiveMQConnectionFactory(uri); + } + + public void testLoad() throws JMSException, InterruptedException { + for (int i = 0; i < numberOfClients; i++) { + clients[i].start(); + } + controller.start(); + assertEquals((batchSize * numberOfBatches), controller.awaitTestComplete()); + + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/BoundaryStatisticTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/BoundaryStatisticTest.java index 194cbbcf11..0ce7a01054 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/BoundaryStatisticTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/BoundaryStatisticTest.java @@ -16,23 +16,22 @@ */ package org.apache.activemq.management; - public class BoundaryStatisticTest extends StatisticTestSupport { - - private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory - .getLog(BoundaryStatisticTest.class); - /** - * Use case for BoundaryStatisticImpl class. - * @throws Exception - */ - public void testStatistic() throws Exception { - BoundaryStatisticImpl stat = new BoundaryStatisticImpl("myBoundaryStat", "seconds", "myBoundaryStatDesc", 1000, 2000); - assertStatistic(stat, "myBoundaryStat", "seconds", "myBoundaryStatDesc"); + private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(BoundaryStatisticTest.class); - assertEquals(1000, stat.getLowerBound()); - assertEquals(2000, stat.getUpperBound()); + /** + * Use case for BoundaryStatisticImpl class. + * + * @throws Exception + */ + public void testStatistic() throws Exception { + BoundaryStatisticImpl stat = new BoundaryStatisticImpl("myBoundaryStat", "seconds", "myBoundaryStatDesc", 1000, 2000); + assertStatistic(stat, "myBoundaryStat", "seconds", "myBoundaryStatDesc"); - LOG.info("Stat is: " + stat); - } + assertEquals(1000, stat.getLowerBound()); + assertEquals(2000, stat.getUpperBound()); + + LOG.info("Stat is: " + stat); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/BoundedRangeStatisticTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/BoundedRangeStatisticTest.java index b920718c75..e02976f967 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/BoundedRangeStatisticTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/BoundedRangeStatisticTest.java @@ -16,23 +16,22 @@ */ package org.apache.activemq.management; - - /** - * + * */ public class BoundedRangeStatisticTest extends RangeStatisticTest { - /** - * Use case for BoundedRangeStatisticImpl class. - * @throws Exception - */ - public void testStatistic() throws Exception { - BoundedRangeStatisticImpl stat = new BoundedRangeStatisticImpl("myRange", "millis", "myDescription", 10, 3000); - assertStatistic(stat, "myRange", "millis", "myDescription"); - assertEquals(10, stat.getLowerBound()); - assertEquals(3000, stat.getUpperBound()); + /** + * Use case for BoundedRangeStatisticImpl class. + * + * @throws Exception + */ + public void testStatistic() throws Exception { + BoundedRangeStatisticImpl stat = new BoundedRangeStatisticImpl("myRange", "millis", "myDescription", 10, 3000); + assertStatistic(stat, "myRange", "millis", "myDescription"); + assertEquals(10, stat.getLowerBound()); + assertEquals(3000, stat.getUpperBound()); - assertRangeStatistic(stat); - } + assertRangeStatistic(stat); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/CountStatisticTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/CountStatisticTest.java index 85f8be104d..4c7a658874 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/CountStatisticTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/CountStatisticTest.java @@ -16,42 +16,41 @@ */ package org.apache.activemq.management; - public class CountStatisticTest extends StatisticTestSupport { - - private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory - .getLog(CountStatisticTest.class); - /** - * Use case for CountStatisticImple class. - * @throws Exception - */ - public void testStatistic() throws Exception { - CountStatisticImpl stat = new CountStatisticImpl("myCounter", "seconds", "myDescription"); - stat.setEnabled(true); - assertStatistic(stat, "myCounter", "seconds", "myDescription"); + private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(CountStatisticTest.class); - assertEquals(0, stat.getCount()); + /** + * Use case for CountStatisticImple class. + * + * @throws Exception + */ + public void testStatistic() throws Exception { + CountStatisticImpl stat = new CountStatisticImpl("myCounter", "seconds", "myDescription"); + stat.setEnabled(true); + assertStatistic(stat, "myCounter", "seconds", "myDescription"); - stat.increment(); - assertEquals(1, stat.getCount()); + assertEquals(0, stat.getCount()); - stat.increment(); - assertEquals(2, stat.getCount()); + stat.increment(); + assertEquals(1, stat.getCount()); - stat.decrement(); - assertEquals(1, stat.getCount()); + stat.increment(); + assertEquals(2, stat.getCount()); - Thread.sleep(500); + stat.decrement(); + assertEquals(1, stat.getCount()); - stat.increment(); + Thread.sleep(500); - assertLastTimeNotStartTime(stat); + stat.increment(); - LOG.info("Counter is: " + stat); + assertLastTimeNotStartTime(stat); - stat.reset(); + LOG.info("Counter is: " + stat); - assertEquals(0, stat.getCount()); - } + stat.reset(); + + assertEquals(0, stat.getCount()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/RangeStatisticTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/RangeStatisticTest.java index 49caa986fc..887527edac 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/RangeStatisticTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/RangeStatisticTest.java @@ -16,63 +16,62 @@ */ package org.apache.activemq.management; - public class RangeStatisticTest extends StatisticTestSupport { - - private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory - .getLog(RangeStatisticTest.class); - /** - * Use case for RangeStatisticImpl class. - * @throws Exception - */ - public void testStatistic() throws Exception { - RangeStatisticImpl stat = new RangeStatisticImpl("myRange", "millis", "myDescription"); - assertStatistic(stat, "myRange", "millis", "myDescription"); + private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(RangeStatisticTest.class); - assertRangeStatistic(stat); - } + /** + * Use case for RangeStatisticImpl class. + * + * @throws Exception + */ + public void testStatistic() throws Exception { + RangeStatisticImpl stat = new RangeStatisticImpl("myRange", "millis", "myDescription"); + assertStatistic(stat, "myRange", "millis", "myDescription"); - protected void assertRangeStatistic(RangeStatisticImpl stat) throws InterruptedException { - assertEquals(0, stat.getCurrent()); - assertEquals(0, stat.getLowWaterMark()); - assertEquals(0, stat.getHighWaterMark()); + assertRangeStatistic(stat); + } - stat.setCurrent(100); - assertEquals(100, stat.getCurrent()); - assertEquals(100, stat.getLowWaterMark()); - assertEquals(100, stat.getHighWaterMark()); + protected void assertRangeStatistic(RangeStatisticImpl stat) throws InterruptedException { + assertEquals(0, stat.getCurrent()); + assertEquals(0, stat.getLowWaterMark()); + assertEquals(0, stat.getHighWaterMark()); - stat.setCurrent(50); - assertEquals(50, stat.getCurrent()); - assertEquals(50, stat.getLowWaterMark()); - assertEquals(100, stat.getHighWaterMark()); + stat.setCurrent(100); + assertEquals(100, stat.getCurrent()); + assertEquals(100, stat.getLowWaterMark()); + assertEquals(100, stat.getHighWaterMark()); - stat.setCurrent(200); - assertEquals(200, stat.getCurrent()); - assertEquals(50, stat.getLowWaterMark()); - assertEquals(200, stat.getHighWaterMark()); + stat.setCurrent(50); + assertEquals(50, stat.getCurrent()); + assertEquals(50, stat.getLowWaterMark()); + assertEquals(100, stat.getHighWaterMark()); - Thread.sleep(500); + stat.setCurrent(200); + assertEquals(200, stat.getCurrent()); + assertEquals(50, stat.getLowWaterMark()); + assertEquals(200, stat.getHighWaterMark()); - stat.setCurrent(10); - assertEquals(10, stat.getCurrent()); - assertEquals(10, stat.getLowWaterMark()); - assertEquals(200, stat.getHighWaterMark()); + Thread.sleep(500); - assertLastTimeNotStartTime(stat); + stat.setCurrent(10); + assertEquals(10, stat.getCurrent()); + assertEquals(10, stat.getLowWaterMark()); + assertEquals(200, stat.getHighWaterMark()); - LOG.info("Stat is: " + stat); + assertLastTimeNotStartTime(stat); - stat.reset(); + LOG.info("Stat is: " + stat); - assertEquals(0, stat.getCurrent()); - assertEquals(0, stat.getLowWaterMark()); - assertEquals(0, stat.getHighWaterMark()); + stat.reset(); - stat.setCurrent(100); - assertEquals(100, stat.getCurrent()); - assertEquals(100, stat.getLowWaterMark()); - assertEquals(100, stat.getHighWaterMark()); - } + assertEquals(0, stat.getCurrent()); + assertEquals(0, stat.getLowWaterMark()); + assertEquals(0, stat.getHighWaterMark()); + + stat.setCurrent(100); + assertEquals(100, stat.getCurrent()); + assertEquals(100, stat.getLowWaterMark()); + assertEquals(100, stat.getHighWaterMark()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/StatisticTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/StatisticTestSupport.java index 9d68cb24c2..9e01f3d932 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/StatisticTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/StatisticTestSupport.java @@ -20,28 +20,26 @@ import junit.framework.TestCase; public abstract class StatisticTestSupport extends TestCase { - /** - * assert method used by the management related classes for its usecase. - * - * @param counter - * @param name - * @param unit - * @param description - */ - protected void assertStatistic(StatisticImpl counter, String name, String unit, String description) { - assertEquals(name, counter.getName()); - assertEquals(unit, counter.getUnit()); - assertEquals(description, counter.getDescription()); - } + /** + * assert method used by the management related classes for its usecase. + * + * @param counter + * @param name + * @param unit + * @param description + */ + protected void assertStatistic(StatisticImpl counter, String name, String unit, String description) { + assertEquals(name, counter.getName()); + assertEquals(unit, counter.getUnit()); + assertEquals(description, counter.getDescription()); + } - /** - * assert method to determine last time vs the start time. - * - * @param counter - */ - protected void assertLastTimeNotStartTime(StatisticImpl counter) { - assertTrue("Should not have start time the same as last sample time. Start time: " - + counter.getStartTime() + " lastTime: " + counter.getLastSampleTime(), counter - .getStartTime() != counter.getLastSampleTime()); - } + /** + * assert method to determine last time vs the start time. + * + * @param counter + */ + protected void assertLastTimeNotStartTime(StatisticImpl counter) { + assertTrue("Should not have start time the same as last sample time. Start time: " + counter.getStartTime() + " lastTime: " + counter.getLastSampleTime(), counter.getStartTime() != counter.getLastSampleTime()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/TimeStatisticTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/TimeStatisticTest.java index 88ec2eac1c..b32f8ce7b7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/TimeStatisticTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/TimeStatisticTest.java @@ -16,60 +16,58 @@ */ package org.apache.activemq.management; - public class TimeStatisticTest extends StatisticTestSupport { - - private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory - .getLog(TimeStatisticTest.class); - /** - * Use case for TimeStatisticImpl class. - * @throws Exception - */ - public void testStatistic() throws Exception { - TimeStatisticImpl stat = new TimeStatisticImpl("myTimer", "millis", "myDescription"); - assertStatistic(stat, "myTimer", "millis", "myDescription"); + private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(TimeStatisticTest.class); - assertEquals(0, stat.getCount()); + /** + * Use case for TimeStatisticImpl class. + * + * @throws Exception + */ + public void testStatistic() throws Exception { + TimeStatisticImpl stat = new TimeStatisticImpl("myTimer", "millis", "myDescription"); + assertStatistic(stat, "myTimer", "millis", "myDescription"); - stat.addTime(100); - assertEquals(1, stat.getCount()); - assertEquals(100, stat.getMinTime()); - assertEquals(100, stat.getMaxTime()); + assertEquals(0, stat.getCount()); - stat.addTime(403); - assertEquals(2, stat.getCount()); - assertEquals(100, stat.getMinTime()); - assertEquals(403, stat.getMaxTime()); + stat.addTime(100); + assertEquals(1, stat.getCount()); + assertEquals(100, stat.getMinTime()); + assertEquals(100, stat.getMaxTime()); - stat.addTime(50); - assertEquals(3, stat.getCount()); - assertEquals(50, stat.getMinTime()); - assertEquals(403, stat.getMaxTime()); + stat.addTime(403); + assertEquals(2, stat.getCount()); + assertEquals(100, stat.getMinTime()); + assertEquals(403, stat.getMaxTime()); + stat.addTime(50); + assertEquals(3, stat.getCount()); + assertEquals(50, stat.getMinTime()); + assertEquals(403, stat.getMaxTime()); - assertEquals(553, stat.getTotalTime()); + assertEquals(553, stat.getTotalTime()); - Thread.sleep(500); + Thread.sleep(500); - stat.addTime(10); + stat.addTime(10); - assertLastTimeNotStartTime(stat); + assertLastTimeNotStartTime(stat); - LOG.info("Stat is: " + stat); + LOG.info("Stat is: " + stat); - stat.reset(); + stat.reset(); - assertEquals(0, stat.getCount()); - assertEquals(0, stat.getMinTime()); - assertEquals(0, stat.getMaxTime()); - assertEquals(0, stat.getTotalTime()); + assertEquals(0, stat.getCount()); + assertEquals(0, stat.getMinTime()); + assertEquals(0, stat.getMaxTime()); + assertEquals(0, stat.getTotalTime()); - stat.addTime(100); - assertEquals(1, stat.getCount()); - assertEquals(100, stat.getMinTime()); - assertEquals(100, stat.getMaxTime()); - assertEquals(100, stat.getTotalTime()); + stat.addTime(100); + assertEquals(1, stat.getCount()); + assertEquals(100, stat.getMinTime()); + assertEquals(100, stat.getMaxTime()); + assertEquals(100, stat.getTotalTime()); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/MemoryPropertyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/MemoryPropertyTest.java index 294916e0a1..701f5e7dfa 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/MemoryPropertyTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/MemoryPropertyTest.java @@ -25,51 +25,50 @@ import org.slf4j.LoggerFactory; public class MemoryPropertyTest extends TestCase { - private static final transient Logger LOG = LoggerFactory.getLogger(MemoryPropertyTest.class); - BrokerService broker; + private static final transient Logger LOG = LoggerFactory.getLogger(MemoryPropertyTest.class); + BrokerService broker; + /** + * Sets up a test where the producer and consumer have their own connection. + * + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + // Create broker from resource + LOG.info("Creating broker... "); + broker = createBroker("xbean:org/apache/activemq/memory/activemq.xml"); + LOG.info("Success"); + super.setUp(); + } - /** - * Sets up a test where the producer and consumer have their own connection. - * - * @see junit.framework.TestCase#setUp() - */ - @Override - protected void setUp() throws Exception { - // Create broker from resource - LOG.info("Creating broker... "); - broker = createBroker("xbean:org/apache/activemq/memory/activemq.xml"); - LOG.info("Success"); - super.setUp(); - } + protected BrokerService createBroker(String resource) throws Exception { + return BrokerFactory.createBroker(resource); + } - protected BrokerService createBroker(String resource) throws Exception { - return BrokerFactory.createBroker(resource); - } + /* + * Stops the Broker + * + * @see junit.framework.TestCase#tearDown() + */ + @Override + protected void tearDown() throws Exception { + LOG.info("Closing Broker"); + if (broker != null) { + broker.stop(); + } + LOG.info("Broker closed..."); + } - /* - * Stops the Broker - * - * @see junit.framework.TestCase#tearDown() - */ - @Override - protected void tearDown() throws Exception { - LOG.info("Closing Broker"); - if (broker != null) { - broker.stop(); - } - LOG.info("Broker closed..."); - } + public void testBrokerInitialized() { + assertTrue("We should have a broker", broker != null); - public void testBrokerInitialized() { - assertTrue("We should have a broker", broker != null); + assertEquals("test-broker", broker.getBrokerName()); + assertEquals(1024, broker.getSystemUsage().getMemoryUsage().getLimit()); + assertEquals(34, broker.getSystemUsage().getMemoryUsage().getPercentUsageMinDelta()); - assertEquals("test-broker", broker.getBrokerName()); - assertEquals(1024, broker.getSystemUsage().getMemoryUsage().getLimit()); - assertEquals(34, broker.getSystemUsage().getMemoryUsage().getPercentUsageMinDelta()); - - assertNotNull(broker.getSystemUsage().getStoreUsage().getStore()); - // non persistent broker so no temp storage - assertNull(broker.getSystemUsage().getTempUsage().getStore()); - } + assertNotNull(broker.getSystemUsage().getStoreUsage().getStore()); + // non persistent broker so no temp storage + assertNull(broker.getSystemUsage().getTempUsage().getStore()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/DummyMessage.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/DummyMessage.java index e5823d8943..2cf1f68261 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/DummyMessage.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/DummyMessage.java @@ -20,24 +20,21 @@ import org.apache.activemq.command.ActiveMQMessage; /** * A message implementation which is useful for testing as we can spoof its size - * - * */ public class DummyMessage extends ActiveMQMessage { - private int size; + private int size; - public DummyMessage(int size) { - this.size = size; - } + public DummyMessage(int size) { + this.size = size; + } - public int getSize() { - return size; - } + public int getSize() { + return size; + } + + public String toString() { + return "DummyMessage[id=" + getMessageId() + " size=" + size + "]"; + } - public String toString() { - return "DummyMessage[id=" + getMessageId() + " size=" + size + "]"; - } - - } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/MemoryBufferTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/MemoryBufferTestSupport.java index ea8f0a6c8d..120a934878 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/MemoryBufferTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/MemoryBufferTestSupport.java @@ -26,42 +26,43 @@ import org.slf4j.LoggerFactory; /** * - * + * */ public abstract class MemoryBufferTestSupport extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(MemoryBufferTestSupport.class); - protected MessageBuffer buffer = createMessageBuffer(); - protected MessageQueue qA = buffer.createMessageQueue(); - protected MessageQueue qB = buffer.createMessageQueue(); - protected MessageQueue qC = buffer.createMessageQueue(); - protected int messageCount; + private static final Logger LOG = LoggerFactory.getLogger(MemoryBufferTestSupport.class); - protected abstract MessageBuffer createMessageBuffer(); + protected MessageBuffer buffer = createMessageBuffer(); + protected MessageQueue qA = buffer.createMessageQueue(); + protected MessageQueue qB = buffer.createMessageQueue(); + protected MessageQueue qC = buffer.createMessageQueue(); + protected int messageCount; - protected void setUp() throws Exception { - buffer = createMessageBuffer(); - qA = buffer.createMessageQueue(); - qB = buffer.createMessageQueue(); - qC = buffer.createMessageQueue(); - } + protected abstract MessageBuffer createMessageBuffer(); - protected void dump() { - LOG.info("Dumping current state"); - dumpQueue(qA, "A"); - dumpQueue(qB, "B"); - dumpQueue(qC, "C"); - } + protected void setUp() throws Exception { + buffer = createMessageBuffer(); + qA = buffer.createMessageQueue(); + qB = buffer.createMessageQueue(); + qC = buffer.createMessageQueue(); + } - protected void dumpQueue(MessageQueue queue, String name) { - LOG.info(" " + name + " = " + queue.getList()); - } + protected void dump() { + LOG.info("Dumping current state"); + dumpQueue(qA, "A"); + dumpQueue(qB, "B"); + dumpQueue(qC, "C"); + } - protected ActiveMQMessage createMessage(int size) throws Exception { - DummyMessage answer = new DummyMessage(size); - answer.setIntProperty("counter", ++messageCount); - answer.setJMSMessageID("" + messageCount); - return answer; - } + protected void dumpQueue(MessageQueue queue, String name) { + LOG.info(" " + name + " = " + queue.getList()); + } + + protected ActiveMQMessage createMessage(int size) throws Exception { + DummyMessage answer = new DummyMessage(size); + answer.setIntProperty("counter", ++messageCount); + answer.setJMSMessageID("" + messageCount); + return answer; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/OrderBasedMemoryBufferTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/OrderBasedMemoryBufferTest.java index 2e771f2706..353097636f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/OrderBasedMemoryBufferTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/OrderBasedMemoryBufferTest.java @@ -19,56 +19,54 @@ package org.apache.activemq.memory.buffer; import org.apache.activemq.memory.buffer.MessageBuffer; import org.apache.activemq.memory.buffer.OrderBasedMessageBuffer; - /** * - * + * */ public class OrderBasedMemoryBufferTest extends MemoryBufferTestSupport { - public void testSizeWorks() throws Exception { - qA.add(createMessage(10)); - qB.add(createMessage(10)); - qB.add(createMessage(10)); - qC.add(createMessage(10)); - - dump(); - - assertEquals("buffer size", 40, buffer.getSize()); - assertEquals("qA", 10, qA.getSize()); - assertEquals("qB", 20, qB.getSize()); - assertEquals("qC", 10, qC.getSize()); - - qC.add(createMessage(10)); - - dump(); - - assertEquals("buffer size", 40, buffer.getSize()); - assertEquals("qA", 0, qA.getSize()); - assertEquals("qB", 20, qB.getSize()); - assertEquals("qC", 20, qC.getSize()); + public void testSizeWorks() throws Exception { + qA.add(createMessage(10)); + qB.add(createMessage(10)); + qB.add(createMessage(10)); + qC.add(createMessage(10)); - qB.add(createMessage(10)); - - dump(); - - assertEquals("buffer size", 40, buffer.getSize()); - assertEquals("qA", 0, qA.getSize()); - assertEquals("qB", 20, qB.getSize()); - assertEquals("qC", 20, qC.getSize()); + dump(); - qA.add(createMessage(10)); + assertEquals("buffer size", 40, buffer.getSize()); + assertEquals("qA", 10, qA.getSize()); + assertEquals("qB", 20, qB.getSize()); + assertEquals("qC", 10, qC.getSize()); - dump(); - - assertEquals("buffer size", 40, buffer.getSize()); - assertEquals("qA", 10, qA.getSize()); - assertEquals("qB", 10, qB.getSize()); - assertEquals("qC", 20, qC.getSize()); - } + qC.add(createMessage(10)); - - protected MessageBuffer createMessageBuffer() { - return new OrderBasedMessageBuffer(40); - } + dump(); + + assertEquals("buffer size", 40, buffer.getSize()); + assertEquals("qA", 0, qA.getSize()); + assertEquals("qB", 20, qB.getSize()); + assertEquals("qC", 20, qC.getSize()); + + qB.add(createMessage(10)); + + dump(); + + assertEquals("buffer size", 40, buffer.getSize()); + assertEquals("qA", 0, qA.getSize()); + assertEquals("qB", 20, qB.getSize()); + assertEquals("qC", 20, qC.getSize()); + + qA.add(createMessage(10)); + + dump(); + + assertEquals("buffer size", 40, buffer.getSize()); + assertEquals("qA", 10, qA.getSize()); + assertEquals("qB", 10, qB.getSize()); + assertEquals("qC", 20, qC.getSize()); + } + + protected MessageBuffer createMessageBuffer() { + return new OrderBasedMessageBuffer(40); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/SizeBasedMessageBufferTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/SizeBasedMessageBufferTest.java index ad02821c48..eea4f1fa3f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/SizeBasedMessageBufferTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/SizeBasedMessageBufferTest.java @@ -19,39 +19,37 @@ package org.apache.activemq.memory.buffer; import org.apache.activemq.memory.buffer.MessageBuffer; import org.apache.activemq.memory.buffer.SizeBasedMessageBuffer; - /** * - * + * */ public class SizeBasedMessageBufferTest extends MemoryBufferTestSupport { - public void testSizeWorks() throws Exception { - qA.add(createMessage(10)); - qB.add(createMessage(10)); - qB.add(createMessage(10)); - qC.add(createMessage(10)); - - dump(); - - assertEquals("buffer size", 40, buffer.getSize()); - assertEquals("qA", 10, qA.getSize()); - assertEquals("qB", 20, qB.getSize()); - assertEquals("qC", 10, qC.getSize()); - - // now lets force an eviction - qC.add(createMessage(10)); + public void testSizeWorks() throws Exception { + qA.add(createMessage(10)); + qB.add(createMessage(10)); + qB.add(createMessage(10)); + qC.add(createMessage(10)); - dump(); - - assertEquals("buffer size", 40, buffer.getSize()); - assertEquals("qA", 10, qA.getSize()); - assertEquals("qB", 10, qB.getSize()); - assertEquals("qC", 20, qC.getSize()); - } + dump(); - - protected MessageBuffer createMessageBuffer() { - return new SizeBasedMessageBuffer(40); - } + assertEquals("buffer size", 40, buffer.getSize()); + assertEquals("qA", 10, qA.getSize()); + assertEquals("qB", 20, qB.getSize()); + assertEquals("qC", 10, qC.getSize()); + + // now lets force an eviction + qC.add(createMessage(10)); + + dump(); + + assertEquals("buffer size", 40, buffer.getSize()); + assertEquals("qA", 10, qA.getSize()); + assertEquals("qB", 10, qB.getSize()); + assertEquals("qC", 20, qC.getSize()); + } + + protected MessageBuffer createMessageBuffer() { + return new SizeBasedMessageBuffer(40); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/BrokerNetworkWithStuckMessagesTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/BrokerNetworkWithStuckMessagesTest.java index 9f085b49c5..aa6f9b96fc 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/BrokerNetworkWithStuckMessagesTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/BrokerNetworkWithStuckMessagesTest.java @@ -42,6 +42,7 @@ import javax.jms.Session; import javax.management.ObjectName; import javax.management.openmbean.CompositeData; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerTestSupport; @@ -82,548 +83,549 @@ import org.slf4j.LoggerFactory; */ public class BrokerNetworkWithStuckMessagesTest { - private static final Logger LOG = LoggerFactory.getLogger(BrokerNetworkWithStuckMessagesTest.class); + private static final Logger LOG = LoggerFactory.getLogger(BrokerNetworkWithStuckMessagesTest.class); - private BrokerService localBroker; - private BrokerService remoteBroker; - private BrokerService secondRemoteBroker; - private DemandForwardingBridge bridge; + private BrokerService localBroker; + private BrokerService remoteBroker; + private BrokerService secondRemoteBroker; + private DemandForwardingBridge bridge; - protected Map brokers = new HashMap(); - protected ArrayList connections = new ArrayList(); + protected Map brokers = new HashMap(); + protected ArrayList connections = new ArrayList(); - protected TransportConnector connector; - protected TransportConnector remoteConnector; - protected TransportConnector secondRemoteConnector; + protected TransportConnector connector; + protected TransportConnector remoteConnector; + protected TransportConnector secondRemoteConnector; - protected long idGenerator; - protected int msgIdGenerator; - protected int tempDestGenerator; - protected int maxWait = 4000; - protected String queueName = "TEST"; + protected long idGenerator; + protected int msgIdGenerator; + protected int tempDestGenerator; + protected int maxWait = 4000; + protected String queueName = "TEST"; - protected String amqDomain = "org.apache.activemq"; + protected String amqDomain = "org.apache.activemq"; - @Before - public void setUp() throws Exception { + @Before + public void setUp() throws Exception { - // For those who want visual confirmation: - // Uncomment the following to enable JMX support on a port number to use - // Jconsole to view each broker. You will need to add some calls to - // Thread.sleep() to be able to actually slow things down so that you - // can manually see JMX attrs. -// System.setProperty("com.sun.management.jmxremote", ""); -// System.setProperty("com.sun.management.jmxremote.port", "1099"); -// System.setProperty("com.sun.management.jmxremote.authenticate", "false"); -// System.setProperty("com.sun.management.jmxremote.ssl", "false"); + // For those who want visual confirmation: + // Uncomment the following to enable JMX support on a port number to use + // Jconsole to view each broker. You will need to add some calls to + // Thread.sleep() to be able to actually slow things down so that you + // can manually see JMX attrs. + // System.setProperty("com.sun.management.jmxremote", ""); + // System.setProperty("com.sun.management.jmxremote.port", "1099"); + // System.setProperty("com.sun.management.jmxremote.authenticate", "false"); + // System.setProperty("com.sun.management.jmxremote.ssl", "false"); - // Create the local broker - createBroker(); - // Create the remote broker - createRemoteBroker(); + // Create the local broker + createBroker(); + // Create the remote broker + createRemoteBroker(); - // Remove the activemq-data directory from the creation of the remote broker - FileUtils.deleteDirectory(new File("activemq-data")); + // Remove the activemq-data directory from the creation of the remote broker + FileUtils.deleteDirectory(new File("activemq-data")); - // Create a network bridge between the local and remote brokers so that - // demand-based forwarding can take place - NetworkBridgeConfiguration config = new NetworkBridgeConfiguration(); - config.setBrokerName("local"); - config.setDispatchAsync(false); - config.setDuplex(true); + // Create a network bridge between the local and remote brokers so that + // demand-based forwarding can take place + NetworkBridgeConfiguration config = new NetworkBridgeConfiguration(); + config.setBrokerName("local"); + config.setDispatchAsync(false); + config.setDuplex(true); - Transport localTransport = createTransport(); - Transport remoteTransport = createRemoteTransport(); + Transport localTransport = createTransport(); + Transport remoteTransport = createRemoteTransport(); - // Create a network bridge between the two brokers - bridge = new DemandForwardingBridge(config, localTransport, remoteTransport); - bridge.setBrokerService(localBroker); - bridge.start(); + // Create a network bridge between the two brokers + bridge = new DemandForwardingBridge(config, localTransport, remoteTransport); + bridge.setBrokerService(localBroker); + bridge.start(); + // introduce a second broker/bridge on remote that should not get any messages because of networkTtl=1 + // local <-> remote <-> secondRemote + createSecondRemoteBroker(); + config = new NetworkBridgeConfiguration(); + config.setBrokerName("remote"); + config.setDuplex(true); - // introduce a second broker/bridge on remote that should not get any messages because of networkTtl=1 - // local <-> remote <-> secondRemote - createSecondRemoteBroker(); - config = new NetworkBridgeConfiguration(); - config.setBrokerName("remote"); - config.setDuplex(true); + localTransport = createRemoteTransport(); + remoteTransport = createSecondRemoteTransport(); - localTransport = createRemoteTransport(); - remoteTransport = createSecondRemoteTransport(); + // Create a network bridge between the two brokers + bridge = new DemandForwardingBridge(config, localTransport, remoteTransport); + bridge.setBrokerService(remoteBroker); + bridge.start(); - // Create a network bridge between the two brokers - bridge = new DemandForwardingBridge(config, localTransport, remoteTransport); - bridge.setBrokerService(remoteBroker); - bridge.start(); + waitForBridgeFormation(); + } - waitForBridgeFormation(); - } + protected void waitForBridgeFormation() throws Exception { + for (final BrokerService broker : brokers.values()) { + if (!broker.getNetworkConnectors().isEmpty()) { + // Max wait here is 30 secs + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return !broker.getNetworkConnectors().get(0).activeBridges().isEmpty(); + } + }); + } + } + } - protected void waitForBridgeFormation() throws Exception { - for (final BrokerService broker : brokers.values()) { - if (!broker.getNetworkConnectors().isEmpty()) { - // Max wait here is 30 secs - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return !broker.getNetworkConnectors().get(0).activeBridges().isEmpty(); - }}); + @After + public void tearDown() throws Exception { + bridge.stop(); + localBroker.stop(); + remoteBroker.stop(); + secondRemoteBroker.stop(); + } + + @Test(timeout = 120000) + public void testBrokerNetworkWithStuckMessages() throws Exception { + + int sendNumMessages = 10; + int receiveNumMessages = 5; + + // Create a producer + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo); + + // Create a destination on the local broker + ActiveMQDestination destinationInfo1 = null; + + // Send a 10 messages to the local broker + for (int i = 0; i < sendNumMessages; ++i) { + destinationInfo1 = createDestinationInfo(connection1, connectionInfo1, ActiveMQDestination.QUEUE_TYPE); + connection1.request(createMessage(producerInfo, destinationInfo1, DeliveryMode.NON_PERSISTENT)); + } + + // Ensure that there are 10 messages on the local broker + Object[] messages = browseQueueWithJmx(localBroker); + assertEquals(sendNumMessages, messages.length); + + // Create a synchronous consumer on the remote broker + StubConnection connection2 = createRemoteConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + ActiveMQDestination destinationInfo2 = createDestinationInfo(connection2, connectionInfo2, ActiveMQDestination.QUEUE_TYPE); + final ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destinationInfo2); + connection2.send(consumerInfo2); + + // Consume 5 of the messages from the remote broker and ack them. + for (int i = 0; i < receiveNumMessages; ++i) { + Message message1 = receiveMessage(connection2, 20000); + assertNotNull(message1); + LOG.info("on remote, got: " + message1.getMessageId()); + connection2.send(createAck(consumerInfo2, message1, 1, MessageAck.INDIVIDUAL_ACK_TYPE)); + assertTrue("JMSActiveMQBrokerPath property present and correct", ((ActiveMQMessage) message1).getStringProperty(ActiveMQMessage.BROKER_PATH_PROPERTY).contains(localBroker.getBroker().getBrokerId().toString())); + } + + // Ensure that there are zero messages on the local broker. This tells + // us that those messages have been prefetched to the remote broker + // where the demand exists. + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Object[] result = browseQueueWithJmx(localBroker); + return 0 == result.length; + } + }); + messages = browseQueueWithJmx(localBroker); + assertEquals(0, messages.length); + + // try and pull the messages from remote, should be denied b/c on networkTtl + LOG.info("creating demand on second remote..."); + StubConnection connection3 = createSecondRemoteConnection(); + ConnectionInfo connectionInfo3 = createConnectionInfo(); + SessionInfo sessionInfo3 = createSessionInfo(connectionInfo3); + connection3.send(connectionInfo3); + connection3.send(sessionInfo3); + ActiveMQDestination destinationInfo3 = createDestinationInfo(connection3, connectionInfo3, ActiveMQDestination.QUEUE_TYPE); + final ConsumerInfo consumerInfoS3 = createConsumerInfo(sessionInfo3, destinationInfo3); + connection3.send(consumerInfoS3); + + Message messageExceedingTtl = receiveMessage(connection3, 5000); + if (messageExceedingTtl != null) { + LOG.error("got message on Second remote: " + messageExceedingTtl); + connection3.send(createAck(consumerInfoS3, messageExceedingTtl, 1, MessageAck.INDIVIDUAL_ACK_TYPE)); + } + + LOG.info("Closing consumer on remote"); + // Close the consumer on the remote broker + connection2.send(consumerInfo2.createRemoveCommand()); + // also close connection etc.. so messages get dropped from the local consumer q + connection2.send(connectionInfo2.createRemoveCommand()); + + // There should now be 5 messages stuck on the remote broker + assertTrue("correct stuck message count", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Object[] result = browseQueueWithJmx(remoteBroker); + return 5 == result.length; + } + })); + messages = browseQueueWithJmx(remoteBroker); + assertEquals(5, messages.length); + + assertTrue("can see broker path property", ((String) ((CompositeData) messages[1]).get("BrokerPath")).contains(localBroker.getBroker().getBrokerId().toString())); + + LOG.info("Messages now stuck on remote"); + + // receive again on the origin broker + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destinationInfo1); + connection1.send(consumerInfo1); + LOG.info("create local consumer: " + consumerInfo1); + + Message message1 = receiveMessage(connection1, 20000); + assertNotNull("Expect to get a replay as remote consumer is gone", message1); + connection1.send(createAck(consumerInfo1, message1, 1, MessageAck.INDIVIDUAL_ACK_TYPE)); + LOG.info("acked one message on origin, waiting for all messages to percolate back"); + + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Object[] result = browseQueueWithJmx(localBroker); + return 4 == result.length; + } + }); + messages = browseQueueWithJmx(localBroker); + assertEquals(4, messages.length); + + LOG.info("checking for messages on remote again"); + // messages won't migrate back again till consumer closes + connection2 = createRemoteConnection(); + connectionInfo2 = createConnectionInfo(); + sessionInfo2 = createSessionInfo(connectionInfo2); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + ConsumerInfo consumerInfo3 = createConsumerInfo(sessionInfo2, destinationInfo2); + connection2.send(consumerInfo3); + message1 = receiveMessage(connection2, 20000); + assertNull("Messages have migrated back: " + message1, message1); + + // Consume the last 4 messages from the local broker and ack them just + // to clean up the queue. + int counter = 1; + for (; counter < receiveNumMessages; counter++) { + message1 = receiveMessage(connection1); + LOG.info("local consume of: " + (message1 != null ? message1.getMessageId() : " null")); + connection1.send(createAck(consumerInfo1, message1, 1, MessageAck.INDIVIDUAL_ACK_TYPE)); + } + // Ensure that 5 messages were received + assertEquals(receiveNumMessages, counter); + + // verify all messages consumed + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Object[] result = browseQueueWithJmx(remoteBroker); + return 0 == result.length; + } + }); + messages = browseQueueWithJmx(remoteBroker); + assertEquals(0, messages.length); + + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Object[] result = browseQueueWithJmx(localBroker); + return 0 == result.length; + } + }); + messages = browseQueueWithJmx(localBroker); + assertEquals(0, messages.length); + + // Close the consumer on the remote broker + connection2.send(consumerInfo3.createRemoveCommand()); + + connection1.stop(); + connection2.stop(); + connection3.stop(); + } + + protected BrokerService createBroker() throws Exception { + localBroker = new BrokerService(); + localBroker.setBrokerName("localhost"); + localBroker.setUseJmx(true); + localBroker.setPersistenceAdapter(null); + localBroker.setPersistent(false); + connector = createConnector(); + localBroker.addConnector(connector); + configureBroker(localBroker); + localBroker.start(); + localBroker.waitUntilStarted(); + + localBroker.getManagementContext().setConnectorPort(2221); + + brokers.put(localBroker.getBrokerName(), localBroker); + + return localBroker; + } + + private void configureBroker(BrokerService broker) { + PolicyMap policyMap = new PolicyMap(); + PolicyEntry defaultEntry = new PolicyEntry(); + defaultEntry.setExpireMessagesPeriod(0); + ConditionalNetworkBridgeFilterFactory filterFactory = new ConditionalNetworkBridgeFilterFactory(); + filterFactory.setReplayWhenNoConsumers(true); + defaultEntry.setNetworkBridgeFilterFactory(filterFactory); + policyMap.setDefaultEntry(defaultEntry); + broker.setDestinationPolicy(policyMap); + } + + protected BrokerService createRemoteBroker() throws Exception { + remoteBroker = new BrokerService(); + remoteBroker.setBrokerName("remotehost"); + remoteBroker.setUseJmx(true); + remoteBroker.setPersistenceAdapter(null); + remoteBroker.setPersistent(false); + remoteConnector = createRemoteConnector(); + remoteBroker.addConnector(remoteConnector); + configureBroker(remoteBroker); + remoteBroker.start(); + remoteBroker.waitUntilStarted(); + + remoteBroker.getManagementContext().setConnectorPort(2222); + + brokers.put(remoteBroker.getBrokerName(), remoteBroker); + + return remoteBroker; + } + + protected BrokerService createSecondRemoteBroker() throws Exception { + secondRemoteBroker = new BrokerService(); + secondRemoteBroker.setBrokerName("secondRemotehost"); + secondRemoteBroker.setUseJmx(false); + secondRemoteBroker.setPersistenceAdapter(null); + secondRemoteBroker.setPersistent(false); + secondRemoteConnector = createSecondRemoteConnector(); + secondRemoteBroker.addConnector(secondRemoteConnector); + configureBroker(secondRemoteBroker); + secondRemoteBroker.start(); + secondRemoteBroker.waitUntilStarted(); + + brokers.put(secondRemoteBroker.getBrokerName(), secondRemoteBroker); + + return secondRemoteBroker; + } + + protected Transport createTransport() throws Exception { + Transport transport = TransportFactory.connect(connector.getServer().getConnectURI()); + return transport; + } + + protected Transport createRemoteTransport() throws Exception { + Transport transport = TransportFactory.connect(remoteConnector.getServer().getConnectURI()); + return transport; + } + + protected Transport createSecondRemoteTransport() throws Exception { + Transport transport = TransportFactory.connect(secondRemoteConnector.getServer().getConnectURI()); + return transport; + } + + protected TransportConnector createConnector() throws Exception, IOException, URISyntaxException { + return new TransportConnector(TransportFactory.bind(new URI(getLocalURI()))); + } + + protected TransportConnector createRemoteConnector() throws Exception, IOException, URISyntaxException { + return new TransportConnector(TransportFactory.bind(new URI(getRemoteURI()))); + } + + protected TransportConnector createSecondRemoteConnector() throws Exception, IOException, URISyntaxException { + return new TransportConnector(TransportFactory.bind(new URI(getSecondRemoteURI()))); + } + + protected String getRemoteURI() { + return "vm://remotehost"; + } + + protected String getSecondRemoteURI() { + return "vm://secondRemotehost"; + } + + protected String getLocalURI() { + return "vm://localhost"; + } + + protected StubConnection createConnection() throws Exception { + Transport transport = TransportFactory.connect(connector.getServer().getConnectURI()); + StubConnection connection = new StubConnection(transport); + connections.add(connection); + return connection; + } + + protected StubConnection createRemoteConnection() throws Exception { + Transport transport = TransportFactory.connect(remoteConnector.getServer().getConnectURI()); + StubConnection connection = new StubConnection(transport); + connections.add(connection); + return connection; + } + + protected StubConnection createSecondRemoteConnection() throws Exception { + Transport transport = TransportFactory.connect(secondRemoteConnector.getServer().getConnectURI()); + StubConnection connection = new StubConnection(transport); + connections.add(connection); + return connection; + } + + @SuppressWarnings({"unchecked", "unused"}) + private Object[] browseQueueWithJms(BrokerService broker) throws Exception { + Object[] messages = null; + Connection connection = null; + Session session = null; + + try { + URI brokerUri = connector.getUri(); + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUri.toString()); + connection = connectionFactory.createConnection(); + connection.start(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue destination = session.createQueue(queueName); + QueueBrowser browser = session.createBrowser(destination); + List list = new ArrayList(); + for (Enumeration enumn = browser.getEnumeration(); enumn.hasMoreElements(); ) { + list.add(enumn.nextElement()); + } + messages = list.toArray(); + } + finally { + if (session != null) { + session.close(); + } + if (connection != null) { + connection.close(); + } + } + LOG.info("+Browsed with JMS: " + messages.length); + + return messages; + } + + private Object[] browseQueueWithJmx(BrokerService broker) throws Exception { + Hashtable params = new Hashtable(); + params.put("brokerName", broker.getBrokerName()); + params.put("type", "Broker"); + params.put("destinationType", "Queue"); + params.put("destinationName", queueName); + ObjectName queueObjectName = ObjectName.getInstance(amqDomain, params); + + ManagementContext mgmtCtx = broker.getManagementContext(); + QueueViewMBean queueView = (QueueViewMBean) mgmtCtx.newProxyInstance(queueObjectName, QueueViewMBean.class, true); + + Object[] messages = queueView.browse(); + + LOG.info("+Browsed with JMX: " + messages.length); + + return messages; + } + + protected ConnectionInfo createConnectionInfo() throws Exception { + ConnectionInfo info = new ConnectionInfo(); + info.setConnectionId(new ConnectionId("connection:" + (++idGenerator))); + info.setClientId(info.getConnectionId().getValue()); + return info; + } + + protected SessionInfo createSessionInfo(ConnectionInfo connectionInfo) throws Exception { + SessionInfo info = new SessionInfo(connectionInfo, ++idGenerator); + return info; + } + + protected ProducerInfo createProducerInfo(SessionInfo sessionInfo) throws Exception { + ProducerInfo info = new ProducerInfo(sessionInfo, ++idGenerator); + return info; + } + + protected ConsumerInfo createConsumerInfo(SessionInfo sessionInfo, + ActiveMQDestination destination) throws Exception { + ConsumerInfo info = new ConsumerInfo(sessionInfo, ++idGenerator); + info.setBrowser(false); + info.setDestination(destination); + info.setPrefetchSize(1000); + info.setDispatchAsync(false); + return info; + } + + protected DestinationInfo createTempDestinationInfo(ConnectionInfo connectionInfo, byte destinationType) { + DestinationInfo info = new DestinationInfo(); + info.setConnectionId(connectionInfo.getConnectionId()); + info.setOperationType(DestinationInfo.ADD_OPERATION_TYPE); + info.setDestination(ActiveMQDestination.createDestination(info.getConnectionId() + ":" + (++tempDestGenerator), destinationType)); + return info; + } + + protected ActiveMQDestination createDestinationInfo(StubConnection connection, + ConnectionInfo connectionInfo1, + byte destinationType) throws Exception { + if ((destinationType & ActiveMQDestination.TEMP_MASK) != 0) { + DestinationInfo info = createTempDestinationInfo(connectionInfo1, destinationType); + connection.send(info); + return info.getDestination(); + } + else { + return ActiveMQDestination.createDestination(queueName, destinationType); + } + } + + protected Message createMessage(ProducerInfo producerInfo, ActiveMQDestination destination, int deliveryMode) { + Message message = createMessage(producerInfo, destination); + message.setPersistent(deliveryMode == DeliveryMode.PERSISTENT); + return message; + } + + protected Message createMessage(ProducerInfo producerInfo, ActiveMQDestination destination) { + ActiveMQTextMessage message = new ActiveMQTextMessage(); + message.setMessageId(new MessageId(producerInfo, ++msgIdGenerator)); + message.setDestination(destination); + message.setPersistent(false); + try { + message.setText("Test Message Payload."); + } + catch (MessageNotWriteableException e) { + } + return message; + } + + protected MessageAck createAck(ConsumerInfo consumerInfo, Message msg, int count, byte ackType) { + MessageAck ack = new MessageAck(); + ack.setAckType(ackType); + ack.setConsumerId(consumerInfo.getConsumerId()); + ack.setDestination(msg.getDestination()); + ack.setLastMessageId(msg.getMessageId()); + ack.setMessageCount(count); + return ack; + } + + public Message receiveMessage(StubConnection connection) throws InterruptedException { + return receiveMessage(connection, maxWait); + } + + public Message receiveMessage(StubConnection connection, long timeout) throws InterruptedException { + while (true) { + Object o = connection.getDispatchQueue().poll(timeout, TimeUnit.MILLISECONDS); + + if (o == null) { + return null; + } + if (o instanceof MessageDispatch) { + + MessageDispatch dispatch = (MessageDispatch) o; + if (dispatch.getMessage() == null) { + return null; } - } - } - - @After - public void tearDown() throws Exception { - bridge.stop(); - localBroker.stop(); - remoteBroker.stop(); - secondRemoteBroker.stop(); - } - - @Test(timeout=120000) - public void testBrokerNetworkWithStuckMessages() throws Exception { - - int sendNumMessages = 10; - int receiveNumMessages = 5; - - // Create a producer - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo); - - // Create a destination on the local broker - ActiveMQDestination destinationInfo1 = null; - - // Send a 10 messages to the local broker - for (int i = 0; i < sendNumMessages; ++i) { - destinationInfo1 = createDestinationInfo(connection1, connectionInfo1, ActiveMQDestination.QUEUE_TYPE); - connection1.request(createMessage(producerInfo, destinationInfo1, DeliveryMode.NON_PERSISTENT)); - } - - // Ensure that there are 10 messages on the local broker - Object[] messages = browseQueueWithJmx(localBroker); - assertEquals(sendNumMessages, messages.length); - - // Create a synchronous consumer on the remote broker - StubConnection connection2 = createRemoteConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - ActiveMQDestination destinationInfo2 = - createDestinationInfo(connection2, connectionInfo2, ActiveMQDestination.QUEUE_TYPE); - final ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destinationInfo2); - connection2.send(consumerInfo2); - - // Consume 5 of the messages from the remote broker and ack them. - for (int i = 0; i < receiveNumMessages; ++i) { - Message message1 = receiveMessage(connection2, 20000); - assertNotNull(message1); - LOG.info("on remote, got: " + message1.getMessageId()); - connection2.send(createAck(consumerInfo2, message1, 1, MessageAck.INDIVIDUAL_ACK_TYPE)); - assertTrue("JMSActiveMQBrokerPath property present and correct", - ((ActiveMQMessage)message1).getStringProperty(ActiveMQMessage.BROKER_PATH_PROPERTY).contains(localBroker.getBroker().getBrokerId().toString())); - } - - // Ensure that there are zero messages on the local broker. This tells - // us that those messages have been prefetched to the remote broker - // where the demand exists. - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Object[] result = browseQueueWithJmx(localBroker); - return 0 == result.length; - } - }); - messages = browseQueueWithJmx(localBroker); - assertEquals(0, messages.length); - - // try and pull the messages from remote, should be denied b/c on networkTtl - LOG.info("creating demand on second remote..."); - StubConnection connection3 = createSecondRemoteConnection(); - ConnectionInfo connectionInfo3 = createConnectionInfo(); - SessionInfo sessionInfo3 = createSessionInfo(connectionInfo3); - connection3.send(connectionInfo3); - connection3.send(sessionInfo3); - ActiveMQDestination destinationInfo3 = - createDestinationInfo(connection3, connectionInfo3, ActiveMQDestination.QUEUE_TYPE); - final ConsumerInfo consumerInfoS3 = createConsumerInfo(sessionInfo3, destinationInfo3); - connection3.send(consumerInfoS3); - - Message messageExceedingTtl = receiveMessage(connection3, 5000); - if (messageExceedingTtl != null) { - LOG.error("got message on Second remote: " + messageExceedingTtl); - connection3.send(createAck(consumerInfoS3, messageExceedingTtl, 1, MessageAck.INDIVIDUAL_ACK_TYPE)); - } - - LOG.info("Closing consumer on remote"); - // Close the consumer on the remote broker - connection2.send(consumerInfo2.createRemoveCommand()); - // also close connection etc.. so messages get dropped from the local consumer q - connection2.send(connectionInfo2.createRemoveCommand()); - - // There should now be 5 messages stuck on the remote broker - assertTrue("correct stuck message count", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Object[] result = browseQueueWithJmx(remoteBroker); - return 5 == result.length; - } - })); - messages = browseQueueWithJmx(remoteBroker); - assertEquals(5, messages.length); - - assertTrue("can see broker path property", - ((String)((CompositeData)messages[1]).get("BrokerPath")).contains(localBroker.getBroker().getBrokerId().toString())); - - LOG.info("Messages now stuck on remote"); - - // receive again on the origin broker - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destinationInfo1); - connection1.send(consumerInfo1); - LOG.info("create local consumer: " + consumerInfo1); - - Message message1 = receiveMessage(connection1, 20000); - assertNotNull("Expect to get a replay as remote consumer is gone", message1); - connection1.send(createAck(consumerInfo1, message1, 1, MessageAck.INDIVIDUAL_ACK_TYPE)); - LOG.info("acked one message on origin, waiting for all messages to percolate back"); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Object[] result = browseQueueWithJmx(localBroker); - return 4 == result.length; - } - }); - messages = browseQueueWithJmx(localBroker); - assertEquals(4, messages.length); - - LOG.info("checking for messages on remote again"); - // messages won't migrate back again till consumer closes - connection2 = createRemoteConnection(); - connectionInfo2 = createConnectionInfo(); - sessionInfo2 = createSessionInfo(connectionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - ConsumerInfo consumerInfo3 = createConsumerInfo(sessionInfo2, destinationInfo2); - connection2.send(consumerInfo3); - message1 = receiveMessage(connection2, 20000); - assertNull("Messages have migrated back: " + message1, message1); - - // Consume the last 4 messages from the local broker and ack them just - // to clean up the queue. - int counter = 1; - for (; counter < receiveNumMessages; counter++) { - message1 = receiveMessage(connection1); - LOG.info("local consume of: " + (message1 != null ? message1.getMessageId() : " null")); - connection1.send(createAck(consumerInfo1, message1, 1, MessageAck.INDIVIDUAL_ACK_TYPE)); - } - // Ensure that 5 messages were received - assertEquals(receiveNumMessages, counter); - - // verify all messages consumed - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Object[] result = browseQueueWithJmx(remoteBroker); - return 0 == result.length; - } - }); - messages = browseQueueWithJmx(remoteBroker); - assertEquals(0, messages.length); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Object[] result = browseQueueWithJmx(localBroker); - return 0 == result.length; - } - }); - messages = browseQueueWithJmx(localBroker); - assertEquals(0, messages.length); - - // Close the consumer on the remote broker - connection2.send(consumerInfo3.createRemoveCommand()); - - connection1.stop(); - connection2.stop(); - connection3.stop(); - } - - protected BrokerService createBroker() throws Exception { - localBroker = new BrokerService(); - localBroker.setBrokerName("localhost"); - localBroker.setUseJmx(true); - localBroker.setPersistenceAdapter(null); - localBroker.setPersistent(false); - connector = createConnector(); - localBroker.addConnector(connector); - configureBroker(localBroker); - localBroker.start(); - localBroker.waitUntilStarted(); - - localBroker.getManagementContext().setConnectorPort(2221); - - brokers.put(localBroker.getBrokerName(), localBroker); - - return localBroker; - } - - private void configureBroker(BrokerService broker) { - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setExpireMessagesPeriod(0); - ConditionalNetworkBridgeFilterFactory filterFactory = new ConditionalNetworkBridgeFilterFactory(); - filterFactory.setReplayWhenNoConsumers(true); - defaultEntry.setNetworkBridgeFilterFactory(filterFactory); - policyMap.setDefaultEntry(defaultEntry); - broker.setDestinationPolicy(policyMap); - } - - protected BrokerService createRemoteBroker() throws Exception { - remoteBroker = new BrokerService(); - remoteBroker.setBrokerName("remotehost"); - remoteBroker.setUseJmx(true); - remoteBroker.setPersistenceAdapter(null); - remoteBroker.setPersistent(false); - remoteConnector = createRemoteConnector(); - remoteBroker.addConnector(remoteConnector); - configureBroker(remoteBroker); - remoteBroker.start(); - remoteBroker.waitUntilStarted(); - - remoteBroker.getManagementContext().setConnectorPort(2222); - - brokers.put(remoteBroker.getBrokerName(), remoteBroker); - - return remoteBroker; - } - - protected BrokerService createSecondRemoteBroker() throws Exception { - secondRemoteBroker = new BrokerService(); - secondRemoteBroker.setBrokerName("secondRemotehost"); - secondRemoteBroker.setUseJmx(false); - secondRemoteBroker.setPersistenceAdapter(null); - secondRemoteBroker.setPersistent(false); - secondRemoteConnector = createSecondRemoteConnector(); - secondRemoteBroker.addConnector(secondRemoteConnector); - configureBroker(secondRemoteBroker); - secondRemoteBroker.start(); - secondRemoteBroker.waitUntilStarted(); - - brokers.put(secondRemoteBroker.getBrokerName(), secondRemoteBroker); - - return secondRemoteBroker; - } - - protected Transport createTransport() throws Exception { - Transport transport = TransportFactory.connect(connector.getServer().getConnectURI()); - return transport; - } - - protected Transport createRemoteTransport() throws Exception { - Transport transport = TransportFactory.connect(remoteConnector.getServer().getConnectURI()); - return transport; - } - - protected Transport createSecondRemoteTransport() throws Exception { - Transport transport = TransportFactory.connect(secondRemoteConnector.getServer().getConnectURI()); - return transport; - } - - protected TransportConnector createConnector() throws Exception, IOException, URISyntaxException { - return new TransportConnector(TransportFactory.bind(new URI(getLocalURI()))); - } - - protected TransportConnector createRemoteConnector() throws Exception, IOException, URISyntaxException { - return new TransportConnector(TransportFactory.bind(new URI(getRemoteURI()))); - } - - protected TransportConnector createSecondRemoteConnector() throws Exception, IOException, URISyntaxException { - return new TransportConnector(TransportFactory.bind(new URI(getSecondRemoteURI()))); - } - - protected String getRemoteURI() { - return "vm://remotehost"; - } - - protected String getSecondRemoteURI() { - return "vm://secondRemotehost"; - } - - protected String getLocalURI() { - return "vm://localhost"; - } - - protected StubConnection createConnection() throws Exception { - Transport transport = TransportFactory.connect(connector.getServer().getConnectURI()); - StubConnection connection = new StubConnection(transport); - connections.add(connection); - return connection; - } - - protected StubConnection createRemoteConnection() throws Exception { - Transport transport = TransportFactory.connect(remoteConnector.getServer().getConnectURI()); - StubConnection connection = new StubConnection(transport); - connections.add(connection); - return connection; - } - - protected StubConnection createSecondRemoteConnection() throws Exception { - Transport transport = TransportFactory.connect(secondRemoteConnector.getServer().getConnectURI()); - StubConnection connection = new StubConnection(transport); - connections.add(connection); - return connection; - } - - @SuppressWarnings({ "unchecked", "unused" }) - private Object[] browseQueueWithJms(BrokerService broker) throws Exception { - Object[] messages = null; - Connection connection = null; - Session session = null; - - try { - URI brokerUri = connector.getUri(); - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUri.toString()); - connection = connectionFactory.createConnection(); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue destination = session.createQueue(queueName); - QueueBrowser browser = session.createBrowser(destination); - List list = new ArrayList(); - for (Enumeration enumn = browser.getEnumeration(); enumn.hasMoreElements();) { - list.add(enumn.nextElement()); - } - messages = list.toArray(); - } - finally { - if (session != null) { - session.close(); - } - if (connection != null) { - connection.close(); - } - } - LOG.info("+Browsed with JMS: " + messages.length); - - return messages; - } - - private Object[] browseQueueWithJmx(BrokerService broker) throws Exception { - Hashtable params = new Hashtable(); - params.put("brokerName", broker.getBrokerName()); - params.put("type", "Broker"); - params.put("destinationType", "Queue"); - params.put("destinationName", queueName); - ObjectName queueObjectName = ObjectName.getInstance(amqDomain, params); - - ManagementContext mgmtCtx = broker.getManagementContext(); - QueueViewMBean queueView = (QueueViewMBean)mgmtCtx.newProxyInstance(queueObjectName, QueueViewMBean.class, true); - - Object[] messages = queueView.browse(); - - LOG.info("+Browsed with JMX: " + messages.length); - - return messages; - } - - protected ConnectionInfo createConnectionInfo() throws Exception { - ConnectionInfo info = new ConnectionInfo(); - info.setConnectionId(new ConnectionId("connection:" + (++idGenerator))); - info.setClientId(info.getConnectionId().getValue()); - return info; - } - - protected SessionInfo createSessionInfo(ConnectionInfo connectionInfo) throws Exception { - SessionInfo info = new SessionInfo(connectionInfo, ++idGenerator); - return info; - } - - protected ProducerInfo createProducerInfo(SessionInfo sessionInfo) throws Exception { - ProducerInfo info = new ProducerInfo(sessionInfo, ++idGenerator); - return info; - } - - protected ConsumerInfo createConsumerInfo(SessionInfo sessionInfo, ActiveMQDestination destination) throws Exception { - ConsumerInfo info = new ConsumerInfo(sessionInfo, ++idGenerator); - info.setBrowser(false); - info.setDestination(destination); - info.setPrefetchSize(1000); - info.setDispatchAsync(false); - return info; - } - - protected DestinationInfo createTempDestinationInfo(ConnectionInfo connectionInfo, byte destinationType) { - DestinationInfo info = new DestinationInfo(); - info.setConnectionId(connectionInfo.getConnectionId()); - info.setOperationType(DestinationInfo.ADD_OPERATION_TYPE); - info.setDestination(ActiveMQDestination.createDestination(info.getConnectionId() + ":" + (++tempDestGenerator), destinationType)); - return info; - } - - protected ActiveMQDestination createDestinationInfo(StubConnection connection, ConnectionInfo connectionInfo1, byte destinationType) throws Exception { - if ((destinationType & ActiveMQDestination.TEMP_MASK) != 0) { - DestinationInfo info = createTempDestinationInfo(connectionInfo1, destinationType); - connection.send(info); - return info.getDestination(); - } else { - return ActiveMQDestination.createDestination(queueName, destinationType); - } - } - - protected Message createMessage(ProducerInfo producerInfo, ActiveMQDestination destination, int deliveryMode) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(deliveryMode == DeliveryMode.PERSISTENT); - return message; - } - - protected Message createMessage(ProducerInfo producerInfo, ActiveMQDestination destination) { - ActiveMQTextMessage message = new ActiveMQTextMessage(); - message.setMessageId(new MessageId(producerInfo, ++msgIdGenerator)); - message.setDestination(destination); - message.setPersistent(false); - try { - message.setText("Test Message Payload."); - } catch (MessageNotWriteableException e) { - } - return message; - } - - protected MessageAck createAck(ConsumerInfo consumerInfo, Message msg, int count, byte ackType) { - MessageAck ack = new MessageAck(); - ack.setAckType(ackType); - ack.setConsumerId(consumerInfo.getConsumerId()); - ack.setDestination(msg.getDestination()); - ack.setLastMessageId(msg.getMessageId()); - ack.setMessageCount(count); - return ack; - } - - public Message receiveMessage(StubConnection connection) throws InterruptedException { - return receiveMessage(connection, maxWait); - } - - public Message receiveMessage(StubConnection connection, long timeout) throws InterruptedException { - while (true) { - Object o = connection.getDispatchQueue().poll(timeout, TimeUnit.MILLISECONDS); - - if (o == null) { - return null; - } - if (o instanceof MessageDispatch) { - - MessageDispatch dispatch = (MessageDispatch)o; - if (dispatch.getMessage() == null) { - return null; - } - dispatch.setMessage(dispatch.getMessage().copy()); - dispatch.getMessage().setRedeliveryCounter(dispatch.getRedeliveryCounter()); - return dispatch.getMessage(); - } - } - } + dispatch.setMessage(dispatch.getMessage().copy()); + dispatch.getMessage().setRedeliveryCounter(dispatch.getRedeliveryCounter()); + return dispatch.getMessage(); + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/CheckDuplicateMessagesOnDuplexTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/CheckDuplicateMessagesOnDuplexTest.java index e0b5cd52f5..c60abe659b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/CheckDuplicateMessagesOnDuplexTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/CheckDuplicateMessagesOnDuplexTest.java @@ -32,6 +32,7 @@ import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; import javax.net.ServerSocketFactory; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.TransportConnector; @@ -55,302 +56,305 @@ import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import static org.junit.Assert.*; /** - * * @author x22koe */ public class CheckDuplicateMessagesOnDuplexTest { - private static final Logger log = LoggerFactory.getLogger(CheckDuplicateMessagesOnDuplexTest.class); - private BrokerService localBroker; - private BrokerService remoteBroker; - private ActiveMQConnectionFactory localFactory; - private ActiveMQConnectionFactory remoteFactory; - private Session localSession; - private MessageConsumer consumer; - private Session remoteSession; - private MessageProducer producer; - private Connection remoteConnection; - private Connection localConnection; - private DebugTransportFilter debugTransportFilter; - private boolean useLevelDB = false; + private static final Logger log = LoggerFactory.getLogger(CheckDuplicateMessagesOnDuplexTest.class); + private BrokerService localBroker; + private BrokerService remoteBroker; + private ActiveMQConnectionFactory localFactory; + private ActiveMQConnectionFactory remoteFactory; + private Session localSession; + private MessageConsumer consumer; + private Session remoteSession; + private MessageProducer producer; + private Connection remoteConnection; + private Connection localConnection; + private DebugTransportFilter debugTransportFilter; + private boolean useLevelDB = false; - public CheckDuplicateMessagesOnDuplexTest() { - } + public CheckDuplicateMessagesOnDuplexTest() { + } - @BeforeClass - public static void setUpClass() { - } + @BeforeClass + public static void setUpClass() { + } - @AfterClass - public static void tearDownClass() { - } + @AfterClass + public static void tearDownClass() { + } - @Before - public void setUp() { - } + @Before + public void setUp() { + } - @After - public void tearDown() { - } + @After + public void tearDown() { + } - @Test - public void testConnectionLossBehaviorBeforeAckIsSent() throws Exception { - createBrokers(); - localBroker.deleteAllMessages(); - remoteBroker.deleteAllMessages(); - startBrokers(); - openConnections(); + @Test + public void testConnectionLossBehaviorBeforeAckIsSent() throws Exception { + createBrokers(); + localBroker.deleteAllMessages(); + remoteBroker.deleteAllMessages(); + startBrokers(); + openConnections(); - Thread.sleep(1000); - log.info("\n\n==============================================\nsend hello1\n"); + Thread.sleep(1000); + log.info("\n\n==============================================\nsend hello1\n"); - // simulate network failure between REMOTE and LOCAL just before the reception response is sent back to REMOTE - debugTransportFilter.closeOnResponse = true; + // simulate network failure between REMOTE and LOCAL just before the reception response is sent back to REMOTE + debugTransportFilter.closeOnResponse = true; - producer.send(remoteSession.createTextMessage("hello1")); - Message msg = consumer.receive(30000); + producer.send(remoteSession.createTextMessage("hello1")); + Message msg = consumer.receive(30000); - assertNotNull("expected hello1", msg); - assertEquals("hello1", ((TextMessage) msg).getText()); + assertNotNull("expected hello1", msg); + assertEquals("hello1", ((TextMessage) msg).getText()); - Thread.sleep(1000); - log.info("\n\n------------------------------------------\nsend hello2\n"); + Thread.sleep(1000); + log.info("\n\n------------------------------------------\nsend hello2\n"); - producer.send(remoteSession.createTextMessage("hello2")); - msg = consumer.receive(30000); + producer.send(remoteSession.createTextMessage("hello2")); + msg = consumer.receive(30000); - assertNotNull("expected hello2", msg); - assertEquals("hello2", ((TextMessage) msg).getText()); + assertNotNull("expected hello2", msg); + assertEquals("hello2", ((TextMessage) msg).getText()); - closeLocalConnection(); + closeLocalConnection(); - Thread.sleep(1000); - log.info("\n\n------------------------------------------\nsend hello3\n"); + Thread.sleep(1000); + log.info("\n\n------------------------------------------\nsend hello3\n"); - openLocalConnection(); + openLocalConnection(); - Thread.sleep(1000); + Thread.sleep(1000); - producer.send(remoteSession.createTextMessage("hello3")); - msg = consumer.receive(30000); + producer.send(remoteSession.createTextMessage("hello3")); + msg = consumer.receive(30000); - assertNotNull("expected hello3", msg); - assertEquals("hello3", ((TextMessage) msg).getText()); + assertNotNull("expected hello3", msg); + assertEquals("hello3", ((TextMessage) msg).getText()); - Thread.sleep(1000); - log.info("\n\n==============================================\n\n"); + Thread.sleep(1000); + log.info("\n\n==============================================\n\n"); - closeConnections(); - stopBrokers(); + closeConnections(); + stopBrokers(); - // restart the local broker, which should be empty + // restart the local broker, which should be empty - Thread.sleep(1000); - log.info("\n\n##############################################\n\n"); + Thread.sleep(1000); + log.info("\n\n##############################################\n\n"); - createLocalBroker(); - startLocalBroker(); - openLocalConnection(); + createLocalBroker(); + startLocalBroker(); + openLocalConnection(); - // this should not return the "hello1" message - msg = consumer.receive(1000); + // this should not return the "hello1" message + msg = consumer.receive(1000); - closeLocalConnection(); - stopLocalBroker(); + closeLocalConnection(); + stopLocalBroker(); - assertNull(msg); - } + assertNull(msg); + } - private void createBrokers() throws Exception { - createLocalBroker(); - createRemoteBroker(); - } + private void createBrokers() throws Exception { + createLocalBroker(); + createRemoteBroker(); + } - private void createLocalBroker() throws Exception { - localBroker = new BrokerService(); - localBroker.setBrokerName("LOCAL"); - localBroker.setUseJmx(true); - localBroker.setSchedulePeriodForDestinationPurge(5000); - ManagementContext managementContext = new ManagementContext(); - managementContext.setCreateConnector(false); - localBroker.setManagementContext(managementContext); - PersistenceAdapter persistenceAdapter = persistenceAdapterFactory("target/local"); - localBroker.setPersistenceAdapter(persistenceAdapter); - List transportConnectors = new ArrayList(); - DebugTransportFactory tf = new DebugTransportFactory(); - TransportServer transport = tf.doBind(URI.create("nio://127.0.0.1:23539")); - TransportConnector transportConnector = new TransportConnector(transport); - transportConnector.setName("tc"); - transportConnector.setAuditNetworkProducers(true); - transportConnectors.add(transportConnector); - localBroker.setTransportConnectors(transportConnectors); - } + private void createLocalBroker() throws Exception { + localBroker = new BrokerService(); + localBroker.setBrokerName("LOCAL"); + localBroker.setUseJmx(true); + localBroker.setSchedulePeriodForDestinationPurge(5000); + ManagementContext managementContext = new ManagementContext(); + managementContext.setCreateConnector(false); + localBroker.setManagementContext(managementContext); + PersistenceAdapter persistenceAdapter = persistenceAdapterFactory("target/local"); + localBroker.setPersistenceAdapter(persistenceAdapter); + List transportConnectors = new ArrayList(); + DebugTransportFactory tf = new DebugTransportFactory(); + TransportServer transport = tf.doBind(URI.create("nio://127.0.0.1:23539")); + TransportConnector transportConnector = new TransportConnector(transport); + transportConnector.setName("tc"); + transportConnector.setAuditNetworkProducers(true); + transportConnectors.add(transportConnector); + localBroker.setTransportConnectors(transportConnectors); + } - private void createRemoteBroker() throws Exception { - remoteBroker = new BrokerService(); - remoteBroker.setBrokerName("REMOTE"); - remoteBroker.setUseJmx(true); - remoteBroker.setSchedulePeriodForDestinationPurge(5000); - ManagementContext managementContext = new ManagementContext(); - managementContext.setCreateConnector(false); - remoteBroker.setManagementContext(managementContext); - PersistenceAdapter persistenceAdapter = persistenceAdapterFactory("target/remote"); - remoteBroker.setPersistenceAdapter(persistenceAdapter); - List networkConnectors = new ArrayList(); - DiscoveryNetworkConnector networkConnector = new DiscoveryNetworkConnector(); - networkConnector.setName("to local"); - // set maxInactivityDuration to 0, otherwise the broker restarts while you are in the debugger - networkConnector.setUri(URI.create("static://(tcp://127.0.0.1:23539?wireFormat.maxInactivityDuration=0)")); - networkConnector.setDuplex(true); - //networkConnector.setNetworkTTL(5); - //networkConnector.setDynamicOnly(true); - networkConnector.setAlwaysSyncSend(true); - networkConnector.setDecreaseNetworkConsumerPriority(false); - networkConnector.setPrefetchSize(1); - networkConnector.setCheckDuplicateMessagesOnDuplex(true); - networkConnectors.add(networkConnector); - remoteBroker.setNetworkConnectors(networkConnectors); - } + private void createRemoteBroker() throws Exception { + remoteBroker = new BrokerService(); + remoteBroker.setBrokerName("REMOTE"); + remoteBroker.setUseJmx(true); + remoteBroker.setSchedulePeriodForDestinationPurge(5000); + ManagementContext managementContext = new ManagementContext(); + managementContext.setCreateConnector(false); + remoteBroker.setManagementContext(managementContext); + PersistenceAdapter persistenceAdapter = persistenceAdapterFactory("target/remote"); + remoteBroker.setPersistenceAdapter(persistenceAdapter); + List networkConnectors = new ArrayList(); + DiscoveryNetworkConnector networkConnector = new DiscoveryNetworkConnector(); + networkConnector.setName("to local"); + // set maxInactivityDuration to 0, otherwise the broker restarts while you are in the debugger + networkConnector.setUri(URI.create("static://(tcp://127.0.0.1:23539?wireFormat.maxInactivityDuration=0)")); + networkConnector.setDuplex(true); + //networkConnector.setNetworkTTL(5); + //networkConnector.setDynamicOnly(true); + networkConnector.setAlwaysSyncSend(true); + networkConnector.setDecreaseNetworkConsumerPriority(false); + networkConnector.setPrefetchSize(1); + networkConnector.setCheckDuplicateMessagesOnDuplex(true); + networkConnectors.add(networkConnector); + remoteBroker.setNetworkConnectors(networkConnectors); + } - private void startBrokers() throws Exception { - startLocalBroker(); - startRemoteBroker(); - } + private void startBrokers() throws Exception { + startLocalBroker(); + startRemoteBroker(); + } - private void startLocalBroker() throws Exception { - localBroker.start(); - localBroker.waitUntilStarted(); - } + private void startLocalBroker() throws Exception { + localBroker.start(); + localBroker.waitUntilStarted(); + } - private void startRemoteBroker() throws Exception { - remoteBroker.start(); - remoteBroker.waitUntilStarted(); - } + private void startRemoteBroker() throws Exception { + remoteBroker.start(); + remoteBroker.waitUntilStarted(); + } - private void openConnections() throws JMSException { - openLocalConnection(); - openRemoteConnection(); - } + private void openConnections() throws JMSException { + openLocalConnection(); + openRemoteConnection(); + } - private void openLocalConnection() throws JMSException { - localFactory = new ActiveMQConnectionFactory(localBroker.getVmConnectorURI()); - //localFactory.setSendAcksAsync(false); - localConnection = localFactory.createConnection(); - localConnection.start(); - localSession = localConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = localSession.createConsumer(localSession.createQueue("testqueue")); - } + private void openLocalConnection() throws JMSException { + localFactory = new ActiveMQConnectionFactory(localBroker.getVmConnectorURI()); + //localFactory.setSendAcksAsync(false); + localConnection = localFactory.createConnection(); + localConnection.start(); + localSession = localConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumer = localSession.createConsumer(localSession.createQueue("testqueue")); + } - private void openRemoteConnection() throws JMSException { - remoteFactory = new ActiveMQConnectionFactory(remoteBroker.getVmConnectorURI()); - //remoteFactory.setSendAcksAsync(false); - remoteConnection = remoteFactory.createConnection(); - remoteConnection.start(); - remoteSession = remoteConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = remoteSession.createProducer(remoteSession.createQueue("testqueue")); - } + private void openRemoteConnection() throws JMSException { + remoteFactory = new ActiveMQConnectionFactory(remoteBroker.getVmConnectorURI()); + //remoteFactory.setSendAcksAsync(false); + remoteConnection = remoteFactory.createConnection(); + remoteConnection.start(); + remoteSession = remoteConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer = remoteSession.createProducer(remoteSession.createQueue("testqueue")); + } - private void closeConnections() throws JMSException { - closeLocalConnection(); - closeRemoteConnection(); - } + private void closeConnections() throws JMSException { + closeLocalConnection(); + closeRemoteConnection(); + } - private void closeLocalConnection() throws JMSException { - localConnection.close(); - } + private void closeLocalConnection() throws JMSException { + localConnection.close(); + } - private void closeRemoteConnection() throws JMSException { - remoteConnection.close(); - } + private void closeRemoteConnection() throws JMSException { + remoteConnection.close(); + } - private void stopBrokers() throws Exception { - stopRemoteBroker(); - stopLocalBroker(); - } + private void stopBrokers() throws Exception { + stopRemoteBroker(); + stopLocalBroker(); + } - private void stopLocalBroker() throws Exception { - localBroker.stop(); - localBroker.waitUntilStopped(); - } + private void stopLocalBroker() throws Exception { + localBroker.stop(); + localBroker.waitUntilStopped(); + } - private void stopRemoteBroker() throws Exception { - remoteBroker.stop(); - remoteBroker.waitUntilStopped(); - } + private void stopRemoteBroker() throws Exception { + remoteBroker.stop(); + remoteBroker.waitUntilStopped(); + } - private PersistenceAdapter persistenceAdapterFactory(String path) { - if (useLevelDB) { - return persistenceAdapterFactory_LevelDB(path); - } else { - return persistenceAdapterFactory_KahaDB(path); - } - } + private PersistenceAdapter persistenceAdapterFactory(String path) { + if (useLevelDB) { + return persistenceAdapterFactory_LevelDB(path); + } + else { + return persistenceAdapterFactory_KahaDB(path); + } + } - private PersistenceAdapter persistenceAdapterFactory_KahaDB(String path) { - KahaDBPersistenceAdapter kahaDBPersistenceAdapter = new KahaDBPersistenceAdapter(); - kahaDBPersistenceAdapter.setDirectory(new File(path)); - kahaDBPersistenceAdapter.setIgnoreMissingJournalfiles(true); - kahaDBPersistenceAdapter.setCheckForCorruptJournalFiles(true); - kahaDBPersistenceAdapter.setChecksumJournalFiles(true); - return kahaDBPersistenceAdapter; - } + private PersistenceAdapter persistenceAdapterFactory_KahaDB(String path) { + KahaDBPersistenceAdapter kahaDBPersistenceAdapter = new KahaDBPersistenceAdapter(); + kahaDBPersistenceAdapter.setDirectory(new File(path)); + kahaDBPersistenceAdapter.setIgnoreMissingJournalfiles(true); + kahaDBPersistenceAdapter.setCheckForCorruptJournalFiles(true); + kahaDBPersistenceAdapter.setChecksumJournalFiles(true); + return kahaDBPersistenceAdapter; + } - private PersistenceAdapter persistenceAdapterFactory_LevelDB(String path) { - LevelDBPersistenceAdapter levelDBPersistenceAdapter = new LevelDBPersistenceAdapter(); - levelDBPersistenceAdapter.setDirectory(new File(path)); - return levelDBPersistenceAdapter; - } + private PersistenceAdapter persistenceAdapterFactory_LevelDB(String path) { + LevelDBPersistenceAdapter levelDBPersistenceAdapter = new LevelDBPersistenceAdapter(); + levelDBPersistenceAdapter.setDirectory(new File(path)); + return levelDBPersistenceAdapter; + } - private class DebugTransportFactory extends NIOTransportFactory { + private class DebugTransportFactory extends NIOTransportFactory { - @Override - protected TcpTransportServer createTcpTransportServer(URI location, ServerSocketFactory serverSocketFactory) - throws IOException, URISyntaxException { - return new DebugTransportServer(this, location, serverSocketFactory); - } - } + @Override + protected TcpTransportServer createTcpTransportServer(URI location, + ServerSocketFactory serverSocketFactory) throws IOException, URISyntaxException { + return new DebugTransportServer(this, location, serverSocketFactory); + } + } - private class DebugTransportServer extends TcpTransportServer { + private class DebugTransportServer extends TcpTransportServer { - public DebugTransportServer(TcpTransportFactory transportFactory, URI location, - ServerSocketFactory serverSocketFactory) throws IOException, URISyntaxException { - super(transportFactory, location, serverSocketFactory); - } + public DebugTransportServer(TcpTransportFactory transportFactory, + URI location, + ServerSocketFactory serverSocketFactory) throws IOException, URISyntaxException { + super(transportFactory, location, serverSocketFactory); + } - @Override - protected Transport createTransport(Socket socket, WireFormat format) throws IOException { - Transport transport; - transport = new NIOTransport(format, socket); - debugTransportFilter = new DebugTransportFilter(transport); - return debugTransportFilter; - } - } + @Override + protected Transport createTransport(Socket socket, WireFormat format) throws IOException { + Transport transport; + transport = new NIOTransport(format, socket); + debugTransportFilter = new DebugTransportFilter(transport); + return debugTransportFilter; + } + } - private class DebugTransportFilter extends TransportFilter { + private class DebugTransportFilter extends TransportFilter { - boolean closeOnResponse = false; + boolean closeOnResponse = false; - public DebugTransportFilter(Transport next) { - super(next); - } + public DebugTransportFilter(Transport next) { + super(next); + } - @Override - public void oneway(Object command) throws IOException { - if (closeOnResponse && command instanceof Response) { - closeOnResponse = false; - log.warn("\n\nclosing connection before response is sent\n\n"); - try { - ((NIOTransport) next).stop(); - } catch (Exception ex) { - log.error("couldn't stop niotransport", ex); - } - // don't send response - return; + @Override + public void oneway(Object command) throws IOException { + if (closeOnResponse && command instanceof Response) { + closeOnResponse = false; + log.warn("\n\nclosing connection before response is sent\n\n"); + try { + ((NIOTransport) next).stop(); } - super.oneway(command); - } - } + catch (Exception ex) { + log.error("couldn't stop niotransport", ex); + } + // don't send response + return; + } + super.oneway(command); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/CompressionOverNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/CompressionOverNetworkTest.java index 58af6dc224..370dd35284 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/CompressionOverNetworkTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/CompressionOverNetworkTest.java @@ -59,272 +59,274 @@ import org.springframework.core.io.Resource; public class CompressionOverNetworkTest { - protected static final int RECEIVE_TIMEOUT_MILLS = 10000; - protected static final int MESSAGE_COUNT = 10; - private static final Logger LOG = LoggerFactory.getLogger(CompressionOverNetworkTest.class); + protected static final int RECEIVE_TIMEOUT_MILLS = 10000; + protected static final int MESSAGE_COUNT = 10; + private static final Logger LOG = LoggerFactory.getLogger(CompressionOverNetworkTest.class); - protected AbstractApplicationContext context; - protected Connection localConnection; - protected Connection remoteConnection; - protected BrokerService localBroker; - protected BrokerService remoteBroker; - protected Session localSession; - protected Session remoteSession; - protected ActiveMQDestination included; + protected AbstractApplicationContext context; + protected Connection localConnection; + protected Connection remoteConnection; + protected BrokerService localBroker; + protected BrokerService remoteBroker; + protected Session localSession; + protected Session remoteSession; + protected ActiveMQDestination included; - @Test - public void testCompressedOverCompressedNetwork() throws Exception { + @Test + public void testCompressedOverCompressedNetwork() throws Exception { - ActiveMQConnection localAmqConnection = (ActiveMQConnection) localConnection; - localAmqConnection.setUseCompression(true); + ActiveMQConnection localAmqConnection = (ActiveMQConnection) localConnection; + localAmqConnection.setUseCompression(true); - MessageConsumer consumer1 = remoteSession.createConsumer(included); - MessageProducer producer = localSession.createProducer(included); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + MessageConsumer consumer1 = remoteSession.createConsumer(included); + MessageProducer producer = localSession.createProducer(included); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - waitForConsumerRegistration(localBroker, 1, included); + waitForConsumerRegistration(localBroker, 1, included); - StringBuilder payload = new StringBuilder("test-"); - for (int i = 0; i < 100; ++i) { - payload.append(UUID.randomUUID().toString()); - } + StringBuilder payload = new StringBuilder("test-"); + for (int i = 0; i < 100; ++i) { + payload.append(UUID.randomUUID().toString()); + } - Message test = localSession.createTextMessage(payload.toString()); - producer.send(test); - Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS); - assertNotNull(msg); - ActiveMQTextMessage message = (ActiveMQTextMessage) msg; - assertTrue(message.isCompressed()); - assertEquals(payload.toString(), message.getText()); - } + Message test = localSession.createTextMessage(payload.toString()); + producer.send(test); + Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS); + assertNotNull(msg); + ActiveMQTextMessage message = (ActiveMQTextMessage) msg; + assertTrue(message.isCompressed()); + assertEquals(payload.toString(), message.getText()); + } - @Test - public void testTextMessageCompression() throws Exception { + @Test + public void testTextMessageCompression() throws Exception { - MessageConsumer consumer1 = remoteSession.createConsumer(included); - MessageProducer producer = localSession.createProducer(included); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + MessageConsumer consumer1 = remoteSession.createConsumer(included); + MessageProducer producer = localSession.createProducer(included); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - waitForConsumerRegistration(localBroker, 1, included); + waitForConsumerRegistration(localBroker, 1, included); - StringBuilder payload = new StringBuilder("test-"); - for (int i = 0; i < 100; ++i) { - payload.append(UUID.randomUUID().toString()); - } + StringBuilder payload = new StringBuilder("test-"); + for (int i = 0; i < 100; ++i) { + payload.append(UUID.randomUUID().toString()); + } - Message test = localSession.createTextMessage(payload.toString()); - producer.send(test); - Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS); - assertNotNull(msg); - ActiveMQTextMessage message = (ActiveMQTextMessage) msg; - assertTrue(message.isCompressed()); - assertEquals(payload.toString(), message.getText()); - } + Message test = localSession.createTextMessage(payload.toString()); + producer.send(test); + Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS); + assertNotNull(msg); + ActiveMQTextMessage message = (ActiveMQTextMessage) msg; + assertTrue(message.isCompressed()); + assertEquals(payload.toString(), message.getText()); + } - @Test - public void testBytesMessageCompression() throws Exception { + @Test + public void testBytesMessageCompression() throws Exception { - MessageConsumer consumer1 = remoteSession.createConsumer(included); - MessageProducer producer = localSession.createProducer(included); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + MessageConsumer consumer1 = remoteSession.createConsumer(included); + MessageProducer producer = localSession.createProducer(included); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - waitForConsumerRegistration(localBroker, 1, included); + waitForConsumerRegistration(localBroker, 1, included); - StringBuilder payload = new StringBuilder("test-"); - for (int i = 0; i < 100; ++i) { - payload.append(UUID.randomUUID().toString()); - } + StringBuilder payload = new StringBuilder("test-"); + for (int i = 0; i < 100; ++i) { + payload.append(UUID.randomUUID().toString()); + } - byte[] bytes = payload.toString().getBytes("UTF-8"); + byte[] bytes = payload.toString().getBytes("UTF-8"); - BytesMessage test = localSession.createBytesMessage(); - test.writeBytes(bytes); - producer.send(test); - Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS); - assertNotNull(msg); - ActiveMQBytesMessage message = (ActiveMQBytesMessage) msg; - assertTrue(message.isCompressed()); - assertTrue(message.getContent().getLength() < bytes.length); + BytesMessage test = localSession.createBytesMessage(); + test.writeBytes(bytes); + producer.send(test); + Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS); + assertNotNull(msg); + ActiveMQBytesMessage message = (ActiveMQBytesMessage) msg; + assertTrue(message.isCompressed()); + assertTrue(message.getContent().getLength() < bytes.length); - byte[] result = new byte[bytes.length]; - assertEquals(bytes.length, message.readBytes(result)); - assertEquals(-1, message.readBytes(result)); + byte[] result = new byte[bytes.length]; + assertEquals(bytes.length, message.readBytes(result)); + assertEquals(-1, message.readBytes(result)); - for(int i = 0; i < bytes.length; ++i) { - assertEquals(bytes[i], result[i]); - } - } + for (int i = 0; i < bytes.length; ++i) { + assertEquals(bytes[i], result[i]); + } + } - @Test - public void testStreamMessageCompression() throws Exception { + @Test + public void testStreamMessageCompression() throws Exception { - MessageConsumer consumer1 = remoteSession.createConsumer(included); - MessageProducer producer = localSession.createProducer(included); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + MessageConsumer consumer1 = remoteSession.createConsumer(included); + MessageProducer producer = localSession.createProducer(included); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - waitForConsumerRegistration(localBroker, 1, included); + waitForConsumerRegistration(localBroker, 1, included); - StreamMessage test = localSession.createStreamMessage(); + StreamMessage test = localSession.createStreamMessage(); - for (int i = 0; i < 100; ++i) { - test.writeString("test string: " + i); - } + for (int i = 0; i < 100; ++i) { + test.writeString("test string: " + i); + } - producer.send(test); - Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS); - assertNotNull(msg); - ActiveMQStreamMessage message = (ActiveMQStreamMessage) msg; - assertTrue(message.isCompressed()); + producer.send(test); + Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS); + assertNotNull(msg); + ActiveMQStreamMessage message = (ActiveMQStreamMessage) msg; + assertTrue(message.isCompressed()); - for (int i = 0; i < 100; ++i) { - assertEquals("test string: " + i, message.readString()); - } - } + for (int i = 0; i < 100; ++i) { + assertEquals("test string: " + i, message.readString()); + } + } - @Test - public void testMapMessageCompression() throws Exception { + @Test + public void testMapMessageCompression() throws Exception { - MessageConsumer consumer1 = remoteSession.createConsumer(included); - MessageProducer producer = localSession.createProducer(included); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + MessageConsumer consumer1 = remoteSession.createConsumer(included); + MessageProducer producer = localSession.createProducer(included); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - waitForConsumerRegistration(localBroker, 1, included); + waitForConsumerRegistration(localBroker, 1, included); - MapMessage test = localSession.createMapMessage(); + MapMessage test = localSession.createMapMessage(); - for (int i = 0; i < 100; ++i) { - test.setString(Integer.toString(i), "test string: " + i); - } + for (int i = 0; i < 100; ++i) { + test.setString(Integer.toString(i), "test string: " + i); + } - producer.send(test); - Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS); - assertNotNull(msg); - ActiveMQMapMessage message = (ActiveMQMapMessage) msg; - assertTrue(message.isCompressed()); + producer.send(test); + Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS); + assertNotNull(msg); + ActiveMQMapMessage message = (ActiveMQMapMessage) msg; + assertTrue(message.isCompressed()); - for (int i = 0; i < 100; ++i) { - assertEquals("test string: " + i, message.getString(Integer.toString(i))); - } - } + for (int i = 0; i < 100; ++i) { + assertEquals("test string: " + i, message.getString(Integer.toString(i))); + } + } - @Test - public void testObjectMessageCompression() throws Exception { + @Test + public void testObjectMessageCompression() throws Exception { - MessageConsumer consumer1 = remoteSession.createConsumer(included); - MessageProducer producer = localSession.createProducer(included); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + MessageConsumer consumer1 = remoteSession.createConsumer(included); + MessageProducer producer = localSession.createProducer(included); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - waitForConsumerRegistration(localBroker, 1, included); + waitForConsumerRegistration(localBroker, 1, included); - StringBuilder payload = new StringBuilder("test-"); - for (int i = 0; i < 100; ++i) { - payload.append(UUID.randomUUID().toString()); - } + StringBuilder payload = new StringBuilder("test-"); + for (int i = 0; i < 100; ++i) { + payload.append(UUID.randomUUID().toString()); + } - Message test = localSession.createObjectMessage(payload.toString()); - producer.send(test); - Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS); - assertNotNull(msg); - ActiveMQObjectMessage message = (ActiveMQObjectMessage) msg; - assertTrue(message.isCompressed()); - assertEquals(payload.toString(), message.getObject()); - } + Message test = localSession.createObjectMessage(payload.toString()); + producer.send(test); + Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS); + assertNotNull(msg); + ActiveMQObjectMessage message = (ActiveMQObjectMessage) msg; + assertTrue(message.isCompressed()); + assertEquals(payload.toString(), message.getObject()); + } - private void waitForConsumerRegistration(final BrokerService brokerService, final int min, final ActiveMQDestination destination) throws Exception { - assertTrue("Internal bridge consumers registered in time", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Object[] bridges = brokerService.getNetworkConnectors().get(0).bridges.values().toArray(); - if (bridges.length > 0) { - LOG.info(brokerService + " bridges " + Arrays.toString(bridges)); - DemandForwardingBridgeSupport demandForwardingBridgeSupport = (DemandForwardingBridgeSupport) bridges[0]; - ConcurrentHashMap forwardingBridges = demandForwardingBridgeSupport.getLocalSubscriptionMap(); - LOG.info(brokerService + " bridge " + demandForwardingBridgeSupport + ", localSubs: " + forwardingBridges); - if (!forwardingBridges.isEmpty()) { - for (DemandSubscription demandSubscription : forwardingBridges.values()) { - if (demandSubscription.getLocalInfo().getDestination().equals(destination)) { - LOG.info(brokerService + " DemandSubscription " + demandSubscription + ", size: " + demandSubscription.size()); - return demandSubscription.size() >= min; - } - } - } - } - return false; + private void waitForConsumerRegistration(final BrokerService brokerService, + final int min, + final ActiveMQDestination destination) throws Exception { + assertTrue("Internal bridge consumers registered in time", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Object[] bridges = brokerService.getNetworkConnectors().get(0).bridges.values().toArray(); + if (bridges.length > 0) { + LOG.info(brokerService + " bridges " + Arrays.toString(bridges)); + DemandForwardingBridgeSupport demandForwardingBridgeSupport = (DemandForwardingBridgeSupport) bridges[0]; + ConcurrentHashMap forwardingBridges = demandForwardingBridgeSupport.getLocalSubscriptionMap(); + LOG.info(brokerService + " bridge " + demandForwardingBridgeSupport + ", localSubs: " + forwardingBridges); + if (!forwardingBridges.isEmpty()) { + for (DemandSubscription demandSubscription : forwardingBridges.values()) { + if (demandSubscription.getLocalInfo().getDestination().equals(destination)) { + LOG.info(brokerService + " DemandSubscription " + demandSubscription + ", size: " + demandSubscription.size()); + return demandSubscription.size() >= min; + } + } + } } - })); - } + return false; + } + })); + } - @Before - public void setUp() throws Exception { - doSetUp(true); - } + @Before + public void setUp() throws Exception { + doSetUp(true); + } - @After - public void tearDown() throws Exception { - doTearDown(); - } + @After + public void tearDown() throws Exception { + doTearDown(); + } - protected void doTearDown() throws Exception { - localConnection.close(); - remoteConnection.close(); - localBroker.stop(); - remoteBroker.stop(); - } + protected void doTearDown() throws Exception { + localConnection.close(); + remoteConnection.close(); + localBroker.stop(); + remoteBroker.stop(); + } - protected void doSetUp(boolean deleteAllMessages) throws Exception { - localBroker = createLocalBroker(); - localBroker.setDeleteAllMessagesOnStartup(deleteAllMessages); - localBroker.start(); - localBroker.waitUntilStarted(); - remoteBroker = createRemoteBroker(); - remoteBroker.setDeleteAllMessagesOnStartup(deleteAllMessages); - remoteBroker.start(); - remoteBroker.waitUntilStarted(); - URI localURI = localBroker.getVmConnectorURI(); - ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory(localURI); - fac.setAlwaysSyncSend(true); - fac.setDispatchAsync(false); - localConnection = fac.createConnection(); - localConnection.setClientID("clientId"); - localConnection.start(); - URI remoteURI = remoteBroker.getVmConnectorURI(); - fac = new ActiveMQConnectionFactory(remoteURI); - remoteConnection = fac.createConnection(); - remoteConnection.setClientID("clientId"); - remoteConnection.start(); - included = new ActiveMQTopic("include.test.bar"); - localSession = localConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - remoteSession = remoteConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } + protected void doSetUp(boolean deleteAllMessages) throws Exception { + localBroker = createLocalBroker(); + localBroker.setDeleteAllMessagesOnStartup(deleteAllMessages); + localBroker.start(); + localBroker.waitUntilStarted(); + remoteBroker = createRemoteBroker(); + remoteBroker.setDeleteAllMessagesOnStartup(deleteAllMessages); + remoteBroker.start(); + remoteBroker.waitUntilStarted(); + URI localURI = localBroker.getVmConnectorURI(); + ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory(localURI); + fac.setAlwaysSyncSend(true); + fac.setDispatchAsync(false); + localConnection = fac.createConnection(); + localConnection.setClientID("clientId"); + localConnection.start(); + URI remoteURI = remoteBroker.getVmConnectorURI(); + fac = new ActiveMQConnectionFactory(remoteURI); + remoteConnection = fac.createConnection(); + remoteConnection.setClientID("clientId"); + remoteConnection.start(); + included = new ActiveMQTopic("include.test.bar"); + localSession = localConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + remoteSession = remoteConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + } - protected String getRemoteBrokerURI() { - return "org/apache/activemq/network/remoteBroker.xml"; - } + protected String getRemoteBrokerURI() { + return "org/apache/activemq/network/remoteBroker.xml"; + } - protected String getLocalBrokerURI() { - return "org/apache/activemq/network/localBroker.xml"; - } + protected String getLocalBrokerURI() { + return "org/apache/activemq/network/localBroker.xml"; + } - protected BrokerService createBroker(String uri) throws Exception { - Resource resource = new ClassPathResource(uri); - BrokerFactoryBean factory = new BrokerFactoryBean(resource); - resource = new ClassPathResource(uri); - factory = new BrokerFactoryBean(resource); - factory.afterPropertiesSet(); - BrokerService result = factory.getBroker(); + protected BrokerService createBroker(String uri) throws Exception { + Resource resource = new ClassPathResource(uri); + BrokerFactoryBean factory = new BrokerFactoryBean(resource); + resource = new ClassPathResource(uri); + factory = new BrokerFactoryBean(resource); + factory.afterPropertiesSet(); + BrokerService result = factory.getBroker(); - for (NetworkConnector connector : result.getNetworkConnectors()) { - connector.setUseCompression(true); - } + for (NetworkConnector connector : result.getNetworkConnectors()) { + connector.setUseCompression(true); + } - return result; - } + return result; + } - protected BrokerService createLocalBroker() throws Exception { - return createBroker(getLocalBrokerURI()); - } + protected BrokerService createLocalBroker() throws Exception { + return createBroker(getLocalBrokerURI()); + } - protected BrokerService createRemoteBroker() throws Exception { - return createBroker(getRemoteBrokerURI()); - } + protected BrokerService createRemoteBroker() throws Exception { + return createBroker(getRemoteBrokerURI()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DemandForwardingBridgeFilterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DemandForwardingBridgeFilterTest.java index 087ddd0a45..76ebe70eeb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DemandForwardingBridgeFilterTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DemandForwardingBridgeFilterTest.java @@ -28,184 +28,165 @@ import org.apache.activemq.command.SessionInfo; import java.util.Arrays; - public class DemandForwardingBridgeFilterTest extends NetworkTestSupport { - private DemandForwardingBridge bridge; + private DemandForwardingBridge bridge; - private StubConnection producerConnection; + private StubConnection producerConnection; - private ProducerInfo producerInfo; + private ProducerInfo producerInfo; - private StubConnection consumerConnection; + private StubConnection consumerConnection; - private SessionInfo consumerSessionInfo; + private SessionInfo consumerSessionInfo; - public void testWildcardOnExcludedDestination() throws Exception { + public void testWildcardOnExcludedDestination() throws Exception { - NetworkBridgeConfiguration configuration = getDefaultBridgeConfiguration(); + NetworkBridgeConfiguration configuration = getDefaultBridgeConfiguration(); - configuration.setExcludedDestinations(Arrays.asList(ActiveMQDestination.createDestination("OTHER.>", - ActiveMQDestination.TOPIC_TYPE))); - configuration.setDynamicallyIncludedDestinations(Arrays.asList(ActiveMQDestination.createDestination( - "TEST", ActiveMQDestination.QUEUE_TYPE))); + configuration.setExcludedDestinations(Arrays.asList(ActiveMQDestination.createDestination("OTHER.>", ActiveMQDestination.TOPIC_TYPE))); + configuration.setDynamicallyIncludedDestinations(Arrays.asList(ActiveMQDestination.createDestination("TEST", ActiveMQDestination.QUEUE_TYPE))); - configureAndStartBridge(configuration); + configureAndStartBridge(configuration); - assertReceiveMessageOn("TEST", ActiveMQDestination.QUEUE_TYPE); - assertReceiveNoMessageOn("OTHER.T1", ActiveMQDestination.TOPIC_TYPE); - } + assertReceiveMessageOn("TEST", ActiveMQDestination.QUEUE_TYPE); + assertReceiveNoMessageOn("OTHER.T1", ActiveMQDestination.TOPIC_TYPE); + } - public void testWildcardOnTwoExcludedDestination() throws Exception { - NetworkBridgeConfiguration configuration = getDefaultBridgeConfiguration(); + public void testWildcardOnTwoExcludedDestination() throws Exception { + NetworkBridgeConfiguration configuration = getDefaultBridgeConfiguration(); - configuration.setExcludedDestinations(Arrays.asList(ActiveMQDestination.createDestination("OTHER.>", ActiveMQDestination.QUEUE_TYPE), - ActiveMQDestination.createDestination("TEST.X1", ActiveMQDestination.QUEUE_TYPE))); - configuration.setDynamicallyIncludedDestinations(Arrays.asList(ActiveMQDestination.createDestination( - "TEST.X2", ActiveMQDestination.QUEUE_TYPE))); + configuration.setExcludedDestinations(Arrays.asList(ActiveMQDestination.createDestination("OTHER.>", ActiveMQDestination.QUEUE_TYPE), ActiveMQDestination.createDestination("TEST.X1", ActiveMQDestination.QUEUE_TYPE))); + configuration.setDynamicallyIncludedDestinations(Arrays.asList(ActiveMQDestination.createDestination("TEST.X2", ActiveMQDestination.QUEUE_TYPE))); - configureAndStartBridge(configuration); + configureAndStartBridge(configuration); - assertReceiveMessageOn("TEST.X2", ActiveMQDestination.QUEUE_TYPE); - assertReceiveNoMessageOn("OTHER.X1", ActiveMQDestination.QUEUE_TYPE); - assertReceiveNoMessageOn("TEST.X1", ActiveMQDestination.QUEUE_TYPE); - } + assertReceiveMessageOn("TEST.X2", ActiveMQDestination.QUEUE_TYPE); + assertReceiveNoMessageOn("OTHER.X1", ActiveMQDestination.QUEUE_TYPE); + assertReceiveNoMessageOn("TEST.X1", ActiveMQDestination.QUEUE_TYPE); + } + public void testWildcardOnDynamicallyIncludedDestination() throws Exception { - public void testWildcardOnDynamicallyIncludedDestination() throws Exception { + NetworkBridgeConfiguration configuration = getDefaultBridgeConfiguration(); - NetworkBridgeConfiguration configuration = getDefaultBridgeConfiguration(); + configuration.setDynamicallyIncludedDestinations(Arrays.asList(ActiveMQDestination.createDestination("OTHER.>", ActiveMQDestination.QUEUE_TYPE), ActiveMQDestination.createDestination("TEST.X2", ActiveMQDestination.QUEUE_TYPE))); - configuration.setDynamicallyIncludedDestinations(Arrays.asList(ActiveMQDestination.createDestination("OTHER.>", ActiveMQDestination.QUEUE_TYPE), - ActiveMQDestination.createDestination("TEST.X2", ActiveMQDestination.QUEUE_TYPE))); + configureAndStartBridge(configuration); - configureAndStartBridge(configuration); + assertReceiveMessageOn("OTHER.X1", ActiveMQDestination.QUEUE_TYPE); + assertReceiveMessageOn("TEST.X2", ActiveMQDestination.QUEUE_TYPE); + } + public void testDistinctTopicAndQueue() throws Exception { - assertReceiveMessageOn("OTHER.X1", ActiveMQDestination.QUEUE_TYPE); - assertReceiveMessageOn("TEST.X2", ActiveMQDestination.QUEUE_TYPE); - } + NetworkBridgeConfiguration configuration = getDefaultBridgeConfiguration(); - public void testDistinctTopicAndQueue() throws Exception { + configuration.setExcludedDestinations(Arrays.asList(ActiveMQDestination.createDestination(">", ActiveMQDestination.TOPIC_TYPE))); + configuration.setDynamicallyIncludedDestinations(Arrays.asList(ActiveMQDestination.createDestination(">", ActiveMQDestination.QUEUE_TYPE))); - NetworkBridgeConfiguration configuration = getDefaultBridgeConfiguration(); + configureAndStartBridge(configuration); - configuration.setExcludedDestinations(Arrays.asList(ActiveMQDestination.createDestination(">", - ActiveMQDestination.TOPIC_TYPE))); - configuration.setDynamicallyIncludedDestinations(Arrays.asList(ActiveMQDestination.createDestination( - ">", ActiveMQDestination.QUEUE_TYPE))); + assertReceiveMessageOn("TEST", ActiveMQDestination.QUEUE_TYPE); + assertReceiveNoMessageOn("TEST", ActiveMQDestination.TOPIC_TYPE); + } - configureAndStartBridge(configuration); + public void testListOfExcludedDestinationWithWildcard() throws Exception { - assertReceiveMessageOn("TEST", ActiveMQDestination.QUEUE_TYPE); - assertReceiveNoMessageOn("TEST", ActiveMQDestination.TOPIC_TYPE); - } + NetworkBridgeConfiguration configuration = getDefaultBridgeConfiguration(); - public void testListOfExcludedDestinationWithWildcard() throws Exception { + configuration.setExcludedDestinations(Arrays.asList(ActiveMQDestination.createDestination("OTHER.>", ActiveMQDestination.TOPIC_TYPE), ActiveMQDestination.createDestination("TEST.*", ActiveMQDestination.TOPIC_TYPE))); + configuration.setDynamicallyIncludedDestinations(Arrays.asList(ActiveMQDestination.createDestination("TEST.X1", ActiveMQDestination.QUEUE_TYPE))); - NetworkBridgeConfiguration configuration = getDefaultBridgeConfiguration(); + configureAndStartBridge(configuration); - configuration.setExcludedDestinations(Arrays.asList(ActiveMQDestination.createDestination("OTHER.>", ActiveMQDestination.TOPIC_TYPE), - ActiveMQDestination.createDestination("TEST.*", ActiveMQDestination.TOPIC_TYPE))); - configuration.setDynamicallyIncludedDestinations(Arrays.asList(ActiveMQDestination.createDestination( - "TEST.X1", ActiveMQDestination.QUEUE_TYPE))); + assertReceiveMessageOn("TEST.X1", ActiveMQDestination.QUEUE_TYPE); + assertReceiveNoMessageOn("OTHER.T1", ActiveMQDestination.TOPIC_TYPE); + assertReceiveNoMessageOn("OTHER.T2", ActiveMQDestination.TOPIC_TYPE); + } - configureAndStartBridge(configuration); + private void assertReceiveMessageOn(String destinationName, + byte destinationType) throws Exception, InterruptedException { - assertReceiveMessageOn("TEST.X1", ActiveMQDestination.QUEUE_TYPE); - assertReceiveNoMessageOn("OTHER.T1", ActiveMQDestination.TOPIC_TYPE); - assertReceiveNoMessageOn("OTHER.T2", ActiveMQDestination.TOPIC_TYPE); - } + ActiveMQDestination destination = ActiveMQDestination.createDestination(destinationName, destinationType); - private void assertReceiveMessageOn(String destinationName, byte destinationType) throws Exception, - InterruptedException { + // Send the message to the local broker. + producerConnection.send(createMessage(producerInfo, destination, destinationType)); - ActiveMQDestination destination = ActiveMQDestination.createDestination(destinationName, destinationType); + // Make sure the message was delivered via the remote. + Message m = createConsumerAndReceiveMessage(destination); - // Send the message to the local broker. - producerConnection.send(createMessage(producerInfo, destination, destinationType)); + assertNotNull(m); + } - // Make sure the message was delivered via the remote. - Message m = createConsumerAndReceiveMessage(destination); + private void assertReceiveNoMessageOn(String destinationName, + byte destinationType) throws Exception, InterruptedException { - assertNotNull(m); - } + ActiveMQDestination destination = ActiveMQDestination.createDestination(destinationName, destinationType); - private void assertReceiveNoMessageOn(String destinationName, byte destinationType) throws Exception, - InterruptedException { + // Send the message to the local broker. + producerConnection.send(createMessage(producerInfo, destination, destinationType)); - ActiveMQDestination destination = ActiveMQDestination.createDestination(destinationName, destinationType); + // Make sure the message was delivered via the remote. + Message m = createConsumerAndReceiveMessage(destination); + assertNull(m); + } - // Send the message to the local broker. - producerConnection.send(createMessage(producerInfo, destination, destinationType)); + private Message createConsumerAndReceiveMessage(ActiveMQDestination destination) throws Exception { + // Now create remote consumer that should cause message to move to this + // remote consumer. + ConsumerInfo consumerInfo = createConsumerInfo(consumerSessionInfo, destination); + consumerConnection.send(consumerInfo); - // Make sure the message was delivered via the remote. - Message m = createConsumerAndReceiveMessage(destination); - assertNull(m); - } + Message m = receiveMessage(consumerConnection); + return m; + } - private Message createConsumerAndReceiveMessage(ActiveMQDestination destination) throws Exception { - // Now create remote consumer that should cause message to move to this - // remote consumer. - ConsumerInfo consumerInfo = createConsumerInfo(consumerSessionInfo, destination); - consumerConnection.send(consumerInfo); + protected void setUp() throws Exception { + super.setUp(); - Message m = receiveMessage(consumerConnection); - return m; - } + producerConnection = createConnection(); + ConnectionInfo producerConnectionInfo = createConnectionInfo(); + SessionInfo producerSessionInfo = createSessionInfo(producerConnectionInfo); + producerInfo = createProducerInfo(producerSessionInfo); + producerConnection.send(producerConnectionInfo); + producerConnection.send(producerSessionInfo); + producerConnection.send(producerInfo); - protected void setUp() throws Exception { - super.setUp(); + consumerConnection = createRemoteConnection(); + ConnectionInfo consumerConnectionInfo = createConnectionInfo(); + consumerSessionInfo = createSessionInfo(consumerConnectionInfo); + consumerConnection.send(consumerConnectionInfo); + consumerConnection.send(consumerSessionInfo); + } + protected void tearDown() throws Exception { + bridge.stop(); + super.tearDown(); + } - producerConnection = createConnection(); - ConnectionInfo producerConnectionInfo = createConnectionInfo(); - SessionInfo producerSessionInfo = createSessionInfo(producerConnectionInfo); - producerInfo = createProducerInfo(producerSessionInfo); - producerConnection.send(producerConnectionInfo); - producerConnection.send(producerSessionInfo); - producerConnection.send(producerInfo); + public static Test suite() { + return suite(DemandForwardingBridgeFilterTest.class); + } - consumerConnection = createRemoteConnection(); - ConnectionInfo consumerConnectionInfo = createConnectionInfo(); - consumerSessionInfo = createSessionInfo(consumerConnectionInfo); - consumerConnection.send(consumerConnectionInfo); - consumerConnection.send(consumerSessionInfo); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - protected void tearDown() throws Exception { - bridge.stop(); - super.tearDown(); - } + public NetworkBridgeConfiguration getDefaultBridgeConfiguration() { + NetworkBridgeConfiguration config = new NetworkBridgeConfiguration(); + config.setBrokerName("local"); + config.setDispatchAsync(false); + return config; + } - public static Test suite() { - return suite(DemandForwardingBridgeFilterTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - - public NetworkBridgeConfiguration getDefaultBridgeConfiguration() { - NetworkBridgeConfiguration config = new NetworkBridgeConfiguration(); - config.setBrokerName("local"); - config.setDispatchAsync(false); - return config; - } - - private void configureAndStartBridge(NetworkBridgeConfiguration configuration) throws Exception { - bridge = new DemandForwardingBridge(configuration, createTransport(), createRemoteTransport()); - bridge.setBrokerService(broker); - bridge.setDynamicallyIncludedDestinations(configuration.getDynamicallyIncludedDestinations().toArray( - new ActiveMQDestination[configuration.getDynamicallyIncludedDestinations().size()] - )); - bridge.setExcludedDestinations(configuration.getExcludedDestinations().toArray( - new ActiveMQDestination[configuration.getExcludedDestinations().size()] - )); - bridge.setStaticallyIncludedDestinations(configuration.getStaticallyIncludedDestinations().toArray( - new ActiveMQDestination[configuration.getStaticallyIncludedDestinations().size()] - )); - bridge.start(); - } + private void configureAndStartBridge(NetworkBridgeConfiguration configuration) throws Exception { + bridge = new DemandForwardingBridge(configuration, createTransport(), createRemoteTransport()); + bridge.setBrokerService(broker); + bridge.setDynamicallyIncludedDestinations(configuration.getDynamicallyIncludedDestinations().toArray(new ActiveMQDestination[configuration.getDynamicallyIncludedDestinations().size()])); + bridge.setExcludedDestinations(configuration.getExcludedDestinations().toArray(new ActiveMQDestination[configuration.getExcludedDestinations().size()])); + bridge.setStaticallyIncludedDestinations(configuration.getStaticallyIncludedDestinations().toArray(new ActiveMQDestination[configuration.getStaticallyIncludedDestinations().size()])); + bridge.start(); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DemandForwardingBridgeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DemandForwardingBridgeTest.java index 97943379a4..aac61ff102 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DemandForwardingBridgeTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DemandForwardingBridgeTest.java @@ -33,145 +33,146 @@ import org.apache.activemq.util.Wait; public class DemandForwardingBridgeTest extends NetworkTestSupport { - public ActiveMQDestination destination; - public byte destinationType; - public int deliveryMode; - private DemandForwardingBridge bridge; + public ActiveMQDestination destination; + public byte destinationType; + public int deliveryMode; + private DemandForwardingBridge bridge; - public void initCombosForTestSendThenAddConsumer() { - addCombinationValues("deliveryMode", new Object[] {new Integer(DeliveryMode.NON_PERSISTENT), new Integer(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[] {new Byte(ActiveMQDestination.QUEUE_TYPE)}); - } + public void initCombosForTestSendThenAddConsumer() { + addCombinationValues("deliveryMode", new Object[]{new Integer(DeliveryMode.NON_PERSISTENT), new Integer(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{new Byte(ActiveMQDestination.QUEUE_TYPE)}); + } - public void testSendThenAddConsumer() throws Exception { + public void testSendThenAddConsumer() throws Exception { - // Start a producer on local broker - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo); + // Start a producer on local broker + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo); - destination = createDestinationInfo(connection1, connectionInfo1, destinationType); + destination = createDestinationInfo(connection1, connectionInfo1, destinationType); - // Start a consumer on a remote broker - final StubConnection connection2 = createRemoteConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); + // Start a consumer on a remote broker + final StubConnection connection2 = createRemoteConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); - // Send the message to the local broker. - connection1.send(createMessage(producerInfo, destination, deliveryMode)); + // Send the message to the local broker. + connection1.send(createMessage(producerInfo, destination, deliveryMode)); - // Verify that the message stayed on the local broker. - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - connection1.send(consumerInfo1); - Message m = receiveMessage(connection1); - assertNotNull(m); - // Close consumer to cause the message to rollback. - connection1.send(consumerInfo1.createRemoveCommand()); + // Verify that the message stayed on the local broker. + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + connection1.send(consumerInfo1); + Message m = receiveMessage(connection1); + assertNotNull(m); + // Close consumer to cause the message to rollback. + connection1.send(consumerInfo1.createRemoveCommand()); - final DestinationStatistics destinationStatistics = broker.getDestination(destination).getDestinationStatistics(); - assertEquals("broker dest stat dispatched", 1, destinationStatistics.getDispatched().getCount()); - assertEquals("broker dest stat dequeues", 0, destinationStatistics.getDequeues().getCount()); - assertEquals("broker dest stat forwards", 0, destinationStatistics.getForwards().getCount()); + final DestinationStatistics destinationStatistics = broker.getDestination(destination).getDestinationStatistics(); + assertEquals("broker dest stat dispatched", 1, destinationStatistics.getDispatched().getCount()); + assertEquals("broker dest stat dequeues", 0, destinationStatistics.getDequeues().getCount()); + assertEquals("broker dest stat forwards", 0, destinationStatistics.getForwards().getCount()); - // Now create remote consumer that should cause message to move to this - // remote consumer. - final ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); - connection2.request(consumerInfo2); + // Now create remote consumer that should cause message to move to this + // remote consumer. + final ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); + connection2.request(consumerInfo2); - // Make sure the message was delivered via the remote. - assertTrue("message was received", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message msg = receiveMessage(connection2); - if (msg != null) { - connection2.request(createAck(consumerInfo2, msg, 1, MessageAck.STANDARD_ACK_TYPE)); - return true; - } - - return false; + // Make sure the message was delivered via the remote. + assertTrue("message was received", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Message msg = receiveMessage(connection2); + if (msg != null) { + connection2.request(createAck(consumerInfo2, msg, 1, MessageAck.STANDARD_ACK_TYPE)); + return true; } - })); - assertTrue("broker dest stat forwards", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return 1 == destinationStatistics.getForwards().getCount(); - } - })); + return false; + } + })); - assertEquals("broker dest stat dequeues", 1, destinationStatistics.getDequeues().getCount()); - } + assertTrue("broker dest stat forwards", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return 1 == destinationStatistics.getForwards().getCount(); + } + })); - public void initCombosForTestAddConsumerThenSend() { - addCombinationValues("deliveryMode", new Object[] {new Integer(DeliveryMode.NON_PERSISTENT), new Integer(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[] {new Byte(ActiveMQDestination.QUEUE_TYPE), new Byte(ActiveMQDestination.TOPIC_TYPE)}); - } + assertEquals("broker dest stat dequeues", 1, destinationStatistics.getDequeues().getCount()); + } - public void testAddConsumerThenSend() throws Exception { + public void initCombosForTestAddConsumerThenSend() { + addCombinationValues("deliveryMode", new Object[]{new Integer(DeliveryMode.NON_PERSISTENT), new Integer(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{new Byte(ActiveMQDestination.QUEUE_TYPE), new Byte(ActiveMQDestination.TOPIC_TYPE)}); + } - // Start a producer on local broker - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo); + public void testAddConsumerThenSend() throws Exception { - destination = createDestinationInfo(connection1, connectionInfo1, destinationType); + // Start a producer on local broker + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo); - // Start a consumer on a remote broker - StubConnection connection2 = createRemoteConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo2, destination); - connection2.send(consumerInfo); + destination = createDestinationInfo(connection1, connectionInfo1, destinationType); - // Give demand forwarding bridge a chance to finish forwarding the - // subscriptions. - try { - Thread.sleep(1000); - } catch (InterruptedException ie) { - ie.printStackTrace(); - } + // Start a consumer on a remote broker + StubConnection connection2 = createRemoteConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo2, destination); + connection2.send(consumerInfo); - // Send the message to the local boker. - connection1.request(createMessage(producerInfo, destination, deliveryMode)); - // Make sure the message was delivered via the remote. - receiveMessage(connection2); - } + // Give demand forwarding bridge a chance to finish forwarding the + // subscriptions. + try { + Thread.sleep(1000); + } + catch (InterruptedException ie) { + ie.printStackTrace(); + } - @Override - protected void setUp() throws Exception { - super.setUp(); - NetworkBridgeConfiguration config = new NetworkBridgeConfiguration(); - config.setBrokerName("local"); - config.setDispatchAsync(false); - bridge = new DemandForwardingBridge(config, createTransport(), createRemoteTransport()); - bridge.setBrokerService(broker); - bridge.start(); - } + // Send the message to the local boker. + connection1.request(createMessage(producerInfo, destination, deliveryMode)); + // Make sure the message was delivered via the remote. + receiveMessage(connection2); + } - @Override - protected void tearDown() throws Exception { - bridge.stop(); - super.tearDown(); - } + @Override + protected void setUp() throws Exception { + super.setUp(); + NetworkBridgeConfiguration config = new NetworkBridgeConfiguration(); + config.setBrokerName("local"); + config.setDispatchAsync(false); + bridge = new DemandForwardingBridge(config, createTransport(), createRemoteTransport()); + bridge.setBrokerService(broker); + bridge.start(); + } - public static Test suite() { - return suite(DemandForwardingBridgeTest.class); - } + @Override + protected void tearDown() throws Exception { + bridge.stop(); + super.tearDown(); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static Test suite() { + return suite(DemandForwardingBridgeTest.class); + } + + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DuplexNetworkMBeanTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DuplexNetworkMBeanTest.java index 213d4aeb63..cba6ff91cc 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DuplexNetworkMBeanTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DuplexNetworkMBeanTest.java @@ -32,140 +32,145 @@ import org.slf4j.LoggerFactory; public class DuplexNetworkMBeanTest { - protected static final Logger LOG = LoggerFactory.getLogger(DuplexNetworkMBeanTest.class); - protected final int numRestarts = 3; + protected static final Logger LOG = LoggerFactory.getLogger(DuplexNetworkMBeanTest.class); + protected final int numRestarts = 3; - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("broker"); - broker.addConnector("tcp://localhost:61617?transport.reuseAddress=true"); + protected BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setBrokerName("broker"); + broker.addConnector("tcp://localhost:61617?transport.reuseAddress=true"); - return broker; - } + return broker; + } - protected BrokerService createNetworkedBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("networkedBroker"); - broker.addConnector("tcp://localhost:62617?transport.reuseAddress=true"); - NetworkConnector networkConnector = broker.addNetworkConnector("static:(tcp://localhost:61617?wireFormat.maxInactivityDuration=500)?useExponentialBackOff=false"); - networkConnector.setDuplex(true); - return broker; - } + protected BrokerService createNetworkedBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setBrokerName("networkedBroker"); + broker.addConnector("tcp://localhost:62617?transport.reuseAddress=true"); + NetworkConnector networkConnector = broker.addNetworkConnector("static:(tcp://localhost:61617?wireFormat.maxInactivityDuration=500)?useExponentialBackOff=false"); + networkConnector.setDuplex(true); + return broker; + } - @Test - public void testMbeanPresenceOnNetworkBrokerRestart() throws Exception { - BrokerService broker = createBroker(); - try { - broker.start(); - assertEquals(1, countMbeans(broker, "connector", 30000)); - assertEquals(0, countMbeans(broker, "connectionName")); - BrokerService networkedBroker = null; - for (int i=0; i mbeans = null; - int count = 0; - do { - if (timeout > 0) { - Thread.sleep(100); + BrokerService broker = null; + for (int i = 0; i < numRestarts; i++) { + broker = createBroker(); + try { + broker.start(); + assertEquals(1, countMbeans(networkedBroker, "networkBridge", 5000)); + assertEquals("restart number: " + i, 2, countMbeans(broker, "connectionName", 10000)); } - - LOG.info("Query name: " + beanName); - mbeans = broker.getManagementContext().queryNames(beanName, null); - if (mbeans != null) { - count = mbeans.size(); - } else { - logAllMbeans(broker); + finally { + broker.stop(); + broker.waitUntilStopped(); } - } while ((mbeans == null || mbeans.isEmpty()) && expiryTime > System.currentTimeMillis()); + assertEquals(0, countMbeans(broker, "stopped")); + } - // If port 1099 is in use when the Broker starts, starting the jmx connector - // will fail. So, if we have no mbsc to query, skip the test. - if (timeout > 0) { - assumeNotNull(mbeans); - } + assertEquals(1, countMbeans(networkedBroker, "connector=networkConnectors")); + assertEquals(0, countMbeans(networkedBroker, "connectionName")); + assertEquals(0, countMbeans(broker, "connectionName")); + } + finally { + networkedBroker.stop(); + networkedBroker.waitUntilStopped(); + } + } - return count; - } + private int countMbeans(BrokerService broker, String type) throws Exception { + return countMbeans(broker, type, 0); + } - private void logAllMbeans(BrokerService broker) throws MalformedURLException { - try { - // trace all existing MBeans - Set all = broker.getManagementContext().queryNames(null, null); - LOG.info("Total MBean count=" + all.size()); - for (Object o : all) { - ObjectInstance bean = (ObjectInstance)o; - LOG.info(bean.getObjectName().toString()); - } - } catch (Exception ignored) { - LOG.warn("getMBeanServer ex: " + ignored); - } - } + private int countMbeans(BrokerService broker, String type, int timeout) throws Exception { + final long expiryTime = System.currentTimeMillis() + timeout; + + if (!type.contains("=")) { + type = type + "=*"; + } + + final ObjectName beanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=" + broker.getBrokerName() + "," + type + ",*"); + Set mbeans = null; + int count = 0; + do { + if (timeout > 0) { + Thread.sleep(100); + } + + LOG.info("Query name: " + beanName); + mbeans = broker.getManagementContext().queryNames(beanName, null); + if (mbeans != null) { + count = mbeans.size(); + } + else { + logAllMbeans(broker); + } + } while ((mbeans == null || mbeans.isEmpty()) && expiryTime > System.currentTimeMillis()); + + // If port 1099 is in use when the Broker starts, starting the jmx connector + // will fail. So, if we have no mbsc to query, skip the test. + if (timeout > 0) { + assumeNotNull(mbeans); + } + + return count; + } + + private void logAllMbeans(BrokerService broker) throws MalformedURLException { + try { + // trace all existing MBeans + Set all = broker.getManagementContext().queryNames(null, null); + LOG.info("Total MBean count=" + all.size()); + for (Object o : all) { + ObjectInstance bean = (ObjectInstance) o; + LOG.info(bean.getObjectName().toString()); + } + } + catch (Exception ignored) { + LOG.warn("getMBeanServer ex: " + ignored); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DuplexNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DuplexNetworkTest.java index 3afa7d13f8..ddfba7d91a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DuplexNetworkTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DuplexNetworkTest.java @@ -28,33 +28,33 @@ import org.junit.Test; public class DuplexNetworkTest extends SimpleNetworkTest { - @Override - protected String getLocalBrokerURI() { - return "org/apache/activemq/network/duplexLocalBroker.xml"; - } + @Override + protected String getLocalBrokerURI() { + return "org/apache/activemq/network/duplexLocalBroker.xml"; + } - @Override - protected BrokerService createRemoteBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("remoteBroker"); - broker.addConnector("tcp://localhost:61617"); - return broker; - } + @Override + protected BrokerService createRemoteBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setBrokerName("remoteBroker"); + broker.addConnector("tcp://localhost:61617"); + return broker; + } - @Test - public void testTempQueues() throws Exception { - TemporaryQueue temp = localSession.createTemporaryQueue(); - MessageProducer producer = localSession.createProducer(temp); - producer.send(localSession.createTextMessage("test")); - Thread.sleep(100); - assertEquals("Destination not created", 1, remoteBroker.getAdminView().getTemporaryQueues().length); - temp.delete(); + @Test + public void testTempQueues() throws Exception { + TemporaryQueue temp = localSession.createTemporaryQueue(); + MessageProducer producer = localSession.createProducer(temp); + producer.send(localSession.createTextMessage("test")); + Thread.sleep(100); + assertEquals("Destination not created", 1, remoteBroker.getAdminView().getTemporaryQueues().length); + temp.delete(); - assertTrue("Destination not deleted", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return 0 == remoteBroker.getAdminView().getTemporaryQueues().length; - } - })); - } + assertTrue("Destination not deleted", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return 0 == remoteBroker.getAdminView().getTemporaryQueues().length; + } + })); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DynamicallyIncludedDestinationsDuplexNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DynamicallyIncludedDestinationsDuplexNetworkTest.java index 3dd8be6c41..1f7cbb5ad2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DynamicallyIncludedDestinationsDuplexNetworkTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DynamicallyIncludedDestinationsDuplexNetworkTest.java @@ -37,81 +37,78 @@ import org.junit.Test; */ public class DynamicallyIncludedDestinationsDuplexNetworkTest extends SimpleNetworkTest { - private static final int REMOTE_BROKER_TCP_PORT = 61617; + private static final int REMOTE_BROKER_TCP_PORT = 61617; - @Override - protected String getLocalBrokerURI() { - return "org/apache/activemq/network/duplexDynamicIncludedDestLocalBroker.xml"; - } + @Override + protected String getLocalBrokerURI() { + return "org/apache/activemq/network/duplexDynamicIncludedDestLocalBroker.xml"; + } - @Override - protected BrokerService createRemoteBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("remoteBroker"); - broker.addConnector("tcp://localhost:" + REMOTE_BROKER_TCP_PORT); - return broker; - } + @Override + protected BrokerService createRemoteBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setBrokerName("remoteBroker"); + broker.addConnector("tcp://localhost:" + REMOTE_BROKER_TCP_PORT); + return broker; + } - // we have to override this, because with dynamicallyIncludedDestinations working properly - // (see https://issues.apache.org/jira/browse/AMQ-4209) you can't get request/response - // with temps working (there is no wild card like there is for staticallyIncludedDest) - // - @Override - public void testRequestReply() throws Exception { + // we have to override this, because with dynamicallyIncludedDestinations working properly + // (see https://issues.apache.org/jira/browse/AMQ-4209) you can't get request/response + // with temps working (there is no wild card like there is for staticallyIncludedDest) + // + @Override + public void testRequestReply() throws Exception { - } + } - @Test - public void testTempQueues() throws Exception { - TemporaryQueue temp = localSession.createTemporaryQueue(); - MessageProducer producer = localSession.createProducer(temp); - producer.send(localSession.createTextMessage("test")); - Thread.sleep(100); - assertEquals("Destination not created", 1, remoteBroker.getAdminView().getTemporaryQueues().length); - temp.delete(); - Thread.sleep(100); - assertEquals("Destination not deleted", 0, remoteBroker.getAdminView().getTemporaryQueues().length); - } + @Test + public void testTempQueues() throws Exception { + TemporaryQueue temp = localSession.createTemporaryQueue(); + MessageProducer producer = localSession.createProducer(temp); + producer.send(localSession.createTextMessage("test")); + Thread.sleep(100); + assertEquals("Destination not created", 1, remoteBroker.getAdminView().getTemporaryQueues().length); + temp.delete(); + Thread.sleep(100); + assertEquals("Destination not deleted", 0, remoteBroker.getAdminView().getTemporaryQueues().length); + } - @Test - public void testDynamicallyIncludedDestinationsForDuplex() throws Exception{ - // Once the bridge is set up, we should see the filter used for the duplex end of the bridge - // only subscribe to the specific destinations included in the list - // so let's test that the filter is correct, let's also test the subscription on the localbroker - // is correct + @Test + public void testDynamicallyIncludedDestinationsForDuplex() throws Exception { + // Once the bridge is set up, we should see the filter used for the duplex end of the bridge + // only subscribe to the specific destinations included in the list + // so let's test that the filter is correct, let's also test the subscription on the localbroker + // is correct - // the bridge on the remote broker has the correct filter - TransportConnection bridgeConnection = getDuplexBridgeConnectionFromRemote(); - assertNotNull(bridgeConnection); - DemandForwardingBridge duplexBridge = getDuplexBridgeFromConnection(bridgeConnection); - assertNotNull(duplexBridge); - NetworkBridgeConfiguration configuration = getConfigurationFromNetworkBridge(duplexBridge); - assertNotNull(configuration); - assertFalse("This destinationFilter does not include ONLY the destinations specified in dynamicallyIncludedDestinations", - configuration.getDestinationFilter().equals(AdvisorySupport.CONSUMER_ADVISORY_TOPIC_PREFIX + ">")); - assertEquals("There are other patterns in the destinationFilter that shouldn't be there", - "ActiveMQ.Advisory.Consumer.Queue.include.test.foo,ActiveMQ.Advisory.Consumer.Topic.include.test.bar", - configuration.getDestinationFilter()); - } + // the bridge on the remote broker has the correct filter + TransportConnection bridgeConnection = getDuplexBridgeConnectionFromRemote(); + assertNotNull(bridgeConnection); + DemandForwardingBridge duplexBridge = getDuplexBridgeFromConnection(bridgeConnection); + assertNotNull(duplexBridge); + NetworkBridgeConfiguration configuration = getConfigurationFromNetworkBridge(duplexBridge); + assertNotNull(configuration); + assertFalse("This destinationFilter does not include ONLY the destinations specified in dynamicallyIncludedDestinations", configuration.getDestinationFilter().equals(AdvisorySupport.CONSUMER_ADVISORY_TOPIC_PREFIX + ">")); + assertEquals("There are other patterns in the destinationFilter that shouldn't be there", "ActiveMQ.Advisory.Consumer.Queue.include.test.foo,ActiveMQ.Advisory.Consumer.Topic.include.test.bar", configuration.getDestinationFilter()); + } - private NetworkBridgeConfiguration getConfigurationFromNetworkBridge(DemandForwardingBridgeSupport duplexBridge) throws NoSuchFieldException, IllegalAccessException { - Field f = DemandForwardingBridgeSupport.class.getDeclaredField("configuration"); - f.setAccessible(true); - NetworkBridgeConfiguration configuration = (NetworkBridgeConfiguration) f.get(duplexBridge); - return configuration; - } + private NetworkBridgeConfiguration getConfigurationFromNetworkBridge(DemandForwardingBridgeSupport duplexBridge) throws NoSuchFieldException, IllegalAccessException { + Field f = DemandForwardingBridgeSupport.class.getDeclaredField("configuration"); + f.setAccessible(true); + NetworkBridgeConfiguration configuration = (NetworkBridgeConfiguration) f.get(duplexBridge); + return configuration; + } - private DemandForwardingBridge getDuplexBridgeFromConnection(TransportConnection bridgeConnection) throws NoSuchFieldException, IllegalAccessException { - Field f = TransportConnection.class.getDeclaredField("duplexBridge"); - f.setAccessible(true); - DemandForwardingBridge bridge = (DemandForwardingBridge) f.get(bridgeConnection); - return bridge; - } + private DemandForwardingBridge getDuplexBridgeFromConnection(TransportConnection bridgeConnection) throws NoSuchFieldException, IllegalAccessException { + Field f = TransportConnection.class.getDeclaredField("duplexBridge"); + f.setAccessible(true); + DemandForwardingBridge bridge = (DemandForwardingBridge) f.get(bridgeConnection); + return bridge; + } - public TransportConnection getDuplexBridgeConnectionFromRemote() { - TransportConnector transportConnector = remoteBroker.getTransportConnectorByScheme("tcp"); - CopyOnWriteArrayList transportConnections = transportConnector.getConnections(); - TransportConnection duplexBridgeConnectionFromRemote = transportConnections.get(0); - return duplexBridgeConnectionFromRemote; - } + public TransportConnection getDuplexBridgeConnectionFromRemote() { + TransportConnector transportConnector = remoteBroker.getTransportConnectorByScheme("tcp"); + CopyOnWriteArrayList transportConnections = transportConnector.getConnections(); + TransportConnection duplexBridgeConnectionFromRemote = transportConnections.get(0); + return duplexBridgeConnectionFromRemote; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/FailoverStaticNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/FailoverStaticNetworkTest.java index 4113f14c44..8fcc6fadfd 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/FailoverStaticNetworkTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/FailoverStaticNetworkTest.java @@ -57,411 +57,417 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FailoverStaticNetworkTest { - protected static final Logger LOG = LoggerFactory.getLogger(FailoverStaticNetworkTest.class); - private final static String DESTINATION_NAME = "testQ"; - protected BrokerService brokerA; - protected BrokerService brokerA1; - protected BrokerService brokerB; - protected BrokerService brokerC; + protected static final Logger LOG = LoggerFactory.getLogger(FailoverStaticNetworkTest.class); + private final static String DESTINATION_NAME = "testQ"; + protected BrokerService brokerA; + protected BrokerService brokerA1; + protected BrokerService brokerB; + protected BrokerService brokerC; - private SslContext sslContext; + private SslContext sslContext; - protected BrokerService createBroker(String scheme, String listenPort, String[] networkToPorts) throws Exception { - return createBroker(scheme, listenPort, networkToPorts, null); - } + protected BrokerService createBroker(String scheme, String listenPort, String[] networkToPorts) throws Exception { + return createBroker(scheme, listenPort, networkToPorts, null); + } - protected BrokerService createBroker(String scheme, String listenPort, String[] networkToPorts, - HashMap networkProps) throws Exception { - BrokerService broker = new BrokerService(); - broker.getManagementContext().setCreateConnector(false); - broker.setSslContext(sslContext); - broker.setDeleteAllMessagesOnStartup(true); - broker.setBrokerName("Broker_" + listenPort); - // lazy init listener on broker start - TransportConnector transportConnector = new TransportConnector(); - transportConnector.setUri(new URI(scheme + "://localhost:" + listenPort)); - List transportConnectors = new ArrayList(); - transportConnectors.add(transportConnector); - broker.setTransportConnectors(transportConnectors); - if (networkToPorts != null && networkToPorts.length > 0) { - StringBuilder builder = new StringBuilder("static:(failover:(" + scheme + "://localhost:"); - builder.append(networkToPorts[0]); - for (int i=1;i networkProps) throws Exception { + BrokerService broker = new BrokerService(); + broker.getManagementContext().setCreateConnector(false); + broker.setSslContext(sslContext); + broker.setDeleteAllMessagesOnStartup(true); + broker.setBrokerName("Broker_" + listenPort); + // lazy init listener on broker start + TransportConnector transportConnector = new TransportConnector(); + transportConnector.setUri(new URI(scheme + "://localhost:" + listenPort)); + List transportConnectors = new ArrayList(); + transportConnectors.add(transportConnector); + broker.setTransportConnectors(transportConnectors); + if (networkToPorts != null && networkToPorts.length > 0) { + StringBuilder builder = new StringBuilder("static:(failover:(" + scheme + "://localhost:"); + builder.append(networkToPorts[0]); + for (int i = 1; i < networkToPorts.length; i++) { + builder.append("," + scheme + "://localhost:" + networkToPorts[i]); + } + // limit the reconnects in case of initial random connection to slave + // leaving randomize on verifies that this config is picked up + builder.append(")?maxReconnectAttempts=0)?useExponentialBackOff=false"); + NetworkConnector nc = broker.addNetworkConnector(builder.toString()); + if (networkProps != null) { + IntrospectionSupport.setProperties(nc, networkProps); + } + } + return broker; + } + + private BrokerService createBroker(String listenPort, String dataDir) throws Exception { + BrokerService broker = new BrokerService(); + broker.setUseJmx(false); + broker.getManagementContext().setCreateConnector(false); + broker.setBrokerName("Broker_Shared"); + // lazy create transport connector on start completion + TransportConnector connector = new TransportConnector(); + connector.setUri(new URI("tcp://localhost:" + listenPort)); + broker.addConnector(connector); + broker.setDataDirectory(dataDir); + return broker; + } + + @Before + public void setUp() throws Exception { + KeyManager[] km = SslBrokerServiceTest.getKeyManager(); + TrustManager[] tm = SslBrokerServiceTest.getTrustManager(); + sslContext = new SslContext(km, tm, null); + } + + @After + public void tearDown() throws Exception { + brokerB.stop(); + brokerB.waitUntilStopped(); + + brokerA.stop(); + brokerA.waitUntilStopped(); + + if (brokerA1 != null) { + brokerA1.stop(); + brokerA1.waitUntilStopped(); + } + + if (brokerC != null) { + brokerC.stop(); + brokerC.waitUntilStopped(); + } + } + + @Test + public void testSendReceiveAfterReconnect() throws Exception { + brokerA = createBroker("tcp", "61617", null); + brokerA.start(); + brokerB = createBroker("tcp", "62617", new String[]{"61617"}); + brokerB.start(); + doTestNetworkSendReceive(); + + LOG.info("stopping brokerA"); + brokerA.stop(); + brokerA.waitUntilStopped(); + + LOG.info("restarting brokerA"); + brokerA = createBroker("tcp", "61617", null); + brokerA.start(); + + doTestNetworkSendReceive(); + } + + @Test + public void testSendReceiveFailover() throws Exception { + brokerA = createBroker("tcp", "61617", null); + brokerA.start(); + brokerB = createBroker("tcp", "62617", new String[]{"61617", "63617"}); + brokerB.start(); + doTestNetworkSendReceive(); + + // check mbean + Set bridgeNames = getNetworkBridgeMBeanName(brokerB); + assertEquals("only one bridgeName: " + bridgeNames, 1, bridgeNames.size()); + + LOG.info("stopping brokerA"); + brokerA.stop(); + brokerA.waitUntilStopped(); + + LOG.info("restarting brokerA"); + brokerA = createBroker("tcp", "63617", null); + brokerA.start(); + + doTestNetworkSendReceive(); + + Set otherBridgeNames = getNetworkBridgeMBeanName(brokerB); + assertEquals("only one bridgeName: " + otherBridgeNames, 1, otherBridgeNames.size()); + + assertTrue("there was an addition", bridgeNames.addAll(otherBridgeNames)); + } + + private Set getNetworkBridgeMBeanName(BrokerService brokerB) throws Exception { + Set names = new HashSet(); + for (ObjectName objectName : brokerB.getManagementContext().queryNames(null, null)) { + if (objectName.getKeyProperty("networkBridge") != null) { + names.add(objectName.getKeyProperty("networkBridge")); + } + } + return names; + } + + @Test + public void testSendReceiveFailoverDuplex() throws Exception { + final Vector errors = new Vector(); + final String dataDir = "target/data/shared"; + brokerA = createBroker("61617", dataDir); + brokerA.start(); + + final BrokerService slave = createBroker("63617", dataDir); + brokerA1 = slave; + ExecutorService executor = Executors.newCachedThreadPool(); + executor.execute(new Runnable() { + @Override + public void run() { + try { + slave.start(); } - // limit the reconnects in case of initial random connection to slave - // leaving randomize on verifies that this config is picked up - builder.append(")?maxReconnectAttempts=0)?useExponentialBackOff=false"); - NetworkConnector nc = broker.addNetworkConnector(builder.toString()); - if (networkProps != null) { - IntrospectionSupport.setProperties(nc, networkProps); + catch (Exception e) { + e.printStackTrace(); + errors.add(e); } - } - return broker; - } + } + }); + executor.shutdown(); - private BrokerService createBroker(String listenPort, String dataDir) throws Exception { - BrokerService broker = new BrokerService(); - broker.setUseJmx(false); - broker.getManagementContext().setCreateConnector(false); - broker.setBrokerName("Broker_Shared"); - // lazy create transport connector on start completion - TransportConnector connector = new TransportConnector(); - connector.setUri(new URI("tcp://localhost:" + listenPort)); - broker.addConnector(connector); - broker.setDataDirectory(dataDir); - return broker; - } + HashMap networkConnectorProps = new HashMap(); + networkConnectorProps.put("duplex", "true"); + brokerB = createBroker("tcp", "62617", new String[]{"61617", "63617"}, networkConnectorProps); + brokerB.start(); - @Before - public void setUp() throws Exception { - KeyManager[] km = SslBrokerServiceTest.getKeyManager(); - TrustManager[] tm = SslBrokerServiceTest.getTrustManager(); - sslContext = new SslContext(km, tm, null); - } + doTestNetworkSendReceive(brokerA, brokerB); + doTestNetworkSendReceive(brokerB, brokerA); - @After - public void tearDown() throws Exception { - brokerB.stop(); - brokerB.waitUntilStopped(); + LOG.info("stopping brokerA (master shared_broker)"); + brokerA.stop(); + brokerA.waitUntilStopped(); - brokerA.stop(); - brokerA.waitUntilStopped(); + // wait for slave to start + brokerA1.waitUntilStarted(); - if (brokerA1 != null) { - brokerA1.stop(); - brokerA1.waitUntilStopped(); - } + doTestNetworkSendReceive(brokerA1, brokerB); + doTestNetworkSendReceive(brokerB, brokerA1); - if (brokerC != null) { - brokerC.stop(); - brokerC.waitUntilStopped(); - } - } + assertTrue("No unexpected exceptions " + errors, errors.isEmpty()); + } - @Test - public void testSendReceiveAfterReconnect() throws Exception { - brokerA = createBroker("tcp", "61617", null); - brokerA.start(); - brokerB = createBroker("tcp", "62617", new String[]{"61617"}); - brokerB.start(); - doTestNetworkSendReceive(); + @Test + // master slave piggy in the middle setup + public void testSendReceiveFailoverDuplexWithPIM() throws Exception { + final String dataDir = "target/data/shared/pim"; + brokerA = createBroker("61617", dataDir); + brokerA.start(); - LOG.info("stopping brokerA"); - brokerA.stop(); - brokerA.waitUntilStopped(); - - LOG.info("restarting brokerA"); - brokerA = createBroker("tcp", "61617", null); - brokerA.start(); - - doTestNetworkSendReceive(); - } - - @Test - public void testSendReceiveFailover() throws Exception { - brokerA = createBroker("tcp", "61617", null); - brokerA.start(); - brokerB = createBroker("tcp", "62617", new String[]{"61617", "63617"}); - brokerB.start(); - doTestNetworkSendReceive(); - - // check mbean - Set bridgeNames = getNetworkBridgeMBeanName(brokerB); - assertEquals("only one bridgeName: " + bridgeNames, 1, bridgeNames.size()); - - LOG.info("stopping brokerA"); - brokerA.stop(); - brokerA.waitUntilStopped(); - - LOG.info("restarting brokerA"); - brokerA = createBroker("tcp", "63617", null); - brokerA.start(); - - doTestNetworkSendReceive(); - - Set otherBridgeNames = getNetworkBridgeMBeanName(brokerB); - assertEquals("only one bridgeName: " + otherBridgeNames, 1, otherBridgeNames.size()); - - assertTrue("there was an addition", bridgeNames.addAll(otherBridgeNames)); - } - - private Set getNetworkBridgeMBeanName(BrokerService brokerB) throws Exception { - Set names = new HashSet(); - for (ObjectName objectName : brokerB.getManagementContext().queryNames(null, null)) { - if (objectName.getKeyProperty("networkBridge") != null) { - names.add(objectName.getKeyProperty("networkBridge")); + final BrokerService slave = createBroker("63617", dataDir); + brokerA1 = slave; + ExecutorService executor = Executors.newCachedThreadPool(); + executor.execute(new Runnable() { + @Override + public void run() { + try { + slave.start(); } - } - return names; - } - - @Test - public void testSendReceiveFailoverDuplex() throws Exception { - final Vector errors = new Vector(); - final String dataDir = "target/data/shared"; - brokerA = createBroker("61617", dataDir); - brokerA.start(); - - final BrokerService slave = createBroker("63617", dataDir); - brokerA1 = slave; - ExecutorService executor = Executors.newCachedThreadPool(); - executor.execute(new Runnable() { - @Override - public void run() { - try { - slave.start(); - } catch (Exception e) { - e.printStackTrace(); - errors.add(e); - } + catch (Exception e) { + e.printStackTrace(); } - }); - executor.shutdown(); + } + }); + executor.shutdown(); - HashMap networkConnectorProps = new HashMap(); - networkConnectorProps.put("duplex", "true"); - brokerB = createBroker("tcp", "62617", new String[]{"61617", "63617"}, networkConnectorProps); - brokerB.start(); + HashMap networkConnectorProps = new HashMap(); + networkConnectorProps.put("duplex", "true"); + networkConnectorProps.put("networkTTL", "2"); - doTestNetworkSendReceive(brokerA, brokerB); - doTestNetworkSendReceive(brokerB, brokerA); + brokerB = createBroker("tcp", "62617", new String[]{"61617", "63617"}, networkConnectorProps); + brokerB.start(); - LOG.info("stopping brokerA (master shared_broker)"); - brokerA.stop(); - brokerA.waitUntilStopped(); + assertTrue("all props applied", networkConnectorProps.isEmpty()); + networkConnectorProps.put("duplex", "true"); + networkConnectorProps.put("networkTTL", "2"); - // wait for slave to start - brokerA1.waitUntilStarted(); + brokerC = createBroker("tcp", "64617", new String[]{"61617", "63617"}, networkConnectorProps); + brokerC.start(); + assertTrue("all props applied a second time", networkConnectorProps.isEmpty()); - doTestNetworkSendReceive(brokerA1, brokerB); - doTestNetworkSendReceive(brokerB, brokerA1); + doTestNetworkSendReceive(brokerC, brokerB); + doTestNetworkSendReceive(brokerB, brokerC); - assertTrue("No unexpected exceptions " + errors, errors.isEmpty()); - } + LOG.info("stopping brokerA (master shared_broker)"); + brokerA.stop(); + brokerA.waitUntilStopped(); - @Test - // master slave piggy in the middle setup - public void testSendReceiveFailoverDuplexWithPIM() throws Exception { - final String dataDir = "target/data/shared/pim"; - brokerA = createBroker("61617", dataDir); - brokerA.start(); + doTestNetworkSendReceive(brokerC, brokerB); + doTestNetworkSendReceive(brokerB, brokerC); - final BrokerService slave = createBroker("63617", dataDir); - brokerA1 = slave; - ExecutorService executor = Executors.newCachedThreadPool(); - executor.execute(new Runnable() { - @Override - public void run() { - try { - slave.start(); - } catch (Exception e) { - e.printStackTrace(); - } + brokerC.stop(); + brokerC.waitUntilStopped(); + } + + /** + * networked broker started after target so first connect attempt succeeds + * start order is important + */ + @Test + public void testSendReceive() throws Exception { + + brokerA = createBroker("tcp", "61617", null); + brokerA.start(); + brokerB = createBroker("tcp", "62617", new String[]{"61617", "1111"}); + brokerB.start(); + + doTestNetworkSendReceive(); + } + + @Test + public void testSendReceiveSsl() throws Exception { + + brokerA = createBroker("ssl", "61617", null); + brokerA.start(); + brokerB = createBroker("ssl", "62617", new String[]{"61617", "1111"}); + brokerB.start(); + + doTestNetworkSendReceive(); + } + + @Test + public void testRepeatedSendReceiveWithMasterSlaveAlternate() throws Exception { + doTestRepeatedSendReceiveWithMasterSlaveAlternate(null); + } + + @Test + public void testRepeatedSendReceiveWithMasterSlaveAlternateDuplex() throws Exception { + HashMap networkConnectorProps = new HashMap(); + networkConnectorProps.put("duplex", "true"); + + doTestRepeatedSendReceiveWithMasterSlaveAlternate(networkConnectorProps); + } + + public void doTestRepeatedSendReceiveWithMasterSlaveAlternate(HashMap networkConnectorProps) throws Exception { + + brokerB = createBroker("tcp", "62617", new String[]{"61610", "61611"}, networkConnectorProps); + brokerB.start(); + + final AtomicBoolean done = new AtomicBoolean(false); + ExecutorService executorService = Executors.newCachedThreadPool(); + executorService.execute(new Runnable() { + @Override + public void run() { + try { + while (!done.get()) { + brokerA = createBroker("tcp", "61610", null); + brokerA.setBrokerName("Pair"); + brokerA.setBrokerObjectName(new ObjectName(brokerA.getManagementContext().getJmxDomainName() + ":" + "BrokerName=" + JMXSupport.encodeObjectNamePart("A") + "," + "Type=Broker")); + ((KahaDBPersistenceAdapter) brokerA.getPersistenceAdapter()).getLocker().setLockAcquireSleepInterval(1000); + brokerA.start(); + brokerA.waitUntilStopped(); + + // restart after peer taken over + brokerA1.waitUntilStarted(); + } } - }); - executor.shutdown(); - - HashMap networkConnectorProps = new HashMap(); - networkConnectorProps.put("duplex", "true"); - networkConnectorProps.put("networkTTL", "2"); - - brokerB = createBroker("tcp", "62617", new String[]{"61617", "63617"}, networkConnectorProps); - brokerB.start(); - - assertTrue("all props applied", networkConnectorProps.isEmpty()); - networkConnectorProps.put("duplex", "true"); - networkConnectorProps.put("networkTTL", "2"); - - brokerC = createBroker("tcp", "64617", new String[]{"61617", "63617"}, networkConnectorProps); - brokerC.start(); - assertTrue("all props applied a second time", networkConnectorProps.isEmpty()); - - doTestNetworkSendReceive(brokerC, brokerB); - doTestNetworkSendReceive(brokerB, brokerC); - - LOG.info("stopping brokerA (master shared_broker)"); - brokerA.stop(); - brokerA.waitUntilStopped(); - - doTestNetworkSendReceive(brokerC, brokerB); - doTestNetworkSendReceive(brokerB, brokerC); - - brokerC.stop(); - brokerC.waitUntilStopped(); - } - - /** - * networked broker started after target so first connect attempt succeeds - * start order is important - */ - @Test - public void testSendReceive() throws Exception { - - brokerA = createBroker("tcp", "61617", null); - brokerA.start(); - brokerB = createBroker("tcp", "62617", new String[]{"61617","1111"}); - brokerB.start(); - - doTestNetworkSendReceive(); - } - - @Test - public void testSendReceiveSsl() throws Exception { - - brokerA = createBroker("ssl", "61617", null); - brokerA.start(); - brokerB = createBroker("ssl", "62617", new String[]{"61617", "1111"}); - brokerB.start(); - - doTestNetworkSendReceive(); - } - - @Test - public void testRepeatedSendReceiveWithMasterSlaveAlternate() throws Exception { - doTestRepeatedSendReceiveWithMasterSlaveAlternate(null); - } - - @Test - public void testRepeatedSendReceiveWithMasterSlaveAlternateDuplex() throws Exception { - HashMap networkConnectorProps = new HashMap(); - networkConnectorProps.put("duplex", "true"); - - doTestRepeatedSendReceiveWithMasterSlaveAlternate(networkConnectorProps); - } - - public void doTestRepeatedSendReceiveWithMasterSlaveAlternate(HashMap networkConnectorProps) throws Exception { - - brokerB = createBroker("tcp", "62617", new String[]{"61610","61611"}, networkConnectorProps); - brokerB.start(); - - final AtomicBoolean done = new AtomicBoolean(false); - ExecutorService executorService = Executors.newCachedThreadPool(); - executorService.execute(new Runnable() { - @Override - public void run() { - try { - while (!done.get()) { - brokerA = createBroker("tcp", "61610", null); - brokerA.setBrokerName("Pair"); - brokerA.setBrokerObjectName(new ObjectName(brokerA.getManagementContext().getJmxDomainName() + ":" + "BrokerName=" - + JMXSupport.encodeObjectNamePart("A") + "," + "Type=Broker")); - ((KahaDBPersistenceAdapter)brokerA.getPersistenceAdapter()).getLocker().setLockAcquireSleepInterval(1000); - brokerA.start(); - brokerA.waitUntilStopped(); - - // restart after peer taken over - brokerA1.waitUntilStarted(); - } - } catch (Exception ignored) { - LOG.info("A create/start, unexpected: " + ignored, ignored); - } + catch (Exception ignored) { + LOG.info("A create/start, unexpected: " + ignored, ignored); } - }); + } + }); - // start with brokerA as master - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return brokerA != null && brokerA.waitUntilStarted(); + // start with brokerA as master + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return brokerA != null && brokerA.waitUntilStarted(); + } + }); + + executorService.execute(new Runnable() { + @Override + public void run() { + try { + while (!done.get()) { + brokerA1 = createBroker("tcp", "61611", null); + brokerA1.setBrokerName("Pair"); + // so they can coexist in local jmx we set the object name b/c the brokername identifies the shared store + brokerA1.setBrokerObjectName(new ObjectName(brokerA.getManagementContext().getJmxDomainName() + ":" + "BrokerName=" + JMXSupport.encodeObjectNamePart("A1") + "," + "Type=Broker")); + ((KahaDBPersistenceAdapter) brokerA1.getPersistenceAdapter()).getLocker().setLockAcquireSleepInterval(1000); + brokerA1.start(); + brokerA1.waitUntilStopped(); + + // restart after peer taken over + brokerA.waitUntilStarted(); + } } - }); - - executorService.execute(new Runnable() { - @Override - public void run() { - try { - while (!done.get()) { - brokerA1 = createBroker("tcp", "61611", null); - brokerA1.setBrokerName("Pair"); - // so they can coexist in local jmx we set the object name b/c the brokername identifies the shared store - brokerA1.setBrokerObjectName(new ObjectName(brokerA.getManagementContext().getJmxDomainName() + ":" + "BrokerName=" - + JMXSupport.encodeObjectNamePart("A1") + "," + "Type=Broker")); - ((KahaDBPersistenceAdapter)brokerA1.getPersistenceAdapter()).getLocker().setLockAcquireSleepInterval(1000); - brokerA1.start(); - brokerA1.waitUntilStopped(); - - // restart after peer taken over - brokerA.waitUntilStarted(); - } - } catch (Exception ignored) { - LOG.info("A1 create/start, unexpected: " + ignored, ignored); - } + catch (Exception ignored) { + LOG.info("A1 create/start, unexpected: " + ignored, ignored); } - }); + } + }); - for (int i=0; i<4; i++) { - BrokerService currentMaster = (i%2 == 0 ? brokerA : brokerA1); - LOG.info("iteration: " + i + ", using: " + currentMaster.getBrokerObjectName().getKeyProperty("BrokerName")); - currentMaster.waitUntilStarted(); + for (int i = 0; i < 4; i++) { + BrokerService currentMaster = (i % 2 == 0 ? brokerA : brokerA1); + LOG.info("iteration: " + i + ", using: " + currentMaster.getBrokerObjectName().getKeyProperty("BrokerName")); + currentMaster.waitUntilStarted(); - doTestNetworkSendReceive(brokerB, currentMaster); + doTestNetworkSendReceive(brokerB, currentMaster); - LOG.info("Stopping " + currentMaster.getBrokerObjectName().getKeyProperty("BrokerName")); - currentMaster.stop(); - currentMaster.waitUntilStopped(); - } + LOG.info("Stopping " + currentMaster.getBrokerObjectName().getKeyProperty("BrokerName")); + currentMaster.stop(); + currentMaster.waitUntilStopped(); + } - done.set(true); - LOG.info("all done"); - executorService.shutdownNow(); - } + done.set(true); + LOG.info("all done"); + executorService.shutdownNow(); + } - private void doTestNetworkSendReceive() throws Exception, JMSException { - doTestNetworkSendReceive(brokerB, brokerA); - } + private void doTestNetworkSendReceive() throws Exception, JMSException { + doTestNetworkSendReceive(brokerB, brokerA); + } - private void doTestNetworkSendReceive(final BrokerService to, final BrokerService from) throws Exception, JMSException { + private void doTestNetworkSendReceive(final BrokerService to, + final BrokerService from) throws Exception, JMSException { - LOG.info("Creating Consumer on the networked broker ..." + from); + LOG.info("Creating Consumer on the networked broker ..." + from); - SslContext.setCurrentSslContext(sslContext); - // Create a consumer on brokerA - ConnectionFactory consFactory = createConnectionFactory(from); - Connection consConn = consFactory.createConnection(); - consConn.start(); - Session consSession = consConn.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination = (ActiveMQDestination) consSession.createQueue(DESTINATION_NAME); - final MessageConsumer consumer = consSession.createConsumer(destination); + SslContext.setCurrentSslContext(sslContext); + // Create a consumer on brokerA + ConnectionFactory consFactory = createConnectionFactory(from); + Connection consConn = consFactory.createConnection(); + consConn.start(); + Session consSession = consConn.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQDestination destination = (ActiveMQDestination) consSession.createQueue(DESTINATION_NAME); + final MessageConsumer consumer = consSession.createConsumer(destination); - LOG.info("publishing to " + to); + LOG.info("publishing to " + to); - sendMessageTo(destination, to); + sendMessageTo(destination, to); - boolean gotMessage = Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = consumer.receive(5000); - LOG.info("from: " + from.getBrokerObjectName().getKeyProperty("BrokerName") + ", received: " + message); - return message != null; - } - }); - try { - consConn.close(); - } catch (JMSException ignored) { - } - assertTrue("consumer on A got message", gotMessage); - } + boolean gotMessage = Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Message message = consumer.receive(5000); + LOG.info("from: " + from.getBrokerObjectName().getKeyProperty("BrokerName") + ", received: " + message); + return message != null; + } + }); + try { + consConn.close(); + } + catch (JMSException ignored) { + } + assertTrue("consumer on A got message", gotMessage); + } - private void sendMessageTo(ActiveMQDestination destination, BrokerService brokerService) throws Exception { - ConnectionFactory factory = createConnectionFactory(brokerService); - Connection conn = factory.createConnection(); - conn.start(); - Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createProducer(destination).send(session.createTextMessage("Hi")); - conn.close(); - } + private void sendMessageTo(ActiveMQDestination destination, BrokerService brokerService) throws Exception { + ConnectionFactory factory = createConnectionFactory(brokerService); + Connection conn = factory.createConnection(); + conn.start(); + Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createProducer(destination).send(session.createTextMessage("Hi")); + conn.close(); + } - protected ConnectionFactory createConnectionFactory(final BrokerService broker) throws Exception { - String url = broker.getTransportConnectors().get(0).getServer().getConnectURI().toString(); - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url); - connectionFactory.setOptimizedMessageDispatch(true); - connectionFactory.setDispatchAsync(false); - connectionFactory.setUseAsyncSend(false); - connectionFactory.setOptimizeAcknowledge(false); - connectionFactory.setAlwaysSyncSend(true); - return connectionFactory; - } + protected ConnectionFactory createConnectionFactory(final BrokerService broker) throws Exception { + String url = broker.getTransportConnectors().get(0).getServer().getConnectURI().toString(); + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url); + connectionFactory.setOptimizedMessageDispatch(true); + connectionFactory.setDispatchAsync(false); + connectionFactory.setUseAsyncSend(false); + connectionFactory.setOptimizeAcknowledge(false); + connectionFactory.setAlwaysSyncSend(true); + return connectionFactory; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/ForwardingBridgeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/ForwardingBridgeTest.java index 71006e3211..411ac1be33 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/ForwardingBridgeTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/ForwardingBridgeTest.java @@ -31,124 +31,122 @@ import org.apache.activemq.command.SessionInfo; public class ForwardingBridgeTest extends NetworkTestSupport { - public ActiveMQDestination destination; - public byte destinationType; - public int deliveryMode; - private ForwardingBridge bridge; + public ActiveMQDestination destination; + public byte destinationType; + public int deliveryMode; + private ForwardingBridge bridge; - public void initCombosForTestForwardMessageCompressed() { - addCombinationValues("deliveryMode", new Object[] {new Integer(DeliveryMode.NON_PERSISTENT), - new Integer(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[] {new Byte(ActiveMQDestination.QUEUE_TYPE), - new Byte(ActiveMQDestination.TOPIC_TYPE)}); - } + public void initCombosForTestForwardMessageCompressed() { + addCombinationValues("deliveryMode", new Object[]{new Integer(DeliveryMode.NON_PERSISTENT), new Integer(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{new Byte(ActiveMQDestination.QUEUE_TYPE), new Byte(ActiveMQDestination.TOPIC_TYPE)}); + } - public void testForwardMessageCompressed() throws Exception { + public void testForwardMessageCompressed() throws Exception { - bridge.setUseCompression(true); + bridge.setUseCompression(true); - // Start a producer on local broker - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo); + // Start a producer on local broker + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo); - destination = createDestinationInfo(connection1, connectionInfo1, destinationType); + destination = createDestinationInfo(connection1, connectionInfo1, destinationType); - // Start a consumer on a remote broker - StubConnection connection2 = createRemoteConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo2, destination); - connection2.send(consumerInfo); - Thread.sleep(1000); - // Give forwarding bridge a chance to finish setting up - try { - Thread.sleep(1000); - } catch (InterruptedException ie) { - ie.printStackTrace(); - } + // Start a consumer on a remote broker + StubConnection connection2 = createRemoteConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo2, destination); + connection2.send(consumerInfo); + Thread.sleep(1000); + // Give forwarding bridge a chance to finish setting up + try { + Thread.sleep(1000); + } + catch (InterruptedException ie) { + ie.printStackTrace(); + } - // Send the message to the local boker. - connection1.send(createMessage(producerInfo, destination, deliveryMode)); + // Send the message to the local boker. + connection1.send(createMessage(producerInfo, destination, deliveryMode)); - // Make sure the message was delivered via the remote. - Message m = receiveMessage(connection2); - assertNotNull(m); + // Make sure the message was delivered via the remote. + Message m = receiveMessage(connection2); + assertNotNull(m); - // Make sure its compressed now - ActiveMQMessage message = (ActiveMQMessage) m; - assertTrue(message.isCompressed()); - } + // Make sure its compressed now + ActiveMQMessage message = (ActiveMQMessage) m; + assertTrue(message.isCompressed()); + } - public void initCombosForTestAddConsumerThenSend() { - addCombinationValues("deliveryMode", new Object[] {new Integer(DeliveryMode.NON_PERSISTENT), - new Integer(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[] {new Byte(ActiveMQDestination.QUEUE_TYPE), - new Byte(ActiveMQDestination.TOPIC_TYPE)}); - } + public void initCombosForTestAddConsumerThenSend() { + addCombinationValues("deliveryMode", new Object[]{new Integer(DeliveryMode.NON_PERSISTENT), new Integer(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{new Byte(ActiveMQDestination.QUEUE_TYPE), new Byte(ActiveMQDestination.TOPIC_TYPE)}); + } - public void testAddConsumerThenSend() throws Exception { - // Start a producer on local broker - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo); + public void testAddConsumerThenSend() throws Exception { + // Start a producer on local broker + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo); - destination = createDestinationInfo(connection1, connectionInfo1, destinationType); + destination = createDestinationInfo(connection1, connectionInfo1, destinationType); - // Start a consumer on a remote broker - StubConnection connection2 = createRemoteConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo2, destination); - connection2.send(consumerInfo); - Thread.sleep(1000); - // Give forwarding bridge a chance to finish setting up - try { - Thread.sleep(1000); - } catch (InterruptedException ie) { - ie.printStackTrace(); - } + // Start a consumer on a remote broker + StubConnection connection2 = createRemoteConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo2, destination); + connection2.send(consumerInfo); + Thread.sleep(1000); + // Give forwarding bridge a chance to finish setting up + try { + Thread.sleep(1000); + } + catch (InterruptedException ie) { + ie.printStackTrace(); + } - // Send the message to the local boker. - connection1.send(createMessage(producerInfo, destination, deliveryMode)); + // Send the message to the local boker. + connection1.send(createMessage(producerInfo, destination, deliveryMode)); - // Make sure the message was delivered via the remote. + // Make sure the message was delivered via the remote. - Message m = receiveMessage(connection2); - assertNotNull(m); - } + Message m = receiveMessage(connection2); + assertNotNull(m); + } - protected void setUp() throws Exception { - super.setUp(); - bridge = new ForwardingBridge(createTransport(), createRemoteTransport()); - bridge.setClientId("local-remote-bridge"); - bridge.setDispatchAsync(false); - bridge.start(); - } + protected void setUp() throws Exception { + super.setUp(); + bridge = new ForwardingBridge(createTransport(), createRemoteTransport()); + bridge.setClientId("local-remote-bridge"); + bridge.setDispatchAsync(false); + bridge.start(); + } - protected void tearDown() throws Exception { - bridge.stop(); - super.tearDown(); - } + protected void tearDown() throws Exception { + bridge.stop(); + super.tearDown(); + } - public static Test suite() { - return suite(ForwardingBridgeTest.class); - } + public static Test suite() { + return suite(ForwardingBridgeTest.class); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/MQTTNetworkOfBrokersFailoverTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/MQTTNetworkOfBrokersFailoverTest.java index d0bd3d79b9..4ee1adb7b8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/MQTTNetworkOfBrokersFailoverTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/MQTTNetworkOfBrokersFailoverTest.java @@ -49,202 +49,202 @@ import org.slf4j.LoggerFactory; public class MQTTNetworkOfBrokersFailoverTest extends NetworkTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(MQTTNetworkOfBrokersFailoverTest.class); - private int localBrokerMQTTPort = -1; - private int remoteBrokerMQTTPort = -1; + private static final Logger LOG = LoggerFactory.getLogger(MQTTNetworkOfBrokersFailoverTest.class); + private int localBrokerMQTTPort = -1; + private int remoteBrokerMQTTPort = -1; - @Override - protected void setUp() throws Exception { - useJmx=true; - super.setUp(); + @Override + protected void setUp() throws Exception { + useJmx = true; + super.setUp(); - URI ncUri = new URI("static:(" + connector.getConnectUri().toString() + ")"); - NetworkConnector nc = new DiscoveryNetworkConnector(ncUri); - nc.setDuplex(true); - remoteBroker.addNetworkConnector(nc); - nc.start(); + URI ncUri = new URI("static:(" + connector.getConnectUri().toString() + ")"); + NetworkConnector nc = new DiscoveryNetworkConnector(ncUri); + nc.setDuplex(true); + remoteBroker.addNetworkConnector(nc); + nc.start(); - // mqtt port should have been assigned by now - assertFalse(localBrokerMQTTPort == -1); - assertFalse(remoteBrokerMQTTPort == -1); - } + // mqtt port should have been assigned by now + assertFalse(localBrokerMQTTPort == -1); + assertFalse(remoteBrokerMQTTPort == -1); + } - @Override - protected void tearDown() throws Exception { - if (remoteBroker.isStarted()) { - remoteBroker.stop(); - remoteBroker.waitUntilStopped(); - } - if (broker.isStarted()) { - broker.stop(); - broker.waitUntilStopped(); - } - super.tearDown(); - } + @Override + protected void tearDown() throws Exception { + if (remoteBroker.isStarted()) { + remoteBroker.stop(); + remoteBroker.waitUntilStopped(); + } + if (broker.isStarted()) { + broker.stop(); + broker.waitUntilStopped(); + } + super.tearDown(); + } - @Test - public void testNoStaleSubscriptionAcrossNetwork() throws Exception { + @Test + public void testNoStaleSubscriptionAcrossNetwork() throws Exception { - // before we get started, we want an async way to be able to know when - // the durable consumer has been networked so we can assert that it indeed - // would have a durable subscriber. for example, when we subscribe on remote broker, - // a network-sub would be created on local broker and we want to listen for when that - // even happens. we do that with advisory messages and a latch: - CountDownLatch consumerNetworked = listenForConsumersOn(broker); + // before we get started, we want an async way to be able to know when + // the durable consumer has been networked so we can assert that it indeed + // would have a durable subscriber. for example, when we subscribe on remote broker, + // a network-sub would be created on local broker and we want to listen for when that + // even happens. we do that with advisory messages and a latch: + CountDownLatch consumerNetworked = listenForConsumersOn(broker); - // create a subscription with Clean == 0 (durable sub for QoS==1 && QoS==2) - // on the remote broker. this sub should still be there after we disconnect - MQTT remoteMqtt = createMQTTTcpConnection("foo", false, remoteBrokerMQTTPort); - BlockingConnection remoteConn = remoteMqtt.blockingConnection(); - remoteConn.connect(); - remoteConn.subscribe(new Topic[]{new Topic("foo/bar", QoS.AT_LEAST_ONCE)}); + // create a subscription with Clean == 0 (durable sub for QoS==1 && QoS==2) + // on the remote broker. this sub should still be there after we disconnect + MQTT remoteMqtt = createMQTTTcpConnection("foo", false, remoteBrokerMQTTPort); + BlockingConnection remoteConn = remoteMqtt.blockingConnection(); + remoteConn.connect(); + remoteConn.subscribe(new Topic[]{new Topic("foo/bar", QoS.AT_LEAST_ONCE)}); - assertTrue("No destination detected!", consumerNetworked.await(1, TimeUnit.SECONDS)); - assertQueueExistsOn(remoteBroker, "Consumer.foo_AT_LEAST_ONCE.VirtualTopic.foo.bar"); - assertQueueExistsOn(broker, "Consumer.foo_AT_LEAST_ONCE.VirtualTopic.foo.bar"); - remoteConn.disconnect(); + assertTrue("No destination detected!", consumerNetworked.await(1, TimeUnit.SECONDS)); + assertQueueExistsOn(remoteBroker, "Consumer.foo_AT_LEAST_ONCE.VirtualTopic.foo.bar"); + assertQueueExistsOn(broker, "Consumer.foo_AT_LEAST_ONCE.VirtualTopic.foo.bar"); + remoteConn.disconnect(); - // now we reconnect the same sub on the local broker, again with clean==0 - MQTT localMqtt = createMQTTTcpConnection("foo", false, localBrokerMQTTPort); - BlockingConnection localConn = localMqtt.blockingConnection(); - localConn.connect(); - localConn.subscribe(new Topic[]{new Topic("foo/bar", QoS.AT_LEAST_ONCE)}); + // now we reconnect the same sub on the local broker, again with clean==0 + MQTT localMqtt = createMQTTTcpConnection("foo", false, localBrokerMQTTPort); + BlockingConnection localConn = localMqtt.blockingConnection(); + localConn.connect(); + localConn.subscribe(new Topic[]{new Topic("foo/bar", QoS.AT_LEAST_ONCE)}); - // now let's connect back up to remote broker and send a message - remoteConn = remoteMqtt.blockingConnection(); - remoteConn.connect(); - remoteConn.publish("foo/bar", "Hello, World!".getBytes(), QoS.AT_LEAST_ONCE, false); + // now let's connect back up to remote broker and send a message + remoteConn = remoteMqtt.blockingConnection(); + remoteConn.connect(); + remoteConn.publish("foo/bar", "Hello, World!".getBytes(), QoS.AT_LEAST_ONCE, false); - // now we should see that message on the local broker because the subscription - // should have been properly networked... we'll give a sec of grace for the - // networking and forwarding to have happened properly - org.fusesource.mqtt.client.Message msg = localConn.receive(100, TimeUnit.SECONDS); - assertNotNull(msg); - msg.ack(); - String response = new String(msg.getPayload()); - assertEquals("Hello, World!", response); - assertEquals("foo/bar", msg.getTopic()); + // now we should see that message on the local broker because the subscription + // should have been properly networked... we'll give a sec of grace for the + // networking and forwarding to have happened properly + org.fusesource.mqtt.client.Message msg = localConn.receive(100, TimeUnit.SECONDS); + assertNotNull(msg); + msg.ack(); + String response = new String(msg.getPayload()); + assertEquals("Hello, World!", response); + assertEquals("foo/bar", msg.getTopic()); - // Now... we SHOULD NOT see a message on the remote broker because we already - // consumed it on the local broker... having the same message on the remote broker - // would effectively give us duplicates in a distributed topic scenario: - remoteConn.subscribe(new Topic[]{new Topic("foo/bar", QoS.AT_LEAST_ONCE)}); - msg = remoteConn.receive(500, TimeUnit.MILLISECONDS); - assertNull("We have duplicate messages across the cluster for a distributed topic", msg); - } + // Now... we SHOULD NOT see a message on the remote broker because we already + // consumed it on the local broker... having the same message on the remote broker + // would effectively give us duplicates in a distributed topic scenario: + remoteConn.subscribe(new Topic[]{new Topic("foo/bar", QoS.AT_LEAST_ONCE)}); + msg = remoteConn.receive(500, TimeUnit.MILLISECONDS); + assertNull("We have duplicate messages across the cluster for a distributed topic", msg); + } - private CountDownLatch listenForConsumersOn(BrokerService broker) throws Exception { - final CountDownLatch latch = new CountDownLatch(1); + private CountDownLatch listenForConsumersOn(BrokerService broker) throws Exception { + final CountDownLatch latch = new CountDownLatch(1); - URI brokerUri = broker.getVmConnectorURI(); + URI brokerUri = broker.getVmConnectorURI(); - final ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(brokerUri.toASCIIString()); - final Connection connection = cf.createConnection(); - connection.start(); - final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination dest = session.createTopic("ActiveMQ.Advisory.Consumer.Queue.Consumer.foo:AT_LEAST_ONCE.VirtualTopic.foo.bar"); - MessageConsumer consumer = session.createConsumer(dest); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - latch.countDown(); - // shutdown this connection - Dispatch.getGlobalQueue().execute(new Runnable() { - @Override - public void run() { - try { - session.close(); - connection.close(); - } catch (JMSException e) { - e.printStackTrace(); - } - } - }); - } - }); + final ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(brokerUri.toASCIIString()); + final Connection connection = cf.createConnection(); + connection.start(); + final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination dest = session.createTopic("ActiveMQ.Advisory.Consumer.Queue.Consumer.foo:AT_LEAST_ONCE.VirtualTopic.foo.bar"); + MessageConsumer consumer = session.createConsumer(dest); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + latch.countDown(); + // shutdown this connection + Dispatch.getGlobalQueue().execute(new Runnable() { + @Override + public void run() { + try { + session.close(); + connection.close(); + } + catch (JMSException e) { + e.printStackTrace(); + } + } + }); + } + }); - return latch; - } + return latch; + } - private void assertQueueExistsOn(BrokerService broker, String queueName) throws Exception { - BrokerViewMBean brokerView = broker.getAdminView(); - ObjectName[] queueNames = brokerView.getQueues(); - assertEquals(1, queueNames.length); + private void assertQueueExistsOn(BrokerService broker, String queueName) throws Exception { + BrokerViewMBean brokerView = broker.getAdminView(); + ObjectName[] queueNames = brokerView.getQueues(); + assertEquals(1, queueNames.length); - assertTrue(queueNames[0].toString().contains(queueName)); - } + assertTrue(queueNames[0].toString().contains(queueName)); + } - @SuppressWarnings("unused") - private void assertOneDurableSubOn(BrokerService broker, String subName) throws Exception { - BrokerViewMBean brokerView = broker.getAdminView(); - ObjectName[] activeDurableSubs = brokerView.getDurableTopicSubscribers(); - ObjectName[] inactiveDurableSubs = brokerView.getInactiveDurableTopicSubscribers(); - ObjectName[] allDurables = (ObjectName[]) ArrayUtils.addAll(activeDurableSubs, inactiveDurableSubs); - assertEquals(1, allDurables.length); + @SuppressWarnings("unused") + private void assertOneDurableSubOn(BrokerService broker, String subName) throws Exception { + BrokerViewMBean brokerView = broker.getAdminView(); + ObjectName[] activeDurableSubs = brokerView.getDurableTopicSubscribers(); + ObjectName[] inactiveDurableSubs = brokerView.getInactiveDurableTopicSubscribers(); + ObjectName[] allDurables = (ObjectName[]) ArrayUtils.addAll(activeDurableSubs, inactiveDurableSubs); + assertEquals(1, allDurables.length); - // at this point our assertions should prove that we have only on durable sub - DurableSubscriptionViewMBean durableSubView = (DurableSubscriptionViewMBean) - broker.getManagementContext().newProxyInstance(allDurables[0], DurableSubscriptionViewMBean.class, true); + // at this point our assertions should prove that we have only on durable sub + DurableSubscriptionViewMBean durableSubView = (DurableSubscriptionViewMBean) broker.getManagementContext().newProxyInstance(allDurables[0], DurableSubscriptionViewMBean.class, true); - assertEquals(subName, durableSubView.getClientId()); - } + assertEquals(subName, durableSubView.getClientId()); + } - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - broker.setPersistent(true); - broker.setBrokerName("local"); - broker.setDataDirectory("target/activemq-data"); - broker.setDeleteAllMessagesOnStartup(true); - TransportConnector tc = broker.addConnector(getDefaultMQTTTransportConnectorUri()); - localBrokerMQTTPort = tc.getConnectUri().getPort(); - return broker; - } + @Override + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); + broker.setPersistent(true); + broker.setBrokerName("local"); + broker.setDataDirectory("target/activemq-data"); + broker.setDeleteAllMessagesOnStartup(true); + TransportConnector tc = broker.addConnector(getDefaultMQTTTransportConnectorUri()); + localBrokerMQTTPort = tc.getConnectUri().getPort(); + return broker; + } - @Override - protected BrokerService createRemoteBroker(PersistenceAdapter persistenceAdapter) throws Exception { - BrokerService broker = super.createRemoteBroker(persistenceAdapter); - broker.setPersistent(true); - broker.setDeleteAllMessagesOnStartup(true); - broker.setDataDirectory("target/activemq-data"); - TransportConnector tc = broker.addConnector(getDefaultMQTTTransportConnectorUri()); - remoteBrokerMQTTPort = tc.getConnectUri().getPort(); - return broker; - } + @Override + protected BrokerService createRemoteBroker(PersistenceAdapter persistenceAdapter) throws Exception { + BrokerService broker = super.createRemoteBroker(persistenceAdapter); + broker.setPersistent(true); + broker.setDeleteAllMessagesOnStartup(true); + broker.setDataDirectory("target/activemq-data"); + TransportConnector tc = broker.addConnector(getDefaultMQTTTransportConnectorUri()); + remoteBrokerMQTTPort = tc.getConnectUri().getPort(); + return broker; + } - private String getDefaultMQTTTransportConnectorUri(){ - return "mqtt://localhost:0?transport.subscriptionStrategy=mqtt-virtual-topic-subscriptions"; - } + private String getDefaultMQTTTransportConnectorUri() { + return "mqtt://localhost:0?transport.subscriptionStrategy=mqtt-virtual-topic-subscriptions"; + } - private MQTT createMQTTTcpConnection(String clientId, boolean clean, int port) throws Exception { - MQTT mqtt = new MQTT(); - mqtt.setConnectAttemptsMax(1); - mqtt.setReconnectAttemptsMax(0); - mqtt.setTracer(createTracer()); - if (clientId != null) { - mqtt.setClientId(clientId); - } - mqtt.setCleanSession(clean); - mqtt.setHost("localhost", port); - return mqtt; - } + private MQTT createMQTTTcpConnection(String clientId, boolean clean, int port) throws Exception { + MQTT mqtt = new MQTT(); + mqtt.setConnectAttemptsMax(1); + mqtt.setReconnectAttemptsMax(0); + mqtt.setTracer(createTracer()); + if (clientId != null) { + mqtt.setClientId(clientId); + } + mqtt.setCleanSession(clean); + mqtt.setHost("localhost", port); + return mqtt; + } - protected Tracer createTracer() { - return new Tracer() { - @Override - public void onReceive(MQTTFrame frame) { - LOG.info("Client Received:\n" + frame); - } + protected Tracer createTracer() { + return new Tracer() { + @Override + public void onReceive(MQTTFrame frame) { + LOG.info("Client Received:\n" + frame); + } - @Override - public void onSend(MQTTFrame frame) { - LOG.info("Client Sent:\n" + frame); - } + @Override + public void onSend(MQTTFrame frame) { + LOG.info("Client Sent:\n" + frame); + } - @Override - public void debug(String message, Object... args) { - LOG.info(String.format(message, args)); - } - }; - } + @Override + public void debug(String message, Object... args) { + LOG.info(String.format(message, args)); + } + }; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/MulticastNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/MulticastNetworkTest.java index 7813b07635..81901fa00d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/MulticastNetworkTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/MulticastNetworkTest.java @@ -17,22 +17,22 @@ package org.apache.activemq.network; /** - * + * */ public class MulticastNetworkTest extends SimpleNetworkTest { - protected String getRemoteBrokerURI() { - return "org/apache/activemq/network/multicast/remoteBroker.xml"; - } + protected String getRemoteBrokerURI() { + return "org/apache/activemq/network/multicast/remoteBroker.xml"; + } - protected String getLocalBrokerURI() { - return "org/apache/activemq/network/multicast/localBroker.xml"; - } + protected String getLocalBrokerURI() { + return "org/apache/activemq/network/multicast/localBroker.xml"; + } - // blocked out for multi cast because temp dest request reply isn't supported - // with dynamicallyAddedDestinations - @Override - public void testRequestReply() throws Exception { + // blocked out for multi cast because temp dest request reply isn't supported + // with dynamicallyAddedDestinations + @Override + public void testRequestReply() throws Exception { - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkBrokerDetachTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkBrokerDetachTest.java index ceef43c8cb..1c89002af0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkBrokerDetachTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkBrokerDetachTest.java @@ -48,258 +48,256 @@ import org.slf4j.LoggerFactory; public class NetworkBrokerDetachTest { - private final static String BROKER_NAME = "broker"; - private final static String REM_BROKER_NAME = "networkedBroker"; - private final static String DESTINATION_NAME = "testQ"; - private final static int NUM_CONSUMERS = 1; + private final static String BROKER_NAME = "broker"; + private final static String REM_BROKER_NAME = "networkedBroker"; + private final static String DESTINATION_NAME = "testQ"; + private final static int NUM_CONSUMERS = 1; - protected static final Logger LOG = LoggerFactory.getLogger(NetworkBrokerDetachTest.class); - protected final int numRestarts = 3; - protected final int networkTTL = 2; - protected final boolean dynamicOnly = false; + protected static final Logger LOG = LoggerFactory.getLogger(NetworkBrokerDetachTest.class); + protected final int numRestarts = 3; + protected final int networkTTL = 2; + protected final boolean dynamicOnly = false; - protected BrokerService broker; - protected BrokerService networkedBroker; + protected BrokerService broker; + protected BrokerService networkedBroker; - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName(BROKER_NAME); - configureBroker(broker); - broker.addConnector("tcp://localhost:61617"); - NetworkConnector networkConnector = broker.addNetworkConnector("static:(tcp://localhost:62617?wireFormat.maxInactivityDuration=500)?useExponentialBackOff=false"); - configureNetworkConnector(networkConnector); - return broker; - } + protected BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setBrokerName(BROKER_NAME); + configureBroker(broker); + broker.addConnector("tcp://localhost:61617"); + NetworkConnector networkConnector = broker.addNetworkConnector("static:(tcp://localhost:62617?wireFormat.maxInactivityDuration=500)?useExponentialBackOff=false"); + configureNetworkConnector(networkConnector); + return broker; + } - protected BrokerService createNetworkedBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName(REM_BROKER_NAME); - configureBroker(broker); - broker.getManagementContext().setCreateConnector(false); - broker.addConnector("tcp://localhost:62617"); - NetworkConnector networkConnector = broker.addNetworkConnector("static:(tcp://localhost:61617?wireFormat.maxInactivityDuration=500)?useExponentialBackOff=false"); - configureNetworkConnector(networkConnector); - return broker; - } + protected BrokerService createNetworkedBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setBrokerName(REM_BROKER_NAME); + configureBroker(broker); + broker.getManagementContext().setCreateConnector(false); + broker.addConnector("tcp://localhost:62617"); + NetworkConnector networkConnector = broker.addNetworkConnector("static:(tcp://localhost:61617?wireFormat.maxInactivityDuration=500)?useExponentialBackOff=false"); + configureNetworkConnector(networkConnector); + return broker; + } - private void configureNetworkConnector(NetworkConnector networkConnector) { - networkConnector.setDuplex(false); - networkConnector.setNetworkTTL(networkTTL); - networkConnector.setDynamicOnly(dynamicOnly); - } + private void configureNetworkConnector(NetworkConnector networkConnector) { + networkConnector.setDuplex(false); + networkConnector.setNetworkTTL(networkTTL); + networkConnector.setDynamicOnly(dynamicOnly); + } - // variants for each store.... - protected void configureBroker(BrokerService broker) throws Exception { - KahaDBPersistenceAdapter persistenceAdapter = new KahaDBPersistenceAdapter(); - persistenceAdapter.setDirectory(new File("target/activemq-data/kahadb/" + broker.getBrokerName() + "NetworBrokerDetatchTest")); - broker.setPersistenceAdapter(persistenceAdapter); - } + // variants for each store.... + protected void configureBroker(BrokerService broker) throws Exception { + KahaDBPersistenceAdapter persistenceAdapter = new KahaDBPersistenceAdapter(); + persistenceAdapter.setDirectory(new File("target/activemq-data/kahadb/" + broker.getBrokerName() + "NetworBrokerDetatchTest")); + broker.setPersistenceAdapter(persistenceAdapter); + } - @Before - public void init() throws Exception { - broker = createBroker(); - broker.setDeleteAllMessagesOnStartup(true); - broker.start(); + @Before + public void init() throws Exception { + broker = createBroker(); + broker.setDeleteAllMessagesOnStartup(true); + broker.start(); - networkedBroker = createNetworkedBroker(); - networkedBroker.setDeleteAllMessagesOnStartup(true); - networkedBroker.start(); - } + networkedBroker = createNetworkedBroker(); + networkedBroker.setDeleteAllMessagesOnStartup(true); + networkedBroker.start(); + } - @After - public void cleanup() throws Exception { - networkedBroker.stop(); - networkedBroker.waitUntilStopped(); + @After + public void cleanup() throws Exception { + networkedBroker.stop(); + networkedBroker.waitUntilStopped(); - broker.stop(); - broker.waitUntilStopped(); - } + broker.stop(); + broker.waitUntilStopped(); + } - @Test - public void testNetworkedBrokerDetach() throws Exception { - LOG.info("Creating Consumer on the networked broker ..."); - // Create a consumer on the networked broker - ConnectionFactory consFactory = createConnectionFactory(networkedBroker); - Connection consConn = consFactory.createConnection(); - Session consSession = consConn.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination = (ActiveMQDestination) consSession.createQueue(DESTINATION_NAME); - for(int i=0; i", config.getDestinationFilter()); - List dests = new ArrayList(); - config.setDynamicallyIncludedDestinations(dests); - assertEquals(AdvisorySupport.CONSUMER_ADVISORY_TOPIC_PREFIX + ">", config.getDestinationFilter()); - dests.add(new ActiveMQQueue("TEST.>")); - dests.add(new ActiveMQTopic("TEST.>")); - dests.add(new ActiveMQTempQueue("TEST.>")); - String prefix = AdvisorySupport.CONSUMER_ADVISORY_TOPIC_PREFIX; - assertEquals(prefix + "Queue.TEST.>," + prefix + "Topic.TEST.>", config.getDestinationFilter()); - } - + public void testFilter() throws Exception { + NetworkBridgeConfiguration config = new NetworkBridgeConfiguration(); + assertEquals(AdvisorySupport.CONSUMER_ADVISORY_TOPIC_PREFIX + ">", config.getDestinationFilter()); + List dests = new ArrayList(); + config.setDynamicallyIncludedDestinations(dests); + assertEquals(AdvisorySupport.CONSUMER_ADVISORY_TOPIC_PREFIX + ">", config.getDestinationFilter()); + dests.add(new ActiveMQQueue("TEST.>")); + dests.add(new ActiveMQTopic("TEST.>")); + dests.add(new ActiveMQTempQueue("TEST.>")); + String prefix = AdvisorySupport.CONSUMER_ADVISORY_TOPIC_PREFIX; + assertEquals(prefix + "Queue.TEST.>," + prefix + "Topic.TEST.>", config.getDestinationFilter()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkFailoverTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkFailoverTest.java index b695b8cf70..5cb9a12cf8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkFailoverTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkFailoverTest.java @@ -50,183 +50,185 @@ import org.springframework.core.io.Resource; public class NetworkFailoverTest extends TestCase { - protected static final int MESSAGE_COUNT = 10; - private static final Logger LOG = LoggerFactory.getLogger(NetworkFailoverTest.class); + protected static final int MESSAGE_COUNT = 10; + private static final Logger LOG = LoggerFactory.getLogger(NetworkFailoverTest.class); - protected AbstractApplicationContext context; - protected Connection localConnection; - protected Connection remoteConnection; - protected BrokerService localBroker; - protected BrokerService remoteBroker; - protected Session localSession; - protected Session remoteSession; - protected ActiveMQQueue included=new ActiveMQQueue("include.test.foo"); - private final AtomicInteger replyToNonExistDest = new AtomicInteger(0); - private final AtomicInteger roundTripComplete = new AtomicInteger(0); - private final AtomicInteger remoteDLQCount = new AtomicInteger(0); + protected AbstractApplicationContext context; + protected Connection localConnection; + protected Connection remoteConnection; + protected BrokerService localBroker; + protected BrokerService remoteBroker; + protected Session localSession; + protected Session remoteSession; + protected ActiveMQQueue included = new ActiveMQQueue("include.test.foo"); + private final AtomicInteger replyToNonExistDest = new AtomicInteger(0); + private final AtomicInteger roundTripComplete = new AtomicInteger(0); + private final AtomicInteger remoteDLQCount = new AtomicInteger(0); - public void testRequestReply() throws Exception { - final MessageProducer remoteProducer = remoteSession.createProducer(null); - MessageConsumer remoteConsumer = remoteSession.createConsumer(included); - remoteConsumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message msg) { - final TextMessage textMsg = (TextMessage)msg; - try { - String payload = "REPLY: " + textMsg.getText() + ", " + textMsg.getJMSMessageID(); - Destination replyTo; - replyTo = msg.getJMSReplyTo(); - textMsg.clearBody(); - textMsg.setText(payload); - LOG.info("*** Sending response: {}", textMsg.getText()); - remoteProducer.send(replyTo, textMsg); - LOG.info("replied with: " + textMsg.getJMSMessageID()); + public void testRequestReply() throws Exception { + final MessageProducer remoteProducer = remoteSession.createProducer(null); + MessageConsumer remoteConsumer = remoteSession.createConsumer(included); + remoteConsumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message msg) { + final TextMessage textMsg = (TextMessage) msg; + try { + String payload = "REPLY: " + textMsg.getText() + ", " + textMsg.getJMSMessageID(); + Destination replyTo; + replyTo = msg.getJMSReplyTo(); + textMsg.clearBody(); + textMsg.setText(payload); + LOG.info("*** Sending response: {}", textMsg.getText()); + remoteProducer.send(replyTo, textMsg); + LOG.info("replied with: " + textMsg.getJMSMessageID()); - } catch (DestinationDoesNotExistException expected) { - // been removed but not yet recreated - replyToNonExistDest.incrementAndGet(); - try { - LOG.info("NED: " + textMsg.getJMSMessageID()); - } catch (JMSException e) { - e.printStackTrace(); - }; - } catch (Exception e) { - LOG.warn("*** Responder listener caught exception: ", e); - e.printStackTrace(); - } } - }); - - Queue tempQueue = localSession.createTemporaryQueue(); - MessageProducer requestProducer = localSession.createProducer(included); - requestProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - MessageConsumer requestConsumer = localSession.createConsumer(tempQueue); - - // track remote dlq for forward failures - MessageConsumer dlqconsumer = remoteSession.createConsumer(new ActiveMQQueue(SharedDeadLetterStrategy.DEFAULT_DEAD_LETTER_QUEUE_NAME)); - dlqconsumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - try { - LOG.info("dlq " + message.getJMSMessageID()); - } catch (JMSException e) { - e.printStackTrace(); - } - remoteDLQCount.incrementAndGet(); + catch (DestinationDoesNotExistException expected) { + // been removed but not yet recreated + replyToNonExistDest.incrementAndGet(); + try { + LOG.info("NED: " + textMsg.getJMSMessageID()); + } + catch (JMSException e) { + e.printStackTrace(); + } + ; } - }); - - // allow for consumer infos to perculate around - Thread.sleep(2000); - long done = System.currentTimeMillis() + (MESSAGE_COUNT * 6000); - int i = 0; - while (MESSAGE_COUNT > roundTripComplete.get() + remoteDLQCount.get() + replyToNonExistDest.get() - && done > System.currentTimeMillis()) { - if ( i < MESSAGE_COUNT) { - String payload = "test msg " + i; - i++; - TextMessage msg = localSession.createTextMessage(payload); - msg.setJMSReplyTo(tempQueue); - requestProducer.send(msg); - LOG.info("Sent: " + msg.getJMSMessageID() +", Failing over"); - ((FailoverTransport) ((TransportFilter) ((TransportFilter) - ((ActiveMQConnection) localConnection) - .getTransport()).getNext()).getNext()) - .handleTransportFailure(new IOException("Forcing failover from test")); + catch (Exception e) { + LOG.warn("*** Responder listener caught exception: ", e); + e.printStackTrace(); } - TextMessage result = (TextMessage)requestConsumer.receive(5000); - if (result != null) { - LOG.info("Got reply: " + result.getJMSMessageID() + ", " + result.getText()); - roundTripComplete.incrementAndGet(); + } + }); + + Queue tempQueue = localSession.createTemporaryQueue(); + MessageProducer requestProducer = localSession.createProducer(included); + requestProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + MessageConsumer requestConsumer = localSession.createConsumer(tempQueue); + + // track remote dlq for forward failures + MessageConsumer dlqconsumer = remoteSession.createConsumer(new ActiveMQQueue(SharedDeadLetterStrategy.DEFAULT_DEAD_LETTER_QUEUE_NAME)); + dlqconsumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + try { + LOG.info("dlq " + message.getJMSMessageID()); } - } + catch (JMSException e) { + e.printStackTrace(); + } + remoteDLQCount.incrementAndGet(); + } + }); - LOG.info("complete: " + roundTripComplete.get() - + ", remoteDLQCount: " + remoteDLQCount.get() - + ", replyToNonExistDest: " + replyToNonExistDest.get()); - assertEquals("complete:" + roundTripComplete.get() - + ", remoteDLQCount: " + remoteDLQCount.get() - + ", replyToNonExistDest: " + replyToNonExistDest.get(), - MESSAGE_COUNT, roundTripComplete.get() + remoteDLQCount.get() + replyToNonExistDest.get() ); - } + // allow for consumer infos to perculate around + Thread.sleep(2000); + long done = System.currentTimeMillis() + (MESSAGE_COUNT * 6000); + int i = 0; + while (MESSAGE_COUNT > roundTripComplete.get() + remoteDLQCount.get() + replyToNonExistDest.get() && done > System.currentTimeMillis()) { + if (i < MESSAGE_COUNT) { + String payload = "test msg " + i; + i++; + TextMessage msg = localSession.createTextMessage(payload); + msg.setJMSReplyTo(tempQueue); + requestProducer.send(msg); + LOG.info("Sent: " + msg.getJMSMessageID() + ", Failing over"); + ((FailoverTransport) ((TransportFilter) ((TransportFilter) ((ActiveMQConnection) localConnection).getTransport()).getNext()).getNext()).handleTransportFailure(new IOException("Forcing failover from test")); + } + TextMessage result = (TextMessage) requestConsumer.receive(5000); + if (result != null) { + LOG.info("Got reply: " + result.getJMSMessageID() + ", " + result.getText()); + roundTripComplete.incrementAndGet(); + } + } - @Override - protected void setUp() throws Exception { - super.setUp(); - doSetUp(true); - } + LOG.info("complete: " + roundTripComplete.get() + ", remoteDLQCount: " + remoteDLQCount.get() + ", replyToNonExistDest: " + replyToNonExistDest.get()); + assertEquals("complete:" + roundTripComplete.get() + ", remoteDLQCount: " + remoteDLQCount.get() + ", replyToNonExistDest: " + replyToNonExistDest.get(), MESSAGE_COUNT, roundTripComplete.get() + remoteDLQCount.get() + replyToNonExistDest.get()); + } - @Override - protected void tearDown() throws Exception { - doTearDown(); - super.tearDown(); - } + @Override + protected void setUp() throws Exception { + super.setUp(); + doSetUp(true); + } - protected void doTearDown() throws Exception { - try { - localConnection.close(); - remoteConnection.close(); - } catch(Exception ex) {} + @Override + protected void tearDown() throws Exception { + doTearDown(); + super.tearDown(); + } - try { - localBroker.stop(); - } catch(Exception ex) {} - try { - remoteBroker.stop(); - } catch(Exception ex) {} - } + protected void doTearDown() throws Exception { + try { + localConnection.close(); + remoteConnection.close(); + } + catch (Exception ex) { + } - protected void doSetUp(boolean deleteAllMessages) throws Exception { + try { + localBroker.stop(); + } + catch (Exception ex) { + } + try { + remoteBroker.stop(); + } + catch (Exception ex) { + } + } - remoteBroker = createRemoteBroker(); - remoteBroker.setDeleteAllMessagesOnStartup(deleteAllMessages); - remoteBroker.setCacheTempDestinations(true); - remoteBroker.start(); + protected void doSetUp(boolean deleteAllMessages) throws Exception { - localBroker = createLocalBroker(); - localBroker.setDeleteAllMessagesOnStartup(deleteAllMessages); - localBroker.setCacheTempDestinations(true); - localBroker.start(); + remoteBroker = createRemoteBroker(); + remoteBroker.setDeleteAllMessagesOnStartup(deleteAllMessages); + remoteBroker.setCacheTempDestinations(true); + remoteBroker.start(); - String localURI = "tcp://localhost:61616"; - String remoteURI = "tcp://localhost:61617"; - ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory("failover:("+localURI+","+remoteURI+")?randomize=false&backup=false&trackMessages=true"); - localConnection = fac.createConnection(); - localConnection.setClientID("local"); - localConnection.start(); - fac = new ActiveMQConnectionFactory("failover:("+remoteURI + ","+localURI+")?randomize=false&backup=false&trackMessages=true"); - fac.setWatchTopicAdvisories(false); - remoteConnection = fac.createConnection(); - remoteConnection.setClientID("remote"); - remoteConnection.start(); + localBroker = createLocalBroker(); + localBroker.setDeleteAllMessagesOnStartup(deleteAllMessages); + localBroker.setCacheTempDestinations(true); + localBroker.start(); - localSession = localConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - remoteSession = remoteConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } + String localURI = "tcp://localhost:61616"; + String remoteURI = "tcp://localhost:61617"; + ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory("failover:(" + localURI + "," + remoteURI + ")?randomize=false&backup=false&trackMessages=true"); + localConnection = fac.createConnection(); + localConnection.setClientID("local"); + localConnection.start(); + fac = new ActiveMQConnectionFactory("failover:(" + remoteURI + "," + localURI + ")?randomize=false&backup=false&trackMessages=true"); + fac.setWatchTopicAdvisories(false); + remoteConnection = fac.createConnection(); + remoteConnection.setClientID("remote"); + remoteConnection.start(); - protected String getRemoteBrokerURI() { - return "org/apache/activemq/network/remoteBroker.xml"; - } + localSession = localConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + remoteSession = remoteConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + } - protected String getLocalBrokerURI() { - return "org/apache/activemq/network/localBroker.xml"; - } + protected String getRemoteBrokerURI() { + return "org/apache/activemq/network/remoteBroker.xml"; + } - protected BrokerService createBroker(String uri) throws Exception { - Resource resource = new ClassPathResource(uri); - BrokerFactoryBean factory = new BrokerFactoryBean(resource); - resource = new ClassPathResource(uri); - factory = new BrokerFactoryBean(resource); - factory.afterPropertiesSet(); - BrokerService result = factory.getBroker(); - return result; - } + protected String getLocalBrokerURI() { + return "org/apache/activemq/network/localBroker.xml"; + } - protected BrokerService createLocalBroker() throws Exception { - return createBroker(getLocalBrokerURI()); - } + protected BrokerService createBroker(String uri) throws Exception { + Resource resource = new ClassPathResource(uri); + BrokerFactoryBean factory = new BrokerFactoryBean(resource); + resource = new ClassPathResource(uri); + factory = new BrokerFactoryBean(resource); + factory.afterPropertiesSet(); + BrokerService result = factory.getBroker(); + return result; + } - protected BrokerService createRemoteBroker() throws Exception { - return createBroker(getRemoteBrokerURI()); - } + protected BrokerService createLocalBroker() throws Exception { + return createBroker(getLocalBrokerURI()); + } + + protected BrokerService createRemoteBroker() throws Exception { + return createBroker(getRemoteBrokerURI()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkLoadTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkLoadTest.java index 17a0f23719..389bdfdcbd 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkLoadTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkLoadTest.java @@ -53,284 +53,283 @@ import org.slf4j.LoggerFactory; /** * This test case is used to load test store and forwarding between brokers. It sets up - * n brokers to which have a chain of queues which this test consumes and produces to. - * - * If the network bridges gets stuck at any point subsequent queues will not get messages. This test + * n brokers to which have a chain of queues which this test consumes and produces to. + * + * If the network bridges gets stuck at any point subsequent queues will not get messages. This test * samples the production and consumption stats every second and if the flow of messages * get stuck then this test fails. The test monitors the flow of messages for 1 min. - * + * * @author chirino */ public class NetworkLoadTest extends TestCase { - private static final transient Logger LOG = LoggerFactory.getLogger(NetworkLoadTest.class); + private static final transient Logger LOG = LoggerFactory.getLogger(NetworkLoadTest.class); - // How many times do we sample? - private static final long SAMPLES = Integer.parseInt(System.getProperty("SAMPLES", ""+60*1/5)); - // Slower machines might need to make this bigger. - private static final long SAMPLE_DURATION = Integer.parseInt(System.getProperty("SAMPLES_DURATION", "" + 1000 * 5)); - protected static final int BROKER_COUNT = 4; - protected static final int MESSAGE_SIZE = 2000; - String groupId; - - class ForwardingClient { + // How many times do we sample? + private static final long SAMPLES = Integer.parseInt(System.getProperty("SAMPLES", "" + 60 * 1 / 5)); + // Slower machines might need to make this bigger. + private static final long SAMPLE_DURATION = Integer.parseInt(System.getProperty("SAMPLES_DURATION", "" + 1000 * 5)); + protected static final int BROKER_COUNT = 4; + protected static final int MESSAGE_SIZE = 2000; + String groupId; - private final AtomicLong forwardCounter = new AtomicLong(); - private final Connection toConnection; - private final Connection fromConnection; + class ForwardingClient { - public ForwardingClient(int from, int to) throws JMSException { - toConnection = createConnection(from); - Session toSession = toConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageProducer producer = toSession.createProducer(new ActiveMQQueue("Q"+to)); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - producer.setDisableMessageID(true); + private final AtomicLong forwardCounter = new AtomicLong(); + private final Connection toConnection; + private final Connection fromConnection; - fromConnection = createConnection(from); - Session fromSession = fromConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = fromSession.createConsumer(new ActiveMQQueue("Q"+from)); - - consumer.setMessageListener(new MessageListener() { - public void onMessage(Message msg) { - try { - producer.send(msg); - forwardCounter.incrementAndGet(); - } catch (JMSException e) { - // this is caused by the connection getting closed. - } - } - }); - } + public ForwardingClient(int from, int to) throws JMSException { + toConnection = createConnection(from); + Session toSession = toConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final MessageProducer producer = toSession.createProducer(new ActiveMQQueue("Q" + to)); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + producer.setDisableMessageID(true); - public void start() throws JMSException { - toConnection.start(); - fromConnection.start(); - } - - public void stop() throws JMSException { - toConnection.stop(); - fromConnection.stop(); - } - - public void close() throws JMSException { - toConnection.close(); - fromConnection.close(); - } - } + fromConnection = createConnection(from); + Session fromSession = fromConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = fromSession.createConsumer(new ActiveMQQueue("Q" + from)); - private BrokerService[] brokers; - private ForwardingClient[] forwardingClients; + consumer.setMessageListener(new MessageListener() { + public void onMessage(Message msg) { + try { + producer.send(msg); + forwardCounter.incrementAndGet(); + } + catch (JMSException e) { + // this is caused by the connection getting closed. + } + } + }); + } - - protected void setUp() throws Exception { - groupId = "network-load-test-"+System.currentTimeMillis(); - brokers = new BrokerService[BROKER_COUNT]; - for (int i = 0; i < brokers.length; i++) { - LOG.info("Starting broker: "+i); - brokers[i] = createBroker(i); - brokers[i].start(); - } - - // Wait for the network connection to get setup. - // The wait is exponential since every broker has to connect to every other broker. - Thread.sleep(BROKER_COUNT*BROKER_COUNT*50); - - forwardingClients = new ForwardingClient[BROKER_COUNT-1]; - for (int i = 0; i < forwardingClients.length; i++) { - LOG.info("Starting fowarding client "+i); - forwardingClients[i] = new ForwardingClient(i, i+1); - forwardingClients[i].start(); - } - } + public void start() throws JMSException { + toConnection.start(); + fromConnection.start(); + } - protected void tearDown() throws Exception { - for (int i = 0; i < forwardingClients.length; i++) { - LOG.info("Stoping fowarding client "+i); - forwardingClients[i].close(); - } - for (int i = 0; i < brokers.length; i++) { - LOG.info("Stoping broker "+i); - brokers[i].stop(); - } - } + public void stop() throws JMSException { + toConnection.stop(); + fromConnection.stop(); + } - protected Connection createConnection(int brokerId) throws JMSException { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:"+(60000+brokerId)); - connectionFactory.setOptimizedMessageDispatch(true); - connectionFactory.setCopyMessageOnSend(false); - connectionFactory.setUseCompression(false); - connectionFactory.setDispatchAsync(true); - connectionFactory.setUseAsyncSend(false); - connectionFactory.setOptimizeAcknowledge(false); - connectionFactory.setWatchTopicAdvisories(false); - ActiveMQPrefetchPolicy qPrefetchPolicy= new ActiveMQPrefetchPolicy(); - qPrefetchPolicy.setQueuePrefetch(100); - qPrefetchPolicy.setTopicPrefetch(1000); - connectionFactory.setPrefetchPolicy(qPrefetchPolicy); - connectionFactory.setAlwaysSyncSend(true); - return connectionFactory.createConnection(); - } + public void close() throws JMSException { + toConnection.close(); + fromConnection.close(); + } + } - protected BrokerService createBroker(int brokerId) throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("broker-" + brokerId); - broker.setPersistent(false); - broker.setUseJmx(true); - broker.getManagementContext().setCreateConnector(false); + private BrokerService[] brokers; + private ForwardingClient[] forwardingClients; - final SystemUsage memoryManager = new SystemUsage(); - memoryManager.getMemoryUsage().setLimit(1024 * 1024 * 50); // 50 MB - broker.setSystemUsage(memoryManager); + protected void setUp() throws Exception { + groupId = "network-load-test-" + System.currentTimeMillis(); + brokers = new BrokerService[BROKER_COUNT]; + for (int i = 0; i < brokers.length; i++) { + LOG.info("Starting broker: " + i); + brokers[i] = createBroker(i); + brokers[i].start(); + } - final List policyEntries = new ArrayList(); - final PolicyEntry entry = new PolicyEntry(); - entry.setQueue(">"); - entry.setMemoryLimit(1024 * 1024 * 1); // Set to 1 MB - entry.setPendingSubscriberPolicy(new VMPendingSubscriberMessageStoragePolicy()); - entry.setPendingQueuePolicy(new VMPendingQueueMessageStoragePolicy()); - policyEntries.add(entry); + // Wait for the network connection to get setup. + // The wait is exponential since every broker has to connect to every other broker. + Thread.sleep(BROKER_COUNT * BROKER_COUNT * 50); - // This is to turn of the default behavior of storing topic messages for retroactive consumption - final PolicyEntry topicPolicyEntry = new PolicyEntry(); - topicPolicyEntry.setTopic(">"); - final NoSubscriptionRecoveryPolicy noSubscriptionRecoveryPolicy = new NoSubscriptionRecoveryPolicy(); - topicPolicyEntry.setSubscriptionRecoveryPolicy(noSubscriptionRecoveryPolicy); + forwardingClients = new ForwardingClient[BROKER_COUNT - 1]; + for (int i = 0; i < forwardingClients.length; i++) { + LOG.info("Starting fowarding client " + i); + forwardingClients[i] = new ForwardingClient(i, i + 1); + forwardingClients[i].start(); + } + } - final PolicyMap policyMap = new PolicyMap(); - policyMap.setPolicyEntries(policyEntries); - broker.setDestinationPolicy(policyMap); - - TransportConnector transportConnector = new TransportConnector(); - transportConnector.setUri(new URI("tcp://localhost:"+(60000+brokerId))); - - transportConnector.setDiscoveryUri(new URI("multicast://default?group="+groupId)); - broker.addConnector(transportConnector); - - DiscoveryNetworkConnector networkConnector = new DiscoveryNetworkConnector(); - networkConnector.setUri(new URI("multicast://default?group="+groupId)); - networkConnector.setBridgeTempDestinations(true); - networkConnector.setPrefetchSize(1); - broker.addNetworkConnector(networkConnector); - - return broker; - } - - public void testRequestReply() throws Exception { + protected void tearDown() throws Exception { + for (int i = 0; i < forwardingClients.length; i++) { + LOG.info("Stoping fowarding client " + i); + forwardingClients[i].close(); + } + for (int i = 0; i < brokers.length; i++) { + LOG.info("Stoping broker " + i); + brokers[i].stop(); + } + } - final int to = 0; // Send to the first broker - int from = brokers.length-1; // consume from the last broker.. - - LOG.info("Staring Final Consumer"); + protected Connection createConnection(int brokerId) throws JMSException { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:" + (60000 + brokerId)); + connectionFactory.setOptimizedMessageDispatch(true); + connectionFactory.setCopyMessageOnSend(false); + connectionFactory.setUseCompression(false); + connectionFactory.setDispatchAsync(true); + connectionFactory.setUseAsyncSend(false); + connectionFactory.setOptimizeAcknowledge(false); + connectionFactory.setWatchTopicAdvisories(false); + ActiveMQPrefetchPolicy qPrefetchPolicy = new ActiveMQPrefetchPolicy(); + qPrefetchPolicy.setQueuePrefetch(100); + qPrefetchPolicy.setTopicPrefetch(1000); + connectionFactory.setPrefetchPolicy(qPrefetchPolicy); + connectionFactory.setAlwaysSyncSend(true); + return connectionFactory.createConnection(); + } - Connection fromConnection = createConnection(from); - fromConnection.start(); - Session fromSession = fromConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = fromSession.createConsumer(new ActiveMQQueue("Q"+from)); - - final AtomicReference lastMessageReceived = new AtomicReference(); - final AtomicLong producedMessages = new AtomicLong(); - final AtomicLong receivedMessages = new AtomicLong(); - final AtomicBoolean done = new AtomicBoolean(); + protected BrokerService createBroker(int brokerId) throws Exception { + BrokerService broker = new BrokerService(); + broker.setBrokerName("broker-" + brokerId); + broker.setPersistent(false); + broker.setUseJmx(true); + broker.getManagementContext().setCreateConnector(false); - // Setup the consumer.. - consumer.setMessageListener(new MessageListener() { - public void onMessage(Message msg) { - ActiveMQTextMessage m = (ActiveMQTextMessage) msg; - ActiveMQTextMessage last = lastMessageReceived.get(); - if( last!=null ) { - // Some order checking... - if( last.getMessageId().getProducerSequenceId() > m.getMessageId().getProducerSequenceId() ) { - System.out.println("Received an out of order message. Got "+m.getMessageId()+", expected something after "+last.getMessageId()); - } - } - lastMessageReceived.set(m); - receivedMessages.incrementAndGet(); - } - }); + final SystemUsage memoryManager = new SystemUsage(); + memoryManager.getMemoryUsage().setLimit(1024 * 1024 * 50); // 50 MB + broker.setSystemUsage(memoryManager); - LOG.info("Staring Initial Producer"); - final Connection toConnection = createConnection(to); - Thread producer = new Thread("Producer") { - @Override - public void run() { - try { - toConnection.start(); - Session toSession = toConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageProducer producer = toSession.createProducer(new ActiveMQQueue("Q"+to)); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - producer.setDisableMessageID(true); + final List policyEntries = new ArrayList(); + final PolicyEntry entry = new PolicyEntry(); + entry.setQueue(">"); + entry.setMemoryLimit(1024 * 1024 * 1); // Set to 1 MB + entry.setPendingSubscriberPolicy(new VMPendingSubscriberMessageStoragePolicy()); + entry.setPendingQueuePolicy(new VMPendingQueueMessageStoragePolicy()); + policyEntries.add(entry); - for (int i = 0; !done.get(); i++) { - TextMessage msg = toSession.createTextMessage(createMessageText(i)); - producer.send(msg); - producedMessages.incrementAndGet(); - } - } catch (JMSException e) { - e.printStackTrace(); - } - } - - private String createMessageText(int index) { - StringBuffer buffer = new StringBuffer(MESSAGE_SIZE); - buffer.append(index + " on " + new Date() + " ..."); - if (buffer.length() > MESSAGE_SIZE) { - return buffer.substring(0, MESSAGE_SIZE); - } - for (int i = buffer.length(); i < MESSAGE_SIZE; i++) { - buffer.append(' '); - } + // This is to turn of the default behavior of storing topic messages for retroactive consumption + final PolicyEntry topicPolicyEntry = new PolicyEntry(); + topicPolicyEntry.setTopic(">"); + final NoSubscriptionRecoveryPolicy noSubscriptionRecoveryPolicy = new NoSubscriptionRecoveryPolicy(); + topicPolicyEntry.setSubscriptionRecoveryPolicy(noSubscriptionRecoveryPolicy); - return buffer.toString(); - } - }; - producer.start(); - - - // Give the forwarding clients a chance to get going and fill the down - // stream broker queues.. - Thread.sleep(BROKER_COUNT*200); - - for (int i = 0; i < SAMPLES; i++) { + final PolicyMap policyMap = new PolicyMap(); + policyMap.setPolicyEntries(policyEntries); + broker.setDestinationPolicy(policyMap); - long start = System.currentTimeMillis(); - producedMessages.set(0); - receivedMessages.set(0); - for (int j = 0; j < forwardingClients.length; j++) { - forwardingClients[j].forwardCounter.set(0); - } + TransportConnector transportConnector = new TransportConnector(); + transportConnector.setUri(new URI("tcp://localhost:" + (60000 + brokerId))); - Thread.sleep(SAMPLE_DURATION); + transportConnector.setDiscoveryUri(new URI("multicast://default?group=" + groupId)); + broker.addConnector(transportConnector); - long end = System.currentTimeMillis(); - long r = receivedMessages.get(); - long p = producedMessages.get(); + DiscoveryNetworkConnector networkConnector = new DiscoveryNetworkConnector(); + networkConnector.setUri(new URI("multicast://default?group=" + groupId)); + networkConnector.setBridgeTempDestinations(true); + networkConnector.setPrefetchSize(1); + broker.addNetworkConnector(networkConnector); - LOG.info("published: " + p + " msgs at " + (p * 1000f / (end - start)) + " msgs/sec, " + "consumed: " + r + " msgs at " + (r * 1000f / (end - start)) + " msgs/sec"); - - StringBuffer fwdingmsg = new StringBuffer(500); - fwdingmsg.append(" forwarding counters: "); - for (int j = 0; j < forwardingClients.length; j++) { - if( j!= 0 ) { - fwdingmsg.append(", "); - } - fwdingmsg.append(forwardingClients[j].forwardCounter.get()); - } - LOG.info(fwdingmsg.toString()); + return broker; + } - // The test is just checking to make sure thaat the producer and consumer does not hang - // due to the network hops take to route the message form the producer to the consumer. - assertTrue("Received some messages since last sample", r>0); - assertTrue("Produced some messages since last sample", p>0); - - } - LOG.info("Sample done."); - done.set(true); - // Wait for the producer to finish. - producer.join(1000*5); - toConnection.close(); - fromConnection.close(); - - } + public void testRequestReply() throws Exception { + final int to = 0; // Send to the first broker + int from = brokers.length - 1; // consume from the last broker.. + + LOG.info("Staring Final Consumer"); + + Connection fromConnection = createConnection(from); + fromConnection.start(); + Session fromSession = fromConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = fromSession.createConsumer(new ActiveMQQueue("Q" + from)); + + final AtomicReference lastMessageReceived = new AtomicReference(); + final AtomicLong producedMessages = new AtomicLong(); + final AtomicLong receivedMessages = new AtomicLong(); + final AtomicBoolean done = new AtomicBoolean(); + + // Setup the consumer.. + consumer.setMessageListener(new MessageListener() { + public void onMessage(Message msg) { + ActiveMQTextMessage m = (ActiveMQTextMessage) msg; + ActiveMQTextMessage last = lastMessageReceived.get(); + if (last != null) { + // Some order checking... + if (last.getMessageId().getProducerSequenceId() > m.getMessageId().getProducerSequenceId()) { + System.out.println("Received an out of order message. Got " + m.getMessageId() + ", expected something after " + last.getMessageId()); + } + } + lastMessageReceived.set(m); + receivedMessages.incrementAndGet(); + } + }); + + LOG.info("Staring Initial Producer"); + final Connection toConnection = createConnection(to); + Thread producer = new Thread("Producer") { + @Override + public void run() { + try { + toConnection.start(); + Session toSession = toConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final MessageProducer producer = toSession.createProducer(new ActiveMQQueue("Q" + to)); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + producer.setDisableMessageID(true); + + for (int i = 0; !done.get(); i++) { + TextMessage msg = toSession.createTextMessage(createMessageText(i)); + producer.send(msg); + producedMessages.incrementAndGet(); + } + } + catch (JMSException e) { + e.printStackTrace(); + } + } + + private String createMessageText(int index) { + StringBuffer buffer = new StringBuffer(MESSAGE_SIZE); + buffer.append(index + " on " + new Date() + " ..."); + if (buffer.length() > MESSAGE_SIZE) { + return buffer.substring(0, MESSAGE_SIZE); + } + for (int i = buffer.length(); i < MESSAGE_SIZE; i++) { + buffer.append(' '); + } + + return buffer.toString(); + } + }; + producer.start(); + + // Give the forwarding clients a chance to get going and fill the down + // stream broker queues.. + Thread.sleep(BROKER_COUNT * 200); + + for (int i = 0; i < SAMPLES; i++) { + + long start = System.currentTimeMillis(); + producedMessages.set(0); + receivedMessages.set(0); + for (int j = 0; j < forwardingClients.length; j++) { + forwardingClients[j].forwardCounter.set(0); + } + + Thread.sleep(SAMPLE_DURATION); + + long end = System.currentTimeMillis(); + long r = receivedMessages.get(); + long p = producedMessages.get(); + + LOG.info("published: " + p + " msgs at " + (p * 1000f / (end - start)) + " msgs/sec, " + "consumed: " + r + " msgs at " + (r * 1000f / (end - start)) + " msgs/sec"); + + StringBuffer fwdingmsg = new StringBuffer(500); + fwdingmsg.append(" forwarding counters: "); + for (int j = 0; j < forwardingClients.length; j++) { + if (j != 0) { + fwdingmsg.append(", "); + } + fwdingmsg.append(forwardingClients[j].forwardCounter.get()); + } + LOG.info(fwdingmsg.toString()); + + // The test is just checking to make sure thaat the producer and consumer does not hang + // due to the network hops take to route the message form the producer to the consumer. + assertTrue("Received some messages since last sample", r > 0); + assertTrue("Produced some messages since last sample", p > 0); + + } + LOG.info("Sample done."); + done.set(true); + // Wait for the producer to finish. + producer.join(1000 * 5); + toConnection.close(); + fromConnection.close(); + + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkLoopBackTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkLoopBackTest.java index 62b79b1668..27c0e58a4d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkLoopBackTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkLoopBackTest.java @@ -25,41 +25,42 @@ import org.apache.activemq.util.Wait; import org.junit.Test; public class NetworkLoopBackTest { - @Test - public void testLoopbackOnDifferentUrlScheme() throws Exception { - final BrokerService brokerServce = new BrokerService(); - brokerServce.setPersistent(false); - TransportConnector transportConnector = brokerServce.addConnector("nio://0.0.0.0:0"); - // connection filter is bypassed when scheme is different - final NetworkConnector networkConnector = brokerServce.addNetworkConnector("static:(tcp://" - + transportConnector.getConnectUri().getHost() + ":" + transportConnector.getConnectUri().getPort() + ")"); + @Test + public void testLoopbackOnDifferentUrlScheme() throws Exception { + final BrokerService brokerServce = new BrokerService(); + brokerServce.setPersistent(false); - brokerServce.start(); - brokerServce.waitUntilStarted(); + TransportConnector transportConnector = brokerServce.addConnector("nio://0.0.0.0:0"); + // connection filter is bypassed when scheme is different + final NetworkConnector networkConnector = brokerServce.addNetworkConnector("static:(tcp://" + transportConnector.getConnectUri().getHost() + ":" + transportConnector.getConnectUri().getPort() + ")"); - try { - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return 1 == networkConnector.bridges.size(); - } - }); + brokerServce.start(); + brokerServce.waitUntilStarted(); - final DemandForwardingBridgeSupport loopbackBridge = (DemandForwardingBridgeSupport) networkConnector.bridges.elements().nextElement(); - assertTrue("nc started", networkConnector.isStarted()); + try { + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return 1 == networkConnector.bridges.size(); + } + }); - assertTrue("It should get disposed", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return loopbackBridge.getRemoteBroker().isDisposed(); - } - })); + final DemandForwardingBridgeSupport loopbackBridge = (DemandForwardingBridgeSupport) networkConnector.bridges.elements().nextElement(); + assertTrue("nc started", networkConnector.isStarted()); - assertEquals("No peer brokers", 0, brokerServce.getBroker().getPeerBrokerInfos().length); + assertTrue("It should get disposed", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return loopbackBridge.getRemoteBroker().isDisposed(); + } + })); - } finally { - brokerServce.stop(); - } - } + assertEquals("No peer brokers", 0, brokerServce.getBroker().getPeerBrokerInfos().length); + + } + finally { + brokerServce.stop(); + } + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkReconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkReconnectTest.java index 68376e16a7..1984a1f4af 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkReconnectTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkReconnectTest.java @@ -30,6 +30,7 @@ import javax.jms.MessageProducer; import javax.jms.Session; import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.advisory.ConsumerEvent; import org.apache.activemq.advisory.ConsumerEventSource; @@ -43,284 +44,289 @@ import org.slf4j.LoggerFactory; /** * These test cases are used to verifiy that network connections get re * established in all broker restart scenarios. - * + * * @author chirino */ public class NetworkReconnectTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(NetworkReconnectTest.class); + private static final Logger LOG = LoggerFactory.getLogger(NetworkReconnectTest.class); - private BrokerService producerBroker; - private BrokerService consumerBroker; - private ActiveMQConnectionFactory producerConnectionFactory; - private ActiveMQConnectionFactory consumerConnectionFactory; - private Destination destination; - private ArrayList connections = new ArrayList(); + private BrokerService producerBroker; + private BrokerService consumerBroker; + private ActiveMQConnectionFactory producerConnectionFactory; + private ActiveMQConnectionFactory consumerConnectionFactory; + private Destination destination; + private ArrayList connections = new ArrayList(); - public void xtestMultipleProducerBrokerRestarts() throws Exception { - for (int i = 0; i < 10; i++) { - testWithProducerBrokerRestart(); - disposeConsumerConnections(); - } - } + public void xtestMultipleProducerBrokerRestarts() throws Exception { + for (int i = 0; i < 10; i++) { + testWithProducerBrokerRestart(); + disposeConsumerConnections(); + } + } - public void xtestWithoutRestarts() throws Exception { - startProducerBroker(); - startConsumerBroker(); + public void xtestWithoutRestarts() throws Exception { + startProducerBroker(); + startConsumerBroker(); - MessageConsumer consumer = createConsumer(); - AtomicInteger counter = createConsumerCounter(producerConnectionFactory); - waitForConsumerToArrive(counter); + MessageConsumer consumer = createConsumer(); + AtomicInteger counter = createConsumerCounter(producerConnectionFactory); + waitForConsumerToArrive(counter); - String messageId = sendMessage(); - Message message = consumer.receive(1000); + String messageId = sendMessage(); + Message message = consumer.receive(1000); - assertEquals(messageId, message.getJMSMessageID()); + assertEquals(messageId, message.getJMSMessageID()); - assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); - } + } - public void testWithProducerBrokerRestart() throws Exception { - startProducerBroker(); - startConsumerBroker(); + public void testWithProducerBrokerRestart() throws Exception { + startProducerBroker(); + startConsumerBroker(); - MessageConsumer consumer = createConsumer(); - AtomicInteger counter = createConsumerCounter(producerConnectionFactory); - waitForConsumerToArrive(counter); + MessageConsumer consumer = createConsumer(); + AtomicInteger counter = createConsumerCounter(producerConnectionFactory); + waitForConsumerToArrive(counter); - String messageId = sendMessage(); - Message message = consumer.receive(1000); + String messageId = sendMessage(); + Message message = consumer.receive(1000); - assertEquals(messageId, message.getJMSMessageID()); - assertNull(consumer.receiveNoWait()); + assertEquals(messageId, message.getJMSMessageID()); + assertNull(consumer.receiveNoWait()); - // Restart the first broker... - stopProducerBroker(); - startProducerBroker(); + // Restart the first broker... + stopProducerBroker(); + startProducerBroker(); - counter = createConsumerCounter(producerConnectionFactory); - waitForConsumerToArrive(counter); + counter = createConsumerCounter(producerConnectionFactory); + waitForConsumerToArrive(counter); - messageId = sendMessage(); - message = consumer.receive(1000); + messageId = sendMessage(); + message = consumer.receive(1000); - assertEquals(messageId, message.getJMSMessageID()); - assertNull(consumer.receiveNoWait()); + assertEquals(messageId, message.getJMSMessageID()); + assertNull(consumer.receiveNoWait()); - } + } - public void xtestWithConsumerBrokerRestart() throws Exception { + public void xtestWithConsumerBrokerRestart() throws Exception { - startProducerBroker(); - startConsumerBroker(); + startProducerBroker(); + startConsumerBroker(); - MessageConsumer consumer = createConsumer(); - AtomicInteger counter = createConsumerCounter(producerConnectionFactory); - waitForConsumerToArrive(counter); + MessageConsumer consumer = createConsumer(); + AtomicInteger counter = createConsumerCounter(producerConnectionFactory); + waitForConsumerToArrive(counter); - String messageId = sendMessage(); - Message message = consumer.receive(1000); + String messageId = sendMessage(); + Message message = consumer.receive(1000); - assertEquals(messageId, message.getJMSMessageID()); - assertNull(consumer.receiveNoWait()); + assertEquals(messageId, message.getJMSMessageID()); + assertNull(consumer.receiveNoWait()); - // Restart the first broker... - stopConsumerBroker(); - waitForConsumerToLeave(counter); - startConsumerBroker(); + // Restart the first broker... + stopConsumerBroker(); + waitForConsumerToLeave(counter); + startConsumerBroker(); - consumer = createConsumer(); - waitForConsumerToArrive(counter); + consumer = createConsumer(); + waitForConsumerToArrive(counter); - messageId = sendMessage(); - message = consumer.receive(1000); + messageId = sendMessage(); + message = consumer.receive(1000); - assertEquals(messageId, message.getJMSMessageID()); - assertNull(consumer.receiveNoWait()); + assertEquals(messageId, message.getJMSMessageID()); + assertNull(consumer.receiveNoWait()); - } + } - public void xtestWithConsumerBrokerStartDelay() throws Exception { + public void xtestWithConsumerBrokerStartDelay() throws Exception { - startConsumerBroker(); - MessageConsumer consumer = createConsumer(); + startConsumerBroker(); + MessageConsumer consumer = createConsumer(); - Thread.sleep(1000 * 5); + Thread.sleep(1000 * 5); - startProducerBroker(); - AtomicInteger counter = createConsumerCounter(producerConnectionFactory); - waitForConsumerToArrive(counter); + startProducerBroker(); + AtomicInteger counter = createConsumerCounter(producerConnectionFactory); + waitForConsumerToArrive(counter); - String messageId = sendMessage(); - Message message = consumer.receive(1000); + String messageId = sendMessage(); + Message message = consumer.receive(1000); - assertEquals(messageId, message.getJMSMessageID()); + assertEquals(messageId, message.getJMSMessageID()); - assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); - } + } - public void xtestWithProducerBrokerStartDelay() throws Exception { + public void xtestWithProducerBrokerStartDelay() throws Exception { - startProducerBroker(); - AtomicInteger counter = createConsumerCounter(producerConnectionFactory); + startProducerBroker(); + AtomicInteger counter = createConsumerCounter(producerConnectionFactory); - Thread.sleep(1000 * 5); + Thread.sleep(1000 * 5); - startConsumerBroker(); - MessageConsumer consumer = createConsumer(); + startConsumerBroker(); + MessageConsumer consumer = createConsumer(); - waitForConsumerToArrive(counter); + waitForConsumerToArrive(counter); - String messageId = sendMessage(); - Message message = consumer.receive(1000); + String messageId = sendMessage(); + Message message = consumer.receive(1000); - assertEquals(messageId, message.getJMSMessageID()); + assertEquals(messageId, message.getJMSMessageID()); - assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); - } + } - protected void setUp() throws Exception { + protected void setUp() throws Exception { - LOG.info("==============================================================================="); - LOG.info("Running Test Case: " + getName()); - LOG.info("==============================================================================="); + LOG.info("==============================================================================="); + LOG.info("Running Test Case: " + getName()); + LOG.info("==============================================================================="); - producerConnectionFactory = createProducerConnectionFactory(); - consumerConnectionFactory = createConsumerConnectionFactory(); - destination = new ActiveMQQueue("RECONNECT.TEST.QUEUE"); + producerConnectionFactory = createProducerConnectionFactory(); + consumerConnectionFactory = createConsumerConnectionFactory(); + destination = new ActiveMQQueue("RECONNECT.TEST.QUEUE"); - } + } - protected void tearDown() throws Exception { - disposeConsumerConnections(); - try { - stopProducerBroker(); - } catch (Throwable e) { - } - try { - stopConsumerBroker(); - } catch (Throwable e) { - } - } - - protected void disposeConsumerConnections() { - for (Iterator iter = connections.iterator(); iter.hasNext();) { - Connection connection = iter.next(); - try { - connection.close(); - } catch (Throwable ignore) { - } - } - } - - protected void startProducerBroker() throws Exception { - if (producerBroker == null) { - producerBroker = createFirstBroker(); - producerBroker.start(); - } - } - - protected void stopProducerBroker() throws Exception { - if (producerBroker != null) { - producerBroker.stop(); - producerBroker = null; - } - } - - protected void startConsumerBroker() throws Exception { - if (consumerBroker == null) { - consumerBroker = createSecondBroker(); - consumerBroker.start(); - } - } - - protected void stopConsumerBroker() throws Exception { - if (consumerBroker != null) { - consumerBroker.stop(); - consumerBroker = null; - } - } - - protected BrokerService createFirstBroker() throws Exception { - return BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/network/reconnect-broker1.xml")); - } - - protected BrokerService createSecondBroker() throws Exception { - return BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/network/reconnect-broker2.xml")); - } - - protected ActiveMQConnectionFactory createProducerConnectionFactory() { - return new ActiveMQConnectionFactory("vm://broker1"); - } - - protected ActiveMQConnectionFactory createConsumerConnectionFactory() { - return new ActiveMQConnectionFactory("vm://broker2"); - } - - protected String sendMessage() throws JMSException { - Connection connection = null; - try { - connection = producerConnectionFactory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - Message message = session.createMessage(); - producer.send(message); - return message.getJMSMessageID(); - } finally { - try { - connection.close(); - } catch (Throwable ignore) { - } - } - } - - protected MessageConsumer createConsumer() throws JMSException { - Connection connection = consumerConnectionFactory.createConnection(); - connections.add(connection); - connection.start(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - return session.createConsumer(destination); - } - - protected AtomicInteger createConsumerCounter(ActiveMQConnectionFactory cf) throws Exception { - final AtomicInteger rc = new AtomicInteger(0); - Connection connection = cf.createConnection(); - connections.add(connection); - connection.start(); - - ConsumerEventSource source = new ConsumerEventSource(connection, destination); - source.setConsumerListener(new ConsumerListener() { - public void onConsumerEvent(ConsumerEvent event) { - rc.set(event.getConsumerCount()); - } - }); - source.start(); - - return rc; - } - - protected void waitForConsumerToArrive(AtomicInteger consumerCounter) throws InterruptedException { - for (int i = 0; i < 100; i++) { - if (consumerCounter.get() > 0) { - return; - } - Thread.sleep(100); - } - fail("The consumer did not arrive."); - } - - protected void waitForConsumerToLeave(AtomicInteger consumerCounter) throws InterruptedException { - for (int i = 0; i < 100; i++) { - if (consumerCounter.get() == 0) { - return; - } - Thread.sleep(100); - } - fail("The consumer did not leave."); - } + protected void tearDown() throws Exception { + disposeConsumerConnections(); + try { + stopProducerBroker(); + } + catch (Throwable e) { + } + try { + stopConsumerBroker(); + } + catch (Throwable e) { + } + } + + protected void disposeConsumerConnections() { + for (Iterator iter = connections.iterator(); iter.hasNext(); ) { + Connection connection = iter.next(); + try { + connection.close(); + } + catch (Throwable ignore) { + } + } + } + + protected void startProducerBroker() throws Exception { + if (producerBroker == null) { + producerBroker = createFirstBroker(); + producerBroker.start(); + } + } + + protected void stopProducerBroker() throws Exception { + if (producerBroker != null) { + producerBroker.stop(); + producerBroker = null; + } + } + + protected void startConsumerBroker() throws Exception { + if (consumerBroker == null) { + consumerBroker = createSecondBroker(); + consumerBroker.start(); + } + } + + protected void stopConsumerBroker() throws Exception { + if (consumerBroker != null) { + consumerBroker.stop(); + consumerBroker = null; + } + } + + protected BrokerService createFirstBroker() throws Exception { + return BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/network/reconnect-broker1.xml")); + } + + protected BrokerService createSecondBroker() throws Exception { + return BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/network/reconnect-broker2.xml")); + } + + protected ActiveMQConnectionFactory createProducerConnectionFactory() { + return new ActiveMQConnectionFactory("vm://broker1"); + } + + protected ActiveMQConnectionFactory createConsumerConnectionFactory() { + return new ActiveMQConnectionFactory("vm://broker2"); + } + + protected String sendMessage() throws JMSException { + Connection connection = null; + try { + connection = producerConnectionFactory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + Message message = session.createMessage(); + producer.send(message); + return message.getJMSMessageID(); + } + finally { + try { + connection.close(); + } + catch (Throwable ignore) { + } + } + } + + protected MessageConsumer createConsumer() throws JMSException { + Connection connection = consumerConnectionFactory.createConnection(); + connections.add(connection); + connection.start(); + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + return session.createConsumer(destination); + } + + protected AtomicInteger createConsumerCounter(ActiveMQConnectionFactory cf) throws Exception { + final AtomicInteger rc = new AtomicInteger(0); + Connection connection = cf.createConnection(); + connections.add(connection); + connection.start(); + + ConsumerEventSource source = new ConsumerEventSource(connection, destination); + source.setConsumerListener(new ConsumerListener() { + public void onConsumerEvent(ConsumerEvent event) { + rc.set(event.getConsumerCount()); + } + }); + source.start(); + + return rc; + } + + protected void waitForConsumerToArrive(AtomicInteger consumerCounter) throws InterruptedException { + for (int i = 0; i < 100; i++) { + if (consumerCounter.get() > 0) { + return; + } + Thread.sleep(100); + } + fail("The consumer did not arrive."); + } + + protected void waitForConsumerToLeave(AtomicInteger consumerCounter) throws InterruptedException { + for (int i = 0; i < 100; i++) { + if (consumerCounter.get() == 0) { + return; + } + Thread.sleep(100); + } + fail("The consumer did not leave."); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRemovesSubscriptionsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRemovesSubscriptionsTest.java index b444379877..7c2a61d22d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRemovesSubscriptionsTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRemovesSubscriptionsTest.java @@ -22,7 +22,9 @@ import javax.jms.Session; import javax.jms.TopicConnection; import javax.jms.TopicSession; import javax.jms.TopicSubscriber; + import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.region.Destination; @@ -31,160 +33,159 @@ import org.apache.activemq.command.ActiveMQTopic; /** * Various Tests to show the memory leak suspect in network of brokers. This is * for https://issues.apache.org/activemq/browse/AMQ-2530 - * */ public class NetworkRemovesSubscriptionsTest extends TestCase { - private final static String frontEndAddress = "tcp://0.0.0.0:61617"; - private final static String backEndAddress = "tcp://0.0.0.0:61616"; - private final static String TOPIC_NAME = "TEST_TOPIC"; - private BrokerService frontEnd; - private BrokerService backEnd; - private final ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(frontEndAddress); - private final ActiveMQTopic topic = new ActiveMQTopic(TOPIC_NAME); - public void testWithSessionAndSubsciberClose() throws Exception { + private final static String frontEndAddress = "tcp://0.0.0.0:61617"; + private final static String backEndAddress = "tcp://0.0.0.0:61616"; + private final static String TOPIC_NAME = "TEST_TOPIC"; + private BrokerService frontEnd; + private BrokerService backEnd; + private final ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(frontEndAddress); + private final ActiveMQTopic topic = new ActiveMQTopic(TOPIC_NAME); - TopicConnection connection = connectionFactory.createTopicConnection(); - connection.start(); + public void testWithSessionAndSubsciberClose() throws Exception { - for (int i = 0; i < 100; i++) { - TopicSession subscriberSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber subscriber = subscriberSession.createSubscriber(topic); - DummyMessageListener listener = new DummyMessageListener(); - subscriber.setMessageListener(listener); + TopicConnection connection = connectionFactory.createTopicConnection(); + connection.start(); + + for (int i = 0; i < 100; i++) { + TopicSession subscriberSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); + TopicSubscriber subscriber = subscriberSession.createSubscriber(topic); + DummyMessageListener listener = new DummyMessageListener(); + subscriber.setMessageListener(listener); + subscriber.close(); + subscriberSession.close(); + } + connection.close(); + Thread.sleep(1000); + Destination dest = backEnd.getRegionBroker().getDestinationMap().get(topic); + assertNotNull(dest); + assertTrue(dest.getConsumers().isEmpty()); + } + + public void testWithSessionCloseOutsideTheLoop() throws Exception { + + TopicConnection connection = connectionFactory.createTopicConnection(); + connection.start(); + TopicSession subscriberSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); + for (int i = 0; i < 100; i++) { + + TopicSubscriber subscriber = subscriberSession.createSubscriber(topic); + DummyMessageListener listener = new DummyMessageListener(); + subscriber.setMessageListener(listener); + subscriber.close(); + } + subscriberSession.close(); + connection.close(); + Thread.sleep(1000); + Destination dest = backEnd.getRegionBroker().getDestinationMap().get(topic); + assertNotNull(dest); + assertTrue(dest.getConsumers().isEmpty()); + + } + + public void testWithOneSubscriber() throws Exception { + + TopicConnection connection = connectionFactory.createTopicConnection(); + connection.start(); + TopicSession subscriberSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); + + TopicSubscriber subscriber = subscriberSession.createSubscriber(topic); + DummyMessageListener listener = new DummyMessageListener(); + subscriber.setMessageListener(listener); + subscriber.close(); + subscriberSession.close(); + connection.close(); + Thread.sleep(1000); + Destination dest = backEnd.getRegionBroker().getDestinationMap().get(topic); + assertNotNull(dest); + assertTrue(dest.getConsumers().isEmpty()); + } + + public void testWithoutSessionAndSubsciberClose() throws Exception { + + TopicConnection connection = connectionFactory.createTopicConnection(); + connection.start(); + + for (int i = 0; i < 100; i++) { + TopicSession subscriberSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); + TopicSubscriber subscriber = subscriberSession.createSubscriber(topic); + assertNotNull(subscriber); + } + + connection.close(); + Thread.sleep(1000); + Destination dest = backEnd.getRegionBroker().getDestinationMap().get(topic); + assertNotNull(dest); + assertTrue(dest.getConsumers().isEmpty()); + } + + /** + * Running this test you can produce a leak of only 2 ConsumerInfo on BE + * broker, NOT 200 as in other cases! + */ + public void testWithoutSessionAndSubsciberClosePlayAround() throws Exception { + + TopicConnection connection = connectionFactory.createTopicConnection(); + connection.start(); + + for (int i = 0; i < 100; i++) { + TopicSession subscriberSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); + TopicSubscriber subscriber = subscriberSession.createSubscriber(topic); + DummyMessageListener listener = new DummyMessageListener(); + subscriber.setMessageListener(listener); + if (i != 50) { subscriber.close(); subscriberSession.close(); - } - connection.close(); - Thread.sleep(1000); - Destination dest = backEnd.getRegionBroker().getDestinationMap().get(topic); - assertNotNull(dest); - assertTrue(dest.getConsumers().isEmpty()); - } + } + } - public void testWithSessionCloseOutsideTheLoop() throws Exception { + connection.close(); + Thread.sleep(1000); + Destination dest = backEnd.getRegionBroker().getDestinationMap().get(topic); + assertNotNull(dest); + assertTrue(dest.getConsumers().isEmpty()); + } - TopicConnection connection = connectionFactory.createTopicConnection(); - connection.start(); - TopicSession subscriberSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - for (int i = 0; i < 100; i++) { + class DummyMessageListener implements MessageListener { - TopicSubscriber subscriber = subscriberSession.createSubscriber(topic); - DummyMessageListener listener = new DummyMessageListener(); - subscriber.setMessageListener(listener); - subscriber.close(); - } - subscriberSession.close(); - connection.close(); - Thread.sleep(1000); - Destination dest = backEnd.getRegionBroker().getDestinationMap().get(topic); - assertNotNull(dest); - assertTrue(dest.getConsumers().isEmpty()); + @Override + public void onMessage(Message arg0) { + // TODO Auto-generated method stub - } + } + } - public void testWithOneSubscriber() throws Exception { + @Override + protected void setUp() throws Exception { + this.backEnd = new BrokerService(); + this.backEnd.setBrokerName("backEnd"); + this.backEnd.setPersistent(false); + NetworkConnector backEndNetwork = this.backEnd.addNetworkConnector("static://" + frontEndAddress); + backEndNetwork.setName("backEndNetwork"); + backEndNetwork.setDynamicOnly(true); + this.backEnd.addConnector(backEndAddress); + this.backEnd.start(); - TopicConnection connection = connectionFactory.createTopicConnection(); - connection.start(); - TopicSession subscriberSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); + this.frontEnd = new BrokerService(); + this.frontEnd.setBrokerName("frontEnd"); + this.frontEnd.setPersistent(false); + NetworkConnector frontEndNetwork = this.frontEnd.addNetworkConnector("static://" + backEndAddress); + frontEndNetwork.setName("frontEndNetwork"); + this.frontEnd.addConnector(frontEndAddress); + this.frontEnd.start(); + Thread.sleep(2000); + } - TopicSubscriber subscriber = subscriberSession.createSubscriber(topic); - DummyMessageListener listener = new DummyMessageListener(); - subscriber.setMessageListener(listener); - subscriber.close(); - subscriberSession.close(); - connection.close(); - Thread.sleep(1000); - Destination dest = backEnd.getRegionBroker().getDestinationMap().get(topic); - assertNotNull(dest); - assertTrue(dest.getConsumers().isEmpty()); - } - - public void testWithoutSessionAndSubsciberClose() throws Exception { - - TopicConnection connection = connectionFactory.createTopicConnection(); - connection.start(); - - for (int i = 0; i < 100; i++) { - TopicSession subscriberSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber subscriber = subscriberSession.createSubscriber(topic); - assertNotNull(subscriber); - } - - connection.close(); - Thread.sleep(1000); - Destination dest = backEnd.getRegionBroker().getDestinationMap().get(topic); - assertNotNull(dest); - assertTrue(dest.getConsumers().isEmpty()); - } - - /** - * Running this test you can produce a leak of only 2 ConsumerInfo on BE - * broker, NOT 200 as in other cases! - * - */ - public void testWithoutSessionAndSubsciberClosePlayAround() throws Exception { - - TopicConnection connection = connectionFactory.createTopicConnection(); - connection.start(); - - for (int i = 0; i < 100; i++) { - TopicSession subscriberSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber subscriber = subscriberSession.createSubscriber(topic); - DummyMessageListener listener = new DummyMessageListener(); - subscriber.setMessageListener(listener); - if (i != 50) { - subscriber.close(); - subscriberSession.close(); - } - } - - connection.close(); - Thread.sleep(1000); - Destination dest = backEnd.getRegionBroker().getDestinationMap().get(topic); - assertNotNull(dest); - assertTrue(dest.getConsumers().isEmpty()); - } - - class DummyMessageListener implements MessageListener { - - @Override - public void onMessage(Message arg0) { - // TODO Auto-generated method stub - - } - } - - @Override - protected void setUp() throws Exception { - this.backEnd = new BrokerService(); - this.backEnd.setBrokerName("backEnd"); - this.backEnd.setPersistent(false); - NetworkConnector backEndNetwork = this.backEnd.addNetworkConnector("static://" + frontEndAddress); - backEndNetwork.setName("backEndNetwork"); - backEndNetwork.setDynamicOnly(true); - this.backEnd.addConnector(backEndAddress); - this.backEnd.start(); - - this.frontEnd = new BrokerService(); - this.frontEnd.setBrokerName("frontEnd"); - this.frontEnd.setPersistent(false); - NetworkConnector frontEndNetwork = this.frontEnd.addNetworkConnector("static://" + backEndAddress); - frontEndNetwork.setName("frontEndNetwork"); - this.frontEnd.addConnector(frontEndAddress); - this.frontEnd.start(); - Thread.sleep(2000); - } - - @Override - protected void tearDown() throws Exception { - if (this.backEnd != null) { - this.backEnd.stop(); - } - if (this.frontEnd != null) { - this.frontEnd.stop(); - } - } + @Override + protected void tearDown() throws Exception { + if (this.backEnd != null) { + this.backEnd.stop(); + } + if (this.frontEnd != null) { + this.frontEnd.stop(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRestartPlainTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRestartPlainTest.java index 79f15f863e..02cbbcd023 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRestartPlainTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRestartPlainTest.java @@ -17,8 +17,9 @@ package org.apache.activemq.network; public class NetworkRestartPlainTest extends NetworkRestartTest { - @Override - protected String getLocalBrokerURI() { - return "org/apache/activemq/network/localBroker-plain.xml"; - } + + @Override + protected String getLocalBrokerURI() { + return "org/apache/activemq/network/localBroker-plain.xml"; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRestartTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRestartTest.java index 2449fc01b8..f34451f65f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRestartTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRestartTest.java @@ -30,158 +30,154 @@ import javax.jms.*; public class NetworkRestartTest extends TestSupport { - private static final Logger LOG = LoggerFactory.getLogger(NetworkRestartTest.class); + private static final Logger LOG = LoggerFactory.getLogger(NetworkRestartTest.class); - protected Connection localConnection; - protected Connection remoteConnection; - protected BrokerService localBroker; - protected BrokerService remoteBroker; - protected Session localSession; - protected Session remoteSession; + protected Connection localConnection; + protected Connection remoteConnection; + protected BrokerService localBroker; + protected BrokerService remoteBroker; + protected Session localSession; + protected Session remoteSession; - protected ActiveMQQueue included=new ActiveMQQueue("include.test.foo"); + protected ActiveMQQueue included = new ActiveMQQueue("include.test.foo"); + public void testConnectorRestart() throws Exception { + MessageConsumer remoteConsumer = remoteSession.createConsumer(included); + MessageProducer localProducer = localSession.createProducer(included); - public void testConnectorRestart() throws Exception { - MessageConsumer remoteConsumer = remoteSession.createConsumer(included); - MessageProducer localProducer = localSession.createProducer(included); + localProducer.send(localSession.createTextMessage("before")); + Message before = remoteConsumer.receive(1000); + assertNotNull(before); + assertEquals("before", ((TextMessage) before).getText()); - localProducer.send(localSession.createTextMessage("before")); - Message before = remoteConsumer.receive(1000); - assertNotNull(before); - assertEquals("before", ((TextMessage)before).getText()); + // restart connector - // restart connector + // wait for ack back to localbroker with concurrent store and dispatch, dispatch occurs first + Thread.sleep(1000); - // wait for ack back to localbroker with concurrent store and dispatch, dispatch occurs first - Thread.sleep(1000); + NetworkConnector connector = localBroker.getNetworkConnectorByName("networkConnector"); - NetworkConnector connector = localBroker.getNetworkConnectorByName("networkConnector"); + LOG.info("Stopping connector"); + connector.stop(); - LOG.info("Stopping connector"); - connector.stop(); + Thread.sleep(5000); + LOG.info("Starting connector"); + connector.start(); - Thread.sleep(5000); - LOG.info("Starting connector"); - connector.start(); + Thread.sleep(5000); - Thread.sleep(5000); + localProducer.send(localSession.createTextMessage("after")); + Message after = remoteConsumer.receive(3000); + assertNotNull(after); + assertEquals("after", ((TextMessage) after).getText()); + } - localProducer.send(localSession.createTextMessage("after")); - Message after = remoteConsumer.receive(3000); - assertNotNull(after); - assertEquals("after", ((TextMessage)after).getText()); + public void testConnectorReAdd() throws Exception { + MessageConsumer remoteConsumer = remoteSession.createConsumer(included); + MessageProducer localProducer = localSession.createProducer(included); - } + localProducer.send(localSession.createTextMessage("before")); + Message before = remoteConsumer.receive(1000); + assertNotNull(before); + assertEquals("before", ((TextMessage) before).getText()); - public void testConnectorReAdd() throws Exception { - MessageConsumer remoteConsumer = remoteSession.createConsumer(included); - MessageProducer localProducer = localSession.createProducer(included); + // restart connector - localProducer.send(localSession.createTextMessage("before")); - Message before = remoteConsumer.receive(1000); - assertNotNull(before); - assertEquals("before", ((TextMessage)before).getText()); + // wait for ack back to localbroker with concurrent store and dispatch, dispatch occurs first + Thread.sleep(1000); - // restart connector + NetworkConnector connector = localBroker.getNetworkConnectorByName("networkConnector"); - // wait for ack back to localbroker with concurrent store and dispatch, dispatch occurs first - Thread.sleep(1000); + LOG.info("Removing connector"); + connector.stop(); + localBroker.removeNetworkConnector(connector); - NetworkConnector connector = localBroker.getNetworkConnectorByName("networkConnector"); + Thread.sleep(5000); + LOG.info("Re-adding connector"); + localBroker.addNetworkConnector(connector); + connector.start(); - LOG.info("Removing connector"); - connector.stop(); - localBroker.removeNetworkConnector(connector); + Thread.sleep(5000); - Thread.sleep(5000); - LOG.info("Re-adding connector"); - localBroker.addNetworkConnector(connector); - connector.start(); + localProducer.send(localSession.createTextMessage("after")); + Message after = remoteConsumer.receive(3000); + assertNotNull(after); + assertEquals("after", ((TextMessage) after).getText()); + } - Thread.sleep(5000); + protected void setUp() throws Exception { + setAutoFail(true); + super.setUp(); + doSetUp(); + } + protected void tearDown() throws Exception { + localBroker.deleteAllMessages(); + remoteBroker.deleteAllMessages(); + doTearDown(); + super.tearDown(); + } - localProducer.send(localSession.createTextMessage("after")); - Message after = remoteConsumer.receive(3000); - assertNotNull(after); - assertEquals("after", ((TextMessage)after).getText()); - } + protected void doTearDown() throws Exception { + localConnection.close(); + remoteConnection.close(); + localBroker.stop(); + localBroker.waitUntilStopped(); + remoteBroker.stop(); + remoteBroker.waitUntilStopped(); + } + protected void doSetUp() throws Exception { - protected void setUp() throws Exception { - setAutoFail(true); - super.setUp(); - doSetUp(); - } + remoteBroker = createRemoteBroker(); + remoteBroker.start(); + remoteBroker.waitUntilStarted(); + localBroker = createLocalBroker(); + localBroker.start(); + localBroker.waitUntilStarted(); - protected void tearDown() throws Exception { - localBroker.deleteAllMessages(); - remoteBroker.deleteAllMessages(); - doTearDown(); - super.tearDown(); - } + String localURI = "tcp://localhost:61616"; + String remoteURI = "tcp://localhost:61617"; + ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory(localURI); + localConnection = fac.createConnection(); + localConnection.setClientID("local"); + localConnection.start(); - protected void doTearDown() throws Exception { - localConnection.close(); - remoteConnection.close(); - localBroker.stop(); - localBroker.waitUntilStopped(); - remoteBroker.stop(); - remoteBroker.waitUntilStopped(); - } + fac = new ActiveMQConnectionFactory(remoteURI); + fac.setWatchTopicAdvisories(false); + remoteConnection = fac.createConnection(); + remoteConnection.setClientID("remote"); + remoteConnection.start(); - protected void doSetUp() throws Exception { + localSession = localConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + remoteSession = remoteConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + } - remoteBroker = createRemoteBroker(); - remoteBroker.start(); - remoteBroker.waitUntilStarted(); - localBroker = createLocalBroker(); - localBroker.start(); - localBroker.waitUntilStarted(); + protected String getRemoteBrokerURI() { + return "org/apache/activemq/network/remoteBroker.xml"; + } - String localURI = "tcp://localhost:61616"; - String remoteURI = "tcp://localhost:61617"; - ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory(localURI); - localConnection = fac.createConnection(); - localConnection.setClientID("local"); - localConnection.start(); + protected String getLocalBrokerURI() { + return "org/apache/activemq/network/localBroker.xml"; + } - fac = new ActiveMQConnectionFactory(remoteURI); - fac.setWatchTopicAdvisories(false); - remoteConnection = fac.createConnection(); - remoteConnection.setClientID("remote"); - remoteConnection.start(); + protected BrokerService createBroker(String uri) throws Exception { + Resource resource = new ClassPathResource(uri); + BrokerFactoryBean factory = new BrokerFactoryBean(resource); + resource = new ClassPathResource(uri); + factory = new BrokerFactoryBean(resource); + factory.afterPropertiesSet(); + BrokerService result = factory.getBroker(); + return result; + } - localSession = localConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - remoteSession = remoteConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } + protected BrokerService createLocalBroker() throws Exception { + return createBroker(getLocalBrokerURI()); + } - protected String getRemoteBrokerURI() { - return "org/apache/activemq/network/remoteBroker.xml"; - } - - protected String getLocalBrokerURI() { - return "org/apache/activemq/network/localBroker.xml"; - } - - protected BrokerService createBroker(String uri) throws Exception { - Resource resource = new ClassPathResource(uri); - BrokerFactoryBean factory = new BrokerFactoryBean(resource); - resource = new ClassPathResource(uri); - factory = new BrokerFactoryBean(resource); - factory.afterPropertiesSet(); - BrokerService result = factory.getBroker(); - return result; - } - - protected BrokerService createLocalBroker() throws Exception { - return createBroker(getLocalBrokerURI()); - } - - protected BrokerService createRemoteBroker() throws Exception { - return createBroker(getRemoteBrokerURI()); - } + protected BrokerService createRemoteBroker() throws Exception { + return createBroker(getRemoteBrokerURI()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRouteTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRouteTest.java index 4cd97b0cbc..1b0390bafa 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRouteTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRouteTest.java @@ -19,6 +19,7 @@ package org.apache.activemq.network; import java.util.Arrays; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; + import org.apache.activemq.advisory.AdvisorySupport; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.command.ActiveMQMessage; @@ -46,301 +47,296 @@ import org.junit.Before; import org.junit.Test; public class NetworkRouteTest { - private IMocksControl control; - private BrokerService brokerService; - private Transport localBroker; - private Transport remoteBroker; - private TransportListener localListener; - private TransportListener remoteListener; - private MessageDispatch msgDispatch; - private ActiveMQMessage path1Msg; - private ActiveMQMessage path2Msg; - private ActiveMQMessage removePath1Msg; - private ActiveMQMessage removePath2Msg; - // this sort of mockery is very brittle but it is fast! + private IMocksControl control; + private BrokerService brokerService; + private Transport localBroker; + private Transport remoteBroker; + private TransportListener localListener; + private TransportListener remoteListener; + private MessageDispatch msgDispatch; + private ActiveMQMessage path1Msg; + private ActiveMQMessage path2Msg; + private ActiveMQMessage removePath1Msg; + private ActiveMQMessage removePath2Msg; - @Test - public void verifyNoRemoveOnOneConduitRemove() throws Exception { - EasyMock.expect(localBroker.request(EasyMock.isA(ConsumerInfo.class))).andReturn(null); - control.replay(); + // this sort of mockery is very brittle but it is fast! - remoteListener.onCommand(path2Msg); - remoteListener.onCommand(path1Msg); + @Test + public void verifyNoRemoveOnOneConduitRemove() throws Exception { + EasyMock.expect(localBroker.request(EasyMock.isA(ConsumerInfo.class))).andReturn(null); + control.replay(); - remoteListener.onCommand(removePath2Msg); - control.verify(); - } + remoteListener.onCommand(path2Msg); + remoteListener.onCommand(path1Msg); - @Test - public void addAndRemoveOppositeOrder() throws Exception { - // from (1) - localBroker.request(EasyMock.isA(ConsumerInfo.class)); - ArgHolder localConsumer = ArgHolder.holdArgsForLastObjectCall(); - // from (2a) - remoteBroker.asyncRequest(EasyMock.isA(ActiveMQMessage.class), EasyMock.isA(ResponseCallback.class)); - ArgHolder firstMessageFuture = ArgHolder.holdArgsForLastFutureRequestCall(); - localBroker.oneway(EasyMock.isA(MessageAck.class)); - // from (2b) - remoteBroker.asyncRequest(EasyMock.isA(ActiveMQMessage.class), EasyMock.isA(ResponseCallback.class)); - ArgHolder secondMessageFuture = ArgHolder.holdArgsForLastFutureRequestCall(); + remoteListener.onCommand(removePath2Msg); + control.verify(); + } - localBroker.oneway(EasyMock.isA(MessageAck.class)); - // from (3) - localBroker.oneway(EasyMock.isA(RemoveInfo.class)); - ExpectationWaiter waitForRemove = ExpectationWaiter.waiterForLastVoidCall(); - control.replay(); + @Test + public void addAndRemoveOppositeOrder() throws Exception { + // from (1) + localBroker.request(EasyMock.isA(ConsumerInfo.class)); + ArgHolder localConsumer = ArgHolder.holdArgsForLastObjectCall(); + // from (2a) + remoteBroker.asyncRequest(EasyMock.isA(ActiveMQMessage.class), EasyMock.isA(ResponseCallback.class)); + ArgHolder firstMessageFuture = ArgHolder.holdArgsForLastFutureRequestCall(); + localBroker.oneway(EasyMock.isA(MessageAck.class)); + // from (2b) + remoteBroker.asyncRequest(EasyMock.isA(ActiveMQMessage.class), EasyMock.isA(ResponseCallback.class)); + ArgHolder secondMessageFuture = ArgHolder.holdArgsForLastFutureRequestCall(); - // (1) send advisory of path 1 - remoteListener.onCommand(path1Msg); - msgDispatch.setConsumerId(((ConsumerInfo) localConsumer.arguments[0]).getConsumerId()); - // send advisory of path 2, doesn't send a ConsumerInfo to localBroker - remoteListener.onCommand(path2Msg); - // (2a) send a message - localListener.onCommand(msgDispatch); - ResponseCallback callback = (ResponseCallback) firstMessageFuture.arguments[1]; - FutureResponse response = new FutureResponse(callback); - response.set(new Response()); + localBroker.oneway(EasyMock.isA(MessageAck.class)); + // from (3) + localBroker.oneway(EasyMock.isA(RemoveInfo.class)); + ExpectationWaiter waitForRemove = ExpectationWaiter.waiterForLastVoidCall(); + control.replay(); - // send advisory of path 2 remove, doesn't send a RemoveInfo to localBroker - remoteListener.onCommand(removePath2Msg); - // (2b) send a message - localListener.onCommand(msgDispatch); - callback = (ResponseCallback) secondMessageFuture.arguments[1]; - response = new FutureResponse(callback); - response.set(new Response()); + // (1) send advisory of path 1 + remoteListener.onCommand(path1Msg); + msgDispatch.setConsumerId(((ConsumerInfo) localConsumer.arguments[0]).getConsumerId()); + // send advisory of path 2, doesn't send a ConsumerInfo to localBroker + remoteListener.onCommand(path2Msg); + // (2a) send a message + localListener.onCommand(msgDispatch); + ResponseCallback callback = (ResponseCallback) firstMessageFuture.arguments[1]; + FutureResponse response = new FutureResponse(callback); + response.set(new Response()); - // (3) send advisory of path 1 remove, sends a RemoveInfo to localBroker - remoteListener.onCommand(removePath1Msg); - waitForRemove.assertHappens(5, TimeUnit.SECONDS); - // send a message, does not send message as in 2a and 2b - localListener.onCommand(msgDispatch); + // send advisory of path 2 remove, doesn't send a RemoveInfo to localBroker + remoteListener.onCommand(removePath2Msg); + // (2b) send a message + localListener.onCommand(msgDispatch); + callback = (ResponseCallback) secondMessageFuture.arguments[1]; + response = new FutureResponse(callback); + response.set(new Response()); - control.verify(); - } + // (3) send advisory of path 1 remove, sends a RemoveInfo to localBroker + remoteListener.onCommand(removePath1Msg); + waitForRemove.assertHappens(5, TimeUnit.SECONDS); + // send a message, does not send message as in 2a and 2b + localListener.onCommand(msgDispatch); - @Test - public void addAndRemoveSameOrder() throws Exception { - // from (1) - localBroker.request(EasyMock.isA(ConsumerInfo.class)); - ArgHolder localConsumer = ArgHolder.holdArgsForLastObjectCall(); + control.verify(); + } - // from (2a) - remoteBroker.asyncRequest(EasyMock.isA(ActiveMQMessage.class), EasyMock.isA(ResponseCallback.class)); - ArgHolder firstMessageFuture = ArgHolder.holdArgsForLastFutureRequestCall(); + @Test + public void addAndRemoveSameOrder() throws Exception { + // from (1) + localBroker.request(EasyMock.isA(ConsumerInfo.class)); + ArgHolder localConsumer = ArgHolder.holdArgsForLastObjectCall(); - localBroker.oneway(EasyMock.isA(MessageAck.class)); + // from (2a) + remoteBroker.asyncRequest(EasyMock.isA(ActiveMQMessage.class), EasyMock.isA(ResponseCallback.class)); + ArgHolder firstMessageFuture = ArgHolder.holdArgsForLastFutureRequestCall(); - // from (2b) - remoteBroker.asyncRequest(EasyMock.isA(ActiveMQMessage.class), EasyMock.isA(ResponseCallback.class)); - ArgHolder secondMessageFuture = ArgHolder.holdArgsForLastFutureRequestCall(); + localBroker.oneway(EasyMock.isA(MessageAck.class)); - localBroker.oneway(EasyMock.isA(MessageAck.class)); + // from (2b) + remoteBroker.asyncRequest(EasyMock.isA(ActiveMQMessage.class), EasyMock.isA(ResponseCallback.class)); + ArgHolder secondMessageFuture = ArgHolder.holdArgsForLastFutureRequestCall(); - // from (3) - localBroker.oneway(EasyMock.isA(RemoveInfo.class)); - ExpectationWaiter waitForRemove = ExpectationWaiter.waiterForLastVoidCall(); - control.replay(); + localBroker.oneway(EasyMock.isA(MessageAck.class)); - // (1) send advisory of path 1 - remoteListener.onCommand(path1Msg); - msgDispatch.setConsumerId(((ConsumerInfo) localConsumer.arguments[0]).getConsumerId()); - // send advisory of path 2, doesn't send a ConsumerInfo to localBroker - remoteListener.onCommand(path2Msg); - // (2a) send a message - localListener.onCommand(msgDispatch); - ResponseCallback callback = (ResponseCallback) firstMessageFuture.arguments[1]; - FutureResponse response = new FutureResponse(callback); - response.set(new Response()); + // from (3) + localBroker.oneway(EasyMock.isA(RemoveInfo.class)); + ExpectationWaiter waitForRemove = ExpectationWaiter.waiterForLastVoidCall(); + control.replay(); - // send advisory of path 1 remove, shouldn't send a RemoveInfo to localBroker - remoteListener.onCommand(removePath1Msg); - // (2b) send a message, should send the message as in 2a - localListener.onCommand(msgDispatch); - callback = (ResponseCallback) secondMessageFuture.arguments[1]; - response = new FutureResponse(callback); - response.set(new Response()); + // (1) send advisory of path 1 + remoteListener.onCommand(path1Msg); + msgDispatch.setConsumerId(((ConsumerInfo) localConsumer.arguments[0]).getConsumerId()); + // send advisory of path 2, doesn't send a ConsumerInfo to localBroker + remoteListener.onCommand(path2Msg); + // (2a) send a message + localListener.onCommand(msgDispatch); + ResponseCallback callback = (ResponseCallback) firstMessageFuture.arguments[1]; + FutureResponse response = new FutureResponse(callback); + response.set(new Response()); - // (3) send advisory of path 1 remove, should send a RemoveInfo to localBroker - remoteListener.onCommand(removePath2Msg); - waitForRemove.assertHappens(5, TimeUnit.SECONDS); - // send a message, does not send message as in 2a - localListener.onCommand(msgDispatch); + // send advisory of path 1 remove, shouldn't send a RemoveInfo to localBroker + remoteListener.onCommand(removePath1Msg); + // (2b) send a message, should send the message as in 2a + localListener.onCommand(msgDispatch); + callback = (ResponseCallback) secondMessageFuture.arguments[1]; + response = new FutureResponse(callback); + response.set(new Response()); - control.verify(); - } + // (3) send advisory of path 1 remove, should send a RemoveInfo to localBroker + remoteListener.onCommand(removePath2Msg); + waitForRemove.assertHappens(5, TimeUnit.SECONDS); + // send a message, does not send message as in 2a + localListener.onCommand(msgDispatch); - @Before - public void before() throws Exception { - control = EasyMock.createControl(); - localBroker = control.createMock(Transport.class); - remoteBroker = control.createMock(Transport.class); + control.verify(); + } - NetworkBridgeConfiguration configuration = new NetworkBridgeConfiguration(); - brokerService = new BrokerService(); - BrokerInfo remoteBrokerInfo = new BrokerInfo(); + @Before + public void before() throws Exception { + control = EasyMock.createControl(); + localBroker = control.createMock(Transport.class); + remoteBroker = control.createMock(Transport.class); - configuration.setDuplex(true); - configuration.setNetworkTTL(5); - brokerService.setBrokerId("broker-1"); - brokerService.setPersistent(false); - brokerService.setUseJmx(false); - brokerService.start(); - brokerService.waitUntilStarted(); - remoteBrokerInfo.setBrokerId(new BrokerId("remote-broker-id")); - remoteBrokerInfo.setBrokerName("remote-broker-name"); + NetworkBridgeConfiguration configuration = new NetworkBridgeConfiguration(); + brokerService = new BrokerService(); + BrokerInfo remoteBrokerInfo = new BrokerInfo(); - localBroker.setTransportListener(EasyMock.isA(TransportListener.class)); - ArgHolder localListenerRef = ArgHolder.holdArgsForLastVoidCall(); + configuration.setDuplex(true); + configuration.setNetworkTTL(5); + brokerService.setBrokerId("broker-1"); + brokerService.setPersistent(false); + brokerService.setUseJmx(false); + brokerService.start(); + brokerService.waitUntilStarted(); + remoteBrokerInfo.setBrokerId(new BrokerId("remote-broker-id")); + remoteBrokerInfo.setBrokerName("remote-broker-name"); - remoteBroker.setTransportListener(EasyMock.isA(TransportListener.class)); - ArgHolder remoteListenerRef = ArgHolder.holdArgsForLastVoidCall(); - localBroker.start(); - remoteBroker.start(); + localBroker.setTransportListener(EasyMock.isA(TransportListener.class)); + ArgHolder localListenerRef = ArgHolder.holdArgsForLastVoidCall(); - remoteBroker.oneway(EasyMock.isA(Object.class)); - EasyMock.expectLastCall().times(4); - remoteBroker.oneway(EasyMock.isA(Object.class)); - ExpectationWaiter remoteInitWaiter = ExpectationWaiter.waiterForLastVoidCall(); + remoteBroker.setTransportListener(EasyMock.isA(TransportListener.class)); + ArgHolder remoteListenerRef = ArgHolder.holdArgsForLastVoidCall(); + localBroker.start(); + remoteBroker.start(); - localBroker.oneway(remoteBrokerInfo); - EasyMock.expect(localBroker.request(EasyMock.isA(Object.class))) - .andReturn(null); - localBroker.oneway(EasyMock.isA(Object.class)); - ExpectationWaiter localInitWaiter = ExpectationWaiter.waiterForLastVoidCall(); + remoteBroker.oneway(EasyMock.isA(Object.class)); + EasyMock.expectLastCall().times(4); + remoteBroker.oneway(EasyMock.isA(Object.class)); + ExpectationWaiter remoteInitWaiter = ExpectationWaiter.waiterForLastVoidCall(); - control.replay(); + localBroker.oneway(remoteBrokerInfo); + EasyMock.expect(localBroker.request(EasyMock.isA(Object.class))).andReturn(null); + localBroker.oneway(EasyMock.isA(Object.class)); + ExpectationWaiter localInitWaiter = ExpectationWaiter.waiterForLastVoidCall(); - DurableConduitBridge bridge = new DurableConduitBridge(configuration, localBroker, remoteBroker); - bridge.setBrokerService(brokerService); - bridge.start(); + control.replay(); - localListener = (TransportListener) localListenerRef.getArguments()[0]; - Assert.assertNotNull(localListener); - remoteListener = (TransportListener) remoteListenerRef.getArguments()[0]; - Assert.assertNotNull(remoteListener); + DurableConduitBridge bridge = new DurableConduitBridge(configuration, localBroker, remoteBroker); + bridge.setBrokerService(brokerService); + bridge.start(); - remoteListener.onCommand(remoteBrokerInfo); + localListener = (TransportListener) localListenerRef.getArguments()[0]; + Assert.assertNotNull(localListener); + remoteListener = (TransportListener) remoteListenerRef.getArguments()[0]; + Assert.assertNotNull(remoteListener); - remoteInitWaiter.assertHappens(5, TimeUnit.SECONDS); - localInitWaiter.assertHappens(5, TimeUnit.SECONDS); + remoteListener.onCommand(remoteBrokerInfo); - control.verify(); - control.reset(); + remoteInitWaiter.assertHappens(5, TimeUnit.SECONDS); + localInitWaiter.assertHappens(5, TimeUnit.SECONDS); - ActiveMQMessage msg = new ActiveMQMessage(); - msg.setDestination(new ActiveMQTopic("test")); - msgDispatch = new MessageDispatch(); - msgDispatch.setMessage(msg); + control.verify(); + control.reset(); - ConsumerInfo path1 = new ConsumerInfo(); - path1.setDestination(msg.getDestination()); - path1.setConsumerId(new ConsumerId(new SessionId(new ConnectionId("conn-id-1"), 1), 3)); - path1.setBrokerPath(new BrokerId[]{ - new BrokerId("remote-broker-id"), - new BrokerId("server(1)-broker-id"), - }); - path1Msg = new ActiveMQMessage(); - path1Msg.setDestination(AdvisorySupport.getConsumerAdvisoryTopic(path1.getDestination())); - path1Msg.setDataStructure(path1); + ActiveMQMessage msg = new ActiveMQMessage(); + msg.setDestination(new ActiveMQTopic("test")); + msgDispatch = new MessageDispatch(); + msgDispatch.setMessage(msg); - ConsumerInfo path2 = new ConsumerInfo(); - path2.setDestination(path1.getDestination()); - path2.setConsumerId(new ConsumerId(new SessionId(new ConnectionId("conn-id-2"), 2), 4)); - path2.setBrokerPath(new BrokerId[]{ - new BrokerId("remote-broker-id"), - new BrokerId("server(2)-broker-id"), - new BrokerId("server(1)-broker-id"), - }); - path2Msg = new ActiveMQMessage(); - path2Msg.setDestination(path1Msg.getDestination()); - path2Msg.setDataStructure(path2); + ConsumerInfo path1 = new ConsumerInfo(); + path1.setDestination(msg.getDestination()); + path1.setConsumerId(new ConsumerId(new SessionId(new ConnectionId("conn-id-1"), 1), 3)); + path1.setBrokerPath(new BrokerId[]{new BrokerId("remote-broker-id"), new BrokerId("server(1)-broker-id"),}); + path1Msg = new ActiveMQMessage(); + path1Msg.setDestination(AdvisorySupport.getConsumerAdvisoryTopic(path1.getDestination())); + path1Msg.setDataStructure(path1); - RemoveInfo removePath1 = new RemoveInfo(path1.getConsumerId()); - RemoveInfo removePath2 = new RemoveInfo(path2.getConsumerId()); + ConsumerInfo path2 = new ConsumerInfo(); + path2.setDestination(path1.getDestination()); + path2.setConsumerId(new ConsumerId(new SessionId(new ConnectionId("conn-id-2"), 2), 4)); + path2.setBrokerPath(new BrokerId[]{new BrokerId("remote-broker-id"), new BrokerId("server(2)-broker-id"), new BrokerId("server(1)-broker-id"),}); + path2Msg = new ActiveMQMessage(); + path2Msg.setDestination(path1Msg.getDestination()); + path2Msg.setDataStructure(path2); - removePath1Msg = new ActiveMQMessage(); - removePath1Msg.setDestination(path1Msg.getDestination()); - removePath1Msg.setDataStructure(removePath1); + RemoveInfo removePath1 = new RemoveInfo(path1.getConsumerId()); + RemoveInfo removePath2 = new RemoveInfo(path2.getConsumerId()); - removePath2Msg = new ActiveMQMessage(); - removePath2Msg.setDestination(path1Msg.getDestination()); - removePath2Msg.setDataStructure(removePath2); - } + removePath1Msg = new ActiveMQMessage(); + removePath1Msg.setDestination(path1Msg.getDestination()); + removePath1Msg.setDataStructure(removePath1); - @After - public void after() throws Exception { - control.reset(); - brokerService.stop(); - brokerService.waitUntilStopped(); - } + removePath2Msg = new ActiveMQMessage(); + removePath2Msg.setDestination(path1Msg.getDestination()); + removePath2Msg.setDataStructure(removePath2); + } - private static class ArgHolder { - public Object[] arguments; + @After + public void after() throws Exception { + control.reset(); + brokerService.stop(); + brokerService.waitUntilStopped(); + } - public static ArgHolder holdArgsForLastVoidCall() { - final ArgHolder holder = new ArgHolder(); - EasyMock.expectLastCall().andAnswer(new IAnswer() { - @Override - public Object answer() throws Throwable { - Object[] args = EasyMock.getCurrentArguments(); - holder.arguments = Arrays.copyOf(args, args.length); - return null; - } - }); - return holder; - } + private static class ArgHolder { - public static ArgHolder holdArgsForLastObjectCall() { - final ArgHolder holder = new ArgHolder(); - EasyMock.expect(new Object()).andAnswer(new IAnswer() { - @Override - public Object answer() throws Throwable { - Object[] args = EasyMock.getCurrentArguments(); - holder.arguments = Arrays.copyOf(args, args.length); - return null; - } - }); - return holder; - } + public Object[] arguments; - public static ArgHolder holdArgsForLastFutureRequestCall() { - final ArgHolder holder = new ArgHolder(); - EasyMock.expect(new FutureResponse(null)).andAnswer(new IAnswer() { - @Override - public FutureResponse answer() throws Throwable { - Object[] args = EasyMock.getCurrentArguments(); - holder.arguments = Arrays.copyOf(args, args.length); - return null; - } - }); + public static ArgHolder holdArgsForLastVoidCall() { + final ArgHolder holder = new ArgHolder(); + EasyMock.expectLastCall().andAnswer(new IAnswer() { + @Override + public Object answer() throws Throwable { + Object[] args = EasyMock.getCurrentArguments(); + holder.arguments = Arrays.copyOf(args, args.length); + return null; + } + }); + return holder; + } - return holder; - } + public static ArgHolder holdArgsForLastObjectCall() { + final ArgHolder holder = new ArgHolder(); + EasyMock.expect(new Object()).andAnswer(new IAnswer() { + @Override + public Object answer() throws Throwable { + Object[] args = EasyMock.getCurrentArguments(); + holder.arguments = Arrays.copyOf(args, args.length); + return null; + } + }); + return holder; + } - public Object[] getArguments() { - Assert.assertNotNull(arguments); - return arguments; - } - } + public static ArgHolder holdArgsForLastFutureRequestCall() { + final ArgHolder holder = new ArgHolder(); + EasyMock.expect(new FutureResponse(null)).andAnswer(new IAnswer() { + @Override + public FutureResponse answer() throws Throwable { + Object[] args = EasyMock.getCurrentArguments(); + holder.arguments = Arrays.copyOf(args, args.length); + return null; + } + }); - private static class ExpectationWaiter { - private CountDownLatch latch = new CountDownLatch(1); + return holder; + } - public static ExpectationWaiter waiterForLastVoidCall() { - final ExpectationWaiter waiter = new ExpectationWaiter(); - EasyMock.expectLastCall().andAnswer(new IAnswer() { - @Override - public Object answer() throws Throwable { - waiter.latch.countDown(); - return null; - } - }); - return waiter; - } + public Object[] getArguments() { + Assert.assertNotNull(arguments); + return arguments; + } + } - public void assertHappens(long timeout, TimeUnit unit) throws InterruptedException { - Assert.assertTrue(latch.await(timeout, unit)); - } - } + private static class ExpectationWaiter { + + private CountDownLatch latch = new CountDownLatch(1); + + public static ExpectationWaiter waiterForLastVoidCall() { + final ExpectationWaiter waiter = new ExpectationWaiter(); + EasyMock.expectLastCall().andAnswer(new IAnswer() { + @Override + public Object answer() throws Throwable { + waiter.latch.countDown(); + return null; + } + }); + return waiter; + } + + public void assertHappens(long timeout, TimeUnit unit) throws InterruptedException { + Assert.assertTrue(latch.await(timeout, unit)); + } + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkTestSupport.java index 6d825a5d69..bb875dc978 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkTestSupport.java @@ -36,144 +36,144 @@ import org.apache.activemq.usage.SystemUsage; public class NetworkTestSupport extends BrokerTestSupport { - protected ArrayList connections = new ArrayList(); + protected ArrayList connections = new ArrayList(); - protected TransportConnector connector; + protected TransportConnector connector; - protected PersistenceAdapter remotePersistenceAdapter; - protected BrokerService remoteBroker; - protected SystemUsage remoteMemoryManager; - protected TransportConnector remoteConnector; - protected boolean useJmx = false; + protected PersistenceAdapter remotePersistenceAdapter; + protected BrokerService remoteBroker; + protected SystemUsage remoteMemoryManager; + protected TransportConnector remoteConnector; + protected boolean useJmx = false; - @Override - protected void setUp() throws Exception { - super.setUp(); + @Override + protected void setUp() throws Exception { + super.setUp(); - remotePersistenceAdapter = createRemotePersistenceAdapter(true); - remoteBroker = createRemoteBroker(remotePersistenceAdapter); - remoteConnector = createRemoteConnector(); - remoteBroker.addConnector( remoteConnector ); - BrokerRegistry.getInstance().bind("remotehost", remoteBroker); - remoteBroker.start(); - } + remotePersistenceAdapter = createRemotePersistenceAdapter(true); + remoteBroker = createRemoteBroker(remotePersistenceAdapter); + remoteConnector = createRemoteConnector(); + remoteBroker.addConnector(remoteConnector); + BrokerRegistry.getInstance().bind("remotehost", remoteBroker); + remoteBroker.start(); + } - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = BrokerFactory.createBroker(new URI("broker:()/localhost?persistent=false&useJmx=false&")); - connector = createConnector(); - broker.addConnector(connector); - broker.setUseJmx(useJmx); - return broker; - } + @Override + protected BrokerService createBroker() throws Exception { + BrokerService broker = BrokerFactory.createBroker(new URI("broker:()/localhost?persistent=false&useJmx=false&")); + connector = createConnector(); + broker.addConnector(connector); + broker.setUseJmx(useJmx); + return broker; + } - /** - * @return - * @throws Exception - * @throws IOException - * @throws URISyntaxException - */ - protected TransportConnector createRemoteConnector() throws Exception, IOException, URISyntaxException { - return new TransportConnector(TransportFactory.bind(new URI(getRemoteURI()))); - } + /** + * @return + * @throws Exception + * @throws IOException + * @throws URISyntaxException + */ + protected TransportConnector createRemoteConnector() throws Exception, IOException, URISyntaxException { + return new TransportConnector(TransportFactory.bind(new URI(getRemoteURI()))); + } - /** - * @param value - * @return - * @throws Exception - * @throws IOException - * @throws URISyntaxException - */ - protected TransportConnector createConnector() throws Exception, IOException, URISyntaxException { - return new TransportConnector(TransportFactory.bind(new URI(getLocalURI()))); - } + /** + * @param value + * @return + * @throws Exception + * @throws IOException + * @throws URISyntaxException + */ + protected TransportConnector createConnector() throws Exception, IOException, URISyntaxException { + return new TransportConnector(TransportFactory.bind(new URI(getLocalURI()))); + } - protected String getRemoteURI() { - return "vm://remotehost"; - } + protected String getRemoteURI() { + return "vm://remotehost"; + } - protected String getLocalURI() { - return "vm://localhost"; - } + protected String getLocalURI() { + return "vm://localhost"; + } - protected PersistenceAdapter createRemotePersistenceAdapter(boolean clean) throws Exception { - if (remotePersistenceAdapter == null || clean) { - remotePersistenceAdapter = new MemoryPersistenceAdapter(); - } - return remotePersistenceAdapter; - } + protected PersistenceAdapter createRemotePersistenceAdapter(boolean clean) throws Exception { + if (remotePersistenceAdapter == null || clean) { + remotePersistenceAdapter = new MemoryPersistenceAdapter(); + } + return remotePersistenceAdapter; + } - protected BrokerService createRemoteBroker(PersistenceAdapter persistenceAdapter) throws Exception { - BrokerService answer = new BrokerService(); - answer.setBrokerName("remote"); - answer.setUseJmx(useJmx); - answer.setPersistenceAdapter(persistenceAdapter); - return answer; - } + protected BrokerService createRemoteBroker(PersistenceAdapter persistenceAdapter) throws Exception { + BrokerService answer = new BrokerService(); + answer.setBrokerName("remote"); + answer.setUseJmx(useJmx); + answer.setPersistenceAdapter(persistenceAdapter); + return answer; + } - @Override - protected StubConnection createConnection() throws Exception { - Transport transport = TransportFactory.connect(connector.getServer().getConnectURI()); - StubConnection connection = new StubConnection(transport); - connections.add(connection); - return connection; - } + @Override + protected StubConnection createConnection() throws Exception { + Transport transport = TransportFactory.connect(connector.getServer().getConnectURI()); + StubConnection connection = new StubConnection(transport); + connections.add(connection); + return connection; + } - protected StubConnection createRemoteConnection() throws Exception { - Transport transport = TransportFactory.connect(remoteConnector.getServer().getConnectURI()); - StubConnection connection = new StubConnection(transport); - connections.add(connection); - return connection; - } + protected StubConnection createRemoteConnection() throws Exception { + Transport transport = TransportFactory.connect(remoteConnector.getServer().getConnectURI()); + StubConnection connection = new StubConnection(transport); + connections.add(connection); + return connection; + } - protected Transport createTransport() throws Exception { - Transport transport = TransportFactory.connect(connector.getServer().getConnectURI()); - return transport; - } + protected Transport createTransport() throws Exception { + Transport transport = TransportFactory.connect(connector.getServer().getConnectURI()); + return transport; + } - protected Transport createRemoteTransport() throws Exception { - Transport transport = TransportFactory.connect(remoteConnector.getServer().getConnectURI()); - return transport; - } + protected Transport createRemoteTransport() throws Exception { + Transport transport = TransportFactory.connect(remoteConnector.getServer().getConnectURI()); + return transport; + } - /** - * Simulates a broker restart. The memory based persistence adapter is - * reused so that it does not "loose" it's "persistent" messages. - * - * @throws Exception - */ - protected void restartRemoteBroker() throws Exception { + /** + * Simulates a broker restart. The memory based persistence adapter is + * reused so that it does not "loose" it's "persistent" messages. + * + * @throws Exception + */ + protected void restartRemoteBroker() throws Exception { - BrokerRegistry.getInstance().unbind("remotehost"); - remoteConnector.stop(); + BrokerRegistry.getInstance().unbind("remotehost"); + remoteConnector.stop(); - remoteBroker.stop(); - remotePersistenceAdapter.stop(); - remotePersistenceAdapter = createRemotePersistenceAdapter(false); - remotePersistenceAdapter.start(); + remoteBroker.stop(); + remotePersistenceAdapter.stop(); + remotePersistenceAdapter = createRemotePersistenceAdapter(false); + remotePersistenceAdapter.start(); - remoteBroker = createRemoteBroker(remotePersistenceAdapter); - remoteBroker.addConnector(getRemoteURI()); - remoteBroker.start(); - BrokerRegistry.getInstance().bind("remotehost", remoteBroker); - } + remoteBroker = createRemoteBroker(remotePersistenceAdapter); + remoteBroker.addConnector(getRemoteURI()); + remoteBroker.start(); + BrokerRegistry.getInstance().bind("remotehost", remoteBroker); + } - @Override - protected void tearDown() throws Exception { - for (Iterator iter = connections.iterator(); iter.hasNext();) { - StubConnection connection = iter.next(); - connection.stop(); - iter.remove(); - } + @Override + protected void tearDown() throws Exception { + for (Iterator iter = connections.iterator(); iter.hasNext(); ) { + StubConnection connection = iter.next(); + connection.stop(); + iter.remove(); + } - BrokerRegistry.getInstance().unbind("remotehost"); - remoteConnector.stop(); - connector.stop(); + BrokerRegistry.getInstance().unbind("remotehost"); + remoteConnector.stop(); + connector.stop(); - remoteBroker.stop(); - remoteBroker.waitUntilStopped(); - remotePersistenceAdapter.stop(); - super.tearDown(); - } + remoteBroker.stop(); + remoteBroker.waitUntilStopped(); + remotePersistenceAdapter.stop(); + super.tearDown(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/SSHTunnelNetworkReconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/SSHTunnelNetworkReconnectTest.java index a7e759bd8b..5e74f1d7da 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/SSHTunnelNetworkReconnectTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/SSHTunnelNetworkReconnectTest.java @@ -28,67 +28,66 @@ import org.apache.activemq.broker.BrokerService; * Test network reconnects over SSH tunnels. This case can be especially tricky * since the SSH tunnels fool the TCP transport into thinking that they are * initially connected. - * */ public class SSHTunnelNetworkReconnectTest extends NetworkReconnectTest { - ArrayList processes = new ArrayList(); + ArrayList processes = new ArrayList(); - @Override - protected BrokerService createFirstBroker() throws Exception { - return BrokerFactory - .createBroker(new URI("xbean:org/apache/activemq/network/ssh-reconnect-broker1.xml")); - } + @Override + protected BrokerService createFirstBroker() throws Exception { + return BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/network/ssh-reconnect-broker1.xml")); + } - @Override - protected BrokerService createSecondBroker() throws Exception { - return BrokerFactory - .createBroker(new URI("xbean:org/apache/activemq/network/ssh-reconnect-broker2.xml")); - } + @Override + protected BrokerService createSecondBroker() throws Exception { + return BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/network/ssh-reconnect-broker2.xml")); + } - @Override - protected void setUp() throws Exception { - startProcess("ssh -Nn -L60006:localhost:61616 localhost"); - startProcess("ssh -Nn -L60007:localhost:61617 localhost"); - super.setUp(); - } + @Override + protected void setUp() throws Exception { + startProcess("ssh -Nn -L60006:localhost:61616 localhost"); + startProcess("ssh -Nn -L60007:localhost:61617 localhost"); + super.setUp(); + } - @Override - protected void tearDown() throws Exception { - super.tearDown(); - for (Process p : processes) { - p.destroy(); - } - } + @Override + protected void tearDown() throws Exception { + super.tearDown(); + for (Process p : processes) { + p.destroy(); + } + } - private void startProcess(String command) throws IOException { - final Process process = Runtime.getRuntime().exec(command); - processes.add(process); - new Thread("stdout: " + command) { - @Override - public void run() { - try { - InputStream is = process.getInputStream(); - int c; - while ((c = is.read()) >= 0) { - System.out.write(c); - } - } catch (IOException e) { - } + private void startProcess(String command) throws IOException { + final Process process = Runtime.getRuntime().exec(command); + processes.add(process); + new Thread("stdout: " + command) { + @Override + public void run() { + try { + InputStream is = process.getInputStream(); + int c; + while ((c = is.read()) >= 0) { + System.out.write(c); + } } - }.start(); - new Thread("stderr: " + command) { - @Override - public void run() { - try { - InputStream is = process.getErrorStream(); - int c; - while ((c = is.read()) >= 0) { - System.err.write(c); - } - } catch (IOException e) { - } + catch (IOException e) { } - }.start(); - } + } + }.start(); + new Thread("stderr: " + command) { + @Override + public void run() { + try { + InputStream is = process.getErrorStream(); + int c; + while ((c = is.read()) >= 0) { + System.err.write(c); + } + } + catch (IOException e) { + } + } + }.start(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/SimpleNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/SimpleNetworkTest.java index 17de21a662..a18012e445 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/SimpleNetworkTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/SimpleNetworkTest.java @@ -58,265 +58,267 @@ import org.springframework.core.io.Resource; public class SimpleNetworkTest { - protected static final int MESSAGE_COUNT = 10; - private static final Logger LOG = LoggerFactory.getLogger(SimpleNetworkTest.class); + protected static final int MESSAGE_COUNT = 10; + private static final Logger LOG = LoggerFactory.getLogger(SimpleNetworkTest.class); - protected AbstractApplicationContext context; - protected Connection localConnection; - protected Connection remoteConnection; - protected BrokerService localBroker; - protected BrokerService remoteBroker; - protected Session localSession; - protected Session remoteSession; - protected ActiveMQTopic included; - protected ActiveMQTopic excluded; - protected String consumerName = "durableSubs"; + protected AbstractApplicationContext context; + protected Connection localConnection; + protected Connection remoteConnection; + protected BrokerService localBroker; + protected BrokerService remoteBroker; + protected Session localSession; + protected Session remoteSession; + protected ActiveMQTopic included; + protected ActiveMQTopic excluded; + protected String consumerName = "durableSubs"; - // works b/c of non marshaling vm transport, the connection - // ref from the client is used during the forward - @Test(timeout = 60 * 1000) - public void testMessageCompression() throws Exception { + // works b/c of non marshaling vm transport, the connection + // ref from the client is used during the forward + @Test(timeout = 60 * 1000) + public void testMessageCompression() throws Exception { - ActiveMQConnection localAmqConnection = (ActiveMQConnection) localConnection; - localAmqConnection.setUseCompression(true); + ActiveMQConnection localAmqConnection = (ActiveMQConnection) localConnection; + localAmqConnection.setUseCompression(true); - MessageConsumer consumer1 = remoteSession.createConsumer(included); - MessageProducer producer = localSession.createProducer(included); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + MessageConsumer consumer1 = remoteSession.createConsumer(included); + MessageProducer producer = localSession.createProducer(included); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - waitForConsumerRegistration(localBroker, 1, included); + waitForConsumerRegistration(localBroker, 1, included); - for (int i = 0; i < MESSAGE_COUNT; i++) { - Message test = localSession.createTextMessage("test-" + i); - producer.send(test); - Message msg = consumer1.receive(3000); - assertNotNull(msg); - ActiveMQMessage amqMessage = (ActiveMQMessage) msg; - assertTrue(amqMessage.isCompressed()); - } - // ensure no more messages received - assertNull(consumer1.receive(1000)); - } + for (int i = 0; i < MESSAGE_COUNT; i++) { + Message test = localSession.createTextMessage("test-" + i); + producer.send(test); + Message msg = consumer1.receive(3000); + assertNotNull(msg); + ActiveMQMessage amqMessage = (ActiveMQMessage) msg; + assertTrue(amqMessage.isCompressed()); + } + // ensure no more messages received + assertNull(consumer1.receive(1000)); + } - @Test(timeout = 60 * 1000) - public void testRequestReply() throws Exception { - final MessageProducer remoteProducer = remoteSession.createProducer(null); - MessageConsumer remoteConsumer = remoteSession.createConsumer(included); - remoteConsumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message msg) { - try { - TextMessage textMsg = (TextMessage)msg; - String payload = "REPLY: " + textMsg.getText(); - Destination replyTo; - replyTo = msg.getJMSReplyTo(); - textMsg.clearBody(); - textMsg.setText(payload); - remoteProducer.send(replyTo, textMsg); - } catch (JMSException e) { - e.printStackTrace(); - } + @Test(timeout = 60 * 1000) + public void testRequestReply() throws Exception { + final MessageProducer remoteProducer = remoteSession.createProducer(null); + MessageConsumer remoteConsumer = remoteSession.createConsumer(included); + remoteConsumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message msg) { + try { + TextMessage textMsg = (TextMessage) msg; + String payload = "REPLY: " + textMsg.getText(); + Destination replyTo; + replyTo = msg.getJMSReplyTo(); + textMsg.clearBody(); + textMsg.setText(payload); + remoteProducer.send(replyTo, textMsg); } - }); - - TopicRequestor requestor = new TopicRequestor((TopicSession)localSession, included); - // allow for consumer infos to perculate around - Thread.sleep(5000); - for (int i = 0; i < MESSAGE_COUNT; i++) { - TextMessage msg = localSession.createTextMessage("test msg: " + i); - TextMessage result = (TextMessage)requestor.request(msg); - assertNotNull(result); - LOG.info(result.getText()); - } - } - - @Test(timeout = 60 * 1000) - public void testFiltering() throws Exception { - MessageConsumer includedConsumer = remoteSession.createConsumer(included); - MessageConsumer excludedConsumer = remoteSession.createConsumer(excluded); - MessageProducer includedProducer = localSession.createProducer(included); - MessageProducer excludedProducer = localSession.createProducer(excluded); - // allow for consumer infos to perculate around - Thread.sleep(2000); - Message test = localSession.createTextMessage("test"); - includedProducer.send(test); - excludedProducer.send(test); - assertNull(excludedConsumer.receive(1000)); - assertNotNull(includedConsumer.receive(1000)); - } - - @Test(timeout = 60 * 1000) - public void testConduitBridge() throws Exception { - MessageConsumer consumer1 = remoteSession.createConsumer(included); - MessageConsumer consumer2 = remoteSession.createConsumer(included); - MessageProducer producer = localSession.createProducer(included); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - - waitForConsumerRegistration(localBroker, 2, included); - - for (int i = 0; i < MESSAGE_COUNT; i++) { - Message test = localSession.createTextMessage("test-" + i); - producer.send(test); - assertNotNull(consumer1.receive(1000)); - assertNotNull(consumer2.receive(1000)); - } - // ensure no more messages received - assertNull(consumer1.receive(1000)); - assertNull(consumer2.receive(1000)); - } - - private void waitForConsumerRegistration(final BrokerService brokerService, final int min, final ActiveMQDestination destination) throws Exception { - assertTrue("Internal bridge consumers registered in time", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Object[] bridges = brokerService.getNetworkConnectors().get(0).bridges.values().toArray(); - if (bridges.length > 0) { - LOG.info(brokerService + " bridges " + Arrays.toString(bridges)); - DemandForwardingBridgeSupport demandForwardingBridgeSupport = (DemandForwardingBridgeSupport) bridges[0]; - ConcurrentHashMap forwardingBridges = demandForwardingBridgeSupport.getLocalSubscriptionMap(); - LOG.info(brokerService + " bridge " + demandForwardingBridgeSupport + ", localSubs: " + forwardingBridges); - if (!forwardingBridges.isEmpty()) { - for (DemandSubscription demandSubscription : forwardingBridges.values()) { - if (demandSubscription.getLocalInfo().getDestination().equals(destination)) { - LOG.info(brokerService + " DemandSubscription " + demandSubscription + ", size: " + demandSubscription.size()); - return demandSubscription.size() >= min; - } - } - } - } - return false; + catch (JMSException e) { + e.printStackTrace(); } - })); - } + } + }); - @Test(timeout = 60 * 1000) - public void testDurableStoreAndForward() throws Exception { - // create a remote durable consumer - MessageConsumer remoteConsumer = remoteSession.createDurableSubscriber(included, consumerName); - Thread.sleep(1000); - // now close everything down and restart - doTearDown(); - doSetUp(false); - MessageProducer producer = localSession.createProducer(included); - for (int i = 0; i < MESSAGE_COUNT; i++) { - Message test = localSession.createTextMessage("test-" + i); - producer.send(test); - } - Thread.sleep(1000); - // close everything down and restart - doTearDown(); - doSetUp(false); - remoteConsumer = remoteSession.createDurableSubscriber(included, consumerName); - for (int i = 0; i < MESSAGE_COUNT; i++) { - assertNotNull("message count: " + i, remoteConsumer.receive(2500)); - } - } + TopicRequestor requestor = new TopicRequestor((TopicSession) localSession, included); + // allow for consumer infos to perculate around + Thread.sleep(5000); + for (int i = 0; i < MESSAGE_COUNT; i++) { + TextMessage msg = localSession.createTextMessage("test msg: " + i); + TextMessage result = (TextMessage) requestor.request(msg); + assertNotNull(result); + LOG.info(result.getText()); + } + } - @Ignore("This seems like a simple use case, but it is problematic to consume an existing topic store, " + - "it requires a connection per durable to match that connectionId") - public void testDurableStoreAndForwardReconnect() throws Exception { - // create a local durable consumer - MessageConsumer localConsumer = localSession.createDurableSubscriber(included, consumerName); - Thread.sleep(5000); - // now close everything down and restart - doTearDown(); - doSetUp(false); - // send messages - MessageProducer producer = localSession.createProducer(included); - for (int i = 0; i < MESSAGE_COUNT; i++) { - Message test = localSession.createTextMessage("test-" + i); - producer.send(test); - } - Thread.sleep(5000); - // consume some messages locally - localConsumer = localSession.createDurableSubscriber(included, consumerName); - LOG.info("Consume from local consumer: " + localConsumer); - for (int i = 0; i < MESSAGE_COUNT / 2; i++) { - assertNotNull("message count: " + i, localConsumer.receive(2500)); - } - Thread.sleep(5000); - // close everything down and restart - doTearDown(); - doSetUp(false); - Thread.sleep(5000); + @Test(timeout = 60 * 1000) + public void testFiltering() throws Exception { + MessageConsumer includedConsumer = remoteSession.createConsumer(included); + MessageConsumer excludedConsumer = remoteSession.createConsumer(excluded); + MessageProducer includedProducer = localSession.createProducer(included); + MessageProducer excludedProducer = localSession.createProducer(excluded); + // allow for consumer infos to perculate around + Thread.sleep(2000); + Message test = localSession.createTextMessage("test"); + includedProducer.send(test); + excludedProducer.send(test); + assertNull(excludedConsumer.receive(1000)); + assertNotNull(includedConsumer.receive(1000)); + } - LOG.info("Consume from remote"); - // consume the rest remotely - MessageConsumer remoteConsumer = remoteSession.createDurableSubscriber(included, consumerName); - LOG.info("Remote consumer: " + remoteConsumer); - Thread.sleep(5000); - for (int i = 0; i < MESSAGE_COUNT / 2; i++) { - assertNotNull("message count: " + i, remoteConsumer.receive(10000)); - } - } + @Test(timeout = 60 * 1000) + public void testConduitBridge() throws Exception { + MessageConsumer consumer1 = remoteSession.createConsumer(included); + MessageConsumer consumer2 = remoteSession.createConsumer(included); + MessageProducer producer = localSession.createProducer(included); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - @Before - public void setUp() throws Exception { - doSetUp(true); - } + waitForConsumerRegistration(localBroker, 2, included); - @After - public void tearDown() throws Exception { - doTearDown(); - } + for (int i = 0; i < MESSAGE_COUNT; i++) { + Message test = localSession.createTextMessage("test-" + i); + producer.send(test); + assertNotNull(consumer1.receive(1000)); + assertNotNull(consumer2.receive(1000)); + } + // ensure no more messages received + assertNull(consumer1.receive(1000)); + assertNull(consumer2.receive(1000)); + } - protected void doTearDown() throws Exception { - localConnection.close(); - remoteConnection.close(); - localBroker.stop(); - remoteBroker.stop(); - } + private void waitForConsumerRegistration(final BrokerService brokerService, + final int min, + final ActiveMQDestination destination) throws Exception { + assertTrue("Internal bridge consumers registered in time", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Object[] bridges = brokerService.getNetworkConnectors().get(0).bridges.values().toArray(); + if (bridges.length > 0) { + LOG.info(brokerService + " bridges " + Arrays.toString(bridges)); + DemandForwardingBridgeSupport demandForwardingBridgeSupport = (DemandForwardingBridgeSupport) bridges[0]; + ConcurrentHashMap forwardingBridges = demandForwardingBridgeSupport.getLocalSubscriptionMap(); + LOG.info(brokerService + " bridge " + demandForwardingBridgeSupport + ", localSubs: " + forwardingBridges); + if (!forwardingBridges.isEmpty()) { + for (DemandSubscription demandSubscription : forwardingBridges.values()) { + if (demandSubscription.getLocalInfo().getDestination().equals(destination)) { + LOG.info(brokerService + " DemandSubscription " + demandSubscription + ", size: " + demandSubscription.size()); + return demandSubscription.size() >= min; + } + } + } + } + return false; + } + })); + } - protected void doSetUp(boolean deleteAllMessages) throws Exception { - remoteBroker = createRemoteBroker(); - remoteBroker.setDeleteAllMessagesOnStartup(deleteAllMessages); - remoteBroker.start(); - remoteBroker.waitUntilStarted(); - localBroker = createLocalBroker(); - localBroker.setDeleteAllMessagesOnStartup(deleteAllMessages); - localBroker.start(); - localBroker.waitUntilStarted(); - URI localURI = localBroker.getVmConnectorURI(); - ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory(localURI); - fac.setAlwaysSyncSend(true); - fac.setDispatchAsync(false); - localConnection = fac.createConnection(); - localConnection.setClientID("clientId"); - localConnection.start(); - URI remoteURI = remoteBroker.getVmConnectorURI(); - fac = new ActiveMQConnectionFactory(remoteURI); - remoteConnection = fac.createConnection(); - remoteConnection.setClientID("clientId"); - remoteConnection.start(); - included = new ActiveMQTopic("include.test.bar"); - excluded = new ActiveMQTopic("exclude.test.bar"); - localSession = localConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - remoteSession = remoteConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } + @Test(timeout = 60 * 1000) + public void testDurableStoreAndForward() throws Exception { + // create a remote durable consumer + MessageConsumer remoteConsumer = remoteSession.createDurableSubscriber(included, consumerName); + Thread.sleep(1000); + // now close everything down and restart + doTearDown(); + doSetUp(false); + MessageProducer producer = localSession.createProducer(included); + for (int i = 0; i < MESSAGE_COUNT; i++) { + Message test = localSession.createTextMessage("test-" + i); + producer.send(test); + } + Thread.sleep(1000); + // close everything down and restart + doTearDown(); + doSetUp(false); + remoteConsumer = remoteSession.createDurableSubscriber(included, consumerName); + for (int i = 0; i < MESSAGE_COUNT; i++) { + assertNotNull("message count: " + i, remoteConsumer.receive(2500)); + } + } - protected String getRemoteBrokerURI() { - return "org/apache/activemq/network/remoteBroker.xml"; - } + @Ignore("This seems like a simple use case, but it is problematic to consume an existing topic store, " + "it requires a connection per durable to match that connectionId") + public void testDurableStoreAndForwardReconnect() throws Exception { + // create a local durable consumer + MessageConsumer localConsumer = localSession.createDurableSubscriber(included, consumerName); + Thread.sleep(5000); + // now close everything down and restart + doTearDown(); + doSetUp(false); + // send messages + MessageProducer producer = localSession.createProducer(included); + for (int i = 0; i < MESSAGE_COUNT; i++) { + Message test = localSession.createTextMessage("test-" + i); + producer.send(test); + } + Thread.sleep(5000); + // consume some messages locally + localConsumer = localSession.createDurableSubscriber(included, consumerName); + LOG.info("Consume from local consumer: " + localConsumer); + for (int i = 0; i < MESSAGE_COUNT / 2; i++) { + assertNotNull("message count: " + i, localConsumer.receive(2500)); + } + Thread.sleep(5000); + // close everything down and restart + doTearDown(); + doSetUp(false); + Thread.sleep(5000); - protected String getLocalBrokerURI() { - return "org/apache/activemq/network/localBroker.xml"; - } + LOG.info("Consume from remote"); + // consume the rest remotely + MessageConsumer remoteConsumer = remoteSession.createDurableSubscriber(included, consumerName); + LOG.info("Remote consumer: " + remoteConsumer); + Thread.sleep(5000); + for (int i = 0; i < MESSAGE_COUNT / 2; i++) { + assertNotNull("message count: " + i, remoteConsumer.receive(10000)); + } + } - protected BrokerService createBroker(String uri) throws Exception { - Resource resource = new ClassPathResource(uri); - BrokerFactoryBean factory = new BrokerFactoryBean(resource); - resource = new ClassPathResource(uri); - factory = new BrokerFactoryBean(resource); - factory.afterPropertiesSet(); - BrokerService result = factory.getBroker(); - return result; - } + @Before + public void setUp() throws Exception { + doSetUp(true); + } - protected BrokerService createLocalBroker() throws Exception { - return createBroker(getLocalBrokerURI()); - } + @After + public void tearDown() throws Exception { + doTearDown(); + } - protected BrokerService createRemoteBroker() throws Exception { - return createBroker(getRemoteBrokerURI()); - } + protected void doTearDown() throws Exception { + localConnection.close(); + remoteConnection.close(); + localBroker.stop(); + remoteBroker.stop(); + } + + protected void doSetUp(boolean deleteAllMessages) throws Exception { + remoteBroker = createRemoteBroker(); + remoteBroker.setDeleteAllMessagesOnStartup(deleteAllMessages); + remoteBroker.start(); + remoteBroker.waitUntilStarted(); + localBroker = createLocalBroker(); + localBroker.setDeleteAllMessagesOnStartup(deleteAllMessages); + localBroker.start(); + localBroker.waitUntilStarted(); + URI localURI = localBroker.getVmConnectorURI(); + ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory(localURI); + fac.setAlwaysSyncSend(true); + fac.setDispatchAsync(false); + localConnection = fac.createConnection(); + localConnection.setClientID("clientId"); + localConnection.start(); + URI remoteURI = remoteBroker.getVmConnectorURI(); + fac = new ActiveMQConnectionFactory(remoteURI); + remoteConnection = fac.createConnection(); + remoteConnection.setClientID("clientId"); + remoteConnection.start(); + included = new ActiveMQTopic("include.test.bar"); + excluded = new ActiveMQTopic("exclude.test.bar"); + localSession = localConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + remoteSession = remoteConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + } + + protected String getRemoteBrokerURI() { + return "org/apache/activemq/network/remoteBroker.xml"; + } + + protected String getLocalBrokerURI() { + return "org/apache/activemq/network/localBroker.xml"; + } + + protected BrokerService createBroker(String uri) throws Exception { + Resource resource = new ClassPathResource(uri); + BrokerFactoryBean factory = new BrokerFactoryBean(resource); + resource = new ClassPathResource(uri); + factory = new BrokerFactoryBean(resource); + factory.afterPropertiesSet(); + BrokerService result = factory.getBroker(); + return result; + } + + protected BrokerService createLocalBroker() throws Exception { + return createBroker(getLocalBrokerURI()); + } + + protected BrokerService createRemoteBroker() throws Exception { + return createBroker(getRemoteBrokerURI()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueBridgeStandaloneReconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueBridgeStandaloneReconnectTest.java index c3553f35bc..2f2a489adb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueBridgeStandaloneReconnectTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueBridgeStandaloneReconnectTest.java @@ -40,331 +40,335 @@ import org.junit.Test; public class QueueBridgeStandaloneReconnectTest { - private SimpleJmsQueueConnector jmsQueueConnector; + private SimpleJmsQueueConnector jmsQueueConnector; - private BrokerService localBroker; - private BrokerService foreignBroker; + private BrokerService localBroker; + private BrokerService foreignBroker; - private ActiveMQConnectionFactory localConnectionFactory; - private ActiveMQConnectionFactory foreignConnectionFactory; + private ActiveMQConnectionFactory localConnectionFactory; + private ActiveMQConnectionFactory foreignConnectionFactory; - private Destination outbound; - private Destination inbound; + private Destination outbound; + private Destination inbound; - private final ArrayList connections = new ArrayList(); + private final ArrayList connections = new ArrayList(); - @Test(timeout = 60 * 1000) - public void testSendAndReceiveOverConnectedBridges() throws Exception { + @Test(timeout = 60 * 1000) + public void testSendAndReceiveOverConnectedBridges() throws Exception { - startLocalBroker(); - startForeignBroker(); + startLocalBroker(); + startForeignBroker(); - jmsQueueConnector.start(); + jmsQueueConnector.start(); - sendMessageToForeignBroker("to.foreign.broker"); - sendMessageToLocalBroker("to.local.broker"); + sendMessageToForeignBroker("to.foreign.broker"); + sendMessageToLocalBroker("to.local.broker"); - final MessageConsumer local = createConsumerForLocalBroker(); + final MessageConsumer local = createConsumerForLocalBroker(); - assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = local.receive(100); - if (message != null && ((TextMessage) message).getText().equals("to.local.broker")) { - return true; - } - return false; + assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Message message = local.receive(100); + if (message != null && ((TextMessage) message).getText().equals("to.local.broker")) { + return true; } - })); + return false; + } + })); - final MessageConsumer foreign = createConsumerForForeignBroker(); + final MessageConsumer foreign = createConsumerForForeignBroker(); - assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = foreign.receive(100); - if (message != null && ((TextMessage) message).getText().equals("to.foreign.broker")) { - return true; - } - return false; + assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Message message = foreign.receive(100); + if (message != null && ((TextMessage) message).getText().equals("to.foreign.broker")) { + return true; } - })); - } + return false; + } + })); + } - @Test(timeout = 60 * 1000) - public void testSendAndReceiveOverBridgeWhenStartedBeforeBrokers() throws Exception { + @Test(timeout = 60 * 1000) + public void testSendAndReceiveOverBridgeWhenStartedBeforeBrokers() throws Exception { - jmsQueueConnector.start(); + jmsQueueConnector.start(); - startLocalBroker(); - startForeignBroker(); + startLocalBroker(); + startForeignBroker(); - assertTrue("Should have Connected.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return jmsQueueConnector.isConnected(); + assertTrue("Should have Connected.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return jmsQueueConnector.isConnected(); + } + })); + + sendMessageToForeignBroker("to.foreign.broker"); + sendMessageToLocalBroker("to.local.broker"); + + final MessageConsumer local = createConsumerForLocalBroker(); + + assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Message message = local.receive(100); + if (message != null && ((TextMessage) message).getText().equals("to.local.broker")) { + return true; } - })); + return false; + } + })); - sendMessageToForeignBroker("to.foreign.broker"); - sendMessageToLocalBroker("to.local.broker"); + final MessageConsumer foreign = createConsumerForForeignBroker(); - final MessageConsumer local = createConsumerForLocalBroker(); - - assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = local.receive(100); - if (message != null && ((TextMessage) message).getText().equals("to.local.broker")) { - return true; - } - return false; + assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Message message = foreign.receive(100); + if (message != null && ((TextMessage) message).getText().equals("to.foreign.broker")) { + return true; } - })); + return false; + } + })); + } - final MessageConsumer foreign = createConsumerForForeignBroker(); + @Test(timeout = 60 * 1000) + public void testSendAndReceiveOverBridgeWithRestart() throws Exception { - assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = foreign.receive(100); - if (message != null && ((TextMessage) message).getText().equals("to.foreign.broker")) { - return true; - } - return false; + startLocalBroker(); + startForeignBroker(); + + jmsQueueConnector.start(); + + assertTrue("Should have Connected.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return jmsQueueConnector.isConnected(); + } + })); + + stopLocalBroker(); + stopForeignBroker(); + + assertTrue("Should have detected connection drop.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return !jmsQueueConnector.isConnected(); + } + })); + + startLocalBroker(); + startForeignBroker(); + + assertTrue("Should have Re-Connected.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return jmsQueueConnector.isConnected(); + } + })); + + sendMessageToForeignBroker("to.foreign.broker"); + sendMessageToLocalBroker("to.local.broker"); + + final MessageConsumer local = createConsumerForLocalBroker(); + + assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Message message = local.receive(100); + if (message != null && ((TextMessage) message).getText().equals("to.local.broker")) { + return true; } - })); - } + return false; + } + })); - @Test(timeout = 60 * 1000) - public void testSendAndReceiveOverBridgeWithRestart() throws Exception { + final MessageConsumer foreign = createConsumerForForeignBroker(); - startLocalBroker(); - startForeignBroker(); - - jmsQueueConnector.start(); - - assertTrue("Should have Connected.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return jmsQueueConnector.isConnected(); + assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Message message = foreign.receive(100); + if (message != null && ((TextMessage) message).getText().equals("to.foreign.broker")) { + return true; } - })); + return false; + } + })); + } - stopLocalBroker(); - stopForeignBroker(); + @Before + public void setUp() throws Exception { - assertTrue("Should have detected connection drop.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return !jmsQueueConnector.isConnected(); - } - })); + localConnectionFactory = createLocalConnectionFactory(); + foreignConnectionFactory = createForeignConnectionFactory(); - startLocalBroker(); - startForeignBroker(); + outbound = new ActiveMQQueue("RECONNECT.TEST.OUT.QUEUE"); + inbound = new ActiveMQQueue("RECONNECT.TEST.IN.QUEUE"); - assertTrue("Should have Re-Connected.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return jmsQueueConnector.isConnected(); - } - })); + jmsQueueConnector = new SimpleJmsQueueConnector(); - sendMessageToForeignBroker("to.foreign.broker"); - sendMessageToLocalBroker("to.local.broker"); + // Wire the bridges. + jmsQueueConnector.setOutboundQueueBridges(new OutboundQueueBridge[]{new OutboundQueueBridge("RECONNECT.TEST.OUT.QUEUE")}); + jmsQueueConnector.setInboundQueueBridges(new InboundQueueBridge[]{new InboundQueueBridge("RECONNECT.TEST.IN.QUEUE")}); - final MessageConsumer local = createConsumerForLocalBroker(); + // Tell it how to reach the two brokers. + jmsQueueConnector.setOutboundQueueConnectionFactory(new ActiveMQConnectionFactory("tcp://localhost:61617")); + jmsQueueConnector.setLocalQueueConnectionFactory(new ActiveMQConnectionFactory("tcp://localhost:61616")); + } - assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = local.receive(100); - if (message != null && ((TextMessage) message).getText().equals("to.local.broker")) { - return true; - } - return false; - } - })); + @After + public void tearDown() throws Exception { + disposeConsumerConnections(); - final MessageConsumer foreign = createConsumerForForeignBroker(); + try { + jmsQueueConnector.stop(); + jmsQueueConnector = null; + } + catch (Exception e) { + } - assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = foreign.receive(100); - if (message != null && ((TextMessage) message).getText().equals("to.foreign.broker")) { - return true; - } - return false; - } - })); - } + try { + stopLocalBroker(); + } + catch (Throwable e) { + } + try { + stopForeignBroker(); + } + catch (Throwable e) { + } + } - @Before - public void setUp() throws Exception { + protected void disposeConsumerConnections() { + for (Iterator iter = connections.iterator(); iter.hasNext(); ) { + Connection connection = iter.next(); + try { + connection.close(); + } + catch (Throwable ignore) { + } + } + } - localConnectionFactory = createLocalConnectionFactory(); - foreignConnectionFactory = createForeignConnectionFactory(); + protected void startLocalBroker() throws Exception { + if (localBroker == null) { + localBroker = createFirstBroker(); + localBroker.start(); + localBroker.waitUntilStarted(); + } + } - outbound = new ActiveMQQueue("RECONNECT.TEST.OUT.QUEUE"); - inbound = new ActiveMQQueue("RECONNECT.TEST.IN.QUEUE"); + protected void stopLocalBroker() throws Exception { + if (localBroker != null) { + localBroker.stop(); + localBroker.waitUntilStopped(); + localBroker = null; + } + } - jmsQueueConnector = new SimpleJmsQueueConnector(); + protected void startForeignBroker() throws Exception { + if (foreignBroker == null) { + foreignBroker = createSecondBroker(); + foreignBroker.start(); + foreignBroker.waitUntilStarted(); + } + } - // Wire the bridges. - jmsQueueConnector.setOutboundQueueBridges( - new OutboundQueueBridge[] {new OutboundQueueBridge("RECONNECT.TEST.OUT.QUEUE")}); - jmsQueueConnector.setInboundQueueBridges( - new InboundQueueBridge[] {new InboundQueueBridge("RECONNECT.TEST.IN.QUEUE")}); + protected void stopForeignBroker() throws Exception { + if (foreignBroker != null) { + foreignBroker.stop(); + foreignBroker.waitUntilStopped(); + foreignBroker = null; + } + } - // Tell it how to reach the two brokers. - jmsQueueConnector.setOutboundQueueConnectionFactory( - new ActiveMQConnectionFactory("tcp://localhost:61617")); - jmsQueueConnector.setLocalQueueConnectionFactory( - new ActiveMQConnectionFactory("tcp://localhost:61616")); - } + protected BrokerService createFirstBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setBrokerName("broker1"); + broker.setPersistent(false); + broker.setUseJmx(false); + broker.addConnector("tcp://localhost:61616"); - @After - public void tearDown() throws Exception { - disposeConsumerConnections(); + return broker; + } - try { - jmsQueueConnector.stop(); - jmsQueueConnector = null; - } catch (Exception e) { - } + protected BrokerService createSecondBroker() throws Exception { - try { - stopLocalBroker(); - } catch (Throwable e) { - } - try { - stopForeignBroker(); - } catch (Throwable e) { - } - } + BrokerService broker = new BrokerService(); + broker.setBrokerName("broker2"); + broker.setPersistent(false); + broker.setUseJmx(false); + broker.addConnector("tcp://localhost:61617"); - protected void disposeConsumerConnections() { - for (Iterator iter = connections.iterator(); iter.hasNext();) { - Connection connection = iter.next(); - try { - connection.close(); - } catch (Throwable ignore) { - } - } - } + return broker; + } - protected void startLocalBroker() throws Exception { - if (localBroker == null) { - localBroker = createFirstBroker(); - localBroker.start(); - localBroker.waitUntilStarted(); - } - } + protected ActiveMQConnectionFactory createLocalConnectionFactory() { + return new ActiveMQConnectionFactory("tcp://localhost:61616"); + } - protected void stopLocalBroker() throws Exception { - if (localBroker != null) { - localBroker.stop(); - localBroker.waitUntilStopped(); - localBroker = null; - } - } + protected ActiveMQConnectionFactory createForeignConnectionFactory() { + return new ActiveMQConnectionFactory("tcp://localhost:61617"); + } - protected void startForeignBroker() throws Exception { - if (foreignBroker == null) { - foreignBroker = createSecondBroker(); - foreignBroker.start(); - foreignBroker.waitUntilStarted(); - } - } + protected void sendMessageToForeignBroker(String text) throws JMSException { + Connection connection = null; + try { + connection = localConnectionFactory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(outbound); + TextMessage message = session.createTextMessage(); + message.setText(text); + producer.send(message); + } + finally { + try { + connection.close(); + } + catch (Throwable ignore) { + } + } + } - protected void stopForeignBroker() throws Exception { - if (foreignBroker != null) { - foreignBroker.stop(); - foreignBroker.waitUntilStopped(); - foreignBroker = null; - } - } + protected void sendMessageToLocalBroker(String text) throws JMSException { + Connection connection = null; + try { + connection = foreignConnectionFactory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(inbound); + TextMessage message = session.createTextMessage(); + message.setText(text); + producer.send(message); + } + finally { + try { + connection.close(); + } + catch (Throwable ignore) { + } + } + } - protected BrokerService createFirstBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("broker1"); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.addConnector("tcp://localhost:61616"); + protected MessageConsumer createConsumerForLocalBroker() throws JMSException { + Connection connection = localConnectionFactory.createConnection(); + connections.add(connection); + connection.start(); - return broker; - } + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + return session.createConsumer(inbound); + } - protected BrokerService createSecondBroker() throws Exception { + protected MessageConsumer createConsumerForForeignBroker() throws JMSException { + Connection connection = foreignConnectionFactory.createConnection(); + connections.add(connection); + connection.start(); - BrokerService broker = new BrokerService(); - broker.setBrokerName("broker2"); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.addConnector("tcp://localhost:61617"); - - return broker; - } - - protected ActiveMQConnectionFactory createLocalConnectionFactory() { - return new ActiveMQConnectionFactory("tcp://localhost:61616"); - } - - protected ActiveMQConnectionFactory createForeignConnectionFactory() { - return new ActiveMQConnectionFactory("tcp://localhost:61617"); - } - - protected void sendMessageToForeignBroker(String text) throws JMSException { - Connection connection = null; - try { - connection = localConnectionFactory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(outbound); - TextMessage message = session.createTextMessage(); - message.setText(text); - producer.send(message); - } finally { - try { - connection.close(); - } catch (Throwable ignore) { - } - } - } - - protected void sendMessageToLocalBroker(String text) throws JMSException { - Connection connection = null; - try { - connection = foreignConnectionFactory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(inbound); - TextMessage message = session.createTextMessage(); - message.setText(text); - producer.send(message); - } finally { - try { - connection.close(); - } catch (Throwable ignore) { - } - } - } - - protected MessageConsumer createConsumerForLocalBroker() throws JMSException { - Connection connection = localConnectionFactory.createConnection(); - connections.add(connection); - connection.start(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - return session.createConsumer(inbound); - } - - protected MessageConsumer createConsumerForForeignBroker() throws JMSException { - Connection connection = foreignConnectionFactory.createConnection(); - connections.add(connection); - connection.start(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - return session.createConsumer(outbound); - } + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + return session.createConsumer(outbound); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueBridgeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueBridgeTest.java index 104e9da9c6..274fe0c670 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueBridgeTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueBridgeTest.java @@ -39,73 +39,74 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; public class QueueBridgeTest extends TestCase implements MessageListener { - protected static final int MESSAGE_COUNT = 10; - private static final Logger LOG = LoggerFactory.getLogger(QueueBridgeTest.class); + protected static final int MESSAGE_COUNT = 10; + private static final Logger LOG = LoggerFactory.getLogger(QueueBridgeTest.class); - protected AbstractApplicationContext context; - protected QueueConnection localConnection; - protected QueueConnection remoteConnection; - protected QueueRequestor requestor; - protected QueueSession requestServerSession; - protected MessageConsumer requestServerConsumer; - protected MessageProducer requestServerProducer; + protected AbstractApplicationContext context; + protected QueueConnection localConnection; + protected QueueConnection remoteConnection; + protected QueueRequestor requestor; + protected QueueSession requestServerSession; + protected MessageConsumer requestServerConsumer; + protected MessageProducer requestServerProducer; - protected void setUp() throws Exception { - super.setUp(); - context = createApplicationContext(); + protected void setUp() throws Exception { + super.setUp(); + context = createApplicationContext(); - createConnections(); + createConnections(); - requestServerSession = localConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); - Queue theQueue = requestServerSession.createQueue(getClass().getName()); - requestServerConsumer = requestServerSession.createConsumer(theQueue); - requestServerConsumer.setMessageListener(this); - requestServerProducer = requestServerSession.createProducer(null); + requestServerSession = localConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); + Queue theQueue = requestServerSession.createQueue(getClass().getName()); + requestServerConsumer = requestServerSession.createConsumer(theQueue); + requestServerConsumer.setMessageListener(this); + requestServerProducer = requestServerSession.createProducer(null); - QueueSession session = remoteConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); - requestor = new QueueRequestor(session, theQueue); - } + QueueSession session = remoteConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); + requestor = new QueueRequestor(session, theQueue); + } - protected void createConnections() throws JMSException { - ActiveMQConnectionFactory fac = (ActiveMQConnectionFactory)context.getBean("localFactory"); - localConnection = fac.createQueueConnection(); - localConnection.start(); + protected void createConnections() throws JMSException { + ActiveMQConnectionFactory fac = (ActiveMQConnectionFactory) context.getBean("localFactory"); + localConnection = fac.createQueueConnection(); + localConnection.start(); - fac = (ActiveMQConnectionFactory)context.getBean("remoteFactory"); - remoteConnection = fac.createQueueConnection(); - remoteConnection.start(); - } + fac = (ActiveMQConnectionFactory) context.getBean("remoteFactory"); + remoteConnection = fac.createQueueConnection(); + remoteConnection.start(); + } - protected AbstractApplicationContext createApplicationContext() { - return new ClassPathXmlApplicationContext("org/apache/activemq/network/jms/queue-config.xml"); - } + protected AbstractApplicationContext createApplicationContext() { + return new ClassPathXmlApplicationContext("org/apache/activemq/network/jms/queue-config.xml"); + } - protected void tearDown() throws Exception { - localConnection.close(); - super.tearDown(); - } + protected void tearDown() throws Exception { + localConnection.close(); + super.tearDown(); + } - public void testQueueRequestorOverBridge() throws JMSException { - for (int i = 0; i < MESSAGE_COUNT; i++) { - TextMessage msg = requestServerSession.createTextMessage("test msg: " + i); - TextMessage result = (TextMessage)requestor.request(msg); - assertNotNull(result); - LOG.info(result.getText()); - } - } + public void testQueueRequestorOverBridge() throws JMSException { + for (int i = 0; i < MESSAGE_COUNT; i++) { + TextMessage msg = requestServerSession.createTextMessage("test msg: " + i); + TextMessage result = (TextMessage) requestor.request(msg); + assertNotNull(result); + LOG.info(result.getText()); + } + } - public void onMessage(Message msg) { - try { - TextMessage textMsg = (TextMessage)msg; - String payload = "REPLY: " + textMsg.getText(); - Destination replyTo; - replyTo = msg.getJMSReplyTo(); - textMsg.clearBody(); - textMsg.setText(payload); - requestServerProducer.send(replyTo, textMsg); - } catch (JMSException e) { - e.printStackTrace(); - } - } + public void onMessage(Message msg) { + try { + TextMessage textMsg = (TextMessage) msg; + String payload = "REPLY: " + textMsg.getText(); + Destination replyTo; + replyTo = msg.getJMSReplyTo(); + textMsg.clearBody(); + textMsg.setText(payload); + requestServerProducer.send(replyTo, textMsg); + } + catch (JMSException e) { + e.printStackTrace(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueBridgeXBeanTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueBridgeXBeanTest.java index c75747d115..1691af1fbe 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueBridgeXBeanTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueBridgeXBeanTest.java @@ -19,23 +19,22 @@ package org.apache.activemq.network.jms; import org.apache.xbean.spring.context.ClassPathXmlApplicationContext; import org.springframework.context.support.AbstractApplicationContext; - /** * - * + * */ public class QueueBridgeXBeanTest extends QueueBridgeTest { - protected AbstractApplicationContext createApplicationContext() { - return new ClassPathXmlApplicationContext("org/apache/activemq/network/jms/queue-xbean.xml"); - } + protected AbstractApplicationContext createApplicationContext() { + return new ClassPathXmlApplicationContext("org/apache/activemq/network/jms/queue-xbean.xml"); + } /* protected void createConnections() throws JMSException { ActiveMQConnectionFactory fac = (ActiveMQConnectionFactory) context.getBean("localFactory"); localConnection = fac.createQueueConnection(); localConnection.start(); - + fac = (ActiveMQConnectionFactory) context.getBean("remoteFactory"); remoteConnection = fac.createQueueConnection(); remoteConnection.start(); diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueOutboundBridgeReconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueOutboundBridgeReconnectTest.java index ed0a6fe57f..7a4582a2c1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueOutboundBridgeReconnectTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueOutboundBridgeReconnectTest.java @@ -49,297 +49,300 @@ import org.junit.Test; */ public class QueueOutboundBridgeReconnectTest { - private BrokerService producerBroker; - private BrokerService consumerBroker; - private ActiveMQConnectionFactory producerConnectionFactory; - private ActiveMQConnectionFactory consumerConnectionFactory; - private Destination destination; - private final ArrayList connections = new ArrayList(); + private BrokerService producerBroker; + private BrokerService consumerBroker; + private ActiveMQConnectionFactory producerConnectionFactory; + private ActiveMQConnectionFactory consumerConnectionFactory; + private Destination destination; + private final ArrayList connections = new ArrayList(); - @Test - public void testMultipleProducerBrokerRestarts() throws Exception { - for (int i = 0; i < 10; i++) { - testWithProducerBrokerRestart(); - disposeConsumerConnections(); - } - } + @Test + public void testMultipleProducerBrokerRestarts() throws Exception { + for (int i = 0; i < 10; i++) { + testWithProducerBrokerRestart(); + disposeConsumerConnections(); + } + } - @Test - public void testRestartProducerWithNoConsumer() throws Exception { - stopConsumerBroker(); + @Test + public void testRestartProducerWithNoConsumer() throws Exception { + stopConsumerBroker(); - startProducerBroker(); - sendMessage("test123"); - sendMessage("test456"); - } + startProducerBroker(); + sendMessage("test123"); + sendMessage("test456"); + } - @Test - public void testWithoutRestartsConsumerFirst() throws Exception { - startConsumerBroker(); - startProducerBroker(); - sendMessage("test123"); - sendMessage("test456"); + @Test + public void testWithoutRestartsConsumerFirst() throws Exception { + startConsumerBroker(); + startProducerBroker(); + sendMessage("test123"); + sendMessage("test456"); - MessageConsumer consumer = createConsumer(); - Message message = consumer.receive(3000); - assertNotNull(message); - assertEquals("test123", ((TextMessage)message).getText()); + MessageConsumer consumer = createConsumer(); + Message message = consumer.receive(3000); + assertNotNull(message); + assertEquals("test123", ((TextMessage) message).getText()); - message = consumer.receive(3000); - assertNotNull(message); - assertEquals("test456", ((TextMessage)message).getText()); + message = consumer.receive(3000); + assertNotNull(message); + assertEquals("test456", ((TextMessage) message).getText()); - assertNull(consumer.receiveNoWait()); - } + assertNull(consumer.receiveNoWait()); + } - @Test - public void testWithoutRestartsProducerFirst() throws Exception { - startProducerBroker(); - sendMessage("test123"); + @Test + public void testWithoutRestartsProducerFirst() throws Exception { + startProducerBroker(); + sendMessage("test123"); - startConsumerBroker(); + startConsumerBroker(); - // unless using a failover URI, the first attempt of this send will likely fail, - // so increase the timeout below to give the bridge time to recover - sendMessage("test456"); + // unless using a failover URI, the first attempt of this send will likely fail, + // so increase the timeout below to give the bridge time to recover + sendMessage("test456"); - MessageConsumer consumer = createConsumer(); - Message message = consumer.receive(5000); - assertNotNull(message); - assertEquals("test123", ((TextMessage) message).getText()); + MessageConsumer consumer = createConsumer(); + Message message = consumer.receive(5000); + assertNotNull(message); + assertEquals("test123", ((TextMessage) message).getText()); - message = consumer.receive(5000); - assertNotNull(message); - assertEquals("test456", ((TextMessage) message).getText()); + message = consumer.receive(5000); + assertNotNull(message); + assertEquals("test456", ((TextMessage) message).getText()); - assertNull(consumer.receiveNoWait()); - } + assertNull(consumer.receiveNoWait()); + } - @Test - public void testWithProducerBrokerRestart() throws Exception { - startProducerBroker(); - startConsumerBroker(); + @Test + public void testWithProducerBrokerRestart() throws Exception { + startProducerBroker(); + startConsumerBroker(); - sendMessage("test123"); + sendMessage("test123"); - MessageConsumer consumer = createConsumer(); - Message message = consumer.receive(5000); - assertNotNull(message); - assertEquals("test123", ((TextMessage)message).getText()); - assertNull(consumer.receiveNoWait()); + MessageConsumer consumer = createConsumer(); + Message message = consumer.receive(5000); + assertNotNull(message); + assertEquals("test123", ((TextMessage) message).getText()); + assertNull(consumer.receiveNoWait()); - // Restart the first broker... - stopProducerBroker(); - startProducerBroker(); + // Restart the first broker... + stopProducerBroker(); + startProducerBroker(); - sendMessage("test123"); - message = consumer.receive(5000); - assertNotNull(message); - assertEquals("test123", ((TextMessage)message).getText()); - assertNull(consumer.receiveNoWait()); - } + sendMessage("test123"); + message = consumer.receive(5000); + assertNotNull(message); + assertEquals("test123", ((TextMessage) message).getText()); + assertNull(consumer.receiveNoWait()); + } - @Test - public void testWithConsumerBrokerRestart() throws Exception { + @Test + public void testWithConsumerBrokerRestart() throws Exception { - startProducerBroker(); - startConsumerBroker(); + startProducerBroker(); + startConsumerBroker(); - sendMessage("test123"); + sendMessage("test123"); - final MessageConsumer consumer1 = createConsumer(); - Message message = consumer1.receive(5000); - assertNotNull(message); - assertEquals("test123", ((TextMessage)message).getText()); - assertNull(consumer1.receiveNoWait()); - consumer1.close(); + final MessageConsumer consumer1 = createConsumer(); + Message message = consumer1.receive(5000); + assertNotNull(message); + assertEquals("test123", ((TextMessage) message).getText()); + assertNull(consumer1.receiveNoWait()); + consumer1.close(); - // Restart the first broker... - stopConsumerBroker(); - startConsumerBroker(); + // Restart the first broker... + stopConsumerBroker(); + startConsumerBroker(); - // unless using a failover URI, the first attempt of this send will likely fail, - // so increase the timeout below to give the bridge time to recover - sendMessage("test123"); + // unless using a failover URI, the first attempt of this send will likely fail, + // so increase the timeout below to give the bridge time to recover + sendMessage("test123"); - final MessageConsumer consumer2 = createConsumer(); - assertTrue("Expected recover and delivery failed", Wait.waitFor(new Wait.Condition() { + final MessageConsumer consumer2 = createConsumer(); + assertTrue("Expected recover and delivery failed", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = consumer2.receiveNoWait(); - if (message == null || !((TextMessage)message).getText().equals("test123")) { - return false; - } - return true; + @Override + public boolean isSatisified() throws Exception { + Message message = consumer2.receiveNoWait(); + if (message == null || !((TextMessage) message).getText().equals("test123")) { + return false; } - })); - assertNull(consumer2.receiveNoWait()); - } + return true; + } + })); + assertNull(consumer2.receiveNoWait()); + } - @Test - public void testWithConsumerBrokerStartDelay() throws Exception { + @Test + public void testWithConsumerBrokerStartDelay() throws Exception { - startConsumerBroker(); - final MessageConsumer consumer = createConsumer(); + startConsumerBroker(); + final MessageConsumer consumer = createConsumer(); - TimeUnit.SECONDS.sleep(5); + TimeUnit.SECONDS.sleep(5); - startProducerBroker(); + startProducerBroker(); - sendMessage("test123"); - assertTrue("Expected recover and delivery failed", Wait.waitFor(new Wait.Condition() { + sendMessage("test123"); + assertTrue("Expected recover and delivery failed", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = consumer.receiveNoWait(); - if (message == null || !((TextMessage)message).getText().equals("test123")) { - return false; - } - return true; + @Override + public boolean isSatisified() throws Exception { + Message message = consumer.receiveNoWait(); + if (message == null || !((TextMessage) message).getText().equals("test123")) { + return false; } - })); - assertNull(consumer.receiveNoWait()); - } + return true; + } + })); + assertNull(consumer.receiveNoWait()); + } - @Test - public void testWithProducerBrokerStartDelay() throws Exception { + @Test + public void testWithProducerBrokerStartDelay() throws Exception { - startProducerBroker(); + startProducerBroker(); - TimeUnit.SECONDS.sleep(5); + TimeUnit.SECONDS.sleep(5); - startConsumerBroker(); - MessageConsumer consumer = createConsumer(); + startConsumerBroker(); + MessageConsumer consumer = createConsumer(); - sendMessage("test123"); - Message message = consumer.receive(5000); - assertNotNull(message); - assertEquals("test123", ((TextMessage)message).getText()); - assertNull(consumer.receiveNoWait()); - } + sendMessage("test123"); + Message message = consumer.receive(5000); + assertNotNull(message); + assertEquals("test123", ((TextMessage) message).getText()); + assertNull(consumer.receiveNoWait()); + } - @Before - public void setUp() throws Exception { + @Before + public void setUp() throws Exception { - producerConnectionFactory = createProducerConnectionFactory(); - consumerConnectionFactory = createConsumerConnectionFactory(); - destination = new ActiveMQQueue("RECONNECT.TEST.QUEUE"); - } + producerConnectionFactory = createProducerConnectionFactory(); + consumerConnectionFactory = createConsumerConnectionFactory(); + destination = new ActiveMQQueue("RECONNECT.TEST.QUEUE"); + } - @After - public void tearDown() throws Exception { - disposeConsumerConnections(); - try { - stopProducerBroker(); - } catch (Throwable e) { - } - try { - stopConsumerBroker(); - } catch (Throwable e) { - } - } + @After + public void tearDown() throws Exception { + disposeConsumerConnections(); + try { + stopProducerBroker(); + } + catch (Throwable e) { + } + try { + stopConsumerBroker(); + } + catch (Throwable e) { + } + } - protected void disposeConsumerConnections() { - for (Iterator iter = connections.iterator(); iter.hasNext();) { - Connection connection = iter.next(); - try { - connection.close(); - } catch (Throwable ignore) { - } - } - } + protected void disposeConsumerConnections() { + for (Iterator iter = connections.iterator(); iter.hasNext(); ) { + Connection connection = iter.next(); + try { + connection.close(); + } + catch (Throwable ignore) { + } + } + } - protected void startProducerBroker() throws Exception { - if (producerBroker == null) { - producerBroker = createFirstBroker(); - producerBroker.start(); - } - } + protected void startProducerBroker() throws Exception { + if (producerBroker == null) { + producerBroker = createFirstBroker(); + producerBroker.start(); + } + } - protected void stopProducerBroker() throws Exception { - if (producerBroker != null) { - producerBroker.stop(); - producerBroker = null; - } - } + protected void stopProducerBroker() throws Exception { + if (producerBroker != null) { + producerBroker.stop(); + producerBroker = null; + } + } - protected void startConsumerBroker() throws Exception { - if (consumerBroker == null) { - consumerBroker = createSecondBroker(); - consumerBroker.start(); - } - } + protected void startConsumerBroker() throws Exception { + if (consumerBroker == null) { + consumerBroker = createSecondBroker(); + consumerBroker.start(); + } + } - protected void stopConsumerBroker() throws Exception { - if (consumerBroker != null) { - consumerBroker.stop(); - consumerBroker = null; - } - } + protected void stopConsumerBroker() throws Exception { + if (consumerBroker != null) { + consumerBroker.stop(); + consumerBroker = null; + } + } - protected BrokerService createFirstBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("broker1"); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.addConnector("tcp://localhost:61616"); - broker.addConnector("vm://broker1"); + protected BrokerService createFirstBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setBrokerName("broker1"); + broker.setPersistent(false); + broker.setUseJmx(false); + broker.addConnector("tcp://localhost:61616"); + broker.addConnector("vm://broker1"); - SimpleJmsQueueConnector jmsQueueConnector = new SimpleJmsQueueConnector(); - jmsQueueConnector.setOutboundQueueBridges( - new OutboundQueueBridge[] {new OutboundQueueBridge("RECONNECT.TEST.QUEUE")}); - jmsQueueConnector.setOutboundQueueConnectionFactory( - new ActiveMQConnectionFactory("tcp://localhost:61617")); + SimpleJmsQueueConnector jmsQueueConnector = new SimpleJmsQueueConnector(); + jmsQueueConnector.setOutboundQueueBridges(new OutboundQueueBridge[]{new OutboundQueueBridge("RECONNECT.TEST.QUEUE")}); + jmsQueueConnector.setOutboundQueueConnectionFactory(new ActiveMQConnectionFactory("tcp://localhost:61617")); - broker.setJmsBridgeConnectors(new JmsConnector[]{jmsQueueConnector}); + broker.setJmsBridgeConnectors(new JmsConnector[]{jmsQueueConnector}); - return broker; - } + return broker; + } - protected BrokerService createSecondBroker() throws Exception { + protected BrokerService createSecondBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("broker2"); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.addConnector("tcp://localhost:61617"); - broker.addConnector("vm://broker2"); + BrokerService broker = new BrokerService(); + broker.setBrokerName("broker2"); + broker.setPersistent(false); + broker.setUseJmx(false); + broker.addConnector("tcp://localhost:61617"); + broker.addConnector("vm://broker2"); - return broker; - } + return broker; + } - protected ActiveMQConnectionFactory createProducerConnectionFactory() { - return new ActiveMQConnectionFactory("vm://broker1"); - } + protected ActiveMQConnectionFactory createProducerConnectionFactory() { + return new ActiveMQConnectionFactory("vm://broker1"); + } - protected ActiveMQConnectionFactory createConsumerConnectionFactory() { - return new ActiveMQConnectionFactory("vm://broker2"); - } + protected ActiveMQConnectionFactory createConsumerConnectionFactory() { + return new ActiveMQConnectionFactory("vm://broker2"); + } - protected void sendMessage(String text) throws JMSException { - Connection connection = null; - try { - connection = producerConnectionFactory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - TextMessage message = session.createTextMessage(); - message.setText(text); - producer.send(message); - } finally { - try { - connection.close(); - } catch (Throwable ignore) { - } - } - } + protected void sendMessage(String text) throws JMSException { + Connection connection = null; + try { + connection = producerConnectionFactory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + TextMessage message = session.createTextMessage(); + message.setText(text); + producer.send(message); + } + finally { + try { + connection.close(); + } + catch (Throwable ignore) { + } + } + } - protected MessageConsumer createConsumer() throws JMSException { - Connection connection = consumerConnectionFactory.createConnection(); - connections.add(connection); - connection.start(); + protected MessageConsumer createConsumer() throws JMSException { + Connection connection = consumerConnectionFactory.createConnection(); + connections.add(connection); + connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - return session.createConsumer(destination); - } + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + return session.createConsumer(destination); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicBridgeSpringTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicBridgeSpringTest.java index 604c496df2..e40db2d6b1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicBridgeSpringTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicBridgeSpringTest.java @@ -28,6 +28,7 @@ import javax.jms.Topic; import javax.jms.TopicConnection; import javax.jms.TopicRequestor; import javax.jms.TopicSession; + import junit.framework.TestCase; import org.apache.activemq.ActiveMQConnectionFactory; @@ -38,69 +39,70 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; public class TopicBridgeSpringTest extends TestCase implements MessageListener { - protected static final int MESSAGE_COUNT = 10; - private static final Logger LOG = LoggerFactory.getLogger(TopicBridgeSpringTest.class); + protected static final int MESSAGE_COUNT = 10; + private static final Logger LOG = LoggerFactory.getLogger(TopicBridgeSpringTest.class); - protected AbstractApplicationContext context; - protected TopicConnection localConnection; - protected TopicConnection remoteConnection; - protected TopicRequestor requestor; - protected TopicSession requestServerSession; - protected MessageConsumer requestServerConsumer; - protected MessageProducer requestServerProducer; + protected AbstractApplicationContext context; + protected TopicConnection localConnection; + protected TopicConnection remoteConnection; + protected TopicRequestor requestor; + protected TopicSession requestServerSession; + protected MessageConsumer requestServerConsumer; + protected MessageProducer requestServerProducer; - protected void setUp() throws Exception { + protected void setUp() throws Exception { - super.setUp(); - context = createApplicationContext(); - ActiveMQConnectionFactory fac = (ActiveMQConnectionFactory)context.getBean("localFactory"); - localConnection = fac.createTopicConnection(); - localConnection.start(); - requestServerSession = localConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - Topic theTopic = requestServerSession.createTopic(getClass().getName()); - requestServerConsumer = requestServerSession.createConsumer(theTopic); - requestServerConsumer.setMessageListener(this); - requestServerProducer = requestServerSession.createProducer(null); + super.setUp(); + context = createApplicationContext(); + ActiveMQConnectionFactory fac = (ActiveMQConnectionFactory) context.getBean("localFactory"); + localConnection = fac.createTopicConnection(); + localConnection.start(); + requestServerSession = localConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); + Topic theTopic = requestServerSession.createTopic(getClass().getName()); + requestServerConsumer = requestServerSession.createConsumer(theTopic); + requestServerConsumer.setMessageListener(this); + requestServerProducer = requestServerSession.createProducer(null); - fac = (ActiveMQConnectionFactory)context.getBean("remoteFactory"); - remoteConnection = fac.createTopicConnection(); - remoteConnection.start(); - TopicSession session = remoteConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - requestor = new TopicRequestor(session, theTopic); - } + fac = (ActiveMQConnectionFactory) context.getBean("remoteFactory"); + remoteConnection = fac.createTopicConnection(); + remoteConnection.start(); + TopicSession session = remoteConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); + requestor = new TopicRequestor(session, theTopic); + } - protected AbstractApplicationContext createApplicationContext() { - return new ClassPathXmlApplicationContext("org/apache/activemq/network/jms/topic-spring.xml"); - } + protected AbstractApplicationContext createApplicationContext() { + return new ClassPathXmlApplicationContext("org/apache/activemq/network/jms/topic-spring.xml"); + } - protected void tearDown() throws Exception { - localConnection.close(); - super.tearDown(); - } + protected void tearDown() throws Exception { + localConnection.close(); + super.tearDown(); + } - public void testTopicRequestorOverBridge() throws JMSException { - for (int i = 0; i < MESSAGE_COUNT; i++) { - TextMessage msg = requestServerSession.createTextMessage("test msg: " + i); - LOG.info("Making request: " + msg); - TextMessage result = (TextMessage)requestor.request(msg); - assertNotNull(result); - LOG.info("Received result: " + result.getText()); - } - } + public void testTopicRequestorOverBridge() throws JMSException { + for (int i = 0; i < MESSAGE_COUNT; i++) { + TextMessage msg = requestServerSession.createTextMessage("test msg: " + i); + LOG.info("Making request: " + msg); + TextMessage result = (TextMessage) requestor.request(msg); + assertNotNull(result); + LOG.info("Received result: " + result.getText()); + } + } - public void onMessage(Message msg) { - try { - TextMessage textMsg = (TextMessage)msg; - String payload = "REPLY: " + textMsg.getText(); - Destination replyTo; - replyTo = msg.getJMSReplyTo(); - textMsg.clearBody(); - textMsg.setText(payload); - LOG.info("Sending response: " + textMsg); - requestServerProducer.send(replyTo, textMsg); - } catch (JMSException e) { - e.printStackTrace(); - } - } + public void onMessage(Message msg) { + try { + TextMessage textMsg = (TextMessage) msg; + String payload = "REPLY: " + textMsg.getText(); + Destination replyTo; + replyTo = msg.getJMSReplyTo(); + textMsg.clearBody(); + textMsg.setText(payload); + LOG.info("Sending response: " + textMsg); + requestServerProducer.send(replyTo, textMsg); + } + catch (JMSException e) { + e.printStackTrace(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicBridgeStandaloneReconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicBridgeStandaloneReconnectTest.java index c499ff36bc..8f62a4f43e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicBridgeStandaloneReconnectTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicBridgeStandaloneReconnectTest.java @@ -40,328 +40,332 @@ import org.junit.Test; public class TopicBridgeStandaloneReconnectTest { - private SimpleJmsTopicConnector jmsTopicConnector; + private SimpleJmsTopicConnector jmsTopicConnector; - private BrokerService localBroker; - private BrokerService foreignBroker; + private BrokerService localBroker; + private BrokerService foreignBroker; - private ActiveMQConnectionFactory localConnectionFactory; - private ActiveMQConnectionFactory foreignConnectionFactory; + private ActiveMQConnectionFactory localConnectionFactory; + private ActiveMQConnectionFactory foreignConnectionFactory; - private Destination outbound; - private Destination inbound; + private Destination outbound; + private Destination inbound; - private final ArrayList connections = new ArrayList(); + private final ArrayList connections = new ArrayList(); - @Test - public void testSendAndReceiveOverConnectedBridges() throws Exception { + @Test + public void testSendAndReceiveOverConnectedBridges() throws Exception { - startLocalBroker(); - startForeignBroker(); + startLocalBroker(); + startForeignBroker(); - jmsTopicConnector.start(); + jmsTopicConnector.start(); - final MessageConsumer local = createConsumerForLocalBroker(); - final MessageConsumer foreign = createConsumerForForeignBroker(); + final MessageConsumer local = createConsumerForLocalBroker(); + final MessageConsumer foreign = createConsumerForForeignBroker(); - sendMessageToForeignBroker("to.foreign.broker"); - sendMessageToLocalBroker("to.local.broker"); + sendMessageToForeignBroker("to.foreign.broker"); + sendMessageToLocalBroker("to.local.broker"); - assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = local.receive(100); - if (message != null && ((TextMessage) message).getText().equals("to.local.broker")) { - return true; - } - return false; + assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Message message = local.receive(100); + if (message != null && ((TextMessage) message).getText().equals("to.local.broker")) { + return true; } - })); + return false; + } + })); - assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = foreign.receive(100); - if (message != null && ((TextMessage) message).getText().equals("to.foreign.broker")) { - return true; - } - return false; + assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Message message = foreign.receive(100); + if (message != null && ((TextMessage) message).getText().equals("to.foreign.broker")) { + return true; } - })); - } + return false; + } + })); + } - @Test - public void testSendAndReceiveOverBridgeWhenStartedBeforeBrokers() throws Exception { + @Test + public void testSendAndReceiveOverBridgeWhenStartedBeforeBrokers() throws Exception { - jmsTopicConnector.start(); + jmsTopicConnector.start(); - startLocalBroker(); - startForeignBroker(); + startLocalBroker(); + startForeignBroker(); - assertTrue("Should have Connected.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return jmsTopicConnector.isConnected(); + assertTrue("Should have Connected.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return jmsTopicConnector.isConnected(); + } + })); + + final MessageConsumer local = createConsumerForLocalBroker(); + final MessageConsumer foreign = createConsumerForForeignBroker(); + + sendMessageToForeignBroker("to.foreign.broker"); + sendMessageToLocalBroker("to.local.broker"); + + assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Message message = local.receive(100); + if (message != null && ((TextMessage) message).getText().equals("to.local.broker")) { + return true; } - })); + return false; + } + })); - final MessageConsumer local = createConsumerForLocalBroker(); - final MessageConsumer foreign = createConsumerForForeignBroker(); - - sendMessageToForeignBroker("to.foreign.broker"); - sendMessageToLocalBroker("to.local.broker"); - - assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = local.receive(100); - if (message != null && ((TextMessage) message).getText().equals("to.local.broker")) { - return true; - } - return false; + assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Message message = foreign.receive(100); + if (message != null && ((TextMessage) message).getText().equals("to.foreign.broker")) { + return true; } - })); + return false; + } + })); + } - assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = foreign.receive(100); - if (message != null && ((TextMessage) message).getText().equals("to.foreign.broker")) { - return true; - } - return false; + @Test + public void testSendAndReceiveOverBridgeWithRestart() throws Exception { + + startLocalBroker(); + startForeignBroker(); + + jmsTopicConnector.start(); + + assertTrue("Should have Connected.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return jmsTopicConnector.isConnected(); + } + })); + + stopLocalBroker(); + stopForeignBroker(); + + assertTrue("Should have detected connection drop.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return !jmsTopicConnector.isConnected(); + } + })); + + startLocalBroker(); + startForeignBroker(); + + assertTrue("Should have Re-Connected.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return jmsTopicConnector.isConnected(); + } + })); + + final MessageConsumer local = createConsumerForLocalBroker(); + final MessageConsumer foreign = createConsumerForForeignBroker(); + + sendMessageToForeignBroker("to.foreign.broker"); + sendMessageToLocalBroker("to.local.broker"); + + assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Message message = local.receive(100); + if (message != null && ((TextMessage) message).getText().equals("to.local.broker")) { + return true; } - })); - } + return false; + } + })); - @Test - public void testSendAndReceiveOverBridgeWithRestart() throws Exception { - - startLocalBroker(); - startForeignBroker(); - - jmsTopicConnector.start(); - - assertTrue("Should have Connected.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return jmsTopicConnector.isConnected(); + assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Message message = foreign.receive(100); + if (message != null && ((TextMessage) message).getText().equals("to.foreign.broker")) { + return true; } - })); + return false; + } + })); + } - stopLocalBroker(); - stopForeignBroker(); + @Before + public void setUp() throws Exception { - assertTrue("Should have detected connection drop.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return !jmsTopicConnector.isConnected(); - } - })); + localConnectionFactory = createLocalConnectionFactory(); + foreignConnectionFactory = createForeignConnectionFactory(); - startLocalBroker(); - startForeignBroker(); + outbound = new ActiveMQTopic("RECONNECT.TEST.OUT.TOPIC"); + inbound = new ActiveMQTopic("RECONNECT.TEST.IN.TOPIC"); - assertTrue("Should have Re-Connected.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return jmsTopicConnector.isConnected(); - } - })); + jmsTopicConnector = new SimpleJmsTopicConnector(); - final MessageConsumer local = createConsumerForLocalBroker(); - final MessageConsumer foreign = createConsumerForForeignBroker(); + // Wire the bridges. + jmsTopicConnector.setOutboundTopicBridges(new OutboundTopicBridge[]{new OutboundTopicBridge("RECONNECT.TEST.OUT.TOPIC")}); + jmsTopicConnector.setInboundTopicBridges(new InboundTopicBridge[]{new InboundTopicBridge("RECONNECT.TEST.IN.TOPIC")}); - sendMessageToForeignBroker("to.foreign.broker"); - sendMessageToLocalBroker("to.local.broker"); + // Tell it how to reach the two brokers. + jmsTopicConnector.setOutboundTopicConnectionFactory(new ActiveMQConnectionFactory("tcp://localhost:61617")); + jmsTopicConnector.setLocalTopicConnectionFactory(new ActiveMQConnectionFactory("tcp://localhost:61616")); + } - assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = local.receive(100); - if (message != null && ((TextMessage) message).getText().equals("to.local.broker")) { - return true; - } - return false; - } - })); + @After + public void tearDown() throws Exception { + disposeConsumerConnections(); - assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = foreign.receive(100); - if (message != null && ((TextMessage) message).getText().equals("to.foreign.broker")) { - return true; - } - return false; - } - })); - } + try { + jmsTopicConnector.stop(); + jmsTopicConnector = null; + } + catch (Exception e) { + } - @Before - public void setUp() throws Exception { + try { + stopLocalBroker(); + } + catch (Throwable e) { + } + try { + stopForeignBroker(); + } + catch (Throwable e) { + } + } - localConnectionFactory = createLocalConnectionFactory(); - foreignConnectionFactory = createForeignConnectionFactory(); + protected void disposeConsumerConnections() { + for (Iterator iter = connections.iterator(); iter.hasNext(); ) { + Connection connection = iter.next(); + try { + connection.close(); + } + catch (Throwable ignore) { + } + } + } - outbound = new ActiveMQTopic("RECONNECT.TEST.OUT.TOPIC"); - inbound = new ActiveMQTopic("RECONNECT.TEST.IN.TOPIC"); + protected void startLocalBroker() throws Exception { + if (localBroker == null) { + localBroker = createFirstBroker(); + localBroker.start(); + localBroker.waitUntilStarted(); + } + } - jmsTopicConnector = new SimpleJmsTopicConnector(); + protected void stopLocalBroker() throws Exception { + if (localBroker != null) { + localBroker.stop(); + localBroker.waitUntilStopped(); + localBroker = null; + } + } - // Wire the bridges. - jmsTopicConnector.setOutboundTopicBridges( - new OutboundTopicBridge[] {new OutboundTopicBridge("RECONNECT.TEST.OUT.TOPIC")}); - jmsTopicConnector.setInboundTopicBridges( - new InboundTopicBridge[] {new InboundTopicBridge("RECONNECT.TEST.IN.TOPIC")}); + protected void startForeignBroker() throws Exception { + if (foreignBroker == null) { + foreignBroker = createSecondBroker(); + foreignBroker.start(); + foreignBroker.waitUntilStarted(); + } + } - // Tell it how to reach the two brokers. - jmsTopicConnector.setOutboundTopicConnectionFactory( - new ActiveMQConnectionFactory("tcp://localhost:61617")); - jmsTopicConnector.setLocalTopicConnectionFactory( - new ActiveMQConnectionFactory("tcp://localhost:61616")); - } + protected void stopForeignBroker() throws Exception { + if (foreignBroker != null) { + foreignBroker.stop(); + foreignBroker.waitUntilStopped(); + foreignBroker = null; + } + } - @After - public void tearDown() throws Exception { - disposeConsumerConnections(); + protected BrokerService createFirstBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setBrokerName("broker1"); + broker.setPersistent(false); + broker.setUseJmx(false); + broker.addConnector("tcp://localhost:61616"); - try { - jmsTopicConnector.stop(); - jmsTopicConnector = null; - } catch (Exception e) { - } + return broker; + } - try { - stopLocalBroker(); - } catch (Throwable e) { - } - try { - stopForeignBroker(); - } catch (Throwable e) { - } - } + protected BrokerService createSecondBroker() throws Exception { - protected void disposeConsumerConnections() { - for (Iterator iter = connections.iterator(); iter.hasNext();) { - Connection connection = iter.next(); - try { - connection.close(); - } catch (Throwable ignore) { - } - } - } + BrokerService broker = new BrokerService(); + broker.setBrokerName("broker2"); + broker.setPersistent(false); + broker.setUseJmx(false); + broker.addConnector("tcp://localhost:61617"); - protected void startLocalBroker() throws Exception { - if (localBroker == null) { - localBroker = createFirstBroker(); - localBroker.start(); - localBroker.waitUntilStarted(); - } - } + return broker; + } - protected void stopLocalBroker() throws Exception { - if (localBroker != null) { - localBroker.stop(); - localBroker.waitUntilStopped(); - localBroker = null; - } - } + protected ActiveMQConnectionFactory createLocalConnectionFactory() { + return new ActiveMQConnectionFactory("tcp://localhost:61616"); + } - protected void startForeignBroker() throws Exception { - if (foreignBroker == null) { - foreignBroker = createSecondBroker(); - foreignBroker.start(); - foreignBroker.waitUntilStarted(); - } - } + protected ActiveMQConnectionFactory createForeignConnectionFactory() { + return new ActiveMQConnectionFactory("tcp://localhost:61617"); + } - protected void stopForeignBroker() throws Exception { - if (foreignBroker != null) { - foreignBroker.stop(); - foreignBroker.waitUntilStopped(); - foreignBroker = null; - } - } + protected void sendMessageToForeignBroker(String text) throws JMSException { + Connection connection = null; + try { + connection = localConnectionFactory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(outbound); + TextMessage message = session.createTextMessage(); + message.setText(text); + producer.send(message); + } + finally { + try { + connection.close(); + } + catch (Throwable ignore) { + } + } + } - protected BrokerService createFirstBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("broker1"); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.addConnector("tcp://localhost:61616"); + protected void sendMessageToLocalBroker(String text) throws JMSException { + Connection connection = null; + try { + connection = foreignConnectionFactory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(inbound); + TextMessage message = session.createTextMessage(); + message.setText(text); + producer.send(message); + } + finally { + try { + connection.close(); + } + catch (Throwable ignore) { + } + } + } - return broker; - } + protected MessageConsumer createConsumerForLocalBroker() throws JMSException { + Connection connection = localConnectionFactory.createConnection(); + connections.add(connection); + connection.start(); - protected BrokerService createSecondBroker() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + return session.createConsumer(inbound); + } - BrokerService broker = new BrokerService(); - broker.setBrokerName("broker2"); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.addConnector("tcp://localhost:61617"); + protected MessageConsumer createConsumerForForeignBroker() throws JMSException { + Connection connection = foreignConnectionFactory.createConnection(); + connections.add(connection); + connection.start(); - return broker; - } - - protected ActiveMQConnectionFactory createLocalConnectionFactory() { - return new ActiveMQConnectionFactory("tcp://localhost:61616"); - } - - protected ActiveMQConnectionFactory createForeignConnectionFactory() { - return new ActiveMQConnectionFactory("tcp://localhost:61617"); - } - - protected void sendMessageToForeignBroker(String text) throws JMSException { - Connection connection = null; - try { - connection = localConnectionFactory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(outbound); - TextMessage message = session.createTextMessage(); - message.setText(text); - producer.send(message); - } finally { - try { - connection.close(); - } catch (Throwable ignore) { - } - } - } - - protected void sendMessageToLocalBroker(String text) throws JMSException { - Connection connection = null; - try { - connection = foreignConnectionFactory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(inbound); - TextMessage message = session.createTextMessage(); - message.setText(text); - producer.send(message); - } finally { - try { - connection.close(); - } catch (Throwable ignore) { - } - } - } - - protected MessageConsumer createConsumerForLocalBroker() throws JMSException { - Connection connection = localConnectionFactory.createConnection(); - connections.add(connection); - connection.start(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - return session.createConsumer(inbound); - } - - protected MessageConsumer createConsumerForForeignBroker() throws JMSException { - Connection connection = foreignConnectionFactory.createConnection(); - connections.add(connection); - connection.start(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - return session.createConsumer(outbound); - } + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + return session.createConsumer(outbound); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicBridgeXBeanTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicBridgeXBeanTest.java index 0b070f2d91..c4b0bd3279 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicBridgeXBeanTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicBridgeXBeanTest.java @@ -20,13 +20,13 @@ import org.apache.xbean.spring.context.ClassPathXmlApplicationContext; import org.springframework.context.support.AbstractApplicationContext; /** - * - * + * + * */ public class TopicBridgeXBeanTest extends TopicBridgeSpringTest { - protected AbstractApplicationContext createApplicationContext() { - return new ClassPathXmlApplicationContext("org/apache/activemq/network/jms/topic-config.xml"); - } + protected AbstractApplicationContext createApplicationContext() { + return new ClassPathXmlApplicationContext("org/apache/activemq/network/jms/topic-config.xml"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicOutboundBridgeReconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicOutboundBridgeReconnectTest.java index 6a64b5c187..745d1ae08f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicOutboundBridgeReconnectTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicOutboundBridgeReconnectTest.java @@ -49,284 +49,287 @@ import org.junit.Test; */ public class TopicOutboundBridgeReconnectTest { - private BrokerService producerBroker; - private BrokerService consumerBroker; - private ActiveMQConnectionFactory producerConnectionFactory; - private ActiveMQConnectionFactory consumerConnectionFactory; - private Destination destination; - private final ArrayList connections = new ArrayList(); + private BrokerService producerBroker; + private BrokerService consumerBroker; + private ActiveMQConnectionFactory producerConnectionFactory; + private ActiveMQConnectionFactory consumerConnectionFactory; + private Destination destination; + private final ArrayList connections = new ArrayList(); - @Test - public void testMultipleProducerBrokerRestarts() throws Exception { - for (int i = 0; i < 10; i++) { - testWithProducerBrokerRestart(); - disposeConsumerConnections(); - } - } + @Test + public void testMultipleProducerBrokerRestarts() throws Exception { + for (int i = 0; i < 10; i++) { + testWithProducerBrokerRestart(); + disposeConsumerConnections(); + } + } - @Test - public void testWithoutRestartsConsumerFirst() throws Exception { - startConsumerBroker(); - startProducerBroker(); + @Test + public void testWithoutRestartsConsumerFirst() throws Exception { + startConsumerBroker(); + startProducerBroker(); - MessageConsumer consumer = createConsumer(); + MessageConsumer consumer = createConsumer(); - sendMessage("test123"); - sendMessage("test456"); - Message message = consumer.receive(2000); - assertNotNull(message); - assertEquals("test123", ((TextMessage)message).getText()); + sendMessage("test123"); + sendMessage("test456"); + Message message = consumer.receive(2000); + assertNotNull(message); + assertEquals("test123", ((TextMessage) message).getText()); - message = consumer.receive(5000); - assertNotNull(message); - assertEquals("test456", ((TextMessage)message).getText()); + message = consumer.receive(5000); + assertNotNull(message); + assertEquals("test456", ((TextMessage) message).getText()); - assertNull(consumer.receiveNoWait()); - } + assertNull(consumer.receiveNoWait()); + } - @Test - public void testWithoutRestartsProducerFirst() throws Exception { - startProducerBroker(); - sendMessage("test123"); + @Test + public void testWithoutRestartsProducerFirst() throws Exception { + startProducerBroker(); + sendMessage("test123"); - startConsumerBroker(); + startConsumerBroker(); - // unless using a failover URI, the first attempt of this send will likely fail, so increase the timeout below - // to give the bridge time to recover - sendMessage("test456"); + // unless using a failover URI, the first attempt of this send will likely fail, so increase the timeout below + // to give the bridge time to recover + sendMessage("test456"); - MessageConsumer consumer = createConsumer(); - Message message = consumer.receive(5000); - assertNotNull(message); - assertEquals("test123", ((TextMessage) message).getText()); + MessageConsumer consumer = createConsumer(); + Message message = consumer.receive(5000); + assertNotNull(message); + assertEquals("test123", ((TextMessage) message).getText()); - message = consumer.receive(5000); - assertNotNull(message); - assertEquals("test456", ((TextMessage) message).getText()); + message = consumer.receive(5000); + assertNotNull(message); + assertEquals("test456", ((TextMessage) message).getText()); - assertNull(consumer.receiveNoWait()); - } + assertNull(consumer.receiveNoWait()); + } - @Test - public void testWithProducerBrokerRestart() throws Exception { - startProducerBroker(); - startConsumerBroker(); + @Test + public void testWithProducerBrokerRestart() throws Exception { + startProducerBroker(); + startConsumerBroker(); - MessageConsumer consumer = createConsumer(); + MessageConsumer consumer = createConsumer(); - sendMessage("test123"); - Message message = consumer.receive(5000); - assertNotNull(message); - assertEquals("test123", ((TextMessage)message).getText()); - assertNull(consumer.receiveNoWait()); + sendMessage("test123"); + Message message = consumer.receive(5000); + assertNotNull(message); + assertEquals("test123", ((TextMessage) message).getText()); + assertNull(consumer.receiveNoWait()); - // Restart the first broker... - stopProducerBroker(); - startProducerBroker(); + // Restart the first broker... + stopProducerBroker(); + startProducerBroker(); - sendMessage("test123"); - message = consumer.receive(5000); - assertNotNull(message); - assertEquals("test123", ((TextMessage)message).getText()); - assertNull(consumer.receiveNoWait()); - } + sendMessage("test123"); + message = consumer.receive(5000); + assertNotNull(message); + assertEquals("test123", ((TextMessage) message).getText()); + assertNull(consumer.receiveNoWait()); + } - @Test - public void testWithConsumerBrokerRestart() throws Exception { - startProducerBroker(); - startConsumerBroker(); + @Test + public void testWithConsumerBrokerRestart() throws Exception { + startProducerBroker(); + startConsumerBroker(); - final MessageConsumer consumer1 = createConsumer(); + final MessageConsumer consumer1 = createConsumer(); - sendMessage("test123"); - Message message = consumer1.receive(5000); - assertNotNull(message); - assertEquals("test123", ((TextMessage)message).getText()); - assertNull(consumer1.receiveNoWait()); - consumer1.close(); + sendMessage("test123"); + Message message = consumer1.receive(5000); + assertNotNull(message); + assertEquals("test123", ((TextMessage) message).getText()); + assertNull(consumer1.receiveNoWait()); + consumer1.close(); - // Restart the first broker... - stopConsumerBroker(); - startConsumerBroker(); + // Restart the first broker... + stopConsumerBroker(); + startConsumerBroker(); - // unless using a failover URI, the first attempt of this send will likely fail, so increase the timeout below - // to give the bridge time to recover - sendMessage("test123"); + // unless using a failover URI, the first attempt of this send will likely fail, so increase the timeout below + // to give the bridge time to recover + sendMessage("test123"); - final MessageConsumer consumer2 = createConsumer(); - assertTrue("Expected recover and delivery failed", Wait.waitFor(new Wait.Condition() { + final MessageConsumer consumer2 = createConsumer(); + assertTrue("Expected recover and delivery failed", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = consumer2.receiveNoWait(); - if (message == null || !((TextMessage)message).getText().equals("test123")) { - return false; - } - return true; + @Override + public boolean isSatisified() throws Exception { + Message message = consumer2.receiveNoWait(); + if (message == null || !((TextMessage) message).getText().equals("test123")) { + return false; } - })); - assertNull(consumer2.receiveNoWait()); - } + return true; + } + })); + assertNull(consumer2.receiveNoWait()); + } - @Test - public void testWithConsumerBrokerStartDelay() throws Exception { - startConsumerBroker(); - final MessageConsumer consumer = createConsumer(); + @Test + public void testWithConsumerBrokerStartDelay() throws Exception { + startConsumerBroker(); + final MessageConsumer consumer = createConsumer(); - TimeUnit.SECONDS.sleep(5); + TimeUnit.SECONDS.sleep(5); - startProducerBroker(); + startProducerBroker(); - sendMessage("test123"); - assertTrue("Expected recover and delivery failed", Wait.waitFor(new Wait.Condition() { + sendMessage("test123"); + assertTrue("Expected recover and delivery failed", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = consumer.receiveNoWait(); - if (message == null || !((TextMessage)message).getText().equals("test123")) { - return false; - } - return true; + @Override + public boolean isSatisified() throws Exception { + Message message = consumer.receiveNoWait(); + if (message == null || !((TextMessage) message).getText().equals("test123")) { + return false; } - })); - assertNull(consumer.receiveNoWait()); - } + return true; + } + })); + assertNull(consumer.receiveNoWait()); + } - @Test - public void testWithProducerBrokerStartDelay() throws Exception { - startProducerBroker(); + @Test + public void testWithProducerBrokerStartDelay() throws Exception { + startProducerBroker(); - TimeUnit.SECONDS.sleep(5); + TimeUnit.SECONDS.sleep(5); - startConsumerBroker(); - MessageConsumer consumer = createConsumer(); + startConsumerBroker(); + MessageConsumer consumer = createConsumer(); - sendMessage("test123"); - Message message = consumer.receive(2000); - assertNotNull(message); - assertEquals("test123", ((TextMessage)message).getText()); - assertNull(consumer.receiveNoWait()); - } + sendMessage("test123"); + Message message = consumer.receive(2000); + assertNotNull(message); + assertEquals("test123", ((TextMessage) message).getText()); + assertNull(consumer.receiveNoWait()); + } - @Before - public void setUp() throws Exception { - producerConnectionFactory = createProducerConnectionFactory(); - consumerConnectionFactory = createConsumerConnectionFactory(); - destination = new ActiveMQTopic("RECONNECT.TEST.TOPIC"); - } + @Before + public void setUp() throws Exception { + producerConnectionFactory = createProducerConnectionFactory(); + consumerConnectionFactory = createConsumerConnectionFactory(); + destination = new ActiveMQTopic("RECONNECT.TEST.TOPIC"); + } - @After - public void tearDown() throws Exception { - disposeConsumerConnections(); - try { - stopProducerBroker(); - } catch (Throwable e) { - } - try { - stopConsumerBroker(); - } catch (Throwable e) { - } - } + @After + public void tearDown() throws Exception { + disposeConsumerConnections(); + try { + stopProducerBroker(); + } + catch (Throwable e) { + } + try { + stopConsumerBroker(); + } + catch (Throwable e) { + } + } - protected void disposeConsumerConnections() { - for (Iterator iter = connections.iterator(); iter.hasNext();) { - Connection connection = iter.next(); - try { - connection.close(); - } catch (Throwable ignore) { - } - } - } + protected void disposeConsumerConnections() { + for (Iterator iter = connections.iterator(); iter.hasNext(); ) { + Connection connection = iter.next(); + try { + connection.close(); + } + catch (Throwable ignore) { + } + } + } - protected void startProducerBroker() throws Exception { - if (producerBroker == null) { - producerBroker = createFirstBroker(); - producerBroker.start(); - } - } + protected void startProducerBroker() throws Exception { + if (producerBroker == null) { + producerBroker = createFirstBroker(); + producerBroker.start(); + } + } - protected void stopProducerBroker() throws Exception { - if (producerBroker != null) { - producerBroker.stop(); - producerBroker = null; - } - } + protected void stopProducerBroker() throws Exception { + if (producerBroker != null) { + producerBroker.stop(); + producerBroker = null; + } + } - protected void startConsumerBroker() throws Exception { - if (consumerBroker == null) { - consumerBroker = createSecondBroker(); - consumerBroker.start(); - } - } + protected void startConsumerBroker() throws Exception { + if (consumerBroker == null) { + consumerBroker = createSecondBroker(); + consumerBroker.start(); + } + } - protected void stopConsumerBroker() throws Exception { - if (consumerBroker != null) { - consumerBroker.stop(); - consumerBroker = null; - } - } + protected void stopConsumerBroker() throws Exception { + if (consumerBroker != null) { + consumerBroker.stop(); + consumerBroker = null; + } + } - protected BrokerService createFirstBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("broker1"); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.addConnector("tcp://localhost:61616"); - broker.addConnector("vm://broker1"); + protected BrokerService createFirstBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setBrokerName("broker1"); + broker.setPersistent(false); + broker.setUseJmx(false); + broker.addConnector("tcp://localhost:61616"); + broker.addConnector("vm://broker1"); - SimpleJmsTopicConnector jmsTopicConnector = new SimpleJmsTopicConnector(); - jmsTopicConnector.setOutboundTopicBridges( - new OutboundTopicBridge[] {new OutboundTopicBridge("RECONNECT.TEST.TOPIC")}); - jmsTopicConnector.setOutboundTopicConnectionFactory( - new ActiveMQConnectionFactory("tcp://localhost:61617")); + SimpleJmsTopicConnector jmsTopicConnector = new SimpleJmsTopicConnector(); + jmsTopicConnector.setOutboundTopicBridges(new OutboundTopicBridge[]{new OutboundTopicBridge("RECONNECT.TEST.TOPIC")}); + jmsTopicConnector.setOutboundTopicConnectionFactory(new ActiveMQConnectionFactory("tcp://localhost:61617")); - broker.setJmsBridgeConnectors(new JmsConnector[]{jmsTopicConnector}); + broker.setJmsBridgeConnectors(new JmsConnector[]{jmsTopicConnector}); - return broker; - } + return broker; + } - protected BrokerService createSecondBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("broker2"); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.addConnector("tcp://localhost:61617"); - broker.addConnector("vm://broker2"); + protected BrokerService createSecondBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setBrokerName("broker2"); + broker.setPersistent(false); + broker.setUseJmx(false); + broker.addConnector("tcp://localhost:61617"); + broker.addConnector("vm://broker2"); - return broker; - } + return broker; + } - protected ActiveMQConnectionFactory createProducerConnectionFactory() { - return new ActiveMQConnectionFactory("vm://broker1"); - } + protected ActiveMQConnectionFactory createProducerConnectionFactory() { + return new ActiveMQConnectionFactory("vm://broker1"); + } - protected ActiveMQConnectionFactory createConsumerConnectionFactory() { - return new ActiveMQConnectionFactory("vm://broker2"); - } + protected ActiveMQConnectionFactory createConsumerConnectionFactory() { + return new ActiveMQConnectionFactory("vm://broker2"); + } - protected void sendMessage(String text) throws JMSException { - Connection connection = null; - try { - connection = producerConnectionFactory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - TextMessage message = session.createTextMessage(); - message.setText(text); - producer.send(message); - } finally { - try { - connection.close(); - } catch (Throwable ignore) { - } - } - } + protected void sendMessage(String text) throws JMSException { + Connection connection = null; + try { + connection = producerConnectionFactory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + TextMessage message = session.createTextMessage(); + message.setText(text); + producer.send(message); + } + finally { + try { + connection.close(); + } + catch (Throwable ignore) { + } + } + } - protected MessageConsumer createConsumer() throws JMSException { - Connection connection = consumerConnectionFactory.createConnection(); - connections.add(connection); - connection.start(); + protected MessageConsumer createConsumer() throws JMSException { + Connection connection = consumerConnectionFactory.createConnection(); + connections.add(connection); + connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - return session.createConsumer(destination); - } + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + return session.createConsumer(destination); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/BooleanStreamTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/BooleanStreamTest.java index ebe1d07e43..e31aece154 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/BooleanStreamTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/BooleanStreamTest.java @@ -30,120 +30,125 @@ import junit.framework.TestCase; */ public class BooleanStreamTest extends TestCase { - protected OpenWireFormat openWireformat; - protected int endOfStreamMarker = 0x12345678; - int numberOfBytes = 8 * 200; + protected OpenWireFormat openWireformat; + protected int endOfStreamMarker = 0x12345678; + int numberOfBytes = 8 * 200; - interface BooleanValueSet { - boolean getBooleanValueFor(int index, int count); - } + interface BooleanValueSet { - public void testBooleanMarshallingUsingAllTrue() throws Exception { - testBooleanStream(numberOfBytes, new BooleanValueSet() { - @Override - public boolean getBooleanValueFor(int index, int count) { - return true; - } - }); - } + boolean getBooleanValueFor(int index, int count); + } - public void testBooleanMarshallingUsingAllFalse() throws Exception { - testBooleanStream(numberOfBytes, new BooleanValueSet() { - @Override - public boolean getBooleanValueFor(int index, int count) { - return false; - } - }); - } + public void testBooleanMarshallingUsingAllTrue() throws Exception { + testBooleanStream(numberOfBytes, new BooleanValueSet() { + @Override + public boolean getBooleanValueFor(int index, int count) { + return true; + } + }); + } - public void testBooleanMarshallingUsingOddAlternateTrueFalse() throws Exception { - testBooleanStream(numberOfBytes, new BooleanValueSet() { - @Override - public boolean getBooleanValueFor(int index, int count) { - return (index & 1) == 0; - } - }); - } + public void testBooleanMarshallingUsingAllFalse() throws Exception { + testBooleanStream(numberOfBytes, new BooleanValueSet() { + @Override + public boolean getBooleanValueFor(int index, int count) { + return false; + } + }); + } - public void testBooleanMarshallingUsingEvenAlternateTrueFalse() throws Exception { - testBooleanStream(numberOfBytes, new BooleanValueSet() { - @Override - public boolean getBooleanValueFor(int index, int count) { - return (index & 1) != 0; - } - }); - } + public void testBooleanMarshallingUsingOddAlternateTrueFalse() throws Exception { + testBooleanStream(numberOfBytes, new BooleanValueSet() { + @Override + public boolean getBooleanValueFor(int index, int count) { + return (index & 1) == 0; + } + }); + } - protected void testBooleanStream(int numberOfBytes, BooleanValueSet valueSet) throws Exception { - for (int i = 0; i < numberOfBytes; i++) { - try { - assertMarshalBooleans(i, valueSet); - } catch (Throwable e) { - throw (AssertionFailedError)new AssertionFailedError("Iteration failed at: " + i).initCause(e); - } - } - } + public void testBooleanMarshallingUsingEvenAlternateTrueFalse() throws Exception { + testBooleanStream(numberOfBytes, new BooleanValueSet() { + @Override + public boolean getBooleanValueFor(int index, int count) { + return (index & 1) != 0; + } + }); + } - protected void assertMarshalBooleans(int count, BooleanValueSet valueSet) throws Exception { - BooleanStream bs = new BooleanStream(); - for (int i = 0; i < count; i++) { - bs.writeBoolean(valueSet.getBooleanValueFor(i, count)); - } - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - DataOutputStream ds = new DataOutputStream(buffer); - bs.marshal(ds); - ds.writeInt(endOfStreamMarker); + protected void testBooleanStream(int numberOfBytes, BooleanValueSet valueSet) throws Exception { + for (int i = 0; i < numberOfBytes; i++) { + try { + assertMarshalBooleans(i, valueSet); + } + catch (Throwable e) { + throw (AssertionFailedError) new AssertionFailedError("Iteration failed at: " + i).initCause(e); + } + } + } - // now lets read from the stream - ds.close(); + protected void assertMarshalBooleans(int count, BooleanValueSet valueSet) throws Exception { + BooleanStream bs = new BooleanStream(); + for (int i = 0; i < count; i++) { + bs.writeBoolean(valueSet.getBooleanValueFor(i, count)); + } + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + DataOutputStream ds = new DataOutputStream(buffer); + bs.marshal(ds); + ds.writeInt(endOfStreamMarker); - ByteArrayInputStream in = new ByteArrayInputStream(buffer.toByteArray()); - DataInputStream dis = new DataInputStream(in); - bs = new BooleanStream(); - try { - bs.unmarshal(dis); - } catch (Exception e) { + // now lets read from the stream + ds.close(); + + ByteArrayInputStream in = new ByteArrayInputStream(buffer.toByteArray()); + DataInputStream dis = new DataInputStream(in); + bs = new BooleanStream(); + try { + bs.unmarshal(dis); + } + catch (Exception e) { + e.printStackTrace(); + fail("Failed to unmarshal: " + count + " booleans: " + e); + } + + for (int i = 0; i < count; i++) { + boolean expected = valueSet.getBooleanValueFor(i, count); + // /System.out.println("Unmarshaling value: " + i + " = " + expected + // + " out of: " + count); + + try { + boolean actual = bs.readBoolean(); + assertEquals("value of object: " + i + " was: " + actual, expected, actual); + } + catch (IOException e) { e.printStackTrace(); - fail("Failed to unmarshal: " + count + " booleans: " + e); - } + fail("Failed to parse boolean: " + i + " out of: " + count + " due to: " + e); + } + } + int marker = dis.readInt(); + assertEquals("Marker int when unmarshalling: " + count + " booleans", Integer.toHexString(endOfStreamMarker), Integer.toHexString(marker)); - for (int i = 0; i < count; i++) { - boolean expected = valueSet.getBooleanValueFor(i, count); - // /System.out.println("Unmarshaling value: " + i + " = " + expected - // + " out of: " + count); + // lets try read and we should get an exception + try { + dis.readByte(); + fail("Should have reached the end of the stream"); + } + catch (IOException e) { + // worked! + } + } - try { - boolean actual = bs.readBoolean(); - assertEquals("value of object: " + i + " was: " + actual, expected, actual); - } catch (IOException e) { - e.printStackTrace(); - fail("Failed to parse boolean: " + i + " out of: " + count + " due to: " + e); - } - } - int marker = dis.readInt(); - assertEquals("Marker int when unmarshalling: " + count + " booleans", Integer.toHexString(endOfStreamMarker), Integer.toHexString(marker)); + @Override + protected void setUp() throws Exception { + super.setUp(); + openWireformat = createOpenWireFormat(); + } - // lets try read and we should get an exception - try { - dis.readByte(); - fail("Should have reached the end of the stream"); - } catch (IOException e) { - // worked! - } - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - openWireformat = createOpenWireFormat(); - } - - protected OpenWireFormat createOpenWireFormat() { - OpenWireFormat wf = new OpenWireFormat(); - wf.setCacheEnabled(true); - wf.setStackTraceEnabled(false); - wf.setVersion(1); - return wf; - } + protected OpenWireFormat createOpenWireFormat() { + OpenWireFormat wf = new OpenWireFormat(); + wf.setCacheEnabled(true); + wf.setStackTraceEnabled(false); + wf.setVersion(1); + return wf; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/BrokerInfoData.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/BrokerInfoData.java index baba584907..e289115bce 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/BrokerInfoData.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/BrokerInfoData.java @@ -21,15 +21,15 @@ import org.apache.activemq.command.BrokerInfo; public class BrokerInfoData extends DataFileGenerator { - protected Object createObject() { - BrokerInfo rc = new BrokerInfo(); - rc.setResponseRequired(false); - rc.setBrokerName("localhost"); - rc.setBrokerURL("tcp://localhost:61616"); - rc.setBrokerId(new BrokerId("ID:1289012830123")); - rc.setCommandId((short) 12); - rc.setResponseRequired(false); - return rc; - } + protected Object createObject() { + BrokerInfo rc = new BrokerInfo(); + rc.setResponseRequired(false); + rc.setBrokerName("localhost"); + rc.setBrokerURL("tcp://localhost:61616"); + rc.setBrokerId(new BrokerId("ID:1289012830123")); + rc.setCommandId((short) 12); + rc.setResponseRequired(false); + return rc; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/DataFileGenerator.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/DataFileGenerator.java index ac9311b142..31bb4ed58a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/DataFileGenerator.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/DataFileGenerator.java @@ -28,114 +28,116 @@ import java.util.ArrayList; public abstract class DataFileGenerator extends org.junit.Assert { - static final File MODULE_BASE_DIR; - static final File CONTROL_DIR; - static final File CLASS_FILE_DIR; + static final File MODULE_BASE_DIR; + static final File CONTROL_DIR; + static final File CLASS_FILE_DIR; - static { - MODULE_BASE_DIR = new File(System.getProperty("basedir", ".")); - CONTROL_DIR = new File(MODULE_BASE_DIR, "src/test/resources/openwire-control"); - CLASS_FILE_DIR = new File(MODULE_BASE_DIR, "src/test/java/org/apache/activemq/openwire"); - } + static { + MODULE_BASE_DIR = new File(System.getProperty("basedir", ".")); + CONTROL_DIR = new File(MODULE_BASE_DIR, "src/test/resources/openwire-control"); + CLASS_FILE_DIR = new File(MODULE_BASE_DIR, "src/test/java/org/apache/activemq/openwire"); + } - public static void main(String[] args) throws Exception { - generateControlFiles(); - } + public static void main(String[] args) throws Exception { + generateControlFiles(); + } - /** - * @param srcdir - * @return - * @throws ClassNotFoundException - * @throws InstantiationException - * @throws IllegalAccessException - */ - public static ArrayList getAllDataFileGenerators() throws Exception { - // System.out.println("Looking for generators in : "+classFileDir); - ArrayList l = new ArrayList(); - File[] files = CLASS_FILE_DIR.listFiles(); - for (int i = 0; files != null && i < files.length; i++) { - File file = files[i]; - if (file.getName().endsWith("Data.java")) { - String cn = file.getName(); - cn = cn.substring(0, cn.length() - ".java".length()); - Class clazz = DataFileGenerator.class.getClassLoader().loadClass("org.apache.activemq.openwire." + cn); - l.add((DataFileGenerator)clazz.newInstance()); - } - } - return l; - } + /** + * @param srcdir + * @return + * @throws ClassNotFoundException + * @throws InstantiationException + * @throws IllegalAccessException + */ + public static ArrayList getAllDataFileGenerators() throws Exception { + // System.out.println("Looking for generators in : "+classFileDir); + ArrayList l = new ArrayList(); + File[] files = CLASS_FILE_DIR.listFiles(); + for (int i = 0; files != null && i < files.length; i++) { + File file = files[i]; + if (file.getName().endsWith("Data.java")) { + String cn = file.getName(); + cn = cn.substring(0, cn.length() - ".java".length()); + Class clazz = DataFileGenerator.class.getClassLoader().loadClass("org.apache.activemq.openwire." + cn); + l.add((DataFileGenerator) clazz.newInstance()); + } + } + return l; + } - private static void generateControlFiles() throws Exception { - ArrayList generators = getAllDataFileGenerators(); - for (DataFileGenerator element : generators) { - try { - // System.out.println("Processing: "+object.getClass()); - element.generateControlFile(); - } catch (Exception e) { - // System.err.println("Error while processing: - // "+object.getClass() + ". Reason: " + e); - } - } - } - - public void generateControlFile() throws Exception { - CONTROL_DIR.mkdirs(); - File dataFile = new File(CONTROL_DIR, getClass().getName() + ".bin"); - - OpenWireFormat wf = new OpenWireFormat(); - wf.setCacheEnabled(false); - wf.setStackTraceEnabled(false); - wf.setVersion(1); - - FileOutputStream os = new FileOutputStream(dataFile); - DataOutputStream ds = new DataOutputStream(os); - wf.marshal(createObject(), ds); - ds.close(); - } - - public InputStream generateInputStream() throws Exception { - OpenWireFormat wf = new OpenWireFormat(); - wf.setCacheEnabled(false); - wf.setStackTraceEnabled(false); - wf.setVersion(1); - - ByteArrayOutputStream os = new ByteArrayOutputStream(); - DataOutputStream ds = new DataOutputStream(os); - wf.marshal(createObject(), ds); - ds.close(); - - return new ByteArrayInputStream(os.toByteArray()); - } - - public static void assertAllControlFileAreEqual() throws Exception { - ArrayList generators = getAllDataFileGenerators(); - for (DataFileGenerator element : generators) { + private static void generateControlFiles() throws Exception { + ArrayList generators = getAllDataFileGenerators(); + for (DataFileGenerator element : generators) { + try { // System.out.println("Processing: "+object.getClass()); - element.assertControlFileIsEqual(); - } - } + element.generateControlFile(); + } + catch (Exception e) { + // System.err.println("Error while processing: + // "+object.getClass() + ". Reason: " + e); + } + } + } - public void assertControlFileIsEqual() throws Exception { - File dataFile = new File(CONTROL_DIR, getClass().getName() + ".bin"); - FileInputStream is1 = new FileInputStream(dataFile); - int pos = 0; - try { - InputStream is2 = generateInputStream(); - int a = is1.read(); - int b = is2.read(); + public void generateControlFile() throws Exception { + CONTROL_DIR.mkdirs(); + File dataFile = new File(CONTROL_DIR, getClass().getName() + ".bin"); + + OpenWireFormat wf = new OpenWireFormat(); + wf.setCacheEnabled(false); + wf.setStackTraceEnabled(false); + wf.setVersion(1); + + FileOutputStream os = new FileOutputStream(dataFile); + DataOutputStream ds = new DataOutputStream(os); + wf.marshal(createObject(), ds); + ds.close(); + } + + public InputStream generateInputStream() throws Exception { + OpenWireFormat wf = new OpenWireFormat(); + wf.setCacheEnabled(false); + wf.setStackTraceEnabled(false); + wf.setVersion(1); + + ByteArrayOutputStream os = new ByteArrayOutputStream(); + DataOutputStream ds = new DataOutputStream(os); + wf.marshal(createObject(), ds); + ds.close(); + + return new ByteArrayInputStream(os.toByteArray()); + } + + public static void assertAllControlFileAreEqual() throws Exception { + ArrayList generators = getAllDataFileGenerators(); + for (DataFileGenerator element : generators) { + // System.out.println("Processing: "+object.getClass()); + element.assertControlFileIsEqual(); + } + } + + public void assertControlFileIsEqual() throws Exception { + File dataFile = new File(CONTROL_DIR, getClass().getName() + ".bin"); + FileInputStream is1 = new FileInputStream(dataFile); + int pos = 0; + try { + InputStream is2 = generateInputStream(); + int a = is1.read(); + int b = is2.read(); + pos++; + assertEquals("Data does not match control file: " + dataFile + " at byte position " + pos, a, b); + while (a >= 0 && b >= 0) { + a = is1.read(); + b = is2.read(); pos++; - assertEquals("Data does not match control file: " + dataFile + " at byte position " + pos, a, b); - while (a >= 0 && b >= 0) { - a = is1.read(); - b = is2.read(); - pos++; - assertEquals(a, b); - } - is2.close(); - } finally { - is1.close(); - } - } + assertEquals(a, b); + } + is2.close(); + } + finally { + is1.close(); + } + } - protected abstract Object createObject() throws IOException; + protected abstract Object createObject() throws IOException; } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/DataFileGeneratorTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/DataFileGeneratorTestSupport.java index b75ba25745..42516143e4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/DataFileGeneratorTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/DataFileGeneratorTestSupport.java @@ -62,269 +62,292 @@ import org.slf4j.LoggerFactory; public abstract class DataFileGeneratorTestSupport extends TestSupport { - protected static final Object[] EMPTY_ARGUMENTS = {}; - private static final Logger LOG = LoggerFactory.getLogger(DataFileGeneratorTestSupport.class); + protected static final Object[] EMPTY_ARGUMENTS = {}; + private static final Logger LOG = LoggerFactory.getLogger(DataFileGeneratorTestSupport.class); - private static final Throwable SINGLETON_EXCEPTION = new Exception("shared exception"); - private static final File MODULE_BASE_DIR; - private static final File CONTROL_DIR; + private static final Throwable SINGLETON_EXCEPTION = new Exception("shared exception"); + private static final File MODULE_BASE_DIR; + private static final File CONTROL_DIR; + static { + File basedir = null; + try { + URL resource = DataFileGeneratorTestSupport.class.getResource("DataFileGeneratorTestSupport.class"); + URI baseURI = new URI(resource.toString()).resolve("../../../../.."); + basedir = new File(baseURI).getCanonicalFile(); + } + catch (Exception e) { + throw new RuntimeException(e); + } + MODULE_BASE_DIR = basedir; + CONTROL_DIR = new File(MODULE_BASE_DIR, "src/test/resources/openwire-control"); + } - static { - File basedir = null; - try { - URL resource = DataFileGeneratorTestSupport.class.getResource("DataFileGeneratorTestSupport.class"); - URI baseURI = new URI(resource.toString()).resolve("../../../../.."); - basedir = new File(baseURI).getCanonicalFile(); - } catch (Exception e) { - throw new RuntimeException(e); - } - MODULE_BASE_DIR = basedir; - CONTROL_DIR = new File(MODULE_BASE_DIR, "src/test/resources/openwire-control"); - } + private int counter; + private OpenWireFormat openWireformat; - private int counter; - private OpenWireFormat openWireformat; + public void xtestControlFileIsValid() throws Exception { + generateControlFile(); + assertControlFileIsEqual(); + } - public void xtestControlFileIsValid() throws Exception { - generateControlFile(); - assertControlFileIsEqual(); - } + public void testGenerateAndReParsingIsTheSame() throws Exception { + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + DataOutputStream ds = new DataOutputStream(buffer); + Object expected = createObject(); + LOG.info("Created: " + expected); + openWireformat.marshal(expected, ds); + ds.close(); - public void testGenerateAndReParsingIsTheSame() throws Exception { - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - DataOutputStream ds = new DataOutputStream(buffer); - Object expected = createObject(); - LOG.info("Created: " + expected); - openWireformat.marshal(expected, ds); - ds.close(); + // now lets try parse it back again + ByteArrayInputStream in = new ByteArrayInputStream(buffer.toByteArray()); + DataInputStream dis = new DataInputStream(in); + Object actual = openWireformat.unmarshal(dis); + assertBeansEqual("", new HashSet(), expected, actual); - // now lets try parse it back again - ByteArrayInputStream in = new ByteArrayInputStream(buffer.toByteArray()); - DataInputStream dis = new DataInputStream(in); - Object actual = openWireformat.unmarshal(dis); - assertBeansEqual("", new HashSet(), expected, actual); + LOG.info("Parsed: " + actual); + } - LOG.info("Parsed: " + actual); - } - - protected void assertBeansEqual(String message, Set comparedObjects, Object expected, Object actual) throws Exception { - assertNotNull("Actual object should be equal to: " + expected + " but was null", actual); - if (comparedObjects.contains(expected)) { - return; - } - comparedObjects.add(expected); - Class type = expected.getClass(); - assertEquals("Should be of same type", type, actual.getClass()); - BeanInfo beanInfo = Introspector.getBeanInfo(type); - PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); - for (int i = 0; i < descriptors.length; i++) { - PropertyDescriptor descriptor = descriptors[i]; - Method method = descriptor.getReadMethod(); - if (method != null) { - String name = descriptor.getName(); - Object expectedValue = null; - Object actualValue = null; - try { - expectedValue = method.invoke(expected, EMPTY_ARGUMENTS); - actualValue = method.invoke(actual, EMPTY_ARGUMENTS); - } catch (Exception e) { - LOG.info("Failed to access property: " + name); - } - assertPropertyValuesEqual(message + name, comparedObjects, expectedValue, actualValue); + protected void assertBeansEqual(String message, + Set comparedObjects, + Object expected, + Object actual) throws Exception { + assertNotNull("Actual object should be equal to: " + expected + " but was null", actual); + if (comparedObjects.contains(expected)) { + return; + } + comparedObjects.add(expected); + Class type = expected.getClass(); + assertEquals("Should be of same type", type, actual.getClass()); + BeanInfo beanInfo = Introspector.getBeanInfo(type); + PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); + for (int i = 0; i < descriptors.length; i++) { + PropertyDescriptor descriptor = descriptors[i]; + Method method = descriptor.getReadMethod(); + if (method != null) { + String name = descriptor.getName(); + Object expectedValue = null; + Object actualValue = null; + try { + expectedValue = method.invoke(expected, EMPTY_ARGUMENTS); + actualValue = method.invoke(actual, EMPTY_ARGUMENTS); } - } - } - - protected void assertPropertyValuesEqual(String name, Set comparedObjects, Object expectedValue, Object actualValue) throws Exception { - String message = "Property " + name + " not equal"; - if (expectedValue == null) { - assertNull("Property " + name + " should be null", actualValue); - } else if (expectedValue instanceof Object[]) { - assertArrayEqual(message, comparedObjects, (Object[])expectedValue, (Object[])actualValue); - } else if (expectedValue.getClass().isArray()) { - assertPrimitiveArrayEqual(message, comparedObjects, expectedValue, actualValue); - } else { - if (expectedValue instanceof Exception) { - assertExceptionsEqual(message, (Exception)expectedValue, actualValue); - } else if (expectedValue instanceof ByteSequence) { - assertByteSequencesEqual(message, (ByteSequence)expectedValue, actualValue); - } else if (expectedValue instanceof DataStructure) { - assertBeansEqual(message + name, comparedObjects, expectedValue, actualValue); - } else if (expectedValue instanceof Enumeration) { - assertEnumerationEqual(message + name, comparedObjects, (Enumeration)expectedValue, (Enumeration)actualValue); - } else { - assertEquals(message, expectedValue, actualValue); + catch (Exception e) { + LOG.info("Failed to access property: " + name); } + assertPropertyValuesEqual(message + name, comparedObjects, expectedValue, actualValue); + } + } + } - } - } + protected void assertPropertyValuesEqual(String name, + Set comparedObjects, + Object expectedValue, + Object actualValue) throws Exception { + String message = "Property " + name + " not equal"; + if (expectedValue == null) { + assertNull("Property " + name + " should be null", actualValue); + } + else if (expectedValue instanceof Object[]) { + assertArrayEqual(message, comparedObjects, (Object[]) expectedValue, (Object[]) actualValue); + } + else if (expectedValue.getClass().isArray()) { + assertPrimitiveArrayEqual(message, comparedObjects, expectedValue, actualValue); + } + else { + if (expectedValue instanceof Exception) { + assertExceptionsEqual(message, (Exception) expectedValue, actualValue); + } + else if (expectedValue instanceof ByteSequence) { + assertByteSequencesEqual(message, (ByteSequence) expectedValue, actualValue); + } + else if (expectedValue instanceof DataStructure) { + assertBeansEqual(message + name, comparedObjects, expectedValue, actualValue); + } + else if (expectedValue instanceof Enumeration) { + assertEnumerationEqual(message + name, comparedObjects, (Enumeration) expectedValue, (Enumeration) actualValue); + } + else { + assertEquals(message, expectedValue, actualValue); + } - protected void assertArrayEqual(String message, Set comparedObjects, Object[] expected, Object[] actual) throws Exception { - assertEquals(message + ". Array length", expected.length, actual.length); - for (int i = 0; i < expected.length; i++) { - assertPropertyValuesEqual(message + ". element: " + i, comparedObjects, expected[i], actual[i]); - } - } + } + } - protected void assertEnumerationEqual(String message, Set comparedObjects, Enumeration expected, Enumeration actual) throws Exception { - while (expected.hasMoreElements()) { - Object expectedElem = expected.nextElement(); - Object actualElem = actual.nextElement(); - assertPropertyValuesEqual(message + ". element: " + expectedElem, comparedObjects, expectedElem, actualElem); - } - } + protected void assertArrayEqual(String message, + Set comparedObjects, + Object[] expected, + Object[] actual) throws Exception { + assertEquals(message + ". Array length", expected.length, actual.length); + for (int i = 0; i < expected.length; i++) { + assertPropertyValuesEqual(message + ". element: " + i, comparedObjects, expected[i], actual[i]); + } + } - protected void assertPrimitiveArrayEqual(String message, Set comparedObjects, Object expected, Object actual) throws ArrayIndexOutOfBoundsException, IllegalArgumentException, - Exception { - int length = Array.getLength(expected); - assertEquals(message + ". Array length", length, Array.getLength(actual)); - for (int i = 0; i < length; i++) { - assertPropertyValuesEqual(message + ". element: " + i, comparedObjects, Array.get(expected, i), Array.get(actual, i)); - } - } + protected void assertEnumerationEqual(String message, + Set comparedObjects, + Enumeration expected, + Enumeration actual) throws Exception { + while (expected.hasMoreElements()) { + Object expectedElem = expected.nextElement(); + Object actualElem = actual.nextElement(); + assertPropertyValuesEqual(message + ". element: " + expectedElem, comparedObjects, expectedElem, actualElem); + } + } - protected void assertByteSequencesEqual(String message, ByteSequence expected, Object actualValue) { - assertTrue(message + ". Actual value should be a ByteSequence but was: " + actualValue, actualValue instanceof ByteSequence); - ByteSequence actual = (ByteSequence)actualValue; - int length = expected.getLength(); - assertEquals(message + ". Length", length, actual.getLength()); - int offset = expected.getOffset(); - assertEquals(message + ". Offset", offset, actual.getOffset()); - byte[] data = expected.getData(); - byte[] actualData = actual.getData(); - for (int i = 0; i < length; i++) { - assertEquals(message + ". Offset " + i, data[offset + i], actualData[offset + i]); - } - } + protected void assertPrimitiveArrayEqual(String message, + Set comparedObjects, + Object expected, + Object actual) throws ArrayIndexOutOfBoundsException, IllegalArgumentException, Exception { + int length = Array.getLength(expected); + assertEquals(message + ". Array length", length, Array.getLength(actual)); + for (int i = 0; i < length; i++) { + assertPropertyValuesEqual(message + ". element: " + i, comparedObjects, Array.get(expected, i), Array.get(actual, i)); + } + } - protected void assertExceptionsEqual(String message, Exception expected, Object actualValue) { - assertTrue(message + ". Actual value should be an exception but was: " + actualValue, actualValue instanceof Exception); - Exception actual = (Exception)actualValue; - assertEquals(message, expected.getMessage(), actual.getMessage()); - } + protected void assertByteSequencesEqual(String message, ByteSequence expected, Object actualValue) { + assertTrue(message + ". Actual value should be a ByteSequence but was: " + actualValue, actualValue instanceof ByteSequence); + ByteSequence actual = (ByteSequence) actualValue; + int length = expected.getLength(); + assertEquals(message + ". Length", length, actual.getLength()); + int offset = expected.getOffset(); + assertEquals(message + ". Offset", offset, actual.getOffset()); + byte[] data = expected.getData(); + byte[] actualData = actual.getData(); + for (int i = 0; i < length; i++) { + assertEquals(message + ". Offset " + i, data[offset + i], actualData[offset + i]); + } + } - @Override - protected void setUp() throws Exception { - super.setUp(); - openWireformat = createOpenWireFormat(); - } + protected void assertExceptionsEqual(String message, Exception expected, Object actualValue) { + assertTrue(message + ". Actual value should be an exception but was: " + actualValue, actualValue instanceof Exception); + Exception actual = (Exception) actualValue; + assertEquals(message, expected.getMessage(), actual.getMessage()); + } - public void generateControlFile() throws Exception { - CONTROL_DIR.mkdirs(); - File dataFile = new File(CONTROL_DIR, getClass().getName() + ".bin"); + @Override + protected void setUp() throws Exception { + super.setUp(); + openWireformat = createOpenWireFormat(); + } - FileOutputStream os = new FileOutputStream(dataFile); - DataOutputStream ds = new DataOutputStream(os); - openWireformat.marshal(createObject(), ds); - ds.close(); - } + public void generateControlFile() throws Exception { + CONTROL_DIR.mkdirs(); + File dataFile = new File(CONTROL_DIR, getClass().getName() + ".bin"); - public InputStream generateInputStream() throws Exception { + FileOutputStream os = new FileOutputStream(dataFile); + DataOutputStream ds = new DataOutputStream(os); + openWireformat.marshal(createObject(), ds); + ds.close(); + } - ByteArrayOutputStream os = new ByteArrayOutputStream(); - DataOutputStream ds = new DataOutputStream(os); - openWireformat.marshal(createObject(), ds); - ds.close(); + public InputStream generateInputStream() throws Exception { - return new ByteArrayInputStream(os.toByteArray()); - } + ByteArrayOutputStream os = new ByteArrayOutputStream(); + DataOutputStream ds = new DataOutputStream(os); + openWireformat.marshal(createObject(), ds); + ds.close(); - public void assertControlFileIsEqual() throws Exception { - File dataFile = new File(CONTROL_DIR, getClass().getName() + ".bin"); - FileInputStream is1 = new FileInputStream(dataFile); - int pos = 0; - try { - InputStream is2 = generateInputStream(); - int a = is1.read(); - int b = is2.read(); + return new ByteArrayInputStream(os.toByteArray()); + } + + public void assertControlFileIsEqual() throws Exception { + File dataFile = new File(CONTROL_DIR, getClass().getName() + ".bin"); + FileInputStream is1 = new FileInputStream(dataFile); + int pos = 0; + try { + InputStream is2 = generateInputStream(); + int a = is1.read(); + int b = is2.read(); + pos++; + assertEquals("Data does not match control file: " + dataFile + " at byte position " + pos, a, b); + while (a >= 0 && b >= 0) { + a = is1.read(); + b = is2.read(); pos++; assertEquals("Data does not match control file: " + dataFile + " at byte position " + pos, a, b); - while (a >= 0 && b >= 0) { - a = is1.read(); - b = is2.read(); - pos++; - assertEquals("Data does not match control file: " + dataFile + " at byte position " + pos, a, b); - } - is2.close(); - } finally { - is1.close(); - } - } + } + is2.close(); + } + finally { + is1.close(); + } + } - protected abstract Object createObject() throws Exception; + protected abstract Object createObject() throws Exception; - protected void populateObject(Object info) throws Exception { - // empty method to allow derived classes to call super - // to simplify generated code - } + protected void populateObject(Object info) throws Exception { + // empty method to allow derived classes to call super + // to simplify generated code + } - protected OpenWireFormat createOpenWireFormat() { - OpenWireFormat wf = new OpenWireFormat(); - wf.setCacheEnabled(true); - wf.setStackTraceEnabled(false); - wf.setVersion(OpenWireFormat.DEFAULT_WIRE_VERSION); - return wf; - } + protected OpenWireFormat createOpenWireFormat() { + OpenWireFormat wf = new OpenWireFormat(); + wf.setCacheEnabled(true); + wf.setStackTraceEnabled(false); + wf.setVersion(OpenWireFormat.DEFAULT_WIRE_VERSION); + return wf; + } - protected BrokerId createBrokerId(String text) { - return new BrokerId(text); - } + protected BrokerId createBrokerId(String text) { + return new BrokerId(text); + } - protected TransactionId createTransactionId(String string) { - return new LocalTransactionId(createConnectionId(string), ++counter); - } + protected TransactionId createTransactionId(String string) { + return new LocalTransactionId(createConnectionId(string), ++counter); + } - protected ConnectionId createConnectionId(String string) { - return new ConnectionId(string); - } + protected ConnectionId createConnectionId(String string) { + return new ConnectionId(string); + } - protected SessionId createSessionId(String string) { - return new SessionId(createConnectionId(string), ++counter); - } + protected SessionId createSessionId(String string) { + return new SessionId(createConnectionId(string), ++counter); + } - protected ProducerId createProducerId(String string) { - return new ProducerId(createSessionId(string), ++counter); - } + protected ProducerId createProducerId(String string) { + return new ProducerId(createSessionId(string), ++counter); + } - protected ConsumerId createConsumerId(String string) { - return new ConsumerId(createSessionId(string), ++counter); - } + protected ConsumerId createConsumerId(String string) { + return new ConsumerId(createSessionId(string), ++counter); + } - protected MessageId createMessageId(String string) { - return new MessageId(createProducerId(string), ++counter); - } + protected MessageId createMessageId(String string) { + return new MessageId(createProducerId(string), ++counter); + } - protected ActiveMQDestination createActiveMQDestination(String string) { - return new ActiveMQQueue(string); - } + protected ActiveMQDestination createActiveMQDestination(String string) { + return new ActiveMQQueue(string); + } - protected Message createMessage(String string) throws Exception { - ActiveMQTextMessage message = (ActiveMQTextMessage)ActiveMQTextMessageTest.SINGLETON.createObject(); - message.setText(string); - return message; - } + protected Message createMessage(String string) throws Exception { + ActiveMQTextMessage message = (ActiveMQTextMessage) ActiveMQTextMessageTest.SINGLETON.createObject(); + message.setText(string); + return message; + } - protected BrokerInfo createBrokerInfo(String string) throws Exception { - return (BrokerInfo)BrokerInfoTest.SINGLETON.createObject(); - } + protected BrokerInfo createBrokerInfo(String string) throws Exception { + return (BrokerInfo) BrokerInfoTest.SINGLETON.createObject(); + } - protected MessageAck createMessageAck(String string) throws Exception { - return (MessageAck)MessageAckTest.SINGLETON.createObject(); - } + protected MessageAck createMessageAck(String string) throws Exception { + return (MessageAck) MessageAckTest.SINGLETON.createObject(); + } - protected DataStructure createDataStructure(String string) throws Exception { - return createBrokerInfo(string); - } + protected DataStructure createDataStructure(String string) throws Exception { + return createBrokerInfo(string); + } - protected Throwable createThrowable(String string) { - // we have issues with stack frames not being equal so share the same - // exception each time - return SINGLETON_EXCEPTION; - } + protected Throwable createThrowable(String string) { + // we have issues with stack frames not being equal so share the same + // exception each time + return SINGLETON_EXCEPTION; + } - protected BooleanExpression createBooleanExpression(String string) { - return new NetworkBridgeFilter(null, new BrokerId(string), 10, 10); - } + protected BooleanExpression createBooleanExpression(String string) { + return new NetworkBridgeFilter(null, new BrokerId(string), 10, 10); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/ItStillMarshallsTheSameTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/ItStillMarshallsTheSameTest.java index 8372f594b9..63f8ee2a45 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/ItStillMarshallsTheSameTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/ItStillMarshallsTheSameTest.java @@ -20,8 +20,8 @@ import junit.framework.TestCase; public class ItStillMarshallsTheSameTest extends TestCase { - public void testAll() throws Exception { - BrokerInfoData.assertAllControlFileAreEqual(); - } - + public void testAll() throws Exception { + BrokerInfoData.assertAllControlFileAreEqual(); + } + } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/NumberRangesWhileMarshallingTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/NumberRangesWhileMarshallingTest.java index 973a00734b..a31a7d2025 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/NumberRangesWhileMarshallingTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/NumberRangesWhileMarshallingTest.java @@ -34,112 +34,111 @@ import org.slf4j.LoggerFactory; */ public class NumberRangesWhileMarshallingTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(NumberRangesWhileMarshallingTest.class); + private static final Logger LOG = LoggerFactory.getLogger(NumberRangesWhileMarshallingTest.class); - protected String connectionId = "Cheese"; - protected ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - protected DataOutputStream ds = new DataOutputStream(buffer); - protected OpenWireFormat openWireformat; - protected int endOfStreamMarker = 0x12345678; + protected String connectionId = "Cheese"; + protected ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + protected DataOutputStream ds = new DataOutputStream(buffer); + protected OpenWireFormat openWireformat; + protected int endOfStreamMarker = 0x12345678; - public void testLongNumberRanges() throws Exception { - long[] numberValues = { - // bytes - 0, 1, 0x7e, 0x7f, 0x80, 0x81, 0xf0, 0xff, - // shorts - 0x7eff, 0x7fffL, 0x8001L, 0x8000L, 0xe000L, 0xe0001L, 0xff00L, 0xffffL, - // ints - 0x10000L, 0x700000L, 0x12345678L, 0x72345678L, 0x7fffffffL, 0x80000000L, 0x80000001L, 0xE0000001L, 0xFFFFFFFFL, - // 3 byte longs - 0x123456781L, 0x1234567812L, 0x12345678123L, 0x123456781234L, 0x1234567812345L, 0x12345678123456L, 0x7e345678123456L, 0x7fffffffffffffL, - 0x80000000000000L, 0x80000000000001L, 0xe0000000000001L, 0xffffffffffffffL, - // 4 byte longs - 0x1234567812345678L, 0x7fffffffffffffffL, 0x8000000000000000L, 0x8000000000000001L, 0xe000000000000001L, 0xffffffffffffffffL, 1 - }; + public void testLongNumberRanges() throws Exception { + long[] numberValues = { + // bytes + 0, 1, 0x7e, 0x7f, 0x80, 0x81, 0xf0, 0xff, + // shorts + 0x7eff, 0x7fffL, 0x8001L, 0x8000L, 0xe000L, 0xe0001L, 0xff00L, 0xffffL, + // ints + 0x10000L, 0x700000L, 0x12345678L, 0x72345678L, 0x7fffffffL, 0x80000000L, 0x80000001L, 0xE0000001L, 0xFFFFFFFFL, + // 3 byte longs + 0x123456781L, 0x1234567812L, 0x12345678123L, 0x123456781234L, 0x1234567812345L, 0x12345678123456L, 0x7e345678123456L, 0x7fffffffffffffL, 0x80000000000000L, 0x80000000000001L, 0xe0000000000001L, 0xffffffffffffffL, + // 4 byte longs + 0x1234567812345678L, 0x7fffffffffffffffL, 0x8000000000000000L, 0x8000000000000001L, 0xe000000000000001L, 0xffffffffffffffffL, 1}; - for (int i = 0; i < numberValues.length; i++) { - long value = numberValues[i]; + for (int i = 0; i < numberValues.length; i++) { + long value = numberValues[i]; - SessionId object = new SessionId(); - object.setConnectionId(connectionId); - object.setValue(value); - writeObject(object); - } - ds.writeInt(endOfStreamMarker); + SessionId object = new SessionId(); + object.setConnectionId(connectionId); + object.setValue(value); + writeObject(object); + } + ds.writeInt(endOfStreamMarker); - // now lets read from the stream - ds.close(); + // now lets read from the stream + ds.close(); - ByteArrayInputStream in = new ByteArrayInputStream(buffer.toByteArray()); - DataInputStream dis = new DataInputStream(in); - for (int i = 0; i < numberValues.length; i++) { - long value = numberValues[i]; - String expected = Long.toHexString(value); - LOG.info("Unmarshaling value: " + i + " = " + expected); + ByteArrayInputStream in = new ByteArrayInputStream(buffer.toByteArray()); + DataInputStream dis = new DataInputStream(in); + for (int i = 0; i < numberValues.length; i++) { + long value = numberValues[i]; + String expected = Long.toHexString(value); + LOG.info("Unmarshaling value: " + i + " = " + expected); - SessionId command = (SessionId)openWireformat.unmarshal(dis); - assertEquals("connection ID in object: " + i, connectionId, command.getConnectionId()); - String actual = Long.toHexString(command.getValue()); - assertEquals("value of object: " + i + " was: " + actual, expected, actual); - } - int marker = dis.readInt(); - assertEquals("Marker int", Integer.toHexString(endOfStreamMarker), Integer.toHexString(marker)); + SessionId command = (SessionId) openWireformat.unmarshal(dis); + assertEquals("connection ID in object: " + i, connectionId, command.getConnectionId()); + String actual = Long.toHexString(command.getValue()); + assertEquals("value of object: " + i + " was: " + actual, expected, actual); + } + int marker = dis.readInt(); + assertEquals("Marker int", Integer.toHexString(endOfStreamMarker), Integer.toHexString(marker)); - // lets try read and we should get an exception - try { - byte value = dis.readByte(); - fail("Should have reached the end of the stream: " + value); - } catch (IOException e) { - // worked! - } - } + // lets try read and we should get an exception + try { + byte value = dis.readByte(); + fail("Should have reached the end of the stream: " + value); + } + catch (IOException e) { + // worked! + } + } - public void testMaxFrameSize() throws Exception { - OpenWireFormat wf = new OpenWireFormat(); - wf.setMaxFrameSize(10); - ActiveMQTextMessage msg = new ActiveMQTextMessage(); - msg.setText("This is a test"); + public void testMaxFrameSize() throws Exception { + OpenWireFormat wf = new OpenWireFormat(); + wf.setMaxFrameSize(10); + ActiveMQTextMessage msg = new ActiveMQTextMessage(); + msg.setText("This is a test"); - writeObject(msg); - ds.writeInt(endOfStreamMarker); + writeObject(msg); + ds.writeInt(endOfStreamMarker); - // now lets read from the stream - ds.close(); + // now lets read from the stream + ds.close(); - ByteArrayInputStream in = new ByteArrayInputStream(buffer.toByteArray()); - DataInputStream dis = new DataInputStream(in); + ByteArrayInputStream in = new ByteArrayInputStream(buffer.toByteArray()); + DataInputStream dis = new DataInputStream(in); - try { - wf.unmarshal(dis); - } catch (IOException ioe) { - return; - } + try { + wf.unmarshal(dis); + } + catch (IOException ioe) { + return; + } - fail("Should fail because of the large frame size"); + fail("Should fail because of the large frame size"); + } - } + public void testDefaultMaxFrameSizeUnlimited() { + OpenWireFormat wf = new OpenWireFormat(); + assertEquals(Long.MAX_VALUE, wf.getMaxFrameSize()); + } - public void testDefaultMaxFrameSizeUnlimited() { - OpenWireFormat wf = new OpenWireFormat(); - assertEquals(Long.MAX_VALUE, wf.getMaxFrameSize()); - } + @Override + protected void setUp() throws Exception { + super.setUp(); + openWireformat = createOpenWireFormat(); + } - @Override - protected void setUp() throws Exception { - super.setUp(); - openWireformat = createOpenWireFormat(); - } + protected OpenWireFormat createOpenWireFormat() { + OpenWireFormat wf = new OpenWireFormat(); + wf.setCacheEnabled(true); + wf.setStackTraceEnabled(false); + wf.setVersion(1); + return wf; + } - protected OpenWireFormat createOpenWireFormat() { - OpenWireFormat wf = new OpenWireFormat(); - wf.setCacheEnabled(true); - wf.setStackTraceEnabled(false); - wf.setVersion(1); - return wf; - } - - private void writeObject(Object object) throws IOException { - openWireformat.marshal(object, ds); - } + private void writeObject(Object object) throws IOException { + openWireformat.marshal(object, ds); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/WireFormatInfoData.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/WireFormatInfoData.java index 208a6ed2d1..c396abb113 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/WireFormatInfoData.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/WireFormatInfoData.java @@ -22,12 +22,12 @@ import org.apache.activemq.command.WireFormatInfo; public class WireFormatInfoData extends DataFileGenerator { - protected Object createObject() throws IOException { - WireFormatInfo rc = new WireFormatInfo(); - rc.setResponseRequired(false); - rc.setCacheEnabled(true); - rc.setVersion(1); - return rc; - } + protected Object createObject() throws IOException { + WireFormatInfo rc = new WireFormatInfo(); + rc.setResponseRequired(false); + rc.setCacheEnabled(true); + rc.setVersion(1); + return rc; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQBytesMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQBytesMessageTest.java index a6a649c1c7..81ccac0723 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQBytesMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQBytesMessageTest.java @@ -20,27 +20,25 @@ import org.apache.activemq.command.ActiveMQBytesMessage; /** * Test case for the OpenWire marshalling for ActiveMQBytesMessage - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class ActiveMQBytesMessageTest extends ActiveMQMessageTest { - public static final ActiveMQBytesMessageTest SINGLETON = new ActiveMQBytesMessageTest(); + public static final ActiveMQBytesMessageTest SINGLETON = new ActiveMQBytesMessageTest(); - public Object createObject() throws Exception { - ActiveMQBytesMessage info = new ActiveMQBytesMessage(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ActiveMQBytesMessage info = new ActiveMQBytesMessage(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQBytesMessage info = (ActiveMQBytesMessage)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ActiveMQBytesMessage info = (ActiveMQBytesMessage) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQDestinationTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQDestinationTestSupport.java index bfa4aedfe8..90cec8ba20 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQDestinationTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQDestinationTestSupport.java @@ -21,20 +21,18 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for ActiveMQDestination - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public abstract class ActiveMQDestinationTestSupport extends DataFileGeneratorTestSupport { - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQDestination info = (ActiveMQDestination)object; - info.setPhysicalName("PhysicalName:1"); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ActiveMQDestination info = (ActiveMQDestination) object; + info.setPhysicalName("PhysicalName:1"); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQMapMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQMapMessageTest.java index 2a0915478b..48662a5acf 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQMapMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQMapMessageTest.java @@ -20,27 +20,25 @@ import org.apache.activemq.command.ActiveMQMapMessage; /** * Test case for the OpenWire marshalling for ActiveMQMapMessage - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class ActiveMQMapMessageTest extends ActiveMQMessageTest { - public static final ActiveMQMapMessageTest SINGLETON = new ActiveMQMapMessageTest(); + public static final ActiveMQMapMessageTest SINGLETON = new ActiveMQMapMessageTest(); - public Object createObject() throws Exception { - ActiveMQMapMessage info = new ActiveMQMapMessage(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ActiveMQMapMessage info = new ActiveMQMapMessage(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQMapMessage info = (ActiveMQMapMessage)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ActiveMQMapMessage info = (ActiveMQMapMessage) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQMessageTest.java index 79f252056d..df78d73f0a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQMessageTest.java @@ -20,27 +20,25 @@ import org.apache.activemq.command.ActiveMQMessage; /** * Test case for the OpenWire marshalling for ActiveMQMessage - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class ActiveMQMessageTest extends MessageTestSupport { - public static final ActiveMQMessageTest SINGLETON = new ActiveMQMessageTest(); + public static final ActiveMQMessageTest SINGLETON = new ActiveMQMessageTest(); - public Object createObject() throws Exception { - ActiveMQMessage info = new ActiveMQMessage(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ActiveMQMessage info = new ActiveMQMessage(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQMessage info = (ActiveMQMessage)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ActiveMQMessage info = (ActiveMQMessage) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQObjectMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQObjectMessageTest.java index 30d1476505..7dd20c0f71 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQObjectMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQObjectMessageTest.java @@ -20,27 +20,25 @@ import org.apache.activemq.command.ActiveMQObjectMessage; /** * Test case for the OpenWire marshalling for ActiveMQObjectMessage - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class ActiveMQObjectMessageTest extends ActiveMQMessageTest { - public static final ActiveMQObjectMessageTest SINGLETON = new ActiveMQObjectMessageTest(); + public static final ActiveMQObjectMessageTest SINGLETON = new ActiveMQObjectMessageTest(); - public Object createObject() throws Exception { - ActiveMQObjectMessage info = new ActiveMQObjectMessage(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ActiveMQObjectMessage info = new ActiveMQObjectMessage(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQObjectMessage info = (ActiveMQObjectMessage)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ActiveMQObjectMessage info = (ActiveMQObjectMessage) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQQueueTest.java index 459090c5e4..09427c7ae2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQQueueTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQQueueTest.java @@ -23,22 +23,20 @@ import org.apache.activemq.command.ActiveMQQueue; * auto generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public class ActiveMQQueueTest extends ActiveMQDestinationTestSupport { - public static final ActiveMQQueueTest SINGLETON = new ActiveMQQueueTest(); + public static final ActiveMQQueueTest SINGLETON = new ActiveMQQueueTest(); - public Object createObject() throws Exception { - ActiveMQQueue info = new ActiveMQQueue(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ActiveMQQueue info = new ActiveMQQueue(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQQueue info = (ActiveMQQueue)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ActiveMQQueue info = (ActiveMQQueue) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQStreamMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQStreamMessageTest.java index 6648554646..d69f80a9c5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQStreamMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQStreamMessageTest.java @@ -23,22 +23,20 @@ import org.apache.activemq.command.ActiveMQStreamMessage; * file is auto generated - do not modify! if you need to make a change, please * see the modify the groovy scripts in the under src/gram/script and then use * maven openwire:generate to regenerate this file. - * - * */ public class ActiveMQStreamMessageTest extends ActiveMQMessageTest { - public static final ActiveMQStreamMessageTest SINGLETON = new ActiveMQStreamMessageTest(); + public static final ActiveMQStreamMessageTest SINGLETON = new ActiveMQStreamMessageTest(); - public Object createObject() throws Exception { - ActiveMQStreamMessage info = new ActiveMQStreamMessage(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ActiveMQStreamMessage info = new ActiveMQStreamMessage(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQStreamMessage info = (ActiveMQStreamMessage)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ActiveMQStreamMessage info = (ActiveMQStreamMessage) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTempDestinationTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTempDestinationTestSupport.java index 73133c470a..c486dba2df 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTempDestinationTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTempDestinationTestSupport.java @@ -23,14 +23,12 @@ import org.apache.activemq.command.ActiveMQTempDestination; * This file is auto generated - do not modify! if you need to make a change, * please see the modify the groovy scripts in the under src/gram/script and * then use maven openwire:generate to regenerate this file. - * - * */ public abstract class ActiveMQTempDestinationTestSupport extends ActiveMQDestinationTestSupport { - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQTempDestination info = (ActiveMQTempDestination)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ActiveMQTempDestination info = (ActiveMQTempDestination) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTempQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTempQueueTest.java index c358a5a808..60c5342aa9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTempQueueTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTempQueueTest.java @@ -23,22 +23,20 @@ import org.apache.activemq.command.ActiveMQTempQueue; * is auto generated - do not modify! if you need to make a change, please see * the modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public class ActiveMQTempQueueTest extends ActiveMQTempDestinationTestSupport { - public static final ActiveMQTempQueueTest SINGLETON = new ActiveMQTempQueueTest(); + public static final ActiveMQTempQueueTest SINGLETON = new ActiveMQTempQueueTest(); - public Object createObject() throws Exception { - ActiveMQTempQueue info = new ActiveMQTempQueue(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ActiveMQTempQueue info = new ActiveMQTempQueue(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQTempQueue info = (ActiveMQTempQueue)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ActiveMQTempQueue info = (ActiveMQTempQueue) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTempTopicTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTempTopicTest.java index 18e33c0e34..8e6d048b88 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTempTopicTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTempTopicTest.java @@ -23,22 +23,20 @@ import org.apache.activemq.command.ActiveMQTempTopic; * is auto generated - do not modify! if you need to make a change, please see * the modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public class ActiveMQTempTopicTest extends ActiveMQTempDestinationTestSupport { - public static final ActiveMQTempTopicTest SINGLETON = new ActiveMQTempTopicTest(); + public static final ActiveMQTempTopicTest SINGLETON = new ActiveMQTempTopicTest(); - public Object createObject() throws Exception { - ActiveMQTempTopic info = new ActiveMQTempTopic(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ActiveMQTempTopic info = new ActiveMQTempTopic(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQTempTopic info = (ActiveMQTempTopic)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ActiveMQTempTopic info = (ActiveMQTempTopic) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTextMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTextMessageTest.java index 839d713673..56fef8e52c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTextMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTextMessageTest.java @@ -23,22 +23,20 @@ import org.apache.activemq.command.ActiveMQTextMessage; * file is auto generated - do not modify! if you need to make a change, please * see the modify the groovy scripts in the under src/gram/script and then use * maven openwire:generate to regenerate this file. - * - * */ public class ActiveMQTextMessageTest extends ActiveMQMessageTest { - public static final ActiveMQTextMessageTest SINGLETON = new ActiveMQTextMessageTest(); + public static final ActiveMQTextMessageTest SINGLETON = new ActiveMQTextMessageTest(); - public Object createObject() throws Exception { - ActiveMQTextMessage info = new ActiveMQTextMessage(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ActiveMQTextMessage info = new ActiveMQTextMessage(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQTextMessage info = (ActiveMQTextMessage)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ActiveMQTextMessage info = (ActiveMQTextMessage) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTopicTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTopicTest.java index a08d43ae79..e85b5bca06 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTopicTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTopicTest.java @@ -23,22 +23,20 @@ import org.apache.activemq.command.ActiveMQTopic; * auto generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public class ActiveMQTopicTest extends ActiveMQDestinationTestSupport { - public static final ActiveMQTopicTest SINGLETON = new ActiveMQTopicTest(); + public static final ActiveMQTopicTest SINGLETON = new ActiveMQTopicTest(); - public Object createObject() throws Exception { - ActiveMQTopic info = new ActiveMQTopic(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ActiveMQTopic info = new ActiveMQTopic(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQTopic info = (ActiveMQTopic)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ActiveMQTopic info = (ActiveMQTopic) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/BaseCommandTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/BaseCommandTestSupport.java index 3240cf0a17..befa49a56f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/BaseCommandTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/BaseCommandTestSupport.java @@ -24,16 +24,14 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; * auto generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public abstract class BaseCommandTestSupport extends DataFileGeneratorTestSupport { - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - BaseCommand info = (BaseCommand)object; - info.setCommandId(1); - info.setResponseRequired(true); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + BaseCommand info = (BaseCommand) object; + info.setCommandId(1); + info.setResponseRequired(true); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/BrokerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/BrokerIdTest.java index 1893de3100..798646f013 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/BrokerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/BrokerIdTest.java @@ -21,28 +21,26 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for BrokerId - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class BrokerIdTest extends DataFileGeneratorTestSupport { - public static final BrokerIdTest SINGLETON = new BrokerIdTest(); + public static final BrokerIdTest SINGLETON = new BrokerIdTest(); - public Object createObject() throws Exception { - BrokerId info = new BrokerId(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + BrokerId info = new BrokerId(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - BrokerId info = (BrokerId)object; - info.setValue("Value:1"); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + BrokerId info = (BrokerId) object; + info.setValue("Value:1"); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/BrokerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/BrokerInfoTest.java index e0541e2ab8..010edc99a0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/BrokerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/BrokerInfoTest.java @@ -23,36 +23,34 @@ import org.apache.activemq.command.BrokerInfo; * auto generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public class BrokerInfoTest extends BaseCommandTestSupport { - public static final BrokerInfoTest SINGLETON = new BrokerInfoTest(); + public static final BrokerInfoTest SINGLETON = new BrokerInfoTest(); - public Object createObject() throws Exception { - BrokerInfo info = new BrokerInfo(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + BrokerInfo info = new BrokerInfo(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - BrokerInfo info = (BrokerInfo)object; - info.setBrokerId(createBrokerId("BrokerId:1")); - info.setBrokerURL("BrokerURL:2"); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + BrokerInfo info = (BrokerInfo) object; + info.setBrokerId(createBrokerId("BrokerId:1")); + info.setBrokerURL("BrokerURL:2"); - { - BrokerInfo value[] = new BrokerInfo[0]; - for (int i = 0; i < 0; i++) { - value[i] = createBrokerInfo("PeerBrokerInfos:3"); - } - info.setPeerBrokerInfos(value); - } - info.setBrokerName("BrokerName:4"); - info.setSlaveBroker(true); - info.setMasterBroker(false); - info.setFaultTolerantConfiguration(true); + { + BrokerInfo value[] = new BrokerInfo[0]; + for (int i = 0; i < 0; i++) { + value[i] = createBrokerInfo("PeerBrokerInfos:3"); + } + info.setPeerBrokerInfos(value); + } + info.setBrokerName("BrokerName:4"); + info.setSlaveBroker(true); + info.setMasterBroker(false); + info.setFaultTolerantConfiguration(true); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConnectionControlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConnectionControlTest.java index 4dae00326d..207359f82e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConnectionControlTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConnectionControlTest.java @@ -20,32 +20,30 @@ import org.apache.activemq.command.ConnectionControl; /** * Test case for the OpenWire marshalling for ConnectionControl - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class ConnectionControlTest extends BaseCommandTestSupport { - public static final ConnectionControlTest SINGLETON = new ConnectionControlTest(); + public static final ConnectionControlTest SINGLETON = new ConnectionControlTest(); - public Object createObject() throws Exception { - ConnectionControl info = new ConnectionControl(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ConnectionControl info = new ConnectionControl(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionControl info = (ConnectionControl)object; - info.setClose(true); - info.setExit(false); - info.setFaultTolerant(true); - info.setResume(false); - info.setSuspend(true); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConnectionControl info = (ConnectionControl) object; + info.setClose(true); + info.setExit(false); + info.setFaultTolerant(true); + info.setResume(false); + info.setSuspend(true); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConnectionErrorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConnectionErrorTest.java index 438fe6b373..aaa399e2f4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConnectionErrorTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConnectionErrorTest.java @@ -20,29 +20,27 @@ import org.apache.activemq.command.ConnectionError; /** * Test case for the OpenWire marshalling for ConnectionError - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class ConnectionErrorTest extends BaseCommandTestSupport { - public static final ConnectionErrorTest SINGLETON = new ConnectionErrorTest(); + public static final ConnectionErrorTest SINGLETON = new ConnectionErrorTest(); - public Object createObject() throws Exception { - ConnectionError info = new ConnectionError(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ConnectionError info = new ConnectionError(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionError info = (ConnectionError)object; - info.setException(createThrowable("Exception:1")); - info.setConnectionId(createConnectionId("ConnectionId:2")); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConnectionError info = (ConnectionError) object; + info.setException(createThrowable("Exception:1")); + info.setConnectionId(createConnectionId("ConnectionId:2")); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConnectionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConnectionIdTest.java index 3dd221e28c..105910f7c6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConnectionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConnectionIdTest.java @@ -21,28 +21,26 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for ConnectionId - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class ConnectionIdTest extends DataFileGeneratorTestSupport { - public static final ConnectionIdTest SINGLETON = new ConnectionIdTest(); + public static final ConnectionIdTest SINGLETON = new ConnectionIdTest(); - public Object createObject() throws Exception { - ConnectionId info = new ConnectionId(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ConnectionId info = new ConnectionId(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionId info = (ConnectionId)object; - info.setValue("Value:1"); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConnectionId info = (ConnectionId) object; + info.setValue("Value:1"); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConnectionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConnectionInfoTest.java index 9b457272b3..784052c6a7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConnectionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConnectionInfoTest.java @@ -24,36 +24,34 @@ import org.apache.activemq.command.ConnectionInfo; * auto generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public class ConnectionInfoTest extends BaseCommandTestSupport { - public static final ConnectionInfoTest SINGLETON = new ConnectionInfoTest(); + public static final ConnectionInfoTest SINGLETON = new ConnectionInfoTest(); - public Object createObject() throws Exception { - ConnectionInfo info = new ConnectionInfo(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ConnectionInfo info = new ConnectionInfo(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionInfo info = (ConnectionInfo)object; - info.setConnectionId(createConnectionId("ConnectionId:1")); - info.setClientId("ClientId:2"); - info.setPassword("Password:3"); - info.setUserName("UserName:4"); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConnectionInfo info = (ConnectionInfo) object; + info.setConnectionId(createConnectionId("ConnectionId:1")); + info.setClientId("ClientId:2"); + info.setPassword("Password:3"); + info.setUserName("UserName:4"); - { - BrokerId value[] = new BrokerId[2]; - for (int i = 0; i < 2; i++) { - value[i] = createBrokerId("BrokerPath:5"); - } - info.setBrokerPath(value); - } - info.setBrokerMasterConnector(true); - info.setManageable(false); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:5"); + } + info.setBrokerPath(value); + } + info.setBrokerMasterConnector(true); + info.setManageable(false); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConsumerControlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConsumerControlTest.java index 4ea061d01a..e86c538a74 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConsumerControlTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConsumerControlTest.java @@ -20,30 +20,28 @@ import org.apache.activemq.command.ConsumerControl; /** * Test case for the OpenWire marshalling for ConsumerControl - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class ConsumerControlTest extends BaseCommandTestSupport { - public static final ConsumerControlTest SINGLETON = new ConsumerControlTest(); + public static final ConsumerControlTest SINGLETON = new ConsumerControlTest(); - public Object createObject() throws Exception { - ConsumerControl info = new ConsumerControl(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ConsumerControl info = new ConsumerControl(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConsumerControl info = (ConsumerControl)object; - info.setClose(true); - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setPrefetch(1); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConsumerControl info = (ConsumerControl) object; + info.setClose(true); + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setPrefetch(1); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConsumerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConsumerIdTest.java index c31d8ef350..fd049856f1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConsumerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConsumerIdTest.java @@ -21,30 +21,28 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for ConsumerId - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class ConsumerIdTest extends DataFileGeneratorTestSupport { - public static final ConsumerIdTest SINGLETON = new ConsumerIdTest(); + public static final ConsumerIdTest SINGLETON = new ConsumerIdTest(); - public Object createObject() throws Exception { - ConsumerId info = new ConsumerId(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ConsumerId info = new ConsumerId(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConsumerId info = (ConsumerId)object; - info.setConnectionId("ConnectionId:1"); - info.setSessionId(1); - info.setValue(2); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConsumerId info = (ConsumerId) object; + info.setConnectionId("ConnectionId:1"); + info.setSessionId(1); + info.setValue(2); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConsumerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConsumerInfoTest.java index 50efd51e0d..d516b8d478 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConsumerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ConsumerInfoTest.java @@ -24,46 +24,44 @@ import org.apache.activemq.command.ConsumerInfo; * auto generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public class ConsumerInfoTest extends BaseCommandTestSupport { - public static final ConsumerInfoTest SINGLETON = new ConsumerInfoTest(); + public static final ConsumerInfoTest SINGLETON = new ConsumerInfoTest(); - public Object createObject() throws Exception { - ConsumerInfo info = new ConsumerInfo(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ConsumerInfo info = new ConsumerInfo(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConsumerInfo info = (ConsumerInfo)object; - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setBrowser(true); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setPrefetchSize(1); - info.setMaximumPendingMessageLimit(2); - info.setDispatchAsync(false); - info.setSelector("Selector:3"); - info.setSubscriptionName("SubcriptionName:4"); - info.setNoLocal(true); - info.setExclusive(false); - info.setRetroactive(true); - info.setPriority((byte)1); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConsumerInfo info = (ConsumerInfo) object; + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setBrowser(true); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setPrefetchSize(1); + info.setMaximumPendingMessageLimit(2); + info.setDispatchAsync(false); + info.setSelector("Selector:3"); + info.setSubscriptionName("SubcriptionName:4"); + info.setNoLocal(true); + info.setExclusive(false); + info.setRetroactive(true); + info.setPriority((byte) 1); - { - BrokerId value[] = new BrokerId[2]; - for (int i = 0; i < 2; i++) { - value[i] = createBrokerId("BrokerPath:5"); - } - info.setBrokerPath(value); - } - info.setAdditionalPredicate(createBooleanExpression("AdditionalPredicate:6")); - info.setNetworkSubscription(false); - info.setOptimizedAcknowledge(true); - info.setNoRangeAcks(false); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:5"); + } + info.setBrokerPath(value); + } + info.setAdditionalPredicate(createBooleanExpression("AdditionalPredicate:6")); + info.setNetworkSubscription(false); + info.setOptimizedAcknowledge(true); + info.setNoRangeAcks(false); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ControlCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ControlCommandTest.java index 1efa08d158..165929b71f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ControlCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ControlCommandTest.java @@ -20,28 +20,26 @@ import org.apache.activemq.command.ControlCommand; /** * Test case for the OpenWire marshalling for ControlCommand - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class ControlCommandTest extends BaseCommandTestSupport { - public static final ControlCommandTest SINGLETON = new ControlCommandTest(); + public static final ControlCommandTest SINGLETON = new ControlCommandTest(); - public Object createObject() throws Exception { - ControlCommand info = new ControlCommand(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ControlCommand info = new ControlCommand(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ControlCommand info = (ControlCommand)object; - info.setCommand("Command:1"); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ControlCommand info = (ControlCommand) object; + info.setCommand("Command:1"); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/DataArrayResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/DataArrayResponseTest.java index 3523ea74f2..b4de6685b2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/DataArrayResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/DataArrayResponseTest.java @@ -24,30 +24,28 @@ import org.apache.activemq.command.DataStructure; * is auto generated - do not modify! if you need to make a change, please see * the modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public class DataArrayResponseTest extends ResponseTest { - public static final DataArrayResponseTest SINGLETON = new DataArrayResponseTest(); + public static final DataArrayResponseTest SINGLETON = new DataArrayResponseTest(); - public Object createObject() throws Exception { - DataArrayResponse info = new DataArrayResponse(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + DataArrayResponse info = new DataArrayResponse(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DataArrayResponse info = (DataArrayResponse)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + DataArrayResponse info = (DataArrayResponse) object; - { - DataStructure value[] = new DataStructure[2]; - for (int i = 0; i < 2; i++) { - value[i] = createDataStructure("Data:1"); - } - info.setData(value); - } + { + DataStructure value[] = new DataStructure[2]; + for (int i = 0; i < 2; i++) { + value[i] = createDataStructure("Data:1"); + } + info.setData(value); + } - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/DataResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/DataResponseTest.java index cffbd0a223..61236774bf 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/DataResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/DataResponseTest.java @@ -20,28 +20,26 @@ import org.apache.activemq.command.DataResponse; /** * Test case for the OpenWire marshalling for DataResponse - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class DataResponseTest extends ResponseTest { - public static final DataResponseTest SINGLETON = new DataResponseTest(); + public static final DataResponseTest SINGLETON = new DataResponseTest(); - public Object createObject() throws Exception { - DataResponse info = new DataResponse(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + DataResponse info = new DataResponse(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DataResponse info = (DataResponse)object; - info.setData(createDataStructure("Data:1")); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + DataResponse info = (DataResponse) object; + info.setData(createDataStructure("Data:1")); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/DestinationInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/DestinationInfoTest.java index 20688f5ea7..31d43857e6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/DestinationInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/DestinationInfoTest.java @@ -24,34 +24,32 @@ import org.apache.activemq.command.DestinationInfo; * is auto generated - do not modify! if you need to make a change, please see * the modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public class DestinationInfoTest extends BaseCommandTestSupport { - public static final DestinationInfoTest SINGLETON = new DestinationInfoTest(); + public static final DestinationInfoTest SINGLETON = new DestinationInfoTest(); - public Object createObject() throws Exception { - DestinationInfo info = new DestinationInfo(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + DestinationInfo info = new DestinationInfo(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DestinationInfo info = (DestinationInfo)object; - info.setConnectionId(createConnectionId("ConnectionId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setOperationType((byte)1); - info.setTimeout(1); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + DestinationInfo info = (DestinationInfo) object; + info.setConnectionId(createConnectionId("ConnectionId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setOperationType((byte) 1); + info.setTimeout(1); - { - BrokerId value[] = new BrokerId[2]; - for (int i = 0; i < 2; i++) { - value[i] = createBrokerId("BrokerPath:3"); - } - info.setBrokerPath(value); - } + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:3"); + } + info.setBrokerPath(value); + } - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/DiscoveryEventTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/DiscoveryEventTest.java index 33a33b59ea..09fa5c228f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/DiscoveryEventTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/DiscoveryEventTest.java @@ -21,29 +21,27 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for DiscoveryEvent - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class DiscoveryEventTest extends DataFileGeneratorTestSupport { - public static final DiscoveryEventTest SINGLETON = new DiscoveryEventTest(); + public static final DiscoveryEventTest SINGLETON = new DiscoveryEventTest(); - public Object createObject() throws Exception { - DiscoveryEvent info = new DiscoveryEvent(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + DiscoveryEvent info = new DiscoveryEvent(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DiscoveryEvent info = (DiscoveryEvent)object; - info.setServiceName("ServiceName:1"); - info.setBrokerName("BrokerName:2"); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + DiscoveryEvent info = (DiscoveryEvent) object; + info.setServiceName("ServiceName:1"); + info.setBrokerName("BrokerName:2"); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ExceptionResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ExceptionResponseTest.java index 01074ecd0d..ae219f948b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ExceptionResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ExceptionResponseTest.java @@ -20,28 +20,26 @@ import org.apache.activemq.command.ExceptionResponse; /** * Test case for the OpenWire marshalling for ExceptionResponse - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class ExceptionResponseTest extends ResponseTest { - public static final ExceptionResponseTest SINGLETON = new ExceptionResponseTest(); + public static final ExceptionResponseTest SINGLETON = new ExceptionResponseTest(); - public Object createObject() throws Exception { - ExceptionResponse info = new ExceptionResponse(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ExceptionResponse info = new ExceptionResponse(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ExceptionResponse info = (ExceptionResponse)object; - info.setException(createThrowable("Exception:1")); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ExceptionResponse info = (ExceptionResponse) object; + info.setException(createThrowable("Exception:1")); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/FlushCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/FlushCommandTest.java index 508444016c..1fee22b87f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/FlushCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/FlushCommandTest.java @@ -20,27 +20,25 @@ import org.apache.activemq.command.FlushCommand; /** * Test case for the OpenWire marshalling for FlushCommand - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class FlushCommandTest extends BaseCommandTestSupport { - public static final FlushCommandTest SINGLETON = new FlushCommandTest(); + public static final FlushCommandTest SINGLETON = new FlushCommandTest(); - public Object createObject() throws Exception { - FlushCommand info = new FlushCommand(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + FlushCommand info = new FlushCommand(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - FlushCommand info = (FlushCommand)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + FlushCommand info = (FlushCommand) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/IntegerResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/IntegerResponseTest.java index fb33c720e4..b082093508 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/IntegerResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/IntegerResponseTest.java @@ -20,28 +20,26 @@ import org.apache.activemq.command.IntegerResponse; /** * Test case for the OpenWire marshalling for IntegerResponse - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class IntegerResponseTest extends ResponseTest { - public static final IntegerResponseTest SINGLETON = new IntegerResponseTest(); + public static final IntegerResponseTest SINGLETON = new IntegerResponseTest(); - public Object createObject() throws Exception { - IntegerResponse info = new IntegerResponse(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + IntegerResponse info = new IntegerResponse(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - IntegerResponse info = (IntegerResponse)object; - info.setResult(1); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + IntegerResponse info = (IntegerResponse) object; + info.setResult(1); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/JournalQueueAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/JournalQueueAckTest.java index 47ace83e45..54eff67609 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/JournalQueueAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/JournalQueueAckTest.java @@ -21,29 +21,27 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for JournalQueueAck - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class JournalQueueAckTest extends DataFileGeneratorTestSupport { - public static final JournalQueueAckTest SINGLETON = new JournalQueueAckTest(); + public static final JournalQueueAckTest SINGLETON = new JournalQueueAckTest(); - public Object createObject() throws Exception { - JournalQueueAck info = new JournalQueueAck(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + JournalQueueAck info = new JournalQueueAck(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalQueueAck info = (JournalQueueAck)object; - info.setDestination(createActiveMQDestination("Destination:1")); - info.setMessageAck(createMessageAck("MessageAck:2")); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + JournalQueueAck info = (JournalQueueAck) object; + info.setDestination(createActiveMQDestination("Destination:1")); + info.setMessageAck(createMessageAck("MessageAck:2")); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/JournalTopicAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/JournalTopicAckTest.java index d74528b1ea..863ef030e5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/JournalTopicAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/JournalTopicAckTest.java @@ -21,33 +21,31 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for JournalTopicAck - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class JournalTopicAckTest extends DataFileGeneratorTestSupport { - public static final JournalTopicAckTest SINGLETON = new JournalTopicAckTest(); + public static final JournalTopicAckTest SINGLETON = new JournalTopicAckTest(); - public Object createObject() throws Exception { - JournalTopicAck info = new JournalTopicAck(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + JournalTopicAck info = new JournalTopicAck(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalTopicAck info = (JournalTopicAck)object; - info.setDestination(createActiveMQDestination("Destination:1")); - info.setMessageId(createMessageId("MessageId:2")); - info.setMessageSequenceId(1); - info.setSubscritionName("SubscritionName:3"); - info.setClientId("ClientId:4"); - info.setTransactionId(createTransactionId("TransactionId:5")); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + JournalTopicAck info = (JournalTopicAck) object; + info.setDestination(createActiveMQDestination("Destination:1")); + info.setMessageId(createMessageId("MessageId:2")); + info.setMessageSequenceId(1); + info.setSubscritionName("SubscritionName:3"); + info.setClientId("ClientId:4"); + info.setTransactionId(createTransactionId("TransactionId:5")); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/JournalTraceTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/JournalTraceTest.java index aad70601ff..cbcc549636 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/JournalTraceTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/JournalTraceTest.java @@ -21,28 +21,26 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for JournalTrace - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class JournalTraceTest extends DataFileGeneratorTestSupport { - public static final JournalTraceTest SINGLETON = new JournalTraceTest(); + public static final JournalTraceTest SINGLETON = new JournalTraceTest(); - public Object createObject() throws Exception { - JournalTrace info = new JournalTrace(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + JournalTrace info = new JournalTrace(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalTrace info = (JournalTrace)object; - info.setMessage("Message:1"); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + JournalTrace info = (JournalTrace) object; + info.setMessage("Message:1"); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/JournalTransactionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/JournalTransactionTest.java index 6e7008e96b..c76ba646f0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/JournalTransactionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/JournalTransactionTest.java @@ -21,30 +21,28 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for JournalTransaction - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class JournalTransactionTest extends DataFileGeneratorTestSupport { - public static final JournalTransactionTest SINGLETON = new JournalTransactionTest(); + public static final JournalTransactionTest SINGLETON = new JournalTransactionTest(); - public Object createObject() throws Exception { - JournalTransaction info = new JournalTransaction(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + JournalTransaction info = new JournalTransaction(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalTransaction info = (JournalTransaction)object; - info.setTransactionId(createTransactionId("TransactionId:1")); - info.setType((byte)1); - info.setWasPrepared(true); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + JournalTransaction info = (JournalTransaction) object; + info.setTransactionId(createTransactionId("TransactionId:1")); + info.setType((byte) 1); + info.setWasPrepared(true); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/KeepAliveInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/KeepAliveInfoTest.java index 4a880bf2d8..316dd34302 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/KeepAliveInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/KeepAliveInfoTest.java @@ -20,27 +20,25 @@ import org.apache.activemq.command.KeepAliveInfo; /** * Test case for the OpenWire marshalling for KeepAliveInfo - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class KeepAliveInfoTest extends BaseCommandTestSupport { - public static final KeepAliveInfoTest SINGLETON = new KeepAliveInfoTest(); + public static final KeepAliveInfoTest SINGLETON = new KeepAliveInfoTest(); - public Object createObject() throws Exception { - KeepAliveInfo info = new KeepAliveInfo(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + KeepAliveInfo info = new KeepAliveInfo(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - KeepAliveInfo info = (KeepAliveInfo)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + KeepAliveInfo info = (KeepAliveInfo) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/LastPartialCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/LastPartialCommandTest.java index c992ad4b54..39c447c26a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/LastPartialCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/LastPartialCommandTest.java @@ -20,27 +20,25 @@ import org.apache.activemq.command.LastPartialCommand; /** * Test case for the OpenWire marshalling for LastPartialCommand - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class LastPartialCommandTest extends PartialCommandTest { - public static final LastPartialCommandTest SINGLETON = new LastPartialCommandTest(); + public static final LastPartialCommandTest SINGLETON = new LastPartialCommandTest(); - public Object createObject() throws Exception { - LastPartialCommand info = new LastPartialCommand(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + LastPartialCommand info = new LastPartialCommand(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - LastPartialCommand info = (LastPartialCommand)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + LastPartialCommand info = (LastPartialCommand) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/LocalTransactionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/LocalTransactionIdTest.java index 2275a30e2e..c7d33e2d38 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/LocalTransactionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/LocalTransactionIdTest.java @@ -20,29 +20,27 @@ import org.apache.activemq.command.LocalTransactionId; /** * Test case for the OpenWire marshalling for LocalTransactionId - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class LocalTransactionIdTest extends TransactionIdTestSupport { - public static final LocalTransactionIdTest SINGLETON = new LocalTransactionIdTest(); + public static final LocalTransactionIdTest SINGLETON = new LocalTransactionIdTest(); - public Object createObject() throws Exception { - LocalTransactionId info = new LocalTransactionId(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + LocalTransactionId info = new LocalTransactionId(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - LocalTransactionId info = (LocalTransactionId)object; - info.setValue(1); - info.setConnectionId(createConnectionId("ConnectionId:1")); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + LocalTransactionId info = (LocalTransactionId) object; + info.setValue(1); + info.setConnectionId(createConnectionId("ConnectionId:1")); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/MessageAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/MessageAckTest.java index 1a055dad37..375f2cefef 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/MessageAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/MessageAckTest.java @@ -20,34 +20,32 @@ import org.apache.activemq.command.MessageAck; /** * Test case for the OpenWire marshalling for MessageAck - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class MessageAckTest extends BaseCommandTestSupport { - public static final MessageAckTest SINGLETON = new MessageAckTest(); + public static final MessageAckTest SINGLETON = new MessageAckTest(); - public Object createObject() throws Exception { - MessageAck info = new MessageAck(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + MessageAck info = new MessageAck(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageAck info = (MessageAck)object; - info.setDestination(createActiveMQDestination("Destination:1")); - info.setTransactionId(createTransactionId("TransactionId:2")); - info.setConsumerId(createConsumerId("ConsumerId:3")); - info.setAckType((byte)1); - info.setFirstMessageId(createMessageId("FirstMessageId:4")); - info.setLastMessageId(createMessageId("LastMessageId:5")); - info.setMessageCount(1); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessageAck info = (MessageAck) object; + info.setDestination(createActiveMQDestination("Destination:1")); + info.setTransactionId(createTransactionId("TransactionId:2")); + info.setConsumerId(createConsumerId("ConsumerId:3")); + info.setAckType((byte) 1); + info.setFirstMessageId(createMessageId("FirstMessageId:4")); + info.setLastMessageId(createMessageId("LastMessageId:5")); + info.setMessageCount(1); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/MessageDispatchNotificationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/MessageDispatchNotificationTest.java index 94589e554c..a7103df1d8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/MessageDispatchNotificationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/MessageDispatchNotificationTest.java @@ -20,31 +20,29 @@ import org.apache.activemq.command.MessageDispatchNotification; /** * Test case for the OpenWire marshalling for MessageDispatchNotification - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class MessageDispatchNotificationTest extends BaseCommandTestSupport { - public static final MessageDispatchNotificationTest SINGLETON = new MessageDispatchNotificationTest(); + public static final MessageDispatchNotificationTest SINGLETON = new MessageDispatchNotificationTest(); - public Object createObject() throws Exception { - MessageDispatchNotification info = new MessageDispatchNotification(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + MessageDispatchNotification info = new MessageDispatchNotification(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageDispatchNotification info = (MessageDispatchNotification)object; - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setDeliverySequenceId(1); - info.setMessageId(createMessageId("MessageId:3")); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessageDispatchNotification info = (MessageDispatchNotification) object; + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setDeliverySequenceId(1); + info.setMessageId(createMessageId("MessageId:3")); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/MessageDispatchTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/MessageDispatchTest.java index f7ffda674a..31a2514fe3 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/MessageDispatchTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/MessageDispatchTest.java @@ -20,31 +20,29 @@ import org.apache.activemq.command.MessageDispatch; /** * Test case for the OpenWire marshalling for MessageDispatch - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class MessageDispatchTest extends BaseCommandTestSupport { - public static final MessageDispatchTest SINGLETON = new MessageDispatchTest(); + public static final MessageDispatchTest SINGLETON = new MessageDispatchTest(); - public Object createObject() throws Exception { - MessageDispatch info = new MessageDispatch(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + MessageDispatch info = new MessageDispatch(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageDispatch info = (MessageDispatch)object; - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setMessage(createMessage("Message:3")); - info.setRedeliveryCounter(1); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessageDispatch info = (MessageDispatch) object; + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setMessage(createMessage("Message:3")); + info.setRedeliveryCounter(1); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/MessageIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/MessageIdTest.java index 4f3b4f6816..b65de9364a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/MessageIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/MessageIdTest.java @@ -21,30 +21,28 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for MessageId - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class MessageIdTest extends DataFileGeneratorTestSupport { - public static final MessageIdTest SINGLETON = new MessageIdTest(); + public static final MessageIdTest SINGLETON = new MessageIdTest(); - public Object createObject() throws Exception { - MessageId info = new MessageId(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + MessageId info = new MessageId(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageId info = (MessageId)object; - info.setProducerId(createProducerId("ProducerId:1")); - info.setProducerSequenceId(1); - info.setBrokerSequenceId(2); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessageId info = (MessageId) object; + info.setProducerId(createProducerId("ProducerId:1")); + info.setProducerSequenceId(1); + info.setBrokerSequenceId(2); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/MessageTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/MessageTestSupport.java index 037375cbb4..1d067bad8e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/MessageTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/MessageTestSupport.java @@ -30,63 +30,61 @@ import org.apache.activemq.util.MarshallingSupport; * generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public abstract class MessageTestSupport extends BaseCommandTestSupport { - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - Message info = (Message)object; - info.setProducerId(createProducerId("ProducerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setTransactionId(createTransactionId("TransactionId:3")); - info.setOriginalDestination(createActiveMQDestination("OriginalDestination:4")); - info.setMessageId(createMessageId("MessageId:5")); - info.setOriginalTransactionId(createTransactionId("OriginalTransactionId:6")); - info.setGroupID("GroupID:7"); - info.setGroupSequence(1); - info.setCorrelationId("CorrelationId:8"); - info.setPersistent(true); - info.setExpiration(1); - info.setPriority((byte)1); - info.setReplyTo(createActiveMQDestination("ReplyTo:9")); - info.setTimestamp(2); - info.setType("Type:10"); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + Message info = (Message) object; + info.setProducerId(createProducerId("ProducerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setTransactionId(createTransactionId("TransactionId:3")); + info.setOriginalDestination(createActiveMQDestination("OriginalDestination:4")); + info.setMessageId(createMessageId("MessageId:5")); + info.setOriginalTransactionId(createTransactionId("OriginalTransactionId:6")); + info.setGroupID("GroupID:7"); + info.setGroupSequence(1); + info.setCorrelationId("CorrelationId:8"); + info.setPersistent(true); + info.setExpiration(1); + info.setPriority((byte) 1); + info.setReplyTo(createActiveMQDestination("ReplyTo:9")); + info.setTimestamp(2); + info.setType("Type:10"); - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream dataOut = new DataOutputStream(baos); - MarshallingSupport.writeUTF8(dataOut, "Content:11"); - dataOut.close(); - info.setContent(baos.toByteSequence()); - } + { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dataOut = new DataOutputStream(baos); + MarshallingSupport.writeUTF8(dataOut, "Content:11"); + dataOut.close(); + info.setContent(baos.toByteSequence()); + } - { - Map map = new HashMap(); - map.put("MarshalledProperties", 12); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream os = new DataOutputStream(baos); - MarshallingSupport.marshalPrimitiveMap(map, os); - os.close(); - info.setMarshalledProperties(baos.toByteSequence()); - } + { + Map map = new HashMap(); + map.put("MarshalledProperties", 12); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream os = new DataOutputStream(baos); + MarshallingSupport.marshalPrimitiveMap(map, os); + os.close(); + info.setMarshalledProperties(baos.toByteSequence()); + } - info.setDataStructure(createDataStructure("DataStructure:13")); - info.setTargetConsumerId(createConsumerId("TargetConsumerId:14")); - info.setCompressed(false); - info.setRedeliveryCounter(2); + info.setDataStructure(createDataStructure("DataStructure:13")); + info.setTargetConsumerId(createConsumerId("TargetConsumerId:14")); + info.setCompressed(false); + info.setRedeliveryCounter(2); - { - BrokerId value[] = new BrokerId[2]; - for (int i = 0; i < 2; i++) { - value[i] = createBrokerId("BrokerPath:15"); - } - info.setBrokerPath(value); - } - info.setArrival(3); - info.setUserID("UserID:16"); - info.setRecievedByDFBridge(true); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:15"); + } + info.setBrokerPath(value); + } + info.setArrival(3); + info.setUserID("UserID:16"); + info.setRecievedByDFBridge(true); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/NetworkBridgeFilterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/NetworkBridgeFilterTest.java index 068af0b2ef..836982cf52 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/NetworkBridgeFilterTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/NetworkBridgeFilterTest.java @@ -21,29 +21,27 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for NetworkBridgeFilter - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class NetworkBridgeFilterTest extends DataFileGeneratorTestSupport { - public static final NetworkBridgeFilterTest SINGLETON = new NetworkBridgeFilterTest(); + public static final NetworkBridgeFilterTest SINGLETON = new NetworkBridgeFilterTest(); - public Object createObject() throws Exception { - NetworkBridgeFilter info = new NetworkBridgeFilter(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + NetworkBridgeFilter info = new NetworkBridgeFilter(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - NetworkBridgeFilter info = (NetworkBridgeFilter)object; - info.setNetworkTTL(1); - info.setNetworkBrokerId(createBrokerId("NetworkBrokerId:1")); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + NetworkBridgeFilter info = (NetworkBridgeFilter) object; + info.setNetworkTTL(1); + info.setNetworkBrokerId(createBrokerId("NetworkBrokerId:1")); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/PartialCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/PartialCommandTest.java index bdbe27d2a9..74bf73f2b7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/PartialCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/PartialCommandTest.java @@ -21,29 +21,27 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for PartialCommand - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class PartialCommandTest extends DataFileGeneratorTestSupport { - public static final PartialCommandTest SINGLETON = new PartialCommandTest(); + public static final PartialCommandTest SINGLETON = new PartialCommandTest(); - public Object createObject() throws Exception { - PartialCommand info = new PartialCommand(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + PartialCommand info = new PartialCommand(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - PartialCommand info = (PartialCommand)object; - info.setCommandId(1); - info.setData("Data:1".getBytes()); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + PartialCommand info = (PartialCommand) object; + info.setCommandId(1); + info.setData("Data:1".getBytes()); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ProducerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ProducerIdTest.java index d67dbaf375..0269b1ac61 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ProducerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ProducerIdTest.java @@ -21,30 +21,28 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for ProducerId - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class ProducerIdTest extends DataFileGeneratorTestSupport { - public static final ProducerIdTest SINGLETON = new ProducerIdTest(); + public static final ProducerIdTest SINGLETON = new ProducerIdTest(); - public Object createObject() throws Exception { - ProducerId info = new ProducerId(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ProducerId info = new ProducerId(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ProducerId info = (ProducerId)object; - info.setConnectionId("ConnectionId:1"); - info.setValue(1); - info.setSessionId(2); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ProducerId info = (ProducerId) object; + info.setConnectionId("ConnectionId:1"); + info.setValue(1); + info.setSessionId(2); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ProducerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ProducerInfoTest.java index 8d8b5b8159..40b6dccf41 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ProducerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ProducerInfoTest.java @@ -24,32 +24,30 @@ import org.apache.activemq.command.ProducerInfo; * auto generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public class ProducerInfoTest extends BaseCommandTestSupport { - public static final ProducerInfoTest SINGLETON = new ProducerInfoTest(); + public static final ProducerInfoTest SINGLETON = new ProducerInfoTest(); - public Object createObject() throws Exception { - ProducerInfo info = new ProducerInfo(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ProducerInfo info = new ProducerInfo(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ProducerInfo info = (ProducerInfo)object; - info.setProducerId(createProducerId("ProducerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ProducerInfo info = (ProducerInfo) object; + info.setProducerId(createProducerId("ProducerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); - { - BrokerId value[] = new BrokerId[2]; - for (int i = 0; i < 2; i++) { - value[i] = createBrokerId("BrokerPath:3"); - } - info.setBrokerPath(value); - } + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:3"); + } + info.setBrokerPath(value); + } - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/RemoveInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/RemoveInfoTest.java index 3d09942ed2..fa9ac7983b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/RemoveInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/RemoveInfoTest.java @@ -20,28 +20,26 @@ import org.apache.activemq.command.RemoveInfo; /** * Test case for the OpenWire marshalling for RemoveInfo - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class RemoveInfoTest extends BaseCommandTestSupport { - public static final RemoveInfoTest SINGLETON = new RemoveInfoTest(); + public static final RemoveInfoTest SINGLETON = new RemoveInfoTest(); - public Object createObject() throws Exception { - RemoveInfo info = new RemoveInfo(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + RemoveInfo info = new RemoveInfo(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - RemoveInfo info = (RemoveInfo)object; - info.setObjectId(createDataStructure("ObjectId:1")); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + RemoveInfo info = (RemoveInfo) object; + info.setObjectId(createDataStructure("ObjectId:1")); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/RemoveSubscriptionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/RemoveSubscriptionInfoTest.java index 32697dda92..965218dd19 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/RemoveSubscriptionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/RemoveSubscriptionInfoTest.java @@ -20,30 +20,28 @@ import org.apache.activemq.command.RemoveSubscriptionInfo; /** * Test case for the OpenWire marshalling for RemoveSubscriptionInfo - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class RemoveSubscriptionInfoTest extends BaseCommandTestSupport { - public static final RemoveSubscriptionInfoTest SINGLETON = new RemoveSubscriptionInfoTest(); + public static final RemoveSubscriptionInfoTest SINGLETON = new RemoveSubscriptionInfoTest(); - public Object createObject() throws Exception { - RemoveSubscriptionInfo info = new RemoveSubscriptionInfo(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + RemoveSubscriptionInfo info = new RemoveSubscriptionInfo(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - RemoveSubscriptionInfo info = (RemoveSubscriptionInfo)object; - info.setConnectionId(createConnectionId("ConnectionId:1")); - info.setSubscriptionName("SubcriptionName:2"); - info.setClientId("ClientId:3"); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + RemoveSubscriptionInfo info = (RemoveSubscriptionInfo) object; + info.setConnectionId(createConnectionId("ConnectionId:1")); + info.setSubscriptionName("SubcriptionName:2"); + info.setClientId("ClientId:3"); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ReplayCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ReplayCommandTest.java index d9decb4641..1281161a24 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ReplayCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ReplayCommandTest.java @@ -20,29 +20,27 @@ import org.apache.activemq.command.ReplayCommand; /** * Test case for the OpenWire marshalling for ReplayCommand - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class ReplayCommandTest extends BaseCommandTestSupport { - public static final ReplayCommandTest SINGLETON = new ReplayCommandTest(); + public static final ReplayCommandTest SINGLETON = new ReplayCommandTest(); - public Object createObject() throws Exception { - ReplayCommand info = new ReplayCommand(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ReplayCommand info = new ReplayCommand(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ReplayCommand info = (ReplayCommand)object; - info.setFirstNakNumber(1); - info.setLastNakNumber(2); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ReplayCommand info = (ReplayCommand) object; + info.setFirstNakNumber(1); + info.setLastNakNumber(2); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ResponseTest.java index 80c6fa4f5f..3834c29c13 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ResponseTest.java @@ -20,28 +20,26 @@ import org.apache.activemq.command.Response; /** * Test case for the OpenWire marshalling for Response - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class ResponseTest extends BaseCommandTestSupport { - public static final ResponseTest SINGLETON = new ResponseTest(); + public static final ResponseTest SINGLETON = new ResponseTest(); - public Object createObject() throws Exception { - Response info = new Response(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + Response info = new Response(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - Response info = (Response)object; - info.setCorrelationId(1); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + Response info = (Response) object; + info.setCorrelationId(1); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/SessionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/SessionIdTest.java index a928a4b09b..404beddbc1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/SessionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/SessionIdTest.java @@ -21,29 +21,27 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for SessionId - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class SessionIdTest extends DataFileGeneratorTestSupport { - public static final SessionIdTest SINGLETON = new SessionIdTest(); + public static final SessionIdTest SINGLETON = new SessionIdTest(); - public Object createObject() throws Exception { - SessionId info = new SessionId(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + SessionId info = new SessionId(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - SessionId info = (SessionId)object; - info.setConnectionId("ConnectionId:1"); - info.setValue(1); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + SessionId info = (SessionId) object; + info.setConnectionId("ConnectionId:1"); + info.setValue(1); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/SessionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/SessionInfoTest.java index 8dc1bb0cbe..16289a2cc7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/SessionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/SessionInfoTest.java @@ -20,28 +20,26 @@ import org.apache.activemq.command.SessionInfo; /** * Test case for the OpenWire marshalling for SessionInfo - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class SessionInfoTest extends BaseCommandTestSupport { - public static final SessionInfoTest SINGLETON = new SessionInfoTest(); + public static final SessionInfoTest SINGLETON = new SessionInfoTest(); - public Object createObject() throws Exception { - SessionInfo info = new SessionInfo(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + SessionInfo info = new SessionInfo(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - SessionInfo info = (SessionInfo)object; - info.setSessionId(createSessionId("SessionId:1")); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + SessionInfo info = (SessionInfo) object; + info.setSessionId(createSessionId("SessionId:1")); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ShutdownInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ShutdownInfoTest.java index ee8dc4da38..ae1f45305a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ShutdownInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/ShutdownInfoTest.java @@ -20,27 +20,25 @@ import org.apache.activemq.command.ShutdownInfo; /** * Test case for the OpenWire marshalling for ShutdownInfo - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class ShutdownInfoTest extends BaseCommandTestSupport { - public static final ShutdownInfoTest SINGLETON = new ShutdownInfoTest(); + public static final ShutdownInfoTest SINGLETON = new ShutdownInfoTest(); - public Object createObject() throws Exception { - ShutdownInfo info = new ShutdownInfo(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ShutdownInfo info = new ShutdownInfo(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ShutdownInfo info = (ShutdownInfo)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ShutdownInfo info = (ShutdownInfo) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/SubscriptionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/SubscriptionInfoTest.java index 5eae49607a..1c77629c6b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/SubscriptionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/SubscriptionInfoTest.java @@ -21,31 +21,29 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for SubscriptionInfo - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class SubscriptionInfoTest extends DataFileGeneratorTestSupport { - public static final SubscriptionInfoTest SINGLETON = new SubscriptionInfoTest(); + public static final SubscriptionInfoTest SINGLETON = new SubscriptionInfoTest(); - public Object createObject() throws Exception { - SubscriptionInfo info = new SubscriptionInfo(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + SubscriptionInfo info = new SubscriptionInfo(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - SubscriptionInfo info = (SubscriptionInfo)object; - info.setClientId("ClientId:1"); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setSelector("Selector:3"); - info.setSubscriptionName("SubcriptionName:4"); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + SubscriptionInfo info = (SubscriptionInfo) object; + info.setClientId("ClientId:1"); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setSelector("Selector:3"); + info.setSubscriptionName("SubcriptionName:4"); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/TransactionIdTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/TransactionIdTestSupport.java index 8c77aa938f..3d63fcf5d6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/TransactionIdTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/TransactionIdTestSupport.java @@ -21,19 +21,17 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for TransactionId - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public abstract class TransactionIdTestSupport extends DataFileGeneratorTestSupport { - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - TransactionId info = (TransactionId)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + TransactionId info = (TransactionId) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/TransactionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/TransactionInfoTest.java index a5e558b8fd..f9d796374c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/TransactionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/TransactionInfoTest.java @@ -20,30 +20,28 @@ import org.apache.activemq.command.TransactionInfo; /** * Test case for the OpenWire marshalling for TransactionInfo - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class TransactionInfoTest extends BaseCommandTestSupport { - public static final TransactionInfoTest SINGLETON = new TransactionInfoTest(); + public static final TransactionInfoTest SINGLETON = new TransactionInfoTest(); - public Object createObject() throws Exception { - TransactionInfo info = new TransactionInfo(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + TransactionInfo info = new TransactionInfo(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - TransactionInfo info = (TransactionInfo)object; - info.setConnectionId(createConnectionId("ConnectionId:1")); - info.setTransactionId(createTransactionId("TransactionId:2")); - info.setType((byte)1); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + TransactionInfo info = (TransactionInfo) object; + info.setConnectionId(createConnectionId("ConnectionId:1")); + info.setTransactionId(createTransactionId("TransactionId:2")); + info.setType((byte) 1); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/WireFormatInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/WireFormatInfoTest.java index 5298b99663..8279feb880 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/WireFormatInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/WireFormatInfoTest.java @@ -24,28 +24,26 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; * auto generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public class WireFormatInfoTest extends DataFileGeneratorTestSupport { - public static final WireFormatInfoTest SINGLETON = new WireFormatInfoTest(); + public static final WireFormatInfoTest SINGLETON = new WireFormatInfoTest(); - public Object createObject() throws Exception { - WireFormatInfo info = new WireFormatInfo(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + WireFormatInfo info = new WireFormatInfo(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - WireFormatInfo info = (WireFormatInfo)object; - info.setVersion(1); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + WireFormatInfo info = (WireFormatInfo) object; + info.setVersion(1); - { - byte data[] = "MarshalledProperties:1".getBytes(); - info.setMarshalledProperties(new org.apache.activemq.util.ByteSequence(data, 0, data.length)); - } + { + byte data[] = "MarshalledProperties:1".getBytes(); + info.setMarshalledProperties(new org.apache.activemq.util.ByteSequence(data, 0, data.length)); + } - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/XATransactionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/XATransactionIdTest.java index 013c9864a9..4e4056d19f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/XATransactionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v1/XATransactionIdTest.java @@ -20,30 +20,28 @@ import org.apache.activemq.command.XATransactionId; /** * Test case for the OpenWire marshalling for XATransactionId - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class XATransactionIdTest extends TransactionIdTestSupport { - public static final XATransactionIdTest SINGLETON = new XATransactionIdTest(); + public static final XATransactionIdTest SINGLETON = new XATransactionIdTest(); - public Object createObject() throws Exception { - XATransactionId info = new XATransactionId(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + XATransactionId info = new XATransactionId(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - XATransactionId info = (XATransactionId)object; - info.setFormatId(1); - info.setGlobalTransactionId("GlobalTransactionId:1".getBytes()); - info.setBranchQualifier("BranchQualifier:2".getBytes()); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + XATransactionId info = (XATransactionId) object; + info.setFormatId(1); + info.setGlobalTransactionId("GlobalTransactionId:1".getBytes()); + info.setBranchQualifier("BranchQualifier:2".getBytes()); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQBytesMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQBytesMessageTest.java index 458821964c..16b61e5929 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQBytesMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQBytesMessageTest.java @@ -20,27 +20,25 @@ import org.apache.activemq.command.ActiveMQBytesMessage; /** * Test case for the OpenWire marshalling for ActiveMQBytesMessage - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class ActiveMQBytesMessageTest extends ActiveMQMessageTest { - public static final ActiveMQBytesMessageTest SINGLETON = new ActiveMQBytesMessageTest(); + public static final ActiveMQBytesMessageTest SINGLETON = new ActiveMQBytesMessageTest(); - public Object createObject() throws Exception { - ActiveMQBytesMessage info = new ActiveMQBytesMessage(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ActiveMQBytesMessage info = new ActiveMQBytesMessage(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQBytesMessage info = (ActiveMQBytesMessage)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ActiveMQBytesMessage info = (ActiveMQBytesMessage) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQDestinationTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQDestinationTestSupport.java index f582368e03..08c3b55031 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQDestinationTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQDestinationTestSupport.java @@ -21,20 +21,18 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for ActiveMQDestination - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public abstract class ActiveMQDestinationTestSupport extends DataFileGeneratorTestSupport { - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQDestination info = (ActiveMQDestination)object; - info.setPhysicalName("PhysicalName:1"); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ActiveMQDestination info = (ActiveMQDestination) object; + info.setPhysicalName("PhysicalName:1"); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQMapMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQMapMessageTest.java index 45e531afaa..c9a7fe2fe9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQMapMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQMapMessageTest.java @@ -20,26 +20,24 @@ import org.apache.activemq.command.ActiveMQMapMessage; /** * Test case for the OpenWire marshalling for ActiveMQMapMessage - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class ActiveMQMapMessageTest extends ActiveMQMessageTest { - public static final ActiveMQMapMessageTest SINGLETON = new ActiveMQMapMessageTest(); + public static final ActiveMQMapMessageTest SINGLETON = new ActiveMQMapMessageTest(); - public Object createObject() throws Exception { - ActiveMQMapMessage info = new ActiveMQMapMessage(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ActiveMQMapMessage info = new ActiveMQMapMessage(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQMapMessage info = (ActiveMQMapMessage)object; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ActiveMQMapMessage info = (ActiveMQMapMessage) object; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQMessageTest.java index eb1d050f25..8e8ccb81fa 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQMessageTest.java @@ -20,27 +20,25 @@ import org.apache.activemq.command.ActiveMQMessage; /** * Test case for the OpenWire marshalling for ActiveMQMessage - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class ActiveMQMessageTest extends MessageTestSupport { - public static final ActiveMQMessageTest SINGLETON = new ActiveMQMessageTest(); + public static final ActiveMQMessageTest SINGLETON = new ActiveMQMessageTest(); - public Object createObject() throws Exception { - ActiveMQMessage info = new ActiveMQMessage(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ActiveMQMessage info = new ActiveMQMessage(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQMessage info = (ActiveMQMessage)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ActiveMQMessage info = (ActiveMQMessage) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQObjectMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQObjectMessageTest.java index ddb9b1b312..70c9c2a891 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQObjectMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQObjectMessageTest.java @@ -20,27 +20,25 @@ import org.apache.activemq.command.ActiveMQObjectMessage; /** * Test case for the OpenWire marshalling for ActiveMQObjectMessage - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class ActiveMQObjectMessageTest extends ActiveMQMessageTest { - public static final ActiveMQObjectMessageTest SINGLETON = new ActiveMQObjectMessageTest(); + public static final ActiveMQObjectMessageTest SINGLETON = new ActiveMQObjectMessageTest(); - public Object createObject() throws Exception { - ActiveMQObjectMessage info = new ActiveMQObjectMessage(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ActiveMQObjectMessage info = new ActiveMQObjectMessage(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQObjectMessage info = (ActiveMQObjectMessage)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ActiveMQObjectMessage info = (ActiveMQObjectMessage) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQQueueTest.java index 453f702cad..5dbd63454d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQQueueTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQQueueTest.java @@ -20,27 +20,25 @@ import org.apache.activemq.command.ActiveMQQueue; /** * Test case for the OpenWire marshalling for ActiveMQQueue - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class ActiveMQQueueTest extends ActiveMQDestinationTestSupport { - public static final ActiveMQQueueTest SINGLETON = new ActiveMQQueueTest(); + public static final ActiveMQQueueTest SINGLETON = new ActiveMQQueueTest(); - public Object createObject() throws Exception { - ActiveMQQueue info = new ActiveMQQueue(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ActiveMQQueue info = new ActiveMQQueue(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQQueue info = (ActiveMQQueue)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ActiveMQQueue info = (ActiveMQQueue) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQStreamMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQStreamMessageTest.java index 21ccc88139..0c62a79b33 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQStreamMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQStreamMessageTest.java @@ -20,27 +20,25 @@ import org.apache.activemq.command.ActiveMQStreamMessage; /** * Test case for the OpenWire marshalling for ActiveMQStreamMessage - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class ActiveMQStreamMessageTest extends ActiveMQMessageTest { - public static final ActiveMQStreamMessageTest SINGLETON = new ActiveMQStreamMessageTest(); + public static final ActiveMQStreamMessageTest SINGLETON = new ActiveMQStreamMessageTest(); - public Object createObject() throws Exception { - ActiveMQStreamMessage info = new ActiveMQStreamMessage(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ActiveMQStreamMessage info = new ActiveMQStreamMessage(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQStreamMessage info = (ActiveMQStreamMessage)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ActiveMQStreamMessage info = (ActiveMQStreamMessage) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTempDestinationTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTempDestinationTestSupport.java index db609bfa2c..7b4aa1980d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTempDestinationTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTempDestinationTestSupport.java @@ -20,19 +20,17 @@ import org.apache.activemq.command.ActiveMQTempDestination; /** * Test case for the OpenWire marshalling for ActiveMQTempDestination - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public abstract class ActiveMQTempDestinationTestSupport extends ActiveMQDestinationTestSupport { - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQTempDestination info = (ActiveMQTempDestination)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ActiveMQTempDestination info = (ActiveMQTempDestination) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTempQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTempQueueTest.java index 817996f732..c9733fdbe3 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTempQueueTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTempQueueTest.java @@ -20,27 +20,25 @@ import org.apache.activemq.command.ActiveMQTempQueue; /** * Test case for the OpenWire marshalling for ActiveMQTempQueue - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class ActiveMQTempQueueTest extends ActiveMQTempDestinationTestSupport { - public static final ActiveMQTempQueueTest SINGLETON = new ActiveMQTempQueueTest(); + public static final ActiveMQTempQueueTest SINGLETON = new ActiveMQTempQueueTest(); - public Object createObject() throws Exception { - ActiveMQTempQueue info = new ActiveMQTempQueue(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ActiveMQTempQueue info = new ActiveMQTempQueue(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQTempQueue info = (ActiveMQTempQueue)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ActiveMQTempQueue info = (ActiveMQTempQueue) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTempTopicTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTempTopicTest.java index b940fc50a0..2dc535747f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTempTopicTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTempTopicTest.java @@ -20,27 +20,25 @@ import org.apache.activemq.command.ActiveMQTempTopic; /** * Test case for the OpenWire marshalling for ActiveMQTempTopic - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class ActiveMQTempTopicTest extends ActiveMQTempDestinationTestSupport { - public static final ActiveMQTempTopicTest SINGLETON = new ActiveMQTempTopicTest(); + public static final ActiveMQTempTopicTest SINGLETON = new ActiveMQTempTopicTest(); - public Object createObject() throws Exception { - ActiveMQTempTopic info = new ActiveMQTempTopic(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ActiveMQTempTopic info = new ActiveMQTempTopic(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQTempTopic info = (ActiveMQTempTopic)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ActiveMQTempTopic info = (ActiveMQTempTopic) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTextMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTextMessageTest.java index 0c7b7427f2..36975897b2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTextMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTextMessageTest.java @@ -20,27 +20,25 @@ import org.apache.activemq.command.ActiveMQTextMessage; /** * Test case for the OpenWire marshalling for ActiveMQTextMessage - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class ActiveMQTextMessageTest extends ActiveMQMessageTest { - public static final ActiveMQTextMessageTest SINGLETON = new ActiveMQTextMessageTest(); + public static final ActiveMQTextMessageTest SINGLETON = new ActiveMQTextMessageTest(); - public Object createObject() throws Exception { - ActiveMQTextMessage info = new ActiveMQTextMessage(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ActiveMQTextMessage info = new ActiveMQTextMessage(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQTextMessage info = (ActiveMQTextMessage)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ActiveMQTextMessage info = (ActiveMQTextMessage) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTopicTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTopicTest.java index ac3e9a1e31..48e0c5c91e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTopicTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTopicTest.java @@ -20,27 +20,25 @@ import org.apache.activemq.command.ActiveMQTopic; /** * Test case for the OpenWire marshalling for ActiveMQTopic - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public class ActiveMQTopicTest extends ActiveMQDestinationTestSupport { - public static final ActiveMQTopicTest SINGLETON = new ActiveMQTopicTest(); + public static final ActiveMQTopicTest SINGLETON = new ActiveMQTopicTest(); - public Object createObject() throws Exception { - ActiveMQTopic info = new ActiveMQTopic(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ActiveMQTopic info = new ActiveMQTopic(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQTopic info = (ActiveMQTopic)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ActiveMQTopic info = (ActiveMQTopic) object; - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/BaseCommandTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/BaseCommandTestSupport.java index 5aebc4f854..43bb7f89d2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/BaseCommandTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/BaseCommandTestSupport.java @@ -24,16 +24,14 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; * auto generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public abstract class BaseCommandTestSupport extends DataFileGeneratorTestSupport { - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - BaseCommand info = (BaseCommand)object; - info.setCommandId(1); - info.setResponseRequired(true); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + BaseCommand info = (BaseCommand) object; + info.setCommandId(1); + info.setResponseRequired(true); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/BrokerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/BrokerIdTest.java index 3ecb39e871..8960410714 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/BrokerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/BrokerIdTest.java @@ -19,33 +19,29 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.BrokerId; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for BrokerId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class BrokerIdTest extends DataFileGeneratorTestSupport { + public static final BrokerIdTest SINGLETON = new BrokerIdTest(); - public static final BrokerIdTest SINGLETON = new BrokerIdTest(); + public Object createObject() throws Exception { + BrokerId info = new BrokerId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - BrokerId info = new BrokerId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + BrokerId info = (BrokerId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - BrokerId info = (BrokerId) object; - - info.setValue("Value:1"); - } + info.setValue("Value:1"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/BrokerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/BrokerInfoTest.java index 5db97830f3..252010c6cf 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/BrokerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/BrokerInfoTest.java @@ -23,38 +23,36 @@ import org.apache.activemq.command.BrokerInfo; * auto generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public class BrokerInfoTest extends BaseCommandTestSupport { - public static final BrokerInfoTest SINGLETON = new BrokerInfoTest(); + public static final BrokerInfoTest SINGLETON = new BrokerInfoTest(); - public Object createObject() throws Exception { - BrokerInfo info = new BrokerInfo(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + BrokerInfo info = new BrokerInfo(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - BrokerInfo info = (BrokerInfo)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + BrokerInfo info = (BrokerInfo) object; - info.setBrokerId(createBrokerId("BrokerId:1")); - info.setBrokerURL("BrokerURL:2"); - { - BrokerInfo value[] = new BrokerInfo[0]; - for (int i = 0; i < 0; i++) { - value[i] = createBrokerInfo("PeerBrokerInfos:3"); - } - info.setPeerBrokerInfos(value); - } - info.setBrokerName("BrokerName:4"); - info.setSlaveBroker(true); - info.setMasterBroker(false); - info.setFaultTolerantConfiguration(true); - info.setDuplexConnection(false); - info.setNetworkConnection(true); - info.setConnectionId(1); - } + info.setBrokerId(createBrokerId("BrokerId:1")); + info.setBrokerURL("BrokerURL:2"); + { + BrokerInfo value[] = new BrokerInfo[0]; + for (int i = 0; i < 0; i++) { + value[i] = createBrokerInfo("PeerBrokerInfos:3"); + } + info.setPeerBrokerInfos(value); + } + info.setBrokerName("BrokerName:4"); + info.setSlaveBroker(true); + info.setMasterBroker(false); + info.setFaultTolerantConfiguration(true); + info.setDuplexConnection(false); + info.setNetworkConnection(true); + info.setConnectionId(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConnectionControlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConnectionControlTest.java index 5e89773be1..12bcaf96be 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConnectionControlTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConnectionControlTest.java @@ -18,37 +18,33 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.ConnectionControl; - /** * Test case for the OpenWire marshalling for ConnectionControl * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConnectionControlTest extends BaseCommandTestSupport { + public static final ConnectionControlTest SINGLETON = new ConnectionControlTest(); - public static final ConnectionControlTest SINGLETON = new ConnectionControlTest(); + public Object createObject() throws Exception { + ConnectionControl info = new ConnectionControl(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConnectionControl info = new ConnectionControl(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConnectionControl info = (ConnectionControl) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionControl info = (ConnectionControl) object; - - info.setClose(true); - info.setExit(false); - info.setFaultTolerant(true); - info.setResume(false); - info.setSuspend(true); - } + info.setClose(true); + info.setExit(false); + info.setFaultTolerant(true); + info.setResume(false); + info.setSuspend(true); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConnectionErrorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConnectionErrorTest.java index ac5b5d9aa7..818955d7f5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConnectionErrorTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConnectionErrorTest.java @@ -18,34 +18,30 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.ConnectionError; - /** * Test case for the OpenWire marshalling for ConnectionError * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConnectionErrorTest extends BaseCommandTestSupport { + public static final ConnectionErrorTest SINGLETON = new ConnectionErrorTest(); - public static final ConnectionErrorTest SINGLETON = new ConnectionErrorTest(); + public Object createObject() throws Exception { + ConnectionError info = new ConnectionError(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConnectionError info = new ConnectionError(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConnectionError info = (ConnectionError) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionError info = (ConnectionError) object; - - info.setException(createThrowable("Exception:1")); - info.setConnectionId(createConnectionId("ConnectionId:2")); - } + info.setException(createThrowable("Exception:1")); + info.setConnectionId(createConnectionId("ConnectionId:2")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConnectionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConnectionIdTest.java index 8e066cef7a..04bcf112d8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConnectionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConnectionIdTest.java @@ -19,33 +19,29 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.ConnectionId; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for ConnectionId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConnectionIdTest extends DataFileGeneratorTestSupport { + public static final ConnectionIdTest SINGLETON = new ConnectionIdTest(); - public static final ConnectionIdTest SINGLETON = new ConnectionIdTest(); + public Object createObject() throws Exception { + ConnectionId info = new ConnectionId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConnectionId info = new ConnectionId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConnectionId info = (ConnectionId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionId info = (ConnectionId) object; - - info.setValue("Value:1"); - } + info.setValue("Value:1"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConnectionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConnectionInfoTest.java index 82fb37d3b2..258dbec596 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConnectionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConnectionInfoTest.java @@ -24,36 +24,34 @@ import org.apache.activemq.command.ConnectionInfo; * auto generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public class ConnectionInfoTest extends BaseCommandTestSupport { - public static final ConnectionInfoTest SINGLETON = new ConnectionInfoTest(); + public static final ConnectionInfoTest SINGLETON = new ConnectionInfoTest(); - public Object createObject() throws Exception { - ConnectionInfo info = new ConnectionInfo(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ConnectionInfo info = new ConnectionInfo(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionInfo info = (ConnectionInfo)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConnectionInfo info = (ConnectionInfo) object; - info.setConnectionId(createConnectionId("ConnectionId:1")); - info.setClientId("ClientId:2"); - info.setPassword("Password:3"); - info.setUserName("UserName:4"); - { - BrokerId value[] = new BrokerId[2]; - for (int i = 0; i < 2; i++) { - value[i] = createBrokerId("BrokerPath:5"); - } - info.setBrokerPath(value); - } - info.setBrokerMasterConnector(true); - info.setManageable(false); - info.setClientMaster(true); - } + info.setConnectionId(createConnectionId("ConnectionId:1")); + info.setClientId("ClientId:2"); + info.setPassword("Password:3"); + info.setUserName("UserName:4"); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:5"); + } + info.setBrokerPath(value); + } + info.setBrokerMasterConnector(true); + info.setManageable(false); + info.setClientMaster(true); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConsumerControlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConsumerControlTest.java index b5505331a4..0d190ab06f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConsumerControlTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConsumerControlTest.java @@ -18,38 +18,34 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.ConsumerControl; - /** * Test case for the OpenWire marshalling for ConsumerControl * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConsumerControlTest extends BaseCommandTestSupport { + public static final ConsumerControlTest SINGLETON = new ConsumerControlTest(); - public static final ConsumerControlTest SINGLETON = new ConsumerControlTest(); + public Object createObject() throws Exception { + ConsumerControl info = new ConsumerControl(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConsumerControl info = new ConsumerControl(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConsumerControl info = (ConsumerControl) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConsumerControl info = (ConsumerControl) object; - - info.setClose(true); - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setPrefetch(1); - info.setFlush(false); - info.setStart(true); - info.setStop(false); - } + info.setClose(true); + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setPrefetch(1); + info.setFlush(false); + info.setStart(true); + info.setStop(false); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConsumerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConsumerIdTest.java index d818c853c0..6c826eda5f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConsumerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConsumerIdTest.java @@ -19,35 +19,31 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.ConsumerId; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for ConsumerId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConsumerIdTest extends DataFileGeneratorTestSupport { + public static final ConsumerIdTest SINGLETON = new ConsumerIdTest(); - public static final ConsumerIdTest SINGLETON = new ConsumerIdTest(); + public Object createObject() throws Exception { + ConsumerId info = new ConsumerId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConsumerId info = new ConsumerId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConsumerId info = (ConsumerId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConsumerId info = (ConsumerId) object; - - info.setConnectionId("ConnectionId:1"); - info.setSessionId(1); - info.setValue(2); - } + info.setConnectionId("ConnectionId:1"); + info.setSessionId(1); + info.setValue(2); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConsumerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConsumerInfoTest.java index 1420260a92..ecc1d32c43 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConsumerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ConsumerInfoTest.java @@ -24,45 +24,43 @@ import org.apache.activemq.command.ConsumerInfo; * auto generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public class ConsumerInfoTest extends BaseCommandTestSupport { - public static final ConsumerInfoTest SINGLETON = new ConsumerInfoTest(); + public static final ConsumerInfoTest SINGLETON = new ConsumerInfoTest(); - public Object createObject() throws Exception { - ConsumerInfo info = new ConsumerInfo(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ConsumerInfo info = new ConsumerInfo(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConsumerInfo info = (ConsumerInfo)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConsumerInfo info = (ConsumerInfo) object; - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setBrowser(true); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setPrefetchSize(1); - info.setMaximumPendingMessageLimit(2); - info.setDispatchAsync(false); - info.setSelector("Selector:3"); - info.setSubscriptionName("SubscriptionName:4"); - info.setNoLocal(true); - info.setExclusive(false); - info.setRetroactive(true); - info.setPriority((byte)1); - { - BrokerId value[] = new BrokerId[2]; - for (int i = 0; i < 2; i++) { - value[i] = createBrokerId("BrokerPath:5"); - } - info.setBrokerPath(value); - } - info.setAdditionalPredicate(createBooleanExpression("AdditionalPredicate:6")); - info.setNetworkSubscription(false); - info.setOptimizedAcknowledge(true); - info.setNoRangeAcks(false); - } + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setBrowser(true); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setPrefetchSize(1); + info.setMaximumPendingMessageLimit(2); + info.setDispatchAsync(false); + info.setSelector("Selector:3"); + info.setSubscriptionName("SubscriptionName:4"); + info.setNoLocal(true); + info.setExclusive(false); + info.setRetroactive(true); + info.setPriority((byte) 1); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:5"); + } + info.setBrokerPath(value); + } + info.setAdditionalPredicate(createBooleanExpression("AdditionalPredicate:6")); + info.setNetworkSubscription(false); + info.setOptimizedAcknowledge(true); + info.setNoRangeAcks(false); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ControlCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ControlCommandTest.java index 776726718e..4e0d9dd5f0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ControlCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ControlCommandTest.java @@ -18,33 +18,29 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.ControlCommand; - /** * Test case for the OpenWire marshalling for ControlCommand * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ControlCommandTest extends BaseCommandTestSupport { + public static final ControlCommandTest SINGLETON = new ControlCommandTest(); - public static final ControlCommandTest SINGLETON = new ControlCommandTest(); + public Object createObject() throws Exception { + ControlCommand info = new ControlCommand(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ControlCommand info = new ControlCommand(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ControlCommand info = (ControlCommand) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ControlCommand info = (ControlCommand) object; - - info.setCommand("Command:1"); - } + info.setCommand("Command:1"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/DataArrayResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/DataArrayResponseTest.java index 3398dff6be..0a2d82bc6e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/DataArrayResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/DataArrayResponseTest.java @@ -24,29 +24,27 @@ import org.apache.activemq.command.DataStructure; * is auto generated - do not modify! if you need to make a change, please see * the modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public class DataArrayResponseTest extends ResponseTest { - public static final DataArrayResponseTest SINGLETON = new DataArrayResponseTest(); + public static final DataArrayResponseTest SINGLETON = new DataArrayResponseTest(); - public Object createObject() throws Exception { - DataArrayResponse info = new DataArrayResponse(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + DataArrayResponse info = new DataArrayResponse(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DataArrayResponse info = (DataArrayResponse)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + DataArrayResponse info = (DataArrayResponse) object; - { - DataStructure value[] = new DataStructure[2]; - for (int i = 0; i < 2; i++) { - value[i] = createDataStructure("Data:1"); - } - info.setData(value); - } - } + { + DataStructure value[] = new DataStructure[2]; + for (int i = 0; i < 2; i++) { + value[i] = createDataStructure("Data:1"); + } + info.setData(value); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/DataResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/DataResponseTest.java index f8b4e495bb..866582bb44 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/DataResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/DataResponseTest.java @@ -18,33 +18,29 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.DataResponse; - /** * Test case for the OpenWire marshalling for DataResponse * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class DataResponseTest extends ResponseTest { + public static final DataResponseTest SINGLETON = new DataResponseTest(); - public static final DataResponseTest SINGLETON = new DataResponseTest(); + public Object createObject() throws Exception { + DataResponse info = new DataResponse(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - DataResponse info = new DataResponse(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + DataResponse info = (DataResponse) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DataResponse info = (DataResponse) object; - - info.setData(createDataStructure("Data:1")); - } + info.setData(createDataStructure("Data:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/DestinationInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/DestinationInfoTest.java index accfb0b7a6..f43e579ffd 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/DestinationInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/DestinationInfoTest.java @@ -24,33 +24,31 @@ import org.apache.activemq.command.DestinationInfo; * is auto generated - do not modify! if you need to make a change, please see * the modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public class DestinationInfoTest extends BaseCommandTestSupport { - public static final DestinationInfoTest SINGLETON = new DestinationInfoTest(); + public static final DestinationInfoTest SINGLETON = new DestinationInfoTest(); - public Object createObject() throws Exception { - DestinationInfo info = new DestinationInfo(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + DestinationInfo info = new DestinationInfo(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DestinationInfo info = (DestinationInfo)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + DestinationInfo info = (DestinationInfo) object; - info.setConnectionId(createConnectionId("ConnectionId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setOperationType((byte)1); - info.setTimeout(1); - { - BrokerId value[] = new BrokerId[2]; - for (int i = 0; i < 2; i++) { - value[i] = createBrokerId("BrokerPath:3"); - } - info.setBrokerPath(value); - } - } + info.setConnectionId(createConnectionId("ConnectionId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setOperationType((byte) 1); + info.setTimeout(1); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:3"); + } + info.setBrokerPath(value); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/DiscoveryEventTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/DiscoveryEventTest.java index 77dca5f9e0..426713ad5d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/DiscoveryEventTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/DiscoveryEventTest.java @@ -19,34 +19,30 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.DiscoveryEvent; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for DiscoveryEvent * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class DiscoveryEventTest extends DataFileGeneratorTestSupport { + public static final DiscoveryEventTest SINGLETON = new DiscoveryEventTest(); - public static final DiscoveryEventTest SINGLETON = new DiscoveryEventTest(); + public Object createObject() throws Exception { + DiscoveryEvent info = new DiscoveryEvent(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - DiscoveryEvent info = new DiscoveryEvent(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + DiscoveryEvent info = (DiscoveryEvent) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DiscoveryEvent info = (DiscoveryEvent) object; - - info.setServiceName("ServiceName:1"); - info.setBrokerName("BrokerName:2"); - } + info.setServiceName("ServiceName:1"); + info.setBrokerName("BrokerName:2"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ExceptionResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ExceptionResponseTest.java index 0f81fc7a6c..977799f7c0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ExceptionResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ExceptionResponseTest.java @@ -18,33 +18,29 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.ExceptionResponse; - /** * Test case for the OpenWire marshalling for ExceptionResponse * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ExceptionResponseTest extends ResponseTest { + public static final ExceptionResponseTest SINGLETON = new ExceptionResponseTest(); - public static final ExceptionResponseTest SINGLETON = new ExceptionResponseTest(); + public Object createObject() throws Exception { + ExceptionResponse info = new ExceptionResponse(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ExceptionResponse info = new ExceptionResponse(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ExceptionResponse info = (ExceptionResponse) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ExceptionResponse info = (ExceptionResponse) object; - - info.setException(createThrowable("Exception:1")); - } + info.setException(createThrowable("Exception:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/FlushCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/FlushCommandTest.java index c00826b783..17237cbee6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/FlushCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/FlushCommandTest.java @@ -18,32 +18,28 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.FlushCommand; - /** * Test case for the OpenWire marshalling for FlushCommand * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class FlushCommandTest extends BaseCommandTestSupport { + public static final FlushCommandTest SINGLETON = new FlushCommandTest(); - public static final FlushCommandTest SINGLETON = new FlushCommandTest(); + public Object createObject() throws Exception { + FlushCommand info = new FlushCommand(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - FlushCommand info = new FlushCommand(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + FlushCommand info = (FlushCommand) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - FlushCommand info = (FlushCommand) object; - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/IntegerResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/IntegerResponseTest.java index 171303b061..04ed49df07 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/IntegerResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/IntegerResponseTest.java @@ -18,33 +18,29 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.IntegerResponse; - /** * Test case for the OpenWire marshalling for IntegerResponse * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class IntegerResponseTest extends ResponseTest { + public static final IntegerResponseTest SINGLETON = new IntegerResponseTest(); - public static final IntegerResponseTest SINGLETON = new IntegerResponseTest(); + public Object createObject() throws Exception { + IntegerResponse info = new IntegerResponse(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - IntegerResponse info = new IntegerResponse(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + IntegerResponse info = (IntegerResponse) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - IntegerResponse info = (IntegerResponse) object; - - info.setResult(1); - } + info.setResult(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/JournalQueueAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/JournalQueueAckTest.java index 5613a992e3..3d99ec5145 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/JournalQueueAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/JournalQueueAckTest.java @@ -19,34 +19,30 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.JournalQueueAck; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for JournalQueueAck * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class JournalQueueAckTest extends DataFileGeneratorTestSupport { + public static final JournalQueueAckTest SINGLETON = new JournalQueueAckTest(); - public static final JournalQueueAckTest SINGLETON = new JournalQueueAckTest(); + public Object createObject() throws Exception { + JournalQueueAck info = new JournalQueueAck(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - JournalQueueAck info = new JournalQueueAck(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + JournalQueueAck info = (JournalQueueAck) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalQueueAck info = (JournalQueueAck) object; - - info.setDestination(createActiveMQDestination("Destination:1")); - info.setMessageAck(createMessageAck("MessageAck:2")); - } + info.setDestination(createActiveMQDestination("Destination:1")); + info.setMessageAck(createMessageAck("MessageAck:2")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/JournalTopicAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/JournalTopicAckTest.java index 022180212b..2599225c93 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/JournalTopicAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/JournalTopicAckTest.java @@ -19,38 +19,34 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.JournalTopicAck; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for JournalTopicAck * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class JournalTopicAckTest extends DataFileGeneratorTestSupport { + public static final JournalTopicAckTest SINGLETON = new JournalTopicAckTest(); - public static final JournalTopicAckTest SINGLETON = new JournalTopicAckTest(); + public Object createObject() throws Exception { + JournalTopicAck info = new JournalTopicAck(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - JournalTopicAck info = new JournalTopicAck(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + JournalTopicAck info = (JournalTopicAck) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalTopicAck info = (JournalTopicAck) object; - - info.setDestination(createActiveMQDestination("Destination:1")); - info.setMessageId(createMessageId("MessageId:2")); - info.setMessageSequenceId(1); - info.setSubscritionName("SubscritionName:3"); - info.setClientId("ClientId:4"); - info.setTransactionId(createTransactionId("TransactionId:5")); - } + info.setDestination(createActiveMQDestination("Destination:1")); + info.setMessageId(createMessageId("MessageId:2")); + info.setMessageSequenceId(1); + info.setSubscritionName("SubscritionName:3"); + info.setClientId("ClientId:4"); + info.setTransactionId(createTransactionId("TransactionId:5")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/JournalTraceTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/JournalTraceTest.java index e0ac05c0ed..06e3160c77 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/JournalTraceTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/JournalTraceTest.java @@ -19,33 +19,29 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.JournalTrace; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for JournalTrace * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class JournalTraceTest extends DataFileGeneratorTestSupport { + public static final JournalTraceTest SINGLETON = new JournalTraceTest(); - public static final JournalTraceTest SINGLETON = new JournalTraceTest(); + public Object createObject() throws Exception { + JournalTrace info = new JournalTrace(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - JournalTrace info = new JournalTrace(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + JournalTrace info = (JournalTrace) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalTrace info = (JournalTrace) object; - - info.setMessage("Message:1"); - } + info.setMessage("Message:1"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/JournalTransactionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/JournalTransactionTest.java index 714a697fed..bab04fff3f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/JournalTransactionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/JournalTransactionTest.java @@ -19,35 +19,31 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.JournalTransaction; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for JournalTransaction * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class JournalTransactionTest extends DataFileGeneratorTestSupport { + public static final JournalTransactionTest SINGLETON = new JournalTransactionTest(); - public static final JournalTransactionTest SINGLETON = new JournalTransactionTest(); + public Object createObject() throws Exception { + JournalTransaction info = new JournalTransaction(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - JournalTransaction info = new JournalTransaction(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + JournalTransaction info = (JournalTransaction) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalTransaction info = (JournalTransaction) object; - - info.setTransactionId(createTransactionId("TransactionId:1")); - info.setType((byte) 1); - info.setWasPrepared(true); - } + info.setTransactionId(createTransactionId("TransactionId:1")); + info.setType((byte) 1); + info.setWasPrepared(true); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/KeepAliveInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/KeepAliveInfoTest.java index b20eb451ff..e83159e95a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/KeepAliveInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/KeepAliveInfoTest.java @@ -18,32 +18,28 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.KeepAliveInfo; - /** * Test case for the OpenWire marshalling for KeepAliveInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class KeepAliveInfoTest extends BaseCommandTestSupport { + public static final KeepAliveInfoTest SINGLETON = new KeepAliveInfoTest(); - public static final KeepAliveInfoTest SINGLETON = new KeepAliveInfoTest(); + public Object createObject() throws Exception { + KeepAliveInfo info = new KeepAliveInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - KeepAliveInfo info = new KeepAliveInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + KeepAliveInfo info = (KeepAliveInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - KeepAliveInfo info = (KeepAliveInfo) object; - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/LastPartialCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/LastPartialCommandTest.java index 5891acdc9c..b7c8885d11 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/LastPartialCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/LastPartialCommandTest.java @@ -18,32 +18,28 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.LastPartialCommand; - /** * Test case for the OpenWire marshalling for LastPartialCommand * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class LastPartialCommandTest extends PartialCommandTest { + public static final LastPartialCommandTest SINGLETON = new LastPartialCommandTest(); - public static final LastPartialCommandTest SINGLETON = new LastPartialCommandTest(); + public Object createObject() throws Exception { + LastPartialCommand info = new LastPartialCommand(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - LastPartialCommand info = new LastPartialCommand(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + LastPartialCommand info = (LastPartialCommand) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - LastPartialCommand info = (LastPartialCommand) object; - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/LocalTransactionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/LocalTransactionIdTest.java index 26748019c5..2959f6d6dd 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/LocalTransactionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/LocalTransactionIdTest.java @@ -18,34 +18,30 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.LocalTransactionId; - /** * Test case for the OpenWire marshalling for LocalTransactionId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class LocalTransactionIdTest extends TransactionIdTestSupport { + public static final LocalTransactionIdTest SINGLETON = new LocalTransactionIdTest(); - public static final LocalTransactionIdTest SINGLETON = new LocalTransactionIdTest(); + public Object createObject() throws Exception { + LocalTransactionId info = new LocalTransactionId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - LocalTransactionId info = new LocalTransactionId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + LocalTransactionId info = (LocalTransactionId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - LocalTransactionId info = (LocalTransactionId) object; - - info.setValue(1); - info.setConnectionId(createConnectionId("ConnectionId:1")); - } + info.setValue(1); + info.setConnectionId(createConnectionId("ConnectionId:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/MessageAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/MessageAckTest.java index c4ac0155e6..6ac350f724 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/MessageAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/MessageAckTest.java @@ -18,39 +18,35 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.MessageAck; - /** * Test case for the OpenWire marshalling for MessageAck * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class MessageAckTest extends BaseCommandTestSupport { + public static final MessageAckTest SINGLETON = new MessageAckTest(); - public static final MessageAckTest SINGLETON = new MessageAckTest(); + public Object createObject() throws Exception { + MessageAck info = new MessageAck(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - MessageAck info = new MessageAck(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessageAck info = (MessageAck) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageAck info = (MessageAck) object; - - info.setDestination(createActiveMQDestination("Destination:1")); - info.setTransactionId(createTransactionId("TransactionId:2")); - info.setConsumerId(createConsumerId("ConsumerId:3")); - info.setAckType((byte) 1); - info.setFirstMessageId(createMessageId("FirstMessageId:4")); - info.setLastMessageId(createMessageId("LastMessageId:5")); - info.setMessageCount(1); - } + info.setDestination(createActiveMQDestination("Destination:1")); + info.setTransactionId(createTransactionId("TransactionId:2")); + info.setConsumerId(createConsumerId("ConsumerId:3")); + info.setAckType((byte) 1); + info.setFirstMessageId(createMessageId("FirstMessageId:4")); + info.setLastMessageId(createMessageId("LastMessageId:5")); + info.setMessageCount(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/MessageDispatchNotificationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/MessageDispatchNotificationTest.java index adfe131e95..69dcdcef0a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/MessageDispatchNotificationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/MessageDispatchNotificationTest.java @@ -18,36 +18,32 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.MessageDispatchNotification; - /** * Test case for the OpenWire marshalling for MessageDispatchNotification * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class MessageDispatchNotificationTest extends BaseCommandTestSupport { + public static final MessageDispatchNotificationTest SINGLETON = new MessageDispatchNotificationTest(); - public static final MessageDispatchNotificationTest SINGLETON = new MessageDispatchNotificationTest(); + public Object createObject() throws Exception { + MessageDispatchNotification info = new MessageDispatchNotification(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - MessageDispatchNotification info = new MessageDispatchNotification(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessageDispatchNotification info = (MessageDispatchNotification) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageDispatchNotification info = (MessageDispatchNotification) object; - - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setDeliverySequenceId(1); - info.setMessageId(createMessageId("MessageId:3")); - } + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setDeliverySequenceId(1); + info.setMessageId(createMessageId("MessageId:3")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/MessageDispatchTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/MessageDispatchTest.java index b100da32bb..c7c8bb4369 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/MessageDispatchTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/MessageDispatchTest.java @@ -18,36 +18,32 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.MessageDispatch; - /** * Test case for the OpenWire marshalling for MessageDispatch * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class MessageDispatchTest extends BaseCommandTestSupport { + public static final MessageDispatchTest SINGLETON = new MessageDispatchTest(); - public static final MessageDispatchTest SINGLETON = new MessageDispatchTest(); + public Object createObject() throws Exception { + MessageDispatch info = new MessageDispatch(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - MessageDispatch info = new MessageDispatch(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessageDispatch info = (MessageDispatch) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageDispatch info = (MessageDispatch) object; - - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setMessage(createMessage("Message:3")); - info.setRedeliveryCounter(1); - } + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setMessage(createMessage("Message:3")); + info.setRedeliveryCounter(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/MessageIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/MessageIdTest.java index bc4af3798d..b4a247dc59 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/MessageIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/MessageIdTest.java @@ -19,35 +19,31 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.MessageId; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for MessageId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class MessageIdTest extends DataFileGeneratorTestSupport { + public static final MessageIdTest SINGLETON = new MessageIdTest(); - public static final MessageIdTest SINGLETON = new MessageIdTest(); + public Object createObject() throws Exception { + MessageId info = new MessageId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - MessageId info = new MessageId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessageId info = (MessageId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageId info = (MessageId) object; - - info.setProducerId(createProducerId("ProducerId:1")); - info.setProducerSequenceId(1); - info.setBrokerSequenceId(2); - } + info.setProducerId(createProducerId("ProducerId:1")); + info.setProducerSequenceId(1); + info.setBrokerSequenceId(2); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/MessagePullTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/MessagePullTest.java index 030574dcea..d63d66b437 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/MessagePullTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/MessagePullTest.java @@ -18,35 +18,31 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.MessagePull; - /** * Test case for the OpenWire marshalling for MessagePull * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class MessagePullTest extends BaseCommandTestSupport { + public static final MessagePullTest SINGLETON = new MessagePullTest(); - public static final MessagePullTest SINGLETON = new MessagePullTest(); + public Object createObject() throws Exception { + MessagePull info = new MessagePull(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - MessagePull info = new MessagePull(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessagePull info = (MessagePull) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessagePull info = (MessagePull) object; - - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setTimeout(1); - } + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setTimeout(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/MessageTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/MessageTestSupport.java index 09bbd95df1..d36d937e03 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/MessageTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/MessageTestSupport.java @@ -30,60 +30,58 @@ import org.apache.activemq.util.MarshallingSupport; * generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public abstract class MessageTestSupport extends BaseCommandTestSupport { - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - Message info = (Message)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + Message info = (Message) object; - info.setProducerId(createProducerId("ProducerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setTransactionId(createTransactionId("TransactionId:3")); - info.setOriginalDestination(createActiveMQDestination("OriginalDestination:4")); - info.setMessageId(createMessageId("MessageId:5")); - info.setOriginalTransactionId(createTransactionId("OriginalTransactionId:6")); - info.setGroupID("GroupID:7"); - info.setGroupSequence(1); - info.setCorrelationId("CorrelationId:8"); - info.setPersistent(true); - info.setExpiration(1); - info.setPriority((byte)1); - info.setReplyTo(createActiveMQDestination("ReplyTo:9")); - info.setTimestamp(2); - info.setType("Type:10"); - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream dataOut = new DataOutputStream(baos); - MarshallingSupport.writeUTF8(dataOut, "Content:11"); - dataOut.close(); - info.setContent(baos.toByteSequence()); - } - { - Map map = new HashMap(); - map.put("MarshalledProperties", 12); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream os = new DataOutputStream(baos); - MarshallingSupport.marshalPrimitiveMap(map, os); - os.close(); - info.setMarshalledProperties(baos.toByteSequence()); - } - info.setDataStructure(createDataStructure("DataStructure:13")); - info.setTargetConsumerId(createConsumerId("TargetConsumerId:14")); - info.setCompressed(false); - info.setRedeliveryCounter(2); - { - BrokerId value[] = new BrokerId[2]; - for (int i = 0; i < 2; i++) { - value[i] = createBrokerId("BrokerPath:15"); - } - info.setBrokerPath(value); - } - info.setArrival(3); - info.setUserID("UserID:16"); - info.setRecievedByDFBridge(true); - info.setDroppable(false); - } + info.setProducerId(createProducerId("ProducerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setTransactionId(createTransactionId("TransactionId:3")); + info.setOriginalDestination(createActiveMQDestination("OriginalDestination:4")); + info.setMessageId(createMessageId("MessageId:5")); + info.setOriginalTransactionId(createTransactionId("OriginalTransactionId:6")); + info.setGroupID("GroupID:7"); + info.setGroupSequence(1); + info.setCorrelationId("CorrelationId:8"); + info.setPersistent(true); + info.setExpiration(1); + info.setPriority((byte) 1); + info.setReplyTo(createActiveMQDestination("ReplyTo:9")); + info.setTimestamp(2); + info.setType("Type:10"); + { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dataOut = new DataOutputStream(baos); + MarshallingSupport.writeUTF8(dataOut, "Content:11"); + dataOut.close(); + info.setContent(baos.toByteSequence()); + } + { + Map map = new HashMap(); + map.put("MarshalledProperties", 12); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream os = new DataOutputStream(baos); + MarshallingSupport.marshalPrimitiveMap(map, os); + os.close(); + info.setMarshalledProperties(baos.toByteSequence()); + } + info.setDataStructure(createDataStructure("DataStructure:13")); + info.setTargetConsumerId(createConsumerId("TargetConsumerId:14")); + info.setCompressed(false); + info.setRedeliveryCounter(2); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:15"); + } + info.setBrokerPath(value); + } + info.setArrival(3); + info.setUserID("UserID:16"); + info.setRecievedByDFBridge(true); + info.setDroppable(false); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/NetworkBridgeFilterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/NetworkBridgeFilterTest.java index 6afa4ef513..92f130ef05 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/NetworkBridgeFilterTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/NetworkBridgeFilterTest.java @@ -19,34 +19,30 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.NetworkBridgeFilter; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for NetworkBridgeFilter * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class NetworkBridgeFilterTest extends DataFileGeneratorTestSupport { + public static final NetworkBridgeFilterTest SINGLETON = new NetworkBridgeFilterTest(); - public static final NetworkBridgeFilterTest SINGLETON = new NetworkBridgeFilterTest(); + public Object createObject() throws Exception { + NetworkBridgeFilter info = new NetworkBridgeFilter(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - NetworkBridgeFilter info = new NetworkBridgeFilter(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + NetworkBridgeFilter info = (NetworkBridgeFilter) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - NetworkBridgeFilter info = (NetworkBridgeFilter) object; - - info.setNetworkTTL(1); - info.setNetworkBrokerId(createBrokerId("NetworkBrokerId:1")); - } + info.setNetworkTTL(1); + info.setNetworkBrokerId(createBrokerId("NetworkBrokerId:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/PartialCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/PartialCommandTest.java index 38e245f55d..3e366d6425 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/PartialCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/PartialCommandTest.java @@ -19,34 +19,30 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.PartialCommand; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for PartialCommand * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class PartialCommandTest extends DataFileGeneratorTestSupport { + public static final PartialCommandTest SINGLETON = new PartialCommandTest(); - public static final PartialCommandTest SINGLETON = new PartialCommandTest(); + public Object createObject() throws Exception { + PartialCommand info = new PartialCommand(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - PartialCommand info = new PartialCommand(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + PartialCommand info = (PartialCommand) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - PartialCommand info = (PartialCommand) object; - - info.setCommandId(1); - info.setData("Data:1".getBytes()); - } + info.setCommandId(1); + info.setData("Data:1".getBytes()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ProducerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ProducerIdTest.java index cbe32f878b..02dfc5c90c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ProducerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ProducerIdTest.java @@ -19,35 +19,31 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.ProducerId; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for ProducerId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ProducerIdTest extends DataFileGeneratorTestSupport { + public static final ProducerIdTest SINGLETON = new ProducerIdTest(); - public static final ProducerIdTest SINGLETON = new ProducerIdTest(); + public Object createObject() throws Exception { + ProducerId info = new ProducerId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ProducerId info = new ProducerId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ProducerId info = (ProducerId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ProducerId info = (ProducerId) object; - - info.setConnectionId("ConnectionId:1"); - info.setValue(1); - info.setSessionId(2); - } + info.setConnectionId("ConnectionId:1"); + info.setValue(1); + info.setSessionId(2); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ProducerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ProducerInfoTest.java index 07e226b56f..98dda5c54f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ProducerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ProducerInfoTest.java @@ -24,32 +24,30 @@ import org.apache.activemq.command.ProducerInfo; * auto generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public class ProducerInfoTest extends BaseCommandTestSupport { - public static final ProducerInfoTest SINGLETON = new ProducerInfoTest(); + public static final ProducerInfoTest SINGLETON = new ProducerInfoTest(); - public Object createObject() throws Exception { - ProducerInfo info = new ProducerInfo(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ProducerInfo info = new ProducerInfo(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ProducerInfo info = (ProducerInfo)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ProducerInfo info = (ProducerInfo) object; - info.setProducerId(createProducerId("ProducerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - { - BrokerId value[] = new BrokerId[2]; - for (int i = 0; i < 2; i++) { - value[i] = createBrokerId("BrokerPath:3"); - } - info.setBrokerPath(value); - } - info.setDispatchAsync(true); - } + info.setProducerId(createProducerId("ProducerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:3"); + } + info.setBrokerPath(value); + } + info.setDispatchAsync(true); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/RemoveInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/RemoveInfoTest.java index c45e7df61d..23eb8e7c6b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/RemoveInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/RemoveInfoTest.java @@ -18,33 +18,29 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.RemoveInfo; - /** * Test case for the OpenWire marshalling for RemoveInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class RemoveInfoTest extends BaseCommandTestSupport { + public static final RemoveInfoTest SINGLETON = new RemoveInfoTest(); - public static final RemoveInfoTest SINGLETON = new RemoveInfoTest(); + public Object createObject() throws Exception { + RemoveInfo info = new RemoveInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - RemoveInfo info = new RemoveInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + RemoveInfo info = (RemoveInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - RemoveInfo info = (RemoveInfo) object; - - info.setObjectId(createDataStructure("ObjectId:1")); - } + info.setObjectId(createDataStructure("ObjectId:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/RemoveSubscriptionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/RemoveSubscriptionInfoTest.java index 4c30153a1f..a2e0669aee 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/RemoveSubscriptionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/RemoveSubscriptionInfoTest.java @@ -18,35 +18,31 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.RemoveSubscriptionInfo; - /** * Test case for the OpenWire marshalling for RemoveSubscriptionInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class RemoveSubscriptionInfoTest extends BaseCommandTestSupport { + public static final RemoveSubscriptionInfoTest SINGLETON = new RemoveSubscriptionInfoTest(); - public static final RemoveSubscriptionInfoTest SINGLETON = new RemoveSubscriptionInfoTest(); + public Object createObject() throws Exception { + RemoveSubscriptionInfo info = new RemoveSubscriptionInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - RemoveSubscriptionInfo info = new RemoveSubscriptionInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + RemoveSubscriptionInfo info = (RemoveSubscriptionInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - RemoveSubscriptionInfo info = (RemoveSubscriptionInfo) object; - - info.setConnectionId(createConnectionId("ConnectionId:1")); - info.setSubscriptionName("SubcriptionName:2"); - info.setClientId("ClientId:3"); - } + info.setConnectionId(createConnectionId("ConnectionId:1")); + info.setSubscriptionName("SubcriptionName:2"); + info.setClientId("ClientId:3"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ReplayCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ReplayCommandTest.java index a2d821cf23..0677ce9666 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ReplayCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ReplayCommandTest.java @@ -18,34 +18,30 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.ReplayCommand; - /** * Test case for the OpenWire marshalling for ReplayCommand * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ReplayCommandTest extends BaseCommandTestSupport { + public static final ReplayCommandTest SINGLETON = new ReplayCommandTest(); - public static final ReplayCommandTest SINGLETON = new ReplayCommandTest(); + public Object createObject() throws Exception { + ReplayCommand info = new ReplayCommand(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ReplayCommand info = new ReplayCommand(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ReplayCommand info = (ReplayCommand) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ReplayCommand info = (ReplayCommand) object; - - info.setFirstNakNumber(1); - info.setLastNakNumber(2); - } + info.setFirstNakNumber(1); + info.setLastNakNumber(2); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ResponseTest.java index 0cde5777d9..4614b5f6c1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ResponseTest.java @@ -18,33 +18,29 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.Response; - /** * Test case for the OpenWire marshalling for Response * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ResponseTest extends BaseCommandTestSupport { + public static final ResponseTest SINGLETON = new ResponseTest(); - public static final ResponseTest SINGLETON = new ResponseTest(); + public Object createObject() throws Exception { + Response info = new Response(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - Response info = new Response(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + Response info = (Response) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - Response info = (Response) object; - - info.setCorrelationId(1); - } + info.setCorrelationId(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/SessionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/SessionIdTest.java index 50d896f4e2..f1e8d9d65d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/SessionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/SessionIdTest.java @@ -19,34 +19,30 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.SessionId; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for SessionId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class SessionIdTest extends DataFileGeneratorTestSupport { + public static final SessionIdTest SINGLETON = new SessionIdTest(); - public static final SessionIdTest SINGLETON = new SessionIdTest(); + public Object createObject() throws Exception { + SessionId info = new SessionId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - SessionId info = new SessionId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + SessionId info = (SessionId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - SessionId info = (SessionId) object; - - info.setConnectionId("ConnectionId:1"); - info.setValue(1); - } + info.setConnectionId("ConnectionId:1"); + info.setValue(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/SessionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/SessionInfoTest.java index 233f37dfb3..836ac8ebaa 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/SessionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/SessionInfoTest.java @@ -18,33 +18,29 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.SessionInfo; - /** * Test case for the OpenWire marshalling for SessionInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class SessionInfoTest extends BaseCommandTestSupport { + public static final SessionInfoTest SINGLETON = new SessionInfoTest(); - public static final SessionInfoTest SINGLETON = new SessionInfoTest(); + public Object createObject() throws Exception { + SessionInfo info = new SessionInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - SessionInfo info = new SessionInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + SessionInfo info = (SessionInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - SessionInfo info = (SessionInfo) object; - - info.setSessionId(createSessionId("SessionId:1")); - } + info.setSessionId(createSessionId("SessionId:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ShutdownInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ShutdownInfoTest.java index f617f145b3..d837faafca 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ShutdownInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/ShutdownInfoTest.java @@ -18,32 +18,28 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.ShutdownInfo; - /** * Test case for the OpenWire marshalling for ShutdownInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ShutdownInfoTest extends BaseCommandTestSupport { + public static final ShutdownInfoTest SINGLETON = new ShutdownInfoTest(); - public static final ShutdownInfoTest SINGLETON = new ShutdownInfoTest(); + public Object createObject() throws Exception { + ShutdownInfo info = new ShutdownInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ShutdownInfo info = new ShutdownInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ShutdownInfo info = (ShutdownInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ShutdownInfo info = (ShutdownInfo) object; - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/SubscriptionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/SubscriptionInfoTest.java index f34f962420..a27052ae66 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/SubscriptionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/SubscriptionInfoTest.java @@ -19,36 +19,32 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.SubscriptionInfo; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for SubscriptionInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class SubscriptionInfoTest extends DataFileGeneratorTestSupport { + public static final SubscriptionInfoTest SINGLETON = new SubscriptionInfoTest(); - public static final SubscriptionInfoTest SINGLETON = new SubscriptionInfoTest(); + public Object createObject() throws Exception { + SubscriptionInfo info = new SubscriptionInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - SubscriptionInfo info = new SubscriptionInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + SubscriptionInfo info = (SubscriptionInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - SubscriptionInfo info = (SubscriptionInfo) object; - - info.setClientId("ClientId:1"); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setSelector("Selector:3"); - info.setSubscriptionName("SubcriptionName:4"); - } + info.setClientId("ClientId:1"); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setSelector("Selector:3"); + info.setSubscriptionName("SubcriptionName:4"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/TransactionIdTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/TransactionIdTestSupport.java index ffa7eb1100..7bf6d3d1e2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/TransactionIdTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/TransactionIdTestSupport.java @@ -19,24 +19,20 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.TransactionId; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for TransactionId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public abstract class TransactionIdTestSupport extends DataFileGeneratorTestSupport { + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + TransactionId info = (TransactionId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - TransactionId info = (TransactionId) object; - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/TransactionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/TransactionInfoTest.java index 128fde8c59..03b457734b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/TransactionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/TransactionInfoTest.java @@ -18,35 +18,31 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.TransactionInfo; - /** * Test case for the OpenWire marshalling for TransactionInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class TransactionInfoTest extends BaseCommandTestSupport { + public static final TransactionInfoTest SINGLETON = new TransactionInfoTest(); - public static final TransactionInfoTest SINGLETON = new TransactionInfoTest(); + public Object createObject() throws Exception { + TransactionInfo info = new TransactionInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - TransactionInfo info = new TransactionInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + TransactionInfo info = (TransactionInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - TransactionInfo info = (TransactionInfo) object; - - info.setConnectionId(createConnectionId("ConnectionId:1")); - info.setTransactionId(createTransactionId("TransactionId:2")); - info.setType((byte) 1); - } + info.setConnectionId(createConnectionId("ConnectionId:1")); + info.setTransactionId(createTransactionId("TransactionId:2")); + info.setType((byte) 1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/WireFormatInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/WireFormatInfoTest.java index 4eba697890..d7237a9671 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/WireFormatInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/WireFormatInfoTest.java @@ -24,28 +24,26 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; * auto generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public class WireFormatInfoTest extends DataFileGeneratorTestSupport { - public static final WireFormatInfoTest SINGLETON = new WireFormatInfoTest(); + public static final WireFormatInfoTest SINGLETON = new WireFormatInfoTest(); - public Object createObject() throws Exception { - WireFormatInfo info = new WireFormatInfo(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + WireFormatInfo info = new WireFormatInfo(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - WireFormatInfo info = (WireFormatInfo)object; - info.setVersion(1); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + WireFormatInfo info = (WireFormatInfo) object; + info.setVersion(1); - { - byte data[] = "MarshalledProperties:1".getBytes(); - info.setMarshalledProperties(new org.apache.activemq.util.ByteSequence(data, 0, data.length)); - } + { + byte data[] = "MarshalledProperties:1".getBytes(); + info.setMarshalledProperties(new org.apache.activemq.util.ByteSequence(data, 0, data.length)); + } - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/XATransactionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/XATransactionIdTest.java index d266111351..9b49001489 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/XATransactionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v2/XATransactionIdTest.java @@ -18,35 +18,31 @@ package org.apache.activemq.openwire.v2; import org.apache.activemq.command.XATransactionId; - /** * Test case for the OpenWire marshalling for XATransactionId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class XATransactionIdTest extends TransactionIdTestSupport { + public static final XATransactionIdTest SINGLETON = new XATransactionIdTest(); - public static final XATransactionIdTest SINGLETON = new XATransactionIdTest(); + public Object createObject() throws Exception { + XATransactionId info = new XATransactionId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - XATransactionId info = new XATransactionId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + XATransactionId info = (XATransactionId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - XATransactionId info = (XATransactionId) object; - - info.setFormatId(1); - info.setGlobalTransactionId("GlobalTransactionId:1".getBytes()); - info.setBranchQualifier("BranchQualifier:2".getBytes()); - } + info.setFormatId(1); + info.setGlobalTransactionId("GlobalTransactionId:1".getBytes()); + info.setBranchQualifier("BranchQualifier:2".getBytes()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/BaseCommandTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/BaseCommandTestSupport.java index 628d34c753..bab20c4c43 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/BaseCommandTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/BaseCommandTestSupport.java @@ -21,21 +21,19 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for BaseCommand - * - * + * + * * NOTE!: This file is auto generated - do not modify! if you need to make a * change, please see the modify the groovy scripts in the under src/gram/script * and then use maven openwire:generate to regenerate this file. - * - * */ public abstract class BaseCommandTestSupport extends DataFileGeneratorTestSupport { - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - BaseCommand info = (BaseCommand)object; - info.setCommandId(1); - info.setResponseRequired(true); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + BaseCommand info = (BaseCommand) object; + info.setCommandId(1); + info.setResponseRequired(true); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/BrokerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/BrokerIdTest.java index b3ed358b5a..f19dcc07c0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/BrokerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/BrokerIdTest.java @@ -19,33 +19,29 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.BrokerId; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for BrokerId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class BrokerIdTest extends DataFileGeneratorTestSupport { + public static final BrokerIdTest SINGLETON = new BrokerIdTest(); - public static final BrokerIdTest SINGLETON = new BrokerIdTest(); + public Object createObject() throws Exception { + BrokerId info = new BrokerId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - BrokerId info = new BrokerId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + BrokerId info = (BrokerId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - BrokerId info = (BrokerId) object; - - info.setValue("Value:1"); - } + info.setValue("Value:1"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/BrokerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/BrokerInfoTest.java index a7bede2d1f..0d4be46dfb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/BrokerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/BrokerInfoTest.java @@ -23,40 +23,38 @@ import org.apache.activemq.command.BrokerInfo; * auto generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public class BrokerInfoTest extends BaseCommandTestSupport { - public static final BrokerInfoTest SINGLETON = new BrokerInfoTest(); + public static final BrokerInfoTest SINGLETON = new BrokerInfoTest(); - public Object createObject() throws Exception { - BrokerInfo info = new BrokerInfo(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + BrokerInfo info = new BrokerInfo(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - BrokerInfo info = (BrokerInfo)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + BrokerInfo info = (BrokerInfo) object; - info.setBrokerId(createBrokerId("BrokerId:1")); - info.setBrokerURL("BrokerURL:2"); - { - BrokerInfo value[] = new BrokerInfo[0]; - for (int i = 0; i < 0; i++) { - value[i] = createBrokerInfo("PeerBrokerInfos:3"); - } - info.setPeerBrokerInfos(value); - } - info.setBrokerName("BrokerName:4"); - info.setSlaveBroker(true); - info.setMasterBroker(false); - info.setFaultTolerantConfiguration(true); - info.setDuplexConnection(false); - info.setNetworkConnection(true); - info.setConnectionId(1); - info.setBrokerUploadUrl("BrokerUploadUrl:5"); - info.setNetworkProperties("NetworkProperties:6"); - } + info.setBrokerId(createBrokerId("BrokerId:1")); + info.setBrokerURL("BrokerURL:2"); + { + BrokerInfo value[] = new BrokerInfo[0]; + for (int i = 0; i < 0; i++) { + value[i] = createBrokerInfo("PeerBrokerInfos:3"); + } + info.setPeerBrokerInfos(value); + } + info.setBrokerName("BrokerName:4"); + info.setSlaveBroker(true); + info.setMasterBroker(false); + info.setFaultTolerantConfiguration(true); + info.setDuplexConnection(false); + info.setNetworkConnection(true); + info.setConnectionId(1); + info.setBrokerUploadUrl("BrokerUploadUrl:5"); + info.setNetworkProperties("NetworkProperties:6"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConnectionControlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConnectionControlTest.java index ec7a10990e..ccb5880d15 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConnectionControlTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConnectionControlTest.java @@ -18,37 +18,33 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.ConnectionControl; - /** * Test case for the OpenWire marshalling for ConnectionControl * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConnectionControlTest extends BaseCommandTestSupport { + public static final ConnectionControlTest SINGLETON = new ConnectionControlTest(); - public static final ConnectionControlTest SINGLETON = new ConnectionControlTest(); + public Object createObject() throws Exception { + ConnectionControl info = new ConnectionControl(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConnectionControl info = new ConnectionControl(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConnectionControl info = (ConnectionControl) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionControl info = (ConnectionControl) object; - - info.setClose(true); - info.setExit(false); - info.setFaultTolerant(true); - info.setResume(false); - info.setSuspend(true); - } + info.setClose(true); + info.setExit(false); + info.setFaultTolerant(true); + info.setResume(false); + info.setSuspend(true); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConnectionErrorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConnectionErrorTest.java index dd19044313..0908400099 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConnectionErrorTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConnectionErrorTest.java @@ -18,34 +18,30 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.ConnectionError; - /** * Test case for the OpenWire marshalling for ConnectionError * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConnectionErrorTest extends BaseCommandTestSupport { + public static final ConnectionErrorTest SINGLETON = new ConnectionErrorTest(); - public static final ConnectionErrorTest SINGLETON = new ConnectionErrorTest(); + public Object createObject() throws Exception { + ConnectionError info = new ConnectionError(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConnectionError info = new ConnectionError(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConnectionError info = (ConnectionError) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionError info = (ConnectionError) object; - - info.setException(createThrowable("Exception:1")); - info.setConnectionId(createConnectionId("ConnectionId:2")); - } + info.setException(createThrowable("Exception:1")); + info.setConnectionId(createConnectionId("ConnectionId:2")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConnectionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConnectionIdTest.java index 05b5430dde..bd65d86c7e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConnectionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConnectionIdTest.java @@ -19,33 +19,29 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.ConnectionId; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for ConnectionId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConnectionIdTest extends DataFileGeneratorTestSupport { + public static final ConnectionIdTest SINGLETON = new ConnectionIdTest(); - public static final ConnectionIdTest SINGLETON = new ConnectionIdTest(); + public Object createObject() throws Exception { + ConnectionId info = new ConnectionId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConnectionId info = new ConnectionId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConnectionId info = (ConnectionId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionId info = (ConnectionId) object; - - info.setValue("Value:1"); - } + info.setValue("Value:1"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConnectionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConnectionInfoTest.java index 78f0729f6c..0bf71131c2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConnectionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConnectionInfoTest.java @@ -24,36 +24,34 @@ import org.apache.activemq.command.ConnectionInfo; * auto generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public class ConnectionInfoTest extends BaseCommandTestSupport { - public static final ConnectionInfoTest SINGLETON = new ConnectionInfoTest(); + public static final ConnectionInfoTest SINGLETON = new ConnectionInfoTest(); - public Object createObject() throws Exception { - ConnectionInfo info = new ConnectionInfo(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ConnectionInfo info = new ConnectionInfo(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionInfo info = (ConnectionInfo)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConnectionInfo info = (ConnectionInfo) object; - info.setConnectionId(createConnectionId("ConnectionId:1")); - info.setClientId("ClientId:2"); - info.setPassword("Password:3"); - info.setUserName("UserName:4"); - { - BrokerId value[] = new BrokerId[2]; - for (int i = 0; i < 2; i++) { - value[i] = createBrokerId("BrokerPath:5"); - } - info.setBrokerPath(value); - } - info.setBrokerMasterConnector(true); - info.setManageable(false); - info.setClientMaster(true); - } + info.setConnectionId(createConnectionId("ConnectionId:1")); + info.setClientId("ClientId:2"); + info.setPassword("Password:3"); + info.setUserName("UserName:4"); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:5"); + } + info.setBrokerPath(value); + } + info.setBrokerMasterConnector(true); + info.setManageable(false); + info.setClientMaster(true); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConsumerControlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConsumerControlTest.java index 7f061c875e..5c2bf7f2f2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConsumerControlTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConsumerControlTest.java @@ -18,38 +18,34 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.ConsumerControl; - /** * Test case for the OpenWire marshalling for ConsumerControl * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConsumerControlTest extends BaseCommandTestSupport { + public static final ConsumerControlTest SINGLETON = new ConsumerControlTest(); - public static final ConsumerControlTest SINGLETON = new ConsumerControlTest(); + public Object createObject() throws Exception { + ConsumerControl info = new ConsumerControl(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConsumerControl info = new ConsumerControl(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConsumerControl info = (ConsumerControl) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConsumerControl info = (ConsumerControl) object; - - info.setClose(true); - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setPrefetch(1); - info.setFlush(false); - info.setStart(true); - info.setStop(false); - } + info.setClose(true); + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setPrefetch(1); + info.setFlush(false); + info.setStart(true); + info.setStop(false); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConsumerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConsumerIdTest.java index 54cc8da812..8da7fd9ead 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConsumerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConsumerIdTest.java @@ -19,35 +19,31 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.ConsumerId; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for ConsumerId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConsumerIdTest extends DataFileGeneratorTestSupport { + public static final ConsumerIdTest SINGLETON = new ConsumerIdTest(); - public static final ConsumerIdTest SINGLETON = new ConsumerIdTest(); + public Object createObject() throws Exception { + ConsumerId info = new ConsumerId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConsumerId info = new ConsumerId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConsumerId info = (ConsumerId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConsumerId info = (ConsumerId) object; - - info.setConnectionId("ConnectionId:1"); - info.setSessionId(1); - info.setValue(2); - } + info.setConnectionId("ConnectionId:1"); + info.setSessionId(1); + info.setValue(2); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConsumerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConsumerInfoTest.java index 24d00d601a..6d3db8097f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConsumerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ConsumerInfoTest.java @@ -24,45 +24,43 @@ import org.apache.activemq.command.ConsumerInfo; * auto generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public class ConsumerInfoTest extends BaseCommandTestSupport { - public static final ConsumerInfoTest SINGLETON = new ConsumerInfoTest(); + public static final ConsumerInfoTest SINGLETON = new ConsumerInfoTest(); - public Object createObject() throws Exception { - ConsumerInfo info = new ConsumerInfo(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ConsumerInfo info = new ConsumerInfo(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConsumerInfo info = (ConsumerInfo)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConsumerInfo info = (ConsumerInfo) object; - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setBrowser(true); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setPrefetchSize(1); - info.setMaximumPendingMessageLimit(2); - info.setDispatchAsync(false); - info.setSelector("Selector:3"); - info.setSubscriptionName("SubscriptionName:4"); - info.setNoLocal(true); - info.setExclusive(false); - info.setRetroactive(true); - info.setPriority((byte)1); - { - BrokerId value[] = new BrokerId[2]; - for (int i = 0; i < 2; i++) { - value[i] = createBrokerId("BrokerPath:5"); - } - info.setBrokerPath(value); - } - info.setAdditionalPredicate(createBooleanExpression("AdditionalPredicate:6")); - info.setNetworkSubscription(false); - info.setOptimizedAcknowledge(true); - info.setNoRangeAcks(false); - } + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setBrowser(true); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setPrefetchSize(1); + info.setMaximumPendingMessageLimit(2); + info.setDispatchAsync(false); + info.setSelector("Selector:3"); + info.setSubscriptionName("SubscriptionName:4"); + info.setNoLocal(true); + info.setExclusive(false); + info.setRetroactive(true); + info.setPriority((byte) 1); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:5"); + } + info.setBrokerPath(value); + } + info.setAdditionalPredicate(createBooleanExpression("AdditionalPredicate:6")); + info.setNetworkSubscription(false); + info.setOptimizedAcknowledge(true); + info.setNoRangeAcks(false); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ControlCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ControlCommandTest.java index 401fe68ee9..735997702e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ControlCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ControlCommandTest.java @@ -18,33 +18,29 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.ControlCommand; - /** * Test case for the OpenWire marshalling for ControlCommand * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ControlCommandTest extends BaseCommandTestSupport { + public static final ControlCommandTest SINGLETON = new ControlCommandTest(); - public static final ControlCommandTest SINGLETON = new ControlCommandTest(); + public Object createObject() throws Exception { + ControlCommand info = new ControlCommand(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ControlCommand info = new ControlCommand(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ControlCommand info = (ControlCommand) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ControlCommand info = (ControlCommand) object; - - info.setCommand("Command:1"); - } + info.setCommand("Command:1"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/DataArrayResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/DataArrayResponseTest.java index b6f3a87dc0..0198aa5399 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/DataArrayResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/DataArrayResponseTest.java @@ -24,29 +24,27 @@ import org.apache.activemq.command.DataStructure; * is auto generated - do not modify! if you need to make a change, please see * the modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public class DataArrayResponseTest extends ResponseTest { - public static final DataArrayResponseTest SINGLETON = new DataArrayResponseTest(); + public static final DataArrayResponseTest SINGLETON = new DataArrayResponseTest(); - public Object createObject() throws Exception { - DataArrayResponse info = new DataArrayResponse(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + DataArrayResponse info = new DataArrayResponse(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DataArrayResponse info = (DataArrayResponse)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + DataArrayResponse info = (DataArrayResponse) object; - { - DataStructure value[] = new DataStructure[2]; - for (int i = 0; i < 2; i++) { - value[i] = createDataStructure("Data:1"); - } - info.setData(value); - } - } + { + DataStructure value[] = new DataStructure[2]; + for (int i = 0; i < 2; i++) { + value[i] = createDataStructure("Data:1"); + } + info.setData(value); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/DataResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/DataResponseTest.java index cf773a5a42..76b1b3f1f8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/DataResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/DataResponseTest.java @@ -18,33 +18,29 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.DataResponse; - /** * Test case for the OpenWire marshalling for DataResponse * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class DataResponseTest extends ResponseTest { + public static final DataResponseTest SINGLETON = new DataResponseTest(); - public static final DataResponseTest SINGLETON = new DataResponseTest(); + public Object createObject() throws Exception { + DataResponse info = new DataResponse(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - DataResponse info = new DataResponse(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + DataResponse info = (DataResponse) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DataResponse info = (DataResponse) object; - - info.setData(createDataStructure("Data:1")); - } + info.setData(createDataStructure("Data:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/DestinationInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/DestinationInfoTest.java index d7f7343003..b52316b95c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/DestinationInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/DestinationInfoTest.java @@ -24,33 +24,31 @@ import org.apache.activemq.command.DestinationInfo; * is auto generated - do not modify! if you need to make a change, please see * the modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public class DestinationInfoTest extends BaseCommandTestSupport { - public static final DestinationInfoTest SINGLETON = new DestinationInfoTest(); + public static final DestinationInfoTest SINGLETON = new DestinationInfoTest(); - public Object createObject() throws Exception { - DestinationInfo info = new DestinationInfo(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + DestinationInfo info = new DestinationInfo(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DestinationInfo info = (DestinationInfo)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + DestinationInfo info = (DestinationInfo) object; - info.setConnectionId(createConnectionId("ConnectionId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setOperationType((byte)1); - info.setTimeout(1); - { - BrokerId value[] = new BrokerId[2]; - for (int i = 0; i < 2; i++) { - value[i] = createBrokerId("BrokerPath:3"); - } - info.setBrokerPath(value); - } - } + info.setConnectionId(createConnectionId("ConnectionId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setOperationType((byte) 1); + info.setTimeout(1); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:3"); + } + info.setBrokerPath(value); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/DiscoveryEventTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/DiscoveryEventTest.java index 173801ec9f..a9282fbb60 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/DiscoveryEventTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/DiscoveryEventTest.java @@ -19,34 +19,30 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.DiscoveryEvent; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for DiscoveryEvent * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class DiscoveryEventTest extends DataFileGeneratorTestSupport { + public static final DiscoveryEventTest SINGLETON = new DiscoveryEventTest(); - public static final DiscoveryEventTest SINGLETON = new DiscoveryEventTest(); + public Object createObject() throws Exception { + DiscoveryEvent info = new DiscoveryEvent(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - DiscoveryEvent info = new DiscoveryEvent(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + DiscoveryEvent info = (DiscoveryEvent) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DiscoveryEvent info = (DiscoveryEvent) object; - - info.setServiceName("ServiceName:1"); - info.setBrokerName("BrokerName:2"); - } + info.setServiceName("ServiceName:1"); + info.setBrokerName("BrokerName:2"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ExceptionResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ExceptionResponseTest.java index 9c2edb36e8..0311b8829d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ExceptionResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ExceptionResponseTest.java @@ -18,33 +18,29 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.ExceptionResponse; - /** * Test case for the OpenWire marshalling for ExceptionResponse * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ExceptionResponseTest extends ResponseTest { + public static final ExceptionResponseTest SINGLETON = new ExceptionResponseTest(); - public static final ExceptionResponseTest SINGLETON = new ExceptionResponseTest(); + public Object createObject() throws Exception { + ExceptionResponse info = new ExceptionResponse(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ExceptionResponse info = new ExceptionResponse(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ExceptionResponse info = (ExceptionResponse) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ExceptionResponse info = (ExceptionResponse) object; - - info.setException(createThrowable("Exception:1")); - } + info.setException(createThrowable("Exception:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/FlushCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/FlushCommandTest.java index ac16ffb37e..21c5bafe7e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/FlushCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/FlushCommandTest.java @@ -18,32 +18,28 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.FlushCommand; - /** * Test case for the OpenWire marshalling for FlushCommand * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class FlushCommandTest extends BaseCommandTestSupport { + public static final FlushCommandTest SINGLETON = new FlushCommandTest(); - public static final FlushCommandTest SINGLETON = new FlushCommandTest(); + public Object createObject() throws Exception { + FlushCommand info = new FlushCommand(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - FlushCommand info = new FlushCommand(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + FlushCommand info = (FlushCommand) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - FlushCommand info = (FlushCommand) object; - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/IntegerResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/IntegerResponseTest.java index 6db78d1c1d..790eb5ca25 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/IntegerResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/IntegerResponseTest.java @@ -18,33 +18,29 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.IntegerResponse; - /** * Test case for the OpenWire marshalling for IntegerResponse * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class IntegerResponseTest extends ResponseTest { + public static final IntegerResponseTest SINGLETON = new IntegerResponseTest(); - public static final IntegerResponseTest SINGLETON = new IntegerResponseTest(); + public Object createObject() throws Exception { + IntegerResponse info = new IntegerResponse(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - IntegerResponse info = new IntegerResponse(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + IntegerResponse info = (IntegerResponse) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - IntegerResponse info = (IntegerResponse) object; - - info.setResult(1); - } + info.setResult(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/JournalQueueAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/JournalQueueAckTest.java index 1cdfa0a472..4ec3fcc217 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/JournalQueueAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/JournalQueueAckTest.java @@ -19,34 +19,30 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.JournalQueueAck; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for JournalQueueAck * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class JournalQueueAckTest extends DataFileGeneratorTestSupport { + public static final JournalQueueAckTest SINGLETON = new JournalQueueAckTest(); - public static final JournalQueueAckTest SINGLETON = new JournalQueueAckTest(); + public Object createObject() throws Exception { + JournalQueueAck info = new JournalQueueAck(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - JournalQueueAck info = new JournalQueueAck(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + JournalQueueAck info = (JournalQueueAck) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalQueueAck info = (JournalQueueAck) object; - - info.setDestination(createActiveMQDestination("Destination:1")); - info.setMessageAck(createMessageAck("MessageAck:2")); - } + info.setDestination(createActiveMQDestination("Destination:1")); + info.setMessageAck(createMessageAck("MessageAck:2")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/JournalTopicAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/JournalTopicAckTest.java index e9b826adac..599403d37d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/JournalTopicAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/JournalTopicAckTest.java @@ -19,38 +19,34 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.JournalTopicAck; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for JournalTopicAck * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class JournalTopicAckTest extends DataFileGeneratorTestSupport { + public static final JournalTopicAckTest SINGLETON = new JournalTopicAckTest(); - public static final JournalTopicAckTest SINGLETON = new JournalTopicAckTest(); + public Object createObject() throws Exception { + JournalTopicAck info = new JournalTopicAck(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - JournalTopicAck info = new JournalTopicAck(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + JournalTopicAck info = (JournalTopicAck) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalTopicAck info = (JournalTopicAck) object; - - info.setDestination(createActiveMQDestination("Destination:1")); - info.setMessageId(createMessageId("MessageId:2")); - info.setMessageSequenceId(1); - info.setSubscritionName("SubscritionName:3"); - info.setClientId("ClientId:4"); - info.setTransactionId(createTransactionId("TransactionId:5")); - } + info.setDestination(createActiveMQDestination("Destination:1")); + info.setMessageId(createMessageId("MessageId:2")); + info.setMessageSequenceId(1); + info.setSubscritionName("SubscritionName:3"); + info.setClientId("ClientId:4"); + info.setTransactionId(createTransactionId("TransactionId:5")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/JournalTraceTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/JournalTraceTest.java index 6cfd58c332..624ec60f87 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/JournalTraceTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/JournalTraceTest.java @@ -19,33 +19,29 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.JournalTrace; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for JournalTrace * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class JournalTraceTest extends DataFileGeneratorTestSupport { + public static final JournalTraceTest SINGLETON = new JournalTraceTest(); - public static final JournalTraceTest SINGLETON = new JournalTraceTest(); + public Object createObject() throws Exception { + JournalTrace info = new JournalTrace(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - JournalTrace info = new JournalTrace(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + JournalTrace info = (JournalTrace) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalTrace info = (JournalTrace) object; - - info.setMessage("Message:1"); - } + info.setMessage("Message:1"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/JournalTransactionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/JournalTransactionTest.java index 5918926f73..cc4efb303c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/JournalTransactionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/JournalTransactionTest.java @@ -19,35 +19,31 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.JournalTransaction; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for JournalTransaction * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class JournalTransactionTest extends DataFileGeneratorTestSupport { + public static final JournalTransactionTest SINGLETON = new JournalTransactionTest(); - public static final JournalTransactionTest SINGLETON = new JournalTransactionTest(); + public Object createObject() throws Exception { + JournalTransaction info = new JournalTransaction(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - JournalTransaction info = new JournalTransaction(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + JournalTransaction info = (JournalTransaction) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalTransaction info = (JournalTransaction) object; - - info.setTransactionId(createTransactionId("TransactionId:1")); - info.setType((byte) 1); - info.setWasPrepared(true); - } + info.setTransactionId(createTransactionId("TransactionId:1")); + info.setType((byte) 1); + info.setWasPrepared(true); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/KeepAliveInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/KeepAliveInfoTest.java index 19896c110b..5222970220 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/KeepAliveInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/KeepAliveInfoTest.java @@ -18,32 +18,28 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.KeepAliveInfo; - /** * Test case for the OpenWire marshalling for KeepAliveInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class KeepAliveInfoTest extends BaseCommandTestSupport { + public static final KeepAliveInfoTest SINGLETON = new KeepAliveInfoTest(); - public static final KeepAliveInfoTest SINGLETON = new KeepAliveInfoTest(); + public Object createObject() throws Exception { + KeepAliveInfo info = new KeepAliveInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - KeepAliveInfo info = new KeepAliveInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + KeepAliveInfo info = (KeepAliveInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - KeepAliveInfo info = (KeepAliveInfo) object; - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/LastPartialCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/LastPartialCommandTest.java index eadb6d840a..58df6da6a9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/LastPartialCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/LastPartialCommandTest.java @@ -18,32 +18,28 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.LastPartialCommand; - /** * Test case for the OpenWire marshalling for LastPartialCommand * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class LastPartialCommandTest extends PartialCommandTest { + public static final LastPartialCommandTest SINGLETON = new LastPartialCommandTest(); - public static final LastPartialCommandTest SINGLETON = new LastPartialCommandTest(); + public Object createObject() throws Exception { + LastPartialCommand info = new LastPartialCommand(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - LastPartialCommand info = new LastPartialCommand(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + LastPartialCommand info = (LastPartialCommand) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - LastPartialCommand info = (LastPartialCommand) object; - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/LocalTransactionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/LocalTransactionIdTest.java index acd7678ac9..45bce5ef62 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/LocalTransactionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/LocalTransactionIdTest.java @@ -18,34 +18,30 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.LocalTransactionId; - /** * Test case for the OpenWire marshalling for LocalTransactionId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class LocalTransactionIdTest extends TransactionIdTestSupport { + public static final LocalTransactionIdTest SINGLETON = new LocalTransactionIdTest(); - public static final LocalTransactionIdTest SINGLETON = new LocalTransactionIdTest(); + public Object createObject() throws Exception { + LocalTransactionId info = new LocalTransactionId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - LocalTransactionId info = new LocalTransactionId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + LocalTransactionId info = (LocalTransactionId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - LocalTransactionId info = (LocalTransactionId) object; - - info.setValue(1); - info.setConnectionId(createConnectionId("ConnectionId:1")); - } + info.setValue(1); + info.setConnectionId(createConnectionId("ConnectionId:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/MessageAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/MessageAckTest.java index f67e844d84..e6ba17a66a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/MessageAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/MessageAckTest.java @@ -18,39 +18,35 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.MessageAck; - /** * Test case for the OpenWire marshalling for MessageAck * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class MessageAckTest extends BaseCommandTestSupport { + public static final MessageAckTest SINGLETON = new MessageAckTest(); - public static final MessageAckTest SINGLETON = new MessageAckTest(); + public Object createObject() throws Exception { + MessageAck info = new MessageAck(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - MessageAck info = new MessageAck(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessageAck info = (MessageAck) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageAck info = (MessageAck) object; - - info.setDestination(createActiveMQDestination("Destination:1")); - info.setTransactionId(createTransactionId("TransactionId:2")); - info.setConsumerId(createConsumerId("ConsumerId:3")); - info.setAckType((byte) 1); - info.setFirstMessageId(createMessageId("FirstMessageId:4")); - info.setLastMessageId(createMessageId("LastMessageId:5")); - info.setMessageCount(1); - } + info.setDestination(createActiveMQDestination("Destination:1")); + info.setTransactionId(createTransactionId("TransactionId:2")); + info.setConsumerId(createConsumerId("ConsumerId:3")); + info.setAckType((byte) 1); + info.setFirstMessageId(createMessageId("FirstMessageId:4")); + info.setLastMessageId(createMessageId("LastMessageId:5")); + info.setMessageCount(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/MessageDispatchNotificationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/MessageDispatchNotificationTest.java index f9a76f40be..3898ab0f5c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/MessageDispatchNotificationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/MessageDispatchNotificationTest.java @@ -18,36 +18,32 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.MessageDispatchNotification; - /** * Test case for the OpenWire marshalling for MessageDispatchNotification * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class MessageDispatchNotificationTest extends BaseCommandTestSupport { + public static final MessageDispatchNotificationTest SINGLETON = new MessageDispatchNotificationTest(); - public static final MessageDispatchNotificationTest SINGLETON = new MessageDispatchNotificationTest(); + public Object createObject() throws Exception { + MessageDispatchNotification info = new MessageDispatchNotification(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - MessageDispatchNotification info = new MessageDispatchNotification(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessageDispatchNotification info = (MessageDispatchNotification) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageDispatchNotification info = (MessageDispatchNotification) object; - - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setDeliverySequenceId(1); - info.setMessageId(createMessageId("MessageId:3")); - } + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setDeliverySequenceId(1); + info.setMessageId(createMessageId("MessageId:3")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/MessageDispatchTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/MessageDispatchTest.java index 089218893b..68e606cb96 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/MessageDispatchTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/MessageDispatchTest.java @@ -18,36 +18,32 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.MessageDispatch; - /** * Test case for the OpenWire marshalling for MessageDispatch * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class MessageDispatchTest extends BaseCommandTestSupport { + public static final MessageDispatchTest SINGLETON = new MessageDispatchTest(); - public static final MessageDispatchTest SINGLETON = new MessageDispatchTest(); + public Object createObject() throws Exception { + MessageDispatch info = new MessageDispatch(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - MessageDispatch info = new MessageDispatch(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessageDispatch info = (MessageDispatch) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageDispatch info = (MessageDispatch) object; - - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setMessage(createMessage("Message:3")); - info.setRedeliveryCounter(1); - } + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setMessage(createMessage("Message:3")); + info.setRedeliveryCounter(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/MessageIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/MessageIdTest.java index 8f4da88954..b59ff2e4ec 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/MessageIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/MessageIdTest.java @@ -19,35 +19,31 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.MessageId; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for MessageId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class MessageIdTest extends DataFileGeneratorTestSupport { + public static final MessageIdTest SINGLETON = new MessageIdTest(); - public static final MessageIdTest SINGLETON = new MessageIdTest(); + public Object createObject() throws Exception { + MessageId info = new MessageId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - MessageId info = new MessageId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessageId info = (MessageId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageId info = (MessageId) object; - - info.setProducerId(createProducerId("ProducerId:1")); - info.setProducerSequenceId(1); - info.setBrokerSequenceId(2); - } + info.setProducerId(createProducerId("ProducerId:1")); + info.setProducerSequenceId(1); + info.setBrokerSequenceId(2); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/MessagePullTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/MessagePullTest.java index 2c628fa6a9..43e8dbb240 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/MessagePullTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/MessagePullTest.java @@ -18,37 +18,33 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.MessagePull; - /** * Test case for the OpenWire marshalling for MessagePull * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class MessagePullTest extends BaseCommandTestSupport { + public static final MessagePullTest SINGLETON = new MessagePullTest(); - public static final MessagePullTest SINGLETON = new MessagePullTest(); + public Object createObject() throws Exception { + MessagePull info = new MessagePull(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - MessagePull info = new MessagePull(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessagePull info = (MessagePull) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessagePull info = (MessagePull) object; - - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setTimeout(1); - info.setCorrelationId("CorrelationId:3"); - info.setMessageId(createMessageId("MessageId:4")); - } + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setTimeout(1); + info.setCorrelationId("CorrelationId:3"); + info.setMessageId(createMessageId("MessageId:4")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/MessageTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/MessageTestSupport.java index 20feff1c07..3571230958 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/MessageTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/MessageTestSupport.java @@ -24,61 +24,59 @@ import org.apache.activemq.command.Message; * generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public abstract class MessageTestSupport extends BaseCommandTestSupport { - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - Message info = (Message)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + Message info = (Message) object; - info.setProducerId(createProducerId("ProducerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setTransactionId(createTransactionId("TransactionId:3")); - info.setOriginalDestination(createActiveMQDestination("OriginalDestination:4")); - info.setMessageId(createMessageId("MessageId:5")); - info.setOriginalTransactionId(createTransactionId("OriginalTransactionId:6")); - info.setGroupID("GroupID:7"); - info.setGroupSequence(1); - info.setCorrelationId("CorrelationId:8"); - info.setPersistent(true); - info.setExpiration(1); - info.setPriority((byte)1); - info.setReplyTo(createActiveMQDestination("ReplyTo:9")); - info.setTimestamp(2); - info.setType("Type:10"); - { - byte data[] = "Content:11".getBytes(); - info.setContent(new org.apache.activemq.util.ByteSequence(data, 0, data.length)); - } - { - byte data[] = "MarshalledProperties:12".getBytes(); - info.setMarshalledProperties(new org.apache.activemq.util.ByteSequence(data, 0, data.length)); - } - info.setDataStructure(createDataStructure("DataStructure:13")); - info.setTargetConsumerId(createConsumerId("TargetConsumerId:14")); - info.setCompressed(false); - info.setRedeliveryCounter(2); - { - BrokerId value[] = new BrokerId[2]; - for (int i = 0; i < 2; i++) { - value[i] = createBrokerId("BrokerPath:15"); - } - info.setBrokerPath(value); - } - info.setArrival(3); - info.setUserID("UserID:16"); - info.setRecievedByDFBridge(true); - info.setDroppable(false); - { - BrokerId value[] = new BrokerId[2]; - for (int i = 0; i < 2; i++) { - value[i] = createBrokerId("Cluster:17"); - } - info.setCluster(value); - } - info.setBrokerInTime(4); - info.setBrokerOutTime(5); - } + info.setProducerId(createProducerId("ProducerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setTransactionId(createTransactionId("TransactionId:3")); + info.setOriginalDestination(createActiveMQDestination("OriginalDestination:4")); + info.setMessageId(createMessageId("MessageId:5")); + info.setOriginalTransactionId(createTransactionId("OriginalTransactionId:6")); + info.setGroupID("GroupID:7"); + info.setGroupSequence(1); + info.setCorrelationId("CorrelationId:8"); + info.setPersistent(true); + info.setExpiration(1); + info.setPriority((byte) 1); + info.setReplyTo(createActiveMQDestination("ReplyTo:9")); + info.setTimestamp(2); + info.setType("Type:10"); + { + byte data[] = "Content:11".getBytes(); + info.setContent(new org.apache.activemq.util.ByteSequence(data, 0, data.length)); + } + { + byte data[] = "MarshalledProperties:12".getBytes(); + info.setMarshalledProperties(new org.apache.activemq.util.ByteSequence(data, 0, data.length)); + } + info.setDataStructure(createDataStructure("DataStructure:13")); + info.setTargetConsumerId(createConsumerId("TargetConsumerId:14")); + info.setCompressed(false); + info.setRedeliveryCounter(2); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:15"); + } + info.setBrokerPath(value); + } + info.setArrival(3); + info.setUserID("UserID:16"); + info.setRecievedByDFBridge(true); + info.setDroppable(false); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("Cluster:17"); + } + info.setCluster(value); + } + info.setBrokerInTime(4); + info.setBrokerOutTime(5); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/NetworkBridgeFilterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/NetworkBridgeFilterTest.java index 19cb220487..b3f93076e7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/NetworkBridgeFilterTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/NetworkBridgeFilterTest.java @@ -19,34 +19,30 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.NetworkBridgeFilter; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for NetworkBridgeFilter * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class NetworkBridgeFilterTest extends DataFileGeneratorTestSupport { + public static final NetworkBridgeFilterTest SINGLETON = new NetworkBridgeFilterTest(); - public static final NetworkBridgeFilterTest SINGLETON = new NetworkBridgeFilterTest(); + public Object createObject() throws Exception { + NetworkBridgeFilter info = new NetworkBridgeFilter(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - NetworkBridgeFilter info = new NetworkBridgeFilter(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + NetworkBridgeFilter info = (NetworkBridgeFilter) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - NetworkBridgeFilter info = (NetworkBridgeFilter) object; - - info.setNetworkTTL(1); - info.setNetworkBrokerId(createBrokerId("NetworkBrokerId:1")); - } + info.setNetworkTTL(1); + info.setNetworkBrokerId(createBrokerId("NetworkBrokerId:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/PartialCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/PartialCommandTest.java index 6ad3f409b8..ef102fce1c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/PartialCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/PartialCommandTest.java @@ -19,34 +19,30 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.PartialCommand; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for PartialCommand * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class PartialCommandTest extends DataFileGeneratorTestSupport { + public static final PartialCommandTest SINGLETON = new PartialCommandTest(); - public static final PartialCommandTest SINGLETON = new PartialCommandTest(); + public Object createObject() throws Exception { + PartialCommand info = new PartialCommand(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - PartialCommand info = new PartialCommand(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + PartialCommand info = (PartialCommand) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - PartialCommand info = (PartialCommand) object; - - info.setCommandId(1); - info.setData("Data:1".getBytes()); - } + info.setCommandId(1); + info.setData("Data:1".getBytes()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ProducerAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ProducerAckTest.java index cd3610d071..84c94ad072 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ProducerAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ProducerAckTest.java @@ -18,34 +18,30 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.ProducerAck; - /** * Test case for the OpenWire marshalling for ProducerAck * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ProducerAckTest extends BaseCommandTestSupport { + public static final ProducerAckTest SINGLETON = new ProducerAckTest(); - public static final ProducerAckTest SINGLETON = new ProducerAckTest(); + public Object createObject() throws Exception { + ProducerAck info = new ProducerAck(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ProducerAck info = new ProducerAck(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ProducerAck info = (ProducerAck) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ProducerAck info = (ProducerAck) object; - - info.setProducerId(createProducerId("ProducerId:1")); - info.setSize(1); - } + info.setProducerId(createProducerId("ProducerId:1")); + info.setSize(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ProducerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ProducerIdTest.java index 438754437b..df980fb605 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ProducerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ProducerIdTest.java @@ -19,35 +19,31 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.ProducerId; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for ProducerId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ProducerIdTest extends DataFileGeneratorTestSupport { + public static final ProducerIdTest SINGLETON = new ProducerIdTest(); - public static final ProducerIdTest SINGLETON = new ProducerIdTest(); + public Object createObject() throws Exception { + ProducerId info = new ProducerId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ProducerId info = new ProducerId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ProducerId info = (ProducerId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ProducerId info = (ProducerId) object; - - info.setConnectionId("ConnectionId:1"); - info.setValue(1); - info.setSessionId(2); - } + info.setConnectionId("ConnectionId:1"); + info.setValue(1); + info.setSessionId(2); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ProducerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ProducerInfoTest.java index 4fbf05f058..e25687aea6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ProducerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ProducerInfoTest.java @@ -24,33 +24,31 @@ import org.apache.activemq.command.ProducerInfo; * auto generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public class ProducerInfoTest extends BaseCommandTestSupport { - public static final ProducerInfoTest SINGLETON = new ProducerInfoTest(); + public static final ProducerInfoTest SINGLETON = new ProducerInfoTest(); - public Object createObject() throws Exception { - ProducerInfo info = new ProducerInfo(); - populateObject(info); - return info; - } + public Object createObject() throws Exception { + ProducerInfo info = new ProducerInfo(); + populateObject(info); + return info; + } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ProducerInfo info = (ProducerInfo)object; + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ProducerInfo info = (ProducerInfo) object; - info.setProducerId(createProducerId("ProducerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - { - BrokerId value[] = new BrokerId[2]; - for (int i = 0; i < 2; i++) { - value[i] = createBrokerId("BrokerPath:3"); - } - info.setBrokerPath(value); - } - info.setDispatchAsync(true); - info.setWindowSize(1); - } + info.setProducerId(createProducerId("ProducerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:3"); + } + info.setBrokerPath(value); + } + info.setDispatchAsync(true); + info.setWindowSize(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/RemoveInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/RemoveInfoTest.java index 7bc480e061..0dd4053430 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/RemoveInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/RemoveInfoTest.java @@ -18,33 +18,29 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.RemoveInfo; - /** * Test case for the OpenWire marshalling for RemoveInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class RemoveInfoTest extends BaseCommandTestSupport { + public static final RemoveInfoTest SINGLETON = new RemoveInfoTest(); - public static final RemoveInfoTest SINGLETON = new RemoveInfoTest(); + public Object createObject() throws Exception { + RemoveInfo info = new RemoveInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - RemoveInfo info = new RemoveInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + RemoveInfo info = (RemoveInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - RemoveInfo info = (RemoveInfo) object; - - info.setObjectId(createDataStructure("ObjectId:1")); - } + info.setObjectId(createDataStructure("ObjectId:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/RemoveSubscriptionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/RemoveSubscriptionInfoTest.java index 2c85ef223c..b516f1ea1e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/RemoveSubscriptionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/RemoveSubscriptionInfoTest.java @@ -18,35 +18,31 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.RemoveSubscriptionInfo; - /** * Test case for the OpenWire marshalling for RemoveSubscriptionInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class RemoveSubscriptionInfoTest extends BaseCommandTestSupport { + public static final RemoveSubscriptionInfoTest SINGLETON = new RemoveSubscriptionInfoTest(); - public static final RemoveSubscriptionInfoTest SINGLETON = new RemoveSubscriptionInfoTest(); + public Object createObject() throws Exception { + RemoveSubscriptionInfo info = new RemoveSubscriptionInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - RemoveSubscriptionInfo info = new RemoveSubscriptionInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + RemoveSubscriptionInfo info = (RemoveSubscriptionInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - RemoveSubscriptionInfo info = (RemoveSubscriptionInfo) object; - - info.setConnectionId(createConnectionId("ConnectionId:1")); - info.setSubscriptionName("SubcriptionName:2"); - info.setClientId("ClientId:3"); - } + info.setConnectionId(createConnectionId("ConnectionId:1")); + info.setSubscriptionName("SubcriptionName:2"); + info.setClientId("ClientId:3"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ReplayCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ReplayCommandTest.java index 9e4c337fb8..fa5e6f2bbd 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ReplayCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ReplayCommandTest.java @@ -18,34 +18,30 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.ReplayCommand; - /** * Test case for the OpenWire marshalling for ReplayCommand * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ReplayCommandTest extends BaseCommandTestSupport { + public static final ReplayCommandTest SINGLETON = new ReplayCommandTest(); - public static final ReplayCommandTest SINGLETON = new ReplayCommandTest(); + public Object createObject() throws Exception { + ReplayCommand info = new ReplayCommand(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ReplayCommand info = new ReplayCommand(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ReplayCommand info = (ReplayCommand) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ReplayCommand info = (ReplayCommand) object; - - info.setFirstNakNumber(1); - info.setLastNakNumber(2); - } + info.setFirstNakNumber(1); + info.setLastNakNumber(2); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ResponseTest.java index 7dd6543918..51afa4f9d4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ResponseTest.java @@ -18,33 +18,29 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.Response; - /** * Test case for the OpenWire marshalling for Response * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ResponseTest extends BaseCommandTestSupport { + public static final ResponseTest SINGLETON = new ResponseTest(); - public static final ResponseTest SINGLETON = new ResponseTest(); + public Object createObject() throws Exception { + Response info = new Response(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - Response info = new Response(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + Response info = (Response) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - Response info = (Response) object; - - info.setCorrelationId(1); - } + info.setCorrelationId(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/SessionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/SessionIdTest.java index 136956ab95..847600bfda 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/SessionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/SessionIdTest.java @@ -19,34 +19,30 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.SessionId; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for SessionId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class SessionIdTest extends DataFileGeneratorTestSupport { + public static final SessionIdTest SINGLETON = new SessionIdTest(); - public static final SessionIdTest SINGLETON = new SessionIdTest(); + public Object createObject() throws Exception { + SessionId info = new SessionId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - SessionId info = new SessionId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + SessionId info = (SessionId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - SessionId info = (SessionId) object; - - info.setConnectionId("ConnectionId:1"); - info.setValue(1); - } + info.setConnectionId("ConnectionId:1"); + info.setValue(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/SessionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/SessionInfoTest.java index 81bed8bcfb..d89967dbb0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/SessionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/SessionInfoTest.java @@ -18,33 +18,29 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.SessionInfo; - /** * Test case for the OpenWire marshalling for SessionInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class SessionInfoTest extends BaseCommandTestSupport { + public static final SessionInfoTest SINGLETON = new SessionInfoTest(); - public static final SessionInfoTest SINGLETON = new SessionInfoTest(); + public Object createObject() throws Exception { + SessionInfo info = new SessionInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - SessionInfo info = new SessionInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + SessionInfo info = (SessionInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - SessionInfo info = (SessionInfo) object; - - info.setSessionId(createSessionId("SessionId:1")); - } + info.setSessionId(createSessionId("SessionId:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ShutdownInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ShutdownInfoTest.java index 2c8c03fb99..0c1b1ba9a1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ShutdownInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/ShutdownInfoTest.java @@ -18,32 +18,28 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.ShutdownInfo; - /** * Test case for the OpenWire marshalling for ShutdownInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ShutdownInfoTest extends BaseCommandTestSupport { + public static final ShutdownInfoTest SINGLETON = new ShutdownInfoTest(); - public static final ShutdownInfoTest SINGLETON = new ShutdownInfoTest(); + public Object createObject() throws Exception { + ShutdownInfo info = new ShutdownInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ShutdownInfo info = new ShutdownInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ShutdownInfo info = (ShutdownInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ShutdownInfo info = (ShutdownInfo) object; - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/SubscriptionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/SubscriptionInfoTest.java index d8da085a71..2960f82a29 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/SubscriptionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/SubscriptionInfoTest.java @@ -19,37 +19,33 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.SubscriptionInfo; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for SubscriptionInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class SubscriptionInfoTest extends DataFileGeneratorTestSupport { + public static final SubscriptionInfoTest SINGLETON = new SubscriptionInfoTest(); - public static final SubscriptionInfoTest SINGLETON = new SubscriptionInfoTest(); + public Object createObject() throws Exception { + SubscriptionInfo info = new SubscriptionInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - SubscriptionInfo info = new SubscriptionInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + SubscriptionInfo info = (SubscriptionInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - SubscriptionInfo info = (SubscriptionInfo) object; - - info.setClientId("ClientId:1"); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setSelector("Selector:3"); - info.setSubscriptionName("SubcriptionName:4"); - info.setSubscribedDestination(createActiveMQDestination("SubscribedDestination:5")); - } + info.setClientId("ClientId:1"); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setSelector("Selector:3"); + info.setSubscriptionName("SubcriptionName:4"); + info.setSubscribedDestination(createActiveMQDestination("SubscribedDestination:5")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/TransactionIdTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/TransactionIdTestSupport.java index ce874bbe7e..62c4ffe545 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/TransactionIdTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/TransactionIdTestSupport.java @@ -19,24 +19,20 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.TransactionId; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; - /** * Test case for the OpenWire marshalling for TransactionId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public abstract class TransactionIdTestSupport extends DataFileGeneratorTestSupport { + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + TransactionId info = (TransactionId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - TransactionId info = (TransactionId) object; - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/TransactionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/TransactionInfoTest.java index 8daad3904f..8619cc1b4a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/TransactionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/TransactionInfoTest.java @@ -18,35 +18,31 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.TransactionInfo; - /** * Test case for the OpenWire marshalling for TransactionInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class TransactionInfoTest extends BaseCommandTestSupport { + public static final TransactionInfoTest SINGLETON = new TransactionInfoTest(); - public static final TransactionInfoTest SINGLETON = new TransactionInfoTest(); + public Object createObject() throws Exception { + TransactionInfo info = new TransactionInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - TransactionInfo info = new TransactionInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + TransactionInfo info = (TransactionInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - TransactionInfo info = (TransactionInfo) object; - - info.setConnectionId(createConnectionId("ConnectionId:1")); - info.setTransactionId(createTransactionId("TransactionId:2")); - info.setType((byte) 1); - } + info.setConnectionId(createConnectionId("ConnectionId:1")); + info.setTransactionId(createTransactionId("TransactionId:2")); + info.setType((byte) 1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/XATransactionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/XATransactionIdTest.java index e9d36e375b..9b47863161 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/XATransactionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/XATransactionIdTest.java @@ -18,35 +18,31 @@ package org.apache.activemq.openwire.v3; import org.apache.activemq.command.XATransactionId; - /** * Test case for the OpenWire marshalling for XATransactionId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class XATransactionIdTest extends TransactionIdTestSupport { + public static final XATransactionIdTest SINGLETON = new XATransactionIdTest(); - public static final XATransactionIdTest SINGLETON = new XATransactionIdTest(); + public Object createObject() throws Exception { + XATransactionId info = new XATransactionId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - XATransactionId info = new XATransactionId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + XATransactionId info = (XATransactionId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - XATransactionId info = (XATransactionId) object; - - info.setFormatId(1); - info.setGlobalTransactionId("GlobalTransactionId:1".getBytes()); - info.setBranchQualifier("BranchQualifier:2".getBytes()); - } + info.setFormatId(1); + info.setGlobalTransactionId("GlobalTransactionId:1".getBytes()); + info.setBranchQualifier("BranchQualifier:2".getBytes()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/BaseCommandTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/BaseCommandTestSupport.java index f281a94c1d..bf60757e86 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/BaseCommandTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/BaseCommandTestSupport.java @@ -24,16 +24,14 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; * auto generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * - * */ public abstract class BaseCommandTestSupport extends DataFileGeneratorTestSupport { - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - BaseCommand info = (BaseCommand)object; - info.setCommandId(1); - info.setResponseRequired(true); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + BaseCommand info = (BaseCommand) object; + info.setCommandId(1); + info.setResponseRequired(true); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/BrokerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/BrokerIdTest.java index 97cf0488b4..52fc6cafea 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/BrokerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/BrokerIdTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for BrokerId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class BrokerIdTest extends DataFileGeneratorTestSupport { + public static BrokerIdTest SINGLETON = new BrokerIdTest(); - public static BrokerIdTest SINGLETON = new BrokerIdTest(); + public Object createObject() throws Exception { + BrokerId info = new BrokerId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - BrokerId info = new BrokerId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + BrokerId info = (BrokerId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - BrokerId info = (BrokerId) object; - - info.setValue("Value:1"); - } + info.setValue("Value:1"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/BrokerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/BrokerInfoTest.java index b76df14501..21fea6f0f5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/BrokerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/BrokerInfoTest.java @@ -24,50 +24,46 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for BrokerInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class BrokerInfoTest extends BaseCommandTestSupport { + public static BrokerInfoTest SINGLETON = new BrokerInfoTest(); - public static BrokerInfoTest SINGLETON = new BrokerInfoTest(); + public Object createObject() throws Exception { + BrokerInfo info = new BrokerInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - BrokerInfo info = new BrokerInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + BrokerInfo info = (BrokerInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - BrokerInfo info = (BrokerInfo) object; - - info.setBrokerId(createBrokerId("BrokerId:1")); - info.setBrokerURL("BrokerURL:2"); - { - BrokerInfo value[] = new BrokerInfo[0]; - for( int i=0; i < 0; i++ ) { - value[i] = createBrokerInfo("PeerBrokerInfos:3"); - } - info.setPeerBrokerInfos(value); - } - info.setBrokerName("BrokerName:4"); - info.setSlaveBroker(true); - info.setMasterBroker(false); - info.setFaultTolerantConfiguration(true); - info.setDuplexConnection(false); - info.setNetworkConnection(true); - info.setConnectionId(1); - info.setBrokerUploadUrl("BrokerUploadUrl:5"); - info.setNetworkProperties("NetworkProperties:6"); - } + info.setBrokerId(createBrokerId("BrokerId:1")); + info.setBrokerURL("BrokerURL:2"); + { + BrokerInfo value[] = new BrokerInfo[0]; + for (int i = 0; i < 0; i++) { + value[i] = createBrokerInfo("PeerBrokerInfos:3"); + } + info.setPeerBrokerInfos(value); + } + info.setBrokerName("BrokerName:4"); + info.setSlaveBroker(true); + info.setMasterBroker(false); + info.setFaultTolerantConfiguration(true); + info.setDuplexConnection(false); + info.setNetworkConnection(true); + info.setConnectionId(1); + info.setBrokerUploadUrl("BrokerUploadUrl:5"); + info.setNetworkProperties("NetworkProperties:6"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConnectionControlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConnectionControlTest.java index 7250787861..06fc534130 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConnectionControlTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConnectionControlTest.java @@ -24,37 +24,33 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ConnectionControl * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConnectionControlTest extends BaseCommandTestSupport { + public static ConnectionControlTest SINGLETON = new ConnectionControlTest(); - public static ConnectionControlTest SINGLETON = new ConnectionControlTest(); + public Object createObject() throws Exception { + ConnectionControl info = new ConnectionControl(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConnectionControl info = new ConnectionControl(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConnectionControl info = (ConnectionControl) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionControl info = (ConnectionControl) object; - - info.setClose(true); - info.setExit(false); - info.setFaultTolerant(true); - info.setResume(false); - info.setSuspend(true); - } + info.setClose(true); + info.setExit(false); + info.setFaultTolerant(true); + info.setResume(false); + info.setSuspend(true); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConnectionErrorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConnectionErrorTest.java index 56d4c89f97..43be7f0ab4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConnectionErrorTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConnectionErrorTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ConnectionError * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConnectionErrorTest extends BaseCommandTestSupport { + public static ConnectionErrorTest SINGLETON = new ConnectionErrorTest(); - public static ConnectionErrorTest SINGLETON = new ConnectionErrorTest(); + public Object createObject() throws Exception { + ConnectionError info = new ConnectionError(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConnectionError info = new ConnectionError(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConnectionError info = (ConnectionError) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionError info = (ConnectionError) object; - - info.setException(createThrowable("Exception:1")); - info.setConnectionId(createConnectionId("ConnectionId:2")); - } + info.setException(createThrowable("Exception:1")); + info.setConnectionId(createConnectionId("ConnectionId:2")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConnectionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConnectionIdTest.java index 9f25aa7321..a04b0c4bca 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConnectionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConnectionIdTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ConnectionId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConnectionIdTest extends DataFileGeneratorTestSupport { + public static ConnectionIdTest SINGLETON = new ConnectionIdTest(); - public static ConnectionIdTest SINGLETON = new ConnectionIdTest(); + public Object createObject() throws Exception { + ConnectionId info = new ConnectionId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConnectionId info = new ConnectionId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConnectionId info = (ConnectionId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionId info = (ConnectionId) object; - - info.setValue("Value:1"); - } + info.setValue("Value:1"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConnectionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConnectionInfoTest.java index 56512a6a34..333153424f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConnectionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConnectionInfoTest.java @@ -24,46 +24,42 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ConnectionInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConnectionInfoTest extends BaseCommandTestSupport { + public static ConnectionInfoTest SINGLETON = new ConnectionInfoTest(); - public static ConnectionInfoTest SINGLETON = new ConnectionInfoTest(); + public Object createObject() throws Exception { + ConnectionInfo info = new ConnectionInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConnectionInfo info = new ConnectionInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConnectionInfo info = (ConnectionInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionInfo info = (ConnectionInfo) object; - - info.setConnectionId(createConnectionId("ConnectionId:1")); - info.setClientId("ClientId:2"); - info.setPassword("Password:3"); - info.setUserName("UserName:4"); - { - BrokerId value[] = new BrokerId[2]; - for( int i=0; i < 2; i++ ) { - value[i] = createBrokerId("BrokerPath:5"); - } - info.setBrokerPath(value); - } - info.setBrokerMasterConnector(true); - info.setManageable(false); - info.setClientMaster(true); - } + info.setConnectionId(createConnectionId("ConnectionId:1")); + info.setClientId("ClientId:2"); + info.setPassword("Password:3"); + info.setUserName("UserName:4"); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:5"); + } + info.setBrokerPath(value); + } + info.setBrokerMasterConnector(true); + info.setManageable(false); + info.setClientMaster(true); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConsumerControlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConsumerControlTest.java index e82fdccae2..57d722e0a2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConsumerControlTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConsumerControlTest.java @@ -24,38 +24,34 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ConsumerControl * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConsumerControlTest extends BaseCommandTestSupport { + public static ConsumerControlTest SINGLETON = new ConsumerControlTest(); - public static ConsumerControlTest SINGLETON = new ConsumerControlTest(); + public Object createObject() throws Exception { + ConsumerControl info = new ConsumerControl(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConsumerControl info = new ConsumerControl(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConsumerControl info = (ConsumerControl) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConsumerControl info = (ConsumerControl) object; - - info.setClose(true); - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setPrefetch(1); - info.setFlush(false); - info.setStart(true); - info.setStop(false); - } + info.setClose(true); + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setPrefetch(1); + info.setFlush(false); + info.setStart(true); + info.setStop(false); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConsumerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConsumerIdTest.java index cd26cb756d..5142821fc6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConsumerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConsumerIdTest.java @@ -24,35 +24,31 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ConsumerId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConsumerIdTest extends DataFileGeneratorTestSupport { + public static ConsumerIdTest SINGLETON = new ConsumerIdTest(); - public static ConsumerIdTest SINGLETON = new ConsumerIdTest(); + public Object createObject() throws Exception { + ConsumerId info = new ConsumerId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConsumerId info = new ConsumerId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConsumerId info = (ConsumerId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConsumerId info = (ConsumerId) object; - - info.setConnectionId("ConnectionId:1"); - info.setSessionId(1); - info.setValue(2); - } + info.setConnectionId("ConnectionId:1"); + info.setSessionId(1); + info.setValue(2); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConsumerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConsumerInfoTest.java index 277cbf57a8..6af8133000 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConsumerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ConsumerInfoTest.java @@ -24,62 +24,58 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ConsumerInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConsumerInfoTest extends BaseCommandTestSupport { + public static ConsumerInfoTest SINGLETON = new ConsumerInfoTest(); - public static ConsumerInfoTest SINGLETON = new ConsumerInfoTest(); + public Object createObject() throws Exception { + ConsumerInfo info = new ConsumerInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConsumerInfo info = new ConsumerInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConsumerInfo info = (ConsumerInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConsumerInfo info = (ConsumerInfo) object; - - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setBrowser(true); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setPrefetchSize(1); - info.setMaximumPendingMessageLimit(2); - info.setDispatchAsync(false); - info.setSelector("Selector:3"); - info.setSubscriptionName("SubscriptionName:4"); - info.setNoLocal(true); - info.setExclusive(false); - info.setRetroactive(true); - info.setPriority((byte) 1); - { - BrokerId value[] = new BrokerId[2]; - for( int i=0; i < 2; i++ ) { - value[i] = createBrokerId("BrokerPath:5"); - } - info.setBrokerPath(value); - } - info.setAdditionalPredicate(createBooleanExpression("AdditionalPredicate:6")); - info.setNetworkSubscription(false); - info.setOptimizedAcknowledge(true); - info.setNoRangeAcks(false); - { - ConsumerId value[] = new ConsumerId[2]; - for( int i=0; i < 2; i++ ) { - value[i] = createConsumerId("NetworkConsumerPath:7"); - } - info.setNetworkConsumerPath(value); - } - } + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setBrowser(true); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setPrefetchSize(1); + info.setMaximumPendingMessageLimit(2); + info.setDispatchAsync(false); + info.setSelector("Selector:3"); + info.setSubscriptionName("SubscriptionName:4"); + info.setNoLocal(true); + info.setExclusive(false); + info.setRetroactive(true); + info.setPriority((byte) 1); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:5"); + } + info.setBrokerPath(value); + } + info.setAdditionalPredicate(createBooleanExpression("AdditionalPredicate:6")); + info.setNetworkSubscription(false); + info.setOptimizedAcknowledge(true); + info.setNoRangeAcks(false); + { + ConsumerId value[] = new ConsumerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createConsumerId("NetworkConsumerPath:7"); + } + info.setNetworkConsumerPath(value); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ControlCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ControlCommandTest.java index 850c663e67..e487428618 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ControlCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ControlCommandTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ControlCommand * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ControlCommandTest extends BaseCommandTestSupport { + public static ControlCommandTest SINGLETON = new ControlCommandTest(); - public static ControlCommandTest SINGLETON = new ControlCommandTest(); + public Object createObject() throws Exception { + ControlCommand info = new ControlCommand(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ControlCommand info = new ControlCommand(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ControlCommand info = (ControlCommand) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ControlCommand info = (ControlCommand) object; - - info.setCommand("Command:1"); - } + info.setCommand("Command:1"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/DataArrayResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/DataArrayResponseTest.java index 20fdd6baf1..e66384377f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/DataArrayResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/DataArrayResponseTest.java @@ -24,39 +24,35 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for DataArrayResponse * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class DataArrayResponseTest extends ResponseTest { + public static DataArrayResponseTest SINGLETON = new DataArrayResponseTest(); - public static DataArrayResponseTest SINGLETON = new DataArrayResponseTest(); + public Object createObject() throws Exception { + DataArrayResponse info = new DataArrayResponse(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - DataArrayResponse info = new DataArrayResponse(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + DataArrayResponse info = (DataArrayResponse) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DataArrayResponse info = (DataArrayResponse) object; - - { - DataStructure value[] = new DataStructure[2]; - for( int i=0; i < 2; i++ ) { - value[i] = createDataStructure("Data:1"); - } - info.setData(value); - } - } + { + DataStructure value[] = new DataStructure[2]; + for (int i = 0; i < 2; i++) { + value[i] = createDataStructure("Data:1"); + } + info.setData(value); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/DataResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/DataResponseTest.java index d7c4c3d8ea..9dd492176b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/DataResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/DataResponseTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for DataResponse * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class DataResponseTest extends ResponseTest { + public static DataResponseTest SINGLETON = new DataResponseTest(); - public static DataResponseTest SINGLETON = new DataResponseTest(); + public Object createObject() throws Exception { + DataResponse info = new DataResponse(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - DataResponse info = new DataResponse(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + DataResponse info = (DataResponse) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DataResponse info = (DataResponse) object; - - info.setData(createDataStructure("Data:1")); - } + info.setData(createDataStructure("Data:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/DestinationInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/DestinationInfoTest.java index cb9fa0a019..8eae2289ac 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/DestinationInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/DestinationInfoTest.java @@ -24,43 +24,39 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for DestinationInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class DestinationInfoTest extends BaseCommandTestSupport { + public static DestinationInfoTest SINGLETON = new DestinationInfoTest(); - public static DestinationInfoTest SINGLETON = new DestinationInfoTest(); + public Object createObject() throws Exception { + DestinationInfo info = new DestinationInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - DestinationInfo info = new DestinationInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + DestinationInfo info = (DestinationInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DestinationInfo info = (DestinationInfo) object; - - info.setConnectionId(createConnectionId("ConnectionId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setOperationType((byte) 1); - info.setTimeout(1); - { - BrokerId value[] = new BrokerId[2]; - for( int i=0; i < 2; i++ ) { - value[i] = createBrokerId("BrokerPath:3"); - } - info.setBrokerPath(value); - } - } + info.setConnectionId(createConnectionId("ConnectionId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setOperationType((byte) 1); + info.setTimeout(1); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:3"); + } + info.setBrokerPath(value); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/DiscoveryEventTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/DiscoveryEventTest.java index e8dbb59386..55e546054b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/DiscoveryEventTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/DiscoveryEventTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for DiscoveryEvent * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class DiscoveryEventTest extends DataFileGeneratorTestSupport { + public static DiscoveryEventTest SINGLETON = new DiscoveryEventTest(); - public static DiscoveryEventTest SINGLETON = new DiscoveryEventTest(); + public Object createObject() throws Exception { + DiscoveryEvent info = new DiscoveryEvent(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - DiscoveryEvent info = new DiscoveryEvent(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + DiscoveryEvent info = (DiscoveryEvent) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DiscoveryEvent info = (DiscoveryEvent) object; - - info.setServiceName("ServiceName:1"); - info.setBrokerName("BrokerName:2"); - } + info.setServiceName("ServiceName:1"); + info.setBrokerName("BrokerName:2"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ExceptionResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ExceptionResponseTest.java index 320b22cc57..e8ff554481 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ExceptionResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ExceptionResponseTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ExceptionResponse * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ExceptionResponseTest extends ResponseTest { + public static ExceptionResponseTest SINGLETON = new ExceptionResponseTest(); - public static ExceptionResponseTest SINGLETON = new ExceptionResponseTest(); + public Object createObject() throws Exception { + ExceptionResponse info = new ExceptionResponse(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ExceptionResponse info = new ExceptionResponse(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ExceptionResponse info = (ExceptionResponse) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ExceptionResponse info = (ExceptionResponse) object; - - info.setException(createThrowable("Exception:1")); - } + info.setException(createThrowable("Exception:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/FlushCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/FlushCommandTest.java index 330b6af1e9..961087ca3a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/FlushCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/FlushCommandTest.java @@ -24,32 +24,28 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for FlushCommand * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class FlushCommandTest extends BaseCommandTestSupport { + public static FlushCommandTest SINGLETON = new FlushCommandTest(); - public static FlushCommandTest SINGLETON = new FlushCommandTest(); + public Object createObject() throws Exception { + FlushCommand info = new FlushCommand(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - FlushCommand info = new FlushCommand(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + FlushCommand info = (FlushCommand) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - FlushCommand info = (FlushCommand) object; - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/IntegerResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/IntegerResponseTest.java index 98c8e90d8c..1f71ddde1d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/IntegerResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/IntegerResponseTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for IntegerResponse * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class IntegerResponseTest extends ResponseTest { + public static IntegerResponseTest SINGLETON = new IntegerResponseTest(); - public static IntegerResponseTest SINGLETON = new IntegerResponseTest(); + public Object createObject() throws Exception { + IntegerResponse info = new IntegerResponse(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - IntegerResponse info = new IntegerResponse(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + IntegerResponse info = (IntegerResponse) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - IntegerResponse info = (IntegerResponse) object; - - info.setResult(1); - } + info.setResult(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/JournalQueueAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/JournalQueueAckTest.java index 1d7cba69e1..f5f09f9b3e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/JournalQueueAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/JournalQueueAckTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for JournalQueueAck * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class JournalQueueAckTest extends DataFileGeneratorTestSupport { + public static JournalQueueAckTest SINGLETON = new JournalQueueAckTest(); - public static JournalQueueAckTest SINGLETON = new JournalQueueAckTest(); + public Object createObject() throws Exception { + JournalQueueAck info = new JournalQueueAck(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - JournalQueueAck info = new JournalQueueAck(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + JournalQueueAck info = (JournalQueueAck) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalQueueAck info = (JournalQueueAck) object; - - info.setDestination(createActiveMQDestination("Destination:1")); - info.setMessageAck(createMessageAck("MessageAck:2")); - } + info.setDestination(createActiveMQDestination("Destination:1")); + info.setMessageAck(createMessageAck("MessageAck:2")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/JournalTopicAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/JournalTopicAckTest.java index ece67794dc..f4361e588c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/JournalTopicAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/JournalTopicAckTest.java @@ -24,38 +24,34 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for JournalTopicAck * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class JournalTopicAckTest extends DataFileGeneratorTestSupport { + public static JournalTopicAckTest SINGLETON = new JournalTopicAckTest(); - public static JournalTopicAckTest SINGLETON = new JournalTopicAckTest(); + public Object createObject() throws Exception { + JournalTopicAck info = new JournalTopicAck(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - JournalTopicAck info = new JournalTopicAck(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + JournalTopicAck info = (JournalTopicAck) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalTopicAck info = (JournalTopicAck) object; - - info.setDestination(createActiveMQDestination("Destination:1")); - info.setMessageId(createMessageId("MessageId:2")); - info.setMessageSequenceId(1); - info.setSubscritionName("SubscritionName:3"); - info.setClientId("ClientId:4"); - info.setTransactionId(createTransactionId("TransactionId:5")); - } + info.setDestination(createActiveMQDestination("Destination:1")); + info.setMessageId(createMessageId("MessageId:2")); + info.setMessageSequenceId(1); + info.setSubscritionName("SubscritionName:3"); + info.setClientId("ClientId:4"); + info.setTransactionId(createTransactionId("TransactionId:5")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/JournalTraceTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/JournalTraceTest.java index 125d9844ee..091ace2a2b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/JournalTraceTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/JournalTraceTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for JournalTrace * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class JournalTraceTest extends DataFileGeneratorTestSupport { + public static JournalTraceTest SINGLETON = new JournalTraceTest(); - public static JournalTraceTest SINGLETON = new JournalTraceTest(); + public Object createObject() throws Exception { + JournalTrace info = new JournalTrace(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - JournalTrace info = new JournalTrace(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + JournalTrace info = (JournalTrace) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalTrace info = (JournalTrace) object; - - info.setMessage("Message:1"); - } + info.setMessage("Message:1"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/JournalTransactionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/JournalTransactionTest.java index 3dc47ab73b..1bfedd1233 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/JournalTransactionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/JournalTransactionTest.java @@ -24,35 +24,31 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for JournalTransaction * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class JournalTransactionTest extends DataFileGeneratorTestSupport { + public static JournalTransactionTest SINGLETON = new JournalTransactionTest(); - public static JournalTransactionTest SINGLETON = new JournalTransactionTest(); + public Object createObject() throws Exception { + JournalTransaction info = new JournalTransaction(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - JournalTransaction info = new JournalTransaction(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + JournalTransaction info = (JournalTransaction) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalTransaction info = (JournalTransaction) object; - - info.setTransactionId(createTransactionId("TransactionId:1")); - info.setType((byte) 1); - info.setWasPrepared(true); - } + info.setTransactionId(createTransactionId("TransactionId:1")); + info.setType((byte) 1); + info.setWasPrepared(true); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/KeepAliveInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/KeepAliveInfoTest.java index d804f5006f..46d50c5cf4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/KeepAliveInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/KeepAliveInfoTest.java @@ -24,32 +24,28 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for KeepAliveInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class KeepAliveInfoTest extends BaseCommandTestSupport { + public static KeepAliveInfoTest SINGLETON = new KeepAliveInfoTest(); - public static KeepAliveInfoTest SINGLETON = new KeepAliveInfoTest(); + public Object createObject() throws Exception { + KeepAliveInfo info = new KeepAliveInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - KeepAliveInfo info = new KeepAliveInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + KeepAliveInfo info = (KeepAliveInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - KeepAliveInfo info = (KeepAliveInfo) object; - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/LastPartialCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/LastPartialCommandTest.java index 81c1eb3101..9721de85ae 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/LastPartialCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/LastPartialCommandTest.java @@ -24,32 +24,28 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for LastPartialCommand * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class LastPartialCommandTest extends PartialCommandTest { + public static LastPartialCommandTest SINGLETON = new LastPartialCommandTest(); - public static LastPartialCommandTest SINGLETON = new LastPartialCommandTest(); + public Object createObject() throws Exception { + LastPartialCommand info = new LastPartialCommand(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - LastPartialCommand info = new LastPartialCommand(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + LastPartialCommand info = (LastPartialCommand) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - LastPartialCommand info = (LastPartialCommand) object; - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/LocalTransactionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/LocalTransactionIdTest.java index 544220b6dc..2a0e32545e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/LocalTransactionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/LocalTransactionIdTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for LocalTransactionId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class LocalTransactionIdTest extends TransactionIdTestSupport { + public static LocalTransactionIdTest SINGLETON = new LocalTransactionIdTest(); - public static LocalTransactionIdTest SINGLETON = new LocalTransactionIdTest(); + public Object createObject() throws Exception { + LocalTransactionId info = new LocalTransactionId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - LocalTransactionId info = new LocalTransactionId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + LocalTransactionId info = (LocalTransactionId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - LocalTransactionId info = (LocalTransactionId) object; - - info.setValue(1); - info.setConnectionId(createConnectionId("ConnectionId:1")); - } + info.setValue(1); + info.setConnectionId(createConnectionId("ConnectionId:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/MessageAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/MessageAckTest.java index 440bfdf092..de815ed49b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/MessageAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/MessageAckTest.java @@ -24,39 +24,35 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for MessageAck * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class MessageAckTest extends BaseCommandTestSupport { + public static MessageAckTest SINGLETON = new MessageAckTest(); - public static MessageAckTest SINGLETON = new MessageAckTest(); + public Object createObject() throws Exception { + MessageAck info = new MessageAck(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - MessageAck info = new MessageAck(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessageAck info = (MessageAck) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageAck info = (MessageAck) object; - - info.setDestination(createActiveMQDestination("Destination:1")); - info.setTransactionId(createTransactionId("TransactionId:2")); - info.setConsumerId(createConsumerId("ConsumerId:3")); - info.setAckType((byte) 1); - info.setFirstMessageId(createMessageId("FirstMessageId:4")); - info.setLastMessageId(createMessageId("LastMessageId:5")); - info.setMessageCount(1); - } + info.setDestination(createActiveMQDestination("Destination:1")); + info.setTransactionId(createTransactionId("TransactionId:2")); + info.setConsumerId(createConsumerId("ConsumerId:3")); + info.setAckType((byte) 1); + info.setFirstMessageId(createMessageId("FirstMessageId:4")); + info.setLastMessageId(createMessageId("LastMessageId:5")); + info.setMessageCount(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/MessageDispatchNotificationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/MessageDispatchNotificationTest.java index bfa23002c1..5ceaa0db64 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/MessageDispatchNotificationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/MessageDispatchNotificationTest.java @@ -24,36 +24,32 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for MessageDispatchNotification * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class MessageDispatchNotificationTest extends BaseCommandTestSupport { + public static MessageDispatchNotificationTest SINGLETON = new MessageDispatchNotificationTest(); - public static MessageDispatchNotificationTest SINGLETON = new MessageDispatchNotificationTest(); + public Object createObject() throws Exception { + MessageDispatchNotification info = new MessageDispatchNotification(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - MessageDispatchNotification info = new MessageDispatchNotification(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessageDispatchNotification info = (MessageDispatchNotification) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageDispatchNotification info = (MessageDispatchNotification) object; - - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setDeliverySequenceId(1); - info.setMessageId(createMessageId("MessageId:3")); - } + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setDeliverySequenceId(1); + info.setMessageId(createMessageId("MessageId:3")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/MessageDispatchTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/MessageDispatchTest.java index 41e40f7982..9faf35bc18 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/MessageDispatchTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/MessageDispatchTest.java @@ -24,36 +24,32 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for MessageDispatch * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class MessageDispatchTest extends BaseCommandTestSupport { + public static MessageDispatchTest SINGLETON = new MessageDispatchTest(); - public static MessageDispatchTest SINGLETON = new MessageDispatchTest(); + public Object createObject() throws Exception { + MessageDispatch info = new MessageDispatch(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - MessageDispatch info = new MessageDispatch(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessageDispatch info = (MessageDispatch) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageDispatch info = (MessageDispatch) object; - - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setMessage(createMessage("Message:3")); - info.setRedeliveryCounter(1); - } + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setMessage(createMessage("Message:3")); + info.setRedeliveryCounter(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/MessageIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/MessageIdTest.java index fcdc62f728..26a5aa514d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/MessageIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/MessageIdTest.java @@ -24,35 +24,31 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for MessageId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class MessageIdTest extends DataFileGeneratorTestSupport { + public static MessageIdTest SINGLETON = new MessageIdTest(); - public static MessageIdTest SINGLETON = new MessageIdTest(); + public Object createObject() throws Exception { + MessageId info = new MessageId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - MessageId info = new MessageId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessageId info = (MessageId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageId info = (MessageId) object; - - info.setProducerId(createProducerId("ProducerId:1")); - info.setProducerSequenceId(1); - info.setBrokerSequenceId(2); - } + info.setProducerId(createProducerId("ProducerId:1")); + info.setProducerSequenceId(1); + info.setBrokerSequenceId(2); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/MessagePullTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/MessagePullTest.java index f07f82774f..e841784d57 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/MessagePullTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/MessagePullTest.java @@ -24,37 +24,33 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for MessagePull * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class MessagePullTest extends BaseCommandTestSupport { + public static MessagePullTest SINGLETON = new MessagePullTest(); - public static MessagePullTest SINGLETON = new MessagePullTest(); + public Object createObject() throws Exception { + MessagePull info = new MessagePull(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - MessagePull info = new MessagePull(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessagePull info = (MessagePull) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessagePull info = (MessagePull) object; - - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setTimeout(1); - info.setCorrelationId("CorrelationId:3"); - info.setMessageId(createMessageId("MessageId:4")); - } + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setTimeout(1); + info.setCorrelationId("CorrelationId:3"); + info.setMessageId(createMessageId("MessageId:4")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/MessageTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/MessageTestSupport.java index f45b80c7d4..4f1bd36252 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/MessageTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/MessageTestSupport.java @@ -19,71 +19,67 @@ package org.apache.activemq.openwire.v4; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for Message * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public abstract class MessageTestSupport extends BaseCommandTestSupport { + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + Message info = (Message) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - Message info = (Message) object; - - info.setProducerId(createProducerId("ProducerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setTransactionId(createTransactionId("TransactionId:3")); - info.setOriginalDestination(createActiveMQDestination("OriginalDestination:4")); - info.setMessageId(createMessageId("MessageId:5")); - info.setOriginalTransactionId(createTransactionId("OriginalTransactionId:6")); - info.setGroupID("GroupID:7"); - info.setGroupSequence(1); - info.setCorrelationId("CorrelationId:8"); - info.setPersistent(true); - info.setExpiration(1); - info.setPriority((byte) 1); - info.setReplyTo(createActiveMQDestination("ReplyTo:9")); - info.setTimestamp(2); - info.setType("Type:10"); - { - byte data[] = "Content:11".getBytes(); - info.setContent(new org.apache.activemq.util.ByteSequence(data,0,data.length)); -} - { - byte data[] = "MarshalledProperties:12".getBytes(); - info.setMarshalledProperties(new org.apache.activemq.util.ByteSequence(data,0,data.length)); -} - info.setDataStructure(createDataStructure("DataStructure:13")); - info.setTargetConsumerId(createConsumerId("TargetConsumerId:14")); - info.setCompressed(false); - info.setRedeliveryCounter(2); - { - BrokerId value[] = new BrokerId[2]; - for( int i=0; i < 2; i++ ) { - value[i] = createBrokerId("BrokerPath:15"); - } - info.setBrokerPath(value); - } - info.setArrival(3); - info.setUserID("UserID:16"); - info.setRecievedByDFBridge(true); - info.setDroppable(false); - { - BrokerId value[] = new BrokerId[2]; - for( int i=0; i < 2; i++ ) { - value[i] = createBrokerId("Cluster:17"); - } - info.setCluster(value); - } - info.setBrokerInTime(4); - info.setBrokerOutTime(5); - } + info.setProducerId(createProducerId("ProducerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setTransactionId(createTransactionId("TransactionId:3")); + info.setOriginalDestination(createActiveMQDestination("OriginalDestination:4")); + info.setMessageId(createMessageId("MessageId:5")); + info.setOriginalTransactionId(createTransactionId("OriginalTransactionId:6")); + info.setGroupID("GroupID:7"); + info.setGroupSequence(1); + info.setCorrelationId("CorrelationId:8"); + info.setPersistent(true); + info.setExpiration(1); + info.setPriority((byte) 1); + info.setReplyTo(createActiveMQDestination("ReplyTo:9")); + info.setTimestamp(2); + info.setType("Type:10"); + { + byte data[] = "Content:11".getBytes(); + info.setContent(new org.apache.activemq.util.ByteSequence(data, 0, data.length)); + } + { + byte data[] = "MarshalledProperties:12".getBytes(); + info.setMarshalledProperties(new org.apache.activemq.util.ByteSequence(data, 0, data.length)); + } + info.setDataStructure(createDataStructure("DataStructure:13")); + info.setTargetConsumerId(createConsumerId("TargetConsumerId:14")); + info.setCompressed(false); + info.setRedeliveryCounter(2); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:15"); + } + info.setBrokerPath(value); + } + info.setArrival(3); + info.setUserID("UserID:16"); + info.setRecievedByDFBridge(true); + info.setDroppable(false); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("Cluster:17"); + } + info.setCluster(value); + } + info.setBrokerInTime(4); + info.setBrokerOutTime(5); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/NetworkBridgeFilterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/NetworkBridgeFilterTest.java index e07dc530eb..0b736cab41 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/NetworkBridgeFilterTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/NetworkBridgeFilterTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for NetworkBridgeFilter * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class NetworkBridgeFilterTest extends DataFileGeneratorTestSupport { + public static NetworkBridgeFilterTest SINGLETON = new NetworkBridgeFilterTest(); - public static NetworkBridgeFilterTest SINGLETON = new NetworkBridgeFilterTest(); + public Object createObject() throws Exception { + NetworkBridgeFilter info = new NetworkBridgeFilter(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - NetworkBridgeFilter info = new NetworkBridgeFilter(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + NetworkBridgeFilter info = (NetworkBridgeFilter) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - NetworkBridgeFilter info = (NetworkBridgeFilter) object; - - info.setNetworkTTL(1); - info.setNetworkBrokerId(createBrokerId("NetworkBrokerId:1")); - } + info.setNetworkTTL(1); + info.setNetworkBrokerId(createBrokerId("NetworkBrokerId:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/PartialCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/PartialCommandTest.java index a6e1f4790d..9eebbeb9f1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/PartialCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/PartialCommandTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for PartialCommand * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class PartialCommandTest extends DataFileGeneratorTestSupport { + public static PartialCommandTest SINGLETON = new PartialCommandTest(); - public static PartialCommandTest SINGLETON = new PartialCommandTest(); + public Object createObject() throws Exception { + PartialCommand info = new PartialCommand(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - PartialCommand info = new PartialCommand(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + PartialCommand info = (PartialCommand) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - PartialCommand info = (PartialCommand) object; - - info.setCommandId(1); - info.setData("Data:1".getBytes()); - } + info.setCommandId(1); + info.setData("Data:1".getBytes()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ProducerAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ProducerAckTest.java index c2de9581c0..8d8e83ca77 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ProducerAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ProducerAckTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ProducerAck * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ProducerAckTest extends BaseCommandTestSupport { + public static ProducerAckTest SINGLETON = new ProducerAckTest(); - public static ProducerAckTest SINGLETON = new ProducerAckTest(); + public Object createObject() throws Exception { + ProducerAck info = new ProducerAck(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ProducerAck info = new ProducerAck(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ProducerAck info = (ProducerAck) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ProducerAck info = (ProducerAck) object; - - info.setProducerId(createProducerId("ProducerId:1")); - info.setSize(1); - } + info.setProducerId(createProducerId("ProducerId:1")); + info.setSize(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ProducerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ProducerIdTest.java index a75953df78..fee5717e0a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ProducerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ProducerIdTest.java @@ -24,35 +24,31 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ProducerId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ProducerIdTest extends DataFileGeneratorTestSupport { + public static ProducerIdTest SINGLETON = new ProducerIdTest(); - public static ProducerIdTest SINGLETON = new ProducerIdTest(); + public Object createObject() throws Exception { + ProducerId info = new ProducerId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ProducerId info = new ProducerId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ProducerId info = (ProducerId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ProducerId info = (ProducerId) object; - - info.setConnectionId("ConnectionId:1"); - info.setValue(1); - info.setSessionId(2); - } + info.setConnectionId("ConnectionId:1"); + info.setValue(1); + info.setSessionId(2); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ProducerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ProducerInfoTest.java index d6bafb6e44..6310eebf30 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ProducerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ProducerInfoTest.java @@ -24,43 +24,39 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ProducerInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ProducerInfoTest extends BaseCommandTestSupport { + public static ProducerInfoTest SINGLETON = new ProducerInfoTest(); - public static ProducerInfoTest SINGLETON = new ProducerInfoTest(); + public Object createObject() throws Exception { + ProducerInfo info = new ProducerInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ProducerInfo info = new ProducerInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ProducerInfo info = (ProducerInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ProducerInfo info = (ProducerInfo) object; - - info.setProducerId(createProducerId("ProducerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - { - BrokerId value[] = new BrokerId[2]; - for( int i=0; i < 2; i++ ) { - value[i] = createBrokerId("BrokerPath:3"); - } - info.setBrokerPath(value); - } - info.setDispatchAsync(true); - info.setWindowSize(1); - } + info.setProducerId(createProducerId("ProducerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:3"); + } + info.setBrokerPath(value); + } + info.setDispatchAsync(true); + info.setWindowSize(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/RemoveInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/RemoveInfoTest.java index 45f05a3e16..3370cfad84 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/RemoveInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/RemoveInfoTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for RemoveInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class RemoveInfoTest extends BaseCommandTestSupport { + public static RemoveInfoTest SINGLETON = new RemoveInfoTest(); - public static RemoveInfoTest SINGLETON = new RemoveInfoTest(); + public Object createObject() throws Exception { + RemoveInfo info = new RemoveInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - RemoveInfo info = new RemoveInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + RemoveInfo info = (RemoveInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - RemoveInfo info = (RemoveInfo) object; - - info.setObjectId(createDataStructure("ObjectId:1")); - } + info.setObjectId(createDataStructure("ObjectId:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/RemoveSubscriptionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/RemoveSubscriptionInfoTest.java index f2e0fd0953..a6a6a56edb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/RemoveSubscriptionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/RemoveSubscriptionInfoTest.java @@ -24,35 +24,31 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for RemoveSubscriptionInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class RemoveSubscriptionInfoTest extends BaseCommandTestSupport { + public static RemoveSubscriptionInfoTest SINGLETON = new RemoveSubscriptionInfoTest(); - public static RemoveSubscriptionInfoTest SINGLETON = new RemoveSubscriptionInfoTest(); + public Object createObject() throws Exception { + RemoveSubscriptionInfo info = new RemoveSubscriptionInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - RemoveSubscriptionInfo info = new RemoveSubscriptionInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + RemoveSubscriptionInfo info = (RemoveSubscriptionInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - RemoveSubscriptionInfo info = (RemoveSubscriptionInfo) object; - - info.setConnectionId(createConnectionId("ConnectionId:1")); - info.setSubscriptionName("SubcriptionName:2"); - info.setClientId("ClientId:3"); - } + info.setConnectionId(createConnectionId("ConnectionId:1")); + info.setSubscriptionName("SubcriptionName:2"); + info.setClientId("ClientId:3"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ReplayCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ReplayCommandTest.java index 81028a7290..e8eec8a205 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ReplayCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ReplayCommandTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ReplayCommand * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ReplayCommandTest extends BaseCommandTestSupport { + public static ReplayCommandTest SINGLETON = new ReplayCommandTest(); - public static ReplayCommandTest SINGLETON = new ReplayCommandTest(); + public Object createObject() throws Exception { + ReplayCommand info = new ReplayCommand(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ReplayCommand info = new ReplayCommand(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ReplayCommand info = (ReplayCommand) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ReplayCommand info = (ReplayCommand) object; - - info.setFirstNakNumber(1); - info.setLastNakNumber(2); - } + info.setFirstNakNumber(1); + info.setLastNakNumber(2); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ResponseTest.java index f757031c4f..3a64c3982b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ResponseTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for Response * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ResponseTest extends BaseCommandTestSupport { + public static ResponseTest SINGLETON = new ResponseTest(); - public static ResponseTest SINGLETON = new ResponseTest(); + public Object createObject() throws Exception { + Response info = new Response(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - Response info = new Response(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + Response info = (Response) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - Response info = (Response) object; - - info.setCorrelationId(1); - } + info.setCorrelationId(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/SessionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/SessionIdTest.java index 923f49b0b5..33c56dedbb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/SessionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/SessionIdTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for SessionId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class SessionIdTest extends DataFileGeneratorTestSupport { + public static SessionIdTest SINGLETON = new SessionIdTest(); - public static SessionIdTest SINGLETON = new SessionIdTest(); + public Object createObject() throws Exception { + SessionId info = new SessionId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - SessionId info = new SessionId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + SessionId info = (SessionId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - SessionId info = (SessionId) object; - - info.setConnectionId("ConnectionId:1"); - info.setValue(1); - } + info.setConnectionId("ConnectionId:1"); + info.setValue(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/SessionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/SessionInfoTest.java index ed897c64c4..34ed897dbe 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/SessionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/SessionInfoTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for SessionInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class SessionInfoTest extends BaseCommandTestSupport { + public static SessionInfoTest SINGLETON = new SessionInfoTest(); - public static SessionInfoTest SINGLETON = new SessionInfoTest(); + public Object createObject() throws Exception { + SessionInfo info = new SessionInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - SessionInfo info = new SessionInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + SessionInfo info = (SessionInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - SessionInfo info = (SessionInfo) object; - - info.setSessionId(createSessionId("SessionId:1")); - } + info.setSessionId(createSessionId("SessionId:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ShutdownInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ShutdownInfoTest.java index 411d392720..827f2067aa 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ShutdownInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/ShutdownInfoTest.java @@ -24,32 +24,28 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ShutdownInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ShutdownInfoTest extends BaseCommandTestSupport { + public static ShutdownInfoTest SINGLETON = new ShutdownInfoTest(); - public static ShutdownInfoTest SINGLETON = new ShutdownInfoTest(); + public Object createObject() throws Exception { + ShutdownInfo info = new ShutdownInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ShutdownInfo info = new ShutdownInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ShutdownInfo info = (ShutdownInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ShutdownInfo info = (ShutdownInfo) object; - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/SubscriptionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/SubscriptionInfoTest.java index 1724bee351..16938910ff 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/SubscriptionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/SubscriptionInfoTest.java @@ -24,37 +24,33 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for SubscriptionInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class SubscriptionInfoTest extends DataFileGeneratorTestSupport { + public static SubscriptionInfoTest SINGLETON = new SubscriptionInfoTest(); - public static SubscriptionInfoTest SINGLETON = new SubscriptionInfoTest(); + public Object createObject() throws Exception { + SubscriptionInfo info = new SubscriptionInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - SubscriptionInfo info = new SubscriptionInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + SubscriptionInfo info = (SubscriptionInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - SubscriptionInfo info = (SubscriptionInfo) object; - - info.setClientId("ClientId:1"); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setSelector("Selector:3"); - info.setSubscriptionName("SubcriptionName:4"); - info.setSubscribedDestination(createActiveMQDestination("SubscribedDestination:5")); - } + info.setClientId("ClientId:1"); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setSelector("Selector:3"); + info.setSubscriptionName("SubcriptionName:4"); + info.setSubscribedDestination(createActiveMQDestination("SubscribedDestination:5")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/TransactionIdTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/TransactionIdTestSupport.java index 6172e4d942..5e028fff3f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/TransactionIdTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/TransactionIdTestSupport.java @@ -24,24 +24,20 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for TransactionId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public abstract class TransactionIdTestSupport extends DataFileGeneratorTestSupport { + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + TransactionId info = (TransactionId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - TransactionId info = (TransactionId) object; - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/TransactionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/TransactionInfoTest.java index 26e2f41b2f..fa0591c7c6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/TransactionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/TransactionInfoTest.java @@ -24,35 +24,31 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for TransactionInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class TransactionInfoTest extends BaseCommandTestSupport { + public static TransactionInfoTest SINGLETON = new TransactionInfoTest(); - public static TransactionInfoTest SINGLETON = new TransactionInfoTest(); + public Object createObject() throws Exception { + TransactionInfo info = new TransactionInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - TransactionInfo info = new TransactionInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + TransactionInfo info = (TransactionInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - TransactionInfo info = (TransactionInfo) object; - - info.setConnectionId(createConnectionId("ConnectionId:1")); - info.setTransactionId(createTransactionId("TransactionId:2")); - info.setType((byte) 1); - } + info.setConnectionId(createConnectionId("ConnectionId:1")); + info.setTransactionId(createTransactionId("TransactionId:2")); + info.setType((byte) 1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/XATransactionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/XATransactionIdTest.java index d79de31ff5..27d60ac02e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/XATransactionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v4/XATransactionIdTest.java @@ -24,35 +24,31 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for XATransactionId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class XATransactionIdTest extends TransactionIdTestSupport { + public static XATransactionIdTest SINGLETON = new XATransactionIdTest(); - public static XATransactionIdTest SINGLETON = new XATransactionIdTest(); + public Object createObject() throws Exception { + XATransactionId info = new XATransactionId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - XATransactionId info = new XATransactionId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + XATransactionId info = (XATransactionId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - XATransactionId info = (XATransactionId) object; - - info.setFormatId(1); - info.setGlobalTransactionId("GlobalTransactionId:1".getBytes()); - info.setBranchQualifier("BranchQualifier:2".getBytes()); - } + info.setFormatId(1); + info.setGlobalTransactionId("GlobalTransactionId:1".getBytes()); + info.setBranchQualifier("BranchQualifier:2".getBytes()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/BaseCommandTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/BaseCommandTestSupport.java index 55bfd64f78..5e2288f659 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/BaseCommandTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/BaseCommandTestSupport.java @@ -24,15 +24,14 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; * auto generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * */ public abstract class BaseCommandTestSupport extends DataFileGeneratorTestSupport { - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - BaseCommand info = (BaseCommand)object; - info.setCommandId(1); - info.setResponseRequired(true); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + BaseCommand info = (BaseCommand) object; + info.setCommandId(1); + info.setResponseRequired(true); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/BrokerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/BrokerIdTest.java index d5ebc11b01..73c8663d9c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/BrokerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/BrokerIdTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for BrokerId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class BrokerIdTest extends DataFileGeneratorTestSupport { + public static BrokerIdTest SINGLETON = new BrokerIdTest(); - public static BrokerIdTest SINGLETON = new BrokerIdTest(); + public Object createObject() throws Exception { + BrokerId info = new BrokerId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - BrokerId info = new BrokerId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + BrokerId info = (BrokerId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - BrokerId info = (BrokerId) object; - - info.setValue("Value:1"); - } + info.setValue("Value:1"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/BrokerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/BrokerInfoTest.java index 26186f17e2..2a74d44fde 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/BrokerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/BrokerInfoTest.java @@ -24,50 +24,46 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for BrokerInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class BrokerInfoTest extends BaseCommandTestSupport { + public static BrokerInfoTest SINGLETON = new BrokerInfoTest(); - public static BrokerInfoTest SINGLETON = new BrokerInfoTest(); + public Object createObject() throws Exception { + BrokerInfo info = new BrokerInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - BrokerInfo info = new BrokerInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + BrokerInfo info = (BrokerInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - BrokerInfo info = (BrokerInfo) object; - - info.setBrokerId(createBrokerId("BrokerId:1")); - info.setBrokerURL("BrokerURL:2"); - { - BrokerInfo value[] = new BrokerInfo[0]; - for( int i=0; i < 0; i++ ) { - value[i] = createBrokerInfo("PeerBrokerInfos:3"); - } - info.setPeerBrokerInfos(value); - } - info.setBrokerName("BrokerName:4"); - info.setSlaveBroker(true); - info.setMasterBroker(false); - info.setFaultTolerantConfiguration(true); - info.setDuplexConnection(false); - info.setNetworkConnection(true); - info.setConnectionId(1); - info.setBrokerUploadUrl("BrokerUploadUrl:5"); - info.setNetworkProperties("NetworkProperties:6"); - } + info.setBrokerId(createBrokerId("BrokerId:1")); + info.setBrokerURL("BrokerURL:2"); + { + BrokerInfo value[] = new BrokerInfo[0]; + for (int i = 0; i < 0; i++) { + value[i] = createBrokerInfo("PeerBrokerInfos:3"); + } + info.setPeerBrokerInfos(value); + } + info.setBrokerName("BrokerName:4"); + info.setSlaveBroker(true); + info.setMasterBroker(false); + info.setFaultTolerantConfiguration(true); + info.setDuplexConnection(false); + info.setNetworkConnection(true); + info.setConnectionId(1); + info.setBrokerUploadUrl("BrokerUploadUrl:5"); + info.setNetworkProperties("NetworkProperties:6"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConnectionControlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConnectionControlTest.java index fa2e0cc082..2dd2fb5b63 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConnectionControlTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConnectionControlTest.java @@ -24,37 +24,33 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ConnectionControl * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConnectionControlTest extends BaseCommandTestSupport { + public static ConnectionControlTest SINGLETON = new ConnectionControlTest(); - public static ConnectionControlTest SINGLETON = new ConnectionControlTest(); + public Object createObject() throws Exception { + ConnectionControl info = new ConnectionControl(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConnectionControl info = new ConnectionControl(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConnectionControl info = (ConnectionControl) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionControl info = (ConnectionControl) object; - - info.setClose(true); - info.setExit(false); - info.setFaultTolerant(true); - info.setResume(false); - info.setSuspend(true); - } + info.setClose(true); + info.setExit(false); + info.setFaultTolerant(true); + info.setResume(false); + info.setSuspend(true); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConnectionErrorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConnectionErrorTest.java index 52420e2147..eb62bbafe7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConnectionErrorTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConnectionErrorTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ConnectionError * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConnectionErrorTest extends BaseCommandTestSupport { + public static ConnectionErrorTest SINGLETON = new ConnectionErrorTest(); - public static ConnectionErrorTest SINGLETON = new ConnectionErrorTest(); + public Object createObject() throws Exception { + ConnectionError info = new ConnectionError(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConnectionError info = new ConnectionError(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConnectionError info = (ConnectionError) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionError info = (ConnectionError) object; - - info.setException(createThrowable("Exception:1")); - info.setConnectionId(createConnectionId("ConnectionId:2")); - } + info.setException(createThrowable("Exception:1")); + info.setConnectionId(createConnectionId("ConnectionId:2")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConnectionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConnectionIdTest.java index e69d674174..565a4d52f0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConnectionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConnectionIdTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ConnectionId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConnectionIdTest extends DataFileGeneratorTestSupport { + public static ConnectionIdTest SINGLETON = new ConnectionIdTest(); - public static ConnectionIdTest SINGLETON = new ConnectionIdTest(); + public Object createObject() throws Exception { + ConnectionId info = new ConnectionId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConnectionId info = new ConnectionId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConnectionId info = (ConnectionId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionId info = (ConnectionId) object; - - info.setValue("Value:1"); - } + info.setValue("Value:1"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConnectionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConnectionInfoTest.java index 776b2d2029..6358411178 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConnectionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConnectionInfoTest.java @@ -24,46 +24,42 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ConnectionInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConnectionInfoTest extends BaseCommandTestSupport { + public static ConnectionInfoTest SINGLETON = new ConnectionInfoTest(); - public static ConnectionInfoTest SINGLETON = new ConnectionInfoTest(); + public Object createObject() throws Exception { + ConnectionInfo info = new ConnectionInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConnectionInfo info = new ConnectionInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConnectionInfo info = (ConnectionInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionInfo info = (ConnectionInfo) object; - - info.setConnectionId(createConnectionId("ConnectionId:1")); - info.setClientId("ClientId:2"); - info.setPassword("Password:3"); - info.setUserName("UserName:4"); - { - BrokerId value[] = new BrokerId[2]; - for( int i=0; i < 2; i++ ) { - value[i] = createBrokerId("BrokerPath:5"); - } - info.setBrokerPath(value); - } - info.setBrokerMasterConnector(true); - info.setManageable(false); - info.setClientMaster(true); - } + info.setConnectionId(createConnectionId("ConnectionId:1")); + info.setClientId("ClientId:2"); + info.setPassword("Password:3"); + info.setUserName("UserName:4"); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:5"); + } + info.setBrokerPath(value); + } + info.setBrokerMasterConnector(true); + info.setManageable(false); + info.setClientMaster(true); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConsumerControlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConsumerControlTest.java index 546f3cb4f5..920da538af 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConsumerControlTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConsumerControlTest.java @@ -24,38 +24,34 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ConsumerControl * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConsumerControlTest extends BaseCommandTestSupport { + public static ConsumerControlTest SINGLETON = new ConsumerControlTest(); - public static ConsumerControlTest SINGLETON = new ConsumerControlTest(); + public Object createObject() throws Exception { + ConsumerControl info = new ConsumerControl(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConsumerControl info = new ConsumerControl(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConsumerControl info = (ConsumerControl) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConsumerControl info = (ConsumerControl) object; - - info.setClose(true); - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setPrefetch(1); - info.setFlush(false); - info.setStart(true); - info.setStop(false); - } + info.setClose(true); + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setPrefetch(1); + info.setFlush(false); + info.setStart(true); + info.setStop(false); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConsumerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConsumerIdTest.java index cfcac6a707..0e8e56397d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConsumerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConsumerIdTest.java @@ -24,35 +24,31 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ConsumerId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConsumerIdTest extends DataFileGeneratorTestSupport { + public static ConsumerIdTest SINGLETON = new ConsumerIdTest(); - public static ConsumerIdTest SINGLETON = new ConsumerIdTest(); + public Object createObject() throws Exception { + ConsumerId info = new ConsumerId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConsumerId info = new ConsumerId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConsumerId info = (ConsumerId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConsumerId info = (ConsumerId) object; - - info.setConnectionId("ConnectionId:1"); - info.setSessionId(1); - info.setValue(2); - } + info.setConnectionId("ConnectionId:1"); + info.setSessionId(1); + info.setValue(2); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConsumerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConsumerInfoTest.java index 3316d2083a..07ee77da06 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConsumerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ConsumerInfoTest.java @@ -24,62 +24,58 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ConsumerInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConsumerInfoTest extends BaseCommandTestSupport { + public static ConsumerInfoTest SINGLETON = new ConsumerInfoTest(); - public static ConsumerInfoTest SINGLETON = new ConsumerInfoTest(); + public Object createObject() throws Exception { + ConsumerInfo info = new ConsumerInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConsumerInfo info = new ConsumerInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConsumerInfo info = (ConsumerInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConsumerInfo info = (ConsumerInfo) object; - - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setBrowser(true); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setPrefetchSize(1); - info.setMaximumPendingMessageLimit(2); - info.setDispatchAsync(false); - info.setSelector("Selector:3"); - info.setSubscriptionName("SubscriptionName:4"); - info.setNoLocal(true); - info.setExclusive(false); - info.setRetroactive(true); - info.setPriority((byte) 1); - { - BrokerId value[] = new BrokerId[2]; - for( int i=0; i < 2; i++ ) { - value[i] = createBrokerId("BrokerPath:5"); - } - info.setBrokerPath(value); - } - info.setAdditionalPredicate(createBooleanExpression("AdditionalPredicate:6")); - info.setNetworkSubscription(false); - info.setOptimizedAcknowledge(true); - info.setNoRangeAcks(false); - { - ConsumerId value[] = new ConsumerId[2]; - for( int i=0; i < 2; i++ ) { - value[i] = createConsumerId("NetworkConsumerPath:7"); - } - info.setNetworkConsumerPath(value); - } - } + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setBrowser(true); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setPrefetchSize(1); + info.setMaximumPendingMessageLimit(2); + info.setDispatchAsync(false); + info.setSelector("Selector:3"); + info.setSubscriptionName("SubscriptionName:4"); + info.setNoLocal(true); + info.setExclusive(false); + info.setRetroactive(true); + info.setPriority((byte) 1); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:5"); + } + info.setBrokerPath(value); + } + info.setAdditionalPredicate(createBooleanExpression("AdditionalPredicate:6")); + info.setNetworkSubscription(false); + info.setOptimizedAcknowledge(true); + info.setNoRangeAcks(false); + { + ConsumerId value[] = new ConsumerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createConsumerId("NetworkConsumerPath:7"); + } + info.setNetworkConsumerPath(value); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ControlCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ControlCommandTest.java index 04c41d3ee5..dc1a257b60 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ControlCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ControlCommandTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ControlCommand * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ControlCommandTest extends BaseCommandTestSupport { + public static ControlCommandTest SINGLETON = new ControlCommandTest(); - public static ControlCommandTest SINGLETON = new ControlCommandTest(); + public Object createObject() throws Exception { + ControlCommand info = new ControlCommand(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ControlCommand info = new ControlCommand(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ControlCommand info = (ControlCommand) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ControlCommand info = (ControlCommand) object; - - info.setCommand("Command:1"); - } + info.setCommand("Command:1"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/DataArrayResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/DataArrayResponseTest.java index 52d2dfd277..826a170672 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/DataArrayResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/DataArrayResponseTest.java @@ -24,39 +24,35 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for DataArrayResponse * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class DataArrayResponseTest extends ResponseTest { + public static DataArrayResponseTest SINGLETON = new DataArrayResponseTest(); - public static DataArrayResponseTest SINGLETON = new DataArrayResponseTest(); + public Object createObject() throws Exception { + DataArrayResponse info = new DataArrayResponse(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - DataArrayResponse info = new DataArrayResponse(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + DataArrayResponse info = (DataArrayResponse) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DataArrayResponse info = (DataArrayResponse) object; - - { - DataStructure value[] = new DataStructure[2]; - for( int i=0; i < 2; i++ ) { - value[i] = createDataStructure("Data:1"); - } - info.setData(value); - } - } + { + DataStructure value[] = new DataStructure[2]; + for (int i = 0; i < 2; i++) { + value[i] = createDataStructure("Data:1"); + } + info.setData(value); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/DataResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/DataResponseTest.java index d1047de6ac..d7e20ac647 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/DataResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/DataResponseTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for DataResponse * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class DataResponseTest extends ResponseTest { + public static DataResponseTest SINGLETON = new DataResponseTest(); - public static DataResponseTest SINGLETON = new DataResponseTest(); + public Object createObject() throws Exception { + DataResponse info = new DataResponse(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - DataResponse info = new DataResponse(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + DataResponse info = (DataResponse) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DataResponse info = (DataResponse) object; - - info.setData(createDataStructure("Data:1")); - } + info.setData(createDataStructure("Data:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/DestinationInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/DestinationInfoTest.java index 45ef248c9b..da96ce6511 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/DestinationInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/DestinationInfoTest.java @@ -24,43 +24,39 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for DestinationInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class DestinationInfoTest extends BaseCommandTestSupport { + public static DestinationInfoTest SINGLETON = new DestinationInfoTest(); - public static DestinationInfoTest SINGLETON = new DestinationInfoTest(); + public Object createObject() throws Exception { + DestinationInfo info = new DestinationInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - DestinationInfo info = new DestinationInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + DestinationInfo info = (DestinationInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DestinationInfo info = (DestinationInfo) object; - - info.setConnectionId(createConnectionId("ConnectionId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setOperationType((byte) 1); - info.setTimeout(1); - { - BrokerId value[] = new BrokerId[2]; - for( int i=0; i < 2; i++ ) { - value[i] = createBrokerId("BrokerPath:3"); - } - info.setBrokerPath(value); - } - } + info.setConnectionId(createConnectionId("ConnectionId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setOperationType((byte) 1); + info.setTimeout(1); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:3"); + } + info.setBrokerPath(value); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/DiscoveryEventTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/DiscoveryEventTest.java index 2c2cbabbce..3131ff5e43 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/DiscoveryEventTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/DiscoveryEventTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for DiscoveryEvent * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class DiscoveryEventTest extends DataFileGeneratorTestSupport { + public static DiscoveryEventTest SINGLETON = new DiscoveryEventTest(); - public static DiscoveryEventTest SINGLETON = new DiscoveryEventTest(); + public Object createObject() throws Exception { + DiscoveryEvent info = new DiscoveryEvent(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - DiscoveryEvent info = new DiscoveryEvent(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + DiscoveryEvent info = (DiscoveryEvent) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DiscoveryEvent info = (DiscoveryEvent) object; - - info.setServiceName("ServiceName:1"); - info.setBrokerName("BrokerName:2"); - } + info.setServiceName("ServiceName:1"); + info.setBrokerName("BrokerName:2"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ExceptionResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ExceptionResponseTest.java index 41d60e2d5b..dcce7a66c6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ExceptionResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ExceptionResponseTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ExceptionResponse * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ExceptionResponseTest extends ResponseTest { + public static ExceptionResponseTest SINGLETON = new ExceptionResponseTest(); - public static ExceptionResponseTest SINGLETON = new ExceptionResponseTest(); + public Object createObject() throws Exception { + ExceptionResponse info = new ExceptionResponse(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ExceptionResponse info = new ExceptionResponse(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ExceptionResponse info = (ExceptionResponse) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ExceptionResponse info = (ExceptionResponse) object; - - info.setException(createThrowable("Exception:1")); - } + info.setException(createThrowable("Exception:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/FlushCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/FlushCommandTest.java index c48a679b26..42bc839ab1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/FlushCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/FlushCommandTest.java @@ -24,32 +24,28 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for FlushCommand * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class FlushCommandTest extends BaseCommandTestSupport { + public static FlushCommandTest SINGLETON = new FlushCommandTest(); - public static FlushCommandTest SINGLETON = new FlushCommandTest(); + public Object createObject() throws Exception { + FlushCommand info = new FlushCommand(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - FlushCommand info = new FlushCommand(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + FlushCommand info = (FlushCommand) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - FlushCommand info = (FlushCommand) object; - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/IntegerResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/IntegerResponseTest.java index 7737769289..4fb93b85c9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/IntegerResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/IntegerResponseTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for IntegerResponse * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class IntegerResponseTest extends ResponseTest { + public static IntegerResponseTest SINGLETON = new IntegerResponseTest(); - public static IntegerResponseTest SINGLETON = new IntegerResponseTest(); + public Object createObject() throws Exception { + IntegerResponse info = new IntegerResponse(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - IntegerResponse info = new IntegerResponse(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + IntegerResponse info = (IntegerResponse) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - IntegerResponse info = (IntegerResponse) object; - - info.setResult(1); - } + info.setResult(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/JournalQueueAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/JournalQueueAckTest.java index 0f1de7eb81..dd58581c44 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/JournalQueueAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/JournalQueueAckTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for JournalQueueAck * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class JournalQueueAckTest extends DataFileGeneratorTestSupport { + public static JournalQueueAckTest SINGLETON = new JournalQueueAckTest(); - public static JournalQueueAckTest SINGLETON = new JournalQueueAckTest(); + public Object createObject() throws Exception { + JournalQueueAck info = new JournalQueueAck(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - JournalQueueAck info = new JournalQueueAck(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + JournalQueueAck info = (JournalQueueAck) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalQueueAck info = (JournalQueueAck) object; - - info.setDestination(createActiveMQDestination("Destination:1")); - info.setMessageAck(createMessageAck("MessageAck:2")); - } + info.setDestination(createActiveMQDestination("Destination:1")); + info.setMessageAck(createMessageAck("MessageAck:2")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/JournalTopicAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/JournalTopicAckTest.java index d0856f8ef5..0911ef9191 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/JournalTopicAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/JournalTopicAckTest.java @@ -24,38 +24,34 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for JournalTopicAck * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class JournalTopicAckTest extends DataFileGeneratorTestSupport { + public static JournalTopicAckTest SINGLETON = new JournalTopicAckTest(); - public static JournalTopicAckTest SINGLETON = new JournalTopicAckTest(); + public Object createObject() throws Exception { + JournalTopicAck info = new JournalTopicAck(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - JournalTopicAck info = new JournalTopicAck(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + JournalTopicAck info = (JournalTopicAck) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalTopicAck info = (JournalTopicAck) object; - - info.setDestination(createActiveMQDestination("Destination:1")); - info.setMessageId(createMessageId("MessageId:2")); - info.setMessageSequenceId(1); - info.setSubscritionName("SubscritionName:3"); - info.setClientId("ClientId:4"); - info.setTransactionId(createTransactionId("TransactionId:5")); - } + info.setDestination(createActiveMQDestination("Destination:1")); + info.setMessageId(createMessageId("MessageId:2")); + info.setMessageSequenceId(1); + info.setSubscritionName("SubscritionName:3"); + info.setClientId("ClientId:4"); + info.setTransactionId(createTransactionId("TransactionId:5")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/JournalTraceTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/JournalTraceTest.java index 530f2ad945..5b6181db76 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/JournalTraceTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/JournalTraceTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for JournalTrace * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class JournalTraceTest extends DataFileGeneratorTestSupport { + public static JournalTraceTest SINGLETON = new JournalTraceTest(); - public static JournalTraceTest SINGLETON = new JournalTraceTest(); + public Object createObject() throws Exception { + JournalTrace info = new JournalTrace(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - JournalTrace info = new JournalTrace(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + JournalTrace info = (JournalTrace) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalTrace info = (JournalTrace) object; - - info.setMessage("Message:1"); - } + info.setMessage("Message:1"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/JournalTransactionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/JournalTransactionTest.java index 4348e23a4b..166b360feb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/JournalTransactionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/JournalTransactionTest.java @@ -24,35 +24,31 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for JournalTransaction * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class JournalTransactionTest extends DataFileGeneratorTestSupport { + public static JournalTransactionTest SINGLETON = new JournalTransactionTest(); - public static JournalTransactionTest SINGLETON = new JournalTransactionTest(); + public Object createObject() throws Exception { + JournalTransaction info = new JournalTransaction(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - JournalTransaction info = new JournalTransaction(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + JournalTransaction info = (JournalTransaction) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalTransaction info = (JournalTransaction) object; - - info.setTransactionId(createTransactionId("TransactionId:1")); - info.setType((byte) 1); - info.setWasPrepared(true); - } + info.setTransactionId(createTransactionId("TransactionId:1")); + info.setType((byte) 1); + info.setWasPrepared(true); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/KeepAliveInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/KeepAliveInfoTest.java index 48610fa4a6..9b6478f727 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/KeepAliveInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/KeepAliveInfoTest.java @@ -24,32 +24,28 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for KeepAliveInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class KeepAliveInfoTest extends BaseCommandTestSupport { + public static KeepAliveInfoTest SINGLETON = new KeepAliveInfoTest(); - public static KeepAliveInfoTest SINGLETON = new KeepAliveInfoTest(); + public Object createObject() throws Exception { + KeepAliveInfo info = new KeepAliveInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - KeepAliveInfo info = new KeepAliveInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + KeepAliveInfo info = (KeepAliveInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - KeepAliveInfo info = (KeepAliveInfo) object; - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/LastPartialCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/LastPartialCommandTest.java index edef39aea5..5b7003154f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/LastPartialCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/LastPartialCommandTest.java @@ -24,32 +24,28 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for LastPartialCommand * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class LastPartialCommandTest extends PartialCommandTest { + public static LastPartialCommandTest SINGLETON = new LastPartialCommandTest(); - public static LastPartialCommandTest SINGLETON = new LastPartialCommandTest(); + public Object createObject() throws Exception { + LastPartialCommand info = new LastPartialCommand(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - LastPartialCommand info = new LastPartialCommand(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + LastPartialCommand info = (LastPartialCommand) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - LastPartialCommand info = (LastPartialCommand) object; - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/LocalTransactionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/LocalTransactionIdTest.java index ba1f7c8752..9baab76102 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/LocalTransactionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/LocalTransactionIdTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for LocalTransactionId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class LocalTransactionIdTest extends TransactionIdTestSupport { + public static LocalTransactionIdTest SINGLETON = new LocalTransactionIdTest(); - public static LocalTransactionIdTest SINGLETON = new LocalTransactionIdTest(); + public Object createObject() throws Exception { + LocalTransactionId info = new LocalTransactionId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - LocalTransactionId info = new LocalTransactionId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + LocalTransactionId info = (LocalTransactionId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - LocalTransactionId info = (LocalTransactionId) object; - - info.setValue(1); - info.setConnectionId(createConnectionId("ConnectionId:1")); - } + info.setValue(1); + info.setConnectionId(createConnectionId("ConnectionId:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/MessageAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/MessageAckTest.java index 3185c7945b..c57a6163ca 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/MessageAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/MessageAckTest.java @@ -24,39 +24,35 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for MessageAck * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class MessageAckTest extends BaseCommandTestSupport { + public static MessageAckTest SINGLETON = new MessageAckTest(); - public static MessageAckTest SINGLETON = new MessageAckTest(); + public Object createObject() throws Exception { + MessageAck info = new MessageAck(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - MessageAck info = new MessageAck(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessageAck info = (MessageAck) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageAck info = (MessageAck) object; - - info.setDestination(createActiveMQDestination("Destination:1")); - info.setTransactionId(createTransactionId("TransactionId:2")); - info.setConsumerId(createConsumerId("ConsumerId:3")); - info.setAckType((byte) 1); - info.setFirstMessageId(createMessageId("FirstMessageId:4")); - info.setLastMessageId(createMessageId("LastMessageId:5")); - info.setMessageCount(1); - } + info.setDestination(createActiveMQDestination("Destination:1")); + info.setTransactionId(createTransactionId("TransactionId:2")); + info.setConsumerId(createConsumerId("ConsumerId:3")); + info.setAckType((byte) 1); + info.setFirstMessageId(createMessageId("FirstMessageId:4")); + info.setLastMessageId(createMessageId("LastMessageId:5")); + info.setMessageCount(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/MessageDispatchNotificationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/MessageDispatchNotificationTest.java index 296aba735b..937ec23210 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/MessageDispatchNotificationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/MessageDispatchNotificationTest.java @@ -24,36 +24,32 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for MessageDispatchNotification * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class MessageDispatchNotificationTest extends BaseCommandTestSupport { + public static MessageDispatchNotificationTest SINGLETON = new MessageDispatchNotificationTest(); - public static MessageDispatchNotificationTest SINGLETON = new MessageDispatchNotificationTest(); + public Object createObject() throws Exception { + MessageDispatchNotification info = new MessageDispatchNotification(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - MessageDispatchNotification info = new MessageDispatchNotification(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessageDispatchNotification info = (MessageDispatchNotification) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageDispatchNotification info = (MessageDispatchNotification) object; - - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setDeliverySequenceId(1); - info.setMessageId(createMessageId("MessageId:3")); - } + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setDeliverySequenceId(1); + info.setMessageId(createMessageId("MessageId:3")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/MessageDispatchTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/MessageDispatchTest.java index a8c69871f2..2a7e570e5b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/MessageDispatchTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/MessageDispatchTest.java @@ -24,36 +24,32 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for MessageDispatch * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class MessageDispatchTest extends BaseCommandTestSupport { + public static MessageDispatchTest SINGLETON = new MessageDispatchTest(); - public static MessageDispatchTest SINGLETON = new MessageDispatchTest(); + public Object createObject() throws Exception { + MessageDispatch info = new MessageDispatch(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - MessageDispatch info = new MessageDispatch(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessageDispatch info = (MessageDispatch) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageDispatch info = (MessageDispatch) object; - - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setMessage(createMessage("Message:3")); - info.setRedeliveryCounter(1); - } + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setMessage(createMessage("Message:3")); + info.setRedeliveryCounter(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/MessageIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/MessageIdTest.java index 78e8029bf0..0664cdd5b7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/MessageIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/MessageIdTest.java @@ -24,35 +24,31 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for MessageId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class MessageIdTest extends DataFileGeneratorTestSupport { + public static MessageIdTest SINGLETON = new MessageIdTest(); - public static MessageIdTest SINGLETON = new MessageIdTest(); + public Object createObject() throws Exception { + MessageId info = new MessageId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - MessageId info = new MessageId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessageId info = (MessageId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageId info = (MessageId) object; - - info.setProducerId(createProducerId("ProducerId:1")); - info.setProducerSequenceId(1); - info.setBrokerSequenceId(2); - } + info.setProducerId(createProducerId("ProducerId:1")); + info.setProducerSequenceId(1); + info.setBrokerSequenceId(2); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/MessagePullTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/MessagePullTest.java index f23fa67b1f..2bd3c57446 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/MessagePullTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/MessagePullTest.java @@ -24,37 +24,33 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for MessagePull * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class MessagePullTest extends BaseCommandTestSupport { + public static MessagePullTest SINGLETON = new MessagePullTest(); - public static MessagePullTest SINGLETON = new MessagePullTest(); + public Object createObject() throws Exception { + MessagePull info = new MessagePull(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - MessagePull info = new MessagePull(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessagePull info = (MessagePull) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessagePull info = (MessagePull) object; - - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setTimeout(1); - info.setCorrelationId("CorrelationId:3"); - info.setMessageId(createMessageId("MessageId:4")); - } + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setTimeout(1); + info.setCorrelationId("CorrelationId:3"); + info.setMessageId(createMessageId("MessageId:4")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/MessageTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/MessageTestSupport.java index e5bfe05728..408846cdf4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/MessageTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/MessageTestSupport.java @@ -19,71 +19,67 @@ package org.apache.activemq.openwire.v5; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for Message * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public abstract class MessageTestSupport extends BaseCommandTestSupport { + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + Message info = (Message) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - Message info = (Message) object; - - info.setProducerId(createProducerId("ProducerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setTransactionId(createTransactionId("TransactionId:3")); - info.setOriginalDestination(createActiveMQDestination("OriginalDestination:4")); - info.setMessageId(createMessageId("MessageId:5")); - info.setOriginalTransactionId(createTransactionId("OriginalTransactionId:6")); - info.setGroupID("GroupID:7"); - info.setGroupSequence(1); - info.setCorrelationId("CorrelationId:8"); - info.setPersistent(true); - info.setExpiration(1); - info.setPriority((byte) 1); - info.setReplyTo(createActiveMQDestination("ReplyTo:9")); - info.setTimestamp(2); - info.setType("Type:10"); - { - byte data[] = "Content:11".getBytes(); - info.setContent(new org.apache.activemq.util.ByteSequence(data,0,data.length)); -} - { - byte data[] = "MarshalledProperties:12".getBytes(); - info.setMarshalledProperties(new org.apache.activemq.util.ByteSequence(data,0,data.length)); -} - info.setDataStructure(createDataStructure("DataStructure:13")); - info.setTargetConsumerId(createConsumerId("TargetConsumerId:14")); - info.setCompressed(false); - info.setRedeliveryCounter(2); - { - BrokerId value[] = new BrokerId[2]; - for( int i=0; i < 2; i++ ) { - value[i] = createBrokerId("BrokerPath:15"); - } - info.setBrokerPath(value); - } - info.setArrival(3); - info.setUserID("UserID:16"); - info.setRecievedByDFBridge(true); - info.setDroppable(false); - { - BrokerId value[] = new BrokerId[2]; - for( int i=0; i < 2; i++ ) { - value[i] = createBrokerId("Cluster:17"); - } - info.setCluster(value); - } - info.setBrokerInTime(4); - info.setBrokerOutTime(5); - } + info.setProducerId(createProducerId("ProducerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setTransactionId(createTransactionId("TransactionId:3")); + info.setOriginalDestination(createActiveMQDestination("OriginalDestination:4")); + info.setMessageId(createMessageId("MessageId:5")); + info.setOriginalTransactionId(createTransactionId("OriginalTransactionId:6")); + info.setGroupID("GroupID:7"); + info.setGroupSequence(1); + info.setCorrelationId("CorrelationId:8"); + info.setPersistent(true); + info.setExpiration(1); + info.setPriority((byte) 1); + info.setReplyTo(createActiveMQDestination("ReplyTo:9")); + info.setTimestamp(2); + info.setType("Type:10"); + { + byte data[] = "Content:11".getBytes(); + info.setContent(new org.apache.activemq.util.ByteSequence(data, 0, data.length)); + } + { + byte data[] = "MarshalledProperties:12".getBytes(); + info.setMarshalledProperties(new org.apache.activemq.util.ByteSequence(data, 0, data.length)); + } + info.setDataStructure(createDataStructure("DataStructure:13")); + info.setTargetConsumerId(createConsumerId("TargetConsumerId:14")); + info.setCompressed(false); + info.setRedeliveryCounter(2); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:15"); + } + info.setBrokerPath(value); + } + info.setArrival(3); + info.setUserID("UserID:16"); + info.setRecievedByDFBridge(true); + info.setDroppable(false); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("Cluster:17"); + } + info.setCluster(value); + } + info.setBrokerInTime(4); + info.setBrokerOutTime(5); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/NetworkBridgeFilterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/NetworkBridgeFilterTest.java index e2e8fef56b..d20d918592 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/NetworkBridgeFilterTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/NetworkBridgeFilterTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for NetworkBridgeFilter * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class NetworkBridgeFilterTest extends DataFileGeneratorTestSupport { + public static NetworkBridgeFilterTest SINGLETON = new NetworkBridgeFilterTest(); - public static NetworkBridgeFilterTest SINGLETON = new NetworkBridgeFilterTest(); + public Object createObject() throws Exception { + NetworkBridgeFilter info = new NetworkBridgeFilter(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - NetworkBridgeFilter info = new NetworkBridgeFilter(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + NetworkBridgeFilter info = (NetworkBridgeFilter) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - NetworkBridgeFilter info = (NetworkBridgeFilter) object; - - info.setNetworkTTL(1); - info.setNetworkBrokerId(createBrokerId("NetworkBrokerId:1")); - } + info.setNetworkTTL(1); + info.setNetworkBrokerId(createBrokerId("NetworkBrokerId:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/PartialCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/PartialCommandTest.java index c234eaf1f3..99212a17fd 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/PartialCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/PartialCommandTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for PartialCommand * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class PartialCommandTest extends DataFileGeneratorTestSupport { + public static PartialCommandTest SINGLETON = new PartialCommandTest(); - public static PartialCommandTest SINGLETON = new PartialCommandTest(); + public Object createObject() throws Exception { + PartialCommand info = new PartialCommand(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - PartialCommand info = new PartialCommand(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + PartialCommand info = (PartialCommand) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - PartialCommand info = (PartialCommand) object; - - info.setCommandId(1); - info.setData("Data:1".getBytes()); - } + info.setCommandId(1); + info.setData("Data:1".getBytes()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ProducerAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ProducerAckTest.java index 48fd0c7ff3..317a737d30 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ProducerAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ProducerAckTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ProducerAck * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ProducerAckTest extends BaseCommandTestSupport { + public static ProducerAckTest SINGLETON = new ProducerAckTest(); - public static ProducerAckTest SINGLETON = new ProducerAckTest(); + public Object createObject() throws Exception { + ProducerAck info = new ProducerAck(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ProducerAck info = new ProducerAck(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ProducerAck info = (ProducerAck) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ProducerAck info = (ProducerAck) object; - - info.setProducerId(createProducerId("ProducerId:1")); - info.setSize(1); - } + info.setProducerId(createProducerId("ProducerId:1")); + info.setSize(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ProducerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ProducerIdTest.java index e4994ff06f..e8b07943e5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ProducerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ProducerIdTest.java @@ -24,35 +24,31 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ProducerId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ProducerIdTest extends DataFileGeneratorTestSupport { + public static ProducerIdTest SINGLETON = new ProducerIdTest(); - public static ProducerIdTest SINGLETON = new ProducerIdTest(); + public Object createObject() throws Exception { + ProducerId info = new ProducerId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ProducerId info = new ProducerId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ProducerId info = (ProducerId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ProducerId info = (ProducerId) object; - - info.setConnectionId("ConnectionId:1"); - info.setValue(1); - info.setSessionId(2); - } + info.setConnectionId("ConnectionId:1"); + info.setValue(1); + info.setSessionId(2); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ProducerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ProducerInfoTest.java index 1dc0633083..22f325f971 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ProducerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ProducerInfoTest.java @@ -24,43 +24,39 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ProducerInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ProducerInfoTest extends BaseCommandTestSupport { + public static ProducerInfoTest SINGLETON = new ProducerInfoTest(); - public static ProducerInfoTest SINGLETON = new ProducerInfoTest(); + public Object createObject() throws Exception { + ProducerInfo info = new ProducerInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ProducerInfo info = new ProducerInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ProducerInfo info = (ProducerInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ProducerInfo info = (ProducerInfo) object; - - info.setProducerId(createProducerId("ProducerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - { - BrokerId value[] = new BrokerId[2]; - for( int i=0; i < 2; i++ ) { - value[i] = createBrokerId("BrokerPath:3"); - } - info.setBrokerPath(value); - } - info.setDispatchAsync(true); - info.setWindowSize(1); - } + info.setProducerId(createProducerId("ProducerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:3"); + } + info.setBrokerPath(value); + } + info.setDispatchAsync(true); + info.setWindowSize(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/RemoveInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/RemoveInfoTest.java index e083079adf..5609701b1b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/RemoveInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/RemoveInfoTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for RemoveInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class RemoveInfoTest extends BaseCommandTestSupport { + public static RemoveInfoTest SINGLETON = new RemoveInfoTest(); - public static RemoveInfoTest SINGLETON = new RemoveInfoTest(); + public Object createObject() throws Exception { + RemoveInfo info = new RemoveInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - RemoveInfo info = new RemoveInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + RemoveInfo info = (RemoveInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - RemoveInfo info = (RemoveInfo) object; - - info.setObjectId(createDataStructure("ObjectId:1")); - info.setLastDeliveredSequenceId(1); - } + info.setObjectId(createDataStructure("ObjectId:1")); + info.setLastDeliveredSequenceId(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/RemoveSubscriptionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/RemoveSubscriptionInfoTest.java index 8c6c05698e..371c7bfd9d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/RemoveSubscriptionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/RemoveSubscriptionInfoTest.java @@ -24,35 +24,31 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for RemoveSubscriptionInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class RemoveSubscriptionInfoTest extends BaseCommandTestSupport { + public static RemoveSubscriptionInfoTest SINGLETON = new RemoveSubscriptionInfoTest(); - public static RemoveSubscriptionInfoTest SINGLETON = new RemoveSubscriptionInfoTest(); + public Object createObject() throws Exception { + RemoveSubscriptionInfo info = new RemoveSubscriptionInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - RemoveSubscriptionInfo info = new RemoveSubscriptionInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + RemoveSubscriptionInfo info = (RemoveSubscriptionInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - RemoveSubscriptionInfo info = (RemoveSubscriptionInfo) object; - - info.setConnectionId(createConnectionId("ConnectionId:1")); - info.setSubscriptionName("SubcriptionName:2"); - info.setClientId("ClientId:3"); - } + info.setConnectionId(createConnectionId("ConnectionId:1")); + info.setSubscriptionName("SubcriptionName:2"); + info.setClientId("ClientId:3"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ReplayCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ReplayCommandTest.java index c4a8879f93..6b13c89037 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ReplayCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ReplayCommandTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ReplayCommand * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ReplayCommandTest extends BaseCommandTestSupport { + public static ReplayCommandTest SINGLETON = new ReplayCommandTest(); - public static ReplayCommandTest SINGLETON = new ReplayCommandTest(); + public Object createObject() throws Exception { + ReplayCommand info = new ReplayCommand(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ReplayCommand info = new ReplayCommand(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ReplayCommand info = (ReplayCommand) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ReplayCommand info = (ReplayCommand) object; - - info.setFirstNakNumber(1); - info.setLastNakNumber(2); - } + info.setFirstNakNumber(1); + info.setLastNakNumber(2); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ResponseTest.java index 4732749ba4..3e017ae7d3 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ResponseTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for Response * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ResponseTest extends BaseCommandTestSupport { + public static ResponseTest SINGLETON = new ResponseTest(); - public static ResponseTest SINGLETON = new ResponseTest(); + public Object createObject() throws Exception { + Response info = new Response(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - Response info = new Response(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + Response info = (Response) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - Response info = (Response) object; - - info.setCorrelationId(1); - } + info.setCorrelationId(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/SessionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/SessionIdTest.java index c38b446420..a4b4ebf1f5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/SessionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/SessionIdTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for SessionId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class SessionIdTest extends DataFileGeneratorTestSupport { + public static SessionIdTest SINGLETON = new SessionIdTest(); - public static SessionIdTest SINGLETON = new SessionIdTest(); + public Object createObject() throws Exception { + SessionId info = new SessionId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - SessionId info = new SessionId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + SessionId info = (SessionId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - SessionId info = (SessionId) object; - - info.setConnectionId("ConnectionId:1"); - info.setValue(1); - } + info.setConnectionId("ConnectionId:1"); + info.setValue(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/SessionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/SessionInfoTest.java index 852a0d77b4..716cee2fb4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/SessionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/SessionInfoTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for SessionInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class SessionInfoTest extends BaseCommandTestSupport { + public static SessionInfoTest SINGLETON = new SessionInfoTest(); - public static SessionInfoTest SINGLETON = new SessionInfoTest(); + public Object createObject() throws Exception { + SessionInfo info = new SessionInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - SessionInfo info = new SessionInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + SessionInfo info = (SessionInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - SessionInfo info = (SessionInfo) object; - - info.setSessionId(createSessionId("SessionId:1")); - } + info.setSessionId(createSessionId("SessionId:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ShutdownInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ShutdownInfoTest.java index af6e21a79b..d50e923298 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ShutdownInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/ShutdownInfoTest.java @@ -24,32 +24,28 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ShutdownInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ShutdownInfoTest extends BaseCommandTestSupport { + public static ShutdownInfoTest SINGLETON = new ShutdownInfoTest(); - public static ShutdownInfoTest SINGLETON = new ShutdownInfoTest(); + public Object createObject() throws Exception { + ShutdownInfo info = new ShutdownInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ShutdownInfo info = new ShutdownInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ShutdownInfo info = (ShutdownInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ShutdownInfo info = (ShutdownInfo) object; - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/SubscriptionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/SubscriptionInfoTest.java index 5740f3e6f4..f79708ce1c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/SubscriptionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/SubscriptionInfoTest.java @@ -24,37 +24,33 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for SubscriptionInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class SubscriptionInfoTest extends DataFileGeneratorTestSupport { + public static SubscriptionInfoTest SINGLETON = new SubscriptionInfoTest(); - public static SubscriptionInfoTest SINGLETON = new SubscriptionInfoTest(); + public Object createObject() throws Exception { + SubscriptionInfo info = new SubscriptionInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - SubscriptionInfo info = new SubscriptionInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + SubscriptionInfo info = (SubscriptionInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - SubscriptionInfo info = (SubscriptionInfo) object; - - info.setClientId("ClientId:1"); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setSelector("Selector:3"); - info.setSubscriptionName("SubcriptionName:4"); - info.setSubscribedDestination(createActiveMQDestination("SubscribedDestination:5")); - } + info.setClientId("ClientId:1"); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setSelector("Selector:3"); + info.setSubscriptionName("SubcriptionName:4"); + info.setSubscribedDestination(createActiveMQDestination("SubscribedDestination:5")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/TransactionIdTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/TransactionIdTestSupport.java index 25c5f5a43f..54f32ef7d7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/TransactionIdTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/TransactionIdTestSupport.java @@ -24,24 +24,20 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for TransactionId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public abstract class TransactionIdTestSupport extends DataFileGeneratorTestSupport { + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + TransactionId info = (TransactionId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - TransactionId info = (TransactionId) object; - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/TransactionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/TransactionInfoTest.java index ab4a153572..c958cd3493 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/TransactionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/TransactionInfoTest.java @@ -24,35 +24,31 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for TransactionInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class TransactionInfoTest extends BaseCommandTestSupport { + public static TransactionInfoTest SINGLETON = new TransactionInfoTest(); - public static TransactionInfoTest SINGLETON = new TransactionInfoTest(); + public Object createObject() throws Exception { + TransactionInfo info = new TransactionInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - TransactionInfo info = new TransactionInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + TransactionInfo info = (TransactionInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - TransactionInfo info = (TransactionInfo) object; - - info.setConnectionId(createConnectionId("ConnectionId:1")); - info.setTransactionId(createTransactionId("TransactionId:2")); - info.setType((byte) 1); - } + info.setConnectionId(createConnectionId("ConnectionId:1")); + info.setTransactionId(createTransactionId("TransactionId:2")); + info.setType((byte) 1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/XATransactionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/XATransactionIdTest.java index 742a8bdcc3..9312dc934f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/XATransactionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v5/XATransactionIdTest.java @@ -24,35 +24,31 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for XATransactionId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class XATransactionIdTest extends TransactionIdTestSupport { + public static XATransactionIdTest SINGLETON = new XATransactionIdTest(); - public static XATransactionIdTest SINGLETON = new XATransactionIdTest(); + public Object createObject() throws Exception { + XATransactionId info = new XATransactionId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - XATransactionId info = new XATransactionId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + XATransactionId info = (XATransactionId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - XATransactionId info = (XATransactionId) object; - - info.setFormatId(1); - info.setGlobalTransactionId("GlobalTransactionId:1".getBytes()); - info.setBranchQualifier("BranchQualifier:2".getBytes()); - } + info.setFormatId(1); + info.setGlobalTransactionId("GlobalTransactionId:1".getBytes()); + info.setBranchQualifier("BranchQualifier:2".getBytes()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/BaseCommandTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/BaseCommandTestSupport.java index 8c16b553e5..a6f2460ebd 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/BaseCommandTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/BaseCommandTestSupport.java @@ -24,15 +24,14 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; * auto generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * */ public abstract class BaseCommandTestSupport extends DataFileGeneratorTestSupport { - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - BaseCommand info = (BaseCommand)object; - info.setCommandId(1); - info.setResponseRequired(true); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + BaseCommand info = (BaseCommand) object; + info.setCommandId(1); + info.setResponseRequired(true); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/BrokerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/BrokerIdTest.java index 0f5ed87301..ef6874e7f4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/BrokerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/BrokerIdTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for BrokerId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class BrokerIdTest extends DataFileGeneratorTestSupport { + public static BrokerIdTest SINGLETON = new BrokerIdTest(); - public static BrokerIdTest SINGLETON = new BrokerIdTest(); + public Object createObject() throws Exception { + BrokerId info = new BrokerId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - BrokerId info = new BrokerId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + BrokerId info = (BrokerId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - BrokerId info = (BrokerId) object; - - info.setValue("Value:1"); - } + info.setValue("Value:1"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/BrokerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/BrokerInfoTest.java index 8c7f26d13f..7327579486 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/BrokerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/BrokerInfoTest.java @@ -24,50 +24,46 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for BrokerInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class BrokerInfoTest extends BaseCommandTestSupport { + public static BrokerInfoTest SINGLETON = new BrokerInfoTest(); - public static BrokerInfoTest SINGLETON = new BrokerInfoTest(); + public Object createObject() throws Exception { + BrokerInfo info = new BrokerInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - BrokerInfo info = new BrokerInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + BrokerInfo info = (BrokerInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - BrokerInfo info = (BrokerInfo) object; - - info.setBrokerId(createBrokerId("BrokerId:1")); - info.setBrokerURL("BrokerURL:2"); - { - BrokerInfo value[] = new BrokerInfo[0]; - for( int i=0; i < 0; i++ ) { - value[i] = createBrokerInfo("PeerBrokerInfos:3"); - } - info.setPeerBrokerInfos(value); - } - info.setBrokerName("BrokerName:4"); - info.setSlaveBroker(true); - info.setMasterBroker(false); - info.setFaultTolerantConfiguration(true); - info.setDuplexConnection(false); - info.setNetworkConnection(true); - info.setConnectionId(1); - info.setBrokerUploadUrl("BrokerUploadUrl:5"); - info.setNetworkProperties("NetworkProperties:6"); - } + info.setBrokerId(createBrokerId("BrokerId:1")); + info.setBrokerURL("BrokerURL:2"); + { + BrokerInfo value[] = new BrokerInfo[0]; + for (int i = 0; i < 0; i++) { + value[i] = createBrokerInfo("PeerBrokerInfos:3"); + } + info.setPeerBrokerInfos(value); + } + info.setBrokerName("BrokerName:4"); + info.setSlaveBroker(true); + info.setMasterBroker(false); + info.setFaultTolerantConfiguration(true); + info.setDuplexConnection(false); + info.setNetworkConnection(true); + info.setConnectionId(1); + info.setBrokerUploadUrl("BrokerUploadUrl:5"); + info.setNetworkProperties("NetworkProperties:6"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConnectionControlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConnectionControlTest.java index f5aa0ca476..39167c95c6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConnectionControlTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConnectionControlTest.java @@ -24,40 +24,36 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ConnectionControl * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConnectionControlTest extends BaseCommandTestSupport { + public static ConnectionControlTest SINGLETON = new ConnectionControlTest(); - public static ConnectionControlTest SINGLETON = new ConnectionControlTest(); + public Object createObject() throws Exception { + ConnectionControl info = new ConnectionControl(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConnectionControl info = new ConnectionControl(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConnectionControl info = (ConnectionControl) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionControl info = (ConnectionControl) object; - - info.setClose(true); - info.setExit(false); - info.setFaultTolerant(true); - info.setResume(false); - info.setSuspend(true); - info.setConnectedBrokers("ConnectedBrokers:1"); - info.setReconnectTo("ReconnectTo:2"); - info.setRebalanceConnection(false); - } + info.setClose(true); + info.setExit(false); + info.setFaultTolerant(true); + info.setResume(false); + info.setSuspend(true); + info.setConnectedBrokers("ConnectedBrokers:1"); + info.setReconnectTo("ReconnectTo:2"); + info.setRebalanceConnection(false); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConnectionErrorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConnectionErrorTest.java index 156ff9f3fb..571a27791e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConnectionErrorTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConnectionErrorTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ConnectionError * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConnectionErrorTest extends BaseCommandTestSupport { + public static ConnectionErrorTest SINGLETON = new ConnectionErrorTest(); - public static ConnectionErrorTest SINGLETON = new ConnectionErrorTest(); + public Object createObject() throws Exception { + ConnectionError info = new ConnectionError(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConnectionError info = new ConnectionError(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConnectionError info = (ConnectionError) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionError info = (ConnectionError) object; - - info.setException(createThrowable("Exception:1")); - info.setConnectionId(createConnectionId("ConnectionId:2")); - } + info.setException(createThrowable("Exception:1")); + info.setConnectionId(createConnectionId("ConnectionId:2")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConnectionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConnectionIdTest.java index 8fa7559a9e..ae4bf75f7d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConnectionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConnectionIdTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ConnectionId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConnectionIdTest extends DataFileGeneratorTestSupport { + public static ConnectionIdTest SINGLETON = new ConnectionIdTest(); - public static ConnectionIdTest SINGLETON = new ConnectionIdTest(); + public Object createObject() throws Exception { + ConnectionId info = new ConnectionId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConnectionId info = new ConnectionId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConnectionId info = (ConnectionId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionId info = (ConnectionId) object; - - info.setValue("Value:1"); - } + info.setValue("Value:1"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConnectionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConnectionInfoTest.java index fb3ecdb8ed..78d32a4360 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConnectionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConnectionInfoTest.java @@ -24,48 +24,44 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ConnectionInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConnectionInfoTest extends BaseCommandTestSupport { + public static ConnectionInfoTest SINGLETON = new ConnectionInfoTest(); - public static ConnectionInfoTest SINGLETON = new ConnectionInfoTest(); + public Object createObject() throws Exception { + ConnectionInfo info = new ConnectionInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConnectionInfo info = new ConnectionInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConnectionInfo info = (ConnectionInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionInfo info = (ConnectionInfo) object; - - info.setConnectionId(createConnectionId("ConnectionId:1")); - info.setClientId("ClientId:2"); - info.setPassword("Password:3"); - info.setUserName("UserName:4"); - { - BrokerId value[] = new BrokerId[2]; - for( int i=0; i < 2; i++ ) { - value[i] = createBrokerId("BrokerPath:5"); - } - info.setBrokerPath(value); - } - info.setBrokerMasterConnector(true); - info.setManageable(false); - info.setClientMaster(true); - info.setFaultTolerant(false); - info.setFailoverReconnect(true); - } + info.setConnectionId(createConnectionId("ConnectionId:1")); + info.setClientId("ClientId:2"); + info.setPassword("Password:3"); + info.setUserName("UserName:4"); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:5"); + } + info.setBrokerPath(value); + } + info.setBrokerMasterConnector(true); + info.setManageable(false); + info.setClientMaster(true); + info.setFaultTolerant(false); + info.setFailoverReconnect(true); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConsumerControlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConsumerControlTest.java index 275ce11719..0671cf681e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConsumerControlTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConsumerControlTest.java @@ -24,39 +24,35 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ConsumerControl * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConsumerControlTest extends BaseCommandTestSupport { + public static ConsumerControlTest SINGLETON = new ConsumerControlTest(); - public static ConsumerControlTest SINGLETON = new ConsumerControlTest(); + public Object createObject() throws Exception { + ConsumerControl info = new ConsumerControl(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConsumerControl info = new ConsumerControl(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConsumerControl info = (ConsumerControl) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConsumerControl info = (ConsumerControl) object; - - info.setDestination(createActiveMQDestination("Destination:1")); - info.setClose(true); - info.setConsumerId(createConsumerId("ConsumerId:2")); - info.setPrefetch(1); - info.setFlush(false); - info.setStart(true); - info.setStop(false); - } + info.setDestination(createActiveMQDestination("Destination:1")); + info.setClose(true); + info.setConsumerId(createConsumerId("ConsumerId:2")); + info.setPrefetch(1); + info.setFlush(false); + info.setStart(true); + info.setStop(false); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConsumerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConsumerIdTest.java index d322dfbfce..45fc3c3a8b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConsumerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConsumerIdTest.java @@ -24,35 +24,31 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ConsumerId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConsumerIdTest extends DataFileGeneratorTestSupport { + public static ConsumerIdTest SINGLETON = new ConsumerIdTest(); - public static ConsumerIdTest SINGLETON = new ConsumerIdTest(); + public Object createObject() throws Exception { + ConsumerId info = new ConsumerId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConsumerId info = new ConsumerId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConsumerId info = (ConsumerId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConsumerId info = (ConsumerId) object; - - info.setConnectionId("ConnectionId:1"); - info.setSessionId(1); - info.setValue(2); - } + info.setConnectionId("ConnectionId:1"); + info.setSessionId(1); + info.setValue(2); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConsumerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConsumerInfoTest.java index d8d1d0c403..4f15b40ac3 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConsumerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ConsumerInfoTest.java @@ -24,62 +24,58 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ConsumerInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ConsumerInfoTest extends BaseCommandTestSupport { + public static ConsumerInfoTest SINGLETON = new ConsumerInfoTest(); - public static ConsumerInfoTest SINGLETON = new ConsumerInfoTest(); + public Object createObject() throws Exception { + ConsumerInfo info = new ConsumerInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ConsumerInfo info = new ConsumerInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ConsumerInfo info = (ConsumerInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConsumerInfo info = (ConsumerInfo) object; - - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setBrowser(true); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setPrefetchSize(1); - info.setMaximumPendingMessageLimit(2); - info.setDispatchAsync(false); - info.setSelector("Selector:3"); - info.setSubscriptionName("SubscriptionName:4"); - info.setNoLocal(true); - info.setExclusive(false); - info.setRetroactive(true); - info.setPriority((byte) 1); - { - BrokerId value[] = new BrokerId[2]; - for( int i=0; i < 2; i++ ) { - value[i] = createBrokerId("BrokerPath:5"); - } - info.setBrokerPath(value); - } - info.setAdditionalPredicate(createBooleanExpression("AdditionalPredicate:6")); - info.setNetworkSubscription(false); - info.setOptimizedAcknowledge(true); - info.setNoRangeAcks(false); - { - ConsumerId value[] = new ConsumerId[2]; - for( int i=0; i < 2; i++ ) { - value[i] = createConsumerId("NetworkConsumerPath:7"); - } - info.setNetworkConsumerPath(value); - } - } + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setBrowser(true); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setPrefetchSize(1); + info.setMaximumPendingMessageLimit(2); + info.setDispatchAsync(false); + info.setSelector("Selector:3"); + info.setSubscriptionName("SubscriptionName:4"); + info.setNoLocal(true); + info.setExclusive(false); + info.setRetroactive(true); + info.setPriority((byte) 1); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:5"); + } + info.setBrokerPath(value); + } + info.setAdditionalPredicate(createBooleanExpression("AdditionalPredicate:6")); + info.setNetworkSubscription(false); + info.setOptimizedAcknowledge(true); + info.setNoRangeAcks(false); + { + ConsumerId value[] = new ConsumerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createConsumerId("NetworkConsumerPath:7"); + } + info.setNetworkConsumerPath(value); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ControlCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ControlCommandTest.java index 8b48365186..d75aba4aeb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ControlCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ControlCommandTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ControlCommand * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ControlCommandTest extends BaseCommandTestSupport { + public static ControlCommandTest SINGLETON = new ControlCommandTest(); - public static ControlCommandTest SINGLETON = new ControlCommandTest(); + public Object createObject() throws Exception { + ControlCommand info = new ControlCommand(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ControlCommand info = new ControlCommand(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ControlCommand info = (ControlCommand) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ControlCommand info = (ControlCommand) object; - - info.setCommand("Command:1"); - } + info.setCommand("Command:1"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/DataArrayResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/DataArrayResponseTest.java index 1fe80fd5e7..ab2c9b29eb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/DataArrayResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/DataArrayResponseTest.java @@ -24,39 +24,35 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for DataArrayResponse * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class DataArrayResponseTest extends ResponseTest { + public static DataArrayResponseTest SINGLETON = new DataArrayResponseTest(); - public static DataArrayResponseTest SINGLETON = new DataArrayResponseTest(); + public Object createObject() throws Exception { + DataArrayResponse info = new DataArrayResponse(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - DataArrayResponse info = new DataArrayResponse(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + DataArrayResponse info = (DataArrayResponse) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DataArrayResponse info = (DataArrayResponse) object; - - { - DataStructure value[] = new DataStructure[2]; - for( int i=0; i < 2; i++ ) { - value[i] = createDataStructure("Data:1"); - } - info.setData(value); - } - } + { + DataStructure value[] = new DataStructure[2]; + for (int i = 0; i < 2; i++) { + value[i] = createDataStructure("Data:1"); + } + info.setData(value); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/DataResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/DataResponseTest.java index e7728ea0b1..ad88e2a5e0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/DataResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/DataResponseTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for DataResponse * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class DataResponseTest extends ResponseTest { + public static DataResponseTest SINGLETON = new DataResponseTest(); - public static DataResponseTest SINGLETON = new DataResponseTest(); + public Object createObject() throws Exception { + DataResponse info = new DataResponse(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - DataResponse info = new DataResponse(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + DataResponse info = (DataResponse) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DataResponse info = (DataResponse) object; - - info.setData(createDataStructure("Data:1")); - } + info.setData(createDataStructure("Data:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/DestinationInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/DestinationInfoTest.java index ac065e2fa9..930bb10413 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/DestinationInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/DestinationInfoTest.java @@ -24,43 +24,39 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for DestinationInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class DestinationInfoTest extends BaseCommandTestSupport { + public static DestinationInfoTest SINGLETON = new DestinationInfoTest(); - public static DestinationInfoTest SINGLETON = new DestinationInfoTest(); + public Object createObject() throws Exception { + DestinationInfo info = new DestinationInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - DestinationInfo info = new DestinationInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + DestinationInfo info = (DestinationInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DestinationInfo info = (DestinationInfo) object; - - info.setConnectionId(createConnectionId("ConnectionId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setOperationType((byte) 1); - info.setTimeout(1); - { - BrokerId value[] = new BrokerId[2]; - for( int i=0; i < 2; i++ ) { - value[i] = createBrokerId("BrokerPath:3"); - } - info.setBrokerPath(value); - } - } + info.setConnectionId(createConnectionId("ConnectionId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setOperationType((byte) 1); + info.setTimeout(1); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:3"); + } + info.setBrokerPath(value); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/DiscoveryEventTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/DiscoveryEventTest.java index de87bd95b8..66ee50ee72 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/DiscoveryEventTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/DiscoveryEventTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for DiscoveryEvent * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class DiscoveryEventTest extends DataFileGeneratorTestSupport { + public static DiscoveryEventTest SINGLETON = new DiscoveryEventTest(); - public static DiscoveryEventTest SINGLETON = new DiscoveryEventTest(); + public Object createObject() throws Exception { + DiscoveryEvent info = new DiscoveryEvent(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - DiscoveryEvent info = new DiscoveryEvent(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + DiscoveryEvent info = (DiscoveryEvent) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DiscoveryEvent info = (DiscoveryEvent) object; - - info.setServiceName("ServiceName:1"); - info.setBrokerName("BrokerName:2"); - } + info.setServiceName("ServiceName:1"); + info.setBrokerName("BrokerName:2"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ExceptionResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ExceptionResponseTest.java index 9471dfd96d..98c76eb710 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ExceptionResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ExceptionResponseTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ExceptionResponse * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ExceptionResponseTest extends ResponseTest { + public static ExceptionResponseTest SINGLETON = new ExceptionResponseTest(); - public static ExceptionResponseTest SINGLETON = new ExceptionResponseTest(); + public Object createObject() throws Exception { + ExceptionResponse info = new ExceptionResponse(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ExceptionResponse info = new ExceptionResponse(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ExceptionResponse info = (ExceptionResponse) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ExceptionResponse info = (ExceptionResponse) object; - - info.setException(createThrowable("Exception:1")); - } + info.setException(createThrowable("Exception:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/FlushCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/FlushCommandTest.java index 46f4bb403f..6afaf6f2e7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/FlushCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/FlushCommandTest.java @@ -24,32 +24,28 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for FlushCommand * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class FlushCommandTest extends BaseCommandTestSupport { + public static FlushCommandTest SINGLETON = new FlushCommandTest(); - public static FlushCommandTest SINGLETON = new FlushCommandTest(); + public Object createObject() throws Exception { + FlushCommand info = new FlushCommand(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - FlushCommand info = new FlushCommand(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + FlushCommand info = (FlushCommand) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - FlushCommand info = (FlushCommand) object; - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/IntegerResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/IntegerResponseTest.java index 999b047b81..80c8b3be01 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/IntegerResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/IntegerResponseTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for IntegerResponse * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class IntegerResponseTest extends ResponseTest { + public static IntegerResponseTest SINGLETON = new IntegerResponseTest(); - public static IntegerResponseTest SINGLETON = new IntegerResponseTest(); + public Object createObject() throws Exception { + IntegerResponse info = new IntegerResponse(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - IntegerResponse info = new IntegerResponse(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + IntegerResponse info = (IntegerResponse) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - IntegerResponse info = (IntegerResponse) object; - - info.setResult(1); - } + info.setResult(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/JournalQueueAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/JournalQueueAckTest.java index 7757277fa0..8cb9761077 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/JournalQueueAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/JournalQueueAckTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for JournalQueueAck * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class JournalQueueAckTest extends DataFileGeneratorTestSupport { + public static JournalQueueAckTest SINGLETON = new JournalQueueAckTest(); - public static JournalQueueAckTest SINGLETON = new JournalQueueAckTest(); + public Object createObject() throws Exception { + JournalQueueAck info = new JournalQueueAck(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - JournalQueueAck info = new JournalQueueAck(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + JournalQueueAck info = (JournalQueueAck) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalQueueAck info = (JournalQueueAck) object; - - info.setDestination(createActiveMQDestination("Destination:1")); - info.setMessageAck(createMessageAck("MessageAck:2")); - } + info.setDestination(createActiveMQDestination("Destination:1")); + info.setMessageAck(createMessageAck("MessageAck:2")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/JournalTopicAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/JournalTopicAckTest.java index dfcb65858e..c844f37d06 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/JournalTopicAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/JournalTopicAckTest.java @@ -24,38 +24,34 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for JournalTopicAck * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class JournalTopicAckTest extends DataFileGeneratorTestSupport { + public static JournalTopicAckTest SINGLETON = new JournalTopicAckTest(); - public static JournalTopicAckTest SINGLETON = new JournalTopicAckTest(); + public Object createObject() throws Exception { + JournalTopicAck info = new JournalTopicAck(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - JournalTopicAck info = new JournalTopicAck(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + JournalTopicAck info = (JournalTopicAck) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalTopicAck info = (JournalTopicAck) object; - - info.setDestination(createActiveMQDestination("Destination:1")); - info.setMessageId(createMessageId("MessageId:2")); - info.setMessageSequenceId(1); - info.setSubscritionName("SubscritionName:3"); - info.setClientId("ClientId:4"); - info.setTransactionId(createTransactionId("TransactionId:5")); - } + info.setDestination(createActiveMQDestination("Destination:1")); + info.setMessageId(createMessageId("MessageId:2")); + info.setMessageSequenceId(1); + info.setSubscritionName("SubscritionName:3"); + info.setClientId("ClientId:4"); + info.setTransactionId(createTransactionId("TransactionId:5")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/JournalTraceTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/JournalTraceTest.java index 9406aeb030..75c0c60878 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/JournalTraceTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/JournalTraceTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for JournalTrace * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class JournalTraceTest extends DataFileGeneratorTestSupport { + public static JournalTraceTest SINGLETON = new JournalTraceTest(); - public static JournalTraceTest SINGLETON = new JournalTraceTest(); + public Object createObject() throws Exception { + JournalTrace info = new JournalTrace(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - JournalTrace info = new JournalTrace(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + JournalTrace info = (JournalTrace) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalTrace info = (JournalTrace) object; - - info.setMessage("Message:1"); - } + info.setMessage("Message:1"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/JournalTransactionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/JournalTransactionTest.java index d61fe9f2a5..18cab1bbb8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/JournalTransactionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/JournalTransactionTest.java @@ -24,35 +24,31 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for JournalTransaction * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class JournalTransactionTest extends DataFileGeneratorTestSupport { + public static JournalTransactionTest SINGLETON = new JournalTransactionTest(); - public static JournalTransactionTest SINGLETON = new JournalTransactionTest(); + public Object createObject() throws Exception { + JournalTransaction info = new JournalTransaction(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - JournalTransaction info = new JournalTransaction(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + JournalTransaction info = (JournalTransaction) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalTransaction info = (JournalTransaction) object; - - info.setTransactionId(createTransactionId("TransactionId:1")); - info.setType((byte) 1); - info.setWasPrepared(true); - } + info.setTransactionId(createTransactionId("TransactionId:1")); + info.setType((byte) 1); + info.setWasPrepared(true); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/KeepAliveInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/KeepAliveInfoTest.java index 67d61f0850..241231f73c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/KeepAliveInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/KeepAliveInfoTest.java @@ -24,32 +24,28 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for KeepAliveInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class KeepAliveInfoTest extends BaseCommandTestSupport { + public static KeepAliveInfoTest SINGLETON = new KeepAliveInfoTest(); - public static KeepAliveInfoTest SINGLETON = new KeepAliveInfoTest(); + public Object createObject() throws Exception { + KeepAliveInfo info = new KeepAliveInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - KeepAliveInfo info = new KeepAliveInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + KeepAliveInfo info = (KeepAliveInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - KeepAliveInfo info = (KeepAliveInfo) object; - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/LastPartialCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/LastPartialCommandTest.java index 4ede0f51b5..11a8eb2255 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/LastPartialCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/LastPartialCommandTest.java @@ -24,32 +24,28 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for LastPartialCommand * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class LastPartialCommandTest extends PartialCommandTest { + public static LastPartialCommandTest SINGLETON = new LastPartialCommandTest(); - public static LastPartialCommandTest SINGLETON = new LastPartialCommandTest(); + public Object createObject() throws Exception { + LastPartialCommand info = new LastPartialCommand(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - LastPartialCommand info = new LastPartialCommand(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + LastPartialCommand info = (LastPartialCommand) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - LastPartialCommand info = (LastPartialCommand) object; - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/LocalTransactionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/LocalTransactionIdTest.java index 02ea10d0bb..89a2c5f64f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/LocalTransactionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/LocalTransactionIdTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for LocalTransactionId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class LocalTransactionIdTest extends TransactionIdTestSupport { + public static LocalTransactionIdTest SINGLETON = new LocalTransactionIdTest(); - public static LocalTransactionIdTest SINGLETON = new LocalTransactionIdTest(); + public Object createObject() throws Exception { + LocalTransactionId info = new LocalTransactionId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - LocalTransactionId info = new LocalTransactionId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + LocalTransactionId info = (LocalTransactionId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - LocalTransactionId info = (LocalTransactionId) object; - - info.setValue(1); - info.setConnectionId(createConnectionId("ConnectionId:1")); - } + info.setValue(1); + info.setConnectionId(createConnectionId("ConnectionId:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/MessageAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/MessageAckTest.java index b66c6ce106..89acfabb63 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/MessageAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/MessageAckTest.java @@ -24,39 +24,35 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for MessageAck * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class MessageAckTest extends BaseCommandTestSupport { + public static MessageAckTest SINGLETON = new MessageAckTest(); - public static MessageAckTest SINGLETON = new MessageAckTest(); + public Object createObject() throws Exception { + MessageAck info = new MessageAck(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - MessageAck info = new MessageAck(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessageAck info = (MessageAck) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageAck info = (MessageAck) object; - - info.setDestination(createActiveMQDestination("Destination:1")); - info.setTransactionId(createTransactionId("TransactionId:2")); - info.setConsumerId(createConsumerId("ConsumerId:3")); - info.setAckType((byte) 1); - info.setFirstMessageId(createMessageId("FirstMessageId:4")); - info.setLastMessageId(createMessageId("LastMessageId:5")); - info.setMessageCount(1); - } + info.setDestination(createActiveMQDestination("Destination:1")); + info.setTransactionId(createTransactionId("TransactionId:2")); + info.setConsumerId(createConsumerId("ConsumerId:3")); + info.setAckType((byte) 1); + info.setFirstMessageId(createMessageId("FirstMessageId:4")); + info.setLastMessageId(createMessageId("LastMessageId:5")); + info.setMessageCount(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/MessageDispatchNotificationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/MessageDispatchNotificationTest.java index aa805cadca..055274da6e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/MessageDispatchNotificationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/MessageDispatchNotificationTest.java @@ -24,36 +24,32 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for MessageDispatchNotification * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class MessageDispatchNotificationTest extends BaseCommandTestSupport { + public static MessageDispatchNotificationTest SINGLETON = new MessageDispatchNotificationTest(); - public static MessageDispatchNotificationTest SINGLETON = new MessageDispatchNotificationTest(); + public Object createObject() throws Exception { + MessageDispatchNotification info = new MessageDispatchNotification(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - MessageDispatchNotification info = new MessageDispatchNotification(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessageDispatchNotification info = (MessageDispatchNotification) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageDispatchNotification info = (MessageDispatchNotification) object; - - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setDeliverySequenceId(1); - info.setMessageId(createMessageId("MessageId:3")); - } + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setDeliverySequenceId(1); + info.setMessageId(createMessageId("MessageId:3")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/MessageDispatchTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/MessageDispatchTest.java index bbc0459174..3f38a16b3f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/MessageDispatchTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/MessageDispatchTest.java @@ -24,36 +24,32 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for MessageDispatch * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class MessageDispatchTest extends BaseCommandTestSupport { + public static MessageDispatchTest SINGLETON = new MessageDispatchTest(); - public static MessageDispatchTest SINGLETON = new MessageDispatchTest(); + public Object createObject() throws Exception { + MessageDispatch info = new MessageDispatch(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - MessageDispatch info = new MessageDispatch(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessageDispatch info = (MessageDispatch) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageDispatch info = (MessageDispatch) object; - - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setMessage(createMessage("Message:3")); - info.setRedeliveryCounter(1); - } + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setMessage(createMessage("Message:3")); + info.setRedeliveryCounter(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/MessageIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/MessageIdTest.java index 1f61361d57..4d85416ce9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/MessageIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/MessageIdTest.java @@ -24,35 +24,31 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for MessageId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class MessageIdTest extends DataFileGeneratorTestSupport { + public static MessageIdTest SINGLETON = new MessageIdTest(); - public static MessageIdTest SINGLETON = new MessageIdTest(); + public Object createObject() throws Exception { + MessageId info = new MessageId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - MessageId info = new MessageId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessageId info = (MessageId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageId info = (MessageId) object; - - info.setProducerId(createProducerId("ProducerId:1")); - info.setProducerSequenceId(1); - info.setBrokerSequenceId(2); - } + info.setProducerId(createProducerId("ProducerId:1")); + info.setProducerSequenceId(1); + info.setBrokerSequenceId(2); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/MessagePullTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/MessagePullTest.java index f0d48a6269..7c2ce1cf88 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/MessagePullTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/MessagePullTest.java @@ -24,37 +24,33 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for MessagePull * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class MessagePullTest extends BaseCommandTestSupport { + public static MessagePullTest SINGLETON = new MessagePullTest(); - public static MessagePullTest SINGLETON = new MessagePullTest(); + public Object createObject() throws Exception { + MessagePull info = new MessagePull(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - MessagePull info = new MessagePull(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + MessagePull info = (MessagePull) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessagePull info = (MessagePull) object; - - info.setConsumerId(createConsumerId("ConsumerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setTimeout(1); - info.setCorrelationId("CorrelationId:3"); - info.setMessageId(createMessageId("MessageId:4")); - } + info.setConsumerId(createConsumerId("ConsumerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setTimeout(1); + info.setCorrelationId("CorrelationId:3"); + info.setMessageId(createMessageId("MessageId:4")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/MessageTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/MessageTestSupport.java index 863ee595c3..92edf106aa 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/MessageTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/MessageTestSupport.java @@ -19,71 +19,67 @@ package org.apache.activemq.openwire.v6; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for Message * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public abstract class MessageTestSupport extends BaseCommandTestSupport { + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + Message info = (Message) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - Message info = (Message) object; - - info.setProducerId(createProducerId("ProducerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setTransactionId(createTransactionId("TransactionId:3")); - info.setOriginalDestination(createActiveMQDestination("OriginalDestination:4")); - info.setMessageId(createMessageId("MessageId:5")); - info.setOriginalTransactionId(createTransactionId("OriginalTransactionId:6")); - info.setGroupID("GroupID:7"); - info.setGroupSequence(1); - info.setCorrelationId("CorrelationId:8"); - info.setPersistent(true); - info.setExpiration(1); - info.setPriority((byte) 1); - info.setReplyTo(createActiveMQDestination("ReplyTo:9")); - info.setTimestamp(2); - info.setType("Type:10"); - { - byte data[] = "Content:11".getBytes(); - info.setContent(new org.apache.activemq.util.ByteSequence(data,0,data.length)); -} - { - byte data[] = "MarshalledProperties:12".getBytes(); - info.setMarshalledProperties(new org.apache.activemq.util.ByteSequence(data,0,data.length)); -} - info.setDataStructure(createDataStructure("DataStructure:13")); - info.setTargetConsumerId(createConsumerId("TargetConsumerId:14")); - info.setCompressed(false); - info.setRedeliveryCounter(2); - { - BrokerId value[] = new BrokerId[2]; - for( int i=0; i < 2; i++ ) { - value[i] = createBrokerId("BrokerPath:15"); - } - info.setBrokerPath(value); - } - info.setArrival(3); - info.setUserID("UserID:16"); - info.setRecievedByDFBridge(true); - info.setDroppable(false); - { - BrokerId value[] = new BrokerId[2]; - for( int i=0; i < 2; i++ ) { - value[i] = createBrokerId("Cluster:17"); - } - info.setCluster(value); - } - info.setBrokerInTime(4); - info.setBrokerOutTime(5); - } + info.setProducerId(createProducerId("ProducerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setTransactionId(createTransactionId("TransactionId:3")); + info.setOriginalDestination(createActiveMQDestination("OriginalDestination:4")); + info.setMessageId(createMessageId("MessageId:5")); + info.setOriginalTransactionId(createTransactionId("OriginalTransactionId:6")); + info.setGroupID("GroupID:7"); + info.setGroupSequence(1); + info.setCorrelationId("CorrelationId:8"); + info.setPersistent(true); + info.setExpiration(1); + info.setPriority((byte) 1); + info.setReplyTo(createActiveMQDestination("ReplyTo:9")); + info.setTimestamp(2); + info.setType("Type:10"); + { + byte data[] = "Content:11".getBytes(); + info.setContent(new org.apache.activemq.util.ByteSequence(data, 0, data.length)); + } + { + byte data[] = "MarshalledProperties:12".getBytes(); + info.setMarshalledProperties(new org.apache.activemq.util.ByteSequence(data, 0, data.length)); + } + info.setDataStructure(createDataStructure("DataStructure:13")); + info.setTargetConsumerId(createConsumerId("TargetConsumerId:14")); + info.setCompressed(false); + info.setRedeliveryCounter(2); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:15"); + } + info.setBrokerPath(value); + } + info.setArrival(3); + info.setUserID("UserID:16"); + info.setRecievedByDFBridge(true); + info.setDroppable(false); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("Cluster:17"); + } + info.setCluster(value); + } + info.setBrokerInTime(4); + info.setBrokerOutTime(5); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/NetworkBridgeFilterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/NetworkBridgeFilterTest.java index e6bcf5433d..19c15b1081 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/NetworkBridgeFilterTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/NetworkBridgeFilterTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for NetworkBridgeFilter * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class NetworkBridgeFilterTest extends DataFileGeneratorTestSupport { + public static NetworkBridgeFilterTest SINGLETON = new NetworkBridgeFilterTest(); - public static NetworkBridgeFilterTest SINGLETON = new NetworkBridgeFilterTest(); + public Object createObject() throws Exception { + NetworkBridgeFilter info = new NetworkBridgeFilter(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - NetworkBridgeFilter info = new NetworkBridgeFilter(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + NetworkBridgeFilter info = (NetworkBridgeFilter) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - NetworkBridgeFilter info = (NetworkBridgeFilter) object; - - info.setNetworkTTL(1); - info.setNetworkBrokerId(createBrokerId("NetworkBrokerId:1")); - } + info.setNetworkTTL(1); + info.setNetworkBrokerId(createBrokerId("NetworkBrokerId:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/PartialCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/PartialCommandTest.java index 2f0e8ee92a..79793794ec 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/PartialCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/PartialCommandTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for PartialCommand * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class PartialCommandTest extends DataFileGeneratorTestSupport { + public static PartialCommandTest SINGLETON = new PartialCommandTest(); - public static PartialCommandTest SINGLETON = new PartialCommandTest(); + public Object createObject() throws Exception { + PartialCommand info = new PartialCommand(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - PartialCommand info = new PartialCommand(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + PartialCommand info = (PartialCommand) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - PartialCommand info = (PartialCommand) object; - - info.setCommandId(1); - info.setData("Data:1".getBytes()); - } + info.setCommandId(1); + info.setData("Data:1".getBytes()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ProducerAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ProducerAckTest.java index f4db4a95b0..636a5c800c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ProducerAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ProducerAckTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ProducerAck * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ProducerAckTest extends BaseCommandTestSupport { + public static ProducerAckTest SINGLETON = new ProducerAckTest(); - public static ProducerAckTest SINGLETON = new ProducerAckTest(); + public Object createObject() throws Exception { + ProducerAck info = new ProducerAck(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ProducerAck info = new ProducerAck(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ProducerAck info = (ProducerAck) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ProducerAck info = (ProducerAck) object; - - info.setProducerId(createProducerId("ProducerId:1")); - info.setSize(1); - } + info.setProducerId(createProducerId("ProducerId:1")); + info.setSize(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ProducerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ProducerIdTest.java index 17c88d32dc..209f70e692 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ProducerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ProducerIdTest.java @@ -24,35 +24,31 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ProducerId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ProducerIdTest extends DataFileGeneratorTestSupport { + public static ProducerIdTest SINGLETON = new ProducerIdTest(); - public static ProducerIdTest SINGLETON = new ProducerIdTest(); + public Object createObject() throws Exception { + ProducerId info = new ProducerId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ProducerId info = new ProducerId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ProducerId info = (ProducerId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ProducerId info = (ProducerId) object; - - info.setConnectionId("ConnectionId:1"); - info.setValue(1); - info.setSessionId(2); - } + info.setConnectionId("ConnectionId:1"); + info.setValue(1); + info.setSessionId(2); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ProducerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ProducerInfoTest.java index d960980596..20044bf4e2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ProducerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ProducerInfoTest.java @@ -24,43 +24,39 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ProducerInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ProducerInfoTest extends BaseCommandTestSupport { + public static ProducerInfoTest SINGLETON = new ProducerInfoTest(); - public static ProducerInfoTest SINGLETON = new ProducerInfoTest(); + public Object createObject() throws Exception { + ProducerInfo info = new ProducerInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ProducerInfo info = new ProducerInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ProducerInfo info = (ProducerInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ProducerInfo info = (ProducerInfo) object; - - info.setProducerId(createProducerId("ProducerId:1")); - info.setDestination(createActiveMQDestination("Destination:2")); - { - BrokerId value[] = new BrokerId[2]; - for( int i=0; i < 2; i++ ) { - value[i] = createBrokerId("BrokerPath:3"); - } - info.setBrokerPath(value); - } - info.setDispatchAsync(true); - info.setWindowSize(1); - } + info.setProducerId(createProducerId("ProducerId:1")); + info.setDestination(createActiveMQDestination("Destination:2")); + { + BrokerId value[] = new BrokerId[2]; + for (int i = 0; i < 2; i++) { + value[i] = createBrokerId("BrokerPath:3"); + } + info.setBrokerPath(value); + } + info.setDispatchAsync(true); + info.setWindowSize(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/RemoveInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/RemoveInfoTest.java index 503393589b..13d0118a89 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/RemoveInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/RemoveInfoTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for RemoveInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class RemoveInfoTest extends BaseCommandTestSupport { + public static RemoveInfoTest SINGLETON = new RemoveInfoTest(); - public static RemoveInfoTest SINGLETON = new RemoveInfoTest(); + public Object createObject() throws Exception { + RemoveInfo info = new RemoveInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - RemoveInfo info = new RemoveInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + RemoveInfo info = (RemoveInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - RemoveInfo info = (RemoveInfo) object; - - info.setObjectId(createDataStructure("ObjectId:1")); - info.setLastDeliveredSequenceId(1); - } + info.setObjectId(createDataStructure("ObjectId:1")); + info.setLastDeliveredSequenceId(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/RemoveSubscriptionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/RemoveSubscriptionInfoTest.java index 9b86af573e..913c1c3084 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/RemoveSubscriptionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/RemoveSubscriptionInfoTest.java @@ -24,35 +24,31 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for RemoveSubscriptionInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class RemoveSubscriptionInfoTest extends BaseCommandTestSupport { + public static RemoveSubscriptionInfoTest SINGLETON = new RemoveSubscriptionInfoTest(); - public static RemoveSubscriptionInfoTest SINGLETON = new RemoveSubscriptionInfoTest(); + public Object createObject() throws Exception { + RemoveSubscriptionInfo info = new RemoveSubscriptionInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - RemoveSubscriptionInfo info = new RemoveSubscriptionInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + RemoveSubscriptionInfo info = (RemoveSubscriptionInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - RemoveSubscriptionInfo info = (RemoveSubscriptionInfo) object; - - info.setConnectionId(createConnectionId("ConnectionId:1")); - info.setSubcriptionName("SubcriptionName:2"); - info.setClientId("ClientId:3"); - } + info.setConnectionId(createConnectionId("ConnectionId:1")); + info.setSubcriptionName("SubcriptionName:2"); + info.setClientId("ClientId:3"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ReplayCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ReplayCommandTest.java index d26de2529c..c808ada380 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ReplayCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ReplayCommandTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ReplayCommand * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ReplayCommandTest extends BaseCommandTestSupport { + public static ReplayCommandTest SINGLETON = new ReplayCommandTest(); - public static ReplayCommandTest SINGLETON = new ReplayCommandTest(); + public Object createObject() throws Exception { + ReplayCommand info = new ReplayCommand(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ReplayCommand info = new ReplayCommand(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ReplayCommand info = (ReplayCommand) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ReplayCommand info = (ReplayCommand) object; - - info.setFirstNakNumber(1); - info.setLastNakNumber(2); - } + info.setFirstNakNumber(1); + info.setLastNakNumber(2); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ResponseTest.java index 8153f23ed5..903fd3f799 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ResponseTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for Response * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ResponseTest extends BaseCommandTestSupport { + public static ResponseTest SINGLETON = new ResponseTest(); - public static ResponseTest SINGLETON = new ResponseTest(); + public Object createObject() throws Exception { + Response info = new Response(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - Response info = new Response(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + Response info = (Response) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - Response info = (Response) object; - - info.setCorrelationId(1); - } + info.setCorrelationId(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/SessionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/SessionIdTest.java index 404fb200d3..a0d272e2bf 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/SessionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/SessionIdTest.java @@ -24,34 +24,30 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for SessionId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class SessionIdTest extends DataFileGeneratorTestSupport { + public static SessionIdTest SINGLETON = new SessionIdTest(); - public static SessionIdTest SINGLETON = new SessionIdTest(); + public Object createObject() throws Exception { + SessionId info = new SessionId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - SessionId info = new SessionId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + SessionId info = (SessionId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - SessionId info = (SessionId) object; - - info.setConnectionId("ConnectionId:1"); - info.setValue(1); - } + info.setConnectionId("ConnectionId:1"); + info.setValue(1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/SessionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/SessionInfoTest.java index 2d69568542..5ba5884a8b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/SessionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/SessionInfoTest.java @@ -24,33 +24,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for SessionInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class SessionInfoTest extends BaseCommandTestSupport { + public static SessionInfoTest SINGLETON = new SessionInfoTest(); - public static SessionInfoTest SINGLETON = new SessionInfoTest(); + public Object createObject() throws Exception { + SessionInfo info = new SessionInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - SessionInfo info = new SessionInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + SessionInfo info = (SessionInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - SessionInfo info = (SessionInfo) object; - - info.setSessionId(createSessionId("SessionId:1")); - } + info.setSessionId(createSessionId("SessionId:1")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ShutdownInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ShutdownInfoTest.java index 5a90219b32..02cb37abe6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ShutdownInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/ShutdownInfoTest.java @@ -24,32 +24,28 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ShutdownInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class ShutdownInfoTest extends BaseCommandTestSupport { + public static ShutdownInfoTest SINGLETON = new ShutdownInfoTest(); - public static ShutdownInfoTest SINGLETON = new ShutdownInfoTest(); + public Object createObject() throws Exception { + ShutdownInfo info = new ShutdownInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - ShutdownInfo info = new ShutdownInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + ShutdownInfo info = (ShutdownInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ShutdownInfo info = (ShutdownInfo) object; - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/SubscriptionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/SubscriptionInfoTest.java index df5e24ee73..2af59c6002 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/SubscriptionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/SubscriptionInfoTest.java @@ -24,37 +24,33 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for SubscriptionInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class SubscriptionInfoTest extends DataFileGeneratorTestSupport { + public static SubscriptionInfoTest SINGLETON = new SubscriptionInfoTest(); - public static SubscriptionInfoTest SINGLETON = new SubscriptionInfoTest(); + public Object createObject() throws Exception { + SubscriptionInfo info = new SubscriptionInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - SubscriptionInfo info = new SubscriptionInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + SubscriptionInfo info = (SubscriptionInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - SubscriptionInfo info = (SubscriptionInfo) object; - - info.setClientId("ClientId:1"); - info.setDestination(createActiveMQDestination("Destination:2")); - info.setSelector("Selector:3"); - info.setSubcriptionName("SubcriptionName:4"); - info.setSubscribedDestination(createActiveMQDestination("SubscribedDestination:5")); - } + info.setClientId("ClientId:1"); + info.setDestination(createActiveMQDestination("Destination:2")); + info.setSelector("Selector:3"); + info.setSubcriptionName("SubcriptionName:4"); + info.setSubscribedDestination(createActiveMQDestination("SubscribedDestination:5")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/TransactionIdTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/TransactionIdTestSupport.java index f2f0ec967e..791e5d2ac7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/TransactionIdTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/TransactionIdTestSupport.java @@ -24,24 +24,20 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for TransactionId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public abstract class TransactionIdTestSupport extends DataFileGeneratorTestSupport { + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + TransactionId info = (TransactionId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - TransactionId info = (TransactionId) object; - - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/TransactionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/TransactionInfoTest.java index fb4e5ca54e..9df27f4cb0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/TransactionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/TransactionInfoTest.java @@ -24,35 +24,31 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for TransactionInfo * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class TransactionInfoTest extends BaseCommandTestSupport { + public static TransactionInfoTest SINGLETON = new TransactionInfoTest(); - public static TransactionInfoTest SINGLETON = new TransactionInfoTest(); + public Object createObject() throws Exception { + TransactionInfo info = new TransactionInfo(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - TransactionInfo info = new TransactionInfo(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + TransactionInfo info = (TransactionInfo) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - TransactionInfo info = (TransactionInfo) object; - - info.setConnectionId(createConnectionId("ConnectionId:1")); - info.setTransactionId(createTransactionId("TransactionId:2")); - info.setType((byte) 1); - } + info.setConnectionId(createConnectionId("ConnectionId:1")); + info.setTransactionId(createTransactionId("TransactionId:2")); + info.setType((byte) 1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/XATransactionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/XATransactionIdTest.java index c4e1c04c88..65bb5815f9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/XATransactionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v6/XATransactionIdTest.java @@ -24,35 +24,31 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for XATransactionId * * * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * - * + * if you need to make a change, please see the modify the groovy scripts in the + * under src/gram/script and then use maven openwire:generate to regenerate + * this file. */ public class XATransactionIdTest extends TransactionIdTestSupport { + public static XATransactionIdTest SINGLETON = new XATransactionIdTest(); - public static XATransactionIdTest SINGLETON = new XATransactionIdTest(); + public Object createObject() throws Exception { + XATransactionId info = new XATransactionId(); + populateObject(info); + return info; + } - public Object createObject() throws Exception { - XATransactionId info = new XATransactionId(); - populateObject(info); - return info; - } + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + XATransactionId info = (XATransactionId) object; - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - XATransactionId info = (XATransactionId) object; - - info.setFormatId(1); - info.setGlobalTransactionId("GlobalTransactionId:1".getBytes()); - info.setBranchQualifier("BranchQualifier:2".getBytes()); - } + info.setFormatId(1); + info.setGlobalTransactionId("GlobalTransactionId:1".getBytes()); + info.setBranchQualifier("BranchQualifier:2".getBytes()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/BaseCommandTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/BaseCommandTestSupport.java index f741fba52a..03e354898e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/BaseCommandTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/BaseCommandTestSupport.java @@ -24,15 +24,14 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; * auto generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * */ public abstract class BaseCommandTestSupport extends DataFileGeneratorTestSupport { - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - BaseCommand info = (BaseCommand)object; - info.setCommandId(1); - info.setResponseRequired(true); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + BaseCommand info = (BaseCommand) object; + info.setCommandId(1); + info.setResponseRequired(true); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/BrokerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/BrokerIdTest.java index b701693dee..20beaccd55 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/BrokerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/BrokerIdTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for BrokerId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class BrokerIdTest extends DataFileGeneratorTestSupport { public static BrokerIdTest SINGLETON = new BrokerIdTest(); public Object createObject() throws Exception { BrokerId info = new BrokerId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); BrokerId info = (BrokerId) object; info.setValue("Value:1"); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for BrokerId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class BrokerIdTest extends DataFileGeneratorTestSupport { public static BrokerIdTest SINGLETON = new BrokerIdTest(); public Object createObject() throws Exception { BrokerId info = new BrokerId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); BrokerId info = (BrokerId) object; info.setValue("Value:1"); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/BrokerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/BrokerInfoTest.java index 657e60f896..cb15d0c82c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/BrokerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/BrokerInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for BrokerInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class BrokerInfoTest extends BaseCommandTestSupport { public static BrokerInfoTest SINGLETON = new BrokerInfoTest(); public Object createObject() throws Exception { BrokerInfo info = new BrokerInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); BrokerInfo info = (BrokerInfo) object; info.setBrokerId(createBrokerId("BrokerId:1")); info.setBrokerURL("BrokerURL:2"); { BrokerInfo value[] = new BrokerInfo[0]; for( int i=0; i < 0; i++ ) { value[i] = createBrokerInfo("PeerBrokerInfos:3"); } info.setPeerBrokerInfos(value); } info.setBrokerName("BrokerName:4"); info.setSlaveBroker(true); info.setMasterBroker(false); info.setFaultTolerantConfiguration(true); info.setDuplexConnection(false); info.setNetworkConnection(true); info.setConnectionId(1); info.setBrokerUploadUrl("BrokerUploadUrl:5"); info.setNetworkProperties("NetworkProperties:6"); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for BrokerInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class BrokerInfoTest extends BaseCommandTestSupport { public static BrokerInfoTest SINGLETON = new BrokerInfoTest(); public Object createObject() throws Exception { BrokerInfo info = new BrokerInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); BrokerInfo info = (BrokerInfo) object; info.setBrokerId(createBrokerId("BrokerId:1")); info.setBrokerURL("BrokerURL:2"); { BrokerInfo value[] = new BrokerInfo[0]; for (int i = 0; i < 0; i++) { value[i] = createBrokerInfo("PeerBrokerInfos:3"); } info.setPeerBrokerInfos(value); } info.setBrokerName("BrokerName:4"); info.setSlaveBroker(true); info.setMasterBroker(false); info.setFaultTolerantConfiguration(true); info.setDuplexConnection(false); info.setNetworkConnection(true); info.setConnectionId(1); info.setBrokerUploadUrl("BrokerUploadUrl:5"); info.setNetworkProperties("NetworkProperties:6"); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConnectionControlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConnectionControlTest.java index cff204ea60..f0de0554b0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConnectionControlTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConnectionControlTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConnectionControl * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ConnectionControlTest extends BaseCommandTestSupport { public static ConnectionControlTest SINGLETON = new ConnectionControlTest(); public Object createObject() throws Exception { ConnectionControl info = new ConnectionControl(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConnectionControl info = (ConnectionControl) object; info.setClose(true); info.setExit(false); info.setFaultTolerant(true); info.setResume(false); info.setSuspend(true); info.setConnectedBrokers("ConnectedBrokers:1"); info.setReconnectTo("ReconnectTo:2"); info.setRebalanceConnection(false); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConnectionControl * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ConnectionControlTest extends BaseCommandTestSupport { public static ConnectionControlTest SINGLETON = new ConnectionControlTest(); public Object createObject() throws Exception { ConnectionControl info = new ConnectionControl(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConnectionControl info = (ConnectionControl) object; info.setClose(true); info.setExit(false); info.setFaultTolerant(true); info.setResume(false); info.setSuspend(true); info.setConnectedBrokers("ConnectedBrokers:1"); info.setReconnectTo("ReconnectTo:2"); info.setRebalanceConnection(false); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConnectionErrorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConnectionErrorTest.java index 46cfa3c891..f96a33000b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConnectionErrorTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConnectionErrorTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConnectionError * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ConnectionErrorTest extends BaseCommandTestSupport { public static ConnectionErrorTest SINGLETON = new ConnectionErrorTest(); public Object createObject() throws Exception { ConnectionError info = new ConnectionError(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConnectionError info = (ConnectionError) object; info.setException(createThrowable("Exception:1")); info.setConnectionId(createConnectionId("ConnectionId:2")); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConnectionError * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ConnectionErrorTest extends BaseCommandTestSupport { public static ConnectionErrorTest SINGLETON = new ConnectionErrorTest(); public Object createObject() throws Exception { ConnectionError info = new ConnectionError(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConnectionError info = (ConnectionError) object; info.setException(createThrowable("Exception:1")); info.setConnectionId(createConnectionId("ConnectionId:2")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConnectionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConnectionIdTest.java index 54fc16ce43..518b61c787 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConnectionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConnectionIdTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConnectionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ConnectionIdTest extends DataFileGeneratorTestSupport { public static ConnectionIdTest SINGLETON = new ConnectionIdTest(); public Object createObject() throws Exception { ConnectionId info = new ConnectionId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConnectionId info = (ConnectionId) object; info.setValue("Value:1"); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConnectionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ConnectionIdTest extends DataFileGeneratorTestSupport { public static ConnectionIdTest SINGLETON = new ConnectionIdTest(); public Object createObject() throws Exception { ConnectionId info = new ConnectionId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConnectionId info = (ConnectionId) object; info.setValue("Value:1"); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConnectionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConnectionInfoTest.java index c059052b7c..98b1eade67 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConnectionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConnectionInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConnectionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ConnectionInfoTest extends BaseCommandTestSupport { public static ConnectionInfoTest SINGLETON = new ConnectionInfoTest(); public Object createObject() throws Exception { ConnectionInfo info = new ConnectionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConnectionInfo info = (ConnectionInfo) object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setClientId("ClientId:2"); info.setPassword("Password:3"); info.setUserName("UserName:4"); { BrokerId value[] = new BrokerId[2]; for( int i=0; i < 2; i++ ) { value[i] = createBrokerId("BrokerPath:5"); } info.setBrokerPath(value); } info.setBrokerMasterConnector(true); info.setManageable(false); info.setClientMaster(true); info.setFaultTolerant(false); info.setFailoverReconnect(true); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConnectionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ConnectionInfoTest extends BaseCommandTestSupport { public static ConnectionInfoTest SINGLETON = new ConnectionInfoTest(); public Object createObject() throws Exception { ConnectionInfo info = new ConnectionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConnectionInfo info = (ConnectionInfo) object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setClientId("ClientId:2"); info.setPassword("Password:3"); info.setUserName("UserName:4"); { BrokerId value[] = new BrokerId[2]; for (int i = 0; i < 2; i++) { value[i] = createBrokerId("BrokerPath:5"); } info.setBrokerPath(value); } info.setBrokerMasterConnector(true); info.setManageable(false); info.setClientMaster(true); info.setFaultTolerant(false); info.setFailoverReconnect(true); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConsumerControlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConsumerControlTest.java index df1b48089d..a08dc2e58b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConsumerControlTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConsumerControlTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConsumerControl * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ConsumerControlTest extends BaseCommandTestSupport { public static ConsumerControlTest SINGLETON = new ConsumerControlTest(); public Object createObject() throws Exception { ConsumerControl info = new ConsumerControl(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConsumerControl info = (ConsumerControl) object; info.setDestination(createActiveMQDestination("Destination:1")); info.setClose(true); info.setConsumerId(createConsumerId("ConsumerId:2")); info.setPrefetch(1); info.setFlush(false); info.setStart(true); info.setStop(false); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConsumerControl * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ConsumerControlTest extends BaseCommandTestSupport { public static ConsumerControlTest SINGLETON = new ConsumerControlTest(); public Object createObject() throws Exception { ConsumerControl info = new ConsumerControl(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConsumerControl info = (ConsumerControl) object; info.setDestination(createActiveMQDestination("Destination:1")); info.setClose(true); info.setConsumerId(createConsumerId("ConsumerId:2")); info.setPrefetch(1); info.setFlush(false); info.setStart(true); info.setStop(false); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConsumerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConsumerIdTest.java index 32db0ac4ce..f06db24554 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConsumerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConsumerIdTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConsumerId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ConsumerIdTest extends DataFileGeneratorTestSupport { public static ConsumerIdTest SINGLETON = new ConsumerIdTest(); public Object createObject() throws Exception { ConsumerId info = new ConsumerId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConsumerId info = (ConsumerId) object; info.setConnectionId("ConnectionId:1"); info.setSessionId(1); info.setValue(2); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConsumerId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ConsumerIdTest extends DataFileGeneratorTestSupport { public static ConsumerIdTest SINGLETON = new ConsumerIdTest(); public Object createObject() throws Exception { ConsumerId info = new ConsumerId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConsumerId info = (ConsumerId) object; info.setConnectionId("ConnectionId:1"); info.setSessionId(1); info.setValue(2); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConsumerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConsumerInfoTest.java index e3a120712e..309ad4ccf7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConsumerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ConsumerInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConsumerInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ConsumerInfoTest extends BaseCommandTestSupport { public static ConsumerInfoTest SINGLETON = new ConsumerInfoTest(); public Object createObject() throws Exception { ConsumerInfo info = new ConsumerInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConsumerInfo info = (ConsumerInfo) object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setBrowser(true); info.setDestination(createActiveMQDestination("Destination:2")); info.setPrefetchSize(1); info.setMaximumPendingMessageLimit(2); info.setDispatchAsync(false); info.setSelector("Selector:3"); info.setSubscriptionName("SubscriptionName:4"); info.setNoLocal(true); info.setExclusive(false); info.setRetroactive(true); info.setPriority((byte) 1); { BrokerId value[] = new BrokerId[2]; for( int i=0; i < 2; i++ ) { value[i] = createBrokerId("BrokerPath:5"); } info.setBrokerPath(value); } info.setAdditionalPredicate(createBooleanExpression("AdditionalPredicate:6")); info.setNetworkSubscription(false); info.setOptimizedAcknowledge(true); info.setNoRangeAcks(false); { ConsumerId value[] = new ConsumerId[2]; for( int i=0; i < 2; i++ ) { value[i] = createConsumerId("NetworkConsumerPath:7"); } info.setNetworkConsumerPath(value); } } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConsumerInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ConsumerInfoTest extends BaseCommandTestSupport { public static ConsumerInfoTest SINGLETON = new ConsumerInfoTest(); public Object createObject() throws Exception { ConsumerInfo info = new ConsumerInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConsumerInfo info = (ConsumerInfo) object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setBrowser(true); info.setDestination(createActiveMQDestination("Destination:2")); info.setPrefetchSize(1); info.setMaximumPendingMessageLimit(2); info.setDispatchAsync(false); info.setSelector("Selector:3"); info.setSubscriptionName("SubscriptionName:4"); info.setNoLocal(true); info.setExclusive(false); info.setRetroactive(true); info.setPriority((byte) 1); { BrokerId value[] = new BrokerId[2]; for (int i = 0; i < 2; i++) { value[i] = createBrokerId("BrokerPath:5"); } info.setBrokerPath(value); } info.setAdditionalPredicate(createBooleanExpression("AdditionalPredicate:6")); info.setNetworkSubscription(false); info.setOptimizedAcknowledge(true); info.setNoRangeAcks(false); { ConsumerId value[] = new ConsumerId[2]; for (int i = 0; i < 2; i++) { value[i] = createConsumerId("NetworkConsumerPath:7"); } info.setNetworkConsumerPath(value); } } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ControlCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ControlCommandTest.java index ca402e634e..b20acfe356 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ControlCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ControlCommandTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ControlCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ControlCommandTest extends BaseCommandTestSupport { public static ControlCommandTest SINGLETON = new ControlCommandTest(); public Object createObject() throws Exception { ControlCommand info = new ControlCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ControlCommand info = (ControlCommand) object; info.setCommand("Command:1"); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ControlCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ControlCommandTest extends BaseCommandTestSupport { public static ControlCommandTest SINGLETON = new ControlCommandTest(); public Object createObject() throws Exception { ControlCommand info = new ControlCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ControlCommand info = (ControlCommand) object; info.setCommand("Command:1"); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/DataArrayResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/DataArrayResponseTest.java index 67e23c6a1e..78044f3283 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/DataArrayResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/DataArrayResponseTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for DataArrayResponse * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class DataArrayResponseTest extends ResponseTest { public static DataArrayResponseTest SINGLETON = new DataArrayResponseTest(); public Object createObject() throws Exception { DataArrayResponse info = new DataArrayResponse(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); DataArrayResponse info = (DataArrayResponse) object; { DataStructure value[] = new DataStructure[2]; for( int i=0; i < 2; i++ ) { value[i] = createDataStructure("Data:1"); } info.setData(value); } } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for DataArrayResponse * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class DataArrayResponseTest extends ResponseTest { public static DataArrayResponseTest SINGLETON = new DataArrayResponseTest(); public Object createObject() throws Exception { DataArrayResponse info = new DataArrayResponse(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); DataArrayResponse info = (DataArrayResponse) object; { DataStructure value[] = new DataStructure[2]; for (int i = 0; i < 2; i++) { value[i] = createDataStructure("Data:1"); } info.setData(value); } } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/DataResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/DataResponseTest.java index ef239cebc5..e9bd160a6a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/DataResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/DataResponseTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for DataResponse * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class DataResponseTest extends ResponseTest { public static DataResponseTest SINGLETON = new DataResponseTest(); public Object createObject() throws Exception { DataResponse info = new DataResponse(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); DataResponse info = (DataResponse) object; info.setData(createDataStructure("Data:1")); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for DataResponse * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class DataResponseTest extends ResponseTest { public static DataResponseTest SINGLETON = new DataResponseTest(); public Object createObject() throws Exception { DataResponse info = new DataResponse(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); DataResponse info = (DataResponse) object; info.setData(createDataStructure("Data:1")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/DestinationInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/DestinationInfoTest.java index 3d36583e0e..fb0eeba106 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/DestinationInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/DestinationInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for DestinationInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class DestinationInfoTest extends BaseCommandTestSupport { public static DestinationInfoTest SINGLETON = new DestinationInfoTest(); public Object createObject() throws Exception { DestinationInfo info = new DestinationInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); DestinationInfo info = (DestinationInfo) object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setOperationType((byte) 1); info.setTimeout(1); { BrokerId value[] = new BrokerId[2]; for( int i=0; i < 2; i++ ) { value[i] = createBrokerId("BrokerPath:3"); } info.setBrokerPath(value); } } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for DestinationInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class DestinationInfoTest extends BaseCommandTestSupport { public static DestinationInfoTest SINGLETON = new DestinationInfoTest(); public Object createObject() throws Exception { DestinationInfo info = new DestinationInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); DestinationInfo info = (DestinationInfo) object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setOperationType((byte) 1); info.setTimeout(1); { BrokerId value[] = new BrokerId[2]; for (int i = 0; i < 2; i++) { value[i] = createBrokerId("BrokerPath:3"); } info.setBrokerPath(value); } } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/DiscoveryEventTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/DiscoveryEventTest.java index 939ed8ca0c..bf0515d960 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/DiscoveryEventTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/DiscoveryEventTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for DiscoveryEvent * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class DiscoveryEventTest extends DataFileGeneratorTestSupport { public static DiscoveryEventTest SINGLETON = new DiscoveryEventTest(); public Object createObject() throws Exception { DiscoveryEvent info = new DiscoveryEvent(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); DiscoveryEvent info = (DiscoveryEvent) object; info.setServiceName("ServiceName:1"); info.setBrokerName("BrokerName:2"); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for DiscoveryEvent * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class DiscoveryEventTest extends DataFileGeneratorTestSupport { public static DiscoveryEventTest SINGLETON = new DiscoveryEventTest(); public Object createObject() throws Exception { DiscoveryEvent info = new DiscoveryEvent(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); DiscoveryEvent info = (DiscoveryEvent) object; info.setServiceName("ServiceName:1"); info.setBrokerName("BrokerName:2"); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ExceptionResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ExceptionResponseTest.java index d05f91867d..83965a5d43 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ExceptionResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ExceptionResponseTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ExceptionResponse * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ExceptionResponseTest extends ResponseTest { public static ExceptionResponseTest SINGLETON = new ExceptionResponseTest(); public Object createObject() throws Exception { ExceptionResponse info = new ExceptionResponse(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ExceptionResponse info = (ExceptionResponse) object; info.setException(createThrowable("Exception:1")); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ExceptionResponse * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ExceptionResponseTest extends ResponseTest { public static ExceptionResponseTest SINGLETON = new ExceptionResponseTest(); public Object createObject() throws Exception { ExceptionResponse info = new ExceptionResponse(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ExceptionResponse info = (ExceptionResponse) object; info.setException(createThrowable("Exception:1")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/FlushCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/FlushCommandTest.java index 21275c7ec8..590f76a6ac 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/FlushCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/FlushCommandTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for FlushCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class FlushCommandTest extends BaseCommandTestSupport { public static FlushCommandTest SINGLETON = new FlushCommandTest(); public Object createObject() throws Exception { FlushCommand info = new FlushCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); FlushCommand info = (FlushCommand) object; } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for FlushCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class FlushCommandTest extends BaseCommandTestSupport { public static FlushCommandTest SINGLETON = new FlushCommandTest(); public Object createObject() throws Exception { FlushCommand info = new FlushCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); FlushCommand info = (FlushCommand) object; } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/IntegerResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/IntegerResponseTest.java index 88c6e33f90..0e99cf6deb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/IntegerResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/IntegerResponseTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for IntegerResponse * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class IntegerResponseTest extends ResponseTest { public static IntegerResponseTest SINGLETON = new IntegerResponseTest(); public Object createObject() throws Exception { IntegerResponse info = new IntegerResponse(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); IntegerResponse info = (IntegerResponse) object; info.setResult(1); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for IntegerResponse * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class IntegerResponseTest extends ResponseTest { public static IntegerResponseTest SINGLETON = new IntegerResponseTest(); public Object createObject() throws Exception { IntegerResponse info = new IntegerResponse(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); IntegerResponse info = (IntegerResponse) object; info.setResult(1); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/JournalQueueAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/JournalQueueAckTest.java index f12c69cd55..412a028568 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/JournalQueueAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/JournalQueueAckTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for JournalQueueAck * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class JournalQueueAckTest extends DataFileGeneratorTestSupport { public static JournalQueueAckTest SINGLETON = new JournalQueueAckTest(); public Object createObject() throws Exception { JournalQueueAck info = new JournalQueueAck(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); JournalQueueAck info = (JournalQueueAck) object; info.setDestination(createActiveMQDestination("Destination:1")); info.setMessageAck(createMessageAck("MessageAck:2")); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for JournalQueueAck * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class JournalQueueAckTest extends DataFileGeneratorTestSupport { public static JournalQueueAckTest SINGLETON = new JournalQueueAckTest(); public Object createObject() throws Exception { JournalQueueAck info = new JournalQueueAck(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); JournalQueueAck info = (JournalQueueAck) object; info.setDestination(createActiveMQDestination("Destination:1")); info.setMessageAck(createMessageAck("MessageAck:2")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/JournalTopicAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/JournalTopicAckTest.java index fe48a8d314..e98135f87b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/JournalTopicAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/JournalTopicAckTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for JournalTopicAck * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class JournalTopicAckTest extends DataFileGeneratorTestSupport { public static JournalTopicAckTest SINGLETON = new JournalTopicAckTest(); public Object createObject() throws Exception { JournalTopicAck info = new JournalTopicAck(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); JournalTopicAck info = (JournalTopicAck) object; info.setDestination(createActiveMQDestination("Destination:1")); info.setMessageId(createMessageId("MessageId:2")); info.setMessageSequenceId(1); info.setSubscritionName("SubscritionName:3"); info.setClientId("ClientId:4"); info.setTransactionId(createTransactionId("TransactionId:5")); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for JournalTopicAck * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class JournalTopicAckTest extends DataFileGeneratorTestSupport { public static JournalTopicAckTest SINGLETON = new JournalTopicAckTest(); public Object createObject() throws Exception { JournalTopicAck info = new JournalTopicAck(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); JournalTopicAck info = (JournalTopicAck) object; info.setDestination(createActiveMQDestination("Destination:1")); info.setMessageId(createMessageId("MessageId:2")); info.setMessageSequenceId(1); info.setSubscritionName("SubscritionName:3"); info.setClientId("ClientId:4"); info.setTransactionId(createTransactionId("TransactionId:5")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/JournalTraceTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/JournalTraceTest.java index fce7d59d9a..88389fa63c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/JournalTraceTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/JournalTraceTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for JournalTrace * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class JournalTraceTest extends DataFileGeneratorTestSupport { public static JournalTraceTest SINGLETON = new JournalTraceTest(); public Object createObject() throws Exception { JournalTrace info = new JournalTrace(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); JournalTrace info = (JournalTrace) object; info.setMessage("Message:1"); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for JournalTrace * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class JournalTraceTest extends DataFileGeneratorTestSupport { public static JournalTraceTest SINGLETON = new JournalTraceTest(); public Object createObject() throws Exception { JournalTrace info = new JournalTrace(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); JournalTrace info = (JournalTrace) object; info.setMessage("Message:1"); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/JournalTransactionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/JournalTransactionTest.java index 8b9bd07c0c..691cc0b476 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/JournalTransactionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/JournalTransactionTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for JournalTransaction * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class JournalTransactionTest extends DataFileGeneratorTestSupport { public static JournalTransactionTest SINGLETON = new JournalTransactionTest(); public Object createObject() throws Exception { JournalTransaction info = new JournalTransaction(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); JournalTransaction info = (JournalTransaction) object; info.setTransactionId(createTransactionId("TransactionId:1")); info.setType((byte) 1); info.setWasPrepared(true); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for JournalTransaction * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class JournalTransactionTest extends DataFileGeneratorTestSupport { public static JournalTransactionTest SINGLETON = new JournalTransactionTest(); public Object createObject() throws Exception { JournalTransaction info = new JournalTransaction(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); JournalTransaction info = (JournalTransaction) object; info.setTransactionId(createTransactionId("TransactionId:1")); info.setType((byte) 1); info.setWasPrepared(true); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/KeepAliveInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/KeepAliveInfoTest.java index ba6a23afb2..c4c2760371 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/KeepAliveInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/KeepAliveInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for KeepAliveInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class KeepAliveInfoTest extends BaseCommandTestSupport { public static KeepAliveInfoTest SINGLETON = new KeepAliveInfoTest(); public Object createObject() throws Exception { KeepAliveInfo info = new KeepAliveInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); KeepAliveInfo info = (KeepAliveInfo) object; } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for KeepAliveInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class KeepAliveInfoTest extends BaseCommandTestSupport { public static KeepAliveInfoTest SINGLETON = new KeepAliveInfoTest(); public Object createObject() throws Exception { KeepAliveInfo info = new KeepAliveInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); KeepAliveInfo info = (KeepAliveInfo) object; } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/LastPartialCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/LastPartialCommandTest.java index 9e5922dca2..81363be0a5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/LastPartialCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/LastPartialCommandTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for LastPartialCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class LastPartialCommandTest extends PartialCommandTest { public static LastPartialCommandTest SINGLETON = new LastPartialCommandTest(); public Object createObject() throws Exception { LastPartialCommand info = new LastPartialCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); LastPartialCommand info = (LastPartialCommand) object; } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for LastPartialCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class LastPartialCommandTest extends PartialCommandTest { public static LastPartialCommandTest SINGLETON = new LastPartialCommandTest(); public Object createObject() throws Exception { LastPartialCommand info = new LastPartialCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); LastPartialCommand info = (LastPartialCommand) object; } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/LocalTransactionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/LocalTransactionIdTest.java index c70c948f1e..475401e8bf 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/LocalTransactionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/LocalTransactionIdTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for LocalTransactionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class LocalTransactionIdTest extends TransactionIdTestSupport { public static LocalTransactionIdTest SINGLETON = new LocalTransactionIdTest(); public Object createObject() throws Exception { LocalTransactionId info = new LocalTransactionId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); LocalTransactionId info = (LocalTransactionId) object; info.setValue(1); info.setConnectionId(createConnectionId("ConnectionId:1")); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for LocalTransactionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class LocalTransactionIdTest extends TransactionIdTestSupport { public static LocalTransactionIdTest SINGLETON = new LocalTransactionIdTest(); public Object createObject() throws Exception { LocalTransactionId info = new LocalTransactionId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); LocalTransactionId info = (LocalTransactionId) object; info.setValue(1); info.setConnectionId(createConnectionId("ConnectionId:1")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/MessageAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/MessageAckTest.java index 8a00f6e3f7..7211b8021f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/MessageAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/MessageAckTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessageAck * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class MessageAckTest extends BaseCommandTestSupport { public static MessageAckTest SINGLETON = new MessageAckTest(); public Object createObject() throws Exception { MessageAck info = new MessageAck(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessageAck info = (MessageAck) object; info.setDestination(createActiveMQDestination("Destination:1")); info.setTransactionId(createTransactionId("TransactionId:2")); info.setConsumerId(createConsumerId("ConsumerId:3")); info.setAckType((byte) 1); info.setFirstMessageId(createMessageId("FirstMessageId:4")); info.setLastMessageId(createMessageId("LastMessageId:5")); info.setMessageCount(1); info.setPoisonCause(createThrowable("PoisonCause:6")); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessageAck * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class MessageAckTest extends BaseCommandTestSupport { public static MessageAckTest SINGLETON = new MessageAckTest(); public Object createObject() throws Exception { MessageAck info = new MessageAck(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessageAck info = (MessageAck) object; info.setDestination(createActiveMQDestination("Destination:1")); info.setTransactionId(createTransactionId("TransactionId:2")); info.setConsumerId(createConsumerId("ConsumerId:3")); info.setAckType((byte) 1); info.setFirstMessageId(createMessageId("FirstMessageId:4")); info.setLastMessageId(createMessageId("LastMessageId:5")); info.setMessageCount(1); info.setPoisonCause(createThrowable("PoisonCause:6")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/MessageDispatchNotificationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/MessageDispatchNotificationTest.java index b661a2362a..ca5a604fa5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/MessageDispatchNotificationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/MessageDispatchNotificationTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessageDispatchNotification * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class MessageDispatchNotificationTest extends BaseCommandTestSupport { public static MessageDispatchNotificationTest SINGLETON = new MessageDispatchNotificationTest(); public Object createObject() throws Exception { MessageDispatchNotification info = new MessageDispatchNotification(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessageDispatchNotification info = (MessageDispatchNotification) object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setDeliverySequenceId(1); info.setMessageId(createMessageId("MessageId:3")); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessageDispatchNotification * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class MessageDispatchNotificationTest extends BaseCommandTestSupport { public static MessageDispatchNotificationTest SINGLETON = new MessageDispatchNotificationTest(); public Object createObject() throws Exception { MessageDispatchNotification info = new MessageDispatchNotification(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessageDispatchNotification info = (MessageDispatchNotification) object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setDeliverySequenceId(1); info.setMessageId(createMessageId("MessageId:3")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/MessageDispatchTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/MessageDispatchTest.java index 05a038494f..049d0fa1b6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/MessageDispatchTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/MessageDispatchTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessageDispatch * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class MessageDispatchTest extends BaseCommandTestSupport { public static MessageDispatchTest SINGLETON = new MessageDispatchTest(); public Object createObject() throws Exception { MessageDispatch info = new MessageDispatch(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessageDispatch info = (MessageDispatch) object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setMessage(createMessage("Message:3")); info.setRedeliveryCounter(1); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessageDispatch * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class MessageDispatchTest extends BaseCommandTestSupport { public static MessageDispatchTest SINGLETON = new MessageDispatchTest(); public Object createObject() throws Exception { MessageDispatch info = new MessageDispatch(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessageDispatch info = (MessageDispatch) object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setMessage(createMessage("Message:3")); info.setRedeliveryCounter(1); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/MessageIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/MessageIdTest.java index 484b0377e1..f9b57ff6d4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/MessageIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/MessageIdTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessageId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class MessageIdTest extends DataFileGeneratorTestSupport { public static MessageIdTest SINGLETON = new MessageIdTest(); public Object createObject() throws Exception { MessageId info = new MessageId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessageId info = (MessageId) object; info.setProducerId(createProducerId("ProducerId:1")); info.setProducerSequenceId(1); info.setBrokerSequenceId(2); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessageId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class MessageIdTest extends DataFileGeneratorTestSupport { public static MessageIdTest SINGLETON = new MessageIdTest(); public Object createObject() throws Exception { MessageId info = new MessageId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessageId info = (MessageId) object; info.setProducerId(createProducerId("ProducerId:1")); info.setProducerSequenceId(1); info.setBrokerSequenceId(2); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/MessagePullTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/MessagePullTest.java index 279c089836..6a1ccf8654 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/MessagePullTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/MessagePullTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessagePull * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class MessagePullTest extends BaseCommandTestSupport { public static MessagePullTest SINGLETON = new MessagePullTest(); public Object createObject() throws Exception { MessagePull info = new MessagePull(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessagePull info = (MessagePull) object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setTimeout(1); info.setCorrelationId("CorrelationId:3"); info.setMessageId(createMessageId("MessageId:4")); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessagePull * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class MessagePullTest extends BaseCommandTestSupport { public static MessagePullTest SINGLETON = new MessagePullTest(); public Object createObject() throws Exception { MessagePull info = new MessagePull(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessagePull info = (MessagePull) object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setTimeout(1); info.setCorrelationId("CorrelationId:3"); info.setMessageId(createMessageId("MessageId:4")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/MessageTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/MessageTestSupport.java index a5d4f3b52c..edce61d627 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/MessageTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/MessageTestSupport.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for Message * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public abstract class MessageTestSupport extends BaseCommandTestSupport { protected void populateObject(Object object) throws Exception { super.populateObject(object); Message info = (Message) object; info.setProducerId(createProducerId("ProducerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setTransactionId(createTransactionId("TransactionId:3")); info.setOriginalDestination(createActiveMQDestination("OriginalDestination:4")); info.setMessageId(createMessageId("MessageId:5")); info.setOriginalTransactionId(createTransactionId("OriginalTransactionId:6")); info.setGroupID("GroupID:7"); info.setGroupSequence(1); info.setCorrelationId("CorrelationId:8"); info.setPersistent(true); info.setExpiration(1); info.setPriority((byte) 1); info.setReplyTo(createActiveMQDestination("ReplyTo:9")); info.setTimestamp(2); info.setType("Type:10"); { byte data[] = "Content:11".getBytes(); info.setContent(new org.apache.activemq.util.ByteSequence(data,0,data.length)); } { byte data[] = "MarshalledProperties:12".getBytes(); info.setMarshalledProperties(new org.apache.activemq.util.ByteSequence(data,0,data.length)); } info.setDataStructure(createDataStructure("DataStructure:13")); info.setTargetConsumerId(createConsumerId("TargetConsumerId:14")); info.setCompressed(false); info.setRedeliveryCounter(2); { BrokerId value[] = new BrokerId[2]; for( int i=0; i < 2; i++ ) { value[i] = createBrokerId("BrokerPath:15"); } info.setBrokerPath(value); } info.setArrival(3); info.setUserID("UserID:16"); info.setRecievedByDFBridge(true); info.setDroppable(false); { BrokerId value[] = new BrokerId[2]; for( int i=0; i < 2; i++ ) { value[i] = createBrokerId("Cluster:17"); } info.setCluster(value); } info.setBrokerInTime(4); info.setBrokerOutTime(5); } } \ No newline at end of file +/** * * 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.openwire.v7; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for Message * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public abstract class MessageTestSupport extends BaseCommandTestSupport { protected void populateObject(Object object) throws Exception { super.populateObject(object); Message info = (Message) object; info.setProducerId(createProducerId("ProducerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setTransactionId(createTransactionId("TransactionId:3")); info.setOriginalDestination(createActiveMQDestination("OriginalDestination:4")); info.setMessageId(createMessageId("MessageId:5")); info.setOriginalTransactionId(createTransactionId("OriginalTransactionId:6")); info.setGroupID("GroupID:7"); info.setGroupSequence(1); info.setCorrelationId("CorrelationId:8"); info.setPersistent(true); info.setExpiration(1); info.setPriority((byte) 1); info.setReplyTo(createActiveMQDestination("ReplyTo:9")); info.setTimestamp(2); info.setType("Type:10"); { byte data[] = "Content:11".getBytes(); info.setContent(new org.apache.activemq.util.ByteSequence(data, 0, data.length)); } { byte data[] = "MarshalledProperties:12".getBytes(); info.setMarshalledProperties(new org.apache.activemq.util.ByteSequence(data, 0, data.length)); } info.setDataStructure(createDataStructure("DataStructure:13")); info.setTargetConsumerId(createConsumerId("TargetConsumerId:14")); info.setCompressed(false); info.setRedeliveryCounter(2); { BrokerId value[] = new BrokerId[2]; for (int i = 0; i < 2; i++) { value[i] = createBrokerId("BrokerPath:15"); } info.setBrokerPath(value); } info.setArrival(3); info.setUserID("UserID:16"); info.setRecievedByDFBridge(true); info.setDroppable(false); { BrokerId value[] = new BrokerId[2]; for (int i = 0; i < 2; i++) { value[i] = createBrokerId("Cluster:17"); } info.setCluster(value); } info.setBrokerInTime(4); info.setBrokerOutTime(5); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/NetworkBridgeFilterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/NetworkBridgeFilterTest.java index 3cb5e249c8..6bd0ed4974 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/NetworkBridgeFilterTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/NetworkBridgeFilterTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for NetworkBridgeFilter * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class NetworkBridgeFilterTest extends DataFileGeneratorTestSupport { public static NetworkBridgeFilterTest SINGLETON = new NetworkBridgeFilterTest(); public Object createObject() throws Exception { NetworkBridgeFilter info = new NetworkBridgeFilter(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); NetworkBridgeFilter info = (NetworkBridgeFilter) object; info.setNetworkTTL(1); info.setNetworkBrokerId(createBrokerId("NetworkBrokerId:1")); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for NetworkBridgeFilter * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class NetworkBridgeFilterTest extends DataFileGeneratorTestSupport { public static NetworkBridgeFilterTest SINGLETON = new NetworkBridgeFilterTest(); public Object createObject() throws Exception { NetworkBridgeFilter info = new NetworkBridgeFilter(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); NetworkBridgeFilter info = (NetworkBridgeFilter) object; info.setNetworkTTL(1); info.setNetworkBrokerId(createBrokerId("NetworkBrokerId:1")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/PartialCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/PartialCommandTest.java index dceac8370d..33915cfad0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/PartialCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/PartialCommandTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for PartialCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class PartialCommandTest extends DataFileGeneratorTestSupport { public static PartialCommandTest SINGLETON = new PartialCommandTest(); public Object createObject() throws Exception { PartialCommand info = new PartialCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); PartialCommand info = (PartialCommand) object; info.setCommandId(1); info.setData("Data:1".getBytes()); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for PartialCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class PartialCommandTest extends DataFileGeneratorTestSupport { public static PartialCommandTest SINGLETON = new PartialCommandTest(); public Object createObject() throws Exception { PartialCommand info = new PartialCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); PartialCommand info = (PartialCommand) object; info.setCommandId(1); info.setData("Data:1".getBytes()); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ProducerAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ProducerAckTest.java index 73104563e7..92c533b45c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ProducerAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ProducerAckTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ProducerAck * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ProducerAckTest extends BaseCommandTestSupport { public static ProducerAckTest SINGLETON = new ProducerAckTest(); public Object createObject() throws Exception { ProducerAck info = new ProducerAck(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ProducerAck info = (ProducerAck) object; info.setProducerId(createProducerId("ProducerId:1")); info.setSize(1); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ProducerAck * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ProducerAckTest extends BaseCommandTestSupport { public static ProducerAckTest SINGLETON = new ProducerAckTest(); public Object createObject() throws Exception { ProducerAck info = new ProducerAck(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ProducerAck info = (ProducerAck) object; info.setProducerId(createProducerId("ProducerId:1")); info.setSize(1); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ProducerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ProducerIdTest.java index 2a8c13ba18..aaffa7aa4e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ProducerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ProducerIdTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ProducerId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ProducerIdTest extends DataFileGeneratorTestSupport { public static ProducerIdTest SINGLETON = new ProducerIdTest(); public Object createObject() throws Exception { ProducerId info = new ProducerId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ProducerId info = (ProducerId) object; info.setConnectionId("ConnectionId:1"); info.setValue(1); info.setSessionId(2); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ProducerId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ProducerIdTest extends DataFileGeneratorTestSupport { public static ProducerIdTest SINGLETON = new ProducerIdTest(); public Object createObject() throws Exception { ProducerId info = new ProducerId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ProducerId info = (ProducerId) object; info.setConnectionId("ConnectionId:1"); info.setValue(1); info.setSessionId(2); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ProducerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ProducerInfoTest.java index 474a55eaa2..8f3854bbbd 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ProducerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ProducerInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ProducerInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ProducerInfoTest extends BaseCommandTestSupport { public static ProducerInfoTest SINGLETON = new ProducerInfoTest(); public Object createObject() throws Exception { ProducerInfo info = new ProducerInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ProducerInfo info = (ProducerInfo) object; info.setProducerId(createProducerId("ProducerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); { BrokerId value[] = new BrokerId[2]; for( int i=0; i < 2; i++ ) { value[i] = createBrokerId("BrokerPath:3"); } info.setBrokerPath(value); } info.setDispatchAsync(true); info.setWindowSize(1); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ProducerInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ProducerInfoTest extends BaseCommandTestSupport { public static ProducerInfoTest SINGLETON = new ProducerInfoTest(); public Object createObject() throws Exception { ProducerInfo info = new ProducerInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ProducerInfo info = (ProducerInfo) object; info.setProducerId(createProducerId("ProducerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); { BrokerId value[] = new BrokerId[2]; for (int i = 0; i < 2; i++) { value[i] = createBrokerId("BrokerPath:3"); } info.setBrokerPath(value); } info.setDispatchAsync(true); info.setWindowSize(1); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/RemoveInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/RemoveInfoTest.java index 01b2639acf..d1df3041b6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/RemoveInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/RemoveInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for RemoveInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class RemoveInfoTest extends BaseCommandTestSupport { public static RemoveInfoTest SINGLETON = new RemoveInfoTest(); public Object createObject() throws Exception { RemoveInfo info = new RemoveInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); RemoveInfo info = (RemoveInfo) object; info.setObjectId(createDataStructure("ObjectId:1")); info.setLastDeliveredSequenceId(1); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for RemoveInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class RemoveInfoTest extends BaseCommandTestSupport { public static RemoveInfoTest SINGLETON = new RemoveInfoTest(); public Object createObject() throws Exception { RemoveInfo info = new RemoveInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); RemoveInfo info = (RemoveInfo) object; info.setObjectId(createDataStructure("ObjectId:1")); info.setLastDeliveredSequenceId(1); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/RemoveSubscriptionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/RemoveSubscriptionInfoTest.java index 4159ee6e15..84067d6e7e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/RemoveSubscriptionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/RemoveSubscriptionInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for RemoveSubscriptionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class RemoveSubscriptionInfoTest extends BaseCommandTestSupport { public static RemoveSubscriptionInfoTest SINGLETON = new RemoveSubscriptionInfoTest(); public Object createObject() throws Exception { RemoveSubscriptionInfo info = new RemoveSubscriptionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); RemoveSubscriptionInfo info = (RemoveSubscriptionInfo) object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setSubcriptionName("SubcriptionName:2"); info.setClientId("ClientId:3"); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for RemoveSubscriptionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class RemoveSubscriptionInfoTest extends BaseCommandTestSupport { public static RemoveSubscriptionInfoTest SINGLETON = new RemoveSubscriptionInfoTest(); public Object createObject() throws Exception { RemoveSubscriptionInfo info = new RemoveSubscriptionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); RemoveSubscriptionInfo info = (RemoveSubscriptionInfo) object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setSubcriptionName("SubcriptionName:2"); info.setClientId("ClientId:3"); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ReplayCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ReplayCommandTest.java index 8a1e8e2af6..0bc0a40c88 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ReplayCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ReplayCommandTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ReplayCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ReplayCommandTest extends BaseCommandTestSupport { public static ReplayCommandTest SINGLETON = new ReplayCommandTest(); public Object createObject() throws Exception { ReplayCommand info = new ReplayCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ReplayCommand info = (ReplayCommand) object; info.setFirstNakNumber(1); info.setLastNakNumber(2); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ReplayCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ReplayCommandTest extends BaseCommandTestSupport { public static ReplayCommandTest SINGLETON = new ReplayCommandTest(); public Object createObject() throws Exception { ReplayCommand info = new ReplayCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ReplayCommand info = (ReplayCommand) object; info.setFirstNakNumber(1); info.setLastNakNumber(2); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ResponseTest.java index 1d64767b99..a592bf2cba 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ResponseTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for Response * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ResponseTest extends BaseCommandTestSupport { public static ResponseTest SINGLETON = new ResponseTest(); public Object createObject() throws Exception { Response info = new Response(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); Response info = (Response) object; info.setCorrelationId(1); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for Response * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ResponseTest extends BaseCommandTestSupport { public static ResponseTest SINGLETON = new ResponseTest(); public Object createObject() throws Exception { Response info = new Response(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); Response info = (Response) object; info.setCorrelationId(1); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/SessionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/SessionIdTest.java index d12c96478d..76ffec0848 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/SessionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/SessionIdTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for SessionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class SessionIdTest extends DataFileGeneratorTestSupport { public static SessionIdTest SINGLETON = new SessionIdTest(); public Object createObject() throws Exception { SessionId info = new SessionId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); SessionId info = (SessionId) object; info.setConnectionId("ConnectionId:1"); info.setValue(1); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for SessionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class SessionIdTest extends DataFileGeneratorTestSupport { public static SessionIdTest SINGLETON = new SessionIdTest(); public Object createObject() throws Exception { SessionId info = new SessionId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); SessionId info = (SessionId) object; info.setConnectionId("ConnectionId:1"); info.setValue(1); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/SessionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/SessionInfoTest.java index cee5c070bd..d803c0442c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/SessionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/SessionInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for SessionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class SessionInfoTest extends BaseCommandTestSupport { public static SessionInfoTest SINGLETON = new SessionInfoTest(); public Object createObject() throws Exception { SessionInfo info = new SessionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); SessionInfo info = (SessionInfo) object; info.setSessionId(createSessionId("SessionId:1")); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for SessionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class SessionInfoTest extends BaseCommandTestSupport { public static SessionInfoTest SINGLETON = new SessionInfoTest(); public Object createObject() throws Exception { SessionInfo info = new SessionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); SessionInfo info = (SessionInfo) object; info.setSessionId(createSessionId("SessionId:1")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ShutdownInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ShutdownInfoTest.java index 66dda57be4..02478a4738 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ShutdownInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/ShutdownInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ShutdownInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ShutdownInfoTest extends BaseCommandTestSupport { public static ShutdownInfoTest SINGLETON = new ShutdownInfoTest(); public Object createObject() throws Exception { ShutdownInfo info = new ShutdownInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ShutdownInfo info = (ShutdownInfo) object; } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ShutdownInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ShutdownInfoTest extends BaseCommandTestSupport { public static ShutdownInfoTest SINGLETON = new ShutdownInfoTest(); public Object createObject() throws Exception { ShutdownInfo info = new ShutdownInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ShutdownInfo info = (ShutdownInfo) object; } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/SubscriptionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/SubscriptionInfoTest.java index 0a9e9344e5..a025cf96d6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/SubscriptionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/SubscriptionInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for SubscriptionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class SubscriptionInfoTest extends DataFileGeneratorTestSupport { public static SubscriptionInfoTest SINGLETON = new SubscriptionInfoTest(); public Object createObject() throws Exception { SubscriptionInfo info = new SubscriptionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); SubscriptionInfo info = (SubscriptionInfo) object; info.setClientId("ClientId:1"); info.setDestination(createActiveMQDestination("Destination:2")); info.setSelector("Selector:3"); info.setSubcriptionName("SubcriptionName:4"); info.setSubscribedDestination(createActiveMQDestination("SubscribedDestination:5")); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for SubscriptionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class SubscriptionInfoTest extends DataFileGeneratorTestSupport { public static SubscriptionInfoTest SINGLETON = new SubscriptionInfoTest(); public Object createObject() throws Exception { SubscriptionInfo info = new SubscriptionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); SubscriptionInfo info = (SubscriptionInfo) object; info.setClientId("ClientId:1"); info.setDestination(createActiveMQDestination("Destination:2")); info.setSelector("Selector:3"); info.setSubcriptionName("SubcriptionName:4"); info.setSubscribedDestination(createActiveMQDestination("SubscribedDestination:5")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/TransactionIdTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/TransactionIdTestSupport.java index 9706f12e27..be6d188953 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/TransactionIdTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/TransactionIdTestSupport.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for TransactionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public abstract class TransactionIdTestSupport extends DataFileGeneratorTestSupport { protected void populateObject(Object object) throws Exception { super.populateObject(object); TransactionId info = (TransactionId) object; } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for TransactionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public abstract class TransactionIdTestSupport extends DataFileGeneratorTestSupport { protected void populateObject(Object object) throws Exception { super.populateObject(object); TransactionId info = (TransactionId) object; } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/TransactionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/TransactionInfoTest.java index 3132a2b15e..0ee6687551 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/TransactionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/TransactionInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for TransactionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class TransactionInfoTest extends BaseCommandTestSupport { public static TransactionInfoTest SINGLETON = new TransactionInfoTest(); public Object createObject() throws Exception { TransactionInfo info = new TransactionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); TransactionInfo info = (TransactionInfo) object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setTransactionId(createTransactionId("TransactionId:2")); info.setType((byte) 1); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for TransactionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class TransactionInfoTest extends BaseCommandTestSupport { public static TransactionInfoTest SINGLETON = new TransactionInfoTest(); public Object createObject() throws Exception { TransactionInfo info = new TransactionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); TransactionInfo info = (TransactionInfo) object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setTransactionId(createTransactionId("TransactionId:2")); info.setType((byte) 1); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/XATransactionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/XATransactionIdTest.java index 79db31688b..977e13d424 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/XATransactionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v7/XATransactionIdTest.java @@ -1 +1 @@ -/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for XATransactionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class XATransactionIdTest extends TransactionIdTestSupport { public static XATransactionIdTest SINGLETON = new XATransactionIdTest(); public Object createObject() throws Exception { XATransactionId info = new XATransactionId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); XATransactionId info = (XATransactionId) object; info.setFormatId(1); info.setGlobalTransactionId("GlobalTransactionId:1".getBytes()); info.setBranchQualifier("BranchQualifier:2".getBytes()); } } \ No newline at end of file +/** * * 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.openwire.v7; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for XATransactionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class XATransactionIdTest extends TransactionIdTestSupport { public static XATransactionIdTest SINGLETON = new XATransactionIdTest(); public Object createObject() throws Exception { XATransactionId info = new XATransactionId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); XATransactionId info = (XATransactionId) object; info.setFormatId(1); info.setGlobalTransactionId("GlobalTransactionId:1".getBytes()); info.setBranchQualifier("BranchQualifier:2".getBytes()); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/BaseCommandTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/BaseCommandTestSupport.java index 478d93d618..9c9f5d9f59 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/BaseCommandTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/BaseCommandTestSupport.java @@ -24,15 +24,14 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; * auto generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * */ public abstract class BaseCommandTestSupport extends DataFileGeneratorTestSupport { - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - BaseCommand info = (BaseCommand)object; - info.setCommandId(1); - info.setResponseRequired(true); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + BaseCommand info = (BaseCommand) object; + info.setCommandId(1); + info.setResponseRequired(true); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/BrokerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/BrokerIdTest.java index afa21c97b9..27da9c656e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/BrokerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/BrokerIdTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for BrokerId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class BrokerIdTest extends DataFileGeneratorTestSupport { public static BrokerIdTest SINGLETON = new BrokerIdTest(); public Object createObject() throws Exception { BrokerId info = new BrokerId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); BrokerId info = (BrokerId) object; info.setValue("Value:1"); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for BrokerId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class BrokerIdTest extends DataFileGeneratorTestSupport { public static BrokerIdTest SINGLETON = new BrokerIdTest(); public Object createObject() throws Exception { BrokerId info = new BrokerId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); BrokerId info = (BrokerId) object; info.setValue("Value:1"); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/BrokerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/BrokerInfoTest.java index acdd9fafe5..962f2fb48b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/BrokerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/BrokerInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for BrokerInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class BrokerInfoTest extends BaseCommandTestSupport { public static BrokerInfoTest SINGLETON = new BrokerInfoTest(); public Object createObject() throws Exception { BrokerInfo info = new BrokerInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); BrokerInfo info = (BrokerInfo) object; info.setBrokerId(createBrokerId("BrokerId:1")); info.setBrokerURL("BrokerURL:2"); { BrokerInfo value[] = new BrokerInfo[0]; for( int i=0; i < 0; i++ ) { value[i] = createBrokerInfo("PeerBrokerInfos:3"); } info.setPeerBrokerInfos(value); } info.setBrokerName("BrokerName:4"); info.setSlaveBroker(true); info.setMasterBroker(false); info.setFaultTolerantConfiguration(true); info.setDuplexConnection(false); info.setNetworkConnection(true); info.setConnectionId(1); info.setBrokerUploadUrl("BrokerUploadUrl:5"); info.setNetworkProperties("NetworkProperties:6"); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for BrokerInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class BrokerInfoTest extends BaseCommandTestSupport { public static BrokerInfoTest SINGLETON = new BrokerInfoTest(); public Object createObject() throws Exception { BrokerInfo info = new BrokerInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); BrokerInfo info = (BrokerInfo) object; info.setBrokerId(createBrokerId("BrokerId:1")); info.setBrokerURL("BrokerURL:2"); { BrokerInfo value[] = new BrokerInfo[0]; for (int i = 0; i < 0; i++) { value[i] = createBrokerInfo("PeerBrokerInfos:3"); } info.setPeerBrokerInfos(value); } info.setBrokerName("BrokerName:4"); info.setSlaveBroker(true); info.setMasterBroker(false); info.setFaultTolerantConfiguration(true); info.setDuplexConnection(false); info.setNetworkConnection(true); info.setConnectionId(1); info.setBrokerUploadUrl("BrokerUploadUrl:5"); info.setNetworkProperties("NetworkProperties:6"); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConnectionControlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConnectionControlTest.java index 64ef24ddc8..5800995394 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConnectionControlTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConnectionControlTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConnectionControl * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ConnectionControlTest extends BaseCommandTestSupport { public static ConnectionControlTest SINGLETON = new ConnectionControlTest(); public Object createObject() throws Exception { ConnectionControl info = new ConnectionControl(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConnectionControl info = (ConnectionControl) object; info.setClose(true); info.setExit(false); info.setFaultTolerant(true); info.setResume(false); info.setSuspend(true); info.setConnectedBrokers("ConnectedBrokers:1"); info.setReconnectTo("ReconnectTo:2"); info.setRebalanceConnection(false); info.setToken("Token:3".getBytes()); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConnectionControl * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ConnectionControlTest extends BaseCommandTestSupport { public static ConnectionControlTest SINGLETON = new ConnectionControlTest(); public Object createObject() throws Exception { ConnectionControl info = new ConnectionControl(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConnectionControl info = (ConnectionControl) object; info.setClose(true); info.setExit(false); info.setFaultTolerant(true); info.setResume(false); info.setSuspend(true); info.setConnectedBrokers("ConnectedBrokers:1"); info.setReconnectTo("ReconnectTo:2"); info.setRebalanceConnection(false); info.setToken("Token:3".getBytes()); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConnectionErrorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConnectionErrorTest.java index 857746c202..4c12286cbf 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConnectionErrorTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConnectionErrorTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConnectionError * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ConnectionErrorTest extends BaseCommandTestSupport { public static ConnectionErrorTest SINGLETON = new ConnectionErrorTest(); public Object createObject() throws Exception { ConnectionError info = new ConnectionError(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConnectionError info = (ConnectionError) object; info.setException(createThrowable("Exception:1")); info.setConnectionId(createConnectionId("ConnectionId:2")); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConnectionError * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ConnectionErrorTest extends BaseCommandTestSupport { public static ConnectionErrorTest SINGLETON = new ConnectionErrorTest(); public Object createObject() throws Exception { ConnectionError info = new ConnectionError(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConnectionError info = (ConnectionError) object; info.setException(createThrowable("Exception:1")); info.setConnectionId(createConnectionId("ConnectionId:2")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConnectionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConnectionIdTest.java index 6c45427cc0..b2ae1977ac 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConnectionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConnectionIdTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConnectionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ConnectionIdTest extends DataFileGeneratorTestSupport { public static ConnectionIdTest SINGLETON = new ConnectionIdTest(); public Object createObject() throws Exception { ConnectionId info = new ConnectionId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConnectionId info = (ConnectionId) object; info.setValue("Value:1"); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConnectionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ConnectionIdTest extends DataFileGeneratorTestSupport { public static ConnectionIdTest SINGLETON = new ConnectionIdTest(); public Object createObject() throws Exception { ConnectionId info = new ConnectionId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConnectionId info = (ConnectionId) object; info.setValue("Value:1"); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConnectionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConnectionInfoTest.java index b10259ebde..c0166e9d65 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConnectionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConnectionInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConnectionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ConnectionInfoTest extends BaseCommandTestSupport { public static ConnectionInfoTest SINGLETON = new ConnectionInfoTest(); public Object createObject() throws Exception { ConnectionInfo info = new ConnectionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConnectionInfo info = (ConnectionInfo) object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setClientId("ClientId:2"); info.setPassword("Password:3"); info.setUserName("UserName:4"); { BrokerId value[] = new BrokerId[2]; for( int i=0; i < 2; i++ ) { value[i] = createBrokerId("BrokerPath:5"); } info.setBrokerPath(value); } info.setBrokerMasterConnector(true); info.setManageable(false); info.setClientMaster(true); info.setFaultTolerant(false); info.setFailoverReconnect(true); info.setClientIp("ClientIp:6"); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConnectionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ConnectionInfoTest extends BaseCommandTestSupport { public static ConnectionInfoTest SINGLETON = new ConnectionInfoTest(); public Object createObject() throws Exception { ConnectionInfo info = new ConnectionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConnectionInfo info = (ConnectionInfo) object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setClientId("ClientId:2"); info.setPassword("Password:3"); info.setUserName("UserName:4"); { BrokerId value[] = new BrokerId[2]; for (int i = 0; i < 2; i++) { value[i] = createBrokerId("BrokerPath:5"); } info.setBrokerPath(value); } info.setBrokerMasterConnector(true); info.setManageable(false); info.setClientMaster(true); info.setFaultTolerant(false); info.setFailoverReconnect(true); info.setClientIp("ClientIp:6"); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConsumerControlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConsumerControlTest.java index 7d0917ef91..19cb7f7b92 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConsumerControlTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConsumerControlTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConsumerControl * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ConsumerControlTest extends BaseCommandTestSupport { public static ConsumerControlTest SINGLETON = new ConsumerControlTest(); public Object createObject() throws Exception { ConsumerControl info = new ConsumerControl(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConsumerControl info = (ConsumerControl) object; info.setDestination(createActiveMQDestination("Destination:1")); info.setClose(true); info.setConsumerId(createConsumerId("ConsumerId:2")); info.setPrefetch(1); info.setFlush(false); info.setStart(true); info.setStop(false); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConsumerControl * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ConsumerControlTest extends BaseCommandTestSupport { public static ConsumerControlTest SINGLETON = new ConsumerControlTest(); public Object createObject() throws Exception { ConsumerControl info = new ConsumerControl(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConsumerControl info = (ConsumerControl) object; info.setDestination(createActiveMQDestination("Destination:1")); info.setClose(true); info.setConsumerId(createConsumerId("ConsumerId:2")); info.setPrefetch(1); info.setFlush(false); info.setStart(true); info.setStop(false); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConsumerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConsumerIdTest.java index 6e5b66dd21..b0240021ac 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConsumerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConsumerIdTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConsumerId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ConsumerIdTest extends DataFileGeneratorTestSupport { public static ConsumerIdTest SINGLETON = new ConsumerIdTest(); public Object createObject() throws Exception { ConsumerId info = new ConsumerId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConsumerId info = (ConsumerId) object; info.setConnectionId("ConnectionId:1"); info.setSessionId(1); info.setValue(2); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConsumerId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ConsumerIdTest extends DataFileGeneratorTestSupport { public static ConsumerIdTest SINGLETON = new ConsumerIdTest(); public Object createObject() throws Exception { ConsumerId info = new ConsumerId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConsumerId info = (ConsumerId) object; info.setConnectionId("ConnectionId:1"); info.setSessionId(1); info.setValue(2); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConsumerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConsumerInfoTest.java index a1e8695ba3..331da0a78d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConsumerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ConsumerInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConsumerInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ConsumerInfoTest extends BaseCommandTestSupport { public static ConsumerInfoTest SINGLETON = new ConsumerInfoTest(); public Object createObject() throws Exception { ConsumerInfo info = new ConsumerInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConsumerInfo info = (ConsumerInfo) object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setBrowser(true); info.setDestination(createActiveMQDestination("Destination:2")); info.setPrefetchSize(1); info.setMaximumPendingMessageLimit(2); info.setDispatchAsync(false); info.setSelector("Selector:3"); info.setSubscriptionName("SubscriptionName:4"); info.setNoLocal(true); info.setExclusive(false); info.setRetroactive(true); info.setPriority((byte) 1); { BrokerId value[] = new BrokerId[2]; for( int i=0; i < 2; i++ ) { value[i] = createBrokerId("BrokerPath:5"); } info.setBrokerPath(value); } info.setAdditionalPredicate(createBooleanExpression("AdditionalPredicate:6")); info.setNetworkSubscription(false); info.setOptimizedAcknowledge(true); info.setNoRangeAcks(false); { ConsumerId value[] = new ConsumerId[2]; for( int i=0; i < 2; i++ ) { value[i] = createConsumerId("NetworkConsumerPath:7"); } info.setNetworkConsumerPath(value); } } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConsumerInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ConsumerInfoTest extends BaseCommandTestSupport { public static ConsumerInfoTest SINGLETON = new ConsumerInfoTest(); public Object createObject() throws Exception { ConsumerInfo info = new ConsumerInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConsumerInfo info = (ConsumerInfo) object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setBrowser(true); info.setDestination(createActiveMQDestination("Destination:2")); info.setPrefetchSize(1); info.setMaximumPendingMessageLimit(2); info.setDispatchAsync(false); info.setSelector("Selector:3"); info.setSubscriptionName("SubscriptionName:4"); info.setNoLocal(true); info.setExclusive(false); info.setRetroactive(true); info.setPriority((byte) 1); { BrokerId value[] = new BrokerId[2]; for (int i = 0; i < 2; i++) { value[i] = createBrokerId("BrokerPath:5"); } info.setBrokerPath(value); } info.setAdditionalPredicate(createBooleanExpression("AdditionalPredicate:6")); info.setNetworkSubscription(false); info.setOptimizedAcknowledge(true); info.setNoRangeAcks(false); { ConsumerId value[] = new ConsumerId[2]; for (int i = 0; i < 2; i++) { value[i] = createConsumerId("NetworkConsumerPath:7"); } info.setNetworkConsumerPath(value); } } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ControlCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ControlCommandTest.java index be712161fe..436e233c6d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ControlCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ControlCommandTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ControlCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ControlCommandTest extends BaseCommandTestSupport { public static ControlCommandTest SINGLETON = new ControlCommandTest(); public Object createObject() throws Exception { ControlCommand info = new ControlCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ControlCommand info = (ControlCommand) object; info.setCommand("Command:1"); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ControlCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ControlCommandTest extends BaseCommandTestSupport { public static ControlCommandTest SINGLETON = new ControlCommandTest(); public Object createObject() throws Exception { ControlCommand info = new ControlCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ControlCommand info = (ControlCommand) object; info.setCommand("Command:1"); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/DataArrayResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/DataArrayResponseTest.java index b2a0d15370..e180b6308a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/DataArrayResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/DataArrayResponseTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for DataArrayResponse * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class DataArrayResponseTest extends ResponseTest { public static DataArrayResponseTest SINGLETON = new DataArrayResponseTest(); public Object createObject() throws Exception { DataArrayResponse info = new DataArrayResponse(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); DataArrayResponse info = (DataArrayResponse) object; { DataStructure value[] = new DataStructure[2]; for( int i=0; i < 2; i++ ) { value[i] = createDataStructure("Data:1"); } info.setData(value); } } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for DataArrayResponse * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class DataArrayResponseTest extends ResponseTest { public static DataArrayResponseTest SINGLETON = new DataArrayResponseTest(); public Object createObject() throws Exception { DataArrayResponse info = new DataArrayResponse(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); DataArrayResponse info = (DataArrayResponse) object; { DataStructure value[] = new DataStructure[2]; for (int i = 0; i < 2; i++) { value[i] = createDataStructure("Data:1"); } info.setData(value); } } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/DataResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/DataResponseTest.java index 2806a893a0..802f74a2fd 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/DataResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/DataResponseTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for DataResponse * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class DataResponseTest extends ResponseTest { public static DataResponseTest SINGLETON = new DataResponseTest(); public Object createObject() throws Exception { DataResponse info = new DataResponse(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); DataResponse info = (DataResponse) object; info.setData(createDataStructure("Data:1")); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for DataResponse * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class DataResponseTest extends ResponseTest { public static DataResponseTest SINGLETON = new DataResponseTest(); public Object createObject() throws Exception { DataResponse info = new DataResponse(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); DataResponse info = (DataResponse) object; info.setData(createDataStructure("Data:1")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/DestinationInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/DestinationInfoTest.java index 5c94e91feb..6bd16c6f8a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/DestinationInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/DestinationInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for DestinationInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class DestinationInfoTest extends BaseCommandTestSupport { public static DestinationInfoTest SINGLETON = new DestinationInfoTest(); public Object createObject() throws Exception { DestinationInfo info = new DestinationInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); DestinationInfo info = (DestinationInfo) object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setOperationType((byte) 1); info.setTimeout(1); { BrokerId value[] = new BrokerId[2]; for( int i=0; i < 2; i++ ) { value[i] = createBrokerId("BrokerPath:3"); } info.setBrokerPath(value); } } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for DestinationInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class DestinationInfoTest extends BaseCommandTestSupport { public static DestinationInfoTest SINGLETON = new DestinationInfoTest(); public Object createObject() throws Exception { DestinationInfo info = new DestinationInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); DestinationInfo info = (DestinationInfo) object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setOperationType((byte) 1); info.setTimeout(1); { BrokerId value[] = new BrokerId[2]; for (int i = 0; i < 2; i++) { value[i] = createBrokerId("BrokerPath:3"); } info.setBrokerPath(value); } } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/DiscoveryEventTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/DiscoveryEventTest.java index 3264cd4b51..9c6a1c88c4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/DiscoveryEventTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/DiscoveryEventTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for DiscoveryEvent * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class DiscoveryEventTest extends DataFileGeneratorTestSupport { public static DiscoveryEventTest SINGLETON = new DiscoveryEventTest(); public Object createObject() throws Exception { DiscoveryEvent info = new DiscoveryEvent(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); DiscoveryEvent info = (DiscoveryEvent) object; info.setServiceName("ServiceName:1"); info.setBrokerName("BrokerName:2"); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for DiscoveryEvent * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class DiscoveryEventTest extends DataFileGeneratorTestSupport { public static DiscoveryEventTest SINGLETON = new DiscoveryEventTest(); public Object createObject() throws Exception { DiscoveryEvent info = new DiscoveryEvent(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); DiscoveryEvent info = (DiscoveryEvent) object; info.setServiceName("ServiceName:1"); info.setBrokerName("BrokerName:2"); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ExceptionResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ExceptionResponseTest.java index bb082a90a2..6e82d556a4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ExceptionResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ExceptionResponseTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ExceptionResponse * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ExceptionResponseTest extends ResponseTest { public static ExceptionResponseTest SINGLETON = new ExceptionResponseTest(); public Object createObject() throws Exception { ExceptionResponse info = new ExceptionResponse(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ExceptionResponse info = (ExceptionResponse) object; info.setException(createThrowable("Exception:1")); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ExceptionResponse * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ExceptionResponseTest extends ResponseTest { public static ExceptionResponseTest SINGLETON = new ExceptionResponseTest(); public Object createObject() throws Exception { ExceptionResponse info = new ExceptionResponse(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ExceptionResponse info = (ExceptionResponse) object; info.setException(createThrowable("Exception:1")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/FlushCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/FlushCommandTest.java index e84280bc1d..ff2ce6faa5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/FlushCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/FlushCommandTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for FlushCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class FlushCommandTest extends BaseCommandTestSupport { public static FlushCommandTest SINGLETON = new FlushCommandTest(); public Object createObject() throws Exception { FlushCommand info = new FlushCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); FlushCommand info = (FlushCommand) object; } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for FlushCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class FlushCommandTest extends BaseCommandTestSupport { public static FlushCommandTest SINGLETON = new FlushCommandTest(); public Object createObject() throws Exception { FlushCommand info = new FlushCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); FlushCommand info = (FlushCommand) object; } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/IntegerResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/IntegerResponseTest.java index 5b4c12a704..2e8ff61543 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/IntegerResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/IntegerResponseTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for IntegerResponse * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class IntegerResponseTest extends ResponseTest { public static IntegerResponseTest SINGLETON = new IntegerResponseTest(); public Object createObject() throws Exception { IntegerResponse info = new IntegerResponse(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); IntegerResponse info = (IntegerResponse) object; info.setResult(1); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for IntegerResponse * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class IntegerResponseTest extends ResponseTest { public static IntegerResponseTest SINGLETON = new IntegerResponseTest(); public Object createObject() throws Exception { IntegerResponse info = new IntegerResponse(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); IntegerResponse info = (IntegerResponse) object; info.setResult(1); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/JournalQueueAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/JournalQueueAckTest.java index 5b69667005..51d4cbf716 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/JournalQueueAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/JournalQueueAckTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for JournalQueueAck * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class JournalQueueAckTest extends DataFileGeneratorTestSupport { public static JournalQueueAckTest SINGLETON = new JournalQueueAckTest(); public Object createObject() throws Exception { JournalQueueAck info = new JournalQueueAck(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); JournalQueueAck info = (JournalQueueAck) object; info.setDestination(createActiveMQDestination("Destination:1")); info.setMessageAck(createMessageAck("MessageAck:2")); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for JournalQueueAck * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class JournalQueueAckTest extends DataFileGeneratorTestSupport { public static JournalQueueAckTest SINGLETON = new JournalQueueAckTest(); public Object createObject() throws Exception { JournalQueueAck info = new JournalQueueAck(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); JournalQueueAck info = (JournalQueueAck) object; info.setDestination(createActiveMQDestination("Destination:1")); info.setMessageAck(createMessageAck("MessageAck:2")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/JournalTopicAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/JournalTopicAckTest.java index 120686970b..fa8e6805f6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/JournalTopicAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/JournalTopicAckTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for JournalTopicAck * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class JournalTopicAckTest extends DataFileGeneratorTestSupport { public static JournalTopicAckTest SINGLETON = new JournalTopicAckTest(); public Object createObject() throws Exception { JournalTopicAck info = new JournalTopicAck(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); JournalTopicAck info = (JournalTopicAck) object; info.setDestination(createActiveMQDestination("Destination:1")); info.setMessageId(createMessageId("MessageId:2")); info.setMessageSequenceId(1); info.setSubscritionName("SubscritionName:3"); info.setClientId("ClientId:4"); info.setTransactionId(createTransactionId("TransactionId:5")); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for JournalTopicAck * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class JournalTopicAckTest extends DataFileGeneratorTestSupport { public static JournalTopicAckTest SINGLETON = new JournalTopicAckTest(); public Object createObject() throws Exception { JournalTopicAck info = new JournalTopicAck(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); JournalTopicAck info = (JournalTopicAck) object; info.setDestination(createActiveMQDestination("Destination:1")); info.setMessageId(createMessageId("MessageId:2")); info.setMessageSequenceId(1); info.setSubscritionName("SubscritionName:3"); info.setClientId("ClientId:4"); info.setTransactionId(createTransactionId("TransactionId:5")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/JournalTraceTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/JournalTraceTest.java index 9172fcc561..3f1edb0761 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/JournalTraceTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/JournalTraceTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for JournalTrace * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class JournalTraceTest extends DataFileGeneratorTestSupport { public static JournalTraceTest SINGLETON = new JournalTraceTest(); public Object createObject() throws Exception { JournalTrace info = new JournalTrace(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); JournalTrace info = (JournalTrace) object; info.setMessage("Message:1"); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for JournalTrace * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class JournalTraceTest extends DataFileGeneratorTestSupport { public static JournalTraceTest SINGLETON = new JournalTraceTest(); public Object createObject() throws Exception { JournalTrace info = new JournalTrace(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); JournalTrace info = (JournalTrace) object; info.setMessage("Message:1"); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/JournalTransactionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/JournalTransactionTest.java index 1216bed8d2..6c19c3ac07 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/JournalTransactionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/JournalTransactionTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for JournalTransaction * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class JournalTransactionTest extends DataFileGeneratorTestSupport { public static JournalTransactionTest SINGLETON = new JournalTransactionTest(); public Object createObject() throws Exception { JournalTransaction info = new JournalTransaction(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); JournalTransaction info = (JournalTransaction) object; info.setTransactionId(createTransactionId("TransactionId:1")); info.setType((byte) 1); info.setWasPrepared(true); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for JournalTransaction * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class JournalTransactionTest extends DataFileGeneratorTestSupport { public static JournalTransactionTest SINGLETON = new JournalTransactionTest(); public Object createObject() throws Exception { JournalTransaction info = new JournalTransaction(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); JournalTransaction info = (JournalTransaction) object; info.setTransactionId(createTransactionId("TransactionId:1")); info.setType((byte) 1); info.setWasPrepared(true); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/KeepAliveInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/KeepAliveInfoTest.java index 9d39ae3ab8..95237c892d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/KeepAliveInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/KeepAliveInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for KeepAliveInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class KeepAliveInfoTest extends BaseCommandTestSupport { public static KeepAliveInfoTest SINGLETON = new KeepAliveInfoTest(); public Object createObject() throws Exception { KeepAliveInfo info = new KeepAliveInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); KeepAliveInfo info = (KeepAliveInfo) object; } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for KeepAliveInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class KeepAliveInfoTest extends BaseCommandTestSupport { public static KeepAliveInfoTest SINGLETON = new KeepAliveInfoTest(); public Object createObject() throws Exception { KeepAliveInfo info = new KeepAliveInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); KeepAliveInfo info = (KeepAliveInfo) object; } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/LastPartialCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/LastPartialCommandTest.java index 1c36b25aff..28de402e8f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/LastPartialCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/LastPartialCommandTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for LastPartialCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class LastPartialCommandTest extends PartialCommandTest { public static LastPartialCommandTest SINGLETON = new LastPartialCommandTest(); public Object createObject() throws Exception { LastPartialCommand info = new LastPartialCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); LastPartialCommand info = (LastPartialCommand) object; } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for LastPartialCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class LastPartialCommandTest extends PartialCommandTest { public static LastPartialCommandTest SINGLETON = new LastPartialCommandTest(); public Object createObject() throws Exception { LastPartialCommand info = new LastPartialCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); LastPartialCommand info = (LastPartialCommand) object; } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/LocalTransactionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/LocalTransactionIdTest.java index b2b1c8148d..21ab9c6819 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/LocalTransactionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/LocalTransactionIdTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for LocalTransactionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class LocalTransactionIdTest extends TransactionIdTestSupport { public static LocalTransactionIdTest SINGLETON = new LocalTransactionIdTest(); public Object createObject() throws Exception { LocalTransactionId info = new LocalTransactionId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); LocalTransactionId info = (LocalTransactionId) object; info.setValue(1); info.setConnectionId(createConnectionId("ConnectionId:1")); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for LocalTransactionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class LocalTransactionIdTest extends TransactionIdTestSupport { public static LocalTransactionIdTest SINGLETON = new LocalTransactionIdTest(); public Object createObject() throws Exception { LocalTransactionId info = new LocalTransactionId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); LocalTransactionId info = (LocalTransactionId) object; info.setValue(1); info.setConnectionId(createConnectionId("ConnectionId:1")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/MessageAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/MessageAckTest.java index ba6efc1fc4..8f109c721f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/MessageAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/MessageAckTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessageAck * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class MessageAckTest extends BaseCommandTestSupport { public static MessageAckTest SINGLETON = new MessageAckTest(); public Object createObject() throws Exception { MessageAck info = new MessageAck(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessageAck info = (MessageAck) object; info.setDestination(createActiveMQDestination("Destination:1")); info.setTransactionId(createTransactionId("TransactionId:2")); info.setConsumerId(createConsumerId("ConsumerId:3")); info.setAckType((byte) 1); info.setFirstMessageId(createMessageId("FirstMessageId:4")); info.setLastMessageId(createMessageId("LastMessageId:5")); info.setMessageCount(1); info.setPoisonCause(createThrowable("PoisonCause:6")); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessageAck * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class MessageAckTest extends BaseCommandTestSupport { public static MessageAckTest SINGLETON = new MessageAckTest(); public Object createObject() throws Exception { MessageAck info = new MessageAck(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessageAck info = (MessageAck) object; info.setDestination(createActiveMQDestination("Destination:1")); info.setTransactionId(createTransactionId("TransactionId:2")); info.setConsumerId(createConsumerId("ConsumerId:3")); info.setAckType((byte) 1); info.setFirstMessageId(createMessageId("FirstMessageId:4")); info.setLastMessageId(createMessageId("LastMessageId:5")); info.setMessageCount(1); info.setPoisonCause(createThrowable("PoisonCause:6")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/MessageDispatchNotificationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/MessageDispatchNotificationTest.java index 1ff388cb70..34b5e4be6c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/MessageDispatchNotificationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/MessageDispatchNotificationTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessageDispatchNotification * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class MessageDispatchNotificationTest extends BaseCommandTestSupport { public static MessageDispatchNotificationTest SINGLETON = new MessageDispatchNotificationTest(); public Object createObject() throws Exception { MessageDispatchNotification info = new MessageDispatchNotification(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessageDispatchNotification info = (MessageDispatchNotification) object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setDeliverySequenceId(1); info.setMessageId(createMessageId("MessageId:3")); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessageDispatchNotification * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class MessageDispatchNotificationTest extends BaseCommandTestSupport { public static MessageDispatchNotificationTest SINGLETON = new MessageDispatchNotificationTest(); public Object createObject() throws Exception { MessageDispatchNotification info = new MessageDispatchNotification(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessageDispatchNotification info = (MessageDispatchNotification) object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setDeliverySequenceId(1); info.setMessageId(createMessageId("MessageId:3")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/MessageDispatchTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/MessageDispatchTest.java index 46067a5c0d..b004b2bac5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/MessageDispatchTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/MessageDispatchTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessageDispatch * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class MessageDispatchTest extends BaseCommandTestSupport { public static MessageDispatchTest SINGLETON = new MessageDispatchTest(); public Object createObject() throws Exception { MessageDispatch info = new MessageDispatch(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessageDispatch info = (MessageDispatch) object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setMessage(createMessage("Message:3")); info.setRedeliveryCounter(1); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessageDispatch * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class MessageDispatchTest extends BaseCommandTestSupport { public static MessageDispatchTest SINGLETON = new MessageDispatchTest(); public Object createObject() throws Exception { MessageDispatch info = new MessageDispatch(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessageDispatch info = (MessageDispatch) object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setMessage(createMessage("Message:3")); info.setRedeliveryCounter(1); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/MessageIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/MessageIdTest.java index 5be4923064..f3dad49429 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/MessageIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/MessageIdTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessageId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class MessageIdTest extends DataFileGeneratorTestSupport { public static MessageIdTest SINGLETON = new MessageIdTest(); public Object createObject() throws Exception { MessageId info = new MessageId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessageId info = (MessageId) object; info.setProducerId(createProducerId("ProducerId:1")); info.setProducerSequenceId(1); info.setBrokerSequenceId(2); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessageId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class MessageIdTest extends DataFileGeneratorTestSupport { public static MessageIdTest SINGLETON = new MessageIdTest(); public Object createObject() throws Exception { MessageId info = new MessageId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessageId info = (MessageId) object; info.setProducerId(createProducerId("ProducerId:1")); info.setProducerSequenceId(1); info.setBrokerSequenceId(2); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/MessagePullTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/MessagePullTest.java index 142224f665..ec85fffb8e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/MessagePullTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/MessagePullTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessagePull * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class MessagePullTest extends BaseCommandTestSupport { public static MessagePullTest SINGLETON = new MessagePullTest(); public Object createObject() throws Exception { MessagePull info = new MessagePull(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessagePull info = (MessagePull) object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setTimeout(1); info.setCorrelationId("CorrelationId:3"); info.setMessageId(createMessageId("MessageId:4")); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessagePull * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class MessagePullTest extends BaseCommandTestSupport { public static MessagePullTest SINGLETON = new MessagePullTest(); public Object createObject() throws Exception { MessagePull info = new MessagePull(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessagePull info = (MessagePull) object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setTimeout(1); info.setCorrelationId("CorrelationId:3"); info.setMessageId(createMessageId("MessageId:4")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/MessageTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/MessageTestSupport.java index 0e3b269b50..94251d6677 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/MessageTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/MessageTestSupport.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for Message * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public abstract class MessageTestSupport extends BaseCommandTestSupport { protected void populateObject(Object object) throws Exception { super.populateObject(object); Message info = (Message) object; info.setProducerId(createProducerId("ProducerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setTransactionId(createTransactionId("TransactionId:3")); info.setOriginalDestination(createActiveMQDestination("OriginalDestination:4")); info.setMessageId(createMessageId("MessageId:5")); info.setOriginalTransactionId(createTransactionId("OriginalTransactionId:6")); info.setGroupID("GroupID:7"); info.setGroupSequence(1); info.setCorrelationId("CorrelationId:8"); info.setPersistent(true); info.setExpiration(1); info.setPriority((byte) 1); info.setReplyTo(createActiveMQDestination("ReplyTo:9")); info.setTimestamp(2); info.setType("Type:10"); { byte data[] = "Content:11".getBytes(); info.setContent(new org.apache.activemq.util.ByteSequence(data,0,data.length)); } { byte data[] = "MarshalledProperties:12".getBytes(); info.setMarshalledProperties(new org.apache.activemq.util.ByteSequence(data,0,data.length)); } info.setDataStructure(createDataStructure("DataStructure:13")); info.setTargetConsumerId(createConsumerId("TargetConsumerId:14")); info.setCompressed(false); info.setRedeliveryCounter(2); { BrokerId value[] = new BrokerId[2]; for( int i=0; i < 2; i++ ) { value[i] = createBrokerId("BrokerPath:15"); } info.setBrokerPath(value); } info.setArrival(3); info.setUserID("UserID:16"); info.setRecievedByDFBridge(true); info.setDroppable(false); { BrokerId value[] = new BrokerId[2]; for( int i=0; i < 2; i++ ) { value[i] = createBrokerId("Cluster:17"); } info.setCluster(value); } info.setBrokerInTime(4); info.setBrokerOutTime(5); } } \ No newline at end of file +/** * * 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.openwire.v8; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for Message * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public abstract class MessageTestSupport extends BaseCommandTestSupport { protected void populateObject(Object object) throws Exception { super.populateObject(object); Message info = (Message) object; info.setProducerId(createProducerId("ProducerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setTransactionId(createTransactionId("TransactionId:3")); info.setOriginalDestination(createActiveMQDestination("OriginalDestination:4")); info.setMessageId(createMessageId("MessageId:5")); info.setOriginalTransactionId(createTransactionId("OriginalTransactionId:6")); info.setGroupID("GroupID:7"); info.setGroupSequence(1); info.setCorrelationId("CorrelationId:8"); info.setPersistent(true); info.setExpiration(1); info.setPriority((byte) 1); info.setReplyTo(createActiveMQDestination("ReplyTo:9")); info.setTimestamp(2); info.setType("Type:10"); { byte data[] = "Content:11".getBytes(); info.setContent(new org.apache.activemq.util.ByteSequence(data, 0, data.length)); } { byte data[] = "MarshalledProperties:12".getBytes(); info.setMarshalledProperties(new org.apache.activemq.util.ByteSequence(data, 0, data.length)); } info.setDataStructure(createDataStructure("DataStructure:13")); info.setTargetConsumerId(createConsumerId("TargetConsumerId:14")); info.setCompressed(false); info.setRedeliveryCounter(2); { BrokerId value[] = new BrokerId[2]; for (int i = 0; i < 2; i++) { value[i] = createBrokerId("BrokerPath:15"); } info.setBrokerPath(value); } info.setArrival(3); info.setUserID("UserID:16"); info.setRecievedByDFBridge(true); info.setDroppable(false); { BrokerId value[] = new BrokerId[2]; for (int i = 0; i < 2; i++) { value[i] = createBrokerId("Cluster:17"); } info.setCluster(value); } info.setBrokerInTime(4); info.setBrokerOutTime(5); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/NetworkBridgeFilterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/NetworkBridgeFilterTest.java index 34d851b45a..b259d868ba 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/NetworkBridgeFilterTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/NetworkBridgeFilterTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for NetworkBridgeFilter * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class NetworkBridgeFilterTest extends DataFileGeneratorTestSupport { public static NetworkBridgeFilterTest SINGLETON = new NetworkBridgeFilterTest(); public Object createObject() throws Exception { NetworkBridgeFilter info = new NetworkBridgeFilter(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); NetworkBridgeFilter info = (NetworkBridgeFilter) object; info.setNetworkTTL(1); info.setNetworkBrokerId(createBrokerId("NetworkBrokerId:1")); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for NetworkBridgeFilter * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class NetworkBridgeFilterTest extends DataFileGeneratorTestSupport { public static NetworkBridgeFilterTest SINGLETON = new NetworkBridgeFilterTest(); public Object createObject() throws Exception { NetworkBridgeFilter info = new NetworkBridgeFilter(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); NetworkBridgeFilter info = (NetworkBridgeFilter) object; info.setNetworkTTL(1); info.setNetworkBrokerId(createBrokerId("NetworkBrokerId:1")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/PartialCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/PartialCommandTest.java index 30a22f8dba..bab437c67e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/PartialCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/PartialCommandTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for PartialCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class PartialCommandTest extends DataFileGeneratorTestSupport { public static PartialCommandTest SINGLETON = new PartialCommandTest(); public Object createObject() throws Exception { PartialCommand info = new PartialCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); PartialCommand info = (PartialCommand) object; info.setCommandId(1); info.setData("Data:1".getBytes()); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for PartialCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class PartialCommandTest extends DataFileGeneratorTestSupport { public static PartialCommandTest SINGLETON = new PartialCommandTest(); public Object createObject() throws Exception { PartialCommand info = new PartialCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); PartialCommand info = (PartialCommand) object; info.setCommandId(1); info.setData("Data:1".getBytes()); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ProducerAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ProducerAckTest.java index d1296311e8..12139c840b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ProducerAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ProducerAckTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ProducerAck * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ProducerAckTest extends BaseCommandTestSupport { public static ProducerAckTest SINGLETON = new ProducerAckTest(); public Object createObject() throws Exception { ProducerAck info = new ProducerAck(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ProducerAck info = (ProducerAck) object; info.setProducerId(createProducerId("ProducerId:1")); info.setSize(1); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ProducerAck * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ProducerAckTest extends BaseCommandTestSupport { public static ProducerAckTest SINGLETON = new ProducerAckTest(); public Object createObject() throws Exception { ProducerAck info = new ProducerAck(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ProducerAck info = (ProducerAck) object; info.setProducerId(createProducerId("ProducerId:1")); info.setSize(1); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ProducerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ProducerIdTest.java index d61330bdb7..6fca0d68af 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ProducerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ProducerIdTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ProducerId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ProducerIdTest extends DataFileGeneratorTestSupport { public static ProducerIdTest SINGLETON = new ProducerIdTest(); public Object createObject() throws Exception { ProducerId info = new ProducerId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ProducerId info = (ProducerId) object; info.setConnectionId("ConnectionId:1"); info.setValue(1); info.setSessionId(2); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ProducerId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ProducerIdTest extends DataFileGeneratorTestSupport { public static ProducerIdTest SINGLETON = new ProducerIdTest(); public Object createObject() throws Exception { ProducerId info = new ProducerId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ProducerId info = (ProducerId) object; info.setConnectionId("ConnectionId:1"); info.setValue(1); info.setSessionId(2); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ProducerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ProducerInfoTest.java index ba576c3468..305baee899 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ProducerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ProducerInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ProducerInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ProducerInfoTest extends BaseCommandTestSupport { public static ProducerInfoTest SINGLETON = new ProducerInfoTest(); public Object createObject() throws Exception { ProducerInfo info = new ProducerInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ProducerInfo info = (ProducerInfo) object; info.setProducerId(createProducerId("ProducerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); { BrokerId value[] = new BrokerId[2]; for( int i=0; i < 2; i++ ) { value[i] = createBrokerId("BrokerPath:3"); } info.setBrokerPath(value); } info.setDispatchAsync(true); info.setWindowSize(1); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ProducerInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ProducerInfoTest extends BaseCommandTestSupport { public static ProducerInfoTest SINGLETON = new ProducerInfoTest(); public Object createObject() throws Exception { ProducerInfo info = new ProducerInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ProducerInfo info = (ProducerInfo) object; info.setProducerId(createProducerId("ProducerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); { BrokerId value[] = new BrokerId[2]; for (int i = 0; i < 2; i++) { value[i] = createBrokerId("BrokerPath:3"); } info.setBrokerPath(value); } info.setDispatchAsync(true); info.setWindowSize(1); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/RemoveInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/RemoveInfoTest.java index 0d5d5da9e6..7bebb00aee 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/RemoveInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/RemoveInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for RemoveInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class RemoveInfoTest extends BaseCommandTestSupport { public static RemoveInfoTest SINGLETON = new RemoveInfoTest(); public Object createObject() throws Exception { RemoveInfo info = new RemoveInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); RemoveInfo info = (RemoveInfo) object; info.setObjectId(createDataStructure("ObjectId:1")); info.setLastDeliveredSequenceId(1); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for RemoveInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class RemoveInfoTest extends BaseCommandTestSupport { public static RemoveInfoTest SINGLETON = new RemoveInfoTest(); public Object createObject() throws Exception { RemoveInfo info = new RemoveInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); RemoveInfo info = (RemoveInfo) object; info.setObjectId(createDataStructure("ObjectId:1")); info.setLastDeliveredSequenceId(1); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/RemoveSubscriptionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/RemoveSubscriptionInfoTest.java index 9120790bc3..4a68a7d529 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/RemoveSubscriptionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/RemoveSubscriptionInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for RemoveSubscriptionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class RemoveSubscriptionInfoTest extends BaseCommandTestSupport { public static RemoveSubscriptionInfoTest SINGLETON = new RemoveSubscriptionInfoTest(); public Object createObject() throws Exception { RemoveSubscriptionInfo info = new RemoveSubscriptionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); RemoveSubscriptionInfo info = (RemoveSubscriptionInfo) object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setSubcriptionName("SubcriptionName:2"); info.setClientId("ClientId:3"); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for RemoveSubscriptionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class RemoveSubscriptionInfoTest extends BaseCommandTestSupport { public static RemoveSubscriptionInfoTest SINGLETON = new RemoveSubscriptionInfoTest(); public Object createObject() throws Exception { RemoveSubscriptionInfo info = new RemoveSubscriptionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); RemoveSubscriptionInfo info = (RemoveSubscriptionInfo) object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setSubcriptionName("SubcriptionName:2"); info.setClientId("ClientId:3"); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ReplayCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ReplayCommandTest.java index 558edf77d5..4a4db661fc 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ReplayCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ReplayCommandTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ReplayCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ReplayCommandTest extends BaseCommandTestSupport { public static ReplayCommandTest SINGLETON = new ReplayCommandTest(); public Object createObject() throws Exception { ReplayCommand info = new ReplayCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ReplayCommand info = (ReplayCommand) object; info.setFirstNakNumber(1); info.setLastNakNumber(2); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ReplayCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ReplayCommandTest extends BaseCommandTestSupport { public static ReplayCommandTest SINGLETON = new ReplayCommandTest(); public Object createObject() throws Exception { ReplayCommand info = new ReplayCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ReplayCommand info = (ReplayCommand) object; info.setFirstNakNumber(1); info.setLastNakNumber(2); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ResponseTest.java index 9a46fa0e18..c36f7f1c0e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ResponseTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for Response * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ResponseTest extends BaseCommandTestSupport { public static ResponseTest SINGLETON = new ResponseTest(); public Object createObject() throws Exception { Response info = new Response(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); Response info = (Response) object; info.setCorrelationId(1); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for Response * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ResponseTest extends BaseCommandTestSupport { public static ResponseTest SINGLETON = new ResponseTest(); public Object createObject() throws Exception { Response info = new Response(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); Response info = (Response) object; info.setCorrelationId(1); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/SessionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/SessionIdTest.java index ed13b5f0f0..74407d76d3 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/SessionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/SessionIdTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for SessionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class SessionIdTest extends DataFileGeneratorTestSupport { public static SessionIdTest SINGLETON = new SessionIdTest(); public Object createObject() throws Exception { SessionId info = new SessionId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); SessionId info = (SessionId) object; info.setConnectionId("ConnectionId:1"); info.setValue(1); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for SessionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class SessionIdTest extends DataFileGeneratorTestSupport { public static SessionIdTest SINGLETON = new SessionIdTest(); public Object createObject() throws Exception { SessionId info = new SessionId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); SessionId info = (SessionId) object; info.setConnectionId("ConnectionId:1"); info.setValue(1); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/SessionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/SessionInfoTest.java index 292e0efe66..937c7c18ec 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/SessionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/SessionInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for SessionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class SessionInfoTest extends BaseCommandTestSupport { public static SessionInfoTest SINGLETON = new SessionInfoTest(); public Object createObject() throws Exception { SessionInfo info = new SessionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); SessionInfo info = (SessionInfo) object; info.setSessionId(createSessionId("SessionId:1")); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for SessionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class SessionInfoTest extends BaseCommandTestSupport { public static SessionInfoTest SINGLETON = new SessionInfoTest(); public Object createObject() throws Exception { SessionInfo info = new SessionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); SessionInfo info = (SessionInfo) object; info.setSessionId(createSessionId("SessionId:1")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ShutdownInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ShutdownInfoTest.java index 3bc212fa84..bb2b21106f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ShutdownInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/ShutdownInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ShutdownInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ShutdownInfoTest extends BaseCommandTestSupport { public static ShutdownInfoTest SINGLETON = new ShutdownInfoTest(); public Object createObject() throws Exception { ShutdownInfo info = new ShutdownInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ShutdownInfo info = (ShutdownInfo) object; } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ShutdownInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ShutdownInfoTest extends BaseCommandTestSupport { public static ShutdownInfoTest SINGLETON = new ShutdownInfoTest(); public Object createObject() throws Exception { ShutdownInfo info = new ShutdownInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ShutdownInfo info = (ShutdownInfo) object; } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/SubscriptionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/SubscriptionInfoTest.java index a7179cf346..f7559d913f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/SubscriptionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/SubscriptionInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for SubscriptionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class SubscriptionInfoTest extends DataFileGeneratorTestSupport { public static SubscriptionInfoTest SINGLETON = new SubscriptionInfoTest(); public Object createObject() throws Exception { SubscriptionInfo info = new SubscriptionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); SubscriptionInfo info = (SubscriptionInfo) object; info.setClientId("ClientId:1"); info.setDestination(createActiveMQDestination("Destination:2")); info.setSelector("Selector:3"); info.setSubcriptionName("SubcriptionName:4"); info.setSubscribedDestination(createActiveMQDestination("SubscribedDestination:5")); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for SubscriptionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class SubscriptionInfoTest extends DataFileGeneratorTestSupport { public static SubscriptionInfoTest SINGLETON = new SubscriptionInfoTest(); public Object createObject() throws Exception { SubscriptionInfo info = new SubscriptionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); SubscriptionInfo info = (SubscriptionInfo) object; info.setClientId("ClientId:1"); info.setDestination(createActiveMQDestination("Destination:2")); info.setSelector("Selector:3"); info.setSubcriptionName("SubcriptionName:4"); info.setSubscribedDestination(createActiveMQDestination("SubscribedDestination:5")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/TransactionIdTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/TransactionIdTestSupport.java index 7781ea367c..ab29ed4bc4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/TransactionIdTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/TransactionIdTestSupport.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for TransactionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public abstract class TransactionIdTestSupport extends DataFileGeneratorTestSupport { protected void populateObject(Object object) throws Exception { super.populateObject(object); TransactionId info = (TransactionId) object; } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for TransactionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public abstract class TransactionIdTestSupport extends DataFileGeneratorTestSupport { protected void populateObject(Object object) throws Exception { super.populateObject(object); TransactionId info = (TransactionId) object; } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/TransactionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/TransactionInfoTest.java index 53a11a508d..2d20d9b2e1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/TransactionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/TransactionInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for TransactionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class TransactionInfoTest extends BaseCommandTestSupport { public static TransactionInfoTest SINGLETON = new TransactionInfoTest(); public Object createObject() throws Exception { TransactionInfo info = new TransactionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); TransactionInfo info = (TransactionInfo) object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setTransactionId(createTransactionId("TransactionId:2")); info.setType((byte) 1); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for TransactionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class TransactionInfoTest extends BaseCommandTestSupport { public static TransactionInfoTest SINGLETON = new TransactionInfoTest(); public Object createObject() throws Exception { TransactionInfo info = new TransactionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); TransactionInfo info = (TransactionInfo) object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setTransactionId(createTransactionId("TransactionId:2")); info.setType((byte) 1); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/XATransactionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/XATransactionIdTest.java index 0f7c2ebcee..aea3bd5af1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/XATransactionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v8/XATransactionIdTest.java @@ -1 +1 @@ -/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for XATransactionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class XATransactionIdTest extends TransactionIdTestSupport { public static XATransactionIdTest SINGLETON = new XATransactionIdTest(); public Object createObject() throws Exception { XATransactionId info = new XATransactionId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); XATransactionId info = (XATransactionId) object; info.setFormatId(1); info.setGlobalTransactionId("GlobalTransactionId:1".getBytes()); info.setBranchQualifier("BranchQualifier:2".getBytes()); } } \ No newline at end of file +/** * * 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.openwire.v8; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for XATransactionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class XATransactionIdTest extends TransactionIdTestSupport { public static XATransactionIdTest SINGLETON = new XATransactionIdTest(); public Object createObject() throws Exception { XATransactionId info = new XATransactionId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); XATransactionId info = (XATransactionId) object; info.setFormatId(1); info.setGlobalTransactionId("GlobalTransactionId:1".getBytes()); info.setBranchQualifier("BranchQualifier:2".getBytes()); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/BaseCommandTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/BaseCommandTestSupport.java index c11b7f4c91..afeea6b402 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/BaseCommandTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/BaseCommandTestSupport.java @@ -24,15 +24,14 @@ import org.apache.activemq.openwire.DataFileGeneratorTestSupport; * auto generated - do not modify! if you need to make a change, please see the * modify the groovy scripts in the under src/gram/script and then use maven * openwire:generate to regenerate this file. - * */ public abstract class BaseCommandTestSupport extends DataFileGeneratorTestSupport { - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - BaseCommand info = (BaseCommand)object; - info.setCommandId(1); - info.setResponseRequired(true); + protected void populateObject(Object object) throws Exception { + super.populateObject(object); + BaseCommand info = (BaseCommand) object; + info.setCommandId(1); + info.setResponseRequired(true); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/BrokerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/BrokerIdTest.java index 0d53067e80..15e0f1f91a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/BrokerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/BrokerIdTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for BrokerId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class BrokerIdTest extends DataFileGeneratorTestSupport { public static BrokerIdTest SINGLETON = new BrokerIdTest(); public Object createObject() throws Exception { BrokerId info = new BrokerId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); BrokerId info = (BrokerId) object; info.setValue("Value:1"); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for BrokerId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class BrokerIdTest extends DataFileGeneratorTestSupport { public static BrokerIdTest SINGLETON = new BrokerIdTest(); public Object createObject() throws Exception { BrokerId info = new BrokerId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); BrokerId info = (BrokerId) object; info.setValue("Value:1"); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/BrokerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/BrokerInfoTest.java index b0d9658922..7f5afbee52 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/BrokerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/BrokerInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for BrokerInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class BrokerInfoTest extends BaseCommandTestSupport { public static BrokerInfoTest SINGLETON = new BrokerInfoTest(); public Object createObject() throws Exception { BrokerInfo info = new BrokerInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); BrokerInfo info = (BrokerInfo) object; info.setBrokerId(createBrokerId("BrokerId:1")); info.setBrokerURL("BrokerURL:2"); { BrokerInfo value[] = new BrokerInfo[0]; for( int i=0; i < 0; i++ ) { value[i] = createBrokerInfo("PeerBrokerInfos:3"); } info.setPeerBrokerInfos(value); } info.setBrokerName("BrokerName:4"); info.setSlaveBroker(true); info.setMasterBroker(false); info.setFaultTolerantConfiguration(true); info.setDuplexConnection(false); info.setNetworkConnection(true); info.setConnectionId(1); info.setBrokerUploadUrl("BrokerUploadUrl:5"); info.setNetworkProperties("NetworkProperties:6"); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for BrokerInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class BrokerInfoTest extends BaseCommandTestSupport { public static BrokerInfoTest SINGLETON = new BrokerInfoTest(); public Object createObject() throws Exception { BrokerInfo info = new BrokerInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); BrokerInfo info = (BrokerInfo) object; info.setBrokerId(createBrokerId("BrokerId:1")); info.setBrokerURL("BrokerURL:2"); { BrokerInfo value[] = new BrokerInfo[0]; for (int i = 0; i < 0; i++) { value[i] = createBrokerInfo("PeerBrokerInfos:3"); } info.setPeerBrokerInfos(value); } info.setBrokerName("BrokerName:4"); info.setSlaveBroker(true); info.setMasterBroker(false); info.setFaultTolerantConfiguration(true); info.setDuplexConnection(false); info.setNetworkConnection(true); info.setConnectionId(1); info.setBrokerUploadUrl("BrokerUploadUrl:5"); info.setNetworkProperties("NetworkProperties:6"); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConnectionControlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConnectionControlTest.java index e259ec7904..3286b2f33a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConnectionControlTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConnectionControlTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConnectionControl * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ConnectionControlTest extends BaseCommandTestSupport { public static ConnectionControlTest SINGLETON = new ConnectionControlTest(); public Object createObject() throws Exception { ConnectionControl info = new ConnectionControl(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConnectionControl info = (ConnectionControl) object; info.setClose(true); info.setExit(false); info.setFaultTolerant(true); info.setResume(false); info.setSuspend(true); info.setConnectedBrokers("ConnectedBrokers:1"); info.setReconnectTo("ReconnectTo:2"); info.setRebalanceConnection(false); info.setToken("Token:3".getBytes()); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConnectionControl * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ConnectionControlTest extends BaseCommandTestSupport { public static ConnectionControlTest SINGLETON = new ConnectionControlTest(); public Object createObject() throws Exception { ConnectionControl info = new ConnectionControl(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConnectionControl info = (ConnectionControl) object; info.setClose(true); info.setExit(false); info.setFaultTolerant(true); info.setResume(false); info.setSuspend(true); info.setConnectedBrokers("ConnectedBrokers:1"); info.setReconnectTo("ReconnectTo:2"); info.setRebalanceConnection(false); info.setToken("Token:3".getBytes()); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConnectionErrorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConnectionErrorTest.java index 52ce46b917..72a52d031b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConnectionErrorTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConnectionErrorTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConnectionError * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ConnectionErrorTest extends BaseCommandTestSupport { public static ConnectionErrorTest SINGLETON = new ConnectionErrorTest(); public Object createObject() throws Exception { ConnectionError info = new ConnectionError(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConnectionError info = (ConnectionError) object; info.setException(createThrowable("Exception:1")); info.setConnectionId(createConnectionId("ConnectionId:2")); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConnectionError * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ConnectionErrorTest extends BaseCommandTestSupport { public static ConnectionErrorTest SINGLETON = new ConnectionErrorTest(); public Object createObject() throws Exception { ConnectionError info = new ConnectionError(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConnectionError info = (ConnectionError) object; info.setException(createThrowable("Exception:1")); info.setConnectionId(createConnectionId("ConnectionId:2")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConnectionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConnectionIdTest.java index d0b4fcfe3d..8b98c25911 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConnectionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConnectionIdTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConnectionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ConnectionIdTest extends DataFileGeneratorTestSupport { public static ConnectionIdTest SINGLETON = new ConnectionIdTest(); public Object createObject() throws Exception { ConnectionId info = new ConnectionId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConnectionId info = (ConnectionId) object; info.setValue("Value:1"); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConnectionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ConnectionIdTest extends DataFileGeneratorTestSupport { public static ConnectionIdTest SINGLETON = new ConnectionIdTest(); public Object createObject() throws Exception { ConnectionId info = new ConnectionId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConnectionId info = (ConnectionId) object; info.setValue("Value:1"); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConnectionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConnectionInfoTest.java index 9cafabc29b..e43eee5dd3 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConnectionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConnectionInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConnectionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ConnectionInfoTest extends BaseCommandTestSupport { public static ConnectionInfoTest SINGLETON = new ConnectionInfoTest(); public Object createObject() throws Exception { ConnectionInfo info = new ConnectionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConnectionInfo info = (ConnectionInfo) object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setClientId("ClientId:2"); info.setPassword("Password:3"); info.setUserName("UserName:4"); { BrokerId value[] = new BrokerId[2]; for( int i=0; i < 2; i++ ) { value[i] = createBrokerId("BrokerPath:5"); } info.setBrokerPath(value); } info.setBrokerMasterConnector(true); info.setManageable(false); info.setClientMaster(true); info.setFaultTolerant(false); info.setFailoverReconnect(true); info.setClientIp("ClientIp:6"); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConnectionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ConnectionInfoTest extends BaseCommandTestSupport { public static ConnectionInfoTest SINGLETON = new ConnectionInfoTest(); public Object createObject() throws Exception { ConnectionInfo info = new ConnectionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConnectionInfo info = (ConnectionInfo) object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setClientId("ClientId:2"); info.setPassword("Password:3"); info.setUserName("UserName:4"); { BrokerId value[] = new BrokerId[2]; for (int i = 0; i < 2; i++) { value[i] = createBrokerId("BrokerPath:5"); } info.setBrokerPath(value); } info.setBrokerMasterConnector(true); info.setManageable(false); info.setClientMaster(true); info.setFaultTolerant(false); info.setFailoverReconnect(true); info.setClientIp("ClientIp:6"); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConsumerControlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConsumerControlTest.java index 39fc381516..11a4f5c575 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConsumerControlTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConsumerControlTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConsumerControl * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ConsumerControlTest extends BaseCommandTestSupport { public static ConsumerControlTest SINGLETON = new ConsumerControlTest(); public Object createObject() throws Exception { ConsumerControl info = new ConsumerControl(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConsumerControl info = (ConsumerControl) object; info.setDestination(createActiveMQDestination("Destination:1")); info.setClose(true); info.setConsumerId(createConsumerId("ConsumerId:2")); info.setPrefetch(1); info.setFlush(false); info.setStart(true); info.setStop(false); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConsumerControl * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ConsumerControlTest extends BaseCommandTestSupport { public static ConsumerControlTest SINGLETON = new ConsumerControlTest(); public Object createObject() throws Exception { ConsumerControl info = new ConsumerControl(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConsumerControl info = (ConsumerControl) object; info.setDestination(createActiveMQDestination("Destination:1")); info.setClose(true); info.setConsumerId(createConsumerId("ConsumerId:2")); info.setPrefetch(1); info.setFlush(false); info.setStart(true); info.setStop(false); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConsumerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConsumerIdTest.java index edefe398c2..7e6374477e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConsumerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConsumerIdTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConsumerId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ConsumerIdTest extends DataFileGeneratorTestSupport { public static ConsumerIdTest SINGLETON = new ConsumerIdTest(); public Object createObject() throws Exception { ConsumerId info = new ConsumerId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConsumerId info = (ConsumerId) object; info.setConnectionId("ConnectionId:1"); info.setSessionId(1); info.setValue(2); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConsumerId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ConsumerIdTest extends DataFileGeneratorTestSupport { public static ConsumerIdTest SINGLETON = new ConsumerIdTest(); public Object createObject() throws Exception { ConsumerId info = new ConsumerId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConsumerId info = (ConsumerId) object; info.setConnectionId("ConnectionId:1"); info.setSessionId(1); info.setValue(2); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConsumerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConsumerInfoTest.java index a31ff687a3..5ff9aaeff2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConsumerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ConsumerInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConsumerInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ConsumerInfoTest extends BaseCommandTestSupport { public static ConsumerInfoTest SINGLETON = new ConsumerInfoTest(); public Object createObject() throws Exception { ConsumerInfo info = new ConsumerInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConsumerInfo info = (ConsumerInfo) object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setBrowser(true); info.setDestination(createActiveMQDestination("Destination:2")); info.setPrefetchSize(1); info.setMaximumPendingMessageLimit(2); info.setDispatchAsync(false); info.setSelector("Selector:3"); info.setSubscriptionName("SubscriptionName:4"); info.setNoLocal(true); info.setExclusive(false); info.setRetroactive(true); info.setPriority((byte) 1); { BrokerId value[] = new BrokerId[2]; for( int i=0; i < 2; i++ ) { value[i] = createBrokerId("BrokerPath:5"); } info.setBrokerPath(value); } info.setAdditionalPredicate(createBooleanExpression("AdditionalPredicate:6")); info.setNetworkSubscription(false); info.setOptimizedAcknowledge(true); info.setNoRangeAcks(false); { ConsumerId value[] = new ConsumerId[2]; for( int i=0; i < 2; i++ ) { value[i] = createConsumerId("NetworkConsumerPath:7"); } info.setNetworkConsumerPath(value); } } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ConsumerInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ConsumerInfoTest extends BaseCommandTestSupport { public static ConsumerInfoTest SINGLETON = new ConsumerInfoTest(); public Object createObject() throws Exception { ConsumerInfo info = new ConsumerInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ConsumerInfo info = (ConsumerInfo) object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setBrowser(true); info.setDestination(createActiveMQDestination("Destination:2")); info.setPrefetchSize(1); info.setMaximumPendingMessageLimit(2); info.setDispatchAsync(false); info.setSelector("Selector:3"); info.setSubscriptionName("SubscriptionName:4"); info.setNoLocal(true); info.setExclusive(false); info.setRetroactive(true); info.setPriority((byte) 1); { BrokerId value[] = new BrokerId[2]; for (int i = 0; i < 2; i++) { value[i] = createBrokerId("BrokerPath:5"); } info.setBrokerPath(value); } info.setAdditionalPredicate(createBooleanExpression("AdditionalPredicate:6")); info.setNetworkSubscription(false); info.setOptimizedAcknowledge(true); info.setNoRangeAcks(false); { ConsumerId value[] = new ConsumerId[2]; for (int i = 0; i < 2; i++) { value[i] = createConsumerId("NetworkConsumerPath:7"); } info.setNetworkConsumerPath(value); } } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ControlCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ControlCommandTest.java index 6e86e3c594..78506823f7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ControlCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ControlCommandTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ControlCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ControlCommandTest extends BaseCommandTestSupport { public static ControlCommandTest SINGLETON = new ControlCommandTest(); public Object createObject() throws Exception { ControlCommand info = new ControlCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ControlCommand info = (ControlCommand) object; info.setCommand("Command:1"); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ControlCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ControlCommandTest extends BaseCommandTestSupport { public static ControlCommandTest SINGLETON = new ControlCommandTest(); public Object createObject() throws Exception { ControlCommand info = new ControlCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ControlCommand info = (ControlCommand) object; info.setCommand("Command:1"); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/DataArrayResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/DataArrayResponseTest.java index 967964a461..53f47cb7d2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/DataArrayResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/DataArrayResponseTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for DataArrayResponse * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class DataArrayResponseTest extends ResponseTest { public static DataArrayResponseTest SINGLETON = new DataArrayResponseTest(); public Object createObject() throws Exception { DataArrayResponse info = new DataArrayResponse(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); DataArrayResponse info = (DataArrayResponse) object; { DataStructure value[] = new DataStructure[2]; for( int i=0; i < 2; i++ ) { value[i] = createDataStructure("Data:1"); } info.setData(value); } } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for DataArrayResponse * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class DataArrayResponseTest extends ResponseTest { public static DataArrayResponseTest SINGLETON = new DataArrayResponseTest(); public Object createObject() throws Exception { DataArrayResponse info = new DataArrayResponse(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); DataArrayResponse info = (DataArrayResponse) object; { DataStructure value[] = new DataStructure[2]; for (int i = 0; i < 2; i++) { value[i] = createDataStructure("Data:1"); } info.setData(value); } } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/DataResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/DataResponseTest.java index 82014879dd..3f92a4acf4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/DataResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/DataResponseTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for DataResponse * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class DataResponseTest extends ResponseTest { public static DataResponseTest SINGLETON = new DataResponseTest(); public Object createObject() throws Exception { DataResponse info = new DataResponse(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); DataResponse info = (DataResponse) object; info.setData(createDataStructure("Data:1")); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for DataResponse * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class DataResponseTest extends ResponseTest { public static DataResponseTest SINGLETON = new DataResponseTest(); public Object createObject() throws Exception { DataResponse info = new DataResponse(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); DataResponse info = (DataResponse) object; info.setData(createDataStructure("Data:1")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/DestinationInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/DestinationInfoTest.java index 35d8298be4..9907a8774f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/DestinationInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/DestinationInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for DestinationInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class DestinationInfoTest extends BaseCommandTestSupport { public static DestinationInfoTest SINGLETON = new DestinationInfoTest(); public Object createObject() throws Exception { DestinationInfo info = new DestinationInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); DestinationInfo info = (DestinationInfo) object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setOperationType((byte) 1); info.setTimeout(1); { BrokerId value[] = new BrokerId[2]; for( int i=0; i < 2; i++ ) { value[i] = createBrokerId("BrokerPath:3"); } info.setBrokerPath(value); } } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for DestinationInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class DestinationInfoTest extends BaseCommandTestSupport { public static DestinationInfoTest SINGLETON = new DestinationInfoTest(); public Object createObject() throws Exception { DestinationInfo info = new DestinationInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); DestinationInfo info = (DestinationInfo) object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setOperationType((byte) 1); info.setTimeout(1); { BrokerId value[] = new BrokerId[2]; for (int i = 0; i < 2; i++) { value[i] = createBrokerId("BrokerPath:3"); } info.setBrokerPath(value); } } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/DiscoveryEventTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/DiscoveryEventTest.java index e2709d7d00..cb185406d1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/DiscoveryEventTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/DiscoveryEventTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for DiscoveryEvent * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class DiscoveryEventTest extends DataFileGeneratorTestSupport { public static DiscoveryEventTest SINGLETON = new DiscoveryEventTest(); public Object createObject() throws Exception { DiscoveryEvent info = new DiscoveryEvent(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); DiscoveryEvent info = (DiscoveryEvent) object; info.setServiceName("ServiceName:1"); info.setBrokerName("BrokerName:2"); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for DiscoveryEvent * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class DiscoveryEventTest extends DataFileGeneratorTestSupport { public static DiscoveryEventTest SINGLETON = new DiscoveryEventTest(); public Object createObject() throws Exception { DiscoveryEvent info = new DiscoveryEvent(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); DiscoveryEvent info = (DiscoveryEvent) object; info.setServiceName("ServiceName:1"); info.setBrokerName("BrokerName:2"); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ExceptionResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ExceptionResponseTest.java index 27b56cad26..f0922da4d8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ExceptionResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ExceptionResponseTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ExceptionResponse * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ExceptionResponseTest extends ResponseTest { public static ExceptionResponseTest SINGLETON = new ExceptionResponseTest(); public Object createObject() throws Exception { ExceptionResponse info = new ExceptionResponse(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ExceptionResponse info = (ExceptionResponse) object; info.setException(createThrowable("Exception:1")); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ExceptionResponse * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ExceptionResponseTest extends ResponseTest { public static ExceptionResponseTest SINGLETON = new ExceptionResponseTest(); public Object createObject() throws Exception { ExceptionResponse info = new ExceptionResponse(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ExceptionResponse info = (ExceptionResponse) object; info.setException(createThrowable("Exception:1")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/FlushCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/FlushCommandTest.java index e6fec771cd..361a161afb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/FlushCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/FlushCommandTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for FlushCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class FlushCommandTest extends BaseCommandTestSupport { public static FlushCommandTest SINGLETON = new FlushCommandTest(); public Object createObject() throws Exception { FlushCommand info = new FlushCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); FlushCommand info = (FlushCommand) object; } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for FlushCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class FlushCommandTest extends BaseCommandTestSupport { public static FlushCommandTest SINGLETON = new FlushCommandTest(); public Object createObject() throws Exception { FlushCommand info = new FlushCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); FlushCommand info = (FlushCommand) object; } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/IntegerResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/IntegerResponseTest.java index 08b844a85d..45a29b002e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/IntegerResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/IntegerResponseTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for IntegerResponse * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class IntegerResponseTest extends ResponseTest { public static IntegerResponseTest SINGLETON = new IntegerResponseTest(); public Object createObject() throws Exception { IntegerResponse info = new IntegerResponse(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); IntegerResponse info = (IntegerResponse) object; info.setResult(1); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for IntegerResponse * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class IntegerResponseTest extends ResponseTest { public static IntegerResponseTest SINGLETON = new IntegerResponseTest(); public Object createObject() throws Exception { IntegerResponse info = new IntegerResponse(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); IntegerResponse info = (IntegerResponse) object; info.setResult(1); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/JournalQueueAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/JournalQueueAckTest.java index 15bc4e1a89..e97a586271 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/JournalQueueAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/JournalQueueAckTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for JournalQueueAck * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class JournalQueueAckTest extends DataFileGeneratorTestSupport { public static JournalQueueAckTest SINGLETON = new JournalQueueAckTest(); public Object createObject() throws Exception { JournalQueueAck info = new JournalQueueAck(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); JournalQueueAck info = (JournalQueueAck) object; info.setDestination(createActiveMQDestination("Destination:1")); info.setMessageAck(createMessageAck("MessageAck:2")); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for JournalQueueAck * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class JournalQueueAckTest extends DataFileGeneratorTestSupport { public static JournalQueueAckTest SINGLETON = new JournalQueueAckTest(); public Object createObject() throws Exception { JournalQueueAck info = new JournalQueueAck(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); JournalQueueAck info = (JournalQueueAck) object; info.setDestination(createActiveMQDestination("Destination:1")); info.setMessageAck(createMessageAck("MessageAck:2")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/JournalTopicAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/JournalTopicAckTest.java index 92ee5fce40..357750a2a4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/JournalTopicAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/JournalTopicAckTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for JournalTopicAck * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class JournalTopicAckTest extends DataFileGeneratorTestSupport { public static JournalTopicAckTest SINGLETON = new JournalTopicAckTest(); public Object createObject() throws Exception { JournalTopicAck info = new JournalTopicAck(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); JournalTopicAck info = (JournalTopicAck) object; info.setDestination(createActiveMQDestination("Destination:1")); info.setMessageId(createMessageId("MessageId:2")); info.setMessageSequenceId(1); info.setSubscritionName("SubscritionName:3"); info.setClientId("ClientId:4"); info.setTransactionId(createTransactionId("TransactionId:5")); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for JournalTopicAck * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class JournalTopicAckTest extends DataFileGeneratorTestSupport { public static JournalTopicAckTest SINGLETON = new JournalTopicAckTest(); public Object createObject() throws Exception { JournalTopicAck info = new JournalTopicAck(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); JournalTopicAck info = (JournalTopicAck) object; info.setDestination(createActiveMQDestination("Destination:1")); info.setMessageId(createMessageId("MessageId:2")); info.setMessageSequenceId(1); info.setSubscritionName("SubscritionName:3"); info.setClientId("ClientId:4"); info.setTransactionId(createTransactionId("TransactionId:5")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/JournalTraceTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/JournalTraceTest.java index fedee00cd1..6bfaf72ae8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/JournalTraceTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/JournalTraceTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for JournalTrace * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class JournalTraceTest extends DataFileGeneratorTestSupport { public static JournalTraceTest SINGLETON = new JournalTraceTest(); public Object createObject() throws Exception { JournalTrace info = new JournalTrace(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); JournalTrace info = (JournalTrace) object; info.setMessage("Message:1"); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for JournalTrace * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class JournalTraceTest extends DataFileGeneratorTestSupport { public static JournalTraceTest SINGLETON = new JournalTraceTest(); public Object createObject() throws Exception { JournalTrace info = new JournalTrace(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); JournalTrace info = (JournalTrace) object; info.setMessage("Message:1"); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/JournalTransactionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/JournalTransactionTest.java index ffad3dc019..6acce92acb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/JournalTransactionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/JournalTransactionTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for JournalTransaction * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class JournalTransactionTest extends DataFileGeneratorTestSupport { public static JournalTransactionTest SINGLETON = new JournalTransactionTest(); public Object createObject() throws Exception { JournalTransaction info = new JournalTransaction(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); JournalTransaction info = (JournalTransaction) object; info.setTransactionId(createTransactionId("TransactionId:1")); info.setType((byte) 1); info.setWasPrepared(true); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for JournalTransaction * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class JournalTransactionTest extends DataFileGeneratorTestSupport { public static JournalTransactionTest SINGLETON = new JournalTransactionTest(); public Object createObject() throws Exception { JournalTransaction info = new JournalTransaction(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); JournalTransaction info = (JournalTransaction) object; info.setTransactionId(createTransactionId("TransactionId:1")); info.setType((byte) 1); info.setWasPrepared(true); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/KeepAliveInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/KeepAliveInfoTest.java index aa04459bb7..a44533c5fc 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/KeepAliveInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/KeepAliveInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for KeepAliveInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class KeepAliveInfoTest extends BaseCommandTestSupport { public static KeepAliveInfoTest SINGLETON = new KeepAliveInfoTest(); public Object createObject() throws Exception { KeepAliveInfo info = new KeepAliveInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); KeepAliveInfo info = (KeepAliveInfo) object; } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for KeepAliveInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class KeepAliveInfoTest extends BaseCommandTestSupport { public static KeepAliveInfoTest SINGLETON = new KeepAliveInfoTest(); public Object createObject() throws Exception { KeepAliveInfo info = new KeepAliveInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); KeepAliveInfo info = (KeepAliveInfo) object; } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/LastPartialCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/LastPartialCommandTest.java index 6073a93311..69822e9f0c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/LastPartialCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/LastPartialCommandTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for LastPartialCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class LastPartialCommandTest extends PartialCommandTest { public static LastPartialCommandTest SINGLETON = new LastPartialCommandTest(); public Object createObject() throws Exception { LastPartialCommand info = new LastPartialCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); LastPartialCommand info = (LastPartialCommand) object; } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for LastPartialCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class LastPartialCommandTest extends PartialCommandTest { public static LastPartialCommandTest SINGLETON = new LastPartialCommandTest(); public Object createObject() throws Exception { LastPartialCommand info = new LastPartialCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); LastPartialCommand info = (LastPartialCommand) object; } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/LocalTransactionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/LocalTransactionIdTest.java index 92fde53172..8908037e85 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/LocalTransactionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/LocalTransactionIdTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for LocalTransactionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class LocalTransactionIdTest extends TransactionIdTestSupport { public static LocalTransactionIdTest SINGLETON = new LocalTransactionIdTest(); public Object createObject() throws Exception { LocalTransactionId info = new LocalTransactionId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); LocalTransactionId info = (LocalTransactionId) object; info.setValue(1); info.setConnectionId(createConnectionId("ConnectionId:1")); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for LocalTransactionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class LocalTransactionIdTest extends TransactionIdTestSupport { public static LocalTransactionIdTest SINGLETON = new LocalTransactionIdTest(); public Object createObject() throws Exception { LocalTransactionId info = new LocalTransactionId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); LocalTransactionId info = (LocalTransactionId) object; info.setValue(1); info.setConnectionId(createConnectionId("ConnectionId:1")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/MessageAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/MessageAckTest.java index 975042f2f8..c53ff2a923 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/MessageAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/MessageAckTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessageAck * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class MessageAckTest extends BaseCommandTestSupport { public static MessageAckTest SINGLETON = new MessageAckTest(); public Object createObject() throws Exception { MessageAck info = new MessageAck(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessageAck info = (MessageAck) object; info.setDestination(createActiveMQDestination("Destination:1")); info.setTransactionId(createTransactionId("TransactionId:2")); info.setConsumerId(createConsumerId("ConsumerId:3")); info.setAckType((byte) 1); info.setFirstMessageId(createMessageId("FirstMessageId:4")); info.setLastMessageId(createMessageId("LastMessageId:5")); info.setMessageCount(1); info.setPoisonCause(createThrowable("PoisonCause:6")); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessageAck * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class MessageAckTest extends BaseCommandTestSupport { public static MessageAckTest SINGLETON = new MessageAckTest(); public Object createObject() throws Exception { MessageAck info = new MessageAck(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessageAck info = (MessageAck) object; info.setDestination(createActiveMQDestination("Destination:1")); info.setTransactionId(createTransactionId("TransactionId:2")); info.setConsumerId(createConsumerId("ConsumerId:3")); info.setAckType((byte) 1); info.setFirstMessageId(createMessageId("FirstMessageId:4")); info.setLastMessageId(createMessageId("LastMessageId:5")); info.setMessageCount(1); info.setPoisonCause(createThrowable("PoisonCause:6")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/MessageDispatchNotificationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/MessageDispatchNotificationTest.java index d335b0bbea..505bc38b7f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/MessageDispatchNotificationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/MessageDispatchNotificationTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessageDispatchNotification * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class MessageDispatchNotificationTest extends BaseCommandTestSupport { public static MessageDispatchNotificationTest SINGLETON = new MessageDispatchNotificationTest(); public Object createObject() throws Exception { MessageDispatchNotification info = new MessageDispatchNotification(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessageDispatchNotification info = (MessageDispatchNotification) object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setDeliverySequenceId(1); info.setMessageId(createMessageId("MessageId:3")); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessageDispatchNotification * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class MessageDispatchNotificationTest extends BaseCommandTestSupport { public static MessageDispatchNotificationTest SINGLETON = new MessageDispatchNotificationTest(); public Object createObject() throws Exception { MessageDispatchNotification info = new MessageDispatchNotification(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessageDispatchNotification info = (MessageDispatchNotification) object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setDeliverySequenceId(1); info.setMessageId(createMessageId("MessageId:3")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/MessageDispatchTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/MessageDispatchTest.java index 38fb0dc0a1..5de7938356 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/MessageDispatchTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/MessageDispatchTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessageDispatch * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class MessageDispatchTest extends BaseCommandTestSupport { public static MessageDispatchTest SINGLETON = new MessageDispatchTest(); public Object createObject() throws Exception { MessageDispatch info = new MessageDispatch(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessageDispatch info = (MessageDispatch) object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setMessage(createMessage("Message:3")); info.setRedeliveryCounter(1); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessageDispatch * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class MessageDispatchTest extends BaseCommandTestSupport { public static MessageDispatchTest SINGLETON = new MessageDispatchTest(); public Object createObject() throws Exception { MessageDispatch info = new MessageDispatch(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessageDispatch info = (MessageDispatch) object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setMessage(createMessage("Message:3")); info.setRedeliveryCounter(1); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/MessageIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/MessageIdTest.java index d64c66e1c0..346bb1e23d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/MessageIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/MessageIdTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessageId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class MessageIdTest extends DataFileGeneratorTestSupport { public static MessageIdTest SINGLETON = new MessageIdTest(); public Object createObject() throws Exception { MessageId info = new MessageId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessageId info = (MessageId) object; info.setProducerId(createProducerId("ProducerId:1")); info.setProducerSequenceId(1); info.setBrokerSequenceId(2); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessageId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class MessageIdTest extends DataFileGeneratorTestSupport { public static MessageIdTest SINGLETON = new MessageIdTest(); public Object createObject() throws Exception { MessageId info = new MessageId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessageId info = (MessageId) object; info.setProducerId(createProducerId("ProducerId:1")); info.setProducerSequenceId(1); info.setBrokerSequenceId(2); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/MessagePullTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/MessagePullTest.java index 55af8b1a3f..f48b7aa001 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/MessagePullTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/MessagePullTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessagePull * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class MessagePullTest extends BaseCommandTestSupport { public static MessagePullTest SINGLETON = new MessagePullTest(); public Object createObject() throws Exception { MessagePull info = new MessagePull(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessagePull info = (MessagePull) object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setTimeout(1); info.setCorrelationId("CorrelationId:3"); info.setMessageId(createMessageId("MessageId:4")); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for MessagePull * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class MessagePullTest extends BaseCommandTestSupport { public static MessagePullTest SINGLETON = new MessagePullTest(); public Object createObject() throws Exception { MessagePull info = new MessagePull(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); MessagePull info = (MessagePull) object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setTimeout(1); info.setCorrelationId("CorrelationId:3"); info.setMessageId(createMessageId("MessageId:4")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/MessageTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/MessageTestSupport.java index 3557528dee..0965fa8f52 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/MessageTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/MessageTestSupport.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for Message * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public abstract class MessageTestSupport extends BaseCommandTestSupport { protected void populateObject(Object object) throws Exception { super.populateObject(object); Message info = (Message) object; info.setProducerId(createProducerId("ProducerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setTransactionId(createTransactionId("TransactionId:3")); info.setOriginalDestination(createActiveMQDestination("OriginalDestination:4")); info.setMessageId(createMessageId("MessageId:5")); info.setOriginalTransactionId(createTransactionId("OriginalTransactionId:6")); info.setGroupID("GroupID:7"); info.setGroupSequence(1); info.setCorrelationId("CorrelationId:8"); info.setPersistent(true); info.setExpiration(1); info.setPriority((byte) 1); info.setReplyTo(createActiveMQDestination("ReplyTo:9")); info.setTimestamp(2); info.setType("Type:10"); { byte data[] = "Content:11".getBytes(); info.setContent(new org.apache.activemq.util.ByteSequence(data,0,data.length)); } { byte data[] = "MarshalledProperties:12".getBytes(); info.setMarshalledProperties(new org.apache.activemq.util.ByteSequence(data,0,data.length)); } info.setDataStructure(createDataStructure("DataStructure:13")); info.setTargetConsumerId(createConsumerId("TargetConsumerId:14")); info.setCompressed(false); info.setRedeliveryCounter(2); { BrokerId value[] = new BrokerId[2]; for( int i=0; i < 2; i++ ) { value[i] = createBrokerId("BrokerPath:15"); } info.setBrokerPath(value); } info.setArrival(3); info.setUserID("UserID:16"); info.setRecievedByDFBridge(true); info.setDroppable(false); { BrokerId value[] = new BrokerId[2]; for( int i=0; i < 2; i++ ) { value[i] = createBrokerId("Cluster:17"); } info.setCluster(value); } info.setBrokerInTime(4); info.setBrokerOutTime(5); } } \ No newline at end of file +/** * * 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.openwire.v9; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for Message * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public abstract class MessageTestSupport extends BaseCommandTestSupport { protected void populateObject(Object object) throws Exception { super.populateObject(object); Message info = (Message) object; info.setProducerId(createProducerId("ProducerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setTransactionId(createTransactionId("TransactionId:3")); info.setOriginalDestination(createActiveMQDestination("OriginalDestination:4")); info.setMessageId(createMessageId("MessageId:5")); info.setOriginalTransactionId(createTransactionId("OriginalTransactionId:6")); info.setGroupID("GroupID:7"); info.setGroupSequence(1); info.setCorrelationId("CorrelationId:8"); info.setPersistent(true); info.setExpiration(1); info.setPriority((byte) 1); info.setReplyTo(createActiveMQDestination("ReplyTo:9")); info.setTimestamp(2); info.setType("Type:10"); { byte data[] = "Content:11".getBytes(); info.setContent(new org.apache.activemq.util.ByteSequence(data, 0, data.length)); } { byte data[] = "MarshalledProperties:12".getBytes(); info.setMarshalledProperties(new org.apache.activemq.util.ByteSequence(data, 0, data.length)); } info.setDataStructure(createDataStructure("DataStructure:13")); info.setTargetConsumerId(createConsumerId("TargetConsumerId:14")); info.setCompressed(false); info.setRedeliveryCounter(2); { BrokerId value[] = new BrokerId[2]; for (int i = 0; i < 2; i++) { value[i] = createBrokerId("BrokerPath:15"); } info.setBrokerPath(value); } info.setArrival(3); info.setUserID("UserID:16"); info.setRecievedByDFBridge(true); info.setDroppable(false); { BrokerId value[] = new BrokerId[2]; for (int i = 0; i < 2; i++) { value[i] = createBrokerId("Cluster:17"); } info.setCluster(value); } info.setBrokerInTime(4); info.setBrokerOutTime(5); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/NetworkBridgeFilterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/NetworkBridgeFilterTest.java index 9b9c501109..fca4b63102 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/NetworkBridgeFilterTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/NetworkBridgeFilterTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for NetworkBridgeFilter * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class NetworkBridgeFilterTest extends DataFileGeneratorTestSupport { public static NetworkBridgeFilterTest SINGLETON = new NetworkBridgeFilterTest(); public Object createObject() throws Exception { NetworkBridgeFilter info = new NetworkBridgeFilter(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); NetworkBridgeFilter info = (NetworkBridgeFilter) object; info.setNetworkTTL(1); info.setNetworkBrokerId(createBrokerId("NetworkBrokerId:1")); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for NetworkBridgeFilter * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class NetworkBridgeFilterTest extends DataFileGeneratorTestSupport { public static NetworkBridgeFilterTest SINGLETON = new NetworkBridgeFilterTest(); public Object createObject() throws Exception { NetworkBridgeFilter info = new NetworkBridgeFilter(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); NetworkBridgeFilter info = (NetworkBridgeFilter) object; info.setNetworkTTL(1); info.setNetworkBrokerId(createBrokerId("NetworkBrokerId:1")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/PartialCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/PartialCommandTest.java index f79e06716a..327fe9f71d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/PartialCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/PartialCommandTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for PartialCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class PartialCommandTest extends DataFileGeneratorTestSupport { public static PartialCommandTest SINGLETON = new PartialCommandTest(); public Object createObject() throws Exception { PartialCommand info = new PartialCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); PartialCommand info = (PartialCommand) object; info.setCommandId(1); info.setData("Data:1".getBytes()); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for PartialCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class PartialCommandTest extends DataFileGeneratorTestSupport { public static PartialCommandTest SINGLETON = new PartialCommandTest(); public Object createObject() throws Exception { PartialCommand info = new PartialCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); PartialCommand info = (PartialCommand) object; info.setCommandId(1); info.setData("Data:1".getBytes()); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ProducerAckTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ProducerAckTest.java index 226a8f8fae..faa3bfe216 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ProducerAckTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ProducerAckTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ProducerAck * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ProducerAckTest extends BaseCommandTestSupport { public static ProducerAckTest SINGLETON = new ProducerAckTest(); public Object createObject() throws Exception { ProducerAck info = new ProducerAck(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ProducerAck info = (ProducerAck) object; info.setProducerId(createProducerId("ProducerId:1")); info.setSize(1); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ProducerAck * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ProducerAckTest extends BaseCommandTestSupport { public static ProducerAckTest SINGLETON = new ProducerAckTest(); public Object createObject() throws Exception { ProducerAck info = new ProducerAck(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ProducerAck info = (ProducerAck) object; info.setProducerId(createProducerId("ProducerId:1")); info.setSize(1); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ProducerIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ProducerIdTest.java index 72d7e35a24..07ce7e299f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ProducerIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ProducerIdTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ProducerId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ProducerIdTest extends DataFileGeneratorTestSupport { public static ProducerIdTest SINGLETON = new ProducerIdTest(); public Object createObject() throws Exception { ProducerId info = new ProducerId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ProducerId info = (ProducerId) object; info.setConnectionId("ConnectionId:1"); info.setValue(1); info.setSessionId(2); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ProducerId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ProducerIdTest extends DataFileGeneratorTestSupport { public static ProducerIdTest SINGLETON = new ProducerIdTest(); public Object createObject() throws Exception { ProducerId info = new ProducerId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ProducerId info = (ProducerId) object; info.setConnectionId("ConnectionId:1"); info.setValue(1); info.setSessionId(2); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ProducerInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ProducerInfoTest.java index 131c478075..b73851ee56 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ProducerInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ProducerInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ProducerInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ProducerInfoTest extends BaseCommandTestSupport { public static ProducerInfoTest SINGLETON = new ProducerInfoTest(); public Object createObject() throws Exception { ProducerInfo info = new ProducerInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ProducerInfo info = (ProducerInfo) object; info.setProducerId(createProducerId("ProducerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); { BrokerId value[] = new BrokerId[2]; for( int i=0; i < 2; i++ ) { value[i] = createBrokerId("BrokerPath:3"); } info.setBrokerPath(value); } info.setDispatchAsync(true); info.setWindowSize(1); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ProducerInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ProducerInfoTest extends BaseCommandTestSupport { public static ProducerInfoTest SINGLETON = new ProducerInfoTest(); public Object createObject() throws Exception { ProducerInfo info = new ProducerInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ProducerInfo info = (ProducerInfo) object; info.setProducerId(createProducerId("ProducerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); { BrokerId value[] = new BrokerId[2]; for (int i = 0; i < 2; i++) { value[i] = createBrokerId("BrokerPath:3"); } info.setBrokerPath(value); } info.setDispatchAsync(true); info.setWindowSize(1); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/RemoveInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/RemoveInfoTest.java index de9b5cd2b4..5add80f71e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/RemoveInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/RemoveInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for RemoveInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class RemoveInfoTest extends BaseCommandTestSupport { public static RemoveInfoTest SINGLETON = new RemoveInfoTest(); public Object createObject() throws Exception { RemoveInfo info = new RemoveInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); RemoveInfo info = (RemoveInfo) object; info.setObjectId(createDataStructure("ObjectId:1")); info.setLastDeliveredSequenceId(1); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for RemoveInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class RemoveInfoTest extends BaseCommandTestSupport { public static RemoveInfoTest SINGLETON = new RemoveInfoTest(); public Object createObject() throws Exception { RemoveInfo info = new RemoveInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); RemoveInfo info = (RemoveInfo) object; info.setObjectId(createDataStructure("ObjectId:1")); info.setLastDeliveredSequenceId(1); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/RemoveSubscriptionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/RemoveSubscriptionInfoTest.java index 9683e33f53..77b6a00186 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/RemoveSubscriptionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/RemoveSubscriptionInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for RemoveSubscriptionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class RemoveSubscriptionInfoTest extends BaseCommandTestSupport { public static RemoveSubscriptionInfoTest SINGLETON = new RemoveSubscriptionInfoTest(); public Object createObject() throws Exception { RemoveSubscriptionInfo info = new RemoveSubscriptionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); RemoveSubscriptionInfo info = (RemoveSubscriptionInfo) object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setSubcriptionName("SubcriptionName:2"); info.setClientId("ClientId:3"); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for RemoveSubscriptionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class RemoveSubscriptionInfoTest extends BaseCommandTestSupport { public static RemoveSubscriptionInfoTest SINGLETON = new RemoveSubscriptionInfoTest(); public Object createObject() throws Exception { RemoveSubscriptionInfo info = new RemoveSubscriptionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); RemoveSubscriptionInfo info = (RemoveSubscriptionInfo) object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setSubcriptionName("SubcriptionName:2"); info.setClientId("ClientId:3"); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ReplayCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ReplayCommandTest.java index 22ede48c93..63e358f3bf 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ReplayCommandTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ReplayCommandTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ReplayCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ReplayCommandTest extends BaseCommandTestSupport { public static ReplayCommandTest SINGLETON = new ReplayCommandTest(); public Object createObject() throws Exception { ReplayCommand info = new ReplayCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ReplayCommand info = (ReplayCommand) object; info.setFirstNakNumber(1); info.setLastNakNumber(2); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ReplayCommand * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ReplayCommandTest extends BaseCommandTestSupport { public static ReplayCommandTest SINGLETON = new ReplayCommandTest(); public Object createObject() throws Exception { ReplayCommand info = new ReplayCommand(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ReplayCommand info = (ReplayCommand) object; info.setFirstNakNumber(1); info.setLastNakNumber(2); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ResponseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ResponseTest.java index 97bb45c5d3..8c26e212e9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ResponseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ResponseTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for Response * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ResponseTest extends BaseCommandTestSupport { public static ResponseTest SINGLETON = new ResponseTest(); public Object createObject() throws Exception { Response info = new Response(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); Response info = (Response) object; info.setCorrelationId(1); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for Response * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ResponseTest extends BaseCommandTestSupport { public static ResponseTest SINGLETON = new ResponseTest(); public Object createObject() throws Exception { Response info = new Response(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); Response info = (Response) object; info.setCorrelationId(1); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/SessionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/SessionIdTest.java index 9d71dd57fe..7ee95b755e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/SessionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/SessionIdTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for SessionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class SessionIdTest extends DataFileGeneratorTestSupport { public static SessionIdTest SINGLETON = new SessionIdTest(); public Object createObject() throws Exception { SessionId info = new SessionId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); SessionId info = (SessionId) object; info.setConnectionId("ConnectionId:1"); info.setValue(1); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for SessionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class SessionIdTest extends DataFileGeneratorTestSupport { public static SessionIdTest SINGLETON = new SessionIdTest(); public Object createObject() throws Exception { SessionId info = new SessionId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); SessionId info = (SessionId) object; info.setConnectionId("ConnectionId:1"); info.setValue(1); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/SessionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/SessionInfoTest.java index 938296abf8..c7d7e3725c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/SessionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/SessionInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for SessionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class SessionInfoTest extends BaseCommandTestSupport { public static SessionInfoTest SINGLETON = new SessionInfoTest(); public Object createObject() throws Exception { SessionInfo info = new SessionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); SessionInfo info = (SessionInfo) object; info.setSessionId(createSessionId("SessionId:1")); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for SessionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class SessionInfoTest extends BaseCommandTestSupport { public static SessionInfoTest SINGLETON = new SessionInfoTest(); public Object createObject() throws Exception { SessionInfo info = new SessionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); SessionInfo info = (SessionInfo) object; info.setSessionId(createSessionId("SessionId:1")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ShutdownInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ShutdownInfoTest.java index be4b398e29..23a1a53470 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ShutdownInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/ShutdownInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ShutdownInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ShutdownInfoTest extends BaseCommandTestSupport { public static ShutdownInfoTest SINGLETON = new ShutdownInfoTest(); public Object createObject() throws Exception { ShutdownInfo info = new ShutdownInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ShutdownInfo info = (ShutdownInfo) object; } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for ShutdownInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class ShutdownInfoTest extends BaseCommandTestSupport { public static ShutdownInfoTest SINGLETON = new ShutdownInfoTest(); public Object createObject() throws Exception { ShutdownInfo info = new ShutdownInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); ShutdownInfo info = (ShutdownInfo) object; } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/SubscriptionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/SubscriptionInfoTest.java index 3366769010..e0240af6bf 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/SubscriptionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/SubscriptionInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for SubscriptionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class SubscriptionInfoTest extends DataFileGeneratorTestSupport { public static SubscriptionInfoTest SINGLETON = new SubscriptionInfoTest(); public Object createObject() throws Exception { SubscriptionInfo info = new SubscriptionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); SubscriptionInfo info = (SubscriptionInfo) object; info.setClientId("ClientId:1"); info.setDestination(createActiveMQDestination("Destination:2")); info.setSelector("Selector:3"); info.setSubcriptionName("SubcriptionName:4"); info.setSubscribedDestination(createActiveMQDestination("SubscribedDestination:5")); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for SubscriptionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class SubscriptionInfoTest extends DataFileGeneratorTestSupport { public static SubscriptionInfoTest SINGLETON = new SubscriptionInfoTest(); public Object createObject() throws Exception { SubscriptionInfo info = new SubscriptionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); SubscriptionInfo info = (SubscriptionInfo) object; info.setClientId("ClientId:1"); info.setDestination(createActiveMQDestination("Destination:2")); info.setSelector("Selector:3"); info.setSubcriptionName("SubcriptionName:4"); info.setSubscribedDestination(createActiveMQDestination("SubscribedDestination:5")); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/TransactionIdTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/TransactionIdTestSupport.java index 3f61dcece4..806a1a8871 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/TransactionIdTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/TransactionIdTestSupport.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for TransactionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public abstract class TransactionIdTestSupport extends DataFileGeneratorTestSupport { protected void populateObject(Object object) throws Exception { super.populateObject(object); TransactionId info = (TransactionId) object; } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for TransactionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public abstract class TransactionIdTestSupport extends DataFileGeneratorTestSupport { protected void populateObject(Object object) throws Exception { super.populateObject(object); TransactionId info = (TransactionId) object; } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/TransactionInfoTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/TransactionInfoTest.java index d08dd818f6..af1e466eae 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/TransactionInfoTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/TransactionInfoTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for TransactionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class TransactionInfoTest extends BaseCommandTestSupport { public static TransactionInfoTest SINGLETON = new TransactionInfoTest(); public Object createObject() throws Exception { TransactionInfo info = new TransactionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); TransactionInfo info = (TransactionInfo) object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setTransactionId(createTransactionId("TransactionId:2")); info.setType((byte) 1); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for TransactionInfo * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class TransactionInfoTest extends BaseCommandTestSupport { public static TransactionInfoTest SINGLETON = new TransactionInfoTest(); public Object createObject() throws Exception { TransactionInfo info = new TransactionInfo(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); TransactionInfo info = (TransactionInfo) object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setTransactionId(createTransactionId("TransactionId:2")); info.setType((byte) 1); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/XATransactionIdTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/XATransactionIdTest.java index f73711ea27..2464b6be5d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/XATransactionIdTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v9/XATransactionIdTest.java @@ -1 +1 @@ -/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for XATransactionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class XATransactionIdTest extends TransactionIdTestSupport { public static XATransactionIdTest SINGLETON = new XATransactionIdTest(); public Object createObject() throws Exception { XATransactionId info = new XATransactionId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); XATransactionId info = (XATransactionId) object; info.setFormatId(1); info.setGlobalTransactionId("GlobalTransactionId:1".getBytes()); info.setBranchQualifier("BranchQualifier:2".getBytes()); } } \ No newline at end of file +/** * * 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.openwire.v9; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for XATransactionId * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class XATransactionIdTest extends TransactionIdTestSupport { public static XATransactionIdTest SINGLETON = new XATransactionIdTest(); public Object createObject() throws Exception { XATransactionId info = new XATransactionId(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); XATransactionId info = (XATransactionId) object; info.setFormatId(1); info.setGlobalTransactionId("GlobalTransactionId:1".getBytes()); info.setBranchQualifier("BranchQualifier:2".getBytes()); } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/ConnectionChurnTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/ConnectionChurnTest.java index 2e2402d178..83a98c2cf9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/ConnectionChurnTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/ConnectionChurnTest.java @@ -36,70 +36,69 @@ import org.slf4j.LoggerFactory; * */ public class ConnectionChurnTest extends TestCase { - protected static final int CONNECTION_COUNT = 200; - private static final Logger LOG = LoggerFactory.getLogger(ConnectionChurnTest.class); - protected BrokerService broker; - protected String bindAddress = ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL+"?transport.closeAsync=false"; - protected int topicCount; - public void testPerformance() throws Exception { - ConnectionFactory factory = createConnectionFactory(); - List list = new ArrayList(); - for (int i = 0; i < CONNECTION_COUNT; i++) { - Connection connection = factory.createConnection(); - connection.start(); - list.add(connection); - LOG.info("Created " + i); - if (i % 100 == 0) { - closeConnections(list); - } - } - closeConnections(list); - } + protected static final int CONNECTION_COUNT = 200; + private static final Logger LOG = LoggerFactory.getLogger(ConnectionChurnTest.class); + protected BrokerService broker; + protected String bindAddress = ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL + "?transport.closeAsync=false"; + protected int topicCount; - protected void closeConnections(List list) throws JMSException { - for (Connection c : list) { - c.close(); - } - for (TransportConnector tc : broker.getTransportConnectors()) { - System.out.println(tc.getConnections().size()); - } - list.clear(); - } + public void testPerformance() throws Exception { + ConnectionFactory factory = createConnectionFactory(); + List list = new ArrayList(); + for (int i = 0; i < CONNECTION_COUNT; i++) { + Connection connection = factory.createConnection(); + connection.start(); + list.add(connection); + LOG.info("Created " + i); + if (i % 100 == 0) { + closeConnections(list); + } + } + closeConnections(list); + } - @Override - protected void setUp() throws Exception { - if (broker == null) { - broker = createBroker(); - } - super.setUp(); - } + protected void closeConnections(List list) throws JMSException { + for (Connection c : list) { + c.close(); + } + for (TransportConnector tc : broker.getTransportConnectors()) { + System.out.println(tc.getConnections().size()); + } + list.clear(); + } - @Override - protected void tearDown() throws Exception { - super.tearDown(); - if (broker != null) { - broker.stop(); - } - } + @Override + protected void setUp() throws Exception { + if (broker == null) { + broker = createBroker(); + } + super.setUp(); + } - protected ActiveMQConnectionFactory createConnectionFactory() - throws Exception { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory( - ActiveMQConnection.DEFAULT_BROKER_URL); - return cf; - } + @Override + protected void tearDown() throws Exception { + super.tearDown(); + if (broker != null) { + broker.stop(); + } + } - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - configureBroker(answer); - answer.start(); - return answer; - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL); + return cf; + } - protected void configureBroker(BrokerService answer) throws Exception { - answer.setPersistent(false); - answer.addConnector(bindAddress); - answer.setDeleteAllMessagesOnStartup(true); - } + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + configureBroker(answer); + answer.start(); + return answer; + } + + protected void configureBroker(BrokerService answer) throws Exception { + answer.setPersistent(false); + answer.addConnector(bindAddress); + answer.setDeleteAllMessagesOnStartup(true); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/InactiveDurableTopicTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/InactiveDurableTopicTest.java index 9ab45b99bd..748d5a9483 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/InactiveDurableTopicTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/InactiveDurableTopicTest.java @@ -37,30 +37,31 @@ import org.slf4j.LoggerFactory; * */ public class InactiveDurableTopicTest extends TestCase { - private static final transient Logger LOG = LoggerFactory.getLogger(InactiveDurableTopicTest.class); - private static final int MESSAGE_COUNT = 2000; - private static final String DEFAULT_PASSWORD = ""; - private static final String USERNAME = "testuser"; - private static final String CLIENTID = "mytestclient"; - private static final String TOPIC_NAME = "testevent"; - private static final String SUBID = "subscription1"; - private static final int DELIVERY_MODE = javax.jms.DeliveryMode.PERSISTENT; - private static final int DELIVERY_PRIORITY = javax.jms.Message.DEFAULT_PRIORITY; - private Connection connection; - private MessageProducer publisher; - private TopicSubscriber subscriber; - private Topic topic; - private Session session; - private ActiveMQConnectionFactory connectionFactory; - private BrokerService broker; + private static final transient Logger LOG = LoggerFactory.getLogger(InactiveDurableTopicTest.class); - @Override - protected void setUp() throws Exception { - super.setUp(); - broker = new BrokerService(); + private static final int MESSAGE_COUNT = 2000; + private static final String DEFAULT_PASSWORD = ""; + private static final String USERNAME = "testuser"; + private static final String CLIENTID = "mytestclient"; + private static final String TOPIC_NAME = "testevent"; + private static final String SUBID = "subscription1"; + private static final int DELIVERY_MODE = javax.jms.DeliveryMode.PERSISTENT; + private static final int DELIVERY_PRIORITY = javax.jms.Message.DEFAULT_PRIORITY; + private Connection connection; + private MessageProducer publisher; + private TopicSubscriber subscriber; + private Topic topic; + private Session session; + private ActiveMQConnectionFactory connectionFactory; + private BrokerService broker; - //broker.setPersistenceAdapter(new KahaPersistenceAdapter()); + @Override + protected void setUp() throws Exception { + super.setUp(); + broker = new BrokerService(); + + //broker.setPersistenceAdapter(new KahaPersistenceAdapter()); /* * JournalPersistenceAdapterFactory factory = new * JournalPersistenceAdapterFactory(); @@ -68,123 +69,129 @@ public class InactiveDurableTopicTest extends TestCase { * factory.setTaskRunnerFactory(broker.getTaskRunnerFactory()); * factory.setUseJournal(false); broker.setPersistenceFactory(factory); */ - broker.addConnector(ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL); - broker.start(); - connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_BROKER_URL); + broker.addConnector(ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL); + broker.start(); + connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_BROKER_URL); /* * Doesn't matter if you enable or disable these, so just leaving them * out for this test case connectionFactory.setAlwaysSessionAsync(true); * connectionFactory.setAsyncDispatch(true); */ - connectionFactory.setUseAsyncSend(true); - } + connectionFactory.setUseAsyncSend(true); + } - @Override - protected void tearDown() throws Exception { - super.tearDown(); - broker.stop(); - } + @Override + protected void tearDown() throws Exception { + super.tearDown(); + broker.stop(); + } - public void test1CreateSubscription() throws Exception { - try { + public void test1CreateSubscription() throws Exception { + try { /* * Step 1 - Establish a connection with a client id and create a * durable subscription */ - connection = connectionFactory.createConnection(USERNAME, DEFAULT_PASSWORD); - assertNotNull(connection); - connection.setClientID(CLIENTID); - connection.start(); - session = connection.createSession(false, javax.jms.Session.CLIENT_ACKNOWLEDGE); - assertNotNull(session); - topic = session.createTopic(TOPIC_NAME); - assertNotNull(topic); - subscriber = session.createDurableSubscriber(topic, SUBID, "", false); - assertNotNull(subscriber); - subscriber.close(); - session.close(); + connection = connectionFactory.createConnection(USERNAME, DEFAULT_PASSWORD); + assertNotNull(connection); + connection.setClientID(CLIENTID); + connection.start(); + session = connection.createSession(false, javax.jms.Session.CLIENT_ACKNOWLEDGE); + assertNotNull(session); + topic = session.createTopic(TOPIC_NAME); + assertNotNull(topic); + subscriber = session.createDurableSubscriber(topic, SUBID, "", false); + assertNotNull(subscriber); + subscriber.close(); + session.close(); + connection.close(); + } + catch (JMSException ex) { + try { connection.close(); - } catch (JMSException ex) { - try { - connection.close(); - } catch (Exception ignore) { - } - throw new AssertionFailedError("Create Subscription caught: " + ex); - } - } + } + catch (Exception ignore) { + } + throw new AssertionFailedError("Create Subscription caught: " + ex); + } + } - public void test2ProducerTestCase() { + public void test2ProducerTestCase() { /* * Step 2 - Establish a connection without a client id and create a * producer and start pumping messages. We will get hung */ - try { - connection = connectionFactory.createConnection(USERNAME, DEFAULT_PASSWORD); - assertNotNull(connection); - session = connection.createSession(false, javax.jms.Session.CLIENT_ACKNOWLEDGE); - assertNotNull(session); - topic = session.createTopic(TOPIC_NAME); - assertNotNull(topic); - publisher = session.createProducer(topic); - assertNotNull(publisher); - MapMessage msg = session.createMapMessage(); - assertNotNull(msg); - msg.setString("key1", "value1"); - int loop; - for (loop = 0; loop < MESSAGE_COUNT; loop++) { - msg.setInt("key2", loop); - publisher.send(msg, DELIVERY_MODE, DELIVERY_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); - if (loop % 5000 == 0) { - LOG.info("Sent " + loop + " messages"); - } + try { + connection = connectionFactory.createConnection(USERNAME, DEFAULT_PASSWORD); + assertNotNull(connection); + session = connection.createSession(false, javax.jms.Session.CLIENT_ACKNOWLEDGE); + assertNotNull(session); + topic = session.createTopic(TOPIC_NAME); + assertNotNull(topic); + publisher = session.createProducer(topic); + assertNotNull(publisher); + MapMessage msg = session.createMapMessage(); + assertNotNull(msg); + msg.setString("key1", "value1"); + int loop; + for (loop = 0; loop < MESSAGE_COUNT; loop++) { + msg.setInt("key2", loop); + publisher.send(msg, DELIVERY_MODE, DELIVERY_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); + if (loop % 5000 == 0) { + LOG.info("Sent " + loop + " messages"); } - assertEquals(loop, MESSAGE_COUNT); - publisher.close(); - session.close(); - connection.stop(); - connection.stop(); - } catch (JMSException ex) { - try { - connection.close(); - } catch (Exception ignore) { - } - throw new AssertionFailedError("Create Subscription caught: " + ex); - } - } + } + assertEquals(loop, MESSAGE_COUNT); + publisher.close(); + session.close(); + connection.stop(); + connection.stop(); + } + catch (JMSException ex) { + try { + connection.close(); + } + catch (Exception ignore) { + } + throw new AssertionFailedError("Create Subscription caught: " + ex); + } + } - public void test3CreateSubscription() throws Exception { - try { + public void test3CreateSubscription() throws Exception { + try { /* * Step 1 - Establish a connection with a client id and create a * durable subscription */ - connection = connectionFactory.createConnection(USERNAME, DEFAULT_PASSWORD); - assertNotNull(connection); - connection.setClientID(CLIENTID); - connection.start(); - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - assertNotNull(session); - topic = session.createTopic(TOPIC_NAME); - assertNotNull(topic); - subscriber = session.createDurableSubscriber(topic, SUBID, "", false); - assertNotNull(subscriber); - int loop; - for (loop = 0; loop < MESSAGE_COUNT; loop++) { - subscriber.receive(); - if (loop % 500 == 0) { - LOG.debug("Received " + loop + " messages"); - } + connection = connectionFactory.createConnection(USERNAME, DEFAULT_PASSWORD); + assertNotNull(connection); + connection.setClientID(CLIENTID); + connection.start(); + session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); + assertNotNull(session); + topic = session.createTopic(TOPIC_NAME); + assertNotNull(topic); + subscriber = session.createDurableSubscriber(topic, SUBID, "", false); + assertNotNull(subscriber); + int loop; + for (loop = 0; loop < MESSAGE_COUNT; loop++) { + subscriber.receive(); + if (loop % 500 == 0) { + LOG.debug("Received " + loop + " messages"); } - assertEquals(loop, MESSAGE_COUNT); - subscriber.close(); - session.close(); + } + assertEquals(loop, MESSAGE_COUNT); + subscriber.close(); + session.close(); + connection.close(); + } + catch (JMSException ex) { + try { connection.close(); - } catch (JMSException ex) { - try { - connection.close(); - } catch (Exception ignore) { - } - throw new AssertionFailedError("Create Subscription caught: " + ex); - } - } + } + catch (Exception ignore) { + } + throw new AssertionFailedError("Create Subscription caught: " + ex); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/InactiveQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/InactiveQueueTest.java index 866926233d..ec34a967ba 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/InactiveQueueTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/InactiveQueueTest.java @@ -34,30 +34,31 @@ import org.slf4j.LoggerFactory; * */ public class InactiveQueueTest extends TestCase { - private static final transient Logger LOG = LoggerFactory.getLogger(InactiveQueueTest.class); - private static final int MESSAGE_COUNT = 0; - private static final String DEFAULT_PASSWORD = ""; - private static final String USERNAME = "testuser"; - private static final String QUEUE_NAME = "testevent"; - private static final int DELIVERY_MODE = javax.jms.DeliveryMode.PERSISTENT; - private static final int DELIVERY_PRIORITY = javax.jms.Message.DEFAULT_PRIORITY; + private static final transient Logger LOG = LoggerFactory.getLogger(InactiveQueueTest.class); - ActiveMQConnectionFactory connectionFactory; - BrokerService broker; + private static final int MESSAGE_COUNT = 0; + private static final String DEFAULT_PASSWORD = ""; + private static final String USERNAME = "testuser"; + private static final String QUEUE_NAME = "testevent"; + private static final int DELIVERY_MODE = javax.jms.DeliveryMode.PERSISTENT; + private static final int DELIVERY_PRIORITY = javax.jms.Message.DEFAULT_PRIORITY; - private Connection connection; - private MessageProducer publisher; - private Destination destination; - private Session session; + ActiveMQConnectionFactory connectionFactory; + BrokerService broker; - @Override - protected void setUp() throws Exception { - super.setUp(); - broker = new BrokerService(); + private Connection connection; + private MessageProducer publisher; + private Destination destination; + private Session session; - // broker.setPersistenceAdapter(new KahaPersistenceAdapter(new File - // ("TEST_STUFD"))); + @Override + protected void setUp() throws Exception { + super.setUp(); + broker = new BrokerService(); + + // broker.setPersistenceAdapter(new KahaPersistenceAdapter(new File + // ("TEST_STUFD"))); /* * JournalPersistenceAdapterFactory factory = new * JournalPersistenceAdapterFactory(); @@ -65,50 +66,50 @@ public class InactiveQueueTest extends TestCase { * factory.setTaskRunnerFactory(broker.getTaskRunnerFactory()); * factory.setUseJournal(false); broker.setPersistenceFactory(factory); */ - broker.addConnector(ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL); - broker.start(); - connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_BROKER_URL); + broker.addConnector(ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL); + broker.start(); + connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_BROKER_URL); /* * Doesn't matter if you enable or disable these, so just leaving them * out for this test case connectionFactory.setAlwaysSessionAsync(true); * connectionFactory.setAsyncDispatch(true); */ - connectionFactory.setUseAsyncSend(true); - } + connectionFactory.setUseAsyncSend(true); + } - @Override - protected void tearDown() throws Exception { - super.tearDown(); - broker.stop(); - } + @Override + protected void tearDown() throws Exception { + super.tearDown(); + broker.stop(); + } - public void testNoSubscribers() throws Exception { - connection = connectionFactory.createConnection(USERNAME, DEFAULT_PASSWORD); - assertNotNull(connection); - connection.start(); - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - assertNotNull(session); - destination = session.createQueue(QUEUE_NAME); - assertNotNull(destination); - publisher = session.createProducer(destination); - assertNotNull(publisher); - MapMessage msg = session.createMapMessage(); - assertNotNull(msg); - msg.setString("key1", "value1"); - int loop; - for (loop = 0; loop < MESSAGE_COUNT; loop++) { - msg.setInt("key2", loop); - publisher.send(msg, DELIVERY_MODE, DELIVERY_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); - if (loop % 500 == 0) { - LOG.debug("Sent " + loop + " messages"); - } - } - Thread.sleep(1000000); - assertEquals(loop, MESSAGE_COUNT); - publisher.close(); - session.close(); - connection.stop(); - connection.stop(); - } + public void testNoSubscribers() throws Exception { + connection = connectionFactory.createConnection(USERNAME, DEFAULT_PASSWORD); + assertNotNull(connection); + connection.start(); + session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); + assertNotNull(session); + destination = session.createQueue(QUEUE_NAME); + assertNotNull(destination); + publisher = session.createProducer(destination); + assertNotNull(publisher); + MapMessage msg = session.createMapMessage(); + assertNotNull(msg); + msg.setString("key1", "value1"); + int loop; + for (loop = 0; loop < MESSAGE_COUNT; loop++) { + msg.setInt("key2", loop); + publisher.send(msg, DELIVERY_MODE, DELIVERY_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); + if (loop % 500 == 0) { + LOG.debug("Sent " + loop + " messages"); + } + } + Thread.sleep(1000000); + assertEquals(loop, MESSAGE_COUNT); + publisher.close(); + session.close(); + connection.stop(); + connection.stop(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaDBDurableTopicTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaDBDurableTopicTest.java index 3609c62879..0d9f002802 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaDBDurableTopicTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaDBDurableTopicTest.java @@ -20,33 +20,33 @@ import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; /** - * + * */ public class KahaDBDurableTopicTest extends SimpleDurableTopicTest { - @Override - protected void setUp() throws Exception { - //this.initialConsumerDelay = 10 * 1000; - super.setUp(); - } - - @Override - protected ActiveMQConnectionFactory createConnectionFactory(String uri) throws Exception { - ActiveMQConnectionFactory result = new ActiveMQConnectionFactory(uri); - //result.setDispatchAsync(false); - return result; - } - - @Override - protected void configureBroker(BrokerService answer,String uri) throws Exception { - //AMQPersistenceAdapterFactory persistenceFactory = new AMQPersistenceAdapterFactory(); - //persistenceFactory.setMaxFileLength(1024*16); - //persistenceFactory.setPersistentIndex(true); - //persistenceFactory.setCleanupInterval(10000); - //answer.setPersistenceFactory(persistenceFactory); - answer.setDeleteAllMessagesOnStartup(true); - answer.addConnector(uri); - answer.setUseShutdownHook(false); - answer.setEnableStatistics(false); - } + @Override + protected void setUp() throws Exception { + //this.initialConsumerDelay = 10 * 1000; + super.setUp(); + } + + @Override + protected ActiveMQConnectionFactory createConnectionFactory(String uri) throws Exception { + ActiveMQConnectionFactory result = new ActiveMQConnectionFactory(uri); + //result.setDispatchAsync(false); + return result; + } + + @Override + protected void configureBroker(BrokerService answer, String uri) throws Exception { + //AMQPersistenceAdapterFactory persistenceFactory = new AMQPersistenceAdapterFactory(); + //persistenceFactory.setMaxFileLength(1024*16); + //persistenceFactory.setPersistentIndex(true); + //persistenceFactory.setCleanupInterval(10000); + //answer.setPersistenceFactory(persistenceFactory); + answer.setDeleteAllMessagesOnStartup(true); + answer.addConnector(uri); + answer.setUseShutdownHook(false); + answer.setEnableStatistics(false); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaDBDurableTransactedTopicTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaDBDurableTransactedTopicTest.java index d1ed9cffd4..b1453c0c03 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaDBDurableTransactedTopicTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaDBDurableTransactedTopicTest.java @@ -22,21 +22,24 @@ import javax.jms.Destination; import javax.jms.JMSException; /** - * + * */ public class KahaDBDurableTransactedTopicTest extends KahaDBDurableTopicTest { - @Override - protected void setUp() throws Exception { - //this.initialConsumerDelay = 10 * 1000; - super.setUp(); - } - @Override - protected PerfProducer createProducer(ConnectionFactory fac, Destination dest, int number, byte[] payload) throws JMSException { - PerfProducer result= new PerfProducer(fac, dest, payload, true); - result.setDeliveryMode(DeliveryMode.PERSISTENT); - return result; - } + @Override + protected void setUp() throws Exception { + //this.initialConsumerDelay = 10 * 1000; + super.setUp(); + } + + @Override + protected PerfProducer createProducer(ConnectionFactory fac, + Destination dest, + int number, + byte[] payload) throws JMSException { + PerfProducer result = new PerfProducer(fac, dest, payload, true); + result.setDeliveryMode(DeliveryMode.PERSISTENT); + return result; + } - } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaDBQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaDBQueueTest.java index a11b92e3c0..b03e284450 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaDBQueueTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaDBQueueTest.java @@ -17,47 +17,49 @@ package org.apache.activemq.perf; import java.io.File; + import org.apache.activemq.broker.BrokerService; import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; /** - * + * */ public class KahaDBQueueTest extends SimpleQueueTest { - @Override - protected void setUp() throws Exception { - this.numberOfDestinations = 25; - this.numberofProducers = 1; - super.setUp(); - } - @Override - protected void configureBroker(BrokerService answer,String uri) throws Exception { + @Override + protected void setUp() throws Exception { + this.numberOfDestinations = 25; + this.numberofProducers = 1; + super.setUp(); + } - File dataFileDir = new File("target/test-amq-data/perfTest/kahadb"); - File archiveDir = new File(dataFileDir,"archive"); - KahaDBPersistenceAdapter kaha = new KahaDBPersistenceAdapter(); - kaha.setDirectory(dataFileDir); - kaha.setDirectoryArchive(archiveDir); - kaha.setArchiveDataLogs(false); + @Override + protected void configureBroker(BrokerService answer, String uri) throws Exception { - // The setEnableJournalDiskSyncs(false) setting is a little dangerous right now, as I have not verified - // what happens if the index is updated but a journal update is lost. - // Index is going to be in consistent, but can it be repaired? - kaha.setEnableJournalDiskSyncs(true); - // Using a bigger journal file size makes he take fewer spikes as it is not switching files as often. - //kaha.setJournalMaxFileLength(1024*1024*100); - - // small batch means more frequent and smaller writes - //kaha.setIndexWriteBatchSize(100); - // do the index write in a separate thread - kaha.setEnableIndexWriteAsync(true); - kaha.setIndexCacheSize(10000); - - answer.setPersistenceAdapter(kaha); - answer.addConnector(uri); - answer.setDeleteAllMessagesOnStartup(true); + File dataFileDir = new File("target/test-amq-data/perfTest/kahadb"); + File archiveDir = new File(dataFileDir, "archive"); + KahaDBPersistenceAdapter kaha = new KahaDBPersistenceAdapter(); + kaha.setDirectory(dataFileDir); + kaha.setDirectoryArchive(archiveDir); + kaha.setArchiveDataLogs(false); - } + // The setEnableJournalDiskSyncs(false) setting is a little dangerous right now, as I have not verified + // what happens if the index is updated but a journal update is lost. + // Index is going to be in consistent, but can it be repaired? + kaha.setEnableJournalDiskSyncs(true); + // Using a bigger journal file size makes he take fewer spikes as it is not switching files as often. + //kaha.setJournalMaxFileLength(1024*1024*100); + + // small batch means more frequent and smaller writes + //kaha.setIndexWriteBatchSize(100); + // do the index write in a separate thread + kaha.setEnableIndexWriteAsync(true); + kaha.setIndexCacheSize(10000); + + answer.setPersistenceAdapter(kaha); + answer.addConnector(uri); + answer.setDeleteAllMessagesOnStartup(true); + + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaQueueTest.java index e448c414a3..e049233c1c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaQueueTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaQueueTest.java @@ -20,18 +20,20 @@ import org.apache.activemq.broker.BrokerService; import org.apache.activemq.xbean.BrokerFactoryBean; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; + /** - * + * */ public class KahaQueueTest extends SimpleQueueTest { - final static String config = "org/apache/activemq/perf/kahadbBroker.xml"; - protected BrokerService createBroker(String uri) throws Exception { - Resource resource = new ClassPathResource(config); - BrokerFactoryBean brokerFactory = new BrokerFactoryBean(resource); - resource = new ClassPathResource(config); - brokerFactory = new BrokerFactoryBean(resource); - brokerFactory.afterPropertiesSet(); - return brokerFactory.getBroker(); - } + final static String config = "org/apache/activemq/perf/kahadbBroker.xml"; + + protected BrokerService createBroker(String uri) throws Exception { + Resource resource = new ClassPathResource(config); + BrokerFactoryBean brokerFactory = new BrokerFactoryBean(resource); + resource = new ClassPathResource(config); + brokerFactory = new BrokerFactoryBean(resource); + brokerFactory.afterPropertiesSet(); + return brokerFactory.getBroker(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/LevelDBDurableTopicTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/LevelDBDurableTopicTest.java index 7fd1c12f4c..48d217c79a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/LevelDBDurableTopicTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/LevelDBDurableTopicTest.java @@ -1,5 +1,5 @@ /** -revision 946600 * Licensed to the Apache Software Foundation (ASF) under one or more + revision 946600 * 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 @@ -20,7 +20,7 @@ import org.apache.activemq.broker.BrokerService; import org.apache.activemq.leveldb.LevelDBStore; /** - * + * */ public class LevelDBDurableTopicTest extends SimpleDurableTopicTest { @@ -32,13 +32,13 @@ public class LevelDBDurableTopicTest extends SimpleDurableTopicTest { * result=factory.getBroker(); result.start(); return result; } */ - @Override - protected void configureBroker(BrokerService answer,String uri) throws Exception { - LevelDBStore store = new LevelDBStore(); - answer.setPersistenceAdapter(store); - answer.setDeleteAllMessagesOnStartup(true); - answer.addConnector(uri); - - } + @Override + protected void configureBroker(BrokerService answer, String uri) throws Exception { + LevelDBStore store = new LevelDBStore(); + answer.setPersistenceAdapter(store); + answer.setDeleteAllMessagesOnStartup(true); + answer.addConnector(uri); + + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/LevelDBStoreQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/LevelDBStoreQueueTest.java index 169c32ea03..157859f339 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/LevelDBStoreQueueTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/LevelDBStoreQueueTest.java @@ -22,21 +22,21 @@ import org.apache.activemq.broker.BrokerService; import org.apache.activemq.leveldb.LevelDBStore; /** - * + * */ public class LevelDBStoreQueueTest extends SimpleQueueTest { - protected void configureBroker(BrokerService answer,String uri) throws Exception { + protected void configureBroker(BrokerService answer, String uri) throws Exception { - File dataFileDir = new File("target/test-amq-data/perfTest/amq"); + File dataFileDir = new File("target/test-amq-data/perfTest/amq"); - LevelDBStore adaptor = new LevelDBStore(); - adaptor.setDirectory(dataFileDir); + LevelDBStore adaptor = new LevelDBStore(); + adaptor.setDirectory(dataFileDir); - answer.setPersistenceAdapter(adaptor); - answer.addConnector(uri); - answer.setDeleteAllMessagesOnStartup(true); + answer.setPersistenceAdapter(adaptor); + answer.addConnector(uri); + answer.setDeleteAllMessagesOnStartup(true); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/MemoryAllocationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/MemoryAllocationTest.java index a6b4380792..37be517e4d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/MemoryAllocationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/MemoryAllocationTest.java @@ -38,80 +38,81 @@ import org.slf4j.LoggerFactory; */ public class MemoryAllocationTest extends TestCase { - protected static final int MESSAGE_COUNT = 2000; - private static final Logger LOG = LoggerFactory.getLogger(MemoryAllocationTest.class); + protected static final int MESSAGE_COUNT = 2000; + private static final Logger LOG = LoggerFactory.getLogger(MemoryAllocationTest.class); - protected BrokerService broker; - protected String bindAddress = "vm://localhost"; - protected int topicCount; + protected BrokerService broker; + protected String bindAddress = "vm://localhost"; + protected int topicCount; - public void testPerformance() throws Exception { - ConnectionFactory factory = createConnectionFactory(); - Connection connection = factory.createConnection(); - for (int i = 0; i < MESSAGE_COUNT; i++) { + public void testPerformance() throws Exception { + ConnectionFactory factory = createConnectionFactory(); + Connection connection = factory.createConnection(); + for (int i = 0; i < MESSAGE_COUNT; i++) { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination dest = session.createTemporaryTopic(); - session.createConsumer(dest); - MessageProducer mp = session.createProducer(dest); - Message msg = session.createTextMessage("test" + i); - mp.send(msg); - session.close(); - releaseDestination(dest); - if (i % 500 == 0) { - LOG.info("Iterator " + i); - } - } - connection.close(); - } + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination dest = session.createTemporaryTopic(); + session.createConsumer(dest); + MessageProducer mp = session.createProducer(dest); + Message msg = session.createTextMessage("test" + i); + mp.send(msg); + session.close(); + releaseDestination(dest); + if (i % 500 == 0) { + LOG.info("Iterator " + i); + } + } + connection.close(); + } - protected Destination getDestination(Session session) throws JMSException { - String topicName = getClass().getName() + "." + topicCount++; - return session.createTopic(topicName); - } + protected Destination getDestination(Session session) throws JMSException { + String topicName = getClass().getName() + "." + topicCount++; + return session.createTopic(topicName); + } - protected void releaseDestination(Destination dest) throws JMSException { - if (dest instanceof TemporaryTopic) { - TemporaryTopic tt = (TemporaryTopic)dest; - tt.delete(); - } else if (dest instanceof TemporaryQueue) { - TemporaryQueue tq = (TemporaryQueue)dest; - tq.delete(); - } - } + protected void releaseDestination(Destination dest) throws JMSException { + if (dest instanceof TemporaryTopic) { + TemporaryTopic tt = (TemporaryTopic) dest; + tt.delete(); + } + else if (dest instanceof TemporaryQueue) { + TemporaryQueue tq = (TemporaryQueue) dest; + tq.delete(); + } + } - @Override - protected void setUp() throws Exception { - if (broker == null) { - broker = createBroker(); - } - super.setUp(); - } + @Override + protected void setUp() throws Exception { + if (broker == null) { + broker = createBroker(); + } + super.setUp(); + } - @Override - protected void tearDown() throws Exception { - super.tearDown(); + @Override + protected void tearDown() throws Exception { + super.tearDown(); - if (broker != null) { - broker.stop(); - } - } + if (broker != null) { + broker.stop(); + } + } - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(bindAddress); - return cf; - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(bindAddress); + return cf; + } - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - configureBroker(answer); - answer.start(); - return answer; - } + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + configureBroker(answer); + answer.start(); + return answer; + } - protected void configureBroker(BrokerService answer) throws Exception { - answer.setPersistent(false); - answer.addConnector(bindAddress); - answer.setDeleteAllMessagesOnStartup(true); - } + protected void configureBroker(BrokerService answer) throws Exception { + answer.setPersistent(false); + answer.addConnector(bindAddress); + answer.setDeleteAllMessagesOnStartup(true); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/NetworkedSyncTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/NetworkedSyncTest.java index 4a3b20de1b..4cff30caae 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/NetworkedSyncTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/NetworkedSyncTest.java @@ -27,6 +27,7 @@ import javax.jms.TextMessage; import javax.jms.Topic; import junit.framework.TestCase; + import junit.textui.TestRunner; import org.apache.activemq.ActiveMQConnectionFactory; @@ -38,209 +39,210 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ClassPathResource; - public class NetworkedSyncTest extends TestCase { - // constants - public static final int MESSAGE_COUNT = 10000; //100000; - public final static String config = "org/apache/activemq/perf/networkSync.xml"; - public final static String broker1URL = "tcp://localhost:61616"; - public final static String broker2URL = "tcp://localhost:62616"; - private final String networkConnectorURL = "static://(" + broker2URL + ")"; - private static final Logger LOG = LoggerFactory.getLogger(NetworkedSyncTest.class); - BrokerService broker1 = null; - BrokerService broker2 = null; - NetworkConnector connector = null; + // constants + public static final int MESSAGE_COUNT = 10000; //100000; + public final static String config = "org/apache/activemq/perf/networkSync.xml"; + public final static String broker1URL = "tcp://localhost:61616"; + public final static String broker2URL = "tcp://localhost:62616"; + private final String networkConnectorURL = "static://(" + broker2URL + ")"; + private static final Logger LOG = LoggerFactory.getLogger(NetworkedSyncTest.class); + BrokerService broker1 = null; + BrokerService broker2 = null; + NetworkConnector connector = null; - /** - * @param name - */ - public NetworkedSyncTest(String name) { - super(name); - LOG.info("Testcase started."); - } - - public static void main(String args[]) { - TestRunner.run(NetworkedSyncTest.class); + /** + * @param name + */ + public NetworkedSyncTest(String name) { + super(name); + LOG.info("Testcase started."); } - /** - * @throws java.lang.Exception - */ - @Override - protected void setUp() throws Exception { - LOG.info("setUp() called."); - ClassPathXmlApplicationContext context1 = null; - BrokerFactoryBean brokerFactory = new BrokerFactoryBean(new ClassPathResource(config)); - assertNotNull(brokerFactory); + public static void main(String args[]) { + TestRunner.run(NetworkedSyncTest.class); + } + + /** + * @throws java.lang.Exception + */ + @Override + protected void setUp() throws Exception { + LOG.info("setUp() called."); + ClassPathXmlApplicationContext context1 = null; + BrokerFactoryBean brokerFactory = new BrokerFactoryBean(new ClassPathResource(config)); + assertNotNull(brokerFactory); /* start up first broker instance */ - try { - // resolve broker1 - Thread.currentThread().setContextClassLoader( - NetworkedSyncTest.class.getClassLoader()); - context1 = new ClassPathXmlApplicationContext(config); - broker1 = (BrokerService) context1.getBean("broker1"); + try { + // resolve broker1 + Thread.currentThread().setContextClassLoader(NetworkedSyncTest.class.getClassLoader()); + context1 = new ClassPathXmlApplicationContext(config); + broker1 = (BrokerService) context1.getBean("broker1"); - // start the broker - if (!broker1.isStarted()) { - LOG.info("Broker broker1 not yet started. Kicking it off now."); - broker1.start(); - } else { - LOG.info("Broker broker1 already started. Not kicking it off a second time."); - broker1.waitUntilStopped(); - } - } catch (Exception e) { - LOG.error("Error: " + e.getMessage()); - throw e; - // brokerService.stop(); - } + // start the broker + if (!broker1.isStarted()) { + LOG.info("Broker broker1 not yet started. Kicking it off now."); + broker1.start(); + } + else { + LOG.info("Broker broker1 already started. Not kicking it off a second time."); + broker1.waitUntilStopped(); + } + } + catch (Exception e) { + LOG.error("Error: " + e.getMessage()); + throw e; + // brokerService.stop(); + } /* start up second broker instance */ - try { - Thread.currentThread().setContextClassLoader( - NetworkedSyncTest.class.getClassLoader()); - context1 = new ClassPathXmlApplicationContext(config); - broker2 = (BrokerService) context1.getBean("broker2"); + try { + Thread.currentThread().setContextClassLoader(NetworkedSyncTest.class.getClassLoader()); + context1 = new ClassPathXmlApplicationContext(config); + broker2 = (BrokerService) context1.getBean("broker2"); - // start the broker - if (!broker2.isStarted()) { - LOG.info("Broker broker2 not yet started. Kicking it off now."); - broker2.start(); - } else { - LOG.info("Broker broker2 already started. Not kicking it off a second time."); - broker2.waitUntilStopped(); - } - } catch (Exception e) { - LOG.error("Error: " + e.getMessage()); - throw e; - } + // start the broker + if (!broker2.isStarted()) { + LOG.info("Broker broker2 not yet started. Kicking it off now."); + broker2.start(); + } + else { + LOG.info("Broker broker2 already started. Not kicking it off a second time."); + broker2.waitUntilStopped(); + } + } + catch (Exception e) { + LOG.error("Error: " + e.getMessage()); + throw e; + } - // setup network connector from broker1 to broker2 - connector = broker1.addNetworkConnector(networkConnectorURL); - connector.setBrokerName(broker1.getBrokerName()); - connector.setDuplex(true); - connector.start(); - LOG.info("Network connector created."); - } + // setup network connector from broker1 to broker2 + connector = broker1.addNetworkConnector(networkConnectorURL); + connector.setBrokerName(broker1.getBrokerName()); + connector.setDuplex(true); + connector.start(); + LOG.info("Network connector created."); + } - /** - * @throws java.lang.Exception - */ - @Override - protected void tearDown() throws Exception { + /** + * @throws java.lang.Exception + */ + @Override + protected void tearDown() throws Exception { - LOG.info("tearDown() called."); + LOG.info("tearDown() called."); - if (broker1 != null && broker1.isStarted()) { - LOG.info("Broker1 still running, stopping it now."); - broker1.stop(); - } else { - LOG.info("Broker1 not running, nothing to shutdown."); - } - if (broker2 != null && broker2.isStarted()) { - LOG.info("Broker2 still running, stopping it now."); - broker2.stop(); - } else { - LOG.info("Broker2 not running, nothing to shutdown."); - } + if (broker1 != null && broker1.isStarted()) { + LOG.info("Broker1 still running, stopping it now."); + broker1.stop(); + } + else { + LOG.info("Broker1 not running, nothing to shutdown."); + } + if (broker2 != null && broker2.isStarted()) { + LOG.info("Broker2 still running, stopping it now."); + broker2.stop(); + } + else { + LOG.info("Broker2 not running, nothing to shutdown."); + } - } + } - public void testMessageExchange() throws Exception { - LOG.info("testMessageExchange() called."); + public void testMessageExchange() throws Exception { + LOG.info("testMessageExchange() called."); - long start = System.currentTimeMillis(); + long start = System.currentTimeMillis(); - // create producer and consumer threads - Thread producer = new Thread(new Producer()); - Thread consumer = new Thread(new Consumer()); - // start threads - consumer.start(); - Thread.sleep(2000); - producer.start(); + // create producer and consumer threads + Thread producer = new Thread(new Producer()); + Thread consumer = new Thread(new Consumer()); + // start threads + consumer.start(); + Thread.sleep(2000); + producer.start(); + // wait for threads to finish + producer.join(); + consumer.join(); + long end = System.currentTimeMillis(); - // wait for threads to finish - producer.join(); - consumer.join(); - long end = System.currentTimeMillis(); - - System.out.println("Duration: "+(end-start)); - } + System.out.println("Duration: " + (end - start)); + } } /** * Message producer running as a separate thread, connecting to broker1 * * @author tmielke - * */ class Producer implements Runnable { - private static final Logger LOG = LoggerFactory.getLogger(Producer.class); + private static final Logger LOG = LoggerFactory.getLogger(Producer.class); - /** - * connect to broker and constantly send messages - */ - @Override - public void run() { + /** + * connect to broker and constantly send messages + */ + @Override + public void run() { - Connection connection = null; - Session session = null; - MessageProducer producer = null; + Connection connection = null; + Session session = null; + MessageProducer producer = null; - try { - ActiveMQConnectionFactory amq = new ActiveMQConnectionFactory( - NetworkedSyncTest.broker1URL); - connection = amq.createConnection(); - - connection.setExceptionListener(new javax.jms.ExceptionListener() { - @Override - public void onException(javax.jms.JMSException e) { - e.printStackTrace(); - } - }); - - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Topic destination = session.createTopic("TEST.FOO"); - - producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - - long counter = 0; - - // Create and send message - for (int i = 0; i < NetworkedSyncTest.MESSAGE_COUNT; i++) { - - String text = "Hello world! From: " - + Thread.currentThread().getName() + " : " - + this.hashCode() + ":" + counter; - TextMessage message = session.createTextMessage(text); - producer.send(message); - counter++; - - if ((counter % 1000) == 0) - LOG.info("sent " + counter + " messages"); + try { + ActiveMQConnectionFactory amq = new ActiveMQConnectionFactory(NetworkedSyncTest.broker1URL); + connection = amq.createConnection(); + connection.setExceptionListener(new javax.jms.ExceptionListener() { + @Override + public void onException(javax.jms.JMSException e) { + e.printStackTrace(); } - } catch (Exception ex) { - LOG.error(ex.toString()); - return; - } finally { - try { - if (producer != null) - producer.close(); - if (session != null) - session.close(); - if (connection != null) - connection.close(); - } catch (Exception e) { - LOG.error("Problem closing down JMS objects: " + e); - } - } - } + }); + + connection.start(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Topic destination = session.createTopic("TEST.FOO"); + + producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + + long counter = 0; + + // Create and send message + for (int i = 0; i < NetworkedSyncTest.MESSAGE_COUNT; i++) { + + String text = "Hello world! From: " + Thread.currentThread().getName() + " : " + this.hashCode() + ":" + counter; + TextMessage message = session.createTextMessage(text); + producer.send(message); + counter++; + + if ((counter % 1000) == 0) + LOG.info("sent " + counter + " messages"); + + } + } + catch (Exception ex) { + LOG.error(ex.toString()); + return; + } + finally { + try { + if (producer != null) + producer.close(); + if (session != null) + session.close(); + if (connection != null) + connection.close(); + } + catch (Exception e) { + LOG.error("Problem closing down JMS objects: " + e); + } + } + } } /* @@ -250,68 +252,70 @@ class Producer implements Runnable { */ class Consumer implements Runnable { - private static final Logger LOG = LoggerFactory.getLogger(Consumer.class);; + private static final Logger LOG = LoggerFactory.getLogger(Consumer.class); + ; + /** + * connect to broker and receive messages + */ + @Override + public void run() { + Connection connection = null; + Session session = null; + MessageConsumer consumer = null; - /** - * connect to broker and receive messages - */ - @Override - public void run() { - Connection connection = null; - Session session = null; - MessageConsumer consumer = null; - - try { - ActiveMQConnectionFactory amq = new ActiveMQConnectionFactory( - NetworkedSyncTest.broker2URL); - connection = amq.createConnection(); - // need to set clientID when using durable subscription. - connection.setClientID("tmielke"); - - connection.setExceptionListener(new javax.jms.ExceptionListener() { - @Override - public void onException(javax.jms.JMSException e) { - e.printStackTrace(); - } - }); - - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createTopic("TEST.FOO"); - consumer = session.createDurableSubscriber((Topic) destination,"tmielke"); - - long counter = 0; - // Wait for a message - for (int i = 0; i < NetworkedSyncTest.MESSAGE_COUNT; i++) { - Message message2 = consumer.receive(); - if (message2 instanceof TextMessage) { - TextMessage textMessage = (TextMessage) message2; - textMessage.getText(); - // logger.info("Received: " + text); - } else { - LOG.error("Received message of unsupported type. Expecting TextMessage. "+ message2); - } - counter++; - if ((counter % 1000) == 0) - LOG.info("received " + counter + " messages"); - + try { + ActiveMQConnectionFactory amq = new ActiveMQConnectionFactory(NetworkedSyncTest.broker2URL); + connection = amq.createConnection(); + // need to set clientID when using durable subscription. + connection.setClientID("tmielke"); + connection.setExceptionListener(new javax.jms.ExceptionListener() { + @Override + public void onException(javax.jms.JMSException e) { + e.printStackTrace(); } - } catch (Exception e) { - LOG.error("Error in Consumer: " + e); - return; - } finally { - try { - if (consumer != null) - consumer.close(); - if (session != null) - session.close(); - if (connection != null) - connection.close(); - } catch (Exception ex) { - LOG.error("Error closing down JMS objects: " + ex); + }); + + connection.start(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createTopic("TEST.FOO"); + consumer = session.createDurableSubscriber((Topic) destination, "tmielke"); + + long counter = 0; + // Wait for a message + for (int i = 0; i < NetworkedSyncTest.MESSAGE_COUNT; i++) { + Message message2 = consumer.receive(); + if (message2 instanceof TextMessage) { + TextMessage textMessage = (TextMessage) message2; + textMessage.getText(); + // logger.info("Received: " + text); } - } - } + else { + LOG.error("Received message of unsupported type. Expecting TextMessage. " + message2); + } + counter++; + if ((counter % 1000) == 0) + LOG.info("received " + counter + " messages"); + + } + } + catch (Exception e) { + LOG.error("Error in Consumer: " + e); + return; + } + finally { + try { + if (consumer != null) + consumer.close(); + if (session != null) + session.close(); + if (connection != null) + connection.close(); + } + catch (Exception ex) { + LOG.error("Error closing down JMS objects: " + ex); + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/NumberOfDestinationsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/NumberOfDestinationsTest.java index f25c0a5923..165b8bfa9d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/NumberOfDestinationsTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/NumberOfDestinationsTest.java @@ -20,6 +20,7 @@ package org.apache.activemq.perf; * A NumberOfDestinationsTest * */ + import java.io.File; import javax.jms.Connection; import javax.jms.ConnectionFactory; @@ -28,100 +29,104 @@ import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageProducer; import javax.jms.Session; + import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + /** - * + * */ public class NumberOfDestinationsTest extends TestCase { - protected static final int MESSAGE_COUNT = 1; - protected static final int NUMBER_OF_DESTINATIONS = 100000; - private static final Logger LOG = LoggerFactory.getLogger(NumberOfDestinationsTest.class); - protected BrokerService broker; - protected String bindAddress = "vm://localhost"; - protected int destinationCount; - public void testDestinations() throws Exception { - ConnectionFactory factory = createConnectionFactory(); - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer mp = session.createProducer(null); - for (int j = 0; j < NUMBER_OF_DESTINATIONS; j++) { - Destination dest = getDestination(session); - - for (int i = 0; i < MESSAGE_COUNT; i++) { - Message msg = session.createTextMessage("test" + i); - mp.send(dest, msg); - - } - if (j % 500 == 0) { - LOG.info("Iterator " + j); - } - } - - connection.close(); - } + protected static final int MESSAGE_COUNT = 1; + protected static final int NUMBER_OF_DESTINATIONS = 100000; + private static final Logger LOG = LoggerFactory.getLogger(NumberOfDestinationsTest.class); + protected BrokerService broker; + protected String bindAddress = "vm://localhost"; + protected int destinationCount; - protected Destination getDestination(Session session) throws JMSException { - String topicName = getClass().getName() + "." + destinationCount++; - return session.createTopic(topicName); - } + public void testDestinations() throws Exception { + ConnectionFactory factory = createConnectionFactory(); + Connection connection = factory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer mp = session.createProducer(null); + for (int j = 0; j < NUMBER_OF_DESTINATIONS; j++) { + Destination dest = getDestination(session); - @Override - protected void setUp() throws Exception { - if (broker == null) { - broker = createBroker(); - } - super.setUp(); - } + for (int i = 0; i < MESSAGE_COUNT; i++) { + Message msg = session.createTextMessage("test" + i); + mp.send(dest, msg); - @Override - protected void tearDown() throws Exception { - super.tearDown(); - if (broker != null) { - broker.stop(); - } - } + } + if (j % 500 == 0) { + LOG.info("Iterator " + j); + } + } - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(bindAddress); - return cf; - } + connection.close(); + } - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - configureBroker(answer); - answer.start(); - return answer; - } + protected Destination getDestination(Session session) throws JMSException { + String topicName = getClass().getName() + "." + destinationCount++; + return session.createTopic(topicName); + } - protected void configureBroker(BrokerService answer) throws Exception { - File dataFileDir = new File("target/test-amq-data/perfTest/kahadb"); + @Override + protected void setUp() throws Exception { + if (broker == null) { + broker = createBroker(); + } + super.setUp(); + } - KahaDBPersistenceAdapter kaha = new KahaDBPersistenceAdapter(); - kaha.setDirectory(dataFileDir); - //answer.setUseJmx(false); + @Override + protected void tearDown() throws Exception { + super.tearDown(); + if (broker != null) { + broker.stop(); + } + } - // The setEnableJournalDiskSyncs(false) setting is a little dangerous right now, as I have not verified - // what happens if the index is updated but a journal update is lost. - // Index is going to be in consistent, but can it be repaired? - //kaha.setEnableJournalDiskSyncs(false); - // Using a bigger journal file size makes he take fewer spikes as it is not switching files as often. - //kaha.setJournalMaxFileLength(1024*100); - - // small batch means more frequent and smaller writes - //kaha.setIndexWriteBatchSize(100); - // do the index write in a separate thread - //kaha.setEnableIndexWriteAsync(true); - - answer.setPersistenceAdapter(kaha); - answer.setAdvisorySupport(false); - answer.setEnableStatistics(false); - answer.addConnector(bindAddress); - answer.setDeleteAllMessagesOnStartup(true); - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(bindAddress); + return cf; + } + + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + configureBroker(answer); + answer.start(); + return answer; + } + + protected void configureBroker(BrokerService answer) throws Exception { + File dataFileDir = new File("target/test-amq-data/perfTest/kahadb"); + + KahaDBPersistenceAdapter kaha = new KahaDBPersistenceAdapter(); + kaha.setDirectory(dataFileDir); + //answer.setUseJmx(false); + + // The setEnableJournalDiskSyncs(false) setting is a little dangerous right now, as I have not verified + // what happens if the index is updated but a journal update is lost. + // Index is going to be in consistent, but can it be repaired? + //kaha.setEnableJournalDiskSyncs(false); + // Using a bigger journal file size makes he take fewer spikes as it is not switching files as often. + //kaha.setJournalMaxFileLength(1024*100); + + // small batch means more frequent and smaller writes + //kaha.setIndexWriteBatchSize(100); + // do the index write in a separate thread + //kaha.setEnableIndexWriteAsync(true); + + answer.setPersistenceAdapter(kaha); + answer.setAdvisorySupport(false); + answer.setEnableStatistics(false); + answer.addConnector(bindAddress); + answer.setDeleteAllMessagesOnStartup(true); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/PerfConsumer.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/PerfConsumer.java index 14292b8d50..c8e8c8ed64 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/PerfConsumer.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/PerfConsumer.java @@ -25,6 +25,7 @@ import javax.jms.MessageConsumer; import javax.jms.MessageListener; import javax.jms.Session; import javax.jms.Topic; + import org.apache.activemq.ActiveMQMessageAudit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -33,108 +34,113 @@ import org.slf4j.LoggerFactory; * */ public class PerfConsumer implements MessageListener { - private static final Logger LOG = LoggerFactory.getLogger(PerfConsumer.class); - protected Connection connection; - protected MessageConsumer consumer; - protected long sleepDuration; - protected long initialDelay; - protected boolean enableAudit = false; - protected ActiveMQMessageAudit audit = new ActiveMQMessageAudit(16 * 1024,20); - protected boolean firstMessage =true; - protected String lastMsgId; - protected PerfRate rate = new PerfRate(); + private static final Logger LOG = LoggerFactory.getLogger(PerfConsumer.class); + protected Connection connection; + protected MessageConsumer consumer; + protected long sleepDuration; + protected long initialDelay; + protected boolean enableAudit = false; + protected ActiveMQMessageAudit audit = new ActiveMQMessageAudit(16 * 1024, 20); + protected boolean firstMessage = true; + protected String lastMsgId; - public PerfConsumer(ConnectionFactory fac, Destination dest, String consumerName) throws JMSException { - connection = fac.createConnection(); - connection.setClientID(consumerName); - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - if (dest instanceof Topic && consumerName != null && consumerName.length() > 0) { - consumer = s.createDurableSubscriber((Topic)dest, consumerName); - } else { - consumer = s.createConsumer(dest); - } - consumer.setMessageListener(this); - } + protected PerfRate rate = new PerfRate(); - public PerfConsumer(ConnectionFactory fac, Destination dest) throws JMSException { - this(fac, dest, null); - } + public PerfConsumer(ConnectionFactory fac, Destination dest, String consumerName) throws JMSException { + connection = fac.createConnection(); + connection.setClientID(consumerName); + Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + if (dest instanceof Topic && consumerName != null && consumerName.length() > 0) { + consumer = s.createDurableSubscriber((Topic) dest, consumerName); + } + else { + consumer = s.createConsumer(dest); + } + consumer.setMessageListener(this); + } - public void start() throws JMSException { - connection.start(); - rate.reset(); - } + public PerfConsumer(ConnectionFactory fac, Destination dest) throws JMSException { + this(fac, dest, null); + } - public void stop() throws JMSException { - connection.stop(); - } + public void start() throws JMSException { + connection.start(); + rate.reset(); + } - public void shutDown() throws JMSException { - connection.close(); - } + public void stop() throws JMSException { + connection.stop(); + } - public PerfRate getRate() { - return rate; - } + public void shutDown() throws JMSException { + connection.close(); + } - public void onMessage(Message msg) { - if (firstMessage) { - firstMessage=false; - if (getInitialDelay() > 0) { - try { - Thread.sleep(getInitialDelay()); - } catch (InterruptedException e) { - } + public PerfRate getRate() { + return rate; + } + + public void onMessage(Message msg) { + if (firstMessage) { + firstMessage = false; + if (getInitialDelay() > 0) { + try { + Thread.sleep(getInitialDelay()); } - } - rate.increment(); - try { - if (enableAudit && !this.audit.isInOrder(msg.getJMSMessageID())) { - LOG.error("Message out of order!!" + msg.getJMSMessageID() + " LAST = " + lastMsgId); + catch (InterruptedException e) { } - if (enableAudit && this.audit.isDuplicate(msg)){ - LOG.error("Duplicate Message!" + msg); - } - lastMsgId=msg.getJMSMessageID(); - } catch (JMSException e1) { - e1.printStackTrace(); - } - try { - if (sleepDuration != 0) { - Thread.sleep(sleepDuration); - } - } catch (InterruptedException e) { - } - } + } + } + rate.increment(); + try { + if (enableAudit && !this.audit.isInOrder(msg.getJMSMessageID())) { + LOG.error("Message out of order!!" + msg.getJMSMessageID() + " LAST = " + lastMsgId); + } + if (enableAudit && this.audit.isDuplicate(msg)) { + LOG.error("Duplicate Message!" + msg); + } + lastMsgId = msg.getJMSMessageID(); + } + catch (JMSException e1) { + e1.printStackTrace(); + } + try { + if (sleepDuration != 0) { + Thread.sleep(sleepDuration); + } + } + catch (InterruptedException e) { + } + } - public synchronized long getSleepDuration() { - return sleepDuration; - } + public synchronized long getSleepDuration() { + return sleepDuration; + } - public synchronized void setSleepDuration(long sleepDuration) { - this.sleepDuration = sleepDuration; - } + public synchronized void setSleepDuration(long sleepDuration) { + this.sleepDuration = sleepDuration; + } - public boolean isEnableAudit() { - return enableAudit; - } + public boolean isEnableAudit() { + return enableAudit; + } - public void setEnableAudit(boolean doAudit) { - this.enableAudit = doAudit; - } + public void setEnableAudit(boolean doAudit) { + this.enableAudit = doAudit; + } - /** - * @return the initialDelay - */ - public long getInitialDelay() { - return initialDelay; - } + /** + * @return the initialDelay + */ + public long getInitialDelay() { + return initialDelay; + } - /** - * @param initialDelay the initialDelay to set - */ - public void setInitialDelay(long initialDelay) { - this.initialDelay = initialDelay; - } + /** + * @param initialDelay the initialDelay to set + */ + public void setInitialDelay(long initialDelay) { + this.initialDelay = initialDelay; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/PerfProducer.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/PerfProducer.java index 10dc740a31..2d9cedd11f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/PerfProducer.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/PerfProducer.java @@ -27,103 +27,110 @@ import javax.jms.MessageProducer; import javax.jms.Session; /** - * + * */ public class PerfProducer implements Runnable { - protected Connection connection; - protected MessageProducer producer; - protected PerfRate rate = new PerfRate(); - private final byte[] payload; - private Session session; - private final CountDownLatch stopped = new CountDownLatch(1); - private boolean running; - private final boolean transacted; - private int sleep = 0; - public PerfProducer(ConnectionFactory fac, Destination dest, byte[] payload) throws JMSException { - this(fac, dest, payload, false); - } - public PerfProducer(ConnectionFactory fac, Destination dest, byte[] payload, boolean transacted) - throws JMSException { - connection = fac.createConnection(); - this.transacted = transacted; - if (transacted) { - session = connection.createSession(true, Session.SESSION_TRANSACTED); - } else { - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } - producer = session.createProducer(dest); - this.payload = payload; - - } + protected Connection connection; + protected MessageProducer producer; + protected PerfRate rate = new PerfRate(); + private final byte[] payload; + private Session session; + private final CountDownLatch stopped = new CountDownLatch(1); + private boolean running; + private final boolean transacted; + private int sleep = 0; - public void setDeliveryMode(int mode) throws JMSException { - producer.setDeliveryMode(mode); - } + public PerfProducer(ConnectionFactory fac, Destination dest, byte[] payload) throws JMSException { + this(fac, dest, payload, false); + } - public void setTimeToLive(int ttl) throws JMSException { - producer.setTimeToLive(ttl); - } + public PerfProducer(ConnectionFactory fac, + Destination dest, + byte[] payload, + boolean transacted) throws JMSException { + connection = fac.createConnection(); + this.transacted = transacted; + if (transacted) { + session = connection.createSession(true, Session.SESSION_TRANSACTED); + } + else { + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + } + producer = session.createProducer(dest); + this.payload = payload; - public void shutDown() throws JMSException { - connection.close(); - } + } - public PerfRate getRate() { - return rate; - } + public void setDeliveryMode(int mode) throws JMSException { + producer.setDeliveryMode(mode); + } - public synchronized void start() throws JMSException { - if (!running) { - rate.reset(); - running = true; - connection.start(); - Thread t = new Thread(this); - t.setName("Producer"); - t.start(); - } - } + public void setTimeToLive(int ttl) throws JMSException { + producer.setTimeToLive(ttl); + } - public void stop() throws JMSException, InterruptedException { - synchronized (this) { - running = false; - } - stopped.await(1, TimeUnit.SECONDS); - connection.stop(); - } + public void shutDown() throws JMSException { + connection.close(); + } - public synchronized boolean isRunning() { - return running; - } + public PerfRate getRate() { + return rate; + } - public void run() { - try { - while (isRunning()) { - BytesMessage msg; - msg = session.createBytesMessage(); - msg.writeBytes(payload); - producer.send(msg); - if(this.transacted) { - this.session.commit(); - } - rate.increment(); - if (sleep > 0) { - Thread.sleep(sleep); - } + public synchronized void start() throws JMSException { + if (!running) { + rate.reset(); + running = true; + connection.start(); + Thread t = new Thread(this); + t.setName("Producer"); + t.start(); + } + } + + public void stop() throws JMSException, InterruptedException { + synchronized (this) { + running = false; + } + stopped.await(1, TimeUnit.SECONDS); + connection.stop(); + } + + public synchronized boolean isRunning() { + return running; + } + + public void run() { + try { + while (isRunning()) { + BytesMessage msg; + msg = session.createBytesMessage(); + msg.writeBytes(payload); + producer.send(msg); + if (this.transacted) { + this.session.commit(); } - } catch (Throwable e) { - e.printStackTrace(); - } finally { - stopped.countDown(); - } - } + rate.increment(); + if (sleep > 0) { + Thread.sleep(sleep); + } + } + } + catch (Throwable e) { + e.printStackTrace(); + } + finally { + stopped.countDown(); + } + } - public int getSleep() { - return sleep; - } + public int getSleep() { + return sleep; + } - public void setSleep(int sleep) { - this.sleep = sleep; - } + public void setSleep(int sleep) { + this.sleep = sleep; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/PerfRate.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/PerfRate.java index 8f82617521..043b65278d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/PerfRate.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/PerfRate.java @@ -17,65 +17,65 @@ package org.apache.activemq.perf; /** - * + * */ public class PerfRate { - protected int totalCount; - protected int count; - protected long startTime = System.currentTimeMillis(); + protected int totalCount; + protected int count; + protected long startTime = System.currentTimeMillis(); - /** - * @return Returns the count. - */ - public int getCount() { - return totalCount; - } + /** + * @return Returns the count. + */ + public int getCount() { + return totalCount; + } - public synchronized void increment() { - totalCount++; - count++; - } + public synchronized void increment() { + totalCount++; + count++; + } - public int getRate() { - long endTime = System.currentTimeMillis(); - long totalTime = endTime - startTime; - int result = (int)((count * 1000) / totalTime); - return result; - } + public int getRate() { + long endTime = System.currentTimeMillis(); + long totalTime = endTime - startTime; + int result = (int) ((count * 1000) / totalTime); + return result; + } - /** - * Resets the rate sampling. - */ - public synchronized PerfRate cloneAndReset() { - PerfRate rc = new PerfRate(); - rc.totalCount = totalCount; - rc.count = count; - rc.startTime = startTime; - count = 0; - startTime = System.currentTimeMillis(); - return rc; - } + /** + * Resets the rate sampling. + */ + public synchronized PerfRate cloneAndReset() { + PerfRate rc = new PerfRate(); + rc.totalCount = totalCount; + rc.count = count; + rc.startTime = startTime; + count = 0; + startTime = System.currentTimeMillis(); + return rc; + } - /** - * Resets the rate sampling. - */ - public void reset() { - count = 0; - startTime = System.currentTimeMillis(); - } + /** + * Resets the rate sampling. + */ + public void reset() { + count = 0; + startTime = System.currentTimeMillis(); + } - /** - * @return Returns the totalCount. - */ - public int getTotalCount() { - return totalCount; - } + /** + * @return Returns the totalCount. + */ + public int getTotalCount() { + return totalCount; + } - /** - * @param totalCount The totalCount to set. - */ - public void setTotalCount(int totalCount) { - this.totalCount = totalCount; - } + /** + * @param totalCount The totalCount to set. + */ + public void setTotalCount(int totalCount) { + this.totalCount = totalCount; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/QueueConnectionMemoryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/QueueConnectionMemoryTest.java index ff19f3e80f..900ece0461 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/QueueConnectionMemoryTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/QueueConnectionMemoryTest.java @@ -30,54 +30,55 @@ import org.slf4j.LoggerFactory; * */ public class QueueConnectionMemoryTest extends SimpleQueueTest { - private static final transient Logger LOG = LoggerFactory.getLogger(QueueConnectionMemoryTest.class); - @Override - protected void setUp() throws Exception { - } + private static final transient Logger LOG = LoggerFactory.getLogger(QueueConnectionMemoryTest.class); - @Override - protected void tearDown() throws Exception { + @Override + protected void setUp() throws Exception { + } - } + @Override + protected void tearDown() throws Exception { - @Override - protected Destination createDestination(Session s, String destinationName) throws JMSException { - return s.createTemporaryQueue(); - } + } - @Override - public void testPerformance() throws JMSException { - // just cancel super class test - } + @Override + protected Destination createDestination(Session s, String destinationName) throws JMSException { + return s.createTemporaryQueue(); + } - @Override - protected void configureBroker(BrokerService answer,String uri) throws Exception { - LevelDBStore adaptor = new LevelDBStore(); - answer.setPersistenceAdapter(adaptor); - answer.addConnector(uri); - answer.setDeleteAllMessagesOnStartup(true); - } + @Override + public void testPerformance() throws JMSException { + // just cancel super class test + } - public void testMemory() throws Exception { - if (broker == null) { - broker = createBroker(bindAddress); - } - factory = createConnectionFactory(bindAddress); - Connection con = factory.createConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - createDestination(session, destinationName); - con.close(); - for (int i = 0; i < 3; i++) { - Connection connection = factory.createConnection(); - connection.start(); - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination dest = s.createTemporaryQueue(); - s.createConsumer(dest); - LOG.debug("Created connnection: " + i); - Thread.sleep(1000); - } + @Override + protected void configureBroker(BrokerService answer, String uri) throws Exception { + LevelDBStore adaptor = new LevelDBStore(); + answer.setPersistenceAdapter(adaptor); + answer.addConnector(uri); + answer.setDeleteAllMessagesOnStartup(true); + } - Thread.sleep(Integer.MAX_VALUE); - } + public void testMemory() throws Exception { + if (broker == null) { + broker = createBroker(bindAddress); + } + factory = createConnectionFactory(bindAddress); + Connection con = factory.createConnection(); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + createDestination(session, destinationName); + con.close(); + for (int i = 0; i < 3; i++) { + Connection connection = factory.createConnection(); + connection.start(); + Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination dest = s.createTemporaryQueue(); + s.createConsumer(dest); + LOG.debug("Created connnection: " + i); + Thread.sleep(1000); + } + + Thread.sleep(Integer.MAX_VALUE); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/RunBroker.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/RunBroker.java index 0e78235b94..4b08ad50ed 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/RunBroker.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/RunBroker.java @@ -24,43 +24,44 @@ import org.apache.activemq.util.IOHelper; public class RunBroker { - public static void main(String arg[]) { + public static void main(String arg[]) { - try { - KahaDBPersistenceAdapter kahaDB = new KahaDBPersistenceAdapter(); - File dataFileDir = new File("target/test-amq-data/perfTest/kahadb"); - IOHelper.deleteChildren(dataFileDir); - kahaDB.setDirectory(dataFileDir); + try { + KahaDBPersistenceAdapter kahaDB = new KahaDBPersistenceAdapter(); + File dataFileDir = new File("target/test-amq-data/perfTest/kahadb"); + IOHelper.deleteChildren(dataFileDir); + kahaDB.setDirectory(dataFileDir); - // The setEnableJournalDiskSyncs(false) setting is a little - // dangerous right now, as I have not verified - // what happens if the index is updated but a journal update is - // lost. - // Index is going to be in consistent, but can it be repaired? - // kaha.setEnableJournalDiskSyncs(false); - // Using a bigger journal file size makes he take fewer spikes as it - // is not switching files as often. - // kaha.setJournalMaxFileLength(1024*1024*100); + // The setEnableJournalDiskSyncs(false) setting is a little + // dangerous right now, as I have not verified + // what happens if the index is updated but a journal update is + // lost. + // Index is going to be in consistent, but can it be repaired? + // kaha.setEnableJournalDiskSyncs(false); + // Using a bigger journal file size makes he take fewer spikes as it + // is not switching files as often. + // kaha.setJournalMaxFileLength(1024*1024*100); - // small batch means more frequent and smaller writes - kahaDB.setIndexWriteBatchSize(1000); - kahaDB.setIndexCacheSize(10000); + // small batch means more frequent and smaller writes + kahaDB.setIndexWriteBatchSize(1000); + kahaDB.setIndexCacheSize(10000); - // do the index write in a separate thread - // kahaDB.setEnableIndexWriteAsync(true); - BrokerService broker = new BrokerService(); - broker.setUseJmx(false); - // broker.setPersistenceAdapter(adaptor); - broker.setPersistenceAdapter(kahaDB); - // broker.setPersistent(false); - broker.setDeleteAllMessagesOnStartup(true); - broker.addConnector("tcp://0.0.0.0:61616"); - broker.start(); - System.err.println("Running"); - Thread.sleep(Long.MAX_VALUE); - } catch (Throwable e) { - e.printStackTrace(); - } + // do the index write in a separate thread + // kahaDB.setEnableIndexWriteAsync(true); + BrokerService broker = new BrokerService(); + broker.setUseJmx(false); + // broker.setPersistenceAdapter(adaptor); + broker.setPersistenceAdapter(kahaDB); + // broker.setPersistent(false); + broker.setDeleteAllMessagesOnStartup(true); + broker.addConnector("tcp://0.0.0.0:61616"); + broker.start(); + System.err.println("Running"); + Thread.sleep(Long.MAX_VALUE); + } + catch (Throwable e) { + e.printStackTrace(); + } - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleDurableTopicNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleDurableTopicNetworkTest.java index c4fd892253..f8da821543 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleDurableTopicNetworkTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleDurableTopicNetworkTest.java @@ -21,25 +21,26 @@ import javax.jms.DeliveryMode; import javax.jms.Destination; import javax.jms.JMSException; - public class SimpleDurableTopicNetworkTest extends SimpleNetworkTest { - - protected void setUp() throws Exception { - numberofProducers=1; - numberOfConsumers=1; - sampleCount=1000; - playloadSize = 1024; - super.setUp(); - } - - - protected PerfProducer createProducer(ConnectionFactory fac, Destination dest, int number, byte payload[]) throws JMSException { - PerfProducer pp = new PerfProducer(fac, dest, payload); - pp.setDeliveryMode(DeliveryMode.PERSISTENT); - return pp; - } - protected PerfConsumer createConsumer(ConnectionFactory fac, Destination dest, int number) throws JMSException { - return new PerfConsumer(fac, dest, "subs:" + number); - } + protected void setUp() throws Exception { + numberofProducers = 1; + numberOfConsumers = 1; + sampleCount = 1000; + playloadSize = 1024; + super.setUp(); + } + + protected PerfProducer createProducer(ConnectionFactory fac, + Destination dest, + int number, + byte payload[]) throws JMSException { + PerfProducer pp = new PerfProducer(fac, dest, payload); + pp.setDeliveryMode(DeliveryMode.PERSISTENT); + return pp; + } + + protected PerfConsumer createConsumer(ConnectionFactory fac, Destination dest, int number) throws JMSException { + return new PerfConsumer(fac, dest, "subs:" + number); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleDurableTopicTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleDurableTopicTest.java index 9ca25c1a13..125b320bb0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleDurableTopicTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleDurableTopicTest.java @@ -26,49 +26,53 @@ import javax.jms.Destination; import javax.jms.JMSException; /** - * + * */ public class SimpleDurableTopicTest extends SimpleTopicTest { - protected long initialConsumerDelay = 0; - @Override - protected void setUp() throws Exception { - numberOfDestinations=1; - numberOfConsumers = 1; - numberofProducers = Integer.parseInt(System.getProperty("SimpleDurableTopicTest.numberofProducers", "20"), 20); - sampleCount= Integer.parseInt(System.getProperty("SimpleDurableTopicTest.sampleCount", "1000"), 10); - playloadSize = 1024; - super.setUp(); - } + protected long initialConsumerDelay = 0; - @Override - protected void configureBroker(BrokerService answer,String uri) throws Exception { - LevelDBStoreFactory persistenceFactory = new LevelDBStoreFactory(); - answer.setPersistenceFactory(persistenceFactory); - //answer.setDeleteAllMessagesOnStartup(true); - answer.addConnector(uri); - answer.setUseShutdownHook(false); - } - - @Override - protected PerfProducer createProducer(ConnectionFactory fac, Destination dest, int number, byte payload[]) throws JMSException { - PerfProducer pp = new PerfProducer(fac, dest, payload); - pp.setDeliveryMode(DeliveryMode.PERSISTENT); - return pp; - } + @Override + protected void setUp() throws Exception { + numberOfDestinations = 1; + numberOfConsumers = 1; + numberofProducers = Integer.parseInt(System.getProperty("SimpleDurableTopicTest.numberofProducers", "20"), 20); + sampleCount = Integer.parseInt(System.getProperty("SimpleDurableTopicTest.sampleCount", "1000"), 10); + playloadSize = 1024; + super.setUp(); + } - @Override - protected PerfConsumer createConsumer(ConnectionFactory fac, Destination dest, int number) throws JMSException { - PerfConsumer result = new PerfConsumer(fac, dest, "subs:" + number); - result.setInitialDelay(this.initialConsumerDelay); - return result; - } - - @Override - protected ActiveMQConnectionFactory createConnectionFactory(String uri) throws Exception { - ActiveMQConnectionFactory result = super.createConnectionFactory(uri); - //result.setSendAcksAsync(false); - return result; - } + @Override + protected void configureBroker(BrokerService answer, String uri) throws Exception { + LevelDBStoreFactory persistenceFactory = new LevelDBStoreFactory(); + answer.setPersistenceFactory(persistenceFactory); + //answer.setDeleteAllMessagesOnStartup(true); + answer.addConnector(uri); + answer.setUseShutdownHook(false); + } + + @Override + protected PerfProducer createProducer(ConnectionFactory fac, + Destination dest, + int number, + byte payload[]) throws JMSException { + PerfProducer pp = new PerfProducer(fac, dest, payload); + pp.setDeliveryMode(DeliveryMode.PERSISTENT); + return pp; + } + + @Override + protected PerfConsumer createConsumer(ConnectionFactory fac, Destination dest, int number) throws JMSException { + PerfConsumer result = new PerfConsumer(fac, dest, "subs:" + number); + result.setInitialDelay(this.initialConsumerDelay); + return result; + } + + @Override + protected ActiveMQConnectionFactory createConnectionFactory(String uri) throws Exception { + ActiveMQConnectionFactory result = super.createConnectionFactory(uri); + //result.setSendAcksAsync(false); + return result; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNetworkTest.java index fdb14e2371..e4ee0ed5f6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNetworkTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNetworkTest.java @@ -27,118 +27,115 @@ import org.apache.activemq.network.NetworkConnector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - public class SimpleNetworkTest extends SimpleTopicTest { - private static final Logger LOG = LoggerFactory.getLogger(SimpleNetworkTest.class); - protected String consumerBindAddress = "tcp://localhost:61616"; - protected String producerBindAddress = "tcp://localhost:61617"; - protected static final String CONSUMER_BROKER_NAME = "Consumer"; - protected static final String PRODUCER_BROKER_NAME = "Producer"; - protected BrokerService consumerBroker; - protected BrokerService producerBroker; - protected ActiveMQConnectionFactory consumerFactory; - protected ActiveMQConnectionFactory producerFactory; - - - protected void setUp() throws Exception { - if (consumerBroker == null) { - consumerBroker = createConsumerBroker(consumerBindAddress); - } - if (producerBroker == null) { - producerBroker = createProducerBroker(producerBindAddress); - } - consumerFactory = createConnectionFactory(consumerBindAddress); - consumerFactory.setDispatchAsync(true); - ActiveMQPrefetchPolicy policy = new ActiveMQPrefetchPolicy(); - policy.setQueuePrefetch(100); - consumerFactory.setPrefetchPolicy(policy); - producerFactory = createConnectionFactory(producerBindAddress); - Connection con = consumerFactory.createConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - - producers = new PerfProducer[numberofProducers*numberOfDestinations]; - consumers = new PerfConsumer[numberOfConsumers*numberOfDestinations]; - - for (int k =0; k < numberOfDestinations;k++) { - Destination destination = createDestination(session, destinationName+":"+k); - LOG.info("Testing against destination: " + destination); - for (int i = 0; i < numberOfConsumers; i++) { - consumers[i] = createConsumer(consumerFactory, destination, i); - consumers[i].start(); - } - for (int i = 0; i < numberofProducers; i++) { - array = new byte[playloadSize]; - for (int j = i; j < array.length; j++) { - array[j] = (byte)j; - } - producers[i] = createProducer(producerFactory, destination, i, array); - producers[i].start(); - - } - } - con.close(); - } + private static final Logger LOG = LoggerFactory.getLogger(SimpleNetworkTest.class); + protected String consumerBindAddress = "tcp://localhost:61616"; + protected String producerBindAddress = "tcp://localhost:61617"; + protected static final String CONSUMER_BROKER_NAME = "Consumer"; + protected static final String PRODUCER_BROKER_NAME = "Producer"; + protected BrokerService consumerBroker; + protected BrokerService producerBroker; + protected ActiveMQConnectionFactory consumerFactory; + protected ActiveMQConnectionFactory producerFactory; - protected void tearDown() throws Exception { - for (int i = 0; i < numberOfConsumers; i++) { - consumers[i].shutDown(); - } - for (int i = 0; i < numberofProducers; i++) { - producers[i].shutDown(); - } - - if (producerBroker != null) { - producerBroker.stop(); - producerBroker = null; - } - if (consumerBroker != null) { - consumerBroker.stop(); - consumerBroker = null; - } - } - - protected BrokerService createConsumerBroker(String uri) throws Exception { - BrokerService answer = new BrokerService(); - configureConsumerBroker(answer,uri); - answer.start(); - return answer; - } - - protected void configureConsumerBroker(BrokerService answer,String uri) throws Exception { - configureBroker(answer); - answer.setPersistent(false); - answer.setBrokerName(CONSUMER_BROKER_NAME); - answer.setDeleteAllMessagesOnStartup(true); - answer.addConnector(uri); - answer.setUseShutdownHook(false); - } - - protected BrokerService createProducerBroker(String uri) throws Exception { - BrokerService answer = new BrokerService(); - configureProducerBroker(answer,uri); - answer.start(); - return answer; - } - - protected void configureProducerBroker(BrokerService answer,String uri) throws Exception { - configureBroker(answer); - answer.setBrokerName(PRODUCER_BROKER_NAME); - answer.setMonitorConnectionSplits(false); - //answer.setSplitSystemUsageForProducersConsumers(true); - answer.setPersistent(false); - answer.setDeleteAllMessagesOnStartup(true); - NetworkConnector connector = answer.addNetworkConnector("static://"+consumerBindAddress); - //connector.setNetworkTTL(3); - //connector.setDynamicOnly(true); - connector.setDuplex(true); - answer.addConnector(uri); - answer.setUseShutdownHook(false); - } - - protected void configureBroker(BrokerService service) throws Exception{ - - } + protected void setUp() throws Exception { + if (consumerBroker == null) { + consumerBroker = createConsumerBroker(consumerBindAddress); + } + if (producerBroker == null) { + producerBroker = createProducerBroker(producerBindAddress); + } + consumerFactory = createConnectionFactory(consumerBindAddress); + consumerFactory.setDispatchAsync(true); + ActiveMQPrefetchPolicy policy = new ActiveMQPrefetchPolicy(); + policy.setQueuePrefetch(100); + consumerFactory.setPrefetchPolicy(policy); + producerFactory = createConnectionFactory(producerBindAddress); + Connection con = consumerFactory.createConnection(); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + producers = new PerfProducer[numberofProducers * numberOfDestinations]; + consumers = new PerfConsumer[numberOfConsumers * numberOfDestinations]; + + for (int k = 0; k < numberOfDestinations; k++) { + Destination destination = createDestination(session, destinationName + ":" + k); + LOG.info("Testing against destination: " + destination); + for (int i = 0; i < numberOfConsumers; i++) { + consumers[i] = createConsumer(consumerFactory, destination, i); + consumers[i].start(); + } + for (int i = 0; i < numberofProducers; i++) { + array = new byte[playloadSize]; + for (int j = i; j < array.length; j++) { + array[j] = (byte) j; + } + producers[i] = createProducer(producerFactory, destination, i, array); + producers[i].start(); + + } + } + con.close(); + } + + protected void tearDown() throws Exception { + for (int i = 0; i < numberOfConsumers; i++) { + consumers[i].shutDown(); + } + for (int i = 0; i < numberofProducers; i++) { + producers[i].shutDown(); + } + + if (producerBroker != null) { + producerBroker.stop(); + producerBroker = null; + } + if (consumerBroker != null) { + consumerBroker.stop(); + consumerBroker = null; + } + } + + protected BrokerService createConsumerBroker(String uri) throws Exception { + BrokerService answer = new BrokerService(); + configureConsumerBroker(answer, uri); + answer.start(); + return answer; + } + + protected void configureConsumerBroker(BrokerService answer, String uri) throws Exception { + configureBroker(answer); + answer.setPersistent(false); + answer.setBrokerName(CONSUMER_BROKER_NAME); + answer.setDeleteAllMessagesOnStartup(true); + answer.addConnector(uri); + answer.setUseShutdownHook(false); + } + + protected BrokerService createProducerBroker(String uri) throws Exception { + BrokerService answer = new BrokerService(); + configureProducerBroker(answer, uri); + answer.start(); + return answer; + } + + protected void configureProducerBroker(BrokerService answer, String uri) throws Exception { + configureBroker(answer); + answer.setBrokerName(PRODUCER_BROKER_NAME); + answer.setMonitorConnectionSplits(false); + //answer.setSplitSystemUsageForProducersConsumers(true); + answer.setPersistent(false); + answer.setDeleteAllMessagesOnStartup(true); + NetworkConnector connector = answer.addNetworkConnector("static://" + consumerBindAddress); + //connector.setNetworkTTL(3); + //connector.setDynamicOnly(true); + connector.setDuplex(true); + answer.addConnector(uri); + answer.setUseShutdownHook(false); + } + + protected void configureBroker(BrokerService service) throws Exception { + + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNonPersistentQueueNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNonPersistentQueueNetworkTest.java index 7011a35020..aa956a30a5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNonPersistentQueueNetworkTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNonPersistentQueueNetworkTest.java @@ -32,52 +32,55 @@ import org.apache.activemq.broker.region.policy.PolicyMap; public class SimpleNonPersistentQueueNetworkTest extends SimpleNetworkTest { - protected void setUp()throws Exception { - numberOfDestinations =20; - super.setUp(); - } - protected PerfProducer createProducer(ConnectionFactory fac, Destination dest, int number, byte[] payload) throws JMSException { - PerfProducer pp = new PerfProducer(fac, dest, payload); - pp.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - // pp.setTimeToLive(1000); - //pp.setSleep(1); - return pp; - } - - protected PerfConsumer createConsumer(ConnectionFactory fac, Destination dest, int number) throws JMSException { - PerfConsumer consumer = new PerfConsumer(fac, dest); - boolean enableAudit = numberOfConsumers <= 1; - System.out.println("Enable Audit = " + enableAudit); - consumer.setEnableAudit(false); - return consumer; - } - - public void testPerformance() throws JMSException, InterruptedException { - //Thread.sleep(5000); - super.testPerformance(); - } - - protected Destination createDestination(Session s, String destinationName) throws JMSException { - return s.createQueue(destinationName); - } - - protected void configureBroker(BrokerService answer) throws Exception { - answer.setPersistent(false); - answer.setMonitorConnectionSplits(true); - final List policyEntries = new ArrayList(); - final PolicyEntry entry = new PolicyEntry(); - entry.setQueue(">"); - entry.setMemoryLimit(1024 * 1024 * 100); // Set to 1 MB - entry.setOptimizedDispatch(true); - entry.setProducerFlowControl(true); - entry.setMaxPageSize(10); - entry.setLazyDispatch(false); - policyEntries.add(entry); + protected void setUp() throws Exception { + numberOfDestinations = 20; + super.setUp(); + } - - final PolicyMap policyMap = new PolicyMap(); - policyMap.setPolicyEntries(policyEntries); - answer.setDestinationPolicy(policyMap); - super.configureBroker(answer); - } + protected PerfProducer createProducer(ConnectionFactory fac, + Destination dest, + int number, + byte[] payload) throws JMSException { + PerfProducer pp = new PerfProducer(fac, dest, payload); + pp.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + // pp.setTimeToLive(1000); + //pp.setSleep(1); + return pp; + } + + protected PerfConsumer createConsumer(ConnectionFactory fac, Destination dest, int number) throws JMSException { + PerfConsumer consumer = new PerfConsumer(fac, dest); + boolean enableAudit = numberOfConsumers <= 1; + System.out.println("Enable Audit = " + enableAudit); + consumer.setEnableAudit(false); + return consumer; + } + + public void testPerformance() throws JMSException, InterruptedException { + //Thread.sleep(5000); + super.testPerformance(); + } + + protected Destination createDestination(Session s, String destinationName) throws JMSException { + return s.createQueue(destinationName); + } + + protected void configureBroker(BrokerService answer) throws Exception { + answer.setPersistent(false); + answer.setMonitorConnectionSplits(true); + final List policyEntries = new ArrayList(); + final PolicyEntry entry = new PolicyEntry(); + entry.setQueue(">"); + entry.setMemoryLimit(1024 * 1024 * 100); // Set to 1 MB + entry.setOptimizedDispatch(true); + entry.setProducerFlowControl(true); + entry.setMaxPageSize(10); + entry.setLazyDispatch(false); + policyEntries.add(entry); + + final PolicyMap policyMap = new PolicyMap(); + policyMap.setPolicyEntries(policyEntries); + answer.setDestinationPolicy(policyMap); + super.configureBroker(answer); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNonPersistentQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNonPersistentQueueTest.java index 1a531f4619..ed5d525eb3 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNonPersistentQueueTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNonPersistentQueueTest.java @@ -22,57 +22,60 @@ import javax.jms.ConnectionFactory; import javax.jms.DeliveryMode; import javax.jms.Destination; import javax.jms.JMSException; + import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.region.policy.PolicyEntry; import org.apache.activemq.broker.region.policy.PolicyMap; /** - * + * */ public class SimpleNonPersistentQueueTest extends SimpleQueueTest { - @Override - protected void setUp() throws Exception { - numberOfConsumers = 1; - numberofProducers = 1; - super.setUp(); - } - @Override - protected PerfProducer createProducer(ConnectionFactory fac, Destination dest, int number, byte[] payload) throws JMSException { - PerfProducer pp = new PerfProducer(fac, dest, payload); - pp.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - //pp.setTimeToLive(100); - return pp; - } - - @Override - protected PerfConsumer createConsumer(ConnectionFactory fac, Destination dest, int number) throws JMSException { - PerfConsumer result = new PerfConsumer(fac, dest); - result.setInitialDelay(10*1000); - boolean enableAudit = numberOfConsumers <= 1; - System.err.println("Enable Audit = " + enableAudit); - result.setEnableAudit(enableAudit); + @Override + protected void setUp() throws Exception { + numberOfConsumers = 1; + numberofProducers = 1; + super.setUp(); + } - return result; - } - - - @Override - protected void configureBroker(BrokerService answer,String uri) throws Exception { - // answer.setPersistent(false); - final List policyEntries = new ArrayList(); - final PolicyEntry entry = new PolicyEntry(); - entry.setQueue(">"); - entry.setMemoryLimit(1024 * 1024 * 1); // Set to 1 MB - entry.setOptimizedDispatch(true); - entry.setLazyDispatch(true); - policyEntries.add(entry); + @Override + protected PerfProducer createProducer(ConnectionFactory fac, + Destination dest, + int number, + byte[] payload) throws JMSException { + PerfProducer pp = new PerfProducer(fac, dest, payload); + pp.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + //pp.setTimeToLive(100); + return pp; + } + + @Override + protected PerfConsumer createConsumer(ConnectionFactory fac, Destination dest, int number) throws JMSException { + PerfConsumer result = new PerfConsumer(fac, dest); + result.setInitialDelay(10 * 1000); + boolean enableAudit = numberOfConsumers <= 1; + System.err.println("Enable Audit = " + enableAudit); + result.setEnableAudit(enableAudit); + + return result; + } + + @Override + protected void configureBroker(BrokerService answer, String uri) throws Exception { + // answer.setPersistent(false); + final List policyEntries = new ArrayList(); + final PolicyEntry entry = new PolicyEntry(); + entry.setQueue(">"); + entry.setMemoryLimit(1024 * 1024 * 1); // Set to 1 MB + entry.setOptimizedDispatch(true); + entry.setLazyDispatch(true); + policyEntries.add(entry); + + final PolicyMap policyMap = new PolicyMap(); + policyMap.setPolicyEntries(policyEntries); + answer.setDestinationPolicy(policyMap); + super.configureBroker(answer, uri); + } - - final PolicyMap policyMap = new PolicyMap(); - policyMap.setPolicyEntries(policyEntries); - answer.setDestinationPolicy(policyMap); - super.configureBroker(answer, uri); - } - } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNonPersistentTopicTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNonPersistentTopicTest.java index eacc6e1775..9c033fe83a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNonPersistentTopicTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNonPersistentTopicTest.java @@ -22,13 +22,16 @@ import javax.jms.Destination; import javax.jms.JMSException; /** - * + * */ public class SimpleNonPersistentTopicTest extends SimpleTopicTest { - protected PerfProducer createProducer(ConnectionFactory fac, Destination dest, int number, byte[] payload) throws JMSException { - PerfProducer pp = new PerfProducer(fac, dest, payload); - pp.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - return pp; - } + protected PerfProducer createProducer(ConnectionFactory fac, + Destination dest, + int number, + byte[] payload) throws JMSException { + PerfProducer pp = new PerfProducer(fac, dest, payload); + pp.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + return pp; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleQueueTest.java index 30708f4c79..9761784d37 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleQueueTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleQueueTest.java @@ -22,32 +22,33 @@ import javax.jms.JMSException; import javax.jms.Session; /** - * + * */ public class SimpleQueueTest extends SimpleTopicTest { - protected long initialConsumerDelay = 0; - protected long consumerSleep = 0; - @Override - protected Destination createDestination(Session s, String destinationName) throws JMSException { - return s.createQueue(destinationName); - } - - @Override - protected void setUp() throws Exception { - numberOfConsumers = 1; - super.setUp(); - } - - @Override - protected PerfConsumer createConsumer(ConnectionFactory fac, Destination dest, int number) throws JMSException { - PerfConsumer consumer = new PerfConsumer(fac, dest); - consumer.setInitialDelay(this.initialConsumerDelay); - consumer.setSleepDuration(this.consumerSleep); - boolean enableAudit = numberOfConsumers <= 1; - System.err.println("Enable Audit = " + enableAudit); - consumer.setEnableAudit(enableAudit); - return consumer; - } + protected long initialConsumerDelay = 0; + protected long consumerSleep = 0; + + @Override + protected Destination createDestination(Session s, String destinationName) throws JMSException { + return s.createQueue(destinationName); + } + + @Override + protected void setUp() throws Exception { + numberOfConsumers = 1; + super.setUp(); + } + + @Override + protected PerfConsumer createConsumer(ConnectionFactory fac, Destination dest, int number) throws JMSException { + PerfConsumer consumer = new PerfConsumer(fac, dest); + consumer.setInitialDelay(this.initialConsumerDelay); + consumer.setSleepDuration(this.consumerSleep); + boolean enableAudit = numberOfConsumers <= 1; + System.err.println("Enable Audit = " + enableAudit); + consumer.setEnableAudit(enableAudit); + return consumer; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleTopicTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleTopicTest.java index e0494ab96d..c93a7f6e22 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleTopicTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleTopicTest.java @@ -34,173 +34,176 @@ import org.slf4j.LoggerFactory; */ public class SimpleTopicTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(SimpleTopicTest.class); + private static final Logger LOG = LoggerFactory.getLogger(SimpleTopicTest.class); - protected BrokerService broker; - protected String clientURI = "tcp://localhost:61616?wireFormat.cacheEnabled=true&wireFormat.tightEncodingEnabled=true&jms.useAsyncSend=false&wireFormat.maxInactivityDuration=0"; - // protected String clientURI="tcp://localhost:61616"; - protected String bindAddress = "tcp://localhost:61616?wireFormat.maxInactivityDuration=0"; - // protected String bindAddress = "tcp://localhost:61616"; - // protected String bindAddress="vm://localhost?marshal=true"; - // protected String bindAddress="vm://localhost"; - protected PerfProducer[] producers; - protected PerfConsumer[] consumers; - protected String destinationName = getClass().getName(); - protected int sampleCount = 20; - protected long sampleInternal = 10000; - protected int numberOfDestinations = 1; - protected int numberOfConsumers = 1; - protected int numberofProducers = 1; - protected int totalNumberOfProducers; - protected int totalNumberOfConsumers; - protected int playloadSize = 12; - protected byte[] array; - protected ConnectionFactory factory; + protected BrokerService broker; + protected String clientURI = "tcp://localhost:61616?wireFormat.cacheEnabled=true&wireFormat.tightEncodingEnabled=true&jms.useAsyncSend=false&wireFormat.maxInactivityDuration=0"; + // protected String clientURI="tcp://localhost:61616"; + protected String bindAddress = "tcp://localhost:61616?wireFormat.maxInactivityDuration=0"; + // protected String bindAddress = "tcp://localhost:61616"; + // protected String bindAddress="vm://localhost?marshal=true"; + // protected String bindAddress="vm://localhost"; + protected PerfProducer[] producers; + protected PerfConsumer[] consumers; + protected String destinationName = getClass().getName(); + protected int sampleCount = 20; + protected long sampleInternal = 10000; + protected int numberOfDestinations = 1; + protected int numberOfConsumers = 1; + protected int numberofProducers = 1; + protected int totalNumberOfProducers; + protected int totalNumberOfConsumers; + protected int playloadSize = 12; + protected byte[] array; + protected ConnectionFactory factory; - /** - * Sets up a test where the producer and consumer have their own connection. - * - * @see junit.framework.TestCase#setUp() - */ - @Override - protected void setUp() throws Exception { - if (broker == null) { - broker = createBroker(bindAddress); - } - factory = createConnectionFactory(clientURI); - Connection con = factory.createConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + /** + * Sets up a test where the producer and consumer have their own connection. + * + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + if (broker == null) { + broker = createBroker(bindAddress); + } + factory = createConnectionFactory(clientURI); + Connection con = factory.createConnection(); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - LOG.info("Running " + numberofProducers + " producer(s) and " + numberOfConsumers + " consumer(s) per " + numberOfDestinations + " Destination(s)"); + LOG.info("Running " + numberofProducers + " producer(s) and " + numberOfConsumers + " consumer(s) per " + numberOfDestinations + " Destination(s)"); - totalNumberOfConsumers = numberOfConsumers * numberOfDestinations; - totalNumberOfProducers = numberofProducers * numberOfDestinations; - producers = new PerfProducer[totalNumberOfProducers]; - consumers = new PerfConsumer[totalNumberOfConsumers]; - int consumerCount = 0; - int producerCount = 0; - for (int k = 0; k < numberOfDestinations; k++) { - Destination destination = createDestination(session, destinationName + ":" + k); - LOG.info("Testing against destination: " + destination); - for (int i = 0; i < numberOfConsumers; i++) { - consumers[consumerCount] = createConsumer(factory, destination, consumerCount); - consumerCount++; + totalNumberOfConsumers = numberOfConsumers * numberOfDestinations; + totalNumberOfProducers = numberofProducers * numberOfDestinations; + producers = new PerfProducer[totalNumberOfProducers]; + consumers = new PerfConsumer[totalNumberOfConsumers]; + int consumerCount = 0; + int producerCount = 0; + for (int k = 0; k < numberOfDestinations; k++) { + Destination destination = createDestination(session, destinationName + ":" + k); + LOG.info("Testing against destination: " + destination); + for (int i = 0; i < numberOfConsumers; i++) { + consumers[consumerCount] = createConsumer(factory, destination, consumerCount); + consumerCount++; + } + for (int i = 0; i < numberofProducers; i++) { + array = new byte[playloadSize]; + for (int j = i; j < array.length; j++) { + array[j] = (byte) j; } - for (int i = 0; i < numberofProducers; i++) { - array = new byte[playloadSize]; - for (int j = i; j < array.length; j++) { - array[j] = (byte) j; - } - producers[producerCount] = createProducer(factory, destination, i, array); - producerCount++; - } - } - con.close(); - super.setUp(); - } + producers[producerCount] = createProducer(factory, destination, i, array); + producerCount++; + } + } + con.close(); + super.setUp(); + } - @Override - protected void tearDown() throws Exception { - super.tearDown(); - for (int i = 0; i < numberOfConsumers; i++) { - consumers[i].shutDown(); - } - for (int i = 0; i < numberofProducers; i++) { - producers[i].shutDown(); - } - if (broker != null) { - broker.stop(); - broker = null; - } - } + @Override + protected void tearDown() throws Exception { + super.tearDown(); + for (int i = 0; i < numberOfConsumers; i++) { + consumers[i].shutDown(); + } + for (int i = 0; i < numberofProducers; i++) { + producers[i].shutDown(); + } + if (broker != null) { + broker.stop(); + broker = null; + } + } - protected Destination createDestination(Session s, String destinationName) throws JMSException { - return s.createTopic(destinationName); - } + protected Destination createDestination(Session s, String destinationName) throws JMSException { + return s.createTopic(destinationName); + } - /** - * Factory method to create a new broker - * - * @throws Exception - */ - protected BrokerService createBroker(String uri) throws Exception { - BrokerService answer = new BrokerService(); - configureBroker(answer, uri); - answer.start(); - return answer; - } + /** + * Factory method to create a new broker + * + * @throws Exception + */ + protected BrokerService createBroker(String uri) throws Exception { + BrokerService answer = new BrokerService(); + configureBroker(answer, uri); + answer.start(); + return answer; + } - protected PerfProducer createProducer(ConnectionFactory fac, Destination dest, int number, byte[] payload) throws JMSException { - return new PerfProducer(fac, dest, payload); - } + protected PerfProducer createProducer(ConnectionFactory fac, + Destination dest, + int number, + byte[] payload) throws JMSException { + return new PerfProducer(fac, dest, payload); + } - protected PerfConsumer createConsumer(ConnectionFactory fac, Destination dest, int number) throws JMSException { - return new PerfConsumer(fac, dest); - } + protected PerfConsumer createConsumer(ConnectionFactory fac, Destination dest, int number) throws JMSException { + return new PerfConsumer(fac, dest); + } - protected void configureBroker(BrokerService answer, String uri) throws Exception { - answer.setDeleteAllMessagesOnStartup(true); - answer.addConnector(uri); - answer.setUseShutdownHook(false); - } + protected void configureBroker(BrokerService answer, String uri) throws Exception { + answer.setDeleteAllMessagesOnStartup(true); + answer.addConnector(uri); + answer.setUseShutdownHook(false); + } - protected ActiveMQConnectionFactory createConnectionFactory(String uri) throws Exception { - return new ActiveMQConnectionFactory(uri); - } + protected ActiveMQConnectionFactory createConnectionFactory(String uri) throws Exception { + return new ActiveMQConnectionFactory(uri); + } - public void testPerformance() throws JMSException, InterruptedException { - for (int i = 0; i < totalNumberOfConsumers; i++) { - consumers[i].start(); - } - for (int i = 0; i < totalNumberOfProducers; i++) { - producers[i].start(); - } - LOG.info("Sampling performance " + sampleCount + " times at a " + sampleInternal + " ms interval."); - for (int i = 0; i < sampleCount; i++) { - Thread.sleep(sampleInternal); - dumpProducerRate(); - dumpConsumerRate(); - } - for (int i = 0; i < totalNumberOfProducers; i++) { - producers[i].stop(); - } - for (int i = 0; i < totalNumberOfConsumers; i++) { - consumers[i].stop(); - } - } + public void testPerformance() throws JMSException, InterruptedException { + for (int i = 0; i < totalNumberOfConsumers; i++) { + consumers[i].start(); + } + for (int i = 0; i < totalNumberOfProducers; i++) { + producers[i].start(); + } + LOG.info("Sampling performance " + sampleCount + " times at a " + sampleInternal + " ms interval."); + for (int i = 0; i < sampleCount; i++) { + Thread.sleep(sampleInternal); + dumpProducerRate(); + dumpConsumerRate(); + } + for (int i = 0; i < totalNumberOfProducers; i++) { + producers[i].stop(); + } + for (int i = 0; i < totalNumberOfConsumers; i++) { + consumers[i].stop(); + } + } - @SuppressWarnings("unused") - protected void dumpProducerRate() { - int totalRate = 0; - int totalCount = 0; - String producerString = "Producers:"; - for (int i = 0; i < producers.length; i++) { - PerfRate rate = producers[i].getRate().cloneAndReset(); - totalRate += rate.getRate(); - totalCount += rate.getTotalCount(); - producerString += "[" + i + ":" + rate.getRate() + "," + rate.getTotalCount() + "];"; - } - if (producers != null && producers.length > 0) { - int avgRate = totalRate / producers.length; - System.out.println("Avg producer rate = " + avgRate + " msg/sec | Total rate = " + totalRate + ", sent = " + totalCount); - // System.out.println(producerString); - } - } + @SuppressWarnings("unused") + protected void dumpProducerRate() { + int totalRate = 0; + int totalCount = 0; + String producerString = "Producers:"; + for (int i = 0; i < producers.length; i++) { + PerfRate rate = producers[i].getRate().cloneAndReset(); + totalRate += rate.getRate(); + totalCount += rate.getTotalCount(); + producerString += "[" + i + ":" + rate.getRate() + "," + rate.getTotalCount() + "];"; + } + if (producers != null && producers.length > 0) { + int avgRate = totalRate / producers.length; + System.out.println("Avg producer rate = " + avgRate + " msg/sec | Total rate = " + totalRate + ", sent = " + totalCount); + // System.out.println(producerString); + } + } - protected void dumpConsumerRate() { - int totalRate = 0; - int totalCount = 0; - String consumerString = "Consumers:"; - for (int i = 0; i < consumers.length; i++) { - PerfRate rate = consumers[i].getRate().cloneAndReset(); - totalRate += rate.getRate(); - totalCount += rate.getTotalCount(); - consumerString += "[" + i + ":" + rate.getRate() + "," + rate.getTotalCount() + "];"; - } - if (consumers != null && consumers.length > 0) { - int avgRate = totalRate / consumers.length; - System.out.println("Avg consumer rate = " + avgRate + " msg/sec | Total rate = " + totalRate + ", received = " + totalCount); - System.out.println(consumerString); - } - } + protected void dumpConsumerRate() { + int totalRate = 0; + int totalCount = 0; + String consumerString = "Consumers:"; + for (int i = 0; i < consumers.length; i++) { + PerfRate rate = consumers[i].getRate().cloneAndReset(); + totalRate += rate.getRate(); + totalCount += rate.getTotalCount(); + consumerString += "[" + i + ":" + rate.getRate() + "," + rate.getTotalCount() + "];"; + } + if (consumers != null && consumers.length > 0) { + int avgRate = totalRate / consumers.length; + System.out.println("Avg consumer rate = " + avgRate + " msg/sec | Total rate = " + totalRate + ", received = " + totalCount); + System.out.println(consumerString); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SlowConsumer.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SlowConsumer.java index 913e86a096..ab82167359 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SlowConsumer.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SlowConsumer.java @@ -25,26 +25,28 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class SlowConsumer extends PerfConsumer { - private static final transient Logger LOG = LoggerFactory.getLogger(SlowConsumer.class); - public SlowConsumer(ConnectionFactory fac, Destination dest, String consumerName) throws JMSException { - super(fac, dest, consumerName); - } + private static final transient Logger LOG = LoggerFactory.getLogger(SlowConsumer.class); - public SlowConsumer(ConnectionFactory fac, Destination dest) throws JMSException { - super(fac, dest, null); - } + public SlowConsumer(ConnectionFactory fac, Destination dest, String consumerName) throws JMSException { + super(fac, dest, consumerName); + } - public void onMessage(Message msg) { - super.onMessage(msg); - LOG.debug("GOT A MSG " + msg); - try { - Thread.sleep(10000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } + public SlowConsumer(ConnectionFactory fac, Destination dest) throws JMSException { + super(fac, dest, null); + } + + public void onMessage(Message msg) { + super.onMessage(msg); + LOG.debug("GOT A MSG " + msg); + try { + Thread.sleep(10000); + } + catch (InterruptedException e) { + e.printStackTrace(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SlowConsumerTopicTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SlowConsumerTopicTest.java index 8c87aa8842..645e8ceddb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SlowConsumerTopicTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SlowConsumerTopicTest.java @@ -20,6 +20,7 @@ import javax.jms.ConnectionFactory; import javax.jms.DeliveryMode; import javax.jms.Destination; import javax.jms.JMSException; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQPrefetchPolicy; import org.apache.activemq.broker.BrokerService; @@ -28,47 +29,49 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; /** - * + * */ public class SlowConsumerTopicTest extends SimpleTopicTest { - protected PerfConsumer[] slowConsumers; - - protected void setUp() throws Exception { - - playloadSize = 10 * 1024; - super.setUp(); - } - + protected PerfConsumer[] slowConsumers; - protected PerfConsumer createConsumer(ConnectionFactory fac, Destination dest, int number) throws JMSException { - PerfConsumer result = new SlowConsumer(fac, dest); - return result; - } + protected void setUp() throws Exception { - protected PerfProducer createProducer(ConnectionFactory fac, Destination dest, int number, byte[] payload) throws JMSException { - PerfProducer result = super.createProducer(fac, dest, number, payload); - result.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - result.setSleep(10); - return result; - } + playloadSize = 10 * 1024; + super.setUp(); + } - protected BrokerService createBroker(String url) throws Exception { - Resource resource = new ClassPathResource("org/apache/activemq/perf/slowConsumerBroker.xml"); - System.err.println("CREATE BROKER FROM " + resource); - BrokerFactoryBean factory = new BrokerFactoryBean(resource); - factory.afterPropertiesSet(); - BrokerService broker = factory.getBroker(); - - broker.start(); - return broker; - } + protected PerfConsumer createConsumer(ConnectionFactory fac, Destination dest, int number) throws JMSException { + PerfConsumer result = new SlowConsumer(fac, dest); + return result; + } - protected ActiveMQConnectionFactory createConnectionFactory(String uri) throws Exception { - ActiveMQConnectionFactory result = super.createConnectionFactory(uri); - ActiveMQPrefetchPolicy policy = new ActiveMQPrefetchPolicy(); - policy.setTopicPrefetch(10); - result.setPrefetchPolicy(policy); - return result; - } + protected PerfProducer createProducer(ConnectionFactory fac, + Destination dest, + int number, + byte[] payload) throws JMSException { + PerfProducer result = super.createProducer(fac, dest, number, payload); + result.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + result.setSleep(10); + return result; + } + + protected BrokerService createBroker(String url) throws Exception { + Resource resource = new ClassPathResource("org/apache/activemq/perf/slowConsumerBroker.xml"); + System.err.println("CREATE BROKER FROM " + resource); + BrokerFactoryBean factory = new BrokerFactoryBean(resource); + factory.afterPropertiesSet(); + BrokerService broker = factory.getBroker(); + + broker.start(); + return broker; + } + + protected ActiveMQConnectionFactory createConnectionFactory(String uri) throws Exception { + ActiveMQConnectionFactory result = super.createConnectionFactory(uri); + ActiveMQPrefetchPolicy policy = new ActiveMQPrefetchPolicy(); + policy.setTopicPrefetch(10); + result.setPrefetchPolicy(policy); + return result; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SlowDurableConsumerTopicTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SlowDurableConsumerTopicTest.java index c71cc5ab2e..b827ee3cfc 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SlowDurableConsumerTopicTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SlowDurableConsumerTopicTest.java @@ -21,15 +21,15 @@ import javax.jms.Destination; import javax.jms.JMSException; /** - * + * */ public class SlowDurableConsumerTopicTest extends SlowConsumerTopicTest { - protected PerfConsumer[] slowConsumers; - protected int numberOfSlowConsumers = 1; + protected PerfConsumer[] slowConsumers; + protected int numberOfSlowConsumers = 1; - protected PerfConsumer createSlowConsumer(ConnectionFactory fac, Destination dest, int number) throws JMSException { - return new SlowConsumer(fac, dest, "durableSlowConsumer" + number); - } + protected PerfConsumer createSlowConsumer(ConnectionFactory fac, Destination dest, int number) throws JMSException { + return new SlowConsumer(fac, dest, "durableSlowConsumer" + number); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/TemporaryTopicMemoryAllocationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/TemporaryTopicMemoryAllocationTest.java index c379b9c6ad..98464ca214 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/TemporaryTopicMemoryAllocationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/TemporaryTopicMemoryAllocationTest.java @@ -24,11 +24,12 @@ import javax.jms.Session; * */ public class TemporaryTopicMemoryAllocationTest extends MemoryAllocationTest { - public TemporaryTopicMemoryAllocationTest() { - super(); - } - protected Destination getDestination(Session session) throws JMSException { - return session.createTemporaryTopic(); - } + public TemporaryTopicMemoryAllocationTest() { + super(); + } + + protected Destination getDestination(Session session) throws JMSException { + return session.createTemporaryTopic(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/plugin/BrokerStatisticsPluginTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/plugin/BrokerStatisticsPluginTest.java index b2e4bddfe5..04bbebed52 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/plugin/BrokerStatisticsPluginTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/plugin/BrokerStatisticsPluginTest.java @@ -39,176 +39,176 @@ import org.slf4j.LoggerFactory; /** * A BrokerStatisticsPluginTest * A testcase for https://issues.apache.org/activemq/browse/AMQ-2379 - * */ -public class BrokerStatisticsPluginTest extends TestCase{ - private static final Logger LOG = LoggerFactory.getLogger(BrokerStatisticsPluginTest.class); +public class BrokerStatisticsPluginTest extends TestCase { - private Connection connection; - private BrokerService broker; + private static final Logger LOG = LoggerFactory.getLogger(BrokerStatisticsPluginTest.class); - public void testBrokerStats() throws Exception{ - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue replyTo = session.createTemporaryQueue(); - MessageConsumer consumer = session.createConsumer(replyTo); - Queue query = session.createQueue(StatisticsBroker.STATS_BROKER_PREFIX); - MessageProducer producer = session.createProducer(query); - Message msg = session.createMessage(); - msg.setJMSReplyTo(replyTo); - producer.send(msg); - MapMessage reply = (MapMessage) consumer.receive(10*1000); - assertNotNull(reply); - assertTrue(reply.getMapNames().hasMoreElements()); - assertTrue(reply.getJMSTimestamp() > 0); - assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority()); + private Connection connection; + private BrokerService broker; + + public void testBrokerStats() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue replyTo = session.createTemporaryQueue(); + MessageConsumer consumer = session.createConsumer(replyTo); + Queue query = session.createQueue(StatisticsBroker.STATS_BROKER_PREFIX); + MessageProducer producer = session.createProducer(query); + Message msg = session.createMessage(); + msg.setJMSReplyTo(replyTo); + producer.send(msg); + MapMessage reply = (MapMessage) consumer.receive(10 * 1000); + assertNotNull(reply); + assertTrue(reply.getMapNames().hasMoreElements()); + assertTrue(reply.getJMSTimestamp() > 0); + assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority()); /* for (Enumeration e = reply.getMapNames();e.hasMoreElements();) { String name = e.nextElement().toString(); System.err.println(name+"="+reply.getObject(name)); } */ - } + } - public void testBrokerStatsReset() throws Exception{ - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue replyTo = session.createTemporaryQueue(); - MessageConsumer consumer = session.createConsumer(replyTo); - Queue testQueue = session.createQueue("Test.Queue"); - Queue query = session.createQueue(StatisticsBroker.STATS_BROKER_PREFIX); - MessageProducer producer = session.createProducer(null); + public void testBrokerStatsReset() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue replyTo = session.createTemporaryQueue(); + MessageConsumer consumer = session.createConsumer(replyTo); + Queue testQueue = session.createQueue("Test.Queue"); + Queue query = session.createQueue(StatisticsBroker.STATS_BROKER_PREFIX); + MessageProducer producer = session.createProducer(null); - producer.send(testQueue, session.createMessage()); + producer.send(testQueue, session.createMessage()); - Message msg = session.createMessage(); - msg.setJMSReplyTo(replyTo); - producer.send(query, msg); - MapMessage reply = (MapMessage) consumer.receive(10*1000); - assertNotNull(reply); - assertTrue(reply.getMapNames().hasMoreElements()); - assertTrue(reply.getLong("enqueueCount") >= 1); + Message msg = session.createMessage(); + msg.setJMSReplyTo(replyTo); + producer.send(query, msg); + MapMessage reply = (MapMessage) consumer.receive(10 * 1000); + assertNotNull(reply); + assertTrue(reply.getMapNames().hasMoreElements()); + assertTrue(reply.getLong("enqueueCount") >= 1); - msg = session.createMessage(); - msg.setBooleanProperty(StatisticsBroker.STATS_BROKER_RESET_HEADER, true); - msg.setJMSReplyTo(replyTo); - producer.send(query, msg); - reply = (MapMessage) consumer.receive(10*1000); - assertNotNull(reply); - assertTrue(reply.getMapNames().hasMoreElements()); - assertEquals(0, reply.getLong("enqueueCount")); - assertTrue(reply.getJMSTimestamp() > 0); - assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority()); - } + msg = session.createMessage(); + msg.setBooleanProperty(StatisticsBroker.STATS_BROKER_RESET_HEADER, true); + msg.setJMSReplyTo(replyTo); + producer.send(query, msg); + reply = (MapMessage) consumer.receive(10 * 1000); + assertNotNull(reply); + assertTrue(reply.getMapNames().hasMoreElements()); + assertEquals(0, reply.getLong("enqueueCount")); + assertTrue(reply.getJMSTimestamp() > 0); + assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority()); + } - public void testDestinationStats() throws Exception{ - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue replyTo = session.createTemporaryQueue(); - MessageConsumer consumer = session.createConsumer(replyTo); - Queue testQueue = session.createQueue("Test.Queue"); - MessageProducer producer = session.createProducer(null); - Queue query = session.createQueue(StatisticsBroker.STATS_DESTINATION_PREFIX + testQueue.getQueueName()); - Message msg = session.createMessage(); + public void testDestinationStats() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue replyTo = session.createTemporaryQueue(); + MessageConsumer consumer = session.createConsumer(replyTo); + Queue testQueue = session.createQueue("Test.Queue"); + MessageProducer producer = session.createProducer(null); + Queue query = session.createQueue(StatisticsBroker.STATS_DESTINATION_PREFIX + testQueue.getQueueName()); + Message msg = session.createMessage(); - producer.send(testQueue,msg); + producer.send(testQueue, msg); - msg.setJMSReplyTo(replyTo); - producer.send(query,msg); - MapMessage reply = (MapMessage) consumer.receive(10 * 1000); - assertNotNull(reply); - assertTrue(reply.getMapNames().hasMoreElements()); - assertTrue(reply.getJMSTimestamp() > 0); - assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority()); + msg.setJMSReplyTo(replyTo); + producer.send(query, msg); + MapMessage reply = (MapMessage) consumer.receive(10 * 1000); + assertNotNull(reply); + assertTrue(reply.getMapNames().hasMoreElements()); + assertTrue(reply.getJMSTimestamp() > 0); + assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority()); /* for (Enumeration e = reply.getMapNames();e.hasMoreElements();) { String name = e.nextElement().toString(); System.err.println(name+"="+reply.getObject(name)); } */ - } + } - public void testDestinationStatsWithDot() throws Exception{ - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue replyTo = session.createTemporaryQueue(); - MessageConsumer consumer = session.createConsumer(replyTo); - Queue testQueue = session.createQueue("Test.Queue"); - MessageProducer producer = session.createProducer(null); - Queue query = session.createQueue(StatisticsBroker.STATS_DESTINATION_PREFIX + "." + testQueue.getQueueName()); - Message msg = session.createMessage(); + public void testDestinationStatsWithDot() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue replyTo = session.createTemporaryQueue(); + MessageConsumer consumer = session.createConsumer(replyTo); + Queue testQueue = session.createQueue("Test.Queue"); + MessageProducer producer = session.createProducer(null); + Queue query = session.createQueue(StatisticsBroker.STATS_DESTINATION_PREFIX + "." + testQueue.getQueueName()); + Message msg = session.createMessage(); - producer.send(testQueue,msg); + producer.send(testQueue, msg); - msg.setJMSReplyTo(replyTo); - producer.send(query,msg); - MapMessage reply = (MapMessage) consumer.receive(10 * 1000); - assertNotNull(reply); - assertTrue(reply.getMapNames().hasMoreElements()); - assertTrue(reply.getJMSTimestamp() > 0); - assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority()); + msg.setJMSReplyTo(replyTo); + producer.send(query, msg); + MapMessage reply = (MapMessage) consumer.receive(10 * 1000); + assertNotNull(reply); + assertTrue(reply.getMapNames().hasMoreElements()); + assertTrue(reply.getJMSTimestamp() > 0); + assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority()); /* for (Enumeration e = reply.getMapNames();e.hasMoreElements();) { String name = e.nextElement().toString(); System.err.println(name+"="+reply.getObject(name)); } */ - } + } - @SuppressWarnings("unused") - public void testSubscriptionStats() throws Exception{ - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue replyTo = session.createTemporaryQueue(); - MessageConsumer consumer = session.createConsumer(replyTo); - Queue testQueue = session.createQueue("Test.Queue"); - MessageConsumer testConsumer = session.createConsumer(testQueue); - MessageProducer producer = session.createProducer(null); - Queue query = session.createQueue(StatisticsBroker.STATS_SUBSCRIPTION_PREFIX); - Message msg = session.createMessage(); + @SuppressWarnings("unused") + public void testSubscriptionStats() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue replyTo = session.createTemporaryQueue(); + MessageConsumer consumer = session.createConsumer(replyTo); + Queue testQueue = session.createQueue("Test.Queue"); + MessageConsumer testConsumer = session.createConsumer(testQueue); + MessageProducer producer = session.createProducer(null); + Queue query = session.createQueue(StatisticsBroker.STATS_SUBSCRIPTION_PREFIX); + Message msg = session.createMessage(); - producer.send(testQueue,msg); + producer.send(testQueue, msg); - msg.setJMSReplyTo(replyTo); - producer.send(query,msg); - MapMessage reply = (MapMessage) consumer.receive(10 * 1000); - assertNotNull(reply); - assertTrue(reply.getMapNames().hasMoreElements()); - assertTrue(reply.getJMSTimestamp() > 0); - assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority()); + msg.setJMSReplyTo(replyTo); + producer.send(query, msg); + MapMessage reply = (MapMessage) consumer.receive(10 * 1000); + assertNotNull(reply); + assertTrue(reply.getMapNames().hasMoreElements()); + assertTrue(reply.getJMSTimestamp() > 0); + assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority()); /*for (Enumeration e = reply.getMapNames();e.hasMoreElements();) { String name = e.nextElement().toString(); System.err.println(name+"="+reply.getObject(name)); }*/ - } + } - @Override - protected void setUp() throws Exception { - broker = createBroker(); - ConnectionFactory factory = new ActiveMQConnectionFactory(broker.getTransportConnectorURIsAsMap().get("tcp")); - connection = factory.createConnection(); - connection.start(); - } + @Override + protected void setUp() throws Exception { + broker = createBroker(); + ConnectionFactory factory = new ActiveMQConnectionFactory(broker.getTransportConnectorURIsAsMap().get("tcp")); + connection = factory.createConnection(); + connection.start(); + } - @Override - protected void tearDown() throws Exception{ - if (this.connection != null) { - this.connection.close(); - } - if (this.broker!=null) { - this.broker.stop(); - } - } + @Override + protected void tearDown() throws Exception { + if (this.connection != null) { + this.connection.close(); + } + if (this.broker != null) { + this.broker.stop(); + } + } - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - BrokerPlugin[] plugins = new BrokerPlugin[1]; - plugins[0] = new StatisticsBrokerPlugin(); - answer.setPlugins(plugins); - answer.setDeleteAllMessagesOnStartup(true); - answer.addConnector("tcp://localhost:0"); - answer.start(); - return answer; - } + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + BrokerPlugin[] plugins = new BrokerPlugin[1]; + plugins[0] = new StatisticsBrokerPlugin(); + answer.setPlugins(plugins); + answer.setDeleteAllMessagesOnStartup(true); + answer.addConnector("tcp://localhost:0"); + answer.start(); + return answer; + } - protected BrokerService createBroker(String uri) throws Exception { - LOG.info("Loading broker configuration from the classpath with URI: " + uri); - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } + protected BrokerService createBroker(String uri) throws Exception { + LOG.info("Loading broker configuration from the classpath with URI: " + uri); + return BrokerFactory.createBroker(new URI("xbean:" + uri)); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/pool/JmsSendReceiveTwoConnectionsWithSenderUsingPoolTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/pool/JmsSendReceiveTwoConnectionsWithSenderUsingPoolTest.java index 05ba17790a..dc0a3a62d0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/pool/JmsSendReceiveTwoConnectionsWithSenderUsingPoolTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/pool/JmsSendReceiveTwoConnectionsWithSenderUsingPoolTest.java @@ -25,23 +25,24 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class JmsSendReceiveTwoConnectionsWithSenderUsingPoolTest extends JmsTopicSendReceiveWithTwoConnectionsTest { - protected static final Logger LOG = LoggerFactory.getLogger(JmsSendReceiveTwoConnectionsWithSenderUsingPoolTest.class); - protected PooledConnectionFactory senderConnectionFactory = new PooledConnectionFactory("vm://localhost?broker.persistent=false"); - protected Connection createSendConnection() throws Exception { - return senderConnectionFactory.createConnection(); - } + protected static final Logger LOG = LoggerFactory.getLogger(JmsSendReceiveTwoConnectionsWithSenderUsingPoolTest.class); + protected PooledConnectionFactory senderConnectionFactory = new PooledConnectionFactory("vm://localhost?broker.persistent=false"); - protected void setUp() throws Exception { - verbose = true; - super.setUp(); - } + protected Connection createSendConnection() throws Exception { + return senderConnectionFactory.createConnection(); + } - protected void tearDown() throws Exception { - super.tearDown(); - senderConnectionFactory.stop(); - } + protected void setUp() throws Exception { + verbose = true; + super.setUp(); + } + + protected void tearDown() throws Exception { + super.tearDown(); + senderConnectionFactory.stop(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/AMQ4889Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/AMQ4889Test.java index 8ee85e099e..94505958fa 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/AMQ4889Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/AMQ4889Test.java @@ -17,7 +17,6 @@ package org.apache.activemq.proxy; - import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerPlugin; import org.apache.activemq.broker.BrokerService; @@ -43,93 +42,95 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; public class AMQ4889Test { - protected static final Logger LOG = LoggerFactory.getLogger(AMQ4889Test.class); - public static final String USER = "user"; - public static final String GOOD_USER_PASSWORD = "password"; - public static final String WRONG_PASSWORD = "wrongPassword"; - public static final String PROXY_URI = "tcp://localhost:6002"; - public static final String LOCAL_URI = "tcp://localhost:6001"; + protected static final Logger LOG = LoggerFactory.getLogger(AMQ4889Test.class); - protected BrokerService brokerService; - private ProxyConnector proxyConnector; - protected TransportConnector transportConnector; - protected ConnectionFactory connectionFactory; + public static final String USER = "user"; + public static final String GOOD_USER_PASSWORD = "password"; + public static final String WRONG_PASSWORD = "wrongPassword"; + public static final String PROXY_URI = "tcp://localhost:6002"; + public static final String LOCAL_URI = "tcp://localhost:6001"; - private static final Integer ITERATIONS = 100; + protected BrokerService brokerService; + private ProxyConnector proxyConnector; + protected TransportConnector transportConnector; + protected ConnectionFactory connectionFactory; - protected BrokerService createBroker() throws Exception { - brokerService = new BrokerService(); - brokerService.setPersistent(false); + private static final Integer ITERATIONS = 100; - ArrayList plugins = new ArrayList(); - BrokerPlugin authenticationPlugin = configureAuthentication(); - plugins.add(authenticationPlugin); - BrokerPlugin[] array = new BrokerPlugin[plugins.size()]; - brokerService.setPlugins(plugins.toArray(array)); + protected BrokerService createBroker() throws Exception { + brokerService = new BrokerService(); + brokerService.setPersistent(false); - transportConnector = brokerService.addConnector(LOCAL_URI); - proxyConnector = new ProxyConnector(); - proxyConnector.setName("proxy"); - proxyConnector.setBind(new URI(PROXY_URI)); - proxyConnector.setRemote(new URI(LOCAL_URI)); - brokerService.addProxyConnector(proxyConnector); + ArrayList plugins = new ArrayList(); + BrokerPlugin authenticationPlugin = configureAuthentication(); + plugins.add(authenticationPlugin); + BrokerPlugin[] array = new BrokerPlugin[plugins.size()]; + brokerService.setPlugins(plugins.toArray(array)); - brokerService.start(); - brokerService.waitUntilStarted(); + transportConnector = brokerService.addConnector(LOCAL_URI); + proxyConnector = new ProxyConnector(); + proxyConnector.setName("proxy"); + proxyConnector.setBind(new URI(PROXY_URI)); + proxyConnector.setRemote(new URI(LOCAL_URI)); + brokerService.addProxyConnector(proxyConnector); - return brokerService; - } + brokerService.start(); + brokerService.waitUntilStarted(); - protected BrokerPlugin configureAuthentication() throws Exception { - List users = new ArrayList(); - users.add(new AuthenticationUser(USER, GOOD_USER_PASSWORD, "users")); - SimpleAuthenticationPlugin authenticationPlugin = new SimpleAuthenticationPlugin(users); + return brokerService; + } - return authenticationPlugin; - } + protected BrokerPlugin configureAuthentication() throws Exception { + List users = new ArrayList(); + users.add(new AuthenticationUser(USER, GOOD_USER_PASSWORD, "users")); + SimpleAuthenticationPlugin authenticationPlugin = new SimpleAuthenticationPlugin(users); - @Before - public void setUp() throws Exception { - brokerService = createBroker(); - connectionFactory = new ActiveMQConnectionFactory(PROXY_URI); - } + return authenticationPlugin; + } - @After - public void tearDown() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - } + @Before + public void setUp() throws Exception { + brokerService = createBroker(); + connectionFactory = new ActiveMQConnectionFactory(PROXY_URI); + } + @After + public void tearDown() throws Exception { + brokerService.stop(); + brokerService.waitUntilStopped(); + } - @Test(timeout = 1 * 60 * 1000) - public void testForConnectionLeak() throws Exception { - Integer expectedConnectionCount = 0; - for (int i=0; i < ITERATIONS; i++) { - try { - if (i % 2 == 0) { - LOG.debug("Iteration {} adding bad connection", i); - Connection connection = connectionFactory.createConnection(USER, WRONG_PASSWORD); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - fail("createSession should fail"); - } else { - LOG.debug("Iteration {} adding good connection", i); - Connection connection = connectionFactory.createConnection(USER, GOOD_USER_PASSWORD); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - expectedConnectionCount++; - } - // - } catch (JMSSecurityException e) { + @Test(timeout = 1 * 60 * 1000) + public void testForConnectionLeak() throws Exception { + Integer expectedConnectionCount = 0; + for (int i = 0; i < ITERATIONS; i++) { + try { + if (i % 2 == 0) { + LOG.debug("Iteration {} adding bad connection", i); + Connection connection = connectionFactory.createConnection(USER, WRONG_PASSWORD); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + fail("createSession should fail"); } - LOG.debug("Iteration {} Connections? {}", i, proxyConnector.getConnectionCount()); - } - final Integer val = expectedConnectionCount; - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return val.equals(proxyConnector.getConnectionCount()); + else { + LOG.debug("Iteration {} adding good connection", i); + Connection connection = connectionFactory.createConnection(USER, GOOD_USER_PASSWORD); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + expectedConnectionCount++; } - }, 20); - assertEquals(val, proxyConnector.getConnectionCount()); - } + // + } + catch (JMSSecurityException e) { + } + LOG.debug("Iteration {} Connections? {}", i, proxyConnector.getConnectionCount()); + } + final Integer val = expectedConnectionCount; + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return val.equals(proxyConnector.getConnectionCount()); + } + }, 20); + assertEquals(val, proxyConnector.getConnectionCount()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/ProxyConnectorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/ProxyConnectorTest.java index bf14a05bf2..acb7ee4cc3 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/ProxyConnectorTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/ProxyConnectorTest.java @@ -19,6 +19,7 @@ package org.apache.activemq.proxy; import javax.jms.DeliveryMode; import junit.framework.Test; + import org.apache.activemq.broker.StubConnection; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ConnectionInfo; @@ -29,75 +30,76 @@ import org.apache.activemq.command.SessionInfo; public class ProxyConnectorTest extends ProxyTestSupport { - public ActiveMQDestination destination; - public byte destinationType; - public int deliveryMode; + public ActiveMQDestination destination; + public byte destinationType; + public int deliveryMode; - public static Test suite() { - return suite(ProxyConnectorTest.class); - } + public static Test suite() { + return suite(ProxyConnectorTest.class); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - } + public void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); + } - public void initCombosForTestSendAndConsume() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); - } + public void initCombosForTestSendAndConsume() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); + } - public void testSendAndConsume() throws Exception { + public void testSendAndConsume() throws Exception { - // Start a producer on local broker using the proxy - StubConnection connection1 = createProxyConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo); + // Start a producer on local broker using the proxy + StubConnection connection1 = createProxyConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ProducerInfo producerInfo = createProducerInfo(sessionInfo1); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.send(producerInfo); - destination = createDestinationInfo(connection1, connectionInfo1, destinationType); - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - connection1.send(consumerInfo1); + destination = createDestinationInfo(connection1, connectionInfo1, destinationType); + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + connection1.send(consumerInfo1); - // Start a consumer on a remote broker using a proxy connection. - StubConnection connection2 = createRemoteProxyConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); + // Start a consumer on a remote broker using a proxy connection. + StubConnection connection2 = createRemoteProxyConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); - connection2.send(consumerInfo2); + ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); + connection2.send(consumerInfo2); - // Give broker enough time to receive and register the consumer info - // Either that or make consumer retroactive - try { - Thread.sleep(2000); - } catch (Exception e) { - e.printStackTrace(); - } + // Give broker enough time to receive and register the consumer info + // Either that or make consumer retroactive + try { + Thread.sleep(2000); + } + catch (Exception e) { + e.printStackTrace(); + } - // Send the message to the local broker. - connection1.request(createMessage(producerInfo, destination, deliveryMode)); + // Send the message to the local broker. + connection1.request(createMessage(producerInfo, destination, deliveryMode)); - // Verify that the message Was sent to the remote broker and the local - // broker. - Message m; - m = receiveMessage(connection1); - assertNotNull(m); - assertNoMessagesLeft(connection1); + // Verify that the message Was sent to the remote broker and the local + // broker. + Message m; + m = receiveMessage(connection1); + assertNotNull(m); + assertNoMessagesLeft(connection1); - m = receiveMessage(connection2); - assertNotNull(m); - assertNoMessagesLeft(connection2); + m = receiveMessage(connection2); + assertNotNull(m); + assertNoMessagesLeft(connection2); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/ProxyFailoverTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/ProxyFailoverTest.java index db0a664b60..79dc784c23 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/ProxyFailoverTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/ProxyFailoverTest.java @@ -17,6 +17,7 @@ package org.apache.activemq.proxy; import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.util.ConsumerThread; @@ -30,68 +31,68 @@ import java.net.URI; public class ProxyFailoverTest extends TestCase { - BrokerService proxyBroker; - BrokerService remoteBroker; + BrokerService proxyBroker; + BrokerService remoteBroker; - @Override - protected void setUp() throws Exception { - startRemoteBroker(true); - proxyBroker = new BrokerService(); - ProxyConnector connector = new ProxyConnector(); - connector.setBind(new URI("tcp://localhost:51618")); - connector.setProxyToLocalBroker(false); - connector.setRemote(new URI("failover:(tcp://localhost:61616)")); - proxyBroker.addProxyConnector(connector); - proxyBroker.setPersistent(false); - proxyBroker.setUseJmx(false); - proxyBroker.start(); - proxyBroker.waitUntilStarted(); - } + @Override + protected void setUp() throws Exception { + startRemoteBroker(true); + proxyBroker = new BrokerService(); + ProxyConnector connector = new ProxyConnector(); + connector.setBind(new URI("tcp://localhost:51618")); + connector.setProxyToLocalBroker(false); + connector.setRemote(new URI("failover:(tcp://localhost:61616)")); + proxyBroker.addProxyConnector(connector); + proxyBroker.setPersistent(false); + proxyBroker.setUseJmx(false); + proxyBroker.start(); + proxyBroker.waitUntilStarted(); + } - @Override - protected void tearDown() throws Exception { - proxyBroker.stop(); - proxyBroker.waitUntilStopped(); - remoteBroker.stop(); - remoteBroker.waitUntilStopped(); - } + @Override + protected void tearDown() throws Exception { + proxyBroker.stop(); + proxyBroker.waitUntilStopped(); + remoteBroker.stop(); + remoteBroker.waitUntilStopped(); + } - public void testFailover() throws Exception { - ActiveMQConnectionFactory producerFactory = new ActiveMQConnectionFactory("failover:(tcp://localhost:61616,tcp://localhost:61626)?randomize=false"); - Connection producerConnection = producerFactory.createConnection(); - producerConnection.start(); - Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ProducerThread producer = new ProducerThread(producerSession, producerSession.createQueue("ProxyTest")); - producer.setSleep(10); - producer.start(); + public void testFailover() throws Exception { + ActiveMQConnectionFactory producerFactory = new ActiveMQConnectionFactory("failover:(tcp://localhost:61616,tcp://localhost:61626)?randomize=false"); + Connection producerConnection = producerFactory.createConnection(); + producerConnection.start(); + Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ProducerThread producer = new ProducerThread(producerSession, producerSession.createQueue("ProxyTest")); + producer.setSleep(10); + producer.start(); - ActiveMQConnectionFactory consumerFactory = new ActiveMQConnectionFactory("tcp://localhost:51618"); - Connection consumerConnection = consumerFactory.createConnection(); - consumerConnection.start(); - Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ConsumerThread consumer = new ConsumerThread(consumerSession, consumerSession.createQueue("ProxyTest")); - consumer.start(); + ActiveMQConnectionFactory consumerFactory = new ActiveMQConnectionFactory("tcp://localhost:51618"); + Connection consumerConnection = consumerFactory.createConnection(); + consumerConnection.start(); + Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ConsumerThread consumer = new ConsumerThread(consumerSession, consumerSession.createQueue("ProxyTest")); + consumer.start(); - TimeUnit.SECONDS.sleep(15); + TimeUnit.SECONDS.sleep(15); - remoteBroker.stop(); - remoteBroker.waitUntilStopped(); - startRemoteBroker(false); + remoteBroker.stop(); + remoteBroker.waitUntilStopped(); + startRemoteBroker(false); - producer.join(); - consumer.join(); + producer.join(); + consumer.join(); - assertEquals(1000, consumer.getReceived()); - } + assertEquals(1000, consumer.getReceived()); + } - protected void startRemoteBroker(boolean delete) throws Exception { - remoteBroker = new BrokerService(); - remoteBroker.addConnector("tcp://localhost:61616"); - if (delete) { - remoteBroker.deleteAllMessages(); - } - remoteBroker.setUseJmx(false); - remoteBroker.start(); - remoteBroker.waitUntilStarted(); - } + protected void startRemoteBroker(boolean delete) throws Exception { + remoteBroker = new BrokerService(); + remoteBroker.addConnector("tcp://localhost:61616"); + if (delete) { + remoteBroker.deleteAllMessages(); + } + remoteBroker.setUseJmx(false); + remoteBroker.start(); + remoteBroker.waitUntilStarted(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/ProxyTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/ProxyTestSupport.java index 2c884ec7ca..7f0af125a6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/ProxyTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/ProxyTestSupport.java @@ -31,107 +31,107 @@ import org.apache.activemq.usage.SystemUsage; public class ProxyTestSupport extends BrokerTestSupport { - protected ArrayList connections = new ArrayList(); + protected ArrayList connections = new ArrayList(); - protected TransportConnector connector; + protected TransportConnector connector; - protected PersistenceAdapter remotePersistenceAdapter; - protected BrokerService remoteBroker; - protected SystemUsage remoteMemoryManager; - protected TransportConnector remoteConnector; - private ProxyConnector proxyConnector; - private ProxyConnector remoteProxyConnector; + protected PersistenceAdapter remotePersistenceAdapter; + protected BrokerService remoteBroker; + protected SystemUsage remoteMemoryManager; + protected TransportConnector remoteConnector; + private ProxyConnector proxyConnector; + private ProxyConnector remoteProxyConnector; - protected BrokerService createBroker() throws Exception { - BrokerService service = new BrokerService(); - service.setBrokerName("broker1"); - service.setPersistent(false); - service.setUseJmx(false); + protected BrokerService createBroker() throws Exception { + BrokerService service = new BrokerService(); + service.setBrokerName("broker1"); + service.setPersistent(false); + service.setUseJmx(false); - connector = service.addConnector(getLocalURI()); - proxyConnector = new ProxyConnector(); - proxyConnector.setName("proxy"); - proxyConnector.setBind(new URI(getLocalProxyURI())); - proxyConnector.setRemote(new URI("fanout:static://" + getRemoteURI())); - service.addProxyConnector(proxyConnector); + connector = service.addConnector(getLocalURI()); + proxyConnector = new ProxyConnector(); + proxyConnector.setName("proxy"); + proxyConnector.setBind(new URI(getLocalProxyURI())); + proxyConnector.setRemote(new URI("fanout:static://" + getRemoteURI())); + service.addProxyConnector(proxyConnector); - return service; - } + return service; + } - protected BrokerService createRemoteBroker() throws Exception { - BrokerService service = new BrokerService(); - service.setBrokerName("broker2"); - service.setPersistent(false); - service.setUseJmx(false); + protected BrokerService createRemoteBroker() throws Exception { + BrokerService service = new BrokerService(); + service.setBrokerName("broker2"); + service.setPersistent(false); + service.setUseJmx(false); - remoteConnector = service.addConnector(getRemoteURI()); - remoteProxyConnector = new ProxyConnector(); - remoteProxyConnector.setName("remoteProxy"); - remoteProxyConnector.setBind(new URI(getRemoteProxyURI())); - remoteProxyConnector.setRemote(new URI("fanout:static://" + getLocalURI())); - service.addProxyConnector(remoteProxyConnector); + remoteConnector = service.addConnector(getRemoteURI()); + remoteProxyConnector = new ProxyConnector(); + remoteProxyConnector.setName("remoteProxy"); + remoteProxyConnector.setBind(new URI(getRemoteProxyURI())); + remoteProxyConnector.setRemote(new URI("fanout:static://" + getLocalURI())); + service.addProxyConnector(remoteProxyConnector); - return service; - } + return service; + } - protected void setUp() throws Exception { - super.setUp(); - remoteBroker = createRemoteBroker(); - remoteBroker.start(); - } + protected void setUp() throws Exception { + super.setUp(); + remoteBroker = createRemoteBroker(); + remoteBroker.start(); + } - protected void tearDown() throws Exception { - for (Iterator iter = connections.iterator(); iter.hasNext();) { - StubConnection connection = iter.next(); - connection.stop(); - iter.remove(); - } - remoteBroker.stop(); - super.tearDown(); - } + protected void tearDown() throws Exception { + for (Iterator iter = connections.iterator(); iter.hasNext(); ) { + StubConnection connection = iter.next(); + connection.stop(); + iter.remove(); + } + remoteBroker.stop(); + super.tearDown(); + } - protected String getRemoteURI() { - return "tcp://localhost:6171"; - } + protected String getRemoteURI() { + return "tcp://localhost:6171"; + } - protected String getLocalURI() { - return "tcp://localhost:6161"; - } + protected String getLocalURI() { + return "tcp://localhost:6161"; + } - protected String getRemoteProxyURI() { - return "tcp://localhost:6162"; - } + protected String getRemoteProxyURI() { + return "tcp://localhost:6162"; + } - protected String getLocalProxyURI() { - return "tcp://localhost:6172"; - } + protected String getLocalProxyURI() { + return "tcp://localhost:6172"; + } - protected StubConnection createConnection() throws Exception { - Transport transport = TransportFactory.connect(connector.getServer().getConnectURI()); - StubConnection connection = new StubConnection(transport); - connections.add(connection); - return connection; - } + protected StubConnection createConnection() throws Exception { + Transport transport = TransportFactory.connect(connector.getServer().getConnectURI()); + StubConnection connection = new StubConnection(transport); + connections.add(connection); + return connection; + } - protected StubConnection createRemoteConnection() throws Exception { - Transport transport = TransportFactory.connect(remoteConnector.getServer().getConnectURI()); - StubConnection connection = new StubConnection(transport); - connections.add(connection); - return connection; - } + protected StubConnection createRemoteConnection() throws Exception { + Transport transport = TransportFactory.connect(remoteConnector.getServer().getConnectURI()); + StubConnection connection = new StubConnection(transport); + connections.add(connection); + return connection; + } - protected StubConnection createProxyConnection() throws Exception { - Transport transport = TransportFactory.connect(proxyConnector.getServer().getConnectURI()); - StubConnection connection = new StubConnection(transport); - connections.add(connection); - return connection; - } + protected StubConnection createProxyConnection() throws Exception { + Transport transport = TransportFactory.connect(proxyConnector.getServer().getConnectURI()); + StubConnection connection = new StubConnection(transport); + connections.add(connection); + return connection; + } - protected StubConnection createRemoteProxyConnection() throws Exception { - Transport transport = TransportFactory.connect(remoteProxyConnector.getServer().getConnectURI()); - StubConnection connection = new StubConnection(transport); - connections.add(connection); - return connection; - } + protected StubConnection createRemoteProxyConnection() throws Exception { + Transport transport = TransportFactory.connect(remoteProxyConnector.getServer().getConnectURI()); + StubConnection connection = new StubConnection(transport); + connections.add(connection); + return connection; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AbstractCachedLDAPAuthorizationMapLegacyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AbstractCachedLDAPAuthorizationMapLegacyTest.java index 86165f5fe7..5ca32d7d97 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AbstractCachedLDAPAuthorizationMapLegacyTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AbstractCachedLDAPAuthorizationMapLegacyTest.java @@ -52,383 +52,378 @@ import org.junit.Test; public abstract class AbstractCachedLDAPAuthorizationMapLegacyTest extends AbstractLdapTestUnit { - static final GroupPrincipal GUESTS = new GroupPrincipal("guests"); - static final GroupPrincipal USERS = new GroupPrincipal("users"); - static final GroupPrincipal ADMINS = new GroupPrincipal("admins"); + static final GroupPrincipal GUESTS = new GroupPrincipal("guests"); + static final GroupPrincipal USERS = new GroupPrincipal("users"); + static final GroupPrincipal ADMINS = new GroupPrincipal("admins"); - protected LdapConnection connection; - protected SimpleCachedLDAPAuthorizationMap map; + protected LdapConnection connection; + protected SimpleCachedLDAPAuthorizationMap map; - @Before - public void setup() throws Exception { - connection = getLdapConnection(); - map = createMap(); - } + @Before + public void setup() throws Exception { + connection = getLdapConnection(); + map = createMap(); + } - @After - public void cleanup() throws Exception { - if (connection != null) { - try { - connection.close(); - } catch (IOException e) { - // Ignore + @After + public void cleanup() throws Exception { + if (connection != null) { + try { + connection.close(); + } + catch (IOException e) { + // Ignore + } + } + + if (map != null) { + map.destroy(); + } + } + + @Test + public void testQuery() throws Exception { + map.query(); + Set readACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); + assertEquals("set size: " + readACLs, 2, readACLs.size()); + assertTrue("Contains admin group", readACLs.contains(ADMINS)); + assertTrue("Contains users group", readACLs.contains(USERS)); + + Set failedACLs = map.getReadACLs(new ActiveMQQueue("FAILED")); + assertEquals("set size: " + failedACLs, 0, failedACLs.size()); + } + + @Test + public void testSynchronousUpdate() throws Exception { + map.setRefreshInterval(1); + map.query(); + Set readACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); + assertEquals("set size: " + readACLs, 2, readACLs.size()); + assertTrue("Contains admin group", readACLs.contains(ADMINS)); + assertTrue("Contains users group", readACLs.contains(USERS)); + + Set failedACLs = map.getReadACLs(new ActiveMQQueue("FAILED")); + assertEquals("set size: " + failedACLs, 0, failedACLs.size()); + + LdifReader reader = new LdifReader(getRemoveLdif()); + + for (LdifEntry entry : reader) { + connection.delete(entry.getDn()); + } + + reader.close(); + + assertTrue("did not get expected size. ", Wait.waitFor(new Wait.Condition() { + + @Override + public boolean isSatisified() throws Exception { + return map.getReadACLs(new ActiveMQQueue("TEST.FOO")).size() == 0; + } + })); + + assertNull(map.getTempDestinationReadACLs()); + assertNull(map.getTempDestinationWriteACLs()); + assertNull(map.getTempDestinationAdminACLs()); + } + + @Test + public void testWildcards() throws Exception { + map.query(); + Set fooACLs = map.getReadACLs(new ActiveMQQueue("FOO.1")); + assertEquals("set size: " + fooACLs, 2, fooACLs.size()); + assertTrue("Contains admin group", fooACLs.contains(ADMINS)); + assertTrue("Contains users group", fooACLs.contains(USERS)); + + Set barACLs = map.getReadACLs(new ActiveMQQueue("BAR.2")); + assertEquals("set size: " + barACLs, 2, barACLs.size()); + assertTrue("Contains admin group", barACLs.contains(ADMINS)); + assertTrue("Contains users group", barACLs.contains(USERS)); + } + + @Test + public void testAdvisory() throws Exception { + map.query(); + Set readACLs = map.getReadACLs(new ActiveMQTopic("ActiveMQ.Advisory.Connection")); + assertEquals("set size: " + readACLs, 2, readACLs.size()); + assertTrue("Contains admin group", readACLs.contains(ADMINS)); + assertTrue("Contains users group", readACLs.contains(USERS)); + } + + @Test + public void testTemporary() throws Exception { + map.query(); + + Thread.sleep(1000); + Set readACLs = map.getTempDestinationReadACLs(); + assertEquals("set size: " + readACLs, 2, readACLs.size()); + assertTrue("Contains admin group", readACLs.contains(ADMINS)); + assertTrue("Contains users group", readACLs.contains(USERS)); + } + + @Test + public void testAdd() throws Exception { + map.query(); + + Set failedACLs = map.getReadACLs(new ActiveMQQueue("FAILED")); + assertEquals("set size: " + failedACLs, 0, failedACLs.size()); + + LdifReader reader = new LdifReader(getAddLdif()); + + for (LdifEntry entry : reader) { + connection.add(entry.getEntry()); + } + + reader.close(); + + Thread.sleep(2000); + + failedACLs = map.getReadACLs(new ActiveMQQueue("FAILED")); + assertEquals("set size: " + failedACLs, 2, failedACLs.size()); + } + + @Test + public void testRemove() throws Exception { + map.query(); + + Set failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); + assertEquals("set size: " + failedACLs, 2, failedACLs.size()); + + LdifReader reader = new LdifReader(getRemoveLdif()); + + for (LdifEntry entry : reader) { + connection.delete(entry.getDn()); + } + + reader.close(); + Thread.sleep(2000); + + failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); + assertEquals("set size: " + failedACLs, 0, failedACLs.size()); + + assertTrue(map.getTempDestinationReadACLs() == null || map.getTempDestinationReadACLs().isEmpty()); + assertTrue(map.getTempDestinationWriteACLs() == null || map.getTempDestinationWriteACLs().isEmpty()); + assertTrue(map.getTempDestinationAdminACLs() == null || map.getTempDestinationAdminACLs().isEmpty()); + } + + @Test + public void testRenameDestination() throws Exception { + map.query(); + + // Test for a destination rename + Set failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); + assertEquals("set size: " + failedACLs, 2, failedACLs.size()); + + connection.rename(new Dn("cn=TEST.FOO," + getQueueBaseDn()), new Rdn("cn=TEST.BAR")); + + Thread.sleep(2000); + + failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); + assertEquals("set size: " + failedACLs, 0, failedACLs.size()); + + failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.BAR")); + assertEquals("set size: " + failedACLs, 2, failedACLs.size()); + } + + @Test + public void testRenamePermission() throws Exception { + map.query(); + + // Test for a permission rename + connection.delete(new Dn("cn=Read,cn=TEST.FOO," + getQueueBaseDn())); + + Thread.sleep(2000); + + Set failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); + assertEquals("set size: " + failedACLs, 0, failedACLs.size()); + + failedACLs = map.getWriteACLs(new ActiveMQQueue("TEST.FOO")); + assertEquals("set size: " + failedACLs, 2, failedACLs.size()); + + connection.rename(new Dn("cn=Write,cn=TEST.FOO," + getQueueBaseDn()), new Rdn("cn=Read")); + + Thread.sleep(2000); + + failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); + assertEquals("set size: " + failedACLs, 2, failedACLs.size()); + + failedACLs = map.getWriteACLs(new ActiveMQQueue("TEST.FOO")); + assertEquals("set size: " + failedACLs, 0, failedACLs.size()); + } + + @Test + public void testChange() throws Exception { + map.query(); + + // Change permission entry + Set failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); + assertEquals("set size: " + failedACLs, 2, failedACLs.size()); + + Dn dn = new Dn("cn=read,cn=TEST.FOO," + getQueueBaseDn()); + + ModifyRequest request = new ModifyRequestImpl(); + request.setName(dn); + setupModifyRequest(request); + + connection.modify(request); + + Thread.sleep(2000); + + failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); + assertEquals("set size: " + failedACLs, 1, failedACLs.size()); + + // Change destination entry + request = new ModifyRequestImpl(); + request.setName(new Dn("cn=TEST.FOO," + getQueueBaseDn())); + request.add("description", "This is a description! In fact, it is a very good description."); + + connection.modify(request); + + Thread.sleep(2000); + + failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); + assertEquals("set size: " + failedACLs, 1, failedACLs.size()); + } + + @Test + public void testRestartAsync() throws Exception { + testRestart(false); + } + + @Test + public void testRestartSync() throws Exception { + testRestart(true); + } + + public void testRestart(final boolean sync) throws Exception { + if (sync) { + // ldap connection can be slow to close + map.setRefreshInterval(1000); + } + map.query(); + + Set failedACLs = map.getReadACLs(new ActiveMQQueue("FAILED")); + assertEquals("set size: " + failedACLs, 0, failedACLs.size()); + + failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); + assertEquals("set size: " + failedACLs, 2, failedACLs.size()); + + getLdapServer().stop(); + + // wait for the context to be closed + // as we can't rely on ldar server isStarted() + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + if (sync) { + return !map.isContextAlive(); } - } - - if (map != null) { - map.destroy(); - } - } - - @Test - public void testQuery() throws Exception { - map.query(); - Set readACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + readACLs, 2, readACLs.size()); - assertTrue("Contains admin group", readACLs.contains(ADMINS)); - assertTrue("Contains users group", readACLs.contains(USERS)); - - Set failedACLs = map.getReadACLs(new ActiveMQQueue("FAILED")); - assertEquals("set size: " + failedACLs, 0, failedACLs.size()); - } - - @Test - public void testSynchronousUpdate() throws Exception { - map.setRefreshInterval(1); - map.query(); - Set readACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + readACLs, 2, readACLs.size()); - assertTrue("Contains admin group", readACLs.contains(ADMINS)); - assertTrue("Contains users group", readACLs.contains(USERS)); - - Set failedACLs = map.getReadACLs(new ActiveMQQueue("FAILED")); - assertEquals("set size: " + failedACLs, 0, failedACLs.size()); - - LdifReader reader = new LdifReader(getRemoveLdif()); - - for (LdifEntry entry : reader) { - connection.delete(entry.getDn()); - } - - reader.close(); - - assertTrue("did not get expected size. ", Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - return map.getReadACLs(new ActiveMQQueue("TEST.FOO")).size() == 0; + else { + return map.context == null; } - })); + } + }); - assertNull(map.getTempDestinationReadACLs()); - assertNull(map.getTempDestinationWriteACLs()); - assertNull(map.getTempDestinationAdminACLs()); - } + failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); + assertEquals("set size: " + failedACLs, 2, failedACLs.size()); - @Test - public void testWildcards() throws Exception { - map.query(); - Set fooACLs = map.getReadACLs(new ActiveMQQueue("FOO.1")); - assertEquals("set size: " + fooACLs, 2, fooACLs.size()); - assertTrue("Contains admin group", fooACLs.contains(ADMINS)); - assertTrue("Contains users group", fooACLs.contains(USERS)); + getLdapServer().start(); - Set barACLs = map.getReadACLs(new ActiveMQQueue("BAR.2")); - assertEquals("set size: " + barACLs, 2, barACLs.size()); - assertTrue("Contains admin group", barACLs.contains(ADMINS)); - assertTrue("Contains users group", barACLs.contains(USERS)); - } + Thread.sleep(2000); - @Test - public void testAdvisory() throws Exception { - map.query(); - Set readACLs = map.getReadACLs(new ActiveMQTopic("ActiveMQ.Advisory.Connection")); - assertEquals("set size: " + readACLs, 2, readACLs.size()); - assertTrue("Contains admin group", readACLs.contains(ADMINS)); - assertTrue("Contains users group", readACLs.contains(USERS)); - } + connection = getLdapConnection(); - @Test - public void testTemporary() throws Exception { - map.query(); + LdifReader reader = new LdifReader(getAddLdif()); - Thread.sleep(1000); - Set readACLs = map.getTempDestinationReadACLs(); - assertEquals("set size: " + readACLs, 2, readACLs.size()); - assertTrue("Contains admin group", readACLs.contains(ADMINS)); - assertTrue("Contains users group", readACLs.contains(USERS)); - } + for (LdifEntry entry : reader) { + connection.add(entry.getEntry()); + } - @Test - public void testAdd() throws Exception { - map.query(); + reader.close(); - Set failedACLs = map.getReadACLs(new ActiveMQQueue("FAILED")); - assertEquals("set size: " + failedACLs, 0, failedACLs.size()); + assertTrue("did not get expected size. ", Wait.waitFor(new Wait.Condition() { - LdifReader reader = new LdifReader(getAddLdif()); + @Override + public boolean isSatisified() throws Exception { + return map.getReadACLs(new ActiveMQQueue("FAILED")).size() == 2; + } + })); + } - for (LdifEntry entry : reader) { - connection.add(entry.getEntry()); - } + protected SimpleCachedLDAPAuthorizationMap createMap() { + return new SimpleCachedLDAPAuthorizationMap(); + } - reader.close(); + protected abstract InputStream getAddLdif(); - Thread.sleep(2000); + protected abstract InputStream getRemoveLdif(); - failedACLs = map.getReadACLs(new ActiveMQQueue("FAILED")); - assertEquals("set size: " + failedACLs, 2, failedACLs.size()); - } + protected void setupModifyRequest(ModifyRequest request) { + request.remove("member", "cn=users"); + } - @Test - public void testRemove() throws Exception { - map.query(); + protected abstract String getQueueBaseDn(); - Set failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 2, failedACLs.size()); + protected abstract LdapConnection getLdapConnection() throws Exception; - LdifReader reader = new LdifReader(getRemoveLdif()); + public static void cleanAndLoad(String deleteFromDn, + String ldifResourcePath, + String ldapHost, + int ldapPort, + String ldapUser, + String ldapPass, + DirContext context) throws Exception { + // Cleanup everything used for testing. + List dns = new LinkedList(); + dns.add(deleteFromDn); - for (LdifEntry entry : reader) { - connection.delete(entry.getDn()); - } + while (!dns.isEmpty()) { + String name = dns.get(dns.size() - 1); + Context currentContext = (Context) context.lookup(name); + NamingEnumeration namingEnum = currentContext.list(""); - reader.close(); - Thread.sleep(2000); - - failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 0, failedACLs.size()); - - assertTrue(map.getTempDestinationReadACLs() == null || map.getTempDestinationReadACLs().isEmpty()); - assertTrue(map.getTempDestinationWriteACLs() == null || map.getTempDestinationWriteACLs().isEmpty()); - assertTrue(map.getTempDestinationAdminACLs() == null || map.getTempDestinationAdminACLs().isEmpty()); - } - - @Test - public void testRenameDestination() throws Exception { - map.query(); - - // Test for a destination rename - Set failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 2, failedACLs.size()); - - connection.rename(new Dn("cn=TEST.FOO," + getQueueBaseDn()), - new Rdn("cn=TEST.BAR")); - - Thread.sleep(2000); - - failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 0, failedACLs.size()); - - - failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.BAR")); - assertEquals("set size: " + failedACLs, 2, failedACLs.size()); - } - - @Test - public void testRenamePermission() throws Exception { - map.query(); - - // Test for a permission rename - connection.delete(new Dn("cn=Read,cn=TEST.FOO," + getQueueBaseDn())); - - Thread.sleep(2000); - - Set failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 0, failedACLs.size()); - - failedACLs = map.getWriteACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 2, failedACLs.size()); - - connection.rename(new Dn("cn=Write,cn=TEST.FOO," + getQueueBaseDn()), - new Rdn("cn=Read")); - - Thread.sleep(2000); - - failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 2, failedACLs.size()); - - failedACLs = map.getWriteACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 0, failedACLs.size()); - } - - @Test - public void testChange() throws Exception { - map.query(); - - // Change permission entry - Set failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 2, failedACLs.size()); - - Dn dn = new Dn("cn=read,cn=TEST.FOO," + getQueueBaseDn()); - - ModifyRequest request = new ModifyRequestImpl(); - request.setName(dn); - setupModifyRequest(request); - - connection.modify(request); - - Thread.sleep(2000); - - failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 1, failedACLs.size()); - - // Change destination entry - request = new ModifyRequestImpl(); - request.setName(new Dn("cn=TEST.FOO," + getQueueBaseDn())); - request.add("description", "This is a description! In fact, it is a very good description."); - - connection.modify(request); - - Thread.sleep(2000); - - failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 1, failedACLs.size()); - } - - @Test - public void testRestartAsync() throws Exception { - testRestart(false); - } - - @Test - public void testRestartSync() throws Exception { - testRestart(true); - } - - public void testRestart(final boolean sync) throws Exception { - if (sync) { - // ldap connection can be slow to close - map.setRefreshInterval(1000); - } - map.query(); - - Set failedACLs = map.getReadACLs(new ActiveMQQueue("FAILED")); - assertEquals("set size: " + failedACLs, 0, failedACLs.size()); - - failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 2, failedACLs.size()); - - getLdapServer().stop(); - - // wait for the context to be closed - // as we can't rely on ldar server isStarted() - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - if (sync) { - return !map.isContextAlive(); - } else { - return map.context == null; - } + if (namingEnum.hasMore()) { + while (namingEnum.hasMore()) { + dns.add(namingEnum.next().getNameInNamespace()); } - }); + } + else { + context.unbind(name); + dns.remove(dns.size() - 1); + } + } - failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 2, failedACLs.size()); + // A bit of a hacked approach to loading an LDIF into OpenLDAP since there isn't an easy way to do it + // otherwise. This approach invokes the command line tool programmatically but has + // to short-circuit the call to System.exit that the command line tool makes when it finishes. + // We are assuming that there isn't already a security manager in place. + final SecurityManager securityManager = new SecurityManager() { - getLdapServer().start(); - - Thread.sleep(2000); - - connection = getLdapConnection(); - - LdifReader reader = new LdifReader(getAddLdif()); - - for (LdifEntry entry : reader) { - connection.add(entry.getEntry()); - } - - reader.close(); - - assertTrue("did not get expected size. ", Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - return map.getReadACLs(new ActiveMQQueue("FAILED")).size() == 2; + @Override + public void checkPermission(java.security.Permission permission) { + if (permission.getName().contains("exitVM")) { + throw new SecurityException("System.exit calls disabled for the moment."); } - })); - } + } + }; - protected SimpleCachedLDAPAuthorizationMap createMap() { - return new SimpleCachedLDAPAuthorizationMap(); - } + System.setSecurityManager(securityManager); - protected abstract InputStream getAddLdif(); + File file = new File(AbstractCachedLDAPAuthorizationMapLegacyTest.class.getClassLoader().getResource(ldifResourcePath).toURI()); - protected abstract InputStream getRemoveLdif(); + Class clazz = Class.forName("LDAPModify"); + Method mainMethod = clazz.getMethod("main", String[].class); - protected void setupModifyRequest(ModifyRequest request) { - request.remove("member", "cn=users"); - } + try { + mainMethod.invoke(null, new Object[]{new String[]{"-v", "-h", ldapHost, "-p", String.valueOf(ldapPort), "-D", ldapUser, "-w", ldapPass, "-a", "-f", file.toString()}}); + } + catch (InvocationTargetException e) { + if (!(e.getTargetException() instanceof SecurityException)) { + throw e; + } + } - protected abstract String getQueueBaseDn(); - - protected abstract LdapConnection getLdapConnection() throws Exception; - - public static void cleanAndLoad(String deleteFromDn, String ldifResourcePath, - String ldapHost, int ldapPort, String ldapUser, String ldapPass, - DirContext context) throws Exception { - // Cleanup everything used for testing. - List dns = new LinkedList(); - dns.add(deleteFromDn); - - while (!dns.isEmpty()) { - String name = dns.get(dns.size() - 1); - Context currentContext = (Context) context.lookup(name); - NamingEnumeration namingEnum = currentContext.list(""); - - if (namingEnum.hasMore()) { - while (namingEnum.hasMore()) { - dns.add(namingEnum.next().getNameInNamespace()); - } - } else { - context.unbind(name); - dns.remove(dns.size() - 1); - } - } - - // A bit of a hacked approach to loading an LDIF into OpenLDAP since there isn't an easy way to do it - // otherwise. This approach invokes the command line tool programmatically but has - // to short-circuit the call to System.exit that the command line tool makes when it finishes. - // We are assuming that there isn't already a security manager in place. - final SecurityManager securityManager = new SecurityManager() { - - @Override - public void checkPermission(java.security.Permission permission) { - if (permission.getName().contains("exitVM")) { - throw new SecurityException("System.exit calls disabled for the moment."); - } - } - }; - - System.setSecurityManager(securityManager); - - - File file = new File(AbstractCachedLDAPAuthorizationMapLegacyTest.class.getClassLoader().getResource( - ldifResourcePath).toURI()); - - Class clazz = Class.forName("LDAPModify"); - Method mainMethod = clazz.getMethod("main", String[].class); - - try { - mainMethod.invoke(null, new Object[] { - new String[] { - "-v", - "-h", ldapHost, - "-p", String.valueOf(ldapPort), - "-D", ldapUser, - "-w", ldapPass, - "-a", - "-f", file.toString()}}); - } catch (InvocationTargetException e) { - if (!(e.getTargetException() instanceof SecurityException)) { - throw e; - } - } - - System.setSecurityManager(null); - } + System.setSecurityManager(null); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AbstractCachedLDAPAuthorizationModuleTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AbstractCachedLDAPAuthorizationModuleTest.java index 3f52ed3ee8..a3086a5c8f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AbstractCachedLDAPAuthorizationModuleTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AbstractCachedLDAPAuthorizationModuleTest.java @@ -26,38 +26,37 @@ import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -public abstract class AbstractCachedLDAPAuthorizationModuleTest - extends AbstractCachedLDAPAuthorizationMapLegacyTest { +public abstract class AbstractCachedLDAPAuthorizationModuleTest extends AbstractCachedLDAPAuthorizationMapLegacyTest { - static final UserPrincipal JDOE = new UserPrincipal("jdoe"); + static final UserPrincipal JDOE = new UserPrincipal("jdoe"); - @Test - public void testQuery() throws Exception { - map.query(); - Set readACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOOBAR")); - assertEquals("set size: " + readACLs, 3, readACLs.size()); - assertTrue("Contains admin group", readACLs.contains(ADMINS)); - assertTrue("Contains users group", readACLs.contains(USERS)); - assertTrue("Contains jdoe user", readACLs.contains(JDOE)); + @Test + public void testQuery() throws Exception { + map.query(); + Set readACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOOBAR")); + assertEquals("set size: " + readACLs, 3, readACLs.size()); + assertTrue("Contains admin group", readACLs.contains(ADMINS)); + assertTrue("Contains users group", readACLs.contains(USERS)); + assertTrue("Contains jdoe user", readACLs.contains(JDOE)); - Set failedACLs = map.getReadACLs(new ActiveMQQueue("FAILED")); - assertEquals("set size: " + failedACLs, 0, failedACLs.size()); - - super.testQuery(); - } + Set failedACLs = map.getReadACLs(new ActiveMQQueue("FAILED")); + assertEquals("set size: " + failedACLs, 0, failedACLs.size()); - @Override - protected final void setupModifyRequest(ModifyRequest request) { - request.remove("member", getMemberAttributeValueForModifyRequest()); - } - - protected abstract String getMemberAttributeValueForModifyRequest(); + super.testQuery(); + } - @Override - protected SimpleCachedLDAPAuthorizationMap createMap() { - SimpleCachedLDAPAuthorizationMap map = super.createMap(); - map.setLegacyGroupMapping(false); - return map; - } + @Override + protected final void setupModifyRequest(ModifyRequest request) { + request.remove("member", getMemberAttributeValueForModifyRequest()); + } + + protected abstract String getMemberAttributeValueForModifyRequest(); + + @Override + protected SimpleCachedLDAPAuthorizationMap createMap() { + SimpleCachedLDAPAuthorizationMap map = super.createMap(); + map.setLegacyGroupMapping(false); + return map; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AuthorizationMapTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AuthorizationMapTest.java index b6ace87282..84753554ea 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AuthorizationMapTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AuthorizationMapTest.java @@ -21,6 +21,7 @@ import java.util.List; import java.util.Set; import junit.framework.TestCase; + import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.filter.DestinationMapEntry; import org.apache.activemq.jaas.GroupPrincipal; @@ -30,165 +31,173 @@ import org.apache.activemq.jaas.GroupPrincipal; * */ public class AuthorizationMapTest extends TestCase { - static final GroupPrincipal USERS = new GroupPrincipal("users"); - static final GroupPrincipal ADMINS = new GroupPrincipal("admins"); - static final GroupPrincipal TEMP_DESTINATION_ADMINS = new GroupPrincipal("tempDestAdmins"); - public void testAuthorizationMap() { - AuthorizationMap map = createAuthorizationMap(); + static final GroupPrincipal USERS = new GroupPrincipal("users"); + static final GroupPrincipal ADMINS = new GroupPrincipal("admins"); + static final GroupPrincipal TEMP_DESTINATION_ADMINS = new GroupPrincipal("tempDestAdmins"); - Set readACLs = map.getReadACLs(new ActiveMQQueue("USERS.FOO.BAR")); - assertEquals("set size: " + readACLs, 2, readACLs.size()); - assertTrue("Contains users group", readACLs.contains(ADMINS)); - assertTrue("Contains users group", readACLs.contains(USERS)); + public void testAuthorizationMap() { + AuthorizationMap map = createAuthorizationMap(); - } + Set readACLs = map.getReadACLs(new ActiveMQQueue("USERS.FOO.BAR")); + assertEquals("set size: " + readACLs, 2, readACLs.size()); + assertTrue("Contains users group", readACLs.contains(ADMINS)); + assertTrue("Contains users group", readACLs.contains(USERS)); - public void testCompositeDoesNotBypassAuthorizationMap() { - AuthorizationMap map = createAuthorizationMap(); + } - Set readACLs = map.getReadACLs(new ActiveMQQueue("USERS.FOO.BAR,DENIED")); - assertEquals("set size: " + readACLs, 1, readACLs.size()); - assertTrue("Contains users group", readACLs.contains(ADMINS)); - } + public void testCompositeDoesNotBypassAuthorizationMap() { + AuthorizationMap map = createAuthorizationMap(); - public void testAuthorizationMapWithTempDest() { - AuthorizationMap map = createAuthorizationMapWithTempDest(); + Set readACLs = map.getReadACLs(new ActiveMQQueue("USERS.FOO.BAR,DENIED")); + assertEquals("set size: " + readACLs, 1, readACLs.size()); + assertTrue("Contains users group", readACLs.contains(ADMINS)); + } - Set readACLs = map.getReadACLs(new ActiveMQQueue("USERS.FOO.BAR")); - assertEquals("set size: " + readACLs, 2, readACLs.size()); - assertTrue("Contains users group", readACLs.contains(ADMINS)); - assertTrue("Contains users group", readACLs.contains(USERS)); + public void testAuthorizationMapWithTempDest() { + AuthorizationMap map = createAuthorizationMapWithTempDest(); - Set tempAdminACLs = map.getTempDestinationAdminACLs(); - assertEquals("set size: " + tempAdminACLs, 1, tempAdminACLs.size()); - assertTrue("Contains users group", tempAdminACLs.contains(TEMP_DESTINATION_ADMINS)); + Set readACLs = map.getReadACLs(new ActiveMQQueue("USERS.FOO.BAR")); + assertEquals("set size: " + readACLs, 2, readACLs.size()); + assertTrue("Contains users group", readACLs.contains(ADMINS)); + assertTrue("Contains users group", readACLs.contains(USERS)); - } + Set tempAdminACLs = map.getTempDestinationAdminACLs(); + assertEquals("set size: " + tempAdminACLs, 1, tempAdminACLs.size()); + assertTrue("Contains users group", tempAdminACLs.contains(TEMP_DESTINATION_ADMINS)); - public void testWildcards() { - AuthorizationMap map = createWildcardAuthorizationMap(); + } - Set readACLs = map.getReadACLs(new ActiveMQQueue("USERS.FOO.BAR")); - assertEquals("set size: " + readACLs, 1, readACLs.size()); - assertTrue("Contains users group", readACLs.contains(ADMINS)); - assertTrue("Contains users group", readACLs.contains(USERS)); + public void testWildcards() { + AuthorizationMap map = createWildcardAuthorizationMap(); - Set writeAcls = map.getWriteACLs(new ActiveMQQueue("USERS.FOO.BAR")); - assertEquals("set size: " + writeAcls, 1, writeAcls.size()); - assertTrue("Contains users group", writeAcls.contains(ADMINS)); - assertTrue("Contains users group", writeAcls.contains(USERS)); + Set readACLs = map.getReadACLs(new ActiveMQQueue("USERS.FOO.BAR")); + assertEquals("set size: " + readACLs, 1, readACLs.size()); + assertTrue("Contains users group", readACLs.contains(ADMINS)); + assertTrue("Contains users group", readACLs.contains(USERS)); - Set adminAcls = map.getAdminACLs(new ActiveMQQueue("USERS.FOO.BAR")); - assertEquals("set size: " + adminAcls, 1, adminAcls.size()); - assertTrue("Contains users group", adminAcls.contains(ADMINS)); - assertFalse("Contains users group", adminAcls.contains(USERS)); + Set writeAcls = map.getWriteACLs(new ActiveMQQueue("USERS.FOO.BAR")); + assertEquals("set size: " + writeAcls, 1, writeAcls.size()); + assertTrue("Contains users group", writeAcls.contains(ADMINS)); + assertTrue("Contains users group", writeAcls.contains(USERS)); - Set tempAdminACLs = map.getTempDestinationAdminACLs(); - assertEquals("set size: " + tempAdminACLs, 1, tempAdminACLs.size()); - assertTrue("Contains users group", tempAdminACLs.contains(TEMP_DESTINATION_ADMINS)); - } + Set adminAcls = map.getAdminACLs(new ActiveMQQueue("USERS.FOO.BAR")); + assertEquals("set size: " + adminAcls, 1, adminAcls.size()); + assertTrue("Contains users group", adminAcls.contains(ADMINS)); + assertFalse("Contains users group", adminAcls.contains(USERS)); - protected AuthorizationMap createWildcardAuthorizationMap() { - DefaultAuthorizationMap answer = new DefaultAuthorizationMap(); + Set tempAdminACLs = map.getTempDestinationAdminACLs(); + assertEquals("set size: " + tempAdminACLs, 1, tempAdminACLs.size()); + assertTrue("Contains users group", tempAdminACLs.contains(TEMP_DESTINATION_ADMINS)); + } - List entries = new ArrayList(); + protected AuthorizationMap createWildcardAuthorizationMap() { + DefaultAuthorizationMap answer = new DefaultAuthorizationMap(); - AuthorizationEntry entry = new AuthorizationEntry(); - entry.setQueue(">"); - try { - entry.setRead("*"); - entry.setWrite("*"); - entry.setAdmin("admins"); - } catch (Exception e) { - fail(e.toString()); - } + List entries = new ArrayList(); - entries.add(entry); + AuthorizationEntry entry = new AuthorizationEntry(); + entry.setQueue(">"); + try { + entry.setRead("*"); + entry.setWrite("*"); + entry.setAdmin("admins"); + } + catch (Exception e) { + fail(e.toString()); + } - answer.setAuthorizationEntries(entries); + entries.add(entry); - TempDestinationAuthorizationEntry tEntry = new TempDestinationAuthorizationEntry(); - try { - tEntry.setAdmin("*"); - } catch (Exception e) { - fail(e.toString()); - } + answer.setAuthorizationEntries(entries); - answer.setTempDestinationAuthorizationEntry(tEntry); + TempDestinationAuthorizationEntry tEntry = new TempDestinationAuthorizationEntry(); + try { + tEntry.setAdmin("*"); + } + catch (Exception e) { + fail(e.toString()); + } - return answer; + answer.setTempDestinationAuthorizationEntry(tEntry); - } + return answer; - @SuppressWarnings("rawtypes") - protected AuthorizationMap createAuthorizationMap() { - DefaultAuthorizationMap answer = new DefaultAuthorizationMap(); + } - List entries = new ArrayList(); + @SuppressWarnings("rawtypes") + protected AuthorizationMap createAuthorizationMap() { + DefaultAuthorizationMap answer = new DefaultAuthorizationMap(); - AuthorizationEntry entry = new AuthorizationEntry(); - entry.setGroupClass("org.apache.activemq.jaas.GroupPrincipal"); - entry.setQueue(">"); - try { - entry.setRead("admins"); - } catch (Exception e) { - fail(e.toString()); - } + List entries = new ArrayList(); - entries.add(entry); - // entry using default org.apache.activemq.jaas.GroupPrincipal class - entry = new AuthorizationEntry(); - entry.setQueue("USERS.>"); - try { - entry.setRead("users"); - } catch (Exception e) { - fail(e.toString()); - } - entries.add(entry); + AuthorizationEntry entry = new AuthorizationEntry(); + entry.setGroupClass("org.apache.activemq.jaas.GroupPrincipal"); + entry.setQueue(">"); + try { + entry.setRead("admins"); + } + catch (Exception e) { + fail(e.toString()); + } - answer.setAuthorizationEntries(entries); + entries.add(entry); + // entry using default org.apache.activemq.jaas.GroupPrincipal class + entry = new AuthorizationEntry(); + entry.setQueue("USERS.>"); + try { + entry.setRead("users"); + } + catch (Exception e) { + fail(e.toString()); + } + entries.add(entry); - return answer; - } + answer.setAuthorizationEntries(entries); - @SuppressWarnings("rawtypes") - protected AuthorizationMap createAuthorizationMapWithTempDest() { - DefaultAuthorizationMap answer = new DefaultAuthorizationMap(); + return answer; + } - List entries = new ArrayList(); + @SuppressWarnings("rawtypes") + protected AuthorizationMap createAuthorizationMapWithTempDest() { + DefaultAuthorizationMap answer = new DefaultAuthorizationMap(); - AuthorizationEntry entry = new AuthorizationEntry(); - entry.setQueue(">"); - try { - entry.setRead("admins"); - } catch (Exception e) { - fail(e.toString()); - } - entries.add(entry); + List entries = new ArrayList(); - entry = new AuthorizationEntry(); - entry.setQueue("USERS.>"); - try { - entry.setRead("users"); - } catch (Exception e) { - fail(e.toString()); - } - entries.add(entry); + AuthorizationEntry entry = new AuthorizationEntry(); + entry.setQueue(">"); + try { + entry.setRead("admins"); + } + catch (Exception e) { + fail(e.toString()); + } + entries.add(entry); - answer.setAuthorizationEntries(entries); + entry = new AuthorizationEntry(); + entry.setQueue("USERS.>"); + try { + entry.setRead("users"); + } + catch (Exception e) { + fail(e.toString()); + } + entries.add(entry); - // create entry for temporary queue - TempDestinationAuthorizationEntry tEntry = new TempDestinationAuthorizationEntry(); - try { - tEntry.setAdmin("tempDestAdmins"); - } catch (Exception e) { - fail(e.toString()); - } + answer.setAuthorizationEntries(entries); - answer.setTempDestinationAuthorizationEntry(tEntry); + // create entry for temporary queue + TempDestinationAuthorizationEntry tEntry = new TempDestinationAuthorizationEntry(); + try { + tEntry.setAdmin("tempDestAdmins"); + } + catch (Exception e) { + fail(e.toString()); + } - return answer; - } + answer.setTempDestinationAuthorizationEntry(tEntry); + + return answer; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleLegacyOpenLDAPTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleLegacyOpenLDAPTest.java index 5c2764a21c..d3a46e8a92 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleLegacyOpenLDAPTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleLegacyOpenLDAPTest.java @@ -30,68 +30,66 @@ import org.junit.Test; /** * Test of the {@link SimpleCachedLDAPAuthorizationMap} that tests against a basic OpenLDAP instance. * Disabled by default because it requires external setup to provide the OpenLDAP instance. - * - * To enable, you need an OpenLDAP with a minimum of the following in the slapd.conf file: - * + * + * To enable, you need an OpenLDAP with a minimum of the following in the slapd.conf file: + * * suffix "dc=apache,dc=org" * rootdn "cn=Manager,dc=apache,dc=org" * rootpw {SSHA}+Rx8kj98q3FlK5rUkT2hAtMP5v2ImQ82 - * - * If you wish to use different settings or don't use the default port, change the constants + * + * If you wish to use different settings or don't use the default port, change the constants * below for your environment. */ @Ignore -public class CachedLDAPAuthorizationModuleLegacyOpenLDAPTest extends - AbstractCachedLDAPAuthorizationMapLegacyTest { - - protected static final String LDAP_USER = "cn=Manager,dc=apache,dc=org"; - protected static final String LDAP_PASS = "password"; - protected static final String LDAP_HOST = "localhost"; - protected static final int LDAP_PORT = 389; - - @Before - @Override - public void setup() throws Exception { - - super.setup(); - - cleanAndLoad("dc=apache,dc=org", "org/apache/activemq/security/activemq-openldap-legacy.ldif", - LDAP_HOST, LDAP_PORT, LDAP_USER, LDAP_PASS, map.open()); - } - - @Test - public void testRenameDestination() throws Exception { - // Subtree rename not implemented by OpenLDAP. - } - - protected SimpleCachedLDAPAuthorizationMap createMap() { - SimpleCachedLDAPAuthorizationMap newMap = super.createMap(); - newMap.setConnectionURL("ldap://" + LDAP_HOST + ":" + String.valueOf(LDAP_PORT)); - newMap.setConnectionUsername(LDAP_USER); - newMap.setConnectionPassword(LDAP_PASS); - // Persistent search is not supported in OpenLDAP - newMap.setRefreshInterval(10); - newMap.setQueueSearchBase("ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"); - newMap.setTopicSearchBase("ou=Topic,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"); - newMap.setTempSearchBase("ou=Temp,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"); - return newMap; - } - - protected InputStream getAddLdif() { - return getClass().getClassLoader().getResourceAsStream("org/apache/activemq/security/activemq-openldap-legacy-add.ldif"); - } - - protected InputStream getRemoveLdif() { - return getClass().getClassLoader().getResourceAsStream("org/apache/activemq/security/activemq-openldap-legacy-delete.ldif"); - } - - protected String getQueueBaseDn() { - return "ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"; - } - - protected LdapConnection getLdapConnection() throws LdapException, IOException { - LdapConnection connection = new LdapNetworkConnection(LDAP_HOST, LDAP_PORT); - connection.bind(new Dn(LDAP_USER), LDAP_PASS); - return connection; - } +public class CachedLDAPAuthorizationModuleLegacyOpenLDAPTest extends AbstractCachedLDAPAuthorizationMapLegacyTest { + + protected static final String LDAP_USER = "cn=Manager,dc=apache,dc=org"; + protected static final String LDAP_PASS = "password"; + protected static final String LDAP_HOST = "localhost"; + protected static final int LDAP_PORT = 389; + + @Before + @Override + public void setup() throws Exception { + + super.setup(); + + cleanAndLoad("dc=apache,dc=org", "org/apache/activemq/security/activemq-openldap-legacy.ldif", LDAP_HOST, LDAP_PORT, LDAP_USER, LDAP_PASS, map.open()); + } + + @Test + public void testRenameDestination() throws Exception { + // Subtree rename not implemented by OpenLDAP. + } + + protected SimpleCachedLDAPAuthorizationMap createMap() { + SimpleCachedLDAPAuthorizationMap newMap = super.createMap(); + newMap.setConnectionURL("ldap://" + LDAP_HOST + ":" + String.valueOf(LDAP_PORT)); + newMap.setConnectionUsername(LDAP_USER); + newMap.setConnectionPassword(LDAP_PASS); + // Persistent search is not supported in OpenLDAP + newMap.setRefreshInterval(10); + newMap.setQueueSearchBase("ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"); + newMap.setTopicSearchBase("ou=Topic,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"); + newMap.setTempSearchBase("ou=Temp,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"); + return newMap; + } + + protected InputStream getAddLdif() { + return getClass().getClassLoader().getResourceAsStream("org/apache/activemq/security/activemq-openldap-legacy-add.ldif"); + } + + protected InputStream getRemoveLdif() { + return getClass().getClassLoader().getResourceAsStream("org/apache/activemq/security/activemq-openldap-legacy-delete.ldif"); + } + + protected String getQueueBaseDn() { + return "ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"; + } + + protected LdapConnection getLdapConnection() throws LdapException, IOException { + LdapConnection connection = new LdapNetworkConnection(LDAP_HOST, LDAP_PORT); + connection.bind(new Dn(LDAP_USER), LDAP_PASS); + return connection; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleLegacyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleLegacyTest.java index f696cb306f..cd2e8f6f6c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleLegacyTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleLegacyTest.java @@ -29,37 +29,35 @@ import org.junit.runner.RunWith; import java.io.IOException; import java.io.InputStream; - -@RunWith( FrameworkRunner.class ) +@RunWith(FrameworkRunner.class) @CreateLdapServer(transports = {@CreateTransport(protocol = "LDAP")}) @ApplyLdifFiles( - "org/apache/activemq/security/activemq-apacheds-legacy.ldif" -) + "org/apache/activemq/security/activemq-apacheds-legacy.ldif") public class CachedLDAPAuthorizationModuleLegacyTest extends AbstractCachedLDAPAuthorizationMapLegacyTest { - @Override - protected SimpleCachedLDAPAuthorizationMap createMap() { - SimpleCachedLDAPAuthorizationMap map = super.createMap(); - map.setConnectionURL("ldap://localhost:" + getLdapServer().getPort()); - return map; - } - - protected InputStream getAddLdif() { - return getClass().getClassLoader().getResourceAsStream("org/apache/activemq/security/activemq-apacheds-legacy-add.ldif"); - } - - protected InputStream getRemoveLdif() { - return getClass().getClassLoader().getResourceAsStream("org/apache/activemq/security/activemq-apacheds-legacy-delete.ldif"); - } - - protected String getQueueBaseDn() { - return "ou=Queue,ou=Destination,ou=ActiveMQ,ou=system"; - } - - protected LdapConnection getLdapConnection() throws LdapException, IOException { - LdapConnection connection = new LdapNetworkConnection("localhost", getLdapServer().getPort()); - connection.bind(new Dn("uid=admin,ou=system"), "secret"); - return connection; - } + @Override + protected SimpleCachedLDAPAuthorizationMap createMap() { + SimpleCachedLDAPAuthorizationMap map = super.createMap(); + map.setConnectionURL("ldap://localhost:" + getLdapServer().getPort()); + return map; + } + + protected InputStream getAddLdif() { + return getClass().getClassLoader().getResourceAsStream("org/apache/activemq/security/activemq-apacheds-legacy-add.ldif"); + } + + protected InputStream getRemoveLdif() { + return getClass().getClassLoader().getResourceAsStream("org/apache/activemq/security/activemq-apacheds-legacy-delete.ldif"); + } + + protected String getQueueBaseDn() { + return "ou=Queue,ou=Destination,ou=ActiveMQ,ou=system"; + } + + protected LdapConnection getLdapConnection() throws LdapException, IOException { + LdapConnection connection = new LdapNetworkConnection("localhost", getLdapServer().getPort()); + connection.bind(new Dn("uid=admin,ou=system"), "secret"); + return connection; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleOpenLDAPTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleOpenLDAPTest.java index 6d0ca9339d..2394d61ccd 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleOpenLDAPTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleOpenLDAPTest.java @@ -30,77 +30,76 @@ import java.io.InputStream; /** * Test of the {@link SimpleCachedLDAPAuthorizationMap} that tests against a basic OpenLDAP instance. * Disabled by default because it requires external setup to provide the OpenLDAP instance. - * - * To enable, you need an OpenLDAP with a minimum of the following in the slapd.conf file: - * + * + * To enable, you need an OpenLDAP with a minimum of the following in the slapd.conf file: + * * suffix "dc=apache,dc=org" * rootdn "cn=Manager,dc=apache,dc=org" * rootpw {SSHA}+Rx8kj98q3FlK5rUkT2hAtMP5v2ImQ82 - * - * If you wish to use different settings or don't use the default port, change the constants + * + * If you wish to use different settings or don't use the default port, change the constants * below for your environment. */ @Ignore public class CachedLDAPAuthorizationModuleOpenLDAPTest extends AbstractCachedLDAPAuthorizationModuleTest { - protected static final String LDAP_USER = "cn=Manager,dc=apache,dc=org"; - protected static final String LDAP_PASS = "password"; - protected static final String LDAP_HOST = "localhost"; - protected static final int LDAP_PORT = 389; - - @Before - @Override - public void setup() throws Exception { - - super.setup(); - - cleanAndLoad("dc=apache,dc=org", "org/apache/activemq/security/activemq-openldap.ldif", - LDAP_HOST, LDAP_PORT, LDAP_USER, LDAP_PASS, map.open()); - } - - @Test - public void testRenameDestination() throws Exception { - // Subtree rename not implemented by OpenLDAP. - } - - @Override - protected SimpleCachedLDAPAuthorizationMap createMap() { - SimpleCachedLDAPAuthorizationMap newMap = super.createMap(); - newMap.setConnectionURL("ldap://" + LDAP_HOST + ":" + String.valueOf(LDAP_PORT)); - newMap.setConnectionUsername(LDAP_USER); - newMap.setConnectionPassword(LDAP_PASS); - // Persistent search is not supported in OpenLDAP - newMap.setRefreshInterval(10); - newMap.setQueueSearchBase("ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"); - newMap.setTopicSearchBase("ou=Topic,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"); - newMap.setTempSearchBase("ou=Temp,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"); - return newMap; - } - - @Override - protected InputStream getAddLdif() { - return getClass().getClassLoader().getResourceAsStream("org/apache/activemq/security/activemq-openldap-add.ldif"); - } - - @Override - protected InputStream getRemoveLdif() { - return getClass().getClassLoader().getResourceAsStream("org/apache/activemq/security/activemq-openldap-delete.ldif"); - } - - @Override - protected String getMemberAttributeValueForModifyRequest() { - return "cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"; - } - - @Override - protected String getQueueBaseDn() { - return "ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"; - } - - @Override - protected LdapConnection getLdapConnection() throws LdapException, IOException { - LdapConnection connection = new LdapNetworkConnection(LDAP_HOST, LDAP_PORT); - connection.bind(new Dn(LDAP_USER), LDAP_PASS); - return connection; - } + protected static final String LDAP_USER = "cn=Manager,dc=apache,dc=org"; + protected static final String LDAP_PASS = "password"; + protected static final String LDAP_HOST = "localhost"; + protected static final int LDAP_PORT = 389; + + @Before + @Override + public void setup() throws Exception { + + super.setup(); + + cleanAndLoad("dc=apache,dc=org", "org/apache/activemq/security/activemq-openldap.ldif", LDAP_HOST, LDAP_PORT, LDAP_USER, LDAP_PASS, map.open()); + } + + @Test + public void testRenameDestination() throws Exception { + // Subtree rename not implemented by OpenLDAP. + } + + @Override + protected SimpleCachedLDAPAuthorizationMap createMap() { + SimpleCachedLDAPAuthorizationMap newMap = super.createMap(); + newMap.setConnectionURL("ldap://" + LDAP_HOST + ":" + String.valueOf(LDAP_PORT)); + newMap.setConnectionUsername(LDAP_USER); + newMap.setConnectionPassword(LDAP_PASS); + // Persistent search is not supported in OpenLDAP + newMap.setRefreshInterval(10); + newMap.setQueueSearchBase("ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"); + newMap.setTopicSearchBase("ou=Topic,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"); + newMap.setTempSearchBase("ou=Temp,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"); + return newMap; + } + + @Override + protected InputStream getAddLdif() { + return getClass().getClassLoader().getResourceAsStream("org/apache/activemq/security/activemq-openldap-add.ldif"); + } + + @Override + protected InputStream getRemoveLdif() { + return getClass().getClassLoader().getResourceAsStream("org/apache/activemq/security/activemq-openldap-delete.ldif"); + } + + @Override + protected String getMemberAttributeValueForModifyRequest() { + return "cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"; + } + + @Override + protected String getQueueBaseDn() { + return "ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"; + } + + @Override + protected LdapConnection getLdapConnection() throws LdapException, IOException { + LdapConnection connection = new LdapNetworkConnection(LDAP_HOST, LDAP_PORT); + connection.bind(new Dn(LDAP_USER), LDAP_PASS); + return connection; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleTest.java index 5d6f2e734f..f1e43b1d17 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleTest.java @@ -27,45 +27,43 @@ import org.junit.runner.RunWith; import java.io.InputStream; - -@RunWith( FrameworkRunner.class ) +@RunWith(FrameworkRunner.class) @CreateLdapServer(transports = {@CreateTransport(protocol = "LDAP")}) @ApplyLdifFiles( - "org/apache/activemq/security/activemq-apacheds.ldif" -) + "org/apache/activemq/security/activemq-apacheds.ldif") public class CachedLDAPAuthorizationModuleTest extends AbstractCachedLDAPAuthorizationModuleTest { - @Override - protected SimpleCachedLDAPAuthorizationMap createMap() { - SimpleCachedLDAPAuthorizationMap map = super.createMap(); - map.setConnectionURL("ldap://localhost:" + getLdapServer().getPort()); - return map; - } - - @Override - protected InputStream getAddLdif() { - return getClass().getClassLoader().getResourceAsStream("org/apache/activemq/security/activemq-apacheds-add.ldif"); - } + @Override + protected SimpleCachedLDAPAuthorizationMap createMap() { + SimpleCachedLDAPAuthorizationMap map = super.createMap(); + map.setConnectionURL("ldap://localhost:" + getLdapServer().getPort()); + return map; + } - @Override - protected InputStream getRemoveLdif() { - return getClass().getClassLoader().getResourceAsStream("org/apache/activemq/security/activemq-apacheds-delete.ldif"); - } + @Override + protected InputStream getAddLdif() { + return getClass().getClassLoader().getResourceAsStream("org/apache/activemq/security/activemq-apacheds-add.ldif"); + } - @Override - protected String getMemberAttributeValueForModifyRequest() { - return "cn=users,ou=Group,ou=ActiveMQ,ou=system"; - } + @Override + protected InputStream getRemoveLdif() { + return getClass().getClassLoader().getResourceAsStream("org/apache/activemq/security/activemq-apacheds-delete.ldif"); + } - protected String getQueueBaseDn() { - return "ou=Queue,ou=Destination,ou=ActiveMQ,ou=system"; - } + @Override + protected String getMemberAttributeValueForModifyRequest() { + return "cn=users,ou=Group,ou=ActiveMQ,ou=system"; + } - @Override - protected LdapConnection getLdapConnection() throws Exception { - LdapConnection connection = new LdapNetworkConnection("localhost", getLdapServer().getPort()); - connection.bind(new Dn("uid=admin,ou=system"), "secret"); - return connection; - } + protected String getQueueBaseDn() { + return "ou=Queue,ou=Destination,ou=ActiveMQ,ou=system"; + } + + @Override + protected LdapConnection getLdapConnection() throws Exception { + LdapConnection connection = new LdapNetworkConnection("localhost", getLdapServer().getPort()); + connection.bind(new Dn("uid=admin,ou=system"), "secret"); + return connection; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPSecurityLegacyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPSecurityLegacyTest.java index 43ff99ce5e..5fe8517968 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPSecurityLegacyTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPSecurityLegacyTest.java @@ -35,94 +35,94 @@ import javax.jms.*; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; - -@RunWith( FrameworkRunner.class ) +@RunWith(FrameworkRunner.class) @CreateLdapServer(transports = {@CreateTransport(protocol = "LDAP")}) @ApplyLdifFiles( - "org/apache/activemq/security/activemq-apacheds-legacy.ldif" -) + "org/apache/activemq/security/activemq-apacheds-legacy.ldif") public class CachedLDAPSecurityLegacyTest extends AbstractLdapTestUnit { - public BrokerService broker; + public BrokerService broker; - public static LdapServer ldapServer; + public static LdapServer ldapServer; - @Before - public void setup() throws Exception { - System.setProperty("ldapPort", String.valueOf(getLdapServer().getPort())); - - broker = BrokerFactory.createBroker("xbean:org/apache/activemq/security/activemq-apacheds-legacy.xml"); - broker.start(); - broker.waitUntilStarted(); - } + @Before + public void setup() throws Exception { + System.setProperty("ldapPort", String.valueOf(getLdapServer().getPort())); - @After - public void shutdown() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } + broker = BrokerFactory.createBroker("xbean:org/apache/activemq/security/activemq-apacheds-legacy.xml"); + broker.start(); + broker.waitUntilStarted(); + } - @Test - public void testSendReceive() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - Connection conn = factory.createQueueConnection("jdoe", "sunflower"); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); - Queue queue = sess.createQueue("TEST.FOO"); + @After + public void shutdown() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + } - MessageProducer producer = sess.createProducer(queue); - MessageConsumer consumer = sess.createConsumer(queue); + @Test + public void testSendReceive() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + Connection conn = factory.createQueueConnection("jdoe", "sunflower"); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + conn.start(); + Queue queue = sess.createQueue("TEST.FOO"); - producer.send(sess.createTextMessage("test")); - Message msg = consumer.receive(1000); - assertNotNull(msg); - } + MessageProducer producer = sess.createProducer(queue); + MessageConsumer consumer = sess.createConsumer(queue); - @Test - public void testSendDenied() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - Connection conn = factory.createQueueConnection("jdoe", "sunflower"); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); - Queue queue = sess.createQueue("ADMIN.FOO"); + producer.send(sess.createTextMessage("test")); + Message msg = consumer.receive(1000); + assertNotNull(msg); + } - try { - sess.createProducer(queue); - fail("expect auth exception"); - } catch (JMSException expected) { - } - } + @Test + public void testSendDenied() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + Connection conn = factory.createQueueConnection("jdoe", "sunflower"); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + conn.start(); + Queue queue = sess.createQueue("ADMIN.FOO"); - @Test - public void testCompositeSendDenied() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - Connection conn = factory.createQueueConnection("jdoe", "sunflower"); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); - Queue queue = sess.createQueue("TEST.FOO,ADMIN.FOO"); + try { + sess.createProducer(queue); + fail("expect auth exception"); + } + catch (JMSException expected) { + } + } - try { - sess.createProducer(queue); - fail("expect auth exception"); - } catch (JMSException expected) { - } - } + @Test + public void testCompositeSendDenied() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + Connection conn = factory.createQueueConnection("jdoe", "sunflower"); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + conn.start(); + Queue queue = sess.createQueue("TEST.FOO,ADMIN.FOO"); - @Test - public void testTempDestinations() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - Connection conn = factory.createQueueConnection("jdoe", "sunflower"); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); - Queue queue = sess.createTemporaryQueue(); + try { + sess.createProducer(queue); + fail("expect auth exception"); + } + catch (JMSException expected) { + } + } - MessageProducer producer = sess.createProducer(queue); - MessageConsumer consumer = sess.createConsumer(queue); + @Test + public void testTempDestinations() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + Connection conn = factory.createQueueConnection("jdoe", "sunflower"); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + conn.start(); + Queue queue = sess.createTemporaryQueue(); - producer.send(sess.createTextMessage("test")); - Message msg = consumer.receive(1000); - assertNotNull(msg); - } + MessageProducer producer = sess.createProducer(queue); + MessageConsumer consumer = sess.createConsumer(queue); + + producer.send(sess.createTextMessage("test")); + Message msg = consumer.receive(1000); + assertNotNull(msg); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPSecurityTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPSecurityTest.java index ec22095833..4e96818e2e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPSecurityTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPSecurityTest.java @@ -24,22 +24,21 @@ import org.apache.directory.server.core.integ.FrameworkRunner; import org.junit.Before; import org.junit.runner.RunWith; -@RunWith( FrameworkRunner.class ) +@RunWith(FrameworkRunner.class) @CreateLdapServer(transports = {@CreateTransport(protocol = "LDAP")}) @ApplyLdifFiles( - "org/apache/activemq/security/activemq-apacheds.ldif" -) + "org/apache/activemq/security/activemq-apacheds.ldif") public class CachedLDAPSecurityTest extends CachedLDAPSecurityLegacyTest { - @Before - @Override - public void setup() throws Exception { - System.setProperty("ldapPort", String.valueOf(getLdapServer().getPort())); - - broker = BrokerFactory.createBroker("xbean:org/apache/activemq/security/activemq-apacheds.xml"); - broker.start(); - broker.waitUntilStarted(); - } + @Before + @Override + public void setup() throws Exception { + System.setProperty("ldapPort", String.valueOf(getLdapServer().getPort())); + + broker = BrokerFactory.createBroker("xbean:org/apache/activemq/security/activemq-apacheds.xml"); + broker.start(); + broker.waitUntilStarted(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/DoSTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/DoSTest.java index 6b55595639..135f3df342 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/DoSTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/DoSTest.java @@ -22,6 +22,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import javax.jms.Connection; import javax.jms.JMSException; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.JmsTestSupport; import org.apache.activemq.broker.BrokerFactory; @@ -40,61 +41,62 @@ import org.slf4j.LoggerFactory; public class DoSTest extends JmsTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(DoSTest.class); + private static final Logger LOG = LoggerFactory.getLogger(DoSTest.class); - public void testInvalidAuthentication() throws Throwable { + public void testInvalidAuthentication() throws Throwable { - // with failover reconnect, we don't expect this thread to complete - // but periodically the failure changes from ExceededMaximumConnectionsException on the broker - // side to a SecurityException. - // A failed to authenticated but idle connection (dos style) is aborted by the inactivity monitor - // since useKeepAlive=false + // with failover reconnect, we don't expect this thread to complete + // but periodically the failure changes from ExceededMaximumConnectionsException on the broker + // side to a SecurityException. + // A failed to authenticated but idle connection (dos style) is aborted by the inactivity monitor + // since useKeepAlive=false - final AtomicBoolean done = new AtomicBoolean(false); - Thread thread = new Thread() { - Connection connection = null; + final AtomicBoolean done = new AtomicBoolean(false); + Thread thread = new Thread() { + Connection connection = null; - public void run() { - for (int i = 0; i < 1000 && !done.get(); i++) { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(); - try { - // Bad password - connection = factory.createConnection("bad", "krap"); - connection.start(); - fail("Expected exception."); - } catch (JMSException e) { - // ignore exception and don't close - e.printStackTrace(); - } - } + public void run() { + for (int i = 0; i < 1000 && !done.get(); i++) { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(); + try { + // Bad password + connection = factory.createConnection("bad", "krap"); + connection.start(); + fail("Expected exception."); + } + catch (JMSException e) { + // ignore exception and don't close + e.printStackTrace(); + } } - }; + } + }; - thread.start(); + thread.start(); - // run dos for a while - TimeUnit.SECONDS.sleep(10); + // run dos for a while + TimeUnit.SECONDS.sleep(10); - LOG.info("trying genuine connection ..."); - // verify a valid connection can work with one of the 2 allowed connections provided it is eager! - // it could take a while as it is competing with the three other reconnect threads. - // wonder if it makes sense to serialise these reconnect attempts on an executor - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("failover:(tcp://127.0.0.1:61616)?useExponentialBackOff=false&reconnectDelay=10"); - Connection goodConnection = factory.createConnection("user", "password"); - goodConnection.start(); - goodConnection.close(); + LOG.info("trying genuine connection ..."); + // verify a valid connection can work with one of the 2 allowed connections provided it is eager! + // it could take a while as it is competing with the three other reconnect threads. + // wonder if it makes sense to serialise these reconnect attempts on an executor + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("failover:(tcp://127.0.0.1:61616)?useExponentialBackOff=false&reconnectDelay=10"); + Connection goodConnection = factory.createConnection("user", "password"); + goodConnection.start(); + goodConnection.close(); - LOG.info("giving up on DOS"); - done.set(true); - } + LOG.info("giving up on DOS"); + done.set(true); + } - protected BrokerService createBroker() throws Exception { - return createBroker("org/apache/activemq/security/dos-broker.xml"); - } + protected BrokerService createBroker() throws Exception { + return createBroker("org/apache/activemq/security/dos-broker.xml"); + } - protected BrokerService createBroker(String uri) throws Exception { - LOG.info("Loading broker configuration from the classpath with URI: " + uri); - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } + protected BrokerService createBroker(String uri) throws Exception { + LOG.info("Loading broker configuration from the classpath with URI: " + uri); + return BrokerFactory.createBroker(new URI("xbean:" + uri)); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/JaasCertificateAuthenticationBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/JaasCertificateAuthenticationBrokerTest.java index 6aa62f7a2e..72cbfc18ac 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/JaasCertificateAuthenticationBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/JaasCertificateAuthenticationBrokerTest.java @@ -36,152 +36,159 @@ import org.apache.activemq.jaas.UserPrincipal; import org.apache.activemq.transport.tcp.StubX509Certificate; public class JaasCertificateAuthenticationBrokerTest extends TestCase { - StubBroker receiveBroker; - JaasCertificateAuthenticationBroker authBroker; + StubBroker receiveBroker; - ConnectionContext connectionContext; - ConnectionInfo connectionInfo; + JaasCertificateAuthenticationBroker authBroker; - @Override - protected void setUp() throws Exception { - receiveBroker = new StubBroker(); + ConnectionContext connectionContext; + ConnectionInfo connectionInfo; - authBroker = new JaasCertificateAuthenticationBroker(receiveBroker, ""); + @Override + protected void setUp() throws Exception { + receiveBroker = new StubBroker(); - connectionContext = new ConnectionContext(); - connectionInfo = new ConnectionInfo(); + authBroker = new JaasCertificateAuthenticationBroker(receiveBroker, ""); - connectionInfo.setTransportContext(new StubX509Certificate[] {}); - } + connectionContext = new ConnectionContext(); + connectionInfo = new ConnectionInfo(); - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } + connectionInfo.setTransportContext(new StubX509Certificate[]{}); + } - private void setConfiguration(Set userNames, Set groupNames, boolean loginShouldSucceed) { - HashMap configOptions = new HashMap(); + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } - String userNamesString; - { - Iterator iter = userNames.iterator(); - userNamesString = "" + (iter.hasNext() ? iter.next() : ""); - while (iter.hasNext()) { - userNamesString += "," + iter.next(); + private void setConfiguration(Set userNames, Set groupNames, boolean loginShouldSucceed) { + HashMap configOptions = new HashMap(); + + String userNamesString; + { + Iterator iter = userNames.iterator(); + userNamesString = "" + (iter.hasNext() ? iter.next() : ""); + while (iter.hasNext()) { + userNamesString += "," + iter.next(); + } + } + + String groupNamesString = ""; + { + Iterator iter = groupNames.iterator(); + groupNamesString = "" + (iter.hasNext() ? iter.next() : ""); + while (iter.hasNext()) { + groupNamesString += "," + iter.next(); + } + } + + configOptions.put(StubLoginModule.ALLOW_LOGIN_PROPERTY, loginShouldSucceed ? "true" : "false"); + configOptions.put(StubLoginModule.USERS_PROPERTY, userNamesString); + configOptions.put(StubLoginModule.GROUPS_PROPERTY, groupNamesString); + AppConfigurationEntry configEntry = new AppConfigurationEntry("org.apache.activemq.security.StubLoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, configOptions); + + StubJaasConfiguration jaasConfig = new StubJaasConfiguration(configEntry); + + Configuration.setConfiguration(jaasConfig); + } + + public void testAddConnectionSuccess() { + String dnUserName = "dnUserName"; + + HashSet userNames = new HashSet(); + userNames.add(dnUserName); + + HashSet groupNames = new HashSet(); + groupNames.add("testGroup1"); + groupNames.add("testGroup2"); + groupNames.add("tesetGroup3"); + + setConfiguration(userNames, groupNames, true); + + try { + authBroker.addConnection(connectionContext, connectionInfo); + } + catch (Exception e) { + fail("Call to addConnection failed: " + e.getMessage()); + } + + assertEquals("Number of addConnection calls to underlying Broker must match number of calls made to " + "AuthenticationBroker.", 1, receiveBroker.addConnectionData.size()); + + ConnectionContext receivedContext = receiveBroker.addConnectionData.getFirst().connectionContext; + + assertEquals("The SecurityContext's userName must be set to that of the UserPrincipal.", dnUserName, receivedContext.getSecurityContext().getUserName()); + + Set receivedPrincipals = receivedContext.getSecurityContext().getPrincipals(); + + for (Iterator iter = receivedPrincipals.iterator(); iter.hasNext(); ) { + Principal currentPrincipal = iter.next(); + + if (currentPrincipal instanceof UserPrincipal) { + if (userNames.remove(currentPrincipal.getName())) { + // Nothing, we did good. } - } - - String groupNamesString = ""; - { - Iterator iter = groupNames.iterator(); - groupNamesString = "" + (iter.hasNext() ? iter.next() : ""); - while (iter.hasNext()) { - groupNamesString += "," + iter.next(); + else { + // Found an unknown userName. + fail("Unknown UserPrincipal found"); } - } - - configOptions.put(StubLoginModule.ALLOW_LOGIN_PROPERTY, loginShouldSucceed ? "true" : "false"); - configOptions.put(StubLoginModule.USERS_PROPERTY, userNamesString); - configOptions.put(StubLoginModule.GROUPS_PROPERTY, groupNamesString); - AppConfigurationEntry configEntry = new AppConfigurationEntry("org.apache.activemq.security.StubLoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, - configOptions); - - StubJaasConfiguration jaasConfig = new StubJaasConfiguration(configEntry); - - Configuration.setConfiguration(jaasConfig); - } - - public void testAddConnectionSuccess() { - String dnUserName = "dnUserName"; - - HashSet userNames = new HashSet(); - userNames.add(dnUserName); - - HashSet groupNames = new HashSet(); - groupNames.add("testGroup1"); - groupNames.add("testGroup2"); - groupNames.add("tesetGroup3"); - - setConfiguration(userNames, groupNames, true); - - try { - authBroker.addConnection(connectionContext, connectionInfo); - } catch (Exception e) { - fail("Call to addConnection failed: " + e.getMessage()); - } - - assertEquals("Number of addConnection calls to underlying Broker must match number of calls made to " + "AuthenticationBroker.", 1, receiveBroker.addConnectionData.size()); - - ConnectionContext receivedContext = receiveBroker.addConnectionData.getFirst().connectionContext; - - assertEquals("The SecurityContext's userName must be set to that of the UserPrincipal.", dnUserName, receivedContext.getSecurityContext().getUserName()); - - Set receivedPrincipals = receivedContext.getSecurityContext().getPrincipals(); - - for (Iterator iter = receivedPrincipals.iterator(); iter.hasNext();) { - Principal currentPrincipal = iter.next(); - - if (currentPrincipal instanceof UserPrincipal) { - if (userNames.remove(currentPrincipal.getName())) { - // Nothing, we did good. - } else { - // Found an unknown userName. - fail("Unknown UserPrincipal found"); - } - } else if (currentPrincipal instanceof GroupPrincipal) { - if (groupNames.remove(currentPrincipal.getName())) { - // Nothing, we did good. - } else { - fail("Unknown GroupPrincipal found."); - } - } else { - fail("Unexpected Principal subclass found."); + } + else if (currentPrincipal instanceof GroupPrincipal) { + if (groupNames.remove(currentPrincipal.getName())) { + // Nothing, we did good. } - } + else { + fail("Unknown GroupPrincipal found."); + } + } + else { + fail("Unexpected Principal subclass found."); + } + } - if (!userNames.isEmpty()) { - fail("Some usernames were not added as UserPrincipals"); - } + if (!userNames.isEmpty()) { + fail("Some usernames were not added as UserPrincipals"); + } - if (!groupNames.isEmpty()) { - fail("Some group names were not added as GroupPrincipals"); - } - } + if (!groupNames.isEmpty()) { + fail("Some group names were not added as GroupPrincipals"); + } + } - public void testAddConnectionFailure() { - HashSet userNames = new HashSet(); + public void testAddConnectionFailure() { + HashSet userNames = new HashSet(); - HashSet groupNames = new HashSet(); - groupNames.add("testGroup1"); - groupNames.add("testGroup2"); - groupNames.add("tesetGroup3"); + HashSet groupNames = new HashSet(); + groupNames.add("testGroup1"); + groupNames.add("testGroup2"); + groupNames.add("tesetGroup3"); - setConfiguration(userNames, groupNames, false); + setConfiguration(userNames, groupNames, false); - boolean connectFailed = false; - try { - authBroker.addConnection(connectionContext, connectionInfo); - } catch (SecurityException e) { - connectFailed = true; - } catch (Exception e) { - fail("Failed to connect for unexpected reason: " + e.getMessage()); - } + boolean connectFailed = false; + try { + authBroker.addConnection(connectionContext, connectionInfo); + } + catch (SecurityException e) { + connectFailed = true; + } + catch (Exception e) { + fail("Failed to connect for unexpected reason: " + e.getMessage()); + } - if (!connectFailed) { - fail("Unauthenticated connection allowed."); - } + if (!connectFailed) { + fail("Unauthenticated connection allowed."); + } - assertEquals("Unauthenticated connection allowed.", true, receiveBroker.addConnectionData.isEmpty()); - } + assertEquals("Unauthenticated connection allowed.", true, receiveBroker.addConnectionData.isEmpty()); + } - public void testRemoveConnection() throws Exception { - connectionContext.setSecurityContext(new StubSecurityContext()); + public void testRemoveConnection() throws Exception { + connectionContext.setSecurityContext(new StubSecurityContext()); - authBroker.removeConnection(connectionContext, connectionInfo, new Throwable()); + authBroker.removeConnection(connectionContext, connectionInfo, new Throwable()); - assertEquals("removeConnection should clear ConnectionContext.", null, connectionContext.getSecurityContext()); + assertEquals("removeConnection should clear ConnectionContext.", null, connectionContext.getSecurityContext()); - assertEquals("Incorrect number of calls to underlying broker were made.", 1, receiveBroker.removeConnectionData.size()); - } + assertEquals("Incorrect number of calls to underlying broker were made.", 1, receiveBroker.removeConnectionData.size()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/JaasDualAuthenticationBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/JaasDualAuthenticationBrokerTest.java index 7d7f3b6e71..17db0a8268 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/JaasDualAuthenticationBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/JaasDualAuthenticationBrokerTest.java @@ -47,170 +47,166 @@ import org.apache.activemq.transport.tcp.TcpTransportServer; */ public class JaasDualAuthenticationBrokerTest extends TestCase { - private static final String INSECURE_GROUP = "insecureGroup"; - private static final String INSECURE_USERNAME = "insecureUserName"; - private static final String DN_GROUP = "dnGroup"; - private static final String DN_USERNAME = "dnUserName"; + private static final String INSECURE_GROUP = "insecureGroup"; + private static final String INSECURE_USERNAME = "insecureUserName"; + private static final String DN_GROUP = "dnGroup"; + private static final String DN_USERNAME = "dnUserName"; - StubBroker receiveBroker; - JaasDualAuthenticationBroker authBroker; + StubBroker receiveBroker; + JaasDualAuthenticationBroker authBroker; - ConnectionContext connectionContext; - ConnectionInfo connectionInfo; + ConnectionContext connectionContext; + ConnectionInfo connectionInfo; - SslTransportServer sslTransportServer; - TcpTransportServer nonSslTransportServer; + SslTransportServer sslTransportServer; + TcpTransportServer nonSslTransportServer; - /** create a dual login config, for both SSL and non-SSL connections - * using the StubLoginModule - * - */ - void createLoginConfig() { - HashMap sslConfigOptions = new HashMap(); - HashMap configOptions = new HashMap(); + /** + * create a dual login config, for both SSL and non-SSL connections + * using the StubLoginModule + */ + void createLoginConfig() { + HashMap sslConfigOptions = new HashMap(); + HashMap configOptions = new HashMap(); - sslConfigOptions.put(StubLoginModule.ALLOW_LOGIN_PROPERTY, "true"); - sslConfigOptions.put(StubLoginModule.USERS_PROPERTY, DN_USERNAME); - sslConfigOptions.put(StubLoginModule.GROUPS_PROPERTY, DN_GROUP); - AppConfigurationEntry sslConfigEntry = new AppConfigurationEntry("org.apache.activemq.security.StubLoginModule", - AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, sslConfigOptions); + sslConfigOptions.put(StubLoginModule.ALLOW_LOGIN_PROPERTY, "true"); + sslConfigOptions.put(StubLoginModule.USERS_PROPERTY, DN_USERNAME); + sslConfigOptions.put(StubLoginModule.GROUPS_PROPERTY, DN_GROUP); + AppConfigurationEntry sslConfigEntry = new AppConfigurationEntry("org.apache.activemq.security.StubLoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, sslConfigOptions); - configOptions.put(StubLoginModule.ALLOW_LOGIN_PROPERTY, "true"); - configOptions.put(StubLoginModule.USERS_PROPERTY, INSECURE_USERNAME); - configOptions.put(StubLoginModule.GROUPS_PROPERTY, INSECURE_GROUP); - AppConfigurationEntry configEntry = new AppConfigurationEntry("org.apache.activemq.security.StubLoginModule", - AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, configOptions); + configOptions.put(StubLoginModule.ALLOW_LOGIN_PROPERTY, "true"); + configOptions.put(StubLoginModule.USERS_PROPERTY, INSECURE_USERNAME); + configOptions.put(StubLoginModule.GROUPS_PROPERTY, INSECURE_GROUP); + AppConfigurationEntry configEntry = new AppConfigurationEntry("org.apache.activemq.security.StubLoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, configOptions); - StubDualJaasConfiguration jaasConfig = new StubDualJaasConfiguration(configEntry, sslConfigEntry); + StubDualJaasConfiguration jaasConfig = new StubDualJaasConfiguration(configEntry, sslConfigEntry); - Configuration.setConfiguration(jaasConfig); - } + Configuration.setConfiguration(jaasConfig); + } - @Override - protected void setUp() throws Exception { - receiveBroker = new StubBroker(); + @Override + protected void setUp() throws Exception { + receiveBroker = new StubBroker(); - authBroker = new JaasDualAuthenticationBroker(receiveBroker, "activemq-domain", "activemq-ssl-domain"); + authBroker = new JaasDualAuthenticationBroker(receiveBroker, "activemq-domain", "activemq-ssl-domain"); - connectionContext = new ConnectionContext(); + connectionContext = new ConnectionContext(); - SSLServerSocket sslServerSocket = new StubSSLServerSocket(); - StubSSLSocketFactory socketFactory = new StubSSLSocketFactory(sslServerSocket); + SSLServerSocket sslServerSocket = new StubSSLServerSocket(); + StubSSLSocketFactory socketFactory = new StubSSLSocketFactory(sslServerSocket); - try { - sslTransportServer = new SslTransportServer(null, new URI("ssl://localhost:61616?needClientAuth=true"), - socketFactory); - } catch (Exception e) { - fail("Unable to create SslTransportServer."); - } - sslTransportServer.setNeedClientAuth(true); - sslTransportServer.bind(); + try { + sslTransportServer = new SslTransportServer(null, new URI("ssl://localhost:61616?needClientAuth=true"), socketFactory); + } + catch (Exception e) { + fail("Unable to create SslTransportServer."); + } + sslTransportServer.setNeedClientAuth(true); + sslTransportServer.bind(); - try { - nonSslTransportServer = new TcpTransportServer(null, new URI("tcp://localhost:61613"), socketFactory); - } catch (Exception e) { - fail("Unable to create TcpTransportServer."); - } + try { + nonSslTransportServer = new TcpTransportServer(null, new URI("tcp://localhost:61613"), socketFactory); + } + catch (Exception e) { + fail("Unable to create TcpTransportServer."); + } + connectionInfo = new ConnectionInfo(); - connectionInfo = new ConnectionInfo(); + createLoginConfig(); + } - createLoginConfig(); - } + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } + public void testSecureConnector() { + Connector connector = new TransportConnector(sslTransportServer); + connectionContext.setConnector(connector); + connectionInfo.setTransportContext(new StubX509Certificate[]{}); + try { + authBroker.addConnection(connectionContext, connectionInfo); + } + catch (Exception e) { + fail("Call to addConnection failed: " + e.getMessage()); + } - public void testSecureConnector() { - Connector connector = new TransportConnector(sslTransportServer); - connectionContext.setConnector(connector); - connectionInfo.setTransportContext(new StubX509Certificate[] {}); + assertEquals("Number of addConnection calls to underlying Broker must match number of calls made to " + "AuthenticationBroker.", 1, receiveBroker.addConnectionData.size()); - try { - authBroker.addConnection(connectionContext, connectionInfo); - } catch (Exception e) { - fail("Call to addConnection failed: " + e.getMessage()); - } + ConnectionContext receivedContext = receiveBroker.addConnectionData.getFirst().connectionContext; - assertEquals("Number of addConnection calls to underlying Broker must match number of calls made to " + - "AuthenticationBroker.", 1, receiveBroker.addConnectionData.size()); + assertEquals("The SecurityContext's userName must be set to that of the UserPrincipal.", DN_USERNAME, receivedContext.getSecurityContext().getUserName()); - ConnectionContext receivedContext = receiveBroker.addConnectionData.getFirst().connectionContext; + Set receivedPrincipals = receivedContext.getSecurityContext().getPrincipals(); - assertEquals("The SecurityContext's userName must be set to that of the UserPrincipal.", - DN_USERNAME, receivedContext.getSecurityContext().getUserName()); + assertEquals("2 Principals received", 2, receivedPrincipals.size()); - Set receivedPrincipals = receivedContext.getSecurityContext().getPrincipals(); + for (Iterator iter = receivedPrincipals.iterator(); iter.hasNext(); ) { + Principal currentPrincipal = iter.next(); + if (currentPrincipal instanceof UserPrincipal) { + assertEquals("UserPrincipal is '" + DN_USERNAME + "'", DN_USERNAME, currentPrincipal.getName()); + } + else if (currentPrincipal instanceof GroupPrincipal) { + assertEquals("GroupPrincipal is '" + DN_GROUP + "'", DN_GROUP, currentPrincipal.getName()); + } + else { + fail("Unexpected Principal subclass found."); + } + } - assertEquals("2 Principals received", 2, receivedPrincipals.size()); + try { + authBroker.removeConnection(connectionContext, connectionInfo, null); + } + catch (Exception e) { + fail("Call to removeConnection failed: " + e.getMessage()); + } + assertEquals("Number of removeConnection calls to underlying Broker must match number of calls made to " + "AuthenticationBroker.", 1, receiveBroker.removeConnectionData.size()); + } - for (Iterator iter = receivedPrincipals.iterator(); iter.hasNext();) { - Principal currentPrincipal = iter.next(); + public void testInsecureConnector() { + Connector connector = new TransportConnector(nonSslTransportServer); + connectionContext.setConnector(connector); + connectionInfo.setUserName(INSECURE_USERNAME); - if (currentPrincipal instanceof UserPrincipal) { - assertEquals("UserPrincipal is '" + DN_USERNAME + "'", DN_USERNAME, currentPrincipal.getName()); - } else if (currentPrincipal instanceof GroupPrincipal) { - assertEquals("GroupPrincipal is '" + DN_GROUP + "'", DN_GROUP, currentPrincipal.getName()); - } else { - fail("Unexpected Principal subclass found."); - } - } + try { + authBroker.addConnection(connectionContext, connectionInfo); + } + catch (Exception e) { + fail("Call to addConnection failed: " + e.getMessage()); + } - try { - authBroker.removeConnection(connectionContext, connectionInfo, null); - } catch (Exception e) { - fail("Call to removeConnection failed: " + e.getMessage()); - } - assertEquals("Number of removeConnection calls to underlying Broker must match number of calls made to " + - "AuthenticationBroker.", 1, receiveBroker.removeConnectionData.size()); - } + assertEquals("Number of addConnection calls to underlying Broker must match number of calls made to " + "AuthenticationBroker.", 1, receiveBroker.addConnectionData.size()); - public void testInsecureConnector() { - Connector connector = new TransportConnector(nonSslTransportServer); - connectionContext.setConnector(connector); - connectionInfo.setUserName(INSECURE_USERNAME); + ConnectionContext receivedContext = receiveBroker.addConnectionData.getFirst().connectionContext; - try { - authBroker.addConnection(connectionContext, connectionInfo); - } catch (Exception e) { - fail("Call to addConnection failed: " + e.getMessage()); - } + assertEquals("The SecurityContext's userName must be set to that of the UserPrincipal.", INSECURE_USERNAME, receivedContext.getSecurityContext().getUserName()); - assertEquals("Number of addConnection calls to underlying Broker must match number of calls made to " + - "AuthenticationBroker.", 1, receiveBroker.addConnectionData.size()); + Set receivedPrincipals = receivedContext.getSecurityContext().getPrincipals(); - ConnectionContext receivedContext = receiveBroker.addConnectionData.getFirst().connectionContext; + assertEquals("2 Principals received", 2, receivedPrincipals.size()); + for (Iterator iter = receivedPrincipals.iterator(); iter.hasNext(); ) { + Principal currentPrincipal = iter.next(); - assertEquals("The SecurityContext's userName must be set to that of the UserPrincipal.", - INSECURE_USERNAME, receivedContext.getSecurityContext().getUserName()); + if (currentPrincipal instanceof UserPrincipal) { + assertEquals("UserPrincipal is '" + INSECURE_USERNAME + "'", INSECURE_USERNAME, currentPrincipal.getName()); + } + else if (currentPrincipal instanceof GroupPrincipal) { + assertEquals("GroupPrincipal is '" + INSECURE_GROUP + "'", INSECURE_GROUP, currentPrincipal.getName()); + } + else { + fail("Unexpected Principal subclass found."); + } + } - Set receivedPrincipals = receivedContext.getSecurityContext().getPrincipals(); - - assertEquals("2 Principals received", 2, receivedPrincipals.size()); - for (Iterator iter = receivedPrincipals.iterator(); iter.hasNext();) { - Principal currentPrincipal = iter.next(); - - if (currentPrincipal instanceof UserPrincipal) { - assertEquals("UserPrincipal is '" + INSECURE_USERNAME + "'", - INSECURE_USERNAME, currentPrincipal.getName()); - } else if (currentPrincipal instanceof GroupPrincipal) { - assertEquals("GroupPrincipal is '" + INSECURE_GROUP + "'", - INSECURE_GROUP, currentPrincipal.getName()); - } else { - fail("Unexpected Principal subclass found."); - } - } - - try { - authBroker.removeConnection(connectionContext, connectionInfo, null); - } catch (Exception e) { - fail("Call to removeConnection failed: " + e.getMessage()); - } - assertEquals("Number of removeConnection calls to underlying Broker must match number of calls made to " + - "AuthenticationBroker.", 1, receiveBroker.removeConnectionData.size()); - } + try { + authBroker.removeConnection(connectionContext, connectionInfo, null); + } + catch (Exception e) { + fail("Call to removeConnection failed: " + e.getMessage()); + } + assertEquals("Number of removeConnection calls to underlying Broker must match number of calls made to " + "AuthenticationBroker.", 1, receiveBroker.removeConnectionData.size()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/JaasNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/JaasNetworkTest.java index 5c85cb602f..67f428d7ec 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/JaasNetworkTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/JaasNetworkTest.java @@ -32,54 +32,52 @@ import org.apache.activemq.broker.BrokerService; import org.apache.activemq.command.ActiveMQQueue; public class JaasNetworkTest extends TestCase { - - BrokerService broker1; - BrokerService broker2; - - public void setUp() throws Exception { - System.setProperty("java.security.auth.login.config", "src/test/resources/login.config"); - broker1 = BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/security/broker1.xml")); - broker2 = BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/security/broker2.xml")); - broker1.waitUntilStarted(); - broker2.waitUntilStarted(); - Thread.sleep(2000); - } - - protected void tearDown() throws Exception { - super.tearDown(); - broker1.stop(); - broker1.waitUntilStopped(); - broker2.stop(); - broker2.waitUntilStopped(); - } + BrokerService broker1; + BrokerService broker2; + public void setUp() throws Exception { + System.setProperty("java.security.auth.login.config", "src/test/resources/login.config"); + broker1 = BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/security/broker1.xml")); + broker2 = BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/security/broker2.xml")); + broker1.waitUntilStarted(); + broker2.waitUntilStarted(); + Thread.sleep(2000); + } - public void testNetwork() throws Exception { - - System.setProperty("javax.net.ssl.trustStore", "src/test/resources/org/apache/activemq/security/client.ts"); - System.setProperty("javax.net.ssl.trustStorePassword", "password"); - System.setProperty("javax.net.ssl.trustStoreType", "jks"); - System.setProperty("javax.net.ssl.keyStore", "src/test/resources/org/apache/activemq/security/client.ks"); - System.setProperty("javax.net.ssl.keyStorePassword", "password"); - System.setProperty("javax.net.ssl.keyStoreType", "jks"); - - ActiveMQConnectionFactory producerFactory = new ActiveMQConnectionFactory("ssl://localhost:61617"); - Connection producerConn = producerFactory.createConnection(); - Session producerSess = producerConn.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = producerSess.createProducer(new ActiveMQQueue("test")); - producerConn.start(); - TextMessage sentMessage = producerSess.createTextMessage("test"); - producer.send(sentMessage); - - ActiveMQConnectionFactory consumerFactory = new ActiveMQConnectionFactory("ssl://localhost:61618"); - Connection consumerConn = consumerFactory.createConnection(); - Session consumerSess = consumerConn.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumerConn.start(); - MessageConsumer consumer = consumerSess.createConsumer(new ActiveMQQueue("test")); - TextMessage receivedMessage = (TextMessage)consumer.receive(100); - assertEquals(sentMessage, receivedMessage); + protected void tearDown() throws Exception { + super.tearDown(); + broker1.stop(); + broker1.waitUntilStopped(); + broker2.stop(); + broker2.waitUntilStopped(); + } + + public void testNetwork() throws Exception { + + System.setProperty("javax.net.ssl.trustStore", "src/test/resources/org/apache/activemq/security/client.ts"); + System.setProperty("javax.net.ssl.trustStorePassword", "password"); + System.setProperty("javax.net.ssl.trustStoreType", "jks"); + System.setProperty("javax.net.ssl.keyStore", "src/test/resources/org/apache/activemq/security/client.ks"); + System.setProperty("javax.net.ssl.keyStorePassword", "password"); + System.setProperty("javax.net.ssl.keyStoreType", "jks"); + + ActiveMQConnectionFactory producerFactory = new ActiveMQConnectionFactory("ssl://localhost:61617"); + Connection producerConn = producerFactory.createConnection(); + Session producerSess = producerConn.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = producerSess.createProducer(new ActiveMQQueue("test")); + producerConn.start(); + TextMessage sentMessage = producerSess.createTextMessage("test"); + producer.send(sentMessage); + + ActiveMQConnectionFactory consumerFactory = new ActiveMQConnectionFactory("ssl://localhost:61618"); + Connection consumerConn = consumerFactory.createConnection(); + Session consumerSess = consumerConn.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumerConn.start(); + MessageConsumer consumer = consumerSess.createConsumer(new ActiveMQQueue("test")); + TextMessage receivedMessage = (TextMessage) consumer.receive(100); + assertEquals(sentMessage, receivedMessage); + + } - } - } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPAuthenticationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPAuthenticationTest.java index 4e77c0125e..4dc8083217 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPAuthenticationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPAuthenticationTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.security; + import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; @@ -41,43 +42,42 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; - -@RunWith( FrameworkRunner.class ) -@CreateLdapServer(transports = {@CreateTransport(protocol = "LDAP", port=1024)}) +@RunWith(FrameworkRunner.class) +@CreateLdapServer(transports = {@CreateTransport(protocol = "LDAP", port = 1024)}) @ApplyLdifFiles( - "org/apache/activemq/security/activemq.ldif" -) + "org/apache/activemq/security/activemq.ldif") public class LDAPAuthenticationTest extends AbstractLdapTestUnit { - public BrokerService broker; + public BrokerService broker; - public static LdapServer ldapServer; + public static LdapServer ldapServer; - @Before - public void setup() throws Exception { - System.setProperty("ldapPort", String.valueOf(getLdapServer().getPort())); + @Before + public void setup() throws Exception { + System.setProperty("ldapPort", String.valueOf(getLdapServer().getPort())); - broker = BrokerFactory.createBroker("xbean:org/apache/activemq/security/activemq-ldap-auth.xml"); - broker.start(); - broker.waitUntilStarted(); - } + broker = BrokerFactory.createBroker("xbean:org/apache/activemq/security/activemq-ldap-auth.xml"); + broker.start(); + broker.waitUntilStarted(); + } - @After - public void shutdown() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } + @After + public void shutdown() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + } - @Test - public void testWildcard() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); - Connection conn = factory.createQueueConnection("*", "sunflower"); - try { - conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - } catch (Exception e) { - e.printStackTrace(); - return; - } - fail("Should have failed connecting"); - } + @Test + public void testWildcard() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); + Connection conn = factory.createQueueConnection("*", "sunflower"); + try { + conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + } + catch (Exception e) { + e.printStackTrace(); + return; + } + fail("Should have failed connecting"); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPAuthorizationMapTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPAuthorizationMapTest.java index 130a0dadb1..34aa7b24c7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPAuthorizationMapTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPAuthorizationMapTest.java @@ -46,111 +46,110 @@ import org.junit.runner.RunWith; * This test assumes setup like in file 'AMQauth.ldif'. Contents of this file is attached below in comments. * * @author ngcutura - * - * */ @RunWith(FrameworkRunner.class) -@CreateLdapServer(transports = { @CreateTransport(protocol = "LDAP") }) +@CreateLdapServer(transports = {@CreateTransport(protocol = "LDAP")}) @ApplyLdifFiles("org/apache/activemq/security/AMQauth.ldif") public class LDAPAuthorizationMapTest extends AbstractLdapTestUnit { - private static LDAPAuthorizationMap authMap; - public static LdapServer ldapServer; + private static LDAPAuthorizationMap authMap; - @Before - public void setup() throws Exception { - authMap = new LDAPAuthorizationMap(); - authMap.setConnectionURL("ldap://localhost:" + getLdapServer().getPort()); - authMap.setTopicSearchMatchingFormat(new MessageFormat("uid={0},ou=topics,ou=destinations,o=ActiveMQ,ou=system")); - authMap.setQueueSearchMatchingFormat(new MessageFormat("uid={0},ou=queues,ou=destinations,o=ActiveMQ,ou=system")); - authMap.setAdvisorySearchBase("uid=ActiveMQ.Advisory,ou=topics,ou=destinations,o=ActiveMQ,ou=system"); - authMap.setTempSearchBase("uid=ActiveMQ.Temp,ou=topics,ou=destinations,o=ActiveMQ,ou=system"); - } + public static LdapServer ldapServer; - @Test - public void testOpen() throws Exception { - DirContext ctx = authMap.open(); - HashSet set = new HashSet(); - NamingEnumeration list = ctx.list("ou=destinations,o=ActiveMQ,ou=system"); - while (list.hasMore()) { - NameClassPair ncp = list.next(); - set.add(ncp.getName()); - } - assertTrue(set.contains("ou=topics")); - assertTrue(set.contains("ou=queues")); - } + @Before + public void setup() throws Exception { + authMap = new LDAPAuthorizationMap(); + authMap.setConnectionURL("ldap://localhost:" + getLdapServer().getPort()); + authMap.setTopicSearchMatchingFormat(new MessageFormat("uid={0},ou=topics,ou=destinations,o=ActiveMQ,ou=system")); + authMap.setQueueSearchMatchingFormat(new MessageFormat("uid={0},ou=queues,ou=destinations,o=ActiveMQ,ou=system")); + authMap.setAdvisorySearchBase("uid=ActiveMQ.Advisory,ou=topics,ou=destinations,o=ActiveMQ,ou=system"); + authMap.setTempSearchBase("uid=ActiveMQ.Temp,ou=topics,ou=destinations,o=ActiveMQ,ou=system"); + } - /* - * Test method for 'org.apache.activemq.security.LDAPAuthorizationMap.getAdminACLs(ActiveMQDestination)' - */ - @Test - public void testGetAdminACLs() { - ActiveMQDestination q1 = new ActiveMQQueue("queue1"); - Set aclsq1 = authMap.getAdminACLs(q1); - assertEquals(1, aclsq1.size()); - assertTrue(aclsq1.contains(new GroupPrincipal("role1"))); + @Test + public void testOpen() throws Exception { + DirContext ctx = authMap.open(); + HashSet set = new HashSet(); + NamingEnumeration list = ctx.list("ou=destinations,o=ActiveMQ,ou=system"); + while (list.hasMore()) { + NameClassPair ncp = list.next(); + set.add(ncp.getName()); + } + assertTrue(set.contains("ou=topics")); + assertTrue(set.contains("ou=queues")); + } - ActiveMQDestination t1 = new ActiveMQTopic("topic1"); - Set aclst1 = authMap.getAdminACLs(t1); - assertEquals(1, aclst1.size()); - assertTrue(aclst1.contains(new GroupPrincipal("role1"))); - } + /* + * Test method for 'org.apache.activemq.security.LDAPAuthorizationMap.getAdminACLs(ActiveMQDestination)' + */ + @Test + public void testGetAdminACLs() { + ActiveMQDestination q1 = new ActiveMQQueue("queue1"); + Set aclsq1 = authMap.getAdminACLs(q1); + assertEquals(1, aclsq1.size()); + assertTrue(aclsq1.contains(new GroupPrincipal("role1"))); - /* - * Test method for 'org.apache.activemq.security.LDAPAuthorizationMap.getReadACLs(ActiveMQDestination)' - */ - @Test - public void testGetReadACLs() { - ActiveMQDestination q1 = new ActiveMQQueue("queue1"); - Set aclsq1 = authMap.getReadACLs(q1); - assertEquals(1, aclsq1.size()); - assertTrue(aclsq1.contains(new GroupPrincipal("role1"))); + ActiveMQDestination t1 = new ActiveMQTopic("topic1"); + Set aclst1 = authMap.getAdminACLs(t1); + assertEquals(1, aclst1.size()); + assertTrue(aclst1.contains(new GroupPrincipal("role1"))); + } - ActiveMQDestination t1 = new ActiveMQTopic("topic1"); - Set aclst1 = authMap.getReadACLs(t1); - assertEquals(1, aclst1.size()); - assertTrue(aclst1.contains(new GroupPrincipal("role2"))); - } + /* + * Test method for 'org.apache.activemq.security.LDAPAuthorizationMap.getReadACLs(ActiveMQDestination)' + */ + @Test + public void testGetReadACLs() { + ActiveMQDestination q1 = new ActiveMQQueue("queue1"); + Set aclsq1 = authMap.getReadACLs(q1); + assertEquals(1, aclsq1.size()); + assertTrue(aclsq1.contains(new GroupPrincipal("role1"))); - /* - * Test method for 'org.apache.activemq.security.LDAPAuthorizationMap.getWriteACLs(ActiveMQDestination)' - */ - @Test - public void testGetWriteACLs() { - ActiveMQDestination q1 = new ActiveMQQueue("queue1"); - Set aclsq1 = authMap.getWriteACLs(q1); - assertEquals(2, aclsq1.size()); - assertTrue(aclsq1.contains(new GroupPrincipal("role1"))); - assertTrue(aclsq1.contains(new GroupPrincipal("role2"))); + ActiveMQDestination t1 = new ActiveMQTopic("topic1"); + Set aclst1 = authMap.getReadACLs(t1); + assertEquals(1, aclst1.size()); + assertTrue(aclst1.contains(new GroupPrincipal("role2"))); + } - ActiveMQDestination t1 = new ActiveMQTopic("topic1"); - Set aclst1 = authMap.getWriteACLs(t1); - assertEquals(1, aclst1.size()); - assertTrue(aclst1.contains(new GroupPrincipal("role3"))); - } + /* + * Test method for 'org.apache.activemq.security.LDAPAuthorizationMap.getWriteACLs(ActiveMQDestination)' + */ + @Test + public void testGetWriteACLs() { + ActiveMQDestination q1 = new ActiveMQQueue("queue1"); + Set aclsq1 = authMap.getWriteACLs(q1); + assertEquals(2, aclsq1.size()); + assertTrue(aclsq1.contains(new GroupPrincipal("role1"))); + assertTrue(aclsq1.contains(new GroupPrincipal("role2"))); - @Test - public void testComposite() { - ActiveMQDestination q1 = new ActiveMQQueue("queue1,topic://topic1"); - Set aclsq1 = authMap.getWriteACLs(q1); - assertEquals(0, aclsq1.size()); - } + ActiveMQDestination t1 = new ActiveMQTopic("topic1"); + Set aclst1 = authMap.getWriteACLs(t1); + assertEquals(1, aclst1.size()); + assertTrue(aclst1.contains(new GroupPrincipal("role3"))); + } - @Test - public void testAdvisory() { - ActiveMQDestination dest = AdvisorySupport.getConnectionAdvisoryTopic(); - Set acls = authMap.getWriteACLs(dest); + @Test + public void testComposite() { + ActiveMQDestination q1 = new ActiveMQQueue("queue1,topic://topic1"); + Set aclsq1 = authMap.getWriteACLs(q1); + assertEquals(0, aclsq1.size()); + } - assertEquals(1, acls.size()); - assertTrue(acls.contains(new GroupPrincipal("role3"))); - } + @Test + public void testAdvisory() { + ActiveMQDestination dest = AdvisorySupport.getConnectionAdvisoryTopic(); + Set acls = authMap.getWriteACLs(dest); - @Test - public void testTemp() { - Set acls = authMap.getTempDestinationAdminACLs(); + assertEquals(1, acls.size()); + assertTrue(acls.contains(new GroupPrincipal("role3"))); + } - assertEquals(1, acls.size()); - assertTrue(acls.contains(new GroupPrincipal("role1"))); - } + @Test + public void testTemp() { + Set acls = authMap.getTempDestinationAdminACLs(); + + assertEquals(1, acls.size()); + assertTrue(acls.contains(new GroupPrincipal("role1"))); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPSecurityTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPSecurityTest.java index 63c4cbda88..46b516cd14 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPSecurityTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPSecurityTest.java @@ -42,111 +42,111 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; - -@RunWith( FrameworkRunner.class ) -@CreateLdapServer(transports = {@CreateTransport(protocol = "LDAP", port=1024)}) +@RunWith(FrameworkRunner.class) +@CreateLdapServer(transports = {@CreateTransport(protocol = "LDAP", port = 1024)}) @ApplyLdifFiles( - "org/apache/activemq/security/activemq.ldif" -) + "org/apache/activemq/security/activemq.ldif") public class LDAPSecurityTest extends AbstractLdapTestUnit { - public BrokerService broker; + public BrokerService broker; - public static LdapServer ldapServer; + public static LdapServer ldapServer; - @Before - public void setup() throws Exception { - System.setProperty("ldapPort", String.valueOf(getLdapServer().getPort())); + @Before + public void setup() throws Exception { + System.setProperty("ldapPort", String.valueOf(getLdapServer().getPort())); - broker = BrokerFactory.createBroker("xbean:org/apache/activemq/security/activemq-ldap.xml"); - broker.start(); - broker.waitUntilStarted(); - } + broker = BrokerFactory.createBroker("xbean:org/apache/activemq/security/activemq-ldap.xml"); + broker.start(); + broker.waitUntilStarted(); + } - @After - public void shutdown() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } + @After + public void shutdown() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + } - @Test - public void testSendReceive() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); - Connection conn = factory.createQueueConnection("jdoe", "sunflower"); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); - Destination queue = sess.createQueue("TEST.FOO"); + @Test + public void testSendReceive() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); + Connection conn = factory.createQueueConnection("jdoe", "sunflower"); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + conn.start(); + Destination queue = sess.createQueue("TEST.FOO"); - MessageProducer producer = sess.createProducer(queue); - MessageConsumer consumer = sess.createConsumer(queue); + MessageProducer producer = sess.createProducer(queue); + MessageConsumer consumer = sess.createConsumer(queue); - producer.send(sess.createTextMessage("test")); - Message msg = consumer.receive(1000); - assertNotNull(msg); - } + producer.send(sess.createTextMessage("test")); + Message msg = consumer.receive(1000); + assertNotNull(msg); + } - @Test - public void testSendTopic() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); - Connection conn = factory.createQueueConnection("jdoe", "sunflower"); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); - Destination topic = sess.createTopic("TEST.BAR"); + @Test + public void testSendTopic() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); + Connection conn = factory.createQueueConnection("jdoe", "sunflower"); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + conn.start(); + Destination topic = sess.createTopic("TEST.BAR"); - MessageProducer producer = sess.createProducer(topic); - MessageConsumer consumer = sess.createConsumer(topic); + MessageProducer producer = sess.createProducer(topic); + MessageConsumer consumer = sess.createConsumer(topic); - producer.send(sess.createTextMessage("test")); - Message msg = consumer.receive(1000); - assertNotNull(msg); - } + producer.send(sess.createTextMessage("test")); + Message msg = consumer.receive(1000); + assertNotNull(msg); + } - @Test - public void testSendDenied() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); - Connection conn = factory.createQueueConnection("jdoe", "sunflower"); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); - Queue queue = sess.createQueue("ADMIN.FOO"); + @Test + public void testSendDenied() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); + Connection conn = factory.createQueueConnection("jdoe", "sunflower"); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + conn.start(); + Queue queue = sess.createQueue("ADMIN.FOO"); - try { - MessageProducer producer = sess.createProducer(queue); - producer.send(sess.createTextMessage("test")); - fail("expect auth exception"); - } catch (JMSException expected) { - } - } + try { + MessageProducer producer = sess.createProducer(queue); + producer.send(sess.createTextMessage("test")); + fail("expect auth exception"); + } + catch (JMSException expected) { + } + } - @Test - public void testCompositeSendDenied() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); - Connection conn = factory.createQueueConnection("jdoe", "sunflower"); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); - Queue queue = sess.createQueue("TEST.FOO,ADMIN.FOO"); + @Test + public void testCompositeSendDenied() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); + Connection conn = factory.createQueueConnection("jdoe", "sunflower"); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + conn.start(); + Queue queue = sess.createQueue("TEST.FOO,ADMIN.FOO"); - try { - MessageProducer producer = sess.createProducer(queue); - producer.send(sess.createTextMessage("test")); - fail("expect auth exception"); - } catch (JMSException expected) { - } - } + try { + MessageProducer producer = sess.createProducer(queue); + producer.send(sess.createTextMessage("test")); + fail("expect auth exception"); + } + catch (JMSException expected) { + } + } - @Test - public void testTempDestinations() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); - Connection conn = factory.createQueueConnection("jdoe", "sunflower"); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); - Queue queue = sess.createTemporaryQueue(); + @Test + public void testTempDestinations() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); + Connection conn = factory.createQueueConnection("jdoe", "sunflower"); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + conn.start(); + Queue queue = sess.createTemporaryQueue(); - MessageProducer producer = sess.createProducer(queue); - MessageConsumer consumer = sess.createConsumer(queue); + MessageProducer producer = sess.createProducer(queue); + MessageConsumer consumer = sess.createConsumer(queue); - producer.send(sess.createTextMessage("test")); - Message msg = consumer.receive(1000); - assertNotNull(msg); - } + producer.send(sess.createTextMessage("test")); + Message msg = consumer.receive(1000); + assertNotNull(msg); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SecurityJMXTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SecurityJMXTest.java index b62fccb90d..d660de30b8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SecurityJMXTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SecurityJMXTest.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.security; - import java.net.URI; import java.util.HashMap; import java.util.concurrent.TimeUnit; @@ -44,65 +43,63 @@ import org.slf4j.LoggerFactory; public class SecurityJMXTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(SimpleAuthenticationPluginTest.class); - private BrokerService broker; + private static final Logger LOG = LoggerFactory.getLogger(SimpleAuthenticationPluginTest.class); + private BrokerService broker; - @Override - public void setUp() throws Exception { - broker = createBroker(); - broker.waitUntilStarted(); - } + @Override + public void setUp() throws Exception { + broker = createBroker(); + broker.waitUntilStarted(); + } - @Override - public void tearDown() throws Exception { - broker.stop(); - } + @Override + public void tearDown() throws Exception { + broker.stop(); + } - public void testMoveMessages() throws Exception { - JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1199/jmxrmi"); - JMXConnector connector = JMXConnectorFactory.connect(url, null); - connector.connect(); - MBeanServerConnection connection = connector.getMBeanServerConnection(); - ObjectName name = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost," + - "destinationType=Queue,destinationName=TEST.Q"); - QueueViewMBean queueMbean = MBeanServerInvocationHandler.newProxyInstance(connection, name, QueueViewMBean.class, true); - String msgId = queueMbean.sendTextMessage("test", "system", "manager"); - queueMbean.moveMessageTo(msgId, "TEST1.Q"); - } + public void testMoveMessages() throws Exception { + JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1199/jmxrmi"); + JMXConnector connector = JMXConnectorFactory.connect(url, null); + connector.connect(); + MBeanServerConnection connection = connector.getMBeanServerConnection(); + ObjectName name = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost," + "destinationType=Queue,destinationName=TEST.Q"); + QueueViewMBean queueMbean = MBeanServerInvocationHandler.newProxyInstance(connection, name, QueueViewMBean.class, true); + String msgId = queueMbean.sendTextMessage("test", "system", "manager"); + queueMbean.moveMessageTo(msgId, "TEST1.Q"); + } - public void testBrowseExpiredMessages() throws Exception { - JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1199/jmxrmi"); - JMXConnector connector = JMXConnectorFactory.connect(url, null); - connector.connect(); - MBeanServerConnection connection = connector.getMBeanServerConnection(); - ObjectName name = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost," + - "destinationType=Queue,destinationName=TEST.Q"); - QueueViewMBean queueMbean = MBeanServerInvocationHandler.newProxyInstance(connection, name, QueueViewMBean.class, true); - HashMap headers = new HashMap(); - headers.put("timeToLive", Long.toString(2000)); - headers.put("JMSDeliveryMode", Integer.toString(DeliveryMode.PERSISTENT)); - queueMbean.sendTextMessage(headers, "test", "system", "manager"); - // allow message to expire on the queue - TimeUnit.SECONDS.sleep(4); + public void testBrowseExpiredMessages() throws Exception { + JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1199/jmxrmi"); + JMXConnector connector = JMXConnectorFactory.connect(url, null); + connector.connect(); + MBeanServerConnection connection = connector.getMBeanServerConnection(); + ObjectName name = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost," + "destinationType=Queue,destinationName=TEST.Q"); + QueueViewMBean queueMbean = MBeanServerInvocationHandler.newProxyInstance(connection, name, QueueViewMBean.class, true); + HashMap headers = new HashMap(); + headers.put("timeToLive", Long.toString(2000)); + headers.put("JMSDeliveryMode", Integer.toString(DeliveryMode.PERSISTENT)); + queueMbean.sendTextMessage(headers, "test", "system", "manager"); + // allow message to expire on the queue + TimeUnit.SECONDS.sleep(4); - Connection c = new ActiveMQConnectionFactory("vm://localhost").createConnection("system", "manager"); - c.start(); + Connection c = new ActiveMQConnectionFactory("vm://localhost").createConnection("system", "manager"); + c.start(); - // browser consumer will force expriation check on addConsumer - QueueBrowser browser = c.createSession(false, Session.AUTO_ACKNOWLEDGE).createBrowser(new ActiveMQQueue("TEST.Q")); - assertTrue("no message in the q", !browser.getEnumeration().hasMoreElements()); + // browser consumer will force expriation check on addConsumer + QueueBrowser browser = c.createSession(false, Session.AUTO_ACKNOWLEDGE).createBrowser(new ActiveMQQueue("TEST.Q")); + assertTrue("no message in the q", !browser.getEnumeration().hasMoreElements()); - // verify dlq got the message, no security exception as brokers context is now used - browser = c.createSession(false, Session.AUTO_ACKNOWLEDGE).createBrowser(new ActiveMQQueue("ActiveMQ.DLQ")); - assertTrue("one message in the dlq", browser.getEnumeration().hasMoreElements()); - } + // verify dlq got the message, no security exception as brokers context is now used + browser = c.createSession(false, Session.AUTO_ACKNOWLEDGE).createBrowser(new ActiveMQQueue("ActiveMQ.DLQ")); + assertTrue("one message in the dlq", browser.getEnumeration().hasMoreElements()); + } - protected BrokerService createBroker() throws Exception { - return createBroker("org/apache/activemq/security/simple-auth-broker.xml"); - } + protected BrokerService createBroker() throws Exception { + return createBroker("org/apache/activemq/security/simple-auth-broker.xml"); + } - protected BrokerService createBroker(String uri) throws Exception { - LOG.info("Loading broker configuration from the classpath with URI: " + uri); - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } + protected BrokerService createBroker(String uri) throws Exception { + LOG.info("Loading broker configuration from the classpath with URI: " + uri); + return BrokerFactory.createBroker(new URI("xbean:" + uri)); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SecurityTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SecurityTestSupport.java index a40970ccb0..6819323476 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SecurityTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SecurityTestSupport.java @@ -32,232 +32,237 @@ import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTopic; /** - * + * */ public class SecurityTestSupport extends JmsTestSupport { - public ActiveMQDestination destination; + public ActiveMQDestination destination; - /** - * Overrides to set the JMSXUserID flag to true. - */ - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - broker.setPopulateJMSXUserID(true); - return broker; - } + /** + * Overrides to set the JMSXUserID flag to true. + */ + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); + broker.setPopulateJMSXUserID(true); + return broker; + } - public void testUserReceiveFails() throws JMSException { - doReceive(true); - } + public void testUserReceiveFails() throws JMSException { + doReceive(true); + } - public void testInvalidAuthentication() throws JMSException { - try { - // No user id - Connection c = factory.createConnection(); - connections.add(c); - c.start(); - fail("Expected exception."); - } catch (JMSException e) { - } + public void testInvalidAuthentication() throws JMSException { + try { + // No user id + Connection c = factory.createConnection(); + connections.add(c); + c.start(); + fail("Expected exception."); + } + catch (JMSException e) { + } - try { - // Bad password - Connection c = factory.createConnection("user", "krap"); - connections.add(c); - c.start(); - fail("Expected exception."); - } catch (JMSException e) { - } + try { + // Bad password + Connection c = factory.createConnection("user", "krap"); + connections.add(c); + c.start(); + fail("Expected exception."); + } + catch (JMSException e) { + } - try { - // Bad userid - Connection c = factory.createConnection("userkrap", null); - connections.add(c); - c.start(); - fail("Expected exception."); - } catch (JMSException e) { - } - } + try { + // Bad userid + Connection c = factory.createConnection("userkrap", null); + connections.add(c); + c.start(); + fail("Expected exception."); + } + catch (JMSException e) { + } + } - public void testUserReceiveSucceeds() throws JMSException { - Message m = doReceive(false); - assertEquals("system", ((ActiveMQMessage)m).getUserID()); - assertEquals("system", m.getStringProperty("JMSXUserID")); - } + public void testUserReceiveSucceeds() throws JMSException { + Message m = doReceive(false); + assertEquals("system", ((ActiveMQMessage) m).getUserID()); + assertEquals("system", m.getStringProperty("JMSXUserID")); + } - public void testGuestReceiveSucceeds() throws JMSException { - doReceive(false); - } + public void testGuestReceiveSucceeds() throws JMSException { + doReceive(false); + } - public void testGuestReceiveFails() throws JMSException { - doReceive(true); - } + public void testGuestReceiveFails() throws JMSException { + doReceive(true); + } - public void testUserSendSucceeds() throws JMSException { - Message m = doSend(false); - assertEquals("user", ((ActiveMQMessage)m).getUserID()); - assertEquals("user", m.getStringProperty("JMSXUserID")); - } + public void testUserSendSucceeds() throws JMSException { + Message m = doSend(false); + assertEquals("user", ((ActiveMQMessage) m).getUserID()); + assertEquals("user", m.getStringProperty("JMSXUserID")); + } - public void testUserSendFails() throws JMSException { - doSend(true); - } + public void testUserSendFails() throws JMSException { + doSend(true); + } - public void testGuestSendFails() throws JMSException { - doSend(true); - } + public void testGuestSendFails() throws JMSException { + doSend(true); + } - public void testGuestSendSucceeds() throws JMSException { - doSend(false); - } + public void testGuestSendSucceeds() throws JMSException { + doSend(false); + } - /** - * @throws JMSException - */ - public Message doSend(boolean fail) throws JMSException { + /** + * @throws JMSException + */ + public Message doSend(boolean fail) throws JMSException { - Connection adminConnection = factory.createConnection("system", "manager"); - connections.add(adminConnection); + Connection adminConnection = factory.createConnection("system", "manager"); + connections.add(adminConnection); - adminConnection.start(); - Session adminSession = adminConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = adminSession.createConsumer(destination); + adminConnection.start(); + Session adminSession = adminConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = adminSession.createConsumer(destination); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - try { - sendMessages(session, destination, 1); - } catch (JMSException e) { - // If test is expected to fail, the cause must only be a - // SecurityException - // otherwise rethrow the exception - if (!fail || !(e.getCause() instanceof SecurityException)) { - throw e; - } - } - - Message m = consumer.receive(1000); - if (fail) { - assertNull(m); - } else { - assertNotNull(m); - assertEquals("0", ((TextMessage)m).getText()); - assertNull(consumer.receiveNoWait()); - } - return m; - } - - /** - * @throws JMSException - */ - public Message doReceive(boolean fail) throws JMSException { - - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = null; - try { - consumer = session.createConsumer(destination); - if (fail) { - fail("Expected failure due to security constraint."); - } - } catch (JMSException e) { - if (fail && e.getCause() instanceof SecurityException) { - return null; - } + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + try { + sendMessages(session, destination, 1); + } + catch (JMSException e) { + // If test is expected to fail, the cause must only be a + // SecurityException + // otherwise rethrow the exception + if (!fail || !(e.getCause() instanceof SecurityException)) { throw e; - } + } + } - Connection adminConnection = factory.createConnection("system", "manager"); - connections.add(adminConnection); - Session adminSession = adminConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - sendMessages(adminSession, destination, 1); + Message m = consumer.receive(1000); + if (fail) { + assertNull(m); + } + else { + assertNotNull(m); + assertEquals("0", ((TextMessage) m).getText()); + assertNull(consumer.receiveNoWait()); + } + return m; + } - Message m = consumer.receive(1000); - assertNotNull(m); - assertEquals("0", ((TextMessage)m).getText()); - assertNull(consumer.receiveNoWait()); - return m; + /** + * @throws JMSException + */ + public Message doReceive(boolean fail) throws JMSException { - } + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = null; + try { + consumer = session.createConsumer(destination); + if (fail) { + fail("Expected failure due to security constraint."); + } + } + catch (JMSException e) { + if (fail && e.getCause() instanceof SecurityException) { + return null; + } + throw e; + } - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestUserReceiveFails() { - addCombinationValues("userName", new Object[] {"user"}); - addCombinationValues("password", new Object[] {"password"}); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("USERS.BY_PASS, TEST"), new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("GUEST.BAR"), new ActiveMQTopic("GUEST.BAR")}); - } + Connection adminConnection = factory.createConnection("system", "manager"); + connections.add(adminConnection); + Session adminSession = adminConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + sendMessages(adminSession, destination, 1); - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestInvalidAuthentication() { - addCombinationValues("userName", new Object[] {"user"}); - addCombinationValues("password", new Object[] {"password"}); - } + Message m = consumer.receive(1000); + assertNotNull(m); + assertEquals("0", ((TextMessage) m).getText()); + assertNull(consumer.receiveNoWait()); + return m; - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestUserReceiveSucceeds() { - addCombinationValues("userName", new Object[] {"user"}); - addCombinationValues("password", new Object[] {"password"}); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("USERS.FOO"), new ActiveMQTopic("USERS.FOO")}); - } + } - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestGuestReceiveSucceeds() { - addCombinationValues("userName", new Object[] {"guest"}); - addCombinationValues("password", new Object[] {"password"}); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("GUEST.BAR"), new ActiveMQTopic("GUEST.BAR")}); - } + /** + * @see {@link CombinationTestSupport} + */ + public void initCombosForTestUserReceiveFails() { + addCombinationValues("userName", new Object[]{"user"}); + addCombinationValues("password", new Object[]{"password"}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("USERS.BY_PASS, TEST"), new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("GUEST.BAR"), new ActiveMQTopic("GUEST.BAR")}); + } - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestGuestReceiveFails() { - addCombinationValues("userName", new Object[] {"guest"}); - addCombinationValues("password", new Object[] {"password"}); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("GUESTS.BY_PASS,TEST"), new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("USERS.FOO"), new ActiveMQTopic("USERS.FOO") }); - } + /** + * @see {@link CombinationTestSupport} + */ + public void initCombosForTestInvalidAuthentication() { + addCombinationValues("userName", new Object[]{"user"}); + addCombinationValues("password", new Object[]{"password"}); + } - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestUserSendSucceeds() { - addCombinationValues("userName", new Object[] {"user"}); - addCombinationValues("password", new Object[] {"password"}); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("USERS.FOO"), new ActiveMQQueue("GUEST.BAR"), new ActiveMQTopic("USERS.FOO"), - new ActiveMQTopic("GUEST.BAR")}); - } + /** + * @see {@link CombinationTestSupport} + */ + public void initCombosForTestUserReceiveSucceeds() { + addCombinationValues("userName", new Object[]{"user"}); + addCombinationValues("password", new Object[]{"password"}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("USERS.FOO"), new ActiveMQTopic("USERS.FOO")}); + } - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestUserSendFails() { - addCombinationValues("userName", new Object[] {"user"}); - addCombinationValues("password", new Object[] {"password"}); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("USERS.BY_PASS,TEST"), new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST")}); - } + /** + * @see {@link CombinationTestSupport} + */ + public void initCombosForTestGuestReceiveSucceeds() { + addCombinationValues("userName", new Object[]{"guest"}); + addCombinationValues("password", new Object[]{"password"}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("GUEST.BAR"), new ActiveMQTopic("GUEST.BAR")}); + } - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestGuestSendFails() { - addCombinationValues("userName", new Object[] {"guest"}); - addCombinationValues("password", new Object[] {"password"}); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("GUESTS.BY_PASS,TEST"), new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("USERS.FOO"), new ActiveMQTopic("USERS.FOO")}); - } + /** + * @see {@link CombinationTestSupport} + */ + public void initCombosForTestGuestReceiveFails() { + addCombinationValues("userName", new Object[]{"guest"}); + addCombinationValues("password", new Object[]{"password"}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("GUESTS.BY_PASS,TEST"), new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("USERS.FOO"), new ActiveMQTopic("USERS.FOO")}); + } - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestGuestSendSucceeds() { - addCombinationValues("userName", new Object[] {"guest"}); - addCombinationValues("password", new Object[] {"password"}); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("GUEST.BAR"), new ActiveMQTopic("GUEST.BAR")}); - } + /** + * @see {@link CombinationTestSupport} + */ + public void initCombosForTestUserSendSucceeds() { + addCombinationValues("userName", new Object[]{"user"}); + addCombinationValues("password", new Object[]{"password"}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("USERS.FOO"), new ActiveMQQueue("GUEST.BAR"), new ActiveMQTopic("USERS.FOO"), new ActiveMQTopic("GUEST.BAR")}); + } + + /** + * @see {@link CombinationTestSupport} + */ + public void initCombosForTestUserSendFails() { + addCombinationValues("userName", new Object[]{"user"}); + addCombinationValues("password", new Object[]{"password"}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("USERS.BY_PASS,TEST"), new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST")}); + } + + /** + * @see {@link CombinationTestSupport} + */ + public void initCombosForTestGuestSendFails() { + addCombinationValues("userName", new Object[]{"guest"}); + addCombinationValues("password", new Object[]{"password"}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("GUESTS.BY_PASS,TEST"), new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("USERS.FOO"), new ActiveMQTopic("USERS.FOO")}); + } + + /** + * @see {@link CombinationTestSupport} + */ + public void initCombosForTestGuestSendSucceeds() { + addCombinationValues("userName", new Object[]{"guest"}); + addCombinationValues("password", new Object[]{"password"}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("GUEST.BAR"), new ActiveMQTopic("GUEST.BAR")}); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAnonymousPluginTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAnonymousPluginTest.java index c97515e999..2e0adcc0cd 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAnonymousPluginTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAnonymousPluginTest.java @@ -28,90 +28,92 @@ import org.apache.activemq.command.ActiveMQTopic; public class SimpleAnonymousPluginTest extends SimpleAuthenticationPluginTest { - public static Test suite() { - return suite(SimpleAnonymousPluginTest.class); - } + public static Test suite() { + return suite(SimpleAnonymousPluginTest.class); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - @Override - protected BrokerService createBroker() throws Exception { - return createBroker("org/apache/activemq/security/simple-anonymous-broker.xml"); - } + @Override + protected BrokerService createBroker() throws Exception { + return createBroker("org/apache/activemq/security/simple-anonymous-broker.xml"); + } - @Override - public void testInvalidAuthentication() throws JMSException { + @Override + public void testInvalidAuthentication() throws JMSException { - try { - // Bad password - Connection c = factory.createConnection("user", "krap"); - connections.add(c); - c.start(); - fail("Expected exception."); - } catch (JMSException e) { - } + try { + // Bad password + Connection c = factory.createConnection("user", "krap"); + connections.add(c); + c.start(); + fail("Expected exception."); + } + catch (JMSException e) { + } - try { - // Bad userid - Connection c = factory.createConnection("userkrap", null); - connections.add(c); - c.start(); - fail("Expected exception."); - } catch (JMSException e) { - } - } + try { + // Bad userid + Connection c = factory.createConnection("userkrap", null); + connections.add(c); + c.start(); + fail("Expected exception."); + } + catch (JMSException e) { + } + } - public void testAnonymousReceiveSucceeds() throws JMSException { - doReceive(false); - } + public void testAnonymousReceiveSucceeds() throws JMSException { + doReceive(false); + } - public void testAnonymousReceiveFails() throws JMSException { - doReceive(true); - } + public void testAnonymousReceiveFails() throws JMSException { + doReceive(true); + } - public void testAnonymousSendFails() throws JMSException { - doSend(true); - } + public void testAnonymousSendFails() throws JMSException { + doSend(true); + } - public void testAnonymousSendSucceeds() throws JMSException { - doSend(false); - } + public void testAnonymousSendSucceeds() throws JMSException { + doSend(false); + } - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestAnonymousReceiveSucceeds() { - addCombinationValues("userName", new Object[] { null }); - addCombinationValues("password", new Object[] { null }); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("GUEST.BAR"), new ActiveMQTopic("GUEST.BAR")}); - } + /** + * @see {@link CombinationTestSupport} + */ + public void initCombosForTestAnonymousReceiveSucceeds() { + addCombinationValues("userName", new Object[]{null}); + addCombinationValues("password", new Object[]{null}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("GUEST.BAR"), new ActiveMQTopic("GUEST.BAR")}); + } - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestAnonymousReceiveFails() { - addCombinationValues("userName", new Object[] { null }); - addCombinationValues("password", new Object[] { null }); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("USERS.FOO"), new ActiveMQTopic("USERS.FOO") }); - } + /** + * @see {@link CombinationTestSupport} + */ + public void initCombosForTestAnonymousReceiveFails() { + addCombinationValues("userName", new Object[]{null}); + addCombinationValues("password", new Object[]{null}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("USERS.FOO"), new ActiveMQTopic("USERS.FOO")}); + } - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestAnonymousSendFails() { - addCombinationValues("userName", new Object[] { null }); - addCombinationValues("password", new Object[] { null }); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("USERS.FOO"), new ActiveMQTopic("USERS.FOO")}); - } + /** + * @see {@link CombinationTestSupport} + */ + public void initCombosForTestAnonymousSendFails() { + addCombinationValues("userName", new Object[]{null}); + addCombinationValues("password", new Object[]{null}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("USERS.FOO"), new ActiveMQTopic("USERS.FOO")}); + } - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestAnonymousSendSucceeds() { - addCombinationValues("userName", new Object[] { null }); - addCombinationValues("password", new Object[] { null }); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("GUEST.BAR"), new ActiveMQTopic("GUEST.BAR")}); - } + /** + * @see {@link CombinationTestSupport} + */ + public void initCombosForTestAnonymousSendSucceeds() { + addCombinationValues("userName", new Object[]{null}); + addCombinationValues("password", new Object[]{null}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("GUEST.BAR"), new ActiveMQTopic("GUEST.BAR")}); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAuthenticationPluginSeparatorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAuthenticationPluginSeparatorTest.java index 0456841f73..298598b4f1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAuthenticationPluginSeparatorTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAuthenticationPluginSeparatorTest.java @@ -18,103 +18,103 @@ package org.apache.activemq.security; import junit.framework.Test; + import org.apache.activemq.broker.BrokerService; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTopic; public class SimpleAuthenticationPluginSeparatorTest extends SimpleAuthenticationPluginTest { - public static Test suite() { - return suite(SimpleAuthenticationPluginSeparatorTest.class); - } + public static Test suite() { + return suite(SimpleAuthenticationPluginSeparatorTest.class); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - @Override - protected BrokerService createBroker() throws Exception { - return createBroker("org/apache/activemq/security/simple-auth-separator.xml"); - } + @Override + protected BrokerService createBroker() throws Exception { + return createBroker("org/apache/activemq/security/simple-auth-separator.xml"); + } - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestUserReceiveFails() { - addCombinationValues("userName", new Object[] {"user"}); - addCombinationValues("password", new Object[] {"password"}); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("GUEST/BAR"), new ActiveMQTopic("GUEST/BAR")}); - } + /** + * @see {@link CombinationTestSupport} + */ + public void initCombosForTestUserReceiveFails() { + addCombinationValues("userName", new Object[]{"user"}); + addCombinationValues("password", new Object[]{"password"}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("GUEST/BAR"), new ActiveMQTopic("GUEST/BAR")}); + } - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestInvalidAuthentication() { - addCombinationValues("userName", new Object[] {"user"}); - addCombinationValues("password", new Object[] {"password"}); - } + /** + * @see {@link CombinationTestSupport} + */ + public void initCombosForTestInvalidAuthentication() { + addCombinationValues("userName", new Object[]{"user"}); + addCombinationValues("password", new Object[]{"password"}); + } - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestUserReceiveSucceeds() { - addCombinationValues("userName", new Object[] {"user"}); - addCombinationValues("password", new Object[] {"password"}); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("USERS/FOO"), new ActiveMQTopic("USERS/FOO")}); - } + /** + * @see {@link CombinationTestSupport} + */ + public void initCombosForTestUserReceiveSucceeds() { + addCombinationValues("userName", new Object[]{"user"}); + addCombinationValues("password", new Object[]{"password"}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("USERS/FOO"), new ActiveMQTopic("USERS/FOO")}); + } - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestGuestReceiveSucceeds() { - addCombinationValues("userName", new Object[] {"guest"}); - addCombinationValues("password", new Object[] {"password"}); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("GUEST/BAR"), new ActiveMQTopic("GUEST/BAR")}); - } + /** + * @see {@link CombinationTestSupport} + */ + public void initCombosForTestGuestReceiveSucceeds() { + addCombinationValues("userName", new Object[]{"guest"}); + addCombinationValues("password", new Object[]{"password"}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("GUEST/BAR"), new ActiveMQTopic("GUEST/BAR")}); + } - /** - * @see {@link org.apache.activemq.CombinationTestSupport} - */ - public void initCombosForTestGuestReceiveFails() { - addCombinationValues("userName", new Object[] {"guest"}); - addCombinationValues("password", new Object[] {"password"}); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("USERS/FOO"), new ActiveMQTopic("USERS/FOO") }); - } + /** + * @see {@link org.apache.activemq.CombinationTestSupport} + */ + public void initCombosForTestGuestReceiveFails() { + addCombinationValues("userName", new Object[]{"guest"}); + addCombinationValues("password", new Object[]{"password"}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("USERS/FOO"), new ActiveMQTopic("USERS/FOO")}); + } - /** - * @see {@link org.apache.activemq.CombinationTestSupport} - */ - public void initCombosForTestUserSendSucceeds() { - addCombinationValues("userName", new Object[] {"user"}); - addCombinationValues("password", new Object[] {"password"}); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("USERS/FOO"), new ActiveMQQueue("GUEST/BAR"), new ActiveMQTopic("USERS/FOO"), - new ActiveMQTopic("GUEST/BAR")}); - } + /** + * @see {@link org.apache.activemq.CombinationTestSupport} + */ + public void initCombosForTestUserSendSucceeds() { + addCombinationValues("userName", new Object[]{"user"}); + addCombinationValues("password", new Object[]{"password"}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("USERS/FOO"), new ActiveMQQueue("GUEST/BAR"), new ActiveMQTopic("USERS/FOO"), new ActiveMQTopic("GUEST/BAR")}); + } - /** - * @see {@link org.apache.activemq.CombinationTestSupport} - */ - public void initCombosForTestUserSendFails() { - addCombinationValues("userName", new Object[] {"user"}); - addCombinationValues("password", new Object[] {"password"}); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST")}); - } + /** + * @see {@link org.apache.activemq.CombinationTestSupport} + */ + public void initCombosForTestUserSendFails() { + addCombinationValues("userName", new Object[]{"user"}); + addCombinationValues("password", new Object[]{"password"}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST")}); + } - /** - * @see {@link org.apache.activemq.CombinationTestSupport} - */ - public void initCombosForTestGuestSendFails() { - addCombinationValues("userName", new Object[] {"guest"}); - addCombinationValues("password", new Object[] {"password"}); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("USERS/FOO"), new ActiveMQTopic("USERS/FOO")}); - } + /** + * @see {@link org.apache.activemq.CombinationTestSupport} + */ + public void initCombosForTestGuestSendFails() { + addCombinationValues("userName", new Object[]{"guest"}); + addCombinationValues("password", new Object[]{"password"}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("USERS/FOO"), new ActiveMQTopic("USERS/FOO")}); + } - /** - * @see {@link org.apache.activemq.CombinationTestSupport} - */ - public void initCombosForTestGuestSendSucceeds() { - addCombinationValues("userName", new Object[] {"guest"}); - addCombinationValues("password", new Object[] {"password"}); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("GUEST/BAR"), new ActiveMQTopic("GUEST/BAR")}); - } + /** + * @see {@link org.apache.activemq.CombinationTestSupport} + */ + public void initCombosForTestGuestSendSucceeds() { + addCombinationValues("userName", new Object[]{"guest"}); + addCombinationValues("password", new Object[]{"password"}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("GUEST/BAR"), new ActiveMQTopic("GUEST/BAR")}); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAuthenticationPluginTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAuthenticationPluginTest.java index 1a154b261b..6d246a8b76 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAuthenticationPluginTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAuthenticationPluginTest.java @@ -45,105 +45,111 @@ import org.slf4j.LoggerFactory; public class SimpleAuthenticationPluginTest extends SecurityTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(SimpleAuthenticationPluginTest.class); + private static final Logger LOG = LoggerFactory.getLogger(SimpleAuthenticationPluginTest.class); - public static Test suite() { - return suite(SimpleAuthenticationPluginTest.class); - } + public static Test suite() { + return suite(SimpleAuthenticationPluginTest.class); + } - @Override - protected void setUp() throws Exception { - setAutoFail(true); - super.setUp(); - } + @Override + protected void setUp() throws Exception { + setAutoFail(true); + super.setUp(); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - @Override - protected BrokerService createBroker() throws Exception { - return createBroker("org/apache/activemq/security/simple-auth-broker.xml"); - } + @Override + protected BrokerService createBroker() throws Exception { + return createBroker("org/apache/activemq/security/simple-auth-broker.xml"); + } - protected BrokerService createBroker(String uri) throws Exception { - LOG.info("Loading broker configuration from the classpath with URI: " + uri); - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } + protected BrokerService createBroker(String uri) throws Exception { + LOG.info("Loading broker configuration from the classpath with URI: " + uri); + return BrokerFactory.createBroker(new URI("xbean:" + uri)); + } - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestPredefinedDestinations() { - addCombinationValues("userName", new Object[] {"guest"}); - addCombinationValues("password", new Object[] {"password"}); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST.Q")}); - } + /** + * @see {@link CombinationTestSupport} + */ + public void initCombosForTestPredefinedDestinations() { + addCombinationValues("userName", new Object[]{"guest"}); + addCombinationValues("password", new Object[]{"password"}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("TEST.Q")}); + } - public void testPredefinedDestinations() throws JMSException { - Message sent = doSend(false); - assertEquals("guest", ((ActiveMQMessage)sent).getUserID()); - assertEquals("guest", sent.getStringProperty("JMSXUserID")); - } + public void testPredefinedDestinations() throws JMSException { + Message sent = doSend(false); + assertEquals("guest", ((ActiveMQMessage) sent).getUserID()); + assertEquals("guest", sent.getStringProperty("JMSXUserID")); + } - public void testTempDestinations() throws Exception { - Connection conn = factory.createConnection("guest", "password"); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - String name = "org.apache.activemq:BrokerName=localhost,Type=TempTopic"; - try { - conn.start(); - TemporaryTopic temp = sess.createTemporaryTopic(); - name += ",Destination=" + temp.getTopicName().replaceAll(":", "_"); - fail("Should have failed creating a temp topic"); - } catch (Exception ignore) {} + public void testTempDestinations() throws Exception { + Connection conn = factory.createConnection("guest", "password"); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + String name = "org.apache.activemq:BrokerName=localhost,Type=TempTopic"; + try { + conn.start(); + TemporaryTopic temp = sess.createTemporaryTopic(); + name += ",Destination=" + temp.getTopicName().replaceAll(":", "_"); + fail("Should have failed creating a temp topic"); + } + catch (Exception ignore) { + } - ObjectName objName = new ObjectName(name); - TopicViewMBean mbean = (TopicViewMBean)broker.getManagementContext().newProxyInstance(objName, TopicViewMBean.class, true); - try { - System.out.println(mbean.getName()); - fail("Shouldn't have created a temp topic"); - } catch (Exception ignore) {} - } + ObjectName objName = new ObjectName(name); + TopicViewMBean mbean = (TopicViewMBean) broker.getManagementContext().newProxyInstance(objName, TopicViewMBean.class, true); + try { + System.out.println(mbean.getName()); + fail("Shouldn't have created a temp topic"); + } + catch (Exception ignore) { + } + } - public void testConnectionStartThrowsJMSSecurityException() throws Exception { + public void testConnectionStartThrowsJMSSecurityException() throws Exception { - Connection connection = factory.createConnection("badUser", "password"); - try { - connection.start(); - fail("Should throw JMSSecurityException"); - } catch (JMSSecurityException jmsEx) { - } catch (Exception e) { - LOG.info("Expected JMSSecurityException but was: {}", e.getClass()); - fail("Should throw JMSSecurityException"); - } - } + Connection connection = factory.createConnection("badUser", "password"); + try { + connection.start(); + fail("Should throw JMSSecurityException"); + } + catch (JMSSecurityException jmsEx) { + } + catch (Exception e) { + LOG.info("Expected JMSSecurityException but was: {}", e.getClass()); + fail("Should throw JMSSecurityException"); + } + } - public void testSecurityContextClearedOnPurge() throws Exception { + public void testSecurityContextClearedOnPurge() throws Exception { - connection.close(); - ActiveMQConnectionFactory tcpFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString()); - ActiveMQConnection conn = (ActiveMQConnection) tcpFactory.createConnection("user", "password"); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); + connection.close(); + ActiveMQConnectionFactory tcpFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString()); + ActiveMQConnection conn = (ActiveMQConnection) tcpFactory.createConnection("user", "password"); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + conn.start(); - final int numDests = broker.getRegionBroker().getDestinations().length; - for (int i=0; i<10; i++) { - MessageProducer p = sess.createProducer(new ActiveMQQueue("USERS.PURGE." + i)); - p.close(); - } + final int numDests = broker.getRegionBroker().getDestinations().length; + for (int i = 0; i < 10; i++) { + MessageProducer p = sess.createProducer(new ActiveMQQueue("USERS.PURGE." + i)); + p.close(); + } - assertTrue("dests are purged", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("dests, orig: " + numDests + ", now: "+ broker.getRegionBroker().getDestinations().length); - return (numDests + 1) == broker.getRegionBroker().getDestinations().length; - } - })); + assertTrue("dests are purged", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("dests, orig: " + numDests + ", now: " + broker.getRegionBroker().getDestinations().length); + return (numDests + 1) == broker.getRegionBroker().getDestinations().length; + } + })); - // verify removed from connection security context - TransportConnection brokerConnection = broker.getTransportConnectors().get(0).getConnections().get(0); - TransportConnectionState transportConnectionState = brokerConnection.lookupConnectionState(conn.getConnectionInfo().getConnectionId()); - assertEquals("no destinations", 0, transportConnectionState.getContext().getSecurityContext().getAuthorizedWriteDests().size()); - } + // verify removed from connection security context + TransportConnection brokerConnection = broker.getTransportConnectors().get(0).getConnections().get(0); + TransportConnectionState transportConnectionState = brokerConnection.lookupConnectionState(conn.getConnectionInfo().getConnectionId()); + assertEquals("no destinations", 0, transportConnectionState.getContext().getSecurityContext().getAuthorizedWriteDests().size()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAuthorizationMapTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAuthorizationMapTest.java index f86e0fc399..d6ad38bfd2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAuthorizationMapTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAuthorizationMapTest.java @@ -17,12 +17,12 @@ package org.apache.activemq.security; /** - * - * + * + * */ public class SimpleAuthorizationMapTest extends AuthorizationMapTest { - - protected AuthorizationMap createAuthorizationMap() { - return SimpleSecurityBrokerSystemTest.createAuthorizationMap(); - } + + protected AuthorizationMap createAuthorizationMap() { + return SimpleSecurityBrokerSystemTest.createAuthorizationMap(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleSecurityBrokerSystemTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleSecurityBrokerSystemTest.java index d5f8b80ccb..ae647fe0ee 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleSecurityBrokerSystemTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleSecurityBrokerSystemTest.java @@ -26,6 +26,7 @@ import java.util.Map; import java.util.Set; import junit.framework.Test; + import org.apache.activemq.CombinationTestSupport; import org.apache.activemq.broker.Broker; import org.apache.activemq.broker.BrokerPlugin; @@ -46,142 +47,142 @@ import javax.management.openmbean.CompositeData; /** * Tests that the broker allows/fails access to destinations based on the * security policy installed on the broker. - * - * */ public class SimpleSecurityBrokerSystemTest extends SecurityTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(SimpleSecurityBrokerSystemTest.class); - public static final GroupPrincipal GUESTS = new GroupPrincipal("guests"); - public static final GroupPrincipal USERS = new GroupPrincipal("users"); - public static final GroupPrincipal ADMINS = new GroupPrincipal("admins"); - public static Principal WILDCARD; - static { - try { + private static final Logger LOG = LoggerFactory.getLogger(SimpleSecurityBrokerSystemTest.class); + + public static final GroupPrincipal GUESTS = new GroupPrincipal("guests"); + public static final GroupPrincipal USERS = new GroupPrincipal("users"); + public static final GroupPrincipal ADMINS = new GroupPrincipal("admins"); + public static Principal WILDCARD; + + static { + try { WILDCARD = (Principal) DefaultAuthorizationMap.createGroupPrincipal("*", GroupPrincipal.class.getName()); - } catch (Exception e) { - LOG.error("Failed to make wildcard principal", e); - } - } + } + catch (Exception e) { + LOG.error("Failed to make wildcard principal", e); + } + } - public BrokerPlugin authorizationPlugin; - public BrokerPlugin authenticationPlugin; + public BrokerPlugin authorizationPlugin; + public BrokerPlugin authenticationPlugin; - static { - String path = System.getProperty("java.security.auth.login.config"); - if (path == null) { - URL resource = SimpleSecurityBrokerSystemTest.class.getClassLoader().getResource("login.config"); - if (resource != null) { - path = resource.getFile(); - System.setProperty("java.security.auth.login.config", path); - } - } - LOG.info("Path to login config: " + path); - } + static { + String path = System.getProperty("java.security.auth.login.config"); + if (path == null) { + URL resource = SimpleSecurityBrokerSystemTest.class.getClassLoader().getResource("login.config"); + if (resource != null) { + path = resource.getFile(); + System.setProperty("java.security.auth.login.config", path); + } + } + LOG.info("Path to login config: " + path); + } - public static Test suite() { - return suite(SimpleSecurityBrokerSystemTest.class); - } + public static Test suite() { + return suite(SimpleSecurityBrokerSystemTest.class); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - /** - * @throws javax.jms.JMSException - */ - public void testPopulateJMSXUserID() throws Exception { - destination = new ActiveMQQueue("TEST"); - Connection connection = factory.createConnection("system", "manager"); - connections.add(connection); - connection.start(); + /** + * @throws javax.jms.JMSException + */ + public void testPopulateJMSXUserID() throws Exception { + destination = new ActiveMQQueue("TEST"); + Connection connection = factory.createConnection("system", "manager"); + connections.add(connection); + connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - sendMessages(session, destination, 1); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + sendMessages(session, destination, 1); - // make sure that the JMSXUserID is exposed over JMX - MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); - CompositeData[] browse = (CompositeData[]) mbs.invoke(new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=TEST"), "browse", null, null); - assertEquals("system", browse[0].get("JMSXUserID")); + // make sure that the JMSXUserID is exposed over JMX + MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); + CompositeData[] browse = (CompositeData[]) mbs.invoke(new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=TEST"), "browse", null, null); + assertEquals("system", browse[0].get("JMSXUserID")); - // And also via JMS. - MessageConsumer consumer = session.createConsumer(destination); - Message m = consumer.receive(1000); - assertTrue(m.propertyExists("JMSXUserID")); - assertEquals("system", m.getStringProperty("JMSXUserID")); - } + // And also via JMS. + MessageConsumer consumer = session.createConsumer(destination); + Message m = consumer.receive(1000); + assertTrue(m.propertyExists("JMSXUserID")); + assertEquals("system", m.getStringProperty("JMSXUserID")); + } - public static AuthorizationMap createAuthorizationMap() { - DestinationMap readAccess = new DefaultAuthorizationMap(); - readAccess.put(new ActiveMQQueue(">"), ADMINS); - readAccess.put(new ActiveMQQueue("USERS.>"), USERS); - readAccess.put(new ActiveMQQueue("GUEST.>"), GUESTS); - readAccess.put(new ActiveMQTopic(">"), ADMINS); - readAccess.put(new ActiveMQTopic("USERS.>"), USERS); - readAccess.put(new ActiveMQTopic("GUEST.>"), GUESTS); + public static AuthorizationMap createAuthorizationMap() { + DestinationMap readAccess = new DefaultAuthorizationMap(); + readAccess.put(new ActiveMQQueue(">"), ADMINS); + readAccess.put(new ActiveMQQueue("USERS.>"), USERS); + readAccess.put(new ActiveMQQueue("GUEST.>"), GUESTS); + readAccess.put(new ActiveMQTopic(">"), ADMINS); + readAccess.put(new ActiveMQTopic("USERS.>"), USERS); + readAccess.put(new ActiveMQTopic("GUEST.>"), GUESTS); - DestinationMap writeAccess = new DefaultAuthorizationMap(); - writeAccess.put(new ActiveMQQueue(">"), ADMINS); - writeAccess.put(new ActiveMQQueue("USERS.>"), USERS); - writeAccess.put(new ActiveMQQueue("GUEST.>"), USERS); - writeAccess.put(new ActiveMQQueue("GUEST.>"), GUESTS); - writeAccess.put(new ActiveMQTopic(">"), ADMINS); - writeAccess.put(new ActiveMQTopic("USERS.>"), USERS); - writeAccess.put(new ActiveMQTopic("GUEST.>"), USERS); - writeAccess.put(new ActiveMQTopic("GUEST.>"), GUESTS); + DestinationMap writeAccess = new DefaultAuthorizationMap(); + writeAccess.put(new ActiveMQQueue(">"), ADMINS); + writeAccess.put(new ActiveMQQueue("USERS.>"), USERS); + writeAccess.put(new ActiveMQQueue("GUEST.>"), USERS); + writeAccess.put(new ActiveMQQueue("GUEST.>"), GUESTS); + writeAccess.put(new ActiveMQTopic(">"), ADMINS); + writeAccess.put(new ActiveMQTopic("USERS.>"), USERS); + writeAccess.put(new ActiveMQTopic("GUEST.>"), USERS); + writeAccess.put(new ActiveMQTopic("GUEST.>"), GUESTS); - readAccess.put(new ActiveMQTopic("ActiveMQ.Advisory.>"), WILDCARD); - writeAccess.put(new ActiveMQTopic("ActiveMQ.Advisory.>"), WILDCARD); + readAccess.put(new ActiveMQTopic("ActiveMQ.Advisory.>"), WILDCARD); + writeAccess.put(new ActiveMQTopic("ActiveMQ.Advisory.>"), WILDCARD); - DestinationMap adminAccess = new DefaultAuthorizationMap(); - adminAccess.put(new ActiveMQTopic(">"), ADMINS); - adminAccess.put(new ActiveMQTopic(">"), USERS); - adminAccess.put(new ActiveMQTopic(">"), GUESTS); - adminAccess.put(new ActiveMQQueue(">"), ADMINS); - adminAccess.put(new ActiveMQQueue(">"), USERS); - adminAccess.put(new ActiveMQQueue(">"), GUESTS); + DestinationMap adminAccess = new DefaultAuthorizationMap(); + adminAccess.put(new ActiveMQTopic(">"), ADMINS); + adminAccess.put(new ActiveMQTopic(">"), USERS); + adminAccess.put(new ActiveMQTopic(">"), GUESTS); + adminAccess.put(new ActiveMQQueue(">"), ADMINS); + adminAccess.put(new ActiveMQQueue(">"), USERS); + adminAccess.put(new ActiveMQQueue(">"), GUESTS); - return new SimpleAuthorizationMap(writeAccess, readAccess, adminAccess); - } + return new SimpleAuthorizationMap(writeAccess, readAccess, adminAccess); + } - public static class SimpleAuthenticationFactory implements BrokerPlugin { - public Broker installPlugin(Broker broker) { + public static class SimpleAuthenticationFactory implements BrokerPlugin { - HashMap u = new HashMap(); - u.put("system", "manager"); - u.put("user", "password"); - u.put("guest", "password"); + public Broker installPlugin(Broker broker) { - Map> groups = new HashMap>(); - groups.put("system", new HashSet(Arrays.asList(new Principal[] {ADMINS, USERS}))); - groups.put("user", new HashSet(Arrays.asList(new Principal[] {USERS}))); - groups.put("guest", new HashSet(Arrays.asList(new Principal[] {GUESTS}))); + HashMap u = new HashMap(); + u.put("system", "manager"); + u.put("user", "password"); + u.put("guest", "password"); - return new SimpleAuthenticationBroker(broker, u, groups); - } + Map> groups = new HashMap>(); + groups.put("system", new HashSet(Arrays.asList(new Principal[]{ADMINS, USERS}))); + groups.put("user", new HashSet(Arrays.asList(new Principal[]{USERS}))); + groups.put("guest", new HashSet(Arrays.asList(new Principal[]{GUESTS}))); - public String toString() { - return "SimpleAuthenticationBroker"; - } - } + return new SimpleAuthenticationBroker(broker, u, groups); + } - /** - * @see {@link CombinationTestSupport} - */ - public void initCombos() { - addCombinationValues("authorizationPlugin", - new Object[] {new AuthorizationPlugin(createAuthorizationMap())}); - addCombinationValues("authenticationPlugin", new Object[] {new SimpleAuthenticationFactory(), - new JaasAuthenticationPlugin()}); - } + public String toString() { + return "SimpleAuthenticationBroker"; + } + } - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - broker.setPopulateJMSXUserID(true); - broker.setUseAuthenticatedPrincipalForJMSXUserID(true); - broker.setPlugins(new BrokerPlugin[] {authorizationPlugin, authenticationPlugin}); - broker.setPersistent(false); - return broker; - } + /** + * @see {@link CombinationTestSupport} + */ + public void initCombos() { + addCombinationValues("authorizationPlugin", new Object[]{new AuthorizationPlugin(createAuthorizationMap())}); + addCombinationValues("authenticationPlugin", new Object[]{new SimpleAuthenticationFactory(), new JaasAuthenticationPlugin()}); + } + + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); + broker.setPopulateJMSXUserID(true); + broker.setUseAuthenticatedPrincipalForJMSXUserID(true); + broker.setPlugins(new BrokerPlugin[]{authorizationPlugin, authenticationPlugin}); + broker.setPersistent(false); + return broker; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubDoNothingCallbackHandler.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubDoNothingCallbackHandler.java index aa9056c2dc..03f38d9108 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubDoNothingCallbackHandler.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubDoNothingCallbackHandler.java @@ -25,7 +25,7 @@ import javax.security.auth.callback.UnsupportedCallbackException; public class StubDoNothingCallbackHandler implements CallbackHandler { - public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { - } + public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubDualJaasConfiguration.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubDualJaasConfiguration.java index 7cb9282982..dbb788a03d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubDualJaasConfiguration.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubDualJaasConfiguration.java @@ -21,23 +21,25 @@ import javax.security.auth.login.AppConfigurationEntry; import javax.security.auth.login.Configuration; public class StubDualJaasConfiguration extends Configuration { - private AppConfigurationEntry nonSslConfigEntry; - private AppConfigurationEntry sslConfigEntry; - public StubDualJaasConfiguration(AppConfigurationEntry nonSslConfigEntry, AppConfigurationEntry sslConfigEntry) { - this.nonSslConfigEntry = nonSslConfigEntry; - this.sslConfigEntry = sslConfigEntry; - } + private AppConfigurationEntry nonSslConfigEntry; + private AppConfigurationEntry sslConfigEntry; - public AppConfigurationEntry[] getAppConfigurationEntry(String name) { - if ("activemq-domain".equals(name)) { - return new AppConfigurationEntry[] {nonSslConfigEntry}; - } else { - return new AppConfigurationEntry[] {sslConfigEntry}; - } - } + public StubDualJaasConfiguration(AppConfigurationEntry nonSslConfigEntry, AppConfigurationEntry sslConfigEntry) { + this.nonSslConfigEntry = nonSslConfigEntry; + this.sslConfigEntry = sslConfigEntry; + } - public void refresh() { - } + public AppConfigurationEntry[] getAppConfigurationEntry(String name) { + if ("activemq-domain".equals(name)) { + return new AppConfigurationEntry[]{nonSslConfigEntry}; + } + else { + return new AppConfigurationEntry[]{sslConfigEntry}; + } + } + + public void refresh() { + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubJaasConfiguration.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubJaasConfiguration.java index 9f66d303b5..fe5ce1abbb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubJaasConfiguration.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubJaasConfiguration.java @@ -21,17 +21,18 @@ import javax.security.auth.login.AppConfigurationEntry; import javax.security.auth.login.Configuration; public class StubJaasConfiguration extends Configuration { - private AppConfigurationEntry configEntry; - public StubJaasConfiguration(AppConfigurationEntry configEntry) { - this.configEntry = configEntry; - } + private AppConfigurationEntry configEntry; - public AppConfigurationEntry[] getAppConfigurationEntry(String name) { - return new AppConfigurationEntry[] {configEntry}; - } + public StubJaasConfiguration(AppConfigurationEntry configEntry) { + this.configEntry = configEntry; + } - public void refresh() { - } + public AppConfigurationEntry[] getAppConfigurationEntry(String name) { + return new AppConfigurationEntry[]{configEntry}; + } + + public void refresh() { + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubLoginModule.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubLoginModule.java index 5492831176..f494a6e0e5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubLoginModule.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubLoginModule.java @@ -29,70 +29,71 @@ import org.apache.activemq.jaas.GroupPrincipal; import org.apache.activemq.jaas.UserPrincipal; public class StubLoginModule implements LoginModule { - public static final String ALLOW_LOGIN_PROPERTY = "org.apache.activemq.jaas.stubproperties.allow_login"; - public static final String USERS_PROPERTY = "org.apache.activemq.jaas.stubproperties.users"; - public static final String GROUPS_PROPERTY = "org.apache.activemq.jaas.stubproperties.groups"; - private Subject subject; + public static final String ALLOW_LOGIN_PROPERTY = "org.apache.activemq.jaas.stubproperties.allow_login"; + public static final String USERS_PROPERTY = "org.apache.activemq.jaas.stubproperties.users"; + public static final String GROUPS_PROPERTY = "org.apache.activemq.jaas.stubproperties.groups"; - private String userNames[]; - private String groupNames[]; - private boolean allowLogin; + private Subject subject; - @Override - @SuppressWarnings("rawtypes") - public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) { - String allowLoginString = (String)(options.get(ALLOW_LOGIN_PROPERTY)); - String usersString = (String)(options.get(USERS_PROPERTY)); - String groupsString = (String)(options.get(GROUPS_PROPERTY)); + private String userNames[]; + private String groupNames[]; + private boolean allowLogin; - this.subject = subject; + @Override + @SuppressWarnings("rawtypes") + public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) { + String allowLoginString = (String) (options.get(ALLOW_LOGIN_PROPERTY)); + String usersString = (String) (options.get(USERS_PROPERTY)); + String groupsString = (String) (options.get(GROUPS_PROPERTY)); - allowLogin = Boolean.parseBoolean(allowLoginString); - userNames = usersString.split(","); - groupNames = groupsString.split(","); - } + this.subject = subject; - @Override - public boolean login() throws LoginException { - if (!allowLogin) { - throw new FailedLoginException("Login was not allowed (as specified in configuration)."); - } + allowLogin = Boolean.parseBoolean(allowLoginString); + userNames = usersString.split(","); + groupNames = groupsString.split(","); + } - return true; - } + @Override + public boolean login() throws LoginException { + if (!allowLogin) { + throw new FailedLoginException("Login was not allowed (as specified in configuration)."); + } - @Override - public boolean commit() throws LoginException { - if (!allowLogin) { - throw new FailedLoginException("Login was not allowed (as specified in configuration)."); - } + return true; + } - for (int i = 0; i < userNames.length; ++i) { - if (userNames[i].length() > 0) { - subject.getPrincipals().add(new UserPrincipal(userNames[i])); - } - } + @Override + public boolean commit() throws LoginException { + if (!allowLogin) { + throw new FailedLoginException("Login was not allowed (as specified in configuration)."); + } - for (int i = 0; i < groupNames.length; ++i) { - if (groupNames[i].length() > 0) { - subject.getPrincipals().add(new GroupPrincipal(groupNames[i])); - } - } + for (int i = 0; i < userNames.length; ++i) { + if (userNames[i].length() > 0) { + subject.getPrincipals().add(new UserPrincipal(userNames[i])); + } + } - return true; - } + for (int i = 0; i < groupNames.length; ++i) { + if (groupNames[i].length() > 0) { + subject.getPrincipals().add(new GroupPrincipal(groupNames[i])); + } + } - @Override - public boolean abort() throws LoginException { - return true; - } + return true; + } - @Override - public boolean logout() throws LoginException { - subject.getPrincipals().clear(); + @Override + public boolean abort() throws LoginException { + return true; + } - return true; - } + @Override + public boolean logout() throws LoginException { + subject.getPrincipals().clear(); + + return true; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubSecurityContext.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubSecurityContext.java index 7ac2d3b4c2..38a0f5a5bd 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubSecurityContext.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubSecurityContext.java @@ -21,11 +21,12 @@ import java.security.Principal; import java.util.Set; public class StubSecurityContext extends SecurityContext { - StubSecurityContext() { - super(""); - } - public Set getPrincipals() { - return null; - } + StubSecurityContext() { + super(""); + } + + public Set getPrincipals() { + return null; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSecurityTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSecurityTest.java index d01e6078c2..d98e70cf0c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSecurityTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSecurityTest.java @@ -19,35 +19,35 @@ package org.apache.activemq.security; import java.net.URI; import junit.framework.Test; + import org.apache.activemq.broker.BrokerFactory; import org.apache.activemq.broker.BrokerService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * - * + * + * */ public class XBeanSecurityTest extends SecurityTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(XBeanSecurityTest.class); - - public static Test suite() { - return suite(XBeanSecurityTest.class); - } + private static final Logger LOG = LoggerFactory.getLogger(XBeanSecurityTest.class); - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static Test suite() { + return suite(XBeanSecurityTest.class); + } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - protected BrokerService createBroker() throws Exception { - return createBroker("org/apache/activemq/security/jaas-broker.xml"); - } + protected BrokerService createBroker() throws Exception { + return createBroker("org/apache/activemq/security/jaas-broker.xml"); + } - protected BrokerService createBroker(String uri) throws Exception { - LOG.info("Loading broker configuration from the classpath with URI: " + uri); - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } + protected BrokerService createBroker(String uri) throws Exception { + LOG.info("Loading broker configuration from the classpath with URI: " + uri); + return BrokerFactory.createBroker(new URI("xbean:" + uri)); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSecurityWithGuestNoCredentialsOnlyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSecurityWithGuestNoCredentialsOnlyTest.java index 14b6dccccf..7c3fef83e7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSecurityWithGuestNoCredentialsOnlyTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSecurityWithGuestNoCredentialsOnlyTest.java @@ -23,7 +23,9 @@ import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.Session; import javax.jms.TextMessage; + import junit.framework.Test; + import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.CombinationTestSupport; import org.apache.activemq.JmsTestSupport; @@ -38,102 +40,105 @@ import org.slf4j.LoggerFactory; public class XBeanSecurityWithGuestNoCredentialsOnlyTest extends JmsTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(XBeanSecurityWithGuestNoCredentialsOnlyTest.class); - public ActiveMQDestination destination; - - public static Test suite() { - return suite(XBeanSecurityWithGuestNoCredentialsOnlyTest.class); - } - - public void testUserSendGoodPassword() throws JMSException { - Message m = doSend(false); - assertEquals("system", ((ActiveMQMessage)m).getUserID()); - assertEquals("system", m.getStringProperty("JMSXUserID")); - } - - public void testUserSendWrongPassword() throws JMSException { - try { - doSend(true); - fail("expect exception on connect"); - } catch (JMSException expected) { - assertTrue("cause as expected", expected.getCause() instanceof SecurityException); - } - } + private static final Logger LOG = LoggerFactory.getLogger(XBeanSecurityWithGuestNoCredentialsOnlyTest.class); + public ActiveMQDestination destination; - public void testUserSendNoCredentials() throws JMSException { - Message m = doSend(false); - // note brokerService.useAuthenticatedPrincipalForJMXUserID=true for this - assertEquals("guest", ((ActiveMQMessage)m).getUserID()); - assertEquals("guest", m.getStringProperty("JMSXUserID")); - } + public static Test suite() { + return suite(XBeanSecurityWithGuestNoCredentialsOnlyTest.class); + } - protected BrokerService createBroker() throws Exception { - return createBroker("org/apache/activemq/security/jaas-broker-guest-no-creds-only.xml"); - } + public void testUserSendGoodPassword() throws JMSException { + Message m = doSend(false); + assertEquals("system", ((ActiveMQMessage) m).getUserID()); + assertEquals("system", m.getStringProperty("JMSXUserID")); + } - protected BrokerService createBroker(String uri) throws Exception { - LOG.info("Loading broker configuration from the classpath with URI: " + uri); - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } + public void testUserSendWrongPassword() throws JMSException { + try { + doSend(true); + fail("expect exception on connect"); + } + catch (JMSException expected) { + assertTrue("cause as expected", expected.getCause() instanceof SecurityException); + } + } - public Message doSend(boolean fail) throws JMSException { + public void testUserSendNoCredentials() throws JMSException { + Message m = doSend(false); + // note brokerService.useAuthenticatedPrincipalForJMXUserID=true for this + assertEquals("guest", ((ActiveMQMessage) m).getUserID()); + assertEquals("guest", m.getStringProperty("JMSXUserID")); + } - Connection adminConnection = factory.createConnection("system", "manager"); - connections.add(adminConnection); + protected BrokerService createBroker() throws Exception { + return createBroker("org/apache/activemq/security/jaas-broker-guest-no-creds-only.xml"); + } - adminConnection.start(); - Session adminSession = adminConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = adminSession.createConsumer(destination); + protected BrokerService createBroker(String uri) throws Exception { + LOG.info("Loading broker configuration from the classpath with URI: " + uri); + return BrokerFactory.createBroker(new URI("xbean:" + uri)); + } - connections.remove(connection); - connection = (ActiveMQConnection)factory.createConnection(userName, password); - connections.add(connection); + public Message doSend(boolean fail) throws JMSException { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - try { - sendMessages(session, destination, 1); - } catch (JMSException e) { - // If test is expected to fail, the cause must only be a - // SecurityException - // otherwise rethrow the exception - if (!fail || !(e.getCause() instanceof SecurityException)) { - throw e; - } - } + Connection adminConnection = factory.createConnection("system", "manager"); + connections.add(adminConnection); - Message m = consumer.receive(1000); - if (fail) { - assertNull(m); - } else { - assertNotNull(m); - assertEquals("0", ((TextMessage)m).getText()); - assertNull(consumer.receiveNoWait()); - } - return m; - } - - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestUserSendGoodPassword() { - addCombinationValues("userName", new Object[] {"system"}); - addCombinationValues("password", new Object[] {"manager"}); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("test"), new ActiveMQTopic("test")}); - } - - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestUserSendWrongPassword() { - addCombinationValues("userName", new Object[] {"system"}); - addCombinationValues("password", new Object[] {"wrongpassword"}); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("GuestQueue")}); - } + adminConnection.start(); + Session adminSession = adminConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = adminSession.createConsumer(destination); - public void initCombosForTestUserSendNoCredentials() { - addCombinationValues("userName", new Object[] {null, "system"}); - addCombinationValues("password", new Object[] {null}); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("GuestQueue")}); - } + connections.remove(connection); + connection = (ActiveMQConnection) factory.createConnection(userName, password); + connections.add(connection); + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + try { + sendMessages(session, destination, 1); + } + catch (JMSException e) { + // If test is expected to fail, the cause must only be a + // SecurityException + // otherwise rethrow the exception + if (!fail || !(e.getCause() instanceof SecurityException)) { + throw e; + } + } + + Message m = consumer.receive(1000); + if (fail) { + assertNull(m); + } + else { + assertNotNull(m); + assertEquals("0", ((TextMessage) m).getText()); + assertNull(consumer.receiveNoWait()); + } + return m; + } + + /** + * @see {@link CombinationTestSupport} + */ + public void initCombosForTestUserSendGoodPassword() { + addCombinationValues("userName", new Object[]{"system"}); + addCombinationValues("password", new Object[]{"manager"}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("test"), new ActiveMQTopic("test")}); + } + + /** + * @see {@link CombinationTestSupport} + */ + public void initCombosForTestUserSendWrongPassword() { + addCombinationValues("userName", new Object[]{"system"}); + addCombinationValues("password", new Object[]{"wrongpassword"}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("GuestQueue")}); + } + + public void initCombosForTestUserSendNoCredentials() { + addCombinationValues("userName", new Object[]{null, "system"}); + addCombinationValues("password", new Object[]{null}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("GuestQueue")}); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSecurityWithGuestTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSecurityWithGuestTest.java index 16f95b49a8..11a6f3494d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSecurityWithGuestTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSecurityWithGuestTest.java @@ -23,7 +23,9 @@ import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.Session; import javax.jms.TextMessage; + import junit.framework.Test; + import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.CombinationTestSupport; import org.apache.activemq.JmsTestSupport; @@ -38,100 +40,102 @@ import org.slf4j.LoggerFactory; public class XBeanSecurityWithGuestTest extends JmsTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(XBeanSecurityWithGuestTest.class); - public ActiveMQDestination destination; - - public static Test suite() { - return suite(XBeanSecurityWithGuestTest.class); - } - - public void testUserSendGoodPassword() throws JMSException { - Message m = doSend(false); - assertEquals("system", ((ActiveMQMessage)m).getUserID()); - assertEquals("system", m.getStringProperty("JMSXUserID")); - } - - public void testUserSendWrongPassword() throws JMSException { - Message m = doSend(false); - // note brokerService.useAuthenticatedPrincipalForJMXUserID=true for this - assertEquals("guest", ((ActiveMQMessage)m).getUserID()); - assertEquals("guest", m.getStringProperty("JMSXUserID")); - } + private static final Logger LOG = LoggerFactory.getLogger(XBeanSecurityWithGuestTest.class); + public ActiveMQDestination destination; - public void testUserSendNoCredentials() throws JMSException { - Message m = doSend(false); - // note brokerService.useAuthenticatedPrincipalForJMXUserID=true for this - assertEquals("guest", ((ActiveMQMessage)m).getUserID()); - assertEquals("guest", m.getStringProperty("JMSXUserID")); - } + public static Test suite() { + return suite(XBeanSecurityWithGuestTest.class); + } - protected BrokerService createBroker() throws Exception { - return createBroker("org/apache/activemq/security/jaas-broker-guest.xml"); - } + public void testUserSendGoodPassword() throws JMSException { + Message m = doSend(false); + assertEquals("system", ((ActiveMQMessage) m).getUserID()); + assertEquals("system", m.getStringProperty("JMSXUserID")); + } - protected BrokerService createBroker(String uri) throws Exception { - LOG.info("Loading broker configuration from the classpath with URI: " + uri); - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } + public void testUserSendWrongPassword() throws JMSException { + Message m = doSend(false); + // note brokerService.useAuthenticatedPrincipalForJMXUserID=true for this + assertEquals("guest", ((ActiveMQMessage) m).getUserID()); + assertEquals("guest", m.getStringProperty("JMSXUserID")); + } - public Message doSend(boolean fail) throws JMSException { + public void testUserSendNoCredentials() throws JMSException { + Message m = doSend(false); + // note brokerService.useAuthenticatedPrincipalForJMXUserID=true for this + assertEquals("guest", ((ActiveMQMessage) m).getUserID()); + assertEquals("guest", m.getStringProperty("JMSXUserID")); + } - Connection adminConnection = factory.createConnection("system", "manager"); - connections.add(adminConnection); + protected BrokerService createBroker() throws Exception { + return createBroker("org/apache/activemq/security/jaas-broker-guest.xml"); + } - adminConnection.start(); - Session adminSession = adminConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = adminSession.createConsumer(destination); + protected BrokerService createBroker(String uri) throws Exception { + LOG.info("Loading broker configuration from the classpath with URI: " + uri); + return BrokerFactory.createBroker(new URI("xbean:" + uri)); + } - connections.remove(connection); - connection = (ActiveMQConnection)factory.createConnection(userName, password); - connections.add(connection); + public Message doSend(boolean fail) throws JMSException { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - try { - sendMessages(session, destination, 1); - } catch (JMSException e) { - // If test is expected to fail, the cause must only be a - // SecurityException - // otherwise rethrow the exception - if (!fail || !(e.getCause() instanceof SecurityException)) { - throw e; - } - } + Connection adminConnection = factory.createConnection("system", "manager"); + connections.add(adminConnection); - Message m = consumer.receive(1000); - if (fail) { - assertNull(m); - } else { - assertNotNull(m); - assertEquals("0", ((TextMessage)m).getText()); - assertNull(consumer.receiveNoWait()); - } - return m; - } - - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestUserSendGoodPassword() { - addCombinationValues("userName", new Object[] {"system"}); - addCombinationValues("password", new Object[] {"manager"}); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("test"), new ActiveMQTopic("test")}); - } - - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestUserSendWrongPassword() { - addCombinationValues("userName", new Object[] {"system"}); - addCombinationValues("password", new Object[] {"wrongpassword"}); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("GuestQueue")}); - } + adminConnection.start(); + Session adminSession = adminConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = adminSession.createConsumer(destination); - public void initCombosForTestUserSendNoCredentials() { - addCombinationValues("userName", new Object[] {"", null}); - addCombinationValues("password", new Object[] {"", null}); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("GuestQueue")}); - } + connections.remove(connection); + connection = (ActiveMQConnection) factory.createConnection(userName, password); + connections.add(connection); + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + try { + sendMessages(session, destination, 1); + } + catch (JMSException e) { + // If test is expected to fail, the cause must only be a + // SecurityException + // otherwise rethrow the exception + if (!fail || !(e.getCause() instanceof SecurityException)) { + throw e; + } + } + + Message m = consumer.receive(1000); + if (fail) { + assertNull(m); + } + else { + assertNotNull(m); + assertEquals("0", ((TextMessage) m).getText()); + assertNull(consumer.receiveNoWait()); + } + return m; + } + + /** + * @see {@link CombinationTestSupport} + */ + public void initCombosForTestUserSendGoodPassword() { + addCombinationValues("userName", new Object[]{"system"}); + addCombinationValues("password", new Object[]{"manager"}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("test"), new ActiveMQTopic("test")}); + } + + /** + * @see {@link CombinationTestSupport} + */ + public void initCombosForTestUserSendWrongPassword() { + addCombinationValues("userName", new Object[]{"system"}); + addCombinationValues("password", new Object[]{"wrongpassword"}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("GuestQueue")}); + } + + public void initCombosForTestUserSendNoCredentials() { + addCombinationValues("userName", new Object[]{"", null}); + addCombinationValues("password", new Object[]{"", null}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("GuestQueue")}); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSslContextTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSslContextTest.java index da8b6ca8f9..cfa9206bb1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSslContextTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSslContextTest.java @@ -25,17 +25,17 @@ import org.junit.Test; public class XBeanSslContextTest { - BrokerService broker; + BrokerService broker; - @Test - public void testSslContextElement() throws Exception { - broker = BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/security/activemq-sslcontext.xml")); - } + @Test + public void testSslContextElement() throws Exception { + broker = BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/security/activemq-sslcontext.xml")); + } - @After - public void stopBroker() throws Exception { - if (broker != null) - broker.stop(); - } + @After + public void stopBroker() throws Exception { + if (broker != null) + broker.stop(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/selector/SelectorParserTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/selector/SelectorParserTest.java index 0ab5118a5a..e16df69413 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/selector/SelectorParserTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/selector/SelectorParserTest.java @@ -17,6 +17,7 @@ package org.apache.activemq.selector; import javax.jms.InvalidSelectorException; + import junit.framework.TestCase; import org.apache.activemq.filter.BooleanExpression; @@ -33,56 +34,59 @@ import org.slf4j.LoggerFactory; * */ public class SelectorParserTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(SelectorParserTest.class); - public void testFunctionCall() throws Exception { - Object filter = parse("REGEX('sales.*', group)"); - assertTrue("expected type", filter instanceof BooleanFunctionCallExpr); - LOG.info("function exp:" + filter); + private static final Logger LOG = LoggerFactory.getLogger(SelectorParserTest.class); - // non existent function - try { - parse("DoesNotExist('sales.*', group)"); - fail("expect ex on non existent function"); - } catch (InvalidSelectorException expected) {} + public void testFunctionCall() throws Exception { + Object filter = parse("REGEX('sales.*', group)"); + assertTrue("expected type", filter instanceof BooleanFunctionCallExpr); + LOG.info("function exp:" + filter); - } + // non existent function + try { + parse("DoesNotExist('sales.*', group)"); + fail("expect ex on non existent function"); + } + catch (InvalidSelectorException expected) { + } - public void testParseXPath() throws Exception { - BooleanExpression filter = parse("XPATH '//title[@lang=''eng'']'"); - assertTrue("Created XPath expression", filter instanceof XPathExpression); - LOG.info("Expression: " + filter); - } + } - public void testParseWithParensAround() throws Exception { - String[] values = {"x = 1 and y = 2", "(x = 1) and (y = 2)", "((x = 1) and (y = 2))"}; + public void testParseXPath() throws Exception { + BooleanExpression filter = parse("XPATH '//title[@lang=''eng'']'"); + assertTrue("Created XPath expression", filter instanceof XPathExpression); + LOG.info("Expression: " + filter); + } - for (int i = 0; i < values.length; i++) { - String value = values[i]; - LOG.info("Parsing: " + value); + public void testParseWithParensAround() throws Exception { + String[] values = {"x = 1 and y = 2", "(x = 1) and (y = 2)", "((x = 1) and (y = 2))"}; - BooleanExpression andExpression = parse(value); - assertTrue("Created LogicExpression expression", andExpression instanceof LogicExpression); - LogicExpression logicExpression = (LogicExpression)andExpression; - Expression left = logicExpression.getLeft(); - Expression right = logicExpression.getRight(); + for (int i = 0; i < values.length; i++) { + String value = values[i]; + LOG.info("Parsing: " + value); - assertTrue("Left is a binary filter", left instanceof ComparisonExpression); - assertTrue("Right is a binary filter", right instanceof ComparisonExpression); - ComparisonExpression leftCompare = (ComparisonExpression)left; - ComparisonExpression rightCompare = (ComparisonExpression)right; - assertPropertyExpression("left", leftCompare.getLeft(), "x"); - assertPropertyExpression("right", rightCompare.getLeft(), "y"); - } - } + BooleanExpression andExpression = parse(value); + assertTrue("Created LogicExpression expression", andExpression instanceof LogicExpression); + LogicExpression logicExpression = (LogicExpression) andExpression; + Expression left = logicExpression.getLeft(); + Expression right = logicExpression.getRight(); - protected void assertPropertyExpression(String message, Expression expression, String expected) { - assertTrue(message + ". Must be PropertyExpression", expression instanceof PropertyExpression); - PropertyExpression propExp = (PropertyExpression)expression; - assertEquals(message + ". Property name", expected, propExp.getName()); - } + assertTrue("Left is a binary filter", left instanceof ComparisonExpression); + assertTrue("Right is a binary filter", right instanceof ComparisonExpression); + ComparisonExpression leftCompare = (ComparisonExpression) left; + ComparisonExpression rightCompare = (ComparisonExpression) right; + assertPropertyExpression("left", leftCompare.getLeft(), "x"); + assertPropertyExpression("right", rightCompare.getLeft(), "y"); + } + } - protected BooleanExpression parse(String text) throws Exception { - return SelectorParser.parse(text); - } + protected void assertPropertyExpression(String message, Expression expression, String expected) { + assertTrue(message + ". Must be PropertyExpression", expression instanceof PropertyExpression); + PropertyExpression propExp = (PropertyExpression) expression; + assertEquals(message + ". Property name", expected, propExp.getName()); + } + + protected BooleanExpression parse(String text) throws Exception { + return SelectorParser.parse(text); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/selector/SelectorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/selector/SelectorTest.java index 8279ae4852..eecc510a5c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/selector/SelectorTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/selector/SelectorTest.java @@ -33,365 +33,363 @@ import org.apache.activemq.filter.MessageEvaluationContext; */ public class SelectorTest extends TestCase { - public void testBooleanSelector() throws Exception { - Message message = createMessage(); + public void testBooleanSelector() throws Exception { + Message message = createMessage(); - assertSelector(message, "(trueProp OR falseProp) AND trueProp", true); - assertSelector(message, "(trueProp OR falseProp) AND falseProp", false); - assertSelector(message, "trueProp", true); + assertSelector(message, "(trueProp OR falseProp) AND trueProp", true); + assertSelector(message, "(trueProp OR falseProp) AND falseProp", false); + assertSelector(message, "trueProp", true); - } + } - public void testXPathSelectors() throws Exception { - ActiveMQTextMessage message = new ActiveMQTextMessage(); + public void testXPathSelectors() throws Exception { + ActiveMQTextMessage message = new ActiveMQTextMessage(); - message.setJMSType("xml"); - message.setText("b"); + message.setJMSType("xml"); + message.setText("b"); - assertSelector(message, "XPATH 'root/a'", true); - assertSelector(message, "XPATH '//root/b'", true); - assertSelector(message, "XPATH 'root/c'", false); - assertSelector(message, "XPATH '//root/b/text()=\"b\"'", true); - assertSelector(message, "XPATH '//root/b=\"b\"'", true); - assertSelector(message, "XPATH '//root/b=\"c\"'", false); - assertSelector(message, "XPATH '//root/b!=\"c\"'", true); + assertSelector(message, "XPATH 'root/a'", true); + assertSelector(message, "XPATH '//root/b'", true); + assertSelector(message, "XPATH 'root/c'", false); + assertSelector(message, "XPATH '//root/b/text()=\"b\"'", true); + assertSelector(message, "XPATH '//root/b=\"b\"'", true); + assertSelector(message, "XPATH '//root/b=\"c\"'", false); + assertSelector(message, "XPATH '//root/b!=\"c\"'", true); - assertSelector(message, "XPATH '//root/*[@key=''second'']'", true); - assertSelector(message, "XPATH '//root/*[@key=''third'']'", false); - assertSelector(message, "XPATH '//root/a[@key=''first'']'", true); - assertSelector(message, "XPATH '//root/a[@num=1]'", true); - assertSelector(message, "XPATH '//root/a[@key=''second'']'", false); + assertSelector(message, "XPATH '//root/*[@key=''second'']'", true); + assertSelector(message, "XPATH '//root/*[@key=''third'']'", false); + assertSelector(message, "XPATH '//root/a[@key=''first'']'", true); + assertSelector(message, "XPATH '//root/a[@num=1]'", true); + assertSelector(message, "XPATH '//root/a[@key=''second'']'", false); - assertSelector(message, "XPATH '/root/*[@key=''first'' or @key=''third'']'", true); - assertSelector(message, "XPATH '//root/*[@key=''third'' or @key=''forth'']'", false); + assertSelector(message, "XPATH '/root/*[@key=''first'' or @key=''third'']'", true); + assertSelector(message, "XPATH '//root/*[@key=''third'' or @key=''forth'']'", false); - assertSelector(message, "XPATH '/root/b=''b'' and /root/b[@key=''second'']'", true); - assertSelector(message, "XPATH '/root/b=''b'' and /root/b[@key=''first'']'", false); + assertSelector(message, "XPATH '/root/b=''b'' and /root/b[@key=''second'']'", true); + assertSelector(message, "XPATH '/root/b=''b'' and /root/b[@key=''first'']'", false); - assertSelector(message, "XPATH 'not(//root/a)'", false); - assertSelector(message, "XPATH 'not(//root/c)'", true); - assertSelector(message, "XPATH '//root/a[not(@key=''first'')]'", false); - assertSelector(message, "XPATH '//root/a[not(not(@key=''first''))]'", true); + assertSelector(message, "XPATH 'not(//root/a)'", false); + assertSelector(message, "XPATH 'not(//root/c)'", true); + assertSelector(message, "XPATH '//root/a[not(@key=''first'')]'", false); + assertSelector(message, "XPATH '//root/a[not(not(@key=''first''))]'", true); - assertSelector(message, "XPATH 'string(//root/b)'", true); - assertSelector(message, "XPATH 'string(//root/a)'", false); + assertSelector(message, "XPATH 'string(//root/b)'", true); + assertSelector(message, "XPATH 'string(//root/a)'", false); - assertSelector(message, "XPATH 'sum(//@num) < 10'", true); - assertSelector(message, "XPATH 'sum(//@num) > 10'", false); + assertSelector(message, "XPATH 'sum(//@num) < 10'", true); + assertSelector(message, "XPATH 'sum(//@num) > 10'", false); - assertSelector(message, "XPATH '//root/a[@num > 1]'", false); - assertSelector(message, "XPATH '//root/b[@num > 1]'", true); + assertSelector(message, "XPATH '//root/a[@num > 1]'", false); + assertSelector(message, "XPATH '//root/b[@num > 1]'", true); - } + } - public void testJMSPropertySelectors() throws Exception { - Message message = createMessage(); - message.setJMSType("selector-test"); - message.setJMSMessageID("id:test:1:1:1:1"); + public void testJMSPropertySelectors() throws Exception { + Message message = createMessage(); + message.setJMSType("selector-test"); + message.setJMSMessageID("id:test:1:1:1:1"); - assertSelector(message, "JMSType = 'selector-test'", true); - assertSelector(message, "JMSType = 'crap'", false); + assertSelector(message, "JMSType = 'selector-test'", true); + assertSelector(message, "JMSType = 'crap'", false); - assertSelector(message, "JMSMessageID = 'id:test:1:1:1:1'", true); - assertSelector(message, "JMSMessageID = 'id:not-test:1:1:1:1'", false); + assertSelector(message, "JMSMessageID = 'id:test:1:1:1:1'", true); + assertSelector(message, "JMSMessageID = 'id:not-test:1:1:1:1'", false); - message = createMessage(); - message.setJMSType("1001"); + message = createMessage(); + message.setJMSType("1001"); - assertSelector(message, "JMSType='1001'", true); - assertSelector(message, "JMSType='1001' OR JMSType='1002'", true); - assertSelector(message, "JMSType = 'crap'", false); - } + assertSelector(message, "JMSType='1001'", true); + assertSelector(message, "JMSType='1001' OR JMSType='1002'", true); + assertSelector(message, "JMSType = 'crap'", false); + } - public void testBasicSelectors() throws Exception { - Message message = createMessage(); + public void testBasicSelectors() throws Exception { + Message message = createMessage(); - assertSelector(message, "name = 'James'", true); - assertSelector(message, "rank > 100", true); - assertSelector(message, "rank >= 123", true); - assertSelector(message, "rank >= 124", false); + assertSelector(message, "name = 'James'", true); + assertSelector(message, "rank > 100", true); + assertSelector(message, "rank >= 123", true); + assertSelector(message, "rank >= 124", false); - } + } - public void testPropertyTypes() throws Exception { - Message message = createMessage(); - assertSelector(message, "byteProp = 123", true); - assertSelector(message, "byteProp = 10", false); - assertSelector(message, "byteProp2 = 33", true); - assertSelector(message, "byteProp2 = 10", false); + public void testPropertyTypes() throws Exception { + Message message = createMessage(); + assertSelector(message, "byteProp = 123", true); + assertSelector(message, "byteProp = 10", false); + assertSelector(message, "byteProp2 = 33", true); + assertSelector(message, "byteProp2 = 10", false); - assertSelector(message, "shortProp = 123", true); - assertSelector(message, "shortProp = 10", false); + assertSelector(message, "shortProp = 123", true); + assertSelector(message, "shortProp = 10", false); - assertSelector(message, "shortProp = 123", true); - assertSelector(message, "shortProp = 10", false); + assertSelector(message, "shortProp = 123", true); + assertSelector(message, "shortProp = 10", false); - assertSelector(message, "intProp = 123", true); - assertSelector(message, "intProp = 10", false); + assertSelector(message, "intProp = 123", true); + assertSelector(message, "intProp = 10", false); - assertSelector(message, "longProp = 123", true); - assertSelector(message, "longProp = 10", false); + assertSelector(message, "longProp = 123", true); + assertSelector(message, "longProp = 10", false); - assertSelector(message, "floatProp = 123", true); - assertSelector(message, "floatProp = 10", false); + assertSelector(message, "floatProp = 123", true); + assertSelector(message, "floatProp = 10", false); - assertSelector(message, "doubleProp = 123", true); - assertSelector(message, "doubleProp = 10", false); - } + assertSelector(message, "doubleProp = 123", true); + assertSelector(message, "doubleProp = 10", false); + } - public void testAndSelectors() throws Exception { - Message message = createMessage(); + public void testAndSelectors() throws Exception { + Message message = createMessage(); - assertSelector(message, "name = 'James' and rank < 200", true); - assertSelector(message, "name = 'James' and rank > 200", false); - assertSelector(message, "name = 'Foo' and rank < 200", false); - assertSelector(message, "unknown = 'Foo' and anotherUnknown < 200", false); - } + assertSelector(message, "name = 'James' and rank < 200", true); + assertSelector(message, "name = 'James' and rank > 200", false); + assertSelector(message, "name = 'Foo' and rank < 200", false); + assertSelector(message, "unknown = 'Foo' and anotherUnknown < 200", false); + } - public void testOrSelectors() throws Exception { - Message message = createMessage(); + public void testOrSelectors() throws Exception { + Message message = createMessage(); - assertSelector(message, "name = 'James' or rank < 200", true); - assertSelector(message, "name = 'James' or rank > 200", true); - assertSelector(message, "name = 'Foo' or rank < 200", true); - assertSelector(message, "name = 'Foo' or rank > 200", false); - assertSelector(message, "unknown = 'Foo' or anotherUnknown < 200", false); - } + assertSelector(message, "name = 'James' or rank < 200", true); + assertSelector(message, "name = 'James' or rank > 200", true); + assertSelector(message, "name = 'Foo' or rank < 200", true); + assertSelector(message, "name = 'Foo' or rank > 200", false); + assertSelector(message, "unknown = 'Foo' or anotherUnknown < 200", false); + } - public void testPlus() throws Exception { - Message message = createMessage(); + public void testPlus() throws Exception { + Message message = createMessage(); - assertSelector(message, "rank + 2 = 125", true); - assertSelector(message, "(rank + 2) = 125", true); - assertSelector(message, "125 = (rank + 2)", true); - assertSelector(message, "rank + version = 125", true); - assertSelector(message, "rank + 2 < 124", false); - assertSelector(message, "name + '!' = 'James!'", true); - } + assertSelector(message, "rank + 2 = 125", true); + assertSelector(message, "(rank + 2) = 125", true); + assertSelector(message, "125 = (rank + 2)", true); + assertSelector(message, "rank + version = 125", true); + assertSelector(message, "rank + 2 < 124", false); + assertSelector(message, "name + '!' = 'James!'", true); + } - public void testMinus() throws Exception { - Message message = createMessage(); + public void testMinus() throws Exception { + Message message = createMessage(); - assertSelector(message, "rank - 2 = 121", true); - assertSelector(message, "rank - version = 121", true); - assertSelector(message, "rank - 2 > 122", false); - } + assertSelector(message, "rank - 2 = 121", true); + assertSelector(message, "rank - version = 121", true); + assertSelector(message, "rank - 2 > 122", false); + } - public void testMultiply() throws Exception { - Message message = createMessage(); + public void testMultiply() throws Exception { + Message message = createMessage(); - assertSelector(message, "rank * 2 = 246", true); - assertSelector(message, "rank * version = 246", true); - assertSelector(message, "rank * 2 < 130", false); - } + assertSelector(message, "rank * 2 = 246", true); + assertSelector(message, "rank * version = 246", true); + assertSelector(message, "rank * 2 < 130", false); + } - public void testDivide() throws Exception { - Message message = createMessage(); + public void testDivide() throws Exception { + Message message = createMessage(); - assertSelector(message, "rank / version = 61.5", true); - assertSelector(message, "rank / 3 > 100.0", false); - assertSelector(message, "rank / 3 > 100", false); - assertSelector(message, "version / 2 = 1", true); - - } - - public void testBetween() throws Exception { - Message message = createMessage(); - - assertSelector(message, "rank between 100 and 150", true); - assertSelector(message, "rank between 10 and 120", false); - } - - public void testIn() throws Exception { - Message message = createMessage(); - - assertSelector(message, "name in ('James', 'Bob', 'Gromit')", true); - assertSelector(message, "name in ('Bob', 'James', 'Gromit')", true); - assertSelector(message, "name in ('Gromit', 'Bob', 'James')", true); - - assertSelector(message, "name in ('Gromit', 'Bob', 'Cheddar')", false); - assertSelector(message, "name not in ('Gromit', 'Bob', 'Cheddar')", true); - } - - public void testIsNull() throws Exception { - Message message = createMessage(); - - assertSelector(message, "dummy is null", true); - assertSelector(message, "dummy is not null", false); - assertSelector(message, "name is not null", true); - assertSelector(message, "name is null", false); - } - - public void testLike() throws Exception { - Message message = createMessage(); - message.setStringProperty("modelClassId", "com.whatever.something.foo.bar"); - message.setStringProperty("modelInstanceId", "170"); - message.setStringProperty("modelRequestError", "abc"); - message.setStringProperty("modelCorrelatedClientId", "whatever"); - - assertSelector(message, "modelClassId LIKE 'com.whatever.something.%' AND modelInstanceId = '170' AND (modelRequestError IS NULL OR modelCorrelatedClientId = 'whatever')", - true); - - message.setStringProperty("modelCorrelatedClientId", "shouldFailNow"); - - assertSelector(message, "modelClassId LIKE 'com.whatever.something.%' AND modelInstanceId = '170' AND (modelRequestError IS NULL OR modelCorrelatedClientId = 'whatever')", - false); - - message = createMessage(); - message.setStringProperty("modelClassId", "com.whatever.something.foo.bar"); - message.setStringProperty("modelInstanceId", "170"); - message.setStringProperty("modelCorrelatedClientId", "shouldNotMatch"); - - assertSelector(message, "modelClassId LIKE 'com.whatever.something.%' AND modelInstanceId = '170' AND (modelRequestError IS NULL OR modelCorrelatedClientId = 'whatever')", - true); - } - - /** - * Test cases from Mats Henricson - */ - public void testMatsHenricsonUseCases() throws Exception { - Message message = createMessage(); - assertSelector(message, "SessionserverId=1870414179", false); - - message.setLongProperty("SessionserverId", 1870414179); - assertSelector(message, "SessionserverId=1870414179", true); - - message.setLongProperty("SessionserverId", 1234); - assertSelector(message, "SessionserverId=1870414179", false); - - assertSelector(message, "Command NOT IN ('MirrorLobbyRequest', 'MirrorLobbyReply')", false); - - message.setStringProperty("Command", "Cheese"); - assertSelector(message, "Command NOT IN ('MirrorLobbyRequest', 'MirrorLobbyReply')", true); - - message.setStringProperty("Command", "MirrorLobbyRequest"); - assertSelector(message, "Command NOT IN ('MirrorLobbyRequest', 'MirrorLobbyReply')", false); - message.setStringProperty("Command", "MirrorLobbyReply"); - assertSelector(message, "Command NOT IN ('MirrorLobbyRequest', 'MirrorLobbyReply')", false); - } - - public void testFloatComparisons() throws Exception { - Message message = createMessage(); - - assertSelector(message, "1.0 < 1.1", true); - assertSelector(message, "-1.1 < 1.0", true); - assertSelector(message, "1.0E1 < 1.1E1", true); - assertSelector(message, "-1.1E1 < 1.0E1", true); - - assertSelector(message, "1. < 1.1", true); - assertSelector(message, "-1.1 < 1.", true); - assertSelector(message, "1.E1 < 1.1E1", true); - assertSelector(message, "-1.1E1 < 1.E1", true); - - assertSelector(message, ".1 < .5", true); - assertSelector(message, "-.5 < .1", true); - assertSelector(message, ".1E1 < .5E1", true); - assertSelector(message, "-.5E1 < .1E1", true); - - assertSelector(message, "4E10 < 5E10", true); - assertSelector(message, "5E8 < 5E10", true); - assertSelector(message, "-4E10 < 2E10", true); - assertSelector(message, "-5E8 < 2E2", true); - assertSelector(message, "4E+10 < 5E+10", true); - assertSelector(message, "4E-10 < 5E-10", true); - } - - public void testStringQuoteParsing() throws Exception { - Message message = createMessage(); - assertSelector(message, "quote = '''In God We Trust'''", true); - } - - public void testLikeComparisons() throws Exception { - Message message = createMessage(); - - assertSelector(message, "quote LIKE '''In G_d We Trust'''", true); - assertSelector(message, "quote LIKE '''In Gd_ We Trust'''", false); - assertSelector(message, "quote NOT LIKE '''In G_d We Trust'''", false); - assertSelector(message, "quote NOT LIKE '''In Gd_ We Trust'''", true); - - assertSelector(message, "foo LIKE '%oo'", true); - assertSelector(message, "foo LIKE '%ar'", false); - assertSelector(message, "foo NOT LIKE '%oo'", false); - assertSelector(message, "foo NOT LIKE '%ar'", true); - - assertSelector(message, "foo LIKE '!_%' ESCAPE '!'", true); - assertSelector(message, "quote LIKE '!_%' ESCAPE '!'", false); - assertSelector(message, "foo NOT LIKE '!_%' ESCAPE '!'", false); - assertSelector(message, "quote NOT LIKE '!_%' ESCAPE '!'", true); - - assertSelector(message, "punctuation LIKE '!#$&()*+,-./:;<=>?@[\\]^`{|}~'", true); - } - - public void testInvalidSelector() throws Exception { - Message message = createMessage(); - assertInvalidSelector(message, "3+5"); - assertInvalidSelector(message, "True AND 3+5"); - assertInvalidSelector(message, "=TEST 'test'"); - } - - public void testFunctionSelector() throws Exception { - Message message = createMessage(); - assertSelector(message, "REGEX('1870414179', SessionserverId)", false); - message.setLongProperty("SessionserverId", 1870414179); - assertSelector(message, "REGEX('1870414179', SessionserverId)", true); - assertSelector(message, "REGEX('[0-9]*', SessionserverId)", true); - assertSelector(message, "REGEX('^[1-8]*$', SessionserverId)", false); - assertSelector(message, "REGEX('^[1-8]*$', SessionserverId)", false); - - assertSelector(message, "INLIST(SPLIT('Tom,Dick,George',','), name)", false); - assertSelector(message, "INLIST(SPLIT('Tom,James,George',','), name)", true); - - assertSelector(message, "INLIST(MAKELIST('Tom','Dick','George'), name)", false); - assertSelector(message, "INLIST(MAKELIST('Tom','James','George'), name)", true); - - assertSelector(message, "REGEX('connection1111', REPLACE(JMSMessageID,':',''))", true); - } - - protected Message createMessage() throws JMSException { - Message message = createMessage("FOO.BAR"); - message.setJMSType("selector-test"); - message.setJMSMessageID("connection:1:1:1:1"); - message.setObjectProperty("name", "James"); - message.setObjectProperty("location", "London"); - - message.setByteProperty("byteProp", (byte)123); - message.setByteProperty("byteProp2", (byte)33); - message.setShortProperty("shortProp", (short)123); - message.setIntProperty("intProp", 123); - message.setLongProperty("longProp", 123); - message.setFloatProperty("floatProp", 123); - message.setDoubleProperty("doubleProp", 123); - - message.setIntProperty("rank", 123); - message.setIntProperty("version", 2); - message.setStringProperty("quote", "'In God We Trust'"); - message.setStringProperty("foo", "_foo"); - message.setStringProperty("punctuation", "!#$&()*+,-./:;<=>?@[\\]^`{|}~"); - message.setBooleanProperty("trueProp", true); - message.setBooleanProperty("falseProp", false); - return message; - } - - protected void assertInvalidSelector(Message message, String text) throws JMSException { - try { - SelectorParser.parse(text); - fail("Created a valid selector"); - } catch (InvalidSelectorException e) { - } - } - - protected void assertSelector(Message message, String text, boolean expected) throws JMSException { - BooleanExpression selector = SelectorParser.parse(text); - assertTrue("Created a valid selector", selector != null); - MessageEvaluationContext context = new MessageEvaluationContext(); - context.setMessageReference((org.apache.activemq.command.Message)message); - boolean value = selector.matches(context); - assertEquals("Selector for: " + text, expected, value); - } - - protected Message createMessage(String subject) throws JMSException { - ActiveMQMessage message = new ActiveMQMessage(); - message.setJMSDestination(new ActiveMQTopic(subject)); - return message; - } + assertSelector(message, "rank / version = 61.5", true); + assertSelector(message, "rank / 3 > 100.0", false); + assertSelector(message, "rank / 3 > 100", false); + assertSelector(message, "version / 2 = 1", true); + + } + + public void testBetween() throws Exception { + Message message = createMessage(); + + assertSelector(message, "rank between 100 and 150", true); + assertSelector(message, "rank between 10 and 120", false); + } + + public void testIn() throws Exception { + Message message = createMessage(); + + assertSelector(message, "name in ('James', 'Bob', 'Gromit')", true); + assertSelector(message, "name in ('Bob', 'James', 'Gromit')", true); + assertSelector(message, "name in ('Gromit', 'Bob', 'James')", true); + + assertSelector(message, "name in ('Gromit', 'Bob', 'Cheddar')", false); + assertSelector(message, "name not in ('Gromit', 'Bob', 'Cheddar')", true); + } + + public void testIsNull() throws Exception { + Message message = createMessage(); + + assertSelector(message, "dummy is null", true); + assertSelector(message, "dummy is not null", false); + assertSelector(message, "name is not null", true); + assertSelector(message, "name is null", false); + } + + public void testLike() throws Exception { + Message message = createMessage(); + message.setStringProperty("modelClassId", "com.whatever.something.foo.bar"); + message.setStringProperty("modelInstanceId", "170"); + message.setStringProperty("modelRequestError", "abc"); + message.setStringProperty("modelCorrelatedClientId", "whatever"); + + assertSelector(message, "modelClassId LIKE 'com.whatever.something.%' AND modelInstanceId = '170' AND (modelRequestError IS NULL OR modelCorrelatedClientId = 'whatever')", true); + + message.setStringProperty("modelCorrelatedClientId", "shouldFailNow"); + + assertSelector(message, "modelClassId LIKE 'com.whatever.something.%' AND modelInstanceId = '170' AND (modelRequestError IS NULL OR modelCorrelatedClientId = 'whatever')", false); + + message = createMessage(); + message.setStringProperty("modelClassId", "com.whatever.something.foo.bar"); + message.setStringProperty("modelInstanceId", "170"); + message.setStringProperty("modelCorrelatedClientId", "shouldNotMatch"); + + assertSelector(message, "modelClassId LIKE 'com.whatever.something.%' AND modelInstanceId = '170' AND (modelRequestError IS NULL OR modelCorrelatedClientId = 'whatever')", true); + } + + /** + * Test cases from Mats Henricson + */ + public void testMatsHenricsonUseCases() throws Exception { + Message message = createMessage(); + assertSelector(message, "SessionserverId=1870414179", false); + + message.setLongProperty("SessionserverId", 1870414179); + assertSelector(message, "SessionserverId=1870414179", true); + + message.setLongProperty("SessionserverId", 1234); + assertSelector(message, "SessionserverId=1870414179", false); + + assertSelector(message, "Command NOT IN ('MirrorLobbyRequest', 'MirrorLobbyReply')", false); + + message.setStringProperty("Command", "Cheese"); + assertSelector(message, "Command NOT IN ('MirrorLobbyRequest', 'MirrorLobbyReply')", true); + + message.setStringProperty("Command", "MirrorLobbyRequest"); + assertSelector(message, "Command NOT IN ('MirrorLobbyRequest', 'MirrorLobbyReply')", false); + message.setStringProperty("Command", "MirrorLobbyReply"); + assertSelector(message, "Command NOT IN ('MirrorLobbyRequest', 'MirrorLobbyReply')", false); + } + + public void testFloatComparisons() throws Exception { + Message message = createMessage(); + + assertSelector(message, "1.0 < 1.1", true); + assertSelector(message, "-1.1 < 1.0", true); + assertSelector(message, "1.0E1 < 1.1E1", true); + assertSelector(message, "-1.1E1 < 1.0E1", true); + + assertSelector(message, "1. < 1.1", true); + assertSelector(message, "-1.1 < 1.", true); + assertSelector(message, "1.E1 < 1.1E1", true); + assertSelector(message, "-1.1E1 < 1.E1", true); + + assertSelector(message, ".1 < .5", true); + assertSelector(message, "-.5 < .1", true); + assertSelector(message, ".1E1 < .5E1", true); + assertSelector(message, "-.5E1 < .1E1", true); + + assertSelector(message, "4E10 < 5E10", true); + assertSelector(message, "5E8 < 5E10", true); + assertSelector(message, "-4E10 < 2E10", true); + assertSelector(message, "-5E8 < 2E2", true); + assertSelector(message, "4E+10 < 5E+10", true); + assertSelector(message, "4E-10 < 5E-10", true); + } + + public void testStringQuoteParsing() throws Exception { + Message message = createMessage(); + assertSelector(message, "quote = '''In God We Trust'''", true); + } + + public void testLikeComparisons() throws Exception { + Message message = createMessage(); + + assertSelector(message, "quote LIKE '''In G_d We Trust'''", true); + assertSelector(message, "quote LIKE '''In Gd_ We Trust'''", false); + assertSelector(message, "quote NOT LIKE '''In G_d We Trust'''", false); + assertSelector(message, "quote NOT LIKE '''In Gd_ We Trust'''", true); + + assertSelector(message, "foo LIKE '%oo'", true); + assertSelector(message, "foo LIKE '%ar'", false); + assertSelector(message, "foo NOT LIKE '%oo'", false); + assertSelector(message, "foo NOT LIKE '%ar'", true); + + assertSelector(message, "foo LIKE '!_%' ESCAPE '!'", true); + assertSelector(message, "quote LIKE '!_%' ESCAPE '!'", false); + assertSelector(message, "foo NOT LIKE '!_%' ESCAPE '!'", false); + assertSelector(message, "quote NOT LIKE '!_%' ESCAPE '!'", true); + + assertSelector(message, "punctuation LIKE '!#$&()*+,-./:;<=>?@[\\]^`{|}~'", true); + } + + public void testInvalidSelector() throws Exception { + Message message = createMessage(); + assertInvalidSelector(message, "3+5"); + assertInvalidSelector(message, "True AND 3+5"); + assertInvalidSelector(message, "=TEST 'test'"); + } + + public void testFunctionSelector() throws Exception { + Message message = createMessage(); + assertSelector(message, "REGEX('1870414179', SessionserverId)", false); + message.setLongProperty("SessionserverId", 1870414179); + assertSelector(message, "REGEX('1870414179', SessionserverId)", true); + assertSelector(message, "REGEX('[0-9]*', SessionserverId)", true); + assertSelector(message, "REGEX('^[1-8]*$', SessionserverId)", false); + assertSelector(message, "REGEX('^[1-8]*$', SessionserverId)", false); + + assertSelector(message, "INLIST(SPLIT('Tom,Dick,George',','), name)", false); + assertSelector(message, "INLIST(SPLIT('Tom,James,George',','), name)", true); + + assertSelector(message, "INLIST(MAKELIST('Tom','Dick','George'), name)", false); + assertSelector(message, "INLIST(MAKELIST('Tom','James','George'), name)", true); + + assertSelector(message, "REGEX('connection1111', REPLACE(JMSMessageID,':',''))", true); + } + + protected Message createMessage() throws JMSException { + Message message = createMessage("FOO.BAR"); + message.setJMSType("selector-test"); + message.setJMSMessageID("connection:1:1:1:1"); + message.setObjectProperty("name", "James"); + message.setObjectProperty("location", "London"); + + message.setByteProperty("byteProp", (byte) 123); + message.setByteProperty("byteProp2", (byte) 33); + message.setShortProperty("shortProp", (short) 123); + message.setIntProperty("intProp", 123); + message.setLongProperty("longProp", 123); + message.setFloatProperty("floatProp", 123); + message.setDoubleProperty("doubleProp", 123); + + message.setIntProperty("rank", 123); + message.setIntProperty("version", 2); + message.setStringProperty("quote", "'In God We Trust'"); + message.setStringProperty("foo", "_foo"); + message.setStringProperty("punctuation", "!#$&()*+,-./:;<=>?@[\\]^`{|}~"); + message.setBooleanProperty("trueProp", true); + message.setBooleanProperty("falseProp", false); + return message; + } + + protected void assertInvalidSelector(Message message, String text) throws JMSException { + try { + SelectorParser.parse(text); + fail("Created a valid selector"); + } + catch (InvalidSelectorException e) { + } + } + + protected void assertSelector(Message message, String text, boolean expected) throws JMSException { + BooleanExpression selector = SelectorParser.parse(text); + assertTrue("Created a valid selector", selector != null); + MessageEvaluationContext context = new MessageEvaluationContext(); + context.setMessageReference((org.apache.activemq.command.Message) message); + boolean value = selector.matches(context); + assertEquals("Selector for: " + text, expected, value); + } + + protected Message createMessage(String subject) throws JMSException { + ActiveMQMessage message = new ActiveMQMessage(); + message.setJMSDestination(new ActiveMQTopic(subject)); + return message; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/selector/UnknownHandlingSelectorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/selector/UnknownHandlingSelectorTest.java index 5c9a8eecf8..e5be653fac 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/selector/UnknownHandlingSelectorTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/selector/UnknownHandlingSelectorTest.java @@ -31,152 +31,153 @@ import org.junit.Test; public class UnknownHandlingSelectorTest { - private Message message; + private Message message; - @Before - public void setUp() throws Exception { - message = new ActiveMQMessage(); - message.setJMSDestination(new ActiveMQTopic("FOO.BAR")); - message.setJMSType("selector-test"); - message.setJMSMessageID("connection:1:1:1:1"); - message.setBooleanProperty("trueProp", true); - message.setBooleanProperty("falseProp", false); - message.setObjectProperty("nullProp", null); - } + @Before + public void setUp() throws Exception { + message = new ActiveMQMessage(); + message.setJMSDestination(new ActiveMQTopic("FOO.BAR")); + message.setJMSType("selector-test"); + message.setJMSMessageID("connection:1:1:1:1"); + message.setBooleanProperty("trueProp", true); + message.setBooleanProperty("falseProp", false); + message.setObjectProperty("nullProp", null); + } - /** - * | NOT - * +------+------ - * | T | F - * | F | T - * | U | U - * +------+------- - */ - @Test - public void notEvaluation() throws Exception { - assertSelector("not(trueProp)", false); - assertSelector("not(falseProp)", true); - assertSelector("not(unknownProp)", false); - } + /** + * | NOT + * +------+------ + * | T | F + * | F | T + * | U | U + * +------+------- + */ + @Test + public void notEvaluation() throws Exception { + assertSelector("not(trueProp)", false); + assertSelector("not(falseProp)", true); + assertSelector("not(unknownProp)", false); + } - /** - * | AND | T | F | U - * +------+-------+-------+------- - * | T | T | F | U - * | F | F | F | F - * | U | U | F | U - * +------+-------+-------+------- - */ - @Test - public void andEvaluation() throws Exception { - assertSelectorEvaluatesToTrue("trueProp AND trueProp"); - assertSelectorEvaluatesToFalse("trueProp AND falseProp"); - assertSelectorEvaluatesToFalse("falseProp AND trueProp"); - assertSelectorEvaluatesToFalse("falseProp AND falseProp"); - assertSelectorEvaluatesToFalse("falseProp AND unknownProp"); - assertSelectorEvaluatesToFalse("unknownProp AND falseProp"); - assertSelectorEvaluatesToUnknown("trueProp AND unknownProp"); - assertSelectorEvaluatesToUnknown("unknownProp AND trueProp"); - assertSelectorEvaluatesToUnknown("unknownProp AND unknownProp"); - } + /** + * | AND | T | F | U + * +------+-------+-------+------- + * | T | T | F | U + * | F | F | F | F + * | U | U | F | U + * +------+-------+-------+------- + */ + @Test + public void andEvaluation() throws Exception { + assertSelectorEvaluatesToTrue("trueProp AND trueProp"); + assertSelectorEvaluatesToFalse("trueProp AND falseProp"); + assertSelectorEvaluatesToFalse("falseProp AND trueProp"); + assertSelectorEvaluatesToFalse("falseProp AND falseProp"); + assertSelectorEvaluatesToFalse("falseProp AND unknownProp"); + assertSelectorEvaluatesToFalse("unknownProp AND falseProp"); + assertSelectorEvaluatesToUnknown("trueProp AND unknownProp"); + assertSelectorEvaluatesToUnknown("unknownProp AND trueProp"); + assertSelectorEvaluatesToUnknown("unknownProp AND unknownProp"); + } - /** - * | OR | T | F | U - * +------+-------+-------+-------- - * | T | T | T | T - * | F | T | F | U - * | U | T | U | U - * +------+-------+-------+------- - */ - @Test - public void orEvaluation() throws Exception { - assertSelectorEvaluatesToTrue("trueProp OR trueProp"); - assertSelectorEvaluatesToTrue("trueProp OR falseProp"); - assertSelectorEvaluatesToTrue("falseProp OR trueProp"); - assertSelectorEvaluatesToTrue("trueProp OR unknownProp"); - assertSelectorEvaluatesToTrue("unknownProp OR trueProp"); - assertSelectorEvaluatesToFalse("falseProp OR falseProp"); - assertSelectorEvaluatesToUnknown("falseProp OR unknownProp"); - assertSelectorEvaluatesToUnknown("unknownProp OR falseProp"); - assertSelectorEvaluatesToUnknown("unknownProp OR unknownProp"); - } + /** + * | OR | T | F | U + * +------+-------+-------+-------- + * | T | T | T | T + * | F | T | F | U + * | U | T | U | U + * +------+-------+-------+------- + */ + @Test + public void orEvaluation() throws Exception { + assertSelectorEvaluatesToTrue("trueProp OR trueProp"); + assertSelectorEvaluatesToTrue("trueProp OR falseProp"); + assertSelectorEvaluatesToTrue("falseProp OR trueProp"); + assertSelectorEvaluatesToTrue("trueProp OR unknownProp"); + assertSelectorEvaluatesToTrue("unknownProp OR trueProp"); + assertSelectorEvaluatesToFalse("falseProp OR falseProp"); + assertSelectorEvaluatesToUnknown("falseProp OR unknownProp"); + assertSelectorEvaluatesToUnknown("unknownProp OR falseProp"); + assertSelectorEvaluatesToUnknown("unknownProp OR unknownProp"); + } - @Test - public void comparisonWithUnknownShouldEvaluateToUnknown() throws Exception { - assertSelectorEvaluatesToUnknown("unknownProp = 0"); - assertSelectorEvaluatesToUnknown("unknownProp > 0"); - assertSelectorEvaluatesToUnknown("unknownProp >= 0"); - assertSelectorEvaluatesToUnknown("unknownProp < 0"); - assertSelectorEvaluatesToUnknown("unknownProp <= 0"); - assertSelectorEvaluatesToUnknown("unknownProp <> 0"); - assertSelectorEvaluatesToUnknown("unknownProp LIKE 'zero'"); - assertSelectorEvaluatesToUnknown("unknownProp NOT LIKE 'zero'"); - assertSelectorEvaluatesToUnknown("unknownProp IN ('zero')"); - assertSelectorEvaluatesToUnknown("unknownProp NOT IN ('zero')"); - assertSelectorEvaluatesToUnknown("unknownProp BETWEEN 1 AND 2"); - assertSelectorEvaluatesToUnknown("unknownProp NOT BETWEEN 1 AND 2"); - } + @Test + public void comparisonWithUnknownShouldEvaluateToUnknown() throws Exception { + assertSelectorEvaluatesToUnknown("unknownProp = 0"); + assertSelectorEvaluatesToUnknown("unknownProp > 0"); + assertSelectorEvaluatesToUnknown("unknownProp >= 0"); + assertSelectorEvaluatesToUnknown("unknownProp < 0"); + assertSelectorEvaluatesToUnknown("unknownProp <= 0"); + assertSelectorEvaluatesToUnknown("unknownProp <> 0"); + assertSelectorEvaluatesToUnknown("unknownProp LIKE 'zero'"); + assertSelectorEvaluatesToUnknown("unknownProp NOT LIKE 'zero'"); + assertSelectorEvaluatesToUnknown("unknownProp IN ('zero')"); + assertSelectorEvaluatesToUnknown("unknownProp NOT IN ('zero')"); + assertSelectorEvaluatesToUnknown("unknownProp BETWEEN 1 AND 2"); + assertSelectorEvaluatesToUnknown("unknownProp NOT BETWEEN 1 AND 2"); + } - @Test - public void comparisonWithNullPropShouldEvaluateToUnknown() throws Exception { - assertSelectorEvaluatesToUnknown("nullProp = 0"); - assertSelectorEvaluatesToUnknown("nullProp > 0"); - assertSelectorEvaluatesToUnknown("nullProp >= 0"); - assertSelectorEvaluatesToUnknown("nullProp < 0"); - assertSelectorEvaluatesToUnknown("nullProp <= 0"); - assertSelectorEvaluatesToUnknown("nullProp <> 0"); - assertSelectorEvaluatesToUnknown("nullProp LIKE 'zero'"); - assertSelectorEvaluatesToUnknown("nullProp NOT LIKE 'zero'"); - assertSelectorEvaluatesToUnknown("nullProp IN ('zero')"); - assertSelectorEvaluatesToUnknown("nullProp NOT IN ('zero')"); - assertSelectorEvaluatesToUnknown("nullProp BETWEEN 1 AND 2"); - assertSelectorEvaluatesToUnknown("nullProp NOT BETWEEN 1 AND 2"); - } + @Test + public void comparisonWithNullPropShouldEvaluateToUnknown() throws Exception { + assertSelectorEvaluatesToUnknown("nullProp = 0"); + assertSelectorEvaluatesToUnknown("nullProp > 0"); + assertSelectorEvaluatesToUnknown("nullProp >= 0"); + assertSelectorEvaluatesToUnknown("nullProp < 0"); + assertSelectorEvaluatesToUnknown("nullProp <= 0"); + assertSelectorEvaluatesToUnknown("nullProp <> 0"); + assertSelectorEvaluatesToUnknown("nullProp LIKE 'zero'"); + assertSelectorEvaluatesToUnknown("nullProp NOT LIKE 'zero'"); + assertSelectorEvaluatesToUnknown("nullProp IN ('zero')"); + assertSelectorEvaluatesToUnknown("nullProp NOT IN ('zero')"); + assertSelectorEvaluatesToUnknown("nullProp BETWEEN 1 AND 2"); + assertSelectorEvaluatesToUnknown("nullProp NOT BETWEEN 1 AND 2"); + } - @Test - public void isNullIsNotNull() throws Exception { - assertSelectorEvaluatesToTrue("unknownProp IS NULL"); - assertSelectorEvaluatesToTrue("nullProp IS NULL"); - assertSelectorEvaluatesToFalse("trueProp IS NULL"); - assertSelectorEvaluatesToFalse("unknownProp IS NOT NULL"); - assertSelectorEvaluatesToFalse("nullProp IS NOT NULL"); - assertSelectorEvaluatesToTrue("trueProp IS NOT NULL"); - } + @Test + public void isNullIsNotNull() throws Exception { + assertSelectorEvaluatesToTrue("unknownProp IS NULL"); + assertSelectorEvaluatesToTrue("nullProp IS NULL"); + assertSelectorEvaluatesToFalse("trueProp IS NULL"); + assertSelectorEvaluatesToFalse("unknownProp IS NOT NULL"); + assertSelectorEvaluatesToFalse("nullProp IS NOT NULL"); + assertSelectorEvaluatesToTrue("trueProp IS NOT NULL"); + } - @Test - public void arithmeticWithNull() throws Exception { - assertSelectorEvaluatesToUnknown("-unknownProp = 0"); - assertSelectorEvaluatesToUnknown("+unknownProp = 0"); - assertSelectorEvaluatesToUnknown("unknownProp * 2 = 0"); - assertSelectorEvaluatesToUnknown("unknownProp / 2 = 0"); - assertSelectorEvaluatesToUnknown("unknownProp + 2 = 0"); - assertSelectorEvaluatesToUnknown("unknownProp - 2 = 0"); - } + @Test + public void arithmeticWithNull() throws Exception { + assertSelectorEvaluatesToUnknown("-unknownProp = 0"); + assertSelectorEvaluatesToUnknown("+unknownProp = 0"); + assertSelectorEvaluatesToUnknown("unknownProp * 2 = 0"); + assertSelectorEvaluatesToUnknown("unknownProp / 2 = 0"); + assertSelectorEvaluatesToUnknown("unknownProp + 2 = 0"); + assertSelectorEvaluatesToUnknown("unknownProp - 2 = 0"); + } - protected void assertSelectorEvaluatesToUnknown(String selector) throws JMSException { - assertSelector(selector, false); - assertSelector(not(selector), false); - } - protected void assertSelectorEvaluatesToTrue(String selector) throws JMSException { - assertSelector(selector, true); - assertSelector(not(selector), false); - } + protected void assertSelectorEvaluatesToUnknown(String selector) throws JMSException { + assertSelector(selector, false); + assertSelector(not(selector), false); + } - protected void assertSelectorEvaluatesToFalse(String selector) throws JMSException { - assertSelector(selector, false); - assertSelector(not(selector), true); - } + protected void assertSelectorEvaluatesToTrue(String selector) throws JMSException { + assertSelector(selector, true); + assertSelector(not(selector), false); + } - protected void assertSelector(String text, boolean matches) throws JMSException { - BooleanExpression selector = SelectorParser.parse(text); - assertTrue("Created a valid selector", selector != null); - MessageEvaluationContext context = new MessageEvaluationContext(); - context.setMessageReference((org.apache.activemq.command.Message)message); - boolean value = selector.matches(context); - assertEquals("Selector for: " + text, matches, value); - } + protected void assertSelectorEvaluatesToFalse(String selector) throws JMSException { + assertSelector(selector, false); + assertSelector(not(selector), true); + } - private static String not(String selector) { - return "not(" + selector + ")"; - } + protected void assertSelector(String text, boolean matches) throws JMSException { + BooleanExpression selector = SelectorParser.parse(text); + assertTrue("Created a valid selector", selector != null); + MessageEvaluationContext context = new MessageEvaluationContext(); + context.setMessageReference((org.apache.activemq.command.Message) message); + boolean value = selector.matches(context); + assertEquals("Selector for: " + text, matches, value); + } + + private static String not(String selector) { + return "not(" + selector + ")"; + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/ActiveMQConnectionFactoryFactoryBeanTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/ActiveMQConnectionFactoryFactoryBeanTest.java index b3bc597a3a..cfa6443be5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/ActiveMQConnectionFactoryFactoryBeanTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/ActiveMQConnectionFactoryFactoryBeanTest.java @@ -20,75 +20,76 @@ package org.apache.activemq.spring; import java.util.Arrays; import junit.framework.TestCase; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class ActiveMQConnectionFactoryFactoryBeanTest extends TestCase { - private static final transient Logger LOG = LoggerFactory.getLogger(ActiveMQConnectionFactoryFactoryBeanTest.class); - private ActiveMQConnectionFactoryFactoryBean factory; + private static final transient Logger LOG = LoggerFactory.getLogger(ActiveMQConnectionFactoryFactoryBeanTest.class); + private ActiveMQConnectionFactoryFactoryBean factory; - public void testSingleTcpURL() throws Exception { - factory.setTcpHostAndPort("tcp://localhost:61616"); - assertCreatedURL("failover:(tcp://localhost:61616)"); - } + public void testSingleTcpURL() throws Exception { + factory.setTcpHostAndPort("tcp://localhost:61616"); + assertCreatedURL("failover:(tcp://localhost:61616)"); + } - public void testSingleTcpURLWithInactivityTimeout() throws Exception { - factory.setTcpHostAndPort("tcp://localhost:61616"); - factory.setMaxInactivityDuration(60000L); - assertCreatedURL("failover:(tcp://localhost:61616?wireFormat.maxInactivityDuration=60000)"); - } + public void testSingleTcpURLWithInactivityTimeout() throws Exception { + factory.setTcpHostAndPort("tcp://localhost:61616"); + factory.setMaxInactivityDuration(60000L); + assertCreatedURL("failover:(tcp://localhost:61616?wireFormat.maxInactivityDuration=60000)"); + } - public void testSingleTcpURLWithInactivityTimeoutAndTcpNoDelay() throws Exception { - factory.setTcpHostAndPort("tcp://localhost:61616"); - factory.setMaxInactivityDuration(50000L); - factory.setTcpProperties("tcpNoDelayEnabled=true"); - assertCreatedURL("failover:(tcp://localhost:61616?wireFormat.maxInactivityDuration=50000&tcpNoDelayEnabled=true)"); - } + public void testSingleTcpURLWithInactivityTimeoutAndTcpNoDelay() throws Exception { + factory.setTcpHostAndPort("tcp://localhost:61616"); + factory.setMaxInactivityDuration(50000L); + factory.setTcpProperties("tcpNoDelayEnabled=true"); + assertCreatedURL("failover:(tcp://localhost:61616?wireFormat.maxInactivityDuration=50000&tcpNoDelayEnabled=true)"); + } - public void testSingleTcpURLWithInactivityTimeoutAndMaxReconnectDelay() throws Exception { - factory.setTcpHostAndPort("tcp://localhost:61616"); - factory.setMaxInactivityDuration(60000L); - factory.setMaxReconnectDelay(50000L); - assertCreatedURL("failover:(tcp://localhost:61616?wireFormat.maxInactivityDuration=60000)?maxReconnectDelay=50000"); - } + public void testSingleTcpURLWithInactivityTimeoutAndMaxReconnectDelay() throws Exception { + factory.setTcpHostAndPort("tcp://localhost:61616"); + factory.setMaxInactivityDuration(60000L); + factory.setMaxReconnectDelay(50000L); + assertCreatedURL("failover:(tcp://localhost:61616?wireFormat.maxInactivityDuration=60000)?maxReconnectDelay=50000"); + } - public void testSingleTcpURLWithInactivityTimeoutAndMaxReconnectDelayAndFailoverProperty() throws Exception { - factory.setTcpHostAndPort("tcp://localhost:61616"); - factory.setMaxInactivityDuration(40000L); - factory.setMaxReconnectDelay(30000L); - factory.setFailoverProperties("useExponentialBackOff=false"); + public void testSingleTcpURLWithInactivityTimeoutAndMaxReconnectDelayAndFailoverProperty() throws Exception { + factory.setTcpHostAndPort("tcp://localhost:61616"); + factory.setMaxInactivityDuration(40000L); + factory.setMaxReconnectDelay(30000L); + factory.setFailoverProperties("useExponentialBackOff=false"); - assertCreatedURL("failover:(tcp://localhost:61616?wireFormat.maxInactivityDuration=40000)?maxReconnectDelay=30000&useExponentialBackOff=false"); - } + assertCreatedURL("failover:(tcp://localhost:61616?wireFormat.maxInactivityDuration=40000)?maxReconnectDelay=30000&useExponentialBackOff=false"); + } - public void testMultipleTcpURLsWithInactivityTimeoutAndMaxReconnectDelayAndFailoverProperty() throws Exception { - factory.setTcpHostAndPorts(Arrays.asList(new String[] {"tcp://localhost:61618", "tcp://foo:61619"})); - factory.setMaxInactivityDuration(40000L); - factory.setMaxReconnectDelay(30000L); - factory.setFailoverProperties("useExponentialBackOff=false"); + public void testMultipleTcpURLsWithInactivityTimeoutAndMaxReconnectDelayAndFailoverProperty() throws Exception { + factory.setTcpHostAndPorts(Arrays.asList(new String[]{"tcp://localhost:61618", "tcp://foo:61619"})); + factory.setMaxInactivityDuration(40000L); + factory.setMaxReconnectDelay(30000L); + factory.setFailoverProperties("useExponentialBackOff=false"); - assertCreatedURL("failover:(tcp://localhost:61618?wireFormat.maxInactivityDuration=40000,tcp://foo:61619?wireFormat.maxInactivityDuration=40000)?maxReconnectDelay=30000&useExponentialBackOff=false"); - } + assertCreatedURL("failover:(tcp://localhost:61618?wireFormat.maxInactivityDuration=40000,tcp://foo:61619?wireFormat.maxInactivityDuration=40000)?maxReconnectDelay=30000&useExponentialBackOff=false"); + } - protected void assertCreatedURL(String expectedURL) throws Exception { - String url = factory.getBrokerURL(); - LOG.debug("Generated URL: " + url); + protected void assertCreatedURL(String expectedURL) throws Exception { + String url = factory.getBrokerURL(); + LOG.debug("Generated URL: " + url); - assertEquals("URL", expectedURL, url); - Object value = factory.getObject(); - assertTrue("Value should be an ActiveMQConnectionFactory", value instanceof ActiveMQConnectionFactory); - ActiveMQConnectionFactory connectionFactory = (ActiveMQConnectionFactory) value; - String brokerURL = connectionFactory.getBrokerURL(); - assertEquals("brokerURL", expectedURL, brokerURL); - } + assertEquals("URL", expectedURL, url); + Object value = factory.getObject(); + assertTrue("Value should be an ActiveMQConnectionFactory", value instanceof ActiveMQConnectionFactory); + ActiveMQConnectionFactory connectionFactory = (ActiveMQConnectionFactory) value; + String brokerURL = connectionFactory.getBrokerURL(); + assertEquals("brokerURL", expectedURL, brokerURL); + } - @Override - protected void setUp() throws Exception { - factory = new ActiveMQConnectionFactoryFactoryBean(); - } + @Override + protected void setUp() throws Exception { + factory = new ActiveMQConnectionFactoryFactoryBean(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/ConsumerBean.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/ConsumerBean.java index 4e1ab59b32..1aa215671d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/ConsumerBean.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/ConsumerBean.java @@ -27,146 +27,145 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ConsumerBean extends Assert implements MessageListener { - private static final Logger LOG = LoggerFactory.getLogger(ConsumerBean.class); - private final List messages = new ArrayList(); - private boolean verbose; - /** - * Constructor. - */ - public ConsumerBean() { - } + private static final Logger LOG = LoggerFactory.getLogger(ConsumerBean.class); + private final List messages = new ArrayList(); + private boolean verbose; - /** - * @return all the messages on the list so far, clearing the buffer - */ - public List flushMessages() { - List answer = null; - synchronized(messages) { - answer = new ArrayList(messages); - messages.clear(); - } - return answer; - } + /** + * Constructor. + */ + public ConsumerBean() { + } - /** - * Method implemented from MessageListener interface. - * - * @param message - */ - @Override - public void onMessage(Message message) { - synchronized (messages) { - messages.add(message); - if (verbose) { - LOG.info("Received: " + message); + /** + * @return all the messages on the list so far, clearing the buffer + */ + public List flushMessages() { + List answer = null; + synchronized (messages) { + answer = new ArrayList(messages); + messages.clear(); + } + return answer; + } + + /** + * Method implemented from MessageListener interface. + * + * @param message + */ + @Override + public void onMessage(Message message) { + synchronized (messages) { + messages.add(message); + if (verbose) { + LOG.info("Received: " + message); + } + messages.notifyAll(); + } + } + + /** + * Use to wait for a single message to arrive. + */ + public void waitForMessageToArrive() { + LOG.info("Waiting for message to arrive"); + + long start = System.currentTimeMillis(); + + synchronized (messages) { + try { + while (hasReceivedMessage()) { + messages.wait(4000); } - messages.notifyAll(); - } - } + } + catch (InterruptedException e) { + LOG.info("Caught: " + e); + } + } + long end = System.currentTimeMillis() - start; - /** - * Use to wait for a single message to arrive. - */ - public void waitForMessageToArrive() { - LOG.info("Waiting for message to arrive"); + LOG.info("End of wait for " + end + " millis"); + } - long start = System.currentTimeMillis(); + /** + * Used to wait for a message to arrive given a particular message count. + * + * @param messageCount + */ - synchronized(messages) - { - try - { - while (hasReceivedMessage()) - { - messages.wait(4000); - } + public void waitForMessagesToArrive(int messageCount) { + waitForMessagesToArrive(messageCount, 120 * 1000); + } + + public void waitForMessagesToArrive(int messageCount, long maxWaitTime) { + long maxRemainingMessageCount = Math.max(0, messageCount - messages.size()); + LOG.info("Waiting for (" + maxRemainingMessageCount + ") message(s) to arrive"); + long start = System.currentTimeMillis(); + long endTime = start + maxWaitTime; + synchronized (messages) { + while (maxRemainingMessageCount > 0) { + try { + messages.wait(1000); + if (hasReceivedMessages(messageCount) || System.currentTimeMillis() > endTime) { + break; + } } - catch (InterruptedException e) - { - LOG.info("Caught: " + e); + catch (InterruptedException e) { + LOG.info("Caught: " + e); } - } - long end = System.currentTimeMillis() - start; + maxRemainingMessageCount = Math.max(0, messageCount - messages.size()); + } + } + long end = System.currentTimeMillis() - start; + LOG.info("End of wait for " + end + " millis"); + } - LOG.info("End of wait for " + end + " millis"); - } + public void assertMessagesArrived(int total) { + waitForMessagesToArrive(total); + synchronized (messages) { + int count = messages.size(); - /** - * Used to wait for a message to arrive given a particular message count. - * - * @param messageCount - */ + assertEquals("Messages received", total, count); + } + } - public void waitForMessagesToArrive(int messageCount){ - waitForMessagesToArrive(messageCount,120 * 1000); - } - public void waitForMessagesToArrive(int messageCount,long maxWaitTime) { - long maxRemainingMessageCount = Math.max(0, messageCount - messages.size()); - LOG.info("Waiting for (" + maxRemainingMessageCount + ") message(s) to arrive"); - long start = System.currentTimeMillis(); - long endTime = start + maxWaitTime; - synchronized (messages) { - while (maxRemainingMessageCount > 0) { - try { - messages.wait(1000); - if (hasReceivedMessages(messageCount) || System.currentTimeMillis() > endTime) { - break; - } - } catch (InterruptedException e) { - LOG.info("Caught: " + e); - } - maxRemainingMessageCount = Math.max(0, messageCount - messages.size()); - } - } - long end = System.currentTimeMillis() - start; - LOG.info("End of wait for " + end + " millis"); - } + public void assertMessagesArrived(int total, long maxWaitTime) { + waitForMessagesToArrive(total, maxWaitTime); + synchronized (messages) { + int count = messages.size(); - public void assertMessagesArrived(int total) { - waitForMessagesToArrive(total); - synchronized (messages) { - int count = messages.size(); + assertEquals("Messages received", total, count); + } + } - assertEquals("Messages received", total, count); - } - } + public boolean isVerbose() { + return verbose; + } - public void assertMessagesArrived(int total, long maxWaitTime) { - waitForMessagesToArrive(total,maxWaitTime); - synchronized (messages) { - int count = messages.size(); + public void setVerbose(boolean verbose) { + this.verbose = verbose; + } - assertEquals("Messages received", total, count); - } - } + /** + * Identifies if the message is empty. + * + * @return + */ + protected boolean hasReceivedMessage() { + return messages.isEmpty(); + } - public boolean isVerbose() { - return verbose; - } - - public void setVerbose(boolean verbose) { - this.verbose = verbose; - } - - /** - * Identifies if the message is empty. - * - * @return - */ - protected boolean hasReceivedMessage() { - return messages.isEmpty(); - } - - /** - * Identifies if the message count has reached the total size of message. - * - * @param messageCount - * @return - */ - protected boolean hasReceivedMessages(int messageCount) { - synchronized (messages) { - return messages.size() >= messageCount; - } - } + /** + * Identifies if the message count has reached the total size of message. + * + * @param messageCount + * @return + */ + protected boolean hasReceivedMessages(int messageCount) { + synchronized (messages) { + return messages.size() >= messageCount; + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/Spring2XmlNamespacesTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/Spring2XmlNamespacesTest.java index ca62d01fc2..136e9bb182 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/Spring2XmlNamespacesTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/Spring2XmlNamespacesTest.java @@ -17,7 +17,8 @@ package org.apache.activemq.spring; public class Spring2XmlNamespacesTest extends SpringTestSupport { - public void testUsingSpringXmlNamespacesWithPublicXsdLocation() throws Exception { - assertSenderConfig("spring-embedded-xbean.xml"); - } + + public void testUsingSpringXmlNamespacesWithPublicXsdLocation() throws Exception { + assertSenderConfig("spring-embedded-xbean.xml"); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/Spring2XmlNamespacesWithoutRemoteSchemaTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/Spring2XmlNamespacesWithoutRemoteSchemaTest.java index 7a3287739e..deae99b892 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/Spring2XmlNamespacesWithoutRemoteSchemaTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/Spring2XmlNamespacesWithoutRemoteSchemaTest.java @@ -17,7 +17,8 @@ package org.apache.activemq.spring; public class Spring2XmlNamespacesWithoutRemoteSchemaTest extends SpringTestSupport { - public void testUsingSpring2NamespacesForANonExistingXsdDocument() throws Exception { - assertSenderConfig("spring-embedded-xbean-noversion.xml"); - } + + public void testUsingSpring2NamespacesForANonExistingXsdDocument() throws Exception { + assertSenderConfig("spring-embedded-xbean-noversion.xml"); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringConsumer.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringConsumer.java index ed0a48af8b..dc676ae588 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringConsumer.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringConsumer.java @@ -30,84 +30,87 @@ import org.slf4j.LoggerFactory; import org.springframework.jms.core.JmsTemplate; public class SpringConsumer extends ConsumerBean implements MessageListener { - private static final Logger LOG = LoggerFactory.getLogger(SpringConsumer.class); - private JmsTemplate template; - private String myId = "foo"; - private Destination destination; - private Connection connection; - private Session session; - private MessageConsumer consumer; - public void start() throws JMSException { - String selector = "next = '" + myId + "'"; + private static final Logger LOG = LoggerFactory.getLogger(SpringConsumer.class); + private JmsTemplate template; + private String myId = "foo"; + private Destination destination; + private Connection connection; + private Session session; + private MessageConsumer consumer; - try { - ConnectionFactory factory = template.getConnectionFactory(); - final Connection c = connection = factory.createConnection(); + public void start() throws JMSException { + String selector = "next = '" + myId + "'"; - // we might be a reusable connection in spring - // so lets only set the client ID once if its not set - synchronized (c) { - if (c.getClientID() == null) { - c.setClientID(myId); - } + try { + ConnectionFactory factory = template.getConnectionFactory(); + final Connection c = connection = factory.createConnection(); + + // we might be a reusable connection in spring + // so lets only set the client ID once if its not set + synchronized (c) { + if (c.getClientID() == null) { + c.setClientID(myId); } + } - connection.start(); + connection.start(); - session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); - consumer = session.createConsumer(destination, selector, false); - consumer.setMessageListener(this); - } catch (JMSException ex) { - LOG.error("", ex); - throw ex; - } - } + session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); + consumer = session.createConsumer(destination, selector, false); + consumer.setMessageListener(this); + } + catch (JMSException ex) { + LOG.error("", ex); + throw ex; + } + } - public void stop() throws JMSException { - if (consumer != null) { - consumer.close(); - } - if (session != null) { - session.close(); - } - if (connection != null) { - connection.close(); - } - } + public void stop() throws JMSException { + if (consumer != null) { + consumer.close(); + } + if (session != null) { + session.close(); + } + if (connection != null) { + connection.close(); + } + } - public void onMessage(Message message) { - super.onMessage(message); - try { - message.acknowledge(); - } catch (JMSException e) { - LOG.error("Failed to acknowledge: " + e, e); - } - } + public void onMessage(Message message) { + super.onMessage(message); + try { + message.acknowledge(); + } + catch (JMSException e) { + LOG.error("Failed to acknowledge: " + e, e); + } + } - // Properties - // ------------------------------------------------------------------------- - public Destination getDestination() { - return destination; - } + // Properties + // ------------------------------------------------------------------------- + public Destination getDestination() { + return destination; + } - public void setDestination(Destination destination) { - this.destination = destination; - } + public void setDestination(Destination destination) { + this.destination = destination; + } - public String getMyId() { - return myId; - } + public String getMyId() { + return myId; + } - public void setMyId(String myId) { - this.myId = myId; - } + public void setMyId(String myId) { + this.myId = myId; + } - public JmsTemplate getTemplate() { - return template; - } + public JmsTemplate getTemplate() { + return template; + } - public void setTemplate(JmsTemplate template) { - this.template = template; - } + public void setTemplate(JmsTemplate template) { + this.template = template; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringProducer.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringProducer.java index c2bbad07c5..c791480502 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringProducer.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringProducer.java @@ -28,52 +28,53 @@ import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.core.MessageCreator; public class SpringProducer { - private static final Logger LOG = LoggerFactory.getLogger(SpringProducer.class); - private JmsTemplate template; - private Destination destination; - private int messageCount = 10; - public void start() throws JMSException { - for (int i = 0; i < messageCount; i++) { - final String text = "Text for message: " + i; - template.send(destination, new MessageCreator() { - public Message createMessage(Session session) throws JMSException { - LOG.info("Sending message: " + text); - TextMessage message = session.createTextMessage(text); - message.setStringProperty("next", "foo"); - return message; - } - }); - } - } + private static final Logger LOG = LoggerFactory.getLogger(SpringProducer.class); + private JmsTemplate template; + private Destination destination; + private int messageCount = 10; - public void stop() throws JMSException { - } + public void start() throws JMSException { + for (int i = 0; i < messageCount; i++) { + final String text = "Text for message: " + i; + template.send(destination, new MessageCreator() { + public Message createMessage(Session session) throws JMSException { + LOG.info("Sending message: " + text); + TextMessage message = session.createTextMessage(text); + message.setStringProperty("next", "foo"); + return message; + } + }); + } + } - // Properties - //------------------------------------------------------------------------- + public void stop() throws JMSException { + } - public JmsTemplate getTemplate() { - return template; - } + // Properties + //------------------------------------------------------------------------- - public void setTemplate(JmsTemplate template) { - this.template = template; - } + public JmsTemplate getTemplate() { + return template; + } - public int getMessageCount() { - return messageCount; - } + public void setTemplate(JmsTemplate template) { + this.template = template; + } - public void setMessageCount(int messageCount) { - this.messageCount = messageCount; - } + public int getMessageCount() { + return messageCount; + } - public Destination getDestination() { - return destination; - } + public void setMessageCount(int messageCount) { + this.messageCount = messageCount; + } - public void setDestination(Destination destination) { - this.destination = destination; - } + public Destination getDestination() { + return destination; + } + + public void setDestination(Destination destination) { + this.destination = destination; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringTest.java index 9bea3edc40..fb48a5f387 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringTest.java @@ -21,78 +21,78 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringTest extends SpringTestSupport { - /** - * Uses ActiveMQConnectionFactory to create the connection context. - * Configuration file is /resources/spring.xml - * - * @throws Exception - */ - public void testSenderWithSpringXml() throws Exception { - String config = "spring.xml"; - assertSenderConfig(config); - } + /** + * Uses ActiveMQConnectionFactory to create the connection context. + * Configuration file is /resources/spring.xml + * + * @throws Exception + */ + public void testSenderWithSpringXml() throws Exception { + String config = "spring.xml"; + assertSenderConfig(config); + } - /** - * Spring configured test that uses ActiveMQConnectionFactory for - * connection context and ActiveMQQueue for destination. Configuration - * file is /resources/spring-queue.xml. - * - * @throws Exception - */ - public void testSenderWithSpringXmlAndQueue() throws Exception { - String config = "spring-queue.xml"; - assertSenderConfig(config); - } + /** + * Spring configured test that uses ActiveMQConnectionFactory for + * connection context and ActiveMQQueue for destination. Configuration + * file is /resources/spring-queue.xml. + * + * @throws Exception + */ + public void testSenderWithSpringXmlAndQueue() throws Exception { + String config = "spring-queue.xml"; + assertSenderConfig(config); + } - /** - * Spring configured test that uses JNDI. Configuration file is - * /resources/spring-jndi.xml. - * - * @throws Exception - */ - public void testSenderWithSpringXmlUsingJNDI() throws Exception { - String config = "spring-jndi.xml"; - assertSenderConfig(config); - } + /** + * Spring configured test that uses JNDI. Configuration file is + * /resources/spring-jndi.xml. + * + * @throws Exception + */ + public void testSenderWithSpringXmlUsingJNDI() throws Exception { + String config = "spring-jndi.xml"; + assertSenderConfig(config); + } - /** - * Spring configured test where in the connection context is set to use - * an embedded broker. Configuration file is /resources/spring-embedded.xml - * and /resources/activemq.xml. - * - * @throws Exception - */ - public void testSenderWithSpringXmlEmbeddedBrokerConfiguredViaXml() throws Exception { - String config = "spring-embedded.xml"; - assertSenderConfig(config); - } + /** + * Spring configured test where in the connection context is set to use + * an embedded broker. Configuration file is /resources/spring-embedded.xml + * and /resources/activemq.xml. + * + * @throws Exception + */ + public void testSenderWithSpringXmlEmbeddedBrokerConfiguredViaXml() throws Exception { + String config = "spring-embedded.xml"; + assertSenderConfig(config); + } - /** - * Spring configured test case that tests the remotely deployed xsd - * http://people.apache.org/repository/org.apache.activemq/xsds/activemq-core-4.1-SNAPSHOT.xsd - * - * @throws Exception - */ - public void testSenderWithSpringXmlUsingSpring2NamespacesWithEmbeddedBrokerConfiguredViaXml() throws Exception { - String config = "spring-embedded-xbean.xml"; - assertSenderConfig(config); - } + /** + * Spring configured test case that tests the remotely deployed xsd + * http://people.apache.org/repository/org.apache.activemq/xsds/activemq-core-4.1-SNAPSHOT.xsd + * + * @throws Exception + */ + public void testSenderWithSpringXmlUsingSpring2NamespacesWithEmbeddedBrokerConfiguredViaXml() throws Exception { + String config = "spring-embedded-xbean.xml"; + assertSenderConfig(config); + } - /** - * Spring configured test case that tests the locally generated xsd - * - * @throws Exception - */ - public void testSenderWithSpringXmlUsingSpring2NamespacesWithEmbeddedBrokerConfiguredViaXmlUsingLocalXsd() throws Exception { - String config = "spring-embedded-xbean-local.xml"; - assertSenderConfig(config); - } - - public void testStartFalse() throws Exception { - String config = "spring-start-false.xml"; - Thread.currentThread().setContextClassLoader(SpringTest.class.getClassLoader()); - context = new ClassPathXmlApplicationContext(config); - BrokerService broker = (BrokerService)context.getBean(BrokerService.class); - assertFalse("Broker is started", broker.isStarted()); - } + /** + * Spring configured test case that tests the locally generated xsd + * + * @throws Exception + */ + public void testSenderWithSpringXmlUsingSpring2NamespacesWithEmbeddedBrokerConfiguredViaXmlUsingLocalXsd() throws Exception { + String config = "spring-embedded-xbean-local.xml"; + assertSenderConfig(config); + } + + public void testStartFalse() throws Exception { + String config = "spring-start-false.xml"; + Thread.currentThread().setContextClassLoader(SpringTest.class.getClassLoader()); + context = new ClassPathXmlApplicationContext(config); + BrokerService broker = (BrokerService) context.getBean(BrokerService.class); + assertFalse("Broker is started", broker.isStarted()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringTestSupport.java index 53ec6d9b2e..b470c4d50c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringTestSupport.java @@ -32,66 +32,67 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; * */ public class SpringTestSupport extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(SpringTest.class); - protected AbstractApplicationContext context; - protected SpringConsumer consumer; - protected SpringProducer producer; - /** - * assert method that is used by all the test method to send and receive messages - * based on each spring configuration. - * - * @param config - * @throws Exception - */ - protected void assertSenderConfig(String config) throws Exception { - Thread.currentThread().setContextClassLoader(SpringTest.class.getClassLoader()); - context = new ClassPathXmlApplicationContext(config); + private static final Logger LOG = LoggerFactory.getLogger(SpringTest.class); + protected AbstractApplicationContext context; + protected SpringConsumer consumer; + protected SpringProducer producer; - consumer = (SpringConsumer) context.getBean("consumer"); - assertTrue("Found a valid consumer", consumer != null); + /** + * assert method that is used by all the test method to send and receive messages + * based on each spring configuration. + * + * @param config + * @throws Exception + */ + protected void assertSenderConfig(String config) throws Exception { + Thread.currentThread().setContextClassLoader(SpringTest.class.getClassLoader()); + context = new ClassPathXmlApplicationContext(config); - consumer.start(); + consumer = (SpringConsumer) context.getBean("consumer"); + assertTrue("Found a valid consumer", consumer != null); - // Wait a little to drain any left over messages. - Thread.sleep(1000); - consumer.flushMessages(); + consumer.start(); - producer = (SpringProducer) context.getBean("producer"); - assertTrue("Found a valid producer", producer != null); + // Wait a little to drain any left over messages. + Thread.sleep(1000); + consumer.flushMessages(); - producer.start(); + producer = (SpringProducer) context.getBean("producer"); + assertTrue("Found a valid producer", producer != null); - // lets sleep a little to give the JMS time to dispatch stuff - consumer.waitForMessagesToArrive(producer.getMessageCount()); + producer.start(); - // now lets check that the consumer has received some messages - List messages = consumer.flushMessages(); - LOG.info("Consumer has received messages...."); - for (Iterator iter = messages.iterator(); iter.hasNext();) { - Object message = iter.next(); - LOG.info("Received: " + message); - } + // lets sleep a little to give the JMS time to dispatch stuff + consumer.waitForMessagesToArrive(producer.getMessageCount()); - assertEquals("Message count", producer.getMessageCount(), messages.size()); - } + // now lets check that the consumer has received some messages + List messages = consumer.flushMessages(); + LOG.info("Consumer has received messages...."); + for (Iterator iter = messages.iterator(); iter.hasNext(); ) { + Object message = iter.next(); + LOG.info("Received: " + message); + } - /** - * Clean up method. - * - * @throws Exception - */ - @Override - protected void tearDown() throws Exception { - if (consumer != null) { - consumer.stop(); - } - if (producer != null) { - producer.stop(); - } + assertEquals("Message count", producer.getMessageCount(), messages.size()); + } - if (context != null) { - context.destroy(); - } - } + /** + * Clean up method. + * + * @throws Exception + */ + @Override + protected void tearDown() throws Exception { + if (consumer != null) { + consumer.stop(); + } + if (producer != null) { + producer.stop(); + } + + if (context != null) { + context.destroy(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/AutoStorePerDestinationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/AutoStorePerDestinationTest.java index 2b76a224df..8c1f3865f3 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/AutoStorePerDestinationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/AutoStorePerDestinationTest.java @@ -17,26 +17,27 @@ package org.apache.activemq.store; import java.util.ArrayList; + import org.apache.activemq.store.kahadb.FilteredKahaDBPersistenceAdapter; import org.apache.activemq.store.kahadb.MultiKahaDBPersistenceAdapter; public class AutoStorePerDestinationTest extends StorePerDestinationTest { - // use perDestinationFlag to get multiple stores from one match all adapter - public void prepareBrokerWithMultiStore(boolean deleteAllMessages) throws Exception { + // use perDestinationFlag to get multiple stores from one match all adapter + public void prepareBrokerWithMultiStore(boolean deleteAllMessages) throws Exception { - MultiKahaDBPersistenceAdapter multiKahaDBPersistenceAdapter = new MultiKahaDBPersistenceAdapter(); - if (deleteAllMessages) { - multiKahaDBPersistenceAdapter.deleteAllMessages(); - } - ArrayList adapters = new ArrayList(); + MultiKahaDBPersistenceAdapter multiKahaDBPersistenceAdapter = new MultiKahaDBPersistenceAdapter(); + if (deleteAllMessages) { + multiKahaDBPersistenceAdapter.deleteAllMessages(); + } + ArrayList adapters = new ArrayList(); - FilteredKahaDBPersistenceAdapter template = new FilteredKahaDBPersistenceAdapter(); - template.setPersistenceAdapter(createStore(deleteAllMessages)); - template.setPerDestination(true); - adapters.add(template); + FilteredKahaDBPersistenceAdapter template = new FilteredKahaDBPersistenceAdapter(); + template.setPersistenceAdapter(createStore(deleteAllMessages)); + template.setPerDestination(true); + adapters.add(template); - multiKahaDBPersistenceAdapter.setFilteredPersistenceAdapters(adapters); - brokerService = createBroker(multiKahaDBPersistenceAdapter); - } + multiKahaDBPersistenceAdapter.setFilteredPersistenceAdapters(adapters); + brokerService = createBroker(multiKahaDBPersistenceAdapter); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/LevelDBStorePerDestinationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/LevelDBStorePerDestinationTest.java index b10786cf86..028fb557d4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/LevelDBStorePerDestinationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/LevelDBStorePerDestinationTest.java @@ -21,25 +21,26 @@ import org.junit.Test; import java.io.IOException; -public class LevelDBStorePerDestinationTest extends StorePerDestinationTest { +public class LevelDBStorePerDestinationTest extends StorePerDestinationTest { - - @Override - protected PersistenceAdapter createStore(boolean delete) throws IOException { - LevelDBStore store = new LevelDBStore(); - store.setLogSize(maxFileLength); - if (delete) { - store.deleteAllMessages(); - } - return store; - } + @Override + protected PersistenceAdapter createStore(boolean delete) throws IOException { + LevelDBStore store = new LevelDBStore(); + store.setLogSize(maxFileLength); + if (delete) { + store.deleteAllMessages(); + } + return store; + } @Test @Override - public void testRollbackRecovery() throws Exception {} + public void testRollbackRecovery() throws Exception { + } @Test @Override - public void testCommitRecovery() throws Exception {} + public void testCommitRecovery() throws Exception { + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/MessagePriorityTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/MessagePriorityTest.java index 521c8991ea..a70ef678c7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/MessagePriorityTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/MessagePriorityTest.java @@ -44,544 +44,541 @@ import org.slf4j.LoggerFactory; abstract public class MessagePriorityTest extends CombinationTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(MessagePriorityTest.class); + private static final Logger LOG = LoggerFactory.getLogger(MessagePriorityTest.class); - BrokerService broker; - PersistenceAdapter adapter; + BrokerService broker; + PersistenceAdapter adapter; - protected ActiveMQConnectionFactory factory; - protected Connection conn; - protected Session sess; + protected ActiveMQConnectionFactory factory; + protected Connection conn; + protected Session sess; - public boolean useCache = true; - public int deliveryMode = Message.DEFAULT_DELIVERY_MODE; - public boolean dispatchAsync = true; - public boolean prioritizeMessages = true; - public boolean immediatePriorityDispatch = true; - public int prefetchVal = 500; - public int expireMessagePeriod = 30000; + public boolean useCache = true; + public int deliveryMode = Message.DEFAULT_DELIVERY_MODE; + public boolean dispatchAsync = true; + public boolean prioritizeMessages = true; + public boolean immediatePriorityDispatch = true; + public int prefetchVal = 500; + public int expireMessagePeriod = 30000; - public int MSG_NUM = 600; - public int HIGH_PRI = 7; - public int LOW_PRI = 3; + public int MSG_NUM = 600; + public int HIGH_PRI = 7; + public int LOW_PRI = 3; - abstract protected PersistenceAdapter createPersistenceAdapter(boolean delete) throws Exception; + abstract protected PersistenceAdapter createPersistenceAdapter(boolean delete) throws Exception; - @Override - protected void setUp() throws Exception { - broker = new BrokerService(); - broker.setBrokerName("priorityTest"); - broker.setAdvisorySupport(false); - adapter = createPersistenceAdapter(true); - broker.setPersistenceAdapter(adapter); - PolicyEntry policy = new PolicyEntry(); - policy.setPrioritizedMessages(prioritizeMessages); - policy.setUseCache(useCache); - policy.setExpireMessagesPeriod(expireMessagePeriod); - StorePendingDurableSubscriberMessageStoragePolicy durableSubPending = - new StorePendingDurableSubscriberMessageStoragePolicy(); - durableSubPending.setImmediatePriorityDispatch(immediatePriorityDispatch); - durableSubPending.setUseCache(useCache); - policy.setPendingDurableSubscriberPolicy(durableSubPending); - PolicyMap policyMap = new PolicyMap(); - policyMap.put(new ActiveMQQueue("TEST"), policy); - policyMap.put(new ActiveMQTopic("TEST"), policy); + @Override + protected void setUp() throws Exception { + broker = new BrokerService(); + broker.setBrokerName("priorityTest"); + broker.setAdvisorySupport(false); + adapter = createPersistenceAdapter(true); + broker.setPersistenceAdapter(adapter); + PolicyEntry policy = new PolicyEntry(); + policy.setPrioritizedMessages(prioritizeMessages); + policy.setUseCache(useCache); + policy.setExpireMessagesPeriod(expireMessagePeriod); + StorePendingDurableSubscriberMessageStoragePolicy durableSubPending = new StorePendingDurableSubscriberMessageStoragePolicy(); + durableSubPending.setImmediatePriorityDispatch(immediatePriorityDispatch); + durableSubPending.setUseCache(useCache); + policy.setPendingDurableSubscriberPolicy(durableSubPending); + PolicyMap policyMap = new PolicyMap(); + policyMap.put(new ActiveMQQueue("TEST"), policy); + policyMap.put(new ActiveMQTopic("TEST"), policy); - // do not process expired for one test - PolicyEntry ignoreExpired = new PolicyEntry(); - SharedDeadLetterStrategy ignoreExpiredStrategy = new SharedDeadLetterStrategy(); - ignoreExpiredStrategy.setProcessExpired(false); - ignoreExpired.setDeadLetterStrategy(ignoreExpiredStrategy); - policyMap.put(new ActiveMQTopic("TEST_CLEANUP_NO_PRIORITY"), ignoreExpired); + // do not process expired for one test + PolicyEntry ignoreExpired = new PolicyEntry(); + SharedDeadLetterStrategy ignoreExpiredStrategy = new SharedDeadLetterStrategy(); + ignoreExpiredStrategy.setProcessExpired(false); + ignoreExpired.setDeadLetterStrategy(ignoreExpiredStrategy); + policyMap.put(new ActiveMQTopic("TEST_CLEANUP_NO_PRIORITY"), ignoreExpired); - broker.setDestinationPolicy(policyMap); - broker.start(); - broker.waitUntilStarted(); + broker.setDestinationPolicy(policyMap); + broker.start(); + broker.waitUntilStarted(); - factory = new ActiveMQConnectionFactory("vm://priorityTest"); - ActiveMQPrefetchPolicy prefetch = new ActiveMQPrefetchPolicy(); - prefetch.setAll(prefetchVal); - factory.setPrefetchPolicy(prefetch); - factory.setWatchTopicAdvisories(false); - factory.setDispatchAsync(dispatchAsync); - conn = factory.createConnection(); - conn.setClientID("priority"); - conn.start(); - sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - } + factory = new ActiveMQConnectionFactory("vm://priorityTest"); + ActiveMQPrefetchPolicy prefetch = new ActiveMQPrefetchPolicy(); + prefetch.setAll(prefetchVal); + factory.setPrefetchPolicy(prefetch); + factory.setWatchTopicAdvisories(false); + factory.setDispatchAsync(dispatchAsync); + conn = factory.createConnection(); + conn.setClientID("priority"); + conn.start(); + sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + } - @Override - protected void tearDown() throws Exception { - try { - sess.close(); - conn.close(); - } catch (Exception ignored) { - } finally { - broker.stop(); - broker.waitUntilStopped(); - } - } + @Override + protected void tearDown() throws Exception { + try { + sess.close(); + conn.close(); + } + catch (Exception ignored) { + } + finally { + broker.stop(); + broker.waitUntilStopped(); + } + } - public void testStoreConfigured() throws Exception { - final Queue queue = sess.createQueue("TEST"); - final Topic topic = sess.createTopic("TEST"); + public void testStoreConfigured() throws Exception { + final Queue queue = sess.createQueue("TEST"); + final Topic topic = sess.createTopic("TEST"); - MessageProducer queueProducer = sess.createProducer(queue); - MessageProducer topicProducer = sess.createProducer(topic); + MessageProducer queueProducer = sess.createProducer(queue); + MessageProducer topicProducer = sess.createProducer(topic); - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return broker.getRegionBroker().getDestinationMap().get(queue) != null; + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return broker.getRegionBroker().getDestinationMap().get(queue) != null; + } + }); + assertTrue(broker.getRegionBroker().getDestinationMap().get(queue).getMessageStore().isPrioritizedMessages()); + + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return broker.getRegionBroker().getDestinationMap().get(topic) != null; + } + }); + assertTrue(broker.getRegionBroker().getDestinationMap().get(topic).getMessageStore().isPrioritizedMessages()); + + queueProducer.close(); + topicProducer.close(); + + } + + protected class ProducerThread extends Thread { + + int priority; + int messageCount; + ActiveMQDestination dest; + + public ProducerThread(ActiveMQDestination dest, int messageCount, int priority) { + this.messageCount = messageCount; + this.priority = priority; + this.dest = dest; + } + + @Override + public void run() { + try { + MessageProducer producer = sess.createProducer(dest); + producer.setPriority(priority); + producer.setDeliveryMode(deliveryMode); + for (int i = 0; i < messageCount; i++) { + producer.send(sess.createTextMessage("message priority: " + priority)); } - }); - assertTrue(broker.getRegionBroker().getDestinationMap().get(queue).getMessageStore().isPrioritizedMessages()); + } + catch (Exception e) { + e.printStackTrace(); + } + } - Wait.waitFor(new Wait.Condition(){ - @Override - public boolean isSatisified() throws Exception { - return broker.getRegionBroker().getDestinationMap().get(topic) != null; + public void setMessagePriority(int priority) { + this.priority = priority; + } + + public void setMessageCount(int messageCount) { + this.messageCount = messageCount; + } + + } + + public void initCombosForTestQueues() { + addCombinationValues("useCache", new Object[]{new Boolean(true), new Boolean(false)}); + addCombinationValues("deliveryMode", new Object[]{new Integer(DeliveryMode.NON_PERSISTENT), new Integer(DeliveryMode.PERSISTENT)}); + } + + public void testQueues() throws Exception { + ActiveMQQueue queue = (ActiveMQQueue) sess.createQueue("TEST"); + + ProducerThread lowPri = new ProducerThread(queue, MSG_NUM, LOW_PRI); + ProducerThread highPri = new ProducerThread(queue, MSG_NUM, HIGH_PRI); + + lowPri.start(); + highPri.start(); + + lowPri.join(); + highPri.join(); + + MessageConsumer queueConsumer = sess.createConsumer(queue); + for (int i = 0; i < MSG_NUM * 2; i++) { + Message msg = queueConsumer.receive(5000); + LOG.debug("received i=" + i + ", " + (msg != null ? msg.getJMSMessageID() : null)); + assertNotNull("Message " + i + " was null", msg); + assertEquals("Message " + i + " has wrong priority", i < MSG_NUM ? HIGH_PRI : LOW_PRI, msg.getJMSPriority()); + } + } + + protected Message createMessage(int priority) throws Exception { + final String text = "priority " + priority; + Message msg = sess.createTextMessage(text); + LOG.info("Sending " + text); + return msg; + } + + public void initCombosForTestDurableSubs() { + addCombinationValues("prefetchVal", new Object[]{new Integer(1000), new Integer(MSG_NUM / 4)}); + } + + public void testDurableSubs() throws Exception { + ActiveMQTopic topic = (ActiveMQTopic) sess.createTopic("TEST"); + TopicSubscriber sub = sess.createDurableSubscriber(topic, "priority"); + sub.close(); + + ProducerThread lowPri = new ProducerThread(topic, MSG_NUM, LOW_PRI); + ProducerThread highPri = new ProducerThread(topic, MSG_NUM, HIGH_PRI); + + lowPri.start(); + highPri.start(); + + lowPri.join(); + highPri.join(); + + sub = sess.createDurableSubscriber(topic, "priority"); + for (int i = 0; i < MSG_NUM * 2; i++) { + Message msg = sub.receive(5000); + assertNotNull("Message " + i + " was null", msg); + assertEquals("Message " + i + " has wrong priority", i < MSG_NUM ? HIGH_PRI : LOW_PRI, msg.getJMSPriority()); + } + + // verify that same broker/store can deal with non priority dest also + topic = (ActiveMQTopic) sess.createTopic("HAS_NO_PRIORITY"); + sub = sess.createDurableSubscriber(topic, "no_priority"); + sub.close(); + + lowPri = new ProducerThread(topic, MSG_NUM, LOW_PRI); + highPri = new ProducerThread(topic, MSG_NUM, HIGH_PRI); + + lowPri.start(); + highPri.start(); + + lowPri.join(); + highPri.join(); + + sub = sess.createDurableSubscriber(topic, "no_priority"); + // verify we got them all + for (int i = 0; i < MSG_NUM * 2; i++) { + Message msg = sub.receive(5000); + assertNotNull("Message " + i + " was null", msg); + } + + } + + public void initCombosForTestDurableSubsReconnect() { + addCombinationValues("prefetchVal", new Object[]{new Integer(1000), new Integer(MSG_NUM / 2)}); + // REVISIT = is dispatchAsync = true a problem or is it just the test? + addCombinationValues("dispatchAsync", new Object[]{Boolean.FALSE}); + addCombinationValues("useCache", new Object[]{Boolean.TRUE, Boolean.FALSE}); + } + + public void testDurableSubsReconnect() throws Exception { + ActiveMQTopic topic = (ActiveMQTopic) sess.createTopic("TEST"); + final String subName = "priorityDisconnect"; + TopicSubscriber sub = sess.createDurableSubscriber(topic, subName); + sub.close(); + + ProducerThread lowPri = new ProducerThread(topic, MSG_NUM, LOW_PRI); + ProducerThread highPri = new ProducerThread(topic, MSG_NUM, HIGH_PRI); + + lowPri.start(); + highPri.start(); + + lowPri.join(); + highPri.join(); + + final int closeFrequency = MSG_NUM / 4; + sub = sess.createDurableSubscriber(topic, subName); + for (int i = 0; i < MSG_NUM * 2; i++) { + Message msg = sub.receive(15000); + LOG.debug("received i=" + i + ", " + (msg != null ? msg.getJMSMessageID() : null)); + assertNotNull("Message " + i + " was null", msg); + assertEquals("Message " + i + " has wrong priority", i < MSG_NUM ? HIGH_PRI : LOW_PRI, msg.getJMSPriority()); + if (i > 0 && i % closeFrequency == 0) { + LOG.info("Closing durable sub.. on: " + i); + sub.close(); + sub = sess.createDurableSubscriber(topic, subName); + } + } + } + + public void testHighPriorityDelivery() throws Exception { + + // get zero prefetch + ActiveMQPrefetchPolicy prefetch = new ActiveMQPrefetchPolicy(); + prefetch.setAll(0); + factory.setPrefetchPolicy(prefetch); + conn.close(); + conn = factory.createConnection(); + conn.setClientID("priority"); + conn.start(); + sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + + ActiveMQTopic topic = (ActiveMQTopic) sess.createTopic("TEST"); + final String subName = "priorityDisconnect"; + TopicSubscriber sub = sess.createDurableSubscriber(topic, subName); + sub.close(); + + final int numToProduce = 2000; + final int[] dups = new int[numToProduce * 2]; + ProducerThread producerThread = new ProducerThread(topic, numToProduce, LOW_PRI + 1); + producerThread.run(); + LOG.info("Low priority messages sent"); + + sub = sess.createDurableSubscriber(topic, subName); + final int batchSize = 250; + int lowLowCount = 0; + for (int i = 0; i < numToProduce; i++) { + Message msg = sub.receive(15000); + LOG.info("received i=" + i + ", " + (msg != null ? msg.getJMSMessageID() + ", priority:" + msg.getJMSPriority() : null)); + assertNotNull("Message " + i + " was null", msg); + assertEquals("Message " + i + " has wrong priority", LOW_PRI + 1, msg.getJMSPriority()); + assertTrue("not duplicate ", dups[i] == 0); + dups[i] = 1; + + if (i % batchSize == 0) { + producerThread.setMessagePriority(HIGH_PRI); + producerThread.setMessageCount(1); + producerThread.run(); + LOG.info("High priority message sent, should be able to receive immediately"); + + if (i % batchSize * 2 == 0) { + producerThread.setMessagePriority(HIGH_PRI - 1); + producerThread.setMessageCount(1); + producerThread.run(); + LOG.info("High -1 priority message sent, should be able to receive immediately"); } - }); - assertTrue(broker.getRegionBroker().getDestinationMap().get(topic).getMessageStore().isPrioritizedMessages()); - queueProducer.close(); - topicProducer.close(); - - } - - protected class ProducerThread extends Thread { - - int priority; - int messageCount; - ActiveMQDestination dest; - - public ProducerThread(ActiveMQDestination dest, int messageCount, int priority) { - this.messageCount = messageCount; - this.priority = priority; - this.dest = dest; - } - - @Override - public void run() { - try { - MessageProducer producer = sess.createProducer(dest); - producer.setPriority(priority); - producer.setDeliveryMode(deliveryMode); - for (int i = 0; i < messageCount; i++) { - producer.send(sess.createTextMessage("message priority: " + priority)); - } - } catch (Exception e) { - e.printStackTrace(); + if (i % batchSize * 4 == 0) { + producerThread.setMessagePriority(LOW_PRI); + producerThread.setMessageCount(1); + producerThread.run(); + lowLowCount++; + LOG.info("Low low priority message sent, should not be able to receive immediately"); } - } - public void setMessagePriority(int priority) { - this.priority = priority; - } - - public void setMessageCount(int messageCount) { - this.messageCount = messageCount; - } - - } - - public void initCombosForTestQueues() { - addCombinationValues("useCache", new Object[] {new Boolean(true), new Boolean(false)}); - addCombinationValues("deliveryMode", new Object[] {new Integer(DeliveryMode.NON_PERSISTENT), new Integer(DeliveryMode.PERSISTENT)}); - } - - public void testQueues() throws Exception { - ActiveMQQueue queue = (ActiveMQQueue)sess.createQueue("TEST"); - - ProducerThread lowPri = new ProducerThread(queue, MSG_NUM, LOW_PRI); - ProducerThread highPri = new ProducerThread(queue, MSG_NUM, HIGH_PRI); - - lowPri.start(); - highPri.start(); - - lowPri.join(); - highPri.join(); - - MessageConsumer queueConsumer = sess.createConsumer(queue); - for (int i = 0; i < MSG_NUM * 2; i++) { - Message msg = queueConsumer.receive(5000); - LOG.debug("received i=" + i + ", " + (msg!=null? msg.getJMSMessageID() : null)); - assertNotNull("Message " + i + " was null", msg); - assertEquals("Message " + i + " has wrong priority", i < MSG_NUM ? HIGH_PRI : LOW_PRI, msg.getJMSPriority()); - } - } - - protected Message createMessage(int priority) throws Exception { - final String text = "priority " + priority; - Message msg = sess.createTextMessage(text); - LOG.info("Sending " + text); - return msg; - } - - public void initCombosForTestDurableSubs() { - addCombinationValues("prefetchVal", new Object[] {new Integer(1000), new Integer(MSG_NUM/4)}); - } - - public void testDurableSubs() throws Exception { - ActiveMQTopic topic = (ActiveMQTopic)sess.createTopic("TEST"); - TopicSubscriber sub = sess.createDurableSubscriber(topic, "priority"); - sub.close(); - - ProducerThread lowPri = new ProducerThread(topic, MSG_NUM, LOW_PRI); - ProducerThread highPri = new ProducerThread(topic, MSG_NUM, HIGH_PRI); - - lowPri.start(); - highPri.start(); - - lowPri.join(); - highPri.join(); - - sub = sess.createDurableSubscriber(topic, "priority"); - for (int i = 0; i < MSG_NUM * 2; i++) { - Message msg = sub.receive(5000); - assertNotNull("Message " + i + " was null", msg); - assertEquals("Message " + i + " has wrong priority", i < MSG_NUM ? HIGH_PRI : LOW_PRI, msg.getJMSPriority()); - } - - - // verify that same broker/store can deal with non priority dest also - topic = (ActiveMQTopic)sess.createTopic("HAS_NO_PRIORITY"); - sub = sess.createDurableSubscriber(topic, "no_priority"); - sub.close(); - - lowPri = new ProducerThread(topic, MSG_NUM, LOW_PRI); - highPri = new ProducerThread(topic, MSG_NUM, HIGH_PRI); - - lowPri.start(); - highPri.start(); - - lowPri.join(); - highPri.join(); - - sub = sess.createDurableSubscriber(topic, "no_priority"); - // verify we got them all - for (int i = 0; i < MSG_NUM * 2; i++) { - Message msg = sub.receive(5000); - assertNotNull("Message " + i + " was null", msg); - } - - } - - public void initCombosForTestDurableSubsReconnect() { - addCombinationValues("prefetchVal", new Object[] {new Integer(1000), new Integer(MSG_NUM/2)}); - // REVISIT = is dispatchAsync = true a problem or is it just the test? - addCombinationValues("dispatchAsync", new Object[] {Boolean.FALSE}); - addCombinationValues("useCache", new Object[] {Boolean.TRUE, Boolean.FALSE}); - } - - public void testDurableSubsReconnect() throws Exception { - ActiveMQTopic topic = (ActiveMQTopic)sess.createTopic("TEST"); - final String subName = "priorityDisconnect"; - TopicSubscriber sub = sess.createDurableSubscriber(topic, subName); - sub.close(); - - ProducerThread lowPri = new ProducerThread(topic, MSG_NUM, LOW_PRI); - ProducerThread highPri = new ProducerThread(topic, MSG_NUM, HIGH_PRI); - - lowPri.start(); - highPri.start(); - - lowPri.join(); - highPri.join(); - - - final int closeFrequency = MSG_NUM/4; - sub = sess.createDurableSubscriber(topic, subName); - for (int i = 0; i < MSG_NUM * 2; i++) { - Message msg = sub.receive(15000); - LOG.debug("received i=" + i + ", " + (msg!=null? msg.getJMSMessageID() : null)); - assertNotNull("Message " + i + " was null", msg); - assertEquals("Message " + i + " has wrong priority", i < MSG_NUM ? HIGH_PRI : LOW_PRI, msg.getJMSPriority()); - if (i>0 && i%closeFrequency==0) { - LOG.info("Closing durable sub.. on: " + i); - sub.close(); - sub = sess.createDurableSubscriber(topic, subName); - } - } - } - - public void testHighPriorityDelivery() throws Exception { - - // get zero prefetch - ActiveMQPrefetchPolicy prefetch = new ActiveMQPrefetchPolicy(); - prefetch.setAll(0); - factory.setPrefetchPolicy(prefetch); - conn.close(); - conn = factory.createConnection(); - conn.setClientID("priority"); - conn.start(); - sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - - ActiveMQTopic topic = (ActiveMQTopic)sess.createTopic("TEST"); - final String subName = "priorityDisconnect"; - TopicSubscriber sub = sess.createDurableSubscriber(topic, subName); - sub.close(); - - final int numToProduce = 2000; - final int[] dups = new int[numToProduce*2]; - ProducerThread producerThread = new ProducerThread(topic, numToProduce, LOW_PRI+1); - producerThread.run(); - LOG.info("Low priority messages sent"); - - sub = sess.createDurableSubscriber(topic, subName); - final int batchSize = 250; - int lowLowCount = 0; - for (int i=0; i exceptions = new Vector(); - BrokerService brokerService; +public class StorePerDestinationTest { - protected BrokerService createBroker(PersistenceAdapter kaha) throws Exception { + static final Logger LOG = LoggerFactory.getLogger(StorePerDestinationTest.class); + final static int maxFileLength = 1024 * 100; + final static int numToSend = 5000; + final Vector exceptions = new Vector(); + BrokerService brokerService; - BrokerService broker = new BrokerService(); - broker.setUseJmx(false); - broker.setPersistenceAdapter(kaha); - return broker; - } + protected BrokerService createBroker(PersistenceAdapter kaha) throws Exception { - protected PersistenceAdapter createStore(boolean delete) throws IOException { - KahaDBPersistenceAdapter kaha = new KahaDBPersistenceAdapter(); - kaha.setJournalMaxFileLength(maxFileLength); - kaha.setCleanupInterval(5000); - if (delete) { - kaha.deleteAllMessages(); - } - return kaha; - } + BrokerService broker = new BrokerService(); + broker.setUseJmx(false); + broker.setPersistenceAdapter(kaha); + return broker; + } - @Before - public void prepareCleanBrokerWithMultiStore() throws Exception { - prepareBrokerWithMultiStore(true); - } + protected PersistenceAdapter createStore(boolean delete) throws IOException { + KahaDBPersistenceAdapter kaha = new KahaDBPersistenceAdapter(); + kaha.setJournalMaxFileLength(maxFileLength); + kaha.setCleanupInterval(5000); + if (delete) { + kaha.deleteAllMessages(); + } + return kaha; + } - public void prepareBrokerWithMultiStore(boolean deleteAllMessages) throws Exception { + @Before + public void prepareCleanBrokerWithMultiStore() throws Exception { + prepareBrokerWithMultiStore(true); + } - MultiKahaDBPersistenceAdapter multiKahaDBPersistenceAdapter = new MultiKahaDBPersistenceAdapter(); - if (deleteAllMessages) { - multiKahaDBPersistenceAdapter.deleteAllMessages(); - } - ArrayList adapters = new ArrayList(); + public void prepareBrokerWithMultiStore(boolean deleteAllMessages) throws Exception { - FilteredKahaDBPersistenceAdapter theRest = new FilteredKahaDBPersistenceAdapter(); - theRest.setPersistenceAdapter(createStore(deleteAllMessages)); - // default destination when not set is a match for all - adapters.add(theRest); + MultiKahaDBPersistenceAdapter multiKahaDBPersistenceAdapter = new MultiKahaDBPersistenceAdapter(); + if (deleteAllMessages) { + multiKahaDBPersistenceAdapter.deleteAllMessages(); + } + ArrayList adapters = new ArrayList(); - // separate store for FastQ - FilteredKahaDBPersistenceAdapter fastQStore = new FilteredKahaDBPersistenceAdapter(); - fastQStore.setPersistenceAdapter(createStore(deleteAllMessages)); - fastQStore.setDestination(new ActiveMQQueue("FastQ")); - adapters.add(fastQStore); + FilteredKahaDBPersistenceAdapter theRest = new FilteredKahaDBPersistenceAdapter(); + theRest.setPersistenceAdapter(createStore(deleteAllMessages)); + // default destination when not set is a match for all + adapters.add(theRest); - multiKahaDBPersistenceAdapter.setFilteredPersistenceAdapters(adapters); - brokerService = createBroker(multiKahaDBPersistenceAdapter); - } + // separate store for FastQ + FilteredKahaDBPersistenceAdapter fastQStore = new FilteredKahaDBPersistenceAdapter(); + fastQStore.setPersistenceAdapter(createStore(deleteAllMessages)); + fastQStore.setDestination(new ActiveMQQueue("FastQ")); + adapters.add(fastQStore); - @After - public void tearDown() throws Exception { - brokerService.stop(); - } + multiKahaDBPersistenceAdapter.setFilteredPersistenceAdapters(adapters); + brokerService = createBroker(multiKahaDBPersistenceAdapter); + } - @Test - public void testTransactedSendReceive() throws Exception { - brokerService.start(); - sendMessages(true, "SlowQ", 1, 0); - assertEquals("got one", 1, receiveMessages(true, "SlowQ", 1)); - } + @After + public void tearDown() throws Exception { + brokerService.stop(); + } - @Test - public void testTransactedSendReceiveAcrossStores() throws Exception { - brokerService.start(); - sendMessages(true, "SlowQ,FastQ", 1, 0); - assertEquals("got one", 2, receiveMessages(true, "SlowQ,FastQ", 2)); - } + @Test + public void testTransactedSendReceive() throws Exception { + brokerService.start(); + sendMessages(true, "SlowQ", 1, 0); + assertEquals("got one", 1, receiveMessages(true, "SlowQ", 1)); + } - @Test - public void testCommitRecovery() throws Exception { - doTestRecovery(true); - } + @Test + public void testTransactedSendReceiveAcrossStores() throws Exception { + brokerService.start(); + sendMessages(true, "SlowQ,FastQ", 1, 0); + assertEquals("got one", 2, receiveMessages(true, "SlowQ,FastQ", 2)); + } - @Test - public void testRollbackRecovery() throws Exception { - doTestRecovery(false); - } + @Test + public void testCommitRecovery() throws Exception { + doTestRecovery(true); + } - public void doTestRecovery(final boolean haveOutcome) throws Exception { - final MultiKahaDBPersistenceAdapter persistenceAdapter = - (MultiKahaDBPersistenceAdapter) brokerService.getPersistenceAdapter(); - MultiKahaDBTransactionStore transactionStore = - new MultiKahaDBTransactionStore(persistenceAdapter) { - @Override - public void persistOutcome(Tx tx, TransactionId txid) throws IOException { - if (haveOutcome) { - super.persistOutcome(tx, txid); - } - try { - // IOExceptions will stop the broker - persistenceAdapter.stop(); - } catch (Exception e) { - LOG.error("ex on stop ", e); - exceptions.add(e); - } - } - }; - persistenceAdapter.setTransactionStore(transactionStore); - brokerService.start(); + @Test + public void testRollbackRecovery() throws Exception { + doTestRecovery(false); + } - ExecutorService executorService = Executors.newCachedThreadPool(); - executorService.execute(new Runnable() { - @Override - public void run() { - try { - // commit will block - sendMessages(true, "SlowQ,FastQ", 1, 0); - } catch(Exception expected) { - LOG.info("expected", expected); - } + public void doTestRecovery(final boolean haveOutcome) throws Exception { + final MultiKahaDBPersistenceAdapter persistenceAdapter = (MultiKahaDBPersistenceAdapter) brokerService.getPersistenceAdapter(); + MultiKahaDBTransactionStore transactionStore = new MultiKahaDBTransactionStore(persistenceAdapter) { + @Override + public void persistOutcome(Tx tx, TransactionId txid) throws IOException { + if (haveOutcome) { + super.persistOutcome(tx, txid); } - }); - - brokerService.waitUntilStopped(); - // interrupt the send thread - executorService.shutdownNow(); - - // verify auto recovery - prepareBrokerWithMultiStore(false); - brokerService.start(); - - assertEquals("expect to get the recovered message", haveOutcome ? 2 : 0, receiveMessages(false, "SlowQ,FastQ", 2)); - assertEquals("all transactions are complete", 0, brokerService.getBroker().getPreparedTransactions(null).length); - } - - @Test - public void testDirectoryDefault() throws Exception { - MultiKahaDBPersistenceAdapter multiKahaDBPersistenceAdapter = new MultiKahaDBPersistenceAdapter(); - ArrayList adapters = new ArrayList(); - - FilteredKahaDBPersistenceAdapter otherFilteredKahaDBPersistenceAdapter = - new FilteredKahaDBPersistenceAdapter(); - PersistenceAdapter otherStore = createStore(false); - File someOtherDisk = new File("target" + File.separator + "someOtherDisk"); - otherStore.setDirectory(someOtherDisk); - otherFilteredKahaDBPersistenceAdapter.setPersistenceAdapter(otherStore); - otherFilteredKahaDBPersistenceAdapter.setDestination(new ActiveMQQueue("Other")); - adapters.add(otherFilteredKahaDBPersistenceAdapter); - - FilteredKahaDBPersistenceAdapter filteredKahaDBPersistenceAdapterDefault = - new FilteredKahaDBPersistenceAdapter(); - PersistenceAdapter storeDefault = createStore(false); - filteredKahaDBPersistenceAdapterDefault.setPersistenceAdapter(storeDefault); - adapters.add(filteredKahaDBPersistenceAdapterDefault); - - multiKahaDBPersistenceAdapter.setFilteredPersistenceAdapters(adapters); - - assertEquals(multiKahaDBPersistenceAdapter.getDirectory(), storeDefault.getDirectory().getParentFile()); - assertEquals(someOtherDisk, otherStore.getDirectory().getParentFile()); - } - - @Test - public void testSlowFastDestinationsStoreUsage() throws Exception { - brokerService.start(); - ExecutorService executorService = Executors.newCachedThreadPool(); - executorService.execute(new Runnable() { - @Override - public void run() { - try { - sendMessages(false, "SlowQ", 50, 500); - } catch (Exception e) { - exceptions.add(e); - } + try { + // IOExceptions will stop the broker + persistenceAdapter.stop(); } - }); - - executorService.execute(new Runnable() { - @Override - public void run() { - try { - sendMessages(false, "FastQ", numToSend, 0); - } catch (Exception e) { - exceptions.add(e); - } + catch (Exception e) { + LOG.error("ex on stop ", e); + exceptions.add(e); } - }); + } + }; + persistenceAdapter.setTransactionStore(transactionStore); + brokerService.start(); - executorService.execute(new Runnable() { - @Override - public void run() { - try { - assertEquals("Got all sent", numToSend, receiveMessages(false, "FastQ", numToSend)); - } catch (Exception e) { - exceptions.add(e); - } + ExecutorService executorService = Executors.newCachedThreadPool(); + executorService.execute(new Runnable() { + @Override + public void run() { + try { + // commit will block + sendMessages(true, "SlowQ,FastQ", 1, 0); } - }); - - executorService.shutdown(); - assertTrue("consumers executor finished on time", executorService.awaitTermination(5*60, TimeUnit.SECONDS)); - final SystemUsage usage = brokerService.getSystemUsage(); - assertTrue("Store is not hogged", Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - long storeUsage = usage.getStoreUsage().getUsage(); - LOG.info("Store Usage: " + storeUsage); - return storeUsage < 5 * maxFileLength; + catch (Exception expected) { + LOG.info("expected", expected); } - })); - assertTrue("no exceptions", exceptions.isEmpty()); - } + } + }); - private void sendMessages(boolean transacted, String destName, int count, long sleep) throws Exception { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = cf.createConnection(); - try { - Session session = transacted ? connection.createSession(true, Session.SESSION_TRANSACTED) : connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(new ActiveMQQueue(destName)); - for (int i = 0; i < count; i++) { - if (sleep > 0) { - TimeUnit.MILLISECONDS.sleep(sleep); - } - producer.send(session.createTextMessage(createContent(i))); - } - if (transacted) { - session.commit(); - } - } finally { - connection.close(); - } - } + brokerService.waitUntilStopped(); + // interrupt the send thread + executorService.shutdownNow(); - private int receiveMessages(boolean transacted, String destName, int max) throws JMSException { - int rc = 0; - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = cf.createConnection(); - try { - connection.start(); - Session session = transacted ? connection.createSession(true, Session.SESSION_TRANSACTED) : connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer messageConsumer = session.createConsumer(new ActiveMQQueue(destName)); - while (rc < max && messageConsumer.receive(4000) != null) { - rc++; + // verify auto recovery + prepareBrokerWithMultiStore(false); + brokerService.start(); - if (transacted && rc % 200 == 0) { - session.commit(); - } - } - if (transacted) { - session.commit(); - } - return rc; - } finally { - connection.close(); - } - } + assertEquals("expect to get the recovered message", haveOutcome ? 2 : 0, receiveMessages(false, "SlowQ,FastQ", 2)); + assertEquals("all transactions are complete", 0, brokerService.getBroker().getPreparedTransactions(null).length); + } - private String createContent(int i) { - StringBuilder sb = new StringBuilder(i + ":"); - while (sb.length() < 1024) { - sb.append("*"); - } - return sb.toString(); - } + @Test + public void testDirectoryDefault() throws Exception { + MultiKahaDBPersistenceAdapter multiKahaDBPersistenceAdapter = new MultiKahaDBPersistenceAdapter(); + ArrayList adapters = new ArrayList(); + + FilteredKahaDBPersistenceAdapter otherFilteredKahaDBPersistenceAdapter = new FilteredKahaDBPersistenceAdapter(); + PersistenceAdapter otherStore = createStore(false); + File someOtherDisk = new File("target" + File.separator + "someOtherDisk"); + otherStore.setDirectory(someOtherDisk); + otherFilteredKahaDBPersistenceAdapter.setPersistenceAdapter(otherStore); + otherFilteredKahaDBPersistenceAdapter.setDestination(new ActiveMQQueue("Other")); + adapters.add(otherFilteredKahaDBPersistenceAdapter); + + FilteredKahaDBPersistenceAdapter filteredKahaDBPersistenceAdapterDefault = new FilteredKahaDBPersistenceAdapter(); + PersistenceAdapter storeDefault = createStore(false); + filteredKahaDBPersistenceAdapterDefault.setPersistenceAdapter(storeDefault); + adapters.add(filteredKahaDBPersistenceAdapterDefault); + + multiKahaDBPersistenceAdapter.setFilteredPersistenceAdapters(adapters); + + assertEquals(multiKahaDBPersistenceAdapter.getDirectory(), storeDefault.getDirectory().getParentFile()); + assertEquals(someOtherDisk, otherStore.getDirectory().getParentFile()); + } + + @Test + public void testSlowFastDestinationsStoreUsage() throws Exception { + brokerService.start(); + ExecutorService executorService = Executors.newCachedThreadPool(); + executorService.execute(new Runnable() { + @Override + public void run() { + try { + sendMessages(false, "SlowQ", 50, 500); + } + catch (Exception e) { + exceptions.add(e); + } + } + }); + + executorService.execute(new Runnable() { + @Override + public void run() { + try { + sendMessages(false, "FastQ", numToSend, 0); + } + catch (Exception e) { + exceptions.add(e); + } + } + }); + + executorService.execute(new Runnable() { + @Override + public void run() { + try { + assertEquals("Got all sent", numToSend, receiveMessages(false, "FastQ", numToSend)); + } + catch (Exception e) { + exceptions.add(e); + } + } + }); + + executorService.shutdown(); + assertTrue("consumers executor finished on time", executorService.awaitTermination(5 * 60, TimeUnit.SECONDS)); + final SystemUsage usage = brokerService.getSystemUsage(); + assertTrue("Store is not hogged", Wait.waitFor(new Wait.Condition() { + + @Override + public boolean isSatisified() throws Exception { + long storeUsage = usage.getStoreUsage().getUsage(); + LOG.info("Store Usage: " + storeUsage); + return storeUsage < 5 * maxFileLength; + } + })); + assertTrue("no exceptions", exceptions.isEmpty()); + } + + private void sendMessages(boolean transacted, String destName, int count, long sleep) throws Exception { + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); + Connection connection = cf.createConnection(); + try { + Session session = transacted ? connection.createSession(true, Session.SESSION_TRANSACTED) : connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(new ActiveMQQueue(destName)); + for (int i = 0; i < count; i++) { + if (sleep > 0) { + TimeUnit.MILLISECONDS.sleep(sleep); + } + producer.send(session.createTextMessage(createContent(i))); + } + if (transacted) { + session.commit(); + } + } + finally { + connection.close(); + } + } + + private int receiveMessages(boolean transacted, String destName, int max) throws JMSException { + int rc = 0; + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); + Connection connection = cf.createConnection(); + try { + connection.start(); + Session session = transacted ? connection.createSession(true, Session.SESSION_TRANSACTED) : connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer messageConsumer = session.createConsumer(new ActiveMQQueue(destName)); + while (rc < max && messageConsumer.receive(4000) != null) { + rc++; + + if (transacted && rc % 200 == 0) { + session.commit(); + } + } + if (transacted) { + session.commit(); + } + return rc; + } + finally { + connection.close(); + } + } + + private String createContent(int i) { + StringBuilder sb = new StringBuilder(i + ":"); + while (sb.length() < 1024) { + sb.append("*"); + } + return sb.toString(); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/BrokenPersistenceAdapter.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/BrokenPersistenceAdapter.java index e275d75260..a484c642d4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/BrokenPersistenceAdapter.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/BrokenPersistenceAdapter.java @@ -26,22 +26,22 @@ import org.slf4j.LoggerFactory; class BrokenPersistenceAdapter extends JDBCPersistenceAdapter { - private final Logger LOG = LoggerFactory.getLogger(BrokenPersistenceAdapter.class); + private final Logger LOG = LoggerFactory.getLogger(BrokenPersistenceAdapter.class); - private boolean shouldBreak = false; + private boolean shouldBreak = false; - @Override - public void commitTransaction(ConnectionContext context) throws IOException { - if ( shouldBreak ) { - LOG.warn("Throwing exception on purpose"); - throw new IOException("Breaking on purpose"); - } - LOG.debug("in commitTransaction"); - super.commitTransaction(context); - } + @Override + public void commitTransaction(ConnectionContext context) throws IOException { + if (shouldBreak) { + LOG.warn("Throwing exception on purpose"); + throw new IOException("Breaking on purpose"); + } + LOG.debug("in commitTransaction"); + super.commitTransaction(context); + } - public void setShouldBreak(boolean shouldBreak) { - this.shouldBreak = shouldBreak; - } + public void setShouldBreak(boolean shouldBreak) { + this.shouldBreak = shouldBreak; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/DatabaseLockerConfigTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/DatabaseLockerConfigTest.java index a99649dbbc..5a4aae8570 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/DatabaseLockerConfigTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/DatabaseLockerConfigTest.java @@ -23,33 +23,33 @@ import org.junit.Test; public class DatabaseLockerConfigTest { - @Test - public void testSleepConfig() throws Exception { - LeaseDatabaseLocker underTest = new LeaseDatabaseLocker(); - underTest.setLockAcquireSleepInterval(50); - underTest.configure(null); - assertEquals("configured sleep value retained", 50, underTest.getLockAcquireSleepInterval()); - } + @Test + public void testSleepConfig() throws Exception { + LeaseDatabaseLocker underTest = new LeaseDatabaseLocker(); + underTest.setLockAcquireSleepInterval(50); + underTest.configure(null); + assertEquals("configured sleep value retained", 50, underTest.getLockAcquireSleepInterval()); + } - @Test - public void testDefaultSleepConfig() throws Exception { - LeaseDatabaseLocker underTest = new LeaseDatabaseLocker(); - underTest.configure(null); - assertEquals("configured sleep value retained", AbstractLocker.DEFAULT_LOCK_ACQUIRE_SLEEP_INTERVAL, underTest.getLockAcquireSleepInterval()); - } + @Test + public void testDefaultSleepConfig() throws Exception { + LeaseDatabaseLocker underTest = new LeaseDatabaseLocker(); + underTest.configure(null); + assertEquals("configured sleep value retained", AbstractLocker.DEFAULT_LOCK_ACQUIRE_SLEEP_INTERVAL, underTest.getLockAcquireSleepInterval()); + } - @Test - public void testSleepConfigOrig() throws Exception { - DefaultDatabaseLocker underTest = new DefaultDatabaseLocker(); - underTest.setLockAcquireSleepInterval(50); - underTest.configure(null); - assertEquals("configured sleep value retained", 50, underTest.getLockAcquireSleepInterval()); - } + @Test + public void testSleepConfigOrig() throws Exception { + DefaultDatabaseLocker underTest = new DefaultDatabaseLocker(); + underTest.setLockAcquireSleepInterval(50); + underTest.configure(null); + assertEquals("configured sleep value retained", 50, underTest.getLockAcquireSleepInterval()); + } - @Test - public void testDefaultSleepConfigOrig() throws Exception { - DefaultDatabaseLocker underTest = new DefaultDatabaseLocker(); - underTest.configure(null); - assertEquals("configured sleep value retained", AbstractLocker.DEFAULT_LOCK_ACQUIRE_SLEEP_INTERVAL, underTest.getLockAcquireSleepInterval()); - } + @Test + public void testDefaultSleepConfigOrig() throws Exception { + DefaultDatabaseLocker underTest = new DefaultDatabaseLocker(); + underTest.configure(null); + assertEquals("configured sleep value retained", AbstractLocker.DEFAULT_LOCK_ACQUIRE_SLEEP_INTERVAL, underTest.getLockAcquireSleepInterval()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCCommitExceptionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCCommitExceptionTest.java index e183553642..00c501f2c1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCCommitExceptionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCCommitExceptionTest.java @@ -41,134 +41,135 @@ import org.slf4j.LoggerFactory; // https://issues.apache.org/activemq/browse/AMQ-2880 public class JDBCCommitExceptionTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(JDBCCommitExceptionTest.class); + private static final Logger LOG = LoggerFactory.getLogger(JDBCCommitExceptionTest.class); - protected static final int messagesExpected = 10; - protected ActiveMQConnectionFactory factory; - protected BrokerService broker; - protected String connectionUri; - protected EmbeddedDataSource dataSource; - protected java.sql.Connection dbConnection; - protected BrokenPersistenceAdapter jdbc; + protected static final int messagesExpected = 10; + protected ActiveMQConnectionFactory factory; + protected BrokerService broker; + protected String connectionUri; + protected EmbeddedDataSource dataSource; + protected java.sql.Connection dbConnection; + protected BrokenPersistenceAdapter jdbc; - @Override - public void setUp() throws Exception { - broker = createBroker(); - broker.start(); + @Override + public void setUp() throws Exception { + broker = createBroker(); + broker.start(); - factory = new ActiveMQConnectionFactory( - connectionUri + "?jms.prefetchPolicy.all=0&jms.redeliveryPolicy.maximumRedeliveries="+messagesExpected); - } + factory = new ActiveMQConnectionFactory(connectionUri + "?jms.prefetchPolicy.all=0&jms.redeliveryPolicy.maximumRedeliveries=" + messagesExpected); + } - @Override - public void tearDown() throws Exception { - broker.stop(); - } + @Override + public void tearDown() throws Exception { + broker.stop(); + } - public void testSqlException() throws Exception { - doTestSqlException(); - } + public void testSqlException() throws Exception { + doTestSqlException(); + } - public void doTestSqlException() throws Exception { - sendMessages(messagesExpected); - int messagesReceived = receiveMessages(messagesExpected); + public void doTestSqlException() throws Exception { + sendMessages(messagesExpected); + int messagesReceived = receiveMessages(messagesExpected); - dumpMessages(); - assertEquals("Messages expected doesn't equal messages received", messagesExpected, messagesReceived); - broker.stop(); - } + dumpMessages(); + assertEquals("Messages expected doesn't equal messages received", messagesExpected, messagesReceived); + broker.stop(); + } - protected void dumpMessages() throws Exception { - WireFormat wireFormat = new OpenWireFormat(); - java.sql.Connection conn = ((JDBCPersistenceAdapter) broker.getPersistenceAdapter()).getDataSource().getConnection(); - PreparedStatement statement = conn.prepareStatement("SELECT ID, MSG FROM ACTIVEMQ_MSGS"); - ResultSet result = statement.executeQuery(); - LOG.info("Messages left in broker after test"); - while(result.next()) { - long id = result.getLong(1); - org.apache.activemq.command.Message message = (org.apache.activemq.command.Message)wireFormat.unmarshal(new ByteSequence(result.getBytes(2))); - LOG.info("id: " + id + ", message SeqId: " + message.getMessageId().getBrokerSequenceId() + ", MSG: " + message); - } - statement.close(); - conn.close(); - } + protected void dumpMessages() throws Exception { + WireFormat wireFormat = new OpenWireFormat(); + java.sql.Connection conn = ((JDBCPersistenceAdapter) broker.getPersistenceAdapter()).getDataSource().getConnection(); + PreparedStatement statement = conn.prepareStatement("SELECT ID, MSG FROM ACTIVEMQ_MSGS"); + ResultSet result = statement.executeQuery(); + LOG.info("Messages left in broker after test"); + while (result.next()) { + long id = result.getLong(1); + org.apache.activemq.command.Message message = (org.apache.activemq.command.Message) wireFormat.unmarshal(new ByteSequence(result.getBytes(2))); + LOG.info("id: " + id + ", message SeqId: " + message.getMessageId().getBrokerSequenceId() + ", MSG: " + message); + } + statement.close(); + conn.close(); + } - protected int receiveMessages(int messagesExpected) throws Exception { - javax.jms.Connection connection = factory.createConnection(); - connection.start(); - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + protected int receiveMessages(int messagesExpected) throws Exception { + javax.jms.Connection connection = factory.createConnection(); + connection.start(); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - jdbc.setShouldBreak(true); + jdbc.setShouldBreak(true); - // first try and receive these messages, they'll continually fail - receiveMessages(messagesExpected, session); + // first try and receive these messages, they'll continually fail + receiveMessages(messagesExpected, session); - jdbc.setShouldBreak(false); + jdbc.setShouldBreak(false); - // now that the store is sane, try and get all the messages sent - return receiveMessages(messagesExpected, session); - } + // now that the store is sane, try and get all the messages sent + return receiveMessages(messagesExpected, session); + } - protected int receiveMessages(int messagesExpected, Session session) throws Exception { - int messagesReceived = 0; + protected int receiveMessages(int messagesExpected, Session session) throws Exception { + int messagesReceived = 0; - for (int i=0; i exceptions = new HashMap(); + private static final Logger LOG = LoggerFactory.getLogger(JDBCIOExceptionHandlerMockeryTest.class); + private HashMap exceptions = new HashMap(); - @Test - public void testShutdownWithoutTransportRestart() throws Exception { + @Test + public void testShutdownWithoutTransportRestart() throws Exception { - Mockery context = new Mockery() {{ - setImposteriser(ClassImposteriser.INSTANCE); - }}; + Mockery context = new Mockery() {{ + setImposteriser(ClassImposteriser.INSTANCE); + }}; - Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { - @Override - public void uncaughtException(Thread t, Throwable e) { - LOG.error("unexpected exception {} on thread {}", e, t); - exceptions.put(t, e); - } - }); + Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { + @Override + public void uncaughtException(Thread t, Throwable e) { + LOG.error("unexpected exception {} on thread {}", e, t); + exceptions.put(t, e); + } + }); - final BrokerService brokerService = context.mock(BrokerService.class); - final JDBCPersistenceAdapter jdbcPersistenceAdapter = context.mock(JDBCPersistenceAdapter.class); - final Locker locker = context.mock(Locker.class); + final BrokerService brokerService = context.mock(BrokerService.class); + final JDBCPersistenceAdapter jdbcPersistenceAdapter = context.mock(JDBCPersistenceAdapter.class); + final Locker locker = context.mock(Locker.class); - final States jdbcConn = context.states("jdbc").startsAs("down"); - final States broker = context.states("broker").startsAs("started"); + final States jdbcConn = context.states("jdbc").startsAs("down"); + final States broker = context.states("broker").startsAs("started"); - // simulate jdbc up between hasLock and checkpoint, so hasLock fails to verify - context.checking(new Expectations() {{ - allowing(brokerService).isRestartAllowed(); - will(returnValue(false)); - allowing(brokerService).stopAllConnectors(with(any(ServiceStopper.class))); - allowing(brokerService).getPersistenceAdapter(); - will(returnValue(jdbcPersistenceAdapter)); - allowing(jdbcPersistenceAdapter).getLocker(); - will(returnValue(locker)); - allowing(locker).keepAlive(); - when(jdbcConn.is("down")); - will(returnValue(true)); - allowing(locker).keepAlive(); - when(jdbcConn.is("up")); - will(returnValue(false)); + // simulate jdbc up between hasLock and checkpoint, so hasLock fails to verify + context.checking(new Expectations() {{ + allowing(brokerService).isRestartAllowed(); + will(returnValue(false)); + allowing(brokerService).stopAllConnectors(with(any(ServiceStopper.class))); + allowing(brokerService).getPersistenceAdapter(); + will(returnValue(jdbcPersistenceAdapter)); + allowing(jdbcPersistenceAdapter).getLocker(); + will(returnValue(locker)); + allowing(locker).keepAlive(); + when(jdbcConn.is("down")); + will(returnValue(true)); + allowing(locker).keepAlive(); + when(jdbcConn.is("up")); + will(returnValue(false)); - allowing(jdbcPersistenceAdapter).checkpoint(with(true)); - then(jdbcConn.is("up")); - allowing(brokerService).stop(); - then(broker.is("stopped")); + allowing(jdbcPersistenceAdapter).checkpoint(with(true)); + then(jdbcConn.is("up")); + allowing(brokerService).stop(); + then(broker.is("stopped")); - }}); + }}); - LeaseLockerIOExceptionHandler underTest = new LeaseLockerIOExceptionHandler(); - underTest.setBrokerService(brokerService); + LeaseLockerIOExceptionHandler underTest = new LeaseLockerIOExceptionHandler(); + underTest.setBrokerService(brokerService); - try { - underTest.handle(new IOException()); - fail("except suppress reply ex"); - } catch (SuppressReplyException expected) { - } + try { + underTest.handle(new IOException()); + fail("except suppress reply ex"); + } + catch (SuppressReplyException expected) { + } - assertTrue("broker stopped state triggered", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("broker state {}", broker); - return broker.is("stopped").isActive(); - } - })); - context.assertIsSatisfied(); + assertTrue("broker stopped state triggered", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("broker state {}", broker); + return broker.is("stopped").isActive(); + } + })); + context.assertIsSatisfied(); - assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); - } + assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCIOExceptionHandlerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCIOExceptionHandlerTest.java index 2502110a6e..e21b54517a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCIOExceptionHandlerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCIOExceptionHandlerTest.java @@ -42,280 +42,287 @@ import org.slf4j.LoggerFactory; */ public class JDBCIOExceptionHandlerTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(JDBCIOExceptionHandlerTest.class); - private static final String TRANSPORT_URL = "tcp://0.0.0.0:0"; + private static final Logger LOG = LoggerFactory.getLogger(JDBCIOExceptionHandlerTest.class); + private static final String TRANSPORT_URL = "tcp://0.0.0.0:0"; - private static final String DATABASE_NAME = "DERBY_OVERRIDE"; - private ActiveMQConnectionFactory factory; - private ReconnectingEmbeddedDataSource dataSource; - private BrokerService broker; + private static final String DATABASE_NAME = "DERBY_OVERRIDE"; + private ActiveMQConnectionFactory factory; + private ReconnectingEmbeddedDataSource dataSource; + private BrokerService broker; - protected BrokerService createBroker(boolean withJMX) throws Exception { - return createBroker("localhost", withJMX, true, true); - } + protected BrokerService createBroker(boolean withJMX) throws Exception { + return createBroker("localhost", withJMX, true, true); + } - protected BrokerService createBroker(String name, boolean withJMX, boolean leaseLocker, boolean startStopConnectors) throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName(name); + protected BrokerService createBroker(String name, + boolean withJMX, + boolean leaseLocker, + boolean startStopConnectors) throws Exception { + BrokerService broker = new BrokerService(); + broker.setBrokerName(name); - broker.setUseJmx(withJMX); + broker.setUseJmx(withJMX); - EmbeddedDataSource embeddedDataSource = new EmbeddedDataSource(); - embeddedDataSource.setDatabaseName(DATABASE_NAME); - embeddedDataSource.setCreateDatabase("create"); + EmbeddedDataSource embeddedDataSource = new EmbeddedDataSource(); + embeddedDataSource.setDatabaseName(DATABASE_NAME); + embeddedDataSource.setCreateDatabase("create"); - // create a wrapper to EmbeddedDataSource to allow the connection be - // reestablished to derby db - dataSource = new ReconnectingEmbeddedDataSource(embeddedDataSource); + // create a wrapper to EmbeddedDataSource to allow the connection be + // reestablished to derby db + dataSource = new ReconnectingEmbeddedDataSource(embeddedDataSource); - JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); - jdbc.setDataSource(dataSource); + JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); + jdbc.setDataSource(dataSource); - jdbc.setLockKeepAlivePeriod(1000L); - if (leaseLocker) { - LeaseDatabaseLocker leaseDatabaseLocker = new LeaseDatabaseLocker(); - leaseDatabaseLocker.setHandleStartException(true); - leaseDatabaseLocker.setLockAcquireSleepInterval(2000L); - jdbc.setLocker(leaseDatabaseLocker); - } + jdbc.setLockKeepAlivePeriod(1000L); + if (leaseLocker) { + LeaseDatabaseLocker leaseDatabaseLocker = new LeaseDatabaseLocker(); + leaseDatabaseLocker.setHandleStartException(true); + leaseDatabaseLocker.setLockAcquireSleepInterval(2000L); + jdbc.setLocker(leaseDatabaseLocker); + } - broker.setPersistenceAdapter(jdbc); - LeaseLockerIOExceptionHandler ioExceptionHandler = new LeaseLockerIOExceptionHandler(); - ioExceptionHandler.setResumeCheckSleepPeriod(1000L); - ioExceptionHandler.setStopStartConnectors(startStopConnectors); - broker.setIoExceptionHandler(ioExceptionHandler); - String connectionUri = broker.addConnector(TRANSPORT_URL).getPublishableConnectString(); + broker.setPersistenceAdapter(jdbc); + LeaseLockerIOExceptionHandler ioExceptionHandler = new LeaseLockerIOExceptionHandler(); + ioExceptionHandler.setResumeCheckSleepPeriod(1000L); + ioExceptionHandler.setStopStartConnectors(startStopConnectors); + broker.setIoExceptionHandler(ioExceptionHandler); + String connectionUri = broker.addConnector(TRANSPORT_URL).getPublishableConnectString(); - factory = new ActiveMQConnectionFactory(connectionUri); + factory = new ActiveMQConnectionFactory(connectionUri); - return broker; - } + return broker; + } - /* - * run test without JMX enabled - */ - public void testRecoverWithOutJMX() throws Exception { - recoverFromDisconnectDB(false); - } + /* + * run test without JMX enabled + */ + public void testRecoverWithOutJMX() throws Exception { + recoverFromDisconnectDB(false); + } - /* - * run test with JMX enabled - */ - public void testRecoverWithJMX() throws Exception { - recoverFromDisconnectDB(true); - } + /* + * run test with JMX enabled + */ + public void testRecoverWithJMX() throws Exception { + recoverFromDisconnectDB(true); + } - public void testSlaveStoppedLease() throws Exception { - testSlaveStopped(true); - } + public void testSlaveStoppedLease() throws Exception { + testSlaveStopped(true); + } - public void testSlaveStoppedDefault() throws Exception { - testSlaveStopped(false); - } + public void testSlaveStoppedDefault() throws Exception { + testSlaveStopped(false); + } - public void testSlaveStopped(final boolean lease) throws Exception { - final BrokerService master = createBroker("master", true, lease, false); - master.start(); - master.waitUntilStarted(); + public void testSlaveStopped(final boolean lease) throws Exception { + final BrokerService master = createBroker("master", true, lease, false); + master.start(); + master.waitUntilStarted(); - final AtomicReference slave = new AtomicReference(); + final AtomicReference slave = new AtomicReference(); - Thread slaveThread = new Thread() { - public void run() { - try { - BrokerService broker = new BrokerService(); - broker.setBrokerName("slave"); - - JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); - jdbc.setDataSource(dataSource); - - jdbc.setLockKeepAlivePeriod(1000L); - - if (lease) { - LeaseDatabaseLocker leaseDatabaseLocker = new LeaseDatabaseLocker(); - leaseDatabaseLocker.setHandleStartException(true); - leaseDatabaseLocker.setLockAcquireSleepInterval(2000L); - jdbc.setLocker(leaseDatabaseLocker); - } - - broker.setPersistenceAdapter(jdbc); - LeaseLockerIOExceptionHandler ioExceptionHandler = new LeaseLockerIOExceptionHandler(); - ioExceptionHandler.setResumeCheckSleepPeriod(1000L); - ioExceptionHandler.setStopStartConnectors(false); - broker.setIoExceptionHandler(ioExceptionHandler); - slave.set(broker); - broker.start(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }; - - slaveThread.start(); - - Thread.sleep(5000); - - dataSource.stopDB(); - - assertTrue("Master hasn't been stopped", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return master.isStopped(); - } - })); - - assertTrue("Slave hasn't been stopped", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return slave.get().isStopped(); - } - })); - - } - - public void recoverFromDisconnectDB(boolean withJMX) throws Exception { - try { - broker = createBroker(withJMX); - broker.start(); - broker.waitUntilStarted(); - - // broker started - stop db underneath it - dataSource.stopDB(); - - // wait - allow the leaselocker to kick the JDBCIOExceptionHandler - TimeUnit.SECONDS.sleep(3); - - // check connector has shutdown - checkTransportConnectorStopped(); - - // restart db underneath - dataSource.restartDB(); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.debug("*** checking connector to start..."); - try { - checkTransportConnectorStarted(); - return true; - } catch (Throwable t) { - LOG.debug(t.toString()); - } - return false; - } - }); - - - } finally { - LOG.debug("*** broker is stopping..."); - broker.stop(); - } - } - - private void checkTransportConnectorStopped() { - // connection is expected to fail - try { - factory.createConnection(); - fail("Transport connector should be stopped"); - } catch (Exception ex) { - // expected an exception - LOG.debug(" checkTransportConnectorStopped() threw", ex); - } - } - - private void checkTransportConnectorStarted() { - // connection is expected to succeed - try { - Connection conn = factory.createConnection(); - conn.close(); - } catch (Exception ex) { - LOG.debug("checkTransportConnectorStarted() threw", ex); - fail("Transport connector should have been started"); - } - } - - /* - * Wrapped the derby datasource object to get DB reconnect functionality as I not - * manage to get that working directly on the EmbeddedDataSource - * - * NOTE: Not a thread Safe but for this unit test it should be fine - */ - public class ReconnectingEmbeddedDataSource implements javax.sql.DataSource { - - private EmbeddedDataSource realDatasource; - - public ReconnectingEmbeddedDataSource(EmbeddedDataSource datasource) { - this.realDatasource = datasource; - } - - @Override - public PrintWriter getLogWriter() throws SQLException { - return this.realDatasource.getLogWriter(); - } - - @Override - public void setLogWriter(PrintWriter out) throws SQLException { - this.realDatasource.setLogWriter(out); - - } - - @Override - public void setLoginTimeout(int seconds) throws SQLException { - this.realDatasource.setLoginTimeout(seconds); - } - - @Override - public int getLoginTimeout() throws SQLException { - return this.realDatasource.getLoginTimeout(); - } - - @Override - public T unwrap(Class iface) throws SQLException { - return this.unwrap(iface); - } - - @Override - public boolean isWrapperFor(Class iface) throws SQLException { - return this.isWrapperFor(iface); - } - - @Override - public java.sql.Connection getConnection() throws SQLException { - return this.realDatasource.getConnection(); - } - - @Override - public java.sql.Connection getConnection(String username, String password) throws SQLException { - return this.getConnection(username, password); - } - - /** - * - * To simulate a db reconnect I just create a new EmbeddedDataSource . - * - * @throws SQLException - */ - public void restartDB() throws SQLException { - EmbeddedDataSource newDatasource = new EmbeddedDataSource(); - newDatasource.setDatabaseName(DATABASE_NAME); - newDatasource.getConnection(); - LOG.info("*** DB restarted now..."); - this.realDatasource = newDatasource; - } - - public void stopDB() { + Thread slaveThread = new Thread() { + public void run() { try { - realDatasource.setShutdownDatabase("shutdown"); - LOG.info("***DB is being shutdown..."); - dataSource.getConnection(); - fail("should have thrown a db closed exception"); - } catch (Exception ex) { - ex.printStackTrace(System.out); - } - } + BrokerService broker = new BrokerService(); + broker.setBrokerName("slave"); - public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException { - return null; - } - } + JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); + jdbc.setDataSource(dataSource); + + jdbc.setLockKeepAlivePeriod(1000L); + + if (lease) { + LeaseDatabaseLocker leaseDatabaseLocker = new LeaseDatabaseLocker(); + leaseDatabaseLocker.setHandleStartException(true); + leaseDatabaseLocker.setLockAcquireSleepInterval(2000L); + jdbc.setLocker(leaseDatabaseLocker); + } + + broker.setPersistenceAdapter(jdbc); + LeaseLockerIOExceptionHandler ioExceptionHandler = new LeaseLockerIOExceptionHandler(); + ioExceptionHandler.setResumeCheckSleepPeriod(1000L); + ioExceptionHandler.setStopStartConnectors(false); + broker.setIoExceptionHandler(ioExceptionHandler); + slave.set(broker); + broker.start(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + }; + + slaveThread.start(); + + Thread.sleep(5000); + + dataSource.stopDB(); + + assertTrue("Master hasn't been stopped", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return master.isStopped(); + } + })); + + assertTrue("Slave hasn't been stopped", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return slave.get().isStopped(); + } + })); + + } + + public void recoverFromDisconnectDB(boolean withJMX) throws Exception { + try { + broker = createBroker(withJMX); + broker.start(); + broker.waitUntilStarted(); + + // broker started - stop db underneath it + dataSource.stopDB(); + + // wait - allow the leaselocker to kick the JDBCIOExceptionHandler + TimeUnit.SECONDS.sleep(3); + + // check connector has shutdown + checkTransportConnectorStopped(); + + // restart db underneath + dataSource.restartDB(); + + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.debug("*** checking connector to start..."); + try { + checkTransportConnectorStarted(); + return true; + } + catch (Throwable t) { + LOG.debug(t.toString()); + } + return false; + } + }); + + } + finally { + LOG.debug("*** broker is stopping..."); + broker.stop(); + } + } + + private void checkTransportConnectorStopped() { + // connection is expected to fail + try { + factory.createConnection(); + fail("Transport connector should be stopped"); + } + catch (Exception ex) { + // expected an exception + LOG.debug(" checkTransportConnectorStopped() threw", ex); + } + } + + private void checkTransportConnectorStarted() { + // connection is expected to succeed + try { + Connection conn = factory.createConnection(); + conn.close(); + } + catch (Exception ex) { + LOG.debug("checkTransportConnectorStarted() threw", ex); + fail("Transport connector should have been started"); + } + } + + /* + * Wrapped the derby datasource object to get DB reconnect functionality as I not + * manage to get that working directly on the EmbeddedDataSource + * + * NOTE: Not a thread Safe but for this unit test it should be fine + */ + public class ReconnectingEmbeddedDataSource implements javax.sql.DataSource { + + private EmbeddedDataSource realDatasource; + + public ReconnectingEmbeddedDataSource(EmbeddedDataSource datasource) { + this.realDatasource = datasource; + } + + @Override + public PrintWriter getLogWriter() throws SQLException { + return this.realDatasource.getLogWriter(); + } + + @Override + public void setLogWriter(PrintWriter out) throws SQLException { + this.realDatasource.setLogWriter(out); + + } + + @Override + public void setLoginTimeout(int seconds) throws SQLException { + this.realDatasource.setLoginTimeout(seconds); + } + + @Override + public int getLoginTimeout() throws SQLException { + return this.realDatasource.getLoginTimeout(); + } + + @Override + public T unwrap(Class iface) throws SQLException { + return this.unwrap(iface); + } + + @Override + public boolean isWrapperFor(Class iface) throws SQLException { + return this.isWrapperFor(iface); + } + + @Override + public java.sql.Connection getConnection() throws SQLException { + return this.realDatasource.getConnection(); + } + + @Override + public java.sql.Connection getConnection(String username, String password) throws SQLException { + return this.getConnection(username, password); + } + + /** + * To simulate a db reconnect I just create a new EmbeddedDataSource . + * + * @throws SQLException + */ + public void restartDB() throws SQLException { + EmbeddedDataSource newDatasource = new EmbeddedDataSource(); + newDatasource.setDatabaseName(DATABASE_NAME); + newDatasource.getConnection(); + LOG.info("*** DB restarted now..."); + this.realDatasource = newDatasource; + } + + public void stopDB() { + try { + realDatasource.setShutdownDatabase("shutdown"); + LOG.info("***DB is being shutdown..."); + dataSource.getConnection(); + fail("should have thrown a db closed exception"); + } + catch (Exception ex) { + ex.printStackTrace(System.out); + } + } + + public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException { + return null; + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCLockTablePrefixTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCLockTablePrefixTest.java index e5b47ba015..854dd7a2e1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCLockTablePrefixTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCLockTablePrefixTest.java @@ -17,26 +17,27 @@ package org.apache.activemq.store.jdbc; import junit.framework.TestCase; + import org.apache.activemq.broker.BrokerFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.store.PersistenceAdapter; public class JDBCLockTablePrefixTest extends TestCase { - public void testLockTable() throws Exception { - BrokerService broker = BrokerFactory.createBroker("xbean:org/apache/activemq/store/jdbc/JDBCLockTablePrefix.xml"); - broker.waitUntilStarted(); + public void testLockTable() throws Exception { + BrokerService broker = BrokerFactory.createBroker("xbean:org/apache/activemq/store/jdbc/JDBCLockTablePrefix.xml"); + broker.waitUntilStarted(); - PersistenceAdapter pa = broker.getPersistenceAdapter(); - assertNotNull(pa); + PersistenceAdapter pa = broker.getPersistenceAdapter(); + assertNotNull(pa); - JDBCPersistenceAdapter jpa = (JDBCPersistenceAdapter) pa; - assertEquals("TTT_", jpa.getStatements().getTablePrefix()); - assertEquals("AMQ_MSGS2", jpa.getStatements().getMessageTableName()); - assertEquals("AMQ_LOCK2", jpa.getStatements().getLockTableName()); + JDBCPersistenceAdapter jpa = (JDBCPersistenceAdapter) pa; + assertEquals("TTT_", jpa.getStatements().getTablePrefix()); + assertEquals("AMQ_MSGS2", jpa.getStatements().getMessageTableName()); + assertEquals("AMQ_LOCK2", jpa.getStatements().getLockTableName()); - broker.stop(); - broker.waitUntilStopped(); - } + broker.stop(); + broker.waitUntilStopped(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCMessagePriorityTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCMessagePriorityTest.java index 2399738ea9..4637778147 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCMessagePriorityTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCMessagePriorityTest.java @@ -47,407 +47,405 @@ import org.slf4j.LoggerFactory; public class JDBCMessagePriorityTest extends MessagePriorityTest { - private static final Logger LOG = LoggerFactory.getLogger(JDBCMessagePriorityTest.class); - EmbeddedDataSource dataSource; - JDBCPersistenceAdapter jdbc; + private static final Logger LOG = LoggerFactory.getLogger(JDBCMessagePriorityTest.class); + EmbeddedDataSource dataSource; + JDBCPersistenceAdapter jdbc; - @Override - protected PersistenceAdapter createPersistenceAdapter(boolean delete) throws Exception { - jdbc = new JDBCPersistenceAdapter(); - dataSource = new EmbeddedDataSource(); - dataSource.setDatabaseName("derbyDb"); - dataSource.setCreateDatabase("create"); - dataSource.setShutdownDatabase(null); - jdbc.setDataSource(dataSource); - jdbc.deleteAllMessages(); - jdbc.setCleanupPeriod(2000); - return jdbc; - } + @Override + protected PersistenceAdapter createPersistenceAdapter(boolean delete) throws Exception { + jdbc = new JDBCPersistenceAdapter(); + dataSource = new EmbeddedDataSource(); + dataSource.setDatabaseName("derbyDb"); + dataSource.setCreateDatabase("create"); + dataSource.setShutdownDatabase(null); + jdbc.setDataSource(dataSource); + jdbc.deleteAllMessages(); + jdbc.setCleanupPeriod(2000); + return jdbc; + } + @Override + protected void tearDown() throws Exception { + super.tearDown(); + try { + if (dataSource != null) { + // ref http://svn.apache.org/viewvc/db/derby/code/trunk/java/testing/org/apache/derbyTesting/junit/JDBCDataSource.java?view=markup + dataSource.setShutdownDatabase("shutdown"); + dataSource.getConnection(); + } + } + catch (Exception ignored) { + } + finally { + dataSource.setShutdownDatabase(null); + } - @Override - protected void tearDown() throws Exception { - super.tearDown(); - try { - if (dataSource != null) { - // ref http://svn.apache.org/viewvc/db/derby/code/trunk/java/testing/org/apache/derbyTesting/junit/JDBCDataSource.java?view=markup - dataSource.setShutdownDatabase("shutdown"); - dataSource.getConnection(); - } - } catch (Exception ignored) { - } finally { - dataSource.setShutdownDatabase(null); - } + } - } + // this cannot be a general test as kahaDB just has support for 3 priority levels + public void testDurableSubsReconnectWithFourLevels() throws Exception { + ActiveMQTopic topic = (ActiveMQTopic) sess.createTopic("TEST"); + final String subName = "priorityDisconnect"; + TopicSubscriber sub = sess.createDurableSubscriber(topic, subName); + sub.close(); - // this cannot be a general test as kahaDB just has support for 3 priority levels - public void testDurableSubsReconnectWithFourLevels() throws Exception { - ActiveMQTopic topic = (ActiveMQTopic) sess.createTopic("TEST"); - final String subName = "priorityDisconnect"; - TopicSubscriber sub = sess.createDurableSubscriber(topic, subName); - sub.close(); + final int MED_PRI = LOW_PRI + 1; + final int MED_HIGH_PRI = HIGH_PRI - 1; - final int MED_PRI = LOW_PRI + 1; - final int MED_HIGH_PRI = HIGH_PRI - 1; + ProducerThread lowPri = new ProducerThread(topic, MSG_NUM, LOW_PRI); + ProducerThread medPri = new ProducerThread(topic, MSG_NUM, MED_PRI); + ProducerThread medHighPri = new ProducerThread(topic, MSG_NUM, MED_HIGH_PRI); + ProducerThread highPri = new ProducerThread(topic, MSG_NUM, HIGH_PRI); - ProducerThread lowPri = new ProducerThread(topic, MSG_NUM, LOW_PRI); - ProducerThread medPri = new ProducerThread(topic, MSG_NUM, MED_PRI); - ProducerThread medHighPri = new ProducerThread(topic, MSG_NUM, MED_HIGH_PRI); - ProducerThread highPri = new ProducerThread(topic, MSG_NUM, HIGH_PRI); + lowPri.start(); + highPri.start(); + medPri.start(); + medHighPri.start(); - lowPri.start(); - highPri.start(); - medPri.start(); - medHighPri.start(); + lowPri.join(); + highPri.join(); + medPri.join(); + medHighPri.join(); - lowPri.join(); - highPri.join(); - medPri.join(); - medHighPri.join(); + final int closeFrequency = MSG_NUM; + final int[] priorities = new int[]{HIGH_PRI, MED_HIGH_PRI, MED_PRI, LOW_PRI}; + sub = sess.createDurableSubscriber(topic, subName); + for (int i = 0; i < MSG_NUM * 4; i++) { + Message msg = sub.receive(10000); + LOG.debug("received i=" + i + ", m=" + (msg != null ? msg.getJMSMessageID() + ", priority: " + msg.getJMSPriority() : null)); + assertNotNull("Message " + i + " was null", msg); + assertEquals("Message " + i + " has wrong priority", priorities[i / MSG_NUM], msg.getJMSPriority()); + if (i > 0 && i % closeFrequency == 0) { + LOG.info("Closing durable sub.. on: " + i); + sub.close(); + sub = sess.createDurableSubscriber(topic, subName); + } + } + LOG.info("closing on done!"); + sub.close(); + } + public void initCombosForTestConcurrentDurableSubsReconnectWithXLevels() { + addCombinationValues("prioritizeMessages", new Object[]{Boolean.TRUE, Boolean.FALSE}); + } - final int closeFrequency = MSG_NUM; - final int[] priorities = new int[]{HIGH_PRI, MED_HIGH_PRI, MED_PRI, LOW_PRI}; - sub = sess.createDurableSubscriber(topic, subName); - for (int i = 0; i < MSG_NUM * 4; i++) { - Message msg = sub.receive(10000); - LOG.debug("received i=" + i + ", m=" + (msg != null ? - msg.getJMSMessageID() + ", priority: " + msg.getJMSPriority() - : null)); - assertNotNull("Message " + i + " was null", msg); - assertEquals("Message " + i + " has wrong priority", priorities[i / MSG_NUM], msg.getJMSPriority()); - if (i > 0 && i % closeFrequency == 0) { - LOG.info("Closing durable sub.. on: " + i); - sub.close(); - sub = sess.createDurableSubscriber(topic, subName); + public void testConcurrentDurableSubsReconnectWithXLevels() throws Exception { + ActiveMQTopic topic = (ActiveMQTopic) sess.createTopic("TEST"); + final String subName = "priorityDisconnect"; + Connection consumerConn = factory.createConnection(); + consumerConn.setClientID("priorityDisconnect"); + consumerConn.start(); + Session consumerSession = consumerConn.createSession(false, Session.AUTO_ACKNOWLEDGE); + + TopicSubscriber sub = consumerSession.createDurableSubscriber(topic, subName); + sub.close(); + + final int maxPriority = 5; + + final AtomicInteger[] messageCounts = new AtomicInteger[maxPriority]; + final long[] messageIds = new long[maxPriority]; + Vector producers = new Vector(); + for (int priority = 0; priority < maxPriority; priority++) { + producers.add(new ProducerThread(topic, MSG_NUM, priority)); + messageCounts[priority] = new AtomicInteger(0); + messageIds[priority] = 1L; + } + + for (ProducerThread producer : producers) { + producer.start(); + } + + final int closeFrequency = MSG_NUM / 2; + HashMap dups = new HashMap(); + sub = consumerSession.createDurableSubscriber(topic, subName); + for (int i = 0; i < MSG_NUM * maxPriority; i++) { + Message msg = sub.receive(10000); + LOG.debug("received i=" + i + ", m=" + (msg != null ? msg.getJMSMessageID() + ", priority: " + msg.getJMSPriority() : null)); + assertNotNull("Message " + i + " was null, counts: " + Arrays.toString(messageCounts), msg); + assertNull("no duplicate message failed on : " + msg.getJMSMessageID(), dups.put(msg.getJMSMessageID(), subName)); + messageCounts[msg.getJMSPriority()].incrementAndGet(); + assertEquals("message is in order : " + msg, messageIds[msg.getJMSPriority()], ((ActiveMQMessage) msg).getMessageId().getProducerSequenceId()); + messageIds[msg.getJMSPriority()]++; + if (i > 0 && i % closeFrequency == 0) { + LOG.info("Closing durable sub.. on: " + i + ", counts: " + Arrays.toString(messageCounts)); + sub.close(); + sub = consumerSession.createDurableSubscriber(topic, subName); + } + } + LOG.info("closing on done!"); + sub.close(); + consumerSession.close(); + consumerConn.close(); + + for (ProducerThread producer : producers) { + producer.join(); + } + } + + public void initCombosForTestConcurrentRate() { + addCombinationValues("prefetchVal", new Object[]{new Integer(1), new Integer(500)}); + } + + public void testConcurrentRate() throws Exception { + ActiveMQTopic topic = (ActiveMQTopic) sess.createTopic("TEST"); + final String subName = "priorityConcurrent"; + Connection consumerConn = factory.createConnection(); + consumerConn.setClientID("subName"); + consumerConn.start(); + Session consumerSession = consumerConn.createSession(false, Session.AUTO_ACKNOWLEDGE); + TopicSubscriber sub = consumerSession.createDurableSubscriber(topic, subName); + sub.close(); + + final int TO_SEND = 2000; + final Vector duplicates = new Vector(); + final int[] dups = new int[TO_SEND * 4]; + long start; + double max = 0, sum = 0; + MessageProducer messageProducer = sess.createProducer(topic); + TextMessage message = sess.createTextMessage(); + for (int i = 0; i < TO_SEND; i++) { + int priority = i % 10; + message.setText(i + "-" + priority); + message.setIntProperty("seq", i); + message.setJMSPriority(priority); + if (i > 0 && i % 1000 == 0) { + LOG.info("Max send time: " + max + ". Sending message: " + message.getText()); + } + start = System.currentTimeMillis(); + messageProducer.send(message, DeliveryMode.PERSISTENT, message.getJMSPriority(), 0); + long duration = System.currentTimeMillis() - start; + max = Math.max(max, duration); + if (duration == max) { + LOG.info("new max: " + max + " on i=" + i + ", " + message.getText()); + } + sum += duration; + } + + LOG.info("Sent: " + TO_SEND + ", max send time: " + max); + + double noConsumerAve = (sum * 100 / TO_SEND); + sub = consumerSession.createDurableSubscriber(topic, subName); + final AtomicInteger count = new AtomicInteger(); + sub.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + try { + count.incrementAndGet(); + if (count.get() % 100 == 0) { + LOG.info("onMessage: count: " + count.get() + ", " + ((TextMessage) message).getText() + ", seqNo " + message.getIntProperty("seq") + ", " + message.getJMSMessageID()); + } + int seqNo = message.getIntProperty("seq"); + if (dups[seqNo] == 0) { + dups[seqNo] = 1; + } + else { + LOG.error("Duplicate: " + ((TextMessage) message).getText() + ", " + message.getJMSMessageID()); + duplicates.add(message); + } } - } - LOG.info("closing on done!"); - sub.close(); - } - - public void initCombosForTestConcurrentDurableSubsReconnectWithXLevels() { - addCombinationValues("prioritizeMessages", new Object[]{Boolean.TRUE, Boolean.FALSE}); - } - - public void testConcurrentDurableSubsReconnectWithXLevels() throws Exception { - ActiveMQTopic topic = (ActiveMQTopic) sess.createTopic("TEST"); - final String subName = "priorityDisconnect"; - Connection consumerConn = factory.createConnection(); - consumerConn.setClientID("priorityDisconnect"); - consumerConn.start(); - Session consumerSession = consumerConn.createSession(false, Session.AUTO_ACKNOWLEDGE); - - TopicSubscriber sub = consumerSession.createDurableSubscriber(topic, subName); - sub.close(); - - final int maxPriority = 5; - - final AtomicInteger[] messageCounts = new AtomicInteger[maxPriority]; - final long[] messageIds = new long[maxPriority]; - Vector producers = new Vector(); - for (int priority = 0; priority < maxPriority; priority++) { - producers.add(new ProducerThread(topic, MSG_NUM, priority)); - messageCounts[priority] = new AtomicInteger(0); - messageIds[priority] = 1L; - } - - for (ProducerThread producer : producers) { - producer.start(); - } - - final int closeFrequency = MSG_NUM / 2; - HashMap dups = new HashMap(); - sub = consumerSession.createDurableSubscriber(topic, subName); - for (int i = 0; i < MSG_NUM * maxPriority; i++) { - Message msg = sub.receive(10000); - LOG.debug("received i=" + i + ", m=" + (msg != null ? - msg.getJMSMessageID() + ", priority: " + msg.getJMSPriority() - : null)); - assertNotNull("Message " + i + " was null, counts: " + Arrays.toString(messageCounts), msg); - assertNull("no duplicate message failed on : " + msg.getJMSMessageID(), dups.put(msg.getJMSMessageID(), subName)); - messageCounts[msg.getJMSPriority()].incrementAndGet(); - assertEquals("message is in order : " + msg, - messageIds[msg.getJMSPriority()],((ActiveMQMessage)msg).getMessageId().getProducerSequenceId()); - messageIds[msg.getJMSPriority()]++; - if (i > 0 && i % closeFrequency == 0) { - LOG.info("Closing durable sub.. on: " + i + ", counts: " + Arrays.toString(messageCounts)); - sub.close(); - sub = consumerSession.createDurableSubscriber(topic, subName); + catch (Exception e) { + e.printStackTrace(); } - } - LOG.info("closing on done!"); - sub.close(); - consumerSession.close(); - consumerConn.close(); + } + }); - for (ProducerThread producer : producers) { - producer.join(); - } - } + LOG.info("Activated consumer"); + sum = max = 0; + for (int i = TO_SEND; i < (TO_SEND * 2); i++) { + int priority = i % 10; + message.setText(i + "-" + priority); + message.setIntProperty("seq", i); + message.setJMSPriority(priority); + if (i > 0 && i % 1000 == 0) { + LOG.info("Max send time: " + max + ". Sending message: " + message.getText()); + } + start = System.currentTimeMillis(); + messageProducer.send(message, DeliveryMode.PERSISTENT, message.getJMSPriority(), 0); + long duration = System.currentTimeMillis() - start; + max = Math.max(max, duration); + if (duration == max) { + LOG.info("new max: " + max + " on i=" + i + ", " + message.getText()); + } + sum += duration; + } + LOG.info("Sent another: " + TO_SEND + ", max send time: " + max); - public void initCombosForTestConcurrentRate() { - addCombinationValues("prefetchVal", new Object[]{new Integer(1), new Integer(500)}); - } + double withConsumerAve = (sum * 100 / TO_SEND); + final int reasonableMultiplier = 4; // not so reasonable, but on slow disks it can be + assertTrue("max X times as slow with consumer:" + withConsumerAve + " , noConsumerMax:" + noConsumerAve, withConsumerAve < noConsumerAve * reasonableMultiplier); + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("count: " + count.get()); + return TO_SEND * 2 == count.get(); + } + }, 60 * 1000); - public void testConcurrentRate() throws Exception { - ActiveMQTopic topic = (ActiveMQTopic) sess.createTopic("TEST"); - final String subName = "priorityConcurrent"; - Connection consumerConn = factory.createConnection(); - consumerConn.setClientID("subName"); - consumerConn.start(); - Session consumerSession = consumerConn.createSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber sub = consumerSession.createDurableSubscriber(topic, subName); - sub.close(); + assertTrue("No duplicates : " + duplicates, duplicates.isEmpty()); + assertEquals("got all messages", TO_SEND * 2, count.get()); + } - final int TO_SEND = 2000; - final Vector duplicates = new Vector(); - final int[] dups = new int[TO_SEND * 4]; - long start; - double max = 0, sum = 0; - MessageProducer messageProducer = sess.createProducer(topic); - TextMessage message = sess.createTextMessage(); - for (int i = 0; i < TO_SEND; i++) { - int priority = i % 10; - message.setText(i + "-" + priority); - message.setIntProperty("seq", i); - message.setJMSPriority(priority); - if (i > 0 && i % 1000 == 0) { - LOG.info("Max send time: " + max + ". Sending message: " + message.getText()); + public void testCleanupPriorityDestination() throws Exception { + assertEquals("no messages pending", 0, messageTableCount()); + + ActiveMQTopic topic = (ActiveMQTopic) sess.createTopic("TEST"); + final String subName = "priorityConcurrent"; + Connection consumerConn = factory.createConnection(); + consumerConn.setClientID("subName"); + consumerConn.start(); + Session consumerSession = consumerConn.createSession(false, Session.AUTO_ACKNOWLEDGE); + TopicSubscriber sub = consumerSession.createDurableSubscriber(topic, subName); + sub.close(); + + MessageProducer messageProducer = sess.createProducer(topic); + Message message = sess.createTextMessage(); + message.setJMSPriority(2); + messageProducer.send(message, DeliveryMode.PERSISTENT, message.getJMSPriority(), 0); + message.setJMSPriority(5); + messageProducer.send(message, DeliveryMode.PERSISTENT, message.getJMSPriority(), 0); + + assertEquals("two messages pending", 2, messageTableCount()); + + sub = consumerSession.createDurableSubscriber(topic, subName); + + message = sub.receive(5000); + assertEquals("got high priority", 5, message.getJMSPriority()); + + waitForAck(5); + + for (int i = 0; i < 10; i++) { + jdbc.cleanup(); + } + assertEquals("one messages pending", 1, messageTableCount()); + + message = sub.receive(5000); + assertEquals("got high priority", 2, message.getJMSPriority()); + + waitForAck(2); + + for (int i = 0; i < 10; i++) { + jdbc.cleanup(); + } + assertEquals("no messages pending", 0, messageTableCount()); + } + + public void testCleanupNonPriorityDestination() throws Exception { + assertEquals("no messages pending", 0, messageTableCount()); + + ActiveMQTopic topic = (ActiveMQTopic) sess.createTopic("TEST_CLEANUP_NO_PRIORITY"); + final String subName = "subName"; + Connection consumerConn = factory.createConnection(); + consumerConn.setClientID("subName"); + consumerConn.start(); + Session consumerSession = consumerConn.createSession(false, Session.AUTO_ACKNOWLEDGE); + TopicSubscriber sub = consumerSession.createDurableSubscriber(topic, subName); + sub.close(); + + MessageProducer messageProducer = sess.createProducer(topic); + Message message = sess.createTextMessage("ToExpire"); + messageProducer.send(message, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, 4000); + + message = sess.createTextMessage("A"); + messageProducer.send(message); + message = sess.createTextMessage("B"); + messageProducer.send(message); + message = null; + + assertEquals("three messages pending", 3, messageTableCount()); + + // let first message expire + TimeUnit.SECONDS.sleep(5); + + sub = consumerSession.createDurableSubscriber(topic, subName); + message = sub.receive(5000); + assertNotNull("got message", message); + LOG.info("Got: " + message); + + waitForAck(0, 1); + + for (int i = 0; i < 10; i++) { + jdbc.cleanup(); + } + assertEquals("one messages pending", 1, messageTableCount()); + + message = sub.receive(5000); + assertNotNull("got message two", message); + LOG.info("Got: " + message); + + waitForAck(0, 2); + + for (int i = 0; i < 10; i++) { + jdbc.cleanup(); + } + assertEquals("no messages pending", 0, messageTableCount()); + } + + private int messageTableCount() throws Exception { + int count = -1; + java.sql.Connection c = dataSource.getConnection(); + try { + PreparedStatement s = c.prepareStatement("SELECT COUNT(*) FROM ACTIVEMQ_MSGS"); + ResultSet rs = s.executeQuery(); + if (rs.next()) { + count = rs.getInt(1); + } + } + finally { + if (c != null) { + c.close(); + } + } + return count; + } + + private void waitForAck(final int priority) throws Exception { + waitForAck(priority, 0); + } + + private void waitForAck(final int priority, final int minId) throws Exception { + assertTrue("got ack for " + priority, Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + int id = 0; + java.sql.Connection c = dataSource.getConnection(); + try { + PreparedStatement s = c.prepareStatement("SELECT LAST_ACKED_ID FROM ACTIVEMQ_ACKS WHERE PRIORITY=" + priority); + ResultSet rs = s.executeQuery(); + if (rs.next()) { + id = rs.getInt(1); + } } - start = System.currentTimeMillis(); - messageProducer.send(message, DeliveryMode.PERSISTENT, message.getJMSPriority(), 0); - long duration = System.currentTimeMillis() - start; - max = Math.max(max, duration); - if (duration == max) { - LOG.info("new max: " + max + " on i=" + i + ", " + message.getText()); + finally { + if (c != null) { + c.close(); + } } - sum += duration; - } + return id > minId; + } + })); + } - LOG.info("Sent: " + TO_SEND + ", max send time: " + max); + @SuppressWarnings("unused") + private int messageTableDump() throws Exception { + int count = -1; + java.sql.Connection c = dataSource.getConnection(); + try { + PreparedStatement s = c.prepareStatement("SELECT * FROM ACTIVEMQ_MSGS"); + ResultSet rs = s.executeQuery(); + if (rs.next()) { + count = rs.getInt(1); + } + } + finally { + if (c != null) { + c.close(); + } + } + return count; + } - double noConsumerAve = (sum * 100 / TO_SEND); - sub = consumerSession.createDurableSubscriber(topic, subName); - final AtomicInteger count = new AtomicInteger(); - sub.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - try { - count.incrementAndGet(); - if (count.get() % 100 == 0) { - LOG.info("onMessage: count: " + count.get() + ", " + ((TextMessage) message).getText() + ", seqNo " + message.getIntProperty("seq") + ", " + message.getJMSMessageID()); - } - int seqNo = message.getIntProperty("seq"); - if (dups[seqNo] == 0) { - dups[seqNo] = 1; - } else { - LOG.error("Duplicate: " + ((TextMessage) message).getText() + ", " + message.getJMSMessageID()); - duplicates.add(message); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - - LOG.info("Activated consumer"); - sum = max = 0; - for (int i = TO_SEND; i < (TO_SEND * 2); i++) { - int priority = i % 10; - message.setText(i + "-" + priority); - message.setIntProperty("seq", i); - message.setJMSPriority(priority); - if (i > 0 && i % 1000 == 0) { - LOG.info("Max send time: " + max + ". Sending message: " + message.getText()); - } - start = System.currentTimeMillis(); - messageProducer.send(message, DeliveryMode.PERSISTENT, message.getJMSPriority(), 0); - long duration = System.currentTimeMillis() - start; - max = Math.max(max, duration); - if (duration == max) { - LOG.info("new max: " + max + " on i=" + i + ", " + message.getText()); - } - sum += duration; - } - LOG.info("Sent another: " + TO_SEND + ", max send time: " + max); - - double withConsumerAve = (sum * 100 / TO_SEND); - final int reasonableMultiplier = 4; // not so reasonable, but on slow disks it can be - assertTrue("max X times as slow with consumer:" + withConsumerAve + " , noConsumerMax:" + noConsumerAve, - withConsumerAve < noConsumerAve * reasonableMultiplier); - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("count: " + count.get()); - return TO_SEND * 2 == count.get(); - } - }, 60 * 1000); - - assertTrue("No duplicates : " + duplicates, duplicates.isEmpty()); - assertEquals("got all messages", TO_SEND * 2, count.get()); - } - - public void testCleanupPriorityDestination() throws Exception { - assertEquals("no messages pending", 0, messageTableCount()); - - ActiveMQTopic topic = (ActiveMQTopic) sess.createTopic("TEST"); - final String subName = "priorityConcurrent"; - Connection consumerConn = factory.createConnection(); - consumerConn.setClientID("subName"); - consumerConn.start(); - Session consumerSession = consumerConn.createSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber sub = consumerSession.createDurableSubscriber(topic, subName); - sub.close(); - - MessageProducer messageProducer = sess.createProducer(topic); - Message message = sess.createTextMessage(); - message.setJMSPriority(2); - messageProducer.send(message, DeliveryMode.PERSISTENT, message.getJMSPriority(), 0); - message.setJMSPriority(5); - messageProducer.send(message, DeliveryMode.PERSISTENT, message.getJMSPriority(), 0); - - assertEquals("two messages pending", 2, messageTableCount()); - - sub = consumerSession.createDurableSubscriber(topic, subName); - - message = sub.receive(5000); - assertEquals("got high priority", 5, message.getJMSPriority()); - - waitForAck(5); - - for (int i=0; i<10; i++) { - jdbc.cleanup(); - } - assertEquals("one messages pending", 1, messageTableCount()); - - message = sub.receive(5000); - assertEquals("got high priority", 2, message.getJMSPriority()); - - waitForAck(2); - - for (int i=0; i<10; i++) { - jdbc.cleanup(); - } - assertEquals("no messages pending", 0, messageTableCount()); - } - - - public void testCleanupNonPriorityDestination() throws Exception { - assertEquals("no messages pending", 0, messageTableCount()); - - ActiveMQTopic topic = (ActiveMQTopic) sess.createTopic("TEST_CLEANUP_NO_PRIORITY"); - final String subName = "subName"; - Connection consumerConn = factory.createConnection(); - consumerConn.setClientID("subName"); - consumerConn.start(); - Session consumerSession = consumerConn.createSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber sub = consumerSession.createDurableSubscriber(topic, subName); - sub.close(); - - MessageProducer messageProducer = sess.createProducer(topic); - Message message = sess.createTextMessage("ToExpire"); - messageProducer.send(message, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, 4000); - - message = sess.createTextMessage("A"); - messageProducer.send(message); - message = sess.createTextMessage("B"); - messageProducer.send(message); - message = null; - - assertEquals("three messages pending", 3, messageTableCount()); - - // let first message expire - TimeUnit.SECONDS.sleep(5); - - sub = consumerSession.createDurableSubscriber(topic, subName); - message = sub.receive(5000); - assertNotNull("got message", message); - LOG.info("Got: " + message); - - waitForAck(0, 1); - - for (int i=0; i<10; i++) { - jdbc.cleanup(); - } - assertEquals("one messages pending", 1, messageTableCount()); - - message = sub.receive(5000); - assertNotNull("got message two", message); - LOG.info("Got: " + message); - - waitForAck(0, 2); - - for (int i=0; i<10; i++) { - jdbc.cleanup(); - } - assertEquals("no messages pending", 0, messageTableCount()); - } - - private int messageTableCount() throws Exception { - int count = -1; - java.sql.Connection c = dataSource.getConnection(); - try { - PreparedStatement s = c.prepareStatement("SELECT COUNT(*) FROM ACTIVEMQ_MSGS"); - ResultSet rs = s.executeQuery(); - if (rs.next()) { - count = rs.getInt(1); - } - } finally { - if (c!=null) { - c.close(); - } - } - return count; - } - - private void waitForAck(final int priority) throws Exception { - waitForAck(priority, 0); - } - - private void waitForAck(final int priority, final int minId) throws Exception { - assertTrue("got ack for " + priority, Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - int id = 0; - java.sql.Connection c = dataSource.getConnection(); - try { - PreparedStatement s = c.prepareStatement("SELECT LAST_ACKED_ID FROM ACTIVEMQ_ACKS WHERE PRIORITY=" + priority); - ResultSet rs = s.executeQuery(); - if (rs.next()) { - id = rs.getInt(1); - } - } finally { - if (c!=null) { - c.close(); - } - } - return id>minId; - } - })); - } - - @SuppressWarnings("unused") - private int messageTableDump() throws Exception { - int count = -1; - java.sql.Connection c = dataSource.getConnection(); - try { - PreparedStatement s = c.prepareStatement("SELECT * FROM ACTIVEMQ_MSGS"); - ResultSet rs = s.executeQuery(); - if (rs.next()) { - count = rs.getInt(1); - } - } finally { - if (c!=null) { - c.close(); - } - } - return count; - } - - public static Test suite() { - return suite(JDBCMessagePriorityTest.class); - } + public static Test suite() { + return suite(JDBCMessagePriorityTest.class); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCNegativeQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCNegativeQueueTest.java index 998ff7c5d7..b3fe798bc7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCNegativeQueueTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCNegativeQueueTest.java @@ -29,63 +29,63 @@ import org.apache.derby.jdbc.EmbeddedDataSource; public class JDBCNegativeQueueTest extends NegativeQueueTest { - EmbeddedDataSource dataSource; - - protected void configureBroker(BrokerService answer) throws Exception { - super.configureBroker(answer); - JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); - dataSource = new EmbeddedDataSource(); - dataSource.setDatabaseName("derbyDb"); - dataSource.setCreateDatabase("create"); - jdbc.setDataSource(dataSource); - answer.setPersistenceAdapter(jdbc); - } + EmbeddedDataSource dataSource; - protected void tearDown() throws Exception { - if (DEBUG) { - printQuery("Select * from ACTIVEMQ_MSGS", System.out); - } - super.tearDown(); - } - - - private void printQuery(String query, PrintStream out) - throws SQLException { - Connection conn = dataSource.getConnection(); - printQuery(conn.prepareStatement(query), out); - conn.close(); - } + protected void configureBroker(BrokerService answer) throws Exception { + super.configureBroker(answer); + JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); + dataSource = new EmbeddedDataSource(); + dataSource.setDatabaseName("derbyDb"); + dataSource.setCreateDatabase("create"); + jdbc.setDataSource(dataSource); + answer.setPersistenceAdapter(jdbc); + } - private void printQuery(PreparedStatement s, PrintStream out) - throws SQLException { + protected void tearDown() throws Exception { + if (DEBUG) { + printQuery("Select * from ACTIVEMQ_MSGS", System.out); + } + super.tearDown(); + } - ResultSet set = null; - try { - set = s.executeQuery(); - ResultSetMetaData metaData = set.getMetaData(); + private void printQuery(String query, PrintStream out) throws SQLException { + Connection conn = dataSource.getConnection(); + printQuery(conn.prepareStatement(query), out); + conn.close(); + } + + private void printQuery(PreparedStatement s, PrintStream out) throws SQLException { + + ResultSet set = null; + try { + set = s.executeQuery(); + ResultSetMetaData metaData = set.getMetaData(); + for (int i = 1; i <= metaData.getColumnCount(); i++) { + if (i == 1) + out.print("||"); + out.print(metaData.getColumnName(i) + "||"); + } + out.println(); + while (set.next()) { for (int i = 1; i <= metaData.getColumnCount(); i++) { - if (i == 1) - out.print("||"); - out.print(metaData.getColumnName(i) + "||"); + if (i == 1) + out.print("|"); + out.print(set.getString(i) + "|"); } out.println(); - while (set.next()) { - for (int i = 1; i <= metaData.getColumnCount(); i++) { - if (i == 1) - out.print("|"); - out.print(set.getString(i) + "|"); - } - out.println(); - } - } finally { - try { - set.close(); - } catch (Throwable ignore) { - } - try { - s.close(); - } catch (Throwable ignore) { - } - } - } + } + } + finally { + try { + set.close(); + } + catch (Throwable ignore) { + } + try { + s.close(); + } + catch (Throwable ignore) { + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCNetworkBrokerDetachTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCNetworkBrokerDetachTest.java index 409b20f0eb..71ffb1b9f8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCNetworkBrokerDetachTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCNetworkBrokerDetachTest.java @@ -22,15 +22,15 @@ import org.apache.derby.jdbc.EmbeddedDataSource; public class JDBCNetworkBrokerDetachTest extends NetworkBrokerDetachTest { - protected void configureBroker(BrokerService broker) throws Exception { - JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); - EmbeddedDataSource dataSource = new EmbeddedDataSource(); - dataSource.setDatabaseName(broker.getBrokerName()); - dataSource.setCreateDatabase("create"); - jdbc.setDataSource(dataSource); - jdbc.deleteAllMessages(); - broker.setPersistenceAdapter(jdbc); - broker.setUseVirtualTopics(false); - } - + protected void configureBroker(BrokerService broker) throws Exception { + JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); + EmbeddedDataSource dataSource = new EmbeddedDataSource(); + dataSource.setDatabaseName(broker.getBrokerName()); + dataSource.setCreateDatabase("create"); + jdbc.setDataSource(dataSource); + jdbc.deleteAllMessages(); + broker.setPersistenceAdapter(jdbc); + broker.setUseVirtualTopics(false); + } + } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCPersistenceAdapterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCPersistenceAdapterTest.java index ce539d2381..b3e299114a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCPersistenceAdapterTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCPersistenceAdapterTest.java @@ -25,41 +25,42 @@ import org.apache.activemq.store.PersistenceAdapterTestSupport; import org.apache.derby.jdbc.EmbeddedDataSource; public class JDBCPersistenceAdapterTest extends PersistenceAdapterTestSupport { - - protected PersistenceAdapter createPersistenceAdapter(boolean delete) throws IOException { - JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); - - // explicitly enable audit as it is now off by default - // due to org.apache.activemq.broker.ProducerBrokerExchange.canDispatch(Message) - jdbc.setEnableAudit(true); - - brokerService.setSchedulerSupport(false); - brokerService.setPersistenceAdapter(jdbc); - jdbc.setBrokerService(brokerService); - EmbeddedDataSource dataSource = new EmbeddedDataSource(); - dataSource.setDatabaseName("derbyDb"); - dataSource.setCreateDatabase("create"); - jdbc.setDataSource(dataSource); - if( delete ) { - jdbc.deleteAllMessages(); - } - return jdbc; - } - - public void testAuditOff() throws Exception { - pa.stop(); - pa = createPersistenceAdapter(true); - ((JDBCPersistenceAdapter)pa).setEnableAudit(false); - pa.start(); - boolean failed = true; - try { - testStoreCanHandleDupMessages(); - failed = false; - } catch (AssertionFailedError e) { - } - - if (!failed) { - fail("Should have failed with audit turned off"); - } - } + + protected PersistenceAdapter createPersistenceAdapter(boolean delete) throws IOException { + JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); + + // explicitly enable audit as it is now off by default + // due to org.apache.activemq.broker.ProducerBrokerExchange.canDispatch(Message) + jdbc.setEnableAudit(true); + + brokerService.setSchedulerSupport(false); + brokerService.setPersistenceAdapter(jdbc); + jdbc.setBrokerService(brokerService); + EmbeddedDataSource dataSource = new EmbeddedDataSource(); + dataSource.setDatabaseName("derbyDb"); + dataSource.setCreateDatabase("create"); + jdbc.setDataSource(dataSource); + if (delete) { + jdbc.deleteAllMessages(); + } + return jdbc; + } + + public void testAuditOff() throws Exception { + pa.stop(); + pa = createPersistenceAdapter(true); + ((JDBCPersistenceAdapter) pa).setEnableAudit(false); + pa.start(); + boolean failed = true; + try { + testStoreCanHandleDupMessages(); + failed = false; + } + catch (AssertionFailedError e) { + } + + if (!failed) { + fail("Should have failed with audit turned off"); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCStoreAutoCommitTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCStoreAutoCommitTest.java index 6a19628c57..de57cbc1ec 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCStoreAutoCommitTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCStoreAutoCommitTest.java @@ -65,438 +65,451 @@ import org.junit.Test; public class JDBCStoreAutoCommitTest { - private static final String BROKER_NAME = "AutoCommitTest"; - private static final String TEST_DEST = "commitCheck"; - private static final String MSG_TEXT = "JDBCStoreAutoCommitTest TEST"; - - /** - * verify dropping and recreating tables - * - * @throws Exception - */ - @Test - public void testDeleteAllMessages() throws Exception { - BrokerService broker = createBrokerService(); - broker.getPersistenceAdapter().deleteAllMessages(); - broker.setUseJmx(false); - broker.start(); - broker.waitUntilStarted(); - broker.stop(); - broker.waitUntilStopped(); - } - - /** - * Send message and consume message, JMS session is not transacted - * - * @throws Exception - */ - @Test - public void testSendConsume() throws Exception { - this.doSendConsume(false); - } - - /** - * send message and consume message, JMS session is transacted - * - * @throws Exception - */ - @Test - public void testSendConsumeTransacted() throws Exception { - this.doSendConsume(true); - } - - private void doSendConsume(boolean transacted) throws Exception { - - BrokerService broker = createBrokerService(); - broker.setUseJmx(false); - broker.start(); - broker.waitUntilStarted(); - - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(new URI("vm:" + BROKER_NAME)); - ActiveMQConnection c1 = (ActiveMQConnection) cf.createConnection(); - c1.start(); - - try { - // message send - Session session1 = c1.createSession(transacted, Session.AUTO_ACKNOWLEDGE); - MessageProducer messageProducer = session1.createProducer(session1.createQueue(TEST_DEST)); - TextMessage textMessage = session1.createTextMessage(MSG_TEXT); - messageProducer.send(textMessage); - - if (transacted) { - session1.commit(); - } - - // consume - Session session2 = c1.createSession(transacted, Session.AUTO_ACKNOWLEDGE); - MessageConsumer messageConsumer = session2.createConsumer(session2.createQueue(TEST_DEST)); - TextMessage messageReceived = (TextMessage) messageConsumer.receive(1000); - - assertEquals("check message received", MSG_TEXT, messageReceived.getText()); - } finally { - c1.close(); - broker.stop(); - broker.waitUntilStopped(); - } - } - - private BrokerService createBrokerService() throws IOException { - BrokerService broker = new BrokerService(); - broker.setBrokerName(BROKER_NAME); - broker.setUseJmx(false); - - JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); - EmbeddedDataSource embeddedDataSource = new EmbeddedDataSource(); - embeddedDataSource.setDatabaseName("derbyDb"); - embeddedDataSource.setCreateDatabase("create"); - - javax.sql.DataSource wrappedDataSource = new TestDataSource(embeddedDataSource); - - jdbc.setDataSource(wrappedDataSource); - - broker.setPersistenceAdapter(jdbc); - return broker; - } - - private class TestDataSource implements javax.sql.DataSource { - - private final javax.sql.DataSource realDataSource; - - public TestDataSource(javax.sql.DataSource dataSource) { - realDataSource = dataSource; - } - - @Override - public Connection getConnection() throws SQLException { - Connection autoCommitCheckConnection = new AutoCommitCheckConnection(realDataSource.getConnection()); - return autoCommitCheckConnection; - } - - @Override - public Connection getConnection(String username, String password) throws SQLException { - Connection autoCommitCheckConnection = new AutoCommitCheckConnection(realDataSource.getConnection(username, password)); - - return autoCommitCheckConnection; - } - - @Override - public PrintWriter getLogWriter() throws SQLException { - return realDataSource.getLogWriter(); - } - - @Override - public void setLogWriter(PrintWriter out) throws SQLException { - realDataSource.setLogWriter(out); - } - - @Override - public void setLoginTimeout(int seconds) throws SQLException { - realDataSource.setLoginTimeout(seconds); - } - - @Override - public int getLoginTimeout() throws SQLException { - return realDataSource.getLoginTimeout(); - } - - @Override - public Logger getParentLogger() throws SQLFeatureNotSupportedException { - return realDataSource.getParentLogger(); - } - - @Override - public T unwrap(Class iface) throws SQLException { - return realDataSource.unwrap(iface); - } - - @Override - public boolean isWrapperFor(Class iface) throws SQLException { - return realDataSource.isWrapperFor(iface); - } - } - - private class AutoCommitCheckConnection implements Connection { - - private final Connection realConnection; - - public AutoCommitCheckConnection(Connection connection) { - this.realConnection = connection; - } - - // verify commit is not called on an auto-commit connection - @Override - public void commit() throws SQLException { - if (getAutoCommit() == true) { - throw new SQLException("AutoCommitCheckConnection: Called commit on autoCommit Connection"); - } - realConnection.commit(); - } - - // Just plumbing for wrapper. Might have been better to do a Dynamic Proxy here. - - @Override - public Statement createStatement() throws SQLException { - return realConnection.createStatement(); - } - - @Override - public PreparedStatement prepareStatement(String sql) throws SQLException { - return realConnection.prepareStatement(sql); - } - - @Override - public CallableStatement prepareCall(String sql) throws SQLException { - return realConnection.prepareCall(sql); - } - - @Override - public String nativeSQL(String sql) throws SQLException { - return realConnection.nativeSQL(sql); - } - - @Override - public void setAutoCommit(boolean autoCommit) throws SQLException { - realConnection.setAutoCommit(autoCommit); - } - - @Override - public boolean getAutoCommit() throws SQLException { - return realConnection.getAutoCommit(); - } - - @Override - public void rollback() throws SQLException { - realConnection.rollback(); - } - - @Override - public void close() throws SQLException { - realConnection.close(); - } - - @Override - public boolean isClosed() throws SQLException { - return realConnection.isClosed(); - } - - @Override - public DatabaseMetaData getMetaData() throws SQLException { - return realConnection.getMetaData(); - } - - @Override - public void setReadOnly(boolean readOnly) throws SQLException { - realConnection.setReadOnly(readOnly); - } - - @Override - public boolean isReadOnly() throws SQLException { - return realConnection.isReadOnly(); - } - - @Override - public void setCatalog(String catalog) throws SQLException { - realConnection.setCatalog(catalog); - } - - @Override - public String getCatalog() throws SQLException { - return realConnection.getCatalog(); - } - - @Override - public void setTransactionIsolation(int level) throws SQLException { - realConnection.setTransactionIsolation(level); - } - - @Override - public int getTransactionIsolation() throws SQLException { - return realConnection.getTransactionIsolation(); - } - - @Override - public SQLWarning getWarnings() throws SQLException { - return realConnection.getWarnings(); - } - - @Override - public void clearWarnings() throws SQLException { - realConnection.clearWarnings(); - } - - @Override - public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { - return realConnection.createStatement(resultSetType, resultSetConcurrency); - } - - @Override - public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { - return realConnection.prepareStatement(sql, resultSetType, resultSetConcurrency); - } - - @Override - public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { - return realConnection.prepareCall(sql, resultSetType, resultSetConcurrency); - } - - @Override - public Map> getTypeMap() throws SQLException { - return realConnection.getTypeMap(); - } - - @Override - public void setTypeMap(Map> map) throws SQLException { - realConnection.setTypeMap(map); - } - - @Override - public void setHoldability(int holdability) throws SQLException { - realConnection.setHoldability(holdability); - } - - @Override - public int getHoldability() throws SQLException { - return realConnection.getHoldability(); - } - - @Override - public Savepoint setSavepoint() throws SQLException { - return realConnection.setSavepoint(); - } - - @Override - public Savepoint setSavepoint(String name) throws SQLException { - return realConnection.setSavepoint(name); - } - - @Override - public void rollback(Savepoint savepoint) throws SQLException { - realConnection.rollback(); - } - - @Override - public void releaseSavepoint(Savepoint savepoint) throws SQLException { - realConnection.releaseSavepoint(savepoint); - } - - @Override - public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { - return realConnection.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); - } - - @Override - public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { - return realConnection.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); - } - - @Override - public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { - return realConnection.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); - } - - @Override - public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { - return realConnection.prepareStatement(sql, autoGeneratedKeys); - } - - @Override - public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { - return realConnection.prepareStatement(sql, columnIndexes); - } - - @Override - public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { - return realConnection.prepareStatement(sql, columnNames); - } - - @Override - public Clob createClob() throws SQLException { - return realConnection.createClob(); - } - - @Override - public Blob createBlob() throws SQLException { - return realConnection.createBlob(); - } - - @Override - public NClob createNClob() throws SQLException { - return realConnection.createNClob(); - } - - @Override - public SQLXML createSQLXML() throws SQLException { - return realConnection.createSQLXML(); - } - - @Override - public boolean isValid(int timeout) throws SQLException { - return realConnection.isValid(timeout); - } - - @Override - public void setClientInfo(String name, String value) throws SQLClientInfoException { - realConnection.setClientInfo(name, value); - } - - @Override - public void setClientInfo(Properties properties) throws SQLClientInfoException { - realConnection.setClientInfo(properties); - } - - @Override - public String getClientInfo(String name) throws SQLException { - return realConnection.getClientInfo(name); - } - - @Override - public Properties getClientInfo() throws SQLException { - return realConnection.getClientInfo(); - } - - @Override - public Array createArrayOf(String typeName, Object[] elements) throws SQLException { - return realConnection.createArrayOf(typeName, elements); - } - - @Override - public Struct createStruct(String typeName, Object[] attributes) throws SQLException { - return realConnection.createStruct(typeName, attributes); - } - - @Override - public void setSchema(String schema) throws SQLException { - realConnection.setSchema(schema); - } - - @Override - public String getSchema() throws SQLException { - return realConnection.getSchema(); - } - - @Override - public void abort(Executor executor) throws SQLException { - realConnection.abort(executor); - } - - @Override - public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { - realConnection.setNetworkTimeout(executor, milliseconds); - } - - @Override - public int getNetworkTimeout() throws SQLException { - return realConnection.getNetworkTimeout(); - } - - @Override - public T unwrap(Class iface) throws SQLException { - return realConnection.unwrap(iface); - } - - @Override - public boolean isWrapperFor(Class iface) throws SQLException { - return realConnection.isWrapperFor(iface); - } - } + private static final String BROKER_NAME = "AutoCommitTest"; + private static final String TEST_DEST = "commitCheck"; + private static final String MSG_TEXT = "JDBCStoreAutoCommitTest TEST"; + + /** + * verify dropping and recreating tables + * + * @throws Exception + */ + @Test + public void testDeleteAllMessages() throws Exception { + BrokerService broker = createBrokerService(); + broker.getPersistenceAdapter().deleteAllMessages(); + broker.setUseJmx(false); + broker.start(); + broker.waitUntilStarted(); + broker.stop(); + broker.waitUntilStopped(); + } + + /** + * Send message and consume message, JMS session is not transacted + * + * @throws Exception + */ + @Test + public void testSendConsume() throws Exception { + this.doSendConsume(false); + } + + /** + * send message and consume message, JMS session is transacted + * + * @throws Exception + */ + @Test + public void testSendConsumeTransacted() throws Exception { + this.doSendConsume(true); + } + + private void doSendConsume(boolean transacted) throws Exception { + + BrokerService broker = createBrokerService(); + broker.setUseJmx(false); + broker.start(); + broker.waitUntilStarted(); + + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(new URI("vm:" + BROKER_NAME)); + ActiveMQConnection c1 = (ActiveMQConnection) cf.createConnection(); + c1.start(); + + try { + // message send + Session session1 = c1.createSession(transacted, Session.AUTO_ACKNOWLEDGE); + MessageProducer messageProducer = session1.createProducer(session1.createQueue(TEST_DEST)); + TextMessage textMessage = session1.createTextMessage(MSG_TEXT); + messageProducer.send(textMessage); + + if (transacted) { + session1.commit(); + } + + // consume + Session session2 = c1.createSession(transacted, Session.AUTO_ACKNOWLEDGE); + MessageConsumer messageConsumer = session2.createConsumer(session2.createQueue(TEST_DEST)); + TextMessage messageReceived = (TextMessage) messageConsumer.receive(1000); + + assertEquals("check message received", MSG_TEXT, messageReceived.getText()); + } + finally { + c1.close(); + broker.stop(); + broker.waitUntilStopped(); + } + } + + private BrokerService createBrokerService() throws IOException { + BrokerService broker = new BrokerService(); + broker.setBrokerName(BROKER_NAME); + broker.setUseJmx(false); + + JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); + EmbeddedDataSource embeddedDataSource = new EmbeddedDataSource(); + embeddedDataSource.setDatabaseName("derbyDb"); + embeddedDataSource.setCreateDatabase("create"); + + javax.sql.DataSource wrappedDataSource = new TestDataSource(embeddedDataSource); + + jdbc.setDataSource(wrappedDataSource); + + broker.setPersistenceAdapter(jdbc); + return broker; + } + + private class TestDataSource implements javax.sql.DataSource { + + private final javax.sql.DataSource realDataSource; + + public TestDataSource(javax.sql.DataSource dataSource) { + realDataSource = dataSource; + } + + @Override + public Connection getConnection() throws SQLException { + Connection autoCommitCheckConnection = new AutoCommitCheckConnection(realDataSource.getConnection()); + return autoCommitCheckConnection; + } + + @Override + public Connection getConnection(String username, String password) throws SQLException { + Connection autoCommitCheckConnection = new AutoCommitCheckConnection(realDataSource.getConnection(username, password)); + + return autoCommitCheckConnection; + } + + @Override + public PrintWriter getLogWriter() throws SQLException { + return realDataSource.getLogWriter(); + } + + @Override + public void setLogWriter(PrintWriter out) throws SQLException { + realDataSource.setLogWriter(out); + } + + @Override + public void setLoginTimeout(int seconds) throws SQLException { + realDataSource.setLoginTimeout(seconds); + } + + @Override + public int getLoginTimeout() throws SQLException { + return realDataSource.getLoginTimeout(); + } + + @Override + public Logger getParentLogger() throws SQLFeatureNotSupportedException { + return realDataSource.getParentLogger(); + } + + @Override + public T unwrap(Class iface) throws SQLException { + return realDataSource.unwrap(iface); + } + + @Override + public boolean isWrapperFor(Class iface) throws SQLException { + return realDataSource.isWrapperFor(iface); + } + } + + private class AutoCommitCheckConnection implements Connection { + + private final Connection realConnection; + + public AutoCommitCheckConnection(Connection connection) { + this.realConnection = connection; + } + + // verify commit is not called on an auto-commit connection + @Override + public void commit() throws SQLException { + if (getAutoCommit() == true) { + throw new SQLException("AutoCommitCheckConnection: Called commit on autoCommit Connection"); + } + realConnection.commit(); + } + + // Just plumbing for wrapper. Might have been better to do a Dynamic Proxy here. + + @Override + public Statement createStatement() throws SQLException { + return realConnection.createStatement(); + } + + @Override + public PreparedStatement prepareStatement(String sql) throws SQLException { + return realConnection.prepareStatement(sql); + } + + @Override + public CallableStatement prepareCall(String sql) throws SQLException { + return realConnection.prepareCall(sql); + } + + @Override + public String nativeSQL(String sql) throws SQLException { + return realConnection.nativeSQL(sql); + } + + @Override + public void setAutoCommit(boolean autoCommit) throws SQLException { + realConnection.setAutoCommit(autoCommit); + } + + @Override + public boolean getAutoCommit() throws SQLException { + return realConnection.getAutoCommit(); + } + + @Override + public void rollback() throws SQLException { + realConnection.rollback(); + } + + @Override + public void close() throws SQLException { + realConnection.close(); + } + + @Override + public boolean isClosed() throws SQLException { + return realConnection.isClosed(); + } + + @Override + public DatabaseMetaData getMetaData() throws SQLException { + return realConnection.getMetaData(); + } + + @Override + public void setReadOnly(boolean readOnly) throws SQLException { + realConnection.setReadOnly(readOnly); + } + + @Override + public boolean isReadOnly() throws SQLException { + return realConnection.isReadOnly(); + } + + @Override + public void setCatalog(String catalog) throws SQLException { + realConnection.setCatalog(catalog); + } + + @Override + public String getCatalog() throws SQLException { + return realConnection.getCatalog(); + } + + @Override + public void setTransactionIsolation(int level) throws SQLException { + realConnection.setTransactionIsolation(level); + } + + @Override + public int getTransactionIsolation() throws SQLException { + return realConnection.getTransactionIsolation(); + } + + @Override + public SQLWarning getWarnings() throws SQLException { + return realConnection.getWarnings(); + } + + @Override + public void clearWarnings() throws SQLException { + realConnection.clearWarnings(); + } + + @Override + public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { + return realConnection.createStatement(resultSetType, resultSetConcurrency); + } + + @Override + public PreparedStatement prepareStatement(String sql, + int resultSetType, + int resultSetConcurrency) throws SQLException { + return realConnection.prepareStatement(sql, resultSetType, resultSetConcurrency); + } + + @Override + public CallableStatement prepareCall(String sql, + int resultSetType, + int resultSetConcurrency) throws SQLException { + return realConnection.prepareCall(sql, resultSetType, resultSetConcurrency); + } + + @Override + public Map> getTypeMap() throws SQLException { + return realConnection.getTypeMap(); + } + + @Override + public void setTypeMap(Map> map) throws SQLException { + realConnection.setTypeMap(map); + } + + @Override + public void setHoldability(int holdability) throws SQLException { + realConnection.setHoldability(holdability); + } + + @Override + public int getHoldability() throws SQLException { + return realConnection.getHoldability(); + } + + @Override + public Savepoint setSavepoint() throws SQLException { + return realConnection.setSavepoint(); + } + + @Override + public Savepoint setSavepoint(String name) throws SQLException { + return realConnection.setSavepoint(name); + } + + @Override + public void rollback(Savepoint savepoint) throws SQLException { + realConnection.rollback(); + } + + @Override + public void releaseSavepoint(Savepoint savepoint) throws SQLException { + realConnection.releaseSavepoint(savepoint); + } + + @Override + public Statement createStatement(int resultSetType, + int resultSetConcurrency, + int resultSetHoldability) throws SQLException { + return realConnection.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); + } + + @Override + public PreparedStatement prepareStatement(String sql, + int resultSetType, + int resultSetConcurrency, + int resultSetHoldability) throws SQLException { + return realConnection.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); + } + + @Override + public CallableStatement prepareCall(String sql, + int resultSetType, + int resultSetConcurrency, + int resultSetHoldability) throws SQLException { + return realConnection.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); + } + + @Override + public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { + return realConnection.prepareStatement(sql, autoGeneratedKeys); + } + + @Override + public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { + return realConnection.prepareStatement(sql, columnIndexes); + } + + @Override + public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { + return realConnection.prepareStatement(sql, columnNames); + } + + @Override + public Clob createClob() throws SQLException { + return realConnection.createClob(); + } + + @Override + public Blob createBlob() throws SQLException { + return realConnection.createBlob(); + } + + @Override + public NClob createNClob() throws SQLException { + return realConnection.createNClob(); + } + + @Override + public SQLXML createSQLXML() throws SQLException { + return realConnection.createSQLXML(); + } + + @Override + public boolean isValid(int timeout) throws SQLException { + return realConnection.isValid(timeout); + } + + @Override + public void setClientInfo(String name, String value) throws SQLClientInfoException { + realConnection.setClientInfo(name, value); + } + + @Override + public void setClientInfo(Properties properties) throws SQLClientInfoException { + realConnection.setClientInfo(properties); + } + + @Override + public String getClientInfo(String name) throws SQLException { + return realConnection.getClientInfo(name); + } + + @Override + public Properties getClientInfo() throws SQLException { + return realConnection.getClientInfo(); + } + + @Override + public Array createArrayOf(String typeName, Object[] elements) throws SQLException { + return realConnection.createArrayOf(typeName, elements); + } + + @Override + public Struct createStruct(String typeName, Object[] attributes) throws SQLException { + return realConnection.createStruct(typeName, attributes); + } + + @Override + public void setSchema(String schema) throws SQLException { + realConnection.setSchema(schema); + } + + @Override + public String getSchema() throws SQLException { + return realConnection.getSchema(); + } + + @Override + public void abort(Executor executor) throws SQLException { + realConnection.abort(executor); + } + + @Override + public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { + realConnection.setNetworkTimeout(executor, milliseconds); + } + + @Override + public int getNetworkTimeout() throws SQLException { + return realConnection.getNetworkTimeout(); + } + + @Override + public T unwrap(Class iface) throws SQLException { + return realConnection.unwrap(iface); + } + + @Override + public boolean isWrapperFor(Class iface) throws SQLException { + return realConnection.isWrapperFor(iface); + } + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCStoreBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCStoreBrokerTest.java index 6e78927cd4..785137feab 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCStoreBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCStoreBrokerTest.java @@ -24,37 +24,36 @@ import org.apache.derby.jdbc.EmbeddedDataSource; public class JDBCStoreBrokerTest extends BrokerTest { - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); - EmbeddedDataSource dataSource = new EmbeddedDataSource(); - dataSource.setDatabaseName("derbyDb"); - dataSource.setCreateDatabase("create"); - jdbc.setDataSource(dataSource); - - jdbc.deleteAllMessages(); - broker.setPersistenceAdapter(jdbc); - return broker; - } - - protected BrokerService createRestartedBroker() throws Exception { - BrokerService broker = new BrokerService(); - JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); - EmbeddedDataSource dataSource = new EmbeddedDataSource(); - dataSource.setDatabaseName("derbyDb"); - dataSource.setCreateDatabase("create"); - jdbc.setDataSource(dataSource); - broker.setPersistenceAdapter(jdbc); - return broker; - } - - - public static Test suite() { - return suite(JDBCStoreBrokerTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - + protected BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); + JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); + EmbeddedDataSource dataSource = new EmbeddedDataSource(); + dataSource.setDatabaseName("derbyDb"); + dataSource.setCreateDatabase("create"); + jdbc.setDataSource(dataSource); + + jdbc.deleteAllMessages(); + broker.setPersistenceAdapter(jdbc); + return broker; + } + + protected BrokerService createRestartedBroker() throws Exception { + BrokerService broker = new BrokerService(); + JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); + EmbeddedDataSource dataSource = new EmbeddedDataSource(); + dataSource.setDatabaseName("derbyDb"); + dataSource.setCreateDatabase("create"); + jdbc.setDataSource(dataSource); + broker.setPersistenceAdapter(jdbc); + return broker; + } + + public static Test suite() { + return suite(JDBCStoreBrokerTest.class); + } + + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } + } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCStoreOrderTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCStoreOrderTest.java index 4d3ac55953..17310cb793 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCStoreOrderTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCStoreOrderTest.java @@ -32,32 +32,31 @@ import org.apache.derby.jdbc.EmbeddedDataSource; // https://issues.apache.org/activemq/browse/AMQ-2594 public class JDBCStoreOrderTest extends StoreOrderTest { - private static final Logger LOG = LoggerFactory.getLogger(JDBCStoreOrderTest.class); - - @Override - protected void dumpMessages() throws Exception { - WireFormat wireFormat = new OpenWireFormat(); - java.sql.Connection conn = ((JDBCPersistenceAdapter) broker.getPersistenceAdapter()).getDataSource().getConnection(); - PreparedStatement statement = conn.prepareStatement("SELECT ID, MSG FROM ACTIVEMQ_MSGS"); - ResultSet result = statement.executeQuery(); - while(result.next()) { - long id = result.getLong(1); - Message message = (Message)wireFormat.unmarshal(new ByteSequence(result.getBytes(2))); - LOG.info("id: " + id + ", message SeqId: " + message.getMessageId().getBrokerSequenceId() + ", MSG: " + message); - } - statement.close(); - conn.close(); - } - - @Override - protected void setPersistentAdapter(BrokerService brokerService) - throws Exception { - JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); - EmbeddedDataSource dataSource = new EmbeddedDataSource(); - dataSource.setDatabaseName("derbyDb"); - dataSource.setCreateDatabase("create"); - jdbc.setDataSource(dataSource); - brokerService.setPersistenceAdapter(jdbc); - } + private static final Logger LOG = LoggerFactory.getLogger(JDBCStoreOrderTest.class); + + @Override + protected void dumpMessages() throws Exception { + WireFormat wireFormat = new OpenWireFormat(); + java.sql.Connection conn = ((JDBCPersistenceAdapter) broker.getPersistenceAdapter()).getDataSource().getConnection(); + PreparedStatement statement = conn.prepareStatement("SELECT ID, MSG FROM ACTIVEMQ_MSGS"); + ResultSet result = statement.executeQuery(); + while (result.next()) { + long id = result.getLong(1); + Message message = (Message) wireFormat.unmarshal(new ByteSequence(result.getBytes(2))); + LOG.info("id: " + id + ", message SeqId: " + message.getMessageId().getBrokerSequenceId() + ", MSG: " + message); + } + statement.close(); + conn.close(); + } + + @Override + protected void setPersistentAdapter(BrokerService brokerService) throws Exception { + JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); + EmbeddedDataSource dataSource = new EmbeddedDataSource(); + dataSource.setDatabaseName("derbyDb"); + dataSource.setCreateDatabase("create"); + jdbc.setDataSource(dataSource); + brokerService.setPersistenceAdapter(jdbc); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCTablePrefixAssignedTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCTablePrefixAssignedTest.java index 06f623f25d..bd00179481 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCTablePrefixAssignedTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCTablePrefixAssignedTest.java @@ -46,87 +46,88 @@ import org.slf4j.LoggerFactory; public class JDBCTablePrefixAssignedTest { - private static final Logger LOG = LoggerFactory.getLogger(JDBCTablePrefixAssignedTest.class); + private static final Logger LOG = LoggerFactory.getLogger(JDBCTablePrefixAssignedTest.class); - private BrokerService service; + private BrokerService service; - @Before - public void setUp() throws Exception { - service = createBroker(); - service.start(); - service.waitUntilStarted(); - } + @Before + public void setUp() throws Exception { + service = createBroker(); + service.start(); + service.waitUntilStarted(); + } - @After - public void tearDown() throws Exception { - service.stop(); - service.waitUntilStopped(); - } + @After + public void tearDown() throws Exception { + service.stop(); + service.waitUntilStopped(); + } - @Test - public void testTablesHave() throws Exception { + @Test + public void testTablesHave() throws Exception { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost?create=false"); - ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection(); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost?create=false"); + ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue("TEST.FOO"); - MessageProducer producer = session.createProducer(destination); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue("TEST.FOO"); + MessageProducer producer = session.createProducer(destination); - for (int i = 0; i < 10; ++i) { - producer.send(session.createTextMessage("test")); - } - producer.close(); - connection.close(); + for (int i = 0; i < 10; ++i) { + producer.send(session.createTextMessage("test")); + } + producer.close(); + connection.close(); - List queuedMessages = null; - try { - queuedMessages = dumpMessages(); - } catch (Exception ex) { - LOG.info("Caught ex: ", ex); - fail("Should not have thrown an exception"); - } + List queuedMessages = null; + try { + queuedMessages = dumpMessages(); + } + catch (Exception ex) { + LOG.info("Caught ex: ", ex); + fail("Should not have thrown an exception"); + } - assertNotNull(queuedMessages); - assertEquals("Should have found 10 messages", 10, queuedMessages.size()); - } + assertNotNull(queuedMessages); + assertEquals("Should have found 10 messages", 10, queuedMessages.size()); + } - protected List dumpMessages() throws Exception { - WireFormat wireFormat = new OpenWireFormat(); - java.sql.Connection conn = ((JDBCPersistenceAdapter) service.getPersistenceAdapter()).getDataSource().getConnection(); - PreparedStatement statement = conn.prepareStatement("SELECT ID, MSG FROM MYPREFIX_ACTIVEMQ_MSGS"); - ResultSet result = statement.executeQuery(); - ArrayList results = new ArrayList(); - while(result.next()) { - long id = result.getLong(1); - Message message = (Message)wireFormat.unmarshal(new ByteSequence(result.getBytes(2))); - LOG.info("id: " + id + ", message SeqId: " + message.getMessageId().getBrokerSequenceId() + ", MSG: " + message); - results.add(message); - } - statement.close(); - conn.close(); + protected List dumpMessages() throws Exception { + WireFormat wireFormat = new OpenWireFormat(); + java.sql.Connection conn = ((JDBCPersistenceAdapter) service.getPersistenceAdapter()).getDataSource().getConnection(); + PreparedStatement statement = conn.prepareStatement("SELECT ID, MSG FROM MYPREFIX_ACTIVEMQ_MSGS"); + ResultSet result = statement.executeQuery(); + ArrayList results = new ArrayList(); + while (result.next()) { + long id = result.getLong(1); + Message message = (Message) wireFormat.unmarshal(new ByteSequence(result.getBytes(2))); + LOG.info("id: " + id + ", message SeqId: " + message.getMessageId().getBrokerSequenceId() + ", MSG: " + message); + results.add(message); + } + statement.close(); + conn.close(); - return results; - } + return results; + } - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); - EmbeddedDataSource dataSource = new EmbeddedDataSource(); - dataSource.setDatabaseName("derbyDb"); - dataSource.setCreateDatabase("create"); + protected BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); + JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); + EmbeddedDataSource dataSource = new EmbeddedDataSource(); + dataSource.setDatabaseName("derbyDb"); + dataSource.setCreateDatabase("create"); - DefaultJDBCAdapter adapter = new DefaultJDBCAdapter(); - jdbc.setAdapter(adapter); + DefaultJDBCAdapter adapter = new DefaultJDBCAdapter(); + jdbc.setAdapter(adapter); - Statements statements = new Statements(); - statements.setTablePrefix("MYPREFIX_"); - jdbc.setStatements(statements); + Statements statements = new Statements(); + statements.setTablePrefix("MYPREFIX_"); + jdbc.setStatements(statements); - jdbc.setUseLock(false); - jdbc.setDataSource(dataSource); - jdbc.deleteAllMessages(); - broker.setPersistenceAdapter(jdbc); - return broker; - } + jdbc.setUseLock(false); + jdbc.setDataSource(dataSource); + jdbc.deleteAllMessages(); + broker.setPersistenceAdapter(jdbc); + return broker; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCTestMemory.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCTestMemory.java index e8bda0786c..543d78e2c6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCTestMemory.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCTestMemory.java @@ -29,124 +29,125 @@ import org.apache.activemq.broker.BrokerService; import org.apache.derby.jdbc.EmbeddedDataSource; import org.junit.Ignore; - public class JDBCTestMemory extends TestCase { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); - Connection conn; - Session sess; - Destination dest; - - BrokerService broker; - - protected void setUp() throws Exception { - broker = createBroker(); - broker.start(); - broker.waitUntilStarted(); - } + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); + Connection conn; + Session sess; + Destination dest; - protected void tearDown() throws Exception { - broker.stop(); - } + BrokerService broker; - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setUseJmx(true); - JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); - EmbeddedDataSource dataSource = new EmbeddedDataSource(); - dataSource.setDatabaseName("derbyDb"); - dataSource.setCreateDatabase("create"); - jdbc.setDataSource(dataSource); - - jdbc.deleteAllMessages(); - broker.setPersistenceAdapter(jdbc); - broker.addConnector("tcp://0.0.0.0:61616"); - return broker; - } - - protected BrokerService createRestartedBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setUseJmx(true); - JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); - EmbeddedDataSource dataSource = new EmbeddedDataSource(); - dataSource.setDatabaseName("derbyDb"); - dataSource.setCreateDatabase("create"); - jdbc.setDataSource(dataSource); - broker.setPersistenceAdapter(jdbc); - broker.addConnector("tcp://0.0.0.0:61616"); - return broker; - } - - public void init() throws Exception { - conn = factory.createConnection(); - conn.start(); - sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - dest = sess.createQueue("test"); - } + protected void setUp() throws Exception { + broker = createBroker(); + broker.start(); + broker.waitUntilStarted(); + } - @Ignore("requires human input to terminate!") - public void testRecovery() throws Exception { - init(); - MessageProducer producer = sess.createProducer(dest); - for (int i = 0; i < 1000; i++) { - producer.send(sess.createTextMessage("test")); - } - producer.close(); - sess.close(); - conn.close(); - - broker.stop(); - broker.waitUntilStopped(); - broker = createRestartedBroker(); - broker.start(); - broker.waitUntilStarted(); - - init(); - - for (int i = 0; i < 10; i++) { - new Thread("Producer " + i) { + protected void tearDown() throws Exception { + broker.stop(); + } - public void run() { - try { - MessageProducer producer = sess.createProducer(dest); - for (int i = 0; i < 15000; i++) { - producer.send(sess.createTextMessage("test")); - if (i % 100 == 0) { - System.out.println(getName() + " sent message " + i); - } - } - producer.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - }.start(); - - new Thread("Consumer " + i) { + protected BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setUseJmx(true); + JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); + EmbeddedDataSource dataSource = new EmbeddedDataSource(); + dataSource.setDatabaseName("derbyDb"); + dataSource.setCreateDatabase("create"); + jdbc.setDataSource(dataSource); + + jdbc.deleteAllMessages(); + broker.setPersistenceAdapter(jdbc); + broker.addConnector("tcp://0.0.0.0:61616"); + return broker; + } + + protected BrokerService createRestartedBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setUseJmx(true); + JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); + EmbeddedDataSource dataSource = new EmbeddedDataSource(); + dataSource.setDatabaseName("derbyDb"); + dataSource.setCreateDatabase("create"); + jdbc.setDataSource(dataSource); + broker.setPersistenceAdapter(jdbc); + broker.addConnector("tcp://0.0.0.0:61616"); + return broker; + } + + public void init() throws Exception { + conn = factory.createConnection(); + conn.start(); + sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + dest = sess.createQueue("test"); + } + + @Ignore("requires human input to terminate!") + public void testRecovery() throws Exception { + init(); + MessageProducer producer = sess.createProducer(dest); + for (int i = 0; i < 1000; i++) { + producer.send(sess.createTextMessage("test")); + } + producer.close(); + sess.close(); + conn.close(); + + broker.stop(); + broker.waitUntilStopped(); + broker = createRestartedBroker(); + broker.start(); + broker.waitUntilStarted(); + + init(); + + for (int i = 0; i < 10; i++) { + new Thread("Producer " + i) { + + public void run() { + try { + MessageProducer producer = sess.createProducer(dest); + for (int i = 0; i < 15000; i++) { + producer.send(sess.createTextMessage("test")); + if (i % 100 == 0) { + System.out.println(getName() + " sent message " + i); + } + } + producer.close(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + }.start(); + + new Thread("Consumer " + i) { + + public void run() { + try { + MessageConsumer consumer = sess.createConsumer(dest); + for (int i = 0; i < 15000; i++) { + consumer.receive(2000); + if (i % 100 == 0) { + System.out.println(getName() + " received message " + i); + } + } + consumer.close(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + }.start(); + } + + // Check out JConsole + System.in.read(); + sess.close(); + conn.close(); + } - public void run() { - try { - MessageConsumer consumer = sess.createConsumer(dest); - for (int i = 0; i < 15000; i++) { - consumer.receive(2000); - if (i % 100 == 0) { - System.out.println(getName() + " received message " + i); - } - } - consumer.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - }.start(); - } - - // Check out JConsole - System.in.read(); - sess.close(); - conn.close(); - } - } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCXACommitExceptionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCXACommitExceptionTest.java index 2713f9fb34..ecc07aef24 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCXACommitExceptionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/jdbc/JDBCXACommitExceptionTest.java @@ -36,124 +36,126 @@ import org.slf4j.LoggerFactory; // https://issues.apache.org/activemq/browse/AMQ-2880 public class JDBCXACommitExceptionTest extends JDBCCommitExceptionTest { - private static final Logger LOG = LoggerFactory.getLogger(JDBCXACommitExceptionTest.class); - private long txGenerator = System.currentTimeMillis(); + private static final Logger LOG = LoggerFactory.getLogger(JDBCXACommitExceptionTest.class); - protected ActiveMQXAConnectionFactory factory; + private long txGenerator = System.currentTimeMillis(); - boolean onePhase = true; + protected ActiveMQXAConnectionFactory factory; - @Override - public void setUp() throws Exception { - super.setUp(); + boolean onePhase = true; - factory = new ActiveMQXAConnectionFactory( - connectionUri + "?jms.prefetchPolicy.all=0&jms.redeliveryPolicy.maximumRedeliveries="+messagesExpected); - } + @Override + public void setUp() throws Exception { + super.setUp(); - public void testTwoPhaseSqlException() throws Exception { - onePhase = false; - doTestSqlException(); - } + factory = new ActiveMQXAConnectionFactory(connectionUri + "?jms.prefetchPolicy.all=0&jms.redeliveryPolicy.maximumRedeliveries=" + messagesExpected); + } - @Override - protected int receiveMessages(int messagesExpected) throws Exception { - XAConnection connection = factory.createXAConnection(); - connection.start(); - XASession session = connection.createXASession(); + public void testTwoPhaseSqlException() throws Exception { + onePhase = false; + doTestSqlException(); + } - jdbc.setShouldBreak(true); + @Override + protected int receiveMessages(int messagesExpected) throws Exception { + XAConnection connection = factory.createXAConnection(); + connection.start(); + XASession session = connection.createXASession(); - // first try and receive these messages, they'll continually fail - receiveMessages(messagesExpected, session, onePhase); + jdbc.setShouldBreak(true); - jdbc.setShouldBreak(false); + // first try and receive these messages, they'll continually fail + receiveMessages(messagesExpected, session, onePhase); - // now that the store is sane, try and get all the messages sent - return receiveMessages(messagesExpected, session, onePhase); - } + jdbc.setShouldBreak(false); - protected int receiveMessages(int messagesExpected, XASession session, boolean onePhase) throws Exception { - int messagesReceived = 0; + // now that the store is sane, try and get all the messages sent + return receiveMessages(messagesExpected, session, onePhase); + } - for (int i=0; i lockedSet = new HashSet(); - ExecutorService executor = Executors.newCachedThreadPool(); - executor.execute(new Runnable() { - @Override - public void run() { - try { - lockerA.start(); - lockedSet.add(lockerA); - printLockTable(connection); + final LeaseDatabaseLocker lockerB = new LeaseDatabaseLocker(); + lockerB.setLeaseHolderId("B"); + jdbc.setLocker(lockerB); + + final Set lockedSet = new HashSet(); + ExecutorService executor = Executors.newCachedThreadPool(); + executor.execute(new Runnable() { + @Override + public void run() { + try { + lockerA.start(); + lockedSet.add(lockerA); + printLockTable(connection); - } catch (Exception e) { - e.printStackTrace(); - } } - }); - - executor.execute(new Runnable() { - @Override - public void run() { - try { - lockerB.start(); - lockedSet.add(lockerB); - printLockTable(connection); - - } catch (Exception e) { - e.printStackTrace(); - } + catch (Exception e) { + e.printStackTrace(); } - }); + } + }); - // sleep for a bit till both are alive - TimeUnit.SECONDS.sleep(2); - assertTrue("no start", lockedSet.isEmpty()); - assertFalse("A is blocked", lockerA.keepAlive()); - assertFalse("B is blocked", lockerB.keepAlive()); + executor.execute(new Runnable() { + @Override + public void run() { + try { + lockerB.start(); + lockedSet.add(lockerB); + printLockTable(connection); - LOG.info("releasing phony lock " + fakeId); + } + catch (Exception e) { + e.printStackTrace(); + } + } + }); - statement = connection.prepareStatement(jdbc.getStatements().getLeaseUpdateStatement()); - statement.setString(1, null); - statement.setLong(2, 0L); - statement.setString(3, fakeId); - assertEquals("we released " + fakeId, 1, statement.executeUpdate()); - LOG.info("released " + fakeId); - printLockTable(connection); + // sleep for a bit till both are alive + TimeUnit.SECONDS.sleep(2); + assertTrue("no start", lockedSet.isEmpty()); + assertFalse("A is blocked", lockerA.keepAlive()); + assertFalse("B is blocked", lockerB.keepAlive()); - TimeUnit.MILLISECONDS.sleep(AbstractLocker.DEFAULT_LOCK_ACQUIRE_SLEEP_INTERVAL); - assertEquals("one locker started", 1, lockedSet.size()); + LOG.info("releasing phony lock " + fakeId); - assertTrue("one isAlive", lockerA.keepAlive() || lockerB.keepAlive()); + statement = connection.prepareStatement(jdbc.getStatements().getLeaseUpdateStatement()); + statement.setString(1, null); + statement.setLong(2, 0L); + statement.setString(3, fakeId); + assertEquals("we released " + fakeId, 1, statement.executeUpdate()); + LOG.info("released " + fakeId); + printLockTable(connection); - LeaseDatabaseLocker winner = lockedSet.iterator().next(); - winner.stop(); - lockedSet.remove(winner); + TimeUnit.MILLISECONDS.sleep(AbstractLocker.DEFAULT_LOCK_ACQUIRE_SLEEP_INTERVAL); + assertEquals("one locker started", 1, lockedSet.size()); - TimeUnit.MILLISECONDS.sleep(AbstractLocker.DEFAULT_LOCK_ACQUIRE_SLEEP_INTERVAL); - assertEquals("one locker started", 1, lockedSet.size()); + assertTrue("one isAlive", lockerA.keepAlive() || lockerB.keepAlive()); - lockedSet.iterator().next().stop(); - printLockTable(connection); - } + LeaseDatabaseLocker winner = lockedSet.iterator().next(); + winner.stop(); + lockedSet.remove(winner); - @Test - public void testDiffOffsetAhead() throws Exception { - LeaseDatabaseLocker underTest = new LeaseDatabaseLocker(); - assertTrue("when ahead of db adjustment is negative", callDiffOffset(underTest, System.currentTimeMillis() - 60000) < 0); - } + TimeUnit.MILLISECONDS.sleep(AbstractLocker.DEFAULT_LOCK_ACQUIRE_SLEEP_INTERVAL); + assertEquals("one locker started", 1, lockedSet.size()); - @Test - public void testDiffOffsetBehind() throws Exception { - LeaseDatabaseLocker underTest = new LeaseDatabaseLocker(); - assertTrue("when behind db adjustment is positive", callDiffOffset(underTest, System.currentTimeMillis() + 60000) > 0); - } + lockedSet.iterator().next().stop(); + printLockTable(connection); + } - @Test - public void testDiffIngoredIfLessthanMaxAllowableDiffFromDBTime() throws Exception { - LeaseDatabaseLocker underTest = new LeaseDatabaseLocker(); - underTest.setMaxAllowableDiffFromDBTime(60000); - assertEquals("no adjust when under limit", 0, callDiffOffset(underTest,System.currentTimeMillis() - 40000 )); - } + @Test + public void testDiffOffsetAhead() throws Exception { + LeaseDatabaseLocker underTest = new LeaseDatabaseLocker(); + assertTrue("when ahead of db adjustment is negative", callDiffOffset(underTest, System.currentTimeMillis() - 60000) < 0); + } - public long callDiffOffset(LeaseDatabaseLocker underTest, final long dbTime) throws Exception { + @Test + public void testDiffOffsetBehind() throws Exception { + LeaseDatabaseLocker underTest = new LeaseDatabaseLocker(); + assertTrue("when behind db adjustment is positive", callDiffOffset(underTest, System.currentTimeMillis() + 60000) > 0); + } - Mockery context = new Mockery() {{ - setImposteriser(ClassImposteriser.INSTANCE); - }}; - final Statements statements = context.mock(Statements.class); - final JDBCPersistenceAdapter jdbcPersistenceAdapter = context.mock(JDBCPersistenceAdapter.class); - final Connection connection = context.mock(Connection.class); - final PreparedStatement preparedStatement = context.mock(PreparedStatement.class); - final ResultSet resultSet = context.mock(ResultSet.class); - final Timestamp timestamp = context.mock(Timestamp.class); + @Test + public void testDiffIngoredIfLessthanMaxAllowableDiffFromDBTime() throws Exception { + LeaseDatabaseLocker underTest = new LeaseDatabaseLocker(); + underTest.setMaxAllowableDiffFromDBTime(60000); + assertEquals("no adjust when under limit", 0, callDiffOffset(underTest, System.currentTimeMillis() - 40000)); + } - context.checking(new Expectations() {{ - allowing(jdbcPersistenceAdapter).getStatements(); - will(returnValue(statements)); - allowing(jdbcPersistenceAdapter); - allowing(statements); - allowing(connection).prepareStatement(with(any(String.class))); - will(returnValue(preparedStatement)); - allowing(connection); - allowing(preparedStatement).executeQuery(); - will(returnValue(resultSet)); - allowing(resultSet).next(); - will(returnValue(true)); - allowing(resultSet).getTimestamp(1); - will(returnValue(timestamp)); - allowing(timestamp).getTime(); - will(returnValue(dbTime)); - }}); + public long callDiffOffset(LeaseDatabaseLocker underTest, final long dbTime) throws Exception { - underTest.configure(jdbcPersistenceAdapter); - underTest.setLockable(jdbcPersistenceAdapter); - return underTest.determineTimeDifference(connection); - } + Mockery context = new Mockery() {{ + setImposteriser(ClassImposteriser.INSTANCE); + }}; + final Statements statements = context.mock(Statements.class); + final JDBCPersistenceAdapter jdbcPersistenceAdapter = context.mock(JDBCPersistenceAdapter.class); + final Connection connection = context.mock(Connection.class); + final PreparedStatement preparedStatement = context.mock(PreparedStatement.class); + final ResultSet resultSet = context.mock(ResultSet.class); + final Timestamp timestamp = context.mock(Timestamp.class); - private void printLockTable(Connection connection) throws Exception { - DefaultJDBCAdapter.printQuery(connection, "SELECT * from ACTIVEMQ_LOCK", System.err); - } + context.checking(new Expectations() {{ + allowing(jdbcPersistenceAdapter).getStatements(); + will(returnValue(statements)); + allowing(jdbcPersistenceAdapter); + allowing(statements); + allowing(connection).prepareStatement(with(any(String.class))); + will(returnValue(preparedStatement)); + allowing(connection); + allowing(preparedStatement).executeQuery(); + will(returnValue(resultSet)); + allowing(resultSet).next(); + will(returnValue(true)); + allowing(resultSet).getTimestamp(1); + will(returnValue(timestamp)); + allowing(timestamp).getTime(); + will(returnValue(dbTime)); + }}); + + underTest.configure(jdbcPersistenceAdapter); + underTest.setLockable(jdbcPersistenceAdapter); + return underTest.determineTimeDifference(connection); + } + + private void printLockTable(Connection connection) throws Exception { + DefaultJDBCAdapter.printQuery(connection, "SELECT * from ACTIVEMQ_LOCK", System.err); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/CustomLockerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/CustomLockerTest.java index bc1e127b66..8136eb6074 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/CustomLockerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/CustomLockerTest.java @@ -17,15 +17,16 @@ package org.apache.activemq.store.kahadb; import junit.framework.TestCase; + import org.apache.activemq.broker.BrokerFactory; import org.apache.activemq.broker.BrokerService; public class CustomLockerTest extends TestCase { - public void testCustomLocker() throws Exception { - BrokerService broker = BrokerFactory.createBroker("xbean:org/apache/activemq/store/kahadb/shared.xml"); - broker.waitUntilStarted(); - broker.stop(); - broker.waitUntilStopped(); - } + public void testCustomLocker() throws Exception { + BrokerService broker = BrokerFactory.createBroker("xbean:org/apache/activemq/store/kahadb/shared.xml"); + broker.waitUntilStarted(); + broker.stop(); + broker.waitUntilStopped(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBFastEnqueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBFastEnqueueTest.java index 4ccb51efe6..b72fe343ba 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBFastEnqueueTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBFastEnqueueTest.java @@ -49,197 +49,201 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class KahaDBFastEnqueueTest { - private static final Logger LOG = LoggerFactory.getLogger(KahaDBFastEnqueueTest.class); - private BrokerService broker; - private ActiveMQConnectionFactory connectionFactory; - KahaDBPersistenceAdapter kahaDBPersistenceAdapter; - private final Destination destination = new ActiveMQQueue("Test"); - private final String payloadString = new String(new byte[6*1024]); - private final boolean useBytesMessage= true; - private final int parallelProducer = 20; - private final Vector exceptions = new Vector(); - long toSend = 10000; - // use with: - // -Xmx4g -Dorg.apache.kahadb.journal.appender.WRITE_STAT_WINDOW=10000 -Dorg.apache.kahadb.journal.CALLER_BUFFER_APPENDER=true - @Test - public void testPublishNoConsumer() throws Exception { + private static final Logger LOG = LoggerFactory.getLogger(KahaDBFastEnqueueTest.class); + private BrokerService broker; + private ActiveMQConnectionFactory connectionFactory; + KahaDBPersistenceAdapter kahaDBPersistenceAdapter; + private final Destination destination = new ActiveMQQueue("Test"); + private final String payloadString = new String(new byte[6 * 1024]); + private final boolean useBytesMessage = true; + private final int parallelProducer = 20; + private final Vector exceptions = new Vector(); + long toSend = 10000; - startBroker(true, 10); + // use with: + // -Xmx4g -Dorg.apache.kahadb.journal.appender.WRITE_STAT_WINDOW=10000 -Dorg.apache.kahadb.journal.CALLER_BUFFER_APPENDER=true + @Test + public void testPublishNoConsumer() throws Exception { - final AtomicLong sharedCount = new AtomicLong(toSend); - long start = System.currentTimeMillis(); - ExecutorService executorService = Executors.newCachedThreadPool(); - for (int i=0; i< parallelProducer; i++) { - executorService.execute(new Runnable() { - @Override - public void run() { - try { - publishMessages(sharedCount, 0); - } catch (Exception e) { - exceptions.add(e); - } - } - }); - } - executorService.shutdown(); - executorService.awaitTermination(30, TimeUnit.MINUTES); - assertTrue("Producers done in time", executorService.isTerminated()); - assertTrue("No exceptions: " + exceptions, exceptions.isEmpty()); - long totalSent = toSend * payloadString.length(); + startBroker(true, 10); - double duration = System.currentTimeMillis() - start; - stopBroker(); - LOG.info("Duration: " + duration + "ms"); - LOG.info("Rate: " + (toSend * 1000/duration) + "m/s"); - LOG.info("Total send: " + totalSent); - LOG.info("Total journal write: " + kahaDBPersistenceAdapter.getStore().getJournal().length()); - LOG.info("Total index size " + kahaDBPersistenceAdapter.getStore().getPageFile().getDiskSize()); - LOG.info("Total store size: " + kahaDBPersistenceAdapter.size()); - LOG.info("Journal writes %: " + kahaDBPersistenceAdapter.getStore().getJournal().length() / (double)totalSent * 100 + "%"); - - restartBroker(0, 1200000); - consumeMessages(toSend); - } - - @Test - public void testPublishNoConsumerNoCheckpoint() throws Exception { - - toSend = 100; - startBroker(true, 0); - - final AtomicLong sharedCount = new AtomicLong(toSend); - long start = System.currentTimeMillis(); - ExecutorService executorService = Executors.newCachedThreadPool(); - for (int i=0; i< parallelProducer; i++) { - executorService.execute(new Runnable() { - @Override - public void run() { - try { - publishMessages(sharedCount, 0); - } catch (Exception e) { - exceptions.add(e); - } - } - }); - } - executorService.shutdown(); - executorService.awaitTermination(30, TimeUnit.MINUTES); - assertTrue("Producers done in time", executorService.isTerminated()); - assertTrue("No exceptions: " + exceptions, exceptions.isEmpty()); - long totalSent = toSend * payloadString.length(); - - broker.getAdminView().gc(); - - - double duration = System.currentTimeMillis() - start; - stopBroker(); - LOG.info("Duration: " + duration + "ms"); - LOG.info("Rate: " + (toSend * 1000/duration) + "m/s"); - LOG.info("Total send: " + totalSent); - LOG.info("Total journal write: " + kahaDBPersistenceAdapter.getStore().getJournal().length()); - LOG.info("Total index size " + kahaDBPersistenceAdapter.getStore().getPageFile().getDiskSize()); - LOG.info("Total store size: " + kahaDBPersistenceAdapter.size()); - LOG.info("Journal writes %: " + kahaDBPersistenceAdapter.getStore().getJournal().length() / (double)totalSent * 100 + "%"); - - restartBroker(0, 0); - consumeMessages(toSend); - } - - private void consumeMessages(long count) throws Exception { - ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.setWatchTopicAdvisories(false); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); - for (int i=0; i 0) { - Message message = null; - if (useBytesMessage) { - message = session.createBytesMessage(); - ((BytesMessage) message).writeBytes(payloadString.getBytes()); - } else { - message = session.createTextMessage(payloadString); + final AtomicLong sharedCount = new AtomicLong(toSend); + long start = System.currentTimeMillis(); + ExecutorService executorService = Executors.newCachedThreadPool(); + for (int i = 0; i < parallelProducer; i++) { + executorService.execute(new Runnable() { + @Override + public void run() { + try { + publishMessages(sharedCount, 0); + } + catch (Exception e) { + exceptions.add(e); + } } - producer.send(message, DeliveryMode.PERSISTENT, 5, expiry); - if (i != toSend && i%sampleRate == 0) { - long now = System.currentTimeMillis(); - LOG.info("Remainder: " + i + ", rate: " + sampleRate * 1000 / (now - start) + "m/s" ); - start = now; + }); + } + executorService.shutdown(); + executorService.awaitTermination(30, TimeUnit.MINUTES); + assertTrue("Producers done in time", executorService.isTerminated()); + assertTrue("No exceptions: " + exceptions, exceptions.isEmpty()); + long totalSent = toSend * payloadString.length(); + + double duration = System.currentTimeMillis() - start; + stopBroker(); + LOG.info("Duration: " + duration + "ms"); + LOG.info("Rate: " + (toSend * 1000 / duration) + "m/s"); + LOG.info("Total send: " + totalSent); + LOG.info("Total journal write: " + kahaDBPersistenceAdapter.getStore().getJournal().length()); + LOG.info("Total index size " + kahaDBPersistenceAdapter.getStore().getPageFile().getDiskSize()); + LOG.info("Total store size: " + kahaDBPersistenceAdapter.size()); + LOG.info("Journal writes %: " + kahaDBPersistenceAdapter.getStore().getJournal().length() / (double) totalSent * 100 + "%"); + + restartBroker(0, 1200000); + consumeMessages(toSend); + } + + @Test + public void testPublishNoConsumerNoCheckpoint() throws Exception { + + toSend = 100; + startBroker(true, 0); + + final AtomicLong sharedCount = new AtomicLong(toSend); + long start = System.currentTimeMillis(); + ExecutorService executorService = Executors.newCachedThreadPool(); + for (int i = 0; i < parallelProducer; i++) { + executorService.execute(new Runnable() { + @Override + public void run() { + try { + publishMessages(sharedCount, 0); + } + catch (Exception e) { + exceptions.add(e); + } } - } - connection.syncSendPacket(new ConnectionControl()); - connection.close(); - } + }); + } + executorService.shutdown(); + executorService.awaitTermination(30, TimeUnit.MINUTES); + assertTrue("Producers done in time", executorService.isTerminated()); + assertTrue("No exceptions: " + exceptions, exceptions.isEmpty()); + long totalSent = toSend * payloadString.length(); - public void startBroker(boolean deleteAllMessages, int checkPointPeriod) throws Exception { - broker = new BrokerService(); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - kahaDBPersistenceAdapter = (KahaDBPersistenceAdapter)broker.getPersistenceAdapter(); - kahaDBPersistenceAdapter.setEnableJournalDiskSyncs(false); - // defer checkpoints which require a sync - kahaDBPersistenceAdapter.setCleanupInterval(checkPointPeriod); - kahaDBPersistenceAdapter.setCheckpointInterval(checkPointPeriod); + broker.getAdminView().gc(); - // optimise for disk best batch rate - kahaDBPersistenceAdapter.setJournalMaxWriteBatchSize(24*1024*1024); //4mb default - kahaDBPersistenceAdapter.setJournalMaxFileLength(128*1024*1024); // 32mb default - // keep index in memory - kahaDBPersistenceAdapter.setIndexCacheSize(500000); - kahaDBPersistenceAdapter.setIndexWriteBatchSize(500000); - kahaDBPersistenceAdapter.setEnableIndexRecoveryFile(false); - kahaDBPersistenceAdapter.setEnableIndexDiskSyncs(false); + double duration = System.currentTimeMillis() - start; + stopBroker(); + LOG.info("Duration: " + duration + "ms"); + LOG.info("Rate: " + (toSend * 1000 / duration) + "m/s"); + LOG.info("Total send: " + totalSent); + LOG.info("Total journal write: " + kahaDBPersistenceAdapter.getStore().getJournal().length()); + LOG.info("Total index size " + kahaDBPersistenceAdapter.getStore().getPageFile().getDiskSize()); + LOG.info("Total store size: " + kahaDBPersistenceAdapter.size()); + LOG.info("Journal writes %: " + kahaDBPersistenceAdapter.getStore().getJournal().length() / (double) totalSent * 100 + "%"); - broker.addConnector("tcp://0.0.0.0:0"); - broker.start(); + restartBroker(0, 0); + consumeMessages(toSend); + } - String options = "?jms.watchTopicAdvisories=false&jms.useAsyncSend=true&jms.alwaysSessionAsync=false&jms.dispatchAsync=false&socketBufferSize=131072&ioBufferSize=16384&wireFormat.tightEncodingEnabled=false&wireFormat.cacheSize=8192"; - connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri() + options); - } + private void consumeMessages(long count) throws Exception { + ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.setWatchTopicAdvisories(false); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(destination); + for (int i = 0; i < count; i++) { + assertNotNull("got message " + i, consumer.receive(10000)); + } + assertNull("none left over", consumer.receive(2000)); + } - @Test - public void testRollover() throws Exception { - byte flip = 0x1; - for (long i=0; i 0) { + Message message = null; + if (useBytesMessage) { + message = session.createBytesMessage(); + ((BytesMessage) message).writeBytes(payloadString.getBytes()); + } + else { + message = session.createTextMessage(payloadString); + } + producer.send(message, DeliveryMode.PERSISTENT, 5, expiry); + if (i != toSend && i % sampleRate == 0) { + long now = System.currentTimeMillis(); + LOG.info("Remainder: " + i + ", rate: " + sampleRate * 1000 / (now - start) + "m/s"); + start = now; + } + } + connection.syncSendPacket(new ConnectionControl()); + connection.close(); + } + + public void startBroker(boolean deleteAllMessages, int checkPointPeriod) throws Exception { + broker = new BrokerService(); + broker.setDeleteAllMessagesOnStartup(deleteAllMessages); + kahaDBPersistenceAdapter = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); + kahaDBPersistenceAdapter.setEnableJournalDiskSyncs(false); + // defer checkpoints which require a sync + kahaDBPersistenceAdapter.setCleanupInterval(checkPointPeriod); + kahaDBPersistenceAdapter.setCheckpointInterval(checkPointPeriod); + + // optimise for disk best batch rate + kahaDBPersistenceAdapter.setJournalMaxWriteBatchSize(24 * 1024 * 1024); //4mb default + kahaDBPersistenceAdapter.setJournalMaxFileLength(128 * 1024 * 1024); // 32mb default + // keep index in memory + kahaDBPersistenceAdapter.setIndexCacheSize(500000); + kahaDBPersistenceAdapter.setIndexWriteBatchSize(500000); + kahaDBPersistenceAdapter.setEnableIndexRecoveryFile(false); + kahaDBPersistenceAdapter.setEnableIndexDiskSyncs(false); + + broker.addConnector("tcp://0.0.0.0:0"); + broker.start(); + + String options = "?jms.watchTopicAdvisories=false&jms.useAsyncSend=true&jms.alwaysSessionAsync=false&jms.dispatchAsync=false&socketBufferSize=131072&ioBufferSize=16384&wireFormat.tightEncodingEnabled=false&wireFormat.cacheSize=8192"; + connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri() + options); + } + + @Test + public void testRollover() throws Exception { + byte flip = 0x1; + for (long i = 0; i < Short.MAX_VALUE; i++) { + assertEquals("0 @:" + i, 0, flip ^= (byte) 1); + assertEquals("1 @:" + i, 1, flip ^= (byte) 1); + } + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBIndexLocationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBIndexLocationTest.java index 4a2333191d..24229c9291 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBIndexLocationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBIndexLocationTest.java @@ -45,121 +45,122 @@ import org.slf4j.LoggerFactory; */ public class KahaDBIndexLocationTest { - private static final Logger LOG = LoggerFactory.getLogger(KahaDBIndexLocationTest.class); + private static final Logger LOG = LoggerFactory.getLogger(KahaDBIndexLocationTest.class); - @Rule public TestName name = new TestName(); + @Rule + public TestName name = new TestName(); - private BrokerService broker; + private BrokerService broker; - private final File testDataDir = new File("target/activemq-data/QueuePurgeTest"); - private final File kahaDataDir = new File(testDataDir, "kahadb"); - private final File kahaIndexDir = new File(testDataDir, "kahadb/index"); + private final File testDataDir = new File("target/activemq-data/QueuePurgeTest"); + private final File kahaDataDir = new File(testDataDir, "kahadb"); + private final File kahaIndexDir = new File(testDataDir, "kahadb/index"); - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - startBroker(); - } + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + startBroker(); + } - @After - public void tearDown() throws Exception { - stopBroker(); - } + @After + public void tearDown() throws Exception { + stopBroker(); + } - private void startBroker() throws Exception { - createBroker(); - broker.start(); - broker.waitUntilStarted(); - } + private void startBroker() throws Exception { + createBroker(); + broker.start(); + broker.waitUntilStarted(); + } - private void stopBroker() throws Exception { - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - } + private void stopBroker() throws Exception { + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + } - private void restartBroker() throws Exception { - stopBroker(); - createBroker(); - broker.start(); - broker.waitUntilStarted(); - } + private void restartBroker() throws Exception { + stopBroker(); + createBroker(); + broker.start(); + broker.waitUntilStarted(); + } - private void createBroker() throws Exception { - broker = new BrokerService(); + private void createBroker() throws Exception { + broker = new BrokerService(); - KahaDBPersistenceAdapter persistenceAdapter = new KahaDBPersistenceAdapter(); - persistenceAdapter.setDirectory(kahaDataDir); - persistenceAdapter.setIndexDirectory(kahaIndexDir); + KahaDBPersistenceAdapter persistenceAdapter = new KahaDBPersistenceAdapter(); + persistenceAdapter.setDirectory(kahaDataDir); + persistenceAdapter.setIndexDirectory(kahaIndexDir); - broker.setDataDirectoryFile(testDataDir); - broker.setUseJmx(false); - broker.setAdvisorySupport(false); - broker.setSchedulerSupport(false); - broker.setDeleteAllMessagesOnStartup(true); - broker.setPersistenceAdapter(persistenceAdapter); - } + broker.setDataDirectoryFile(testDataDir); + broker.setUseJmx(false); + broker.setAdvisorySupport(false); + broker.setSchedulerSupport(false); + broker.setDeleteAllMessagesOnStartup(true); + broker.setPersistenceAdapter(persistenceAdapter); + } - @Test - public void testIndexDirExists() throws Exception { - LOG.info("Index dir is configured as: {}", kahaIndexDir); - assertTrue(kahaDataDir.exists()); - assertTrue(kahaIndexDir.exists()); + @Test + public void testIndexDirExists() throws Exception { + LOG.info("Index dir is configured as: {}", kahaIndexDir); + assertTrue(kahaDataDir.exists()); + assertTrue(kahaIndexDir.exists()); - String[] index = kahaIndexDir.list(new FilenameFilter() { + String[] index = kahaIndexDir.list(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - LOG.info("Testing filename: {}", name); - return name.endsWith("data") || name.endsWith("redo"); - } - }); + @Override + public boolean accept(File dir, String name) { + LOG.info("Testing filename: {}", name); + return name.endsWith("data") || name.endsWith("redo"); + } + }); - String[] journal = kahaDataDir.list(new FilenameFilter() { + String[] journal = kahaDataDir.list(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - LOG.info("Testing filename: {}", name); - return name.endsWith("log") || name.equals("lock"); - } - }); + @Override + public boolean accept(File dir, String name) { + LOG.info("Testing filename: {}", name); + return name.endsWith("log") || name.equals("lock"); + } + }); - produceMessages(); + produceMessages(); - // Should be db.data and db.redo and nothing else. - assertNotNull(index); - assertEquals(2, index.length); + // Should be db.data and db.redo and nothing else. + assertNotNull(index); + assertEquals(2, index.length); - // Should contain the initial log for the journal and the lock. - assertNotNull(journal); - assertEquals(2, journal.length); - } + // Should contain the initial log for the journal and the lock. + assertNotNull(journal); + assertEquals(2, journal.length); + } - @Test - public void testRestartWithDeleteWorksWhenIndexIsSeparate() throws Exception { - produceMessages(); - restartBroker(); + @Test + public void testRestartWithDeleteWorksWhenIndexIsSeparate() throws Exception { + produceMessages(); + restartBroker(); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost?create=false"); - Connection connection = cf.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createQueue(name.getMethodName()); - MessageConsumer consumer = session.createConsumer(queue); - assertNull(consumer.receive(2000)); - } + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost?create=false"); + Connection connection = cf.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = session.createQueue(name.getMethodName()); + MessageConsumer consumer = session.createConsumer(queue); + assertNull(consumer.receive(2000)); + } - private void produceMessages() throws Exception { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost?create=false"); - Connection connection = cf.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createQueue(name.getMethodName()); - MessageProducer producer = session.createProducer(queue); - for (int i = 0; i < 5; ++i) { - producer.send(session.createTextMessage("test:" + i)); - } - connection.close(); - } + private void produceMessages() throws Exception { + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost?create=false"); + Connection connection = cf.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = session.createQueue(name.getMethodName()); + MessageProducer producer = session.createProducer(queue); + for (int i = 0; i < 5; ++i) { + producer.send(session.createTextMessage("test:" + i)); + } + connection.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBMessagePriorityTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBMessagePriorityTest.java index 438b8c0f96..bb0e9547b7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBMessagePriorityTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBMessagePriorityTest.java @@ -18,23 +18,24 @@ package org.apache.activemq.store.kahadb; import junit.framework.Test; + import org.apache.activemq.store.MessagePriorityTest; import org.apache.activemq.store.PersistenceAdapter; import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; public class KahaDBMessagePriorityTest extends MessagePriorityTest { - @Override - protected PersistenceAdapter createPersistenceAdapter(boolean delete) throws Exception { - KahaDBPersistenceAdapter adapter = new KahaDBPersistenceAdapter(); - adapter.setConcurrentStoreAndDispatchQueues(false); - adapter.setConcurrentStoreAndDispatchTopics(false); - adapter.deleteAllMessages(); - return adapter; - } - - public static Test suite() { - return suite(KahaDBMessagePriorityTest.class); - } + @Override + protected PersistenceAdapter createPersistenceAdapter(boolean delete) throws Exception { + KahaDBPersistenceAdapter adapter = new KahaDBPersistenceAdapter(); + adapter.setConcurrentStoreAndDispatchQueues(false); + adapter.setConcurrentStoreAndDispatchTopics(false); + adapter.deleteAllMessages(); + return adapter; + } + + public static Test suite() { + return suite(KahaDBMessagePriorityTest.class); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBPersistenceAdapterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBPersistenceAdapterTest.java index c45c3e5a42..9a3114ea3a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBPersistenceAdapterTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBPersistenceAdapterTest.java @@ -23,17 +23,16 @@ import org.apache.activemq.store.PersistenceAdapter; import org.apache.activemq.store.PersistenceAdapterTestSupport; /** - * * @author Hiram Chirino */ public class KahaDBPersistenceAdapterTest extends PersistenceAdapterTestSupport { - - protected PersistenceAdapter createPersistenceAdapter(boolean delete) throws IOException { - KahaDBStore kaha = new KahaDBStore(); - kaha.setDirectory(new File("target/activemq-data/kahadb")); - if (delete) { - kaha.deleteAllMessages(); - } - return kaha; - } + + protected PersistenceAdapter createPersistenceAdapter(boolean delete) throws IOException { + KahaDBStore kaha = new KahaDBStore(); + kaha.setDirectory(new File("target/activemq-data/kahadb")); + if (delete) { + kaha.deleteAllMessages(); + } + return kaha; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBStoreBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBStoreBrokerTest.java index 2152501606..4409d69e5e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBStoreBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBStoreBrokerTest.java @@ -26,42 +26,39 @@ import org.apache.activemq.util.IOHelper; /** * Once the wire format is completed we can test against real persistence storage. - * - * */ public class KahaDBStoreBrokerTest extends BrokerTest { - protected void setUp() throws Exception { - this.setAutoFail(true); - super.setUp(); - } - - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - KahaDBStore kaha = new KahaDBStore(); - File directory = new File("target/activemq-data/kahadb"); - IOHelper.deleteChildren(directory); - kaha.setDirectory(directory); - kaha.deleteAllMessages(); - broker.setPersistenceAdapter(kaha); - return broker; - } - - protected BrokerService createRestartedBroker() throws Exception { - BrokerService broker = new BrokerService(); - KahaDBStore kaha = new KahaDBStore(); - kaha.setDirectory(new File("target/activemq-data/kahadb")); - broker.setPersistenceAdapter(kaha); - return broker; - } - - - public static Test suite() { - return suite(KahaDBStoreBrokerTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + protected void setUp() throws Exception { + this.setAutoFail(true); + super.setUp(); + } + + protected BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); + KahaDBStore kaha = new KahaDBStore(); + File directory = new File("target/activemq-data/kahadb"); + IOHelper.deleteChildren(directory); + kaha.setDirectory(directory); + kaha.deleteAllMessages(); + broker.setPersistenceAdapter(kaha); + return broker; + } + + protected BrokerService createRestartedBroker() throws Exception { + BrokerService broker = new BrokerService(); + KahaDBStore kaha = new KahaDBStore(); + kaha.setDirectory(new File("target/activemq-data/kahadb")); + broker.setPersistenceAdapter(kaha); + return broker; + } + + public static Test suite() { + return suite(KahaDBStoreBrokerTest.class); + } + + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBStoreOrderTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBStoreOrderTest.java index 8cace613df..e672890a89 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBStoreOrderTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBStoreOrderTest.java @@ -23,13 +23,12 @@ import org.apache.activemq.store.StoreOrderTest; // https://issues.apache.org/activemq/browse/AMQ-2594 public class KahaDBStoreOrderTest extends StoreOrderTest { - - @Override - protected void setPersistentAdapter(BrokerService brokerService) - throws Exception { - KahaDBStore kaha = new KahaDBStore(); - File directory = new File("target/activemq-data/kahadb/storeOrder"); - kaha.setDirectory(directory); - brokerService.setPersistenceAdapter(kaha); - } + + @Override + protected void setPersistentAdapter(BrokerService brokerService) throws Exception { + KahaDBStore kaha = new KahaDBStore(); + File directory = new File("target/activemq-data/kahadb/storeOrder"); + kaha.setDirectory(directory); + brokerService.setPersistenceAdapter(kaha); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBStoreRecoveryBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBStoreRecoveryBrokerTest.java index 3725572b10..b815fe5301 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBStoreRecoveryBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBStoreRecoveryBrokerTest.java @@ -36,178 +36,178 @@ import org.apache.activemq.command.ProducerInfo; import org.apache.activemq.command.SessionInfo; import org.apache.commons.io.FileUtils; - /** * Used to verify that recovery works correctly against - * - * */ public class KahaDBStoreRecoveryBrokerTest extends RecoveryBrokerTest { - public static final String KAHADB_DIR_BASE = "target/activemq-data/kahadb"; - public static String kahaDbDirectoryName; - enum CorruptionType { None, FailToLoad, LoadInvalid, LoadCorrupt, LoadOrderIndex0 }; - public CorruptionType failTest = CorruptionType.None; + public static final String KAHADB_DIR_BASE = "target/activemq-data/kahadb"; + public static String kahaDbDirectoryName; - @Override - protected void setUp() throws Exception { - kahaDbDirectoryName = KAHADB_DIR_BASE + "/" + System.currentTimeMillis(); - super.setUp(); - } + enum CorruptionType {None, FailToLoad, LoadInvalid, LoadCorrupt, LoadOrderIndex0} - @Override - protected void tearDown() throws Exception { - super.tearDown(); - try { - File kahaDbDir = new File(kahaDbDirectoryName); - FileUtils.deleteDirectory(kahaDbDir); - } catch (IOException e) { - } - } + ; + public CorruptionType failTest = CorruptionType.None; - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - KahaDBStore kaha = new KahaDBStore(); - kaha.setDirectory(new File(kahaDbDirectoryName)); - kaha.deleteAllMessages(); - kaha.setCheckForCorruptJournalFiles(failTest == CorruptionType.LoadOrderIndex0); - broker.setPersistenceAdapter(kaha); - return broker; - } + @Override + protected void setUp() throws Exception { + kahaDbDirectoryName = KAHADB_DIR_BASE + "/" + System.currentTimeMillis(); + super.setUp(); + } - @Override - @SuppressWarnings("resource") - protected BrokerService createRestartedBroker() throws Exception { + @Override + protected void tearDown() throws Exception { + super.tearDown(); + try { + File kahaDbDir = new File(kahaDbDirectoryName); + FileUtils.deleteDirectory(kahaDbDir); + } + catch (IOException e) { + } + } - // corrupting index - File index = new File(kahaDbDirectoryName + "/db.data"); - RandomAccessFile raf = new RandomAccessFile(index, "rw"); - switch (failTest) { - case FailToLoad: - index.delete(); - raf = new RandomAccessFile(index, "rw"); - raf.seek(index.length()); - raf.writeBytes("corrupt"); - break; - case LoadInvalid: - // page size 0 - raf.seek(0); - raf.writeBytes("corrupt and cannot load metadata"); - break; - case LoadCorrupt: - // loadable but invalid metadata - // location of order index low priority index for first destination... - raf.seek(8*1024 + 57); - raf.writeLong(Integer.MAX_VALUE-10); - break; - case LoadOrderIndex0: - // loadable but invalid metadata - // location of order index default priority index size - // so looks like there are no ids in the order index - // picked up by setCheckForCorruptJournalFiles - raf.seek(12*1024 + 21); - raf.writeShort(0); - raf.writeChar(0); - raf.writeLong(-1); - break; - default: - } - raf.close(); + @Override + protected BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); + KahaDBStore kaha = new KahaDBStore(); + kaha.setDirectory(new File(kahaDbDirectoryName)); + kaha.deleteAllMessages(); + kaha.setCheckForCorruptJournalFiles(failTest == CorruptionType.LoadOrderIndex0); + broker.setPersistenceAdapter(kaha); + return broker; + } - // starting broker - BrokerService broker = new BrokerService(); - KahaDBStore kaha = new KahaDBStore(); - kaha.setCheckForCorruptJournalFiles(failTest == CorruptionType.LoadOrderIndex0); - // uncomment if you want to test archiving - //kaha.setArchiveCorruptedIndex(true); - kaha.setDirectory(new File(kahaDbDirectoryName)); - broker.setPersistenceAdapter(kaha); - return broker; - } + @Override + @SuppressWarnings("resource") + protected BrokerService createRestartedBroker() throws Exception { - public static Test suite() { - return suite(KahaDBStoreRecoveryBrokerTest.class); - } + // corrupting index + File index = new File(kahaDbDirectoryName + "/db.data"); + RandomAccessFile raf = new RandomAccessFile(index, "rw"); + switch (failTest) { + case FailToLoad: + index.delete(); + raf = new RandomAccessFile(index, "rw"); + raf.seek(index.length()); + raf.writeBytes("corrupt"); + break; + case LoadInvalid: + // page size 0 + raf.seek(0); + raf.writeBytes("corrupt and cannot load metadata"); + break; + case LoadCorrupt: + // loadable but invalid metadata + // location of order index low priority index for first destination... + raf.seek(8 * 1024 + 57); + raf.writeLong(Integer.MAX_VALUE - 10); + break; + case LoadOrderIndex0: + // loadable but invalid metadata + // location of order index default priority index size + // so looks like there are no ids in the order index + // picked up by setCheckForCorruptJournalFiles + raf.seek(12 * 1024 + 21); + raf.writeShort(0); + raf.writeChar(0); + raf.writeLong(-1); + break; + default: + } + raf.close(); - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + // starting broker + BrokerService broker = new BrokerService(); + KahaDBStore kaha = new KahaDBStore(); + kaha.setCheckForCorruptJournalFiles(failTest == CorruptionType.LoadOrderIndex0); + // uncomment if you want to test archiving + //kaha.setArchiveCorruptedIndex(true); + kaha.setDirectory(new File(kahaDbDirectoryName)); + broker.setPersistenceAdapter(kaha); + return broker; + } - public void initCombosForTestLargeQueuePersistentMessagesNotLostOnRestart() { - this.addCombinationValues("failTest", new CorruptionType[]{CorruptionType.FailToLoad, CorruptionType.LoadInvalid, CorruptionType.LoadCorrupt, CorruptionType.LoadOrderIndex0} ); - } + public static Test suite() { + return suite(KahaDBStoreRecoveryBrokerTest.class); + } - public void testLargeQueuePersistentMessagesNotLostOnRestart() throws Exception { + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - ActiveMQDestination destination = new ActiveMQQueue("TEST"); + public void initCombosForTestLargeQueuePersistentMessagesNotLostOnRestart() { + this.addCombinationValues("failTest", new CorruptionType[]{CorruptionType.FailToLoad, CorruptionType.LoadInvalid, CorruptionType.LoadCorrupt, CorruptionType.LoadOrderIndex0}); + } - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); + public void testLargeQueuePersistentMessagesNotLostOnRestart() throws Exception { - ArrayList expected = new ArrayList(); + ActiveMQDestination destination = new ActiveMQQueue("TEST"); - int MESSAGE_COUNT = 10000; - for(int i=0; i < MESSAGE_COUNT; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - expected.add(message.getMessageId().toString()); - } - connection.request(closeConnectionInfo(connectionInfo)); + // Setup the producer and send the message. + StubConnection connection = createConnection(); + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); - // restart the broker. - restartBroker(); + ArrayList expected = new ArrayList(); - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - producerInfo = createProducerInfo(sessionInfo); - connection.send(producerInfo); + int MESSAGE_COUNT = 10000; + for (int i = 0; i < MESSAGE_COUNT; i++) { + Message message = createMessage(producerInfo, destination); + message.setPersistent(true); + connection.send(message); + expected.add(message.getMessageId().toString()); + } + connection.request(closeConnectionInfo(connectionInfo)); - for(int i=0; i < MESSAGE_COUNT/2; i++) { - Message m = receiveMessage(connection); - assertNotNull("Should have received message "+expected.get(0)+" by now!", m); - assertEquals(expected.remove(0), m.getMessageId().toString()); - MessageAck ack = createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE); - connection.send(ack); - } + // restart the broker. + restartBroker(); - connection.request(closeConnectionInfo(connectionInfo)); + // Setup the consumer and receive the message. + connection = createConnection(); + connectionInfo = createConnectionInfo(); + sessionInfo = createSessionInfo(connectionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); + producerInfo = createProducerInfo(sessionInfo); + connection.send(producerInfo); - // restart the broker. - restartBroker(); + for (int i = 0; i < MESSAGE_COUNT / 2; i++) { + Message m = receiveMessage(connection); + assertNotNull("Should have received message " + expected.get(0) + " by now!", m); + assertEquals(expected.remove(0), m.getMessageId().toString()); + MessageAck ack = createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE); + connection.send(ack); + } - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); + connection.request(closeConnectionInfo(connectionInfo)); - for(int i=0; i < MESSAGE_COUNT/2; i++) { - Message m = receiveMessage(connection); - assertNotNull("Should have received message "+expected.get(i)+" by now!", m); - assertEquals(expected.get(i), m.getMessageId().toString()); - MessageAck ack = createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE); - connection.send(ack); + // restart the broker. + restartBroker(); + // Setup the consumer and receive the message. + connection = createConnection(); + connectionInfo = createConnectionInfo(); + sessionInfo = createSessionInfo(connectionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + consumerInfo = createConsumerInfo(sessionInfo, destination); + connection.send(consumerInfo); - } + for (int i = 0; i < MESSAGE_COUNT / 2; i++) { + Message m = receiveMessage(connection); + assertNotNull("Should have received message " + expected.get(i) + " by now!", m); + assertEquals(expected.get(i), m.getMessageId().toString()); + MessageAck ack = createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE); + connection.send(ack); - connection.request(closeConnectionInfo(connectionInfo)); - } + } + + connection.request(closeConnectionInfo(connectionInfo)); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBStoreRecoveryExpiryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBStoreRecoveryExpiryTest.java index 754cf1aff6..6ed40008c9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBStoreRecoveryExpiryTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBStoreRecoveryExpiryTest.java @@ -42,72 +42,72 @@ import org.junit.Test; public class KahaDBStoreRecoveryExpiryTest { - private BrokerService broker; - private ActiveMQConnection connection; - private final Destination destination = new ActiveMQQueue("Test"); - private Session session; + private BrokerService broker; + private ActiveMQConnection connection; + private final Destination destination = new ActiveMQQueue("Test"); + private Session session; - @Test - public void testRestartWitExpired() throws Exception { - publishMessages(1, 0); - publishMessages(1, 2000); - publishMessages(1, 0); - restartBroker(3000); - consumeMessages(2); - } + @Test + public void testRestartWitExpired() throws Exception { + publishMessages(1, 0); + publishMessages(1, 2000); + publishMessages(1, 0); + restartBroker(3000); + consumeMessages(2); + } - @Test - public void testRestartWitExpiredLargerThanBatchRecovery() throws Exception { - publishMessages(BaseDestination.MAX_PAGE_SIZE + 10, 2000); - publishMessages(10, 0); - restartBroker(3000); - consumeMessages(10); - } + @Test + public void testRestartWitExpiredLargerThanBatchRecovery() throws Exception { + publishMessages(BaseDestination.MAX_PAGE_SIZE + 10, 2000); + publishMessages(10, 0); + restartBroker(3000); + consumeMessages(10); + } - private void consumeMessages(int count) throws Exception { - MessageConsumer consumer = session.createConsumer(destination); - for (int i=0; i exceptions = new Vector(); + KahaDBStore.KahaDBMessageStore underTest; + KahaDBStore store; + ActiveMQMessage message; + ProducerId producerId = new ProducerId("1.1.1"); + private static final int MESSAGE_COUNT = 2000; + private Vector exceptions = new Vector(); - @Before - public void initStore() throws Exception { - ActiveMQDestination destination = new ActiveMQQueue("Test"); - store = new KahaDBStore(); - store.setMaxAsyncJobs(100); - store.setDeleteAllMessages(true); - store.start(); - underTest = store.new KahaDBMessageStore(destination); - underTest.start(); - message = new ActiveMQMessage(); - message.setDestination(destination); - } + @Before + public void initStore() throws Exception { + ActiveMQDestination destination = new ActiveMQQueue("Test"); + store = new KahaDBStore(); + store.setMaxAsyncJobs(100); + store.setDeleteAllMessages(true); + store.start(); + underTest = store.new KahaDBMessageStore(destination); + underTest.start(); + message = new ActiveMQMessage(); + message.setDestination(destination); + } - @After - public void destroyStore() throws Exception { - if (store != null) { - store.stop(); - } - } + @After + public void destroyStore() throws Exception { + if (store != null) { + store.stop(); + } + } - @Test - public void testConcurrentStoreAndDispatchQueue() throws Exception { + @Test + public void testConcurrentStoreAndDispatchQueue() throws Exception { - ExecutorService executor = Executors.newCachedThreadPool(); - for (int i=0; i 800); + assertTrue(count < 1000); - // We know we won't get all the messages but we should get most of them. - int count = receiveMessages(); - assertTrue( count > 800 ); - assertTrue( count < 1000 ); + broker.stop(); + } - broker.stop(); - } + public void testCheckCorruptionNotIgnored() throws Exception { + KahaDBStore kaha = createStore(true); + assertTrue(kaha.isChecksumJournalFiles()); + assertFalse(kaha.isCheckForCorruptJournalFiles()); + kaha.setJournalMaxFileLength(1024 * 100); + kaha.setChecksumJournalFiles(true); + BrokerService broker = createBroker(kaha); + sendMessages(1000); + broker.stop(); - public void testCheckCorruptionNotIgnored() throws Exception { - KahaDBStore kaha = createStore(true); - assertTrue(kaha.isChecksumJournalFiles()); - assertFalse(kaha.isCheckForCorruptJournalFiles()); + // Modify/Corrupt some journal files.. + assertExistsAndCorrupt(new File(kaha.getDirectory(), "db-4.log")); + assertExistsAndCorrupt(new File(kaha.getDirectory(), "db-8.log")); - kaha.setJournalMaxFileLength(1024*100); - kaha.setChecksumJournalFiles(true); - BrokerService broker = createBroker(kaha); - sendMessages(1000); - broker.stop(); + kaha = createStore(false); + kaha.setJournalMaxFileLength(1024 * 100); + kaha.setChecksumJournalFiles(true); + kaha.setCheckForCorruptJournalFiles(true); + assertFalse(kaha.isIgnoreMissingJournalfiles()); + try { + broker = createBroker(kaha); + fail("expected IOException"); + } + catch (IOException e) { + assertTrue(e.getMessage().startsWith("Detected missing/corrupt journal files")); + } - // Modify/Corrupt some journal files.. - assertExistsAndCorrupt(new File(kaha.getDirectory(), "db-4.log")); - assertExistsAndCorrupt(new File(kaha.getDirectory(), "db-8.log")); + } - kaha = createStore(false); - kaha.setJournalMaxFileLength(1024*100); - kaha.setChecksumJournalFiles(true); - kaha.setCheckForCorruptJournalFiles(true); - assertFalse(kaha.isIgnoreMissingJournalfiles()); - try { - broker = createBroker(kaha); - fail("expected IOException"); - } catch (IOException e) { - assertTrue( e.getMessage().startsWith("Detected missing/corrupt journal files") ); - } + public void testMigrationOnNewDefaultForChecksumJournalFiles() throws Exception { + KahaDBStore kaha = createStore(true); + kaha.setChecksumJournalFiles(false); + assertFalse(kaha.isChecksumJournalFiles()); + assertFalse(kaha.isCheckForCorruptJournalFiles()); - } + kaha.setJournalMaxFileLength(1024 * 100); + BrokerService broker = createBroker(kaha); + sendMessages(1000); + broker.stop(); + kaha = createStore(false); + kaha.setJournalMaxFileLength(1024 * 100); + kaha.setCheckForCorruptJournalFiles(true); + assertFalse(kaha.isIgnoreMissingJournalfiles()); + createBroker(kaha); + assertEquals(1000, receiveMessages()); + } - public void testMigrationOnNewDefaultForChecksumJournalFiles() throws Exception { - KahaDBStore kaha = createStore(true); - kaha.setChecksumJournalFiles(false); - assertFalse(kaha.isChecksumJournalFiles()); - assertFalse(kaha.isCheckForCorruptJournalFiles()); + private void assertExistsAndCorrupt(File file) throws IOException { + assertTrue(file.exists()); + RandomAccessFile f = new RandomAccessFile(file, "rw"); + try { + f.seek(1024 * 5 + 134); + f.write("... corruption string ...".getBytes()); + } + finally { + f.close(); + } + } - kaha.setJournalMaxFileLength(1024*100); - BrokerService broker = createBroker(kaha); - sendMessages(1000); - broker.stop(); + public void testCheckCorruptionIgnored() throws Exception { + KahaDBStore kaha = createStore(true); + kaha.setJournalMaxFileLength(1024 * 100); + BrokerService broker = createBroker(kaha); + sendMessages(1000); + broker.stop(); - kaha = createStore(false); - kaha.setJournalMaxFileLength(1024*100); - kaha.setCheckForCorruptJournalFiles(true); - assertFalse(kaha.isIgnoreMissingJournalfiles()); - createBroker(kaha); - assertEquals(1000, receiveMessages()); - } + // Delete some journal files.. + assertExistsAndCorrupt(new File(kaha.getDirectory(), "db-4.log")); + assertExistsAndCorrupt(new File(kaha.getDirectory(), "db-8.log")); + kaha = createStore(false); + kaha.setIgnoreMissingJournalfiles(true); + kaha.setJournalMaxFileLength(1024 * 100); + kaha.setCheckForCorruptJournalFiles(true); + broker = createBroker(kaha); - private void assertExistsAndCorrupt(File file) throws IOException { - assertTrue(file.exists()); - RandomAccessFile f = new RandomAccessFile(file, "rw"); - try { - f.seek(1024*5+134); - f.write("... corruption string ...".getBytes()); - } finally { - f.close(); - } - } + // We know we won't get all the messages but we should get most of them. + int count = receiveMessages(); + assertTrue("Expected to received a min # of messages.. Got: " + count, count > 990); + assertTrue(count < 1000); + broker.stop(); + } - public void testCheckCorruptionIgnored() throws Exception { - KahaDBStore kaha = createStore(true); - kaha.setJournalMaxFileLength(1024*100); - BrokerService broker = createBroker(kaha); - sendMessages(1000); - broker.stop(); + private void assertExistsAndDelete(File file) { + assertTrue(file.exists()); + file.delete(); + assertFalse(file.exists()); + } - // Delete some journal files.. - assertExistsAndCorrupt(new File(kaha.getDirectory(), "db-4.log")); - assertExistsAndCorrupt(new File(kaha.getDirectory(), "db-8.log")); + private void sendMessages(int count) throws JMSException { + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); + Connection connection = cf.createConnection(); + try { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(new ActiveMQQueue("TEST")); + for (int i = 0; i < count; i++) { + producer.send(session.createTextMessage(createContent(i))); + } + } + finally { + connection.close(); + } + } - kaha = createStore(false); - kaha.setIgnoreMissingJournalfiles(true); - kaha.setJournalMaxFileLength(1024*100); - kaha.setCheckForCorruptJournalFiles(true); - broker = createBroker(kaha); + private int receiveMessages() throws JMSException { + int rc = 0; + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); + Connection connection = cf.createConnection(); + try { + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer messageConsumer = session.createConsumer(new ActiveMQQueue("TEST")); + while (messageConsumer.receive(1000) != null) { + rc++; + } + return rc; + } + finally { + connection.close(); + } + } - // We know we won't get all the messages but we should get most of them. - int count = receiveMessages(); - assertTrue("Expected to received a min # of messages.. Got: "+count, count > 990 ); - assertTrue( count < 1000 ); - - broker.stop(); - } - - private void assertExistsAndDelete(File file) { - assertTrue(file.exists()); - file.delete(); - assertFalse(file.exists()); - } - - private void sendMessages(int count) throws JMSException { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = cf.createConnection(); - try { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(new ActiveMQQueue("TEST")); - for (int i = 0; i < count; i++) { - producer.send(session.createTextMessage(createContent(i))); - } - } finally { - connection.close(); - } - } - - private int receiveMessages() throws JMSException { - int rc=0; - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = cf.createConnection(); - try { - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer messageConsumer = session.createConsumer(new ActiveMQQueue("TEST")); - while ( messageConsumer.receive(1000) !=null ) { - rc++; - } - return rc; - } finally { - connection.close(); - } - } - - private String createContent(int i) { - StringBuilder sb = new StringBuilder(i+":"); - while( sb.length() < 1024 ) { - sb.append("*"); - } - return sb.toString(); - } + private String createContent(int i) { + StringBuilder sb = new StringBuilder(i + ":"); + while (sb.length() < 1024) { + sb.append("*"); + } + return sb.toString(); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBVersionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBVersionTest.java index c03f60db01..e1b42ad20c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBVersionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/KahaDBVersionTest.java @@ -41,139 +41,142 @@ import org.slf4j.LoggerFactory; * @author chirino */ public class KahaDBVersionTest extends TestCase { - static String basedir; - static { - try { - ProtectionDomain protectionDomain = KahaDBVersionTest.class.getProtectionDomain(); - basedir = new File(new File(protectionDomain.getCodeSource().getLocation().getPath()), "../..").getCanonicalPath(); - } catch (IOException e) { - basedir = "."; - } - } - static final Logger LOG = LoggerFactory.getLogger(KahaDBVersionTest.class); - final static File VERSION_1_DB = new File(basedir + "/src/test/resources/org/apache/activemq/store/kahadb/KahaDBVersion1"); - final static File VERSION_2_DB = new File(basedir + "/src/test/resources/org/apache/activemq/store/kahadb/KahaDBVersion2"); - final static File VERSION_3_DB = new File(basedir + "/src/test/resources/org/apache/activemq/store/kahadb/KahaDBVersion3"); - final static File VERSION_4_DB = new File(basedir + "/src/test/resources/org/apache/activemq/store/kahadb/KahaDBVersion4"); + static String basedir; - BrokerService broker = null; + static { + try { + ProtectionDomain protectionDomain = KahaDBVersionTest.class.getProtectionDomain(); + basedir = new File(new File(protectionDomain.getCodeSource().getLocation().getPath()), "../..").getCanonicalPath(); + } + catch (IOException e) { + basedir = "."; + } + } - protected BrokerService createBroker(KahaDBPersistenceAdapter kaha) throws Exception { - broker = new BrokerService(); - broker.setUseJmx(false); - broker.setPersistenceAdapter(kaha); - broker.start(); - return broker; - } + static final Logger LOG = LoggerFactory.getLogger(KahaDBVersionTest.class); + final static File VERSION_1_DB = new File(basedir + "/src/test/resources/org/apache/activemq/store/kahadb/KahaDBVersion1"); + final static File VERSION_2_DB = new File(basedir + "/src/test/resources/org/apache/activemq/store/kahadb/KahaDBVersion2"); + final static File VERSION_3_DB = new File(basedir + "/src/test/resources/org/apache/activemq/store/kahadb/KahaDBVersion3"); + final static File VERSION_4_DB = new File(basedir + "/src/test/resources/org/apache/activemq/store/kahadb/KahaDBVersion4"); - @Override - protected void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - } - } + BrokerService broker = null; - public void XtestCreateStore() throws Exception { - KahaDBPersistenceAdapter kaha = new KahaDBPersistenceAdapter(); - File dir = new File("src/test/resources/org/apache/activemq/store/kahadb/KahaDBVersion4"); - IOHelper.deleteFile(dir); - kaha.setDirectory(dir); - kaha.setJournalMaxFileLength(1024 * 1024); - BrokerService broker = createBroker(kaha); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = cf.createConnection(); - connection.setClientID("test"); - connection.start(); - producerSomeMessages(connection, 1000); - connection.close(); - broker.stop(); - } + protected BrokerService createBroker(KahaDBPersistenceAdapter kaha) throws Exception { + broker = new BrokerService(); + broker.setUseJmx(false); + broker.setPersistenceAdapter(kaha); + broker.start(); + return broker; + } - private void producerSomeMessages(Connection connection, int numToSend) throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic("test.topic"); - Queue queue = session.createQueue("test.queue"); - MessageConsumer consumer = session.createDurableSubscriber(topic, "test"); - consumer.close(); - MessageProducer producer = session.createProducer(topic); - producer.setPriority(9); - for (int i = 0; i < numToSend; i++) { - Message msg = session.createTextMessage("test message:" + i); - producer.send(msg); - } - LOG.info("sent " + numToSend + " to topic"); - producer = session.createProducer(queue); - for (int i = 0; i < numToSend; i++) { - Message msg = session.createTextMessage("test message:" + i); - producer.send(msg); - } - LOG.info("sent " + numToSend + " to queue"); - } + @Override + protected void tearDown() throws Exception { + if (broker != null) { + broker.stop(); + } + } - public void testVersion1Conversion() throws Exception { - doConvertRestartCycle(VERSION_1_DB); - } + public void XtestCreateStore() throws Exception { + KahaDBPersistenceAdapter kaha = new KahaDBPersistenceAdapter(); + File dir = new File("src/test/resources/org/apache/activemq/store/kahadb/KahaDBVersion4"); + IOHelper.deleteFile(dir); + kaha.setDirectory(dir); + kaha.setJournalMaxFileLength(1024 * 1024); + BrokerService broker = createBroker(kaha); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); + Connection connection = cf.createConnection(); + connection.setClientID("test"); + connection.start(); + producerSomeMessages(connection, 1000); + connection.close(); + broker.stop(); + } - public void testVersion2Conversion() throws Exception { - doConvertRestartCycle(VERSION_2_DB); - } + private void producerSomeMessages(Connection connection, int numToSend) throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Topic topic = session.createTopic("test.topic"); + Queue queue = session.createQueue("test.queue"); + MessageConsumer consumer = session.createDurableSubscriber(topic, "test"); + consumer.close(); + MessageProducer producer = session.createProducer(topic); + producer.setPriority(9); + for (int i = 0; i < numToSend; i++) { + Message msg = session.createTextMessage("test message:" + i); + producer.send(msg); + } + LOG.info("sent " + numToSend + " to topic"); + producer = session.createProducer(queue); + for (int i = 0; i < numToSend; i++) { + Message msg = session.createTextMessage("test message:" + i); + producer.send(msg); + } + LOG.info("sent " + numToSend + " to queue"); + } - public void testVersion3Conversion() throws Exception { - doConvertRestartCycle(VERSION_3_DB); - } + public void testVersion1Conversion() throws Exception { + doConvertRestartCycle(VERSION_1_DB); + } - public void testVersion4Conversion() throws Exception { - doConvertRestartCycle(VERSION_4_DB); - } + public void testVersion2Conversion() throws Exception { + doConvertRestartCycle(VERSION_2_DB); + } - public void doConvertRestartCycle(File existingStore) throws Exception { + public void testVersion3Conversion() throws Exception { + doConvertRestartCycle(VERSION_3_DB); + } - File testDir = new File("target/activemq-data/kahadb/versionDB"); - IOHelper.deleteFile(testDir); - IOHelper.copyFile(existingStore, testDir); - final int numToSend = 1000; + public void testVersion4Conversion() throws Exception { + doConvertRestartCycle(VERSION_4_DB); + } - // on repeat store will be upgraded - for (int repeats = 0; repeats < 3; repeats++) { - KahaDBPersistenceAdapter kaha = new KahaDBPersistenceAdapter(); - kaha.setDirectory(testDir); - kaha.setJournalMaxFileLength(1024 * 1024); - BrokerService broker = createBroker(kaha); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = cf.createConnection(); - connection.setClientID("test"); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic("test.topic"); - Queue queue = session.createQueue("test.queue"); + public void doConvertRestartCycle(File existingStore) throws Exception { - if (repeats > 0) { - // upgraded store will be empty so generated some more messages - producerSomeMessages(connection, numToSend); - } + File testDir = new File("target/activemq-data/kahadb/versionDB"); + IOHelper.deleteFile(testDir); + IOHelper.copyFile(existingStore, testDir); + final int numToSend = 1000; - MessageConsumer queueConsumer = session.createConsumer(queue); - int count = 0; - for (int i = 0; i < (repeats == 0 ? 1000 : numToSend); i++) { - TextMessage msg = (TextMessage) queueConsumer.receive(10000); - count++; - // System.err.println(msg.getText()); - assertNotNull(msg); - } - LOG.info("Consumed " + count + " from queue"); - count = 0; - MessageConsumer topicConsumer = session.createDurableSubscriber(topic, "test"); - for (int i = 0; i < (repeats == 0 ? 1000 : numToSend); i++) { - TextMessage msg = (TextMessage) topicConsumer.receive(10000); - count++; - // System.err.println(msg.getText()); - assertNotNull("" + count, msg); - } - LOG.info("Consumed " + count + " from topic"); - connection.close(); + // on repeat store will be upgraded + for (int repeats = 0; repeats < 3; repeats++) { + KahaDBPersistenceAdapter kaha = new KahaDBPersistenceAdapter(); + kaha.setDirectory(testDir); + kaha.setJournalMaxFileLength(1024 * 1024); + BrokerService broker = createBroker(kaha); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); + Connection connection = cf.createConnection(); + connection.setClientID("test"); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Topic topic = session.createTopic("test.topic"); + Queue queue = session.createQueue("test.queue"); - broker.stop(); - } - } + if (repeats > 0) { + // upgraded store will be empty so generated some more messages + producerSomeMessages(connection, numToSend); + } + + MessageConsumer queueConsumer = session.createConsumer(queue); + int count = 0; + for (int i = 0; i < (repeats == 0 ? 1000 : numToSend); i++) { + TextMessage msg = (TextMessage) queueConsumer.receive(10000); + count++; + // System.err.println(msg.getText()); + assertNotNull(msg); + } + LOG.info("Consumed " + count + " from queue"); + count = 0; + MessageConsumer topicConsumer = session.createDurableSubscriber(topic, "test"); + for (int i = 0; i < (repeats == 0 ? 1000 : numToSend); i++) { + TextMessage msg = (TextMessage) topicConsumer.receive(10000); + count++; + // System.err.println(msg.getText()); + assertNotNull("" + count, msg); + } + LOG.info("Consumed " + count + " from topic"); + connection.close(); + + broker.stop(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/NoSpaceIOTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/NoSpaceIOTest.java index fd61f89b2d..30e79c981d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/NoSpaceIOTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/kahadb/NoSpaceIOTest.java @@ -25,6 +25,7 @@ import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.command.ActiveMQQueue; @@ -34,87 +35,92 @@ import org.junit.Ignore; import org.junit.Test; public class NoSpaceIOTest { - private static final Logger LOG = LoggerFactory.getLogger(NoSpaceIOTest.class); - // need an app to input to console in intellij idea - public static void main(String[] args) throws Exception { - new NoSpaceIOTest().testRunOutOfSpace(); - } + private static final Logger LOG = LoggerFactory.getLogger(NoSpaceIOTest.class); - // handy way to validate some out of space related errors with a usb key - // allow it to run out of space, delete toDelete and see it recover - @Ignore("needs small volume, like usb key") - @Test - public void testRunOutOfSpace() throws Exception { - BrokerService broker = new BrokerService(); - File dataDir = new File("/Volumes/NO NAME/"); - File useUpSpace = new File(dataDir, "bigFile"); - if (!useUpSpace.exists()) { - LOG.info("using up some space..."); - RandomAccessFile filler = new RandomAccessFile(useUpSpace, "rw"); - filler.setLength(1024*1024*1212); // use ~1.xG of 2G (usb) volume - filler.close(); - File toDelete = new File(dataDir, "toDelete"); - filler = new RandomAccessFile(toDelete, "rw"); - filler.setLength(1024*1024*32*10); // 10 data files - filler.close(); - } - broker.setDataDirectoryFile(dataDir); - broker.start(); - AtomicLong consumed = new AtomicLong(0); - consume(consumed); - LOG.info("consumed: " + consumed); + // need an app to input to console in intellij idea + public static void main(String[] args) throws Exception { + new NoSpaceIOTest().testRunOutOfSpace(); + } - broker.getPersistenceAdapter().checkpoint(true); + // handy way to validate some out of space related errors with a usb key + // allow it to run out of space, delete toDelete and see it recover + @Ignore("needs small volume, like usb key") + @Test + public void testRunOutOfSpace() throws Exception { + BrokerService broker = new BrokerService(); + File dataDir = new File("/Volumes/NO NAME/"); + File useUpSpace = new File(dataDir, "bigFile"); + if (!useUpSpace.exists()) { + LOG.info("using up some space..."); + RandomAccessFile filler = new RandomAccessFile(useUpSpace, "rw"); + filler.setLength(1024 * 1024 * 1212); // use ~1.xG of 2G (usb) volume + filler.close(); + File toDelete = new File(dataDir, "toDelete"); + filler = new RandomAccessFile(toDelete, "rw"); + filler.setLength(1024 * 1024 * 32 * 10); // 10 data files + filler.close(); + } + broker.setDataDirectoryFile(dataDir); + broker.start(); + AtomicLong consumed = new AtomicLong(0); + consume(consumed); + LOG.info("consumed: " + consumed); - AtomicLong sent = new AtomicLong(0); - try { - produce(sent, 200); - } catch (Exception expected) { - LOG.info("got ex, sent: " + sent); - } - LOG.info("sent: " + sent); - System.out.println("Remove toDelete file and press any key to continue"); - int read = System.in.read(); - System.err.println("read:" + read); + broker.getPersistenceAdapter().checkpoint(true); - LOG.info("Trying to send again: " + sent); - try { - produce(sent, 200); - } catch (Exception expected) { - LOG.info("got ex, sent: " + sent); - } - LOG.info("sent: " + sent); - } + AtomicLong sent = new AtomicLong(0); + try { + produce(sent, 200); + } + catch (Exception expected) { + LOG.info("got ex, sent: " + sent); + } + LOG.info("sent: " + sent); + System.out.println("Remove toDelete file and press any key to continue"); + int read = System.in.read(); + System.err.println("read:" + read); - private void consume(AtomicLong consumed) throws JMSException { - Connection c = new ActiveMQConnectionFactory("vm://localhost").createConnection(); - try { - c.start(); - Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = s.createConsumer(new ActiveMQQueue("t")); - while (consumer.receive(2000) != null) { - consumed.incrementAndGet(); - } - } finally { - c.close(); - } - } + LOG.info("Trying to send again: " + sent); + try { + produce(sent, 200); + } + catch (Exception expected) { + LOG.info("got ex, sent: " + sent); + } + LOG.info("sent: " + sent); + } - private void produce(AtomicLong sent, long toSend) throws JMSException { - Connection c = new ActiveMQConnectionFactory("vm://localhost").createConnection(); - try { - c.start(); - Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = s.createProducer(new ActiveMQQueue("t")); - TextMessage m = s.createTextMessage(); - m.setText(String.valueOf(new char[1024*1024])); - for (int i=0; i exceptions = new Vector(); - ExecutorService executor; - private PListEntry getFirst(PList plist) throws IOException { - PList.PListIterator iterator = plist.iterator(); - try { - if (iterator.hasNext()) { - return iterator.next(); - } else { - return null; - } - } finally { - iterator.release(); - } - } + static final Logger LOG = LoggerFactory.getLogger(PListTest.class); + private PListStoreImpl store; + private PListImpl plist; + final ByteSequence payload = new ByteSequence(new byte[400]); + final String idSeed = new String("Seed" + Arrays.toString(new byte[1024])); + final Vector exceptions = new Vector(); + ExecutorService executor; - @Test - public void testAddLast() throws Exception { - final int COUNT = 1000; - Map map = new LinkedHashMap(); - for (int i = 0; i < COUNT; i++) { - String test = new String("test" + i); - ByteSequence bs = new ByteSequence(test.getBytes()); - map.put(test, bs); - plist.addLast(test, bs); - } - assertEquals(plist.size(), COUNT); - int count = 0; - for (ByteSequence bs : map.values()) { - String origStr = new String(bs.getData(), bs.getOffset(), bs.getLength()); - PListEntry entry = plist.get(count); - String plistString = new String(entry.getByteSequence().getData(), entry.getByteSequence().getOffset(), entry.getByteSequence().getLength()); - assertEquals(origStr, plistString); - count++; - } - } + private PListEntry getFirst(PList plist) throws IOException { + PList.PListIterator iterator = plist.iterator(); + try { + if (iterator.hasNext()) { + return iterator.next(); + } + else { + return null; + } + } + finally { + iterator.release(); + } + } - @Test - public void testAddFirst() throws Exception { - final int COUNT = 1000; - Map map = new LinkedHashMap(); - for (int i = 0; i < COUNT; i++) { - String test = new String("test" + i); - ByteSequence bs = new ByteSequence(test.getBytes()); - map.put(test, bs); - plist.addFirst(test, bs); - } - assertEquals(plist.size(), COUNT); - long count = plist.size() - 1; - for (ByteSequence bs : map.values()) { - String origStr = new String(bs.getData(), bs.getOffset(), bs.getLength()); - PListEntry entry = plist.get(count); - String plistString = new String(entry.getByteSequence().getData(), entry.getByteSequence().getOffset(), entry.getByteSequence().getLength()); - assertEquals(origStr, plistString); - count--; - } - } + @Test + public void testAddLast() throws Exception { + final int COUNT = 1000; + Map map = new LinkedHashMap(); + for (int i = 0; i < COUNT; i++) { + String test = new String("test" + i); + ByteSequence bs = new ByteSequence(test.getBytes()); + map.put(test, bs); + plist.addLast(test, bs); + } + assertEquals(plist.size(), COUNT); + int count = 0; + for (ByteSequence bs : map.values()) { + String origStr = new String(bs.getData(), bs.getOffset(), bs.getLength()); + PListEntry entry = plist.get(count); + String plistString = new String(entry.getByteSequence().getData(), entry.getByteSequence().getOffset(), entry.getByteSequence().getLength()); + assertEquals(origStr, plistString); + count++; + } + } - @Test - public void testRemove() throws IOException { - doTestRemove(2000); - } + @Test + public void testAddFirst() throws Exception { + final int COUNT = 1000; + Map map = new LinkedHashMap(); + for (int i = 0; i < COUNT; i++) { + String test = new String("test" + i); + ByteSequence bs = new ByteSequence(test.getBytes()); + map.put(test, bs); + plist.addFirst(test, bs); + } + assertEquals(plist.size(), COUNT); + long count = plist.size() - 1; + for (ByteSequence bs : map.values()) { + String origStr = new String(bs.getData(), bs.getOffset(), bs.getLength()); + PListEntry entry = plist.get(count); + String plistString = new String(entry.getByteSequence().getData(), entry.getByteSequence().getOffset(), entry.getByteSequence().getLength()); + assertEquals(origStr, plistString); + count--; + } + } - protected void doTestRemove(final int COUNT) throws IOException { - Map map = new LinkedHashMap(); - for (int i = 0; i < COUNT; i++) { - String test = new String("test" + i); - ByteSequence bs = new ByteSequence(test.getBytes()); - map.put(test, bs); - plist.addLast(test, bs); - } - assertEquals(plist.size(), COUNT); - PListEntry entry = plist.getFirst(); - while (entry != null) { - plist.remove(entry.getId()); - entry = plist.getFirst(); - } - assertEquals(0, plist.size()); - } + @Test + public void testRemove() throws IOException { + doTestRemove(2000); + } - @Test - public void testDestroy() throws Exception { - doTestRemove(1); - plist.destroy(); - assertEquals(0, plist.size()); - } + protected void doTestRemove(final int COUNT) throws IOException { + Map map = new LinkedHashMap(); + for (int i = 0; i < COUNT; i++) { + String test = new String("test" + i); + ByteSequence bs = new ByteSequence(test.getBytes()); + map.put(test, bs); + plist.addLast(test, bs); + } + assertEquals(plist.size(), COUNT); + PListEntry entry = plist.getFirst(); + while (entry != null) { + plist.remove(entry.getId()); + entry = plist.getFirst(); + } + assertEquals(0, plist.size()); + } - @Test - public void testDestroyNonEmpty() throws Exception { - final int COUNT = 1000; - Map map = new LinkedHashMap(); - for (int i = 0; i < COUNT; i++) { - String test = new String("test" + i); - ByteSequence bs = new ByteSequence(test.getBytes()); - map.put(test, bs); - plist.addLast(test, bs); - } - plist.destroy(); - assertEquals(0, plist.size()); - } + @Test + public void testDestroy() throws Exception { + doTestRemove(1); + plist.destroy(); + assertEquals(0, plist.size()); + } - @Test - public void testRemoveSecond() throws Exception { - plist.addLast("First", new ByteSequence("A".getBytes())); - plist.addLast("Second", new ByteSequence("B".getBytes())); + @Test + public void testDestroyNonEmpty() throws Exception { + final int COUNT = 1000; + Map map = new LinkedHashMap(); + for (int i = 0; i < COUNT; i++) { + String test = new String("test" + i); + ByteSequence bs = new ByteSequence(test.getBytes()); + map.put(test, bs); + plist.addLast(test, bs); + } + plist.destroy(); + assertEquals(0, plist.size()); + } - assertTrue(plist.remove("Second")); - assertTrue(plist.remove("First")); - assertFalse(plist.remove("doesNotExist")); - } + @Test + public void testRemoveSecond() throws Exception { + plist.addLast("First", new ByteSequence("A".getBytes())); + plist.addLast("Second", new ByteSequence("B".getBytes())); - @Test - public void testRemoveSingleEntry() throws Exception { - plist.addLast("First", new ByteSequence("A".getBytes())); + assertTrue(plist.remove("Second")); + assertTrue(plist.remove("First")); + assertFalse(plist.remove("doesNotExist")); + } - Iterator iterator = plist.iterator(); - while (iterator.hasNext()) { - iterator.next(); - iterator.remove(); - } - } + @Test + public void testRemoveSingleEntry() throws Exception { + plist.addLast("First", new ByteSequence("A".getBytes())); - @Test - public void testRemoveSecondPosition() throws Exception { - plist.addLast("First", new ByteSequence("A".getBytes())); - plist.addLast("Second", new ByteSequence("B".getBytes())); + Iterator iterator = plist.iterator(); + while (iterator.hasNext()) { + iterator.next(); + iterator.remove(); + } + } - assertTrue(plist.remove(1)); - assertTrue(plist.remove(0)); - assertFalse(plist.remove(0)); - } + @Test + public void testRemoveSecondPosition() throws Exception { + plist.addLast("First", new ByteSequence("A".getBytes())); + plist.addLast("Second", new ByteSequence("B".getBytes())); - @Test - public void testConcurrentAddRemove() throws Exception { - File directory = store.getDirectory(); - store.stop(); - IOHelper.mkdirs(directory); - IOHelper.deleteChildren(directory); - store = new PListStoreImpl(); - store.setCleanupInterval(400); - store.setDirectory(directory); - store.setJournalMaxFileLength(1024 * 5); - store.setLazyInit(false); - store.start(); + assertTrue(plist.remove(1)); + assertTrue(plist.remove(0)); + assertFalse(plist.remove(0)); + } - final ByteSequence payload = new ByteSequence(new byte[1024 * 2]); + @Test + public void testConcurrentAddRemove() throws Exception { + File directory = store.getDirectory(); + store.stop(); + IOHelper.mkdirs(directory); + IOHelper.deleteChildren(directory); + store = new PListStoreImpl(); + store.setCleanupInterval(400); + store.setDirectory(directory); + store.setJournalMaxFileLength(1024 * 5); + store.setLazyInit(false); + store.start(); - final Vector exceptions = new Vector(); - final int iterations = 1000; - final int numLists = 10; + final ByteSequence payload = new ByteSequence(new byte[1024 * 2]); - final PList[] lists = new PList[numLists]; - String threadName = Thread.currentThread().getName(); - for (int i = 0; i < numLists; i++) { - Thread.currentThread().setName("C:" + String.valueOf(i)); - lists[i] = store.getPList(String.valueOf(i)); - } - Thread.currentThread().setName(threadName); + final Vector exceptions = new Vector(); + final int iterations = 1000; + final int numLists = 10; - executor = Executors.newFixedThreadPool(100); - class A implements Runnable { - @Override - public void run() { - final String threadName = Thread.currentThread().getName(); - try { - for (int i = 0; i < iterations; i++) { - PList candidate = lists[i % numLists]; - Thread.currentThread().setName("ALRF:" + candidate.getName()); - synchronized (plistLocks(candidate)) { - Object locator = candidate.addLast(String.valueOf(i), payload); - getFirst(candidate); - assertTrue(candidate.remove(locator)); - } - } - } catch (Exception error) { - LOG.error("Unexpcted ex", error); - error.printStackTrace(); - exceptions.add(error); - } finally { - Thread.currentThread().setName(threadName); - } - } - }; + final PList[] lists = new PList[numLists]; + String threadName = Thread.currentThread().getName(); + for (int i = 0; i < numLists; i++) { + Thread.currentThread().setName("C:" + String.valueOf(i)); + lists[i] = store.getPList(String.valueOf(i)); + } + Thread.currentThread().setName(threadName); - class B implements Runnable { - @Override - public void run() { - final String threadName = Thread.currentThread().getName(); - try { - for (int i = 0; i < iterations; i++) { - PList candidate = lists[i % numLists]; - Thread.currentThread().setName("ALRF:" + candidate.getName()); - synchronized (plistLocks(candidate)) { - Object locator = candidate.addLast(String.valueOf(i), payload); - getFirst(candidate); - assertTrue(candidate.remove(locator)); - } - } - } catch (Exception error) { - error.printStackTrace(); - exceptions.add(error); - } finally { - Thread.currentThread().setName(threadName); - } - } - }; + executor = Executors.newFixedThreadPool(100); + class A implements Runnable { - executor.execute(new A()); - executor.execute(new A()); - executor.execute(new A()); - executor.execute(new B()); - executor.execute(new B()); - executor.execute(new B()); - - executor.shutdown(); - boolean finishedInTime = executor.awaitTermination(30, TimeUnit.SECONDS); - - assertTrue("no exceptions", exceptions.isEmpty()); - assertTrue("finished ok", finishedInTime); - } - - @Test - public void testConcurrentAddLast() throws Exception { - File directory = store.getDirectory(); - store.stop(); - IOHelper.mkdirs(directory); - IOHelper.deleteChildren(directory); - store = new PListStoreImpl(); - store.setDirectory(directory); - store.start(); - - final int numThreads = 20; - final int iterations = 1000; - executor = Executors.newFixedThreadPool(100); - for (int i = 0; i < numThreads; i++) { - new Job(i, PListTest.TaskType.ADD, iterations).run(); - } - - for (int i = 0; i < numThreads; i++) { - executor.execute(new Job(i, PListTest.TaskType.ITERATE, iterations)); - } - - for (int i = 0; i < 100; i++) { - executor.execute(new Job(i + 20, PListTest.TaskType.ADD, 100)); - } - - executor.shutdown(); - boolean finishedInTime = executor.awaitTermination(60 * 5, TimeUnit.SECONDS); - assertTrue("finished ok", finishedInTime); - } - - @Test - public void testOverFlow() throws Exception { - File directory = store.getDirectory(); - store.stop(); - IOHelper.mkdirs(directory); - IOHelper.deleteChildren(directory); - store = new PListStoreImpl(); - store.setDirectory(directory); - store.start(); - - for (int i = 0; i < 2000; i++) { - new Job(i, PListTest.TaskType.ADD, 5).run(); - - } - LOG.info("After Load index file: " + store.pageFile.getFile().length()); - LOG.info("After remove index file: " + store.pageFile.getFile().length()); - } - - @Test - public void testConcurrentAddRemoveWithPreload() throws Exception { - File directory = store.getDirectory(); - store.stop(); - IOHelper.mkdirs(directory); - IOHelper.deleteChildren(directory); - store = new PListStoreImpl(); - store.setDirectory(directory); - store.setJournalMaxFileLength(1024 * 5); - store.setCleanupInterval(5000); - store.setIndexWriteBatchSize(500); - store.start(); - - final int iterations = 500; - final int numLists = 10; - - // prime the store - - // create/delete - LOG.info("create"); - for (int i = 0; i < numLists; i++) { - new Job(i, PListTest.TaskType.CREATE, iterations).run(); - } - - LOG.info("delete"); - for (int i = 0; i < numLists; i++) { - new Job(i, PListTest.TaskType.DELETE, iterations).run(); - } - - LOG.info("fill"); - for (int i = 0; i < numLists; i++) { - new Job(i, PListTest.TaskType.ADD, iterations).run(); - } - LOG.info("remove"); - for (int i = 0; i < numLists; i++) { - new Job(i, PListTest.TaskType.REMOVE, iterations).run(); - } - - LOG.info("check empty"); - for (int i = 0; i < numLists; i++) { - assertEquals("empty " + i, 0, store.getPList("List-" + i).size()); - } - - LOG.info("delete again"); - for (int i = 0; i < numLists; i++) { - new Job(i, PListTest.TaskType.DELETE, iterations).run(); - } - - LOG.info("fill again"); - for (int i = 0; i < numLists; i++) { - new Job(i, PListTest.TaskType.ADD, iterations).run(); - } - - LOG.info("parallel add and remove"); - executor = Executors.newFixedThreadPool(numLists * 2); - for (int i = 0; i < numLists * 2; i++) { - executor.execute(new Job(i, i >= numLists ? PListTest.TaskType.ADD : PListTest.TaskType.REMOVE, iterations)); - } - - executor.shutdown(); - LOG.info("wait for parallel work to complete"); - boolean finishedInTime = executor.awaitTermination(60 * 5, TimeUnit.SECONDS); - assertTrue("no exceptions", exceptions.isEmpty()); - assertTrue("finished ok", finishedInTime); - } - - // for non determinant issues, increasing this may help diagnose - final int numRepeats = 1; - - @Test - public void testRepeatStressWithCache() throws Exception { - for (int i = 0; i < numRepeats; i++) { - do_testConcurrentAddIterateRemove(true); - } - } - - @Test - public void testRepeatStressWithOutCache() throws Exception { - for (int i = 0; i < numRepeats; i++) { - do_testConcurrentAddIterateRemove(false); - } - } - - public void do_testConcurrentAddIterateRemove(boolean enablePageCache) throws Exception { - File directory = store.getDirectory(); - store.stop(); - IOHelper.mkdirs(directory); - IOHelper.deleteChildren(directory); - store = new PListStoreImpl(); - store.setIndexEnablePageCaching(enablePageCache); - store.setIndexPageSize(2 * 1024); - store.setDirectory(directory); - store.start(); - - final int iterations = 500; - final int numLists = 10; - - LOG.info("create"); - for (int i = 0; i < numLists; i++) { - new Job(i, PListTest.TaskType.CREATE, iterations).run(); - } - - LOG.info("fill"); - for (int i = 0; i < numLists; i++) { - new Job(i, PListTest.TaskType.ADD, iterations).run(); - } - - LOG.info("parallel add and remove"); - executor = Executors.newFixedThreadPool(400); - final int numProducer = 5; - final int numConsumer = 10; - for (int i = 0; i < numLists; i++) { - for (int j = 0; j < numProducer; j++) { - executor.execute(new Job(i, PListTest.TaskType.ADD, iterations * 2)); - } - for (int k = 0; k < numConsumer; k++) { - executor.execute(new Job(i, TaskType.ITERATE_REMOVE, iterations / 4)); - } - } - - for (int i = numLists; i < numLists * 10; i++) { - executor.execute(new Job(i, PListTest.TaskType.ADD, iterations)); - } - - executor.shutdown(); - LOG.info("wait for parallel work to complete"); - boolean shutdown = executor.awaitTermination(60 * 60, TimeUnit.SECONDS); - assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); - assertTrue("test did not timeout ", shutdown); - } - - @Test - public void testConcurrentAddIterate() throws Exception { - File directory = store.getDirectory(); - store.stop(); - IOHelper.mkdirs(directory); - IOHelper.deleteChildren(directory); - store = new PListStoreImpl(); - store.setIndexPageSize(2 * 1024); - store.setJournalMaxFileLength(1024 * 1024); - store.setDirectory(directory); - store.setCleanupInterval(-1); - store.setIndexEnablePageCaching(false); - store.setIndexWriteBatchSize(100); - store.start(); - - final int iterations = 250; - final int numLists = 10; - - LOG.info("create"); - for (int i = 0; i < numLists; i++) { - new Job(i, PListTest.TaskType.CREATE, iterations).run(); - } - - LOG.info("parallel add and iterate"); - // We want a lot of adds occurring so that new free pages get created - // along - // with overlapping seeks from the iterators so that we are likely to - // seek into - // some bad area in the page file. - executor = Executors.newFixedThreadPool(100); - final int numProducer = 30; - final int numConsumer = 10; - for (int i = 0; i < numLists; i++) { - for (int j = 0; j < numProducer; j++) { - executor.execute(new Job(i, PListTest.TaskType.ADD, iterations)); - } - for (int k = 0; k < numConsumer; k++) { - executor.execute(new Job(i, TaskType.ITERATE, iterations * 2)); - } - } - - executor.shutdown(); - LOG.info("wait for parallel work to complete"); - boolean shutdown = executor.awaitTermination(5 * 60, TimeUnit.SECONDS); - assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); - assertTrue("test did not timeout ", shutdown); - LOG.info("Num dataFiles:" + store.getJournal().getFiles().size()); - } - - enum TaskType { - CREATE, DELETE, ADD, REMOVE, ITERATE, ITERATE_REMOVE - } - - class Job implements Runnable { - - int id; - TaskType task; - int iterations; - - public Job(int id, TaskType t, int iterations) { - this.id = id; - this.task = t; - this.iterations = iterations; - } - - @Override - public void run() { + @Override + public void run() { final String threadName = Thread.currentThread().getName(); try { - PListImpl plist = null; - switch (task) { - case CREATE: - Thread.currentThread().setName("C:" + id); - plist = store.getPList(String.valueOf(id)); - LOG.info("Job-" + id + ", CREATE"); - break; - case DELETE: - Thread.currentThread().setName("D:" + id); - store.removePList(String.valueOf(id)); - break; - case ADD: - Thread.currentThread().setName("A:" + id); - plist = store.getPList(String.valueOf(id)); + for (int i = 0; i < iterations; i++) { + PList candidate = lists[i % numLists]; + Thread.currentThread().setName("ALRF:" + candidate.getName()); + synchronized (plistLocks(candidate)) { + Object locator = candidate.addLast(String.valueOf(i), payload); + getFirst(candidate); + assertTrue(candidate.remove(locator)); + } + } + } + catch (Exception error) { + LOG.error("Unexpcted ex", error); + error.printStackTrace(); + exceptions.add(error); + } + finally { + Thread.currentThread().setName(threadName); + } + } + } + ; - for (int j = 0; j < iterations; j++) { - synchronized (plistLocks(plist)) { - if (exceptions.isEmpty()) { - plist.addLast("PL>" + id + idSeed + "-" + j, payload); - } else { - break; - } - } - } + class B implements Runnable { + @Override + public void run() { + final String threadName = Thread.currentThread().getName(); + try { + for (int i = 0; i < iterations; i++) { + PList candidate = lists[i % numLists]; + Thread.currentThread().setName("ALRF:" + candidate.getName()); + synchronized (plistLocks(candidate)) { + Object locator = candidate.addLast(String.valueOf(i), payload); + getFirst(candidate); + assertTrue(candidate.remove(locator)); + } + } + } + catch (Exception error) { + error.printStackTrace(); + exceptions.add(error); + } + finally { + Thread.currentThread().setName(threadName); + } + } + } + ; + + executor.execute(new A()); + executor.execute(new A()); + executor.execute(new A()); + executor.execute(new B()); + executor.execute(new B()); + executor.execute(new B()); + + executor.shutdown(); + boolean finishedInTime = executor.awaitTermination(30, TimeUnit.SECONDS); + + assertTrue("no exceptions", exceptions.isEmpty()); + assertTrue("finished ok", finishedInTime); + } + + @Test + public void testConcurrentAddLast() throws Exception { + File directory = store.getDirectory(); + store.stop(); + IOHelper.mkdirs(directory); + IOHelper.deleteChildren(directory); + store = new PListStoreImpl(); + store.setDirectory(directory); + store.start(); + + final int numThreads = 20; + final int iterations = 1000; + executor = Executors.newFixedThreadPool(100); + for (int i = 0; i < numThreads; i++) { + new Job(i, PListTest.TaskType.ADD, iterations).run(); + } + + for (int i = 0; i < numThreads; i++) { + executor.execute(new Job(i, PListTest.TaskType.ITERATE, iterations)); + } + + for (int i = 0; i < 100; i++) { + executor.execute(new Job(i + 20, PListTest.TaskType.ADD, 100)); + } + + executor.shutdown(); + boolean finishedInTime = executor.awaitTermination(60 * 5, TimeUnit.SECONDS); + assertTrue("finished ok", finishedInTime); + } + + @Test + public void testOverFlow() throws Exception { + File directory = store.getDirectory(); + store.stop(); + IOHelper.mkdirs(directory); + IOHelper.deleteChildren(directory); + store = new PListStoreImpl(); + store.setDirectory(directory); + store.start(); + + for (int i = 0; i < 2000; i++) { + new Job(i, PListTest.TaskType.ADD, 5).run(); + + } + LOG.info("After Load index file: " + store.pageFile.getFile().length()); + LOG.info("After remove index file: " + store.pageFile.getFile().length()); + } + + @Test + public void testConcurrentAddRemoveWithPreload() throws Exception { + File directory = store.getDirectory(); + store.stop(); + IOHelper.mkdirs(directory); + IOHelper.deleteChildren(directory); + store = new PListStoreImpl(); + store.setDirectory(directory); + store.setJournalMaxFileLength(1024 * 5); + store.setCleanupInterval(5000); + store.setIndexWriteBatchSize(500); + store.start(); + + final int iterations = 500; + final int numLists = 10; + + // prime the store + + // create/delete + LOG.info("create"); + for (int i = 0; i < numLists; i++) { + new Job(i, PListTest.TaskType.CREATE, iterations).run(); + } + + LOG.info("delete"); + for (int i = 0; i < numLists; i++) { + new Job(i, PListTest.TaskType.DELETE, iterations).run(); + } + + LOG.info("fill"); + for (int i = 0; i < numLists; i++) { + new Job(i, PListTest.TaskType.ADD, iterations).run(); + } + LOG.info("remove"); + for (int i = 0; i < numLists; i++) { + new Job(i, PListTest.TaskType.REMOVE, iterations).run(); + } + + LOG.info("check empty"); + for (int i = 0; i < numLists; i++) { + assertEquals("empty " + i, 0, store.getPList("List-" + i).size()); + } + + LOG.info("delete again"); + for (int i = 0; i < numLists; i++) { + new Job(i, PListTest.TaskType.DELETE, iterations).run(); + } + + LOG.info("fill again"); + for (int i = 0; i < numLists; i++) { + new Job(i, PListTest.TaskType.ADD, iterations).run(); + } + + LOG.info("parallel add and remove"); + executor = Executors.newFixedThreadPool(numLists * 2); + for (int i = 0; i < numLists * 2; i++) { + executor.execute(new Job(i, i >= numLists ? PListTest.TaskType.ADD : PListTest.TaskType.REMOVE, iterations)); + } + + executor.shutdown(); + LOG.info("wait for parallel work to complete"); + boolean finishedInTime = executor.awaitTermination(60 * 5, TimeUnit.SECONDS); + assertTrue("no exceptions", exceptions.isEmpty()); + assertTrue("finished ok", finishedInTime); + } + + // for non determinant issues, increasing this may help diagnose + final int numRepeats = 1; + + @Test + public void testRepeatStressWithCache() throws Exception { + for (int i = 0; i < numRepeats; i++) { + do_testConcurrentAddIterateRemove(true); + } + } + + @Test + public void testRepeatStressWithOutCache() throws Exception { + for (int i = 0; i < numRepeats; i++) { + do_testConcurrentAddIterateRemove(false); + } + } + + public void do_testConcurrentAddIterateRemove(boolean enablePageCache) throws Exception { + File directory = store.getDirectory(); + store.stop(); + IOHelper.mkdirs(directory); + IOHelper.deleteChildren(directory); + store = new PListStoreImpl(); + store.setIndexEnablePageCaching(enablePageCache); + store.setIndexPageSize(2 * 1024); + store.setDirectory(directory); + store.start(); + + final int iterations = 500; + final int numLists = 10; + + LOG.info("create"); + for (int i = 0; i < numLists; i++) { + new Job(i, PListTest.TaskType.CREATE, iterations).run(); + } + + LOG.info("fill"); + for (int i = 0; i < numLists; i++) { + new Job(i, PListTest.TaskType.ADD, iterations).run(); + } + + LOG.info("parallel add and remove"); + executor = Executors.newFixedThreadPool(400); + final int numProducer = 5; + final int numConsumer = 10; + for (int i = 0; i < numLists; i++) { + for (int j = 0; j < numProducer; j++) { + executor.execute(new Job(i, PListTest.TaskType.ADD, iterations * 2)); + } + for (int k = 0; k < numConsumer; k++) { + executor.execute(new Job(i, TaskType.ITERATE_REMOVE, iterations / 4)); + } + } + + for (int i = numLists; i < numLists * 10; i++) { + executor.execute(new Job(i, PListTest.TaskType.ADD, iterations)); + } + + executor.shutdown(); + LOG.info("wait for parallel work to complete"); + boolean shutdown = executor.awaitTermination(60 * 60, TimeUnit.SECONDS); + assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); + assertTrue("test did not timeout ", shutdown); + } + + @Test + public void testConcurrentAddIterate() throws Exception { + File directory = store.getDirectory(); + store.stop(); + IOHelper.mkdirs(directory); + IOHelper.deleteChildren(directory); + store = new PListStoreImpl(); + store.setIndexPageSize(2 * 1024); + store.setJournalMaxFileLength(1024 * 1024); + store.setDirectory(directory); + store.setCleanupInterval(-1); + store.setIndexEnablePageCaching(false); + store.setIndexWriteBatchSize(100); + store.start(); + + final int iterations = 250; + final int numLists = 10; + + LOG.info("create"); + for (int i = 0; i < numLists; i++) { + new Job(i, PListTest.TaskType.CREATE, iterations).run(); + } + + LOG.info("parallel add and iterate"); + // We want a lot of adds occurring so that new free pages get created + // along + // with overlapping seeks from the iterators so that we are likely to + // seek into + // some bad area in the page file. + executor = Executors.newFixedThreadPool(100); + final int numProducer = 30; + final int numConsumer = 10; + for (int i = 0; i < numLists; i++) { + for (int j = 0; j < numProducer; j++) { + executor.execute(new Job(i, PListTest.TaskType.ADD, iterations)); + } + for (int k = 0; k < numConsumer; k++) { + executor.execute(new Job(i, TaskType.ITERATE, iterations * 2)); + } + } + + executor.shutdown(); + LOG.info("wait for parallel work to complete"); + boolean shutdown = executor.awaitTermination(5 * 60, TimeUnit.SECONDS); + assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); + assertTrue("test did not timeout ", shutdown); + LOG.info("Num dataFiles:" + store.getJournal().getFiles().size()); + } + + enum TaskType { + CREATE, DELETE, ADD, REMOVE, ITERATE, ITERATE_REMOVE + } + + class Job implements Runnable { + + int id; + TaskType task; + int iterations; + + public Job(int id, TaskType t, int iterations) { + this.id = id; + this.task = t; + this.iterations = iterations; + } + + @Override + public void run() { + final String threadName = Thread.currentThread().getName(); + try { + PListImpl plist = null; + switch (task) { + case CREATE: + Thread.currentThread().setName("C:" + id); + plist = store.getPList(String.valueOf(id)); + LOG.info("Job-" + id + ", CREATE"); + break; + case DELETE: + Thread.currentThread().setName("D:" + id); + store.removePList(String.valueOf(id)); + break; + case ADD: + Thread.currentThread().setName("A:" + id); + plist = store.getPList(String.valueOf(id)); + + for (int j = 0; j < iterations; j++) { + synchronized (plistLocks(plist)) { if (exceptions.isEmpty()) { - LOG.info("Job-" + id + ", Add, done: " + iterations); + plist.addLast("PL>" + id + idSeed + "-" + j, payload); } - break; - case REMOVE: - Thread.currentThread().setName("R:" + id); - plist = store.getPList(String.valueOf(id)); - synchronized (plistLocks(plist)) { - - for (int j = iterations - 1; j >= 0; j--) { - plist.remove("PL>" + id + idSeed + "-" + j); - if (j > 0 && j % (iterations / 2) == 0) { - LOG.info("Job-" + id + " Done remove: " + j); - } - } + else { + break; } - break; - case ITERATE: - Thread.currentThread().setName("I:" + id); - plist = store.getPList(String.valueOf(id)); - int iterateCount = 0; - synchronized (plistLocks(plist)) { - if (exceptions.isEmpty()) { - Iterator iterator = plist.iterator(); - while (iterator.hasNext() && exceptions.isEmpty()) { - iterator.next(); - iterateCount++; - } + } + } - // LOG.info("Job-" + id + " Done iterate: it=" + - // iterator + ", count:" + iterateCount + - // ", size:" + plist.size()); - if (plist.size() != iterateCount) { - System.err.println("Count Wrong: " + iterator); - } - assertEquals("iterate got all " + id + " iterator:" + iterator, plist.size(), iterateCount); - } + if (exceptions.isEmpty()) { + LOG.info("Job-" + id + ", Add, done: " + iterations); + } + break; + case REMOVE: + Thread.currentThread().setName("R:" + id); + plist = store.getPList(String.valueOf(id)); + synchronized (plistLocks(plist)) { + + for (int j = iterations - 1; j >= 0; j--) { + plist.remove("PL>" + id + idSeed + "-" + j); + if (j > 0 && j % (iterations / 2) == 0) { + LOG.info("Job-" + id + " Done remove: " + j); } - break; - - case ITERATE_REMOVE: - Thread.currentThread().setName("IRM:" + id); - plist = store.getPList(String.valueOf(id)); - - int removeCount = 0; - synchronized (plistLocks(plist)) { - - Iterator removeIterator = plist.iterator(); - - while (removeIterator.hasNext()) { - removeIterator.next(); - removeIterator.remove(); - if (removeCount++ > iterations) { - break; - } - } + } + } + break; + case ITERATE: + Thread.currentThread().setName("I:" + id); + plist = store.getPList(String.valueOf(id)); + int iterateCount = 0; + synchronized (plistLocks(plist)) { + if (exceptions.isEmpty()) { + Iterator iterator = plist.iterator(); + while (iterator.hasNext() && exceptions.isEmpty()) { + iterator.next(); + iterateCount++; } - LOG.info("Job-" + id + " Done remove: " + removeCount); - break; - default: - } + // LOG.info("Job-" + id + " Done iterate: it=" + + // iterator + ", count:" + iterateCount + + // ", size:" + plist.size()); + if (plist.size() != iterateCount) { + System.err.println("Count Wrong: " + iterator); + } + assertEquals("iterate got all " + id + " iterator:" + iterator, plist.size(), iterateCount); + } + } + break; - } catch (Exception e) { - LOG.warn("Job[" + id + "] caught exception: " + e.getMessage()); - e.printStackTrace(); - exceptions.add(e); - if (executor != null) { - executor.shutdownNow(); - } - } finally { - Thread.currentThread().setName(threadName); + case ITERATE_REMOVE: + Thread.currentThread().setName("IRM:" + id); + plist = store.getPList(String.valueOf(id)); + + int removeCount = 0; + synchronized (plistLocks(plist)) { + + Iterator removeIterator = plist.iterator(); + + while (removeIterator.hasNext()) { + removeIterator.next(); + removeIterator.remove(); + if (removeCount++ > iterations) { + break; + } + } + } + LOG.info("Job-" + id + " Done remove: " + removeCount); + break; + + default: } - } - } - final Map locks = new HashMap(); - - private Object plistLocks(PList plist) { - Object lock = null; - synchronized (locks) { - if (locks.containsKey(plist)) { - lock = locks.get(plist); - } else { - lock = new Object(); - locks.put(plist, lock); + } + catch (Exception e) { + LOG.warn("Job[" + id + "] caught exception: " + e.getMessage()); + e.printStackTrace(); + exceptions.add(e); + if (executor != null) { + executor.shutdownNow(); } - } - return lock; - } + } + finally { + Thread.currentThread().setName(threadName); + } + } + } - @Before - public void setUp() throws Exception { - File directory = new File("target/test/PlistDB"); - IOHelper.mkdirs(directory); - IOHelper.deleteChildren(directory); - startStore(directory); + final Map locks = new HashMap(); - } + private Object plistLocks(PList plist) { + Object lock = null; + synchronized (locks) { + if (locks.containsKey(plist)) { + lock = locks.get(plist); + } + else { + lock = new Object(); + locks.put(plist, lock); + } + } + return lock; + } - protected void startStore(File directory) throws Exception { - store = new PListStoreImpl(); - store.setDirectory(directory); - store.start(); - plist = store.getPList("main"); - } + @Before + public void setUp() throws Exception { + File directory = new File("target/test/PlistDB"); + IOHelper.mkdirs(directory); + IOHelper.deleteChildren(directory); + startStore(directory); - @After - public void tearDown() throws Exception { - if (executor != null) { - executor.shutdownNow(); - } - store.stop(); - exceptions.clear(); - } + } + + protected void startStore(File directory) throws Exception { + store = new PListStoreImpl(); + store.setDirectory(directory); + store.start(); + plist = store.getPList("main"); + } + + @After + public void tearDown() throws Exception { + if (executor != null) { + executor.shutdownNow(); + } + store.stop(); + exceptions.clear(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/leveldb/LevelDBNegativeQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/leveldb/LevelDBNegativeQueueTest.java index 7ea7d1a4c2..3c28b3da58 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/leveldb/LevelDBNegativeQueueTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/leveldb/LevelDBNegativeQueueTest.java @@ -25,14 +25,14 @@ import java.io.File; public class LevelDBNegativeQueueTest extends NegativeQueueTest { - @Override - protected void configureBroker(BrokerService answer) throws Exception { - super.configureBroker(answer); - LevelDBStore levelDBStore = new LevelDBStore(); - File directory = new File("target/activemq-data/leveldb"); - IOHelper.deleteChildren(directory); - levelDBStore.setDirectory(directory); - levelDBStore.deleteAllMessages(); - answer.setPersistenceAdapter(levelDBStore); - } + @Override + protected void configureBroker(BrokerService answer) throws Exception { + super.configureBroker(answer); + LevelDBStore levelDBStore = new LevelDBStore(); + File directory = new File("target/activemq-data/leveldb"); + IOHelper.deleteChildren(directory); + levelDBStore.setDirectory(directory); + levelDBStore.deleteAllMessages(); + answer.setPersistenceAdapter(levelDBStore); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/leveldb/LevelDBStoreBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/leveldb/LevelDBStoreBrokerTest.java index 156e9ca781..c1977dedd0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/leveldb/LevelDBStoreBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/store/leveldb/LevelDBStoreBrokerTest.java @@ -19,6 +19,7 @@ package org.apache.activemq.store.leveldb; import java.io.File; import junit.framework.Test; + import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerTest; import org.apache.activemq.store.kahadb.KahaDBStore; @@ -27,42 +28,39 @@ import org.apache.activemq.leveldb.LevelDBStore; /** * Once the wire format is completed we can test against real persistence storage. - * - * */ public class LevelDBStoreBrokerTest extends BrokerTest { - protected void setUp() throws Exception { - this.setAutoFail(true); - super.setUp(); - } - - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - LevelDBStore levelDBStore = new LevelDBStore(); - File directory = new File("target/activemq-data/leveldb"); - IOHelper.deleteChildren(directory); - levelDBStore.setDirectory(directory); - levelDBStore.deleteAllMessages(); - broker.setPersistenceAdapter(levelDBStore); - return broker; - } - - protected BrokerService createRestartedBroker() throws Exception { - BrokerService broker = new BrokerService(); - KahaDBStore kaha = new KahaDBStore(); - kaha.setDirectory(new File("target/activemq-data/leveldb")); - broker.setPersistenceAdapter(kaha); - return broker; - } - - - public static Test suite() { - return suite(LevelDBStoreBrokerTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + protected void setUp() throws Exception { + this.setAutoFail(true); + super.setUp(); + } + + protected BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); + LevelDBStore levelDBStore = new LevelDBStore(); + File directory = new File("target/activemq-data/leveldb"); + IOHelper.deleteChildren(directory); + levelDBStore.setDirectory(directory); + levelDBStore.deleteAllMessages(); + broker.setPersistenceAdapter(levelDBStore); + return broker; + } + + protected BrokerService createRestartedBroker() throws Exception { + BrokerService broker = new BrokerService(); + KahaDBStore kaha = new KahaDBStore(); + kaha.setDirectory(new File("target/activemq-data/leveldb")); + broker.setPersistenceAdapter(kaha); + return broker; + } + + public static Test suite() { + return suite(LevelDBStoreBrokerTest.class); + } + + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/streams/JMSInputStreamTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/streams/JMSInputStreamTest.java index b07c8cce6b..6ec27c0c4b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/streams/JMSInputStreamTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/streams/JMSInputStreamTest.java @@ -44,238 +44,243 @@ import org.apache.activemq.command.ActiveMQTopic; @Deprecated public class JMSInputStreamTest extends JmsTestSupport { - public Destination destination; - protected DataOutputStream out; - protected DataInputStream in; - private ActiveMQConnection connection2; + public Destination destination; + protected DataOutputStream out; + protected DataInputStream in; + private ActiveMQConnection connection2; - private ActiveMQInputStream amqIn; - private ActiveMQOutputStream amqOut; + private ActiveMQInputStream amqIn; + private ActiveMQOutputStream amqOut; - public static Test suite() { - return suite(JMSInputStreamTest.class); - } + public static Test suite() { + return suite(JMSInputStreamTest.class); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - public void initCombos() { - addCombinationValues("destination", new Object[] { new ActiveMQQueue("TEST.QUEUE"), new ActiveMQTopic("TEST.TOPIC") }); - } + public void initCombos() { + addCombinationValues("destination", new Object[]{new ActiveMQQueue("TEST.QUEUE"), new ActiveMQTopic("TEST.TOPIC")}); + } - @Override - protected void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - } + @Override + protected void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); + } - private void setUpConnection(Map props, long timeout) throws JMSException { - connection2 = (ActiveMQConnection) factory.createConnection(userName, password); - connections.add(connection2); - if (props != null) { - amqOut = (ActiveMQOutputStream) connection.createOutputStream(destination, props, Message.DEFAULT_DELIVERY_MODE, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); - } else { - amqOut = (ActiveMQOutputStream) connection.createOutputStream(destination); - } + private void setUpConnection(Map props, long timeout) throws JMSException { + connection2 = (ActiveMQConnection) factory.createConnection(userName, password); + connections.add(connection2); + if (props != null) { + amqOut = (ActiveMQOutputStream) connection.createOutputStream(destination, props, Message.DEFAULT_DELIVERY_MODE, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); + } + else { + amqOut = (ActiveMQOutputStream) connection.createOutputStream(destination); + } - out = new DataOutputStream(amqOut); - if (timeout == -1) { - amqIn = (ActiveMQInputStream) connection2.createInputStream(destination); - } else { - amqIn = (ActiveMQInputStream) connection2.createInputStream(destination, null, false, timeout); - } - in = new DataInputStream(amqIn); - } + out = new DataOutputStream(amqOut); + if (timeout == -1) { + amqIn = (ActiveMQInputStream) connection2.createInputStream(destination); + } + else { + amqIn = (ActiveMQInputStream) connection2.createInputStream(destination, null, false, timeout); + } + in = new DataInputStream(amqIn); + } - /* - * @see TestCase#tearDown() - */ - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } + /* + * @see TestCase#tearDown() + */ + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } - /** - * Test for AMQ-3010 - */ - public void testInputStreamTimeout() throws Exception { - long timeout = 500; + /** + * Test for AMQ-3010 + */ + public void testInputStreamTimeout() throws Exception { + long timeout = 500; - setUpConnection(null, timeout); - try { - in.read(); - fail(); - } catch (ActiveMQInputStream.ReadTimeoutException e) { - // timeout reached, everything ok - } - in.close(); - } + setUpConnection(null, timeout); + try { + in.read(); + fail(); + } + catch (ActiveMQInputStream.ReadTimeoutException e) { + // timeout reached, everything ok + } + in.close(); + } - // Test for AMQ-2988 - public void testStreamsWithProperties() throws Exception { - String name1 = "PROPERTY_1"; - String name2 = "PROPERTY_2"; - String value1 = "VALUE_1"; - String value2 = "VALUE_2"; - Map jmsProperties = new HashMap(); - jmsProperties.put(name1, value1); - jmsProperties.put(name2, value2); - setUpConnection(jmsProperties, -1); + // Test for AMQ-2988 + public void testStreamsWithProperties() throws Exception { + String name1 = "PROPERTY_1"; + String name2 = "PROPERTY_2"; + String value1 = "VALUE_1"; + String value2 = "VALUE_2"; + Map jmsProperties = new HashMap(); + jmsProperties.put(name1, value1); + jmsProperties.put(name2, value2); + setUpConnection(jmsProperties, -1); - out.writeInt(4); - out.flush(); - assertTrue(in.readInt() == 4); - out.writeFloat(2.3f); - out.flush(); - assertTrue(in.readFloat() == 2.3f); - String str = "this is a test string"; - out.writeUTF(str); - out.flush(); - assertTrue(in.readUTF().equals(str)); - for (int i = 0; i < 100; i++) { - out.writeLong(i); - } - out.flush(); + out.writeInt(4); + out.flush(); + assertTrue(in.readInt() == 4); + out.writeFloat(2.3f); + out.flush(); + assertTrue(in.readFloat() == 2.3f); + String str = "this is a test string"; + out.writeUTF(str); + out.flush(); + assertTrue(in.readUTF().equals(str)); + for (int i = 0; i < 100; i++) { + out.writeLong(i); + } + out.flush(); - // check properties before we try to read the stream - checkProperties(jmsProperties); + // check properties before we try to read the stream + checkProperties(jmsProperties); - for (int i = 0; i < 100; i++) { - assertTrue(in.readLong() == i); - } + for (int i = 0; i < 100; i++) { + assertTrue(in.readLong() == i); + } - // check again after read was done - checkProperties(jmsProperties); - } + // check again after read was done + checkProperties(jmsProperties); + } - public void testStreamsWithPropertiesOnlyOnFirstMessage() throws Exception { - String name1 = "PROPERTY_1"; - String name2 = "PROPERTY_2"; - String value1 = "VALUE_1"; - String value2 = "VALUE_2"; - Map jmsProperties = new HashMap(); - jmsProperties.put(name1, value1); - jmsProperties.put(name2, value2); + public void testStreamsWithPropertiesOnlyOnFirstMessage() throws Exception { + String name1 = "PROPERTY_1"; + String name2 = "PROPERTY_2"; + String value1 = "VALUE_1"; + String value2 = "VALUE_2"; + Map jmsProperties = new HashMap(); + jmsProperties.put(name1, value1); + jmsProperties.put(name2, value2); - ActiveMQDestination dest = (ActiveMQDestination) destination; + ActiveMQDestination dest = (ActiveMQDestination) destination; - if (dest.isQueue()) { - destination = new ActiveMQQueue(dest.getPhysicalName() + "?producer.addPropertiesOnFirstMsgOnly=true"); - } else { - destination = new ActiveMQTopic(dest.getPhysicalName() + "?producer.addPropertiesOnFirstMsgOnly=true"); - } + if (dest.isQueue()) { + destination = new ActiveMQQueue(dest.getPhysicalName() + "?producer.addPropertiesOnFirstMsgOnly=true"); + } + else { + destination = new ActiveMQTopic(dest.getPhysicalName() + "?producer.addPropertiesOnFirstMsgOnly=true"); + } - setUpConnection(jmsProperties, -1); + setUpConnection(jmsProperties, -1); - assertTrue(amqOut.isAddPropertiesOnFirstMsgOnly()); + assertTrue(amqOut.isAddPropertiesOnFirstMsgOnly()); - out.writeInt(4); - out.flush(); - assertTrue(in.readInt() == 4); - out.writeFloat(2.3f); - out.flush(); - assertTrue(in.readFloat() == 2.3f); - String str = "this is a test string"; - out.writeUTF(str); - out.flush(); - assertTrue(in.readUTF().equals(str)); - for (int i = 0; i < 100; i++) { - out.writeLong(i); - } - out.flush(); + out.writeInt(4); + out.flush(); + assertTrue(in.readInt() == 4); + out.writeFloat(2.3f); + out.flush(); + assertTrue(in.readFloat() == 2.3f); + String str = "this is a test string"; + out.writeUTF(str); + out.flush(); + assertTrue(in.readUTF().equals(str)); + for (int i = 0; i < 100; i++) { + out.writeLong(i); + } + out.flush(); - // check properties before we try to read the stream - checkProperties(jmsProperties); + // check properties before we try to read the stream + checkProperties(jmsProperties); - for (int i = 0; i < 100; i++) { - assertTrue(in.readLong() == i); - } + for (int i = 0; i < 100; i++) { + assertTrue(in.readLong() == i); + } - // check again after read was done - checkProperties(jmsProperties); - } + // check again after read was done + checkProperties(jmsProperties); + } - // check if the received stream has the properties set - // Test for AMQ-2988 - private void checkProperties(Map jmsProperties) throws IOException { - Map receivedJmsProps = amqIn.getJMSProperties(); + // check if the received stream has the properties set + // Test for AMQ-2988 + private void checkProperties(Map jmsProperties) throws IOException { + Map receivedJmsProps = amqIn.getJMSProperties(); - // we should at least have the same amount or more properties - assertTrue(jmsProperties.size() <= receivedJmsProps.size()); + // we should at least have the same amount or more properties + assertTrue(jmsProperties.size() <= receivedJmsProps.size()); - // check the properties to see if we have everything in there - Iterator propsIt = jmsProperties.keySet().iterator(); - while (propsIt.hasNext()) { - String key = propsIt.next(); - assertTrue(receivedJmsProps.containsKey(key)); - assertEquals(jmsProperties.get(key), receivedJmsProps.get(key)); - } - } + // check the properties to see if we have everything in there + Iterator propsIt = jmsProperties.keySet().iterator(); + while (propsIt.hasNext()) { + String key = propsIt.next(); + assertTrue(receivedJmsProps.containsKey(key)); + assertEquals(jmsProperties.get(key), receivedJmsProps.get(key)); + } + } - public void testLarge() throws Exception { - setUpConnection(null, -1); + public void testLarge() throws Exception { + setUpConnection(null, -1); - final int testData = 23; - final int dataLength = 4096; - final int count = 1024; - byte[] data = new byte[dataLength]; - for (int i = 0; i < data.length; i++) { - data[i] = testData; - } - final AtomicBoolean complete = new AtomicBoolean(false); - Thread runner = new Thread(new Runnable() { - @Override - public void run() { - try { - for (int x = 0; x < count; x++) { - byte[] b = new byte[2048]; - in.readFully(b); - for (int i = 0; i < b.length; i++) { - assertTrue(b[i] == testData); - } - } - complete.set(true); - synchronized (complete) { - complete.notify(); - } - } catch (Exception ex) { - ex.printStackTrace(); - } + final int testData = 23; + final int dataLength = 4096; + final int count = 1024; + byte[] data = new byte[dataLength]; + for (int i = 0; i < data.length; i++) { + data[i] = testData; + } + final AtomicBoolean complete = new AtomicBoolean(false); + Thread runner = new Thread(new Runnable() { + @Override + public void run() { + try { + for (int x = 0; x < count; x++) { + byte[] b = new byte[2048]; + in.readFully(b); + for (int i = 0; i < b.length; i++) { + assertTrue(b[i] == testData); + } + } + complete.set(true); + synchronized (complete) { + complete.notify(); + } } - }); - runner.start(); - for (int i = 0; i < count; i++) { - out.write(data); - } - out.flush(); - synchronized (complete) { - while (!complete.get()) { - complete.wait(30000); + catch (Exception ex) { + ex.printStackTrace(); } - } - assertTrue(complete.get()); - } + } + }); + runner.start(); + for (int i = 0; i < count; i++) { + out.write(data); + } + out.flush(); + synchronized (complete) { + while (!complete.get()) { + complete.wait(30000); + } + } + assertTrue(complete.get()); + } - public void testStreams() throws Exception { - setUpConnection(null, -1); - out.writeInt(4); - out.flush(); - assertTrue(in.readInt() == 4); - out.writeFloat(2.3f); - out.flush(); - assertTrue(in.readFloat() == 2.3f); - String str = "this is a test string"; - out.writeUTF(str); - out.flush(); - assertTrue(in.readUTF().equals(str)); - for (int i = 0; i < 100; i++) { - out.writeLong(i); - } - out.flush(); + public void testStreams() throws Exception { + setUpConnection(null, -1); + out.writeInt(4); + out.flush(); + assertTrue(in.readInt() == 4); + out.writeFloat(2.3f); + out.flush(); + assertTrue(in.readFloat() == 2.3f); + String str = "this is a test string"; + out.writeUTF(str); + out.flush(); + assertTrue(in.readUTF().equals(str)); + for (int i = 0; i < 100; i++) { + out.writeLong(i); + } + out.flush(); - for (int i = 0; i < 100; i++) { - assertTrue(in.readLong() == i); - } - } + for (int i = 0; i < 100; i++) { + assertTrue(in.readLong() == i); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsSendReceiveTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsSendReceiveTestSupport.java index 931beedc9b..cd0433389a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsSendReceiveTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsSendReceiveTestSupport.java @@ -40,221 +40,225 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public abstract class JmsSendReceiveTestSupport extends org.apache.activemq.TestSupport implements MessageListener { - private static final Logger LOG = LoggerFactory.getLogger(JmsSendReceiveTestSupport.class); - protected int messageCount = 100; - protected String[] data; - protected Session session; - protected Session consumeSession; - protected MessageConsumer consumer; - protected MessageProducer producer; - protected Destination consumerDestination; - protected Destination producerDestination; - protected List messages = createConcurrentList(); - protected boolean topic = true; - protected boolean durable; - protected int deliveryMode = DeliveryMode.PERSISTENT; - protected final Object lock = new Object(); - protected boolean verbose; - protected boolean useSeparateSession; - protected boolean largeMessages; - protected int largeMessageLoopSize = 4 * 1024; + private static final Logger LOG = LoggerFactory.getLogger(JmsSendReceiveTestSupport.class); - /* - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - String temp = System.getProperty("messageCount"); + protected int messageCount = 100; + protected String[] data; + protected Session session; + protected Session consumeSession; + protected MessageConsumer consumer; + protected MessageProducer producer; + protected Destination consumerDestination; + protected Destination producerDestination; + protected List messages = createConcurrentList(); + protected boolean topic = true; + protected boolean durable; + protected int deliveryMode = DeliveryMode.PERSISTENT; + protected final Object lock = new Object(); + protected boolean verbose; + protected boolean useSeparateSession; + protected boolean largeMessages; + protected int largeMessageLoopSize = 4 * 1024; - if (temp != null) { - int i = Integer.parseInt(temp); - if (i > 0) { - messageCount = i; - } - } + /* + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + String temp = System.getProperty("messageCount"); - LOG.info("Message count for test case is: " + messageCount); - data = new String[messageCount]; - for (int i = 0; i < messageCount; i++) { - data[i] = createMessageText(i); - } - } + if (temp != null) { + int i = Integer.parseInt(temp); + if (i > 0) { + messageCount = i; + } + } - protected String createMessageText(int i) { - if (largeMessages) { - return createMessageBodyText(); - } else { - return "Text for message: " + i + " at " + new Date(); - } - } + LOG.info("Message count for test case is: " + messageCount); + data = new String[messageCount]; + for (int i = 0; i < messageCount; i++) { + data[i] = createMessageText(i); + } + } - protected String createMessageBodyText() { - StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < largeMessageLoopSize; i++) { - buffer.append("0123456789"); - } - return buffer.toString(); - } + protected String createMessageText(int i) { + if (largeMessages) { + return createMessageBodyText(); + } + else { + return "Text for message: " + i + " at " + new Date(); + } + } - /** - * Test if all the messages sent are being received. - * - * @throws Exception - */ - public void testSendReceive() throws Exception { + protected String createMessageBodyText() { + StringBuffer buffer = new StringBuffer(); + for (int i = 0; i < largeMessageLoopSize; i++) { + buffer.append("0123456789"); + } + return buffer.toString(); + } - Thread.sleep(1000); - messages.clear(); + /** + * Test if all the messages sent are being received. + * + * @throws Exception + */ + public void testSendReceive() throws Exception { - sendMessages(); + Thread.sleep(1000); + messages.clear(); - assertMessagesAreReceived(); - LOG.info("" + data.length + " messages(s) received, closing down connections"); - } + sendMessages(); - protected void sendMessages() throws Exception { - for (int i = 0; i < data.length; i++) { - Message message = createMessage(i); - configureMessage(message); - if (verbose) { - LOG.info("About to send a message: " + message + " with text: " + data[i]); - } - sendMessage(i, message); - } - } + assertMessagesAreReceived(); + LOG.info("" + data.length + " messages(s) received, closing down connections"); + } - protected void sendMessage(int index, Message message) throws Exception { + protected void sendMessages() throws Exception { + for (int i = 0; i < data.length; i++) { + Message message = createMessage(i); + configureMessage(message); + if (verbose) { + LOG.info("About to send a message: " + message + " with text: " + data[i]); + } + sendMessage(i, message); + } + } + + protected void sendMessage(int index, Message message) throws Exception { System.out.println("----sending a message to dest: " + producerDestination); - producer.send(producerDestination, message); - } + producer.send(producerDestination, message); + } - protected Message createMessage(int index) throws JMSException { - Message message = session.createTextMessage(data[index]); - return message; - } + protected Message createMessage(int index) throws JMSException { + Message message = session.createTextMessage(data[index]); + return message; + } - /** - * A hook to allow the message to be configured such as adding extra headers - * - * @throws JMSException - */ - protected void configureMessage(Message message) throws JMSException { - } + /** + * A hook to allow the message to be configured such as adding extra headers + * + * @throws JMSException + */ + protected void configureMessage(Message message) throws JMSException { + } - /** - * Waits to receive the messages and performs the test if all messages have - * been received and are in sequential order. - * - * @throws JMSException - */ - protected void assertMessagesAreReceived() throws JMSException { - waitForMessagesToBeDelivered(); - assertMessagesReceivedAreValid(messages); - } + /** + * Waits to receive the messages and performs the test if all messages have + * been received and are in sequential order. + * + * @throws JMSException + */ + protected void assertMessagesAreReceived() throws JMSException { + waitForMessagesToBeDelivered(); + assertMessagesReceivedAreValid(messages); + } - /** - * Tests if the messages have all been received and are in sequential order. - * - * @param receivedMessages - * @throws JMSException - */ - protected void assertMessagesReceivedAreValid(List receivedMessages) throws JMSException { - List copyOfMessages = Arrays.asList(receivedMessages.toArray()); - int counter = 0; + /** + * Tests if the messages have all been received and are in sequential order. + * + * @param receivedMessages + * @throws JMSException + */ + protected void assertMessagesReceivedAreValid(List receivedMessages) throws JMSException { + List copyOfMessages = Arrays.asList(receivedMessages.toArray()); + int counter = 0; - if (data.length != copyOfMessages.size()) { - for (Iterator iter = copyOfMessages.iterator(); iter.hasNext();) { - Object message = iter.next(); - LOG.info("<== " + counter++ + " = " + message); + if (data.length != copyOfMessages.size()) { + for (Iterator iter = copyOfMessages.iterator(); iter.hasNext(); ) { + Object message = iter.next(); + LOG.info("<== " + counter++ + " = " + message); + } + } + + assertEquals("Invalid number of messages received", data.length, receivedMessages.size()); + + for (int i = 0; i < data.length; i++) { + Message received = receivedMessages.get(i); + try { + assertMessageValid(i, received); + } + catch (AssertionFailedError e) { + for (int j = 0; j < data.length; j++) { + Message m = receivedMessages.get(j); + System.out.println(j + " => " + m.getJMSMessageID()); } - } + throw e; + } + } + } - assertEquals("Invalid number of messages received", data.length, receivedMessages.size()); + protected void assertMessageValid(int index, Message message) throws JMSException { + TextMessage textMessage = (TextMessage) message; + String text = textMessage.getText(); - for (int i = 0; i < data.length; i++) { - Message received = receivedMessages.get(i); + if (verbose) { + LOG.info("Received Text: " + text); + } + + assertEquals("Message: " + index, data[index], text); + } + + /** + * Waits for the messages to be delivered or when the wait time has been + * reached. + */ + protected void waitForMessagesToBeDelivered() { + long maxWaitTime = 60000; + long waitTime = maxWaitTime; + long start = (maxWaitTime <= 0) ? 0 : System.currentTimeMillis(); + + synchronized (lock) { + while (messages.size() < data.length && waitTime >= 0) { try { - assertMessageValid(i, received); - } catch (AssertionFailedError e) { - for (int j = 0; j < data.length; j++) { - Message m = receivedMessages.get(j); - System.out.println(j+" => "+m.getJMSMessageID()); - } - throw e; + lock.wait(200); } - } - } - - protected void assertMessageValid(int index, Message message) throws JMSException { - TextMessage textMessage = (TextMessage)message; - String text = textMessage.getText(); - - if (verbose) { - LOG.info("Received Text: " + text); - } - - assertEquals("Message: " + index, data[index], text); - } - - /** - * Waits for the messages to be delivered or when the wait time has been - * reached. - */ - protected void waitForMessagesToBeDelivered() { - long maxWaitTime = 60000; - long waitTime = maxWaitTime; - long start = (maxWaitTime <= 0) ? 0 : System.currentTimeMillis(); - - synchronized (lock) { - while (messages.size() < data.length && waitTime >= 0) { - try { - lock.wait(200); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - waitTime = maxWaitTime - (System.currentTimeMillis() - start); + catch (InterruptedException e) { + e.printStackTrace(); } - } - } - /** - * @see javax.jms.MessageListener#onMessage(javax.jms.Message) - */ - public synchronized void onMessage(Message message) { - consumeMessage(message, messages); - } + waitTime = maxWaitTime - (System.currentTimeMillis() - start); + } + } + } - /** - * Consumes a received message. - * - * @param message - a newly received message. - * @param messageList - list containing the received messages. - */ - protected void consumeMessage(Message message, List messageList) { - if (verbose) { - LOG.info("Received message: " + message); - } + /** + * @see javax.jms.MessageListener#onMessage(javax.jms.Message) + */ + public synchronized void onMessage(Message message) { + consumeMessage(message, messages); + } - messageList.add(message); + /** + * Consumes a received message. + * + * @param message - a newly received message. + * @param messageList - list containing the received messages. + */ + protected void consumeMessage(Message message, List messageList) { + if (verbose) { + LOG.info("Received message: " + message); + } - if (messageList.size() >= data.length) { - synchronized (lock) { - lock.notifyAll(); - } - } - } + messageList.add(message); - /** - * Creates a synchronized list. - * - * @return a synchronized view of the specified list. - */ - protected List createConcurrentList() { - return Collections.synchronizedList(new ArrayList()); - } + if (messageList.size() >= data.length) { + synchronized (lock) { + lock.notifyAll(); + } + } + } + + /** + * Creates a synchronized list. + * + * @return a synchronized view of the specified list. + */ + protected List createConcurrentList() { + return Collections.synchronizedList(new ArrayList()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveTest.java index 84cedeae3b..37cd85f169 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveTest.java @@ -27,93 +27,96 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class JmsTopicSendReceiveTest extends JmsSendReceiveTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(JmsTopicSendReceiveTest.class); - protected Connection connection; + private static final Logger LOG = LoggerFactory.getLogger(JmsTopicSendReceiveTest.class); - protected void setUp() throws Exception { - super.setUp(); + protected Connection connection; - connectionFactory = createConnectionFactory(); - connection = createConnection(); - if (durable) { - connection.setClientID(getClass().getName()); - } + protected void setUp() throws Exception { + super.setUp(); - LOG.info("Created connection: " + connection); + connectionFactory = createConnectionFactory(); + connection = createConnection(); + if (durable) { + connection.setClientID(getClass().getName()); + } - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumeSession = createConsumerSession(); + LOG.info("Created connection: " + connection); - LOG.info("Created session: " + session); - LOG.info("Created consumeSession: " + consumeSession); - producer = session.createProducer(null); - producer.setDeliveryMode(deliveryMode); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumeSession = createConsumerSession(); - LOG.info("Created producer: " + producer + " delivery mode = " + (deliveryMode == DeliveryMode.PERSISTENT ? "PERSISTENT" : "NON_PERSISTENT")); + LOG.info("Created session: " + session); + LOG.info("Created consumeSession: " + consumeSession); + producer = session.createProducer(null); + producer.setDeliveryMode(deliveryMode); - if (topic) { - consumerDestination = session.createTopic(getConsumerSubject()); - producerDestination = session.createTopic(getProducerSubject()); - } else { - consumerDestination = session.createQueue(getConsumerSubject()); - producerDestination = session.createQueue(getProducerSubject()); - } + LOG.info("Created producer: " + producer + " delivery mode = " + (deliveryMode == DeliveryMode.PERSISTENT ? "PERSISTENT" : "NON_PERSISTENT")); - LOG.info("Created consumer destination: " + consumerDestination + " of type: " + consumerDestination.getClass()); - LOG.info("Created producer destination: " + producerDestination + " of type: " + producerDestination.getClass()); - consumer = createConsumer(); - consumer.setMessageListener(this); - startConnection(); + if (topic) { + consumerDestination = session.createTopic(getConsumerSubject()); + producerDestination = session.createTopic(getProducerSubject()); + } + else { + consumerDestination = session.createQueue(getConsumerSubject()); + producerDestination = session.createQueue(getProducerSubject()); + } - LOG.info("Created connection: " + connection); - } + LOG.info("Created consumer destination: " + consumerDestination + " of type: " + consumerDestination.getClass()); + LOG.info("Created producer destination: " + producerDestination + " of type: " + producerDestination.getClass()); + consumer = createConsumer(); + consumer.setMessageListener(this); + startConnection(); - protected void startConnection() throws JMSException { - connection.start(); - } + LOG.info("Created connection: " + connection); + } - protected void tearDown() throws Exception { - LOG.info("Dumping stats..."); - // TODO - // connectionFactory.getFactoryStats().dump(new IndentPrinter()); + protected void startConnection() throws JMSException { + connection.start(); + } - LOG.info("Closing down connection"); + protected void tearDown() throws Exception { + LOG.info("Dumping stats..."); + // TODO + // connectionFactory.getFactoryStats().dump(new IndentPrinter()); - /** TODO we should be able to shut down properly */ - session.close(); - connection.close(); - } + LOG.info("Closing down connection"); - /** - * Creates a session. - * - * @return session - * @throws JMSException - */ - protected Session createConsumerSession() throws JMSException { - if (useSeparateSession) { - return connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } else { - return session; - } - } + /** TODO we should be able to shut down properly */ + session.close(); + connection.close(); + } - /** - * Creates a durable suscriber or a consumer. - * - * @return MessageConsumer - durable suscriber or consumer. - * @throws JMSException - */ - protected MessageConsumer createConsumer() throws JMSException { - if (durable) { - LOG.info("Creating durable consumer"); - return consumeSession.createDurableSubscriber((Topic)consumerDestination, getName()); - } - System.out.println(">>>>>>>creating cons on " + consumerDestination); - return consumeSession.createConsumer(consumerDestination); - } + /** + * Creates a session. + * + * @return session + * @throws JMSException + */ + protected Session createConsumerSession() throws JMSException { + if (useSeparateSession) { + return connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + } + else { + return session; + } + } + + /** + * Creates a durable suscriber or a consumer. + * + * @return MessageConsumer - durable suscriber or consumer. + * @throws JMSException + */ + protected MessageConsumer createConsumer() throws JMSException { + if (durable) { + LOG.info("Creating durable consumer"); + return consumeSession.createDurableSubscriber((Topic) consumerDestination, getName()); + } + System.out.println(">>>>>>>creating cons on " + consumerDestination); + return consumeSession.createConsumer(consumerDestination); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithEmbeddedBrokerAndUserIDTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithEmbeddedBrokerAndUserIDTest.java index aac150f023..f2cf9e33d6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithEmbeddedBrokerAndUserIDTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithEmbeddedBrokerAndUserIDTest.java @@ -30,82 +30,83 @@ import org.slf4j.LoggerFactory; * */ public class JmsTopicSendReceiveWithEmbeddedBrokerAndUserIDTest extends JmsTopicSendReceiveWithTwoConnectionsAndEmbeddedBrokerTest { - private static final Logger LOG = LoggerFactory.getLogger(JmsTopicSendReceiveWithEmbeddedBrokerAndUserIDTest.class); - protected String userName = "James"; + private static final Logger LOG = LoggerFactory.getLogger(JmsTopicSendReceiveWithEmbeddedBrokerAndUserIDTest.class); - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory answer = super.createConnectionFactory(); - answer.setUserName(userName); - return answer; - } + protected String userName = "James"; - @Override - protected void configureBroker(BrokerService answer) throws Exception { - answer.setPopulateJMSXUserID(true); - super.configureBroker(answer); - } + @Override + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory answer = super.createConnectionFactory(); + answer.setUserName(userName); + return answer; + } - @Override - protected void assertMessagesReceivedAreValid(List receivedMessages) throws JMSException { - super.assertMessagesReceivedAreValid(receivedMessages); + @Override + protected void configureBroker(BrokerService answer) throws Exception { + answer.setPopulateJMSXUserID(true); + super.configureBroker(answer); + } - // lets assert that the user ID is set - for (Message message : receivedMessages) { - String userID = message.getStringProperty("JMSXUserID"); - LOG.info("Received message with userID: " + userID); - assertEquals("JMSXUserID header", userName, userID); - } - } + @Override + protected void assertMessagesReceivedAreValid(List receivedMessages) throws JMSException { + super.assertMessagesReceivedAreValid(receivedMessages); - protected void assertMessagesAreReceived2() throws JMSException { - waitForMessagesToBeDelivered(); - assertMessagesReceivedAreValid2(messages); - } + // lets assert that the user ID is set + for (Message message : receivedMessages) { + String userID = message.getStringProperty("JMSXUserID"); + LOG.info("Received message with userID: " + userID); + assertEquals("JMSXUserID header", userName, userID); + } + } - protected void assertMessagesReceivedAreValid2(List receivedMessages) throws JMSException { - super.assertMessagesReceivedAreValid(receivedMessages); + protected void assertMessagesAreReceived2() throws JMSException { + waitForMessagesToBeDelivered(); + assertMessagesReceivedAreValid2(messages); + } - // lets assert that the user ID is set - for (Message message : receivedMessages) { - String userID = (String) message.getObjectProperty("JMSXUserID"); - LOG.info("Received message with userID: " + userID); - assertEquals("JMSXUserID header", userName, userID); - } - } + protected void assertMessagesReceivedAreValid2(List receivedMessages) throws JMSException { + super.assertMessagesReceivedAreValid(receivedMessages); - public void testSpoofedJMSXUserIdIsIgnored() throws Exception { - Thread.sleep(1000); - messages.clear(); + // lets assert that the user ID is set + for (Message message : receivedMessages) { + String userID = (String) message.getObjectProperty("JMSXUserID"); + LOG.info("Received message with userID: " + userID); + assertEquals("JMSXUserID header", userName, userID); + } + } - for (int i = 0; i < data.length; i++) { - Message message = createMessage(i); - configureMessage(message); - message.setStringProperty("JMSXUserID", "spoofedId"); - if (verbose) { - LOG.info("About to send a message: " + message + " with text: " + data[i]); - } - sendMessage(i, message); - } - assertMessagesAreReceived(); - LOG.info("" + data.length + " messages(s) received, closing down connections"); - } + public void testSpoofedJMSXUserIdIsIgnored() throws Exception { + Thread.sleep(1000); + messages.clear(); - public void testSpoofedJMSXUserIdIsIgnoredAsObjectProperty() throws Exception { - Thread.sleep(1000); - messages.clear(); + for (int i = 0; i < data.length; i++) { + Message message = createMessage(i); + configureMessage(message); + message.setStringProperty("JMSXUserID", "spoofedId"); + if (verbose) { + LOG.info("About to send a message: " + message + " with text: " + data[i]); + } + sendMessage(i, message); + } + assertMessagesAreReceived(); + LOG.info("" + data.length + " messages(s) received, closing down connections"); + } - for (int i = 0; i < data.length; i++) { - Message message = createMessage(i); - configureMessage(message); - message.setStringProperty("JMSXUserID", "spoofedId"); - if (verbose) { - LOG.info("About to send a message: " + message + " with text: " + data[i]); - } - sendMessage(i, message); - } - assertMessagesAreReceived2(); - LOG.info("" + data.length + " messages(s) received, closing down connections"); - } + public void testSpoofedJMSXUserIdIsIgnoredAsObjectProperty() throws Exception { + Thread.sleep(1000); + messages.clear(); + + for (int i = 0; i < data.length; i++) { + Message message = createMessage(i); + configureMessage(message); + message.setStringProperty("JMSXUserID", "spoofedId"); + if (verbose) { + LOG.info("About to send a message: " + message + " with text: " + data[i]); + } + sendMessage(i, message); + } + assertMessagesAreReceived2(); + LOG.info("" + data.length + " messages(s) received, closing down connections"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithTwoConnectionsAndByteSelectorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithTwoConnectionsAndByteSelectorTest.java index 78a7f6f0e8..11b313a77a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithTwoConnectionsAndByteSelectorTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithTwoConnectionsAndByteSelectorTest.java @@ -21,17 +21,16 @@ import javax.jms.Message; import javax.jms.MessageConsumer; /** - * + * */ public class JmsTopicSendReceiveWithTwoConnectionsAndByteSelectorTest extends JmsTopicSendReceiveWithTwoConnectionsTest { - - protected void configureMessage(Message message) throws JMSException { - message.setByteProperty("dummy", (byte) 33); - } + protected void configureMessage(Message message) throws JMSException { + message.setByteProperty("dummy", (byte) 33); + } - protected MessageConsumer createConsumer() throws JMSException { - return receiveSession.createConsumer(consumerDestination, "dummy = 33", false); - } + protected MessageConsumer createConsumer() throws JMSException { + return receiveSession.createConsumer(consumerDestination, "dummy = 33", false); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithTwoConnectionsAndEmbeddedBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithTwoConnectionsAndEmbeddedBrokerTest.java index 6bd92df8b5..4385242fed 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithTwoConnectionsAndEmbeddedBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithTwoConnectionsAndEmbeddedBrokerTest.java @@ -20,50 +20,50 @@ import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; /** - * + * */ public class JmsTopicSendReceiveWithTwoConnectionsAndEmbeddedBrokerTest extends JmsTopicSendReceiveWithTwoConnectionsTest { - protected BrokerService broker; - protected String bindAddress = "tcp://localhost:61616"; + protected BrokerService broker; + protected String bindAddress = "tcp://localhost:61616"; - /** - * Sets up a test where the producer and consumer have their own connection. - * - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception { - if (broker == null) { - broker = createBroker(); - } - super.setUp(); - } + /** + * Sets up a test where the producer and consumer have their own connection. + * + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + if (broker == null) { + broker = createBroker(); + } + super.setUp(); + } - protected void tearDown() throws Exception { - super.tearDown(); + protected void tearDown() throws Exception { + super.tearDown(); - if (broker != null) { - broker.stop(); - } - } + if (broker != null) { + broker.stop(); + } + } - /** - * Factory method to create a new broker - * - * @throws Exception - */ - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - configureBroker(answer); - answer.start(); - return answer; - } + /** + * Factory method to create a new broker + * + * @throws Exception + */ + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + configureBroker(answer); + answer.start(); + return answer; + } - protected void configureBroker(BrokerService answer) throws Exception { - answer.addConnector(bindAddress); - } + protected void configureBroker(BrokerService answer) throws Exception { + answer.addConnector(bindAddress); + } - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(bindAddress); - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory(bindAddress); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithTwoConnectionsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithTwoConnectionsTest.java index 21a3575990..39c9a17984 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithTwoConnectionsTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithTwoConnectionsTest.java @@ -27,107 +27,108 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class JmsTopicSendReceiveWithTwoConnectionsTest extends JmsSendReceiveTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(JmsTopicSendReceiveWithTwoConnectionsTest.class); + private static final Logger LOG = LoggerFactory.getLogger(JmsTopicSendReceiveWithTwoConnectionsTest.class); - protected Connection sendConnection; - protected Connection receiveConnection; - protected Session receiveSession; + protected Connection sendConnection; + protected Connection receiveConnection; + protected Session receiveSession; - /** - * Sets up a test where the producer and consumer have their own connection. - * - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); + /** + * Sets up a test where the producer and consumer have their own connection. + * + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); - connectionFactory = createConnectionFactory(); + connectionFactory = createConnectionFactory(); - LOG.info("Creating send connection"); - sendConnection = createSendConnection(); - LOG.info("Starting send connection"); - sendConnection.start(); + LOG.info("Creating send connection"); + sendConnection = createSendConnection(); + LOG.info("Starting send connection"); + sendConnection.start(); - LOG.info("Creating receive connection"); - receiveConnection = createReceiveConnection(); - LOG.info("Starting receive connection"); - receiveConnection.start(); + LOG.info("Creating receive connection"); + receiveConnection = createReceiveConnection(); + LOG.info("Starting receive connection"); + receiveConnection.start(); - LOG.info("Created sendConnection: " + sendConnection); - LOG.info("Created receiveConnection: " + receiveConnection); + LOG.info("Created sendConnection: " + sendConnection); + LOG.info("Created receiveConnection: " + receiveConnection); - session = sendConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - receiveSession = receiveConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + session = sendConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + receiveSession = receiveConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - LOG.info("Created sendSession: " + session); - LOG.info("Created receiveSession: " + receiveSession); + LOG.info("Created sendSession: " + session); + LOG.info("Created receiveSession: " + receiveSession); - producer = session.createProducer(null); - producer.setDeliveryMode(deliveryMode); + producer = session.createProducer(null); + producer.setDeliveryMode(deliveryMode); - LOG.info("Created producer: " + producer + " delivery mode = " + (deliveryMode == DeliveryMode.PERSISTENT ? "PERSISTENT" : "NON_PERSISTENT")); + LOG.info("Created producer: " + producer + " delivery mode = " + (deliveryMode == DeliveryMode.PERSISTENT ? "PERSISTENT" : "NON_PERSISTENT")); - if (topic) { - consumerDestination = session.createTopic(getConsumerSubject()); - producerDestination = session.createTopic(getProducerSubject()); - } else { - consumerDestination = session.createQueue(getConsumerSubject()); - producerDestination = session.createQueue(getProducerSubject()); - } + if (topic) { + consumerDestination = session.createTopic(getConsumerSubject()); + producerDestination = session.createTopic(getProducerSubject()); + } + else { + consumerDestination = session.createQueue(getConsumerSubject()); + producerDestination = session.createQueue(getProducerSubject()); + } - LOG.info("Created consumer destination: " + consumerDestination + " of type: " + consumerDestination.getClass()); - LOG.info("Created producer destination: " + producerDestination + " of type: " + producerDestination.getClass()); + LOG.info("Created consumer destination: " + consumerDestination + " of type: " + consumerDestination.getClass()); + LOG.info("Created producer destination: " + producerDestination + " of type: " + producerDestination.getClass()); - consumer = createConsumer(); - consumer.setMessageListener(this); + consumer = createConsumer(); + consumer.setMessageListener(this); - LOG.info("Started connections"); - } + LOG.info("Started connections"); + } - protected MessageConsumer createConsumer() throws JMSException { - return receiveSession.createConsumer(consumerDestination); - } + protected MessageConsumer createConsumer() throws JMSException { + return receiveSession.createConsumer(consumerDestination); + } - /* - * @see junit.framework.TestCase#tearDown() - */ - protected void tearDown() throws Exception { - session.close(); - receiveSession.close(); - sendConnection.close(); - receiveConnection.close(); - } + /* + * @see junit.framework.TestCase#tearDown() + */ + protected void tearDown() throws Exception { + session.close(); + receiveSession.close(); + sendConnection.close(); + receiveConnection.close(); + } - /** - * Creates a connection. - * - * @return Connection - * @throws Exception - */ - protected Connection createReceiveConnection() throws Exception { - return createConnection(); - } + /** + * Creates a connection. + * + * @return Connection + * @throws Exception + */ + protected Connection createReceiveConnection() throws Exception { + return createConnection(); + } - /** - * Creates a connection. - * - * @return Connection - * @throws Exception - */ - protected Connection createSendConnection() throws Exception { - return createConnection(); - } + /** + * Creates a connection. + * + * @return Connection + * @throws Exception + */ + protected Connection createSendConnection() throws Exception { + return createConnection(); + } - /** - * Creates an ActiveMQConnectionFactory. - * - * @see org.apache.activemq.test.TestSupport#createConnectionFactory() - */ - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); - } + /** + * Creates an ActiveMQConnectionFactory. + * + * @see org.apache.activemq.test.TestSupport#createConnectionFactory() + */ + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/TemporaryDestinationToFromNameTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/TemporaryDestinationToFromNameTest.java index 4dc008859e..c40b813af5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/TemporaryDestinationToFromNameTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/TemporaryDestinationToFromNameTest.java @@ -26,33 +26,33 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class TemporaryDestinationToFromNameTest extends EmbeddedBrokerAndConnectionTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(TemporaryDestinationToFromNameTest.class); + private static final Logger LOG = LoggerFactory.getLogger(TemporaryDestinationToFromNameTest.class); - public void testCreateTemporaryQueueThenCreateAQueueFromItsName() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + public void testCreateTemporaryQueueThenCreateAQueueFromItsName() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue tempQueue = session.createTemporaryQueue(); - String name = tempQueue.getQueueName(); - LOG.info("Created queue named: " + name); + Queue tempQueue = session.createTemporaryQueue(); + String name = tempQueue.getQueueName(); + LOG.info("Created queue named: " + name); - Queue createdQueue = session.createQueue(name); + Queue createdQueue = session.createQueue(name); - assertEquals("created queue not equal to temporary queue", tempQueue, createdQueue); - } + assertEquals("created queue not equal to temporary queue", tempQueue, createdQueue); + } - public void testCreateTemporaryTopicThenCreateATopicFromItsName() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + public void testCreateTemporaryTopicThenCreateATopicFromItsName() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Topic tempTopic = session.createTemporaryTopic(); - String name = tempTopic.getTopicName(); - LOG.info("Created topic named: " + name); + Topic tempTopic = session.createTemporaryTopic(); + String name = tempTopic.getTopicName(); + LOG.info("Created topic named: " + name); - Topic createdTopic = session.createTopic(name); + Topic createdTopic = session.createTopic(name); - assertEquals("created topic not equal to temporary topic", tempTopic, createdTopic); - } + assertEquals("created topic not equal to temporary topic", tempTopic, createdTopic); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/message/NestedMapAndListPropertyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/message/NestedMapAndListPropertyTest.java index bf83d0ae9e..291e4de9c7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/message/NestedMapAndListPropertyTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/message/NestedMapAndListPropertyTest.java @@ -30,66 +30,65 @@ import org.slf4j.LoggerFactory; /** * Tests that a Message can have nested Map and List properties attached. - * */ public class NestedMapAndListPropertyTest extends JmsTopicSendReceiveWithTwoConnectionsAndEmbeddedBrokerTest { - private static final Logger LOG = LoggerFactory.getLogger(NestedMapAndListPropertyTest.class); + private static final Logger LOG = LoggerFactory.getLogger(NestedMapAndListPropertyTest.class); - @Override - @SuppressWarnings("rawtypes") - protected void assertMessageValid(int index, Message message) throws JMSException { - Object value = message.getObjectProperty("textField"); - assertEquals("textField", data[index], value); + @Override + @SuppressWarnings("rawtypes") + protected void assertMessageValid(int index, Message message) throws JMSException { + Object value = message.getObjectProperty("textField"); + assertEquals("textField", data[index], value); - Map map = (Map)message.getObjectProperty("mapField"); - assertNotNull(map); - assertEquals("mapField.a", "foo", map.get("a")); - assertEquals("mapField.b", new Integer(23), map.get("b")); - assertEquals("mapField.c", new Long(45), map.get("c")); + Map map = (Map) message.getObjectProperty("mapField"); + assertNotNull(map); + assertEquals("mapField.a", "foo", map.get("a")); + assertEquals("mapField.b", new Integer(23), map.get("b")); + assertEquals("mapField.c", new Long(45), map.get("c")); - value = map.get("d"); - assertTrue("mapField.d should be a Map", value instanceof Map); - map = (Map)value; + value = map.get("d"); + assertTrue("mapField.d should be a Map", value instanceof Map); + map = (Map) value; - assertEquals("mapField.d.x", "abc", map.get("x")); - value = map.get("y"); - assertTrue("mapField.d.y is a List", value instanceof List); - List list = (List)value; - LOG.debug("mapField.d.y: " + list); - assertEquals("listField.size", 3, list.size()); + assertEquals("mapField.d.x", "abc", map.get("x")); + value = map.get("y"); + assertTrue("mapField.d.y is a List", value instanceof List); + List list = (List) value; + LOG.debug("mapField.d.y: " + list); + assertEquals("listField.size", 3, list.size()); - LOG.debug("Found map: " + map); + LOG.debug("Found map: " + map); - list = (List)message.getObjectProperty("listField"); - LOG.debug("listField: " + list); - assertEquals("listField.size", 3, list.size()); - assertEquals("listField[0]", "a", list.get(0)); - assertEquals("listField[1]", "b", list.get(1)); - assertEquals("listField[2]", "c", list.get(2)); - assertEquals("JohnDoe", message.getStringProperty("JMSXUserID")); - } + list = (List) message.getObjectProperty("listField"); + LOG.debug("listField: " + list); + assertEquals("listField.size", 3, list.size()); + assertEquals("listField[0]", "a", list.get(0)); + assertEquals("listField[1]", "b", list.get(1)); + assertEquals("listField[2]", "c", list.get(2)); + assertEquals("JohnDoe", message.getStringProperty("JMSXUserID")); + } - @Override - protected Message createMessage(int index) throws JMSException { - Message answer = session.createMessage(); + @Override + protected Message createMessage(int index) throws JMSException { + Message answer = session.createMessage(); - answer.setStringProperty("textField", data[index]); + answer.setStringProperty("textField", data[index]); - Map grandChildMap = new HashMap(); - grandChildMap.put("x", "abc"); - grandChildMap.put("y", Arrays.asList(new Object[] {"a", "b", "c"})); + Map grandChildMap = new HashMap(); + grandChildMap.put("x", "abc"); + grandChildMap.put("y", Arrays.asList(new Object[]{"a", "b", "c"})); - Map nestedMap = new HashMap(); - nestedMap.put("a", "foo"); - nestedMap.put("b", new Integer(23)); - nestedMap.put("c", new Long(45)); - nestedMap.put("d", grandChildMap); + Map nestedMap = new HashMap(); + nestedMap.put("a", "foo"); + nestedMap.put("b", new Integer(23)); + nestedMap.put("c", new Long(45)); + nestedMap.put("d", grandChildMap); - answer.setObjectProperty("mapField", nestedMap); - answer.setObjectProperty("listField", Arrays.asList(new Object[] {"a", "b", "c"})); - answer.setStringProperty("JMSXUserID", "JohnDoe"); + answer.setObjectProperty("mapField", nestedMap); + answer.setObjectProperty("listField", Arrays.asList(new Object[]{"a", "b", "c"})); + answer.setStringProperty("JMSXUserID", "JohnDoe"); - return answer; - } + return answer; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/message/NestedMapMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/message/NestedMapMessageTest.java index f0131ce068..062cbab9f4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/message/NestedMapMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/message/NestedMapMessageTest.java @@ -34,65 +34,65 @@ import org.slf4j.LoggerFactory; */ public class NestedMapMessageTest extends JmsTopicSendReceiveWithTwoConnectionsAndEmbeddedBrokerTest { - private static final Logger LOG = LoggerFactory.getLogger(NestedMapMessageTest.class); + private static final Logger LOG = LoggerFactory.getLogger(NestedMapMessageTest.class); - @Override - @SuppressWarnings("rawtypes") - protected void assertMessageValid(int index, Message message) throws JMSException { - assertTrue("Should be a MapMessage: " + message, message instanceof MapMessage); + @Override + @SuppressWarnings("rawtypes") + protected void assertMessageValid(int index, Message message) throws JMSException { + assertTrue("Should be a MapMessage: " + message, message instanceof MapMessage); - MapMessage mapMessage = (MapMessage)message; + MapMessage mapMessage = (MapMessage) message; - Object value = mapMessage.getObject("textField"); - assertEquals("textField", data[index], value); + Object value = mapMessage.getObject("textField"); + assertEquals("textField", data[index], value); - Map map = (Map)mapMessage.getObject("mapField"); - assertNotNull(map); - assertEquals("mapField.a", "foo", map.get("a")); - assertEquals("mapField.b", Integer.valueOf(23), map.get("b")); - assertEquals("mapField.c", Long.valueOf(45), map.get("c")); + Map map = (Map) mapMessage.getObject("mapField"); + assertNotNull(map); + assertEquals("mapField.a", "foo", map.get("a")); + assertEquals("mapField.b", Integer.valueOf(23), map.get("b")); + assertEquals("mapField.c", Long.valueOf(45), map.get("c")); - value = map.get("d"); - assertTrue("mapField.d should be a Map", value instanceof Map); - map = (Map)value; + value = map.get("d"); + assertTrue("mapField.d should be a Map", value instanceof Map); + map = (Map) value; - assertEquals("mapField.d.x", "abc", map.get("x")); - value = map.get("y"); - assertTrue("mapField.d.y is a List", value instanceof List); - List list = (List)value; - LOG.debug("mapField.d.y: " + list); - assertEquals("listField.size", 3, list.size()); + assertEquals("mapField.d.x", "abc", map.get("x")); + value = map.get("y"); + assertTrue("mapField.d.y is a List", value instanceof List); + List list = (List) value; + LOG.debug("mapField.d.y: " + list); + assertEquals("listField.size", 3, list.size()); - LOG.debug("Found map: " + map); + LOG.debug("Found map: " + map); - list = (List)mapMessage.getObject("listField"); - LOG.debug("listField: " + list); - assertEquals("listField.size", 3, list.size()); - assertEquals("listField[0]", "a", list.get(0)); - assertEquals("listField[1]", "b", list.get(1)); - assertEquals("listField[2]", "c", list.get(2)); - } + list = (List) mapMessage.getObject("listField"); + LOG.debug("listField: " + list); + assertEquals("listField.size", 3, list.size()); + assertEquals("listField[0]", "a", list.get(0)); + assertEquals("listField[1]", "b", list.get(1)); + assertEquals("listField[2]", "c", list.get(2)); + } - @Override - protected Message createMessage(int index) throws JMSException { - MapMessage answer = session.createMapMessage(); + @Override + protected Message createMessage(int index) throws JMSException { + MapMessage answer = session.createMapMessage(); - answer.setString("textField", data[index]); + answer.setString("textField", data[index]); - Map grandChildMap = new HashMap(); - grandChildMap.put("x", "abc"); - grandChildMap.put("y", Arrays.asList(new Object[] {"a", "b", "c"})); + Map grandChildMap = new HashMap(); + grandChildMap.put("x", "abc"); + grandChildMap.put("y", Arrays.asList(new Object[]{"a", "b", "c"})); - Map nestedMap = new HashMap(); - nestedMap.put("a", "foo"); - nestedMap.put("b", Integer.valueOf(23)); - nestedMap.put("c", Long.valueOf(45)); - nestedMap.put("d", grandChildMap); + Map nestedMap = new HashMap(); + nestedMap.put("a", "foo"); + nestedMap.put("b", Integer.valueOf(23)); + nestedMap.put("c", Long.valueOf(45)); + nestedMap.put("d", grandChildMap); - answer.setObject("mapField", nestedMap); - answer.setObject("listField", Arrays.asList(new Object[] {"a", "b", "c"})); + answer.setObject("mapField", nestedMap); + answer.setObject("listField", Arrays.asList(new Object[]{"a", "b", "c"})); - return answer; - } + return answer; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/DummyMessageQuery.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/DummyMessageQuery.java index 98f547cc72..36fd73738a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/DummyMessageQuery.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/DummyMessageQuery.java @@ -27,24 +27,23 @@ import org.slf4j.LoggerFactory; /** * - * + * */ public class DummyMessageQuery implements MessageQuery { - - public static final int MESSAGE_COUNT = 10; - private static final Logger LOG = LoggerFactory.getLogger(DummyMessageQuery.class); - - public void execute(ActiveMQDestination destination, MessageListener listener) throws Exception { - LOG.info("Initial query is creating: " + MESSAGE_COUNT + " messages"); - for (int i = 0; i < MESSAGE_COUNT; i++) { - ActiveMQTextMessage message = new ActiveMQTextMessage(); - message.setText("Initial message: " + i + " loaded from query"); - listener.onMessage(message); - } - } + public static final int MESSAGE_COUNT = 10; + private static final Logger LOG = LoggerFactory.getLogger(DummyMessageQuery.class); - public boolean validateUpdate(Message message) { - return true; - } + public void execute(ActiveMQDestination destination, MessageListener listener) throws Exception { + LOG.info("Initial query is creating: " + MESSAGE_COUNT + " messages"); + for (int i = 0; i < MESSAGE_COUNT; i++) { + ActiveMQTextMessage message = new ActiveMQTextMessage(); + message.setText("Initial message: " + i + " loaded from query"); + listener.onMessage(message); + } + } + + public boolean validateUpdate(Message message) { + return true; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithDestinationBasedBufferTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithDestinationBasedBufferTest.java index 0248109ac8..4ca9af1349 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithDestinationBasedBufferTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithDestinationBasedBufferTest.java @@ -18,10 +18,11 @@ package org.apache.activemq.test.retroactive; /** * - * + * */ public class RetroactiveConsumerTestWithDestinationBasedBufferTest extends RetroactiveConsumerTestWithSimpleMessageListTest { - protected String getBrokerXml() { - return "org/apache/activemq/test/retroactive/activemq-fixed-destination-buffer.xml"; - } + + protected String getBrokerXml() { + return "org/apache/activemq/test/retroactive/activemq-fixed-destination-buffer.xml"; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithLastImagePolicyWithWildcardTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithLastImagePolicyWithWildcardTest.java index d34189a735..3ace7128b4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithLastImagePolicyWithWildcardTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithLastImagePolicyWithWildcardTest.java @@ -24,25 +24,26 @@ import javax.jms.TextMessage; import org.apache.activemq.command.ActiveMQTopic; /** - * + * */ public class RetroactiveConsumerTestWithLastImagePolicyWithWildcardTest extends RetroactiveConsumerTestWithSimpleMessageListTest { - private int counter = 1; - protected void sendMessage(MessageProducer producer, TextMessage message) throws JMSException { - ActiveMQTopic topic = new ActiveMQTopic(destination.getPhysicalName() + "." + (counter++)); - producer.send(topic, message); - } + private int counter = 1; - protected MessageProducer createProducer() throws JMSException { - return session.createProducer(null); - } + protected void sendMessage(MessageProducer producer, TextMessage message) throws JMSException { + ActiveMQTopic topic = new ActiveMQTopic(destination.getPhysicalName() + "." + (counter++)); + producer.send(topic, message); + } - protected MessageConsumer createConsumer() throws JMSException { - return session.createConsumer(new ActiveMQTopic(destination.getPhysicalName() + ".>")); - } + protected MessageProducer createProducer() throws JMSException { + return session.createProducer(null); + } - protected String getBrokerXml() { - return "org/apache/activemq/test/retroactive/activemq-lastimage-policy.xml"; - } + protected MessageConsumer createConsumer() throws JMSException { + return session.createConsumer(new ActiveMQTopic(destination.getPhysicalName() + ".>")); + } + + protected String getBrokerXml() { + return "org/apache/activemq/test/retroactive/activemq-lastimage-policy.xml"; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithSimpleMessageListTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithSimpleMessageListTest.java index ecc6bde940..dbfc7f7189 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithSimpleMessageListTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithSimpleMessageListTest.java @@ -39,89 +39,90 @@ import org.slf4j.LoggerFactory; * */ public class RetroactiveConsumerTestWithSimpleMessageListTest extends EmbeddedBrokerTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(RetroactiveConsumerTestWithSimpleMessageListTest.class); - protected int messageCount = 20; - protected Connection connection; - protected Session session; + private static final Logger LOG = LoggerFactory.getLogger(RetroactiveConsumerTestWithSimpleMessageListTest.class); - public void testSendThenConsume() throws Exception { + protected int messageCount = 20; + protected Connection connection; + protected Session session; - // lets some messages - connection = createConnection(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = createProducer(); - for (int i = 0; i < messageCount; i++) { - TextMessage message = session.createTextMessage("Message: " + i + " sent at: " + new Date()); - sendMessage(producer, message); - } - producer.close(); - session.close(); - connection.close(); + public void testSendThenConsume() throws Exception { - connection = createConnection(); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + // lets some messages + connection = createConnection(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = createProducer(); + for (int i = 0; i < messageCount; i++) { + TextMessage message = session.createTextMessage("Message: " + i + " sent at: " + new Date()); + sendMessage(producer, message); + } + producer.close(); + session.close(); + connection.close(); - MessageConsumer consumer = createConsumer(); - MessageIdList listener = new MessageIdList(); - consumer.setMessageListener(listener); - listener.waitForMessagesToArrive(messageCount); - listener.assertMessagesReceived(messageCount); + connection = createConnection(); + connection.start(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } + MessageConsumer consumer = createConsumer(); + MessageIdList listener = new MessageIdList(); + consumer.setMessageListener(listener); + listener.waitForMessagesToArrive(messageCount); + listener.assertMessagesReceived(messageCount); - @Override - protected void setUp() throws Exception { - useTopic = true; - bindAddress = "vm://localhost"; - super.setUp(); - } + } - @Override - protected void tearDown() throws Exception { - if (session != null) { - session.close(); - session = null; - } - if (connection != null) { - connection.close(); - } - super.tearDown(); - } + @Override + protected void setUp() throws Exception { + useTopic = true; + bindAddress = "vm://localhost"; + super.setUp(); + } - @Override - protected ConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory answer = new ActiveMQConnectionFactory(bindAddress); - answer.setUseRetroactiveConsumer(true); - return answer; - } + @Override + protected void tearDown() throws Exception { + if (session != null) { + session.close(); + session = null; + } + if (connection != null) { + connection.close(); + } + super.tearDown(); + } - @Override - protected BrokerService createBroker() throws Exception { - String uri = getBrokerXml(); - LOG.info("Loading broker configuration from the classpath with URI: " + uri); - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } + @Override + protected ConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory answer = new ActiveMQConnectionFactory(bindAddress); + answer.setUseRetroactiveConsumer(true); + return answer; + } - @Override - protected void startBroker() throws Exception { - // broker already started by XBean - } + @Override + protected BrokerService createBroker() throws Exception { + String uri = getBrokerXml(); + LOG.info("Loading broker configuration from the classpath with URI: " + uri); + return BrokerFactory.createBroker(new URI("xbean:" + uri)); + } - protected String getBrokerXml() { - return "org/apache/activemq/test/retroactive/activemq-fixed-buffer.xml"; - } + @Override + protected void startBroker() throws Exception { + // broker already started by XBean + } - protected MessageProducer createProducer() throws JMSException { - return session.createProducer(destination); - } + protected String getBrokerXml() { + return "org/apache/activemq/test/retroactive/activemq-fixed-buffer.xml"; + } - protected void sendMessage(MessageProducer producer, TextMessage message) throws JMSException { - producer.send(message); - } + protected MessageProducer createProducer() throws JMSException { + return session.createProducer(destination); + } - protected MessageConsumer createConsumer() throws JMSException { - return session.createConsumer(destination); - } + protected void sendMessage(MessageProducer producer, TextMessage message) throws JMSException { + producer.send(message); + } + + protected MessageConsumer createConsumer() throws JMSException { + return session.createConsumer(destination); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithTimePolicyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithTimePolicyTest.java index bb99b5d00a..463d25e9b7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithTimePolicyTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithTimePolicyTest.java @@ -18,10 +18,11 @@ package org.apache.activemq.test.retroactive; /** * - * + * */ public class RetroactiveConsumerTestWithTimePolicyTest extends RetroactiveConsumerTestWithSimpleMessageListTest { - protected String getBrokerXml() { - return "org/apache/activemq/test/retroactive/activemq-timed-policy.xml"; - } + + protected String getBrokerXml() { + return "org/apache/activemq/test/retroactive/activemq-timed-policy.xml"; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerWithMessageQueryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerWithMessageQueryTest.java index 2631619644..7e9188c3de 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerWithMessageQueryTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerWithMessageQueryTest.java @@ -38,77 +38,78 @@ import org.slf4j.LoggerFactory; * */ public class RetroactiveConsumerWithMessageQueryTest extends EmbeddedBrokerTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(RetroactiveConsumerWithMessageQueryTest.class); - protected int messageCount = 20; - protected Connection connection; - protected Session session; + private static final Logger LOG = LoggerFactory.getLogger(RetroactiveConsumerWithMessageQueryTest.class); - public void testConsumeAndReceiveInitialQueryBeforeUpdates() throws Exception { + protected int messageCount = 20; + protected Connection connection; + protected Session session; - // lets some messages - connection = createConnection(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - connection.start(); + public void testConsumeAndReceiveInitialQueryBeforeUpdates() throws Exception { - MessageConsumer consumer = session.createConsumer(destination); - MessageIdList listener = new MessageIdList(); - listener.setVerbose(true); - consumer.setMessageListener(listener); + // lets some messages + connection = createConnection(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + connection.start(); - MessageProducer producer = session.createProducer(destination); - int updateMessageCount = messageCount - DummyMessageQuery.MESSAGE_COUNT; - for (int i = 0; i < updateMessageCount; i++) { - TextMessage message = session.createTextMessage("Update Message: " + i + " sent at: " + new Date()); - producer.send(message); - } - producer.close(); - LOG.info("Sent: " + updateMessageCount + " update messages"); + MessageConsumer consumer = session.createConsumer(destination); + MessageIdList listener = new MessageIdList(); + listener.setVerbose(true); + consumer.setMessageListener(listener); - listener.assertMessagesReceived(messageCount); - } + MessageProducer producer = session.createProducer(destination); + int updateMessageCount = messageCount - DummyMessageQuery.MESSAGE_COUNT; + for (int i = 0; i < updateMessageCount; i++) { + TextMessage message = session.createTextMessage("Update Message: " + i + " sent at: " + new Date()); + producer.send(message); + } + producer.close(); + LOG.info("Sent: " + updateMessageCount + " update messages"); - @Override - protected void setUp() throws Exception { - useTopic = true; - bindAddress = "vm://localhost"; - super.setUp(); - } + listener.assertMessagesReceived(messageCount); + } - @Override - protected void tearDown() throws Exception { - if (session != null) { - session.close(); - session = null; - } - if (connection != null) { - connection.close(); - } - super.tearDown(); - } + @Override + protected void setUp() throws Exception { + useTopic = true; + bindAddress = "vm://localhost"; + super.setUp(); + } - @Override - protected ConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory answer = new ActiveMQConnectionFactory(bindAddress); - // answer.setUseRetroactiveConsumer(true); - // option applied via destination policy alwaysRetroactive - return answer; - } + @Override + protected void tearDown() throws Exception { + if (session != null) { + session.close(); + session = null; + } + if (connection != null) { + connection.close(); + } + super.tearDown(); + } - @Override - protected BrokerService createBroker() throws Exception { - String uri = getBrokerXml(); - LOG.info("Loading broker configuration from the classpath with URI: " + uri); - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } + @Override + protected ConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory answer = new ActiveMQConnectionFactory(bindAddress); + // answer.setUseRetroactiveConsumer(true); + // option applied via destination policy alwaysRetroactive + return answer; + } - @Override - protected void startBroker() throws Exception { - // broker already started by XBean - } + @Override + protected BrokerService createBroker() throws Exception { + String uri = getBrokerXml(); + LOG.info("Loading broker configuration from the classpath with URI: " + uri); + return BrokerFactory.createBroker(new URI("xbean:" + uri)); + } - protected String getBrokerXml() { - return "org/apache/activemq/test/retroactive/activemq-message-query.xml"; - } + @Override + protected void startBroker() throws Exception { + // broker already started by XBean + } + + protected String getBrokerXml() { + return "org/apache/activemq/test/retroactive/activemq-message-query.xml"; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/rollback/CloseRollbackRedeliveryQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/rollback/CloseRollbackRedeliveryQueueTest.java index 26725a64f8..ea80c08f36 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/rollback/CloseRollbackRedeliveryQueueTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/rollback/CloseRollbackRedeliveryQueueTest.java @@ -32,103 +32,103 @@ import org.springframework.jms.core.MessageCreator; public class CloseRollbackRedeliveryQueueTest extends EmbeddedBrokerTestSupport { - private static final transient Logger LOG = LoggerFactory.getLogger(CloseRollbackRedeliveryQueueTest.class); + private static final transient Logger LOG = LoggerFactory.getLogger(CloseRollbackRedeliveryQueueTest.class); - protected int numberOfMessagesOnQueue = 1; - private Connection connection; - - public void testVerifySessionCloseRedeliveryWithFailoverTransport() throws Throwable { - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageConsumer consumer = session.createConsumer(destination); + protected int numberOfMessagesOnQueue = 1; + private Connection connection; - Message message = consumer.receive(1000); - String id = message.getJMSMessageID(); - assertNotNull(message); - LOG.info("got message " + message); - // close will rollback the current tx - session.close(); - - session = connection.createSession(true, Session.SESSION_TRANSACTED); - consumer = session.createConsumer(destination); + public void testVerifySessionCloseRedeliveryWithFailoverTransport() throws Throwable { + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageConsumer consumer = session.createConsumer(destination); - message = consumer.receive(1000); - session.commit(); - assertNotNull(message); - assertEquals("redelivered message", id, message.getJMSMessageID()); - assertEquals(2, message.getLongProperty("JMSXDeliveryCount")); - } - - public void testVerifyConsumerAndSessionCloseRedeliveryWithFailoverTransport() throws Throwable { - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageConsumer consumer = session.createConsumer(destination); + Message message = consumer.receive(1000); + String id = message.getJMSMessageID(); + assertNotNull(message); + LOG.info("got message " + message); + // close will rollback the current tx + session.close(); - Message message = consumer.receive(1000); - String id = message.getJMSMessageID(); - assertNotNull(message); - LOG.info("got message " + message); - consumer.close(); - session.close(); - session = connection.createSession(true, Session.SESSION_TRANSACTED); - consumer = session.createConsumer(destination); + session = connection.createSession(true, Session.SESSION_TRANSACTED); + consumer = session.createConsumer(destination); - message = consumer.receive(1000); - session.commit(); - assertNotNull(message); - assertEquals("redelivered message", id, message.getJMSMessageID()); - assertEquals(2, message.getLongProperty("JMSXDeliveryCount")); - } + message = consumer.receive(1000); + session.commit(); + assertNotNull(message); + assertEquals("redelivered message", id, message.getJMSMessageID()); + assertEquals(2, message.getLongProperty("JMSXDeliveryCount")); + } - public void testVerifyConsumerCloseSessionRollbackRedeliveryWithFailoverTransport() throws Throwable { - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageConsumer consumer = session.createConsumer(destination); + public void testVerifyConsumerAndSessionCloseRedeliveryWithFailoverTransport() throws Throwable { + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageConsumer consumer = session.createConsumer(destination); - Message message = consumer.receive(1000); - String id = message.getJMSMessageID(); - assertNotNull(message); - LOG.info("got message " + message); - consumer.close(); - session.rollback(); - - consumer = session.createConsumer(destination); - message = consumer.receive(1000); - session.commit(); - assertNotNull(message); - assertEquals("redelivered message", id, message.getJMSMessageID()); - assertEquals(2, message.getLongProperty("JMSXDeliveryCount")); - } - - protected void setUp() throws Exception { - super.setUp(); + Message message = consumer.receive(1000); + String id = message.getJMSMessageID(); + assertNotNull(message); + LOG.info("got message " + message); + consumer.close(); + session.close(); + session = connection.createSession(true, Session.SESSION_TRANSACTED); + consumer = session.createConsumer(destination); - connection = createConnection(); - connection.start(); + message = consumer.receive(1000); + session.commit(); + assertNotNull(message); + assertEquals("redelivered message", id, message.getJMSMessageID()); + assertEquals(2, message.getLongProperty("JMSXDeliveryCount")); + } - // lets fill the queue up - for (int i = 0; i < numberOfMessagesOnQueue; i++) { - template.send(createMessageCreator(i)); - } + public void testVerifyConsumerCloseSessionRollbackRedeliveryWithFailoverTransport() throws Throwable { + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageConsumer consumer = session.createConsumer(destination); - } + Message message = consumer.receive(1000); + String id = message.getJMSMessageID(); + assertNotNull(message); + LOG.info("got message " + message); + consumer.close(); + session.rollback(); - protected ConnectionFactory createConnectionFactory() throws Exception { - // failover: enables message audit - which could get in the way of redelivery - return new ActiveMQConnectionFactory("failover:" + bindAddress); - } - - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - super.tearDown(); - } + consumer = session.createConsumer(destination); + message = consumer.receive(1000); + session.commit(); + assertNotNull(message); + assertEquals("redelivered message", id, message.getJMSMessageID()); + assertEquals(2, message.getLongProperty("JMSXDeliveryCount")); + } - protected MessageCreator createMessageCreator(final int i) { - return new MessageCreator() { - public Message createMessage(Session session) throws JMSException { - TextMessage answer = session.createTextMessage("Message: " + i); - answer.setIntProperty("Counter", i); - return answer; - } - }; - } + protected void setUp() throws Exception { + super.setUp(); + + connection = createConnection(); + connection.start(); + + // lets fill the queue up + for (int i = 0; i < numberOfMessagesOnQueue; i++) { + template.send(createMessageCreator(i)); + } + + } + + protected ConnectionFactory createConnectionFactory() throws Exception { + // failover: enables message audit - which could get in the way of redelivery + return new ActiveMQConnectionFactory("failover:" + bindAddress); + } + + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + } + super.tearDown(); + } + + protected MessageCreator createMessageCreator(final int i) { + return new MessageCreator() { + public Message createMessage(Session session) throws JMSException { + TextMessage answer = session.createTextMessage("Message: " + i); + answer.setIntProperty("Counter", i); + return answer; + } + }; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/rollback/DelegatingTransactionalMessageListener.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/rollback/DelegatingTransactionalMessageListener.java index 8fd3457a98..5953d46a10 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/rollback/DelegatingTransactionalMessageListener.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/rollback/DelegatingTransactionalMessageListener.java @@ -28,43 +28,49 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DelegatingTransactionalMessageListener implements MessageListener { - private static final transient Logger LOG = LoggerFactory.getLogger(DelegatingTransactionalMessageListener.class); - private final MessageListener underlyingListener; - private boolean transacted = true; - private int ackMode = Session.AUTO_ACKNOWLEDGE; - private Session session; + private static final transient Logger LOG = LoggerFactory.getLogger(DelegatingTransactionalMessageListener.class); - public DelegatingTransactionalMessageListener(MessageListener underlyingListener, Connection connection, Destination destination) { - this.underlyingListener = underlyingListener; + private final MessageListener underlyingListener; + private boolean transacted = true; + private int ackMode = Session.AUTO_ACKNOWLEDGE; + private Session session; - try { - session = connection.createSession(transacted, ackMode); - MessageConsumer consumer = session.createConsumer(destination); - consumer.setMessageListener(this); - } catch (JMSException e) { - throw new IllegalStateException("Could not listen to " + destination, e); - } - } + public DelegatingTransactionalMessageListener(MessageListener underlyingListener, + Connection connection, + Destination destination) { + this.underlyingListener = underlyingListener; - public void onMessage(Message message) { - try { - underlyingListener.onMessage(message); - session.commit(); - } catch (Throwable e) { - rollback(); - } - } + try { + session = connection.createSession(transacted, ackMode); + MessageConsumer consumer = session.createConsumer(destination); + consumer.setMessageListener(this); + } + catch (JMSException e) { + throw new IllegalStateException("Could not listen to " + destination, e); + } + } - private void rollback() { - try { - session.rollback(); - } catch (JMSException e) { - LOG.error("Failed to rollback: " + e, e); - } - } + public void onMessage(Message message) { + try { + underlyingListener.onMessage(message); + session.commit(); + } + catch (Throwable e) { + rollback(); + } + } - public Session getSession() { - return session; - } + private void rollback() { + try { + session.rollback(); + } + catch (JMSException e) { + LOG.error("Failed to rollback: " + e, e); + } + } + + public Session getSession() { + return session; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/rollback/RollbacksWhileConsumingLargeQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/rollback/RollbacksWhileConsumingLargeQueueTest.java index cebe74d5af..4b9b060d62 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/rollback/RollbacksWhileConsumingLargeQueueTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/rollback/RollbacksWhileConsumingLargeQueueTest.java @@ -37,146 +37,149 @@ import org.slf4j.LoggerFactory; import org.springframework.jms.core.MessageCreator; /** - * + * */ public class RollbacksWhileConsumingLargeQueueTest extends EmbeddedBrokerTestSupport implements MessageListener { - private static final transient Logger LOG = LoggerFactory.getLogger(RollbacksWhileConsumingLargeQueueTest.class); + private static final transient Logger LOG = LoggerFactory.getLogger(RollbacksWhileConsumingLargeQueueTest.class); - protected int numberOfMessagesOnQueue = 650; - private Connection connection; - private AtomicInteger deliveryCounter = new AtomicInteger(0); - private AtomicInteger ackCounter = new AtomicInteger(0); - private CountDownLatch latch; - private Throwable failure; + protected int numberOfMessagesOnQueue = 650; + private Connection connection; + private AtomicInteger deliveryCounter = new AtomicInteger(0); + private AtomicInteger ackCounter = new AtomicInteger(0); + private CountDownLatch latch; + private Throwable failure; - public void testWithReciever() throws Throwable { - latch = new CountDownLatch(numberOfMessagesOnQueue); - Session session = connection.createSession(true, 0); - MessageConsumer consumer = session.createConsumer(destination); + public void testWithReciever() throws Throwable { + latch = new CountDownLatch(numberOfMessagesOnQueue); + Session session = connection.createSession(true, 0); + MessageConsumer consumer = session.createConsumer(destination); - long start = System.currentTimeMillis(); - while ((System.currentTimeMillis() - start) < 1000 * 1000) { - if (getFailure() != null) { - throw getFailure(); - } + long start = System.currentTimeMillis(); + while ((System.currentTimeMillis() - start) < 1000 * 1000) { + if (getFailure() != null) { + throw getFailure(); + } - // Are we done receiving all the messages. - if (ackCounter.get() == numberOfMessagesOnQueue) { - return; - } + // Are we done receiving all the messages. + if (ackCounter.get() == numberOfMessagesOnQueue) { + return; + } - Message message = consumer.receive(1000); - if (message == null) { - continue; - } + Message message = consumer.receive(1000); + if (message == null) { + continue; + } - try { - onMessage(message); - session.commit(); - } catch (Throwable e) { - session.rollback(); - } - } + try { + onMessage(message); + session.commit(); + } + catch (Throwable e) { + session.rollback(); + } + } - fail("Did not receive all the messages."); - } + fail("Did not receive all the messages."); + } - public void testWithMessageListener() throws Throwable { - latch = new CountDownLatch(numberOfMessagesOnQueue); - new DelegatingTransactionalMessageListener(this, connection, destination); + public void testWithMessageListener() throws Throwable { + latch = new CountDownLatch(numberOfMessagesOnQueue); + new DelegatingTransactionalMessageListener(this, connection, destination); - long start = System.currentTimeMillis(); - while ((System.currentTimeMillis() - start) < 1000 * 1000) { + long start = System.currentTimeMillis(); + while ((System.currentTimeMillis() - start) < 1000 * 1000) { - if (getFailure() != null) { - throw getFailure(); - } + if (getFailure() != null) { + throw getFailure(); + } - if (latch.await(1, TimeUnit.SECONDS)) { - LOG.debug("Received: " + deliveryCounter.get() + " message(s)"); - return; - } + if (latch.await(1, TimeUnit.SECONDS)) { + LOG.debug("Received: " + deliveryCounter.get() + " message(s)"); + return; + } - } + } - fail("Did not receive all the messages."); - } + fail("Did not receive all the messages."); + } - protected ConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory answer = (ActiveMQConnectionFactory) super.createConnectionFactory(); - RedeliveryPolicy policy = new RedeliveryPolicy(); - policy.setMaximumRedeliveries(3); - policy.setRedeliveryDelay(0); - policy.setInitialRedeliveryDelay(0); - policy.setUseExponentialBackOff(false); - answer.setRedeliveryPolicy(policy); - return answer; - } + protected ConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory answer = (ActiveMQConnectionFactory) super.createConnectionFactory(); + RedeliveryPolicy policy = new RedeliveryPolicy(); + policy.setMaximumRedeliveries(3); + policy.setRedeliveryDelay(0); + policy.setInitialRedeliveryDelay(0); + policy.setUseExponentialBackOff(false); + answer.setRedeliveryPolicy(policy); + return answer; + } - protected void setUp() throws Exception { - super.setUp(); + protected void setUp() throws Exception { + super.setUp(); - connection = createConnection(); - connection.start(); + connection = createConnection(); + connection.start(); - // lets fill the queue up - for (int i = 0; i < numberOfMessagesOnQueue; i++) { - template.send(createMessageCreator(i)); - } + // lets fill the queue up + for (int i = 0; i < numberOfMessagesOnQueue; i++) { + template.send(createMessageCreator(i)); + } - } + } - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - super.tearDown(); - } + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + } + super.tearDown(); + } - protected MessageCreator createMessageCreator(final int i) { - return new MessageCreator() { - public Message createMessage(Session session) throws JMSException { - TextMessage answer = session.createTextMessage("Message: " + i); - answer.setIntProperty("Counter", i); - return answer; - } - }; - } + protected MessageCreator createMessageCreator(final int i) { + return new MessageCreator() { + public Message createMessage(Session session) throws JMSException { + TextMessage answer = session.createTextMessage("Message: " + i); + answer.setIntProperty("Counter", i); + return answer; + } + }; + } - public void onMessage(Message message) { - String msgId = null; - String msgText = null; + public void onMessage(Message message) { + String msgId = null; + String msgText = null; - try { - msgId = message.getJMSMessageID(); - msgText = ((TextMessage)message).getText(); - } catch (JMSException e) { - setFailure(e); - } + try { + msgId = message.getJMSMessageID(); + msgText = ((TextMessage) message).getText(); + } + catch (JMSException e) { + setFailure(e); + } - try { - assertEquals("Message: " + ackCounter.get(), msgText); - } catch (Throwable e) { - setFailure(e); - } + try { + assertEquals("Message: " + ackCounter.get(), msgText); + } + catch (Throwable e) { + setFailure(e); + } - int value = deliveryCounter.incrementAndGet(); - if (value % 2 == 0) { - LOG.info("Rolling Back message: " + ackCounter.get() + " id: " + msgId + ", content: " + msgText); - throw new RuntimeException("Dummy exception on message: " + value); - } + int value = deliveryCounter.incrementAndGet(); + if (value % 2 == 0) { + LOG.info("Rolling Back message: " + ackCounter.get() + " id: " + msgId + ", content: " + msgText); + throw new RuntimeException("Dummy exception on message: " + value); + } - LOG.info("Received message: " + ackCounter.get() + " id: " + msgId + ", content: " + msgText); - ackCounter.incrementAndGet(); - latch.countDown(); - } + LOG.info("Received message: " + ackCounter.get() + " id: " + msgId + ", content: " + msgText); + ackCounter.incrementAndGet(); + latch.countDown(); + } - public synchronized Throwable getFailure() { - return failure; - } + public synchronized Throwable getFailure() { + return failure; + } - public synchronized void setFailure(Throwable failure) { - this.failure = failure; - } + public synchronized void setFailure(Throwable failure) { + this.failure = failure; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/QueueClusterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/QueueClusterTest.java index 447e2e2e87..901ea9a556 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/QueueClusterTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/QueueClusterTest.java @@ -17,17 +17,17 @@ package org.apache.activemq.transport; /** - * + * */ public class QueueClusterTest extends TopicClusterTest { - protected void setUp() throws Exception { - topic = false; - super.setUp(); - } + protected void setUp() throws Exception { + topic = false; + super.setUp(); + } - protected int expectedReceiveCount() { - return MESSAGE_COUNT * NUMBER_IN_CLUSTER; - } + protected int expectedReceiveCount() { + return MESSAGE_COUNT * NUMBER_IN_CLUSTER; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/SoWriteTimeoutClientTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/SoWriteTimeoutClientTest.java index 59ba91501f..91823e9785 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/SoWriteTimeoutClientTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/SoWriteTimeoutClientTest.java @@ -23,7 +23,9 @@ import java.util.concurrent.TimeUnit; import javax.jms.Connection; import javax.jms.MessageConsumer; import javax.jms.Session; + import junit.framework.Test; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.JmsTestSupport; import org.apache.activemq.broker.BrokerService; @@ -36,76 +38,78 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SoWriteTimeoutClientTest extends JmsTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(SoWriteTimeoutClientTest.class); - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setDeleteAllMessagesOnStartup(true); - KahaDBPersistenceAdapter adapter = new KahaDBPersistenceAdapter(); - adapter.setConcurrentStoreAndDispatchQueues(false); - broker.setPersistenceAdapter(adapter); - broker.addConnector("tcp://localhost:0?wireFormat.maxInactivityDuration=0"); - return broker; - } + private static final Logger LOG = LoggerFactory.getLogger(SoWriteTimeoutClientTest.class); - public void testSendWithClientWriteTimeout() throws Exception { - final ActiveMQQueue dest = new ActiveMQQueue("testClientWriteTimeout"); - messageTextPrefix = initMessagePrefix(80*1024); + protected BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setDeleteAllMessagesOnStartup(true); + KahaDBPersistenceAdapter adapter = new KahaDBPersistenceAdapter(); + adapter.setConcurrentStoreAndDispatchQueues(false); + broker.setPersistenceAdapter(adapter); + broker.addConnector("tcp://localhost:0?wireFormat.maxInactivityDuration=0"); + return broker; + } - URI tcpBrokerUri = URISupport.removeQuery(broker.getTransportConnectors().get(0).getConnectUri()); - LOG.info("consuming using uri: " + tcpBrokerUri); + public void testSendWithClientWriteTimeout() throws Exception { + final ActiveMQQueue dest = new ActiveMQQueue("testClientWriteTimeout"); + messageTextPrefix = initMessagePrefix(80 * 1024); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(tcpBrokerUri); - Connection c = factory.createConnection(); - c.start(); - Session session = c.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(dest); + URI tcpBrokerUri = URISupport.removeQuery(broker.getTransportConnectors().get(0).getConnectUri()); + LOG.info("consuming using uri: " + tcpBrokerUri); - SocketProxy proxy = new SocketProxy(); - proxy.setTarget(tcpBrokerUri); - proxy.open(); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(tcpBrokerUri); + Connection c = factory.createConnection(); + c.start(); + Session session = c.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(dest); - ActiveMQConnectionFactory pFactory = new ActiveMQConnectionFactory("failover:(" + proxy.getUrl() + "?soWriteTimeout=4000&sleep=500)?jms.useAsyncSend=true&trackMessages=true&maxCacheSize=6638400"); - final Connection pc = pFactory.createConnection(); - pc.start(); - proxy.pause(); + SocketProxy proxy = new SocketProxy(); + proxy.setTarget(tcpBrokerUri); + proxy.open(); - final int messageCount = 20; - ExecutorService executorService = Executors.newCachedThreadPool(); - executorService.execute(new Runnable() { - @Override - public void run() { - try{ - sendMessages(pc, dest, messageCount); - } catch (Exception ignored) { - ignored.printStackTrace(); - } + ActiveMQConnectionFactory pFactory = new ActiveMQConnectionFactory("failover:(" + proxy.getUrl() + "?soWriteTimeout=4000&sleep=500)?jms.useAsyncSend=true&trackMessages=true&maxCacheSize=6638400"); + final Connection pc = pFactory.createConnection(); + pc.start(); + proxy.pause(); + + final int messageCount = 20; + ExecutorService executorService = Executors.newCachedThreadPool(); + executorService.execute(new Runnable() { + @Override + public void run() { + try { + sendMessages(pc, dest, messageCount); } - }); - - // wait for timeout and reconnect - TimeUnit.SECONDS.sleep(8); - proxy.goOn(); - for (int i=0; i transportURIs = new ArrayList(); - - /** - * @see org.apache.activemq.transport.CompositeTransport#add(java.net.URI[]) - */ - public void add(boolean rebalance, URI[] uris) - { - transportURIs.addAll(Arrays.asList(uris)); - } +public class StubCompositeTransport extends StubTransport implements CompositeTransport { - /** - * @see org.apache.activemq.transport.CompositeTransport#remove(java.net.URI[]) - */ - public void remove(boolean rebalance, URI[] uris) - { - transportURIs.removeAll(Arrays.asList(uris)); - } + private List transportURIs = new ArrayList(); - public URI[] getTransportURIs() - { - return transportURIs.toArray(new URI[0]); - } + /** + * @see org.apache.activemq.transport.CompositeTransport#add(java.net.URI[]) + */ + public void add(boolean rebalance, URI[] uris) { + transportURIs.addAll(Arrays.asList(uris)); + } + + /** + * @see org.apache.activemq.transport.CompositeTransport#remove(java.net.URI[]) + */ + public void remove(boolean rebalance, URI[] uris) { + transportURIs.removeAll(Arrays.asList(uris)); + } + + public URI[] getTransportURIs() { + return transportURIs.toArray(new URI[0]); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/StubTransport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/StubTransport.java index a11d45a5c2..89294c195e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/StubTransport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/StubTransport.java @@ -24,35 +24,35 @@ import java.util.concurrent.atomic.AtomicInteger; import org.apache.activemq.util.ServiceStopper; /** - * - * + * + * */ public class StubTransport extends TransportSupport { - private Queue queue = new ConcurrentLinkedQueue(); - private AtomicInteger receiveCounter; + private Queue queue = new ConcurrentLinkedQueue(); + private AtomicInteger receiveCounter; - protected void doStop(ServiceStopper stopper) throws Exception { - } + protected void doStop(ServiceStopper stopper) throws Exception { + } - protected void doStart() throws Exception { - } + protected void doStart() throws Exception { + } - public void oneway(Object command) throws IOException { - receiveCounter.incrementAndGet(); - queue.add(command); - } + public void oneway(Object command) throws IOException { + receiveCounter.incrementAndGet(); + queue.add(command); + } - public Queue getQueue() { - return queue; - } + public Queue getQueue() { + return queue; + } - public String getRemoteAddress() { - return null; - } + public String getRemoteAddress() { + return null; + } - public int getReceiveCounter() { - return receiveCounter.get(); - } + public int getReceiveCounter() { + return receiveCounter.get(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/StubTransportListener.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/StubTransportListener.java index 018cfc7925..6c67e3cb07 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/StubTransportListener.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/StubTransportListener.java @@ -26,33 +26,33 @@ import java.util.concurrent.ConcurrentLinkedQueue; */ public class StubTransportListener implements TransportListener { - private final Queue commands = new ConcurrentLinkedQueue(); - private final Queue exceptions = new ConcurrentLinkedQueue(); + private final Queue commands = new ConcurrentLinkedQueue(); + private final Queue exceptions = new ConcurrentLinkedQueue(); - public Queue getCommands() { - return commands; - } + public Queue getCommands() { + return commands; + } - public Queue getExceptions() { - return exceptions; - } + public Queue getExceptions() { + return exceptions; + } - @Override - public void onCommand(Object command) { - commands.add(command); - } + @Override + public void onCommand(Object command) { + commands.add(command); + } - @Override - public void onException(IOException error) { - exceptions.add(error); - } + @Override + public void onException(IOException error) { + exceptions.add(error); + } - @Override - public void transportInterupted() { - } + @Override + public void transportInterupted() { + } - @Override - public void transportResumed() { - } + @Override + public void transportResumed() { + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/TopicClusterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/TopicClusterTest.java index 26c215a47b..a7b585860c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/TopicClusterTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/TopicClusterTest.java @@ -34,6 +34,7 @@ import javax.jms.Session; import javax.jms.TextMessage; import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.TransportConnector; @@ -45,135 +46,137 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class TopicClusterTest extends TestCase implements MessageListener { - - protected static final int MESSAGE_COUNT = 50; - protected static final int NUMBER_IN_CLUSTER = 3; - private static final Logger LOG = LoggerFactory.getLogger(TopicClusterTest.class); - - protected Destination destination; - protected boolean topic = true; - protected final AtomicInteger receivedMessageCount = new AtomicInteger(0); - protected int deliveryMode = DeliveryMode.NON_PERSISTENT; - protected MessageProducer[] producers; - protected Connection[] connections; - protected List services = new ArrayList(); - protected String groupId; - - protected void setUp() throws Exception { - groupId = "topic-cluster-test-"+System.currentTimeMillis(); - connections = new Connection[NUMBER_IN_CLUSTER]; - producers = new MessageProducer[NUMBER_IN_CLUSTER]; - Destination destination = createDestination(); - String root = System.getProperty("activemq.store.dir"); - if (root == null) { - root = "target/store"; - } - try { - for (int i = 0; i < NUMBER_IN_CLUSTER; i++) { - System.setProperty("activemq.store.dir", root + "_broker_" + i); - connections[i] = createConnection("broker-" + i); - connections[i].setClientID("ClusterTest" + i); - connections[i].start(); - Session session = connections[i].createSession(false, Session.AUTO_ACKNOWLEDGE); - producers[i] = session.createProducer(destination); - producers[i].setDeliveryMode(deliveryMode); - MessageConsumer consumer = createMessageConsumer(session, destination); - consumer.setMessageListener(this); + protected static final int MESSAGE_COUNT = 50; + protected static final int NUMBER_IN_CLUSTER = 3; + private static final Logger LOG = LoggerFactory.getLogger(TopicClusterTest.class); - } - LOG.info("Sleeping to ensure cluster is fully connected"); - Thread.sleep(5000); - } finally { - System.setProperty("activemq.store.dir", root); - } - } + protected Destination destination; + protected boolean topic = true; + protected final AtomicInteger receivedMessageCount = new AtomicInteger(0); + protected int deliveryMode = DeliveryMode.NON_PERSISTENT; + protected MessageProducer[] producers; + protected Connection[] connections; + protected List services = new ArrayList(); + protected String groupId; - protected void tearDown() throws Exception { - if (connections != null) { - for (int i = 0; i < connections.length; i++) { - connections[i].close(); - } - } - ServiceStopper stopper = new ServiceStopper(); - stopper.stopServices(services); - } + protected void setUp() throws Exception { + groupId = "topic-cluster-test-" + System.currentTimeMillis(); + connections = new Connection[NUMBER_IN_CLUSTER]; + producers = new MessageProducer[NUMBER_IN_CLUSTER]; + Destination destination = createDestination(); + String root = System.getProperty("activemq.store.dir"); + if (root == null) { + root = "target/store"; + } + try { + for (int i = 0; i < NUMBER_IN_CLUSTER; i++) { - protected MessageConsumer createMessageConsumer(Session session, Destination destination) throws JMSException { - return session.createConsumer(destination); - } + System.setProperty("activemq.store.dir", root + "_broker_" + i); + connections[i] = createConnection("broker-" + i); + connections[i].setClientID("ClusterTest" + i); + connections[i].start(); + Session session = connections[i].createSession(false, Session.AUTO_ACKNOWLEDGE); + producers[i] = session.createProducer(destination); + producers[i].setDeliveryMode(deliveryMode); + MessageConsumer consumer = createMessageConsumer(session, destination); + consumer.setMessageListener(this); - protected ActiveMQConnectionFactory createGenericClusterFactory(String brokerName) throws Exception { - BrokerService container = new BrokerService(); - container.setBrokerName(brokerName); + } + LOG.info("Sleeping to ensure cluster is fully connected"); + Thread.sleep(5000); + } + finally { + System.setProperty("activemq.store.dir", root); + } + } - String url = "tcp://localhost:0"; - TransportConnector connector = container.addConnector(url); - connector.setDiscoveryUri(new URI("multicast://default?group="+groupId)); - container.addNetworkConnector("multicast://default?group="+groupId); - container.start(); + protected void tearDown() throws Exception { + if (connections != null) { + for (int i = 0; i < connections.length; i++) { + connections[i].close(); + } + } + ServiceStopper stopper = new ServiceStopper(); + stopper.stopServices(services); + } - services.add(container); + protected MessageConsumer createMessageConsumer(Session session, Destination destination) throws JMSException { + return session.createConsumer(destination); + } - return new ActiveMQConnectionFactory("vm://" + brokerName); - } + protected ActiveMQConnectionFactory createGenericClusterFactory(String brokerName) throws Exception { + BrokerService container = new BrokerService(); + container.setBrokerName(brokerName); - protected int expectedReceiveCount() { - return MESSAGE_COUNT * NUMBER_IN_CLUSTER * NUMBER_IN_CLUSTER; - } + String url = "tcp://localhost:0"; + TransportConnector connector = container.addConnector(url); + connector.setDiscoveryUri(new URI("multicast://default?group=" + groupId)); + container.addNetworkConnector("multicast://default?group=" + groupId); + container.start(); - protected Connection createConnection(String name) throws Exception { - return createGenericClusterFactory(name).createConnection(); - } + services.add(container); - protected Destination createDestination() { - return createDestination(getClass().getName()); - } + return new ActiveMQConnectionFactory("vm://" + brokerName); + } - protected Destination createDestination(String name) { - if (topic) { - return new ActiveMQTopic(name); - } else { - return new ActiveMQQueue(name); - } - } + protected int expectedReceiveCount() { + return MESSAGE_COUNT * NUMBER_IN_CLUSTER * NUMBER_IN_CLUSTER; + } - /** - * @param msg - */ - public void onMessage(Message msg) { - // log.info("GOT: " + msg); - receivedMessageCount.incrementAndGet(); - synchronized (receivedMessageCount) { - if (receivedMessageCount.get() >= expectedReceiveCount()) { - receivedMessageCount.notify(); - } - } - } + protected Connection createConnection(String name) throws Exception { + return createGenericClusterFactory(name).createConnection(); + } - /** - * @throws Exception - */ - public void testSendReceive() throws Exception { - for (int i = 0; i < MESSAGE_COUNT; i++) { - TextMessage textMessage = new ActiveMQTextMessage(); - textMessage.setText("MSG-NO:" + i); - for (int x = 0; x < producers.length; x++) { - producers[x].send(textMessage); - } - } - synchronized (receivedMessageCount) { - while (receivedMessageCount.get() < expectedReceiveCount()) { - receivedMessageCount.wait(20000); - } - } - // sleep a little - to check we don't get too many messages - Thread.sleep(2000); - LOG.info("GOT: " + receivedMessageCount.get()); - assertEquals("Expected message count not correct", expectedReceiveCount(), receivedMessageCount.get()); - } + protected Destination createDestination() { + return createDestination(getClass().getName()); + } + + protected Destination createDestination(String name) { + if (topic) { + return new ActiveMQTopic(name); + } + else { + return new ActiveMQQueue(name); + } + } + + /** + * @param msg + */ + public void onMessage(Message msg) { + // log.info("GOT: " + msg); + receivedMessageCount.incrementAndGet(); + synchronized (receivedMessageCount) { + if (receivedMessageCount.get() >= expectedReceiveCount()) { + receivedMessageCount.notify(); + } + } + } + + /** + * @throws Exception + */ + public void testSendReceive() throws Exception { + for (int i = 0; i < MESSAGE_COUNT; i++) { + TextMessage textMessage = new ActiveMQTextMessage(); + textMessage.setText("MSG-NO:" + i); + for (int x = 0; x < producers.length; x++) { + producers[x].send(textMessage); + } + } + synchronized (receivedMessageCount) { + while (receivedMessageCount.get() < expectedReceiveCount()) { + receivedMessageCount.wait(20000); + } + } + // sleep a little - to check we don't get too many messages + Thread.sleep(2000); + LOG.info("GOT: " + receivedMessageCount.get()); + assertEquals("Expected message count not correct", expectedReceiveCount(), receivedMessageCount.get()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/TransportBrokerTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/TransportBrokerTestSupport.java index 5c221d330c..501c2a020e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/TransportBrokerTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/TransportBrokerTestSupport.java @@ -28,51 +28,50 @@ import org.apache.activemq.broker.TransportConnector; public abstract class TransportBrokerTestSupport extends BrokerTest { - protected TransportConnector connector; - private ArrayList connections = new ArrayList(); + protected TransportConnector connector; + private ArrayList connections = new ArrayList(); - protected void setUp() throws Exception { - super.setUp(); - } + protected void setUp() throws Exception { + super.setUp(); + } - protected BrokerService createBroker() throws Exception { - BrokerService service = super.createBroker(); - connector = service.addConnector(getBindLocation()); - return service; - } - - protected abstract String getBindLocation(); + protected BrokerService createBroker() throws Exception { + BrokerService service = super.createBroker(); + connector = service.addConnector(getBindLocation()); + return service; + } - protected void tearDown() throws Exception { - for (Iterator iter = connections.iterator(); iter.hasNext();) { - StubConnection connection = iter.next(); - connection.stop(); - iter.remove(); - } - if( connector!=null ) { - connector.stop(); - } - super.tearDown(); - } + protected abstract String getBindLocation(); - protected URI getBindURI() throws URISyntaxException { - return new URI(getBindLocation()); - } + protected void tearDown() throws Exception { + for (Iterator iter = connections.iterator(); iter.hasNext(); ) { + StubConnection connection = iter.next(); + connection.stop(); + iter.remove(); + } + if (connector != null) { + connector.stop(); + } + super.tearDown(); + } - protected StubConnection createConnection() throws Exception { - URI bindURI = getBindURI(); - - // Note: on platforms like OS X we cannot bind to the actual hostname, so we - // instead use the original host name (typically localhost) to bind to - - URI actualURI = connector.getServer().getConnectURI(); - URI connectURI = new URI(actualURI.getScheme(), actualURI.getUserInfo(), bindURI.getHost(), actualURI.getPort(), actualURI.getPath(), bindURI - .getQuery(), bindURI.getFragment()); + protected URI getBindURI() throws URISyntaxException { + return new URI(getBindLocation()); + } - Transport transport = TransportFactory.connect(connectURI); - StubConnection connection = new StubConnection(transport); - connections.add(connection); - return connection; - } + protected StubConnection createConnection() throws Exception { + URI bindURI = getBindURI(); + + // Note: on platforms like OS X we cannot bind to the actual hostname, so we + // instead use the original host name (typically localhost) to bind to + + URI actualURI = connector.getServer().getConnectURI(); + URI connectURI = new URI(actualURI.getScheme(), actualURI.getUserInfo(), bindURI.getHost(), actualURI.getPort(), actualURI.getPath(), bindURI.getQuery(), bindURI.getFragment()); + + Transport transport = TransportFactory.connect(connectURI); + StubConnection connection = new StubConnection(transport); + connections.add(connection); + return connection; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryNetworkReconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryNetworkReconnectTest.java index 8601c34268..8ee3adc7b8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryNetworkReconnectTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryNetworkReconnectTest.java @@ -46,195 +46,179 @@ import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - @RunWith(JMock.class) public class DiscoveryNetworkReconnectTest { - private static final Logger LOG = LoggerFactory.getLogger(DiscoveryNetworkReconnectTest.class); - final int maxReconnects = 2; - final String groupName = "GroupID-" + "DiscoveryNetworkReconnectTest"; - final String discoveryAddress = "multicast://default?group=" + groupName + "&initialReconnectDelay=1000"; - final Semaphore mbeanRegistered = new Semaphore(0); - final Semaphore mbeanUnregistered = new Semaphore(0); - BrokerService brokerA, brokerB; - Mockery context; - ManagementContext managementContext; - DiscoveryAgent agent; - SocketProxy proxy; + private static final Logger LOG = LoggerFactory.getLogger(DiscoveryNetworkReconnectTest.class); + final int maxReconnects = 2; + final String groupName = "GroupID-" + "DiscoveryNetworkReconnectTest"; + final String discoveryAddress = "multicast://default?group=" + groupName + "&initialReconnectDelay=1000"; + final Semaphore mbeanRegistered = new Semaphore(0); + final Semaphore mbeanUnregistered = new Semaphore(0); + BrokerService brokerA, brokerB; + Mockery context; + ManagementContext managementContext; + DiscoveryAgent agent; + SocketProxy proxy; - // ignore the hostname resolution component as this is machine dependent - class NetworkBridgeObjectNameMatcher extends BaseMatcher { - T name; - NetworkBridgeObjectNameMatcher(T o) { - name = o; - } + // ignore the hostname resolution component as this is machine dependent + class NetworkBridgeObjectNameMatcher extends BaseMatcher { - @Override - public boolean matches(Object arg0) { - ObjectName other = (ObjectName) arg0; - ObjectName mine = (ObjectName) name; - LOG.info("Match: " + mine + " vs: " + other); + T name; - if (!"networkConnectors".equals(other.getKeyProperty("connector"))) { - return false; + NetworkBridgeObjectNameMatcher(T o) { + name = o; + } + + @Override + public boolean matches(Object arg0) { + ObjectName other = (ObjectName) arg0; + ObjectName mine = (ObjectName) name; + LOG.info("Match: " + mine + " vs: " + other); + + if (!"networkConnectors".equals(other.getKeyProperty("connector"))) { + return false; + } + return other.getKeyProperty("connector").equals(mine.getKeyProperty("connector")) && + other.getKeyProperty("networkBridge") != null && mine.getKeyProperty("networkBridge") != null; + } + + @Override + public void describeTo(Description arg0) { + arg0.appendText(this.getClass().getName()); + } + } + + @Before + public void setUp() throws Exception { + context = new JUnit4Mockery() {{ + setImposteriser(ClassImposteriser.INSTANCE); + }}; + brokerA = new BrokerService(); + brokerA.setBrokerName("BrokerA"); + configure(brokerA); + brokerA.addConnector("tcp://localhost:0"); + brokerA.start(); + brokerA.waitUntilStarted(); + + proxy = new SocketProxy(brokerA.getTransportConnectors().get(0).getConnectUri()); + managementContext = context.mock(ManagementContext.class); + + context.checking(new Expectations() {{ + allowing(managementContext).getJmxDomainName(); + will(returnValue("Test")); + allowing(managementContext).setBrokerName("BrokerNC"); + allowing(managementContext).start(); + allowing(managementContext).isCreateConnector(); + allowing(managementContext).stop(); + allowing(managementContext).isConnectorStarted(); + + // expected MBeans + allowing(managementContext).registerMBean(with(any(Object.class)), with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC")))); + allowing(managementContext).registerMBean(with(any(Object.class)), with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,service=Health")))); + allowing(managementContext).registerMBean(with(any(Object.class)), with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,connector=networkConnectors,networkConnectorName=NC")))); + allowing(managementContext).registerMBean(with(any(Object.class)), with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,service=Log4JConfiguration")))); + allowing(managementContext).registerMBean(with(any(Object.class)), with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,destinationType=Topic,destinationName=ActiveMQ.Advisory.Connection")))); + allowing(managementContext).registerMBean(with(any(Object.class)), with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,destinationType=Topic,destinationName=ActiveMQ.Advisory.NetworkBridge")))); + allowing(managementContext).registerMBean(with(any(Object.class)), with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,destinationType=Topic,destinationName=ActiveMQ.Advisory.MasterBroker")))); + allowing(managementContext).registerMBean(with(any(Object.class)), with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,service=jobScheduler,jobSchedulerName=JMS")))); + + atLeast(maxReconnects - 1).of(managementContext).registerMBean(with(any(Object.class)), with(new NetworkBridgeObjectNameMatcher(new ObjectName("Test:type=Broker,brokerName=BrokerNC,connector=networkConnectors,networkConnectorName=NC,networkBridge=localhost/127.0.0.1_" + proxy.getUrl().getPort())))); + will(new CustomAction("signal register network mbean") { + @Override + public Object invoke(Invocation invocation) throws Throwable { + LOG.info("Mbean Registered: " + invocation.getParameter(0)); + mbeanRegistered.release(); + return new ObjectInstance((ObjectName) invocation.getParameter(1), "discription"); } - return other.getKeyProperty("connector").equals(mine.getKeyProperty("connector")) && - other.getKeyProperty("networkBridge") != null && mine.getKeyProperty("networkBridge") != null; - } + }); + atLeast(maxReconnects - 1).of(managementContext).unregisterMBean(with(new NetworkBridgeObjectNameMatcher(new ObjectName("Test:type=Broker,brokerName=BrokerNC,connector=networkConnectors,networkConnectorName=NC,networkBridge=localhost/127.0.0.1_" + proxy.getUrl().getPort())))); + will(new CustomAction("signal unregister network mbean") { + @Override + public Object invoke(Invocation invocation) throws Throwable { + LOG.info("Mbean Unregistered: " + invocation.getParameter(0)); + mbeanUnregistered.release(); + return null; + } + }); - @Override - public void describeTo(Description arg0) { - arg0.appendText(this.getClass().getName()); - } - } + allowing(managementContext).unregisterMBean(with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC")))); + allowing(managementContext).unregisterMBean(with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,service=Health")))); + allowing(managementContext).unregisterMBean(with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,connector=networkConnectors,networkConnectorName=NC")))); + allowing(managementContext).unregisterMBean(with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,service=Log4JConfiguration")))); + allowing(managementContext).unregisterMBean(with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,destinationType=Topic,destinationName=ActiveMQ.Advisory.Connection")))); + allowing(managementContext).unregisterMBean(with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,destinationType=Topic,destinationName=ActiveMQ.Advisory.NetworkBridge")))); + allowing(managementContext).unregisterMBean(with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,destinationType=Topic,destinationName=ActiveMQ.Advisory.MasterBroker")))); + }}); - @Before - public void setUp() throws Exception { - context = new JUnit4Mockery() {{ - setImposteriser(ClassImposteriser.INSTANCE); - }}; - brokerA = new BrokerService(); - brokerA.setBrokerName("BrokerA"); - configure(brokerA); - brokerA.addConnector("tcp://localhost:0"); - brokerA.start(); - brokerA.waitUntilStarted(); + brokerB = new BrokerService(); + brokerB.setManagementContext(managementContext); + brokerB.setBrokerName("BrokerNC"); + configure(brokerB); + } - proxy = new SocketProxy(brokerA.getTransportConnectors().get(0).getConnectUri()); - managementContext = context.mock(ManagementContext.class); + @After + public void tearDown() throws Exception { + brokerA.stop(); + brokerA.waitUntilStopped(); + brokerB.stop(); + brokerB.waitUntilStopped(); + proxy.close(); + } - context.checking(new Expectations(){{ - allowing(managementContext).getJmxDomainName(); will (returnValue("Test")); - allowing(managementContext).setBrokerName("BrokerNC"); - allowing(managementContext).start(); - allowing(managementContext).isCreateConnector(); - allowing(managementContext).stop(); - allowing(managementContext).isConnectorStarted(); + private void configure(BrokerService broker) { + broker.setPersistent(false); + broker.setUseJmx(true); + } - // expected MBeans - allowing(managementContext).registerMBean(with(any(Object.class)), with(equal( - new ObjectName("Test:type=Broker,brokerName=BrokerNC")))); - allowing(managementContext).registerMBean(with(any(Object.class)), with(equal( - new ObjectName("Test:type=Broker,brokerName=BrokerNC,service=Health")))); - allowing(managementContext).registerMBean(with(any(Object.class)), with(equal( - new ObjectName("Test:type=Broker,brokerName=BrokerNC,connector=networkConnectors,networkConnectorName=NC")))); - allowing(managementContext).registerMBean(with(any(Object.class)), with(equal( - new ObjectName("Test:type=Broker,brokerName=BrokerNC,service=Log4JConfiguration")))); - allowing(managementContext).registerMBean(with(any(Object.class)), with(equal( - new ObjectName("Test:type=Broker,brokerName=BrokerNC,destinationType=Topic,destinationName=ActiveMQ.Advisory.Connection")))); - allowing(managementContext).registerMBean(with(any(Object.class)), with(equal( - new ObjectName("Test:type=Broker,brokerName=BrokerNC,destinationType=Topic,destinationName=ActiveMQ.Advisory.NetworkBridge")))); - allowing(managementContext).registerMBean(with(any(Object.class)), with(equal( - new ObjectName("Test:type=Broker,brokerName=BrokerNC,destinationType=Topic,destinationName=ActiveMQ.Advisory.MasterBroker")))); - allowing(managementContext).registerMBean(with(any(Object.class)), with(equal( - new ObjectName("Test:type=Broker,brokerName=BrokerNC,service=jobScheduler,jobSchedulerName=JMS")))); + @Test + public void testMulicastReconnect() throws Exception { - atLeast(maxReconnects - 1).of (managementContext).registerMBean(with(any(Object.class)), with(new NetworkBridgeObjectNameMatcher( - new ObjectName("Test:type=Broker,brokerName=BrokerNC,connector=networkConnectors,networkConnectorName=NC,networkBridge=localhost/127.0.0.1_" - + proxy.getUrl().getPort())))); will(new CustomAction("signal register network mbean") { - @Override - public Object invoke(Invocation invocation) throws Throwable { - LOG.info("Mbean Registered: " + invocation.getParameter(0)); - mbeanRegistered.release(); - return new ObjectInstance((ObjectName)invocation.getParameter(1), "discription"); - } - }); - atLeast(maxReconnects - 1).of (managementContext).unregisterMBean(with(new NetworkBridgeObjectNameMatcher( - new ObjectName("Test:type=Broker,brokerName=BrokerNC,connector=networkConnectors,networkConnectorName=NC,networkBridge=localhost/127.0.0.1_" - + proxy.getUrl().getPort())))); will(new CustomAction("signal unregister network mbean") { - @Override - public Object invoke(Invocation invocation) throws Throwable { - LOG.info("Mbean Unregistered: " + invocation.getParameter(0)); - mbeanUnregistered.release(); - return null; - } - }); + brokerB.addNetworkConnector(discoveryAddress + "&discovered.trace=true&discovered.wireFormat.maxInactivityDuration=1000&discovered.wireFormat.maxInactivityDurationInitalDelay=1000"); + brokerB.start(); + brokerB.waitUntilStarted(); - allowing(managementContext).unregisterMBean(with(equal( - new ObjectName("Test:type=Broker,brokerName=BrokerNC")))); - allowing(managementContext).unregisterMBean(with(equal( - new ObjectName("Test:type=Broker,brokerName=BrokerNC,service=Health")))); - allowing(managementContext).unregisterMBean(with(equal( - new ObjectName("Test:type=Broker,brokerName=BrokerNC,connector=networkConnectors,networkConnectorName=NC")))); - allowing(managementContext).unregisterMBean(with(equal( - new ObjectName("Test:type=Broker,brokerName=BrokerNC,service=Log4JConfiguration")))); - allowing(managementContext).unregisterMBean(with(equal( - new ObjectName("Test:type=Broker,brokerName=BrokerNC,destinationType=Topic,destinationName=ActiveMQ.Advisory.Connection")))); - allowing(managementContext).unregisterMBean(with(equal( - new ObjectName("Test:type=Broker,brokerName=BrokerNC,destinationType=Topic,destinationName=ActiveMQ.Advisory.NetworkBridge")))); - allowing(managementContext).unregisterMBean(with(equal( - new ObjectName("Test:type=Broker,brokerName=BrokerNC,destinationType=Topic,destinationName=ActiveMQ.Advisory.MasterBroker")))); - }}); + // control multicast advertise agent to inject proxy + agent = MulticastDiscoveryAgentFactory.createDiscoveryAgent(new URI(discoveryAddress)); + agent.registerService(proxy.getUrl().toString()); + agent.start(); - brokerB = new BrokerService(); - brokerB.setManagementContext(managementContext); - brokerB.setBrokerName("BrokerNC"); - configure(brokerB); - } + doReconnect(); + } - @After - public void tearDown() throws Exception { - brokerA.stop(); - brokerA.waitUntilStopped(); - brokerB.stop(); - brokerB.waitUntilStopped(); - proxy.close(); - } + @Test + public void testSimpleReconnect() throws Exception { + brokerB.addNetworkConnector("simple://(" + proxy.getUrl() + ")?useExponentialBackOff=false&initialReconnectDelay=500&discovered.wireFormat.maxInactivityDuration=1000&discovered.wireFormat.maxInactivityDurationInitalDelay=1000"); + brokerB.start(); + brokerB.waitUntilStarted(); + doReconnect(); + } - private void configure(BrokerService broker) { - broker.setPersistent(false); - broker.setUseJmx(true); - } + private void doReconnect() throws Exception { - @Test - public void testMulicastReconnect() throws Exception { + for (int i = 0; i < maxReconnects; i++) { + // Wait for connection + assertTrue("we got a network connection in a timely manner", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return proxy.connections.size() >= 1; + } + })); - brokerB.addNetworkConnector(discoveryAddress + "&discovered.trace=true&discovered.wireFormat.maxInactivityDuration=1000&discovered.wireFormat.maxInactivityDurationInitalDelay=1000"); - brokerB.start(); - brokerB.waitUntilStarted(); + // wait for network connector + assertTrue("network connector mbean registered within 1 minute", mbeanRegistered.tryAcquire(60, TimeUnit.SECONDS)); - // control multicast advertise agent to inject proxy - agent = MulticastDiscoveryAgentFactory.createDiscoveryAgent(new URI(discoveryAddress)); - agent.registerService(proxy.getUrl().toString()); - agent.start(); + // force an inactivity timeout via the proxy + proxy.pause(); - doReconnect(); - } + // wait for the inactivity timeout and network shutdown + assertTrue("network connector mbean unregistered within 1 minute", mbeanUnregistered.tryAcquire(60, TimeUnit.SECONDS)); - @Test - public void testSimpleReconnect() throws Exception { - brokerB.addNetworkConnector("simple://(" + proxy.getUrl() - + ")?useExponentialBackOff=false&initialReconnectDelay=500&discovered.wireFormat.maxInactivityDuration=1000&discovered.wireFormat.maxInactivityDurationInitalDelay=1000"); - brokerB.start(); - brokerB.waitUntilStarted(); - doReconnect(); - } + // whack all connections + proxy.close(); - private void doReconnect() throws Exception { - - for (int i=0; i= 1; - } - })); - - // wait for network connector - assertTrue("network connector mbean registered within 1 minute", mbeanRegistered.tryAcquire(60, TimeUnit.SECONDS)); - - // force an inactivity timeout via the proxy - proxy.pause(); - - // wait for the inactivity timeout and network shutdown - assertTrue("network connector mbean unregistered within 1 minute", mbeanUnregistered.tryAcquire(60, TimeUnit.SECONDS)); - - // whack all connections - proxy.close(); - - // let a reconnect succeed - proxy.reopen(); - } - } + // let a reconnect succeed + proxy.reopen(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryTransportBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryTransportBrokerTest.java index 2f77109d8b..d750243758 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryTransportBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryTransportBrokerTest.java @@ -41,122 +41,123 @@ import org.slf4j.LoggerFactory; public class DiscoveryTransportBrokerTest extends NetworkTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(DiscoveryTransportBrokerTest.class); + private static final Logger LOG = LoggerFactory.getLogger(DiscoveryTransportBrokerTest.class); - String groupName; - - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - } + String groupName; - public void testPublisherFailsOver() throws Exception { - ActiveMQDestination destination = new ActiveMQQueue("TEST"); - int deliveryMode = DeliveryMode.NON_PERSISTENT; + public void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); + } - // Start a normal consumer on the local broker - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.request(consumerInfo1); + public void testPublisherFailsOver() throws Exception { + ActiveMQDestination destination = new ActiveMQQueue("TEST"); + int deliveryMode = DeliveryMode.NON_PERSISTENT; - // Start a normal consumer on a remote broker - StubConnection connection2 = createRemoteConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.request(consumerInfo2); + // Start a normal consumer on the local broker + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.request(consumerInfo1); - // Start a failover publisher. - StubConnection connection3 = createFailoverConnection(); - ConnectionInfo connectionInfo3 = createConnectionInfo(); - SessionInfo sessionInfo3 = createSessionInfo(connectionInfo3); - ProducerInfo producerInfo3 = createProducerInfo(sessionInfo3); - connection3.send(connectionInfo3); - connection3.send(sessionInfo3); - connection3.send(producerInfo3); + // Start a normal consumer on a remote broker + StubConnection connection2 = createRemoteConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + connection2.request(consumerInfo2); - // Send the message using the fail over publisher. - connection3.request(createMessage(producerInfo3, destination, deliveryMode)); + // Start a failover publisher. + StubConnection connection3 = createFailoverConnection(); + ConnectionInfo connectionInfo3 = createConnectionInfo(); + SessionInfo sessionInfo3 = createSessionInfo(connectionInfo3); + ProducerInfo producerInfo3 = createProducerInfo(sessionInfo3); + connection3.send(connectionInfo3); + connection3.send(sessionInfo3); + connection3.send(producerInfo3); - // The message will be sent to one of the brokers. - FailoverTransport ft = (FailoverTransport)connection3.getTransport().narrow(FailoverTransport.class); + // Send the message using the fail over publisher. + connection3.request(createMessage(producerInfo3, destination, deliveryMode)); - // See which broker we were connected to. - StubConnection connectionA; - StubConnection connectionB; - TransportConnector serverA; - if (connector.getServer().getConnectURI().getPort() == ft.getConnectedTransportURI().getPort()) { - connectionA = connection1; - connectionB = connection2; - serverA = connector; - } else { - connectionA = connection2; - connectionB = connection1; - serverA = remoteConnector; - } + // The message will be sent to one of the brokers. + FailoverTransport ft = (FailoverTransport) connection3.getTransport().narrow(FailoverTransport.class); - assertNotNull(receiveMessage(connectionA)); - assertNoMessagesLeft(connectionB); + // See which broker we were connected to. + StubConnection connectionA; + StubConnection connectionB; + TransportConnector serverA; + if (connector.getServer().getConnectURI().getPort() == ft.getConnectedTransportURI().getPort()) { + connectionA = connection1; + connectionB = connection2; + serverA = connector; + } + else { + connectionA = connection2; + connectionB = connection1; + serverA = remoteConnector; + } - // Dispose the server so that it fails over to the other server. - LOG.info("Disconnecting active server"); - serverA.stop(); + assertNotNull(receiveMessage(connectionA)); + assertNoMessagesLeft(connectionB); - LOG.info("Sending request that should failover"); - connection3.request(createMessage(producerInfo3, destination, deliveryMode)); + // Dispose the server so that it fails over to the other server. + LOG.info("Disconnecting active server"); + serverA.stop(); - assertNotNull(receiveMessage(connectionB)); - assertNoMessagesLeft(connectionA); + LOG.info("Sending request that should failover"); + connection3.request(createMessage(producerInfo3, destination, deliveryMode)); - } + assertNotNull(receiveMessage(connectionB)); + assertNoMessagesLeft(connectionA); - protected String getLocalURI() { - return "tcp://localhost:0?wireFormat.tcpNoDelayEnabled=true"; - } + } - protected String getRemoteURI() { - return "tcp://localhost:0?wireFormat.tcpNoDelayEnabled=true"; - } + protected String getLocalURI() { + return "tcp://localhost:0?wireFormat.tcpNoDelayEnabled=true"; + } - protected TransportConnector createConnector() throws Exception, IOException, URISyntaxException { - TransportConnector x = super.createConnector(); - x.setDiscoveryUri(new URI(getDiscoveryUri())); - return x; - } + protected String getRemoteURI() { + return "tcp://localhost:0?wireFormat.tcpNoDelayEnabled=true"; + } - protected String getDiscoveryUri() { - if ( groupName == null ) { - groupName = "group-"+System.currentTimeMillis(); - } - return "multicast://default?group="+groupName; - } + protected TransportConnector createConnector() throws Exception, IOException, URISyntaxException { + TransportConnector x = super.createConnector(); + x.setDiscoveryUri(new URI(getDiscoveryUri())); + return x; + } - protected TransportConnector createRemoteConnector() throws Exception, IOException, URISyntaxException { - TransportConnector x = super.createRemoteConnector(); - x.setDiscoveryUri(new URI(getDiscoveryUri())); - return x; - } + protected String getDiscoveryUri() { + if (groupName == null) { + groupName = "group-" + System.currentTimeMillis(); + } + return "multicast://default?group=" + groupName; + } - protected StubConnection createFailoverConnection() throws Exception { - URI failoverURI = new URI("discovery:(" + getDiscoveryUri() + ")?startupMaxReconnectAttempts=10&initialReconnectDelay=1000"); - Transport transport = TransportFactory.connect(failoverURI); - StubConnection connection = new StubConnection(transport); - connections.add(connection); - return connection; - } + protected TransportConnector createRemoteConnector() throws Exception, IOException, URISyntaxException { + TransportConnector x = super.createRemoteConnector(); + x.setDiscoveryUri(new URI(getDiscoveryUri())); + return x; + } - public static Test suite() { - return suite(DiscoveryTransportBrokerTest.class); - } + protected StubConnection createFailoverConnection() throws Exception { + URI failoverURI = new URI("discovery:(" + getDiscoveryUri() + ")?startupMaxReconnectAttempts=10&initialReconnectDelay=1000"); + Transport transport = TransportFactory.connect(failoverURI); + StubConnection connection = new StubConnection(transport); + connections.add(connection); + return connection; + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static Test suite() { + return suite(DiscoveryTransportBrokerTest.class); + } + + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryTransportNoBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryTransportNoBrokerTest.java index 7ba24db55f..bf022f0eb1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryTransportNoBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryTransportNoBrokerTest.java @@ -36,144 +36,140 @@ import org.slf4j.LoggerFactory; public class DiscoveryTransportNoBrokerTest extends CombinationTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(DiscoveryTransportNoBrokerTest.class); + private static final Logger LOG = LoggerFactory.getLogger(DiscoveryTransportNoBrokerTest.class); - @Override - public void setUp() throws Exception { - setAutoFail(true); - super.setUp(); - } + @Override + public void setUp() throws Exception { + setAutoFail(true); + super.setUp(); + } - public void testNoExtraThreads() throws Exception { - BrokerService broker = new BrokerService(); - TransportConnector tcp = broker.addConnector("tcp://localhost:0?transport.closeAsync=false"); - String group = "GR-" + System.currentTimeMillis(); - URI discoveryUri = new URI("multicast://default?group=" + group); - tcp.setDiscoveryUri(discoveryUri); - broker.start(); - broker.waitUntilStarted(); + public void testNoExtraThreads() throws Exception { + BrokerService broker = new BrokerService(); + TransportConnector tcp = broker.addConnector("tcp://localhost:0?transport.closeAsync=false"); + String group = "GR-" + System.currentTimeMillis(); + URI discoveryUri = new URI("multicast://default?group=" + group); + tcp.setDiscoveryUri(discoveryUri); + broker.start(); + broker.waitUntilStarted(); - Vector existingNames = new Vector(); - Thread[] threads = getThreads(); - for (Thread t : threads) { - existingNames.add(t.getName()); - } - final int idleThreadCount = threads.length; - LOG.info("Broker started - thread Count:" + idleThreadCount); + Vector existingNames = new Vector(); + Thread[] threads = getThreads(); + for (Thread t : threads) { + existingNames.add(t.getName()); + } + final int idleThreadCount = threads.length; + LOG.info("Broker started - thread Count:" + idleThreadCount); - final int noConnectionToCreate = 10; - for (int i=0; i<10;i++) { - ActiveMQConnectionFactory factory = - new ActiveMQConnectionFactory("discovery:(multicast://239.255.2.3:6155?group=" + group +")?closeAsync=false&startupMaxReconnectAttempts=10&initialReconnectDelay=1000"); - LOG.info("Connecting."); - Connection connection = factory.createConnection(); - connection.setClientID("test"); - connection.close(); - } - Thread.sleep(2000); - threads = getThreads(); - for (Thread t : threads) { - if (!existingNames.contains(t.getName())) { - LOG.info("Remaining thread:" + t); - } - } - assertTrue("no extra threads per connection", Thread.activeCount() - idleThreadCount < noConnectionToCreate); - } + final int noConnectionToCreate = 10; + for (int i = 0; i < 10; i++) { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("discovery:(multicast://239.255.2.3:6155?group=" + group + ")?closeAsync=false&startupMaxReconnectAttempts=10&initialReconnectDelay=1000"); + LOG.info("Connecting."); + Connection connection = factory.createConnection(); + connection.setClientID("test"); + connection.close(); + } + Thread.sleep(2000); + threads = getThreads(); + for (Thread t : threads) { + if (!existingNames.contains(t.getName())) { + LOG.info("Remaining thread:" + t); + } + } + assertTrue("no extra threads per connection", Thread.activeCount() - idleThreadCount < noConnectionToCreate); + } + private Thread[] getThreads() { + Thread[] threads = new Thread[Thread.activeCount()]; + Thread.enumerate(threads); + return threads; + } - private Thread[] getThreads() { - Thread[] threads = new Thread[Thread.activeCount()]; - Thread.enumerate(threads); - return threads; - } + public void testMaxReconnectAttempts() throws JMSException { + try { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("discovery:(multicast://doesNOTexist)"); + LOG.info("Connecting."); + Connection connection = factory.createConnection(); + connection.setClientID("test"); + fail("Did not fail to connect as expected."); + } + catch (JMSException expected) { + assertTrue("reason is java.io.IOException, was: " + expected.getCause(), expected.getCause() instanceof java.io.IOException); + } + } + public void testInitialConnectDelayWithNoBroker() throws Exception { + // the initialReconnectDelay only kicks in once a set of connect URL have + // been returned from the discovery agent. + // Up to that point the reconnectDelay is used which has a default value of 10 + // + long initialReconnectDelay = 4000; + long startT = System.currentTimeMillis(); + String groupId = "WillNotMatch" + startT; + try { + String urlStr = "discovery:(multicast://default?group=" + groupId + + ")?useExponentialBackOff=false&maxReconnectAttempts=2&reconnectDelay=" + initialReconnectDelay; + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(urlStr); + LOG.info("Connecting."); + Connection connection = factory.createConnection(); + connection.setClientID("test"); + fail("Did not fail to connect as expected."); + } + catch (JMSException expected) { + assertTrue("reason is java.io.IOException, was: " + expected.getCause(), expected.getCause() instanceof java.io.IOException); + long duration = System.currentTimeMillis() - startT; + assertTrue("took at least initialReconnectDelay time: " + duration + " e:" + expected, duration >= initialReconnectDelay); + } + } - public void testMaxReconnectAttempts() throws JMSException { - try { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("discovery:(multicast://doesNOTexist)"); - LOG.info("Connecting."); - Connection connection = factory.createConnection(); - connection.setClientID("test"); - fail("Did not fail to connect as expected."); - } - catch ( JMSException expected ) { - assertTrue("reason is java.io.IOException, was: " + expected.getCause(), expected.getCause() instanceof java.io.IOException); - } - } + public void testSetDiscoveredBrokerProperties() throws Exception { + final String extraParameterName = "connectionTimeout"; + final String extraParameterValue = "3000"; + final URI uri = new URI("discovery:(multicast://default)?initialReconnectDelay=100&" + DiscoveryListener.DISCOVERED_OPTION_PREFIX + extraParameterName + "=" + extraParameterValue); + CompositeData compositeData = URISupport.parseComposite(uri); - public void testInitialConnectDelayWithNoBroker() throws Exception { - // the initialReconnectDelay only kicks in once a set of connect URL have - // been returned from the discovery agent. - // Up to that point the reconnectDelay is used which has a default value of 10 - // - long initialReconnectDelay = 4000; - long startT = System.currentTimeMillis(); - String groupId = "WillNotMatch" + startT; - try { - String urlStr = "discovery:(multicast://default?group=" + groupId + - ")?useExponentialBackOff=false&maxReconnectAttempts=2&reconnectDelay=" + initialReconnectDelay; - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(urlStr); - LOG.info("Connecting."); - Connection connection = factory.createConnection(); - connection.setClientID("test"); - fail("Did not fail to connect as expected."); - } catch ( JMSException expected ) { - assertTrue("reason is java.io.IOException, was: " + expected.getCause(), expected.getCause() instanceof java.io.IOException); - long duration = System.currentTimeMillis() - startT; - assertTrue("took at least initialReconnectDelay time: " + duration + " e:" + expected, duration >= initialReconnectDelay); - } - } + StubCompositeTransport compositeTransport = new StubCompositeTransport(); + DiscoveryTransport discoveryTransport = DiscoveryTransportFactory.createTransport(compositeTransport, compositeData, compositeData.getParameters()); - public void testSetDiscoveredBrokerProperties() throws Exception { - final String extraParameterName = "connectionTimeout"; - final String extraParameterValue = "3000"; - final URI uri = new URI("discovery:(multicast://default)?initialReconnectDelay=100&" - + DiscoveryListener.DISCOVERED_OPTION_PREFIX + extraParameterName + "=" + extraParameterValue); - CompositeData compositeData = URISupport.parseComposite(uri); + discoveryTransport.onServiceAdd(new DiscoveryEvent("tcp://localhost:61616")); + assertEquals("expected added URI after discovery event", compositeTransport.getTransportURIs().length, 1); - StubCompositeTransport compositeTransport = new StubCompositeTransport(); - DiscoveryTransport discoveryTransport = DiscoveryTransportFactory.createTransport(compositeTransport, compositeData, compositeData.getParameters()); + URI discoveredServiceURI = compositeTransport.getTransportURIs()[0]; + Map parameters = URISupport.parseParameters(discoveredServiceURI); + assertTrue("unable to add parameter to discovered service", parameters.containsKey(extraParameterName)); + assertEquals("incorrect value for parameter added to discovered service", parameters.get(extraParameterName), extraParameterValue); + } - discoveryTransport.onServiceAdd(new DiscoveryEvent("tcp://localhost:61616")); - assertEquals("expected added URI after discovery event", compositeTransport.getTransportURIs().length, 1); + public void testSetDiscoveredStaticBrokerProperties() throws Exception { + final String extraParameterName = "connectionTimeout"; + final String extraParameterValue = "3000"; + final URI uri = new URI("discovery:(static:tcp://localhost:61616)?initialReconnectDelay=100&" + DiscoveryListener.DISCOVERED_OPTION_PREFIX + extraParameterName + "=" + extraParameterValue); + CompositeData compositeData = URISupport.parseComposite(uri); - URI discoveredServiceURI = compositeTransport.getTransportURIs()[0]; - Map parameters = URISupport.parseParameters(discoveredServiceURI); - assertTrue("unable to add parameter to discovered service", parameters.containsKey(extraParameterName)); - assertEquals("incorrect value for parameter added to discovered service", parameters.get(extraParameterName), extraParameterValue); - } + StubCompositeTransport compositeTransport = new StubCompositeTransport(); + DiscoveryTransport discoveryTransport = DiscoveryTransportFactory.createTransport(compositeTransport, compositeData, compositeData.getParameters()); - public void testSetDiscoveredStaticBrokerProperties() throws Exception { - final String extraParameterName = "connectionTimeout"; - final String extraParameterValue = "3000"; - final URI uri = new URI("discovery:(static:tcp://localhost:61616)?initialReconnectDelay=100&" - + DiscoveryListener.DISCOVERED_OPTION_PREFIX + extraParameterName + "=" + extraParameterValue); - CompositeData compositeData = URISupport.parseComposite(uri); + discoveryTransport.start(); + assertEquals("expected added URI after discovery event", 1, compositeTransport.getTransportURIs().length); - StubCompositeTransport compositeTransport = new StubCompositeTransport(); - DiscoveryTransport discoveryTransport = DiscoveryTransportFactory.createTransport(compositeTransport, compositeData, compositeData.getParameters()); + URI discoveredServiceURI = compositeTransport.getTransportURIs()[0]; + Map parameters = URISupport.parseParameters(discoveredServiceURI); + assertTrue("unable to add parameter to discovered service", parameters.containsKey(extraParameterName)); + assertEquals("incorrect value for parameter added to discovered service", parameters.get(extraParameterName), extraParameterValue); + } - discoveryTransport.start(); - assertEquals("expected added URI after discovery event", 1, compositeTransport.getTransportURIs().length); + public void testAddRemoveDiscoveredBroker() throws Exception { + final URI uri = new URI("discovery:(multicast://default)?initialReconnectDelay=100&connectionTimeout=3000"); + CompositeData compositeData = URISupport.parseComposite(uri); - URI discoveredServiceURI = compositeTransport.getTransportURIs()[0]; - Map parameters = URISupport.parseParameters(discoveredServiceURI); - assertTrue("unable to add parameter to discovered service", parameters.containsKey(extraParameterName)); - assertEquals("incorrect value for parameter added to discovered service", parameters.get(extraParameterName), extraParameterValue); - } + StubCompositeTransport compositeTransport = new StubCompositeTransport(); + DiscoveryTransport discoveryTransport = DiscoveryTransportFactory.createTransport(compositeTransport, compositeData, compositeData.getParameters()); - public void testAddRemoveDiscoveredBroker() throws Exception { - final URI uri = new URI("discovery:(multicast://default)?initialReconnectDelay=100&connectionTimeout=3000"); - CompositeData compositeData = URISupport.parseComposite(uri); + final String serviceName = "tcp://localhost:61616"; + discoveryTransport.onServiceAdd(new DiscoveryEvent(serviceName)); + assertEquals("expected added URI after discovery event", 1, compositeTransport.getTransportURIs().length); - StubCompositeTransport compositeTransport = new StubCompositeTransport(); - DiscoveryTransport discoveryTransport = DiscoveryTransportFactory.createTransport(compositeTransport, compositeData, compositeData.getParameters()); - - final String serviceName = "tcp://localhost:61616"; - discoveryTransport.onServiceAdd(new DiscoveryEvent(serviceName)); - assertEquals("expected added URI after discovery event", 1, compositeTransport.getTransportURIs().length); - - discoveryTransport.onServiceRemove(new DiscoveryEvent(serviceName)); - assertEquals("expected URI removed after discovery event", 0, compositeTransport.getTransportURIs().length); - } + discoveryTransport.onServiceRemove(new DiscoveryEvent(serviceName)); + assertEquals("expected URI removed after discovery event", 0, compositeTransport.getTransportURIs().length); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryUriTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryUriTest.java index 778d03d9f0..b902c2533a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryUriTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryUriTest.java @@ -27,39 +27,40 @@ import java.net.URI; public class DiscoveryUriTest extends EmbeddedBrokerTestSupport { - @Override - protected BrokerService createBroker() throws Exception { - bindAddress = "tcp://localhost:0"; - BrokerService answer = new BrokerService(); - answer.setPersistent(isPersistent()); - TransportConnector connector = new TransportConnector(); - connector.setUri(new URI(bindAddress)); - connector.setDiscoveryUri(new URI("multicast://default?group=test")); - answer.addConnector(connector); - return answer; - } + @Override + protected BrokerService createBroker() throws Exception { + bindAddress = "tcp://localhost:0"; + BrokerService answer = new BrokerService(); + answer.setPersistent(isPersistent()); + TransportConnector connector = new TransportConnector(); + connector.setUri(new URI(bindAddress)); + connector.setDiscoveryUri(new URI("multicast://default?group=test")); + answer.addConnector(connector); + return answer; + } - public void testConnect() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("discovery:(multicast://default?group=test)?reconnectDelay=1000&maxReconnectAttempts=30&useExponentialBackOff=false"); - Connection conn = factory.createConnection(); - conn.start(); + public void testConnect() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("discovery:(multicast://default?group=test)?reconnectDelay=1000&maxReconnectAttempts=30&useExponentialBackOff=false"); + Connection conn = factory.createConnection(); + conn.start(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = sess.createProducer(sess.createQueue("test")); - producer.send(sess.createTextMessage("test")); - MessageConsumer consumer = sess.createConsumer(sess.createQueue("test")); - Message msg = consumer.receive(1000); - assertNotNull(msg); - } + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = sess.createProducer(sess.createQueue("test")); + producer.send(sess.createTextMessage("test")); + MessageConsumer consumer = sess.createConsumer(sess.createQueue("test")); + Message msg = consumer.receive(1000); + assertNotNull(msg); + } - public void testFailedConnect() throws Exception { - try { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("discovery:(multicast://default?group=test1)?reconnectDelay=1000&startupMaxReconnectAttempts=3&useExponentialBackOff=false"); - Connection conn = factory.createConnection(); - conn.start(); - } catch (Exception e) { - return; - } - fail("Expected connection failure"); - } + public void testFailedConnect() throws Exception { + try { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("discovery:(multicast://default?group=test1)?reconnectDelay=1000&startupMaxReconnectAttempts=3&useExponentialBackOff=false"); + Connection conn = factory.createConnection(); + conn.start(); + } + catch (Exception e) { + return; + } + fail("Expected connection failure"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/ZeroconfDiscoverTransportTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/ZeroconfDiscoverTransportTest.java index 92614107d6..0a3142f097 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/ZeroconfDiscoverTransportTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/ZeroconfDiscoverTransportTest.java @@ -18,12 +18,12 @@ package org.apache.activemq.transport.discovery; /** * - * + * */ public class ZeroconfDiscoverTransportTest extends DiscoveryTransportBrokerTest { - protected String getDiscoveryUri() { - return "zeroconf://cheese"; - } + protected String getDiscoveryUri() { + return "zeroconf://cheese"; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/AMQ1925Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/AMQ1925Test.java index d03dbcd41c..e1f976293e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/AMQ1925Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/AMQ1925Test.java @@ -48,348 +48,326 @@ import org.apache.log4j.Logger; /** * TestCase showing the message-destroying described in AMQ-1925 - * - * */ public class AMQ1925Test extends TestCase implements ExceptionListener { - private static final Logger log = Logger.getLogger(AMQ1925Test.class); - private static final String QUEUE_NAME = "test.amq1925"; - private static final String PROPERTY_MSG_NUMBER = "NUMBER"; - private static final int MESSAGE_COUNT = 10000; + private static final Logger log = Logger.getLogger(AMQ1925Test.class); - private BrokerService bs; - private URI tcpUri; - private ActiveMQConnectionFactory cf; + private static final String QUEUE_NAME = "test.amq1925"; + private static final String PROPERTY_MSG_NUMBER = "NUMBER"; + private static final int MESSAGE_COUNT = 10000; - private JMSException exception; + private BrokerService bs; + private URI tcpUri; + private ActiveMQConnectionFactory cf; - public void XtestAMQ1925_TXInProgress() throws Exception { - Connection connection = cf.createConnection(); - connection.start(); - Session session = connection.createSession(true, - Session.SESSION_TRANSACTED); - MessageConsumer consumer = session.createConsumer(session - .createQueue(QUEUE_NAME)); + private JMSException exception; - // The runnable is likely to interrupt during the session#commit, since - // this takes the longest - final CountDownLatch starter = new CountDownLatch(1); - final AtomicBoolean restarted = new AtomicBoolean(); - new Thread(new Runnable() { - public void run() { - try { - starter.await(); + public void XtestAMQ1925_TXInProgress() throws Exception { + Connection connection = cf.createConnection(); + connection.start(); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME)); - // Simulate broker failure & restart - bs.stop(); - bs = new BrokerService(); - bs.setPersistent(true); - bs.setUseJmx(true); - bs.addConnector(tcpUri); - bs.start(); + // The runnable is likely to interrupt during the session#commit, since + // this takes the longest + final CountDownLatch starter = new CountDownLatch(1); + final AtomicBoolean restarted = new AtomicBoolean(); + new Thread(new Runnable() { + public void run() { + try { + starter.await(); - restarted.set(true); - } catch (Exception e) { - e.printStackTrace(); - } - } - }).start(); + // Simulate broker failure & restart + bs.stop(); + bs = new BrokerService(); + bs.setPersistent(true); + bs.setUseJmx(true); + bs.addConnector(tcpUri); + bs.start(); - for (int i = 0; i < MESSAGE_COUNT; i++) { - Message message = consumer.receive(500); - assertNotNull("No Message " + i + " found", message); + restarted.set(true); + } + catch (Exception e) { + e.printStackTrace(); + } + } + }).start(); - if (i < 10) - assertFalse("Timing problem, restarted too soon", restarted - .get()); - if (i == 10) { - starter.countDown(); - } - if (i > MESSAGE_COUNT - 100) { - assertTrue("Timing problem, restarted too late", restarted - .get()); - } + for (int i = 0; i < MESSAGE_COUNT; i++) { + Message message = consumer.receive(500); + assertNotNull("No Message " + i + " found", message); - assertEquals(i, message.getIntProperty(PROPERTY_MSG_NUMBER)); - session.commit(); - } - assertNull(consumer.receive(500)); + if (i < 10) + assertFalse("Timing problem, restarted too soon", restarted.get()); + if (i == 10) { + starter.countDown(); + } + if (i > MESSAGE_COUNT - 100) { + assertTrue("Timing problem, restarted too late", restarted.get()); + } - consumer.close(); - session.close(); - connection.close(); + assertEquals(i, message.getIntProperty(PROPERTY_MSG_NUMBER)); + session.commit(); + } + assertNull(consumer.receive(500)); - assertQueueEmpty(); - } + consumer.close(); + session.close(); + connection.close(); - public void XtestAMQ1925_TXInProgress_TwoConsumers() throws Exception { - Connection connection = cf.createConnection(); - connection.start(); - Session session1 = connection.createSession(true, - Session.SESSION_TRANSACTED); - MessageConsumer consumer1 = session1.createConsumer(session1 - .createQueue(QUEUE_NAME)); - Session session2 = connection.createSession(true, - Session.SESSION_TRANSACTED); - MessageConsumer consumer2 = session2.createConsumer(session2 - .createQueue(QUEUE_NAME)); + assertQueueEmpty(); + } - // The runnable is likely to interrupt during the session#commit, since - // this takes the longest - final CountDownLatch starter = new CountDownLatch(1); - final AtomicBoolean restarted = new AtomicBoolean(); - new Thread(new Runnable() { - public void run() { - try { - starter.await(); + public void XtestAMQ1925_TXInProgress_TwoConsumers() throws Exception { + Connection connection = cf.createConnection(); + connection.start(); + Session session1 = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageConsumer consumer1 = session1.createConsumer(session1.createQueue(QUEUE_NAME)); + Session session2 = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageConsumer consumer2 = session2.createConsumer(session2.createQueue(QUEUE_NAME)); - // Simulate broker failure & restart - bs.stop(); - bs = new BrokerService(); - bs.setPersistent(true); - bs.setUseJmx(true); - bs.addConnector(tcpUri); - bs.start(); + // The runnable is likely to interrupt during the session#commit, since + // this takes the longest + final CountDownLatch starter = new CountDownLatch(1); + final AtomicBoolean restarted = new AtomicBoolean(); + new Thread(new Runnable() { + public void run() { + try { + starter.await(); - restarted.set(true); - } catch (Exception e) { - e.printStackTrace(); - } - } - }).start(); + // Simulate broker failure & restart + bs.stop(); + bs = new BrokerService(); + bs.setPersistent(true); + bs.setUseJmx(true); + bs.addConnector(tcpUri); + bs.start(); - Collection results = new ArrayList(MESSAGE_COUNT); - for (int i = 0; i < MESSAGE_COUNT; i++) { - Message message1 = consumer1.receive(20); - Message message2 = consumer2.receive(20); - if (message1 == null && message2 == null) { - if (results.size() < MESSAGE_COUNT) { - message1 = consumer1.receive(500); - message2 = consumer2.receive(500); + restarted.set(true); + } + catch (Exception e) { + e.printStackTrace(); + } + } + }).start(); - if (message1 == null && message2 == null) { - // Missing messages - break; - } - } - break; - } + Collection results = new ArrayList(MESSAGE_COUNT); + for (int i = 0; i < MESSAGE_COUNT; i++) { + Message message1 = consumer1.receive(20); + Message message2 = consumer2.receive(20); + if (message1 == null && message2 == null) { + if (results.size() < MESSAGE_COUNT) { + message1 = consumer1.receive(500); + message2 = consumer2.receive(500); - if (i < 10) - assertFalse("Timing problem, restarted too soon", restarted - .get()); - if (i == 10) { - starter.countDown(); - } - if (i > MESSAGE_COUNT - 50) { - assertTrue("Timing problem, restarted too late", restarted - .get()); - } + if (message1 == null && message2 == null) { + // Missing messages + break; + } + } + break; + } - if (message1 != null) { - results.add(message1.getIntProperty(PROPERTY_MSG_NUMBER)); - session1.commit(); - } - if (message2 != null) { - results.add(message2.getIntProperty(PROPERTY_MSG_NUMBER)); - session2.commit(); - } - } - assertNull(consumer1.receive(500)); - assertNull(consumer2.receive(500)); + if (i < 10) + assertFalse("Timing problem, restarted too soon", restarted.get()); + if (i == 10) { + starter.countDown(); + } + if (i > MESSAGE_COUNT - 50) { + assertTrue("Timing problem, restarted too late", restarted.get()); + } - consumer1.close(); - session1.close(); - consumer2.close(); - session2.close(); - connection.close(); + if (message1 != null) { + results.add(message1.getIntProperty(PROPERTY_MSG_NUMBER)); + session1.commit(); + } + if (message2 != null) { + results.add(message2.getIntProperty(PROPERTY_MSG_NUMBER)); + session2.commit(); + } + } + assertNull(consumer1.receive(500)); + assertNull(consumer2.receive(500)); - int foundMissingMessages = 0; - if (results.size() < MESSAGE_COUNT) { - foundMissingMessages = tryToFetchMissingMessages(); - } - for (int i = 0; i < MESSAGE_COUNT; i++) { - assertTrue("Message-Nr " + i + " not found (" + results.size() - + " total, " + foundMissingMessages - + " have been found 'lingering' in the queue)", results - .contains(i)); - } - assertQueueEmpty(); - } + consumer1.close(); + session1.close(); + consumer2.close(); + session2.close(); + connection.close(); - private int tryToFetchMissingMessages() throws JMSException { - Connection connection = cf.createConnection(); - connection.start(); - Session session = connection.createSession(true, 0); - MessageConsumer consumer = session.createConsumer(session - .createQueue(QUEUE_NAME)); + int foundMissingMessages = 0; + if (results.size() < MESSAGE_COUNT) { + foundMissingMessages = tryToFetchMissingMessages(); + } + for (int i = 0; i < MESSAGE_COUNT; i++) { + assertTrue("Message-Nr " + i + " not found (" + results.size() + " total, " + foundMissingMessages + " have been found 'lingering' in the queue)", results.contains(i)); + } + assertQueueEmpty(); + } - int count = 0; - while (true) { - Message message = consumer.receive(500); - if (message == null) - break; + private int tryToFetchMissingMessages() throws JMSException { + Connection connection = cf.createConnection(); + connection.start(); + Session session = connection.createSession(true, 0); + MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME)); - log.info("Found \"missing\" message: " + message); - count++; - } + int count = 0; + while (true) { + Message message = consumer.receive(500); + if (message == null) + break; - consumer.close(); - session.close(); - connection.close(); + log.info("Found \"missing\" message: " + message); + count++; + } - return count; - } + consumer.close(); + session.close(); + connection.close(); - public void testAMQ1925_TXBegin() throws Exception { - Connection connection = cf.createConnection(); - connection.start(); - connection.setExceptionListener(this); - Session session = connection.createSession(true, - Session.SESSION_TRANSACTED); - MessageConsumer consumer = session.createConsumer(session - .createQueue(QUEUE_NAME)); + return count; + } - boolean restartDone = false; - for (int i = 0; i < MESSAGE_COUNT; i++) { - Message message = consumer.receive(5000); - assertNotNull(message); + public void testAMQ1925_TXBegin() throws Exception { + Connection connection = cf.createConnection(); + connection.start(); + connection.setExceptionListener(this); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME)); - if (i == 222 && !restartDone) { - // Simulate broker failure & restart - bs.stop(); - bs = new BrokerService(); - bs.setPersistent(true); - bs.setUseJmx(true); - bs.addConnector(tcpUri); - bs.start(); - restartDone = true; - } + boolean restartDone = false; + for (int i = 0; i < MESSAGE_COUNT; i++) { + Message message = consumer.receive(5000); + assertNotNull(message); - assertEquals(i, message.getIntProperty(PROPERTY_MSG_NUMBER)); - try { - session.commit(); - } catch (TransactionRolledBackException expectedOnOccasion) { - log.info("got rollback: " + expectedOnOccasion); - i--; - } - } - assertNull(consumer.receive(500)); + if (i == 222 && !restartDone) { + // Simulate broker failure & restart + bs.stop(); + bs = new BrokerService(); + bs.setPersistent(true); + bs.setUseJmx(true); + bs.addConnector(tcpUri); + bs.start(); + restartDone = true; + } - consumer.close(); - session.close(); - connection.close(); + assertEquals(i, message.getIntProperty(PROPERTY_MSG_NUMBER)); + try { + session.commit(); + } + catch (TransactionRolledBackException expectedOnOccasion) { + log.info("got rollback: " + expectedOnOccasion); + i--; + } + } + assertNull(consumer.receive(500)); - assertQueueEmpty(); - assertNull("no exception on connection listener: " + exception, exception); - } + consumer.close(); + session.close(); + connection.close(); - public void testAMQ1925_TXCommited() throws Exception { - Connection connection = cf.createConnection(); - connection.start(); - Session session = connection.createSession(true, - Session.SESSION_TRANSACTED); - MessageConsumer consumer = session.createConsumer(session - .createQueue(QUEUE_NAME)); + assertQueueEmpty(); + assertNull("no exception on connection listener: " + exception, exception); + } - for (int i = 0; i < MESSAGE_COUNT; i++) { - Message message = consumer.receive(5000); - assertNotNull(message); + public void testAMQ1925_TXCommited() throws Exception { + Connection connection = cf.createConnection(); + connection.start(); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME)); - assertEquals(i, message.getIntProperty(PROPERTY_MSG_NUMBER)); - session.commit(); + for (int i = 0; i < MESSAGE_COUNT; i++) { + Message message = consumer.receive(5000); + assertNotNull(message); - if (i == 222) { - // Simulate broker failure & restart - bs.stop(); - bs = new BrokerService(); - bs.setPersistent(true); - bs.setUseJmx(true); - bs.addConnector(tcpUri); - bs.start(); - } - } - assertNull(consumer.receive(500)); + assertEquals(i, message.getIntProperty(PROPERTY_MSG_NUMBER)); + session.commit(); - consumer.close(); - session.close(); - connection.close(); + if (i == 222) { + // Simulate broker failure & restart + bs.stop(); + bs = new BrokerService(); + bs.setPersistent(true); + bs.setUseJmx(true); + bs.addConnector(tcpUri); + bs.start(); + } + } + assertNull(consumer.receive(500)); - assertQueueEmpty(); - } + consumer.close(); + session.close(); + connection.close(); - private void assertQueueEmpty() throws Exception { - Connection connection = cf.createConnection(); - connection.start(); - Session session = connection.createSession(true, - Session.SESSION_TRANSACTED); - MessageConsumer consumer = session.createConsumer(session - .createQueue(QUEUE_NAME)); + assertQueueEmpty(); + } - Message msg = consumer.receive(500); - if (msg != null) { - fail(msg.toString()); - } + private void assertQueueEmpty() throws Exception { + Connection connection = cf.createConnection(); + connection.start(); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME)); - consumer.close(); - session.close(); - connection.close(); + Message msg = consumer.receive(500); + if (msg != null) { + fail(msg.toString()); + } - assertQueueLength(0); - } + consumer.close(); + session.close(); + connection.close(); - private void assertQueueLength(int len) throws Exception, IOException { - Set destinations = bs.getBroker().getDestinations( - new ActiveMQQueue(QUEUE_NAME)); - Queue queue = (Queue) destinations.iterator().next(); - assertEquals(len, queue.getMessageStore().getMessageCount()); - } + assertQueueLength(0); + } - private void sendMessagesToQueue() throws Exception { - Connection connection = cf.createConnection(); - Session session = connection.createSession(true, - Session.SESSION_TRANSACTED); - MessageProducer producer = session.createProducer(session - .createQueue(QUEUE_NAME)); + private void assertQueueLength(int len) throws Exception, IOException { + Set destinations = bs.getBroker().getDestinations(new ActiveMQQueue(QUEUE_NAME)); + Queue queue = (Queue) destinations.iterator().next(); + assertEquals(len, queue.getMessageStore().getMessageCount()); + } - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - for (int i = 0; i < MESSAGE_COUNT; i++) { - TextMessage message = session - .createTextMessage("Test message " + i); - message.setIntProperty(PROPERTY_MSG_NUMBER, i); - producer.send(message); - } - session.commit(); + private void sendMessagesToQueue() throws Exception { + Connection connection = cf.createConnection(); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageProducer producer = session.createProducer(session.createQueue(QUEUE_NAME)); - producer.close(); - session.close(); - connection.close(); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + for (int i = 0; i < MESSAGE_COUNT; i++) { + TextMessage message = session.createTextMessage("Test message " + i); + message.setIntProperty(PROPERTY_MSG_NUMBER, i); + producer.send(message); + } + session.commit(); - assertQueueLength(MESSAGE_COUNT); - } + producer.close(); + session.close(); + connection.close(); - protected void setUp() throws Exception { - exception = null; - bs = new BrokerService(); - bs.setDeleteAllMessagesOnStartup(true); - bs.setPersistent(true); - bs.setUseJmx(true); - TransportConnector connector = bs.addConnector("tcp://localhost:0"); - bs.start(); - tcpUri = connector.getConnectUri(); + assertQueueLength(MESSAGE_COUNT); + } - cf = new ActiveMQConnectionFactory("failover://(" + tcpUri + ")"); + protected void setUp() throws Exception { + exception = null; + bs = new BrokerService(); + bs.setDeleteAllMessagesOnStartup(true); + bs.setPersistent(true); + bs.setUseJmx(true); + TransportConnector connector = bs.addConnector("tcp://localhost:0"); + bs.start(); + tcpUri = connector.getConnectUri(); - sendMessagesToQueue(); - } + cf = new ActiveMQConnectionFactory("failover://(" + tcpUri + ")"); - protected void tearDown() throws Exception { - new ServiceStopper().stop(bs); - } + sendMessagesToQueue(); + } - public void onException(JMSException exception) { - this.exception = exception; - } + protected void tearDown() throws Exception { + new ServiceStopper().stop(bs); + } + + public void onException(JMSException exception) { + this.exception = exception; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/BadConnectionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/BadConnectionTest.java index dd89456e87..54f3fe4134 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/BadConnectionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/BadConnectionTest.java @@ -20,6 +20,7 @@ import java.io.IOException; import java.net.URI; import junit.framework.TestCase; + import org.apache.activemq.command.ActiveMQMessage; import org.apache.activemq.transport.Transport; import org.apache.activemq.transport.TransportFactory; @@ -28,50 +29,51 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class BadConnectionTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(BadConnectionTest.class); + private static final Logger LOG = LoggerFactory.getLogger(BadConnectionTest.class); - protected Transport transport; + protected Transport transport; - public void testConnectingToUnavailableServer() throws Exception { - try { - transport.asyncRequest(new ActiveMQMessage(), null); - fail("This should never succeed"); - } catch (IOException e) { - LOG.info("Caught expected exception: " + e, e); - } - } + public void testConnectingToUnavailableServer() throws Exception { + try { + transport.asyncRequest(new ActiveMQMessage(), null); + fail("This should never succeed"); + } + catch (IOException e) { + LOG.info("Caught expected exception: " + e, e); + } + } - protected Transport createTransport() throws Exception { - return TransportFactory.connect(new URI("failover://(tcp://doesNotExist:1234)?useExponentialBackOff=false&maxReconnectAttempts=3&initialReconnectDelay=100")); - } + protected Transport createTransport() throws Exception { + return TransportFactory.connect(new URI("failover://(tcp://doesNotExist:1234)?useExponentialBackOff=false&maxReconnectAttempts=3&initialReconnectDelay=100")); + } - protected void setUp() throws Exception { - transport = createTransport(); - transport.setTransportListener(new TransportListener() { + protected void setUp() throws Exception { + transport = createTransport(); + transport.setTransportListener(new TransportListener() { - public void onCommand(Object command) { - } + public void onCommand(Object command) { + } - public void onException(IOException error) { - } + public void onException(IOException error) { + } - public void transportInterupted() { - } + public void transportInterupted() { + } - public void transportResumed() { - } - }); - transport.start(); - } + public void transportResumed() { + } + }); + transport.start(); + } - protected void tearDown() throws Exception { - if (transport != null) { - transport.stop(); - } - } + protected void tearDown() throws Exception { + if (transport != null) { + transport.stop(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/ConnectionHangOnStartupTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/ConnectionHangOnStartupTest.java index 09e496e943..6f38203b7a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/ConnectionHangOnStartupTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/ConnectionHangOnStartupTest.java @@ -35,76 +35,77 @@ import org.springframework.core.io.ClassPathResource; */ public class ConnectionHangOnStartupTest { - private static final Logger LOG = LoggerFactory.getLogger(ConnectionHangOnStartupTest.class); + private static final Logger LOG = LoggerFactory.getLogger(ConnectionHangOnStartupTest.class); - // short maxInactivityDurationInitalDelay to trigger the bug, short - // maxReconnectDelay so that the test runs faster (because it will retry - // connection sooner) - protected String uriString = "failover://(tcp://localhost:62001?wireFormat.maxInactivityDurationInitalDelay=1,tcp://localhost:62002?wireFormat.maxInactivityDurationInitalDelay=1)?randomize=false&maxReconnectDelay=200"; - protected BrokerService master = null; - protected AtomicReference slave = new AtomicReference(); + // short maxInactivityDurationInitalDelay to trigger the bug, short + // maxReconnectDelay so that the test runs faster (because it will retry + // connection sooner) + protected String uriString = "failover://(tcp://localhost:62001?wireFormat.maxInactivityDurationInitalDelay=1,tcp://localhost:62002?wireFormat.maxInactivityDurationInitalDelay=1)?randomize=false&maxReconnectDelay=200"; + protected BrokerService master = null; + protected AtomicReference slave = new AtomicReference(); - @After - public void tearDown() throws Exception { + @After + public void tearDown() throws Exception { - BrokerService brokerService = slave.get(); - if (brokerService != null) { - brokerService.stop(); - } - if (master != null) - master.stop(); - } + BrokerService brokerService = slave.get(); + if (brokerService != null) { + brokerService.stop(); + } + if (master != null) + master.stop(); + } - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(uriString); - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory(uriString); + } - protected void createMaster() throws Exception { - BrokerFactoryBean brokerFactory = new BrokerFactoryBean(new ClassPathResource(getMasterXml())); - brokerFactory.afterPropertiesSet(); - master = brokerFactory.getBroker(); - master.start(); - } + protected void createMaster() throws Exception { + BrokerFactoryBean brokerFactory = new BrokerFactoryBean(new ClassPathResource(getMasterXml())); + brokerFactory.afterPropertiesSet(); + master = brokerFactory.getBroker(); + master.start(); + } - protected void createSlave() throws Exception { - BrokerFactoryBean brokerFactory = new BrokerFactoryBean(new ClassPathResource(getSlaveXml())); - brokerFactory.afterPropertiesSet(); - BrokerService broker = brokerFactory.getBroker(); - broker.start(); - slave.set(broker); - } + protected void createSlave() throws Exception { + BrokerFactoryBean brokerFactory = new BrokerFactoryBean(new ClassPathResource(getSlaveXml())); + brokerFactory.afterPropertiesSet(); + BrokerService broker = brokerFactory.getBroker(); + broker.start(); + slave.set(broker); + } - protected String getSlaveXml() { - return "org/apache/activemq/broker/ft/sharedFileSlave.xml"; - } + protected String getSlaveXml() { + return "org/apache/activemq/broker/ft/sharedFileSlave.xml"; + } - protected String getMasterXml() { - return "org/apache/activemq/broker/ft/sharedFileMaster.xml"; - } + protected String getMasterXml() { + return "org/apache/activemq/broker/ft/sharedFileMaster.xml"; + } - @Test(timeout=60000) - public void testInitialWireFormatNegotiationTimeout() throws Exception { - final AtomicReference conn = new AtomicReference(); - final CountDownLatch connStarted = new CountDownLatch(1); + @Test(timeout = 60000) + public void testInitialWireFormatNegotiationTimeout() throws Exception { + final AtomicReference conn = new AtomicReference(); + final CountDownLatch connStarted = new CountDownLatch(1); - Thread t = new Thread() { - @Override - public void run() { - try { - conn.set(createConnectionFactory().createConnection()); - conn.get().start(); - } catch (Exception ex) { - LOG.error("could not create or start connection", ex); - } - connStarted.countDown(); + Thread t = new Thread() { + @Override + public void run() { + try { + conn.set(createConnectionFactory().createConnection()); + conn.get().start(); } - }; - t.start(); - createMaster(); - // slave will never start unless the master dies! - //createSlave(); + catch (Exception ex) { + LOG.error("could not create or start connection", ex); + } + connStarted.countDown(); + } + }; + t.start(); + createMaster(); + // slave will never start unless the master dies! + //createSlave(); - conn.get().stop(); - } + conn.get().stop(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverBackupLeakTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverBackupLeakTest.java index 24278be1d8..cf1d43d944 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverBackupLeakTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverBackupLeakTest.java @@ -35,93 +35,104 @@ import org.junit.Test; */ public class FailoverBackupLeakTest { - private static BrokerService s1, s2; + private static BrokerService s1, s2; - @BeforeClass - public static void setUp() throws Exception { - s1 = buildBroker("broker1"); - s2 = buildBroker("broker2"); + @BeforeClass + public static void setUp() throws Exception { + s1 = buildBroker("broker1"); + s2 = buildBroker("broker2"); - s1.start(); - s1.waitUntilStarted(); - s2.start(); - s2.waitUntilStarted(); - } + s1.start(); + s1.waitUntilStarted(); + s2.start(); + s2.waitUntilStarted(); + } - @AfterClass - public static void tearDown() throws Exception { - if (s2 != null) { - s2.stop(); - s2.waitUntilStopped(); - } - if (s1 != null) { - s1.stop(); - s1.waitUntilStopped(); - } - } + @AfterClass + public static void tearDown() throws Exception { + if (s2 != null) { + s2.stop(); + s2.waitUntilStopped(); + } + if (s1 != null) { + s1.stop(); + s1.waitUntilStopped(); + } + } - private static String getConnectString(BrokerService service) throws Exception { - return service.getTransportConnectors().get(0).getPublishableConnectString(); - } + private static String getConnectString(BrokerService service) throws Exception { + return service.getTransportConnectors().get(0).getPublishableConnectString(); + } - private static BrokerService buildBroker(String brokerName) throws Exception { - BrokerService service = new BrokerService(); - service.setBrokerName(brokerName); - service.setUseJmx(false); - service.setPersistent(false); - service.setUseShutdownHook(false); - service.addConnector("tcp://0.0.0.0:0?transport.closeAsync=false"); - return service; - } + private static BrokerService buildBroker(String brokerName) throws Exception { + BrokerService service = new BrokerService(); + service.setBrokerName(brokerName); + service.setUseJmx(false); + service.setPersistent(false); + service.setUseShutdownHook(false); + service.addConnector("tcp://0.0.0.0:0?transport.closeAsync=false"); + return service; + } - @Test - public void backupNoRandomize() throws Exception { - check("backup=true&randomize=false"); - } + @Test + public void backupNoRandomize() throws Exception { + check("backup=true&randomize=false"); + } - @Test - public void priorityBackupNoRandomize() throws Exception { - check("priorityBackup=true&randomize=false"); - } + @Test + public void priorityBackupNoRandomize() throws Exception { + check("priorityBackup=true&randomize=false"); + } - private void check(String connectionProperties) throws Exception { - String s1URL = getConnectString(s1), s2URL = getConnectString(s2); - String uri = "failover://(" + s1URL + "," + s2URL + ")?" + connectionProperties; - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(uri); - for (int i = 0; i < 10; i++) { - buildConnection(factory); - } + private void check(String connectionProperties) throws Exception { + String s1URL = getConnectString(s1), s2URL = getConnectString(s2); + String uri = "failover://(" + s1URL + "," + s2URL + ")?" + connectionProperties; + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(uri); + for (int i = 0; i < 10; i++) { + buildConnection(factory); + } - assertTrue(connectionProperties + " broker1 connection count not zero: was["+getConnectionCount(s1)+"]", Wait.waitFor(new Wait.Condition() { + assertTrue(connectionProperties + " broker1 connection count not zero: was[" + getConnectionCount(s1) + "]", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return getConnectionCount(s1) == 0; - } - })); + @Override + public boolean isSatisified() throws Exception { + return getConnectionCount(s1) == 0; + } + })); - assertTrue(connectionProperties + " broker2 connection count not zero: was["+getConnectionCount(s2)+"]", Wait.waitFor(new Wait.Condition() { + assertTrue(connectionProperties + " broker2 connection count not zero: was[" + getConnectionCount(s2) + "]", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return getConnectionCount(s2) == 0; - } - })); - } + @Override + public boolean isSatisified() throws Exception { + return getConnectionCount(s2) == 0; + } + })); + } - private int getConnectionCount(BrokerService service) { - return service.getTransportConnectors().get(0).getConnections().size(); - } + private int getConnectionCount(BrokerService service) { + return service.getTransportConnectors().get(0).getConnections().size(); + } - private void buildConnection(ConnectionFactory local) throws JMSException { - Connection conn = null; - Session sess = null; - try { - conn = local.createConnection(); - sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); - } finally { - try { if (sess != null) sess.close(); } catch (JMSException ignore) { } - try { if (conn != null) conn.close(); } catch (JMSException ignore) { } - } - } + private void buildConnection(ConnectionFactory local) throws JMSException { + Connection conn = null; + Session sess = null; + try { + conn = local.createConnection(); + sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); + } + finally { + try { + if (sess != null) + sess.close(); + } + catch (JMSException ignore) { + } + try { + if (conn != null) + conn.close(); + } + catch (JMSException ignore) { + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverClusterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverClusterTest.java index 417516f03d..113db64d00 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverClusterTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverClusterTest.java @@ -25,7 +25,9 @@ import javax.jms.Connection; import javax.jms.MessageConsumer; import javax.jms.Queue; import javax.jms.Session; + import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; @@ -34,130 +36,130 @@ import org.apache.activemq.network.NetworkConnector; public class FailoverClusterTest extends TestCase { - private static final int NUMBER = 10; - private static final String BROKER_BIND_ADDRESS = "tcp://0.0.0.0:0"; - private static final String BROKER_A_NAME = "BROKERA"; - private static final String BROKER_B_NAME = "BROKERB"; - private BrokerService brokerA; - private BrokerService brokerB; - private String clientUrl; + private static final int NUMBER = 10; + private static final String BROKER_BIND_ADDRESS = "tcp://0.0.0.0:0"; + private static final String BROKER_A_NAME = "BROKERA"; + private static final String BROKER_B_NAME = "BROKERB"; + private BrokerService brokerA; + private BrokerService brokerB; + private String clientUrl; - private final List connections = new ArrayList(); + private final List connections = new ArrayList(); - public void testClusterConnectedAfterClients() throws Exception { - createClients(); - if (brokerB == null) { - brokerB = createBrokerB(BROKER_BIND_ADDRESS); - } - Thread.sleep(3000); - Set set = new HashSet(); - for (ActiveMQConnection c : connections) { - set.add(c.getTransportChannel().getRemoteAddress()); - } - assertTrue(set.size() > 1); - } + public void testClusterConnectedAfterClients() throws Exception { + createClients(); + if (brokerB == null) { + brokerB = createBrokerB(BROKER_BIND_ADDRESS); + } + Thread.sleep(3000); + Set set = new HashSet(); + for (ActiveMQConnection c : connections) { + set.add(c.getTransportChannel().getRemoteAddress()); + } + assertTrue(set.size() > 1); + } - public void testClusterURIOptionsStrip() throws Exception { - createClients(); - if (brokerB == null) { - // add in server side only url param, should not be propagated - brokerB = createBrokerB(BROKER_BIND_ADDRESS + "?transport.closeAsync=false"); - } - Thread.sleep(3000); - Set set = new HashSet(); - for (ActiveMQConnection c : connections) { - set.add(c.getTransportChannel().getRemoteAddress()); - } - assertTrue(set.size() > 1); - } + public void testClusterURIOptionsStrip() throws Exception { + createClients(); + if (brokerB == null) { + // add in server side only url param, should not be propagated + brokerB = createBrokerB(BROKER_BIND_ADDRESS + "?transport.closeAsync=false"); + } + Thread.sleep(3000); + Set set = new HashSet(); + for (ActiveMQConnection c : connections) { + set.add(c.getTransportChannel().getRemoteAddress()); + } + assertTrue(set.size() > 1); + } - public void testClusterConnectedBeforeClients() throws Exception { + public void testClusterConnectedBeforeClients() throws Exception { - if (brokerB == null) { - brokerB = createBrokerB(BROKER_BIND_ADDRESS); - } - Thread.sleep(5000); - createClients(); - Thread.sleep(2000); - brokerA.stop(); - Thread.sleep(2000); + if (brokerB == null) { + brokerB = createBrokerB(BROKER_BIND_ADDRESS); + } + Thread.sleep(5000); + createClients(); + Thread.sleep(2000); + brokerA.stop(); + Thread.sleep(2000); - URI brokerBURI = new URI( brokerB.getTransportConnectors().get(0).getPublishableConnectString()); - for (ActiveMQConnection c : connections) { - String addr = c.getTransportChannel().getRemoteAddress(); - assertTrue(addr.indexOf("" + brokerBURI.getPort()) > 0); - } - } + URI brokerBURI = new URI(brokerB.getTransportConnectors().get(0).getPublishableConnectString()); + for (ActiveMQConnection c : connections) { + String addr = c.getTransportChannel().getRemoteAddress(); + assertTrue(addr.indexOf("" + brokerBURI.getPort()) > 0); + } + } - @Override - protected void setUp() throws Exception { - if (brokerA == null) { - brokerA = createBrokerA(BROKER_BIND_ADDRESS + "?transport.closeAsync=false"); - clientUrl = "failover://(" + brokerA.getTransportConnectors().get(0).getPublishableConnectString() + ")"; - } - } + @Override + protected void setUp() throws Exception { + if (brokerA == null) { + brokerA = createBrokerA(BROKER_BIND_ADDRESS + "?transport.closeAsync=false"); + clientUrl = "failover://(" + brokerA.getTransportConnectors().get(0).getPublishableConnectString() + ")"; + } + } - @Override - protected void tearDown() throws Exception { - for (Connection c : connections) { - c.close(); - } - if (brokerB != null) { - brokerB.stop(); - brokerB = null; - } - if (brokerA != null) { - brokerA.stop(); - brokerA = null; - } - } + @Override + protected void tearDown() throws Exception { + for (Connection c : connections) { + c.close(); + } + if (brokerB != null) { + brokerB.stop(); + brokerB = null; + } + if (brokerA != null) { + brokerA.stop(); + brokerA = null; + } + } - protected BrokerService createBrokerA(String uri) throws Exception { - BrokerService answer = new BrokerService(); - answer.setUseJmx(false); - configureConsumerBroker(answer, uri); - answer.start(); - return answer; - } + protected BrokerService createBrokerA(String uri) throws Exception { + BrokerService answer = new BrokerService(); + answer.setUseJmx(false); + configureConsumerBroker(answer, uri); + answer.start(); + return answer; + } - protected void configureConsumerBroker(BrokerService answer, String uri) throws Exception { - answer.setBrokerName(BROKER_A_NAME); - answer.setPersistent(false); - TransportConnector connector = answer.addConnector(uri); - connector.setRebalanceClusterClients(true); - connector.setUpdateClusterClients(true); - answer.setUseShutdownHook(false); - } + protected void configureConsumerBroker(BrokerService answer, String uri) throws Exception { + answer.setBrokerName(BROKER_A_NAME); + answer.setPersistent(false); + TransportConnector connector = answer.addConnector(uri); + connector.setRebalanceClusterClients(true); + connector.setUpdateClusterClients(true); + answer.setUseShutdownHook(false); + } - protected BrokerService createBrokerB(String uri) throws Exception { - BrokerService answer = new BrokerService(); - answer.setUseJmx(false); - configureNetwork(answer, uri); - answer.start(); - return answer; - } + protected BrokerService createBrokerB(String uri) throws Exception { + BrokerService answer = new BrokerService(); + answer.setUseJmx(false); + configureNetwork(answer, uri); + answer.start(); + return answer; + } - protected void configureNetwork(BrokerService answer, String uri) throws Exception { - answer.setBrokerName(BROKER_B_NAME); - answer.setPersistent(false); - NetworkConnector network = answer.addNetworkConnector("static://" + brokerA.getTransportConnectors().get(0).getPublishableConnectString()); - network.setDuplex(true); - TransportConnector connector = answer.addConnector(uri); - connector.setRebalanceClusterClients(true); - connector.setUpdateClusterClients(true); - answer.setUseShutdownHook(false); - } + protected void configureNetwork(BrokerService answer, String uri) throws Exception { + answer.setBrokerName(BROKER_B_NAME); + answer.setPersistent(false); + NetworkConnector network = answer.addNetworkConnector("static://" + brokerA.getTransportConnectors().get(0).getPublishableConnectString()); + network.setDuplex(true); + TransportConnector connector = answer.addConnector(uri); + connector.setRebalanceClusterClients(true); + connector.setUpdateClusterClients(true); + answer.setUseShutdownHook(false); + } - @SuppressWarnings("unused") - protected void createClients() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(clientUrl); - for (int i = 0; i < NUMBER; i++) { - ActiveMQConnection c = (ActiveMQConnection) factory.createConnection(); - c.start(); - Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = s.createQueue(getClass().getName()); - MessageConsumer consumer = s.createConsumer(queue); - connections.add(c); - } - } + @SuppressWarnings("unused") + protected void createClients() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(clientUrl); + for (int i = 0; i < NUMBER; i++) { + ActiveMQConnection c = (ActiveMQConnection) factory.createConnection(); + c.start(); + Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = s.createQueue(getClass().getName()); + MessageConsumer consumer = s.createConsumer(queue); + connections.add(c); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverClusterTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverClusterTestSupport.java index b277636851..2a125e106f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverClusterTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverClusterTestSupport.java @@ -40,163 +40,168 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FailoverClusterTestSupport extends TestCase { - protected final Logger logger = LoggerFactory.getLogger(getClass()); - private static final int NUMBER_OF_CLIENTS = 30; + protected final Logger logger = LoggerFactory.getLogger(getClass()); - private String clientUrl; + private static final int NUMBER_OF_CLIENTS = 30; - private final Map brokers = new HashMap(); - private final List connections = new ArrayList(); + private String clientUrl; - protected void assertClientsConnectedToTwoBrokers() { - Set set = new HashSet(); - for (ActiveMQConnection c : connections) { - if (c.getTransportChannel().getRemoteAddress() != null) { - set.add(c.getTransportChannel().getRemoteAddress()); + private final Map brokers = new HashMap(); + private final List connections = new ArrayList(); + + protected void assertClientsConnectedToTwoBrokers() { + Set set = new HashSet(); + for (ActiveMQConnection c : connections) { + if (c.getTransportChannel().getRemoteAddress() != null) { + set.add(c.getTransportChannel().getRemoteAddress()); + } + } + assertTrue("Only 2 connections should be found: " + set, set.size() == 2); + } + + protected void assertClientsConnectedToThreeBrokers() { + Set set = new HashSet(); + for (ActiveMQConnection c : connections) { + if (c.getTransportChannel().getRemoteAddress() != null) { + set.add(c.getTransportChannel().getRemoteAddress()); + } + } + assertTrue("Only 3 connections should be found: " + set, set.size() == 3); + } + + protected void assertClientsConnectionsEvenlyDistributed(double minimumPercentage) { + Map clientConnectionCounts = new HashMap(); + int total = 0; + for (ActiveMQConnection c : connections) { + String key = c.getTransportChannel().getRemoteAddress(); + if (key != null) { + total++; + if (clientConnectionCounts.containsKey(key)) { + double count = clientConnectionCounts.get(key); + count += 1.0; + clientConnectionCounts.put(key, count); } - } - assertTrue("Only 2 connections should be found: " + set, - set.size() == 2); - } - - protected void assertClientsConnectedToThreeBrokers() { - Set set = new HashSet(); - for (ActiveMQConnection c : connections) { - if (c.getTransportChannel().getRemoteAddress() != null) { - set.add(c.getTransportChannel().getRemoteAddress()); + else { + clientConnectionCounts.put(key, 1.0); } - } - assertTrue("Only 3 connections should be found: " + set, - set.size() == 3); - } + } + } + Set keys = clientConnectionCounts.keySet(); + for (String key : keys) { + double count = clientConnectionCounts.get(key); + double percentage = count / total; + logger.info(count + " of " + total + " connections for " + key + " = " + percentage); + assertTrue("Connections distribution expected to be >= than " + minimumPercentage + ". Actuall distribution was " + percentage + " for connection " + key, percentage >= minimumPercentage); + } + } - protected void assertClientsConnectionsEvenlyDistributed(double minimumPercentage) { - Map clientConnectionCounts = new HashMap(); - int total = 0; - for (ActiveMQConnection c : connections) { - String key = c.getTransportChannel().getRemoteAddress(); - if (key != null) { - total++; - if (clientConnectionCounts.containsKey(key)) { - double count = clientConnectionCounts.get(key); - count += 1.0; - clientConnectionCounts.put(key, count); - } else { - clientConnectionCounts.put(key, 1.0); - } - } - } - Set keys = clientConnectionCounts.keySet(); - for(String key: keys){ - double count = clientConnectionCounts.get(key); - double percentage = count / total; - logger.info(count + " of " + total + " connections for " + key + " = " + percentage); - assertTrue("Connections distribution expected to be >= than " + minimumPercentage - + ". Actuall distribution was " + percentage + " for connection " + key, - percentage >= minimumPercentage); - } - } + protected void assertAllConnectedTo(String url) throws Exception { + for (ActiveMQConnection c : connections) { + assertEquals(url, c.getTransportChannel().getRemoteAddress()); + } + } - protected void assertAllConnectedTo(String url) throws Exception { - for (ActiveMQConnection c : connections) { - assertEquals(url, c.getTransportChannel().getRemoteAddress()); - } - } + protected void addBroker(String name, BrokerService brokerService) { + brokers.put(name, brokerService); + } - protected void addBroker(String name, BrokerService brokerService) { - brokers.put(name, brokerService); - } + protected BrokerService getBroker(String name) { + return brokers.get(name); + } - protected BrokerService getBroker(String name) { - return brokers.get(name); - } + protected void stopBroker(String name) throws Exception { + BrokerService broker = brokers.remove(name); + broker.stop(); + broker.waitUntilStopped(); + } - protected void stopBroker(String name) throws Exception { - BrokerService broker = brokers.remove(name); - broker.stop(); - broker.waitUntilStopped(); - } + protected BrokerService removeBroker(String name) { + return brokers.remove(name); + } - protected BrokerService removeBroker(String name) { - return brokers.remove(name); - } + protected void destroyBrokerCluster() throws JMSException, Exception { + for (BrokerService b : brokers.values()) { + try { + b.stop(); + b.waitUntilStopped(); + } + catch (Exception e) { + // Keep on going, we want to try and stop them all. + logger.info("Error while stopping broker[" + b.getBrokerName() + "] continuing..."); + } + } + brokers.clear(); + } - protected void destroyBrokerCluster() throws JMSException, Exception { - for (BrokerService b : brokers.values()) { - try { - b.stop(); - b.waitUntilStopped(); - } catch (Exception e) { - // Keep on going, we want to try and stop them all. - logger.info("Error while stopping broker["+ b.getBrokerName() +"] continuing..."); - } - } - brokers.clear(); - } + protected void shutdownClients() throws JMSException { + for (Connection c : connections) { + c.close(); + } + } - protected void shutdownClients() throws JMSException { - for (Connection c : connections) { - c.close(); - } - } + protected BrokerService createBroker(String brokerName) throws Exception { + BrokerService answer = new BrokerService(); + answer.setPersistent(false); + answer.setUseJmx(false); + answer.setBrokerName(brokerName); + answer.setUseShutdownHook(false); + return answer; + } - protected BrokerService createBroker(String brokerName) throws Exception { - BrokerService answer = new BrokerService(); - answer.setPersistent(false); - answer.setUseJmx(false); - answer.setBrokerName(brokerName); - answer.setUseShutdownHook(false); - return answer; - } + protected void addTransportConnector(BrokerService brokerService, + String connectorName, + String uri, + boolean clustered) throws Exception { + TransportConnector connector = brokerService.addConnector(uri); + connector.setName(connectorName); + if (clustered) { + connector.setRebalanceClusterClients(true); + connector.setUpdateClusterClients(true); + connector.setUpdateClusterClientsOnRemove(true); + } + else { + connector.setRebalanceClusterClients(false); + connector.setUpdateClusterClients(false); + connector.setUpdateClusterClientsOnRemove(false); + } + } - protected void addTransportConnector(BrokerService brokerService, - String connectorName, String uri, boolean clustered) throws Exception { - TransportConnector connector = brokerService.addConnector(uri); - connector.setName(connectorName); - if (clustered) { - connector.setRebalanceClusterClients(true); - connector.setUpdateClusterClients(true); - connector.setUpdateClusterClientsOnRemove(true); - } else { - connector.setRebalanceClusterClients(false); - connector.setUpdateClusterClients(false); - connector.setUpdateClusterClientsOnRemove(false); - } - } + protected void addNetworkBridge(BrokerService answer, + String bridgeName, + String uri, + boolean duplex, + String destinationFilter) throws Exception { + NetworkConnector network = answer.addNetworkConnector(uri); + network.setName(bridgeName); + network.setDuplex(duplex); + if (destinationFilter != null && !destinationFilter.equals("")) { + network.setDestinationFilter(bridgeName); + } + } - protected void addNetworkBridge(BrokerService answer, String bridgeName, - String uri, boolean duplex, String destinationFilter) throws Exception { - NetworkConnector network = answer.addNetworkConnector(uri); - network.setName(bridgeName); - network.setDuplex(duplex); - if (destinationFilter != null && !destinationFilter.equals("")) { - network.setDestinationFilter(bridgeName); - } - } + protected void createClients() throws Exception { + createClients(NUMBER_OF_CLIENTS); + } - protected void createClients() throws Exception { - createClients(NUMBER_OF_CLIENTS); - } + @SuppressWarnings("unused") + protected void createClients(int numOfClients) throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(clientUrl); + for (int i = 0; i < numOfClients; i++) { + ActiveMQConnection c = (ActiveMQConnection) factory.createConnection(); + c.start(); + Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = s.createQueue(getClass().getName()); + MessageConsumer consumer = s.createConsumer(queue); + connections.add(c); + } + } - @SuppressWarnings("unused") - protected void createClients(int numOfClients) throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(clientUrl); - for (int i = 0; i < numOfClients; i++) { - ActiveMQConnection c = (ActiveMQConnection) factory.createConnection(); - c.start(); - Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = s.createQueue(getClass().getName()); - MessageConsumer consumer = s.createConsumer(queue); - connections.add(c); - } - } + public String getClientUrl() { + return clientUrl; + } - public String getClientUrl() { - return clientUrl; - } - - public void setClientUrl(String clientUrl) { - this.clientUrl = clientUrl; - } + public void setClientUrl(String clientUrl) { + this.clientUrl = clientUrl; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverComplexClusterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverComplexClusterTest.java index fab2da50cb..6fb1c1b42d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverComplexClusterTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverComplexClusterTest.java @@ -20,7 +20,6 @@ import org.apache.activemq.broker.TransportConnector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - /** * Complex cluster test that will exercise the dynamic failover capabilities of * a network of brokers. Using a networking of 3 brokers where the 3rd broker is @@ -30,351 +29,369 @@ import org.slf4j.LoggerFactory; */ public class FailoverComplexClusterTest extends FailoverClusterTestSupport { - private static final String BROKER_A_CLIENT_TC_ADDRESS = "tcp://127.0.0.1:61616"; - private static final String BROKER_B_CLIENT_TC_ADDRESS = "tcp://127.0.0.1:61617"; - private static final String BROKER_C_CLIENT_TC_ADDRESS = "tcp://127.0.0.1:61618"; - private static final String BROKER_A_NOB_TC_ADDRESS = "tcp://127.0.0.1:61626"; - private static final String BROKER_B_NOB_TC_ADDRESS = "tcp://127.0.0.1:61627"; - private static final String BROKER_C_NOB_TC_ADDRESS = "tcp://127.0.0.1:61628"; - private static final String BROKER_A_NAME = "BROKERA"; - private static final String BROKER_B_NAME = "BROKERB"; - private static final String BROKER_C_NAME = "BROKERC"; - - /** - * Basic dynamic failover 3 broker test - * - * @throws Exception - */ - public void testThreeBrokerClusterSingleConnectorBasic() throws Exception { - - initSingleTcBroker("", null, null); - - Thread.sleep(2000); - - setClientUrl("failover://(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + ")"); - createClients(); - Thread.sleep(2000); - - runTests(false, null, null, null); - } - - /** - * Tests a 3 broker configuration to ensure that the backup is random and - * supported in a cluster. useExponentialBackOff is set to false and - * maxReconnectAttempts is set to 1 to move through the list quickly for - * this test. - * - * @throws Exception - */ - public void testThreeBrokerClusterSingleConnectorBackupFailoverConfig() throws Exception { - - initSingleTcBroker("", null, null); - - Thread.sleep(2000); - - setClientUrl("failover://(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + ")?backup=true&backupPoolSize=2&useExponentialBackOff=false&initialReconnectDelay=500"); - createClients(); - Thread.sleep(2000); - - runTests(false, null, null, null); - } - - /** - * Tests a 3 broker cluster that passes in connection params on the - * transport connector. Prior versions of AMQ passed the TC connection - * params to the client and this should not happen. The chosen param is not - * compatible with the client and will throw an error if used. - * - * @throws Exception - */ - public void testThreeBrokerClusterSingleConnectorWithParams() throws Exception { - - initSingleTcBroker("?transport.closeAsync=false", null, null); - - Thread.sleep(2000); - setClientUrl("failover://(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + ")"); - createClients(); - Thread.sleep(2000); - - runTests(false, null, null, null); - } - - /** - * Tests a 3 broker cluster using a cluster filter of * - * - * @throws Exception - */ - public void testThreeBrokerClusterWithClusterFilter() throws Exception { - - initSingleTcBroker("?transport.closeAsync=false", null, null); - - Thread.sleep(2000); - setClientUrl("failover://(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + ")"); - createClients(); - - runTests(false, null, "*", null); - } - - /** - * Test to verify that a broker with multiple transport connections only the - * one marked to update clients is propagate - * - * @throws Exception - */ - public void testThreeBrokerClusterMultipleConnectorBasic() throws Exception { - - initMultiTcCluster("", null); - - Thread.sleep(2000); - - setClientUrl("failover://(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + ")"); - createClients(); - Thread.sleep(2000); - - runTests(true, null, null, null); - } - - /** - * Test to verify the reintroduction of the A Broker - * - * @throws Exception - */ - public void testOriginalBrokerRestart() throws Exception { - initSingleTcBroker("", null, null); - - Thread.sleep(2000); - - setClientUrl("failover://(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + ")"); - createClients(); - Thread.sleep(2000); - - assertClientsConnectedToThreeBrokers(); - - getBroker(BROKER_A_NAME).stop(); - getBroker(BROKER_A_NAME).waitUntilStopped(); - removeBroker(BROKER_A_NAME); - - Thread.sleep(5000); - - assertClientsConnectedToTwoBrokers(); - - createBrokerA(false, null, null, null); - getBroker(BROKER_A_NAME).waitUntilStarted(); - Thread.sleep(5000); - - assertClientsConnectedToThreeBrokers(); - } - - /** - * Test to ensure clients are evenly to all available brokers in the - * network. - * - * @throws Exception - */ - public void testThreeBrokerClusterClientDistributions() throws Exception { - - initSingleTcBroker("", null, null); - - Thread.sleep(2000); - setClientUrl("failover://(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false&initialReconnectDelay=500"); - createClients(100); - Thread.sleep(5000); - - runClientDistributionTests(false, null, null, null); - } - - /** - * Test to verify that clients are distributed with no less than 20% of the - * clients on any one broker. - * - * @throws Exception - */ - public void testThreeBrokerClusterDestinationFilter() throws Exception { - - initSingleTcBroker("", null, null); - - Thread.sleep(2000); - setClientUrl("failover://(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + ")"); - createClients(); - - runTests(false, null, null, "Queue.TEST.FOO.>"); - } - - public void testFailOverWithUpdateClientsOnRemove() throws Exception{ - // Broker A - addBroker(BROKER_A_NAME, createBroker(BROKER_A_NAME)); - TransportConnector connectorA = getBroker(BROKER_A_NAME).addConnector(BROKER_A_CLIENT_TC_ADDRESS); - connectorA.setName("openwire"); - connectorA.setRebalanceClusterClients(true); - connectorA.setUpdateClusterClients(true); - connectorA.setUpdateClusterClientsOnRemove(true); //If set to false the test succeeds. - addNetworkBridge(getBroker(BROKER_A_NAME), "A_2_B_Bridge", "static://(" + BROKER_B_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); - getBroker(BROKER_A_NAME).start(); - - // Broker B - addBroker(BROKER_B_NAME, createBroker(BROKER_B_NAME)); - TransportConnector connectorB = getBroker(BROKER_B_NAME).addConnector(BROKER_B_CLIENT_TC_ADDRESS); - connectorB.setName("openwire"); - connectorB.setRebalanceClusterClients(true); - connectorB.setUpdateClusterClients(true); - connectorB.setUpdateClusterClientsOnRemove(true); //If set to false the test succeeds. - addNetworkBridge(getBroker(BROKER_B_NAME), "B_2_A_Bridge", "static://(" + BROKER_A_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); - getBroker(BROKER_B_NAME).start(); - - getBroker(BROKER_B_NAME).waitUntilStarted(); - Thread.sleep(1000); - - // create client connecting only to A. It should receive broker B address whet it connects to A. - setClientUrl("failover:(" + BROKER_A_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=true"); - createClients(1); - Thread.sleep(5000); - - // We stop broker A. - logger.info("Stopping broker A whose address is: {}", BROKER_A_CLIENT_TC_ADDRESS); - getBroker(BROKER_A_NAME).stop(); - getBroker(BROKER_A_NAME).waitUntilStopped(); - Thread.sleep(5000); - - // Client should failover to B. - assertAllConnectedTo(BROKER_B_CLIENT_TC_ADDRESS); - } - - /** - * Runs a 3 Broker dynamic failover test:
    - *
      - *
    • asserts clients are distributed across all 3 brokers
    • - *
    • asserts clients are distributed across 2 brokers after removing the 3rd
    • - *
    • asserts clients are distributed across all 3 brokers after - * reintroducing the 3rd broker
    • - *
    - * - * @param multi - * @param tcParams - * @param clusterFilter - * @param destinationFilter - * @throws Exception - * @throws InterruptedException - */ - private void runTests(boolean multi, String tcParams, String clusterFilter, String destinationFilter) throws Exception, InterruptedException { - assertClientsConnectedToThreeBrokers(); - - getBroker(BROKER_C_NAME).stop(); - getBroker(BROKER_C_NAME).waitUntilStopped(); - removeBroker(BROKER_C_NAME); - - Thread.sleep(5000); - - assertClientsConnectedToTwoBrokers(); - - createBrokerC(multi, tcParams, clusterFilter, destinationFilter); - getBroker(BROKER_C_NAME).waitUntilStarted(); - Thread.sleep(5000); - - assertClientsConnectedToThreeBrokers(); - } - - /** - * @param multi - * @param tcParams - * @param clusterFilter - * @param destinationFilter - * @throws Exception - * @throws InterruptedException - */ - private void runClientDistributionTests(boolean multi, String tcParams, String clusterFilter, String destinationFilter) throws Exception, InterruptedException { - assertClientsConnectedToThreeBrokers(); - assertClientsConnectionsEvenlyDistributed(.25); - - getBroker(BROKER_C_NAME).stop(); - getBroker(BROKER_C_NAME).waitUntilStopped(); - removeBroker(BROKER_C_NAME); - - Thread.sleep(5000); - - assertClientsConnectedToTwoBrokers(); - assertClientsConnectionsEvenlyDistributed(.35); - - createBrokerC(multi, tcParams, clusterFilter, destinationFilter); - getBroker(BROKER_C_NAME).waitUntilStarted(); - Thread.sleep(5000); - - assertClientsConnectedToThreeBrokers(); - assertClientsConnectionsEvenlyDistributed(.20); - } - - @Override - protected void setUp() throws Exception { - } - - @Override - protected void tearDown() throws Exception { - shutdownClients(); - Thread.sleep(2000); - destroyBrokerCluster(); - } - - private void initSingleTcBroker(String params, String clusterFilter, String destinationFilter) throws Exception { - createBrokerA(false, params, clusterFilter, null); - createBrokerB(false, params, clusterFilter, null); - createBrokerC(false, params, clusterFilter, null); - getBroker(BROKER_C_NAME).waitUntilStarted(); - } - - private void initMultiTcCluster(String params, String clusterFilter) throws Exception { - createBrokerA(true, params, clusterFilter, null); - createBrokerB(true, params, clusterFilter, null); - createBrokerC(true, params, clusterFilter, null); - getBroker(BROKER_C_NAME).waitUntilStarted(); - } - - private void createBrokerA(boolean multi, String params, String clusterFilter, String destinationFilter) throws Exception { - final String tcParams = (params == null)?"":params; - if (getBroker(BROKER_A_NAME) == null) { - addBroker(BROKER_A_NAME, createBroker(BROKER_A_NAME)); - addTransportConnector(getBroker(BROKER_A_NAME), "openwire", BROKER_A_CLIENT_TC_ADDRESS + tcParams, true); - if (multi) { - addTransportConnector(getBroker(BROKER_A_NAME), "network", BROKER_A_NOB_TC_ADDRESS + tcParams, false); - addNetworkBridge(getBroker(BROKER_A_NAME), "A_2_B_Bridge", "static://(" + BROKER_B_NOB_TC_ADDRESS + ")?useExponentialBackOff=false", false, clusterFilter); - addNetworkBridge(getBroker(BROKER_A_NAME), "A_2_C_Bridge", "static://(" + BROKER_C_NOB_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); - } else { - addNetworkBridge(getBroker(BROKER_A_NAME), "A_2_B_Bridge", "static://(" + BROKER_B_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, clusterFilter); - addNetworkBridge(getBroker(BROKER_A_NAME), "A_2_C_Bridge", "static://(" + BROKER_C_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); - } - getBroker(BROKER_A_NAME).start(); - } - } - - private void createBrokerB(boolean multi, String params, String clusterFilter, String destinationFilter) throws Exception { - final String tcParams = (params == null)?"":params; - if (getBroker(BROKER_B_NAME) == null) { - addBroker(BROKER_B_NAME, createBroker(BROKER_B_NAME)); - addTransportConnector(getBroker(BROKER_B_NAME), "openwire", BROKER_B_CLIENT_TC_ADDRESS + tcParams, true); - if (multi) { - addTransportConnector(getBroker(BROKER_B_NAME), "network", BROKER_B_NOB_TC_ADDRESS + tcParams, false); - addNetworkBridge(getBroker(BROKER_B_NAME), "B_2_A_Bridge", "static://(" + BROKER_A_NOB_TC_ADDRESS + ")?useExponentialBackOff=false", false, clusterFilter); - addNetworkBridge(getBroker(BROKER_B_NAME), "B_2_C_Bridge", "static://(" + BROKER_C_NOB_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); - } else { - addNetworkBridge(getBroker(BROKER_B_NAME), "B_2_A_Bridge", "static://(" + BROKER_A_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, clusterFilter); - addNetworkBridge(getBroker(BROKER_B_NAME), "B_2_C_Bridge", "static://(" + BROKER_C_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); - } - getBroker(BROKER_B_NAME).start(); - } - } - - private void createBrokerC(boolean multi, String params, String clusterFilter, String destinationFilter) throws Exception { - final String tcParams = (params == null)?"":params; - if (getBroker(BROKER_C_NAME) == null) { - addBroker(BROKER_C_NAME, createBroker(BROKER_C_NAME)); - addTransportConnector(getBroker(BROKER_C_NAME), "openwire", BROKER_C_CLIENT_TC_ADDRESS + tcParams, true); - if (multi) { - addTransportConnector(getBroker(BROKER_C_NAME), "network", BROKER_C_NOB_TC_ADDRESS + tcParams, false); - addNetworkBridge(getBroker(BROKER_C_NAME), "C_2_A_Bridge", "static://(" + BROKER_A_NOB_TC_ADDRESS + ")?useExponentialBackOff=false", false, clusterFilter); - addNetworkBridge(getBroker(BROKER_C_NAME), "C_2_B_Bridge", "static://(" + BROKER_B_NOB_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); - } else { - addNetworkBridge(getBroker(BROKER_C_NAME), "C_2_A_Bridge", "static://(" + BROKER_A_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, clusterFilter); - addNetworkBridge(getBroker(BROKER_C_NAME), "C_2_B_Bridge", "static://(" + BROKER_B_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); - } - getBroker(BROKER_C_NAME).start(); - } - } + private static final String BROKER_A_CLIENT_TC_ADDRESS = "tcp://127.0.0.1:61616"; + private static final String BROKER_B_CLIENT_TC_ADDRESS = "tcp://127.0.0.1:61617"; + private static final String BROKER_C_CLIENT_TC_ADDRESS = "tcp://127.0.0.1:61618"; + private static final String BROKER_A_NOB_TC_ADDRESS = "tcp://127.0.0.1:61626"; + private static final String BROKER_B_NOB_TC_ADDRESS = "tcp://127.0.0.1:61627"; + private static final String BROKER_C_NOB_TC_ADDRESS = "tcp://127.0.0.1:61628"; + private static final String BROKER_A_NAME = "BROKERA"; + private static final String BROKER_B_NAME = "BROKERB"; + private static final String BROKER_C_NAME = "BROKERC"; + + /** + * Basic dynamic failover 3 broker test + * + * @throws Exception + */ + public void testThreeBrokerClusterSingleConnectorBasic() throws Exception { + + initSingleTcBroker("", null, null); + + Thread.sleep(2000); + + setClientUrl("failover://(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + ")"); + createClients(); + Thread.sleep(2000); + + runTests(false, null, null, null); + } + + /** + * Tests a 3 broker configuration to ensure that the backup is random and + * supported in a cluster. useExponentialBackOff is set to false and + * maxReconnectAttempts is set to 1 to move through the list quickly for + * this test. + * + * @throws Exception + */ + public void testThreeBrokerClusterSingleConnectorBackupFailoverConfig() throws Exception { + + initSingleTcBroker("", null, null); + + Thread.sleep(2000); + + setClientUrl("failover://(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + ")?backup=true&backupPoolSize=2&useExponentialBackOff=false&initialReconnectDelay=500"); + createClients(); + Thread.sleep(2000); + + runTests(false, null, null, null); + } + + /** + * Tests a 3 broker cluster that passes in connection params on the + * transport connector. Prior versions of AMQ passed the TC connection + * params to the client and this should not happen. The chosen param is not + * compatible with the client and will throw an error if used. + * + * @throws Exception + */ + public void testThreeBrokerClusterSingleConnectorWithParams() throws Exception { + + initSingleTcBroker("?transport.closeAsync=false", null, null); + + Thread.sleep(2000); + setClientUrl("failover://(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + ")"); + createClients(); + Thread.sleep(2000); + + runTests(false, null, null, null); + } + + /** + * Tests a 3 broker cluster using a cluster filter of * + * + * @throws Exception + */ + public void testThreeBrokerClusterWithClusterFilter() throws Exception { + + initSingleTcBroker("?transport.closeAsync=false", null, null); + + Thread.sleep(2000); + setClientUrl("failover://(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + ")"); + createClients(); + + runTests(false, null, "*", null); + } + + /** + * Test to verify that a broker with multiple transport connections only the + * one marked to update clients is propagate + * + * @throws Exception + */ + public void testThreeBrokerClusterMultipleConnectorBasic() throws Exception { + + initMultiTcCluster("", null); + + Thread.sleep(2000); + + setClientUrl("failover://(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + ")"); + createClients(); + Thread.sleep(2000); + + runTests(true, null, null, null); + } + + /** + * Test to verify the reintroduction of the A Broker + * + * @throws Exception + */ + public void testOriginalBrokerRestart() throws Exception { + initSingleTcBroker("", null, null); + + Thread.sleep(2000); + + setClientUrl("failover://(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + ")"); + createClients(); + Thread.sleep(2000); + + assertClientsConnectedToThreeBrokers(); + + getBroker(BROKER_A_NAME).stop(); + getBroker(BROKER_A_NAME).waitUntilStopped(); + removeBroker(BROKER_A_NAME); + + Thread.sleep(5000); + + assertClientsConnectedToTwoBrokers(); + + createBrokerA(false, null, null, null); + getBroker(BROKER_A_NAME).waitUntilStarted(); + Thread.sleep(5000); + + assertClientsConnectedToThreeBrokers(); + } + + /** + * Test to ensure clients are evenly to all available brokers in the + * network. + * + * @throws Exception + */ + public void testThreeBrokerClusterClientDistributions() throws Exception { + + initSingleTcBroker("", null, null); + + Thread.sleep(2000); + setClientUrl("failover://(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false&initialReconnectDelay=500"); + createClients(100); + Thread.sleep(5000); + + runClientDistributionTests(false, null, null, null); + } + + /** + * Test to verify that clients are distributed with no less than 20% of the + * clients on any one broker. + * + * @throws Exception + */ + public void testThreeBrokerClusterDestinationFilter() throws Exception { + + initSingleTcBroker("", null, null); + + Thread.sleep(2000); + setClientUrl("failover://(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + ")"); + createClients(); + + runTests(false, null, null, "Queue.TEST.FOO.>"); + } + + public void testFailOverWithUpdateClientsOnRemove() throws Exception { + // Broker A + addBroker(BROKER_A_NAME, createBroker(BROKER_A_NAME)); + TransportConnector connectorA = getBroker(BROKER_A_NAME).addConnector(BROKER_A_CLIENT_TC_ADDRESS); + connectorA.setName("openwire"); + connectorA.setRebalanceClusterClients(true); + connectorA.setUpdateClusterClients(true); + connectorA.setUpdateClusterClientsOnRemove(true); //If set to false the test succeeds. + addNetworkBridge(getBroker(BROKER_A_NAME), "A_2_B_Bridge", "static://(" + BROKER_B_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); + getBroker(BROKER_A_NAME).start(); + + // Broker B + addBroker(BROKER_B_NAME, createBroker(BROKER_B_NAME)); + TransportConnector connectorB = getBroker(BROKER_B_NAME).addConnector(BROKER_B_CLIENT_TC_ADDRESS); + connectorB.setName("openwire"); + connectorB.setRebalanceClusterClients(true); + connectorB.setUpdateClusterClients(true); + connectorB.setUpdateClusterClientsOnRemove(true); //If set to false the test succeeds. + addNetworkBridge(getBroker(BROKER_B_NAME), "B_2_A_Bridge", "static://(" + BROKER_A_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); + getBroker(BROKER_B_NAME).start(); + + getBroker(BROKER_B_NAME).waitUntilStarted(); + Thread.sleep(1000); + + // create client connecting only to A. It should receive broker B address whet it connects to A. + setClientUrl("failover:(" + BROKER_A_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=true"); + createClients(1); + Thread.sleep(5000); + + // We stop broker A. + logger.info("Stopping broker A whose address is: {}", BROKER_A_CLIENT_TC_ADDRESS); + getBroker(BROKER_A_NAME).stop(); + getBroker(BROKER_A_NAME).waitUntilStopped(); + Thread.sleep(5000); + + // Client should failover to B. + assertAllConnectedTo(BROKER_B_CLIENT_TC_ADDRESS); + } + + /** + * Runs a 3 Broker dynamic failover test:
    + *
      + *
    • asserts clients are distributed across all 3 brokers
    • + *
    • asserts clients are distributed across 2 brokers after removing the 3rd
    • + *
    • asserts clients are distributed across all 3 brokers after + * reintroducing the 3rd broker
    • + *
    + * + * @param multi + * @param tcParams + * @param clusterFilter + * @param destinationFilter + * @throws Exception + * @throws InterruptedException + */ + private void runTests(boolean multi, + String tcParams, + String clusterFilter, + String destinationFilter) throws Exception, InterruptedException { + assertClientsConnectedToThreeBrokers(); + + getBroker(BROKER_C_NAME).stop(); + getBroker(BROKER_C_NAME).waitUntilStopped(); + removeBroker(BROKER_C_NAME); + + Thread.sleep(5000); + + assertClientsConnectedToTwoBrokers(); + + createBrokerC(multi, tcParams, clusterFilter, destinationFilter); + getBroker(BROKER_C_NAME).waitUntilStarted(); + Thread.sleep(5000); + + assertClientsConnectedToThreeBrokers(); + } + + /** + * @param multi + * @param tcParams + * @param clusterFilter + * @param destinationFilter + * @throws Exception + * @throws InterruptedException + */ + private void runClientDistributionTests(boolean multi, + String tcParams, + String clusterFilter, + String destinationFilter) throws Exception, InterruptedException { + assertClientsConnectedToThreeBrokers(); + assertClientsConnectionsEvenlyDistributed(.25); + + getBroker(BROKER_C_NAME).stop(); + getBroker(BROKER_C_NAME).waitUntilStopped(); + removeBroker(BROKER_C_NAME); + + Thread.sleep(5000); + + assertClientsConnectedToTwoBrokers(); + assertClientsConnectionsEvenlyDistributed(.35); + + createBrokerC(multi, tcParams, clusterFilter, destinationFilter); + getBroker(BROKER_C_NAME).waitUntilStarted(); + Thread.sleep(5000); + + assertClientsConnectedToThreeBrokers(); + assertClientsConnectionsEvenlyDistributed(.20); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + shutdownClients(); + Thread.sleep(2000); + destroyBrokerCluster(); + } + + private void initSingleTcBroker(String params, String clusterFilter, String destinationFilter) throws Exception { + createBrokerA(false, params, clusterFilter, null); + createBrokerB(false, params, clusterFilter, null); + createBrokerC(false, params, clusterFilter, null); + getBroker(BROKER_C_NAME).waitUntilStarted(); + } + + private void initMultiTcCluster(String params, String clusterFilter) throws Exception { + createBrokerA(true, params, clusterFilter, null); + createBrokerB(true, params, clusterFilter, null); + createBrokerC(true, params, clusterFilter, null); + getBroker(BROKER_C_NAME).waitUntilStarted(); + } + + private void createBrokerA(boolean multi, + String params, + String clusterFilter, + String destinationFilter) throws Exception { + final String tcParams = (params == null) ? "" : params; + if (getBroker(BROKER_A_NAME) == null) { + addBroker(BROKER_A_NAME, createBroker(BROKER_A_NAME)); + addTransportConnector(getBroker(BROKER_A_NAME), "openwire", BROKER_A_CLIENT_TC_ADDRESS + tcParams, true); + if (multi) { + addTransportConnector(getBroker(BROKER_A_NAME), "network", BROKER_A_NOB_TC_ADDRESS + tcParams, false); + addNetworkBridge(getBroker(BROKER_A_NAME), "A_2_B_Bridge", "static://(" + BROKER_B_NOB_TC_ADDRESS + ")?useExponentialBackOff=false", false, clusterFilter); + addNetworkBridge(getBroker(BROKER_A_NAME), "A_2_C_Bridge", "static://(" + BROKER_C_NOB_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); + } + else { + addNetworkBridge(getBroker(BROKER_A_NAME), "A_2_B_Bridge", "static://(" + BROKER_B_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, clusterFilter); + addNetworkBridge(getBroker(BROKER_A_NAME), "A_2_C_Bridge", "static://(" + BROKER_C_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); + } + getBroker(BROKER_A_NAME).start(); + } + } + + private void createBrokerB(boolean multi, + String params, + String clusterFilter, + String destinationFilter) throws Exception { + final String tcParams = (params == null) ? "" : params; + if (getBroker(BROKER_B_NAME) == null) { + addBroker(BROKER_B_NAME, createBroker(BROKER_B_NAME)); + addTransportConnector(getBroker(BROKER_B_NAME), "openwire", BROKER_B_CLIENT_TC_ADDRESS + tcParams, true); + if (multi) { + addTransportConnector(getBroker(BROKER_B_NAME), "network", BROKER_B_NOB_TC_ADDRESS + tcParams, false); + addNetworkBridge(getBroker(BROKER_B_NAME), "B_2_A_Bridge", "static://(" + BROKER_A_NOB_TC_ADDRESS + ")?useExponentialBackOff=false", false, clusterFilter); + addNetworkBridge(getBroker(BROKER_B_NAME), "B_2_C_Bridge", "static://(" + BROKER_C_NOB_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); + } + else { + addNetworkBridge(getBroker(BROKER_B_NAME), "B_2_A_Bridge", "static://(" + BROKER_A_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, clusterFilter); + addNetworkBridge(getBroker(BROKER_B_NAME), "B_2_C_Bridge", "static://(" + BROKER_C_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); + } + getBroker(BROKER_B_NAME).start(); + } + } + + private void createBrokerC(boolean multi, + String params, + String clusterFilter, + String destinationFilter) throws Exception { + final String tcParams = (params == null) ? "" : params; + if (getBroker(BROKER_C_NAME) == null) { + addBroker(BROKER_C_NAME, createBroker(BROKER_C_NAME)); + addTransportConnector(getBroker(BROKER_C_NAME), "openwire", BROKER_C_CLIENT_TC_ADDRESS + tcParams, true); + if (multi) { + addTransportConnector(getBroker(BROKER_C_NAME), "network", BROKER_C_NOB_TC_ADDRESS + tcParams, false); + addNetworkBridge(getBroker(BROKER_C_NAME), "C_2_A_Bridge", "static://(" + BROKER_A_NOB_TC_ADDRESS + ")?useExponentialBackOff=false", false, clusterFilter); + addNetworkBridge(getBroker(BROKER_C_NAME), "C_2_B_Bridge", "static://(" + BROKER_B_NOB_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); + } + else { + addNetworkBridge(getBroker(BROKER_C_NAME), "C_2_A_Bridge", "static://(" + BROKER_A_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, clusterFilter); + addNetworkBridge(getBroker(BROKER_C_NAME), "C_2_B_Bridge", "static://(" + BROKER_B_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); + } + getBroker(BROKER_C_NAME).start(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverConsumerOutstandingCommitTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverConsumerOutstandingCommitTest.java index c5d39d9bdf..5d2d0f9353 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverConsumerOutstandingCommitTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverConsumerOutstandingCommitTest.java @@ -53,320 +53,324 @@ import org.junit.Test; public class FailoverConsumerOutstandingCommitTest { - private static final Logger LOG = LoggerFactory.getLogger(FailoverConsumerOutstandingCommitTest.class); - private static final String QUEUE_NAME = "FailoverWithOutstandingCommit"; - private static final String MESSAGE_TEXT = "Test message "; - private static final String TRANSPORT_URI = "tcp://localhost:0"; - private String url; - final int prefetch = 10; - BrokerService broker; + private static final Logger LOG = LoggerFactory.getLogger(FailoverConsumerOutstandingCommitTest.class); + private static final String QUEUE_NAME = "FailoverWithOutstandingCommit"; + private static final String MESSAGE_TEXT = "Test message "; + private static final String TRANSPORT_URI = "tcp://localhost:0"; + private String url; + final int prefetch = 10; + BrokerService broker; - @After - public void stopBroker() throws Exception { - if (broker != null) { - broker.stop(); - } - } + @After + public void stopBroker() throws Exception { + if (broker != null) { + broker.stop(); + } + } - public void startBroker(boolean deleteAllMessagesOnStartup) throws Exception { - broker = createBroker(deleteAllMessagesOnStartup); - broker.start(); - } + public void startBroker(boolean deleteAllMessagesOnStartup) throws Exception { + broker = createBroker(deleteAllMessagesOnStartup); + broker.start(); + } - public BrokerService createBroker(boolean deleteAllMessagesOnStartup) throws Exception { - return createBroker(deleteAllMessagesOnStartup, TRANSPORT_URI); - } + public BrokerService createBroker(boolean deleteAllMessagesOnStartup) throws Exception { + return createBroker(deleteAllMessagesOnStartup, TRANSPORT_URI); + } - public BrokerService createBroker(boolean deleteAllMessagesOnStartup, String bindAddress) throws Exception { - broker = new BrokerService(); - broker.addConnector(bindAddress); - broker.setDeleteAllMessagesOnStartup(deleteAllMessagesOnStartup); - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); + public BrokerService createBroker(boolean deleteAllMessagesOnStartup, String bindAddress) throws Exception { + broker = new BrokerService(); + broker.addConnector(bindAddress); + broker.setDeleteAllMessagesOnStartup(deleteAllMessagesOnStartup); + PolicyMap policyMap = new PolicyMap(); + PolicyEntry defaultEntry = new PolicyEntry(); - // optimizedDispatche and sync dispatch ensure that the dispatch happens - // before the commit reply that the consumer.clearDispatchList is waiting for. - defaultEntry.setOptimizedDispatch(true); - policyMap.setDefaultEntry(defaultEntry); - broker.setDestinationPolicy(policyMap); + // optimizedDispatche and sync dispatch ensure that the dispatch happens + // before the commit reply that the consumer.clearDispatchList is waiting for. + defaultEntry.setOptimizedDispatch(true); + policyMap.setDefaultEntry(defaultEntry); + broker.setDestinationPolicy(policyMap); - url = broker.getTransportConnectors().get(0).getConnectUri().toString(); + url = broker.getTransportConnectors().get(0).getConnectUri().toString(); - return broker; - } + return broker; + } - @Test - public void testFailoverConsumerDups() throws Exception { - doTestFailoverConsumerDups(true); - } + @Test + public void testFailoverConsumerDups() throws Exception { + doTestFailoverConsumerDups(true); + } - @SuppressWarnings("unchecked") - public void doTestFailoverConsumerDups(final boolean watchTopicAdvisories) throws Exception { + @SuppressWarnings("unchecked") + public void doTestFailoverConsumerDups(final boolean watchTopicAdvisories) throws Exception { - broker = createBroker(true); + broker = createBroker(true); - broker.setPlugins(new BrokerPlugin[] { - new BrokerPluginSupport() { - @Override - public void commitTransaction(ConnectionContext context, - TransactionId xid, boolean onePhase) throws Exception { - // so commit will hang as if reply is lost - context.setDontSendReponse(true); - Executors.newSingleThreadExecutor().execute(new Runnable() { - public void run() { - LOG.info("Stopping broker before commit..."); - try { - broker.stop(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - } - } - }); - broker.start(); + broker.setPlugins(new BrokerPlugin[]{new BrokerPluginSupport() { + @Override + public void commitTransaction(ConnectionContext context, + TransactionId xid, + boolean onePhase) throws Exception { + // so commit will hang as if reply is lost + context.setDontSendReponse(true); + Executors.newSingleThreadExecutor().execute(new Runnable() { + public void run() { + LOG.info("Stopping broker before commit..."); + try { + broker.stop(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + }); + } + }}); + broker.start(); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); - cf.setWatchTopicAdvisories(watchTopicAdvisories); - cf.setDispatchAsync(false); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); + cf.setWatchTopicAdvisories(watchTopicAdvisories); + cf.setDispatchAsync(false); - final ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection(); - connection.start(); + final ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection(); + connection.start(); - final Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final Queue destination = producerSession.createQueue(QUEUE_NAME + "?consumer.prefetchSize=" + prefetch); + final Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final Queue destination = producerSession.createQueue(QUEUE_NAME + "?consumer.prefetchSize=" + prefetch); - final Session consumerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + final Session consumerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - final CountDownLatch commitDoneLatch = new CountDownLatch(1); - final CountDownLatch messagesReceived = new CountDownLatch(2); + final CountDownLatch commitDoneLatch = new CountDownLatch(1); + final CountDownLatch messagesReceived = new CountDownLatch(2); - final MessageConsumer testConsumer = consumerSession.createConsumer(destination); - testConsumer.setMessageListener(new MessageListener() { + final MessageConsumer testConsumer = consumerSession.createConsumer(destination); + testConsumer.setMessageListener(new MessageListener() { - public void onMessage(Message message) { - LOG.info("consume one and commit"); + public void onMessage(Message message) { + LOG.info("consume one and commit"); - assertNotNull("got message", message); + assertNotNull("got message", message); - try { - consumerSession.commit(); - } catch (JMSException e) { - e.printStackTrace(); - } - commitDoneLatch.countDown(); - messagesReceived.countDown(); - LOG.info("done commit"); + try { + consumerSession.commit(); } - }); - - // may block if broker shutodwn happens quickly - Executors.newSingleThreadExecutor().execute(new Runnable() { - public void run() { - LOG.info("producer started"); - try { - produceMessage(producerSession, destination, prefetch * 2); - } catch (javax.jms.IllegalStateException SessionClosedExpectedOnShutdown) { - } catch (JMSException e) { - e.printStackTrace(); - fail("unexpceted ex on producer: " + e); - } - LOG.info("producer done"); + catch (JMSException e) { + e.printStackTrace(); } - }); + commitDoneLatch.countDown(); + messagesReceived.countDown(); + LOG.info("done commit"); + } + }); - // will be stopped by the plugin - broker.waitUntilStopped(); - broker = createBroker(false, url); - broker.start(); - - assertTrue("consumer added through failover", commitDoneLatch.await(20, TimeUnit.SECONDS)); - assertTrue("another message was received after failover", messagesReceived.await(20, TimeUnit.SECONDS)); - - connection.close(); - } - - @Test - public void TestFailoverConsumerOutstandingSendTxIncomplete() throws Exception { - doTestFailoverConsumerOutstandingSendTx(false); - } - - @Test - public void TestFailoverConsumerOutstandingSendTxComplete() throws Exception { - doTestFailoverConsumerOutstandingSendTx(true); - } - - @SuppressWarnings("unchecked") - public void doTestFailoverConsumerOutstandingSendTx(final boolean doActualBrokerCommit) throws Exception { - final boolean watchTopicAdvisories = true; - broker = createBroker(true); - - broker.setPlugins(new BrokerPlugin[] { new BrokerPluginSupport() { - @Override - public void commitTransaction(ConnectionContext context, - TransactionId xid, boolean onePhase) throws Exception { - // from the consumer perspective whether the commit completed on the broker or - // not is irrelevant, the transaction is still in doubt in the absence of a reply - if (doActualBrokerCommit) { - LOG.info("doing actual broker commit..."); - super.commitTransaction(context, xid, onePhase); - } - // so commit will hang as if reply is lost - context.setDontSendReponse(true); - Executors.newSingleThreadExecutor().execute(new Runnable() { - public void run() { - LOG.info("Stopping broker before commit..."); - try { - broker.stop(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); + // may block if broker shutodwn happens quickly + Executors.newSingleThreadExecutor().execute(new Runnable() { + public void run() { + LOG.info("producer started"); + try { + produceMessage(producerSession, destination, prefetch * 2); } - } }); - broker.start(); - - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); - cf.setWatchTopicAdvisories(watchTopicAdvisories); - cf.setDispatchAsync(false); - - final ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection(); - connection.start(); - - final Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final Queue destination = producerSession.createQueue(QUEUE_NAME - + "?consumer.prefetchSize=" + prefetch); - - final Queue signalDestination = producerSession.createQueue(QUEUE_NAME + ".signal" - + "?consumer.prefetchSize=" + prefetch); - - final Session consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED); - - final CountDownLatch commitDoneLatch = new CountDownLatch(1); - final CountDownLatch messagesReceived = new CountDownLatch(3); - final AtomicBoolean gotCommitException = new AtomicBoolean(false); - final ArrayList receivedMessages = new ArrayList(); - final MessageConsumer testConsumer = consumerSession.createConsumer(destination); - testConsumer.setMessageListener(new MessageListener() { - - public void onMessage(Message message) { - LOG.info("consume one and commit: " + message); - assertNotNull("got message", message); - receivedMessages.add((TextMessage) message); - try { - produceMessage(consumerSession, signalDestination, 1); - consumerSession.commit(); - } catch (JMSException e) { - LOG.info("commit exception", e); - gotCommitException.set(true); - } - commitDoneLatch.countDown(); - messagesReceived.countDown(); - LOG.info("done commit"); + catch (javax.jms.IllegalStateException SessionClosedExpectedOnShutdown) { } - }); - - // may block if broker shutdown happens quickly - Executors.newSingleThreadExecutor().execute(new Runnable() { - public void run() { - LOG.info("producer started"); - try { - produceMessage(producerSession, destination, prefetch * 2); - } catch (javax.jms.IllegalStateException SessionClosedExpectedOnShutdown) { - } catch (JMSException e) { - e.printStackTrace(); - fail("unexpceted ex on producer: " + e); - } - LOG.info("producer done"); + catch (JMSException e) { + e.printStackTrace(); + fail("unexpceted ex on producer: " + e); } - }); + LOG.info("producer done"); + } + }); - // will be stopped by the plugin - broker.waitUntilStopped(); - broker = createBroker(false, url); - broker.start(); + // will be stopped by the plugin + broker.waitUntilStopped(); + broker = createBroker(false, url); + broker.start(); - assertTrue("commit done through failover", commitDoneLatch.await(20, TimeUnit.SECONDS)); - assertTrue("commit failed", gotCommitException.get()); - assertTrue("another message was received after failover", messagesReceived.await(20, TimeUnit.SECONDS)); - int receivedIndex = 0; - assertEquals("get message 0 first", MESSAGE_TEXT + "0", receivedMessages.get(receivedIndex++).getText()); - if (!doActualBrokerCommit) { - // it will be redelivered and not tracked as a duplicate - assertEquals("get message 0 second", MESSAGE_TEXT + "0", receivedMessages.get(receivedIndex++).getText()); - } - assertTrue("another message was received", messagesReceived.await(20, TimeUnit.SECONDS)); - assertEquals("get message 1 eventually", MESSAGE_TEXT + "1", receivedMessages.get(receivedIndex++).getText()); + assertTrue("consumer added through failover", commitDoneLatch.await(20, TimeUnit.SECONDS)); + assertTrue("another message was received after failover", messagesReceived.await(20, TimeUnit.SECONDS)); - connection.close(); - } + connection.close(); + } - @Test - public void testRollbackFailoverConsumerTx() throws Exception { - broker = createBroker(true); - broker.start(); + @Test + public void TestFailoverConsumerOutstandingSendTxIncomplete() throws Exception { + doTestFailoverConsumerOutstandingSendTx(false); + } - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); - cf.setConsumerFailoverRedeliveryWaitPeriod(10000); - final ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection(); - connection.start(); + @Test + public void TestFailoverConsumerOutstandingSendTxComplete() throws Exception { + doTestFailoverConsumerOutstandingSendTx(true); + } - final Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final Queue destination = producerSession.createQueue(QUEUE_NAME); + @SuppressWarnings("unchecked") + public void doTestFailoverConsumerOutstandingSendTx(final boolean doActualBrokerCommit) throws Exception { + final boolean watchTopicAdvisories = true; + broker = createBroker(true); - final Session consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED); - final MessageConsumer testConsumer = consumerSession.createConsumer(destination); - assertNull("no message yet", testConsumer.receiveNoWait()); + broker.setPlugins(new BrokerPlugin[]{new BrokerPluginSupport() { + @Override + public void commitTransaction(ConnectionContext context, + TransactionId xid, + boolean onePhase) throws Exception { + // from the consumer perspective whether the commit completed on the broker or + // not is irrelevant, the transaction is still in doubt in the absence of a reply + if (doActualBrokerCommit) { + LOG.info("doing actual broker commit..."); + super.commitTransaction(context, xid, onePhase); + } + // so commit will hang as if reply is lost + context.setDontSendReponse(true); + Executors.newSingleThreadExecutor().execute(new Runnable() { + public void run() { + LOG.info("Stopping broker before commit..."); + try { + broker.stop(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + }); + } + }}); + broker.start(); - produceMessage(producerSession, destination, 1); - producerSession.close(); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); + cf.setWatchTopicAdvisories(watchTopicAdvisories); + cf.setDispatchAsync(false); - // consume then rollback after restart - Message msg = testConsumer.receive(5000); - assertNotNull(msg); + final ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection(); + connection.start(); - // restart with outstanding delivered message - broker.stop(); - broker.waitUntilStopped(); - broker = createBroker(false, url); - broker.start(); + final Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final Queue destination = producerSession.createQueue(QUEUE_NAME + "?consumer.prefetchSize=" + prefetch); - consumerSession.rollback(); + final Queue signalDestination = producerSession.createQueue(QUEUE_NAME + ".signal" + "?consumer.prefetchSize=" + prefetch); - // receive again - msg = testConsumer.receive(10000); - assertNotNull("got message again after rollback", msg); + final Session consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED); - consumerSession.commit(); + final CountDownLatch commitDoneLatch = new CountDownLatch(1); + final CountDownLatch messagesReceived = new CountDownLatch(3); + final AtomicBoolean gotCommitException = new AtomicBoolean(false); + final ArrayList receivedMessages = new ArrayList(); + final MessageConsumer testConsumer = consumerSession.createConsumer(destination); + testConsumer.setMessageListener(new MessageListener() { - // close before sweep - consumerSession.close(); - msg = receiveMessage(cf, destination); - assertNull("should be nothing left after commit", msg); - connection.close(); - } + public void onMessage(Message message) { + LOG.info("consume one and commit: " + message); + assertNotNull("got message", message); + receivedMessages.add((TextMessage) message); + try { + produceMessage(consumerSession, signalDestination, 1); + consumerSession.commit(); + } + catch (JMSException e) { + LOG.info("commit exception", e); + gotCommitException.set(true); + } + commitDoneLatch.countDown(); + messagesReceived.countDown(); + LOG.info("done commit"); + } + }); - private Message receiveMessage(ActiveMQConnectionFactory cf, - Queue destination) throws Exception { - final ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection(); - connection.start(); - final Session consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED); - final MessageConsumer consumer = consumerSession.createConsumer(destination); - Message msg = consumer.receive(5000); - consumerSession.commit(); - connection.close(); - return msg; - } + // may block if broker shutdown happens quickly + Executors.newSingleThreadExecutor().execute(new Runnable() { + public void run() { + LOG.info("producer started"); + try { + produceMessage(producerSession, destination, prefetch * 2); + } + catch (javax.jms.IllegalStateException SessionClosedExpectedOnShutdown) { + } + catch (JMSException e) { + e.printStackTrace(); + fail("unexpceted ex on producer: " + e); + } + LOG.info("producer done"); + } + }); - private void produceMessage(final Session producerSession, Queue destination, long count) - throws JMSException { - MessageProducer producer = producerSession.createProducer(destination); - for (int i=0; i testConsumers = new Vector(); + for (int i = 0; i < maxConsumers - 1; i++) { + testConsumers.add(new TestConsumer(consumerSession, destination, connection)); + } - public int unconsumedSize() { - return unconsumedMessages.size(); - } + produceMessage(consumerSession, destination, maxConsumers * prefetch); - public int deliveredSize() { - return deliveredMessages.size(); - } - } + assertTrue("add messages are dispatched", Wait.waitFor(new Wait.Condition() { + public boolean isSatisified() throws Exception { + int totalUnconsumed = 0; + for (TestConsumer testConsumer : testConsumers) { + long unconsumed = testConsumer.unconsumedSize(); + LOG.info(testConsumer.getConsumerId() + " unconsumed: " + unconsumed); + totalUnconsumed += unconsumed; + } + return totalUnconsumed == (maxConsumers - 1) * prefetch; + } + })); - static long idGen = 100; - private static long nextGen() { - idGen -=5; - return idGen; - } + final CountDownLatch shutdownConsumerAdded = new CountDownLatch(1); + + Executors.newSingleThreadExecutor().execute(new Runnable() { + public void run() { + try { + LOG.info("add last consumer..."); + testConsumers.add(new TestConsumer(consumerSession, destination, connection)); + shutdownConsumerAdded.countDown(); + LOG.info("done add last consumer"); + } + catch (Exception e) { + e.printStackTrace(); + } + } + }); + + // will be stopped by the plugin + broker.waitUntilStopped(); + + // verify interrupt + assertTrue("add messages dispatched and unconsumed are cleaned up", Wait.waitFor(new Wait.Condition() { + public boolean isSatisified() throws Exception { + int totalUnconsumed = 0; + for (TestConsumer testConsumer : testConsumers) { + long unconsumed = testConsumer.unconsumedSize(); + LOG.info(testConsumer.getConsumerId() + " unconsumed: " + unconsumed); + totalUnconsumed += unconsumed; + } + return totalUnconsumed == 0; + } + })); + + broker = createBroker(false, this.url); + broker.start(); + + assertTrue("consumer added through failover", shutdownConsumerAdded.await(30, TimeUnit.SECONDS)); + + // each should again get prefetch messages - all unconsumed deliveries should be rolledback + assertTrue("after start all messages are re dispatched", Wait.waitFor(new Wait.Condition() { + public boolean isSatisified() throws Exception { + int totalUnconsumed = 0; + for (TestConsumer testConsumer : testConsumers) { + long unconsumed = testConsumer.unconsumedSize(); + LOG.info(testConsumer.getConsumerId() + " after restart: unconsumed: " + unconsumed); + totalUnconsumed += unconsumed; + } + return totalUnconsumed == (maxConsumers) * prefetch; + } + })); + + connection.close(); + } + + private void produceMessage(final Session producerSession, Queue destination, long count) throws JMSException { + MessageProducer producer = producerSession.createProducer(destination); + for (int i = 0; i < count; i++) { + TextMessage message = producerSession.createTextMessage("Test message " + i); + producer.send(message); + } + producer.close(); + } + + // allow access to unconsumedMessages + class TestConsumer extends ActiveMQMessageConsumer { + + TestConsumer(Session consumerSession, Destination destination, ActiveMQConnection connection) throws Exception { + super((ActiveMQSession) consumerSession, new ConsumerId(new SessionId(connection.getConnectionInfo().getConnectionId(), 1), nextGen()), ActiveMQMessageTransformation.transformDestination(destination), null, "", prefetch, -1, false, false, true, null); + } + + public int unconsumedSize() { + return unconsumedMessages.size(); + } + + public int deliveredSize() { + return deliveredMessages.size(); + } + } + + static long idGen = 100; + + private static long nextGen() { + idGen -= 5; + return idGen; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverDuplicateTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverDuplicateTest.java index ceb48ecf45..cb15940522 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverDuplicateTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverDuplicateTest.java @@ -45,208 +45,206 @@ import org.slf4j.LoggerFactory; public class FailoverDuplicateTest extends TestSupport { - private static final Logger LOG = LoggerFactory.getLogger(FailoverDuplicateTest.class); - private static final String QUEUE_NAME = "TestQueue"; - private static final String TRANSPORT_URI = "tcp://localhost:0"; - private String url; - BrokerService broker; + private static final Logger LOG = LoggerFactory.getLogger(FailoverDuplicateTest.class); + private static final String QUEUE_NAME = "TestQueue"; + private static final String TRANSPORT_URI = "tcp://localhost:0"; + private String url; + BrokerService broker; - @Override - public void tearDown() throws Exception { - stopBroker(); - } + @Override + public void tearDown() throws Exception { + stopBroker(); + } - public void stopBroker() throws Exception { - if (broker != null) { - broker.stop(); - } - } + public void stopBroker() throws Exception { + if (broker != null) { + broker.stop(); + } + } - public void startBroker(boolean deleteAllMessagesOnStartup) throws Exception { - broker = createBroker(deleteAllMessagesOnStartup); - broker.start(); - } + public void startBroker(boolean deleteAllMessagesOnStartup) throws Exception { + broker = createBroker(deleteAllMessagesOnStartup); + broker.start(); + } - public void startBroker(boolean deleteAllMessagesOnStartup, String bindAddress) throws Exception { - broker = createBroker(deleteAllMessagesOnStartup, bindAddress); - broker.start(); - } + public void startBroker(boolean deleteAllMessagesOnStartup, String bindAddress) throws Exception { + broker = createBroker(deleteAllMessagesOnStartup, bindAddress); + broker.start(); + } - public BrokerService createBroker(boolean deleteAllMessagesOnStartup) throws Exception { - return createBroker(deleteAllMessagesOnStartup, TRANSPORT_URI); - } + public BrokerService createBroker(boolean deleteAllMessagesOnStartup) throws Exception { + return createBroker(deleteAllMessagesOnStartup, TRANSPORT_URI); + } - public BrokerService createBroker(boolean deleteAllMessagesOnStartup, String bindAddress) throws Exception { - broker = new BrokerService(); - broker.setUseJmx(false); - broker.setAdvisorySupport(false); - broker.addConnector(bindAddress); - broker.setDeleteAllMessagesOnStartup(deleteAllMessagesOnStartup); + public BrokerService createBroker(boolean deleteAllMessagesOnStartup, String bindAddress) throws Exception { + broker = new BrokerService(); + broker.setUseJmx(false); + broker.setAdvisorySupport(false); + broker.addConnector(bindAddress); + broker.setDeleteAllMessagesOnStartup(deleteAllMessagesOnStartup); - url = broker.getTransportConnectors().get(0).getConnectUri().toString(); + url = broker.getTransportConnectors().get(0).getConnectUri().toString(); - return broker; - } + return broker; + } - public void configureConnectionFactory(ActiveMQConnectionFactory factory) { - factory.setAuditMaximumProducerNumber(2048); - factory.setOptimizeAcknowledge(true); - } + public void configureConnectionFactory(ActiveMQConnectionFactory factory) { + factory.setAuditMaximumProducerNumber(2048); + factory.setOptimizeAcknowledge(true); + } - @SuppressWarnings("unchecked") - public void testFailoverSendReplyLost() throws Exception { + @SuppressWarnings("unchecked") + public void testFailoverSendReplyLost() throws Exception { - broker = createBroker(true); - setDefaultPersistenceAdapter(broker); + broker = createBroker(true); + setDefaultPersistenceAdapter(broker); - final CountDownLatch gotMessageLatch = new CountDownLatch(1); - final CountDownLatch producersDone = new CountDownLatch(1); - final AtomicBoolean first = new AtomicBoolean(false); - broker.setPlugins(new BrokerPlugin[]{ - new BrokerPluginSupport() { - @Override - public void send(final ProducerBrokerExchange producerExchange, - org.apache.activemq.command.Message messageSend) - throws Exception { - // so send will hang as if reply is lost - super.send(producerExchange, messageSend); - if (first.compareAndSet(false, true)) { - producerExchange.getConnectionContext().setDontSendReponse(true); - Executors.newSingleThreadExecutor().execute(new Runnable() { - @Override - public void run() { - try { - LOG.info("Waiting for recepit"); - assertTrue("message received on time", gotMessageLatch.await(60, TimeUnit.SECONDS)); - assertTrue("new producers done on time", producersDone.await(120, TimeUnit.SECONDS)); - LOG.info("Stopping connection post send and receive and multiple producers"); - producerExchange.getConnectionContext().getConnection().stop(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - } - } - } - }); - broker.start(); - - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")?jms.watchTopicAdvisories=false"); - configureConnectionFactory(cf); - Connection sendConnection = cf.createConnection(); - sendConnection.start(); - - final Session sendSession = sendConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final Queue destination = sendSession.createQueue(QUEUE_NAME); - - - final AtomicInteger receivedCount = new AtomicInteger(); - MessageListener listener = new MessageListener() { - @Override - public void onMessage(Message message) { - gotMessageLatch.countDown(); - receivedCount.incrementAndGet(); + final CountDownLatch gotMessageLatch = new CountDownLatch(1); + final CountDownLatch producersDone = new CountDownLatch(1); + final AtomicBoolean first = new AtomicBoolean(false); + broker.setPlugins(new BrokerPlugin[]{new BrokerPluginSupport() { + @Override + public void send(final ProducerBrokerExchange producerExchange, + org.apache.activemq.command.Message messageSend) throws Exception { + // so send will hang as if reply is lost + super.send(producerExchange, messageSend); + if (first.compareAndSet(false, true)) { + producerExchange.getConnectionContext().setDontSendReponse(true); + Executors.newSingleThreadExecutor().execute(new Runnable() { + @Override + public void run() { + try { + LOG.info("Waiting for recepit"); + assertTrue("message received on time", gotMessageLatch.await(60, TimeUnit.SECONDS)); + assertTrue("new producers done on time", producersDone.await(120, TimeUnit.SECONDS)); + LOG.info("Stopping connection post send and receive and multiple producers"); + producerExchange.getConnectionContext().getConnection().stop(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + }); } - }; - Connection receiveConnection; - Session receiveSession = null; - receiveConnection = cf.createConnection(); - receiveConnection.start(); - receiveSession = receiveConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - receiveSession.createConsumer(destination).setMessageListener(listener); + } + }}); + broker.start(); - final CountDownLatch sendDoneLatch = new CountDownLatch(1); - // broker will die on send reply so this will hang till restart - Executors.newSingleThreadExecutor().execute(new Runnable() { - @Override - public void run() { - LOG.info("doing async send..."); - try { - produceMessage(sendSession, destination, "will resend", 1); - } catch (JMSException e) { - LOG.error("got send exception: ", e); - fail("got unexpected send exception" + e); - } - sendDoneLatch.countDown(); - LOG.info("done async send"); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")?jms.watchTopicAdvisories=false"); + configureConnectionFactory(cf); + Connection sendConnection = cf.createConnection(); + sendConnection.start(); + + final Session sendSession = sendConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final Queue destination = sendSession.createQueue(QUEUE_NAME); + + final AtomicInteger receivedCount = new AtomicInteger(); + MessageListener listener = new MessageListener() { + @Override + public void onMessage(Message message) { + gotMessageLatch.countDown(); + receivedCount.incrementAndGet(); + } + }; + Connection receiveConnection; + Session receiveSession = null; + receiveConnection = cf.createConnection(); + receiveConnection.start(); + receiveSession = receiveConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + receiveSession.createConsumer(destination).setMessageListener(listener); + + final CountDownLatch sendDoneLatch = new CountDownLatch(1); + // broker will die on send reply so this will hang till restart + Executors.newSingleThreadExecutor().execute(new Runnable() { + @Override + public void run() { + LOG.info("doing async send..."); + try { + produceMessage(sendSession, destination, "will resend", 1); } - }); - - - assertTrue("one message got through on time", gotMessageLatch.await(20, TimeUnit.SECONDS)); - // send more messages, blow producer audit - final int numProducers = 1050; - final int numPerProducer = 2; - final int totalSent = numPerProducer * numProducers + 1; - for (int i=0; i received = new Vector(); + Executors.newSingleThreadExecutor().execute(new Runnable() { + public void run() { + try { + LOG.info("receive one..."); + Message msg = consumer.receive(30000); + if (msg != null) { + received.add(msg); + } + receiveDone.countDown(); + LOG.info("done receive"); } - }); + catch (Exception e) { + e.printStackTrace(); + } + } + }); - // will be stopped by the plugin - assertTrue("pull completed on broker", pullDone.await(30, TimeUnit.SECONDS)); - broker.waitUntilStopped(); - broker = createBroker(false, url); - broker.start(); + // will be stopped by the plugin + assertTrue("pull completed on broker", pullDone.await(30, TimeUnit.SECONDS)); + broker.waitUntilStopped(); + broker = createBroker(false, url); + broker.start(); - assertTrue("receive completed through failover", receiveDone.await(30, TimeUnit.SECONDS)); + assertTrue("receive completed through failover", receiveDone.await(30, TimeUnit.SECONDS)); - assertTrue("we got our message:", !received.isEmpty()); + assertTrue("we got our message:", !received.isEmpty()); - connection.close(); - } + connection.close(); + } - private void produceMessage(final Session producerSession, Queue destination, long count) - throws JMSException { - MessageProducer producer = producerSession.createProducer(destination); - for (int i = 0; i < count; i++) { - TextMessage message = producerSession.createTextMessage("Test message " + i); - producer.send(message); - } - producer.close(); - } + private void produceMessage(final Session producerSession, Queue destination, long count) throws JMSException { + MessageProducer producer = producerSession.createProducer(destination); + for (int i = 0; i < count; i++) { + TextMessage message = producerSession.createTextMessage("Test message " + i); + producer.send(message); + } + producer.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverPriorityTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverPriorityTest.java index bed51830d0..fb4f969f26 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverPriorityTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverPriorityTest.java @@ -23,204 +23,206 @@ import org.slf4j.LoggerFactory; public class FailoverPriorityTest extends FailoverClusterTestSupport { - protected final Logger LOG = LoggerFactory.getLogger(getClass()); + protected final Logger LOG = LoggerFactory.getLogger(getClass()); - private static final String BROKER_A_CLIENT_TC_ADDRESS = "tcp://127.0.0.1:61616"; - private static final String BROKER_B_CLIENT_TC_ADDRESS = "tcp://127.0.0.1:61617"; - private static final String BROKER_C_CLIENT_TC_ADDRESS = "tcp://127.0.0.1:61618"; - private final HashMap urls = new HashMap(); + private static final String BROKER_A_CLIENT_TC_ADDRESS = "tcp://127.0.0.1:61616"; + private static final String BROKER_B_CLIENT_TC_ADDRESS = "tcp://127.0.0.1:61617"; + private static final String BROKER_C_CLIENT_TC_ADDRESS = "tcp://127.0.0.1:61618"; + private final HashMap urls = new HashMap(); - @Override - public void setUp() throws Exception { - super.setUp(); - urls.put(BROKER_A_NAME, BROKER_A_CLIENT_TC_ADDRESS); - urls.put(BROKER_B_NAME, BROKER_B_CLIENT_TC_ADDRESS); - } + @Override + public void setUp() throws Exception { + super.setUp(); + urls.put(BROKER_A_NAME, BROKER_A_CLIENT_TC_ADDRESS); + urls.put(BROKER_B_NAME, BROKER_B_CLIENT_TC_ADDRESS); + } - private static final String BROKER_A_NAME = "BROKERA"; - private static final String BROKER_B_NAME = "BROKERB"; - private static final String BROKER_C_NAME = "BROKERC"; + private static final String BROKER_A_NAME = "BROKERA"; + private static final String BROKER_B_NAME = "BROKERB"; + private static final String BROKER_C_NAME = "BROKERC"; + public void testPriorityBackup() throws Exception { + createBrokerA(); + createBrokerB(); + getBroker(BROKER_B_NAME).waitUntilStarted(); + Thread.sleep(1000); - public void testPriorityBackup() throws Exception { - createBrokerA(); - createBrokerB(); - getBroker(BROKER_B_NAME).waitUntilStarted(); - Thread.sleep(1000); + setClientUrl("failover:(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + ")?randomize=false&priorityBackup=true&initialReconnectDelay=1000&useExponentialBackOff=false"); + createClients(5); - setClientUrl("failover:(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + ")?randomize=false&priorityBackup=true&initialReconnectDelay=1000&useExponentialBackOff=false"); - createClients(5); + assertAllConnectedTo(urls.get(BROKER_A_NAME)); - assertAllConnectedTo(urls.get(BROKER_A_NAME)); + restart(false, BROKER_A_NAME, BROKER_B_NAME); + for (int i = 0; i < 3; i++) { + restart(true, BROKER_A_NAME, BROKER_B_NAME); + } - restart(false, BROKER_A_NAME, BROKER_B_NAME); + Thread.sleep(5000); - for (int i = 0; i < 3; i++) { - restart(true, BROKER_A_NAME, BROKER_B_NAME); - } + restart(false, BROKER_A_NAME, BROKER_B_NAME); - Thread.sleep(5000); + } - restart(false, BROKER_A_NAME, BROKER_B_NAME); + public void testPriorityBackupList() throws Exception { + createBrokerA(); + createBrokerB(); + getBroker(BROKER_B_NAME).waitUntilStarted(); + Thread.sleep(1000); - } + setClientUrl("failover:(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + ")?randomize=false&priorityBackup=true&priorityURIs=tcp://127.0.0.1:61617&initialReconnectDelay=1000&useExponentialBackOff=false"); + createClients(5); - public void testPriorityBackupList() throws Exception { - createBrokerA(); - createBrokerB(); - getBroker(BROKER_B_NAME).waitUntilStarted(); - Thread.sleep(1000); + Thread.sleep(3000); - setClientUrl("failover:(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + ")?randomize=false&priorityBackup=true&priorityURIs=tcp://127.0.0.1:61617&initialReconnectDelay=1000&useExponentialBackOff=false"); - createClients(5); + assertAllConnectedTo(urls.get(BROKER_B_NAME)); - Thread.sleep(3000); + restart(false, BROKER_B_NAME, BROKER_A_NAME); - assertAllConnectedTo(urls.get(BROKER_B_NAME)); + for (int i = 0; i < 3; i++) { + restart(true, BROKER_B_NAME, BROKER_A_NAME); + } - restart(false, BROKER_B_NAME, BROKER_A_NAME); + restart(false, BROKER_B_NAME, BROKER_A_NAME); - for (int i = 0; i < 3; i++) { - restart(true, BROKER_B_NAME, BROKER_A_NAME); - } + } - restart(false, BROKER_B_NAME, BROKER_A_NAME); + public void testThreeBrokers() throws Exception { + // Broker A + addBroker(BROKER_A_NAME, createBroker(BROKER_A_NAME)); + addTransportConnector(getBroker(BROKER_A_NAME), "openwire", BROKER_A_CLIENT_TC_ADDRESS, false); + addNetworkBridge(getBroker(BROKER_A_NAME), "A_2_B_Bridge", "static://(" + BROKER_B_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); + addNetworkBridge(getBroker(BROKER_A_NAME), "A_2_C_Bridge", "static://(" + BROKER_C_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); + getBroker(BROKER_A_NAME).start(); - } + // Broker B + addBroker(BROKER_B_NAME, createBroker(BROKER_B_NAME)); + addTransportConnector(getBroker(BROKER_B_NAME), "openwire", BROKER_B_CLIENT_TC_ADDRESS, false); + addNetworkBridge(getBroker(BROKER_B_NAME), "B_2_A_Bridge", "static://(" + BROKER_A_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); + addNetworkBridge(getBroker(BROKER_B_NAME), "B_2_C_Bridge", "static://(" + BROKER_C_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); + getBroker(BROKER_B_NAME).start(); - public void testThreeBrokers() throws Exception { - // Broker A - addBroker(BROKER_A_NAME, createBroker(BROKER_A_NAME)); - addTransportConnector(getBroker(BROKER_A_NAME), "openwire", BROKER_A_CLIENT_TC_ADDRESS, false); - addNetworkBridge(getBroker(BROKER_A_NAME), "A_2_B_Bridge", "static://(" + BROKER_B_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); - addNetworkBridge(getBroker(BROKER_A_NAME), "A_2_C_Bridge", "static://(" + BROKER_C_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); - getBroker(BROKER_A_NAME).start(); + // Broker C + addBroker(BROKER_C_NAME, createBroker(BROKER_C_NAME)); + addTransportConnector(getBroker(BROKER_C_NAME), "openwire", BROKER_C_CLIENT_TC_ADDRESS, false); + addNetworkBridge(getBroker(BROKER_C_NAME), "C_2_A_Bridge", "static://(" + BROKER_A_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); + addNetworkBridge(getBroker(BROKER_C_NAME), "C_2_B_Bridge", "static://(" + BROKER_B_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); + getBroker(BROKER_C_NAME).start(); - // Broker B - addBroker(BROKER_B_NAME, createBroker(BROKER_B_NAME)); - addTransportConnector(getBroker(BROKER_B_NAME), "openwire", BROKER_B_CLIENT_TC_ADDRESS, false); - addNetworkBridge(getBroker(BROKER_B_NAME), "B_2_A_Bridge", "static://(" + BROKER_A_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); - addNetworkBridge(getBroker(BROKER_B_NAME), "B_2_C_Bridge", "static://(" + BROKER_C_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); - getBroker(BROKER_B_NAME).start(); + getBroker(BROKER_C_NAME).waitUntilStarted(); + Thread.sleep(1000); - // Broker C - addBroker(BROKER_C_NAME, createBroker(BROKER_C_NAME)); - addTransportConnector(getBroker(BROKER_C_NAME), "openwire", BROKER_C_CLIENT_TC_ADDRESS, false); - addNetworkBridge(getBroker(BROKER_C_NAME), "C_2_A_Bridge", "static://(" + BROKER_A_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); - addNetworkBridge(getBroker(BROKER_C_NAME), "C_2_B_Bridge", "static://(" + BROKER_B_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); - getBroker(BROKER_C_NAME).start(); + setClientUrl("failover:(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + "," + BROKER_C_CLIENT_TC_ADDRESS + ")?randomize=false&priorityBackup=true&initialReconnectDelay=1000&useExponentialBackOff=false"); + createClients(5); - getBroker(BROKER_C_NAME).waitUntilStarted(); - Thread.sleep(1000); + assertAllConnectedTo(urls.get(BROKER_A_NAME)); - setClientUrl("failover:(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + "," + BROKER_C_CLIENT_TC_ADDRESS + ")?randomize=false&priorityBackup=true&initialReconnectDelay=1000&useExponentialBackOff=false"); + restart(true, BROKER_A_NAME, BROKER_B_NAME); - createClients(5); + } - assertAllConnectedTo(urls.get(BROKER_A_NAME)); + public void testPriorityBackupAndUpdateClients() throws Exception { + // Broker A + addBroker(BROKER_A_NAME, createBroker(BROKER_A_NAME)); + addTransportConnector(getBroker(BROKER_A_NAME), "openwire", BROKER_A_CLIENT_TC_ADDRESS, true); + addNetworkBridge(getBroker(BROKER_A_NAME), "A_2_B_Bridge", "static://(" + BROKER_B_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); + getBroker(BROKER_A_NAME).start(); - restart(true, BROKER_A_NAME, BROKER_B_NAME); + // Broker B + addBroker(BROKER_B_NAME, createBroker(BROKER_B_NAME)); + addTransportConnector(getBroker(BROKER_B_NAME), "openwire", BROKER_B_CLIENT_TC_ADDRESS, true); + addNetworkBridge(getBroker(BROKER_B_NAME), "B_2_A_Bridge", "static://(" + BROKER_A_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); + getBroker(BROKER_B_NAME).start(); - } + getBroker(BROKER_B_NAME).waitUntilStarted(); + Thread.sleep(1000); - public void testPriorityBackupAndUpdateClients() throws Exception { - // Broker A - addBroker(BROKER_A_NAME, createBroker(BROKER_A_NAME)); - addTransportConnector(getBroker(BROKER_A_NAME), "openwire", BROKER_A_CLIENT_TC_ADDRESS, true); - addNetworkBridge(getBroker(BROKER_A_NAME), "A_2_B_Bridge", "static://(" + BROKER_B_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); - getBroker(BROKER_A_NAME).start(); + setClientUrl("failover:(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + ")?randomize=false&priorityBackup=true&initialReconnectDelay=1000&useExponentialBackOff=false"); - // Broker B - addBroker(BROKER_B_NAME, createBroker(BROKER_B_NAME)); - addTransportConnector(getBroker(BROKER_B_NAME), "openwire", BROKER_B_CLIENT_TC_ADDRESS, true); - addNetworkBridge(getBroker(BROKER_B_NAME), "B_2_A_Bridge", "static://(" + BROKER_A_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); - getBroker(BROKER_B_NAME).start(); + LOG.info("Client URI will be: " + getClientUrl()); - getBroker(BROKER_B_NAME).waitUntilStarted(); - Thread.sleep(1000); + createClients(5); - setClientUrl("failover:(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + ")?randomize=false&priorityBackup=true&initialReconnectDelay=1000&useExponentialBackOff=false"); + // Let's wait a little bit longer just in case it takes a while to realize that the + // Broker A is the one with higher priority. + Thread.sleep(5000); - LOG.info("Client URI will be: " + getClientUrl()); + assertAllConnectedTo(urls.get(BROKER_A_NAME)); + } - createClients(5); + private void restart(boolean primary, String primaryName, String secondaryName) throws Exception { - // Let's wait a little bit longer just in case it takes a while to realize that the - // Broker A is the one with higher priority. - Thread.sleep(5000); + Thread.sleep(1000); - assertAllConnectedTo(urls.get(BROKER_A_NAME)); - } + if (primary) { + LOG.info("Stopping " + primaryName); + stopBroker(primaryName); + } + else { + LOG.info("Stopping " + secondaryName); + stopBroker(secondaryName); + } + Thread.sleep(5000); - private void restart(boolean primary, String primaryName, String secondaryName) throws Exception { + if (primary) { + assertAllConnectedTo(urls.get(secondaryName)); + } + else { + assertAllConnectedTo(urls.get(primaryName)); + } - Thread.sleep(1000); + if (primary) { + LOG.info("Starting " + primaryName); + createBrokerByName(primaryName); + getBroker(primaryName).waitUntilStarted(); + } + else { + LOG.info("Starting " + secondaryName); + createBrokerByName(secondaryName); + getBroker(secondaryName).waitUntilStarted(); + } - if (primary) { - LOG.info("Stopping " + primaryName); - stopBroker(primaryName); - } else { - LOG.info("Stopping " + secondaryName); - stopBroker(secondaryName); - } - Thread.sleep(5000); + Thread.sleep(5000); - if (primary) { - assertAllConnectedTo(urls.get(secondaryName)); - } else { - assertAllConnectedTo(urls.get(primaryName)); - } + assertAllConnectedTo(urls.get(primaryName)); - if (primary) { - LOG.info("Starting " + primaryName); - createBrokerByName(primaryName); - getBroker(primaryName).waitUntilStarted(); - } else { - LOG.info("Starting " + secondaryName); - createBrokerByName(secondaryName); - getBroker(secondaryName).waitUntilStarted(); - } + } - Thread.sleep(5000); + private void createBrokerByName(String name) throws Exception { + if (name.equals(BROKER_A_NAME)) { + createBrokerA(); + } + else if (name.equals(BROKER_B_NAME)) { + createBrokerB(); + } + else { + throw new Exception("Unknown broker " + name); + } + } - assertAllConnectedTo(urls.get(primaryName)); + private void createBrokerA() throws Exception { + if (getBroker(BROKER_A_NAME) == null) { + addBroker(BROKER_A_NAME, createBroker(BROKER_A_NAME)); + addTransportConnector(getBroker(BROKER_A_NAME), "openwire", BROKER_A_CLIENT_TC_ADDRESS, false); + addNetworkBridge(getBroker(BROKER_A_NAME), "A_2_B_Bridge", "static://(" + BROKER_B_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); + getBroker(BROKER_A_NAME).start(); + } + } - } + private void createBrokerB() throws Exception { + if (getBroker(BROKER_B_NAME) == null) { + addBroker(BROKER_B_NAME, createBroker(BROKER_B_NAME)); + addTransportConnector(getBroker(BROKER_B_NAME), "openwire", BROKER_B_CLIENT_TC_ADDRESS, false); + addNetworkBridge(getBroker(BROKER_B_NAME), "B_2_A_Bridge", "static://(" + BROKER_A_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); + getBroker(BROKER_B_NAME).start(); + } + } - private void createBrokerByName(String name) throws Exception { - if (name.equals(BROKER_A_NAME)) { - createBrokerA(); - } else if (name.equals(BROKER_B_NAME)) { - createBrokerB(); - } else { - throw new Exception("Unknown broker " + name); - } - } - - private void createBrokerA() throws Exception { - if (getBroker(BROKER_A_NAME) == null) { - addBroker(BROKER_A_NAME, createBroker(BROKER_A_NAME)); - addTransportConnector(getBroker(BROKER_A_NAME), "openwire", BROKER_A_CLIENT_TC_ADDRESS, false); - addNetworkBridge(getBroker(BROKER_A_NAME), "A_2_B_Bridge", "static://(" + BROKER_B_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); - getBroker(BROKER_A_NAME).start(); - } - } - - private void createBrokerB() throws Exception { - if (getBroker(BROKER_B_NAME) == null) { - addBroker(BROKER_B_NAME, createBroker(BROKER_B_NAME)); - addTransportConnector(getBroker(BROKER_B_NAME), "openwire", BROKER_B_CLIENT_TC_ADDRESS, false); - addNetworkBridge(getBroker(BROKER_B_NAME), "B_2_A_Bridge", "static://(" + BROKER_A_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, null); - getBroker(BROKER_B_NAME).start(); - } - } - - @Override - protected void tearDown() throws Exception { - shutdownClients(); - destroyBrokerCluster(); - } + @Override + protected void tearDown() throws Exception { + shutdownClients(); + destroyBrokerCluster(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverRandomTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverRandomTest.java index 8998fe78d4..b4c25c24fe 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverRandomTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverRandomTest.java @@ -24,54 +24,49 @@ import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; public class FailoverRandomTest extends TestCase { - - BrokerService brokerA, brokerB; - - public void setUp() throws Exception { - brokerA = createBroker("A"); - brokerB = createBroker("B"); - } - - public void tearDown() throws Exception { - brokerA.stop(); - brokerB.stop(); - } - - private BrokerService createBroker(String name) throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("Broker"+ name); - broker.addConnector("tcp://localhost:0"); - broker.getManagementContext().setCreateConnector(false); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.start(); - return broker; - } - public void testRandomConnections() throws Exception { - String failoverUrl = "failover:(" - + brokerA.getTransportConnectors().get(0).getConnectUri() - + "," - + brokerB.getTransportConnectors().get(0).getConnectUri() - + ")"; - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(failoverUrl); - - - ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection(); - connection.start(); - String brokerName1 = connection.getBrokerName(); - assertNotNull(brokerName1); - connection.close(); - - String brokerName2 = brokerName1; - int attempts = 40; - while (brokerName1.equals(brokerName2) && attempts-- > 0) { - connection = (ActiveMQConnection) cf.createConnection(); - connection.start(); - brokerName2 = connection.getBrokerName(); - assertNotNull(brokerName2); - connection.close(); - } - assertTrue(brokerName1 + "!=" + brokerName2, !brokerName1.equals(brokerName2)); - } + BrokerService brokerA, brokerB; + + public void setUp() throws Exception { + brokerA = createBroker("A"); + brokerB = createBroker("B"); + } + + public void tearDown() throws Exception { + brokerA.stop(); + brokerB.stop(); + } + + private BrokerService createBroker(String name) throws Exception { + BrokerService broker = new BrokerService(); + broker.setBrokerName("Broker" + name); + broker.addConnector("tcp://localhost:0"); + broker.getManagementContext().setCreateConnector(false); + broker.setPersistent(false); + broker.setUseJmx(false); + broker.start(); + return broker; + } + + public void testRandomConnections() throws Exception { + String failoverUrl = "failover:(" + brokerA.getTransportConnectors().get(0).getConnectUri() + "," + brokerB.getTransportConnectors().get(0).getConnectUri() + ")"; + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(failoverUrl); + + ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection(); + connection.start(); + String brokerName1 = connection.getBrokerName(); + assertNotNull(brokerName1); + connection.close(); + + String brokerName2 = brokerName1; + int attempts = 40; + while (brokerName1.equals(brokerName2) && attempts-- > 0) { + connection = (ActiveMQConnection) cf.createConnection(); + connection.start(); + brokerName2 = connection.getBrokerName(); + assertNotNull(brokerName2); + connection.close(); + } + assertTrue(brokerName1 + "!=" + brokerName2, !brokerName1.equals(brokerName2)); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverRedeliveryTransactionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverRedeliveryTransactionTest.java index c8d4c511a6..6b7a2bb992 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverRedeliveryTransactionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverRedeliveryTransactionTest.java @@ -17,6 +17,7 @@ package org.apache.activemq.transport.failover; import junit.framework.Test; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.region.policy.PolicyEntry; @@ -24,65 +25,65 @@ import org.apache.activemq.broker.region.policy.PolicyMap; public class FailoverRedeliveryTransactionTest extends FailoverTransactionTest { - public static Test suite() { - return suite(FailoverRedeliveryTransactionTest.class); - } + public static Test suite() { + return suite(FailoverRedeliveryTransactionTest.class); + } - @Override - public void configureConnectionFactory(ActiveMQConnectionFactory factory) { - super.configureConnectionFactory(factory); - factory.setTransactedIndividualAck(true); - } + @Override + public void configureConnectionFactory(ActiveMQConnectionFactory factory) { + super.configureConnectionFactory(factory); + factory.setTransactedIndividualAck(true); + } - @Override - public BrokerService createBroker(boolean deleteAllMessagesOnStartup, String bindAddress) throws Exception { - BrokerService brokerService = super.createBroker(deleteAllMessagesOnStartup, bindAddress); - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setPersistJMSRedelivered(true); - policyMap.setDefaultEntry(defaultEntry); - brokerService.setDestinationPolicy(policyMap); - return brokerService; - } + @Override + public BrokerService createBroker(boolean deleteAllMessagesOnStartup, String bindAddress) throws Exception { + BrokerService brokerService = super.createBroker(deleteAllMessagesOnStartup, bindAddress); + PolicyMap policyMap = new PolicyMap(); + PolicyEntry defaultEntry = new PolicyEntry(); + defaultEntry.setPersistJMSRedelivered(true); + policyMap.setDefaultEntry(defaultEntry); + brokerService.setDestinationPolicy(policyMap); + return brokerService; + } - // no point rerunning these - @Override - public void testFailoverProducerCloseBeforeTransaction() throws Exception { - } + // no point rerunning these + @Override + public void testFailoverProducerCloseBeforeTransaction() throws Exception { + } - @Override - public void initCombosForTestFailoverCommitReplyLost() { - } + @Override + public void initCombosForTestFailoverCommitReplyLost() { + } - @Override - public void testFailoverCommitReplyLost() throws Exception { - } + @Override + public void testFailoverCommitReplyLost() throws Exception { + } - @Override - public void testFailoverCommitReplyLostWithDestinationPathSeparator() throws Exception { - } + @Override + public void testFailoverCommitReplyLostWithDestinationPathSeparator() throws Exception { + } - @Override - public void initCombosForTestFailoverSendReplyLost() { - } + @Override + public void initCombosForTestFailoverSendReplyLost() { + } - @Override - public void testFailoverSendReplyLost() throws Exception { - } + @Override + public void testFailoverSendReplyLost() throws Exception { + } - @Override - public void initCombosForTestFailoverConnectionSendReplyLost() { - } + @Override + public void initCombosForTestFailoverConnectionSendReplyLost() { + } - @Override - public void testFailoverConnectionSendReplyLost() throws Exception { - } + @Override + public void testFailoverConnectionSendReplyLost() throws Exception { + } - @Override - public void testFailoverProducerCloseBeforeTransactionFailWhenDisabled() throws Exception { - } + @Override + public void testFailoverProducerCloseBeforeTransactionFailWhenDisabled() throws Exception { + } - @Override - public void testFailoverMultipleProducerCloseBeforeTransaction() throws Exception { - } + @Override + public void testFailoverMultipleProducerCloseBeforeTransaction() throws Exception { + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverTimeoutTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverTimeoutTest.java index 9ef6e28bfa..07a84365c9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverTimeoutTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverTimeoutTest.java @@ -39,98 +39,95 @@ import org.slf4j.LoggerFactory; public class FailoverTimeoutTest { - private static final Logger LOG = LoggerFactory.getLogger(FailoverTimeoutTest.class); + private static final Logger LOG = LoggerFactory.getLogger(FailoverTimeoutTest.class); - private static final String QUEUE_NAME = "test.failovertimeout"; - BrokerService bs; - URI tcpUri; + private static final String QUEUE_NAME = "test.failovertimeout"; + BrokerService bs; + URI tcpUri; - @Before - public void setUp() throws Exception { - bs = new BrokerService(); - bs.setUseJmx(false); - bs.addConnector("tcp://localhost:0"); - bs.start(); - tcpUri = bs.getTransportConnectors().get(0).getConnectUri(); - } + @Before + public void setUp() throws Exception { + bs = new BrokerService(); + bs.setUseJmx(false); + bs.addConnector("tcp://localhost:0"); + bs.start(); + tcpUri = bs.getTransportConnectors().get(0).getConnectUri(); + } - @After - public void tearDown() throws Exception { - if (bs != null) { - bs.stop(); - } - } + @After + public void tearDown() throws Exception { + if (bs != null) { + bs.stop(); + } + } - @Test - public void testTimoutDoesNotFailConnectionAttempts() throws Exception { - bs.stop(); - long timeout = 1000; + @Test + public void testTimoutDoesNotFailConnectionAttempts() throws Exception { + bs.stop(); + long timeout = 1000; - long startTime = System.currentTimeMillis(); + long startTime = System.currentTimeMillis(); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory( - "failover:(" + tcpUri + ")" + - "?timeout=" + timeout + "&useExponentialBackOff=false" + - "&maxReconnectAttempts=5" + "&initialReconnectDelay=1000"); - Connection connection = cf.createConnection(); - try { - connection.start(); - fail("Should have failed to connect"); - } catch (JMSException ex) { - LOG.info("Caught exception on call to start: {}", ex.getMessage()); - } + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + tcpUri + ")" + + "?timeout=" + timeout + "&useExponentialBackOff=false" + + "&maxReconnectAttempts=5" + "&initialReconnectDelay=1000"); + Connection connection = cf.createConnection(); + try { + connection.start(); + fail("Should have failed to connect"); + } + catch (JMSException ex) { + LOG.info("Caught exception on call to start: {}", ex.getMessage()); + } - long endTime = System.currentTimeMillis(); - long duration = endTime - startTime; + long endTime = System.currentTimeMillis(); + long duration = endTime - startTime; - LOG.info("Time spent waiting to connect: {} ms", duration); + LOG.info("Time spent waiting to connect: {} ms", duration); - assertTrue(duration > 3000); - } + assertTrue(duration > 3000); + } - @Test - public void testTimeout() throws Exception { + @Test + public void testTimeout() throws Exception { - long timeout = 1000; - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + tcpUri + ")?timeout=" + timeout + "&useExponentialBackOff=false"); - Connection connection = cf.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(session - .createQueue(QUEUE_NAME)); - TextMessage message = session.createTextMessage("Test message"); - producer.send(message); + long timeout = 1000; + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + tcpUri + ")?timeout=" + timeout + "&useExponentialBackOff=false"); + Connection connection = cf.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(session.createQueue(QUEUE_NAME)); + TextMessage message = session.createTextMessage("Test message"); + producer.send(message); - bs.stop(); + bs.stop(); - try { - producer.send(message); - } catch (JMSException jmse) { - assertEquals("Failover timeout of " + timeout + " ms reached.", jmse.getMessage()); - } + try { + producer.send(message); + } + catch (JMSException jmse) { + assertEquals("Failover timeout of " + timeout + " ms reached.", jmse.getMessage()); + } - bs = new BrokerService(); - bs.setUseJmx(false); - bs.addConnector(tcpUri); - bs.start(); - bs.waitUntilStarted(); + bs = new BrokerService(); + bs.setUseJmx(false); + bs.addConnector(tcpUri); + bs.start(); + bs.waitUntilStarted(); - producer.send(message); + producer.send(message); - bs.stop(); - } + bs.stop(); + } - @Test - public void testUpdateUris() throws Exception { + @Test + public void testUpdateUris() throws Exception { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + tcpUri + ")?useExponentialBackOff=false"); - ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection(); - connection.start(); - FailoverTransport failoverTransport = connection.getTransport().narrow(FailoverTransport.class); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + tcpUri + ")?useExponentialBackOff=false"); + ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection(); + connection.start(); + FailoverTransport failoverTransport = connection.getTransport().narrow(FailoverTransport.class); - URI[] bunchOfUnknownAndOneKnown = new URI[]{ - new URI("tcp://unknownHost:" + tcpUri.getPort()), - new URI("tcp://unknownHost2:" + tcpUri.getPort()), - new URI("tcp://localhost:2222")}; - failoverTransport.add(false, bunchOfUnknownAndOneKnown); - } + URI[] bunchOfUnknownAndOneKnown = new URI[]{new URI("tcp://unknownHost:" + tcpUri.getPort()), new URI("tcp://unknownHost2:" + tcpUri.getPort()), new URI("tcp://localhost:2222")}; + failoverTransport.add(false, bunchOfUnknownAndOneKnown); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverTransactionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverTransactionTest.java index 4270eea7d4..d50c77f3d2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverTransactionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverTransactionTest.java @@ -17,6 +17,7 @@ package org.apache.activemq.transport.failover; import junit.framework.Test; + import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQMessageConsumer; @@ -70,1112 +71,1112 @@ import java.util.concurrent.atomic.AtomicBoolean; // https://issues.apache.org/activemq/browse/AMQ-2590 public class FailoverTransactionTest extends TestSupport { - private static final Logger LOG = LoggerFactory.getLogger(FailoverTransactionTest.class); - private static final String QUEUE_NAME = "Failover.WithTx"; - private static final String TRANSPORT_URI = "tcp://localhost:0"; - private String url; - BrokerService broker; + private static final Logger LOG = LoggerFactory.getLogger(FailoverTransactionTest.class); + private static final String QUEUE_NAME = "Failover.WithTx"; + private static final String TRANSPORT_URI = "tcp://localhost:0"; + private String url; + BrokerService broker; - public static Test suite() { - return suite(FailoverTransactionTest.class); - } + public static Test suite() { + return suite(FailoverTransactionTest.class); + } - public void setUp() throws Exception { - super.setMaxTestTime(2 * 60 * 1000); // some boxes can be real slow - super.setAutoFail(true); - super.setUp(); - } + public void setUp() throws Exception { + super.setMaxTestTime(2 * 60 * 1000); // some boxes can be real slow + super.setAutoFail(true); + super.setUp(); + } - public void tearDown() throws Exception { - super.tearDown(); - stopBroker(); - } + public void tearDown() throws Exception { + super.tearDown(); + stopBroker(); + } - public void stopBroker() throws Exception { - if (broker != null) { - broker.stop(); - } - } + public void stopBroker() throws Exception { + if (broker != null) { + broker.stop(); + } + } - private void startCleanBroker() throws Exception { - startBroker(true); - } + private void startCleanBroker() throws Exception { + startBroker(true); + } - public void startBroker(boolean deleteAllMessagesOnStartup) throws Exception { - broker = createBroker(deleteAllMessagesOnStartup); - broker.start(); - } + public void startBroker(boolean deleteAllMessagesOnStartup) throws Exception { + broker = createBroker(deleteAllMessagesOnStartup); + broker.start(); + } - public void startBroker(boolean deleteAllMessagesOnStartup, String bindAddress) throws Exception { - broker = createBroker(deleteAllMessagesOnStartup, bindAddress); - broker.start(); - } + public void startBroker(boolean deleteAllMessagesOnStartup, String bindAddress) throws Exception { + broker = createBroker(deleteAllMessagesOnStartup, bindAddress); + broker.start(); + } - public BrokerService createBroker(boolean deleteAllMessagesOnStartup) throws Exception { - return createBroker(deleteAllMessagesOnStartup, TRANSPORT_URI); - } + public BrokerService createBroker(boolean deleteAllMessagesOnStartup) throws Exception { + return createBroker(deleteAllMessagesOnStartup, TRANSPORT_URI); + } - public BrokerService createBroker(boolean deleteAllMessagesOnStartup, String bindAddress) throws Exception { - broker = new BrokerService(); - broker.setUseJmx(false); - broker.setAdvisorySupport(false); - broker.addConnector(bindAddress); - broker.setDeleteAllMessagesOnStartup(deleteAllMessagesOnStartup); + public BrokerService createBroker(boolean deleteAllMessagesOnStartup, String bindAddress) throws Exception { + broker = new BrokerService(); + broker.setUseJmx(false); + broker.setAdvisorySupport(false); + broker.addConnector(bindAddress); + broker.setDeleteAllMessagesOnStartup(deleteAllMessagesOnStartup); - url = broker.getTransportConnectors().get(0).getConnectUri().toString(); + url = broker.getTransportConnectors().get(0).getConnectUri().toString(); - return broker; - } + return broker; + } - public void configureConnectionFactory(ActiveMQConnectionFactory factory) { - // nothing to do - } + public void configureConnectionFactory(ActiveMQConnectionFactory factory) { + // nothing to do + } - public void testFailoverProducerCloseBeforeTransaction() throws Exception { - startCleanBroker(); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); - configureConnectionFactory(cf); - Connection connection = cf.createConnection(); - connection.start(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - Queue destination = session.createQueue(QUEUE_NAME); + public void testFailoverProducerCloseBeforeTransaction() throws Exception { + startCleanBroker(); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); + configureConnectionFactory(cf); + Connection connection = cf.createConnection(); + connection.start(); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + Queue destination = session.createQueue(QUEUE_NAME); - MessageConsumer consumer = session.createConsumer(destination); - produceMessage(session, destination); + MessageConsumer consumer = session.createConsumer(destination); + produceMessage(session, destination); - // restart to force failover and connection state recovery before the commit - broker.stop(); - startBroker(false, url); + // restart to force failover and connection state recovery before the commit + broker.stop(); + startBroker(false, url); - session.commit(); - assertNotNull("we got the message", consumer.receive(20000)); - session.commit(); - connection.close(); - } + session.commit(); + assertNotNull("we got the message", consumer.receive(20000)); + session.commit(); + connection.close(); + } - public void initCombosForTestFailoverCommitReplyLost() { - String osName = System.getProperty("os.name"); - Object[] persistenceAdapters; - if (!osName.equalsIgnoreCase("AIX") && !osName.equalsIgnoreCase("SunOS")) { - persistenceAdapters = new Object[]{PersistenceAdapterChoice.KahaDB, PersistenceAdapterChoice.LevelDB, PersistenceAdapterChoice.JDBC}; - } else { - persistenceAdapters = new Object[]{PersistenceAdapterChoice.KahaDB, PersistenceAdapterChoice.JDBC}; - } - addCombinationValues("defaultPersistenceAdapter",persistenceAdapters); - } + public void initCombosForTestFailoverCommitReplyLost() { + String osName = System.getProperty("os.name"); + Object[] persistenceAdapters; + if (!osName.equalsIgnoreCase("AIX") && !osName.equalsIgnoreCase("SunOS")) { + persistenceAdapters = new Object[]{PersistenceAdapterChoice.KahaDB, PersistenceAdapterChoice.LevelDB, PersistenceAdapterChoice.JDBC}; + } + else { + persistenceAdapters = new Object[]{PersistenceAdapterChoice.KahaDB, PersistenceAdapterChoice.JDBC}; + } + addCombinationValues("defaultPersistenceAdapter", persistenceAdapters); + } - @SuppressWarnings("unchecked") - public void testFailoverCommitReplyLost() throws Exception { + @SuppressWarnings("unchecked") + public void testFailoverCommitReplyLost() throws Exception { - broker = createBroker(true); - setDefaultPersistenceAdapter(broker); + broker = createBroker(true); + setDefaultPersistenceAdapter(broker); - broker.setPlugins(new BrokerPlugin[]{ - new BrokerPluginSupport() { - @Override - public void commitTransaction(ConnectionContext context, - TransactionId xid, boolean onePhase) throws Exception { - super.commitTransaction(context, xid, onePhase); - // so commit will hang as if reply is lost - context.setDontSendReponse(true); - Executors.newSingleThreadExecutor().execute(new Runnable() { - public void run() { - LOG.info("Stopping broker post commit..."); - try { - broker.stop(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - } - } - }); - broker.start(); - - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); - configureConnectionFactory(cf); - Connection connection = cf.createConnection(); - connection.start(); - final Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - Queue destination = session.createQueue(QUEUE_NAME); - - MessageConsumer consumer = session.createConsumer(destination); - produceMessage(session, destination); - - final CountDownLatch commitDoneLatch = new CountDownLatch(1); - // broker will die on commit reply so this will hang till restart - Executors.newSingleThreadExecutor().execute(new Runnable() { - public void run() { - LOG.info("doing async commit..."); - try { - session.commit(); - } catch (JMSException e) { - assertTrue(e instanceof TransactionRolledBackException); - LOG.info("got commit exception: ", e); - } - commitDoneLatch.countDown(); - LOG.info("done async commit"); - } - }); - - // will be stopped by the plugin - broker.waitUntilStopped(); - broker = createBroker(false, url); - setDefaultPersistenceAdapter(broker); - broker.start(); - - assertTrue("tx committed through failover", commitDoneLatch.await(30, TimeUnit.SECONDS)); - - // new transaction - Message msg = consumer.receive(20000); - LOG.info("Received: " + msg); - assertNotNull("we got the message", msg); - assertNull("we got just one message", consumer.receive(2000)); - session.commit(); - consumer.close(); - connection.close(); - - // ensure no dangling messages with fresh broker etc - broker.stop(); - broker.waitUntilStopped(); - - LOG.info("Checking for remaining/hung messages.."); - broker = createBroker(false, url); - setDefaultPersistenceAdapter(broker); - broker.start(); - - // after restart, ensure no dangling messages - cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); - configureConnectionFactory(cf); - connection = cf.createConnection(); - connection.start(); - Session session2 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = session2.createConsumer(destination); - msg = consumer.receive(1000); - if (msg == null) { - msg = consumer.receive(5000); - } - LOG.info("Received: " + msg); - assertNull("no messges left dangling but got: " + msg, msg); - connection.close(); - } - - @SuppressWarnings("unchecked") - public void testFailoverCommitReplyLostWithDestinationPathSeparator() throws Exception { - - broker = createBroker(true); - setDefaultPersistenceAdapter(broker); - - broker.setPlugins(new BrokerPlugin[]{ - new DestinationPathSeparatorBroker(), - new BrokerPluginSupport() { - @Override - public void commitTransaction(ConnectionContext context, - TransactionId xid, boolean onePhase) throws Exception { - super.commitTransaction(context, xid, onePhase); - // so commit will hang as if reply is lost - context.setDontSendReponse(true); - Executors.newSingleThreadExecutor().execute(new Runnable() { - public void run() { - LOG.info("Stopping broker post commit..."); - try { - broker.stop(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - } - } - }); - broker.start(); - - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); - configureConnectionFactory(cf); - Connection connection = cf.createConnection(); - connection.start(); - final Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - Queue destination = session.createQueue(QUEUE_NAME.replace('.','/') + "?consumer.prefetchSize=0"); - - MessageConsumer consumer = session.createConsumer(destination); - produceMessage(session, destination); - - final CountDownLatch commitDoneLatch = new CountDownLatch(1); - // broker will die on commit reply so this will hang till restart - Executors.newSingleThreadExecutor().execute(new Runnable() { - public void run() { - LOG.info("doing async commit..."); - try { - session.commit(); - } catch (JMSException e) { - assertTrue(e instanceof TransactionRolledBackException); - LOG.info("got commit exception: ", e); - } - commitDoneLatch.countDown(); - LOG.info("done async commit"); - } - }); - - // will be stopped by the plugin - broker.waitUntilStopped(); - broker = createBroker(false, url); - setDefaultPersistenceAdapter(broker); - broker.setPlugins(new BrokerPlugin[]{new DestinationPathSeparatorBroker()}); - broker.start(); - - assertTrue("tx committed trough failover", commitDoneLatch.await(30, TimeUnit.SECONDS)); - - // new transaction - Message msg = consumer.receive(20000); - LOG.info("Received: " + msg); - assertNotNull("we got the message", msg); - assertNull("we got just one message", consumer.receive(2000)); - session.commit(); - consumer.close(); - connection.close(); - - // ensure no dangling messages with fresh broker etc - broker.stop(); - broker.waitUntilStopped(); - - LOG.info("Checking for remaining/hung messages.."); - broker = createBroker(false, url); - setDefaultPersistenceAdapter(broker); - broker.setPlugins(new BrokerPlugin[]{new DestinationPathSeparatorBroker()}); - broker.start(); - - // after restart, ensure no dangling messages - cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); - configureConnectionFactory(cf); - connection = cf.createConnection(); - connection.start(); - Session session2 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = session2.createConsumer(destination); - msg = consumer.receive(1000); - if (msg == null) { - msg = consumer.receive(5000); - } - LOG.info("Received: " + msg); - assertNull("no messges left dangling but got: " + msg, msg); - connection.close(); - - ActiveMQDestination[] destinations = broker.getRegionBroker().getDestinations(); - for (ActiveMQDestination dest : destinations) { - LOG.info("Destinations list: " + dest); - } - assertEquals("Only one destination", 1, broker.getRegionBroker().getDestinations().length); - } - - public void initCombosForTestFailoverSendReplyLost() { - addCombinationValues("defaultPersistenceAdapter", - new Object[]{PersistenceAdapterChoice.KahaDB, - PersistenceAdapterChoice.JDBC - // not implemented for AMQ store or PersistenceAdapterChoice.LevelDB + broker.setPlugins(new BrokerPlugin[]{new BrokerPluginSupport() { + @Override + public void commitTransaction(ConnectionContext context, + TransactionId xid, + boolean onePhase) throws Exception { + super.commitTransaction(context, xid, onePhase); + // so commit will hang as if reply is lost + context.setDontSendReponse(true); + Executors.newSingleThreadExecutor().execute(new Runnable() { + public void run() { + LOG.info("Stopping broker post commit..."); + try { + broker.stop(); + } + catch (Exception e) { + e.printStackTrace(); + } + } }); - } + } + }}); + broker.start(); - @SuppressWarnings("unchecked") - public void testFailoverSendReplyLost() throws Exception { + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); + configureConnectionFactory(cf); + Connection connection = cf.createConnection(); + connection.start(); + final Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + Queue destination = session.createQueue(QUEUE_NAME); - broker = createBroker(true); - setDefaultPersistenceAdapter(broker); + MessageConsumer consumer = session.createConsumer(destination); + produceMessage(session, destination); - broker.setPlugins(new BrokerPlugin[]{ - new BrokerPluginSupport() { - @Override - public void send(ProducerBrokerExchange producerExchange, - org.apache.activemq.command.Message messageSend) - throws Exception { - // so send will hang as if reply is lost - super.send(producerExchange, messageSend); - producerExchange.getConnectionContext().setDontSendReponse(true); - Executors.newSingleThreadExecutor().execute(new Runnable() { - public void run() { - LOG.info("Stopping broker post send..."); - try { - broker.stop(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - } - } - }); - broker.start(); - - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")?jms.watchTopicAdvisories=false"); - configureConnectionFactory(cf); - Connection connection = cf.createConnection(); - connection.start(); - final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final Queue destination = session.createQueue(QUEUE_NAME); - - MessageConsumer consumer = session.createConsumer(destination); - final CountDownLatch sendDoneLatch = new CountDownLatch(1); - // broker will die on send reply so this will hang till restart - Executors.newSingleThreadExecutor().execute(new Runnable() { - public void run() { - LOG.info("doing async send..."); - try { - produceMessage(session, destination); - } catch (JMSException e) { - //assertTrue(e instanceof TransactionRolledBackException); - LOG.error("got send exception: ", e); - fail("got unexpected send exception" + e); - } - sendDoneLatch.countDown(); - LOG.info("done async send"); - } - }); - - // will be stopped by the plugin - broker.waitUntilStopped(); - broker = createBroker(false, url); - setDefaultPersistenceAdapter(broker); - LOG.info("restarting...."); - broker.start(); - - assertTrue("message sent through failover", sendDoneLatch.await(30, TimeUnit.SECONDS)); - - // new transaction - Message msg = consumer.receive(20000); - LOG.info("Received: " + msg); - assertNotNull("we got the message", msg); - assertNull("we got just one message", consumer.receive(2000)); - consumer.close(); - connection.close(); - - // verify stats - assertEquals("no newly queued messages", 0, ((RegionBroker) broker.getRegionBroker()).getDestinationStatistics().getEnqueues().getCount()); - assertEquals("1 dequeue", 1, ((RegionBroker) broker.getRegionBroker()).getDestinationStatistics().getDequeues().getCount()); - - // ensure no dangling messages with fresh broker etc - broker.stop(); - broker.waitUntilStopped(); - - LOG.info("Checking for remaining/hung messages with second restart.."); - broker = createBroker(false, url); - setDefaultPersistenceAdapter(broker); - broker.start(); - - // after restart, ensure no dangling messages - cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); - configureConnectionFactory(cf); - connection = cf.createConnection(); - connection.start(); - Session session2 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = session2.createConsumer(destination); - msg = consumer.receive(1000); - if (msg == null) { - msg = consumer.receive(5000); - } - LOG.info("Received: " + msg); - assertNull("no messges left dangling but got: " + msg, msg); - connection.close(); - } - - public void initCombosForTestFailoverConnectionSendReplyLost() { - addCombinationValues("defaultPersistenceAdapter", - new Object[]{PersistenceAdapterChoice.KahaDB, - PersistenceAdapterChoice.JDBC - // last producer message id store feature not implemented for AMQ store - // or PersistenceAdapterChoice.LevelDB - }); - } - - @SuppressWarnings("unchecked") - public void testFailoverConnectionSendReplyLost() throws Exception { - - broker = createBroker(true); - PersistenceAdapter store = setDefaultPersistenceAdapter(broker); - if (store instanceof KahaDBPersistenceAdapter) { - // duplicate checker not updated on canceled tasks, even it - // it was, recovery of the audit would fail as the message is - // not recorded in the store and the audit may not be up to date. - // So if duplicate messages are an absolute no no after restarts, - // ConcurrentStoreAndDispatchQueues must be disabled - ((KahaDBPersistenceAdapter) store).setConcurrentStoreAndDispatchQueues(false); - } - - final SocketProxy proxy = new SocketProxy(); - - broker.setPlugins(new BrokerPlugin[]{ - new BrokerPluginSupport() { - private boolean firstSend = true; - - @Override - public void send(ProducerBrokerExchange producerExchange, - org.apache.activemq.command.Message messageSend) - throws Exception { - // so send will hang as if reply is lost - super.send(producerExchange, messageSend); - if (firstSend) { - firstSend = false; - - producerExchange.getConnectionContext().setDontSendReponse(true); - Executors.newSingleThreadExecutor().execute(new Runnable() { - public void run() { - LOG.info("Stopping connection post send..."); - try { - proxy.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - } - } - } - }); - broker.start(); - - proxy.setTarget(new URI(url)); - proxy.open(); - - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + proxy.getUrl().toASCIIString() + ")?jms.watchTopicAdvisories=false"); - configureConnectionFactory(cf); - Connection connection = cf.createConnection(); - connection.start(); - final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final Queue destination = session.createQueue(QUEUE_NAME); - - MessageConsumer consumer = session.createConsumer(destination); - final CountDownLatch sendDoneLatch = new CountDownLatch(1); - // proxy connection will die on send reply so this will hang on failover reconnect till open - Executors.newSingleThreadExecutor().execute(new Runnable() { - public void run() { - LOG.info("doing async send..."); - try { - produceMessage(session, destination); - } catch (JMSException e) { - //assertTrue(e instanceof TransactionRolledBackException); - LOG.info("got send exception: ", e); - } - sendDoneLatch.countDown(); - LOG.info("done async send"); - } - }); - - // will be closed by the plugin - assertTrue("proxy was closed", proxy.waitUntilClosed(30)); - LOG.info("restarting proxy"); - proxy.open(); - - assertTrue("message sent through failover", sendDoneLatch.await(30, TimeUnit.SECONDS)); - - Message msg = consumer.receive(20000); - LOG.info("Received: " + msg); - assertNotNull("we got the message", msg); - assertNull("we got just one message", consumer.receive(2000)); - consumer.close(); - connection.close(); - - // verify stats, connection dup suppression means dups don't get to broker - assertEquals("one queued message", 1, ((RegionBroker) broker.getRegionBroker()).getDestinationStatistics().getEnqueues().getCount()); - - // ensure no dangling messages with fresh broker etc - broker.stop(); - broker.waitUntilStopped(); - - LOG.info("Checking for remaining/hung messages with restart.."); - broker = createBroker(false, url); - setDefaultPersistenceAdapter(broker); - broker.start(); - - // after restart, ensure no dangling messages - cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); - configureConnectionFactory(cf); - connection = cf.createConnection(); - connection.start(); - Session session2 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = session2.createConsumer(destination); - msg = consumer.receive(1000); - if (msg == null) { - msg = consumer.receive(5000); - } - LOG.info("Received: " + msg); - assertNull("no messges left dangling but got: " + msg, msg); - connection.close(); - } - - public void testFailoverProducerCloseBeforeTransactionFailWhenDisabled() throws Exception { - startCleanBroker(); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")?trackTransactionProducers=false"); - configureConnectionFactory(cf); - Connection connection = cf.createConnection(); - connection.start(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - Queue destination = session.createQueue(QUEUE_NAME); - - MessageConsumer consumer = session.createConsumer(destination); - produceMessage(session, destination); - - // restart to force failover and connection state recovery before the commit - broker.stop(); - startBroker(false, url); - - session.commit(); - - // without tracking producers, message will not be replayed on recovery - assertNull("we got the message", consumer.receive(5000)); - session.commit(); - connection.close(); - } - - public void testFailoverMultipleProducerCloseBeforeTransaction() throws Exception { - startCleanBroker(); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); - configureConnectionFactory(cf); - Connection connection = cf.createConnection(); - connection.start(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - Queue destination = session.createQueue(QUEUE_NAME); - - MessageConsumer consumer = session.createConsumer(destination); - MessageProducer producer; - TextMessage message; - final int count = 10; - for (int i = 0; i < count; i++) { - producer = session.createProducer(destination); - message = session.createTextMessage("Test message: " + count); - producer.send(message); - producer.close(); - } - - // restart to force failover and connection state recovery before the commit - broker.stop(); - startBroker(false, url); - - session.commit(); - for (int i = 0; i < count; i++) { - assertNotNull("we got all the message: " + count, consumer.receive(20000)); - } - session.commit(); - connection.close(); - } - - // https://issues.apache.org/activemq/browse/AMQ-2772 - public void testFailoverWithConnectionConsumer() throws Exception { - startCleanBroker(); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); - configureConnectionFactory(cf); - Connection connection = cf.createConnection(); - connection.start(); - - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - Queue destination = session.createQueue(QUEUE_NAME); - - final CountDownLatch connectionConsumerGotOne = new CountDownLatch(1); - final Session poolSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - connection.createConnectionConsumer(destination, null, new ServerSessionPool() { - public ServerSession getServerSession() throws JMSException { - return new ServerSession() { - public Session getSession() throws JMSException { - return poolSession; - } - - public void start() throws JMSException { - connectionConsumerGotOne.countDown(); - poolSession.run(); - } - }; - } - }, 1); - - MessageConsumer consumer = session.createConsumer(destination); - MessageProducer producer; - TextMessage message; - final int count = 10; - for (int i = 0; i < count; i++) { - producer = session.createProducer(destination); - message = session.createTextMessage("Test message: " + count); - producer.send(message); - producer.close(); - } - - // restart to force failover and connection state recovery before the commit - broker.stop(); - startBroker(false, url); - - session.commit(); - for (int i = 0; i < count - 1; i++) { - assertNotNull("Failed to get message: " + count, consumer.receive(20000)); - } - session.commit(); - connection.close(); - - assertTrue("connectionconsumer did not get a message", connectionConsumerGotOne.await(10, TimeUnit.SECONDS)); - } - - public void testFailoverConsumerAckLost() throws Exception { - // as failure depends on hash order of state tracker recovery, do a few times - for (int i = 0; i < 3; i++) { + final CountDownLatch commitDoneLatch = new CountDownLatch(1); + // broker will die on commit reply so this will hang till restart + Executors.newSingleThreadExecutor().execute(new Runnable() { + public void run() { + LOG.info("doing async commit..."); try { - LOG.info("Iteration: " + i); - doTestFailoverConsumerAckLost(i); - } finally { - stopBroker(); + session.commit(); } - } - } + catch (JMSException e) { + assertTrue(e instanceof TransactionRolledBackException); + LOG.info("got commit exception: ", e); + } + commitDoneLatch.countDown(); + LOG.info("done async commit"); + } + }); - @SuppressWarnings("unchecked") - public void doTestFailoverConsumerAckLost(final int pauseSeconds) throws Exception { - broker = createBroker(true); - setDefaultPersistenceAdapter(broker); + // will be stopped by the plugin + broker.waitUntilStopped(); + broker = createBroker(false, url); + setDefaultPersistenceAdapter(broker); + broker.start(); - broker.setPlugins(new BrokerPlugin[]{ - new BrokerPluginSupport() { + assertTrue("tx committed through failover", commitDoneLatch.await(30, TimeUnit.SECONDS)); - // broker is killed on delivered ack as prefetch is 1 - @Override - public void acknowledge( - ConsumerBrokerExchange consumerExchange, - final MessageAck ack) throws Exception { + // new transaction + Message msg = consumer.receive(20000); + LOG.info("Received: " + msg); + assertNotNull("we got the message", msg); + assertNull("we got just one message", consumer.receive(2000)); + session.commit(); + consumer.close(); + connection.close(); - consumerExchange.getConnectionContext().setDontSendReponse(true); - Executors.newSingleThreadExecutor().execute(new Runnable() { - public void run() { - LOG.info("Stopping broker on ack: " + ack); - try { - broker.stop(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - } - } - }); - broker.start(); + // ensure no dangling messages with fresh broker etc + broker.stop(); + broker.waitUntilStopped(); - Vector connections = new Vector(); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); - configureConnectionFactory(cf); - Connection connection = cf.createConnection(); - connection.start(); - connections.add(connection); - final Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final Queue destination = producerSession.createQueue(QUEUE_NAME + "?consumer.prefetchSize=1"); + LOG.info("Checking for remaining/hung messages.."); + broker = createBroker(false, url); + setDefaultPersistenceAdapter(broker); + broker.start(); - connection = cf.createConnection(); - connection.start(); - connections.add(connection); - final Session consumerSession1 = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + // after restart, ensure no dangling messages + cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); + configureConnectionFactory(cf); + connection = cf.createConnection(); + connection.start(); + Session session2 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumer = session2.createConsumer(destination); + msg = consumer.receive(1000); + if (msg == null) { + msg = consumer.receive(5000); + } + LOG.info("Received: " + msg); + assertNull("no messges left dangling but got: " + msg, msg); + connection.close(); + } - connection = cf.createConnection(); - connection.start(); - connections.add(connection); - final Session consumerSession2 = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + @SuppressWarnings("unchecked") + public void testFailoverCommitReplyLostWithDestinationPathSeparator() throws Exception { - final MessageConsumer consumer1 = consumerSession1.createConsumer(destination); - final MessageConsumer consumer2 = consumerSession2.createConsumer(destination); + broker = createBroker(true); + setDefaultPersistenceAdapter(broker); - produceMessage(producerSession, destination); - produceMessage(producerSession, destination); + broker.setPlugins(new BrokerPlugin[]{new DestinationPathSeparatorBroker(), new BrokerPluginSupport() { + @Override + public void commitTransaction(ConnectionContext context, + TransactionId xid, + boolean onePhase) throws Exception { + super.commitTransaction(context, xid, onePhase); + // so commit will hang as if reply is lost + context.setDontSendReponse(true); + Executors.newSingleThreadExecutor().execute(new Runnable() { + public void run() { + LOG.info("Stopping broker post commit..."); + try { + broker.stop(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + }); + } + }}); + broker.start(); - final Vector receivedMessages = new Vector(); - final CountDownLatch commitDoneLatch = new CountDownLatch(1); - final AtomicBoolean gotTransactionRolledBackException = new AtomicBoolean(false); - Executors.newSingleThreadExecutor().execute(new Runnable() { - public void run() { - LOG.info("doing async commit after consume..."); - try { - Message msg = consumer1.receive(20000); - LOG.info("consumer1 first attempt got message: " + msg); - receivedMessages.add(msg); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); + configureConnectionFactory(cf); + Connection connection = cf.createConnection(); + connection.start(); + final Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + Queue destination = session.createQueue(QUEUE_NAME.replace('.', '/') + "?consumer.prefetchSize=0"); - // give some variance to the runs - TimeUnit.SECONDS.sleep(pauseSeconds * 2); + MessageConsumer consumer = session.createConsumer(destination); + produceMessage(session, destination); - // should not get a second message as there are two messages and two consumers - // and prefetch=1, but with failover and unordered connection restore it can get the second - // message. + final CountDownLatch commitDoneLatch = new CountDownLatch(1); + // broker will die on commit reply so this will hang till restart + Executors.newSingleThreadExecutor().execute(new Runnable() { + public void run() { + LOG.info("doing async commit..."); + try { + session.commit(); + } + catch (JMSException e) { + assertTrue(e instanceof TransactionRolledBackException); + LOG.info("got commit exception: ", e); + } + commitDoneLatch.countDown(); + LOG.info("done async commit"); + } + }); - // For the transaction to complete it needs to get the same one or two messages - // again so that the acks line up. - // If redelivery order is different, the commit should fail with an ex - // - msg = consumer1.receive(5000); - LOG.info("consumer1 second attempt got message: " + msg); - if (msg != null) { - receivedMessages.add(msg); - } + // will be stopped by the plugin + broker.waitUntilStopped(); + broker = createBroker(false, url); + setDefaultPersistenceAdapter(broker); + broker.setPlugins(new BrokerPlugin[]{new DestinationPathSeparatorBroker()}); + broker.start(); - LOG.info("committing consumer1 session: " + receivedMessages.size() + " messsage(s)"); - try { - consumerSession1.commit(); - } catch (JMSException expectedSometimes) { - LOG.info("got exception ex on commit", expectedSometimes); - if (expectedSometimes instanceof TransactionRolledBackException) { - gotTransactionRolledBackException.set(true); - // ok, message one was not replayed so we expect the rollback - } else { - throw expectedSometimes; + assertTrue("tx committed trough failover", commitDoneLatch.await(30, TimeUnit.SECONDS)); + + // new transaction + Message msg = consumer.receive(20000); + LOG.info("Received: " + msg); + assertNotNull("we got the message", msg); + assertNull("we got just one message", consumer.receive(2000)); + session.commit(); + consumer.close(); + connection.close(); + + // ensure no dangling messages with fresh broker etc + broker.stop(); + broker.waitUntilStopped(); + + LOG.info("Checking for remaining/hung messages.."); + broker = createBroker(false, url); + setDefaultPersistenceAdapter(broker); + broker.setPlugins(new BrokerPlugin[]{new DestinationPathSeparatorBroker()}); + broker.start(); + + // after restart, ensure no dangling messages + cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); + configureConnectionFactory(cf); + connection = cf.createConnection(); + connection.start(); + Session session2 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumer = session2.createConsumer(destination); + msg = consumer.receive(1000); + if (msg == null) { + msg = consumer.receive(5000); + } + LOG.info("Received: " + msg); + assertNull("no messges left dangling but got: " + msg, msg); + connection.close(); + + ActiveMQDestination[] destinations = broker.getRegionBroker().getDestinations(); + for (ActiveMQDestination dest : destinations) { + LOG.info("Destinations list: " + dest); + } + assertEquals("Only one destination", 1, broker.getRegionBroker().getDestinations().length); + } + + public void initCombosForTestFailoverSendReplyLost() { + addCombinationValues("defaultPersistenceAdapter", new Object[]{PersistenceAdapterChoice.KahaDB, PersistenceAdapterChoice.JDBC + // not implemented for AMQ store or PersistenceAdapterChoice.LevelDB + }); + } + + @SuppressWarnings("unchecked") + public void testFailoverSendReplyLost() throws Exception { + + broker = createBroker(true); + setDefaultPersistenceAdapter(broker); + + broker.setPlugins(new BrokerPlugin[]{new BrokerPluginSupport() { + @Override + public void send(ProducerBrokerExchange producerExchange, + org.apache.activemq.command.Message messageSend) throws Exception { + // so send will hang as if reply is lost + super.send(producerExchange, messageSend); + producerExchange.getConnectionContext().setDontSendReponse(true); + Executors.newSingleThreadExecutor().execute(new Runnable() { + public void run() { + LOG.info("Stopping broker post send..."); + try { + broker.stop(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + }); + } + }}); + broker.start(); + + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")?jms.watchTopicAdvisories=false"); + configureConnectionFactory(cf); + Connection connection = cf.createConnection(); + connection.start(); + final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final Queue destination = session.createQueue(QUEUE_NAME); + + MessageConsumer consumer = session.createConsumer(destination); + final CountDownLatch sendDoneLatch = new CountDownLatch(1); + // broker will die on send reply so this will hang till restart + Executors.newSingleThreadExecutor().execute(new Runnable() { + public void run() { + LOG.info("doing async send..."); + try { + produceMessage(session, destination); + } + catch (JMSException e) { + //assertTrue(e instanceof TransactionRolledBackException); + LOG.error("got send exception: ", e); + fail("got unexpected send exception" + e); + } + sendDoneLatch.countDown(); + LOG.info("done async send"); + } + }); + + // will be stopped by the plugin + broker.waitUntilStopped(); + broker = createBroker(false, url); + setDefaultPersistenceAdapter(broker); + LOG.info("restarting...."); + broker.start(); + + assertTrue("message sent through failover", sendDoneLatch.await(30, TimeUnit.SECONDS)); + + // new transaction + Message msg = consumer.receive(20000); + LOG.info("Received: " + msg); + assertNotNull("we got the message", msg); + assertNull("we got just one message", consumer.receive(2000)); + consumer.close(); + connection.close(); + + // verify stats + assertEquals("no newly queued messages", 0, ((RegionBroker) broker.getRegionBroker()).getDestinationStatistics().getEnqueues().getCount()); + assertEquals("1 dequeue", 1, ((RegionBroker) broker.getRegionBroker()).getDestinationStatistics().getDequeues().getCount()); + + // ensure no dangling messages with fresh broker etc + broker.stop(); + broker.waitUntilStopped(); + + LOG.info("Checking for remaining/hung messages with second restart.."); + broker = createBroker(false, url); + setDefaultPersistenceAdapter(broker); + broker.start(); + + // after restart, ensure no dangling messages + cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); + configureConnectionFactory(cf); + connection = cf.createConnection(); + connection.start(); + Session session2 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumer = session2.createConsumer(destination); + msg = consumer.receive(1000); + if (msg == null) { + msg = consumer.receive(5000); + } + LOG.info("Received: " + msg); + assertNull("no messges left dangling but got: " + msg, msg); + connection.close(); + } + + public void initCombosForTestFailoverConnectionSendReplyLost() { + addCombinationValues("defaultPersistenceAdapter", new Object[]{PersistenceAdapterChoice.KahaDB, PersistenceAdapterChoice.JDBC + // last producer message id store feature not implemented for AMQ store + // or PersistenceAdapterChoice.LevelDB + }); + } + + @SuppressWarnings("unchecked") + public void testFailoverConnectionSendReplyLost() throws Exception { + + broker = createBroker(true); + PersistenceAdapter store = setDefaultPersistenceAdapter(broker); + if (store instanceof KahaDBPersistenceAdapter) { + // duplicate checker not updated on canceled tasks, even it + // it was, recovery of the audit would fail as the message is + // not recorded in the store and the audit may not be up to date. + // So if duplicate messages are an absolute no no after restarts, + // ConcurrentStoreAndDispatchQueues must be disabled + ((KahaDBPersistenceAdapter) store).setConcurrentStoreAndDispatchQueues(false); + } + + final SocketProxy proxy = new SocketProxy(); + + broker.setPlugins(new BrokerPlugin[]{new BrokerPluginSupport() { + private boolean firstSend = true; + + @Override + public void send(ProducerBrokerExchange producerExchange, + org.apache.activemq.command.Message messageSend) throws Exception { + // so send will hang as if reply is lost + super.send(producerExchange, messageSend); + if (firstSend) { + firstSend = false; + + producerExchange.getConnectionContext().setDontSendReponse(true); + Executors.newSingleThreadExecutor().execute(new Runnable() { + public void run() { + LOG.info("Stopping connection post send..."); + try { + proxy.close(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + }); + } + } + }}); + broker.start(); + + proxy.setTarget(new URI(url)); + proxy.open(); + + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + proxy.getUrl().toASCIIString() + ")?jms.watchTopicAdvisories=false"); + configureConnectionFactory(cf); + Connection connection = cf.createConnection(); + connection.start(); + final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final Queue destination = session.createQueue(QUEUE_NAME); + + MessageConsumer consumer = session.createConsumer(destination); + final CountDownLatch sendDoneLatch = new CountDownLatch(1); + // proxy connection will die on send reply so this will hang on failover reconnect till open + Executors.newSingleThreadExecutor().execute(new Runnable() { + public void run() { + LOG.info("doing async send..."); + try { + produceMessage(session, destination); + } + catch (JMSException e) { + //assertTrue(e instanceof TransactionRolledBackException); + LOG.info("got send exception: ", e); + } + sendDoneLatch.countDown(); + LOG.info("done async send"); + } + }); + + // will be closed by the plugin + assertTrue("proxy was closed", proxy.waitUntilClosed(30)); + LOG.info("restarting proxy"); + proxy.open(); + + assertTrue("message sent through failover", sendDoneLatch.await(30, TimeUnit.SECONDS)); + + Message msg = consumer.receive(20000); + LOG.info("Received: " + msg); + assertNotNull("we got the message", msg); + assertNull("we got just one message", consumer.receive(2000)); + consumer.close(); + connection.close(); + + // verify stats, connection dup suppression means dups don't get to broker + assertEquals("one queued message", 1, ((RegionBroker) broker.getRegionBroker()).getDestinationStatistics().getEnqueues().getCount()); + + // ensure no dangling messages with fresh broker etc + broker.stop(); + broker.waitUntilStopped(); + + LOG.info("Checking for remaining/hung messages with restart.."); + broker = createBroker(false, url); + setDefaultPersistenceAdapter(broker); + broker.start(); + + // after restart, ensure no dangling messages + cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); + configureConnectionFactory(cf); + connection = cf.createConnection(); + connection.start(); + Session session2 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumer = session2.createConsumer(destination); + msg = consumer.receive(1000); + if (msg == null) { + msg = consumer.receive(5000); + } + LOG.info("Received: " + msg); + assertNull("no messges left dangling but got: " + msg, msg); + connection.close(); + } + + public void testFailoverProducerCloseBeforeTransactionFailWhenDisabled() throws Exception { + startCleanBroker(); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")?trackTransactionProducers=false"); + configureConnectionFactory(cf); + Connection connection = cf.createConnection(); + connection.start(); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + Queue destination = session.createQueue(QUEUE_NAME); + + MessageConsumer consumer = session.createConsumer(destination); + produceMessage(session, destination); + + // restart to force failover and connection state recovery before the commit + broker.stop(); + startBroker(false, url); + + session.commit(); + + // without tracking producers, message will not be replayed on recovery + assertNull("we got the message", consumer.receive(5000)); + session.commit(); + connection.close(); + } + + public void testFailoverMultipleProducerCloseBeforeTransaction() throws Exception { + startCleanBroker(); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); + configureConnectionFactory(cf); + Connection connection = cf.createConnection(); + connection.start(); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + Queue destination = session.createQueue(QUEUE_NAME); + + MessageConsumer consumer = session.createConsumer(destination); + MessageProducer producer; + TextMessage message; + final int count = 10; + for (int i = 0; i < count; i++) { + producer = session.createProducer(destination); + message = session.createTextMessage("Test message: " + count); + producer.send(message); + producer.close(); + } + + // restart to force failover and connection state recovery before the commit + broker.stop(); + startBroker(false, url); + + session.commit(); + for (int i = 0; i < count; i++) { + assertNotNull("we got all the message: " + count, consumer.receive(20000)); + } + session.commit(); + connection.close(); + } + + // https://issues.apache.org/activemq/browse/AMQ-2772 + public void testFailoverWithConnectionConsumer() throws Exception { + startCleanBroker(); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); + configureConnectionFactory(cf); + Connection connection = cf.createConnection(); + connection.start(); + + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + Queue destination = session.createQueue(QUEUE_NAME); + + final CountDownLatch connectionConsumerGotOne = new CountDownLatch(1); + final Session poolSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + connection.createConnectionConsumer(destination, null, new ServerSessionPool() { + public ServerSession getServerSession() throws JMSException { + return new ServerSession() { + public Session getSession() throws JMSException { + return poolSession; + } + + public void start() throws JMSException { + connectionConsumerGotOne.countDown(); + poolSession.run(); + } + }; + } + }, 1); + + MessageConsumer consumer = session.createConsumer(destination); + MessageProducer producer; + TextMessage message; + final int count = 10; + for (int i = 0; i < count; i++) { + producer = session.createProducer(destination); + message = session.createTextMessage("Test message: " + count); + producer.send(message); + producer.close(); + } + + // restart to force failover and connection state recovery before the commit + broker.stop(); + startBroker(false, url); + + session.commit(); + for (int i = 0; i < count - 1; i++) { + assertNotNull("Failed to get message: " + count, consumer.receive(20000)); + } + session.commit(); + connection.close(); + + assertTrue("connectionconsumer did not get a message", connectionConsumerGotOne.await(10, TimeUnit.SECONDS)); + } + + public void testFailoverConsumerAckLost() throws Exception { + // as failure depends on hash order of state tracker recovery, do a few times + for (int i = 0; i < 3; i++) { + try { + LOG.info("Iteration: " + i); + doTestFailoverConsumerAckLost(i); + } + finally { + stopBroker(); + } + } + } + + @SuppressWarnings("unchecked") + public void doTestFailoverConsumerAckLost(final int pauseSeconds) throws Exception { + broker = createBroker(true); + setDefaultPersistenceAdapter(broker); + + broker.setPlugins(new BrokerPlugin[]{new BrokerPluginSupport() { + + // broker is killed on delivered ack as prefetch is 1 + @Override + public void acknowledge(ConsumerBrokerExchange consumerExchange, final MessageAck ack) throws Exception { + + consumerExchange.getConnectionContext().setDontSendReponse(true); + Executors.newSingleThreadExecutor().execute(new Runnable() { + public void run() { + LOG.info("Stopping broker on ack: " + ack); + try { + broker.stop(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + }); + } + }}); + broker.start(); + + Vector connections = new Vector(); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); + configureConnectionFactory(cf); + Connection connection = cf.createConnection(); + connection.start(); + connections.add(connection); + final Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final Queue destination = producerSession.createQueue(QUEUE_NAME + "?consumer.prefetchSize=1"); + + connection = cf.createConnection(); + connection.start(); + connections.add(connection); + final Session consumerSession1 = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + + connection = cf.createConnection(); + connection.start(); + connections.add(connection); + final Session consumerSession2 = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + + final MessageConsumer consumer1 = consumerSession1.createConsumer(destination); + final MessageConsumer consumer2 = consumerSession2.createConsumer(destination); + + produceMessage(producerSession, destination); + produceMessage(producerSession, destination); + + final Vector receivedMessages = new Vector(); + final CountDownLatch commitDoneLatch = new CountDownLatch(1); + final AtomicBoolean gotTransactionRolledBackException = new AtomicBoolean(false); + Executors.newSingleThreadExecutor().execute(new Runnable() { + public void run() { + LOG.info("doing async commit after consume..."); + try { + Message msg = consumer1.receive(20000); + LOG.info("consumer1 first attempt got message: " + msg); + receivedMessages.add(msg); + + // give some variance to the runs + TimeUnit.SECONDS.sleep(pauseSeconds * 2); + + // should not get a second message as there are two messages and two consumers + // and prefetch=1, but with failover and unordered connection restore it can get the second + // message. + + // For the transaction to complete it needs to get the same one or two messages + // again so that the acks line up. + // If redelivery order is different, the commit should fail with an ex + // + msg = consumer1.receive(5000); + LOG.info("consumer1 second attempt got message: " + msg); + if (msg != null) { + receivedMessages.add(msg); + } + + LOG.info("committing consumer1 session: " + receivedMessages.size() + " messsage(s)"); + try { + consumerSession1.commit(); + } + catch (JMSException expectedSometimes) { + LOG.info("got exception ex on commit", expectedSometimes); + if (expectedSometimes instanceof TransactionRolledBackException) { + gotTransactionRolledBackException.set(true); + // ok, message one was not replayed so we expect the rollback + } + else { + throw expectedSometimes; + } + + } + commitDoneLatch.countDown(); + LOG.info("done async commit"); + } + catch (Exception e) { + e.printStackTrace(); + } + } + }); + + // will be stopped by the plugin + broker.waitUntilStopped(); + broker = createBroker(false, url); + setDefaultPersistenceAdapter(broker); + broker.start(); + + assertTrue("tx committed through failover", commitDoneLatch.await(30, TimeUnit.SECONDS)); + + LOG.info("received message count: " + receivedMessages.size()); + + // new transaction + Message msg = consumer1.receive(gotTransactionRolledBackException.get() ? 5000 : 20000); + LOG.info("post: from consumer1 received: " + msg); + if (gotTransactionRolledBackException.get()) { + assertNotNull("should be available again after commit rollback ex", msg); + } + else { + assertNull("should be nothing left for consumer as receive should have committed", msg); + } + consumerSession1.commit(); + + if (gotTransactionRolledBackException.get() || !gotTransactionRolledBackException.get() && receivedMessages.size() == 1) { + // just one message successfully consumed or none consumed + // consumer2 should get other message + msg = consumer2.receive(10000); + LOG.info("post: from consumer2 received: " + msg); + assertNotNull("got second message on consumer2", msg); + consumerSession2.commit(); + } + + for (Connection c : connections) { + c.close(); + } + + // ensure no dangling messages with fresh broker etc + broker.stop(); + broker.waitUntilStopped(); + + LOG.info("Checking for remaining/hung messages.."); + broker = createBroker(false, url); + setDefaultPersistenceAdapter(broker); + broker.start(); + + // after restart, ensure no dangling messages + cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); + configureConnectionFactory(cf); + connection = cf.createConnection(); + connection.start(); + Session sweeperSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer sweeper = sweeperSession.createConsumer(destination); + msg = sweeper.receive(1000); + if (msg == null) { + msg = sweeper.receive(5000); + } + LOG.info("Sweep received: " + msg); + assertNull("no messges left dangling but got: " + msg, msg); + connection.close(); + } + + public void testPoolingNConsumesAfterReconnect() throws Exception { + broker = createBroker(true); + setDefaultPersistenceAdapter(broker); + + broker.setPlugins(new BrokerPlugin[]{new BrokerPluginSupport() { + int count = 0; + + @Override + public void removeConsumer(ConnectionContext context, final ConsumerInfo info) throws Exception { + if (count++ == 1) { + Executors.newSingleThreadExecutor().execute(new Runnable() { + public void run() { + LOG.info("Stopping broker on removeConsumer: " + info); + try { + broker.stop(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + }); + } + } + }}); + broker.start(); + + Vector connections = new Vector(); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); + configureConnectionFactory(cf); + Connection connection = cf.createConnection(); + connection.start(); + Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final Queue destination = producerSession.createQueue(QUEUE_NAME + "?consumer.prefetchSize=1"); + + produceMessage(producerSession, destination); + connection.close(); + + connection = cf.createConnection(); + connection.start(); + connections.add(connection); + final Session consumerSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + + final int sessionCount = 10; + final Stack sessions = new Stack(); + for (int i = 0; i < sessionCount; i++) { + sessions.push(connection.createSession(false, Session.AUTO_ACKNOWLEDGE)); + } + + final int consumerCount = 1000; + final Deque consumers = new ArrayDeque(); + for (int i = 0; i < consumerCount; i++) { + consumers.push(consumerSession.createConsumer(destination)); + } + final ExecutorService executorService = Executors.newCachedThreadPool(); + + final FailoverTransport failoverTransport = ((ActiveMQConnection) connection).getTransport().narrow(FailoverTransport.class); + final TransportListener delegate = failoverTransport.getTransportListener(); + failoverTransport.setTransportListener(new TransportListener() { + @Override + public void onCommand(Object command) { + delegate.onCommand(command); + } + + @Override + public void onException(IOException error) { + delegate.onException(error); + } + + @Override + public void transportInterupted() { + + LOG.error("Transport interrupted: " + failoverTransport, new RuntimeException("HERE")); + for (int i = 0; i < consumerCount && !consumers.isEmpty(); i++) { + + executorService.execute(new Runnable() { + public void run() { + MessageConsumer localConsumer = null; + try { + synchronized (delegate) { + localConsumer = consumers.pop(); } + localConsumer.receive(1); - } - commitDoneLatch.countDown(); - LOG.info("done async commit"); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - - // will be stopped by the plugin - broker.waitUntilStopped(); - broker = createBroker(false, url); - setDefaultPersistenceAdapter(broker); - broker.start(); - - assertTrue("tx committed through failover", commitDoneLatch.await(30, TimeUnit.SECONDS)); - - LOG.info("received message count: " + receivedMessages.size()); - - // new transaction - Message msg = consumer1.receive(gotTransactionRolledBackException.get() ? 5000 : 20000); - LOG.info("post: from consumer1 received: " + msg); - if (gotTransactionRolledBackException.get()) { - assertNotNull("should be available again after commit rollback ex", msg); - } else { - assertNull("should be nothing left for consumer as receive should have committed", msg); - } - consumerSession1.commit(); - - if (gotTransactionRolledBackException.get() || - !gotTransactionRolledBackException.get() && receivedMessages.size() == 1) { - // just one message successfully consumed or none consumed - // consumer2 should get other message - msg = consumer2.receive(10000); - LOG.info("post: from consumer2 received: " + msg); - assertNotNull("got second message on consumer2", msg); - consumerSession2.commit(); - } - - for (Connection c : connections) { - c.close(); - } - - // ensure no dangling messages with fresh broker etc - broker.stop(); - broker.waitUntilStopped(); - - LOG.info("Checking for remaining/hung messages.."); - broker = createBroker(false, url); - setDefaultPersistenceAdapter(broker); - broker.start(); - - // after restart, ensure no dangling messages - cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); - configureConnectionFactory(cf); - connection = cf.createConnection(); - connection.start(); - Session sweeperSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer sweeper = sweeperSession.createConsumer(destination); - msg = sweeper.receive(1000); - if (msg == null) { - msg = sweeper.receive(5000); - } - LOG.info("Sweep received: " + msg); - assertNull("no messges left dangling but got: " + msg, msg); - connection.close(); - } - - public void testPoolingNConsumesAfterReconnect() throws Exception { - broker = createBroker(true); - setDefaultPersistenceAdapter(broker); - - broker.setPlugins(new BrokerPlugin[]{ - new BrokerPluginSupport() { - int count = 0; - - @Override - public void removeConsumer(ConnectionContext context, final ConsumerInfo info) throws Exception { - if (count++ == 1) { - Executors.newSingleThreadExecutor().execute(new Runnable() { - public void run() { - LOG.info("Stopping broker on removeConsumer: " + info); - try { - broker.stop(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - } - } - } - }); - broker.start(); - - Vector connections = new Vector(); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); - configureConnectionFactory(cf); - Connection connection = cf.createConnection(); - connection.start(); - Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final Queue destination = producerSession.createQueue(QUEUE_NAME + "?consumer.prefetchSize=1"); - - produceMessage(producerSession, destination); - connection.close(); - - connection = cf.createConnection(); - connection.start(); - connections.add(connection); - final Session consumerSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - - final int sessionCount = 10; - final Stack sessions = new Stack(); - for (int i = 0; i < sessionCount; i++) { - sessions.push(connection.createSession(false, Session.AUTO_ACKNOWLEDGE)); - } - - final int consumerCount = 1000; - final Deque consumers = new ArrayDeque(); - for (int i = 0; i < consumerCount; i++) { - consumers.push(consumerSession.createConsumer(destination)); - } - final ExecutorService executorService = Executors.newCachedThreadPool(); - - final FailoverTransport failoverTransport = ((ActiveMQConnection) connection).getTransport().narrow(FailoverTransport.class); - final TransportListener delegate = failoverTransport.getTransportListener(); - failoverTransport.setTransportListener(new TransportListener() { - @Override - public void onCommand(Object command) { - delegate.onCommand(command); + LOG.info("calling close() " + ((ActiveMQMessageConsumer) localConsumer).getConsumerId()); + localConsumer.close(); + } + catch (NoSuchElementException nse) { + } + catch (Exception ignored) { + LOG.error("Ex on: " + ((ActiveMQMessageConsumer) localConsumer).getConsumerId(), ignored); + } + } + }); } - @Override - public void onException(IOException error) { - delegate.onException(error); + delegate.transportInterupted(); + } + + @Override + public void transportResumed() { + delegate.transportResumed(); + } + }); + + MessageConsumer consumer = null; + synchronized (delegate) { + consumer = consumers.pop(); + } + LOG.info("calling close to trigger broker stop " + ((ActiveMQMessageConsumer) consumer).getConsumerId()); + consumer.close(); + + // will be stopped by the plugin + broker.waitUntilStopped(); + broker = createBroker(false, url); + setDefaultPersistenceAdapter(broker); + broker.start(); + + consumer = consumerSession.createConsumer(destination); + LOG.info("finally consuming message: " + ((ActiveMQMessageConsumer) consumer).getConsumerId()); + + Message msg = null; + for (int i = 0; i < 4 && msg == null; i++) { + msg = consumer.receive(1000); + } + LOG.info("post: from consumer1 received: " + msg); + assertNotNull("got message after failover", msg); + msg.acknowledge(); + + for (Connection c : connections) { + c.close(); + } + } + + public void testAutoRollbackWithMissingRedeliveries() throws Exception { + broker = createBroker(true); + broker.start(); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); + configureConnectionFactory(cf); + Connection connection = cf.createConnection(); + connection.start(); + final Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final Queue destination = producerSession.createQueue(QUEUE_NAME + "?consumer.prefetchSize=1"); + final Session consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageConsumer consumer = consumerSession.createConsumer(destination); + + produceMessage(producerSession, destination); + + Message msg = consumer.receive(20000); + assertNotNull(msg); + + broker.stop(); + broker = createBroker(false, url); + // use empty jdbc store so that default wait(0) for redeliveries will timeout after failover + setPersistenceAdapter(broker, PersistenceAdapterChoice.JDBC); + broker.start(); + + try { + consumerSession.commit(); + fail("expected transaciton rolledback ex"); + } + catch (TransactionRolledBackException expected) { + } + + broker.stop(); + broker = createBroker(false, url); + broker.start(); + + assertNotNull("should get rolledback message from original restarted broker", consumer.receive(20000)); + connection.close(); + } + + public void testWaitForMissingRedeliveries() throws Exception { + LOG.info("testWaitForMissingRedeliveries()"); + broker = createBroker(true); + broker.start(); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")?jms.consumerFailoverRedeliveryWaitPeriod=30000"); + configureConnectionFactory(cf); + Connection connection = cf.createConnection(); + connection.start(); + final Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final Queue destination = producerSession.createQueue(QUEUE_NAME); + final Session consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageConsumer consumer = consumerSession.createConsumer(destination); + + produceMessage(producerSession, destination); + Message msg = consumer.receive(20000); + if (msg == null) { + AutoFailTestSupport.dumpAllThreads("missing-"); + } + assertNotNull("got message just produced", msg); + + broker.stop(); + broker = createBroker(false, url); + // use empty jdbc store so that wait for re-deliveries occur when failover resumes + setPersistenceAdapter(broker, PersistenceAdapterChoice.JDBC); + broker.start(); + + final CountDownLatch commitDone = new CountDownLatch(1); + // will block pending re-deliveries + Executors.newSingleThreadExecutor().execute(new Runnable() { + public void run() { + LOG.info("doing async commit..."); + try { + consumerSession.commit(); + commitDone.countDown(); } - - @Override - public void transportInterupted() { - - LOG.error("Transport interrupted: " + failoverTransport, new RuntimeException("HERE")); - for (int i = 0; i < consumerCount && !consumers.isEmpty(); i++) { - - executorService.execute(new Runnable() { - public void run() { - MessageConsumer localConsumer = null; - try { - synchronized (delegate) { - localConsumer = consumers.pop(); - } - localConsumer.receive(1); - - LOG.info("calling close() " + ((ActiveMQMessageConsumer) localConsumer).getConsumerId()); - localConsumer.close(); - } catch (NoSuchElementException nse) { - } catch (Exception ignored) { - LOG.error("Ex on: " + ((ActiveMQMessageConsumer) localConsumer).getConsumerId(), ignored); - } - } - }); - } - - delegate.transportInterupted(); + catch (JMSException ignored) { } + } + }); - @Override - public void transportResumed() { - delegate.transportResumed(); + broker.stop(); + broker = createBroker(false, url); + broker.start(); + + assertTrue("commit was successful", commitDone.await(30, TimeUnit.SECONDS)); + + assertNull("should not get committed message", consumer.receive(5000)); + connection.close(); + } + + public void testReDeliveryWhilePending() throws Exception { + LOG.info("testReDeliveryWhilePending()"); + broker = createBroker(true); + broker.start(); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")?jms.consumerFailoverRedeliveryWaitPeriod=10000"); + configureConnectionFactory(cf); + Connection connection = cf.createConnection(); + connection.start(); + final Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final Queue destination = producerSession.createQueue(QUEUE_NAME + "?consumer.prefetchSize=0"); + final Session consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageConsumer consumer = consumerSession.createConsumer(destination); + + produceMessage(producerSession, destination); + Message msg = consumer.receive(20000); + if (msg == null) { + AutoFailTestSupport.dumpAllThreads("missing-"); + } + assertNotNull("got message just produced", msg); + + // add another consumer into the mix that may get the message after restart + MessageConsumer consumer2 = consumerSession.createConsumer(consumerSession.createQueue(QUEUE_NAME + "?consumer.prefetchSize=1")); + + broker.stop(); + broker = createBroker(false, url); + broker.start(); + + final CountDownLatch commitDone = new CountDownLatch(1); + + final Vector exceptions = new Vector(); + + // commit may fail if other consumer gets the message on restart + Executors.newSingleThreadExecutor().execute(new Runnable() { + public void run() { + LOG.info("doing async commit..."); + try { + consumerSession.commit(); } - }); - - - MessageConsumer consumer = null; - synchronized (delegate) { - consumer = consumers.pop(); - } - LOG.info("calling close to trigger broker stop " + ((ActiveMQMessageConsumer) consumer).getConsumerId()); - consumer.close(); - - // will be stopped by the plugin - broker.waitUntilStopped(); - broker = createBroker(false, url); - setDefaultPersistenceAdapter(broker); - broker.start(); - - consumer = consumerSession.createConsumer(destination); - LOG.info("finally consuming message: " + ((ActiveMQMessageConsumer) consumer).getConsumerId()); - - Message msg = null; - for (int i = 0; i < 4 && msg == null; i++) { - msg = consumer.receive(1000); - } - LOG.info("post: from consumer1 received: " + msg); - assertNotNull("got message after failover", msg); - msg.acknowledge(); - - for (Connection c : connections) { - c.close(); - } - } - - public void testAutoRollbackWithMissingRedeliveries() throws Exception { - broker = createBroker(true); - broker.start(); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")"); - configureConnectionFactory(cf); - Connection connection = cf.createConnection(); - connection.start(); - final Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final Queue destination = producerSession.createQueue(QUEUE_NAME + "?consumer.prefetchSize=1"); - final Session consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageConsumer consumer = consumerSession.createConsumer(destination); - - produceMessage(producerSession, destination); - - Message msg = consumer.receive(20000); - assertNotNull(msg); - - broker.stop(); - broker = createBroker(false, url); - // use empty jdbc store so that default wait(0) for redeliveries will timeout after failover - setPersistenceAdapter(broker, PersistenceAdapterChoice.JDBC); - broker.start(); - - try { - consumerSession.commit(); - fail("expected transaciton rolledback ex"); - } catch (TransactionRolledBackException expected) { - } - - broker.stop(); - broker = createBroker(false, url); - broker.start(); - - assertNotNull("should get rolledback message from original restarted broker", consumer.receive(20000)); - connection.close(); - } - - public void testWaitForMissingRedeliveries() throws Exception { - LOG.info("testWaitForMissingRedeliveries()"); - broker = createBroker(true); - broker.start(); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")?jms.consumerFailoverRedeliveryWaitPeriod=30000"); - configureConnectionFactory(cf); - Connection connection = cf.createConnection(); - connection.start(); - final Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final Queue destination = producerSession.createQueue(QUEUE_NAME); - final Session consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageConsumer consumer = consumerSession.createConsumer(destination); - - produceMessage(producerSession, destination); - Message msg = consumer.receive(20000); - if (msg == null) { - AutoFailTestSupport.dumpAllThreads("missing-"); - } - assertNotNull("got message just produced", msg); - - broker.stop(); - broker = createBroker(false, url); - // use empty jdbc store so that wait for re-deliveries occur when failover resumes - setPersistenceAdapter(broker, PersistenceAdapterChoice.JDBC); - broker.start(); - - final CountDownLatch commitDone = new CountDownLatch(1); - // will block pending re-deliveries - Executors.newSingleThreadExecutor().execute(new Runnable() { - public void run() { - LOG.info("doing async commit..."); - try { - consumerSession.commit(); - commitDone.countDown(); - } catch (JMSException ignored) { - } + catch (JMSException ex) { + exceptions.add(ex); } - }); - - broker.stop(); - broker = createBroker(false, url); - broker.start(); - - assertTrue("commit was successful", commitDone.await(30, TimeUnit.SECONDS)); - - assertNull("should not get committed message", consumer.receive(5000)); - connection.close(); - } - - public void testReDeliveryWhilePending() throws Exception { - LOG.info("testReDeliveryWhilePending()"); - broker = createBroker(true); - broker.start(); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")?jms.consumerFailoverRedeliveryWaitPeriod=10000"); - configureConnectionFactory(cf); - Connection connection = cf.createConnection(); - connection.start(); - final Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final Queue destination = producerSession.createQueue(QUEUE_NAME + "?consumer.prefetchSize=0"); - final Session consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageConsumer consumer = consumerSession.createConsumer(destination); - - produceMessage(producerSession, destination); - Message msg = consumer.receive(20000); - if (msg == null) { - AutoFailTestSupport.dumpAllThreads("missing-"); - } - assertNotNull("got message just produced", msg); - - // add another consumer into the mix that may get the message after restart - MessageConsumer consumer2 = consumerSession.createConsumer(consumerSession.createQueue(QUEUE_NAME + "?consumer.prefetchSize=1")); - - broker.stop(); - broker = createBroker(false, url); - broker.start(); - - final CountDownLatch commitDone = new CountDownLatch(1); - - final Vector exceptions = new Vector(); - - // commit may fail if other consumer gets the message on restart - Executors.newSingleThreadExecutor().execute(new Runnable() { - public void run() { - LOG.info("doing async commit..."); - try { - consumerSession.commit(); - } catch (JMSException ex) { - exceptions.add(ex); - } finally { - commitDone.countDown(); - } + finally { + commitDone.countDown(); } - }); + } + }); + assertTrue("commit completed ", commitDone.await(15, TimeUnit.SECONDS)); - assertTrue("commit completed ", commitDone.await(15, TimeUnit.SECONDS)); + // either message redelivered in existing tx or consumed by consumer2 + // should not be available again in any event + assertNull("consumer should not get rolled back on non redelivered message or duplicate", consumer.receive(5000)); - // either message redelivered in existing tx or consumed by consumer2 - // should not be available again in any event - assertNull("consumer should not get rolled back on non redelivered message or duplicate", consumer.receive(5000)); + // consumer replay is hashmap order dependent on a failover connection state recover so need to deal with both cases + if (exceptions.isEmpty()) { + LOG.info("commit succeeded, message was redelivered to the correct consumer after restart so commit was fine"); + assertNull("consumer2 not get a second message consumed by 1", consumer2.receive(2000)); + } + else { + LOG.info("commit failed, consumer2 should get it", exceptions.get(0)); + assertNotNull("consumer2 got message", consumer2.receive(2000)); + consumerSession.commit(); + // no message should be in dlq + MessageConsumer dlqConsumer = consumerSession.createConsumer(consumerSession.createQueue("ActiveMQ.DLQ")); + assertNull("nothing in the dlq", dlqConsumer.receive(5000)); + } + connection.close(); + } - // consumer replay is hashmap order dependent on a failover connection state recover so need to deal with both cases - if (exceptions.isEmpty()) { - LOG.info("commit succeeded, message was redelivered to the correct consumer after restart so commit was fine"); - assertNull("consumer2 not get a second message consumed by 1", consumer2.receive(2000)); - } else { - LOG.info("commit failed, consumer2 should get it", exceptions.get(0)); - assertNotNull("consumer2 got message", consumer2.receive(2000)); - consumerSession.commit(); - // no message should be in dlq - MessageConsumer dlqConsumer = consumerSession.createConsumer(consumerSession.createQueue("ActiveMQ.DLQ")); - assertNull("nothing in the dlq", dlqConsumer.receive(5000)); - } - connection.close(); - } - - private void produceMessage(final Session producerSession, Queue destination) - throws JMSException { - MessageProducer producer = producerSession.createProducer(destination); - TextMessage message = producerSession.createTextMessage("Test message"); - producer.send(message); - producer.close(); - } + private void produceMessage(final Session producerSession, Queue destination) throws JMSException { + MessageProducer producer = producerSession.createProducer(destination); + TextMessage message = producerSession.createTextMessage("Test message"); + producer.send(message); + producer.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverTransportBackupsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverTransportBackupsTest.java index b1c8a1b43a..0ba3939511 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverTransportBackupsTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverTransportBackupsTest.java @@ -36,192 +36,192 @@ import org.slf4j.LoggerFactory; public class FailoverTransportBackupsTest { - private static final Logger LOG = LoggerFactory.getLogger(FailoverTransportBackupsTest.class); + private static final Logger LOG = LoggerFactory.getLogger(FailoverTransportBackupsTest.class); - protected Transport transport; - protected FailoverTransport failoverTransport; - private int transportInterruptions; - private int transportResumptions; + protected Transport transport; + protected FailoverTransport failoverTransport; + private int transportInterruptions; + private int transportResumptions; - BrokerService broker1; - BrokerService broker2; - BrokerService broker3; + BrokerService broker1; + BrokerService broker2; + BrokerService broker3; - @Before - public void setUp() throws Exception { - broker1 = createBroker("1"); - broker2 = createBroker("2"); - broker3 = createBroker("3"); + @Before + public void setUp() throws Exception { + broker1 = createBroker("1"); + broker2 = createBroker("2"); + broker3 = createBroker("3"); - broker1.start(); - broker2.start(); - broker3.start(); + broker1.start(); + broker2.start(); + broker3.start(); - broker1.waitUntilStarted(); - broker2.waitUntilStarted(); - broker3.waitUntilStarted(); + broker1.waitUntilStarted(); + broker2.waitUntilStarted(); + broker3.waitUntilStarted(); - // Reset stats - transportInterruptions = 0; - transportResumptions = 0; - } + // Reset stats + transportInterruptions = 0; + transportResumptions = 0; + } - @After - public void tearDown() throws Exception { - if (transport != null) { - transport.stop(); - } + @After + public void tearDown() throws Exception { + if (transport != null) { + transport.stop(); + } - broker1.stop(); - broker1.waitUntilStopped(); - broker2.stop(); - broker2.waitUntilStopped(); - broker3.stop(); - broker3.waitUntilStopped(); - } + broker1.stop(); + broker1.waitUntilStopped(); + broker2.stop(); + broker2.waitUntilStopped(); + broker3.stop(); + broker3.waitUntilStopped(); + } - @Test - public void testBackupsAreCreated() throws Exception { - this.transport = createTransport(2); - assertNotNull(failoverTransport); - assertTrue(failoverTransport.isBackup()); - assertEquals(2, failoverTransport.getBackupPoolSize()); + @Test + public void testBackupsAreCreated() throws Exception { + this.transport = createTransport(2); + assertNotNull(failoverTransport); + assertTrue(failoverTransport.isBackup()); + assertEquals(2, failoverTransport.getBackupPoolSize()); - assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition(){ - @Override - public boolean isSatisified() throws Exception { - LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups()); - return failoverTransport.getCurrentBackups() == 2; - } - })); - } + assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups()); + return failoverTransport.getCurrentBackups() == 2; + } + })); + } - @Test - public void testFailoverToBackups() throws Exception { - this.transport = createTransport(2); - assertNotNull(failoverTransport); - assertTrue(failoverTransport.isBackup()); - assertEquals(2, failoverTransport.getBackupPoolSize()); + @Test + public void testFailoverToBackups() throws Exception { + this.transport = createTransport(2); + assertNotNull(failoverTransport); + assertTrue(failoverTransport.isBackup()); + assertEquals(2, failoverTransport.getBackupPoolSize()); - assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition(){ - @Override - public boolean isSatisified() throws Exception { - LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups()); - return failoverTransport.getCurrentBackups() == 2; - } - })); + assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups()); + return failoverTransport.getCurrentBackups() == 2; + } + })); - broker1.stop(); + broker1.stop(); - assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition(){ - @Override - public boolean isSatisified() throws Exception { - LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups()); - return failoverTransport.getCurrentBackups() == 1; - } - })); + assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups()); + return failoverTransport.getCurrentBackups() == 1; + } + })); - assertTrue("Incorrect number of Transport interruptions", transportInterruptions >= 1); - assertTrue("Incorrect number of Transport resumptions", transportResumptions >= 1); + assertTrue("Incorrect number of Transport interruptions", transportInterruptions >= 1); + assertTrue("Incorrect number of Transport resumptions", transportResumptions >= 1); - broker2.stop(); + broker2.stop(); - assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition(){ - @Override - public boolean isSatisified() throws Exception { - LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups()); - return failoverTransport.getCurrentBackups() == 0; - } - })); + assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups()); + return failoverTransport.getCurrentBackups() == 0; + } + })); - assertTrue("Incorrect number of Transport interruptions", transportInterruptions >= 2); - assertTrue("Incorrect number of Transport resumptions", transportResumptions >= 2); - } + assertTrue("Incorrect number of Transport interruptions", transportInterruptions >= 2); + assertTrue("Incorrect number of Transport resumptions", transportResumptions >= 2); + } - @Test - public void testBackupsRefilled() throws Exception { - this.transport = createTransport(1); - assertNotNull(failoverTransport); - assertTrue(failoverTransport.isBackup()); - assertEquals(1, failoverTransport.getBackupPoolSize()); + @Test + public void testBackupsRefilled() throws Exception { + this.transport = createTransport(1); + assertNotNull(failoverTransport); + assertTrue(failoverTransport.isBackup()); + assertEquals(1, failoverTransport.getBackupPoolSize()); - assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition(){ - @Override - public boolean isSatisified() throws Exception { - LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups()); - return failoverTransport.getCurrentBackups() == 1; - } - })); + assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups()); + return failoverTransport.getCurrentBackups() == 1; + } + })); - broker1.stop(); + broker1.stop(); - assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition(){ - @Override - public boolean isSatisified() throws Exception { - LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups()); - return failoverTransport.getCurrentBackups() == 1; - } - })); + assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups()); + return failoverTransport.getCurrentBackups() == 1; + } + })); - broker2.stop(); + broker2.stop(); - assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition(){ - @Override - public boolean isSatisified() throws Exception { - LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups()); - return failoverTransport.getCurrentBackups() == 0; - } - })); - } + assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups()); + return failoverTransport.getCurrentBackups() == 0; + } + })); + } - private BrokerService createBroker(String name) throws Exception { - BrokerService bs = new BrokerService(); - bs.setBrokerName(name); - bs.setUseJmx(false); - bs.setPersistent(false); - bs.addConnector("tcp://localhost:0"); - return bs; - } + private BrokerService createBroker(String name) throws Exception { + BrokerService bs = new BrokerService(); + bs.setBrokerName(name); + bs.setUseJmx(false); + bs.setPersistent(false); + bs.addConnector("tcp://localhost:0"); + return bs; + } - protected Transport createTransport(int backups) throws Exception { - String connectionUri = "failover://("+ - broker1.getTransportConnectors().get(0).getPublishableConnectString() + "," + - broker2.getTransportConnectors().get(0).getPublishableConnectString() + "," + - broker3.getTransportConnectors().get(0).getPublishableConnectString() + ")"; + protected Transport createTransport(int backups) throws Exception { + String connectionUri = "failover://(" + + broker1.getTransportConnectors().get(0).getPublishableConnectString() + "," + + broker2.getTransportConnectors().get(0).getPublishableConnectString() + "," + + broker3.getTransportConnectors().get(0).getPublishableConnectString() + ")"; - if (backups > 0) { - connectionUri += "?randomize=false&backup=true&backupPoolSize=" + backups; - } + if (backups > 0) { + connectionUri += "?randomize=false&backup=true&backupPoolSize=" + backups; + } - Transport transport = TransportFactory.connect(new URI(connectionUri)); - transport.setTransportListener(new TransportListener() { + Transport transport = TransportFactory.connect(new URI(connectionUri)); + transport.setTransportListener(new TransportListener() { - @Override - public void onCommand(Object command) { - LOG.debug("Test Transport Listener received Command: " + command); - } + @Override + public void onCommand(Object command) { + LOG.debug("Test Transport Listener received Command: " + command); + } - @Override - public void onException(IOException error) { - LOG.debug("Test Transport Listener received Exception: " + error); - } + @Override + public void onException(IOException error) { + LOG.debug("Test Transport Listener received Exception: " + error); + } - @Override - public void transportInterupted() { - transportInterruptions++; - LOG.debug("Test Transport Listener records transport Interrupted: " + transportInterruptions); - } + @Override + public void transportInterupted() { + transportInterruptions++; + LOG.debug("Test Transport Listener records transport Interrupted: " + transportInterruptions); + } - @Override - public void transportResumed() { - transportResumptions++; - LOG.debug("Test Transport Listener records transport Resumed: " + transportResumptions); - } - }); - transport.start(); + @Override + public void transportResumed() { + transportResumptions++; + LOG.debug("Test Transport Listener records transport Resumed: " + transportResumptions); + } + }); + transport.start(); - this.failoverTransport = transport.narrow(FailoverTransport.class); + this.failoverTransport = transport.narrow(FailoverTransport.class); - return transport; - } + return transport; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverTransportBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverTransportBrokerTest.java index 575b594b4a..806facaa37 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverTransportBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverTransportBrokerTest.java @@ -43,140 +43,141 @@ import org.slf4j.LoggerFactory; public class FailoverTransportBrokerTest extends NetworkTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(FailoverTransportBrokerTest.class); + private static final Logger LOG = LoggerFactory.getLogger(FailoverTransportBrokerTest.class); - public ActiveMQDestination destination; - public int deliveryMode; + public ActiveMQDestination destination; + public int deliveryMode; - public void initCombosForTestPublisherFailsOver() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST")}); - } + public void initCombosForTestPublisherFailsOver() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destination", new Object[]{new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST")}); + } - public void testPublisherFailsOver() throws Exception { + public void testPublisherFailsOver() throws Exception { - // Start a normal consumer on the local broker - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.request(consumerInfo1); + // Start a normal consumer on the local broker + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.request(consumerInfo1); - // Start a normal consumer on a remote broker - StubConnection connection2 = createRemoteConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.request(consumerInfo2); + // Start a normal consumer on a remote broker + StubConnection connection2 = createRemoteConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + connection2.request(consumerInfo2); - // Start a failover publisher. - LOG.info("Starting the failover connection."); - StubConnection connection3 = createFailoverConnection(null); - ConnectionInfo connectionInfo3 = createConnectionInfo(); - SessionInfo sessionInfo3 = createSessionInfo(connectionInfo3); - ProducerInfo producerInfo3 = createProducerInfo(sessionInfo3); - connection3.send(connectionInfo3); - connection3.send(sessionInfo3); - connection3.send(producerInfo3); + // Start a failover publisher. + LOG.info("Starting the failover connection."); + StubConnection connection3 = createFailoverConnection(null); + ConnectionInfo connectionInfo3 = createConnectionInfo(); + SessionInfo sessionInfo3 = createSessionInfo(connectionInfo3); + ProducerInfo producerInfo3 = createProducerInfo(sessionInfo3); + connection3.send(connectionInfo3); + connection3.send(sessionInfo3); + connection3.send(producerInfo3); - // Send the message using the fail over publisher. - connection3.request(createMessage(producerInfo3, destination, deliveryMode)); + // Send the message using the fail over publisher. + connection3.request(createMessage(producerInfo3, destination, deliveryMode)); - // The message will be sent to one of the brokers. - FailoverTransport ft = connection3.getTransport().narrow(FailoverTransport.class); + // The message will be sent to one of the brokers. + FailoverTransport ft = connection3.getTransport().narrow(FailoverTransport.class); - // See which broker we were connected to. - StubConnection connectionA; - StubConnection connectionB; - TransportConnector serverA; - if (connector.getServer().getConnectURI().equals(ft.getConnectedTransportURI())) { - connectionA = connection1; - connectionB = connection2; - serverA = connector; - } else { - connectionA = connection2; - connectionB = connection1; - serverA = remoteConnector; - } + // See which broker we were connected to. + StubConnection connectionA; + StubConnection connectionB; + TransportConnector serverA; + if (connector.getServer().getConnectURI().equals(ft.getConnectedTransportURI())) { + connectionA = connection1; + connectionB = connection2; + serverA = connector; + } + else { + connectionA = connection2; + connectionB = connection1; + serverA = remoteConnector; + } - assertNotNull(receiveMessage(connectionA)); - assertNoMessagesLeft(connectionB); + assertNotNull(receiveMessage(connectionA)); + assertNoMessagesLeft(connectionB); - // Dispose the server so that it fails over to the other server. - LOG.info("Disconnecting the active connection"); - serverA.stop(); + // Dispose the server so that it fails over to the other server. + LOG.info("Disconnecting the active connection"); + serverA.stop(); - connection3.request(createMessage(producerInfo3, destination, deliveryMode)); + connection3.request(createMessage(producerInfo3, destination, deliveryMode)); - assertNotNull(receiveMessage(connectionB)); - assertNoMessagesLeft(connectionA); + assertNotNull(receiveMessage(connectionB)); + assertNoMessagesLeft(connectionA); - } + } - public void testNoBrokersInBrokerInfo() throws Exception { - final BrokerInfo info[] = new BrokerInfo[1]; - TransportListener listener = new TransportListener() { - @Override - public void onCommand(Object command) { - LOG.info("Got command: " + command); - if (command instanceof BrokerInfo) { - info[0] = (BrokerInfo) command; - } + public void testNoBrokersInBrokerInfo() throws Exception { + final BrokerInfo info[] = new BrokerInfo[1]; + TransportListener listener = new TransportListener() { + @Override + public void onCommand(Object command) { + LOG.info("Got command: " + command); + if (command instanceof BrokerInfo) { + info[0] = (BrokerInfo) command; } + } - @Override - public void onException(IOException error) { - //To change body of implemented methods use File | Settings | File Templates. - } + @Override + public void onException(IOException error) { + //To change body of implemented methods use File | Settings | File Templates. + } - @Override - public void transportInterupted() { - //To change body of implemented methods use File | Settings | File Templates. - } + @Override + public void transportInterupted() { + //To change body of implemented methods use File | Settings | File Templates. + } - @Override - public void transportResumed() { - //To change body of implemented methods use File | Settings | File Templates. - } - }; - @SuppressWarnings("unused") - StubConnection c = createFailoverConnection(listener); - int count = 0; - while(count++ < 20 && info[0] == null) { - TimeUnit.SECONDS.sleep(1); - } - assertNotNull("got a valid brokerInfo after 20 secs", info[0]); - assertNull("no peer brokers present", info[0].getPeerBrokerInfos()); - } + @Override + public void transportResumed() { + //To change body of implemented methods use File | Settings | File Templates. + } + }; + @SuppressWarnings("unused") + StubConnection c = createFailoverConnection(listener); + int count = 0; + while (count++ < 20 && info[0] == null) { + TimeUnit.SECONDS.sleep(1); + } + assertNotNull("got a valid brokerInfo after 20 secs", info[0]); + assertNull("no peer brokers present", info[0].getPeerBrokerInfos()); + } - @Override - protected String getLocalURI() { - return "tcp://localhost:0?wireFormat.tcpNoDelayEnabled=true"; - } + @Override + protected String getLocalURI() { + return "tcp://localhost:0?wireFormat.tcpNoDelayEnabled=true"; + } - @Override - protected String getRemoteURI() { - return "tcp://localhost:0?wireFormat.tcpNoDelayEnabled=true"; - } + @Override + protected String getRemoteURI() { + return "tcp://localhost:0?wireFormat.tcpNoDelayEnabled=true"; + } - protected StubConnection createFailoverConnection(TransportListener listener) throws Exception { - URI failoverURI = new URI("failover://" + connector.getServer().getConnectURI() + "," + remoteConnector.getServer().getConnectURI() + ""); - Transport transport = TransportFactory.connect(failoverURI); - StubConnection connection = new StubConnection(transport, listener); - connections.add(connection); - return connection; - } + protected StubConnection createFailoverConnection(TransportListener listener) throws Exception { + URI failoverURI = new URI("failover://" + connector.getServer().getConnectURI() + "," + remoteConnector.getServer().getConnectURI() + ""); + Transport transport = TransportFactory.connect(failoverURI); + StubConnection connection = new StubConnection(transport, listener); + connections.add(connection); + return connection; + } - public static Test suite() { - return suite(FailoverTransportBrokerTest.class); - } + public static Test suite() { + return suite(FailoverTransportBrokerTest.class); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverTransportTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverTransportTest.java index fd130fcb77..1cb5daad5a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverTransportTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverTransportTest.java @@ -40,141 +40,140 @@ import org.junit.Test; public class FailoverTransportTest { - protected Transport transport; - protected FailoverTransport failoverTransport; + protected Transport transport; + protected FailoverTransport failoverTransport; - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - if (transport != null) { - transport.stop(); - } - } + @After + public void tearDown() throws Exception { + if (transport != null) { + transport.stop(); + } + } - @Test(timeout = 30000) - @Ignore("Test fails on windows") - public void testReconnectUnlimited() throws Exception { + @Test(timeout = 30000) + @Ignore("Test fails on windows") + public void testReconnectUnlimited() throws Exception { - Transport transport = TransportFactory.connect( - new URI("failover://(tcp://0.0.0.0:61616)?useExponentialBackOff=false&reconnectDelay=0&initialReconnectDelay=0")); + Transport transport = TransportFactory.connect(new URI("failover://(tcp://0.0.0.0:61616)?useExponentialBackOff=false&reconnectDelay=0&initialReconnectDelay=0")); - transport.setTransportListener(new TransportListener() { + transport.setTransportListener(new TransportListener() { - public void onCommand(Object command) { - } + public void onCommand(Object command) { + } - public void onException(IOException error) { - } + public void onException(IOException error) { + } - public void transportInterupted() { - } + public void transportInterupted() { + } - public void transportResumed() { - } - }); - transport.start(); + public void transportResumed() { + } + }); + transport.start(); - this.failoverTransport = transport.narrow(FailoverTransport.class); + this.failoverTransport = transport.narrow(FailoverTransport.class); - assertTrue("no implicit limit of 1000", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return failoverTransport.getConnectFailures() > 1002; - } - })); - } + assertTrue("no implicit limit of 1000", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return failoverTransport.getConnectFailures() > 1002; + } + })); + } - @Test(timeout=30000) - public void testCommandsIgnoredWhenOffline() throws Exception { - this.transport = createTransport(); + @Test(timeout = 30000) + public void testCommandsIgnoredWhenOffline() throws Exception { + this.transport = createTransport(); - assertNotNull(failoverTransport); + assertNotNull(failoverTransport); - ConnectionStateTracker tracker = failoverTransport.getStateTracker(); - assertNotNull(tracker); + ConnectionStateTracker tracker = failoverTransport.getStateTracker(); + assertNotNull(tracker); - ConnectionId id = new ConnectionId("1"); - ConnectionInfo connection = new ConnectionInfo(id); + ConnectionId id = new ConnectionId("1"); + ConnectionInfo connection = new ConnectionInfo(id); - // Track a connection - tracker.track(connection); - try { - this.transport.oneway(new RemoveInfo(new ConnectionId("1"))); - } catch(Exception e) { - fail("Should not have failed to remove this known connection"); - } + // Track a connection + tracker.track(connection); + try { + this.transport.oneway(new RemoveInfo(new ConnectionId("1"))); + } + catch (Exception e) { + fail("Should not have failed to remove this known connection"); + } - try { - this.transport.oneway(new RemoveInfo(new ConnectionId("2"))); - } catch(Exception e) { - fail("Should not have failed to remove this unknown connection"); - } + try { + this.transport.oneway(new RemoveInfo(new ConnectionId("2"))); + } + catch (Exception e) { + fail("Should not have failed to remove this unknown connection"); + } - this.transport.oneway(new MessageAck()); - this.transport.oneway(new ShutdownInfo()); - } + this.transport.oneway(new MessageAck()); + this.transport.oneway(new ShutdownInfo()); + } - @Test(timeout=30000) - public void testResponsesSentWhenRequestForIgnoredCommands() throws Exception { - this.transport = createTransport(); - assertNotNull(failoverTransport); - MessageAck ack = new MessageAck(); - assertNotNull("Should have received a Response", this.transport.request(ack)); - RemoveInfo info = new RemoveInfo(new ConnectionId("2")); - assertNotNull("Should have received a Response", this.transport.request(info)); - } + @Test(timeout = 30000) + public void testResponsesSentWhenRequestForIgnoredCommands() throws Exception { + this.transport = createTransport(); + assertNotNull(failoverTransport); + MessageAck ack = new MessageAck(); + assertNotNull("Should have received a Response", this.transport.request(ack)); + RemoveInfo info = new RemoveInfo(new ConnectionId("2")); + assertNotNull("Should have received a Response", this.transport.request(info)); + } - @Test - public void testLocalhostPortSyntax() throws Exception { - transport = TransportFactory.connect( - new URI("failover://(tcp://localhost:1111/localhost:2111)")); + @Test + public void testLocalhostPortSyntax() throws Exception { + transport = TransportFactory.connect(new URI("failover://(tcp://localhost:1111/localhost:2111)")); - transport.setTransportListener(new TransportListener() { + transport.setTransportListener(new TransportListener() { - public void onCommand(Object command) { - } + public void onCommand(Object command) { + } - public void onException(IOException error) { - } + public void onException(IOException error) { + } - public void transportInterupted() { - } + public void transportInterupted() { + } - public void transportResumed() { - } - }); + public void transportResumed() { + } + }); - failoverTransport = transport.narrow(FailoverTransport.class); + failoverTransport = transport.narrow(FailoverTransport.class); - transport.start(); + transport.start(); - } + } - protected Transport createTransport() throws Exception { - Transport transport = TransportFactory.connect( - new URI("failover://(tcp://localhost:1234?transport.connectTimeout=10000)")); - transport.setTransportListener(new TransportListener() { + protected Transport createTransport() throws Exception { + Transport transport = TransportFactory.connect(new URI("failover://(tcp://localhost:1234?transport.connectTimeout=10000)")); + transport.setTransportListener(new TransportListener() { - public void onCommand(Object command) { - } + public void onCommand(Object command) { + } - public void onException(IOException error) { - } + public void onException(IOException error) { + } - public void transportInterupted() { - } + public void transportInterupted() { + } - public void transportResumed() { - } - }); - transport.start(); + public void transportResumed() { + } + }); + transport.start(); - this.failoverTransport = transport.narrow(FailoverTransport.class); + this.failoverTransport = transport.narrow(FailoverTransport.class); - return transport; - } + return transport; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverTransportUriHandlingTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverTransportUriHandlingTest.java index 1258fbcad1..8155575352 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverTransportUriHandlingTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverTransportUriHandlingTest.java @@ -27,120 +27,110 @@ import org.junit.Test; public class FailoverTransportUriHandlingTest { - @Test - public void testFailoverTransportAddWithInitialUnknown() throws Exception { - FailoverTransport transport = new FailoverTransport(); + @Test + public void testFailoverTransportAddWithInitialUnknown() throws Exception { + FailoverTransport transport = new FailoverTransport(); - final String initialUri = "tcp://no.existing.hostname:61616"; + final String initialUri = "tcp://no.existing.hostname:61616"; - transport.add(false, initialUri); + transport.add(false, initialUri); - String[] uriArray = new String[] {"tcp://127.0.0.2:61616", - "tcp://localhost:61616", - "tcp://localhost:61617"}; + String[] uriArray = new String[]{"tcp://127.0.0.2:61616", "tcp://localhost:61616", "tcp://localhost:61617"}; - for(String uri : uriArray) { - transport.add(false, uri); - } + for (String uri : uriArray) { + transport.add(false, uri); + } - Collection uris = getRegisteredUrlsFromPrivateField(transport); + Collection uris = getRegisteredUrlsFromPrivateField(transport); - for(String uri : uriArray) { - assertTrue("Collection should contain: " + uri, uris.contains(new URI(uri))); - } - } + for (String uri : uriArray) { + assertTrue("Collection should contain: " + uri, uris.contains(new URI(uri))); + } + } - @Test - public void testFailoverTransportAddWithInitialKnown() throws Exception { - FailoverTransport transport = new FailoverTransport(); + @Test + public void testFailoverTransportAddWithInitialKnown() throws Exception { + FailoverTransport transport = new FailoverTransport(); - final String initialUri = "tcp://localhost:61616"; + final String initialUri = "tcp://localhost:61616"; - transport.add(false, initialUri); + transport.add(false, initialUri); - String[] uriArray = new String[] {"tcp://127.0.0.2:61616", - "tcp://no.existing.hostname:61616", - "tcp://localhost:61617"}; + String[] uriArray = new String[]{"tcp://127.0.0.2:61616", "tcp://no.existing.hostname:61616", "tcp://localhost:61617"}; - for(String uri : uriArray) { - transport.add(false, uri); - } + for (String uri : uriArray) { + transport.add(false, uri); + } - Collection uris = getRegisteredUrlsFromPrivateField(transport); + Collection uris = getRegisteredUrlsFromPrivateField(transport); - for(String uri : uriArray) { - assertTrue("Collection should contain: " + uri, uris.contains(new URI(uri))); - } - } + for (String uri : uriArray) { + assertTrue("Collection should contain: " + uri, uris.contains(new URI(uri))); + } + } - @Test - public void testFailoverTransportAddWithPreventsDups() throws Exception { - FailoverTransport transport = new FailoverTransport(); + @Test + public void testFailoverTransportAddWithPreventsDups() throws Exception { + FailoverTransport transport = new FailoverTransport(); - final String initialUri = "tcp://localhost:61616"; + final String initialUri = "tcp://localhost:61616"; - transport.add(false, initialUri); + transport.add(false, initialUri); - String[] uriArray = new String[] {"tcp://127.0.0.2:61616", - "tcp://localhost:61616", - "tcp://no.existing.hostname:61616", - "tcp://localhost:61617", - "tcp://127.0.0.1:61616"}; + String[] uriArray = new String[]{"tcp://127.0.0.2:61616", "tcp://localhost:61616", "tcp://no.existing.hostname:61616", "tcp://localhost:61617", "tcp://127.0.0.1:61616"}; - for(String uri : uriArray) { - transport.add(false, uri); - } + for (String uri : uriArray) { + transport.add(false, uri); + } - Collection uris = getRegisteredUrlsFromPrivateField(transport); + Collection uris = getRegisteredUrlsFromPrivateField(transport); - assertEquals(4, uris.size()); + assertEquals(4, uris.size()); - // Ensure even the unknowns get checked. - transport.add(false, "tcp://no.existing.hostname:61616"); + // Ensure even the unknowns get checked. + transport.add(false, "tcp://no.existing.hostname:61616"); - uris = getRegisteredUrlsFromPrivateField(transport); + uris = getRegisteredUrlsFromPrivateField(transport); - assertEquals(4, uris.size()); - } + assertEquals(4, uris.size()); + } - @Test - public void testFailoverTransportAddArray() throws Exception { - FailoverTransport transport = new FailoverTransport(); + @Test + public void testFailoverTransportAddArray() throws Exception { + FailoverTransport transport = new FailoverTransport(); - final String initialUri = "tcp://no.existing.hostname:61616"; + final String initialUri = "tcp://no.existing.hostname:61616"; - transport.add(false, initialUri); + transport.add(false, initialUri); - URI[] uriArray = new URI[] {new URI("tcp://127.0.0.2:61616"), - new URI("tcp://localhost:61616"), - new URI("tcp://localhost:61617")}; + URI[] uriArray = new URI[]{new URI("tcp://127.0.0.2:61616"), new URI("tcp://localhost:61616"), new URI("tcp://localhost:61617")}; - transport.add(false, uriArray); + transport.add(false, uriArray); - Collection uris = getRegisteredUrlsFromPrivateField(transport); + Collection uris = getRegisteredUrlsFromPrivateField(transport); - for(URI uri : uriArray) { - assertTrue("Collection should contain: " + uri, uris.contains(uri)); - } + for (URI uri : uriArray) { + assertTrue("Collection should contain: " + uri, uris.contains(uri)); + } - assertEquals(4, uris.size()); + assertEquals(4, uris.size()); - // Ensure even the unknowns get checked. - transport.add(false, "tcp://no.existing.hostname:61616"); + // Ensure even the unknowns get checked. + transport.add(false, "tcp://no.existing.hostname:61616"); - uris = getRegisteredUrlsFromPrivateField(transport); + uris = getRegisteredUrlsFromPrivateField(transport); - assertEquals(4, uris.size()); + assertEquals(4, uris.size()); - transport.add(false, uriArray); + transport.add(false, uriArray); - assertEquals(4, uris.size()); - } + assertEquals(4, uris.size()); + } - @SuppressWarnings("unchecked") - private Collection getRegisteredUrlsFromPrivateField(FailoverTransport failoverTransport) throws SecurityException, NoSuchFieldException, IllegalAccessException { - Field urisField = failoverTransport.getClass().getDeclaredField("uris"); - urisField.setAccessible(true); - return (Collection) urisField.get(failoverTransport); - } + @SuppressWarnings("unchecked") + private Collection getRegisteredUrlsFromPrivateField(FailoverTransport failoverTransport) throws SecurityException, NoSuchFieldException, IllegalAccessException { + Field urisField = failoverTransport.getClass().getDeclaredField("uris"); + urisField.setAccessible(true); + return (Collection) urisField.get(failoverTransport); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverUpdateURIsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverUpdateURIsTest.java index 9c9b2fd978..e792228195 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverUpdateURIsTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverUpdateURIsTest.java @@ -37,120 +37,120 @@ import org.apache.log4j.Logger; public class FailoverUpdateURIsTest extends TestCase { - private static final String QUEUE_NAME = "test.failoverupdateuris"; - private static final Logger LOG = Logger.getLogger(FailoverUpdateURIsTest.class); + private static final String QUEUE_NAME = "test.failoverupdateuris"; + private static final Logger LOG = Logger.getLogger(FailoverUpdateURIsTest.class); - String firstTcpUri = "tcp://localhost:61616"; - String secondTcpUri = "tcp://localhost:61626"; - Connection connection = null; - BrokerService bs1 = null; - BrokerService bs2 = null; + String firstTcpUri = "tcp://localhost:61616"; + String secondTcpUri = "tcp://localhost:61626"; + Connection connection = null; + BrokerService bs1 = null; + BrokerService bs2 = null; - @Override - public void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - if (bs1 != null) { - bs1.stop(); - } - if (bs2 != null) { - bs2.stop(); - } - } + @Override + public void tearDown() throws Exception { + if (connection != null) { + connection.close(); + } + if (bs1 != null) { + bs1.stop(); + } + if (bs2 != null) { + bs2.stop(); + } + } - public void testUpdateURIsViaFile() throws Exception { + public void testUpdateURIsViaFile() throws Exception { - String targetDir = "target/" + getName(); - new File(targetDir).mkdir(); - File updateFile = new File(targetDir + "/updateURIsFile.txt"); - LOG.info(updateFile); - LOG.info(updateFile.toURI()); - LOG.info(updateFile.getAbsoluteFile()); - LOG.info(updateFile.getAbsoluteFile().toURI()); - FileOutputStream out = new FileOutputStream(updateFile); - out.write(firstTcpUri.getBytes()); - out.close(); + String targetDir = "target/" + getName(); + new File(targetDir).mkdir(); + File updateFile = new File(targetDir + "/updateURIsFile.txt"); + LOG.info(updateFile); + LOG.info(updateFile.toURI()); + LOG.info(updateFile.getAbsoluteFile()); + LOG.info(updateFile.getAbsoluteFile().toURI()); + FileOutputStream out = new FileOutputStream(updateFile); + out.write(firstTcpUri.getBytes()); + out.close(); - bs1 = createBroker("bs1", firstTcpUri); - bs1.start(); + bs1 = createBroker("bs1", firstTcpUri); + bs1.start(); - // no failover uri's to start with, must be read from file... - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:()?updateURIsURL=file:///" + updateFile.getAbsoluteFile()); - connection = cf.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue theQueue = session.createQueue(QUEUE_NAME); - MessageProducer producer = session.createProducer(theQueue); - MessageConsumer consumer = session.createConsumer(theQueue); - Message message = session.createTextMessage("Test message"); - producer.send(message); - Message msg = consumer.receive(2000); - assertNotNull(msg); + // no failover uri's to start with, must be read from file... + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:()?updateURIsURL=file:///" + updateFile.getAbsoluteFile()); + connection = cf.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue theQueue = session.createQueue(QUEUE_NAME); + MessageProducer producer = session.createProducer(theQueue); + MessageConsumer consumer = session.createConsumer(theQueue); + Message message = session.createTextMessage("Test message"); + producer.send(message); + Message msg = consumer.receive(2000); + assertNotNull(msg); - bs1.stop(); - bs1.waitUntilStopped(); - bs1 = null; + bs1.stop(); + bs1.waitUntilStopped(); + bs1 = null; - bs2 = createBroker("bs2", secondTcpUri); - bs2.start(); + bs2 = createBroker("bs2", secondTcpUri); + bs2.start(); - // add the transport uri for broker number 2 - out = new FileOutputStream(updateFile, true); - out.write(",".getBytes()); - out.write(secondTcpUri.toString().getBytes()); - out.close(); + // add the transport uri for broker number 2 + out = new FileOutputStream(updateFile, true); + out.write(",".getBytes()); + out.write(secondTcpUri.toString().getBytes()); + out.close(); - producer.send(message); - msg = consumer.receive(2000); - assertNotNull(msg); - } + producer.send(message); + msg = consumer.receive(2000); + assertNotNull(msg); + } - private BrokerService createBroker(String name, String tcpUri) throws Exception { - BrokerService bs = new BrokerService(); - bs.setBrokerName(name); - bs.setUseJmx(false); - bs.setPersistent(false); - bs.addConnector(tcpUri); - return bs; - } + private BrokerService createBroker(String name, String tcpUri) throws Exception { + BrokerService bs = new BrokerService(); + bs.setBrokerName(name); + bs.setUseJmx(false); + bs.setPersistent(false); + bs.addConnector(tcpUri); + return bs; + } - public void testAutoUpdateURIs() throws Exception { + public void testAutoUpdateURIs() throws Exception { - bs1 = new BrokerService(); - bs1.setUseJmx(false); - TransportConnector transportConnector = bs1.addConnector(firstTcpUri); - transportConnector.setUpdateClusterClients(true); - bs1.start(); + bs1 = new BrokerService(); + bs1.setUseJmx(false); + TransportConnector transportConnector = bs1.addConnector(firstTcpUri); + transportConnector.setUpdateClusterClients(true); + bs1.start(); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + firstTcpUri + ")"); - connection = cf.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue theQueue = session.createQueue(QUEUE_NAME); - MessageProducer producer = session.createProducer(theQueue); - MessageConsumer consumer = session.createConsumer(theQueue); - Message message = session.createTextMessage("Test message"); - producer.send(message); - Message msg = consumer.receive(4000); - assertNotNull(msg); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + firstTcpUri + ")"); + connection = cf.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue theQueue = session.createQueue(QUEUE_NAME); + MessageProducer producer = session.createProducer(theQueue); + MessageConsumer consumer = session.createConsumer(theQueue); + Message message = session.createTextMessage("Test message"); + producer.send(message); + Message msg = consumer.receive(4000); + assertNotNull(msg); - bs2 = createBroker("bs2", secondTcpUri); - NetworkConnector networkConnector = bs2.addNetworkConnector("static:(" + firstTcpUri + ")"); - networkConnector.setDuplex(true); - bs2.start(); - LOG.info("started brokerService 2"); - bs2.waitUntilStarted(); + bs2 = createBroker("bs2", secondTcpUri); + NetworkConnector networkConnector = bs2.addNetworkConnector("static:(" + firstTcpUri + ")"); + networkConnector.setDuplex(true); + bs2.start(); + LOG.info("started brokerService 2"); + bs2.waitUntilStarted(); - TimeUnit.SECONDS.sleep(4); + TimeUnit.SECONDS.sleep(4); - LOG.info("stopping brokerService 1"); - bs1.stop(); - bs1.waitUntilStopped(); - bs1 = null; + LOG.info("stopping brokerService 1"); + bs1.stop(); + bs1.waitUntilStopped(); + bs1 = null; - producer.send(message); - msg = consumer.receive(4000); - assertNotNull(msg); - } + producer.send(message); + msg = consumer.receive(4000); + assertNotNull(msg); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverUriTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverUriTest.java index 01a8966e0c..ae637ef837 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverUriTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/FailoverUriTest.java @@ -22,27 +22,25 @@ import org.apache.activemq.transport.tcp.TransportUriTest; public class FailoverUriTest extends TransportUriTest { - @Override - public void initCombosForTestUriOptionsWork() { - addCombinationValues("prefix", new Object[]{"failover:(", "failover://("}); - addCombinationValues("postfix", new Object[] {")?initialReconnectDelay=1000&maxReconnectDelay=1000" - , "?wireFormat.tightEncodingEnabled=false)?jms.useAsyncSend=true&jms.copyMessageOnSend=false" - , "?wireFormat.maxInactivityDuration=0&keepAlive=true)?jms.prefetchPolicy.all=500&initialReconnectDelay=10000&useExponentialBackOff=false&maxReconnectAttempts=0&randomize=false"}); - } + @Override + public void initCombosForTestUriOptionsWork() { + addCombinationValues("prefix", new Object[]{"failover:(", "failover://("}); + addCombinationValues("postfix", new Object[]{")?initialReconnectDelay=1000&maxReconnectDelay=1000", "?wireFormat.tightEncodingEnabled=false)?jms.useAsyncSend=true&jms.copyMessageOnSend=false", "?wireFormat.maxInactivityDuration=0&keepAlive=true)?jms.prefetchPolicy.all=500&initialReconnectDelay=10000&useExponentialBackOff=false&maxReconnectAttempts=0&randomize=false"}); + } - @Override - public void initCombosForTestBadVersionNumberDoesNotWork() { - addCombinationValues("prefix", new Object[]{"failover:("}); - addCombinationValues("postfix", new Object[] {")?initialReconnectDelay=1000&maxReconnectDelay=1000"}); - } + @Override + public void initCombosForTestBadVersionNumberDoesNotWork() { + addCombinationValues("prefix", new Object[]{"failover:("}); + addCombinationValues("postfix", new Object[]{")?initialReconnectDelay=1000&maxReconnectDelay=1000"}); + } - @Override - public void initCombosForTestBadPropertyNameFails() { - addCombinationValues("prefix", new Object[]{"failover:("}); - addCombinationValues("postfix", new Object[] {")?initialReconnectDelay=1000&maxReconnectDelay=1000"}); - } + @Override + public void initCombosForTestBadPropertyNameFails() { + addCombinationValues("prefix", new Object[]{"failover:("}); + addCombinationValues("postfix", new Object[]{")?initialReconnectDelay=1000&maxReconnectDelay=1000"}); + } - public static Test suite() { - return suite(FailoverUriTest.class); - } + public static Test suite() { + return suite(FailoverUriTest.class); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/InitalReconnectDelayTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/InitalReconnectDelayTest.java index 8fe8c08f53..34e73333bd 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/InitalReconnectDelayTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/InitalReconnectDelayTest.java @@ -24,6 +24,7 @@ import javax.jms.Message; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.transport.TransportListener; @@ -33,155 +34,154 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import static org.junit.Assert.*; public class InitalReconnectDelayTest { - private static final transient Logger LOG = LoggerFactory.getLogger(InitalReconnectDelayTest.class); - protected BrokerService broker1; - protected BrokerService broker2; + private static final transient Logger LOG = LoggerFactory.getLogger(InitalReconnectDelayTest.class); + protected BrokerService broker1; + protected BrokerService broker2; - @Test - public void testInitialReconnectDelay() throws Exception { + @Test + public void testInitialReconnectDelay() throws Exception { - String uriString = "failover://(tcp://localhost:" + - broker1.getTransportConnectors().get(0).getConnectUri().getPort() + - ",tcp://localhost:" + - broker2.getTransportConnectors().get(0).getConnectUri().getPort() + - ")?randomize=false&initialReconnectDelay=15000"; + String uriString = "failover://(tcp://localhost:" + + broker1.getTransportConnectors().get(0).getConnectUri().getPort() + + ",tcp://localhost:" + + broker2.getTransportConnectors().get(0).getConnectUri().getPort() + + ")?randomize=false&initialReconnectDelay=15000"; - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(uriString); - Connection connection = connectionFactory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue destination = session.createQueue("foo"); - MessageProducer producer = session.createProducer(destination); + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(uriString); + Connection connection = connectionFactory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue destination = session.createQueue("foo"); + MessageProducer producer = session.createProducer(destination); - long start = (new Date()).getTime(); - producer.send(session.createTextMessage("TEST")); - long end = (new Date()).getTime(); + long start = (new Date()).getTime(); + producer.send(session.createTextMessage("TEST")); + long end = (new Date()).getTime(); - //Verify we can send quickly - assertTrue((end - start) < 2000); + //Verify we can send quickly + assertTrue((end - start) < 2000); - //Halt the broker1... - LOG.info("Stopping the Broker1..."); - start = (new Date()).getTime(); - broker1.stop(); + //Halt the broker1... + LOG.info("Stopping the Broker1..."); + start = (new Date()).getTime(); + broker1.stop(); - LOG.info("Attempting to send... failover should kick in..."); - producer.send(session.createTextMessage("TEST")); - end = (new Date()).getTime(); + LOG.info("Attempting to send... failover should kick in..."); + producer.send(session.createTextMessage("TEST")); + end = (new Date()).getTime(); - //Inital reconnection should kick in and be darned close to what we expected - LOG.info("Failover took " + (end - start) + " ms."); - assertTrue("Failover took " + (end - start) + " ms and should be > 14000.", (end - start) > 14000); - } + //Inital reconnection should kick in and be darned close to what we expected + LOG.info("Failover took " + (end - start) + " ms."); + assertTrue("Failover took " + (end - start) + " ms and should be > 14000.", (end - start) > 14000); + } - @Test - public void testNoSuspendedCallbackOnNoReconnect() throws Exception { + @Test + public void testNoSuspendedCallbackOnNoReconnect() throws Exception { - String uriString = "failover://(tcp://localhost:" + - broker1.getTransportConnectors().get(0).getConnectUri().getPort() + - ",tcp://localhost:" + - broker2.getTransportConnectors().get(0).getConnectUri().getPort() + - ")?randomize=false&maxReconnectAttempts=0"; + String uriString = "failover://(tcp://localhost:" + + broker1.getTransportConnectors().get(0).getConnectUri().getPort() + + ",tcp://localhost:" + + broker2.getTransportConnectors().get(0).getConnectUri().getPort() + + ")?randomize=false&maxReconnectAttempts=0"; + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(uriString); + final AtomicInteger calls = new AtomicInteger(0); + connectionFactory.setTransportListener(new TransportListener() { + @Override + public void onCommand(Object command) { + } - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(uriString); - final AtomicInteger calls = new AtomicInteger(0); - connectionFactory.setTransportListener(new TransportListener() { - @Override - public void onCommand(Object command) { - } + @Override + public void onException(IOException error) { + LOG.info("on exception: " + error); + calls.set(0x01 | calls.intValue()); + } - @Override - public void onException(IOException error) { - LOG.info("on exception: " + error); - calls.set(0x01 | calls.intValue()); - } + @Override + public void transportInterupted() { + LOG.info("on transportInterupted"); + calls.set(0x02 | calls.intValue()); + } - @Override - public void transportInterupted() { - LOG.info("on transportInterupted"); - calls.set(0x02 | calls.intValue()); - } + @Override + public void transportResumed() { + LOG.info("on transportResumed"); + calls.set(0x04 | calls.intValue()); + } + }); + Connection connection = connectionFactory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue destination = session.createQueue("foo"); + MessageProducer producer = session.createProducer(destination); - @Override - public void transportResumed() { - LOG.info("on transportResumed"); - calls.set(0x04 | calls.intValue()); - } - }); - Connection connection = connectionFactory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue destination = session.createQueue("foo"); - MessageProducer producer = session.createProducer(destination); + final Message message = session.createTextMessage("TEST"); + producer.send(message); - final Message message = session.createTextMessage("TEST"); - producer.send(message); + // clear listener state + calls.set(0); - // clear listener state - calls.set(0); + LOG.info("Stopping the Broker1..."); + broker1.stop(); - LOG.info("Stopping the Broker1..."); - broker1.stop(); + LOG.info("Attempting to send... failover should throw on disconnect"); + try { + producer.send(destination, message); + fail("Expect IOException to bubble up on send"); + } + catch (javax.jms.IllegalStateException producerClosed) { + } - LOG.info("Attempting to send... failover should throw on disconnect"); - try { - producer.send(destination, message); - fail("Expect IOException to bubble up on send"); - } catch (javax.jms.IllegalStateException producerClosed) { - } + assertEquals("Only an exception is reported to the listener", 0x1, calls.get()); + } - assertEquals("Only an exception is reported to the listener", 0x1, calls.get()); - } + @Before + public void setUp() throws Exception { - @Before - public void setUp() throws Exception { + final String dataDir = "target/data/shared"; - final String dataDir = "target/data/shared"; + broker1 = new BrokerService(); - broker1 = new BrokerService(); + broker1.setBrokerName("broker1"); + broker1.setDeleteAllMessagesOnStartup(true); + broker1.setDataDirectory(dataDir); + broker1.addConnector("tcp://localhost:0"); + broker1.setUseJmx(false); + broker1.start(); + broker1.waitUntilStarted(); - broker1.setBrokerName("broker1"); - broker1.setDeleteAllMessagesOnStartup(true); - broker1.setDataDirectory(dataDir); - broker1.addConnector("tcp://localhost:0"); - broker1.setUseJmx(false); - broker1.start(); - broker1.waitUntilStarted(); + broker2 = new BrokerService(); + broker2.setBrokerName("broker2"); + broker2.setDataDirectory(dataDir); + broker2.setUseJmx(false); + broker2.addConnector("tcp://localhost:0"); + broker2.start(); + broker2.waitUntilStarted(); - broker2 = new BrokerService(); - broker2.setBrokerName("broker2"); - broker2.setDataDirectory(dataDir); - broker2.setUseJmx(false); - broker2.addConnector("tcp://localhost:0"); - broker2.start(); - broker2.waitUntilStarted(); + } - } + protected String getSlaveXml() { + return "org/apache/activemq/broker/ft/sharedFileSlave.xml"; + } - protected String getSlaveXml() { - return "org/apache/activemq/broker/ft/sharedFileSlave.xml"; - } + protected String getMasterXml() { + return "org/apache/activemq/broker/ft/sharedFileMaster.xml"; + } - protected String getMasterXml() { - return "org/apache/activemq/broker/ft/sharedFileMaster.xml"; - } + @After + public void tearDown() throws Exception { - @After - public void tearDown() throws Exception { + if (broker1.isStarted()) { + broker1.stop(); + broker1.waitUntilStopped(); + } - if (broker1.isStarted()) { - broker1.stop(); - broker1.waitUntilStopped(); - } - - if (broker2.isStarted()) { - broker2.stop(); - broker2.waitUntilStopped(); - } - } + if (broker2.isStarted()) { + broker2.stop(); + broker2.waitUntilStopped(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/ReconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/ReconnectTest.java index 28031578e0..4f413604db 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/ReconnectTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/ReconnectTest.java @@ -28,7 +28,9 @@ import javax.jms.JMSException; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; + import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; @@ -43,190 +45,194 @@ import org.slf4j.LoggerFactory; public class ReconnectTest extends TestCase { - public static final int MESSAGES_PER_ITTERATION = 10; - public static final int WORKER_COUNT = 10; + public static final int MESSAGES_PER_ITTERATION = 10; + public static final int WORKER_COUNT = 10; - private static final Logger LOG = LoggerFactory.getLogger(ReconnectTest.class); + private static final Logger LOG = LoggerFactory.getLogger(ReconnectTest.class); - private BrokerService bs; - private URI tcpUri; - private final AtomicInteger resumedCount = new AtomicInteger(); - private final AtomicInteger interruptedCount = new AtomicInteger(); - private Worker[] workers; + private BrokerService bs; + private URI tcpUri; + private final AtomicInteger resumedCount = new AtomicInteger(); + private final AtomicInteger interruptedCount = new AtomicInteger(); + private Worker[] workers; - class Worker implements Runnable { + class Worker implements Runnable { - public AtomicInteger iterations = new AtomicInteger(); - public CountDownLatch stopped = new CountDownLatch(1); + public AtomicInteger iterations = new AtomicInteger(); + public CountDownLatch stopped = new CountDownLatch(1); - private final ActiveMQConnection connection; - private final AtomicBoolean stop = new AtomicBoolean(false); - private Throwable error; - private final String name; + private final ActiveMQConnection connection; + private final AtomicBoolean stop = new AtomicBoolean(false); + private Throwable error; + private final String name; - public Worker(final String name) throws URISyntaxException, JMSException { - this.name = name; - URI uri = new URI("failover://(mock://(" + tcpUri + "))?updateURIsSupported=false"); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(uri); - connection = (ActiveMQConnection) factory.createConnection(); - connection.addTransportListener(new TransportListener() { - public void onCommand(Object command) { - } - - public void onException(IOException error) { - setError(error); - } - - public void transportInterupted() { - LOG.info("Worker " + name + " was interrupted..."); - interruptedCount.incrementAndGet(); - } - - public void transportResumed() { - LOG.info("Worker " + name + " was resummed..."); - resumedCount.incrementAndGet(); - } - }); - connection.start(); - } - - public void failConnection() { - MockTransport mockTransport = connection.getTransportChannel().narrow(MockTransport.class); - mockTransport.onException(new IOException("Simulated error")); - } - - public void start() { - new Thread(this).start(); - } - - public void stop() { - stop.set(true); - try { - if (!stopped.await(5, TimeUnit.SECONDS)) { - connection.close(); - stopped.await(5, TimeUnit.SECONDS); - } else { - connection.close(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - public void run() { - try { - ActiveMQQueue queue = new ActiveMQQueue("FOO_" + name); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(queue); - MessageProducer producer = session.createProducer(queue); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - while (!stop.get()) { - for (int i = 0; i < MESSAGES_PER_ITTERATION; i++) { - producer.send(session.createTextMessage("TEST:" + i)); - } - for (int i = 0; i < MESSAGES_PER_ITTERATION; i++) { - consumer.receive(); - } - iterations.incrementAndGet(); - } - session.close(); - } catch (JMSException e) { - setError(e); - } finally { - stopped.countDown(); - } - } - - public synchronized Throwable getError() { - return error; - } - - public synchronized void setError(Throwable error) { - this.error = error; - } - - public synchronized void assertNoErrors() { - if (error != null) { - error.printStackTrace(); - fail("Worker " + name + " got Exception: " + error); - } - } - } - - public void testReconnects() throws Exception { - - for (int k = 1; k < 10; k++) { - LOG.info("Test run: " + k); - - // Wait for at least one iteration to occur... - for (int i = 0; i < WORKER_COUNT; i++) { - int c = 0; - for (int j = 0; j < 30; j++) { - c = workers[i].iterations.getAndSet(0); - if (c != 0) { - break; - } - workers[i].assertNoErrors(); - LOG.info("Test run " + k + ": Waiting for worker " + i + " to finish an iteration."); - Thread.sleep(1000); - } - assertTrue("Test run " + k + ": Worker " + i + " never completed an interation.", c != 0); - workers[i].assertNoErrors(); + public Worker(final String name) throws URISyntaxException, JMSException { + this.name = name; + URI uri = new URI("failover://(mock://(" + tcpUri + "))?updateURIsSupported=false"); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(uri); + connection = (ActiveMQConnection) factory.createConnection(); + connection.addTransportListener(new TransportListener() { + public void onCommand(Object command) { } - LOG.info("Simulating transport error to cause reconnect."); - - // Simulate a transport failure. - for (int i = 0; i < WORKER_COUNT; i++) { - workers[i].failConnection(); + public void onException(IOException error) { + setError(error); } - assertTrue("Timed out waiting for all connections to be interrupted.", Wait.waitFor(new Wait.Condition(){ - public boolean isSatisified() throws Exception { - LOG.debug("Test run waiting for connections to get interrupted.. at: " + interruptedCount.get()); - return interruptedCount.get() == WORKER_COUNT; - } - }, TimeUnit.SECONDS.toMillis(60))); - - // Wait for the connections to re-establish... - assertTrue("Timed out waiting for all connections to be resumed.", Wait.waitFor(new Wait.Condition(){ - public boolean isSatisified() throws Exception { - LOG.debug("Test run waiting for connections to get resumed.. at: " + resumedCount.get()); - return resumedCount.get() >= WORKER_COUNT; - } - }, TimeUnit.SECONDS.toMillis(60))); - - // Reset the counters.. - interruptedCount.set(0); - resumedCount.set(0); - for (int i = 0; i < WORKER_COUNT; i++) { - workers[i].iterations.set(0); + public void transportInterupted() { + LOG.info("Worker " + name + " was interrupted..."); + interruptedCount.incrementAndGet(); } - Thread.sleep(1000); - } - } + public void transportResumed() { + LOG.info("Worker " + name + " was resummed..."); + resumedCount.incrementAndGet(); + } + }); + connection.start(); + } - @Override - protected void setUp() throws Exception { - bs = new BrokerService(); - bs.setPersistent(false); - bs.setUseJmx(true); - TransportConnector connector = bs.addConnector("tcp://localhost:0"); - bs.start(); - tcpUri = connector.getConnectUri(); - workers = new Worker[WORKER_COUNT]; - for (int i = 0; i < WORKER_COUNT; i++) { - workers[i] = new Worker("" + i); - workers[i].start(); - } - } + public void failConnection() { + MockTransport mockTransport = connection.getTransportChannel().narrow(MockTransport.class); + mockTransport.onException(new IOException("Simulated error")); + } - @Override - protected void tearDown() throws Exception { - for (int i = 0; i < WORKER_COUNT; i++) { - workers[i].stop(); - } - new ServiceStopper().stop(bs); - } + public void start() { + new Thread(this).start(); + } + + public void stop() { + stop.set(true); + try { + if (!stopped.await(5, TimeUnit.SECONDS)) { + connection.close(); + stopped.await(5, TimeUnit.SECONDS); + } + else { + connection.close(); + } + } + catch (Exception e) { + e.printStackTrace(); + } + } + + public void run() { + try { + ActiveMQQueue queue = new ActiveMQQueue("FOO_" + name); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(queue); + MessageProducer producer = session.createProducer(queue); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + while (!stop.get()) { + for (int i = 0; i < MESSAGES_PER_ITTERATION; i++) { + producer.send(session.createTextMessage("TEST:" + i)); + } + for (int i = 0; i < MESSAGES_PER_ITTERATION; i++) { + consumer.receive(); + } + iterations.incrementAndGet(); + } + session.close(); + } + catch (JMSException e) { + setError(e); + } + finally { + stopped.countDown(); + } + } + + public synchronized Throwable getError() { + return error; + } + + public synchronized void setError(Throwable error) { + this.error = error; + } + + public synchronized void assertNoErrors() { + if (error != null) { + error.printStackTrace(); + fail("Worker " + name + " got Exception: " + error); + } + } + } + + public void testReconnects() throws Exception { + + for (int k = 1; k < 10; k++) { + LOG.info("Test run: " + k); + + // Wait for at least one iteration to occur... + for (int i = 0; i < WORKER_COUNT; i++) { + int c = 0; + for (int j = 0; j < 30; j++) { + c = workers[i].iterations.getAndSet(0); + if (c != 0) { + break; + } + workers[i].assertNoErrors(); + LOG.info("Test run " + k + ": Waiting for worker " + i + " to finish an iteration."); + Thread.sleep(1000); + } + assertTrue("Test run " + k + ": Worker " + i + " never completed an interation.", c != 0); + workers[i].assertNoErrors(); + } + + LOG.info("Simulating transport error to cause reconnect."); + + // Simulate a transport failure. + for (int i = 0; i < WORKER_COUNT; i++) { + workers[i].failConnection(); + } + + assertTrue("Timed out waiting for all connections to be interrupted.", Wait.waitFor(new Wait.Condition() { + public boolean isSatisified() throws Exception { + LOG.debug("Test run waiting for connections to get interrupted.. at: " + interruptedCount.get()); + return interruptedCount.get() == WORKER_COUNT; + } + }, TimeUnit.SECONDS.toMillis(60))); + + // Wait for the connections to re-establish... + assertTrue("Timed out waiting for all connections to be resumed.", Wait.waitFor(new Wait.Condition() { + public boolean isSatisified() throws Exception { + LOG.debug("Test run waiting for connections to get resumed.. at: " + resumedCount.get()); + return resumedCount.get() >= WORKER_COUNT; + } + }, TimeUnit.SECONDS.toMillis(60))); + + // Reset the counters.. + interruptedCount.set(0); + resumedCount.set(0); + for (int i = 0; i < WORKER_COUNT; i++) { + workers[i].iterations.set(0); + } + + Thread.sleep(1000); + } + } + + @Override + protected void setUp() throws Exception { + bs = new BrokerService(); + bs.setPersistent(false); + bs.setUseJmx(true); + TransportConnector connector = bs.addConnector("tcp://localhost:0"); + bs.start(); + tcpUri = connector.getConnectUri(); + workers = new Worker[WORKER_COUNT]; + for (int i = 0; i < WORKER_COUNT; i++) { + workers[i] = new Worker("" + i); + workers[i].start(); + } + } + + @Override + protected void tearDown() throws Exception { + for (int i = 0; i < WORKER_COUNT; i++) { + workers[i].stop(); + } + new ServiceStopper().stop(bs); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/SlowConnectionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/SlowConnectionTest.java index 357e0fbcb7..10e3ce2a3e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/SlowConnectionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/SlowConnectionTest.java @@ -31,69 +31,89 @@ import org.apache.activemq.util.Wait; public class SlowConnectionTest extends TestCase { - private CountDownLatch socketReadyLatch = new CountDownLatch(1); + private CountDownLatch socketReadyLatch = new CountDownLatch(1); - public void testSlowConnection() throws Exception { + public void testSlowConnection() throws Exception { - MockBroker broker = new MockBroker(); - broker.start(); + MockBroker broker = new MockBroker(); + broker.start(); - socketReadyLatch.await(); - int timeout = 1000; - URI tcpUri = new URI("tcp://localhost:" + broker.ss.getLocalPort() + "?soTimeout=" + timeout + "&trace=true&connectionTimeout=" + timeout + "&wireFormat.maxInactivityDurationInitalDelay=" + timeout); + socketReadyLatch.await(); + int timeout = 1000; + URI tcpUri = new URI("tcp://localhost:" + broker.ss.getLocalPort() + "?soTimeout=" + timeout + "&trace=true&connectionTimeout=" + timeout + "&wireFormat.maxInactivityDurationInitalDelay=" + timeout); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + tcpUri + ")"); - final Connection connection = cf.createConnection(); - - new Thread(new Runnable() { - public void run() { - try { connection.start(); } catch (Throwable ignored) {} - } - }).start(); - - int count = 0; - assertTrue("Transport count: " + count + ", expected <= 1", Wait.waitFor(new Wait.Condition(){ - public boolean isSatisified() throws Exception { - int count = 0; - for (Thread thread : Thread.getAllStackTraces().keySet()) { - if (thread.getName().contains("ActiveMQ Transport")) { count++; } - } - return count == 1; - }})); - - broker.interrupt(); - broker.join(); - } - - class MockBroker extends Thread { - ServerSocket ss = null; - public MockBroker() { - super("MockBroker"); - } - - public void run() { - - List inProgress = new ArrayList(); - ServerSocketFactory factory = ServerSocketFactory.getDefault(); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + tcpUri + ")"); + final Connection connection = cf.createConnection(); + new Thread(new Runnable() { + public void run() { try { - ss = factory.createServerSocket(0); - ss.setSoTimeout(5000); - - socketReadyLatch.countDown(); - while (!interrupted()) { - inProgress.add(ss.accept()); // eat socket - } - } catch (java.net.SocketTimeoutException expected) { - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { ss.close(); } catch (IOException ignored) {} - for (Socket s : inProgress) { - try { s.close(); } catch (IOException ignored) {} - } + connection.start(); } - } - } + catch (Throwable ignored) { + } + } + }).start(); + + int count = 0; + assertTrue("Transport count: " + count + ", expected <= 1", Wait.waitFor(new Wait.Condition() { + public boolean isSatisified() throws Exception { + int count = 0; + for (Thread thread : Thread.getAllStackTraces().keySet()) { + if (thread.getName().contains("ActiveMQ Transport")) { + count++; + } + } + return count == 1; + } + })); + + broker.interrupt(); + broker.join(); + } + + class MockBroker extends Thread { + + ServerSocket ss = null; + + public MockBroker() { + super("MockBroker"); + } + + public void run() { + + List inProgress = new ArrayList(); + ServerSocketFactory factory = ServerSocketFactory.getDefault(); + + try { + ss = factory.createServerSocket(0); + ss.setSoTimeout(5000); + + socketReadyLatch.countDown(); + while (!interrupted()) { + inProgress.add(ss.accept()); // eat socket + } + } + catch (java.net.SocketTimeoutException expected) { + } + catch (Exception e) { + e.printStackTrace(); + } + finally { + try { + ss.close(); + } + catch (IOException ignored) { + } + for (Socket s : inProgress) { + try { + s.close(); + } + catch (IOException ignored) { + } + } + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/TwoBrokerFailoverClusterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/TwoBrokerFailoverClusterTest.java index 19addc3305..5016e302e8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/TwoBrokerFailoverClusterTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/failover/TwoBrokerFailoverClusterTest.java @@ -18,75 +18,81 @@ package org.apache.activemq.transport.failover; public class TwoBrokerFailoverClusterTest extends FailoverClusterTestSupport { - private static final String BROKER_A_CLIENT_TC_ADDRESS = "tcp://127.0.0.1:61616"; - private static final String BROKER_B_CLIENT_TC_ADDRESS = "tcp://127.0.0.1:61617"; - private static final String BROKER_A_NOB_TC_ADDRESS = "tcp://127.0.0.1:61626"; - private static final String BROKER_B_NOB_TC_ADDRESS = "tcp://127.0.0.1:61627"; - private static final String BROKER_A_NAME = "BROKERA"; - private static final String BROKER_B_NAME = "BROKERB"; + private static final String BROKER_A_CLIENT_TC_ADDRESS = "tcp://127.0.0.1:61616"; + private static final String BROKER_B_CLIENT_TC_ADDRESS = "tcp://127.0.0.1:61617"; + private static final String BROKER_A_NOB_TC_ADDRESS = "tcp://127.0.0.1:61626"; + private static final String BROKER_B_NOB_TC_ADDRESS = "tcp://127.0.0.1:61627"; + private static final String BROKER_A_NAME = "BROKERA"; + private static final String BROKER_B_NAME = "BROKERB"; - public void testTwoBrokersRestart() throws Exception { - createBrokerA(false, "", null, null); - createBrokerB(false, "", null, null); - getBroker(BROKER_B_NAME).waitUntilStarted(); + public void testTwoBrokersRestart() throws Exception { + createBrokerA(false, "", null, null); + createBrokerB(false, "", null, null); + getBroker(BROKER_B_NAME).waitUntilStarted(); - Thread.sleep(2000); - setClientUrl("failover://(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + ")"); - createClients(); + Thread.sleep(2000); + setClientUrl("failover://(" + BROKER_A_CLIENT_TC_ADDRESS + "," + BROKER_B_CLIENT_TC_ADDRESS + ")"); + createClients(); - Thread.sleep(5000); + Thread.sleep(5000); - assertClientsConnectedToTwoBrokers(); - assertClientsConnectionsEvenlyDistributed(.35); + assertClientsConnectedToTwoBrokers(); + assertClientsConnectionsEvenlyDistributed(.35); + getBroker(BROKER_A_NAME).stop(); + getBroker(BROKER_A_NAME).waitUntilStopped(); + removeBroker(BROKER_A_NAME); - getBroker(BROKER_A_NAME).stop(); - getBroker(BROKER_A_NAME).waitUntilStopped(); - removeBroker(BROKER_A_NAME); + Thread.sleep(1000); - Thread.sleep(1000); + assertAllConnectedTo(BROKER_B_CLIENT_TC_ADDRESS); - assertAllConnectedTo(BROKER_B_CLIENT_TC_ADDRESS); + Thread.sleep(5000); - Thread.sleep(5000); + createBrokerA(false, "", null, null); + getBroker(BROKER_A_NAME).waitUntilStarted(); + Thread.sleep(5000); - createBrokerA(false, "", null, null); - getBroker(BROKER_A_NAME).waitUntilStarted(); - Thread.sleep(5000); + assertClientsConnectedToTwoBrokers(); + assertClientsConnectionsEvenlyDistributed(.35); + } - assertClientsConnectedToTwoBrokers(); - assertClientsConnectionsEvenlyDistributed(.35); - } + private void createBrokerA(boolean multi, + String params, + String clusterFilter, + String destinationFilter) throws Exception { + final String tcParams = (params == null) ? "" : params; + if (getBroker(BROKER_A_NAME) == null) { + addBroker(BROKER_A_NAME, createBroker(BROKER_A_NAME)); + addTransportConnector(getBroker(BROKER_A_NAME), "openwire", BROKER_A_CLIENT_TC_ADDRESS + tcParams, true); + if (multi) { + addTransportConnector(getBroker(BROKER_A_NAME), "network", BROKER_A_NOB_TC_ADDRESS + tcParams, false); + addNetworkBridge(getBroker(BROKER_A_NAME), "A_2_B_Bridge", "static://(" + BROKER_B_NOB_TC_ADDRESS + ")?useExponentialBackOff=false", false, clusterFilter); + } + else { + addNetworkBridge(getBroker(BROKER_A_NAME), "A_2_B_Bridge", "static://(" + BROKER_B_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, clusterFilter); + } + getBroker(BROKER_A_NAME).start(); + } + } - - private void createBrokerA(boolean multi, String params, String clusterFilter, String destinationFilter) throws Exception { - final String tcParams = (params == null)?"":params; - if (getBroker(BROKER_A_NAME) == null) { - addBroker(BROKER_A_NAME, createBroker(BROKER_A_NAME)); - addTransportConnector(getBroker(BROKER_A_NAME), "openwire", BROKER_A_CLIENT_TC_ADDRESS + tcParams, true); - if (multi) { - addTransportConnector(getBroker(BROKER_A_NAME), "network", BROKER_A_NOB_TC_ADDRESS + tcParams, false); - addNetworkBridge(getBroker(BROKER_A_NAME), "A_2_B_Bridge", "static://(" + BROKER_B_NOB_TC_ADDRESS + ")?useExponentialBackOff=false", false, clusterFilter); - } else { - addNetworkBridge(getBroker(BROKER_A_NAME), "A_2_B_Bridge", "static://(" + BROKER_B_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, clusterFilter); - } - getBroker(BROKER_A_NAME).start(); - } - } - - private void createBrokerB(boolean multi, String params, String clusterFilter, String destinationFilter) throws Exception { - final String tcParams = (params == null)?"":params; - if (getBroker(BROKER_B_NAME) == null) { - addBroker(BROKER_B_NAME, createBroker(BROKER_B_NAME)); - addTransportConnector(getBroker(BROKER_B_NAME), "openwire", BROKER_B_CLIENT_TC_ADDRESS + tcParams, true); - if (multi) { - addTransportConnector(getBroker(BROKER_B_NAME), "network", BROKER_B_NOB_TC_ADDRESS + tcParams, false); - addNetworkBridge(getBroker(BROKER_B_NAME), "B_2_A_Bridge", "static://(" + BROKER_A_NOB_TC_ADDRESS + ")?useExponentialBackOff=false", false, clusterFilter); - } else { - addNetworkBridge(getBroker(BROKER_B_NAME), "B_2_A_Bridge", "static://(" + BROKER_A_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, clusterFilter); - } - getBroker(BROKER_B_NAME).start(); - } - } + private void createBrokerB(boolean multi, + String params, + String clusterFilter, + String destinationFilter) throws Exception { + final String tcParams = (params == null) ? "" : params; + if (getBroker(BROKER_B_NAME) == null) { + addBroker(BROKER_B_NAME, createBroker(BROKER_B_NAME)); + addTransportConnector(getBroker(BROKER_B_NAME), "openwire", BROKER_B_CLIENT_TC_ADDRESS + tcParams, true); + if (multi) { + addTransportConnector(getBroker(BROKER_B_NAME), "network", BROKER_B_NOB_TC_ADDRESS + tcParams, false); + addNetworkBridge(getBroker(BROKER_B_NAME), "B_2_A_Bridge", "static://(" + BROKER_A_NOB_TC_ADDRESS + ")?useExponentialBackOff=false", false, clusterFilter); + } + else { + addNetworkBridge(getBroker(BROKER_B_NAME), "B_2_A_Bridge", "static://(" + BROKER_A_CLIENT_TC_ADDRESS + ")?useExponentialBackOff=false", false, clusterFilter); + } + getBroker(BROKER_B_NAME).start(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/fanout/FanoutTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/fanout/FanoutTest.java index 62104d49de..c97c9f4867 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/fanout/FanoutTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/fanout/FanoutTest.java @@ -32,66 +32,68 @@ import org.apache.activemq.util.MessageIdList; public class FanoutTest extends TestCase { - BrokerService broker1; - BrokerService broker2; - - ActiveMQConnectionFactory producerFactory = new ActiveMQConnectionFactory("fanout:(static:(tcp://localhost:61616,tcp://localhost:61617))?fanOutQueues=true"); - Connection producerConnection; - Session producerSession; - int messageCount = 100; + BrokerService broker1; + BrokerService broker2; - public void setUp() throws Exception { - broker1 = BrokerFactory.createBroker("broker:(tcp://localhost:61616)/brokerA?persistent=false&useJmx=false"); - broker2 = BrokerFactory.createBroker("broker:(tcp://localhost:61617)/brokerB?persistent=false&useJmx=false"); - - broker1.start(); - broker2.start(); - - broker1.waitUntilStarted(); - broker2.waitUntilStarted(); - - producerConnection = producerFactory.createConnection(); - producerConnection.start(); - producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } - - public void tearDown() throws Exception { - producerSession.close(); - producerConnection.close(); - - broker1.stop(); - broker2.stop(); - } - - public void testSendReceive() throws Exception { + ActiveMQConnectionFactory producerFactory = new ActiveMQConnectionFactory("fanout:(static:(tcp://localhost:61616,tcp://localhost:61617))?fanOutQueues=true"); + Connection producerConnection; + Session producerSession; + int messageCount = 100; - MessageProducer prod = createProducer(); - for (int i = 0; i < messageCount; i++) { - Message msg = producerSession.createTextMessage("Message " + i); - prod.send(msg); - } - prod.close(); - - assertMessagesReceived("tcp://localhost:61616"); - assertMessagesReceived("tcp://localhost:61617"); - - } - - protected MessageProducer createProducer() throws Exception { - return producerSession.createProducer(producerSession.createQueue("TEST")); - } - - protected void assertMessagesReceived(String brokerURL) throws Exception { - ActiveMQConnectionFactory consumerFactory = new ActiveMQConnectionFactory(brokerURL); - Connection consumerConnection = consumerFactory.createConnection(); - consumerConnection.start(); - Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = consumerSession.createConsumer(consumerSession.createQueue("TEST")); - MessageIdList listener = new MessageIdList(); - consumer.setMessageListener(listener); - listener.waitForMessagesToArrive(messageCount); - listener.assertMessagesReceived(messageCount); - - consumer.close(); consumerConnection.close(); consumerSession.close(); - } + public void setUp() throws Exception { + broker1 = BrokerFactory.createBroker("broker:(tcp://localhost:61616)/brokerA?persistent=false&useJmx=false"); + broker2 = BrokerFactory.createBroker("broker:(tcp://localhost:61617)/brokerB?persistent=false&useJmx=false"); + + broker1.start(); + broker2.start(); + + broker1.waitUntilStarted(); + broker2.waitUntilStarted(); + + producerConnection = producerFactory.createConnection(); + producerConnection.start(); + producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + } + + public void tearDown() throws Exception { + producerSession.close(); + producerConnection.close(); + + broker1.stop(); + broker2.stop(); + } + + public void testSendReceive() throws Exception { + + MessageProducer prod = createProducer(); + for (int i = 0; i < messageCount; i++) { + Message msg = producerSession.createTextMessage("Message " + i); + prod.send(msg); + } + prod.close(); + + assertMessagesReceived("tcp://localhost:61616"); + assertMessagesReceived("tcp://localhost:61617"); + + } + + protected MessageProducer createProducer() throws Exception { + return producerSession.createProducer(producerSession.createQueue("TEST")); + } + + protected void assertMessagesReceived(String brokerURL) throws Exception { + ActiveMQConnectionFactory consumerFactory = new ActiveMQConnectionFactory(brokerURL); + Connection consumerConnection = consumerFactory.createConnection(); + consumerConnection.start(); + Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = consumerSession.createConsumer(consumerSession.createQueue("TEST")); + MessageIdList listener = new MessageIdList(); + consumer.setMessageListener(listener); + listener.waitForMessagesToArrive(messageCount); + listener.assertMessagesReceived(messageCount); + + consumer.close(); + consumerConnection.close(); + consumerSession.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/fanout/FanoutTransportBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/fanout/FanoutTransportBrokerTest.java index f8236f51f9..bf770e385e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/fanout/FanoutTransportBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/fanout/FanoutTransportBrokerTest.java @@ -24,6 +24,7 @@ import java.util.concurrent.TimeUnit; import javax.jms.DeliveryMode; import junit.framework.Test; + import org.apache.activemq.broker.StubConnection; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; @@ -42,162 +43,163 @@ import org.slf4j.LoggerFactory; public class FanoutTransportBrokerTest extends NetworkTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(FanoutTransportBrokerTest.class); + private static final Logger LOG = LoggerFactory.getLogger(FanoutTransportBrokerTest.class); - public ActiveMQDestination destination; - public int deliveryMode; + public ActiveMQDestination destination; + public int deliveryMode; - public static Test suite() { - return suite(FanoutTransportBrokerTest.class); - } + public static Test suite() { + return suite(FanoutTransportBrokerTest.class); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - public void initCombosForTestPublisherFansout() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destination", new Object[] {new ActiveMQTopic("TEST"), new ActiveMQQueue("TEST")}); - } + public void initCombosForTestPublisherFansout() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destination", new Object[]{new ActiveMQTopic("TEST"), new ActiveMQQueue("TEST")}); + } - public void testPublisherFansout() throws Exception { + public void testPublisherFansout() throws Exception { - // Start a normal consumer on the local broker - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.request(consumerInfo1); + // Start a normal consumer on the local broker + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.request(consumerInfo1); - // Start a normal consumer on a remote broker - StubConnection connection2 = createRemoteConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.request(consumerInfo2); + // Start a normal consumer on a remote broker + StubConnection connection2 = createRemoteConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + connection2.request(consumerInfo2); - // Start a fanout publisher. - LOG.info("Starting the fanout connection."); - StubConnection connection3 = createFanoutConnection(); - ConnectionInfo connectionInfo3 = createConnectionInfo(); - SessionInfo sessionInfo3 = createSessionInfo(connectionInfo3); - ProducerInfo producerInfo3 = createProducerInfo(sessionInfo3); - connection3.send(connectionInfo3); - connection3.send(sessionInfo3); - connection3.send(producerInfo3); + // Start a fanout publisher. + LOG.info("Starting the fanout connection."); + StubConnection connection3 = createFanoutConnection(); + ConnectionInfo connectionInfo3 = createConnectionInfo(); + SessionInfo sessionInfo3 = createSessionInfo(connectionInfo3); + ProducerInfo producerInfo3 = createProducerInfo(sessionInfo3); + connection3.send(connectionInfo3); + connection3.send(sessionInfo3); + connection3.send(producerInfo3); - // Send the message using the fail over publisher. - connection3.request(createMessage(producerInfo3, destination, deliveryMode)); + // Send the message using the fail over publisher. + connection3.request(createMessage(producerInfo3, destination, deliveryMode)); - assertNotNull(receiveMessage(connection1)); - assertNoMessagesLeft(connection1); + assertNotNull(receiveMessage(connection1)); + assertNoMessagesLeft(connection1); - assertNotNull(receiveMessage(connection2)); - assertNoMessagesLeft(connection2); + assertNotNull(receiveMessage(connection2)); + assertNoMessagesLeft(connection2); - } + } - public void initCombosForTestPublisherWaitsForServerToBeUp() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destination", new Object[] {new ActiveMQTopic("TEST")}); - } + public void initCombosForTestPublisherWaitsForServerToBeUp() { + addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destination", new Object[]{new ActiveMQTopic("TEST")}); + } - public void testPublisherWaitsForServerToBeUp() throws Exception { + public void testPublisherWaitsForServerToBeUp() throws Exception { - // Start a normal consumer on the local broker - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.request(consumerInfo1); + // Start a normal consumer on the local broker + StubConnection connection1 = createConnection(); + ConnectionInfo connectionInfo1 = createConnectionInfo(); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); + connection1.send(connectionInfo1); + connection1.send(sessionInfo1); + connection1.request(consumerInfo1); - // Start a normal consumer on a remote broker - StubConnection connection2 = createRemoteConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.request(consumerInfo2); + // Start a normal consumer on a remote broker + StubConnection connection2 = createRemoteConnection(); + ConnectionInfo connectionInfo2 = createConnectionInfo(); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); + connection2.send(connectionInfo2); + connection2.send(sessionInfo2); + connection2.request(consumerInfo2); - // Start a fanout publisher. - LOG.info("Starting the fanout connection."); - final StubConnection connection3 = createFanoutConnection(); - ConnectionInfo connectionInfo3 = createConnectionInfo(); - SessionInfo sessionInfo3 = createSessionInfo(connectionInfo3); - final ProducerInfo producerInfo3 = createProducerInfo(sessionInfo3); - connection3.send(connectionInfo3); - connection3.send(sessionInfo3); - connection3.send(producerInfo3); + // Start a fanout publisher. + LOG.info("Starting the fanout connection."); + final StubConnection connection3 = createFanoutConnection(); + ConnectionInfo connectionInfo3 = createConnectionInfo(); + SessionInfo sessionInfo3 = createSessionInfo(connectionInfo3); + final ProducerInfo producerInfo3 = createProducerInfo(sessionInfo3); + connection3.send(connectionInfo3); + connection3.send(sessionInfo3); + connection3.send(producerInfo3); - // Send the message using the fail over publisher. - connection3.request(createMessage(producerInfo3, destination, deliveryMode)); + // Send the message using the fail over publisher. + connection3.request(createMessage(producerInfo3, destination, deliveryMode)); - assertNotNull(receiveMessage(connection1)); - assertNoMessagesLeft(connection1); + assertNotNull(receiveMessage(connection1)); + assertNoMessagesLeft(connection1); - assertNotNull(receiveMessage(connection2)); - assertNoMessagesLeft(connection2); + assertNotNull(receiveMessage(connection2)); + assertNoMessagesLeft(connection2); - final CountDownLatch publishDone = new CountDownLatch(1); + final CountDownLatch publishDone = new CountDownLatch(1); - // The MockTransport is on the remote connection. - // Slip in a new transport filter after the MockTransport - MockTransport mt = (MockTransport)connection3.getTransport().narrow(MockTransport.class); - mt.install(new TransportFilter(mt.getNext()) { - public void oneway(Object command) throws IOException { - LOG.info("Dropping: " + command); - // just eat it! to simulate a recent failure. + // The MockTransport is on the remote connection. + // Slip in a new transport filter after the MockTransport + MockTransport mt = (MockTransport) connection3.getTransport().narrow(MockTransport.class); + mt.install(new TransportFilter(mt.getNext()) { + public void oneway(Object command) throws IOException { + LOG.info("Dropping: " + command); + // just eat it! to simulate a recent failure. + } + }); + + // Send a message (async) as this will block + new Thread() { + public void run() { + // Send the message using the fail over publisher. + try { + connection3.request(createMessage(producerInfo3, destination, deliveryMode)); } - }); - - // Send a message (async) as this will block - new Thread() { - public void run() { - // Send the message using the fail over publisher. - try { - connection3.request(createMessage(producerInfo3, destination, deliveryMode)); - } catch (Throwable e) { - e.printStackTrace(); - } - publishDone.countDown(); + catch (Throwable e) { + e.printStackTrace(); } - }.start(); + publishDone.countDown(); + } + }.start(); - // Assert that we block: - assertFalse(publishDone.await(3, TimeUnit.SECONDS)); + // Assert that we block: + assertFalse(publishDone.await(3, TimeUnit.SECONDS)); - // Restart the remote server. State should be re-played and the publish - // should continue. - LOG.info("Restarting Broker"); - restartRemoteBroker(); - LOG.info("Broker Restarted"); + // Restart the remote server. State should be re-played and the publish + // should continue. + LOG.info("Restarting Broker"); + restartRemoteBroker(); + LOG.info("Broker Restarted"); - // This should reconnect, and resend - assertTrue(publishDone.await(20, TimeUnit.SECONDS)); + // This should reconnect, and resend + assertTrue(publishDone.await(20, TimeUnit.SECONDS)); - } + } - protected String getLocalURI() { - return "tcp://localhost:61616"; - } + protected String getLocalURI() { + return "tcp://localhost:61616"; + } - protected String getRemoteURI() { - return "tcp://localhost:61617"; - } + protected String getRemoteURI() { + return "tcp://localhost:61617"; + } - protected StubConnection createFanoutConnection() throws Exception { - URI fanoutURI = new URI("fanout://(static://(" + connector.getServer().getConnectURI() + "," + "mock://" + remoteConnector.getServer().getConnectURI() + "))?fanOutQueues=true"); - Transport transport = TransportFactory.connect(fanoutURI); - StubConnection connection = new StubConnection(transport); - connections.add(connection); - return connection; - } + protected StubConnection createFanoutConnection() throws Exception { + URI fanoutURI = new URI("fanout://(static://(" + connector.getServer().getConnectURI() + "," + "mock://" + remoteConnector.getServer().getConnectURI() + "))?fanOutQueues=true"); + Transport transport = TransportFactory.connect(fanoutURI); + StubConnection connection = new StubConnection(transport); + connections.add(connection); + return connection; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/multicast/MulticastTransportTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/multicast/MulticastTransportTest.java index a4ca8a2c57..0d897f9bb6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/multicast/MulticastTransportTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/multicast/MulticastTransportTest.java @@ -28,44 +28,43 @@ import org.slf4j.LoggerFactory; /** * - * + * */ public class MulticastTransportTest extends UdpTransportTest { - - private static final Logger LOG = LoggerFactory.getLogger(MulticastTransportTest.class); - private String multicastURI = "multicast://224.1.2.3:6255"; - + private static final Logger LOG = LoggerFactory.getLogger(MulticastTransportTest.class); - protected Transport createProducer() throws Exception { - LOG.info("Producer using URI: " + multicastURI); - - // we are not using the TransportFactory as this assumes that - // transports talk to a server using a WireFormat Negotiation step - // rather than talking directly to each other - - OpenWireFormat wireFormat = createWireFormat(); - MulticastTransport transport = new MulticastTransport(wireFormat, new URI(multicastURI)); - transport.setLoopBackMode(false); - transport.setSequenceGenerator(new IntSequenceGenerator()); - return new CommandJoiner(transport, wireFormat); - } + private String multicastURI = "multicast://224.1.2.3:6255"; - protected Transport createConsumer() throws Exception { - OpenWireFormat wireFormat = createWireFormat(); - MulticastTransport transport = new MulticastTransport(wireFormat, new URI(multicastURI)); - transport.setLoopBackMode(false); - transport.setSequenceGenerator(new IntSequenceGenerator()); - return new CommandJoiner(transport, wireFormat); - } + protected Transport createProducer() throws Exception { + LOG.info("Producer using URI: " + multicastURI); - @Override - public void testSendingMediumMessage() throws Exception { - // Ignoring, see AMQ-4973 - } + // we are not using the TransportFactory as this assumes that + // transports talk to a server using a WireFormat Negotiation step + // rather than talking directly to each other - @Override - public void testSendingLargeMessage() throws Exception { - // Ignoring, see AMQ-4973 - } + OpenWireFormat wireFormat = createWireFormat(); + MulticastTransport transport = new MulticastTransport(wireFormat, new URI(multicastURI)); + transport.setLoopBackMode(false); + transport.setSequenceGenerator(new IntSequenceGenerator()); + return new CommandJoiner(transport, wireFormat); + } + + protected Transport createConsumer() throws Exception { + OpenWireFormat wireFormat = createWireFormat(); + MulticastTransport transport = new MulticastTransport(wireFormat, new URI(multicastURI)); + transport.setLoopBackMode(false); + transport.setSequenceGenerator(new IntSequenceGenerator()); + return new CommandJoiner(transport, wireFormat); + } + + @Override + public void testSendingMediumMessage() throws Exception { + // Ignoring, see AMQ-4973 + } + + @Override + public void testSendingLargeMessage() throws Exception { + // Ignoring, see AMQ-4973 + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOJmsDurableTopicSendReceiveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOJmsDurableTopicSendReceiveTest.java index 84f955e2bb..aeca0de6eb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOJmsDurableTopicSendReceiveTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOJmsDurableTopicSendReceiveTest.java @@ -21,36 +21,37 @@ import org.apache.activemq.JmsDurableTopicSendReceiveTest; import org.apache.activemq.broker.BrokerService; public class NIOJmsDurableTopicSendReceiveTest extends JmsDurableTopicSendReceiveTest { - protected BrokerService broker; - protected void setUp() throws Exception { - if (broker == null) { - broker = createBroker(); - broker.start(); - } - super.setUp(); - } + protected BrokerService broker; - protected void tearDown() throws Exception { - super.tearDown(); - if (broker != null) { - broker.stop(); - } - } + protected void setUp() throws Exception { + if (broker == null) { + broker = createBroker(); + broker.start(); + } + super.setUp(); + } - protected ActiveMQConnectionFactory createConnectionFactory() { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(getBrokerURL()); - return connectionFactory; - } + protected void tearDown() throws Exception { + super.tearDown(); + if (broker != null) { + broker.stop(); + } + } - protected String getBrokerURL() { - return "nio://localhost:61616"; - } + protected ActiveMQConnectionFactory createConnectionFactory() { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(getBrokerURL()); + return connectionFactory; + } - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setPersistent(false); - answer.addConnector(getBrokerURL()); - return answer; - } + protected String getBrokerURL() { + return "nio://localhost:61616"; + } + + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + answer.setPersistent(false); + answer.addConnector(getBrokerURL()); + return answer; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOJmsSendAndReceiveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOJmsSendAndReceiveTest.java index 0f1032cfe8..ea229334fa 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOJmsSendAndReceiveTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOJmsSendAndReceiveTest.java @@ -21,39 +21,40 @@ import org.apache.activemq.broker.BrokerService; import org.apache.activemq.test.JmsTopicSendReceiveWithTwoConnectionsTest; /** - * + * */ public class NIOJmsSendAndReceiveTest extends JmsTopicSendReceiveWithTwoConnectionsTest { - protected BrokerService broker; - protected void setUp() throws Exception { - if (broker == null) { - broker = createBroker(); - broker.start(); - } - super.setUp(); - } + protected BrokerService broker; - protected void tearDown() throws Exception { - super.tearDown(); - if (broker != null) { - broker.stop(); - } - } + protected void setUp() throws Exception { + if (broker == null) { + broker = createBroker(); + broker.start(); + } + super.setUp(); + } - protected ActiveMQConnectionFactory createConnectionFactory() { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(getBrokerURL()); - return connectionFactory; - } + protected void tearDown() throws Exception { + super.tearDown(); + if (broker != null) { + broker.stop(); + } + } - protected String getBrokerURL() { - return "nio://localhost:61616"; - } + protected ActiveMQConnectionFactory createConnectionFactory() { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(getBrokerURL()); + return connectionFactory; + } - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setPersistent(false); - answer.addConnector(getBrokerURL()); - return answer; - } + protected String getBrokerURL() { + return "nio://localhost:61616"; + } + + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + answer.setPersistent(false); + answer.addConnector(getBrokerURL()); + return answer; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOPersistentSendAndReceiveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOPersistentSendAndReceiveTest.java index 330557f907..cca6b6dcae 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOPersistentSendAndReceiveTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOPersistentSendAndReceiveTest.java @@ -21,18 +21,19 @@ import javax.jms.DeliveryMode; import org.apache.activemq.broker.BrokerService; public class NIOPersistentSendAndReceiveTest extends NIOJmsSendAndReceiveTest { - protected BrokerService broker; - protected void setUp() throws Exception { - this.topic = false; - this.deliveryMode = DeliveryMode.PERSISTENT; - super.setUp(); - } + protected BrokerService broker; - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setPersistent(true); - answer.addConnector(getBrokerURL()); - return answer; - } + protected void setUp() throws Exception { + this.topic = false; + this.deliveryMode = DeliveryMode.PERSISTENT; + super.setUp(); + } + + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + answer.setPersistent(true); + answer.addConnector(getBrokerURL()); + return answer; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOSSLBasicTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOSSLBasicTest.java index 885446df88..d27003b836 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOSSLBasicTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOSSLBasicTest.java @@ -35,81 +35,81 @@ import org.junit.Test; public class NIOSSLBasicTest { - public static final String KEYSTORE_TYPE = "jks"; - public static final String PASSWORD = "password"; - public static final String SERVER_KEYSTORE = "src/test/resources/org/apache/activemq/security/broker1.ks"; - public static final String TRUST_KEYSTORE = "src/test/resources/org/apache/activemq/security/broker1.ks"; + public static final String KEYSTORE_TYPE = "jks"; + public static final String PASSWORD = "password"; + public static final String SERVER_KEYSTORE = "src/test/resources/org/apache/activemq/security/broker1.ks"; + public static final String TRUST_KEYSTORE = "src/test/resources/org/apache/activemq/security/broker1.ks"; - public static final int MESSAGE_COUNT = 1000; + public static final int MESSAGE_COUNT = 1000; - @Before - public void before() throws Exception { - System.setProperty("javax.net.ssl.trustStore", TRUST_KEYSTORE); - System.setProperty("javax.net.ssl.trustStorePassword", PASSWORD); - System.setProperty("javax.net.ssl.trustStoreType", KEYSTORE_TYPE); - System.setProperty("javax.net.ssl.keyStore", SERVER_KEYSTORE); - System.setProperty("javax.net.ssl.keyStoreType", KEYSTORE_TYPE); - System.setProperty("javax.net.ssl.keyStorePassword", PASSWORD); - // Choose a value that's informative: ssl,handshake,data,trustmanager or all - //System.setProperty("javax.net.debug", "handshake"); - } + @Before + public void before() throws Exception { + System.setProperty("javax.net.ssl.trustStore", TRUST_KEYSTORE); + System.setProperty("javax.net.ssl.trustStorePassword", PASSWORD); + System.setProperty("javax.net.ssl.trustStoreType", KEYSTORE_TYPE); + System.setProperty("javax.net.ssl.keyStore", SERVER_KEYSTORE); + System.setProperty("javax.net.ssl.keyStoreType", KEYSTORE_TYPE); + System.setProperty("javax.net.ssl.keyStorePassword", PASSWORD); + // Choose a value that's informative: ssl,handshake,data,trustmanager or all + //System.setProperty("javax.net.debug", "handshake"); + } - @After - public void after() throws Exception { - } + @After + public void after() throws Exception { + } - public BrokerService createBroker(String connectorName, String connectorString) throws Exception { - BrokerService broker = new BrokerService(); - broker.setPersistent(false); - broker.setUseJmx(false); - TransportConnector connector = broker.addConnector(connectorString); - connector.setName(connectorName); - broker.start(); - broker.waitUntilStarted(); - return broker; - } + public BrokerService createBroker(String connectorName, String connectorString) throws Exception { + BrokerService broker = new BrokerService(); + broker.setPersistent(false); + broker.setUseJmx(false); + TransportConnector connector = broker.addConnector(connectorString); + connector.setName(connectorName); + broker.start(); + broker.waitUntilStarted(); + return broker; + } - public void stopBroker(BrokerService broker) throws Exception { - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - } + public void stopBroker(BrokerService broker) throws Exception { + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + } - @Test - public void basicConnector() throws Exception { - BrokerService broker = createBroker("nio+ssl", "nio+ssl://localhost:0?transport.needClientAuth=true"); - basicSendReceive("ssl://localhost:" + broker.getConnectorByName("nio+ssl").getConnectUri().getPort()); - stopBroker(broker); - } + @Test + public void basicConnector() throws Exception { + BrokerService broker = createBroker("nio+ssl", "nio+ssl://localhost:0?transport.needClientAuth=true"); + basicSendReceive("ssl://localhost:" + broker.getConnectorByName("nio+ssl").getConnectUri().getPort()); + stopBroker(broker); + } - @Test - public void enabledCipherSuites() throws Exception { - BrokerService broker = createBroker("nio+ssl", "nio+ssl://localhost:0?transport.needClientAuth=true&transport.enabledCipherSuites=SSL_RSA_WITH_RC4_128_SHA,SSL_DH_anon_WITH_3DES_EDE_CBC_SHA"); - basicSendReceive("ssl://localhost:" + broker.getConnectorByName("nio+ssl").getConnectUri().getPort()); - stopBroker(broker); - } + @Test + public void enabledCipherSuites() throws Exception { + BrokerService broker = createBroker("nio+ssl", "nio+ssl://localhost:0?transport.needClientAuth=true&transport.enabledCipherSuites=SSL_RSA_WITH_RC4_128_SHA,SSL_DH_anon_WITH_3DES_EDE_CBC_SHA"); + basicSendReceive("ssl://localhost:" + broker.getConnectorByName("nio+ssl").getConnectUri().getPort()); + stopBroker(broker); + } - @Test - public void enabledProtocols() throws Exception { - BrokerService broker = createBroker("nio+ssl", "nio+ssl://localhost:61616?transport.needClientAuth=true&transport.enabledProtocols=TLSv1,TLSv1.1,TLSv1.2"); - basicSendReceive("ssl://localhost:" + broker.getConnectorByName("nio+ssl").getConnectUri().getPort()); - stopBroker(broker); - } + @Test + public void enabledProtocols() throws Exception { + BrokerService broker = createBroker("nio+ssl", "nio+ssl://localhost:61616?transport.needClientAuth=true&transport.enabledProtocols=TLSv1,TLSv1.1,TLSv1.2"); + basicSendReceive("ssl://localhost:" + broker.getConnectorByName("nio+ssl").getConnectUri().getPort()); + stopBroker(broker); + } - public void basicSendReceive(String uri) throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(uri); - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - connection.start(); + public void basicSendReceive(String uri) throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(uri); + Connection connection = factory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + connection.start(); - String body = "hello world!"; - Queue destination = session.createQueue("TEST"); - MessageProducer producer = session.createProducer(destination); - producer.send(session.createTextMessage(body)); + String body = "hello world!"; + Queue destination = session.createQueue("TEST"); + MessageProducer producer = session.createProducer(destination); + producer.send(session.createTextMessage(body)); - MessageConsumer consumer = session.createConsumer(destination); - Message received = consumer.receive(2000); - TestCase.assertEquals(body, ((TextMessage)received).getText()); - } + MessageConsumer consumer = session.createConsumer(destination); + Message received = consumer.receive(2000); + TestCase.assertEquals(body, ((TextMessage) received).getText()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOSSLConcurrencyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOSSLConcurrencyTest.java index 1ade5165c0..e854f8a0fc 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOSSLConcurrencyTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOSSLConcurrencyTest.java @@ -35,217 +35,223 @@ import org.apache.activemq.util.Wait; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -@SuppressWarnings({ "javadoc" }) +@SuppressWarnings({"javadoc"}) public class NIOSSLConcurrencyTest extends TestCase { - BrokerService broker; - Connection connection; + BrokerService broker; + Connection connection; - public static final String KEYSTORE_TYPE = "jks"; - public static final String PASSWORD = "password"; - public static final String SERVER_KEYSTORE = "src/test/resources/server.keystore"; - public static final String TRUST_KEYSTORE = "src/test/resources/client.keystore"; + public static final String KEYSTORE_TYPE = "jks"; + public static final String PASSWORD = "password"; + public static final String SERVER_KEYSTORE = "src/test/resources/server.keystore"; + public static final String TRUST_KEYSTORE = "src/test/resources/client.keystore"; - public static final int PRODUCER_COUNT = 10; - public static final int CONSUMER_COUNT = 10; - public static final int MESSAGE_COUNT = 10000; - public static final int MESSAGE_SIZE = 4096; + public static final int PRODUCER_COUNT = 10; + public static final int CONSUMER_COUNT = 10; + public static final int MESSAGE_COUNT = 10000; + public static final int MESSAGE_SIZE = 4096; - final ConsumerThread[] consumers = new ConsumerThread[CONSUMER_COUNT]; - final Session[] producerSessions = new Session[PRODUCER_COUNT]; - final Session[] consumerSessions = new Session[CONSUMER_COUNT]; + final ConsumerThread[] consumers = new ConsumerThread[CONSUMER_COUNT]; + final Session[] producerSessions = new Session[PRODUCER_COUNT]; + final Session[] consumerSessions = new Session[CONSUMER_COUNT]; - byte[] messageData; - volatile boolean failed; + byte[] messageData; + volatile boolean failed; - @Override - protected void setUp() throws Exception { - System.setProperty("javax.net.ssl.trustStore", TRUST_KEYSTORE); - System.setProperty("javax.net.ssl.trustStorePassword", PASSWORD); - System.setProperty("javax.net.ssl.trustStoreType", KEYSTORE_TYPE); - System.setProperty("javax.net.ssl.keyStore", SERVER_KEYSTORE); - System.setProperty("javax.net.ssl.keyStoreType", KEYSTORE_TYPE); - System.setProperty("javax.net.ssl.keyStorePassword", PASSWORD); + @Override + protected void setUp() throws Exception { + System.setProperty("javax.net.ssl.trustStore", TRUST_KEYSTORE); + System.setProperty("javax.net.ssl.trustStorePassword", PASSWORD); + System.setProperty("javax.net.ssl.trustStoreType", KEYSTORE_TYPE); + System.setProperty("javax.net.ssl.keyStore", SERVER_KEYSTORE); + System.setProperty("javax.net.ssl.keyStoreType", KEYSTORE_TYPE); + System.setProperty("javax.net.ssl.keyStorePassword", PASSWORD); - broker = new BrokerService(); - broker.setPersistent(false); - broker.setUseJmx(false); - TransportConnector connector = broker.addConnector("nio+ssl://localhost:0?transport.needClientAuth=true&transport.enabledCipherSuites=SSL_RSA_WITH_RC4_128_SHA,SSL_DH_anon_WITH_3DES_EDE_CBC_SHA"); - broker.start(); - broker.waitUntilStarted(); + broker = new BrokerService(); + broker.setPersistent(false); + broker.setUseJmx(false); + TransportConnector connector = broker.addConnector("nio+ssl://localhost:0?transport.needClientAuth=true&transport.enabledCipherSuites=SSL_RSA_WITH_RC4_128_SHA,SSL_DH_anon_WITH_3DES_EDE_CBC_SHA"); + broker.start(); + broker.waitUntilStarted(); - failed = false; - messageData = new byte[MESSAGE_SIZE]; - for (int i = 0; i < MESSAGE_SIZE; i++) - { - messageData[i] = (byte) (i & 0xff); - } + failed = false; + messageData = new byte[MESSAGE_SIZE]; + for (int i = 0; i < MESSAGE_SIZE; i++) { + messageData[i] = (byte) (i & 0xff); + } - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("nio+ssl://localhost:" + connector.getConnectUri().getPort()); - connection = factory.createConnection(); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("nio+ssl://localhost:" + connector.getConnectUri().getPort()); + connection = factory.createConnection(); - for (int i = 0; i < PRODUCER_COUNT; i++) { - producerSessions[i] = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } + for (int i = 0; i < PRODUCER_COUNT; i++) { + producerSessions[i] = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + } - for (int i = 0; i < CONSUMER_COUNT; i++) { - consumerSessions[i] = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } + for (int i = 0; i < CONSUMER_COUNT; i++) { + consumerSessions[i] = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + } - connection.start(); - } + connection.start(); + } - @Override - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } + @Override + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + } - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - } + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + } - public void testLoad() throws Exception { - for (int i = 0; i < PRODUCER_COUNT; i++) { - Queue dest = producerSessions[i].createQueue("TEST" + i); - ProducerThread producer = new ProducerThread(producerSessions[i], dest); - producer.setMessageCount(MESSAGE_COUNT); - producer.start(); - } + public void testLoad() throws Exception { + for (int i = 0; i < PRODUCER_COUNT; i++) { + Queue dest = producerSessions[i].createQueue("TEST" + i); + ProducerThread producer = new ProducerThread(producerSessions[i], dest); + producer.setMessageCount(MESSAGE_COUNT); + producer.start(); + } - for (int i = 0; i < CONSUMER_COUNT; i++) { - Queue dest = consumerSessions[i].createQueue("TEST" + i); - ConsumerThread consumer = new ConsumerThread(consumerSessions[i], dest); - consumer.setMessageCount(MESSAGE_COUNT); - consumer.start(); - consumers[i] = consumer; - } + for (int i = 0; i < CONSUMER_COUNT; i++) { + Queue dest = consumerSessions[i].createQueue("TEST" + i); + ConsumerThread consumer = new ConsumerThread(consumerSessions[i], dest); + consumer.setMessageCount(MESSAGE_COUNT); + consumer.start(); + consumers[i] = consumer; + } - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return failed || getReceived() == PRODUCER_COUNT * MESSAGE_COUNT; + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return failed || getReceived() == PRODUCER_COUNT * MESSAGE_COUNT; + } + }, 120000); + + assertEquals(PRODUCER_COUNT * MESSAGE_COUNT, getReceived()); + + } + + protected int getReceived() { + int received = 0; + for (ConsumerThread consumer : consumers) { + received += consumer.getReceived(); + } + return received; + } + + private class ConsumerThread extends Thread { + + private final Logger LOG = LoggerFactory.getLogger(ConsumerThread.class); + + int messageCount = 1000; + int received = 0; + Destination dest; + Session sess; + boolean breakOnNull = true; + + public ConsumerThread(Session sess, Destination dest) { + this.dest = dest; + this.sess = sess; + } + + @Override + public void run() { + MessageConsumer consumer = null; + + try { + consumer = sess.createConsumer(dest); + while (received < messageCount) { + Message msg = consumer.receive(3000); + if (msg != null) { + LOG.info("Received test message: " + received++); + } + else { + if (breakOnNull) { + break; + } + } } - }, 120000); - - assertEquals(PRODUCER_COUNT * MESSAGE_COUNT, getReceived()); - - } - - protected int getReceived() { - int received = 0; - for (ConsumerThread consumer : consumers) { - received += consumer.getReceived(); - } - return received; - } - - private class ConsumerThread extends Thread { - - private final Logger LOG = LoggerFactory.getLogger(ConsumerThread.class); - - int messageCount = 1000; - int received = 0; - Destination dest; - Session sess; - boolean breakOnNull = true; - - public ConsumerThread(Session sess, Destination dest) { - this.dest = dest; - this.sess = sess; - } - - @Override - public void run() { - MessageConsumer consumer = null; - - try { - consumer = sess.createConsumer(dest); - while (received < messageCount) { - Message msg = consumer.receive(3000); - if (msg != null) { - LOG.info("Received test message: " + received++); - } else { - if (breakOnNull) { - break; - } - } - } - } catch (JMSException e) { - e.printStackTrace(); - failed = true; - } finally { - if (consumer != null) { - try { - consumer.close(); - } catch (JMSException e) { - e.printStackTrace(); - } - } + } + catch (JMSException e) { + e.printStackTrace(); + failed = true; + } + finally { + if (consumer != null) { + try { + consumer.close(); + } + catch (JMSException e) { + e.printStackTrace(); + } } - } + } + } - public int getReceived() { - return received; - } + public int getReceived() { + return received; + } - public void setMessageCount(int messageCount) { - this.messageCount = messageCount; - } - } + public void setMessageCount(int messageCount) { + this.messageCount = messageCount; + } + } - private class ProducerThread extends Thread { + private class ProducerThread extends Thread { - private final Logger LOG = LoggerFactory.getLogger(ProducerThread.class); + private final Logger LOG = LoggerFactory.getLogger(ProducerThread.class); - int messageCount = 1000; - Destination dest; - protected Session sess; - int sleep = 0; - int sentCount = 0; + int messageCount = 1000; + Destination dest; + protected Session sess; + int sleep = 0; + int sentCount = 0; - public ProducerThread(Session sess, Destination dest) { - this.dest = dest; - this.sess = sess; - } + public ProducerThread(Session sess, Destination dest) { + this.dest = dest; + this.sess = sess; + } - @Override - public void run() { - MessageProducer producer = null; - try { - producer = sess.createProducer(dest); - for (sentCount = 0; sentCount < messageCount; sentCount++) { - producer.send(createMessage(sentCount)); - LOG.info("Sent 'test message: " + sentCount + "'"); - if (sleep > 0) { - Thread.sleep(sleep); - } - } - } catch (Exception e) { - e.printStackTrace(); - failed = true; - } finally { - if (producer != null) { - try { - producer.close(); - } catch (JMSException e) { - e.printStackTrace(); - } - } + @Override + public void run() { + MessageProducer producer = null; + try { + producer = sess.createProducer(dest); + for (sentCount = 0; sentCount < messageCount; sentCount++) { + producer.send(createMessage(sentCount)); + LOG.info("Sent 'test message: " + sentCount + "'"); + if (sleep > 0) { + Thread.sleep(sleep); + } } - } + } + catch (Exception e) { + e.printStackTrace(); + failed = true; + } + finally { + if (producer != null) { + try { + producer.close(); + } + catch (JMSException e) { + e.printStackTrace(); + } + } + } + } - protected Message createMessage(int i) throws Exception { - BytesMessage b = sess.createBytesMessage(); - b.writeBytes(messageData); - return b; - } + protected Message createMessage(int i) throws Exception { + BytesMessage b = sess.createBytesMessage(); + b.writeBytes(messageData); + return b; + } - public void setMessageCount(int messageCount) { - this.messageCount = messageCount; - } + public void setMessageCount(int messageCount) { + this.messageCount = messageCount; + } - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOSSLLoadTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOSSLLoadTest.java index 698945c614..a3ce6e26f7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOSSLLoadTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOSSLLoadTest.java @@ -17,6 +17,7 @@ package org.apache.activemq.transport.nio; import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.TransportConnector; @@ -30,86 +31,86 @@ import javax.jms.Session; public class NIOSSLLoadTest extends TestCase { - BrokerService broker; - Connection connection; - Session session; + BrokerService broker; + Connection connection; + Session session; - public static final String KEYSTORE_TYPE = "jks"; - public static final String PASSWORD = "password"; - public static final String SERVER_KEYSTORE = "src/test/resources/server.keystore"; - public static final String TRUST_KEYSTORE = "src/test/resources/client.keystore"; + public static final String KEYSTORE_TYPE = "jks"; + public static final String PASSWORD = "password"; + public static final String SERVER_KEYSTORE = "src/test/resources/server.keystore"; + public static final String TRUST_KEYSTORE = "src/test/resources/client.keystore"; - public static final int PRODUCER_COUNT = 10; - public static final int CONSUMER_COUNT = 10; - public static final int MESSAGE_COUNT = 1000; + public static final int PRODUCER_COUNT = 10; + public static final int CONSUMER_COUNT = 10; + public static final int MESSAGE_COUNT = 1000; - final ConsumerThread[] consumers = new ConsumerThread[CONSUMER_COUNT]; + final ConsumerThread[] consumers = new ConsumerThread[CONSUMER_COUNT]; - @Override - protected void setUp() throws Exception { - System.setProperty("javax.net.ssl.trustStore", TRUST_KEYSTORE); - System.setProperty("javax.net.ssl.trustStorePassword", PASSWORD); - System.setProperty("javax.net.ssl.trustStoreType", KEYSTORE_TYPE); - System.setProperty("javax.net.ssl.keyStore", SERVER_KEYSTORE); - System.setProperty("javax.net.ssl.keyStoreType", KEYSTORE_TYPE); - System.setProperty("javax.net.ssl.keyStorePassword", PASSWORD); + @Override + protected void setUp() throws Exception { + System.setProperty("javax.net.ssl.trustStore", TRUST_KEYSTORE); + System.setProperty("javax.net.ssl.trustStorePassword", PASSWORD); + System.setProperty("javax.net.ssl.trustStoreType", KEYSTORE_TYPE); + System.setProperty("javax.net.ssl.keyStore", SERVER_KEYSTORE); + System.setProperty("javax.net.ssl.keyStoreType", KEYSTORE_TYPE); + System.setProperty("javax.net.ssl.keyStorePassword", PASSWORD); - broker = new BrokerService(); - broker.setPersistent(false); - broker.setUseJmx(false); - TransportConnector connector = broker.addConnector("nio+ssl://localhost:0?transport.needClientAuth=true&transport.enabledCipherSuites=SSL_RSA_WITH_RC4_128_SHA,SSL_DH_anon_WITH_3DES_EDE_CBC_SHA"); - broker.start(); - broker.waitUntilStarted(); + broker = new BrokerService(); + broker.setPersistent(false); + broker.setUseJmx(false); + TransportConnector connector = broker.addConnector("nio+ssl://localhost:0?transport.needClientAuth=true&transport.enabledCipherSuites=SSL_RSA_WITH_RC4_128_SHA,SSL_DH_anon_WITH_3DES_EDE_CBC_SHA"); + broker.start(); + broker.waitUntilStarted(); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("nio+ssl://localhost:" + connector.getConnectUri().getPort()); - connection = factory.createConnection(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - connection.start(); - } + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("nio+ssl://localhost:" + connector.getConnectUri().getPort()); + connection = factory.createConnection(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + connection.start(); + } - @Override - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } + @Override + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + } - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - } + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + } - public void testLoad() throws Exception { - Queue dest = session.createQueue("TEST"); - for (int i = 0; i < PRODUCER_COUNT; i++) { - ProducerThread producer = new ProducerThread(session, dest); - producer.setMessageCount(MESSAGE_COUNT); - producer.start(); - } + public void testLoad() throws Exception { + Queue dest = session.createQueue("TEST"); + for (int i = 0; i < PRODUCER_COUNT; i++) { + ProducerThread producer = new ProducerThread(session, dest); + producer.setMessageCount(MESSAGE_COUNT); + producer.start(); + } - for (int i = 0; i < CONSUMER_COUNT; i++) { - ConsumerThread consumer = new ConsumerThread(session, dest); - consumer.setMessageCount(MESSAGE_COUNT); - consumer.start(); - consumers[i] = consumer; - } + for (int i = 0; i < CONSUMER_COUNT; i++) { + ConsumerThread consumer = new ConsumerThread(session, dest); + consumer.setMessageCount(MESSAGE_COUNT); + consumer.start(); + consumers[i] = consumer; + } - Wait.waitFor(new Wait.Condition() { - public boolean isSatisified() throws Exception { - return getReceived() == PRODUCER_COUNT * MESSAGE_COUNT; - } - }, 60000); + Wait.waitFor(new Wait.Condition() { + public boolean isSatisified() throws Exception { + return getReceived() == PRODUCER_COUNT * MESSAGE_COUNT; + } + }, 60000); - assertEquals(PRODUCER_COUNT * MESSAGE_COUNT, getReceived()); + assertEquals(PRODUCER_COUNT * MESSAGE_COUNT, getReceived()); - } + } - protected int getReceived() { - int received = 0; - for (ConsumerThread consumer : consumers) { - received += consumer.getReceived(); - } - return received; - } + protected int getReceived() { + int received = 0; + for (ConsumerThread consumer : consumers) { + received += consumer.getReceived(); + } + return received; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOSSLTransportBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOSSLTransportBrokerTest.java index 33735407bd..605dd06663 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOSSLTransportBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOSSLTransportBrokerTest.java @@ -18,50 +18,52 @@ package org.apache.activemq.transport.nio; import java.net.URI; import java.net.URISyntaxException; + import junit.framework.Test; + import junit.textui.TestRunner; import org.apache.activemq.transport.TransportBrokerTestSupport; public class NIOSSLTransportBrokerTest extends TransportBrokerTestSupport { - public static final String KEYSTORE_TYPE = "jks"; - public static final String PASSWORD = "password"; - public static final String SERVER_KEYSTORE = "src/test/resources/server.keystore"; - public static final String TRUST_KEYSTORE = "src/test/resources/client.keystore"; + public static final String KEYSTORE_TYPE = "jks"; + public static final String PASSWORD = "password"; + public static final String SERVER_KEYSTORE = "src/test/resources/server.keystore"; + public static final String TRUST_KEYSTORE = "src/test/resources/client.keystore"; - protected String getBindLocation() { - return "nio+ssl://localhost:0?transport.soWriteTimeout=20000"; - } + protected String getBindLocation() { + return "nio+ssl://localhost:0?transport.soWriteTimeout=20000"; + } - @Override - protected URI getBindURI() throws URISyntaxException { - return new URI("nio+ssl://localhost:0?soWriteTimeout=20000"); - } + @Override + protected URI getBindURI() throws URISyntaxException { + return new URI("nio+ssl://localhost:0?soWriteTimeout=20000"); + } - protected void setUp() throws Exception { - System.setProperty("javax.net.ssl.trustStore", TRUST_KEYSTORE); - System.setProperty("javax.net.ssl.trustStorePassword", PASSWORD); - System.setProperty("javax.net.ssl.trustStoreType", KEYSTORE_TYPE); - System.setProperty("javax.net.ssl.keyStore", SERVER_KEYSTORE); - System.setProperty("javax.net.ssl.keyStoreType", KEYSTORE_TYPE); - System.setProperty("javax.net.ssl.keyStorePassword", PASSWORD); - //System.setProperty("javax.net.debug", "ssl,handshake,data,trustmanager"); + protected void setUp() throws Exception { + System.setProperty("javax.net.ssl.trustStore", TRUST_KEYSTORE); + System.setProperty("javax.net.ssl.trustStorePassword", PASSWORD); + System.setProperty("javax.net.ssl.trustStoreType", KEYSTORE_TYPE); + System.setProperty("javax.net.ssl.keyStore", SERVER_KEYSTORE); + System.setProperty("javax.net.ssl.keyStoreType", KEYSTORE_TYPE); + System.setProperty("javax.net.ssl.keyStorePassword", PASSWORD); + //System.setProperty("javax.net.debug", "ssl,handshake,data,trustmanager"); - maxWait = 10000; - super.setUp(); - } + maxWait = 10000; + super.setUp(); + } - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } - public static Test suite() { - return suite(NIOSSLTransportBrokerTest.class); - } + public static Test suite() { + return suite(NIOSSLTransportBrokerTest.class); + } - public static void main(String[] args) { - TestRunner.run(suite()); - } + public static void main(String[] args) { + TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOSSLWindowSizeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOSSLWindowSizeTest.java index 17cdc415f2..3f41802b41 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOSSLWindowSizeTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOSSLWindowSizeTest.java @@ -17,6 +17,7 @@ package org.apache.activemq.transport.nio; import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.TransportConnector; @@ -30,84 +31,84 @@ import javax.jms.Session; @SuppressWarnings("javadoc") public class NIOSSLWindowSizeTest extends TestCase { - - BrokerService broker; - Connection connection; - Session session; - - public static final String KEYSTORE_TYPE = "jks"; - public static final String PASSWORD = "password"; - public static final String SERVER_KEYSTORE = "src/test/resources/server.keystore"; - public static final String TRUST_KEYSTORE = "src/test/resources/client.keystore"; - public static final int PRODUCER_COUNT = 1; - public static final int CONSUMER_COUNT = 1; - public static final int MESSAGE_COUNT = 1; - public static final int MESSAGE_SIZE = 65536; + BrokerService broker; + Connection connection; + Session session; - byte[] messageData; - - @Override - protected void setUp() throws Exception { - System.setProperty("javax.net.ssl.trustStore", TRUST_KEYSTORE); - System.setProperty("javax.net.ssl.trustStorePassword", PASSWORD); - System.setProperty("javax.net.ssl.trustStoreType", KEYSTORE_TYPE); - System.setProperty("javax.net.ssl.keyStore", SERVER_KEYSTORE); - System.setProperty("javax.net.ssl.keyStoreType", KEYSTORE_TYPE); - System.setProperty("javax.net.ssl.keyStorePassword", PASSWORD); + public static final String KEYSTORE_TYPE = "jks"; + public static final String PASSWORD = "password"; + public static final String SERVER_KEYSTORE = "src/test/resources/server.keystore"; + public static final String TRUST_KEYSTORE = "src/test/resources/client.keystore"; - broker = new BrokerService(); - broker.setPersistent(false); - broker.setUseJmx(false); - TransportConnector connector = broker.addConnector("nio+ssl://localhost:0?transport.needClientAuth=true"); - broker.start(); - broker.waitUntilStarted(); - - messageData = new byte[MESSAGE_SIZE]; - for (int i = 0; i < MESSAGE_SIZE; i++) - { - messageData[i] = (byte) (i & 0xff); - } - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("nio+ssl://localhost:" + connector.getConnectUri().getPort()); - connection = factory.createConnection(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - connection.start(); - } + public static final int PRODUCER_COUNT = 1; + public static final int CONSUMER_COUNT = 1; + public static final int MESSAGE_COUNT = 1; + public static final int MESSAGE_SIZE = 65536; - @Override - protected void tearDown() throws Exception { - if (session != null) { - session.close(); - } - if (connection != null) { - connection.close(); - } + byte[] messageData; - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - } + @Override + protected void setUp() throws Exception { + System.setProperty("javax.net.ssl.trustStore", TRUST_KEYSTORE); + System.setProperty("javax.net.ssl.trustStorePassword", PASSWORD); + System.setProperty("javax.net.ssl.trustStoreType", KEYSTORE_TYPE); + System.setProperty("javax.net.ssl.keyStore", SERVER_KEYSTORE); + System.setProperty("javax.net.ssl.keyStoreType", KEYSTORE_TYPE); + System.setProperty("javax.net.ssl.keyStorePassword", PASSWORD); - public void testLargePayload() throws Exception { - Queue dest = session.createQueue("TEST"); - MessageProducer prod = null; - try { - prod = session.createProducer(dest); - BytesMessage msg = session.createBytesMessage(); - msg.writeBytes(messageData); - prod.send(msg); - } finally { - prod.close(); - } - MessageConsumer cons = null; - try - { - cons = session.createConsumer(dest); - assertNotNull(cons.receive(30000L)); - } finally { - cons.close(); - } - } + broker = new BrokerService(); + broker.setPersistent(false); + broker.setUseJmx(false); + TransportConnector connector = broker.addConnector("nio+ssl://localhost:0?transport.needClientAuth=true"); + broker.start(); + broker.waitUntilStarted(); + + messageData = new byte[MESSAGE_SIZE]; + for (int i = 0; i < MESSAGE_SIZE; i++) { + messageData[i] = (byte) (i & 0xff); + } + + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("nio+ssl://localhost:" + connector.getConnectUri().getPort()); + connection = factory.createConnection(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + connection.start(); + } + + @Override + protected void tearDown() throws Exception { + if (session != null) { + session.close(); + } + if (connection != null) { + connection.close(); + } + + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + } + + public void testLargePayload() throws Exception { + Queue dest = session.createQueue("TEST"); + MessageProducer prod = null; + try { + prod = session.createProducer(dest); + BytesMessage msg = session.createBytesMessage(); + msg.writeBytes(messageData); + prod.send(msg); + } + finally { + prod.close(); + } + MessageConsumer cons = null; + try { + cons = session.createConsumer(dest); + assertNotNull(cons.receive(30000L)); + } + finally { + cons.close(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOTransportBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOTransportBrokerTest.java index ea103873e3..e49562ac28 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOTransportBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOTransportBrokerTest.java @@ -17,21 +17,22 @@ package org.apache.activemq.transport.nio; import junit.framework.Test; + import junit.textui.TestRunner; import org.apache.activemq.transport.TransportBrokerTestSupport; public class NIOTransportBrokerTest extends TransportBrokerTestSupport { - protected String getBindLocation() { - return "nio://localhost:61616"; - } + protected String getBindLocation() { + return "nio://localhost:61616"; + } - public static Test suite() { - return suite(NIOTransportBrokerTest.class); - } + public static Test suite() { + return suite(NIOTransportBrokerTest.class); + } - public static void main(String[] args) { - TestRunner.run(suite()); - } + public static void main(String[] args) { + TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/peer/PeerTransportTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/peer/PeerTransportTest.java index 4ac3dd4dd0..a7d164749c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/peer/PeerTransportTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/peer/PeerTransportTest.java @@ -44,114 +44,116 @@ import org.slf4j.LoggerFactory; * */ public class PeerTransportTest extends TestCase { - protected static final int MESSAGE_COUNT = 50; - protected static final int NUMBER_IN_CLUSTER = 3; - private static final Logger LOG = LoggerFactory.getLogger(PeerTransportTest.class); - protected ActiveMQDestination destination; - protected boolean topic = true; - protected int deliveryMode = DeliveryMode.NON_PERSISTENT; - protected MessageProducer[] producers; - protected Connection[] connections; - protected MessageIdList messageIdList[]; + protected static final int MESSAGE_COUNT = 50; + protected static final int NUMBER_IN_CLUSTER = 3; + private static final Logger LOG = LoggerFactory.getLogger(PeerTransportTest.class); - @Override - protected void setUp() throws Exception { + protected ActiveMQDestination destination; + protected boolean topic = true; + protected int deliveryMode = DeliveryMode.NON_PERSISTENT; + protected MessageProducer[] producers; + protected Connection[] connections; + protected MessageIdList messageIdList[]; - connections = new Connection[NUMBER_IN_CLUSTER]; - producers = new MessageProducer[NUMBER_IN_CLUSTER]; - messageIdList = new MessageIdList[NUMBER_IN_CLUSTER]; - ActiveMQDestination destination = createDestination(); + @Override + protected void setUp() throws Exception { - for (int i = 0; i < NUMBER_IN_CLUSTER; i++) { - connections[i] = createConnection(i); - connections[i].setClientID("ClusterTest" + i); - connections[i].start(); + connections = new Connection[NUMBER_IN_CLUSTER]; + producers = new MessageProducer[NUMBER_IN_CLUSTER]; + messageIdList = new MessageIdList[NUMBER_IN_CLUSTER]; + ActiveMQDestination destination = createDestination(); - Session session = connections[i].createSession(false, Session.AUTO_ACKNOWLEDGE); - producers[i] = session.createProducer(destination); - producers[i].setDeliveryMode(deliveryMode); - MessageConsumer consumer = createMessageConsumer(session, destination); - messageIdList[i] = new MessageIdList(); - consumer.setMessageListener(messageIdList[i]); - } + for (int i = 0; i < NUMBER_IN_CLUSTER; i++) { + connections[i] = createConnection(i); + connections[i].setClientID("ClusterTest" + i); + connections[i].start(); - LOG.info("Waiting for cluster to be fully connected"); + Session session = connections[i].createSession(false, Session.AUTO_ACKNOWLEDGE); + producers[i] = session.createProducer(destination); + producers[i].setDeliveryMode(deliveryMode); + MessageConsumer consumer = createMessageConsumer(session, destination); + messageIdList[i] = new MessageIdList(); + consumer.setMessageListener(messageIdList[i]); + } - // Each connection should see that NUMBER_IN_CLUSTER consumers get - // registered on the destination. - ActiveMQDestination advisoryDest = AdvisorySupport.getConsumerAdvisoryTopic(destination); - for (int i = 0; i < NUMBER_IN_CLUSTER; i++) { - Session session = connections[i].createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = createMessageConsumer(session, advisoryDest); + LOG.info("Waiting for cluster to be fully connected"); - int j = 0; - while (j < NUMBER_IN_CLUSTER) { - ActiveMQMessage message = (ActiveMQMessage)consumer.receive(1000); - if (message == null) { - fail("Connection " + i + " saw " + j + " consumers, expected: " + NUMBER_IN_CLUSTER); - } - if (message.getDataStructure() != null && message.getDataStructure().getDataStructureType() == ConsumerInfo.DATA_STRUCTURE_TYPE) { - j++; - } + // Each connection should see that NUMBER_IN_CLUSTER consumers get + // registered on the destination. + ActiveMQDestination advisoryDest = AdvisorySupport.getConsumerAdvisoryTopic(destination); + for (int i = 0; i < NUMBER_IN_CLUSTER; i++) { + Session session = connections[i].createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = createMessageConsumer(session, advisoryDest); + + int j = 0; + while (j < NUMBER_IN_CLUSTER) { + ActiveMQMessage message = (ActiveMQMessage) consumer.receive(1000); + if (message == null) { + fail("Connection " + i + " saw " + j + " consumers, expected: " + NUMBER_IN_CLUSTER); } - - session.close(); - } - - LOG.info("Cluster is online."); - } - - @Override - protected void tearDown() throws Exception { - if (connections != null) { - for (int i = 0; i < connections.length; i++) { - connections[i].close(); + if (message.getDataStructure() != null && message.getDataStructure().getDataStructureType() == ConsumerInfo.DATA_STRUCTURE_TYPE) { + j++; } - } - } + } - protected MessageConsumer createMessageConsumer(Session session, Destination destination) throws JMSException { - return session.createConsumer(destination); - } + session.close(); + } - protected Connection createConnection(int i) throws JMSException { - LOG.info("creating connection ...."); - ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory("peer://" + getClass().getName() + "/node" + i); - return fac.createConnection(); - } + LOG.info("Cluster is online."); + } - protected ActiveMQDestination createDestination() { - return createDestination(getClass().getName()); - } + @Override + protected void tearDown() throws Exception { + if (connections != null) { + for (int i = 0; i < connections.length; i++) { + connections[i].close(); + } + } + } - protected ActiveMQDestination createDestination(String name) { - if (topic) { - return new ActiveMQTopic(name); - } else { - return new ActiveMQQueue(name); - } - } + protected MessageConsumer createMessageConsumer(Session session, Destination destination) throws JMSException { + return session.createConsumer(destination); + } - /** - * @throws Exception - */ - public void testSendReceive() throws Exception { - for (int i = 0; i < MESSAGE_COUNT; i++) { - for (int x = 0; x < producers.length; x++) { - TextMessage textMessage = new ActiveMQTextMessage(); - textMessage.setText("MSG-NO: " + i + " in cluster: " + x); - producers[x].send(textMessage); - } - } + protected Connection createConnection(int i) throws JMSException { + LOG.info("creating connection ...."); + ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory("peer://" + getClass().getName() + "/node" + i); + return fac.createConnection(); + } - for (int i = 0; i < NUMBER_IN_CLUSTER; i++) { - messageIdList[i].assertMessagesReceived(expectedReceiveCount()); - } - } + protected ActiveMQDestination createDestination() { + return createDestination(getClass().getName()); + } - protected int expectedReceiveCount() { - return MESSAGE_COUNT * NUMBER_IN_CLUSTER; - } + protected ActiveMQDestination createDestination(String name) { + if (topic) { + return new ActiveMQTopic(name); + } + else { + return new ActiveMQQueue(name); + } + } + + /** + * @throws Exception + */ + public void testSendReceive() throws Exception { + for (int i = 0; i < MESSAGE_COUNT; i++) { + for (int x = 0; x < producers.length; x++) { + TextMessage textMessage = new ActiveMQTextMessage(); + textMessage.setText("MSG-NO: " + i + " in cluster: " + x); + producers[x].send(textMessage); + } + } + + for (int i = 0; i < NUMBER_IN_CLUSTER; i++) { + messageIdList[i].assertMessagesReceived(expectedReceiveCount()); + } + } + + protected int expectedReceiveCount() { + return MESSAGE_COUNT * NUMBER_IN_CLUSTER; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/reliable/DropCommandStrategy.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/reliable/DropCommandStrategy.java index f35ed7e85b..5ee7bab0b7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/reliable/DropCommandStrategy.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/reliable/DropCommandStrategy.java @@ -20,14 +20,14 @@ import java.net.SocketAddress; /** * - * + * */ public interface DropCommandStrategy { - /** - * Returns true if the command should be dropped for - * the given command ID and address - */ - boolean shouldDropCommand(int commandId, SocketAddress address, boolean redelivery); + /** + * Returns true if the command should be dropped for + * the given command ID and address + */ + boolean shouldDropCommand(int commandId, SocketAddress address, boolean redelivery); } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/reliable/ReliableTransportTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/reliable/ReliableTransportTest.java index 4f00e06251..1037bf5615 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/reliable/ReliableTransportTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/reliable/ReliableTransportTest.java @@ -19,6 +19,7 @@ package org.apache.activemq.transport.reliable; import java.util.Queue; import junit.framework.TestCase; + import org.apache.activemq.command.ConsumerInfo; import org.apache.activemq.transport.StubTransport; import org.apache.activemq.transport.StubTransportListener; @@ -26,108 +27,109 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class ReliableTransportTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(ReliableTransportTest.class); + private static final Logger LOG = LoggerFactory.getLogger(ReliableTransportTest.class); - protected ReliableTransport transport; - protected StubTransportListener listener = new StubTransportListener(); - protected ReplayStrategy replayStrategy; + protected ReliableTransport transport; + protected StubTransportListener listener = new StubTransportListener(); + protected ReplayStrategy replayStrategy; - public void testValidSequenceOfPackets() throws Exception { - int[] sequenceNumbers = {1, 2, 3, 4, 5, 6, 7}; + public void testValidSequenceOfPackets() throws Exception { + int[] sequenceNumbers = {1, 2, 3, 4, 5, 6, 7}; - sendStreamOfCommands(sequenceNumbers, true); - } + sendStreamOfCommands(sequenceNumbers, true); + } - public void testValidWrapAroundPackets() throws Exception { - int[] sequenceNumbers = new int[10]; + public void testValidWrapAroundPackets() throws Exception { + int[] sequenceNumbers = new int[10]; - int value = Integer.MAX_VALUE - 3; - transport.setExpectedCounter(value); + int value = Integer.MAX_VALUE - 3; + transport.setExpectedCounter(value); - for (int i = 0; i < 10; i++) { - LOG.info("command: " + i + " = " + value); - sequenceNumbers[i] = value++; - } + for (int i = 0; i < 10; i++) { + LOG.info("command: " + i + " = " + value); + sequenceNumbers[i] = value++; + } - sendStreamOfCommands(sequenceNumbers, true); - } + sendStreamOfCommands(sequenceNumbers, true); + } - public void testDuplicatePacketsDropped() throws Exception { - int[] sequenceNumbers = {1, 2, 2, 3, 4, 5, 6, 7}; + public void testDuplicatePacketsDropped() throws Exception { + int[] sequenceNumbers = {1, 2, 2, 3, 4, 5, 6, 7}; - sendStreamOfCommands(sequenceNumbers, true, 7); - } + sendStreamOfCommands(sequenceNumbers, true, 7); + } - public void testOldDuplicatePacketsDropped() throws Exception { - int[] sequenceNumbers = {1, 2, 3, 4, 5, 2, 6, 7}; + public void testOldDuplicatePacketsDropped() throws Exception { + int[] sequenceNumbers = {1, 2, 3, 4, 5, 2, 6, 7}; - sendStreamOfCommands(sequenceNumbers, true, 7); - } + sendStreamOfCommands(sequenceNumbers, true, 7); + } - public void testOldDuplicatePacketsDroppedUsingNegativeCounters() throws Exception { - int[] sequenceNumbers = {-3, -1, -3, -2, -1, 0, 1, -1, 3, 2, 0, 2, 4}; + public void testOldDuplicatePacketsDroppedUsingNegativeCounters() throws Exception { + int[] sequenceNumbers = {-3, -1, -3, -2, -1, 0, 1, -1, 3, 2, 0, 2, 4}; - transport.setExpectedCounter(-3); + transport.setExpectedCounter(-3); - sendStreamOfCommands(sequenceNumbers, true, 8); - } + sendStreamOfCommands(sequenceNumbers, true, 8); + } - public void testWrongOrderOfPackets() throws Exception { - int[] sequenceNumbers = {4, 3, 1, 5, 2, 7, 6, 8, 10, 9}; + public void testWrongOrderOfPackets() throws Exception { + int[] sequenceNumbers = {4, 3, 1, 5, 2, 7, 6, 8, 10, 9}; - sendStreamOfCommands(sequenceNumbers, true); - } + sendStreamOfCommands(sequenceNumbers, true); + } - public void testMissingPacketsFails() throws Exception { - int[] sequenceNumbers = {1, 2, /* 3, */4, 5, 6, 7, 8, 9, 10}; + public void testMissingPacketsFails() throws Exception { + int[] sequenceNumbers = {1, 2, /* 3, */4, 5, 6, 7, 8, 9, 10}; - sendStreamOfCommands(sequenceNumbers, false); - } + sendStreamOfCommands(sequenceNumbers, false); + } - protected void sendStreamOfCommands(int[] sequenceNumbers, boolean expected) { - sendStreamOfCommands(sequenceNumbers, expected, sequenceNumbers.length); - } + protected void sendStreamOfCommands(int[] sequenceNumbers, boolean expected) { + sendStreamOfCommands(sequenceNumbers, expected, sequenceNumbers.length); + } - protected void sendStreamOfCommands(int[] sequenceNumbers, boolean expected, int expectedCount) { - for (int i = 0; i < sequenceNumbers.length; i++) { - int commandId = sequenceNumbers[i]; + protected void sendStreamOfCommands(int[] sequenceNumbers, boolean expected, int expectedCount) { + for (int i = 0; i < sequenceNumbers.length; i++) { + int commandId = sequenceNumbers[i]; - ConsumerInfo info = new ConsumerInfo(); - info.setSelector("Cheese: " + commandId); - info.setCommandId(commandId); + ConsumerInfo info = new ConsumerInfo(); + info.setSelector("Cheese: " + commandId); + info.setCommandId(commandId); - transport.onCommand(info); - } + transport.onCommand(info); + } - Queue exceptions = listener.getExceptions(); - Queue commands = listener.getCommands(); - if (expected) { - if (!exceptions.isEmpty()) { - Exception e = (Exception)exceptions.remove(); - e.printStackTrace(); - fail("Caught exception: " + e); - } - assertEquals("number of messages received", expectedCount, commands.size()); + Queue exceptions = listener.getExceptions(); + Queue commands = listener.getCommands(); + if (expected) { + if (!exceptions.isEmpty()) { + Exception e = (Exception) exceptions.remove(); + e.printStackTrace(); + fail("Caught exception: " + e); + } + assertEquals("number of messages received", expectedCount, commands.size()); - assertEquals("Should have no buffered commands", 0, transport.getBufferedCommandCount()); - } else { - assertTrue("Should have received an exception!", exceptions.size() > 0); - Exception e = (Exception)exceptions.remove(); - LOG.info("Caught expected response: " + e); - } - } + assertEquals("Should have no buffered commands", 0, transport.getBufferedCommandCount()); + } + else { + assertTrue("Should have received an exception!", exceptions.size() > 0); + Exception e = (Exception) exceptions.remove(); + LOG.info("Caught expected response: " + e); + } + } - protected void setUp() throws Exception { - if (replayStrategy == null) { - replayStrategy = new ExceptionIfDroppedReplayStrategy(); - } - transport = new ReliableTransport(new StubTransport(), replayStrategy); - transport.setTransportListener(listener); - transport.start(); - } + protected void setUp() throws Exception { + if (replayStrategy == null) { + replayStrategy = new ExceptionIfDroppedReplayStrategy(); + } + transport = new ReliableTransport(new StubTransport(), replayStrategy); + transport.setTransportListener(listener); + transport.start(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/reliable/UnreliableCommandDatagramChannel.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/reliable/UnreliableCommandDatagramChannel.java index 0acf5c3231..3bb69ed58f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/reliable/UnreliableCommandDatagramChannel.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/reliable/UnreliableCommandDatagramChannel.java @@ -30,30 +30,40 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class UnreliableCommandDatagramChannel extends CommandDatagramChannel { - private static final Logger LOG = LoggerFactory.getLogger(UnreliableCommandDatagramChannel.class); + private static final Logger LOG = LoggerFactory.getLogger(UnreliableCommandDatagramChannel.class); - private DropCommandStrategy dropCommandStrategy; + private DropCommandStrategy dropCommandStrategy; - public UnreliableCommandDatagramChannel(UdpTransport transport, OpenWireFormat wireFormat, int datagramSize, SocketAddress targetAddress, - DatagramHeaderMarshaller headerMarshaller, ReplayBuffer replayBuffer, DatagramChannel channel, ByteBufferPool bufferPool, - DropCommandStrategy strategy) { - super(transport, wireFormat, datagramSize, targetAddress, headerMarshaller, channel, bufferPool); - this.dropCommandStrategy = strategy; - } + public UnreliableCommandDatagramChannel(UdpTransport transport, + OpenWireFormat wireFormat, + int datagramSize, + SocketAddress targetAddress, + DatagramHeaderMarshaller headerMarshaller, + ReplayBuffer replayBuffer, + DatagramChannel channel, + ByteBufferPool bufferPool, + DropCommandStrategy strategy) { + super(transport, wireFormat, datagramSize, targetAddress, headerMarshaller, channel, bufferPool); + this.dropCommandStrategy = strategy; + } - protected void sendWriteBuffer(int commandId, SocketAddress address, ByteBuffer writeBuffer, boolean redelivery) throws IOException { - if (dropCommandStrategy.shouldDropCommand(commandId, address, redelivery)) { - writeBuffer.flip(); - LOG.info("Dropping datagram with command: " + commandId); + protected void sendWriteBuffer(int commandId, + SocketAddress address, + ByteBuffer writeBuffer, + boolean redelivery) throws IOException { + if (dropCommandStrategy.shouldDropCommand(commandId, address, redelivery)) { + writeBuffer.flip(); + LOG.info("Dropping datagram with command: " + commandId); - // lets still add it to the replay buffer though! - getReplayBuffer().addBuffer(commandId, writeBuffer); - } else { - super.sendWriteBuffer(commandId, address, writeBuffer, redelivery); - } - } + // lets still add it to the replay buffer though! + getReplayBuffer().addBuffer(commandId, writeBuffer); + } + else { + super.sendWriteBuffer(commandId, address, writeBuffer, redelivery); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/reliable/UnreliableCommandDatagramSocket.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/reliable/UnreliableCommandDatagramSocket.java index 2d599031be..048facd336 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/reliable/UnreliableCommandDatagramSocket.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/reliable/UnreliableCommandDatagramSocket.java @@ -28,30 +28,40 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class UnreliableCommandDatagramSocket extends CommandDatagramSocket { - private static final Logger LOG = LoggerFactory.getLogger(UnreliableCommandDatagramSocket.class); - private DropCommandStrategy dropCommandStrategy; + private static final Logger LOG = LoggerFactory.getLogger(UnreliableCommandDatagramSocket.class); - public UnreliableCommandDatagramSocket(UdpTransport transport, OpenWireFormat wireFormat, int datagramSize, SocketAddress targetAddress, - DatagramHeaderMarshaller headerMarshaller, DatagramSocket channel, DropCommandStrategy strategy) { - super(transport, wireFormat, datagramSize, targetAddress, headerMarshaller, channel); - this.dropCommandStrategy = strategy; - } + private DropCommandStrategy dropCommandStrategy; - protected void sendWriteBuffer(int commandId, SocketAddress address, byte[] data, boolean redelivery) throws IOException { - if (dropCommandStrategy.shouldDropCommand(commandId, address, redelivery)) { - LOG.info("Dropping datagram with command: " + commandId); + public UnreliableCommandDatagramSocket(UdpTransport transport, + OpenWireFormat wireFormat, + int datagramSize, + SocketAddress targetAddress, + DatagramHeaderMarshaller headerMarshaller, + DatagramSocket channel, + DropCommandStrategy strategy) { + super(transport, wireFormat, datagramSize, targetAddress, headerMarshaller, channel); + this.dropCommandStrategy = strategy; + } - // lets still add it to the replay buffer though! - ReplayBuffer bufferCache = getReplayBuffer(); - if (bufferCache != null && !redelivery) { - bufferCache.addBuffer(commandId, data); - } - } else { - super.sendWriteBuffer(commandId, address, data, redelivery); - } - } + protected void sendWriteBuffer(int commandId, + SocketAddress address, + byte[] data, + boolean redelivery) throws IOException { + if (dropCommandStrategy.shouldDropCommand(commandId, address, redelivery)) { + LOG.info("Dropping datagram with command: " + commandId); + + // lets still add it to the replay buffer though! + ReplayBuffer bufferCache = getReplayBuffer(); + if (bufferCache != null && !redelivery) { + bufferCache.addBuffer(commandId, data); + } + } + else { + super.sendWriteBuffer(commandId, address, data, redelivery); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/reliable/UnreliableUdpTransport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/reliable/UnreliableUdpTransport.java index cd969d49d9..f0606a7140 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/reliable/UnreliableUdpTransport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/reliable/UnreliableUdpTransport.java @@ -28,41 +28,38 @@ import org.apache.activemq.transport.udp.UdpTransport; /** * An unreliable UDP transport that will randomly discard packets to simulate a * bad network (or UDP buffers being flooded). - * - * */ public class UnreliableUdpTransport extends UdpTransport { - private DropCommandStrategy dropCommandStrategy; + private DropCommandStrategy dropCommandStrategy; - public UnreliableUdpTransport(OpenWireFormat wireFormat, int port) throws UnknownHostException, IOException { - super(wireFormat, port); - } + public UnreliableUdpTransport(OpenWireFormat wireFormat, int port) throws UnknownHostException, IOException { + super(wireFormat, port); + } - public UnreliableUdpTransport(OpenWireFormat wireFormat, SocketAddress socketAddress) throws IOException { - super(wireFormat, socketAddress); - } + public UnreliableUdpTransport(OpenWireFormat wireFormat, SocketAddress socketAddress) throws IOException { + super(wireFormat, socketAddress); + } - public UnreliableUdpTransport(OpenWireFormat wireFormat, URI remoteLocation) throws UnknownHostException, - IOException { - super(wireFormat, remoteLocation); - } + public UnreliableUdpTransport(OpenWireFormat wireFormat, + URI remoteLocation) throws UnknownHostException, IOException { + super(wireFormat, remoteLocation); + } - public UnreliableUdpTransport(OpenWireFormat wireFormat) throws IOException { - super(wireFormat); - } + public UnreliableUdpTransport(OpenWireFormat wireFormat) throws IOException { + super(wireFormat); + } - public DropCommandStrategy getDropCommandStrategy() { - return dropCommandStrategy; - } + public DropCommandStrategy getDropCommandStrategy() { + return dropCommandStrategy; + } - public void setDropCommandStrategy(DropCommandStrategy dropCommandStrategy) { - this.dropCommandStrategy = dropCommandStrategy; - } + public void setDropCommandStrategy(DropCommandStrategy dropCommandStrategy) { + this.dropCommandStrategy = dropCommandStrategy; + } - protected CommandChannel createCommandDatagramChannel() { - return new UnreliableCommandDatagramChannel(this, getWireFormat(), getDatagramSize(), getTargetAddress(), - createDatagramHeaderMarshaller(), getReplayBuffer(), getChannel(), getBufferPool(), dropCommandStrategy); - } + protected CommandChannel createCommandDatagramChannel() { + return new UnreliableCommandDatagramChannel(this, getWireFormat(), getDatagramSize(), getTargetAddress(), createDatagramHeaderMarshaller(), getReplayBuffer(), getChannel(), getBufferPool(), dropCommandStrategy); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/reliable/UnreliableUdpTransportTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/reliable/UnreliableUdpTransportTest.java index 3ac406acc0..bd1db95fa1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/reliable/UnreliableUdpTransportTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/reliable/UnreliableUdpTransportTest.java @@ -33,60 +33,61 @@ import org.slf4j.LoggerFactory; * */ public class UnreliableUdpTransportTest extends UdpTransportTest { - private static final Logger LOG = LoggerFactory.getLogger(UnreliableUdpTransportTest.class); - protected DropCommandStrategy dropStrategy = new DropCommandStrategy() { + private static final Logger LOG = LoggerFactory.getLogger(UnreliableUdpTransportTest.class); - @Override - public boolean shouldDropCommand(int commandId, SocketAddress address, boolean redelivery) { - if (redelivery) { - return false; - } - return commandId % 3 == 2; - } - }; + protected DropCommandStrategy dropStrategy = new DropCommandStrategy() { - @Override - protected Transport createProducer() throws Exception { - LOG.info("Producer using URI: " + producerURI); + @Override + public boolean shouldDropCommand(int commandId, SocketAddress address, boolean redelivery) { + if (redelivery) { + return false; + } + return commandId % 3 == 2; + } + }; - OpenWireFormat wireFormat = createWireFormat(); - UnreliableUdpTransport transport = new UnreliableUdpTransport(wireFormat, new URI(producerURI)); - transport.setDropCommandStrategy(dropStrategy); + @Override + protected Transport createProducer() throws Exception { + LOG.info("Producer using URI: " + producerURI); - ReliableTransport reliableTransport = new ReliableTransport(transport, transport); - Replayer replayer = reliableTransport.getReplayer(); - reliableTransport.setReplayStrategy(createReplayStrategy(replayer)); + OpenWireFormat wireFormat = createWireFormat(); + UnreliableUdpTransport transport = new UnreliableUdpTransport(wireFormat, new URI(producerURI)); + transport.setDropCommandStrategy(dropStrategy); - return new CommandJoiner(reliableTransport, wireFormat); - } + ReliableTransport reliableTransport = new ReliableTransport(transport, transport); + Replayer replayer = reliableTransport.getReplayer(); + reliableTransport.setReplayStrategy(createReplayStrategy(replayer)); - @Override - protected Transport createConsumer() throws Exception { - LOG.info("Consumer on port: " + consumerPort); - OpenWireFormat wireFormat = createWireFormat(); - UdpTransport transport = new UdpTransport(wireFormat, consumerPort); + return new CommandJoiner(reliableTransport, wireFormat); + } - ReliableTransport reliableTransport = new ReliableTransport(transport, transport); - Replayer replayer = reliableTransport.getReplayer(); - reliableTransport.setReplayStrategy(createReplayStrategy(replayer)); + @Override + protected Transport createConsumer() throws Exception { + LOG.info("Consumer on port: " + consumerPort); + OpenWireFormat wireFormat = createWireFormat(); + UdpTransport transport = new UdpTransport(wireFormat, consumerPort); - ResponseRedirectInterceptor redirectInterceptor = new ResponseRedirectInterceptor(reliableTransport, transport); - return new CommandJoiner(redirectInterceptor, wireFormat); - } + ReliableTransport reliableTransport = new ReliableTransport(transport, transport); + Replayer replayer = reliableTransport.getReplayer(); + reliableTransport.setReplayStrategy(createReplayStrategy(replayer)); - protected ReplayStrategy createReplayStrategy(Replayer replayer) { - assertNotNull("Should have a replayer!", replayer); - return new DefaultReplayStrategy(1); - } + ResponseRedirectInterceptor redirectInterceptor = new ResponseRedirectInterceptor(reliableTransport, transport); + return new CommandJoiner(redirectInterceptor, wireFormat); + } - @Override - public void testSendingMediumMessage() throws Exception { - // Ignoring, see AMQ-4973 - } + protected ReplayStrategy createReplayStrategy(Replayer replayer) { + assertNotNull("Should have a replayer!", replayer); + return new DefaultReplayStrategy(1); + } - @Override - public void testSendingLargeMessage() throws Exception { - // Ignoring, see AMQ-4973 - } + @Override + public void testSendingMediumMessage() throws Exception { + // Ignoring, see AMQ-4973 + } + + @Override + public void testSendingLargeMessage() throws Exception { + // Ignoring, see AMQ-4973 + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/InactivityMonitorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/InactivityMonitorTest.java index 05acaf46c1..8ab802a915 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/InactivityMonitorTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/InactivityMonitorTest.java @@ -36,49 +36,111 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class InactivityMonitorTest extends CombinationTestSupport implements TransportAcceptListener { - private static final Logger LOG = LoggerFactory.getLogger(InactivityMonitorTest.class); - public Runnable serverRunOnCommand; - public Runnable clientRunOnCommand; + private static final Logger LOG = LoggerFactory.getLogger(InactivityMonitorTest.class); - private TransportServer server; - private Transport clientTransport; - private Transport serverTransport; - private int serverPort; + public Runnable serverRunOnCommand; + public Runnable clientRunOnCommand; - private final AtomicInteger clientReceiveCount = new AtomicInteger(0); - private final AtomicInteger clientErrorCount = new AtomicInteger(0); - private final AtomicInteger serverReceiveCount = new AtomicInteger(0); - private final AtomicInteger serverErrorCount = new AtomicInteger(0); + private TransportServer server; + private Transport clientTransport; + private Transport serverTransport; + private int serverPort; - private final AtomicBoolean ignoreClientError = new AtomicBoolean(false); - private final AtomicBoolean ignoreServerError = new AtomicBoolean(false); + private final AtomicInteger clientReceiveCount = new AtomicInteger(0); + private final AtomicInteger clientErrorCount = new AtomicInteger(0); + private final AtomicInteger serverReceiveCount = new AtomicInteger(0); + private final AtomicInteger serverErrorCount = new AtomicInteger(0); - protected void setUp() throws Exception { - super.setUp(); - startTransportServer(); - } + private final AtomicBoolean ignoreClientError = new AtomicBoolean(false); + private final AtomicBoolean ignoreServerError = new AtomicBoolean(false); - /** - * @throws Exception - * @throws URISyntaxException - */ - private void startClient() throws Exception, URISyntaxException { - clientTransport = TransportFactory.connect(new URI("tcp://localhost:" + serverPort + "?trace=true&wireFormat.maxInactivityDuration=1000")); - clientTransport.setTransportListener(new TransportListener() { + protected void setUp() throws Exception { + super.setUp(); + startTransportServer(); + } + + /** + * @throws Exception + * @throws URISyntaxException + */ + private void startClient() throws Exception, URISyntaxException { + clientTransport = TransportFactory.connect(new URI("tcp://localhost:" + serverPort + "?trace=true&wireFormat.maxInactivityDuration=1000")); + clientTransport.setTransportListener(new TransportListener() { + public void onCommand(Object command) { + clientReceiveCount.incrementAndGet(); + if (clientRunOnCommand != null) { + clientRunOnCommand.run(); + } + } + + public void onException(IOException error) { + if (!ignoreClientError.get()) { + LOG.info("Client transport error:"); + error.printStackTrace(); + clientErrorCount.incrementAndGet(); + } + } + + public void transportInterupted() { + } + + public void transportResumed() { + } + }); + clientTransport.start(); + } + + /** + * @throws IOException + * @throws URISyntaxException + * @throws Exception + */ + private void startTransportServer() throws IOException, URISyntaxException, Exception { + server = TransportFactory.bind(new URI("tcp://localhost:0?trace=true&wireFormat.maxInactivityDuration=1000")); + server.setAcceptListener(this); + server.start(); + + serverPort = server.getSocketAddress().getPort(); + } + + protected void tearDown() throws Exception { + ignoreClientError.set(true); + ignoreServerError.set(true); + try { + if (clientTransport != null) { + clientTransport.stop(); + } + if (serverTransport != null) { + serverTransport.stop(); + } + if (server != null) { + server.stop(); + } + } + catch (Throwable e) { + e.printStackTrace(); + } + super.tearDown(); + } + + public void onAccept(Transport transport) { + try { + LOG.info("[" + getName() + "] Server Accepted a Connection"); + serverTransport = transport; + serverTransport.setTransportListener(new TransportListener() { public void onCommand(Object command) { - clientReceiveCount.incrementAndGet(); - if (clientRunOnCommand != null) { - clientRunOnCommand.run(); - } + serverReceiveCount.incrementAndGet(); + if (serverRunOnCommand != null) { + serverRunOnCommand.run(); + } } public void onException(IOException error) { - if (!ignoreClientError.get()) { - LOG.info("Client transport error:"); - error.printStackTrace(); - clientErrorCount.incrementAndGet(); - } + if (!ignoreClientError.get()) { + LOG.info("Server transport error:", error); + serverErrorCount.incrementAndGet(); + } } public void transportInterupted() { @@ -86,170 +148,112 @@ public class InactivityMonitorTest extends CombinationTestSupport implements Tra public void transportResumed() { } - }); - clientTransport.start(); - } + }); + serverTransport.start(); + } + catch (Exception e) { + e.printStackTrace(); + } + } - /** - * @throws IOException - * @throws URISyntaxException - * @throws Exception - */ - private void startTransportServer() throws IOException, URISyntaxException, Exception { - server = TransportFactory.bind(new URI("tcp://localhost:0?trace=true&wireFormat.maxInactivityDuration=1000")); - server.setAcceptListener(this); - server.start(); + public void onAcceptError(Exception error) { + LOG.trace(error.toString()); + } - serverPort = server.getSocketAddress().getPort(); - } + public void testClientHang() throws Exception { - protected void tearDown() throws Exception { - ignoreClientError.set(true); - ignoreServerError.set(true); - try { - if (clientTransport != null) { - clientTransport.stop(); + // + // Manually create a client transport so that it does not send KeepAlive + // packets. + // this should simulate a client hang. + clientTransport = new TcpTransport(new OpenWireFormat(), SocketFactory.getDefault(), new URI("tcp://localhost:" + serverPort), null); + clientTransport.setTransportListener(new TransportListener() { + public void onCommand(Object command) { + clientReceiveCount.incrementAndGet(); + if (clientRunOnCommand != null) { + clientRunOnCommand.run(); } - if (serverTransport != null) { - serverTransport.stop(); + } + + public void onException(IOException error) { + if (!ignoreClientError.get()) { + LOG.info("Client transport error:"); + error.printStackTrace(); + clientErrorCount.incrementAndGet(); } - if (server != null) { - server.stop(); + } + + public void transportInterupted() { + } + + public void transportResumed() { + } + }); + clientTransport.start(); + WireFormatInfo info = new WireFormatInfo(); + info.setVersion(OpenWireFormat.DEFAULT_VERSION); + info.setMaxInactivityDuration(1000); + clientTransport.oneway(info); + + assertEquals(0, serverErrorCount.get()); + assertEquals(0, clientErrorCount.get()); + + // Server should consider the client timed out right away since the + // client is not hart beating fast enough. + Thread.sleep(6000); + + assertEquals(0, clientErrorCount.get()); + assertTrue(serverErrorCount.get() > 0); + } + + public void testNoClientHang() throws Exception { + startClient(); + + assertEquals(0, serverErrorCount.get()); + assertEquals(0, clientErrorCount.get()); + + Thread.sleep(4000); + + assertEquals(0, clientErrorCount.get()); + assertEquals(0, serverErrorCount.get()); + } + + /** + * Used to test when an operation blocks. This should not cause transport to + * get disconnected. + * + * @throws Exception + * @throws URISyntaxException + */ + public void initCombosForTestNoClientHangWithServerBlock() throws Exception { + + startClient(); + + addCombinationValues("clientInactivityLimit", new Object[]{Long.valueOf(1000)}); + addCombinationValues("serverInactivityLimit", new Object[]{Long.valueOf(1000)}); + addCombinationValues("serverRunOnCommand", new Object[]{new Runnable() { + public void run() { + try { + LOG.info("Sleeping"); + Thread.sleep(4000); } - } catch (Throwable e) { - e.printStackTrace(); - } - super.tearDown(); - } - - public void onAccept(Transport transport) { - try { - LOG.info("[" + getName() + "] Server Accepted a Connection"); - serverTransport = transport; - serverTransport.setTransportListener(new TransportListener() { - public void onCommand(Object command) { - serverReceiveCount.incrementAndGet(); - if (serverRunOnCommand != null) { - serverRunOnCommand.run(); - } - } - - public void onException(IOException error) { - if (!ignoreClientError.get()) { - LOG.info("Server transport error:", error); - serverErrorCount.incrementAndGet(); - } - } - - public void transportInterupted() { - } - - public void transportResumed() { - } - }); - serverTransport.start(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public void onAcceptError(Exception error) { - LOG.trace(error.toString()); - } - - public void testClientHang() throws Exception { - - // - // Manually create a client transport so that it does not send KeepAlive - // packets. - // this should simulate a client hang. - clientTransport = new TcpTransport(new OpenWireFormat(), SocketFactory.getDefault(), new URI("tcp://localhost:" + serverPort), null); - clientTransport.setTransportListener(new TransportListener() { - public void onCommand(Object command) { - clientReceiveCount.incrementAndGet(); - if (clientRunOnCommand != null) { - clientRunOnCommand.run(); - } + catch (InterruptedException e) { } + } + }}); + } - public void onException(IOException error) { - if (!ignoreClientError.get()) { - LOG.info("Client transport error:"); - error.printStackTrace(); - clientErrorCount.incrementAndGet(); - } - } + public void testNoClientHangWithServerBlock() throws Exception { - public void transportInterupted() { - } + startClient(); - public void transportResumed() { - } - }); - clientTransport.start(); - WireFormatInfo info = new WireFormatInfo(); - info.setVersion(OpenWireFormat.DEFAULT_VERSION); - info.setMaxInactivityDuration(1000); - clientTransport.oneway(info); + assertEquals(0, serverErrorCount.get()); + assertEquals(0, clientErrorCount.get()); - assertEquals(0, serverErrorCount.get()); - assertEquals(0, clientErrorCount.get()); + Thread.sleep(4000); - // Server should consider the client timed out right away since the - // client is not hart beating fast enough. - Thread.sleep(6000); - - assertEquals(0, clientErrorCount.get()); - assertTrue(serverErrorCount.get() > 0); - } - - public void testNoClientHang() throws Exception { - startClient(); - - assertEquals(0, serverErrorCount.get()); - assertEquals(0, clientErrorCount.get()); - - Thread.sleep(4000); - - assertEquals(0, clientErrorCount.get()); - assertEquals(0, serverErrorCount.get()); - } - - /** - * Used to test when an operation blocks. This should not cause transport to - * get disconnected. - * - * @throws Exception - * @throws URISyntaxException - */ - public void initCombosForTestNoClientHangWithServerBlock() throws Exception { - - startClient(); - - addCombinationValues("clientInactivityLimit", new Object[] {Long.valueOf(1000)}); - addCombinationValues("serverInactivityLimit", new Object[] {Long.valueOf(1000)}); - addCombinationValues("serverRunOnCommand", new Object[] {new Runnable() { - public void run() { - try { - LOG.info("Sleeping"); - Thread.sleep(4000); - } catch (InterruptedException e) { - } - } - }}); - } - - public void testNoClientHangWithServerBlock() throws Exception { - - startClient(); - - assertEquals(0, serverErrorCount.get()); - assertEquals(0, clientErrorCount.get()); - - Thread.sleep(4000); - - assertEquals(0, clientErrorCount.get()); - assertEquals(0, serverErrorCount.get()); - } + assertEquals(0, clientErrorCount.get()); + assertEquals(0, serverErrorCount.get()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/QualityOfServiceUtilsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/QualityOfServiceUtilsTest.java index ec619a0fb4..e45bf64cbc 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/QualityOfServiceUtilsTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/QualityOfServiceUtilsTest.java @@ -23,148 +23,146 @@ import java.util.Map; import junit.framework.TestCase; public class QualityOfServiceUtilsTest extends TestCase { - /** - * Keeps track of the value that the System has set for the ECN bits, which - * should not be overridden when Differentiated Services is set, but may be - * overridden when Type of Service is set. - */ - private int ECN; - @Override - protected void setUp() throws Exception { - Socket socket = new Socket(); - ECN = socket.getTrafficClass() & Integer.parseInt("00000011", 2); - socket.close(); - } + /** + * Keeps track of the value that the System has set for the ECN bits, which + * should not be overridden when Differentiated Services is set, but may be + * overridden when Type of Service is set. + */ + private int ECN; - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } + @Override + protected void setUp() throws Exception { + Socket socket = new Socket(); + ECN = socket.getTrafficClass() & Integer.parseInt("00000011", 2); + socket.close(); + } - public void testValidDiffServIntegerValues() { - int[] values = {0, 1, 32, 62, 63}; - for (int val : values) { - testValidDiffServIntegerValue(val); - } - } + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } - public void testInvalidDiffServIntegerValues() { - int[] values = {-2, -1, 64, 65}; - for (int val : values) { - testInvalidDiffServIntegerValue(val); - } - } + public void testValidDiffServIntegerValues() { + int[] values = {0, 1, 32, 62, 63}; + for (int val : values) { + testValidDiffServIntegerValue(val); + } + } - public void testValidDiffServNames() { - Map namesToExpected = new HashMap(); - namesToExpected.put("CS0", Integer.valueOf("000000", 2)); - namesToExpected.put("CS1", Integer.valueOf("001000", 2)); - namesToExpected.put("CS2", Integer.valueOf("010000", 2)); - namesToExpected.put("CS3", Integer.valueOf("011000", 2)); - namesToExpected.put("CS4", Integer.valueOf("100000", 2)); - namesToExpected.put("CS5", Integer.valueOf("101000", 2)); - namesToExpected.put("CS6", Integer.valueOf("110000", 2)); - namesToExpected.put("CS7", Integer.valueOf("111000", 2)); - namesToExpected.put("EF", Integer.valueOf("101110", 2)); - namesToExpected.put("AF11", Integer.valueOf("001010", 2)); - namesToExpected.put("AF12", Integer.valueOf("001100", 2)); - namesToExpected.put("AF13", Integer.valueOf("001110", 2)); - namesToExpected.put("AF21", Integer.valueOf("010010", 2)); - namesToExpected.put("AF22", Integer.valueOf("010100", 2)); - namesToExpected.put("AF23", Integer.valueOf("010110", 2)); - namesToExpected.put("AF31", Integer.valueOf("011010", 2)); - namesToExpected.put("AF32", Integer.valueOf("011100", 2)); - namesToExpected.put("AF33", Integer.valueOf("011110", 2)); - namesToExpected.put("AF41", Integer.valueOf("100010", 2)); - namesToExpected.put("AF42", Integer.valueOf("100100", 2)); - namesToExpected.put("AF43", Integer.valueOf("100110", 2)); - for (String name : namesToExpected.keySet()) { - testValidDiffServName(name, namesToExpected.get(name)); - } - } + public void testInvalidDiffServIntegerValues() { + int[] values = {-2, -1, 64, 65}; + for (int val : values) { + testInvalidDiffServIntegerValue(val); + } + } - public void testInvalidDiffServNames() { - String[] names = {"hello_world", "", "abcd"}; - for (String name : names) { - testInvalidDiffServName(name); - } - } + public void testValidDiffServNames() { + Map namesToExpected = new HashMap(); + namesToExpected.put("CS0", Integer.valueOf("000000", 2)); + namesToExpected.put("CS1", Integer.valueOf("001000", 2)); + namesToExpected.put("CS2", Integer.valueOf("010000", 2)); + namesToExpected.put("CS3", Integer.valueOf("011000", 2)); + namesToExpected.put("CS4", Integer.valueOf("100000", 2)); + namesToExpected.put("CS5", Integer.valueOf("101000", 2)); + namesToExpected.put("CS6", Integer.valueOf("110000", 2)); + namesToExpected.put("CS7", Integer.valueOf("111000", 2)); + namesToExpected.put("EF", Integer.valueOf("101110", 2)); + namesToExpected.put("AF11", Integer.valueOf("001010", 2)); + namesToExpected.put("AF12", Integer.valueOf("001100", 2)); + namesToExpected.put("AF13", Integer.valueOf("001110", 2)); + namesToExpected.put("AF21", Integer.valueOf("010010", 2)); + namesToExpected.put("AF22", Integer.valueOf("010100", 2)); + namesToExpected.put("AF23", Integer.valueOf("010110", 2)); + namesToExpected.put("AF31", Integer.valueOf("011010", 2)); + namesToExpected.put("AF32", Integer.valueOf("011100", 2)); + namesToExpected.put("AF33", Integer.valueOf("011110", 2)); + namesToExpected.put("AF41", Integer.valueOf("100010", 2)); + namesToExpected.put("AF42", Integer.valueOf("100100", 2)); + namesToExpected.put("AF43", Integer.valueOf("100110", 2)); + for (String name : namesToExpected.keySet()) { + testValidDiffServName(name, namesToExpected.get(name)); + } + } - private void testValidDiffServName(String name, int expected) { - int dscp = -1; - try { - dscp = QualityOfServiceUtils.getDSCP(name); - } catch (IllegalArgumentException e) { - fail("IllegalArgumentException thrown for valid Differentiated " - + " Services name: " + name); - } - // Make sure it adjusted for any system ECN values. - assertEquals("Incorrect Differentiated Services Code Point " + dscp - + " returned for name " + name + ".", ECN | (expected << 2), dscp); - } + public void testInvalidDiffServNames() { + String[] names = {"hello_world", "", "abcd"}; + for (String name : names) { + testInvalidDiffServName(name); + } + } - private void testInvalidDiffServName(String name) { - try { - QualityOfServiceUtils.getDSCP(name); - fail("No IllegalArgumentException thrown for invalid Differentiated" - + " Services value: " + name + "."); - } catch (IllegalArgumentException e) { - } - } + private void testValidDiffServName(String name, int expected) { + int dscp = -1; + try { + dscp = QualityOfServiceUtils.getDSCP(name); + } + catch (IllegalArgumentException e) { + fail("IllegalArgumentException thrown for valid Differentiated " + " Services name: " + name); + } + // Make sure it adjusted for any system ECN values. + assertEquals("Incorrect Differentiated Services Code Point " + dscp + " returned for name " + name + ".", ECN | (expected << 2), dscp); + } - private void testValidDiffServIntegerValue(int val) { - try { - int dscp = QualityOfServiceUtils.getDSCP(Integer.toString(val)); - // Make sure it adjusted for any system ECN values. - assertEquals("Incorrect Differentiated Services Code Point " - + "returned for value " + val + ".", ECN | (val << 2), dscp); - } catch (IllegalArgumentException e) { - fail("IllegalArgumentException thrown for valid Differentiated " - + "Services value " + val); - } - } + private void testInvalidDiffServName(String name) { + try { + QualityOfServiceUtils.getDSCP(name); + fail("No IllegalArgumentException thrown for invalid Differentiated" + " Services value: " + name + "."); + } + catch (IllegalArgumentException e) { + } + } - private void testInvalidDiffServIntegerValue(int val) { - try { - QualityOfServiceUtils.getDSCP(Integer.toString(val)); - fail("No IllegalArgumentException thrown for invalid " - + "Differentiated Services value " + val + "."); - } catch (IllegalArgumentException expected) { - } - } + private void testValidDiffServIntegerValue(int val) { + try { + int dscp = QualityOfServiceUtils.getDSCP(Integer.toString(val)); + // Make sure it adjusted for any system ECN values. + assertEquals("Incorrect Differentiated Services Code Point " + "returned for value " + val + ".", ECN | (val << 2), dscp); + } + catch (IllegalArgumentException e) { + fail("IllegalArgumentException thrown for valid Differentiated " + "Services value " + val); + } + } - public void testValidTypeOfServiceValues() { - int[] values = {0, 1, 32, 100, 255}; - for (int val : values) { - testValidTypeOfServiceValue(val); - } - } + private void testInvalidDiffServIntegerValue(int val) { + try { + QualityOfServiceUtils.getDSCP(Integer.toString(val)); + fail("No IllegalArgumentException thrown for invalid " + "Differentiated Services value " + val + "."); + } + catch (IllegalArgumentException expected) { + } + } - public void testInvalidTypeOfServiceValues() { - int[] values = {-2, -1, 256, 257}; - for (int val : values) { - testInvalidTypeOfServiceValue(val); - } - } + public void testValidTypeOfServiceValues() { + int[] values = {0, 1, 32, 100, 255}; + for (int val : values) { + testValidTypeOfServiceValue(val); + } + } - private void testValidTypeOfServiceValue(int val) { - try { - int typeOfService = QualityOfServiceUtils.getToS(val); - assertEquals("Incorrect Type of Services value returned for " + val - + ".", val, typeOfService); - } catch (IllegalArgumentException e) { - fail("IllegalArgumentException thrown for valid Type of Service " - + "value " + val + "."); - } - } + public void testInvalidTypeOfServiceValues() { + int[] values = {-2, -1, 256, 257}; + for (int val : values) { + testInvalidTypeOfServiceValue(val); + } + } - private void testInvalidTypeOfServiceValue(int val) { - try { - QualityOfServiceUtils.getToS(val); - fail("No IllegalArgumentException thrown for invalid " - + "Type of Service value " + val + "."); - } catch (IllegalArgumentException expected) { - } - } + private void testValidTypeOfServiceValue(int val) { + try { + int typeOfService = QualityOfServiceUtils.getToS(val); + assertEquals("Incorrect Type of Services value returned for " + val + ".", val, typeOfService); + } + catch (IllegalArgumentException e) { + fail("IllegalArgumentException thrown for valid Type of Service " + "value " + val + "."); + } + } + + private void testInvalidTypeOfServiceValue(int val) { + try { + QualityOfServiceUtils.getToS(val); + fail("No IllegalArgumentException thrown for invalid " + "Type of Service value " + val + "."); + } + catch (IllegalArgumentException expected) { + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/ServerSocketTstFactory.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/ServerSocketTstFactory.java index 5b6adf6d0a..291ebb1c6e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/ServerSocketTstFactory.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/ServerSocketTstFactory.java @@ -21,61 +21,65 @@ import java.net.InetAddress; import java.net.ServerSocket; import java.util.Random; import javax.net.ServerSocketFactory; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** */ public class ServerSocketTstFactory extends ServerSocketFactory { - private static final Logger LOG = LoggerFactory.getLogger(ServerSocketTstFactory.class); - private class ServerSocketTst { + private static final Logger LOG = LoggerFactory.getLogger(ServerSocketTstFactory.class); - private final ServerSocket socket; + private class ServerSocketTst { - public ServerSocketTst(int port, Random rnd) throws IOException { - this.socket = ServerSocketFactory.getDefault().createServerSocket(port); - } + private final ServerSocket socket; - public ServerSocketTst(int port, int backlog, Random rnd) throws IOException { - this.socket = ServerSocketFactory.getDefault().createServerSocket(port, backlog); - } + public ServerSocketTst(int port, Random rnd) throws IOException { + this.socket = ServerSocketFactory.getDefault().createServerSocket(port); + } - public ServerSocketTst(int port, int backlog, InetAddress bindAddr, Random rnd) throws IOException { - this.socket = ServerSocketFactory.getDefault().createServerSocket(port, backlog, bindAddr); - } + public ServerSocketTst(int port, int backlog, Random rnd) throws IOException { + this.socket = ServerSocketFactory.getDefault().createServerSocket(port, backlog); + } - public ServerSocket getSocket() { - return this.socket; - } - }; + public ServerSocketTst(int port, int backlog, InetAddress bindAddr, Random rnd) throws IOException { + this.socket = ServerSocketFactory.getDefault().createServerSocket(port, backlog, bindAddr); + } - private final Random rnd; + public ServerSocket getSocket() { + return this.socket; + } + } + + ; + + private final Random rnd; public ServerSocketTstFactory() { - super(); - LOG.info("Creating a new ServerSocketTstFactory"); - this.rnd = new Random(); + super(); + LOG.info("Creating a new ServerSocketTstFactory"); + this.rnd = new Random(); } public ServerSocket createServerSocket(int port) throws IOException { - ServerSocketTst sSock = new ServerSocketTst(port, this.rnd); - return sSock.getSocket(); + ServerSocketTst sSock = new ServerSocketTst(port, this.rnd); + return sSock.getSocket(); } public ServerSocket createServerSocket(int port, int backlog) throws IOException { - ServerSocketTst sSock = new ServerSocketTst(port, backlog, this.rnd); - return sSock.getSocket(); + ServerSocketTst sSock = new ServerSocketTst(port, backlog, this.rnd); + return sSock.getSocket(); } public ServerSocket createServerSocket(int port, int backlog, InetAddress ifAddress) throws IOException { - ServerSocketTst sSock = new ServerSocketTst(port, backlog, ifAddress, this.rnd); - return sSock.getSocket(); + ServerSocketTst sSock = new ServerSocketTst(port, backlog, ifAddress, this.rnd); + return sSock.getSocket(); } private final static ServerSocketTstFactory server = new ServerSocketTstFactory(); public static ServerSocketTstFactory getDefault() { - return server; + return server; } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SocketTstFactory.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SocketTstFactory.java index 9b31a7348c..b4de0cedc2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SocketTstFactory.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SocketTstFactory.java @@ -30,150 +30,160 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * - * * Automatically generated socket.close() calls to simulate network faults */ public class SocketTstFactory extends SocketFactory { - private static final Logger LOG = LoggerFactory.getLogger(SocketTstFactory.class); - private static final ConcurrentMap closeIter = new ConcurrentHashMap(); + private static final Logger LOG = LoggerFactory.getLogger(SocketTstFactory.class); - private class SocketTst { + private static final ConcurrentMap closeIter = new ConcurrentHashMap(); - private class Bagot implements Runnable { - private final Thread processus; - private final Socket socket; - private final InetAddress address; + private class SocketTst { - public Bagot(Random rnd, Socket socket, InetAddress address) { - this.processus = new Thread(this, "Network Faults maker : undefined"); - this.socket = socket; - this.address = address; + private class Bagot implements Runnable { + + private final Thread processus; + private final Socket socket; + private final InetAddress address; + + public Bagot(Random rnd, Socket socket, InetAddress address) { + this.processus = new Thread(this, "Network Faults maker : undefined"); + this.socket = socket; + this.address = address; + } + + public void start() { + this.processus.setName("Network Faults maker : " + this.socket.toString()); + this.processus.start(); + } + + @Override + public void run() { + int lastDelayVal; + Integer lastDelay; + while (!this.processus.isInterrupted()) { + if (!this.socket.isClosed()) { + try { + lastDelay = closeIter.get(this.address); + if (lastDelay == null) { + lastDelayVal = 0; + } + else { + lastDelayVal = lastDelay.intValue(); + if (lastDelayVal > 10) + lastDelayVal += 20; + else + lastDelayVal += 1; + } + + lastDelay = new Integer(lastDelayVal); + + LOG.info("Trying to close client socket " + socket.toString() + " in " + lastDelayVal + " milliseconds"); + + try { + Thread.sleep(lastDelayVal); + } + catch (InterruptedException e) { + this.processus.interrupt(); + Thread.currentThread().interrupt(); + } + catch (IllegalArgumentException e) { + } + + this.socket.close(); + closeIter.put(this.address, lastDelay); + LOG.info("Client socket " + this.socket.toString() + " is closed."); + } + catch (IOException e) { + } + } + + this.processus.interrupt(); } + } + } - public void start() { - this.processus.setName("Network Faults maker : " + this.socket.toString()); - this.processus.start(); - } + private final Bagot bagot; + private final Socket socket; - @Override - public void run() { - int lastDelayVal; - Integer lastDelay; - while (!this.processus.isInterrupted()) { - if (!this.socket.isClosed()) { - try { - lastDelay = closeIter.get(this.address); - if (lastDelay == null) { - lastDelayVal = 0; - } else { - lastDelayVal = lastDelay.intValue(); - if (lastDelayVal > 10) - lastDelayVal += 20; - else - lastDelayVal += 1; - } + public SocketTst(InetAddress address, int port, Random rnd) throws IOException { + this.socket = new Socket(address, port); + bagot = new Bagot(rnd, this.socket, address); + } - lastDelay = new Integer(lastDelayVal); + public SocketTst(InetAddress address, + int port, + InetAddress localAddr, + int localPort, + Random rnd) throws IOException { + this.socket = new Socket(address, port, localAddr, localPort); + bagot = new Bagot(rnd, this.socket, address); + } - LOG.info("Trying to close client socket " + socket.toString() + " in " + lastDelayVal + " milliseconds"); + public SocketTst(String address, int port, Random rnd) throws UnknownHostException, IOException { + this.socket = new Socket(address, port); + bagot = new Bagot(rnd, this.socket, InetAddress.getByName(address)); + } - try { - Thread.sleep(lastDelayVal); - } catch (InterruptedException e) { - this.processus.interrupt(); - Thread.currentThread().interrupt(); - } catch (IllegalArgumentException e) { - } + public SocketTst(String address, int port, InetAddress localAddr, int localPort, Random rnd) throws IOException { + this.socket = new Socket(address, port, localAddr, localPort); + bagot = new Bagot(rnd, this.socket, InetAddress.getByName(address)); + } - this.socket.close(); - closeIter.put(this.address, lastDelay); - LOG.info("Client socket " + this.socket.toString() + " is closed."); - } catch (IOException e) { - } - } + public Socket getSocket() { + return this.socket; + } - this.processus.interrupt(); - } - } - } + public void startBagot() { + bagot.start(); + } + } - private final Bagot bagot; - private final Socket socket; + ; - public SocketTst(InetAddress address, int port, Random rnd) throws IOException { - this.socket = new Socket(address, port); - bagot = new Bagot(rnd, this.socket, address); - } + private final Random rnd; - public SocketTst(InetAddress address, int port, InetAddress localAddr, int localPort, Random rnd) throws IOException { - this.socket = new Socket(address, port, localAddr, localPort); - bagot = new Bagot(rnd, this.socket, address); - } + public SocketTstFactory() { + super(); + LOG.info("Creating a new SocketTstFactory"); + this.rnd = new Random(); + } - public SocketTst(String address, int port, Random rnd) throws UnknownHostException, IOException { - this.socket = new Socket(address, port); - bagot = new Bagot(rnd, this.socket, InetAddress.getByName(address)); - } + @Override + public Socket createSocket(InetAddress host, int port) throws IOException { + SocketTst sockTst; + sockTst = new SocketTst(host, port, this.rnd); + sockTst.startBagot(); + return sockTst.getSocket(); + } - public SocketTst(String address, int port, InetAddress localAddr, int localPort, Random rnd) throws IOException { - this.socket = new Socket(address, port, localAddr, localPort); - bagot = new Bagot(rnd, this.socket, InetAddress.getByName(address)); - } + @Override + public Socket createSocket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException { + SocketTst sockTst; + sockTst = new SocketTst(host, port, localAddress, localPort, this.rnd); + sockTst.startBagot(); + return sockTst.getSocket(); + } - public Socket getSocket() { - return this.socket; - } + @Override + public Socket createSocket(String host, int port) throws IOException { + SocketTst sockTst; + sockTst = new SocketTst(host, port, this.rnd); + sockTst.startBagot(); + return sockTst.getSocket(); + } - public void startBagot() { - bagot.start(); - } - }; + @Override + public Socket createSocket(String host, int port, InetAddress localAddress, int localPort) throws IOException { + SocketTst sockTst; + sockTst = new SocketTst(host, port, localAddress, localPort, this.rnd); + sockTst.startBagot(); + return sockTst.getSocket(); + } - private final Random rnd; + private final static SocketTstFactory client = new SocketTstFactory(); - public SocketTstFactory() { - super(); - LOG.info("Creating a new SocketTstFactory"); - this.rnd = new Random(); - } - - @Override - public Socket createSocket(InetAddress host, int port) throws IOException { - SocketTst sockTst; - sockTst = new SocketTst(host, port, this.rnd); - sockTst.startBagot(); - return sockTst.getSocket(); - } - - @Override - public Socket createSocket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException { - SocketTst sockTst; - sockTst = new SocketTst(host, port, localAddress, localPort, this.rnd); - sockTst.startBagot(); - return sockTst.getSocket(); - } - - @Override - public Socket createSocket(String host, int port) throws IOException { - SocketTst sockTst; - sockTst = new SocketTst(host, port, this.rnd); - sockTst.startBagot(); - return sockTst.getSocket(); - } - - @Override - public Socket createSocket(String host, int port, InetAddress localAddress, int localPort) throws IOException { - SocketTst sockTst; - sockTst = new SocketTst(host, port, localAddress, localPort, this.rnd); - sockTst.startBagot(); - return sockTst.getSocket(); - } - - private final static SocketTstFactory client = new SocketTstFactory(); - - public static SocketFactory getDefault() { - return client; - } + public static SocketFactory getDefault() { + return client; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslBrokerServiceTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslBrokerServiceTest.java index 5c8d03af2a..dc59997840 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslBrokerServiceTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslBrokerServiceTest.java @@ -34,6 +34,7 @@ import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import junit.framework.Test; + import junit.textui.TestRunner; import org.apache.activemq.broker.BrokerService; @@ -46,149 +47,150 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SslBrokerServiceTest extends TransportBrokerTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(SslBrokerServiceTest.class); - TransportConnector needClientAuthConnector; - TransportConnector limitedCipherSuites; - - protected String getBindLocation() { - return "ssl://localhost:0"; - } - - @Override - protected BrokerService createBroker() throws Exception { - - // http://java.sun.com/javase/javaseforbusiness/docs/TLSReadme.html - // work around: javax.net.ssl.SSLHandshakeException: renegotiation is not allowed - System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true"); - - SslBrokerService service = new SslBrokerService(); - service.setPersistent(false); - - KeyManager[] km = getKeyManager(); - TrustManager[] tm = getTrustManager(); - connector = service.addSslConnector(getBindLocation(), km, tm, null); - limitedCipherSuites = service.addSslConnector("ssl://localhost:0?transport.enabledCipherSuites=SSL_RSA_WITH_RC4_128_SHA,SSL_DH_anon_WITH_3DES_EDE_CBC_SHA", km, tm, null); - needClientAuthConnector = service.addSslConnector("ssl://localhost:0?transport.needClientAuth=true", km, tm, null); - - // for client side - SslTransportFactory sslFactory = new SslTransportFactory(); - SslContext ctx = new SslContext(km, tm, null); - SslContext.setCurrentSslContext(ctx); - TransportFactory.registerTransportFactory("ssl", sslFactory); - - return service; - } + private static final Logger LOG = LoggerFactory.getLogger(SslBrokerServiceTest.class); - public void testNeedClientAuthReject() throws Exception { - SSLContext context = SSLContext.getInstance("TLS"); - // no client cert - context.init(null, getTrustManager(), null); - - try { - makeSSLConnection(context, null, needClientAuthConnector); - fail("expected failure on no client cert"); - } catch (SSLException expected) { - expected.printStackTrace(); - } - // should work with regular connector - makeSSLConnection(context, null, connector); - } + TransportConnector needClientAuthConnector; + TransportConnector limitedCipherSuites; - public void testNeedClientAuthSucceed() throws Exception { - SSLContext context = SSLContext.getInstance("TLS"); - context.init(getKeyManager(), getTrustManager(), null); - makeSSLConnection(context, null, needClientAuthConnector); - } - - public void testCipherSuitesDisabled() throws Exception { - SSLContext context = SSLContext.getInstance("TLS"); - context.init(getKeyManager(), getTrustManager(), null); - - // Enable only one cipher suite which is not enabled on the server - try { - makeSSLConnection(context, new String[]{ "SSL_RSA_WITH_RC4_128_MD5" }, limitedCipherSuites); - fail("expected failure on non allowed cipher suite"); - } catch (SSLException expectedOnNotAnAvailableSuite) { - } + protected String getBindLocation() { + return "ssl://localhost:0"; + } - // ok with the enabled one - makeSSLConnection(context, new String[]{ "SSL_RSA_WITH_RC4_128_SHA" }, limitedCipherSuites); - } + @Override + protected BrokerService createBroker() throws Exception { - private void makeSSLConnection(SSLContext context, String enabledSuites[], TransportConnector connector) throws Exception, - UnknownHostException, SocketException { - SSLSocket sslSocket = (SSLSocket) context.getSocketFactory().createSocket("localhost", connector.getUri().getPort()); - - if (enabledSuites != null) { - sslSocket.setEnabledCipherSuites(enabledSuites); - } - sslSocket.setSoTimeout(5000); - - SSLSession session = sslSocket.getSession(); - sslSocket.startHandshake(); - LOG.info("cyphersuite: " + session.getCipherSuite()); - LOG.info("peer port: " + session.getPeerPort()); - LOG.info("peer cert: " + session.getPeerCertificateChain()[0].toString()); - } - - public static TrustManager[] getTrustManager() throws Exception { - TrustManager[] trustStoreManagers = null; - KeyStore trustedCertStore = KeyStore.getInstance(SslTransportBrokerTest.KEYSTORE_TYPE); - - trustedCertStore.load(new FileInputStream(SslTransportBrokerTest.TRUST_KEYSTORE), null); - TrustManagerFactory tmf = - TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - - tmf.init(trustedCertStore); - trustStoreManagers = tmf.getTrustManagers(); - return trustStoreManagers; - } + // http://java.sun.com/javase/javaseforbusiness/docs/TLSReadme.html + // work around: javax.net.ssl.SSLHandshakeException: renegotiation is not allowed + System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true"); - public static KeyManager[] getKeyManager() throws Exception { - KeyManagerFactory kmf = - KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); - KeyStore ks = KeyStore.getInstance(SslTransportBrokerTest.KEYSTORE_TYPE); - KeyManager[] keystoreManagers = null; - - byte[] sslCert = loadClientCredential(SslTransportBrokerTest.SERVER_KEYSTORE); - - - if (sslCert != null && sslCert.length > 0) { - ByteArrayInputStream bin = new ByteArrayInputStream(sslCert); - ks.load(bin, SslTransportBrokerTest.PASSWORD.toCharArray()); - kmf.init(ks, SslTransportBrokerTest.PASSWORD.toCharArray()); - keystoreManagers = kmf.getKeyManagers(); - } - return keystoreManagers; - } + SslBrokerService service = new SslBrokerService(); + service.setPersistent(false); - private static byte[] loadClientCredential(String fileName) throws IOException { - if (fileName == null) { - return null; - } - FileInputStream in = new FileInputStream(fileName); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - byte[] buf = new byte[512]; - int i = in.read(buf); - while (i > 0) { - out.write(buf, 0, i); - i = in.read(buf); - } - in.close(); - return out.toByteArray(); - } + KeyManager[] km = getKeyManager(); + TrustManager[] tm = getTrustManager(); + connector = service.addSslConnector(getBindLocation(), km, tm, null); + limitedCipherSuites = service.addSslConnector("ssl://localhost:0?transport.enabledCipherSuites=SSL_RSA_WITH_RC4_128_SHA,SSL_DH_anon_WITH_3DES_EDE_CBC_SHA", km, tm, null); + needClientAuthConnector = service.addSslConnector("ssl://localhost:0?transport.needClientAuth=true", km, tm, null); - protected void setUp() throws Exception { - maxWait = 10000; - super.setUp(); - } + // for client side + SslTransportFactory sslFactory = new SslTransportFactory(); + SslContext ctx = new SslContext(km, tm, null); + SslContext.setCurrentSslContext(ctx); + TransportFactory.registerTransportFactory("ssl", sslFactory); - public static Test suite() { - return suite(SslBrokerServiceTest.class); - } + return service; + } - public static void main(String[] args) { - TestRunner.run(suite()); - } + public void testNeedClientAuthReject() throws Exception { + SSLContext context = SSLContext.getInstance("TLS"); + // no client cert + context.init(null, getTrustManager(), null); + + try { + makeSSLConnection(context, null, needClientAuthConnector); + fail("expected failure on no client cert"); + } + catch (SSLException expected) { + expected.printStackTrace(); + } + // should work with regular connector + makeSSLConnection(context, null, connector); + } + + public void testNeedClientAuthSucceed() throws Exception { + SSLContext context = SSLContext.getInstance("TLS"); + context.init(getKeyManager(), getTrustManager(), null); + makeSSLConnection(context, null, needClientAuthConnector); + } + + public void testCipherSuitesDisabled() throws Exception { + SSLContext context = SSLContext.getInstance("TLS"); + context.init(getKeyManager(), getTrustManager(), null); + + // Enable only one cipher suite which is not enabled on the server + try { + makeSSLConnection(context, new String[]{"SSL_RSA_WITH_RC4_128_MD5"}, limitedCipherSuites); + fail("expected failure on non allowed cipher suite"); + } + catch (SSLException expectedOnNotAnAvailableSuite) { + } + + // ok with the enabled one + makeSSLConnection(context, new String[]{"SSL_RSA_WITH_RC4_128_SHA"}, limitedCipherSuites); + } + + private void makeSSLConnection(SSLContext context, + String enabledSuites[], + TransportConnector connector) throws Exception, UnknownHostException, SocketException { + SSLSocket sslSocket = (SSLSocket) context.getSocketFactory().createSocket("localhost", connector.getUri().getPort()); + + if (enabledSuites != null) { + sslSocket.setEnabledCipherSuites(enabledSuites); + } + sslSocket.setSoTimeout(5000); + + SSLSession session = sslSocket.getSession(); + sslSocket.startHandshake(); + LOG.info("cyphersuite: " + session.getCipherSuite()); + LOG.info("peer port: " + session.getPeerPort()); + LOG.info("peer cert: " + session.getPeerCertificateChain()[0].toString()); + } + + public static TrustManager[] getTrustManager() throws Exception { + TrustManager[] trustStoreManagers = null; + KeyStore trustedCertStore = KeyStore.getInstance(SslTransportBrokerTest.KEYSTORE_TYPE); + + trustedCertStore.load(new FileInputStream(SslTransportBrokerTest.TRUST_KEYSTORE), null); + TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + + tmf.init(trustedCertStore); + trustStoreManagers = tmf.getTrustManagers(); + return trustStoreManagers; + } + + public static KeyManager[] getKeyManager() throws Exception { + KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + KeyStore ks = KeyStore.getInstance(SslTransportBrokerTest.KEYSTORE_TYPE); + KeyManager[] keystoreManagers = null; + + byte[] sslCert = loadClientCredential(SslTransportBrokerTest.SERVER_KEYSTORE); + + if (sslCert != null && sslCert.length > 0) { + ByteArrayInputStream bin = new ByteArrayInputStream(sslCert); + ks.load(bin, SslTransportBrokerTest.PASSWORD.toCharArray()); + kmf.init(ks, SslTransportBrokerTest.PASSWORD.toCharArray()); + keystoreManagers = kmf.getKeyManagers(); + } + return keystoreManagers; + } + + private static byte[] loadClientCredential(String fileName) throws IOException { + if (fileName == null) { + return null; + } + FileInputStream in = new FileInputStream(fileName); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buf = new byte[512]; + int i = in.read(buf); + while (i > 0) { + out.write(buf, 0, i); + i = in.read(buf); + } + in.close(); + return out.toByteArray(); + } + + protected void setUp() throws Exception { + maxWait = 10000; + super.setUp(); + } + + public static Test suite() { + return suite(SslBrokerServiceTest.class); + } + + public static void main(String[] args) { + TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslContextBrokerServiceTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslContextBrokerServiceTest.java index 4d44c461e2..5e5366b4ba 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslContextBrokerServiceTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslContextBrokerServiceTest.java @@ -31,36 +31,36 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; */ public class SslContextBrokerServiceTest extends TestCase { - private ClassPathXmlApplicationContext context; - private BrokerService broker; - private TransportConnector connector; + private ClassPathXmlApplicationContext context; + private BrokerService broker; + private TransportConnector connector; - public void testConfiguration() throws URISyntaxException { + public void testConfiguration() throws URISyntaxException { - assertNotNull(broker); - assertNotNull(connector); + assertNotNull(broker); + assertNotNull(connector); - assertEquals(new URI("ssl://localhost:61616"), connector.getUri()); + assertEquals(new URI("ssl://localhost:61616"), connector.getUri()); - assertNotNull(broker.getSslContext()); - assertFalse(broker.getSslContext().getKeyManagers().isEmpty()); - assertFalse(broker.getSslContext().getTrustManagers().isEmpty()); + assertNotNull(broker.getSslContext()); + assertFalse(broker.getSslContext().getKeyManagers().isEmpty()); + assertFalse(broker.getSslContext().getTrustManagers().isEmpty()); - } + } - @Override - protected void setUp() throws Exception { - Thread.currentThread().setContextClassLoader(SslContextBrokerServiceTest.class.getClassLoader()); - context = new ClassPathXmlApplicationContext("org/apache/activemq/transport/tcp/activemq-ssl.xml"); - Map beansOfType = context.getBeansOfType(BrokerService.class); - broker = beansOfType.values().iterator().next(); - connector = broker.getTransportConnectors().get(0); - } + @Override + protected void setUp() throws Exception { + Thread.currentThread().setContextClassLoader(SslContextBrokerServiceTest.class.getClassLoader()); + context = new ClassPathXmlApplicationContext("org/apache/activemq/transport/tcp/activemq-ssl.xml"); + Map beansOfType = context.getBeansOfType(BrokerService.class); + broker = beansOfType.values().iterator().next(); + connector = broker.getTransportConnectors().get(0); + } - @Override - protected void tearDown() throws Exception { + @Override + protected void tearDown() throws Exception { - context.destroy(); - } + context.destroy(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslContextNBrokerServiceTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslContextNBrokerServiceTest.java index 03a1d84148..ee47e5c12c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslContextNBrokerServiceTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslContextNBrokerServiceTest.java @@ -41,107 +41,110 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; import static org.junit.Assert.*; public class SslContextNBrokerServiceTest { - private static final transient Logger LOG = LoggerFactory.getLogger(SslContextNBrokerServiceTest.class); - private ClassPathXmlApplicationContext context; - Map beansOfType; + private static final transient Logger LOG = LoggerFactory.getLogger(SslContextNBrokerServiceTest.class); - @Test(timeout = 3 * 60 * 1000) - public void testDummyConfigurationIsolation() throws Exception { - assertTrue("dummy bean has dummy cert", verifyCredentials("dummy")); - } + private ClassPathXmlApplicationContext context; + Map beansOfType; - @Test(timeout = 3 * 60 * 1000) - public void testActiveMQDotOrgConfigurationIsolation() throws Exception { - assertTrue("good bean has amq cert", verifyCredentials("activemq.org")); - } + @Test(timeout = 3 * 60 * 1000) + public void testDummyConfigurationIsolation() throws Exception { + assertTrue("dummy bean has dummy cert", verifyCredentials("dummy")); + } - private boolean verifyCredentials(String name) throws Exception { - boolean result = false; - BrokerService broker = getBroker(name); - assertNotNull(name, broker); - broker.start(); - broker.waitUntilStarted(); - try { - result = verifySslCredentials(broker); - } finally { - broker.stop(); - } - return result; - } + @Test(timeout = 3 * 60 * 1000) + public void testActiveMQDotOrgConfigurationIsolation() throws Exception { + assertTrue("good bean has amq cert", verifyCredentials("activemq.org")); + } - private boolean verifySslCredentials(BrokerService broker) throws Exception { - TransportConnector connector = broker.getTransportConnectors().get(0); - URI brokerUri = connector.getConnectUri(); + private boolean verifyCredentials(String name) throws Exception { + boolean result = false; + BrokerService broker = getBroker(name); + assertNotNull(name, broker); + broker.start(); + broker.waitUntilStarted(); + try { + result = verifySslCredentials(broker); + } + finally { + broker.stop(); + } + return result; + } - SSLContext context = SSLContext.getInstance("TLS"); - CertChainCatcher catcher = new CertChainCatcher(); - context.init(null, new TrustManager[] { catcher }, null); + private boolean verifySslCredentials(BrokerService broker) throws Exception { + TransportConnector connector = broker.getTransportConnectors().get(0); + URI brokerUri = connector.getConnectUri(); - SSLSocketFactory factory = context.getSocketFactory(); - LOG.info("Connecting to broker: " + broker.getBrokerName() + " on: " + brokerUri.getHost() + ":" + brokerUri.getPort()); - SSLSocket socket = (SSLSocket) factory.createSocket(brokerUri.getHost(), brokerUri.getPort()); - socket.setSoTimeout(2 * 60 * 1000); - socket.startHandshake(); - socket.close(); + SSLContext context = SSLContext.getInstance("TLS"); + CertChainCatcher catcher = new CertChainCatcher(); + context.init(null, new TrustManager[]{catcher}, null); - boolean matches = false; - if (catcher.serverCerts != null) { - for (int i = 0; i < catcher.serverCerts.length; i++) { - X509Certificate cert = catcher.serverCerts[i]; - LOG.info(" " + (i + 1) + " Issuer " + cert.getIssuerDN()); + SSLSocketFactory factory = context.getSocketFactory(); + LOG.info("Connecting to broker: " + broker.getBrokerName() + " on: " + brokerUri.getHost() + ":" + brokerUri.getPort()); + SSLSocket socket = (SSLSocket) factory.createSocket(brokerUri.getHost(), brokerUri.getPort()); + socket.setSoTimeout(2 * 60 * 1000); + socket.startHandshake(); + socket.close(); + + boolean matches = false; + if (catcher.serverCerts != null) { + for (int i = 0; i < catcher.serverCerts.length; i++) { + X509Certificate cert = catcher.serverCerts[i]; + LOG.info(" " + (i + 1) + " Issuer " + cert.getIssuerDN()); + } + if (catcher.serverCerts.length > 0) { + String issuer = catcher.serverCerts[0].getIssuerDN().toString(); + if (issuer.indexOf(broker.getBrokerName()) != -1) { + matches = true; } - if (catcher.serverCerts.length > 0) { - String issuer = catcher.serverCerts[0].getIssuerDN().toString(); - if (issuer.indexOf(broker.getBrokerName()) != -1) { - matches = true; - } - } - } - return matches; - } + } + } + return matches; + } - private BrokerService getBroker(String name) { - BrokerService result = null; - Iterator iterator = beansOfType.values().iterator(); - while (iterator.hasNext()) { - BrokerService candidate = iterator.next(); - if (candidate.getBrokerName().equals(name)) { - result = candidate; - break; - } - } - return result; - } + private BrokerService getBroker(String name) { + BrokerService result = null; + Iterator iterator = beansOfType.values().iterator(); + while (iterator.hasNext()) { + BrokerService candidate = iterator.next(); + if (candidate.getBrokerName().equals(name)) { + result = candidate; + break; + } + } + return result; + } - @Before - public void setUp() throws Exception { - // System.setProperty("javax.net.debug", "ssl"); - Thread.currentThread().setContextClassLoader(SslContextNBrokerServiceTest.class.getClassLoader()); - context = new ClassPathXmlApplicationContext("org/apache/activemq/transport/tcp/n-brokers-ssl.xml"); - beansOfType = context.getBeansOfType(BrokerService.class); - } + @Before + public void setUp() throws Exception { + // System.setProperty("javax.net.debug", "ssl"); + Thread.currentThread().setContextClassLoader(SslContextNBrokerServiceTest.class.getClassLoader()); + context = new ClassPathXmlApplicationContext("org/apache/activemq/transport/tcp/n-brokers-ssl.xml"); + beansOfType = context.getBeansOfType(BrokerService.class); + } - @After - public void tearDown() throws Exception { - context.destroy(); - } + @After + public void tearDown() throws Exception { + context.destroy(); + } - class CertChainCatcher implements X509TrustManager { - X509Certificate[] serverCerts; + class CertChainCatcher implements X509TrustManager { - @Override - public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { - } + X509Certificate[] serverCerts; - @Override - public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { - serverCerts = arg0; - } + @Override + public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { + } - @Override - public X509Certificate[] getAcceptedIssuers() { - return null; - } - } + @Override + public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { + serverCerts = arg0; + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslSocketHelper.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslSocketHelper.java index 52a5db1eda..6413116b91 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslSocketHelper.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslSocketHelper.java @@ -23,22 +23,23 @@ import javax.management.remote.JMXPrincipal; import javax.net.ssl.SSLSocket; /** - * + * */ public final class SslSocketHelper { - private SslSocketHelper() { - } + private SslSocketHelper() { + } - public static SSLSocket createSSLSocket(String certDistinguishedName, boolean wantAuth, boolean needAuth) - throws IOException { - JMXPrincipal principal = new JMXPrincipal(certDistinguishedName); - X509Certificate cert = new StubX509Certificate(principal); - StubSSLSession sslSession = new StubSSLSession(cert); + public static SSLSocket createSSLSocket(String certDistinguishedName, + boolean wantAuth, + boolean needAuth) throws IOException { + JMXPrincipal principal = new JMXPrincipal(certDistinguishedName); + X509Certificate cert = new StubX509Certificate(principal); + StubSSLSession sslSession = new StubSSLSession(cert); - StubSSLSocket sslSocket = new StubSSLSocket(sslSession); - sslSocket.setWantClientAuth(wantAuth); - sslSocket.setNeedClientAuth(needAuth); - return sslSocket; - } + StubSSLSocket sslSocket = new StubSSLSocket(sslSession); + sslSocket.setWantClientAuth(wantAuth); + sslSocket.setNeedClientAuth(needAuth); + return sslSocket; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslTransportBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslTransportBrokerTest.java index de07a74f86..dae1249481 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslTransportBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslTransportBrokerTest.java @@ -18,45 +18,47 @@ package org.apache.activemq.transport.tcp; import java.net.URI; import java.net.URISyntaxException; + import junit.framework.Test; + import junit.textui.TestRunner; import org.apache.activemq.transport.TransportBrokerTestSupport; public class SslTransportBrokerTest extends TransportBrokerTestSupport { - public static final String KEYSTORE_TYPE = "jks"; - public static final String PASSWORD = "password"; - public static final String SERVER_KEYSTORE = "src/test/resources/server.keystore"; - public static final String TRUST_KEYSTORE = "src/test/resources/client.keystore"; + public static final String KEYSTORE_TYPE = "jks"; + public static final String PASSWORD = "password"; + public static final String SERVER_KEYSTORE = "src/test/resources/server.keystore"; + public static final String TRUST_KEYSTORE = "src/test/resources/client.keystore"; - protected String getBindLocation() { - return "ssl://localhost:0?transport.soWriteTimeout=20000"; - } + protected String getBindLocation() { + return "ssl://localhost:0?transport.soWriteTimeout=20000"; + } - @Override - protected URI getBindURI() throws URISyntaxException { - return new URI("ssl://localhost:0?soWriteTimeout=20000"); - } + @Override + protected URI getBindURI() throws URISyntaxException { + return new URI("ssl://localhost:0?soWriteTimeout=20000"); + } - protected void setUp() throws Exception { - System.setProperty("javax.net.ssl.trustStore", TRUST_KEYSTORE); - System.setProperty("javax.net.ssl.trustStorePassword", PASSWORD); - System.setProperty("javax.net.ssl.trustStoreType", KEYSTORE_TYPE); - System.setProperty("javax.net.ssl.keyStore", SERVER_KEYSTORE); - System.setProperty("javax.net.ssl.keyStorePassword", PASSWORD); - System.setProperty("javax.net.ssl.keyStoreType", KEYSTORE_TYPE); - //System.setProperty("javax.net.debug", "ssl,handshake,data,trustmanager"); + protected void setUp() throws Exception { + System.setProperty("javax.net.ssl.trustStore", TRUST_KEYSTORE); + System.setProperty("javax.net.ssl.trustStorePassword", PASSWORD); + System.setProperty("javax.net.ssl.trustStoreType", KEYSTORE_TYPE); + System.setProperty("javax.net.ssl.keyStore", SERVER_KEYSTORE); + System.setProperty("javax.net.ssl.keyStorePassword", PASSWORD); + System.setProperty("javax.net.ssl.keyStoreType", KEYSTORE_TYPE); + //System.setProperty("javax.net.debug", "ssl,handshake,data,trustmanager"); - maxWait = 10000; - super.setUp(); - } + maxWait = 10000; + super.setUp(); + } - public static Test suite() { - return suite(SslTransportBrokerTest.class); - } + public static Test suite() { + return suite(SslTransportBrokerTest.class); + } - public static void main(String[] args) { - TestRunner.run(suite()); - } + public static void main(String[] args) { + TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslTransportFactoryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslTransportFactoryTest.java index af9d6725ba..b69c468ab0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslTransportFactoryTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslTransportFactoryTest.java @@ -23,125 +23,120 @@ import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; + import org.apache.activemq.openwire.OpenWireFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SslTransportFactoryTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(SslTransportFactoryTest.class); - private SslTransportFactory factory; - private boolean verbose; + private static final Logger LOG = LoggerFactory.getLogger(SslTransportFactoryTest.class); - protected void setUp() throws Exception { - factory = new SslTransportFactory(); - } + private SslTransportFactory factory; + private boolean verbose; - protected void tearDown() throws Exception { - super.tearDown(); - } + protected void setUp() throws Exception { + factory = new SslTransportFactory(); + } - public void testBindServerOptions() throws IOException { + protected void tearDown() throws Exception { + super.tearDown(); + } - SslTransportServer sslTransportServer = null; + public void testBindServerOptions() throws IOException { - for (int i = 0; i < 4; ++i) { - final boolean wantClientAuth = (i & 0x1) == 1; - final boolean needClientAuth = (i & 0x2) == 1; + SslTransportServer sslTransportServer = null; - String options = "wantClientAuth=" + (wantClientAuth ? "true" : "false") + "&needClientAuth=" - + (needClientAuth ? "true" : "false"); + for (int i = 0; i < 4; ++i) { + final boolean wantClientAuth = (i & 0x1) == 1; + final boolean needClientAuth = (i & 0x2) == 1; - try { - sslTransportServer = (SslTransportServer)factory.doBind(new URI( - "ssl://localhost:61616?" - + options)); - } catch (Exception e) { - fail("Unable to bind to address: " + e.getMessage()); + String options = "wantClientAuth=" + (wantClientAuth ? "true" : "false") + "&needClientAuth=" + (needClientAuth ? "true" : "false"); + + try { + sslTransportServer = (SslTransportServer) factory.doBind(new URI("ssl://localhost:61616?" + options)); + } + catch (Exception e) { + fail("Unable to bind to address: " + e.getMessage()); + } + + assertEquals("Created ServerSocket did not have correct wantClientAuth status.", sslTransportServer.getWantClientAuth(), wantClientAuth); + + assertEquals("Created ServerSocket did not have correct needClientAuth status.", sslTransportServer.getNeedClientAuth(), needClientAuth); + + try { + sslTransportServer.stop(); + } + catch (Exception e) { + fail("Unable to stop TransportServer: " + e.getMessage()); + } + } + } + + private int getMthNaryDigit(int number, int digitIdx, int numBase) { + return (number / ((int) Math.pow(numBase, digitIdx))) % numBase; + } + + public void testCompositeConfigure() throws IOException { + // The 5 options being tested. + int optionSettings[] = new int[5]; + + String optionNames[] = {"wantClientAuth", "needClientAuth", "socket.wantClientAuth", "socket.needClientAuth", "socket.useClientMode"}; + + // Using a trinary interpretation of i to set all possible values of + // stub options for socket and transport. + // 2 transport options, 3 socket options, 3 settings for each option => + // 3^5 = 243 combos. + for (int i = 0; i < 243; ++i) { + Map options = new HashMap(); + + for (int j = 0; j < 5; ++j) { + // -1 since the option range is [-1,1], not [0,2]. + optionSettings[j] = getMthNaryDigit(i, j, 3) - 1; + + if (optionSettings[j] != -1) { + options.put(optionNames[j], optionSettings[j] == 1 ? "true" : "false"); } + } - assertEquals("Created ServerSocket did not have correct wantClientAuth status.", - sslTransportServer.getWantClientAuth(), wantClientAuth); + StubSSLSocket socketStub = new StubSSLSocket(null); + StubSslTransport transport = null; - assertEquals("Created ServerSocket did not have correct needClientAuth status.", - sslTransportServer.getNeedClientAuth(), needClientAuth); + try { + transport = new StubSslTransport(null, socketStub); + } + catch (Exception e) { + fail("Unable to create StubSslTransport: " + e.getMessage()); + } - try { - sslTransportServer.stop(); - } catch (Exception e) { - fail("Unable to stop TransportServer: " + e.getMessage()); + if (verbose) { + LOG.info(""); + LOG.info("Iteration: " + i); + LOG.info("Map settings: " + options); + for (int x = 0; x < optionSettings.length; x++) { + LOG.info("optionSetting[" + x + "] = " + optionSettings[x]); } - } - } + } - private int getMthNaryDigit(int number, int digitIdx, int numBase) { - return (number / ((int)Math.pow(numBase, digitIdx))) % numBase; - } + factory.compositeConfigure(transport, new OpenWireFormat(), options); - public void testCompositeConfigure() throws IOException { - // The 5 options being tested. - int optionSettings[] = new int[5]; + // lets start the transport to force the introspection + try { + transport.start(); + } + catch (Exception e) { + // ignore bad connection + } - String optionNames[] = {"wantClientAuth", "needClientAuth", "socket.wantClientAuth", - "socket.needClientAuth", "socket.useClientMode"}; + if (socketStub.getWantClientAuthStatus() != optionSettings[2]) { + LOG.info("sheiite"); + } - // Using a trinary interpretation of i to set all possible values of - // stub options for socket and transport. - // 2 transport options, 3 socket options, 3 settings for each option => - // 3^5 = 243 combos. - for (int i = 0; i < 243; ++i) { - Map options = new HashMap(); - - for (int j = 0; j < 5; ++j) { - // -1 since the option range is [-1,1], not [0,2]. - optionSettings[j] = getMthNaryDigit(i, j, 3) - 1; - - if (optionSettings[j] != -1) { - options.put(optionNames[j], optionSettings[j] == 1 ? "true" : "false"); - } - } - - StubSSLSocket socketStub = new StubSSLSocket(null); - StubSslTransport transport = null; - - try { - transport = new StubSslTransport(null, socketStub); - } catch (Exception e) { - fail("Unable to create StubSslTransport: " + e.getMessage()); - } - - if (verbose) { - LOG.info(""); - LOG.info("Iteration: " + i); - LOG.info("Map settings: " + options); - for (int x = 0; x < optionSettings.length; x++) { - LOG.info("optionSetting[" + x + "] = " + optionSettings[x]); - } - } - - factory.compositeConfigure(transport, new OpenWireFormat(), options); - - // lets start the transport to force the introspection - try { - transport.start(); - } catch (Exception e) { - // ignore bad connection - } - - if (socketStub.getWantClientAuthStatus() != optionSettings[2]) { - LOG.info("sheiite"); - } - - assertEquals("wantClientAuth was not properly set for iteration: " + i, optionSettings[0], - transport.getWantClientAuthStatus()); - assertEquals("needClientAuth was not properly set for iteration: " + i, optionSettings[1], - transport.getNeedClientAuthStatus()); - assertEquals("socket.wantClientAuth was not properly set for iteration: " + i, optionSettings[2], - socketStub.getWantClientAuthStatus()); - assertEquals("socket.needClientAuth was not properly set for iteration: " + i, optionSettings[3], - socketStub.getNeedClientAuthStatus()); - assertEquals("socket.useClientMode was not properly set for iteration: " + i, optionSettings[4], - socketStub.getUseClientModeStatus()); - } - } + assertEquals("wantClientAuth was not properly set for iteration: " + i, optionSettings[0], transport.getWantClientAuthStatus()); + assertEquals("needClientAuth was not properly set for iteration: " + i, optionSettings[1], transport.getNeedClientAuthStatus()); + assertEquals("socket.wantClientAuth was not properly set for iteration: " + i, optionSettings[2], socketStub.getWantClientAuthStatus()); + assertEquals("socket.needClientAuth was not properly set for iteration: " + i, optionSettings[3], socketStub.getNeedClientAuthStatus()); + assertEquals("socket.useClientMode was not properly set for iteration: " + i, optionSettings[4], socketStub.getUseClientModeStatus()); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslTransportServerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslTransportServerTest.java index 4053a5bf07..9ee01292ba 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslTransportServerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslTransportServerTest.java @@ -23,70 +23,71 @@ import java.net.URI; import junit.framework.TestCase; public class SslTransportServerTest extends TestCase { - private SslTransportServer sslTransportServer; - private StubSSLServerSocket sslServerSocket; - protected void setUp() throws Exception { - } + private SslTransportServer sslTransportServer; + private StubSSLServerSocket sslServerSocket; - protected void tearDown() throws Exception { - super.tearDown(); - } + protected void setUp() throws Exception { + } - private void createAndBindTransportServer(boolean wantClientAuth, boolean needClientAuth, String options) throws IOException { - sslServerSocket = new StubSSLServerSocket(); + protected void tearDown() throws Exception { + super.tearDown(); + } - StubSSLSocketFactory socketFactory = new StubSSLSocketFactory(sslServerSocket); + private void createAndBindTransportServer(boolean wantClientAuth, + boolean needClientAuth, + String options) throws IOException { + sslServerSocket = new StubSSLServerSocket(); - try { - sslTransportServer = new SslTransportServer(null, new URI("ssl://localhost:61616?" + options), socketFactory); - } catch (Exception e) { - fail("Unable to create SslTransportServer."); - } + StubSSLSocketFactory socketFactory = new StubSSLSocketFactory(sslServerSocket); - sslTransportServer.setWantClientAuth(wantClientAuth); - sslTransportServer.setNeedClientAuth(needClientAuth); + try { + sslTransportServer = new SslTransportServer(null, new URI("ssl://localhost:61616?" + options), socketFactory); + } + catch (Exception e) { + fail("Unable to create SslTransportServer."); + } - sslTransportServer.bind(); - } + sslTransportServer.setWantClientAuth(wantClientAuth); + sslTransportServer.setNeedClientAuth(needClientAuth); - public void testWantAndNeedClientAuthSetters() throws IOException { - for (int i = 0; i < 4; ++i) { - String options = ""; - singleTest(i, options); - } - } + sslTransportServer.bind(); + } - public void testWantAndNeedAuthReflection() throws IOException { - for (int i = 0; i < 4; ++i) { - String options = "wantClientAuth=" + (getWantClientAuth(i) ? "true" : "false") + - "&needClientAuth=" + (getNeedClientAuth(i) ? "true" : "false"); - singleTest(i, options); - } - } + public void testWantAndNeedClientAuthSetters() throws IOException { + for (int i = 0; i < 4; ++i) { + String options = ""; + singleTest(i, options); + } + } - private void singleTest(int i, String options) throws IOException { - final boolean wantClientAuth = getWantClientAuth(i); - final boolean needClientAuth = getNeedClientAuth(i); + public void testWantAndNeedAuthReflection() throws IOException { + for (int i = 0; i < 4; ++i) { + String options = "wantClientAuth=" + (getWantClientAuth(i) ? "true" : "false") + + "&needClientAuth=" + (getNeedClientAuth(i) ? "true" : "false"); + singleTest(i, options); + } + } - final int expectedWantStatus = (needClientAuth? StubSSLServerSocket.UNTOUCHED: wantClientAuth ? StubSSLServerSocket.TRUE : StubSSLServerSocket.UNTOUCHED); - final int expectedNeedStatus = (needClientAuth ? StubSSLServerSocket.TRUE : StubSSLServerSocket.UNTOUCHED ); + private void singleTest(int i, String options) throws IOException { + final boolean wantClientAuth = getWantClientAuth(i); + final boolean needClientAuth = getNeedClientAuth(i); + final int expectedWantStatus = (needClientAuth ? StubSSLServerSocket.UNTOUCHED : wantClientAuth ? StubSSLServerSocket.TRUE : StubSSLServerSocket.UNTOUCHED); + final int expectedNeedStatus = (needClientAuth ? StubSSLServerSocket.TRUE : StubSSLServerSocket.UNTOUCHED); - createAndBindTransportServer(wantClientAuth, needClientAuth, options); + createAndBindTransportServer(wantClientAuth, needClientAuth, options); - assertEquals("Created ServerSocket did not have correct wantClientAuth status. wantClientAuth: " + wantClientAuth + ", needClientAuth: " + needClientAuth, - expectedWantStatus, sslServerSocket.getWantClientAuthStatus()); + assertEquals("Created ServerSocket did not have correct wantClientAuth status. wantClientAuth: " + wantClientAuth + ", needClientAuth: " + needClientAuth, expectedWantStatus, sslServerSocket.getWantClientAuthStatus()); - assertEquals("Created ServerSocket did not have correct needClientAuth status. wantClientAuth: " + wantClientAuth + ", needClientAuth: " + needClientAuth, - expectedNeedStatus, sslServerSocket.getNeedClientAuthStatus()); - } + assertEquals("Created ServerSocket did not have correct needClientAuth status. wantClientAuth: " + wantClientAuth + ", needClientAuth: " + needClientAuth, expectedNeedStatus, sslServerSocket.getNeedClientAuthStatus()); + } - private boolean getNeedClientAuth(int i) { - return ((i & 0x2) == 0x2); - } + private boolean getNeedClientAuth(int i) { + return ((i & 0x2) == 0x2); + } - private boolean getWantClientAuth(int i) { - return ((i & 0x1) == 0x1); - } + private boolean getWantClientAuth(int i) { + return ((i & 0x1) == 0x1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslTransportTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslTransportTest.java index d049745450..2c7a3449ff 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslTransportTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslTransportTest.java @@ -24,6 +24,7 @@ import javax.management.remote.JMXPrincipal; import javax.net.ssl.SSLSocket; import junit.framework.TestCase; + import org.apache.activemq.command.ConnectionInfo; import org.apache.activemq.transport.StubTransportListener; import org.apache.activemq.wireformat.ObjectStreamWireFormat; @@ -33,64 +34,65 @@ import org.apache.activemq.wireformat.ObjectStreamWireFormat; */ public class SslTransportTest extends TestCase { - SSLSocket sslSocket; - StubTransportListener stubListener; + SSLSocket sslSocket; + StubTransportListener stubListener; - String username; - String password; - String certDistinguishedName; + String username; + String password; + String certDistinguishedName; - protected void setUp() throws Exception { - certDistinguishedName = "ThisNameIsDistinguished"; - username = "SomeUserName"; - password = "SomePassword"; - } + protected void setUp() throws Exception { + certDistinguishedName = "ThisNameIsDistinguished"; + username = "SomeUserName"; + password = "SomePassword"; + } - protected void tearDown() throws Exception { - super.tearDown(); - } + protected void tearDown() throws Exception { + super.tearDown(); + } - private void createTransportAndConsume(boolean wantAuth, boolean needAuth) throws IOException { - JMXPrincipal principal = new JMXPrincipal(certDistinguishedName); - X509Certificate cert = new StubX509Certificate(principal); - StubSSLSession sslSession = new StubSSLSession(cert); + private void createTransportAndConsume(boolean wantAuth, boolean needAuth) throws IOException { + JMXPrincipal principal = new JMXPrincipal(certDistinguishedName); + X509Certificate cert = new StubX509Certificate(principal); + StubSSLSession sslSession = new StubSSLSession(cert); - sslSocket = new StubSSLSocket(sslSession); - sslSocket.setWantClientAuth(wantAuth); - sslSocket.setNeedClientAuth(needAuth); + sslSocket = new StubSSLSocket(sslSession); + sslSocket.setWantClientAuth(wantAuth); + sslSocket.setNeedClientAuth(needAuth); - SslTransport transport = new SslTransport(new ObjectStreamWireFormat(), sslSocket); + SslTransport transport = new SslTransport(new ObjectStreamWireFormat(), sslSocket); - stubListener = new StubTransportListener(); + stubListener = new StubTransportListener(); - transport.setTransportListener(stubListener); + transport.setTransportListener(stubListener); - ConnectionInfo sentInfo = new ConnectionInfo(); + ConnectionInfo sentInfo = new ConnectionInfo(); - sentInfo.setUserName(username); - sentInfo.setPassword(password); + sentInfo.setUserName(username); + sentInfo.setPassword(password); - transport.doConsume(sentInfo); - } + transport.doConsume(sentInfo); + } - public void testKeepClientUserName() throws IOException { - createTransportAndConsume(true, true); + public void testKeepClientUserName() throws IOException { + createTransportAndConsume(true, true); - final ConnectionInfo receivedInfo = (ConnectionInfo)stubListener.getCommands().remove(); + final ConnectionInfo receivedInfo = (ConnectionInfo) stubListener.getCommands().remove(); - X509Certificate receivedCert; + X509Certificate receivedCert; - try { - receivedCert = ((X509Certificate[])receivedInfo.getTransportContext())[0]; - } catch (Exception e) { - receivedCert = null; - } + try { + receivedCert = ((X509Certificate[]) receivedInfo.getTransportContext())[0]; + } + catch (Exception e) { + receivedCert = null; + } - if (receivedCert == null) { - fail("Transmitted certificate chain was not attached to ConnectionInfo."); - } + if (receivedCert == null) { + fail("Transmitted certificate chain was not attached to ConnectionInfo."); + } - assertEquals("Received certificate distinguished name did not match the one transmitted.", certDistinguishedName, receivedCert.getSubjectDN().getName()); + assertEquals("Received certificate distinguished name did not match the one transmitted.", certDistinguishedName, receivedCert.getSubjectDN().getName()); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/StubSSLServerSocket.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/StubSSLServerSocket.java index cc3d91cd16..668a7eb7d2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/StubSSLServerSocket.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/StubSSLServerSocket.java @@ -22,76 +22,77 @@ import java.io.IOException; import javax.net.ssl.SSLServerSocket; public class StubSSLServerSocket extends SSLServerSocket { - public static final int UNTOUCHED = -1; - public static final int FALSE = 0; - public static final int TRUE = 1; - - private int wantClientAuthStatus = UNTOUCHED; - private int needClientAuthStatus = UNTOUCHED; - - public StubSSLServerSocket() throws IOException { - - } - - public int getWantClientAuthStatus() { - return wantClientAuthStatus; - } - - public int getNeedClientAuthStatus() { - return needClientAuthStatus; - } - - public void setWantClientAuth(boolean want) { - wantClientAuthStatus = want ? TRUE : FALSE; - } - - public void setNeedClientAuth(boolean need) { - needClientAuthStatus = need ? TRUE : FALSE; - } - // --- Stubbed methods --- - - public boolean getEnableSessionCreation() { - return false; - } + public static final int UNTOUCHED = -1; + public static final int FALSE = 0; + public static final int TRUE = 1; - public String[] getEnabledCipherSuites() { - return null; - } + private int wantClientAuthStatus = UNTOUCHED; + private int needClientAuthStatus = UNTOUCHED; - public String[] getEnabledProtocols() { - return null; - } + public StubSSLServerSocket() throws IOException { - public boolean getNeedClientAuth() { - return false; - } + } - public String[] getSupportedCipherSuites() { - return null; - } + public int getWantClientAuthStatus() { + return wantClientAuthStatus; + } - public String[] getSupportedProtocols() { - return null; - } + public int getNeedClientAuthStatus() { + return needClientAuthStatus; + } - public boolean getUseClientMode() { - return false; - } + public void setWantClientAuth(boolean want) { + wantClientAuthStatus = want ? TRUE : FALSE; + } - public boolean getWantClientAuth() { - return false; - } + public void setNeedClientAuth(boolean need) { + needClientAuthStatus = need ? TRUE : FALSE; + } - public void setEnableSessionCreation(boolean flag) { - } + // --- Stubbed methods --- - public void setEnabledCipherSuites(String[] suites) { - } + public boolean getEnableSessionCreation() { + return false; + } - public void setEnabledProtocols(String[] protocols) { - } + public String[] getEnabledCipherSuites() { + return null; + } - public void setUseClientMode(boolean mode) { - } + public String[] getEnabledProtocols() { + return null; + } + + public boolean getNeedClientAuth() { + return false; + } + + public String[] getSupportedCipherSuites() { + return null; + } + + public String[] getSupportedProtocols() { + return null; + } + + public boolean getUseClientMode() { + return false; + } + + public boolean getWantClientAuth() { + return false; + } + + public void setEnableSessionCreation(boolean flag) { + } + + public void setEnabledCipherSuites(String[] suites) { + } + + public void setEnabledProtocols(String[] protocols) { + } + + public void setUseClientMode(boolean mode) { + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/StubSSLSession.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/StubSSLSession.java index 7c0a70b071..76a5d07b3d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/StubSSLSession.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/StubSSLSession.java @@ -27,107 +27,109 @@ import javax.net.ssl.SSLSessionContext; class StubSSLSession implements SSLSession { - X509Certificate cert; - boolean isVerified; + X509Certificate cert; + boolean isVerified; - public StubSSLSession(X509Certificate cert) { - if (cert != null) { - this.isVerified = true; - this.cert = cert; - } else { - this.isVerified = false; - this.cert = null; - } - } + public StubSSLSession(X509Certificate cert) { + if (cert != null) { + this.isVerified = true; + this.cert = cert; + } + else { + this.isVerified = false; + this.cert = null; + } + } - public void setIsVerified(boolean verified) { - this.isVerified = verified; - } + public void setIsVerified(boolean verified) { + this.isVerified = verified; + } - public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException { - if (this.isVerified) { - return new X509Certificate[] {this.cert}; - } else { - throw new SSLPeerUnverifiedException("Socket is unverified."); - } - } + public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException { + if (this.isVerified) { + return new X509Certificate[]{this.cert}; + } + else { + throw new SSLPeerUnverifiedException("Socket is unverified."); + } + } - // --- Stubbed methods --- + // --- Stubbed methods --- - public byte[] getId() { - return null; - } + public byte[] getId() { + return null; + } - public SSLSessionContext getSessionContext() { - return null; - } + public SSLSessionContext getSessionContext() { + return null; + } - public long getCreationTime() { - return 0; - } + public long getCreationTime() { + return 0; + } - public long getLastAccessedTime() { - return 0; - } + public long getLastAccessedTime() { + return 0; + } - public void invalidate() { - } + public void invalidate() { + } - public boolean isValid() { - return false; - } + public boolean isValid() { + return false; + } - public void putValue(String arg0, Object arg1) { - } + public void putValue(String arg0, Object arg1) { + } - public Object getValue(String arg0) { - return null; - } + public Object getValue(String arg0) { + return null; + } - public void removeValue(String arg0) { - } + public void removeValue(String arg0) { + } - public String[] getValueNames() { - return null; - } + public String[] getValueNames() { + return null; + } - public Certificate[] getLocalCertificates() { - return null; - } + public Certificate[] getLocalCertificates() { + return null; + } - public javax.security.cert.X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException { - return null; - } + public javax.security.cert.X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException { + return null; + } - public Principal getPeerPrincipal() throws SSLPeerUnverifiedException { - return null; - } + public Principal getPeerPrincipal() throws SSLPeerUnverifiedException { + return null; + } - public Principal getLocalPrincipal() { - return null; - } + public Principal getLocalPrincipal() { + return null; + } - public String getCipherSuite() { - return null; - } + public String getCipherSuite() { + return null; + } - public String getProtocol() { - return null; - } + public String getProtocol() { + return null; + } - public String getPeerHost() { - return null; - } + public String getPeerHost() { + return null; + } - public int getPeerPort() { - return 0; - } + public int getPeerPort() { + return 0; + } - public int getPacketBufferSize() { - return 0; - } + public int getPacketBufferSize() { + return 0; + } - public int getApplicationBufferSize() { - return 0; - } + public int getApplicationBufferSize() { + return 0; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/StubSSLSocket.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/StubSSLSocket.java index d1de9aaef5..988a85947f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/StubSSLSocket.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/StubSSLSocket.java @@ -25,100 +25,100 @@ import javax.net.ssl.SSLSocket; public class StubSSLSocket extends SSLSocket { - public static final int UNTOUCHED = -1; - public static final int FALSE = 0; - public static final int TRUE = 1; + public static final int UNTOUCHED = -1; + public static final int FALSE = 0; + public static final int TRUE = 1; - private int wantClientAuthStatus = UNTOUCHED; - private int needClientAuthStatus = UNTOUCHED; - private int useClientModeStatus = UNTOUCHED; - private final StubSSLSession session; + private int wantClientAuthStatus = UNTOUCHED; + private int needClientAuthStatus = UNTOUCHED; + private int useClientModeStatus = UNTOUCHED; + private final StubSSLSession session; - public StubSSLSocket(StubSSLSession ses) { - this.session = ses; - } + public StubSSLSocket(StubSSLSession ses) { + this.session = ses; + } - public void setWantClientAuth(boolean arg0) { - this.wantClientAuthStatus = arg0 ? TRUE : FALSE; - } + public void setWantClientAuth(boolean arg0) { + this.wantClientAuthStatus = arg0 ? TRUE : FALSE; + } - public void setNeedClientAuth(boolean arg0) { - this.needClientAuthStatus = arg0 ? TRUE : FALSE; - if (session != null) { - this.session.setIsVerified(arg0); - } - } + public void setNeedClientAuth(boolean arg0) { + this.needClientAuthStatus = arg0 ? TRUE : FALSE; + if (session != null) { + this.session.setIsVerified(arg0); + } + } - public void setUseClientMode(boolean arg0) { - useClientModeStatus = arg0 ? TRUE : FALSE; - } + public void setUseClientMode(boolean arg0) { + useClientModeStatus = arg0 ? TRUE : FALSE; + } - public boolean getWantClientAuth() { - return wantClientAuthStatus == TRUE; - } + public boolean getWantClientAuth() { + return wantClientAuthStatus == TRUE; + } - public boolean getNeedClientAuth() { - return needClientAuthStatus == TRUE; - } + public boolean getNeedClientAuth() { + return needClientAuthStatus == TRUE; + } - public boolean getUseClientMode() { - return useClientModeStatus == TRUE; - } + public boolean getUseClientMode() { + return useClientModeStatus == TRUE; + } - public int getWantClientAuthStatus() { - return wantClientAuthStatus; - } + public int getWantClientAuthStatus() { + return wantClientAuthStatus; + } - public int getNeedClientAuthStatus() { - return needClientAuthStatus; - } + public int getNeedClientAuthStatus() { + return needClientAuthStatus; + } - public int getUseClientModeStatus() { - return useClientModeStatus; - } + public int getUseClientModeStatus() { + return useClientModeStatus; + } - public SSLSession getSession() { - return this.session; - } + public SSLSession getSession() { + return this.session; + } - // --- Stubbed methods --- + // --- Stubbed methods --- - public String[] getSupportedCipherSuites() { - return null; - } + public String[] getSupportedCipherSuites() { + return null; + } - public String[] getEnabledCipherSuites() { - return null; - } + public String[] getEnabledCipherSuites() { + return null; + } - public void setEnabledCipherSuites(String[] arg0) { - } + public void setEnabledCipherSuites(String[] arg0) { + } - public String[] getSupportedProtocols() { - return null; - } + public String[] getSupportedProtocols() { + return null; + } - public String[] getEnabledProtocols() { - return null; - } + public String[] getEnabledProtocols() { + return null; + } - public void setEnabledProtocols(String[] arg0) { - } + public void setEnabledProtocols(String[] arg0) { + } - public void addHandshakeCompletedListener(HandshakeCompletedListener arg0) { - } + public void addHandshakeCompletedListener(HandshakeCompletedListener arg0) { + } - public void removeHandshakeCompletedListener(HandshakeCompletedListener arg0) { - } + public void removeHandshakeCompletedListener(HandshakeCompletedListener arg0) { + } - public void startHandshake() throws IOException { - } + public void startHandshake() throws IOException { + } - public void setEnableSessionCreation(boolean arg0) { - } + public void setEnableSessionCreation(boolean arg0) { + } - public boolean getEnableSessionCreation() { - return false; - } + public boolean getEnableSessionCreation() { + return false; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/StubSSLSocketFactory.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/StubSSLSocketFactory.java index fa13cc30ff..54e04b5e87 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/StubSSLSocketFactory.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/StubSSLSocketFactory.java @@ -25,31 +25,31 @@ import javax.net.ssl.SSLServerSocketFactory; public class StubSSLSocketFactory extends SSLServerSocketFactory { - private final ServerSocket retServerSocket; + private final ServerSocket retServerSocket; - public StubSSLSocketFactory(ServerSocket returnServerSocket) { - retServerSocket = returnServerSocket; - } + public StubSSLSocketFactory(ServerSocket returnServerSocket) { + retServerSocket = returnServerSocket; + } - public ServerSocket createServerSocket(int arg0) throws IOException { - return retServerSocket; - } + public ServerSocket createServerSocket(int arg0) throws IOException { + return retServerSocket; + } - public ServerSocket createServerSocket(int arg0, int arg1) throws IOException { - return retServerSocket; - } + public ServerSocket createServerSocket(int arg0, int arg1) throws IOException { + return retServerSocket; + } - public ServerSocket createServerSocket(int arg0, int arg1, InetAddress arg2) throws IOException { - return retServerSocket; - } + public ServerSocket createServerSocket(int arg0, int arg1, InetAddress arg2) throws IOException { + return retServerSocket; + } - // --- Stubbed Methods --- + // --- Stubbed Methods --- - public String[] getDefaultCipherSuites() { - return null; - } + public String[] getDefaultCipherSuites() { + return null; + } - public String[] getSupportedCipherSuites() { - return null; - } + public String[] getSupportedCipherSuites() { + return null; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/StubSslTransport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/StubSslTransport.java index f5d2dc7eef..2e3c7fc6d2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/StubSslTransport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/StubSslTransport.java @@ -22,30 +22,31 @@ import javax.net.ssl.SSLSocket; import org.apache.activemq.wireformat.WireFormat; public class StubSslTransport extends SslTransport { - public static final int UNTOUCHED = -1; - public static final int FALSE = 0; - public static final int TRUE = 1; - private int wantClientAuthStatus = UNTOUCHED; - private int needClientAuthStatus = UNTOUCHED; + public static final int UNTOUCHED = -1; + public static final int FALSE = 0; + public static final int TRUE = 1; - public StubSslTransport(WireFormat wireFormat, SSLSocket socket) throws Exception { - super(wireFormat, socket); - } + private int wantClientAuthStatus = UNTOUCHED; + private int needClientAuthStatus = UNTOUCHED; - public void setWantClientAuth(boolean arg0) { - this.wantClientAuthStatus = arg0 ? TRUE : FALSE; - } + public StubSslTransport(WireFormat wireFormat, SSLSocket socket) throws Exception { + super(wireFormat, socket); + } - public void setNeedClientAuth(boolean arg0) { - this.needClientAuthStatus = arg0 ? TRUE : FALSE; - } + public void setWantClientAuth(boolean arg0) { + this.wantClientAuthStatus = arg0 ? TRUE : FALSE; + } - public int getWantClientAuthStatus() { - return wantClientAuthStatus; - } + public void setNeedClientAuth(boolean arg0) { + this.needClientAuthStatus = arg0 ? TRUE : FALSE; + } - public int getNeedClientAuthStatus() { - return needClientAuthStatus; - } + public int getWantClientAuthStatus() { + return wantClientAuthStatus; + } + + public int getNeedClientAuthStatus() { + return needClientAuthStatus; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/StubX509Certificate.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/StubX509Certificate.java index 3cd873ad7d..462f6c76bf 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/StubX509Certificate.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/StubX509Certificate.java @@ -26,113 +26,113 @@ import java.util.Set; public class StubX509Certificate extends X509Certificate { - private final Principal id; + private final Principal id; - public StubX509Certificate(Principal id) { - this.id = id; - } + public StubX509Certificate(Principal id) { + this.id = id; + } - public Principal getSubjectDN() { - return this.id; - } + public Principal getSubjectDN() { + return this.id; + } - // --- Stubbed Methods --- - public void checkValidity() { - } + // --- Stubbed Methods --- + public void checkValidity() { + } - public void checkValidity(Date arg0) { - } + public void checkValidity(Date arg0) { + } - public int getVersion() { - return 0; - } + public int getVersion() { + return 0; + } - public BigInteger getSerialNumber() { - return null; - } + public BigInteger getSerialNumber() { + return null; + } - public Principal getIssuerDN() { - return null; - } + public Principal getIssuerDN() { + return null; + } - public Date getNotBefore() { - return null; - } + public Date getNotBefore() { + return null; + } - public Date getNotAfter() { - return null; - } + public Date getNotAfter() { + return null; + } - public byte[] getTBSCertificate() { - return null; - } + public byte[] getTBSCertificate() { + return null; + } - public byte[] getSignature() { - return null; - } + public byte[] getSignature() { + return null; + } - public String getSigAlgName() { - return null; - } + public String getSigAlgName() { + return null; + } - public String getSigAlgOID() { - return null; - } + public String getSigAlgOID() { + return null; + } - public byte[] getSigAlgParams() { - return null; - } + public byte[] getSigAlgParams() { + return null; + } - public boolean[] getIssuerUniqueID() { - return null; - } + public boolean[] getIssuerUniqueID() { + return null; + } - public boolean[] getSubjectUniqueID() { - return null; - } + public boolean[] getSubjectUniqueID() { + return null; + } - public boolean[] getKeyUsage() { - return null; - } + public boolean[] getKeyUsage() { + return null; + } - public int getBasicConstraints() { - return 0; - } + public int getBasicConstraints() { + return 0; + } - public byte[] getEncoded() { - return null; - } + public byte[] getEncoded() { + return null; + } - public void verify(PublicKey arg0) { - } + public void verify(PublicKey arg0) { + } - public void verify(PublicKey arg0, String arg1) { - } + public void verify(PublicKey arg0, String arg1) { + } - public String toString() { - return null; - } + public String toString() { + return null; + } - public PublicKey getPublicKey() { - return null; - } + public PublicKey getPublicKey() { + return null; + } - public boolean hasUnsupportedCriticalExtension() { - return false; - } + public boolean hasUnsupportedCriticalExtension() { + return false; + } - @SuppressWarnings({ "unchecked", "rawtypes" }) - public Set getCriticalExtensionOIDs() { - return null; - } + @SuppressWarnings({"unchecked", "rawtypes"}) + public Set getCriticalExtensionOIDs() { + return null; + } - @SuppressWarnings({ "unchecked", "rawtypes" }) - public Set getNonCriticalExtensionOIDs() { - return null; - } + @SuppressWarnings({"unchecked", "rawtypes"}) + public Set getNonCriticalExtensionOIDs() { + return null; + } - public byte[] getExtensionValue(String arg0) { - return null; - } + public byte[] getExtensionValue(String arg0) { + return null; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TcpFaultyTransport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TcpFaultyTransport.java index 176934fae5..bb6f834db9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TcpFaultyTransport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TcpFaultyTransport.java @@ -29,21 +29,22 @@ import javax.net.SocketFactory; /** * An implementation of the {@link Transport} interface using raw tcp/ip - * + * * @author David Martin Clavo david(dot)martin(dot)clavo(at)gmail.com (logging improvement modifications) - * */ public class TcpFaultyTransport extends TcpTransport implements Transport, Service, Runnable { - public TcpFaultyTransport(WireFormat wireFormat, SocketFactory socketFactory, URI remoteLocation, - URI localLocation) throws UnknownHostException, IOException { - super(wireFormat, socketFactory, remoteLocation, localLocation); - } + public TcpFaultyTransport(WireFormat wireFormat, + SocketFactory socketFactory, + URI remoteLocation, + URI localLocation) throws UnknownHostException, IOException { + super(wireFormat, socketFactory, remoteLocation, localLocation); + } - /** - * @return pretty print of 'this' - */ - public String toString() { - return "tcpfaulty://" + socket.getInetAddress() + ":" + socket.getPort(); - } + /** + * @return pretty print of 'this' + */ + public String toString() { + return "tcpfaulty://" + socket.getInetAddress() + ":" + socket.getPort(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TcpFaultyTransportFactory.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TcpFaultyTransportFactory.java index 592f2fb6f5..77e7b6a3e9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TcpFaultyTransportFactory.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TcpFaultyTransportFactory.java @@ -39,59 +39,64 @@ import org.slf4j.LoggerFactory; * Automatically generated socket.close() calls to simulate network faults */ public class TcpFaultyTransportFactory extends TcpTransportFactory { - private static final Logger LOG = LoggerFactory.getLogger(TcpFaultyTransportFactory.class); - protected TcpFaultyTransport createTcpFaultyTransport(WireFormat wf, SocketFactory socketFactory, URI location, URI localLocation) throws UnknownHostException, IOException { - return new TcpFaultyTransport(wf, socketFactory, location, localLocation); - } + private static final Logger LOG = LoggerFactory.getLogger(TcpFaultyTransportFactory.class); - protected Transport createTransport(URI location, WireFormat wf) throws UnknownHostException, IOException { - URI localLocation = null; - String path = location.getPath(); - // see if the path is a local URI location - if (path != null && path.length() > 0) { - int localPortIndex = path.indexOf(':'); - try { - Integer.parseInt(path.substring(localPortIndex + 1, path.length())); - String localString = location.getScheme() + ":/" + path; - localLocation = new URI(localString); - } catch (Exception e) { - LOG.warn("path isn't a valid local location for TcpTransport to use", e); - } - } - SocketFactory socketFactory = createSocketFactory(); - return createTcpFaultyTransport(wf, socketFactory, location, localLocation); - } + protected TcpFaultyTransport createTcpFaultyTransport(WireFormat wf, + SocketFactory socketFactory, + URI location, + URI localLocation) throws UnknownHostException, IOException { + return new TcpFaultyTransport(wf, socketFactory, location, localLocation); + } - protected TcpFaultyTransportServer createTcpFaultyTransportServer(final URI location, ServerSocketFactory serverSocketFactory) throws IOException, URISyntaxException { - return new TcpFaultyTransportServer(this, location, serverSocketFactory); - } + protected Transport createTransport(URI location, WireFormat wf) throws UnknownHostException, IOException { + URI localLocation = null; + String path = location.getPath(); + // see if the path is a local URI location + if (path != null && path.length() > 0) { + int localPortIndex = path.indexOf(':'); + try { + Integer.parseInt(path.substring(localPortIndex + 1, path.length())); + String localString = location.getScheme() + ":/" + path; + localLocation = new URI(localString); + } + catch (Exception e) { + LOG.warn("path isn't a valid local location for TcpTransport to use", e); + } + } + SocketFactory socketFactory = createSocketFactory(); + return createTcpFaultyTransport(wf, socketFactory, location, localLocation); + } - public TransportServer doBind(final URI location) throws IOException { - try { - Map options = new HashMap(URISupport.parseParameters(location)); + protected TcpFaultyTransportServer createTcpFaultyTransportServer(final URI location, + ServerSocketFactory serverSocketFactory) throws IOException, URISyntaxException { + return new TcpFaultyTransportServer(this, location, serverSocketFactory); + } - ServerSocketFactory serverSocketFactory = createServerSocketFactory(); - TcpFaultyTransportServer server = createTcpFaultyTransportServer(location, serverSocketFactory); - server.setWireFormatFactory(createWireFormatFactory(options)); - IntrospectionSupport.setProperties(server, options); - Map transportOptions = IntrospectionSupport.extractProperties(options, "transport."); - server.setTransportOption(transportOptions); - server.bind(); + public TransportServer doBind(final URI location) throws IOException { + try { + Map options = new HashMap(URISupport.parseParameters(location)); - return server; - } catch (URISyntaxException e) { - throw IOExceptionSupport.create(e); - } - } + ServerSocketFactory serverSocketFactory = createServerSocketFactory(); + TcpFaultyTransportServer server = createTcpFaultyTransportServer(location, serverSocketFactory); + server.setWireFormatFactory(createWireFormatFactory(options)); + IntrospectionSupport.setProperties(server, options); + Map transportOptions = IntrospectionSupport.extractProperties(options, "transport."); + server.setTransportOption(transportOptions); + server.bind(); - - protected SocketFactory createSocketFactory() throws IOException { - return SocketTstFactory.getDefault(); - } + return server; + } + catch (URISyntaxException e) { + throw IOExceptionSupport.create(e); + } + } - - protected ServerSocketFactory createServerSocketFactory() throws IOException { - return ServerSocketTstFactory.getDefault(); - } + protected SocketFactory createSocketFactory() throws IOException { + return SocketTstFactory.getDefault(); + } + + protected ServerSocketFactory createServerSocketFactory() throws IOException { + return ServerSocketTstFactory.getDefault(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TcpFaultyTransportServer.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TcpFaultyTransportServer.java index 36c0fd54d2..f0061d2edf 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TcpFaultyTransportServer.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TcpFaultyTransportServer.java @@ -26,21 +26,22 @@ import javax.net.ServerSocketFactory; /** * A TCP based implementation of {@link TransportServer} - * + * * @author David Martin Clavo david(dot)martin(dot)clavo(at)gmail.com (logging improvement modifications) - * */ -public class TcpFaultyTransportServer extends TcpTransportServer implements ServiceListener{ +public class TcpFaultyTransportServer extends TcpTransportServer implements ServiceListener { - public TcpFaultyTransportServer(TcpFaultyTransportFactory transportFactory, URI location, ServerSocketFactory serverSocketFactory) throws IOException, URISyntaxException { - super(transportFactory, location, serverSocketFactory); - } + public TcpFaultyTransportServer(TcpFaultyTransportFactory transportFactory, + URI location, + ServerSocketFactory serverSocketFactory) throws IOException, URISyntaxException { + super(transportFactory, location, serverSocketFactory); + } - /** - * @return pretty print of this - */ - public String toString() { - return "" + getBindLocation(); - } + /** + * @return pretty print of this + */ + public String toString() { + return "" + getBindLocation(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TcpTransportBindTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TcpTransportBindTest.java index 61c20aea9c..1c34d83764 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TcpTransportBindTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TcpTransportBindTest.java @@ -27,47 +27,52 @@ import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.EmbeddedBrokerTestSupport; public class TcpTransportBindTest extends EmbeddedBrokerTestSupport { - String addr = "tcp://localhost:0"; - /** - * exercise some server side socket options - * @throws Exception - */ - @Override - protected void setUp() throws Exception { - bindAddress = addr + "?transport.reuseAddress=true&transport.soTimeout=1000"; - super.setUp(); + String addr = "tcp://localhost:0"; - addr = broker.getTransportConnectors().get(0).getPublishableConnectString(); - } + /** + * exercise some server side socket options + * + * @throws Exception + */ + @Override + protected void setUp() throws Exception { + bindAddress = addr + "?transport.reuseAddress=true&transport.soTimeout=1000"; + super.setUp(); - public void testConnect() throws Exception { - Connection connection = new ActiveMQConnectionFactory(addr).createConnection(); - connection.start(); - } + addr = broker.getTransportConnectors().get(0).getPublishableConnectString(); + } - public void testReceiveThrowsException() throws Exception { - Connection connection = new ActiveMQConnectionFactory(addr).createConnection(); - connection.start(); - Session sess = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = sess.createConsumer(createDestination()); - class StopTask extends TimerTask { - @Override - public void run() { - try { - broker.stop(); - } catch (Exception e) { - e.printStackTrace(); - } + public void testConnect() throws Exception { + Connection connection = new ActiveMQConnectionFactory(addr).createConnection(); + connection.start(); + } + + public void testReceiveThrowsException() throws Exception { + Connection connection = new ActiveMQConnectionFactory(addr).createConnection(); + connection.start(); + Session sess = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = sess.createConsumer(createDestination()); + class StopTask extends TimerTask { + + @Override + public void run() { + try { + broker.stop(); } - } - Timer timer = new Timer(); - timer.schedule(new StopTask(), 1000); - try { - consumer.receive(30000); - fail("Should have thrown an exception"); - } catch (Exception e) { - // should fail - } - } + catch (Exception e) { + e.printStackTrace(); + } + } + } + Timer timer = new Timer(); + timer.schedule(new StopTask(), 1000); + try { + consumer.receive(30000); + fail("Should have thrown an exception"); + } + catch (Exception e) { + // should fail + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TcpTransportBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TcpTransportBrokerTest.java index 9ce2e8bbcb..49c4839526 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TcpTransportBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TcpTransportBrokerTest.java @@ -17,25 +17,26 @@ package org.apache.activemq.transport.tcp; import junit.framework.Test; + import org.apache.activemq.transport.TransportBrokerTestSupport; public class TcpTransportBrokerTest extends TransportBrokerTestSupport { - protected String getBindLocation() { - return "tcp://localhost:0"; - } + protected String getBindLocation() { + return "tcp://localhost:0"; + } - protected void setUp() throws Exception { - maxWait = 2000; - super.setUp(); - } + protected void setUp() throws Exception { + maxWait = 2000; + super.setUp(); + } - public static Test suite() { - return suite(TcpTransportBrokerTest.class); - } + public static Test suite() { + return suite(TcpTransportBrokerTest.class); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TcpTransportServerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TcpTransportServerTest.java index 46db53f15f..110b1c2f89 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TcpTransportServerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TcpTransportServerTest.java @@ -17,6 +17,7 @@ package org.apache.activemq.transport.tcp; import junit.framework.TestCase; + import org.apache.activemq.transport.*; import java.net.Socket; @@ -26,54 +27,52 @@ import java.util.HashMap; /** * @author Christian Posta */ -public class TcpTransportServerTest extends TestCase{ +public class TcpTransportServerTest extends TestCase { - public void testDefaultPropertiesSetOnTransport() throws Exception { - TcpTransportServer server = (TcpTransportServer) TransportFactory.bind(new URI("tcp://localhost:61616?trace=true")); - server.setTransportOption(new HashMap()); + public void testDefaultPropertiesSetOnTransport() throws Exception { + TcpTransportServer server = (TcpTransportServer) TransportFactory.bind(new URI("tcp://localhost:61616?trace=true")); + server.setTransportOption(new HashMap()); - server.setAcceptListener(new TransportAcceptListener() { - @Override - public void onAccept(Transport transport) { - assertTrue("This transport does not have a TransportLogger!!", hasTransportLogger(transport)); + server.setAcceptListener(new TransportAcceptListener() { + @Override + public void onAccept(Transport transport) { + assertTrue("This transport does not have a TransportLogger!!", hasTransportLogger(transport)); + } + + @Override + public void onAcceptError(Exception error) { + fail("Should not have received an error!"); + } + }); + + server.start(); + + Socket socket = new Socket("localhost", 61616); + server.handleSocket(socket); + server.stop(); + + } + + private boolean hasTransportLogger(Transport transport) { + boolean end = false; + + Transport current = transport; + while (!end) { + + if (current instanceof TransportFilter) { + TransportFilter filter = (TransportFilter) current; + + if (filter instanceof TransportLogger) { + return true; } - @Override - public void onAcceptError(Exception error) { - fail("Should not have received an error!"); - } - }); + current = filter.getNext(); + } + else { + end = true; + } + } - server.start(); - - - Socket socket = new Socket("localhost", 61616); - server.handleSocket(socket); - server.stop(); - - - } - - private boolean hasTransportLogger(Transport transport) { - boolean end = false; - - Transport current = transport; - while(!end) { - - if (current instanceof TransportFilter) { - TransportFilter filter = (TransportFilter) current; - - if(filter instanceof TransportLogger){ - return true; - } - - current = filter.getNext(); - } - else { - end = true; - } - } - - return false; - } + return false; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TransportConnectorInvalidSocketOptionsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TransportConnectorInvalidSocketOptionsTest.java index 5a171b713d..870638a949 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TransportConnectorInvalidSocketOptionsTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TransportConnectorInvalidSocketOptionsTest.java @@ -19,47 +19,51 @@ package org.apache.activemq.transport.tcp; import javax.jms.JMSException; import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.junit.Test; public class TransportConnectorInvalidSocketOptionsTest extends TestCase { - @Test - public void testClientParameters() throws Exception { - try { - new ActiveMQConnectionFactory("tcp://localhost:42?foo=bar").createConnection(); + @Test + public void testClientParameters() throws Exception { + try { + new ActiveMQConnectionFactory("tcp://localhost:42?foo=bar").createConnection(); + fail("Should have thrown an exception"); + } + catch (Exception e) { + assertEquals(JMSException.class, e.getClass()); + assertEquals(IllegalArgumentException.class, e.getCause().getClass()); + assertEquals("Invalid connect parameters: {foo=bar}", e.getCause().getMessage()); + } + } + + @Test + public void testClientSocketParameters() throws Exception { + BrokerService broker = null; + + try { + broker = new BrokerService(); + broker.setPersistent(false); + broker.addConnector("tcp://localhost:61616"); + broker.start(); + + try { + new ActiveMQConnectionFactory("tcp://localhost:61616?socket.foo=bar").createConnection(); fail("Should have thrown an exception"); - } catch (Exception e) { + } + catch (Exception e) { assertEquals(JMSException.class, e.getClass()); assertEquals(IllegalArgumentException.class, e.getCause().getClass()); - assertEquals("Invalid connect parameters: {foo=bar}", e.getCause().getMessage()); - } - } - - @Test - public void testClientSocketParameters() throws Exception { - BrokerService broker = null; - - try { - broker = new BrokerService(); - broker.setPersistent(false); - broker.addConnector("tcp://localhost:61616"); - broker.start(); - - try { - new ActiveMQConnectionFactory("tcp://localhost:61616?socket.foo=bar").createConnection(); - fail("Should have thrown an exception"); - } catch (Exception e) { - assertEquals(JMSException.class, e.getClass()); - assertEquals(IllegalArgumentException.class, e.getCause().getClass()); - assertEquals("Invalid socket parameters: {foo=bar}", e.getCause().getMessage()); - } - } finally { - if (broker != null) { - broker.stop(); - } - } - } + assertEquals("Invalid socket parameters: {foo=bar}", e.getCause().getMessage()); + } + } + finally { + if (broker != null) { + broker.stop(); + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TransportUriTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TransportUriTest.java index 349c5c3fca..9ae82ac853 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TransportUriTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/TransportUriTest.java @@ -32,173 +32,167 @@ import org.slf4j.LoggerFactory; */ public class TransportUriTest extends EmbeddedBrokerTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(TransportUriTest.class); - private static final String DIFF_SERV = "&diffServ="; - private static final String TOS = "&typeOfService="; + private static final Logger LOG = LoggerFactory.getLogger(TransportUriTest.class); + private static final String DIFF_SERV = "&diffServ="; + private static final String TOS = "&typeOfService="; - protected Connection connection; + protected Connection connection; - public String prefix; - public String postfix; + public String prefix; + public String postfix; - public void initCombosForTestUriOptionsWork() { - initSharedCombos(); - } + public void initCombosForTestUriOptionsWork() { + initSharedCombos(); + } - public void testUriOptionsWork() throws Exception { - String uri = prefix + bindAddress + postfix; - LOG.info("Connecting via: " + uri); + public void testUriOptionsWork() throws Exception { + String uri = prefix + bindAddress + postfix; + LOG.info("Connecting via: " + uri); - connection = new ActiveMQConnectionFactory(uri).createConnection(); - connection.start(); - } + connection = new ActiveMQConnectionFactory(uri).createConnection(); + connection.start(); + } - public void initCombosForTestValidDiffServOptionsWork() { - initSharedCombos(); - } + public void initCombosForTestValidDiffServOptionsWork() { + initSharedCombos(); + } - public void testValidDiffServOptionsWork() throws Exception { - String[] validIntegerOptions = {"0", "1", "32", "62", "63"}; - for (String opt : validIntegerOptions) { - testValidOptionsWork(DIFF_SERV + opt, ""); - } - String[] validNameOptions = { "CS0", "CS1", "CS2", "CS3", "CS4", "CS5", "CS6", - "CS7", "EF", "AF11", "AF12","AF13", "AF21", "AF22", "AF23", "AF31", - "AF32", "AF33", "AF41", "AF42", "AF43" }; - for (String opt : validNameOptions) { - testValidOptionsWork(DIFF_SERV + opt, ""); - } - } + public void testValidDiffServOptionsWork() throws Exception { + String[] validIntegerOptions = {"0", "1", "32", "62", "63"}; + for (String opt : validIntegerOptions) { + testValidOptionsWork(DIFF_SERV + opt, ""); + } + String[] validNameOptions = {"CS0", "CS1", "CS2", "CS3", "CS4", "CS5", "CS6", "CS7", "EF", "AF11", "AF12", "AF13", "AF21", "AF22", "AF23", "AF31", "AF32", "AF33", "AF41", "AF42", "AF43"}; + for (String opt : validNameOptions) { + testValidOptionsWork(DIFF_SERV + opt, ""); + } + } - public void initCombosForTestInvalidDiffServOptionDoesNotWork() { - initSharedCombos(); - } + public void initCombosForTestInvalidDiffServOptionDoesNotWork() { + initSharedCombos(); + } - public void testInvalidDiffServOptionsDoesNotWork() throws Exception { - String[] invalidIntegerOptions = {"-2", "-1", "64", "65", "100", "255"}; - for (String opt : invalidIntegerOptions) { - testInvalidOptionsDoNotWork(DIFF_SERV + opt, ""); - } - String[] invalidNameOptions = {"hi", "", "A", "AF", "-AF21"}; - for (String opt : invalidNameOptions) { - testInvalidOptionsDoNotWork(DIFF_SERV + opt, ""); - } - } + public void testInvalidDiffServOptionsDoesNotWork() throws Exception { + String[] invalidIntegerOptions = {"-2", "-1", "64", "65", "100", "255"}; + for (String opt : invalidIntegerOptions) { + testInvalidOptionsDoNotWork(DIFF_SERV + opt, ""); + } + String[] invalidNameOptions = {"hi", "", "A", "AF", "-AF21"}; + for (String opt : invalidNameOptions) { + testInvalidOptionsDoNotWork(DIFF_SERV + opt, ""); + } + } - public void initCombosForTestValidTypeOfServiceOptionsWork() { - initSharedCombos(); - } + public void initCombosForTestValidTypeOfServiceOptionsWork() { + initSharedCombos(); + } - public void testValidTypeOfServiceOptionsWork() throws Exception { - int[] validOptions = {0, 1, 32, 100, 254, 255}; - for (int opt : validOptions) { - testValidOptionsWork(TOS + opt, ""); - } - } + public void testValidTypeOfServiceOptionsWork() throws Exception { + int[] validOptions = {0, 1, 32, 100, 254, 255}; + for (int opt : validOptions) { + testValidOptionsWork(TOS + opt, ""); + } + } - public void initCombosForTestInvalidTypeOfServiceOptionDoesNotWork() { - initSharedCombos(); - } + public void initCombosForTestInvalidTypeOfServiceOptionDoesNotWork() { + initSharedCombos(); + } - public void testInvalidTypeOfServiceOptionDoesNotWork() throws Exception { - int[] invalidOptions = {-2, -1, 256, 257}; - for (int opt : invalidOptions) { - testInvalidOptionsDoNotWork(TOS + opt, ""); - } - } + public void testInvalidTypeOfServiceOptionDoesNotWork() throws Exception { + int[] invalidOptions = {-2, -1, 256, 257}; + for (int opt : invalidOptions) { + testInvalidOptionsDoNotWork(TOS + opt, ""); + } + } - public void initCombosForTestDiffServAndTypeOfServiceMutuallyExclusive() { - initSharedCombos(); - } + public void initCombosForTestDiffServAndTypeOfServiceMutuallyExclusive() { + initSharedCombos(); + } - public void testDiffServAndTypeServiceMutuallyExclusive() { - String msg = "It should not be possible to set both Differentiated " - + "Services and Type of Service options on the same connection " - + "URI."; - testInvalidOptionsDoNotWork(TOS + 32 + DIFF_SERV, msg); - testInvalidOptionsDoNotWork(DIFF_SERV + 32 + TOS + 32, msg); - } + public void testDiffServAndTypeServiceMutuallyExclusive() { + String msg = "It should not be possible to set both Differentiated " + "Services and Type of Service options on the same connection " + "URI."; + testInvalidOptionsDoNotWork(TOS + 32 + DIFF_SERV, msg); + testInvalidOptionsDoNotWork(DIFF_SERV + 32 + TOS + 32, msg); + } - public void initCombosForTestBadVersionNumberDoesNotWork() { - initSharedCombos(); - } + public void initCombosForTestBadVersionNumberDoesNotWork() { + initSharedCombos(); + } - public void testBadVersionNumberDoesNotWork() throws Exception { - testInvalidOptionsDoNotWork("&minmumWireFormatVersion=65535", ""); - } + public void testBadVersionNumberDoesNotWork() throws Exception { + testInvalidOptionsDoNotWork("&minmumWireFormatVersion=65535", ""); + } - public void initCombosForTestBadPropertyNameFails() { - initSharedCombos(); - } + public void initCombosForTestBadPropertyNameFails() { + initSharedCombos(); + } - public void testBadPropertyNameFails() throws Exception { - testInvalidOptionsDoNotWork("&cheese=abc", ""); - } + public void testBadPropertyNameFails() throws Exception { + testInvalidOptionsDoNotWork("&cheese=abc", ""); + } - private void initSharedCombos() { - addCombinationValues("prefix", new Object[] {""}); - // TODO: Add more combinations. - addCombinationValues("postfix", new Object[] - {"?tcpNoDelay=true&keepAlive=true&soLinger=0"}); - addCombinationValues("postfix", new Object[] - {"?tcpNoDelay=true&keepAlive=true&soLinger=-1"}); - } + private void initSharedCombos() { + addCombinationValues("prefix", new Object[]{""}); + // TODO: Add more combinations. + addCombinationValues("postfix", new Object[]{"?tcpNoDelay=true&keepAlive=true&soLinger=0"}); + addCombinationValues("postfix", new Object[]{"?tcpNoDelay=true&keepAlive=true&soLinger=-1"}); + } - private void testValidOptionsWork(String options, String msg) { - String uri = prefix + bindAddress + postfix + options; - LOG.info("Connecting via: " + uri); + private void testValidOptionsWork(String options, String msg) { + String uri = prefix + bindAddress + postfix + options; + LOG.info("Connecting via: " + uri); - try { - connection = new ActiveMQConnectionFactory(uri).createConnection(); - connection.start(); - } catch (Exception unexpected) { - fail("Valid options '" + options + "' on URI '" + uri + "' should " - + "not have caused an exception to be thrown. " + msg - + " Exception: " + unexpected); - } - } + try { + connection = new ActiveMQConnectionFactory(uri).createConnection(); + connection.start(); + } + catch (Exception unexpected) { + fail("Valid options '" + options + "' on URI '" + uri + "' should " + "not have caused an exception to be thrown. " + msg + " Exception: " + unexpected); + } + } - private void testInvalidOptionsDoNotWork(String options, String msg) { - String uri = prefix + bindAddress + postfix + options; - LOG.info("Connecting via: " + uri); + private void testInvalidOptionsDoNotWork(String options, String msg) { + String uri = prefix + bindAddress + postfix + options; + LOG.info("Connecting via: " + uri); - try { - connection = new ActiveMQConnectionFactory(uri).createConnection(); - connection.start(); - fail("Invalid options '" + options + "' on URI '" + uri + "' should" - + " have caused an exception to be thrown. " + msg); - } catch (Exception expected) { - } - } + try { + connection = new ActiveMQConnectionFactory(uri).createConnection(); + connection.start(); + fail("Invalid options '" + options + "' on URI '" + uri + "' should" + " have caused an exception to be thrown. " + msg); + } + catch (Exception expected) { + } + } - @Override - protected void setUp() throws Exception { - bindAddress = "tcp://localhost:61616"; - super.setUp(); - } + @Override + protected void setUp() throws Exception { + bindAddress = "tcp://localhost:61616"; + super.setUp(); + } - @Override - protected void tearDown() throws Exception { - if (connection != null) { - try { - connection.close(); - } catch (JMSException e) { - e.printStackTrace(); - } - } - super.tearDown(); - } + @Override + protected void tearDown() throws Exception { + if (connection != null) { + try { + connection.close(); + } + catch (JMSException e) { + e.printStackTrace(); + } + } + super.tearDown(); + } - @Override - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setUseJmx(false); - answer.setPersistent(isPersistent()); - answer.addConnector(bindAddress); - return answer; - } + @Override + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + answer.setUseJmx(false); + answer.setPersistent(isPersistent()); + answer.addConnector(bindAddress); + return answer; + } - public static Test suite() { - return suite(TransportUriTest.class); - } + public static Test suite() { + return suite(TransportUriTest.class); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/WireformatNegociationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/WireformatNegociationTest.java index 998c951cea..3537794ca0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/WireformatNegociationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/tcp/WireformatNegociationTest.java @@ -36,201 +36,204 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WireformatNegociationTest extends CombinationTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(WireformatNegociationTest.class); - private TransportServer server; - private Transport clientTransport; - private Transport serverTransport; + private static final Logger LOG = LoggerFactory.getLogger(WireformatNegociationTest.class); - private final AtomicReference clientWF = new AtomicReference(); - private final AtomicReference serverWF = new AtomicReference(); - private final AtomicReference asyncError = new AtomicReference(); - private final AtomicBoolean ignoreAsycError = new AtomicBoolean(); + private TransportServer server; + private Transport clientTransport; + private Transport serverTransport; - private final CountDownLatch negotiationCounter = new CountDownLatch(2); + private final AtomicReference clientWF = new AtomicReference(); + private final AtomicReference serverWF = new AtomicReference(); + private final AtomicReference asyncError = new AtomicReference(); + private final AtomicBoolean ignoreAsycError = new AtomicBoolean(); - protected void setUp() throws Exception { - super.setUp(); - } + private final CountDownLatch negotiationCounter = new CountDownLatch(2); - /** - * @throws Exception - * @throws URISyntaxException - */ - private void startClient(String uri) throws Exception, URISyntaxException { - clientTransport = TransportFactory.connect(new URI(uri)); - clientTransport.setTransportListener(new TransportListener() { - public void onCommand(Object command) { - if (command instanceof WireFormatInfo) { - clientWF.set((WireFormatInfo)command); - negotiationCounter.countDown(); - } + protected void setUp() throws Exception { + super.setUp(); + } + + /** + * @throws Exception + * @throws URISyntaxException + */ + private void startClient(String uri) throws Exception, URISyntaxException { + clientTransport = TransportFactory.connect(new URI(uri)); + clientTransport.setTransportListener(new TransportListener() { + public void onCommand(Object command) { + if (command instanceof WireFormatInfo) { + clientWF.set((WireFormatInfo) command); + negotiationCounter.countDown(); } + } - public void onException(IOException error) { - if (!ignoreAsycError.get()) { - LOG.info("Client transport error: ", error); - asyncError.set(error); - negotiationCounter.countDown(); - } + public void onException(IOException error) { + if (!ignoreAsycError.get()) { + LOG.info("Client transport error: ", error); + asyncError.set(error); + negotiationCounter.countDown(); } + } - public void transportInterupted() { + public void transportInterupted() { + } + + public void transportResumed() { + } + }); + clientTransport.start(); + } + + /** + * @throws IOException + * @throws URISyntaxException + * @throws Exception + */ + private void startServer(String uri) throws IOException, URISyntaxException, Exception { + server = TransportFactory.bind(new URI(uri)); + server.setAcceptListener(new TransportAcceptListener() { + public void onAccept(Transport transport) { + try { + LOG.info("[" + getName() + "] Server Accepted a Connection"); + serverTransport = transport; + serverTransport.setTransportListener(new TransportListener() { + public void onCommand(Object command) { + if (command instanceof WireFormatInfo) { + serverWF.set((WireFormatInfo) command); + negotiationCounter.countDown(); + } + } + + public void onException(IOException error) { + if (!ignoreAsycError.get()) { + LOG.info("Server transport error: ", error); + asyncError.set(error); + negotiationCounter.countDown(); + } + } + + public void transportInterupted() { + } + + public void transportResumed() { + } + }); + serverTransport.start(); } - - public void transportResumed() { + catch (Exception e) { + e.printStackTrace(); } - }); - clientTransport.start(); - } + } - /** - * @throws IOException - * @throws URISyntaxException - * @throws Exception - */ - private void startServer(String uri) throws IOException, URISyntaxException, Exception { - server = TransportFactory.bind(new URI(uri)); - server.setAcceptListener(new TransportAcceptListener() { - public void onAccept(Transport transport) { - try { - LOG.info("[" + getName() + "] Server Accepted a Connection"); - serverTransport = transport; - serverTransport.setTransportListener(new TransportListener() { - public void onCommand(Object command) { - if (command instanceof WireFormatInfo) { - serverWF.set((WireFormatInfo)command); - negotiationCounter.countDown(); - } - } + public void onAcceptError(Exception error) { + error.printStackTrace(); + } + }); + server.start(); + } - public void onException(IOException error) { - if (!ignoreAsycError.get()) { - LOG.info("Server transport error: ", error); - asyncError.set(error); - negotiationCounter.countDown(); - } - } + protected void tearDown() throws Exception { + ignoreAsycError.set(true); + try { + if (clientTransport != null) { + clientTransport.stop(); + } + if (serverTransport != null) { + serverTransport.stop(); + } + if (server != null) { + server.stop(); + } + } + catch (Throwable e) { + e.printStackTrace(); + } + super.tearDown(); + } - public void transportInterupted() { - } + /** + * @throws Exception + */ + public void testWireFormatInfoSeverVersion1() throws Exception { - public void transportResumed() { - } - }); - serverTransport.start(); - } catch (Exception e) { - e.printStackTrace(); - } - } + startServer("tcp://localhost:61616?wireFormat.version=1"); + startClient("tcp://localhost:61616"); - public void onAcceptError(Exception error) { - error.printStackTrace(); - } - }); - server.start(); - } + assertTrue("Connect timeout", negotiationCounter.await(10, TimeUnit.SECONDS)); + assertNull("Async error: " + asyncError, asyncError.get()); - protected void tearDown() throws Exception { - ignoreAsycError.set(true); - try { - if (clientTransport != null) { - clientTransport.stop(); - } - if (serverTransport != null) { - serverTransport.stop(); - } - if (server != null) { - server.stop(); - } - } catch (Throwable e) { - e.printStackTrace(); - } - super.tearDown(); - } + assertNotNull(clientWF.get()); + assertEquals(1, clientWF.get().getVersion()); - /** - * @throws Exception - */ - public void testWireFormatInfoSeverVersion1() throws Exception { + assertNotNull(serverWF.get()); + assertEquals(1, serverWF.get().getVersion()); + } - startServer("tcp://localhost:61616?wireFormat.version=1"); - startClient("tcp://localhost:61616"); + /** + * @throws Exception + */ + public void testWireFormatInfoClientVersion1() throws Exception { - assertTrue("Connect timeout", negotiationCounter.await(10, TimeUnit.SECONDS)); - assertNull("Async error: " + asyncError, asyncError.get()); + startServer("tcp://localhost:61616"); + startClient("tcp://localhost:61616?wireFormat.version=1"); - assertNotNull(clientWF.get()); - assertEquals(1, clientWF.get().getVersion()); + assertTrue("Connect timeout", negotiationCounter.await(10, TimeUnit.SECONDS)); + assertNull("Async error: " + asyncError, asyncError.get()); - assertNotNull(serverWF.get()); - assertEquals(1, serverWF.get().getVersion()); - } + assertNotNull(clientWF.get()); + assertEquals(1, clientWF.get().getVersion()); - /** - * @throws Exception - */ - public void testWireFormatInfoClientVersion1() throws Exception { + assertNotNull(serverWF.get()); + assertEquals(1, serverWF.get().getVersion()); + } - startServer("tcp://localhost:61616"); - startClient("tcp://localhost:61616?wireFormat.version=1"); + /** + * @throws Exception + */ + public void testWireFormatInfoCurrentVersion() throws Exception { - assertTrue("Connect timeout", negotiationCounter.await(10, TimeUnit.SECONDS)); - assertNull("Async error: " + asyncError, asyncError.get()); + startServer("tcp://localhost:61616"); + startClient("tcp://localhost:61616"); - assertNotNull(clientWF.get()); - assertEquals(1, clientWF.get().getVersion()); + assertTrue("Connect timeout", negotiationCounter.await(10, TimeUnit.SECONDS)); + assertNull("Async error: " + asyncError, asyncError.get()); - assertNotNull(serverWF.get()); - assertEquals(1, serverWF.get().getVersion()); - } + assertNotNull(clientWF.get()); + assertEquals(CommandTypes.PROTOCOL_VERSION, clientWF.get().getVersion()); - /** - * @throws Exception - */ - public void testWireFormatInfoCurrentVersion() throws Exception { + assertNotNull(serverWF.get()); + assertEquals(CommandTypes.PROTOCOL_VERSION, serverWF.get().getVersion()); + } - startServer("tcp://localhost:61616"); - startClient("tcp://localhost:61616"); + public void testWireFormatInactivityDurationInitialDelay() throws Exception { - assertTrue("Connect timeout", negotiationCounter.await(10, TimeUnit.SECONDS)); - assertNull("Async error: " + asyncError, asyncError.get()); + startServer("tcp://localhost:61616"); + startClient("tcp://localhost:61616?wireFormat.maxInactivityDurationInitalDelay=60000"); - assertNotNull(clientWF.get()); - assertEquals(CommandTypes.PROTOCOL_VERSION, clientWF.get().getVersion()); + assertTrue("Connect timeout", negotiationCounter.await(10, TimeUnit.SECONDS)); + assertNull("Async error: " + asyncError, asyncError.get()); - assertNotNull(serverWF.get()); - assertEquals(CommandTypes.PROTOCOL_VERSION, serverWF.get().getVersion()); - } - - public void testWireFormatInactivityDurationInitialDelay() throws Exception { + assertNotNull(clientWF.get()); + assertEquals(CommandTypes.PROTOCOL_VERSION, clientWF.get().getVersion()); - startServer("tcp://localhost:61616"); - startClient("tcp://localhost:61616?wireFormat.maxInactivityDurationInitalDelay=60000"); + assertNotNull(serverWF.get()); + assertEquals(CommandTypes.PROTOCOL_VERSION, serverWF.get().getVersion()); + } - assertTrue("Connect timeout", negotiationCounter.await(10, TimeUnit.SECONDS)); - assertNull("Async error: " + asyncError, asyncError.get()); + public void testWireFormatMaxFrameSize() throws Exception { - assertNotNull(clientWF.get()); - assertEquals(CommandTypes.PROTOCOL_VERSION, clientWF.get().getVersion()); + startServer("tcp://localhost:61616"); + startClient("tcp://localhost:61616?wireFormat.maxFrameSize=1048576"); - assertNotNull(serverWF.get()); - assertEquals(CommandTypes.PROTOCOL_VERSION, serverWF.get().getVersion()); - } + assertTrue("Connect timeout", negotiationCounter.await(10, TimeUnit.SECONDS)); + assertNull("Async error: " + asyncError, asyncError.get()); - public void testWireFormatMaxFrameSize() throws Exception { + assertNotNull(clientWF.get()); + assertEquals(1048576, clientWF.get().getMaxFrameSize()); - startServer("tcp://localhost:61616"); - startClient("tcp://localhost:61616?wireFormat.maxFrameSize=1048576"); - - assertTrue("Connect timeout", negotiationCounter.await(10, TimeUnit.SECONDS)); - assertNull("Async error: " + asyncError, asyncError.get()); - - assertNotNull(clientWF.get()); - assertEquals(1048576, clientWF.get().getMaxFrameSize()); - - assertNotNull(serverWF.get()); - assertEquals(1048576, serverWF.get().getMaxFrameSize()); - } + assertNotNull(serverWF.get()); + assertEquals(1048576, serverWF.get().getMaxFrameSize()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/udp/UdpSendReceiveWithTwoConnectionsAndLargeMessagesTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/udp/UdpSendReceiveWithTwoConnectionsAndLargeMessagesTest.java index 01d69b4796..6c39af1212 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/udp/UdpSendReceiveWithTwoConnectionsAndLargeMessagesTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/udp/UdpSendReceiveWithTwoConnectionsAndLargeMessagesTest.java @@ -18,14 +18,14 @@ package org.apache.activemq.transport.udp; /** * - * + * */ public class UdpSendReceiveWithTwoConnectionsAndLargeMessagesTest extends UdpSendReceiveWithTwoConnectionsTest { - protected void setUp() throws Exception { - largeMessages = true; - messageCount = 2; - super.setUp(); - } + protected void setUp() throws Exception { + largeMessages = true; + messageCount = 2; + super.setUp(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/udp/UdpSendReceiveWithTwoConnectionsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/udp/UdpSendReceiveWithTwoConnectionsTest.java index 9ddd5ab31b..4b65872065 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/udp/UdpSendReceiveWithTwoConnectionsTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/udp/UdpSendReceiveWithTwoConnectionsTest.java @@ -25,32 +25,32 @@ import org.apache.activemq.test.JmsTopicSendReceiveWithTwoConnectionsTest; */ public class UdpSendReceiveWithTwoConnectionsTest extends JmsTopicSendReceiveWithTwoConnectionsTest { - protected String brokerURI = "udp://localhost:8891"; - protected BrokerService broker; + protected String brokerURI = "udp://localhost:8891"; + protected BrokerService broker; - protected void setUp() throws Exception { - broker = createBroker(); - broker.start(); + protected void setUp() throws Exception { + broker = createBroker(); + broker.start(); - super.setUp(); - } + super.setUp(); + } - protected void tearDown() throws Exception { - super.tearDown(); - if (broker != null) { - broker.stop(); - } - } + protected void tearDown() throws Exception { + super.tearDown(); + if (broker != null) { + broker.stop(); + } + } - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setPersistent(false); - answer.setUseJmx(false); - answer.addConnector(brokerURI); - return answer; - } + protected BrokerService createBroker() throws Exception { + BrokerService answer = new BrokerService(); + answer.setPersistent(false); + answer.setUseJmx(false); + answer.addConnector(brokerURI); + return answer; + } - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(brokerURI); - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory(brokerURI); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/udp/UdpTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/udp/UdpTestSupport.java index 02e19b7c8e..1d27f67826 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/udp/UdpTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/udp/UdpTestSupport.java @@ -21,6 +21,7 @@ import java.io.IOException; import javax.jms.MessageNotWriteableException; import junit.framework.TestCase; + import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTextMessage; @@ -37,236 +38,245 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public abstract class UdpTestSupport extends TestCase implements TransportListener { - private static final Logger LOG = LoggerFactory.getLogger(UdpTestSupport.class); + private static final Logger LOG = LoggerFactory.getLogger(UdpTestSupport.class); - protected Transport producer; - protected Transport consumer; + protected Transport producer; + protected Transport consumer; - protected final Object lock = new Object(); - protected Command receivedCommand; - protected TransportServer server; - protected boolean large; + protected final Object lock = new Object(); + protected Command receivedCommand; + protected TransportServer server; + protected boolean large; - // You might want to set this to massive number if debugging - protected int waitForCommandTimeout = 40000; + // You might want to set this to massive number if debugging + protected int waitForCommandTimeout = 40000; - public void testSendingSmallMessage() throws Exception { - ConsumerInfo expected = new ConsumerInfo(); - expected.setSelector("Cheese"); - expected.setExclusive(true); - expected.setExclusive(true); - expected.setPrefetchSize(3456); + public void testSendingSmallMessage() throws Exception { + ConsumerInfo expected = new ConsumerInfo(); + expected.setSelector("Cheese"); + expected.setExclusive(true); + expected.setExclusive(true); + expected.setPrefetchSize(3456); - try { - LOG.info("About to send: " + expected); - producer.oneway(expected); + try { + LOG.info("About to send: " + expected); + producer.oneway(expected); - Command received = assertCommandReceived(); - assertTrue("Should have received a ConsumerInfo but was: " + received, received instanceof ConsumerInfo); - ConsumerInfo actual = (ConsumerInfo)received; - assertEquals("Selector", expected.getSelector(), actual.getSelector()); - assertEquals("isExclusive", expected.isExclusive(), actual.isExclusive()); - assertEquals("getPrefetchSize", expected.getPrefetchSize(), actual.getPrefetchSize()); - } catch (Exception e) { - LOG.info("Caught: " + e); - e.printStackTrace(); - fail("Failed to send to transport: " + e); - } - } + Command received = assertCommandReceived(); + assertTrue("Should have received a ConsumerInfo but was: " + received, received instanceof ConsumerInfo); + ConsumerInfo actual = (ConsumerInfo) received; + assertEquals("Selector", expected.getSelector(), actual.getSelector()); + assertEquals("isExclusive", expected.isExclusive(), actual.isExclusive()); + assertEquals("getPrefetchSize", expected.getPrefetchSize(), actual.getPrefetchSize()); + } + catch (Exception e) { + LOG.info("Caught: " + e); + e.printStackTrace(); + fail("Failed to send to transport: " + e); + } + } - public void testSendingMediumMessage() throws Exception { - String text = createMessageBodyText(4 * 105); - ActiveMQDestination destination = new ActiveMQQueue("Foo.Bar.Medium"); - assertSendTextMessage(destination, text); - } + public void testSendingMediumMessage() throws Exception { + String text = createMessageBodyText(4 * 105); + ActiveMQDestination destination = new ActiveMQQueue("Foo.Bar.Medium"); + assertSendTextMessage(destination, text); + } - public void testSendingLargeMessage() throws Exception { - String text = createMessageBodyText(4 * 1024); - ActiveMQDestination destination = new ActiveMQQueue("Foo.Bar.Large"); - assertSendTextMessage(destination, text); - } + public void testSendingLargeMessage() throws Exception { + String text = createMessageBodyText(4 * 1024); + ActiveMQDestination destination = new ActiveMQQueue("Foo.Bar.Large"); + assertSendTextMessage(destination, text); + } - protected void assertSendTextMessage(ActiveMQDestination destination, String text) throws MessageNotWriteableException { - large = true; + protected void assertSendTextMessage(ActiveMQDestination destination, + String text) throws MessageNotWriteableException { + large = true; - ActiveMQTextMessage expected = new ActiveMQTextMessage(); + ActiveMQTextMessage expected = new ActiveMQTextMessage(); - expected.setText(text); - expected.setDestination(destination); + expected.setText(text); + expected.setDestination(destination); - try { - LOG.info("About to send message of type: " + expected.getClass()); - producer.oneway(expected); + try { + LOG.info("About to send message of type: " + expected.getClass()); + producer.oneway(expected); - // lets send a dummy command to ensure things don't block if we - // discard the last one - // keepalive does not have a commandId... - // producer.oneway(new KeepAliveInfo()); - producer.oneway(new ProducerInfo()); - producer.oneway(new ProducerInfo()); + // lets send a dummy command to ensure things don't block if we + // discard the last one + // keepalive does not have a commandId... + // producer.oneway(new KeepAliveInfo()); + producer.oneway(new ProducerInfo()); + producer.oneway(new ProducerInfo()); - Command received = assertCommandReceived(); - assertTrue("Should have received an ActiveMQTextMessage but was: " + received, received instanceof ActiveMQTextMessage); - ActiveMQTextMessage actual = (ActiveMQTextMessage)received; + Command received = assertCommandReceived(); + assertTrue("Should have received an ActiveMQTextMessage but was: " + received, received instanceof ActiveMQTextMessage); + ActiveMQTextMessage actual = (ActiveMQTextMessage) received; - assertEquals("getDestination", expected.getDestination(), actual.getDestination()); - assertEquals("getText", expected.getText(), actual.getText()); + assertEquals("getDestination", expected.getDestination(), actual.getDestination()); + assertEquals("getText", expected.getText(), actual.getText()); - LOG.info("Received text message with: " + actual.getText().length() + " character(s)"); - } catch (Exception e) { - LOG.info("Caught: " + e); - e.printStackTrace(); - fail("Failed to send to transport: " + e); - } - } + LOG.info("Received text message with: " + actual.getText().length() + " character(s)"); + } + catch (Exception e) { + LOG.info("Caught: " + e); + e.printStackTrace(); + fail("Failed to send to transport: " + e); + } + } - protected String createMessageBodyText(int loopSize) { - StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < loopSize; i++) { - buffer.append("0123456789"); - } - return buffer.toString(); - } + protected String createMessageBodyText(int loopSize) { + StringBuffer buffer = new StringBuffer(); + for (int i = 0; i < loopSize; i++) { + buffer.append("0123456789"); + } + return buffer.toString(); + } - protected void setUp() throws Exception { - server = createServer(); - if (server != null) { - server.setAcceptListener(new TransportAcceptListener() { + protected void setUp() throws Exception { + server = createServer(); + if (server != null) { + server.setAcceptListener(new TransportAcceptListener() { - public void onAccept(Transport transport) { - consumer = transport; - consumer.setTransportListener(UdpTestSupport.this); - try { - consumer.start(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - public void onAcceptError(Exception error) { - } - }); - server.start(); - } - - consumer = createConsumer(); - if (consumer != null) { - consumer.setTransportListener(this); - consumer.start(); - } - - producer = createProducer(); - producer.setTransportListener(new TransportListener() { - public void onCommand(Object command) { - LOG.info("Producer received: " + command); + public void onAccept(Transport transport) { + consumer = transport; + consumer.setTransportListener(UdpTestSupport.this); + try { + consumer.start(); + } + catch (Exception e) { + throw new RuntimeException(e); + } } - public void onException(IOException error) { - LOG.info("Producer exception: " + error); - error.printStackTrace(); + public void onAcceptError(Exception error) { } + }); + server.start(); + } - public void transportInterupted() { + consumer = createConsumer(); + if (consumer != null) { + consumer.setTransportListener(this); + consumer.start(); + } + + producer = createProducer(); + producer.setTransportListener(new TransportListener() { + public void onCommand(Object command) { + LOG.info("Producer received: " + command); + } + + public void onException(IOException error) { + LOG.info("Producer exception: " + error); + error.printStackTrace(); + } + + public void transportInterupted() { + } + + public void transportResumed() { + } + }); + + producer.start(); + } + + protected void tearDown() throws Exception { + if (producer != null) { + try { + producer.stop(); + } + catch (Exception e) { + } + } + if (consumer != null) { + consumer.stop(); + } + if (server != null) { + server.stop(); + } + } + + public void onCommand(Object o) { + final Command command = (Command) o; + if (command instanceof WireFormatInfo) { + LOG.info("Got WireFormatInfo: " + command); + } + else { + if (command.isResponseRequired()) { + // lets send a response back... + sendResponse(command); + + } + if (large) { + LOG.info("### Received command: " + command.getClass() + " with id: " + command.getCommandId()); + } + else { + LOG.info("### Received command: " + command); + } + + synchronized (lock) { + if (receivedCommand == null) { + receivedCommand = command; } - - public void transportResumed() { + else { + LOG.info("Ignoring superfluous command: " + command); } - }); + lock.notifyAll(); + } + } + } - producer.start(); - } + protected void sendResponse(Command command) { + Response response = new Response(); + response.setCorrelationId(command.getCommandId()); + try { + consumer.oneway(response); + } + catch (IOException e) { + LOG.info("Caught: " + e); + e.printStackTrace(); + throw new RuntimeException(e); + } + } - protected void tearDown() throws Exception { - if (producer != null) { - try { - producer.stop(); - } catch (Exception e) { - } - } - if (consumer != null) { - consumer.stop(); - } - if (server != null) { - server.stop(); - } - } + public void onException(IOException error) { + LOG.info("### Received error: " + error); + error.printStackTrace(); + } - public void onCommand(Object o) { - final Command command = (Command)o; - if (command instanceof WireFormatInfo) { - LOG.info("Got WireFormatInfo: " + command); - } else { - if (command.isResponseRequired()) { - // lets send a response back... - sendResponse(command); + public void transportInterupted() { + LOG.info("### Transport interrupted"); + } - } - if (large) { - LOG.info("### Received command: " + command.getClass() + " with id: " + command.getCommandId()); - } else { - LOG.info("### Received command: " + command); - } + public void transportResumed() { + LOG.info("### Transport resumed"); + } - synchronized (lock) { - if (receivedCommand == null) { - receivedCommand = command; - } else { - LOG.info("Ignoring superfluous command: " + command); - } - lock.notifyAll(); - } - } - } - - protected void sendResponse(Command command) { - Response response = new Response(); - response.setCorrelationId(command.getCommandId()); - try { - consumer.oneway(response); - } catch (IOException e) { - LOG.info("Caught: " + e); - e.printStackTrace(); - throw new RuntimeException(e); - } - } - - public void onException(IOException error) { - LOG.info("### Received error: " + error); - error.printStackTrace(); - } - - public void transportInterupted() { - LOG.info("### Transport interrupted"); - } - - public void transportResumed() { - LOG.info("### Transport resumed"); - } - - protected Command assertCommandReceived() throws InterruptedException { - Command answer = null; - synchronized (lock) { + protected Command assertCommandReceived() throws InterruptedException { + Command answer = null; + synchronized (lock) { + answer = receivedCommand; + while (answer == null) { + lock.wait(waitForCommandTimeout); answer = receivedCommand; - while (answer == null) { - lock.wait(waitForCommandTimeout); - answer = receivedCommand; - } - } + } + } - assertNotNull("Should have received a Command by now!", answer); - return answer; - } + assertNotNull("Should have received a Command by now!", answer); + return answer; + } - protected abstract Transport createConsumer() throws Exception; + protected abstract Transport createConsumer() throws Exception; - protected abstract Transport createProducer() throws Exception; + protected abstract Transport createProducer() throws Exception; - protected TransportServer createServer() throws Exception { - return null; - } + protected TransportServer createServer() throws Exception { + return null; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/udp/UdpTransportTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/udp/UdpTransportTest.java index 98ea8f188b..5904e217d8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/udp/UdpTransportTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/udp/UdpTransportTest.java @@ -26,39 +26,39 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * - * + * + * */ public class UdpTransportTest extends UdpTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(UdpTransportTest.class); + private static final Logger LOG = LoggerFactory.getLogger(UdpTransportTest.class); - protected int consumerPort = 9123; - protected String producerURI = "udp://localhost:" + consumerPort; + protected int consumerPort = 9123; + protected String producerURI = "udp://localhost:" + consumerPort; - protected Transport createProducer() throws Exception { - LOG.info("Producer using URI: " + producerURI); - - // we are not using the TransportFactory as this assumes that - // UDP transports talk to a server using a WireFormat Negotiation step - // rather than talking directly to each other - - OpenWireFormat wireFormat = createWireFormat(); - UdpTransport transport = new UdpTransport(wireFormat, new URI(producerURI)); - transport.setSequenceGenerator(new IntSequenceGenerator()); - return new CommandJoiner(transport, wireFormat); - } + protected Transport createProducer() throws Exception { + LOG.info("Producer using URI: " + producerURI); - protected Transport createConsumer() throws Exception { - LOG.info("Consumer on port: " + consumerPort); - OpenWireFormat wireFormat = createWireFormat(); - UdpTransport transport = new UdpTransport(wireFormat, consumerPort); - transport.setSequenceGenerator(new IntSequenceGenerator()); - return new CommandJoiner(transport, wireFormat); - } + // we are not using the TransportFactory as this assumes that + // UDP transports talk to a server using a WireFormat Negotiation step + // rather than talking directly to each other - protected OpenWireFormat createWireFormat() { - return new OpenWireFormat(); - } + OpenWireFormat wireFormat = createWireFormat(); + UdpTransport transport = new UdpTransport(wireFormat, new URI(producerURI)); + transport.setSequenceGenerator(new IntSequenceGenerator()); + return new CommandJoiner(transport, wireFormat); + } + + protected Transport createConsumer() throws Exception { + LOG.info("Consumer on port: " + consumerPort); + OpenWireFormat wireFormat = createWireFormat(); + UdpTransport transport = new UdpTransport(wireFormat, consumerPort); + transport.setSequenceGenerator(new IntSequenceGenerator()); + return new CommandJoiner(transport, wireFormat); + } + + protected OpenWireFormat createWireFormat() { + return new OpenWireFormat(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/udp/UdpTransportUsingServerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/udp/UdpTransportUsingServerTest.java index bd9d9637a7..d3e58fad4b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/udp/UdpTransportUsingServerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/udp/UdpTransportUsingServerTest.java @@ -28,39 +28,40 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * - * + * + * */ public class UdpTransportUsingServerTest extends UdpTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(UdpTransportUsingServerTest.class); - protected int consumerPort = 9123; - protected String producerURI = "udp://localhost:" + consumerPort; - protected String serverURI = producerURI; + private static final Logger LOG = LoggerFactory.getLogger(UdpTransportUsingServerTest.class); - public void testRequestResponse() throws Exception { - ConsumerInfo expected = new ConsumerInfo(); - expected.setSelector("Edam"); - expected.setResponseRequired(true); - LOG.info("About to send: " + expected); - Response response = (Response) producer.request(expected, 2000); + protected int consumerPort = 9123; + protected String producerURI = "udp://localhost:" + consumerPort; + protected String serverURI = producerURI; - LOG.info("Received: " + response); - assertNotNull("Received a response", response); - assertTrue("Should not be an exception", !response.isException()); - } + public void testRequestResponse() throws Exception { + ConsumerInfo expected = new ConsumerInfo(); + expected.setSelector("Edam"); + expected.setResponseRequired(true); + LOG.info("About to send: " + expected); + Response response = (Response) producer.request(expected, 2000); - protected Transport createProducer() throws Exception { - LOG.info("Producer using URI: " + producerURI); - URI uri = new URI(producerURI); - return TransportFactory.connect(uri); - } + LOG.info("Received: " + response); + assertNotNull("Received a response", response); + assertTrue("Should not be an exception", !response.isException()); + } - protected TransportServer createServer() throws Exception { - return TransportFactory.bind(new URI(serverURI)); - } + protected Transport createProducer() throws Exception { + LOG.info("Producer using URI: " + producerURI); + URI uri = new URI(producerURI); + return TransportFactory.connect(uri); + } - protected Transport createConsumer() throws Exception { - return null; - } + protected TransportServer createServer() throws Exception { + return TransportFactory.bind(new URI(serverURI)); + } + + protected Transport createConsumer() throws Exception { + return null; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/udp/UpdTransportBindTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/udp/UpdTransportBindTest.java index 943b0439c6..c15e32e183 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/udp/UpdTransportBindTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/udp/UpdTransportBindTest.java @@ -22,22 +22,23 @@ import org.apache.activemq.EmbeddedBrokerTestSupport; import javax.jms.Connection; import javax.jms.JMSException; -public class UpdTransportBindTest extends EmbeddedBrokerTestSupport{ - final String addr = "udp://localhost:61625"; +public class UpdTransportBindTest extends EmbeddedBrokerTestSupport { - protected void setUp() throws Exception { - bindAddress = addr + "?soTimeout=1000"; - super.setUp(); - } + final String addr = "udp://localhost:61625"; - public void testConnect() throws Exception { - try { - Connection connection = new ActiveMQConnectionFactory(addr).createConnection(); - connection.start(); - } catch (JMSException e) { - fail("Could not start the connection for a UDP Transport. " + - "Check that the port and connector are available."); - } - } + protected void setUp() throws Exception { + bindAddress = addr + "?soTimeout=1000"; + super.setUp(); + } + + public void testConnect() throws Exception { + try { + Connection connection = new ActiveMQConnectionFactory(addr).createConnection(); + connection.start(); + } + catch (JMSException e) { + fail("Could not start the connection for a UDP Transport. " + "Check that the port and connector are available."); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/vm/VMTransportBrokerNameTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/vm/VMTransportBrokerNameTest.java index ac0539317a..3791848166 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/vm/VMTransportBrokerNameTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/vm/VMTransportBrokerNameTest.java @@ -28,23 +28,23 @@ import org.apache.activemq.broker.BrokerRegistry; public class VMTransportBrokerNameTest extends TestCase { - private static final String MY_BROKER = "myBroker"; - final String vmUrl = "vm:(broker:(tcp://localhost:61616)/" + MY_BROKER + "?persistent=false)"; + private static final String MY_BROKER = "myBroker"; + final String vmUrl = "vm:(broker:(tcp://localhost:61616)/" + MY_BROKER + "?persistent=false)"; - public void testBrokerName() throws Exception { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(new URI(vmUrl)); - ActiveMQConnection c1 = (ActiveMQConnection) cf.createConnection(); - assertTrue("Transport has name in it: " + c1.getTransport(), c1.getTransport().toString().contains(MY_BROKER)); - - // verify Broker is there with name - ActiveMQConnectionFactory cfbyName = new ActiveMQConnectionFactory(new URI("vm://" + MY_BROKER + "?create=false")); - Connection c2 = cfbyName.createConnection(); - - assertNotNull(BrokerRegistry.getInstance().lookup(MY_BROKER)); - assertEquals(BrokerRegistry.getInstance().findFirst().getBrokerName(), MY_BROKER); - assertEquals(BrokerRegistry.getInstance().getBrokers().size(), 1); - - c1.close(); - c2.close(); - } + public void testBrokerName() throws Exception { + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(new URI(vmUrl)); + ActiveMQConnection c1 = (ActiveMQConnection) cf.createConnection(); + assertTrue("Transport has name in it: " + c1.getTransport(), c1.getTransport().toString().contains(MY_BROKER)); + + // verify Broker is there with name + ActiveMQConnectionFactory cfbyName = new ActiveMQConnectionFactory(new URI("vm://" + MY_BROKER + "?create=false")); + Connection c2 = cfbyName.createConnection(); + + assertNotNull(BrokerRegistry.getInstance().lookup(MY_BROKER)); + assertEquals(BrokerRegistry.getInstance().findFirst().getBrokerName(), MY_BROKER); + assertEquals(BrokerRegistry.getInstance().getBrokers().size(), 1); + + c1.close(); + c2.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/vm/VMTransportBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/vm/VMTransportBrokerTest.java index c4f9ab2063..b43038b8d4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/vm/VMTransportBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/vm/VMTransportBrokerTest.java @@ -17,21 +17,21 @@ package org.apache.activemq.transport.vm; import junit.framework.Test; + import org.apache.activemq.transport.TransportBrokerTestSupport; public class VMTransportBrokerTest extends TransportBrokerTestSupport { - protected String getBindLocation() { - return "vm://localhost"; - } + protected String getBindLocation() { + return "vm://localhost"; + } - public static Test suite() { - return suite(VMTransportBrokerTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static Test suite() { + return suite(VMTransportBrokerTest.class); + } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/vm/VMTransportEmbeddedBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/vm/VMTransportEmbeddedBrokerTest.java index 62e4f71538..528059ccb4 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/vm/VMTransportEmbeddedBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/vm/VMTransportEmbeddedBrokerTest.java @@ -36,65 +36,66 @@ import org.apache.activemq.util.IOExceptionSupport; /** * Used to see if the VM transport starts an embedded broker on demand. - * - * */ public class VMTransportEmbeddedBrokerTest extends BrokerTestSupport { - public static void main(String[] args) { - junit.textui.TestRunner.run(VMTransportEmbeddedBrokerTest.class); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(VMTransportEmbeddedBrokerTest.class); + } - public void testConsumerPrefetchAtOne() throws Exception { - - // Make sure the broker is created due to the connection being started. - assertNull(BrokerRegistry.getInstance().lookup("localhost")); - StubConnection connection = createConnection(); - assertNotNull(BrokerRegistry.getInstance().lookup("localhost")); + public void testConsumerPrefetchAtOne() throws Exception { - // Start a producer and consumer - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - ActiveMQQueue destination = new ActiveMQQueue("TEST"); + // Make sure the broker is created due to the connection being started. + assertNull(BrokerRegistry.getInstance().lookup("localhost")); + StubConnection connection = createConnection(); + assertNotNull(BrokerRegistry.getInstance().lookup("localhost")); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setPrefetchSize(1); - connection.send(consumerInfo); - - // Send 2 messages to the broker. - connection.send(createMessage(producerInfo, destination, DeliveryMode.NON_PERSISTENT)); - connection.send(createMessage(producerInfo, destination, DeliveryMode.NON_PERSISTENT)); - - // Make sure only 1 message was delivered. - Message m = receiveMessage(connection); - assertNotNull(m); - assertNoMessagesLeft(connection); - - // Make sure the broker is shutdown when the connection is stopped. - assertNotNull(BrokerRegistry.getInstance().lookup("localhost")); - connection.stop(); - assertNull(BrokerRegistry.getInstance().lookup("localhost")); - } + // Start a producer and consumer + ConnectionInfo connectionInfo = createConnectionInfo(); + SessionInfo sessionInfo = createSessionInfo(connectionInfo); + ProducerInfo producerInfo = createProducerInfo(sessionInfo); + connection.send(connectionInfo); + connection.send(sessionInfo); + connection.send(producerInfo); - protected void setUp() throws Exception { - // Don't call super since it manually starts up a broker. - } - protected void tearDown() throws Exception { - // Don't call super since it manually tears down a broker. - } - protected StubConnection createConnection() throws Exception { - try { - Transport transport = TransportFactory.connect(new URI("vm://localhost?broker.persistent=false")); - StubConnection connection = new StubConnection(transport); - return connection; - } catch (URISyntaxException e) { - throw IOExceptionSupport.create(e); - } - } + ActiveMQQueue destination = new ActiveMQQueue("TEST"); + + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); + consumerInfo.setPrefetchSize(1); + connection.send(consumerInfo); + + // Send 2 messages to the broker. + connection.send(createMessage(producerInfo, destination, DeliveryMode.NON_PERSISTENT)); + connection.send(createMessage(producerInfo, destination, DeliveryMode.NON_PERSISTENT)); + + // Make sure only 1 message was delivered. + Message m = receiveMessage(connection); + assertNotNull(m); + assertNoMessagesLeft(connection); + + // Make sure the broker is shutdown when the connection is stopped. + assertNotNull(BrokerRegistry.getInstance().lookup("localhost")); + connection.stop(); + assertNull(BrokerRegistry.getInstance().lookup("localhost")); + } + + protected void setUp() throws Exception { + // Don't call super since it manually starts up a broker. + } + + protected void tearDown() throws Exception { + // Don't call super since it manually tears down a broker. + } + + protected StubConnection createConnection() throws Exception { + try { + Transport transport = TransportFactory.connect(new URI("vm://localhost?broker.persistent=false")); + StubConnection connection = new StubConnection(transport); + return connection; + } + catch (URISyntaxException e) { + throw IOExceptionSupport.create(e); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/vm/VMTransportThreadSafeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/vm/VMTransportThreadSafeTest.java index 8534f8908a..1f8ad67831 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/vm/VMTransportThreadSafeTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/vm/VMTransportThreadSafeTest.java @@ -49,872 +49,889 @@ import org.slf4j.LoggerFactory; public class VMTransportThreadSafeTest { - private static final Logger LOG = LoggerFactory.getLogger(VMTransportThreadSafeTest.class); + private static final Logger LOG = LoggerFactory.getLogger(VMTransportThreadSafeTest.class); - private final static String location1 = "vm://transport1"; - private final static String location2 = "vm://transport2"; + private final static String location1 = "vm://transport1"; + private final static String location2 = "vm://transport2"; - private final ConcurrentLinkedQueue localReceived = new ConcurrentLinkedQueue(); - private final ConcurrentLinkedQueue remoteReceived = new ConcurrentLinkedQueue(); + private final ConcurrentLinkedQueue localReceived = new ConcurrentLinkedQueue(); + private final ConcurrentLinkedQueue remoteReceived = new ConcurrentLinkedQueue(); - private class DummyCommand extends BaseCommand { + private class DummyCommand extends BaseCommand { - public final int sequenceId; + public final int sequenceId; - public DummyCommand() { - this.sequenceId = 0; - } + public DummyCommand() { + this.sequenceId = 0; + } - public DummyCommand(int id) { - this.sequenceId = id; - } + public DummyCommand(int id) { + this.sequenceId = id; + } - @Override - public Response visit(CommandVisitor visitor) throws Exception { - return null; - } + @Override + public Response visit(CommandVisitor visitor) throws Exception { + return null; + } - @Override - public byte getDataStructureType() { - return 42; - } - } + @Override + public byte getDataStructureType() { + return 42; + } + } - private class VMTestTransportListener implements TransportListener { + private class VMTestTransportListener implements TransportListener { - protected final Queue received; + protected final Queue received; - public boolean shutdownReceived = false; + public boolean shutdownReceived = false; - public VMTestTransportListener(Queue receiveQueue) { - this.received = receiveQueue; - } + public VMTestTransportListener(Queue receiveQueue) { + this.received = receiveQueue; + } - @Override - public void onCommand(Object command) { + @Override + public void onCommand(Object command) { - if (command instanceof ShutdownInfo) { - shutdownReceived = true; - } else { - received.add((DummyCommand) command); + if (command instanceof ShutdownInfo) { + shutdownReceived = true; + } + else { + received.add((DummyCommand) command); + } + } + + @Override + public void onException(IOException error) { + } + + @Override + public void transportInterupted() { + } + + @Override + public void transportResumed() { + } + } + + private class VMResponderTransportListener implements TransportListener { + + protected final Queue received; + + private final Transport peer; + + public VMResponderTransportListener(Queue receiveQueue, Transport peer) { + this.received = receiveQueue; + this.peer = peer; + } + + @Override + public void onCommand(Object command) { + + if (command instanceof ShutdownInfo) { + return; + } + else { + received.add((DummyCommand) command); + + if (peer != null) { + try { + peer.oneway(command); + } + catch (IOException e) { + } } - } + } + } - @Override - public void onException(IOException error) { - } + @Override + public void onException(IOException error) { + } - @Override - public void transportInterupted() { - } + @Override + public void transportInterupted() { + } - @Override - public void transportResumed() { - } - } + @Override + public void transportResumed() { + } + } - private class VMResponderTransportListener implements TransportListener { + private class SlowVMTestTransportListener extends VMTestTransportListener { - protected final Queue received; + private final TimeUnit delayUnit; + private final long delay; - private final Transport peer; + public SlowVMTestTransportListener(Queue receiveQueue) { + this(receiveQueue, 10, TimeUnit.MILLISECONDS); + } - public VMResponderTransportListener(Queue receiveQueue, Transport peer) { - this.received = receiveQueue; - this.peer = peer; - } + public SlowVMTestTransportListener(Queue receiveQueue, long delay, TimeUnit delayUnit) { + super(receiveQueue); - @Override - public void onCommand(Object command) { + this.delay = delay; + this.delayUnit = delayUnit; + } - if (command instanceof ShutdownInfo) { - return; - } else { - received.add((DummyCommand) command); + @Override + public void onCommand(Object command) { + super.onCommand(command); + try { + delayUnit.sleep(delay); + } + catch (InterruptedException e) { + } + } + } - if (peer != null) { - try { - peer.oneway(command); - } catch (IOException e) { - } - } - } - } + private class GatedVMTestTransportListener extends VMTestTransportListener { - @Override - public void onException(IOException error) { - } + private final CountDownLatch gate; - @Override - public void transportInterupted() { - } + public GatedVMTestTransportListener(Queue receiveQueue) { + this(receiveQueue, new CountDownLatch(1)); + } - @Override - public void transportResumed() { - } - } + public GatedVMTestTransportListener(Queue receiveQueue, CountDownLatch gate) { + super(receiveQueue); - private class SlowVMTestTransportListener extends VMTestTransportListener { + this.gate = gate; + } - private final TimeUnit delayUnit; - private final long delay; + @Override + public void onCommand(Object command) { + super.onCommand(command); + try { + gate.await(); + } + catch (InterruptedException e) { + } + } + } - public SlowVMTestTransportListener(Queue receiveQueue) { - this(receiveQueue, 10, TimeUnit.MILLISECONDS); - } + private void assertMessageAreOrdered(ConcurrentLinkedQueue queue) { + int lastSequenceId = 0; + for (DummyCommand command : queue) { + int id = command.sequenceId; + assertTrue("Last id: " + lastSequenceId + " should be less than current id: " + id, id > lastSequenceId); + } + } - public SlowVMTestTransportListener(Queue receiveQueue, long delay, TimeUnit delayUnit) { - super(receiveQueue); + @Before + public void setUp() throws Exception { + localReceived.clear(); + remoteReceived.clear(); + } - this.delay = delay; - this.delayUnit = delayUnit; - } + @After + public void tearDown() throws Exception { + } - @Override - public void onCommand(Object command) { - super.onCommand(command); + @Test(timeout = 60000) + public void testStartWthoutListenerIOE() throws Exception { + + final VMTransport local = new VMTransport(new URI(location1)); + final VMTransport remote = new VMTransport(new URI(location2)); + + local.setPeer(remote); + remote.setPeer(local); + + remote.setTransportListener(new VMTestTransportListener(localReceived)); + + try { + local.start(); + fail("Should have thrown an IOExcoption"); + } + catch (IOException e) { + } + } + + @Test(timeout = 60000) + public void testOnewayOnStoppedTransportTDE() throws Exception { + + final VMTransport local = new VMTransport(new URI(location1)); + final VMTransport remote = new VMTransport(new URI(location2)); + + local.setPeer(remote); + remote.setPeer(local); + + local.setTransportListener(new VMTestTransportListener(localReceived)); + remote.setTransportListener(new VMTestTransportListener(remoteReceived)); + + local.start(); + local.stop(); + + try { + local.oneway(new DummyCommand()); + fail("Should have thrown a TransportDisposedException"); + } + catch (TransportDisposedIOException e) { + } + } + + @Test(timeout = 60000) + public void testStopSendsShutdownToPeer() throws Exception { + + final VMTransport local = new VMTransport(new URI(location1)); + final VMTransport remote = new VMTransport(new URI(location2)); + + local.setPeer(remote); + remote.setPeer(local); + + final VMTestTransportListener remoteListener = new VMTestTransportListener(remoteReceived); + + local.setTransportListener(new VMTestTransportListener(localReceived)); + remote.setTransportListener(remoteListener); + + local.start(); + local.stop(); + + assertTrue(Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return remoteListener.shutdownReceived; + } + })); + } + + @Test(timeout = 60000) + public void testRemoteStopSendsExceptionToPendingRequests() throws Exception { + + final VMTransport local = new VMTransport(new URI(location1)); + final VMTransport remote = new VMTransport(new URI(location2)); + + local.setPeer(remote); + remote.setPeer(local); + + final VMTestTransportListener remoteListener = new VMTestTransportListener(remoteReceived); + remote.setTransportListener(remoteListener); + remote.start(); + + final Response[] answer = new Response[1]; + ResponseCorrelator responseCorrelator = new ResponseCorrelator(local); + responseCorrelator.setTransportListener(new VMTestTransportListener(localReceived)); + responseCorrelator.start(); + responseCorrelator.asyncRequest(new DummyCommand(), new ResponseCallback() { + @Override + public void onCompletion(FutureResponse resp) { try { - delayUnit.sleep(delay); - } catch (InterruptedException e) { + answer[0] = resp.getResult(); } - } - } + catch (IOException e) { + e.printStackTrace(); + } + } + }); - private class GatedVMTestTransportListener extends VMTestTransportListener { + // simulate broker stop + remote.stop(); - private final CountDownLatch gate; + assertTrue(Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("answer: " + answer[0]); + return answer[0] instanceof ExceptionResponse && ((ExceptionResponse) answer[0]).getException() instanceof TransportDisposedIOException; + } + })); - public GatedVMTestTransportListener(Queue receiveQueue) { - this(receiveQueue, new CountDownLatch(1)); - } + local.stop(); + } - public GatedVMTestTransportListener(Queue receiveQueue, CountDownLatch gate) { - super(receiveQueue); + @Test(timeout = 60000) + public void testMultipleStartsAndStops() throws Exception { - this.gate = gate; - } + final VMTransport local = new VMTransport(new URI(location1)); + final VMTransport remote = new VMTransport(new URI(location2)); - @Override - public void onCommand(Object command) { - super.onCommand(command); + local.setPeer(remote); + remote.setPeer(local); + + local.setTransportListener(new VMTestTransportListener(localReceived)); + remote.setTransportListener(new VMTestTransportListener(remoteReceived)); + + local.start(); + remote.start(); + + local.start(); + remote.start(); + + for (int i = 0; i < 100; ++i) { + local.oneway(new DummyCommand()); + } + + for (int i = 0; i < 100; ++i) { + remote.oneway(new DummyCommand()); + } + + local.start(); + remote.start(); + + assertTrue(Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return remoteReceived.size() == 100; + } + })); + + assertTrue(Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return localReceived.size() == 100; + } + })); + + local.stop(); + local.stop(); + remote.stop(); + remote.stop(); + } + + @Test(timeout = 60000) + public void testStartWithPeerNotStartedEnqueusCommandsNonAsync() throws Exception { + doTestStartWithPeerNotStartedEnqueusCommands(false); + } + + private void doTestStartWithPeerNotStartedEnqueusCommands(boolean async) throws Exception { + + final VMTransport local = new VMTransport(new URI(location1)); + final VMTransport remote = new VMTransport(new URI(location2)); + + remote.setAsync(async); + + local.setPeer(remote); + remote.setPeer(local); + + local.setTransportListener(new VMTestTransportListener(localReceived)); + remote.setTransportListener(new VMTestTransportListener(remoteReceived)); + + local.start(); + + for (int i = 0; i < 100; ++i) { + local.oneway(new DummyCommand()); + } + + assertEquals(100, remote.getMessageQueue().size()); + + remote.start(); + + assertTrue(Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return remoteReceived.size() == 100; + } + })); + + local.stop(); + remote.stop(); + } + + @Test(timeout = 60000) + public void testBlockedOnewayEnqeueAandStopTransportAsync() throws Exception { + doTestBlockedOnewayEnqeueAandStopTransport(true); + } + + @Test(timeout = 60000) + public void testBlockedOnewayEnqeueAandStopTransportNonAsync() throws Exception { + doTestBlockedOnewayEnqeueAandStopTransport(false); + } + + private void doTestBlockedOnewayEnqeueAandStopTransport(boolean async) throws Exception { + + final VMTransport local = new VMTransport(new URI(location1)); + final VMTransport remote = new VMTransport(new URI(location2)); + + final AtomicInteger sequenceId = new AtomicInteger(); + + remote.setAsync(async); + remote.setAsyncQueueDepth(99); + + local.setPeer(remote); + remote.setPeer(local); + + local.setTransportListener(new VMTestTransportListener(localReceived)); + remote.setTransportListener(new VMTestTransportListener(remoteReceived)); + + local.start(); + + Thread t = new Thread(new Runnable() { + + @Override + public void run() { + for (int i = 0; i < 100; ++i) { + try { + local.oneway(new DummyCommand(sequenceId.incrementAndGet())); + } + catch (Exception e) { + } + } + + } + }); + t.start(); + + LOG.debug("Started async delivery, wait for remote's queue to fill up"); + + assertTrue(Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return remote.getMessageQueue().remainingCapacity() == 0; + } + })); + + LOG.debug("Remote messageQ is full, start it and stop all"); + + remote.start(); + local.stop(); + remote.stop(); + } + + @Test(timeout = 60000) + public void testBlockedOnewayEnqeueWhileStartedDetectsStop() throws Exception { + final VMTransport local = new VMTransport(new URI(location1)); + final VMTransport remote = new VMTransport(new URI(location2)); + + final AtomicInteger sequenceId = new AtomicInteger(); + + remote.setAsync(true); + remote.setAsyncQueueDepth(2); + + local.setPeer(remote); + remote.setPeer(local); + + local.setTransportListener(new VMTestTransportListener(localReceived)); + remote.setTransportListener(new GatedVMTestTransportListener(remoteReceived)); + + local.start(); + remote.start(); + + Thread t = new Thread(new Runnable() { + + @Override + public void run() { + for (int i = 0; i < 3; ++i) { + try { + local.oneway(new DummyCommand(sequenceId.incrementAndGet())); + } + catch (Exception e) { + } + } + + } + }); + t.start(); + + LOG.debug("Started async delivery, wait for remote's queue to fill up"); + assertTrue(Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return remote.getMessageQueue().remainingCapacity() == 0; + } + })); + + LOG.debug("Starting async gate open."); + Thread gateman = new Thread(new Runnable() { + @Override + public void run() { try { - gate.await(); - } catch (InterruptedException e) { + Thread.sleep(100); } - } - } - - private void assertMessageAreOrdered(ConcurrentLinkedQueue queue) { - int lastSequenceId = 0; - for(DummyCommand command : queue) { - int id = command.sequenceId; - assertTrue("Last id: " + lastSequenceId + " should be less than current id: " + id, id > lastSequenceId); - } - } - - @Before - public void setUp() throws Exception { - localReceived.clear(); - remoteReceived.clear(); - } - - @After - public void tearDown() throws Exception { - } - - @Test(timeout=60000) - public void testStartWthoutListenerIOE() throws Exception { - - final VMTransport local = new VMTransport(new URI(location1)); - final VMTransport remote = new VMTransport(new URI(location2)); - - local.setPeer(remote); - remote.setPeer(local); - - remote.setTransportListener(new VMTestTransportListener(localReceived)); - - try { - local.start(); - fail("Should have thrown an IOExcoption"); - } catch (IOException e) { - } - } - - @Test(timeout=60000) - public void testOnewayOnStoppedTransportTDE() throws Exception { - - final VMTransport local = new VMTransport(new URI(location1)); - final VMTransport remote = new VMTransport(new URI(location2)); - - local.setPeer(remote); - remote.setPeer(local); - - local.setTransportListener(new VMTestTransportListener(localReceived)); - remote.setTransportListener(new VMTestTransportListener(remoteReceived)); - - local.start(); - local.stop(); - - try { - local.oneway(new DummyCommand()); - fail("Should have thrown a TransportDisposedException"); - } catch(TransportDisposedIOException e) { - } - } - - @Test(timeout=60000) - public void testStopSendsShutdownToPeer() throws Exception { - - final VMTransport local = new VMTransport(new URI(location1)); - final VMTransport remote = new VMTransport(new URI(location2)); - - local.setPeer(remote); - remote.setPeer(local); - - final VMTestTransportListener remoteListener = new VMTestTransportListener(remoteReceived); - - local.setTransportListener(new VMTestTransportListener(localReceived)); - remote.setTransportListener(remoteListener); - - local.start(); - local.stop(); - - assertTrue(Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return remoteListener.shutdownReceived; + catch (InterruptedException e) { } - })); - } + ((GatedVMTestTransportListener) remote.getTransportListener()).gate.countDown(); + } + }); + gateman.start(); - @Test(timeout=60000) - public void testRemoteStopSendsExceptionToPendingRequests() throws Exception { + remote.stop(); + local.stop(); - final VMTransport local = new VMTransport(new URI(location1)); - final VMTransport remote = new VMTransport(new URI(location2)); + assertEquals(1, remoteReceived.size()); + assertMessageAreOrdered(remoteReceived); + } - local.setPeer(remote); - remote.setPeer(local); + @Test(timeout = 60000) + public void testStopWhileStartingAsyncWithNoAsyncLimit() throws Exception { + // In the async case the iterate method should see that we are stopping and + // drop out before we dispatch all the messages but it should get at least 49 since + // the stop thread waits 500 mills and the listener is waiting 10 mills on each receive. + doTestStopWhileStartingWithNoAsyncLimit(true, 49); + } - final VMTestTransportListener remoteListener = new VMTestTransportListener(remoteReceived); - remote.setTransportListener(remoteListener); - remote.start(); + @Test(timeout = 60000) + public void testStopWhileStartingNonAsyncWithNoAsyncLimit() throws Exception { + // In the non-async case the start dispatches all messages up front and then continues on + doTestStopWhileStartingWithNoAsyncLimit(false, 100); + } - final Response[] answer = new Response[1]; - ResponseCorrelator responseCorrelator = new ResponseCorrelator(local); - responseCorrelator.setTransportListener(new VMTestTransportListener(localReceived)); - responseCorrelator.start(); - responseCorrelator.asyncRequest(new DummyCommand(), new ResponseCallback() { - @Override - public void onCompletion(FutureResponse resp) { - try { - answer[0] = resp.getResult(); - } catch (IOException e) { - e.printStackTrace(); - } + private void doTestStopWhileStartingWithNoAsyncLimit(boolean async, final int expect) throws Exception { + + final VMTransport local = new VMTransport(new URI(location1)); + final VMTransport remote = new VMTransport(new URI(location2)); + + remote.setAsync(async); + + local.setPeer(remote); + remote.setPeer(local); + + local.setTransportListener(new VMTestTransportListener(localReceived)); + remote.setTransportListener(new SlowVMTestTransportListener(remoteReceived)); + + local.start(); + + for (int i = 0; i < 100; ++i) { + local.oneway(new DummyCommand(i)); + } + + Thread t = new Thread(new Runnable() { + + @Override + public void run() { + try { + Thread.sleep(1000); + remote.stop(); } - }); - - // simulate broker stop - remote.stop(); - - assertTrue(Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("answer: " + answer[0]); - return answer[0] instanceof ExceptionResponse && ((ExceptionResponse)answer[0]).getException() instanceof TransportDisposedIOException; + catch (Exception e) { } - })); + } + }); - local.stop(); - } + remote.start(); - @Test(timeout=60000) - public void testMultipleStartsAndStops() throws Exception { + t.start(); - final VMTransport local = new VMTransport(new URI(location1)); - final VMTransport remote = new VMTransport(new URI(location2)); + assertTrue("Remote should receive: " + expect + ", commands but got: " + remoteReceived.size(), Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return remoteReceived.size() >= expect; + } + })); - local.setPeer(remote); - remote.setPeer(local); + LOG.debug("Remote listener received " + remoteReceived.size() + " messages"); - local.setTransportListener(new VMTestTransportListener(localReceived)); - remote.setTransportListener(new VMTestTransportListener(remoteReceived)); + local.stop(); - local.start(); - remote.start(); + assertTrue("Remote transport never was disposed.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return remote.isDisposed(); + } + })); + } - local.start(); - remote.start(); + @Test(timeout = 120000) + public void TestTwoWayMessageThroughPutSync() throws Exception { - for(int i = 0; i < 100; ++i) { - local.oneway(new DummyCommand()); - } + long totalTimes = 0; + final long executions = 20; - for(int i = 0; i < 100; ++i) { - remote.oneway(new DummyCommand()); - } + for (int i = 0; i < 20; ++i) { + totalTimes += doTestTwoWayMessageThroughPut(false); + } - local.start(); - remote.start(); + LOG.info("Total time of one way sync send throughput test: " + (totalTimes / executions) + "ms"); + } - assertTrue(Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return remoteReceived.size() == 100; + @Test(timeout = 120000) + public void TestTwoWayMessageThroughPutAsnyc() throws Exception { + + long totalTimes = 0; + final long executions = 50; + + for (int i = 0; i < executions; ++i) { + totalTimes += doTestTwoWayMessageThroughPut(false); + } + + LOG.info("Total time of one way async send throughput test: " + (totalTimes / executions) + "ms"); + } + + private long doTestTwoWayMessageThroughPut(boolean async) throws Exception { + + final VMTransport local = new VMTransport(new URI(location1)); + final VMTransport remote = new VMTransport(new URI(location2)); + + final AtomicInteger sequenceId = new AtomicInteger(); + + remote.setAsync(async); + + local.setPeer(remote); + remote.setPeer(local); + + local.setTransportListener(new VMTestTransportListener(localReceived)); + remote.setTransportListener(new VMTestTransportListener(remoteReceived)); + + final int messageCount = 200000; + + local.start(); + remote.start(); + + long startTime = System.currentTimeMillis(); + + Thread localSend = new Thread(new Runnable() { + + @Override + public void run() { + for (int i = 0; i < messageCount; ++i) { + try { + local.oneway(new DummyCommand(sequenceId.incrementAndGet())); + } + catch (Exception e) { + } } - })); - assertTrue(Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return localReceived.size() == 100; + } + }); + + Thread remoteSend = new Thread(new Runnable() { + + @Override + public void run() { + for (int i = 0; i < messageCount; ++i) { + try { + remote.oneway(new DummyCommand(sequenceId.incrementAndGet())); + } + catch (Exception e) { + } } - })); - local.stop(); - local.stop(); - remote.stop(); - remote.stop(); - } + } + }); - @Test(timeout=60000) - public void testStartWithPeerNotStartedEnqueusCommandsNonAsync() throws Exception { - doTestStartWithPeerNotStartedEnqueusCommands(false); - } + localSend.start(); + remoteSend.start(); - private void doTestStartWithPeerNotStartedEnqueusCommands(boolean async) throws Exception { + // Wait for both to finish and then check that each side go the correct amount + localSend.join(); + remoteSend.join(); - final VMTransport local = new VMTransport(new URI(location1)); - final VMTransport remote = new VMTransport(new URI(location2)); + long endTime = System.currentTimeMillis(); - remote.setAsync(async); + assertTrue(Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return remoteReceived.size() == messageCount; + } + })); - local.setPeer(remote); - remote.setPeer(local); + assertTrue(Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return localReceived.size() == messageCount; + } + })); - local.setTransportListener(new VMTestTransportListener(localReceived)); - remote.setTransportListener(new VMTestTransportListener(remoteReceived)); + LOG.debug("All messages sent,stop all"); - local.start(); + local.stop(); + remote.stop(); - for(int i = 0; i < 100; ++i) { - local.oneway(new DummyCommand()); - } + localReceived.clear(); + remoteReceived.clear(); - assertEquals(100, remote.getMessageQueue().size()); + return endTime - startTime; + } - remote.start(); + @Test(timeout = 120000) + public void TestOneWayMessageThroughPutSync() throws Exception { - assertTrue(Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return remoteReceived.size() == 100; + long totalTimes = 0; + final long executions = 30; + + for (int i = 0; i < executions; ++i) { + totalTimes += doTestOneWayMessageThroughPut(false); + } + + LOG.info("Total time of one way sync send throughput test: " + (totalTimes / executions) + "ms"); + } + + @Test(timeout = 120000) + public void TestOneWayMessageThroughPutAsnyc() throws Exception { + + long totalTimes = 0; + final long executions = 20; + + for (int i = 0; i < 20; ++i) { + totalTimes += doTestOneWayMessageThroughPut(true); + } + + LOG.info("Total time of one way async send throughput test: " + (totalTimes / executions) + "ms"); + } + + private long doTestOneWayMessageThroughPut(boolean async) throws Exception { + + final VMTransport local = new VMTransport(new URI(location1)); + final VMTransport remote = new VMTransport(new URI(location2)); + + final AtomicInteger sequenceId = new AtomicInteger(); + + remote.setAsync(async); + + local.setPeer(remote); + remote.setPeer(local); + + local.setTransportListener(new VMTestTransportListener(localReceived)); + remote.setTransportListener(new VMTestTransportListener(remoteReceived)); + + final int messageCount = 100000; + + local.start(); + remote.start(); + + long startTime = System.currentTimeMillis(); + + Thread localSend = new Thread(new Runnable() { + + @Override + public void run() { + for (int i = 0; i < messageCount; ++i) { + try { + local.oneway(new DummyCommand(sequenceId.incrementAndGet())); + } + catch (Exception e) { + } } - })); - local.stop(); - remote.stop(); - } + } + }); - @Test(timeout=60000) - public void testBlockedOnewayEnqeueAandStopTransportAsync() throws Exception { - doTestBlockedOnewayEnqeueAandStopTransport(true); - } + localSend.start(); - @Test(timeout=60000) - public void testBlockedOnewayEnqeueAandStopTransportNonAsync() throws Exception { - doTestBlockedOnewayEnqeueAandStopTransport(false); - } + // Wait for both to finish and then check that each side go the correct amount + localSend.join(); - private void doTestBlockedOnewayEnqeueAandStopTransport(boolean async) throws Exception { + long endTime = System.currentTimeMillis(); - final VMTransport local = new VMTransport(new URI(location1)); - final VMTransport remote = new VMTransport(new URI(location2)); + assertTrue(Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return remoteReceived.size() == messageCount; + } + })); - final AtomicInteger sequenceId = new AtomicInteger(); + LOG.debug("All messages sent,stop all"); - remote.setAsync(async); - remote.setAsyncQueueDepth(99); + local.stop(); + remote.stop(); - local.setPeer(remote); - remote.setPeer(local); + localReceived.clear(); + remoteReceived.clear(); - local.setTransportListener(new VMTestTransportListener(localReceived)); - remote.setTransportListener(new VMTestTransportListener(remoteReceived)); + return endTime - startTime; + } - local.start(); + @Test(timeout = 120000) + public void testTwoWayTrafficWithMutexTransportSync1() throws Exception { - Thread t = new Thread(new Runnable() { + for (int i = 0; i < 20; ++i) { + doTestTwoWayTrafficWithMutexTransport(false, false); + } + } - @Override - public void run() { - for(int i = 0; i < 100; ++i) { - try { - local.oneway(new DummyCommand(sequenceId.incrementAndGet())); - } catch (Exception e) { - } - } + @Test(timeout = 120000) + public void testTwoWayTrafficWithMutexTransportSync2() throws Exception { + for (int i = 0; i < 20; ++i) { + doTestTwoWayTrafficWithMutexTransport(true, false); + } + } + + @Test(timeout = 120000) + public void testTwoWayTrafficWithMutexTransportSync3() throws Exception { + + for (int i = 0; i < 20; ++i) { + doTestTwoWayTrafficWithMutexTransport(false, true); + } + } + + @Test(timeout = 120000) + public void testTwoWayTrafficWithMutexTransportSync4() throws Exception { + + for (int i = 0; i < 20; ++i) { + doTestTwoWayTrafficWithMutexTransport(false, false); + } + } + + public void doTestTwoWayTrafficWithMutexTransport(boolean localAsync, boolean remoteAsync) throws Exception { + + final VMTransport vmlocal = new VMTransport(new URI(location1)); + final VMTransport vmremote = new VMTransport(new URI(location2)); + + final MutexTransport local = new MutexTransport(vmlocal); + final MutexTransport remote = new MutexTransport(vmremote); + + final AtomicInteger sequenceId = new AtomicInteger(); + + vmlocal.setAsync(localAsync); + vmremote.setAsync(remoteAsync); + + vmlocal.setPeer(vmremote); + vmremote.setPeer(vmlocal); + + local.setTransportListener(new VMTestTransportListener(localReceived)); + remote.setTransportListener(new VMResponderTransportListener(remoteReceived, remote)); + + final int messageCount = 200000; + + Thread localSend = new Thread(new Runnable() { + + @Override + public void run() { + for (int i = 0; i < messageCount; ++i) { + try { + local.oneway(new DummyCommand(sequenceId.incrementAndGet())); + } + catch (Exception e) { + } } - }); - t.start(); + } + }); - LOG.debug("Started async delivery, wait for remote's queue to fill up"); + Thread remoteSend = new Thread(new Runnable() { - assertTrue(Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return remote.getMessageQueue().remainingCapacity() == 0; + @Override + public void run() { + for (int i = 0; i < messageCount; ++i) { + try { + remote.oneway(new DummyCommand(sequenceId.incrementAndGet())); + } + catch (Exception e) { + } } - })); + } + }); - LOG.debug("Remote messageQ is full, start it and stop all"); + localSend.start(); + remoteSend.start(); - remote.start(); - local.stop(); - remote.stop(); - } + Thread.sleep(10); - @Test(timeout=60000) - public void testBlockedOnewayEnqeueWhileStartedDetectsStop() throws Exception { - final VMTransport local = new VMTransport(new URI(location1)); - final VMTransport remote = new VMTransport(new URI(location2)); + local.start(); + remote.start(); - final AtomicInteger sequenceId = new AtomicInteger(); + // Wait for both to finish and then check that each side go the correct amount + localSend.join(); + remoteSend.join(); - remote.setAsync(true); - remote.setAsyncQueueDepth(2); + assertTrue("Remote should have received (" + messageCount + ") but got ()" + remoteReceived.size(), Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return remoteReceived.size() == messageCount; + } + })); - local.setPeer(remote); - remote.setPeer(local); + assertTrue("Local should have received (" + messageCount * 2 + ") but got ()" + localReceived.size(), Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return localReceived.size() == messageCount * 2; + } + })); - local.setTransportListener(new VMTestTransportListener(localReceived)); - remote.setTransportListener(new GatedVMTestTransportListener(remoteReceived)); + LOG.debug("All messages sent,stop all"); - local.start(); - remote.start(); + local.stop(); + remote.stop(); - Thread t = new Thread(new Runnable() { - - @Override - public void run() { - for(int i = 0; i < 3; ++i) { - try { - local.oneway(new DummyCommand(sequenceId.incrementAndGet())); - } catch (Exception e) { - } - } - - } - }); - t.start(); - - LOG.debug("Started async delivery, wait for remote's queue to fill up"); - assertTrue(Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return remote.getMessageQueue().remainingCapacity() == 0; - } - })); - - LOG.debug("Starting async gate open."); - Thread gateman = new Thread(new Runnable() { - @Override - public void run() { - try { - Thread.sleep(100); - } catch (InterruptedException e) { - } - ((GatedVMTestTransportListener) remote.getTransportListener()).gate.countDown(); - } - }); - gateman.start(); - - remote.stop(); - local.stop(); - - assertEquals(1, remoteReceived.size()); - assertMessageAreOrdered(remoteReceived); - } - - @Test(timeout=60000) - public void testStopWhileStartingAsyncWithNoAsyncLimit() throws Exception { - // In the async case the iterate method should see that we are stopping and - // drop out before we dispatch all the messages but it should get at least 49 since - // the stop thread waits 500 mills and the listener is waiting 10 mills on each receive. - doTestStopWhileStartingWithNoAsyncLimit(true, 49); - } - - @Test(timeout=60000) - public void testStopWhileStartingNonAsyncWithNoAsyncLimit() throws Exception { - // In the non-async case the start dispatches all messages up front and then continues on - doTestStopWhileStartingWithNoAsyncLimit(false, 100); - } - - private void doTestStopWhileStartingWithNoAsyncLimit(boolean async, final int expect) throws Exception { - - final VMTransport local = new VMTransport(new URI(location1)); - final VMTransport remote = new VMTransport(new URI(location2)); - - remote.setAsync(async); - - local.setPeer(remote); - remote.setPeer(local); - - local.setTransportListener(new VMTestTransportListener(localReceived)); - remote.setTransportListener(new SlowVMTestTransportListener(remoteReceived)); - - local.start(); - - for(int i = 0; i < 100; ++i) { - local.oneway(new DummyCommand(i)); - } - - Thread t = new Thread(new Runnable() { - - @Override - public void run() { - try { - Thread.sleep(1000); - remote.stop(); - } catch (Exception e) { - } - } - }); - - remote.start(); - - t.start(); - - assertTrue("Remote should receive: " + expect + ", commands but got: " + remoteReceived.size(), Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return remoteReceived.size() >= expect; - } - })); - - LOG.debug("Remote listener received " + remoteReceived.size() + " messages"); - - local.stop(); - - assertTrue("Remote transport never was disposed.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return remote.isDisposed(); - } - })); - } - - @Test(timeout=120000) - public void TestTwoWayMessageThroughPutSync() throws Exception { - - long totalTimes = 0; - final long executions = 20; - - for (int i = 0; i < 20; ++i) { - totalTimes += doTestTwoWayMessageThroughPut(false); - } - - LOG.info("Total time of one way sync send throughput test: " + (totalTimes/executions) + "ms"); - } - - @Test(timeout=120000) - public void TestTwoWayMessageThroughPutAsnyc() throws Exception { - - long totalTimes = 0; - final long executions = 50; - - for (int i = 0; i < executions; ++i) { - totalTimes += doTestTwoWayMessageThroughPut(false); - } - - LOG.info("Total time of one way async send throughput test: " + (totalTimes/executions) + "ms"); - } - - private long doTestTwoWayMessageThroughPut(boolean async) throws Exception { - - final VMTransport local = new VMTransport(new URI(location1)); - final VMTransport remote = new VMTransport(new URI(location2)); - - final AtomicInteger sequenceId = new AtomicInteger(); - - remote.setAsync(async); - - local.setPeer(remote); - remote.setPeer(local); - - local.setTransportListener(new VMTestTransportListener(localReceived)); - remote.setTransportListener(new VMTestTransportListener(remoteReceived)); - - final int messageCount = 200000; - - local.start(); - remote.start(); - - long startTime = System.currentTimeMillis(); - - Thread localSend = new Thread(new Runnable() { - - @Override - public void run() { - for(int i = 0; i < messageCount; ++i) { - try { - local.oneway(new DummyCommand(sequenceId.incrementAndGet())); - } catch (Exception e) { - } - } - - } - }); - - Thread remoteSend = new Thread(new Runnable() { - - @Override - public void run() { - for(int i = 0; i < messageCount; ++i) { - try { - remote.oneway(new DummyCommand(sequenceId.incrementAndGet())); - } catch (Exception e) { - } - } - - } - }); - - localSend.start(); - remoteSend.start(); - - // Wait for both to finish and then check that each side go the correct amount - localSend.join(); - remoteSend.join(); - - long endTime = System.currentTimeMillis(); - - assertTrue(Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return remoteReceived.size() == messageCount; - } - })); - - assertTrue(Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return localReceived.size() == messageCount; - } - })); - - LOG.debug("All messages sent,stop all"); - - local.stop(); - remote.stop(); - - localReceived.clear(); - remoteReceived.clear(); - - return endTime - startTime; - } - - @Test(timeout=120000) - public void TestOneWayMessageThroughPutSync() throws Exception { - - long totalTimes = 0; - final long executions = 30; - - for (int i = 0; i < executions; ++i) { - totalTimes += doTestOneWayMessageThroughPut(false); - } - - LOG.info("Total time of one way sync send throughput test: " + (totalTimes/executions) + "ms"); - } - - @Test(timeout=120000) - public void TestOneWayMessageThroughPutAsnyc() throws Exception { - - long totalTimes = 0; - final long executions = 20; - - for (int i = 0; i < 20; ++i) { - totalTimes += doTestOneWayMessageThroughPut(true); - } - - LOG.info("Total time of one way async send throughput test: " + (totalTimes/executions) + "ms"); - } - - private long doTestOneWayMessageThroughPut(boolean async) throws Exception { - - final VMTransport local = new VMTransport(new URI(location1)); - final VMTransport remote = new VMTransport(new URI(location2)); - - final AtomicInteger sequenceId = new AtomicInteger(); - - remote.setAsync(async); - - local.setPeer(remote); - remote.setPeer(local); - - local.setTransportListener(new VMTestTransportListener(localReceived)); - remote.setTransportListener(new VMTestTransportListener(remoteReceived)); - - final int messageCount = 100000; - - local.start(); - remote.start(); - - long startTime = System.currentTimeMillis(); - - Thread localSend = new Thread(new Runnable() { - - @Override - public void run() { - for(int i = 0; i < messageCount; ++i) { - try { - local.oneway(new DummyCommand(sequenceId.incrementAndGet())); - } catch (Exception e) { - } - } - - } - }); - - localSend.start(); - - // Wait for both to finish and then check that each side go the correct amount - localSend.join(); - - long endTime = System.currentTimeMillis(); - - assertTrue(Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return remoteReceived.size() == messageCount; - } - })); - - LOG.debug("All messages sent,stop all"); - - local.stop(); - remote.stop(); - - localReceived.clear(); - remoteReceived.clear(); - - return endTime - startTime; - } - - @Test(timeout=120000) - public void testTwoWayTrafficWithMutexTransportSync1() throws Exception { - - for (int i = 0; i < 20; ++i) { - doTestTwoWayTrafficWithMutexTransport(false, false); - } - } - - @Test(timeout=120000) - public void testTwoWayTrafficWithMutexTransportSync2() throws Exception { - - for (int i = 0; i < 20; ++i) { - doTestTwoWayTrafficWithMutexTransport(true, false); - } - } - - @Test(timeout=120000) - public void testTwoWayTrafficWithMutexTransportSync3() throws Exception { - - for (int i = 0; i < 20; ++i) { - doTestTwoWayTrafficWithMutexTransport(false, true); - } - } - - @Test(timeout=120000) - public void testTwoWayTrafficWithMutexTransportSync4() throws Exception { - - for (int i = 0; i < 20; ++i) { - doTestTwoWayTrafficWithMutexTransport(false, false); - } - } - - public void doTestTwoWayTrafficWithMutexTransport(boolean localAsync, boolean remoteAsync) throws Exception { - - final VMTransport vmlocal = new VMTransport(new URI(location1)); - final VMTransport vmremote = new VMTransport(new URI(location2)); - - final MutexTransport local = new MutexTransport(vmlocal); - final MutexTransport remote = new MutexTransport(vmremote); - - final AtomicInteger sequenceId = new AtomicInteger(); - - vmlocal.setAsync(localAsync); - vmremote.setAsync(remoteAsync); - - vmlocal.setPeer(vmremote); - vmremote.setPeer(vmlocal); - - local.setTransportListener(new VMTestTransportListener(localReceived)); - remote.setTransportListener(new VMResponderTransportListener(remoteReceived, remote)); - - final int messageCount = 200000; - - Thread localSend = new Thread(new Runnable() { - - @Override - public void run() { - for(int i = 0; i < messageCount; ++i) { - try { - local.oneway(new DummyCommand(sequenceId.incrementAndGet())); - } catch (Exception e) { - } - } - } - }); - - Thread remoteSend = new Thread(new Runnable() { - - @Override - public void run() { - for(int i = 0; i < messageCount; ++i) { - try { - remote.oneway(new DummyCommand(sequenceId.incrementAndGet())); - } catch (Exception e) { - } - } - } - }); - - localSend.start(); - remoteSend.start(); - - Thread.sleep(10); - - local.start(); - remote.start(); - - // Wait for both to finish and then check that each side go the correct amount - localSend.join(); - remoteSend.join(); - - assertTrue("Remote should have received ("+messageCount+") but got ()" + remoteReceived.size(), Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return remoteReceived.size() == messageCount; - } - })); - - assertTrue("Local should have received ("+messageCount*2+") but got ()" + localReceived.size(), Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return localReceived.size() == messageCount*2; - } - })); - - LOG.debug("All messages sent,stop all"); - - local.stop(); - remote.stop(); - - localReceived.clear(); - remoteReceived.clear(); - } + localReceived.clear(); + remoteReceived.clear(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/vm/VMTransportWaitForTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/vm/VMTransportWaitForTest.java index 805a10c6be..dd14d67658 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/vm/VMTransportWaitForTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/vm/VMTransportWaitForTest.java @@ -36,102 +36,104 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class VMTransportWaitForTest { - static final Logger LOG = LoggerFactory.getLogger(VMTransportWaitForTest.class); - private static final int WAIT_TIME = 20000; - private static final int SHORT_WAIT_TIME = 5000; + static final Logger LOG = LoggerFactory.getLogger(VMTransportWaitForTest.class); - private static final String VM_BROKER_URI_NO_WAIT = - "vm://localhost?broker.persistent=false&create=false"; + private static final int WAIT_TIME = 20000; + private static final int SHORT_WAIT_TIME = 5000; - private static final String VM_BROKER_URI_WAIT_FOR_START = - VM_BROKER_URI_NO_WAIT + "&waitForStart=" + WAIT_TIME; + private static final String VM_BROKER_URI_NO_WAIT = "vm://localhost?broker.persistent=false&create=false"; - private static final String VM_BROKER_URI_SHORT_WAIT_FOR_START = - VM_BROKER_URI_NO_WAIT + "&waitForStart=" + SHORT_WAIT_TIME; + private static final String VM_BROKER_URI_WAIT_FOR_START = VM_BROKER_URI_NO_WAIT + "&waitForStart=" + WAIT_TIME; - CountDownLatch started = new CountDownLatch(1); - CountDownLatch gotConnection = new CountDownLatch(1); + private static final String VM_BROKER_URI_SHORT_WAIT_FOR_START = VM_BROKER_URI_NO_WAIT + "&waitForStart=" + SHORT_WAIT_TIME; - @After - public void after() throws IOException { - BrokerRegistry.getInstance().unbind("localhost"); - } + CountDownLatch started = new CountDownLatch(1); + CountDownLatch gotConnection = new CountDownLatch(1); - @Test(timeout=90000) - public void testWaitFor() throws Exception { - try { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(new URI(VM_BROKER_URI_NO_WAIT)); - cf.createConnection(); - fail("expect broker not exist exception"); - } catch (JMSException expectedOnNoBrokerAndNoCreate) { - } + @After + public void after() throws IOException { + BrokerRegistry.getInstance().unbind("localhost"); + } - // spawn a thread that will wait for an embedded broker to start via - // vm://.. - Thread t = new Thread("ClientConnectionThread") { - @Override - public void run() { - try { - started.countDown(); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(new URI(VM_BROKER_URI_WAIT_FOR_START)); - cf.createConnection(); - gotConnection.countDown(); - } catch (Exception e) { - e.printStackTrace(); - fail("unexpected exception: " + e); - } + @Test(timeout = 90000) + public void testWaitFor() throws Exception { + try { + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(new URI(VM_BROKER_URI_NO_WAIT)); + cf.createConnection(); + fail("expect broker not exist exception"); + } + catch (JMSException expectedOnNoBrokerAndNoCreate) { + } + + // spawn a thread that will wait for an embedded broker to start via + // vm://.. + Thread t = new Thread("ClientConnectionThread") { + @Override + public void run() { + try { + started.countDown(); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(new URI(VM_BROKER_URI_WAIT_FOR_START)); + cf.createConnection(); + gotConnection.countDown(); } - }; - t.start(); - started.await(20, TimeUnit.SECONDS); - Thread.yield(); - assertFalse("has not got connection", gotConnection.await(2, TimeUnit.SECONDS)); + catch (Exception e) { + e.printStackTrace(); + fail("unexpected exception: " + e); + } + } + }; + t.start(); + started.await(20, TimeUnit.SECONDS); + Thread.yield(); + assertFalse("has not got connection", gotConnection.await(2, TimeUnit.SECONDS)); - BrokerService broker = new BrokerService(); - broker.setPersistent(false); - broker.start(); - assertTrue("has got connection", gotConnection.await(5, TimeUnit.SECONDS)); - broker.stop(); - } + BrokerService broker = new BrokerService(); + broker.setPersistent(false); + broker.start(); + assertTrue("has got connection", gotConnection.await(5, TimeUnit.SECONDS)); + broker.stop(); + } - @Test(timeout=90000) - public void testWaitForNoBrokerInRegistry() throws Exception { + @Test(timeout = 90000) + public void testWaitForNoBrokerInRegistry() throws Exception { - long startTime = System.currentTimeMillis(); + long startTime = System.currentTimeMillis(); - try { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(new URI(VM_BROKER_URI_SHORT_WAIT_FOR_START)); - cf.createConnection(); - fail("expect broker not exist exception"); - } catch (JMSException expectedOnNoBrokerAndNoCreate) { - } + try { + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(new URI(VM_BROKER_URI_SHORT_WAIT_FOR_START)); + cf.createConnection(); + fail("expect broker not exist exception"); + } + catch (JMSException expectedOnNoBrokerAndNoCreate) { + } - long endTime = System.currentTimeMillis(); + long endTime = System.currentTimeMillis(); - LOG.info("Total wait time was: {}", endTime - startTime); - assertTrue(endTime - startTime >= SHORT_WAIT_TIME - 100); - } + LOG.info("Total wait time was: {}", endTime - startTime); + assertTrue(endTime - startTime >= SHORT_WAIT_TIME - 100); + } - @Test(timeout=90000) - public void testWaitForNotStartedButInRegistry() throws Exception { + @Test(timeout = 90000) + public void testWaitForNotStartedButInRegistry() throws Exception { - BrokerService broker = new BrokerService(); - broker.setPersistent(false); - BrokerRegistry.getInstance().bind("localhost", broker); + BrokerService broker = new BrokerService(); + broker.setPersistent(false); + BrokerRegistry.getInstance().bind("localhost", broker); - long startTime = System.currentTimeMillis(); + long startTime = System.currentTimeMillis(); - try { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(new URI(VM_BROKER_URI_SHORT_WAIT_FOR_START)); - cf.createConnection(); - fail("expect broker not exist exception"); - } catch (JMSException expectedOnNoBrokerAndNoCreate) { - } + try { + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(new URI(VM_BROKER_URI_SHORT_WAIT_FOR_START)); + cf.createConnection(); + fail("expect broker not exist exception"); + } + catch (JMSException expectedOnNoBrokerAndNoCreate) { + } - long endTime = System.currentTimeMillis(); + long endTime = System.currentTimeMillis(); - LOG.info("Total wait time was: {}", endTime - startTime); - assertTrue(endTime - startTime >= SHORT_WAIT_TIME - 100); - } + LOG.info("Total wait time was: {}", endTime - startTime); + assertTrue(endTime - startTime >= SHORT_WAIT_TIME - 100); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/vm/VmTransportNetworkBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/vm/VmTransportNetworkBrokerTest.java index e29c078e16..3453a2e6df 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/vm/VmTransportNetworkBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/vm/VmTransportNetworkBrokerTest.java @@ -24,6 +24,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.jms.Connection; + import junit.framework.TestCase; import org.apache.activemq.ActiveMQConnectionFactory; @@ -34,122 +35,117 @@ import org.apache.activemq.network.NetworkConnector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - public class VmTransportNetworkBrokerTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(VmTransportNetworkBrokerTest.class); + private static final Logger LOG = LoggerFactory.getLogger(VmTransportNetworkBrokerTest.class); - private static final String VM_BROKER_URI = - "vm://localhost?create=false"; - - CountDownLatch started = new CountDownLatch(1); - CountDownLatch gotConnection = new CountDownLatch(1); + private static final String VM_BROKER_URI = "vm://localhost?create=false"; - public void testNoThreadLeak() throws Exception { + CountDownLatch started = new CountDownLatch(1); + CountDownLatch gotConnection = new CountDownLatch(1); - // with VMConnection and simple discovery network connector - int originalThreadCount = Thread.activeCount(); - LOG.debug(ThreadExplorer.show("threads at beginning")); - - BrokerService broker = new BrokerService(); - broker.setDedicatedTaskRunner(true); - broker.setPersistent(false); - broker.addConnector("tcp://localhost:61616"); - NetworkConnector networkConnector = broker.addNetworkConnector("static:(tcp://wrongHostname1:61617,tcp://wrongHostname2:61618)?useExponentialBackOff=false"); - networkConnector.setDuplex(true); - broker.start(); - - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(new URI(VM_BROKER_URI)); - Connection connection = cf.createConnection("system", "manager"); - connection.start(); - - // let it settle - TimeUnit.SECONDS.sleep(5); - - int threadCountAfterStart = Thread.activeCount(); - TimeUnit.SECONDS.sleep(30); - int threadCountAfterSleep = Thread.activeCount(); - - assertTrue("Threads are leaking: " + ThreadExplorer.show("active sleep") + ", threadCount=" +threadCountAfterStart + " threadCountAfterSleep=" + threadCountAfterSleep, - threadCountAfterSleep < threadCountAfterStart + 8); + public void testNoThreadLeak() throws Exception { - connection.close(); - broker.stop(); - broker.waitUntilStopped(); + // with VMConnection and simple discovery network connector + int originalThreadCount = Thread.activeCount(); + LOG.debug(ThreadExplorer.show("threads at beginning")); - // testNoDanglingThreadsAfterStop with tcp transport - broker = new BrokerService(); - broker.setSchedulerSupport(true); - broker.setDedicatedTaskRunner(true); - broker.setPersistent(false); - broker.addConnector("tcp://localhost:61616?wireFormat.maxInactivityDuration=1000&wireFormat.maxInactivityDurationInitalDelay=1000"); - broker.start(); + BrokerService broker = new BrokerService(); + broker.setDedicatedTaskRunner(true); + broker.setPersistent(false); + broker.addConnector("tcp://localhost:61616"); + NetworkConnector networkConnector = broker.addNetworkConnector("static:(tcp://wrongHostname1:61617,tcp://wrongHostname2:61618)?useExponentialBackOff=false"); + networkConnector.setDuplex(true); + broker.start(); - cf = new ActiveMQConnectionFactory("tcp://localhost:61616?wireFormat.maxInactivityDuration=1000&wireFormat.maxInactivityDurationInitalDelay=1000"); - connection = cf.createConnection("system", "manager"); - connection.start(); - connection.close(); - broker.stop(); - broker.waitUntilStopped(); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(new URI(VM_BROKER_URI)); + Connection connection = cf.createConnection("system", "manager"); + connection.start(); - // let it settle - TimeUnit.SECONDS.sleep(5); + // let it settle + TimeUnit.SECONDS.sleep(5); - // get final threads but filter out any daemon threads that the JVM may have created. - Thread[] threads = filterDaemonThreads(ThreadExplorer.listThreads()); - int threadCountAfterStop = threads.length; + int threadCountAfterStart = Thread.activeCount(); + TimeUnit.SECONDS.sleep(30); + int threadCountAfterSleep = Thread.activeCount(); - // lets see the thread counts at INFO level so they are always in the test log - LOG.info(ThreadExplorer.show("active after stop")); - LOG.info("originalThreadCount=" + originalThreadCount + " threadCountAfterStop=" + threadCountAfterStop); + assertTrue("Threads are leaking: " + ThreadExplorer.show("active sleep") + ", threadCount=" + threadCountAfterStart + " threadCountAfterSleep=" + threadCountAfterSleep, threadCountAfterSleep < threadCountAfterStart + 8); - assertTrue("Threads are leaking: " + - ThreadExplorer.show("active after stop") + - ". originalThreadCount=" + - originalThreadCount + - " threadCountAfterStop=" + - threadCountAfterStop, - threadCountAfterStop <= originalThreadCount); - } - - - /** - * Filters any daemon threads from the thread list. - * - * Thread counts before and after the test should ideally be equal. - * However there is no guarantee that the JVM does not create any - * additional threads itself. - * E.g. on Mac OSX there is a JVM internal thread called - * "Poller SunPKCS11-Darwin" created after the test go started and - * under the main thread group. - * When debugging tests in Eclipse another so called "Reader" thread - * is created by Eclipse. - * So we cannot assume that the JVM does not create additional threads - * during the test. However for the time being we assume that any such - * additionally created threads are daemon threads. - * - * @param threads - the array of threads to parse - * @return a new array with any daemon threads removed - */ - public Thread[] filterDaemonThreads(Thread[] threads) throws Exception { - - List threadList = new ArrayList(Arrays.asList(threads)); - - // Can't use an Iterator as it would raise a - // ConcurrentModificationException when trying to remove an element - // from the list, so using standard walk through - for (int i = 0 ; i < threadList.size(); i++) { - - Thread thread = threadList.get(i); - LOG.debug("Inspecting thread " + thread.getName()); - if (thread.isDaemon()) { - LOG.debug("Removing deamon thread."); - threadList.remove(thread); - Thread.sleep(100); - - } - } - LOG.debug("Converting list back to Array"); - return threadList.toArray(new Thread[0]); - } + connection.close(); + broker.stop(); + broker.waitUntilStopped(); + + // testNoDanglingThreadsAfterStop with tcp transport + broker = new BrokerService(); + broker.setSchedulerSupport(true); + broker.setDedicatedTaskRunner(true); + broker.setPersistent(false); + broker.addConnector("tcp://localhost:61616?wireFormat.maxInactivityDuration=1000&wireFormat.maxInactivityDurationInitalDelay=1000"); + broker.start(); + + cf = new ActiveMQConnectionFactory("tcp://localhost:61616?wireFormat.maxInactivityDuration=1000&wireFormat.maxInactivityDurationInitalDelay=1000"); + connection = cf.createConnection("system", "manager"); + connection.start(); + connection.close(); + broker.stop(); + broker.waitUntilStopped(); + + // let it settle + TimeUnit.SECONDS.sleep(5); + + // get final threads but filter out any daemon threads that the JVM may have created. + Thread[] threads = filterDaemonThreads(ThreadExplorer.listThreads()); + int threadCountAfterStop = threads.length; + + // lets see the thread counts at INFO level so they are always in the test log + LOG.info(ThreadExplorer.show("active after stop")); + LOG.info("originalThreadCount=" + originalThreadCount + " threadCountAfterStop=" + threadCountAfterStop); + + assertTrue("Threads are leaking: " + + ThreadExplorer.show("active after stop") + + ". originalThreadCount=" + + originalThreadCount + + " threadCountAfterStop=" + + threadCountAfterStop, threadCountAfterStop <= originalThreadCount); + } + + /** + * Filters any daemon threads from the thread list. + * + * Thread counts before and after the test should ideally be equal. + * However there is no guarantee that the JVM does not create any + * additional threads itself. + * E.g. on Mac OSX there is a JVM internal thread called + * "Poller SunPKCS11-Darwin" created after the test go started and + * under the main thread group. + * When debugging tests in Eclipse another so called "Reader" thread + * is created by Eclipse. + * So we cannot assume that the JVM does not create additional threads + * during the test. However for the time being we assume that any such + * additionally created threads are daemon threads. + * + * @param threads - the array of threads to parse + * @return a new array with any daemon threads removed + */ + public Thread[] filterDaemonThreads(Thread[] threads) throws Exception { + + List threadList = new ArrayList(Arrays.asList(threads)); + + // Can't use an Iterator as it would raise a + // ConcurrentModificationException when trying to remove an element + // from the list, so using standard walk through + for (int i = 0; i < threadList.size(); i++) { + + Thread thread = threadList.get(i); + LOG.debug("Inspecting thread " + thread.getName()); + if (thread.isDaemon()) { + LOG.debug("Removing deamon thread."); + threadList.remove(thread); + Thread.sleep(100); + + } + } + LOG.debug("Converting list back to Array"); + return threadList.toArray(new Thread[0]); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/CompositeMessageCursorUsageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/CompositeMessageCursorUsageTest.java index d0d5965aed..79fbbdf415 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/CompositeMessageCursorUsageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/CompositeMessageCursorUsageTest.java @@ -32,59 +32,59 @@ import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.core.MessageCreator; public class CompositeMessageCursorUsageTest extends TestCase { - - BrokerService broker; - - public void setUp() throws Exception { - broker = new BrokerService(); - broker.setPersistent(false); - broker.start(); - } - - protected void tearDown() throws Exception { - broker.stop(); - } - public void testCompositeMessageUsage() throws Exception { + BrokerService broker; - String compositeQueue = "compositeA,compositeB"; + public void setUp() throws Exception { + broker = new BrokerService(); + broker.setPersistent(false); + broker.start(); + } - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); - JmsTemplate jt = new JmsTemplate(cf); + protected void tearDown() throws Exception { + broker.stop(); + } - jt.send(compositeQueue, new MessageCreator() { - public Message createMessage(Session session) throws JMSException { - TextMessage tm = session.createTextMessage(); - tm.setText("test"); - return tm; - } - }); + public void testCompositeMessageUsage() throws Exception { - jt.send("noCompositeA", new MessageCreator() { - public Message createMessage(Session session) throws JMSException { - TextMessage tm = session.createTextMessage(); - tm.setText("test"); - return tm; - } - }); + String compositeQueue = "compositeA,compositeB"; - jt.send("noCompositeB", new MessageCreator() { - public Message createMessage(Session session) throws JMSException { - TextMessage tm = session.createTextMessage(); - tm.setText("test"); - return tm; - } - }); - - assertEquals("Cursor memory usage wrong for 'noCompositeA' queue", 1032, getQueueView("noCompositeA").getCursorMemoryUsage()); - assertEquals("Cursor memory usage wrong for 'noCompositeB' queue", 1032, getQueueView("noCompositeB").getCursorMemoryUsage()); - assertEquals("Cursor memory usage wrong for 'CompositeA' queue", 1032, getQueueView("compositeA").getCursorMemoryUsage()); - assertEquals("Cursor memory usage wrong for 'CompositeB' queue", 1032, getQueueView("compositeB").getCursorMemoryUsage()); - - } - - public QueueViewMBean getQueueView(String queueName) throws Exception { - ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq" + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + queueName); - return (QueueViewMBean) broker.getManagementContext().newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); - } + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); + JmsTemplate jt = new JmsTemplate(cf); + + jt.send(compositeQueue, new MessageCreator() { + public Message createMessage(Session session) throws JMSException { + TextMessage tm = session.createTextMessage(); + tm.setText("test"); + return tm; + } + }); + + jt.send("noCompositeA", new MessageCreator() { + public Message createMessage(Session session) throws JMSException { + TextMessage tm = session.createTextMessage(); + tm.setText("test"); + return tm; + } + }); + + jt.send("noCompositeB", new MessageCreator() { + public Message createMessage(Session session) throws JMSException { + TextMessage tm = session.createTextMessage(); + tm.setText("test"); + return tm; + } + }); + + assertEquals("Cursor memory usage wrong for 'noCompositeA' queue", 1032, getQueueView("noCompositeA").getCursorMemoryUsage()); + assertEquals("Cursor memory usage wrong for 'noCompositeB' queue", 1032, getQueueView("noCompositeB").getCursorMemoryUsage()); + assertEquals("Cursor memory usage wrong for 'CompositeA' queue", 1032, getQueueView("compositeA").getCursorMemoryUsage()); + assertEquals("Cursor memory usage wrong for 'CompositeB' queue", 1032, getQueueView("compositeB").getCursorMemoryUsage()); + + } + + public QueueViewMBean getQueueView(String queueName) throws Exception { + ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq" + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + queueName); + return (QueueViewMBean) broker.getManagementContext().newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/JobSchedulerStoreUsageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/JobSchedulerStoreUsageTest.java index f9697d975a..06fd4a3ee8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/JobSchedulerStoreUsageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/JobSchedulerStoreUsageTest.java @@ -36,72 +36,72 @@ import org.slf4j.LoggerFactory; public class JobSchedulerStoreUsageTest extends EmbeddedBrokerTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(JobSchedulerStoreUsageTest.class); + private static final Logger LOG = LoggerFactory.getLogger(JobSchedulerStoreUsageTest.class); - final int WAIT_TIME_MILLS = 20*1000; + final int WAIT_TIME_MILLS = 20 * 1000; - @Override - protected BrokerService createBroker() throws Exception { - File schedulerDirectory = new File("target/scheduler"); + @Override + protected BrokerService createBroker() throws Exception { + File schedulerDirectory = new File("target/scheduler"); - IOHelper.mkdirs(schedulerDirectory); - IOHelper.deleteChildren(schedulerDirectory); + IOHelper.mkdirs(schedulerDirectory); + IOHelper.deleteChildren(schedulerDirectory); - BrokerService broker = super.createBroker(); - broker.setSchedulerSupport(true); - broker.setSchedulerDirectoryFile(schedulerDirectory); - broker.getSystemUsage().getJobSchedulerUsage().setLimit(7 * 1024); - broker.deleteAllMessages(); - return broker; - } + BrokerService broker = super.createBroker(); + broker.setSchedulerSupport(true); + broker.setSchedulerDirectoryFile(schedulerDirectory); + broker.getSystemUsage().getJobSchedulerUsage().setLimit(7 * 1024); + broker.deleteAllMessages(); + return broker; + } - @Override - protected boolean isPersistent() { - return true; - } + @Override + protected boolean isPersistent() { + return true; + } - public void testJmx() throws Exception { + public void testJmx() throws Exception { - LOG.info("Initial scheduler usage: {}", broker.getAdminView().getJobSchedulerStorePercentUsage()); + LOG.info("Initial scheduler usage: {}", broker.getAdminView().getJobSchedulerStorePercentUsage()); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - Connection conn = factory.createConnection(); - conn.start(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination dest = sess.createQueue(this.getClass().getName()); - final ProducerThread producer = new ProducerThread(sess, dest) { - @Override - protected Message createMessage(int i) throws Exception { - Message message = super.createMessage(i); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, WAIT_TIME_MILLS / 2); - return message; - } - }; - producer.setMessageCount(100); - producer.start(); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + Connection conn = factory.createConnection(); + conn.start(); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination dest = sess.createQueue(this.getClass().getName()); + final ProducerThread producer = new ProducerThread(sess, dest) { + @Override + protected Message createMessage(int i) throws Exception { + Message message = super.createMessage(i); + message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, WAIT_TIME_MILLS / 2); + return message; + } + }; + producer.setMessageCount(100); + producer.start(); - assertEquals(7 * 1024, broker.getAdminView().getJobSchedulerStoreLimit()); + assertEquals(7 * 1024, broker.getAdminView().getJobSchedulerStoreLimit()); - // wait for the producer to block - Thread.sleep(WAIT_TIME_MILLS / 2); + // wait for the producer to block + Thread.sleep(WAIT_TIME_MILLS / 2); - assertTrue(broker.getAdminView().getJobSchedulerStorePercentUsage() > 100); + assertTrue(broker.getAdminView().getJobSchedulerStorePercentUsage() > 100); - broker.getAdminView().setJobSchedulerStoreLimit(1024 * 1024 * 33); + broker.getAdminView().setJobSchedulerStoreLimit(1024 * 1024 * 33); - Thread.sleep(WAIT_TIME_MILLS); + Thread.sleep(WAIT_TIME_MILLS); - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return producer.getSentCount() == producer.getMessageCount(); - } - }, WAIT_TIME_MILLS * 2); + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return producer.getSentCount() == producer.getMessageCount(); + } + }, WAIT_TIME_MILLS * 2); - assertEquals("Producer didn't send all messages", producer.getMessageCount(), producer.getSentCount()); + assertEquals("Producer didn't send all messages", producer.getMessageCount(), producer.getSentCount()); - LOG.info("Final scheduler usage: {}", broker.getAdminView().getJobSchedulerStorePercentUsage()); + LOG.info("Final scheduler usage: {}", broker.getAdminView().getJobSchedulerStorePercentUsage()); - assertTrue(broker.getAdminView().getJobSchedulerStorePercentUsage() < 100); - } + assertTrue(broker.getAdminView().getJobSchedulerStorePercentUsage() < 100); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/StoreUsageLimitsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/StoreUsageLimitsTest.java index 80bb0a389e..49d95fd533 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/StoreUsageLimitsTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/StoreUsageLimitsTest.java @@ -28,48 +28,50 @@ import org.apache.activemq.broker.BrokerService; public class StoreUsageLimitsTest extends EmbeddedBrokerTestSupport { - final int WAIT_TIME_MILLS = 20 * 1000; - private static final String limitsLogLevel = "warn"; + final int WAIT_TIME_MILLS = 20 * 1000; + private static final String limitsLogLevel = "warn"; - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - broker.getSystemUsage().getMemoryUsage().setLimit(Long.MAX_VALUE); - broker.getSystemUsage().setCheckLimitsLogLevel(limitsLogLevel); - broker.deleteAllMessages(); - return broker; - } + @Override + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); + broker.getSystemUsage().getMemoryUsage().setLimit(Long.MAX_VALUE); + broker.getSystemUsage().setCheckLimitsLogLevel(limitsLogLevel); + broker.deleteAllMessages(); + return broker; + } - @Override - protected boolean isPersistent() { - return true; - } + @Override + protected boolean isPersistent() { + return true; + } - public void testCheckLimitsLogLevel() throws Exception { + public void testCheckLimitsLogLevel() throws Exception { - File file = new File("target/activemq-test.log"); - if (!file.exists()) { - fail("target/activemq-test.log was not created."); - } + File file = new File("target/activemq-test.log"); + if (!file.exists()) { + fail("target/activemq-test.log was not created."); + } - BufferedReader br = null; - boolean foundUsage = false; + BufferedReader br = null; + boolean foundUsage = false; - try { - br = new BufferedReader(new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8"))); - String line = null; - while ((line = br.readLine()) != null) { - if (line.contains(new String(Long.toString(Long.MAX_VALUE / (1024 * 1024)))) && line.contains(limitsLogLevel.toUpperCase())) { - foundUsage = true; - } + try { + br = new BufferedReader(new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8"))); + String line = null; + while ((line = br.readLine()) != null) { + if (line.contains(new String(Long.toString(Long.MAX_VALUE / (1024 * 1024)))) && line.contains(limitsLogLevel.toUpperCase())) { + foundUsage = true; } - } catch (Exception e) { - fail(e.getMessage()); - } finally { - br.close(); - } + } + } + catch (Exception e) { + fail(e.getMessage()); + } + finally { + br.close(); + } - if (!foundUsage) - fail("checkLimitsLogLevel message did not write to log target/activemq-test.log"); - } + if (!foundUsage) + fail("checkLimitsLogLevel message did not write to log target/activemq-test.log"); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/StoreUsageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/StoreUsageTest.java index 901a325b17..a29e2a125e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/StoreUsageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/StoreUsageTest.java @@ -29,43 +29,43 @@ import javax.jms.Session; public class StoreUsageTest extends EmbeddedBrokerTestSupport { - final int WAIT_TIME_MILLS = 20*1000; + final int WAIT_TIME_MILLS = 20 * 1000; - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - broker.getSystemUsage().getStoreUsage().setLimit(10 * 1024); - broker.deleteAllMessages(); - return broker; - } + @Override + protected BrokerService createBroker() throws Exception { + BrokerService broker = super.createBroker(); + broker.getSystemUsage().getStoreUsage().setLimit(10 * 1024); + broker.deleteAllMessages(); + return broker; + } - protected boolean isPersistent() { - return true; - } + protected boolean isPersistent() { + return true; + } - public void testJmx() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - Connection conn = factory.createConnection(); - conn.start(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination dest = sess.createQueue(this.getClass().getName()); - final ProducerThread producer = new ProducerThread(sess, dest); - producer.start(); + public void testJmx() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + Connection conn = factory.createConnection(); + conn.start(); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination dest = sess.createQueue(this.getClass().getName()); + final ProducerThread producer = new ProducerThread(sess, dest); + producer.start(); - // wait for the producer to block - Thread.sleep(WAIT_TIME_MILLS / 2); + // wait for the producer to block + Thread.sleep(WAIT_TIME_MILLS / 2); - broker.getAdminView().setStoreLimit(1024 * 1024); + broker.getAdminView().setStoreLimit(1024 * 1024); - Thread.sleep(WAIT_TIME_MILLS); + Thread.sleep(WAIT_TIME_MILLS); - Wait.waitFor(new Wait.Condition() { - public boolean isSatisified() throws Exception { - return producer.getSentCount() == producer.getMessageCount(); - } - }, WAIT_TIME_MILLS * 2); + Wait.waitFor(new Wait.Condition() { + public boolean isSatisified() throws Exception { + return producer.getSentCount() == producer.getMessageCount(); + } + }, WAIT_TIME_MILLS * 2); - assertEquals("Producer didn't send all messages", producer.getMessageCount(), producer.getSentCount()); + assertEquals("Producer didn't send all messages", producer.getMessageCount(), producer.getSentCount()); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AMQ2927Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AMQ2927Test.java index e2df753ec5..ec3d0a9d2e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AMQ2927Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AMQ2927Test.java @@ -24,112 +24,109 @@ import org.apache.activemq.util.MessageIdList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import javax.jms.MessageConsumer; import java.net.URI; - public class AMQ2927Test extends JmsMultipleBrokersTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(AMQ2927Test.class); + private static final Logger LOG = LoggerFactory.getLogger(AMQ2927Test.class); - ActiveMQQueue queue = new ActiveMQQueue("TEST"); + ActiveMQQueue queue = new ActiveMQQueue("TEST"); - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - BrokerService brokerA = createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=true&useJmx=false&deleteAllMessagesOnStartup=true")); - brokerA.setBrokerId("BrokerA"); - BrokerService brokerB = createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=true&useJmx=false&deleteAllMessagesOnStartup=true")); - brokerB.setBrokerId("BrokerB"); - NetworkConnector aTOb = bridgeBrokers(brokers.get("BrokerA").broker, brokers.get("BrokerB").broker, false, 2, true, true); - aTOb.addStaticallyIncludedDestination(queue); - NetworkConnector bTOa = bridgeBrokers(brokers.get("BrokerB").broker, brokers.get("BrokerA").broker, false, 2, true, true); - bTOa.addStaticallyIncludedDestination(queue); + @Override + public void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); + BrokerService brokerA = createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=true&useJmx=false&deleteAllMessagesOnStartup=true")); + brokerA.setBrokerId("BrokerA"); + BrokerService brokerB = createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=true&useJmx=false&deleteAllMessagesOnStartup=true")); + brokerB.setBrokerId("BrokerB"); + NetworkConnector aTOb = bridgeBrokers(brokers.get("BrokerA").broker, brokers.get("BrokerB").broker, false, 2, true, true); + aTOb.addStaticallyIncludedDestination(queue); + NetworkConnector bTOa = bridgeBrokers(brokers.get("BrokerB").broker, brokers.get("BrokerA").broker, false, 2, true, true); + bTOa.addStaticallyIncludedDestination(queue); - startAllBrokers(); - waitForBridgeFormation(); - - } + startAllBrokers(); + waitForBridgeFormation(); - public void testRestartSend() throws Exception { + } - Thread.sleep(1000); + public void testRestartSend() throws Exception { - LOG.info("restarting broker"); + Thread.sleep(1000); - restartBroker("BrokerA"); + LOG.info("restarting broker"); - Thread.sleep(5000); + restartBroker("BrokerA"); - LOG.info("sending message"); + Thread.sleep(5000); - sendMessages("BrokerA", queue, 1); + LOG.info("sending message"); - Thread.sleep(3000); + sendMessages("BrokerA", queue, 1); - LOG.info("consuming message"); + Thread.sleep(3000); - MessageConsumer consumerA = createConsumer("BrokerA", queue); - MessageConsumer consumerB = createConsumer("BrokerB", queue); + LOG.info("consuming message"); - Thread.sleep(1000); + MessageConsumer consumerA = createConsumer("BrokerA", queue); + MessageConsumer consumerB = createConsumer("BrokerB", queue); - MessageIdList messagesA = getConsumerMessages("BrokerA", consumerA); - MessageIdList messagesB = getConsumerMessages("BrokerB", consumerB); + Thread.sleep(1000); - LOG.info("consumerA = " + messagesA); - LOG.info("consumerB = " + messagesB); + MessageIdList messagesA = getConsumerMessages("BrokerA", consumerA); + MessageIdList messagesB = getConsumerMessages("BrokerB", consumerB); - messagesA.assertMessagesReceived(0); - messagesB.assertMessagesReceived(1); + LOG.info("consumerA = " + messagesA); + LOG.info("consumerB = " + messagesB); - } + messagesA.assertMessagesReceived(0); + messagesB.assertMessagesReceived(1); + } - public void testSendRestart() throws Exception { + public void testSendRestart() throws Exception { - Thread.sleep(1000); + Thread.sleep(1000); - LOG.info("sending message"); + LOG.info("sending message"); - sendMessages("BrokerA", queue, 1); + sendMessages("BrokerA", queue, 1); - Thread.sleep(3000); + Thread.sleep(3000); - LOG.info("restarting broker"); + LOG.info("restarting broker"); - restartBroker("BrokerA"); + restartBroker("BrokerA"); - Thread.sleep(5000); + Thread.sleep(5000); - LOG.info("consuming message"); + LOG.info("consuming message"); - MessageConsumer consumerA = createConsumer("BrokerA", queue); - MessageConsumer consumerB = createConsumer("BrokerB", queue); + MessageConsumer consumerA = createConsumer("BrokerA", queue); + MessageConsumer consumerB = createConsumer("BrokerB", queue); - Thread.sleep(1000); + Thread.sleep(1000); - MessageIdList messagesA = getConsumerMessages("BrokerA", consumerA); - MessageIdList messagesB = getConsumerMessages("BrokerB", consumerB); + MessageIdList messagesA = getConsumerMessages("BrokerA", consumerA); + MessageIdList messagesB = getConsumerMessages("BrokerB", consumerB); - LOG.info("consumerA = " + messagesA); - LOG.info("consumerB = " + messagesB); + LOG.info("consumerA = " + messagesA); + LOG.info("consumerB = " + messagesB); - messagesA.assertMessagesReceived(0); - messagesB.assertMessagesReceived(1); - } + messagesA.assertMessagesReceived(0); + messagesB.assertMessagesReceived(1); + } - protected void restartBroker(String brokerName) throws Exception { - destroyBroker("BrokerA"); - BrokerService broker = createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=true&useJmx=false")); - broker.setBrokerId("BrokerA"); - NetworkConnector aTOb = bridgeBrokers(brokers.get("BrokerA").broker, brokers.get("BrokerB").broker, false, 2, true, true); - aTOb.addStaticallyIncludedDestination(queue); - broker.start(); - broker.waitUntilStarted(); - waitForBridgeFormation(); - } + protected void restartBroker(String brokerName) throws Exception { + destroyBroker("BrokerA"); + BrokerService broker = createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=true&useJmx=false")); + broker.setBrokerId("BrokerA"); + NetworkConnector aTOb = bridgeBrokers(brokers.get("BrokerA").broker, brokers.get("BrokerB").broker, false, 2, true, true); + aTOb.addStaticallyIncludedDestination(queue); + broker.start(); + broker.waitUntilStarted(); + waitForBridgeFormation(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AMQStackOverFlowTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AMQStackOverFlowTest.java index 3803723f2a..4e0acbaeb7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AMQStackOverFlowTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AMQStackOverFlowTest.java @@ -41,108 +41,110 @@ import org.springframework.jms.core.MessageCreator; public class AMQStackOverFlowTest extends TestCase { - private static final String URL1 = "tcp://localhost:61616"; + private static final String URL1 = "tcp://localhost:61616"; - private static final String URL2 = "tcp://localhost:61617"; + private static final String URL2 = "tcp://localhost:61617"; - public void testStackOverflow() throws Exception { - BrokerService brokerService1 = null; - BrokerService brokerService2 = null; + public void testStackOverflow() throws Exception { + BrokerService brokerService1 = null; + BrokerService brokerService2 = null; - try { - brokerService1 = createBrokerService("broker1", URL1, URL2); - brokerService1.start(); - brokerService2 = createBrokerService("broker2", URL2, URL1); - brokerService2.start(); + try { + brokerService1 = createBrokerService("broker1", URL1, URL2); + brokerService1.start(); + brokerService2 = createBrokerService("broker2", URL2, URL1); + brokerService2.start(); - final ActiveMQConnectionFactory cf1 = new ActiveMQConnectionFactory(URL1); - cf1.setUseAsyncSend(false); + final ActiveMQConnectionFactory cf1 = new ActiveMQConnectionFactory(URL1); + cf1.setUseAsyncSend(false); - final ActiveMQConnectionFactory cf2 = new ActiveMQConnectionFactory(URL2); - cf2.setUseAsyncSend(false); + final ActiveMQConnectionFactory cf2 = new ActiveMQConnectionFactory(URL2); + cf2.setUseAsyncSend(false); - final JmsTemplate template1 = new JmsTemplate(cf1); - template1.setReceiveTimeout(10000); + final JmsTemplate template1 = new JmsTemplate(cf1); + template1.setReceiveTimeout(10000); - template1.send("test.q", new MessageCreator() { + template1.send("test.q", new MessageCreator() { - @Override - public Message createMessage(Session session) throws JMSException { - return session.createTextMessage("test"); - } + @Override + public Message createMessage(Session session) throws JMSException { + return session.createTextMessage("test"); + } - }); + }); - final JmsTemplate template2 = new JmsTemplate(cf2); - template2.setReceiveTimeout(10000); + final JmsTemplate template2 = new JmsTemplate(cf2); + template2.setReceiveTimeout(10000); - final Message m = template2.receive("test.q"); - assertTrue(m instanceof TextMessage); + final Message m = template2.receive("test.q"); + assertTrue(m instanceof TextMessage); - final TextMessage tm = (TextMessage)m; + final TextMessage tm = (TextMessage) m; - assertEquals("test", tm.getText()); + assertEquals("test", tm.getText()); - template2.send("test2.q", new MessageCreator() { + template2.send("test2.q", new MessageCreator() { - @Override - public Message createMessage(Session session) throws JMSException { - return session.createTextMessage("test2"); - } - }); + @Override + public Message createMessage(Session session) throws JMSException { + return session.createTextMessage("test2"); + } + }); - final Message m2 = template1.receive("test2.q"); - assertNotNull(m2); - assertTrue(m2 instanceof TextMessage); + final Message m2 = template1.receive("test2.q"); + assertNotNull(m2); + assertTrue(m2 instanceof TextMessage); - final TextMessage tm2 = (TextMessage)m2; + final TextMessage tm2 = (TextMessage) m2; - assertEquals("test2", tm2.getText()); + assertEquals("test2", tm2.getText()); - } finally { - brokerService1.stop(); - brokerService1 = null; - brokerService2.stop(); - brokerService2 = null; - } - } + } + finally { + brokerService1.stop(); + brokerService1 = null; + brokerService2.stop(); + brokerService2 = null; + } + } - private BrokerService createBrokerService(final String brokerName, final String uri1, final String uri2) - throws Exception { - final BrokerService brokerService = new BrokerService(); + private BrokerService createBrokerService(final String brokerName, + final String uri1, + final String uri2) throws Exception { + final BrokerService brokerService = new BrokerService(); - brokerService.setBrokerName(brokerName); - brokerService.setPersistent(false); - brokerService.setUseJmx(true); + brokerService.setBrokerName(brokerName); + brokerService.setPersistent(false); + brokerService.setUseJmx(true); - final SystemUsage memoryManager = new SystemUsage(); - //memoryManager.getMemoryUsage().setLimit(10); - brokerService.setSystemUsage(memoryManager); + final SystemUsage memoryManager = new SystemUsage(); + //memoryManager.getMemoryUsage().setLimit(10); + brokerService.setSystemUsage(memoryManager); - final List policyEntries = new ArrayList(); + final List policyEntries = new ArrayList(); - final PolicyEntry entry = new PolicyEntry(); - entry.setQueue(">"); - //entry.setMemoryLimit(1); - policyEntries.add(entry); + final PolicyEntry entry = new PolicyEntry(); + entry.setQueue(">"); + //entry.setMemoryLimit(1); + policyEntries.add(entry); - final PolicyMap policyMap = new PolicyMap(); - policyMap.setPolicyEntries(policyEntries); - brokerService.setDestinationPolicy(policyMap); + final PolicyMap policyMap = new PolicyMap(); + policyMap.setPolicyEntries(policyEntries); + brokerService.setDestinationPolicy(policyMap); - final TransportConnector tConnector = new TransportConnector(); - tConnector.setUri(new URI(uri1)); - tConnector.setName(brokerName + ".transportConnector"); - brokerService.addConnector(tConnector); + final TransportConnector tConnector = new TransportConnector(); + tConnector.setUri(new URI(uri1)); + tConnector.setName(brokerName + ".transportConnector"); + brokerService.addConnector(tConnector); - if (uri2 != null) { - final NetworkConnector nc = new DiscoveryNetworkConnector(new URI("static:" + uri2)); - nc.setBridgeTempDestinations(true); - nc.setBrokerName(brokerName); - //nc.setPrefetchSize(1); - brokerService.addNetworkConnector(nc); - } + if (uri2 != null) { + final NetworkConnector nc = new DiscoveryNetworkConnector(new URI("static:" + uri2)); + nc.setBridgeTempDestinations(true); + nc.setBrokerName(brokerName); + //nc.setPrefetchSize(1); + brokerService.addNetworkConnector(nc); + } - return brokerService; - } + return brokerService; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AbstractTwoBrokerNetworkConnectorWildcardIncludedDestinationTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AbstractTwoBrokerNetworkConnectorWildcardIncludedDestinationTestSupport.java index 7ccf5d10a3..47b43822aa 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AbstractTwoBrokerNetworkConnectorWildcardIncludedDestinationTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AbstractTwoBrokerNetworkConnectorWildcardIncludedDestinationTestSupport.java @@ -34,114 +34,121 @@ import org.apache.activemq.util.MessageIdList; public abstract class AbstractTwoBrokerNetworkConnectorWildcardIncludedDestinationTestSupport extends JmsMultipleBrokersTestSupport { - protected static final int MESSAGE_COUNT = 1; - boolean dynamicOnly = true; - int networkTTL = 1; - boolean conduit = true; - boolean suppressDuplicateQueueSubscriptions = true; - boolean decreaseNetworkConsumerPriority = true; + protected static final int MESSAGE_COUNT = 1; + boolean dynamicOnly = true; + int networkTTL = 1; + boolean conduit = true; + boolean suppressDuplicateQueueSubscriptions = true; + boolean decreaseNetworkConsumerPriority = true; - /** - * simple nwob - */ - public void testSimpleNWOB() throws Exception { + /** + * simple nwob + */ + public void testSimpleNWOB() throws Exception { - sendReceive("BrokerA", "local.test", false, "BrokerB", "local.test", false, 1, 0); - sendReceive("BrokerA", "local.test", true, "BrokerB", "local.test", true, 1, 0); - sendReceive("BrokerA", "global.test", false, "BrokerB", "global.test", false, 1, 1); - sendReceive("BrokerA", "global.test", true, "BrokerB", "global.test", true, 1, 1); + sendReceive("BrokerA", "local.test", false, "BrokerB", "local.test", false, 1, 0); + sendReceive("BrokerA", "local.test", true, "BrokerB", "local.test", true, 1, 0); + sendReceive("BrokerA", "global.test", false, "BrokerB", "global.test", false, 1, 1); + sendReceive("BrokerA", "global.test", true, "BrokerB", "global.test", true, 1, 1); - } + } - /** - * nwob with wild-card subscriptions - */ - public void testSimpleNWOBWithWildcardSubscriptions() throws Exception { + /** + * nwob with wild-card subscriptions + */ + public void testSimpleNWOBWithWildcardSubscriptions() throws Exception { - sendReceive("BrokerA", "local.test.1", false, "BrokerB", "local.test.>", false, 1, 0); - sendReceive("BrokerA", "local.test.2", true, "BrokerB", "local.test.>", true, 1, 0); - sendReceive("BrokerA", "global.test.1", false, "BrokerB", "global.test.>", false, 1, 1); - sendReceive("BrokerA", "global.test.2", true, "BrokerB", "global.test.>", true, 1, 1); + sendReceive("BrokerA", "local.test.1", false, "BrokerB", "local.test.>", false, 1, 0); + sendReceive("BrokerA", "local.test.2", true, "BrokerB", "local.test.>", true, 1, 0); + sendReceive("BrokerA", "global.test.1", false, "BrokerB", "global.test.>", false, 1, 1); + sendReceive("BrokerA", "global.test.2", true, "BrokerB", "global.test.>", true, 1, 1); - } + } - /** - * nwob with virtual destinations - */ - public void testSimpleNWOBWithVirtualDestinations() throws Exception { + /** + * nwob with virtual destinations + */ + public void testSimpleNWOBWithVirtualDestinations() throws Exception { - sendReceive("BrokerA", "local.test", true, "BrokerB", "Consumer.a.local.test", false, 1, 0); - sendReceive("BrokerA", "global.test", true, "BrokerB", "Consumer.a.global.test", false, 1, 1); + sendReceive("BrokerA", "local.test", true, "BrokerB", "Consumer.a.local.test", false, 1, 0); + sendReceive("BrokerA", "global.test", true, "BrokerB", "Consumer.a.global.test", false, 1, 1); - } + } - /** - * nwob with virtual destinations and wild-card subscriptions - */ - public void testSimpleNWOBWithVirtualDestinationsAndWildcardSubscriptions() throws Exception { + /** + * nwob with virtual destinations and wild-card subscriptions + */ + public void testSimpleNWOBWithVirtualDestinationsAndWildcardSubscriptions() throws Exception { - sendReceive("BrokerA", "local.test.1", true, "BrokerB", "Consumer.a.local.test.>", false, 1, 0); - sendReceive("BrokerA", "global.test.1", true, "BrokerB", "Consumer.a.global.test.>", false, 1, 1); + sendReceive("BrokerA", "local.test.1", true, "BrokerB", "Consumer.a.local.test.>", false, 1, 0); + sendReceive("BrokerA", "global.test.1", true, "BrokerB", "Consumer.a.global.test.>", false, 1, 1); - } + } - public void sendReceive(String broker1, String dest1, boolean topic1, String broker2, String dest2, boolean topic2, int send, int expected) throws Exception{ - MessageConsumer client = createConsumer(broker2, createDestination(dest2, topic2)); - Thread.sleep(2000); - sendMessages(broker1, createDestination(dest1, topic1), send); - MessageIdList msgs = getConsumerMessages(broker2, client); - msgs.setMaximumDuration(10000); - msgs.waitForMessagesToArrive(send); - assertEquals(expected, msgs.getMessageCount()); - client.close(); - Thread.sleep(1000); - } + public void sendReceive(String broker1, + String dest1, + boolean topic1, + String broker2, + String dest2, + boolean topic2, + int send, + int expected) throws Exception { + MessageConsumer client = createConsumer(broker2, createDestination(dest2, topic2)); + Thread.sleep(2000); + sendMessages(broker1, createDestination(dest1, topic1), send); + MessageIdList msgs = getConsumerMessages(broker2, client); + msgs.setMaximumDuration(10000); + msgs.waitForMessagesToArrive(send); + assertEquals(expected, msgs.getMessageCount()); + client.close(); + Thread.sleep(1000); + } - protected abstract void addIncludedDestination(NetworkConnector networkConnector); + protected abstract void addIncludedDestination(NetworkConnector networkConnector); - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - String options = new String("?useJmx=false&deleteAllMessagesOnStartup=true"); - createAndConfigureBroker(new URI("broker:(tcp://localhost:61616)/BrokerA" + options)); - createAndConfigureBroker(new URI("broker:(tcp://localhost:61617)/BrokerB" + options)); + @Override + public void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); + String options = new String("?useJmx=false&deleteAllMessagesOnStartup=true"); + createAndConfigureBroker(new URI("broker:(tcp://localhost:61616)/BrokerA" + options)); + createAndConfigureBroker(new URI("broker:(tcp://localhost:61617)/BrokerB" + options)); - // Setup broker networks - NetworkConnector nc = bridgeBrokers("BrokerA", "BrokerB", dynamicOnly, networkTTL, conduit); - nc.setDecreaseNetworkConsumerPriority(decreaseNetworkConsumerPriority); - nc.setSuppressDuplicateQueueSubscriptions(suppressDuplicateQueueSubscriptions); + // Setup broker networks + NetworkConnector nc = bridgeBrokers("BrokerA", "BrokerB", dynamicOnly, networkTTL, conduit); + nc.setDecreaseNetworkConsumerPriority(decreaseNetworkConsumerPriority); + nc.setSuppressDuplicateQueueSubscriptions(suppressDuplicateQueueSubscriptions); - addIncludedDestination(nc); + addIncludedDestination(nc); - nc = bridgeBrokers("BrokerB", "BrokerA", dynamicOnly, networkTTL, conduit); - nc.setDecreaseNetworkConsumerPriority(decreaseNetworkConsumerPriority); - nc.setSuppressDuplicateQueueSubscriptions(suppressDuplicateQueueSubscriptions); + nc = bridgeBrokers("BrokerB", "BrokerA", dynamicOnly, networkTTL, conduit); + nc.setDecreaseNetworkConsumerPriority(decreaseNetworkConsumerPriority); + nc.setSuppressDuplicateQueueSubscriptions(suppressDuplicateQueueSubscriptions); - addIncludedDestination(nc); + addIncludedDestination(nc); - startAllBrokers(); + startAllBrokers(); - } + } - private BrokerService createAndConfigureBroker(URI uri) throws Exception { - BrokerService broker = createBroker(uri); + private BrokerService createAndConfigureBroker(URI uri) throws Exception { + BrokerService broker = createBroker(uri); - configurePersistenceAdapter(broker); + configurePersistenceAdapter(broker); - // make all topics virtual and consumers use the default prefix - VirtualDestinationInterceptor virtualDestinationInterceptor = new VirtualDestinationInterceptor(); - virtualDestinationInterceptor.setVirtualDestinations(new VirtualDestination[]{new VirtualTopic()}); - DestinationInterceptor[] destinationInterceptors = new DestinationInterceptor[]{virtualDestinationInterceptor}; - broker.setDestinationInterceptors(destinationInterceptors); - return broker; - } + // make all topics virtual and consumers use the default prefix + VirtualDestinationInterceptor virtualDestinationInterceptor = new VirtualDestinationInterceptor(); + virtualDestinationInterceptor.setVirtualDestinations(new VirtualDestination[]{new VirtualTopic()}); + DestinationInterceptor[] destinationInterceptors = new DestinationInterceptor[]{virtualDestinationInterceptor}; + broker.setDestinationInterceptors(destinationInterceptors); + return broker; + } - protected void configurePersistenceAdapter(BrokerService broker) throws IOException { - File dataFileDir = new File("target/test-amq-data/kahadb/" + broker.getBrokerName()); - KahaDBStore kaha = new KahaDBStore(); - kaha.setDirectory(dataFileDir); - broker.setPersistenceAdapter(kaha); - } + protected void configurePersistenceAdapter(BrokerService broker) throws IOException { + File dataFileDir = new File("target/test-amq-data/kahadb/" + broker.getBrokerName()); + KahaDBStore kaha = new KahaDBStore(); + kaha.setDirectory(dataFileDir); + broker.setPersistenceAdapter(kaha); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AdvisoryTopicCleanUpTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AdvisoryTopicCleanUpTest.java index 2d279636be..fc424889c2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AdvisoryTopicCleanUpTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AdvisoryTopicCleanUpTest.java @@ -35,128 +35,126 @@ import javax.jms.*; public class AdvisoryTopicCleanUpTest { - private static final Logger LOG = LoggerFactory.getLogger(AdvisoryTopicCleanUpTest.class); + private static final Logger LOG = LoggerFactory.getLogger(AdvisoryTopicCleanUpTest.class); - private BrokerService broker; - private String connectionUri; + private BrokerService broker; + private String connectionUri; - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(connectionUri + "?jms.redeliveryPolicy.maximumRedeliveries=2"); - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory(connectionUri + "?jms.redeliveryPolicy.maximumRedeliveries=2"); + } - @Before - public void setUp() throws Exception { - createBroker(); - } + @Before + public void setUp() throws Exception { + createBroker(); + } - @After - public void tearDown() throws Exception { - destroyBroker(); - } + @After + public void tearDown() throws Exception { + destroyBroker(); + } - private void createBroker() throws Exception { - broker = new BrokerService(); - broker.setPersistent(false); - broker.setDeleteAllMessagesOnStartup(true); - broker.setUseJmx(true); - connectionUri = broker.addConnector("tcp://localhost:0").getPublishableConnectString(); + private void createBroker() throws Exception { + broker = new BrokerService(); + broker.setPersistent(false); + broker.setDeleteAllMessagesOnStartup(true); + broker.setUseJmx(true); + connectionUri = broker.addConnector("tcp://localhost:0").getPublishableConnectString(); - PolicyEntry policy = new PolicyEntry(); - policy.setAdvisoryForFastProducers(true); - policy.setAdvisoryForConsumed(true); - policy.setAdvisoryForDelivery(true); - policy.setAdvisoryForDiscardingMessages(true); - policy.setAdvisoryForSlowConsumers(true); - policy.setAdvisoryWhenFull(true); - policy.setProducerFlowControl(false); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - broker.setDestinationPolicy(pMap); + PolicyEntry policy = new PolicyEntry(); + policy.setAdvisoryForFastProducers(true); + policy.setAdvisoryForConsumed(true); + policy.setAdvisoryForDelivery(true); + policy.setAdvisoryForDiscardingMessages(true); + policy.setAdvisoryForSlowConsumers(true); + policy.setAdvisoryWhenFull(true); + policy.setProducerFlowControl(false); + PolicyMap pMap = new PolicyMap(); + pMap.setDefaultEntry(policy); + broker.setDestinationPolicy(pMap); - broker.start(); - } + broker.start(); + } - protected Connection createConnection() throws Exception { - Connection con = createConnectionFactory().createConnection(); - con.start(); - return con; - } + protected Connection createConnection() throws Exception { + Connection con = createConnectionFactory().createConnection(); + con.start(); + return con; + } - private void destroyBroker() throws Exception { - if (broker != null) - broker.stop(); - } + private void destroyBroker() throws Exception { + if (broker != null) + broker.stop(); + } - @Test - public void testAdvisoryTopic() throws Exception { - Connection connection = createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination queue = (ActiveMQDestination) session.createQueue("AdvisoryTopicCleanUpTestQueue"); - MessageProducer prod = session.createProducer(queue); - Message message = session.createMessage(); - prod.send(message); - message = session.createMessage(); - prod.send(message); - message = session.createMessage(); - prod.send(message, Message.DEFAULT_DELIVERY_MODE, Message.DEFAULT_PRIORITY, 1000); - connection.close(); - connection = createConnection(); + @Test + public void testAdvisoryTopic() throws Exception { + Connection connection = createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQDestination queue = (ActiveMQDestination) session.createQueue("AdvisoryTopicCleanUpTestQueue"); + MessageProducer prod = session.createProducer(queue); + Message message = session.createMessage(); + prod.send(message); + message = session.createMessage(); + prod.send(message); + message = session.createMessage(); + prod.send(message, Message.DEFAULT_DELIVERY_MODE, Message.DEFAULT_PRIORITY, 1000); + connection.close(); + connection = createConnection(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(queue); - message = consumer.receive(60 * 1000); - message.acknowledge(); - connection.close(); - connection = null; + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(queue); + message = consumer.receive(60 * 1000); + message.acknowledge(); + connection.close(); + connection = null; - for (int i = 0; i < 2; i++) { - connection = createConnection(); - session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); - consumer = session.createConsumer(queue); - message = consumer.receive(60 * 1000); - session.rollback(); - connection.close(); - connection = null; - } + for (int i = 0; i < 2; i++) { + connection = createConnection(); + session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); + consumer = session.createConsumer(queue); + message = consumer.receive(60 * 1000); + session.rollback(); + connection.close(); + connection = null; + } - Thread.sleep(2 * 1000); + Thread.sleep(2 * 1000); - connection = createConnection(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - consumer = session.createConsumer(queue); - message = consumer.receive(1000); - if (message != null) - message.acknowledge(); - connection.close(); - connection = null; + connection = createConnection(); + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + consumer = session.createConsumer(queue); + message = consumer.receive(1000); + if (message != null) + message.acknowledge(); + connection.close(); + connection = null; - TimeUnit.SECONDS.sleep(1); + TimeUnit.SECONDS.sleep(1); - ActiveMQDestination dests[] = broker.getRegionBroker().getDestinations(); + ActiveMQDestination dests[] = broker.getRegionBroker().getDestinations(); - for (ActiveMQDestination destination: dests) { + for (ActiveMQDestination destination : dests) { + String name = destination.getPhysicalName(); + if (name.contains(queue.getPhysicalName())) { + LOG.info("Destination on Broker before removing the Queue: " + name); + } + } + + dests = broker.getRegionBroker().getDestinations(); + if (dests == null) { + fail("Should have Destination for: " + queue.getPhysicalName()); + } + + broker.getAdminView().removeQueue(queue.getPhysicalName()); + + dests = broker.getRegionBroker().getDestinations(); + if (dests != null) { + for (ActiveMQDestination destination : dests) { String name = destination.getPhysicalName(); - if (name.contains(queue.getPhysicalName())) { - LOG.info("Destination on Broker before removing the Queue: " + name); - } - } - - dests = broker.getRegionBroker().getDestinations(); - if (dests == null) { - fail("Should have Destination for: " + queue.getPhysicalName()); - } - - broker.getAdminView().removeQueue(queue.getPhysicalName()); - - dests = broker.getRegionBroker().getDestinations(); - if (dests != null) - { - for (ActiveMQDestination destination: dests) { - String name = destination.getPhysicalName(); - LOG.info("Destination on broker after removing the Queue: " + name); - assertFalse("Advisory topic should not exist. " + name, - name.startsWith("ActiveMQ.Advisory") && name.contains(queue.getPhysicalName())); - } - } - } + LOG.info("Destination on broker after removing the Queue: " + name); + assertFalse("Advisory topic should not exist. " + name, name.startsWith("ActiveMQ.Advisory") && name.contains(queue.getPhysicalName())); + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AdvisoryTopicDeletionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AdvisoryTopicDeletionTest.java index d84ad1871e..6e8c8bf1d8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AdvisoryTopicDeletionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AdvisoryTopicDeletionTest.java @@ -32,94 +32,96 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AdvisoryTopicDeletionTest extends TestSupport { - private static final Logger LOG = LoggerFactory.getLogger(AdvisoryTopicDeletionTest.class); - private BrokerService broker; - private Connection connection; + private static final Logger LOG = LoggerFactory.getLogger(AdvisoryTopicDeletionTest.class); - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://" + getName()); - } + private BrokerService broker; + private Connection connection; - @Override - protected void setUp() throws Exception { - createBroker(); - topic = false; - super.setUp(); - } + @Override + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory("vm://" + getName()); + } - @Override - protected void tearDown() throws Exception { - super.tearDown(); - destroyBroker(); - } + @Override + protected void setUp() throws Exception { + createBroker(); + topic = false; + super.setUp(); + } - private void createBroker() throws Exception { - broker = BrokerFactory.createBroker("broker:(vm://localhost)"); - broker.setPersistent(false); - broker.setBrokerName(getName()); - broker.start(); + @Override + protected void tearDown() throws Exception { + super.tearDown(); + destroyBroker(); + } - connection = createConnection(); - } + private void createBroker() throws Exception { + broker = BrokerFactory.createBroker("broker:(vm://localhost)"); + broker.setPersistent(false); + broker.setBrokerName(getName()); + broker.start(); - @Override - protected Connection createConnection() throws Exception { - Connection con = super.createConnection(); - con.start(); - return con; - } + connection = createConnection(); + } - private void destroyBroker() throws Exception { - if (connection != null) - connection.close(); - if (broker != null) - broker.stop(); - } + @Override + protected Connection createConnection() throws Exception { + Connection con = super.createConnection(); + con.start(); + return con; + } - public void doTest() throws Exception { - Destination dest = createDestination(); + private void destroyBroker() throws Exception { + if (connection != null) + connection.close(); + if (broker != null) + broker.stop(); + } - Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + public void doTest() throws Exception { + Destination dest = createDestination(); - MessageConsumer consumer = consumerSession.createConsumer(dest); + Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer prod = producerSession.createProducer(dest); - Message message = producerSession.createMessage(); - prod.send(message); + MessageConsumer consumer = consumerSession.createConsumer(dest); - consumer.receive(60 * 1000); - connection.close(); - connection = null; + MessageProducer prod = producerSession.createProducer(dest); + Message message = producerSession.createMessage(); + prod.send(message); - if ( topic ) { - broker.getAdminView().removeTopic(((ActiveMQDestination)dest).getPhysicalName()); - } else { - broker.getAdminView().removeQueue(((ActiveMQDestination)dest).getPhysicalName()); - } + consumer.receive(60 * 1000); + connection.close(); + connection = null; - ActiveMQDestination dests[] = broker.getRegionBroker().getDestinations(); - int matchingDestinations = 0; - for (ActiveMQDestination destination: dests) { - String name = destination.getPhysicalName(); - LOG.debug("Found destination " + name); - if (name.startsWith("ActiveMQ.Advisory") && name.contains(getDestinationString())) { - matchingDestinations++; - } - } + if (topic) { + broker.getAdminView().removeTopic(((ActiveMQDestination) dest).getPhysicalName()); + } + else { + broker.getAdminView().removeQueue(((ActiveMQDestination) dest).getPhysicalName()); + } - assertEquals("No matching destinations should be found", 0, matchingDestinations); - } + ActiveMQDestination dests[] = broker.getRegionBroker().getDestinations(); + int matchingDestinations = 0; + for (ActiveMQDestination destination : dests) { + String name = destination.getPhysicalName(); + LOG.debug("Found destination " + name); + if (name.startsWith("ActiveMQ.Advisory") && name.contains(getDestinationString())) { + matchingDestinations++; + } + } - public void testTopic() throws Exception { - topic=true; - doTest(); - } + assertEquals("No matching destinations should be found", 0, matchingDestinations); + } - public void testQueue() throws Exception { - topic=false; - doTest(); - } + public void testTopic() throws Exception { + topic = true; + doTest(); + } + + public void testQueue() throws Exception { + topic = false; + doTest(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AuthorizationFromAdminViewTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AuthorizationFromAdminViewTest.java index 33651cb03c..a9cd448686 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AuthorizationFromAdminViewTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AuthorizationFromAdminViewTest.java @@ -25,41 +25,41 @@ import org.apache.activemq.security.SimpleAuthorizationMap; public class AuthorizationFromAdminViewTest extends org.apache.activemq.TestSupport { - private BrokerService broker; + private BrokerService broker; - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://" + getName()); - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory("vm://" + getName()); + } - protected void setUp() throws Exception { - createBroker(); - super.setUp(); - } + protected void setUp() throws Exception { + createBroker(); + super.setUp(); + } - protected void tearDown() throws Exception { - super.tearDown(); - destroyBroker(); - } + protected void tearDown() throws Exception { + super.tearDown(); + destroyBroker(); + } - private void createBroker() throws Exception { - broker = BrokerFactory.createBroker("broker:(vm://localhost)"); - broker.setPersistent(false); - broker.setBrokerName(getName()); + private void createBroker() throws Exception { + broker = BrokerFactory.createBroker("broker:(vm://localhost)"); + broker.setPersistent(false); + broker.setBrokerName(getName()); - AuthorizationPlugin plugin = new AuthorizationPlugin(); - plugin.setMap(new SimpleAuthorizationMap()); - BrokerPlugin[] plugins = new BrokerPlugin[] {plugin}; - broker.setPlugins(plugins); + AuthorizationPlugin plugin = new AuthorizationPlugin(); + plugin.setMap(new SimpleAuthorizationMap()); + BrokerPlugin[] plugins = new BrokerPlugin[]{plugin}; + broker.setPlugins(plugins); - broker.start(); - } + broker.start(); + } - private void destroyBroker() throws Exception { - if (broker != null) - broker.stop(); - } + private void destroyBroker() throws Exception { + if (broker != null) + broker.stop(); + } - public void testAuthorizationFromAdminView() throws Exception { - broker.getAdminView().addQueue(getDestinationString()); - } + public void testAuthorizationFromAdminView() throws Exception { + broker.getAdminView().addQueue(getDestinationString()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BacklogNetworkCrossTalkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BacklogNetworkCrossTalkTest.java index b56c5b0134..6ae2acddd7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BacklogNetworkCrossTalkTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BacklogNetworkCrossTalkTest.java @@ -18,6 +18,7 @@ package org.apache.activemq.usecases; import java.net.URI; import javax.jms.MessageConsumer; + import org.apache.activemq.JmsMultipleBrokersTestSupport; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.command.ActiveMQDestination; @@ -27,70 +28,68 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BacklogNetworkCrossTalkTest extends JmsMultipleBrokersTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(BacklogNetworkCrossTalkTest.class); - protected BrokerService createBroker(String brokerName) throws Exception { - BrokerService broker = new BrokerService(); - broker.setDeleteAllMessagesOnStartup(true); - broker.setPersistent(true); - broker.setUseJmx(false); - broker.setBrokerName(brokerName); - broker.addConnector(new URI(AUTO_ASSIGN_TRANSPORT)); - brokers.put(brokerName, new BrokerItem(broker)); + private static final Logger LOG = LoggerFactory.getLogger(BacklogNetworkCrossTalkTest.class); - return broker; - } + protected BrokerService createBroker(String brokerName) throws Exception { + BrokerService broker = new BrokerService(); + broker.setDeleteAllMessagesOnStartup(true); + broker.setPersistent(true); + broker.setUseJmx(false); + broker.setBrokerName(brokerName); + broker.addConnector(new URI(AUTO_ASSIGN_TRANSPORT)); + brokers.put(brokerName, new BrokerItem(broker)); - public void testProduceConsume() throws Exception { - createBroker("A"); - createBroker("B"); + return broker; + } - NetworkConnector nc = bridgeBrokers("A", "B"); - nc.setDuplex(true); - nc.setDispatchAsync(false); - startAllBrokers(); + public void testProduceConsume() throws Exception { + createBroker("A"); + createBroker("B"); - waitForBridgeFormation(); + NetworkConnector nc = bridgeBrokers("A", "B"); + nc.setDuplex(true); + nc.setDispatchAsync(false); + startAllBrokers(); - final int numMessages = 10000; - // Create queue - ActiveMQDestination destA = createDestination("AAA", false); - sendMessages("A", destA, numMessages); + waitForBridgeFormation(); - ActiveMQDestination destB = createDestination("BBB", false); - sendMessages("B", destB, numMessages); + final int numMessages = 10000; + // Create queue + ActiveMQDestination destA = createDestination("AAA", false); + sendMessages("A", destA, numMessages); - // consume across network - LOG.info("starting consumers.."); + ActiveMQDestination destB = createDestination("BBB", false); + sendMessages("B", destB, numMessages); - // Setup consumers - MessageConsumer clientA = createConsumer("A", destB); - // Setup consumers - MessageConsumer clientB = createConsumer("B", destA); + // consume across network + LOG.info("starting consumers.."); + // Setup consumers + MessageConsumer clientA = createConsumer("A", destB); + // Setup consumers + MessageConsumer clientB = createConsumer("B", destA); - final long maxWait = 5 * 60 * 1000L; - MessageIdList listA = getConsumerMessages("A", clientA); - listA.setMaximumDuration(maxWait); - listA.waitForMessagesToArrive(numMessages); + final long maxWait = 5 * 60 * 1000L; + MessageIdList listA = getConsumerMessages("A", clientA); + listA.setMaximumDuration(maxWait); + listA.waitForMessagesToArrive(numMessages); - MessageIdList listB = getConsumerMessages("B", clientB); - listB.setMaximumDuration(maxWait); - listB.waitForMessagesToArrive(numMessages); + MessageIdList listB = getConsumerMessages("B", clientB); + listB.setMaximumDuration(maxWait); + listB.waitForMessagesToArrive(numMessages); - assertEquals("got all on A" + listA.getMessageCount(), - numMessages, listA.getMessageCount()); + assertEquals("got all on A" + listA.getMessageCount(), numMessages, listA.getMessageCount()); - assertEquals("got all on B" + listB.getMessageCount(), - numMessages, listB.getMessageCount()); + assertEquals("got all on B" + listB.getMessageCount(), numMessages, listB.getMessageCount()); - } + } - @Override - public void setUp() throws Exception { - messageSize = 5000; - super.setMaxTestTime(10*60*1000); - super.setAutoFail(true); - super.setUp(); - } + @Override + public void setUp() throws Exception { + messageSize = 5000; + super.setMaxTestTime(10 * 60 * 1000); + super.setAutoFail(true); + super.setUp(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BatchedMessagePriorityConsumerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BatchedMessagePriorityConsumerTest.java index 16e2ac2530..67401416fc 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BatchedMessagePriorityConsumerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BatchedMessagePriorityConsumerTest.java @@ -20,6 +20,7 @@ import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; + import org.apache.activemq.JmsTestSupport; import org.apache.activemq.command.ActiveMQDestination; import org.slf4j.Logger; @@ -27,55 +28,54 @@ import org.slf4j.LoggerFactory; public class BatchedMessagePriorityConsumerTest extends JmsTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(BatchedMessagePriorityConsumerTest.class); + private static final Logger LOG = LoggerFactory.getLogger(BatchedMessagePriorityConsumerTest.class); - public void testBatchWithLowPriorityFirstAndClientSupport() throws Exception { - doTestBatchWithLowPriorityFirst(true); - } + public void testBatchWithLowPriorityFirstAndClientSupport() throws Exception { + doTestBatchWithLowPriorityFirst(true); + } - public void testBatchWithLowPriorityFirstAndClientSupportOff() throws Exception { - doTestBatchWithLowPriorityFirst(false); - } + public void testBatchWithLowPriorityFirstAndClientSupportOff() throws Exception { + doTestBatchWithLowPriorityFirst(false); + } - public void doTestBatchWithLowPriorityFirst(boolean clientPrioritySupport) throws Exception { + public void doTestBatchWithLowPriorityFirst(boolean clientPrioritySupport) throws Exception { - connection.start(); - connection.setMessagePrioritySupported(clientPrioritySupport); + connection.start(); + connection.setMessagePrioritySupported(clientPrioritySupport); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); + MessageProducer producer = session.createProducer(destination); + producer.setPriority(0); + sendMessages(session, producer, 2); + producer.close(); - MessageProducer producer = session.createProducer(destination); - producer.setPriority(0); - sendMessages(session, producer, 2); - producer.close(); + MessageProducer producer2 = session.createProducer(destination); + producer2.setPriority(9); + sendMessages(session, producer2, 3); + producer2.close(); - MessageProducer producer2 = session.createProducer(destination); - producer2.setPriority(9); - sendMessages(session, producer2, 3); - producer2.close(); + session.close(); - session.close(); + Session consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageConsumer messageConsumer = consumerSession.createConsumer(destination); - Session consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageConsumer messageConsumer = consumerSession.createConsumer(destination); + for (int i = 0; i < 5; i++) { + Message message = messageConsumer.receive(4000); + LOG.info("MessageID: " + message.getJMSMessageID()); + } - for (int i = 0; i < 5; i++) { - Message message = messageConsumer.receive(4000); - LOG.info("MessageID: " + message.getJMSMessageID()); - } + consumerSession.commit(); + consumerSession.close(); - consumerSession.commit(); - consumerSession.close(); + // should be nothing left + consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + messageConsumer = consumerSession.createConsumer(destination); - // should be nothing left - consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - messageConsumer = consumerSession.createConsumer(destination); + assertNull("No message left", messageConsumer.receive(1000)); - assertNull("No message left", messageConsumer.receive(1000)); + consumerSession.close(); - consumerSession.close(); - - } + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BrokerQueueNetworkWithDisconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BrokerQueueNetworkWithDisconnectTest.java index 5841b2b1b5..642379fed8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BrokerQueueNetworkWithDisconnectTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BrokerQueueNetworkWithDisconnectTest.java @@ -42,218 +42,230 @@ import org.apache.activemq.util.Wait; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - public class BrokerQueueNetworkWithDisconnectTest extends JmsMultipleBrokersTestSupport { - private static final Log LOG = LogFactory.getLog(BrokerQueueNetworkWithDisconnectTest.class); - private static final int NETWORK_DOWN_TIME = 5000; - protected static final int MESSAGE_COUNT = 200; - private static final String HUB = "HubBroker"; - private static final String SPOKE = "SpokeBroker"; - private SocketProxy socketProxy; - private long networkDownTimeStart; - public boolean useDuplexNetworkBridge = true; - public boolean simulateStalledNetwork; - private long inactiveDuration = 1000; - private boolean useSocketProxy = true; - public void initCombosForTestSendOnAReceiveOnBWithTransportDisconnect() { - addCombinationValues( "useDuplexNetworkBridge", new Object[]{ Boolean.TRUE, Boolean.FALSE} ); - addCombinationValues( "simulateStalledNetwork", new Object[]{ Boolean.TRUE } ); - } + private static final Log LOG = LogFactory.getLog(BrokerQueueNetworkWithDisconnectTest.class); + private static final int NETWORK_DOWN_TIME = 5000; + protected static final int MESSAGE_COUNT = 200; + private static final String HUB = "HubBroker"; + private static final String SPOKE = "SpokeBroker"; + private SocketProxy socketProxy; + private long networkDownTimeStart; + public boolean useDuplexNetworkBridge = true; + public boolean simulateStalledNetwork; + private long inactiveDuration = 1000; + private boolean useSocketProxy = true; - public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception { - bridgeBrokers(SPOKE, HUB); + public void initCombosForTestSendOnAReceiveOnBWithTransportDisconnect() { + addCombinationValues("useDuplexNetworkBridge", new Object[]{Boolean.TRUE, Boolean.FALSE}); + addCombinationValues("simulateStalledNetwork", new Object[]{Boolean.TRUE}); + } - startAllBrokers(); + public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception { + bridgeBrokers(SPOKE, HUB); - // Setup destination - Destination dest = createDestination("TEST.FOO", false); + startAllBrokers(); - // Setup consumers - MessageConsumer client = createConsumer(HUB, dest); + // Setup destination + Destination dest = createDestination("TEST.FOO", false); - // allow subscription information to flow back to Spoke - sleep(600); + // Setup consumers + MessageConsumer client = createConsumer(HUB, dest); - // Send messages - sendMessages(SPOKE, dest, MESSAGE_COUNT); + // allow subscription information to flow back to Spoke + sleep(600); - MessageIdList msgs = getConsumerMessages(HUB, client); - msgs.waitForMessagesToArrive(MESSAGE_COUNT); + // Send messages + sendMessages(SPOKE, dest, MESSAGE_COUNT); - assertTrue("At least message " + MESSAGE_COUNT + - " must be received, duplicates are expected, count=" + msgs.getMessageCount(), - MESSAGE_COUNT <= msgs.getMessageCount()); - } + MessageIdList msgs = getConsumerMessages(HUB, client); + msgs.waitForMessagesToArrive(MESSAGE_COUNT); - @SuppressWarnings("unchecked") - public void testNoStuckConnectionsWithTransportDisconnect() throws Exception { - inactiveDuration=60000L; - useDuplexNetworkBridge = true; + assertTrue("At least message " + MESSAGE_COUNT + + " must be received, duplicates are expected, count=" + msgs.getMessageCount(), MESSAGE_COUNT <= msgs.getMessageCount()); + } - bridgeBrokers(SPOKE, HUB); + @SuppressWarnings("unchecked") + public void testNoStuckConnectionsWithTransportDisconnect() throws Exception { + inactiveDuration = 60000L; + useDuplexNetworkBridge = true; - final BrokerItem hub = brokers.get(HUB); - hub.broker.setPlugins(new BrokerPlugin[]{ - new BrokerPluginSupport() { - int sleepCount = 2; - @Override - public void removeConnection(ConnectionContext context, - ConnectionInfo info, Throwable error) - throws Exception { - try { - while(--sleepCount >= 0) { - LOG.info("sleeping for a bit in close impl to simulate load where reconnect fails due to a pending close"); - TimeUnit.SECONDS.sleep(2); - } - } catch (Exception ignored) {} - super.removeConnection(context, info, error); - } - } - }); - startAllBrokers(); - waitForBridgeFormation(); + bridgeBrokers(SPOKE, HUB); - // kill the initiator side, leaving remote end intact - // simulate async network breakage - // remote side will need to spot duplicate network and stop/kill the original - for (int i=0; i< 3; i++) { - socketProxy.halfClose(); - sleep(10000); - } - // wait for full reformation of bridge - // verify no extra connections - boolean allGood = Wait.waitFor(new Wait.Condition(){ - @Override - public boolean isSatisified() throws Exception { - long numConnections = hub.broker.getTransportConnectors().get(0).getConnections().size(); - LOG.info("Num connetions:" + numConnections); - return numConnections == 1; - }}); - if (!allGood) { - dumpAllThreads("ExtraHubConnection"); - } - assertTrue("should be only one transport connection for the single duplex network connector", allGood); + final BrokerItem hub = brokers.get(HUB); + hub.broker.setPlugins(new BrokerPlugin[]{new BrokerPluginSupport() { + int sleepCount = 2; - allGood = Wait.waitFor(new Wait.Condition(){ - @Override - public boolean isSatisified() throws Exception { - long numVmConnections = VMTransportFactory.SERVERS.get(HUB).getConnectionCount(); - LOG.info("Num VM connetions:" + numVmConnections); - return numVmConnections == 2; - }}); - if (!allGood) { - dumpAllThreads("ExtraHubVMConnection"); - } - assertTrue("should be only 2 vm connections for the single network duplex network connector", allGood); - } + @Override + public void removeConnection(ConnectionContext context, + ConnectionInfo info, + Throwable error) throws Exception { + try { + while (--sleepCount >= 0) { + LOG.info("sleeping for a bit in close impl to simulate load where reconnect fails due to a pending close"); + TimeUnit.SECONDS.sleep(2); + } + } + catch (Exception ignored) { + } + super.removeConnection(context, info, error); + } + }}); + startAllBrokers(); + waitForBridgeFormation(); - public void testTwoDuplexNCsAreAllowed() throws Exception { - useDuplexNetworkBridge = true; - useSocketProxy = false; + // kill the initiator side, leaving remote end intact + // simulate async network breakage + // remote side will need to spot duplicate network and stop/kill the original + for (int i = 0; i < 3; i++) { + socketProxy.halfClose(); + sleep(10000); + } + // wait for full reformation of bridge + // verify no extra connections + boolean allGood = Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + long numConnections = hub.broker.getTransportConnectors().get(0).getConnections().size(); + LOG.info("Num connetions:" + numConnections); + return numConnections == 1; + } + }); + if (!allGood) { + dumpAllThreads("ExtraHubConnection"); + } + assertTrue("should be only one transport connection for the single duplex network connector", allGood); - NetworkConnector connector = bridgeBrokers(SPOKE, HUB); - connector.setName("FirstDuplex"); - connector = bridgeBrokers(SPOKE, HUB); - connector.setName("SecondDuplex"); + allGood = Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + long numVmConnections = VMTransportFactory.SERVERS.get(HUB).getConnectionCount(); + LOG.info("Num VM connetions:" + numVmConnections); + return numVmConnections == 2; + } + }); + if (!allGood) { + dumpAllThreads("ExtraHubVMConnection"); + } + assertTrue("should be only 2 vm connections for the single network duplex network connector", allGood); + } - startAllBrokers(); - waitForBridgeFormation(); + public void testTwoDuplexNCsAreAllowed() throws Exception { + useDuplexNetworkBridge = true; + useSocketProxy = false; - BrokerItem hub = brokers.get(HUB); - assertEquals("Has two transport Connectors", 2, hub.broker.getTransportConnectors().get(0).getConnections().size()); - } + NetworkConnector connector = bridgeBrokers(SPOKE, HUB); + connector.setName("FirstDuplex"); + connector = bridgeBrokers(SPOKE, HUB); + connector.setName("SecondDuplex"); - @Override - protected void startAllBrokers() throws Exception { - // Ensure HUB is started first so bridge will be active from the get go - BrokerItem brokerItem = brokers.get(HUB); - brokerItem.broker.start(); - brokerItem = brokers.get(SPOKE); - brokerItem.broker.start(); - sleep(600); - } + startAllBrokers(); + waitForBridgeFormation(); - @Override - public void setUp() throws Exception { - networkDownTimeStart = 0; - inactiveDuration = 1000; - useSocketProxy = true; - super.setAutoFail(true); - super.setUp(); - final String options = "?persistent=true&useJmx=false&deleteAllMessagesOnStartup=true"; - createBroker(new URI("broker:(tcp://localhost:61617)/" + HUB + options)); - createBroker(new URI("broker:(tcp://localhost:61616)/" + SPOKE + options)); - } + BrokerItem hub = brokers.get(HUB); + assertEquals("Has two transport Connectors", 2, hub.broker.getTransportConnectors().get(0).getConnections().size()); + } - @Override - public void tearDown() throws Exception { - super.tearDown(); - if (socketProxy != null) { + @Override + protected void startAllBrokers() throws Exception { + // Ensure HUB is started first so bridge will be active from the get go + BrokerItem brokerItem = brokers.get(HUB); + brokerItem.broker.start(); + brokerItem = brokers.get(SPOKE); + brokerItem.broker.start(); + sleep(600); + } + + @Override + public void setUp() throws Exception { + networkDownTimeStart = 0; + inactiveDuration = 1000; + useSocketProxy = true; + super.setAutoFail(true); + super.setUp(); + final String options = "?persistent=true&useJmx=false&deleteAllMessagesOnStartup=true"; + createBroker(new URI("broker:(tcp://localhost:61617)/" + HUB + options)); + createBroker(new URI("broker:(tcp://localhost:61616)/" + SPOKE + options)); + } + + @Override + public void tearDown() throws Exception { + super.tearDown(); + if (socketProxy != null) { + socketProxy.close(); + } + } + + public static Test suite() { + return suite(BrokerQueueNetworkWithDisconnectTest.class); + } + + @Override + protected void onSend(int i, TextMessage msg) { + sleep(50); + if (i == 50 || i == 150) { + if (simulateStalledNetwork) { + socketProxy.pause(); + } + else { socketProxy.close(); - } - } - - public static Test suite() { - return suite(BrokerQueueNetworkWithDisconnectTest.class); - } - - @Override - protected void onSend(int i, TextMessage msg) { - sleep(50); - if (i == 50 || i == 150) { + } + networkDownTimeStart = System.currentTimeMillis(); + } + else if (networkDownTimeStart > 0) { + // restart after NETWORK_DOWN_TIME seconds + if (networkDownTimeStart + NETWORK_DOWN_TIME < System.currentTimeMillis()) { if (simulateStalledNetwork) { - socketProxy.pause(); - } else { - socketProxy.close(); + socketProxy.goOn(); } - networkDownTimeStart = System.currentTimeMillis(); - } else if (networkDownTimeStart > 0) { - // restart after NETWORK_DOWN_TIME seconds - if (networkDownTimeStart + NETWORK_DOWN_TIME < System.currentTimeMillis()) { - if (simulateStalledNetwork) { - socketProxy.goOn(); - } else { - socketProxy.reopen(); - } - networkDownTimeStart = 0; - } else { - // slow message production to allow bridge to recover and limit message duplication - sleep(500); + else { + socketProxy.reopen(); } - } - super.onSend(i, msg); - } + networkDownTimeStart = 0; + } + else { + // slow message production to allow bridge to recover and limit message duplication + sleep(500); + } + } + super.onSend(i, msg); + } - private void sleep(int milliSecondTime) { - try { - Thread.sleep(milliSecondTime); - } catch (InterruptedException igonred) { - } - } + private void sleep(int milliSecondTime) { + try { + Thread.sleep(milliSecondTime); + } + catch (InterruptedException igonred) { + } + } - @Override - protected NetworkConnector bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker, boolean dynamicOnly, int networkTTL, boolean conduit, boolean failover) throws Exception { - List transportConnectors = remoteBroker.getTransportConnectors(); - URI remoteURI; - if (!transportConnectors.isEmpty()) { - remoteURI = transportConnectors.get(0).getConnectUri(); - if (useSocketProxy) { - socketProxy = new SocketProxy(remoteURI); - remoteURI = socketProxy.getUrl(); - } - DiscoveryNetworkConnector connector = new DiscoveryNetworkConnector(new URI("static:(" + remoteURI - + "?wireFormat.maxInactivityDuration=" + inactiveDuration + "&wireFormat.maxInactivityDurationInitalDelay=" + inactiveDuration + ")?useExponentialBackOff=false")); - connector.setDynamicOnly(dynamicOnly); - connector.setNetworkTTL(networkTTL); - localBroker.addNetworkConnector(connector); - maxSetupTime = 2000; - if (useDuplexNetworkBridge) { - connector.setDuplex(true); - } - return connector; - } else { - throw new Exception("Remote broker has no registered connectors."); - } - } + @Override + protected NetworkConnector bridgeBrokers(BrokerService localBroker, + BrokerService remoteBroker, + boolean dynamicOnly, + int networkTTL, + boolean conduit, + boolean failover) throws Exception { + List transportConnectors = remoteBroker.getTransportConnectors(); + URI remoteURI; + if (!transportConnectors.isEmpty()) { + remoteURI = transportConnectors.get(0).getConnectUri(); + if (useSocketProxy) { + socketProxy = new SocketProxy(remoteURI); + remoteURI = socketProxy.getUrl(); + } + DiscoveryNetworkConnector connector = new DiscoveryNetworkConnector(new URI("static:(" + remoteURI + "?wireFormat.maxInactivityDuration=" + inactiveDuration + "&wireFormat.maxInactivityDurationInitalDelay=" + inactiveDuration + ")?useExponentialBackOff=false")); + connector.setDynamicOnly(dynamicOnly); + connector.setNetworkTTL(networkTTL); + localBroker.addNetworkConnector(connector); + maxSetupTime = 2000; + if (useDuplexNetworkBridge) { + connector.setDuplex(true); + } + return connector; + } + else { + throw new Exception("Remote broker has no registered connectors."); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BrowseDLQTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BrowseDLQTest.java index bbcda6890d..0402012285 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BrowseDLQTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BrowseDLQTest.java @@ -42,67 +42,63 @@ import static org.junit.Assert.*; */ public class BrowseDLQTest { - private static final int NUM_MESSAGES = 100; - private BrokerService brokerService; - private ActiveMQQueue testQueue = new ActiveMQQueue("TEST.FOO"); - private ActiveMQQueue dlq = new ActiveMQQueue("ActiveMQ.DLQ"); + private static final int NUM_MESSAGES = 100; + private BrokerService brokerService; + private ActiveMQQueue testQueue = new ActiveMQQueue("TEST.FOO"); + private ActiveMQQueue dlq = new ActiveMQQueue("ActiveMQ.DLQ"); - @Test - public void testCannotBrowseDLQAsTable() throws Exception { - startBroker(); - // send 100 messages to queue with TTL of 1 second - sendMessagesToBeExpired(); + @Test + public void testCannotBrowseDLQAsTable() throws Exception { + startBroker(); + // send 100 messages to queue with TTL of 1 second + sendMessagesToBeExpired(); - // let's let the messages expire - TimeUnit.SECONDS.sleep(2); + // let's let the messages expire + TimeUnit.SECONDS.sleep(2); - assertCanBrowse(); - } + assertCanBrowse(); + } - private void assertCanBrowse() throws MalformedObjectNameException, OpenDataException { - ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=ActiveMQ.DLQ"); - QueueViewMBean queue = (QueueViewMBean) - brokerService.getManagementContext().newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); - // make sure we have messages here - assertTrue(queue.getQueueSize() > 0); + private void assertCanBrowse() throws MalformedObjectNameException, OpenDataException { + ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=ActiveMQ.DLQ"); + QueueViewMBean queue = (QueueViewMBean) brokerService.getManagementContext().newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); + // make sure we have messages here + assertTrue(queue.getQueueSize() > 0); - CompositeData[] regularBrowse = queue.browse(); - assertNotNull(regularBrowse); + CompositeData[] regularBrowse = queue.browse(); + assertNotNull(regularBrowse); - TabularData tableData = queue.browseAsTable(); - assertNotNull(tableData); + TabularData tableData = queue.browseAsTable(); + assertNotNull(tableData); - } + } + @After + public void tearDown() throws Exception { + brokerService.stop(); + brokerService.waitUntilStopped(); + } + private void startBroker() throws Exception { + brokerService = BrokerFactory.createBroker("broker:()/localhost?deleteAllMessagesOnStartup=true"); - @After - public void tearDown() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - } + PolicyMap policyMap = new PolicyMap(); + PolicyEntry policyEntry = new PolicyEntry(); + policyEntry.setExpireMessagesPeriod(1000); + policyMap.setDefaultEntry(policyEntry); + brokerService.setDestinationPolicy(policyMap); + brokerService.start(); + brokerService.waitUntilStarted(); + } - private void startBroker() throws Exception { - brokerService = BrokerFactory.createBroker("broker:()/localhost?deleteAllMessagesOnStartup=true"); - - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policyEntry = new PolicyEntry(); - policyEntry.setExpireMessagesPeriod(1000); - policyMap.setDefaultEntry(policyEntry); - brokerService.setDestinationPolicy(policyMap); - brokerService.start(); - brokerService.waitUntilStarted(); - } - - private void sendMessagesToBeExpired() throws JMSException, InterruptedException { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(testQueue); - for (int i = 0; i < NUM_MESSAGES; i++) { - producer.send(testQueue,session.createTextMessage("Hello world #" + i), DeliveryMode.PERSISTENT, - 4, 500); - } - connection.close(); - } + private void sendMessagesToBeExpired() throws JMSException, InterruptedException { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + Connection connection = factory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(testQueue); + for (int i = 0; i < NUM_MESSAGES; i++) { + producer.send(testQueue, session.createTextMessage("Hello world #" + i), DeliveryMode.PERSISTENT, 4, 500); + } + connection.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BrowseOverNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BrowseOverNetworkTest.java index 694facfb65..8b3b42bb02 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BrowseOverNetworkTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BrowseOverNetworkTest.java @@ -37,214 +37,217 @@ import org.slf4j.LoggerFactory; import org.springframework.core.io.ClassPathResource; public class BrowseOverNetworkTest extends JmsMultipleBrokersTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(QueueSubscription.class); - protected static final int MESSAGE_COUNT = 10; - public void testBrowse() throws Exception { - createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=false")); - createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=false")); + private static final Logger LOG = LoggerFactory.getLogger(QueueSubscription.class); + protected static final int MESSAGE_COUNT = 10; - bridgeBrokers("BrokerA", "BrokerB"); + public void testBrowse() throws Exception { + createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=false")); + createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=false")); + bridgeBrokers("BrokerA", "BrokerB"); - startAllBrokers(); + startAllBrokers(); - Destination dest = createDestination("TEST.FOO", false); + Destination dest = createDestination("TEST.FOO", false); - sendMessages("BrokerA", dest, MESSAGE_COUNT); + sendMessages("BrokerA", dest, MESSAGE_COUNT); - Thread.sleep(1000); + Thread.sleep(1000); - int browsed = browseMessages("BrokerB", dest); + int browsed = browseMessages("BrokerB", dest); - Thread.sleep(1000); + Thread.sleep(1000); - MessageConsumer clientA = createConsumer("BrokerA", dest); - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - msgsA.waitForMessagesToArrive(MESSAGE_COUNT); + MessageConsumer clientA = createConsumer("BrokerA", dest); + MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); + msgsA.waitForMessagesToArrive(MESSAGE_COUNT); - Thread.sleep(1000); - MessageConsumer clientB = createConsumer("BrokerB", dest); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - msgsB.waitForMessagesToArrive(MESSAGE_COUNT); + Thread.sleep(1000); + MessageConsumer clientB = createConsumer("BrokerB", dest); + MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); + msgsB.waitForMessagesToArrive(MESSAGE_COUNT); - LOG.info("A+B: " + msgsA.getMessageCount() + "+" - + msgsB.getMessageCount()); - assertEquals("Consumer on Broker A, should've consumed all messages", MESSAGE_COUNT, msgsA.getMessageCount()); - assertEquals("Broker B shouldn't get any messages", 0, browsed); - } + LOG.info("A+B: " + msgsA.getMessageCount() + "+" + msgsB.getMessageCount()); + assertEquals("Consumer on Broker A, should've consumed all messages", MESSAGE_COUNT, msgsA.getMessageCount()); + assertEquals("Broker B shouldn't get any messages", 0, browsed); + } - public void testConsumerInfo() throws Exception { - createBroker(new ClassPathResource("org/apache/activemq/usecases/browse-broker1.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/browse-broker2.xml")); + public void testConsumerInfo() throws Exception { + createBroker(new ClassPathResource("org/apache/activemq/usecases/browse-broker1.xml")); + createBroker(new ClassPathResource("org/apache/activemq/usecases/browse-broker2.xml")); - startAllBrokers(); + startAllBrokers(); - brokers.get("broker1").broker.waitUntilStarted(); + brokers.get("broker1").broker.waitUntilStarted(); + Destination dest = createDestination("QUEUE.A,QUEUE.B", false); - Destination dest = createDestination("QUEUE.A,QUEUE.B", false); + int broker1 = browseMessages("broker1", dest); + assertEquals("Browsed a message on an empty queue", 0, broker1); + Thread.sleep(1000); + int broker2 = browseMessages("broker2", dest); + assertEquals("Browsed a message on an empty queue", 0, broker2); + } - int broker1 = browseMessages("broker1", dest); - assertEquals("Browsed a message on an empty queue", 0, broker1); - Thread.sleep(1000); - int broker2 = browseMessages("broker2", dest); - assertEquals("Browsed a message on an empty queue", 0, broker2); + public class Browser extends Thread { - } + String broker; + Destination dest; + int totalCount; + final int expect; + QueueBrowser browser = null; + MessageConsumer consumer = null; + boolean consume = false; - public class Browser extends Thread { + public Browser(String broker, Destination dest, int expect) { + this.broker = broker; + this.dest = dest; + this.expect = expect; + } - String broker; - Destination dest; - int totalCount; - final int expect; - QueueBrowser browser = null; - MessageConsumer consumer = null; - boolean consume = false; + @Override + public void run() { + int retries = 0; + while (retries++ < 20 && totalCount != expect) { + try { + QueueBrowser browser = createBrowser(broker, dest); + int count = browseMessages(browser, broker); + if (consume) { + if (count != 0) { + MessageConsumer consumer = createSyncConsumer(broker, dest); + totalCount += count; + for (int i = 0; i < count; i++) { + ActiveMQTextMessage message = (ActiveMQTextMessage) consumer.receive(1000); + if (message == null) + break; + LOG.info(broker + " consumer: " + message.getText() + " " + message.getDestination() + " " + message.getMessageId() + " " + Arrays.toString(message.getBrokerPath())); + } + } + } + else { + totalCount = count; + } + LOG.info("browser '" + broker + "' browsed " + totalCount); - public Browser(String broker, Destination dest, int expect) { - this.broker = broker; - this.dest = dest; - this.expect = expect; - } - - @Override - public void run() { - int retries = 0; - while (retries++ < 20 && totalCount != expect) { - try { - QueueBrowser browser = createBrowser(broker, dest); - int count = browseMessages(browser, broker); - if (consume) { - if (count != 0) { - MessageConsumer consumer = createSyncConsumer(broker, dest); - totalCount += count; - for (int i = 0; i < count; i++) { - ActiveMQTextMessage message = (ActiveMQTextMessage)consumer.receive(1000); - if (message == null) break; - LOG.info(broker + " consumer: " + message.getText() + " " + message.getDestination() + " " + message.getMessageId() + " " + Arrays.toString(message.getBrokerPath())); - } - } - } else { - totalCount = count; - } - LOG.info("browser '" + broker + "' browsed " + totalCount); - - Thread.sleep(1000); - } catch (Exception e) { - LOG.info("Exception browsing " + e, e); - } finally { - try { - if (browser != null) { - browser.close(); - } - if (consumer != null) { - consumer.close(); - } - } catch (Exception e) { - LOG.info("Exception closing browser " + e, e); - } - } + Thread.sleep(1000); + } + catch (Exception e) { + LOG.info("Exception browsing " + e, e); + } + finally { + try { + if (browser != null) { + browser.close(); + } + if (consumer != null) { + consumer.close(); + } + } + catch (Exception e) { + LOG.info("Exception closing browser " + e, e); + } } - } - - public int getTotalCount() { - return totalCount; - } - } - - protected NetworkConnector bridgeBrokersWithIncludedDestination(String localBrokerName, String remoteBrokerName, ActiveMQDestination included, ActiveMQDestination excluded) throws Exception { - NetworkConnector nc = bridgeBrokers(localBrokerName, remoteBrokerName, false, 4, true); - nc.addStaticallyIncludedDestination(included); - if (excluded != null) { - nc.addExcludedDestination(excluded); - } - nc.setPrefetchSize(1); - return nc; - } - - public void testAMQ3020() throws Exception { - createBroker(new ClassPathResource("org/apache/activemq/usecases/browse-broker1A.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/browse-broker1B.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/browse-broker2A.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/browse-broker2B.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/browse-broker3A.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/browse-broker3B.xml")); - - brokers.get("broker-1A").broker.waitUntilStarted(); - brokers.get("broker-2A").broker.waitUntilStarted(); - brokers.get("broker-3A").broker.waitUntilStarted(); - - for (BrokerItem brokerItem : brokers.values()) { - final BrokerService broker = brokerItem.broker; - waitForBridgeFormation(broker, 1, 0); - waitForBridgeFormation(broker, 1, 1); - waitForBridgeFormation(broker, 1, 2); - waitForBridgeFormation(broker, 1, 3); - waitForBridgeFormation(broker, 1, 4); } + } - Destination composite = createDestination("PROD.FUSESOURCE.3.A,PROD.FUSESOURCE.3.B", false); + public int getTotalCount() { + return totalCount; + } + } - final Browser browser1 = new Browser("broker-3A", composite, MESSAGE_COUNT); - browser1.start(); + protected NetworkConnector bridgeBrokersWithIncludedDestination(String localBrokerName, + String remoteBrokerName, + ActiveMQDestination included, + ActiveMQDestination excluded) throws Exception { + NetworkConnector nc = bridgeBrokers(localBrokerName, remoteBrokerName, false, 4, true); + nc.addStaticallyIncludedDestination(included); + if (excluded != null) { + nc.addExcludedDestination(excluded); + } + nc.setPrefetchSize(1); + return nc; + } - final Browser browser2 = new Browser("broker-3B", composite, MESSAGE_COUNT); - browser2.start(); + public void testAMQ3020() throws Exception { + createBroker(new ClassPathResource("org/apache/activemq/usecases/browse-broker1A.xml")); + createBroker(new ClassPathResource("org/apache/activemq/usecases/browse-broker1B.xml")); + createBroker(new ClassPathResource("org/apache/activemq/usecases/browse-broker2A.xml")); + createBroker(new ClassPathResource("org/apache/activemq/usecases/browse-broker2B.xml")); + createBroker(new ClassPathResource("org/apache/activemq/usecases/browse-broker3A.xml")); + createBroker(new ClassPathResource("org/apache/activemq/usecases/browse-broker3B.xml")); - LOG.info("Sending messages to broker-1A"); - sendMessages("broker-1A", composite, MESSAGE_COUNT); - LOG.info("Message sent to broker-1A"); + brokers.get("broker-1A").broker.waitUntilStarted(); + brokers.get("broker-2A").broker.waitUntilStarted(); + brokers.get("broker-3A").broker.waitUntilStarted(); - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return browser1.getTotalCount() == MESSAGE_COUNT; - } - }); - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return browser2.getTotalCount() == MESSAGE_COUNT; - } - }); + for (BrokerItem brokerItem : brokers.values()) { + final BrokerService broker = brokerItem.broker; + waitForBridgeFormation(broker, 1, 0); + waitForBridgeFormation(broker, 1, 1); + waitForBridgeFormation(broker, 1, 2); + waitForBridgeFormation(broker, 1, 3); + waitForBridgeFormation(broker, 1, 4); + } - browser1.join(); - browser2.join(); + Destination composite = createDestination("PROD.FUSESOURCE.3.A,PROD.FUSESOURCE.3.B", false); + final Browser browser1 = new Browser("broker-3A", composite, MESSAGE_COUNT); + browser1.start(); - LOG.info("broker-3A browsed " + browser1.getTotalCount()); - LOG.info("broker-3B browsed " + browser2.getTotalCount()); + final Browser browser2 = new Browser("broker-3B", composite, MESSAGE_COUNT); + browser2.start(); - assertEquals(MESSAGE_COUNT * 2, browser1.getTotalCount() + browser2.getTotalCount() ); + LOG.info("Sending messages to broker-1A"); + sendMessages("broker-1A", composite, MESSAGE_COUNT); + LOG.info("Message sent to broker-1A"); - } + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return browser1.getTotalCount() == MESSAGE_COUNT; + } + }); + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return browser2.getTotalCount() == MESSAGE_COUNT; + } + }); - protected int browseMessages(QueueBrowser browser, String name) throws Exception { - Enumeration msgs = browser.getEnumeration(); - int browsedMessage = 0; - while (msgs.hasMoreElements()) { - browsedMessage++; - ActiveMQTextMessage message = (ActiveMQTextMessage)msgs.nextElement(); - LOG.info(name + " browsed: " + message.getText() + " " + message.getDestination() + " " + message.getMessageId() + " " + Arrays.toString(message.getBrokerPath())); - } - return browsedMessage; - } + browser1.join(); + browser2.join(); + LOG.info("broker-3A browsed " + browser1.getTotalCount()); + LOG.info("broker-3B browsed " + browser2.getTotalCount()); - protected int browseMessages(String broker, Destination dest) throws Exception { - QueueBrowser browser = createBrowser(broker, dest); - int browsedMessage = browseMessages(browser, "browser"); - browser.close(); - return browsedMessage; - } + assertEquals(MESSAGE_COUNT * 2, browser1.getTotalCount() + browser2.getTotalCount()); - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - } + } + + protected int browseMessages(QueueBrowser browser, String name) throws Exception { + Enumeration msgs = browser.getEnumeration(); + int browsedMessage = 0; + while (msgs.hasMoreElements()) { + browsedMessage++; + ActiveMQTextMessage message = (ActiveMQTextMessage) msgs.nextElement(); + LOG.info(name + " browsed: " + message.getText() + " " + message.getDestination() + " " + message.getMessageId() + " " + Arrays.toString(message.getBrokerPath())); + } + return browsedMessage; + } + + protected int browseMessages(String broker, Destination dest) throws Exception { + QueueBrowser browser = createBrowser(broker, dest); + int browsedMessage = browseMessages(browser, "browser"); + browser.close(); + return browsedMessage; + } + + @Override + public void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ChangeSentMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ChangeSentMessageTest.java index 90dfa2d4f1..347548ce8c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ChangeSentMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ChangeSentMessageTest.java @@ -32,36 +32,37 @@ import org.apache.activemq.test.TestSupport; * */ public class ChangeSentMessageTest extends TestSupport { - private static final int COUNT = 200; - private static final String VALUE_NAME = "value"; - /** - * test Object messages can be changed after sending with no side-affects - * - * @throws Exception - */ - @SuppressWarnings("rawtypes") - public void testDoChangeSentMessage() throws Exception { - Destination destination = createDestination("test-" + ChangeSentMessageTest.class.getName()); - Connection connection = createConnection(); - connection.start(); - Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = consumerSession.createConsumer(destination); - Session publisherSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = publisherSession.createProducer(destination); - HashMap map = new HashMap(); - ObjectMessage message = publisherSession.createObjectMessage(); - for (int i = 0; i < COUNT; i++) { - map.put(VALUE_NAME, Integer.valueOf(i)); - message.setObject(map); - producer.send(message); - assertTrue(message.getObject() == map); - } - for (int i = 0; i < COUNT; i++) { - ObjectMessage msg = (ObjectMessage)consumer.receive(); - HashMap receivedMap = (HashMap)msg.getObject(); - Integer intValue = (Integer)receivedMap.get(VALUE_NAME); - assertTrue(intValue.intValue() == i); - } - } + private static final int COUNT = 200; + private static final String VALUE_NAME = "value"; + + /** + * test Object messages can be changed after sending with no side-affects + * + * @throws Exception + */ + @SuppressWarnings("rawtypes") + public void testDoChangeSentMessage() throws Exception { + Destination destination = createDestination("test-" + ChangeSentMessageTest.class.getName()); + Connection connection = createConnection(); + connection.start(); + Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = consumerSession.createConsumer(destination); + Session publisherSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = publisherSession.createProducer(destination); + HashMap map = new HashMap(); + ObjectMessage message = publisherSession.createObjectMessage(); + for (int i = 0; i < COUNT; i++) { + map.put(VALUE_NAME, Integer.valueOf(i)); + message.setObject(map); + producer.send(message); + assertTrue(message.getObject() == map); + } + for (int i = 0; i < COUNT; i++) { + ObjectMessage msg = (ObjectMessage) consumer.receive(); + HashMap receivedMap = (HashMap) msg.getObject(); + Integer intValue = (Integer) receivedMap.get(VALUE_NAME); + assertTrue(intValue.intValue() == i); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ChangeSessionDeliveryModeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ChangeSessionDeliveryModeTest.java index bb62d1a641..da838e250d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ChangeSessionDeliveryModeTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ChangeSessionDeliveryModeTest.java @@ -33,31 +33,32 @@ import org.apache.activemq.test.TestSupport; */ public class ChangeSessionDeliveryModeTest extends TestSupport implements MessageListener { - /** - * test following condition- which are defined by JMS Spec 1.1: - * MessageConsumers cannot use a MessageListener and receive() from the same - * session - * - * @throws Exception - */ - public void testDoChangeSessionDeliveryMode() throws Exception { - Destination destination = createDestination("foo.bar"); - Connection connection = createConnection(); - connection.start(); - Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer1 = consumerSession.createConsumer(destination); - consumer1.setMessageListener(this); - MessageConsumer consumer2 = consumerSession.createConsumer(destination); + /** + * test following condition- which are defined by JMS Spec 1.1: + * MessageConsumers cannot use a MessageListener and receive() from the same + * session + * + * @throws Exception + */ + public void testDoChangeSessionDeliveryMode() throws Exception { + Destination destination = createDestination("foo.bar"); + Connection connection = createConnection(); + connection.start(); + Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer1 = consumerSession.createConsumer(destination); + consumer1.setMessageListener(this); + MessageConsumer consumer2 = consumerSession.createConsumer(destination); - try { - consumer2.receive(10); - fail("Did not receive expected exception."); - } catch (JMSException e) { - assertTrue(e instanceof IllegalStateException); - } - } + try { + consumer2.receive(10); + fail("Did not receive expected exception."); + } + catch (JMSException e) { + assertTrue(e instanceof IllegalStateException); + } + } - @Override - public void onMessage(Message msg) { - } + @Override + public void onMessage(Message msg) { + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ClientRebalanceTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ClientRebalanceTest.java index e00eb70b10..8fa255cdc5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ClientRebalanceTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ClientRebalanceTest.java @@ -29,62 +29,62 @@ import org.apache.log4j.Logger; import org.springframework.core.io.ClassPathResource; public class ClientRebalanceTest extends JmsMultipleBrokersTestSupport { - private static final Logger LOG = Logger.getLogger(ClientRebalanceTest.class); - private static final String QUEUE_NAME = "Test.ClientRebalanceTest"; - protected void setUp() throws Exception { - setAutoFail(true); - super.setUp(); - } + private static final Logger LOG = Logger.getLogger(ClientRebalanceTest.class); + private static final String QUEUE_NAME = "Test.ClientRebalanceTest"; + protected void setUp() throws Exception { + setAutoFail(true); + super.setUp(); + } - public void testRebalance() throws Exception { - createBroker(new ClassPathResource("org/apache/activemq/usecases/rebalance-broker1.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/rebalance-broker2.xml")); + public void testRebalance() throws Exception { + createBroker(new ClassPathResource("org/apache/activemq/usecases/rebalance-broker1.xml")); + createBroker(new ClassPathResource("org/apache/activemq/usecases/rebalance-broker2.xml")); - startAllBrokers(); + startAllBrokers(); - brokers.get("b1").broker.waitUntilStarted(); + brokers.get("b1").broker.waitUntilStarted(); - LOG.info("Starting connection"); + LOG.info("Starting connection"); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("failover:(tcp://localhost:61616,tcp://localhost:61617)?randomize=false"); - Connection conn = factory.createConnection(); - conn.start(); - Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue theQueue = session.createQueue(QUEUE_NAME); - MessageProducer producer = session.createProducer(theQueue); - MessageConsumer consumer = session.createConsumer(theQueue); - Message message = session.createTextMessage("Test message"); - producer.send(message); - Message msg = consumer.receive(2000); - assertNotNull(msg); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("failover:(tcp://localhost:61616,tcp://localhost:61617)?randomize=false"); + Connection conn = factory.createConnection(); + conn.start(); + Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue theQueue = session.createQueue(QUEUE_NAME); + MessageProducer producer = session.createProducer(theQueue); + MessageConsumer consumer = session.createConsumer(theQueue); + Message message = session.createTextMessage("Test message"); + producer.send(message); + Message msg = consumer.receive(2000); + assertNotNull(msg); - // introduce third broker - createBroker(new ClassPathResource("org/apache/activemq/usecases/rebalance-broker3.xml")); - brokers.get("b3").broker.waitUntilStarted(); - - Thread.sleep(3000); + // introduce third broker + createBroker(new ClassPathResource("org/apache/activemq/usecases/rebalance-broker3.xml")); + brokers.get("b3").broker.waitUntilStarted(); - LOG.info("Stopping broker 1"); + Thread.sleep(3000); - brokers.get("b1").broker.stop(); - brokers.get("b1").broker.waitUntilStopped(); - - Thread.sleep(3000); - // should reconnect to some of the remaining brokers - producer.send(message); - msg = consumer.receive(2000); - assertNotNull(msg); + LOG.info("Stopping broker 1"); - LOG.info("Stopping broker 2"); + brokers.get("b1").broker.stop(); + brokers.get("b1").broker.waitUntilStopped(); - brokers.get("b2").broker.stop(); - brokers.get("b2").broker.waitUntilStopped(); + Thread.sleep(3000); + // should reconnect to some of the remaining brokers + producer.send(message); + msg = consumer.receive(2000); + assertNotNull(msg); - // should reconnect to broker3 - producer.send(message); - msg = consumer.receive(2000); - assertNotNull(msg); - } + LOG.info("Stopping broker 2"); + + brokers.get("b2").broker.stop(); + brokers.get("b2").broker.waitUntilStopped(); + + // should reconnect to broker3 + producer.send(message); + msg = consumer.receive(2000); + assertNotNull(msg); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CompositeConsumeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CompositeConsumeTest.java index add5a3c379..c73d7ad40d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CompositeConsumeTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CompositeConsumeTest.java @@ -26,49 +26,50 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class CompositeConsumeTest extends JmsTopicSendReceiveWithTwoConnectionsTest { - private static final Logger LOG = LoggerFactory.getLogger(CompositeConsumeTest.class); - public void testSendReceive() throws Exception { - messages.clear(); + private static final Logger LOG = LoggerFactory.getLogger(CompositeConsumeTest.class); - Destination[] destinations = getDestinations(); - int destIdx = 0; + public void testSendReceive() throws Exception { + messages.clear(); - for (int i = 0; i < data.length; i++) { - Message message = session.createTextMessage(data[i]); + Destination[] destinations = getDestinations(); + int destIdx = 0; - if (verbose) { - LOG.info("About to send a message: " + message + " with text: " + data[i]); - } + for (int i = 0; i < data.length; i++) { + Message message = session.createTextMessage(data[i]); - producer.send(destinations[destIdx], message); + if (verbose) { + LOG.info("About to send a message: " + message + " with text: " + data[i]); + } - if (++destIdx >= destinations.length) { - destIdx = 0; - } - } + producer.send(destinations[destIdx], message); - assertMessagesAreReceived(); - } + if (++destIdx >= destinations.length) { + destIdx = 0; + } + } - /** - * Returns the subscription subject - */ - protected String getSubject() { - return getPrefix() + "FOO.BAR," + getPrefix() + "FOO.X.Y," + getPrefix() + "BAR.>"; - } + assertMessagesAreReceived(); + } - /** - * Returns the destinations on which we publish - */ - protected Destination[] getDestinations() { - return new Destination[]{new ActiveMQTopic(getPrefix() + "FOO.BAR"), new ActiveMQTopic(getPrefix() + "BAR.WHATNOT.XYZ"), new ActiveMQTopic(getPrefix() + "FOO.X.Y")}; - } + /** + * Returns the subscription subject + */ + protected String getSubject() { + return getPrefix() + "FOO.BAR," + getPrefix() + "FOO.X.Y," + getPrefix() + "BAR.>"; + } - protected String getPrefix() { - return super.getSubject() + "."; - } + /** + * Returns the destinations on which we publish + */ + protected Destination[] getDestinations() { + return new Destination[]{new ActiveMQTopic(getPrefix() + "FOO.BAR"), new ActiveMQTopic(getPrefix() + "BAR.WHATNOT.XYZ"), new ActiveMQTopic(getPrefix() + "FOO.X.Y")}; + } + + protected String getPrefix() { + return super.getSubject() + "."; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CompositePublishTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CompositePublishTest.java index 2018a5d916..651376a96d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CompositePublishTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CompositePublishTest.java @@ -36,118 +36,120 @@ import org.slf4j.LoggerFactory; * */ public class CompositePublishTest extends JmsSendReceiveTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(CompositePublishTest.class); - protected Connection sendConnection; - protected Connection receiveConnection; - protected Session receiveSession; - protected MessageConsumer[] consumers; - @SuppressWarnings("rawtypes") - protected List[] messageLists; + private static final Logger LOG = LoggerFactory.getLogger(CompositePublishTest.class); - @SuppressWarnings("unchecked") - @Override - protected void setUp() throws Exception { - super.setUp(); + protected Connection sendConnection; + protected Connection receiveConnection; + protected Session receiveSession; + protected MessageConsumer[] consumers; + @SuppressWarnings("rawtypes") + protected List[] messageLists; - connectionFactory = createConnectionFactory(); + @SuppressWarnings("unchecked") + @Override + protected void setUp() throws Exception { + super.setUp(); - sendConnection = createConnection(); - sendConnection.start(); + connectionFactory = createConnectionFactory(); - receiveConnection = createConnection(); - receiveConnection.start(); + sendConnection = createConnection(); + sendConnection.start(); - LOG.info("Created sendConnection: " + sendConnection); - LOG.info("Created receiveConnection: " + receiveConnection); + receiveConnection = createConnection(); + receiveConnection.start(); - session = sendConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - receiveSession = receiveConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + LOG.info("Created sendConnection: " + sendConnection); + LOG.info("Created receiveConnection: " + receiveConnection); - LOG.info("Created sendSession: " + session); - LOG.info("Created receiveSession: " + receiveSession); + session = sendConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + receiveSession = receiveConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(null); + LOG.info("Created sendSession: " + session); + LOG.info("Created receiveSession: " + receiveSession); - LOG.info("Created producer: " + producer); + producer = session.createProducer(null); - if (topic) { - consumerDestination = session.createTopic(getConsumerSubject()); - producerDestination = session.createTopic(getProducerSubject()); - } else { - consumerDestination = session.createQueue(getConsumerSubject()); - producerDestination = session.createQueue(getProducerSubject()); - } + LOG.info("Created producer: " + producer); - LOG.info("Created consumer destination: " + consumerDestination + " of type: " + consumerDestination.getClass()); - LOG.info("Created producer destination: " + producerDestination + " of type: " + producerDestination.getClass()); + if (topic) { + consumerDestination = session.createTopic(getConsumerSubject()); + producerDestination = session.createTopic(getProducerSubject()); + } + else { + consumerDestination = session.createQueue(getConsumerSubject()); + producerDestination = session.createQueue(getProducerSubject()); + } - Destination[] destinations = getDestinations(); - consumers = new MessageConsumer[destinations.length]; - messageLists = new List[destinations.length]; - for (int i = 0; i < destinations.length; i++) { - Destination dest = destinations[i]; - messageLists[i] = createConcurrentList(); - consumers[i] = receiveSession.createConsumer(dest); - consumers[i].setMessageListener(createMessageListener(i, messageLists[i])); - } + LOG.info("Created consumer destination: " + consumerDestination + " of type: " + consumerDestination.getClass()); + LOG.info("Created producer destination: " + producerDestination + " of type: " + producerDestination.getClass()); - LOG.info("Started connections"); - } + Destination[] destinations = getDestinations(); + consumers = new MessageConsumer[destinations.length]; + messageLists = new List[destinations.length]; + for (int i = 0; i < destinations.length; i++) { + Destination dest = destinations[i]; + messageLists[i] = createConcurrentList(); + consumers[i] = receiveSession.createConsumer(dest); + consumers[i].setMessageListener(createMessageListener(i, messageLists[i])); + } - protected MessageListener createMessageListener(int i, final List messageList) { - return new MessageListener() { - @Override - public void onMessage(Message message) { - consumeMessage(message, messageList); - } - }; - } + LOG.info("Started connections"); + } - /** - * Returns the subject on which we publish - */ - @Override - protected String getSubject() { - return getPrefix() + "FOO.BAR," + getPrefix() + "FOO.X.Y"; - } + protected MessageListener createMessageListener(int i, final List messageList) { + return new MessageListener() { + @Override + public void onMessage(Message message) { + consumeMessage(message, messageList); + } + }; + } - /** - * Returns the destinations to which we consume - */ - protected Destination[] getDestinations() { - return new Destination[] {new ActiveMQTopic(getPrefix() + "FOO.BAR"), new ActiveMQTopic(getPrefix() + "FOO.*"), new ActiveMQTopic(getPrefix() + "FOO.X.Y")}; - } + /** + * Returns the subject on which we publish + */ + @Override + protected String getSubject() { + return getPrefix() + "FOO.BAR," + getPrefix() + "FOO.X.Y"; + } - protected String getPrefix() { - return super.getSubject() + "."; - } + /** + * Returns the destinations to which we consume + */ + protected Destination[] getDestinations() { + return new Destination[]{new ActiveMQTopic(getPrefix() + "FOO.BAR"), new ActiveMQTopic(getPrefix() + "FOO.*"), new ActiveMQTopic(getPrefix() + "FOO.X.Y")}; + } - @SuppressWarnings("unchecked") - @Override - protected void assertMessagesAreReceived() throws JMSException { - waitForMessagesToBeDelivered(); - int size = messageLists.length; - for (int i = 0; i < size; i++) { - LOG.info("Message list: " + i + " contains: " + messageLists[i].size() + " message(s)"); - } - size = messageLists.length; - for (int i = 0; i < size; i++) { - assertMessagesReceivedAreValid(messageLists[i]); - } - } + protected String getPrefix() { + return super.getSubject() + "."; + } - @Override - protected ActiveMQConnectionFactory createConnectionFactory() { - return new ActiveMQConnectionFactory("vm://localhost"); - } + @SuppressWarnings("unchecked") + @Override + protected void assertMessagesAreReceived() throws JMSException { + waitForMessagesToBeDelivered(); + int size = messageLists.length; + for (int i = 0; i < size; i++) { + LOG.info("Message list: " + i + " contains: " + messageLists[i].size() + " message(s)"); + } + size = messageLists.length; + for (int i = 0; i < size; i++) { + assertMessagesReceivedAreValid(messageLists[i]); + } + } - @Override - protected void tearDown() throws Exception { - session.close(); - receiveSession.close(); + @Override + protected ActiveMQConnectionFactory createConnectionFactory() { + return new ActiveMQConnectionFactory("vm://localhost"); + } - sendConnection.close(); - receiveConnection.close(); - } + @Override + protected void tearDown() throws Exception { + session.close(); + receiveSession.close(); + + sendConnection.close(); + receiveConnection.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConcurrentDestinationCreationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConcurrentDestinationCreationTest.java index eb9e5d4144..9e44bb4c77 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConcurrentDestinationCreationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConcurrentDestinationCreationTest.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.usecases; - import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; @@ -29,6 +28,7 @@ import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.command.ActiveMQQueue; @@ -36,117 +36,121 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ConcurrentDestinationCreationTest extends org.apache.activemq.TestSupport { - private static final Logger LOG = LoggerFactory.getLogger(ConcurrentDestinationCreationTest.class); - BrokerService broker; - @Override - protected void setUp() throws Exception { - broker = createBroker(); - super.setUp(); - } + private static final Logger LOG = LoggerFactory.getLogger(ConcurrentDestinationCreationTest.class); + BrokerService broker; - @Override - protected void tearDown() throws Exception { - super.tearDown(); - broker.stop(); - } + @Override + protected void setUp() throws Exception { + broker = createBroker(); + super.setUp(); + } - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString() + "?jms.watchTopicAdvisories=false&jms.closeTimeout=35000"); - } + @Override + protected void tearDown() throws Exception { + super.tearDown(); + broker.stop(); + } - BrokerService createBroker() throws Exception { - BrokerService service = new BrokerService(); - service.setDeleteAllMessagesOnStartup(true); - service.setAdvisorySupport(false); - service.setTransportConnectorURIs(new String[]{"tcp://localhost:0"}); - service.setPersistent(false); - service.setUseJmx(false); - service.start(); - return service; - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString() + "?jms.watchTopicAdvisories=false&jms.closeTimeout=35000"); + } - public void testSendRateWithActivatingConsumers() throws Exception { + BrokerService createBroker() throws Exception { + BrokerService service = new BrokerService(); + service.setDeleteAllMessagesOnStartup(true); + service.setAdvisorySupport(false); + service.setTransportConnectorURIs(new String[]{"tcp://localhost:0"}); + service.setPersistent(false); + service.setUseJmx(false); + service.start(); + return service; + } - final Vector exceptions = new Vector(); - final int jobs = 50; - final int destinationCount = 10; - final CountDownLatch allDone = new CountDownLatch(jobs); - ExecutorService executor = java.util.concurrent.Executors.newCachedThreadPool(); - for (int i = 0; i < jobs; i++) { - if (i %2 == 0 && i exceptions = new Vector(); + final int jobs = 50; + final int destinationCount = 10; + final CountDownLatch allDone = new CountDownLatch(jobs); + ExecutorService executor = java.util.concurrent.Executors.newCachedThreadPool(); + for (int i = 0; i < jobs; i++) { + if (i % 2 == 0 && i < jobs / 2) { + executor.execute(new Runnable() { + final ConnectionFactory factory = createConnectionFactory(); - for (int j = 0; j< jobs*10; j++) { - final MessageProducer producer = session.createProducer(new ActiveMQQueue("Q." + (j%destinationCount))); - producer.send(session.createMessage()); - } - connection.close(); - allDone.countDown(); - LOG.info("Producers done!"); - } catch (Exception ignored) { - LOG.error("unexpected ", ignored); - exceptions.add(ignored); - } - } - }); - } else { + @Override + public void run() { + try { + final Connection connection = factory.createConnection(); + connection.start(); + final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - executor.execute(new Runnable() { - final ConnectionFactory factory = createConnectionFactory(); + for (int j = 0; j < jobs * 10; j++) { + final MessageProducer producer = session.createProducer(new ActiveMQQueue("Q." + (j % destinationCount))); + producer.send(session.createMessage()); + } + connection.close(); + allDone.countDown(); + LOG.info("Producers done!"); + } + catch (Exception ignored) { + LOG.error("unexpected ", ignored); + exceptions.add(ignored); + } + } + }); + } + else { - @Override - public void run() { - try { - final Connection connection = factory.createConnection(); - connection.start(); - final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - for (int j = 0; j < jobs; j++) { - final MessageConsumer consumer = session.createConsumer(new ActiveMQQueue("Q.>")); - consumer.receiveNoWait(); - } - connection.close(); - allDone.countDown(); - LOG.info("Consumers done!"); - } catch (Exception ignored) { - LOG.error("unexpected ", ignored); - exceptions.add(ignored); - } - } - }); + executor.execute(new Runnable() { + final ConnectionFactory factory = createConnectionFactory(); + + @Override + public void run() { + try { + final Connection connection = factory.createConnection(); + connection.start(); + final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + for (int j = 0; j < jobs; j++) { + final MessageConsumer consumer = session.createConsumer(new ActiveMQQueue("Q.>")); + consumer.receiveNoWait(); + } + connection.close(); + allDone.countDown(); + LOG.info("Consumers done!"); + } + catch (Exception ignored) { + LOG.error("unexpected ", ignored); + exceptions.add(ignored); + } + } + }); + } + } + LOG.info("Waiting for completion"); + executor.shutdown(); + boolean success = allDone.await(30, TimeUnit.SECONDS); + if (!success) { + dumpAllThreads("hung"); + + ThreadMXBean bean = ManagementFactory.getThreadMXBean(); + LOG.info("Supports dead lock detection: " + bean.isSynchronizerUsageSupported()); + long[] threadIds = bean.findDeadlockedThreads(); + if (threadIds != null) { + System.err.println("Dead locked threads...."); + ThreadInfo[] infos = bean.getThreadInfo(threadIds); + + for (ThreadInfo info : infos) { + StackTraceElement[] stack = info.getStackTrace(); + System.err.println(" " + info + ", stack size::" + stack.length); + for (StackTraceElement stackEntry : stack) { + System.err.println(" " + stackEntry); + } } - } - LOG.info("Waiting for completion"); - executor.shutdown(); - boolean success = allDone.await(30, TimeUnit.SECONDS); - if (!success) { - dumpAllThreads("hung"); - - ThreadMXBean bean = ManagementFactory.getThreadMXBean(); - LOG.info("Supports dead lock detection: " + bean.isSynchronizerUsageSupported()); - long[] threadIds = bean.findDeadlockedThreads(); - if (threadIds != null) { - System.err.println("Dead locked threads...."); - ThreadInfo[] infos = bean.getThreadInfo(threadIds); - - for (ThreadInfo info : infos) { - StackTraceElement[] stack = info.getStackTrace(); - System.err.println(" " + info + ", stack size::" + stack.length); - for (StackTraceElement stackEntry : stack) { - System.err.println(" " + stackEntry); - } - } - } - } - assertTrue("Finished on time", success); - assertTrue("No unexpected exceptions", exceptions.isEmpty()); - } + } + } + assertTrue("Finished on time", success); + assertTrue("No unexpected exceptions", exceptions.isEmpty()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConcurrentProducerDurableConsumerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConcurrentProducerDurableConsumerTest.java index 0e71dfea3a..a65d217272 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConcurrentProducerDurableConsumerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConcurrentProducerDurableConsumerTest.java @@ -64,306 +64,300 @@ import org.slf4j.LoggerFactory; @RunWith(value = Parameterized.class) public class ConcurrentProducerDurableConsumerTest extends TestSupport { - private static final Logger LOG = LoggerFactory.getLogger(ConcurrentProducerDurableConsumerTest.class); - private final int consumerCount = 5; - BrokerService broker; - protected List connections = Collections.synchronizedList(new ArrayList()); - protected Map consumers = new HashMap(); - protected MessageIdList allMessagesList = new MessageIdList(); - private final int messageSize = 1024; - private final TestSupport.PersistenceAdapterChoice persistenceAdapterChoice; + private static final Logger LOG = LoggerFactory.getLogger(ConcurrentProducerDurableConsumerTest.class); + private final int consumerCount = 5; + BrokerService broker; + protected List connections = Collections.synchronizedList(new ArrayList()); + protected Map consumers = new HashMap(); + protected MessageIdList allMessagesList = new MessageIdList(); + private final int messageSize = 1024; - @Parameterized.Parameters - public static Collection getTestParameters() { - TestSupport.PersistenceAdapterChoice[] kahaDb = {TestSupport.PersistenceAdapterChoice.KahaDB}; - TestSupport.PersistenceAdapterChoice[] levelDb = {TestSupport.PersistenceAdapterChoice.LevelDB}; - TestSupport.PersistenceAdapterChoice[] mem = {TestSupport.PersistenceAdapterChoice.MEM}; - List choices = new ArrayList(); - choices.add(kahaDb); - choices.add(levelDb); - choices.add(mem); - return choices; - } + private final TestSupport.PersistenceAdapterChoice persistenceAdapterChoice; - public ConcurrentProducerDurableConsumerTest(TestSupport.PersistenceAdapterChoice choice) { - this.persistenceAdapterChoice = choice; - } + @Parameterized.Parameters + public static Collection getTestParameters() { + TestSupport.PersistenceAdapterChoice[] kahaDb = {TestSupport.PersistenceAdapterChoice.KahaDB}; + TestSupport.PersistenceAdapterChoice[] levelDb = {TestSupport.PersistenceAdapterChoice.LevelDB}; + TestSupport.PersistenceAdapterChoice[] mem = {TestSupport.PersistenceAdapterChoice.MEM}; + List choices = new ArrayList(); + choices.add(kahaDb); + choices.add(levelDb); + choices.add(mem); + return choices; + } - @Test(timeout = 120000) - public void testSendRateWithActivatingConsumers() throws Exception { - final Destination destination = createDestination(); - final ConnectionFactory factory = createConnectionFactory(); - startInactiveConsumers(factory, destination); + public ConcurrentProducerDurableConsumerTest(TestSupport.PersistenceAdapterChoice choice) { + this.persistenceAdapterChoice = choice; + } - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = createMessageProducer(session, destination); + @Test(timeout = 120000) + public void testSendRateWithActivatingConsumers() throws Exception { + final Destination destination = createDestination(); + final ConnectionFactory factory = createConnectionFactory(); + startInactiveConsumers(factory, destination); - // preload the durable consumers - double[] inactiveConsumerStats = produceMessages(destination, 500, 10, session, producer, null); - LOG.info("With inactive consumers: ave: " + inactiveConsumerStats[1] - + ", max: " + inactiveConsumerStats[0] + ", multiplier: " + (inactiveConsumerStats[0]/inactiveConsumerStats[1])); + Connection connection = factory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = createMessageProducer(session, destination); - // periodically start a durable sub that has a backlog - final int consumersToActivate = 5; - final CountDownLatch addConsumerSignal = new CountDownLatch(1); - Executors.newCachedThreadPool(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "ActivateConsumer" + this); - } - }).execute(new Runnable() { - @Override - public void run() { - try { - MessageConsumer consumer = null; - for (int i = 0; i < consumersToActivate; i++) { - LOG.info("Waiting for add signal from producer..."); - addConsumerSignal.await(30, TimeUnit.MINUTES); - TimedMessageListener listener = new TimedMessageListener(); - consumer = createDurableSubscriber(factory.createConnection(), destination, "consumer" + (i + 1)); - LOG.info("Created consumer " + consumer); - consumer.setMessageListener(listener); - consumers.put(consumer, listener); - } - } catch (Exception e) { - LOG.error("failed to start consumer", e); - } - } - }); + // preload the durable consumers + double[] inactiveConsumerStats = produceMessages(destination, 500, 10, session, producer, null); + LOG.info("With inactive consumers: ave: " + inactiveConsumerStats[1] + ", max: " + inactiveConsumerStats[0] + ", multiplier: " + (inactiveConsumerStats[0] / inactiveConsumerStats[1])); - double[] statsWithActive = produceMessages(destination, 500, 10, session, producer, addConsumerSignal); - - LOG.info(" with concurrent activate, ave: " + statsWithActive[1] + ", max: " + statsWithActive[0] + ", multiplier: " + (statsWithActive[0]/ statsWithActive[1])); - - while(consumers.size() < consumersToActivate) { - TimeUnit.SECONDS.sleep(2); - } - - long timeToFirstAccumulator = 0; - for (TimedMessageListener listener : consumers.values()) { - long time = listener.getFirstReceipt(); - timeToFirstAccumulator += time; - LOG.info("Time to first " + time); - } - LOG.info("Ave time to first message =" + timeToFirstAccumulator/consumers.size()); - - for (TimedMessageListener listener : consumers.values()) { - LOG.info("Ave batch receipt time: " + listener.waitForReceivedLimit(10000) + " max receipt: " + listener.maxReceiptTime); - } - - //assertTrue("max (" + statsWithActive[0] + ") within reasonable multiplier of ave (" + statsWithActive[1] + ")", - // statsWithActive[0] < 5 * statsWithActive[1]); - - // compare no active to active - LOG.info("Ave send time with active: " + statsWithActive[1] - + " as multiplier of ave with none active: " + inactiveConsumerStats[1] - + ", multiplier=" + (statsWithActive[1]/inactiveConsumerStats[1])); - - assertTrue("Ave send time with active: " + statsWithActive[1] - + " within reasonable multpler of ave with none active: " + inactiveConsumerStats[1] - + ", multiplier " + (statsWithActive[1]/inactiveConsumerStats[1]), - statsWithActive[1] < 15 * inactiveConsumerStats[1]); - } - - public void x_testSendWithInactiveAndActiveConsumers() throws Exception { - Destination destination = createDestination(); - ConnectionFactory factory = createConnectionFactory(); - startInactiveConsumers(factory, destination); - - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - - final int toSend = 100; - final int numIterations = 5; - - double[] noConsumerStats = produceMessages(destination, toSend, numIterations, session, producer, null); - - startConsumers(factory, destination); - LOG.info("Activated consumer"); - - double[] withConsumerStats = produceMessages(destination, toSend, numIterations, session, producer, null); - - LOG.info("With consumer: " + withConsumerStats[1] + " , with noConsumer: " + noConsumerStats[1] - + ", multiplier: " + (withConsumerStats[1]/noConsumerStats[1])); - final int reasonableMultiplier = 15; // not so reasonable but improving - assertTrue("max X times as slow with consumer: " + withConsumerStats[1] + ", with no Consumer: " - + noConsumerStats[1] + ", multiplier: " + (withConsumerStats[1]/noConsumerStats[1]), - withConsumerStats[1] < noConsumerStats[1] * reasonableMultiplier); - - final int toReceive = toSend * numIterations * consumerCount * 2; - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("count: " + allMessagesList.getMessageCount()); - return toReceive == allMessagesList.getMessageCount(); - } - }, 60 * 1000); - - assertEquals("got all messages", toReceive, allMessagesList.getMessageCount()); - } - - private MessageProducer createMessageProducer(Session session, Destination destination) throws JMSException { - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - return producer; - } - - private void startInactiveConsumers(ConnectionFactory factory, Destination destination) throws Exception { - // create off line consumers - startConsumers(factory, destination); - for (Connection connection: connections) { - connection.close(); - } - connections.clear(); - consumers.clear(); - } - - protected void startConsumers(ConnectionFactory factory, Destination dest) throws Exception { - MessageConsumer consumer; - for (int i = 0; i < consumerCount; i++) { - TimedMessageListener list = new TimedMessageListener(); - consumer = createDurableSubscriber(factory.createConnection(), dest, "consumer" + (i + 1)); - consumer.setMessageListener(list); - consumers.put(consumer, list); - } - } - - protected TopicSubscriber createDurableSubscriber(Connection conn, Destination dest, String name) throws Exception { - conn.setClientID(name); - connections.add(conn); - conn.start(); - - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - final TopicSubscriber consumer = sess.createDurableSubscriber((javax.jms.Topic)dest, name); - - return consumer; - } - - /** - * @return max and ave send time - * @throws Exception - */ - private double[] produceMessages(Destination destination, - final int toSend, - final int numIterations, - Session session, - MessageProducer producer, - CountDownLatch addConsumerSignal) throws Exception { - long start; - long count = 0; - double batchMax = 0, max = 0, sum = 0; - for (int i=0; i iter = connections.iterator(); iter.hasNext();) { - Connection conn = iter.next(); + // periodically start a durable sub that has a backlog + final int consumersToActivate = 5; + final CountDownLatch addConsumerSignal = new CountDownLatch(1); + Executors.newCachedThreadPool(new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + return new Thread(r, "ActivateConsumer" + this); + } + }).execute(new Runnable() { + @Override + public void run() { try { - conn.close(); - } catch (Throwable e) { + MessageConsumer consumer = null; + for (int i = 0; i < consumersToActivate; i++) { + LOG.info("Waiting for add signal from producer..."); + addConsumerSignal.await(30, TimeUnit.MINUTES); + TimedMessageListener listener = new TimedMessageListener(); + consumer = createDurableSubscriber(factory.createConnection(), destination, "consumer" + (i + 1)); + LOG.info("Created consumer " + consumer); + consumer.setMessageListener(listener); + consumers.put(consumer, listener); + } } - } - broker.stop(); - allMessagesList.flushMessages(); - consumers.clear(); - super.tearDown(); - } + catch (Exception e) { + LOG.error("failed to start consumer", e); + } + } + }); - protected BrokerService createBroker() throws Exception { - BrokerService brokerService = new BrokerService(); - brokerService.setEnableStatistics(false); - brokerService.addConnector("tcp://0.0.0.0:0"); - brokerService.setDeleteAllMessagesOnStartup(true); + double[] statsWithActive = produceMessages(destination, 500, 10, session, producer, addConsumerSignal); - PolicyEntry policy = new PolicyEntry(); - policy.setPrioritizedMessages(true); - policy.setMaxPageSize(500); + LOG.info(" with concurrent activate, ave: " + statsWithActive[1] + ", max: " + statsWithActive[0] + ", multiplier: " + (statsWithActive[0] / statsWithActive[1])); - StorePendingDurableSubscriberMessageStoragePolicy durableSubPending = - new StorePendingDurableSubscriberMessageStoragePolicy(); - durableSubPending.setImmediatePriorityDispatch(true); - durableSubPending.setUseCache(true); - policy.setPendingDurableSubscriberPolicy(durableSubPending); + while (consumers.size() < consumersToActivate) { + TimeUnit.SECONDS.sleep(2); + } - PolicyMap policyMap = new PolicyMap(); - policyMap.setDefaultEntry(policy); - brokerService.setDestinationPolicy(policyMap); + long timeToFirstAccumulator = 0; + for (TimedMessageListener listener : consumers.values()) { + long time = listener.getFirstReceipt(); + timeToFirstAccumulator += time; + LOG.info("Time to first " + time); + } + LOG.info("Ave time to first message =" + timeToFirstAccumulator / consumers.size()); -// if (false) { -// // external mysql works a lot faster -// // -// JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); -// BasicDataSource ds = new BasicDataSource(); -// com.mysql.jdbc.Driver d = new com.mysql.jdbc.Driver(); -// ds.setDriverClassName("com.mysql.jdbc.Driver"); -// ds.setUrl("jdbc:mysql://localhost/activemq?relaxAutoCommit=true"); -// ds.setMaxActive(200); -// ds.setUsername("root"); -// ds.setPassword(""); -// ds.setPoolPreparedStatements(true); -// jdbc.setDataSource(ds); -// brokerService.setPersistenceAdapter(jdbc); + for (TimedMessageListener listener : consumers.values()) { + LOG.info("Ave batch receipt time: " + listener.waitForReceivedLimit(10000) + " max receipt: " + listener.maxReceiptTime); + } + + //assertTrue("max (" + statsWithActive[0] + ") within reasonable multiplier of ave (" + statsWithActive[1] + ")", + // statsWithActive[0] < 5 * statsWithActive[1]); + + // compare no active to active + LOG.info("Ave send time with active: " + statsWithActive[1] + " as multiplier of ave with none active: " + inactiveConsumerStats[1] + ", multiplier=" + (statsWithActive[1] / inactiveConsumerStats[1])); + + assertTrue("Ave send time with active: " + statsWithActive[1] + " within reasonable multpler of ave with none active: " + inactiveConsumerStats[1] + ", multiplier " + (statsWithActive[1] / inactiveConsumerStats[1]), statsWithActive[1] < 15 * inactiveConsumerStats[1]); + } + + public void x_testSendWithInactiveAndActiveConsumers() throws Exception { + Destination destination = createDestination(); + ConnectionFactory factory = createConnectionFactory(); + startInactiveConsumers(factory, destination); + + Connection connection = factory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + + final int toSend = 100; + final int numIterations = 5; + + double[] noConsumerStats = produceMessages(destination, toSend, numIterations, session, producer, null); + + startConsumers(factory, destination); + LOG.info("Activated consumer"); + + double[] withConsumerStats = produceMessages(destination, toSend, numIterations, session, producer, null); + + LOG.info("With consumer: " + withConsumerStats[1] + " , with noConsumer: " + noConsumerStats[1] + ", multiplier: " + (withConsumerStats[1] / noConsumerStats[1])); + final int reasonableMultiplier = 15; // not so reasonable but improving + assertTrue("max X times as slow with consumer: " + withConsumerStats[1] + ", with no Consumer: " + noConsumerStats[1] + ", multiplier: " + (withConsumerStats[1] / noConsumerStats[1]), withConsumerStats[1] < noConsumerStats[1] * reasonableMultiplier); + + final int toReceive = toSend * numIterations * consumerCount * 2; + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("count: " + allMessagesList.getMessageCount()); + return toReceive == allMessagesList.getMessageCount(); + } + }, 60 * 1000); + + assertEquals("got all messages", toReceive, allMessagesList.getMessageCount()); + } + + private MessageProducer createMessageProducer(Session session, Destination destination) throws JMSException { + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + return producer; + } + + private void startInactiveConsumers(ConnectionFactory factory, Destination destination) throws Exception { + // create off line consumers + startConsumers(factory, destination); + for (Connection connection : connections) { + connection.close(); + } + connections.clear(); + consumers.clear(); + } + + protected void startConsumers(ConnectionFactory factory, Destination dest) throws Exception { + MessageConsumer consumer; + for (int i = 0; i < consumerCount; i++) { + TimedMessageListener list = new TimedMessageListener(); + consumer = createDurableSubscriber(factory.createConnection(), dest, "consumer" + (i + 1)); + consumer.setMessageListener(list); + consumers.put(consumer, list); + } + } + + protected TopicSubscriber createDurableSubscriber(Connection conn, Destination dest, String name) throws Exception { + conn.setClientID(name); + connections.add(conn); + conn.start(); + + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + final TopicSubscriber consumer = sess.createDurableSubscriber((javax.jms.Topic) dest, name); + + return consumer; + } + + /** + * @return max and ave send time + * @throws Exception + */ + private double[] produceMessages(Destination destination, + final int toSend, + final int numIterations, + Session session, + MessageProducer producer, + CountDownLatch addConsumerSignal) throws Exception { + long start; + long count = 0; + double batchMax = 0, max = 0, sum = 0; + for (int i = 0; i < numIterations; i++) { + start = System.currentTimeMillis(); + for (int j = 0; j < toSend; j++) { + long singleSendstart = System.currentTimeMillis(); + TextMessage msg = createTextMessage(session, "" + j); + // rotate + int priority = ((int) count % 10); + producer.send(msg, DeliveryMode.PERSISTENT, priority, 0); + max = Math.max(max, (System.currentTimeMillis() - singleSendstart)); + if (++count % 500 == 0) { + if (addConsumerSignal != null) { + addConsumerSignal.countDown(); + LOG.info("Signalled add consumer"); + } + } + ; + if (count % 5000 == 0) { + LOG.info("Sent " + count + ", singleSendMax:" + max); + } + + } + long duration = System.currentTimeMillis() - start; + batchMax = Math.max(batchMax, duration); + sum += duration; + LOG.info("Iteration " + i + ", sent " + toSend + ", time: " + duration + ", batchMax:" + batchMax + ", singleSendMax:" + max); + } + + LOG.info("Sent: " + toSend * numIterations + ", batchMax: " + batchMax + " singleSendMax: " + max); + return new double[]{batchMax, sum / numIterations}; + } + + protected TextMessage createTextMessage(Session session, String initText) throws Exception { + TextMessage msg = session.createTextMessage(); + + // Pad message text + if (initText.length() < messageSize) { + char[] data = new char[messageSize - initText.length()]; + Arrays.fill(data, '*'); + String str = new String(data); + msg.setText(initText + str); + + // Do not pad message text + } + else { + msg.setText(initText); + } + + return msg; + } + + @Override + @Before + public void setUp() throws Exception { + topic = true; + super.setUp(); + broker = createBroker(); + broker.start(); + } + + @Override + @After + public void tearDown() throws Exception { + for (Iterator iter = connections.iterator(); iter.hasNext(); ) { + Connection conn = iter.next(); + try { + conn.close(); + } + catch (Throwable e) { + } + } + broker.stop(); + allMessagesList.flushMessages(); + consumers.clear(); + super.tearDown(); + } + + protected BrokerService createBroker() throws Exception { + BrokerService brokerService = new BrokerService(); + brokerService.setEnableStatistics(false); + brokerService.addConnector("tcp://0.0.0.0:0"); + brokerService.setDeleteAllMessagesOnStartup(true); + + PolicyEntry policy = new PolicyEntry(); + policy.setPrioritizedMessages(true); + policy.setMaxPageSize(500); + + StorePendingDurableSubscriberMessageStoragePolicy durableSubPending = new StorePendingDurableSubscriberMessageStoragePolicy(); + durableSubPending.setImmediatePriorityDispatch(true); + durableSubPending.setUseCache(true); + policy.setPendingDurableSubscriberPolicy(durableSubPending); + + PolicyMap policyMap = new PolicyMap(); + policyMap.setDefaultEntry(policy); + brokerService.setDestinationPolicy(policyMap); + + // if (false) { + // // external mysql works a lot faster + // // + // JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); + // BasicDataSource ds = new BasicDataSource(); + // com.mysql.jdbc.Driver d = new com.mysql.jdbc.Driver(); + // ds.setDriverClassName("com.mysql.jdbc.Driver"); + // ds.setUrl("jdbc:mysql://localhost/activemq?relaxAutoCommit=true"); + // ds.setMaxActive(200); + // ds.setUsername("root"); + // ds.setPassword(""); + // ds.setPoolPreparedStatements(true); + // jdbc.setDataSource(ds); + // brokerService.setPersistenceAdapter(jdbc); /* add mysql bits to the pom in the testing dependencies @@ -379,109 +373,113 @@ public class ConcurrentProducerDurableConsumerTest extends TestSupport { test */ -// } else { - setPersistenceAdapter(brokerService, persistenceAdapterChoice); -// } - return brokerService; - } + // } else { + setPersistenceAdapter(brokerService, persistenceAdapterChoice); + // } + return brokerService; + } - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory( - broker.getTransportConnectors().get(0).getPublishableConnectString()); - ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); - prefetchPolicy.setAll(1); - factory.setPrefetchPolicy(prefetchPolicy); + @Override + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString()); + ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); + prefetchPolicy.setAll(1); + factory.setPrefetchPolicy(prefetchPolicy); - factory.setDispatchAsync(true); - return factory; - } + factory.setDispatchAsync(true); + return factory; + } - class TimedMessageListener implements MessageListener { - final int batchSize = 1000; - CountDownLatch firstReceiptLatch = new CountDownLatch(1); - long mark = System.currentTimeMillis(); - long firstReceipt = 0L; - long receiptAccumulator = 0; - long batchReceiptAccumulator = 0; - long maxReceiptTime = 0; - AtomicLong count = new AtomicLong(0); - Map messageLists = new ConcurrentHashMap(new HashMap()); + class TimedMessageListener implements MessageListener { - @Override - public void onMessage(Message message) { - final long current = System.currentTimeMillis(); - final long duration = current - mark; - receiptAccumulator += duration; - int priority = 0; - try { - priority = message.getJMSPriority(); - } catch (JMSException ignored) {} - if (!messageLists.containsKey(priority)) { - MessageIdList perPriorityList = new MessageIdList(); - perPriorityList.setParent(allMessagesList); - messageLists.put(priority, perPriorityList); + final int batchSize = 1000; + CountDownLatch firstReceiptLatch = new CountDownLatch(1); + long mark = System.currentTimeMillis(); + long firstReceipt = 0L; + long receiptAccumulator = 0; + long batchReceiptAccumulator = 0; + long maxReceiptTime = 0; + AtomicLong count = new AtomicLong(0); + Map messageLists = new ConcurrentHashMap(new HashMap()); + + @Override + public void onMessage(Message message) { + final long current = System.currentTimeMillis(); + final long duration = current - mark; + receiptAccumulator += duration; + int priority = 0; + try { + priority = message.getJMSPriority(); + } + catch (JMSException ignored) { + } + if (!messageLists.containsKey(priority)) { + MessageIdList perPriorityList = new MessageIdList(); + perPriorityList.setParent(allMessagesList); + messageLists.put(priority, perPriorityList); + } + messageLists.get(priority).onMessage(message); + if (count.incrementAndGet() == 1) { + firstReceipt = duration; + firstReceiptLatch.countDown(); + LOG.info("First receipt in " + firstReceipt + "ms"); + } + else if (count.get() % batchSize == 0) { + LOG.info("Consumed " + count.get() + " in " + batchReceiptAccumulator + "ms" + ", priority:" + priority); + batchReceiptAccumulator = 0; + } + maxReceiptTime = Math.max(maxReceiptTime, duration); + receiptAccumulator += duration; + batchReceiptAccumulator += duration; + mark = current; + } + + long getMessageCount() { + return count.get(); + } + + long getFirstReceipt() throws Exception { + firstReceiptLatch.await(30, TimeUnit.SECONDS); + return firstReceipt; + } + + public long waitForReceivedLimit(long limit) throws Exception { + final long expiry = System.currentTimeMillis() + 30 * 60 * 1000; + while (count.get() < limit) { + if (System.currentTimeMillis() > expiry) { + throw new RuntimeException("Expired waiting for X messages, " + limit); } - messageLists.get(priority).onMessage(message); - if (count.incrementAndGet() == 1) { - firstReceipt = duration; - firstReceiptLatch.countDown(); - LOG.info("First receipt in " + firstReceipt + "ms"); - } else if (count.get() % batchSize == 0) { - LOG.info("Consumed " + count.get() + " in " + batchReceiptAccumulator + "ms" + ", priority:" + priority); - batchReceiptAccumulator=0; + TimeUnit.SECONDS.sleep(2); + String missing = findFirstMissingMessage(); + if (missing != null) { + LOG.info("first missing = " + missing); + throw new RuntimeException("We have a missing message. " + missing); } - maxReceiptTime = Math.max(maxReceiptTime, duration); - receiptAccumulator += duration; - batchReceiptAccumulator += duration; - mark = current; - } - long getMessageCount() { - return count.get(); - } - - long getFirstReceipt() throws Exception { - firstReceiptLatch.await(30, TimeUnit.SECONDS); - return firstReceipt; - } - - public long waitForReceivedLimit(long limit) throws Exception { - final long expiry = System.currentTimeMillis() + 30*60*1000; - while (count.get() < limit) { - if (System.currentTimeMillis() > expiry) { - throw new RuntimeException("Expired waiting for X messages, " + limit); - } - TimeUnit.SECONDS.sleep(2); - String missing = findFirstMissingMessage(); - if (missing != null) { - LOG.info("first missing = " + missing); - throw new RuntimeException("We have a missing message. " + missing); - } + } + return receiptAccumulator / (limit / batchSize); + } + private String findFirstMissingMessage() { + MessageId current = new MessageId(); + for (MessageIdList priorityList : messageLists.values()) { + MessageId previous = null; + for (String id : priorityList.getMessageIds()) { + current.setValue(id); + if (previous == null) { + previous = current.copy(); + } + else { + if (current.getProducerSequenceId() - 1 != previous.getProducerSequenceId() && current.getProducerSequenceId() - 10 != previous.getProducerSequenceId()) { + return "Missing next after: " + previous + ", got: " + current; + } + else { + previous = current.copy(); + } + } } - return receiptAccumulator/(limit/batchSize); - } - - private String findFirstMissingMessage() { - MessageId current = new MessageId(); - for (MessageIdList priorityList : messageLists.values()) { - MessageId previous = null; - for (String id : priorityList.getMessageIds()) { - current.setValue(id); - if (previous == null) { - previous = current.copy(); - } else { - if (current.getProducerSequenceId() - 1 != previous.getProducerSequenceId() && - current.getProducerSequenceId() - 10 != previous.getProducerSequenceId()) { - return "Missing next after: " + previous + ", got: " + current; - } else { - previous = current.copy(); - } - } - } - } - return null; - } - } + } + return null; + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConcurrentProducerQueueConsumerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConcurrentProducerQueueConsumerTest.java index 931fb55f08..ab319f5bc8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConcurrentProducerQueueConsumerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConcurrentProducerQueueConsumerTest.java @@ -55,377 +55,368 @@ import org.apache.activemq.util.Wait; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class ConcurrentProducerQueueConsumerTest extends TestSupport -{ - private static final Logger LOG = LoggerFactory.getLogger(ConcurrentProducerQueueConsumerTest.class); +public class ConcurrentProducerQueueConsumerTest extends TestSupport { - protected List connections = Collections.synchronizedList(new ArrayList()); - protected Map consumers = - new HashMap(); - protected MessageIdList allMessagesList = new MessageIdList(); + private static final Logger LOG = LoggerFactory.getLogger(ConcurrentProducerQueueConsumerTest.class); - private BrokerService broker; - private final int consumerCount = 5; - private final int messageSize = 1024; - private final int NUM_MESSAGES = 500; - private final int ITERATIONS = 10; + protected List connections = Collections.synchronizedList(new ArrayList()); + protected Map consumers = new HashMap(); + protected MessageIdList allMessagesList = new MessageIdList(); - private int expectedQueueDeliveries = 0; + private BrokerService broker; + private final int consumerCount = 5; + private final int messageSize = 1024; + private final int NUM_MESSAGES = 500; + private final int ITERATIONS = 10; - public void initCombosForTestSendRateWithActivatingConsumers() throws Exception { - addCombinationValues("defaultPersistenceAdapter", - new Object[]{PersistenceAdapterChoice.KahaDB, PersistenceAdapterChoice.LevelDB, + private int expectedQueueDeliveries = 0; + + public void initCombosForTestSendRateWithActivatingConsumers() throws Exception { + addCombinationValues("defaultPersistenceAdapter", new Object[]{PersistenceAdapterChoice.KahaDB, PersistenceAdapterChoice.LevelDB, /* too slow for hudson - PersistenceAdapterChoice.JDBC,*/ - PersistenceAdapterChoice.MEM}); - } + PersistenceAdapterChoice.MEM}); + } - public void testSendRateWithActivatingConsumers() throws Exception { - final Destination destination = createDestination(); - final ConnectionFactory factory = createConnectionFactory(); + public void testSendRateWithActivatingConsumers() throws Exception { + final Destination destination = createDestination(); + final ConnectionFactory factory = createConnectionFactory(); - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = createMessageProducer(session, destination); + Connection connection = factory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = createMessageProducer(session, destination); - // preload the queue before adding any consumers - double[] noConsumerStats = produceMessages(destination, NUM_MESSAGES, ITERATIONS, session, producer, null); - LOG.info("With no consumers: ave: " + noConsumerStats[1] + ", max: " + - noConsumerStats[0] + ", multiplier: " + (noConsumerStats[0]/noConsumerStats[1])); - expectedQueueDeliveries = NUM_MESSAGES * ITERATIONS; + // preload the queue before adding any consumers + double[] noConsumerStats = produceMessages(destination, NUM_MESSAGES, ITERATIONS, session, producer, null); + LOG.info("With no consumers: ave: " + noConsumerStats[1] + ", max: " + + noConsumerStats[0] + ", multiplier: " + (noConsumerStats[0] / noConsumerStats[1])); + expectedQueueDeliveries = NUM_MESSAGES * ITERATIONS; - // periodically start a queue consumer - final int consumersToActivate = 5; - final CountDownLatch addConsumerSignal = new CountDownLatch(1); - Executors.newCachedThreadPool(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "ActivateConsumer" + this); + // periodically start a queue consumer + final int consumersToActivate = 5; + final CountDownLatch addConsumerSignal = new CountDownLatch(1); + Executors.newCachedThreadPool(new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + return new Thread(r, "ActivateConsumer" + this); + } + }).execute(new Runnable() { + @Override + public void run() { + try { + MessageConsumer consumer = null; + for (int i = 0; i < consumersToActivate; i++) { + LOG.info("Waiting for add signal from producer..."); + addConsumerSignal.await(30, TimeUnit.MINUTES); + TimedMessageListener listener = new TimedMessageListener(); + consumer = createConsumer(factory.createConnection(), destination); + LOG.info("Created consumer " + consumer); + consumer.setMessageListener(listener); + consumers.put(consumer, listener); + } } - }).execute(new Runnable() { - @Override - public void run() { - try { - MessageConsumer consumer = null; - for (int i = 0; i < consumersToActivate; i++) { - LOG.info("Waiting for add signal from producer..."); - addConsumerSignal.await(30, TimeUnit.MINUTES); - TimedMessageListener listener = new TimedMessageListener(); - consumer = createConsumer(factory.createConnection(), destination); - LOG.info("Created consumer " + consumer); - consumer.setMessageListener(listener); - consumers.put(consumer, listener); - } - } catch (Exception e) { - LOG.error("failed to start consumer", e); - } + catch (Exception e) { + LOG.error("failed to start consumer", e); } - }); + } + }); - // Collect statistics when there are active consumers. - double[] statsWithActive = - produceMessages(destination, NUM_MESSAGES, ITERATIONS, session, producer, addConsumerSignal); - expectedQueueDeliveries += NUM_MESSAGES * ITERATIONS; + // Collect statistics when there are active consumers. + double[] statsWithActive = produceMessages(destination, NUM_MESSAGES, ITERATIONS, session, producer, addConsumerSignal); + expectedQueueDeliveries += NUM_MESSAGES * ITERATIONS; - LOG.info(" with concurrent activate, ave: " + statsWithActive[1] + ", max: " + - statsWithActive[0] + ", multiplier: " + (statsWithActive[0]/ statsWithActive[1])); + LOG.info(" with concurrent activate, ave: " + statsWithActive[1] + ", max: " + + statsWithActive[0] + ", multiplier: " + (statsWithActive[0] / statsWithActive[1])); - assertTrue(Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return consumers.size() == consumersToActivate; - } - })); + assertTrue(Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return consumers.size() == consumersToActivate; + } + })); - long timeToFirstAccumulator = 0; - for (TimedMessageListener listener : consumers.values()) { - long time = listener.getFirstReceipt(); - timeToFirstAccumulator += time; - LOG.info("Time to first " + time); - } - LOG.info("Ave time to first message =" + timeToFirstAccumulator/consumers.size()); + long timeToFirstAccumulator = 0; + for (TimedMessageListener listener : consumers.values()) { + long time = listener.getFirstReceipt(); + timeToFirstAccumulator += time; + LOG.info("Time to first " + time); + } + LOG.info("Ave time to first message =" + timeToFirstAccumulator / consumers.size()); - for (TimedMessageListener listener : consumers.values()) { - LOG.info("Ave batch receipt time: " + listener.waitForReceivedLimit(expectedQueueDeliveries) + + for (TimedMessageListener listener : consumers.values()) { + LOG.info("Ave batch receipt time: " + listener.waitForReceivedLimit(expectedQueueDeliveries) + " max receipt: " + listener.maxReceiptTime); - } + } - // compare no active to active - LOG.info("Ave send time with active: " + statsWithActive[1] - + " as multiplier of ave with none active: " + noConsumerStats[1] - + ", multiplier=" + (statsWithActive[1]/noConsumerStats[1])); + // compare no active to active + LOG.info("Ave send time with active: " + statsWithActive[1] + " as multiplier of ave with none active: " + noConsumerStats[1] + ", multiplier=" + (statsWithActive[1] / noConsumerStats[1])); - assertTrue("Ave send time with active: " + statsWithActive[1] - + " within reasonable multpler of ave with none active: " + noConsumerStats[1] - + ", multiplier " + (statsWithActive[1]/noConsumerStats[1]), - statsWithActive[1] < 15 * noConsumerStats[1]); - } + assertTrue("Ave send time with active: " + statsWithActive[1] + " within reasonable multpler of ave with none active: " + noConsumerStats[1] + ", multiplier " + (statsWithActive[1] / noConsumerStats[1]), statsWithActive[1] < 15 * noConsumerStats[1]); + } - public void x_initCombosForTestSendWithInactiveAndActiveConsumers() throws Exception { - addCombinationValues("defaultPersistenceAdapter", - new Object[]{PersistenceAdapterChoice.KahaDB, PersistenceAdapterChoice.LevelDB, + public void x_initCombosForTestSendWithInactiveAndActiveConsumers() throws Exception { + addCombinationValues("defaultPersistenceAdapter", new Object[]{PersistenceAdapterChoice.KahaDB, PersistenceAdapterChoice.LevelDB, /* too slow for hudson - PersistenceAdapterChoice.JDBC,*/ - PersistenceAdapterChoice.MEM}); - } + PersistenceAdapterChoice.MEM}); + } - public void x_testSendWithInactiveAndActiveConsumers() throws Exception { - Destination destination = createDestination(); - ConnectionFactory factory = createConnectionFactory(); + public void x_testSendWithInactiveAndActiveConsumers() throws Exception { + Destination destination = createDestination(); + ConnectionFactory factory = createConnectionFactory(); - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); + Connection connection = factory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); - final int toSend = 100; - final int numIterations = 5; + final int toSend = 100; + final int numIterations = 5; - double[] noConsumerStats = produceMessages(destination, toSend, numIterations, session, producer, null); + double[] noConsumerStats = produceMessages(destination, toSend, numIterations, session, producer, null); - startConsumers(factory, destination); - LOG.info("Activated consumer"); + startConsumers(factory, destination); + LOG.info("Activated consumer"); - double[] withConsumerStats = produceMessages(destination, toSend, numIterations, session, producer, null); + double[] withConsumerStats = produceMessages(destination, toSend, numIterations, session, producer, null); - LOG.info("With consumer: " + withConsumerStats[1] + " , with noConsumer: " + noConsumerStats[1] - + ", multiplier: " + (withConsumerStats[1]/noConsumerStats[1])); - final int reasonableMultiplier = 15; // not so reasonable but improving - assertTrue("max X times as slow with consumer: " + withConsumerStats[1] + ", with no Consumer: " - + noConsumerStats[1] + ", multiplier: " + (withConsumerStats[1]/noConsumerStats[1]), - withConsumerStats[1] < noConsumerStats[1] * reasonableMultiplier); + LOG.info("With consumer: " + withConsumerStats[1] + " , with noConsumer: " + noConsumerStats[1] + ", multiplier: " + (withConsumerStats[1] / noConsumerStats[1])); + final int reasonableMultiplier = 15; // not so reasonable but improving + assertTrue("max X times as slow with consumer: " + withConsumerStats[1] + ", with no Consumer: " + noConsumerStats[1] + ", multiplier: " + (withConsumerStats[1] / noConsumerStats[1]), withConsumerStats[1] < noConsumerStats[1] * reasonableMultiplier); - final int toReceive = toSend * numIterations * consumerCount * 2; - Wait.waitFor(new Wait.Condition() { - public boolean isSatisified() throws Exception { - LOG.info("count: " + allMessagesList.getMessageCount()); - return toReceive == allMessagesList.getMessageCount(); + final int toReceive = toSend * numIterations * consumerCount * 2; + Wait.waitFor(new Wait.Condition() { + public boolean isSatisified() throws Exception { + LOG.info("count: " + allMessagesList.getMessageCount()); + return toReceive == allMessagesList.getMessageCount(); + } + }, 60 * 1000); + + assertEquals("got all messages", toReceive, allMessagesList.getMessageCount()); + } + + private MessageProducer createMessageProducer(Session session, Destination destination) throws JMSException { + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + return producer; + } + + protected void startConsumers(ConnectionFactory factory, Destination dest) throws Exception { + MessageConsumer consumer; + for (int i = 0; i < consumerCount; i++) { + TimedMessageListener list = new TimedMessageListener(); + consumer = createConsumer(factory.createConnection(), dest); + consumer.setMessageListener(list); + consumers.put(consumer, list); + } + } + + protected MessageConsumer createConsumer(Connection conn, Destination dest) throws Exception { + connections.add(conn); + conn.start(); + + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + final MessageConsumer consumer = sess.createConsumer(dest); + + return consumer; + } + + /** + * @return max and average send time + * @throws Exception + */ + private double[] produceMessages(Destination destination, + final int toSend, + final int numIterations, + Session session, + MessageProducer producer, + CountDownLatch addConsumerSignal) throws Exception { + long start; + long count = 0; + double batchMax = 0, max = 0, sum = 0; + + for (int i = 0; i < numIterations; i++) { + start = System.currentTimeMillis(); + for (int j = 0; j < toSend; j++) { + long singleSendstart = System.currentTimeMillis(); + TextMessage msg = createTextMessage(session, "" + j); + // rotate + int priority = ((int) count % 10); + producer.send(msg, DeliveryMode.PERSISTENT, priority, 0); + max = Math.max(max, (System.currentTimeMillis() - singleSendstart)); + if (++count % 500 == 0) { + if (addConsumerSignal != null) { + addConsumerSignal.countDown(); + LOG.info("Signalled add consumer"); + } } - }, 60 * 1000); - - assertEquals("got all messages", toReceive, allMessagesList.getMessageCount()); - } - - private MessageProducer createMessageProducer(Session session, Destination destination) throws JMSException { - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - return producer; - } - - protected void startConsumers(ConnectionFactory factory, Destination dest) throws Exception { - MessageConsumer consumer; - for (int i = 0; i < consumerCount; i++) { - TimedMessageListener list = new TimedMessageListener(); - consumer = createConsumer(factory.createConnection(), dest); - consumer.setMessageListener(list); - consumers.put(consumer, list); - } - } - - protected MessageConsumer createConsumer(Connection conn, Destination dest) throws Exception { - connections.add(conn); - conn.start(); - - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageConsumer consumer = sess.createConsumer(dest); - - return consumer; - } - - /** - * @return max and average send time - * @throws Exception - */ - private double[] produceMessages(Destination destination, - final int toSend, - final int numIterations, - Session session, - MessageProducer producer, - CountDownLatch addConsumerSignal) throws Exception { - long start; - long count = 0; - double batchMax = 0, max = 0, sum = 0; - - for (int i=0; i iter = connections.iterator(); iter.hasNext();) { - Connection conn = iter.next(); - try { - conn.close(); - } catch (Throwable e) { - } - } - broker.stop(); - allMessagesList.flushMessages(); - consumers.clear(); - super.tearDown(); - } - - protected BrokerService createBroker() throws Exception { - BrokerService brokerService = new BrokerService(); - brokerService.setEnableStatistics(false); - brokerService.addConnector("tcp://0.0.0.0:0"); - brokerService.setDeleteAllMessagesOnStartup(true); - - PolicyEntry policy = new PolicyEntry(); - policy.setPrioritizedMessages(true); - policy.setMaxPageSize(500); - - PolicyMap policyMap = new PolicyMap(); - policyMap.setDefaultEntry(policy); - brokerService.setDestinationPolicy(policyMap); - setDefaultPersistenceAdapter(brokerService); - - return brokerService; - } - - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory( - broker.getTransportConnectors().get(0).getPublishableConnectString()); - ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); - prefetchPolicy.setAll(1); - factory.setPrefetchPolicy(prefetchPolicy); - - factory.setDispatchAsync(true); - return factory; - } - - public static Test suite() { - return suite(ConcurrentProducerQueueConsumerTest.class); - } - - static class TimedMessageListener implements MessageListener { - - static final AtomicLong count = new AtomicLong(0); - - final int batchSize = 1000; - final CountDownLatch firstReceiptLatch = new CountDownLatch(1); - - long mark = System.currentTimeMillis(); - long firstReceipt = 0L; - long receiptAccumulator = 0; - long batchReceiptAccumulator = 0; - long maxReceiptTime = 0; - - final Map messageLists = - new ConcurrentHashMap(new HashMap()); - - @Override - public void onMessage(Message message) { - final long current = System.currentTimeMillis(); - final long duration = current - mark; - receiptAccumulator += duration; - int priority = 0; - - try { - priority = message.getJMSPriority(); - } catch (JMSException ignored) {} - - if (!messageLists.containsKey(priority)) { - messageLists.put(priority, new MessageIdList()); - } - messageLists.get(priority).onMessage(message); - - if (count.incrementAndGet() == 1) { - firstReceipt = duration; - firstReceiptLatch.countDown(); - LOG.info("First receipt in " + firstReceipt + "ms"); - } else if (count.get() % batchSize == 0) { - LOG.info("Consumed " + count.get() + " in " + batchReceiptAccumulator + "ms" + ", priority:" + priority); - batchReceiptAccumulator=0; + ; + if (count % 5000 == 0) { + LOG.info("Sent " + count + ", singleSendMax:" + max); } - maxReceiptTime = Math.max(maxReceiptTime, duration); - receiptAccumulator += duration; - batchReceiptAccumulator += duration; - mark = current; - } + } + long duration = System.currentTimeMillis() - start; + batchMax = Math.max(batchMax, duration); + sum += duration; + LOG.info("Iteration " + i + ", sent " + toSend + ", time: " + duration + ", batchMax:" + batchMax + ", singleSendMax:" + max); + } - long getMessageCount() { - return count.get(); - } + LOG.info("Sent: " + toSend * numIterations + ", batchMax: " + batchMax + " singleSendMax: " + max); + return new double[]{batchMax, sum / numIterations}; + } - long getFirstReceipt() throws Exception { - firstReceiptLatch.await(30, TimeUnit.SECONDS); - return firstReceipt; - } + protected TextMessage createTextMessage(Session session, String initText) throws Exception { + TextMessage msg = session.createTextMessage(); - public long waitForReceivedLimit(long limit) throws Exception { - final long expiry = System.currentTimeMillis() + 30*60*1000; - while (count.get() < limit) { - if (System.currentTimeMillis() > expiry) { - throw new RuntimeException("Expired waiting for X messages, " + limit); - } - TimeUnit.SECONDS.sleep(2); - String missing = findFirstMissingMessage(); - if (missing != null) { - LOG.info("first missing = " + missing); - throw new RuntimeException("We have a missing message. " + missing); - } + // Pad message text + if (initText.length() < messageSize) { + char[] data = new char[messageSize - initText.length()]; + Arrays.fill(data, '*'); + String str = new String(data); + msg.setText(initText + str); + // Do not pad message text + } + else { + msg.setText(initText); + } + + return msg; + } + + @Override + protected void setUp() throws Exception { + topic = false; + super.setUp(); + broker = createBroker(); + broker.start(); + } + + @Override + protected void tearDown() throws Exception { + for (Iterator iter = connections.iterator(); iter.hasNext(); ) { + Connection conn = iter.next(); + try { + conn.close(); + } + catch (Throwable e) { + } + } + broker.stop(); + allMessagesList.flushMessages(); + consumers.clear(); + super.tearDown(); + } + + protected BrokerService createBroker() throws Exception { + BrokerService brokerService = new BrokerService(); + brokerService.setEnableStatistics(false); + brokerService.addConnector("tcp://0.0.0.0:0"); + brokerService.setDeleteAllMessagesOnStartup(true); + + PolicyEntry policy = new PolicyEntry(); + policy.setPrioritizedMessages(true); + policy.setMaxPageSize(500); + + PolicyMap policyMap = new PolicyMap(); + policyMap.setDefaultEntry(policy); + brokerService.setDestinationPolicy(policyMap); + setDefaultPersistenceAdapter(brokerService); + + return brokerService; + } + + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString()); + ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); + prefetchPolicy.setAll(1); + factory.setPrefetchPolicy(prefetchPolicy); + + factory.setDispatchAsync(true); + return factory; + } + + public static Test suite() { + return suite(ConcurrentProducerQueueConsumerTest.class); + } + + static class TimedMessageListener implements MessageListener { + + static final AtomicLong count = new AtomicLong(0); + + final int batchSize = 1000; + final CountDownLatch firstReceiptLatch = new CountDownLatch(1); + + long mark = System.currentTimeMillis(); + long firstReceipt = 0L; + long receiptAccumulator = 0; + long batchReceiptAccumulator = 0; + long maxReceiptTime = 0; + + final Map messageLists = new ConcurrentHashMap(new HashMap()); + + @Override + public void onMessage(Message message) { + final long current = System.currentTimeMillis(); + final long duration = current - mark; + receiptAccumulator += duration; + int priority = 0; + + try { + priority = message.getJMSPriority(); + } + catch (JMSException ignored) { + } + + if (!messageLists.containsKey(priority)) { + messageLists.put(priority, new MessageIdList()); + } + messageLists.get(priority).onMessage(message); + + if (count.incrementAndGet() == 1) { + firstReceipt = duration; + firstReceiptLatch.countDown(); + LOG.info("First receipt in " + firstReceipt + "ms"); + } + else if (count.get() % batchSize == 0) { + LOG.info("Consumed " + count.get() + " in " + batchReceiptAccumulator + "ms" + ", priority:" + priority); + batchReceiptAccumulator = 0; + } + + maxReceiptTime = Math.max(maxReceiptTime, duration); + receiptAccumulator += duration; + batchReceiptAccumulator += duration; + mark = current; + } + + long getMessageCount() { + return count.get(); + } + + long getFirstReceipt() throws Exception { + firstReceiptLatch.await(30, TimeUnit.SECONDS); + return firstReceipt; + } + + public long waitForReceivedLimit(long limit) throws Exception { + final long expiry = System.currentTimeMillis() + 30 * 60 * 1000; + while (count.get() < limit) { + if (System.currentTimeMillis() > expiry) { + throw new RuntimeException("Expired waiting for X messages, " + limit); + } + TimeUnit.SECONDS.sleep(2); + String missing = findFirstMissingMessage(); + if (missing != null) { + LOG.info("first missing = " + missing); + throw new RuntimeException("We have a missing message. " + missing); } - return receiptAccumulator/(limit/batchSize); - } - private String findFirstMissingMessage() { - return null; - } - } + } + return receiptAccumulator / (limit / batchSize); + } + + private String findFirstMissingMessage() { + return null; + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConsumeQueuePrefetchTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConsumeQueuePrefetchTest.java index 3810505523..4bec5afa87 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConsumeQueuePrefetchTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConsumeQueuePrefetchTest.java @@ -23,35 +23,35 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ConsumeQueuePrefetchTest extends ConsumeTopicPrefetchTest { - private static final Logger LOG = LoggerFactory.getLogger(ConsumeQueuePrefetchTest.class); - - protected void setUp() throws Exception { - topic = false; - super.setUp(); - } - - public void testInflightWithConsumerPerMessage() throws JMSException { - makeMessages(prefetchSize); - LOG.info("About to send and receive: " + prefetchSize + " on destination: " + destination - + " of type: " + destination.getClass().getName()); + private static final Logger LOG = LoggerFactory.getLogger(ConsumeQueuePrefetchTest.class); - for (int i = 0; i < prefetchSize; i++) { - Message message = session.createTextMessage(messageTexts[i]); - producer.send(message); - } + protected void setUp() throws Exception { + topic = false; + super.setUp(); + } - validateConsumerPrefetch(this.getSubject(), prefetchSize); - - // new consumer per 20 messages - for (int i = 0; i < prefetchSize; i+=20) { - consumer.close(); - consumer = session.createConsumer(destination); - validateConsumerPrefetch(this.getSubject(), prefetchSize - i); - for (int j=0; j<20; j++) { - Message message = consumeMessge(i+j); - message.acknowledge(); - } - } - } + public void testInflightWithConsumerPerMessage() throws JMSException { + makeMessages(prefetchSize); + + LOG.info("About to send and receive: " + prefetchSize + " on destination: " + destination + " of type: " + destination.getClass().getName()); + + for (int i = 0; i < prefetchSize; i++) { + Message message = session.createTextMessage(messageTexts[i]); + producer.send(message); + } + + validateConsumerPrefetch(this.getSubject(), prefetchSize); + + // new consumer per 20 messages + for (int i = 0; i < prefetchSize; i += 20) { + consumer.close(); + consumer = session.createConsumer(destination); + validateConsumerPrefetch(this.getSubject(), prefetchSize - i); + for (int j = 0; j < 20; j++) { + Message message = consumeMessge(i + j); + message.acknowledge(); + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConsumeTopicPrefetchTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConsumeTopicPrefetchTest.java index d95d2d6d47..a6af6b097e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConsumeTopicPrefetchTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConsumeTopicPrefetchTest.java @@ -32,123 +32,125 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class ConsumeTopicPrefetchTest extends ProducerConsumerTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(ConsumeTopicPrefetchTest.class); - protected int prefetchSize = 100; - protected String[] messageTexts; - protected long consumerTimeout = 10000L; + private static final Logger LOG = LoggerFactory.getLogger(ConsumeTopicPrefetchTest.class); - public void testSendPrefetchSize() throws JMSException { - testWithMessageCount(prefetchSize); - } + protected int prefetchSize = 100; + protected String[] messageTexts; + protected long consumerTimeout = 10000L; - public void testSendDoublePrefetchSize() throws JMSException { - testWithMessageCount(prefetchSize * 2); - } + public void testSendPrefetchSize() throws JMSException { + testWithMessageCount(prefetchSize); + } - public void testSendPrefetchSizePlusOne() throws JMSException { - testWithMessageCount(prefetchSize + 1); - } + public void testSendDoublePrefetchSize() throws JMSException { + testWithMessageCount(prefetchSize * 2); + } - protected void testWithMessageCount(int messageCount) throws JMSException { - makeMessages(messageCount); + public void testSendPrefetchSizePlusOne() throws JMSException { + testWithMessageCount(prefetchSize + 1); + } - LOG.info("About to send and receive: " + messageCount + " on destination: " + destination - + " of type: " + destination.getClass().getName()); + protected void testWithMessageCount(int messageCount) throws JMSException { + makeMessages(messageCount); - for (int i = 0; i < messageCount; i++) { - Message message = session.createTextMessage(messageTexts[i]); - producer.send(message); - } + LOG.info("About to send and receive: " + messageCount + " on destination: " + destination + " of type: " + destination.getClass().getName()); - validateConsumerPrefetch(this.getSubject(), prefetchSize); + for (int i = 0; i < messageCount; i++) { + Message message = session.createTextMessage(messageTexts[i]); + producer.send(message); + } - LinkedList consumed = new LinkedList(); - // lets consume them in two fetch batches - int batchSize = messageCount/2; - for (int i = 0; i < batchSize; i++) { - consumed.add(consumeMessge(i)); - } + validateConsumerPrefetch(this.getSubject(), prefetchSize); - // delayed delivered ack a .5 prefetch - validateConsumerPrefetchGreaterOrEqual(this.getSubject(), (long) Math.min(messageCount, 1.5 * prefetchSize)); + LinkedList consumed = new LinkedList(); + // lets consume them in two fetch batches + int batchSize = messageCount / 2; + for (int i = 0; i < batchSize; i++) { + consumed.add(consumeMessge(i)); + } - for (int i = 0; i < batchSize; i++) { - consumed.remove().acknowledge(); - } + // delayed delivered ack a .5 prefetch + validateConsumerPrefetchGreaterOrEqual(this.getSubject(), (long) Math.min(messageCount, 1.5 * prefetchSize)); - // second batch to consume the rest - for (int i = batchSize; i < messageCount; i++) { - consumeMessge(i).acknowledge(); - } - validateConsumerPrefetch(this.getSubject(), 0); - } + for (int i = 0; i < batchSize; i++) { + consumed.remove().acknowledge(); + } - protected Connection createConnection() throws Exception { - ActiveMQConnection connection = (ActiveMQConnection) super.createConnection(); - connection.getPrefetchPolicy().setQueuePrefetch(prefetchSize); - connection.getPrefetchPolicy().setTopicPrefetch(prefetchSize); - return connection; - } + // second batch to consume the rest + for (int i = batchSize; i < messageCount; i++) { + consumeMessge(i).acknowledge(); + } + validateConsumerPrefetch(this.getSubject(), 0); + } - protected TextMessage consumeMessge(int i) throws JMSException { - Message message = consumer.receive(consumerTimeout); - assertTrue("Should have received a message by now for message: " + i, message != null); - assertTrue("Should be a TextMessage: " + message, message instanceof TextMessage); - TextMessage textMessage = (TextMessage) message; - assertEquals("Message content", messageTexts[i], textMessage.getText()); - return textMessage; - } + protected Connection createConnection() throws Exception { + ActiveMQConnection connection = (ActiveMQConnection) super.createConnection(); + connection.getPrefetchPolicy().setQueuePrefetch(prefetchSize); + connection.getPrefetchPolicy().setTopicPrefetch(prefetchSize); + return connection; + } + protected TextMessage consumeMessge(int i) throws JMSException { + Message message = consumer.receive(consumerTimeout); + assertTrue("Should have received a message by now for message: " + i, message != null); + assertTrue("Should be a TextMessage: " + message, message instanceof TextMessage); + TextMessage textMessage = (TextMessage) message; + assertEquals("Message content", messageTexts[i], textMessage.getText()); + return textMessage; + } - protected void makeMessages(int messageCount) { - messageTexts = new String[messageCount]; - for (int i = 0; i < messageCount; i++) { - messageTexts[i] = "Message for test: + " + getName() + " = " + i; - } - } + protected void makeMessages(int messageCount) { + messageTexts = new String[messageCount]; + for (int i = 0; i < messageCount; i++) { + messageTexts[i] = "Message for test: + " + getName() + " = " + i; + } + } - private void validateConsumerPrefetchGreaterOrEqual(String subject, long min) throws JMSException { - doValidateConsumerPrefetch(subject, min, true); - } + private void validateConsumerPrefetchGreaterOrEqual(String subject, long min) throws JMSException { + doValidateConsumerPrefetch(subject, min, true); + } - protected void validateConsumerPrefetch(String subject, final long expectedCount) throws JMSException { - doValidateConsumerPrefetch(subject, expectedCount, false); - } + protected void validateConsumerPrefetch(String subject, final long expectedCount) throws JMSException { + doValidateConsumerPrefetch(subject, expectedCount, false); + } - protected void doValidateConsumerPrefetch(String destination, final long expectedCount, final boolean greaterOrEqual) throws JMSException { - RegionBroker regionBroker = (RegionBroker) BrokerRegistry.getInstance().lookup("localhost").getRegionBroker(); - for (org.apache.activemq.broker.region.Destination dest : regionBroker.getTopicRegion().getDestinationMap().values()) { - final org.apache.activemq.broker.region.Destination target = dest; - if (dest.getName().equals(destination)) { - try { - Wait.waitFor(new Condition() { - public boolean isSatisified() throws Exception { - DestinationStatistics stats = target.getDestinationStatistics(); - LOG.info("inflight for : " + target.getName() + ": " + stats.getInflight().getCount()); - if (greaterOrEqual) { - return stats.getInflight().getCount() >= expectedCount; - } else { - return stats.getInflight().getCount() == expectedCount; - } - } - }); - } catch (Exception e) { - throw new JMSException(e.toString()); - } - DestinationStatistics stats = dest.getDestinationStatistics(); - LOG.info("inflight for : " + dest.getName() + ": " + stats.getInflight().getCount()); - if (greaterOrEqual) { - assertTrue("inflight for: " + dest.getName() + ": " + stats.getInflight().getCount() + " > " + stats.getInflight().getCount(), - stats.getInflight().getCount() >= expectedCount); - } else { - assertEquals("inflight for: " + dest.getName() + ": " + stats.getInflight().getCount() + " matches", - expectedCount, stats.getInflight().getCount()); - } + protected void doValidateConsumerPrefetch(String destination, + final long expectedCount, + final boolean greaterOrEqual) throws JMSException { + RegionBroker regionBroker = (RegionBroker) BrokerRegistry.getInstance().lookup("localhost").getRegionBroker(); + for (org.apache.activemq.broker.region.Destination dest : regionBroker.getTopicRegion().getDestinationMap().values()) { + final org.apache.activemq.broker.region.Destination target = dest; + if (dest.getName().equals(destination)) { + try { + Wait.waitFor(new Condition() { + public boolean isSatisified() throws Exception { + DestinationStatistics stats = target.getDestinationStatistics(); + LOG.info("inflight for : " + target.getName() + ": " + stats.getInflight().getCount()); + if (greaterOrEqual) { + return stats.getInflight().getCount() >= expectedCount; + } + else { + return stats.getInflight().getCount() == expectedCount; + } + } + }); } - } - } + catch (Exception e) { + throw new JMSException(e.toString()); + } + DestinationStatistics stats = dest.getDestinationStatistics(); + LOG.info("inflight for : " + dest.getName() + ": " + stats.getInflight().getCount()); + if (greaterOrEqual) { + assertTrue("inflight for: " + dest.getName() + ": " + stats.getInflight().getCount() + " > " + stats.getInflight().getCount(), stats.getInflight().getCount() >= expectedCount); + } + else { + assertEquals("inflight for: " + dest.getName() + ": " + stats.getInflight().getCount() + " matches", expectedCount, stats.getInflight().getCount()); + } + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConsumeUncompressedCompressedMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConsumeUncompressedCompressedMessageTest.java index 3c3568853e..2e54fef313 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConsumeUncompressedCompressedMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConsumeUncompressedCompressedMessageTest.java @@ -48,147 +48,143 @@ import org.slf4j.LoggerFactory; public class ConsumeUncompressedCompressedMessageTest { - private static final Logger LOG = LoggerFactory.getLogger(ConsumeUncompressedCompressedMessageTest.class); + private static final Logger LOG = LoggerFactory.getLogger(ConsumeUncompressedCompressedMessageTest.class); - private BrokerService broker; - private URI tcpUri; + private BrokerService broker; + private URI tcpUri; - ActiveMQConnectionFactory factory; - ActiveMQConnection connection; - Session session; - Queue queue; + ActiveMQConnectionFactory factory; + ActiveMQConnection connection; + Session session; + Queue queue; - @Before - public void setUp() throws Exception { - broker = createBroker(); - broker.start(); - broker.waitUntilStarted(); + @Before + public void setUp() throws Exception { + broker = createBroker(); + broker.start(); + broker.waitUntilStarted(); - factory = new ActiveMQConnectionFactory(tcpUri); - factory.setUseCompression(true); + factory = new ActiveMQConnectionFactory(tcpUri); + factory.setUseCompression(true); - connection = (ActiveMQConnection) factory.createConnection(); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - queue = session.createQueue("CompressionTestQueue"); - } + connection = (ActiveMQConnection) factory.createConnection(); + connection.start(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + queue = session.createQueue("CompressionTestQueue"); + } - @After - public void tearDown() throws Exception { + @After + public void tearDown() throws Exception { - if(connection != null) { - connection.close(); - } + if (connection != null) { + connection.close(); + } - broker.stop(); - broker.waitUntilStopped(); - } + broker.stop(); + broker.waitUntilStopped(); + } - protected BrokerService createBroker() throws Exception { - return createBroker(true); - } + protected BrokerService createBroker() throws Exception { + return createBroker(true); + } - protected BrokerService createBroker(boolean delete) throws Exception { - BrokerService answer = new BrokerService(); - answer.setPersistent(false); - answer.setDeleteAllMessagesOnStartup(true); - answer.setSchedulerSupport(false); - answer.setUseJmx(true); - TransportConnector connector = answer.addConnector("tcp://localhost:0"); - tcpUri = connector.getConnectUri(); - return answer; - } + protected BrokerService createBroker(boolean delete) throws Exception { + BrokerService answer = new BrokerService(); + answer.setPersistent(false); + answer.setDeleteAllMessagesOnStartup(true); + answer.setSchedulerSupport(false); + answer.setUseJmx(true); + TransportConnector connector = answer.addConnector("tcp://localhost:0"); + tcpUri = connector.getConnectUri(); + return answer; + } - @Test - public void testBrowseAndReceiveCompressedMessages() throws Exception { + @Test + public void testBrowseAndReceiveCompressedMessages() throws Exception { - assertTrue(connection.isUseCompression()); + assertTrue(connection.isUseCompression()); - createProducerAndSendMessages(1); + createProducerAndSendMessages(1); - QueueViewMBean queueView = getProxyToQueueViewMBean(); + QueueViewMBean queueView = getProxyToQueueViewMBean(); - assertNotNull(queueView); + assertNotNull(queueView); - CompositeData[] compdatalist = queueView.browse(); - if (compdatalist.length == 0) { - fail("There is no message in the queue:"); - } + CompositeData[] compdatalist = queueView.browse(); + if (compdatalist.length == 0) { + fail("There is no message in the queue:"); + } - CompositeData cdata = compdatalist[0]; + CompositeData cdata = compdatalist[0]; - assertComplexData(0, cdata, "Text", "Test Text Message: " + 0); + assertComplexData(0, cdata, "Text", "Test Text Message: " + 0); - assertMessageAreCorrect(1); - } + assertMessageAreCorrect(1); + } - @Test - public void testReceiveAndResendWithCompressionOff() throws Exception { + @Test + public void testReceiveAndResendWithCompressionOff() throws Exception { - assertTrue(connection.isUseCompression()); + assertTrue(connection.isUseCompression()); - createProducerAndSendMessages(1); + createProducerAndSendMessages(1); - MessageConsumer consumer = session.createConsumer(queue); - TextMessage message = (TextMessage) consumer.receive(5000); + MessageConsumer consumer = session.createConsumer(queue); + TextMessage message = (TextMessage) consumer.receive(5000); - assertTrue(((ActiveMQMessage) message).isCompressed()); + assertTrue(((ActiveMQMessage) message).isCompressed()); - LOG.debug("Received Message with Text = " + message.getText()); + LOG.debug("Received Message with Text = " + message.getText()); - connection.setUseCompression(false); + connection.setUseCompression(false); - MessageProducer producer = session.createProducer(queue); - producer.send(message); - producer.close(); + MessageProducer producer = session.createProducer(queue); + producer.send(message); + producer.close(); - message = (TextMessage) consumer.receive(5000); + message = (TextMessage) consumer.receive(5000); - LOG.debug("Received Message with Text = " + message.getText()); - } + LOG.debug("Received Message with Text = " + message.getText()); + } - protected void assertComplexData(int messageIndex, CompositeData cdata, String name, Object expected) { - Object value = cdata.get(name); - assertEquals("Message " + messageIndex + " CData field: " + name, expected, value); - } + protected void assertComplexData(int messageIndex, CompositeData cdata, String name, Object expected) { + Object value = cdata.get(name); + assertEquals("Message " + messageIndex + " CData field: " + name, expected, value); + } - private void createProducerAndSendMessages(int numToSend) throws Exception { - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(queue); - for (int i = 0; i < numToSend; i++) { - TextMessage message = session.createTextMessage("Test Text Message: " + i); - if (i != 0 && i % 10000 == 0) { - LOG.info("sent: " + i); - } - producer.send(message); - } - producer.close(); - } + private void createProducerAndSendMessages(int numToSend) throws Exception { + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(queue); + for (int i = 0; i < numToSend; i++) { + TextMessage message = session.createTextMessage("Test Text Message: " + i); + if (i != 0 && i % 10000 == 0) { + LOG.info("sent: " + i); + } + producer.send(message); + } + producer.close(); + } - private QueueViewMBean getProxyToQueueViewMBean() - throws MalformedObjectNameException, JMSException { - ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq" - + ":destinationType=Queue,destinationName=" + queue.getQueueName() - + ",type=Broker,brokerName=localhost"); - QueueViewMBean proxy = (QueueViewMBean) broker.getManagementContext() - .newProxyInstance(queueViewMBeanName, QueueViewMBean.class, - true); - return proxy; - } + private QueueViewMBean getProxyToQueueViewMBean() throws MalformedObjectNameException, JMSException { + ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq" + ":destinationType=Queue,destinationName=" + queue.getQueueName() + ",type=Broker,brokerName=localhost"); + QueueViewMBean proxy = (QueueViewMBean) broker.getManagementContext().newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); + return proxy; + } - private void assertMessageAreCorrect(int numToReceive) throws Exception { - MessageConsumer consumer = session.createConsumer(queue); + private void assertMessageAreCorrect(int numToReceive) throws Exception { + MessageConsumer consumer = session.createConsumer(queue); - try{ + try { - for (int i = 0; i < numToReceive; ++i) { - TextMessage message = (TextMessage) consumer.receive(5000); - assertNotNull(message); - assertEquals("Test Text Message: " + i, message.getText()); - } + for (int i = 0; i < numToReceive; ++i) { + TextMessage message = (TextMessage) consumer.receive(5000); + assertNotNull(message); + assertEquals("Test Text Message: " + i, message.getText()); + } - } finally { - consumer.close(); - } - } + } + finally { + consumer.close(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CreateLotsOfTemporaryQueuesTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CreateLotsOfTemporaryQueuesTest.java index 77b821e821..6585cced43 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CreateLotsOfTemporaryQueuesTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CreateLotsOfTemporaryQueuesTest.java @@ -21,47 +21,49 @@ import javax.jms.TemporaryQueue; import junit.framework.Test; import junit.framework.TestSuite; + import junit.textui.TestRunner; import org.apache.activemq.EmbeddedBrokerAndConnectionTestSupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class CreateLotsOfTemporaryQueuesTest extends EmbeddedBrokerAndConnectionTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(CreateLotsOfTemporaryQueuesTest.class); - private static int numberToCreate = 500; - private static long sleep = 20; + private static final Logger LOG = LoggerFactory.getLogger(CreateLotsOfTemporaryQueuesTest.class); - public static void main(String[] args) { - configure(args); - TestRunner.run(suite()); - } + private static int numberToCreate = 500; + private static long sleep = 20; - public static Test suite() { - return new TestSuite(CreateLotsOfTemporaryQueuesTest.class); - } + public static void main(String[] args) { + configure(args); + TestRunner.run(suite()); + } - public void testCreateLotsOfTemporaryQueues() throws Exception { - LOG.info("Creating " + numberToCreate + " temporary queue(s)"); + public static Test suite() { + return new TestSuite(CreateLotsOfTemporaryQueuesTest.class); + } - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - for (int i = 0; i < numberToCreate; i++) { - if (i % 1000 == 0) { - LOG.info("attempt " + i); - } - TemporaryQueue temporaryQueue = session.createTemporaryQueue(); - temporaryQueue.delete(); - Thread.sleep(sleep); - } - LOG.info("Created " + numberToCreate + " temporary queue(s)"); - } + public void testCreateLotsOfTemporaryQueues() throws Exception { + LOG.info("Creating " + numberToCreate + " temporary queue(s)"); - public static void configure(String[] args) { - if (args.length > 0) { - numberToCreate = Integer.parseInt(args[0]); - } - } + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + for (int i = 0; i < numberToCreate; i++) { + if (i % 1000 == 0) { + LOG.info("attempt " + i); + } + TemporaryQueue temporaryQueue = session.createTemporaryQueue(); + temporaryQueue.delete(); + Thread.sleep(sleep); + } + LOG.info("Created " + numberToCreate + " temporary queue(s)"); + } + + public static void configure(String[] args) { + if (args.length > 0) { + numberToCreate = Integer.parseInt(args[0]); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CreateTemporaryQueueBeforeStartTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CreateTemporaryQueueBeforeStartTest.java index e2d961cf39..23e67c778d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CreateTemporaryQueueBeforeStartTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CreateTemporaryQueueBeforeStartTest.java @@ -27,105 +27,108 @@ import javax.jms.Session; import javax.jms.Topic; import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; /** * @author Peter Henning - * */ public class CreateTemporaryQueueBeforeStartTest extends TestCase { - private final String bindAddress = "tcp://localhost:0"; - private String connectionUri; - private Connection connection; - private BrokerService broker = new BrokerService(); - public void testCreateTemporaryQueue() throws Exception { - connection = createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createTemporaryQueue(); - assertTrue("No queue created!", queue != null); - Topic topic = session.createTemporaryTopic(); - assertTrue("No topic created!", topic != null); - } + private final String bindAddress = "tcp://localhost:0"; + private String connectionUri; + private Connection connection; + private BrokerService broker = new BrokerService(); - public void testTryToReproduceNullPointerBug() throws Exception { - String url = connectionUri; - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(url); - QueueConnection queueConnection = factory.createQueueConnection(); - this.connection = queueConnection; - QueueSession session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); - session.createSender(null); // Unidentified - Queue receiverQueue = session.createTemporaryQueue(); - session.createReceiver(receiverQueue); - queueConnection.start(); - } + public void testCreateTemporaryQueue() throws Exception { + connection = createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = session.createTemporaryQueue(); + assertTrue("No queue created!", queue != null); + Topic topic = session.createTemporaryTopic(); + assertTrue("No topic created!", topic != null); + } - public void testTemporaryQueueConsumer() throws Exception { - final int number = 20; - final AtomicInteger count = new AtomicInteger(0); - for (int i = 0; i < number; i++) { - Thread thread = new Thread(new Runnable() { - public void run() { - try { - QueueConnection connection = createConnection(); - QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createTemporaryQueue(); - session.createReceiver(queue); - connection.start(); + public void testTryToReproduceNullPointerBug() throws Exception { + String url = connectionUri; + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(url); + QueueConnection queueConnection = factory.createQueueConnection(); + this.connection = queueConnection; + QueueSession session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); + session.createSender(null); // Unidentified + Queue receiverQueue = session.createTemporaryQueue(); + session.createReceiver(receiverQueue); + queueConnection.start(); + } - if (count.incrementAndGet() >= number) { - synchronized (count) { - count.notify(); - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } - }); - thread.start(); - } - int maxWaitTime = 20000; - synchronized (count) { - long waitTime = maxWaitTime; - long start = System.currentTimeMillis(); - while (count.get() < number) { - if (waitTime <= 0) { - break; - } else { - count.wait(waitTime); - waitTime = maxWaitTime - (System.currentTimeMillis() - start); - } + public void testTemporaryQueueConsumer() throws Exception { + final int number = 20; + final AtomicInteger count = new AtomicInteger(0); + for (int i = 0; i < number; i++) { + Thread thread = new Thread(new Runnable() { + public void run() { + try { + QueueConnection connection = createConnection(); + QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = session.createTemporaryQueue(); + session.createReceiver(queue); + connection.start(); + + if (count.incrementAndGet() >= number) { + synchronized (count) { + count.notify(); + } + } + } + catch (Exception ex) { + ex.printStackTrace(); + } } - } - assertTrue("Unexpected count: " + count, count.get() == number); - } + }); + thread.start(); + } + int maxWaitTime = 20000; + synchronized (count) { + long waitTime = maxWaitTime; + long start = System.currentTimeMillis(); + while (count.get() < number) { + if (waitTime <= 0) { + break; + } + else { + count.wait(waitTime); + waitTime = maxWaitTime - (System.currentTimeMillis() - start); + } + } + } + assertTrue("Unexpected count: " + count, count.get() == number); + } - protected QueueConnection createConnection() throws Exception { - ActiveMQConnectionFactory factory = createConnectionFactory(); - return factory.createQueueConnection(); - } + protected QueueConnection createConnection() throws Exception { + ActiveMQConnectionFactory factory = createConnectionFactory(); + return factory.createQueueConnection(); + } - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(connectionUri); - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory(connectionUri); + } - protected void setUp() throws Exception { - broker.setUseJmx(false); - broker.setPersistent(false); - connectionUri = broker.addConnector(bindAddress).getPublishableConnectString(); - broker.start(); - broker.waitUntilStarted(); + protected void setUp() throws Exception { + broker.setUseJmx(false); + broker.setPersistent(false); + connectionUri = broker.addConnector(bindAddress).getPublishableConnectString(); + broker.start(); + broker.waitUntilStarted(); - super.setUp(); - } + super.setUp(); + } - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - broker.stop(); - super.tearDown(); - } + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + } + broker.stop(); + super.tearDown(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DiscriminatingConsumerLoadTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DiscriminatingConsumerLoadTest.java index 5ea5518f13..fbff4f76f2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DiscriminatingConsumerLoadTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DiscriminatingConsumerLoadTest.java @@ -41,270 +41,275 @@ import org.apache.activemq.broker.region.policy.PolicyMap; * particularly when the messages in the queue do not meet the selector criteria of the client. * * https://issues.apache.org/activemq/browse/AMQ-2217 - * */ public class DiscriminatingConsumerLoadTest extends TestSupport { - private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(DiscriminatingConsumerLoadTest.class); + private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(DiscriminatingConsumerLoadTest.class); - private Connection producerConnection; - private Connection consumerConnection; + private Connection producerConnection; + private Connection consumerConnection; - public static final String JMSTYPE_EATME = "DiscriminatingLoadClient.EatMe"; - public static final String JMSTYPE_IGNOREME = "DiscriminatingLoadClient.IgnoreMe"; + public static final String JMSTYPE_EATME = "DiscriminatingLoadClient.EatMe"; + public static final String JMSTYPE_IGNOREME = "DiscriminatingLoadClient.IgnoreMe"; - private final int testSize = 5000; // setting this to a small number will pass all tests + private final int testSize = 5000; // setting this to a small number will pass all tests - BrokerService broker; + BrokerService broker; - @Override - protected void setUp() throws Exception { - broker = new BrokerService(); - broker.setPersistent(false); + @Override + protected void setUp() throws Exception { + broker = new BrokerService(); + broker.setPersistent(false); - // workaround is to ensure sufficient dispatch buffer for the destination - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultPolicy = new PolicyEntry(); - defaultPolicy.setMaxPageSize(testSize); - policyMap.setDefaultEntry(defaultPolicy); - broker.setDestinationPolicy(policyMap); - broker.start(); + // workaround is to ensure sufficient dispatch buffer for the destination + PolicyMap policyMap = new PolicyMap(); + PolicyEntry defaultPolicy = new PolicyEntry(); + defaultPolicy.setMaxPageSize(testSize); + policyMap.setDefaultEntry(defaultPolicy); + broker.setDestinationPolicy(policyMap); + broker.start(); - super.setUp(); - this.producerConnection = this.createConnection(); - this.consumerConnection = this.createConnection(); - } + super.setUp(); + this.producerConnection = this.createConnection(); + this.consumerConnection = this.createConnection(); + } - /** - * @see junit.framework.TestCase#tearDown() - */ - @Override - protected void tearDown() throws Exception { - if (producerConnection != null) { - producerConnection.close(); - producerConnection = null; - } - if (consumerConnection != null) { - consumerConnection.close(); - consumerConnection = null; - } - super.tearDown(); - broker.stop(); - } + /** + * @see junit.framework.TestCase#tearDown() + */ + @Override + protected void tearDown() throws Exception { + if (producerConnection != null) { + producerConnection.close(); + producerConnection = null; + } + if (consumerConnection != null) { + consumerConnection.close(); + consumerConnection = null; + } + super.tearDown(); + broker.stop(); + } - /** - * Test to check if a single consumer with no JMS selector will receive all intended messages - * - * @throws java.lang.Exception - */ - public void testNonDiscriminatingConsumer() throws Exception { + /** + * Test to check if a single consumer with no JMS selector will receive all intended messages + * + * @throws java.lang.Exception + */ + public void testNonDiscriminatingConsumer() throws Exception { - consumerConnection = createConnection(); - consumerConnection.start(); - LOG.info("consumerConnection = " + consumerConnection); + consumerConnection = createConnection(); + consumerConnection.start(); + LOG.info("consumerConnection = " + consumerConnection); - try { - Thread.sleep(1000); - } catch (Exception e) { - } + try { + Thread.sleep(1000); + } + catch (Exception e) { + } - // here we pass in null for the JMS selector - Consumer consumer = new Consumer(consumerConnection, null); - Thread consumerThread = new Thread(consumer); + // here we pass in null for the JMS selector + Consumer consumer = new Consumer(consumerConnection, null); + Thread consumerThread = new Thread(consumer); - consumerThread.start(); + consumerThread.start(); - producerConnection = createConnection(); - producerConnection.start(); - LOG.info("producerConnection = " + producerConnection); + producerConnection = createConnection(); + producerConnection.start(); + LOG.info("producerConnection = " + producerConnection); - try { - Thread.sleep(3000); - } catch (Exception e) { - } + try { + Thread.sleep(3000); + } + catch (Exception e) { + } - Producer producer = new Producer(producerConnection); - Thread producerThread = new Thread(producer); - producerThread.start(); + Producer producer = new Producer(producerConnection); + Thread producerThread = new Thread(producer); + producerThread.start(); - // now that everything is running, let's wait for the consumer thread to finish ... - consumerThread.join(); - producer.stop = true; + // now that everything is running, let's wait for the consumer thread to finish ... + consumerThread.join(); + producer.stop = true; - if (consumer.getCount() == testSize) - LOG.info("test complete .... all messsages consumed!!"); - else - LOG.info("test failed .... Sent " + (testSize / 1) + " messages intended to be consumed ( " + testSize + " total), but only consumed " - + consumer.getCount()); + if (consumer.getCount() == testSize) + LOG.info("test complete .... all messsages consumed!!"); + else + LOG.info("test failed .... Sent " + (testSize / 1) + " messages intended to be consumed ( " + testSize + " total), but only consumed " + consumer.getCount()); - assertTrue("Sent " + testSize + " messages intended to be consumed, but only consumed " + consumer.getCount(), (consumer.getCount() == testSize)); - assertFalse("Delivery of messages to consumer was halted during this test", consumer.deliveryHalted()); - } + assertTrue("Sent " + testSize + " messages intended to be consumed, but only consumed " + consumer.getCount(), (consumer.getCount() == testSize)); + assertFalse("Delivery of messages to consumer was halted during this test", consumer.deliveryHalted()); + } - /** - * Test to check if a single consumer with a JMS selector will receive all intended messages - * - * @throws java.lang.Exception - */ - public void testDiscriminatingConsumer() throws Exception { + /** + * Test to check if a single consumer with a JMS selector will receive all intended messages + * + * @throws java.lang.Exception + */ + public void testDiscriminatingConsumer() throws Exception { - consumerConnection = createConnection(); - consumerConnection.start(); - LOG.info("consumerConnection = " + consumerConnection); + consumerConnection = createConnection(); + consumerConnection.start(); + LOG.info("consumerConnection = " + consumerConnection); - try { - Thread.sleep(1000); - } catch (Exception e) { - } + try { + Thread.sleep(1000); + } + catch (Exception e) { + } - // here we pass the JMS selector we intend to consume - Consumer consumer = new Consumer(consumerConnection, JMSTYPE_EATME); - Thread consumerThread = new Thread(consumer); + // here we pass the JMS selector we intend to consume + Consumer consumer = new Consumer(consumerConnection, JMSTYPE_EATME); + Thread consumerThread = new Thread(consumer); - consumerThread.start(); + consumerThread.start(); - producerConnection = createConnection(); - producerConnection.start(); - LOG.info("producerConnection = " + producerConnection); + producerConnection = createConnection(); + producerConnection.start(); + LOG.info("producerConnection = " + producerConnection); - try { - Thread.sleep(3000); - } catch (Exception e) { - } + try { + Thread.sleep(3000); + } + catch (Exception e) { + } - Producer producer = new Producer(producerConnection); - Thread producerThread = new Thread(producer); - producerThread.start(); + Producer producer = new Producer(producerConnection); + Thread producerThread = new Thread(producer); + producerThread.start(); - // now that everything is running, let's wait for the consumer thread to finish ... - consumerThread.join(); - producer.stop = true; + // now that everything is running, let's wait for the consumer thread to finish ... + consumerThread.join(); + producer.stop = true; - if (consumer.getCount() == (testSize / 2)) { - LOG.info("test complete .... all messsages consumed!!"); - } else { - LOG.info("test failed .... Sent " + testSize + " original messages, only half of which (" + (testSize / 2) - + ") were intended to be consumed: consumer paused at: " + consumer.getCount()); - // System.out.println("test failed .... Sent " + testSize + " original messages, only half of which (" + - // (testSize / 2) + - // ") were intended to be consumed: consumer paused at: " + consumer.getCount()); + if (consumer.getCount() == (testSize / 2)) { + LOG.info("test complete .... all messsages consumed!!"); + } + else { + LOG.info("test failed .... Sent " + testSize + " original messages, only half of which (" + (testSize / 2) + ") were intended to be consumed: consumer paused at: " + consumer.getCount()); + // System.out.println("test failed .... Sent " + testSize + " original messages, only half of which (" + + // (testSize / 2) + + // ") were intended to be consumed: consumer paused at: " + consumer.getCount()); - } + } - assertTrue("Sent " + testSize + " original messages, only half of which (" + (testSize / 2) + ") were intended to be consumed: consumer paused at: " - + consumer.getCount(), (consumer.getCount() == (testSize / 2))); - assertTrue("Delivery of messages to consumer was halted during this test as it only wants half", consumer.deliveryHalted()); - } + assertTrue("Sent " + testSize + " original messages, only half of which (" + (testSize / 2) + ") were intended to be consumed: consumer paused at: " + consumer.getCount(), (consumer.getCount() == (testSize / 2))); + assertTrue("Delivery of messages to consumer was halted during this test as it only wants half", consumer.deliveryHalted()); + } - /** - * Helper class that will publish 2 * testSize messages. The messages will be distributed evenly between the - * following two JMS types: - * - * @see JMSTYPE_INTENDED_FOR_CONSUMPTION - * @see JMSTYPE_NOT_INTENDED_FOR_CONSUMPTION - * - */ - private class Producer extends Thread { - private int counterSent = 0; - private Connection connection = null; - public boolean stop = false; + /** + * Helper class that will publish 2 * testSize messages. The messages will be distributed evenly between the + * following two JMS types: + * + * @see JMSTYPE_INTENDED_FOR_CONSUMPTION + * @see JMSTYPE_NOT_INTENDED_FOR_CONSUMPTION + */ + private class Producer extends Thread { - public Producer(Connection connection) { - this.connection = connection; - } + private int counterSent = 0; + private Connection connection = null; + public boolean stop = false; - @Override - public void run() { - try { - final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final Queue queue = session.createQueue("test"); + public Producer(Connection connection) { + this.connection = connection; + } - // wait for 10 seconds to allow consumer.receive to be run - // first - Thread.sleep(10000); - MessageProducer producer = session.createProducer(queue); + @Override + public void run() { + try { + final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final Queue queue = session.createQueue("test"); - while (!stop && (counterSent < testSize)) { - // first send a message intended to be consumed .... - TextMessage message = session.createTextMessage("*** Ill ....... Ini ***"); // alma mater ... - message.setJMSType(JMSTYPE_EATME); - // LOG.info("sending .... JMSType = " + message.getJMSType()); - producer.send(message, DeliveryMode.NON_PERSISTENT, 0, 1800000); + // wait for 10 seconds to allow consumer.receive to be run + // first + Thread.sleep(10000); + MessageProducer producer = session.createProducer(queue); - counterSent++; + while (!stop && (counterSent < testSize)) { + // first send a message intended to be consumed .... + TextMessage message = session.createTextMessage("*** Ill ....... Ini ***"); // alma mater ... + message.setJMSType(JMSTYPE_EATME); + // LOG.info("sending .... JMSType = " + message.getJMSType()); + producer.send(message, DeliveryMode.NON_PERSISTENT, 0, 1800000); - // now send a message intended to be consumed by some other consumer in the the future - // ... we expect these messages to accrue in the queue - message = session.createTextMessage("*** Ill ....... Ini ***"); // alma mater ... - message.setJMSType(JMSTYPE_IGNOREME); - // LOG.info("sending .... JMSType = " + message.getJMSType()); - producer.send(message, DeliveryMode.NON_PERSISTENT, 0, 1800000); + counterSent++; - counterSent++; - } + // now send a message intended to be consumed by some other consumer in the the future + // ... we expect these messages to accrue in the queue + message = session.createTextMessage("*** Ill ....... Ini ***"); // alma mater ... + message.setJMSType(JMSTYPE_IGNOREME); + // LOG.info("sending .... JMSType = " + message.getJMSType()); + producer.send(message, DeliveryMode.NON_PERSISTENT, 0, 1800000); - session.close(); - - } catch (Exception e) { - e.printStackTrace(); - } - LOG.info("producer thread complete ... " + counterSent + " messages sent to the queue"); - } - } - - /** - * Helper class that will consume messages from the queue based on the supplied JMS selector. Thread will stop after - * the first receive(..) timeout, or once all expected messages have been received (see testSize). If the thread - * stops due to a timeout, it is experiencing the delivery pause that is symptomatic of a bug in the broker. - * - */ - private class Consumer extends Thread { - protected int counterReceived = 0; - private String jmsSelector = null; - private boolean deliveryHalted = false; - - public Consumer(Connection connection, String jmsSelector) { - this.jmsSelector = jmsSelector; - } - - @Override - public void run() { - try { - Session session = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final Queue queue = session.createQueue("test"); - MessageConsumer consumer = null; - if (null != this.jmsSelector) { - consumer = session.createConsumer(queue, "JMSType='" + this.jmsSelector + "'"); - } else { - consumer = session.createConsumer(queue); - } - - while (!deliveryHalted && (counterReceived < testSize)) { - TextMessage result = (TextMessage) consumer.receive(30000); - if (result != null) { - counterReceived++; - // System.out.println("consuming .... JMSType = " + result.getJMSType() + " received = " + - // counterReceived); - LOG.info("consuming .... JMSType = " + result.getJMSType() + " received = " + counterReceived); - } else { - LOG.info("consuming .... timeout while waiting for a message ... broker must have stopped delivery ... received = " + counterReceived); - deliveryHalted = true; - } - } - session.close(); - } catch (Exception e) { - e.printStackTrace(); + counterSent++; } - } + session.close(); - public int getCount() { - return this.counterReceived; - } + } + catch (Exception e) { + e.printStackTrace(); + } + LOG.info("producer thread complete ... " + counterSent + " messages sent to the queue"); + } + } - public boolean deliveryHalted() { - return this.deliveryHalted; - } - } + /** + * Helper class that will consume messages from the queue based on the supplied JMS selector. Thread will stop after + * the first receive(..) timeout, or once all expected messages have been received (see testSize). If the thread + * stops due to a timeout, it is experiencing the delivery pause that is symptomatic of a bug in the broker. + */ + private class Consumer extends Thread { + + protected int counterReceived = 0; + private String jmsSelector = null; + private boolean deliveryHalted = false; + + public Consumer(Connection connection, String jmsSelector) { + this.jmsSelector = jmsSelector; + } + + @Override + public void run() { + try { + Session session = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final Queue queue = session.createQueue("test"); + MessageConsumer consumer = null; + if (null != this.jmsSelector) { + consumer = session.createConsumer(queue, "JMSType='" + this.jmsSelector + "'"); + } + else { + consumer = session.createConsumer(queue); + } + + while (!deliveryHalted && (counterReceived < testSize)) { + TextMessage result = (TextMessage) consumer.receive(30000); + if (result != null) { + counterReceived++; + // System.out.println("consuming .... JMSType = " + result.getJMSType() + " received = " + + // counterReceived); + LOG.info("consuming .... JMSType = " + result.getJMSType() + " received = " + counterReceived); + } + else { + LOG.info("consuming .... timeout while waiting for a message ... broker must have stopped delivery ... received = " + counterReceived); + deliveryHalted = true; + } + } + session.close(); + } + catch (Exception e) { + e.printStackTrace(); + } + + } + + public int getCount() { + return this.counterReceived; + } + + public boolean deliveryHalted() { + return this.deliveryHalted; + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DispatchMultipleConsumersTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DispatchMultipleConsumersTest.java index 166049f71e..9c8981e2bf 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DispatchMultipleConsumersTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DispatchMultipleConsumersTest.java @@ -25,7 +25,9 @@ import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; + import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.command.ActiveMQQueue; @@ -36,192 +38,206 @@ import org.slf4j.LoggerFactory; * @author Rajani Chennamaneni */ public class DispatchMultipleConsumersTest extends TestCase { - private final static Logger logger = LoggerFactory.getLogger(DispatchMultipleConsumersTest.class); - BrokerService broker; - Destination dest; - String destinationName = "TEST.Q"; - String msgStr = "Test text message"; - int messagesPerThread = 20; - int producerThreads = 50; - int consumerCount = 2; - AtomicInteger sentCount; - AtomicInteger consumedCount; - CountDownLatch producerLatch; - CountDownLatch consumerLatch; - String brokerURL; - String userName = ""; - String password = ""; - @Override - protected void setUp() throws Exception { - super.setUp(); - broker = new BrokerService(); - broker.setPersistent(true); - broker.setUseJmx(true); - broker.deleteAllMessages(); - broker.addConnector("tcp://localhost:0"); - broker.start(); - broker.waitUntilStarted(); - dest = new ActiveMQQueue(destinationName); - resetCounters(); - brokerURL = broker.getTransportConnectors().get(0).getPublishableConnectString(); - } + private final static Logger logger = LoggerFactory.getLogger(DispatchMultipleConsumersTest.class); + BrokerService broker; + Destination dest; + String destinationName = "TEST.Q"; + String msgStr = "Test text message"; + int messagesPerThread = 20; + int producerThreads = 50; + int consumerCount = 2; + AtomicInteger sentCount; + AtomicInteger consumedCount; + CountDownLatch producerLatch; + CountDownLatch consumerLatch; + String brokerURL; + String userName = ""; + String password = ""; - @Override - protected void tearDown() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - super.tearDown(); - } + @Override + protected void setUp() throws Exception { + super.setUp(); + broker = new BrokerService(); + broker.setPersistent(true); + broker.setUseJmx(true); + broker.deleteAllMessages(); + broker.addConnector("tcp://localhost:0"); + broker.start(); + broker.waitUntilStarted(); + dest = new ActiveMQQueue(destinationName); + resetCounters(); + brokerURL = broker.getTransportConnectors().get(0).getPublishableConnectString(); + } - private void resetCounters() { - sentCount = new AtomicInteger(0); - consumedCount = new AtomicInteger(0); - producerLatch = new CountDownLatch(producerThreads); - consumerLatch = new CountDownLatch(consumerCount); - } + @Override + protected void tearDown() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + super.tearDown(); + } - public void testDispatch1() { - for (int i = 1; i <= 5; i++) { - resetCounters(); - dispatch(); - assertEquals("Incorrect messages in Iteration " + i, sentCount.get(), consumedCount.get()); - } - } + private void resetCounters() { + sentCount = new AtomicInteger(0); + consumedCount = new AtomicInteger(0); + producerLatch = new CountDownLatch(producerThreads); + consumerLatch = new CountDownLatch(consumerCount); + } - private void dispatch() { - startConsumers(); - startProducers(); - try { - producerLatch.await(); - consumerLatch.await(); - } catch (InterruptedException e) { - fail("test interrupted!"); - } - } + public void testDispatch1() { + for (int i = 1; i <= 5; i++) { + resetCounters(); + dispatch(); + assertEquals("Incorrect messages in Iteration " + i, sentCount.get(), consumedCount.get()); + } + } - private void startConsumers() { - ActiveMQConnectionFactory connFactory = new ActiveMQConnectionFactory(userName, password, brokerURL); - Connection conn; - try { + private void dispatch() { + startConsumers(); + startProducers(); + try { + producerLatch.await(); + consumerLatch.await(); + } + catch (InterruptedException e) { + fail("test interrupted!"); + } + } + + private void startConsumers() { + ActiveMQConnectionFactory connFactory = new ActiveMQConnectionFactory(userName, password, brokerURL); + Connection conn; + try { + conn = connFactory.createConnection(); + conn.start(); + for (int i = 0; i < consumerCount; i++) { + new ConsumerThread(conn, "ConsumerThread" + i); + } + } + catch (JMSException e) { + logger.error("Failed to start consumers", e); + } + } + + private void startProducers() { + ActiveMQConnectionFactory connFactory = new ActiveMQConnectionFactory(userName, password, brokerURL); + for (int i = 0; i < producerThreads; i++) { + new ProducerThread(connFactory, messagesPerThread, "ProducerThread" + i); + } + } + + private class ConsumerThread extends Thread { + + Session session; + MessageConsumer consumer; + + public ConsumerThread(Connection conn, String name) { + super(); + this.setName(name); + logger.trace("Created new consumer thread:" + name); + try { + session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumer = session.createConsumer(dest); + start(); + } + catch (JMSException e) { + logger.error("Failed to start consumer thread:" + name, e); + } + } + + @Override + public void run() { + int msgCount = 0; + int nullCount = 0; + while (true) { + try { + Message msg = consumer.receive(1000); + if (msg == null) { + if (producerLatch.getCount() > 0) { + continue; + } + nullCount++; + if (nullCount > 10) { + //assume that we are not getting any more messages + break; + } + else { + continue; + } + } + else { + nullCount = 0; + } + Thread.sleep(100); + if (logger.isTraceEnabled()) { + logger.trace("Message received:" + msg.getJMSMessageID()); + } + msgCount++; + } + catch (JMSException e) { + logger.error("Failed to consume:", e); + } + catch (InterruptedException e) { + logger.error("Interrupted!", e); + } + } + try { + consumer.close(); + } + catch (JMSException e) { + logger.error("Failed to close consumer " + getName(), e); + } + consumedCount.addAndGet(msgCount); + consumerLatch.countDown(); + logger.trace("Consumed " + msgCount + " messages using thread " + getName()); + } + } + + private class ProducerThread extends Thread { + + int count; + Connection conn; + Session session; + MessageProducer producer; + + public ProducerThread(ActiveMQConnectionFactory connFactory, int count, String name) { + super(); + this.count = count; + this.setName(name); + logger.trace("Created new producer thread:" + name); + try { conn = connFactory.createConnection(); conn.start(); - for (int i = 0; i < consumerCount; i++) { - new ConsumerThread(conn, "ConsumerThread"+i); - } - } catch (JMSException e) { - logger.error("Failed to start consumers", e); - } - } + session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer = session.createProducer(dest); + start(); + } + catch (JMSException e) { + logger.error("Failed to start producer thread:" + name, e); + } + } - private void startProducers() { - ActiveMQConnectionFactory connFactory = new ActiveMQConnectionFactory(userName, password, brokerURL); - for (int i = 0; i < producerThreads; i++) { - new ProducerThread(connFactory, messagesPerThread, "ProducerThread"+i); - } - } - - private class ConsumerThread extends Thread { - Session session; - MessageConsumer consumer; - - public ConsumerThread(Connection conn, String name) { - super(); - this.setName(name); - logger.trace("Created new consumer thread:" + name); - try { - session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = session.createConsumer(dest); - start(); - } catch (JMSException e) { - logger.error("Failed to start consumer thread:" + name, e); + @Override + public void run() { + int i = 0; + try { + for (; i < count; i++) { + producer.send(session.createTextMessage(msgStr)); + Thread.sleep(500); } - } - - @Override - public void run() { - int msgCount = 0; - int nullCount = 0; - while (true) { - try { - Message msg = consumer.receive(1000); - if (msg == null) { - if (producerLatch.getCount() > 0) { - continue; - } - nullCount++; - if (nullCount > 10) { - //assume that we are not getting any more messages - break; - } else { - continue; - } - } else { - nullCount = 0; - } - Thread.sleep(100); - if (logger.isTraceEnabled()) { - logger.trace("Message received:" + msg.getJMSMessageID()); - } - msgCount++; - } catch (JMSException e) { - logger.error("Failed to consume:", e); - } catch (InterruptedException e) { - logger.error("Interrupted!", e); - } - } - try { - consumer.close(); - } catch (JMSException e) { - logger.error("Failed to close consumer " + getName(), e); - } - consumedCount.addAndGet(msgCount); - consumerLatch.countDown(); - logger.trace("Consumed " + msgCount + " messages using thread " + getName()); - } - } - - private class ProducerThread extends Thread { - int count; - Connection conn; - Session session; - MessageProducer producer; - - public ProducerThread(ActiveMQConnectionFactory connFactory, int count, String name) { - super(); - this.count = count; - this.setName(name); - logger.trace("Created new producer thread:" + name); - try { - conn = connFactory.createConnection(); - conn.start(); - session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(dest); - start(); - } catch (JMSException e) { - logger.error("Failed to start producer thread:" + name, e); - } - } - - @Override - public void run() { - int i = 0; - try { - for (; i < count; i++) { - producer.send(session.createTextMessage(msgStr)); - Thread.sleep(500); - } - conn.close(); - } catch (JMSException e) { - logger.error(e.getMessage(), e); - } catch (InterruptedException e) { - logger.error("Interrupted!", e); - } - sentCount.addAndGet(i); - producerLatch.countDown(); - if (logger.isTraceEnabled()) { - logger.trace("Sent " + i + " messages from thread " + getName()); - } - } - } + conn.close(); + } + catch (JMSException e) { + logger.error(e.getMessage(), e); + } + catch (InterruptedException e) { + logger.error("Interrupted!", e); + } + sentCount.addAndGet(i); + producerLatch.countDown(); + if (logger.isTraceEnabled()) { + logger.trace("Sent " + i + " messages from thread " + getName()); + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableConsumerCloseAndReconnectTcpTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableConsumerCloseAndReconnectTcpTest.java index ac7bd62776..bccd3673c6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableConsumerCloseAndReconnectTcpTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableConsumerCloseAndReconnectTcpTest.java @@ -38,156 +38,171 @@ import org.apache.activemq.util.URISupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class DurableConsumerCloseAndReconnectTcpTest extends DurableConsumerCloseAndReconnectTest -implements ExceptionListener, TransportListener { - private static final Logger LOG = LoggerFactory.getLogger(DurableConsumerCloseAndReconnectTcpTest.class); - - private BrokerService broker; - private TransportConnector connector; +public class DurableConsumerCloseAndReconnectTcpTest extends DurableConsumerCloseAndReconnectTest implements ExceptionListener, TransportListener { - private CountDownLatch gotException = new CountDownLatch(1); + private static final Logger LOG = LoggerFactory.getLogger(DurableConsumerCloseAndReconnectTcpTest.class); - private Exception reconnectException; + private BrokerService broker; + private TransportConnector connector; - private boolean reconnectInExceptionListener; + private CountDownLatch gotException = new CountDownLatch(1); - private boolean reconnectInTransportListener; - - public void setUp() throws Exception { - broker = new BrokerService(); - // let the client initiate the inactivity timeout - connector = broker.addConnector("tcp://localhost:0?transport.useInactivityMonitor=false"); - broker.setPersistent(false); - broker.start(); - broker.waitUntilStarted(); - - class SlowCloseSocketTcpTransportFactory extends TcpTransportFactory { + private Exception reconnectException; - class SlowCloseSocketFactory extends SocketFactory { - - class SlowCloseSocket extends Socket { - public SlowCloseSocket(String host, int port) throws IOException { - super(host, port); - } + private boolean reconnectInExceptionListener; - public SlowCloseSocket(InetAddress host, int port) throws IOException { - super(host, port); - } + private boolean reconnectInTransportListener; - public SlowCloseSocket(String host, int port, InetAddress localHost, int localPort) throws IOException { - super(host, port, localHost, localPort); - } + public void setUp() throws Exception { + broker = new BrokerService(); + // let the client initiate the inactivity timeout + connector = broker.addConnector("tcp://localhost:0?transport.useInactivityMonitor=false"); + broker.setPersistent(false); + broker.start(); + broker.waitUntilStarted(); - public SlowCloseSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { - super(address, port, localAddress, localPort); - } + class SlowCloseSocketTcpTransportFactory extends TcpTransportFactory { - @Override - public synchronized void close() throws IOException { - LOG.info("delaying close"); - try { - TimeUnit.MILLISECONDS.sleep(500); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - super.close(); - } - - - } - @Override - public Socket createSocket(String host, int port) throws IOException, UnknownHostException { - return new SlowCloseSocket(host, port); - } + class SlowCloseSocketFactory extends SocketFactory { - @Override - public Socket createSocket(InetAddress host, int port) throws IOException { - return new SlowCloseSocket(host, port); - } + class SlowCloseSocket extends Socket { - @Override - public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, - UnknownHostException { - return new SlowCloseSocket(host, port, localHost, localPort); - } + public SlowCloseSocket(String host, int port) throws IOException { + super(host, port); + } + + public SlowCloseSocket(InetAddress host, int port) throws IOException { + super(host, port); + } + + public SlowCloseSocket(String host, int port, InetAddress localHost, int localPort) throws IOException { + super(host, port, localHost, localPort); + } + + public SlowCloseSocket(InetAddress address, + int port, + InetAddress localAddress, + int localPort) throws IOException { + super(address, port, localAddress, localPort); + } + + @Override + public synchronized void close() throws IOException { + LOG.info("delaying close"); + try { + TimeUnit.MILLISECONDS.sleep(500); + } + catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + super.close(); + } - @Override - public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { - return new SlowCloseSocket(address, port, localAddress, localPort); - } - } + @Override - protected SocketFactory createSocketFactory() throws IOException { - return new SlowCloseSocketFactory(); + public Socket createSocket(String host, int port) throws IOException, UnknownHostException { + return new SlowCloseSocket(host, port); } - - } - - TransportFactory.registerTransportFactory("tcp", new SlowCloseSocketTcpTransportFactory()); - - } - - public void tearDown() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(URISupport.removeQuery(connector.getConnectUri()) + "?useKeepAlive=false&wireFormat.maxInactivityDuration=2000"); - } - - @Override - public void testCreateDurableConsumerCloseThenReconnect() throws Exception { - reconnectInExceptionListener = true; - makeConsumer(); - connection.setExceptionListener(this); - ((ActiveMQConnection)connection).addTransportListener(this); - assertTrue("inactive connection timedout", gotException.await(30, TimeUnit.SECONDS)); - assertNotNull("Got expected exception on close reconnect overlap: " + reconnectException, reconnectException); - } - - - public void testCreateDurableConsumerSlowCloseThenReconnectTransportListener() throws Exception { - reconnectInTransportListener = true; - makeConsumer(); - connection.setExceptionListener(this); - ((ActiveMQConnection)connection).addTransportListener(this); - assertTrue("inactive connection timedout", gotException.await(30, TimeUnit.SECONDS)); - assertNull("No exception: " + reconnectException, reconnectException); - } - - public void onException(JMSException exception) { - LOG.info("Exception listener exception:" + exception); - if (reconnectInExceptionListener) { - try { - makeConsumer(); - } catch (Exception e) { - reconnectException = e; + @Override + public Socket createSocket(InetAddress host, int port) throws IOException { + return new SlowCloseSocket(host, port); } - - gotException.countDown(); - } - } - public void onCommand(Object command) {} + @Override + public Socket createSocket(String host, + int port, + InetAddress localHost, + int localPort) throws IOException, UnknownHostException { + return new SlowCloseSocket(host, port, localHost, localPort); + } - public void onException(IOException error) { - LOG.info("Transport listener exception:" + error); - if (reconnectInTransportListener) { - try { - TimeUnit.MILLISECONDS.sleep(500); - makeConsumer(); - } catch (Exception e) { - reconnectException = e; - } - - gotException.countDown(); - } - } + @Override + public Socket createSocket(InetAddress address, + int port, + InetAddress localAddress, + int localPort) throws IOException { + return new SlowCloseSocket(address, port, localAddress, localPort); + } - public void transportInterupted() {} + } - public void transportResumed() {} + @Override + protected SocketFactory createSocketFactory() throws IOException { + return new SlowCloseSocketFactory(); + } + + } + + TransportFactory.registerTransportFactory("tcp", new SlowCloseSocketTcpTransportFactory()); + + } + + public void tearDown() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + } + + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory(URISupport.removeQuery(connector.getConnectUri()) + "?useKeepAlive=false&wireFormat.maxInactivityDuration=2000"); + } + + @Override + public void testCreateDurableConsumerCloseThenReconnect() throws Exception { + reconnectInExceptionListener = true; + makeConsumer(); + connection.setExceptionListener(this); + ((ActiveMQConnection) connection).addTransportListener(this); + assertTrue("inactive connection timedout", gotException.await(30, TimeUnit.SECONDS)); + assertNotNull("Got expected exception on close reconnect overlap: " + reconnectException, reconnectException); + } + + public void testCreateDurableConsumerSlowCloseThenReconnectTransportListener() throws Exception { + reconnectInTransportListener = true; + makeConsumer(); + connection.setExceptionListener(this); + ((ActiveMQConnection) connection).addTransportListener(this); + assertTrue("inactive connection timedout", gotException.await(30, TimeUnit.SECONDS)); + assertNull("No exception: " + reconnectException, reconnectException); + } + + public void onException(JMSException exception) { + LOG.info("Exception listener exception:" + exception); + if (reconnectInExceptionListener) { + try { + makeConsumer(); + } + catch (Exception e) { + reconnectException = e; + } + + gotException.countDown(); + } + } + + public void onCommand(Object command) { + } + + public void onException(IOException error) { + LOG.info("Transport listener exception:" + error); + if (reconnectInTransportListener) { + try { + TimeUnit.MILLISECONDS.sleep(500); + makeConsumer(); + } + catch (Exception e) { + reconnectException = e; + } + + gotException.countDown(); + } + } + + public void transportInterupted() { + } + + public void transportResumed() { + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableConsumerCloseAndReconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableConsumerCloseAndReconnectTest.java index 32c2d2c325..7ad8a2e26d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableConsumerCloseAndReconnectTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableConsumerCloseAndReconnectTest.java @@ -38,209 +38,211 @@ import org.slf4j.LoggerFactory; import java.io.IOException; /** - * + * */ public class DurableConsumerCloseAndReconnectTest extends TestSupport { - protected static final long RECEIVE_TIMEOUT = 5000L; - private static final Logger LOG = LoggerFactory.getLogger(DurableConsumerCloseAndReconnectTest.class); - BrokerService brokerService; + protected static final long RECEIVE_TIMEOUT = 5000L; + private static final Logger LOG = LoggerFactory.getLogger(DurableConsumerCloseAndReconnectTest.class); - protected Connection connection; - private Session session; - private MessageConsumer consumer; - private MessageProducer producer; - private Destination destination; - private int messageCount; + BrokerService brokerService; - private String vmConnectorURI; + protected Connection connection; + private Session session; + private MessageConsumer consumer; + private MessageProducer producer; + private Destination destination; + private int messageCount; - - @Override - protected void setUp() throws Exception { - createBroker(); - super.setUp(); - } + private String vmConnectorURI; - @Override - protected void tearDown() throws Exception { - stopBroker(); - super.tearDown(); - } + @Override + protected void setUp() throws Exception { + createBroker(); + super.setUp(); + } - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(vmConnectorURI); - } + @Override + protected void tearDown() throws Exception { + stopBroker(); + super.tearDown(); + } - protected void createBroker() throws Exception { - brokerService = new BrokerService(); - brokerService.setUseJmx(false); - brokerService.setPersistent(false); - KahaDBPersistenceAdapter store = new KahaDBPersistenceAdapter(); - brokerService.setPersistenceAdapter(store); - brokerService.start(); - brokerService.waitUntilStarted(); - vmConnectorURI = brokerService.getVmConnectorURI().toString(); - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory(vmConnectorURI); + } - protected void stopBroker() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - } + protected void createBroker() throws Exception { + brokerService = new BrokerService(); + brokerService.setUseJmx(false); + brokerService.setPersistent(false); + KahaDBPersistenceAdapter store = new KahaDBPersistenceAdapter(); + brokerService.setPersistenceAdapter(store); + brokerService.start(); + brokerService.waitUntilStarted(); + vmConnectorURI = brokerService.getVmConnectorURI().toString(); + } - public void testDurableSubscriberReconnectMultipleTimes() throws Exception { - Connection dummyConnection = createConnection(); - dummyConnection.start(); + protected void stopBroker() throws Exception { + brokerService.stop(); + brokerService.waitUntilStopped(); + } - makeConsumer(Session.AUTO_ACKNOWLEDGE); - closeConsumer(); + public void testDurableSubscriberReconnectMultipleTimes() throws Exception { + Connection dummyConnection = createConnection(); + dummyConnection.start(); - publish(30); + makeConsumer(Session.AUTO_ACKNOWLEDGE); + closeConsumer(); - int counter = 1; - for (int i = 0; i < 15; i++) { - makeConsumer(Session.AUTO_ACKNOWLEDGE); - Message message = consumer.receive(RECEIVE_TIMEOUT); - assertTrue("Should have received a message!", message != null); - LOG.info("Received message " + counter++); - message = consumer.receive(RECEIVE_TIMEOUT); - assertTrue("Should have received a message!", message != null); - LOG.info("Received message " + counter++); - closeConsumer(); - } + publish(30); - dummyConnection.close(); - } + int counter = 1; + for (int i = 0; i < 15; i++) { + makeConsumer(Session.AUTO_ACKNOWLEDGE); + Message message = consumer.receive(RECEIVE_TIMEOUT); + assertTrue("Should have received a message!", message != null); + LOG.info("Received message " + counter++); + message = consumer.receive(RECEIVE_TIMEOUT); + assertTrue("Should have received a message!", message != null); + LOG.info("Received message " + counter++); + closeConsumer(); + } - public void testCreateDurableConsumerCloseThenReconnect() throws Exception { - // force the server to stay up across both connection tests - Connection dummyConnection = createConnection(); - dummyConnection.start(); + dummyConnection.close(); + } - consumeMessagesDeliveredWhileConsumerClosed(); + public void testCreateDurableConsumerCloseThenReconnect() throws Exception { + // force the server to stay up across both connection tests + Connection dummyConnection = createConnection(); + dummyConnection.start(); - dummyConnection.close(); + consumeMessagesDeliveredWhileConsumerClosed(); - // now lets try again without one connection open - consumeMessagesDeliveredWhileConsumerClosed(); - } + dummyConnection.close(); - protected void consumeMessagesDeliveredWhileConsumerClosed() throws Exception { - // default to client ack for consumer - makeConsumer(); - closeConsumer(); + // now lets try again without one connection open + consumeMessagesDeliveredWhileConsumerClosed(); + } - publish(1); + protected void consumeMessagesDeliveredWhileConsumerClosed() throws Exception { + // default to client ack for consumer + makeConsumer(); + closeConsumer(); - // wait a few moments for the close to really occur - Thread.sleep(1000); + publish(1); - makeConsumer(); + // wait a few moments for the close to really occur + Thread.sleep(1000); - Message message = consumer.receive(RECEIVE_TIMEOUT); - assertTrue("Should have received a message!", message != null); + makeConsumer(); - closeConsumer(); + Message message = consumer.receive(RECEIVE_TIMEOUT); + assertTrue("Should have received a message!", message != null); - LOG.info("Now lets create the consumer again and because we didn't ack, we should get it again"); - makeConsumer(); + closeConsumer(); - message = consumer.receive(RECEIVE_TIMEOUT); - assertTrue("Should have received a message!", message != null); - message.acknowledge(); + LOG.info("Now lets create the consumer again and because we didn't ack, we should get it again"); + makeConsumer(); - closeConsumer(); + message = consumer.receive(RECEIVE_TIMEOUT); + assertTrue("Should have received a message!", message != null); + message.acknowledge(); - LOG.info("Now lets create the consumer again and because we did ack, we should not get it again"); - makeConsumer(); + closeConsumer(); - message = consumer.receive(2000); - assertTrue("Should have no more messages left!", message == null); + LOG.info("Now lets create the consumer again and because we did ack, we should not get it again"); + makeConsumer(); - closeConsumer(); + message = consumer.receive(2000); + assertTrue("Should have no more messages left!", message == null); - LOG.info("Lets publish one more message now"); - publish(1); + closeConsumer(); - makeConsumer(); - message = consumer.receive(RECEIVE_TIMEOUT); - assertTrue("Should have received a message!", message != null); - message.acknowledge(); + LOG.info("Lets publish one more message now"); + publish(1); - closeConsumer(); - } + makeConsumer(); + message = consumer.receive(RECEIVE_TIMEOUT); + assertTrue("Should have received a message!", message != null); + message.acknowledge(); - protected void publish(int numMessages) throws Exception { - connection = createConnection(); - connection.start(); + closeConsumer(); + } - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - destination = createDestination(); + protected void publish(int numMessages) throws Exception { + connection = createConnection(); + connection.start(); - producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - for (int i = 0; i < numMessages; i++) { - TextMessage msg = session.createTextMessage("This is a test: " + messageCount++); - producer.send(msg); - } + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + destination = createDestination(); - producer.close(); - producer = null; - closeSession(); - } + producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + for (int i = 0; i < numMessages; i++) { + TextMessage msg = session.createTextMessage("This is a test: " + messageCount++); + producer.send(msg); + } - protected Destination createDestination() throws JMSException { - if (isTopic()) { - return session.createTopic(getSubject()); - } else { - return session.createQueue(getSubject()); - } - } + producer.close(); + producer = null; + closeSession(); + } - protected boolean isTopic() { - return true; - } + protected Destination createDestination() throws JMSException { + if (isTopic()) { + return session.createTopic(getSubject()); + } + else { + return session.createQueue(getSubject()); + } + } - protected void closeConsumer() throws JMSException { - LOG.info("Closing the consumer"); - consumer.close(); - consumer = null; - closeSession(); - } + protected boolean isTopic() { + return true; + } - protected void closeSession() throws JMSException { - session.close(); - session = null; - connection.close(); - connection = null; - } + protected void closeConsumer() throws JMSException { + LOG.info("Closing the consumer"); + consumer.close(); + consumer = null; + closeSession(); + } - protected void makeConsumer() throws Exception { - makeConsumer(Session.CLIENT_ACKNOWLEDGE); - } + protected void closeSession() throws JMSException { + session.close(); + session = null; + connection.close(); + connection = null; + } - protected void makeConsumer(int ackMode) throws Exception { - String durableName = getName(); - String clientID = getSubject(); - LOG.info("Creating a durable subscriber for clientID: " + clientID + " and durable name: " + durableName); - createSession(clientID, ackMode); - consumer = createConsumer(durableName); - } + protected void makeConsumer() throws Exception { + makeConsumer(Session.CLIENT_ACKNOWLEDGE); + } - private MessageConsumer createConsumer(String durableName) throws JMSException { - if (destination instanceof Topic) { - return session.createDurableSubscriber((Topic)destination, durableName); - } else { - return session.createConsumer(destination); - } - } + protected void makeConsumer(int ackMode) throws Exception { + String durableName = getName(); + String clientID = getSubject(); + LOG.info("Creating a durable subscriber for clientID: " + clientID + " and durable name: " + durableName); + createSession(clientID, ackMode); + consumer = createConsumer(durableName); + } - protected void createSession(String clientID, int ackMode) throws Exception { - connection = createConnection(); - connection.setClientID(clientID); - connection.start(); + private MessageConsumer createConsumer(String durableName) throws JMSException { + if (destination instanceof Topic) { + return session.createDurableSubscriber((Topic) destination, durableName); + } + else { + return session.createConsumer(destination); + } + } - session = connection.createSession(false, ackMode); - destination = createDestination(); - } + protected void createSession(String clientID, int ackMode) throws Exception { + connection = createConnection(); + connection.setClientID(clientID); + connection.start(); + + session = connection.createSession(false, ackMode); + destination = createDestination(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubDelayedUnsubscribeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubDelayedUnsubscribeTest.java index aeda7c2d82..d04cad6603 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubDelayedUnsubscribeTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubDelayedUnsubscribeTest.java @@ -55,726 +55,734 @@ import org.slf4j.LoggerFactory; */ public class DurableSubDelayedUnsubscribeTest { - private static final Logger LOG = LoggerFactory.getLogger(DurableSubDelayedUnsubscribeTest.class); + private static final Logger LOG = LoggerFactory.getLogger(DurableSubDelayedUnsubscribeTest.class); - private static final long RUNTIME = 2 * 60 * 1000; - private static final int CARGO_SIZE = 400; // max - private static final int MAX_CLIENTS = 15; - private static boolean ALLOW_SUBSCRIPTION_ABANDONMENT = true; - private static final Vector exceptions = new Vector(); + private static final long RUNTIME = 2 * 60 * 1000; + private static final int CARGO_SIZE = 400; // max + private static final int MAX_CLIENTS = 15; + private static boolean ALLOW_SUBSCRIPTION_ABANDONMENT = true; + private static final Vector exceptions = new Vector(); - private BrokerService broker; - private ActiveMQTopic topic; + private BrokerService broker; + private ActiveMQTopic topic; - private ClientManager clientManager; - private Server server; - private HouseKeeper houseKeeper; + private ClientManager clientManager; + private Server server; + private HouseKeeper houseKeeper; - private final ReentrantReadWriteLock processLock = new ReentrantReadWriteLock(true); + private final ReentrantReadWriteLock processLock = new ReentrantReadWriteLock(true); - @Test - public void testProcess() throws Exception { + @Test + public void testProcess() throws Exception { - server.start(); - clientManager.start(); + server.start(); + clientManager.start(); - houseKeeper.start(); + houseKeeper.start(); - // Sleep to - Thread.sleep(RUNTIME); + // Sleep to + Thread.sleep(RUNTIME); - // inform message producer to stop - server.stopped = true; + // inform message producer to stop + server.stopped = true; - // add one Subscriber to the topic that will not be unsubscribed. - // should not have any pending messages in the kahadb store - Client lastClient = new Client(32000, ClientType.A); - lastClient.process(1000); + // add one Subscriber to the topic that will not be unsubscribed. + // should not have any pending messages in the kahadb store + Client lastClient = new Client(32000, ClientType.A); + lastClient.process(1000); - // stop client manager from creating any more clients - clientManager.stopped = true; + // stop client manager from creating any more clients + clientManager.stopped = true; - final BrokerService brokerService = this.broker; + final BrokerService brokerService = this.broker; - // Wait for all client subscription to be unsubscribed or swept away. - // Ensure we sleep longer than the housekeeper's sweep delay otherwise we can - // miss the fact that all durables that were abandoned do finally get cleaned up. + // Wait for all client subscription to be unsubscribed or swept away. + // Ensure we sleep longer than the housekeeper's sweep delay otherwise we can + // miss the fact that all durables that were abandoned do finally get cleaned up. - // Wait for all clients to stop - Wait.waitFor(new Wait.Condition() { - public boolean isSatisified() throws Exception { - return clientManager.getClientCount() == 0; - } - }, Client.lifetime + TimeUnit.SECONDS.toMillis(10)); + // Wait for all clients to stop + Wait.waitFor(new Wait.Condition() { + public boolean isSatisified() throws Exception { + return clientManager.getClientCount() == 0; + } + }, Client.lifetime + TimeUnit.SECONDS.toMillis(10)); - assertTrue("should have only one inactiveSubscriber subscribed but was: " + brokerService.getAdminView().getInactiveDurableTopicSubscribers().length, - Wait.waitFor(new Wait.Condition() { + assertTrue("should have only one inactiveSubscriber subscribed but was: " + brokerService.getAdminView().getInactiveDurableTopicSubscribers().length, Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return brokerService.getAdminView().getInactiveDurableTopicSubscribers().length == 1; - } - }, houseKeeper.SWEEP_DELAY * 2)); - - assertTrue("should be no subscribers subscribed but was: " + brokerService.getAdminView().getDurableTopicSubscribers().length, - Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - return brokerService.getAdminView().getDurableTopicSubscribers().length == 0; - } - }, TimeUnit.MINUTES.toMillis(3))); - - processLock.writeLock().lock(); - - // check outcome. - - ObjectName[] subscribers = broker.getAdminView().getDurableTopicSubscribers(); - ObjectName[] inactiveSubscribers = broker.getAdminView().getInactiveDurableTopicSubscribers(); - final KahaDBPersistenceAdapter persistenceAdapter = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); - - printDebugClientInfo(subscribers, inactiveSubscribers, persistenceAdapter); - - assertEquals("should have only one inactiveSubscriber subscribed", 1, broker.getAdminView().getInactiveDurableTopicSubscribers().length); - assertEquals("should be no subscribers subscribed", 0, broker.getAdminView().getDurableTopicSubscribers().length); - - final KahaDBPersistenceAdapter pa = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); - assertTrue("should be less than 3 journal file left but was: " + persistenceAdapter.getStore().getJournal().getFileMap().size(), - Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - return pa.getStore().getJournal().getFileMap().size() <= 3; - } - }, TimeUnit.MINUTES.toMillis(3))); - - // Be good and cleanup our mess a bit. - this.houseKeeper.shutdown(); - - assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); - - LOG.info("DONE."); - } - - private void printDebugClientInfo(ObjectName[] subscribers, ObjectName[] inactiveSubscribers, final KahaDBPersistenceAdapter pa) throws IOException { - - LOG.info("====>>> START DEBUG Subscriber INFO"); - - LOG.info("Number of subscribers subscribed as seen through JMX is" + subscribers.length); - - for (int i = 0; i < subscribers.length; i++) { - LOG.info("subscribers subscribed as seen throngh JMX: " + subscribers[i]); - } - - LOG.info("Number of inactiveSubscribers subscribed as seen through JMX is" + inactiveSubscribers.length); - - for (int i = 0; i < inactiveSubscribers.length; i++) { - LOG.info("subscribers subscribed as seen throngh JMX: " + inactiveSubscribers[i]); - } - - LOG.info("ClientManager.clients size is" + clientManager.clients.size()); - - for (int i = 0; i < clientManager.clients.size(); i++) { - LOG.info("clients is: " + clientManager.clients.get(i)); - } - - LOG.info("housekeep.subscriptions size is " + houseKeeper.abandonedSubscriptions.size()); - - for (int i = 0; i < houseKeeper.abandonedSubscriptions.size(); i++) { - LOG.info("housekeep is: " + houseKeeper.abandonedSubscriptions.get(i)); - } - - LOG.info("number of journal files left" + pa.getStore().getJournal().getFileMap().size()); - - LOG.info("====>>> END DEBUG Subscriber INFO"); - } - - /** - * Creates batch of messages in a transaction periodically. The last message - * in the transaction is always a special message what contains info about - * the whole transaction. - *

    - * Notifies the clients about the created messages also. - */ - final class Server extends Thread { - - public boolean stopped; - final String url = "vm://" + DurableSubDelayedUnsubscribeTest.getName() + "?" - + "jms.redeliveryPolicy.maximumRedeliveries=2&jms.redeliveryPolicy.initialRedeliveryDelay=500&" - + "jms.producerWindowSize=20971520&jms.prefetchPolicy.all=100&" + "jms.copyMessageOnSend=false&jms.disableTimeStampsByDefault=false&" - + "jms.alwaysSyncSend=true&jms.dispatchAsync=false&" + "jms.watchTopicAdvisories=false&" + "waitForStart=200&create=false"; - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); - - final Object sendMutex = new Object(); - final String[] cargos = new String[500]; - - int transRover = 0; - int messageRover = 0; - - public Server() { - super("Server"); - setDaemon(true); - } - - @Override - public void run() { - try { - while (true) { - - if (stopped) { - // server should stop producing - break; + @Override + public boolean isSatisified() throws Exception { + return brokerService.getAdminView().getInactiveDurableTopicSubscribers().length == 1; } + }, houseKeeper.SWEEP_DELAY * 2)); - Thread.sleep(500); - processLock.readLock().lock(); - try { - send(); - } finally { - processLock.readLock().unlock(); + assertTrue("should be no subscribers subscribed but was: " + brokerService.getAdminView().getDurableTopicSubscribers().length, Wait.waitFor(new Wait.Condition() { + + @Override + public boolean isSatisified() throws Exception { + return brokerService.getAdminView().getDurableTopicSubscribers().length == 0; } - } - } catch (Throwable e) { - exit("Server.run failed", e); - } - } + }, TimeUnit.MINUTES.toMillis(3))); - public void send() throws JMSException { - // do not create new clients now - // ToDo: Test this case later. - synchronized (sendMutex) { - int trans = ++transRover; - boolean relevantTrans = random(2) > 1; - ClientType clientType = relevantTrans ? ClientType.randomClientType() : null; // sends - // this - // types - int count = random(200); + processLock.writeLock().lock(); - LOG.info("Sending Trans[id=" + trans + ", count=" + count + ", clientType=" + clientType + "]"); + // check outcome. - Connection con = cf.createConnection(); - Session sess = con.createSession(true, Session.SESSION_TRANSACTED); - MessageProducer prod = sess.createProducer(null); + ObjectName[] subscribers = broker.getAdminView().getDurableTopicSubscribers(); + ObjectName[] inactiveSubscribers = broker.getAdminView().getInactiveDurableTopicSubscribers(); + final KahaDBPersistenceAdapter persistenceAdapter = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); - for (int i = 0; i < count; i++) { - Message message = sess.createMessage(); - message.setIntProperty("ID", ++messageRover); - message.setIntProperty("TRANS", trans); - String type = clientType != null ? clientType.randomMessageType() : ClientType.randomNonRelevantMessageType(); - message.setStringProperty("TYPE", type); + printDebugClientInfo(subscribers, inactiveSubscribers, persistenceAdapter); - if (CARGO_SIZE > 0) - message.setStringProperty("CARGO", getCargo(random(CARGO_SIZE))); + assertEquals("should have only one inactiveSubscriber subscribed", 1, broker.getAdminView().getInactiveDurableTopicSubscribers().length); + assertEquals("should be no subscribers subscribed", 0, broker.getAdminView().getDurableTopicSubscribers().length); - prod.send(topic, message); + final KahaDBPersistenceAdapter pa = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); + assertTrue("should be less than 3 journal file left but was: " + persistenceAdapter.getStore().getJournal().getFileMap().size(), Wait.waitFor(new Wait.Condition() { - } - - Message message = sess.createMessage(); - message.setIntProperty("ID", ++messageRover); - message.setIntProperty("TRANS", trans); - message.setBooleanProperty("COMMIT", true); - message.setBooleanProperty("RELEVANT", relevantTrans); - prod.send(topic, message); - - sess.commit(); - LOG.info("Committed Trans[id=" + trans + ", count=" + count + ", clientType=" + clientType + "], ID=" + messageRover); - - sess.close(); - con.close(); - } - } - - private String getCargo(int length) { - if (length == 0) - return null; - - if (length < cargos.length) { - String result = cargos[length]; - if (result == null) { - result = getCargoImpl(length); - cargos[length] = result; - } - return result; - } - return getCargoImpl(length); - } - - private String getCargoImpl(int length) { - StringBuilder sb = new StringBuilder(length); - for (int i = length; --i >= 0;) { - sb.append('a'); - } - return sb.toString(); - } - } - - /** - * Clients listen on different messages in the topic. The 'TYPE' property - * helps the client to select the proper messages. - */ - private enum ClientType { - A("a", "b", "c"), B("c", "d", "e"), C("d", "e", "f"), D("g", "h"); - - public final String[] messageTypes; - - public final String selector; - - ClientType(String... messageTypes) { - this.messageTypes = messageTypes; - - StringBuilder sb = new StringBuilder("TYPE in ("); - for (int i = 0; i < messageTypes.length; i++) { - if (i > 0) - sb.append(", "); - sb.append('\'').append(messageTypes[i]).append('\''); - } - sb.append(')'); - selector = sb.toString(); - } - - public static ClientType randomClientType() { - return values()[DurableSubDelayedUnsubscribeTest.random(values().length - 1)]; - } - - public final String randomMessageType() { - return messageTypes[DurableSubDelayedUnsubscribeTest.random(messageTypes.length - 1)]; - } - - public static String randomNonRelevantMessageType() { - return Integer.toString(DurableSubDelayedUnsubscribeTest.random(20)); - } - - @Override - public final String toString() { - return this.name() /* + '[' + selector + ']' */; - } - } - - /** - * Creates new cliens. - */ - private final class ClientManager extends Thread { - - private int clientRover = 0; - - private final CopyOnWriteArrayList clients = new CopyOnWriteArrayList(); - - private boolean stopped; - - public ClientManager() { - super("ClientManager"); - setDaemon(true); - } - - public int getClientCount() { - return clients.size(); - } - - @Override - public void run() { - try { - while (true) { - if (clients.size() < MAX_CLIENTS) { - - if (stopped) { - // get out, don't start any more threads - break; - } - processLock.readLock().lock(); - try { - createNewClient(); - } finally { - processLock.readLock().unlock(); - } + @Override + public boolean isSatisified() throws Exception { + return pa.getStore().getJournal().getFileMap().size() <= 3; } + }, TimeUnit.MINUTES.toMillis(3))); - int size = clients.size(); - sleepRandom(size * 3 * 1000, size * 6 * 1000); - } - } catch (Throwable e) { - exit("ClientManager.run failed.", e); + // Be good and cleanup our mess a bit. + this.houseKeeper.shutdown(); + + assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); + + LOG.info("DONE."); + } + + private void printDebugClientInfo(ObjectName[] subscribers, + ObjectName[] inactiveSubscribers, + final KahaDBPersistenceAdapter pa) throws IOException { + + LOG.info("====>>> START DEBUG Subscriber INFO"); + + LOG.info("Number of subscribers subscribed as seen through JMX is" + subscribers.length); + + for (int i = 0; i < subscribers.length; i++) { + LOG.info("subscribers subscribed as seen throngh JMX: " + subscribers[i]); + } + + LOG.info("Number of inactiveSubscribers subscribed as seen through JMX is" + inactiveSubscribers.length); + + for (int i = 0; i < inactiveSubscribers.length; i++) { + LOG.info("subscribers subscribed as seen throngh JMX: " + inactiveSubscribers[i]); + } + + LOG.info("ClientManager.clients size is" + clientManager.clients.size()); + + for (int i = 0; i < clientManager.clients.size(); i++) { + LOG.info("clients is: " + clientManager.clients.get(i)); + } + + LOG.info("housekeep.subscriptions size is " + houseKeeper.abandonedSubscriptions.size()); + + for (int i = 0; i < houseKeeper.abandonedSubscriptions.size(); i++) { + LOG.info("housekeep is: " + houseKeeper.abandonedSubscriptions.get(i)); + } + + LOG.info("number of journal files left" + pa.getStore().getJournal().getFileMap().size()); + + LOG.info("====>>> END DEBUG Subscriber INFO"); + } + + /** + * Creates batch of messages in a transaction periodically. The last message + * in the transaction is always a special message what contains info about + * the whole transaction. + *

    + * Notifies the clients about the created messages also. + */ + final class Server extends Thread { + + public boolean stopped; + final String url = "vm://" + DurableSubDelayedUnsubscribeTest.getName() + "?" + "jms.redeliveryPolicy.maximumRedeliveries=2&jms.redeliveryPolicy.initialRedeliveryDelay=500&" + "jms.producerWindowSize=20971520&jms.prefetchPolicy.all=100&" + "jms.copyMessageOnSend=false&jms.disableTimeStampsByDefault=false&" + "jms.alwaysSyncSend=true&jms.dispatchAsync=false&" + "jms.watchTopicAdvisories=false&" + "waitForStart=200&create=false"; + final ConnectionFactory cf = new ActiveMQConnectionFactory(url); + + final Object sendMutex = new Object(); + final String[] cargos = new String[500]; + + int transRover = 0; + int messageRover = 0; + + public Server() { + super("Server"); + setDaemon(true); + } + + @Override + public void run() { + try { + while (true) { + + if (stopped) { + // server should stop producing + break; + } + + Thread.sleep(500); + processLock.readLock().lock(); + try { + send(); + } + finally { + processLock.readLock().unlock(); + } } - } + } + catch (Throwable e) { + exit("Server.run failed", e); + } + } - private void createNewClient() throws JMSException { - ClientType type = ClientType.randomClientType(); + public void send() throws JMSException { + // do not create new clients now + // ToDo: Test this case later. + synchronized (sendMutex) { + int trans = ++transRover; + boolean relevantTrans = random(2) > 1; + ClientType clientType = relevantTrans ? ClientType.randomClientType() : null; // sends + // this + // types + int count = random(200); - Client client; - synchronized (server.sendMutex) { - client = new Client(++clientRover, type); - clients.add(client); - } - client.start(); + LOG.info("Sending Trans[id=" + trans + ", count=" + count + ", clientType=" + clientType + "]"); - LOG.info(client.toString() + " created. " + this); - } - - public void removeClient(Client client) { - clients.remove(client); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("ClientManager[count="); - sb.append(clients.size()); - sb.append(", clients="); - boolean sep = false; - for (Client client : clients) { - if (sep) - sb.append(", "); - else - sep = true; - sb.append(client.toString()); - } - sb.append(']'); - return sb.toString(); - } - } - - /** - * Consumes massages from a durable subscription. Goes online/offline - * periodically. Checks the incoming messages against the sent messages of - * the server. - */ - private final class Client extends Thread { - - String url = "failover:(tcp://localhost:61656?wireFormat.maxInactivityDuration=0)?" + "jms.watchTopicAdvisories=false&" - + "jms.alwaysSyncSend=true&jms.dispatchAsync=true&" + "jms.producerWindowSize=20971520&" + "jms.copyMessageOnSend=false&" - + "initialReconnectDelay=100&maxReconnectDelay=30000&" + "useExponentialBackOff=true"; - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); - - public static final String SUBSCRIPTION_NAME = "subscription"; - - private final int id; - private final String conClientId; - - public static final int lifetime = 60 * 1000; - private final int online = 1 * 1000; - private final int offline = 59 * 1000; - - private final ClientType clientType; - private final String selector; - - public Client(int id, ClientType clientType) throws JMSException { - super("Client" + id); - setDaemon(true); - - this.id = id; - conClientId = "cli" + id; - this.clientType = clientType; - selector = "(COMMIT = true and RELEVANT = true) or " + clientType.selector; - - subscribe(); - } - - @Override - public void run() { - // long end = System.currentTimeMillis() + lifetime.next(); - long end = System.currentTimeMillis() + lifetime; - try { - boolean sleep = false; - while (true) { - long max = end - System.currentTimeMillis(); - if (max <= 0) - break; - - if (sleep) - Thread.sleep(offline); - // offline.sleepRandom(); - else - sleep = true; - - processLock.readLock().lock(); - try { - process(online); - } finally { - processLock.readLock().unlock(); - } - } - - // 50% unsubscribe, 50% abandon subscription - if (!ALLOW_SUBSCRIPTION_ABANDONMENT) { - unsubscribe(); - ALLOW_SUBSCRIPTION_ABANDONMENT = true; - } else { - - LOG.info("Client abandon the subscription. " + this); - - // housekeeper should sweep these abandoned subscriptions - houseKeeper.abandonedSubscriptions.add(conClientId); - ALLOW_SUBSCRIPTION_ABANDONMENT = false; - } - } catch (Throwable e) { - exit(toString() + " failed.", e); - } - - clientManager.removeClient(this); - LOG.info(toString() + " DONE."); - } - - private void process(long processingTime) throws JMSException { - long end = System.currentTimeMillis() + processingTime; - long hardEnd = end + 20000; // wait to finish the transaction. - boolean inTransaction = false; - int transCount = 0; - - LOG.info(toString() + " ONLINE."); - Connection con = openConnection(); - Session sess = con.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = sess.createDurableSubscriber(topic, SUBSCRIPTION_NAME, selector, false); - try { - do { - long max = end - System.currentTimeMillis(); - if (max <= 0) { - if (!inTransaction) - break; - - max = hardEnd - System.currentTimeMillis(); - if (max <= 0) - exit("" + this + " failed: Transaction is not finished."); - } - - Message message = consumer.receive(max); - if (message == null) - continue; - - if (message.propertyExists("COMMIT")) { - message.acknowledge(); // CLIENT_ACKNOWLEDGE - - LOG.info("Received Trans[id=" + message.getIntProperty("TRANS") + ", count=" + transCount + "] in " + this + "."); - - inTransaction = false; - transCount = 0; - } else { - inTransaction = true; - transCount++; - } - } while (true); - } finally { - sess.close(); - con.close(); - LOG.info(toString() + " OFFLINE."); - } - } - - private Connection openConnection() throws JMSException { Connection con = cf.createConnection(); - con.setClientID(conClientId); - con.start(); - return con; - } + Session sess = con.createSession(true, Session.SESSION_TRANSACTED); + MessageProducer prod = sess.createProducer(null); - private void subscribe() throws JMSException { - Connection con = openConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, SUBSCRIPTION_NAME, selector, true); - session.close(); - con.close(); - } + for (int i = 0; i < count; i++) { + Message message = sess.createMessage(); + message.setIntProperty("ID", ++messageRover); + message.setIntProperty("TRANS", trans); + String type = clientType != null ? clientType.randomMessageType() : ClientType.randomNonRelevantMessageType(); + message.setStringProperty("TYPE", type); - private void unsubscribe() throws JMSException { - Connection con = openConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.unsubscribe(SUBSCRIPTION_NAME); - session.close(); - con.close(); - } + if (CARGO_SIZE > 0) + message.setStringProperty("CARGO", getCargo(random(CARGO_SIZE))); - @Override - public String toString() { - return "Client[id=" + id + ", type=" + clientType + "]"; - } - } + prod.send(topic, message); - /** - * Sweeps out not-used durable subscriptions. - */ - private final class HouseKeeper extends Thread { - - private final AtomicBoolean done = new AtomicBoolean(); - - public final long SWEEP_DELAY = TimeUnit.MINUTES.toMillis(3); - - private HouseKeeper() { - super("HouseKeeper"); - setDaemon(true); - } - - public final CopyOnWriteArrayList abandonedSubscriptions = new CopyOnWriteArrayList(); - - public void shutdown() throws Exception { - done.set(true); - - // In case we are sleeping, abort the sleep. - this.interrupt(); - - // Wait for run to complete. - this.join(TimeUnit.MINUTES.toMillis(SWEEP_DELAY)); - - // Ensure all abandoned subscriptions get wiped. - if (!abandonedSubscriptions.isEmpty()) { - this.sweep(); } - } - @Override - public void run() { - while (!done.get()) { - try { - Thread.sleep(SWEEP_DELAY); + Message message = sess.createMessage(); + message.setIntProperty("ID", ++messageRover); + message.setIntProperty("TRANS", trans); + message.setBooleanProperty("COMMIT", true); + message.setBooleanProperty("RELEVANT", relevantTrans); + prod.send(topic, message); - processLock.readLock().lock(); - try { - sweep(); - } finally { - processLock.readLock().unlock(); - } - } catch (InterruptedException ex) { - break; - } catch (Throwable e) { - Exception log = new Exception("HouseKeeper failed.", e); - log.printStackTrace(); - } + sess.commit(); + LOG.info("Committed Trans[id=" + trans + ", count=" + count + ", clientType=" + clientType + "], ID=" + messageRover); + + sess.close(); + con.close(); + } + } + + private String getCargo(int length) { + if (length == 0) + return null; + + if (length < cargos.length) { + String result = cargos[length]; + if (result == null) { + result = getCargoImpl(length); + cargos[length] = result; } - } + return result; + } + return getCargoImpl(length); + } - private void sweep() throws Exception { - LOG.info("Housekeeper sweeping."); + private String getCargoImpl(int length) { + StringBuilder sb = new StringBuilder(length); + for (int i = length; --i >= 0; ) { + sb.append('a'); + } + return sb.toString(); + } + } - int closed = 0; - ArrayList sweeped = new ArrayList(); + /** + * Clients listen on different messages in the topic. The 'TYPE' property + * helps the client to select the proper messages. + */ + private enum ClientType { + A("a", "b", "c"), B("c", "d", "e"), C("d", "e", "f"), D("g", "h"); + + public final String[] messageTypes; + + public final String selector; + + ClientType(String... messageTypes) { + this.messageTypes = messageTypes; + + StringBuilder sb = new StringBuilder("TYPE in ("); + for (int i = 0; i < messageTypes.length; i++) { + if (i > 0) + sb.append(", "); + sb.append('\'').append(messageTypes[i]).append('\''); + } + sb.append(')'); + selector = sb.toString(); + } + + public static ClientType randomClientType() { + return values()[DurableSubDelayedUnsubscribeTest.random(values().length - 1)]; + } + + public final String randomMessageType() { + return messageTypes[DurableSubDelayedUnsubscribeTest.random(messageTypes.length - 1)]; + } + + public static String randomNonRelevantMessageType() { + return Integer.toString(DurableSubDelayedUnsubscribeTest.random(20)); + } + + @Override + public final String toString() { + return this.name() /* + '[' + selector + ']' */; + } + } + + /** + * Creates new cliens. + */ + private final class ClientManager extends Thread { + + private int clientRover = 0; + + private final CopyOnWriteArrayList clients = new CopyOnWriteArrayList(); + + private boolean stopped; + + public ClientManager() { + super("ClientManager"); + setDaemon(true); + } + + public int getClientCount() { + return clients.size(); + } + + @Override + public void run() { + try { + while (true) { + if (clients.size() < MAX_CLIENTS) { + + if (stopped) { + // get out, don't start any more threads + break; + } + processLock.readLock().lock(); + try { + createNewClient(); + } + finally { + processLock.readLock().unlock(); + } + } + + int size = clients.size(); + sleepRandom(size * 3 * 1000, size * 6 * 1000); + } + } + catch (Throwable e) { + exit("ClientManager.run failed.", e); + } + } + + private void createNewClient() throws JMSException { + ClientType type = ClientType.randomClientType(); + + Client client; + synchronized (server.sendMutex) { + client = new Client(++clientRover, type); + clients.add(client); + } + client.start(); + + LOG.info(client.toString() + " created. " + this); + } + + public void removeClient(Client client) { + clients.remove(client); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("ClientManager[count="); + sb.append(clients.size()); + sb.append(", clients="); + boolean sep = false; + for (Client client : clients) { + if (sep) + sb.append(", "); + else + sep = true; + sb.append(client.toString()); + } + sb.append(']'); + return sb.toString(); + } + } + + /** + * Consumes massages from a durable subscription. Goes online/offline + * periodically. Checks the incoming messages against the sent messages of + * the server. + */ + private final class Client extends Thread { + + String url = "failover:(tcp://localhost:61656?wireFormat.maxInactivityDuration=0)?" + "jms.watchTopicAdvisories=false&" + "jms.alwaysSyncSend=true&jms.dispatchAsync=true&" + "jms.producerWindowSize=20971520&" + "jms.copyMessageOnSend=false&" + "initialReconnectDelay=100&maxReconnectDelay=30000&" + "useExponentialBackOff=true"; + final ConnectionFactory cf = new ActiveMQConnectionFactory(url); + + public static final String SUBSCRIPTION_NAME = "subscription"; + + private final int id; + private final String conClientId; + + public static final int lifetime = 60 * 1000; + private final int online = 1 * 1000; + private final int offline = 59 * 1000; + + private final ClientType clientType; + private final String selector; + + public Client(int id, ClientType clientType) throws JMSException { + super("Client" + id); + setDaemon(true); + + this.id = id; + conClientId = "cli" + id; + this.clientType = clientType; + selector = "(COMMIT = true and RELEVANT = true) or " + clientType.selector; + + subscribe(); + } + + @Override + public void run() { + // long end = System.currentTimeMillis() + lifetime.next(); + long end = System.currentTimeMillis() + lifetime; + try { + boolean sleep = false; + while (true) { + long max = end - System.currentTimeMillis(); + if (max <= 0) + break; + + if (sleep) + Thread.sleep(offline); + // offline.sleepRandom(); + else + sleep = true; + + processLock.readLock().lock(); + try { + process(online); + } + finally { + processLock.readLock().unlock(); + } + } + + // 50% unsubscribe, 50% abandon subscription + if (!ALLOW_SUBSCRIPTION_ABANDONMENT) { + unsubscribe(); + ALLOW_SUBSCRIPTION_ABANDONMENT = true; + } + else { + + LOG.info("Client abandon the subscription. " + this); + + // housekeeper should sweep these abandoned subscriptions + houseKeeper.abandonedSubscriptions.add(conClientId); + ALLOW_SUBSCRIPTION_ABANDONMENT = false; + } + } + catch (Throwable e) { + exit(toString() + " failed.", e); + } + + clientManager.removeClient(this); + LOG.info(toString() + " DONE."); + } + + private void process(long processingTime) throws JMSException { + long end = System.currentTimeMillis() + processingTime; + long hardEnd = end + 20000; // wait to finish the transaction. + boolean inTransaction = false; + int transCount = 0; + + LOG.info(toString() + " ONLINE."); + Connection con = openConnection(); + Session sess = con.createSession(false, Session.CLIENT_ACKNOWLEDGE); + MessageConsumer consumer = sess.createDurableSubscriber(topic, SUBSCRIPTION_NAME, selector, false); + try { + do { + long max = end - System.currentTimeMillis(); + if (max <= 0) { + if (!inTransaction) + break; + + max = hardEnd - System.currentTimeMillis(); + if (max <= 0) + exit("" + this + " failed: Transaction is not finished."); + } + + Message message = consumer.receive(max); + if (message == null) + continue; + + if (message.propertyExists("COMMIT")) { + message.acknowledge(); // CLIENT_ACKNOWLEDGE + + LOG.info("Received Trans[id=" + message.getIntProperty("TRANS") + ", count=" + transCount + "] in " + this + "."); + + inTransaction = false; + transCount = 0; + } + else { + inTransaction = true; + transCount++; + } + } while (true); + } + finally { + sess.close(); + con.close(); + LOG.info(toString() + " OFFLINE."); + } + } + + private Connection openConnection() throws JMSException { + Connection con = cf.createConnection(); + con.setClientID(conClientId); + con.start(); + return con; + } + + private void subscribe() throws JMSException { + Connection con = openConnection(); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, SUBSCRIPTION_NAME, selector, true); + session.close(); + con.close(); + } + + private void unsubscribe() throws JMSException { + Connection con = openConnection(); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.unsubscribe(SUBSCRIPTION_NAME); + session.close(); + con.close(); + } + + @Override + public String toString() { + return "Client[id=" + id + ", type=" + clientType + "]"; + } + } + + /** + * Sweeps out not-used durable subscriptions. + */ + private final class HouseKeeper extends Thread { + + private final AtomicBoolean done = new AtomicBoolean(); + + public final long SWEEP_DELAY = TimeUnit.MINUTES.toMillis(3); + + private HouseKeeper() { + super("HouseKeeper"); + setDaemon(true); + } + + public final CopyOnWriteArrayList abandonedSubscriptions = new CopyOnWriteArrayList(); + + public void shutdown() throws Exception { + done.set(true); + + // In case we are sleeping, abort the sleep. + this.interrupt(); + + // Wait for run to complete. + this.join(TimeUnit.MINUTES.toMillis(SWEEP_DELAY)); + + // Ensure all abandoned subscriptions get wiped. + if (!abandonedSubscriptions.isEmpty()) { + this.sweep(); + } + } + + @Override + public void run() { + while (!done.get()) { try { - for (String clientId : abandonedSubscriptions) { - LOG.info("Sweeping out subscription of " + clientId + "."); - broker.getAdminView().destroyDurableSubscriber(clientId, Client.SUBSCRIPTION_NAME); - sweeped.add(clientId); - closed++; - } - } catch (Exception ignored) { - LOG.info("Ex on destroy sub " + ignored); - } finally { - abandonedSubscriptions.removeAll(sweeped); + Thread.sleep(SWEEP_DELAY); + + processLock.readLock().lock(); + try { + sweep(); + } + finally { + processLock.readLock().unlock(); + } } - - LOG.info("Housekeeper sweeped out " + closed + " subscriptions."); - } - } - - public static int random(int max) { - return (int) (Math.random() * (max + 1)); - } - - public static int random(int min, int max) { - return random(max - min) + min; - } - - public static void sleepRandom(int maxMillis) throws InterruptedException { - Thread.sleep(random(maxMillis)); - } - - public static void sleepRandom(int minMillis, int maxMillis) throws InterruptedException { - Thread.sleep(random(minMillis, maxMillis)); - } - - public static final class Random { - - final int min; - final int max; - - Random(int min, int max) { - this.min = min; - this.max = max; - } - - public int next() { - return random(min, max); - } - - public void sleepRandom() throws InterruptedException { - DurableSubDelayedUnsubscribeTest.sleepRandom(min, max); - } - } - - public static void exit(String message) { - exit(message, null); - } - - public static void exit(String message, Throwable e) { - Throwable cause = new RuntimeException(message, e); - LOG.error(message, cause); - exceptions.add(cause); - fail(cause.toString()); - } - - @Before - public void setUp() throws Exception { - topic = new ActiveMQTopic("TopicT"); - startBroker(); - - clientManager = new ClientManager(); - server = new Server(); - houseKeeper = new HouseKeeper(); - } - - @After - public void tearDown() throws Exception { - destroyBroker(); - } - - private void startBroker() throws Exception { - startBroker(true); - } - - private void startBroker(boolean deleteAllMessages) throws Exception { - if (broker != null) - return; - - broker = BrokerFactory.createBroker("broker:(vm://" + getName() + ")"); - broker.setBrokerName(getName()); - broker.setAdvisorySupport(false); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - - File kahadbData = new File("activemq-data/" + getName() + "-kahadb"); - if (deleteAllMessages) - delete(kahadbData); - - broker.setPersistent(true); - KahaDBPersistenceAdapter kahadb = new KahaDBPersistenceAdapter(); - kahadb.setDirectory(kahadbData); - kahadb.setJournalMaxFileLength(512 * 1024); - broker.setPersistenceAdapter(kahadb); - - broker.addConnector("tcp://localhost:61656"); - - broker.getSystemUsage().getMemoryUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getTempUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getStoreUsage().setLimit(256 * 1024 * 1024); - - broker.start(); - } - - protected static String getName() { - return "DurableSubProcessWithRestartTest"; - } - - private static boolean delete(File path) { - if (path == null) - return true; - - if (path.isDirectory()) { - for (File file : path.listFiles()) { - delete(file); + catch (InterruptedException ex) { + break; } - } - return path.delete(); - } + catch (Throwable e) { + Exception log = new Exception("HouseKeeper failed.", e); + log.printStackTrace(); + } + } + } - private void destroyBroker() throws Exception { - if (broker == null) - return; + private void sweep() throws Exception { + LOG.info("Housekeeper sweeping."); - broker.stop(); - broker = null; - } + int closed = 0; + ArrayList sweeped = new ArrayList(); + try { + for (String clientId : abandonedSubscriptions) { + LOG.info("Sweeping out subscription of " + clientId + "."); + broker.getAdminView().destroyDurableSubscriber(clientId, Client.SUBSCRIPTION_NAME); + sweeped.add(clientId); + closed++; + } + } + catch (Exception ignored) { + LOG.info("Ex on destroy sub " + ignored); + } + finally { + abandonedSubscriptions.removeAll(sweeped); + } + + LOG.info("Housekeeper sweeped out " + closed + " subscriptions."); + } + } + + public static int random(int max) { + return (int) (Math.random() * (max + 1)); + } + + public static int random(int min, int max) { + return random(max - min) + min; + } + + public static void sleepRandom(int maxMillis) throws InterruptedException { + Thread.sleep(random(maxMillis)); + } + + public static void sleepRandom(int minMillis, int maxMillis) throws InterruptedException { + Thread.sleep(random(minMillis, maxMillis)); + } + + public static final class Random { + + final int min; + final int max; + + Random(int min, int max) { + this.min = min; + this.max = max; + } + + public int next() { + return random(min, max); + } + + public void sleepRandom() throws InterruptedException { + DurableSubDelayedUnsubscribeTest.sleepRandom(min, max); + } + } + + public static void exit(String message) { + exit(message, null); + } + + public static void exit(String message, Throwable e) { + Throwable cause = new RuntimeException(message, e); + LOG.error(message, cause); + exceptions.add(cause); + fail(cause.toString()); + } + + @Before + public void setUp() throws Exception { + topic = new ActiveMQTopic("TopicT"); + startBroker(); + + clientManager = new ClientManager(); + server = new Server(); + houseKeeper = new HouseKeeper(); + } + + @After + public void tearDown() throws Exception { + destroyBroker(); + } + + private void startBroker() throws Exception { + startBroker(true); + } + + private void startBroker(boolean deleteAllMessages) throws Exception { + if (broker != null) + return; + + broker = BrokerFactory.createBroker("broker:(vm://" + getName() + ")"); + broker.setBrokerName(getName()); + broker.setAdvisorySupport(false); + broker.setDeleteAllMessagesOnStartup(deleteAllMessages); + + File kahadbData = new File("activemq-data/" + getName() + "-kahadb"); + if (deleteAllMessages) + delete(kahadbData); + + broker.setPersistent(true); + KahaDBPersistenceAdapter kahadb = new KahaDBPersistenceAdapter(); + kahadb.setDirectory(kahadbData); + kahadb.setJournalMaxFileLength(512 * 1024); + broker.setPersistenceAdapter(kahadb); + + broker.addConnector("tcp://localhost:61656"); + + broker.getSystemUsage().getMemoryUsage().setLimit(256 * 1024 * 1024); + broker.getSystemUsage().getTempUsage().setLimit(256 * 1024 * 1024); + broker.getSystemUsage().getStoreUsage().setLimit(256 * 1024 * 1024); + + broker.start(); + } + + protected static String getName() { + return "DurableSubProcessWithRestartTest"; + } + + private static boolean delete(File path) { + if (path == null) + return true; + + if (path.isDirectory()) { + for (File file : path.listFiles()) { + delete(file); + } + } + return path.delete(); + } + + private void destroyBroker() throws Exception { + if (broker == null) + return; + + broker.stop(); + broker = null; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubInBrokerNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubInBrokerNetworkTest.java index cad4170b2b..67e836a5cb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubInBrokerNetworkTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubInBrokerNetworkTest.java @@ -35,153 +35,145 @@ import org.slf4j.LoggerFactory; /** * Tests durable topic subscriptions inside a network of brokers. - * - * @author tmielke * + * @author tmielke */ public class DurableSubInBrokerNetworkTest extends NetworkTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(DurableSubInBrokerNetworkTest.class); - // protected BrokerService localBroker; - private final String subName = "Subscriber1"; - private final String subName2 = "Subscriber2"; - private final String topicName = "TEST.FOO"; + private static final Logger LOG = LoggerFactory.getLogger(DurableSubInBrokerNetworkTest.class); + // protected BrokerService localBroker; + private final String subName = "Subscriber1"; + private final String subName2 = "Subscriber2"; + private final String topicName = "TEST.FOO"; - protected void setUp() throws Exception { - useJmx=true; - super.setUp(); + protected void setUp() throws Exception { + useJmx = true; + super.setUp(); - URI ncUri = new URI("static:(" + connector.getConnectUri().toString() + ")"); - NetworkConnector nc = new DiscoveryNetworkConnector(ncUri); - nc.setDuplex(true); - remoteBroker.addNetworkConnector(nc); - nc.start(); - } + URI ncUri = new URI("static:(" + connector.getConnectUri().toString() + ")"); + NetworkConnector nc = new DiscoveryNetworkConnector(ncUri); + nc.setDuplex(true); + remoteBroker.addNetworkConnector(nc); + nc.start(); + } - protected void tearDown() throws Exception { - if (remoteBroker.isStarted()) { - remoteBroker.stop(); - remoteBroker.waitUntilStopped(); - } - if (broker.isStarted()) { - broker.stop(); - broker.waitUntilStopped(); - } - super.tearDown(); - } + protected void tearDown() throws Exception { + if (remoteBroker.isStarted()) { + remoteBroker.stop(); + remoteBroker.waitUntilStopped(); + } + if (broker.isStarted()) { + broker.stop(); + broker.waitUntilStopped(); + } + super.tearDown(); + } + /** + * Creates a durable topic subscription, checks that it is propagated + * in the broker network, removes the subscription and checks that + * the subscription is removed from remote broker as well. + * + * @throws Exception + */ + public void testDurableSubNetwork() throws Exception { + LOG.info("testDurableSubNetwork started."); - /** - * Creates a durable topic subscription, checks that it is propagated - * in the broker network, removes the subscription and checks that - * the subscription is removed from remote broker as well. - * - * @throws Exception - */ - public void testDurableSubNetwork() throws Exception { - LOG.info("testDurableSubNetwork started."); + // create durable sub + ActiveMQConnectionFactory fact = new ActiveMQConnectionFactory(connector.getConnectUri().toString()); + Connection conn = fact.createConnection(); + conn.setClientID("clientID1"); + Session session = conn.createSession(false, 1); + Destination dest = session.createTopic(topicName); + TopicSubscriber sub = session.createDurableSubscriber((Topic) dest, subName); + LOG.info("Durable subscription of name " + subName + "created."); + Thread.sleep(100); - // create durable sub - ActiveMQConnectionFactory fact = new ActiveMQConnectionFactory(connector.getConnectUri().toString()); - Connection conn = fact.createConnection(); - conn.setClientID("clientID1"); - Session session = conn.createSession(false, 1); - Destination dest = session.createTopic(topicName); - TopicSubscriber sub = session.createDurableSubscriber((Topic)dest, subName); - LOG.info("Durable subscription of name " + subName + "created."); - Thread.sleep(100); + // query durable sub on local and remote broker + // raise an error if not found - // query durable sub on local and remote broker - // raise an error if not found + assertTrue(foundSubInLocalBroker(subName)); - assertTrue(foundSubInLocalBroker(subName)); + assertTrue(foundSubInRemoteBrokerByTopicName(topicName)); + // unsubscribe from durable sub + sub.close(); + session.unsubscribe(subName); + LOG.info("Unsubscribed from durable subscription."); + Thread.sleep(100); - assertTrue(foundSubInRemoteBrokerByTopicName(topicName)); + // query durable sub on local and remote broker + // raise an error if its not removed from both brokers + assertFalse(foundSubInLocalBroker(subName)); - // unsubscribe from durable sub - sub.close(); - session.unsubscribe(subName); - LOG.info("Unsubscribed from durable subscription."); - Thread.sleep(100); + assertFalse("Durable subscription not unregistered on remote broker", foundSubInRemoteBrokerByTopicName(topicName)); - // query durable sub on local and remote broker - // raise an error if its not removed from both brokers - assertFalse(foundSubInLocalBroker(subName)); + } - assertFalse("Durable subscription not unregistered on remote broker", - foundSubInRemoteBrokerByTopicName(topicName)); + public void testTwoDurableSubsInNetworkWithUnsubscribe() throws Exception { + // create 1st durable sub to topic TEST.FOO + ActiveMQConnectionFactory fact = new ActiveMQConnectionFactory(connector.getConnectUri().toString()); + Connection conn = fact.createConnection(); + conn.setClientID("clientID1"); + Session session = conn.createSession(false, 1); + Destination dest = session.createTopic(topicName); + TopicSubscriber sub = session.createDurableSubscriber((Topic) dest, subName); + LOG.info("Durable subscription of name " + subName + "created."); + TopicSubscriber sub2 = session.createDurableSubscriber((Topic) dest, subName2); + LOG.info("Durable subscription of name " + subName2 + "created."); - } + Thread.sleep(100); - public void testTwoDurableSubsInNetworkWithUnsubscribe() throws Exception{ + // query durable sub on local and remote broker + // raise an error if not found - // create 1st durable sub to topic TEST.FOO - ActiveMQConnectionFactory fact = new ActiveMQConnectionFactory(connector.getConnectUri().toString()); - Connection conn = fact.createConnection(); - conn.setClientID("clientID1"); - Session session = conn.createSession(false, 1); - Destination dest = session.createTopic(topicName); - TopicSubscriber sub = session.createDurableSubscriber((Topic)dest, subName); - LOG.info("Durable subscription of name " + subName + "created."); - TopicSubscriber sub2 = session.createDurableSubscriber((Topic) dest, subName2); - LOG.info("Durable subscription of name " + subName2 + "created."); + assertTrue(foundSubInLocalBroker(subName)); + assertTrue(foundSubInLocalBroker(subName2)); - Thread.sleep(100); + assertTrue(foundSubInRemoteBrokerByTopicName(topicName)); - // query durable sub on local and remote broker - // raise an error if not found + // unsubscribe from durable sub + sub.close(); + session.unsubscribe(subName); + LOG.info("Unsubscribed from durable subscription."); + Thread.sleep(100); - assertTrue(foundSubInLocalBroker(subName)); - assertTrue(foundSubInLocalBroker(subName2)); + // query durable sub on local and remote broker + assertFalse(foundSubInLocalBroker(subName)); + assertTrue(foundSubInLocalBroker(subName2)); + assertTrue("Durable subscription should still be on remote broker", foundSubInRemoteBrokerByTopicName(topicName)); - assertTrue(foundSubInRemoteBrokerByTopicName(topicName)); + sub2.close(); + session.unsubscribe(subName2); - // unsubscribe from durable sub - sub.close(); - session.unsubscribe(subName); - LOG.info("Unsubscribed from durable subscription."); - Thread.sleep(100); + Thread.sleep(100); - // query durable sub on local and remote broker - assertFalse(foundSubInLocalBroker(subName)); - assertTrue(foundSubInLocalBroker(subName2)); + assertFalse(foundSubInLocalBroker(subName2)); - assertTrue("Durable subscription should still be on remote broker", - foundSubInRemoteBrokerByTopicName(topicName)); + assertFalse("Durable subscription not unregistered on remote broker", foundSubInRemoteBrokerByTopicName(topicName)); - sub2.close(); - session.unsubscribe(subName2); + } - Thread.sleep(100); + private boolean foundSubInRemoteBrokerByTopicName(String topicName) throws Exception { + boolean foundSub = false; + ObjectName[] subs = remoteBroker.getAdminView().getDurableTopicSubscribers(); + for (int i = 0; i < subs.length; i++) { + if (subs[i].toString().contains("destinationName=" + topicName)) + foundSub = true; + } + return foundSub; + } - assertFalse(foundSubInLocalBroker(subName2)); + private boolean foundSubInLocalBroker(String subName) throws Exception { + boolean foundSub = false; + ObjectName[] subs = broker.getAdminView().getDurableTopicSubscribers(); - assertFalse("Durable subscription not unregistered on remote broker", - foundSubInRemoteBrokerByTopicName(topicName)); - - } - - private boolean foundSubInRemoteBrokerByTopicName(String topicName) throws Exception { - boolean foundSub = false; - ObjectName[] subs = remoteBroker.getAdminView().getDurableTopicSubscribers(); - for (int i=0 ; i exceptions = new Vector(); - if (ALLOW_SUBSCRIPTION_ABANDONMENT) - houseKeeper.start(); + // long form of test that found https://issues.apache.org/jira/browse/AMQ-3805 + @Ignore("short version in org.apache.activemq.usecases.DurableSubscriptionOfflineTest.testNoDuplicateOnConcurrentSendTranCommitAndActivate" + " and org.apache.activemq.usecases.DurableSubscriptionOfflineTest.testOrderOnActivateDeactivate") + @Test + public void testProcess() { + try { + server.start(); + clientManager.start(); - if (BROKER_RESTART <= 0) - Thread.sleep(RUNTIME); - else { - long end = System.currentTimeMillis() + RUNTIME; + if (ALLOW_SUBSCRIPTION_ABANDONMENT) + houseKeeper.start(); - while (true) { - long now = System.currentTimeMillis(); - if (now > end) - break; + if (BROKER_RESTART <= 0) + Thread.sleep(RUNTIME); + else { + long end = System.currentTimeMillis() + RUNTIME; - now = end - now; - now = now < BROKER_RESTART ? now : BROKER_RESTART; - Thread.sleep(now); + while (true) { + long now = System.currentTimeMillis(); + if (now > end) + break; - restartBroker(); - } + now = end - now; + now = now < BROKER_RESTART ? now : BROKER_RESTART; + Thread.sleep(now); + + restartBroker(); } - } catch (Throwable e) { - exit("ProcessTest.testProcess failed.", e); - } + } + } + catch (Throwable e) { + exit("ProcessTest.testProcess failed.", e); + } - //allow the clients to unsubscribe before finishing - clientManager.setEnd(true); - try { - Thread.sleep(60 * 1000); - } catch (InterruptedException e) { - exit("ProcessTest.testProcess failed.", e); - } + //allow the clients to unsubscribe before finishing + clientManager.setEnd(true); + try { + Thread.sleep(60 * 1000); + } + catch (InterruptedException e) { + exit("ProcessTest.testProcess failed.", e); + } - server.done = true; + server.done = true; - try { - server.join(60*1000); - } catch (Exception ignored) {} - processLock.writeLock().lock(); - assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); - LOG.info("DONE."); - } + try { + server.join(60 * 1000); + } + catch (Exception ignored) { + } + processLock.writeLock().lock(); + assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); + LOG.info("DONE."); + } - private void restartBroker() throws Exception { - LOG.info("Broker restart: waiting for components."); + private void restartBroker() throws Exception { + LOG.info("Broker restart: waiting for components."); - processLock.writeLock().lock(); - try { - destroyBroker(); - startBroker(false); + processLock.writeLock().lock(); + try { + destroyBroker(); + startBroker(false); - restartCount++; - LOG.info("Broker restarted. count: " + restartCount); - } finally { - processLock.writeLock().unlock(); - } - } + restartCount++; + LOG.info("Broker restarted. count: " + restartCount); + } + finally { + processLock.writeLock().unlock(); + } + } - /** - * Creates batch of messages in a transaction periodically. The last message - * in the transaction is always a special message what contains info about - * the whole transaction. - *

    - * Notifies the clients about the created messages also. - */ - final class Server extends Thread { + /** + * Creates batch of messages in a transaction periodically. The last message + * in the transaction is always a special message what contains info about + * the whole transaction. + *

    + * Notifies the clients about the created messages also. + */ + final class Server extends Thread { - final String url = "vm://" - + DurableSubProcessConcurrentCommitActivateNoDuplicateTest.getName() - + "?" - + "jms.redeliveryPolicy.maximumRedeliveries=2&jms.redeliveryPolicy.initialRedeliveryDelay=500&" - + "jms.producerWindowSize=20971520&jms.prefetchPolicy.all=100&" - + "jms.copyMessageOnSend=false&jms.disableTimeStampsByDefault=false&" - + "jms.alwaysSyncSend=true&jms.dispatchAsync=false&" - + "jms.watchTopicAdvisories=false&" - + "waitForStart=200&create=false"; - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); + final String url = "vm://" + DurableSubProcessConcurrentCommitActivateNoDuplicateTest.getName() + "?" + "jms.redeliveryPolicy.maximumRedeliveries=2&jms.redeliveryPolicy.initialRedeliveryDelay=500&" + "jms.producerWindowSize=20971520&jms.prefetchPolicy.all=100&" + "jms.copyMessageOnSend=false&jms.disableTimeStampsByDefault=false&" + "jms.alwaysSyncSend=true&jms.dispatchAsync=false&" + "jms.watchTopicAdvisories=false&" + "waitForStart=200&create=false"; + final ConnectionFactory cf = new ActiveMQConnectionFactory(url); - final Object sendMutex = new Object(); - final String[] cargos = new String[500]; + final Object sendMutex = new Object(); + final String[] cargos = new String[500]; - int transRover = 0; - int messageRover = 0; - public volatile int committingTransaction = -1; - public boolean done = false; - public Server() { - super("Server"); - setPriority(Thread.MIN_PRIORITY); - setDaemon(true); - } + int transRover = 0; + int messageRover = 0; + public volatile int committingTransaction = -1; + public boolean done = false; - @Override - public void run() { - try { - while (!done) { + public Server() { + super("Server"); + setPriority(Thread.MIN_PRIORITY); + setDaemon(true); + } - Thread.sleep(1000); + @Override + public void run() { + try { + while (!done) { - processLock.readLock().lock(); - try { - send(); - } finally { - processLock.readLock().unlock(); - } - } - } catch (Throwable e) { - exit("Server.run failed", e); + Thread.sleep(1000); + + processLock.readLock().lock(); + try { + send(); + } + finally { + processLock.readLock().unlock(); + } } - } + } + catch (Throwable e) { + exit("Server.run failed", e); + } + } - public void send() throws JMSException { - // do not create new clients now - // ToDo: Test this case later. - synchronized (sendMutex) { - int trans = ++transRover; - boolean relevantTrans = true; //random(2) > 1; - ClientType clientType = relevantTrans ? ClientType - .randomClientType() : null; // sends this types - //int count = random(500, 700); - int count = 1000; + public void send() throws JMSException { + // do not create new clients now + // ToDo: Test this case later. + synchronized (sendMutex) { + int trans = ++transRover; + boolean relevantTrans = true; //random(2) > 1; + ClientType clientType = relevantTrans ? ClientType.randomClientType() : null; // sends this types + //int count = random(500, 700); + int count = 1000; - LOG.info("Sending Trans[id=" + trans + ", count=" - + count + ", clientType=" + clientType + ", firstID=" + (messageRover+1) + "]"); + LOG.info("Sending Trans[id=" + trans + ", count=" + count + ", clientType=" + clientType + ", firstID=" + (messageRover + 1) + "]"); - Connection con = cf.createConnection(); - Session sess = con - .createSession(true, Session.SESSION_TRANSACTED); - MessageProducer prod = sess.createProducer(null); + Connection con = cf.createConnection(); + Session sess = con.createSession(true, Session.SESSION_TRANSACTED); + MessageProducer prod = sess.createProducer(null); - for (int i = 0; i < count; i++) { - Message message = sess.createMessage(); - message.setIntProperty("ID", ++messageRover); - message.setIntProperty("TRANS", trans); - String type = clientType != null ? clientType - .randomMessageType() : ClientType - .randomNonRelevantMessageType(); - message.setStringProperty("TYPE", type); + for (int i = 0; i < count; i++) { + Message message = sess.createMessage(); + message.setIntProperty("ID", ++messageRover); + message.setIntProperty("TRANS", trans); + String type = clientType != null ? clientType.randomMessageType() : ClientType.randomNonRelevantMessageType(); + message.setStringProperty("TYPE", type); - if (CARGO_SIZE > 0) - message.setStringProperty("CARGO", - getCargo(random(CARGO_SIZE))); + if (CARGO_SIZE > 0) + message.setStringProperty("CARGO", getCargo(random(CARGO_SIZE))); - prod.send(topic, message); - clientManager.onServerMessage(message); - } - - Message message = sess.createMessage(); - message.setIntProperty("ID", ++messageRover); - message.setIntProperty("TRANS", trans); - message.setBooleanProperty("COMMIT", true); - message.setBooleanProperty("RELEVANT", relevantTrans); - prod.send(topic, message); - clientManager.onServerMessage(message); - - committingTransaction = trans; - sess.commit(); - committingTransaction = -1; - - LOG.info("Committed Trans[id=" + trans + ", count=" - + count + ", clientType=" + clientType + "], ID=" + messageRover); - - sess.close(); - con.close(); + prod.send(topic, message); + clientManager.onServerMessage(message); } - } - private String getCargo(int length) { - if (length == 0) - return null; + Message message = sess.createMessage(); + message.setIntProperty("ID", ++messageRover); + message.setIntProperty("TRANS", trans); + message.setBooleanProperty("COMMIT", true); + message.setBooleanProperty("RELEVANT", relevantTrans); + prod.send(topic, message); + clientManager.onServerMessage(message); - if (length < cargos.length) { - String result = cargos[length]; - if (result == null) { - result = getCargoImpl(length); - cargos[length] = result; - } - return result; + committingTransaction = trans; + sess.commit(); + committingTransaction = -1; + + LOG.info("Committed Trans[id=" + trans + ", count=" + count + ", clientType=" + clientType + "], ID=" + messageRover); + + sess.close(); + con.close(); + } + } + + private String getCargo(int length) { + if (length == 0) + return null; + + if (length < cargos.length) { + String result = cargos[length]; + if (result == null) { + result = getCargoImpl(length); + cargos[length] = result; } - return getCargoImpl(length); - } + return result; + } + return getCargoImpl(length); + } - private String getCargoImpl(int length) { - StringBuilder sb = new StringBuilder(length); - for (int i = length; --i >= 0;) { - sb.append('a'); + private String getCargoImpl(int length) { + StringBuilder sb = new StringBuilder(length); + for (int i = length; --i >= 0; ) { + sb.append('a'); + } + return sb.toString(); + } + } + + /** + * Clients listen on different messages in the topic. The 'TYPE' property + * helps the client to select the proper messages. + */ + private enum ClientType { + A("a", "b", "c"), B("c", "d", "e"), C("d", "e", "f"), D("g", "h"); + + public final String[] messageTypes; + public final HashSet messageTypeSet; + public final String selector; + + ClientType(String... messageTypes) { + this.messageTypes = messageTypes; + messageTypeSet = new HashSet(Arrays.asList(messageTypes)); + + StringBuilder sb = new StringBuilder("TYPE in ("); + for (int i = 0; i < messageTypes.length; i++) { + if (i > 0) + sb.append(", "); + sb.append('\'').append(messageTypes[i]).append('\''); + } + sb.append(')'); + selector = sb.toString(); + } + + public static ClientType randomClientType() { + return values()[DurableSubProcessConcurrentCommitActivateNoDuplicateTest.random(values().length - 1)]; + } + + public final String randomMessageType() { + return messageTypes[DurableSubProcessConcurrentCommitActivateNoDuplicateTest.random(messageTypes.length - 1)]; + } + + public static String randomNonRelevantMessageType() { + return Integer.toString(DurableSubProcessConcurrentCommitActivateNoDuplicateTest.random(20)); + } + + public final boolean isRelevant(String messageType) { + return messageTypeSet.contains(messageType); + } + + @Override + public final String toString() { + return this.name() /* + '[' + selector + ']' */; + } + } + + /** + * Creates new cliens. + */ + private final class ClientManager extends Thread { + + private int clientRover = 0; + + private final CopyOnWriteArrayList clients = new CopyOnWriteArrayList(); + + private boolean end; + + public ClientManager() { + super("ClientManager"); + setDaemon(true); + } + + public synchronized void setEnd(boolean end) { + this.end = end; + + } + + @Override + public void run() { + try { + while (true) { + if (clients.size() < MAX_CLIENTS && !end) { + processLock.readLock().lock(); + try { + createNewClient(); + } + finally { + processLock.readLock().unlock(); + } + } + + int size = clients.size(); + //sleepRandom(1000, 4000); + Thread.sleep(100); } - return sb.toString(); - } - } + } + catch (Throwable e) { + exit("ClientManager.run failed.", e); + } + } - /** - * Clients listen on different messages in the topic. The 'TYPE' property - * helps the client to select the proper messages. - */ - private enum ClientType { - A("a", "b", "c"), B("c", "d", "e"), C("d", "e", "f"), D("g", "h"); + private void createNewClient() throws JMSException { + ClientType type = ClientType.randomClientType(); - public final String[] messageTypes; - public final HashSet messageTypeSet; - public final String selector; + Client client; + synchronized (server.sendMutex) { + client = new Client(++clientRover, type, CLIENT_LIFETIME, CLIENT_ONLINE, CLIENT_OFFLINE); + clients.add(client); + } + client.start(); - ClientType(String... messageTypes) { - this.messageTypes = messageTypes; - messageTypeSet = new HashSet(Arrays.asList(messageTypes)); + LOG.info(client.toString() + " created. " + this); + } - StringBuilder sb = new StringBuilder("TYPE in ("); - for (int i = 0; i < messageTypes.length; i++) { - if (i > 0) - sb.append(", "); - sb.append('\'').append(messageTypes[i]).append('\''); - } - sb.append(')'); - selector = sb.toString(); - } + public void removeClient(Client client) { + clients.remove(client); + } - public static ClientType randomClientType() { - return values()[DurableSubProcessConcurrentCommitActivateNoDuplicateTest - .random(values().length - 1)]; - } + public void onServerMessage(Message message) throws JMSException { + for (Client client : clients) { + client.onServerMessage(message); + } + } - public final String randomMessageType() { - return messageTypes[DurableSubProcessConcurrentCommitActivateNoDuplicateTest - .random(messageTypes.length - 1)]; - } + @Override + public String toString() { + StringBuilder sb = new StringBuilder("ClientManager[count="); + sb.append(clients.size()); + sb.append(", clients="); + boolean sep = false; + for (Client client : clients) { + if (sep) + sb.append(", "); + else + sep = true; + sb.append(client.toString()); + } + sb.append(']'); + return sb.toString(); + } + } - public static String randomNonRelevantMessageType() { - return Integer - .toString(DurableSubProcessConcurrentCommitActivateNoDuplicateTest.random(20)); - } + /** + * Consumes massages from a durable subscription. Goes online/offline + * periodically. Checks the incoming messages against the sent messages of + * the server. + */ + private final class Client extends Thread { - public final boolean isRelevant(String messageType) { - return messageTypeSet.contains(messageType); - } + String url = "failover:(tcp://localhost:61656?wireFormat.maxInactivityDuration=0)?" + "jms.watchTopicAdvisories=false&" + "jms.alwaysSyncSend=true&jms.dispatchAsync=true&" + "jms.producerWindowSize=20971520&" + "jms.copyMessageOnSend=false&" + "jms.sendAcksAsync=false&" + "initialReconnectDelay=100&maxReconnectDelay=30000&" + "useExponentialBackOff=true"; + final ConnectionFactory cf = new ActiveMQConnectionFactory(url); - @Override - public final String toString() { - return this.name() /* + '[' + selector + ']' */; - } - } + public static final String SUBSCRIPTION_NAME = "subscription"; - /** - * Creates new cliens. - */ - private final class ClientManager extends Thread { + private final int id; + private final String conClientId; - private int clientRover = 0; + private final Random lifetime; + private final Random online; + private final Random offline; - private final CopyOnWriteArrayList clients = new CopyOnWriteArrayList(); + private final ClientType clientType; + private final String selector; - private boolean end; + private final ConcurrentLinkedQueue waitingList = new ConcurrentLinkedQueue(); + private final HashSet processed = CHECK_REDELIVERY ? new HashSet(10000) : null; - public ClientManager() { - super("ClientManager"); - setDaemon(true); - } + private ActiveMQMessageConsumer consumer = null; - public synchronized void setEnd(boolean end) { - this.end = end; + public Client(int id, ClientType clientType, Random lifetime, Random online, Random offline) throws JMSException { + super("Client" + id); + setDaemon(true); - } + this.id = id; + conClientId = "cli" + id; + this.clientType = clientType; + selector = "(COMMIT = true and RELEVANT = true) or " + clientType.selector; - @Override - public void run() { - try { - while (true) { - if (clients.size() < MAX_CLIENTS && !end) { - processLock.readLock().lock(); - try { - createNewClient(); - } finally { - processLock.readLock().unlock(); - } - } + this.lifetime = lifetime; + this.online = online; + this.offline = offline; - int size = clients.size(); - //sleepRandom(1000, 4000); - Thread.sleep(100); - } - } catch (Throwable e) { - exit("ClientManager.run failed.", e); - } - } + subscribe(); + } - private void createNewClient() throws JMSException { - ClientType type = ClientType.randomClientType(); - - Client client; - synchronized (server.sendMutex) { - client = new Client(++clientRover, type, CLIENT_LIFETIME, - CLIENT_ONLINE, CLIENT_OFFLINE); - clients.add(client); - } - client.start(); - - LOG.info(client.toString() + " created. " + this); - } - - public void removeClient(Client client) { - clients.remove(client); - } - - public void onServerMessage(Message message) throws JMSException { - for (Client client : clients) { - client.onServerMessage(message); - } - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("ClientManager[count="); - sb.append(clients.size()); - sb.append(", clients="); - boolean sep = false; - for (Client client : clients) { - if (sep) - sb.append(", "); - else - sep = true; - sb.append(client.toString()); - } - sb.append(']'); - return sb.toString(); - } - } - - /** - * Consumes massages from a durable subscription. Goes online/offline - * periodically. Checks the incoming messages against the sent messages of - * the server. - */ - private final class Client extends Thread { - - String url = "failover:(tcp://localhost:61656?wireFormat.maxInactivityDuration=0)?" - + "jms.watchTopicAdvisories=false&" - + "jms.alwaysSyncSend=true&jms.dispatchAsync=true&" - + "jms.producerWindowSize=20971520&" - + "jms.copyMessageOnSend=false&" - + "jms.sendAcksAsync=false&" - + "initialReconnectDelay=100&maxReconnectDelay=30000&" - + "useExponentialBackOff=true"; - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); - - public static final String SUBSCRIPTION_NAME = "subscription"; - - private final int id; - private final String conClientId; - - private final Random lifetime; - private final Random online; - private final Random offline; - - private final ClientType clientType; - private final String selector; - - private final ConcurrentLinkedQueue waitingList = new ConcurrentLinkedQueue(); - private final HashSet processed = CHECK_REDELIVERY ? new HashSet( - 10000) : null; - - private ActiveMQMessageConsumer consumer = null; - - public Client(int id, ClientType clientType, Random lifetime, - Random online, Random offline) throws JMSException { - super("Client" + id); - setDaemon(true); - - this.id = id; - conClientId = "cli" + id; - this.clientType = clientType; - selector = "(COMMIT = true and RELEVANT = true) or " - + clientType.selector; - - this.lifetime = lifetime; - this.online = online; - this.offline = offline; - - subscribe(); - } - - @Override - public void run() { - long end = System.currentTimeMillis() + 60000; - try { - boolean sleep = false; - while (true) { - long max = end - System.currentTimeMillis(); - if (max <= 0) - break; + @Override + public void run() { + long end = System.currentTimeMillis() + 60000; + try { + boolean sleep = false; + while (true) { + long max = end - System.currentTimeMillis(); + if (max <= 0) + break; /* if (sleep) @@ -492,388 +472,376 @@ public class DurableSubProcessConcurrentCommitActivateNoDuplicateTest { sleep = true; */ - Thread.sleep(100); + Thread.sleep(100); - processLock.readLock().lock(); - onlineCount.incrementAndGet(); - try { - process(online.next()); - } finally { - onlineCount.decrementAndGet(); - processLock.readLock().unlock(); - } - } - - if (!ALLOW_SUBSCRIPTION_ABANDONMENT || random(1) > 0) - unsubscribe(); - else { - LOG.info("Client abandon the subscription. " - + this); - - // housekeeper should sweep these abandoned subscriptions - houseKeeper.abandonedSubscriptions.add(conClientId); - } - } catch (Throwable e) { - exit(toString() + " failed.", e); + processLock.readLock().lock(); + onlineCount.incrementAndGet(); + try { + process(online.next()); + } + finally { + onlineCount.decrementAndGet(); + processLock.readLock().unlock(); + } } - clientManager.removeClient(this); - LOG.info(toString() + " DONE."); - } + if (!ALLOW_SUBSCRIPTION_ABANDONMENT || random(1) > 0) + unsubscribe(); + else { + LOG.info("Client abandon the subscription. " + this); - private void process(long millis) throws JMSException { - //long end = System.currentTimeMillis() + millis; - long end = System.currentTimeMillis() + 200; - long hardEnd = end + 20000; // wait to finish the transaction. - boolean inTransaction = false; - int transCount = 0; + // housekeeper should sweep these abandoned subscriptions + houseKeeper.abandonedSubscriptions.add(conClientId); + } + } + catch (Throwable e) { + exit(toString() + " failed.", e); + } + clientManager.removeClient(this); + LOG.info(toString() + " DONE."); + } + + private void process(long millis) throws JMSException { + //long end = System.currentTimeMillis() + millis; + long end = System.currentTimeMillis() + 200; + long hardEnd = end + 20000; // wait to finish the transaction. + boolean inTransaction = false; + int transCount = 0; + + Connection con = openConnection(); + Session sess = con.createSession(false, Session.CLIENT_ACKNOWLEDGE); + consumer = (ActiveMQMessageConsumer) sess.createDurableSubscriber(topic, SUBSCRIPTION_NAME, selector, false); + LOG.info(toString() + " ONLINE."); + try { + do { + long max = end - System.currentTimeMillis(); + if (max <= 0) { + if (!inTransaction) { + LOG.info(toString() + " done after no work!"); + break; + } + + max = hardEnd - System.currentTimeMillis(); + if (max <= 0) + exit("" + this + " failed: Transaction is not finished."); + } + + Message message = consumer.receive(max); + if (message == null) + continue; + + onClientMessage(message); + + if (message.propertyExists("COMMIT")) { + message.acknowledge(); // CLIENT_ACKNOWLEDGE + + int trans = message.getIntProperty("TRANS"); + LOG.info("Received Trans[id=" + trans + ", count=" + transCount + "] in " + this + "."); + + inTransaction = false; + transCount = 0; + + int committing = server.committingTransaction; + if (committing == trans) { + LOG.info("Going offline during transaction commit. messageID=" + message.getIntProperty("ID")); + break; + } + } + else { + inTransaction = true; + transCount++; + if (1 == transCount) { + LOG.info("In Trans[id=" + message.getIntProperty("TRANS") + "] first ID=" + message.getIntProperty("ID")); + } + } + } while (true); + } + finally { + sess.close(); + con.close(); + + LOG.info(toString() + " OFFLINE."); + + // Check if the messages are in the waiting + // list for long time. + Message topMessage = waitingList.peek(); + if (topMessage != null) + checkDeliveryTime(topMessage); + } + } + + public void onServerMessage(Message message) throws JMSException { + if (Boolean.TRUE.equals(message.getObjectProperty("COMMIT"))) { + if (Boolean.TRUE.equals(message.getObjectProperty("RELEVANT"))) + waitingList.add(message); + } + else { + String messageType = message.getStringProperty("TYPE"); + if (clientType.isRelevant(messageType)) + waitingList.add(message); + } + } + + public void onClientMessage(Message message) { + Message serverMessage = waitingList.poll(); + try { + Integer receivedId = (Integer) message.getObjectProperty("ID"); + if (processed != null && processed.contains(receivedId)) + LOG.info("! Message has been processed before. " + this + " redeliveredFlag=" + message.getJMSRedelivered() + ", message = " + message); + + if (serverMessage == null) + exit("" + this + " failed: There is no next server message, but received: " + message); + + Integer serverId = (Integer) serverMessage.getObjectProperty("ID"); + if (receivedId == null || serverId == null) + exit("" + this + " failed: message ID not found.\r\n" + " received: " + message + "\r\n" + " server: " + serverMessage); + + if (!serverId.equals(receivedId)) { + StringBuilder missingList = new StringBuilder(); + Object lastTrans = null; + int transCount = 0; + Message nextServerMessage = serverMessage; + do { + Integer nextServerId = (Integer) nextServerMessage.getObjectProperty("ID"); + if (nextServerId.equals(receivedId)) { + if (lastTrans != null) + missingList.append("Missing TRANS=").append(lastTrans).append(", size=").append(transCount).append("\r\n"); + break; + } + + Object trans = nextServerMessage.getObjectProperty("TRANS"); + if (!trans.equals(lastTrans)) { + if (lastTrans != null) + missingList.append("Missing TRANS=").append(lastTrans).append(", size=").append(transCount).append("\r\n"); + lastTrans = trans; + transCount = 1; + } + else + transCount++; + } while ((nextServerMessage = waitingList.poll()) != null); + + exit("Missing messages!\r\n" + missingList + + "Received message: " + message + "\r\n" + + "Expected message: " + serverMessage); + } + + checkDeliveryTime(message); + + if (processed != null) + processed.add(receivedId); + } + catch (Throwable e) { + exit("" + this + ".onClientMessage failed.\r\n" + " received: " + message + "\r\n" + " server: " + serverMessage, e); + } + } + + /** + * Checks if the message was not delivered fast enough. + */ + public void checkDeliveryTime(Message message) throws JMSException { + long creation = message.getJMSTimestamp(); + long min = System.currentTimeMillis() - (offline.max + online.min) * (BROKER_RESTART > 0 ? 4 : 1); + + if (false && min > creation) { + SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss.SSS"); + exit("" + this + ".checkDeliveryTime failed. Message time: " + df.format(new Date(creation)) + ", min: " + df.format(new Date(min)) + "\r\n" + message); + } + } + + private Connection openConnection() throws JMSException { + Connection con = cf.createConnection(); + con.setClientID(conClientId); + ((ActiveMQConnection) con).setCloseTimeout(60000); + con.start(); + return con; + } + + private void subscribe() throws JMSException { + processLock.readLock().lock(); + try { Connection con = openConnection(); - Session sess = con.createSession(false, Session.CLIENT_ACKNOWLEDGE); - consumer = (ActiveMQMessageConsumer) sess.createDurableSubscriber(topic, - SUBSCRIPTION_NAME, selector, false); - LOG.info(toString() + " ONLINE."); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, SUBSCRIPTION_NAME, selector, true); + session.close(); + con.close(); + } + finally { + processLock.readLock().unlock(); + } + } + + private void unsubscribe() throws JMSException { + processLock.readLock().lock(); + LOG.info("Unsubscribe: " + this); + try { + Connection con = openConnection(); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.unsubscribe(SUBSCRIPTION_NAME); + session.close(); + con.close(); + } + finally { + processLock.readLock().unlock(); + } + } + + @Override + public String toString() { + return "Client[id=" + id + ", type=" + clientType + "] consumerId=" + (consumer != null ? consumer.getConsumerId() : "null"); + } + } + + /** + * Sweeps out not-used durable subscriptions. + */ + private final class HouseKeeper extends Thread { + + private HouseKeeper() { + super("HouseKeeper"); + setDaemon(true); + } + + public final CopyOnWriteArrayList abandonedSubscriptions = new CopyOnWriteArrayList(); + + @Override + public void run() { + while (true) { try { - do { - long max = end - System.currentTimeMillis(); - if (max <= 0) { - if (!inTransaction) { - LOG.info(toString() + " done after no work!"); - break; - } + Thread.sleep(3 * 60 * 1000); - max = hardEnd - System.currentTimeMillis(); - if (max <= 0) - exit("" + this - + " failed: Transaction is not finished."); - } - - Message message = consumer.receive(max); - if (message == null) - continue; - - onClientMessage(message); - - if (message.propertyExists("COMMIT")) { - message.acknowledge(); // CLIENT_ACKNOWLEDGE - - int trans = message.getIntProperty("TRANS"); - LOG.info("Received Trans[id=" - + trans + ", count=" - + transCount + "] in " + this + "."); - - inTransaction = false; - transCount = 0; - - int committing = server.committingTransaction; - if (committing == trans) { - LOG.info("Going offline during transaction commit. messageID=" + message.getIntProperty("ID")); - break; - } - } else { - inTransaction = true; - transCount++; - if (1 == transCount) { - LOG.info("In Trans[id=" + message.getIntProperty("TRANS") + "] first ID=" + message.getIntProperty("ID")); - } - } - } while (true); - } finally { - sess.close(); - con.close(); - - LOG.info(toString() + " OFFLINE."); - - // Check if the messages are in the waiting - // list for long time. - Message topMessage = waitingList.peek(); - if (topMessage != null) - checkDeliveryTime(topMessage); + processLock.readLock().lock(); + try { + sweep(); + } + finally { + processLock.readLock().unlock(); + } } - } - - public void onServerMessage(Message message) throws JMSException { - if (Boolean.TRUE.equals(message.getObjectProperty("COMMIT"))) { - if (Boolean.TRUE.equals(message.getObjectProperty("RELEVANT"))) - waitingList.add(message); - } else { - String messageType = message.getStringProperty("TYPE"); - if (clientType.isRelevant(messageType)) - waitingList.add(message); + catch (InterruptedException ex) { + break; } - } - - public void onClientMessage(Message message) { - Message serverMessage = waitingList.poll(); - try { - Integer receivedId = (Integer) message.getObjectProperty("ID"); - if (processed != null && processed.contains(receivedId)) - LOG.info("! Message has been processed before. " - + this + " redeliveredFlag=" + message.getJMSRedelivered() + ", message = " + message); - - if (serverMessage == null) - exit("" - + this - + " failed: There is no next server message, but received: " - + message); - - Integer serverId = (Integer) serverMessage - .getObjectProperty("ID"); - if (receivedId == null || serverId == null) - exit("" + this + " failed: message ID not found.\r\n" - + " received: " + message + "\r\n" + " server: " - + serverMessage); - - if (!serverId.equals(receivedId)) { - StringBuilder missingList = new StringBuilder(); - Object lastTrans = null; - int transCount = 0; - Message nextServerMessage = serverMessage; - do { - Integer nextServerId = (Integer) nextServerMessage.getObjectProperty("ID"); - if (nextServerId.equals(receivedId)) { - if (lastTrans != null) - missingList.append("Missing TRANS=").append(lastTrans).append(", size=").append(transCount).append("\r\n"); - break; - } - - Object trans = nextServerMessage.getObjectProperty("TRANS"); - if (!trans.equals(lastTrans)) { - if (lastTrans != null) - missingList.append("Missing TRANS=").append(lastTrans).append(", size=").append(transCount).append("\r\n"); - lastTrans = trans; - transCount = 1; - } - else - transCount++; - } while ((nextServerMessage = waitingList.poll()) != null); - - exit("Missing messages!\r\n" + missingList + - "Received message: " + message + "\r\n" + - "Expected message: " + serverMessage); - } - - checkDeliveryTime(message); - - if (processed != null) - processed.add(receivedId); - } catch (Throwable e) { - exit("" + this + ".onClientMessage failed.\r\n" + " received: " - + message + "\r\n" + " server: " + serverMessage, e); + catch (Throwable e) { + Exception log = new Exception("HouseKeeper failed.", e); + log.printStackTrace(); } - } + } + } - /** - * Checks if the message was not delivered fast enough. - */ - public void checkDeliveryTime(Message message) throws JMSException { - long creation = message.getJMSTimestamp(); - long min = System.currentTimeMillis() - (offline.max + online.min) - * (BROKER_RESTART > 0 ? 4 : 1); + private void sweep() throws Exception { + LOG.info("Housekeeper sweeping."); - if (false && min > creation) { - SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss.SSS"); - exit("" + this + ".checkDeliveryTime failed. Message time: " - + df.format(new Date(creation)) + ", min: " - + df.format(new Date(min)) + "\r\n" + message); + int closed = 0; + ArrayList sweeped = new ArrayList(); + try { + for (String clientId : abandonedSubscriptions) { + LOG.info("Sweeping out subscription of " + clientId + "."); + broker.getAdminView().destroyDurableSubscriber(clientId, Client.SUBSCRIPTION_NAME); + sweeped.add(clientId); + closed++; } - } + } + catch (Exception ignored) { + LOG.info("Ex on destroy sub " + ignored); + } + finally { + abandonedSubscriptions.removeAll(sweeped); + } - private Connection openConnection() throws JMSException { - Connection con = cf.createConnection(); - con.setClientID(conClientId); - ((ActiveMQConnection) con).setCloseTimeout(60000); - con.start(); - return con; - } + LOG.info("Housekeeper sweeped out " + closed + " subscriptions."); + } + } - private void subscribe() throws JMSException { - processLock.readLock().lock(); - try { - Connection con = openConnection(); - Session session = con - .createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, SUBSCRIPTION_NAME, selector, - true); - session.close(); - con.close(); - } - finally { - processLock.readLock().unlock(); - } - } + public static int random(int max) { + return (int) (Math.random() * (max + 1)); + } - private void unsubscribe() throws JMSException { - processLock.readLock().lock(); - LOG.info("Unsubscribe: " + this); - try { - Connection con = openConnection(); - Session session = con - .createSession(false, Session.AUTO_ACKNOWLEDGE); - session.unsubscribe(SUBSCRIPTION_NAME); - session.close(); - con.close(); - } - finally { - processLock.readLock().unlock(); - } - } + public static int random(int min, int max) { + return random(max - min) + min; + } - @Override - public String toString() { - return "Client[id=" + id + ", type=" + clientType + "] consumerId=" + (consumer != null ? consumer.getConsumerId() : "null"); - } - } + public static void sleepRandom(int maxMillis) throws InterruptedException { + Thread.sleep(random(maxMillis)); + } - /** - * Sweeps out not-used durable subscriptions. - */ - private final class HouseKeeper extends Thread { + public static void sleepRandom(int minMillis, int maxMillis) throws InterruptedException { + Thread.sleep(random(minMillis, maxMillis)); + } - private HouseKeeper() { - super("HouseKeeper"); - setDaemon(true); - } + public static final class Random { - public final CopyOnWriteArrayList abandonedSubscriptions = new CopyOnWriteArrayList(); + final int min; + final int max; - @Override - public void run() { - while (true) { - try { - Thread.sleep(3 * 60 * 1000); + Random(int min, int max) { + this.min = min; + this.max = max; + } - processLock.readLock().lock(); - try { - sweep(); - } finally { - processLock.readLock().unlock(); - } - } catch (InterruptedException ex) { - break; - } catch (Throwable e) { - Exception log = new Exception("HouseKeeper failed.", e); - log.printStackTrace(); - } - } - } + public int next() { + return random(min, max); + } - private void sweep() throws Exception { - LOG.info("Housekeeper sweeping."); + public void sleepRandom() throws InterruptedException { + DurableSubProcessConcurrentCommitActivateNoDuplicateTest.sleepRandom(min, max); + } + } - int closed = 0; - ArrayList sweeped = new ArrayList(); - try { - for (String clientId : abandonedSubscriptions) { - LOG.info("Sweeping out subscription of " - + clientId + "."); - broker.getAdminView().destroyDurableSubscriber(clientId, - Client.SUBSCRIPTION_NAME); - sweeped.add(clientId); - closed++; - } - } catch (Exception ignored) { - LOG.info("Ex on destroy sub " + ignored); - } finally { - abandonedSubscriptions.removeAll(sweeped); - } + public static void exit(String message) { + exit(message, null); + } - LOG.info("Housekeeper sweeped out " + closed - + " subscriptions."); - } - } + public static void exit(String message, Throwable e) { + Throwable cause = new RuntimeException(message, e); + LOG.error(message, cause); + exceptions.add(cause); + ThreadTracker.result(); + //fail(cause.toString()); + System.exit(-9); + } - public static int random(int max) { - return (int) (Math.random() * (max + 1)); - } + @Before + public void setUp() throws Exception { + topic = new ActiveMQTopic("TopicT"); + startBroker(); - public static int random(int min, int max) { - return random(max - min) + min; - } + clientManager = new ClientManager(); + server = new Server(); + houseKeeper = new HouseKeeper(); - public static void sleepRandom(int maxMillis) throws InterruptedException { - Thread.sleep(random(maxMillis)); - } + } - public static void sleepRandom(int minMillis, int maxMillis) - throws InterruptedException { - Thread.sleep(random(minMillis, maxMillis)); - } + @After + public void tearDown() throws Exception { + destroyBroker(); + } - public static final class Random { + private enum Persistence { + MEMORY, LEVELDB, KAHADB + } - final int min; - final int max; + private void startBroker() throws Exception { + startBroker(true); + } - Random(int min, int max) { - this.min = min; - this.max = max; - } + private void startBroker(boolean deleteAllMessages) throws Exception { + if (broker != null) + return; - public int next() { - return random(min, max); - } + broker = BrokerFactory.createBroker("broker:(vm://" + getName() + ")"); + broker.setBrokerName(getName()); + broker.setAdvisorySupport(false); + broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - public void sleepRandom() throws InterruptedException { - DurableSubProcessConcurrentCommitActivateNoDuplicateTest.sleepRandom(min, max); - } - } - - public static void exit(String message) { - exit(message, null); - } - - public static void exit(String message, Throwable e) { - Throwable cause = new RuntimeException(message, e); - LOG.error(message, cause); - exceptions.add(cause); - ThreadTracker.result(); - //fail(cause.toString()); - System.exit(-9); - } - - @Before - public void setUp() throws Exception { - topic = new ActiveMQTopic("TopicT"); - startBroker(); - - clientManager = new ClientManager(); - server = new Server(); - houseKeeper = new HouseKeeper(); - - } - - @After - public void tearDown() throws Exception { - destroyBroker(); - } - - private enum Persistence { - MEMORY, LEVELDB, KAHADB - } - - private void startBroker() throws Exception { - startBroker(true); - } - - private void startBroker(boolean deleteAllMessages) throws Exception { - if (broker != null) - return; - - broker = BrokerFactory.createBroker("broker:(vm://" + getName() + ")"); - broker.setBrokerName(getName()); - broker.setAdvisorySupport(false); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - - switch (PERSISTENT_ADAPTER) { - case MEMORY: + switch (PERSISTENT_ADAPTER) { + case MEMORY: broker.setPersistent(false); break; - case LEVELDB: + case LEVELDB: File amqData = new File("activemq-data/" + getName() + "-leveldb"); if (deleteAllMessages) - delete(amqData); + delete(amqData); broker.setPersistent(true); LevelDBStore amq = new LevelDBStore(); @@ -881,10 +849,10 @@ public class DurableSubProcessConcurrentCommitActivateNoDuplicateTest { broker.setPersistenceAdapter(amq); break; - case KAHADB: + case KAHADB: File kahadbData = new File("activemq-data/" + getName() + "-kahadb"); if (deleteAllMessages) - delete(kahadbData); + delete(kahadbData); broker.setPersistent(true); KahaDBPersistenceAdapter kahadb = new KahaDBPersistenceAdapter(); @@ -892,44 +860,43 @@ public class DurableSubProcessConcurrentCommitActivateNoDuplicateTest { kahadb.setJournalMaxFileLength(5 * 1024 * 1024); broker.setPersistenceAdapter(kahadb); break; - } + } - broker.addConnector("tcp://localhost:61656"); + broker.addConnector("tcp://localhost:61656"); - broker.getSystemUsage().getMemoryUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getTempUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getStoreUsage().setLimit(1024 * 1024 * 1024); + broker.getSystemUsage().getMemoryUsage().setLimit(256 * 1024 * 1024); + broker.getSystemUsage().getTempUsage().setLimit(256 * 1024 * 1024); + broker.getSystemUsage().getStoreUsage().setLimit(1024 * 1024 * 1024); + PolicyMap policyMap = new PolicyMap(); + PolicyEntry defaultEntry = new PolicyEntry(); + defaultEntry.setMaxAuditDepth(20000); + policyMap.setDefaultEntry(defaultEntry); + broker.setDestinationPolicy(policyMap); + broker.start(); + } - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setMaxAuditDepth(20000); - policyMap.setDefaultEntry(defaultEntry); - broker.setDestinationPolicy(policyMap); - broker.start(); - } + protected static String getName() { + return "DurableSubProcessWithRestartTest"; + } - protected static String getName() { - return "DurableSubProcessWithRestartTest"; - } + private static boolean delete(File path) { + if (path == null) + return true; - private static boolean delete(File path) { - if (path == null) - return true; + if (path.isDirectory()) { + for (File file : path.listFiles()) { + delete(file); + } + } + return path.delete(); + } - if (path.isDirectory()) { - for (File file : path.listFiles()) { - delete(file); - } - } - return path.delete(); - } + private void destroyBroker() throws Exception { + if (broker == null) + return; - private void destroyBroker() throws Exception { - if (broker == null) - return; - - broker.stop(); - broker = null; - } + broker.stop(); + broker = null; + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessMultiRestartTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessMultiRestartTest.java index 8d3117b73f..90a02c9919 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessMultiRestartTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessMultiRestartTest.java @@ -48,362 +48,370 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DurableSubProcessMultiRestartTest { - private static final Logger LOG = LoggerFactory.getLogger(DurableSubProcessMultiRestartTest.class); - public static final long RUNTIME = 1 * 60 * 1000; + private static final Logger LOG = LoggerFactory.getLogger(DurableSubProcessMultiRestartTest.class); - private BrokerService broker; - private ActiveMQTopic topic; + public static final long RUNTIME = 1 * 60 * 1000; - private final ReentrantReadWriteLock processLock = new ReentrantReadWriteLock(true); + private BrokerService broker; + private ActiveMQTopic topic; - private int restartCount = 0; - private final int SUBSCRIPTION_ID = 1; + private final ReentrantReadWriteLock processLock = new ReentrantReadWriteLock(true); - static final Vector exceptions = new Vector(); + private int restartCount = 0; + private final int SUBSCRIPTION_ID = 1; - /** - * The test creates a durable subscriber and producer with a broker that is - * continually restarted. - * - * Producer creates a message every .5 seconds -creates a new connection for - * each message - * - * durable subscriber - comes online for 10 seconds, - then goes offline for - * a "moment" - repeats the cycle - * - * approx every 10 seconds the broker restarts. Subscriber and Producer - * connections will be closed BEFORE the restart. - * - * The Durable subscriber is "unsubscribed" before the the end of the test. - * - * checks for number of kahaDB files left on filesystem. - * - * @throws Exception - */ - @Test - public void testProcess() throws Exception { + static final Vector exceptions = new Vector(); - DurableSubscriber durableSubscriber = new DurableSubscriber(SUBSCRIPTION_ID); - MsgProducer msgProducer = new MsgProducer(); + /** + * The test creates a durable subscriber and producer with a broker that is + * continually restarted. + * + * Producer creates a message every .5 seconds -creates a new connection for + * each message + * + * durable subscriber - comes online for 10 seconds, - then goes offline for + * a "moment" - repeats the cycle + * + * approx every 10 seconds the broker restarts. Subscriber and Producer + * connections will be closed BEFORE the restart. + * + * The Durable subscriber is "unsubscribed" before the the end of the test. + * + * checks for number of kahaDB files left on filesystem. + * + * @throws Exception + */ + @Test + public void testProcess() throws Exception { - try { - // register the subscription & start messages - durableSubscriber.start(); - msgProducer.start(); + DurableSubscriber durableSubscriber = new DurableSubscriber(SUBSCRIPTION_ID); + MsgProducer msgProducer = new MsgProducer(); - long endTime = System.currentTimeMillis() + RUNTIME; + try { + // register the subscription & start messages + durableSubscriber.start(); + msgProducer.start(); - while (endTime > System.currentTimeMillis()) { - Thread.sleep(10000); - restartBroker(); - } - } catch (Throwable e) { - exit("ProcessTest.testProcess failed.", e); - } + long endTime = System.currentTimeMillis() + RUNTIME; - // wait for threads to finish - try { - msgProducer.join(); - durableSubscriber.join(); - } catch (InterruptedException e) { - e.printStackTrace(System.out); - } + while (endTime > System.currentTimeMillis()) { + Thread.sleep(10000); + restartBroker(); + } + } + catch (Throwable e) { + exit("ProcessTest.testProcess failed.", e); + } - // restart broker one last time - restartBroker(); + // wait for threads to finish + try { + msgProducer.join(); + durableSubscriber.join(); + } + catch (InterruptedException e) { + e.printStackTrace(System.out); + } - assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); + // restart broker one last time + restartBroker(); - final KahaDBPersistenceAdapter pa = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); - assertTrue("only less than two journal files should be left: " + pa.getStore().getJournal().getFileMap().size(), - Wait.waitFor(new Wait.Condition() { + assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); - @Override - public boolean isSatisified() throws Exception { - return pa.getStore().getJournal().getFileMap().size() <= 2; - } - }, TimeUnit.MINUTES.toMillis(3)) - ); + final KahaDBPersistenceAdapter pa = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); + assertTrue("only less than two journal files should be left: " + pa.getStore().getJournal().getFileMap().size(), Wait.waitFor(new Wait.Condition() { - LOG.info("DONE."); - } - - private void restartBroker() throws Exception { - LOG.info("Broker restart: waiting for components."); - - processLock.writeLock().lock(); - try { - destroyBroker(); - startBroker(false); - - restartCount++; - LOG.info("Broker restarted. count: " + restartCount); - } finally { - processLock.writeLock().unlock(); - } - } - - /** - * Producers messages - * - */ - final class MsgProducer extends Thread { - - String url = "vm://" + DurableSubProcessMultiRestartTest.getName(); - - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); - - private long msgCount; - int messageRover = 0; - - public MsgProducer() { - super("MsgProducer"); - setDaemon(true); - } - - @Override - public void run() { - - long endTime = RUNTIME + System.currentTimeMillis(); - - try { - while (endTime > System.currentTimeMillis()) { - - Thread.sleep(500); - - processLock.readLock().lock(); - try { - send(); - } finally { - processLock.readLock().unlock(); + @Override + public boolean isSatisified() throws Exception { + return pa.getStore().getJournal().getFileMap().size() <= 2; } - LOG.info("MsgProducer msgCount=" + msgCount); - } - } catch (Throwable e) { - exit("Server.run failed", e); + }, TimeUnit.MINUTES.toMillis(3))); + + LOG.info("DONE."); + } + + private void restartBroker() throws Exception { + LOG.info("Broker restart: waiting for components."); + + processLock.writeLock().lock(); + try { + destroyBroker(); + startBroker(false); + + restartCount++; + LOG.info("Broker restarted. count: " + restartCount); + } + finally { + processLock.writeLock().unlock(); + } + } + + /** + * Producers messages + */ + final class MsgProducer extends Thread { + + String url = "vm://" + DurableSubProcessMultiRestartTest.getName(); + + final ConnectionFactory cf = new ActiveMQConnectionFactory(url); + + private long msgCount; + int messageRover = 0; + + public MsgProducer() { + super("MsgProducer"); + setDaemon(true); + } + + @Override + public void run() { + + long endTime = RUNTIME + System.currentTimeMillis(); + + try { + while (endTime > System.currentTimeMillis()) { + + Thread.sleep(500); + + processLock.readLock().lock(); + try { + send(); + } + finally { + processLock.readLock().unlock(); + } + LOG.info("MsgProducer msgCount=" + msgCount); } - } + } + catch (Throwable e) { + exit("Server.run failed", e); + } + } - public void send() throws JMSException { + public void send() throws JMSException { - LOG.info("Sending ... "); + LOG.info("Sending ... "); - Connection con = cf.createConnection(); + Connection con = cf.createConnection(); - Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer prod = sess.createProducer(null); - Message message = sess.createMessage(); - message.setIntProperty("ID", ++messageRover); - message.setBooleanProperty("COMMIT", true); - prod.send(topic, message); + MessageProducer prod = sess.createProducer(null); + Message message = sess.createMessage(); + message.setIntProperty("ID", ++messageRover); + message.setBooleanProperty("COMMIT", true); + prod.send(topic, message); - msgCount++; - LOG.info("Message Sent."); + msgCount++; + LOG.info("Message Sent."); + sess.close(); + con.close(); + } + } + + /** + * Consumes massages from a durable subscription. Goes online/offline + * periodically. + */ + private final class DurableSubscriber extends Thread { + + String url = "tcp://localhost:61656"; + + final ConnectionFactory cf = new ActiveMQConnectionFactory(url); + + public static final String SUBSCRIPTION_NAME = "subscription"; + + private final int id; + private final String conClientId; + private long msgCount; + + public DurableSubscriber(int id) throws JMSException { + super("DurableSubscriber" + id); + setDaemon(true); + + this.id = id; + conClientId = "cli" + id; + + subscribe(); + } + + @Override + public void run() { + + long end = System.currentTimeMillis() + RUNTIME; + + try { + + // while (true) { + while (end > System.currentTimeMillis()) { + + processLock.readLock().lock(); + try { + process(5000); + } + finally { + processLock.readLock().unlock(); + } + } + + unsubscribe(); + + } + catch (JMSException maybe) { + if (maybe.getCause() instanceof IOException) { + // ok on broker shutdown; + } + else { + exit(toString() + " failed with JMSException", maybe); + } + } + catch (Throwable e) { + exit(toString() + " failed.", e); + } + + LOG.info(toString() + " DONE. MsgCout=" + msgCount); + } + + private void process(long duration) throws JMSException { + LOG.info(toString() + " ONLINE."); + + Connection con = openConnection(); + Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + + MessageConsumer consumer = sess.createDurableSubscriber(topic, SUBSCRIPTION_NAME); + + long end = System.currentTimeMillis() + duration; + + try { + while (end > System.currentTimeMillis()) { + Message message = consumer.receive(100); + if (message != null) { + LOG.info(toString() + "received message..."); + msgCount++; + } + } + } + finally { sess.close(); con.close(); - } - } + LOG.info(toString() + " OFFLINE."); + } + } - /** - * Consumes massages from a durable subscription. Goes online/offline - * periodically. - */ - private final class DurableSubscriber extends Thread { + private Connection openConnection() throws JMSException { + Connection con = cf.createConnection(); + con.setClientID(conClientId); + con.start(); + return con; + } - String url = "tcp://localhost:61656"; + private void subscribe() throws JMSException { + Connection con = openConnection(); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); + session.createDurableSubscriber(topic, SUBSCRIPTION_NAME); + LOG.info(toString() + " SUBSCRIBED"); - public static final String SUBSCRIPTION_NAME = "subscription"; + session.close(); + con.close(); + } - private final int id; - private final String conClientId; - private long msgCount; + private void unsubscribe() throws JMSException { + Connection con = openConnection(); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.unsubscribe(SUBSCRIPTION_NAME); + LOG.info(toString() + " UNSUBSCRIBED"); - public DurableSubscriber(int id) throws JMSException { - super("DurableSubscriber" + id); - setDaemon(true); + session.close(); + con.close(); + } - this.id = id; - conClientId = "cli" + id; + @Override + public String toString() { + return "DurableSubscriber[id=" + id + "]"; + } + } - subscribe(); - } + // -------- helper methods ----------- - @Override - public void run() { + public static void exit(String message) { + exit(message, null); + } - long end = System.currentTimeMillis() + RUNTIME; + public static void exit(String message, Throwable e) { + Throwable cause = new RuntimeException(message, e); + LOG.error(message, cause); + exceptions.add(cause); + fail(cause.toString()); + } - try { + @Before + public void setUp() throws Exception { + topic = new ActiveMQTopic("TopicT"); + startBroker(); + } - // while (true) { - while (end > System.currentTimeMillis()) { + @After + public void tearDown() throws Exception { + destroyBroker(); + } - processLock.readLock().lock(); - try { - process(5000); - } finally { - processLock.readLock().unlock(); - } - } + private void startBroker() throws Exception { + startBroker(true); + } - unsubscribe(); + private void startBroker(boolean deleteAllMessages) throws Exception { + if (broker != null) + return; - } catch (JMSException maybe) { - if (maybe.getCause() instanceof IOException) { - // ok on broker shutdown; - } else { - exit(toString() + " failed with JMSException", maybe); - } - } catch (Throwable e) { - exit(toString() + " failed.", e); - } + broker = BrokerFactory.createBroker("broker:(vm://" + getName() + ")"); + broker.setBrokerName(getName()); + broker.setAdvisorySupport(false); + broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - LOG.info(toString() + " DONE. MsgCout=" + msgCount); - } + broker.setKeepDurableSubsActive(true); - private void process(long duration) throws JMSException { - LOG.info(toString() + " ONLINE."); + File kahadbData = new File("activemq-data/" + getName() + "-kahadb"); + if (deleteAllMessages) + delete(kahadbData); - Connection con = openConnection(); - Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + broker.setPersistent(true); + KahaDBPersistenceAdapter kahadb = new KahaDBPersistenceAdapter(); + kahadb.setDirectory(kahadbData); + kahadb.setJournalMaxFileLength(20 * 1024); + broker.setPersistenceAdapter(kahadb); - MessageConsumer consumer = sess.createDurableSubscriber(topic, SUBSCRIPTION_NAME); + broker.addConnector("tcp://localhost:61656"); - long end = System.currentTimeMillis() + duration; + broker.getSystemUsage().getMemoryUsage().setLimit(256 * 1024 * 1024); + broker.getSystemUsage().getTempUsage().setLimit(256 * 1024 * 1024); + broker.getSystemUsage().getStoreUsage().setLimit(256 * 1024 * 1024); - try { - while (end > System.currentTimeMillis()) { - Message message = consumer.receive(100); - if (message != null) { - LOG.info(toString() + "received message..."); - msgCount++; - } - } - } finally { - sess.close(); - con.close(); - LOG.info(toString() + " OFFLINE."); - } - } + broker.start(); + } - private Connection openConnection() throws JMSException { - Connection con = cf.createConnection(); - con.setClientID(conClientId); - con.start(); - return con; - } + protected static String getName() { + return "DurableSubProcessMultiRestartTest"; + } - private void subscribe() throws JMSException { - Connection con = openConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + private static boolean delete(File path) { + if (path == null) + return true; - session.createDurableSubscriber(topic, SUBSCRIPTION_NAME); - LOG.info(toString() + " SUBSCRIBED"); + if (path.isDirectory()) { + for (File file : path.listFiles()) { + delete(file); + } + } + return path.delete(); + } - session.close(); - con.close(); - } + private void destroyBroker() throws Exception { + if (broker == null) + return; - private void unsubscribe() throws JMSException { - Connection con = openConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.unsubscribe(SUBSCRIPTION_NAME); - LOG.info(toString() + " UNSUBSCRIBED"); - - session.close(); - con.close(); - } - - @Override - public String toString() { - return "DurableSubscriber[id=" + id + "]"; - } - } - - // -------- helper methods ----------- - - public static void exit(String message) { - exit(message, null); - } - - public static void exit(String message, Throwable e) { - Throwable cause = new RuntimeException(message, e); - LOG.error(message, cause); - exceptions.add(cause); - fail(cause.toString()); - } - - @Before - public void setUp() throws Exception { - topic = new ActiveMQTopic("TopicT"); - startBroker(); - } - - @After - public void tearDown() throws Exception { - destroyBroker(); - } - - private void startBroker() throws Exception { - startBroker(true); - } - - private void startBroker(boolean deleteAllMessages) throws Exception { - if (broker != null) - return; - - broker = BrokerFactory.createBroker("broker:(vm://" + getName() + ")"); - broker.setBrokerName(getName()); - broker.setAdvisorySupport(false); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - - broker.setKeepDurableSubsActive(true); - - File kahadbData = new File("activemq-data/" + getName() + "-kahadb"); - if (deleteAllMessages) - delete(kahadbData); - - broker.setPersistent(true); - KahaDBPersistenceAdapter kahadb = new KahaDBPersistenceAdapter(); - kahadb.setDirectory(kahadbData); - kahadb.setJournalMaxFileLength(20 * 1024); - broker.setPersistenceAdapter(kahadb); - - broker.addConnector("tcp://localhost:61656"); - - broker.getSystemUsage().getMemoryUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getTempUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getStoreUsage().setLimit(256 * 1024 * 1024); - - broker.start(); - } - - protected static String getName() { - return "DurableSubProcessMultiRestartTest"; - } - - private static boolean delete(File path) { - if (path == null) - return true; - - if (path.isDirectory()) { - for (File file : path.listFiles()) { - delete(file); - } - } - return path.delete(); - } - - private void destroyBroker() throws Exception { - if (broker == null) - return; - - broker.stop(); - broker = null; - } + broker.stop(); + broker = null; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessTest.java index 71ab687cdd..f298767cf5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessTest.java @@ -38,641 +38,645 @@ import java.util.concurrent.CopyOnWriteArrayList; // see https://issues.apache.org/activemq/browse/AMQ-2985 // this demonstrated receiving old messages eventually along with validating order receipt -public class DurableSubProcessTest extends org.apache.activemq.TestSupport { - private static final Logger LOG = LoggerFactory.getLogger(DurableSubProcessTest.class); - public static final long RUNTIME = 4 * 60 * 1000; - - public static final int SERVER_SLEEP = 2 * 1000; // max - public static final int CARGO_SIZE = 10; // max - - public static final int MAX_CLIENTS = 7; - public static final Random CLIENT_LIFETIME = new Random(30 * 1000, 2 * 60 * 1000); - public static final Random CLIENT_ONLINE = new Random(2 * 1000, 15 * 1000); - public static final Random CLIENT_OFFLINE = new Random(1 * 1000, 20 * 1000); - - public static final boolean PERSISTENT_BROKER = true; - public static final boolean ALLOW_SUBSCRIPTION_ABANDONMENT = true; - - - private BrokerService broker; - private ActiveMQTopic topic; - - private ClientManager clientManager; - private Server server; - private HouseKeeper houseKeeper; - - static final Vector exceptions = new Vector(); - - @Test - public void testProcess() { - try { - server.start(); - clientManager.start(); - - if (ALLOW_SUBSCRIPTION_ABANDONMENT) - houseKeeper.start(); - - Thread.sleep(RUNTIME); - assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); - } - catch (Throwable e) { - exit("DurableSubProcessTest.testProcess failed.", e); - } - LOG.info("DONE."); - } - - /** - * Creates batch of messages in a transaction periodically. - * The last message in the transaction is always a special - * message what contains info about the whole transaction. - *

    Notifies the clients about the created messages also. - */ - final class Server extends Thread { - - final String url = "vm://" + DurableSubProcessTest.this.getName() + "?" + - "jms.redeliveryPolicy.maximumRedeliveries=2&jms.redeliveryPolicy.initialRedeliveryDelay=500&" + - "jms.producerWindowSize=20971520&jms.prefetchPolicy.all=100&" + - "jms.copyMessageOnSend=false&jms.disableTimeStampsByDefault=false&" + - "jms.alwaysSyncSend=true&jms.dispatchAsync=false&" + - "jms.watchTopicAdvisories=false&" + - "waitForStart=200&create=false"; - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); - - final Object sendMutex = new Object(); - final String[] cargos = new String[500]; - - int transRover = 0; - int messageRover = 0; - - public Server() { - super("Server"); - setDaemon(true); - } - - @Override - public void run() { - try { - while (true) { - DurableSubProcessTest.sleepRandom(SERVER_SLEEP); - send(); - } - } - catch (Throwable e) { - exit("Server.run failed", e); - } - } - - public void send() throws JMSException { - // do not create new clients now - // ToDo: Test this case later. - synchronized (sendMutex) { - int trans = ++transRover; - boolean relevantTrans = random(2) > 1; - ClientType clientType = relevantTrans ? ClientType.randomClientType() : null; // sends this types - int count = random(200); - - LOG.info("Sending Trans[id=" + trans + ", count=" + count + ", clientType=" + clientType + "]"); - - Connection con = cf.createConnection(); - Session sess = con.createSession(true, Session.AUTO_ACKNOWLEDGE); - MessageProducer prod = sess.createProducer(null); - - for (int i = 0; i < count; i++) { - Message message = sess.createMessage(); - message.setIntProperty("ID", ++messageRover); - String type = clientType != null ? clientType.randomMessageType() : ClientType.randomNonRelevantMessageType(); - message.setStringProperty("TYPE", type); - - if (CARGO_SIZE > 0) - message.setStringProperty("CARGO", getCargo(CARGO_SIZE)); - - prod.send(topic, message); - clientManager.onServerMessage(message); - } - - Message message = sess.createMessage(); - message.setIntProperty("ID", ++messageRover); - message.setIntProperty("TRANS", trans); - message.setBooleanProperty("COMMIT", true); - message.setBooleanProperty("RELEVANT", relevantTrans); - prod.send(topic, message); - clientManager.onServerMessage(message); - - sess.commit(); - sess.close(); - con.close(); - } - } - - private String getCargo(int length) { - if (length == 0) - return null; - - if (length < cargos.length) { - String result = cargos[length]; - if (result == null) { - result = getCargoImpl(length); - cargos[length] = result; - } - return result; - } - return getCargoImpl(length); - } - - private String getCargoImpl(int length) { - StringBuilder sb = new StringBuilder(length); - for (int i = length; --i >=0; ) { - sb.append('a'); - } - return sb.toString(); - } - } - - /** - * Clients listen on different messages in the topic. - * The 'TYPE' property helps the client to select the - * proper messages. - */ - private enum ClientType { - A ("a", "b", "c"), - B ("c", "d", "e"), - C ("d", "e", "f"), - D ("g", "h"); - - public final String[] messageTypes; - public final HashSet messageTypeSet; - public final String selector; - - ClientType(String... messageTypes) { - this.messageTypes = messageTypes; - messageTypeSet = new HashSet(Arrays.asList(messageTypes)); - - StringBuilder sb = new StringBuilder("TYPE in ("); - for (int i = 0; i < messageTypes.length; i++) { - if (i > 0) - sb.append(", "); - sb.append('\'').append(messageTypes[i]).append('\''); - } - sb.append(')'); - selector = sb.toString(); - } - - public static ClientType randomClientType() { - return values()[DurableSubProcessTest.random(values().length - 1)]; - } - - public final String randomMessageType() { - return messageTypes[DurableSubProcessTest.random(messageTypes.length - 1)]; - } - - public static String randomNonRelevantMessageType() { - return Integer.toString(DurableSubProcessTest.random(20)); - } - - public final boolean isRelevant(String messageType) { - return messageTypeSet.contains(messageType); - } - - @Override - public final String toString() { - return this.name() /*+ '[' + selector + ']'*/; - } - } - - /** - * Creates new cliens. - */ - private final class ClientManager extends Thread { - - private int clientRover = 0; - - private final CopyOnWriteArrayList clients = new CopyOnWriteArrayList(); - - public ClientManager() { - super("ClientManager"); - setDaemon(true); - } - - @Override - public void run() { - try { - while (true) { - if (clients.size() < MAX_CLIENTS) - createNewClient(); - - int size = clients.size(); - sleepRandom(size * 3 * 1000, size * 6 * 1000); - } - } - catch (Throwable e) { - exit("ClientManager.run failed.", e); - } - } - - private void createNewClient() throws JMSException { - ClientType type = ClientType.randomClientType(); - - Client client; - synchronized (server.sendMutex) { - client = new Client(++clientRover, type, CLIENT_LIFETIME, CLIENT_ONLINE, CLIENT_OFFLINE); - clients.add(client); - } - client.start(); - - LOG.info(client.toString() + " created. " + this); - } - - public void removeClient(Client client) { - clients.remove(client); - } - - public void onServerMessage(Message message) throws JMSException { - for (Client client: clients) { - client.onServerMessage(message); - } - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("ClientManager[count="); - sb.append(clients.size()); - sb.append(", clients="); - boolean sep = false; - for (Client client: clients) { - if (sep) sb.append(", "); - else sep = true; - sb.append(client.toString()); - } - sb.append(']'); - return sb.toString(); - } - } - - /** - * Consumes massages from a durable subscription. - * Goes online/offline periodically. Checks the incoming messages - * against the sent messages of the server. - */ - private final class Client extends Thread { - - String url = "failover:(tcp://localhost:61656?wireFormat.maxInactivityDuration=0)?" + - "jms.watchTopicAdvisories=false&" + - "jms.alwaysSyncSend=true&jms.dispatchAsync=true&" + - "jms.producerWindowSize=20971520&" + - "jms.copyMessageOnSend=false&" + - "initialReconnectDelay=100&maxReconnectDelay=30000&" + - "useExponentialBackOff=true"; - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); - - public static final String SUBSCRIPTION_NAME = "subscription"; - - private final int id; - private final String conClientId; - - private final Random lifetime; - private final Random online; - private final Random offline; - - private final ClientType clientType; - private final String selector; - - private final ConcurrentLinkedQueue waitingList = new ConcurrentLinkedQueue(); - - public Client(int id, ClientType clientType, Random lifetime, Random online, Random offline) throws JMSException { - super("Client" + id); - setDaemon(true); - - this.id = id; - conClientId = "cli" + id; - this.clientType = clientType; - selector = "(COMMIT = true and RELEVANT = true) or " + clientType.selector; - - this.lifetime = lifetime; - this.online = online; - this.offline = offline; - - subscribe(); - } - - @Override - public void run() { - long end = System.currentTimeMillis() + lifetime.next(); - try { - boolean sleep = false; - while (true) { - long max = end - System.currentTimeMillis(); - if (max <= 0) - break; - - if (sleep) offline.sleepRandom(); - else sleep = true; - - process(online.next()); - } - - if (!ALLOW_SUBSCRIPTION_ABANDONMENT || random(1) > 0) - unsubscribe(); - else { - LOG.info("Client abandon the subscription. " + this); - - // housekeeper should sweep these abandoned subscriptions - houseKeeper.abandonedSubscriptions.add(conClientId); - } - } - catch (Throwable e) { - exit(toString() + " failed.", e); - } - - clientManager.removeClient(this); - LOG.info(toString() + " DONE."); - } - - private void process(long millis) throws JMSException { - long end = System.currentTimeMillis() + millis; - long hardEnd = end + 2000; // wait to finish the transaction. - boolean inTransaction = false; - int transCount = 0; - - LOG.info(toString() + " ONLINE."); - Connection con = openConnection(); - Session sess = con.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = sess.createDurableSubscriber(topic, SUBSCRIPTION_NAME, selector, false); - try { - do { - long max = end - System.currentTimeMillis(); - if (max <= 0) { - if (!inTransaction) - break; - - max = hardEnd - System.currentTimeMillis(); - if (max <= 0) - exit("" + this + " failed: Transaction is not finished."); - } - - Message message = consumer.receive(max); - if (message == null) - continue; - - onClientMessage(message); - - if (message.propertyExists("COMMIT")) { - message.acknowledge(); - - LOG.info("Received Trans[id=" + message.getIntProperty("TRANS") + ", count=" + transCount + "] in " + this + "."); - - inTransaction = false; - transCount = 0; - } - else { - inTransaction = true; - transCount++; - } - } while (true); - } - finally { - sess.close(); - con.close(); - - LOG.info(toString() + " OFFLINE."); - - // Check if the messages are in the waiting - // list for long time. - Message topMessage = waitingList.peek(); - if (topMessage != null) - checkDeliveryTime(topMessage); - } - } - - public void onServerMessage(Message message) throws JMSException { - if (Boolean.TRUE.equals(message.getObjectProperty("COMMIT"))) { - if (Boolean.TRUE.equals(message.getObjectProperty("RELEVANT"))) - waitingList.add(message); - } - else { - String messageType = message.getStringProperty("TYPE"); - if (clientType.isRelevant(messageType)) - waitingList.add(message); - } - } - - public void onClientMessage(Message message) { - Message serverMessage = waitingList.poll(); - try { - if (serverMessage == null) - exit("" + this + " failed: There is no next server message, but received: " + message); - - Integer receivedId = (Integer) message.getObjectProperty("ID"); - Integer serverId = (Integer) serverMessage.getObjectProperty("ID"); - if (receivedId == null || serverId == null) - exit("" + this + " failed: message ID not found.\r\n" + - " received: " + message + "\r\n" + - " server: " + serverMessage); - - if (!serverId.equals(receivedId)) - exit("" + this + " failed: Received wrong message.\r\n" + - " received: " + message + "\r\n" + - " server: " + serverMessage); - - checkDeliveryTime(message); - } - catch (Throwable e) { - exit("" + this + ".onClientMessage failed.\r\n" + - " received: " + message + "\r\n" + - " server: " + serverMessage, e); - } - } - - /** - * Checks if the message was not delivered fast enough. - */ - public void checkDeliveryTime(Message message) throws JMSException { - long creation = message.getJMSTimestamp(); - long min = System.currentTimeMillis() - (offline.max + online.min); - - if (min > creation) { - SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss.SSS"); - exit("" + this + ".checkDeliveryTime failed. Message time: " + df.format(new Date(creation)) + ", min: " + df.format(new Date(min)) + "\r\n" + message); - } - } - - private Connection openConnection() throws JMSException { - Connection con = cf.createConnection(); - con.setClientID(conClientId); - con.start(); - return con; - } - - private void subscribe() throws JMSException { - Connection con = openConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, SUBSCRIPTION_NAME, selector, true); - session.close(); - con.close(); - } - - private void unsubscribe() throws JMSException { - Connection con = openConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.unsubscribe(SUBSCRIPTION_NAME); - session.close(); - con.close(); - } - - @Override - public String toString() { - return "Client[id=" + id + ", type=" + clientType + "]"; - } - } - - /** - * Sweeps out not-used durable subscriptions. - */ - private final class HouseKeeper extends Thread { - - private HouseKeeper() { - super("HouseKeeper"); - setDaemon(true); - } - - public final CopyOnWriteArrayList abandonedSubscriptions = new CopyOnWriteArrayList(); - - @Override - public void run() { +public class DurableSubProcessTest extends org.apache.activemq.TestSupport { + + private static final Logger LOG = LoggerFactory.getLogger(DurableSubProcessTest.class); + public static final long RUNTIME = 4 * 60 * 1000; + + public static final int SERVER_SLEEP = 2 * 1000; // max + public static final int CARGO_SIZE = 10; // max + + public static final int MAX_CLIENTS = 7; + public static final Random CLIENT_LIFETIME = new Random(30 * 1000, 2 * 60 * 1000); + public static final Random CLIENT_ONLINE = new Random(2 * 1000, 15 * 1000); + public static final Random CLIENT_OFFLINE = new Random(1 * 1000, 20 * 1000); + + public static final boolean PERSISTENT_BROKER = true; + public static final boolean ALLOW_SUBSCRIPTION_ABANDONMENT = true; + + private BrokerService broker; + private ActiveMQTopic topic; + + private ClientManager clientManager; + private Server server; + private HouseKeeper houseKeeper; + + static final Vector exceptions = new Vector(); + + @Test + public void testProcess() { + try { + server.start(); + clientManager.start(); + + if (ALLOW_SUBSCRIPTION_ABANDONMENT) + houseKeeper.start(); + + Thread.sleep(RUNTIME); + assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); + } + catch (Throwable e) { + exit("DurableSubProcessTest.testProcess failed.", e); + } + LOG.info("DONE."); + } + + /** + * Creates batch of messages in a transaction periodically. + * The last message in the transaction is always a special + * message what contains info about the whole transaction. + *

    Notifies the clients about the created messages also. + */ + final class Server extends Thread { + + final String url = "vm://" + DurableSubProcessTest.this.getName() + "?" + + "jms.redeliveryPolicy.maximumRedeliveries=2&jms.redeliveryPolicy.initialRedeliveryDelay=500&" + + "jms.producerWindowSize=20971520&jms.prefetchPolicy.all=100&" + + "jms.copyMessageOnSend=false&jms.disableTimeStampsByDefault=false&" + + "jms.alwaysSyncSend=true&jms.dispatchAsync=false&" + + "jms.watchTopicAdvisories=false&" + + "waitForStart=200&create=false"; + final ConnectionFactory cf = new ActiveMQConnectionFactory(url); + + final Object sendMutex = new Object(); + final String[] cargos = new String[500]; + + int transRover = 0; + int messageRover = 0; + + public Server() { + super("Server"); + setDaemon(true); + } + + @Override + public void run() { + try { while (true) { - try { - Thread.sleep(60 * 1000); - sweep(); - } - catch (InterruptedException ex) { - break; - } - catch (Throwable e) { - Exception log = new Exception("HouseKeeper failed.", e); - log.printStackTrace(); - } + DurableSubProcessTest.sleepRandom(SERVER_SLEEP); + send(); } - } + } + catch (Throwable e) { + exit("Server.run failed", e); + } + } - private void sweep() throws Exception { - LOG.info("Housekeeper sweeping."); + public void send() throws JMSException { + // do not create new clients now + // ToDo: Test this case later. + synchronized (sendMutex) { + int trans = ++transRover; + boolean relevantTrans = random(2) > 1; + ClientType clientType = relevantTrans ? ClientType.randomClientType() : null; // sends this types + int count = random(200); - int closed = 0; - ArrayList sweeped = new ArrayList(); + LOG.info("Sending Trans[id=" + trans + ", count=" + count + ", clientType=" + clientType + "]"); + + Connection con = cf.createConnection(); + Session sess = con.createSession(true, Session.AUTO_ACKNOWLEDGE); + MessageProducer prod = sess.createProducer(null); + + for (int i = 0; i < count; i++) { + Message message = sess.createMessage(); + message.setIntProperty("ID", ++messageRover); + String type = clientType != null ? clientType.randomMessageType() : ClientType.randomNonRelevantMessageType(); + message.setStringProperty("TYPE", type); + + if (CARGO_SIZE > 0) + message.setStringProperty("CARGO", getCargo(CARGO_SIZE)); + + prod.send(topic, message); + clientManager.onServerMessage(message); + } + + Message message = sess.createMessage(); + message.setIntProperty("ID", ++messageRover); + message.setIntProperty("TRANS", trans); + message.setBooleanProperty("COMMIT", true); + message.setBooleanProperty("RELEVANT", relevantTrans); + prod.send(topic, message); + clientManager.onServerMessage(message); + + sess.commit(); + sess.close(); + con.close(); + } + } + + private String getCargo(int length) { + if (length == 0) + return null; + + if (length < cargos.length) { + String result = cargos[length]; + if (result == null) { + result = getCargoImpl(length); + cargos[length] = result; + } + return result; + } + return getCargoImpl(length); + } + + private String getCargoImpl(int length) { + StringBuilder sb = new StringBuilder(length); + for (int i = length; --i >= 0; ) { + sb.append('a'); + } + return sb.toString(); + } + } + + /** + * Clients listen on different messages in the topic. + * The 'TYPE' property helps the client to select the + * proper messages. + */ + private enum ClientType { + A("a", "b", "c"), + B("c", "d", "e"), + C("d", "e", "f"), + D("g", "h"); + + public final String[] messageTypes; + public final HashSet messageTypeSet; + public final String selector; + + ClientType(String... messageTypes) { + this.messageTypes = messageTypes; + messageTypeSet = new HashSet(Arrays.asList(messageTypes)); + + StringBuilder sb = new StringBuilder("TYPE in ("); + for (int i = 0; i < messageTypes.length; i++) { + if (i > 0) + sb.append(", "); + sb.append('\'').append(messageTypes[i]).append('\''); + } + sb.append(')'); + selector = sb.toString(); + } + + public static ClientType randomClientType() { + return values()[DurableSubProcessTest.random(values().length - 1)]; + } + + public final String randomMessageType() { + return messageTypes[DurableSubProcessTest.random(messageTypes.length - 1)]; + } + + public static String randomNonRelevantMessageType() { + return Integer.toString(DurableSubProcessTest.random(20)); + } + + public final boolean isRelevant(String messageType) { + return messageTypeSet.contains(messageType); + } + + @Override + public final String toString() { + return this.name() /*+ '[' + selector + ']'*/; + } + } + + /** + * Creates new cliens. + */ + private final class ClientManager extends Thread { + + private int clientRover = 0; + + private final CopyOnWriteArrayList clients = new CopyOnWriteArrayList(); + + public ClientManager() { + super("ClientManager"); + setDaemon(true); + } + + @Override + public void run() { + try { + while (true) { + if (clients.size() < MAX_CLIENTS) + createNewClient(); + + int size = clients.size(); + sleepRandom(size * 3 * 1000, size * 6 * 1000); + } + } + catch (Throwable e) { + exit("ClientManager.run failed.", e); + } + } + + private void createNewClient() throws JMSException { + ClientType type = ClientType.randomClientType(); + + Client client; + synchronized (server.sendMutex) { + client = new Client(++clientRover, type, CLIENT_LIFETIME, CLIENT_ONLINE, CLIENT_OFFLINE); + clients.add(client); + } + client.start(); + + LOG.info(client.toString() + " created. " + this); + } + + public void removeClient(Client client) { + clients.remove(client); + } + + public void onServerMessage(Message message) throws JMSException { + for (Client client : clients) { + client.onServerMessage(message); + } + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("ClientManager[count="); + sb.append(clients.size()); + sb.append(", clients="); + boolean sep = false; + for (Client client : clients) { + if (sep) + sb.append(", "); + else + sep = true; + sb.append(client.toString()); + } + sb.append(']'); + return sb.toString(); + } + } + + /** + * Consumes massages from a durable subscription. + * Goes online/offline periodically. Checks the incoming messages + * against the sent messages of the server. + */ + private final class Client extends Thread { + + String url = "failover:(tcp://localhost:61656?wireFormat.maxInactivityDuration=0)?" + + "jms.watchTopicAdvisories=false&" + + "jms.alwaysSyncSend=true&jms.dispatchAsync=true&" + + "jms.producerWindowSize=20971520&" + + "jms.copyMessageOnSend=false&" + + "initialReconnectDelay=100&maxReconnectDelay=30000&" + + "useExponentialBackOff=true"; + final ConnectionFactory cf = new ActiveMQConnectionFactory(url); + + public static final String SUBSCRIPTION_NAME = "subscription"; + + private final int id; + private final String conClientId; + + private final Random lifetime; + private final Random online; + private final Random offline; + + private final ClientType clientType; + private final String selector; + + private final ConcurrentLinkedQueue waitingList = new ConcurrentLinkedQueue(); + + public Client(int id, ClientType clientType, Random lifetime, Random online, Random offline) throws JMSException { + super("Client" + id); + setDaemon(true); + + this.id = id; + conClientId = "cli" + id; + this.clientType = clientType; + selector = "(COMMIT = true and RELEVANT = true) or " + clientType.selector; + + this.lifetime = lifetime; + this.online = online; + this.offline = offline; + + subscribe(); + } + + @Override + public void run() { + long end = System.currentTimeMillis() + lifetime.next(); + try { + boolean sleep = false; + while (true) { + long max = end - System.currentTimeMillis(); + if (max <= 0) + break; + + if (sleep) + offline.sleepRandom(); + else + sleep = true; + + process(online.next()); + } + + if (!ALLOW_SUBSCRIPTION_ABANDONMENT || random(1) > 0) + unsubscribe(); + else { + LOG.info("Client abandon the subscription. " + this); + + // housekeeper should sweep these abandoned subscriptions + houseKeeper.abandonedSubscriptions.add(conClientId); + } + } + catch (Throwable e) { + exit(toString() + " failed.", e); + } + + clientManager.removeClient(this); + LOG.info(toString() + " DONE."); + } + + private void process(long millis) throws JMSException { + long end = System.currentTimeMillis() + millis; + long hardEnd = end + 2000; // wait to finish the transaction. + boolean inTransaction = false; + int transCount = 0; + + LOG.info(toString() + " ONLINE."); + Connection con = openConnection(); + Session sess = con.createSession(false, Session.CLIENT_ACKNOWLEDGE); + MessageConsumer consumer = sess.createDurableSubscriber(topic, SUBSCRIPTION_NAME, selector, false); + try { + do { + long max = end - System.currentTimeMillis(); + if (max <= 0) { + if (!inTransaction) + break; + + max = hardEnd - System.currentTimeMillis(); + if (max <= 0) + exit("" + this + " failed: Transaction is not finished."); + } + + Message message = consumer.receive(max); + if (message == null) + continue; + + onClientMessage(message); + + if (message.propertyExists("COMMIT")) { + message.acknowledge(); + + LOG.info("Received Trans[id=" + message.getIntProperty("TRANS") + ", count=" + transCount + "] in " + this + "."); + + inTransaction = false; + transCount = 0; + } + else { + inTransaction = true; + transCount++; + } + } while (true); + } + finally { + sess.close(); + con.close(); + + LOG.info(toString() + " OFFLINE."); + + // Check if the messages are in the waiting + // list for long time. + Message topMessage = waitingList.peek(); + if (topMessage != null) + checkDeliveryTime(topMessage); + } + } + + public void onServerMessage(Message message) throws JMSException { + if (Boolean.TRUE.equals(message.getObjectProperty("COMMIT"))) { + if (Boolean.TRUE.equals(message.getObjectProperty("RELEVANT"))) + waitingList.add(message); + } + else { + String messageType = message.getStringProperty("TYPE"); + if (clientType.isRelevant(messageType)) + waitingList.add(message); + } + } + + public void onClientMessage(Message message) { + Message serverMessage = waitingList.poll(); + try { + if (serverMessage == null) + exit("" + this + " failed: There is no next server message, but received: " + message); + + Integer receivedId = (Integer) message.getObjectProperty("ID"); + Integer serverId = (Integer) serverMessage.getObjectProperty("ID"); + if (receivedId == null || serverId == null) + exit("" + this + " failed: message ID not found.\r\n" + + " received: " + message + "\r\n" + + " server: " + serverMessage); + + if (!serverId.equals(receivedId)) + exit("" + this + " failed: Received wrong message.\r\n" + + " received: " + message + "\r\n" + + " server: " + serverMessage); + + checkDeliveryTime(message); + } + catch (Throwable e) { + exit("" + this + ".onClientMessage failed.\r\n" + + " received: " + message + "\r\n" + + " server: " + serverMessage, e); + } + } + + /** + * Checks if the message was not delivered fast enough. + */ + public void checkDeliveryTime(Message message) throws JMSException { + long creation = message.getJMSTimestamp(); + long min = System.currentTimeMillis() - (offline.max + online.min); + + if (min > creation) { + SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss.SSS"); + exit("" + this + ".checkDeliveryTime failed. Message time: " + df.format(new Date(creation)) + ", min: " + df.format(new Date(min)) + "\r\n" + message); + } + } + + private Connection openConnection() throws JMSException { + Connection con = cf.createConnection(); + con.setClientID(conClientId); + con.start(); + return con; + } + + private void subscribe() throws JMSException { + Connection con = openConnection(); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, SUBSCRIPTION_NAME, selector, true); + session.close(); + con.close(); + } + + private void unsubscribe() throws JMSException { + Connection con = openConnection(); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.unsubscribe(SUBSCRIPTION_NAME); + session.close(); + con.close(); + } + + @Override + public String toString() { + return "Client[id=" + id + ", type=" + clientType + "]"; + } + } + + /** + * Sweeps out not-used durable subscriptions. + */ + private final class HouseKeeper extends Thread { + + private HouseKeeper() { + super("HouseKeeper"); + setDaemon(true); + } + + public final CopyOnWriteArrayList abandonedSubscriptions = new CopyOnWriteArrayList(); + + @Override + public void run() { + while (true) { try { - for (String clientId: abandonedSubscriptions) { - sweeped.add(clientId); - LOG.info("Sweeping out subscription of " + clientId + "."); - broker.getAdminView().destroyDurableSubscriber(clientId, Client.SUBSCRIPTION_NAME); - closed++; - } + Thread.sleep(60 * 1000); + sweep(); } - finally { - abandonedSubscriptions.removeAll(sweeped); + catch (InterruptedException ex) { + break; } + catch (Throwable e) { + Exception log = new Exception("HouseKeeper failed.", e); + log.printStackTrace(); + } + } + } - LOG.info("Housekeeper sweeped out " + closed + " subscriptions."); - } - } + private void sweep() throws Exception { + LOG.info("Housekeeper sweeping."); - public static int random(int max) { - return (int) (Math.random() * (max + 1)); - } + int closed = 0; + ArrayList sweeped = new ArrayList(); + try { + for (String clientId : abandonedSubscriptions) { + sweeped.add(clientId); + LOG.info("Sweeping out subscription of " + clientId + "."); + broker.getAdminView().destroyDurableSubscriber(clientId, Client.SUBSCRIPTION_NAME); + closed++; + } + } + finally { + abandonedSubscriptions.removeAll(sweeped); + } - public static int random(int min, int max) { - return random(max - min) + min; - } + LOG.info("Housekeeper sweeped out " + closed + " subscriptions."); + } + } - public static void sleepRandom(int maxMillis) throws InterruptedException { - Thread.sleep(random(maxMillis)); - } + public static int random(int max) { + return (int) (Math.random() * (max + 1)); + } - public static void sleepRandom(int minMillis, int maxMillis) throws InterruptedException { - Thread.sleep(random(minMillis, maxMillis)); - } + public static int random(int min, int max) { + return random(max - min) + min; + } - public static final class Random { + public static void sleepRandom(int maxMillis) throws InterruptedException { + Thread.sleep(random(maxMillis)); + } - final int min; - final int max; + public static void sleepRandom(int minMillis, int maxMillis) throws InterruptedException { + Thread.sleep(random(minMillis, maxMillis)); + } - Random(int min, int max) { - this.min = min; - this.max = max; - } + public static final class Random { - public int next() { - return random(min, max); - } + final int min; + final int max; - public void sleepRandom() throws InterruptedException { - DurableSubProcessTest.sleepRandom(min, max); - } - } + Random(int min, int max) { + this.min = min; + this.max = max; + } - public static void exit(String message) { - exit(message, null); - } + public int next() { + return random(min, max); + } - public static void exit(String message, Throwable e) { - Throwable log = new RuntimeException(message, e); - log.printStackTrace(); - LOG.error(message, e); - exceptions.add(e); - fail(message); - } + public void sleepRandom() throws InterruptedException { + DurableSubProcessTest.sleepRandom(min, max); + } + } - protected void setUp() throws Exception { - topic = (ActiveMQTopic) createDestination(); - startBroker(); + public static void exit(String message) { + exit(message, null); + } - clientManager = new ClientManager(); - server = new Server(); - houseKeeper = new HouseKeeper(); + public static void exit(String message, Throwable e) { + Throwable log = new RuntimeException(message, e); + log.printStackTrace(); + LOG.error(message, e); + exceptions.add(e); + fail(message); + } - super.setUp(); - } + protected void setUp() throws Exception { + topic = (ActiveMQTopic) createDestination(); + startBroker(); - protected void tearDown() throws Exception { - super.tearDown(); + clientManager = new ClientManager(); + server = new Server(); + houseKeeper = new HouseKeeper(); - destroyBroker(); - } + super.setUp(); + } - private void startBroker() throws Exception { - startBroker(true); - } + protected void tearDown() throws Exception { + super.tearDown(); - private void startBroker(boolean deleteAllMessages) throws Exception { - if (broker != null) - return; + destroyBroker(); + } - broker = BrokerFactory.createBroker("broker:(vm://localhost)"); - broker.setBrokerName(getName()); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); + private void startBroker() throws Exception { + startBroker(true); + } - if (PERSISTENT_BROKER) { - broker.setPersistent(true); - KahaDBPersistenceAdapter persistenceAdapter = new KahaDBPersistenceAdapter(); - persistenceAdapter.setDirectory(new File("activemq-data/" + getName())); - broker.setPersistenceAdapter(persistenceAdapter); - } - else - broker.setPersistent(false); + private void startBroker(boolean deleteAllMessages) throws Exception { + if (broker != null) + return; - broker.addConnector("tcp://localhost:61656"); + broker = BrokerFactory.createBroker("broker:(vm://localhost)"); + broker.setBrokerName(getName()); + broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - broker.getSystemUsage().getMemoryUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getTempUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getStoreUsage().setLimit(256 * 1024 * 1024); + if (PERSISTENT_BROKER) { + broker.setPersistent(true); + KahaDBPersistenceAdapter persistenceAdapter = new KahaDBPersistenceAdapter(); + persistenceAdapter.setDirectory(new File("activemq-data/" + getName())); + broker.setPersistenceAdapter(persistenceAdapter); + } + else + broker.setPersistent(false); - broker.start(); - } + broker.addConnector("tcp://localhost:61656"); - private void destroyBroker() throws Exception { - if (broker == null) - return; + broker.getSystemUsage().getMemoryUsage().setLimit(256 * 1024 * 1024); + broker.getSystemUsage().getTempUsage().setLimit(256 * 1024 * 1024); + broker.getSystemUsage().getStoreUsage().setLimit(256 * 1024 * 1024); - broker.stop(); - broker = null; - } + broker.start(); + } + + private void destroyBroker() throws Exception { + if (broker == null) + return; + + broker.stop(); + broker = null; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessWithRestartTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessWithRestartTest.java index c190952c15..e4118ec56e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessWithRestartTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessWithRestartTest.java @@ -52,731 +52,693 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DurableSubProcessWithRestartTest { - private static final Logger LOG = LoggerFactory.getLogger(DurableSubProcessWithRestartTest.class); - public static final long RUNTIME = 5 * 60 * 1000; - public static final int SERVER_SLEEP = 2 * 1000; // max - public static final int CARGO_SIZE = 400; // max + private static final Logger LOG = LoggerFactory.getLogger(DurableSubProcessWithRestartTest.class); + public static final long RUNTIME = 5 * 60 * 1000; - public static final int MAX_CLIENTS = 5; - public static final Random CLIENT_LIFETIME = new Random(5 * 1000, - 2 * 5 * 1000); - public static final Random CLIENT_ONLINE = new Random(2 * 1000, 2 * 1000); - public static final Random CLIENT_OFFLINE = new Random(10 * 1000, 10 * 1000); + public static final int SERVER_SLEEP = 2 * 1000; // max + public static final int CARGO_SIZE = 400; // max - public static final Persistence PERSISTENT_ADAPTER = Persistence.KAHADB; - public static final long BROKER_RESTART = 1 * 10 * 1000; + public static final int MAX_CLIENTS = 5; + public static final Random CLIENT_LIFETIME = new Random(5 * 1000, 2 * 5 * 1000); + public static final Random CLIENT_ONLINE = new Random(2 * 1000, 2 * 1000); + public static final Random CLIENT_OFFLINE = new Random(10 * 1000, 10 * 1000); - public static final boolean ALLOW_SUBSCRIPTION_ABANDONMENT = true; - public static final boolean CHECK_REDELIVERY = true; + public static final Persistence PERSISTENT_ADAPTER = Persistence.KAHADB; + public static final long BROKER_RESTART = 1 * 10 * 1000; - private BrokerService broker; - private ActiveMQTopic topic; + public static final boolean ALLOW_SUBSCRIPTION_ABANDONMENT = true; + public static final boolean CHECK_REDELIVERY = true; - private ClientManager clientManager; - private Server server; - private HouseKeeper houseKeeper; + private BrokerService broker; + private ActiveMQTopic topic; - private final ReentrantReadWriteLock processLock = new ReentrantReadWriteLock( - true); - private int restartCount = 0; - static final Vector exceptions = new Vector(); + private ClientManager clientManager; + private Server server; + private HouseKeeper houseKeeper; - // this is a nice test but it takes 5mins, may be handy in the future - // resulting bug https://issues.apache.org/jira/browse/AMQ-3190 - @Ignore("covered by org.apache.activemq.usecases.DurableSubscriptionOfflineTest.testNoMissOnMatchingSubAfterRestart()") @Test - public void testProcess() { - try { - server.start(); - clientManager.start(); + private final ReentrantReadWriteLock processLock = new ReentrantReadWriteLock(true); + private int restartCount = 0; + static final Vector exceptions = new Vector(); - if (ALLOW_SUBSCRIPTION_ABANDONMENT) - houseKeeper.start(); + // this is a nice test but it takes 5mins, may be handy in the future + // resulting bug https://issues.apache.org/jira/browse/AMQ-3190 + @Ignore("covered by org.apache.activemq.usecases.DurableSubscriptionOfflineTest.testNoMissOnMatchingSubAfterRestart()") + @Test + public void testProcess() { + try { + server.start(); + clientManager.start(); - long end = System.currentTimeMillis() + RUNTIME; + if (ALLOW_SUBSCRIPTION_ABANDONMENT) + houseKeeper.start(); + long end = System.currentTimeMillis() + RUNTIME; + + while (true) { + long now = System.currentTimeMillis(); + if (now > end) + break; + + now = end - now; + now = now < BROKER_RESTART ? now : BROKER_RESTART; + Thread.sleep(now); + + restartBroker(); + } + } + catch (Throwable e) { + exit("ProcessTest.testProcess failed.", e); + } + + processLock.writeLock().lock(); + assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); + LOG.info("DONE."); + } + + private void restartBroker() throws Exception { + LOG.info("Broker restart: waiting for components."); + + processLock.writeLock().lock(); + try { + destroyBroker(); + startBroker(false); + + restartCount++; + LOG.info("Broker restarted. count: " + restartCount); + } + finally { + processLock.writeLock().unlock(); + } + } + + /** + * Creates batch of messages in a transaction periodically. The last message + * in the transaction is always a special message what contains info about + * the whole transaction. + *

    + * Notifies the clients about the created messages also. + */ + final class Server extends Thread { + + final String url = "vm://" + DurableSubProcessWithRestartTest.getName() + "?" + "jms.redeliveryPolicy.maximumRedeliveries=2&jms.redeliveryPolicy.initialRedeliveryDelay=500&" + "jms.producerWindowSize=20971520&jms.prefetchPolicy.all=100&" + "jms.copyMessageOnSend=false&jms.disableTimeStampsByDefault=false&" + "jms.alwaysSyncSend=true&jms.dispatchAsync=false&" + "jms.watchTopicAdvisories=false&" + "waitForStart=200&create=false"; + final ConnectionFactory cf = new ActiveMQConnectionFactory(url); + + final Object sendMutex = new Object(); + final String[] cargos = new String[500]; + + int transRover = 0; + int messageRover = 0; + + public Server() { + super("Server"); + setDaemon(true); + } + + @Override + public void run() { + try { while (true) { - long now = System.currentTimeMillis(); - if (now > end) - break; + DurableSubProcessWithRestartTest.sleepRandom(SERVER_SLEEP); - now = end - now; - now = now < BROKER_RESTART ? now : BROKER_RESTART; - Thread.sleep(now); - - restartBroker(); + processLock.readLock().lock(); + try { + send(); + } + finally { + processLock.readLock().unlock(); + } } - } catch (Throwable e) { - exit("ProcessTest.testProcess failed.", e); - } + } + catch (Throwable e) { + exit("Server.run failed", e); + } + } + + public void send() throws JMSException { + // do not create new clients now + // ToDo: Test this case later. + synchronized (sendMutex) { + int trans = ++transRover; + boolean relevantTrans = random(2) > 1; + ClientType clientType = relevantTrans ? ClientType.randomClientType() : null; // sends this types + int count = random(200); + + LOG.info("Sending Trans[id=" + trans + ", count=" + count + ", clientType=" + clientType + "]"); - processLock.writeLock().lock(); - assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); - LOG.info("DONE."); - } - - private void restartBroker() throws Exception { - LOG.info("Broker restart: waiting for components."); - - processLock.writeLock().lock(); - try { - destroyBroker(); - startBroker(false); - - restartCount++; - LOG.info("Broker restarted. count: " + restartCount); - } finally { - processLock.writeLock().unlock(); - } - } - - /** - * Creates batch of messages in a transaction periodically. The last message - * in the transaction is always a special message what contains info about - * the whole transaction. - *

    - * Notifies the clients about the created messages also. - */ - final class Server extends Thread { - - final String url = "vm://" - + DurableSubProcessWithRestartTest.getName() - + "?" - + "jms.redeliveryPolicy.maximumRedeliveries=2&jms.redeliveryPolicy.initialRedeliveryDelay=500&" - + "jms.producerWindowSize=20971520&jms.prefetchPolicy.all=100&" - + "jms.copyMessageOnSend=false&jms.disableTimeStampsByDefault=false&" - + "jms.alwaysSyncSend=true&jms.dispatchAsync=false&" - + "jms.watchTopicAdvisories=false&" - + "waitForStart=200&create=false"; - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); - - final Object sendMutex = new Object(); - final String[] cargos = new String[500]; - - int transRover = 0; - int messageRover = 0; - - public Server() { - super("Server"); - setDaemon(true); - } - - @Override - public void run() { - try { - while (true) { - DurableSubProcessWithRestartTest.sleepRandom(SERVER_SLEEP); - - processLock.readLock().lock(); - try { - send(); - } finally { - processLock.readLock().unlock(); - } - } - } catch (Throwable e) { - exit("Server.run failed", e); - } - } - - public void send() throws JMSException { - // do not create new clients now - // ToDo: Test this case later. - synchronized (sendMutex) { - int trans = ++transRover; - boolean relevantTrans = random(2) > 1; - ClientType clientType = relevantTrans ? ClientType - .randomClientType() : null; // sends this types - int count = random(200); - - LOG.info("Sending Trans[id=" + trans + ", count=" - + count + ", clientType=" + clientType + "]"); - - Connection con = cf.createConnection(); - Session sess = con - .createSession(true, Session.SESSION_TRANSACTED); - MessageProducer prod = sess.createProducer(null); - - for (int i = 0; i < count; i++) { - Message message = sess.createMessage(); - message.setIntProperty("ID", ++messageRover); - message.setIntProperty("TRANS", trans); - String type = clientType != null ? clientType - .randomMessageType() : ClientType - .randomNonRelevantMessageType(); - message.setStringProperty("TYPE", type); - - if (CARGO_SIZE > 0) - message.setStringProperty("CARGO", - getCargo(random(CARGO_SIZE))); - - prod.send(topic, message); - clientManager.onServerMessage(message); - } - - Message message = sess.createMessage(); - message.setIntProperty("ID", ++messageRover); - message.setIntProperty("TRANS", trans); - message.setBooleanProperty("COMMIT", true); - message.setBooleanProperty("RELEVANT", relevantTrans); - prod.send(topic, message); - clientManager.onServerMessage(message); - - sess.commit(); - LOG.info("Committed Trans[id=" + trans + ", count=" - + count + ", clientType=" + clientType + "], ID=" + messageRover); - - sess.close(); - con.close(); - } - } - - private String getCargo(int length) { - if (length == 0) - return null; - - if (length < cargos.length) { - String result = cargos[length]; - if (result == null) { - result = getCargoImpl(length); - cargos[length] = result; - } - return result; - } - return getCargoImpl(length); - } - - private String getCargoImpl(int length) { - StringBuilder sb = new StringBuilder(length); - for (int i = length; --i >= 0;) { - sb.append('a'); - } - return sb.toString(); - } - } - - /** - * Clients listen on different messages in the topic. The 'TYPE' property - * helps the client to select the proper messages. - */ - private enum ClientType { - A("a", "b", "c"), B("c", "d", "e"), C("d", "e", "f"), D("g", "h"); - - public final String[] messageTypes; - public final HashSet messageTypeSet; - public final String selector; - - ClientType(String... messageTypes) { - this.messageTypes = messageTypes; - messageTypeSet = new HashSet(Arrays.asList(messageTypes)); - - StringBuilder sb = new StringBuilder("TYPE in ("); - for (int i = 0; i < messageTypes.length; i++) { - if (i > 0) - sb.append(", "); - sb.append('\'').append(messageTypes[i]).append('\''); - } - sb.append(')'); - selector = sb.toString(); - } - - public static ClientType randomClientType() { - return values()[DurableSubProcessWithRestartTest - .random(values().length - 1)]; - } - - public final String randomMessageType() { - return messageTypes[DurableSubProcessWithRestartTest - .random(messageTypes.length - 1)]; - } - - public static String randomNonRelevantMessageType() { - return Integer - .toString(DurableSubProcessWithRestartTest.random(20)); - } - - public final boolean isRelevant(String messageType) { - return messageTypeSet.contains(messageType); - } - - @Override - public final String toString() { - return this.name() /* + '[' + selector + ']' */; - } - } - - /** - * Creates new cliens. - */ - private final class ClientManager extends Thread { - - private int clientRover = 0; - - private final CopyOnWriteArrayList clients = new CopyOnWriteArrayList(); - - public ClientManager() { - super("ClientManager"); - setDaemon(true); - } - - @Override - public void run() { - try { - while (true) { - if (clients.size() < MAX_CLIENTS) { - processLock.readLock().lock(); - try { - createNewClient(); - } finally { - processLock.readLock().unlock(); - } - } - - int size = clients.size(); - sleepRandom(size * 3 * 1000, size * 6 * 1000); - } - } catch (Throwable e) { - exit("ClientManager.run failed.", e); - } - } - - private void createNewClient() throws JMSException { - ClientType type = ClientType.randomClientType(); - - Client client; - synchronized (server.sendMutex) { - client = new Client(++clientRover, type, CLIENT_LIFETIME, - CLIENT_ONLINE, CLIENT_OFFLINE); - clients.add(client); - } - client.start(); - - LOG.info(client.toString() + " created. " + this); - } - - public void removeClient(Client client) { - clients.remove(client); - } - - public void onServerMessage(Message message) throws JMSException { - for (Client client : clients) { - client.onServerMessage(message); - } - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("ClientManager[count="); - sb.append(clients.size()); - sb.append(", clients="); - boolean sep = false; - for (Client client : clients) { - if (sep) - sb.append(", "); - else - sep = true; - sb.append(client.toString()); - } - sb.append(']'); - return sb.toString(); - } - } - - /** - * Consumes massages from a durable subscription. Goes online/offline - * periodically. Checks the incoming messages against the sent messages of - * the server. - */ - private final class Client extends Thread { - - String url = "failover:(tcp://localhost:61656?wireFormat.maxInactivityDuration=0)?" - + "jms.watchTopicAdvisories=false&" - + "jms.alwaysSyncSend=true&jms.dispatchAsync=true&" - + "jms.producerWindowSize=20971520&" - + "jms.copyMessageOnSend=false&" - + "initialReconnectDelay=100&maxReconnectDelay=30000&" - + "useExponentialBackOff=true"; - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); - - public static final String SUBSCRIPTION_NAME = "subscription"; - - private final int id; - private final String conClientId; - - private final Random lifetime; - private final Random online; - private final Random offline; - - private final ClientType clientType; - private final String selector; - - private final ConcurrentLinkedQueue waitingList = new ConcurrentLinkedQueue(); - private final HashSet processed = CHECK_REDELIVERY ? new HashSet( - 10000) : null; - - public Client(int id, ClientType clientType, Random lifetime, - Random online, Random offline) throws JMSException { - super("Client" + id); - setDaemon(true); - - this.id = id; - conClientId = "cli" + id; - this.clientType = clientType; - selector = "(COMMIT = true and RELEVANT = true) or " - + clientType.selector; - - this.lifetime = lifetime; - this.online = online; - this.offline = offline; - - subscribe(); - } - - @Override - public void run() { - long end = System.currentTimeMillis() + lifetime.next(); - try { - boolean sleep = false; - while (true) { - long max = end - System.currentTimeMillis(); - if (max <= 0) - break; - - if (sleep) - offline.sleepRandom(); - else - sleep = true; - - processLock.readLock().lock(); - try { - process(online.next()); - } finally { - processLock.readLock().unlock(); - } - } - - if (!ALLOW_SUBSCRIPTION_ABANDONMENT || random(1) > 0) - unsubscribe(); - else { - LOG.info("Client abandon the subscription. " - + this); - - // housekeeper should sweep these abandoned subscriptions - houseKeeper.abandonedSubscriptions.add(conClientId); - } - } catch (Throwable e) { - exit(toString() + " failed.", e); - } - - clientManager.removeClient(this); - LOG.info(toString() + " DONE."); - } - - private void process(long millis) throws JMSException { - long end = System.currentTimeMillis() + millis; - long hardEnd = end + 20000; // wait to finish the transaction. - boolean inTransaction = false; - int transCount = 0; - - LOG.info(toString() + " ONLINE."); - Connection con = openConnection(); - Session sess = con.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = sess.createDurableSubscriber(topic, - SUBSCRIPTION_NAME, selector, false); - try { - do { - long max = end - System.currentTimeMillis(); - if (max <= 0) { - if (!inTransaction) - break; - - max = hardEnd - System.currentTimeMillis(); - if (max <= 0) - exit("" + this - + " failed: Transaction is not finished."); - } - - Message message = consumer.receive(max); - if (message == null) - continue; - - onClientMessage(message); - - if (message.propertyExists("COMMIT")) { - message.acknowledge(); // CLIENT_ACKNOWLEDGE - - LOG.info("Received Trans[id=" - + message.getIntProperty("TRANS") + ", count=" - + transCount + "] in " + this + "."); - - inTransaction = false; - transCount = 0; - } else { - inTransaction = true; - transCount++; - } - } while (true); - } finally { - sess.close(); - con.close(); - - LOG.info(toString() + " OFFLINE."); - - // Check if the messages are in the waiting - // list for long time. - Message topMessage = waitingList.peek(); - if (topMessage != null) - checkDeliveryTime(topMessage); - } - } - - public void onServerMessage(Message message) throws JMSException { - if (Boolean.TRUE.equals(message.getObjectProperty("COMMIT"))) { - if (Boolean.TRUE.equals(message.getObjectProperty("RELEVANT"))) - waitingList.add(message); - } else { - String messageType = message.getStringProperty("TYPE"); - if (clientType.isRelevant(messageType)) - waitingList.add(message); - } - } - - public void onClientMessage(Message message) { - Message serverMessage = waitingList.poll(); - try { - Integer receivedId = (Integer) message.getObjectProperty("ID"); - if (processed != null && processed.contains(receivedId)) - LOG.info("! Message has been processed before. " - + this + " message = " + message); - - if (serverMessage == null) - exit("" - + this - + " failed: There is no next server message, but received: " - + message); - - Integer serverId = (Integer) serverMessage - .getObjectProperty("ID"); - if (receivedId == null || serverId == null) - exit("" + this + " failed: message ID not found.\r\n" - + " received: " + message + "\r\n" + " server: " - + serverMessage); - - if (!serverId.equals(receivedId)) { - String detail = processed != null ? - Arrays.toString(processed.toArray()) + "\n" - : ""; - exit(detail + this + " failed: Received wrong message.\r\n" - + " received: " + message + "\r\n" + " server: " - + serverMessage); - } - - checkDeliveryTime(message); - - if (processed != null) - processed.add(receivedId); - } catch (Throwable e) { - exit("" + this + ".onClientMessage failed.\r\n" + " received: " - + message + "\r\n" + " server: " + serverMessage, e); - } - } - - /** - * Checks if the message was not delivered fast enough. - */ - @SuppressWarnings("unused") - public void checkDeliveryTime(Message message) throws JMSException { - long creation = message.getJMSTimestamp(); - long min = System.currentTimeMillis() - (offline.max + online.min) - * (BROKER_RESTART > 0 ? 4 : 1); - - if (false && min > creation) { - SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss.SSS"); - exit("" + this + ".checkDeliveryTime failed. Message time: " - + df.format(new Date(creation)) + ", min: " - + df.format(new Date(min)) + "\r\n" + message); - } - } - - private Connection openConnection() throws JMSException { Connection con = cf.createConnection(); - con.setClientID(conClientId); - con.start(); - return con; - } + Session sess = con.createSession(true, Session.SESSION_TRANSACTED); + MessageProducer prod = sess.createProducer(null); - private void subscribe() throws JMSException { - Connection con = openConnection(); - Session session = con - .createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, SUBSCRIPTION_NAME, selector, - true); - session.close(); + for (int i = 0; i < count; i++) { + Message message = sess.createMessage(); + message.setIntProperty("ID", ++messageRover); + message.setIntProperty("TRANS", trans); + String type = clientType != null ? clientType.randomMessageType() : ClientType.randomNonRelevantMessageType(); + message.setStringProperty("TYPE", type); + + if (CARGO_SIZE > 0) + message.setStringProperty("CARGO", getCargo(random(CARGO_SIZE))); + + prod.send(topic, message); + clientManager.onServerMessage(message); + } + + Message message = sess.createMessage(); + message.setIntProperty("ID", ++messageRover); + message.setIntProperty("TRANS", trans); + message.setBooleanProperty("COMMIT", true); + message.setBooleanProperty("RELEVANT", relevantTrans); + prod.send(topic, message); + clientManager.onServerMessage(message); + + sess.commit(); + LOG.info("Committed Trans[id=" + trans + ", count=" + count + ", clientType=" + clientType + "], ID=" + messageRover); + + sess.close(); con.close(); - } + } + } - private void unsubscribe() throws JMSException { - Connection con = openConnection(); - Session session = con - .createSession(false, Session.AUTO_ACKNOWLEDGE); - session.unsubscribe(SUBSCRIPTION_NAME); - session.close(); - con.close(); - } + private String getCargo(int length) { + if (length == 0) + return null; - @Override - public String toString() { - return "Client[id=" + id + ", type=" + clientType + "]"; - } - } + if (length < cargos.length) { + String result = cargos[length]; + if (result == null) { + result = getCargoImpl(length); + cargos[length] = result; + } + return result; + } + return getCargoImpl(length); + } - /** - * Sweeps out not-used durable subscriptions. - */ - private final class HouseKeeper extends Thread { + private String getCargoImpl(int length) { + StringBuilder sb = new StringBuilder(length); + for (int i = length; --i >= 0; ) { + sb.append('a'); + } + return sb.toString(); + } + } - private HouseKeeper() { - super("HouseKeeper"); - setDaemon(true); - } + /** + * Clients listen on different messages in the topic. The 'TYPE' property + * helps the client to select the proper messages. + */ + private enum ClientType { + A("a", "b", "c"), B("c", "d", "e"), C("d", "e", "f"), D("g", "h"); - public final CopyOnWriteArrayList abandonedSubscriptions = new CopyOnWriteArrayList(); + public final String[] messageTypes; + public final HashSet messageTypeSet; + public final String selector; - @Override - public void run() { + ClientType(String... messageTypes) { + this.messageTypes = messageTypes; + messageTypeSet = new HashSet(Arrays.asList(messageTypes)); + + StringBuilder sb = new StringBuilder("TYPE in ("); + for (int i = 0; i < messageTypes.length; i++) { + if (i > 0) + sb.append(", "); + sb.append('\'').append(messageTypes[i]).append('\''); + } + sb.append(')'); + selector = sb.toString(); + } + + public static ClientType randomClientType() { + return values()[DurableSubProcessWithRestartTest.random(values().length - 1)]; + } + + public final String randomMessageType() { + return messageTypes[DurableSubProcessWithRestartTest.random(messageTypes.length - 1)]; + } + + public static String randomNonRelevantMessageType() { + return Integer.toString(DurableSubProcessWithRestartTest.random(20)); + } + + public final boolean isRelevant(String messageType) { + return messageTypeSet.contains(messageType); + } + + @Override + public final String toString() { + return this.name() /* + '[' + selector + ']' */; + } + } + + /** + * Creates new cliens. + */ + private final class ClientManager extends Thread { + + private int clientRover = 0; + + private final CopyOnWriteArrayList clients = new CopyOnWriteArrayList(); + + public ClientManager() { + super("ClientManager"); + setDaemon(true); + } + + @Override + public void run() { + try { while (true) { - try { - Thread.sleep(3 * 60 * 1000); + if (clients.size() < MAX_CLIENTS) { + processLock.readLock().lock(); + try { + createNewClient(); + } + finally { + processLock.readLock().unlock(); + } + } - processLock.readLock().lock(); - try { - sweep(); - } finally { - processLock.readLock().unlock(); - } - } catch (InterruptedException ex) { - break; - } catch (Throwable e) { - Exception log = new Exception("HouseKeeper failed.", e); - log.printStackTrace(); - } + int size = clients.size(); + sleepRandom(size * 3 * 1000, size * 6 * 1000); } - } + } + catch (Throwable e) { + exit("ClientManager.run failed.", e); + } + } - private void sweep() throws Exception { - LOG.info("Housekeeper sweeping."); + private void createNewClient() throws JMSException { + ClientType type = ClientType.randomClientType(); - int closed = 0; - ArrayList sweeped = new ArrayList(); + Client client; + synchronized (server.sendMutex) { + client = new Client(++clientRover, type, CLIENT_LIFETIME, CLIENT_ONLINE, CLIENT_OFFLINE); + clients.add(client); + } + client.start(); + + LOG.info(client.toString() + " created. " + this); + } + + public void removeClient(Client client) { + clients.remove(client); + } + + public void onServerMessage(Message message) throws JMSException { + for (Client client : clients) { + client.onServerMessage(message); + } + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("ClientManager[count="); + sb.append(clients.size()); + sb.append(", clients="); + boolean sep = false; + for (Client client : clients) { + if (sep) + sb.append(", "); + else + sep = true; + sb.append(client.toString()); + } + sb.append(']'); + return sb.toString(); + } + } + + /** + * Consumes massages from a durable subscription. Goes online/offline + * periodically. Checks the incoming messages against the sent messages of + * the server. + */ + private final class Client extends Thread { + + String url = "failover:(tcp://localhost:61656?wireFormat.maxInactivityDuration=0)?" + "jms.watchTopicAdvisories=false&" + "jms.alwaysSyncSend=true&jms.dispatchAsync=true&" + "jms.producerWindowSize=20971520&" + "jms.copyMessageOnSend=false&" + "initialReconnectDelay=100&maxReconnectDelay=30000&" + "useExponentialBackOff=true"; + final ConnectionFactory cf = new ActiveMQConnectionFactory(url); + + public static final String SUBSCRIPTION_NAME = "subscription"; + + private final int id; + private final String conClientId; + + private final Random lifetime; + private final Random online; + private final Random offline; + + private final ClientType clientType; + private final String selector; + + private final ConcurrentLinkedQueue waitingList = new ConcurrentLinkedQueue(); + private final HashSet processed = CHECK_REDELIVERY ? new HashSet(10000) : null; + + public Client(int id, ClientType clientType, Random lifetime, Random online, Random offline) throws JMSException { + super("Client" + id); + setDaemon(true); + + this.id = id; + conClientId = "cli" + id; + this.clientType = clientType; + selector = "(COMMIT = true and RELEVANT = true) or " + clientType.selector; + + this.lifetime = lifetime; + this.online = online; + this.offline = offline; + + subscribe(); + } + + @Override + public void run() { + long end = System.currentTimeMillis() + lifetime.next(); + try { + boolean sleep = false; + while (true) { + long max = end - System.currentTimeMillis(); + if (max <= 0) + break; + + if (sleep) + offline.sleepRandom(); + else + sleep = true; + + processLock.readLock().lock(); + try { + process(online.next()); + } + finally { + processLock.readLock().unlock(); + } + } + + if (!ALLOW_SUBSCRIPTION_ABANDONMENT || random(1) > 0) + unsubscribe(); + else { + LOG.info("Client abandon the subscription. " + this); + + // housekeeper should sweep these abandoned subscriptions + houseKeeper.abandonedSubscriptions.add(conClientId); + } + } + catch (Throwable e) { + exit(toString() + " failed.", e); + } + + clientManager.removeClient(this); + LOG.info(toString() + " DONE."); + } + + private void process(long millis) throws JMSException { + long end = System.currentTimeMillis() + millis; + long hardEnd = end + 20000; // wait to finish the transaction. + boolean inTransaction = false; + int transCount = 0; + + LOG.info(toString() + " ONLINE."); + Connection con = openConnection(); + Session sess = con.createSession(false, Session.CLIENT_ACKNOWLEDGE); + MessageConsumer consumer = sess.createDurableSubscriber(topic, SUBSCRIPTION_NAME, selector, false); + try { + do { + long max = end - System.currentTimeMillis(); + if (max <= 0) { + if (!inTransaction) + break; + + max = hardEnd - System.currentTimeMillis(); + if (max <= 0) + exit("" + this + " failed: Transaction is not finished."); + } + + Message message = consumer.receive(max); + if (message == null) + continue; + + onClientMessage(message); + + if (message.propertyExists("COMMIT")) { + message.acknowledge(); // CLIENT_ACKNOWLEDGE + + LOG.info("Received Trans[id=" + message.getIntProperty("TRANS") + ", count=" + transCount + "] in " + this + "."); + + inTransaction = false; + transCount = 0; + } + else { + inTransaction = true; + transCount++; + } + } while (true); + } + finally { + sess.close(); + con.close(); + + LOG.info(toString() + " OFFLINE."); + + // Check if the messages are in the waiting + // list for long time. + Message topMessage = waitingList.peek(); + if (topMessage != null) + checkDeliveryTime(topMessage); + } + } + + public void onServerMessage(Message message) throws JMSException { + if (Boolean.TRUE.equals(message.getObjectProperty("COMMIT"))) { + if (Boolean.TRUE.equals(message.getObjectProperty("RELEVANT"))) + waitingList.add(message); + } + else { + String messageType = message.getStringProperty("TYPE"); + if (clientType.isRelevant(messageType)) + waitingList.add(message); + } + } + + public void onClientMessage(Message message) { + Message serverMessage = waitingList.poll(); + try { + Integer receivedId = (Integer) message.getObjectProperty("ID"); + if (processed != null && processed.contains(receivedId)) + LOG.info("! Message has been processed before. " + this + " message = " + message); + + if (serverMessage == null) + exit("" + this + " failed: There is no next server message, but received: " + message); + + Integer serverId = (Integer) serverMessage.getObjectProperty("ID"); + if (receivedId == null || serverId == null) + exit("" + this + " failed: message ID not found.\r\n" + " received: " + message + "\r\n" + " server: " + serverMessage); + + if (!serverId.equals(receivedId)) { + String detail = processed != null ? Arrays.toString(processed.toArray()) + "\n" : ""; + exit(detail + this + " failed: Received wrong message.\r\n" + " received: " + message + "\r\n" + " server: " + serverMessage); + } + + checkDeliveryTime(message); + + if (processed != null) + processed.add(receivedId); + } + catch (Throwable e) { + exit("" + this + ".onClientMessage failed.\r\n" + " received: " + message + "\r\n" + " server: " + serverMessage, e); + } + } + + /** + * Checks if the message was not delivered fast enough. + */ + @SuppressWarnings("unused") + public void checkDeliveryTime(Message message) throws JMSException { + long creation = message.getJMSTimestamp(); + long min = System.currentTimeMillis() - (offline.max + online.min) * (BROKER_RESTART > 0 ? 4 : 1); + + if (false && min > creation) { + SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss.SSS"); + exit("" + this + ".checkDeliveryTime failed. Message time: " + df.format(new Date(creation)) + ", min: " + df.format(new Date(min)) + "\r\n" + message); + } + } + + private Connection openConnection() throws JMSException { + Connection con = cf.createConnection(); + con.setClientID(conClientId); + con.start(); + return con; + } + + private void subscribe() throws JMSException { + Connection con = openConnection(); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, SUBSCRIPTION_NAME, selector, true); + session.close(); + con.close(); + } + + private void unsubscribe() throws JMSException { + Connection con = openConnection(); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.unsubscribe(SUBSCRIPTION_NAME); + session.close(); + con.close(); + } + + @Override + public String toString() { + return "Client[id=" + id + ", type=" + clientType + "]"; + } + } + + /** + * Sweeps out not-used durable subscriptions. + */ + private final class HouseKeeper extends Thread { + + private HouseKeeper() { + super("HouseKeeper"); + setDaemon(true); + } + + public final CopyOnWriteArrayList abandonedSubscriptions = new CopyOnWriteArrayList(); + + @Override + public void run() { + while (true) { try { - for (String clientId : abandonedSubscriptions) { - LOG.info("Sweeping out subscription of " - + clientId + "."); - broker.getAdminView().destroyDurableSubscriber(clientId, - Client.SUBSCRIPTION_NAME); - sweeped.add(clientId); - closed++; - } - } catch (Exception ignored) { - LOG.info("Ex on destroy sub " + ignored); - } finally { - abandonedSubscriptions.removeAll(sweeped); + Thread.sleep(3 * 60 * 1000); + + processLock.readLock().lock(); + try { + sweep(); + } + finally { + processLock.readLock().unlock(); + } } + catch (InterruptedException ex) { + break; + } + catch (Throwable e) { + Exception log = new Exception("HouseKeeper failed.", e); + log.printStackTrace(); + } + } + } - LOG.info("Housekeeper sweeped out " + closed - + " subscriptions."); - } - } + private void sweep() throws Exception { + LOG.info("Housekeeper sweeping."); - public static int random(int max) { - return (int) (Math.random() * (max + 1)); - } + int closed = 0; + ArrayList sweeped = new ArrayList(); + try { + for (String clientId : abandonedSubscriptions) { + LOG.info("Sweeping out subscription of " + clientId + "."); + broker.getAdminView().destroyDurableSubscriber(clientId, Client.SUBSCRIPTION_NAME); + sweeped.add(clientId); + closed++; + } + } + catch (Exception ignored) { + LOG.info("Ex on destroy sub " + ignored); + } + finally { + abandonedSubscriptions.removeAll(sweeped); + } - public static int random(int min, int max) { - return random(max - min) + min; - } + LOG.info("Housekeeper sweeped out " + closed + " subscriptions."); + } + } - public static void sleepRandom(int maxMillis) throws InterruptedException { - Thread.sleep(random(maxMillis)); - } + public static int random(int max) { + return (int) (Math.random() * (max + 1)); + } - public static void sleepRandom(int minMillis, int maxMillis) - throws InterruptedException { - Thread.sleep(random(minMillis, maxMillis)); - } + public static int random(int min, int max) { + return random(max - min) + min; + } - public static final class Random { + public static void sleepRandom(int maxMillis) throws InterruptedException { + Thread.sleep(random(maxMillis)); + } - final int min; - final int max; + public static void sleepRandom(int minMillis, int maxMillis) throws InterruptedException { + Thread.sleep(random(minMillis, maxMillis)); + } - Random(int min, int max) { - this.min = min; - this.max = max; - } + public static final class Random { - public int next() { - return random(min, max); - } + final int min; + final int max; - public void sleepRandom() throws InterruptedException { - DurableSubProcessWithRestartTest.sleepRandom(min, max); - } - } + Random(int min, int max) { + this.min = min; + this.max = max; + } - public static void exit(String message) { - exit(message, null); - } + public int next() { + return random(min, max); + } - public static void exit(String message, Throwable e) { - Throwable cause = new RuntimeException(message, e); - LOG.error(message, cause); - exceptions.add(cause); - fail(cause.toString()); - } + public void sleepRandom() throws InterruptedException { + DurableSubProcessWithRestartTest.sleepRandom(min, max); + } + } - @Before - public void setUp() throws Exception { - topic = new ActiveMQTopic("TopicT"); - startBroker(); + public static void exit(String message) { + exit(message, null); + } - clientManager = new ClientManager(); - server = new Server(); - houseKeeper = new HouseKeeper(); + public static void exit(String message, Throwable e) { + Throwable cause = new RuntimeException(message, e); + LOG.error(message, cause); + exceptions.add(cause); + fail(cause.toString()); + } - } + @Before + public void setUp() throws Exception { + topic = new ActiveMQTopic("TopicT"); + startBroker(); - @After - public void tearDown() throws Exception { - destroyBroker(); - } + clientManager = new ClientManager(); + server = new Server(); + houseKeeper = new HouseKeeper(); - private enum Persistence { - MEMORY, LEVELDB, KAHADB - } + } - private void startBroker() throws Exception { - startBroker(true); - } + @After + public void tearDown() throws Exception { + destroyBroker(); + } - private void startBroker(boolean deleteAllMessages) throws Exception { - if (broker != null) - return; + private enum Persistence { + MEMORY, LEVELDB, KAHADB + } - broker = BrokerFactory.createBroker("broker:(vm://" + getName() + ")"); - broker.setBrokerName(getName()); - broker.setAdvisorySupport(false); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); + private void startBroker() throws Exception { + startBroker(true); + } - switch (PERSISTENT_ADAPTER) { - case MEMORY: + private void startBroker(boolean deleteAllMessages) throws Exception { + if (broker != null) + return; + + broker = BrokerFactory.createBroker("broker:(vm://" + getName() + ")"); + broker.setBrokerName(getName()); + broker.setAdvisorySupport(false); + broker.setDeleteAllMessagesOnStartup(deleteAllMessages); + + switch (PERSISTENT_ADAPTER) { + case MEMORY: broker.setPersistent(false); break; - case LEVELDB: + case LEVELDB: File datadir = new File("activemq-data/" + getName() + "-leveldb"); if (deleteAllMessages) - delete(datadir); + delete(datadir); broker.setPersistent(true); LevelDBStore amq = new LevelDBStore(); @@ -784,10 +746,10 @@ public class DurableSubProcessWithRestartTest { broker.setPersistenceAdapter(amq); break; - case KAHADB: + case KAHADB: File kahadbData = new File("activemq-data/" + getName() + "-kahadb"); if (deleteAllMessages) - delete(kahadbData); + delete(kahadbData); broker.setPersistent(true); KahaDBPersistenceAdapter kahadb = new KahaDBPersistenceAdapter(); @@ -795,38 +757,38 @@ public class DurableSubProcessWithRestartTest { kahadb.setJournalMaxFileLength(5 * 1024 * 1024); broker.setPersistenceAdapter(kahadb); break; - } + } - broker.addConnector("tcp://localhost:61656"); + broker.addConnector("tcp://localhost:61656"); - broker.getSystemUsage().getMemoryUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getTempUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getStoreUsage().setLimit(256 * 1024 * 1024); + broker.getSystemUsage().getMemoryUsage().setLimit(256 * 1024 * 1024); + broker.getSystemUsage().getTempUsage().setLimit(256 * 1024 * 1024); + broker.getSystemUsage().getStoreUsage().setLimit(256 * 1024 * 1024); - broker.start(); - } + broker.start(); + } - protected static String getName() { - return "DurableSubProcessWithRestartTest"; - } + protected static String getName() { + return "DurableSubProcessWithRestartTest"; + } - private static boolean delete(File path) { - if (path == null) - return true; + private static boolean delete(File path) { + if (path == null) + return true; - if (path.isDirectory()) { - for (File file : path.listFiles()) { - delete(file); - } - } - return path.delete(); - } + if (path.isDirectory()) { + for (File file : path.listFiles()) { + delete(file); + } + } + return path.delete(); + } - private void destroyBroker() throws Exception { - if (broker == null) - return; + private void destroyBroker() throws Exception { + if (broker == null) + return; - broker.stop(); - broker = null; - } + broker.stop(); + broker = null; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubSelectorDelayTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubSelectorDelayTest.java index f17db91cea..f04dd08014 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubSelectorDelayTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubSelectorDelayTest.java @@ -43,267 +43,269 @@ import org.slf4j.LoggerFactory; public class DurableSubSelectorDelayTest { - private static final Logger LOG = LoggerFactory.getLogger(DurableSubSelectorDelayTest.class); + private static final Logger LOG = LoggerFactory.getLogger(DurableSubSelectorDelayTest.class); - public static final long RUNTIME = 3 * 60 * 1000; + public static final long RUNTIME = 3 * 60 * 1000; - private BrokerService broker; - private ActiveMQTopic topic; - private String connectionUri; + private BrokerService broker; + private ActiveMQTopic topic; + private String connectionUri; - @Test - public void testProcess() throws Exception { + @Test + public void testProcess() throws Exception { - MsgProducer msgProducer = new MsgProducer(); - msgProducer.start(); + MsgProducer msgProducer = new MsgProducer(); + msgProducer.start(); - DurableSubscriber subscribers[] = new DurableSubscriber[10]; + DurableSubscriber subscribers[] = new DurableSubscriber[10]; - for (int i = 0; i < subscribers.length; i++) { - subscribers[i] = new DurableSubscriber(i); - subscribers[i].process(); - } + for (int i = 0; i < subscribers.length; i++) { + subscribers[i] = new DurableSubscriber(i); + subscribers[i].process(); + } - // wait for server to finish - msgProducer.join(); + // wait for server to finish + msgProducer.join(); - for (int j = 0; j < subscribers.length; j++) { - LOG.info("Unsubscribing subscriber " + subscribers[j]); - subscribers[j].unsubscribe(); - } + for (int j = 0; j < subscribers.length; j++) { + LOG.info("Unsubscribing subscriber " + subscribers[j]); + subscribers[j].unsubscribe(); + } - // allow the clean up thread time to run - TimeUnit.MINUTES.sleep(2); + // allow the clean up thread time to run + TimeUnit.MINUTES.sleep(2); - final KahaDBPersistenceAdapter pa = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); - assertTrue("less than two journal file should be left, was: " + pa.getStore().getJournal().getFileMap().size(), Wait.waitFor(new Wait.Condition() { + final KahaDBPersistenceAdapter pa = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); + assertTrue("less than two journal file should be left, was: " + pa.getStore().getJournal().getFileMap().size(), Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return pa.getStore().getJournal().getFileMap().size() <= 2; + @Override + public boolean isSatisified() throws Exception { + return pa.getStore().getJournal().getFileMap().size() <= 2; + } + }, TimeUnit.MINUTES.toMillis(2))); + + LOG.info("DONE."); + } + + /** + * Message Producer + */ + final class MsgProducer extends Thread { + + final String url = "vm://" + DurableSubSelectorDelayTest.getName(); + + final ConnectionFactory cf = new ActiveMQConnectionFactory(url); + + int transRover = 0; + int messageRover = 0; + int count = 40; + + public MsgProducer() { + super("MsgProducer"); + setDaemon(true); + } + + public MsgProducer(int count) { + super("MsgProducer"); + setDaemon(true); + this.count = count; + } + + @Override + public void run() { + long endTime = RUNTIME + System.currentTimeMillis(); + + try { + while (endTime > System.currentTimeMillis()) { + Thread.sleep(400); + send(); } - }, TimeUnit.MINUTES.toMillis(2))); + } + catch (Throwable e) { + e.printStackTrace(System.out); + throw new RuntimeException(e); + } + } - LOG.info("DONE."); - } + public void send() throws JMSException { - /** - * Message Producer - */ - final class MsgProducer extends Thread { + int trans = ++transRover; + boolean relevantTrans = true; - final String url = "vm://" + DurableSubSelectorDelayTest.getName(); + LOG.info("Sending Trans[id=" + trans + ", count=" + count + "]"); - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); + Connection con = cf.createConnection(); - int transRover = 0; - int messageRover = 0; - int count = 40; + Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - public MsgProducer() { - super("MsgProducer"); - setDaemon(true); - } - - public MsgProducer(int count) { - super("MsgProducer"); - setDaemon(true); - this.count = count; - } - - @Override - public void run() { - long endTime = RUNTIME + System.currentTimeMillis(); - - try { - while (endTime > System.currentTimeMillis()) { - Thread.sleep(400); - send(); - } - } catch (Throwable e) { - e.printStackTrace(System.out); - throw new RuntimeException(e); - } - } - - public void send() throws JMSException { - - int trans = ++transRover; - boolean relevantTrans = true; - - LOG.info("Sending Trans[id=" + trans + ", count=" + count + "]"); - - Connection con = cf.createConnection(); - - Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageProducer prod = sess.createProducer(null); - - for (int i = 0; i < count; i++) { - Message message = sess.createMessage(); - message.setIntProperty("ID", ++messageRover); - message.setIntProperty("TRANS", trans); - message.setBooleanProperty("RELEVANT", false); - prod.send(topic, message); - } + MessageProducer prod = sess.createProducer(null); + for (int i = 0; i < count; i++) { Message message = sess.createMessage(); message.setIntProperty("ID", ++messageRover); message.setIntProperty("TRANS", trans); - message.setBooleanProperty("COMMIT", true); - message.setBooleanProperty("RELEVANT", relevantTrans); + message.setBooleanProperty("RELEVANT", false); prod.send(topic, message); + } - LOG.info("Committed Trans[id=" + trans + ", count=" + count + "], ID=" + messageRover); + Message message = sess.createMessage(); + message.setIntProperty("ID", ++messageRover); + message.setIntProperty("TRANS", trans); + message.setBooleanProperty("COMMIT", true); + message.setBooleanProperty("RELEVANT", relevantTrans); + prod.send(topic, message); + LOG.info("Committed Trans[id=" + trans + ", count=" + count + "], ID=" + messageRover); + + sess.close(); + con.close(); + } + } + + /** + * Consumes massages from a durable subscription. Goes online/offline + * periodically. Checks the incoming messages against the sent messages of + * the server. + */ + private final class DurableSubscriber { + + final ConnectionFactory cf = new ActiveMQConnectionFactory(connectionUri); + + private final String subName; + + private final int id; + private final String conClientId; + private final String selector; + + public DurableSubscriber(int id) throws JMSException { + this.id = id; + conClientId = "cli" + id; + subName = "subscription" + id; + selector = "RELEVANT = true"; + } + + private void process() throws JMSException { + long end = System.currentTimeMillis() + 20000; + int transCount = 0; + + LOG.info(toString() + " ONLINE."); + Connection con = openConnection(); + + Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = sess.createDurableSubscriber(topic, subName, selector, false); + + try { + + do { + long max = end - System.currentTimeMillis(); + + if (max <= 0) { + break; + } + + Message message = consumer.receive(max); + if (message == null) { + continue; + } + + LOG.info("Received Trans[id=" + message.getIntProperty("TRANS") + ", count=" + transCount + "] in " + this + "."); + + } while (true); + + } + finally { sess.close(); con.close(); - } - } - /** - * Consumes massages from a durable subscription. Goes online/offline - * periodically. Checks the incoming messages against the sent messages of - * the server. - */ - private final class DurableSubscriber { + LOG.info(toString() + " OFFLINE."); + } + } - final ConnectionFactory cf = new ActiveMQConnectionFactory(connectionUri); + private Connection openConnection() throws JMSException { + Connection con = cf.createConnection(); + con.setClientID(conClientId); + con.start(); + return con; + } - private final String subName; + private void unsubscribe() throws JMSException { + Connection con = openConnection(); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.unsubscribe(subName); + session.close(); + con.close(); + } - private final int id; - private final String conClientId; - private final String selector; + @Override + public String toString() { + return "DurableSubscriber[id=" + id + "]"; + } + } - public DurableSubscriber(int id) throws JMSException { - this.id = id; - conClientId = "cli" + id; - subName = "subscription" + id; - selector = "RELEVANT = true"; - } + @Before + public void setUp() throws Exception { + topic = new ActiveMQTopic("TopicT"); + startBroker(); + } - private void process() throws JMSException { - long end = System.currentTimeMillis() + 20000; - int transCount = 0; + @After + public void tearDown() throws Exception { + destroyBroker(); + } - LOG.info(toString() + " ONLINE."); - Connection con = openConnection(); + private void startBroker() throws Exception { + startBroker(true); + } - Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = sess.createDurableSubscriber(topic, subName, selector, false); + private void startBroker(boolean deleteAllMessages) throws Exception { + if (broker != null) + return; - try { + broker = BrokerFactory.createBroker("broker:(vm://" + getName() + ")"); + broker.setBrokerName(getName()); + broker.setAdvisorySupport(false); + broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - do { - long max = end - System.currentTimeMillis(); + File kahadbData = new File("activemq-data/" + getName() + "-kahadb"); + if (deleteAllMessages) + delete(kahadbData); - if (max <= 0) { - break; - } + broker.setPersistent(true); + KahaDBPersistenceAdapter kahadb = new KahaDBPersistenceAdapter(); + kahadb.setDirectory(kahadbData); + kahadb.setJournalMaxFileLength(500 * 1024); + broker.setPersistenceAdapter(kahadb); - Message message = consumer.receive(max); - if (message == null) { - continue; - } + connectionUri = broker.addConnector("tcp://localhost:0").getPublishableConnectString(); - LOG.info("Received Trans[id=" + message.getIntProperty("TRANS") + ", count=" + transCount + "] in " + this + "."); + broker.getSystemUsage().getMemoryUsage().setLimit(256 * 1024 * 1024); + broker.getSystemUsage().getTempUsage().setLimit(256 * 1024 * 1024); + broker.getSystemUsage().getStoreUsage().setLimit(256 * 1024 * 1024); - } while (true); + broker.start(); + } - } finally { - sess.close(); - con.close(); + protected static String getName() { + return "DurableSubSelectorDelayTest"; + } - LOG.info(toString() + " OFFLINE."); - } - } + private static boolean delete(File path) { + if (path == null) + return true; - private Connection openConnection() throws JMSException { - Connection con = cf.createConnection(); - con.setClientID(conClientId); - con.start(); - return con; - } + if (path.isDirectory()) { + for (File file : path.listFiles()) { + delete(file); + } + } + return path.delete(); + } - private void unsubscribe() throws JMSException { - Connection con = openConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.unsubscribe(subName); - session.close(); - con.close(); - } + private void destroyBroker() throws Exception { + if (broker == null) + return; - @Override - public String toString() { - return "DurableSubscriber[id=" + id + "]"; - } - } - - @Before - public void setUp() throws Exception { - topic = new ActiveMQTopic("TopicT"); - startBroker(); - } - - @After - public void tearDown() throws Exception { - destroyBroker(); - } - - private void startBroker() throws Exception { - startBroker(true); - } - - private void startBroker(boolean deleteAllMessages) throws Exception { - if (broker != null) - return; - - broker = BrokerFactory.createBroker("broker:(vm://" + getName() + ")"); - broker.setBrokerName(getName()); - broker.setAdvisorySupport(false); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - - File kahadbData = new File("activemq-data/" + getName() + "-kahadb"); - if (deleteAllMessages) - delete(kahadbData); - - broker.setPersistent(true); - KahaDBPersistenceAdapter kahadb = new KahaDBPersistenceAdapter(); - kahadb.setDirectory(kahadbData); - kahadb.setJournalMaxFileLength(500 * 1024); - broker.setPersistenceAdapter(kahadb); - - connectionUri = broker.addConnector("tcp://localhost:0").getPublishableConnectString(); - - broker.getSystemUsage().getMemoryUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getTempUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getStoreUsage().setLimit(256 * 1024 * 1024); - - broker.start(); - } - - protected static String getName() { - return "DurableSubSelectorDelayTest"; - } - - private static boolean delete(File path) { - if (path == null) - return true; - - if (path.isDirectory()) { - for (File file : path.listFiles()) { - delete(file); - } - } - return path.delete(); - } - - private void destroyBroker() throws Exception { - if (broker == null) - return; - - broker.stop(); - broker = null; - } + broker.stop(); + broker = null; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubSelectorDelayWithRestartTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubSelectorDelayWithRestartTest.java index 5e1cb429ba..70d9943fe6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubSelectorDelayWithRestartTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubSelectorDelayWithRestartTest.java @@ -43,300 +43,299 @@ import org.slf4j.LoggerFactory; public class DurableSubSelectorDelayWithRestartTest { - private static final Logger LOG = LoggerFactory.getLogger(DurableSubSelectorDelayWithRestartTest.class); + private static final Logger LOG = LoggerFactory.getLogger(DurableSubSelectorDelayWithRestartTest.class); - public static final long RUNTIME = 1 * 60 * 1000; + public static final long RUNTIME = 1 * 60 * 1000; - private boolean RESTART = true; - private int NUMBER_SUBSCRIBERS = 3; + private boolean RESTART = true; + private int NUMBER_SUBSCRIBERS = 3; - private BrokerService broker; - private ActiveMQTopic topic; + private BrokerService broker; + private ActiveMQTopic topic; - @Test - public void testProcess() throws Exception { + @Test + public void testProcess() throws Exception { - MsgProducer msgProducer = new MsgProducer(); - msgProducer.start(); + MsgProducer msgProducer = new MsgProducer(); + msgProducer.start(); - DurableSubscriber subscribers[] = new DurableSubscriber[NUMBER_SUBSCRIBERS]; + DurableSubscriber subscribers[] = new DurableSubscriber[NUMBER_SUBSCRIBERS]; - for (int i = 0; i < subscribers.length - 1; i++) { - subscribers[i] = new DurableSubscriber(i); - subscribers[i].process(); - } + for (int i = 0; i < subscribers.length - 1; i++) { + subscribers[i] = new DurableSubscriber(i); + subscribers[i].process(); + } - // wait for server to finish - msgProducer.join(); + // wait for server to finish + msgProducer.join(); - //for the last subscriber pop one message into the topic. - subscribers[(subscribers.length - 1)] = new DurableSubscriber((subscribers.length - 1)); - subscribers[(subscribers.length - 1)].subscribe(); - MsgProducer msgProducer2 = new MsgProducer(); - msgProducer2.send(); - subscribers[(subscribers.length - 1)].process(); + //for the last subscriber pop one message into the topic. + subscribers[(subscribers.length - 1)] = new DurableSubscriber((subscribers.length - 1)); + subscribers[(subscribers.length - 1)].subscribe(); + MsgProducer msgProducer2 = new MsgProducer(); + msgProducer2.send(); + subscribers[(subscribers.length - 1)].process(); - // unsubscribe all, but the last subscriber. - for (int j = 0; j < (subscribers.length - 1); j++) { - LOG.info("Unsubscribing subscriber " + subscribers[j]); - subscribers[j].unsubscribe(); - } + // unsubscribe all, but the last subscriber. + for (int j = 0; j < (subscribers.length - 1); j++) { + LOG.info("Unsubscribing subscriber " + subscribers[j]); + subscribers[j].unsubscribe(); + } - final KahaDBPersistenceAdapter pa = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); - assertTrue("small number of journal files should be left ", Wait.waitFor(new Wait.Condition() { + final KahaDBPersistenceAdapter pa = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); + assertTrue("small number of journal files should be left ", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("journal data file count - expected {} actual {}", 4, pa.getStore().getJournal().getFileMap().size()); - return pa.getStore().getJournal().getFileMap().size() < 4; + @Override + public boolean isSatisified() throws Exception { + LOG.info("journal data file count - expected {} actual {}", 4, pa.getStore().getJournal().getFileMap().size()); + return pa.getStore().getJournal().getFileMap().size() < 4; + } + }, TimeUnit.MINUTES.toMillis(3))); + + LOG.info("DONE."); + } + + /** + * Message Producer + */ + final class MsgProducer extends Thread { + + final String url = "failover:(tcp://localhost:61656)"; + + final ConnectionFactory cf = new ActiveMQConnectionFactory(url); + + int transRover = 0; + int messageRover = 0; + + public MsgProducer() { + super("MsgProducer"); + setDaemon(true); + } + + @Override + public void run() { + long endTime = RUNTIME + System.currentTimeMillis(); + + try { + while (endTime > System.currentTimeMillis()) { + Thread.sleep(400); + send(); + + //restart broker all the time + if (RESTART) { + destroyBroker(); + startBroker(false); + } } - }, TimeUnit.MINUTES.toMillis(3))); + } + catch (Throwable e) { + e.printStackTrace(System.out); + throw new RuntimeException(e); + } + } - LOG.info("DONE."); - } + public void send() throws JMSException { - /** - * Message Producer - */ - final class MsgProducer extends Thread { + int trans = ++transRover; + boolean relevantTrans = true; + int count = 40; - final String url = "failover:(tcp://localhost:61656)"; + LOG.info("Sending Trans[id=" + trans + ", count=" + count + "]"); - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); + Connection con = cf.createConnection(); - int transRover = 0; - int messageRover = 0; + Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - public MsgProducer() { - super("MsgProducer"); - setDaemon(true); - } - - @Override - public void run() { - long endTime = RUNTIME + System.currentTimeMillis(); - - try { - while (endTime > System.currentTimeMillis()) { - Thread.sleep(400); - send(); - - //restart broker all the time - if(RESTART){ - destroyBroker(); - startBroker(false); - } - } - } catch (Throwable e) { - e.printStackTrace(System.out); - throw new RuntimeException(e); - } - } - - public void send() throws JMSException { - - int trans = ++transRover; - boolean relevantTrans = true; - int count = 40; - - LOG.info("Sending Trans[id=" + trans + ", count=" - + count + "]"); - - Connection con = cf.createConnection(); - - Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageProducer prod = sess.createProducer(null); - - for (int i = 0; i < count; i++) { - Message message = sess.createMessage(); - message.setIntProperty("ID", ++messageRover); - message.setIntProperty("TRANS", trans); - message.setBooleanProperty("RELEVANT", false); - prod.send(topic, message); - } + MessageProducer prod = sess.createProducer(null); + for (int i = 0; i < count; i++) { Message message = sess.createMessage(); message.setIntProperty("ID", ++messageRover); message.setIntProperty("TRANS", trans); - message.setBooleanProperty("COMMIT", true); - message.setBooleanProperty("RELEVANT", relevantTrans); + message.setBooleanProperty("RELEVANT", false); prod.send(topic, message); + } - LOG.info("Committed Trans[id=" + trans + ", count=" - + count + "], ID=" + messageRover); + Message message = sess.createMessage(); + message.setIntProperty("ID", ++messageRover); + message.setIntProperty("TRANS", trans); + message.setBooleanProperty("COMMIT", true); + message.setBooleanProperty("RELEVANT", relevantTrans); + prod.send(topic, message); - sess.close(); - con.close(); - } - } + LOG.info("Committed Trans[id=" + trans + ", count=" + count + "], ID=" + messageRover); - /** - * Consumes massages from a durable subscription. Goes online/offline - * periodically. Checks the incoming messages against the sent messages of - * the server. - */ - private final class DurableSubscriber { + sess.close(); + con.close(); + } + } - final String url = "failover:(tcp://localhost:61656)"; + /** + * Consumes massages from a durable subscription. Goes online/offline + * periodically. Checks the incoming messages against the sent messages of + * the server. + */ + private final class DurableSubscriber { - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); + final String url = "failover:(tcp://localhost:61656)"; - private final String subName ; + final ConnectionFactory cf = new ActiveMQConnectionFactory(url); - private final int id; - private final String conClientId; - private final String selector; + private final String subName; - public DurableSubscriber(int id) throws JMSException { - this.id = id; - conClientId = "cli" + id; - subName = "subscription"+ id; - selector ="RELEVANT = true"; - } + private final int id; + private final String conClientId; + private final String selector; - private void process() throws JMSException { - long end = System.currentTimeMillis() + 20000; - int transCount = 0; + public DurableSubscriber(int id) throws JMSException { + this.id = id; + conClientId = "cli" + id; + subName = "subscription" + id; + selector = "RELEVANT = true"; + } - LOG.info(toString() + " ONLINE."); - Connection con = openConnection(); + private void process() throws JMSException { + long end = System.currentTimeMillis() + 20000; + int transCount = 0; - Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = sess.createDurableSubscriber(topic, subName, selector, false); + LOG.info(toString() + " ONLINE."); + Connection con = openConnection(); + Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = sess.createDurableSubscriber(topic, subName, selector, false); + + try { + + do { + long max = end - System.currentTimeMillis(); + + if (max <= 0) { + break; + } + + Message message = consumer.receive(max); + if (message == null) { + continue; + } + + LOG.info("Received Trans[id=" + message.getIntProperty("TRANS") + ", count=" + transCount + "] in " + this + "."); + + } while (true); + + } + finally { try { - - do { - long max = end - System.currentTimeMillis(); - - if (max <= 0) { - break; - } - - Message message = consumer.receive(max); - if (message == null) { - continue; - } - - LOG.info("Received Trans[id=" - + message.getIntProperty("TRANS") + ", count=" - + transCount + "] in " + this + "."); - - } while (true); - - } finally { - try { - sess.close(); - con.close(); - } catch (Exception e) {} - - LOG.info(toString() + " OFFLINE."); + sess.close(); + con.close(); } - } - - private Connection openConnection() throws JMSException { - Connection con = cf.createConnection(); - con.setClientID(conClientId); - con.start(); - return con; - } - - public void subscribe() throws JMSException{ - LOG.info(toString() + "SUBSCRIBING"); - Connection con = openConnection(); - - Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - sess.createDurableSubscriber(topic, subName, selector, false); - - sess.close(); - con.close(); - } - - private void unsubscribe() throws JMSException { - Connection con = openConnection(); - Session session = con - .createSession(false, Session.AUTO_ACKNOWLEDGE); - session.unsubscribe(subName); - session.close(); - con.close(); - } - - @Override - public String toString() { - return "DurableSubscriber[id=" + id + "]"; - } - } - - @Before - public void setUp() throws Exception { - topic = new ActiveMQTopic("TopicT"); - startBroker(); - } - - @After - public void tearDown() throws Exception { - destroyBroker(); - } - - private void startBroker() throws Exception { - startBroker(true); - } - - private void startBroker(boolean deleteAllMessages) throws Exception { - if (broker != null) - return; - - broker = BrokerFactory.createBroker("broker:(vm://" + getName() + ")"); - broker.setBrokerName(getName()); - broker.setAdvisorySupport(false); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - - File kahadbData = new File("activemq-data/" + getName() + "-kahadb"); - if (deleteAllMessages) - delete(kahadbData); - - broker.setPersistent(true); - KahaDBPersistenceAdapter kahadb = new KahaDBPersistenceAdapter(); - kahadb.setDirectory(kahadbData); - kahadb.setJournalMaxFileLength( 10 * 1024); - kahadb.setCleanupInterval(5000); - broker.setPersistenceAdapter(kahadb); - - broker.addConnector("tcp://localhost:61656"); - - broker.getSystemUsage().getMemoryUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getTempUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getStoreUsage().setLimit(256 * 1024 * 1024); - - LOG.info(toString() + "Starting Broker..."); - broker.start(); - broker.waitUntilStarted(); - - LOG.info(toString() + " Broker started!!"); - } - - protected static String getName() { - return "DurableSubSelectorDelayTest"; - } - - private static boolean delete(File path) { - if (path == null) - return true; - - if (path.isDirectory()) { - for (File file : path.listFiles()) { - delete(file); + catch (Exception e) { } - } - return path.delete(); - } - private void destroyBroker() throws Exception { - if (broker == null) - return; + LOG.info(toString() + " OFFLINE."); + } + } - broker.stop(); - broker = null; - } + private Connection openConnection() throws JMSException { + Connection con = cf.createConnection(); + con.setClientID(conClientId); + con.start(); + return con; + } + + public void subscribe() throws JMSException { + LOG.info(toString() + "SUBSCRIBING"); + Connection con = openConnection(); + + Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + sess.createDurableSubscriber(topic, subName, selector, false); + + sess.close(); + con.close(); + } + + private void unsubscribe() throws JMSException { + Connection con = openConnection(); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.unsubscribe(subName); + session.close(); + con.close(); + } + + @Override + public String toString() { + return "DurableSubscriber[id=" + id + "]"; + } + } + + @Before + public void setUp() throws Exception { + topic = new ActiveMQTopic("TopicT"); + startBroker(); + } + + @After + public void tearDown() throws Exception { + destroyBroker(); + } + + private void startBroker() throws Exception { + startBroker(true); + } + + private void startBroker(boolean deleteAllMessages) throws Exception { + if (broker != null) + return; + + broker = BrokerFactory.createBroker("broker:(vm://" + getName() + ")"); + broker.setBrokerName(getName()); + broker.setAdvisorySupport(false); + broker.setDeleteAllMessagesOnStartup(deleteAllMessages); + + File kahadbData = new File("activemq-data/" + getName() + "-kahadb"); + if (deleteAllMessages) + delete(kahadbData); + + broker.setPersistent(true); + KahaDBPersistenceAdapter kahadb = new KahaDBPersistenceAdapter(); + kahadb.setDirectory(kahadbData); + kahadb.setJournalMaxFileLength(10 * 1024); + kahadb.setCleanupInterval(5000); + broker.setPersistenceAdapter(kahadb); + + broker.addConnector("tcp://localhost:61656"); + + broker.getSystemUsage().getMemoryUsage().setLimit(256 * 1024 * 1024); + broker.getSystemUsage().getTempUsage().setLimit(256 * 1024 * 1024); + broker.getSystemUsage().getStoreUsage().setLimit(256 * 1024 * 1024); + + LOG.info(toString() + "Starting Broker..."); + broker.start(); + broker.waitUntilStarted(); + + LOG.info(toString() + " Broker started!!"); + } + + protected static String getName() { + return "DurableSubSelectorDelayTest"; + } + + private static boolean delete(File path) { + if (path == null) + return true; + + if (path.isDirectory()) { + for (File file : path.listFiles()) { + delete(file); + } + } + return path.delete(); + } + + private void destroyBroker() throws Exception { + if (broker == null) + return; + + broker.stop(); + broker = null; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubsOfflineSelectorConcurrentConsumeIndexUseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubsOfflineSelectorConcurrentConsumeIndexUseTest.java index 0afc8da7a9..48ba447b0d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubsOfflineSelectorConcurrentConsumeIndexUseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubsOfflineSelectorConcurrentConsumeIndexUseTest.java @@ -43,215 +43,217 @@ import org.slf4j.LoggerFactory; public class DurableSubsOfflineSelectorConcurrentConsumeIndexUseTest extends org.apache.activemq.TestSupport { - private static final Logger LOG = LoggerFactory.getLogger(DurableSubsOfflineSelectorConcurrentConsumeIndexUseTest.class); - public int messageCount = 10000; - private BrokerService broker; - private ActiveMQTopic topic; - private final List exceptions = new ArrayList(); + private static final Logger LOG = LoggerFactory.getLogger(DurableSubsOfflineSelectorConcurrentConsumeIndexUseTest.class); + public int messageCount = 10000; + private BrokerService broker; + private ActiveMQTopic topic; + private final List exceptions = new ArrayList(); - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + getName(true)); - connectionFactory.setWatchTopicAdvisories(false); - return connectionFactory; - } + @Override + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + getName(true)); + connectionFactory.setWatchTopicAdvisories(false); + return connectionFactory; + } - @Override - protected Connection createConnection() throws Exception { - return createConnection("id"); - } + @Override + protected Connection createConnection() throws Exception { + return createConnection("id"); + } - protected Connection createConnection(String name) throws Exception { - Connection con = getConnectionFactory().createConnection(); - con.setClientID(name); - con.start(); - return con; - } + protected Connection createConnection(String name) throws Exception { + Connection con = getConnectionFactory().createConnection(); + con.setClientID(name); + con.start(); + return con; + } - public static Test suite() { - return suite(DurableSubsOfflineSelectorConcurrentConsumeIndexUseTest.class); - } + public static Test suite() { + return suite(DurableSubsOfflineSelectorConcurrentConsumeIndexUseTest.class); + } - @Override - protected void setUp() throws Exception { - exceptions.clear(); - topic = (ActiveMQTopic) createDestination(); - createBroker(); - super.setUp(); - } + @Override + protected void setUp() throws Exception { + exceptions.clear(); + topic = (ActiveMQTopic) createDestination(); + createBroker(); + super.setUp(); + } - @Override - protected void tearDown() throws Exception { - super.tearDown(); - destroyBroker(); - } + @Override + protected void tearDown() throws Exception { + super.tearDown(); + destroyBroker(); + } - private void createBroker() throws Exception { - createBroker(true); - } + private void createBroker() throws Exception { + createBroker(true); + } - private void createBroker(boolean deleteAllMessages) throws Exception { - broker = BrokerFactory.createBroker("broker:(vm://" + getName(true) + ")"); - broker.setBrokerName(getName(true)); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - broker.getManagementContext().setCreateConnector(false); - broker.setAdvisorySupport(false); - broker.addConnector("tcp://0.0.0.0:0"); + private void createBroker(boolean deleteAllMessages) throws Exception { + broker = BrokerFactory.createBroker("broker:(vm://" + getName(true) + ")"); + broker.setBrokerName(getName(true)); + broker.setDeleteAllMessagesOnStartup(deleteAllMessages); + broker.getManagementContext().setCreateConnector(false); + broker.setAdvisorySupport(false); + broker.addConnector("tcp://0.0.0.0:0"); - setDefaultPersistenceAdapter(broker); + setDefaultPersistenceAdapter(broker); - ((KahaDBPersistenceAdapter)broker.getPersistenceAdapter()).getStore().getPageFile().setPageSize(1024); + ((KahaDBPersistenceAdapter) broker.getPersistenceAdapter()).getStore().getPageFile().setPageSize(1024); - broker.start(); - } + broker.start(); + } - private void destroyBroker() throws Exception { - if (broker != null) - broker.stop(); - } + private void destroyBroker() throws Exception { + if (broker != null) + broker.stop(); + } - public void testIndexPageUsage() throws Exception { - Connection con = createConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "true", "filter = 'true'", true); - session.close(); + public void testIndexPageUsage() throws Exception { + Connection con = createConnection(); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "true", "filter = 'true'", true); + session.close(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "false", "filter = 'false'", true); - session.close(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "false", "filter = 'false'", true); + session.close(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "all", null, true); - session.close(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "all", null, true); + session.close(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "all2", null, true); - session.close(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "all2", null, true); + session.close(); - con.close(); + con.close(); - // send messages + // send messages - final CountDownLatch goOn = new CountDownLatch(1); - Thread sendThread = new Thread() { - @Override - public void run() { - try { + final CountDownLatch goOn = new CountDownLatch(1); + Thread sendThread = new Thread() { + @Override + public void run() { + try { - final Connection sendCon = createConnection("send"); - final Session sendSession = sendCon.createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageProducer producer = sendSession.createProducer(null); + final Connection sendCon = createConnection("send"); + final Session sendSession = sendCon.createSession(false, Session.AUTO_ACKNOWLEDGE); + final MessageProducer producer = sendSession.createProducer(null); - for (int i = 0; i < messageCount; i++) { - boolean filter = i % 2 == 1; - Message message = sendSession.createMessage(); - message.setStringProperty("filter", filter ? "true" : "false"); - producer.send(topic, message); + for (int i = 0; i < messageCount; i++) { + boolean filter = i % 2 == 1; + Message message = sendSession.createMessage(); + message.setStringProperty("filter", filter ? "true" : "false"); + producer.send(topic, message); - if (i > 0 && i % 10000 == 0) { - LOG.info("Sent:" + i); - } - if (i> messageCount/2) { - goOn.countDown(); - } - } - sendSession.close(); - sendCon.close(); - } catch (Exception e) { - exceptions.add(e); - } + if (i > 0 && i % 10000 == 0) { + LOG.info("Sent:" + i); + } + if (i > messageCount / 2) { + goOn.countDown(); + } + } + sendSession.close(); + sendCon.close(); } - }; - sendThread.start(); + catch (Exception e) { + exceptions.add(e); + } + } + }; + sendThread.start(); - goOn.await(5, TimeUnit.MINUTES); - LOG.info("Activating consumers"); + goOn.await(5, TimeUnit.MINUTES); + LOG.info("Activating consumers"); - // consume messages in parallel - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + // consume messages in parallel + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumerTrue = session.createDurableSubscriber(topic, "true", "filter = 'true'", true); - Listener listenerT = new Listener(); - consumerTrue.setMessageListener(listenerT); + MessageConsumer consumerTrue = session.createDurableSubscriber(topic, "true", "filter = 'true'", true); + Listener listenerT = new Listener(); + consumerTrue.setMessageListener(listenerT); - MessageConsumer consumerFalse = session.createDurableSubscriber(topic, "false", "filter = 'false'", true); - Listener listenerF = new Listener(); - consumerFalse.setMessageListener(listenerF); + MessageConsumer consumerFalse = session.createDurableSubscriber(topic, "false", "filter = 'false'", true); + Listener listenerF = new Listener(); + consumerFalse.setMessageListener(listenerF); - MessageConsumer consumerAll = session.createDurableSubscriber(topic, "all", null, true); - Listener listenerA = new Listener(); - consumerAll.setMessageListener(listenerA); + MessageConsumer consumerAll = session.createDurableSubscriber(topic, "all", null, true); + Listener listenerA = new Listener(); + consumerAll.setMessageListener(listenerA); - MessageConsumer consumerAll2 = session.createDurableSubscriber(topic, "all2", null, true); - Listener listenerA2 = new Listener(); - consumerAll2.setMessageListener(listenerA2); + MessageConsumer consumerAll2 = session.createDurableSubscriber(topic, "all2", null, true); + Listener listenerA2 = new Listener(); + consumerAll2.setMessageListener(listenerA2); - waitFor(listenerA, messageCount); - assertEquals(messageCount, listenerA.count); + waitFor(listenerA, messageCount); + assertEquals(messageCount, listenerA.count); - waitFor(listenerA2, messageCount); - assertEquals(messageCount, listenerA2.count); + waitFor(listenerA2, messageCount); + assertEquals(messageCount, listenerA2.count); - assertEquals(messageCount / 2, listenerT.count); - assertEquals(messageCount / 2, listenerF.count); + assertEquals(messageCount / 2, listenerT.count); + assertEquals(messageCount / 2, listenerF.count); - consumerTrue.close(); - session.unsubscribe("true"); + consumerTrue.close(); + session.unsubscribe("true"); - consumerFalse.close(); - session.unsubscribe("false"); + consumerFalse.close(); + session.unsubscribe("false"); - consumerAll.close(); - session.unsubscribe("all"); + consumerAll.close(); + session.unsubscribe("all"); - session.close(); - con.close(); + session.close(); + con.close(); - PersistenceAdapter persistenceAdapter = broker.getPersistenceAdapter(); - if( persistenceAdapter instanceof KahaDBPersistenceAdapter) { - final KahaDBStore store = ((KahaDBPersistenceAdapter) persistenceAdapter).getStore(); - LOG.info("Store page count: " + store.getPageFile().getPageCount()); - LOG.info("Store free page count: " + store.getPageFile().getFreePageCount()); - LOG.info("Store page in-use: " + (store.getPageFile().getPageCount() - store.getPageFile().getFreePageCount())); + PersistenceAdapter persistenceAdapter = broker.getPersistenceAdapter(); + if (persistenceAdapter instanceof KahaDBPersistenceAdapter) { + final KahaDBStore store = ((KahaDBPersistenceAdapter) persistenceAdapter).getStore(); + LOG.info("Store page count: " + store.getPageFile().getPageCount()); + LOG.info("Store free page count: " + store.getPageFile().getFreePageCount()); + LOG.info("Store page in-use: " + (store.getPageFile().getPageCount() - store.getPageFile().getFreePageCount())); - assertTrue("no leak of pages, always use just 11", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return 11 == store.getPageFile().getPageCount() - - store.getPageFile().getFreePageCount(); - } - }, TimeUnit.SECONDS.toMillis(10))); - } - } - - private void waitFor(final Listener listener, final int count) throws Exception { - - assertTrue("got all messages on time", Wait.waitFor(new Wait.Condition() { + assertTrue("no leak of pages, always use just 11", Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisified() throws Exception { - return listener.count == count; + return 11 == store.getPageFile().getPageCount() - store.getPageFile().getFreePageCount(); } - }, TimeUnit.MINUTES.toMillis(10))); + }, TimeUnit.SECONDS.toMillis(10))); + } + } - } + private void waitFor(final Listener listener, final int count) throws Exception { - public static class Listener implements MessageListener { - int count = 0; - String id = null; + assertTrue("got all messages on time", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return listener.count == count; + } + }, TimeUnit.MINUTES.toMillis(10))); - Listener() { - } + } - @Override - public void onMessage(Message message) { - count++; - if (id != null) { - try { - LOG.info(id + ", " + message.getJMSMessageID()); - } catch (Exception ignored) { - } + public static class Listener implements MessageListener { + + int count = 0; + String id = null; + + Listener() { + } + + @Override + public void onMessage(Message message) { + count++; + if (id != null) { + try { + LOG.info(id + ", " + message.getJMSMessageID()); } - } - } + catch (Exception ignored) { + } + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubsOfflineSelectorIndexUseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubsOfflineSelectorIndexUseTest.java index e25a30c009..8aac35ab72 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubsOfflineSelectorIndexUseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubsOfflineSelectorIndexUseTest.java @@ -25,7 +25,9 @@ import javax.jms.MessageConsumer; import javax.jms.MessageListener; import javax.jms.MessageProducer; import javax.jms.Session; + import junit.framework.Test; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerFactory; import org.apache.activemq.broker.BrokerService; @@ -39,187 +41,189 @@ import org.slf4j.LoggerFactory; public class DurableSubsOfflineSelectorIndexUseTest extends org.apache.activemq.TestSupport { - private static final Logger LOG = LoggerFactory.getLogger(DurableSubsOfflineSelectorIndexUseTest.class); - public int messageCount = 400; - private BrokerService broker; - private ActiveMQTopic topic; - private List exceptions = new ArrayList(); + private static final Logger LOG = LoggerFactory.getLogger(DurableSubsOfflineSelectorIndexUseTest.class); + public int messageCount = 400; + private BrokerService broker; + private ActiveMQTopic topic; + private List exceptions = new ArrayList(); - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + getName(true)); - connectionFactory.setWatchTopicAdvisories(false); - return connectionFactory; - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + getName(true)); + connectionFactory.setWatchTopicAdvisories(false); + return connectionFactory; + } - @Override - protected Connection createConnection() throws Exception { - return createConnection("id"); - } + @Override + protected Connection createConnection() throws Exception { + return createConnection("id"); + } - protected Connection createConnection(String name) throws Exception { - Connection con = super.createConnection(); - con.setClientID(name); - con.start(); - return con; - } + protected Connection createConnection(String name) throws Exception { + Connection con = super.createConnection(); + con.setClientID(name); + con.start(); + return con; + } - public static Test suite() { - return suite(DurableSubsOfflineSelectorIndexUseTest.class); - } + public static Test suite() { + return suite(DurableSubsOfflineSelectorIndexUseTest.class); + } - protected void setUp() throws Exception { - exceptions.clear(); - topic = (ActiveMQTopic) createDestination(); - createBroker(); - super.setUp(); - } + protected void setUp() throws Exception { + exceptions.clear(); + topic = (ActiveMQTopic) createDestination(); + createBroker(); + super.setUp(); + } - protected void tearDown() throws Exception { - super.tearDown(); - destroyBroker(); - } + protected void tearDown() throws Exception { + super.tearDown(); + destroyBroker(); + } - private void createBroker() throws Exception { - createBroker(true); - } + private void createBroker() throws Exception { + createBroker(true); + } - private void createBroker(boolean deleteAllMessages) throws Exception { - broker = BrokerFactory.createBroker("broker:(vm://" + getName(true) + ")"); - broker.setBrokerName(getName(true)); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - broker.getManagementContext().setCreateConnector(false); - broker.setAdvisorySupport(false); - broker.addConnector("tcp://0.0.0.0:0"); + private void createBroker(boolean deleteAllMessages) throws Exception { + broker = BrokerFactory.createBroker("broker:(vm://" + getName(true) + ")"); + broker.setBrokerName(getName(true)); + broker.setDeleteAllMessagesOnStartup(deleteAllMessages); + broker.getManagementContext().setCreateConnector(false); + broker.setAdvisorySupport(false); + broker.addConnector("tcp://0.0.0.0:0"); - setDefaultPersistenceAdapter(broker); - broker.start(); - } + setDefaultPersistenceAdapter(broker); + broker.start(); + } - private void destroyBroker() throws Exception { - if (broker != null) - broker.stop(); - } + private void destroyBroker() throws Exception { + if (broker != null) + broker.stop(); + } - public void initCombosForTestIndexPageUsage() { - addCombinationValues("messageCount", new Integer[]{890, 900, 400}); - } + public void initCombosForTestIndexPageUsage() { + addCombinationValues("messageCount", new Integer[]{890, 900, 400}); + } - public void testIndexPageUsage() throws Exception { - Connection con = createConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "true", "filter = 'true'", true); - session.close(); + public void testIndexPageUsage() throws Exception { + Connection con = createConnection(); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "true", "filter = 'true'", true); + session.close(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "false", "filter = 'false'", true); - session.close(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "false", "filter = 'false'", true); + session.close(); - con.close(); + con.close(); - // send messages - final Connection sendCon = createConnection("send"); - final Session sendSession = sendCon.createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageProducer producer = sendSession.createProducer(null); + // send messages + final Connection sendCon = createConnection("send"); + final Session sendSession = sendCon.createSession(false, Session.AUTO_ACKNOWLEDGE); + final MessageProducer producer = sendSession.createProducer(null); - Thread sendThread = new Thread() { - public void run() { - try { + Thread sendThread = new Thread() { + public void run() { + try { - for (int i = 0; i < messageCount; i++) { - boolean filter = i % 2 == 1; - Message message = sendSession.createMessage(); - message.setStringProperty("filter", filter ? "true" : "false"); - producer.send(topic, message); + for (int i = 0; i < messageCount; i++) { + boolean filter = i % 2 == 1; + Message message = sendSession.createMessage(); + message.setStringProperty("filter", filter ? "true" : "false"); + producer.send(topic, message); - if (i > 0 && i % 1000 == 0) { - LOG.info("Sent:" + i); - } - } - sendSession.close(); - sendCon.close(); - } catch (Exception e) { - exceptions.add(e); - } + if (i > 0 && i % 1000 == 0) { + LOG.info("Sent:" + i); + } + } + sendSession.close(); + sendCon.close(); } - }; - sendThread.start(); + catch (Exception e) { + exceptions.add(e); + } + } + }; + sendThread.start(); - sendThread.join(); + sendThread.join(); - // settle with sent messages - TimeUnit.SECONDS.sleep(4); + // settle with sent messages + TimeUnit.SECONDS.sleep(4); - // consume messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + // consume messages + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumerTrue = session.createDurableSubscriber(topic, "true", "filter = 'true'", true); - Listener listenerT = new Listener(); - consumerTrue.setMessageListener(listenerT); + MessageConsumer consumerTrue = session.createDurableSubscriber(topic, "true", "filter = 'true'", true); + Listener listenerT = new Listener(); + consumerTrue.setMessageListener(listenerT); - waitFor(listenerT, messageCount / 2); + waitFor(listenerT, messageCount / 2); - MessageConsumer consumerFalse = session.createDurableSubscriber(topic, "false", "filter = 'false'", true); - Listener listenerF = new Listener(); - consumerFalse.setMessageListener(listenerF); + MessageConsumer consumerFalse = session.createDurableSubscriber(topic, "false", "filter = 'false'", true); + Listener listenerF = new Listener(); + consumerFalse.setMessageListener(listenerF); - waitFor(listenerF, messageCount / 2); + waitFor(listenerF, messageCount / 2); - assertEquals(messageCount / 2, listenerT.count); - assertEquals(messageCount / 2, listenerF.count); + assertEquals(messageCount / 2, listenerT.count); + assertEquals(messageCount / 2, listenerF.count); - consumerTrue.close(); - session.unsubscribe("true"); + consumerTrue.close(); + session.unsubscribe("true"); - consumerFalse.close(); - session.unsubscribe("false"); + consumerFalse.close(); + session.unsubscribe("false"); - session.close(); - con.close(); + session.close(); + con.close(); - PersistenceAdapter persistenceAdapter = broker.getPersistenceAdapter(); - if( persistenceAdapter instanceof KahaDBStore) { - final KahaDBStore store = ((KahaDBPersistenceAdapter) persistenceAdapter).getStore(); - LOG.info("Store page count: " + store.getPageFile().getPageCount()); - LOG.info("Store free page count: " + store.getPageFile().getFreePageCount()); - LOG.info("Store page in-use: " + (store.getPageFile().getPageCount() - store.getPageFile().getFreePageCount())); + PersistenceAdapter persistenceAdapter = broker.getPersistenceAdapter(); + if (persistenceAdapter instanceof KahaDBStore) { + final KahaDBStore store = ((KahaDBPersistenceAdapter) persistenceAdapter).getStore(); + LOG.info("Store page count: " + store.getPageFile().getPageCount()); + LOG.info("Store free page count: " + store.getPageFile().getFreePageCount()); + LOG.info("Store page in-use: " + (store.getPageFile().getPageCount() - store.getPageFile().getFreePageCount())); - assertTrue("no leak of pages, always use just 10", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return 10 == store.getPageFile().getPageCount() - - store.getPageFile().getFreePageCount(); - } - }, TimeUnit.SECONDS.toMillis(10))); - } - } - - private void waitFor(final Listener listener, final int count) throws Exception { - - assertTrue("got all messages on time", Wait.waitFor(new Wait.Condition() { + assertTrue("no leak of pages, always use just 10", Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisified() throws Exception { - return listener.count == count; + return 10 == store.getPageFile().getPageCount() - store.getPageFile().getFreePageCount(); } - }, TimeUnit.MINUTES.toMillis(10))); + }, TimeUnit.SECONDS.toMillis(10))); + } + } - } + private void waitFor(final Listener listener, final int count) throws Exception { - public static class Listener implements MessageListener { - int count = 0; - String id = null; + assertTrue("got all messages on time", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return listener.count == count; + } + }, TimeUnit.MINUTES.toMillis(10))); - Listener() { - } + } - public void onMessage(Message message) { - count++; - if (id != null) { - try { - LOG.info(id + ", " + message.getJMSMessageID()); - } catch (Exception ignored) { - } + public static class Listener implements MessageListener { + + int count = 0; + String id = null; + + Listener() { + } + + public void onMessage(Message message) { + count++; + if (id != null) { + try { + LOG.info(id + ", " + message.getJMSMessageID()); } - } - } + catch (Exception ignored) { + } + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriberNonPersistentMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriberNonPersistentMessageTest.java index 74f6664dec..a634e98a21 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriberNonPersistentMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriberNonPersistentMessageTest.java @@ -53,270 +53,273 @@ import org.slf4j.LoggerFactory; public class DurableSubscriberNonPersistentMessageTest extends TestCase { - private final Logger LOG = LoggerFactory.getLogger(DurableSubscriberNonPersistentMessageTest.class); - private String brokerURL; - private String consumerBrokerURL; + private final Logger LOG = LoggerFactory.getLogger(DurableSubscriberNonPersistentMessageTest.class); + private String brokerURL; + private String consumerBrokerURL; - int initialMaxMsgs = 10; - int cleanupMsgCount = 10; - int totalMsgCount = initialMaxMsgs + cleanupMsgCount; - int totalMsgReceived = 0; - int sleep = 500; - int reconnectSleep = 2000; - int messageTimeout = 1000; - int messageSize = 1024; + int initialMaxMsgs = 10; + int cleanupMsgCount = 10; + int totalMsgCount = initialMaxMsgs + cleanupMsgCount; + int totalMsgReceived = 0; + int sleep = 500; + int reconnectSleep = 2000; + int messageTimeout = 1000; + int messageSize = 1024; - // Note: If ttl is set 0, the default set by the broker will be used if any - // setting a value greater than 0 will enable the producer to set the ttl on - // the message - long ttl = 0; + // Note: If ttl is set 0, the default set by the broker will be used if any + // setting a value greater than 0 will enable the producer to set the ttl on + // the message + long ttl = 0; - static String clientId = "Jason"; - MBeanServer mbeanServer; + static String clientId = "Jason"; + MBeanServer mbeanServer; - BrokerService broker; + BrokerService broker; - @Override - protected void setUp() throws Exception { - super.setUp(); - broker = new BrokerService(); - TransportConnector transportConnector = broker.addConnector("tcp://localhost:0"); - KahaDBStore store = new KahaDBStore(); - store.setDirectory(new File("data")); - broker.setPersistenceAdapter(store); - broker.start(); + @Override + protected void setUp() throws Exception { + super.setUp(); + broker = new BrokerService(); + TransportConnector transportConnector = broker.addConnector("tcp://localhost:0"); + KahaDBStore store = new KahaDBStore(); + store.setDirectory(new File("data")); + broker.setPersistenceAdapter(store); + broker.start(); - brokerURL = "failover:(" + transportConnector.getPublishableConnectString() + ")"; - consumerBrokerURL = brokerURL + "?jms.prefetchPolicy.all=100"; + brokerURL = "failover:(" + transportConnector.getPublishableConnectString() + ")"; + consumerBrokerURL = brokerURL + "?jms.prefetchPolicy.all=100"; - mbeanServer = ManagementFactory.getPlatformMBeanServer(); - } + mbeanServer = ManagementFactory.getPlatformMBeanServer(); + } - @Override - protected void tearDown() throws Exception { - broker.stop(); - super.tearDown(); - } + @Override + protected void tearDown() throws Exception { + broker.stop(); + super.tearDown(); + } - /** - * Create the test case - * - * @param testName - * name of the test case - */ - public DurableSubscriberNonPersistentMessageTest(String testName) { - super(testName); - } + /** + * Create the test case + * + * @param testName name of the test case + */ + public DurableSubscriberNonPersistentMessageTest(String testName) { + super(testName); + } - /** - * @return the suite of tests being tested - */ - public static Test suite() { - return new TestSuite(DurableSubscriberNonPersistentMessageTest.class); - } + /** + * @return the suite of tests being tested + */ + public static Test suite() { + return new TestSuite(DurableSubscriberNonPersistentMessageTest.class); + } - public void testDurableSubscriberNonPersistentMessage() { - String interest = "TEST"; + public void testDurableSubscriberNonPersistentMessage() { + String interest = "TEST"; - LOG.info("Starting DurableSubscriberNonPersistentMessageTest"); + LOG.info("Starting DurableSubscriberNonPersistentMessageTest"); - try { - // create durable topic consumer and disconnect - createConsumer(interest, 0); - Thread.sleep(1000); + try { + // create durable topic consumer and disconnect + createConsumer(interest, 0); + Thread.sleep(1000); - // produce 15 messages to topic - Producer producer = new Producer(brokerURL, interest, messageSize, ttl); - producer.sendMessages(totalMsgCount); - producer.close(); - LOG.info(totalMsgCount + " messages sent"); + // produce 15 messages to topic + Producer producer = new Producer(brokerURL, interest, messageSize, ttl); + producer.sendMessages(totalMsgCount); + producer.close(); + LOG.info(totalMsgCount + " messages sent"); - // durable topic consumer will consume 10 messages and disconnect - createConsumer(interest, initialMaxMsgs); + // durable topic consumer will consume 10 messages and disconnect + createConsumer(interest, initialMaxMsgs); - Thread.sleep(reconnectSleep); + Thread.sleep(reconnectSleep); - createConsumer(interest, cleanupMsgCount); + createConsumer(interest, cleanupMsgCount); - String brokerVersion = (String) mbeanServer.getAttribute(new ObjectName("org.apache.activemq:brokerName=localhost,type=Broker"), "BrokerVersion"); + String brokerVersion = (String) mbeanServer.getAttribute(new ObjectName("org.apache.activemq:brokerName=localhost,type=Broker"), "BrokerVersion"); - LOG.info("Test run on: " + brokerVersion); - final String theJmxObject = "org.apache.activemq:type=Broker,brokerName=localhost," + - "endpoint=Consumer,destinationType=Topic,destinationName=TEST,clientId=Jason," + - "consumerId=Durable(Jason_MyDurableTopic)"; + LOG.info("Test run on: " + brokerVersion); + final String theJmxObject = "org.apache.activemq:type=Broker,brokerName=localhost," + + "endpoint=Consumer,destinationType=Topic,destinationName=TEST,clientId=Jason," + + "consumerId=Durable(Jason_MyDurableTopic)"; - assertTrue("pendingQueueSize should be zero", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Integer pendingQueueSize = (Integer) mbeanServer.getAttribute(new ObjectName(theJmxObject), "PendingQueueSize"); - LOG.info("pendingQueueSize = " + pendingQueueSize); - return pendingQueueSize.intValue() == 0; - } - })); - - assertTrue("cursorMemoryUsage should be zero", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Long cursorMemoryUsage = (Long) mbeanServer.getAttribute(new ObjectName(theJmxObject), "CursorMemoryUsage"); - LOG.info("cursorMemoryUsage = " + cursorMemoryUsage); - return cursorMemoryUsage.longValue() == 0L; - } - })); - - // Not sure what the behavior should be here, if the messages - // expired the received count shouldn't equal total message count - assertTrue(totalMsgReceived == initialMaxMsgs + cleanupMsgCount); - } catch (Exception e) { - LOG.error("Exception Executing DurableSubscriberNonPersistentMessageTest: " + getStackTrace(e)); - fail("Should not throw any exceptions"); - } - } - - // create durable topic consumer and max number of messages - public void createConsumer(String interest, int maxMsgs) { - int messageReceived = 0; - int messagesNotReceived = 0; - - LOG.info("Starting DurableSubscriber"); - - Consumer consumer = null; - - try { - consumer = new Consumer(consumerBrokerURL, interest, clientId); - - for (int i = 0; i < maxMsgs; i++) { - try { - Message msg = consumer.getMessage(messageTimeout); - if (msg != null) { - LOG.debug("Received Message: " + msg.toString()); - messageReceived++; - totalMsgReceived++; - } else { - LOG.debug("message " + i + " not received"); - messagesNotReceived++; - } - - Thread.sleep(sleep); - } catch (InterruptedException ie) { - LOG.debug("Exception: " + ie); - } + assertTrue("pendingQueueSize should be zero", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Integer pendingQueueSize = (Integer) mbeanServer.getAttribute(new ObjectName(theJmxObject), "PendingQueueSize"); + LOG.info("pendingQueueSize = " + pendingQueueSize); + return pendingQueueSize.intValue() == 0; } + })); - consumer.close(); - - LOG.info("Consumer Finished"); - LOG.info("Received " + messageReceived); - LOG.info("Not Received " + messagesNotReceived); - } catch (JMSException e) { - LOG.error("Exception Executing SimpleConsumer: " + getStackTrace(e)); - } - } - - public String getStackTrace(Throwable aThrowable) { - final Writer result = new StringWriter(); - final PrintWriter printWriter = new PrintWriter(result); - aThrowable.printStackTrace(printWriter); - return result.toString(); - } - - public class Producer { - - protected ConnectionFactory factory; - protected transient Connection connection; - protected transient Session session; - protected transient MessageProducer producer; - protected static final int messageSize = 1024; - - public Producer(String brokerURL, String interest, int messageSize, long ttl) throws JMSException { - - factory = new ActiveMQConnectionFactory(brokerURL); - connection = factory.createConnection(); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(session.createTopic(interest)); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - if (ttl > 0) { - producer.setTimeToLive(ttl); + assertTrue("cursorMemoryUsage should be zero", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Long cursorMemoryUsage = (Long) mbeanServer.getAttribute(new ObjectName(theJmxObject), "CursorMemoryUsage"); + LOG.info("cursorMemoryUsage = " + cursorMemoryUsage); + return cursorMemoryUsage.longValue() == 0L; } - } + })); - public void close() throws JMSException { - if (connection != null) { - connection.close(); + // Not sure what the behavior should be here, if the messages + // expired the received count shouldn't equal total message count + assertTrue(totalMsgReceived == initialMaxMsgs + cleanupMsgCount); + } + catch (Exception e) { + LOG.error("Exception Executing DurableSubscriberNonPersistentMessageTest: " + getStackTrace(e)); + fail("Should not throw any exceptions"); + } + } + + // create durable topic consumer and max number of messages + public void createConsumer(String interest, int maxMsgs) { + int messageReceived = 0; + int messagesNotReceived = 0; + + LOG.info("Starting DurableSubscriber"); + + Consumer consumer = null; + + try { + consumer = new Consumer(consumerBrokerURL, interest, clientId); + + for (int i = 0; i < maxMsgs; i++) { + try { + Message msg = consumer.getMessage(messageTimeout); + if (msg != null) { + LOG.debug("Received Message: " + msg.toString()); + messageReceived++; + totalMsgReceived++; + } + else { + LOG.debug("message " + i + " not received"); + messagesNotReceived++; + } + + Thread.sleep(sleep); } - } + catch (InterruptedException ie) { + LOG.debug("Exception: " + ie); + } + } - protected void sendMessage() throws JMSException { - TextMessage textMessage = session.createTextMessage("test message"); + consumer.close(); + + LOG.info("Consumer Finished"); + LOG.info("Received " + messageReceived); + LOG.info("Not Received " + messagesNotReceived); + } + catch (JMSException e) { + LOG.error("Exception Executing SimpleConsumer: " + getStackTrace(e)); + } + } + + public String getStackTrace(Throwable aThrowable) { + final Writer result = new StringWriter(); + final PrintWriter printWriter = new PrintWriter(result); + aThrowable.printStackTrace(printWriter); + return result.toString(); + } + + public class Producer { + + protected ConnectionFactory factory; + protected transient Connection connection; + protected transient Session session; + protected transient MessageProducer producer; + protected static final int messageSize = 1024; + + public Producer(String brokerURL, String interest, int messageSize, long ttl) throws JMSException { + + factory = new ActiveMQConnectionFactory(brokerURL); + connection = factory.createConnection(); + connection.start(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer = session.createProducer(session.createTopic(interest)); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + if (ttl > 0) { + producer.setTimeToLive(ttl); + } + } + + public void close() throws JMSException { + if (connection != null) { + connection.close(); + } + } + + protected void sendMessage() throws JMSException { + TextMessage textMessage = session.createTextMessage("test message"); + producer.send(textMessage); + } + + protected void sendMessages(int count) throws JMSException { + for (int i = 0; i < count; i++) { + TextMessage textMessage = session.createTextMessage(createMessageText(i)); producer.send(textMessage); - } + } + } - protected void sendMessages(int count) throws JMSException { - for (int i = 0; i < count; i++) { - TextMessage textMessage = session.createTextMessage(createMessageText(i)); - producer.send(textMessage); - } - } + private String createMessageText(int index) { + StringBuffer buffer = new StringBuffer(messageSize); + buffer.append("Message: " + index + " sent at: " + new Date()); + if (buffer.length() > messageSize) { + return buffer.substring(0, messageSize); + } + for (int i = buffer.length(); i < messageSize; i++) { + buffer.append(' '); + } + return buffer.toString(); + } - private String createMessageText(int index) { - StringBuffer buffer = new StringBuffer(messageSize); - buffer.append("Message: " + index + " sent at: " + new Date()); - if (buffer.length() > messageSize) { - return buffer.substring(0, messageSize); - } - for (int i = buffer.length(); i < messageSize; i++) { - buffer.append(' '); - } - return buffer.toString(); - } + protected void commitTransaction() throws JMSException { + session.commit(); + } + } - protected void commitTransaction() throws JMSException { - session.commit(); - } - } + public class Consumer { - public class Consumer { + private final ConnectionFactory factory; + private final ActiveMQConnection connection; + private final Session session; + private final MessageConsumer messageConsumer; - private final ConnectionFactory factory; - private final ActiveMQConnection connection; - private final Session session; - private final MessageConsumer messageConsumer; + public Consumer(String brokerURL, String interest, String clientId) throws JMSException { + factory = new ActiveMQConnectionFactory(brokerURL); + connection = (ActiveMQConnection) factory.createConnection(); + connection.setClientID(clientId); + connection.start(); + connection.getPrefetchPolicy().setAll(15); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createTopic(interest); + messageConsumer = session.createDurableSubscriber((Topic) destination, "MyDurableTopic"); + } - public Consumer(String brokerURL, String interest, String clientId) throws JMSException { - factory = new ActiveMQConnectionFactory(brokerURL); - connection = (ActiveMQConnection) factory.createConnection(); - connection.setClientID(clientId); - connection.start(); - connection.getPrefetchPolicy().setAll(15); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createTopic(interest); - messageConsumer = session.createDurableSubscriber((Topic) destination, "MyDurableTopic"); - } + public void deleteAllMessages() throws JMSException { + while (getMessage(500) != null) { + // empty queue + } + } - public void deleteAllMessages() throws JMSException { - while (getMessage(500) != null) { - // empty queue - } - } + public Message getMessage(int timeout) throws JMSException { + return messageConsumer.receive(timeout); + } - public Message getMessage(int timeout) throws JMSException { - return messageConsumer.receive(timeout); - } + public void close() throws JMSException { + if (messageConsumer != null) { + messageConsumer.close(); + } + if (session != null) { + session.close(); + } + if (connection != null) { + connection.close(); + } + } - public void close() throws JMSException { - if (messageConsumer != null) { - messageConsumer.close(); - } - if (session != null) { - session.close(); - } - if (connection != null) { - connection.close(); - } - } - - public Session getSession() { - return session; - } - } + public Session getSession() { + return session; + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriberWithNetworkDisconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriberWithNetworkDisconnectTest.java index 147d29566d..62ddc8c933 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriberWithNetworkDisconnectTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriberWithNetworkDisconnectTest.java @@ -27,7 +27,9 @@ import javax.jms.MessageListener; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; + import junit.framework.Test; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.JmsMultipleBrokersTestSupport; import org.apache.activemq.broker.BrokerService; @@ -40,195 +42,208 @@ import org.apache.activemq.util.Wait; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - public class DurableSubscriberWithNetworkDisconnectTest extends JmsMultipleBrokersTestSupport { - private static final Log LOG = LogFactory.getLog(DurableSubscriberWithNetworkDisconnectTest.class); - private static final int NETWORK_DOWN_TIME = 10000; - private static final String HUB = "HubBroker"; - private static final String SPOKE = "SpokeBroker"; - private SocketProxy socketProxy; - private long networkDownTimeStart; - private long inactiveDuration = 1000; - private long receivedMsgs = 0; - private boolean useSocketProxy = true; - protected static final int MESSAGE_COUNT = 200; - public boolean useDuplexNetworkBridge = true; - public boolean simulateStalledNetwork; - public boolean dynamicOnly = true; - public long networkTTL = 3; - public boolean exponentialBackOff; - public boolean failover = false; - public boolean inactivity = true; - public void initCombosForTestSendOnAReceiveOnBWithTransportDisconnect() { - addCombinationValues("failover", new Object[]{Boolean.FALSE, Boolean.TRUE}); - } + private static final Log LOG = LogFactory.getLog(DurableSubscriberWithNetworkDisconnectTest.class); + private static final int NETWORK_DOWN_TIME = 10000; + private static final String HUB = "HubBroker"; + private static final String SPOKE = "SpokeBroker"; + private SocketProxy socketProxy; + private long networkDownTimeStart; + private long inactiveDuration = 1000; + private long receivedMsgs = 0; + private boolean useSocketProxy = true; + protected static final int MESSAGE_COUNT = 200; + public boolean useDuplexNetworkBridge = true; + public boolean simulateStalledNetwork; + public boolean dynamicOnly = true; + public long networkTTL = 3; + public boolean exponentialBackOff; + public boolean failover = false; + public boolean inactivity = true; - public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception { - bridgeBrokers(SPOKE, HUB); + public void initCombosForTestSendOnAReceiveOnBWithTransportDisconnect() { + addCombinationValues("failover", new Object[]{Boolean.FALSE, Boolean.TRUE}); + } - startAllBrokers(); + public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception { + bridgeBrokers(SPOKE, HUB); - // 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); + startAllBrokers(); - ActiveMQTopic topic = new ActiveMQTopic("TEST.FOO"); - String consumerName = "consumerName"; + // 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); - // 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(); - } + 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()); } - }); - - // 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); + catch (JMSException e) { + e.printStackTrace(); } - 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; + // 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(); } - }); - - 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(); - } - - @Override - protected void startAllBrokers() throws Exception { - // Ensure HUB is started first so bridge will be active from the get go - BrokerItem brokerItem = brokers.get(HUB); - brokerItem.broker.start(); - brokerItem = brokers.get(SPOKE); - brokerItem.broker.start(); - sleep(600); - } - - public void setUp() throws Exception { - networkDownTimeStart = 0; - inactiveDuration = 1000; - useSocketProxy = true; - receivedMsgs = 0; - super.setAutoFail(true); - super.setUp(); - final String options = "?persistent=true&useJmx=false&deleteAllMessagesOnStartup=true"; - createBroker(new URI("broker:(tcp://localhost:61617)/" + HUB + options)); - createBroker(new URI("broker:(tcp://localhost:61616)/" + SPOKE + options)); - } - - public void tearDown() throws Exception { - super.tearDown(); - if (socketProxy != null) { - socketProxy.close(); - } - } - - public static Test suite() { - return suite(DurableSubscriberWithNetworkDisconnectTest.class); - } - - private void sleep(int milliSecondTime) { - try { - Thread.sleep(milliSecondTime); - } catch (InterruptedException igonred) { - } - } - - @Override - protected NetworkConnector bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker, boolean l_dynamicOnly, int networkTTL, boolean l_conduit, boolean l_failover) throws Exception { - List transportConnectors = remoteBroker.getTransportConnectors(); - URI remoteURI; - if (!transportConnectors.isEmpty()) { - remoteURI = ((TransportConnector) transportConnectors.get(0)).getConnectUri(); - if (useSocketProxy) { - socketProxy = new SocketProxy(remoteURI); - remoteURI = socketProxy.getUrl(); + else { + socketProxy.close(); } - String options = ""; - if (failover) { - options = "static:(failover:(" + remoteURI; - } else { - options = "static:(" + remoteURI; + networkDownTimeStart = System.currentTimeMillis(); + } + else if (networkDownTimeStart > 0) { + // restart after NETWORK_DOWN_TIME seconds + sleep(NETWORK_DOWN_TIME); + networkDownTimeStart = 0; + if (simulateStalledNetwork) { + socketProxy.goOn(); } - if (inactivity) { - options += "?wireFormat.maxInactivityDuration=" + inactiveDuration + "&wireFormat.maxInactivityDurationInitalDelay=" + inactiveDuration + ")"; - } else { - options += ")"; + 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); + } - if (failover) { - options += "?maxReconnectAttempts=0)"; - } + LOG.info("waiting for messages to flow"); + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return receivedMsgs >= MESSAGE_COUNT; + } + }); - options += "?useExponentialBackOff=" + exponentialBackOff; - DiscoveryNetworkConnector connector = new DiscoveryNetworkConnector(new URI(options)); - connector.setDynamicOnly(dynamicOnly); - connector.setNetworkTTL(networkTTL); - localBroker.addNetworkConnector(connector); - maxSetupTime = 2000; - if (useDuplexNetworkBridge) { - connector.setDuplex(true); - } - return connector; - } else { - throw new Exception("Remote broker has no registered connectors."); - } - } + 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(); + } + + @Override + protected void startAllBrokers() throws Exception { + // Ensure HUB is started first so bridge will be active from the get go + BrokerItem brokerItem = brokers.get(HUB); + brokerItem.broker.start(); + brokerItem = brokers.get(SPOKE); + brokerItem.broker.start(); + sleep(600); + } + + public void setUp() throws Exception { + networkDownTimeStart = 0; + inactiveDuration = 1000; + useSocketProxy = true; + receivedMsgs = 0; + super.setAutoFail(true); + super.setUp(); + final String options = "?persistent=true&useJmx=false&deleteAllMessagesOnStartup=true"; + createBroker(new URI("broker:(tcp://localhost:61617)/" + HUB + options)); + createBroker(new URI("broker:(tcp://localhost:61616)/" + SPOKE + options)); + } + + public void tearDown() throws Exception { + super.tearDown(); + if (socketProxy != null) { + socketProxy.close(); + } + } + + public static Test suite() { + return suite(DurableSubscriberWithNetworkDisconnectTest.class); + } + + private void sleep(int milliSecondTime) { + try { + Thread.sleep(milliSecondTime); + } + catch (InterruptedException igonred) { + } + } + + @Override + protected NetworkConnector bridgeBrokers(BrokerService localBroker, + BrokerService remoteBroker, + boolean l_dynamicOnly, + int networkTTL, + boolean l_conduit, + boolean l_failover) throws Exception { + List transportConnectors = remoteBroker.getTransportConnectors(); + URI remoteURI; + if (!transportConnectors.isEmpty()) { + remoteURI = ((TransportConnector) transportConnectors.get(0)).getConnectUri(); + if (useSocketProxy) { + socketProxy = new SocketProxy(remoteURI); + remoteURI = socketProxy.getUrl(); + } + String options = ""; + if (failover) { + options = "static:(failover:(" + remoteURI; + } + else { + options = "static:(" + remoteURI; + } + if (inactivity) { + options += "?wireFormat.maxInactivityDuration=" + inactiveDuration + "&wireFormat.maxInactivityDurationInitalDelay=" + inactiveDuration + ")"; + } + else { + options += ")"; + } + + if (failover) { + options += "?maxReconnectAttempts=0)"; + } + + options += "?useExponentialBackOff=" + exponentialBackOff; + DiscoveryNetworkConnector connector = new DiscoveryNetworkConnector(new URI(options)); + connector.setDynamicOnly(dynamicOnly); + connector.setNetworkTTL(networkTTL); + localBroker.addNetworkConnector(connector); + maxSetupTime = 2000; + if (useDuplexNetworkBridge) { + connector.setDuplex(true); + } + return connector; + } + else { + throw new Exception("Remote broker has no registered connectors."); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriberWithNetworkRestartTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriberWithNetworkRestartTest.java index 3799c6cc7a..eaf05355b1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriberWithNetworkRestartTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriberWithNetworkRestartTest.java @@ -26,6 +26,7 @@ import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; import javax.management.ObjectName; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.JmsMultipleBrokersTestSupport; import org.apache.activemq.broker.BrokerService; @@ -37,195 +38,196 @@ import org.apache.activemq.util.Wait; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - import static org.junit.Assume.assumeNotNull; - public class DurableSubscriberWithNetworkRestartTest extends JmsMultipleBrokersTestSupport { - private static final Log LOG = LogFactory.getLog(DurableSubscriberWithNetworkRestartTest.class); - private static final String HUB = "HubBroker"; - private static final String SPOKE = "SpokeBroker"; - protected static final int MESSAGE_COUNT = 10; - public boolean dynamicOnly = false; - public void testSendOnAReceiveOnBWithTransportDisconnectDynamicOnly() throws Exception { - dynamicOnly = true; - try { - testSendOnAReceiveOnBWithTransportDisconnect(); - } finally { - dynamicOnly = false; - } - } + private static final Log LOG = LogFactory.getLog(DurableSubscriberWithNetworkRestartTest.class); + private static final String HUB = "HubBroker"; + private static final String SPOKE = "SpokeBroker"; + protected static final int MESSAGE_COUNT = 10; + public boolean dynamicOnly = false; - public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception { - bridge(SPOKE, HUB); - startAllBrokers(); + public void testSendOnAReceiveOnBWithTransportDisconnectDynamicOnly() throws Exception { + dynamicOnly = true; + try { + testSendOnAReceiveOnBWithTransportDisconnect(); + } + finally { + dynamicOnly = false; + } + } - verifyDuplexBridgeMbean(); + public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception { + bridge(SPOKE, HUB); + startAllBrokers(); - // 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); + verifyDuplexBridgeMbean(); - ActiveMQTopic topic = new ActiveMQTopic("TEST.FOO"); - String consumerName = "consumerName"; + // 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); - // Setup consumers - MessageConsumer remoteConsumer = sesHub.createDurableSubscriber(topic, consumerName); - sleep(1000); - remoteConsumer.close(); + ActiveMQTopic topic = new ActiveMQTopic("TEST.FOO"); + String consumerName = "consumerName"; - // Setup producer - MessageProducer localProducer = sesSpoke.createProducer(topic); - localProducer.setDeliveryMode(DeliveryMode.PERSISTENT); + // Setup consumers + MessageConsumer remoteConsumer = sesHub.createDurableSubscriber(topic, consumerName); + sleep(1000); + remoteConsumer.close(); - 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(); + // Setup producer + MessageProducer localProducer = sesSpoke.createProducer(topic); + localProducer.setDeliveryMode(DeliveryMode.PERSISTENT); - 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); + 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(); - 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); - } - })); - } - } + 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); - private void verifyDuplexBridgeMbean() throws Exception { - assertEquals(1, countMbeans( brokers.get(HUB).broker, "networkBridge", 5000)); - } - - private int countMbeans(BrokerService broker, String type, int timeout) throws Exception { - final long expiryTime = System.currentTimeMillis() + timeout; - - if (!type.contains("=")) { - type = type + "=*"; - } - - final ObjectName beanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=" - + broker.getBrokerName() + "," + type +",*"); - Set mbeans = null; - int count = 0; - do { - if (timeout > 0) { - Thread.sleep(100); + 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); } + })); + } + } - mbeans = broker.getManagementContext().queryNames(beanName, null); - if (mbeans != null) { - count = mbeans.size(); - LOG.info("Found: " + count + ", matching type: " +type); - for (ObjectName objectName : mbeans) { - LOG.info("" + objectName); - } - //} else { - //logAllMbeans(broker); + private void verifyDuplexBridgeMbean() throws Exception { + assertEquals(1, countMbeans(brokers.get(HUB).broker, "networkBridge", 5000)); + } + + private int countMbeans(BrokerService broker, String type, int timeout) throws Exception { + final long expiryTime = System.currentTimeMillis() + timeout; + + if (!type.contains("=")) { + type = type + "=*"; + } + + final ObjectName beanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=" + broker.getBrokerName() + "," + type + ",*"); + Set mbeans = null; + int count = 0; + do { + if (timeout > 0) { + Thread.sleep(100); + } + + mbeans = broker.getManagementContext().queryNames(beanName, null); + if (mbeans != null) { + count = mbeans.size(); + LOG.info("Found: " + count + ", matching type: " + type); + for (ObjectName objectName : mbeans) { + LOG.info("" + objectName); } - } while ((mbeans == null || mbeans.isEmpty()) && expiryTime > System.currentTimeMillis()); + //} else { + //logAllMbeans(broker); + } + } while ((mbeans == null || mbeans.isEmpty()) && expiryTime > System.currentTimeMillis()); - // If port 1099 is in use when the Broker starts, starting the jmx connector - // will fail. So, if we have no mbsc to query, skip the test. - if (timeout > 0) { - assumeNotNull(mbeans); - } + // If port 1099 is in use when the Broker starts, starting the jmx connector + // will fail. So, if we have no mbsc to query, skip the test. + if (timeout > 0) { + assumeNotNull(mbeans); + } - return count; + return count; - } + } - private void logAllMbeans(BrokerService broker) throws MalformedURLException { - try { - // trace all existing MBeans - Set all = broker.getManagementContext().queryNames(null, null); - LOG.info("Total MBean count=" + all.size()); - for (Object o : all) { - //ObjectInstance bean = (ObjectInstance)o; - LOG.info(o); - } - } catch (Exception ignored) { - LOG.warn("getMBeanServer ex: " + ignored); - } - } + private void logAllMbeans(BrokerService broker) throws MalformedURLException { + try { + // trace all existing MBeans + Set all = broker.getManagementContext().queryNames(null, null); + LOG.info("Total MBean count=" + all.size()); + for (Object o : all) { + //ObjectInstance bean = (ObjectInstance)o; + LOG.info(o); + } + } + catch (Exception ignored) { + LOG.warn("getMBeanServer ex: " + ignored); + } + } - public NetworkConnector bridge(String from, String to) throws Exception { - NetworkConnector networkConnector = bridgeBrokers(from, to, dynamicOnly, -1, true); - networkConnector.setSuppressDuplicateQueueSubscriptions(true); - networkConnector.setDecreaseNetworkConsumerPriority(true); - networkConnector.setConsumerTTL(1); - networkConnector.setDuplex(true); - return networkConnector; - } + public NetworkConnector bridge(String from, String to) throws Exception { + NetworkConnector networkConnector = bridgeBrokers(from, to, dynamicOnly, -1, true); + networkConnector.setSuppressDuplicateQueueSubscriptions(true); + networkConnector.setDecreaseNetworkConsumerPriority(true); + networkConnector.setConsumerTTL(1); + networkConnector.setDuplex(true); + return networkConnector; + } - @Override - protected void startAllBrokers() throws Exception { - // Ensure HUB is started first so bridge will be active from the get go - BrokerItem brokerItem = brokers.get(HUB); - brokerItem.broker.start(); - brokerItem = brokers.get(SPOKE); - brokerItem.broker.start(); - sleep(600); - } + @Override + protected void startAllBrokers() throws Exception { + // Ensure HUB is started first so bridge will be active from the get go + BrokerItem brokerItem = brokers.get(HUB); + brokerItem.broker.start(); + brokerItem = brokers.get(SPOKE); + brokerItem.broker.start(); + sleep(600); + } - public void setUp() throws Exception { - super.setAutoFail(false); - super.setUp(); - createBrokers(true); - } + public void setUp() throws Exception { + super.setAutoFail(false); + super.setUp(); + createBrokers(true); + } - private void createBrokers(boolean del) throws Exception { - final String options = "?persistent=true&useJmx=true&deleteAllMessagesOnStartup=" + del; - createBroker(new URI("broker:(tcp://localhost:61617)/" + HUB + options)); - createBroker(new URI("broker:(tcp://localhost:61616)/" + SPOKE + options)); - } + private void createBrokers(boolean del) throws Exception { + final String options = "?persistent=true&useJmx=true&deleteAllMessagesOnStartup=" + del; + createBroker(new URI("broker:(tcp://localhost:61617)/" + HUB + options)); + createBroker(new URI("broker:(tcp://localhost:61616)/" + SPOKE + options)); + } - protected void configureBroker(BrokerService broker) { - broker.setKeepDurableSubsActive(false); - broker.getManagementContext().setCreateConnector(false); - PolicyMap defaultPolcyMap = new PolicyMap(); - PolicyEntry defaultPolicy = new PolicyEntry(); - //defaultPolicy.setUseCache(false); - if (broker.getBrokerName().equals(HUB)) { - defaultPolicy.setStoreUsageHighWaterMark(2); - broker.getSystemUsage().getStoreUsage().setLimit(1*1024*1024); - } - defaultPolcyMap.setDefaultEntry(defaultPolicy); - broker.setDestinationPolicy(defaultPolcyMap); - broker.getSystemUsage().getMemoryUsage().setLimit(100*1024*1024); - } + protected void configureBroker(BrokerService broker) { + broker.setKeepDurableSubsActive(false); + broker.getManagementContext().setCreateConnector(false); + PolicyMap defaultPolcyMap = new PolicyMap(); + PolicyEntry defaultPolicy = new PolicyEntry(); + //defaultPolicy.setUseCache(false); + if (broker.getBrokerName().equals(HUB)) { + defaultPolicy.setStoreUsageHighWaterMark(2); + broker.getSystemUsage().getStoreUsage().setLimit(1 * 1024 * 1024); + } + defaultPolcyMap.setDefaultEntry(defaultPolicy); + broker.setDestinationPolicy(defaultPolcyMap); + broker.getSystemUsage().getMemoryUsage().setLimit(100 * 1024 * 1024); + } - public void tearDown() throws Exception { - super.tearDown(); - } + public void tearDown() throws Exception { + super.tearDown(); + } - private void sleep(int milliSecondTime) { - try { - Thread.sleep(milliSecondTime); - } catch (InterruptedException igonred) { - } - } + private void sleep(int milliSecondTime) { + try { + Thread.sleep(milliSecondTime); + } + catch (InterruptedException igonred) { + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionActivationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionActivationTest.java index 6156657081..969211f18f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionActivationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionActivationTest.java @@ -31,92 +31,92 @@ import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; public class DurableSubscriptionActivationTest extends org.apache.activemq.TestSupport { - private BrokerService broker; - private Connection connection; - private ActiveMQTopic topic; + private BrokerService broker; + private Connection connection; + private ActiveMQTopic topic; - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://" + getName()); - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory("vm://" + getName()); + } - protected Connection createConnection() throws Exception { - Connection rc = super.createConnection(); - rc.setClientID(getName()); - return rc; - } + protected Connection createConnection() throws Exception { + Connection rc = super.createConnection(); + rc.setClientID(getName()); + return rc; + } - protected void setUp() throws Exception { - topic = (ActiveMQTopic) createDestination(); - createBroker(true); - super.setUp(); - } + protected void setUp() throws Exception { + topic = (ActiveMQTopic) createDestination(); + createBroker(true); + super.setUp(); + } - protected void tearDown() throws Exception { - super.tearDown(); - destroyBroker(); - } + protected void tearDown() throws Exception { + super.tearDown(); + destroyBroker(); + } - protected void restartBroker() throws Exception { - destroyBroker(); - createBroker(false); - } + protected void restartBroker() throws Exception { + destroyBroker(); + createBroker(false); + } - private void createBroker(boolean delete) throws Exception { - broker = BrokerFactory.createBroker("broker:(vm://localhost)"); - broker.setKeepDurableSubsActive(true); - broker.setPersistent(true); - broker.setDeleteAllMessagesOnStartup(delete); - KahaDBPersistenceAdapter kahadb = new KahaDBPersistenceAdapter(); - kahadb.setDirectory(new File("activemq-data/" + getName() + "-kahadb")); - kahadb.setJournalMaxFileLength(500 * 1024); - broker.setPersistenceAdapter(kahadb); - broker.setBrokerName(getName()); + private void createBroker(boolean delete) throws Exception { + broker = BrokerFactory.createBroker("broker:(vm://localhost)"); + broker.setKeepDurableSubsActive(true); + broker.setPersistent(true); + broker.setDeleteAllMessagesOnStartup(delete); + KahaDBPersistenceAdapter kahadb = new KahaDBPersistenceAdapter(); + kahadb.setDirectory(new File("activemq-data/" + getName() + "-kahadb")); + kahadb.setJournalMaxFileLength(500 * 1024); + broker.setPersistenceAdapter(kahadb); + broker.setBrokerName(getName()); - // only if we pre-create the destinations - broker.setDestinations(new ActiveMQDestination[]{topic}); + // only if we pre-create the destinations + broker.setDestinations(new ActiveMQDestination[]{topic}); - broker.start(); - broker.waitUntilStarted(); + broker.start(); + broker.waitUntilStarted(); - connection = createConnection(); - } + connection = createConnection(); + } - private void destroyBroker() throws Exception { - if (connection != null) - connection.close(); - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - } + private void destroyBroker() throws Exception { + if (connection != null) + connection.close(); + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + } - public void testActivateWithExistingTopic() throws Exception { - // create durable subscription - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId"); + public void testActivateWithExistingTopic() throws Exception { + // create durable subscription + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId"); - Destination d = broker.getDestination(topic); - assertTrue("More than one consumer found: " + d.getConsumers().size(), d.getConsumers().size() == 1); + Destination d = broker.getDestination(topic); + assertTrue("More than one consumer found: " + d.getConsumers().size(), d.getConsumers().size() == 1); - // restart the broker - restartBroker(); + // restart the broker + restartBroker(); - d = broker.getDestination(topic); - assertTrue("More than one consumer found: " + d.getConsumers().size(), d.getConsumers().size() == 1); + d = broker.getDestination(topic); + assertTrue("More than one consumer found: " + d.getConsumers().size(), d.getConsumers().size() == 1); - // activate - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId"); + // activate + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId"); - assertTrue("More than one consumer found: " + d.getConsumers().size(), d.getConsumers().size() == 1); + assertTrue("More than one consumer found: " + d.getConsumers().size(), d.getConsumers().size() == 1); - // re-activate - connection.close(); - connection = createConnection(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId"); + // re-activate + connection.close(); + connection = createConnection(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId"); - assertTrue("More than one consumer found: " + d.getConsumers().size(), d.getConsumers().size() == 1); - } + assertTrue("More than one consumer found: " + d.getConsumers().size(), d.getConsumers().size() == 1); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionHangTestCase.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionHangTestCase.java index bef912a514..d7c40fdca2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionHangTestCase.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionHangTestCase.java @@ -26,6 +26,7 @@ import javax.jms.Topic; import javax.jms.TopicConnection; import javax.jms.TopicSession; import javax.jms.TopicSubscriber; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.region.policy.PolicyEntry; @@ -37,99 +38,95 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import static org.junit.Assert.assertNotNull; public class DurableSubscriptionHangTestCase { - private static final Logger LOG = LoggerFactory.getLogger(DurableSubscriptionHangTestCase.class); - final static String brokerName = "DurableSubscriptionHangTestCase"; - final static String clientID = "myId"; - private static final String topicName = "myTopic"; - private static final String durableSubName = "mySub"; - BrokerService brokerService; - @Before - public void startBroker() throws Exception { - brokerService = new BrokerService(); - brokerService.setDeleteAllMessagesOnStartup(true); - brokerService.setBrokerName(brokerName); - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setExpireMessagesPeriod(5000); - policyMap.setDefaultEntry(defaultEntry); - brokerService.setDestinationPolicy(policyMap); - brokerService.start(); - } + private static final Logger LOG = LoggerFactory.getLogger(DurableSubscriptionHangTestCase.class); + final static String brokerName = "DurableSubscriptionHangTestCase"; + final static String clientID = "myId"; + private static final String topicName = "myTopic"; + private static final String durableSubName = "mySub"; + BrokerService brokerService; - @After - public void brokerStop() throws Exception { - brokerService.stop(); - } + @Before + public void startBroker() throws Exception { + brokerService = new BrokerService(); + brokerService.setDeleteAllMessagesOnStartup(true); + brokerService.setBrokerName(brokerName); + PolicyMap policyMap = new PolicyMap(); + PolicyEntry defaultEntry = new PolicyEntry(); + defaultEntry.setExpireMessagesPeriod(5000); + policyMap.setDefaultEntry(defaultEntry); + brokerService.setDestinationPolicy(policyMap); + brokerService.start(); + } - @Test - public void testHanging() throws Exception - { - registerDurableSubscription(); - produceExpiredAndOneNonExpiredMessages(); - TimeUnit.SECONDS.sleep(10); // make sure messages are expired - Message message = collectMessagesFromDurableSubscriptionForOneMinute(); - LOG.info("got message:" + message); - assertNotNull("Unable to read unexpired message", message); - } + @After + public void brokerStop() throws Exception { + brokerService.stop(); + } - private void produceExpiredAndOneNonExpiredMessages() throws JMSException { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + brokerName); - TopicConnection connection = connectionFactory.createTopicConnection(); - TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic(topicName); - MessageProducer producer = session.createProducer(topic); - producer.setTimeToLive(TimeUnit.SECONDS.toMillis(1)); - for(int i=0; i<40000; i++) - { - sendRandomMessage(session, producer); - } - producer.setTimeToLive(TimeUnit.DAYS.toMillis(1)); - sendRandomMessage(session, producer); - connection.close(); - LOG.info("produceExpiredAndOneNonExpiredMessages done"); - } + @Test + public void testHanging() throws Exception { + registerDurableSubscription(); + produceExpiredAndOneNonExpiredMessages(); + TimeUnit.SECONDS.sleep(10); // make sure messages are expired + Message message = collectMessagesFromDurableSubscriptionForOneMinute(); + LOG.info("got message:" + message); + assertNotNull("Unable to read unexpired message", message); + } - private void registerDurableSubscription() throws JMSException - { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + brokerName); - TopicConnection connection = connectionFactory.createTopicConnection(); - connection.setClientID(clientID); - TopicSession topicSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic = topicSession.createTopic(topicName); - TopicSubscriber durableSubscriber = topicSession.createDurableSubscriber(topic, durableSubName); - connection.start(); - durableSubscriber.close(); - connection.close(); - LOG.info("Durable Sub Registered"); - } + private void produceExpiredAndOneNonExpiredMessages() throws JMSException { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + brokerName); + TopicConnection connection = connectionFactory.createTopicConnection(); + TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); + Topic topic = session.createTopic(topicName); + MessageProducer producer = session.createProducer(topic); + producer.setTimeToLive(TimeUnit.SECONDS.toMillis(1)); + for (int i = 0; i < 40000; i++) { + sendRandomMessage(session, producer); + } + producer.setTimeToLive(TimeUnit.DAYS.toMillis(1)); + sendRandomMessage(session, producer); + connection.close(); + LOG.info("produceExpiredAndOneNonExpiredMessages done"); + } - private Message collectMessagesFromDurableSubscriptionForOneMinute() throws Exception - { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + brokerName); - TopicConnection connection = connectionFactory.createTopicConnection(); + private void registerDurableSubscription() throws JMSException { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + brokerName); + TopicConnection connection = connectionFactory.createTopicConnection(); + connection.setClientID(clientID); + TopicSession topicSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); + Topic topic = topicSession.createTopic(topicName); + TopicSubscriber durableSubscriber = topicSession.createDurableSubscriber(topic, durableSubName); + connection.start(); + durableSubscriber.close(); + connection.close(); + LOG.info("Durable Sub Registered"); + } - connection.setClientID(clientID); - TopicSession topicSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic = topicSession.createTopic(topicName); - connection.start(); - TopicSubscriber subscriber = topicSession.createDurableSubscriber(topic, durableSubName); - LOG.info("About to receive messages"); - Message message = subscriber.receive(120000); - subscriber.close(); - connection.close(); - LOG.info("collectMessagesFromDurableSubscriptionForOneMinute done"); + private Message collectMessagesFromDurableSubscriptionForOneMinute() throws Exception { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + brokerName); + TopicConnection connection = connectionFactory.createTopicConnection(); - return message; - } + connection.setClientID(clientID); + TopicSession topicSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); + Topic topic = topicSession.createTopic(topicName); + connection.start(); + TopicSubscriber subscriber = topicSession.createDurableSubscriber(topic, durableSubName); + LOG.info("About to receive messages"); + Message message = subscriber.receive(120000); + subscriber.close(); + connection.close(); + LOG.info("collectMessagesFromDurableSubscriptionForOneMinute done"); - private void sendRandomMessage(TopicSession session, MessageProducer producer) throws JMSException { - TextMessage textMessage = session.createTextMessage(); - textMessage.setText(RandomStringUtils.random(500, "abcdefghijklmnopqrstuvwxyz")); - producer.send(textMessage); - } + return message; + } + + private void sendRandomMessage(TopicSession session, MessageProducer producer) throws JMSException { + TextMessage textMessage = session.createTextMessage(); + textMessage.setText(RandomStringUtils.random(500, "abcdefghijklmnopqrstuvwxyz")); + producer.send(textMessage); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline1Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline1Test.java index 47fdac01d4..2f69b4d103 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline1Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline1Test.java @@ -37,211 +37,211 @@ import static org.junit.Assert.assertEquals; @RunWith(value = Parameterized.class) public class DurableSubscriptionOffline1Test extends DurableSubscriptionOfflineTestBase { - private static final Logger LOG = LoggerFactory.getLogger(DurableSubscriptionOffline1Test.class); + private static final Logger LOG = LoggerFactory.getLogger(DurableSubscriptionOffline1Test.class); - @Parameterized.Parameters(name = "{0}-{1}") - public static Collection getTestParameters() { - String osName = System.getProperty("os.name"); - LOG.debug("Running on [" + osName + "]"); + @Parameterized.Parameters(name = "{0}-{1}") + public static Collection getTestParameters() { + String osName = System.getProperty("os.name"); + LOG.debug("Running on [" + osName + "]"); - List persistenceAdapterChoices = new ArrayList(); + List persistenceAdapterChoices = new ArrayList(); - persistenceAdapterChoices.add(PersistenceAdapterChoice.KahaDB); - persistenceAdapterChoices.add(PersistenceAdapterChoice.JDBC); - if (!osName.equalsIgnoreCase("AIX") && !osName.equalsIgnoreCase("SunOS")) { - //choices.add(levelDb); - persistenceAdapterChoices.add(PersistenceAdapterChoice.LevelDB); - } + persistenceAdapterChoices.add(PersistenceAdapterChoice.KahaDB); + persistenceAdapterChoices.add(PersistenceAdapterChoice.JDBC); + if (!osName.equalsIgnoreCase("AIX") && !osName.equalsIgnoreCase("SunOS")) { + //choices.add(levelDb); + persistenceAdapterChoices.add(PersistenceAdapterChoice.LevelDB); + } - List testParameters = new ArrayList(); - Boolean[] booleanValues = {Boolean.FALSE, Boolean.TRUE}; - List booleans = java.util.Arrays.asList(booleanValues); - for (Boolean booleanValue : booleans) { - for (PersistenceAdapterChoice persistenceAdapterChoice : persistenceAdapterChoices) { - Object[] currentChoice = {persistenceAdapterChoice, booleanValue}; - testParameters.add(currentChoice); - } - } + List testParameters = new ArrayList(); + Boolean[] booleanValues = {Boolean.FALSE, Boolean.TRUE}; + List booleans = java.util.Arrays.asList(booleanValues); + for (Boolean booleanValue : booleans) { + for (PersistenceAdapterChoice persistenceAdapterChoice : persistenceAdapterChoices) { + Object[] currentChoice = {persistenceAdapterChoice, booleanValue}; + testParameters.add(currentChoice); + } + } - return testParameters; - } + return testParameters; + } - public DurableSubscriptionOffline1Test(PersistenceAdapterChoice adapter, Boolean usePrioritySupport) { - this.defaultPersistenceAdapter = adapter; - this.usePrioritySupport = usePrioritySupport.booleanValue(); - LOG.debug(">>>> Created with adapter {} usePrioritySupport? {}", defaultPersistenceAdapter, usePrioritySupport); + public DurableSubscriptionOffline1Test(PersistenceAdapterChoice adapter, Boolean usePrioritySupport) { + this.defaultPersistenceAdapter = adapter; + this.usePrioritySupport = usePrioritySupport.booleanValue(); + LOG.debug(">>>> Created with adapter {} usePrioritySupport? {}", defaultPersistenceAdapter, usePrioritySupport); - } + } - @Test - public void testConsumeOnlyMatchedMessages() throws Exception { - // create durable subscription - Connection con = createConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); + @Test + public void testConsumeOnlyMatchedMessages() throws Exception { + // create durable subscription + Connection con = createConnection(); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + session.close(); + con.close(); - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); + // send messages + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(null); - int sent = 0; - for (int i = 0; i < 10; i++) { - boolean filter = i % 2 == 1; - if (filter) - sent++; - - Message message = session.createMessage(); - message.setStringProperty("filter", filter ? "true" : "false"); - producer.send(topic, message); - } - - session.close(); - con.close(); - - // consume messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); - consumer.setMessageListener(listener); - - Thread.sleep(3 * 1000); - - session.close(); - con.close(); - - assertEquals(sent, listener.count); - } - - @Test - public void testVerifyAllConsumedAreAcked() throws Exception { - // create durable subscription - Connection con = createConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); - - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); - - int sent = 0; - for (int i = 0; i < 10; i++) { + int sent = 0; + for (int i = 0; i < 10; i++) { + boolean filter = i % 2 == 1; + if (filter) sent++; - Message message = session.createMessage(); - message.setStringProperty("filter", "true"); - producer.send(topic, message); - } - Thread.sleep(1 * 1000); + Message message = session.createMessage(); + message.setStringProperty("filter", filter ? "true" : "false"); + producer.send(topic, message); + } - session.close(); - con.close(); + session.close(); + con.close(); - // consume messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); - consumer.setMessageListener(listener); + // consume messages + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); + consumer.setMessageListener(listener); - Thread.sleep(3 * 1000); + Thread.sleep(3 * 1000); - session.close(); - con.close(); + session.close(); + con.close(); - LOG.info("Consumed: " + listener.count); - assertEquals(sent, listener.count); + assertEquals(sent, listener.count); + } - // consume messages again, should not get any - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - listener = new DurableSubscriptionOfflineTestListener(); - consumer.setMessageListener(listener); + @Test + public void testVerifyAllConsumedAreAcked() throws Exception { + // create durable subscription + Connection con = createConnection(); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + session.close(); + con.close(); - Thread.sleep(3 * 1000); + // send messages + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(null); - session.close(); - con.close(); + int sent = 0; + for (int i = 0; i < 10; i++) { + sent++; + Message message = session.createMessage(); + message.setStringProperty("filter", "true"); + producer.send(topic, message); + } - assertEquals(0, listener.count); - } + Thread.sleep(1 * 1000); - @Test - public void testOfflineSubscriptionCanConsumeAfterOnlineSubs() throws Exception { - Connection con = createConnection("offCli1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); + session.close(); + con.close(); - con = createConnection("offCli2"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); + // consume messages + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); + consumer.setMessageListener(listener); - Connection con2 = createConnection("onlineCli1"); - Session session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer2 = session2.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - DurableSubscriptionOfflineTestListener listener2 = new DurableSubscriptionOfflineTestListener(); - consumer2.setMessageListener(listener2); + Thread.sleep(3 * 1000); - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); + session.close(); + con.close(); - int sent = 0; - for (int i = 0; i < 10; i++) { - sent++; - Message message = session.createMessage(); - message.setStringProperty("filter", "true"); - producer.send(topic, message); - } + LOG.info("Consumed: " + listener.count); + assertEquals(sent, listener.count); - Thread.sleep(1 * 1000); - session.close(); - con.close(); + // consume messages again, should not get any + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + listener = new DurableSubscriptionOfflineTestListener(); + consumer.setMessageListener(listener); - // test online subs - Thread.sleep(3 * 1000); - session2.close(); - con2.close(); - assertEquals(sent, listener2.count); + Thread.sleep(3 * 1000); - // restart broker - broker.stop(); - createBroker(false /*deleteAllMessages*/); + session.close(); + con.close(); - // test offline - con = createConnection("offCli1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + assertEquals(0, listener.count); + } - Connection con3 = createConnection("offCli2"); - Session session3 = con3.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer3 = session3.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + @Test + public void testOfflineSubscriptionCanConsumeAfterOnlineSubs() throws Exception { + Connection con = createConnection("offCli1"); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + session.close(); + con.close(); - DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); - consumer.setMessageListener(listener); - DurableSubscriptionOfflineTestListener listener3 = new DurableSubscriptionOfflineTestListener(); - consumer3.setMessageListener(listener3); + con = createConnection("offCli2"); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + session.close(); + con.close(); - Thread.sleep(3 * 1000); + Connection con2 = createConnection("onlineCli1"); + Session session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer2 = session2.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + DurableSubscriptionOfflineTestListener listener2 = new DurableSubscriptionOfflineTestListener(); + consumer2.setMessageListener(listener2); - session.close(); - con.close(); - session3.close(); - con3.close(); + // send messages + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(null); - assertEquals(sent, listener.count); - assertEquals(sent, listener3.count); - } + int sent = 0; + for (int i = 0; i < 10; i++) { + sent++; + Message message = session.createMessage(); + message.setStringProperty("filter", "true"); + producer.send(topic, message); + } + + Thread.sleep(1 * 1000); + session.close(); + con.close(); + + // test online subs + Thread.sleep(3 * 1000); + session2.close(); + con2.close(); + assertEquals(sent, listener2.count); + + // restart broker + broker.stop(); + createBroker(false /*deleteAllMessages*/); + + // test offline + con = createConnection("offCli1"); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + + Connection con3 = createConnection("offCli2"); + Session session3 = con3.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer3 = session3.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + + DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); + consumer.setMessageListener(listener); + DurableSubscriptionOfflineTestListener listener3 = new DurableSubscriptionOfflineTestListener(); + consumer3.setMessageListener(listener3); + + Thread.sleep(3 * 1000); + + session.close(); + con.close(); + session3.close(); + con3.close(); + + assertEquals(sent, listener.count); + assertEquals(sent, listener3.count); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline2Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline2Test.java index 960d9eaebb..a0a4bcd614 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline2Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline2Test.java @@ -37,135 +37,129 @@ import java.util.List; import static org.junit.Assert.*; - @RunWith(value = Parameterized.class) public class DurableSubscriptionOffline2Test extends DurableSubscriptionOfflineTestBase { - private static final Logger LOG = LoggerFactory.getLogger(DurableSubscriptionOffline2Test.class); + private static final Logger LOG = LoggerFactory.getLogger(DurableSubscriptionOffline2Test.class); - @Parameterized.Parameters(name = "{0}") - public static Collection getTestParameters() { - Boolean[] f = {Boolean.FALSE}; - Boolean[] t = {Boolean.TRUE}; - List booleanChoices = new ArrayList(); - booleanChoices.add(f); - booleanChoices.add(t); + @Parameterized.Parameters(name = "{0}") + public static Collection getTestParameters() { + Boolean[] f = {Boolean.FALSE}; + Boolean[] t = {Boolean.TRUE}; + List booleanChoices = new ArrayList(); + booleanChoices.add(f); + booleanChoices.add(t); - return booleanChoices; - } + return booleanChoices; + } - public DurableSubscriptionOffline2Test(Boolean keepDurableSubsActive) { - this.keepDurableSubsActive = keepDurableSubsActive.booleanValue(); + public DurableSubscriptionOffline2Test(Boolean keepDurableSubsActive) { + this.keepDurableSubsActive = keepDurableSubsActive.booleanValue(); - LOG.info(">>>> running {} with keepDurableSubsActive: {}", testName.getMethodName(), this.keepDurableSubsActive); - } + LOG.info(">>>> running {} with keepDurableSubsActive: {}", testName.getMethodName(), this.keepDurableSubsActive); + } + @Test(timeout = 60 * 1000) + public void testJMXCountersWithOfflineSubs() throws Exception { + // create durable subscription 1 + Connection con = createConnection("cliId1"); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId", null, true); + session.close(); + con.close(); - @Test(timeout = 60 * 1000) - public void testJMXCountersWithOfflineSubs() throws Exception { - // create durable subscription 1 - Connection con = createConnection("cliId1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", null, true); - session.close(); - con.close(); + // restart broker + broker.stop(); + createBroker(false /*deleteAllMessages*/); - // restart broker - broker.stop(); - createBroker(false /*deleteAllMessages*/); + // send messages + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(null); - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); + int sent = 0; + for (int i = 0; i < 10; i++) { + sent++; + Message message = session.createMessage(); + producer.send(topic, message); + } + session.close(); + con.close(); - int sent = 0; - for (int i = 0; i < 10; i++) { - sent++; - Message message = session.createMessage(); - producer.send(topic, message); - } - session.close(); - con.close(); + // consume some messages + con = createConnection("cliId1"); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", null, true); - // consume some messages - con = createConnection("cliId1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", null, true); + for (int i = 0; i < sent / 2; i++) { + Message m = consumer.receive(4000); + assertNotNull("got message: " + i, m); + LOG.info("Got :" + i + ", " + m); + } - for (int i=0; i getTestParameters() { - String osName = System.getProperty("os.name"); - LOG.debug("Running on [" + osName + "]"); + @Parameterized.Parameters(name = "{0}") + public static Collection getTestParameters() { + String osName = System.getProperty("os.name"); + LOG.debug("Running on [" + osName + "]"); - PersistenceAdapterChoice[] kahaDb = {PersistenceAdapterChoice.KahaDB}; - PersistenceAdapterChoice[] jdbc = {PersistenceAdapterChoice.JDBC}; - List choices = new ArrayList(); - choices.add(kahaDb); - choices.add(jdbc); - if (!osName.equalsIgnoreCase("AIX") && !osName.equalsIgnoreCase("SunOS")) { - PersistenceAdapterChoice[] levelDb = {PersistenceAdapterChoice.LevelDB}; - choices.add(levelDb); - } + PersistenceAdapterChoice[] kahaDb = {PersistenceAdapterChoice.KahaDB}; + PersistenceAdapterChoice[] jdbc = {PersistenceAdapterChoice.JDBC}; + List choices = new ArrayList(); + choices.add(kahaDb); + choices.add(jdbc); + if (!osName.equalsIgnoreCase("AIX") && !osName.equalsIgnoreCase("SunOS")) { + PersistenceAdapterChoice[] levelDb = {PersistenceAdapterChoice.LevelDB}; + choices.add(levelDb); + } - return choices; - } + return choices; + } - public DurableSubscriptionOffline3Test(PersistenceAdapterChoice persistenceAdapterChoice) { - this.defaultPersistenceAdapter = persistenceAdapterChoice; + public DurableSubscriptionOffline3Test(PersistenceAdapterChoice persistenceAdapterChoice) { + this.defaultPersistenceAdapter = persistenceAdapterChoice; - LOG.info(">>>> running {} with persistenceAdapterChoice: {}", testName.getMethodName(), this.defaultPersistenceAdapter); - } + LOG.info(">>>> running {} with persistenceAdapterChoice: {}", testName.getMethodName(), this.defaultPersistenceAdapter); + } - @Test(timeout = 60 * 1000) - public void testInterleavedOfflineSubscriptionCanConsume() throws Exception { - // create durable subscription 1 - Connection con = createConnection("cliId1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); + @Test(timeout = 60 * 1000) + public void testInterleavedOfflineSubscriptionCanConsume() throws Exception { + // create durable subscription 1 + Connection con = createConnection("cliId1"); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + session.close(); + con.close(); - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); + // send messages + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(null); - int sent = 0; - for (int i = 0; i < 10; i++) { - sent++; - Message message = session.createMessage(); - message.setStringProperty("filter", "true"); - producer.send(topic, message); - } + int sent = 0; + for (int i = 0; i < 10; i++) { + sent++; + Message message = session.createMessage(); + message.setStringProperty("filter", "true"); + producer.send(topic, message); + } - Thread.sleep(1 * 1000); + Thread.sleep(1 * 1000); - // create durable subscription 2 - Connection con2 = createConnection("cliId2"); - Session session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer2 = session2.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - DurableSubscriptionOfflineTestListener listener2 = new DurableSubscriptionOfflineTestListener(); - consumer2.setMessageListener(listener2); + // create durable subscription 2 + Connection con2 = createConnection("cliId2"); + Session session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer2 = session2.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + DurableSubscriptionOfflineTestListener listener2 = new DurableSubscriptionOfflineTestListener(); + consumer2.setMessageListener(listener2); - assertEquals(0, listener2.count); - session2.close(); - con2.close(); + assertEquals(0, listener2.count); + session2.close(); + con2.close(); - // send some more - for (int i = 0; i < 10; i++) { - sent++; - Message message = session.createMessage(); - message.setStringProperty("filter", "true"); - producer.send(topic, message); - } + // send some more + for (int i = 0; i < 10; i++) { + sent++; + Message message = session.createMessage(); + message.setStringProperty("filter", "true"); + producer.send(topic, message); + } - Thread.sleep(1 * 1000); - session.close(); - con.close(); + Thread.sleep(1 * 1000); + session.close(); + con.close(); - con2 = createConnection("cliId2"); - session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer2 = session2.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - listener2 = new DurableSubscriptionOfflineTestListener("cliId2"); - consumer2.setMessageListener(listener2); - // test online subs - Thread.sleep(3 * 1000); + con2 = createConnection("cliId2"); + session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumer2 = session2.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + listener2 = new DurableSubscriptionOfflineTestListener("cliId2"); + consumer2.setMessageListener(listener2); + // test online subs + Thread.sleep(3 * 1000); - assertEquals(10, listener2.count); + assertEquals(10, listener2.count); - // consume all messages - con = createConnection("cliId1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener("cliId1"); - consumer.setMessageListener(listener); + // consume all messages + con = createConnection("cliId1"); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener("cliId1"); + consumer.setMessageListener(listener); - Thread.sleep(3 * 1000); + Thread.sleep(3 * 1000); - session.close(); - con.close(); + session.close(); + con.close(); - assertEquals("offline consumer got all", sent, listener.count); - } + assertEquals("offline consumer got all", sent, listener.count); + } - private static String filter = "$a='A1' AND (($b=true AND $c=true) OR ($d='D1' OR $d='D2'))"; - @Test(timeout = 60 * 1000) - public void testMixOfOnLineAndOfflineSubsGetAllMatched() throws Exception { - // create offline subs 1 - Connection con = createConnection("offCli1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", filter, true); - session.close(); - con.close(); + private static String filter = "$a='A1' AND (($b=true AND $c=true) OR ($d='D1' OR $d='D2'))"; - // create offline subs 2 - con = createConnection("offCli2"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", filter, true); - session.close(); - con.close(); + @Test(timeout = 60 * 1000) + public void testMixOfOnLineAndOfflineSubsGetAllMatched() throws Exception { + // create offline subs 1 + Connection con = createConnection("offCli1"); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId", filter, true); + session.close(); + con.close(); - // create online subs - Connection con2 = createConnection("onlineCli1"); - Session session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer2 = session2.createDurableSubscriber(topic, "SubsId", filter, true); - DurableSubscriptionOfflineTestListener listener2 = new DurableSubscriptionOfflineTestListener(); - consumer2.setMessageListener(listener2); + // create offline subs 2 + con = createConnection("offCli2"); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId", filter, true); + session.close(); + con.close(); - // create non-durable consumer - Connection con4 = createConnection("nondurableCli"); - Session session4 = con4.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer4 = session4.createConsumer(topic, filter, true); - DurableSubscriptionOfflineTestListener listener4 = new DurableSubscriptionOfflineTestListener(); - consumer4.setMessageListener(listener4); + // create online subs + Connection con2 = createConnection("onlineCli1"); + Session session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer2 = session2.createDurableSubscriber(topic, "SubsId", filter, true); + DurableSubscriptionOfflineTestListener listener2 = new DurableSubscriptionOfflineTestListener(); + consumer2.setMessageListener(listener2); - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); + // create non-durable consumer + Connection con4 = createConnection("nondurableCli"); + Session session4 = con4.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer4 = session4.createConsumer(topic, filter, true); + DurableSubscriptionOfflineTestListener listener4 = new DurableSubscriptionOfflineTestListener(); + consumer4.setMessageListener(listener4); - boolean hasRelevant = false; - int filtered = 0; - for (int i = 0; i < 100; i++) { - int postf = (int) (Math.random() * 9) + 1; - String d = "D" + postf; + // send messages + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(null); - if ("D1".equals(d) || "D2".equals(d)) { - hasRelevant = true; - filtered++; - } + boolean hasRelevant = false; + int filtered = 0; + for (int i = 0; i < 100; i++) { + int postf = (int) (Math.random() * 9) + 1; + String d = "D" + postf; - Message message = session.createMessage(); - message.setStringProperty("$a", "A1"); - message.setStringProperty("$d", d); - producer.send(topic, message); - } + if ("D1".equals(d) || "D2".equals(d)) { + hasRelevant = true; + filtered++; + } - Message message = session.createMessage(); - message.setStringProperty("$a", "A1"); - message.setBooleanProperty("$b", true); - message.setBooleanProperty("$c", hasRelevant); - producer.send(topic, message); + Message message = session.createMessage(); + message.setStringProperty("$a", "A1"); + message.setStringProperty("$d", d); + producer.send(topic, message); + } - if (hasRelevant) + Message message = session.createMessage(); + message.setStringProperty("$a", "A1"); + message.setBooleanProperty("$b", true); + message.setBooleanProperty("$c", hasRelevant); + producer.send(topic, message); + + if (hasRelevant) + filtered++; + + Thread.sleep(1 * 1000); + session.close(); + con.close(); + + Thread.sleep(3 * 1000); + + // test non-durable consumer + session4.close(); + con4.close(); + assertEquals(filtered, listener4.count); // succeeded! + + // test online subs + session2.close(); + con2.close(); + assertEquals(filtered, listener2.count); // succeeded! + + // test offline 1 + con = createConnection("offCli1"); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", filter, true); + DurableSubscriptionOfflineTestListener listener = new FilterCheckListener(); + consumer.setMessageListener(listener); + + Thread.sleep(3 * 1000); + session.close(); + con.close(); + + assertEquals(filtered, listener.count); + + // test offline 2 + Connection con3 = createConnection("offCli2"); + Session session3 = con3.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer3 = session3.createDurableSubscriber(topic, "SubsId", filter, true); + DurableSubscriptionOfflineTestListener listener3 = new FilterCheckListener(); + consumer3.setMessageListener(listener3); + + Thread.sleep(3 * 1000); + session3.close(); + con3.close(); + + assertEquals(filtered, listener3.count); + assertTrue("no unexpected exceptions: " + exceptions, exceptions.isEmpty()); + } + + @Test(timeout = 60 * 1000) + public void testOfflineSubscriptionWithSelectorAfterRestart() throws Exception { + + if (PersistenceAdapterChoice.LevelDB == defaultPersistenceAdapter) { + // https://issues.apache.org/jira/browse/AMQ-4296 + return; + } + + // create offline subs 1 + Connection con = createConnection("offCli1"); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + session.close(); + con.close(); + + // create offline subs 2 + con = createConnection("offCli2"); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + session.close(); + con.close(); + + // send messages + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(null); + + int filtered = 0; + for (int i = 0; i < 10; i++) { + boolean filter = (int) (Math.random() * 2) >= 1; + if (filter) filtered++; - Thread.sleep(1 * 1000); - session.close(); - con.close(); + Message message = session.createMessage(); + message.setStringProperty("filter", filter ? "true" : "false"); + producer.send(topic, message); + } - Thread.sleep(3 * 1000); + LOG.info("sent: " + filtered); + Thread.sleep(1 * 1000); + session.close(); + con.close(); - // test non-durable consumer - session4.close(); - con4.close(); - assertEquals(filtered, listener4.count); // succeeded! + // restart broker + Thread.sleep(3 * 1000); + broker.stop(); + createBroker(false /*deleteAllMessages*/); - // test online subs - session2.close(); - con2.close(); - assertEquals(filtered, listener2.count); // succeeded! + // send more messages + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer = session.createProducer(null); - // test offline 1 - con = createConnection("offCli1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", filter, true); - DurableSubscriptionOfflineTestListener listener = new FilterCheckListener(); - consumer.setMessageListener(listener); + for (int i = 0; i < 10; i++) { + boolean filter = (int) (Math.random() * 2) >= 1; + if (filter) + filtered++; - Thread.sleep(3 * 1000); - session.close(); - con.close(); + Message message = session.createMessage(); + message.setStringProperty("filter", filter ? "true" : "false"); + producer.send(topic, message); + } - assertEquals(filtered, listener.count); + LOG.info("after restart, total sent with filter='true': " + filtered); + Thread.sleep(1 * 1000); + session.close(); + con.close(); - // test offline 2 - Connection con3 = createConnection("offCli2"); - Session session3 = con3.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer3 = session3.createDurableSubscriber(topic, "SubsId", filter, true); - DurableSubscriptionOfflineTestListener listener3 = new FilterCheckListener(); - consumer3.setMessageListener(listener3); + // test offline subs + con = createConnection("offCli1"); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener("1>"); + consumer.setMessageListener(listener); - Thread.sleep(3 * 1000); - session3.close(); - con3.close(); + Connection con3 = createConnection("offCli2"); + Session session3 = con3.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer3 = session3.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + DurableSubscriptionOfflineTestListener listener3 = new DurableSubscriptionOfflineTestListener(); + consumer3.setMessageListener(listener3); - assertEquals(filtered, listener3.count); - assertTrue("no unexpected exceptions: " + exceptions, exceptions.isEmpty()); - } + Thread.sleep(3 * 1000); - @Test(timeout = 60 * 1000) - public void testOfflineSubscriptionWithSelectorAfterRestart() throws Exception { + session.close(); + con.close(); + session3.close(); + con3.close(); - if (PersistenceAdapterChoice.LevelDB == defaultPersistenceAdapter) { - // https://issues.apache.org/jira/browse/AMQ-4296 - return; - } + assertEquals(filtered, listener.count); + assertEquals(filtered, listener3.count); + } - // create offline subs 1 - Connection con = createConnection("offCli1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); + @Test(timeout = 60 * 1000) + public void testOfflineSubscriptionAfterRestart() throws Exception { + // create offline subs 1 + Connection con = createConnection("offCli1"); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", null, false); + DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); + consumer.setMessageListener(listener); - // create offline subs 2 - con = createConnection("offCli2"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); + // send messages + MessageProducer producer = session.createProducer(null); - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); + int sent = 0; + for (int i = 0; i < 10; i++) { + sent++; + Message message = session.createMessage(); + message.setStringProperty("filter", "false"); + producer.send(topic, message); + } - int filtered = 0; - for (int i = 0; i < 10; i++) { - boolean filter = (int) (Math.random() * 2) >= 1; - if (filter) - filtered++; + LOG.info("sent: " + sent); + Thread.sleep(5 * 1000); + session.close(); + con.close(); - Message message = session.createMessage(); - message.setStringProperty("filter", filter ? "true" : "false"); - producer.send(topic, message); - } + assertEquals(sent, listener.count); - LOG.info("sent: " + filtered); - Thread.sleep(1 * 1000); - session.close(); - con.close(); + // restart broker + Thread.sleep(3 * 1000); + broker.stop(); + createBroker(false /*deleteAllMessages*/); - // restart broker - Thread.sleep(3 * 1000); - broker.stop(); - createBroker(false /*deleteAllMessages*/); + // send more messages + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer = session.createProducer(null); - // send more messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(null); + for (int i = 0; i < 10; i++) { + sent++; + Message message = session.createMessage(); + message.setStringProperty("filter", "false"); + producer.send(topic, message); + } - for (int i = 0; i < 10; i++) { - boolean filter = (int) (Math.random() * 2) >= 1; - if (filter) - filtered++; + LOG.info("after restart, sent: " + sent); + Thread.sleep(1 * 1000); + session.close(); + con.close(); - Message message = session.createMessage(); - message.setStringProperty("filter", filter ? "true" : "false"); - producer.send(topic, message); - } + // test offline subs + con = createConnection("offCli1"); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumer = session.createDurableSubscriber(topic, "SubsId", null, true); + consumer.setMessageListener(listener); - LOG.info("after restart, total sent with filter='true': " + filtered); - Thread.sleep(1 * 1000); - session.close(); - con.close(); + Thread.sleep(3 * 1000); - // test offline subs - con = createConnection("offCli1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener("1>"); - consumer.setMessageListener(listener); + session.close(); + con.close(); - Connection con3 = createConnection("offCli2"); - Session session3 = con3.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer3 = session3.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - DurableSubscriptionOfflineTestListener listener3 = new DurableSubscriptionOfflineTestListener(); - consumer3.setMessageListener(listener3); + assertEquals(sent, listener.count); + } - Thread.sleep(3 * 1000); + public class FilterCheckListener extends DurableSubscriptionOfflineTestListener { - session.close(); - con.close(); - session3.close(); - con3.close(); + @Override + public void onMessage(Message message) { + count++; - assertEquals(filtered, listener.count); - assertEquals(filtered, listener3.count); - } - - @Test(timeout = 60 * 1000) - public void testOfflineSubscriptionAfterRestart() throws Exception { - // create offline subs 1 - Connection con = createConnection("offCli1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", null, false); - DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); - consumer.setMessageListener(listener); - - // send messages - MessageProducer producer = session.createProducer(null); - - int sent = 0; - for (int i = 0; i < 10; i++) { - sent++; - Message message = session.createMessage(); - message.setStringProperty("filter", "false"); - producer.send(topic, message); - } - - LOG.info("sent: " + sent); - Thread.sleep(5 * 1000); - session.close(); - con.close(); - - assertEquals(sent, listener.count); - - // restart broker - Thread.sleep(3 * 1000); - broker.stop(); - createBroker(false /*deleteAllMessages*/); - - // send more messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(null); - - for (int i = 0; i < 10; i++) { - sent++; - Message message = session.createMessage(); - message.setStringProperty("filter", "false"); - producer.send(topic, message); - } - - LOG.info("after restart, sent: " + sent); - Thread.sleep(1 * 1000); - session.close(); - con.close(); - - // test offline subs - con = createConnection("offCli1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = session.createDurableSubscriber(topic, "SubsId", null, true); - consumer.setMessageListener(listener); - - Thread.sleep(3 * 1000); - - session.close(); - con.close(); - - assertEquals(sent, listener.count); - } - - public class FilterCheckListener extends DurableSubscriptionOfflineTestListener { - - @Override - public void onMessage(Message message) { - count++; - - try { - Object b = message.getObjectProperty("$b"); - if (b != null) { - boolean c = message.getBooleanProperty("$c"); - assertTrue("", c); - } else { - String d = message.getStringProperty("$d"); - assertTrue("", "D1".equals(d) || "D2".equals(d)); - } + try { + Object b = message.getObjectProperty("$b"); + if (b != null) { + boolean c = message.getBooleanProperty("$c"); + assertTrue("", c); } - catch (JMSException e) { - e.printStackTrace(); - exceptions.add(e); + else { + String d = message.getStringProperty("$d"); + assertTrue("", "D1".equals(d) || "D2".equals(d)); } - } - } + } + catch (JMSException e) { + e.printStackTrace(); + exceptions.add(e); + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline4Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline4Test.java index bc31444d06..e6edee9fe9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline4Test.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline4Test.java @@ -36,97 +36,94 @@ import java.util.List; import static org.junit.Assert.assertTrue; - @RunWith(value = Parameterized.class) public class DurableSubscriptionOffline4Test extends DurableSubscriptionOfflineTestBase { - private static final Logger LOG = LoggerFactory.getLogger(DurableSubscriptionOffline4Test.class); + private static final Logger LOG = LoggerFactory.getLogger(DurableSubscriptionOffline4Test.class); - @Parameterized.Parameters(name = "keepDurableSubsActive_{0}") - public static Collection getTestParameters() { - Boolean[] f = {Boolean.FALSE}; - Boolean[] t = {Boolean.TRUE}; - List booleanChoices = new ArrayList(); - booleanChoices.add(f); - booleanChoices.add(t); + @Parameterized.Parameters(name = "keepDurableSubsActive_{0}") + public static Collection getTestParameters() { + Boolean[] f = {Boolean.FALSE}; + Boolean[] t = {Boolean.TRUE}; + List booleanChoices = new ArrayList(); + booleanChoices.add(f); + booleanChoices.add(t); - return booleanChoices; - } + return booleanChoices; + } - public DurableSubscriptionOffline4Test(Boolean keepDurableSubsActive) { - this.journalMaxFileLength = 64 * 1024; - this.keepDurableSubsActive = keepDurableSubsActive.booleanValue(); + public DurableSubscriptionOffline4Test(Boolean keepDurableSubsActive) { + this.journalMaxFileLength = 64 * 1024; + this.keepDurableSubsActive = keepDurableSubsActive.booleanValue(); - LOG.info(">>>> running {} with keepDurableSubsActive: {}, journalMaxFileLength", testName.getMethodName(), this.keepDurableSubsActive, journalMaxFileLength); - } + LOG.info(">>>> running {} with keepDurableSubsActive: {}, journalMaxFileLength", testName.getMethodName(), this.keepDurableSubsActive, journalMaxFileLength); + } + @Test(timeout = 60 * 1000) + // https://issues.apache.org/jira/browse/AMQ-3206 + public void testCleanupDeletedSubAfterRestart() throws Exception { + Connection con = createConnection("cli1"); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId", null, true); + session.close(); + con.close(); - @Test(timeout = 60 * 1000) - // https://issues.apache.org/jira/browse/AMQ-3206 - public void testCleanupDeletedSubAfterRestart() throws Exception { - Connection con = createConnection("cli1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", null, true); - session.close(); - con.close(); + con = createConnection("cli2"); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId", null, true); + session.close(); + con.close(); - con = createConnection("cli2"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", null, true); - session.close(); - con.close(); + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(null); - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); + final int toSend = 500; + final String payload = Arrays.toString(new byte[40 * 1024]); + int sent = 0; + for (int i = sent; i < toSend; i++) { + Message message = session.createTextMessage(payload); + message.setStringProperty("filter", "false"); + message.setIntProperty("ID", i); + producer.send(topic, message); + sent++; + } + con.close(); + LOG.info("sent: " + sent); - final int toSend = 500; - final String payload = Arrays.toString(new byte[40 * 1024]); - int sent = 0; - for (int i = sent; i < toSend; i++) { - Message message = session.createTextMessage(payload); - message.setStringProperty("filter", "false"); - message.setIntProperty("ID", i); - producer.send(topic, message); - sent++; - } - con.close(); - LOG.info("sent: " + sent); + // kill off cli1 + con = createConnection("cli1"); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.unsubscribe("SubsId"); - // kill off cli1 - con = createConnection("cli1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.unsubscribe("SubsId"); + destroyBroker(); + createBroker(false); - destroyBroker(); - createBroker(false); + con = createConnection("cli2"); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", null, true); + final DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); + consumer.setMessageListener(listener); + assertTrue("got all sent", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("Want: " + toSend + ", current: " + listener.count); + return listener.count == toSend; + } + })); + session.close(); + con.close(); - con = createConnection("cli2"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", null, true); - final DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); - consumer.setMessageListener(listener); - assertTrue("got all sent", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("Want: " + toSend + ", current: " + listener.count); - return listener.count == toSend; - } - })); - session.close(); - con.close(); + destroyBroker(); + createBroker(false); + final KahaDBPersistenceAdapter pa = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); + assertTrue("Should have less than three journal files left but was: " + pa.getStore().getJournal().getFileMap().size(), Wait.waitFor(new Wait.Condition() { - destroyBroker(); - createBroker(false); - final KahaDBPersistenceAdapter pa = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); - assertTrue("Should have less than three journal files left but was: " + - pa.getStore().getJournal().getFileMap().size(), Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - return pa.getStore().getJournal().getFileMap().size() <= 3; - } - })); - } + @Override + public boolean isSatisified() throws Exception { + return pa.getStore().getJournal().getFileMap().size() <= 3; + } + })); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOfflineTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOfflineTest.java index a1ce526de8..f7689d87cb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOfflineTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOfflineTest.java @@ -41,838 +41,832 @@ import static org.junit.Assert.*; public class DurableSubscriptionOfflineTest extends DurableSubscriptionOfflineTestBase { - private static final Logger LOG = LoggerFactory.getLogger(DurableSubscriptionOfflineTest.class); + private static final Logger LOG = LoggerFactory.getLogger(DurableSubscriptionOfflineTest.class); - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + getName(true)); - connectionFactory.setWatchTopicAdvisories(false); - return connectionFactory; - } + @Override + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + getName(true)); + connectionFactory.setWatchTopicAdvisories(false); + return connectionFactory; + } - @Test(timeout = 60 * 1000) - public void testConsumeAllMatchedMessages() throws Exception { - // create durable subscription - Connection con = createConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); + @Test(timeout = 60 * 1000) + public void testConsumeAllMatchedMessages() throws Exception { + // create durable subscription + Connection con = createConnection(); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + session.close(); + con.close(); - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); + // send messages + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(null); - int sent = 0; - for (int i = 0; i < 10; i++) { - sent++; + int sent = 0; + for (int i = 0; i < 10; i++) { + sent++; + Message message = session.createMessage(); + message.setStringProperty("filter", "true"); + producer.send(topic, message); + } + + Thread.sleep(1 * 1000); + + session.close(); + con.close(); + + // consume messages + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); + consumer.setMessageListener(listener); + + Thread.sleep(3 * 1000); + + session.close(); + con.close(); + + assertEquals(sent, listener.count); + } + + @Test(timeout = 60 * 1000) + public void testTwoOfflineSubscriptionCanConsume() throws Exception { + // create durable subscription 1 + Connection con = createConnection("cliId1"); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + session.close(); + con.close(); + + // create durable subscription 2 + Connection con2 = createConnection("cliId2"); + Session session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer2 = session2.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + DurableSubscriptionOfflineTestListener listener2 = new DurableSubscriptionOfflineTestListener(); + consumer2.setMessageListener(listener2); + + // send messages + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(null); + + int sent = 0; + for (int i = 0; i < 10; i++) { + sent++; + Message message = session.createMessage(); + message.setStringProperty("filter", "true"); + producer.send(topic, message); + } + + Thread.sleep(1 * 1000); + session.close(); + con.close(); + + // test online subs + Thread.sleep(3 * 1000); + session2.close(); + con2.close(); + + assertEquals(sent, listener2.count); + + // consume messages + con = createConnection("cliId1"); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); + consumer.setMessageListener(listener); + + Thread.sleep(3 * 1000); + + session.close(); + con.close(); + + assertEquals("offline consumer got all", sent, listener.count); + } + + @Test(timeout = 60 * 1000) + public void testRemovedDurableSubDeletes() throws Exception { + String filter = "$a='A1' AND (($b=true AND $c=true) OR ($d='D1' OR $d='D2'))"; + // create durable subscription 1 + Connection con = createConnection("cliId1"); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + session.close(); + con.close(); + + // send messages + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(null); + + for (int i = 0; i < 10; i++) { + Message message = session.createMessage(); + message.setStringProperty("filter", "true"); + producer.send(topic, message); + } + + Thread.sleep(1 * 1000); + + Connection con2 = createConnection("cliId1"); + Session session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE); + session2.unsubscribe("SubsId"); + session2.close(); + con2.close(); + + // see if retroactive can consumer any + topic = new ActiveMQTopic(topic.getPhysicalName() + "?consumer.retroactive=true"); + con = createConnection("offCli2"); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", filter, true); + DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); + consumer.setMessageListener(listener); + session.close(); + con.close(); + assertEquals(0, listener.count); + } + + @Test(timeout = 60 * 1000) + public void testRemovedDurableSubDeletesFromIndex() throws Exception { + + if (!(broker.getPersistenceAdapter() instanceof KahaDBPersistenceAdapter)) { + return; + } + + final int numMessages = 2750; + + KahaDBPersistenceAdapter kahaDBPersistenceAdapter = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); + PageFile pageFile = kahaDBPersistenceAdapter.getStore().getPageFile(); + LOG.info("PageCount " + pageFile.getPageCount() + " f:" + pageFile.getFreePageCount() + ", fileSize:" + pageFile.getFile().length()); + + long lastDiff = 0; + for (int repeats = 0; repeats < 2; repeats++) { + + LOG.info("Iteration: " + repeats + " Count:" + pageFile.getPageCount() + " f:" + pageFile.getFreePageCount()); + + Connection con = createConnection("cliId1" + "-" + repeats); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + session.close(); + con.close(); + + // send messages + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(null); + + for (int i = 0; i < numMessages; i++) { Message message = session.createMessage(); message.setStringProperty("filter", "true"); producer.send(topic, message); - } + } + con.close(); - Thread.sleep(1 * 1000); + Connection con2 = createConnection("cliId1" + "-" + repeats); + Session session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE); + session2.unsubscribe("SubsId"); + session2.close(); + con2.close(); - session.close(); - con.close(); + LOG.info("PageCount " + pageFile.getPageCount() + " f:" + pageFile.getFreePageCount() + " diff: " + (pageFile.getPageCount() - pageFile.getFreePageCount()) + " fileSize:" + pageFile.getFile().length()); - // consume messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); - consumer.setMessageListener(listener); + if (lastDiff != 0) { + assertEquals("Only use X pages per iteration: " + repeats, lastDiff, pageFile.getPageCount() - pageFile.getFreePageCount()); + } + lastDiff = pageFile.getPageCount() - pageFile.getFreePageCount(); + } + } - Thread.sleep(3 * 1000); + @Test(timeout = 60 * 1000) + public void testInterleavedOfflineSubscriptionCanConsumeAfterUnsub() throws Exception { + // create offline subs 1 + Connection con = createConnection("offCli1"); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + session.close(); + con.close(); - session.close(); - con.close(); + // create offline subs 2 + con = createConnection("offCli2"); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId", null, true); + session.close(); + con.close(); - assertEquals(sent, listener.count); - } + // send messages + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(null); + int sent = 0; + for (int i = 0; i < 10; i++) { + boolean filter = (int) (Math.random() * 2) >= 1; - @Test(timeout = 60 * 1000) - public void testTwoOfflineSubscriptionCanConsume() throws Exception { - // create durable subscription 1 - Connection con = createConnection("cliId1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); + sent++; - // create durable subscription 2 - Connection con2 = createConnection("cliId2"); - Session session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer2 = session2.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - DurableSubscriptionOfflineTestListener listener2 = new DurableSubscriptionOfflineTestListener(); - consumer2.setMessageListener(listener2); + Message message = session.createMessage(); + message.setStringProperty("filter", filter ? "true" : "false"); + producer.send(topic, message); + } - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); + Thread.sleep(1 * 1000); - int sent = 0; - for (int i = 0; i < 10; i++) { - sent++; - Message message = session.createMessage(); - message.setStringProperty("filter", "true"); - producer.send(topic, message); - } + Connection con2 = createConnection("offCli1"); + Session session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE); + session2.unsubscribe("SubsId"); + session2.close(); + con2.close(); - Thread.sleep(1 * 1000); - session.close(); - con.close(); + // consume all messages + con = createConnection("offCli2"); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", null, true); + DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener("SubsId"); + consumer.setMessageListener(listener); - // test online subs - Thread.sleep(3 * 1000); - session2.close(); - con2.close(); + Thread.sleep(3 * 1000); - assertEquals(sent, listener2.count); + session.close(); + con.close(); - // consume messages - con = createConnection("cliId1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); - consumer.setMessageListener(listener); + assertEquals("offline consumer got all", sent, listener.count); + } - Thread.sleep(3 * 1000); + @Test(timeout = 60 * 1000) + public void testNoDuplicateOnConcurrentSendTranCommitAndActivate() throws Exception { + final int messageCount = 1000; + Connection con = null; + Session session = null; + final int numConsumers = 10; + for (int i = 0; i <= numConsumers; i++) { + con = createConnection("cli" + i); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId", null, true); + session.close(); + con.close(); + } - session.close(); - con.close(); + class CheckForDupsClient implements Runnable { - assertEquals("offline consumer got all", sent, listener.count); - } + HashSet ids = new HashSet(); + final int id; - @Test(timeout = 60 * 1000) - public void testRemovedDurableSubDeletes() throws Exception { - String filter = "$a='A1' AND (($b=true AND $c=true) OR ($d='D1' OR $d='D2'))"; - // create durable subscription 1 - Connection con = createConnection("cliId1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); + public CheckForDupsClient(int id) { + this.id = id; + } - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); + @Override + public void run() { + try { + Connection con = createConnection("cli" + id); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + for (int j = 0; j < 2; j++) { + MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", null, true); + for (int i = 0; i < messageCount / 2; i++) { + Message message = consumer.receive(4000); + assertNotNull(message); + long producerSequenceId = new MessageId(message.getJMSMessageID()).getProducerSequenceId(); + assertTrue("ID=" + id + " not a duplicate: " + producerSequenceId, ids.add(producerSequenceId)); + } + consumer.close(); + } - for (int i = 0; i < 10; i++) { - Message message = session.createMessage(); - message.setStringProperty("filter", "true"); - producer.send(topic, message); - } + // verify no duplicates left + MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", null, true); + Message message = consumer.receive(4000); + if (message != null) { + long producerSequenceId = new MessageId(message.getJMSMessageID()).getProducerSequenceId(); + assertTrue("ID=" + id + " not a duplicate: " + producerSequenceId, ids.add(producerSequenceId)); + } + assertNull(message); - Thread.sleep(1 * 1000); - - Connection con2 = createConnection("cliId1"); - Session session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE); - session2.unsubscribe("SubsId"); - session2.close(); - con2.close(); - - // see if retroactive can consumer any - topic = new ActiveMQTopic(topic.getPhysicalName() + "?consumer.retroactive=true"); - con = createConnection("offCli2"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", filter, true); - DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); - consumer.setMessageListener(listener); - session.close(); - con.close(); - assertEquals(0, listener.count); - } - - @Test(timeout = 60 * 1000) - public void testRemovedDurableSubDeletesFromIndex() throws Exception { - - if (! (broker.getPersistenceAdapter() instanceof KahaDBPersistenceAdapter)) { - return; - } - - final int numMessages = 2750; - - KahaDBPersistenceAdapter kahaDBPersistenceAdapter = (KahaDBPersistenceAdapter)broker.getPersistenceAdapter(); - PageFile pageFile = kahaDBPersistenceAdapter.getStore().getPageFile(); - LOG.info("PageCount " + pageFile.getPageCount() + " f:" + pageFile.getFreePageCount() + ", fileSize:" + pageFile.getFile().length()); - - long lastDiff = 0; - for (int repeats=0; repeats<2; repeats++) { - - LOG.info("Iteration: "+ repeats + " Count:" + pageFile.getPageCount() + " f:" + pageFile.getFreePageCount()); - - Connection con = createConnection("cliId1" + "-" + repeats); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); - - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); - - for (int i = 0; i < numMessages; i++) { - Message message = session.createMessage(); - message.setStringProperty("filter", "true"); - producer.send(topic, message); + session.close(); + con.close(); } - con.close(); - - Connection con2 = createConnection("cliId1" + "-" + repeats); - Session session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE); - session2.unsubscribe("SubsId"); - session2.close(); - con2.close(); - - LOG.info("PageCount " + pageFile.getPageCount() + " f:" + pageFile.getFreePageCount() + " diff: " + (pageFile.getPageCount() - pageFile.getFreePageCount()) + " fileSize:" + pageFile.getFile().length()); - - if (lastDiff != 0) { - assertEquals("Only use X pages per iteration: " + repeats, lastDiff, pageFile.getPageCount() - pageFile.getFreePageCount()); + catch (Throwable e) { + e.printStackTrace(); + exceptions.add(e); } - lastDiff = pageFile.getPageCount() - pageFile.getFreePageCount(); - } - } + } + } - @Test(timeout = 60 * 1000) - public void testInterleavedOfflineSubscriptionCanConsumeAfterUnsub() throws Exception { - // create offline subs 1 - Connection con = createConnection("offCli1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); + final String payLoad = new String(new byte[1000]); + con = createConnection(); + final Session sendSession = con.createSession(true, Session.SESSION_TRANSACTED); + MessageProducer producer = sendSession.createProducer(topic); + for (int i = 0; i < messageCount; i++) { + producer.send(sendSession.createTextMessage(payLoad)); + } - // create offline subs 2 - con = createConnection("offCli2"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", null, true); - session.close(); - con.close(); + ExecutorService executorService = Executors.newCachedThreadPool(); - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); - - int sent = 0; - for (int i = 0; i < 10; i++) { - boolean filter = (int) (Math.random() * 2) >= 1; - - sent++; - - Message message = session.createMessage(); - message.setStringProperty("filter", filter ? "true" : "false"); - producer.send(topic, message); - } - - Thread.sleep(1 * 1000); - - Connection con2 = createConnection("offCli1"); - Session session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE); - session2.unsubscribe("SubsId"); - session2.close(); - con2.close(); - - // consume all messages - con = createConnection("offCli2"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", null, true); - DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener("SubsId"); - consumer.setMessageListener(listener); - - Thread.sleep(3 * 1000); - - session.close(); - con.close(); - - assertEquals("offline consumer got all", sent, listener.count); - } - - @Test(timeout = 60 * 1000) - public void testNoDuplicateOnConcurrentSendTranCommitAndActivate() throws Exception { - final int messageCount = 1000; - Connection con = null; - Session session = null; - final int numConsumers = 10; - for (int i = 0; i <= numConsumers; i++) { - con = createConnection("cli" + i); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", null, true); - session.close(); - con.close(); - } - - class CheckForDupsClient implements Runnable { - HashSet ids = new HashSet(); - final int id; - - public CheckForDupsClient(int id) { - this.id = id; + // concurrent commit and activate + executorService.execute(new Runnable() { + @Override + public void run() { + try { + sendSession.commit(); } - - @Override - public void run() { - try { - Connection con = createConnection("cli" + id); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - for (int j=0;j<2;j++) { - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", null, true); - for (int i = 0; i < messageCount/2; i++) { - Message message = consumer.receive(4000); - assertNotNull(message); - long producerSequenceId = new MessageId(message.getJMSMessageID()).getProducerSequenceId(); - assertTrue("ID=" + id + " not a duplicate: " + producerSequenceId, ids.add(producerSequenceId)); - } - consumer.close(); - } - - // verify no duplicates left - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", null, true); - Message message = consumer.receive(4000); - if (message != null) { - long producerSequenceId = new MessageId(message.getJMSMessageID()).getProducerSequenceId(); - assertTrue("ID=" + id + " not a duplicate: " + producerSequenceId, ids.add(producerSequenceId)); - } - assertNull(message); - - - session.close(); - con.close(); - } catch (Throwable e) { - e.printStackTrace(); - exceptions.add(e); - } + catch (JMSException e) { + e.printStackTrace(); + exceptions.add(e); } - } + } + }); + for (int i = 0; i < numConsumers; i++) { + executorService.execute(new CheckForDupsClient(i)); + } - final String payLoad = new String(new byte[1000]); - con = createConnection(); - final Session sendSession = con.createSession(true, Session.SESSION_TRANSACTED); - MessageProducer producer = sendSession.createProducer(topic); - for (int i = 0; i < messageCount; i++) { - producer.send(sendSession.createTextMessage(payLoad)); - } + executorService.shutdown(); + executorService.awaitTermination(5, TimeUnit.MINUTES); + con.close(); - ExecutorService executorService = Executors.newCachedThreadPool(); + assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); + } - // concurrent commit and activate - executorService.execute(new Runnable() { - @Override - public void run() { - try { - sendSession.commit(); - } catch (JMSException e) { - e.printStackTrace(); - exceptions.add(e); - } + @Test(timeout = 2 * 60 * 1000) + public void testOrderOnActivateDeactivate() throws Exception { + for (int i = 0; i < 10; i++) { + LOG.info("Iteration: " + i); + doTestOrderOnActivateDeactivate(); + broker.stop(); + broker.waitUntilStopped(); + createBroker(true /*deleteAllMessages*/); + } + } + + public void doTestOrderOnActivateDeactivate() throws Exception { + final int messageCount = 1000; + Connection con = null; + Session session = null; + final int numConsumers = 4; + for (int i = 0; i <= numConsumers; i++) { + con = createConnection("cli" + i); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId", null, true); + session.close(); + con.close(); + } + + final String url = "failover:(tcp://localhost:" + (broker.getTransportConnectors().get(1).getConnectUri()).getPort() + "?wireFormat.maxInactivityDuration=0)?" + "jms.watchTopicAdvisories=false&" + "jms.alwaysSyncSend=true&jms.dispatchAsync=true&" + "jms.sendAcksAsync=true&" + "initialReconnectDelay=100&maxReconnectDelay=30000&" + "useExponentialBackOff=true"; + final ActiveMQConnectionFactory clientFactory = new ActiveMQConnectionFactory(url); + + class CheckOrderClient implements Runnable { + + final int id; + int runCount = 0; + + public CheckOrderClient(int id) { + this.id = id; + } + + @Override + public void run() { + try { + synchronized (this) { + Connection con = clientFactory.createConnection(); + con.setClientID("cli" + id); + con.start(); + Session session = con.createSession(false, Session.CLIENT_ACKNOWLEDGE); + MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", null, true); + int nextId = 0; + + ++runCount; + int i = 0; + for (; i < messageCount / 2; i++) { + Message message = consumer.receiveNoWait(); + if (message == null) { + break; + } + long producerSequenceId = new MessageId(message.getJMSMessageID()).getProducerSequenceId(); + assertEquals(id + " expected order: runCount: " + runCount + " id: " + message.getJMSMessageID(), ++nextId, producerSequenceId); + } + LOG.info(con.getClientID() + " peeked " + i); + session.close(); + con.close(); + } } - }); - for (int i = 0; i < numConsumers; i++) { - executorService.execute(new CheckForDupsClient(i)); - } - - executorService.shutdown(); - executorService.awaitTermination(5, TimeUnit.MINUTES); - con.close(); - - assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); - } - - - @Test(timeout = 2 * 60 * 1000) - public void testOrderOnActivateDeactivate() throws Exception { - for (int i=0;i<10;i++) { - LOG.info("Iteration: " + i); - doTestOrderOnActivateDeactivate(); - broker.stop(); - broker.waitUntilStopped(); - createBroker(true /*deleteAllMessages*/); - } - } - - - public void doTestOrderOnActivateDeactivate() throws Exception { - final int messageCount = 1000; - Connection con = null; - Session session = null; - final int numConsumers = 4; - for (int i = 0; i <= numConsumers; i++) { - con = createConnection("cli" + i); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", null, true); - session.close(); - con.close(); - } - - final String url = "failover:(tcp://localhost:" - + (broker.getTransportConnectors().get(1).getConnectUri()).getPort() - + "?wireFormat.maxInactivityDuration=0)?" - + "jms.watchTopicAdvisories=false&" - + "jms.alwaysSyncSend=true&jms.dispatchAsync=true&" - + "jms.sendAcksAsync=true&" - + "initialReconnectDelay=100&maxReconnectDelay=30000&" - + "useExponentialBackOff=true"; - final ActiveMQConnectionFactory clientFactory = new ActiveMQConnectionFactory(url); - - class CheckOrderClient implements Runnable { - final int id; - int runCount = 0; - - public CheckOrderClient(int id) { - this.id = id; + catch (Throwable e) { + e.printStackTrace(); + exceptions.add(e); } + } + } - @Override - public void run() { - try { - synchronized (this) { - Connection con = clientFactory.createConnection(); - con.setClientID("cli" + id); - con.start(); - Session session = con.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", null, true); - int nextId = 0; + Runnable producer = new Runnable() { + final String payLoad = new String(new byte[600]); - ++runCount; - int i=0; - for (; i < messageCount/2; i++) { - Message message = consumer.receiveNoWait(); - if (message == null) { - break; - } - long producerSequenceId = new MessageId(message.getJMSMessageID()).getProducerSequenceId(); - assertEquals(id + " expected order: runCount: " + runCount + " id: " + message.getJMSMessageID(), ++nextId, producerSequenceId); - } - LOG.info(con.getClientID() + " peeked " + i); - session.close(); - con.close(); - } - } catch (Throwable e) { - e.printStackTrace(); - exceptions.add(e); - } + @Override + public void run() { + try { + Connection con = createConnection(); + final Session sendSession = con.createSession(true, Session.SESSION_TRANSACTED); + MessageProducer producer = sendSession.createProducer(topic); + for (int i = 0; i < messageCount; i++) { + producer.send(sendSession.createTextMessage(payLoad)); + } + LOG.info("About to commit: " + messageCount); + sendSession.commit(); + LOG.info("committed: " + messageCount); + con.close(); } - } - - Runnable producer = new Runnable() { - final String payLoad = new String(new byte[600]); - - @Override - public void run() { - try { - Connection con = createConnection(); - final Session sendSession = con.createSession(true, Session.SESSION_TRANSACTED); - MessageProducer producer = sendSession.createProducer(topic); - for (int i = 0; i < messageCount; i++) { - producer.send(sendSession.createTextMessage(payLoad)); - } - LOG.info("About to commit: " + messageCount); - sendSession.commit(); - LOG.info("committed: " + messageCount); - con.close(); - } catch (Exception e) { - e.printStackTrace(); - exceptions.add(e); - } + catch (Exception e) { + e.printStackTrace(); + exceptions.add(e); } - }; + } + }; - ExecutorService executorService = Executors.newCachedThreadPool(); + ExecutorService executorService = Executors.newCachedThreadPool(); - // concurrent commit and activate - for (int i = 0; i < numConsumers; i++) { - final CheckOrderClient client = new CheckOrderClient(i); - for (int j=0; j<100; j++) { - executorService.execute(client); - } - } - executorService.execute(producer); + // concurrent commit and activate + for (int i = 0; i < numConsumers; i++) { + final CheckOrderClient client = new CheckOrderClient(i); + for (int j = 0; j < 100; j++) { + executorService.execute(client); + } + } + executorService.execute(producer); - executorService.shutdown(); - executorService.awaitTermination(5, TimeUnit.MINUTES); - con.close(); + executorService.shutdown(); + executorService.awaitTermination(5, TimeUnit.MINUTES); + con.close(); - assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); - } + assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); + } - @Test(timeout = 60 * 1000) - public void testUnmatchedSubUnsubscribeDeletesAll() throws Exception { - // create offline subs 1 - Connection con = createConnection("offCli1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); + @Test(timeout = 60 * 1000) + public void testUnmatchedSubUnsubscribeDeletesAll() throws Exception { + // create offline subs 1 + Connection con = createConnection("offCli1"); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + session.close(); + con.close(); - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); + // send messages + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(null); - int filtered = 0; - for (int i = 0; i < 10; i++) { - boolean filter = (i %2 == 0); //(int) (Math.random() * 2) >= 1; - if (filter) - filtered++; + int filtered = 0; + for (int i = 0; i < 10; i++) { + boolean filter = (i % 2 == 0); //(int) (Math.random() * 2) >= 1; + if (filter) + filtered++; - Message message = session.createMessage(); - message.setStringProperty("filter", filter ? "true" : "false"); - producer.send(topic, message); - } + Message message = session.createMessage(); + message.setStringProperty("filter", filter ? "true" : "false"); + producer.send(topic, message); + } - LOG.info("sent: " + filtered); - Thread.sleep(1 * 1000); - session.close(); - con.close(); + LOG.info("sent: " + filtered); + Thread.sleep(1 * 1000); + session.close(); + con.close(); - // test offline subs - con = createConnection("offCli1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.unsubscribe("SubsId"); - session.close(); - con.close(); + // test offline subs + con = createConnection("offCli1"); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.unsubscribe("SubsId"); + session.close(); + con.close(); - con = createConnection("offCli1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); - consumer.setMessageListener(listener); + con = createConnection("offCli1"); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); + consumer.setMessageListener(listener); - Thread.sleep(3 * 1000); + Thread.sleep(3 * 1000); - session.close(); - con.close(); + session.close(); + con.close(); - assertEquals(0, listener.count); - } + assertEquals(0, listener.count); + } - @Test(timeout = 60 * 1000) - public void testAllConsumed() throws Exception { - final String filter = "filter = 'true'"; - Connection con = createConnection("cli1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", filter, true); - session.close(); - con.close(); + @Test(timeout = 60 * 1000) + public void testAllConsumed() throws Exception { + final String filter = "filter = 'true'"; + Connection con = createConnection("cli1"); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId", filter, true); + session.close(); + con.close(); - con = createConnection("cli2"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", filter, true); - session.close(); - con.close(); + con = createConnection("cli2"); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId", filter, true); + session.close(); + con.close(); - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); + // send messages + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(null); - int sent = 0; - for (int i = 0; i < 10; i++) { - Message message = session.createMessage(); - message.setStringProperty("filter", "true"); - producer.send(topic, message); - sent++; - } + int sent = 0; + for (int i = 0; i < 10; i++) { + Message message = session.createMessage(); + message.setStringProperty("filter", "true"); + producer.send(topic, message); + sent++; + } - LOG.info("sent: " + sent); - Thread.sleep(1 * 1000); - session.close(); - con.close(); + LOG.info("sent: " + sent); + Thread.sleep(1 * 1000); + session.close(); + con.close(); - con = createConnection("cli1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", filter, true); - DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); - consumer.setMessageListener(listener); - Thread.sleep(3 * 1000); - session.close(); - con.close(); + con = createConnection("cli1"); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", filter, true); + DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); + consumer.setMessageListener(listener); + Thread.sleep(3 * 1000); + session.close(); + con.close(); - assertEquals(sent, listener.count); + assertEquals(sent, listener.count); - LOG.info("cli2 pull 2"); - con = createConnection("cli2"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = session.createDurableSubscriber(topic, "SubsId", filter, true); - assertNotNull("got message", consumer.receive(2000)); - assertNotNull("got message", consumer.receive(2000)); - session.close(); - con.close(); + LOG.info("cli2 pull 2"); + con = createConnection("cli2"); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumer = session.createDurableSubscriber(topic, "SubsId", filter, true); + assertNotNull("got message", consumer.receive(2000)); + assertNotNull("got message", consumer.receive(2000)); + session.close(); + con.close(); - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(null); + // send messages + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer = session.createProducer(null); - sent = 0; - for (int i = 0; i < 2; i++) { - Message message = session.createMessage(); - message.setStringProperty("filter", i==1 ? "true" : "false"); - producer.send(topic, message); - sent++; - } - LOG.info("sent: " + sent); - Thread.sleep(1 * 1000); - session.close(); - con.close(); + sent = 0; + for (int i = 0; i < 2; i++) { + Message message = session.createMessage(); + message.setStringProperty("filter", i == 1 ? "true" : "false"); + producer.send(topic, message); + sent++; + } + LOG.info("sent: " + sent); + Thread.sleep(1 * 1000); + session.close(); + con.close(); - LOG.info("cli1 again, should get 1 new ones"); - con = createConnection("cli1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = session.createDurableSubscriber(topic, "SubsId", filter, true); - listener = new DurableSubscriptionOfflineTestListener(); - consumer.setMessageListener(listener); - Thread.sleep(3 * 1000); - session.close(); - con.close(); + LOG.info("cli1 again, should get 1 new ones"); + con = createConnection("cli1"); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumer = session.createDurableSubscriber(topic, "SubsId", filter, true); + listener = new DurableSubscriptionOfflineTestListener(); + consumer.setMessageListener(listener); + Thread.sleep(3 * 1000); + session.close(); + con.close(); - assertEquals(1, listener.count); - } + assertEquals(1, listener.count); + } - // https://issues.apache.org/jira/browse/AMQ-3190 - @Test(timeout = 60 * 1000) - public void testNoMissOnMatchingSubAfterRestart() throws Exception { + // https://issues.apache.org/jira/browse/AMQ-3190 + @Test(timeout = 60 * 1000) + public void testNoMissOnMatchingSubAfterRestart() throws Exception { - final String filter = "filter = 'true'"; - Connection con = createConnection("cli1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", filter, true); - session.close(); - con.close(); + final String filter = "filter = 'true'"; + Connection con = createConnection("cli1"); + Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId", filter, true); + session.close(); + con.close(); - // send unmatched messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); + // send unmatched messages + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(null); - int sent = 0; - // message for cli1 to keep it interested - Message message = session.createMessage(); - message.setStringProperty("filter", "true"); - message.setIntProperty("ID", 0); - producer.send(topic, message); - sent++; + int sent = 0; + // message for cli1 to keep it interested + Message message = session.createMessage(); + message.setStringProperty("filter", "true"); + message.setIntProperty("ID", 0); + producer.send(topic, message); + sent++; - for (int i = sent; i < 10; i++) { - message = session.createMessage(); - message.setStringProperty("filter", "false"); - message.setIntProperty("ID", i); - producer.send(topic, message); - sent++; - } - con.close(); - LOG.info("sent: " + sent); + for (int i = sent; i < 10; i++) { + message = session.createMessage(); + message.setStringProperty("filter", "false"); + message.setIntProperty("ID", i); + producer.send(topic, message); + sent++; + } + con.close(); + LOG.info("sent: " + sent); - // new sub at id 10 - con = createConnection("cli2"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", filter, true); - session.close(); - con.close(); + // new sub at id 10 + con = createConnection("cli2"); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId", filter, true); + session.close(); + con.close(); - destroyBroker(); - createBroker(false); + destroyBroker(); + createBroker(false); - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(null); + con = createConnection(); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer = session.createProducer(null); - for (int i = sent; i < 30; i++) { - message = session.createMessage(); - message.setStringProperty("filter", "true"); - message.setIntProperty("ID", i); - producer.send(topic, message); - sent++; - } - con.close(); - LOG.info("sent: " + sent); + for (int i = sent; i < 30; i++) { + message = session.createMessage(); + message.setStringProperty("filter", "true"); + message.setIntProperty("ID", i); + producer.send(topic, message); + sent++; + } + con.close(); + LOG.info("sent: " + sent); - // pick up the first of the next twenty messages - con = createConnection("cli2"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", filter, true); - Message m = consumer.receive(3000); - assertEquals("is message 10", 10, m.getIntProperty("ID")); + // pick up the first of the next twenty messages + con = createConnection("cli2"); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", filter, true); + Message m = consumer.receive(3000); + assertEquals("is message 10", 10, m.getIntProperty("ID")); - session.close(); - con.close(); + session.close(); + con.close(); - // pick up the first few messages for client1 - con = createConnection("cli1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = session.createDurableSubscriber(topic, "SubsId", filter, true); - m = consumer.receive(3000); - assertEquals("is message 0", 0, m.getIntProperty("ID")); - m = consumer.receive(3000); - assertEquals("is message 10", 10, m.getIntProperty("ID")); + // pick up the first few messages for client1 + con = createConnection("cli1"); + session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumer = session.createDurableSubscriber(topic, "SubsId", filter, true); + m = consumer.receive(3000); + assertEquals("is message 0", 0, m.getIntProperty("ID")); + m = consumer.receive(3000); + assertEquals("is message 10", 10, m.getIntProperty("ID")); - session.close(); - con.close(); - } + session.close(); + con.close(); + } - -// // https://issues.apache.org/jira/browse/AMQ-3768 -// public void testPageReuse() throws Exception { -// Connection con = null; -// Session session = null; -// -// final int numConsumers = 115; -// for (int i=0; i<=numConsumers;i++) { -// con = createConnection("cli" + i); -// session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); -// session.createDurableSubscriber(topic, "SubsId", null, true); -// session.close(); -// con.close(); -// } -// -// // populate ack locations -// con = createConnection(); -// session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); -// MessageProducer producer = session.createProducer(null); -// Message message = session.createTextMessage(new byte[10].toString()); -// producer.send(topic, message); -// con.close(); -// -// // we have a split, remove all but the last so that -// // the head pageid changes in the acklocations listindex -// for (int i=0; i<=numConsumers -1; i++) { -// con = createConnection("cli" + i); -// session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); -// session.unsubscribe("SubsId"); -// session.close(); -// con.close(); -// } -// -// destroyBroker(); -// createBroker(false); -// -// // create a bunch more subs to reuse the freed page and get us in a knot -// for (int i=1; i<=numConsumers;i++) { -// con = createConnection("cli" + i); -// session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); -// session.createDurableSubscriber(topic, "SubsId", filter, true); -// session.close(); -// con.close(); -// } -// } -// -// public void testRedeliveryFlag() throws Exception { -// -// Connection con; -// Session session; -// final int numClients = 2; -// for (int i=0; i exceptions = new ArrayList(); - protected ActiveMQConnectionFactory connectionFactory; - protected boolean isTopic = true; - public PersistenceAdapterChoice defaultPersistenceAdapter = PersistenceAdapterChoice.KahaDB; - @Rule - public TestName testName = new TestName(); + private static final Logger LOG = LoggerFactory.getLogger(DurableSubscriptionOfflineTestBase.class); + public boolean usePrioritySupport = Boolean.TRUE; + public int journalMaxFileLength = Journal.DEFAULT_MAX_FILE_LENGTH; + public boolean keepDurableSubsActive = true; + protected BrokerService broker; + protected ActiveMQTopic topic; + protected final List exceptions = new ArrayList(); + protected ActiveMQConnectionFactory connectionFactory; + protected boolean isTopic = true; + public PersistenceAdapterChoice defaultPersistenceAdapter = PersistenceAdapterChoice.KahaDB; - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + getName(true)); - connectionFactory.setWatchTopicAdvisories(false); - return connectionFactory; - } + @Rule + public TestName testName = new TestName(); - protected Connection createConnection() throws Exception { - return createConnection("cliName"); - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + getName(true)); + connectionFactory.setWatchTopicAdvisories(false); + return connectionFactory; + } - protected Connection createConnection(String name) throws Exception { - ConnectionFactory connectionFactory1 = createConnectionFactory(); - Connection connection = connectionFactory1.createConnection(); - connection.setClientID(name); - connection.start(); - return connection; - } + protected Connection createConnection() throws Exception { + return createConnection("cliName"); + } - public ActiveMQConnectionFactory getConnectionFactory() throws Exception { - if (connectionFactory == null) { - connectionFactory = createConnectionFactory(); - assertTrue("Should have created a connection factory!", connectionFactory != null); - } - return connectionFactory; - } + protected Connection createConnection(String name) throws Exception { + ConnectionFactory connectionFactory1 = createConnectionFactory(); + Connection connection = connectionFactory1.createConnection(); + connection.setClientID(name); + connection.start(); + return connection; + } - @Before - public void setUp() throws Exception { - exceptions.clear(); - topic = (ActiveMQTopic) createDestination(); - createBroker(); - } + public ActiveMQConnectionFactory getConnectionFactory() throws Exception { + if (connectionFactory == null) { + connectionFactory = createConnectionFactory(); + assertTrue("Should have created a connection factory!", connectionFactory != null); + } + return connectionFactory; + } - @After - public void tearDown() throws Exception { - destroyBroker(); - } + @Before + public void setUp() throws Exception { + exceptions.clear(); + topic = (ActiveMQTopic) createDestination(); + createBroker(); + } - protected void createBroker() throws Exception { - createBroker(true); - } + @After + public void tearDown() throws Exception { + destroyBroker(); + } - protected void createBroker(boolean deleteAllMessages) throws Exception { - String currentTestName = getName(true); - broker = BrokerFactory.createBroker("broker:(vm://" + currentTestName +")"); - broker.setBrokerName(currentTestName); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - broker.getManagementContext().setCreateConnector(false); - broker.setAdvisorySupport(false); - broker.setKeepDurableSubsActive(keepDurableSubsActive); - broker.addConnector("tcp://0.0.0.0:0"); + protected void createBroker() throws Exception { + createBroker(true); + } - if (usePrioritySupport) { - PolicyEntry policy = new PolicyEntry(); - policy.setPrioritizedMessages(true); - PolicyMap policyMap = new PolicyMap(); - policyMap.setDefaultEntry(policy); - broker.setDestinationPolicy(policyMap); - } + protected void createBroker(boolean deleteAllMessages) throws Exception { + String currentTestName = getName(true); + broker = BrokerFactory.createBroker("broker:(vm://" + currentTestName + ")"); + broker.setBrokerName(currentTestName); + broker.setDeleteAllMessagesOnStartup(deleteAllMessages); + broker.getManagementContext().setCreateConnector(false); + broker.setAdvisorySupport(false); + broker.setKeepDurableSubsActive(keepDurableSubsActive); + broker.addConnector("tcp://0.0.0.0:0"); - setDefaultPersistenceAdapter(broker); - if (broker.getPersistenceAdapter() instanceof JDBCPersistenceAdapter) { - // ensure it kicks in during tests - ((JDBCPersistenceAdapter)broker.getPersistenceAdapter()).setCleanupPeriod(2*1000); - } else if (broker.getPersistenceAdapter() instanceof KahaDBPersistenceAdapter) { - // have lots of journal files - ((KahaDBPersistenceAdapter)broker.getPersistenceAdapter()).setJournalMaxFileLength(journalMaxFileLength); - } - broker.start(); - broker.waitUntilStarted(); - } + if (usePrioritySupport) { + PolicyEntry policy = new PolicyEntry(); + policy.setPrioritizedMessages(true); + PolicyMap policyMap = new PolicyMap(); + policyMap.setDefaultEntry(policy); + broker.setDestinationPolicy(policyMap); + } - protected void destroyBroker() throws Exception { - if (broker != null) - broker.stop(); - } + setDefaultPersistenceAdapter(broker); + if (broker.getPersistenceAdapter() instanceof JDBCPersistenceAdapter) { + // ensure it kicks in during tests + ((JDBCPersistenceAdapter) broker.getPersistenceAdapter()).setCleanupPeriod(2 * 1000); + } + else if (broker.getPersistenceAdapter() instanceof KahaDBPersistenceAdapter) { + // have lots of journal files + ((KahaDBPersistenceAdapter) broker.getPersistenceAdapter()).setJournalMaxFileLength(journalMaxFileLength); + } + broker.start(); + broker.waitUntilStarted(); + } - protected Destination createDestination(String subject) { - if (isTopic) { - return new ActiveMQTopic(subject); - } else { - return new ActiveMQQueue(subject); - } - } + protected void destroyBroker() throws Exception { + if (broker != null) + broker.stop(); + } - protected Destination createDestination() { - return createDestination(getDestinationString()); - } + protected Destination createDestination(String subject) { + if (isTopic) { + return new ActiveMQTopic(subject); + } + else { + return new ActiveMQQueue(subject); + } + } - /** - * Returns the name of the destination used in this test case - */ - protected String getDestinationString() { - return getClass().getName() + "." + getName(true); - } + protected Destination createDestination() { + return createDestination(getDestinationString()); + } + /** + * Returns the name of the destination used in this test case + */ + protected String getDestinationString() { + return getClass().getName() + "." + getName(true); + } - public String getName() { - return getName(false); - } + public String getName() { + return getName(false); + } - protected String getName(boolean original) { - String currentTestName = testName.getMethodName(); - currentTestName = currentTestName.replace("[",""); - currentTestName = currentTestName.replace("]",""); - return currentTestName; - } + protected String getName(boolean original) { + String currentTestName = testName.getMethodName(); + currentTestName = currentTestName.replace("[", ""); + currentTestName = currentTestName.replace("]", ""); + return currentTestName; + } - public PersistenceAdapter setDefaultPersistenceAdapter(BrokerService broker) throws IOException { - return setPersistenceAdapter(broker, defaultPersistenceAdapter); - } + public PersistenceAdapter setDefaultPersistenceAdapter(BrokerService broker) throws IOException { + return setPersistenceAdapter(broker, defaultPersistenceAdapter); + } - public PersistenceAdapter setPersistenceAdapter(BrokerService broker, PersistenceAdapterChoice choice) throws IOException { - PersistenceAdapter adapter = null; - switch (choice) { - case JDBC: - LOG.debug(">>>> setPersistenceAdapter to JDBC "); - adapter = new JDBCPersistenceAdapter(); - break; - case KahaDB: - LOG.debug(">>>> setPersistenceAdapter to KahaDB "); - adapter = new KahaDBPersistenceAdapter(); - break; - case LevelDB: - LOG.debug(">>>> setPersistenceAdapter to LevelDB "); - adapter = new LevelDBPersistenceAdapter(); - break; - case MEM: - LOG.debug(">>>> setPersistenceAdapter to MEM "); - adapter = new MemoryPersistenceAdapter(); - break; - } - broker.setPersistenceAdapter(adapter); - return adapter; - } + public PersistenceAdapter setPersistenceAdapter(BrokerService broker, + PersistenceAdapterChoice choice) throws IOException { + PersistenceAdapter adapter = null; + switch (choice) { + case JDBC: + LOG.debug(">>>> setPersistenceAdapter to JDBC "); + adapter = new JDBCPersistenceAdapter(); + break; + case KahaDB: + LOG.debug(">>>> setPersistenceAdapter to KahaDB "); + adapter = new KahaDBPersistenceAdapter(); + break; + case LevelDB: + LOG.debug(">>>> setPersistenceAdapter to LevelDB "); + adapter = new LevelDBPersistenceAdapter(); + break; + case MEM: + LOG.debug(">>>> setPersistenceAdapter to MEM "); + adapter = new MemoryPersistenceAdapter(); + break; + } + broker.setPersistenceAdapter(adapter); + return adapter; + } } class DurableSubscriptionOfflineTestListener implements MessageListener { - private static final Logger LOG = LoggerFactory.getLogger(DurableSubscriptionOfflineTestListener.class); - int count = 0; - String id = null; - DurableSubscriptionOfflineTestListener() {} + private static final Logger LOG = LoggerFactory.getLogger(DurableSubscriptionOfflineTestListener.class); + int count = 0; + String id = null; - DurableSubscriptionOfflineTestListener(String id) { - this.id = id; - } - @Override - public void onMessage(javax.jms.Message message) { - count++; - if (id != null) { - try { - LOG.info(id + ", " + message.getJMSMessageID()); - } catch (Exception ignored) {} - } - } + DurableSubscriptionOfflineTestListener() { + } + + DurableSubscriptionOfflineTestListener(String id) { + this.id = id; + } + + @Override + public void onMessage(javax.jms.Message message) { + count++; + if (id != null) { + try { + LOG.info(id + ", " + message.getJMSMessageID()); + } + catch (Exception ignored) { + } + } + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionReactivationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionReactivationTest.java index 7bd50a8355..bad361019e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionReactivationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionReactivationTest.java @@ -32,64 +32,64 @@ import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter; public class DurableSubscriptionReactivationTest extends EmbeddedBrokerTestSupport { - public boolean keepDurableSubsActive; - - public void initCombosForTestReactivateKeepaliveSubscription() { - addCombinationValues("keepDurableSubsActive", new Object[] { new Boolean(true), new Boolean(false) }); - } - - public void testReactivateKeepaliveSubscription() throws Exception { + public boolean keepDurableSubsActive; - Connection connection = createConnection(); - connection.setClientID("cliID"); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber subscriber = session.createDurableSubscriber((Topic) createDestination(), "subName"); - subscriber.close(); - connection.close(); + public void initCombosForTestReactivateKeepaliveSubscription() { + addCombinationValues("keepDurableSubsActive", new Object[]{new Boolean(true), new Boolean(false)}); + } - connection = createConnection(); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(createDestination()); - producer.send(session.createMessage()); - connection.close(); + public void testReactivateKeepaliveSubscription() throws Exception { - connection = createConnection(); - connection.setClientID("cliID"); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - subscriber = session.createDurableSubscriber((Topic) createDestination(), "subName"); - Message message = subscriber.receive(1 * 1000); - subscriber.close(); - connection.close(); + Connection connection = createConnection(); + connection.setClientID("cliID"); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + TopicSubscriber subscriber = session.createDurableSubscriber((Topic) createDestination(), "subName"); + subscriber.close(); + connection.close(); - assertNotNull("Message not received.", message); - } + connection = createConnection(); + connection.start(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(createDestination()); + producer.send(session.createMessage()); + connection.close(); - protected void setUp() throws Exception { - useTopic = true; - super.setUp(); - } + connection = createConnection(); + connection.setClientID("cliID"); + connection.start(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + subscriber = session.createDurableSubscriber((Topic) createDestination(), "subName"); + Message message = subscriber.receive(1 * 1000); + subscriber.close(); + connection.close(); - protected void tearDown() throws Exception { - super.tearDown(); - } + assertNotNull("Message not received.", message); + } - @Override - protected BrokerService createBroker() throws Exception { - BrokerService answer = super.createBroker(); - answer.setKeepDurableSubsActive(keepDurableSubsActive); - answer.setPersistenceAdapter(new JDBCPersistenceAdapter()); - answer.setDeleteAllMessagesOnStartup(true); - return answer; - } + protected void setUp() throws Exception { + useTopic = true; + super.setUp(); + } - protected boolean isPersistent() { - return true; - } - - public static Test suite() { - return suite(DurableSubscriptionReactivationTest.class); - } + protected void tearDown() throws Exception { + super.tearDown(); + } + + @Override + protected BrokerService createBroker() throws Exception { + BrokerService answer = super.createBroker(); + answer.setKeepDurableSubsActive(keepDurableSubsActive); + answer.setPersistenceAdapter(new JDBCPersistenceAdapter()); + answer.setDeleteAllMessagesOnStartup(true); + return answer; + } + + protected boolean isPersistent() { + return true; + } + + public static Test suite() { + return suite(DurableSubscriptionReactivationTest.class); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionRemoveOfflineTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionRemoveOfflineTest.java index 1e2c08c0f6..e0c6aa27fc 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionRemoveOfflineTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionRemoveOfflineTest.java @@ -31,88 +31,88 @@ import org.slf4j.LoggerFactory; public class DurableSubscriptionRemoveOfflineTest extends EmbeddedBrokerTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(DurableSubscriptionRemoveOfflineTest.class); + private static final Logger LOG = LoggerFactory.getLogger(DurableSubscriptionRemoveOfflineTest.class); - protected void setUp() throws Exception { - useTopic = true; - super.setUp(); - } + protected void setUp() throws Exception { + useTopic = true; + super.setUp(); + } - protected void tearDown() throws Exception { - super.tearDown(); - } + protected void tearDown() throws Exception { + super.tearDown(); + } - @Override - protected BrokerService createBroker() throws Exception { - BrokerService answer = super.createBroker(); - answer.setOfflineDurableSubscriberTaskSchedule(3 * 1000); - answer.setOfflineDurableSubscriberTimeout(5 * 1000); - answer.setDeleteAllMessagesOnStartup(true); - return answer; - } + @Override + protected BrokerService createBroker() throws Exception { + BrokerService answer = super.createBroker(); + answer.setOfflineDurableSubscriberTaskSchedule(3 * 1000); + answer.setOfflineDurableSubscriberTimeout(5 * 1000); + answer.setDeleteAllMessagesOnStartup(true); + return answer; + } - protected BrokerService restartBroker() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - broker = null; + protected BrokerService restartBroker() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + broker = null; - broker = super.createBroker(); - broker.setOfflineDurableSubscriberTaskSchedule(3 * 1000); - broker.setOfflineDurableSubscriberTimeout(5 * 1000); + broker = super.createBroker(); + broker.setOfflineDurableSubscriberTaskSchedule(3 * 1000); + broker.setOfflineDurableSubscriberTimeout(5 * 1000); - broker.start(); - broker.waitUntilStarted(); + broker.start(); + broker.waitUntilStarted(); - return broker; - } + return broker; + } - public void testRemove() throws Exception { - Connection connection = createConnection(); - connection.setClientID("cliID"); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber subscriber = session.createDurableSubscriber((Topic) createDestination(), "subName"); - subscriber.close(); - connection.close(); + public void testRemove() throws Exception { + Connection connection = createConnection(); + connection.setClientID("cliID"); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + TopicSubscriber subscriber = session.createDurableSubscriber((Topic) createDestination(), "subName"); + subscriber.close(); + connection.close(); - assertTrue(Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return broker.getAdminView().getInactiveDurableTopicSubscribers().length == 0; - } - }, 15000)); - } + assertTrue(Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return broker.getAdminView().getInactiveDurableTopicSubscribers().length == 0; + } + }, 15000)); + } - public void testRemoveAfterRestart() throws Exception { - Connection connection = createConnection(); - connection.setClientID("cliID"); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber subscriber = session.createDurableSubscriber((Topic) createDestination(), "subName"); - subscriber.close(); - connection.close(); + public void testRemoveAfterRestart() throws Exception { + Connection connection = createConnection(); + connection.setClientID("cliID"); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + TopicSubscriber subscriber = session.createDurableSubscriber((Topic) createDestination(), "subName"); + subscriber.close(); + connection.close(); - LOG.info("Broker restarting, wait for inactive cleanup afterwards."); + LOG.info("Broker restarting, wait for inactive cleanup afterwards."); - restartBroker(); + restartBroker(); - LOG.info("Broker restarted, wait for inactive cleanup now."); + LOG.info("Broker restarted, wait for inactive cleanup now."); - assertTrue(broker.getAdminView().getInactiveDurableTopicSubscribers().length == 1); + assertTrue(broker.getAdminView().getInactiveDurableTopicSubscribers().length == 1); - assertTrue(Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return broker.getAdminView().getInactiveDurableTopicSubscribers().length == 0; - } - }, 20000)); - } + assertTrue(Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return broker.getAdminView().getInactiveDurableTopicSubscribers().length == 0; + } + }, 20000)); + } - protected boolean isPersistent() { - return true; - } + protected boolean isPersistent() { + return true; + } - public static Test suite() { - return suite(DurableSubscriptionRemoveOfflineTest.class); - } + public static Test suite() { + return suite(DurableSubscriptionRemoveOfflineTest.class); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionSelectorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionSelectorTest.java index 317866d2cd..d31b6aaf29 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionSelectorTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionSelectorTest.java @@ -38,140 +38,144 @@ import org.apache.activemq.util.Wait; public class DurableSubscriptionSelectorTest extends org.apache.activemq.TestSupport { - MBeanServer mbs; - BrokerService broker = null; - ActiveMQTopic topic; + MBeanServer mbs; + BrokerService broker = null; + ActiveMQTopic topic; - ActiveMQConnection consumerConnection = null, producerConnection = null; - Session producerSession; - MessageProducer producer; + ActiveMQConnection consumerConnection = null, producerConnection = null; + Session producerSession; + MessageProducer producer; - private int received = 0; + private int received = 0; - public static Test suite() { - return suite(DurableSubscriptionSelectorTest.class); - } + public static Test suite() { + return suite(DurableSubscriptionSelectorTest.class); + } - public void initCombosForTestSubscription() throws Exception { - this.addCombinationValues("defaultPersistenceAdapter", PersistenceAdapterChoice.values()); - } + public void initCombosForTestSubscription() throws Exception { + this.addCombinationValues("defaultPersistenceAdapter", PersistenceAdapterChoice.values()); + } - public void testSubscription() throws Exception { - openConsumer(); - for (int i = 0; i < 4000; i++) { - sendMessage(false); - } - Thread.sleep(1000); + public void testSubscription() throws Exception { + openConsumer(); + for (int i = 0; i < 4000; i++) { + sendMessage(false); + } + Thread.sleep(1000); - assertEquals("Invalid message received.", 0, received); + assertEquals("Invalid message received.", 0, received); - closeProducer(); - closeConsumer(); - stopBroker(); + closeProducer(); + closeConsumer(); + stopBroker(); - startBroker(false); - openConsumer(); + startBroker(false); + openConsumer(); - sendMessage(true); + sendMessage(true); - Wait.waitFor(new Wait.Condition() { @Override - public boolean isSatisified() { return received >= 1;} }, 10000); + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() { + return received >= 1; + } + }, 10000); - assertEquals("Message is not received.", 1, received); + assertEquals("Message is not received.", 1, received); - sendMessage(true); - Thread.sleep(100); + sendMessage(true); + Thread.sleep(100); - assertEquals("Message is not received.", 2, received); - } + assertEquals("Message is not received.", 2, received); + } - private void openConsumer() throws Exception { - consumerConnection = (ActiveMQConnection) createConnection(); - consumerConnection.setClientID("cliID"); - consumerConnection.start(); - Session session = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber subscriber = session.createDurableSubscriber(topic, "subName", "filter=true", false); + private void openConsumer() throws Exception { + consumerConnection = (ActiveMQConnection) createConnection(); + consumerConnection.setClientID("cliID"); + consumerConnection.start(); + Session session = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + TopicSubscriber subscriber = session.createDurableSubscriber(topic, "subName", "filter=true", false); - subscriber.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - received++; - } - }); - } + subscriber.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + received++; + } + }); + } - private void closeConsumer() throws JMSException { - if (consumerConnection != null) - consumerConnection.close(); - consumerConnection = null; - } + private void closeConsumer() throws JMSException { + if (consumerConnection != null) + consumerConnection.close(); + consumerConnection = null; + } - private void sendMessage(boolean filter) throws Exception { - if (producerConnection == null) { - producerConnection = (ActiveMQConnection) createConnection(); - producerConnection.start(); - producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = producerSession.createProducer(topic); - } + private void sendMessage(boolean filter) throws Exception { + if (producerConnection == null) { + producerConnection = (ActiveMQConnection) createConnection(); + producerConnection.start(); + producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer = producerSession.createProducer(topic); + } - Message message = producerSession.createMessage(); - message.setBooleanProperty("filter", filter); - producer.send(message); - } + Message message = producerSession.createMessage(); + message.setBooleanProperty("filter", filter); + producer.send(message); + } - private void closeProducer() throws JMSException { - if (producerConnection != null) - producerConnection.close(); - producerConnection = null; - } + private void closeProducer() throws JMSException { + if (producerConnection != null) + producerConnection.close(); + producerConnection = null; + } - private void startBroker(boolean deleteMessages) throws Exception { - broker = new BrokerService(); - broker.setBrokerName("test-broker"); + private void startBroker(boolean deleteMessages) throws Exception { + broker = new BrokerService(); + broker.setBrokerName("test-broker"); - if (deleteMessages) { - broker.setDeleteAllMessagesOnStartup(true); - } - setDefaultPersistenceAdapter(broker); + if (deleteMessages) { + broker.setDeleteAllMessagesOnStartup(true); + } + setDefaultPersistenceAdapter(broker); /* use maxPageSize policy in place of always pulling from the broker in maxRows chunks if (broker.getPersistenceAdapter() instanceof JDBCPersistenceAdapter) { ((JDBCPersistenceAdapter)broker.getPersistenceAdapter()).setMaxRows(5000); }*/ - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setMaxPageSize(5000); - policyMap.setDefaultEntry(defaultEntry); - broker.setDestinationPolicy(policyMap); + PolicyMap policyMap = new PolicyMap(); + PolicyEntry defaultEntry = new PolicyEntry(); + defaultEntry.setMaxPageSize(5000); + policyMap.setDefaultEntry(defaultEntry); + broker.setDestinationPolicy(policyMap); - broker.start(); - } + broker.start(); + } - private void stopBroker() throws Exception { - if (broker != null) - broker.stop(); - broker = null; - } + private void stopBroker() throws Exception { + if (broker != null) + broker.stop(); + broker = null; + } - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://test-broker?jms.watchTopicAdvisories=false&waitForStart=5000&create=false"); - } + @Override + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory("vm://test-broker?jms.watchTopicAdvisories=false&waitForStart=5000&create=false"); + } - @Override - protected void setUp() throws Exception { - setAutoFail(true); - super.setUp(); + @Override + protected void setUp() throws Exception { + setAutoFail(true); + super.setUp(); - startBroker(true); - topic = (ActiveMQTopic) createDestination(); - mbs = ManagementFactory.getPlatformMBeanServer(); - } + startBroker(true); + topic = (ActiveMQTopic) createDestination(); + mbs = ManagementFactory.getPlatformMBeanServer(); + } - @Override - protected void tearDown() throws Exception { - stopBroker(); - super.tearDown(); - } + @Override + protected void tearDown() throws Exception { + stopBroker(); + super.tearDown(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionTestSupport.java index 6e419490e7..040aa8597a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionTestSupport.java @@ -39,496 +39,496 @@ import org.apache.activemq.store.PersistenceAdapter; */ public abstract class DurableSubscriptionTestSupport extends TestSupport { - private Connection connection; - private Session session; - private TopicSubscriber consumer; - private MessageProducer producer; - private BrokerService broker; - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://durable-broker"); - } - - @Override - protected Connection createConnection() throws Exception { - Connection rc = super.createConnection(); - rc.setClientID(getName()); - return rc; - } - - @Override - protected void setUp() throws Exception { - createBroker(); - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - destroyBroker(); - } - - protected void restartBroker() throws Exception { - destroyBroker(); - createRestartedBroker(); // retain stored messages - } - - private void createBroker() throws Exception { - broker = new BrokerService(); - broker.setBrokerName("durable-broker"); - broker.setDeleteAllMessagesOnStartup(true); - broker.setPersistenceAdapter(createPersistenceAdapter()); - broker.setPersistent(true); - broker.start(); - broker.waitUntilStarted(); - - connection = createConnection(); - } - - private void createRestartedBroker() throws Exception { - broker = new BrokerService(); - broker.setBrokerName("durable-broker"); - broker.setDeleteAllMessagesOnStartup(false); - broker.setPersistenceAdapter(createPersistenceAdapter()); - broker.setPersistent(true); - broker.start(); - broker.waitUntilStarted(); - - connection = createConnection(); - } - - private void destroyBroker() throws Exception { - if (connection != null) { - connection.close(); - } - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - } - - protected abstract PersistenceAdapter createPersistenceAdapter() throws Exception; - - public void testMessageExpire() throws Exception { - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic("TestTopic"); - consumer = session.createDurableSubscriber(topic, "sub1"); - producer = session.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - producer.setTimeToLive(1000); - connection.start(); - - // Make sure it works when the durable sub is active. - producer.send(session.createTextMessage("Msg:1")); - assertTextMessageEquals("Msg:1", consumer.receive(1000)); - - consumer.close(); - - producer.send(session.createTextMessage("Msg:2")); - producer.send(session.createTextMessage("Msg:3")); - - consumer = session.createDurableSubscriber(topic, "sub1"); - - // Try to get the message. - assertTextMessageEquals("Msg:2", consumer.receive(1000)); - Thread.sleep(1000); - assertNull(consumer.receive(1000)); - } - - public void testUnsubscribeSubscription() throws Exception { - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic("TestTopic"); - consumer = session.createDurableSubscriber(topic, "sub1"); - producer = session.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - connection.start(); - - // Make sure it works when the durable sub is active. - producer.send(session.createTextMessage("Msg:1")); - assertTextMessageEquals("Msg:1", consumer.receive(5000)); - - // Deactivate the sub. - consumer.close(); - // Send a new message. - producer.send(session.createTextMessage("Msg:2")); - session.unsubscribe("sub1"); - - // Reopen the connection. - connection.close(); - connection = createConnection(); - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(topic); - connection.start(); - - // Activate the sub. - consumer = session.createDurableSubscriber(topic, "sub1"); - producer.send(session.createTextMessage("Msg:3")); - - // Try to get the message. - assertTextMessageEquals("Msg:3", consumer.receive(5000)); - } - - public void testInactiveDurableSubscriptionTwoConnections() throws Exception { - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic("TestTopic"); - consumer = session.createDurableSubscriber(topic, "sub1"); - producer = session.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - connection.start(); - - // Make sure it works when the durable sub is active. - producer.send(session.createTextMessage("Msg:1")); - assertTextMessageEquals("Msg:1", consumer.receive(5000)); - - // Deactivate the sub. - consumer.close(); - - // Send a new message. - producer.send(session.createTextMessage("Msg:2")); - - // Reopen the connection. - connection.close(); - connection = createConnection(); - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - connection.start(); - - // Activate the sub. - consumer = session.createDurableSubscriber(topic, "sub1"); - - // Try to get the message. - assertTextMessageEquals("Msg:2", consumer.receive(5000)); - } - - public void testInactiveDurableSubscriptionBrokerRestart() throws Exception { - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic("TestTopic"); - consumer = session.createDurableSubscriber(topic, "sub1"); - producer = session.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - connection.start(); - - // Make sure it works when the durable sub is active. - producer.send(session.createTextMessage("Msg:1")); - assertTextMessageEquals("Msg:1", consumer.receive(5000)); - - // Deactivate the sub. - consumer.close(); - - // Send a new message. - producer.send(session.createTextMessage("Msg:2")); - - // Reopen the connection. - restartBroker(); - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - connection.start(); + private Connection connection; + private Session session; + private TopicSubscriber consumer; + private MessageProducer producer; + private BrokerService broker; + + @Override + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory("vm://durable-broker"); + } + + @Override + protected Connection createConnection() throws Exception { + Connection rc = super.createConnection(); + rc.setClientID(getName()); + return rc; + } + + @Override + protected void setUp() throws Exception { + createBroker(); + super.setUp(); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + destroyBroker(); + } + + protected void restartBroker() throws Exception { + destroyBroker(); + createRestartedBroker(); // retain stored messages + } + + private void createBroker() throws Exception { + broker = new BrokerService(); + broker.setBrokerName("durable-broker"); + broker.setDeleteAllMessagesOnStartup(true); + broker.setPersistenceAdapter(createPersistenceAdapter()); + broker.setPersistent(true); + broker.start(); + broker.waitUntilStarted(); + + connection = createConnection(); + } + + private void createRestartedBroker() throws Exception { + broker = new BrokerService(); + broker.setBrokerName("durable-broker"); + broker.setDeleteAllMessagesOnStartup(false); + broker.setPersistenceAdapter(createPersistenceAdapter()); + broker.setPersistent(true); + broker.start(); + broker.waitUntilStarted(); + + connection = createConnection(); + } + + private void destroyBroker() throws Exception { + if (connection != null) { + connection.close(); + } + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + } + + protected abstract PersistenceAdapter createPersistenceAdapter() throws Exception; + + public void testMessageExpire() throws Exception { + session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); + Topic topic = session.createTopic("TestTopic"); + consumer = session.createDurableSubscriber(topic, "sub1"); + producer = session.createProducer(topic); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + producer.setTimeToLive(1000); + connection.start(); + + // Make sure it works when the durable sub is active. + producer.send(session.createTextMessage("Msg:1")); + assertTextMessageEquals("Msg:1", consumer.receive(1000)); + + consumer.close(); + + producer.send(session.createTextMessage("Msg:2")); + producer.send(session.createTextMessage("Msg:3")); + + consumer = session.createDurableSubscriber(topic, "sub1"); + + // Try to get the message. + assertTextMessageEquals("Msg:2", consumer.receive(1000)); + Thread.sleep(1000); + assertNull(consumer.receive(1000)); + } + + public void testUnsubscribeSubscription() throws Exception { + session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); + Topic topic = session.createTopic("TestTopic"); + consumer = session.createDurableSubscriber(topic, "sub1"); + producer = session.createProducer(topic); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + connection.start(); + + // Make sure it works when the durable sub is active. + producer.send(session.createTextMessage("Msg:1")); + assertTextMessageEquals("Msg:1", consumer.receive(5000)); + + // Deactivate the sub. + consumer.close(); + // Send a new message. + producer.send(session.createTextMessage("Msg:2")); + session.unsubscribe("sub1"); + + // Reopen the connection. + connection.close(); + connection = createConnection(); + session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); + producer = session.createProducer(topic); + connection.start(); + + // Activate the sub. + consumer = session.createDurableSubscriber(topic, "sub1"); + producer.send(session.createTextMessage("Msg:3")); + + // Try to get the message. + assertTextMessageEquals("Msg:3", consumer.receive(5000)); + } + + public void testInactiveDurableSubscriptionTwoConnections() throws Exception { + session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); + Topic topic = session.createTopic("TestTopic"); + consumer = session.createDurableSubscriber(topic, "sub1"); + producer = session.createProducer(topic); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + connection.start(); + + // Make sure it works when the durable sub is active. + producer.send(session.createTextMessage("Msg:1")); + assertTextMessageEquals("Msg:1", consumer.receive(5000)); + + // Deactivate the sub. + consumer.close(); + + // Send a new message. + producer.send(session.createTextMessage("Msg:2")); + + // Reopen the connection. + connection.close(); + connection = createConnection(); + session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); + connection.start(); + + // Activate the sub. + consumer = session.createDurableSubscriber(topic, "sub1"); + + // Try to get the message. + assertTextMessageEquals("Msg:2", consumer.receive(5000)); + } + + public void testInactiveDurableSubscriptionBrokerRestart() throws Exception { + session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); + Topic topic = session.createTopic("TestTopic"); + consumer = session.createDurableSubscriber(topic, "sub1"); + producer = session.createProducer(topic); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + connection.start(); + + // Make sure it works when the durable sub is active. + producer.send(session.createTextMessage("Msg:1")); + assertTextMessageEquals("Msg:1", consumer.receive(5000)); + + // Deactivate the sub. + consumer.close(); + + // Send a new message. + producer.send(session.createTextMessage("Msg:2")); + + // Reopen the connection. + restartBroker(); + session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); + connection.start(); - // Activate the sub. - consumer = session.createDurableSubscriber(topic, "sub1"); - - // Try to get the message. - assertTextMessageEquals("Msg:2", consumer.receive(5000)); - assertNull(consumer.receive(5000)); - } - - public void testDurableSubscriptionBrokerRestart() throws Exception { - - // Create the durable sub. - connection.start(); - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - - // Ensure that consumer will receive messages sent before it was created - Topic topic = session.createTopic("TestTopic?consumer.retroactive=true"); - consumer = session.createDurableSubscriber(topic, "sub1"); + // Activate the sub. + consumer = session.createDurableSubscriber(topic, "sub1"); + + // Try to get the message. + assertTextMessageEquals("Msg:2", consumer.receive(5000)); + assertNull(consumer.receive(5000)); + } + + public void testDurableSubscriptionBrokerRestart() throws Exception { + + // Create the durable sub. + connection.start(); + session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); + + // Ensure that consumer will receive messages sent before it was created + Topic topic = session.createTopic("TestTopic?consumer.retroactive=true"); + consumer = session.createDurableSubscriber(topic, "sub1"); - producer = session.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - producer.send(session.createTextMessage("Msg:1")); - assertTextMessageEquals("Msg:1", consumer.receive(5000)); + producer = session.createProducer(topic); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + producer.send(session.createTextMessage("Msg:1")); + assertTextMessageEquals("Msg:1", consumer.receive(5000)); - // Make sure cleanup kicks in - Thread.sleep(1000); + // Make sure cleanup kicks in + Thread.sleep(1000); - // Restart the broker. - restartBroker(); - } + // Restart the broker. + restartBroker(); + } - public void testDurableSubscriptionPersistsPastBrokerRestart() throws Exception { + public void testDurableSubscriptionPersistsPastBrokerRestart() throws Exception { - // Create the durable sub. - connection.start(); - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); + // Create the durable sub. + connection.start(); + session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - // Ensure that consumer will receive messages sent before it was created - Topic topic = session.createTopic("TestTopic?consumer.retroactive=true"); - consumer = session.createDurableSubscriber(topic, "sub1"); + // Ensure that consumer will receive messages sent before it was created + Topic topic = session.createTopic("TestTopic?consumer.retroactive=true"); + consumer = session.createDurableSubscriber(topic, "sub1"); - // Restart the broker. - restartBroker(); + // Restart the broker. + restartBroker(); - // Reconnection - connection.start(); - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); + // Reconnection + connection.start(); + session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); + producer = session.createProducer(topic); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); - // Make sure it works when the durable sub is active. - producer.send(session.createTextMessage("Msg:1")); + // Make sure it works when the durable sub is active. + producer.send(session.createTextMessage("Msg:1")); - // Activate the sub. - consumer = session.createDurableSubscriber(topic, "sub1"); + // Activate the sub. + consumer = session.createDurableSubscriber(topic, "sub1"); - // Send a new message. - producer.send(session.createTextMessage("Msg:2")); + // Send a new message. + producer.send(session.createTextMessage("Msg:2")); - // Try to get the message. - assertTextMessageEquals("Msg:1", consumer.receive(5000)); - assertTextMessageEquals("Msg:2", consumer.receive(5000)); + // Try to get the message. + assertTextMessageEquals("Msg:1", consumer.receive(5000)); + assertTextMessageEquals("Msg:2", consumer.receive(5000)); - assertNull(consumer.receive(5000)); - } + assertNull(consumer.receive(5000)); + } - public void testDurableSubscriptionRetroactive() throws Exception { + public void testDurableSubscriptionRetroactive() throws Exception { - // Create the durable sub. - connection.start(); - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); + // Create the durable sub. + connection.start(); + session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic("TestTopic?consumer.retroactive=true"); - consumer = session.createDurableSubscriber(topic, "sub1"); - connection.close(); + Topic topic = session.createTopic("TestTopic?consumer.retroactive=true"); + consumer = session.createDurableSubscriber(topic, "sub1"); + connection.close(); - // Produce - connection = createConnection(); - connection.start(); - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - producer.send(session.createTextMessage("Msg:1")); + // Produce + connection = createConnection(); + connection.start(); + session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); + producer = session.createProducer(topic); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + producer.send(session.createTextMessage("Msg:1")); - restartBroker(); + restartBroker(); - // connect second durable to pick up retroactive message - connection.start(); - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - consumer = session.createDurableSubscriber(topic, "sub2"); + // connect second durable to pick up retroactive message + connection.start(); + session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); + consumer = session.createDurableSubscriber(topic, "sub2"); - // Try to get the message. - assertTextMessageEquals("Msg:1", consumer.receive(5000)); - assertNull(consumer.receive(2000)); - } + // Try to get the message. + assertTextMessageEquals("Msg:1", consumer.receive(5000)); + assertNull(consumer.receive(2000)); + } - public void testDurableSubscriptionRollbackRedeliver() throws Exception { - - // Create the durable sub. - connection.start(); + public void testDurableSubscriptionRollbackRedeliver() throws Exception { + + // Create the durable sub. + connection.start(); - session = connection.createSession(true, javax.jms.Session.SESSION_TRANSACTED); - Topic topic = session.createTopic("TestTopic"); - consumer = session.createDurableSubscriber(topic, "sub1"); - - Session producerSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - producer = producerSession.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); + session = connection.createSession(true, javax.jms.Session.SESSION_TRANSACTED); + Topic topic = session.createTopic("TestTopic"); + consumer = session.createDurableSubscriber(topic, "sub1"); + + Session producerSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); + producer = producerSession.createProducer(topic); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); - producer.send(session.createTextMessage("Msg:1")); - - // receive and rollback - assertTextMessageEquals("Msg:1", consumer.receive(5000)); - session.rollback(); - consumer.close(); - session.close(); - - session = connection.createSession(true, javax.jms.Session.SESSION_TRANSACTED); - - // Ensure that consumer will receive messages sent and rolled back - consumer = session.createDurableSubscriber(topic, "sub1"); - - assertTextMessageEquals("Msg:1", consumer.receive(5000)); - session.commit(); - - assertNull(consumer.receive(5000)); - } - - public void xtestInactiveDurableSubscriptionOneConnection() throws Exception { - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic("TestTopic"); - consumer = session.createDurableSubscriber(topic, "sub1"); - producer = session.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - connection.start(); - - // Make sure it works when the durable sub is active. - producer.send(session.createTextMessage("Msg:1")); - assertTextMessageEquals("Msg:1", consumer.receive(5000)); - - // Deactivate the sub. - consumer.close(); - - // Send a new message. - producer.send(session.createTextMessage("Msg:2")); - - // Activate the sub. - consumer = session.createDurableSubscriber(topic, "sub1"); - - // Try to get the message. - assertTextMessageEquals("Msg:2", consumer.receive(5000)); - } - - public void testSelectorChange() throws Exception { - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic("TestTopic"); - consumer = session.createDurableSubscriber(topic, "sub1", "color='red'", false); - producer = session.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - connection.start(); - - // Make sure it works when the durable sub is active. - TextMessage msg = session.createTextMessage(); - msg.setText("Msg:1"); - msg.setStringProperty("color", "blue"); - producer.send(msg); - msg.setText("Msg:2"); - msg.setStringProperty("color", "red"); - producer.send(msg); - - assertTextMessageEquals("Msg:2", consumer.receive(5000)); - - // Change the subscription - consumer.close(); - consumer = session.createDurableSubscriber(topic, "sub1", "color='blue'", false); - - // Send a new message. - msg.setText("Msg:3"); - msg.setStringProperty("color", "red"); - producer.send(msg); - msg.setText("Msg:4"); - msg.setStringProperty("color", "blue"); - producer.send(msg); - - // Try to get the message. - assertTextMessageEquals("Msg:4", consumer.receive(5000)); - } - - public void testDurableSubWorksInNewSession() throws JMSException { - - // Create the consumer. - connection.start(); - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Topic topic = session.createTopic("topic-" + getName()); - MessageConsumer consumer = session.createDurableSubscriber(topic, "sub1"); - // Drain any messages that may already be in the sub - while (consumer.receive(1000) != null) { - } - - // See if the durable sub works in a new session. - session.close(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - - // Send a Message that should be added to the durable sub. - MessageProducer producer = createProducer(session, topic); - producer.send(session.createTextMessage("Message 1")); - - // Activate the durable sub now. And receive the message. - consumer = session.createDurableSubscriber(topic, "sub1"); - Message msg = consumer.receive(1000); - assertNotNull(msg); - assertEquals("Message 1", ((TextMessage) msg).getText()); - } - - public void testDurableSubWorksInNewConnection() throws Exception { - - // Create the consumer. - connection.start(); - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Topic topic = session.createTopic("topic-" + getName()); - MessageConsumer consumer = session.createDurableSubscriber(topic, "sub1"); - // Drain any messages that may already be in the sub - while (consumer.receive(1000) != null) { - } - - // See if the durable sub works in a new connection. - // The embeded broker shutsdown when his connections are closed. - // So we open the new connection before the old one is closed. - connection.close(); - connection = createConnection(); - connection.start(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - - // Send a Message that should be added to the durable sub. - MessageProducer producer = createProducer(session, topic); - producer.send(session.createTextMessage("Message 1")); - - // Activate the durable sub now. And receive the message. - consumer = session.createDurableSubscriber(topic, "sub1"); - Message msg = consumer.receive(1000); - assertNotNull(msg); - assertEquals("Message 1", ((TextMessage) msg).getText()); - } - - public void testIndividualAckWithDurableSubs() throws Exception { - // Create the consumer. - connection.start(); - - Session session = connection.createSession(false, ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE); - Topic topic = session.createTopic("topic-" + getName()); - MessageConsumer consumer = session.createDurableSubscriber(topic, "sub1"); - // Drain any messages that may already be in the sub - while (consumer.receive(1000) != null) { - } - consumer.close(); - - MessageProducer producer = session.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - producer.send(session.createTextMessage("Message 1")); - producer.send(session.createTextMessage("Message 2")); - producer.send(session.createTextMessage("Message 3")); - producer.close(); - - connection.close(); - connection = createConnection(); - connection.start(); - - session = connection.createSession(false, ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE); - consumer = session.createDurableSubscriber(topic, "sub1"); - - Message message = null; - for (int i = 0; i < 3; ++i) { - message = consumer.receive(5000); - assertNotNull(message); - assertEquals("Message " + (i + 1), ((TextMessage) message).getText()); - } - - message.acknowledge(); - - connection.close(); - connection = createConnection(); - connection.start(); - - session = connection.createSession(false, ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE); - consumer = session.createDurableSubscriber(topic, "sub1"); - - for (int i = 0; i < 2; ++i) { - message = consumer.receive(5000); - assertNotNull(message); - assertEquals("Message " + (i + 1), ((TextMessage) message).getText()); - } - } - - private MessageProducer createProducer(Session session, Destination queue) throws JMSException { - MessageProducer producer = session.createProducer(queue); - producer.setDeliveryMode(getDeliveryMode()); - return producer; - } - - protected int getDeliveryMode() { - return DeliveryMode.PERSISTENT; - } - - private void assertTextMessageEquals(String string, Message message) throws JMSException { - assertNotNull("Message was null", message); - assertTrue("Message is not a TextMessage", message instanceof TextMessage); - assertEquals(string, ((TextMessage) message).getText()); - } + producer.send(session.createTextMessage("Msg:1")); + + // receive and rollback + assertTextMessageEquals("Msg:1", consumer.receive(5000)); + session.rollback(); + consumer.close(); + session.close(); + + session = connection.createSession(true, javax.jms.Session.SESSION_TRANSACTED); + + // Ensure that consumer will receive messages sent and rolled back + consumer = session.createDurableSubscriber(topic, "sub1"); + + assertTextMessageEquals("Msg:1", consumer.receive(5000)); + session.commit(); + + assertNull(consumer.receive(5000)); + } + + public void xtestInactiveDurableSubscriptionOneConnection() throws Exception { + session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); + Topic topic = session.createTopic("TestTopic"); + consumer = session.createDurableSubscriber(topic, "sub1"); + producer = session.createProducer(topic); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + connection.start(); + + // Make sure it works when the durable sub is active. + producer.send(session.createTextMessage("Msg:1")); + assertTextMessageEquals("Msg:1", consumer.receive(5000)); + + // Deactivate the sub. + consumer.close(); + + // Send a new message. + producer.send(session.createTextMessage("Msg:2")); + + // Activate the sub. + consumer = session.createDurableSubscriber(topic, "sub1"); + + // Try to get the message. + assertTextMessageEquals("Msg:2", consumer.receive(5000)); + } + + public void testSelectorChange() throws Exception { + session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); + Topic topic = session.createTopic("TestTopic"); + consumer = session.createDurableSubscriber(topic, "sub1", "color='red'", false); + producer = session.createProducer(topic); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + connection.start(); + + // Make sure it works when the durable sub is active. + TextMessage msg = session.createTextMessage(); + msg.setText("Msg:1"); + msg.setStringProperty("color", "blue"); + producer.send(msg); + msg.setText("Msg:2"); + msg.setStringProperty("color", "red"); + producer.send(msg); + + assertTextMessageEquals("Msg:2", consumer.receive(5000)); + + // Change the subscription + consumer.close(); + consumer = session.createDurableSubscriber(topic, "sub1", "color='blue'", false); + + // Send a new message. + msg.setText("Msg:3"); + msg.setStringProperty("color", "red"); + producer.send(msg); + msg.setText("Msg:4"); + msg.setStringProperty("color", "blue"); + producer.send(msg); + + // Try to get the message. + assertTextMessageEquals("Msg:4", consumer.receive(5000)); + } + + public void testDurableSubWorksInNewSession() throws JMSException { + + // Create the consumer. + connection.start(); + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Topic topic = session.createTopic("topic-" + getName()); + MessageConsumer consumer = session.createDurableSubscriber(topic, "sub1"); + // Drain any messages that may already be in the sub + while (consumer.receive(1000) != null) { + } + + // See if the durable sub works in a new session. + session.close(); + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + + // Send a Message that should be added to the durable sub. + MessageProducer producer = createProducer(session, topic); + producer.send(session.createTextMessage("Message 1")); + + // Activate the durable sub now. And receive the message. + consumer = session.createDurableSubscriber(topic, "sub1"); + Message msg = consumer.receive(1000); + assertNotNull(msg); + assertEquals("Message 1", ((TextMessage) msg).getText()); + } + + public void testDurableSubWorksInNewConnection() throws Exception { + + // Create the consumer. + connection.start(); + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Topic topic = session.createTopic("topic-" + getName()); + MessageConsumer consumer = session.createDurableSubscriber(topic, "sub1"); + // Drain any messages that may already be in the sub + while (consumer.receive(1000) != null) { + } + + // See if the durable sub works in a new connection. + // The embeded broker shutsdown when his connections are closed. + // So we open the new connection before the old one is closed. + connection.close(); + connection = createConnection(); + connection.start(); + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + + // Send a Message that should be added to the durable sub. + MessageProducer producer = createProducer(session, topic); + producer.send(session.createTextMessage("Message 1")); + + // Activate the durable sub now. And receive the message. + consumer = session.createDurableSubscriber(topic, "sub1"); + Message msg = consumer.receive(1000); + assertNotNull(msg); + assertEquals("Message 1", ((TextMessage) msg).getText()); + } + + public void testIndividualAckWithDurableSubs() throws Exception { + // Create the consumer. + connection.start(); + + Session session = connection.createSession(false, ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE); + Topic topic = session.createTopic("topic-" + getName()); + MessageConsumer consumer = session.createDurableSubscriber(topic, "sub1"); + // Drain any messages that may already be in the sub + while (consumer.receive(1000) != null) { + } + consumer.close(); + + MessageProducer producer = session.createProducer(topic); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + producer.send(session.createTextMessage("Message 1")); + producer.send(session.createTextMessage("Message 2")); + producer.send(session.createTextMessage("Message 3")); + producer.close(); + + connection.close(); + connection = createConnection(); + connection.start(); + + session = connection.createSession(false, ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE); + consumer = session.createDurableSubscriber(topic, "sub1"); + + Message message = null; + for (int i = 0; i < 3; ++i) { + message = consumer.receive(5000); + assertNotNull(message); + assertEquals("Message " + (i + 1), ((TextMessage) message).getText()); + } + + message.acknowledge(); + + connection.close(); + connection = createConnection(); + connection.start(); + + session = connection.createSession(false, ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE); + consumer = session.createDurableSubscriber(topic, "sub1"); + + for (int i = 0; i < 2; ++i) { + message = consumer.receive(5000); + assertNotNull(message); + assertEquals("Message " + (i + 1), ((TextMessage) message).getText()); + } + } + + private MessageProducer createProducer(Session session, Destination queue) throws JMSException { + MessageProducer producer = session.createProducer(queue); + producer.setDeliveryMode(getDeliveryMode()); + return producer; + } + + protected int getDeliveryMode() { + return DeliveryMode.PERSISTENT; + } + + private void assertTextMessageEquals(String string, Message message) throws JMSException { + assertNotNull("Message was null", message); + assertTrue("Message is not a TextMessage", message instanceof TextMessage); + assertEquals(string, ((TextMessage) message).getText()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionUnsubscribeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionUnsubscribeTest.java index d0ecfdef90..5e7cd1adfe 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionUnsubscribeTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionUnsubscribeTest.java @@ -42,299 +42,298 @@ import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; public class DurableSubscriptionUnsubscribeTest extends TestSupport { - BrokerService broker = null; - Connection connection = null; - ActiveMQTopic topic; + BrokerService broker = null; + Connection connection = null; + ActiveMQTopic topic; - public void testJMXSubscriptionUnsubscribe() throws Exception { - doJMXUnsubscribe(false); - } + public void testJMXSubscriptionUnsubscribe() throws Exception { + doJMXUnsubscribe(false); + } - public void testJMXSubscriptionUnsubscribeWithRestart() throws Exception { - doJMXUnsubscribe(true); - } + public void testJMXSubscriptionUnsubscribeWithRestart() throws Exception { + doJMXUnsubscribe(true); + } - public void testConnectionSubscriptionUnsubscribe() throws Exception { - doConnectionUnsubscribe(false); - } + public void testConnectionSubscriptionUnsubscribe() throws Exception { + doConnectionUnsubscribe(false); + } - public void testConnectionSubscriptionUnsubscribeWithRestart() throws Exception { - doConnectionUnsubscribe(true); - } + public void testConnectionSubscriptionUnsubscribeWithRestart() throws Exception { + doConnectionUnsubscribe(true); + } - public void testDirectSubscriptionUnsubscribe() throws Exception { - doDirectUnsubscribe(false); - } + public void testDirectSubscriptionUnsubscribe() throws Exception { + doDirectUnsubscribe(false); + } - public void testDirectubscriptionUnsubscribeWithRestart() throws Exception { - doDirectUnsubscribe(true); - } + public void testDirectubscriptionUnsubscribeWithRestart() throws Exception { + doDirectUnsubscribe(true); + } - public void doJMXUnsubscribe(boolean restart) throws Exception { - createSubscriptions(); - createAdvisorySubscription(); + public void doJMXUnsubscribe(boolean restart) throws Exception { + createSubscriptions(); + createAdvisorySubscription(); - Thread.sleep(1000); - assertCount(100, 0); + Thread.sleep(1000); + assertCount(100, 0); - if (restart) { - restartBroker(); - createAdvisorySubscription(); - assertCount(100, 0); - } + if (restart) { + restartBroker(); + createAdvisorySubscription(); + assertCount(100, 0); + } - ObjectName[] subs = broker.getAdminView().getInactiveDurableTopicSubscribers(); + ObjectName[] subs = broker.getAdminView().getInactiveDurableTopicSubscribers(); - for (int i = 0; i < subs.length; i++) { - ObjectName subName = subs[i]; - DurableSubscriptionViewMBean sub = (DurableSubscriptionViewMBean)broker.getManagementContext().newProxyInstance(subName, DurableSubscriptionViewMBean.class, true); - sub.destroy(); + for (int i = 0; i < subs.length; i++) { + ObjectName subName = subs[i]; + DurableSubscriptionViewMBean sub = (DurableSubscriptionViewMBean) broker.getManagementContext().newProxyInstance(subName, DurableSubscriptionViewMBean.class, true); + sub.destroy(); - if (i % 20 == 0) { - Thread.sleep(1000); - assertCount(100 - i - 1, 0); + if (i % 20 == 0) { + Thread.sleep(1000); + assertCount(100 - i - 1, 0); + } + } + + Thread.sleep(1000); + assertCount(0, 0); + + if (restart) { + restartBroker(); + createAdvisorySubscription(); + assertCount(0, 0); + } + } + + public void doConnectionUnsubscribe(boolean restart) throws Exception { + createSubscriptions(); + createAdvisorySubscription(); + + Thread.sleep(1000); + assertCount(100, 0); + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId1"); + + Thread.sleep(1000); + assertCount(100, 1); + + Session session2 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + session2.createDurableSubscriber(topic, "SubsId2"); + + Thread.sleep(1000); + assertCount(100, 2); + + session.close(); + + Thread.sleep(1000); + assertCount(100, 1); + + session2.close(); + + Thread.sleep(1000); + assertCount(100, 0); + + if (restart) { + restartBroker(); + createAdvisorySubscription(); + assertCount(100, 0); + } + + for (int i = 0; i < 100; i++) { + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.unsubscribe("SubsId" + i); + session.close(); + + if (i % 20 == 0) { + Thread.sleep(1000); + assertCount(100 - i - 1, 0); + } + } + + Thread.sleep(1000); + assertCount(0, 0); + + if (restart) { + restartBroker(); + createAdvisorySubscription(); + assertCount(0, 0); + } + } + + public void doDirectUnsubscribe(boolean restart) throws Exception { + createSubscriptions(); + createAdvisorySubscription(); + + Thread.sleep(1000); + assertCount(100, 0); + + if (restart) { + restartBroker(); + createAdvisorySubscription(); + assertCount(100, 0); + } + + for (int i = 0; i < 100; i++) { + RemoveSubscriptionInfo info = new RemoveSubscriptionInfo(); + info.setClientId(getName()); + info.setSubscriptionName("SubsId" + i); + ConnectionContext context = new ConnectionContext(); + context.setBroker(broker.getRegionBroker()); + context.setClientId(getName()); + broker.getBroker().removeSubscription(context, info); + + if (i % 20 == 0) { + Thread.sleep(1000); + assertCount(100 - i - 1, 0); + } + } + + assertCount(0, 0); + + if (restart) { + restartBroker(); + createAdvisorySubscription(); + assertCount(0, 0); + } + } + + private void createSubscriptions() throws Exception { + for (int i = 0; i < 100; i++) { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId" + i); + session.close(); + } + } + + private final AtomicInteger advisories = new AtomicInteger(0); + + private void createAdvisorySubscription() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer advisoryConsumer = session.createConsumer(AdvisorySupport.getConsumerAdvisoryTopic(topic)); + advisoryConsumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + if (((ActiveMQMessage) message).getDataStructure() instanceof RemoveSubscriptionInfo) { + advisories.incrementAndGet(); } - } + } + }); + } - Thread.sleep(1000); - assertCount(0, 0); + private void assertCount(int all, int active) throws Exception { + int inactive = all - active; - if (restart) { - restartBroker(); - createAdvisorySubscription(); - assertCount(0, 0); - } - } + // broker check + Destination destination = broker.getDestination(topic); + List subs = destination.getConsumers(); + int cActive = 0, cInactive = 0; + for (Subscription sub : subs) { + if (sub instanceof DurableTopicSubscription) { + DurableTopicSubscription durable = (DurableTopicSubscription) sub; + if (durable.isActive()) + cActive++; + else + cInactive++; + } + } + assertEquals(active, cActive); + assertEquals(inactive, cInactive); - public void doConnectionUnsubscribe(boolean restart) throws Exception { - createSubscriptions(); - createAdvisorySubscription(); + // admin view + ObjectName[] subscriptions = broker.getAdminView().getDurableTopicSubscribers(); + assertEquals(active, subscriptions.length); + subscriptions = broker.getAdminView().getInactiveDurableTopicSubscribers(); + assertEquals(inactive, subscriptions.length); - Thread.sleep(1000); - assertCount(100, 0); + // check the strange false MBean + if (all == 0) + assertEquals(0, countMBean()); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId1"); + // check if we got all advisories + assertEquals(100, all + advisories.get()); + } - Thread.sleep(1000); - assertCount(100, 1); + private int countMBean() throws MalformedObjectNameException, InstanceNotFoundException { + int count = 0; + for (int i = 0; i < 100; i++) { + String name = "org.apache.activemq:BrokerName=" + getName() + ",Type=Subscription,active=false,name=" + getName() + "_SubsId" + i; + ObjectName sub = new ObjectName(name); + try { + broker.getManagementContext().getObjectInstance(sub); + count++; + } + catch (InstanceNotFoundException ignore) { + // this should happen + } + } + return count; + } - Session session2 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session2.createDurableSubscriber(topic, "SubsId2"); + private void startBroker(boolean deleteMessages) throws Exception { + broker = BrokerFactory.createBroker("broker:(vm://" + getName() + ")"); + broker.setUseJmx(true); + broker.getManagementContext().setCreateConnector(false); + broker.setBrokerName(getName()); - Thread.sleep(1000); - assertCount(100, 2); + broker.setPersistent(true); + KahaDBPersistenceAdapter persistenceAdapter = new KahaDBPersistenceAdapter(); + persistenceAdapter.setDirectory(new File("activemq-data/" + getName())); + broker.setPersistenceAdapter(persistenceAdapter); + if (deleteMessages) { + broker.setDeleteAllMessagesOnStartup(true); + } - session.close(); + broker.setKeepDurableSubsActive(true); - Thread.sleep(1000); - assertCount(100, 1); + broker.start(); + broker.waitUntilStarted(); - session2.close(); + connection = createConnection(); + } - Thread.sleep(1000); - assertCount(100, 0); + private void stopBroker() throws Exception { + if (connection != null) + connection.close(); + connection = null; - if (restart) { - restartBroker(); - createAdvisorySubscription(); - assertCount(100, 0); - } + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + broker = null; + } - for (int i = 0; i < 100; i++) { - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.unsubscribe("SubsId" + i); - session.close(); + private void restartBroker() throws Exception { + stopBroker(); + startBroker(false); + } - if (i % 20 == 0) { - Thread.sleep(1000); - assertCount(100 - i - 1, 0); - } - } + @Override + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory("vm://" + getName() + "?waitForStart=5000&create=false"); + } - Thread.sleep(1000); - assertCount(0, 0); + @Override + protected void setUp() throws Exception { + super.setUp(); - if (restart) { - restartBroker(); - createAdvisorySubscription(); - assertCount(0, 0); - } - } + topic = (ActiveMQTopic) createDestination(); + startBroker(true); + } - public void doDirectUnsubscribe(boolean restart) throws Exception { - createSubscriptions(); - createAdvisorySubscription(); + @Override + protected void tearDown() throws Exception { + stopBroker(); + super.tearDown(); + } - Thread.sleep(1000); - assertCount(100, 0); - - if (restart) { - restartBroker(); - createAdvisorySubscription(); - assertCount(100, 0); - } - - for (int i = 0; i < 100; i++) { - RemoveSubscriptionInfo info = new RemoveSubscriptionInfo(); - info.setClientId(getName()); - info.setSubscriptionName("SubsId" + i); - ConnectionContext context = new ConnectionContext(); - context.setBroker(broker.getRegionBroker()); - context.setClientId(getName()); - broker.getBroker().removeSubscription(context, info); - - if (i % 20 == 0) { - Thread.sleep(1000); - assertCount(100 - i - 1, 0); - } - } - - assertCount(0, 0); - - if (restart) { - restartBroker(); - createAdvisorySubscription(); - assertCount(0, 0); - } - } - - private void createSubscriptions() throws Exception { - for (int i = 0; i < 100; i++) { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId" + i); - session.close(); - } - } - - private final AtomicInteger advisories = new AtomicInteger(0); - - private void createAdvisorySubscription() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer advisoryConsumer = session.createConsumer(AdvisorySupport.getConsumerAdvisoryTopic(topic)); - advisoryConsumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - if (((ActiveMQMessage)message).getDataStructure() instanceof RemoveSubscriptionInfo) { - advisories.incrementAndGet(); - } - } - }); - } - - private void assertCount(int all, int active) throws Exception { - int inactive = all - active; - - // broker check - Destination destination = broker.getDestination(topic); - List subs = destination.getConsumers(); - int cActive = 0, cInactive = 0; - for (Subscription sub: subs) { - if (sub instanceof DurableTopicSubscription) { - DurableTopicSubscription durable = (DurableTopicSubscription) sub; - if (durable.isActive()) - cActive++; - else - cInactive++; - } - } - assertEquals(active, cActive); - assertEquals(inactive, cInactive); - - // admin view - ObjectName[] subscriptions = broker.getAdminView().getDurableTopicSubscribers(); - assertEquals(active, subscriptions.length); - subscriptions = broker.getAdminView().getInactiveDurableTopicSubscribers(); - assertEquals(inactive, subscriptions.length); - - // check the strange false MBean - if (all == 0) - assertEquals(0, countMBean()); - - // check if we got all advisories - assertEquals(100, all + advisories.get()); - } - - private int countMBean() throws MalformedObjectNameException, InstanceNotFoundException { - int count = 0; - for (int i = 0; i < 100; i++) { - String name = "org.apache.activemq:BrokerName=" + getName() + ",Type=Subscription,active=false,name=" + getName() + "_SubsId" + i; - ObjectName sub = new ObjectName(name); - try { - broker.getManagementContext().getObjectInstance(sub); - count++; - } - catch (InstanceNotFoundException ignore) { - // this should happen - } - } - return count; - } - - private void startBroker(boolean deleteMessages) throws Exception { - broker = BrokerFactory.createBroker("broker:(vm://" + getName() + ")"); - broker.setUseJmx(true); - broker.getManagementContext().setCreateConnector(false); - broker.setBrokerName(getName()); - - broker.setPersistent(true); - KahaDBPersistenceAdapter persistenceAdapter = new KahaDBPersistenceAdapter(); - persistenceAdapter.setDirectory(new File("activemq-data/" + getName())); - broker.setPersistenceAdapter(persistenceAdapter); - if (deleteMessages) { - broker.setDeleteAllMessagesOnStartup(true); - } - - - broker.setKeepDurableSubsActive(true); - - broker.start(); - broker.waitUntilStarted(); - - connection = createConnection(); - } - - private void stopBroker() throws Exception { - if (connection != null) - connection.close(); - connection = null; - - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - broker = null; - } - - private void restartBroker() throws Exception { - stopBroker(); - startBroker(false); - } - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://" + getName() + "?waitForStart=5000&create=false"); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - - topic = (ActiveMQTopic) createDestination(); - startBroker(true); - } - - @Override - protected void tearDown() throws Exception { - stopBroker(); - super.tearDown(); - } - - @Override - protected Connection createConnection() throws Exception { - Connection rc = super.createConnection(); - rc.setClientID(getName()); - rc.start(); - return rc; - } + @Override + protected Connection createConnection() throws Exception { + Connection rc = super.createConnection(); + rc.setClientID(getName()); + rc.start(); + return rc; + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableUnsubscribeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableUnsubscribeTest.java index b42ce52d31..8a8839c510 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableUnsubscribeTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableUnsubscribeTest.java @@ -32,88 +32,87 @@ import org.apache.activemq.command.ActiveMQTopic; public class DurableUnsubscribeTest extends org.apache.activemq.TestSupport { - private BrokerService broker; - private Connection connection; - private ActiveMQTopic topic; + private BrokerService broker; + private Connection connection; + private ActiveMQTopic topic; - public void testUnsubscribe() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId"); - session.close(); + public void testUnsubscribe() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId"); + session.close(); - Destination d = broker.getDestination(topic); - assertEquals("Subscription is missing.", 1, d.getConsumers().size()); + Destination d = broker.getDestination(topic); + assertEquals("Subscription is missing.", 1, d.getConsumers().size()); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(topic); + for (int i = 0; i < 1000; i++) { + producer.send(session.createTextMessage("text")); + } - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(topic); - for (int i = 0; i < 1000; i++) { - producer.send(session.createTextMessage("text")); - } + Thread.sleep(1000); - Thread.sleep(1000); + session.unsubscribe("SubsId"); + session.close(); - session.unsubscribe("SubsId"); - session.close(); + assertEquals("Subscription exists.", 0, d.getConsumers().size()); + } - assertEquals("Subscription exists.", 0, d.getConsumers().size()); - } + public void testDestroy() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId2"); + session.close(); - public void testDestroy() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId2"); - session.close(); + connection.close(); + connection = null; + Thread.sleep(1000); - connection.close(); - connection = null; - Thread.sleep(1000); + Destination d = broker.getDestination(topic); + assertEquals("Subscription is missing.", 1, d.getConsumers().size()); - Destination d = broker.getDestination(topic); - assertEquals("Subscription is missing.", 1, d.getConsumers().size()); + MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); + ObjectName[] subNames = broker.getAdminView().getInactiveDurableTopicSubscribers(); + mbs.invoke(subNames[0], "destroy", new Object[0], new String[0]); - MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); - ObjectName[] subNames = broker.getAdminView().getInactiveDurableTopicSubscribers(); - mbs.invoke(subNames[0], "destroy", new Object[0], new String[0]); + assertEquals("Subscription exists.", 0, d.getConsumers().size()); + } - assertEquals("Subscription exists.", 0, d.getConsumers().size()); - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory("vm://" + getName()); + } - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://" + getName()); - } + protected Connection createConnection() throws Exception { + Connection rc = super.createConnection(); + rc.setClientID(getName()); + return rc; + } - protected Connection createConnection() throws Exception { - Connection rc = super.createConnection(); - rc.setClientID(getName()); - return rc; - } + protected void setUp() throws Exception { + topic = (ActiveMQTopic) createDestination(); + createBroker(); + super.setUp(); + } - protected void setUp() throws Exception { - topic = (ActiveMQTopic) createDestination(); - createBroker(); - super.setUp(); - } + protected void tearDown() throws Exception { + super.tearDown(); + destroyBroker(); + } - protected void tearDown() throws Exception { - super.tearDown(); - destroyBroker(); - } + private void createBroker() throws Exception { + broker = BrokerFactory.createBroker("broker:(vm://localhost)"); + //broker.setPersistent(false); + broker.setUseJmx(true); + broker.setBrokerName(getName()); + broker.deleteAllMessages(); + broker.start(); - private void createBroker() throws Exception { - broker = BrokerFactory.createBroker("broker:(vm://localhost)"); - //broker.setPersistent(false); - broker.setUseJmx(true); - broker.setBrokerName(getName()); - broker.deleteAllMessages(); - broker.start(); + connection = createConnection(); + } - connection = createConnection(); - } - - private void destroyBroker() throws Exception { - if (connection != null) - connection.close(); - if (broker != null) - broker.stop(); - } + private void destroyBroker() throws Exception { + if (connection != null) + connection.close(); + if (broker != null) + broker.stop(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ExceptionListenerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ExceptionListenerTest.java index e426b126b2..a7c91deed2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ExceptionListenerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ExceptionListenerTest.java @@ -24,6 +24,7 @@ import javax.jms.ExceptionListener; import javax.jms.JMSException; import javax.jms.JMSSecurityException; import javax.jms.Session; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ConnectionFailedException; import org.apache.activemq.broker.BrokerPlugin; @@ -36,7 +37,6 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -45,74 +45,77 @@ import static org.junit.Assert.fail; * @author Oliver Belikan */ public class ExceptionListenerTest implements ExceptionListener { - private static final Logger LOG = LoggerFactory.getLogger(ExceptionListenerTest.class); - BrokerService brokerService; - URI brokerUri; - LinkedList exceptionsViaListener = new LinkedList(); - @Before - public void startBroker() throws Exception { - brokerService = new BrokerService(); - brokerService.setAdvisorySupport(false); - brokerService.setUseJmx(false); - brokerService.setPersistent(false); - brokerService.setPlugins(new BrokerPlugin[]{new SimpleAuthenticationPlugin(new ArrayList())}); - brokerUri = brokerService.addConnector("tcp://0.0.0.0:0").getConnectUri(); - brokerService.start(); - } + private static final Logger LOG = LoggerFactory.getLogger(ExceptionListenerTest.class); + BrokerService brokerService; + URI brokerUri; + LinkedList exceptionsViaListener = new LinkedList(); - @After - public void stopBroker() throws Exception { - exceptionsViaListener.clear(); - if (brokerService != null) { - brokerService.stop(); - } - } + @Before + public void startBroker() throws Exception { + brokerService = new BrokerService(); + brokerService.setAdvisorySupport(false); + brokerService.setUseJmx(false); + brokerService.setPersistent(false); + brokerService.setPlugins(new BrokerPlugin[]{new SimpleAuthenticationPlugin(new ArrayList())}); + brokerUri = brokerService.addConnector("tcp://0.0.0.0:0").getConnectUri(); + brokerService.start(); + } - @Test - public void fireOnSecurityException() throws Exception { - doFireOnSecurityException(new ActiveMQConnectionFactory(brokerUri)); - } + @After + public void stopBroker() throws Exception { + exceptionsViaListener.clear(); + if (brokerService != null) { + brokerService.stop(); + } + } - @Test - public void fireOnSecurityExceptionFailover() throws Exception { - doFireOnSecurityException(new ActiveMQConnectionFactory("failover://" + brokerUri)); - } + @Test + public void fireOnSecurityException() throws Exception { + doFireOnSecurityException(new ActiveMQConnectionFactory(brokerUri)); + } - public void doFireOnSecurityException(ActiveMQConnectionFactory factory) throws Exception { - factory.setWatchTopicAdvisories(false); - Connection connection = factory.createConnection(); - connection.setExceptionListener(this); + @Test + public void fireOnSecurityExceptionFailover() throws Exception { + doFireOnSecurityException(new ActiveMQConnectionFactory("failover://" + brokerUri)); + } - try { - connection.start(); - fail("Expect securityException"); - } catch (JMSSecurityException expected) { - expected.printStackTrace(); - assertTrue("nested security exception: " + expected, expected.getCause() instanceof SecurityException); - } + public void doFireOnSecurityException(ActiveMQConnectionFactory factory) throws Exception { + factory.setWatchTopicAdvisories(false); + Connection connection = factory.createConnection(); + connection.setExceptionListener(this); - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return !exceptionsViaListener.isEmpty(); - } - }); - Throwable expected = exceptionsViaListener.getFirst(); - assertNotNull(expected); - assertNotNull(expected.getCause()); + try { + connection.start(); + fail("Expect securityException"); + } + catch (JMSSecurityException expected) { + expected.printStackTrace(); + assertTrue("nested security exception: " + expected, expected.getCause() instanceof SecurityException); + } - assertTrue("expected exception: " + expected, expected.getCause().getCause() instanceof SecurityException); + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return !exceptionsViaListener.isEmpty(); + } + }); + Throwable expected = exceptionsViaListener.getFirst(); + assertNotNull(expected); + assertNotNull(expected.getCause()); - try { - connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - fail("Expect error b/c connection is auto closed on security exception above"); - } catch (ConnectionFailedException e) { - } - } + assertTrue("expected exception: " + expected, expected.getCause().getCause() instanceof SecurityException); - public void onException(JMSException e) { - LOG.info("onException:" + e, new Throwable("FromHere")); - exceptionsViaListener.add(e); - } + try { + connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + fail("Expect error b/c connection is auto closed on security exception above"); + } + catch (ConnectionFailedException e) { + } + } + + public void onException(JMSException e) { + LOG.info("onException:" + e, new Throwable("FromHere")); + exceptionsViaListener.add(e); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ExpiredMessagesTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ExpiredMessagesTest.java index 02055991fc..d1f1358180 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ExpiredMessagesTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ExpiredMessagesTest.java @@ -42,280 +42,266 @@ import static org.apache.activemq.TestSupport.getDestinationStatistics; public class ExpiredMessagesTest extends CombinationTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(ExpiredMessagesTest.class); + private static final Logger LOG = LoggerFactory.getLogger(ExpiredMessagesTest.class); - BrokerService broker; - Connection connection; - Session session; - MessageProducer producer; - MessageConsumer consumer; - public ActiveMQDestination destination = new ActiveMQQueue("test"); - public ActiveMQDestination dlqDestination = new ActiveMQQueue("ActiveMQ.DLQ"); - public boolean useTextMessage = true; - public boolean useVMCursor = true; - protected String brokerUri; + BrokerService broker; + Connection connection; + Session session; + MessageProducer producer; + MessageConsumer consumer; + public ActiveMQDestination destination = new ActiveMQQueue("test"); + public ActiveMQDestination dlqDestination = new ActiveMQQueue("ActiveMQ.DLQ"); + public boolean useTextMessage = true; + public boolean useVMCursor = true; + protected String brokerUri; - public static Test suite() { - return suite(ExpiredMessagesTest.class); - } + public static Test suite() { + return suite(ExpiredMessagesTest.class); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - @Override - protected void setUp() throws Exception { - final boolean deleteAllMessages = true; - broker = createBroker(deleteAllMessages, 100); - brokerUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); - } + @Override + protected void setUp() throws Exception { + final boolean deleteAllMessages = true; + broker = createBroker(deleteAllMessages, 100); + brokerUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); + } - @Override - protected void tearDown() throws Exception { - connection.stop(); - broker.stop(); - broker.waitUntilStopped(); - } + @Override + protected void tearDown() throws Exception { + connection.stop(); + broker.stop(); + broker.waitUntilStopped(); + } - public void testExpiredMessages() throws Exception { + public void testExpiredMessages() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerUri); - connection = factory.createConnection(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(destination); - producer.setTimeToLive(100); - consumer = session.createConsumer(destination); - connection.start(); - final AtomicLong received = new AtomicLong(); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerUri); + connection = factory.createConnection(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer = session.createProducer(destination); + producer.setTimeToLive(100); + consumer = session.createConsumer(destination); + connection.start(); + final AtomicLong received = new AtomicLong(); - Thread consumerThread = new Thread("Consumer Thread") { - @Override - public void run() { - long start = System.currentTimeMillis(); - try { - long end = System.currentTimeMillis(); - while (end - start < 3000) { - if (consumer.receive(1000) != null) { - received.incrementAndGet(); - } - Thread.sleep(100); - end = System.currentTimeMillis(); - } - consumer.close(); - } catch (Throwable ex) { - ex.printStackTrace(); - } + Thread consumerThread = new Thread("Consumer Thread") { + @Override + public void run() { + long start = System.currentTimeMillis(); + try { + long end = System.currentTimeMillis(); + while (end - start < 3000) { + if (consumer.receive(1000) != null) { + received.incrementAndGet(); + } + Thread.sleep(100); + end = System.currentTimeMillis(); + } + consumer.close(); } - }; - - consumerThread.start(); - - final int numMessagesToSend = 10000; - Thread producingThread = new Thread("Producing Thread") { - @Override - public void run() { - try { - int i = 0; - while (i++ < numMessagesToSend) { - producer.send(session.createTextMessage("test")); - } - producer.close(); - } catch (Throwable ex) { - ex.printStackTrace(); - } + catch (Throwable ex) { + ex.printStackTrace(); } - }; + } + }; - producingThread.start(); + consumerThread.start(); - consumerThread.join(); - producingThread.join(); - session.close(); - - final DestinationStatistics view = getDestinationStatistics(broker, destination); - - // wait for all to inflight to expire - assertTrue("all inflight messages expired ", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return view.getInflight().getCount() == 0; + final int numMessagesToSend = 10000; + Thread producingThread = new Thread("Producing Thread") { + @Override + public void run() { + try { + int i = 0; + while (i++ < numMessagesToSend) { + producer.send(session.createTextMessage("test")); + } + producer.close(); } - })); - assertEquals("Wrong inFlightCount: ", 0, view.getInflight().getCount()); - - LOG.info("Stats: received: " + received.get() + ", enqueues: " + view.getEnqueues().getCount() + ", dequeues: " + view.getDequeues().getCount() - + ", dispatched: " + view.getDispatched().getCount() + ", inflight: " + view.getInflight().getCount() + ", expiries: " + view.getExpired().getCount()); - - // wait for all sent to get delivered and expire - assertTrue("all sent messages expired ", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - long oldEnqueues = view.getEnqueues().getCount(); - Thread.sleep(200); - LOG.info("Stats: received: " + received.get() + ", size= " + view.getMessages().getCount() + ", enqueues: " + view.getDequeues().getCount() + ", dequeues: " + view.getDequeues().getCount() - + ", dispatched: " + view.getDispatched().getCount() + ", inflight: " + view.getInflight().getCount() + ", expiries: " + view.getExpired().getCount()); - return oldEnqueues == view.getEnqueues().getCount(); + catch (Throwable ex) { + ex.printStackTrace(); } - }, 60*1000)); + } + }; + producingThread.start(); - LOG.info("Stats: received: " + received.get() + ", size= " + view.getMessages().getCount() + ", enqueues: " + view.getEnqueues().getCount() + ", dequeues: " + view.getDequeues().getCount() - + ", dispatched: " + view.getDispatched().getCount() + ", inflight: " + view.getInflight().getCount() + ", expiries: " + view.getExpired().getCount()); + consumerThread.join(); + producingThread.join(); + session.close(); - assertTrue("got at least what did not expire", received.get() >= view.getDequeues().getCount() - view.getExpired().getCount()); + final DestinationStatistics view = getDestinationStatistics(broker, destination); - assertTrue("all messages expired - queue size gone to zero " + view.getMessages().getCount(), Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("Stats: received: " + received.get() + ", size= " + view.getMessages().getCount() + ", enqueues: " + view.getEnqueues().getCount() + ", dequeues: " + view.getDequeues().getCount() - + ", dispatched: " + view.getDispatched().getCount() + ", inflight: " + view.getInflight().getCount() + ", expiries: " + view.getExpired().getCount()); - return view.getMessages().getCount() == 0; + // wait for all to inflight to expire + assertTrue("all inflight messages expired ", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return view.getInflight().getCount() == 0; + } + })); + assertEquals("Wrong inFlightCount: ", 0, view.getInflight().getCount()); + + LOG.info("Stats: received: " + received.get() + ", enqueues: " + view.getEnqueues().getCount() + ", dequeues: " + view.getDequeues().getCount() + ", dispatched: " + view.getDispatched().getCount() + ", inflight: " + view.getInflight().getCount() + ", expiries: " + view.getExpired().getCount()); + + // wait for all sent to get delivered and expire + assertTrue("all sent messages expired ", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + long oldEnqueues = view.getEnqueues().getCount(); + Thread.sleep(200); + LOG.info("Stats: received: " + received.get() + ", size= " + view.getMessages().getCount() + ", enqueues: " + view.getDequeues().getCount() + ", dequeues: " + view.getDequeues().getCount() + ", dispatched: " + view.getDispatched().getCount() + ", inflight: " + view.getInflight().getCount() + ", expiries: " + view.getExpired().getCount()); + return oldEnqueues == view.getEnqueues().getCount(); + } + }, 60 * 1000)); + + LOG.info("Stats: received: " + received.get() + ", size= " + view.getMessages().getCount() + ", enqueues: " + view.getEnqueues().getCount() + ", dequeues: " + view.getDequeues().getCount() + ", dispatched: " + view.getDispatched().getCount() + ", inflight: " + view.getInflight().getCount() + ", expiries: " + view.getExpired().getCount()); + + assertTrue("got at least what did not expire", received.get() >= view.getDequeues().getCount() - view.getExpired().getCount()); + + assertTrue("all messages expired - queue size gone to zero " + view.getMessages().getCount(), Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("Stats: received: " + received.get() + ", size= " + view.getMessages().getCount() + ", enqueues: " + view.getEnqueues().getCount() + ", dequeues: " + view.getDequeues().getCount() + ", dispatched: " + view.getDispatched().getCount() + ", inflight: " + view.getInflight().getCount() + ", expiries: " + view.getExpired().getCount()); + return view.getMessages().getCount() == 0; + } + })); + + final long expiredBeforeEnqueue = numMessagesToSend - view.getEnqueues().getCount(); + final long totalExpiredCount = view.getExpired().getCount() + expiredBeforeEnqueue; + + final DestinationStatistics dlqView = getDestinationStatistics(broker, dlqDestination); + LOG.info("DLQ stats: size= " + dlqView.getMessages().getCount() + ", enqueues: " + dlqView.getDequeues().getCount() + ", dequeues: " + dlqView.getDequeues().getCount() + ", dispatched: " + dlqView.getDispatched().getCount() + ", inflight: " + dlqView.getInflight().getCount() + ", expiries: " + dlqView.getExpired().getCount()); + + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return totalExpiredCount == dlqView.getMessages().getCount(); + } + }); + assertEquals("dlq contains all expired", totalExpiredCount, dlqView.getMessages().getCount()); + + // memory check + assertEquals("memory usage is back to duck egg", 0, getDestination(broker, destination).getMemoryUsage().getPercentUsage()); + assertTrue("memory usage is increased ", 0 < getDestination(broker, dlqDestination).getMemoryUsage().getUsage()); + + // verify DLQ + MessageConsumer dlqConsumer = createDlqConsumer(connection); + final DLQListener dlqListener = new DLQListener(); + dlqConsumer.setMessageListener(dlqListener); + + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return totalExpiredCount == dlqListener.count; + } + }, 60 * 1000); + + assertEquals("dlq returned all expired", dlqListener.count, totalExpiredCount); + } + + class DLQListener implements MessageListener { + + int count = 0; + + @Override + public void onMessage(Message message) { + count++; + } + + } + + ; + + private MessageConsumer createDlqConsumer(Connection connection) throws Exception { + return connection.createSession(false, Session.AUTO_ACKNOWLEDGE).createConsumer(dlqDestination); + } + + public void initCombosForTestRecoverExpiredMessages() { + addCombinationValues("useVMCursor", new Object[]{Boolean.TRUE, Boolean.FALSE}); + } + + public void testRecoverExpiredMessages() throws Exception { + + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("failover://" + brokerUri); + connection = factory.createConnection(); + connection.start(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer = session.createProducer(destination); + producer.setTimeToLive(2000); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + + Thread producingThread = new Thread("Producing Thread") { + @Override + public void run() { + try { + int i = 0; + while (i++ < 1000) { + Message message = useTextMessage ? session.createTextMessage("test") : session.createObjectMessage("test"); + producer.send(message); + } + producer.close(); } - })); - - final long expiredBeforeEnqueue = numMessagesToSend - view.getEnqueues().getCount(); - final long totalExpiredCount = view.getExpired().getCount() + expiredBeforeEnqueue; - - final DestinationStatistics dlqView = getDestinationStatistics(broker, dlqDestination); - LOG.info("DLQ stats: size= " + dlqView.getMessages().getCount() + ", enqueues: " + dlqView.getDequeues().getCount() + ", dequeues: " + dlqView.getDequeues().getCount() - + ", dispatched: " + dlqView.getDispatched().getCount() + ", inflight: " + dlqView.getInflight().getCount() + ", expiries: " + dlqView.getExpired().getCount()); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return totalExpiredCount == dlqView.getMessages().getCount(); + catch (Throwable ex) { + ex.printStackTrace(); } - }); - assertEquals("dlq contains all expired", totalExpiredCount, dlqView.getMessages().getCount()); + } + }; - // memory check - assertEquals("memory usage is back to duck egg", 0, getDestination(broker, destination).getMemoryUsage().getPercentUsage()); - assertTrue("memory usage is increased ", 0 < getDestination(broker, dlqDestination).getMemoryUsage().getUsage()); + producingThread.start(); + producingThread.join(); - // verify DLQ - MessageConsumer dlqConsumer = createDlqConsumer(connection); - final DLQListener dlqListener = new DLQListener(); - dlqConsumer.setMessageListener(dlqListener); + DestinationStatistics view = getDestinationStatistics(broker, destination); + LOG.info("Stats: size: " + view.getMessages().getCount() + ", enqueues: " + view.getEnqueues().getCount() + ", dequeues: " + view.getDequeues().getCount() + ", dispatched: " + view.getDispatched().getCount() + ", inflight: " + view.getInflight().getCount() + ", expiries: " + view.getExpired().getCount()); - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return totalExpiredCount == dlqListener.count; - } - }, 60 * 1000); + LOG.info("stopping broker"); + broker.stop(); + broker.waitUntilStopped(); - assertEquals("dlq returned all expired", dlqListener.count, totalExpiredCount); - } + Thread.sleep(5000); - class DLQListener implements MessageListener { + LOG.info("recovering broker"); + final boolean deleteAllMessages = false; + broker = createBroker(deleteAllMessages, 5000); - int count = 0; + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + DestinationStatistics view = getDestinationStatistics(broker, destination); + LOG.info("Stats: size: " + view.getMessages().getCount() + ", enqueues: " + view.getEnqueues().getCount() + ", dequeues: " + view.getDequeues().getCount() + ", dispatched: " + view.getDispatched().getCount() + ", inflight: " + view.getInflight().getCount() + ", expiries: " + view.getExpired().getCount()); - @Override - public void onMessage(Message message) { - count++; - } + return view.getMessages().getCount() == 0; + } + }); - }; + view = getDestinationStatistics(broker, destination); + assertEquals("Expect empty queue, QueueSize: ", 0, view.getMessages().getCount()); + assertEquals("all dequeues were expired", view.getDequeues().getCount(), view.getExpired().getCount()); + } - private MessageConsumer createDlqConsumer(Connection connection) throws Exception { - return connection.createSession(false, Session.AUTO_ACKNOWLEDGE).createConsumer(dlqDestination); - } + private BrokerService createBroker(boolean deleteAllMessages, long expireMessagesPeriod) throws Exception { + BrokerService broker = new BrokerService(); + broker.setBrokerName("localhost"); + broker.setDestinations(new ActiveMQDestination[]{destination}); + broker.setPersistenceAdapter(new MemoryPersistenceAdapter()); - public void initCombosForTestRecoverExpiredMessages() { - addCombinationValues("useVMCursor", new Object[] {Boolean.TRUE, Boolean.FALSE}); - } - - public void testRecoverExpiredMessages() throws Exception { - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory( - "failover://"+brokerUri); - connection = factory.createConnection(); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(destination); - producer.setTimeToLive(2000); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - - Thread producingThread = new Thread("Producing Thread") { - @Override - public void run() { - try { - int i = 0; - while (i++ < 1000) { - Message message = useTextMessage ? session - .createTextMessage("test") : session - .createObjectMessage("test"); - producer.send(message); - } - producer.close(); - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - }; - - producingThread.start(); - producingThread.join(); - - DestinationStatistics view = getDestinationStatistics(broker, destination); - LOG.info("Stats: size: " + view.getMessages().getCount() + ", enqueues: " - + view.getEnqueues().getCount() + ", dequeues: " - + view.getDequeues().getCount() + ", dispatched: " - + view.getDispatched().getCount() + ", inflight: " - + view.getInflight().getCount() + ", expiries: " - + view.getExpired().getCount()); - - LOG.info("stopping broker"); - broker.stop(); - broker.waitUntilStopped(); - - Thread.sleep(5000); - - LOG.info("recovering broker"); - final boolean deleteAllMessages = false; - broker = createBroker(deleteAllMessages, 5000); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - DestinationStatistics view = getDestinationStatistics(broker, destination); - LOG.info("Stats: size: " + view.getMessages().getCount() + ", enqueues: " - + view.getEnqueues().getCount() + ", dequeues: " - + view.getDequeues().getCount() + ", dispatched: " - + view.getDispatched().getCount() + ", inflight: " - + view.getInflight().getCount() + ", expiries: " - + view.getExpired().getCount()); - - return view.getMessages().getCount() == 0; - } - }); - - view = getDestinationStatistics(broker, destination); - assertEquals("Expect empty queue, QueueSize: ", 0, view.getMessages().getCount()); - assertEquals("all dequeues were expired", view.getDequeues().getCount(), view.getExpired().getCount()); - } - - private BrokerService createBroker(boolean deleteAllMessages, long expireMessagesPeriod) throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("localhost"); - broker.setDestinations(new ActiveMQDestination[]{destination}); - broker.setPersistenceAdapter(new MemoryPersistenceAdapter()); - - PolicyEntry defaultPolicy = new PolicyEntry(); - if (useVMCursor) { - defaultPolicy.setPendingQueuePolicy(new VMPendingQueueMessageStoragePolicy()); - } - defaultPolicy.setExpireMessagesPeriod(expireMessagesPeriod); - defaultPolicy.setMaxExpirePageSize(1200); - PolicyMap policyMap = new PolicyMap(); - policyMap.setDefaultEntry(defaultPolicy); - broker.setDestinationPolicy(policyMap); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - broker.addConnector("tcp://localhost:0"); - broker.start(); - broker.waitUntilStarted(); - return broker; - } + PolicyEntry defaultPolicy = new PolicyEntry(); + if (useVMCursor) { + defaultPolicy.setPendingQueuePolicy(new VMPendingQueueMessageStoragePolicy()); + } + defaultPolicy.setExpireMessagesPeriod(expireMessagesPeriod); + defaultPolicy.setMaxExpirePageSize(1200); + PolicyMap policyMap = new PolicyMap(); + policyMap.setDefaultEntry(defaultPolicy); + broker.setDestinationPolicy(policyMap); + broker.setDeleteAllMessagesOnStartup(deleteAllMessages); + broker.addConnector("tcp://localhost:0"); + broker.start(); + broker.waitUntilStarted(); + return broker; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ExpiredMessagesWithNoConsumerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ExpiredMessagesWithNoConsumerTest.java index e2ad7f602a..caf6f99f2b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ExpiredMessagesWithNoConsumerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ExpiredMessagesWithNoConsumerTest.java @@ -51,564 +51,544 @@ import org.slf4j.LoggerFactory; public class ExpiredMessagesWithNoConsumerTest extends CombinationTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(ExpiredMessagesWithNoConsumerTest.class); + private static final Logger LOG = LoggerFactory.getLogger(ExpiredMessagesWithNoConsumerTest.class); - private final ActiveMQDestination destination = new ActiveMQQueue("test"); + private final ActiveMQDestination destination = new ActiveMQQueue("test"); - private boolean optimizedDispatch = true; - private PendingQueueMessageStoragePolicy pendingQueuePolicy; + private boolean optimizedDispatch = true; + private PendingQueueMessageStoragePolicy pendingQueuePolicy; - private BrokerService broker; - private String connectionUri; - private Connection connection; - private Session session; - private MessageProducer producer; + private BrokerService broker; + private String connectionUri; + private Connection connection; + private Session session; + private MessageProducer producer; - public static Test suite() { - return suite(ExpiredMessagesWithNoConsumerTest.class); - } + public static Test suite() { + return suite(ExpiredMessagesWithNoConsumerTest.class); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - protected void createBrokerWithMemoryLimit() throws Exception { - createBrokerWithMemoryLimit(800); - } + protected void createBrokerWithMemoryLimit() throws Exception { + createBrokerWithMemoryLimit(800); + } - protected void createBrokerWithMemoryLimit(int expireMessagesPeriod) throws Exception { - doCreateBroker(true, expireMessagesPeriod); - } + protected void createBrokerWithMemoryLimit(int expireMessagesPeriod) throws Exception { + doCreateBroker(true, expireMessagesPeriod); + } - protected void createBroker() throws Exception { - doCreateBroker(false, 800); - } + protected void createBroker() throws Exception { + doCreateBroker(false, 800); + } - private void doCreateBroker(boolean memoryLimit, int expireMessagesPeriod) throws Exception { - broker = new BrokerService(); - broker.setBrokerName("localhost"); - broker.setUseJmx(true); - broker.setDeleteAllMessagesOnStartup(true); - broker.addConnector("tcp://localhost:0"); + private void doCreateBroker(boolean memoryLimit, int expireMessagesPeriod) throws Exception { + broker = new BrokerService(); + broker.setBrokerName("localhost"); + broker.setUseJmx(true); + broker.setDeleteAllMessagesOnStartup(true); + broker.addConnector("tcp://localhost:0"); - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setOptimizedDispatch(optimizedDispatch); - defaultEntry.setExpireMessagesPeriod(expireMessagesPeriod); - defaultEntry.setMaxExpirePageSize(800); + PolicyMap policyMap = new PolicyMap(); + PolicyEntry defaultEntry = new PolicyEntry(); + defaultEntry.setOptimizedDispatch(optimizedDispatch); + defaultEntry.setExpireMessagesPeriod(expireMessagesPeriod); + defaultEntry.setMaxExpirePageSize(800); - defaultEntry.setPendingQueuePolicy(pendingQueuePolicy); + defaultEntry.setPendingQueuePolicy(pendingQueuePolicy); - if (memoryLimit) { - // so memory is not consumed by DLQ turn if off - defaultEntry.setDeadLetterStrategy(null); - defaultEntry.setMemoryLimit(200 * 1000); - } + if (memoryLimit) { + // so memory is not consumed by DLQ turn if off + defaultEntry.setDeadLetterStrategy(null); + defaultEntry.setMemoryLimit(200 * 1000); + } - policyMap.setDefaultEntry(defaultEntry); + policyMap.setDefaultEntry(defaultEntry); - broker.setDestinationPolicy(policyMap); - broker.start(); - broker.waitUntilStarted(); + broker.setDestinationPolicy(policyMap); + broker.start(); + broker.waitUntilStarted(); - connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); - } + connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); + } - public void testExpiredNonPersistentMessagesWithNoConsumer() throws Exception { + public void testExpiredNonPersistentMessagesWithNoConsumer() throws Exception { - createBrokerWithMemoryLimit(2000); + createBrokerWithMemoryLimit(2000); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - connection = factory.createConnection(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(destination); - producer.setTimeToLive(1000); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - connection.start(); - final long sendCount = 2000; + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); + connection = factory.createConnection(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer = session.createProducer(destination); + producer.setTimeToLive(1000); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + connection.start(); + final long sendCount = 2000; - final Thread producingThread = new Thread("Producing Thread") { - @Override - public void run() { - try { - int i = 0; - long tStamp = System.currentTimeMillis(); - while (i++ < sendCount) { - producer.send(session.createTextMessage("test")); - if (i%100 == 0) { - LOG.info("sent: " + i + " @ " + ((System.currentTimeMillis() - tStamp) / 100) + "m/ms"); - tStamp = System.currentTimeMillis() ; - } + final Thread producingThread = new Thread("Producing Thread") { + @Override + public void run() { + try { + int i = 0; + long tStamp = System.currentTimeMillis(); + while (i++ < sendCount) { + producer.send(session.createTextMessage("test")); + if (i % 100 == 0) { + LOG.info("sent: " + i + " @ " + ((System.currentTimeMillis() - tStamp) / 100) + "m/ms"); + tStamp = System.currentTimeMillis(); + } - if (135 == i) { - // allow pending messages to expire, before usage limit kicks in to flush them - TimeUnit.SECONDS.sleep(5); - } - } - } catch (Throwable ex) { - ex.printStackTrace(); - } + if (135 == i) { + // allow pending messages to expire, before usage limit kicks in to flush them + TimeUnit.SECONDS.sleep(5); + } + } } - }; - - producingThread.start(); - - assertTrue("producer failed to complete within allocated time", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - producingThread.join(TimeUnit.SECONDS.toMillis(3000)); - return !producingThread.isAlive(); + catch (Throwable ex) { + ex.printStackTrace(); } - })); + } + }; - TimeUnit.SECONDS.sleep(5); + producingThread.start(); - final DestinationViewMBean view = createView(destination); - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - try { - LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() - + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() - + ", size= " + view.getQueueSize()); - return view.getDequeueCount() != 0 - && view.getDequeueCount() == view.getExpiredCount() - && view.getDequeueCount() == view.getEnqueueCount() - && view.getQueueSize() == 0; - } catch (Exception ignored) { - LOG.info(ignored.toString()); - } - return false; + assertTrue("producer failed to complete within allocated time", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + producingThread.join(TimeUnit.SECONDS.toMillis(3000)); + return !producingThread.isAlive(); + } + })); + + TimeUnit.SECONDS.sleep(5); + + final DestinationViewMBean view = createView(destination); + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + try { + LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() + ", size= " + view.getQueueSize()); + return view.getDequeueCount() != 0 && view.getDequeueCount() == view.getExpiredCount() && view.getDequeueCount() == view.getEnqueueCount() && view.getQueueSize() == 0; } - }, Wait.MAX_WAIT_MILLIS * 10); - LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() - + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() - + ", size= " + view.getQueueSize()); - - assertEquals("memory usage doesn't go to duck egg", 0, view.getMemoryPercentUsage()); - assertEquals("0 queue", 0, view.getQueueSize()); - } - - - public void initCombosForTestExpiredMessagesWithNoConsumer() { - addCombinationValues("optimizedDispatch", new Object[] {Boolean.TRUE, Boolean.FALSE}); - addCombinationValues("pendingQueuePolicy", new Object[] {null, new VMPendingQueueMessageStoragePolicy(), new FilePendingQueueMessageStoragePolicy()}); - } - - public void testExpiredMessagesWithNoConsumer() throws Exception { - - createBrokerWithMemoryLimit(); - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - connection = factory.createConnection(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(destination); - producer.setTimeToLive(1000); - connection.start(); - final long sendCount = 2000; - - final Thread producingThread = new Thread("Producing Thread") { - @Override - public void run() { - try { - int i = 0; - long tStamp = System.currentTimeMillis(); - while (i++ < sendCount) { - producer.send(session.createTextMessage("test")); - if (i%100 == 0) { - LOG.info("sent: " + i + " @ " + ((System.currentTimeMillis() - tStamp) / 100) + "m/ms"); - tStamp = System.currentTimeMillis() ; - } - } - } catch (Throwable ex) { - ex.printStackTrace(); - } + catch (Exception ignored) { + LOG.info(ignored.toString()); } - }; + return false; + } + }, Wait.MAX_WAIT_MILLIS * 10); + LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() + ", size= " + view.getQueueSize()); - producingThread.start(); + assertEquals("memory usage doesn't go to duck egg", 0, view.getMemoryPercentUsage()); + assertEquals("0 queue", 0, view.getQueueSize()); + } - assertTrue("producer failed to complete within allocated time", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - producingThread.join(TimeUnit.SECONDS.toMillis(3000)); - return !producingThread.isAlive(); + public void initCombosForTestExpiredMessagesWithNoConsumer() { + addCombinationValues("optimizedDispatch", new Object[]{Boolean.TRUE, Boolean.FALSE}); + addCombinationValues("pendingQueuePolicy", new Object[]{null, new VMPendingQueueMessageStoragePolicy(), new FilePendingQueueMessageStoragePolicy()}); + } + + public void testExpiredMessagesWithNoConsumer() throws Exception { + + createBrokerWithMemoryLimit(); + + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); + connection = factory.createConnection(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer = session.createProducer(destination); + producer.setTimeToLive(1000); + connection.start(); + final long sendCount = 2000; + + final Thread producingThread = new Thread("Producing Thread") { + @Override + public void run() { + try { + int i = 0; + long tStamp = System.currentTimeMillis(); + while (i++ < sendCount) { + producer.send(session.createTextMessage("test")); + if (i % 100 == 0) { + LOG.info("sent: " + i + " @ " + ((System.currentTimeMillis() - tStamp) / 100) + "m/ms"); + tStamp = System.currentTimeMillis(); + } + } } - })); - - final DestinationViewMBean view = createView(destination); - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() - + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() - + ", size= " + view.getQueueSize()); - return sendCount == view.getExpiredCount(); + catch (Throwable ex) { + ex.printStackTrace(); } - }, Wait.MAX_WAIT_MILLIS * 10); - LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() - + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() - + ", size= " + view.getQueueSize()); + } + }; - assertEquals("Not all sent messages have expired", sendCount, view.getExpiredCount()); - assertEquals("memory usage doesn't go to duck egg", 0, view.getMemoryPercentUsage()); - } + producingThread.start(); - // first ack delivered after expiry - public void testExpiredMessagesWithVerySlowConsumer() throws Exception { - createBroker(); - final long queuePrefetch = 5; - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory( - connectionUri + "?jms.prefetchPolicy.queuePrefetch=" + queuePrefetch); - connection = factory.createConnection(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - producer = session.createProducer(destination); - final int ttl = 4000; - producer.setTimeToLive(ttl); + assertTrue("producer failed to complete within allocated time", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + producingThread.join(TimeUnit.SECONDS.toMillis(3000)); + return !producingThread.isAlive(); + } + })); - final long sendCount = 10; - final CountDownLatch receivedOneCondition = new CountDownLatch(1); - final CountDownLatch waitCondition = new CountDownLatch(1); + final DestinationViewMBean view = createView(destination); + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() + ", size= " + view.getQueueSize()); + return sendCount == view.getExpiredCount(); + } + }, Wait.MAX_WAIT_MILLIS * 10); + LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() + ", size= " + view.getQueueSize()); - MessageConsumer consumer = session.createConsumer(destination); - consumer.setMessageListener(new MessageListener() { + assertEquals("Not all sent messages have expired", sendCount, view.getExpiredCount()); + assertEquals("memory usage doesn't go to duck egg", 0, view.getMemoryPercentUsage()); + } - @Override - public void onMessage(Message message) { - try { - LOG.info("Got my message: " + message); - receivedOneCondition.countDown(); - waitCondition.await(6, TimeUnit.MINUTES); - LOG.info("acking message: " + message); - message.acknowledge(); - } catch (Exception e) { - e.printStackTrace(); - fail(e.toString()); - } + // first ack delivered after expiry + public void testExpiredMessagesWithVerySlowConsumer() throws Exception { + createBroker(); + final long queuePrefetch = 5; + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri + "?jms.prefetchPolicy.queuePrefetch=" + queuePrefetch); + connection = factory.createConnection(); + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + producer = session.createProducer(destination); + final int ttl = 4000; + producer.setTimeToLive(ttl); + + final long sendCount = 10; + final CountDownLatch receivedOneCondition = new CountDownLatch(1); + final CountDownLatch waitCondition = new CountDownLatch(1); + + MessageConsumer consumer = session.createConsumer(destination); + consumer.setMessageListener(new MessageListener() { + + @Override + public void onMessage(Message message) { + try { + LOG.info("Got my message: " + message); + receivedOneCondition.countDown(); + waitCondition.await(6, TimeUnit.MINUTES); + LOG.info("acking message: " + message); + message.acknowledge(); } - }); - - connection.start(); - - final Thread producingThread = new Thread("Producing Thread") { - @Override - public void run() { - try { - int i = 0; - long tStamp = System.currentTimeMillis(); - while (i++ < sendCount) { - producer.send(session.createTextMessage("test")); - if (i%100 == 0) { - LOG.info("sent: " + i + " @ " + ((System.currentTimeMillis() - tStamp) / 100) + "m/ms"); - tStamp = System.currentTimeMillis() ; - } - } - } catch (Throwable ex) { - ex.printStackTrace(); - } + catch (Exception e) { + e.printStackTrace(); + fail(e.toString()); } - }; + } + }); - producingThread.start(); - assertTrue("got one message", receivedOneCondition.await(20, TimeUnit.SECONDS)); + connection.start(); - assertTrue("producer failed to complete within allocated time", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - producingThread.join(1000); - return !producingThread.isAlive(); + final Thread producingThread = new Thread("Producing Thread") { + @Override + public void run() { + try { + int i = 0; + long tStamp = System.currentTimeMillis(); + while (i++ < sendCount) { + producer.send(session.createTextMessage("test")); + if (i % 100 == 0) { + LOG.info("sent: " + i + " @ " + ((System.currentTimeMillis() - tStamp) / 100) + "m/ms"); + tStamp = System.currentTimeMillis(); + } + } } - }, Wait.MAX_WAIT_MILLIS * 10)); - - final DestinationViewMBean view = createView(destination); - - assertTrue("all dispatched up to default prefetch ", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return queuePrefetch == view.getDispatchCount(); + catch (Throwable ex) { + ex.printStackTrace(); } - })); - assertTrue("all non inflight have expired ", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() - + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() - + ", size= " + view.getQueueSize()); + } + }; - return view.getExpiredCount() > 0 && (view.getEnqueueCount() - view.getInFlightCount()) == view.getExpiredCount(); + producingThread.start(); + assertTrue("got one message", receivedOneCondition.await(20, TimeUnit.SECONDS)); + + assertTrue("producer failed to complete within allocated time", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + producingThread.join(1000); + return !producingThread.isAlive(); + } + }, Wait.MAX_WAIT_MILLIS * 10)); + + final DestinationViewMBean view = createView(destination); + + assertTrue("all dispatched up to default prefetch ", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return queuePrefetch == view.getDispatchCount(); + } + })); + assertTrue("all non inflight have expired ", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() + ", size= " + view.getQueueSize()); + + return view.getExpiredCount() > 0 && (view.getEnqueueCount() - view.getInFlightCount()) == view.getExpiredCount(); + } + })); + + LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() + ", size= " + view.getQueueSize()); + + // let the ack happen + waitCondition.countDown(); + + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return 0 == view.getInFlightCount(); + } + }); + LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() + ", size= " + view.getQueueSize()); + + assertEquals("inflight reduced to duck", 0, view.getInFlightCount()); + assertEquals("size didn't get back to 0 ", 0, view.getQueueSize()); + assertEquals("dequeues didn't match sent/expired ", sendCount, view.getDequeueCount()); + + consumer.close(); + + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return 0 == view.getInFlightCount(); + } + }); + assertEquals("inflight goes to zero on close", 0, view.getInFlightCount()); + + LOG.info("done: " + getName()); + } + + public void testExpiredMessagesWithVerySlowConsumerCanContinue() throws Exception { + createBroker(); + final long queuePrefetch = 600; + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri + "?jms.prefetchPolicy.queuePrefetch=" + queuePrefetch); + connection = factory.createConnection(); + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + producer = session.createProducer(destination); + final int ttl = 4000; + producer.setTimeToLive(ttl); + + final long sendCount = 1500; + final CountDownLatch receivedOneCondition = new CountDownLatch(1); + final CountDownLatch waitCondition = new CountDownLatch(1); + final AtomicLong received = new AtomicLong(); + MessageConsumer consumer = session.createConsumer(destination); + consumer.setMessageListener(new MessageListener() { + + @Override + public void onMessage(Message message) { + try { + if (LOG.isDebugEnabled()) { + LOG.debug("Got my message: " + message); + } + receivedOneCondition.countDown(); + received.incrementAndGet(); + waitCondition.await(5, TimeUnit.MINUTES); + if (LOG.isDebugEnabled()) { + LOG.debug("acking message: " + message); + } + message.acknowledge(); } - })); - - LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() - + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() - + ", size= " + view.getQueueSize()); - - // let the ack happen - waitCondition.countDown(); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return 0 == view.getInFlightCount(); + catch (Exception e) { + e.printStackTrace(); + fail(e.toString()); } - }); - LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() - + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() - + ", size= " + view.getQueueSize()); + } + }); - assertEquals("inflight reduced to duck", - 0, view.getInFlightCount()); - assertEquals("size didn't get back to 0 ", 0, view.getQueueSize()); - assertEquals("dequeues didn't match sent/expired ", sendCount, view.getDequeueCount()); + connection.start(); - consumer.close(); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return 0 == view.getInFlightCount(); + final Thread producingThread = new Thread("Producing Thread") { + @Override + public void run() { + try { + int i = 0; + long tStamp = System.currentTimeMillis(); + while (i++ < sendCount) { + producer.send(session.createTextMessage("test")); + if (i % 100 == 0) { + LOG.info("sent: " + i + " @ " + ((System.currentTimeMillis() - tStamp) / 100) + "m/ms"); + tStamp = System.currentTimeMillis(); + } + } } - }); - assertEquals("inflight goes to zero on close", 0, view.getInFlightCount()); - - LOG.info("done: " + getName()); - } - - public void testExpiredMessagesWithVerySlowConsumerCanContinue() throws Exception { - createBroker(); - final long queuePrefetch = 600; - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory( - connectionUri + "?jms.prefetchPolicy.queuePrefetch=" + queuePrefetch); - connection = factory.createConnection(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - producer = session.createProducer(destination); - final int ttl = 4000; - producer.setTimeToLive(ttl); - - final long sendCount = 1500; - final CountDownLatch receivedOneCondition = new CountDownLatch(1); - final CountDownLatch waitCondition = new CountDownLatch(1); - final AtomicLong received = new AtomicLong(); - MessageConsumer consumer = session.createConsumer(destination); - consumer.setMessageListener(new MessageListener() { - - @Override - public void onMessage(Message message) { - try { - if(LOG.isDebugEnabled()) { - LOG.debug("Got my message: " + message); - } - receivedOneCondition.countDown(); - received.incrementAndGet(); - waitCondition.await(5, TimeUnit.MINUTES); - if(LOG.isDebugEnabled()) { - LOG.debug("acking message: " + message); - } - message.acknowledge(); - } catch (Exception e) { - e.printStackTrace(); - fail(e.toString()); - } + catch (Throwable ex) { + ex.printStackTrace(); } - }); + } + }; - connection.start(); + producingThread.start(); + assertTrue("got one message", receivedOneCondition.await(20, TimeUnit.SECONDS)); - final Thread producingThread = new Thread("Producing Thread") { - @Override - public void run() { - try { - int i = 0; - long tStamp = System.currentTimeMillis(); - while (i++ < sendCount) { - producer.send(session.createTextMessage("test")); - if (i%100 == 0) { - LOG.info("sent: " + i + " @ " + ((System.currentTimeMillis() - tStamp) / 100) + "m/ms"); - tStamp = System.currentTimeMillis() ; - } - } - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - }; + assertTrue("producer failed to complete within allocated time", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + producingThread.join(1000); + return !producingThread.isAlive(); + } + }, Wait.MAX_WAIT_MILLIS * 10)); - producingThread.start(); - assertTrue("got one message", receivedOneCondition.await(20, TimeUnit.SECONDS)); + final DestinationViewMBean view = createView(destination); - assertTrue("producer failed to complete within allocated time", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - producingThread.join(1000); - return !producingThread.isAlive(); - } - }, Wait.MAX_WAIT_MILLIS * 10)); + assertTrue("Not all dispatched up to default prefetch ", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return queuePrefetch == view.getDispatchCount(); + } + })); - final DestinationViewMBean view = createView(destination); + assertTrue("all non inflight have expired ", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() + ", size= " + view.getQueueSize()); - assertTrue("Not all dispatched up to default prefetch ", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return queuePrefetch == view.getDispatchCount(); - } - })); + return view.getExpiredCount() > 0 && (view.getEnqueueCount() - view.getInFlightCount()) == view.getExpiredCount(); + } + })); - assertTrue("all non inflight have expired ", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() - + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() - + ", size= " + view.getQueueSize()); + LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() + ", size= " + view.getQueueSize()); - return view.getExpiredCount() > 0 && (view.getEnqueueCount() - view.getInFlightCount()) == view.getExpiredCount(); - } - })); + // let the ack happen + waitCondition.countDown(); - LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() - + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() - + ", size= " + view.getQueueSize()); + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return 0 == view.getInFlightCount(); + } + }); + LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() + ", size= " + view.getQueueSize()); - // let the ack happen - waitCondition.countDown(); + assertEquals("inflight didn't reduce to duck", 0, view.getInFlightCount()); + assertEquals("size doesn't get back to 0 ", 0, view.getQueueSize()); + assertEquals("dequeues don't match sent/expired ", sendCount, view.getDequeueCount()); - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return 0 == view.getInFlightCount(); - } - }); - LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() - + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() - + ", size= " + view.getQueueSize()); + // produce some more + producer.setTimeToLive(0); + long tStamp = System.currentTimeMillis(); + for (int i = 0; i < sendCount; i++) { + producer.send(session.createTextMessage("test-" + i)); + if (i % 100 == 0) { + LOG.info("sent: " + i + " @ " + ((System.currentTimeMillis() - tStamp) / 100) + "m/ms"); + tStamp = System.currentTimeMillis(); + } + } - assertEquals("inflight didn't reduce to duck", - 0, view.getInFlightCount()); - assertEquals("size doesn't get back to 0 ", 0, view.getQueueSize()); - assertEquals("dequeues don't match sent/expired ", sendCount, view.getDequeueCount()); + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return received.get() >= sendCount; + } + }); - // produce some more - producer.setTimeToLive(0); - long tStamp = System.currentTimeMillis(); - for (int i=0; i= sendCount; - } - }); + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return 0 == view.getInFlightCount(); + } + }); + assertEquals("inflight did not go to zero on close", 0, view.getInFlightCount()); - consumer.close(); + LOG.info("done: " + getName()); + } - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return 0 == view.getInFlightCount(); - } - }); - assertEquals("inflight did not go to zero on close", 0, view.getInFlightCount()); + public void testExpireMessagesForDurableSubscriber() throws Exception { + createBroker(); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); + connection = factory.createConnection(); + connection.setClientID("myConnection"); + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + connection.start(); + Topic destination = session.createTopic("test"); + producer = session.createProducer(destination); + final int ttl = 1000; + producer.setTimeToLive(ttl); - LOG.info("done: " + getName()); - } + final long sendCount = 10; - public void testExpireMessagesForDurableSubscriber() throws Exception { - createBroker(); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - connection = factory.createConnection(); - connection.setClientID("myConnection"); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - connection.start(); - Topic destination = session.createTopic("test"); - producer = session.createProducer(destination); - final int ttl = 1000; - producer.setTimeToLive(ttl); + TopicSubscriber sub = session.createDurableSubscriber(destination, "mySub"); + sub.close(); - final long sendCount = 10; + for (int i = 0; i < sendCount; i++) { + producer.send(session.createTextMessage("test")); + } - TopicSubscriber sub = session.createDurableSubscriber(destination, "mySub"); - sub.close(); + DestinationViewMBean view = createView((ActiveMQTopic) destination); - for (int i=0; i < sendCount; i++) { - producer.send(session.createTextMessage("test")); - } + LOG.info("messages sent"); + LOG.info("expired=" + view.getExpiredCount() + " " + view.getEnqueueCount()); + assertEquals(0, view.getExpiredCount()); + assertEquals(10, view.getEnqueueCount()); - DestinationViewMBean view = createView((ActiveMQTopic)destination); + Thread.sleep(5000); - LOG.info("messages sent"); - LOG.info("expired=" + view.getExpiredCount() + " " + view.getEnqueueCount()); - assertEquals(0, view.getExpiredCount()); - assertEquals(10, view.getEnqueueCount()); + LOG.info("expired=" + view.getExpiredCount() + " " + view.getEnqueueCount()); + assertEquals(10, view.getExpiredCount()); + assertEquals(10, view.getEnqueueCount()); - Thread.sleep(5000); + final AtomicLong received = new AtomicLong(); + sub = session.createDurableSubscriber(destination, "mySub"); + sub.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + received.incrementAndGet(); + } + }); - LOG.info("expired=" + view.getExpiredCount() + " " + view.getEnqueueCount()); - assertEquals(10, view.getExpiredCount()); - assertEquals(10, view.getEnqueueCount()); + LOG.info("Waiting for messages to arrive"); - final AtomicLong received = new AtomicLong(); - sub = session.createDurableSubscriber(destination, "mySub"); - sub.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - received.incrementAndGet(); - } - }); + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return received.get() >= sendCount; + } + }, 1000); - LOG.info("Waiting for messages to arrive"); + LOG.info("received=" + received.get()); + LOG.info("expired=" + view.getExpiredCount() + " " + view.getEnqueueCount()); - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return received.get() >= sendCount; - } - }, 1000); + assertEquals(0, received.get()); + assertEquals(10, view.getExpiredCount()); + assertEquals(10, view.getEnqueueCount()); + } - LOG.info("received=" + received.get()); - LOG.info("expired=" + view.getExpiredCount() + " " + view.getEnqueueCount()); + protected DestinationViewMBean createView(ActiveMQDestination destination) throws Exception { + String domain = "org.apache.activemq"; + ObjectName name; + if (destination.isQueue()) { + name = new ObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=test"); + } + else { + name = new ObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Topic,destinationName=test"); + } - assertEquals(0, received.get()); - assertEquals(10, view.getExpiredCount()); - assertEquals(10, view.getEnqueueCount()); - } + return (DestinationViewMBean) broker.getManagementContext().newProxyInstance(name, DestinationViewMBean.class, true); + } - protected DestinationViewMBean createView(ActiveMQDestination destination) throws Exception { - String domain = "org.apache.activemq"; - ObjectName name; - if (destination.isQueue()) { - name = new ObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=test"); - } else { - name = new ObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Topic,destinationName=test"); - } + @Override + protected void tearDown() throws Exception { + connection.stop(); + broker.stop(); + broker.waitUntilStopped(); + } - return (DestinationViewMBean) broker.getManagementContext().newProxyInstance(name, DestinationViewMBean.class, true); - } + public boolean getOptimizedDispatch() { + return this.optimizedDispatch; + } - @Override - protected void tearDown() throws Exception { - connection.stop(); - broker.stop(); - broker.waitUntilStopped(); - } + public void setOptimizedDispatch(boolean option) { + this.optimizedDispatch = option; + } - public boolean getOptimizedDispatch() { - return this.optimizedDispatch; - } + public PendingQueueMessageStoragePolicy getPendingQueuePolicy() { + return this.pendingQueuePolicy; + } - public void setOptimizedDispatch(boolean option) { - this.optimizedDispatch = option; - } - - public PendingQueueMessageStoragePolicy getPendingQueuePolicy() { - return this.pendingQueuePolicy; - } - - public void setPendingQueuePolicy(PendingQueueMessageStoragePolicy policy) { - this.pendingQueuePolicy = policy; - } + public void setPendingQueuePolicy(PendingQueueMessageStoragePolicy policy) { + this.pendingQueuePolicy = policy; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JDBCDurableSubscriptionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JDBCDurableSubscriptionTest.java index 33afc85a9e..5a5e4bf258 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JDBCDurableSubscriptionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JDBCDurableSubscriptionTest.java @@ -23,18 +23,18 @@ import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter; import org.apache.derby.jdbc.EmbeddedDataSource; /** - * + * */ public class JDBCDurableSubscriptionTest extends DurableSubscriptionTestSupport { - protected PersistenceAdapter createPersistenceAdapter() throws IOException { - JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); - EmbeddedDataSource dataSource = new EmbeddedDataSource(); - dataSource.setDatabaseName("derbyDb"); - dataSource.setCreateDatabase("create"); - jdbc.setDataSource(dataSource); - jdbc.setCleanupPeriod(1000); // set up small cleanup period - return jdbc; - } + protected PersistenceAdapter createPersistenceAdapter() throws IOException { + JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); + EmbeddedDataSource dataSource = new EmbeddedDataSource(); + dataSource.setDatabaseName("derbyDb"); + dataSource.setCreateDatabase("create"); + jdbc.setDataSource(dataSource); + jdbc.setCleanupPeriod(1000); // set up small cleanup period + return jdbc; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JMXRemoveQueueThenSendIgnoredTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JMXRemoveQueueThenSendIgnoredTest.java index 7c301f535b..52431a1631 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JMXRemoveQueueThenSendIgnoredTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JMXRemoveQueueThenSendIgnoredTest.java @@ -41,115 +41,113 @@ import org.slf4j.LoggerFactory; public class JMXRemoveQueueThenSendIgnoredTest { - private static final Logger LOG = LoggerFactory.getLogger(JMXRemoveQueueThenSendIgnoredTest.class); - private static final String domain = "org.apache.activemq"; + private static final Logger LOG = LoggerFactory.getLogger(JMXRemoveQueueThenSendIgnoredTest.class); + private static final String domain = "org.apache.activemq"; - private BrokerService brokerService; - private MessageProducer producer; - private QueueSession session; - private QueueConnection connection; - private Queue queue; - private int count = 1; + private BrokerService brokerService; + private MessageProducer producer; + private QueueSession session; + private QueueConnection connection; + private Queue queue; + private int count = 1; - @Before - public void setUp() throws Exception { - brokerService = new BrokerService(); - brokerService.setBrokerName("dev"); - brokerService.setPersistent(false); - brokerService.setUseJmx(true); - brokerService.addConnector("tcp://localhost:0"); - brokerService.start(); + @Before + public void setUp() throws Exception { + brokerService = new BrokerService(); + brokerService.setBrokerName("dev"); + brokerService.setPersistent(false); + brokerService.setUseJmx(true); + brokerService.addConnector("tcp://localhost:0"); + brokerService.start(); - final String brokerUri = brokerService.getTransportConnectors().get(0).getPublishableConnectString(); + final String brokerUri = brokerService.getTransportConnectors().get(0).getPublishableConnectString(); - ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(brokerUri); - connection = activeMQConnectionFactory.createQueueConnection(); - session = connection.createQueueSession(true, Session.AUTO_ACKNOWLEDGE/*SESSION_TRANSACTED*/); - queue = session.createQueue("myqueue"); - producer = session.createProducer(queue); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); + ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(brokerUri); + connection = activeMQConnectionFactory.createQueueConnection(); + session = connection.createQueueSession(true, Session.AUTO_ACKNOWLEDGE/*SESSION_TRANSACTED*/); + queue = session.createQueue("myqueue"); + producer = session.createProducer(queue); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); - connection.start(); - } + connection.start(); + } - @Test - public void testRemoveQueueAndProduceAfterNewConsumerAdded() throws Exception { - MessageConsumer firstConsumer = registerConsumer(); - produceMessage(); - Message message = firstConsumer.receive(5000); - LOG.info("Received message " + message); + @Test + public void testRemoveQueueAndProduceAfterNewConsumerAdded() throws Exception { + MessageConsumer firstConsumer = registerConsumer(); + produceMessage(); + Message message = firstConsumer.receive(5000); + LOG.info("Received message " + message); - assertEquals(1, numberOfMessages()); - firstConsumer.close(); - session.commit(); - Thread.sleep(1000); + assertEquals(1, numberOfMessages()); + firstConsumer.close(); + session.commit(); + Thread.sleep(1000); - removeQueue(); - Thread.sleep(1000); + removeQueue(); + Thread.sleep(1000); - MessageConsumer secondConsumer = registerConsumer(); - produceMessage(); - message = secondConsumer.receive(5000); - LOG.debug("Received message " + message); + MessageConsumer secondConsumer = registerConsumer(); + produceMessage(); + message = secondConsumer.receive(5000); + LOG.debug("Received message " + message); - assertEquals(1, numberOfMessages()); - secondConsumer.close(); - } + assertEquals(1, numberOfMessages()); + secondConsumer.close(); + } - @Test - public void testRemoveQueueAndProduceBeforeNewConsumerAdded() throws Exception { - MessageConsumer firstConsumer = registerConsumer(); - produceMessage(); - Message message = firstConsumer.receive(5000); - LOG.info("Received message " + message); + @Test + public void testRemoveQueueAndProduceBeforeNewConsumerAdded() throws Exception { + MessageConsumer firstConsumer = registerConsumer(); + produceMessage(); + Message message = firstConsumer.receive(5000); + LOG.info("Received message " + message); - assertEquals(1, numberOfMessages()); - firstConsumer.close(); - session.commit(); - Thread.sleep(1000); + assertEquals(1, numberOfMessages()); + firstConsumer.close(); + session.commit(); + Thread.sleep(1000); - removeQueue(); - Thread.sleep(1000); + removeQueue(); + Thread.sleep(1000); - produceMessage(); - MessageConsumer secondConsumer = registerConsumer(); - message = secondConsumer.receive(5000); - LOG.debug("Received message " + message); + produceMessage(); + MessageConsumer secondConsumer = registerConsumer(); + message = secondConsumer.receive(5000); + LOG.debug("Received message " + message); - assertEquals(1, numberOfMessages()); - secondConsumer.close(); - } + assertEquals(1, numberOfMessages()); + secondConsumer.close(); + } - private MessageConsumer registerConsumer() throws JMSException { - MessageConsumer consumer = session.createConsumer(queue); - return consumer; - } + private MessageConsumer registerConsumer() throws JMSException { + MessageConsumer consumer = session.createConsumer(queue); + return consumer; + } - private int numberOfMessages() throws Exception { - ObjectName queueViewMBeanName = new ObjectName( - domain + ":destinationType=Queue,destinationName=myqueue,type=Broker,brokerName=dev"); - QueueViewMBean queue = (QueueViewMBean) - brokerService.getManagementContext().newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); - long size = queue.getQueueSize(); - return (int)size; - } + private int numberOfMessages() throws Exception { + ObjectName queueViewMBeanName = new ObjectName(domain + ":destinationType=Queue,destinationName=myqueue,type=Broker,brokerName=dev"); + QueueViewMBean queue = (QueueViewMBean) brokerService.getManagementContext().newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); + long size = queue.getQueueSize(); + return (int) size; + } - private void removeQueue() throws Exception { - LOG.debug("Removing Destination: myqueue"); - brokerService.getAdminView().removeQueue("myqueue"); - } + private void removeQueue() throws Exception { + LOG.debug("Removing Destination: myqueue"); + brokerService.getAdminView().removeQueue("myqueue"); + } - private void produceMessage() throws JMSException { - TextMessage textMessage = session.createTextMessage(); - textMessage.setText("Sending message: " + count++); - LOG.debug("Sending message: " + textMessage); - producer.send(textMessage); - session.commit(); - } + private void produceMessage() throws JMSException { + TextMessage textMessage = session.createTextMessage(); + textMessage.setText("Sending message: " + count++); + LOG.debug("Sending message: " + textMessage); + producer.send(textMessage); + session.commit(); + } - @After - public void tearDown() throws Exception { - connection.close(); - brokerService.stop(); - } + @After + public void tearDown() throws Exception { + connection.close(); + brokerService.stop(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JdbcDurableSubDupTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JdbcDurableSubDupTest.java index 1b3be069c2..de7ee38ee2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JdbcDurableSubDupTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JdbcDurableSubDupTest.java @@ -48,250 +48,254 @@ import org.slf4j.LoggerFactory; public class JdbcDurableSubDupTest { - private static final Logger LOG = LoggerFactory.getLogger(JdbcDurableSubDupTest.class); - final int prefetchVal = 150; - String urlOptions = "jms.watchTopicAdvisories=false"; - String url = null; - String queueName = "topicTest?consumer.prefetchSize=" + prefetchVal; - String xmlMessage = ""; + private static final Logger LOG = LoggerFactory.getLogger(JdbcDurableSubDupTest.class); + final int prefetchVal = 150; + String urlOptions = "jms.watchTopicAdvisories=false"; + String url = null; + String queueName = "topicTest?consumer.prefetchSize=" + prefetchVal; + String xmlMessage = ""; - String selector = ""; - String clntVersion = "87"; - String clntId = "timsClntId345" + clntVersion; - String subscriptionName = "subscriptionName-y" + clntVersion; - SimpleDateFormat dtf = new SimpleDateFormat("HH:mm:ss"); + String selector = ""; + String clntVersion = "87"; + String clntId = "timsClntId345" + clntVersion; + String subscriptionName = "subscriptionName-y" + clntVersion; + SimpleDateFormat dtf = new SimpleDateFormat("HH:mm:ss"); - final int TO_RECEIVE = 5000; - BrokerService broker = null; - Vector exceptions = new Vector(); - final int MAX_MESSAGES = 100000; - int[] dupChecker = new int[MAX_MESSAGES]; + final int TO_RECEIVE = 5000; + BrokerService broker = null; + Vector exceptions = new Vector(); + final int MAX_MESSAGES = 100000; + int[] dupChecker = new int[MAX_MESSAGES]; - @Before - public void startBroker() throws Exception { - exceptions.clear(); - for (int i = 0; i < MAX_MESSAGES; i++) { - dupChecker[i] = 0; - } - broker = new BrokerService(); - broker.setAdvisorySupport(false); - broker.setPersistenceAdapter(new JDBCPersistenceAdapter()); - PolicyEntry policyEntry = new PolicyEntry(); - policyEntry.setMaxAuditDepth(3000); - policyEntry.setMaxPageSize(150); - policyEntry.setPrioritizedMessages(true); - PolicyMap policyMap = new PolicyMap(); - policyMap.setDefaultEntry(policyEntry); - broker.setDestinationPolicy(policyMap); + @Before + public void startBroker() throws Exception { + exceptions.clear(); + for (int i = 0; i < MAX_MESSAGES; i++) { + dupChecker[i] = 0; + } + broker = new BrokerService(); + broker.setAdvisorySupport(false); + broker.setPersistenceAdapter(new JDBCPersistenceAdapter()); + PolicyEntry policyEntry = new PolicyEntry(); + policyEntry.setMaxAuditDepth(3000); + policyEntry.setMaxPageSize(150); + policyEntry.setPrioritizedMessages(true); + PolicyMap policyMap = new PolicyMap(); + policyMap.setDefaultEntry(policyEntry); + broker.setDestinationPolicy(policyMap); - broker.addConnector("tcp://localhost:0"); - broker.setDeleteAllMessagesOnStartup(true); - broker.start(); - broker.waitUntilStarted(); - url = broker.getTransportConnectors().get(0).getConnectUri().toString() + "?" + urlOptions; - } + broker.addConnector("tcp://localhost:0"); + broker.setDeleteAllMessagesOnStartup(true); + broker.start(); + broker.waitUntilStarted(); + url = broker.getTransportConnectors().get(0).getConnectUri().toString() + "?" + urlOptions; + } - @After - public void stopBroker() throws Exception { - if (broker != null) { - broker.stop(); - } - } + @After + public void stopBroker() throws Exception { + if (broker != null) { + broker.stop(); + } + } - @Test - public void testNoDupsOnSlowConsumerReconnect() throws Exception { - JmsConsumerDup consumer = new JmsConsumerDup(); - consumer.done.set(true); - consumer.run(); + @Test + public void testNoDupsOnSlowConsumerReconnect() throws Exception { + JmsConsumerDup consumer = new JmsConsumerDup(); + consumer.done.set(true); + consumer.run(); - consumer.done.set(false); + consumer.done.set(false); - LOG.info("serial production then consumption"); - JmsProvider provider = new JmsProvider(); - provider.run(); + LOG.info("serial production then consumption"); + JmsProvider provider = new JmsProvider(); + provider.run(); - consumer.run(); + consumer.run(); - assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); + assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); - for (int i = 0; i < TO_RECEIVE; i++) { - assertTrue("got message " + i, dupChecker[i] == 1); - } - } + for (int i = 0; i < TO_RECEIVE; i++) { + assertTrue("got message " + i, dupChecker[i] == 1); + } + } - @Test - public void testNoDupsOnSlowConsumerLargePriorityGapReconnect() throws Exception { - JmsConsumerDup consumer = new JmsConsumerDup(); - consumer.done.set(true); - consumer.run(); + @Test + public void testNoDupsOnSlowConsumerLargePriorityGapReconnect() throws Exception { + JmsConsumerDup consumer = new JmsConsumerDup(); + consumer.done.set(true); + consumer.run(); - consumer.done.set(false); - JmsProvider provider = new JmsProvider(); - provider.priorityModulator = 2500; - provider.run(); + consumer.done.set(false); + JmsProvider provider = new JmsProvider(); + provider.priorityModulator = 2500; + provider.run(); - consumer.run(); + consumer.run(); - assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); - for (int i = 0; i < TO_RECEIVE; i++) { - assertTrue("got message " + i, dupChecker[i] == 1); - } + assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); + for (int i = 0; i < TO_RECEIVE; i++) { + assertTrue("got message " + i, dupChecker[i] == 1); + } - } + } - class JmsConsumerDup implements MessageListener { - long count = 0; + class JmsConsumerDup implements MessageListener { - AtomicBoolean done = new AtomicBoolean(false); + long count = 0; - public void run() { - Connection connection = null; - Session session; - Topic topic; - ActiveMQConnectionFactory factory; - MessageConsumer consumer; + AtomicBoolean done = new AtomicBoolean(false); - factory = new ActiveMQConnectionFactory(url); + public void run() { + Connection connection = null; + Session session; + Topic topic; + ActiveMQConnectionFactory factory; + MessageConsumer consumer; - try { - connection = factory.createConnection("MyUsername", "MyPassword"); - connection.setClientID(clntId); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - topic = session.createTopic(queueName); - consumer = session.createDurableSubscriber(topic, subscriptionName, selector, false); - consumer.setMessageListener(this); - LOG.info("Waiting for messages..."); + factory = new ActiveMQConnectionFactory(url); - while (!done.get()) { - TimeUnit.SECONDS.sleep(5); - if (count == TO_RECEIVE || !exceptions.isEmpty()) { - done.set(true); - } - } - } catch (Exception e) { - LOG.error("caught", e); - exceptions.add(e); - throw new RuntimeException(e); - } finally { - if (connection != null) { - try { - LOG.info("consumer done (" + exceptions.isEmpty() + "), closing connection"); - connection.close(); - } catch (JMSException e) { - e.printStackTrace(); - } - } + try { + connection = factory.createConnection("MyUsername", "MyPassword"); + connection.setClientID(clntId); + connection.start(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + topic = session.createTopic(queueName); + consumer = session.createDurableSubscriber(topic, subscriptionName, selector, false); + consumer.setMessageListener(this); + LOG.info("Waiting for messages..."); + + while (!done.get()) { + TimeUnit.SECONDS.sleep(5); + if (count == TO_RECEIVE || !exceptions.isEmpty()) { + done.set(true); + } } - } - - @Override - public void onMessage(Message message) { - ++count; - - try { - Thread.sleep(0L); - } catch (InterruptedException e) { + } + catch (Exception e) { + LOG.error("caught", e); + exceptions.add(e); + throw new RuntimeException(e); + } + finally { + if (connection != null) { + try { + LOG.info("consumer done (" + exceptions.isEmpty() + "), closing connection"); + connection.close(); + } + catch (JMSException e) { + e.printStackTrace(); + } } - ; + } + } - try { - TextMessage m = (TextMessage) message; + @Override + public void onMessage(Message message) { + ++count; - if (count%100 == 0) { - LOG.info("Rcvd Msg #-" + count + " " + m.getText() - + " Sent->" + dtf.format(new Date(m.getJMSTimestamp())) - + " Recv->" + dtf.format(new Date()) - + " Expr->" + dtf.format(new Date(m.getJMSExpiration())) - + ", mid: " + m.getJMSMessageID() - ); - } - int i = m.getIntProperty("SeqNo"); + try { + Thread.sleep(0L); + } + catch (InterruptedException e) { + } + ; - //check for duplicate messages - if (i < MAX_MESSAGES) { - if (dupChecker[i] == 1) { - LOG.error("Duplicate message received at count: " + count + ", id: " + m.getJMSMessageID()); - exceptions.add(new RuntimeException("Got Duplicate at: " + m.getJMSMessageID())); + try { + TextMessage m = (TextMessage) message; - } else { - dupChecker[i] = 1; - } - } - } catch (JMSException e) { - LOG.error("caught ", e); - exceptions.add(e); + if (count % 100 == 0) { + LOG.info("Rcvd Msg #-" + count + " " + m.getText() + " Sent->" + dtf.format(new Date(m.getJMSTimestamp())) + " Recv->" + dtf.format(new Date()) + " Expr->" + dtf.format(new Date(m.getJMSExpiration())) + ", mid: " + m.getJMSMessageID()); } - } - } + int i = m.getIntProperty("SeqNo"); + //check for duplicate messages + if (i < MAX_MESSAGES) { + if (dupChecker[i] == 1) { + LOG.error("Duplicate message received at count: " + count + ", id: " + m.getJMSMessageID()); + exceptions.add(new RuntimeException("Got Duplicate at: " + m.getJMSMessageID())); - class JmsProvider implements Runnable { - - int priorityModulator = 10; - - @Override - public void run() { - - Connection connection; - Session session; - Topic topic; - - ActiveMQConnectionFactory factory; - MessageProducer messageProducer; - long timeToLive = 0L; - - TextMessage message = null; - - factory = new ActiveMQConnectionFactory(url); - - try { - connection = factory.createConnection("MyUserName", "MyPassword"); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - topic = session.createTopic(queueName); - messageProducer = session.createProducer(topic); - messageProducer.setPriority(3); - messageProducer.setTimeToLive(timeToLive); - messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT); - - int msgSeqNo = 0; - int NUM_MSGS = 1000; - int NUM_GROUPS = TO_RECEIVE/NUM_MSGS; - for (int n = 0; n < NUM_GROUPS; n++) { - - message = session.createTextMessage(); - - for (int i = 0; i < NUM_MSGS; i++) { - int priority = 0; - if (priorityModulator <= 10) { - priority = msgSeqNo % priorityModulator; - } else { - priority = (msgSeqNo >= priorityModulator) ? 9 : 0; - } - message.setText(xmlMessage + msgSeqNo + "-" + priority); - message.setJMSPriority(priority); - message.setIntProperty("SeqNo", msgSeqNo); - if (i > 0 && i%100 == 0) { - LOG.info("Sending message: " + message.getText()); - } - messageProducer.send(message, DeliveryMode.PERSISTENT, message.getJMSPriority(), timeToLive); - msgSeqNo++; - } - try { - Thread.sleep(1000L); - } catch (InterruptedException e) { - e.printStackTrace(); - exceptions.add(e); - } - } - - } catch (JMSException e) { - LOG.error("caught ", e); - e.printStackTrace(); - exceptions.add(e); - + } + else { + dupChecker[i] = 1; + } } - } + } + catch (JMSException e) { + LOG.error("caught ", e); + exceptions.add(e); + } + } + } - } + class JmsProvider implements Runnable { + + int priorityModulator = 10; + + @Override + public void run() { + + Connection connection; + Session session; + Topic topic; + + ActiveMQConnectionFactory factory; + MessageProducer messageProducer; + long timeToLive = 0L; + + TextMessage message = null; + + factory = new ActiveMQConnectionFactory(url); + + try { + connection = factory.createConnection("MyUserName", "MyPassword"); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + topic = session.createTopic(queueName); + messageProducer = session.createProducer(topic); + messageProducer.setPriority(3); + messageProducer.setTimeToLive(timeToLive); + messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT); + + int msgSeqNo = 0; + int NUM_MSGS = 1000; + int NUM_GROUPS = TO_RECEIVE / NUM_MSGS; + for (int n = 0; n < NUM_GROUPS; n++) { + + message = session.createTextMessage(); + + for (int i = 0; i < NUM_MSGS; i++) { + int priority = 0; + if (priorityModulator <= 10) { + priority = msgSeqNo % priorityModulator; + } + else { + priority = (msgSeqNo >= priorityModulator) ? 9 : 0; + } + message.setText(xmlMessage + msgSeqNo + "-" + priority); + message.setJMSPriority(priority); + message.setIntProperty("SeqNo", msgSeqNo); + if (i > 0 && i % 100 == 0) { + LOG.info("Sending message: " + message.getText()); + } + messageProducer.send(message, DeliveryMode.PERSISTENT, message.getJMSPriority(), timeToLive); + msgSeqNo++; + } + try { + Thread.sleep(1000L); + } + catch (InterruptedException e) { + e.printStackTrace(); + exceptions.add(e); + } + } + + } + catch (JMSException e) { + LOG.error("caught ", e); + e.printStackTrace(); + exceptions.add(e); + + } + } + + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JournalDurableSubscriptionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JournalDurableSubscriptionTest.java index 8634be320e..b8358eda22 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JournalDurableSubscriptionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JournalDurableSubscriptionTest.java @@ -23,16 +23,16 @@ import org.apache.activemq.store.PersistenceAdapter; import org.apache.activemq.store.journal.JournalPersistenceAdapterFactory; /** - * + * */ public class JournalDurableSubscriptionTest extends DurableSubscriptionTestSupport { - protected PersistenceAdapter createPersistenceAdapter() throws IOException { - File dataDir = new File("target/test-data/durableJournal"); - JournalPersistenceAdapterFactory factory = new JournalPersistenceAdapterFactory(); - factory.setDataDirectoryFile(dataDir); - factory.setUseJournal(true); - factory.setJournalLogFileSize(1024 * 64); - return factory.createPersistenceAdapter(); - } + protected PersistenceAdapter createPersistenceAdapter() throws IOException { + File dataDir = new File("target/test-data/durableJournal"); + JournalPersistenceAdapterFactory factory = new JournalPersistenceAdapterFactory(); + factory.setDataDirectoryFile(dataDir); + factory.setUseJournal(true); + factory.setJournalLogFileSize(1024 * 64); + return factory.createPersistenceAdapter(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/KahaDBDurableSubscriptionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/KahaDBDurableSubscriptionTest.java index 26faccc8fb..cb22e712d8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/KahaDBDurableSubscriptionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/KahaDBDurableSubscriptionTest.java @@ -17,11 +17,12 @@ package org.apache.activemq.usecases; import java.io.IOException; + import org.apache.activemq.store.PersistenceAdapter; public class KahaDBDurableSubscriptionTest extends DurableSubscriptionTestSupport { - protected PersistenceAdapter createPersistenceAdapter() throws IOException { - return null; // use default - } + protected PersistenceAdapter createPersistenceAdapter() throws IOException { + return null; // use default + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/LargeQueueSparseDeleteTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/LargeQueueSparseDeleteTest.java index f69f1b7c69..8c8f5171c6 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/LargeQueueSparseDeleteTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/LargeQueueSparseDeleteTest.java @@ -36,165 +36,145 @@ import org.slf4j.LoggerFactory; * {@link org.apache.activemq.broker.region.Queue#moveMatchingMessagesTo(org.apache.activemq.broker.ConnectionContext, String, org.apache.activemq.command.ActiveMQDestination)}. */ public class LargeQueueSparseDeleteTest extends EmbeddedBrokerTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(LargeQueueSparseDeleteTest.class); - /** - * {@inheritDoc} - */ - @Override - protected void setUp() throws Exception { - super.useTopic = false; - super.setUp(); - } + private static final Logger LOG = LoggerFactory.getLogger(LargeQueueSparseDeleteTest.class); - /** - * The test queue is filled with QUEUE_SIZE test messages, each with a - * numeric id property beginning at 0. Once the queue is filled, the last - * message (id = QUEUE_SIZE-1) is moved to another queue. The test succeeds - * if the move completes within TEST_TIMEOUT milliseconds. - * - * @throws Exception - */ - public void testMoveMessages() throws Exception { - final int QUEUE_SIZE = 30000; - final String MOVE_TO_DESTINATION_NAME = getDestinationString() - + ".dest"; - final long TEST_TIMEOUT = 20000; + /** + * {@inheritDoc} + */ + @Override + protected void setUp() throws Exception { + super.useTopic = false; + super.setUp(); + } - // Populate a test queue with uniquely-identifiable messages. - Connection conn = createConnection(); - try { - conn.start(); - Session session = conn.createSession(true, - Session.SESSION_TRANSACTED); - MessageProducer producer = session.createProducer(destination); - for (int i = 0; i < QUEUE_SIZE; i++) { - Message message = session.createMessage(); - message.setIntProperty("id", i); - producer.send(message); - } - session.commit(); - } finally { - conn.close(); - } + /** + * The test queue is filled with QUEUE_SIZE test messages, each with a + * numeric id property beginning at 0. Once the queue is filled, the last + * message (id = QUEUE_SIZE-1) is moved to another queue. The test succeeds + * if the move completes within TEST_TIMEOUT milliseconds. + * + * @throws Exception + */ + public void testMoveMessages() throws Exception { + final int QUEUE_SIZE = 30000; + final String MOVE_TO_DESTINATION_NAME = getDestinationString() + ".dest"; + final long TEST_TIMEOUT = 20000; - // Access the implementation of the test queue and move the last message - // to another queue. Verify that the move occurred within the limits of - // the test. - Queue queue = (Queue) broker.getRegionBroker().getDestinationMap().get( - destination); + // Populate a test queue with uniquely-identifiable messages. + Connection conn = createConnection(); + try { + conn.start(); + Session session = conn.createSession(true, Session.SESSION_TRANSACTED); + MessageProducer producer = session.createProducer(destination); + for (int i = 0; i < QUEUE_SIZE; i++) { + Message message = session.createMessage(); + message.setIntProperty("id", i); + producer.send(message); + } + session.commit(); + } + finally { + conn.close(); + } - ConnectionContext context = new ConnectionContext( - new NonCachedMessageEvaluationContext()); - context.setBroker(broker.getBroker()); - context.getMessageEvaluationContext().setDestination(destination); + // Access the implementation of the test queue and move the last message + // to another queue. Verify that the move occurred within the limits of + // the test. + Queue queue = (Queue) broker.getRegionBroker().getDestinationMap().get(destination); - long startTimeMillis = System.currentTimeMillis(); - Assert.assertEquals(1, queue - .moveMatchingMessagesTo(context, "id=" + (QUEUE_SIZE - 1), - createDestination(MOVE_TO_DESTINATION_NAME))); + ConnectionContext context = new ConnectionContext(new NonCachedMessageEvaluationContext()); + context.setBroker(broker.getBroker()); + context.getMessageEvaluationContext().setDestination(destination); - long durationMillis = System.currentTimeMillis() - startTimeMillis; + long startTimeMillis = System.currentTimeMillis(); + Assert.assertEquals(1, queue.moveMatchingMessagesTo(context, "id=" + (QUEUE_SIZE - 1), createDestination(MOVE_TO_DESTINATION_NAME))); - LOG.info("It took " + durationMillis - + "ms to move the last message from a queue a " + QUEUE_SIZE - + " messages."); + long durationMillis = System.currentTimeMillis() - startTimeMillis; - Assert.assertTrue("Moving the message took too long: " + durationMillis - + "ms", durationMillis < TEST_TIMEOUT); - } + LOG.info("It took " + durationMillis + "ms to move the last message from a queue a " + QUEUE_SIZE + " messages."); - public void testCopyMessages() throws Exception { - final int QUEUE_SIZE = 30000; - final String MOVE_TO_DESTINATION_NAME = getDestinationString() - + ".dest"; - final long TEST_TIMEOUT = 10000; + Assert.assertTrue("Moving the message took too long: " + durationMillis + "ms", durationMillis < TEST_TIMEOUT); + } - // Populate a test queue with uniquely-identifiable messages. - Connection conn = createConnection(); - try { - conn.start(); - Session session = conn.createSession(true, - Session.SESSION_TRANSACTED); - MessageProducer producer = session.createProducer(destination); - for (int i = 0; i < QUEUE_SIZE; i++) { - Message message = session.createMessage(); - message.setIntProperty("id", i); - producer.send(message); - } - session.commit(); - } finally { - conn.close(); - } + public void testCopyMessages() throws Exception { + final int QUEUE_SIZE = 30000; + final String MOVE_TO_DESTINATION_NAME = getDestinationString() + ".dest"; + final long TEST_TIMEOUT = 10000; - // Access the implementation of the test queue and move the last message - // to another queue. Verify that the move occurred within the limits of - // the test. - Queue queue = (Queue) broker.getRegionBroker().getDestinationMap().get( - destination); + // Populate a test queue with uniquely-identifiable messages. + Connection conn = createConnection(); + try { + conn.start(); + Session session = conn.createSession(true, Session.SESSION_TRANSACTED); + MessageProducer producer = session.createProducer(destination); + for (int i = 0; i < QUEUE_SIZE; i++) { + Message message = session.createMessage(); + message.setIntProperty("id", i); + producer.send(message); + } + session.commit(); + } + finally { + conn.close(); + } - ConnectionContext context = new ConnectionContext( - new NonCachedMessageEvaluationContext()); - context.setBroker(broker.getBroker()); - context.getMessageEvaluationContext().setDestination(destination); + // Access the implementation of the test queue and move the last message + // to another queue. Verify that the move occurred within the limits of + // the test. + Queue queue = (Queue) broker.getRegionBroker().getDestinationMap().get(destination); - long startTimeMillis = System.currentTimeMillis(); - Assert.assertEquals(1, - queue.copyMatchingMessagesTo(context, "id=" + (QUEUE_SIZE - 1), createDestination(MOVE_TO_DESTINATION_NAME))); + ConnectionContext context = new ConnectionContext(new NonCachedMessageEvaluationContext()); + context.setBroker(broker.getBroker()); + context.getMessageEvaluationContext().setDestination(destination); - long durationMillis = System.currentTimeMillis() - startTimeMillis; + long startTimeMillis = System.currentTimeMillis(); + Assert.assertEquals(1, queue.copyMatchingMessagesTo(context, "id=" + (QUEUE_SIZE - 1), createDestination(MOVE_TO_DESTINATION_NAME))); - LOG.info("It took " + durationMillis - + "ms to copy the last message from a queue a " + QUEUE_SIZE - + " messages."); + long durationMillis = System.currentTimeMillis() - startTimeMillis; - Assert.assertTrue("Copying the message took too long: " + durationMillis - + "ms", durationMillis < TEST_TIMEOUT); - } + LOG.info("It took " + durationMillis + "ms to copy the last message from a queue a " + QUEUE_SIZE + " messages."); - public void testRemoveMessages() throws Exception { - final int QUEUE_SIZE = 30000; - final long TEST_TIMEOUT = 20000; + Assert.assertTrue("Copying the message took too long: " + durationMillis + "ms", durationMillis < TEST_TIMEOUT); + } - // Populate a test queue with uniquely-identifiable messages. - Connection conn = createConnection(); - try { - conn.start(); - Session session = conn.createSession(true, - Session.SESSION_TRANSACTED); - MessageProducer producer = session.createProducer(destination); - for (int i = 0; i < QUEUE_SIZE; i++) { - Message message = session.createMessage(); - message.setIntProperty("id", i); - producer.send(message); - } - session.commit(); - } finally { - conn.close(); - } + public void testRemoveMessages() throws Exception { + final int QUEUE_SIZE = 30000; + final long TEST_TIMEOUT = 20000; - // Access the implementation of the test queue and move the last message - // to another queue. Verify that the move occurred within the limits of - // the test. - Queue queue = (Queue) broker.getRegionBroker().getDestinationMap().get( - destination); + // Populate a test queue with uniquely-identifiable messages. + Connection conn = createConnection(); + try { + conn.start(); + Session session = conn.createSession(true, Session.SESSION_TRANSACTED); + MessageProducer producer = session.createProducer(destination); + for (int i = 0; i < QUEUE_SIZE; i++) { + Message message = session.createMessage(); + message.setIntProperty("id", i); + producer.send(message); + } + session.commit(); + } + finally { + conn.close(); + } - ConnectionContext context = new ConnectionContext( - new NonCachedMessageEvaluationContext()); - context.setBroker(broker.getBroker()); - context.getMessageEvaluationContext().setDestination(destination); + // Access the implementation of the test queue and move the last message + // to another queue. Verify that the move occurred within the limits of + // the test. + Queue queue = (Queue) broker.getRegionBroker().getDestinationMap().get(destination); - long startTimeMillis = System.currentTimeMillis(); - Assert.assertEquals(1, - queue.removeMatchingMessages("id=" + (QUEUE_SIZE - 1))); + ConnectionContext context = new ConnectionContext(new NonCachedMessageEvaluationContext()); + context.setBroker(broker.getBroker()); + context.getMessageEvaluationContext().setDestination(destination); - long durationMillis = System.currentTimeMillis() - startTimeMillis; + long startTimeMillis = System.currentTimeMillis(); + Assert.assertEquals(1, queue.removeMatchingMessages("id=" + (QUEUE_SIZE - 1))); - LOG.info("It took " + durationMillis - + "ms to remove the last message from a queue a " + QUEUE_SIZE - + " messages."); + long durationMillis = System.currentTimeMillis() - startTimeMillis; - Assert.assertTrue("Removing the message took too long: " + durationMillis - + "ms", durationMillis < TEST_TIMEOUT); - } + LOG.info("It took " + durationMillis + "ms to remove the last message from a queue a " + QUEUE_SIZE + " messages."); + + Assert.assertTrue("Removing the message took too long: " + durationMillis + "ms", durationMillis < TEST_TIMEOUT); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/LevelDBDurableSubscriptionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/LevelDBDurableSubscriptionTest.java index 426b8a31eb..3bd45038e2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/LevelDBDurableSubscriptionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/LevelDBDurableSubscriptionTest.java @@ -23,15 +23,15 @@ import org.apache.activemq.leveldb.LevelDBStore; import org.apache.activemq.store.PersistenceAdapter; /** - * + * */ public class LevelDBDurableSubscriptionTest extends DurableSubscriptionTestSupport { - protected PersistenceAdapter createPersistenceAdapter() throws IOException { - File dataDir = new File("target/test-data/durableLevelDB"); - LevelDBStore adaptor = new LevelDBStore(); - adaptor.setDirectory(dataDir); - return adaptor; - } + protected PersistenceAdapter createPersistenceAdapter() throws IOException { + File dataDir = new File("target/test-data/durableLevelDB"); + LevelDBStore adaptor = new LevelDBStore(); + adaptor.setDirectory(dataDir); + return adaptor; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ManagedDurableSubscriptionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ManagedDurableSubscriptionTest.java index 14fe6cb55a..75800e32c0 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ManagedDurableSubscriptionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ManagedDurableSubscriptionTest.java @@ -30,90 +30,90 @@ import org.apache.activemq.leveldb.LevelDBStore; public class ManagedDurableSubscriptionTest extends org.apache.activemq.TestSupport { - BrokerService broker = null; - Connection connection = null; - ActiveMQTopic topic; + BrokerService broker = null; + Connection connection = null; + ActiveMQTopic topic; - public void testJMXSubscriptions() throws Exception { - // create durable subscription - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId"); - session.close(); + public void testJMXSubscriptions() throws Exception { + // create durable subscription + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId"); + session.close(); - // restart the broker - stopBroker(); - startBroker(); + // restart the broker + stopBroker(); + startBroker(); - ObjectName inactiveSubscriptionObjectName = broker.getAdminView().getInactiveDurableTopicSubscribers()[0]; + ObjectName inactiveSubscriptionObjectName = broker.getAdminView().getInactiveDurableTopicSubscribers()[0]; - Object inactive = broker.getManagementContext().getAttribute(inactiveSubscriptionObjectName, "Active"); - assertTrue("Subscription is active.", Boolean.FALSE.equals(inactive)); + Object inactive = broker.getManagementContext().getAttribute(inactiveSubscriptionObjectName, "Active"); + assertTrue("Subscription is active.", Boolean.FALSE.equals(inactive)); - // activate - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId"); + // activate + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createDurableSubscriber(topic, "SubsId"); - ObjectName activeSubscriptionObjectName = broker.getAdminView().getDurableTopicSubscribers()[0]; + ObjectName activeSubscriptionObjectName = broker.getAdminView().getDurableTopicSubscribers()[0]; - Object active = broker.getManagementContext().getAttribute(activeSubscriptionObjectName, "Active"); - assertTrue("Subscription is INactive.", Boolean.TRUE.equals(active)); + Object active = broker.getManagementContext().getAttribute(activeSubscriptionObjectName, "Active"); + assertTrue("Subscription is INactive.", Boolean.TRUE.equals(active)); - // deactivate - connection.close(); - connection = null; + // deactivate + connection.close(); + connection = null; - inactive = broker.getManagementContext().getAttribute(inactiveSubscriptionObjectName, "Active"); - assertTrue("Subscription is active.", Boolean.FALSE.equals(inactive)); + inactive = broker.getManagementContext().getAttribute(inactiveSubscriptionObjectName, "Active"); + assertTrue("Subscription is active.", Boolean.FALSE.equals(inactive)); - } + } - private void startBroker() throws Exception { - broker = BrokerFactory.createBroker("broker:(vm://localhost)"); - broker.setKeepDurableSubsActive(false); - broker.setPersistent(true); - LevelDBStore persistenceAdapter = new LevelDBStore(); - persistenceAdapter.setDirectory(new File("activemq-data/" + getName())); - broker.setPersistenceAdapter(persistenceAdapter); - broker.setUseJmx(true); - broker.getManagementContext().setCreateConnector(false); - broker.setBrokerName(getName()); - broker.start(); + private void startBroker() throws Exception { + broker = BrokerFactory.createBroker("broker:(vm://localhost)"); + broker.setKeepDurableSubsActive(false); + broker.setPersistent(true); + LevelDBStore persistenceAdapter = new LevelDBStore(); + persistenceAdapter.setDirectory(new File("activemq-data/" + getName())); + broker.setPersistenceAdapter(persistenceAdapter); + broker.setUseJmx(true); + broker.getManagementContext().setCreateConnector(false); + broker.setBrokerName(getName()); + broker.start(); - connection = createConnection(); - } + connection = createConnection(); + } - private void stopBroker() throws Exception { - if (connection != null) - connection.close(); - connection = null; - if (broker != null) - broker.stop(); - broker = null; - } + private void stopBroker() throws Exception { + if (connection != null) + connection.close(); + connection = null; + if (broker != null) + broker.stop(); + broker = null; + } - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://" + getName() + "?waitForStart=5000&create=false"); - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory("vm://" + getName() + "?waitForStart=5000&create=false"); + } - @Override - protected void setUp() throws Exception { - super.setUp(); + @Override + protected void setUp() throws Exception { + super.setUp(); - topic = (ActiveMQTopic) createDestination(); - startBroker(); - } + topic = (ActiveMQTopic) createDestination(); + startBroker(); + } - @Override - protected void tearDown() throws Exception { - stopBroker(); - super.tearDown(); - } + @Override + protected void tearDown() throws Exception { + stopBroker(); + super.tearDown(); + } - @Override - protected Connection createConnection() throws Exception { - Connection rc = super.createConnection(); - rc.setClientID(getName()); - rc.start(); - return rc; - } + @Override + protected Connection createConnection() throws Exception { + Connection rc = super.createConnection(); + rc.setClientID(getName()); + rc.start(); + return rc; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MemoryLimitTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MemoryLimitTest.java index deb9cde774..8003364c33 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MemoryLimitTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MemoryLimitTest.java @@ -23,6 +23,7 @@ import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.Queue; import javax.jms.Session; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.TestSupport; import org.apache.activemq.broker.BrokerService; @@ -44,159 +45,160 @@ import org.slf4j.LoggerFactory; @RunWith(value = Parameterized.class) public class MemoryLimitTest extends TestSupport { - private static final Logger LOG = LoggerFactory.getLogger(MemoryLimitTest.class); - final byte[] payload = new byte[10 * 1024]; //10KB - protected BrokerService broker; - @Parameterized.Parameter - public TestSupport.PersistenceAdapterChoice persistenceAdapterChoice; + private static final Logger LOG = LoggerFactory.getLogger(MemoryLimitTest.class); + final byte[] payload = new byte[10 * 1024]; //10KB + protected BrokerService broker; - @Parameterized.Parameters(name="store={0}") - public static Iterable getTestParameters() { - return Arrays.asList(new Object[][]{{TestSupport.PersistenceAdapterChoice.KahaDB}, {PersistenceAdapterChoice.LevelDB}, {PersistenceAdapterChoice.JDBC}}); - } + @Parameterized.Parameter + public TestSupport.PersistenceAdapterChoice persistenceAdapterChoice; - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.getSystemUsage().getMemoryUsage().setLimit(1 * 1024 * 1024); //1MB - broker.deleteAllMessages(); + @Parameterized.Parameters(name = "store={0}") + public static Iterable getTestParameters() { + return Arrays.asList(new Object[][]{{TestSupport.PersistenceAdapterChoice.KahaDB}, {PersistenceAdapterChoice.LevelDB}, {PersistenceAdapterChoice.JDBC}}); + } - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policyEntry = new PolicyEntry(); - policyEntry.setProducerFlowControl(false); - policyMap.put(new ActiveMQQueue(">"), policyEntry); - broker.setDestinationPolicy(policyMap); + protected BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.getSystemUsage().getMemoryUsage().setLimit(1 * 1024 * 1024); //1MB + broker.deleteAllMessages(); - LOG.info("Starting broker with persistenceAdapterChoice " + persistenceAdapterChoice.toString()); - setPersistenceAdapter(broker, persistenceAdapterChoice); - broker.getPersistenceAdapter().deleteAllMessages(); + PolicyMap policyMap = new PolicyMap(); + PolicyEntry policyEntry = new PolicyEntry(); + policyEntry.setProducerFlowControl(false); + policyMap.put(new ActiveMQQueue(">"), policyEntry); + broker.setDestinationPolicy(policyMap); - return broker; - } + LOG.info("Starting broker with persistenceAdapterChoice " + persistenceAdapterChoice.toString()); + setPersistenceAdapter(broker, persistenceAdapterChoice); + broker.getPersistenceAdapter().deleteAllMessages(); - @Override - @Before - public void setUp() throws Exception { - if (broker == null) { - broker = createBroker(); - } - broker.start(); - broker.waitUntilStarted(); - } + return broker; + } - @Override - @After - public void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - } + @Override + @Before + public void setUp() throws Exception { + if (broker == null) { + broker = createBroker(); + } + broker.start(); + broker.waitUntilStarted(); + } - @Test(timeout = 120000) - public void testCursorBatch() throws Exception { + @Override + @After + public void tearDown() throws Exception { + if (broker != null) { + broker.stop(); + broker.waitUntilStopped(); + } + } - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?jms.prefetchPolicy.all=10"); - factory.setOptimizeAcknowledge(true); - Connection conn = factory.createConnection(); - conn.start(); - Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Queue queue = sess.createQueue("STORE"); - final ProducerThread producer = new ProducerThread(sess, queue) { - @Override - protected Message createMessage(int i) throws Exception { - BytesMessage bytesMessage = sess.createBytesMessage(); - bytesMessage.writeBytes(payload); - return bytesMessage; - } - }; - producer.setMessageCount(2000); - producer.start(); - producer.join(); + @Test(timeout = 120000) + public void testCursorBatch() throws Exception { - Thread.sleep(1000); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?jms.prefetchPolicy.all=10"); + factory.setOptimizeAcknowledge(true); + Connection conn = factory.createConnection(); + conn.start(); + Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Queue queue = sess.createQueue("STORE"); + final ProducerThread producer = new ProducerThread(sess, queue) { + @Override + protected Message createMessage(int i) throws Exception { + BytesMessage bytesMessage = sess.createBytesMessage(); + bytesMessage.writeBytes(payload); + return bytesMessage; + } + }; + producer.setMessageCount(2000); + producer.start(); + producer.join(); - // assert we didn't break high watermark (70%) usage - final Destination dest = broker.getDestination((ActiveMQQueue) queue); - LOG.info("Destination usage: " + dest.getMemoryUsage()); - int percentUsage = dest.getMemoryUsage().getPercentUsage(); - assertTrue("Should be less than 70% of limit but was: " + percentUsage, percentUsage <= 71); - LOG.info("Broker usage: " + broker.getSystemUsage().getMemoryUsage()); - assertTrue(broker.getSystemUsage().getMemoryUsage().getPercentUsage() <= 71); + Thread.sleep(1000); - // consume one message - MessageConsumer consumer = sess.createConsumer(queue); - Message msg = consumer.receive(5000); - msg.acknowledge(); + // assert we didn't break high watermark (70%) usage + final Destination dest = broker.getDestination((ActiveMQQueue) queue); + LOG.info("Destination usage: " + dest.getMemoryUsage()); + int percentUsage = dest.getMemoryUsage().getPercentUsage(); + assertTrue("Should be less than 70% of limit but was: " + percentUsage, percentUsage <= 71); + LOG.info("Broker usage: " + broker.getSystemUsage().getMemoryUsage()); + assertTrue(broker.getSystemUsage().getMemoryUsage().getPercentUsage() <= 71); - // this should free some space and allow us to get new batch of messages in the memory - // exceeding the limit - assertTrue("Limit is exceeded", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("Destination usage: " + dest.getMemoryUsage()); - return dest.getMemoryUsage().getPercentUsage() >= 200; - } - })); + // consume one message + MessageConsumer consumer = sess.createConsumer(queue); + Message msg = consumer.receive(5000); + msg.acknowledge(); - LOG.info("Broker usage: " + broker.getSystemUsage().getMemoryUsage()); - assertTrue(broker.getSystemUsage().getMemoryUsage().getPercentUsage() >= 200); + // this should free some space and allow us to get new batch of messages in the memory + // exceeding the limit + assertTrue("Limit is exceeded", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("Destination usage: " + dest.getMemoryUsage()); + return dest.getMemoryUsage().getPercentUsage() >= 200; + } + })); - // let's make sure we can consume all messages - for (int i = 1; i < 2000; i++) { - msg = consumer.receive(5000); - if (msg == null) { - dumpAllThreads("NoMessage"); - } - assertNotNull("Didn't receive message " + i, msg); - msg.acknowledge(); - } - } + LOG.info("Broker usage: " + broker.getSystemUsage().getMemoryUsage()); + assertTrue(broker.getSystemUsage().getMemoryUsage().getPercentUsage() >= 200); - /** - * Handy test for manually checking what's going on - */ - @Ignore - @Test(timeout = 120000) - public void testLimit() throws Exception { + // let's make sure we can consume all messages + for (int i = 1; i < 2000; i++) { + msg = consumer.receive(5000); + if (msg == null) { + dumpAllThreads("NoMessage"); + } + assertNotNull("Didn't receive message " + i, msg); + msg.acknowledge(); + } + } - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?jms.prefetchPolicy.all=10"); - factory.setOptimizeAcknowledge(true); - Connection conn = factory.createConnection(); - conn.start(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - final ProducerThread producer = new ProducerThread(sess, sess.createQueue("STORE.1")) { - @Override - protected Message createMessage(int i) throws Exception { - return sess.createTextMessage(Arrays.toString(payload) + "::" + i); - } - }; - producer.setMessageCount(1000); + /** + * Handy test for manually checking what's going on + */ + @Ignore + @Test(timeout = 120000) + public void testLimit() throws Exception { - final ProducerThread producer2 = new ProducerThread(sess, sess.createQueue("STORE.2")) { - @Override - protected Message createMessage(int i) throws Exception { - return sess.createTextMessage(Arrays.toString(payload) + "::" + i); - } - }; - producer2.setMessageCount(1000); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?jms.prefetchPolicy.all=10"); + factory.setOptimizeAcknowledge(true); + Connection conn = factory.createConnection(); + conn.start(); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + final ProducerThread producer = new ProducerThread(sess, sess.createQueue("STORE.1")) { + @Override + protected Message createMessage(int i) throws Exception { + return sess.createTextMessage(Arrays.toString(payload) + "::" + i); + } + }; + producer.setMessageCount(1000); - ConsumerThread consumer = new ConsumerThread(sess, sess.createQueue("STORE.1")); - consumer.setBreakOnNull(false); - consumer.setMessageCount(1000); + final ProducerThread producer2 = new ProducerThread(sess, sess.createQueue("STORE.2")) { + @Override + protected Message createMessage(int i) throws Exception { + return sess.createTextMessage(Arrays.toString(payload) + "::" + i); + } + }; + producer2.setMessageCount(1000); - producer.start(); - producer.join(); + ConsumerThread consumer = new ConsumerThread(sess, sess.createQueue("STORE.1")); + consumer.setBreakOnNull(false); + consumer.setMessageCount(1000); - producer2.start(); + producer.start(); + producer.join(); - Thread.sleep(300); + producer2.start(); - consumer.start(); + Thread.sleep(300); - consumer.join(); - producer2.join(); + consumer.start(); - assertEquals("consumer got all produced messages", producer.getMessageCount(), consumer.getReceived()); - } + consumer.join(); + producer2.join(); + + assertEquals("consumer got all produced messages", producer.getMessageCount(), consumer.getReceived()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupCloseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupCloseTest.java index b3341d85a5..5be065d7ea 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupCloseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupCloseTest.java @@ -17,6 +17,7 @@ package org.apache.activemq.usecases; import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -35,201 +36,212 @@ import java.util.concurrent.CountDownLatch; * 1 and 6 have the JMSXGroupFirstForConsumer property set to true. */ public class MessageGroupCloseTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(MessageGroupNewConsumerTest.class); - private Connection connection; - // Released after all messages are created - private CountDownLatch latchMessagesCreated = new CountDownLatch(1); - private int messagesSent, messagesRecvd1, messagesRecvd2, messageGroupCount, errorCountFirstForConsumer, errorCountWrongConsumerClose, errorCountDuplicateClose; - // groupID, count - private HashMap messageGroups1 = new HashMap(); - private HashMap messageGroups2 = new HashMap(); - private HashSet closedGroups1 = new HashSet(); - private HashSet closedGroups2 = new HashSet(); - // with the prefetch too high, this bug is not realized - private static final String connStr = - "vm://localhost?broker.persistent=false&broker.useJmx=false&jms.prefetchPolicy.all=1"; + private static final Logger LOG = LoggerFactory.getLogger(MessageGroupNewConsumerTest.class); + private Connection connection; + // Released after all messages are created + private CountDownLatch latchMessagesCreated = new CountDownLatch(1); - public void testNewConsumer() throws JMSException, InterruptedException { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connStr); - connection = factory.createConnection(); - connection.start(); - final String queueName = this.getClass().getSimpleName(); - final Thread producerThread = new Thread() { - public void run() { - try { - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Queue queue = session.createQueue(queueName); - MessageProducer prod = session.createProducer(queue); - for (int i=0; i<10; i++) { - for (int j=0; j<10; j++) { - int seq = j + 1; - if ((j+1) % 5 == 0) { - seq = -1; - } - Message message = generateMessage(session, Integer.toString(i), seq); - prod.send(message); - session.commit(); - messagesSent++; - LOG.info("Sent message: group=" + i + ", seq="+ seq); - //Thread.sleep(20); - } - if (i % 100 == 0) { - LOG.info("Sent messages: group=" + i); - } - setMessageGroupCount(getMessageGroupCount() + 1); - } - LOG.info(messagesSent+" messages sent"); - latchMessagesCreated.countDown(); - prod.close(); - session.close(); - } catch (Exception e) { - LOG.error("Producer failed", e); - } + private int messagesSent, messagesRecvd1, messagesRecvd2, messageGroupCount, errorCountFirstForConsumer, errorCountWrongConsumerClose, errorCountDuplicateClose; + // groupID, count + private HashMap messageGroups1 = new HashMap(); + private HashMap messageGroups2 = new HashMap(); + private HashSet closedGroups1 = new HashSet(); + private HashSet closedGroups2 = new HashSet(); + // with the prefetch too high, this bug is not realized + private static final String connStr = "vm://localhost?broker.persistent=false&broker.useJmx=false&jms.prefetchPolicy.all=1"; + + public void testNewConsumer() throws JMSException, InterruptedException { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connStr); + connection = factory.createConnection(); + connection.start(); + final String queueName = this.getClass().getSimpleName(); + final Thread producerThread = new Thread() { + public void run() { + try { + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + Queue queue = session.createQueue(queueName); + MessageProducer prod = session.createProducer(queue); + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + int seq = j + 1; + if ((j + 1) % 5 == 0) { + seq = -1; + } + Message message = generateMessage(session, Integer.toString(i), seq); + prod.send(message); + session.commit(); + messagesSent++; + LOG.info("Sent message: group=" + i + ", seq=" + seq); + //Thread.sleep(20); + } + if (i % 100 == 0) { + LOG.info("Sent messages: group=" + i); + } + setMessageGroupCount(getMessageGroupCount() + 1); + } + LOG.info(messagesSent + " messages sent"); + latchMessagesCreated.countDown(); + prod.close(); + session.close(); } - }; - final Thread consumerThread1 = new Thread() { - public void run() { - try { - latchMessagesCreated.await(); - LOG.info("starting consumer1"); - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Queue queue = session.createQueue(queueName); - MessageConsumer con1 = session.createConsumer(queue); - while(true) { - Message message = con1.receive(5000); - if (message == null) break; - LOG.info("Con1: got message "+formatMessage(message)); - checkMessage(message, "Con1", messageGroups1, closedGroups1); - session.commit(); - messagesRecvd1++; - if (messagesRecvd1 % 100 == 0) { - LOG.info("Con1: got messages count=" + messagesRecvd1); - } - //Thread.sleep(50); - } - LOG.info("Con1: total messages=" + messagesRecvd1); - LOG.info("Con1: total message groups=" + messageGroups1.size()); - con1.close(); - session.close(); - } catch (Exception e) { - LOG.error("Consumer 1 failed", e); - } + catch (Exception e) { + LOG.error("Producer failed", e); } - }; - final Thread consumerThread2 = new Thread() { - public void run() { - try { - latchMessagesCreated.await(); - LOG.info("starting consumer2"); - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Queue queue = session.createQueue(queueName); - MessageConsumer con2 = session.createConsumer(queue); - while(true) { - Message message = con2.receive(5000); - if (message == null) { break; } - LOG.info("Con2: got message "+formatMessage(message)); - checkMessage(message, "Con2", messageGroups2, closedGroups2); - session.commit(); - messagesRecvd2++; - if (messagesRecvd2 % 100 == 0) { - LOG.info("Con2: got messages count=" + messagesRecvd2); - } - //Thread.sleep(50); - } - con2.close(); - session.close(); - LOG.info("Con2: total messages=" + messagesRecvd2); - LOG.info("Con2: total message groups=" + messageGroups2.size()); - } catch (Exception e) { - LOG.error("Consumer 2 failed", e); - } + } + }; + final Thread consumerThread1 = new Thread() { + public void run() { + try { + latchMessagesCreated.await(); + LOG.info("starting consumer1"); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + Queue queue = session.createQueue(queueName); + MessageConsumer con1 = session.createConsumer(queue); + while (true) { + Message message = con1.receive(5000); + if (message == null) + break; + LOG.info("Con1: got message " + formatMessage(message)); + checkMessage(message, "Con1", messageGroups1, closedGroups1); + session.commit(); + messagesRecvd1++; + if (messagesRecvd1 % 100 == 0) { + LOG.info("Con1: got messages count=" + messagesRecvd1); + } + //Thread.sleep(50); + } + LOG.info("Con1: total messages=" + messagesRecvd1); + LOG.info("Con1: total message groups=" + messageGroups1.size()); + con1.close(); + session.close(); } - }; - consumerThread2.start(); - consumerThread1.start(); - producerThread.start(); - // wait for threads to finish - producerThread.join(); - consumerThread1.join(); - consumerThread2.join(); - connection.close(); - // check results + catch (Exception e) { + LOG.error("Consumer 1 failed", e); + } + } + }; + final Thread consumerThread2 = new Thread() { + public void run() { + try { + latchMessagesCreated.await(); + LOG.info("starting consumer2"); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + Queue queue = session.createQueue(queueName); + MessageConsumer con2 = session.createConsumer(queue); + while (true) { + Message message = con2.receive(5000); + if (message == null) { + break; + } + LOG.info("Con2: got message " + formatMessage(message)); + checkMessage(message, "Con2", messageGroups2, closedGroups2); + session.commit(); + messagesRecvd2++; + if (messagesRecvd2 % 100 == 0) { + LOG.info("Con2: got messages count=" + messagesRecvd2); + } + //Thread.sleep(50); + } + con2.close(); + session.close(); + LOG.info("Con2: total messages=" + messagesRecvd2); + LOG.info("Con2: total message groups=" + messageGroups2.size()); + } + catch (Exception e) { + LOG.error("Consumer 2 failed", e); + } + } + }; + consumerThread2.start(); + consumerThread1.start(); + producerThread.start(); + // wait for threads to finish + producerThread.join(); + consumerThread1.join(); + consumerThread2.join(); + connection.close(); + // check results - assertEquals("consumers should get all the messages", messagesSent, messagesRecvd1 + messagesRecvd2); - assertEquals("not all message groups closed for consumer 1", messageGroups1.size(), closedGroups1.size()); - assertEquals("not all message groups closed for consumer 2", messageGroups2.size(), closedGroups2.size()); - assertTrue("producer failed to send any messages", messagesSent > 0); - assertEquals("JMSXGroupFirstForConsumer not set", 0, errorCountFirstForConsumer); - assertEquals("wrong consumer got close message", 0, errorCountWrongConsumerClose); - assertEquals("consumer got duplicate close message", 0, errorCountDuplicateClose); - } + assertEquals("consumers should get all the messages", messagesSent, messagesRecvd1 + messagesRecvd2); + assertEquals("not all message groups closed for consumer 1", messageGroups1.size(), closedGroups1.size()); + assertEquals("not all message groups closed for consumer 2", messageGroups2.size(), closedGroups2.size()); + assertTrue("producer failed to send any messages", messagesSent > 0); + assertEquals("JMSXGroupFirstForConsumer not set", 0, errorCountFirstForConsumer); + assertEquals("wrong consumer got close message", 0, errorCountWrongConsumerClose); + assertEquals("consumer got duplicate close message", 0, errorCountDuplicateClose); + } - public Message generateMessage(Session session, String groupId, int seq) throws JMSException { - TextMessage m = session.createTextMessage(); - m.setJMSType("TEST_MESSAGE"); - m.setStringProperty("JMSXGroupID", groupId); - m.setIntProperty("JMSXGroupSeq", seq); - m.setText(""); - return m; - } - public String formatMessage(Message m) { - try { - return "group="+m.getStringProperty("JMSXGroupID")+", seq="+m.getIntProperty("JMSXGroupSeq"); - } catch (Exception e) { - return e.getClass().getSimpleName()+": "+e.getMessage(); - } - } - public void checkMessage(Message m, String consumerId, Map messageGroups, Set closedGroups) throws JMSException { - String groupId = m.getStringProperty("JMSXGroupID"); - int seq = m.getIntProperty("JMSXGroupSeq"); - Integer count = messageGroups.get(groupId); - if (count == null) { - // first time seeing this group - if (!m.propertyExists("JMSXGroupFirstForConsumer") || - !m.getBooleanProperty("JMSXGroupFirstForConsumer")) { - LOG.info(consumerId + ": JMSXGroupFirstForConsumer not set for group=" + groupId + ", seq=" +seq); - errorCountFirstForConsumer++; + public Message generateMessage(Session session, String groupId, int seq) throws JMSException { + TextMessage m = session.createTextMessage(); + m.setJMSType("TEST_MESSAGE"); + m.setStringProperty("JMSXGroupID", groupId); + m.setIntProperty("JMSXGroupSeq", seq); + m.setText(""); + return m; + } + + public String formatMessage(Message m) { + try { + return "group=" + m.getStringProperty("JMSXGroupID") + ", seq=" + m.getIntProperty("JMSXGroupSeq"); + } + catch (Exception e) { + return e.getClass().getSimpleName() + ": " + e.getMessage(); + } + } + + public void checkMessage(Message m, + String consumerId, + Map messageGroups, + Set closedGroups) throws JMSException { + String groupId = m.getStringProperty("JMSXGroupID"); + int seq = m.getIntProperty("JMSXGroupSeq"); + Integer count = messageGroups.get(groupId); + if (count == null) { + // first time seeing this group + if (!m.propertyExists("JMSXGroupFirstForConsumer") || !m.getBooleanProperty("JMSXGroupFirstForConsumer")) { + LOG.info(consumerId + ": JMSXGroupFirstForConsumer not set for group=" + groupId + ", seq=" + seq); + errorCountFirstForConsumer++; + } + if (seq == -1) { + closedGroups.add(groupId); + LOG.info(consumerId + ": wrong consumer got close message for group=" + groupId); + errorCountWrongConsumerClose++; + } + messageGroups.put(groupId, 1); + } + else { + // existing group + if (closedGroups.contains(groupId)) { + // group reassigned to same consumer + closedGroups.remove(groupId); + if (!m.propertyExists("JMSXGroupFirstForConsumer") || !m.getBooleanProperty("JMSXGroupFirstForConsumer")) { + LOG.info(consumerId + ": JMSXGroupFirstForConsumer not set for group=" + groupId + ", seq=" + seq); + errorCountFirstForConsumer++; } if (seq == -1) { - closedGroups.add(groupId); - LOG.info(consumerId + ": wrong consumer got close message for group=" + groupId); - errorCountWrongConsumerClose++; + LOG.info(consumerId + ": consumer got duplicate close message for group=" + groupId); + errorCountDuplicateClose++; } - messageGroups.put(groupId, 1); - } else { - // existing group - if (closedGroups.contains(groupId)) { - // group reassigned to same consumer - closedGroups.remove(groupId); - if (!m.propertyExists("JMSXGroupFirstForConsumer") || - !m.getBooleanProperty("JMSXGroupFirstForConsumer")) { - LOG.info(consumerId + ": JMSXGroupFirstForConsumer not set for group=" + groupId + ", seq=" +seq); - errorCountFirstForConsumer++; - } - if (seq == -1) { - LOG.info(consumerId + ": consumer got duplicate close message for group=" + groupId); - errorCountDuplicateClose++; - } - } - if (seq == -1) { - closedGroups.add(groupId); - } - messageGroups.put(groupId, count + 1); - } - } + } + if (seq == -1) { + closedGroups.add(groupId); + } + messageGroups.put(groupId, count + 1); + } + } - /** - * @return the messageGroupCount - */ - public int getMessageGroupCount() { - return messageGroupCount; - } + /** + * @return the messageGroupCount + */ + public int getMessageGroupCount() { + return messageGroupCount; + } - /** - * @param messageGroupCount the messageGroupCount to set - */ - public void setMessageGroupCount(int messageGroupCount) { - this.messageGroupCount = messageGroupCount; - } + /** + * @param messageGroupCount the messageGroupCount to set + */ + public void setMessageGroupCount(int messageGroupCount) { + this.messageGroupCount = messageGroupCount; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupDelayedTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupDelayedTest.java index bb20e420a7..678631912f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupDelayedTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupDelayedTest.java @@ -41,203 +41,213 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MessageGroupDelayedTest extends JmsTestSupport { - public static final Logger log = LoggerFactory.getLogger(MessageGroupDelayedTest.class); - protected Connection connection; - protected Session session; - protected MessageProducer producer; - protected Destination destination; - public int consumersBeforeDispatchStarts; - public int timeBeforeDispatchStarts; + public static final Logger log = LoggerFactory.getLogger(MessageGroupDelayedTest.class); + protected Connection connection; + protected Session session; + protected MessageProducer producer; + protected Destination destination; - BrokerService broker; - protected TransportConnector connector; + public int consumersBeforeDispatchStarts; + public int timeBeforeDispatchStarts; - protected HashMap messageCount = new HashMap(); - protected HashMap> messageGroups = new HashMap>(); + BrokerService broker; + protected TransportConnector connector; - public static Test suite() { - return suite(MessageGroupDelayedTest.class); - } + protected HashMap messageCount = new HashMap(); + protected HashMap> messageGroups = new HashMap>(); - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static Test suite() { + return suite(MessageGroupDelayedTest.class); + } - @Override - public void setUp() throws Exception { - broker = createBroker(); - broker.start(); - ActiveMQConnectionFactory connFactory = new ActiveMQConnectionFactory(connector.getConnectUri() + "?jms.prefetchPolicy.all=1"); - connection = connFactory.createConnection(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - destination = new ActiveMQQueue("test-queue2"); - producer = session.createProducer(destination); - connection.start(); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - @Override - protected BrokerService createBroker() throws Exception { - BrokerService service = new BrokerService(); - service.setPersistent(false); - service.setUseJmx(false); + @Override + public void setUp() throws Exception { + broker = createBroker(); + broker.start(); + ActiveMQConnectionFactory connFactory = new ActiveMQConnectionFactory(connector.getConnectUri() + "?jms.prefetchPolicy.all=1"); + connection = connFactory.createConnection(); + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + destination = new ActiveMQQueue("test-queue2"); + producer = session.createProducer(destination); + connection.start(); + } - // Setup a destination policy where it takes only 1 message at a time. - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policy = new PolicyEntry(); - log.info("testing with consumersBeforeDispatchStarts=" + consumersBeforeDispatchStarts + " and timeBeforeDispatchStarts=" + timeBeforeDispatchStarts); - policy.setConsumersBeforeDispatchStarts(consumersBeforeDispatchStarts); - policy.setTimeBeforeDispatchStarts(timeBeforeDispatchStarts); - policyMap.setDefaultEntry(policy); - service.setDestinationPolicy(policyMap); + @Override + protected BrokerService createBroker() throws Exception { + BrokerService service = new BrokerService(); + service.setPersistent(false); + service.setUseJmx(false); - connector = service.addConnector("tcp://localhost:0"); - return service; - } + // Setup a destination policy where it takes only 1 message at a time. + PolicyMap policyMap = new PolicyMap(); + PolicyEntry policy = new PolicyEntry(); + log.info("testing with consumersBeforeDispatchStarts=" + consumersBeforeDispatchStarts + " and timeBeforeDispatchStarts=" + timeBeforeDispatchStarts); + policy.setConsumersBeforeDispatchStarts(consumersBeforeDispatchStarts); + policy.setTimeBeforeDispatchStarts(timeBeforeDispatchStarts); + policyMap.setDefaultEntry(policy); + service.setDestinationPolicy(policyMap); - @Override - public void tearDown() throws Exception { - producer.close(); - session.close(); - connection.close(); - broker.stop(); - } + connector = service.addConnector("tcp://localhost:0"); + return service; + } - public void initCombosForTestDelayedDirectConnectionListener() { - addCombinationValues("consumersBeforeDispatchStarts", new Object[] { 0, 3, 5 }); - addCombinationValues("timeBeforeDispatchStarts", new Object[] { 0, 100 }); - } + @Override + public void tearDown() throws Exception { + producer.close(); + session.close(); + connection.close(); + broker.stop(); + } - public void testDelayedDirectConnectionListener() throws Exception { + public void initCombosForTestDelayedDirectConnectionListener() { + addCombinationValues("consumersBeforeDispatchStarts", new Object[]{0, 3, 5}); + addCombinationValues("timeBeforeDispatchStarts", new Object[]{0, 100}); + } - for (int i = 0; i < 10; i++) { - Message msga = session.createTextMessage("hello a"); - msga.setStringProperty("JMSXGroupID", "A"); - producer.send(msga); - Message msgb = session.createTextMessage("hello b"); - msgb.setStringProperty("JMSXGroupID", "B"); - producer.send(msgb); - Message msgc = session.createTextMessage("hello c"); - msgc.setStringProperty("JMSXGroupID", "C"); - producer.send(msgc); - } - log.info("30 messages sent to group A/B/C"); + public void testDelayedDirectConnectionListener() throws Exception { - int[] counters = { 10, 10, 10 }; + for (int i = 0; i < 10; i++) { + Message msga = session.createTextMessage("hello a"); + msga.setStringProperty("JMSXGroupID", "A"); + producer.send(msga); + Message msgb = session.createTextMessage("hello b"); + msgb.setStringProperty("JMSXGroupID", "B"); + producer.send(msgb); + Message msgc = session.createTextMessage("hello c"); + msgc.setStringProperty("JMSXGroupID", "C"); + producer.send(msgc); + } + log.info("30 messages sent to group A/B/C"); - CountDownLatch startSignal = new CountDownLatch(1); - CountDownLatch doneSignal = new CountDownLatch(1); + int[] counters = {10, 10, 10}; - messageCount.put("worker1", 0); - messageGroups.put("worker1", new HashSet()); - Worker worker1 = new Worker(connection, destination, "worker1", startSignal, doneSignal, counters, messageCount, messageGroups); - messageCount.put("worker2", 0); - messageGroups.put("worker2", new HashSet()); - Worker worker2 = new Worker(connection, destination, "worker2", startSignal, doneSignal, counters, messageCount, messageGroups); - messageCount.put("worker3", 0); - messageGroups.put("worker3", new HashSet()); - Worker worker3 = new Worker(connection, destination, "worker3", startSignal, doneSignal, counters, messageCount, messageGroups); + CountDownLatch startSignal = new CountDownLatch(1); + CountDownLatch doneSignal = new CountDownLatch(1); - new Thread(worker1).start(); - new Thread(worker2).start(); - new Thread(worker3).start(); + messageCount.put("worker1", 0); + messageGroups.put("worker1", new HashSet()); + Worker worker1 = new Worker(connection, destination, "worker1", startSignal, doneSignal, counters, messageCount, messageGroups); + messageCount.put("worker2", 0); + messageGroups.put("worker2", new HashSet()); + Worker worker2 = new Worker(connection, destination, "worker2", startSignal, doneSignal, counters, messageCount, messageGroups); + messageCount.put("worker3", 0); + messageGroups.put("worker3", new HashSet()); + Worker worker3 = new Worker(connection, destination, "worker3", startSignal, doneSignal, counters, messageCount, messageGroups); - startSignal.countDown(); - doneSignal.await(); + new Thread(worker1).start(); + new Thread(worker2).start(); + new Thread(worker3).start(); - // check results - if (consumersBeforeDispatchStarts == 0 && timeBeforeDispatchStarts == 0) { - log.info("Ignoring results because both parameters are 0"); - return; - } + startSignal.countDown(); + doneSignal.await(); - for (String worker : messageCount.keySet()) { - log.info("worker " + worker + " received " + messageCount.get(worker) + " messages from groups " + messageGroups.get(worker)); - assertEquals("worker " + worker + " received " + messageCount.get(worker) + " messages from groups " + messageGroups.get(worker), 10, messageCount - .get(worker).intValue()); - assertEquals("worker " + worker + " received " + messageCount.get(worker) + " messages from groups " + messageGroups.get(worker), 1, messageGroups - .get(worker).size()); - } + // check results + if (consumersBeforeDispatchStarts == 0 && timeBeforeDispatchStarts == 0) { + log.info("Ignoring results because both parameters are 0"); + return; + } - } + for (String worker : messageCount.keySet()) { + log.info("worker " + worker + " received " + messageCount.get(worker) + " messages from groups " + messageGroups.get(worker)); + assertEquals("worker " + worker + " received " + messageCount.get(worker) + " messages from groups " + messageGroups.get(worker), 10, messageCount.get(worker).intValue()); + assertEquals("worker " + worker + " received " + messageCount.get(worker) + " messages from groups " + messageGroups.get(worker), 1, messageGroups.get(worker).size()); + } - private static final class Worker implements Runnable { - private Connection connection = null; - private Destination queueName = null; - private String workerName = null; - private CountDownLatch startSignal = null; - private CountDownLatch doneSignal = null; - private int[] counters = null; - private final HashMap messageCount; - private final HashMap> messageGroups; + } - private Worker(Connection connection, Destination queueName, String workerName, CountDownLatch startSignal, CountDownLatch doneSignal, int[] counters, - HashMap messageCount, HashMap> messageGroups) { - this.connection = connection; - this.queueName = queueName; - this.workerName = workerName; - this.startSignal = startSignal; - this.doneSignal = doneSignal; - this.counters = counters; - this.messageCount = messageCount; - this.messageGroups = messageGroups; - } + private static final class Worker implements Runnable { - private void update(String group) { - int msgCount = messageCount.get(workerName); - messageCount.put(workerName, msgCount + 1); - Set groups = messageGroups.get(workerName); - groups.add(group); - messageGroups.put(workerName, groups); - } + private Connection connection = null; + private Destination queueName = null; + private String workerName = null; + private CountDownLatch startSignal = null; + private CountDownLatch doneSignal = null; + private int[] counters = null; + private final HashMap messageCount; + private final HashMap> messageGroups; - @Override - public void run() { + private Worker(Connection connection, + Destination queueName, + String workerName, + CountDownLatch startSignal, + CountDownLatch doneSignal, + int[] counters, + HashMap messageCount, + HashMap> messageGroups) { + this.connection = connection; + this.queueName = queueName; + this.workerName = workerName; + this.startSignal = startSignal; + this.doneSignal = doneSignal; + this.counters = counters; + this.messageCount = messageCount; + this.messageGroups = messageGroups; + } - try { - log.info(workerName); - startSignal.await(); - Session sess = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = sess.createConsumer(queueName); + private void update(String group) { + int msgCount = messageCount.get(workerName); + messageCount.put(workerName, msgCount + 1); + Set groups = messageGroups.get(workerName); + groups.add(group); + messageGroups.put(workerName, groups); + } - while (true) { - if (counters[0] == 0 && counters[1] == 0 && counters[2] == 0) { - doneSignal.countDown(); - log.info(workerName + " done..."); - break; - } + @Override + public void run() { - Message msg = consumer.receive(500); - if (msg == null) - continue; + try { + log.info(workerName); + startSignal.await(); + Session sess = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + MessageConsumer consumer = sess.createConsumer(queueName); - String group = msg.getStringProperty("JMSXGroupID"); - msg.getBooleanProperty("JMSXGroupFirstForConsumer"); + while (true) { + if (counters[0] == 0 && counters[1] == 0 && counters[2] == 0) { + doneSignal.countDown(); + log.info(workerName + " done..."); + break; + } - if ("A".equals(group)) { - --counters[0]; - update(group); - Thread.sleep(500); - } else if ("B".equals(group)) { - --counters[1]; - update(group); - Thread.sleep(100); - } else if ("C".equals(group)) { - --counters[2]; - update(group); - Thread.sleep(10); - } else { - log.warn("unknown group"); - } - if (counters[0] != 0 || counters[1] != 0 || counters[2] != 0) { - msg.acknowledge(); - } - } - consumer.close(); - sess.close(); - } catch (Exception e) { - e.printStackTrace(); + Message msg = consumer.receive(500); + if (msg == null) + continue; + + String group = msg.getStringProperty("JMSXGroupID"); + msg.getBooleanProperty("JMSXGroupFirstForConsumer"); + + if ("A".equals(group)) { + --counters[0]; + update(group); + Thread.sleep(500); + } + else if ("B".equals(group)) { + --counters[1]; + update(group); + Thread.sleep(100); + } + else if ("C".equals(group)) { + --counters[2]; + update(group); + Thread.sleep(10); + } + else { + log.warn("unknown group"); + } + if (counters[0] != 0 || counters[1] != 0 || counters[2] != 0) { + msg.acknowledge(); + } } - } - } + consumer.close(); + sess.close(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupLateArrivalsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupLateArrivalsTest.java index 7a9b410a90..8b83e44665 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupLateArrivalsTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupLateArrivalsTest.java @@ -50,254 +50,261 @@ import static org.junit.Assert.*; @RunWith(BlockJUnit4ClassRunner.class) public class MessageGroupLateArrivalsTest { - public static final Logger log = LoggerFactory.getLogger(MessageGroupLateArrivalsTest.class); - protected Connection connection; - protected Session session; - protected MessageProducer producer; - protected Destination destination; - BrokerService broker; - protected TransportConnector connector; + public static final Logger log = LoggerFactory.getLogger(MessageGroupLateArrivalsTest.class); + protected Connection connection; + protected Session session; + protected MessageProducer producer; + protected Destination destination; - protected HashMap messageCount = new HashMap(); - protected HashMap> messageGroups = new HashMap>(); + BrokerService broker; + protected TransportConnector connector; - @Before - public void setUp() throws Exception { - broker = createBroker(); - broker.start(); - ActiveMQConnectionFactory connFactory = new ActiveMQConnectionFactory(connector.getConnectUri() + "?jms.prefetchPolicy.all=1000"); - connection = connFactory.createConnection(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - destination = new ActiveMQQueue("test-queue2"); - producer = session.createProducer(destination); - connection.start(); - } + protected HashMap messageCount = new HashMap(); + protected HashMap> messageGroups = new HashMap>(); - protected BrokerService createBroker() throws Exception { - BrokerService service = new BrokerService(); - service.setPersistent(false); - service.setUseJmx(false); + @Before + public void setUp() throws Exception { + broker = createBroker(); + broker.start(); + ActiveMQConnectionFactory connFactory = new ActiveMQConnectionFactory(connector.getConnectUri() + "?jms.prefetchPolicy.all=1000"); + connection = connFactory.createConnection(); + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + destination = new ActiveMQQueue("test-queue2"); + producer = session.createProducer(destination); + connection.start(); + } - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policy = new PolicyEntry(); - policy.setUseConsumerPriority(true); - policyMap.setDefaultEntry(policy); - service.setDestinationPolicy(policyMap); + protected BrokerService createBroker() throws Exception { + BrokerService service = new BrokerService(); + service.setPersistent(false); + service.setUseJmx(false); - connector = service.addConnector("tcp://localhost:0"); - return service; - } + PolicyMap policyMap = new PolicyMap(); + PolicyEntry policy = new PolicyEntry(); + policy.setUseConsumerPriority(true); + policyMap.setDefaultEntry(policy); + service.setDestinationPolicy(policyMap); - @After - public void tearDown() throws Exception { - producer.close(); - session.close(); - connection.close(); - broker.stop(); - } + connector = service.addConnector("tcp://localhost:0"); + return service; + } - @Test(timeout = 30 * 1000) - public void testConsumersLateToThePartyGetSomeNewGroups() throws Exception { + @After + public void tearDown() throws Exception { + producer.close(); + session.close(); + connection.close(); + broker.stop(); + } - final int perBatch = 3; - int[] counters = {perBatch, perBatch, perBatch}; + @Test(timeout = 30 * 1000) + public void testConsumersLateToThePartyGetSomeNewGroups() throws Exception { - CountDownLatch startSignal = new CountDownLatch(0); - CountDownLatch doneSignal = new CountDownLatch(3); - CountDownLatch worker1Started = new CountDownLatch(1); - CountDownLatch worker2Started = new CountDownLatch(1); - CountDownLatch worker3Started = new CountDownLatch(1); + final int perBatch = 3; + int[] counters = {perBatch, perBatch, perBatch}; - messageCount.put("worker1", 0); - messageGroups.put("worker1", new HashSet()); - Worker worker1 = new Worker(connection, destination, "worker1", startSignal, doneSignal, counters, messageCount, messageGroups, worker1Started); - messageCount.put("worker2", 0); - messageGroups.put("worker2", new HashSet()); - Worker worker2 = new Worker(connection, destination, "worker2", startSignal, doneSignal, counters, messageCount, messageGroups, worker2Started); - messageCount.put("worker3", 0); - messageGroups.put("worker3", new HashSet()); - Worker worker3 = new Worker(connection, destination, "worker3", startSignal, doneSignal, counters, messageCount, messageGroups, worker3Started); + CountDownLatch startSignal = new CountDownLatch(0); + CountDownLatch doneSignal = new CountDownLatch(3); + CountDownLatch worker1Started = new CountDownLatch(1); + CountDownLatch worker2Started = new CountDownLatch(1); + CountDownLatch worker3Started = new CountDownLatch(1); - new Thread(worker1).start(); - new Thread(worker2).start(); - worker1Started.await(); - worker2Started.await(); + messageCount.put("worker1", 0); + messageGroups.put("worker1", new HashSet()); + Worker worker1 = new Worker(connection, destination, "worker1", startSignal, doneSignal, counters, messageCount, messageGroups, worker1Started); + messageCount.put("worker2", 0); + messageGroups.put("worker2", new HashSet()); + Worker worker2 = new Worker(connection, destination, "worker2", startSignal, doneSignal, counters, messageCount, messageGroups, worker2Started); + messageCount.put("worker3", 0); + messageGroups.put("worker3", new HashSet()); + Worker worker3 = new Worker(connection, destination, "worker3", startSignal, doneSignal, counters, messageCount, messageGroups, worker3Started); - for (int i = 0; i < perBatch; i++) { - Message msga = session.createTextMessage("hello a"); - msga.setStringProperty("JMSXGroupID", "A"); - producer.send(msga); + new Thread(worker1).start(); + new Thread(worker2).start(); + worker1Started.await(); + worker2Started.await(); - Message msgb = session.createTextMessage("hello b"); - msgb.setStringProperty("JMSXGroupID", "B"); - producer.send(msgb); - } + for (int i = 0; i < perBatch; i++) { + Message msga = session.createTextMessage("hello a"); + msga.setStringProperty("JMSXGroupID", "A"); + producer.send(msga); - // ensure this chap, late to the party gets a new group - new Thread(worker3).start(); + Message msgb = session.createTextMessage("hello b"); + msgb.setStringProperty("JMSXGroupID", "B"); + producer.send(msgb); + } - // wait for presence before new group - worker3Started.await(); + // ensure this chap, late to the party gets a new group + new Thread(worker3).start(); - for (int i = 0; i < perBatch; i++) { - Message msgc = session.createTextMessage("hello c"); - msgc.setStringProperty("JMSXGroupID", "C"); - producer.send(msgc); - } + // wait for presence before new group + worker3Started.await(); - doneSignal.await(); + for (int i = 0; i < perBatch; i++) { + Message msgc = session.createTextMessage("hello c"); + msgc.setStringProperty("JMSXGroupID", "C"); + producer.send(msgc); + } - List workers = new ArrayList(messageCount.keySet()); - Collections.sort(workers); - for (String worker : workers) { - log.info("worker " + worker + " received " + messageCount.get(worker) + " messages from groups " + messageGroups.get(worker)); - } + doneSignal.await(); - for (String worker : workers) { - assertEquals("worker " + worker + " received " + messageCount.get(worker) + " messages from groups " + messageGroups.get(worker) - , perBatch, messageCount.get(worker).intValue()); - assertEquals("worker " + worker + " received " + messageCount.get(worker) + " messages from groups " + messageGroups.get(worker) - , 1, messageGroups.get(worker).size()); - } - } + List workers = new ArrayList(messageCount.keySet()); + Collections.sort(workers); + for (String worker : workers) { + log.info("worker " + worker + " received " + messageCount.get(worker) + " messages from groups " + messageGroups.get(worker)); + } - @Test(timeout = 30 * 1000) - public void testConsumerLateToBigPartyGetsNewGroup() throws Exception { + for (String worker : workers) { + assertEquals("worker " + worker + " received " + messageCount.get(worker) + " messages from groups " + messageGroups.get(worker), perBatch, messageCount.get(worker).intValue()); + assertEquals("worker " + worker + " received " + messageCount.get(worker) + " messages from groups " + messageGroups.get(worker), 1, messageGroups.get(worker).size()); + } + } - final int perBatch = 2; - int[] counters = {perBatch, perBatch, perBatch}; + @Test(timeout = 30 * 1000) + public void testConsumerLateToBigPartyGetsNewGroup() throws Exception { - CountDownLatch startSignal = new CountDownLatch(0); - CountDownLatch doneSignal = new CountDownLatch(2); - CountDownLatch worker1Started = new CountDownLatch(1); - CountDownLatch worker2Started = new CountDownLatch(1); + final int perBatch = 2; + int[] counters = {perBatch, perBatch, perBatch}; - messageCount.put("worker1", 0); - messageGroups.put("worker1", new HashSet()); - Worker worker1 = new Worker(connection, destination, "worker1", startSignal, doneSignal, counters, messageCount, messageGroups, worker1Started); - messageCount.put("worker2", 0); - messageGroups.put("worker2", new HashSet()); - Worker worker2 = new Worker(connection, destination, "worker2", startSignal, doneSignal, counters, messageCount, messageGroups, worker2Started); + CountDownLatch startSignal = new CountDownLatch(0); + CountDownLatch doneSignal = new CountDownLatch(2); + CountDownLatch worker1Started = new CountDownLatch(1); + CountDownLatch worker2Started = new CountDownLatch(1); - new Thread(worker1).start(); + messageCount.put("worker1", 0); + messageGroups.put("worker1", new HashSet()); + Worker worker1 = new Worker(connection, destination, "worker1", startSignal, doneSignal, counters, messageCount, messageGroups, worker1Started); + messageCount.put("worker2", 0); + messageGroups.put("worker2", new HashSet()); + Worker worker2 = new Worker(connection, destination, "worker2", startSignal, doneSignal, counters, messageCount, messageGroups, worker2Started); - for (int i = 0; i < perBatch; i++) { - Message msga = session.createTextMessage("hello c"); - msga.setStringProperty("JMSXGroupID", "A"); - producer.send(msga); + new Thread(worker1).start(); - Message msgb = session.createTextMessage("hello b"); - msgb.setStringProperty("JMSXGroupID", "B"); - producer.send(msgb); - } + for (int i = 0; i < perBatch; i++) { + Message msga = session.createTextMessage("hello c"); + msga.setStringProperty("JMSXGroupID", "A"); + producer.send(msga); - // ensure this chap, late to the party gets a new group - new Thread(worker2).start(); + Message msgb = session.createTextMessage("hello b"); + msgb.setStringProperty("JMSXGroupID", "B"); + producer.send(msgb); + } - // wait for presence before new group - worker2Started.await(); + // ensure this chap, late to the party gets a new group + new Thread(worker2).start(); - for (int i = 0; i < perBatch; i++) { - Message msgc = session.createTextMessage("hello a"); - msgc.setStringProperty("JMSXGroupID", "C"); - producer.send(msgc); - } + // wait for presence before new group + worker2Started.await(); - doneSignal.await(); + for (int i = 0; i < perBatch; i++) { + Message msgc = session.createTextMessage("hello a"); + msgc.setStringProperty("JMSXGroupID", "C"); + producer.send(msgc); + } - log.info("worker1 received " + messageCount.get("worker1") + " messages from groups " + messageGroups.get("worker1")); - assertEquals("worker1 received " + messageCount.get("worker1") + " messages from groups " + messageGroups.get("worker1") - , 2 * perBatch, messageCount.get("worker1").intValue()); - assertEquals("worker1 received " + messageCount.get("worker1") + " messages from groups " + messageGroups.get("worker1") - , 2, messageGroups.get("worker1").size()); + doneSignal.await(); - log.info("worker2 received " + messageCount.get("worker2") + " messages from groups " + messageGroups.get("worker2")); - assertEquals("worker2 received " + messageCount.get("worker2") + " messages from groups " + messageGroups.get("worker2") - , 2 * perBatch, messageCount.get("worker1").intValue()); - assertEquals("worker2 received " + messageCount.get("worker2") + " messages from groups " + messageGroups.get("worker2") - , 1, messageGroups.get("worker2").size()); - } + log.info("worker1 received " + messageCount.get("worker1") + " messages from groups " + messageGroups.get("worker1")); + assertEquals("worker1 received " + messageCount.get("worker1") + " messages from groups " + messageGroups.get("worker1"), 2 * perBatch, messageCount.get("worker1").intValue()); + assertEquals("worker1 received " + messageCount.get("worker1") + " messages from groups " + messageGroups.get("worker1"), 2, messageGroups.get("worker1").size()); - private static final class Worker implements Runnable { - private Connection connection = null; - private Destination queueName = null; - private String workerName = null; - private CountDownLatch startSignal = null; - private CountDownLatch doneSignal = null; - private CountDownLatch workerStarted = null; - private int[] counters = null; - private final HashMap messageCount; - private final HashMap> messageGroups; + log.info("worker2 received " + messageCount.get("worker2") + " messages from groups " + messageGroups.get("worker2")); + assertEquals("worker2 received " + messageCount.get("worker2") + " messages from groups " + messageGroups.get("worker2"), 2 * perBatch, messageCount.get("worker1").intValue()); + assertEquals("worker2 received " + messageCount.get("worker2") + " messages from groups " + messageGroups.get("worker2"), 1, messageGroups.get("worker2").size()); + } - private Worker(Connection connection, Destination queueName, String workerName, CountDownLatch startSignal, CountDownLatch doneSignal, - int[] counters, HashMap messageCount, HashMap> messageGroups, CountDownLatch workerStarted) { - this.connection = connection; - this.queueName = queueName; - this.workerName = workerName; - this.startSignal = startSignal; - this.doneSignal = doneSignal; - this.counters = counters; - this.messageCount = messageCount; - this.messageGroups = messageGroups; - this.workerStarted = workerStarted; - } + private static final class Worker implements Runnable { - private void update(String group) { - int msgCount = messageCount.get(workerName); - messageCount.put(workerName, msgCount + 1); - Set groups = messageGroups.get(workerName); - groups.add(group); - messageGroups.put(workerName, groups); - } + private Connection connection = null; + private Destination queueName = null; + private String workerName = null; + private CountDownLatch startSignal = null; + private CountDownLatch doneSignal = null; + private CountDownLatch workerStarted = null; + private int[] counters = null; + private final HashMap messageCount; + private final HashMap> messageGroups; - @Override - public void run() { + private Worker(Connection connection, + Destination queueName, + String workerName, + CountDownLatch startSignal, + CountDownLatch doneSignal, + int[] counters, + HashMap messageCount, + HashMap> messageGroups, + CountDownLatch workerStarted) { + this.connection = connection; + this.queueName = queueName; + this.workerName = workerName; + this.startSignal = startSignal; + this.doneSignal = doneSignal; + this.counters = counters; + this.messageCount = messageCount; + this.messageGroups = messageGroups; + this.workerStarted = workerStarted; + } - try { - startSignal.await(); - log.info(workerName); - Session sess = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = sess.createConsumer(queueName); - workerStarted.countDown(); + private void update(String group) { + int msgCount = messageCount.get(workerName); + messageCount.put(workerName, msgCount + 1); + Set groups = messageGroups.get(workerName); + groups.add(group); + messageGroups.put(workerName, groups); + } - while (true) { - if (counters[0] == 0 && counters[1] == 0 && counters[2] == 0) { - doneSignal.countDown(); - log.info(workerName + " done..."); - break; - } + @Override + public void run() { - Message msg = consumer.receive(500); - if (msg == null) - continue; + try { + startSignal.await(); + log.info(workerName); + Session sess = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + MessageConsumer consumer = sess.createConsumer(queueName); + workerStarted.countDown(); - msg.acknowledge(); + while (true) { + if (counters[0] == 0 && counters[1] == 0 && counters[2] == 0) { + doneSignal.countDown(); + log.info(workerName + " done..."); + break; + } - String group = msg.getStringProperty("JMSXGroupID"); - msg.getBooleanProperty("JMSXGroupFirstForConsumer"); + Message msg = consumer.receive(500); + if (msg == null) + continue; - if ("A".equals(group)) { - --counters[0]; - update(group); - } else if ("B".equals(group)) { - --counters[1]; - update(group); - } else if ("C".equals(group)) { - --counters[2]; - update(group); - } else { - log.warn(workerName + ", unknown group"); - } - if (counters[0] != 0 || counters[1] != 0 || counters[2] != 0) { - msg.acknowledge(); - } - } - consumer.close(); - sess.close(); - } catch (Exception e) { - e.printStackTrace(); + msg.acknowledge(); + + String group = msg.getStringProperty("JMSXGroupID"); + msg.getBooleanProperty("JMSXGroupFirstForConsumer"); + + if ("A".equals(group)) { + --counters[0]; + update(group); + } + else if ("B".equals(group)) { + --counters[1]; + update(group); + } + else if ("C".equals(group)) { + --counters[2]; + update(group); + } + else { + log.warn(workerName + ", unknown group"); + } + if (counters[0] != 0 || counters[1] != 0 || counters[2] != 0) { + msg.acknowledge(); + } } - } - } + consumer.close(); + sess.close(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupNewConsumerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupNewConsumerTest.java index 5d43f66510..cb88ea922a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupNewConsumerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupNewConsumerTest.java @@ -30,6 +30,7 @@ import javax.jms.TextMessage; import org.apache.activemq.ActiveMQConnectionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import junit.framework.TestCase; /* @@ -37,142 +38,150 @@ import junit.framework.TestCase; * Producer: publish messages into a queue, with three message groups * Consumer1: created before any messages are created * Consumer2: created after consumer1 has processed one message from each message group - * + * * All three groups are handled by to consumer1, so consumer2 should not get any messages. * See bug AMQ-2016: Message grouping fails when consumers are added */ public class MessageGroupNewConsumerTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(MessageGroupNewConsumerTest.class); - private Connection connection; - // Released after the messages are created - private CountDownLatch latchMessagesCreated = new CountDownLatch(1); - // Released after one message from each group is consumed - private CountDownLatch latchGroupsAcquired = new CountDownLatch(1); - private static final String[] groupNames = { "GrA", "GrB", "GrC" }; - private int messagesSent, messagesRecvd1, messagesRecvd2; - // with the prefetch too high, this bug is not realized - private static final String connStr = "vm://localhost?broker.persistent=false&broker.useJmx=false&jms.prefetchPolicy.all=1"; + private static final Logger LOG = LoggerFactory.getLogger(MessageGroupNewConsumerTest.class); + private Connection connection; + // Released after the messages are created + private CountDownLatch latchMessagesCreated = new CountDownLatch(1); + // Released after one message from each group is consumed + private CountDownLatch latchGroupsAcquired = new CountDownLatch(1); - public void testNewConsumer() throws JMSException, InterruptedException { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connStr); - connection = factory.createConnection(); - connection.start(); - final String queueName = this.getClass().getSimpleName(); - final Thread producerThread = new Thread() { - public void run() { - try { - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Queue queue = session.createQueue(queueName); - MessageProducer prod = session.createProducer(queue); - for (int i=0; i<10; i++) { - for(String group : groupNames) { - Message message = generateMessage(session, group, i+1); - prod.send(message); - session.commit(); - messagesSent++; - } - LOG.info("Sent message seq "+ (i+1)); - if (i==0) { - latchMessagesCreated.countDown(); - } - if (i==2) { - LOG.info("Prod: Waiting for groups"); - latchGroupsAcquired.await(); - } - Thread.sleep(20); - } - LOG.info(messagesSent+" messages sent"); - prod.close(); - session.close(); - } catch (Exception e) { - LOG.error("Producer failed", e); - } - } - }; - final Thread consumerThread1 = new Thread() { - public void run() { - try { - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Queue queue = session.createQueue(queueName); - MessageConsumer con1 = session.createConsumer(queue); - latchMessagesCreated.await(); - while(true) { - Message message = con1.receive(1000); - if (message == null) break; - LOG.info("Con1 got message "+formatMessage(message)); - session.commit(); - messagesRecvd1++; - // since we get the messages in order, the first few messages will be one from each group - // after we get one from each group, start the other consumer - if (messagesRecvd1 == groupNames.length) { - LOG.info("All groups acquired"); - latchGroupsAcquired.countDown(); - Thread.sleep(1000); - } - Thread.sleep(50); - } - LOG.info(messagesRecvd1+" messages received by consumer1"); - con1.close(); - session.close(); - } catch (Exception e) { - LOG.error("Consumer 1 failed", e); - } - } - }; - final Thread consumerThread2 = new Thread() { - public void run() { - try { - latchGroupsAcquired.await(); - while(consumerThread1.isAlive()) { - LOG.info("(re)starting consumer2"); - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Queue queue = session.createQueue(queueName); - MessageConsumer con2 = session.createConsumer(queue); - while(true) { - Message message = con2.receive(500); - if (message == null) break; - LOG.info("Con2 got message "+formatMessage(message)); - session.commit(); - messagesRecvd2++; - Thread.sleep(50); - } - con2.close(); - session.close(); - } - LOG.info(messagesRecvd2+" messages received by consumer2"); - } catch (Exception e) { - LOG.error("Consumer 2 failed", e); - } - } - }; - consumerThread2.start(); - consumerThread1.start(); - producerThread.start(); - // wait for threads to finish - producerThread.join(); - consumerThread1.join(); - consumerThread2.join(); - connection.close(); - // check results - assertEquals("consumer 2 should not get any messages", 0, messagesRecvd2); - assertEquals("consumer 1 should get all the messages", messagesSent, messagesRecvd1); - assertTrue("producer failed to send any messages", messagesSent > 0); - } + private static final String[] groupNames = {"GrA", "GrB", "GrC"}; + private int messagesSent, messagesRecvd1, messagesRecvd2; + // with the prefetch too high, this bug is not realized + private static final String connStr = "vm://localhost?broker.persistent=false&broker.useJmx=false&jms.prefetchPolicy.all=1"; - public Message generateMessage(Session session, String groupId, int seq) throws JMSException { - TextMessage m = session.createTextMessage(); - m.setJMSType("TEST_MESSAGE"); - m.setStringProperty("JMSXGroupID", groupId); - m.setIntProperty("JMSXGroupSeq", seq); - m.setText(""); - return m; - } - public String formatMessage(Message m) { - try { - return m.getStringProperty("JMSXGroupID")+"-"+m.getIntProperty("JMSXGroupSeq")+"-"+m.getBooleanProperty("JMSXGroupFirstForConsumer"); - } catch (Exception e) { - return e.getClass().getSimpleName()+": "+e.getMessage(); - } - } + public void testNewConsumer() throws JMSException, InterruptedException { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connStr); + connection = factory.createConnection(); + connection.start(); + final String queueName = this.getClass().getSimpleName(); + final Thread producerThread = new Thread() { + public void run() { + try { + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + Queue queue = session.createQueue(queueName); + MessageProducer prod = session.createProducer(queue); + for (int i = 0; i < 10; i++) { + for (String group : groupNames) { + Message message = generateMessage(session, group, i + 1); + prod.send(message); + session.commit(); + messagesSent++; + } + LOG.info("Sent message seq " + (i + 1)); + if (i == 0) { + latchMessagesCreated.countDown(); + } + if (i == 2) { + LOG.info("Prod: Waiting for groups"); + latchGroupsAcquired.await(); + } + Thread.sleep(20); + } + LOG.info(messagesSent + " messages sent"); + prod.close(); + session.close(); + } + catch (Exception e) { + LOG.error("Producer failed", e); + } + } + }; + final Thread consumerThread1 = new Thread() { + public void run() { + try { + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + Queue queue = session.createQueue(queueName); + MessageConsumer con1 = session.createConsumer(queue); + latchMessagesCreated.await(); + while (true) { + Message message = con1.receive(1000); + if (message == null) + break; + LOG.info("Con1 got message " + formatMessage(message)); + session.commit(); + messagesRecvd1++; + // since we get the messages in order, the first few messages will be one from each group + // after we get one from each group, start the other consumer + if (messagesRecvd1 == groupNames.length) { + LOG.info("All groups acquired"); + latchGroupsAcquired.countDown(); + Thread.sleep(1000); + } + Thread.sleep(50); + } + LOG.info(messagesRecvd1 + " messages received by consumer1"); + con1.close(); + session.close(); + } + catch (Exception e) { + LOG.error("Consumer 1 failed", e); + } + } + }; + final Thread consumerThread2 = new Thread() { + public void run() { + try { + latchGroupsAcquired.await(); + while (consumerThread1.isAlive()) { + LOG.info("(re)starting consumer2"); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + Queue queue = session.createQueue(queueName); + MessageConsumer con2 = session.createConsumer(queue); + while (true) { + Message message = con2.receive(500); + if (message == null) + break; + LOG.info("Con2 got message " + formatMessage(message)); + session.commit(); + messagesRecvd2++; + Thread.sleep(50); + } + con2.close(); + session.close(); + } + LOG.info(messagesRecvd2 + " messages received by consumer2"); + } + catch (Exception e) { + LOG.error("Consumer 2 failed", e); + } + } + }; + consumerThread2.start(); + consumerThread1.start(); + producerThread.start(); + // wait for threads to finish + producerThread.join(); + consumerThread1.join(); + consumerThread2.join(); + connection.close(); + // check results + assertEquals("consumer 2 should not get any messages", 0, messagesRecvd2); + assertEquals("consumer 1 should get all the messages", messagesSent, messagesRecvd1); + assertTrue("producer failed to send any messages", messagesSent > 0); + } + + public Message generateMessage(Session session, String groupId, int seq) throws JMSException { + TextMessage m = session.createTextMessage(); + m.setJMSType("TEST_MESSAGE"); + m.setStringProperty("JMSXGroupID", groupId); + m.setIntProperty("JMSXGroupSeq", seq); + m.setText(""); + return m; + } + + public String formatMessage(Message m) { + try { + return m.getStringProperty("JMSXGroupID") + "-" + m.getIntProperty("JMSXGroupSeq") + "-" + m.getBooleanProperty("JMSXGroupFirstForConsumer"); + } + catch (Exception e) { + return e.getClass().getSimpleName() + ": " + e.getMessage(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupReconnectDistributionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupReconnectDistributionTest.java index bbc3a7aec5..609626622b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupReconnectDistributionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupReconnectDistributionTest.java @@ -31,6 +31,7 @@ import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.TransportConnector; @@ -45,174 +46,175 @@ import org.junit.runners.Parameterized; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @RunWith(Parameterized.class) public class MessageGroupReconnectDistributionTest { - public static final Logger LOG = LoggerFactory.getLogger(MessageGroupReconnectDistributionTest.class); - final Random random = new Random(); - protected Connection connection; - protected Session session; - protected MessageProducer producer; - protected ActiveMQQueue destination = new ActiveMQQueue("GroupQ"); - protected TransportConnector connector; - ActiveMQConnectionFactory connFactory; - BrokerService broker; - int numMessages = 10000; - int groupSize = 10; - int batchSize = 20; - @Parameterized.Parameter(0) - public int numConsumers = 4; + public static final Logger LOG = LoggerFactory.getLogger(MessageGroupReconnectDistributionTest.class); + final Random random = new Random(); + protected Connection connection; + protected Session session; + protected MessageProducer producer; + protected ActiveMQQueue destination = new ActiveMQQueue("GroupQ"); + protected TransportConnector connector; + ActiveMQConnectionFactory connFactory; + BrokerService broker; + int numMessages = 10000; + int groupSize = 10; + int batchSize = 20; - @Parameterized.Parameter(1) - public boolean consumerPriority = true; + @Parameterized.Parameter(0) + public int numConsumers = 4; - @Parameterized.Parameters(name="numConsumers={0},consumerPriority={1}") - public static Iterable combinations() { - return Arrays.asList(new Object[][]{{4, true}, {10, true}}); - } + @Parameterized.Parameter(1) + public boolean consumerPriority = true; - @Before - public void setUp() throws Exception { - broker = createBroker(); - broker.start(); - connFactory = new ActiveMQConnectionFactory(connector.getConnectUri() + "?jms.prefetchPolicy.all=200"); - connFactory.setWatchTopicAdvisories(false); - connection = connFactory.createConnection(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - producer = session.createProducer(destination); - connection.start(); - } + @Parameterized.Parameters(name = "numConsumers={0},consumerPriority={1}") + public static Iterable combinations() { + return Arrays.asList(new Object[][]{{4, true}, {10, true}}); + } - protected BrokerService createBroker() throws Exception { - BrokerService service = new BrokerService(); - service.setAdvisorySupport(false); - service.setPersistent(false); - service.setUseJmx(true); + @Before + public void setUp() throws Exception { + broker = createBroker(); + broker.start(); + connFactory = new ActiveMQConnectionFactory(connector.getConnectUri() + "?jms.prefetchPolicy.all=200"); + connFactory.setWatchTopicAdvisories(false); + connection = connFactory.createConnection(); + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + producer = session.createProducer(destination); + connection.start(); + } - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policy = new PolicyEntry(); - policy.setUseConsumerPriority(consumerPriority); - policy.setMessageGroupMapFactoryType("cached?cacheSize=" + (numConsumers - 1)); - policyMap.setDefaultEntry(policy); - service.setDestinationPolicy(policyMap); + protected BrokerService createBroker() throws Exception { + BrokerService service = new BrokerService(); + service.setAdvisorySupport(false); + service.setPersistent(false); + service.setUseJmx(true); - connector = service.addConnector("tcp://localhost:0"); - return service; - } + PolicyMap policyMap = new PolicyMap(); + PolicyEntry policy = new PolicyEntry(); + policy.setUseConsumerPriority(consumerPriority); + policy.setMessageGroupMapFactoryType("cached?cacheSize=" + (numConsumers - 1)); + policyMap.setDefaultEntry(policy); + service.setDestinationPolicy(policyMap); - @After - public void tearDown() throws Exception { - producer.close(); - session.close(); - connection.close(); - broker.stop(); - } + connector = service.addConnector("tcp://localhost:0"); + return service; + } - @Test(timeout = 5 * 60 * 1000) - public void testReconnect() throws Exception { + @After + public void tearDown() throws Exception { + producer.close(); + session.close(); + connection.close(); + broker.stop(); + } - final AtomicLong totalConsumed = new AtomicLong(0); + @Test(timeout = 5 * 60 * 1000) + public void testReconnect() throws Exception { - ExecutorService executorService = Executors.newFixedThreadPool(numConsumers); - final ArrayList consumedCounters = new ArrayList(numConsumers); - final ArrayList batchCounters = new ArrayList(numConsumers); + final AtomicLong totalConsumed = new AtomicLong(0); - for (int i = 0; i < numConsumers; i++) { - consumedCounters.add(new AtomicLong(0L)); - batchCounters.add(new AtomicLong(0L)); + ExecutorService executorService = Executors.newFixedThreadPool(numConsumers); + final ArrayList consumedCounters = new ArrayList(numConsumers); + final ArrayList batchCounters = new ArrayList(numConsumers); - final int id = i; - executorService.submit(new Runnable() { - int getBatchSize() { - return (id + 1) * batchSize; - } + for (int i = 0; i < numConsumers; i++) { + consumedCounters.add(new AtomicLong(0L)); + batchCounters.add(new AtomicLong(0L)); - @Override - public void run() { - try { - Session connectionSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - int batchSize = getBatchSize(); - MessageConsumer messageConsumer = connectionSession.createConsumer(destWithPrefetch(destination)); - - Message message; - AtomicLong consumed = consumedCounters.get(id); - AtomicLong batches = batchCounters.get(id); - - LOG.info("Consumer: " + id + ", batchSize:" + batchSize + ", totalConsumed:" + totalConsumed.get() + ", consumed:" + consumed.get()); - - while (totalConsumed.get() < numMessages) { - - message = messageConsumer.receive(10000); - - if (message == null) { - LOG.info("Consumer: " + id + ", batchSize:" + batchSize + ", null message (totalConsumed:" + totalConsumed.get() + ") consumed:" + consumed.get()); - messageConsumer.close(); - - if (totalConsumed.get() == numMessages) { - break; - } else { - batchSize = getBatchSize(); - messageConsumer = connectionSession.createConsumer(destWithPrefetch(destination)); - batches.incrementAndGet(); - continue; - } - } - - consumed.incrementAndGet(); - totalConsumed.incrementAndGet(); - - if (consumed.get() > 0 && consumed.intValue() % batchSize == 0) { - messageConsumer.close(); - batchSize = getBatchSize(); - messageConsumer = connectionSession.createConsumer(destWithPrefetch(destination)); - batches.incrementAndGet(); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - TimeUnit.MILLISECONDS.sleep(200); - } - - TimeUnit.SECONDS.sleep(1); - produceMessages(numMessages); - - executorService.shutdown(); - assertTrue("threads done on time", executorService.awaitTermination(10, TimeUnit.MINUTES)); - - assertEquals("All consumed", numMessages, totalConsumed.intValue()); - - LOG.info("Distribution: " + consumedCounters); - LOG.info("Batches: " + batchCounters); - - double max = consumedCounters.get(0).longValue() * 1.5; - double min = consumedCounters.get(0).longValue() * 0.5; - - for (AtomicLong l : consumedCounters) { - assertTrue("Even +/- 50% distribution on consumed:" + consumedCounters + ", outlier:" + l.get(), - l.longValue() < max && l.longValue() > min); - } - } - - private Destination destWithPrefetch(ActiveMQQueue destination) throws Exception { - return destination; - } - - private void produceMessages(int numMessages) throws JMSException { - int groupID=0; - for (int i = 0; i < numMessages; i++) { - if (i>0 && i%groupSize==0) { - groupID++; + final int id = i; + executorService.submit(new Runnable() { + int getBatchSize() { + return (id + 1) * batchSize; } - TextMessage msga = session.createTextMessage("hello " + i); - msga.setStringProperty("JMSXGroupID", "Group-"+groupID); - producer.send(msga); - } - } + + @Override + public void run() { + try { + Session connectionSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + int batchSize = getBatchSize(); + MessageConsumer messageConsumer = connectionSession.createConsumer(destWithPrefetch(destination)); + + Message message; + AtomicLong consumed = consumedCounters.get(id); + AtomicLong batches = batchCounters.get(id); + + LOG.info("Consumer: " + id + ", batchSize:" + batchSize + ", totalConsumed:" + totalConsumed.get() + ", consumed:" + consumed.get()); + + while (totalConsumed.get() < numMessages) { + + message = messageConsumer.receive(10000); + + if (message == null) { + LOG.info("Consumer: " + id + ", batchSize:" + batchSize + ", null message (totalConsumed:" + totalConsumed.get() + ") consumed:" + consumed.get()); + messageConsumer.close(); + + if (totalConsumed.get() == numMessages) { + break; + } + else { + batchSize = getBatchSize(); + messageConsumer = connectionSession.createConsumer(destWithPrefetch(destination)); + batches.incrementAndGet(); + continue; + } + } + + consumed.incrementAndGet(); + totalConsumed.incrementAndGet(); + + if (consumed.get() > 0 && consumed.intValue() % batchSize == 0) { + messageConsumer.close(); + batchSize = getBatchSize(); + messageConsumer = connectionSession.createConsumer(destWithPrefetch(destination)); + batches.incrementAndGet(); + } + } + } + catch (Exception e) { + e.printStackTrace(); + } + } + }); + TimeUnit.MILLISECONDS.sleep(200); + } + + TimeUnit.SECONDS.sleep(1); + produceMessages(numMessages); + + executorService.shutdown(); + assertTrue("threads done on time", executorService.awaitTermination(10, TimeUnit.MINUTES)); + + assertEquals("All consumed", numMessages, totalConsumed.intValue()); + + LOG.info("Distribution: " + consumedCounters); + LOG.info("Batches: " + batchCounters); + + double max = consumedCounters.get(0).longValue() * 1.5; + double min = consumedCounters.get(0).longValue() * 0.5; + + for (AtomicLong l : consumedCounters) { + assertTrue("Even +/- 50% distribution on consumed:" + consumedCounters + ", outlier:" + l.get(), l.longValue() < max && l.longValue() > min); + } + } + + private Destination destWithPrefetch(ActiveMQQueue destination) throws Exception { + return destination; + } + + private void produceMessages(int numMessages) throws JMSException { + int groupID = 0; + for (int i = 0; i < numMessages; i++) { + if (i > 0 && i % groupSize == 0) { + groupID++; + } + TextMessage msga = session.createTextMessage("hello " + i); + msga.setStringProperty("JMSXGroupID", "Group-" + groupID); + producer.send(msga); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageReroutingTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageReroutingTest.java index 8a83ee382a..86a3c11b64 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageReroutingTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageReroutingTest.java @@ -30,58 +30,55 @@ import org.slf4j.LoggerFactory; import org.springframework.core.io.ClassPathResource; public class MessageReroutingTest extends JmsMultipleBrokersTestSupport { - private static final transient Logger LOG = LoggerFactory.getLogger(MessageReroutingTest.class); - - - public Destination dest; - public static final int MESSAGE_COUNT = 50; - protected void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - - createBroker(new ClassPathResource("org/apache/activemq/usecases/rerouting-activemq-D.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/rerouting-activemq-C.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/rerouting-activemq-B.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/rerouting-activemq-A.xml")); + private static final transient Logger LOG = LoggerFactory.getLogger(MessageReroutingTest.class); - brokers.get("broker-A").broker.waitUntilStarted(); - } - - public void initCombos() { - addCombinationValues("dest", new Object[] {new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST")}); - } - - public void testMessageRerouting() throws Exception { - MessageConsumer consumer = createConsumer("broker-D", dest); - - MessageIdList received = getConsumerMessages("broker-D", consumer); - - Thread.sleep(2000); //wait for subs to propagate + public Destination dest; + public static final int MESSAGE_COUNT = 50; - // send/receive messages - sendMessages("broker-A", dest, MESSAGE_COUNT); - received.waitForMessagesToArrive(MESSAGE_COUNT); - LOG.info("received " + received.getMessageCount() + " messages"); - assertEquals(MESSAGE_COUNT, received.getMessageCount()); - - brokers.get("broker-B").broker.stop(); - brokers.get("broker-B").broker.waitUntilStopped(); - Thread.sleep(2000); - - // ensure send/receive still works - sendMessages("broker-A", dest, MESSAGE_COUNT); - received.waitForMessagesToArrive(MESSAGE_COUNT); - LOG.info("received " + received.getMessageCount() + " messages"); - assertTrue("Didn't receive any more messages " + received.getMessageCount(), received.getMessageCount() > MESSAGE_COUNT); - - - } + protected void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); + + createBroker(new ClassPathResource("org/apache/activemq/usecases/rerouting-activemq-D.xml")); + createBroker(new ClassPathResource("org/apache/activemq/usecases/rerouting-activemq-C.xml")); + createBroker(new ClassPathResource("org/apache/activemq/usecases/rerouting-activemq-B.xml")); + createBroker(new ClassPathResource("org/apache/activemq/usecases/rerouting-activemq-A.xml")); + + brokers.get("broker-A").broker.waitUntilStarted(); + } + + public void initCombos() { + addCombinationValues("dest", new Object[]{new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST")}); + } + + public void testMessageRerouting() throws Exception { + MessageConsumer consumer = createConsumer("broker-D", dest); + + MessageIdList received = getConsumerMessages("broker-D", consumer); + + Thread.sleep(2000); //wait for subs to propagate + + // send/receive messages + sendMessages("broker-A", dest, MESSAGE_COUNT); + received.waitForMessagesToArrive(MESSAGE_COUNT); + LOG.info("received " + received.getMessageCount() + " messages"); + assertEquals(MESSAGE_COUNT, received.getMessageCount()); + + brokers.get("broker-B").broker.stop(); + brokers.get("broker-B").broker.waitUntilStopped(); + Thread.sleep(2000); + + // ensure send/receive still works + sendMessages("broker-A", dest, MESSAGE_COUNT); + received.waitForMessagesToArrive(MESSAGE_COUNT); + LOG.info("received " + received.getMessageCount() + " messages"); + assertTrue("Didn't receive any more messages " + received.getMessageCount(), received.getMessageCount() > MESSAGE_COUNT); + + } + + public static Test suite() { + return suite(MessageReroutingTest.class); + } - - public static Test suite() { - return suite(MessageReroutingTest.class); - } - - } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MultiBrokersMultiClientsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MultiBrokersMultiClientsTest.java index df02d9e7ee..77cea3a9aa 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MultiBrokersMultiClientsTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MultiBrokersMultiClientsTest.java @@ -33,134 +33,134 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class MultiBrokersMultiClientsTest extends JmsMultipleBrokersTestSupport implements UncaughtExceptionHandler { - public static final int BROKER_COUNT = 6; // number of brokers to network - public static final int CONSUMER_COUNT = 25; // consumers per broker - public static final int PRODUCER_COUNT = 3; // producers per broker - public static final int MESSAGE_COUNT = 20; // messages per producer - private static final Logger LOG = LoggerFactory.getLogger(MultiBrokersMultiClientsTest.class); + public static final int BROKER_COUNT = 6; // number of brokers to network + public static final int CONSUMER_COUNT = 25; // consumers per broker + public static final int PRODUCER_COUNT = 3; // producers per broker + public static final int MESSAGE_COUNT = 20; // messages per producer - protected Map consumerMap; - final Map unhandeledExceptions = new HashMap(); + private static final Logger LOG = LoggerFactory.getLogger(MultiBrokersMultiClientsTest.class); - public void testTopicAllConnected() throws Exception { - bridgeAllBrokers(); - startAllBrokers(); - waitForBridgeFormation(); + protected Map consumerMap; + final Map unhandeledExceptions = new HashMap(); - // Setup topic destination - Destination dest = createDestination("TEST.FOO", true); + public void testTopicAllConnected() throws Exception { + bridgeAllBrokers(); + startAllBrokers(); + waitForBridgeFormation(); - CountDownLatch latch = new CountDownLatch(BROKER_COUNT * PRODUCER_COUNT * BROKER_COUNT * CONSUMER_COUNT * MESSAGE_COUNT); + // Setup topic destination + Destination dest = createDestination("TEST.FOO", true); - // Setup consumers - for (int i = 1; i <= BROKER_COUNT; i++) { - for (int j = 0; j < CONSUMER_COUNT; j++) { - consumerMap.put("Consumer:" + i + ":" + j, createConsumer("Broker" + i, dest, latch)); - } - } + CountDownLatch latch = new CountDownLatch(BROKER_COUNT * PRODUCER_COUNT * BROKER_COUNT * CONSUMER_COUNT * MESSAGE_COUNT); - // wait for consumers to get propagated - for (int i = 1; i <= BROKER_COUNT; i++) { - // all consumers on the remote brokers look like 1 consumer to the local broker. - assertConsumersConnect("Broker" + i, dest, (BROKER_COUNT-1)+CONSUMER_COUNT, 65000); - } + // Setup consumers + for (int i = 1; i <= BROKER_COUNT; i++) { + for (int j = 0; j < CONSUMER_COUNT; j++) { + consumerMap.put("Consumer:" + i + ":" + j, createConsumer("Broker" + i, dest, latch)); + } + } - // Send messages - for (int i = 1; i <= BROKER_COUNT; i++) { - for (int j = 0; j < PRODUCER_COUNT; j++) { - sendMessages("Broker" + i, dest, MESSAGE_COUNT); - } - } + // wait for consumers to get propagated + for (int i = 1; i <= BROKER_COUNT; i++) { + // all consumers on the remote brokers look like 1 consumer to the local broker. + assertConsumersConnect("Broker" + i, dest, (BROKER_COUNT - 1) + CONSUMER_COUNT, 65000); + } - assertTrue("Missing " + latch.getCount() + " messages", latch.await(45, TimeUnit.SECONDS)); + // Send messages + for (int i = 1; i <= BROKER_COUNT; i++) { + for (int j = 0; j < PRODUCER_COUNT; j++) { + sendMessages("Broker" + i, dest, MESSAGE_COUNT); + } + } - // Get message count - for (int i = 1; i <= BROKER_COUNT; i++) { - for (int j = 0; j < CONSUMER_COUNT; j++) { - MessageIdList msgs = getConsumerMessages("Broker" + i, (MessageConsumer)consumerMap.get("Consumer:" + i + ":" + j)); - assertEquals(BROKER_COUNT * PRODUCER_COUNT * MESSAGE_COUNT, msgs.getMessageCount()); - } - } + assertTrue("Missing " + latch.getCount() + " messages", latch.await(45, TimeUnit.SECONDS)); - assertNoUnhandeledExceptions(); - } + // Get message count + for (int i = 1; i <= BROKER_COUNT; i++) { + for (int j = 0; j < CONSUMER_COUNT; j++) { + MessageIdList msgs = getConsumerMessages("Broker" + i, (MessageConsumer) consumerMap.get("Consumer:" + i + ":" + j)); + assertEquals(BROKER_COUNT * PRODUCER_COUNT * MESSAGE_COUNT, msgs.getMessageCount()); + } + } - private void assertNoUnhandeledExceptions() { - for( Entry e: unhandeledExceptions.entrySet()) { - LOG.error("Thread:" + e.getKey() + " Had unexpected: " + e.getValue()); - } - assertTrue("There are no unhandelled exceptions, see: log for detail on: " + unhandeledExceptions, - unhandeledExceptions.isEmpty()); - } + assertNoUnhandeledExceptions(); + } - public void testQueueAllConnected() throws Exception { - bridgeAllBrokers(); - startAllBrokers(); - this.waitForBridgeFormation(); + private void assertNoUnhandeledExceptions() { + for (Entry e : unhandeledExceptions.entrySet()) { + LOG.error("Thread:" + e.getKey() + " Had unexpected: " + e.getValue()); + } + assertTrue("There are no unhandelled exceptions, see: log for detail on: " + unhandeledExceptions, unhandeledExceptions.isEmpty()); + } - // Setup topic destination - Destination dest = createDestination("TEST.FOO", false); + public void testQueueAllConnected() throws Exception { + bridgeAllBrokers(); + startAllBrokers(); + this.waitForBridgeFormation(); - CountDownLatch latch = new CountDownLatch(BROKER_COUNT * PRODUCER_COUNT * MESSAGE_COUNT); + // Setup topic destination + Destination dest = createDestination("TEST.FOO", false); - // Setup consumers - for (int i = 1; i <= BROKER_COUNT; i++) { - for (int j = 0; j < CONSUMER_COUNT; j++) { - consumerMap.put("Consumer:" + i + ":" + j, createConsumer("Broker" + i, dest, latch)); - } - } + CountDownLatch latch = new CountDownLatch(BROKER_COUNT * PRODUCER_COUNT * MESSAGE_COUNT); - // wait for consumers to get propagated - for (int i = 1; i <= BROKER_COUNT; i++) { - // all consumers on the remote brokers look like 1 consumer to the local broker. - assertConsumersConnect("Broker" + i, dest, (BROKER_COUNT-1)+CONSUMER_COUNT, 65000); - } + // Setup consumers + for (int i = 1; i <= BROKER_COUNT; i++) { + for (int j = 0; j < CONSUMER_COUNT; j++) { + consumerMap.put("Consumer:" + i + ":" + j, createConsumer("Broker" + i, dest, latch)); + } + } - // Send messages - for (int i = 1; i <= BROKER_COUNT; i++) { - for (int j = 0; j < PRODUCER_COUNT; j++) { - sendMessages("Broker" + i, dest, MESSAGE_COUNT); - } - } + // wait for consumers to get propagated + for (int i = 1; i <= BROKER_COUNT; i++) { + // all consumers on the remote brokers look like 1 consumer to the local broker. + assertConsumersConnect("Broker" + i, dest, (BROKER_COUNT - 1) + CONSUMER_COUNT, 65000); + } - // Wait for messages to be delivered - assertTrue("Missing " + latch.getCount() + " messages", latch.await(45, TimeUnit.SECONDS)); + // Send messages + for (int i = 1; i <= BROKER_COUNT; i++) { + for (int j = 0; j < PRODUCER_COUNT; j++) { + sendMessages("Broker" + i, dest, MESSAGE_COUNT); + } + } - // Get message count - int totalMsg = 0; - for (int i = 1; i <= BROKER_COUNT; i++) { - for (int j = 0; j < CONSUMER_COUNT; j++) { - MessageIdList msgs = getConsumerMessages("Broker" + i, consumerMap.get("Consumer:" + i + ":" + j)); - totalMsg += msgs.getMessageCount(); - } - } - assertEquals(BROKER_COUNT * PRODUCER_COUNT * MESSAGE_COUNT, totalMsg); - - assertNoUnhandeledExceptions(); - } + // Wait for messages to be delivered + assertTrue("Missing " + latch.getCount() + " messages", latch.await(45, TimeUnit.SECONDS)); - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); + // Get message count + int totalMsg = 0; + for (int i = 1; i <= BROKER_COUNT; i++) { + for (int j = 0; j < CONSUMER_COUNT; j++) { + MessageIdList msgs = getConsumerMessages("Broker" + i, consumerMap.get("Consumer:" + i + ":" + j)); + totalMsg += msgs.getMessageCount(); + } + } + assertEquals(BROKER_COUNT * PRODUCER_COUNT * MESSAGE_COUNT, totalMsg); - unhandeledExceptions.clear(); - Thread.setDefaultUncaughtExceptionHandler(this); - - // Setup n brokers - for (int i = 1; i <= BROKER_COUNT; i++) { - createBroker(new URI("broker:()/Broker" + i + "?persistent=false&useJmx=false")); - } + assertNoUnhandeledExceptions(); + } - consumerMap = new HashMap(); - } + public void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); - public void uncaughtException(Thread t, Throwable e) { - synchronized(unhandeledExceptions) { - unhandeledExceptions.put(t,e); - } - } + unhandeledExceptions.clear(); + Thread.setDefaultUncaughtExceptionHandler(this); + + // Setup n brokers + for (int i = 1; i <= BROKER_COUNT; i++) { + createBroker(new URI("broker:()/Broker" + i + "?persistent=false&useJmx=false")); + } + + consumerMap = new HashMap(); + } + + public void uncaughtException(Thread t, Throwable e) { + synchronized (unhandeledExceptions) { + unhandeledExceptions.put(t, e); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MultiBrokersMultiClientsUsingTcpTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MultiBrokersMultiClientsUsingTcpTest.java index 23cf042107..846e1b0ef5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MultiBrokersMultiClientsUsingTcpTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MultiBrokersMultiClientsUsingTcpTest.java @@ -28,59 +28,62 @@ import org.apache.activemq.network.NetworkBridgeConfiguration; import org.apache.activemq.transport.TransportFactory; /** - * + * */ public class MultiBrokersMultiClientsUsingTcpTest extends MultiBrokersMultiClientsTest { - protected List bridges; - protected void bridgeAllBrokers(String groupName) throws Exception { - for (int i = 1; i <= BROKER_COUNT; i++) { - for (int j = 1; j <= BROKER_COUNT; j++) { - if (i != j) { - bridgeBrokers("Broker" + i, "Broker" + j); - } + protected List bridges; + + protected void bridgeAllBrokers(String groupName) throws Exception { + for (int i = 1; i <= BROKER_COUNT; i++) { + for (int j = 1; j <= BROKER_COUNT; j++) { + if (i != j) { + bridgeBrokers("Broker" + i, "Broker" + j); } - } + } + } - maxSetupTime = 5000; - } + maxSetupTime = 5000; + } - protected void bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker) throws Exception { - List remoteTransports = remoteBroker.getTransportConnectors(); - List localTransports = localBroker.getTransportConnectors(); + protected void bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker) throws Exception { + List remoteTransports = remoteBroker.getTransportConnectors(); + List localTransports = localBroker.getTransportConnectors(); - URI remoteURI; - URI localURI; - if (!remoteTransports.isEmpty() && !localTransports.isEmpty()) { - remoteURI = remoteTransports.get(0).getConnectUri(); - localURI = localTransports.get(0).getConnectUri(); + URI remoteURI; + URI localURI; + if (!remoteTransports.isEmpty() && !localTransports.isEmpty()) { + remoteURI = remoteTransports.get(0).getConnectUri(); + localURI = localTransports.get(0).getConnectUri(); - // Ensure that we are connecting using tcp - if (remoteURI.toString().startsWith("tcp:") && localURI.toString().startsWith("tcp:")) { - NetworkBridgeConfiguration config = new NetworkBridgeConfiguration(); - config.setBrokerName(localBroker.getBrokerName()); - DemandForwardingBridge bridge = new DemandForwardingBridge(config, TransportFactory.connect(localURI), TransportFactory.connect(remoteURI)); - bridge.setBrokerService(localBroker); - bridges.add(bridge); + // Ensure that we are connecting using tcp + if (remoteURI.toString().startsWith("tcp:") && localURI.toString().startsWith("tcp:")) { + NetworkBridgeConfiguration config = new NetworkBridgeConfiguration(); + config.setBrokerName(localBroker.getBrokerName()); + DemandForwardingBridge bridge = new DemandForwardingBridge(config, TransportFactory.connect(localURI), TransportFactory.connect(remoteURI)); + bridge.setBrokerService(localBroker); + bridges.add(bridge); - bridge.start(); - } else { - throw new Exception("Remote broker or local broker is not using tcp connectors"); - } - } else { - throw new Exception("Remote broker or local broker has no registered connectors."); - } - } + bridge.start(); + } + else { + throw new Exception("Remote broker or local broker is not using tcp connectors"); + } + } + else { + throw new Exception("Remote broker or local broker has no registered connectors."); + } + } - public void setUp() throws Exception { - super.setUp(); + public void setUp() throws Exception { + super.setUp(); - // Assign a tcp connector to each broker - int j = 0; - for (Iterator i = brokers.values().iterator(); i.hasNext();) { - i.next().broker.addConnector("tcp://localhost:" + (61616 + j++)); - } + // Assign a tcp connector to each broker + int j = 0; + for (Iterator i = brokers.values().iterator(); i.hasNext(); ) { + i.next().broker.addConnector("tcp://localhost:" + (61616 + j++)); + } - bridges = new ArrayList(); - } + bridges = new ArrayList(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MulticastDiscoveryOnFaultyNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MulticastDiscoveryOnFaultyNetworkTest.java index 6b61438102..0ba292eb61 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MulticastDiscoveryOnFaultyNetworkTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MulticastDiscoveryOnFaultyNetworkTest.java @@ -32,99 +32,100 @@ import org.apache.activemq.network.DiscoveryNetworkConnector; import org.apache.activemq.network.NetworkConnector; import org.apache.activemq.util.MessageIdList; - public class MulticastDiscoveryOnFaultyNetworkTest extends JmsMultipleBrokersTestSupport { - protected static final int MESSAGE_COUNT = 200; - private static final String HUB = "HubBroker"; - private static final String SPOKE = "SpokeBroker"; - public boolean useDuplexNetworkBridge = true; - public boolean useStaticDiscovery = false; - public void initCombosForTestSendOnAFaultyTransport() { - addCombinationValues( "useDuplexNetworkBridge", new Object[]{ Boolean.TRUE , Boolean.FALSE } ); - addCombinationValues( "useStaticDiscovery", new Object[]{ Boolean.TRUE , Boolean.FALSE } ); - } - - public void testSendOnAFaultyTransport() throws Exception { - bridgeBrokers(SPOKE, HUB); + protected static final int MESSAGE_COUNT = 200; + private static final String HUB = "HubBroker"; + private static final String SPOKE = "SpokeBroker"; + public boolean useDuplexNetworkBridge = true; + public boolean useStaticDiscovery = false; - startAllBrokers(); + public void initCombosForTestSendOnAFaultyTransport() { + addCombinationValues("useDuplexNetworkBridge", new Object[]{Boolean.TRUE, Boolean.FALSE}); + addCombinationValues("useStaticDiscovery", new Object[]{Boolean.TRUE, Boolean.FALSE}); + } - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - MessageConsumer client = createConsumer(HUB, dest); - - // allow subscription information to flow back to Spoke - sleep(600); - - // Send messages - sendMessages(SPOKE, dest, MESSAGE_COUNT); + public void testSendOnAFaultyTransport() throws Exception { + bridgeBrokers(SPOKE, HUB); - MessageIdList msgs = getConsumerMessages(HUB, client); - msgs.setMaximumDuration(200000L); - msgs.waitForMessagesToArrive(MESSAGE_COUNT); + startAllBrokers(); - assertTrue("At least message " + MESSAGE_COUNT + - " must be received, duplicates are expected, count=" + msgs.getMessageCount(), - MESSAGE_COUNT <= msgs.getMessageCount()); - } + // Setup destination + Destination dest = createDestination("TEST.FOO", false); - - @Override - protected void startAllBrokers() throws Exception { - // Ensure HUB is started first so bridge will be active from the get go - BrokerItem brokerItem = brokers.get(HUB); - brokerItem.broker.start(); - brokerItem = brokers.get(SPOKE); - brokerItem.broker.start(); - } + // Setup consumers + MessageConsumer client = createConsumer(HUB, dest); - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - final String options = "?persistent=false&useJmx=false&deleteAllMessagesOnStartup=true"; - createBroker(new URI("broker:(tcpfaulty://localhost:61617)/" + HUB + options)); - createBroker(new URI("broker:(tcpfaulty://localhost:61616)/" + SPOKE + options)); - } - - public static Test suite() { - return suite(MulticastDiscoveryOnFaultyNetworkTest.class); - } - - @Override - protected void onSend(int i, TextMessage msg) { - sleep(50); - } + // allow subscription information to flow back to Spoke + sleep(600); - private void sleep(int milliSecondTime) { - try { - Thread.sleep(milliSecondTime); - } catch (InterruptedException igonred) { - } - } + // Send messages + sendMessages(SPOKE, dest, MESSAGE_COUNT); + MessageIdList msgs = getConsumerMessages(HUB, client); + msgs.setMaximumDuration(200000L); + msgs.waitForMessagesToArrive(MESSAGE_COUNT); - @Override - protected NetworkConnector bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker, boolean dynamicOnly, int networkTTL, boolean conduit, boolean failover) throws Exception { - String networkDisoveryUrlString = useStaticDiscovery ? - "static:(" + remoteBroker.getTransportConnectors().get(0).getPublishableConnectString() + ")?useExponentialBackOff=false" : - "multicast://default?group=TESTERIC&useLocalHost=false"; + assertTrue("At least message " + MESSAGE_COUNT + + " must be received, duplicates are expected, count=" + msgs.getMessageCount(), MESSAGE_COUNT <= msgs.getMessageCount()); + } - DiscoveryNetworkConnector connector = new DiscoveryNetworkConnector(new URI(networkDisoveryUrlString)); - connector.setDynamicOnly(dynamicOnly); - connector.setNetworkTTL(networkTTL); - connector.setDuplex(useDuplexNetworkBridge); - maxSetupTime = 2000; - if (!useStaticDiscovery) { - List transportConnectors = remoteBroker.getTransportConnectors(); - if (!transportConnectors.isEmpty()) { - TransportConnector mCastTrpConnector = ((TransportConnector)transportConnectors.get(0)); - mCastTrpConnector.setDiscoveryUri(new URI("multicast://default?group=TESTERIC")); - } - } - localBroker.addNetworkConnector(connector); - return connector; - } + @Override + protected void startAllBrokers() throws Exception { + // Ensure HUB is started first so bridge will be active from the get go + BrokerItem brokerItem = brokers.get(HUB); + brokerItem.broker.start(); + brokerItem = brokers.get(SPOKE); + brokerItem.broker.start(); + } + + public void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); + final String options = "?persistent=false&useJmx=false&deleteAllMessagesOnStartup=true"; + createBroker(new URI("broker:(tcpfaulty://localhost:61617)/" + HUB + options)); + createBroker(new URI("broker:(tcpfaulty://localhost:61616)/" + SPOKE + options)); + } + + public static Test suite() { + return suite(MulticastDiscoveryOnFaultyNetworkTest.class); + } + + @Override + protected void onSend(int i, TextMessage msg) { + sleep(50); + } + + private void sleep(int milliSecondTime) { + try { + Thread.sleep(milliSecondTime); + } + catch (InterruptedException igonred) { + } + } + + @Override + protected NetworkConnector bridgeBrokers(BrokerService localBroker, + BrokerService remoteBroker, + boolean dynamicOnly, + int networkTTL, + boolean conduit, + boolean failover) throws Exception { + String networkDisoveryUrlString = useStaticDiscovery ? "static:(" + remoteBroker.getTransportConnectors().get(0).getPublishableConnectString() + ")?useExponentialBackOff=false" : "multicast://default?group=TESTERIC&useLocalHost=false"; + + DiscoveryNetworkConnector connector = new DiscoveryNetworkConnector(new URI(networkDisoveryUrlString)); + connector.setDynamicOnly(dynamicOnly); + connector.setNetworkTTL(networkTTL); + connector.setDuplex(useDuplexNetworkBridge); + maxSetupTime = 2000; + if (!useStaticDiscovery) { + List transportConnectors = remoteBroker.getTransportConnectors(); + if (!transportConnectors.isEmpty()) { + TransportConnector mCastTrpConnector = ((TransportConnector) transportConnectors.get(0)); + mCastTrpConnector.setDiscoveryUri(new URI("multicast://default?group=TESTERIC")); + } + } + localBroker.addNetworkConnector(connector); + return connector; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MyObject.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MyObject.java index d8bc5dd6c4..cdcecc062f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MyObject.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MyObject.java @@ -23,46 +23,46 @@ import java.util.concurrent.atomic.AtomicInteger; public class MyObject implements Serializable { - private static final long serialVersionUID = -2505777188753549398L; + private static final long serialVersionUID = -2505777188753549398L; - private String message; - private final AtomicInteger writeObjectCalled = new AtomicInteger(0); - private final AtomicInteger readObjectCalled = new AtomicInteger(0); - private final AtomicInteger readObjectNoDataCalled = new AtomicInteger(0); + private String message; + private final AtomicInteger writeObjectCalled = new AtomicInteger(0); + private final AtomicInteger readObjectCalled = new AtomicInteger(0); + private final AtomicInteger readObjectNoDataCalled = new AtomicInteger(0); - public MyObject(String message) { - this.setMessage(message); - } + public MyObject(String message) { + this.setMessage(message); + } - public void setMessage(String message) { - this.message = message; - } + public void setMessage(String message) { + this.message = message; + } - public String getMessage() { - return message; - } + public String getMessage() { + return message; + } - private void writeObject(java.io.ObjectOutputStream out) throws IOException { - writeObjectCalled.incrementAndGet(); - out.defaultWriteObject(); - } + private void writeObject(java.io.ObjectOutputStream out) throws IOException { + writeObjectCalled.incrementAndGet(); + out.defaultWriteObject(); + } - private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - readObjectCalled.incrementAndGet(); - } + private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { + in.defaultReadObject(); + readObjectCalled.incrementAndGet(); + } - public int getWriteObjectCalled() { - return writeObjectCalled.get(); - } + public int getWriteObjectCalled() { + return writeObjectCalled.get(); + } - public int getReadObjectCalled() { - return readObjectCalled.get(); - } + public int getReadObjectCalled() { + return readObjectCalled.get(); + } - public int getReadObjectNoDataCalled() { - return readObjectNoDataCalled.get(); - } + public int getReadObjectNoDataCalled() { + return readObjectNoDataCalled.get(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NetworkAsyncStartTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NetworkAsyncStartTest.java index 8f74117c2b..c348549519 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NetworkAsyncStartTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NetworkAsyncStartTest.java @@ -19,6 +19,7 @@ package org.apache.activemq.usecases; import java.net.URI; import java.util.concurrent.Executor; import java.util.concurrent.Executors; + import org.apache.activemq.JmsMultipleBrokersTestSupport; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.network.DiscoveryNetworkConnector; @@ -28,93 +29,95 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NetworkAsyncStartTest extends JmsMultipleBrokersTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(NetworkAsyncStartTest.class); - private String brokerBUri = "tcp://localhost:61617"; - private String brokerCUri = "tcp://localhost:61618"; - int bridgeCount=0; + private static final Logger LOG = LoggerFactory.getLogger(NetworkAsyncStartTest.class); - public void testAsyncNetworkStartup() throws Exception { + private String brokerBUri = "tcp://localhost:61617"; + private String brokerCUri = "tcp://localhost:61618"; + int bridgeCount = 0; - BrokerService brokerA = brokers.get("BrokerA").broker; - bridgeBroker(brokerA, brokerBUri); - bridgeBroker(brokerA, brokerCUri); + public void testAsyncNetworkStartup() throws Exception { - LOG.info("starting A, no blocking on failed network connectors"); - brokerA.start(); + BrokerService brokerA = brokers.get("BrokerA").broker; + bridgeBroker(brokerA, brokerBUri); + bridgeBroker(brokerA, brokerCUri); - LOG.info("starting C transport connector"); - BrokerService brokerC = brokers.get("BrokerC").broker; - brokerC.addConnector(brokerCUri); - brokerC.start(); + LOG.info("starting A, no blocking on failed network connectors"); + brokerA.start(); - assertTrue("got bridge to C", waitForBridgeFormation(brokerA, 1, 1)); - LOG.info("Got bridge A->C"); + LOG.info("starting C transport connector"); + BrokerService brokerC = brokers.get("BrokerC").broker; + brokerC.addConnector(brokerCUri); + brokerC.start(); - LOG.info("starting B transport connector"); - BrokerService brokerB = brokers.get("BrokerB").broker; - brokerB.addConnector(brokerBUri); - brokerB.start(); + assertTrue("got bridge to C", waitForBridgeFormation(brokerA, 1, 1)); + LOG.info("Got bridge A->C"); - assertTrue("got bridge to B", waitForBridgeFormation(brokerA, 1, 0)); - assertTrue("got bridge to B&C", waitForBridgeFormation(brokerA, 1, 1)); - } + LOG.info("starting B transport connector"); + BrokerService brokerB = brokers.get("BrokerB").broker; + brokerB.addConnector(brokerBUri); + brokerB.start(); - public void testAsyncNetworkStartupWithSlowConnectionCreation() throws Exception { + assertTrue("got bridge to B", waitForBridgeFormation(brokerA, 1, 0)); + assertTrue("got bridge to B&C", waitForBridgeFormation(brokerA, 1, 1)); + } - final BrokerService brokerA = brokers.get("BrokerA").broker; + public void testAsyncNetworkStartupWithSlowConnectionCreation() throws Exception { - SocketProxy proxyToB = new SocketProxy(); - // don't accept any connections so limited to one connection with backlog - proxyToB.setPauseAtStart(true); - proxyToB.setAcceptBacklog(1); - proxyToB.setTarget(new URI(brokerBUri)); - proxyToB.open(); - bridgeBroker(brokerA, proxyToB.getUrl().toString()); - bridgeBroker(brokerA, proxyToB.getUrl().toString()); - bridgeBroker(brokerA, proxyToB.getUrl().toString()); - bridgeBroker(brokerA, proxyToB.getUrl().toString()); - bridgeBroker(brokerA, proxyToB.getUrl().toString()); - bridgeBroker(brokerA, proxyToB.getUrl().toString()); - bridgeBroker(brokerA, proxyToB.getUrl().toString()); - bridgeBroker(brokerA, brokerCUri); + final BrokerService brokerA = brokers.get("BrokerA").broker; - Executor e = Executors.newCachedThreadPool(); - e.execute(new Runnable() { - public void run() { - LOG.info("starting A"); - try { - brokerA.setNetworkConnectorStartAsync(true); - brokerA.start(); - } catch (Exception e) { - LOG.error("start failed", e); - } + SocketProxy proxyToB = new SocketProxy(); + // don't accept any connections so limited to one connection with backlog + proxyToB.setPauseAtStart(true); + proxyToB.setAcceptBacklog(1); + proxyToB.setTarget(new URI(brokerBUri)); + proxyToB.open(); + bridgeBroker(brokerA, proxyToB.getUrl().toString()); + bridgeBroker(brokerA, proxyToB.getUrl().toString()); + bridgeBroker(brokerA, proxyToB.getUrl().toString()); + bridgeBroker(brokerA, proxyToB.getUrl().toString()); + bridgeBroker(brokerA, proxyToB.getUrl().toString()); + bridgeBroker(brokerA, proxyToB.getUrl().toString()); + bridgeBroker(brokerA, proxyToB.getUrl().toString()); + bridgeBroker(brokerA, brokerCUri); + + Executor e = Executors.newCachedThreadPool(); + e.execute(new Runnable() { + public void run() { + LOG.info("starting A"); + try { + brokerA.setNetworkConnectorStartAsync(true); + brokerA.start(); } - }); + catch (Exception e) { + LOG.error("start failed", e); + } + } + }); - LOG.info("starting transport connector on C"); - BrokerService brokerC = brokers.get("BrokerC").broker; - brokerC.addConnector(brokerCUri); - brokerC.start(); + LOG.info("starting transport connector on C"); + BrokerService brokerC = brokers.get("BrokerC").broker; + brokerC.addConnector(brokerCUri); + brokerC.start(); - final long maxWaitMillis = 20*1000; - assertTrue("got bridge to C in 10 seconds", waitForBridgeFormation(brokerA, 1, 7, maxWaitMillis)); - } + final long maxWaitMillis = 20 * 1000; + assertTrue("got bridge to C in 10 seconds", waitForBridgeFormation(brokerA, 1, 7, maxWaitMillis)); + } - private void bridgeBroker(BrokerService localBroker, String remoteURI) throws Exception { - String uri = "static:(" + remoteURI + ")"; - NetworkConnector connector = new DiscoveryNetworkConnector(new URI(uri)); - connector.setName("bridge-" + bridgeCount++); - localBroker.addNetworkConnector(connector); - } + private void bridgeBroker(BrokerService localBroker, String remoteURI) throws Exception { + String uri = "static:(" + remoteURI + ")"; + NetworkConnector connector = new DiscoveryNetworkConnector(new URI(uri)); + connector.setName("bridge-" + bridgeCount++); + localBroker.addNetworkConnector(connector); + } - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - // initially with no tcp transport connector - createBroker(new URI("broker:()BrokerA?persistent=false&useJmx=false")); - createBroker(new URI("broker:()BrokerB?persistent=false&useJmx=false")); - createBroker(new URI("broker:()BrokerC?persistent=false&useJmx=false")); - } + @Override + public void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); + // initially with no tcp transport connector + createBroker(new URI("broker:()BrokerA?persistent=false&useJmx=false")); + createBroker(new URI("broker:()BrokerB?persistent=false&useJmx=false")); + createBroker(new URI("broker:()BrokerC?persistent=false&useJmx=false")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NetworkBridgeProducerFlowControlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NetworkBridgeProducerFlowControlTest.java index 3a8388c798..a3705f90e5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NetworkBridgeProducerFlowControlTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NetworkBridgeProducerFlowControlTest.java @@ -23,7 +23,9 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import javax.jms.MessageConsumer; + import junit.framework.Test; + import org.apache.activemq.JmsMultipleBrokersTestSupport; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.region.policy.PolicyEntry; @@ -93,295 +95,258 @@ import org.junit.Assert; * * @author schow */ -public class NetworkBridgeProducerFlowControlTest extends - JmsMultipleBrokersTestSupport { +public class NetworkBridgeProducerFlowControlTest extends JmsMultipleBrokersTestSupport { - // Protect against hanging test. - private static final long MAX_TEST_TIME = 120000; + // Protect against hanging test. + private static final long MAX_TEST_TIME = 120000; - private static final Log LOG = LogFactory - .getLog(NetworkBridgeProducerFlowControlTest.class); + private static final Log LOG = LogFactory.getLog(NetworkBridgeProducerFlowControlTest.class); - // Combo flag set to true/false by the test framework. - public boolean persistentTestMessages; - public boolean networkIsAlwaysSendSync; + // Combo flag set to true/false by the test framework. + public boolean persistentTestMessages; + public boolean networkIsAlwaysSendSync; - private Vector exceptions = new Vector(); + private Vector exceptions = new Vector(); - public static Test suite() { - return suite(NetworkBridgeProducerFlowControlTest.class); - } + public static Test suite() { + return suite(NetworkBridgeProducerFlowControlTest.class); + } - public void initCombosForTestFastAndSlowRemoteConsumers() { - addCombinationValues("persistentTestMessages", new Object[]{ - new Boolean(true), new Boolean(false)}); - addCombinationValues("networkIsAlwaysSendSync", new Object[]{ - new Boolean(true), new Boolean(false)}); - } + public void initCombosForTestFastAndSlowRemoteConsumers() { + addCombinationValues("persistentTestMessages", new Object[]{new Boolean(true), new Boolean(false)}); + addCombinationValues("networkIsAlwaysSendSync", new Object[]{new Boolean(true), new Boolean(false)}); + } - @Override - protected void setUp() throws Exception { - setAutoFail(true); - setMaxTestTime(MAX_TEST_TIME); - super.setUp(); - } + @Override + protected void setUp() throws Exception { + setAutoFail(true); + setMaxTestTime(MAX_TEST_TIME); + super.setUp(); + } - /** - * This test is parameterized by {@link #persistentTestMessages}, which - * determines whether the producer on broker0 sends persistent or - * non-persistent messages, and {@link #networkIsAlwaysSendSync}, which - * determines how the bridge will forward both persistent and non-persistent - * messages to broker1. - * - * @see #initCombosForTestFastAndSlowRemoteConsumers() - */ - public void testFastAndSlowRemoteConsumers() throws Exception { - final int NUM_MESSAGES = 100; - final long TEST_MESSAGE_SIZE = 1024; - final long SLOW_CONSUMER_DELAY_MILLIS = 100; + /** + * This test is parameterized by {@link #persistentTestMessages}, which + * determines whether the producer on broker0 sends persistent or + * non-persistent messages, and {@link #networkIsAlwaysSendSync}, which + * determines how the bridge will forward both persistent and non-persistent + * messages to broker1. + * + * @see #initCombosForTestFastAndSlowRemoteConsumers() + */ + public void testFastAndSlowRemoteConsumers() throws Exception { + final int NUM_MESSAGES = 100; + final long TEST_MESSAGE_SIZE = 1024; + final long SLOW_CONSUMER_DELAY_MILLIS = 100; - // Consumer prefetch is disabled for broker1's consumers. - final ActiveMQQueue SLOW_SHARED_QUEUE = new ActiveMQQueue( - NetworkBridgeProducerFlowControlTest.class.getSimpleName() - + ".slow.shared?consumer.prefetchSize=1"); + // Consumer prefetch is disabled for broker1's consumers. + final ActiveMQQueue SLOW_SHARED_QUEUE = new ActiveMQQueue(NetworkBridgeProducerFlowControlTest.class.getSimpleName() + ".slow.shared?consumer.prefetchSize=1"); - final ActiveMQQueue FAST_SHARED_QUEUE = new ActiveMQQueue( - NetworkBridgeProducerFlowControlTest.class.getSimpleName() - + ".fast.shared?consumer.prefetchSize=1"); + final ActiveMQQueue FAST_SHARED_QUEUE = new ActiveMQQueue(NetworkBridgeProducerFlowControlTest.class.getSimpleName() + ".fast.shared?consumer.prefetchSize=1"); - // Start a local and a remote broker. - createBroker(new URI("broker:(tcp://localhost:0" - + ")?brokerName=broker0&persistent=false&useJmx=true")); - BrokerService remoteBroker = createBroker(new URI( - "broker:(tcp://localhost:0" - + ")?brokerName=broker1&persistent=false&useJmx=true")); + // Start a local and a remote broker. + createBroker(new URI("broker:(tcp://localhost:0" + ")?brokerName=broker0&persistent=false&useJmx=true")); + BrokerService remoteBroker = createBroker(new URI("broker:(tcp://localhost:0" + ")?brokerName=broker1&persistent=false&useJmx=true")); - // Set a policy on the remote broker that limits the maximum size of the - // slow shared queue. - PolicyEntry policyEntry = new PolicyEntry(); - policyEntry.setMemoryLimit(5 * TEST_MESSAGE_SIZE); - PolicyMap policyMap = new PolicyMap(); - policyMap.put(SLOW_SHARED_QUEUE, policyEntry); - remoteBroker.setDestinationPolicy(policyMap); + // Set a policy on the remote broker that limits the maximum size of the + // slow shared queue. + PolicyEntry policyEntry = new PolicyEntry(); + policyEntry.setMemoryLimit(5 * TEST_MESSAGE_SIZE); + PolicyMap policyMap = new PolicyMap(); + policyMap.put(SLOW_SHARED_QUEUE, policyEntry); + remoteBroker.setDestinationPolicy(policyMap); - // Create an outbound bridge from the local broker to the remote broker. - // The bridge is configured with the remoteDispatchType enhancement. - NetworkConnector nc = bridgeBrokers("broker0", "broker1"); - nc.setAlwaysSyncSend(networkIsAlwaysSendSync); - nc.setPrefetchSize(1); + // Create an outbound bridge from the local broker to the remote broker. + // The bridge is configured with the remoteDispatchType enhancement. + NetworkConnector nc = bridgeBrokers("broker0", "broker1"); + nc.setAlwaysSyncSend(networkIsAlwaysSendSync); + nc.setPrefetchSize(1); - startAllBrokers(); - waitForBridgeFormation(); + startAllBrokers(); + waitForBridgeFormation(); - // Send the test messages to the local broker's shared queues. The - // messages are either persistent or non-persistent to demonstrate the - // difference between synchronous and asynchronous dispatch. - persistentDelivery = persistentTestMessages; - sendMessages("broker0", FAST_SHARED_QUEUE, NUM_MESSAGES); - sendMessages("broker0", SLOW_SHARED_QUEUE, NUM_MESSAGES); + // Send the test messages to the local broker's shared queues. The + // messages are either persistent or non-persistent to demonstrate the + // difference between synchronous and asynchronous dispatch. + persistentDelivery = persistentTestMessages; + sendMessages("broker0", FAST_SHARED_QUEUE, NUM_MESSAGES); + sendMessages("broker0", SLOW_SHARED_QUEUE, NUM_MESSAGES); - // Start two asynchronous consumers on the remote broker, one for each - // of the two shared queues, and keep track of how long it takes for - // each of the consumers to receive all the messages. - final CountDownLatch fastConsumerLatch = new CountDownLatch( - NUM_MESSAGES); - final CountDownLatch slowConsumerLatch = new CountDownLatch( - NUM_MESSAGES); + // Start two asynchronous consumers on the remote broker, one for each + // of the two shared queues, and keep track of how long it takes for + // each of the consumers to receive all the messages. + final CountDownLatch fastConsumerLatch = new CountDownLatch(NUM_MESSAGES); + final CountDownLatch slowConsumerLatch = new CountDownLatch(NUM_MESSAGES); - final long startTimeMillis = System.currentTimeMillis(); - final AtomicLong fastConsumerTime = new AtomicLong(); - final AtomicLong slowConsumerTime = new AtomicLong(); + final long startTimeMillis = System.currentTimeMillis(); + final AtomicLong fastConsumerTime = new AtomicLong(); + final AtomicLong slowConsumerTime = new AtomicLong(); - Thread fastWaitThread = new Thread() { - @Override - public void run() { - try { - fastConsumerLatch.await(); - fastConsumerTime.set(System.currentTimeMillis() - - startTimeMillis); - } catch (InterruptedException ex) { - exceptions.add(ex); - Assert.fail(ex.getMessage()); - } + Thread fastWaitThread = new Thread() { + @Override + public void run() { + try { + fastConsumerLatch.await(); + fastConsumerTime.set(System.currentTimeMillis() - startTimeMillis); } - }; - - Thread slowWaitThread = new Thread() { - @Override - public void run() { - try { - slowConsumerLatch.await(); - slowConsumerTime.set(System.currentTimeMillis() - - startTimeMillis); - } catch (InterruptedException ex) { - exceptions.add(ex); - Assert.fail(ex.getMessage()); - } + catch (InterruptedException ex) { + exceptions.add(ex); + Assert.fail(ex.getMessage()); } - }; + } + }; - fastWaitThread.start(); - slowWaitThread.start(); - - createConsumer("broker1", FAST_SHARED_QUEUE, fastConsumerLatch); - MessageConsumer slowConsumer = createConsumer("broker1", - SLOW_SHARED_QUEUE, slowConsumerLatch); - MessageIdList messageIdList = brokers.get("broker1").consumers - .get(slowConsumer); - messageIdList.setProcessingDelay(SLOW_CONSUMER_DELAY_MILLIS); - - fastWaitThread.join(); - slowWaitThread.join(); - - assertTrue("no exceptions on the wait threads:" + exceptions, - exceptions.isEmpty()); - - LOG.info("Fast consumer duration (ms): " + fastConsumerTime.get()); - LOG.info("Slow consumer duration (ms): " + slowConsumerTime.get()); - - // Verify the behaviour as described in the description of this class. - if (networkIsAlwaysSendSync) { - Assert - .assertTrue(fastConsumerTime.get() < slowConsumerTime.get() / 10); - - } else { - Assert.assertEquals(persistentTestMessages, - fastConsumerTime.get() < slowConsumerTime.get() / 10); - } - } - - public void testSendFailIfNoSpaceDoesNotBlockQueueNetwork() throws Exception { - // Consumer prefetch is disabled for broker1's consumers. - final ActiveMQQueue SLOW_SHARED_QUEUE = new ActiveMQQueue( - NetworkBridgeProducerFlowControlTest.class.getSimpleName() - + ".slow.shared?consumer.prefetchSize=1"); - - final ActiveMQQueue FAST_SHARED_QUEUE = new ActiveMQQueue( - NetworkBridgeProducerFlowControlTest.class.getSimpleName() - + ".fast.shared?consumer.prefetchSize=1"); - - doTestSendFailIfNoSpaceDoesNotBlockNetwork( - SLOW_SHARED_QUEUE, - FAST_SHARED_QUEUE); - } - - public void testSendFailIfNoSpaceDoesNotBlockTopicNetwork() throws Exception { - // Consumer prefetch is disabled for broker1's consumers. - final ActiveMQTopic SLOW_SHARED_TOPIC = new ActiveMQTopic( - NetworkBridgeProducerFlowControlTest.class.getSimpleName() - + ".slow.shared?consumer.prefetchSize=1"); - - final ActiveMQTopic FAST_SHARED_TOPIC = new ActiveMQTopic( - NetworkBridgeProducerFlowControlTest.class.getSimpleName() - + ".fast.shared?consumer.prefetchSize=1"); - - doTestSendFailIfNoSpaceDoesNotBlockNetwork( - SLOW_SHARED_TOPIC, - FAST_SHARED_TOPIC); - } - - public void doTestSendFailIfNoSpaceDoesNotBlockNetwork( - ActiveMQDestination slowDestination, ActiveMQDestination fastDestination) throws Exception { - - final int NUM_MESSAGES = 100; - final long TEST_MESSAGE_SIZE = 1024; - final long SLOW_CONSUMER_DELAY_MILLIS = 100; - - // Start a local and a remote broker. - createBroker(new URI("broker:(tcp://localhost:0" - + ")?brokerName=broker0&persistent=false&useJmx=true")); - BrokerService remoteBroker = createBroker(new URI( - "broker:(tcp://localhost:0" - + ")?brokerName=broker1&persistent=false&useJmx=true")); - remoteBroker.getSystemUsage().setSendFailIfNoSpace(true); - - // Set a policy on the remote broker that limits the maximum size of the - // slow shared queue. - PolicyEntry policyEntry = new PolicyEntry(); - policyEntry.setMemoryLimit(5 * TEST_MESSAGE_SIZE); - PolicyMap policyMap = new PolicyMap(); - policyMap.put(slowDestination, policyEntry); - remoteBroker.setDestinationPolicy(policyMap); - - // Create an outbound bridge from the local broker to the remote broker. - // The bridge is configured with the remoteDispatchType enhancement. - NetworkConnector nc = bridgeBrokers("broker0", "broker1"); - nc.setAlwaysSyncSend(true); - nc.setPrefetchSize(1); - - startAllBrokers(); - waitForBridgeFormation(); - - // Start two asynchronous consumers on the remote broker, one for each - // of the two shared queues, and keep track of how long it takes for - // each of the consumers to receive all the messages. - final CountDownLatch fastConsumerLatch = new CountDownLatch( - NUM_MESSAGES); - final CountDownLatch slowConsumerLatch = new CountDownLatch( - NUM_MESSAGES); - - final long startTimeMillis = System.currentTimeMillis(); - final AtomicLong fastConsumerTime = new AtomicLong(); - final AtomicLong slowConsumerTime = new AtomicLong(); - - Thread fastWaitThread = new Thread() { - @Override - public void run() { - try { - fastConsumerLatch.await(); - fastConsumerTime.set(System.currentTimeMillis() - - startTimeMillis); - } catch (InterruptedException ex) { - exceptions.add(ex); - Assert.fail(ex.getMessage()); - } + Thread slowWaitThread = new Thread() { + @Override + public void run() { + try { + slowConsumerLatch.await(); + slowConsumerTime.set(System.currentTimeMillis() - startTimeMillis); } - }; - - Thread slowWaitThread = new Thread() { - @Override - public void run() { - try { - slowConsumerLatch.await(); - slowConsumerTime.set(System.currentTimeMillis() - - startTimeMillis); - } catch (InterruptedException ex) { - exceptions.add(ex); - Assert.fail(ex.getMessage()); - } + catch (InterruptedException ex) { + exceptions.add(ex); + Assert.fail(ex.getMessage()); } - }; + } + }; - fastWaitThread.start(); - slowWaitThread.start(); + fastWaitThread.start(); + slowWaitThread.start(); - createConsumer("broker1", fastDestination, fastConsumerLatch); - MessageConsumer slowConsumer = createConsumer("broker1", - slowDestination, slowConsumerLatch); - MessageIdList messageIdList = brokers.get("broker1").consumers - .get(slowConsumer); - messageIdList.setProcessingDelay(SLOW_CONSUMER_DELAY_MILLIS); + createConsumer("broker1", FAST_SHARED_QUEUE, fastConsumerLatch); + MessageConsumer slowConsumer = createConsumer("broker1", SLOW_SHARED_QUEUE, slowConsumerLatch); + MessageIdList messageIdList = brokers.get("broker1").consumers.get(slowConsumer); + messageIdList.setProcessingDelay(SLOW_CONSUMER_DELAY_MILLIS); - // Send the test messages to the local broker's shared queues. The - // messages are either persistent or non-persistent to demonstrate the - // difference between synchronous and asynchronous dispatch. - persistentDelivery = false; - sendMessages("broker0", fastDestination, NUM_MESSAGES); - sendMessages("broker0", slowDestination, NUM_MESSAGES); + fastWaitThread.join(); + slowWaitThread.join(); - fastWaitThread.join(TimeUnit.SECONDS.toMillis(60)); - slowWaitThread.join(TimeUnit.SECONDS.toMillis(60)); + assertTrue("no exceptions on the wait threads:" + exceptions, exceptions.isEmpty()); - assertTrue("no exceptions on the wait threads:" + exceptions, - exceptions.isEmpty()); + LOG.info("Fast consumer duration (ms): " + fastConsumerTime.get()); + LOG.info("Slow consumer duration (ms): " + slowConsumerTime.get()); - LOG.info("Fast consumer duration (ms): " + fastConsumerTime.get()); - LOG.info("Slow consumer duration (ms): " + slowConsumerTime.get()); + // Verify the behaviour as described in the description of this class. + if (networkIsAlwaysSendSync) { + Assert.assertTrue(fastConsumerTime.get() < slowConsumerTime.get() / 10); - assertTrue("fast time set", fastConsumerTime.get() > 0); - assertTrue("slow time set", slowConsumerTime.get() > 0); + } + else { + Assert.assertEquals(persistentTestMessages, fastConsumerTime.get() < slowConsumerTime.get() / 10); + } + } - // Verify the behaviour as described in the description of this class. - Assert.assertTrue(fastConsumerTime.get() < slowConsumerTime.get() / 10); - } + public void testSendFailIfNoSpaceDoesNotBlockQueueNetwork() throws Exception { + // Consumer prefetch is disabled for broker1's consumers. + final ActiveMQQueue SLOW_SHARED_QUEUE = new ActiveMQQueue(NetworkBridgeProducerFlowControlTest.class.getSimpleName() + ".slow.shared?consumer.prefetchSize=1"); + + final ActiveMQQueue FAST_SHARED_QUEUE = new ActiveMQQueue(NetworkBridgeProducerFlowControlTest.class.getSimpleName() + ".fast.shared?consumer.prefetchSize=1"); + + doTestSendFailIfNoSpaceDoesNotBlockNetwork(SLOW_SHARED_QUEUE, FAST_SHARED_QUEUE); + } + + public void testSendFailIfNoSpaceDoesNotBlockTopicNetwork() throws Exception { + // Consumer prefetch is disabled for broker1's consumers. + final ActiveMQTopic SLOW_SHARED_TOPIC = new ActiveMQTopic(NetworkBridgeProducerFlowControlTest.class.getSimpleName() + ".slow.shared?consumer.prefetchSize=1"); + + final ActiveMQTopic FAST_SHARED_TOPIC = new ActiveMQTopic(NetworkBridgeProducerFlowControlTest.class.getSimpleName() + ".fast.shared?consumer.prefetchSize=1"); + + doTestSendFailIfNoSpaceDoesNotBlockNetwork(SLOW_SHARED_TOPIC, FAST_SHARED_TOPIC); + } + + public void doTestSendFailIfNoSpaceDoesNotBlockNetwork(ActiveMQDestination slowDestination, + ActiveMQDestination fastDestination) throws Exception { + + final int NUM_MESSAGES = 100; + final long TEST_MESSAGE_SIZE = 1024; + final long SLOW_CONSUMER_DELAY_MILLIS = 100; + + // Start a local and a remote broker. + createBroker(new URI("broker:(tcp://localhost:0" + ")?brokerName=broker0&persistent=false&useJmx=true")); + BrokerService remoteBroker = createBroker(new URI("broker:(tcp://localhost:0" + ")?brokerName=broker1&persistent=false&useJmx=true")); + remoteBroker.getSystemUsage().setSendFailIfNoSpace(true); + + // Set a policy on the remote broker that limits the maximum size of the + // slow shared queue. + PolicyEntry policyEntry = new PolicyEntry(); + policyEntry.setMemoryLimit(5 * TEST_MESSAGE_SIZE); + PolicyMap policyMap = new PolicyMap(); + policyMap.put(slowDestination, policyEntry); + remoteBroker.setDestinationPolicy(policyMap); + + // Create an outbound bridge from the local broker to the remote broker. + // The bridge is configured with the remoteDispatchType enhancement. + NetworkConnector nc = bridgeBrokers("broker0", "broker1"); + nc.setAlwaysSyncSend(true); + nc.setPrefetchSize(1); + + startAllBrokers(); + waitForBridgeFormation(); + + // Start two asynchronous consumers on the remote broker, one for each + // of the two shared queues, and keep track of how long it takes for + // each of the consumers to receive all the messages. + final CountDownLatch fastConsumerLatch = new CountDownLatch(NUM_MESSAGES); + final CountDownLatch slowConsumerLatch = new CountDownLatch(NUM_MESSAGES); + + final long startTimeMillis = System.currentTimeMillis(); + final AtomicLong fastConsumerTime = new AtomicLong(); + final AtomicLong slowConsumerTime = new AtomicLong(); + + Thread fastWaitThread = new Thread() { + @Override + public void run() { + try { + fastConsumerLatch.await(); + fastConsumerTime.set(System.currentTimeMillis() - startTimeMillis); + } + catch (InterruptedException ex) { + exceptions.add(ex); + Assert.fail(ex.getMessage()); + } + } + }; + + Thread slowWaitThread = new Thread() { + @Override + public void run() { + try { + slowConsumerLatch.await(); + slowConsumerTime.set(System.currentTimeMillis() - startTimeMillis); + } + catch (InterruptedException ex) { + exceptions.add(ex); + Assert.fail(ex.getMessage()); + } + } + }; + + fastWaitThread.start(); + slowWaitThread.start(); + + createConsumer("broker1", fastDestination, fastConsumerLatch); + MessageConsumer slowConsumer = createConsumer("broker1", slowDestination, slowConsumerLatch); + MessageIdList messageIdList = brokers.get("broker1").consumers.get(slowConsumer); + messageIdList.setProcessingDelay(SLOW_CONSUMER_DELAY_MILLIS); + + // Send the test messages to the local broker's shared queues. The + // messages are either persistent or non-persistent to demonstrate the + // difference between synchronous and asynchronous dispatch. + persistentDelivery = false; + sendMessages("broker0", fastDestination, NUM_MESSAGES); + sendMessages("broker0", slowDestination, NUM_MESSAGES); + + fastWaitThread.join(TimeUnit.SECONDS.toMillis(60)); + slowWaitThread.join(TimeUnit.SECONDS.toMillis(60)); + + assertTrue("no exceptions on the wait threads:" + exceptions, exceptions.isEmpty()); + + LOG.info("Fast consumer duration (ms): " + fastConsumerTime.get()); + LOG.info("Slow consumer duration (ms): " + slowConsumerTime.get()); + + assertTrue("fast time set", fastConsumerTime.get() > 0); + assertTrue("slow time set", slowConsumerTime.get() > 0); + + // Verify the behaviour as described in the description of this class. + Assert.assertTrue(fastConsumerTime.get() < slowConsumerTime.get() / 10); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NetworkOfTwentyBrokersTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NetworkOfTwentyBrokersTest.java index f1266e3f33..5cbc11f597 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NetworkOfTwentyBrokersTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NetworkOfTwentyBrokersTest.java @@ -20,6 +20,7 @@ import java.net.URI; import java.util.Collection; import java.util.Iterator; import java.util.List; + import org.apache.activemq.JmsMultipleBrokersTestSupport; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.TransportConnector; @@ -32,186 +33,192 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NetworkOfTwentyBrokersTest extends JmsMultipleBrokersTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(NetworkOfTwentyBrokersTest.class); - // This will interconnect all brokers using multicast - protected void bridgeAllBrokers() throws Exception { - bridgeAllBrokers("TwentyBrokersTest", 1, false, false); - } + private static final Logger LOG = LoggerFactory.getLogger(NetworkOfTwentyBrokersTest.class); - protected void bridgeAllBrokers(String groupName, int ttl, boolean suppressduplicateQueueSubs) throws Exception { - bridgeAllBrokers(groupName, ttl, suppressduplicateQueueSubs, false); - } + // This will interconnect all brokers using multicast + protected void bridgeAllBrokers() throws Exception { + bridgeAllBrokers("TwentyBrokersTest", 1, false, false); + } - protected void bridgeAllBrokers(String groupName, int ttl, boolean suppressduplicateQueueSubs, boolean decreasePriority) throws Exception { - Collection brokerList = brokers.values(); - for (Iterator i = brokerList.iterator(); i.hasNext();) { - BrokerService broker = i.next().broker; - List transportConnectors = broker.getTransportConnectors(); + protected void bridgeAllBrokers(String groupName, int ttl, boolean suppressduplicateQueueSubs) throws Exception { + bridgeAllBrokers(groupName, ttl, suppressduplicateQueueSubs, false); + } - if (transportConnectors.isEmpty()) { - broker.addConnector(new URI(AUTO_ASSIGN_TRANSPORT)); - transportConnectors = broker.getTransportConnectors(); - } + protected void bridgeAllBrokers(String groupName, + int ttl, + boolean suppressduplicateQueueSubs, + boolean decreasePriority) throws Exception { + Collection brokerList = brokers.values(); + for (Iterator i = brokerList.iterator(); i.hasNext(); ) { + BrokerService broker = i.next().broker; + List transportConnectors = broker.getTransportConnectors(); - TransportConnector transport = transportConnectors.get(0); - if (transport.getDiscoveryUri() == null) { - transport.setDiscoveryUri(new URI("multicast://default?group=" + groupName)); - } + if (transportConnectors.isEmpty()) { + broker.addConnector(new URI(AUTO_ASSIGN_TRANSPORT)); + transportConnectors = broker.getTransportConnectors(); + } - List networkConnectors = broker.getNetworkConnectors(); - if (networkConnectors.isEmpty()) { - broker.addNetworkConnector("multicast://default?group=" + groupName); - networkConnectors = broker.getNetworkConnectors(); - } + TransportConnector transport = transportConnectors.get(0); + if (transport.getDiscoveryUri() == null) { + transport.setDiscoveryUri(new URI("multicast://default?group=" + groupName)); + } - NetworkConnector nc = networkConnectors.get(0); - nc.setNetworkTTL(ttl); - nc.setSuppressDuplicateQueueSubscriptions(suppressduplicateQueueSubs); - nc.setDecreaseNetworkConsumerPriority(decreasePriority); - } + List networkConnectors = broker.getNetworkConnectors(); + if (networkConnectors.isEmpty()) { + broker.addNetworkConnector("multicast://default?group=" + groupName); + networkConnectors = broker.getNetworkConnectors(); + } - // Multicasting may take longer to setup - maxSetupTime = 8000; - } + NetworkConnector nc = networkConnectors.get(0); + nc.setNetworkTTL(ttl); + nc.setSuppressDuplicateQueueSubscriptions(suppressduplicateQueueSubs); + nc.setDecreaseNetworkConsumerPriority(decreasePriority); + } - protected BrokerService createBroker(String brokerName) throws Exception { - BrokerService broker = new BrokerService(); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.setBrokerName(brokerName); - broker.addConnector(new URI(AUTO_ASSIGN_TRANSPORT)); - brokers.put(brokerName, new BrokerItem(broker)); + // Multicasting may take longer to setup + maxSetupTime = 8000; + } - return broker; - } + protected BrokerService createBroker(String brokerName) throws Exception { + BrokerService broker = new BrokerService(); + broker.setPersistent(false); + broker.setUseJmx(false); + broker.setBrokerName(brokerName); + broker.addConnector(new URI(AUTO_ASSIGN_TRANSPORT)); + brokers.put(brokerName, new BrokerItem(broker)); - /* AMQ-3077 Bug */ - public void testBrokers() throws Exception { - int X = 20; - int i; + return broker; + } - LOG.info("Creating X Brokers"); - for (i = 0; i < X; i++) { - createBroker("Broker" + i); - } + /* AMQ-3077 Bug */ + public void testBrokers() throws Exception { + int X = 20; + int i; - bridgeAllBrokers(); - startAllBrokers(); - waitForBridgeFormation(X-1); + LOG.info("Creating X Brokers"); + for (i = 0; i < X; i++) { + createBroker("Broker" + i); + } - LOG.info("Waiting for complete formation"); - try { - Thread.sleep(20000); - } catch (Exception e) { - } + bridgeAllBrokers(); + startAllBrokers(); + waitForBridgeFormation(X - 1); - verifyPeerBrokerInfos(X-1); + LOG.info("Waiting for complete formation"); + try { + Thread.sleep(20000); + } + catch (Exception e) { + } - LOG.info("Stopping half the brokers"); - for (i = 0; i < X/2; i++) { - destroyBroker("Broker" + i); - } + verifyPeerBrokerInfos(X - 1); - LOG.info("Waiting for complete stop"); - try { - Thread.sleep(20000); - } catch (Exception e) { - } + LOG.info("Stopping half the brokers"); + for (i = 0; i < X / 2; i++) { + destroyBroker("Broker" + i); + } - verifyPeerBrokerInfos((X/2) - 1); + LOG.info("Waiting for complete stop"); + try { + Thread.sleep(20000); + } + catch (Exception e) { + } - LOG.info("Recreating first half"); - for (i = 0; i < X/2; i++) { - createBroker("Broker" + i); - } + verifyPeerBrokerInfos((X / 2) - 1); - bridgeAllBrokers(); - startAllBrokers(); - waitForBridgeFormation(X-1); + LOG.info("Recreating first half"); + for (i = 0; i < X / 2; i++) { + createBroker("Broker" + i); + } - LOG.info("Waiting for complete reformation"); - try { - Thread.sleep(20000); - } catch (Exception e) { - } + bridgeAllBrokers(); + startAllBrokers(); + waitForBridgeFormation(X - 1); - verifyPeerBrokerInfos(X-1); - } + LOG.info("Waiting for complete reformation"); + try { + Thread.sleep(20000); + } + catch (Exception e) { + } - public void testPeerBrokerCountHalfPeer() throws Exception { - createBroker("A"); - createBroker("B"); - bridgeBrokers("A", "B"); - startAllBrokers(); - verifyPeerBrokerInfo(brokers.get("A"), 1); - verifyPeerBrokerInfo(brokers.get("B"), 0); - } + verifyPeerBrokerInfos(X - 1); + } - public void testPeerBrokerCountHalfPeerTwice() throws Exception { - createBroker("A"); - createBroker("B"); - bridgeBrokers("A", "B"); - bridgeBrokers("A", "B"); - startAllBrokers(); - verifyPeerBrokerInfo(brokers.get("A"), 1); - verifyPeerBrokerInfo(brokers.get("B"), 0); - } + public void testPeerBrokerCountHalfPeer() throws Exception { + createBroker("A"); + createBroker("B"); + bridgeBrokers("A", "B"); + startAllBrokers(); + verifyPeerBrokerInfo(brokers.get("A"), 1); + verifyPeerBrokerInfo(brokers.get("B"), 0); + } - public void testPeerBrokerCountFullPeer() throws Exception { - createBroker("A"); - createBroker("B"); - bridgeBrokers("A", "B"); - bridgeBrokers("B", "A"); - startAllBrokers(); - verifyPeerBrokerInfo(brokers.get("A"), 1); - verifyPeerBrokerInfo(brokers.get("B"), 1); - } + public void testPeerBrokerCountHalfPeerTwice() throws Exception { + createBroker("A"); + createBroker("B"); + bridgeBrokers("A", "B"); + bridgeBrokers("A", "B"); + startAllBrokers(); + verifyPeerBrokerInfo(brokers.get("A"), 1); + verifyPeerBrokerInfo(brokers.get("B"), 0); + } - public void testPeerBrokerCountFullPeerDuplex() throws Exception { - createBroker("A"); - createBroker("B"); - NetworkConnector nc = bridgeBrokers("A", "B"); - nc.setDuplex(true); - startAllBrokers(); - verifyPeerBrokerInfo(brokers.get("A"), 1); - verifyPeerBrokerInfo(brokers.get("B"), 1); - } + public void testPeerBrokerCountFullPeer() throws Exception { + createBroker("A"); + createBroker("B"); + bridgeBrokers("A", "B"); + bridgeBrokers("B", "A"); + startAllBrokers(); + verifyPeerBrokerInfo(brokers.get("A"), 1); + verifyPeerBrokerInfo(brokers.get("B"), 1); + } + public void testPeerBrokerCountFullPeerDuplex() throws Exception { + createBroker("A"); + createBroker("B"); + NetworkConnector nc = bridgeBrokers("A", "B"); + nc.setDuplex(true); + startAllBrokers(); + verifyPeerBrokerInfo(brokers.get("A"), 1); + verifyPeerBrokerInfo(brokers.get("B"), 1); + } - private void verifyPeerBrokerInfo(BrokerItem brokerItem, final int max) throws Exception { - final BrokerService broker = brokerItem.broker; - final RegionBroker regionBroker = (RegionBroker) broker.getRegionBroker(); - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("verify infos " + broker.getBrokerName() + ", len: " + regionBroker.getPeerBrokerInfos().length); - return max == regionBroker.getPeerBrokerInfos().length; - } - }, 120 * 1000); - LOG.info("verify infos " + broker.getBrokerName() + ", len: " + regionBroker.getPeerBrokerInfos().length); - for (BrokerInfo info : regionBroker.getPeerBrokerInfos()) { - LOG.info(info.getBrokerName()); - } - assertEquals(broker.getBrokerName(), max, regionBroker.getPeerBrokerInfos().length); - } + private void verifyPeerBrokerInfo(BrokerItem brokerItem, final int max) throws Exception { + final BrokerService broker = brokerItem.broker; + final RegionBroker regionBroker = (RegionBroker) broker.getRegionBroker(); + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("verify infos " + broker.getBrokerName() + ", len: " + regionBroker.getPeerBrokerInfos().length); + return max == regionBroker.getPeerBrokerInfos().length; + } + }, 120 * 1000); + LOG.info("verify infos " + broker.getBrokerName() + ", len: " + regionBroker.getPeerBrokerInfos().length); + for (BrokerInfo info : regionBroker.getPeerBrokerInfos()) { + LOG.info(info.getBrokerName()); + } + assertEquals(broker.getBrokerName(), max, regionBroker.getPeerBrokerInfos().length); + } - private void verifyPeerBrokerInfos(final int max) throws Exception { - Collection brokerList = brokers.values(); - for (Iterator i = brokerList.iterator(); i.hasNext();) { - verifyPeerBrokerInfo(i.next(), max); - } - } + private void verifyPeerBrokerInfos(final int max) throws Exception { + Collection brokerList = brokers.values(); + for (Iterator i = brokerList.iterator(); i.hasNext(); ) { + verifyPeerBrokerInfo(i.next(), max); + } + } - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - } + @Override + public void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); + } - @Override - public void tearDown() throws Exception { - super.tearDown(); - ThreadTracker.result(); - } + @Override + public void tearDown() throws Exception { + super.tearDown(); + ThreadTracker.result(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NewConsumerCreatesDestinationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NewConsumerCreatesDestinationTest.java index 30ae2ec188..150d845670 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NewConsumerCreatesDestinationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NewConsumerCreatesDestinationTest.java @@ -32,32 +32,33 @@ import org.slf4j.LoggerFactory; * */ public class NewConsumerCreatesDestinationTest extends EmbeddedBrokerAndConnectionTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(NewConsumerCreatesDestinationTest.class); - private ActiveMQQueue wildcard; + private static final Logger LOG = LoggerFactory.getLogger(NewConsumerCreatesDestinationTest.class); - public void testNewConsumerCausesNewDestinationToBeAutoCreated() throws Exception { + private ActiveMQQueue wildcard; - // lets create a wildcard thats kinda like those used by Virtual Topics - String wildcardText = "org.*" + getDestinationString().substring("org.apache".length()); - wildcard = new ActiveMQQueue(wildcardText); + public void testNewConsumerCausesNewDestinationToBeAutoCreated() throws Exception { - LOG.info("Using wildcard: " + wildcard); - LOG.info("on destination: " + destination); + // lets create a wildcard thats kinda like those used by Virtual Topics + String wildcardText = "org.*" + getDestinationString().substring("org.apache".length()); + wildcard = new ActiveMQQueue(wildcardText); - assertDestinationCreated(destination, false); - assertDestinationCreated(wildcard, false); + LOG.info("Using wildcard: " + wildcard); + LOG.info("on destination: " + destination); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createConsumer(destination); + assertDestinationCreated(destination, false); + assertDestinationCreated(wildcard, false); - assertDestinationCreated(destination, true); - assertDestinationCreated(wildcard, true); - } + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + session.createConsumer(destination); - protected void assertDestinationCreated(Destination destination, boolean expected) throws Exception { - Set answer = broker.getBroker().getDestinations((ActiveMQDestination) destination); - int size = expected ? 1 : 0; - assertEquals("Size of found destinations: " + answer, size, answer.size()); - } + assertDestinationCreated(destination, true); + assertDestinationCreated(wildcard, true); + } + + protected void assertDestinationCreated(Destination destination, boolean expected) throws Exception { + Set answer = broker.getBroker().getDestinations((ActiveMQDestination) destination); + int size = expected ? 1 : 0; + assertEquals("Size of found destinations: " + answer, size, answer.size()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NoDuplicateOnTopicNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NoDuplicateOnTopicNetworkTest.java index 046818a5e3..c3394fd5af 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NoDuplicateOnTopicNetworkTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NoDuplicateOnTopicNetworkTest.java @@ -57,318 +57,319 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NoDuplicateOnTopicNetworkTest extends CombinationTestSupport { - private static final Logger LOG = LoggerFactory - .getLogger(NoDuplicateOnTopicNetworkTest.class); - private static final String MULTICAST_DEFAULT = "multicast://default"; - private static final String BROKER_1 = "tcp://localhost:61626"; - private static final String BROKER_2 = "tcp://localhost:61636"; - private static final String BROKER_3 = "tcp://localhost:61646"; - private final static String TOPIC_NAME = "broadcast"; - private static byte BASE_PRIORITY = -20; - private BrokerService broker1; - private BrokerService broker2; - private BrokerService broker3; + private static final Logger LOG = LoggerFactory.getLogger(NoDuplicateOnTopicNetworkTest.class); - public boolean suppressDuplicateTopicSubs = false; - public DispatchPolicy dispatchPolicy = new SimpleDispatchPolicy(); - public boolean durableSub = false; - AtomicInteger idCounter = new AtomicInteger(0); - - private boolean dynamicOnly = false; - // no duplicates in cyclic network if networkTTL <=1 - // when > 1, subscriptions percolate around resulting in duplicates as there is no - // memory of the original subscription. - // solution for 6.0 using org.apache.activemq.command.ConsumerInfo.getNetworkConsumerIds() - private int ttl = 3; - - - - @Override - protected void setUp() throws Exception { - super.setUp(); + private static final String MULTICAST_DEFAULT = "multicast://default"; + private static final String BROKER_1 = "tcp://localhost:61626"; + private static final String BROKER_2 = "tcp://localhost:61636"; + private static final String BROKER_3 = "tcp://localhost:61646"; + private final static String TOPIC_NAME = "broadcast"; + private static byte BASE_PRIORITY = -20; + private BrokerService broker1; + private BrokerService broker2; + private BrokerService broker3; - broker3 = createAndStartBroker("broker3", BROKER_3); - Thread.sleep(3000); - broker2 = createAndStartBroker("broker2", BROKER_2); - Thread.sleep(3000); - broker1 = createAndStartBroker("broker1", BROKER_1); - Thread.sleep(1000); - - waitForBridgeFormation(); - } - - public static Test suite() { - return suite(NoDuplicateOnTopicNetworkTest.class); - } - - protected void waitForBridgeFormation() throws Exception { - Wait.waitFor(new Wait.Condition() { - public boolean isSatisified() throws Exception { - return !broker3.getNetworkConnectors().get(0).activeBridges().isEmpty(); - }}); - - Wait.waitFor(new Wait.Condition() { - public boolean isSatisified() throws Exception { - return !broker2.getNetworkConnectors().get(0).activeBridges().isEmpty(); - }}); + public boolean suppressDuplicateTopicSubs = false; + public DispatchPolicy dispatchPolicy = new SimpleDispatchPolicy(); + public boolean durableSub = false; + AtomicInteger idCounter = new AtomicInteger(0); - Wait.waitFor(new Wait.Condition() { - public boolean isSatisified() throws Exception { - return !broker1.getNetworkConnectors().get(0).activeBridges().isEmpty(); - }}); - } + private boolean dynamicOnly = false; + // no duplicates in cyclic network if networkTTL <=1 + // when > 1, subscriptions percolate around resulting in duplicates as there is no + // memory of the original subscription. + // solution for 6.0 using org.apache.activemq.command.ConsumerInfo.getNetworkConsumerIds() + private int ttl = 3; - private BrokerService createAndStartBroker(String name, String addr) - throws Exception { - BrokerService broker = new BrokerService(); - broker.setDeleteAllMessagesOnStartup(true); - broker.setBrokerName(name); - broker.addConnector(addr).setDiscoveryUri(new URI(MULTICAST_DEFAULT)); - broker.setUseJmx(false); + @Override + protected void setUp() throws Exception { + super.setUp(); - NetworkConnector networkConnector = broker - .addNetworkConnector(MULTICAST_DEFAULT); - networkConnector.setDecreaseNetworkConsumerPriority(true); - networkConnector.setDynamicOnly(dynamicOnly); - networkConnector.setNetworkTTL(ttl); - networkConnector.setSuppressDuplicateTopicSubscriptions(suppressDuplicateTopicSubs); - networkConnector.setConsumerPriorityBase(BASE_PRIORITY); - networkConnector.addStaticallyIncludedDestination(new ActiveMQTopic("BeStaticallyIncluded")); - - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policy = new PolicyEntry(); - policy.setDispatchPolicy(dispatchPolicy); - // the audit will suppress the duplicates as it defaults to true so this test - // checking for dups will fail. it is good to have it on in practice. - policy.setEnableAudit(false); - policyMap.put(new ActiveMQTopic(TOPIC_NAME), policy); - broker.setDestinationPolicy(policyMap); - broker.start(); - - return broker; - } + broker3 = createAndStartBroker("broker3", BROKER_3); + Thread.sleep(3000); + broker2 = createAndStartBroker("broker2", BROKER_2); + Thread.sleep(3000); + broker1 = createAndStartBroker("broker1", BROKER_1); + Thread.sleep(1000); - @Override - protected void tearDown() throws Exception { - broker1.stop(); - broker2.stop(); - broker3.stop(); - super.tearDown(); - } + waitForBridgeFormation(); + } - public void initCombosForTestProducerConsumerTopic() { - this.addCombinationValues("suppressDuplicateTopicSubs", new Object[]{Boolean.TRUE, Boolean.FALSE}); - this.addCombinationValues("dispatchPolicy", new Object[]{new PriorityNetworkDispatchPolicy(), new SimpleDispatchPolicy()}); - this.addCombinationValues("durableSub", new Object[]{Boolean.TRUE, Boolean.FALSE}); - } - - public void testProducerConsumerTopic() throws Exception { - - final CountDownLatch consumerStarted = new CountDownLatch(1); - - Thread producerThread = new Thread(new Runnable() { - public void run() { - TopicWithDuplicateMessages producer = new TopicWithDuplicateMessages(); - producer.setBrokerURL(BROKER_1); - producer.setTopicName(TOPIC_NAME); - try { - producer.produce(); - } catch (JMSException e) { - fail("Unexpected " + e); - } + public static Test suite() { + return suite(NoDuplicateOnTopicNetworkTest.class); + } + + protected void waitForBridgeFormation() throws Exception { + Wait.waitFor(new Wait.Condition() { + public boolean isSatisified() throws Exception { + return !broker3.getNetworkConnectors().get(0).activeBridges().isEmpty(); + } + }); + + Wait.waitFor(new Wait.Condition() { + public boolean isSatisified() throws Exception { + return !broker2.getNetworkConnectors().get(0).activeBridges().isEmpty(); + } + }); + + Wait.waitFor(new Wait.Condition() { + public boolean isSatisified() throws Exception { + return !broker1.getNetworkConnectors().get(0).activeBridges().isEmpty(); + } + }); + } + + private BrokerService createAndStartBroker(String name, String addr) throws Exception { + BrokerService broker = new BrokerService(); + broker.setDeleteAllMessagesOnStartup(true); + broker.setBrokerName(name); + broker.addConnector(addr).setDiscoveryUri(new URI(MULTICAST_DEFAULT)); + broker.setUseJmx(false); + + NetworkConnector networkConnector = broker.addNetworkConnector(MULTICAST_DEFAULT); + networkConnector.setDecreaseNetworkConsumerPriority(true); + networkConnector.setDynamicOnly(dynamicOnly); + networkConnector.setNetworkTTL(ttl); + networkConnector.setSuppressDuplicateTopicSubscriptions(suppressDuplicateTopicSubs); + networkConnector.setConsumerPriorityBase(BASE_PRIORITY); + networkConnector.addStaticallyIncludedDestination(new ActiveMQTopic("BeStaticallyIncluded")); + + PolicyMap policyMap = new PolicyMap(); + PolicyEntry policy = new PolicyEntry(); + policy.setDispatchPolicy(dispatchPolicy); + // the audit will suppress the duplicates as it defaults to true so this test + // checking for dups will fail. it is good to have it on in practice. + policy.setEnableAudit(false); + policyMap.put(new ActiveMQTopic(TOPIC_NAME), policy); + broker.setDestinationPolicy(policyMap); + broker.start(); + + return broker; + } + + @Override + protected void tearDown() throws Exception { + broker1.stop(); + broker2.stop(); + broker3.stop(); + super.tearDown(); + } + + public void initCombosForTestProducerConsumerTopic() { + this.addCombinationValues("suppressDuplicateTopicSubs", new Object[]{Boolean.TRUE, Boolean.FALSE}); + this.addCombinationValues("dispatchPolicy", new Object[]{new PriorityNetworkDispatchPolicy(), new SimpleDispatchPolicy()}); + this.addCombinationValues("durableSub", new Object[]{Boolean.TRUE, Boolean.FALSE}); + } + + public void testProducerConsumerTopic() throws Exception { + + final CountDownLatch consumerStarted = new CountDownLatch(1); + + Thread producerThread = new Thread(new Runnable() { + public void run() { + TopicWithDuplicateMessages producer = new TopicWithDuplicateMessages(); + producer.setBrokerURL(BROKER_1); + producer.setTopicName(TOPIC_NAME); + try { + producer.produce(); } - }); - - final TopicWithDuplicateMessages consumer = new TopicWithDuplicateMessages(); - Thread consumerThread = new Thread(new Runnable() { - public void run() { - consumer.setBrokerURL(BROKER_2); - consumer.setTopicName(TOPIC_NAME); - try { - consumer.consumer(); - consumerStarted.countDown(); - consumer.getLatch().await(60, TimeUnit.SECONDS); - } catch (Exception e) { - fail("Unexpected " + e); - } + catch (JMSException e) { + fail("Unexpected " + e); } - }); + } + }); - consumerThread.start(); - LOG.info("Started Consumer"); - - assertTrue("consumer started eventually", consumerStarted.await(10, TimeUnit.SECONDS)); - - // ensure subscription has percolated though the network - Thread.sleep(2000); - - // verify network consumer priority - final RegionBroker regionBroker = (RegionBroker)broker1.getRegionBroker(); - assertTrue("Found network destination with priority as expected", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Map destinationMap = regionBroker.getTopicRegion().getDestinationMap(); - LOG.info("destinations: " + destinationMap.keySet()); - boolean found = false; - for (Destination destination : destinationMap.values()) { - List subscriptions = destination.getConsumers(); - LOG.info(destination + " subscriptions: " + subscriptions); - for (Subscription subscription : subscriptions) { - if (subscription.getConsumerInfo().isNetworkSubscription()) { - LOG.info("subscription: " + subscription + ", priority: " + subscription.getConsumerInfo().getPriority()); - assertTrue("priority is < our base: " + subscription.getConsumerInfo().getPriority(), - subscription.getConsumerInfo().getPriority() <= BASE_PRIORITY); - found = true; - } - } - } - return found; + final TopicWithDuplicateMessages consumer = new TopicWithDuplicateMessages(); + Thread consumerThread = new Thread(new Runnable() { + public void run() { + consumer.setBrokerURL(BROKER_2); + consumer.setTopicName(TOPIC_NAME); + try { + consumer.consumer(); + consumerStarted.countDown(); + consumer.getLatch().await(60, TimeUnit.SECONDS); } - })); - - producerThread.start(); - LOG.info("Started Producer"); - producerThread.join(); - consumerThread.join(); - - int duplicateCount = 0; - Map map = new HashMap(); - for (String msg : consumer.getMessageStrings()) { - if (map.containsKey(msg)) { - LOG.info("got duplicate: " + msg); - duplicateCount++; + catch (Exception e) { + fail("Unexpected " + e); } - map.put(msg, msg); - } - consumer.unSubscribe(); - if (suppressDuplicateTopicSubs || dispatchPolicy instanceof PriorityNetworkDispatchPolicy) { - assertEquals("no duplicates", 0, duplicateCount); - assertEquals("got all required messages: " + map.size(), consumer - .getNumMessages(), map.size()); - } else { - assertTrue("we can get some duplicates: " + duplicateCount, duplicateCount >= 0); - if (duplicateCount == 0) { - assertEquals("got all required messages: " + map.size(), consumer - .getNumMessages(), map.size()); + } + }); + + consumerThread.start(); + LOG.info("Started Consumer"); + + assertTrue("consumer started eventually", consumerStarted.await(10, TimeUnit.SECONDS)); + + // ensure subscription has percolated though the network + Thread.sleep(2000); + + // verify network consumer priority + final RegionBroker regionBroker = (RegionBroker) broker1.getRegionBroker(); + assertTrue("Found network destination with priority as expected", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Map destinationMap = regionBroker.getTopicRegion().getDestinationMap(); + LOG.info("destinations: " + destinationMap.keySet()); + boolean found = false; + for (Destination destination : destinationMap.values()) { + List subscriptions = destination.getConsumers(); + LOG.info(destination + " subscriptions: " + subscriptions); + for (Subscription subscription : subscriptions) { + if (subscription.getConsumerInfo().isNetworkSubscription()) { + LOG.info("subscription: " + subscription + ", priority: " + subscription.getConsumerInfo().getPriority()); + assertTrue("priority is < our base: " + subscription.getConsumerInfo().getPriority(), subscription.getConsumerInfo().getPriority() <= BASE_PRIORITY); + found = true; + } + } } - } - } + return found; + } + })); - class TopicWithDuplicateMessages { - private String brokerURL; - private String topicName; - private Connection connection; - private Session session; - private Topic topic; - private MessageProducer producer; - private MessageConsumer consumer; - private final String durableID = "DURABLE_ID"; + producerThread.start(); + LOG.info("Started Producer"); + producerThread.join(); + consumerThread.join(); - private final List receivedStrings = Collections.synchronizedList(new ArrayList()); - private int numMessages = 10; - private CountDownLatch receivedLatch = new CountDownLatch(numMessages); + int duplicateCount = 0; + Map map = new HashMap(); + for (String msg : consumer.getMessageStrings()) { + if (map.containsKey(msg)) { + LOG.info("got duplicate: " + msg); + duplicateCount++; + } + map.put(msg, msg); + } + consumer.unSubscribe(); + if (suppressDuplicateTopicSubs || dispatchPolicy instanceof PriorityNetworkDispatchPolicy) { + assertEquals("no duplicates", 0, duplicateCount); + assertEquals("got all required messages: " + map.size(), consumer.getNumMessages(), map.size()); + } + else { + assertTrue("we can get some duplicates: " + duplicateCount, duplicateCount >= 0); + if (duplicateCount == 0) { + assertEquals("got all required messages: " + map.size(), consumer.getNumMessages(), map.size()); + } + } + } - public CountDownLatch getLatch() { - return receivedLatch; - } - - public List getMessageStrings() { - synchronized(receivedStrings) { - return new ArrayList(receivedStrings); + class TopicWithDuplicateMessages { + + private String brokerURL; + private String topicName; + private Connection connection; + private Session session; + private Topic topic; + private MessageProducer producer; + private MessageConsumer consumer; + private final String durableID = "DURABLE_ID"; + + private final List receivedStrings = Collections.synchronizedList(new ArrayList()); + private int numMessages = 10; + private CountDownLatch receivedLatch = new CountDownLatch(numMessages); + + public CountDownLatch getLatch() { + return receivedLatch; + } + + public List getMessageStrings() { + synchronized (receivedStrings) { + return new ArrayList(receivedStrings); + } + } + + public String getBrokerURL() { + return brokerURL; + } + + public void setBrokerURL(String brokerURL) { + this.brokerURL = brokerURL; + } + + public String getTopicName() { + return topicName; + } + + public void setTopicName(String topicName) { + this.topicName = topicName; + } + + private void createConnection() throws JMSException { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURL); + connection = factory.createConnection(); + connection.setClientID("ID" + idCounter.incrementAndGet()); + } + + private void createTopic() throws JMSException { + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + topic = session.createTopic(topicName); + } + + private void createProducer() throws JMSException { + producer = session.createProducer(topic); + } + + private void createConsumer() throws JMSException { + if (durableSub) { + consumer = session.createDurableSubscriber(topic, durableID); + } + else { + consumer = session.createConsumer(topic); + } + consumer.setMessageListener(new MessageListener() { + + public void onMessage(Message arg0) { + TextMessage msg = (TextMessage) arg0; + try { + LOG.debug("Received message [" + msg.getText() + "]"); + receivedStrings.add(msg.getText()); + receivedLatch.countDown(); + } + catch (JMSException e) { + fail("Unexpected :" + e); + } } - } - public String getBrokerURL() { - return brokerURL; - } + }); + } - public void setBrokerURL(String brokerURL) { - this.brokerURL = brokerURL; - } + private void publish() throws JMSException { + for (int i = 0; i < numMessages; i++) { + TextMessage textMessage = session.createTextMessage(); + String message = "message: " + i; + LOG.debug("Sending message[" + message + "]"); + textMessage.setText(message); + producer.send(textMessage); + } + } - public String getTopicName() { - return topicName; - } + public void produce() throws JMSException { + createConnection(); + createTopic(); + createProducer(); + connection.start(); + publish(); + } - public void setTopicName(String topicName) { - this.topicName = topicName; - } + public void consumer() throws JMSException { + createConnection(); + createTopic(); + createConsumer(); + connection.start(); + } - private void createConnection() throws JMSException { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory( - brokerURL); - connection = factory.createConnection(); - connection.setClientID("ID" + idCounter.incrementAndGet()); - } + public int getNumMessages() { + return numMessages; + } - private void createTopic() throws JMSException { - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - topic = session.createTopic(topicName); - } - - private void createProducer() throws JMSException { - producer = session.createProducer(topic); - } - - private void createConsumer() throws JMSException { - if (durableSub) { - consumer = session.createDurableSubscriber(topic, durableID); - } else { - consumer = session.createConsumer(topic); - } - consumer.setMessageListener(new MessageListener() { - - public void onMessage(Message arg0) { - TextMessage msg = (TextMessage) arg0; - try { - LOG.debug("Received message [" + msg.getText() + "]"); - receivedStrings.add(msg.getText()); - receivedLatch.countDown(); - } catch (JMSException e) { - fail("Unexpected :" + e); - } - } - - }); - } - - private void publish() throws JMSException { - for (int i = 0; i < numMessages; i++) { - TextMessage textMessage = session.createTextMessage(); - String message = "message: " + i; - LOG.debug("Sending message[" + message + "]"); - textMessage.setText(message); - producer.send(textMessage); - } - } - - public void produce() throws JMSException { - createConnection(); - createTopic(); - createProducer(); - connection.start(); - publish(); - } - - public void consumer() throws JMSException { - createConnection(); - createTopic(); - createConsumer(); - connection.start(); - } - - public int getNumMessages() { - return numMessages; - } - - public void unSubscribe() throws Exception { - consumer.close(); - if (durableSub) { - session.unsubscribe(durableID); - // ensure un-subscription has percolated though the network - Thread.sleep(2000); - } - } - } + public void unSubscribe() throws Exception { + consumer.close(); + if (durableSub) { + session.unsubscribe(durableID); + // ensure un-subscription has percolated though the network + Thread.sleep(2000); + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NonBlockingConsumerRedeliveryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NonBlockingConsumerRedeliveryTest.java index aa829d5f59..f4775ccc2e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NonBlockingConsumerRedeliveryTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NonBlockingConsumerRedeliveryTest.java @@ -46,420 +46,401 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NonBlockingConsumerRedeliveryTest { - private static final Logger LOG = LoggerFactory.getLogger(NonBlockingConsumerRedeliveryTest.class); - private final String destinationName = "Destination"; - private final int MSG_COUNT = 100; + private static final Logger LOG = LoggerFactory.getLogger(NonBlockingConsumerRedeliveryTest.class); - private BrokerService broker; - private String connectionUri; + private final String destinationName = "Destination"; + private final int MSG_COUNT = 100; - private ActiveMQConnectionFactory connectionFactory; + private BrokerService broker; + private String connectionUri; - @Test - public void testMessageDeleiveredWhenNonBlockingEnabled() throws Exception { + private ActiveMQConnectionFactory connectionFactory; - final LinkedHashSet received = new LinkedHashSet(); - final LinkedHashSet beforeRollback = new LinkedHashSet(); - final LinkedHashSet afterRollback = new LinkedHashSet(); + @Test + public void testMessageDeleiveredWhenNonBlockingEnabled() throws Exception { - Connection connection = connectionFactory.createConnection(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(destinationName); - MessageConsumer consumer = session.createConsumer(destination); + final LinkedHashSet received = new LinkedHashSet(); + final LinkedHashSet beforeRollback = new LinkedHashSet(); + final LinkedHashSet afterRollback = new LinkedHashSet(); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - received.add(message); + Connection connection = connectionFactory.createConnection(); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue(destinationName); + MessageConsumer consumer = session.createConsumer(destination); + + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + received.add(message); + } + }); + + sendMessages(); + + session.commit(); + connection.start(); + + assertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("Consumer has received " + received.size() + " messages."); + return received.size() == MSG_COUNT; + } + })); + + beforeRollback.addAll(received); + received.clear(); + session.rollback(); + + assertTrue("Post-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("Consumer has received " + received.size() + " messages since rollback."); + return received.size() == MSG_COUNT; + } + })); + + afterRollback.addAll(received); + received.clear(); + + assertEquals(beforeRollback.size(), afterRollback.size()); + assertEquals(beforeRollback, afterRollback); + session.commit(); + } + + @Test + public void testMessageDeleiveredInCorrectOrder() throws Exception { + + final LinkedHashSet received = new LinkedHashSet(); + final LinkedHashSet beforeRollback = new LinkedHashSet(); + final LinkedHashSet afterRollback = new LinkedHashSet(); + + Connection connection = connectionFactory.createConnection(); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue(destinationName); + MessageConsumer consumer = session.createConsumer(destination); + + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + received.add(message); + } + }); + + sendMessages(); + + session.commit(); + connection.start(); + + assertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("Consumer has received " + received.size() + " messages."); + return received.size() == MSG_COUNT; + } + })); + + beforeRollback.addAll(received); + received.clear(); + session.rollback(); + + assertTrue("Post-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("Consumer has received " + received.size() + " messages since rollback."); + return received.size() == MSG_COUNT; + } + })); + + afterRollback.addAll(received); + received.clear(); + + assertEquals(beforeRollback.size(), afterRollback.size()); + assertEquals(beforeRollback, afterRollback); + + Iterator after = afterRollback.iterator(); + Iterator before = beforeRollback.iterator(); + + while (before.hasNext() && after.hasNext()) { + TextMessage original = (TextMessage) before.next(); + TextMessage rolledBack = (TextMessage) after.next(); + + int originalInt = Integer.parseInt(original.getText()); + int rolledbackInt = Integer.parseInt(rolledBack.getText()); + + assertEquals(originalInt, rolledbackInt); + } + + session.commit(); + } + + @Test + public void testMessageDeleiveryDoesntStop() throws Exception { + + final LinkedHashSet received = new LinkedHashSet(); + final LinkedHashSet beforeRollback = new LinkedHashSet(); + final LinkedHashSet afterRollback = new LinkedHashSet(); + + Connection connection = connectionFactory.createConnection(); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue(destinationName); + MessageConsumer consumer = session.createConsumer(destination); + + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + received.add(message); + } + }); + + sendMessages(); + connection.start(); + + assertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("Consumer has received " + received.size() + " messages."); + return received.size() == MSG_COUNT; + } + })); + + beforeRollback.addAll(received); + received.clear(); + session.rollback(); + + sendMessages(); + + assertTrue("Post-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("Consumer has received " + received.size() + " messages since rollback."); + return received.size() == MSG_COUNT * 2; + } + })); + + afterRollback.addAll(received); + received.clear(); + + assertEquals(beforeRollback.size() * 2, afterRollback.size()); + + session.commit(); + } + + @Test + public void testNonBlockingMessageDeleiveryIsDelayed() throws Exception { + final LinkedHashSet received = new LinkedHashSet(); + + ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.getRedeliveryPolicy().setInitialRedeliveryDelay(TimeUnit.SECONDS.toMillis(6)); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue(destinationName); + MessageConsumer consumer = session.createConsumer(destination); + + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + received.add(message); + } + }); + + sendMessages(); + connection.start(); + + assertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("Consumer has received " + received.size() + " messages."); + return received.size() == MSG_COUNT; + } + })); + + received.clear(); + session.rollback(); + + assertFalse("Delayed redelivery test not expecting any messages yet.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return received.size() > 0; + } + }, TimeUnit.SECONDS.toMillis(4))); + + session.commit(); + session.close(); + } + + @Test + public void testNonBlockingMessageDeleiveryWithRollbacks() throws Exception { + final LinkedHashSet received = new LinkedHashSet(); + + ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); + final Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + final Destination destination = session.createQueue(destinationName); + final MessageConsumer consumer = session.createConsumer(destination); + + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + received.add(message); + } + }); + + sendMessages(); + connection.start(); + + assertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("Consumer has received " + received.size() + " messages."); + return received.size() == MSG_COUNT; + } + })); + + received.clear(); + + consumer.setMessageListener(new MessageListener() { + + int count = 0; + + @Override + public void onMessage(Message message) { + + if (++count > 10) { + try { + session.rollback(); + LOG.info("Rolling back session."); + count = 0; + } + catch (JMSException e) { + LOG.warn("Caught an unexcepted exception: " + e.getMessage()); + } } - }); - - sendMessages(); - - session.commit(); - connection.start(); - - assertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", - Wait.waitFor(new Wait.Condition(){ - @Override - public boolean isSatisified() throws Exception { - LOG.info("Consumer has received " + received.size() + " messages."); - return received.size() == MSG_COUNT; - } + else { + received.add(message); + try { + session.commit(); + } + catch (JMSException e) { + LOG.warn("Caught an unexcepted exception: " + e.getMessage()); + } } - )); + } + }); - beforeRollback.addAll(received); - received.clear(); - session.rollback(); + session.rollback(); - assertTrue("Post-Rollback expects to receive: " + MSG_COUNT + " messages.", - Wait.waitFor(new Wait.Condition(){ - @Override - public boolean isSatisified() throws Exception { - LOG.info("Consumer has received " + received.size() + " messages since rollback."); - return received.size() == MSG_COUNT; - } + assertTrue("Post-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("Consumer has received " + received.size() + " messages since rollback."); + return received.size() == MSG_COUNT; + } + })); + + assertEquals(MSG_COUNT, received.size()); + session.commit(); + } + + @Test + public void testNonBlockingMessageDeleiveryWithAllRolledBack() throws Exception { + final LinkedHashSet received = new LinkedHashSet(); + final LinkedHashSet dlqed = new LinkedHashSet(); + + ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); + connection.getRedeliveryPolicy().setMaximumRedeliveries(5); + final Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + final Destination destination = session.createQueue(destinationName); + final Destination dlq = session.createQueue("ActiveMQ.DLQ"); + final MessageConsumer consumer = session.createConsumer(destination); + final MessageConsumer dlqConsumer = session.createConsumer(dlq); + + dlqConsumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + dlqed.add(message); + } + }); + + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + received.add(message); + } + }); + + sendMessages(); + connection.start(); + + assertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("Consumer has received " + received.size() + " messages."); + return received.size() == MSG_COUNT; + } + })); + + session.rollback(); + + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + try { + session.rollback(); } - )); - - afterRollback.addAll(received); - received.clear(); - - assertEquals(beforeRollback.size(), afterRollback.size()); - assertEquals(beforeRollback, afterRollback); - session.commit(); - } - - @Test - public void testMessageDeleiveredInCorrectOrder() throws Exception { - - final LinkedHashSet received = new LinkedHashSet(); - final LinkedHashSet beforeRollback = new LinkedHashSet(); - final LinkedHashSet afterRollback = new LinkedHashSet(); - - Connection connection = connectionFactory.createConnection(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(destinationName); - MessageConsumer consumer = session.createConsumer(destination); - - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - received.add(message); + catch (JMSException e) { + LOG.warn("Caught an unexcepted exception: " + e.getMessage()); } - }); + } + }); - sendMessages(); + assertTrue("Post-Rollback expects to DLQ: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("Consumer has received " + dlqed.size() + " messages in DLQ."); + return dlqed.size() == MSG_COUNT; + } + })); - session.commit(); - connection.start(); + session.commit(); + } - assertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", - Wait.waitFor(new Wait.Condition(){ - @Override - public boolean isSatisified() throws Exception { - LOG.info("Consumer has received " + received.size() + " messages."); - return received.size() == MSG_COUNT; - } - } - )); + private void sendMessages() throws Exception { + Connection connection = connectionFactory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue(destinationName); + MessageProducer producer = session.createProducer(destination); + for (int i = 0; i < MSG_COUNT; ++i) { + producer.send(session.createTextMessage("" + i)); + } + } - beforeRollback.addAll(received); - received.clear(); - session.rollback(); + @Before + public void startBroker() throws Exception { + broker = new BrokerService(); + broker.setDeleteAllMessagesOnStartup(true); + broker.setPersistent(false); + broker.setUseJmx(false); + broker.addConnector("tcp://0.0.0.0:0"); + broker.start(); + broker.waitUntilStarted(); - assertTrue("Post-Rollback expects to receive: " + MSG_COUNT + " messages.", - Wait.waitFor(new Wait.Condition(){ - @Override - public boolean isSatisified() throws Exception { - LOG.info("Consumer has received " + received.size() + " messages since rollback."); - return received.size() == MSG_COUNT; - } - } - )); + connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); + connectionFactory = new ActiveMQConnectionFactory(connectionUri); + connectionFactory.setNonBlockingRedelivery(true); - afterRollback.addAll(received); - received.clear(); + RedeliveryPolicy policy = connectionFactory.getRedeliveryPolicy(); + policy.setInitialRedeliveryDelay(TimeUnit.SECONDS.toMillis(2)); + policy.setBackOffMultiplier(-1); + policy.setRedeliveryDelay(TimeUnit.SECONDS.toMillis(2)); + policy.setMaximumRedeliveryDelay(-1); + policy.setUseExponentialBackOff(false); + policy.setMaximumRedeliveries(-1); + } - assertEquals(beforeRollback.size(), afterRollback.size()); - assertEquals(beforeRollback, afterRollback); - - Iterator after = afterRollback.iterator(); - Iterator before = beforeRollback.iterator(); - - while (before.hasNext() && after.hasNext()) { - TextMessage original = (TextMessage) before.next(); - TextMessage rolledBack = (TextMessage) after.next(); - - int originalInt = Integer.parseInt(original.getText()); - int rolledbackInt = Integer.parseInt(rolledBack.getText()); - - assertEquals(originalInt, rolledbackInt); - } - - session.commit(); - } - - @Test - public void testMessageDeleiveryDoesntStop() throws Exception { - - final LinkedHashSet received = new LinkedHashSet(); - final LinkedHashSet beforeRollback = new LinkedHashSet(); - final LinkedHashSet afterRollback = new LinkedHashSet(); - - Connection connection = connectionFactory.createConnection(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(destinationName); - MessageConsumer consumer = session.createConsumer(destination); - - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - received.add(message); - } - }); - - sendMessages(); - connection.start(); - - assertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", - Wait.waitFor(new Wait.Condition(){ - @Override - public boolean isSatisified() throws Exception { - LOG.info("Consumer has received " + received.size() + " messages."); - return received.size() == MSG_COUNT; - } - } - )); - - beforeRollback.addAll(received); - received.clear(); - session.rollback(); - - sendMessages(); - - assertTrue("Post-Rollback expects to receive: " + MSG_COUNT + " messages.", - Wait.waitFor(new Wait.Condition(){ - @Override - public boolean isSatisified() throws Exception { - LOG.info("Consumer has received " + received.size() + " messages since rollback."); - return received.size() == MSG_COUNT * 2; - } - } - )); - - afterRollback.addAll(received); - received.clear(); - - assertEquals(beforeRollback.size() * 2, afterRollback.size()); - - session.commit(); - } - - @Test - public void testNonBlockingMessageDeleiveryIsDelayed() throws Exception { - final LinkedHashSet received = new LinkedHashSet(); - - ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.getRedeliveryPolicy().setInitialRedeliveryDelay(TimeUnit.SECONDS.toMillis(6)); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(destinationName); - MessageConsumer consumer = session.createConsumer(destination); - - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - received.add(message); - } - }); - - sendMessages(); - connection.start(); - - assertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", - Wait.waitFor(new Wait.Condition(){ - @Override - public boolean isSatisified() throws Exception { - LOG.info("Consumer has received " + received.size() + " messages."); - return received.size() == MSG_COUNT; - } - } - )); - - received.clear(); - session.rollback(); - - assertFalse("Delayed redelivery test not expecting any messages yet.", - Wait.waitFor(new Wait.Condition(){ - @Override - public boolean isSatisified() throws Exception { - return received.size() > 0; - } - }, TimeUnit.SECONDS.toMillis(4) - )); - - session.commit(); - session.close(); - } - - @Test - public void testNonBlockingMessageDeleiveryWithRollbacks() throws Exception { - final LinkedHashSet received = new LinkedHashSet(); - - ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); - final Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - final Destination destination = session.createQueue(destinationName); - final MessageConsumer consumer = session.createConsumer(destination); - - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - received.add(message); - } - }); - - sendMessages(); - connection.start(); - - assertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", - Wait.waitFor(new Wait.Condition(){ - @Override - public boolean isSatisified() throws Exception { - LOG.info("Consumer has received " + received.size() + " messages."); - return received.size() == MSG_COUNT; - } - } - )); - - received.clear(); - - consumer.setMessageListener(new MessageListener() { - - int count = 0; - - @Override - public void onMessage(Message message) { - - if (++count > 10) { - try { - session.rollback(); - LOG.info("Rolling back session."); - count = 0; - } catch (JMSException e) { - LOG.warn("Caught an unexcepted exception: " + e.getMessage()); - } - } else { - received.add(message); - try { - session.commit(); - } catch (JMSException e) { - LOG.warn("Caught an unexcepted exception: " + e.getMessage()); - } - } - } - }); - - session.rollback(); - - assertTrue("Post-Rollback expects to receive: " + MSG_COUNT + " messages.", - Wait.waitFor(new Wait.Condition(){ - @Override - public boolean isSatisified() throws Exception { - LOG.info("Consumer has received " + received.size() + " messages since rollback."); - return received.size() == MSG_COUNT; - } - } - )); - - assertEquals(MSG_COUNT, received.size()); - session.commit(); - } - - @Test - public void testNonBlockingMessageDeleiveryWithAllRolledBack() throws Exception { - final LinkedHashSet received = new LinkedHashSet(); - final LinkedHashSet dlqed = new LinkedHashSet(); - - ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.getRedeliveryPolicy().setMaximumRedeliveries(5); - final Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - final Destination destination = session.createQueue(destinationName); - final Destination dlq = session.createQueue("ActiveMQ.DLQ"); - final MessageConsumer consumer = session.createConsumer(destination); - final MessageConsumer dlqConsumer = session.createConsumer(dlq); - - dlqConsumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - dlqed.add(message); - } - }); - - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - received.add(message); - } - }); - - sendMessages(); - connection.start(); - - assertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", - Wait.waitFor(new Wait.Condition(){ - @Override - public boolean isSatisified() throws Exception { - LOG.info("Consumer has received " + received.size() + " messages."); - return received.size() == MSG_COUNT; - } - } - )); - - session.rollback(); - - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - try { - session.rollback(); - } catch (JMSException e) { - LOG.warn("Caught an unexcepted exception: " + e.getMessage()); - } - } - }); - - assertTrue("Post-Rollback expects to DLQ: " + MSG_COUNT + " messages.", - Wait.waitFor(new Wait.Condition(){ - @Override - public boolean isSatisified() throws Exception { - LOG.info("Consumer has received " + dlqed.size() + " messages in DLQ."); - return dlqed.size() == MSG_COUNT; - } - } - )); - - session.commit(); - } - - private void sendMessages() throws Exception { - Connection connection = connectionFactory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(destinationName); - MessageProducer producer = session.createProducer(destination); - for(int i = 0; i < MSG_COUNT; ++i) { - producer.send(session.createTextMessage("" + i)); - } - } - - @Before - public void startBroker() throws Exception { - broker = new BrokerService(); - broker.setDeleteAllMessagesOnStartup(true); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.addConnector("tcp://0.0.0.0:0"); - broker.start(); - broker.waitUntilStarted(); - - connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); - connectionFactory = new ActiveMQConnectionFactory(connectionUri); - connectionFactory.setNonBlockingRedelivery(true); - - RedeliveryPolicy policy = connectionFactory.getRedeliveryPolicy(); - policy.setInitialRedeliveryDelay(TimeUnit.SECONDS.toMillis(2)); - policy.setBackOffMultiplier(-1); - policy.setRedeliveryDelay(TimeUnit.SECONDS.toMillis(2)); - policy.setMaximumRedeliveryDelay(-1); - policy.setUseExponentialBackOff(false); - policy.setMaximumRedeliveries(-1); - } - - @After - public void stopBroker() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } + @After + public void stopBroker() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ObjectMessageNotSerializableTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ObjectMessageNotSerializableTest.java index c9f0f5306a..8313c985aa 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ObjectMessageNotSerializableTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ObjectMessageNotSerializableTest.java @@ -38,236 +38,239 @@ import org.apache.activemq.command.ActiveMQTopic; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - public class ObjectMessageNotSerializableTest extends CombinationTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(ObjectMessageNotSerializableTest.class); - - BrokerService broker; - AtomicInteger numReceived = new AtomicInteger(0); - final Vector exceptions = new Vector(); + private static final Logger LOG = LoggerFactory.getLogger(ObjectMessageNotSerializableTest.class); - public static Test suite() { - return suite(ObjectMessageNotSerializableTest.class); - } + BrokerService broker; + AtomicInteger numReceived = new AtomicInteger(0); + final Vector exceptions = new Vector(); - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - - protected void setUp() throws Exception { - exceptions.clear(); - broker = createBroker(); - } - - public void testSendNotSerializeableObjectMessage() throws Exception { + public static Test suite() { + return suite(ObjectMessageNotSerializableTest.class); + } - final ActiveMQDestination destination = new ActiveMQQueue("testQ"); - final MyObject obj = new MyObject("A message"); + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - final CountDownLatch consumerStarted = new CountDownLatch(1); + protected void setUp() throws Exception { + exceptions.clear(); + broker = createBroker(); + } - Thread vmConsumerThread = new Thread("Consumer Thread") { - public void run() { - try { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - factory.setOptimizedMessageDispatch(true); - factory.setObjectMessageSerializationDefered(true); - factory.setCopyMessageOnSend(false); + public void testSendNotSerializeableObjectMessage() throws Exception { - Connection connection = factory.createConnection(); - Session session = (ActiveMQSession)connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); - connection.start(); - consumerStarted.countDown(); - ActiveMQObjectMessage message = (ActiveMQObjectMessage)consumer.receive(30000); - if ( message != null ) { - MyObject object = (MyObject)message.getObject(); - LOG.info("Got message " + object.getMessage()); - numReceived.incrementAndGet(); - } - consumer.close(); - } catch (Throwable ex) { - exceptions.add(ex); - } - } - }; - vmConsumerThread.start(); + final ActiveMQDestination destination = new ActiveMQQueue("testQ"); + final MyObject obj = new MyObject("A message"); - Thread producingThread = new Thread("Producing Thread") { - public void run() { - try { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - factory.setOptimizedMessageDispatch(true); - factory.setObjectMessageSerializationDefered(true); - factory.setCopyMessageOnSend(false); + final CountDownLatch consumerStarted = new CountDownLatch(1); - Connection connection = factory.createConnection(); - Session session = (ActiveMQSession)connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - ActiveMQObjectMessage message = (ActiveMQObjectMessage)session.createObjectMessage(); - message.setObject(obj); - producer.send(message); - producer.close(); - } catch (Throwable ex) { - exceptions.add(ex); - } + Thread vmConsumerThread = new Thread("Consumer Thread") { + public void run() { + try { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + factory.setOptimizedMessageDispatch(true); + factory.setObjectMessageSerializationDefered(true); + factory.setCopyMessageOnSend(false); + + Connection connection = factory.createConnection(); + Session session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(destination); + connection.start(); + consumerStarted.countDown(); + ActiveMQObjectMessage message = (ActiveMQObjectMessage) consumer.receive(30000); + if (message != null) { + MyObject object = (MyObject) message.getObject(); + LOG.info("Got message " + object.getMessage()); + numReceived.incrementAndGet(); + } + consumer.close(); } - }; - - assertTrue("consumers started", consumerStarted.await(10, TimeUnit.SECONDS)); - producingThread.start(); - - vmConsumerThread.join(); - producingThread.join(); - - assertEquals("writeObject called", 0, obj.getWriteObjectCalled()); - assertEquals("readObject called", 0, obj.getReadObjectCalled()); - assertEquals("readObjectNoData called", 0, obj.getReadObjectNoDataCalled()); - - assertEquals("Got expected messages", 1, numReceived.get()); - assertTrue("no unexpected exceptions: " + exceptions, exceptions.isEmpty()); - } - - public void testSendNotSerializeableObjectMessageOverTcp() throws Exception { - final ActiveMQDestination destination = new ActiveMQTopic("testTopic"); - final MyObject obj = new MyObject("A message"); - - final CountDownLatch consumerStarted = new CountDownLatch(3); - final Vector exceptions = new Vector(); - Thread vmConsumerThread = new Thread("Consumer Thread") { - public void run() { - try { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - factory.setOptimizedMessageDispatch(true); - factory.setObjectMessageSerializationDefered(true); - factory.setCopyMessageOnSend(false); - - Connection connection = factory.createConnection(); - Session session = (ActiveMQSession)connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); - connection.start(); - consumerStarted.countDown(); - ActiveMQObjectMessage message = (ActiveMQObjectMessage)consumer.receive(30000); - if ( message != null ) { - MyObject object = (MyObject)message.getObject(); - LOG.info("Got message " + object.getMessage()); - numReceived.incrementAndGet(); - } - consumer.close(); - } catch (Throwable ex) { - exceptions.add(ex); - } - } - }; - vmConsumerThread.start(); - - Thread tcpConsumerThread = new Thread("Consumer Thread") { - public void run() { - try { - - ActiveMQConnectionFactory factory = - new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri()); - factory.setOptimizedMessageDispatch(true); - - Connection connection = factory.createConnection(); - Session session = (ActiveMQSession)connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); - connection.start(); - consumerStarted.countDown(); - ActiveMQObjectMessage message = (ActiveMQObjectMessage)consumer.receive(30000); - if ( message != null ) { - MyObject object = (MyObject)message.getObject(); - LOG.info("Got message " + object.getMessage()); - numReceived.incrementAndGet(); - assertEquals("readObject called", 1, object.getReadObjectCalled()); - } - consumer.close(); - } catch (Throwable ex) { - exceptions.add(ex); - } - } - }; - tcpConsumerThread.start(); - - - Thread notherVmConsumerThread = new Thread("Consumer Thread") { - public void run() { - try { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - factory.setOptimizedMessageDispatch(true); - factory.setObjectMessageSerializationDefered(true); - factory.setCopyMessageOnSend(false); - - Connection connection = factory.createConnection(); - Session session = (ActiveMQSession)connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); - connection.start(); - consumerStarted.countDown(); - ActiveMQObjectMessage message = (ActiveMQObjectMessage)consumer.receive(30000); - if ( message != null ) { - MyObject object = (MyObject)message.getObject(); - LOG.info("Got message " + object.getMessage()); - numReceived.incrementAndGet(); - } - consumer.close(); - } catch (Throwable ex) { - exceptions.add(ex); - } + catch (Throwable ex) { + exceptions.add(ex); } - }; - notherVmConsumerThread.start(); + } + }; + vmConsumerThread.start(); - Thread producingThread = new Thread("Producing Thread") { - public void run() { - try { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - factory.setOptimizedMessageDispatch(true); - factory.setObjectMessageSerializationDefered(true); - factory.setCopyMessageOnSend(false); + Thread producingThread = new Thread("Producing Thread") { + public void run() { + try { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + factory.setOptimizedMessageDispatch(true); + factory.setObjectMessageSerializationDefered(true); + factory.setCopyMessageOnSend(false); - Connection connection = factory.createConnection(); - Session session = (ActiveMQSession)connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - ActiveMQObjectMessage message = (ActiveMQObjectMessage)session.createObjectMessage(); - message.setObject(obj); - producer.send(message); - producer.close(); - } catch (Throwable ex) { - exceptions.add(ex); - } + Connection connection = factory.createConnection(); + Session session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + ActiveMQObjectMessage message = (ActiveMQObjectMessage) session.createObjectMessage(); + message.setObject(obj); + producer.send(message); + producer.close(); } - }; + catch (Throwable ex) { + exceptions.add(ex); + } + } + }; - assertTrue("consumers started", consumerStarted.await(10, TimeUnit.SECONDS)); - producingThread.start(); - - vmConsumerThread.join(); - tcpConsumerThread.join(); - notherVmConsumerThread.join(); - producingThread.join(); + assertTrue("consumers started", consumerStarted.await(10, TimeUnit.SECONDS)); + producingThread.start(); - assertEquals("writeObject called", 1, obj.getWriteObjectCalled()); - assertEquals("readObject called", 0, obj.getReadObjectCalled()); - assertEquals("readObjectNoData called", 0, obj.getReadObjectNoDataCalled()); + vmConsumerThread.join(); + producingThread.join(); - assertEquals("Got expected messages", 3, numReceived.get()); - assertTrue("no unexpected exceptions: " + exceptions, exceptions.isEmpty()); - } + assertEquals("writeObject called", 0, obj.getWriteObjectCalled()); + assertEquals("readObject called", 0, obj.getReadObjectCalled()); + assertEquals("readObjectNoData called", 0, obj.getReadObjectNoDataCalled()); - private BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.addConnector("tcp://localhost:0"); - - broker.start(); - broker.waitUntilStarted(); - return broker; - } + assertEquals("Got expected messages", 1, numReceived.get()); + assertTrue("no unexpected exceptions: " + exceptions, exceptions.isEmpty()); + } - protected void tearDown() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } + public void testSendNotSerializeableObjectMessageOverTcp() throws Exception { + final ActiveMQDestination destination = new ActiveMQTopic("testTopic"); + final MyObject obj = new MyObject("A message"); + + final CountDownLatch consumerStarted = new CountDownLatch(3); + final Vector exceptions = new Vector(); + Thread vmConsumerThread = new Thread("Consumer Thread") { + public void run() { + try { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + factory.setOptimizedMessageDispatch(true); + factory.setObjectMessageSerializationDefered(true); + factory.setCopyMessageOnSend(false); + + Connection connection = factory.createConnection(); + Session session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(destination); + connection.start(); + consumerStarted.countDown(); + ActiveMQObjectMessage message = (ActiveMQObjectMessage) consumer.receive(30000); + if (message != null) { + MyObject object = (MyObject) message.getObject(); + LOG.info("Got message " + object.getMessage()); + numReceived.incrementAndGet(); + } + consumer.close(); + } + catch (Throwable ex) { + exceptions.add(ex); + } + } + }; + vmConsumerThread.start(); + + Thread tcpConsumerThread = new Thread("Consumer Thread") { + public void run() { + try { + + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri()); + factory.setOptimizedMessageDispatch(true); + + Connection connection = factory.createConnection(); + Session session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(destination); + connection.start(); + consumerStarted.countDown(); + ActiveMQObjectMessage message = (ActiveMQObjectMessage) consumer.receive(30000); + if (message != null) { + MyObject object = (MyObject) message.getObject(); + LOG.info("Got message " + object.getMessage()); + numReceived.incrementAndGet(); + assertEquals("readObject called", 1, object.getReadObjectCalled()); + } + consumer.close(); + } + catch (Throwable ex) { + exceptions.add(ex); + } + } + }; + tcpConsumerThread.start(); + + Thread notherVmConsumerThread = new Thread("Consumer Thread") { + public void run() { + try { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + factory.setOptimizedMessageDispatch(true); + factory.setObjectMessageSerializationDefered(true); + factory.setCopyMessageOnSend(false); + + Connection connection = factory.createConnection(); + Session session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(destination); + connection.start(); + consumerStarted.countDown(); + ActiveMQObjectMessage message = (ActiveMQObjectMessage) consumer.receive(30000); + if (message != null) { + MyObject object = (MyObject) message.getObject(); + LOG.info("Got message " + object.getMessage()); + numReceived.incrementAndGet(); + } + consumer.close(); + } + catch (Throwable ex) { + exceptions.add(ex); + } + } + }; + notherVmConsumerThread.start(); + + Thread producingThread = new Thread("Producing Thread") { + public void run() { + try { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + factory.setOptimizedMessageDispatch(true); + factory.setObjectMessageSerializationDefered(true); + factory.setCopyMessageOnSend(false); + + Connection connection = factory.createConnection(); + Session session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(destination); + ActiveMQObjectMessage message = (ActiveMQObjectMessage) session.createObjectMessage(); + message.setObject(obj); + producer.send(message); + producer.close(); + } + catch (Throwable ex) { + exceptions.add(ex); + } + } + }; + + assertTrue("consumers started", consumerStarted.await(10, TimeUnit.SECONDS)); + producingThread.start(); + + vmConsumerThread.join(); + tcpConsumerThread.join(); + notherVmConsumerThread.join(); + producingThread.join(); + + assertEquals("writeObject called", 1, obj.getWriteObjectCalled()); + assertEquals("readObject called", 0, obj.getReadObjectCalled()); + assertEquals("readObjectNoData called", 0, obj.getReadObjectNoDataCalled()); + + assertEquals("Got expected messages", 3, numReceived.get()); + assertTrue("no unexpected exceptions: " + exceptions, exceptions.isEmpty()); + } + + private BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setPersistent(false); + broker.setUseJmx(false); + broker.addConnector("tcp://localhost:0"); + + broker.start(); + broker.waitUntilStarted(); + return broker; + } + + protected void tearDown() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ProducerConsumerTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ProducerConsumerTestSupport.java index ce0c135f64..fdc54c0d13 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ProducerConsumerTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ProducerConsumerTestSupport.java @@ -22,35 +22,33 @@ import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; - /** * Base class for simple test cases using a single connection, session * producer and consumer - * - * */ public class ProducerConsumerTestSupport extends TestSupport { - protected Connection connection; - protected Session session; - protected MessageProducer producer; - protected MessageConsumer consumer; - protected Destination destination; - protected void setUp() throws Exception { - super.setUp(); - connection = createConnection(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - destination = this.createDestination(getSubject()); - producer = session.createProducer(destination); - consumer = session.createConsumer(destination); - connection.start(); - } + protected Connection connection; + protected Session session; + protected MessageProducer producer; + protected MessageConsumer consumer; + protected Destination destination; - protected void tearDown() throws Exception { - consumer.close(); - producer.close(); - session.close(); - connection.close(); - super.tearDown(); - } + protected void setUp() throws Exception { + super.setUp(); + connection = createConnection(); + session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + destination = this.createDestination(getSubject()); + producer = session.createProducer(destination); + consumer = session.createConsumer(destination); + connection.start(); + } + + protected void tearDown() throws Exception { + consumer.close(); + producer.close(); + session.close(); + connection.close(); + super.tearDown(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnDurableTopicConsumedMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnDurableTopicConsumedMessageTest.java index c701301a3e..9481410fa8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnDurableTopicConsumedMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnDurableTopicConsumedMessageTest.java @@ -17,12 +17,12 @@ package org.apache.activemq.usecases; /** - * + * */ public class PublishOnDurableTopicConsumedMessageTest extends PublishOnTopicConsumedMessageTest { - protected void setUp() throws Exception { - this.durable = true; - super.setUp(); - } + protected void setUp() throws Exception { + this.durable = true; + super.setUp(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnQueueConsumedMessageInTransactionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnQueueConsumedMessageInTransactionTest.java index ae203b0471..afa1c95e5d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnQueueConsumedMessageInTransactionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnQueueConsumedMessageInTransactionTest.java @@ -32,6 +32,7 @@ import javax.jms.ObjectMessage; import javax.jms.Session; import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.util.IOHelper; @@ -40,147 +41,152 @@ import org.slf4j.LoggerFactory; public final class PublishOnQueueConsumedMessageInTransactionTest extends TestCase implements MessageListener { - private static final Logger LOG = LoggerFactory.getLogger(PublishOnQueueConsumedMessageInTransactionTest.class); + private static final Logger LOG = LoggerFactory.getLogger(PublishOnQueueConsumedMessageInTransactionTest.class); - private Session producerSession; - private Session consumerSession; - private Destination queue; - private ActiveMQConnectionFactory factory; - private MessageProducer producer; - private MessageConsumer consumer; - private Connection connection; - private ObjectMessage objectMessage; - private List messages = createConcurrentList(); - private final Object lock = new Object(); - private String[] data; - private String dataFileRoot = IOHelper.getDefaultDataDirectory(); - private int messageCount = 3; - private String url = "vm://localhost"; + private Session producerSession; + private Session consumerSession; + private Destination queue; + private ActiveMQConnectionFactory factory; + private MessageProducer producer; + private MessageConsumer consumer; + private Connection connection; + private ObjectMessage objectMessage; + private List messages = createConcurrentList(); + private final Object lock = new Object(); + private String[] data; + private String dataFileRoot = IOHelper.getDefaultDataDirectory(); + private int messageCount = 3; + private String url = "vm://localhost"; - // Invalid acknowledgment warning can be viewed on the console of a remote - // broker - // The warning message is not thrown back to the client - // private String url = "tcp://localhost:61616"; + // Invalid acknowledgment warning can be viewed on the console of a remote + // broker + // The warning message is not thrown back to the client + // private String url = "tcp://localhost:61616"; - protected void setUp() throws Exception { - File dataFile = new File(dataFileRoot); - recursiveDelete(dataFile); - try { - factory = new ActiveMQConnectionFactory(url); - connection = factory.createConnection(); - producerSession = connection.createSession(true, Session.SESSION_TRANSACTED); - consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED); - queue = new ActiveMQQueue("FOO.BAR"); - data = new String[messageCount]; + protected void setUp() throws Exception { + File dataFile = new File(dataFileRoot); + recursiveDelete(dataFile); + try { + factory = new ActiveMQConnectionFactory(url); + connection = factory.createConnection(); + producerSession = connection.createSession(true, Session.SESSION_TRANSACTED); + consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED); + queue = new ActiveMQQueue("FOO.BAR"); + data = new String[messageCount]; - for (int i = 0; i < messageCount; i++) { - data[i] = "Message : " + i; - } - } catch (JMSException je) { - fail("Error setting up connection : " + je.toString()); - } - } + for (int i = 0; i < messageCount; i++) { + data[i] = "Message : " + i; + } + } + catch (JMSException je) { + fail("Error setting up connection : " + je.toString()); + } + } - public void testSendReceive() throws Exception { - sendMessage(); + public void testSendReceive() throws Exception { + sendMessage(); - connection.start(); - consumer = consumerSession.createConsumer(queue); - consumer.setMessageListener(this); - waitForMessagesToBeDelivered(); - assertEquals("Messages received doesn't equal messages sent", messages.size(), data.length); + connection.start(); + consumer = consumerSession.createConsumer(queue); + consumer.setMessageListener(this); + waitForMessagesToBeDelivered(); + assertEquals("Messages received doesn't equal messages sent", messages.size(), data.length); - } + } - protected void sendMessage() throws JMSException { - messages.clear(); - try { - for (int i = 0; i < data.length; ++i) { - producer = producerSession.createProducer(queue); - objectMessage = producerSession.createObjectMessage(data[i]); - producer.send(objectMessage); - producerSession.commit(); - LOG.info("sending message :" + objectMessage); - } - } catch (Exception e) { - if (producerSession != null) { - producerSession.rollback(); - LOG.info("rollback"); - producerSession.close(); - } + protected void sendMessage() throws JMSException { + messages.clear(); + try { + for (int i = 0; i < data.length; ++i) { + producer = producerSession.createProducer(queue); + objectMessage = producerSession.createObjectMessage(data[i]); + producer.send(objectMessage); + producerSession.commit(); + LOG.info("sending message :" + objectMessage); + } + } + catch (Exception e) { + if (producerSession != null) { + producerSession.rollback(); + LOG.info("rollback"); + producerSession.close(); + } - e.printStackTrace(); - } - } + e.printStackTrace(); + } + } - public synchronized void onMessage(Message m) { - try { - objectMessage = (ObjectMessage)m; - consumeMessage(objectMessage, messages); + public synchronized void onMessage(Message m) { + try { + objectMessage = (ObjectMessage) m; + consumeMessage(objectMessage, messages); - LOG.info("consumer received message :" + objectMessage); - consumerSession.commit(); + LOG.info("consumer received message :" + objectMessage); + consumerSession.commit(); - } catch (Exception e) { + } + catch (Exception e) { + try { + consumerSession.rollback(); + LOG.info("rolled back transaction"); + } + catch (JMSException e1) { + LOG.info(e1.toString()); + e1.printStackTrace(); + } + LOG.info(e.toString()); + e.printStackTrace(); + } + } + + protected void consumeMessage(Message message, List messageList) { + messageList.add(message); + if (messageList.size() >= data.length) { + synchronized (lock) { + lock.notifyAll(); + } + } + + } + + protected List createConcurrentList() { + return Collections.synchronizedList(new ArrayList()); + } + + protected void waitForMessagesToBeDelivered() { + long maxWaitTime = 5000; + long waitTime = maxWaitTime; + long start = (maxWaitTime <= 0) ? 0 : System.currentTimeMillis(); + + synchronized (lock) { + while (messages.size() <= data.length && waitTime >= 0) { try { - consumerSession.rollback(); - LOG.info("rolled back transaction"); - } catch (JMSException e1) { - LOG.info(e1.toString()); - e1.printStackTrace(); + lock.wait(200); } - LOG.info(e.toString()); - e.printStackTrace(); - } - } - - protected void consumeMessage(Message message, List messageList) { - messageList.add(message); - if (messageList.size() >= data.length) { - synchronized (lock) { - lock.notifyAll(); + catch (InterruptedException e) { + e.printStackTrace(); } - } - } + waitTime = maxWaitTime - (System.currentTimeMillis() - start); + } + } + } - protected List createConcurrentList() { - return Collections.synchronizedList(new ArrayList()); - } + protected static void recursiveDelete(File file) { + if (file.isDirectory()) { + File[] files = file.listFiles(); + for (int i = 0; i < files.length; i++) { + recursiveDelete(files[i]); + } + } + file.delete(); + } - protected void waitForMessagesToBeDelivered() { - long maxWaitTime = 5000; - long waitTime = maxWaitTime; - long start = (maxWaitTime <= 0) ? 0 : System.currentTimeMillis(); + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + } - synchronized (lock) { - while (messages.size() <= data.length && waitTime >= 0) { - try { - lock.wait(200); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - waitTime = maxWaitTime - (System.currentTimeMillis() - start); - } - } - } - - protected static void recursiveDelete(File file) { - if (file.isDirectory()) { - File[] files = file.listFiles(); - for (int i = 0; i < files.length; i++) { - recursiveDelete(files[i]); - } - } - file.delete(); - } - - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - - super.tearDown(); - } + super.tearDown(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnQueueConsumedMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnQueueConsumedMessageTest.java index 584af37edc..67128669bf 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnQueueConsumedMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnQueueConsumedMessageTest.java @@ -17,12 +17,12 @@ package org.apache.activemq.usecases; /** - * + * */ public class PublishOnQueueConsumedMessageTest extends PublishOnTopicConsumedMessageTest { - protected void setUp() throws Exception { - topic = false; - super.setUp(); - } + protected void setUp() throws Exception { + topic = false; + super.setUp(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnQueueConsumedMessageUsingActivemqXMLTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnQueueConsumedMessageUsingActivemqXMLTest.java index 0ccbb685f7..f9b15b2e04 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnQueueConsumedMessageUsingActivemqXMLTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnQueueConsumedMessageUsingActivemqXMLTest.java @@ -28,63 +28,62 @@ import org.springframework.core.io.Resource; /** * Test Publish/Consume queue using the release activemq.xml configuration file - * - * */ public class PublishOnQueueConsumedMessageUsingActivemqXMLTest extends PublishOnTopicConsumedMessageTest { - protected static final String JOURNAL_ROOT = "../data/"; - private static final transient Logger LOG = LoggerFactory.getLogger(PublishOnQueueConsumedMessageUsingActivemqXMLTest.class); - BrokerService broker; - /** - * Use the transportConnector uri configured on the activemq.xml - * - * @return ActiveMQConnectionFactory - * @throws Exception - */ - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("tcp://localhost:61616"); - } + protected static final String JOURNAL_ROOT = "../data/"; + private static final transient Logger LOG = LoggerFactory.getLogger(PublishOnQueueConsumedMessageUsingActivemqXMLTest.class); + BrokerService broker; - /** - * Sets up a test where the producer and consumer have their own connection. - * - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception { - File journalFile = new File(JOURNAL_ROOT); - recursiveDelete(journalFile); - // Create broker from resource - LOG.info("Creating broker... "); - broker = createBroker("org/apache/activemq/usecases/activemq.xml"); - LOG.info("Success"); - super.setUp(); - } - - /* - * Stops the Broker - * @see junit.framework.TestCase#tearDown() + /** + * Use the transportConnector uri configured on the activemq.xml + * + * @return ActiveMQConnectionFactory + * @throws Exception */ - protected void tearDown() throws Exception { - LOG.info("Closing Broker"); - if (broker != null) { - broker.stop(); - } - LOG.info("Broker closed..."); - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory("tcp://localhost:61616"); + } - protected BrokerService createBroker(String resource) throws Exception { - return createBroker(new ClassPathResource(resource)); - } + /** + * Sets up a test where the producer and consumer have their own connection. + * + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + File journalFile = new File(JOURNAL_ROOT); + recursiveDelete(journalFile); + // Create broker from resource + LOG.info("Creating broker... "); + broker = createBroker("org/apache/activemq/usecases/activemq.xml"); + LOG.info("Success"); + super.setUp(); + } - protected BrokerService createBroker(Resource resource) throws Exception { - BrokerFactoryBean factory = new BrokerFactoryBean(resource); - factory.afterPropertiesSet(); + /* + * Stops the Broker + * @see junit.framework.TestCase#tearDown() + */ + protected void tearDown() throws Exception { + LOG.info("Closing Broker"); + if (broker != null) { + broker.stop(); + } + LOG.info("Broker closed..."); + } - BrokerService broker = factory.getBroker(); + protected BrokerService createBroker(String resource) throws Exception { + return createBroker(new ClassPathResource(resource)); + } - //assertTrue("Should have a broker!", broker != null); + protected BrokerService createBroker(Resource resource) throws Exception { + BrokerFactoryBean factory = new BrokerFactoryBean(resource); + factory.afterPropertiesSet(); - return broker; - } + BrokerService broker = factory.getBroker(); + + //assertTrue("Should have a broker!", broker != null); + + return broker; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnTemporaryQueueConsumedMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnTemporaryQueueConsumedMessageTest.java index d2ee38f768..4773dfc80c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnTemporaryQueueConsumedMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnTemporaryQueueConsumedMessageTest.java @@ -19,13 +19,13 @@ package org.apache.activemq.usecases; import javax.jms.DeliveryMode; /** - * + * */ public class PublishOnTemporaryQueueConsumedMessageTest extends PublishOnTopicConsumedMessageTest { - protected void setUp() throws Exception { - topic = false; - deliveryMode = DeliveryMode.NON_PERSISTENT; - super.setUp(); - } + protected void setUp() throws Exception { + topic = false; + deliveryMode = DeliveryMode.NON_PERSISTENT; + super.setUp(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnTopicConsumedMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnTopicConsumedMessageTest.java index f28a48033a..6a891b1193 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnTopicConsumedMessageTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnTopicConsumedMessageTest.java @@ -26,42 +26,44 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class PublishOnTopicConsumedMessageTest extends JmsTopicSendReceiveWithTwoConnectionsTest { - private static final Logger LOG = LoggerFactory.getLogger(PublishOnTopicConsumedMessageTest.class); + private static final Logger LOG = LoggerFactory.getLogger(PublishOnTopicConsumedMessageTest.class); - private MessageProducer replyProducer; + private MessageProducer replyProducer; - public synchronized void onMessage(Message message) { + public synchronized void onMessage(Message message) { - // lets resend the message somewhere else - try { - Message msgCopy = (Message)((org.apache.activemq.command.Message)message).copy(); - replyProducer.send(msgCopy); + // lets resend the message somewhere else + try { + Message msgCopy = (Message) ((org.apache.activemq.command.Message) message).copy(); + replyProducer.send(msgCopy); - // log.info("Sending reply: " + message); - super.onMessage(message); - } catch (JMSException e) { - LOG.info("Failed to send message: " + e); - e.printStackTrace(); - } - } + // log.info("Sending reply: " + message); + super.onMessage(message); + } + catch (JMSException e) { + LOG.info("Failed to send message: " + e); + e.printStackTrace(); + } + } - protected void setUp() throws Exception { - super.setUp(); + protected void setUp() throws Exception { + super.setUp(); - Destination replyDestination = null; + Destination replyDestination = null; - if (topic) { - replyDestination = receiveSession.createTopic("REPLY." + getSubject()); - } else { - replyDestination = receiveSession.createQueue("REPLY." + getSubject()); - } + if (topic) { + replyDestination = receiveSession.createTopic("REPLY." + getSubject()); + } + else { + replyDestination = receiveSession.createQueue("REPLY." + getSubject()); + } - replyProducer = receiveSession.createProducer(replyDestination); - LOG.info("Created replyProducer: " + replyProducer); + replyProducer = receiveSession.createProducer(replyDestination); + LOG.info("Created replyProducer: " + replyProducer); - } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnTopicConsumerMessageUsingActivemqXMLTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnTopicConsumerMessageUsingActivemqXMLTest.java index d904d12e10..e1b3518b1f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnTopicConsumerMessageUsingActivemqXMLTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnTopicConsumerMessageUsingActivemqXMLTest.java @@ -28,64 +28,63 @@ import org.springframework.core.io.Resource; /** * Test Publish/Consume topic using the release activemq.xml configuration file - * - * */ public class PublishOnTopicConsumerMessageUsingActivemqXMLTest extends PublishOnTopicConsumedMessageTest { - protected static final String JOURNAL_ROOT = "../data/"; - private static final transient Logger LOG = LoggerFactory.getLogger(PublishOnTopicConsumerMessageUsingActivemqXMLTest.class); - BrokerService broker; + protected static final String JOURNAL_ROOT = "../data/"; + private static final transient Logger LOG = LoggerFactory.getLogger(PublishOnTopicConsumerMessageUsingActivemqXMLTest.class); - /** - * Use the transportConnector uri configured on the activemq.xml - * - * @return ActiveMQConnectionFactory - * @throws Exception - */ - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("tcp://localhost:61616"); - } + BrokerService broker; - /** - * Sets up a test where the producer and consumer have their own connection. - * - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception { - File journalFile = new File(JOURNAL_ROOT); - recursiveDelete(journalFile); - // Create broker from resource - LOG.info("Creating broker... "); - broker = createBroker("org/apache/activemq/usecases/activemq.xml"); - LOG.info("Success"); - super.setUp(); - } - - /* - * Stops the Broker - * @see junit.framework.TestCase#tearDown() + /** + * Use the transportConnector uri configured on the activemq.xml + * + * @return ActiveMQConnectionFactory + * @throws Exception */ - protected void tearDown() throws Exception { - LOG.info("Closing Broker"); - if (broker != null) { - broker.stop(); - } - LOG.info("Broker closed..."); - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory("tcp://localhost:61616"); + } - protected BrokerService createBroker(String resource) throws Exception { - return createBroker(new ClassPathResource(resource)); - } + /** + * Sets up a test where the producer and consumer have their own connection. + * + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + File journalFile = new File(JOURNAL_ROOT); + recursiveDelete(journalFile); + // Create broker from resource + LOG.info("Creating broker... "); + broker = createBroker("org/apache/activemq/usecases/activemq.xml"); + LOG.info("Success"); + super.setUp(); + } - protected BrokerService createBroker(Resource resource) throws Exception { - BrokerFactoryBean factory = new BrokerFactoryBean(resource); - factory.afterPropertiesSet(); + /* + * Stops the Broker + * @see junit.framework.TestCase#tearDown() + */ + protected void tearDown() throws Exception { + LOG.info("Closing Broker"); + if (broker != null) { + broker.stop(); + } + LOG.info("Broker closed..."); + } - BrokerService broker = factory.getBroker(); + protected BrokerService createBroker(String resource) throws Exception { + return createBroker(new ClassPathResource(resource)); + } - //assertTrue("Should have a broker!", broker != null); + protected BrokerService createBroker(Resource resource) throws Exception { + BrokerFactoryBean factory = new BrokerFactoryBean(resource); + factory.afterPropertiesSet(); - return broker; - } + BrokerService broker = factory.getBroker(); + + //assertTrue("Should have a broker!", broker != null); + + return broker; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueBrowsingLevelDBTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueBrowsingLevelDBTest.java index 55a9bfd8fb..8102dbb550 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueBrowsingLevelDBTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueBrowsingLevelDBTest.java @@ -24,13 +24,13 @@ import java.io.IOException; public class QueueBrowsingLevelDBTest extends QueueBrowsingTest { - @Override - public BrokerService createBroker() throws IOException { - BrokerService broker = super.createBroker(); - LevelDBStore store = new LevelDBStore(); - store.setDirectory(new File("target/test-data/leveldb")); - broker.setPersistenceAdapter(store); - return broker; - } + @Override + public BrokerService createBroker() throws IOException { + BrokerService broker = super.createBroker(); + LevelDBStore store = new LevelDBStore(); + store.setDirectory(new File("target/test-data/leveldb")); + broker.setPersistenceAdapter(store); + return broker; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueBrowsingLimitTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueBrowsingLimitTest.java index 15df78cf53..ecd3c48b1e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueBrowsingLimitTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueBrowsingLimitTest.java @@ -24,6 +24,7 @@ import javax.jms.Message; import javax.jms.MessageProducer; import javax.jms.QueueBrowser; import javax.jms.Session; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.TransportConnector; @@ -36,78 +37,76 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import static org.junit.Assert.assertEquals; public class QueueBrowsingLimitTest { - private static final Logger LOG = LoggerFactory.getLogger(QueueBrowsingLimitTest.class); + private static final Logger LOG = LoggerFactory.getLogger(QueueBrowsingLimitTest.class); - private BrokerService broker; - private URI connectUri; - private ActiveMQConnectionFactory factory; - private final int browserLimit = 300; + private BrokerService broker; + private URI connectUri; + private ActiveMQConnectionFactory factory; + private final int browserLimit = 300; + @Before + public void startBroker() throws Exception { + broker = createBroker(); + TransportConnector connector = broker.addConnector("tcp://0.0.0.0:0"); + broker.deleteAllMessages(); + broker.start(); + broker.waitUntilStarted(); - @Before - public void startBroker() throws Exception { - broker = createBroker(); - TransportConnector connector = broker.addConnector("tcp://0.0.0.0:0"); - broker.deleteAllMessages(); - broker.start(); - broker.waitUntilStarted(); + PolicyEntry policy = new PolicyEntry(); + policy.setMaxBrowsePageSize(browserLimit); + broker.setDestinationPolicy(new PolicyMap()); + broker.getDestinationPolicy().setDefaultEntry(policy); - PolicyEntry policy = new PolicyEntry(); - policy.setMaxBrowsePageSize(browserLimit); - broker.setDestinationPolicy(new PolicyMap()); - broker.getDestinationPolicy().setDefaultEntry(policy); + connectUri = connector.getConnectUri(); + factory = new ActiveMQConnectionFactory(connectUri); - connectUri = connector.getConnectUri(); - factory = new ActiveMQConnectionFactory(connectUri); + } - } + public BrokerService createBroker() throws IOException { + return new BrokerService(); + } - public BrokerService createBroker() throws IOException { - return new BrokerService(); - } + @After + public void stopBroker() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + } - @After - public void stopBroker() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } + @Test + public void testBrowsingLimited() throws Exception { - @Test - public void testBrowsingLimited() throws Exception { + int messageToSend = 470; - int messageToSend = 470; + ActiveMQQueue queue = new ActiveMQQueue("TEST"); + Connection connection = factory.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(queue); - ActiveMQQueue queue = new ActiveMQQueue("TEST"); - Connection connection = factory.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(queue); + String data = ""; + for (int i = 0; i < 1024 * 2; i++) { + data += "x"; + } - String data = ""; - for( int i=0; i < 1024*2; i++ ) { - data += "x"; - } + for (int i = 0; i < messageToSend; i++) { + producer.send(session.createTextMessage(data)); + } - for( int i=0; i < messageToSend; i++ ) { - producer.send(session.createTextMessage(data)); - } + QueueBrowser browser = session.createBrowser(queue); + Enumeration enumeration = browser.getEnumeration(); + int received = 0; + while (enumeration.hasMoreElements()) { + Message m = (Message) enumeration.nextElement(); + received++; + LOG.info("Browsed message " + received + ": " + m.getJMSMessageID()); + } - QueueBrowser browser = session.createBrowser(queue); - Enumeration enumeration = browser.getEnumeration(); - int received = 0; - while (enumeration.hasMoreElements()) { - Message m = (Message) enumeration.nextElement(); - received++; - LOG.info("Browsed message " + received + ": " + m.getJMSMessageID()); - } + browser.close(); - browser.close(); - - assertEquals(browserLimit, received); - } + assertEquals(browserLimit, received); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueBrowsingTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueBrowsingTest.java index 29b6e7297c..5afaf7fc56 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueBrowsingTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueBrowsingTest.java @@ -19,7 +19,6 @@ package org.apache.activemq.usecases; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.net.URI; import java.util.Enumeration; @@ -46,171 +45,173 @@ import org.slf4j.LoggerFactory; public class QueueBrowsingTest { - private static final Logger LOG = LoggerFactory.getLogger(QueueBrowsingTest.class); + private static final Logger LOG = LoggerFactory.getLogger(QueueBrowsingTest.class); - private BrokerService broker; - private URI connectUri; - private ActiveMQConnectionFactory factory; - private final int maxPageSize = 100; + private BrokerService broker; + private URI connectUri; + private ActiveMQConnectionFactory factory; + private final int maxPageSize = 100; - @Before - public void startBroker() throws Exception { - broker = createBroker(); - TransportConnector connector = broker.addConnector("tcp://0.0.0.0:0"); - broker.deleteAllMessages(); - broker.start(); - broker.waitUntilStarted(); + @Before + public void startBroker() throws Exception { + broker = createBroker(); + TransportConnector connector = broker.addConnector("tcp://0.0.0.0:0"); + broker.deleteAllMessages(); + broker.start(); + broker.waitUntilStarted(); - PolicyEntry policy = new PolicyEntry(); - policy.setMaxPageSize(maxPageSize); - broker.setDestinationPolicy(new PolicyMap()); - broker.getDestinationPolicy().setDefaultEntry(policy); + PolicyEntry policy = new PolicyEntry(); + policy.setMaxPageSize(maxPageSize); + broker.setDestinationPolicy(new PolicyMap()); + broker.getDestinationPolicy().setDefaultEntry(policy); - connectUri = connector.getConnectUri(); - factory = new ActiveMQConnectionFactory(connectUri); - } + connectUri = connector.getConnectUri(); + factory = new ActiveMQConnectionFactory(connectUri); + } - public BrokerService createBroker() throws IOException { - return new BrokerService(); - } + public BrokerService createBroker() throws IOException { + return new BrokerService(); + } - @After - public void stopBroker() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } + @After + public void stopBroker() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + } - @Test - public void testBrowsing() throws JMSException { + @Test + public void testBrowsing() throws JMSException { - int messageToSend = 370; + int messageToSend = 370; - ActiveMQQueue queue = new ActiveMQQueue("TEST"); - Connection connection = factory.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(queue); + ActiveMQQueue queue = new ActiveMQQueue("TEST"); + Connection connection = factory.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(queue); - String data = ""; - for( int i=0; i < 1024*2; i++ ) { - data += "x"; - } + String data = ""; + for (int i = 0; i < 1024 * 2; i++) { + data += "x"; + } - for( int i=0; i < messageToSend; i++ ) { - producer.send(session.createTextMessage(data)); - } + for (int i = 0; i < messageToSend; i++) { + producer.send(session.createTextMessage(data)); + } - QueueBrowser browser = session.createBrowser(queue); - Enumeration enumeration = browser.getEnumeration(); - int received = 0; - while (enumeration.hasMoreElements()) { - Message m = (Message) enumeration.nextElement(); - received++; - LOG.info("Browsed message " + received + ": " + m.getJMSMessageID()); - } + QueueBrowser browser = session.createBrowser(queue); + Enumeration enumeration = browser.getEnumeration(); + int received = 0; + while (enumeration.hasMoreElements()) { + Message m = (Message) enumeration.nextElement(); + received++; + LOG.info("Browsed message " + received + ": " + m.getJMSMessageID()); + } - browser.close(); + browser.close(); - assertEquals(messageToSend, received); - } + assertEquals(messageToSend, received); + } - @Test - public void testBrowseConcurrent() throws Exception { - final int messageToSend = 370; + @Test + public void testBrowseConcurrent() throws Exception { + final int messageToSend = 370; - final ActiveMQQueue queue = new ActiveMQQueue("TEST"); - Connection connection = factory.createConnection(); - connection.start(); - final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final ActiveMQQueue queue = new ActiveMQQueue("TEST"); + Connection connection = factory.createConnection(); + connection.start(); + final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(queue); + MessageProducer producer = session.createProducer(queue); - String data = ""; - for( int i=0; i < 1024*2; i++ ) { - data += "x"; - } + String data = ""; + for (int i = 0; i < 1024 * 2; i++) { + data += "x"; + } - for( int i=0; i < messageToSend; i++ ) { - producer.send(session.createTextMessage(data)); - } + for (int i = 0; i < messageToSend; i++) { + producer.send(session.createTextMessage(data)); + } - Thread browserThread = new Thread() { - @Override - public void run() { - try { - QueueBrowser browser = session.createBrowser(queue); - Enumeration enumeration = browser.getEnumeration(); - int received = 0; - while (enumeration.hasMoreElements()) { - Message m = (Message) enumeration.nextElement(); - received++; - LOG.info("Browsed message " + received + ": " + m.getJMSMessageID()); - } - assertEquals("Browsed all messages", messageToSend, received); - } catch (Exception e) { - e.printStackTrace(); - } + Thread browserThread = new Thread() { + @Override + public void run() { + try { + QueueBrowser browser = session.createBrowser(queue); + Enumeration enumeration = browser.getEnumeration(); + int received = 0; + while (enumeration.hasMoreElements()) { + Message m = (Message) enumeration.nextElement(); + received++; + LOG.info("Browsed message " + received + ": " + m.getJMSMessageID()); + } + assertEquals("Browsed all messages", messageToSend, received); } - }; - - browserThread.start(); - - Thread consumerThread = new Thread() { - @Override - public void run() { - try { - MessageConsumer consumer = session.createConsumer(queue); - int received = 0; - while (true) { - Message m = consumer.receive(1000); - if (m == null) - break; - received++; - } - assertEquals("Consumed all messages", messageToSend, received); - } catch (Exception e) { - e.printStackTrace(); - } + catch (Exception e) { + e.printStackTrace(); } - }; + } + }; - consumerThread.start(); + browserThread.start(); - browserThread.join(); - consumerThread.join(); - } + Thread consumerThread = new Thread() { + @Override + public void run() { + try { + MessageConsumer consumer = session.createConsumer(queue); + int received = 0; + while (true) { + Message m = consumer.receive(1000); + if (m == null) + break; + received++; + } + assertEquals("Consumed all messages", messageToSend, received); + } + catch (Exception e) { + e.printStackTrace(); + } + } + }; - @Test - public void testMemoryLimit() throws Exception { - broker.getSystemUsage().getMemoryUsage().setLimit(16 * 1024); + consumerThread.start(); - int messageToSend = 370; + browserThread.join(); + consumerThread.join(); + } - ActiveMQQueue queue = new ActiveMQQueue("TEST"); - Connection connection = factory.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(queue); + @Test + public void testMemoryLimit() throws Exception { + broker.getSystemUsage().getMemoryUsage().setLimit(16 * 1024); - String data = ""; - for( int i=0; i < 1024*2; i++ ) { - data += "x"; - } + int messageToSend = 370; - for( int i=0; i < messageToSend; i++ ) { - producer.send(session.createTextMessage(data)); - } + ActiveMQQueue queue = new ActiveMQQueue("TEST"); + Connection connection = factory.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(queue); - QueueBrowser browser = session.createBrowser(queue); - Enumeration enumeration = browser.getEnumeration(); - int received = 0; - while (enumeration.hasMoreElements()) { - Message m = (Message) enumeration.nextElement(); - received++; - LOG.info("Browsed message " + received + ": " + m.getJMSMessageID()); - } + String data = ""; + for (int i = 0; i < 1024 * 2; i++) { + data += "x"; + } - browser.close(); - assertTrue("got at least maxPageSize", received >= maxPageSize); - } + for (int i = 0; i < messageToSend; i++) { + producer.send(session.createTextMessage(data)); + } + + QueueBrowser browser = session.createBrowser(queue); + Enumeration enumeration = browser.getEnumeration(); + int received = 0; + while (enumeration.hasMoreElements()) { + Message m = (Message) enumeration.nextElement(); + received++; + LOG.info("Browsed message " + received + ": " + m.getJMSMessageID()); + } + + browser.close(); + assertTrue("got at least maxPageSize", received >= maxPageSize); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueConsumerCloseAndReconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueConsumerCloseAndReconnectTest.java index 73fa27ae52..3ba0bd2591 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueConsumerCloseAndReconnectTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueConsumerCloseAndReconnectTest.java @@ -17,10 +17,11 @@ package org.apache.activemq.usecases; /** - * + * */ public class QueueConsumerCloseAndReconnectTest extends DurableConsumerCloseAndReconnectTest { - protected boolean isTopic() { - return false; - } + + protected boolean isTopic() { + return false; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueDuplicatesTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueDuplicatesTest.java index 1084ce9457..6fcd8ff145 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueDuplicatesTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueDuplicatesTest.java @@ -42,117 +42,122 @@ import org.slf4j.LoggerFactory; public class QueueDuplicatesTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(QueueDuplicatesTest.class); + private static final Logger LOG = LoggerFactory.getLogger(QueueDuplicatesTest.class); - private static DateFormat formatter = new SimpleDateFormat("HH:mm:ss SSS"); - private String brokerUrl; - private String subject; - private Connection brokerConnection; + private static DateFormat formatter = new SimpleDateFormat("HH:mm:ss SSS"); + private String brokerUrl; + private String subject; + private Connection brokerConnection; - public QueueDuplicatesTest(String name) { - super(name); - } + public QueueDuplicatesTest(String name) { + super(name); + } - protected void setUp() throws Exception { - String peerUrl = "peer://localhost:6099"; + protected void setUp() throws Exception { + String peerUrl = "peer://localhost:6099"; - subject = this.getClass().getName(); + subject = this.getClass().getName(); - ActiveMQConnectionFactory fac = createFactory(peerUrl); - brokerConnection = fac.createConnection(); - brokerConnection.start(); - } + ActiveMQConnectionFactory fac = createFactory(peerUrl); + brokerConnection = fac.createConnection(); + brokerConnection.start(); + } - protected void tearDown() throws Exception { - if (brokerConnection != null) { - brokerConnection.close(); - } - } + protected void tearDown() throws Exception { + if (brokerConnection != null) { + brokerConnection.close(); + } + } - public void testDuplicates() { - try { - // Get Session + public void testDuplicates() { + try { + // Get Session + Session session = createSession(brokerConnection); + // create consumer + Destination dest = session.createQueue(subject); + MessageConsumer consumer = session.createConsumer(dest); + // subscribe to queue + consumer.setMessageListener(new SimpleConsumer()); + // create producer + Thread sendingThread = new SendingThread(brokerUrl, subject); + // start producer + sendingThread.start(); + // wait about 5 seconds + Thread.sleep(5000); + // unsubscribe consumer + consumer.close(); + // wait another 5 seconds + Thread.sleep(5000); + // create new consumer + consumer = session.createConsumer(dest); + // subscribe to queue + consumer.setMessageListener(new SimpleConsumer()); + // sleep a little while longer + Thread.sleep(15000); + session.close(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + Session createSession(Connection peerConnection) throws JMSException { + // Connect using peer to peer connection + Session session = peerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + return session; + } + + private ActiveMQConnectionFactory createFactory(String brokerUrl) { + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(); + cf.setBrokerURL(brokerUrl); + + return cf; + } + + private class SendingThread extends Thread { + + private String subject; + + SendingThread(String brokerUrl, String subject) { + this.subject = subject; + setDaemon(false); + } + + public void run() { + try { Session session = createSession(brokerConnection); - // create consumer Destination dest = session.createQueue(subject); - MessageConsumer consumer = session.createConsumer(dest); - // subscribe to queue - consumer.setMessageListener(new SimpleConsumer()); - // create producer - Thread sendingThread = new SendingThread(brokerUrl, subject); - // start producer - sendingThread.start(); - // wait about 5 seconds - Thread.sleep(5000); - // unsubscribe consumer - consumer.close(); - // wait another 5 seconds - Thread.sleep(5000); - // create new consumer - consumer = session.createConsumer(dest); - // subscribe to queue - consumer.setMessageListener(new SimpleConsumer()); - // sleep a little while longer - Thread.sleep(15000); + MessageProducer producer = session.createProducer(dest); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + for (int i = 0; i < 20; i++) { + String txt = "Text Message: " + i; + TextMessage msg = session.createTextMessage(txt); + producer.send(msg); + LOG.info(formatter.format(new Date()) + " Sent ==> " + msg + " to " + subject); + Thread.sleep(1000); + } session.close(); - } catch (Exception e) { + } + catch (Exception e) { e.printStackTrace(); - } - } + } + } + } - Session createSession(Connection peerConnection) throws JMSException { - // Connect using peer to peer connection - Session session = peerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - return session; - } + private static class SimpleConsumer implements MessageListener { - private ActiveMQConnectionFactory createFactory(String brokerUrl) { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(); - cf.setBrokerURL(brokerUrl); + private Map msgs = new HashMap(); - return cf; - } - - private class SendingThread extends Thread { - private String subject; - - SendingThread(String brokerUrl, String subject) { - this.subject = subject; - setDaemon(false); - } - - public void run() { - try { - Session session = createSession(brokerConnection); - Destination dest = session.createQueue(subject); - MessageProducer producer = session.createProducer(dest); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - for (int i = 0; i < 20; i++) { - String txt = "Text Message: " + i; - TextMessage msg = session.createTextMessage(txt); - producer.send(msg); - LOG.info(formatter.format(new Date()) + " Sent ==> " + msg + " to " + subject); - Thread.sleep(1000); - } - session.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - private static class SimpleConsumer implements MessageListener { - private Map msgs = new HashMap(); - - public void onMessage(Message message) { - LOG.info(formatter.format(new Date()) + " SimpleConsumer Message Received: " + message); - try { - String id = message.getJMSMessageID(); - assertNull("Message is duplicate: " + id, msgs.get(id)); - msgs.put(id, message); - } catch (Exception e) { - e.printStackTrace(); - } - } - } + public void onMessage(Message message) { + LOG.info(formatter.format(new Date()) + " SimpleConsumer Message Received: " + message); + try { + String id = message.getJMSMessageID(); + assertNull("Message is duplicate: " + id, msgs.get(id)); + msgs.put(id, message); + } + catch (Exception e) { + e.printStackTrace(); + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueMemoryFullMultiBrokersTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueMemoryFullMultiBrokersTest.java index 42776a48f1..0293121754 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueMemoryFullMultiBrokersTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueMemoryFullMultiBrokersTest.java @@ -35,66 +35,67 @@ import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.usage.SystemUsage; public class QueueMemoryFullMultiBrokersTest extends JmsMultipleBrokersTestSupport { - public static final int BROKER_COUNT = 2; - public static final int MESSAGE_COUNT = 2000; - - public void testQueueNetworkWithConsumerFull() throws Exception { - - bridgeAllBrokers(); - startAllBrokers(); - Destination dest = createDestination("TEST.FOO", false); + public static final int BROKER_COUNT = 2; + public static final int MESSAGE_COUNT = 2000; - sendMessages("Broker1", dest, 50); + public void testQueueNetworkWithConsumerFull() throws Exception { - CountDownLatch latch = new CountDownLatch(MESSAGE_COUNT); - createConsumer("Broker2", dest, latch); - assertConsumersConnect("Broker1", dest, 1, 30000); - sendMessages("Broker1", dest, MESSAGE_COUNT - 50); + bridgeAllBrokers(); + startAllBrokers(); - // Wait for messages to be delivered - assertTrue("Missing " + latch.getCount() + " messages", latch.await(45, TimeUnit.SECONDS)); - - // verify stats, all messages acked - BrokerService broker1 = brokers.get("Broker1").broker; - RegionBroker regionBroker = (RegionBroker) broker1.getRegionBroker(); - // give the acks a chance to flow - Thread.sleep(2000); - Queue internalQueue = (Queue) regionBroker.getDestinations(ActiveMQDestination.transform(dest)).iterator().next(); - - assertTrue("All messages are consumed and acked from source:" + internalQueue, internalQueue.getMessages().isEmpty()); - assertEquals("messages source:" + internalQueue, 0, internalQueue.getDestinationStatistics().getMessages().getCount()); - assertEquals("inflight source:" + internalQueue, 0, internalQueue.getDestinationStatistics().getInflight().getCount()); - } + Destination dest = createDestination("TEST.FOO", false); - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - messageSize = 1024; - - // Setup n brokers - for (int i = 1; i <= BROKER_COUNT; i++) { - createBroker(new URI("broker:()/Broker" + i + "?persistent=false&useJmx=false")); - } - BrokerService broker2 = brokers.get("Broker2").broker; - applyMemoryLimitPolicy(broker2); - } + sendMessages("Broker1", dest, 50); - private void applyMemoryLimitPolicy(BrokerService broker) { - final SystemUsage memoryManager = new SystemUsage(); - memoryManager.getMemoryUsage().setLimit(1024 * 50); // 50 MB - broker.setSystemUsage(memoryManager); + CountDownLatch latch = new CountDownLatch(MESSAGE_COUNT); + createConsumer("Broker2", dest, latch); + assertConsumersConnect("Broker1", dest, 1, 30000); + sendMessages("Broker1", dest, MESSAGE_COUNT - 50); - final List policyEntries = new ArrayList(); - final PolicyEntry entry = new PolicyEntry(); - entry.setQueue(">"); - entry.setMemoryLimit(1024 * 4); // Set to 2 kb - entry.setPendingQueuePolicy(new VMPendingQueueMessageStoragePolicy()); - policyEntries.add(entry); + // Wait for messages to be delivered + assertTrue("Missing " + latch.getCount() + " messages", latch.await(45, TimeUnit.SECONDS)); - final PolicyMap policyMap = new PolicyMap(); - policyMap.setPolicyEntries(policyEntries); - broker.setDestinationPolicy(policyMap); - - } + // verify stats, all messages acked + BrokerService broker1 = brokers.get("Broker1").broker; + RegionBroker regionBroker = (RegionBroker) broker1.getRegionBroker(); + // give the acks a chance to flow + Thread.sleep(2000); + Queue internalQueue = (Queue) regionBroker.getDestinations(ActiveMQDestination.transform(dest)).iterator().next(); + + assertTrue("All messages are consumed and acked from source:" + internalQueue, internalQueue.getMessages().isEmpty()); + assertEquals("messages source:" + internalQueue, 0, internalQueue.getDestinationStatistics().getMessages().getCount()); + assertEquals("inflight source:" + internalQueue, 0, internalQueue.getDestinationStatistics().getInflight().getCount()); + } + + public void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); + messageSize = 1024; + + // Setup n brokers + for (int i = 1; i <= BROKER_COUNT; i++) { + createBroker(new URI("broker:()/Broker" + i + "?persistent=false&useJmx=false")); + } + BrokerService broker2 = brokers.get("Broker2").broker; + applyMemoryLimitPolicy(broker2); + } + + private void applyMemoryLimitPolicy(BrokerService broker) { + final SystemUsage memoryManager = new SystemUsage(); + memoryManager.getMemoryUsage().setLimit(1024 * 50); // 50 MB + broker.setSystemUsage(memoryManager); + + final List policyEntries = new ArrayList(); + final PolicyEntry entry = new PolicyEntry(); + entry.setQueue(">"); + entry.setMemoryLimit(1024 * 4); // Set to 2 kb + entry.setPendingQueuePolicy(new VMPendingQueueMessageStoragePolicy()); + policyEntries.add(entry); + + final PolicyMap policyMap = new PolicyMap(); + policyMap.setPolicyEntries(policyEntries); + broker.setDestinationPolicy(policyMap); + + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueRedeliverTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueRedeliverTest.java index b9f821a98f..b594515e22 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueRedeliverTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueRedeliverTest.java @@ -17,13 +17,13 @@ package org.apache.activemq.usecases; /** - * + * */ public class QueueRedeliverTest extends TopicRedeliverTest { - protected void setUp() throws Exception { - super.setUp(); - topic = false; - } + protected void setUp() throws Exception { + super.setUp(); + topic = false; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueRepeaterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueRepeaterTest.java index dcd32fcba6..190baa20ad 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueRepeaterTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueRepeaterTest.java @@ -31,6 +31,7 @@ import javax.jms.Session; import javax.jms.TextMessage; import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.command.ActiveMQQueue; import org.slf4j.Logger; @@ -38,82 +39,84 @@ import org.slf4j.LoggerFactory; /** * @author pragmasoft - * */ public final class QueueRepeaterTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(QueueRepeaterTest.class); + private static final Logger LOG = LoggerFactory.getLogger(QueueRepeaterTest.class); - private volatile String receivedText; + private volatile String receivedText; - private Session producerSession; - private Session consumerSession; - private Destination queue; + private Session producerSession; + private Session consumerSession; + private Destination queue; - private MessageProducer producer; - private MessageConsumer consumer; - private Connection connection; - private CountDownLatch latch = new CountDownLatch(1); + private MessageProducer producer; + private MessageConsumer consumer; + private Connection connection; + private CountDownLatch latch = new CountDownLatch(1); - public void testTransaction() throws Exception { + public void testTransaction() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); - connection = factory.createConnection(); - queue = new ActiveMQQueue(getClass().getName() + "." + getName()); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); + connection = factory.createConnection(); + queue = new ActiveMQQueue(getClass().getName() + "." + getName()); - producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumerSession = connection.createSession(true, 0); + producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumerSession = connection.createSession(true, 0); - producer = producerSession.createProducer(queue); + producer = producerSession.createProducer(queue); - consumer = consumerSession.createConsumer(queue); - consumer.setMessageListener(new MessageListener() { + consumer = consumerSession.createConsumer(queue); + consumer.setMessageListener(new MessageListener() { - public void onMessage(Message m) { - try { - TextMessage tm = (TextMessage)m; - receivedText = tm.getText(); - latch.countDown(); + public void onMessage(Message m) { + try { + TextMessage tm = (TextMessage) m; + receivedText = tm.getText(); + latch.countDown(); - LOG.info("consumer received message :" + receivedText); - consumerSession.commit(); - LOG.info("committed transaction"); - } catch (JMSException e) { - try { - consumerSession.rollback(); - LOG.info("rolled back transaction"); - } catch (JMSException e1) { - LOG.info(e1.toString()); - e1.printStackTrace(); - } - LOG.info(e.toString()); - e.printStackTrace(); - } + LOG.info("consumer received message :" + receivedText); + consumerSession.commit(); + LOG.info("committed transaction"); } - }); + catch (JMSException e) { + try { + consumerSession.rollback(); + LOG.info("rolled back transaction"); + } + catch (JMSException e1) { + LOG.info(e1.toString()); + e1.printStackTrace(); + } + LOG.info(e.toString()); + e.printStackTrace(); + } + } + }); - connection.start(); + connection.start(); - TextMessage tm = null; - try { - tm = producerSession.createTextMessage(); - tm.setText("Hello, " + new Date()); - producer.send(tm); - LOG.info("producer sent message :" + tm.getText()); - } catch (JMSException e) { - e.printStackTrace(); - } + TextMessage tm = null; + try { + tm = producerSession.createTextMessage(); + tm.setText("Hello, " + new Date()); + producer.send(tm); + LOG.info("producer sent message :" + tm.getText()); + } + catch (JMSException e) { + e.printStackTrace(); + } - LOG.info("Waiting for latch"); - latch.await(2,TimeUnit.SECONDS); - assertNotNull(receivedText); - LOG.info("test completed, destination=" + receivedText); - } + LOG.info("Waiting for latch"); + latch.await(2, TimeUnit.SECONDS); + assertNotNull(receivedText); + LOG.info("test completed, destination=" + receivedText); + } - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - super.tearDown(); - } + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + } + super.tearDown(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ReliableReconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ReliableReconnectTest.java index 9dc0032816..6c83cde156 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ReliableReconnectTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ReliableReconnectTest.java @@ -39,141 +39,143 @@ import org.apache.activemq.store.PersistenceAdapter; import org.apache.activemq.util.IdGenerator; public class ReliableReconnectTest extends org.apache.activemq.TestSupport { - - protected static final int MESSAGE_COUNT = 100; - protected static final String DEFAULT_BROKER_URL = ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL; - private static final int RECEIVE_TIMEOUT = 10000; - - protected int deliveryMode = DeliveryMode.PERSISTENT; - protected String consumerClientId; - protected Destination destination; - protected final AtomicBoolean closeBroker = new AtomicBoolean(false); - protected final AtomicInteger messagesReceived = new AtomicInteger(0); - protected BrokerService broker; - protected int firstBatch = MESSAGE_COUNT / 10; - private IdGenerator idGen = new IdGenerator(); - public ReliableReconnectTest() { - } + protected static final int MESSAGE_COUNT = 100; + protected static final String DEFAULT_BROKER_URL = ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL; + private static final int RECEIVE_TIMEOUT = 10000; - protected void setUp() throws Exception { - this.setAutoFail(true); - consumerClientId = idGen.generateId(); - super.setUp(); - topic = true; - destination = createDestination(getClass().getName()); - } - - protected void tearDown() throws Exception { - if (broker!=null) { - broker.stop(); - } - } + protected int deliveryMode = DeliveryMode.PERSISTENT; + protected String consumerClientId; + protected Destination destination; + protected final AtomicBoolean closeBroker = new AtomicBoolean(false); + protected final AtomicInteger messagesReceived = new AtomicInteger(0); + protected BrokerService broker; + protected int firstBatch = MESSAGE_COUNT / 10; + private IdGenerator idGen = new IdGenerator(); - public ActiveMQConnectionFactory getConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(); - } + public ReliableReconnectTest() { + } - protected void startBroker(boolean deleteOnStart) throws JMSException { - try { - broker = BrokerFactory.createBroker(new URI("broker://()/localhost")); - broker.setUseShutdownHook(false); - broker.setDeleteAllMessagesOnStartup(deleteOnStart); - - broker.setUseJmx(false); - broker.addConnector(DEFAULT_BROKER_URL); - broker.start(); - } catch (Exception e) { - e.printStackTrace(); - } - } + protected void setUp() throws Exception { + this.setAutoFail(true); + consumerClientId = idGen.generateId(); + super.setUp(); + topic = true; + destination = createDestination(getClass().getName()); + } - protected Connection createConsumerConnection() throws Exception { - Connection consumerConnection = getConnectionFactory().createConnection(); - consumerConnection.setClientID(consumerClientId); - consumerConnection.start(); - return consumerConnection; - } + protected void tearDown() throws Exception { + if (broker != null) { + broker.stop(); + } + } - protected MessageConsumer createConsumer(Connection con) throws Exception { - Session s = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - return s.createDurableSubscriber((Topic)destination, "TestFred"); - } + public ActiveMQConnectionFactory getConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory(); + } - protected void spawnConsumer() { - Thread thread = new Thread(new Runnable() { - public void run() { - try { - Connection consumerConnection = createConsumerConnection(); - MessageConsumer consumer = createConsumer(consumerConnection); - // consume some messages + protected void startBroker(boolean deleteOnStart) throws JMSException { + try { + broker = BrokerFactory.createBroker(new URI("broker://()/localhost")); + broker.setUseShutdownHook(false); + broker.setDeleteAllMessagesOnStartup(deleteOnStart); - for (int i = 0; i < firstBatch; i++) { - Message msg = consumer.receive(RECEIVE_TIMEOUT); - if (msg != null) { - // log.info("GOT: " + msg); - messagesReceived.incrementAndGet(); - } - } - synchronized (closeBroker) { - closeBroker.set(true); - closeBroker.notify(); - } - Thread.sleep(2000); - for (int i = firstBatch; i < MESSAGE_COUNT; i++) { - Message msg = consumer.receive(RECEIVE_TIMEOUT); - // log.info("GOT: " + msg); - if (msg != null) { - messagesReceived.incrementAndGet(); - } - } - consumerConnection.close(); - synchronized (messagesReceived) { - messagesReceived.notify(); - } - } catch (Throwable e) { - e.printStackTrace(); - } + broker.setUseJmx(false); + broker.addConnector(DEFAULT_BROKER_URL); + broker.start(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + protected Connection createConsumerConnection() throws Exception { + Connection consumerConnection = getConnectionFactory().createConnection(); + consumerConnection.setClientID(consumerClientId); + consumerConnection.start(); + return consumerConnection; + } + + protected MessageConsumer createConsumer(Connection con) throws Exception { + Session s = con.createSession(false, Session.AUTO_ACKNOWLEDGE); + return s.createDurableSubscriber((Topic) destination, "TestFred"); + } + + protected void spawnConsumer() { + Thread thread = new Thread(new Runnable() { + public void run() { + try { + Connection consumerConnection = createConsumerConnection(); + MessageConsumer consumer = createConsumer(consumerConnection); + // consume some messages + + for (int i = 0; i < firstBatch; i++) { + Message msg = consumer.receive(RECEIVE_TIMEOUT); + if (msg != null) { + // log.info("GOT: " + msg); + messagesReceived.incrementAndGet(); + } + } + synchronized (closeBroker) { + closeBroker.set(true); + closeBroker.notify(); + } + Thread.sleep(2000); + for (int i = firstBatch; i < MESSAGE_COUNT; i++) { + Message msg = consumer.receive(RECEIVE_TIMEOUT); + // log.info("GOT: " + msg); + if (msg != null) { + messagesReceived.incrementAndGet(); + } + } + consumerConnection.close(); + synchronized (messagesReceived) { + messagesReceived.notify(); + } } - }); - thread.start(); - } + catch (Throwable e) { + e.printStackTrace(); + } + } + }); + thread.start(); + } - public void testReconnect() throws Exception { - startBroker(true); - // register an interest as a durable subscriber - Connection consumerConnection = createConsumerConnection(); - createConsumer(consumerConnection); - consumerConnection.close(); - // send some messages ... - Connection connection = createConnection(); - connection.setClientID(idGen.generateId()); - connection.start(); - Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = producerSession.createProducer(destination); - TextMessage msg = producerSession.createTextMessage(); - for (int i = 0; i < MESSAGE_COUNT; i++) { - msg.setText("msg: " + i); - producer.send(msg); - } - connection.close(); - spawnConsumer(); - synchronized (closeBroker) { - while (!closeBroker.get()) { - closeBroker.wait(); - } - } - // System.err.println("Stopping broker"); - broker.stop(); - startBroker(false); - // System.err.println("Started Broker again"); - synchronized (messagesReceived) { - while (messagesReceived.get() < MESSAGE_COUNT) { - messagesReceived.wait(60000); - } - } - // assertTrue(messagesReceived.get() == MESSAGE_COUNT); - int count = messagesReceived.get(); - assertTrue("Not enough messages received: " + count, count > firstBatch); - } + public void testReconnect() throws Exception { + startBroker(true); + // register an interest as a durable subscriber + Connection consumerConnection = createConsumerConnection(); + createConsumer(consumerConnection); + consumerConnection.close(); + // send some messages ... + Connection connection = createConnection(); + connection.setClientID(idGen.generateId()); + connection.start(); + Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = producerSession.createProducer(destination); + TextMessage msg = producerSession.createTextMessage(); + for (int i = 0; i < MESSAGE_COUNT; i++) { + msg.setText("msg: " + i); + producer.send(msg); + } + connection.close(); + spawnConsumer(); + synchronized (closeBroker) { + while (!closeBroker.get()) { + closeBroker.wait(); + } + } + // System.err.println("Stopping broker"); + broker.stop(); + startBroker(false); + // System.err.println("Started Broker again"); + synchronized (messagesReceived) { + while (messagesReceived.get() < MESSAGE_COUNT) { + messagesReceived.wait(60000); + } + } + // assertTrue(messagesReceived.get() == MESSAGE_COUNT); + int count = messagesReceived.get(); + assertTrue("Not enough messages received: " + count, count > firstBatch); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/RequestReplyNoAdvisoryNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/RequestReplyNoAdvisoryNetworkTest.java index 9670d4080f..593c9213e2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/RequestReplyNoAdvisoryNetworkTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/RequestReplyNoAdvisoryNetworkTest.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.usecases; - import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -51,231 +50,229 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RequestReplyNoAdvisoryNetworkTest extends JmsMultipleBrokersTestSupport { - private static final transient Logger LOG = LoggerFactory.getLogger(RequestReplyNoAdvisoryNetworkTest.class); - Vector brokers = new Vector(); - BrokerService a, b; - ActiveMQQueue sendQ = new ActiveMQQueue("sendQ"); - static final String connectionIdMarker = "ID:marker."; - ActiveMQTempQueue replyQWildcard = new ActiveMQTempQueue(connectionIdMarker + ">"); - private final long receiveTimeout = 30000; + private static final transient Logger LOG = LoggerFactory.getLogger(RequestReplyNoAdvisoryNetworkTest.class); - public void testNonAdvisoryNetworkRequestReplyXmlConfig() throws Exception { - final String xmlConfigString = new String( - "" + - " " + - " " + - " " + - " " + - " "+ - " "+ - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - ""); - final String localProtocolScheme = "inline"; - URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() { - @Override - public URLStreamHandler createURLStreamHandler(String protocol) { - if (localProtocolScheme.equalsIgnoreCase(protocol)) { - return new URLStreamHandler() { + Vector brokers = new Vector(); + BrokerService a, b; + ActiveMQQueue sendQ = new ActiveMQQueue("sendQ"); + static final String connectionIdMarker = "ID:marker."; + ActiveMQTempQueue replyQWildcard = new ActiveMQTempQueue(connectionIdMarker + ">"); + private final long receiveTimeout = 30000; + + public void testNonAdvisoryNetworkRequestReplyXmlConfig() throws Exception { + final String xmlConfigString = new String("" + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + ""); + final String localProtocolScheme = "inline"; + URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() { + @Override + public URLStreamHandler createURLStreamHandler(String protocol) { + if (localProtocolScheme.equalsIgnoreCase(protocol)) { + return new URLStreamHandler() { + @Override + protected URLConnection openConnection(URL u) throws IOException { + return new URLConnection(u) { @Override - protected URLConnection openConnection(URL u) throws IOException { - return new URLConnection(u) { - @Override - public void connect() throws IOException { - } - @Override - public InputStream getInputStream() throws IOException { - return new ByteArrayInputStream(xmlConfigString.replace("%HOST%", url.getFile()).getBytes("UTF-8")); - } - }; + public void connect() throws IOException { } - }; - } - return null; + + @Override + public InputStream getInputStream() throws IOException { + return new ByteArrayInputStream(xmlConfigString.replace("%HOST%", url.getFile()).getBytes("UTF-8")); + } + }; + } + }; } - }); - a = new XBeanBrokerFactory().createBroker(new URI("xbean:" + localProtocolScheme + ":A")); - b = new XBeanBrokerFactory().createBroker(new URI("xbean:" + localProtocolScheme + ":B")); - brokers.add(a); - brokers.add(b); + return null; + } + }); + a = new XBeanBrokerFactory().createBroker(new URI("xbean:" + localProtocolScheme + ":A")); + b = new XBeanBrokerFactory().createBroker(new URI("xbean:" + localProtocolScheme + ":B")); + brokers.add(a); + brokers.add(b); - doTestNonAdvisoryNetworkRequestReply(); - } + doTestNonAdvisoryNetworkRequestReply(); + } - public void testNonAdvisoryNetworkRequestReply() throws Exception { - createBridgeAndStartBrokers(); - doTestNonAdvisoryNetworkRequestReply(); - } + public void testNonAdvisoryNetworkRequestReply() throws Exception { + createBridgeAndStartBrokers(); + doTestNonAdvisoryNetworkRequestReply(); + } - public void testNonAdvisoryNetworkRequestReplyWithPIM() throws Exception { - a = configureBroker("A"); - b = configureBroker("B"); - BrokerService hub = configureBroker("M"); - hub.setAllowTempAutoCreationOnSend(true); - configureForPiggyInTheMiddle(bridge(a, hub)); - configureForPiggyInTheMiddle(bridge(b, hub)); + public void testNonAdvisoryNetworkRequestReplyWithPIM() throws Exception { + a = configureBroker("A"); + b = configureBroker("B"); + BrokerService hub = configureBroker("M"); + hub.setAllowTempAutoCreationOnSend(true); + configureForPiggyInTheMiddle(bridge(a, hub)); + configureForPiggyInTheMiddle(bridge(b, hub)); - startBrokers(); + startBrokers(); - waitForBridgeFormation(hub, 2, 0); - doTestNonAdvisoryNetworkRequestReply(); - } + waitForBridgeFormation(hub, 2, 0); + doTestNonAdvisoryNetworkRequestReply(); + } - private void configureForPiggyInTheMiddle(NetworkConnector bridge) { - bridge.setDuplex(true); - bridge.setNetworkTTL(2); - } + private void configureForPiggyInTheMiddle(NetworkConnector bridge) { + bridge.setDuplex(true); + bridge.setNetworkTTL(2); + } - public void doTestNonAdvisoryNetworkRequestReply() throws Exception { + public void doTestNonAdvisoryNetworkRequestReply() throws Exception { - waitForBridgeFormation(a, 1, 0); - waitForBridgeFormation(b, 1, 0); + waitForBridgeFormation(a, 1, 0); + waitForBridgeFormation(b, 1, 0); - ActiveMQConnectionFactory sendFactory = createConnectionFactory(a); - ActiveMQConnection sendConnection = createConnection(sendFactory); + ActiveMQConnectionFactory sendFactory = createConnectionFactory(a); + ActiveMQConnection sendConnection = createConnection(sendFactory); - ActiveMQSession sendSession = (ActiveMQSession)sendConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = sendSession.createProducer(sendQ); - ActiveMQTempQueue realReplyQ = (ActiveMQTempQueue) sendSession.createTemporaryQueue(); - TextMessage message = sendSession.createTextMessage("1"); - message.setJMSReplyTo(realReplyQ); - producer.send(message); - LOG.info("request sent"); + ActiveMQSession sendSession = (ActiveMQSession) sendConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = sendSession.createProducer(sendQ); + ActiveMQTempQueue realReplyQ = (ActiveMQTempQueue) sendSession.createTemporaryQueue(); + TextMessage message = sendSession.createTextMessage("1"); + message.setJMSReplyTo(realReplyQ); + producer.send(message); + LOG.info("request sent"); - // responder - ActiveMQConnectionFactory consumerFactory = createConnectionFactory(b); - ActiveMQConnection consumerConnection = createConnection(consumerFactory); + // responder + ActiveMQConnectionFactory consumerFactory = createConnectionFactory(b); + ActiveMQConnection consumerConnection = createConnection(consumerFactory); - ActiveMQSession consumerSession = (ActiveMQSession)consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = consumerSession.createConsumer(sendQ); - TextMessage received = (TextMessage) consumer.receive(receiveTimeout); - assertNotNull("got request from sender ok", received); + ActiveMQSession consumerSession = (ActiveMQSession) consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = consumerSession.createConsumer(sendQ); + TextMessage received = (TextMessage) consumer.receive(receiveTimeout); + assertNotNull("got request from sender ok", received); - LOG.info("got request, sending reply"); + LOG.info("got request, sending reply"); - MessageProducer consumerProducer = consumerSession.createProducer(received.getJMSReplyTo()); - consumerProducer.send(consumerSession.createTextMessage("got " + received.getText())); - // temp dest on reply broker tied to this connection, setOptimizedDispatch=true ensures - // message gets delivered before destination is removed - consumerConnection.close(); + MessageProducer consumerProducer = consumerSession.createProducer(received.getJMSReplyTo()); + consumerProducer.send(consumerSession.createTextMessage("got " + received.getText())); + // temp dest on reply broker tied to this connection, setOptimizedDispatch=true ensures + // message gets delivered before destination is removed + consumerConnection.close(); - // reply consumer - MessageConsumer replyConsumer = sendSession.createConsumer(realReplyQ); - TextMessage reply = (TextMessage) replyConsumer.receive(receiveTimeout); - assertNotNull("expected reply message", reply); - assertEquals("text is as expected", "got 1", reply.getText()); - sendConnection.close(); + // reply consumer + MessageConsumer replyConsumer = sendSession.createConsumer(realReplyQ); + TextMessage reply = (TextMessage) replyConsumer.receive(receiveTimeout); + assertNotNull("expected reply message", reply); + assertEquals("text is as expected", "got 1", reply.getText()); + sendConnection.close(); - LOG.info("checking for dangling temp destinations"); - // ensure all temp dests get cleaned up on all brokers - for (BrokerService brokerService : brokers) { - final RegionBroker regionBroker = (RegionBroker) brokerService.getRegionBroker(); - assertTrue("all temps are gone on " + regionBroker.getBrokerName(), Wait.waitFor(new Wait.Condition(){ - @Override - public boolean isSatisified() throws Exception { - Map tempTopics = regionBroker.getTempTopicRegion().getDestinationMap(); - LOG.info("temp topics on " + regionBroker.getBrokerName() + ", " + tempTopics); - Map tempQ = regionBroker.getTempQueueRegion().getDestinationMap(); - LOG.info("temp queues on " + regionBroker.getBrokerName() + ", " + tempQ); - return tempQ.isEmpty() && tempTopics.isEmpty(); - } - })); - } - } + LOG.info("checking for dangling temp destinations"); + // ensure all temp dests get cleaned up on all brokers + for (BrokerService brokerService : brokers) { + final RegionBroker regionBroker = (RegionBroker) brokerService.getRegionBroker(); + assertTrue("all temps are gone on " + regionBroker.getBrokerName(), Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + Map tempTopics = regionBroker.getTempTopicRegion().getDestinationMap(); + LOG.info("temp topics on " + regionBroker.getBrokerName() + ", " + tempTopics); + Map tempQ = regionBroker.getTempQueueRegion().getDestinationMap(); + LOG.info("temp queues on " + regionBroker.getBrokerName() + ", " + tempQ); + return tempQ.isEmpty() && tempTopics.isEmpty(); + } + })); + } + } - private ActiveMQConnection createConnection(ActiveMQConnectionFactory factory) throws Exception { - ActiveMQConnection c =(ActiveMQConnection) factory.createConnection(); - c.start(); - return c; - } + private ActiveMQConnection createConnection(ActiveMQConnectionFactory factory) throws Exception { + ActiveMQConnection c = (ActiveMQConnection) factory.createConnection(); + c.start(); + return c; + } - private ActiveMQConnectionFactory createConnectionFactory(BrokerService brokerService) throws Exception { - String target = brokerService.getTransportConnectors().get(0).getPublishableConnectString(); - ActiveMQConnectionFactory factory = - new ActiveMQConnectionFactory(target); - factory.setWatchTopicAdvisories(false); - factory.setConnectionIDPrefix(connectionIdMarker + brokerService.getBrokerName()); - return factory; - } + private ActiveMQConnectionFactory createConnectionFactory(BrokerService brokerService) throws Exception { + String target = brokerService.getTransportConnectors().get(0).getPublishableConnectString(); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(target); + factory.setWatchTopicAdvisories(false); + factory.setConnectionIDPrefix(connectionIdMarker + brokerService.getBrokerName()); + return factory; + } - public void createBridgeAndStartBrokers() throws Exception { - a = configureBroker("A"); - b = configureBroker("B"); - bridge(a, b); - bridge(b, a); - startBrokers(); - } + public void createBridgeAndStartBrokers() throws Exception { + a = configureBroker("A"); + b = configureBroker("B"); + bridge(a, b); + bridge(b, a); + startBrokers(); + } - private void startBrokers() throws Exception { - for (BrokerService broker: brokers) { - broker.start(); - } - } + private void startBrokers() throws Exception { + for (BrokerService broker : brokers) { + broker.start(); + } + } - @Override - public void tearDown() throws Exception { - for (BrokerService broker: brokers) { - broker.stop(); - } - brokers.clear(); - } + @Override + public void tearDown() throws Exception { + for (BrokerService broker : brokers) { + broker.stop(); + } + brokers.clear(); + } + private NetworkConnector bridge(BrokerService from, BrokerService to) throws Exception { + TransportConnector toConnector = to.getTransportConnectors().get(0); + NetworkConnector bridge = from.addNetworkConnector("static://" + toConnector.getPublishableConnectString()); + bridge.addStaticallyIncludedDestination(sendQ); + bridge.addStaticallyIncludedDestination(replyQWildcard); + return bridge; + } - private NetworkConnector bridge(BrokerService from, BrokerService to) throws Exception { - TransportConnector toConnector = to.getTransportConnectors().get(0); - NetworkConnector bridge = - from.addNetworkConnector("static://" + toConnector.getPublishableConnectString()); - bridge.addStaticallyIncludedDestination(sendQ); - bridge.addStaticallyIncludedDestination(replyQWildcard); - return bridge; - } + private BrokerService configureBroker(String brokerName) throws Exception { + BrokerService broker = new BrokerService(); + broker.setBrokerName(brokerName); + broker.setAdvisorySupport(false); + broker.setPersistent(false); + broker.setUseJmx(false); + broker.setSchedulePeriodForDestinationPurge(1000); + broker.setAllowTempAutoCreationOnSend(true); - private BrokerService configureBroker(String brokerName) throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName(brokerName); - broker.setAdvisorySupport(false); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.setSchedulePeriodForDestinationPurge(1000); - broker.setAllowTempAutoCreationOnSend(true); + PolicyMap map = new PolicyMap(); + PolicyEntry tempReplyQPolicy = new PolicyEntry(); + tempReplyQPolicy.setOptimizedDispatch(true); + tempReplyQPolicy.setGcInactiveDestinations(true); + tempReplyQPolicy.setGcWithNetworkConsumers(true); + tempReplyQPolicy.setInactiveTimoutBeforeGC(1000); + map.put(replyQWildcard, tempReplyQPolicy); + broker.setDestinationPolicy(map); - PolicyMap map = new PolicyMap(); - PolicyEntry tempReplyQPolicy = new PolicyEntry(); - tempReplyQPolicy.setOptimizedDispatch(true); - tempReplyQPolicy.setGcInactiveDestinations(true); - tempReplyQPolicy.setGcWithNetworkConsumers(true); - tempReplyQPolicy.setInactiveTimoutBeforeGC(1000); - map.put(replyQWildcard, tempReplyQPolicy); - broker.setDestinationPolicy(map); - - broker.addConnector("tcp://localhost:0"); - brokers.add(broker); - return broker; - } + broker.addConnector("tcp://localhost:0"); + brokers.add(broker); + return broker; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/RequestReplyTempDestRemovalAdvisoryRaceTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/RequestReplyTempDestRemovalAdvisoryRaceTest.java index 4822e0250f..c3a15b3f3b 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/RequestReplyTempDestRemovalAdvisoryRaceTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/RequestReplyTempDestRemovalAdvisoryRaceTest.java @@ -36,7 +36,9 @@ import javax.jms.MessageListener; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; + import junit.framework.Test; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.JmsMultipleBrokersTestSupport; import org.apache.activemq.advisory.AdvisorySupport; @@ -62,425 +64,421 @@ import org.slf4j.LoggerFactory; * @author Christian Posta */ public class RequestReplyTempDestRemovalAdvisoryRaceTest extends JmsMultipleBrokersTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(RequestReplyTempDestRemovalAdvisoryRaceTest.class); - private static final String BROKER_A = "BrokerA"; - private static final String BROKER_B = "BrokerB"; - private static final String BROKER_C = "BrokerC"; + private static final Logger LOG = LoggerFactory.getLogger(RequestReplyTempDestRemovalAdvisoryRaceTest.class); - private static final int NUM_RESPONDENTS = 1; - private static final int NUM_SENDS = 1; - private static final int RANDOM_SLEEP_FOR_RESPONDENT_MS = 0; - private static final int RANDOM_SLEEP_FOR_SENDER_MS = 1; - private static final String QUEUE_NAME = "foo.queue"; - private static String[] TEST_ITERATIONS = new String[]{QUEUE_NAME+"0", QUEUE_NAME+"1", QUEUE_NAME+"2", QUEUE_NAME+"3"}; + private static final String BROKER_A = "BrokerA"; + private static final String BROKER_B = "BrokerB"; + private static final String BROKER_C = "BrokerC"; - final AtomicLong messageCount = new AtomicLong(0); - final AtomicLong respondentSendError = new AtomicLong(0); - final AtomicLong responseReceived = new AtomicLong(0); - final AtomicLong sendsWithNoConsumers = new AtomicLong(0); - final AtomicLong forwardFailures = new AtomicLong(0); + private static final int NUM_RESPONDENTS = 1; + private static final int NUM_SENDS = 1; + private static final int RANDOM_SLEEP_FOR_RESPONDENT_MS = 0; + private static final int RANDOM_SLEEP_FOR_SENDER_MS = 1; + private static final String QUEUE_NAME = "foo.queue"; + private static String[] TEST_ITERATIONS = new String[]{QUEUE_NAME + "0", QUEUE_NAME + "1", QUEUE_NAME + "2", QUEUE_NAME + "3"}; + final AtomicLong messageCount = new AtomicLong(0); + final AtomicLong respondentSendError = new AtomicLong(0); + final AtomicLong responseReceived = new AtomicLong(0); + final AtomicLong sendsWithNoConsumers = new AtomicLong(0); + final AtomicLong forwardFailures = new AtomicLong(0); - protected final AtomicBoolean shutdown = new AtomicBoolean(false); - HashSet networkConnectors = new HashSet(); - HashSet advisoryConsumerConnections = new HashSet(); - Appender slowDownAppender; + protected final AtomicBoolean shutdown = new AtomicBoolean(false); + HashSet networkConnectors = new HashSet(); + HashSet advisoryConsumerConnections = new HashSet(); + Appender slowDownAppender; - CountDownLatch consumerDemandExists; + CountDownLatch consumerDemandExists; - protected boolean useDuplex = false; + protected boolean useDuplex = false; - public static Test suite() { - return suite(RequestReplyTempDestRemovalAdvisoryRaceTest.class); - } + public static Test suite() { + return suite(RequestReplyTempDestRemovalAdvisoryRaceTest.class); + } - /** - * Notes: to reliably reproduce use debugger... set a "thread" breakpoint at line 679 in DemandForwardingBridgeSupport, - * and only break on the "2nd" pass (broker C's bridge). Allow debugging to continue shortly after hitting - * the breakpoint, for this test we use a logging appender to implement the pause, - * it fails most of the time, hence the combos - */ - public void initCombos() { - addCombinationValues("QUEUE_NAME", TEST_ITERATIONS); - } + /** + * Notes: to reliably reproduce use debugger... set a "thread" breakpoint at line 679 in DemandForwardingBridgeSupport, + * and only break on the "2nd" pass (broker C's bridge). Allow debugging to continue shortly after hitting + * the breakpoint, for this test we use a logging appender to implement the pause, + * it fails most of the time, hence the combos + */ + public void initCombos() { + addCombinationValues("QUEUE_NAME", TEST_ITERATIONS); + } - public void testTempDestRaceDuplex() throws Exception { - // duplex - useDuplex = true; - bridgeBrokers(BROKER_A, BROKER_B, false, 3); - bridgeBrokers(BROKER_B, BROKER_C, false, 3); + public void testTempDestRaceDuplex() throws Exception { + // duplex + useDuplex = true; + bridgeBrokers(BROKER_A, BROKER_B, false, 3); + bridgeBrokers(BROKER_B, BROKER_C, false, 3); - startAllBrokers(); + startAllBrokers(); - waitForBridgeFormation(1); + waitForBridgeFormation(1); - HashSet bridgesStart = new HashSet(); - for (NetworkConnector networkConnector : networkConnectors) { - bridgesStart.addAll(networkConnector.activeBridges()); - } - LOG.info("Bridges start:" + bridgesStart); + HashSet bridgesStart = new HashSet(); + for (NetworkConnector networkConnector : networkConnectors) { + bridgesStart.addAll(networkConnector.activeBridges()); + } + LOG.info("Bridges start:" + bridgesStart); - slowDownAdvisoryDispatch(); - noConsumerAdvisory(); - forwardFailureAdvisory(); + slowDownAdvisoryDispatch(); + noConsumerAdvisory(); + forwardFailureAdvisory(); - // set up respondents - ExecutorService respondentThreadPool = Executors.newFixedThreadPool(50); - BrokerItem brokerA = brokers.get(BROKER_A); - ActiveMQConnectionFactory brokerAFactory = new ActiveMQConnectionFactory(brokerA.broker.getTransportConnectorByScheme("tcp").getName() - + "?jms.watchTopicAdvisories=false"); - brokerAFactory.setAlwaysSyncSend(true); - for (int i = 0; i < NUM_RESPONDENTS; i++) { - respondentThreadPool.execute(new EchoRespondent(brokerAFactory)); - } + // set up respondents + ExecutorService respondentThreadPool = Executors.newFixedThreadPool(50); + BrokerItem brokerA = brokers.get(BROKER_A); + ActiveMQConnectionFactory brokerAFactory = new ActiveMQConnectionFactory(brokerA.broker.getTransportConnectorByScheme("tcp").getName() + "?jms.watchTopicAdvisories=false"); + brokerAFactory.setAlwaysSyncSend(true); + for (int i = 0; i < NUM_RESPONDENTS; i++) { + respondentThreadPool.execute(new EchoRespondent(brokerAFactory)); + } - // fire off sends - ExecutorService senderThreadPool = Executors.newCachedThreadPool(); - BrokerItem brokerC = brokers.get(BROKER_C); - ActiveMQConnectionFactory brokerCFactory = new ActiveMQConnectionFactory(brokerC.broker.getTransportConnectorByScheme("tcp").getName() - + "?jms.watchTopicAdvisories=false"); - for (int i = 0; i < NUM_SENDS; i++) { - senderThreadPool.execute(new MessageSender(brokerCFactory)); - } + // fire off sends + ExecutorService senderThreadPool = Executors.newCachedThreadPool(); + BrokerItem brokerC = brokers.get(BROKER_C); + ActiveMQConnectionFactory brokerCFactory = new ActiveMQConnectionFactory(brokerC.broker.getTransportConnectorByScheme("tcp").getName() + "?jms.watchTopicAdvisories=false"); + for (int i = 0; i < NUM_SENDS; i++) { + senderThreadPool.execute(new MessageSender(brokerCFactory)); + } - senderThreadPool.shutdown(); - senderThreadPool.awaitTermination(30, TimeUnit.SECONDS); - TimeUnit.SECONDS.sleep(15); - LOG.info("shutting down"); - shutdown.compareAndSet(false, true); + senderThreadPool.shutdown(); + senderThreadPool.awaitTermination(30, TimeUnit.SECONDS); + TimeUnit.SECONDS.sleep(15); + LOG.info("shutting down"); + shutdown.compareAndSet(false, true); - HashSet bridgesEnd = new HashSet(); - for (NetworkConnector networkConnector : networkConnectors) { - bridgesEnd.addAll(networkConnector.activeBridges()); - } - LOG.info("Bridges end:" + bridgesEnd); + HashSet bridgesEnd = new HashSet(); + for (NetworkConnector networkConnector : networkConnectors) { + bridgesEnd.addAll(networkConnector.activeBridges()); + } + LOG.info("Bridges end:" + bridgesEnd); - assertEquals("no new bridges created", bridgesStart, bridgesEnd); + assertEquals("no new bridges created", bridgesStart, bridgesEnd); - // validate success or error of dlq - LOG.info("received: " + responseReceived.get() + ", respondent error: " + respondentSendError.get() - + ", noConsumerCount: " + sendsWithNoConsumers.get() - + ", forwardFailures: " + forwardFailures.get()); - assertEquals("success or error", NUM_SENDS, respondentSendError.get() + forwardFailures.get() - + responseReceived.get() + sendsWithNoConsumers.get()); + // validate success or error of dlq + LOG.info("received: " + responseReceived.get() + ", respondent error: " + respondentSendError.get() + ", noConsumerCount: " + sendsWithNoConsumers.get() + ", forwardFailures: " + forwardFailures.get()); + assertEquals("success or error", NUM_SENDS, respondentSendError.get() + forwardFailures.get() + responseReceived.get() + sendsWithNoConsumers.get()); - } + } - private void forwardFailureAdvisory() throws JMSException { - for (BrokerItem item : brokers.values()) { - ActiveMQConnectionFactory brokerAFactory = new ActiveMQConnectionFactory(item.broker.getTransportConnectorByScheme("tcp").getName() - + "?jms.watchTopicAdvisories=false"); - Connection connection = brokerAFactory.createConnection(); - connection.start(); - connection.createSession(false, Session.AUTO_ACKNOWLEDGE).createConsumer( - AdvisorySupport.getNetworkBridgeForwardFailureAdvisoryTopic()).setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - forwardFailures.incrementAndGet(); - } - }); - } - } - - private void noConsumerAdvisory() throws JMSException { - for (BrokerItem item : brokers.values()) { - ActiveMQConnectionFactory brokerAFactory = new ActiveMQConnectionFactory(item.broker.getTransportConnectorByScheme("tcp").getName() - + "?jms.watchTopicAdvisories=false"); - Connection connection = brokerAFactory.createConnection(); - connection.start(); - connection.createSession(false, Session.AUTO_ACKNOWLEDGE).createConsumer( - AdvisorySupport.getNoTopicConsumersAdvisoryTopic(new ActiveMQTempTopic(">"))).setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - sendsWithNoConsumers.incrementAndGet(); - } - }); - } - } - - - public void testTempDestRace() throws Exception { - // non duplex - bridgeBrokers(BROKER_A, BROKER_B, false, 3); - bridgeBrokers(BROKER_B, BROKER_A, false, 3); - bridgeBrokers(BROKER_B, BROKER_C, false, 3); - bridgeBrokers(BROKER_C, BROKER_B, false, 3); - - startAllBrokers(); - - waitForBridgeFormation(1); - - HashSet bridgesStart = new HashSet(); - for (NetworkConnector networkConnector : networkConnectors) { - bridgesStart.addAll(networkConnector.activeBridges()); - } - - slowDownAdvisoryDispatch(); - noConsumerAdvisory(); - forwardFailureAdvisory(); - - - // set up respondents - ExecutorService respondentThreadPool = Executors.newFixedThreadPool(50); - BrokerItem brokerA = brokers.get(BROKER_A); - ActiveMQConnectionFactory brokerAFactory = new ActiveMQConnectionFactory(brokerA.broker.getTransportConnectorByScheme("tcp").getName() - + "?jms.watchTopicAdvisories=false"); - brokerAFactory.setAlwaysSyncSend(true); - for (int i = 0; i < NUM_RESPONDENTS; i++) { - respondentThreadPool.execute(new EchoRespondent(brokerAFactory)); - } - - // fire off sends - ExecutorService senderThreadPool = Executors.newCachedThreadPool(); - BrokerItem brokerC = brokers.get(BROKER_C); - ActiveMQConnectionFactory brokerCFactory = new ActiveMQConnectionFactory(brokerC.broker.getTransportConnectorByScheme("tcp").getName() - + "?jms.watchTopicAdvisories=false"); - for (int i = 0; i < NUM_SENDS; i++) { - senderThreadPool.execute(new MessageSender(brokerCFactory)); - } - - senderThreadPool.shutdown(); - senderThreadPool.awaitTermination(30, TimeUnit.SECONDS); - TimeUnit.SECONDS.sleep(10); - LOG.info("shutting down"); - shutdown.compareAndSet(false, true); - - HashSet bridgesEnd = new HashSet(); - for (NetworkConnector networkConnector : networkConnectors) { - bridgesEnd.addAll(networkConnector.activeBridges()); - } - assertEquals("no new bridges created", bridgesStart, bridgesEnd); - - // validate success or error or dlq - LOG.info("received: " + responseReceived.get() + ", respondent error: " + respondentSendError.get() - + ", noConsumerCount: " + sendsWithNoConsumers.get() - + ", forwardFailures: " + forwardFailures.get()); - assertEquals("success or error", NUM_SENDS, respondentSendError.get() + forwardFailures.get() - + responseReceived.get() + sendsWithNoConsumers.get()); - - } - - private void slowDownAdvisoryDispatch() throws Exception { - - org.apache.log4j.Logger.getLogger(DemandForwardingBridgeSupport.class).setLevel(Level.DEBUG); - - // instrument a logger to block the processing of a remove sub advisory - // simulate a slow thread - slowDownAppender = new DefaultTestAppender() { + private void forwardFailureAdvisory() throws JMSException { + for (BrokerItem item : brokers.values()) { + ActiveMQConnectionFactory brokerAFactory = new ActiveMQConnectionFactory(item.broker.getTransportConnectorByScheme("tcp").getName() + "?jms.watchTopicAdvisories=false"); + Connection connection = brokerAFactory.createConnection(); + connection.start(); + connection.createSession(false, Session.AUTO_ACKNOWLEDGE).createConsumer(AdvisorySupport.getNetworkBridgeForwardFailureAdvisoryTopic()).setMessageListener(new MessageListener() { @Override - public void doAppend(LoggingEvent loggingEvent) { - if (Level.DEBUG.equals(loggingEvent.getLevel())) { - String message = loggingEvent.getMessage().toString(); - if (message.startsWith("BrokerB") && message.contains("remove local subscription")) { - // sleep for a bit - try { - consumerDemandExists.countDown(); - System.err.println("Sleeping on receipt of remove info debug message: " + message); - TimeUnit.SECONDS.sleep(2); - } catch (Exception ignored) { - } - } - - } + public void onMessage(Message message) { + forwardFailures.incrementAndGet(); } - }; + }); + } + } - org.apache.log4j.Logger.getRootLogger().addAppender(slowDownAppender); - } + private void noConsumerAdvisory() throws JMSException { + for (BrokerItem item : brokers.values()) { + ActiveMQConnectionFactory brokerAFactory = new ActiveMQConnectionFactory(item.broker.getTransportConnectorByScheme("tcp").getName() + "?jms.watchTopicAdvisories=false"); + Connection connection = brokerAFactory.createConnection(); + connection.start(); + connection.createSession(false, Session.AUTO_ACKNOWLEDGE).createConsumer(AdvisorySupport.getNoTopicConsumersAdvisoryTopic(new ActiveMQTempTopic(">"))).setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + sendsWithNoConsumers.incrementAndGet(); + } + }); + } + } - @Override - protected void setUp() throws Exception { - super.setUp(); - responseReceived.set(0); - respondentSendError.set(0); - forwardFailures.set(0); - sendsWithNoConsumers.set(0); - networkConnectors.clear(); - advisoryConsumerConnections.clear(); - consumerDemandExists = new CountDownLatch(1); - createBroker(new URI("broker:(tcp://localhost:0)/" + BROKER_A + "?persistent=false&useJmx=false")).setDedicatedTaskRunner(false); - createBroker(new URI("broker:(tcp://localhost:0)/" + BROKER_B + "?persistent=false&useJmx=false")).setDedicatedTaskRunner(false); - createBroker(new URI("broker:(tcp://localhost:0)/" + BROKER_C + "?persistent=false&useJmx=false")).setDedicatedTaskRunner(false); + public void testTempDestRace() throws Exception { + // non duplex + bridgeBrokers(BROKER_A, BROKER_B, false, 3); + bridgeBrokers(BROKER_B, BROKER_A, false, 3); + bridgeBrokers(BROKER_B, BROKER_C, false, 3); + bridgeBrokers(BROKER_C, BROKER_B, false, 3); - PolicyMap map = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setSendAdvisoryIfNoConsumers(true); - DeadLetterStrategy deadletterStrategy = new SharedDeadLetterStrategy(); - deadletterStrategy.setProcessNonPersistent(true); - defaultEntry.setDeadLetterStrategy(deadletterStrategy); - defaultEntry.setDispatchPolicy(new PriorityDispatchPolicy()); - map.put(new ActiveMQTempTopic(">"), defaultEntry); + startAllBrokers(); - for (BrokerItem item : brokers.values()) { - item.broker.setDestinationPolicy(map); - } - } + waitForBridgeFormation(1); - @Override - protected void tearDown() throws Exception { - if (slowDownAppender != null) { - org.apache.log4j.Logger.getRootLogger().removeAppender(slowDownAppender); - } - for (Connection connection : advisoryConsumerConnections) { - connection.close(); - } - super.tearDown(); - } + HashSet bridgesStart = new HashSet(); + for (NetworkConnector networkConnector : networkConnectors) { + bridgesStart.addAll(networkConnector.activeBridges()); + } - protected NetworkConnector bridgeBrokers(String localBrokerName, String remoteBrokerName, boolean dynamicOnly, int networkTTL) throws Exception { - NetworkConnector connector = super.bridgeBrokers(localBrokerName, remoteBrokerName, dynamicOnly, networkTTL, true); - connector.setBridgeTempDestinations(true); - connector.setAdvisoryForFailedForward(true); - connector.setDuplex(useDuplex); - connector.setAlwaysSyncSend(true); - networkConnectors.add(connector); - return connector; - } + slowDownAdvisoryDispatch(); + noConsumerAdvisory(); + forwardFailureAdvisory(); - abstract class MessageClient { - protected Connection connection; - protected Session session; - protected MessageConsumer consumer; - protected MessageProducer producer; - protected Random random; - protected int timeToSleep; + // set up respondents + ExecutorService respondentThreadPool = Executors.newFixedThreadPool(50); + BrokerItem brokerA = brokers.get(BROKER_A); + ActiveMQConnectionFactory brokerAFactory = new ActiveMQConnectionFactory(brokerA.broker.getTransportConnectorByScheme("tcp").getName() + "?jms.watchTopicAdvisories=false"); + brokerAFactory.setAlwaysSyncSend(true); + for (int i = 0; i < NUM_RESPONDENTS; i++) { + respondentThreadPool.execute(new EchoRespondent(brokerAFactory)); + } - // set up the connection and session - public MessageClient(ActiveMQConnectionFactory factory, int timeToSleep) throws Exception { - this.connection = factory.createConnection(); - this.session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - this.timeToSleep = timeToSleep; - this.random = new Random(System.currentTimeMillis()); - preInit(); - initProducer(); - initConsumer(); - this.connection.start(); - } + // fire off sends + ExecutorService senderThreadPool = Executors.newCachedThreadPool(); + BrokerItem brokerC = brokers.get(BROKER_C); + ActiveMQConnectionFactory brokerCFactory = new ActiveMQConnectionFactory(brokerC.broker.getTransportConnectorByScheme("tcp").getName() + "?jms.watchTopicAdvisories=false"); + for (int i = 0; i < NUM_SENDS; i++) { + senderThreadPool.execute(new MessageSender(brokerCFactory)); + } - protected void preInit() throws JMSException { + senderThreadPool.shutdown(); + senderThreadPool.awaitTermination(30, TimeUnit.SECONDS); + TimeUnit.SECONDS.sleep(10); + LOG.info("shutting down"); + shutdown.compareAndSet(false, true); - } + HashSet bridgesEnd = new HashSet(); + for (NetworkConnector networkConnector : networkConnectors) { + bridgesEnd.addAll(networkConnector.activeBridges()); + } + assertEquals("no new bridges created", bridgesStart, bridgesEnd); - abstract protected void initProducer() throws JMSException; + // validate success or error or dlq + LOG.info("received: " + responseReceived.get() + ", respondent error: " + respondentSendError.get() + ", noConsumerCount: " + sendsWithNoConsumers.get() + ", forwardFailures: " + forwardFailures.get()); + assertEquals("success or error", NUM_SENDS, respondentSendError.get() + forwardFailures.get() + responseReceived.get() + sendsWithNoConsumers.get()); - abstract protected void initConsumer() throws JMSException; - } + } - class MessageSender extends MessageClient implements Runnable { + private void slowDownAdvisoryDispatch() throws Exception { + org.apache.log4j.Logger.getLogger(DemandForwardingBridgeSupport.class).setLevel(Level.DEBUG); - protected Destination tempDest; + // instrument a logger to block the processing of a remove sub advisory + // simulate a slow thread + slowDownAppender = new DefaultTestAppender() { + @Override + public void doAppend(LoggingEvent loggingEvent) { + if (Level.DEBUG.equals(loggingEvent.getLevel())) { + String message = loggingEvent.getMessage().toString(); + if (message.startsWith("BrokerB") && message.contains("remove local subscription")) { + // sleep for a bit + try { + consumerDemandExists.countDown(); + System.err.println("Sleeping on receipt of remove info debug message: " + message); + TimeUnit.SECONDS.sleep(2); + } + catch (Exception ignored) { + } + } - public MessageSender(ActiveMQConnectionFactory factory) throws Exception { - super(factory, RANDOM_SLEEP_FOR_SENDER_MS); - } + } + } + }; - @Override - public void run() { - // create a message + org.apache.log4j.Logger.getRootLogger().addAppender(slowDownAppender); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + responseReceived.set(0); + respondentSendError.set(0); + forwardFailures.set(0); + sendsWithNoConsumers.set(0); + networkConnectors.clear(); + advisoryConsumerConnections.clear(); + consumerDemandExists = new CountDownLatch(1); + createBroker(new URI("broker:(tcp://localhost:0)/" + BROKER_A + "?persistent=false&useJmx=false")).setDedicatedTaskRunner(false); + createBroker(new URI("broker:(tcp://localhost:0)/" + BROKER_B + "?persistent=false&useJmx=false")).setDedicatedTaskRunner(false); + createBroker(new URI("broker:(tcp://localhost:0)/" + BROKER_C + "?persistent=false&useJmx=false")).setDedicatedTaskRunner(false); + + PolicyMap map = new PolicyMap(); + PolicyEntry defaultEntry = new PolicyEntry(); + defaultEntry.setSendAdvisoryIfNoConsumers(true); + DeadLetterStrategy deadletterStrategy = new SharedDeadLetterStrategy(); + deadletterStrategy.setProcessNonPersistent(true); + defaultEntry.setDeadLetterStrategy(deadletterStrategy); + defaultEntry.setDispatchPolicy(new PriorityDispatchPolicy()); + map.put(new ActiveMQTempTopic(">"), defaultEntry); + + for (BrokerItem item : brokers.values()) { + item.broker.setDestinationPolicy(map); + } + } + + @Override + protected void tearDown() throws Exception { + if (slowDownAppender != null) { + org.apache.log4j.Logger.getRootLogger().removeAppender(slowDownAppender); + } + for (Connection connection : advisoryConsumerConnections) { + connection.close(); + } + super.tearDown(); + } + + protected NetworkConnector bridgeBrokers(String localBrokerName, + String remoteBrokerName, + boolean dynamicOnly, + int networkTTL) throws Exception { + NetworkConnector connector = super.bridgeBrokers(localBrokerName, remoteBrokerName, dynamicOnly, networkTTL, true); + connector.setBridgeTempDestinations(true); + connector.setAdvisoryForFailedForward(true); + connector.setDuplex(useDuplex); + connector.setAlwaysSyncSend(true); + networkConnectors.add(connector); + return connector; + } + + abstract class MessageClient { + + protected Connection connection; + protected Session session; + protected MessageConsumer consumer; + protected MessageProducer producer; + protected Random random; + protected int timeToSleep; + + // set up the connection and session + public MessageClient(ActiveMQConnectionFactory factory, int timeToSleep) throws Exception { + this.connection = factory.createConnection(); + this.session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + this.timeToSleep = timeToSleep; + this.random = new Random(System.currentTimeMillis()); + preInit(); + initProducer(); + initConsumer(); + this.connection.start(); + } + + protected void preInit() throws JMSException { + + } + + abstract protected void initProducer() throws JMSException; + + abstract protected void initConsumer() throws JMSException; + } + + class MessageSender extends MessageClient implements Runnable { + + protected Destination tempDest; + + public MessageSender(ActiveMQConnectionFactory factory) throws Exception { + super(factory, RANDOM_SLEEP_FOR_SENDER_MS); + } + + @Override + public void run() { + // create a message + try { + TextMessage message = session.createTextMessage("request: message #" + messageCount.getAndIncrement()); + message.setJMSReplyTo(tempDest); + producer.send(message); + LOG.info("SENDER: Message [" + message.getText() + "] has been sent."); + + Message incomingMessage = consumer.receive(timeToSleep); + if (incomingMessage instanceof TextMessage) { + try { + LOG.info("SENDER: Got a response from echo service!" + ((TextMessage) incomingMessage).getText()); + responseReceived.incrementAndGet(); + } + catch (JMSException e) { + LOG.error("SENDER: might want to see why i'm getting non-text messages..." + incomingMessage, e); + } + } + else { + LOG.info("SENDER: Did not get a response this time"); + } + + } + catch (JMSException e) { + LOG.error("SENDER: Could not complete message sending properly: " + e.getMessage()); + } + finally { try { - TextMessage message = session.createTextMessage("request: message #" + messageCount.getAndIncrement()); - message.setJMSReplyTo(tempDest); - producer.send(message); - LOG.info("SENDER: Message [" + message.getText() + "] has been sent."); - - Message incomingMessage = consumer.receive(timeToSleep); - if (incomingMessage instanceof TextMessage) { - try { - LOG.info("SENDER: Got a response from echo service!" + ((TextMessage) incomingMessage).getText()); - responseReceived.incrementAndGet(); - } catch (JMSException e) { - LOG.error("SENDER: might want to see why i'm getting non-text messages..." + incomingMessage, e); - } - } else { - LOG.info("SENDER: Did not get a response this time"); - } - - - } catch (JMSException e) { - LOG.error("SENDER: Could not complete message sending properly: " + e.getMessage()); - } finally { - try { - producer.close(); - consumer.close(); - session.close(); - connection.close(); - } catch (JMSException e) { - e.printStackTrace(); - } + producer.close(); + consumer.close(); + session.close(); + connection.close(); } - } - - @Override - protected void preInit() throws JMSException { - this.tempDest = session.createTemporaryTopic(); - - } - - @Override - protected void initProducer() throws JMSException { - this.producer = session.createProducer(new ActiveMQQueue(QUEUE_NAME)); - } - - @Override - protected void initConsumer() throws JMSException { - this.consumer = session.createConsumer(tempDest); - LOG.info("consumer for: " + tempDest + ", " + consumer); - - } - - } - - class EchoRespondent extends MessageClient implements Runnable { - - public EchoRespondent(ActiveMQConnectionFactory factory) throws Exception { - super(factory, RANDOM_SLEEP_FOR_RESPONDENT_MS); - } - - @Override - public void run() { - try { - LOG.info("RESPONDENT LISTENING"); - while (!shutdown.get()) { - Message incomingMessage = consumer.receive(1000); - if (incomingMessage instanceof TextMessage) { - ActiveMQTextMessage textMessage = (ActiveMQTextMessage) incomingMessage; - try { - LOG.info("RESPONDENT: Received a message: [" + textMessage.getText() + "]" + Arrays.asList(textMessage.getBrokerPath())); - Message message = session.createTextMessage("reply: " + textMessage.getText()); - Destination replyTo = incomingMessage.getJMSReplyTo(); - TimeUnit.MILLISECONDS.sleep(timeToSleep); - consumerDemandExists.await(5, TimeUnit.SECONDS); - try { - producer.send(replyTo, message); - LOG.info("RESPONDENT: sent reply:" + message.getJMSMessageID() + " back to: " + replyTo); - } catch (JMSException e) { - LOG.error("RESPONDENT: could not send reply message: " + e.getLocalizedMessage(), e); - respondentSendError.incrementAndGet(); - } - } catch (JMSException e) { - LOG.error("RESPONDENT: could not create the reply message: " + e.getLocalizedMessage(), e); - } catch (InterruptedException e) { - LOG.info("RESPONDENT could not generate a random number"); - } - } - } - } catch (JMSException e) { - LOG.info("RESPONDENT: Could not set the message listener on the respondent"); + catch (JMSException e) { + e.printStackTrace(); } - } + } + } - @Override - protected void initProducer() throws JMSException { - this.producer = session.createProducer(null); - // so that we can get an advisory on sending with no consumers - this.producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - } + @Override + protected void preInit() throws JMSException { + this.tempDest = session.createTemporaryTopic(); - @Override - protected void initConsumer() throws JMSException { - this.consumer = session.createConsumer(new ActiveMQQueue(QUEUE_NAME)); - } - } + } + + @Override + protected void initProducer() throws JMSException { + this.producer = session.createProducer(new ActiveMQQueue(QUEUE_NAME)); + } + + @Override + protected void initConsumer() throws JMSException { + this.consumer = session.createConsumer(tempDest); + LOG.info("consumer for: " + tempDest + ", " + consumer); + + } + + } + + class EchoRespondent extends MessageClient implements Runnable { + + public EchoRespondent(ActiveMQConnectionFactory factory) throws Exception { + super(factory, RANDOM_SLEEP_FOR_RESPONDENT_MS); + } + + @Override + public void run() { + try { + LOG.info("RESPONDENT LISTENING"); + while (!shutdown.get()) { + Message incomingMessage = consumer.receive(1000); + if (incomingMessage instanceof TextMessage) { + ActiveMQTextMessage textMessage = (ActiveMQTextMessage) incomingMessage; + try { + LOG.info("RESPONDENT: Received a message: [" + textMessage.getText() + "]" + Arrays.asList(textMessage.getBrokerPath())); + Message message = session.createTextMessage("reply: " + textMessage.getText()); + Destination replyTo = incomingMessage.getJMSReplyTo(); + TimeUnit.MILLISECONDS.sleep(timeToSleep); + consumerDemandExists.await(5, TimeUnit.SECONDS); + try { + producer.send(replyTo, message); + LOG.info("RESPONDENT: sent reply:" + message.getJMSMessageID() + " back to: " + replyTo); + } + catch (JMSException e) { + LOG.error("RESPONDENT: could not send reply message: " + e.getLocalizedMessage(), e); + respondentSendError.incrementAndGet(); + } + } + catch (JMSException e) { + LOG.error("RESPONDENT: could not create the reply message: " + e.getLocalizedMessage(), e); + } + catch (InterruptedException e) { + LOG.info("RESPONDENT could not generate a random number"); + } + } + } + } + catch (JMSException e) { + LOG.info("RESPONDENT: Could not set the message listener on the respondent"); + } + } + + @Override + protected void initProducer() throws JMSException { + this.producer = session.createProducer(null); + // so that we can get an advisory on sending with no consumers + this.producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + } + + @Override + protected void initConsumer() throws JMSException { + this.consumer = session.createConsumer(new ActiveMQQueue(QUEUE_NAME)); + } + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/RequestReplyToTopicViaThreeNetworkHopsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/RequestReplyToTopicViaThreeNetworkHopsTest.java index 0c042f482e..787312ffd5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/RequestReplyToTopicViaThreeNetworkHopsTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/RequestReplyToTopicViaThreeNetworkHopsTest.java @@ -48,930 +48,959 @@ import org.apache.commons.logging.LogFactory; import org.junit.Test; public class RequestReplyToTopicViaThreeNetworkHopsTest { - protected static final int CONCURRENT_CLIENT_COUNT = 5; - protected static final int CONCURRENT_SERVER_COUNT = 5; - protected static final int TOTAL_CLIENT_ITER = 10; - - protected static int Next_broker_num = 0; - protected EmbeddedTcpBroker edge1; - protected EmbeddedTcpBroker edge2; - protected EmbeddedTcpBroker core1; - protected EmbeddedTcpBroker core2; - - protected boolean testError = false; - protected boolean fatalTestError = false; - - protected int echoResponseFill = 0; // Number of "filler" response messages per request - - protected static Log LOG; - public boolean duplex = true; - - static { - LOG = LogFactory.getLog(RequestReplyToTopicViaThreeNetworkHopsTest.class); - } - - public RequestReplyToTopicViaThreeNetworkHopsTest() throws Exception { - edge1 = new EmbeddedTcpBroker("edge", 1); - edge2 = new EmbeddedTcpBroker("edge", 2); - core1 = new EmbeddedTcpBroker("core", 1); - core2 = new EmbeddedTcpBroker("core", 2); - - // duplex is necessary to serialise sends with consumer/destination creation - edge1.coreConnectTo(core1, duplex); - edge2.coreConnectTo(core2, duplex); - core1.coreConnectTo(core2, duplex); - } - - public void logMessage(String msg) { - System.out.println(msg); - System.out.flush(); - } - - public void testMessages(Session sess, MessageProducer req_prod, Destination resp_dest, int num_msg) throws Exception { - MessageConsumer resp_cons; - TextMessage msg; - MessageClient cons_client; - int cur; - int tot_expected; - - resp_cons = sess.createConsumer(resp_dest); - - cons_client = new MessageClient(resp_cons, num_msg); - cons_client.start(); - - cur = 0; - while ((cur < num_msg) && (!fatalTestError)) { - msg = sess.createTextMessage("MSG AAAA " + cur); - msg.setIntProperty("SEQ", 100 + cur); - msg.setStringProperty("TEST", "TOPO"); - msg.setJMSReplyTo(resp_dest); - - if (cur == (num_msg - 1)) - msg.setBooleanProperty("end-of-response", true); - - sendWithRetryOnDeletedDest(req_prod, msg); - LOG.debug("Sent:" + msg); - - cur++; - } - - // - // Give the consumer some time to receive the response. - // - cons_client.waitShutdown(5000); - - // - // Now shutdown the consumer if it's still running. - // - if (cons_client.shutdown()) - LOG.debug("Consumer client shutdown complete"); - else - LOG.debug("Consumer client shutdown incomplete!!!"); - - // - // Check that the correct number of messages was received. - // - tot_expected = num_msg * (echoResponseFill + 1); - - if (cons_client.getNumMsgReceived() == tot_expected) { - LOG.debug("Have " + tot_expected + " messages, as-expected"); - } else { - testError = true; - - if (cons_client.getNumMsgReceived() == 0) - fatalTestError = true; - - LOG.error("Have " + cons_client.getNumMsgReceived() + " messages; expected " + tot_expected + " on destination " + resp_dest); - } - - resp_cons.close(); - } - - protected void sendWithRetryOnDeletedDest(MessageProducer prod, Message msg) throws JMSException { - try { - if (LOG.isDebugEnabled()) - LOG.debug("SENDING REQUEST message " + msg); - - prod.send(msg); - } catch (JMSException jms_exc) { - System.out.println("AAA: " + jms_exc.getMessage()); - throw jms_exc; - } - } - - /** - * Test one destination between the given "producer broker" and "consumer broker" specified. - */ - public void testOneDest(Connection conn, Session sess, Destination cons_dest, int num_msg) throws Exception { - Destination prod_dest; - MessageProducer msg_prod; - - // - // Create the Producer to the echo request Queue - // - LOG.trace("Creating echo queue and producer"); - prod_dest = sess.createQueue("echo"); - msg_prod = sess.createProducer(prod_dest); - - // - // Pass messages around. - // - testMessages(sess, msg_prod, cons_dest, num_msg); - - msg_prod.close(); - } - - /** - * TEST TEMPORARY TOPICS - */ - public void testTempTopic(String prod_broker_url, String cons_broker_url) throws Exception { - Connection conn; - Session sess; - Destination cons_dest; - int num_msg; - - num_msg = 5; - - LOG.debug("TESTING TEMP TOPICS " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)"); - - // - // Connect to the bus. - // - conn = createConnection(cons_broker_url); - conn.start(); - sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // - // Create the destination on which messages are being tested. - // - LOG.trace("Creating destination"); - cons_dest = sess.createTemporaryTopic(); - - testOneDest(conn, sess, cons_dest, num_msg); - - // - // Cleanup - // - sess.close(); - conn.close(); - } - - /** - * TEST TOPICS - */ - public void testTopic(String prod_broker_url, String cons_broker_url) throws Exception { - int num_msg; - - Connection conn; - Session sess; - String topic_name; - - Destination cons_dest; - - num_msg = 5; - - LOG.info("TESTING TOPICS " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)"); - - conn = createConnection(cons_broker_url); - conn.start(); - sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // - // Create the destination on which messages are being tested. - // - topic_name = "topotest2.perm.topic"; - LOG.trace("Removing existing Topic"); - removeTopic(conn, topic_name); - LOG.trace("Creating Topic, " + topic_name); - cons_dest = sess.createTopic(topic_name); - - testOneDest(conn, sess, cons_dest, num_msg); - - // - // Cleanup - // - removeTopic(conn, topic_name); - sess.close(); - conn.close(); - } - - /** - * TEST TEMPORARY QUEUES - */ - public void testTempQueue(String prod_broker_url, String cons_broker_url) throws Exception { - int num_msg; - - Connection conn; - Session sess; - - Destination cons_dest; - - num_msg = 5; - - LOG.info("TESTING TEMP QUEUES " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)"); - - // - // Connect to the bus. - // - conn = createConnection(cons_broker_url); - conn.start(); - sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // - // Create the destination on which messages are being tested. - // - LOG.trace("Creating destination"); - cons_dest = sess.createTemporaryQueue(); - - testOneDest(conn, sess, cons_dest, num_msg); - - // - // Cleanup - // - sess.close(); - conn.close(); - } - - /** - * TEST QUEUES - */ - public void testQueue(String prod_broker_url, String cons_broker_url) throws Exception { - int num_msg; - - Connection conn; - Session sess; - String queue_name; - - Destination cons_dest; - - num_msg = 5; - - LOG.info("TESTING QUEUES " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)"); - - conn = createConnection(cons_broker_url); - conn.start(); - sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // - // Create the destination on which messages are being tested. - // - queue_name = "topotest2.perm.queue"; - LOG.trace("Removing existing Queue"); - removeQueue(conn, queue_name); - LOG.trace("Creating Queue, " + queue_name); - cons_dest = sess.createQueue(queue_name); - - testOneDest(conn, sess, cons_dest, num_msg); - - removeQueue(conn, queue_name); - sess.close(); - conn.close(); - } - - @Test - public void runWithTempTopicReplyTo() throws Exception { - EchoService echo_svc; - TopicTrafficGenerator traffic_gen; - Thread start1; - Thread start2; - Thread start3; - Thread start4; - ThreadPoolExecutor clientExecPool; - final CountDownLatch clientCompletionLatch; - int iter; - - fatalTestError = false; - testError = false; - - // - // Execute up to 20 clients at a time to simulate that load. - // - - clientExecPool = new ThreadPoolExecutor(CONCURRENT_CLIENT_COUNT, CONCURRENT_CLIENT_COUNT, 0, TimeUnit.SECONDS, new ArrayBlockingQueue(10000)); - clientCompletionLatch = new CountDownLatch(TOTAL_CLIENT_ITER); - - // Use threads to avoid startup deadlock since the first broker started waits until - // it knows the name of the remote broker before finishing its startup, which means - // the remote must already be running. - - start1 = new Thread() { + + protected static final int CONCURRENT_CLIENT_COUNT = 5; + protected static final int CONCURRENT_SERVER_COUNT = 5; + protected static final int TOTAL_CLIENT_ITER = 10; + + protected static int Next_broker_num = 0; + protected EmbeddedTcpBroker edge1; + protected EmbeddedTcpBroker edge2; + protected EmbeddedTcpBroker core1; + protected EmbeddedTcpBroker core2; + + protected boolean testError = false; + protected boolean fatalTestError = false; + + protected int echoResponseFill = 0; // Number of "filler" response messages per request + + protected static Log LOG; + public boolean duplex = true; + + static { + LOG = LogFactory.getLog(RequestReplyToTopicViaThreeNetworkHopsTest.class); + } + + public RequestReplyToTopicViaThreeNetworkHopsTest() throws Exception { + edge1 = new EmbeddedTcpBroker("edge", 1); + edge2 = new EmbeddedTcpBroker("edge", 2); + core1 = new EmbeddedTcpBroker("core", 1); + core2 = new EmbeddedTcpBroker("core", 2); + + // duplex is necessary to serialise sends with consumer/destination creation + edge1.coreConnectTo(core1, duplex); + edge2.coreConnectTo(core2, duplex); + core1.coreConnectTo(core2, duplex); + } + + public void logMessage(String msg) { + System.out.println(msg); + System.out.flush(); + } + + public void testMessages(Session sess, + MessageProducer req_prod, + Destination resp_dest, + int num_msg) throws Exception { + MessageConsumer resp_cons; + TextMessage msg; + MessageClient cons_client; + int cur; + int tot_expected; + + resp_cons = sess.createConsumer(resp_dest); + + cons_client = new MessageClient(resp_cons, num_msg); + cons_client.start(); + + cur = 0; + while ((cur < num_msg) && (!fatalTestError)) { + msg = sess.createTextMessage("MSG AAAA " + cur); + msg.setIntProperty("SEQ", 100 + cur); + msg.setStringProperty("TEST", "TOPO"); + msg.setJMSReplyTo(resp_dest); + + if (cur == (num_msg - 1)) + msg.setBooleanProperty("end-of-response", true); + + sendWithRetryOnDeletedDest(req_prod, msg); + LOG.debug("Sent:" + msg); + + cur++; + } + + // + // Give the consumer some time to receive the response. + // + cons_client.waitShutdown(5000); + + // + // Now shutdown the consumer if it's still running. + // + if (cons_client.shutdown()) + LOG.debug("Consumer client shutdown complete"); + else + LOG.debug("Consumer client shutdown incomplete!!!"); + + // + // Check that the correct number of messages was received. + // + tot_expected = num_msg * (echoResponseFill + 1); + + if (cons_client.getNumMsgReceived() == tot_expected) { + LOG.debug("Have " + tot_expected + " messages, as-expected"); + } + else { + testError = true; + + if (cons_client.getNumMsgReceived() == 0) + fatalTestError = true; + + LOG.error("Have " + cons_client.getNumMsgReceived() + " messages; expected " + tot_expected + " on destination " + resp_dest); + } + + resp_cons.close(); + } + + protected void sendWithRetryOnDeletedDest(MessageProducer prod, Message msg) throws JMSException { + try { + if (LOG.isDebugEnabled()) + LOG.debug("SENDING REQUEST message " + msg); + + prod.send(msg); + } + catch (JMSException jms_exc) { + System.out.println("AAA: " + jms_exc.getMessage()); + throw jms_exc; + } + } + + /** + * Test one destination between the given "producer broker" and "consumer broker" specified. + */ + public void testOneDest(Connection conn, Session sess, Destination cons_dest, int num_msg) throws Exception { + Destination prod_dest; + MessageProducer msg_prod; + + // + // Create the Producer to the echo request Queue + // + LOG.trace("Creating echo queue and producer"); + prod_dest = sess.createQueue("echo"); + msg_prod = sess.createProducer(prod_dest); + + // + // Pass messages around. + // + testMessages(sess, msg_prod, cons_dest, num_msg); + + msg_prod.close(); + } + + /** + * TEST TEMPORARY TOPICS + */ + public void testTempTopic(String prod_broker_url, String cons_broker_url) throws Exception { + Connection conn; + Session sess; + Destination cons_dest; + int num_msg; + + num_msg = 5; + + LOG.debug("TESTING TEMP TOPICS " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)"); + + // + // Connect to the bus. + // + conn = createConnection(cons_broker_url); + conn.start(); + sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + + // + // Create the destination on which messages are being tested. + // + LOG.trace("Creating destination"); + cons_dest = sess.createTemporaryTopic(); + + testOneDest(conn, sess, cons_dest, num_msg); + + // + // Cleanup + // + sess.close(); + conn.close(); + } + + /** + * TEST TOPICS + */ + public void testTopic(String prod_broker_url, String cons_broker_url) throws Exception { + int num_msg; + + Connection conn; + Session sess; + String topic_name; + + Destination cons_dest; + + num_msg = 5; + + LOG.info("TESTING TOPICS " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)"); + + conn = createConnection(cons_broker_url); + conn.start(); + sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + + // + // Create the destination on which messages are being tested. + // + topic_name = "topotest2.perm.topic"; + LOG.trace("Removing existing Topic"); + removeTopic(conn, topic_name); + LOG.trace("Creating Topic, " + topic_name); + cons_dest = sess.createTopic(topic_name); + + testOneDest(conn, sess, cons_dest, num_msg); + + // + // Cleanup + // + removeTopic(conn, topic_name); + sess.close(); + conn.close(); + } + + /** + * TEST TEMPORARY QUEUES + */ + public void testTempQueue(String prod_broker_url, String cons_broker_url) throws Exception { + int num_msg; + + Connection conn; + Session sess; + + Destination cons_dest; + + num_msg = 5; + + LOG.info("TESTING TEMP QUEUES " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)"); + + // + // Connect to the bus. + // + conn = createConnection(cons_broker_url); + conn.start(); + sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + + // + // Create the destination on which messages are being tested. + // + LOG.trace("Creating destination"); + cons_dest = sess.createTemporaryQueue(); + + testOneDest(conn, sess, cons_dest, num_msg); + + // + // Cleanup + // + sess.close(); + conn.close(); + } + + /** + * TEST QUEUES + */ + public void testQueue(String prod_broker_url, String cons_broker_url) throws Exception { + int num_msg; + + Connection conn; + Session sess; + String queue_name; + + Destination cons_dest; + + num_msg = 5; + + LOG.info("TESTING QUEUES " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)"); + + conn = createConnection(cons_broker_url); + conn.start(); + sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + + // + // Create the destination on which messages are being tested. + // + queue_name = "topotest2.perm.queue"; + LOG.trace("Removing existing Queue"); + removeQueue(conn, queue_name); + LOG.trace("Creating Queue, " + queue_name); + cons_dest = sess.createQueue(queue_name); + + testOneDest(conn, sess, cons_dest, num_msg); + + removeQueue(conn, queue_name); + sess.close(); + conn.close(); + } + + @Test + public void runWithTempTopicReplyTo() throws Exception { + EchoService echo_svc; + TopicTrafficGenerator traffic_gen; + Thread start1; + Thread start2; + Thread start3; + Thread start4; + ThreadPoolExecutor clientExecPool; + final CountDownLatch clientCompletionLatch; + int iter; + + fatalTestError = false; + testError = false; + + // + // Execute up to 20 clients at a time to simulate that load. + // + + clientExecPool = new ThreadPoolExecutor(CONCURRENT_CLIENT_COUNT, CONCURRENT_CLIENT_COUNT, 0, TimeUnit.SECONDS, new ArrayBlockingQueue(10000)); + clientCompletionLatch = new CountDownLatch(TOTAL_CLIENT_ITER); + + // Use threads to avoid startup deadlock since the first broker started waits until + // it knows the name of the remote broker before finishing its startup, which means + // the remote must already be running. + + start1 = new Thread() { + @Override + public void run() { + try { + edge1.start(); + } + catch (Exception ex) { + LOG.error(null, ex); + } + } + }; + + start2 = new Thread() { + @Override + public void run() { + try { + edge2.start(); + } + catch (Exception ex) { + LOG.error(null, ex); + } + } + }; + + start3 = new Thread() { + @Override + public void run() { + try { + core1.start(); + } + catch (Exception ex) { + LOG.error(null, ex); + } + } + }; + + start4 = new Thread() { + @Override + public void run() { + try { + core2.start(); + } + catch (Exception ex) { + LOG.error(null, ex); + } + } + }; + + start1.start(); + start2.start(); + start3.start(); + start4.start(); + + start1.join(); + start2.join(); + start3.join(); + start4.join(); + + traffic_gen = new TopicTrafficGenerator(edge1.getConnectionUrl(), edge2.getConnectionUrl()); + traffic_gen.start(); + + // + // Now start the echo service with that queue. + // + echo_svc = new EchoService("echo", edge1.getConnectionUrl()); + echo_svc.start(); + + // + // Run the tests on Temp Topics. + // + + LOG.info("** STARTING TEMP TOPIC TESTS"); + iter = 0; + while ((iter < TOTAL_CLIENT_ITER) && (!fatalTestError)) { + clientExecPool.execute(new Runnable() { @Override public void run() { - try { - edge1.start(); - } catch (Exception ex) { - LOG.error(null, ex); - } + try { + RequestReplyToTopicViaThreeNetworkHopsTest.this.testTempTopic(edge1.getConnectionUrl(), edge2.getConnectionUrl()); + } + catch (Exception exc) { + LOG.error("test exception", exc); + fatalTestError = true; + testError = true; + } + + clientCompletionLatch.countDown(); } - }; + }); - start2 = new Thread() { - @Override - public void run() { - try { - edge2.start(); - } catch (Exception ex) { - LOG.error(null, ex); - } - } - }; + iter++; + } - start3 = new Thread() { - @Override - public void run() { - try { - core1.start(); - } catch (Exception ex) { - LOG.error(null, ex); - } - } - }; + boolean allDoneOnTime = clientCompletionLatch.await(20, TimeUnit.MINUTES); - start4 = new Thread() { - @Override - public void run() { - try { - core2.start(); - } catch (Exception ex) { - LOG.error(null, ex); - } - } - }; + LOG.info("** FINISHED TEMP TOPIC TESTS AFTER " + iter + " ITERATIONS, testError:" + testError + ", fatal: " + fatalTestError + ", onTime:" + allDoneOnTime); - start1.start(); - start2.start(); - start3.start(); - start4.start(); + Thread.sleep(100); - start1.join(); - start2.join(); - start3.join(); - start4.join(); + echo_svc.shutdown(); + traffic_gen.shutdown(); - traffic_gen = new TopicTrafficGenerator(edge1.getConnectionUrl(), edge2.getConnectionUrl()); - traffic_gen.start(); + shutdown(); - // - // Now start the echo service with that queue. - // - echo_svc = new EchoService("echo", edge1.getConnectionUrl()); - echo_svc.start(); + assertTrue("test completed in time", allDoneOnTime); + assertTrue("no errors", !testError); + } - // - // Run the tests on Temp Topics. - // + public void shutdown() throws Exception { + edge1.stop(); + edge2.stop(); + core1.stop(); + core2.stop(); + } - LOG.info("** STARTING TEMP TOPIC TESTS"); - iter = 0; - while ((iter < TOTAL_CLIENT_ITER) && (!fatalTestError)) { - clientExecPool.execute(new Runnable() { - @Override - public void run() { - try { - RequestReplyToTopicViaThreeNetworkHopsTest.this.testTempTopic(edge1.getConnectionUrl(), edge2.getConnectionUrl()); - } catch (Exception exc) { - LOG.error("test exception", exc); - fatalTestError = true; - testError = true; - } + protected Connection createConnection(String url) throws Exception { + return org.apache.activemq.ActiveMQConnection.makeConnection(url); + } - clientCompletionLatch.countDown(); - } - }); + protected static void removeQueue(Connection conn, String dest_name) throws java.lang.Exception { + org.apache.activemq.command.ActiveMQDestination dest; - iter++; - } + if (conn instanceof org.apache.activemq.ActiveMQConnection) { + dest = org.apache.activemq.command.ActiveMQDestination.createDestination(dest_name, org.apache.activemq.command.ActiveMQDestination.QUEUE_TYPE); + ((org.apache.activemq.ActiveMQConnection) conn).destroyDestination(dest); + } + } - boolean allDoneOnTime = clientCompletionLatch.await(20, TimeUnit.MINUTES); + protected static void removeTopic(Connection conn, String dest_name) throws java.lang.Exception { + org.apache.activemq.command.ActiveMQDestination dest; - LOG.info("** FINISHED TEMP TOPIC TESTS AFTER " + iter + " ITERATIONS, testError:" + testError + ", fatal: " + fatalTestError + ", onTime:" - + allDoneOnTime); + if (conn instanceof org.apache.activemq.ActiveMQConnection) { + dest = org.apache.activemq.command.ActiveMQDestination.createDestination(dest_name, org.apache.activemq.command.ActiveMQDestination.TOPIC_TYPE); + ((org.apache.activemq.ActiveMQConnection) conn).destroyDestination(dest); + } + } - Thread.sleep(100); + public static String fmtMsgInfo(Message msg) throws Exception { + StringBuilder msg_desc; + String prop; + Enumeration prop_enum; - echo_svc.shutdown(); - traffic_gen.shutdown(); + msg_desc = new StringBuilder(); + msg_desc = new StringBuilder(); - shutdown(); + if (msg instanceof TextMessage) { + msg_desc.append(((TextMessage) msg).getText()); + } + else { + msg_desc.append("["); + msg_desc.append(msg.getClass().getName()); + msg_desc.append("]"); + } - assertTrue("test completed in time", allDoneOnTime); - assertTrue("no errors", !testError); - } + prop_enum = msg.getPropertyNames(); + while (prop_enum.hasMoreElements()) { + prop = (String) prop_enum.nextElement(); + msg_desc.append("; "); + msg_desc.append(prop); + msg_desc.append("="); + msg_desc.append(msg.getStringProperty(prop)); + } - public void shutdown() throws Exception { - edge1.stop(); - edge2.stop(); - core1.stop(); - core2.stop(); - } + return msg_desc.toString(); + } - protected Connection createConnection(String url) throws Exception { - return org.apache.activemq.ActiveMQConnection.makeConnection(url); - } + protected class EmbeddedTcpBroker { - protected static void removeQueue(Connection conn, String dest_name) throws java.lang.Exception { - org.apache.activemq.command.ActiveMQDestination dest; + protected BrokerService brokerSvc; + protected int brokerNum; + protected String brokerName; + protected String brokerId; + protected int port; + protected String tcpUrl; + protected String fullUrl; - if (conn instanceof org.apache.activemq.ActiveMQConnection) { - dest = org.apache.activemq.command.ActiveMQDestination.createDestination(dest_name, org.apache.activemq.command.ActiveMQDestination.QUEUE_TYPE); - ((org.apache.activemq.ActiveMQConnection) conn).destroyDestination(dest); - } - } + public EmbeddedTcpBroker(String name, int number) throws Exception { + brokerSvc = new BrokerService(); - protected static void removeTopic(Connection conn, String dest_name) throws java.lang.Exception { - org.apache.activemq.command.ActiveMQDestination dest; + synchronized (this.getClass()) { + brokerNum = Next_broker_num; + Next_broker_num++; + } - if (conn instanceof org.apache.activemq.ActiveMQConnection) { - dest = org.apache.activemq.command.ActiveMQDestination.createDestination(dest_name, org.apache.activemq.command.ActiveMQDestination.TOPIC_TYPE); - ((org.apache.activemq.ActiveMQConnection) conn).destroyDestination(dest); - } - } + brokerName = name + number; + brokerId = brokerName; - public static String fmtMsgInfo(Message msg) throws Exception { - StringBuilder msg_desc; - String prop; - Enumeration prop_enum; + brokerSvc.setBrokerName(brokerName); + brokerSvc.setBrokerId(brokerId); - msg_desc = new StringBuilder(); - msg_desc = new StringBuilder(); + brokerSvc.setPersistent(false); + brokerSvc.setUseJmx(false); - if (msg instanceof TextMessage) { - msg_desc.append(((TextMessage) msg).getText()); - } else { - msg_desc.append("["); - msg_desc.append(msg.getClass().getName()); - msg_desc.append("]"); - } + port = 60000 + (brokerNum * 10); - prop_enum = msg.getPropertyNames(); - while (prop_enum.hasMoreElements()) { - prop = (String) prop_enum.nextElement(); - msg_desc.append("; "); - msg_desc.append(prop); - msg_desc.append("="); - msg_desc.append(msg.getStringProperty(prop)); - } + tcpUrl = "tcp://127.0.0.1:" + Integer.toString(port); + fullUrl = tcpUrl + "?jms.watchTopicAdvisories=false"; - return msg_desc.toString(); - } + brokerSvc.addConnector(tcpUrl); + } - protected class EmbeddedTcpBroker { - protected BrokerService brokerSvc; - protected int brokerNum; - protected String brokerName; - protected String brokerId; - protected int port; - protected String tcpUrl; - protected String fullUrl; + public Connection createConnection() throws URISyntaxException, JMSException { + Connection result; - public EmbeddedTcpBroker(String name, int number) throws Exception { - brokerSvc = new BrokerService(); + result = org.apache.activemq.ActiveMQConnection.makeConnection(this.fullUrl); - synchronized (this.getClass()) { - brokerNum = Next_broker_num; - Next_broker_num++; + return result; + } + + public String getConnectionUrl() { + return this.fullUrl; + } + + public void coreConnectTo(EmbeddedTcpBroker other, boolean duplex_f) throws Exception { + this.makeConnectionTo(other, duplex_f, true); + this.makeConnectionTo(other, duplex_f, false); + if (!duplex_f) { + other.makeConnectionTo(this, duplex_f, true); + other.makeConnectionTo(this, duplex_f, false); + } + } + + public void start() throws Exception { + brokerSvc.start(); + brokerSvc.waitUntilStarted(); + } + + public void stop() throws Exception { + brokerSvc.stop(); + } + + protected void makeConnectionTo(EmbeddedTcpBroker other, boolean duplex_f, boolean queue_f) throws Exception { + NetworkConnector nw_conn; + String prefix; + ActiveMQDestination excl_dest; + ArrayList excludes; + + nw_conn = new DiscoveryNetworkConnector(new URI("static:(" + other.tcpUrl + ")")); + nw_conn.setDuplex(duplex_f); + + if (queue_f) + nw_conn.setConduitSubscriptions(false); + else + nw_conn.setConduitSubscriptions(true); + + nw_conn.setNetworkTTL(3); + nw_conn.setSuppressDuplicateQueueSubscriptions(true); + nw_conn.setDecreaseNetworkConsumerPriority(true); + nw_conn.setBridgeTempDestinations(queue_f); + + if (queue_f) { + prefix = "queue"; + excl_dest = ActiveMQDestination.createDestination(">", ActiveMQDestination.TOPIC_TYPE); + } + else { + prefix = "topic"; + excl_dest = ActiveMQDestination.createDestination(">", ActiveMQDestination.QUEUE_TYPE); + } + + excludes = new ArrayList(); + excludes.add(excl_dest); + nw_conn.setExcludedDestinations(excludes); + + if (duplex_f) + nw_conn.setName(this.brokerId + "<-" + prefix + "->" + other.brokerId); + else + nw_conn.setName(this.brokerId + "-" + prefix + "->" + other.brokerId); + + brokerSvc.addNetworkConnector(nw_conn); + } + } + + protected class MessageClient extends java.lang.Thread { + + protected MessageConsumer msgCons; + protected boolean shutdownInd; + protected int expectedCount; + protected int lastSeq = 0; + protected int msgCount = 0; + protected boolean haveFirstSeq; + protected CountDownLatch shutdownLatch; + + public MessageClient(MessageConsumer cons, int num_to_expect) { + msgCons = cons; + expectedCount = (num_to_expect * (echoResponseFill + 1)); + shutdownLatch = new CountDownLatch(1); + } + + @Override + public void run() { + CountDownLatch latch; + + try { + synchronized (this) { + latch = shutdownLatch; } - brokerName = name + number; - brokerId = brokerName; + shutdownInd = false; + processMessages(); - brokerSvc.setBrokerName(brokerName); - brokerSvc.setBrokerId(brokerId); + latch.countDown(); + } + catch (Exception exc) { + LOG.error("message client error", exc); + } + } - brokerSvc.setPersistent(false); - brokerSvc.setUseJmx(false); + public void waitShutdown(long timeout) { + CountDownLatch latch; - port = 60000 + (brokerNum * 10); - - tcpUrl = "tcp://127.0.0.1:" + Integer.toString(port); - fullUrl = tcpUrl + "?jms.watchTopicAdvisories=false"; - - brokerSvc.addConnector(tcpUrl); - } - - public Connection createConnection() throws URISyntaxException, JMSException { - Connection result; - - result = org.apache.activemq.ActiveMQConnection.makeConnection(this.fullUrl); - - return result; - } - - public String getConnectionUrl() { - return this.fullUrl; - } - - public void coreConnectTo(EmbeddedTcpBroker other, boolean duplex_f) throws Exception { - this.makeConnectionTo(other, duplex_f, true); - this.makeConnectionTo(other, duplex_f, false); - if (!duplex_f) { - other.makeConnectionTo(this, duplex_f, true); - other.makeConnectionTo(this, duplex_f, false); + try { + synchronized (this) { + latch = shutdownLatch; } - } - public void start() throws Exception { - brokerSvc.start(); - brokerSvc.waitUntilStarted(); - } - - public void stop() throws Exception { - brokerSvc.stop(); - } - - protected void makeConnectionTo(EmbeddedTcpBroker other, boolean duplex_f, boolean queue_f) throws Exception { - NetworkConnector nw_conn; - String prefix; - ActiveMQDestination excl_dest; - ArrayList excludes; - - nw_conn = new DiscoveryNetworkConnector(new URI("static:(" + other.tcpUrl + ")")); - nw_conn.setDuplex(duplex_f); - - if (queue_f) - nw_conn.setConduitSubscriptions(false); + if (latch != null) + latch.await(timeout, TimeUnit.MILLISECONDS); else - nw_conn.setConduitSubscriptions(true); + LOG.info("echo client shutdown: client does not appear to be active"); + } + catch (InterruptedException int_exc) { + LOG.warn("wait for message client shutdown interrupted", int_exc); + } + } - nw_conn.setNetworkTTL(3); - nw_conn.setSuppressDuplicateQueueSubscriptions(true); - nw_conn.setDecreaseNetworkConsumerPriority(true); - nw_conn.setBridgeTempDestinations(queue_f); + public boolean shutdown() { + boolean down_ind; - if (queue_f) { - prefix = "queue"; - excl_dest = ActiveMQDestination.createDestination(">", ActiveMQDestination.TOPIC_TYPE); - } else { - prefix = "topic"; - excl_dest = ActiveMQDestination.createDestination(">", ActiveMQDestination.QUEUE_TYPE); + if (!shutdownInd) { + shutdownInd = true; + } + + waitShutdown(200); + + synchronized (this) { + if ((shutdownLatch == null) || (shutdownLatch.getCount() == 0)) + down_ind = true; + else + down_ind = false; + } + + return down_ind; + } + + public int getNumMsgReceived() { + return msgCount; + } + + protected void processMessages() throws Exception { + Message in_msg; + + haveFirstSeq = false; + + // + // Stop at shutdown time or after any test error is detected. + // + + while ((!shutdownInd) && (!fatalTestError)) { + in_msg = msgCons.receive(100); + + if (in_msg != null) { + msgCount++; + checkMessage(in_msg); + } + } + + msgCons.close(); + } + + protected void checkMessage(Message in_msg) throws Exception { + int seq; + + LOG.debug("received message " + fmtMsgInfo(in_msg) + " from " + in_msg.getJMSDestination()); + + // + // Only check messages with a sequence number. + // + + if (in_msg.propertyExists("SEQ")) { + seq = in_msg.getIntProperty("SEQ"); + + if ((haveFirstSeq) && (seq != (lastSeq + 1))) { + LOG.error("***ERROR*** incorrect sequence number; expected " + Integer.toString(lastSeq + 1) + " but have " + Integer.toString(seq)); + + testError = true; } - excludes = new ArrayList(); - excludes.add(excl_dest); - nw_conn.setExcludedDestinations(excludes); + lastSeq = seq; - if (duplex_f) - nw_conn.setName(this.brokerId + "<-" + prefix + "->" + other.brokerId); - else - nw_conn.setName(this.brokerId + "-" + prefix + "->" + other.brokerId); + if (msgCount > expectedCount) { + LOG.error("*** have more messages than expected; have " + msgCount + "; expect " + expectedCount); - brokerSvc.addNetworkConnector(nw_conn); - } - } + testError = true; + } + } - protected class MessageClient extends java.lang.Thread { - protected MessageConsumer msgCons; - protected boolean shutdownInd; - protected int expectedCount; - protected int lastSeq = 0; - protected int msgCount = 0; - protected boolean haveFirstSeq; - protected CountDownLatch shutdownLatch; + if (in_msg.propertyExists("end-of-response")) { + LOG.trace("received end-of-response message"); + } + } + } - public MessageClient(MessageConsumer cons, int num_to_expect) { - msgCons = cons; - expectedCount = (num_to_expect * (echoResponseFill + 1)); - shutdownLatch = new CountDownLatch(1); - } + /** + * + */ + protected class EchoService extends java.lang.Thread { - @Override - public void run() { - CountDownLatch latch; + protected String destName; + protected Connection jmsConn; + protected Session sess; + protected MessageConsumer msg_cons; + protected boolean Shutdown_ind; + + protected Destination req_dest; + + protected CountDownLatch waitShutdown; + + protected ThreadPoolExecutor processorPool; + + public EchoService(String dest, Connection broker_conn) throws Exception { + destName = dest; + jmsConn = broker_conn; + + Shutdown_ind = false; + + sess = jmsConn.createSession(false, Session.AUTO_ACKNOWLEDGE); + req_dest = sess.createQueue(destName); + msg_cons = sess.createConsumer(req_dest); + + jmsConn.start(); + + waitShutdown = new CountDownLatch(1); + + processorPool = new ThreadPoolExecutor(CONCURRENT_SERVER_COUNT, CONCURRENT_SERVER_COUNT, 0, TimeUnit.SECONDS, new ArrayBlockingQueue(10000)); + } + + public EchoService(String dest, String broker_url) throws Exception { + this(dest, ActiveMQConnection.makeConnection(broker_url)); + } + + @Override + public void run() { + Message req; + + try { + LOG.info("STARTING ECHO SERVICE"); + + while (!Shutdown_ind) { + req = msg_cons.receive(100); + if (req != null) { + processorPool.execute(new EchoRequestProcessor(sess, req)); + } + } + } + catch (Exception ex) { + LOG.error("error processing echo service requests", ex); + } + finally { + LOG.info("shutting down test echo service"); try { - synchronized (this) { - latch = shutdownLatch; - } - - shutdownInd = false; - processMessages(); - - latch.countDown(); - } catch (Exception exc) { - LOG.error("message client error", exc); + jmsConn.stop(); } - } - - public void waitShutdown(long timeout) { - CountDownLatch latch; - - try { - synchronized (this) { - latch = shutdownLatch; - } - - if (latch != null) - latch.await(timeout, TimeUnit.MILLISECONDS); - else - LOG.info("echo client shutdown: client does not appear to be active"); - } catch (InterruptedException int_exc) { - LOG.warn("wait for message client shutdown interrupted", int_exc); + catch (javax.jms.JMSException jms_exc) { + LOG.warn("error on shutting down JMS connection", jms_exc); } - } - - public boolean shutdown() { - boolean down_ind; - - if (!shutdownInd) { - shutdownInd = true; - } - - waitShutdown(200); synchronized (this) { - if ((shutdownLatch == null) || (shutdownLatch.getCount() == 0)) - down_ind = true; - else - down_ind = false; + waitShutdown.countDown(); + } + } + } + + /** + * Shut down the service, waiting up to 3 seconds for the service to terminate. + */ + public void shutdown() { + CountDownLatch wait_l; + + synchronized (this) { + wait_l = waitShutdown; + } + + Shutdown_ind = true; + + try { + if (wait_l != null) { + if (wait_l.await(3000, TimeUnit.MILLISECONDS)) + LOG.info("echo service shutdown complete"); + else + LOG.warn("timeout waiting for echo service shutdown"); + } + else { + LOG.info("echo service shutdown: service does not appear to be active"); + } + } + catch (InterruptedException int_exc) { + LOG.warn("interrupted while waiting for echo service shutdown"); + } + } + } + + /** + * + */ + protected class EchoRequestProcessor implements Runnable { + + protected Session session; + + protected Destination resp_dest; + protected MessageProducer msg_prod; + + protected Message request; + + public EchoRequestProcessor(Session sess, Message req) throws Exception { + this.session = sess; + this.request = req; + + this.resp_dest = req.getJMSReplyTo(); + + if (resp_dest == null) { + throw new Exception("invalid request: no reply-to destination given"); + } + + this.msg_prod = session.createProducer(this.resp_dest); + } + + @Override + public void run() { + try { + this.processRequest(this.request); + } + catch (Exception ex) { + LOG.error("Failed to process request", ex); + } + } + + /** + * Process one request for the Echo Service. + */ + protected void processRequest(Message req) throws Exception { + if (LOG.isDebugEnabled()) + LOG.debug("ECHO request message " + req.toString()); + + resp_dest = req.getJMSReplyTo(); + if (resp_dest != null) { + msg_prod = session.createProducer(resp_dest); + + LOG.debug("SENDING ECHO RESPONSE to:" + resp_dest); + + msg_prod.send(req); + + LOG.debug((((ActiveMQSession) session).getConnection()).getBrokerName() + " SENT ECHO RESPONSE to " + resp_dest); + + msg_prod.close(); + msg_prod = null; + } + else { + LOG.warn("invalid request: no reply-to destination given"); + } + } + } + + protected class TopicTrafficGenerator extends java.lang.Thread { + + protected Connection conn1; + protected Connection conn2; + protected Session sess1; + protected Session sess2; + protected Destination dest; + protected MessageProducer prod; + protected MessageConsumer cons; + protected boolean Shutdown_ind; + protected int send_count; + + public TopicTrafficGenerator(String url1, String url2) throws Exception { + conn1 = createConnection(url1); + conn2 = createConnection(url2); + + sess1 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE); + sess2 = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE); + + conn1.start(); + conn2.start(); + + dest = sess1.createTopic("traffic"); + prod = sess1.createProducer(dest); + + dest = sess2.createTopic("traffic"); + cons = sess2.createConsumer(dest); + } + + public void shutdown() { + Shutdown_ind = true; + } + + @Override + public void run() { + Message msg; + + try { + LOG.info("Starting Topic Traffic Generator"); + + while (!Shutdown_ind) { + msg = sess1.createTextMessage("TRAFFIC"); + + prod.send(msg); + + send_count++; + + // + // Time out the receipt; early messages may not make it. + // + + msg = cons.receive(250); + } + } + catch (JMSException jms_exc) { + LOG.warn("traffic generator failed on jms exception", jms_exc); + } + finally { + LOG.info("Shutdown of Topic Traffic Generator; send count = " + send_count); + + if (conn1 != null) { + try { + conn1.stop(); + } + catch (JMSException jms_exc) { + LOG.warn("failed to shutdown connection", jms_exc); + } } - return down_ind; - } - - public int getNumMsgReceived() { - return msgCount; - } - - protected void processMessages() throws Exception { - Message in_msg; - - haveFirstSeq = false; - - // - // Stop at shutdown time or after any test error is detected. - // - - while ((!shutdownInd) && (!fatalTestError)) { - in_msg = msgCons.receive(100); - - if (in_msg != null) { - msgCount++; - checkMessage(in_msg); - } + if (conn2 != null) { + try { + conn2.stop(); + } + catch (JMSException jms_exc) { + LOG.warn("failed to shutdown connection", jms_exc); + } } - - msgCons.close(); - } - - protected void checkMessage(Message in_msg) throws Exception { - int seq; - - LOG.debug("received message " + fmtMsgInfo(in_msg) + " from " + in_msg.getJMSDestination()); - - // - // Only check messages with a sequence number. - // - - if (in_msg.propertyExists("SEQ")) { - seq = in_msg.getIntProperty("SEQ"); - - if ((haveFirstSeq) && (seq != (lastSeq + 1))) { - LOG.error("***ERROR*** incorrect sequence number; expected " + Integer.toString(lastSeq + 1) + " but have " + Integer.toString(seq)); - - testError = true; - } - - lastSeq = seq; - - if (msgCount > expectedCount) { - LOG.error("*** have more messages than expected; have " + msgCount + "; expect " + expectedCount); - - testError = true; - } - } - - if (in_msg.propertyExists("end-of-response")) { - LOG.trace("received end-of-response message"); - } - } - } - - /** - * - */ - protected class EchoService extends java.lang.Thread { - protected String destName; - protected Connection jmsConn; - protected Session sess; - protected MessageConsumer msg_cons; - protected boolean Shutdown_ind; - - protected Destination req_dest; - - protected CountDownLatch waitShutdown; - - protected ThreadPoolExecutor processorPool; - - public EchoService(String dest, Connection broker_conn) throws Exception { - destName = dest; - jmsConn = broker_conn; - - Shutdown_ind = false; - - sess = jmsConn.createSession(false, Session.AUTO_ACKNOWLEDGE); - req_dest = sess.createQueue(destName); - msg_cons = sess.createConsumer(req_dest); - - jmsConn.start(); - - waitShutdown = new CountDownLatch(1); - - processorPool = new ThreadPoolExecutor(CONCURRENT_SERVER_COUNT, CONCURRENT_SERVER_COUNT, 0, TimeUnit.SECONDS, new ArrayBlockingQueue( - 10000)); - } - - public EchoService(String dest, String broker_url) throws Exception { - this(dest, ActiveMQConnection.makeConnection(broker_url)); - } - - @Override - public void run() { - Message req; - - try { - LOG.info("STARTING ECHO SERVICE"); - - while (!Shutdown_ind) { - req = msg_cons.receive(100); - if (req != null) { - processorPool.execute(new EchoRequestProcessor(sess, req)); - } - } - } catch (Exception ex) { - LOG.error("error processing echo service requests", ex); - } finally { - LOG.info("shutting down test echo service"); - - try { - jmsConn.stop(); - } catch (javax.jms.JMSException jms_exc) { - LOG.warn("error on shutting down JMS connection", jms_exc); - } - - synchronized (this) { - waitShutdown.countDown(); - } - } - } - - /** - * Shut down the service, waiting up to 3 seconds for the service to terminate. - */ - public void shutdown() { - CountDownLatch wait_l; - - synchronized (this) { - wait_l = waitShutdown; - } - - Shutdown_ind = true; - - try { - if (wait_l != null) { - if (wait_l.await(3000, TimeUnit.MILLISECONDS)) - LOG.info("echo service shutdown complete"); - else - LOG.warn("timeout waiting for echo service shutdown"); - } else { - LOG.info("echo service shutdown: service does not appear to be active"); - } - } catch (InterruptedException int_exc) { - LOG.warn("interrupted while waiting for echo service shutdown"); - } - } - } - - /** - * - */ - protected class EchoRequestProcessor implements Runnable { - protected Session session; - - protected Destination resp_dest; - protected MessageProducer msg_prod; - - protected Message request; - - public EchoRequestProcessor(Session sess, Message req) throws Exception { - this.session = sess; - this.request = req; - - this.resp_dest = req.getJMSReplyTo(); - - if (resp_dest == null) { - throw new Exception("invalid request: no reply-to destination given"); - } - - this.msg_prod = session.createProducer(this.resp_dest); - } - - @Override - public void run() { - try { - this.processRequest(this.request); - } catch (Exception ex) { - LOG.error("Failed to process request", ex); - } - } - - /** - * Process one request for the Echo Service. - */ - protected void processRequest(Message req) throws Exception { - if (LOG.isDebugEnabled()) - LOG.debug("ECHO request message " + req.toString()); - - resp_dest = req.getJMSReplyTo(); - if (resp_dest != null) { - msg_prod = session.createProducer(resp_dest); - - LOG.debug("SENDING ECHO RESPONSE to:" + resp_dest); - - msg_prod.send(req); - - LOG.debug((((ActiveMQSession) session).getConnection()).getBrokerName() + " SENT ECHO RESPONSE to " + resp_dest); - - msg_prod.close(); - msg_prod = null; - } else { - LOG.warn("invalid request: no reply-to destination given"); - } - } - } - - protected class TopicTrafficGenerator extends java.lang.Thread { - protected Connection conn1; - protected Connection conn2; - protected Session sess1; - protected Session sess2; - protected Destination dest; - protected MessageProducer prod; - protected MessageConsumer cons; - protected boolean Shutdown_ind; - protected int send_count; - - public TopicTrafficGenerator(String url1, String url2) throws Exception { - conn1 = createConnection(url1); - conn2 = createConnection(url2); - - sess1 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE); - sess2 = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE); - - conn1.start(); - conn2.start(); - - dest = sess1.createTopic("traffic"); - prod = sess1.createProducer(dest); - - dest = sess2.createTopic("traffic"); - cons = sess2.createConsumer(dest); - } - - public void shutdown() { - Shutdown_ind = true; - } - - @Override - public void run() { - Message msg; - - try { - LOG.info("Starting Topic Traffic Generator"); - - while (!Shutdown_ind) { - msg = sess1.createTextMessage("TRAFFIC"); - - prod.send(msg); - - send_count++; - - // - // Time out the receipt; early messages may not make it. - // - - msg = cons.receive(250); - } - } catch (JMSException jms_exc) { - LOG.warn("traffic generator failed on jms exception", jms_exc); - } finally { - LOG.info("Shutdown of Topic Traffic Generator; send count = " + send_count); - - if (conn1 != null) { - try { - conn1.stop(); - } catch (JMSException jms_exc) { - LOG.warn("failed to shutdown connection", jms_exc); - } - } - - if (conn2 != null) { - try { - conn2.stop(); - } catch (JMSException jms_exc) { - LOG.warn("failed to shutdown connection", jms_exc); - } - } - } - } - } + } + } + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/SingleBrokerVirtualDestinationsWithWildcardLevelDBTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/SingleBrokerVirtualDestinationsWithWildcardLevelDBTest.java index 543f83fc35..d9df0c6044 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/SingleBrokerVirtualDestinationsWithWildcardLevelDBTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/SingleBrokerVirtualDestinationsWithWildcardLevelDBTest.java @@ -33,12 +33,12 @@ import java.net.URI; public class SingleBrokerVirtualDestinationsWithWildcardLevelDBTest extends SingleBrokerVirtualDestinationsWithWildcardTest { - @Override - protected void configurePersistenceAdapter(BrokerService broker) throws IOException { - File dataFileDir = new File("target/test-amq-data/leveldb/" + broker.getBrokerName()); - LevelDBStore kaha = new LevelDBStore(); - kaha.setDirectory(dataFileDir); - broker.setPersistenceAdapter(kaha); - } + @Override + protected void configurePersistenceAdapter(BrokerService broker) throws IOException { + File dataFileDir = new File("target/test-amq-data/leveldb/" + broker.getBrokerName()); + LevelDBStore kaha = new LevelDBStore(); + kaha.setDirectory(dataFileDir); + broker.setPersistenceAdapter(kaha); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/SingleBrokerVirtualDestinationsWithWildcardTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/SingleBrokerVirtualDestinationsWithWildcardTest.java index f30cdb2d86..0970b76e83 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/SingleBrokerVirtualDestinationsWithWildcardTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/SingleBrokerVirtualDestinationsWithWildcardTest.java @@ -33,94 +33,99 @@ import org.apache.activemq.util.MessageIdList; public class SingleBrokerVirtualDestinationsWithWildcardTest extends JmsMultipleBrokersTestSupport { - /** - * virtual destinations - */ - public void testVirtualDestinations() throws Exception { - startAllBrokers(); + /** + * virtual destinations + */ + public void testVirtualDestinations() throws Exception { + startAllBrokers(); - sendReceive("local.test", true, "Consumer.a.local.test", false, 1, 1); - sendReceive("global.test", true, "Consumer.a.global.test", false, 1, 1); + sendReceive("local.test", true, "Consumer.a.local.test", false, 1, 1); + sendReceive("global.test", true, "Consumer.a.global.test", false, 1, 1); - destroyAllBrokers(); - } + destroyAllBrokers(); + } - /** - * virtual destinations with wild-card subscriptions (without individual virtual queue) - */ - public void testVirtualDestinationsWithWildcardWithoutIndividualVirtualQueue() throws Exception { - startAllBrokers(); + /** + * virtual destinations with wild-card subscriptions (without individual virtual queue) + */ + public void testVirtualDestinationsWithWildcardWithoutIndividualVirtualQueue() throws Exception { + startAllBrokers(); - sendReceive("local.test.1", true, "Consumer.a.local.test.>", false, 1, 1); - sendReceive("global.test.1", true, "Consumer.a.global.test.>", false, 1, 1); + sendReceive("local.test.1", true, "Consumer.a.local.test.>", false, 1, 1); + sendReceive("global.test.1", true, "Consumer.a.global.test.>", false, 1, 1); - destroyAllBrokers(); - } + destroyAllBrokers(); + } - /** - * virtual destinations with wild-card subscriptions (with individual virtual queue) - */ - public void testVirtualDestinationsWithWildcardWithIndividualVirtualQueue() throws Exception { - startAllBrokers(); + /** + * virtual destinations with wild-card subscriptions (with individual virtual queue) + */ + public void testVirtualDestinationsWithWildcardWithIndividualVirtualQueue() throws Exception { + startAllBrokers(); - sendReceive("local.test.1", true, "Consumer.a.local.test.1", false, 1, 1); - sendReceive("local.test.1", true, "Consumer.a.local.test.>", false, 1, 1); - sendReceive("global.test.1", true, "Consumer.a.global.test.1", false, 1, 1); - sendReceive("global.test.1", true, "Consumer.a.global.test.>", false, 1, 1); + sendReceive("local.test.1", true, "Consumer.a.local.test.1", false, 1, 1); + sendReceive("local.test.1", true, "Consumer.a.local.test.>", false, 1, 1); + sendReceive("global.test.1", true, "Consumer.a.global.test.1", false, 1, 1); + sendReceive("global.test.1", true, "Consumer.a.global.test.>", false, 1, 1); - destroyAllBrokers(); - } + destroyAllBrokers(); + } - /** - * virtual destinations with wild-card subscriptions (wit virtual queue pre-created) - */ - public void testVirtualDestinationsWithWildcardWithVirtualQueuePreCreated() throws Exception { - startAllBrokers(); + /** + * virtual destinations with wild-card subscriptions (wit virtual queue pre-created) + */ + public void testVirtualDestinationsWithWildcardWithVirtualQueuePreCreated() throws Exception { + startAllBrokers(); - sendReceive("Consumer.a.local.test.>", false, "Consumer.a.local.test.>", false, 1, 1); - sendReceive("local.test.1", true, "Consumer.a.local.test.>", false, 1, 1); - sendReceive("Consumer.a.global.test.>", false, "Consumer.a.global.test.>", false, 1, 1); - sendReceive("global.test.1", true, "Consumer.a.global.test.>", false, 1, 1); + sendReceive("Consumer.a.local.test.>", false, "Consumer.a.local.test.>", false, 1, 1); + sendReceive("local.test.1", true, "Consumer.a.local.test.>", false, 1, 1); + sendReceive("Consumer.a.global.test.>", false, "Consumer.a.global.test.>", false, 1, 1); + sendReceive("global.test.1", true, "Consumer.a.global.test.>", false, 1, 1); - destroyAllBrokers(); - } + destroyAllBrokers(); + } - public void sendReceive(String dest1, boolean topic1, String dest2, boolean topic2, int send, int expected) throws Exception{ - MessageConsumer client = createConsumer("BrokerA", createDestination(dest2, topic2)); - Thread.sleep(1000); - sendMessages("BrokerA", createDestination(dest1, topic1), send); - MessageIdList msgs = getConsumerMessages("BrokerA", client); - msgs.setMaximumDuration(1000); - assertEquals(expected, msgs.getMessageCount()); - client.close(); - Thread.sleep(500); - } + public void sendReceive(String dest1, + boolean topic1, + String dest2, + boolean topic2, + int send, + int expected) throws Exception { + MessageConsumer client = createConsumer("BrokerA", createDestination(dest2, topic2)); + Thread.sleep(1000); + sendMessages("BrokerA", createDestination(dest1, topic1), send); + MessageIdList msgs = getConsumerMessages("BrokerA", client); + msgs.setMaximumDuration(1000); + assertEquals(expected, msgs.getMessageCount()); + client.close(); + Thread.sleep(500); + } - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - String options = new String("?useJmx=false&deleteAllMessagesOnStartup=true"); - createAndConfigureBroker(new URI("broker:(tcp://localhost:61616)/BrokerA" + options)); - } + @Override + public void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); + String options = new String("?useJmx=false&deleteAllMessagesOnStartup=true"); + createAndConfigureBroker(new URI("broker:(tcp://localhost:61616)/BrokerA" + options)); + } - private BrokerService createAndConfigureBroker(URI uri) throws Exception { - BrokerService broker = createBroker(uri); + private BrokerService createAndConfigureBroker(URI uri) throws Exception { + BrokerService broker = createBroker(uri); - configurePersistenceAdapter(broker); + configurePersistenceAdapter(broker); - // make all topics virtual and consumers use the default prefix - VirtualDestinationInterceptor virtualDestinationInterceptor = new VirtualDestinationInterceptor(); - virtualDestinationInterceptor.setVirtualDestinations(new VirtualDestination[]{new VirtualTopic()}); - DestinationInterceptor[] destinationInterceptors = new DestinationInterceptor[]{virtualDestinationInterceptor}; - broker.setDestinationInterceptors(destinationInterceptors); - return broker; - } + // make all topics virtual and consumers use the default prefix + VirtualDestinationInterceptor virtualDestinationInterceptor = new VirtualDestinationInterceptor(); + virtualDestinationInterceptor.setVirtualDestinations(new VirtualDestination[]{new VirtualTopic()}); + DestinationInterceptor[] destinationInterceptors = new DestinationInterceptor[]{virtualDestinationInterceptor}; + broker.setDestinationInterceptors(destinationInterceptors); + return broker; + } - protected void configurePersistenceAdapter(BrokerService broker) throws IOException { - File dataFileDir = new File("target/test-amq-data/kahadb/" + broker.getBrokerName()); - KahaDBStore kaha = new KahaDBStore(); - kaha.setDirectory(dataFileDir); - broker.setPersistenceAdapter(kaha); - } + protected void configurePersistenceAdapter(BrokerService broker) throws IOException { + File dataFileDir = new File("target/test-amq-data/kahadb/" + broker.getBrokerName()); + KahaDBStore kaha = new KahaDBStore(); + kaha.setDirectory(dataFileDir); + broker.setPersistenceAdapter(kaha); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/StartAndStopBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/StartAndStopBrokerTest.java index 728a2cca0b..eb20e10dac 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/StartAndStopBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/StartAndStopBrokerTest.java @@ -21,58 +21,59 @@ import java.net.URI; import javax.jms.JMSException; import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerFactory; import org.apache.activemq.broker.BrokerService; /** * @author Oliver Belikan - * */ public class StartAndStopBrokerTest extends TestCase { - public void testStartupShutdown() throws Exception { - // This systemproperty is used if we dont want to - // have persistence messages as a default - System.setProperty("activemq.persistenceAdapter", - "org.apache.activemq.store.vm.VMPersistenceAdapter"); - // configuration of container and all protocolls - BrokerService broker = createBroker(); + public void testStartupShutdown() throws Exception { + // This systemproperty is used if we dont want to + // have persistence messages as a default + System.setProperty("activemq.persistenceAdapter", "org.apache.activemq.store.vm.VMPersistenceAdapter"); - // start a client - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:9100"); - factory.createConnection(); + // configuration of container and all protocolls + BrokerService broker = createBroker(); - // stop activemq broker - broker.stop(); + // start a client + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:9100"); + factory.createConnection(); - // start activemq broker again - broker = createBroker(); + // stop activemq broker + broker.stop(); - // start a client again - factory = new ActiveMQConnectionFactory("tcp://localhost:9100"); - factory.createConnection(); + // start activemq broker again + broker = createBroker(); - // stop activemq broker - broker.stop(); + // start a client again + factory = new ActiveMQConnectionFactory("tcp://localhost:9100"); + factory.createConnection(); - } + // stop activemq broker + broker.stop(); - protected BrokerService createBroker() throws JMSException { - BrokerService broker = null; + } - try { - broker = BrokerFactory.createBroker(new URI("broker://()/localhost")); - broker.setBrokerName("DefaultBroker"); - broker.addConnector("tcp://localhost:9100"); - broker.setUseShutdownHook(false); - - broker.start(); - } catch (Exception e) { - e.printStackTrace(); - } + protected BrokerService createBroker() throws JMSException { + BrokerService broker = null; - return broker; - } + try { + broker = BrokerFactory.createBroker(new URI("broker://()/localhost")); + broker.setBrokerName("DefaultBroker"); + broker.addConnector("tcp://localhost:9100"); + broker.setUseShutdownHook(false); + + broker.start(); + } + catch (Exception e) { + e.printStackTrace(); + } + + return broker; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/StartAndStopClientAndBrokerDoesNotLeaveThreadsRunningTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/StartAndStopClientAndBrokerDoesNotLeaveThreadsRunningTest.java index 164d6a82fa..b3c0d9a317 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/StartAndStopClientAndBrokerDoesNotLeaveThreadsRunningTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/StartAndStopClientAndBrokerDoesNotLeaveThreadsRunningTest.java @@ -24,70 +24,72 @@ import javax.jms.Session; import javax.jms.TextMessage; import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.spring.ConsumerBean; /** - * - * + * + * */ public class StartAndStopClientAndBrokerDoesNotLeaveThreadsRunningTest extends TestCase { - public static interface Task { - void execute() throws Exception; - } + public static interface Task { - public void setUp() throws Exception { - } + void execute() throws Exception; + } - public void testStartAndStopClientAndBrokerAndCheckNoThreadsAreLeft() throws Exception { - runTest(new Task() { + public void setUp() throws Exception { + } - public void execute() throws Exception { - BrokerService broker = new BrokerService(); - broker.setPersistent(false); - broker.start(); + public void testStartAndStopClientAndBrokerAndCheckNoThreadsAreLeft() throws Exception { + runTest(new Task() { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = factory.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue destination = session.createQueue(getName()); + public void execute() throws Exception { + BrokerService broker = new BrokerService(); + broker.setPersistent(false); + broker.start(); - // consumer - MessageConsumer consumer = session.createConsumer(destination); - ConsumerBean listener = new ConsumerBean(); - consumer.setMessageListener(listener); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); + Connection connection = factory.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue destination = session.createQueue(getName()); - // producer - MessageProducer producer = session.createProducer(destination); - TextMessage message = session.createTextMessage("Hello World!"); - producer.send(message); - producer.close(); + // consumer + MessageConsumer consumer = session.createConsumer(destination); + ConsumerBean listener = new ConsumerBean(); + consumer.setMessageListener(listener); - listener.assertMessagesArrived(1); + // producer + MessageProducer producer = session.createProducer(destination); + TextMessage message = session.createTextMessage("Hello World!"); + producer.send(message); + producer.close(); - consumer.close(); - session.close(); - connection.close(); + listener.assertMessagesArrived(1); - broker.stop(); - } - }); - } + consumer.close(); + session.close(); + connection.close(); - public void runTest(Task task) throws Exception { - int before = Thread.currentThread().getThreadGroup().activeCount(); + broker.stop(); + } + }); + } - task.execute(); + public void runTest(Task task) throws Exception { + int before = Thread.currentThread().getThreadGroup().activeCount(); - Thread.yield(); - // need to wait for slow servers - Thread.sleep(5000); + task.execute(); - int after = Thread.currentThread().getThreadGroup().activeCount(); - int diff = Math.abs(before - after); - assertTrue("Should be at most one more thread. Diff = " + diff, diff + 1 <= after); - } + Thread.yield(); + // need to wait for slow servers + Thread.sleep(5000); + + int after = Thread.currentThread().getThreadGroup().activeCount(); + int diff = Math.abs(before - after); + assertTrue("Should be at most one more thread. Diff = " + diff, diff + 1 <= after); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/StaticNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/StaticNetworkTest.java index cba9c5c43c..7682113afa 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/StaticNetworkTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/StaticNetworkTest.java @@ -26,46 +26,44 @@ import java.net.URI; public class StaticNetworkTest extends JmsMultipleBrokersTestSupport { - public void testStaticNetwork() throws Exception { - // Setup destination - ActiveMQDestination dest = createDestination("TEST", false); - ActiveMQDestination dest1 = createDestination("TEST1", false); + public void testStaticNetwork() throws Exception { + // Setup destination + ActiveMQDestination dest = createDestination("TEST", false); + ActiveMQDestination dest1 = createDestination("TEST1", false); - NetworkConnector bridgeAB =bridgeBrokers("BrokerA", "BrokerB", true); - bridgeAB.addStaticallyIncludedDestination(dest); - bridgeAB.setStaticBridge(true); + NetworkConnector bridgeAB = bridgeBrokers("BrokerA", "BrokerB", true); + bridgeAB.addStaticallyIncludedDestination(dest); + bridgeAB.setStaticBridge(true); - startAllBrokers(); - waitForBridgeFormation(); + startAllBrokers(); + waitForBridgeFormation(); - MessageConsumer consumer1 = createConsumer("BrokerB", dest); - MessageConsumer consumer2 = createConsumer("BrokerB", dest1); + MessageConsumer consumer1 = createConsumer("BrokerB", dest); + MessageConsumer consumer2 = createConsumer("BrokerB", dest1); + Thread.sleep(1000); - Thread.sleep(1000); + sendMessages("BrokerA", dest, 1); + sendMessages("BrokerA", dest1, 1); + MessageIdList msgs1 = getConsumerMessages("BrokerB", consumer1); + MessageIdList msgs2 = getConsumerMessages("BrokerB", consumer2); - sendMessages("BrokerA", dest, 1); - sendMessages("BrokerA", dest1, 1); + msgs1.waitForMessagesToArrive(1); - MessageIdList msgs1 = getConsumerMessages("BrokerB", consumer1); - MessageIdList msgs2 = getConsumerMessages("BrokerB", consumer2); + Thread.sleep(1000); - msgs1.waitForMessagesToArrive(1); + assertEquals(1, msgs1.getMessageCount()); + assertEquals(0, msgs2.getMessageCount()); - Thread.sleep(1000); + } - assertEquals(1, msgs1.getMessageCount()); - assertEquals(0, msgs2.getMessageCount()); - - } - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=false")); - createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=false")); - } + @Override + public void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); + createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=false")); + createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=false")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/SubscribeClosePublishThenConsumeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/SubscribeClosePublishThenConsumeTest.java index 38b9144bf7..9718f7bc5f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/SubscribeClosePublishThenConsumeTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/SubscribeClosePublishThenConsumeTest.java @@ -32,80 +32,80 @@ import org.slf4j.LoggerFactory; /** * @author Paul Smith - * */ public class SubscribeClosePublishThenConsumeTest extends TestSupport { - private static final Logger LOG = LoggerFactory.getLogger(SubscribeClosePublishThenConsumeTest.class); - public void testDurableTopic() throws Exception { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://locahost"); + private static final Logger LOG = LoggerFactory.getLogger(SubscribeClosePublishThenConsumeTest.class); - String topicName = "TestTopic"; - String clientID = getName(); - String subscriberName = "MySubscriber:" + System.currentTimeMillis(); + public void testDurableTopic() throws Exception { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://locahost"); - Connection connection = connectionFactory.createConnection(); - connection.setClientID(clientID); + String topicName = "TestTopic"; + String clientID = getName(); + String subscriberName = "MySubscriber:" + System.currentTimeMillis(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic(topicName); + Connection connection = connectionFactory.createConnection(); + connection.setClientID(clientID); - // this should register a durable subscriber, we then close it to - // test that we get messages from the producer later on - TopicSubscriber subscriber = session.createDurableSubscriber(topic, subscriberName); - connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Topic topic = session.createTopic(topicName); - topic = null; - subscriber.close(); - subscriber = null; - session.close(); - session = null; + // this should register a durable subscriber, we then close it to + // test that we get messages from the producer later on + TopicSubscriber subscriber = session.createDurableSubscriber(topic, subscriberName); + connection.start(); - // Create the new connection before closing to avoid the broker shutting - // down. - // now create a new Connection, Session & Producer, send some messages & - // then close - Connection t = connectionFactory.createConnection(); - connection.close(); - connection = t; + topic = null; + subscriber.close(); + subscriber = null; + session.close(); + session = null; - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - topic = session.createTopic(topicName); - MessageProducer producer = session.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - TextMessage textMessage = session.createTextMessage("Hello World"); - producer.send(textMessage); - textMessage = null; + // Create the new connection before closing to avoid the broker shutting + // down. + // now create a new Connection, Session & Producer, send some messages & + // then close + Connection t = connectionFactory.createConnection(); + connection.close(); + connection = t; - topic = null; - session.close(); - session = null; + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + topic = session.createTopic(topicName); + MessageProducer producer = session.createProducer(topic); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + TextMessage textMessage = session.createTextMessage("Hello World"); + producer.send(textMessage); + textMessage = null; - // Now (re)register the Durable subscriber, setup a listener and wait - // for messages that should - // have been published by the previous producer - t = connectionFactory.createConnection(); - connection.close(); - connection = t; + topic = null; + session.close(); + session = null; - connection.setClientID(clientID); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - topic = session.createTopic(topicName); + // Now (re)register the Durable subscriber, setup a listener and wait + // for messages that should + // have been published by the previous producer + t = connectionFactory.createConnection(); + connection.close(); + connection = t; - subscriber = session.createDurableSubscriber(topic, subscriberName); - connection.start(); + connection.setClientID(clientID); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + topic = session.createTopic(topicName); - LOG.info("Started connection - now about to try receive the textMessage"); + subscriber = session.createDurableSubscriber(topic, subscriberName); + connection.start(); - long time = System.currentTimeMillis(); - Message message = subscriber.receive(15000L); - long elapsed = System.currentTimeMillis() - time; + LOG.info("Started connection - now about to try receive the textMessage"); - LOG.info("Waited for: " + elapsed + " millis"); + long time = System.currentTimeMillis(); + Message message = subscriber.receive(15000L); + long elapsed = System.currentTimeMillis() - time; - assertNotNull("Should have received the message we published by now", message); - assertTrue("should be text textMessage", message instanceof TextMessage); - textMessage = (TextMessage)message; - assertEquals("Hello World", textMessage.getText()); - } + LOG.info("Waited for: " + elapsed + " millis"); + + assertNotNull("Should have received the message we published by now", message); + assertTrue("should be text textMessage", message instanceof TextMessage); + textMessage = (TextMessage) message; + assertEquals("Hello World", textMessage.getText()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TempTopicProducerFlowControlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TempTopicProducerFlowControlTest.java index ca8b697bba..b144146cbb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TempTopicProducerFlowControlTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TempTopicProducerFlowControlTest.java @@ -18,26 +18,27 @@ package org.apache.activemq.usecases; import javax.jms.Destination; import javax.jms.Session; + import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.region.policy.PolicyEntry; import org.apache.activemq.broker.region.policy.PolicyMap; public class TempTopicProducerFlowControlTest extends TopicProducerFlowControlTest { - @Override - protected void setDestinationPolicy(BrokerService broker, PolicyMap pm) { - PolicyEntry tpe = new PolicyEntry(); - tpe.setTempTopic(true); - tpe.setMemoryLimit(destinationMemLimit); - tpe.setProducerFlowControl(true); - tpe.setAdvisoryWhenFull(true); - pm.setDefaultEntry(tpe); + @Override + protected void setDestinationPolicy(BrokerService broker, PolicyMap pm) { + PolicyEntry tpe = new PolicyEntry(); + tpe.setTempTopic(true); + tpe.setMemoryLimit(destinationMemLimit); + tpe.setProducerFlowControl(true); + tpe.setAdvisoryWhenFull(true); + pm.setDefaultEntry(tpe); - broker.setDestinationPolicy(pm); - } + broker.setDestinationPolicy(pm); + } - @Override - protected Destination createDestination(Session session) throws Exception { - return session.createTemporaryTopic(); - } + @Override + protected Destination createDestination(Session session) throws Exception { + return session.createTemporaryTopic(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TestBrokerConnectionDuplexExcludedDestinations.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TestBrokerConnectionDuplexExcludedDestinations.java index 2d3b64ceb1..53fda1a19a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TestBrokerConnectionDuplexExcludedDestinations.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TestBrokerConnectionDuplexExcludedDestinations.java @@ -37,135 +37,136 @@ import org.apache.activemq.broker.BrokerService; public class TestBrokerConnectionDuplexExcludedDestinations extends TestCase { - BrokerService receiverBroker; - BrokerService senderBroker; + BrokerService receiverBroker; + BrokerService senderBroker; - Connection hubConnection; - Session hubSession; + Connection hubConnection; + Session hubSession; - Connection spokeConnection; - Session spokeSession; + Connection spokeConnection; + Session spokeSession; - @Override - public void setUp() throws Exception { - // Hub broker - String configFileName = "org/apache/activemq/usecases/receiver-duplex.xml"; - URI uri = new URI("xbean:" + configFileName); - receiverBroker = BrokerFactory.createBroker(uri); - receiverBroker.setPersistent(false); - receiverBroker.setBrokerName("Hub"); + @Override + public void setUp() throws Exception { + // Hub broker + String configFileName = "org/apache/activemq/usecases/receiver-duplex.xml"; + URI uri = new URI("xbean:" + configFileName); + receiverBroker = BrokerFactory.createBroker(uri); + receiverBroker.setPersistent(false); + receiverBroker.setBrokerName("Hub"); - // Spoke broker - configFileName = "org/apache/activemq/usecases/sender-duplex.xml"; - uri = new URI("xbean:" + configFileName); - senderBroker = BrokerFactory.createBroker(uri); - senderBroker.setPersistent(false); - senderBroker.setBrokerName("Spoke"); + // Spoke broker + configFileName = "org/apache/activemq/usecases/sender-duplex.xml"; + uri = new URI("xbean:" + configFileName); + senderBroker = BrokerFactory.createBroker(uri); + senderBroker.setPersistent(false); + senderBroker.setBrokerName("Spoke"); - // Start both Hub and Spoke broker - receiverBroker.start(); - senderBroker.start(); + // Start both Hub and Spoke broker + receiverBroker.start(); + senderBroker.start(); - // create hub session - ConnectionFactory cfHub = new ActiveMQConnectionFactory("tcp://localhost:62002"); + // create hub session + ConnectionFactory cfHub = new ActiveMQConnectionFactory("tcp://localhost:62002"); - hubConnection = cfHub.createConnection(); - hubConnection.start(); - hubSession = hubConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + hubConnection = cfHub.createConnection(); + hubConnection.start(); + hubSession = hubConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - // create spoke session - ConnectionFactory cfSpoke = new ActiveMQConnectionFactory("tcp://localhost:62001"); - spokeConnection = cfSpoke.createConnection(); - spokeConnection.start(); - spokeSession = spokeConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } + // create spoke session + ConnectionFactory cfSpoke = new ActiveMQConnectionFactory("tcp://localhost:62001"); + spokeConnection = cfSpoke.createConnection(); + spokeConnection.start(); + spokeSession = spokeConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + } - @Override - public void tearDown() throws Exception { - hubSession.close(); - hubConnection.stop(); - hubConnection.close(); + @Override + public void tearDown() throws Exception { + hubSession.close(); + hubConnection.stop(); + hubConnection.close(); - spokeSession.close(); - spokeConnection.stop(); - spokeConnection.close(); + spokeSession.close(); + spokeConnection.stop(); + spokeConnection.close(); - senderBroker.stop(); - receiverBroker.stop(); - } + senderBroker.stop(); + receiverBroker.stop(); + } - public void testDuplexSendFromHubToSpoke() throws Exception { + public void testDuplexSendFromHubToSpoke() throws Exception { - //create hub producer - MessageProducer hubProducer = hubSession.createProducer(null); - hubProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - hubProducer.setDisableMessageID(true); - hubProducer.setDisableMessageTimestamp(true); + //create hub producer + MessageProducer hubProducer = hubSession.createProducer(null); + hubProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + hubProducer.setDisableMessageID(true); + hubProducer.setDisableMessageTimestamp(true); - //create spoke producer - MessageProducer spokeProducer = hubSession.createProducer(null); - spokeProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - spokeProducer.setDisableMessageID(true); - spokeProducer.setDisableMessageTimestamp(true); + //create spoke producer + MessageProducer spokeProducer = hubSession.createProducer(null); + spokeProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + spokeProducer.setDisableMessageID(true); + spokeProducer.setDisableMessageTimestamp(true); - Queue excludedQueueHub = hubSession.createQueue("exclude.test.foo"); - TextMessage excludedMsgHub = hubSession.createTextMessage(); - excludedMsgHub.setText(excludedQueueHub.toString()); + Queue excludedQueueHub = hubSession.createQueue("exclude.test.foo"); + TextMessage excludedMsgHub = hubSession.createTextMessage(); + excludedMsgHub.setText(excludedQueueHub.toString()); - Queue includedQueueHub = hubSession.createQueue("include.test.foo"); + Queue includedQueueHub = hubSession.createQueue("include.test.foo"); - TextMessage includedMsgHub = hubSession.createTextMessage(); - includedMsgHub.setText(includedQueueHub.toString()); + TextMessage includedMsgHub = hubSession.createTextMessage(); + includedMsgHub.setText(includedQueueHub.toString()); - Queue alwaysIncludedQueueHub = hubSession.createQueue("always.include.test.foo"); + Queue alwaysIncludedQueueHub = hubSession.createQueue("always.include.test.foo"); - TextMessage alwaysIncludedMsgHub = hubSession.createTextMessage(); - alwaysIncludedMsgHub.setText(alwaysIncludedQueueHub.toString()); + TextMessage alwaysIncludedMsgHub = hubSession.createTextMessage(); + alwaysIncludedMsgHub.setText(alwaysIncludedQueueHub.toString()); - // Sending from Hub queue - hubProducer.send(excludedQueueHub, excludedMsgHub); - hubProducer.send(includedQueueHub, includedMsgHub); - hubProducer.send(alwaysIncludedQueueHub, alwaysIncludedMsgHub); + // Sending from Hub queue + hubProducer.send(excludedQueueHub, excludedMsgHub); + hubProducer.send(includedQueueHub, includedMsgHub); + hubProducer.send(alwaysIncludedQueueHub, alwaysIncludedMsgHub); - Queue excludedQueueSpoke = spokeSession.createQueue("exclude.test.foo"); - MessageConsumer excludedConsumerSpoke = spokeSession.createConsumer(excludedQueueSpoke); + Queue excludedQueueSpoke = spokeSession.createQueue("exclude.test.foo"); + MessageConsumer excludedConsumerSpoke = spokeSession.createConsumer(excludedQueueSpoke); - Thread.sleep(100); + Thread.sleep(100); - Queue includedQueueSpoke = spokeSession.createQueue("include.test.foo"); - MessageConsumer includedConsumerSpoke = spokeSession.createConsumer(includedQueueSpoke); + Queue includedQueueSpoke = spokeSession.createQueue("include.test.foo"); + MessageConsumer includedConsumerSpoke = spokeSession.createConsumer(includedQueueSpoke); - Thread.sleep(100); + Thread.sleep(100); - Queue alwaysIncludedQueueSpoke = spokeSession.createQueue("always.include.test.foo"); - MessageConsumer alwaysIncludedConsumerSpoke = spokeSession.createConsumer(alwaysIncludedQueueHub); + Queue alwaysIncludedQueueSpoke = spokeSession.createQueue("always.include.test.foo"); + MessageConsumer alwaysIncludedConsumerSpoke = spokeSession.createConsumer(alwaysIncludedQueueHub); - Thread.sleep(100); - TextMessage alwaysIncludedMsgSpoke = spokeSession.createTextMessage(); - alwaysIncludedMsgSpoke.setText(alwaysIncludedQueueSpoke.toString()); - spokeProducer.send(alwaysIncludedQueueSpoke, alwaysIncludedMsgSpoke); + Thread.sleep(100); + TextMessage alwaysIncludedMsgSpoke = spokeSession.createTextMessage(); + alwaysIncludedMsgSpoke.setText(alwaysIncludedQueueSpoke.toString()); + spokeProducer.send(alwaysIncludedQueueSpoke, alwaysIncludedMsgSpoke); - MessageConsumer alwaysIncludedConsumerHub = spokeSession.createConsumer(alwaysIncludedQueueHub); - assertNotNull(alwaysIncludedConsumerHub); + MessageConsumer alwaysIncludedConsumerHub = spokeSession.createConsumer(alwaysIncludedQueueHub); + assertNotNull(alwaysIncludedConsumerHub); - // Receiving from excluded Spoke queue - Message msg = excludedConsumerSpoke.receive(200); - assertNull(msg); + // Receiving from excluded Spoke queue + Message msg = excludedConsumerSpoke.receive(200); + assertNull(msg); - // Receiving from included Spoke queue - msg = includedConsumerSpoke.receive(200); - assertEquals(includedMsgHub, msg); + // Receiving from included Spoke queue + msg = includedConsumerSpoke.receive(200); + assertEquals(includedMsgHub, msg); - // Receiving from included Spoke queue - msg = alwaysIncludedConsumerSpoke.receive(200); - assertEquals(alwaysIncludedMsgHub, msg); + // Receiving from included Spoke queue + msg = alwaysIncludedConsumerSpoke.receive(200); + assertEquals(alwaysIncludedMsgHub, msg); - // we should be able to receive excluded queue message on Hub - MessageConsumer excludedConsumerHub = hubSession.createConsumer(excludedQueueHub); - msg = excludedConsumerHub.receive(200);; - assertEquals(excludedMsgHub, msg); + // we should be able to receive excluded queue message on Hub + MessageConsumer excludedConsumerHub = hubSession.createConsumer(excludedQueueHub); + msg = excludedConsumerHub.receive(200); + ; + assertEquals(excludedMsgHub, msg); - hubProducer.close(); - excludedConsumerSpoke.close(); - } + hubProducer.close(); + excludedConsumerSpoke.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TestSupport.java index 4858870a07..49ff66324c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TestSupport.java @@ -34,114 +34,118 @@ import org.apache.activemq.command.ActiveMQTopic; */ public class TestSupport extends TestCase { - protected ActiveMQConnectionFactory connectionFactory; - protected boolean topic = true; + protected ActiveMQConnectionFactory connectionFactory; + protected boolean topic = true; - public TestSupport() { - super(); - } + public TestSupport() { + super(); + } - public TestSupport(String name) { - super(name); - } + public TestSupport(String name) { + super(name); + } - protected ActiveMQMessage createMessage() { - return new ActiveMQMessage(); - } + protected ActiveMQMessage createMessage() { + return new ActiveMQMessage(); + } - protected Destination createDestination(String subject) { - if (topic) { - return new ActiveMQTopic(subject); - } else { - return new ActiveMQQueue(subject); - } - } + protected Destination createDestination(String subject) { + if (topic) { + return new ActiveMQTopic(subject); + } + else { + return new ActiveMQQueue(subject); + } + } - protected void assertTextMessagesEqual(Message[] firstSet, Message[] secondSet) throws JMSException { - assertTextMessagesEqual("", firstSet, secondSet); - } + protected void assertTextMessagesEqual(Message[] firstSet, Message[] secondSet) throws JMSException { + assertTextMessagesEqual("", firstSet, secondSet); + } - /** - * @param messsage - * @param firstSet - * @param secondSet - */ - protected void assertTextMessagesEqual(String messsage, Message[] firstSet, Message[] secondSet) throws JMSException { - assertEquals("Message count does not match: " + messsage, firstSet.length, secondSet.length); - for (int i = 0; i < secondSet.length; i++) { - TextMessage m1 = (TextMessage)firstSet[i]; - TextMessage m2 = (TextMessage)secondSet[i]; - assertTextMessageEqual("Message " + (i + 1) + " did not match : ", m1, m2); - } - } + /** + * @param messsage + * @param firstSet + * @param secondSet + */ + protected void assertTextMessagesEqual(String messsage, + Message[] firstSet, + Message[] secondSet) throws JMSException { + assertEquals("Message count does not match: " + messsage, firstSet.length, secondSet.length); + for (int i = 0; i < secondSet.length; i++) { + TextMessage m1 = (TextMessage) firstSet[i]; + TextMessage m2 = (TextMessage) secondSet[i]; + assertTextMessageEqual("Message " + (i + 1) + " did not match : ", m1, m2); + } + } - protected void assertEquals(TextMessage m1, TextMessage m2) throws JMSException { - assertEquals("", m1, m2); - } + protected void assertEquals(TextMessage m1, TextMessage m2) throws JMSException { + assertEquals("", m1, m2); + } - /** - * @param message - * @param firstSet - * @param secondSet - */ - protected void assertTextMessageEqual(String message, TextMessage m1, TextMessage m2) throws JMSException { - assertFalse(message + ": expected {" + m1 + "}, but was {" + m2 + "}", m1 == null ^ m2 == null); - if (m1 == null) { - return; - } - assertEquals(message, m1.getText(), m2.getText()); - } + /** + * @param message + * @param firstSet + * @param secondSet + */ + protected void assertTextMessageEqual(String message, TextMessage m1, TextMessage m2) throws JMSException { + assertFalse(message + ": expected {" + m1 + "}, but was {" + m2 + "}", m1 == null ^ m2 == null); + if (m1 == null) { + return; + } + assertEquals(message, m1.getText(), m2.getText()); + } - protected void assertEquals(Message m1, Message m2) throws JMSException { - assertEquals("", m1, m2); - } + protected void assertEquals(Message m1, Message m2) throws JMSException { + assertEquals("", m1, m2); + } - /** - * @param message - * @param firstSet - * @param secondSet - */ - protected void assertEquals(String message, Message m1, Message m2) throws JMSException { - assertFalse(message + ": expected {" + m1 + "}, but was {" + m2 + "}", m1 == null ^ m2 == null); - if (m1 == null) { - return; - } - assertTrue(message + ": expected {" + m1 + "}, but was {" + m2 + "}", m1.getClass() == m2.getClass()); - if (m1 instanceof TextMessage) { - assertTextMessageEqual(message, (TextMessage)m1, (TextMessage)m2); - } else { - assertEquals(message, m1, m2); - } - } + /** + * @param message + * @param firstSet + * @param secondSet + */ + protected void assertEquals(String message, Message m1, Message m2) throws JMSException { + assertFalse(message + ": expected {" + m1 + "}, but was {" + m2 + "}", m1 == null ^ m2 == null); + if (m1 == null) { + return; + } + assertTrue(message + ": expected {" + m1 + "}, but was {" + m2 + "}", m1.getClass() == m2.getClass()); + if (m1 instanceof TextMessage) { + assertTextMessageEqual(message, (TextMessage) m1, (TextMessage) m2); + } + else { + assertEquals(message, m1, m2); + } + } - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); - } + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + return new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); + } - /** - * Factory method to create a new connection - */ - protected Connection createConnection() throws Exception { - return getConnectionFactory().createConnection(); - } + /** + * Factory method to create a new connection + */ + protected Connection createConnection() throws Exception { + return getConnectionFactory().createConnection(); + } - public ActiveMQConnectionFactory getConnectionFactory() throws Exception { - if (connectionFactory == null) { - connectionFactory = createConnectionFactory(); - assertTrue("Should have created a connection factory!", connectionFactory != null); - } - return connectionFactory; - } + public ActiveMQConnectionFactory getConnectionFactory() throws Exception { + if (connectionFactory == null) { + connectionFactory = createConnectionFactory(); + assertTrue("Should have created a connection factory!", connectionFactory != null); + } + return connectionFactory; + } - protected String getConsumerSubject() { - return getSubject(); - } + protected String getConsumerSubject() { + return getSubject(); + } - protected String getProducerSubject() { - return getSubject(); - } + protected String getProducerSubject() { + return getSubject(); + } - protected String getSubject() { - return getClass().getName() + "." + getName(); - } + protected String getSubject() { + return getClass().getName() + "." + getName(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerQueueNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerQueueNetworkTest.java index 2e91d4c9df..8fa590d3da 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerQueueNetworkTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerQueueNetworkTest.java @@ -25,6 +25,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.jms.Destination; import javax.jms.MessageConsumer; + import org.apache.activemq.JmsMultipleBrokersTestSupport; import org.apache.activemq.broker.Broker; import org.apache.activemq.broker.BrokerFilter; @@ -41,626 +42,624 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class ThreeBrokerQueueNetworkTest extends JmsMultipleBrokersTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(ThreeBrokerQueueNetworkTest.class); - protected static final int MESSAGE_COUNT = 100; - private static final long MAX_WAIT_MILLIS = 10000; - - interface Condition { - boolean isSatisified() throws Exception; - } - - /** - * BrokerA -> BrokerB -> BrokerC - */ - public void testABandBCbrokerNetwork() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerA", "BrokerB"); - bridgeBrokers("BrokerB", "BrokerC"); - - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - MessageConsumer clientC = createConsumer("BrokerC", dest); - - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); - - // Let's try to wait for any messages. Should be none. - Thread.sleep(1000); - - // Get message count - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - assertEquals(0, msgsC.getMessageCount()); - } - - /** - * BrokerA <- BrokerB -> BrokerC - */ - public void testBAandBCbrokerNetwork() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerB", "BrokerA"); - bridgeBrokers("BrokerB", "BrokerC"); - - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); - MessageConsumer clientC = createConsumer("BrokerC", dest); - Thread.sleep(2000); //et subscriptions get propagated - // Send messages - sendMessages("BrokerB", dest, MESSAGE_COUNT); - - // Let's try to wait for any messages. - Thread.sleep(1000); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - // Total received should be 100 - assertEquals(MESSAGE_COUNT, msgsA.getMessageCount() + msgsC.getMessageCount()); - } - - /** - * BrokerA <- BrokerB -> BrokerC - */ - public void testBAandBCbrokerNetworkWithSelectorsSendFirst() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerB", "BrokerA", true, 1, false); - bridgeBrokers("BrokerB", "BrokerC", true, 1, false); - - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - - // Send messages for broker A - HashMap props = new HashMap(); - props.put("broker", "BROKER_A"); - sendMessages("BrokerB", dest, MESSAGE_COUNT, props); - - //Send messages for broker C - props.clear(); - props.put("broker", "BROKER_C"); - sendMessages("BrokerB", dest, MESSAGE_COUNT, props); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest, "broker = 'BROKER_A'"); - MessageConsumer clientC = createConsumer("BrokerC", dest, "broker = 'BROKER_C'"); - Thread.sleep(2000); //et subscriptions get propagated - - // Let's try to wait for any messages. - //Thread.sleep(1000); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - // Total received should be 100 - assertEquals(MESSAGE_COUNT, msgsA.getMessageCount()); - assertEquals(MESSAGE_COUNT, msgsC.getMessageCount()); - } - - /** - * BrokerA <- BrokerB -> BrokerC - */ - public void testBAandBCbrokerNetworkWithSelectorsSubscribeFirst() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerB", "BrokerA", true, 1, false); - bridgeBrokers("BrokerB", "BrokerC", true, 1, false); - - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest, "broker = 'BROKER_A'"); - MessageConsumer clientC = createConsumer("BrokerC", dest, "broker = 'BROKER_C'"); - Thread.sleep(2000); //et subscriptions get propagated - - - // Send messages for broker A - HashMap props = new HashMap(); - props.put("broker", "BROKER_A"); - sendMessages("BrokerB", dest, MESSAGE_COUNT, props); - - //Send messages for broker C - props.clear(); - props.put("broker", "BROKER_C"); - sendMessages("BrokerB", dest, MESSAGE_COUNT, props); - - // Let's try to wait for any messages. - Thread.sleep(1000); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - // Total received should be 100 - assertEquals(MESSAGE_COUNT, msgsA.getMessageCount()); - assertEquals(MESSAGE_COUNT, msgsC.getMessageCount()); - } - - /** - * BrokerA -> BrokerB <- BrokerC - */ - public void testABandCBbrokerNetwork() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerA", "BrokerB"); - bridgeBrokers("BrokerC", "BrokerB"); - - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - MessageConsumer clientB = createConsumer("BrokerB", dest); - - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); - sendMessages("BrokerC", dest, MESSAGE_COUNT); - - // Get message count - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - - msgsB.waitForMessagesToArrive(MESSAGE_COUNT * 2); - - assertEquals(MESSAGE_COUNT * 2, msgsB.getMessageCount()); - } - - /** - * BrokerA <-> BrokerB <-> BrokerC - */ - public void testAllConnectedBrokerNetwork() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerA", "BrokerB"); - bridgeBrokers("BrokerB", "BrokerA"); - bridgeBrokers("BrokerB", "BrokerC"); - bridgeBrokers("BrokerC", "BrokerB"); - bridgeBrokers("BrokerA", "BrokerC"); - bridgeBrokers("BrokerC", "BrokerA"); - - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); - MessageConsumer clientB = createConsumer("BrokerB", dest); - MessageConsumer clientC = createConsumer("BrokerC", dest); - - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); - sendMessages("BrokerB", dest, MESSAGE_COUNT); - sendMessages("BrokerC", dest, MESSAGE_COUNT); - - // Let's try to wait for any messages. - Thread.sleep(1000); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - assertEquals(MESSAGE_COUNT * 3, msgsA.getMessageCount() + msgsB.getMessageCount() + msgsC.getMessageCount()); - } - - public void testAllConnectedUsingMulticast() throws Exception { - // Setup broker networks - bridgeAllBrokers(); - - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); - MessageConsumer clientB = createConsumer("BrokerB", dest); - MessageConsumer clientC = createConsumer("BrokerC", dest); - - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); - sendMessages("BrokerB", dest, MESSAGE_COUNT); - sendMessages("BrokerC", dest, MESSAGE_COUNT); - - // Let's try to wait for any messages. - Thread.sleep(1000); - - // Get message count - final MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - waitFor(new Condition() { - public boolean isSatisified() { - return msgsA.getMessageCount() == MESSAGE_COUNT; - } - }); - - assertEquals(MESSAGE_COUNT * 3, msgsA.getMessageCount() + msgsB.getMessageCount() + msgsC.getMessageCount()); - } - - // on slow machines some more waiting is required on account of slow advisories - private void waitFor(Condition condition) throws Exception { - final long expiry = System.currentTimeMillis() + MAX_WAIT_MILLIS; - while (!condition.isSatisified() && System.currentTimeMillis() < expiry) { - Thread.sleep(1000); - } - if (System.currentTimeMillis() >= expiry) { - LOG.error("expired while waiting for condition " + condition); - } - - } - - public void testAllConnectedUsingMulticastProducerConsumerOnA() throws Exception { - bridgeAllBrokers("default", 3, false); - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - int messageCount = 2000; - CountDownLatch messagesReceived = new CountDownLatch(messageCount); - MessageConsumer clientA = createConsumer("BrokerA", dest, messagesReceived); - - // Let's try to wait for advisory percolation. - Thread.sleep(1000); - - // Send messages - sendMessages("BrokerA", dest, messageCount); - - assertTrue(messagesReceived.await(30, TimeUnit.SECONDS)); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - assertEquals(messageCount, msgsA.getMessageCount()); - } - - public void testAllConnectedWithSpare() throws Exception { - bridgeAllBrokers("default", 3, false); - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - int messageCount = 2000; - CountDownLatch messagesReceived = new CountDownLatch(messageCount); - MessageConsumer clientA = createConsumer("BrokerA", dest, messagesReceived); - - // ensure advisory percolation. - Thread.sleep(2000); - - // Send messages - sendMessages("BrokerB", dest, messageCount); - - assertTrue("messaged received within time limit", messagesReceived.await(30, TimeUnit.SECONDS)); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - assertEquals(messageCount, msgsA.getMessageCount()); - } - - /* - * This test is disabled - as it fails with a fix for - * http://issues.apache.org/activemq/browse/AMQ-2530 - which highlights that - * For a Conduit bridge - local subscription Ids weren't removed in a ConduitBridge - * The test fails because on closing clientA - clientB correctly receives all the - * messages - ie. half dont get stuck on BrokerA - - */ - public void XtestMigrateConsumerStuckMessages() throws Exception { - boolean suppressQueueDuplicateSubscriptions = false; - bridgeAllBrokers("default", 3, suppressQueueDuplicateSubscriptions); - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - LOG.info("Consumer on A"); - MessageConsumer clientA = createConsumer("BrokerA", dest); - - // ensure advisors have percolated - Thread.sleep(2000); - - LOG.info("Consumer on B"); - int messageCount = 2000; - - // will only get half of the messages - CountDownLatch messagesReceived = new CountDownLatch(messageCount/2); - MessageConsumer clientB = createConsumer("BrokerB", dest, messagesReceived); - - // ensure advisors have percolated - Thread.sleep(2000); - - LOG.info("Close consumer on A"); - clientA.close(); - - // ensure advisors have percolated - Thread.sleep(2000); - - LOG.info("Send to B"); - sendMessages("BrokerB", dest, messageCount); - - // Let's try to wait for any messages. - assertTrue(messagesReceived.await(30, TimeUnit.SECONDS)); - - // Get message count - MessageIdList msgs = getConsumerMessages("BrokerB", clientB); - - // see will any more arrive - Thread.sleep(500); - assertEquals(messageCount/2, msgs.getMessageCount()); - - // pick up the stuck messages - messagesReceived = new CountDownLatch(messageCount/2); - clientA = createConsumer("BrokerA", dest, messagesReceived); - // Let's try to wait for any messages. - assertTrue(messagesReceived.await(30, TimeUnit.SECONDS)); - - msgs = getConsumerMessages("BrokerA", clientA); - assertEquals(messageCount/2, msgs.getMessageCount()); - } - - // use case: for maintenance, migrate consumers and producers from one - // node in the network to another so node can be replaced/updated - public void testMigrateConsumer() throws Exception { - boolean suppressQueueDuplicateSubscriptions = true; - boolean decreaseNetworkConsumerPriority = true; - bridgeAllBrokers("default", 3, suppressQueueDuplicateSubscriptions, decreaseNetworkConsumerPriority); - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - LOG.info("Consumer on A"); - MessageConsumer clientA = createConsumer("BrokerA", dest); - - // ensure advisors have percolated - Thread.sleep(2000); - - LOG.info("Consumer on B"); - int messageCount = 2000; - CountDownLatch messagesReceived = new CountDownLatch(messageCount); - MessageConsumer clientB = createConsumer("BrokerB", dest, messagesReceived); - - // make the consumer slow so that any network consumer has a chance, even - // if it has a lower priority - MessageIdList msgs = getConsumerMessages("BrokerB", clientB); - msgs.setProcessingDelay(10); - - // ensure advisors have percolated - Thread.sleep(2000); - - LOG.info("Close consumer on A"); - clientA.close(); - - // ensure advisors have percolated - Thread.sleep(2000); - - LOG.info("Send to B"); - sendMessages("BrokerB", dest, messageCount); - - // Let's try to wait for any messages. - assertTrue("messages are received within limit", messagesReceived.await(60, TimeUnit.SECONDS)); - assertEquals(messageCount, msgs.getMessageCount()); - } - - public void testNoDuplicateQueueSubs() throws Exception { - - bridgeAllBrokers("default", 3, true); - - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - String brokerName = "BrokerA"; - MessageConsumer consumer = createConsumer(brokerName, dest); - - // wait for advisories - Thread.sleep(2000); - - // verify there is one consumer on each broker, no cycles - Collection brokerList = brokers.values(); - for (Iterator i = brokerList.iterator(); i.hasNext();) { - BrokerService broker = i.next().broker; - verifyConsumerCount(broker, 1, dest); - } - - consumer.close(); - - // wait for advisories - Thread.sleep(2000); - - // verify there is no more consumers - for (Iterator i = brokerList.iterator(); i.hasNext();) { - BrokerService broker = i.next().broker; - verifyConsumerCount(broker, 0, dest); - } - } - - - public void testNoDuplicateQueueSubsHasLowestPriority() throws Exception { - boolean suppressQueueDuplicateSubscriptions = true; - boolean decreaseNetworkConsumerPriority = true; - bridgeAllBrokers("default", 3, suppressQueueDuplicateSubscriptions, decreaseNetworkConsumerPriority); - - // Setup destination - final Destination dest = createDestination("TEST.FOO", false); - - // delay the advisory messages so that one can percolate fully (cyclicly) before the other - BrokerItem brokerB = brokers.get("BrokerA"); - brokerB.broker.setPlugins(new BrokerPlugin[]{new BrokerPlugin() { - - public Broker installPlugin(Broker broker) throws Exception { - return new BrokerFilter(broker) { - - final AtomicInteger count = new AtomicInteger(); - @Override - public void preProcessDispatch( - MessageDispatch messageDispatch) { - if (messageDispatch.getDestination().getPhysicalName().contains("ActiveMQ.Advisory.Consumer")) { - // lets delay the first advisory - if (count.getAndIncrement() == 0) { - LOG.info("Sleeping on first advisory: " + messageDispatch); - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } + + private static final Logger LOG = LoggerFactory.getLogger(ThreeBrokerQueueNetworkTest.class); + protected static final int MESSAGE_COUNT = 100; + private static final long MAX_WAIT_MILLIS = 10000; + + interface Condition { + + boolean isSatisified() throws Exception; + } + + /** + * BrokerA -> BrokerB -> BrokerC + */ + public void testABandBCbrokerNetwork() throws Exception { + // Setup broker networks + bridgeBrokers("BrokerA", "BrokerB"); + bridgeBrokers("BrokerB", "BrokerC"); + + startAllBrokers(); + waitForBridgeFormation(); + + // Setup destination + Destination dest = createDestination("TEST.FOO", false); + + // Setup consumers + MessageConsumer clientC = createConsumer("BrokerC", dest); + + // Send messages + sendMessages("BrokerA", dest, MESSAGE_COUNT); + + // Let's try to wait for any messages. Should be none. + Thread.sleep(1000); + + // Get message count + MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); + assertEquals(0, msgsC.getMessageCount()); + } + + /** + * BrokerA <- BrokerB -> BrokerC + */ + public void testBAandBCbrokerNetwork() throws Exception { + // Setup broker networks + bridgeBrokers("BrokerB", "BrokerA"); + bridgeBrokers("BrokerB", "BrokerC"); + + startAllBrokers(); + waitForBridgeFormation(); + + // Setup destination + Destination dest = createDestination("TEST.FOO", false); + + // Setup consumers + MessageConsumer clientA = createConsumer("BrokerA", dest); + MessageConsumer clientC = createConsumer("BrokerC", dest); + Thread.sleep(2000); //et subscriptions get propagated + // Send messages + sendMessages("BrokerB", dest, MESSAGE_COUNT); + + // Let's try to wait for any messages. + Thread.sleep(1000); + + // Get message count + MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); + MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); + + // Total received should be 100 + assertEquals(MESSAGE_COUNT, msgsA.getMessageCount() + msgsC.getMessageCount()); + } + + /** + * BrokerA <- BrokerB -> BrokerC + */ + public void testBAandBCbrokerNetworkWithSelectorsSendFirst() throws Exception { + // Setup broker networks + bridgeBrokers("BrokerB", "BrokerA", true, 1, false); + bridgeBrokers("BrokerB", "BrokerC", true, 1, false); + + startAllBrokers(); + waitForBridgeFormation(); + + // Setup destination + Destination dest = createDestination("TEST.FOO", false); + + // Send messages for broker A + HashMap props = new HashMap(); + props.put("broker", "BROKER_A"); + sendMessages("BrokerB", dest, MESSAGE_COUNT, props); + + //Send messages for broker C + props.clear(); + props.put("broker", "BROKER_C"); + sendMessages("BrokerB", dest, MESSAGE_COUNT, props); + + // Setup consumers + MessageConsumer clientA = createConsumer("BrokerA", dest, "broker = 'BROKER_A'"); + MessageConsumer clientC = createConsumer("BrokerC", dest, "broker = 'BROKER_C'"); + Thread.sleep(2000); //et subscriptions get propagated + + // Let's try to wait for any messages. + //Thread.sleep(1000); + + // Get message count + MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); + MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); + + // Total received should be 100 + assertEquals(MESSAGE_COUNT, msgsA.getMessageCount()); + assertEquals(MESSAGE_COUNT, msgsC.getMessageCount()); + } + + /** + * BrokerA <- BrokerB -> BrokerC + */ + public void testBAandBCbrokerNetworkWithSelectorsSubscribeFirst() throws Exception { + // Setup broker networks + bridgeBrokers("BrokerB", "BrokerA", true, 1, false); + bridgeBrokers("BrokerB", "BrokerC", true, 1, false); + + startAllBrokers(); + waitForBridgeFormation(); + + // Setup destination + Destination dest = createDestination("TEST.FOO", false); + + // Setup consumers + MessageConsumer clientA = createConsumer("BrokerA", dest, "broker = 'BROKER_A'"); + MessageConsumer clientC = createConsumer("BrokerC", dest, "broker = 'BROKER_C'"); + Thread.sleep(2000); //et subscriptions get propagated + + // Send messages for broker A + HashMap props = new HashMap(); + props.put("broker", "BROKER_A"); + sendMessages("BrokerB", dest, MESSAGE_COUNT, props); + + //Send messages for broker C + props.clear(); + props.put("broker", "BROKER_C"); + sendMessages("BrokerB", dest, MESSAGE_COUNT, props); + + // Let's try to wait for any messages. + Thread.sleep(1000); + + // Get message count + MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); + MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); + + // Total received should be 100 + assertEquals(MESSAGE_COUNT, msgsA.getMessageCount()); + assertEquals(MESSAGE_COUNT, msgsC.getMessageCount()); + } + + /** + * BrokerA -> BrokerB <- BrokerC + */ + public void testABandCBbrokerNetwork() throws Exception { + // Setup broker networks + bridgeBrokers("BrokerA", "BrokerB"); + bridgeBrokers("BrokerC", "BrokerB"); + + startAllBrokers(); + waitForBridgeFormation(); + + // Setup destination + Destination dest = createDestination("TEST.FOO", false); + + // Setup consumers + MessageConsumer clientB = createConsumer("BrokerB", dest); + + // Send messages + sendMessages("BrokerA", dest, MESSAGE_COUNT); + sendMessages("BrokerC", dest, MESSAGE_COUNT); + + // Get message count + MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); + + msgsB.waitForMessagesToArrive(MESSAGE_COUNT * 2); + + assertEquals(MESSAGE_COUNT * 2, msgsB.getMessageCount()); + } + + /** + * BrokerA <-> BrokerB <-> BrokerC + */ + public void testAllConnectedBrokerNetwork() throws Exception { + // Setup broker networks + bridgeBrokers("BrokerA", "BrokerB"); + bridgeBrokers("BrokerB", "BrokerA"); + bridgeBrokers("BrokerB", "BrokerC"); + bridgeBrokers("BrokerC", "BrokerB"); + bridgeBrokers("BrokerA", "BrokerC"); + bridgeBrokers("BrokerC", "BrokerA"); + + startAllBrokers(); + waitForBridgeFormation(); + + // Setup destination + Destination dest = createDestination("TEST.FOO", false); + + // Setup consumers + MessageConsumer clientA = createConsumer("BrokerA", dest); + MessageConsumer clientB = createConsumer("BrokerB", dest); + MessageConsumer clientC = createConsumer("BrokerC", dest); + + // Send messages + sendMessages("BrokerA", dest, MESSAGE_COUNT); + sendMessages("BrokerB", dest, MESSAGE_COUNT); + sendMessages("BrokerC", dest, MESSAGE_COUNT); + + // Let's try to wait for any messages. + Thread.sleep(1000); + + // Get message count + MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); + MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); + MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); + + assertEquals(MESSAGE_COUNT * 3, msgsA.getMessageCount() + msgsB.getMessageCount() + msgsC.getMessageCount()); + } + + public void testAllConnectedUsingMulticast() throws Exception { + // Setup broker networks + bridgeAllBrokers(); + + startAllBrokers(); + waitForBridgeFormation(); + + // Setup destination + Destination dest = createDestination("TEST.FOO", false); + + // Setup consumers + MessageConsumer clientA = createConsumer("BrokerA", dest); + MessageConsumer clientB = createConsumer("BrokerB", dest); + MessageConsumer clientC = createConsumer("BrokerC", dest); + + // Send messages + sendMessages("BrokerA", dest, MESSAGE_COUNT); + sendMessages("BrokerB", dest, MESSAGE_COUNT); + sendMessages("BrokerC", dest, MESSAGE_COUNT); + + // Let's try to wait for any messages. + Thread.sleep(1000); + + // Get message count + final MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); + MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); + MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); + + waitFor(new Condition() { + public boolean isSatisified() { + return msgsA.getMessageCount() == MESSAGE_COUNT; + } + }); + + assertEquals(MESSAGE_COUNT * 3, msgsA.getMessageCount() + msgsB.getMessageCount() + msgsC.getMessageCount()); + } + + // on slow machines some more waiting is required on account of slow advisories + private void waitFor(Condition condition) throws Exception { + final long expiry = System.currentTimeMillis() + MAX_WAIT_MILLIS; + while (!condition.isSatisified() && System.currentTimeMillis() < expiry) { + Thread.sleep(1000); + } + if (System.currentTimeMillis() >= expiry) { + LOG.error("expired while waiting for condition " + condition); + } + + } + + public void testAllConnectedUsingMulticastProducerConsumerOnA() throws Exception { + bridgeAllBrokers("default", 3, false); + startAllBrokers(); + waitForBridgeFormation(); + + // Setup destination + Destination dest = createDestination("TEST.FOO", false); + + // Setup consumers + int messageCount = 2000; + CountDownLatch messagesReceived = new CountDownLatch(messageCount); + MessageConsumer clientA = createConsumer("BrokerA", dest, messagesReceived); + + // Let's try to wait for advisory percolation. + Thread.sleep(1000); + + // Send messages + sendMessages("BrokerA", dest, messageCount); + + assertTrue(messagesReceived.await(30, TimeUnit.SECONDS)); + + // Get message count + MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); + assertEquals(messageCount, msgsA.getMessageCount()); + } + + public void testAllConnectedWithSpare() throws Exception { + bridgeAllBrokers("default", 3, false); + startAllBrokers(); + waitForBridgeFormation(); + + // Setup destination + Destination dest = createDestination("TEST.FOO", false); + + // Setup consumers + int messageCount = 2000; + CountDownLatch messagesReceived = new CountDownLatch(messageCount); + MessageConsumer clientA = createConsumer("BrokerA", dest, messagesReceived); + + // ensure advisory percolation. + Thread.sleep(2000); + + // Send messages + sendMessages("BrokerB", dest, messageCount); + + assertTrue("messaged received within time limit", messagesReceived.await(30, TimeUnit.SECONDS)); + + // Get message count + MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); + assertEquals(messageCount, msgsA.getMessageCount()); + } + + /* + * This test is disabled - as it fails with a fix for + * http://issues.apache.org/activemq/browse/AMQ-2530 - which highlights that + * For a Conduit bridge - local subscription Ids weren't removed in a ConduitBridge + * The test fails because on closing clientA - clientB correctly receives all the + * messages - ie. half dont get stuck on BrokerA - + */ + public void XtestMigrateConsumerStuckMessages() throws Exception { + boolean suppressQueueDuplicateSubscriptions = false; + bridgeAllBrokers("default", 3, suppressQueueDuplicateSubscriptions); + startAllBrokers(); + waitForBridgeFormation(); + + // Setup destination + Destination dest = createDestination("TEST.FOO", false); + + // Setup consumers + LOG.info("Consumer on A"); + MessageConsumer clientA = createConsumer("BrokerA", dest); + + // ensure advisors have percolated + Thread.sleep(2000); + + LOG.info("Consumer on B"); + int messageCount = 2000; + + // will only get half of the messages + CountDownLatch messagesReceived = new CountDownLatch(messageCount / 2); + MessageConsumer clientB = createConsumer("BrokerB", dest, messagesReceived); + + // ensure advisors have percolated + Thread.sleep(2000); + + LOG.info("Close consumer on A"); + clientA.close(); + + // ensure advisors have percolated + Thread.sleep(2000); + + LOG.info("Send to B"); + sendMessages("BrokerB", dest, messageCount); + + // Let's try to wait for any messages. + assertTrue(messagesReceived.await(30, TimeUnit.SECONDS)); + + // Get message count + MessageIdList msgs = getConsumerMessages("BrokerB", clientB); + + // see will any more arrive + Thread.sleep(500); + assertEquals(messageCount / 2, msgs.getMessageCount()); + + // pick up the stuck messages + messagesReceived = new CountDownLatch(messageCount / 2); + clientA = createConsumer("BrokerA", dest, messagesReceived); + // Let's try to wait for any messages. + assertTrue(messagesReceived.await(30, TimeUnit.SECONDS)); + + msgs = getConsumerMessages("BrokerA", clientA); + assertEquals(messageCount / 2, msgs.getMessageCount()); + } + + // use case: for maintenance, migrate consumers and producers from one + // node in the network to another so node can be replaced/updated + public void testMigrateConsumer() throws Exception { + boolean suppressQueueDuplicateSubscriptions = true; + boolean decreaseNetworkConsumerPriority = true; + bridgeAllBrokers("default", 3, suppressQueueDuplicateSubscriptions, decreaseNetworkConsumerPriority); + startAllBrokers(); + waitForBridgeFormation(); + + // Setup destination + Destination dest = createDestination("TEST.FOO", false); + + // Setup consumers + LOG.info("Consumer on A"); + MessageConsumer clientA = createConsumer("BrokerA", dest); + + // ensure advisors have percolated + Thread.sleep(2000); + + LOG.info("Consumer on B"); + int messageCount = 2000; + CountDownLatch messagesReceived = new CountDownLatch(messageCount); + MessageConsumer clientB = createConsumer("BrokerB", dest, messagesReceived); + + // make the consumer slow so that any network consumer has a chance, even + // if it has a lower priority + MessageIdList msgs = getConsumerMessages("BrokerB", clientB); + msgs.setProcessingDelay(10); + + // ensure advisors have percolated + Thread.sleep(2000); + + LOG.info("Close consumer on A"); + clientA.close(); + + // ensure advisors have percolated + Thread.sleep(2000); + + LOG.info("Send to B"); + sendMessages("BrokerB", dest, messageCount); + + // Let's try to wait for any messages. + assertTrue("messages are received within limit", messagesReceived.await(60, TimeUnit.SECONDS)); + assertEquals(messageCount, msgs.getMessageCount()); + } + + public void testNoDuplicateQueueSubs() throws Exception { + + bridgeAllBrokers("default", 3, true); + + startAllBrokers(); + waitForBridgeFormation(); + + // Setup destination + Destination dest = createDestination("TEST.FOO", false); + + // Setup consumers + String brokerName = "BrokerA"; + MessageConsumer consumer = createConsumer(brokerName, dest); + + // wait for advisories + Thread.sleep(2000); + + // verify there is one consumer on each broker, no cycles + Collection brokerList = brokers.values(); + for (Iterator i = brokerList.iterator(); i.hasNext(); ) { + BrokerService broker = i.next().broker; + verifyConsumerCount(broker, 1, dest); + } + + consumer.close(); + + // wait for advisories + Thread.sleep(2000); + + // verify there is no more consumers + for (Iterator i = brokerList.iterator(); i.hasNext(); ) { + BrokerService broker = i.next().broker; + verifyConsumerCount(broker, 0, dest); + } + } + + public void testNoDuplicateQueueSubsHasLowestPriority() throws Exception { + boolean suppressQueueDuplicateSubscriptions = true; + boolean decreaseNetworkConsumerPriority = true; + bridgeAllBrokers("default", 3, suppressQueueDuplicateSubscriptions, decreaseNetworkConsumerPriority); + + // Setup destination + final Destination dest = createDestination("TEST.FOO", false); + + // delay the advisory messages so that one can percolate fully (cyclicly) before the other + BrokerItem brokerB = brokers.get("BrokerA"); + brokerB.broker.setPlugins(new BrokerPlugin[]{new BrokerPlugin() { + + public Broker installPlugin(Broker broker) throws Exception { + return new BrokerFilter(broker) { + + final AtomicInteger count = new AtomicInteger(); + + @Override + public void preProcessDispatch(MessageDispatch messageDispatch) { + if (messageDispatch.getDestination().getPhysicalName().contains("ActiveMQ.Advisory.Consumer")) { + // lets delay the first advisory + if (count.getAndIncrement() == 0) { + LOG.info("Sleeping on first advisory: " + messageDispatch); + try { + Thread.sleep(2000); } - super.postProcessDispatch(messageDispatch); - } - - }; - }} - }); - - startAllBrokers(); - waitForBridgeFormation(); - - - // Setup consumers - String brokerName = "BrokerA"; - createConsumer(brokerName, dest); - - // wait for advisories - Thread.sleep(5000); - - // verify there is one consumer on each broker, no cycles - Collection brokerList = brokers.values(); - for (Iterator i = brokerList.iterator(); i.hasNext();) { - BrokerService broker = i.next().broker; - verifyConsumerCount(broker, 1, dest); - if (!brokerName.equals(broker.getBrokerName())) { - verifyConsumePriority(broker, ConsumerInfo.NETWORK_CONSUMER_PRIORITY, dest); - } - } - } + catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + super.postProcessDispatch(messageDispatch); + } + }; + } + }}); - public void testDuplicateQueueSubs() throws Exception { + startAllBrokers(); + waitForBridgeFormation(); - configureBroker(createBroker("BrokerD")); - - bridgeAllBrokers("default", 3, false); - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); + // Setup consumers + String brokerName = "BrokerA"; + createConsumer(brokerName, dest); - // Setup consumers - String brokerName = "BrokerA"; - MessageConsumer consumer = createConsumer(brokerName, dest); - - // wait for advisories - Thread.sleep(2000); - - verifyConsumerCount(brokers.get(brokerName).broker, 1, dest); - - // in a cyclic network, other brokers will get second order consumer - // an alternative route to A via each other - Collection brokerList = brokers.values(); - for (Iterator i = brokerList.iterator(); i.hasNext();) { - BrokerService broker = i.next().broker; - if (!brokerName.equals(broker.getBrokerName())) { - verifyConsumerCount(broker, 5, dest); - verifyConsumePriority(broker, ConsumerInfo.NORMAL_PRIORITY, dest); - } - } - - consumer.close(); - - // wait for advisories - Thread.sleep(2000); + // wait for advisories + Thread.sleep(5000); - for (Iterator i = brokerList.iterator(); i.hasNext();) { - BrokerService broker = i.next().broker; - if (!brokerName.equals(broker.getBrokerName())) { - logConsumerCount(broker, 0, dest); - } - } + // verify there is one consumer on each broker, no cycles + Collection brokerList = brokers.values(); + for (Iterator i = brokerList.iterator(); i.hasNext(); ) { + BrokerService broker = i.next().broker; + verifyConsumerCount(broker, 1, dest); + if (!brokerName.equals(broker.getBrokerName())) { + verifyConsumePriority(broker, ConsumerInfo.NETWORK_CONSUMER_PRIORITY, dest); + } + } + } - for (Iterator i = brokerList.iterator(); i.hasNext();) { - BrokerService broker = i.next().broker; - verifyConsumerCount(broker, 0, dest); - } - } + public void testDuplicateQueueSubs() throws Exception { - private void verifyConsumerCount(BrokerService broker, int count, final Destination dest) throws Exception { - final RegionBroker regionBroker = (RegionBroker) broker.getRegionBroker(); - waitFor(new Condition() { - public boolean isSatisified() throws Exception { - return !regionBroker.getDestinations(ActiveMQDestination.transform(dest)).isEmpty(); - } - }); - Queue internalQueue = (Queue) regionBroker.getDestinations(ActiveMQDestination.transform(dest)).iterator().next(); - LOG.info("Verify: consumer count on " + broker.getBrokerName() + " matches:" + count + ", val:" + internalQueue.getConsumers().size()); - assertEquals("consumer count on " + broker.getBrokerName() + " matches for q: " + internalQueue, count, internalQueue.getConsumers().size()); - } + configureBroker(createBroker("BrokerD")); - private void logConsumerCount(BrokerService broker, int count, final Destination dest) throws Exception { - final RegionBroker regionBroker = (RegionBroker) broker.getRegionBroker(); - waitFor(new Condition() { - public boolean isSatisified() throws Exception { - return !regionBroker.getDestinations(ActiveMQDestination.transform(dest)).isEmpty(); - } - }); - Queue internalQueue = (Queue) regionBroker.getDestinations(ActiveMQDestination.transform(dest)).iterator().next(); - LOG.info("Verify: consumer count on " + broker.getBrokerName() + " matches:" + count + ", val:" + internalQueue.getConsumers().size()); - } + bridgeAllBrokers("default", 3, false); + startAllBrokers(); + waitForBridgeFormation(); - private void verifyConsumePriority(BrokerService broker, byte expectedPriority, Destination dest) throws Exception { - RegionBroker regionBroker = (RegionBroker) broker.getRegionBroker(); - Queue internalQueue = (Queue) regionBroker.getDestinations(ActiveMQDestination.transform(dest)).iterator().next(); - for (Subscription consumer : internalQueue.getConsumers()) { - assertEquals("consumer on " + broker.getBrokerName() + " matches priority: " + internalQueue, expectedPriority, consumer.getConsumerInfo().getPriority()); - } - } + // Setup destination + Destination dest = createDestination("TEST.FOO", false); - @Override - public void configureBroker(BrokerService brokerService) { - brokerService.setBrokerId(brokerService.getBrokerName()); - } + // Setup consumers + String brokerName = "BrokerA"; + MessageConsumer consumer = createConsumer(brokerName, dest); - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=false")); - createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=false")); - createBroker(new URI("broker:(tcp://localhost:61618)/BrokerC?persistent=false&useJmx=false")); - } + // wait for advisories + Thread.sleep(2000); + + verifyConsumerCount(brokers.get(brokerName).broker, 1, dest); + + // in a cyclic network, other brokers will get second order consumer + // an alternative route to A via each other + Collection brokerList = brokers.values(); + for (Iterator i = brokerList.iterator(); i.hasNext(); ) { + BrokerService broker = i.next().broker; + if (!brokerName.equals(broker.getBrokerName())) { + verifyConsumerCount(broker, 5, dest); + verifyConsumePriority(broker, ConsumerInfo.NORMAL_PRIORITY, dest); + } + } + + consumer.close(); + + // wait for advisories + Thread.sleep(2000); + + for (Iterator i = brokerList.iterator(); i.hasNext(); ) { + BrokerService broker = i.next().broker; + if (!brokerName.equals(broker.getBrokerName())) { + logConsumerCount(broker, 0, dest); + } + } + + for (Iterator i = brokerList.iterator(); i.hasNext(); ) { + BrokerService broker = i.next().broker; + verifyConsumerCount(broker, 0, dest); + } + } + + private void verifyConsumerCount(BrokerService broker, int count, final Destination dest) throws Exception { + final RegionBroker regionBroker = (RegionBroker) broker.getRegionBroker(); + waitFor(new Condition() { + public boolean isSatisified() throws Exception { + return !regionBroker.getDestinations(ActiveMQDestination.transform(dest)).isEmpty(); + } + }); + Queue internalQueue = (Queue) regionBroker.getDestinations(ActiveMQDestination.transform(dest)).iterator().next(); + LOG.info("Verify: consumer count on " + broker.getBrokerName() + " matches:" + count + ", val:" + internalQueue.getConsumers().size()); + assertEquals("consumer count on " + broker.getBrokerName() + " matches for q: " + internalQueue, count, internalQueue.getConsumers().size()); + } + + private void logConsumerCount(BrokerService broker, int count, final Destination dest) throws Exception { + final RegionBroker regionBroker = (RegionBroker) broker.getRegionBroker(); + waitFor(new Condition() { + public boolean isSatisified() throws Exception { + return !regionBroker.getDestinations(ActiveMQDestination.transform(dest)).isEmpty(); + } + }); + Queue internalQueue = (Queue) regionBroker.getDestinations(ActiveMQDestination.transform(dest)).iterator().next(); + LOG.info("Verify: consumer count on " + broker.getBrokerName() + " matches:" + count + ", val:" + internalQueue.getConsumers().size()); + } + + private void verifyConsumePriority(BrokerService broker, byte expectedPriority, Destination dest) throws Exception { + RegionBroker regionBroker = (RegionBroker) broker.getRegionBroker(); + Queue internalQueue = (Queue) regionBroker.getDestinations(ActiveMQDestination.transform(dest)).iterator().next(); + for (Subscription consumer : internalQueue.getConsumers()) { + assertEquals("consumer on " + broker.getBrokerName() + " matches priority: " + internalQueue, expectedPriority, consumer.getConsumerInfo().getPriority()); + } + } + + @Override + public void configureBroker(BrokerService brokerService) { + brokerService.setBrokerId(brokerService.getBrokerName()); + } + + @Override + public void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); + createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=false")); + createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=false")); + createBroker(new URI("broker:(tcp://localhost:61618)/BrokerC?persistent=false&useJmx=false")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerQueueNetworkUsingTcpTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerQueueNetworkUsingTcpTest.java index 2a87b7d06e..c78530c6b9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerQueueNetworkUsingTcpTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerQueueNetworkUsingTcpTest.java @@ -30,41 +30,44 @@ import org.apache.activemq.transport.TransportFactory; * */ public class ThreeBrokerQueueNetworkUsingTcpTest extends ThreeBrokerQueueNetworkTest { - protected List bridges; - protected void bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker) throws Exception { - List remoteTransports = remoteBroker.getTransportConnectors(); - List localTransports = localBroker.getTransportConnectors(); + protected List bridges; - URI remoteURI; - URI localURI; - if (!remoteTransports.isEmpty() && !localTransports.isEmpty()) { - remoteURI = remoteTransports.get(0).getConnectUri(); - localURI = localTransports.get(0).getConnectUri(); + protected void bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker) throws Exception { + List remoteTransports = remoteBroker.getTransportConnectors(); + List localTransports = localBroker.getTransportConnectors(); - // Ensure that we are connecting using tcp - if (remoteURI.toString().startsWith("tcp:") && localURI.toString().startsWith("tcp:")) { - NetworkBridgeConfiguration config = new NetworkBridgeConfiguration(); - config.setBrokerName(localBroker.getBrokerName()); - DemandForwardingBridge bridge = new DemandForwardingBridge(config, TransportFactory.connect(localURI), TransportFactory.connect(remoteURI)); - bridge.setBrokerService(localBroker); - bridges.add(bridge); + URI remoteURI; + URI localURI; + if (!remoteTransports.isEmpty() && !localTransports.isEmpty()) { + remoteURI = remoteTransports.get(0).getConnectUri(); + localURI = localTransports.get(0).getConnectUri(); - bridge.start(); - } else { - throw new Exception("Remote broker or local broker is not using tcp connectors"); - } - } else { - throw new Exception("Remote broker or local broker has no registered connectors."); - } + // Ensure that we are connecting using tcp + if (remoteURI.toString().startsWith("tcp:") && localURI.toString().startsWith("tcp:")) { + NetworkBridgeConfiguration config = new NetworkBridgeConfiguration(); + config.setBrokerName(localBroker.getBrokerName()); + DemandForwardingBridge bridge = new DemandForwardingBridge(config, TransportFactory.connect(localURI), TransportFactory.connect(remoteURI)); + bridge.setBrokerService(localBroker); + bridges.add(bridge); - maxSetupTime = 2000; - } + bridge.start(); + } + else { + throw new Exception("Remote broker or local broker is not using tcp connectors"); + } + } + else { + throw new Exception("Remote broker or local broker has no registered connectors."); + } - @Override - public void setUp() throws Exception { - super.setUp(); + maxSetupTime = 2000; + } - bridges = new ArrayList(); - } + @Override + public void setUp() throws Exception { + super.setUp(); + + bridges = new ArrayList(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerStompTemporaryQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerStompTemporaryQueueTest.java index eb987440a7..1349edd31f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerStompTemporaryQueueTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerStompTemporaryQueueTest.java @@ -33,144 +33,149 @@ import org.apache.activemq.transport.stomp.StompFrame; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - public class ThreeBrokerStompTemporaryQueueTest extends JmsMultipleBrokersTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(ThreeBrokerStompTemporaryQueueTest.class); - private StompConnection stompConnection; - @Override - protected NetworkConnector bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker, boolean dynamicOnly, int networkTTL, boolean conduit, boolean failover) throws Exception { - List transportConnectors = remoteBroker.getTransportConnectors(); - URI remoteURI; - if (!transportConnectors.isEmpty()) { - remoteURI = transportConnectors.get(0).getConnectUri(); - NetworkConnector connector = new DiscoveryNetworkConnector(new URI("static:" + remoteURI)); - connector.setName(localBroker.getBrokerName() + remoteBroker.getBrokerName()); - localBroker.addNetworkConnector(connector); - maxSetupTime = 2000; - return connector; - } else { - throw new Exception("Remote broker has no registered connectors."); - } - } + private static final Logger LOG = LoggerFactory.getLogger(ThreeBrokerStompTemporaryQueueTest.class); + private StompConnection stompConnection; - public void testStompTemporaryQueue() throws Exception { - // Setup broker networks - bridgeAndConfigureBrokers("BrokerA", "BrokerB"); - bridgeAndConfigureBrokers("BrokerA", "BrokerC"); - bridgeAndConfigureBrokers("BrokerB", "BrokerA"); - bridgeAndConfigureBrokers("BrokerB", "BrokerC"); - bridgeAndConfigureBrokers("BrokerC", "BrokerA"); - bridgeAndConfigureBrokers("BrokerC", "BrokerB"); + @Override + protected NetworkConnector bridgeBrokers(BrokerService localBroker, + BrokerService remoteBroker, + boolean dynamicOnly, + int networkTTL, + boolean conduit, + boolean failover) throws Exception { + List transportConnectors = remoteBroker.getTransportConnectors(); + URI remoteURI; + if (!transportConnectors.isEmpty()) { + remoteURI = transportConnectors.get(0).getConnectUri(); + NetworkConnector connector = new DiscoveryNetworkConnector(new URI("static:" + remoteURI)); + connector.setName(localBroker.getBrokerName() + remoteBroker.getBrokerName()); + localBroker.addNetworkConnector(connector); + maxSetupTime = 2000; + return connector; + } + else { + throw new Exception("Remote broker has no registered connectors."); + } + } - startAllBrokers(); - waitForBridgeFormation(); + public void testStompTemporaryQueue() throws Exception { + // Setup broker networks + bridgeAndConfigureBrokers("BrokerA", "BrokerB"); + bridgeAndConfigureBrokers("BrokerA", "BrokerC"); + bridgeAndConfigureBrokers("BrokerB", "BrokerA"); + bridgeAndConfigureBrokers("BrokerB", "BrokerC"); + bridgeAndConfigureBrokers("BrokerC", "BrokerA"); + bridgeAndConfigureBrokers("BrokerC", "BrokerB"); - Thread.sleep(1000); + startAllBrokers(); + waitForBridgeFormation(); - stompConnection = new StompConnection(); - stompConnection.open("localhost", 61614); - // Creating a temp queue - stompConnection.sendFrame("CONNECT\n" + "login:system\n" + "passcode:manager\n\n" + Stomp.NULL); + Thread.sleep(1000); - StompFrame frame = stompConnection.receive(); - assertTrue(frame.toString().startsWith("CONNECTED")); + stompConnection = new StompConnection(); + stompConnection.open("localhost", 61614); + // Creating a temp queue + stompConnection.sendFrame("CONNECT\n" + "login:system\n" + "passcode:manager\n\n" + Stomp.NULL); - stompConnection.subscribe("/temp-queue/meaningless", "auto"); - stompConnection.send("/temp-queue/meaningless", "Hello World"); + StompFrame frame = stompConnection.receive(); + assertTrue(frame.toString().startsWith("CONNECTED")); - frame = stompConnection.receive(3000); - assertEquals("Hello World", frame.getBody()); + stompConnection.subscribe("/temp-queue/meaningless", "auto"); + stompConnection.send("/temp-queue/meaningless", "Hello World"); - Thread.sleep(1000); + frame = stompConnection.receive(3000); + assertEquals("Hello World", frame.getBody()); - assertEquals("Destination", 1, brokers.get("BrokerA").broker.getAdminView().getTemporaryQueues().length); - assertEquals("Destination", 1, brokers.get("BrokerB").broker.getAdminView().getTemporaryQueues().length); - assertEquals("Destination", 1, brokers.get("BrokerC").broker.getAdminView().getTemporaryQueues().length); + Thread.sleep(1000); - int advisoryTopicsForTempQueues; - advisoryTopicsForTempQueues = countTopicsByName("BrokerA", "ActiveMQ.Advisory.Consumer.Queue.ID"); - assertEquals("Advisory topic should be present", 1, advisoryTopicsForTempQueues); + assertEquals("Destination", 1, brokers.get("BrokerA").broker.getAdminView().getTemporaryQueues().length); + assertEquals("Destination", 1, brokers.get("BrokerB").broker.getAdminView().getTemporaryQueues().length); + assertEquals("Destination", 1, brokers.get("BrokerC").broker.getAdminView().getTemporaryQueues().length); - advisoryTopicsForTempQueues = countTopicsByName("BrokerB", "ActiveMQ.Advisory.Consumer.Queue.ID"); - assertEquals("Advisory topic should be present", 1, advisoryTopicsForTempQueues); + int advisoryTopicsForTempQueues; + advisoryTopicsForTempQueues = countTopicsByName("BrokerA", "ActiveMQ.Advisory.Consumer.Queue.ID"); + assertEquals("Advisory topic should be present", 1, advisoryTopicsForTempQueues); - advisoryTopicsForTempQueues = countTopicsByName("BrokerC", "ActiveMQ.Advisory.Consumer.Queue.ID"); - assertEquals("Advisory topic should be present", 1, advisoryTopicsForTempQueues); + advisoryTopicsForTempQueues = countTopicsByName("BrokerB", "ActiveMQ.Advisory.Consumer.Queue.ID"); + assertEquals("Advisory topic should be present", 1, advisoryTopicsForTempQueues); - stompConnection.disconnect(); + advisoryTopicsForTempQueues = countTopicsByName("BrokerC", "ActiveMQ.Advisory.Consumer.Queue.ID"); + assertEquals("Advisory topic should be present", 1, advisoryTopicsForTempQueues); - Thread.sleep(1000); + stompConnection.disconnect(); - advisoryTopicsForTempQueues = countTopicsByName("BrokerA", "ActiveMQ.Advisory.Consumer.Queue.ID"); - assertEquals("Advisory topic should have been deleted", 0, advisoryTopicsForTempQueues); - advisoryTopicsForTempQueues = countTopicsByName("BrokerB", "ActiveMQ.Advisory.Consumer.Queue.ID"); - assertEquals("Advisory topic should have been deleted", 0, advisoryTopicsForTempQueues); - advisoryTopicsForTempQueues = countTopicsByName("BrokerC", "ActiveMQ.Advisory.Consumer.Queue.ID"); - assertEquals("Advisory topic should have been deleted", 0, advisoryTopicsForTempQueues); + Thread.sleep(1000); - LOG.info("Restarting brokerA"); - BrokerItem brokerItem = brokers.remove("BrokerA"); - if (brokerItem != null) { - brokerItem.destroy(); - } + advisoryTopicsForTempQueues = countTopicsByName("BrokerA", "ActiveMQ.Advisory.Consumer.Queue.ID"); + assertEquals("Advisory topic should have been deleted", 0, advisoryTopicsForTempQueues); + advisoryTopicsForTempQueues = countTopicsByName("BrokerB", "ActiveMQ.Advisory.Consumer.Queue.ID"); + assertEquals("Advisory topic should have been deleted", 0, advisoryTopicsForTempQueues); + advisoryTopicsForTempQueues = countTopicsByName("BrokerC", "ActiveMQ.Advisory.Consumer.Queue.ID"); + assertEquals("Advisory topic should have been deleted", 0, advisoryTopicsForTempQueues); - BrokerService restartedBroker = createAndConfigureBroker(new URI("broker:(tcp://localhost:61616,stomp://localhost:61613)/BrokerA")); - bridgeAndConfigureBrokers("BrokerA", "BrokerB"); - bridgeAndConfigureBrokers("BrokerA", "BrokerC"); - restartedBroker.start(); - waitForBridgeFormation(); + LOG.info("Restarting brokerA"); + BrokerItem brokerItem = brokers.remove("BrokerA"); + if (brokerItem != null) { + brokerItem.destroy(); + } - Thread.sleep(3000); + BrokerService restartedBroker = createAndConfigureBroker(new URI("broker:(tcp://localhost:61616,stomp://localhost:61613)/BrokerA")); + bridgeAndConfigureBrokers("BrokerA", "BrokerB"); + bridgeAndConfigureBrokers("BrokerA", "BrokerC"); + restartedBroker.start(); + waitForBridgeFormation(); - assertEquals("Destination", 0, brokers.get("BrokerA").broker.getAdminView().getTemporaryQueues().length); - assertEquals("Destination", 0, brokers.get("BrokerB").broker.getAdminView().getTemporaryQueues().length); - assertEquals("Destination", 0, brokers.get("BrokerC").broker.getAdminView().getTemporaryQueues().length); + Thread.sleep(3000); - advisoryTopicsForTempQueues = countTopicsByName("BrokerA", "ActiveMQ.Advisory.Consumer.Queue.ID"); - assertEquals("Advisory topic should have been deleted", 0, advisoryTopicsForTempQueues); - advisoryTopicsForTempQueues = countTopicsByName("BrokerB", "ActiveMQ.Advisory.Consumer.Queue.ID"); - assertEquals("Advisory topic should have been deleted", 0, advisoryTopicsForTempQueues); - advisoryTopicsForTempQueues = countTopicsByName("BrokerC", "ActiveMQ.Advisory.Consumer.Queue.ID"); - assertEquals("Advisory topic should have been deleted", 0, advisoryTopicsForTempQueues); - } + assertEquals("Destination", 0, brokers.get("BrokerA").broker.getAdminView().getTemporaryQueues().length); + assertEquals("Destination", 0, brokers.get("BrokerB").broker.getAdminView().getTemporaryQueues().length); + assertEquals("Destination", 0, brokers.get("BrokerC").broker.getAdminView().getTemporaryQueues().length); - private int countTopicsByName(String broker, String name) - throws Exception { - int advisoryTopicsForTempQueues = 0; - for(int i=0; iChristian Posta */ public class ThreeBrokerTempDestDemandSubscriptionCleanupTest extends JmsMultipleBrokersTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(ThreeBrokerTempDestDemandSubscriptionCleanupTest.class); - boolean enableTempDestinationBridging = true; + private static final Logger LOG = LoggerFactory.getLogger(ThreeBrokerTempDestDemandSubscriptionCleanupTest.class); - private static final String BROKER_A = "BrokerA"; - private static final String BROKER_B = "BrokerB"; - private static final String BROKER_C = "BrokerC"; + boolean enableTempDestinationBridging = true; - private static final String ECHO_QUEUE_NAME = "echo"; - private static final int NUM_ITER = 100; - private static final long CONSUME_TIMEOUT = 500; + private static final String BROKER_A = "BrokerA"; + private static final String BROKER_B = "BrokerB"; + private static final String BROKER_C = "BrokerC"; + private static final String ECHO_QUEUE_NAME = "echo"; + private static final int NUM_ITER = 100; + private static final long CONSUME_TIMEOUT = 500; - /** - * So we network three brokers together, and send a message with request-reply semantics. - * The message goes to an echo service listening on broker C. We send a message on a queue - * to broker A which gets demand forwarded to broker C. the echo service will respond to the - * temp destination listed in the JMSReplyTo header. that will get demand forwarded back to - * broker A. When the consumer of the temp dest on broker A closes, that subscription should - * be removed on broker A. advisories firing from broker A to broker B should remove that - * subscription on broker B. advisories firing from broker B to broker C should remove that - * subscription on broker C. - * - * @throws Exception - */ - public void testSubscriptionsCleanedUpRace() throws Exception { + /** + * So we network three brokers together, and send a message with request-reply semantics. + * The message goes to an echo service listening on broker C. We send a message on a queue + * to broker A which gets demand forwarded to broker C. the echo service will respond to the + * temp destination listed in the JMSReplyTo header. that will get demand forwarded back to + * broker A. When the consumer of the temp dest on broker A closes, that subscription should + * be removed on broker A. advisories firing from broker A to broker B should remove that + * subscription on broker B. advisories firing from broker B to broker C should remove that + * subscription on broker C. + * + * @throws Exception + */ + public void testSubscriptionsCleanedUpRace() throws Exception { - final BrokerItem brokerA = brokers.get(BROKER_A); + final BrokerItem brokerA = brokers.get(BROKER_A); + Runnable tester = new Runnable() { - Runnable tester = new Runnable() { + @Override + public void run() { + for (int i = 0; i < NUM_ITER; i++) { - @Override - public void run() { - for (int i = 0; i < NUM_ITER; i++) { + Connection conn = null; + try { + conn = brokerA.createConnection(); - Connection conn = null; - try { - conn = brokerA.createConnection(); + conn.start(); - conn.start(); + final Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = sess.createQueue(ECHO_QUEUE_NAME); - final Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = sess.createQueue(ECHO_QUEUE_NAME); + MessageProducer producer = sess.createProducer(destination); - MessageProducer producer = sess.createProducer(destination); + LOG.info("Starting iter: " + i); + Destination replyTo = sess.createTemporaryQueue(); + MessageConsumer responseConsumer = sess.createConsumer(replyTo); - LOG.info("Starting iter: " + i); - Destination replyTo = sess.createTemporaryQueue(); - MessageConsumer responseConsumer = sess.createConsumer(replyTo); + Message message = sess.createTextMessage("Iteration: " + i); + message.setJMSReplyTo(replyTo); - Message message = sess.createTextMessage("Iteration: " + i); - message.setJMSReplyTo(replyTo); + producer.send(message); - producer.send(message); + TextMessage response = (TextMessage) responseConsumer.receive(CONSUME_TIMEOUT); + assertNotNull("We should have gotten a response, but didn't for iter: " + i, response); + assertEquals("We got the wrong response from the echo service", "Iteration: " + i, response.getText()); - TextMessage response = (TextMessage)responseConsumer.receive(CONSUME_TIMEOUT); - assertNotNull("We should have gotten a response, but didn't for iter: " + i, response); - assertEquals("We got the wrong response from the echo service", "Iteration: " + i, response.getText()); + // so we close the consumer so that an actual RemoveInfo command gets propogated through the + // network + responseConsumer.close(); + conn.close(); + } + catch (Exception e) { + e.printStackTrace(); + fail(); + } - // so we close the consumer so that an actual RemoveInfo command gets propogated through the - // network - responseConsumer.close(); - conn.close(); - - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - - } } - }; + } + }; - ExecutorService threadService = Executors.newFixedThreadPool(2); - threadService.submit(tester); - threadService.submit(tester); + ExecutorService threadService = Executors.newFixedThreadPool(2); + threadService.submit(tester); + threadService.submit(tester); - threadService.shutdown(); - assertTrue("executor done on time", threadService.awaitTermination(30L, TimeUnit.SECONDS)); + threadService.shutdown(); + assertTrue("executor done on time", threadService.awaitTermination(30L, TimeUnit.SECONDS)); - // for the real test... we should not have any subscriptions left on broker C for the temp dests - BrokerItem brokerC = brokers.get(BROKER_C); - RegionBroker regionBroker = (RegionBroker) brokerC.broker.getRegionBroker(); - final AbstractRegion region = (AbstractRegion) regionBroker.getTempQueueRegion(); + // for the real test... we should not have any subscriptions left on broker C for the temp dests + BrokerItem brokerC = brokers.get(BROKER_C); + RegionBroker regionBroker = (RegionBroker) brokerC.broker.getRegionBroker(); + final AbstractRegion region = (AbstractRegion) regionBroker.getTempQueueRegion(); - assertTrue("There were no lingering temp-queue destinations", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("Lingering temps: " + region.getSubscriptions().size()); - return 0 == region.getSubscriptions().size(); - } - })); - } + assertTrue("There were no lingering temp-queue destinations", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("Lingering temps: " + region.getSubscriptions().size()); + return 0 == region.getSubscriptions().size(); + } + })); + } + /** + * This test is slightly different from the above. We don't explicitly close the consumer down + * (which we did in the previous test to force the RemoveInfo to be sent). Here we just close + * the connection which should still clean up the subscriptions and temp destinations on the + * networked brokers. + * + * @throws Exception + */ + public void testSubscriptionsCleanedUpAfterConnectionClose() throws Exception { - /** - * This test is slightly different from the above. We don't explicitly close the consumer down - * (which we did in the previous test to force the RemoveInfo to be sent). Here we just close - * the connection which should still clean up the subscriptions and temp destinations on the - * networked brokers. - * - * @throws Exception - */ - public void testSubscriptionsCleanedUpAfterConnectionClose() throws Exception { + final BrokerItem brokerA = brokers.get(BROKER_A); - final BrokerItem brokerA = brokers.get(BROKER_A); + for (int i = 0; i < NUM_ITER; i++) { - for (int i = 0; i < NUM_ITER; i++) { + Connection conn = null; + try { + conn = brokerA.createConnection(); + + conn.start(); + + final Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = sess.createQueue(ECHO_QUEUE_NAME); + + MessageProducer producer = sess.createProducer(destination); + + LOG.info("Starting iter: " + i); + Destination replyTo = sess.createTemporaryQueue(); + MessageConsumer responseConsumer = sess.createConsumer(replyTo); + + Message message = sess.createTextMessage("Iteration: " + i); + message.setJMSReplyTo(replyTo); + + producer.send(message); + + TextMessage response = (TextMessage) responseConsumer.receive(CONSUME_TIMEOUT); + assertNotNull("We should have gotten a response, but didn't for iter: " + i, response); + assertEquals("We got the wrong response from the echo service", "Iteration: " + i, response.getText()); + + // so closing the connection without closing the consumer first will leak subscriptions + // in a nob? + // responseConsumer.close(); + conn.close(); + + } + catch (Exception e) { + e.printStackTrace(); + fail(); + } + + } + + // for the real test... we should not have any subscriptions left on broker C for the temp dests + BrokerItem brokerC = brokers.get(BROKER_C); + RegionBroker regionBroker = (RegionBroker) brokerC.broker.getRegionBroker(); + final AbstractRegion region = (AbstractRegion) regionBroker.getTempQueueRegion(); + + assertTrue("There were no lingering temp-queue destinations", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("Lingering temps: " + region.getSubscriptions().size()); + return 0 == region.getSubscriptions().size(); + } + })); + + } + + private void installEchoClientOnBrokerC() throws Exception { + BrokerItem brokerC = brokers.get(BROKER_C); + Connection conn = brokerC.createConnection(); + conn.start(); + + final Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = sess.createQueue(ECHO_QUEUE_NAME); + MessageConsumer consumer = sess.createConsumer(destination); + + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + + TextMessage textMessage = (TextMessage) message; - Connection conn = null; try { - conn = brokerA.createConnection(); + Destination replyTo = message.getJMSReplyTo(); - conn.start(); + MessageProducer producer = sess.createProducer(replyTo); + Message response = sess.createTextMessage(textMessage.getText()); - final Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = sess.createQueue(ECHO_QUEUE_NAME); + LOG.info("Replying to this request: " + textMessage.getText()); + producer.send(response); + producer.close(); - MessageProducer producer = sess.createProducer(destination); - - LOG.info("Starting iter: " + i); - Destination replyTo = sess.createTemporaryQueue(); - MessageConsumer responseConsumer = sess.createConsumer(replyTo); - - Message message = sess.createTextMessage("Iteration: " + i); - message.setJMSReplyTo(replyTo); - - producer.send(message); - - TextMessage response = (TextMessage)responseConsumer.receive(CONSUME_TIMEOUT); - assertNotNull("We should have gotten a response, but didn't for iter: " + i, response); - assertEquals("We got the wrong response from the echo service", "Iteration: " + i, response.getText()); - - - // so closing the connection without closing the consumer first will leak subscriptions - // in a nob? -// responseConsumer.close(); - conn.close(); - - } catch (Exception e) { - e.printStackTrace(); - fail(); } - - } - - // for the real test... we should not have any subscriptions left on broker C for the temp dests - BrokerItem brokerC = brokers.get(BROKER_C); - RegionBroker regionBroker = (RegionBroker) brokerC.broker.getRegionBroker(); - final AbstractRegion region = (AbstractRegion) regionBroker.getTempQueueRegion(); - - assertTrue("There were no lingering temp-queue destinations", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("Lingering temps: " + region.getSubscriptions().size()); - return 0 == region.getSubscriptions().size(); + catch (JMSException e) { + e.printStackTrace(); + fail("Could not respond to an echo request"); } - })); + } + }); + } - } + @Override + protected void setUp() throws Exception { + super.setUp(); + createBroker(new URI("broker:(tcp://localhost:61616)/" + BROKER_A + "?persistent=false&useJmx=false")); + createBroker(new URI("broker:(tcp://localhost:61617)/" + BROKER_B + "?persistent=false&useJmx=false")); + createBroker(new URI("broker:(tcp://localhost:61618)/" + BROKER_C + "?persistent=false&useJmx=false")); - private void installEchoClientOnBrokerC() throws Exception { - BrokerItem brokerC = brokers.get(BROKER_C); - Connection conn = brokerC.createConnection(); - conn.start(); + bridgeBrokers("BrokerA", "BrokerB", false, 3); + bridgeBrokers("BrokerB", "BrokerC", false, 3); - final Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = sess.createQueue(ECHO_QUEUE_NAME); - MessageConsumer consumer = sess.createConsumer(destination); + startAllBrokers(); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { + // set up a listener on broker C that will demand forward subscriptions over the network + installEchoClientOnBrokerC(); + } - TextMessage textMessage = (TextMessage) message; - - try { - Destination replyTo = message.getJMSReplyTo(); - - MessageProducer producer = sess.createProducer(replyTo); - Message response = sess.createTextMessage(textMessage.getText()); - - LOG.info("Replying to this request: " + textMessage.getText()); - producer.send(response); - producer.close(); - - } catch (JMSException e) { - e.printStackTrace(); - fail("Could not respond to an echo request"); - } - } - }); - } - - - @Override - protected void setUp() throws Exception { - super.setUp(); - createBroker(new URI("broker:(tcp://localhost:61616)/" + BROKER_A + "?persistent=false&useJmx=false")); - createBroker(new URI("broker:(tcp://localhost:61617)/" + BROKER_B + "?persistent=false&useJmx=false")); - createBroker(new URI("broker:(tcp://localhost:61618)/" + BROKER_C + "?persistent=false&useJmx=false")); - - bridgeBrokers("BrokerA", "BrokerB", false, 3); - bridgeBrokers("BrokerB", "BrokerC", false, 3); - - startAllBrokers(); - - // set up a listener on broker C that will demand forward subscriptions over the network - installEchoClientOnBrokerC(); - } - - protected NetworkConnector bridgeBrokers(String localBrokerName, String remoteBrokerName, boolean dynamicOnly, int networkTTL) throws Exception { - NetworkConnector connector = super.bridgeBrokers(localBrokerName, remoteBrokerName, dynamicOnly, networkTTL, true); - connector.setBridgeTempDestinations(enableTempDestinationBridging); - connector.setDuplex(true); - return connector; - } + protected NetworkConnector bridgeBrokers(String localBrokerName, + String remoteBrokerName, + boolean dynamicOnly, + int networkTTL) throws Exception { + NetworkConnector connector = super.bridgeBrokers(localBrokerName, remoteBrokerName, dynamicOnly, networkTTL, true); + connector.setBridgeTempDestinations(enableTempDestinationBridging); + connector.setDuplex(true); + return connector; + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTempQueueNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTempQueueNetworkTest.java index 2f7b13701e..52be70bbbf 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTempQueueNetworkTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTempQueueNetworkTest.java @@ -30,89 +30,94 @@ import org.apache.activemq.network.NetworkConnector; * */ public class ThreeBrokerTempQueueNetworkTest extends JmsMultipleBrokersTestSupport { - protected static final int MESSAGE_COUNT = 100; - boolean enableTempDestinationBridging = true; - /** - * BrokerA -> BrokerB -> BrokerC - */ - public void testTempQueueCleanup() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerA", "BrokerB", false, 2); - bridgeBrokers("BrokerB", "BrokerC", false, 2); - startAllBrokers(); - BrokerItem brokerItem = brokers.get("BrokerC"); - Connection conn = brokerItem.createConnection(); - conn.start(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - TemporaryQueue tempQ = sess.createTemporaryQueue(); - Thread.sleep(5000); - for (Iterator i = brokers.values().iterator(); i.hasNext();) { - BrokerItem bi = i.next(); - assertEquals("No queues on broker " + bi.broker.getBrokerName(), 1, bi.broker.getAdminView().getTemporaryQueues().length); - } - tempQ.delete(); - Thread.sleep(2000); - for (Iterator i = brokers.values().iterator(); i.hasNext();) { - BrokerItem bi = i.next(); - assertEquals("Temp queue left behind on broker " + bi.broker.getBrokerName(), 0, bi.broker.getAdminView().getTemporaryQueues().length); - } - } + protected static final int MESSAGE_COUNT = 100; + boolean enableTempDestinationBridging = true; - // this actually uses 4 brokers ... - public void testTempQueueRecovery() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerA", "BrokerB", false, 3); - bridgeBrokers("BrokerB", "BrokerC", false, 3); - startAllBrokers(); - BrokerItem brokerItem = brokers.get("BrokerC"); - Connection conn = brokerItem.createConnection(); - conn.start(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - TemporaryQueue tempQ = sess.createTemporaryQueue(); - Thread.sleep(5000); - for (Iterator i = brokers.values().iterator(); i.hasNext();) { - BrokerItem bi = i.next(); - assertEquals("No queues on broker " + bi.broker.getBrokerName(), 1, bi.broker.getAdminView().getTemporaryQueues().length); - } - createBroker(new URI("broker:(tcp://localhost:61619)/BrokerD?persistent=false&useJmx=true")); - bridgeBrokers("BrokerD", "BrokerA", false, 3); - BrokerItem newBroker = brokers.get("BrokerD"); - newBroker.broker.start(); - Thread.sleep(1000); - assertEquals("No queues on broker D", 1, newBroker.broker.getAdminView().getTemporaryQueues().length); - tempQ.delete(); - Thread.sleep(2000); - for (Iterator i = brokers.values().iterator(); i.hasNext();) { - BrokerItem bi = i.next(); - assertEquals("Temp queue left behind on broker " + bi.broker.getBrokerName(), 0, bi.broker.getAdminView().getTemporaryQueues().length); - } - } + /** + * BrokerA -> BrokerB -> BrokerC + */ + public void testTempQueueCleanup() throws Exception { + // Setup broker networks + bridgeBrokers("BrokerA", "BrokerB", false, 2); + bridgeBrokers("BrokerB", "BrokerC", false, 2); + startAllBrokers(); + BrokerItem brokerItem = brokers.get("BrokerC"); + Connection conn = brokerItem.createConnection(); + conn.start(); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + TemporaryQueue tempQ = sess.createTemporaryQueue(); + Thread.sleep(5000); + for (Iterator i = brokers.values().iterator(); i.hasNext(); ) { + BrokerItem bi = i.next(); + assertEquals("No queues on broker " + bi.broker.getBrokerName(), 1, bi.broker.getAdminView().getTemporaryQueues().length); + } + tempQ.delete(); + Thread.sleep(2000); + for (Iterator i = brokers.values().iterator(); i.hasNext(); ) { + BrokerItem bi = i.next(); + assertEquals("Temp queue left behind on broker " + bi.broker.getBrokerName(), 0, bi.broker.getAdminView().getTemporaryQueues().length); + } + } - public void testTempDisable() throws Exception { - enableTempDestinationBridging = false; - try { - testTempQueueCleanup(); - } catch (Throwable e) { - // Expecting an error - return; - } - fail("Test should have failed since temp queues are disabled."); - } + // this actually uses 4 brokers ... + public void testTempQueueRecovery() throws Exception { + // Setup broker networks + bridgeBrokers("BrokerA", "BrokerB", false, 3); + bridgeBrokers("BrokerB", "BrokerC", false, 3); + startAllBrokers(); + BrokerItem brokerItem = brokers.get("BrokerC"); + Connection conn = brokerItem.createConnection(); + conn.start(); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + TemporaryQueue tempQ = sess.createTemporaryQueue(); + Thread.sleep(5000); + for (Iterator i = brokers.values().iterator(); i.hasNext(); ) { + BrokerItem bi = i.next(); + assertEquals("No queues on broker " + bi.broker.getBrokerName(), 1, bi.broker.getAdminView().getTemporaryQueues().length); + } + createBroker(new URI("broker:(tcp://localhost:61619)/BrokerD?persistent=false&useJmx=true")); + bridgeBrokers("BrokerD", "BrokerA", false, 3); + BrokerItem newBroker = brokers.get("BrokerD"); + newBroker.broker.start(); + Thread.sleep(1000); + assertEquals("No queues on broker D", 1, newBroker.broker.getAdminView().getTemporaryQueues().length); + tempQ.delete(); + Thread.sleep(2000); + for (Iterator i = brokers.values().iterator(); i.hasNext(); ) { + BrokerItem bi = i.next(); + assertEquals("Temp queue left behind on broker " + bi.broker.getBrokerName(), 0, bi.broker.getAdminView().getTemporaryQueues().length); + } + } - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=true")); - createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=true")); - createBroker(new URI("broker:(tcp://localhost:61618)/BrokerC?persistent=false&useJmx=true")); - } + public void testTempDisable() throws Exception { + enableTempDestinationBridging = false; + try { + testTempQueueCleanup(); + } + catch (Throwable e) { + // Expecting an error + return; + } + fail("Test should have failed since temp queues are disabled."); + } - protected NetworkConnector bridgeBrokers(String localBrokerName, String remoteBrokerName, boolean dynamicOnly, int networkTTL) throws Exception { - NetworkConnector connector = super.bridgeBrokers(localBrokerName, remoteBrokerName, dynamicOnly, networkTTL, true); - connector.setBridgeTempDestinations(enableTempDestinationBridging); - return connector; - } + @Override + public void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); + createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=true")); + createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=true")); + createBroker(new URI("broker:(tcp://localhost:61618)/BrokerC?persistent=false&useJmx=true")); + } + + protected NetworkConnector bridgeBrokers(String localBrokerName, + String remoteBrokerName, + boolean dynamicOnly, + int networkTTL) throws Exception { + NetworkConnector connector = super.bridgeBrokers(localBrokerName, remoteBrokerName, dynamicOnly, networkTTL, true); + connector.setBridgeTempDestinations(enableTempDestinationBridging); + return connector; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTopicNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTopicNetworkTest.java index 70d3563232..73a4b107b7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTopicNetworkTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTopicNetworkTest.java @@ -38,374 +38,374 @@ import org.apache.activemq.util.MessageIdList; * */ public class ThreeBrokerTopicNetworkTest extends JmsMultipleBrokersTestSupport { - protected static final int MESSAGE_COUNT = 100; - public boolean dynamicOnly; - - /** - * BrokerA -> BrokerB -> BrokerC - */ - public void testABandBCbrokerNetwork() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerA", "BrokerB"); - bridgeBrokers("BrokerB", "BrokerC"); - - startAllBrokers(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", true); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); - MessageConsumer clientB = createConsumer("BrokerB", dest); - MessageConsumer clientC = createConsumer("BrokerC", dest); - - //let consumers propagate around the network - Thread.sleep(2000); - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); - sendMessages("BrokerB", dest, MESSAGE_COUNT); - sendMessages("BrokerC", dest, MESSAGE_COUNT); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - msgsA.waitForMessagesToArrive(MESSAGE_COUNT); - msgsB.waitForMessagesToArrive(MESSAGE_COUNT * 2); - msgsC.waitForMessagesToArrive(MESSAGE_COUNT * 2); - - assertEquals(MESSAGE_COUNT, msgsA.getMessageCount()); - assertEquals(MESSAGE_COUNT * 2, msgsB.getMessageCount()); - assertEquals(MESSAGE_COUNT * 2, msgsC.getMessageCount()); - - assertEquals("Correct forwards from A", MESSAGE_COUNT, - brokers.get("BrokerA").broker.getDestination(ActiveMQDestination.transform(dest)).getDestinationStatistics().getForwards().getCount()); - } - - public void initCombosForTestABandBCbrokerNetworkWithSelectors() { - addCombinationValues("dynamicOnly", new Object[] {true, false}); - } - - /** - * BrokerA -> BrokerB -> BrokerC - */ - public void testABandBCbrokerNetworkWithSelectors() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerA", "BrokerB", dynamicOnly, 2, true); - bridgeBrokers("BrokerB", "BrokerC", dynamicOnly, 2, true); - - startAllBrokers(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", true); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerC", dest, "dummy = 33"); - MessageConsumer clientB = createConsumer("BrokerC", dest, "dummy > 30"); - MessageConsumer clientC = createConsumer("BrokerC", dest, "dummy = 34"); - - // let consumers propagate around the network - Thread.sleep(2000); - // Send messages - // Send messages for broker A - HashMap props = new HashMap(); - props.put("dummy", 33); - sendMessages("BrokerA", dest, MESSAGE_COUNT, props); - props.put("dummy", 34); - sendMessages("BrokerA", dest, MESSAGE_COUNT * 2, props); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerC", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerC", clientB); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - msgsA.waitForMessagesToArrive(MESSAGE_COUNT); - msgsB.waitForMessagesToArrive(MESSAGE_COUNT * 3); - msgsC.waitForMessagesToArrive(MESSAGE_COUNT * 2) ; - - assertEquals(MESSAGE_COUNT, msgsA.getMessageCount()); - assertEquals(MESSAGE_COUNT * 3, msgsB.getMessageCount()); - assertEquals(MESSAGE_COUNT *2, msgsC.getMessageCount()); - } - - /** - * BrokerA <- BrokerB -> BrokerC - */ - public void testBAandBCbrokerNetwork() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerB", "BrokerA"); - bridgeBrokers("BrokerB", "BrokerC"); - - startAllBrokers(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", true); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); - MessageConsumer clientB = createConsumer("BrokerB", dest); - MessageConsumer clientC = createConsumer("BrokerC", dest); - - //let consumers propagate around the network - Thread.sleep(2000); - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); - sendMessages("BrokerB", dest, MESSAGE_COUNT); - sendMessages("BrokerC", dest, MESSAGE_COUNT); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - msgsA.waitForMessagesToArrive(MESSAGE_COUNT * 2); - msgsB.waitForMessagesToArrive(MESSAGE_COUNT); - msgsC.waitForMessagesToArrive(MESSAGE_COUNT * 2); - - assertEquals(MESSAGE_COUNT * 2, msgsA.getMessageCount()); - assertEquals(MESSAGE_COUNT, msgsB.getMessageCount()); - assertEquals(MESSAGE_COUNT * 2, msgsC.getMessageCount()); - } - - /** - * BrokerA -> BrokerB <- BrokerC - */ - public void testABandCBbrokerNetwork() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerA", "BrokerB"); - bridgeBrokers("BrokerC", "BrokerB"); - - startAllBrokers(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", true); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); - MessageConsumer clientB = createConsumer("BrokerB", dest); - MessageConsumer clientC = createConsumer("BrokerC", dest); - - //let consumers propagate around the network - Thread.sleep(2000); - - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); - sendMessages("BrokerB", dest, MESSAGE_COUNT); - sendMessages("BrokerC", dest, MESSAGE_COUNT); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - msgsA.waitForMessagesToArrive(MESSAGE_COUNT); - msgsB.waitForMessagesToArrive(MESSAGE_COUNT * 3); - msgsC.waitForMessagesToArrive(MESSAGE_COUNT); - - assertEquals(MESSAGE_COUNT, msgsA.getMessageCount()); - assertEquals(MESSAGE_COUNT * 3, msgsB.getMessageCount()); - assertEquals(MESSAGE_COUNT, msgsC.getMessageCount()); - } - - /** - * BrokerA <-> BrokerB <-> BrokerC - */ - public void testAllConnectedBrokerNetwork() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerA", "BrokerB"); - bridgeBrokers("BrokerB", "BrokerA"); - bridgeBrokers("BrokerB", "BrokerC"); - bridgeBrokers("BrokerC", "BrokerB"); - bridgeBrokers("BrokerA", "BrokerC"); - bridgeBrokers("BrokerC", "BrokerA"); - - startAllBrokers(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", true); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); - MessageConsumer clientB = createConsumer("BrokerB", dest); - MessageConsumer clientC = createConsumer("BrokerC", dest); - //let consumers propagate around the network - Thread.sleep(2000); - - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); - sendMessages("BrokerB", dest, MESSAGE_COUNT); - sendMessages("BrokerC", dest, MESSAGE_COUNT); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - msgsA.waitForMessagesToArrive(MESSAGE_COUNT * 3); - msgsB.waitForMessagesToArrive(MESSAGE_COUNT * 3); - msgsC.waitForMessagesToArrive(MESSAGE_COUNT * 3); - - assertEquals(MESSAGE_COUNT * 3, msgsA.getMessageCount()); - assertEquals(MESSAGE_COUNT * 3, msgsB.getMessageCount()); - assertEquals(MESSAGE_COUNT * 3, msgsC.getMessageCount()); - } - - public void testAllConnectedBrokerNetworkSingleProducerTTL() throws Exception { - - // duplicates are expected with ttl of 2 as each broker is connected to the next - // but the dups are suppressed by the store and now also by the topic sub when enableAudit - // default (true) is present in a matching destination policy entry - int networkTTL = 2; - boolean conduitSubs = true; - // Setup ring broker networks - bridgeBrokers("BrokerA", "BrokerB", dynamicOnly, networkTTL, conduitSubs); - bridgeBrokers("BrokerB", "BrokerA", dynamicOnly, networkTTL, conduitSubs); - bridgeBrokers("BrokerB", "BrokerC", dynamicOnly, networkTTL, conduitSubs); - bridgeBrokers("BrokerC", "BrokerB", dynamicOnly, networkTTL, conduitSubs); - bridgeBrokers("BrokerA", "BrokerC", dynamicOnly, networkTTL, conduitSubs); - bridgeBrokers("BrokerC", "BrokerA", dynamicOnly, networkTTL, conduitSubs); - - PolicyMap policyMap = new PolicyMap(); - // enable audit is on by default just need to give it matching policy entry - // so it will be applied to the topic subscription - policyMap.setDefaultEntry(new PolicyEntry()); - Collection brokerList = brokers.values(); - for (Iterator i = brokerList.iterator(); i.hasNext();) { - BrokerService broker = i.next().broker; - broker.setDestinationPolicy(policyMap); - broker.setDeleteAllMessagesOnStartup(true); - } - startAllBrokers(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", true); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); - MessageConsumer clientB = createConsumer("BrokerB", dest); - MessageConsumer clientC = createConsumer("BrokerC", dest); - //let consumers propagate around the network - Thread.sleep(2000); - - // Send messages - sendMessages("BrokerA", dest, 1); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - msgsA.waitForMessagesToArrive(1); - msgsB.waitForMessagesToArrive(1); - msgsC.waitForMessagesToArrive(1); - - // ensure we don't get any more messages - Thread.sleep(2000); - - assertEquals(1, msgsA.getMessageCount()); - assertEquals(1, msgsB.getMessageCount()); - assertEquals(1, msgsC.getMessageCount()); - } - - public void testAllConnectedBrokerNetworkDurableSubTTL() throws Exception { - int networkTTL = 2; - boolean conduitSubs = true; - // Setup ring broker network - bridgeBrokers("BrokerA", "BrokerB", dynamicOnly, networkTTL, conduitSubs); - bridgeBrokers("BrokerB", "BrokerA", dynamicOnly, networkTTL, conduitSubs); - bridgeBrokers("BrokerB", "BrokerC", dynamicOnly, networkTTL, conduitSubs); - bridgeBrokers("BrokerC", "BrokerB", dynamicOnly, networkTTL, conduitSubs); - bridgeBrokers("BrokerA", "BrokerC", dynamicOnly, networkTTL, conduitSubs); - bridgeBrokers("BrokerC", "BrokerA", dynamicOnly, networkTTL, conduitSubs); - - startAllBrokers(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", true); - - // Setup consumers - MessageConsumer clientA = createDurableSubscriber("BrokerA", (Topic)dest, "clientA"); - MessageConsumer clientB = createDurableSubscriber("BrokerB", (Topic)dest, "clientB"); - MessageConsumer clientC = createDurableSubscriber("BrokerC", (Topic)dest, "clientC"); - //let consumers propagate around the network - Thread.sleep(2000); - - // Send messages - sendMessages("BrokerA", dest, 1); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - msgsA.waitForMessagesToArrive(1); - msgsB.waitForMessagesToArrive(1); - msgsC.waitForMessagesToArrive(1); - - // ensure we don't get any more messages - Thread.sleep(2000); - - assertEquals(1, msgsA.getMessageCount()); - assertEquals(1, msgsB.getMessageCount()); - assertEquals(1, msgsC.getMessageCount()); - } - - /** - * BrokerA <-> BrokerB <-> BrokerC - */ - public void testAllConnectedUsingMulticast() throws Exception { - // Setup broker networks - bridgeAllBrokers(); - - startAllBrokers(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", true); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); - MessageConsumer clientB = createConsumer("BrokerB", dest); - MessageConsumer clientC = createConsumer("BrokerC", dest); - - //let consumers propagate around the network - Thread.sleep(2000); - - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); - sendMessages("BrokerB", dest, MESSAGE_COUNT); - sendMessages("BrokerC", dest, MESSAGE_COUNT); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - msgsA.waitForMessagesToArrive(MESSAGE_COUNT * 3); - msgsB.waitForMessagesToArrive(MESSAGE_COUNT * 3); - msgsC.waitForMessagesToArrive(MESSAGE_COUNT * 3); - - assertEquals(MESSAGE_COUNT * 3, msgsA.getMessageCount()); - assertEquals(MESSAGE_COUNT * 3, msgsB.getMessageCount()); - assertEquals(MESSAGE_COUNT * 3, msgsC.getMessageCount()); - } - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - String options = new String("?persistent=false&useJmx=false"); - createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA" + options)); - createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB" + options)); - createBroker(new URI("broker:(tcp://localhost:61618)/BrokerC" + options)); - } - - @Override - protected void configureBroker(BrokerService broker) { - broker.setBrokerId(broker.getBrokerName()); - } - - public static Test suite() { - return suite(ThreeBrokerTopicNetworkTest.class); - } + + protected static final int MESSAGE_COUNT = 100; + public boolean dynamicOnly; + + /** + * BrokerA -> BrokerB -> BrokerC + */ + public void testABandBCbrokerNetwork() throws Exception { + // Setup broker networks + bridgeBrokers("BrokerA", "BrokerB"); + bridgeBrokers("BrokerB", "BrokerC"); + + startAllBrokers(); + + // Setup destination + Destination dest = createDestination("TEST.FOO", true); + + // Setup consumers + MessageConsumer clientA = createConsumer("BrokerA", dest); + MessageConsumer clientB = createConsumer("BrokerB", dest); + MessageConsumer clientC = createConsumer("BrokerC", dest); + + //let consumers propagate around the network + Thread.sleep(2000); + // Send messages + sendMessages("BrokerA", dest, MESSAGE_COUNT); + sendMessages("BrokerB", dest, MESSAGE_COUNT); + sendMessages("BrokerC", dest, MESSAGE_COUNT); + + // Get message count + MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); + MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); + MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); + + msgsA.waitForMessagesToArrive(MESSAGE_COUNT); + msgsB.waitForMessagesToArrive(MESSAGE_COUNT * 2); + msgsC.waitForMessagesToArrive(MESSAGE_COUNT * 2); + + assertEquals(MESSAGE_COUNT, msgsA.getMessageCount()); + assertEquals(MESSAGE_COUNT * 2, msgsB.getMessageCount()); + assertEquals(MESSAGE_COUNT * 2, msgsC.getMessageCount()); + + assertEquals("Correct forwards from A", MESSAGE_COUNT, brokers.get("BrokerA").broker.getDestination(ActiveMQDestination.transform(dest)).getDestinationStatistics().getForwards().getCount()); + } + + public void initCombosForTestABandBCbrokerNetworkWithSelectors() { + addCombinationValues("dynamicOnly", new Object[]{true, false}); + } + + /** + * BrokerA -> BrokerB -> BrokerC + */ + public void testABandBCbrokerNetworkWithSelectors() throws Exception { + // Setup broker networks + bridgeBrokers("BrokerA", "BrokerB", dynamicOnly, 2, true); + bridgeBrokers("BrokerB", "BrokerC", dynamicOnly, 2, true); + + startAllBrokers(); + + // Setup destination + Destination dest = createDestination("TEST.FOO", true); + + // Setup consumers + MessageConsumer clientA = createConsumer("BrokerC", dest, "dummy = 33"); + MessageConsumer clientB = createConsumer("BrokerC", dest, "dummy > 30"); + MessageConsumer clientC = createConsumer("BrokerC", dest, "dummy = 34"); + + // let consumers propagate around the network + Thread.sleep(2000); + // Send messages + // Send messages for broker A + HashMap props = new HashMap(); + props.put("dummy", 33); + sendMessages("BrokerA", dest, MESSAGE_COUNT, props); + props.put("dummy", 34); + sendMessages("BrokerA", dest, MESSAGE_COUNT * 2, props); + + // Get message count + MessageIdList msgsA = getConsumerMessages("BrokerC", clientA); + MessageIdList msgsB = getConsumerMessages("BrokerC", clientB); + MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); + + msgsA.waitForMessagesToArrive(MESSAGE_COUNT); + msgsB.waitForMessagesToArrive(MESSAGE_COUNT * 3); + msgsC.waitForMessagesToArrive(MESSAGE_COUNT * 2); + + assertEquals(MESSAGE_COUNT, msgsA.getMessageCount()); + assertEquals(MESSAGE_COUNT * 3, msgsB.getMessageCount()); + assertEquals(MESSAGE_COUNT * 2, msgsC.getMessageCount()); + } + + /** + * BrokerA <- BrokerB -> BrokerC + */ + public void testBAandBCbrokerNetwork() throws Exception { + // Setup broker networks + bridgeBrokers("BrokerB", "BrokerA"); + bridgeBrokers("BrokerB", "BrokerC"); + + startAllBrokers(); + + // Setup destination + Destination dest = createDestination("TEST.FOO", true); + + // Setup consumers + MessageConsumer clientA = createConsumer("BrokerA", dest); + MessageConsumer clientB = createConsumer("BrokerB", dest); + MessageConsumer clientC = createConsumer("BrokerC", dest); + + //let consumers propagate around the network + Thread.sleep(2000); + // Send messages + sendMessages("BrokerA", dest, MESSAGE_COUNT); + sendMessages("BrokerB", dest, MESSAGE_COUNT); + sendMessages("BrokerC", dest, MESSAGE_COUNT); + + // Get message count + MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); + MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); + MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); + + msgsA.waitForMessagesToArrive(MESSAGE_COUNT * 2); + msgsB.waitForMessagesToArrive(MESSAGE_COUNT); + msgsC.waitForMessagesToArrive(MESSAGE_COUNT * 2); + + assertEquals(MESSAGE_COUNT * 2, msgsA.getMessageCount()); + assertEquals(MESSAGE_COUNT, msgsB.getMessageCount()); + assertEquals(MESSAGE_COUNT * 2, msgsC.getMessageCount()); + } + + /** + * BrokerA -> BrokerB <- BrokerC + */ + public void testABandCBbrokerNetwork() throws Exception { + // Setup broker networks + bridgeBrokers("BrokerA", "BrokerB"); + bridgeBrokers("BrokerC", "BrokerB"); + + startAllBrokers(); + + // Setup destination + Destination dest = createDestination("TEST.FOO", true); + + // Setup consumers + MessageConsumer clientA = createConsumer("BrokerA", dest); + MessageConsumer clientB = createConsumer("BrokerB", dest); + MessageConsumer clientC = createConsumer("BrokerC", dest); + + //let consumers propagate around the network + Thread.sleep(2000); + + // Send messages + sendMessages("BrokerA", dest, MESSAGE_COUNT); + sendMessages("BrokerB", dest, MESSAGE_COUNT); + sendMessages("BrokerC", dest, MESSAGE_COUNT); + + // Get message count + MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); + MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); + MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); + + msgsA.waitForMessagesToArrive(MESSAGE_COUNT); + msgsB.waitForMessagesToArrive(MESSAGE_COUNT * 3); + msgsC.waitForMessagesToArrive(MESSAGE_COUNT); + + assertEquals(MESSAGE_COUNT, msgsA.getMessageCount()); + assertEquals(MESSAGE_COUNT * 3, msgsB.getMessageCount()); + assertEquals(MESSAGE_COUNT, msgsC.getMessageCount()); + } + + /** + * BrokerA <-> BrokerB <-> BrokerC + */ + public void testAllConnectedBrokerNetwork() throws Exception { + // Setup broker networks + bridgeBrokers("BrokerA", "BrokerB"); + bridgeBrokers("BrokerB", "BrokerA"); + bridgeBrokers("BrokerB", "BrokerC"); + bridgeBrokers("BrokerC", "BrokerB"); + bridgeBrokers("BrokerA", "BrokerC"); + bridgeBrokers("BrokerC", "BrokerA"); + + startAllBrokers(); + + // Setup destination + Destination dest = createDestination("TEST.FOO", true); + + // Setup consumers + MessageConsumer clientA = createConsumer("BrokerA", dest); + MessageConsumer clientB = createConsumer("BrokerB", dest); + MessageConsumer clientC = createConsumer("BrokerC", dest); + //let consumers propagate around the network + Thread.sleep(2000); + + // Send messages + sendMessages("BrokerA", dest, MESSAGE_COUNT); + sendMessages("BrokerB", dest, MESSAGE_COUNT); + sendMessages("BrokerC", dest, MESSAGE_COUNT); + + // Get message count + MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); + MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); + MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); + + msgsA.waitForMessagesToArrive(MESSAGE_COUNT * 3); + msgsB.waitForMessagesToArrive(MESSAGE_COUNT * 3); + msgsC.waitForMessagesToArrive(MESSAGE_COUNT * 3); + + assertEquals(MESSAGE_COUNT * 3, msgsA.getMessageCount()); + assertEquals(MESSAGE_COUNT * 3, msgsB.getMessageCount()); + assertEquals(MESSAGE_COUNT * 3, msgsC.getMessageCount()); + } + + public void testAllConnectedBrokerNetworkSingleProducerTTL() throws Exception { + + // duplicates are expected with ttl of 2 as each broker is connected to the next + // but the dups are suppressed by the store and now also by the topic sub when enableAudit + // default (true) is present in a matching destination policy entry + int networkTTL = 2; + boolean conduitSubs = true; + // Setup ring broker networks + bridgeBrokers("BrokerA", "BrokerB", dynamicOnly, networkTTL, conduitSubs); + bridgeBrokers("BrokerB", "BrokerA", dynamicOnly, networkTTL, conduitSubs); + bridgeBrokers("BrokerB", "BrokerC", dynamicOnly, networkTTL, conduitSubs); + bridgeBrokers("BrokerC", "BrokerB", dynamicOnly, networkTTL, conduitSubs); + bridgeBrokers("BrokerA", "BrokerC", dynamicOnly, networkTTL, conduitSubs); + bridgeBrokers("BrokerC", "BrokerA", dynamicOnly, networkTTL, conduitSubs); + + PolicyMap policyMap = new PolicyMap(); + // enable audit is on by default just need to give it matching policy entry + // so it will be applied to the topic subscription + policyMap.setDefaultEntry(new PolicyEntry()); + Collection brokerList = brokers.values(); + for (Iterator i = brokerList.iterator(); i.hasNext(); ) { + BrokerService broker = i.next().broker; + broker.setDestinationPolicy(policyMap); + broker.setDeleteAllMessagesOnStartup(true); + } + startAllBrokers(); + + // Setup destination + Destination dest = createDestination("TEST.FOO", true); + + // Setup consumers + MessageConsumer clientA = createConsumer("BrokerA", dest); + MessageConsumer clientB = createConsumer("BrokerB", dest); + MessageConsumer clientC = createConsumer("BrokerC", dest); + //let consumers propagate around the network + Thread.sleep(2000); + + // Send messages + sendMessages("BrokerA", dest, 1); + + // Get message count + MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); + MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); + MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); + + msgsA.waitForMessagesToArrive(1); + msgsB.waitForMessagesToArrive(1); + msgsC.waitForMessagesToArrive(1); + + // ensure we don't get any more messages + Thread.sleep(2000); + + assertEquals(1, msgsA.getMessageCount()); + assertEquals(1, msgsB.getMessageCount()); + assertEquals(1, msgsC.getMessageCount()); + } + + public void testAllConnectedBrokerNetworkDurableSubTTL() throws Exception { + int networkTTL = 2; + boolean conduitSubs = true; + // Setup ring broker network + bridgeBrokers("BrokerA", "BrokerB", dynamicOnly, networkTTL, conduitSubs); + bridgeBrokers("BrokerB", "BrokerA", dynamicOnly, networkTTL, conduitSubs); + bridgeBrokers("BrokerB", "BrokerC", dynamicOnly, networkTTL, conduitSubs); + bridgeBrokers("BrokerC", "BrokerB", dynamicOnly, networkTTL, conduitSubs); + bridgeBrokers("BrokerA", "BrokerC", dynamicOnly, networkTTL, conduitSubs); + bridgeBrokers("BrokerC", "BrokerA", dynamicOnly, networkTTL, conduitSubs); + + startAllBrokers(); + + // Setup destination + Destination dest = createDestination("TEST.FOO", true); + + // Setup consumers + MessageConsumer clientA = createDurableSubscriber("BrokerA", (Topic) dest, "clientA"); + MessageConsumer clientB = createDurableSubscriber("BrokerB", (Topic) dest, "clientB"); + MessageConsumer clientC = createDurableSubscriber("BrokerC", (Topic) dest, "clientC"); + //let consumers propagate around the network + Thread.sleep(2000); + + // Send messages + sendMessages("BrokerA", dest, 1); + + // Get message count + MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); + MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); + MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); + + msgsA.waitForMessagesToArrive(1); + msgsB.waitForMessagesToArrive(1); + msgsC.waitForMessagesToArrive(1); + + // ensure we don't get any more messages + Thread.sleep(2000); + + assertEquals(1, msgsA.getMessageCount()); + assertEquals(1, msgsB.getMessageCount()); + assertEquals(1, msgsC.getMessageCount()); + } + + /** + * BrokerA <-> BrokerB <-> BrokerC + */ + public void testAllConnectedUsingMulticast() throws Exception { + // Setup broker networks + bridgeAllBrokers(); + + startAllBrokers(); + + // Setup destination + Destination dest = createDestination("TEST.FOO", true); + + // Setup consumers + MessageConsumer clientA = createConsumer("BrokerA", dest); + MessageConsumer clientB = createConsumer("BrokerB", dest); + MessageConsumer clientC = createConsumer("BrokerC", dest); + + //let consumers propagate around the network + Thread.sleep(2000); + + // Send messages + sendMessages("BrokerA", dest, MESSAGE_COUNT); + sendMessages("BrokerB", dest, MESSAGE_COUNT); + sendMessages("BrokerC", dest, MESSAGE_COUNT); + + // Get message count + MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); + MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); + MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); + + msgsA.waitForMessagesToArrive(MESSAGE_COUNT * 3); + msgsB.waitForMessagesToArrive(MESSAGE_COUNT * 3); + msgsC.waitForMessagesToArrive(MESSAGE_COUNT * 3); + + assertEquals(MESSAGE_COUNT * 3, msgsA.getMessageCount()); + assertEquals(MESSAGE_COUNT * 3, msgsB.getMessageCount()); + assertEquals(MESSAGE_COUNT * 3, msgsC.getMessageCount()); + } + + @Override + public void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); + String options = new String("?persistent=false&useJmx=false"); + createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA" + options)); + createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB" + options)); + createBroker(new URI("broker:(tcp://localhost:61618)/BrokerC" + options)); + } + + @Override + protected void configureBroker(BrokerService broker) { + broker.setBrokerId(broker.getBrokerName()); + } + + public static Test suite() { + return suite(ThreeBrokerTopicNetworkTest.class); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTopicNetworkUsingTcpTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTopicNetworkUsingTcpTest.java index 6e50b6ecb0..110b8806d2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTopicNetworkUsingTcpTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTopicNetworkUsingTcpTest.java @@ -30,41 +30,44 @@ import org.apache.activemq.transport.TransportFactory; * */ public class ThreeBrokerTopicNetworkUsingTcpTest extends ThreeBrokerTopicNetworkTest { - protected List bridges; - protected void bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker) throws Exception { - List remoteTransports = remoteBroker.getTransportConnectors(); - List localTransports = localBroker.getTransportConnectors(); + protected List bridges; - URI remoteURI; - URI localURI; - if (!remoteTransports.isEmpty() && !localTransports.isEmpty()) { - remoteURI = remoteTransports.get(0).getConnectUri(); - localURI = localTransports.get(0).getConnectUri(); + protected void bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker) throws Exception { + List remoteTransports = remoteBroker.getTransportConnectors(); + List localTransports = localBroker.getTransportConnectors(); - // Ensure that we are connecting using tcp - if (remoteURI.toString().startsWith("tcp:") && localURI.toString().startsWith("tcp:")) { - NetworkBridgeConfiguration config = new NetworkBridgeConfiguration(); - config.setBrokerName(localBroker.getBrokerName()); - DemandForwardingBridge bridge = new DemandForwardingBridge(config, TransportFactory.connect(localURI), TransportFactory.connect(remoteURI)); - bridge.setBrokerService(localBroker); - bridges.add(bridge); + URI remoteURI; + URI localURI; + if (!remoteTransports.isEmpty() && !localTransports.isEmpty()) { + remoteURI = remoteTransports.get(0).getConnectUri(); + localURI = localTransports.get(0).getConnectUri(); - bridge.start(); - } else { - throw new Exception("Remote broker or local broker is not using tcp connectors"); - } - } else { - throw new Exception("Remote broker or local broker has no registered connectors."); - } + // Ensure that we are connecting using tcp + if (remoteURI.toString().startsWith("tcp:") && localURI.toString().startsWith("tcp:")) { + NetworkBridgeConfiguration config = new NetworkBridgeConfiguration(); + config.setBrokerName(localBroker.getBrokerName()); + DemandForwardingBridge bridge = new DemandForwardingBridge(config, TransportFactory.connect(localURI), TransportFactory.connect(remoteURI)); + bridge.setBrokerService(localBroker); + bridges.add(bridge); - maxSetupTime = 2000; - } + bridge.start(); + } + else { + throw new Exception("Remote broker or local broker is not using tcp connectors"); + } + } + else { + throw new Exception("Remote broker or local broker has no registered connectors."); + } - @Override - public void setUp() throws Exception { - super.setUp(); + maxSetupTime = 2000; + } - bridges = new ArrayList(); - } + @Override + public void setUp() throws Exception { + super.setUp(); + + bridges = new ArrayList(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerVirtualTopicNetworkLevelDBTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerVirtualTopicNetworkLevelDBTest.java index a9f5955b28..0a2de634f1 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerVirtualTopicNetworkLevelDBTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerVirtualTopicNetworkLevelDBTest.java @@ -22,13 +22,12 @@ import java.io.IOException; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.leveldb.LevelDBStore; - public class ThreeBrokerVirtualTopicNetworkLevelDBTest extends ThreeBrokerVirtualTopicNetworkTest { - - protected void configurePersistenceAdapter(BrokerService broker) throws IOException { - File dataFileDir = new File("target/test-data/leveldb/" + broker.getBrokerName()); - LevelDBStore adapter = new LevelDBStore(); - adapter.setDirectory(dataFileDir); - broker.setPersistenceAdapter(adapter); - } + + protected void configurePersistenceAdapter(BrokerService broker) throws IOException { + File dataFileDir = new File("target/test-data/leveldb/" + broker.getBrokerName()); + LevelDBStore adapter = new LevelDBStore(); + adapter.setDirectory(dataFileDir); + broker.setPersistenceAdapter(adapter); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerVirtualTopicNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerVirtualTopicNetworkTest.java index a8e8f5046d..9427bd4193 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerVirtualTopicNetworkTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerVirtualTopicNetworkTest.java @@ -35,152 +35,154 @@ import org.apache.activemq.util.MessageIdList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - public class ThreeBrokerVirtualTopicNetworkTest extends JmsMultipleBrokersTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(ThreeBrokerVirtualTopicNetworkTest.class); - protected static final int MESSAGE_COUNT = 1; - public boolean dynamicOnly = false; - - public void testNetworkVirtualTopic() throws Exception { - int networkTTL = 6; - boolean conduitSubs = true; - // Setup broker networks - bridgeAndConfigureBrokers("BrokerA", "BrokerB", dynamicOnly, networkTTL, conduitSubs); - bridgeAndConfigureBrokers("BrokerA", "BrokerC", dynamicOnly, networkTTL, conduitSubs); - bridgeAndConfigureBrokers("BrokerB", "BrokerA", dynamicOnly, networkTTL, conduitSubs); - bridgeAndConfigureBrokers("BrokerB", "BrokerC", dynamicOnly, networkTTL, conduitSubs); - bridgeAndConfigureBrokers("BrokerC", "BrokerA", dynamicOnly, networkTTL, conduitSubs); - bridgeAndConfigureBrokers("BrokerC", "BrokerB", dynamicOnly, networkTTL, conduitSubs); + private static final Logger LOG = LoggerFactory.getLogger(ThreeBrokerVirtualTopicNetworkTest.class); + protected static final int MESSAGE_COUNT = 1; + public boolean dynamicOnly = false; - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", true); + public void testNetworkVirtualTopic() throws Exception { + int networkTTL = 6; + boolean conduitSubs = true; + // Setup broker networks + bridgeAndConfigureBrokers("BrokerA", "BrokerB", dynamicOnly, networkTTL, conduitSubs); + bridgeAndConfigureBrokers("BrokerA", "BrokerC", dynamicOnly, networkTTL, conduitSubs); + bridgeAndConfigureBrokers("BrokerB", "BrokerA", dynamicOnly, networkTTL, conduitSubs); + bridgeAndConfigureBrokers("BrokerB", "BrokerC", dynamicOnly, networkTTL, conduitSubs); + bridgeAndConfigureBrokers("BrokerC", "BrokerA", dynamicOnly, networkTTL, conduitSubs); + bridgeAndConfigureBrokers("BrokerC", "BrokerB", dynamicOnly, networkTTL, conduitSubs); - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", createDestination("Consumer.A.TEST.FOO", false)); - MessageConsumer clientB = createConsumer("BrokerB", createDestination("Consumer.B.TEST.FOO", false)); - MessageConsumer clientC = createConsumer("BrokerC", createDestination("Consumer.C.TEST.FOO", false)); - - Thread.sleep(2000); + startAllBrokers(); + waitForBridgeFormation(); - // Send messages - sendMessages("BrokerA", dest, 1); + // Setup destination + Destination dest = createDestination("TEST.FOO", true); - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); + // Setup consumers + MessageConsumer clientA = createConsumer("BrokerA", createDestination("Consumer.A.TEST.FOO", false)); + MessageConsumer clientB = createConsumer("BrokerB", createDestination("Consumer.B.TEST.FOO", false)); + MessageConsumer clientC = createConsumer("BrokerC", createDestination("Consumer.C.TEST.FOO", false)); - msgsA.waitForMessagesToArrive(1); - msgsB.waitForMessagesToArrive(1); - msgsC.waitForMessagesToArrive(1); + Thread.sleep(2000); - // ensure we don't get any more messages - Thread.sleep(2000); - - assertEquals(1, msgsA.getMessageCount()); - assertEquals(1, msgsB.getMessageCount()); - assertEquals(1, msgsC.getMessageCount()); - - // restart to ensure no hanging messages - LOG.info("Restarting brokerA"); - BrokerItem brokerItem = brokers.remove("BrokerA"); - if (brokerItem != null) { - brokerItem.destroy(); - } - - BrokerService restartedBroker = createAndConfigureBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?useJmx=false")); - bridgeAndConfigureBrokers("BrokerA", "BrokerB", dynamicOnly, networkTTL, conduitSubs); - bridgeAndConfigureBrokers("BrokerA", "BrokerC", dynamicOnly, networkTTL, conduitSubs); - restartedBroker.start(); - waitForBridgeFormation(); - - clientA = createConsumer("BrokerA", createDestination("Consumer.A.TEST.FOO", false)); - LOG.info("recreated clientA"); - - Thread.sleep(2000); + // Send messages + sendMessages("BrokerA", dest, 1); - sendMessages("BrokerA", dest, 10); + // Get message count + MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); + MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); + MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - msgsA = getConsumerMessages("BrokerA", clientA); + msgsA.waitForMessagesToArrive(1); + msgsB.waitForMessagesToArrive(1); + msgsC.waitForMessagesToArrive(1); - msgsA.waitForMessagesToArrive(10); - msgsB.waitForMessagesToArrive(11); - msgsC.waitForMessagesToArrive(11); + // ensure we don't get any more messages + Thread.sleep(2000); - // ensure we don't get any more messages - Thread.sleep(2000); - - LOG.info("MessagesA: " + msgsA.getMessageIds()); - assertEquals(10, msgsA.getMessageCount()); - assertEquals(11, msgsB.getMessageCount()); - assertEquals(11, msgsC.getMessageCount()); - - // restart to ensure no hanging messages - LOG.info("Restarting brokerA again"); - brokerItem = brokers.remove("BrokerA"); - if (brokerItem != null) { - brokerItem.destroy(); - } - - restartedBroker = createAndConfigureBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?useJmx=false")); - bridgeAndConfigureBrokers("BrokerA", "BrokerB", dynamicOnly, networkTTL, conduitSubs); - bridgeAndConfigureBrokers("BrokerA", "BrokerC", dynamicOnly, networkTTL, conduitSubs); - restartedBroker.start(); - waitForBridgeFormation(); - - clientA = createConsumer("BrokerA", createDestination("Consumer.A.TEST.FOO", false)); - LOG.info("recreated clientA again"); - - Thread.sleep(2000); + assertEquals(1, msgsA.getMessageCount()); + assertEquals(1, msgsB.getMessageCount()); + assertEquals(1, msgsC.getMessageCount()); - msgsA = getConsumerMessages("BrokerA", clientA); + // restart to ensure no hanging messages + LOG.info("Restarting brokerA"); + BrokerItem brokerItem = brokers.remove("BrokerA"); + if (brokerItem != null) { + brokerItem.destroy(); + } - // ensure we don't get any more messages - Thread.sleep(5000); - - LOG.info("Extra MessagesA: " + msgsA.getMessageIds()); - assertEquals(0, msgsA.getMessageCount()); - assertEquals(11, msgsB.getMessageCount()); - assertEquals(11, msgsC.getMessageCount()); - } - + BrokerService restartedBroker = createAndConfigureBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?useJmx=false")); + bridgeAndConfigureBrokers("BrokerA", "BrokerB", dynamicOnly, networkTTL, conduitSubs); + bridgeAndConfigureBrokers("BrokerA", "BrokerC", dynamicOnly, networkTTL, conduitSubs); + restartedBroker.start(); + waitForBridgeFormation(); - private void bridgeAndConfigureBrokers(String local, String remote, boolean dynamicOnly, int networkTTL, boolean conduitSubs) throws Exception { - NetworkConnector bridge = bridgeBrokers(local, remote, dynamicOnly, networkTTL, conduitSubs); - bridge.setDecreaseNetworkConsumerPriority(true); - } + clientA = createConsumer("BrokerA", createDestination("Consumer.A.TEST.FOO", false)); + LOG.info("recreated clientA"); - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - String options = new String("?useJmx=false&deleteAllMessagesOnStartup=true"); - createAndConfigureBroker(new URI("broker:(tcp://localhost:61616)/BrokerA" + options)); - createAndConfigureBroker(new URI("broker:(tcp://localhost:61617)/BrokerB" + options)); - createAndConfigureBroker(new URI("broker:(tcp://localhost:61618)/BrokerC" + options)); - } - - private BrokerService createAndConfigureBroker(URI uri) throws Exception { - BrokerService broker = createBroker(uri); - - configurePersistenceAdapter(broker); - - // make all topics virtual and consumers use the default prefix - VirtualDestinationInterceptor virtualDestinationInterceptor = new VirtualDestinationInterceptor(); - virtualDestinationInterceptor.setVirtualDestinations(new VirtualDestination[]{new VirtualTopic()}); - DestinationInterceptor[] destinationInterceptors = new DestinationInterceptor[]{virtualDestinationInterceptor}; - broker.setDestinationInterceptors(destinationInterceptors); - return broker; - } - - protected void configurePersistenceAdapter(BrokerService broker) throws IOException { - File dataFileDir = new File("target/test-amq-data/kahadb/" + broker.getBrokerName()); - KahaDBStore kaha = new KahaDBStore(); - kaha.setDirectory(dataFileDir); - broker.setPersistenceAdapter(kaha); - } + Thread.sleep(2000); + + sendMessages("BrokerA", dest, 10); + + msgsA = getConsumerMessages("BrokerA", clientA); + + msgsA.waitForMessagesToArrive(10); + msgsB.waitForMessagesToArrive(11); + msgsC.waitForMessagesToArrive(11); + + // ensure we don't get any more messages + Thread.sleep(2000); + + LOG.info("MessagesA: " + msgsA.getMessageIds()); + assertEquals(10, msgsA.getMessageCount()); + assertEquals(11, msgsB.getMessageCount()); + assertEquals(11, msgsC.getMessageCount()); + + // restart to ensure no hanging messages + LOG.info("Restarting brokerA again"); + brokerItem = brokers.remove("BrokerA"); + if (brokerItem != null) { + brokerItem.destroy(); + } + + restartedBroker = createAndConfigureBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?useJmx=false")); + bridgeAndConfigureBrokers("BrokerA", "BrokerB", dynamicOnly, networkTTL, conduitSubs); + bridgeAndConfigureBrokers("BrokerA", "BrokerC", dynamicOnly, networkTTL, conduitSubs); + restartedBroker.start(); + waitForBridgeFormation(); + + clientA = createConsumer("BrokerA", createDestination("Consumer.A.TEST.FOO", false)); + LOG.info("recreated clientA again"); + + Thread.sleep(2000); + + msgsA = getConsumerMessages("BrokerA", clientA); + + // ensure we don't get any more messages + Thread.sleep(5000); + + LOG.info("Extra MessagesA: " + msgsA.getMessageIds()); + assertEquals(0, msgsA.getMessageCount()); + assertEquals(11, msgsB.getMessageCount()); + assertEquals(11, msgsC.getMessageCount()); + } + + private void bridgeAndConfigureBrokers(String local, + String remote, + boolean dynamicOnly, + int networkTTL, + boolean conduitSubs) throws Exception { + NetworkConnector bridge = bridgeBrokers(local, remote, dynamicOnly, networkTTL, conduitSubs); + bridge.setDecreaseNetworkConsumerPriority(true); + } + + public void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); + String options = new String("?useJmx=false&deleteAllMessagesOnStartup=true"); + createAndConfigureBroker(new URI("broker:(tcp://localhost:61616)/BrokerA" + options)); + createAndConfigureBroker(new URI("broker:(tcp://localhost:61617)/BrokerB" + options)); + createAndConfigureBroker(new URI("broker:(tcp://localhost:61618)/BrokerC" + options)); + } + + private BrokerService createAndConfigureBroker(URI uri) throws Exception { + BrokerService broker = createBroker(uri); + + configurePersistenceAdapter(broker); + + // make all topics virtual and consumers use the default prefix + VirtualDestinationInterceptor virtualDestinationInterceptor = new VirtualDestinationInterceptor(); + virtualDestinationInterceptor.setVirtualDestinations(new VirtualDestination[]{new VirtualTopic()}); + DestinationInterceptor[] destinationInterceptors = new DestinationInterceptor[]{virtualDestinationInterceptor}; + broker.setDestinationInterceptors(destinationInterceptors); + return broker; + } + + protected void configurePersistenceAdapter(BrokerService broker) throws IOException { + File dataFileDir = new File("target/test-amq-data/kahadb/" + broker.getBrokerName()); + KahaDBStore kaha = new KahaDBStore(); + kaha.setDirectory(dataFileDir); + broker.setPersistenceAdapter(kaha); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicDurableConnectStatsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicDurableConnectStatsTest.java index 3612fdded1..2384aa6e42 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicDurableConnectStatsTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicDurableConnectStatsTest.java @@ -49,225 +49,226 @@ import org.slf4j.LoggerFactory; public class TopicDurableConnectStatsTest extends org.apache.activemq.TestSupport { - private static final Logger LOG = LoggerFactory.getLogger(TopicDurableConnectStatsTest.class); - private BrokerService broker; - private ActiveMQTopic topic; - private final Vector exceptions = new Vector(); - private final int messageSize = 4000; - protected MBeanServerConnection mbeanServer; - protected String domain = "org.apache.activemq"; - private ActiveMQConnectionFactory connectionFactory = null; - final int numMessages = 20; + private static final Logger LOG = LoggerFactory.getLogger(TopicDurableConnectStatsTest.class); + private BrokerService broker; + private ActiveMQTopic topic; + private final Vector exceptions = new Vector(); + private final int messageSize = 4000; + protected MBeanServerConnection mbeanServer; + protected String domain = "org.apache.activemq"; + private ActiveMQConnectionFactory connectionFactory = null; + final int numMessages = 20; - private static Session session2 = null; + private static Session session2 = null; - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { + @Override + protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - connectionFactory = new ActiveMQConnectionFactory("vm://" + getName(true)); + connectionFactory = new ActiveMQConnectionFactory("vm://" + getName(true)); - ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); - prefetchPolicy.setAll(10); - connectionFactory.setPrefetchPolicy(prefetchPolicy); + ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); + prefetchPolicy.setAll(10); + connectionFactory.setPrefetchPolicy(prefetchPolicy); - connectionFactory.setWatchTopicAdvisories(false); - return connectionFactory; - } + connectionFactory.setWatchTopicAdvisories(false); + return connectionFactory; + } - @Override - protected Connection createConnection() throws Exception { - return createConnection("cliName"); - } + @Override + protected Connection createConnection() throws Exception { + return createConnection("cliName"); + } - protected Connection createConnection(String name) throws Exception { - Connection con = super.createConnection(); - con.setClientID(name); - con.start(); - return con; - } + protected Connection createConnection(String name) throws Exception { + Connection con = super.createConnection(); + con.setClientID(name); + con.start(); + return con; + } - public static Test suite() { - return suite(TopicDurableConnectStatsTest.class); - } + public static Test suite() { + return suite(TopicDurableConnectStatsTest.class); + } - @Override - protected void setUp() throws Exception { - exceptions.clear(); - topic = (ActiveMQTopic) createDestination(); + @Override + protected void setUp() throws Exception { + exceptions.clear(); + topic = (ActiveMQTopic) createDestination(); - createBroker(); - mbeanServer = ManagementFactory.getPlatformMBeanServer(); - super.setUp(); - } + createBroker(); + mbeanServer = ManagementFactory.getPlatformMBeanServer(); + super.setUp(); + } - @Override - protected void tearDown() throws Exception { - super.tearDown(); - destroyBroker(); - } + @Override + protected void tearDown() throws Exception { + super.tearDown(); + destroyBroker(); + } - private void createBroker() throws Exception { - createBroker(true); - } + private void createBroker() throws Exception { + createBroker(true); + } - private void createBroker(boolean deleteAllMessages) throws Exception { - broker = BrokerFactory.createBroker("broker:(vm://" + getName(true) + ")"); - broker.setBrokerName(getName(true)); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - broker.setAdvisorySupport(false); - broker.addConnector("tcp://0.0.0.0:0"); + private void createBroker(boolean deleteAllMessages) throws Exception { + broker = BrokerFactory.createBroker("broker:(vm://" + getName(true) + ")"); + broker.setBrokerName(getName(true)); + broker.setDeleteAllMessagesOnStartup(deleteAllMessages); + broker.setAdvisorySupport(false); + broker.addConnector("tcp://0.0.0.0:0"); - setDefaultPersistenceAdapter(broker); - broker.start(); - } + setDefaultPersistenceAdapter(broker); + broker.start(); + } - private void destroyBroker() throws Exception { - if (broker != null) - broker.stop(); - } + private void destroyBroker() throws Exception { + if (broker != null) + broker.stop(); + } - protected ObjectName assertRegisteredObjectName(String name) throws MalformedObjectNameException, NullPointerException { - ObjectName objectName = new ObjectName(name); + protected ObjectName assertRegisteredObjectName(String name) throws MalformedObjectNameException, NullPointerException { + ObjectName objectName = new ObjectName(name); - LOG.info("** Looking for " + name); - try { - if (mbeanServer.isRegistered(objectName)) { - LOG.info("Bean Registered: " + objectName); - } else { - LOG.info("Couldn't find Mbean! " + objectName); + LOG.info("** Looking for " + name); + try { + if (mbeanServer.isRegistered(objectName)) { + LOG.info("Bean Registered: " + objectName); + } + else { + LOG.info("Couldn't find Mbean! " + objectName); + } + } + catch (IOException e) { + e.printStackTrace(); + } + return objectName; + } + + public void testPendingTopicStat() throws Exception { + + Connection consumerCon = createConnection("cliId1"); + Session consumerSession = consumerCon.createSession(true, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer1 = consumerSession.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + assertNotNull(consumer1); + + DurableSubscriptionViewMBean subscriber1 = null; + + ObjectName query = new ObjectName(domain + ":type=Broker,brokerName=" + getName(true) + ",destinationType=Topic,destinationName=" + topic.getTopicName() + ",endpoint=Consumer,clientId=cliId1,consumerId=*"); + + java.util.Set set = mbeanServer.queryNames(query, null); + + ObjectName subscriberObjName1 = set.iterator().next(); + subscriber1 = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, subscriberObjName1, DurableSubscriptionViewMBean.class, true); + + LOG.info("Beginning Pending Queue Size count: " + subscriber1.getPendingQueueSize()); + LOG.info("Prefetch Limit: " + subscriber1.getPrefetchSize()); + + assertEquals("no pending", 0, subscriber1.getPendingQueueSize()); + assertEquals("Prefetch Limit ", 10, subscriber1.getPrefetchSize()); + + Connection producerCon = createConnection("x"); + Session producerSessions = producerCon.createSession(true, Session.AUTO_ACKNOWLEDGE); + + MessageProducer producer = producerSessions.createProducer(topic); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + + int i = 0; + for (; i < numMessages; i++) { + + if (i == 15) { + // kill consumer + + LOG.info("Killing consumer at 15"); + consumerSession.close(); + consumerCon.close(); + } + + TextMessage message = producerSessions.createTextMessage(createMessageText(i)); + message.setJMSExpiration(0); + message.setStringProperty("filter", "true"); + producer.send(topic, message); + producerSessions.commit(); + + } + LOG.info("Sent " + i + " messages in total"); + producerCon.close(); + + LOG.info("Pending Queue Size count: " + subscriber1.getPendingQueueSize()); + assertEquals("pending as expected", 20, subscriber1.getPendingQueueSize()); + + LOG.info("Re-connect client and consume messages"); + Connection con2 = createConnection("cliId1"); + session2 = con2.createSession(true, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer2 = session2.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); + + final Listener listener = new Listener(); + consumer2.setMessageListener(listener); + + assertTrue("received all sent", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return numMessages == listener.count; + } + })); + + LOG.info("Received: " + listener.count); + + int pq = subscriber1.getPendingQueueSize(); + LOG.info("Pending Queue Size count: " + pq); + assertEquals("Pending queue after consumed", 0, pq); + + session2.close(); + con2.close(); + LOG.info("FINAL Pending Queue Size count (after consumer close): " + subscriber1.getPendingQueueSize()); + } + + private String createMessageText(int index) { + StringBuffer buffer = new StringBuffer(messageSize); + buffer.append("Message: " + index + " sent at: " + new Date()); + if (buffer.length() > messageSize) { + return buffer.substring(0, messageSize); + } + for (int i = buffer.length(); i < messageSize; i++) { + buffer.append(' '); + } + return buffer.toString(); + } + + public static class Listener implements MessageListener { + + int count = 0; + String id = null; + + Listener() { + } + + @Override + public void onMessage(Message message) { + count++; + try { + session2.commit(); + } + catch (JMSException e1) { + e1.printStackTrace(); + } + + if (id != null) { + try { + LOG.info(id + ", " + message.getJMSMessageID()); } - } catch (IOException e) { + catch (Exception ignored) { + } + } + + try { + Thread.sleep(2); + } + catch (InterruptedException e) { e.printStackTrace(); - } - return objectName; - } - - public void testPendingTopicStat() throws Exception { - - Connection consumerCon = createConnection("cliId1"); - Session consumerSession = consumerCon.createSession(true, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer1 = consumerSession.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - assertNotNull(consumer1); - - DurableSubscriptionViewMBean subscriber1 = null; - - ObjectName query = new ObjectName(domain + ":type=Broker,brokerName=" + getName(true) + ",destinationType=Topic,destinationName=" + topic.getTopicName() + ",endpoint=Consumer,clientId=cliId1,consumerId=*"); - - java.util.Setset = mbeanServer.queryNames(query,null); - - ObjectName subscriberObjName1 = set.iterator().next(); - subscriber1 = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, subscriberObjName1, DurableSubscriptionViewMBean.class, true); - - LOG.info("Beginning Pending Queue Size count: " + subscriber1.getPendingQueueSize()); - LOG.info("Prefetch Limit: " + subscriber1.getPrefetchSize()); - - assertEquals("no pending", 0, subscriber1.getPendingQueueSize()); - assertEquals("Prefetch Limit ", 10, subscriber1.getPrefetchSize()); - - - Connection producerCon = createConnection("x"); - Session producerSessions = producerCon.createSession(true, Session.AUTO_ACKNOWLEDGE); - - - MessageProducer producer = producerSessions.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - - int i = 0; - for (; i < numMessages; i++) { - - if (i == 15) { - // kill consumer - - LOG.info("Killing consumer at 15"); - consumerSession.close(); - consumerCon.close(); - } - - TextMessage message = producerSessions.createTextMessage(createMessageText(i)); - message.setJMSExpiration(0); - message.setStringProperty("filter", "true"); - producer.send(topic, message); - producerSessions.commit(); - - } - LOG.info("Sent " + i + " messages in total"); - producerCon.close(); - - LOG.info("Pending Queue Size count: " + subscriber1.getPendingQueueSize()); - assertEquals("pending as expected", 20, subscriber1.getPendingQueueSize()); - - LOG.info("Re-connect client and consume messages"); - Connection con2 = createConnection("cliId1"); - session2 = con2.createSession(true, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer2 = session2.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - - - final Listener listener = new Listener(); - consumer2.setMessageListener(listener); - - assertTrue("received all sent", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return numMessages == listener.count; - } - })); - - LOG.info("Received: " + listener.count); - - int pq = subscriber1.getPendingQueueSize(); - LOG.info("Pending Queue Size count: " + pq); - assertEquals("Pending queue after consumed", 0, pq); - - session2.close(); - con2.close(); - LOG.info("FINAL Pending Queue Size count (after consumer close): " + subscriber1.getPendingQueueSize()); - } - - - private String createMessageText(int index) { - StringBuffer buffer = new StringBuffer(messageSize); - buffer.append("Message: " + index + " sent at: " + new Date()); - if (buffer.length() > messageSize) { - return buffer.substring(0, messageSize); - } - for (int i = buffer.length(); i < messageSize; i++) { - buffer.append(' '); - } - return buffer.toString(); - } - - - public static class Listener implements MessageListener { - int count = 0; - String id = null; - - Listener() { - } - - @Override - public void onMessage(Message message) { - count++; - try { - session2.commit(); - } catch (JMSException e1) { - e1.printStackTrace(); - } - - if (id != null) { - try { - LOG.info(id + ", " + message.getJMSMessageID()); - } catch (Exception ignored) { - } - } - - try { - Thread.sleep(2); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicProducerFlowControlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicProducerFlowControlTest.java index 9ea1446e41..2af86b9efc 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicProducerFlowControlTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicProducerFlowControlTest.java @@ -41,149 +41,154 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TopicProducerFlowControlTest extends TestCase implements MessageListener { - private static final Logger LOG = LoggerFactory.getLogger(TopicProducerFlowControlTest.class); - private static final String brokerName = "testBroker"; - private static final String brokerUrl = "vm://" + brokerName; - protected static final int destinationMemLimit = 2097152; // 2MB - private static final AtomicLong produced = new AtomicLong(); - private static final AtomicLong consumed = new AtomicLong(); - private static final int numMessagesToSend = 50000; - private BrokerService broker; + private static final Logger LOG = LoggerFactory.getLogger(TopicProducerFlowControlTest.class); + private static final String brokerName = "testBroker"; + private static final String brokerUrl = "vm://" + brokerName; + protected static final int destinationMemLimit = 2097152; // 2MB + private static final AtomicLong produced = new AtomicLong(); + private static final AtomicLong consumed = new AtomicLong(); + private static final int numMessagesToSend = 50000; - protected void setUp() throws Exception { - // Setup and start the broker - broker = new BrokerService(); - broker.setBrokerName(brokerName); - broker.setPersistent(false); - broker.setSchedulerSupport(false); - broker.setUseJmx(false); - broker.setUseShutdownHook(false); - broker.addConnector(brokerUrl); + private BrokerService broker; - // Setup the destination policy - PolicyMap pm = new PolicyMap(); + protected void setUp() throws Exception { + // Setup and start the broker + broker = new BrokerService(); + broker.setBrokerName(brokerName); + broker.setPersistent(false); + broker.setSchedulerSupport(false); + broker.setUseJmx(false); + broker.setUseShutdownHook(false); + broker.addConnector(brokerUrl); - // Setup the topic destination policy - PolicyEntry tpe = new PolicyEntry(); - tpe.setTopic(">"); - tpe.setMemoryLimit(destinationMemLimit); - tpe.setProducerFlowControl(true); - tpe.setAdvisoryWhenFull(true); + // Setup the destination policy + PolicyMap pm = new PolicyMap(); - // Setup the topic destination policy - PolicyEntry qpe = new PolicyEntry(); - qpe.setQueue(">"); - qpe.setMemoryLimit(destinationMemLimit); - qpe.setProducerFlowControl(true); - qpe.setQueuePrefetch(1); - qpe.setAdvisoryWhenFull(true); + // Setup the topic destination policy + PolicyEntry tpe = new PolicyEntry(); + tpe.setTopic(">"); + tpe.setMemoryLimit(destinationMemLimit); + tpe.setProducerFlowControl(true); + tpe.setAdvisoryWhenFull(true); - pm.setPolicyEntries(Arrays.asList(new PolicyEntry[]{tpe, qpe})); + // Setup the topic destination policy + PolicyEntry qpe = new PolicyEntry(); + qpe.setQueue(">"); + qpe.setMemoryLimit(destinationMemLimit); + qpe.setProducerFlowControl(true); + qpe.setQueuePrefetch(1); + qpe.setAdvisoryWhenFull(true); - setDestinationPolicy(broker, pm); + pm.setPolicyEntries(Arrays.asList(new PolicyEntry[]{tpe, qpe})); - // Start the broker - broker.start(); - broker.waitUntilStarted(); - } + setDestinationPolicy(broker, pm); - protected void setDestinationPolicy(BrokerService broker, PolicyMap pm) { - broker.setDestinationPolicy(pm); - } + // Start the broker + broker.start(); + broker.waitUntilStarted(); + } - protected void tearDown() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } + protected void setDestinationPolicy(BrokerService broker, PolicyMap pm) { + broker.setDestinationPolicy(pm); + } - public void testTopicProducerFlowControl() throws Exception { + protected void tearDown() throws Exception { + broker.stop(); + broker.waitUntilStopped(); + } - // Create the connection factory - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl); - connectionFactory.setAlwaysSyncSend(true); - connectionFactory.setProducerWindowSize(1024); + public void testTopicProducerFlowControl() throws Exception { - ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); - prefetchPolicy.setAll(5000); - connectionFactory.setPrefetchPolicy(prefetchPolicy); - // Start the test destination listener - Connection c = connectionFactory.createConnection(); - c.start(); - Session listenerSession = c.createSession(false, 1); - Destination destination = createDestination(listenerSession); + // Create the connection factory + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl); + connectionFactory.setAlwaysSyncSend(true); + connectionFactory.setProducerWindowSize(1024); - listenerSession.createConsumer(destination).setMessageListener(new TopicProducerFlowControlTest()); - final AtomicInteger blockedCounter = new AtomicInteger(0); - listenerSession.createConsumer(new ActiveMQTopic(AdvisorySupport.FULL_TOPIC_PREFIX + ">")).setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - LOG.info("Got full advisory, blockedCounter: " + blockedCounter.get()); - blockedCounter.incrementAndGet(); - } - }); + ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); + prefetchPolicy.setAll(5000); + connectionFactory.setPrefetchPolicy(prefetchPolicy); + // Start the test destination listener + Connection c = connectionFactory.createConnection(); + c.start(); + Session listenerSession = c.createSession(false, 1); + Destination destination = createDestination(listenerSession); - // Start producing the test messages - final Session session = connectionFactory.createConnection().createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageProducer producer = session.createProducer(destination); + listenerSession.createConsumer(destination).setMessageListener(new TopicProducerFlowControlTest()); + final AtomicInteger blockedCounter = new AtomicInteger(0); + listenerSession.createConsumer(new ActiveMQTopic(AdvisorySupport.FULL_TOPIC_PREFIX + ">")).setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + LOG.info("Got full advisory, blockedCounter: " + blockedCounter.get()); + blockedCounter.incrementAndGet(); + } + }); - Thread producingThread = new Thread("Producing Thread") { - public void run() { - try { - for (long i = 0; i < numMessagesToSend; i++) { - producer.send(session.createTextMessage("test")); + // Start producing the test messages + final Session session = connectionFactory.createConnection().createSession(false, Session.AUTO_ACKNOWLEDGE); + final MessageProducer producer = session.createProducer(destination); - long count = produced.incrementAndGet(); - if (count % 10000 == 0) { - LOG.info("Produced " + count + " messages"); - } - } - } catch (Throwable ex) { - ex.printStackTrace(); - } finally { - try { - producer.close(); - session.close(); - } catch (Exception e) { - } - } - } - }; - - producingThread.start(); - - Wait.waitFor(new Wait.Condition() { - public boolean isSatisified() throws Exception { - return consumed.get() == numMessagesToSend; - } - }, 5 * 60 * 1000); // give it plenty of time before failing - - assertEquals("Didn't produce all messages", numMessagesToSend, produced.get()); - assertEquals("Didn't consume all messages", numMessagesToSend, consumed.get()); - - assertTrue("Producer got blocked", Wait.waitFor(new Wait.Condition() { - public boolean isSatisified() throws Exception { - return blockedCounter.get() > 0; - } - }, 5 * 1000)); - } - - protected Destination createDestination(Session listenerSession) throws Exception { - return new ActiveMQTopic("test"); - } - - @Override - public void onMessage(Message message) { - long count = consumed.incrementAndGet(); - if (count % 100 == 0) { + Thread producingThread = new Thread("Producing Thread") { + public void run() { try { - Thread.sleep(100); - } catch (InterruptedException e) { - } - } - if (count % 10000 == 0) { - LOG.info("\tConsumed " + count + " messages"); - } + for (long i = 0; i < numMessagesToSend; i++) { + producer.send(session.createTextMessage("test")); - } + long count = produced.incrementAndGet(); + if (count % 10000 == 0) { + LOG.info("Produced " + count + " messages"); + } + } + } + catch (Throwable ex) { + ex.printStackTrace(); + } + finally { + try { + producer.close(); + session.close(); + } + catch (Exception e) { + } + } + } + }; + + producingThread.start(); + + Wait.waitFor(new Wait.Condition() { + public boolean isSatisified() throws Exception { + return consumed.get() == numMessagesToSend; + } + }, 5 * 60 * 1000); // give it plenty of time before failing + + assertEquals("Didn't produce all messages", numMessagesToSend, produced.get()); + assertEquals("Didn't consume all messages", numMessagesToSend, consumed.get()); + + assertTrue("Producer got blocked", Wait.waitFor(new Wait.Condition() { + public boolean isSatisified() throws Exception { + return blockedCounter.get() > 0; + } + }, 5 * 1000)); + } + + protected Destination createDestination(Session listenerSession) throws Exception { + return new ActiveMQTopic("test"); + } + + @Override + public void onMessage(Message message) { + long count = consumed.incrementAndGet(); + if (count % 100 == 0) { + try { + Thread.sleep(100); + } + catch (InterruptedException e) { + } + } + if (count % 10000 == 0) { + LOG.info("\tConsumed " + count + " messages"); + } + + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicRedeliverTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicRedeliverTest.java index 38134916fe..41c3553928 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicRedeliverTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicRedeliverTest.java @@ -35,244 +35,247 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ public class TopicRedeliverTest extends TestSupport { - private static final Logger LOG = LoggerFactory.getLogger(TopicRedeliverTest.class); - private static final int RECEIVE_TIMEOUT = 10000; + private static final Logger LOG = LoggerFactory.getLogger(TopicRedeliverTest.class); + private static final int RECEIVE_TIMEOUT = 10000; - protected int deliveryMode = DeliveryMode.PERSISTENT; - private IdGenerator idGen = new IdGenerator(); + protected int deliveryMode = DeliveryMode.PERSISTENT; + private IdGenerator idGen = new IdGenerator(); - public TopicRedeliverTest() { - } + public TopicRedeliverTest() { + } - public TopicRedeliverTest(String n) { - super(n); - } + public TopicRedeliverTest(String n) { + super(n); + } - protected void setUp() throws Exception { - super.setUp(); - topic = true; - } + protected void setUp() throws Exception { + super.setUp(); + topic = true; + } - /** - * test messages are acknowledged and recovered properly - * - * @throws Exception - */ - public void testClientAcknowledge() throws Exception { - Destination destination = createDestination(getClass().getName()); - Connection connection = createConnection(); - connection.setClientID(idGen.generateId()); - connection.start(); - Session consumerSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = consumerSession.createConsumer(destination); - Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = producerSession.createProducer(destination); - producer.setDeliveryMode(deliveryMode); + /** + * test messages are acknowledged and recovered properly + * + * @throws Exception + */ + public void testClientAcknowledge() throws Exception { + Destination destination = createDestination(getClass().getName()); + Connection connection = createConnection(); + connection.setClientID(idGen.generateId()); + connection.start(); + Session consumerSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + MessageConsumer consumer = consumerSession.createConsumer(destination); + Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = producerSession.createProducer(destination); + producer.setDeliveryMode(deliveryMode); - // send some messages + // send some messages - TextMessage sent1 = producerSession.createTextMessage(); - sent1.setText("msg1"); - producer.send(sent1); + TextMessage sent1 = producerSession.createTextMessage(); + sent1.setText("msg1"); + producer.send(sent1); - TextMessage sent2 = producerSession.createTextMessage(); - sent1.setText("msg2"); - producer.send(sent2); + TextMessage sent2 = producerSession.createTextMessage(); + sent1.setText("msg2"); + producer.send(sent2); - TextMessage sent3 = producerSession.createTextMessage(); - sent1.setText("msg3"); - producer.send(sent3); + TextMessage sent3 = producerSession.createTextMessage(); + sent1.setText("msg3"); + producer.send(sent3); - consumer.receive(RECEIVE_TIMEOUT); - Message rec2 = consumer.receive(RECEIVE_TIMEOUT); - consumer.receive(RECEIVE_TIMEOUT); + consumer.receive(RECEIVE_TIMEOUT); + Message rec2 = consumer.receive(RECEIVE_TIMEOUT); + consumer.receive(RECEIVE_TIMEOUT); - // ack rec2 - rec2.acknowledge(); + // ack rec2 + rec2.acknowledge(); - TextMessage sent4 = producerSession.createTextMessage(); - sent4.setText("msg4"); - producer.send(sent4); + TextMessage sent4 = producerSession.createTextMessage(); + sent4.setText("msg4"); + producer.send(sent4); - Message rec4 = consumer.receive(RECEIVE_TIMEOUT); - assertTrue(rec4.equals(sent4)); - consumerSession.recover(); - rec4 = consumer.receive(RECEIVE_TIMEOUT); - assertTrue(rec4.equals(sent4)); - assertTrue(rec4.getJMSRedelivered()); - rec4.acknowledge(); - connection.close(); + Message rec4 = consumer.receive(RECEIVE_TIMEOUT); + assertTrue(rec4.equals(sent4)); + consumerSession.recover(); + rec4 = consumer.receive(RECEIVE_TIMEOUT); + assertTrue(rec4.equals(sent4)); + assertTrue(rec4.getJMSRedelivered()); + rec4.acknowledge(); + connection.close(); - } + } - /** - * Test redelivered flag is set on rollbacked transactions - * - * @throws Exception - */ - public void testRedilveredFlagSetOnRollback() throws Exception { - Destination destination = createDestination(getClass().getName()); - Connection connection = createConnection(); - connection.setClientID(idGen.generateId()); - connection.start(); - Session consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = null; - if (topic) { - consumer = consumerSession.createDurableSubscriber((Topic)destination, "TESTRED"); - } else { - consumer = consumerSession.createConsumer(destination); - } - Session producerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = producerSession.createProducer(destination); - producer.setDeliveryMode(deliveryMode); + /** + * Test redelivered flag is set on rollbacked transactions + * + * @throws Exception + */ + public void testRedilveredFlagSetOnRollback() throws Exception { + Destination destination = createDestination(getClass().getName()); + Connection connection = createConnection(); + connection.setClientID(idGen.generateId()); + connection.start(); + Session consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); + MessageConsumer consumer = null; + if (topic) { + consumer = consumerSession.createDurableSubscriber((Topic) destination, "TESTRED"); + } + else { + consumer = consumerSession.createConsumer(destination); + } + Session producerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = producerSession.createProducer(destination); + producer.setDeliveryMode(deliveryMode); - TextMessage sentMsg = producerSession.createTextMessage(); - sentMsg.setText("msg1"); - producer.send(sentMsg); - producerSession.commit(); + TextMessage sentMsg = producerSession.createTextMessage(); + sentMsg.setText("msg1"); + producer.send(sentMsg); + producerSession.commit(); - Message recMsg = consumer.receive(RECEIVE_TIMEOUT); - assertFalse(recMsg.getJMSRedelivered()); - recMsg = consumer.receive(RECEIVE_TIMEOUT); - consumerSession.rollback(); - recMsg = consumer.receive(RECEIVE_TIMEOUT); - assertTrue(recMsg.getJMSRedelivered()); - consumerSession.commit(); - assertTrue(recMsg.equals(sentMsg)); - assertTrue(recMsg.getJMSRedelivered()); - connection.close(); - } + Message recMsg = consumer.receive(RECEIVE_TIMEOUT); + assertFalse(recMsg.getJMSRedelivered()); + recMsg = consumer.receive(RECEIVE_TIMEOUT); + consumerSession.rollback(); + recMsg = consumer.receive(RECEIVE_TIMEOUT); + assertTrue(recMsg.getJMSRedelivered()); + consumerSession.commit(); + assertTrue(recMsg.equals(sentMsg)); + assertTrue(recMsg.getJMSRedelivered()); + connection.close(); + } - public void testNoExceptionOnRedeliveryAckWithSimpleTopicConsumer() throws Exception { - Destination destination = createDestination(getClass().getName()); - Connection connection = createConnection(); - final AtomicBoolean gotException = new AtomicBoolean(); - connection.setExceptionListener(new ExceptionListener() { - public void onException(JMSException exception) { - LOG.error("unexpected ex:" + exception); - gotException.set(true); - } - }); - connection.setClientID(idGen.generateId()); - connection.start(); - Session consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = null; - if (topic) { - consumer = consumerSession.createConsumer((Topic)destination); - } else { - consumer = consumerSession.createConsumer(destination); - } - Session producerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = producerSession.createProducer(destination); - producer.setDeliveryMode(deliveryMode); + public void testNoExceptionOnRedeliveryAckWithSimpleTopicConsumer() throws Exception { + Destination destination = createDestination(getClass().getName()); + Connection connection = createConnection(); + final AtomicBoolean gotException = new AtomicBoolean(); + connection.setExceptionListener(new ExceptionListener() { + public void onException(JMSException exception) { + LOG.error("unexpected ex:" + exception); + gotException.set(true); + } + }); + connection.setClientID(idGen.generateId()); + connection.start(); + Session consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); + MessageConsumer consumer = null; + if (topic) { + consumer = consumerSession.createConsumer((Topic) destination); + } + else { + consumer = consumerSession.createConsumer(destination); + } + Session producerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = producerSession.createProducer(destination); + producer.setDeliveryMode(deliveryMode); - TextMessage sentMsg = producerSession.createTextMessage(); - sentMsg.setText("msg1"); - producer.send(sentMsg); - producerSession.commit(); + TextMessage sentMsg = producerSession.createTextMessage(); + sentMsg.setText("msg1"); + producer.send(sentMsg); + producerSession.commit(); - Message recMsg = consumer.receive(RECEIVE_TIMEOUT); - assertFalse(recMsg.getJMSRedelivered()); - recMsg = consumer.receive(RECEIVE_TIMEOUT); - consumerSession.rollback(); - recMsg = consumer.receive(RECEIVE_TIMEOUT); - assertTrue(recMsg.getJMSRedelivered()); - consumerSession.rollback(); - recMsg = consumer.receive(RECEIVE_TIMEOUT); - assertTrue(recMsg.getJMSRedelivered()); - consumerSession.commit(); - assertTrue(recMsg.equals(sentMsg)); - assertTrue(recMsg.getJMSRedelivered()); - connection.close(); + Message recMsg = consumer.receive(RECEIVE_TIMEOUT); + assertFalse(recMsg.getJMSRedelivered()); + recMsg = consumer.receive(RECEIVE_TIMEOUT); + consumerSession.rollback(); + recMsg = consumer.receive(RECEIVE_TIMEOUT); + assertTrue(recMsg.getJMSRedelivered()); + consumerSession.rollback(); + recMsg = consumer.receive(RECEIVE_TIMEOUT); + assertTrue(recMsg.getJMSRedelivered()); + consumerSession.commit(); + assertTrue(recMsg.equals(sentMsg)); + assertTrue(recMsg.getJMSRedelivered()); + connection.close(); - assertFalse("no exception", gotException.get()); - } + assertFalse("no exception", gotException.get()); + } - /** - * Check a session is rollbacked on a Session close(); - * - * @throws Exception - */ + /** + * Check a session is rollbacked on a Session close(); + * + * @throws Exception + */ - public void xtestTransactionRollbackOnSessionClose() throws Exception { - Destination destination = createDestination(getClass().getName()); - Connection connection = createConnection(); - connection.setClientID(idGen.generateId()); - connection.start(); - Session consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = null; - if (topic) { - consumer = consumerSession.createDurableSubscriber((Topic)destination, "TESTRED"); - } else { - consumer = consumerSession.createConsumer(destination); - } - Session producerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = producerSession.createProducer(destination); - producer.setDeliveryMode(deliveryMode); + public void xtestTransactionRollbackOnSessionClose() throws Exception { + Destination destination = createDestination(getClass().getName()); + Connection connection = createConnection(); + connection.setClientID(idGen.generateId()); + connection.start(); + Session consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); + MessageConsumer consumer = null; + if (topic) { + consumer = consumerSession.createDurableSubscriber((Topic) destination, "TESTRED"); + } + else { + consumer = consumerSession.createConsumer(destination); + } + Session producerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = producerSession.createProducer(destination); + producer.setDeliveryMode(deliveryMode); - TextMessage sentMsg = producerSession.createTextMessage(); - sentMsg.setText("msg1"); - producer.send(sentMsg); + TextMessage sentMsg = producerSession.createTextMessage(); + sentMsg.setText("msg1"); + producer.send(sentMsg); - producerSession.commit(); + producerSession.commit(); - Message recMsg = consumer.receive(RECEIVE_TIMEOUT); - assertFalse(recMsg.getJMSRedelivered()); - consumerSession.close(); - consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); - consumer = consumerSession.createConsumer(destination); + Message recMsg = consumer.receive(RECEIVE_TIMEOUT); + assertFalse(recMsg.getJMSRedelivered()); + consumerSession.close(); + consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); + consumer = consumerSession.createConsumer(destination); - recMsg = consumer.receive(RECEIVE_TIMEOUT); - consumerSession.commit(); - assertTrue(recMsg.equals(sentMsg)); - connection.close(); - } + recMsg = consumer.receive(RECEIVE_TIMEOUT); + consumerSession.commit(); + assertTrue(recMsg.equals(sentMsg)); + connection.close(); + } - /** - * check messages are actuallly sent on a tx rollback - * - * @throws Exception - */ + /** + * check messages are actuallly sent on a tx rollback + * + * @throws Exception + */ - public void testTransactionRollbackOnSend() throws Exception { - Destination destination = createDestination(getClass().getName()); - Connection connection = createConnection(); - connection.setClientID(idGen.generateId()); - connection.start(); - Session consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = consumerSession.createConsumer(destination); - Session producerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = producerSession.createProducer(destination); - producer.setDeliveryMode(deliveryMode); + public void testTransactionRollbackOnSend() throws Exception { + Destination destination = createDestination(getClass().getName()); + Connection connection = createConnection(); + connection.setClientID(idGen.generateId()); + connection.start(); + Session consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); + MessageConsumer consumer = consumerSession.createConsumer(destination); + Session producerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = producerSession.createProducer(destination); + producer.setDeliveryMode(deliveryMode); - TextMessage sentMsg = producerSession.createTextMessage(); - sentMsg.setText("msg1"); - producer.send(sentMsg); - producerSession.commit(); + TextMessage sentMsg = producerSession.createTextMessage(); + sentMsg.setText("msg1"); + producer.send(sentMsg); + producerSession.commit(); - Message recMsg = consumer.receive(RECEIVE_TIMEOUT); - consumerSession.commit(); - assertTrue(recMsg.equals(sentMsg)); + Message recMsg = consumer.receive(RECEIVE_TIMEOUT); + consumerSession.commit(); + assertTrue(recMsg.equals(sentMsg)); - sentMsg = producerSession.createTextMessage(); - sentMsg.setText("msg2"); - producer.send(sentMsg); - producerSession.rollback(); + sentMsg = producerSession.createTextMessage(); + sentMsg.setText("msg2"); + producer.send(sentMsg); + producerSession.rollback(); - sentMsg = producerSession.createTextMessage(); - sentMsg.setText("msg3"); - producer.send(sentMsg); - producerSession.commit(); + sentMsg = producerSession.createTextMessage(); + sentMsg.setText("msg3"); + producer.send(sentMsg); + producerSession.commit(); - recMsg = consumer.receive(RECEIVE_TIMEOUT); - assertTrue(recMsg.equals(sentMsg)); - consumerSession.commit(); + recMsg = consumer.receive(RECEIVE_TIMEOUT); + assertTrue(recMsg.equals(sentMsg)); + consumerSession.commit(); - connection.close(); - } + connection.close(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicReplicationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicReplicationTest.java index e01616e871..845cb9e4db 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicReplicationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicReplicationTest.java @@ -25,92 +25,88 @@ import javax.jms.MessageConsumer; public class TopicReplicationTest extends JmsMultipleBrokersTestSupport { - public static final int MSG_COUNT = 10; + public static final int MSG_COUNT = 10; - public void testReplication() throws Exception { - createBroker(new ClassPathResource("org/apache/activemq/usecases/replication-broker1.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/replication-broker2.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/replication-broker3.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/replication-broker4.xml")); + public void testReplication() throws Exception { + createBroker(new ClassPathResource("org/apache/activemq/usecases/replication-broker1.xml")); + createBroker(new ClassPathResource("org/apache/activemq/usecases/replication-broker2.xml")); + createBroker(new ClassPathResource("org/apache/activemq/usecases/replication-broker3.xml")); + createBroker(new ClassPathResource("org/apache/activemq/usecases/replication-broker4.xml")); - brokers.get("replication-broker1").broker.waitUntilStarted(); - brokers.get("replication-broker2").broker.waitUntilStarted(); - brokers.get("replication-broker3").broker.waitUntilStarted(); - brokers.get("replication-broker4").broker.waitUntilStarted(); + brokers.get("replication-broker1").broker.waitUntilStarted(); + brokers.get("replication-broker2").broker.waitUntilStarted(); + brokers.get("replication-broker3").broker.waitUntilStarted(); + brokers.get("replication-broker4").broker.waitUntilStarted(); - Destination dest = createDestination("replication", true); + Destination dest = createDestination("replication", true); - // Setup consumers - MessageConsumer clientA = createConsumer("replication-broker2", dest); - MessageConsumer clientB = createConsumer("replication-broker3", dest); - MessageConsumer clientC = createConsumer("replication-broker4", dest); - MessageConsumer clientD = createConsumer("replication-broker4", dest); + // Setup consumers + MessageConsumer clientA = createConsumer("replication-broker2", dest); + MessageConsumer clientB = createConsumer("replication-broker3", dest); + MessageConsumer clientC = createConsumer("replication-broker4", dest); + MessageConsumer clientD = createConsumer("replication-broker4", dest); - //let consumers propagate around the network - Thread.sleep(2000); + //let consumers propagate around the network + Thread.sleep(2000); - // Get message count - MessageIdList msgsA = getConsumerMessages("replication-broker2", clientA); - MessageIdList msgsB = getConsumerMessages("replication-broker3", clientB); - MessageIdList msgsC = getConsumerMessages("replication-broker4", clientC); - MessageIdList msgsD = getConsumerMessages("replication-broker4", clientD); + // Get message count + MessageIdList msgsA = getConsumerMessages("replication-broker2", clientA); + MessageIdList msgsB = getConsumerMessages("replication-broker3", clientB); + MessageIdList msgsC = getConsumerMessages("replication-broker4", clientC); + MessageIdList msgsD = getConsumerMessages("replication-broker4", clientD); + // send messages to broker1 + sendMessages("replication-broker1", dest, MSG_COUNT); + msgsA.waitForMessagesToArrive(MSG_COUNT); + msgsB.waitForMessagesToArrive(MSG_COUNT); + msgsC.waitForMessagesToArrive(MSG_COUNT); + msgsD.waitForMessagesToArrive(MSG_COUNT); - // send messages to broker1 - sendMessages("replication-broker1", dest, MSG_COUNT); + assertEquals(MSG_COUNT, msgsA.getMessageCount()); + assertEquals(MSG_COUNT, msgsB.getMessageCount()); + assertEquals(MSG_COUNT, msgsC.getMessageCount()); + assertEquals(MSG_COUNT, msgsD.getMessageCount()); + // send messages to broker4 + sendMessages("replication-broker4", dest, MSG_COUNT); - msgsA.waitForMessagesToArrive(MSG_COUNT); - msgsB.waitForMessagesToArrive(MSG_COUNT); - msgsC.waitForMessagesToArrive(MSG_COUNT); - msgsD.waitForMessagesToArrive(MSG_COUNT); + msgsA.waitForMessagesToArrive(2 * MSG_COUNT); + msgsB.waitForMessagesToArrive(2 * MSG_COUNT); + msgsC.waitForMessagesToArrive(2 * MSG_COUNT); + msgsD.waitForMessagesToArrive(2 * MSG_COUNT); - assertEquals(MSG_COUNT, msgsA.getMessageCount()); - assertEquals(MSG_COUNT, msgsB.getMessageCount()); - assertEquals(MSG_COUNT, msgsC.getMessageCount()); - assertEquals(MSG_COUNT, msgsD.getMessageCount()); + assertEquals(2 * MSG_COUNT, msgsA.getMessageCount()); + assertEquals(2 * MSG_COUNT, msgsB.getMessageCount()); + assertEquals(2 * MSG_COUNT, msgsC.getMessageCount()); + assertEquals(2 * MSG_COUNT, msgsD.getMessageCount()); - // send messages to broker4 - sendMessages("replication-broker4", dest, MSG_COUNT); + // send messages to broker3 + sendMessages("replication-broker3", dest, MSG_COUNT); - msgsA.waitForMessagesToArrive(2 * MSG_COUNT); - msgsB.waitForMessagesToArrive(2 * MSG_COUNT); - msgsC.waitForMessagesToArrive(2 * MSG_COUNT); - msgsD.waitForMessagesToArrive(2 * MSG_COUNT); + msgsA.waitForMessagesToArrive(3 * MSG_COUNT); + msgsB.waitForMessagesToArrive(3 * MSG_COUNT); + msgsC.waitForMessagesToArrive(3 * MSG_COUNT); + msgsD.waitForMessagesToArrive(3 * MSG_COUNT); - assertEquals(2 * MSG_COUNT, msgsA.getMessageCount()); - assertEquals(2 * MSG_COUNT, msgsB.getMessageCount()); - assertEquals(2 * MSG_COUNT, msgsC.getMessageCount()); - assertEquals(2 * MSG_COUNT, msgsD.getMessageCount()); + assertEquals(3 * MSG_COUNT, msgsA.getMessageCount()); + assertEquals(3 * MSG_COUNT, msgsB.getMessageCount()); + assertEquals(3 * MSG_COUNT, msgsC.getMessageCount()); + assertEquals(3 * MSG_COUNT, msgsD.getMessageCount()); - // send messages to broker3 - sendMessages("replication-broker3", dest, MSG_COUNT); + // send messages to broker2 + sendMessages("replication-broker2", dest, MSG_COUNT); - msgsA.waitForMessagesToArrive(3 * MSG_COUNT); - msgsB.waitForMessagesToArrive(3 * MSG_COUNT); - msgsC.waitForMessagesToArrive(3 * MSG_COUNT); - msgsD.waitForMessagesToArrive(3 * MSG_COUNT); + msgsA.waitForMessagesToArrive(4 * MSG_COUNT); + msgsB.waitForMessagesToArrive(4 * MSG_COUNT); + msgsC.waitForMessagesToArrive(4 * MSG_COUNT); + msgsD.waitForMessagesToArrive(4 * MSG_COUNT); - assertEquals(3 * MSG_COUNT, msgsA.getMessageCount()); - assertEquals(3 * MSG_COUNT, msgsB.getMessageCount()); - assertEquals(3 * MSG_COUNT, msgsC.getMessageCount()); - assertEquals(3 * MSG_COUNT, msgsD.getMessageCount()); - - // send messages to broker2 - sendMessages("replication-broker2", dest, MSG_COUNT); - - msgsA.waitForMessagesToArrive(4 * MSG_COUNT); - msgsB.waitForMessagesToArrive(4 * MSG_COUNT); - msgsC.waitForMessagesToArrive(4 * MSG_COUNT); - msgsD.waitForMessagesToArrive(4 * MSG_COUNT); - - assertEquals(4 * MSG_COUNT, msgsA.getMessageCount()); - assertEquals(4 * MSG_COUNT, msgsB.getMessageCount()); - assertEquals(4 * MSG_COUNT, msgsC.getMessageCount()); - assertEquals(4 * MSG_COUNT, msgsD.getMessageCount()); - - } + assertEquals(4 * MSG_COUNT, msgsA.getMessageCount()); + assertEquals(4 * MSG_COUNT, msgsB.getMessageCount()); + assertEquals(4 * MSG_COUNT, msgsC.getMessageCount()); + assertEquals(4 * MSG_COUNT, msgsD.getMessageCount()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicSubscriptionSlowConsumerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicSubscriptionSlowConsumerTest.java index 4d56601d65..6c2fcf8169 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicSubscriptionSlowConsumerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicSubscriptionSlowConsumerTest.java @@ -17,6 +17,7 @@ package org.apache.activemq.usecases; import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.advisory.AdvisorySupport; import org.apache.activemq.broker.BrokerService; @@ -31,98 +32,90 @@ import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; - /** - * Checks to see if "slow consumer advisory messages" are generated when - * small number of messages (2) are published to a topic which has a subscriber + * Checks to see if "slow consumer advisory messages" are generated when + * small number of messages (2) are published to a topic which has a subscriber * with a prefetch of one set. - * */ public class TopicSubscriptionSlowConsumerTest extends TestCase { - private static final String TOPIC_NAME = "slow.consumer"; - Connection connection; - private Session session; - private ActiveMQTopic destination; - private MessageProducer producer; - private MessageConsumer consumer; - private BrokerService brokerService; + private static final String TOPIC_NAME = "slow.consumer"; + Connection connection; + private Session session; + private ActiveMQTopic destination; + private MessageProducer producer; + private MessageConsumer consumer; + private BrokerService brokerService; - - public void setUp() throws Exception { + public void setUp() throws Exception { - brokerService = createBroker(); - - ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory("vm://localhost"); - - activeMQConnectionFactory.setWatchTopicAdvisories(true); - connection = activeMQConnectionFactory.createConnection(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - destination = new ActiveMQTopic(TOPIC_NAME); - producer = session.createProducer(destination); - - connection.start(); - } + brokerService = createBroker(); - - - public void testPrefetchValueOne() throws Exception{ - - ActiveMQTopic consumerDestination = new ActiveMQTopic(TOPIC_NAME+"?consumer.prefetchSize=1"); - consumer = session.createConsumer(consumerDestination); - - //add a consumer to the slow consumer advisory topic. - ActiveMQTopic slowConsumerAdvisoryTopic = AdvisorySupport.getSlowConsumerAdvisoryTopic(destination); - MessageConsumer slowConsumerAdvisory = session.createConsumer(slowConsumerAdvisoryTopic); - - //publish 2 messages - Message txtMessage = session.createTextMessage("Sample Text Message"); - for(int i= 0; i<2; i++){ - producer.send(txtMessage); - } - - //consume 2 messages - for(int i= 0; i<2; i++){ - Message receivedMsg = consumer.receive(100); - Assert.assertNotNull("received msg "+i+" should not be null",receivedMsg); - } + ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory("vm://localhost"); - //check for "slow consumer" advisory message - Message slowAdvisoryMessage = slowConsumerAdvisory.receive(100); - Assert.assertNull( "should not have received a slow consumer advisory message",slowAdvisoryMessage); - - } + activeMQConnectionFactory.setWatchTopicAdvisories(true); + connection = activeMQConnectionFactory.createConnection(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + destination = new ActiveMQTopic(TOPIC_NAME); + producer = session.createProducer(destination); - + connection.start(); + } - public void tearDown() throws Exception { - consumer.close(); - producer.close(); - session.close(); - connection.close(); - brokerService.stop(); - } - - - //helper method to create a broker with slow consumer advisory turned on - private BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("localhost"); - broker.setUseJmx(true); - broker.setDeleteAllMessagesOnStartup(true); - broker.addConnector("vm://localhost"); + public void testPrefetchValueOne() throws Exception { - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setAdvisoryForSlowConsumers(true); + ActiveMQTopic consumerDestination = new ActiveMQTopic(TOPIC_NAME + "?consumer.prefetchSize=1"); + consumer = session.createConsumer(consumerDestination); - policyMap.setDefaultEntry(defaultEntry); + //add a consumer to the slow consumer advisory topic. + ActiveMQTopic slowConsumerAdvisoryTopic = AdvisorySupport.getSlowConsumerAdvisoryTopic(destination); + MessageConsumer slowConsumerAdvisory = session.createConsumer(slowConsumerAdvisoryTopic); - broker.setDestinationPolicy(policyMap); - broker.start(); - broker.waitUntilStarted(); - return broker; - } + //publish 2 messages + Message txtMessage = session.createTextMessage("Sample Text Message"); + for (int i = 0; i < 2; i++) { + producer.send(txtMessage); + } + + //consume 2 messages + for (int i = 0; i < 2; i++) { + Message receivedMsg = consumer.receive(100); + Assert.assertNotNull("received msg " + i + " should not be null", receivedMsg); + } + + //check for "slow consumer" advisory message + Message slowAdvisoryMessage = slowConsumerAdvisory.receive(100); + Assert.assertNull("should not have received a slow consumer advisory message", slowAdvisoryMessage); + + } + + public void tearDown() throws Exception { + consumer.close(); + producer.close(); + session.close(); + connection.close(); + brokerService.stop(); + } + + //helper method to create a broker with slow consumer advisory turned on + private BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setBrokerName("localhost"); + broker.setUseJmx(true); + broker.setDeleteAllMessagesOnStartup(true); + broker.addConnector("vm://localhost"); + + PolicyMap policyMap = new PolicyMap(); + PolicyEntry defaultEntry = new PolicyEntry(); + defaultEntry.setAdvisoryForSlowConsumers(true); + + policyMap.setDefaultEntry(defaultEntry); + + broker.setDestinationPolicy(policyMap); + broker.start(); + broker.waitUntilStarted(); + return broker; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicSubscriptionZeroPrefetchTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicSubscriptionZeroPrefetchTest.java index b9f0d5063f..7122acc4bd 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicSubscriptionZeroPrefetchTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicSubscriptionZeroPrefetchTest.java @@ -32,85 +32,85 @@ import org.junit.Test; public class TopicSubscriptionZeroPrefetchTest { - private static final String TOPIC_NAME = "slow.consumer"; - private Connection connection; - private Session session; - private ActiveMQTopic destination; - private MessageProducer producer; - private MessageConsumer consumer; - private BrokerService brokerService; + private static final String TOPIC_NAME = "slow.consumer"; + private Connection connection; + private Session session; + private ActiveMQTopic destination; + private MessageProducer producer; + private MessageConsumer consumer; + private BrokerService brokerService; - @Before - public void setUp() throws Exception { + @Before + public void setUp() throws Exception { - brokerService = createBroker(); + brokerService = createBroker(); - ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory("vm://localhost"); + ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory("vm://localhost"); - activeMQConnectionFactory.setWatchTopicAdvisories(true); - connection = activeMQConnectionFactory.createConnection(); - connection.setClientID("ClientID-1"); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - destination = new ActiveMQTopic(TOPIC_NAME); - producer = session.createProducer(destination); + activeMQConnectionFactory.setWatchTopicAdvisories(true); + connection = activeMQConnectionFactory.createConnection(); + connection.setClientID("ClientID-1"); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + destination = new ActiveMQTopic(TOPIC_NAME); + producer = session.createProducer(destination); - connection.start(); - } + connection.start(); + } - /* - * test non durable topic subscription with prefetch set to zero - */ - @Test(timeout=60000) - public void testTopicConsumerPrefetchZero() throws Exception { + /* + * test non durable topic subscription with prefetch set to zero + */ + @Test(timeout = 60000) + public void testTopicConsumerPrefetchZero() throws Exception { - ActiveMQTopic consumerDestination = new ActiveMQTopic(TOPIC_NAME + "?consumer.retroactive=true&consumer.prefetchSize=0"); - consumer = session.createConsumer(consumerDestination); + ActiveMQTopic consumerDestination = new ActiveMQTopic(TOPIC_NAME + "?consumer.retroactive=true&consumer.prefetchSize=0"); + consumer = session.createConsumer(consumerDestination); - // publish messages - Message txtMessage = session.createTextMessage("M"); - producer.send(txtMessage); + // publish messages + Message txtMessage = session.createTextMessage("M"); + producer.send(txtMessage); - Message consumedMessage = consumer.receiveNoWait(); + Message consumedMessage = consumer.receiveNoWait(); - Assert.assertNotNull("should have received a message the published message", consumedMessage); - } + Assert.assertNotNull("should have received a message the published message", consumedMessage); + } - /* - * test durable topic subscription with prefetch zero - */ - @Test(timeout=60000) - public void testDurableTopicConsumerPrefetchZero() throws Exception { + /* + * test durable topic subscription with prefetch zero + */ + @Test(timeout = 60000) + public void testDurableTopicConsumerPrefetchZero() throws Exception { - ActiveMQTopic consumerDestination = new ActiveMQTopic(TOPIC_NAME + "?consumer.prefetchSize=0"); - consumer = session.createDurableSubscriber(consumerDestination, "mysub1"); + ActiveMQTopic consumerDestination = new ActiveMQTopic(TOPIC_NAME + "?consumer.prefetchSize=0"); + consumer = session.createDurableSubscriber(consumerDestination, "mysub1"); - // publish messages - Message txtMessage = session.createTextMessage("M"); - producer.send(txtMessage); + // publish messages + Message txtMessage = session.createTextMessage("M"); + producer.send(txtMessage); - Message consumedMessage = consumer.receive(100); + Message consumedMessage = consumer.receive(100); - Assert.assertNotNull("should have received a message the published message", consumedMessage); - } + Assert.assertNotNull("should have received a message the published message", consumedMessage); + } - @After - public void tearDown() throws Exception { - consumer.close(); - producer.close(); - session.close(); - connection.close(); - brokerService.stop(); - } + @After + public void tearDown() throws Exception { + consumer.close(); + producer.close(); + session.close(); + connection.close(); + brokerService.stop(); + } - // helper method to create a broker with slow consumer advisory turned on - private BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("localhost"); - broker.setUseJmx(false); - broker.setDeleteAllMessagesOnStartup(true); - broker.addConnector("vm://localhost"); - broker.start(); - broker.waitUntilStarted(); - return broker; - } + // helper method to create a broker with slow consumer advisory turned on + private BrokerService createBroker() throws Exception { + BrokerService broker = new BrokerService(); + broker.setBrokerName("localhost"); + broker.setUseJmx(false); + broker.setDeleteAllMessagesOnStartup(true); + broker.addConnector("vm://localhost"); + broker.start(); + broker.waitUntilStarted(); + return broker; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TransactionRollbackOrderTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TransactionRollbackOrderTest.java index 9567cea072..b910593c62 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TransactionRollbackOrderTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TransactionRollbackOrderTest.java @@ -31,6 +31,7 @@ import javax.jms.Session; import javax.jms.TextMessage; import junit.framework.TestCase; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.command.ActiveMQQueue; import org.slf4j.Logger; @@ -38,122 +39,126 @@ import org.slf4j.LoggerFactory; /** * Test case for AMQ-268 - * + * * @author Paul Smith - * */ public final class TransactionRollbackOrderTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(TransactionRollbackOrderTest.class); - private volatile String receivedText; + private static final Logger LOG = LoggerFactory.getLogger(TransactionRollbackOrderTest.class); - private Session producerSession; - private Session consumerSession; - private Destination queue; + private volatile String receivedText; - private MessageProducer producer; - private MessageConsumer consumer; - private Connection connection; - private CountDownLatch latch = new CountDownLatch(1); - private int numMessages = 5; - private List msgSent = new ArrayList(); - private List msgCommitted = new ArrayList(); - private List msgRolledBack = new ArrayList(); - private List msgRedelivered = new ArrayList(); + private Session producerSession; + private Session consumerSession; + private Destination queue; - public void testTransaction() throws Exception { + private MessageProducer producer; + private MessageConsumer consumer; + private Connection connection; + private CountDownLatch latch = new CountDownLatch(1); + private int numMessages = 5; + private List msgSent = new ArrayList(); + private List msgCommitted = new ArrayList(); + private List msgRolledBack = new ArrayList(); + private List msgRedelivered = new ArrayList(); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); + public void testTransaction() throws Exception { - connection = factory.createConnection(); - queue = new ActiveMQQueue(getClass().getName() + "." + getName()); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); - producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumerSession = connection.createSession(true, 0); + connection = factory.createConnection(); + queue = new ActiveMQQueue(getClass().getName() + "." + getName()); - producer = producerSession.createProducer(queue); + producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumerSession = connection.createSession(true, 0); - consumer = consumerSession.createConsumer(queue); - consumer.setMessageListener(new MessageListener() { + producer = producerSession.createProducer(queue); - int msgCount; - int msgCommittedCount; + consumer = consumerSession.createConsumer(queue); + consumer.setMessageListener(new MessageListener() { - public void onMessage(Message m) { - try { - msgCount++; - TextMessage tm = (TextMessage)m; - receivedText = tm.getText(); + int msgCount; + int msgCommittedCount; - if (tm.getJMSRedelivered()) { - msgRedelivered.add(receivedText); - } + public void onMessage(Message m) { + try { + msgCount++; + TextMessage tm = (TextMessage) m; + receivedText = tm.getText(); - LOG.info("consumer received message: " + receivedText + (tm.getJMSRedelivered() ? " ** Redelivered **" : "")); - if (msgCount == 3) { - msgRolledBack.add(receivedText); - consumerSession.rollback(); - LOG.info("[msg: " + receivedText + "] ** rolled back **"); - } else { - msgCommittedCount++; - msgCommitted.add(receivedText); - consumerSession.commit(); - LOG.info("[msg: " + receivedText + "] committed transaction "); - } - if (msgCommittedCount == numMessages) { - latch.countDown(); - } - } catch (JMSException e) { - try { - consumerSession.rollback(); - LOG.info("rolled back transaction"); - } catch (JMSException e1) { - LOG.info(e1.toString()); - e1.printStackTrace(); - } - LOG.info(e.toString()); - e.printStackTrace(); - } + if (tm.getJMSRedelivered()) { + msgRedelivered.add(receivedText); + } + + LOG.info("consumer received message: " + receivedText + (tm.getJMSRedelivered() ? " ** Redelivered **" : "")); + if (msgCount == 3) { + msgRolledBack.add(receivedText); + consumerSession.rollback(); + LOG.info("[msg: " + receivedText + "] ** rolled back **"); + } + else { + msgCommittedCount++; + msgCommitted.add(receivedText); + consumerSession.commit(); + LOG.info("[msg: " + receivedText + "] committed transaction "); + } + if (msgCommittedCount == numMessages) { + latch.countDown(); + } } - }); - connection.start(); - - TextMessage tm = null; - try { - for (int i = 1; i <= numMessages; i++) { - tm = producerSession.createTextMessage(); - tm.setText("Hello " + i); - msgSent.add(tm.getText()); - producer.send(tm); - LOG.info("producer sent message: " + tm.getText()); + catch (JMSException e) { + try { + consumerSession.rollback(); + LOG.info("rolled back transaction"); + } + catch (JMSException e1) { + LOG.info(e1.toString()); + e1.printStackTrace(); + } + LOG.info(e.toString()); + e.printStackTrace(); } - } catch (JMSException e) { - e.printStackTrace(); - } + } + }); + connection.start(); - LOG.info("Waiting for latch"); - latch.await(); + TextMessage tm = null; + try { + for (int i = 1; i <= numMessages; i++) { + tm = producerSession.createTextMessage(); + tm.setText("Hello " + i); + msgSent.add(tm.getText()); + producer.send(tm); + LOG.info("producer sent message: " + tm.getText()); + } + } + catch (JMSException e) { + e.printStackTrace(); + } - assertEquals(1, msgRolledBack.size()); - assertEquals(1, msgRedelivered.size()); + LOG.info("Waiting for latch"); + latch.await(); - LOG.info("msg RolledBack = " + msgRolledBack.get(0)); - LOG.info("msg Redelivered = " + msgRedelivered.get(0)); + assertEquals(1, msgRolledBack.size()); + assertEquals(1, msgRedelivered.size()); - assertEquals(msgRolledBack.get(0), msgRedelivered.get(0)); + LOG.info("msg RolledBack = " + msgRolledBack.get(0)); + LOG.info("msg Redelivered = " + msgRedelivered.get(0)); - assertEquals(numMessages, msgSent.size()); - assertEquals(numMessages, msgCommitted.size()); + assertEquals(msgRolledBack.get(0), msgRedelivered.get(0)); - assertEquals(msgSent, msgCommitted); + assertEquals(numMessages, msgSent.size()); + assertEquals(numMessages, msgCommitted.size()); - } + assertEquals(msgSent, msgCommitted); - protected void tearDown() throws Exception { - if (connection != null) { - LOG.info("Closing the connection"); - connection.close(); - } - super.tearDown(); - } + } + + protected void tearDown() throws Exception { + if (connection != null) { + LOG.info("Closing the connection"); + connection.close(); + } + super.tearDown(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TransactionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TransactionTest.java index baee89ebaa..3ccc147497 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TransactionTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TransactionTest.java @@ -39,84 +39,86 @@ import org.slf4j.LoggerFactory; /** * @author pragmasoft - * */ public final class TransactionTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(TransactionTest.class); + private static final Logger LOG = LoggerFactory.getLogger(TransactionTest.class); - private volatile String receivedText; + private volatile String receivedText; - private Session producerSession; - private Session consumerSession; - private Destination queue; + private Session producerSession; + private Session consumerSession; + private Destination queue; - private MessageProducer producer; - private MessageConsumer consumer; - private Connection connection; - private final CountDownLatch latch = new CountDownLatch(1); + private MessageProducer producer; + private MessageConsumer consumer; + private Connection connection; + private final CountDownLatch latch = new CountDownLatch(1); - public void testTransaction() throws Exception { + public void testTransaction() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); - connection = factory.createConnection(); - queue = new ActiveMQQueue(getClass().getName() + "." + getName()); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); + connection = factory.createConnection(); + queue = new ActiveMQQueue(getClass().getName() + "." + getName()); - producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumerSession = connection.createSession(true, 0); + producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumerSession = connection.createSession(true, 0); - producer = producerSession.createProducer(queue); + producer = producerSession.createProducer(queue); - consumer = consumerSession.createConsumer(queue); - consumer.setMessageListener(new MessageListener() { + consumer = consumerSession.createConsumer(queue); + consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message m) { - try { - TextMessage tm = (TextMessage)m; - receivedText = tm.getText(); - latch.countDown(); + @Override + public void onMessage(Message m) { + try { + TextMessage tm = (TextMessage) m; + receivedText = tm.getText(); + latch.countDown(); - LOG.info("consumer received message :" + receivedText); - consumerSession.commit(); - LOG.info("committed transaction"); - } catch (JMSException e) { - try { - consumerSession.rollback(); - LOG.info("rolled back transaction"); - } catch (JMSException e1) { - LOG.info(e1.toString()); - e1.printStackTrace(); - } - LOG.info(e.toString()); - e.printStackTrace(); - } + LOG.info("consumer received message :" + receivedText); + consumerSession.commit(); + LOG.info("committed transaction"); } - }); + catch (JMSException e) { + try { + consumerSession.rollback(); + LOG.info("rolled back transaction"); + } + catch (JMSException e1) { + LOG.info(e1.toString()); + e1.printStackTrace(); + } + LOG.info(e.toString()); + e.printStackTrace(); + } + } + }); - connection.start(); + connection.start(); - TextMessage tm = null; - try { - tm = producerSession.createTextMessage(); - tm.setText("Hello, " + new Date()); - producer.send(tm); - LOG.info("producer sent message :" + tm.getText()); - } catch (JMSException e) { - e.printStackTrace(); - } + TextMessage tm = null; + try { + tm = producerSession.createTextMessage(); + tm.setText("Hello, " + new Date()); + producer.send(tm); + LOG.info("producer sent message :" + tm.getText()); + } + catch (JMSException e) { + e.printStackTrace(); + } - LOG.info("Waiting for latch"); - latch.await(2,TimeUnit.SECONDS); - assertNotNull(receivedText); - LOG.info("test completed, destination=" + receivedText); - } + LOG.info("Waiting for latch"); + latch.await(2, TimeUnit.SECONDS); + assertNotNull(receivedText); + LOG.info("test completed, destination=" + receivedText); + } - @Override - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - super.tearDown(); - } + @Override + protected void tearDown() throws Exception { + if (connection != null) { + connection.close(); + } + super.tearDown(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TransientQueueRedeliverTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TransientQueueRedeliverTest.java index 24fd890f75..58958427ef 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TransientQueueRedeliverTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TransientQueueRedeliverTest.java @@ -19,14 +19,14 @@ package org.apache.activemq.usecases; import javax.jms.DeliveryMode; /** - * + * */ public class TransientQueueRedeliverTest extends TopicRedeliverTest { - protected void setUp() throws Exception { - super.setUp(); - topic = false; - deliveryMode = DeliveryMode.NON_PERSISTENT; - } + protected void setUp() throws Exception { + super.setUp(); + topic = false; + deliveryMode = DeliveryMode.NON_PERSISTENT; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerMessageNotSentToRemoteWhenNoConsumerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerMessageNotSentToRemoteWhenNoConsumerTest.java index 3e97eb2223..708d0aa521 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerMessageNotSentToRemoteWhenNoConsumerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerMessageNotSentToRemoteWhenNoConsumerTest.java @@ -25,107 +25,106 @@ import org.apache.activemq.JmsMultipleBrokersTestSupport; import org.apache.activemq.util.MessageIdList; public class TwoBrokerMessageNotSentToRemoteWhenNoConsumerTest extends JmsMultipleBrokersTestSupport { - protected static final int MESSAGE_COUNT = 100; - /** - * BrokerA -> BrokerB - */ - public void testRemoteBrokerHasConsumer() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerA", "BrokerB"); + protected static final int MESSAGE_COUNT = 100; - startAllBrokers(); + /** + * BrokerA -> BrokerB + */ + public void testRemoteBrokerHasConsumer() throws Exception { + // Setup broker networks + bridgeBrokers("BrokerA", "BrokerB"); - // Setup destination - Destination dest = createDestination("TEST.FOO", true); + startAllBrokers(); - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); - MessageConsumer clientB = createConsumer("BrokerB", dest); + // Setup destination + Destination dest = createDestination("TEST.FOO", true); - Thread.sleep(2000); - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); + // Setup consumers + MessageConsumer clientA = createConsumer("BrokerA", dest); + MessageConsumer clientB = createConsumer("BrokerB", dest); - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); + Thread.sleep(2000); + // Send messages + sendMessages("BrokerA", dest, MESSAGE_COUNT); - msgsA.waitForMessagesToArrive(MESSAGE_COUNT); - msgsB.waitForMessagesToArrive(MESSAGE_COUNT); + // Get message count + MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); + MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - assertEquals(MESSAGE_COUNT, msgsA.getMessageCount()); - assertEquals(MESSAGE_COUNT, msgsB.getMessageCount()); + msgsA.waitForMessagesToArrive(MESSAGE_COUNT); + msgsB.waitForMessagesToArrive(MESSAGE_COUNT); - } + assertEquals(MESSAGE_COUNT, msgsA.getMessageCount()); + assertEquals(MESSAGE_COUNT, msgsB.getMessageCount()); - /** - * BrokerA -> BrokerB - */ - public void testRemoteBrokerHasNoConsumer() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerA", "BrokerB"); + } - startAllBrokers(); + /** + * BrokerA -> BrokerB + */ + public void testRemoteBrokerHasNoConsumer() throws Exception { + // Setup broker networks + bridgeBrokers("BrokerA", "BrokerB"); - // Setup destination - Destination dest = createDestination("TEST.FOO", true); + startAllBrokers(); - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); + // Setup destination + Destination dest = createDestination("TEST.FOO", true); - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); + // Setup consumers + MessageConsumer clientA = createConsumer("BrokerA", dest); - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); + // Send messages + sendMessages("BrokerA", dest, MESSAGE_COUNT); - msgsA.waitForMessagesToArrive(MESSAGE_COUNT); + // Get message count + MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - assertEquals(MESSAGE_COUNT, msgsA.getMessageCount()); + msgsA.waitForMessagesToArrive(MESSAGE_COUNT); - } - - /** - * BrokerA -> BrokerB && BrokerB -> BrokerA - */ - public void testDuplexStaticRemoteBrokerHasNoConsumer() throws Exception { - // Setup broker networks - boolean dynamicOnly = true; - int networkTTL = 2; - boolean conduit = true; - bridgeBrokers("BrokerA", "BrokerB", dynamicOnly, networkTTL, conduit); - bridgeBrokers("BrokerB", "BrokerA", dynamicOnly, networkTTL, conduit); + assertEquals(MESSAGE_COUNT, msgsA.getMessageCount()); - startAllBrokers(); + } - // Setup destination - Destination dest = createDestination("TEST.FOO", false); + /** + * BrokerA -> BrokerB && BrokerB -> BrokerA + */ + public void testDuplexStaticRemoteBrokerHasNoConsumer() throws Exception { + // Setup broker networks + boolean dynamicOnly = true; + int networkTTL = 2; + boolean conduit = true; + bridgeBrokers("BrokerA", "BrokerB", dynamicOnly, networkTTL, conduit); + bridgeBrokers("BrokerB", "BrokerA", dynamicOnly, networkTTL, conduit); - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); + startAllBrokers(); - Thread.sleep(2*1000); - - int messageCount = 2000; - // Send messages - sendMessages("BrokerA", dest, messageCount); + // Setup destination + Destination dest = createDestination("TEST.FOO", false); - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); + // Setup consumers + MessageConsumer clientA = createConsumer("BrokerA", dest); - msgsA.waitForMessagesToArrive(messageCount); + Thread.sleep(2 * 1000); - assertEquals(messageCount, msgsA.getMessageCount()); + int messageCount = 2000; + // Send messages + sendMessages("BrokerA", dest, messageCount); - } + // Get message count + MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - createBroker(new URI( - "broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=false")); - createBroker(new URI( - "broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=false")); - } + msgsA.waitForMessagesToArrive(messageCount); + + assertEquals(messageCount, msgsA.getMessageCount()); + + } + + public void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); + createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=false")); + createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=false")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerMulticastQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerMulticastQueueTest.java index 4f196fb7e7..38f682a7e9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerMulticastQueueTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerMulticastQueueTest.java @@ -29,6 +29,7 @@ import javax.jms.Session; import javax.jms.TextMessage; import junit.framework.Test; + import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.CombinationTestSupport; import org.apache.activemq.broker.BrokerService; @@ -38,230 +39,234 @@ import org.apache.activemq.xbean.XBeanBrokerFactory; public class TwoBrokerMulticastQueueTest extends CombinationTestSupport { - public static final int MESSAGE_COUNT = 100; - public static final int BROKER_COUNT = 2; - public static final int CONSUMER_COUNT = 20; + public static final int MESSAGE_COUNT = 100; + public static final int BROKER_COUNT = 2; + public static final int CONSUMER_COUNT = 20; - public String sendUri; - public String recvUri; - private BrokerService[] brokers; - private String groupId; + public String sendUri; + public String recvUri; + private BrokerService[] brokers; + private String groupId; - public static Test suite() { - return suite(TwoBrokerMulticastQueueTest.class); - } + public static Test suite() { + return suite(TwoBrokerMulticastQueueTest.class); + } - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - public void setUp() throws Exception { - groupId = getClass().getName()+"-"+System.currentTimeMillis(); - System.setProperty("groupId", groupId); - super.setAutoFail(true); - super.setUp(); - } + public void setUp() throws Exception { + groupId = getClass().getName() + "-" + System.currentTimeMillis(); + System.setProperty("groupId", groupId); + super.setAutoFail(true); + super.setUp(); + } - public void tearDown() throws Exception { - if (brokers != null) { - for (int i = 0; i < BROKER_COUNT; i++) { - if (brokers[i] != null) { - brokers[i].stop(); - } + public void tearDown() throws Exception { + if (brokers != null) { + for (int i = 0; i < BROKER_COUNT; i++) { + if (brokers[i] != null) { + brokers[i].stop(); } - super.tearDown(); - } - } + } + super.tearDown(); + } + } - private void doSendReceiveTest() throws Exception { - Destination dest = new ActiveMQQueue("TEST.FOO"); + private void doSendReceiveTest() throws Exception { + Destination dest = new ActiveMQQueue("TEST.FOO"); - ConnectionFactory sendFactory = createConnectionFactory(sendUri); + ConnectionFactory sendFactory = createConnectionFactory(sendUri); - Connection conn = createConnection(sendFactory); - sendMessages(conn, dest, MESSAGE_COUNT); + Connection conn = createConnection(sendFactory); + sendMessages(conn, dest, MESSAGE_COUNT); - Thread.sleep(500); + Thread.sleep(500); - ConnectionFactory recvFactory = createConnectionFactory(recvUri); - assertEquals(MESSAGE_COUNT, receiveMessages(createConnection(recvFactory), dest, 0)); - } + ConnectionFactory recvFactory = createConnectionFactory(recvUri); + assertEquals(MESSAGE_COUNT, receiveMessages(createConnection(recvFactory), dest, 0)); + } - private void doMultipleConsumersConnectTest() throws Exception { - Destination dest = new ActiveMQQueue("TEST.FOO"); + private void doMultipleConsumersConnectTest() throws Exception { + Destination dest = new ActiveMQQueue("TEST.FOO"); - ConnectionFactory sendFactory = createConnectionFactory(sendUri); + ConnectionFactory sendFactory = createConnectionFactory(sendUri); - Connection conn = createConnection(sendFactory); - sendMessages(conn, dest, MESSAGE_COUNT); + Connection conn = createConnection(sendFactory); + sendMessages(conn, dest, MESSAGE_COUNT); - Thread.sleep(500); + Thread.sleep(500); - ConnectionFactory recvFactory = createConnectionFactory(recvUri); - assertEquals(MESSAGE_COUNT, receiveMessages(createConnection(recvFactory), dest, 0)); + ConnectionFactory recvFactory = createConnectionFactory(recvUri); + assertEquals(MESSAGE_COUNT, receiveMessages(createConnection(recvFactory), dest, 0)); - for (int i = 0; i < (CONSUMER_COUNT - 1); i++) { - assertEquals(0, receiveMessages(createConnection(recvFactory), dest, 200)); - } - } + for (int i = 0; i < (CONSUMER_COUNT - 1); i++) { + assertEquals(0, receiveMessages(createConnection(recvFactory), dest, 200)); + } + } - public void initCombosForTestSendReceive() { - addCombinationValues("sendUri", new Object[] {"tcp://localhost:61616", "tcp://localhost:61617"}); - addCombinationValues("recvUri", new Object[] {"tcp://localhost:61616", "tcp://localhost:61617"}); - } + public void initCombosForTestSendReceive() { + addCombinationValues("sendUri", new Object[]{"tcp://localhost:61616", "tcp://localhost:61617"}); + addCombinationValues("recvUri", new Object[]{"tcp://localhost:61616", "tcp://localhost:61617"}); + } - public void testSendReceive() throws Exception { - createMulticastBrokerNetwork(); - doSendReceiveTest(); - } + public void testSendReceive() throws Exception { + createMulticastBrokerNetwork(); + doSendReceiveTest(); + } - public void initCombosForTestMultipleConsumersConnect() { - addCombinationValues("sendUri", new Object[] {"tcp://localhost:61616", "tcp://localhost:61617"}); - addCombinationValues("recvUri", new Object[] {"tcp://localhost:61616", "tcp://localhost:61617"}); - } + public void initCombosForTestMultipleConsumersConnect() { + addCombinationValues("sendUri", new Object[]{"tcp://localhost:61616", "tcp://localhost:61617"}); + addCombinationValues("recvUri", new Object[]{"tcp://localhost:61616", "tcp://localhost:61617"}); + } - public void testMultipleConsumersConnect() throws Exception { - createMulticastBrokerNetwork(); - doMultipleConsumersConnectTest(); - } + public void testMultipleConsumersConnect() throws Exception { + createMulticastBrokerNetwork(); + doMultipleConsumersConnectTest(); + } - public void testSendReceiveUsingFailover() throws Exception { - sendUri = "failover:(tcp://localhost:61616,tcp://localhost:61617)"; - recvUri = "failover:(tcp://localhost:61616,tcp://localhost:61617)"; - createMulticastBrokerNetwork(); - doSendReceiveTest(); - } + public void testSendReceiveUsingFailover() throws Exception { + sendUri = "failover:(tcp://localhost:61616,tcp://localhost:61617)"; + recvUri = "failover:(tcp://localhost:61616,tcp://localhost:61617)"; + createMulticastBrokerNetwork(); + doSendReceiveTest(); + } - public void testMultipleConsumersConnectUsingFailover() throws Exception { - sendUri = "failover:(tcp://localhost:61616,tcp://localhost:61617)"; - recvUri = "failover:(tcp://localhost:61616,tcp://localhost:61617)"; - createMulticastBrokerNetwork(); - doMultipleConsumersConnectTest(); - } + public void testMultipleConsumersConnectUsingFailover() throws Exception { + sendUri = "failover:(tcp://localhost:61616,tcp://localhost:61617)"; + recvUri = "failover:(tcp://localhost:61616,tcp://localhost:61617)"; + createMulticastBrokerNetwork(); + doMultipleConsumersConnectTest(); + } - public void testSendReceiveUsingDiscovery() throws Exception { - sendUri = "discovery:multicast://default?group="+groupId; - recvUri = "discovery:multicast://default?group="+groupId; - createMulticastBrokerNetwork(); - doSendReceiveTest(); - } + public void testSendReceiveUsingDiscovery() throws Exception { + sendUri = "discovery:multicast://default?group=" + groupId; + recvUri = "discovery:multicast://default?group=" + groupId; + createMulticastBrokerNetwork(); + doSendReceiveTest(); + } - public void testMultipleConsumersConnectUsingDiscovery() throws Exception { - sendUri = "discovery:multicast://default?group="+groupId; - recvUri = "discovery:multicast://default?group="+groupId; - createMulticastBrokerNetwork(); - doMultipleConsumersConnectTest(); - } + public void testMultipleConsumersConnectUsingDiscovery() throws Exception { + sendUri = "discovery:multicast://default?group=" + groupId; + recvUri = "discovery:multicast://default?group=" + groupId; + createMulticastBrokerNetwork(); + doMultipleConsumersConnectTest(); + } - public void testSendReceiveUsingAutoAssignFailover() throws Exception { - sendUri = "failover:(discovery:multicast:default?group=//"+groupId+")"; - recvUri = "failover:(discovery:multicast:default?group=//"+groupId+")"; - createAutoAssignMulticastBrokerNetwork(); - doSendReceiveTest(); - } + public void testSendReceiveUsingAutoAssignFailover() throws Exception { + sendUri = "failover:(discovery:multicast:default?group=//" + groupId + ")"; + recvUri = "failover:(discovery:multicast:default?group=//" + groupId + ")"; + createAutoAssignMulticastBrokerNetwork(); + doSendReceiveTest(); + } - public void testMultipleConsumersConnectUsingAutoAssignFailover() throws Exception { - sendUri = "failover:(discovery:multicast:default?group=//"+groupId+")"; - recvUri = "failover:(discovery:multicast:default?group=//"+groupId+")"; - createAutoAssignMulticastBrokerNetwork(); - doMultipleConsumersConnectTest(); - } + public void testMultipleConsumersConnectUsingAutoAssignFailover() throws Exception { + sendUri = "failover:(discovery:multicast:default?group=//" + groupId + ")"; + recvUri = "failover:(discovery:multicast:default?group=//" + groupId + ")"; + createAutoAssignMulticastBrokerNetwork(); + doMultipleConsumersConnectTest(); + } - public void testSendReceiveUsingAutoAssignDiscovery() throws Exception { - sendUri = "discovery:multicast://default?group="+groupId; - recvUri = "discovery:multicast://default?group="+groupId; - createAutoAssignMulticastBrokerNetwork(); - doSendReceiveTest(); - } + public void testSendReceiveUsingAutoAssignDiscovery() throws Exception { + sendUri = "discovery:multicast://default?group=" + groupId; + recvUri = "discovery:multicast://default?group=" + groupId; + createAutoAssignMulticastBrokerNetwork(); + doSendReceiveTest(); + } - public void testMultipleConsumersConnectUsingAutoAssignDiscovery() throws Exception { - sendUri = "discovery:multicast://default?group="+groupId; - recvUri = "discovery:multicast://default?group="+groupId; - createAutoAssignMulticastBrokerNetwork(); - doMultipleConsumersConnectTest(); - } + public void testMultipleConsumersConnectUsingAutoAssignDiscovery() throws Exception { + sendUri = "discovery:multicast://default?group=" + groupId; + recvUri = "discovery:multicast://default?group=" + groupId; + createAutoAssignMulticastBrokerNetwork(); + doMultipleConsumersConnectTest(); + } - protected void createMulticastBrokerNetwork() throws Exception { - brokers = new BrokerService[BROKER_COUNT]; - for (int i = 0; i < BROKER_COUNT; i++) { - brokers[i] = createBroker("org/apache/activemq/usecases/multicast-broker-" + (i + 1) + ".xml"); - brokers[i].start(); - } + protected void createMulticastBrokerNetwork() throws Exception { + brokers = new BrokerService[BROKER_COUNT]; + for (int i = 0; i < BROKER_COUNT; i++) { + brokers[i] = createBroker("org/apache/activemq/usecases/multicast-broker-" + (i + 1) + ".xml"); + brokers[i].start(); + } - // Let the brokers discover each other first - Thread.sleep(1000); - } + // Let the brokers discover each other first + Thread.sleep(1000); + } - protected void createAutoAssignMulticastBrokerNetwork() throws Exception { - brokers = new BrokerService[BROKER_COUNT]; - for (int i = 0; i < BROKER_COUNT; i++) { - brokers[i] = createBroker("org/apache/activemq/usecases/multicast-broker-auto.xml"); - brokers[i].start(); - } + protected void createAutoAssignMulticastBrokerNetwork() throws Exception { + brokers = new BrokerService[BROKER_COUNT]; + for (int i = 0; i < BROKER_COUNT; i++) { + brokers[i] = createBroker("org/apache/activemq/usecases/multicast-broker-auto.xml"); + brokers[i].start(); + } - // Let the brokers discover each other first - Thread.sleep(1000); - } + // Let the brokers discover each other first + Thread.sleep(1000); + } - protected BrokerService createBroker(String uri) throws Exception { - return (new XBeanBrokerFactory()).createBroker(new URI(uri)); - } + protected BrokerService createBroker(String uri) throws Exception { + return (new XBeanBrokerFactory()).createBroker(new URI(uri)); + } - protected ConnectionFactory createConnectionFactory(String uri) { - return new ActiveMQConnectionFactory(uri); - } + protected ConnectionFactory createConnectionFactory(String uri) { + return new ActiveMQConnectionFactory(uri); + } - protected Connection createConnection(ConnectionFactory factory) throws JMSException { - Connection conn = factory.createConnection(); - return conn; - } + protected Connection createConnection(ConnectionFactory factory) throws JMSException { + Connection conn = factory.createConnection(); + return conn; + } - protected int receiveMessages(Connection conn, Destination dest, int waitTime) throws JMSException, InterruptedException { - conn.start(); - MessageIdList list = new MessageIdList(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = sess.createConsumer(dest); - consumer.setMessageListener(list); + protected int receiveMessages(Connection conn, + Destination dest, + int waitTime) throws JMSException, InterruptedException { + conn.start(); + MessageIdList list = new MessageIdList(); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = sess.createConsumer(dest); + consumer.setMessageListener(list); - if (waitTime > 0) { - Thread.sleep(waitTime); - } else { - list.waitForMessagesToArrive(MESSAGE_COUNT); - } + if (waitTime > 0) { + Thread.sleep(waitTime); + } + else { + list.waitForMessagesToArrive(MESSAGE_COUNT); + } - conn.close(); + conn.close(); - return list.getMessageCount(); - } + return list.getMessageCount(); + } - protected void sendMessages(Connection conn, Destination dest, int count) throws JMSException { - conn.start(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer prod = sess.createProducer(dest); + protected void sendMessages(Connection conn, Destination dest, int count) throws JMSException { + conn.start(); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer prod = sess.createProducer(dest); - for (int i = 0; i < count; i++) { - prod.send(createTextMessage(sess, "Message " + i, 1024)); - } + for (int i = 0; i < count; i++) { + prod.send(createTextMessage(sess, "Message " + i, 1024)); + } - conn.close(); - } + conn.close(); + } - protected TextMessage createTextMessage(Session session, String initText, int messageSize) throws JMSException { - TextMessage msg = session.createTextMessage(); + protected TextMessage createTextMessage(Session session, String initText, int messageSize) throws JMSException { + TextMessage msg = session.createTextMessage(); - // Pad message text - if (initText.length() < messageSize) { - char[] data = new char[messageSize - initText.length()]; - Arrays.fill(data, '*'); - String str = new String(data); - msg.setText(initText + str); + // Pad message text + if (initText.length() < messageSize) { + char[] data = new char[messageSize - initText.length()]; + Arrays.fill(data, '*'); + String str = new String(data); + msg.setText(initText + str); - // Do not pad message text - } else { - msg.setText(initText); - } + // Do not pad message text + } + else { + msg.setText(initText); + } - return msg; - } + return msg; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerNetworkConnectorWildcardDynamicallyIncludedDestinationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerNetworkConnectorWildcardDynamicallyIncludedDestinationTest.java index d6d0d65ad5..ef39719e92 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerNetworkConnectorWildcardDynamicallyIncludedDestinationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerNetworkConnectorWildcardDynamicallyIncludedDestinationTest.java @@ -20,14 +20,14 @@ import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.network.NetworkConnector; public class TwoBrokerNetworkConnectorWildcardDynamicallyIncludedDestinationTest extends AbstractTwoBrokerNetworkConnectorWildcardIncludedDestinationTestSupport { - - protected void addIncludedDestination(NetworkConnector nc) { - nc.addExcludedDestination(ActiveMQDestination.createDestination("local.>", ActiveMQDestination.QUEUE_TYPE)); - nc.addExcludedDestination(ActiveMQDestination.createDestination("local.>", ActiveMQDestination.TOPIC_TYPE)); - nc.addExcludedDestination(ActiveMQDestination.createDestination("Consumer.*.local.>", ActiveMQDestination.QUEUE_TYPE)); - nc.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.QUEUE_TYPE)); - nc.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.TOPIC_TYPE)); - nc.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("Consumer.*.global.>", ActiveMQDestination.QUEUE_TYPE)); - } - + + protected void addIncludedDestination(NetworkConnector nc) { + nc.addExcludedDestination(ActiveMQDestination.createDestination("local.>", ActiveMQDestination.QUEUE_TYPE)); + nc.addExcludedDestination(ActiveMQDestination.createDestination("local.>", ActiveMQDestination.TOPIC_TYPE)); + nc.addExcludedDestination(ActiveMQDestination.createDestination("Consumer.*.local.>", ActiveMQDestination.QUEUE_TYPE)); + nc.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.QUEUE_TYPE)); + nc.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.TOPIC_TYPE)); + nc.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("Consumer.*.global.>", ActiveMQDestination.QUEUE_TYPE)); + } + } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerNetworkConnectorWildcardStaticallyIncludedDestinationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerNetworkConnectorWildcardStaticallyIncludedDestinationTest.java index a8051db4f8..9d1c4efd9f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerNetworkConnectorWildcardStaticallyIncludedDestinationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerNetworkConnectorWildcardStaticallyIncludedDestinationTest.java @@ -20,14 +20,14 @@ import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.network.NetworkConnector; public class TwoBrokerNetworkConnectorWildcardStaticallyIncludedDestinationTest extends AbstractTwoBrokerNetworkConnectorWildcardIncludedDestinationTestSupport { - - protected void addIncludedDestination(NetworkConnector nc) { - nc.addExcludedDestination(ActiveMQDestination.createDestination("local.>", ActiveMQDestination.QUEUE_TYPE)); - nc.addExcludedDestination(ActiveMQDestination.createDestination("local.>", ActiveMQDestination.TOPIC_TYPE)); - nc.addExcludedDestination(ActiveMQDestination.createDestination("Consumer.*.local.>", ActiveMQDestination.QUEUE_TYPE)); - nc.addStaticallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.QUEUE_TYPE)); - nc.addStaticallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.TOPIC_TYPE)); - nc.addStaticallyIncludedDestination(ActiveMQDestination.createDestination("Consumer.*.global.>", ActiveMQDestination.QUEUE_TYPE)); - } - + + protected void addIncludedDestination(NetworkConnector nc) { + nc.addExcludedDestination(ActiveMQDestination.createDestination("local.>", ActiveMQDestination.QUEUE_TYPE)); + nc.addExcludedDestination(ActiveMQDestination.createDestination("local.>", ActiveMQDestination.TOPIC_TYPE)); + nc.addExcludedDestination(ActiveMQDestination.createDestination("Consumer.*.local.>", ActiveMQDestination.QUEUE_TYPE)); + nc.addStaticallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.QUEUE_TYPE)); + nc.addStaticallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.TOPIC_TYPE)); + nc.addStaticallyIncludedDestination(ActiveMQDestination.createDestination("Consumer.*.global.>", ActiveMQDestination.QUEUE_TYPE)); + } + } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerNetworkLoadBalanceTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerNetworkLoadBalanceTest.java index e773db288b..24212ce2a2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerNetworkLoadBalanceTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerNetworkLoadBalanceTest.java @@ -28,50 +28,51 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TwoBrokerNetworkLoadBalanceTest extends JmsMultipleBrokersTestSupport { - protected static final Logger LOG = LoggerFactory.getLogger(TwoBrokerNetworkLoadBalanceTest.class); - public void testLoadBalancing() throws Exception { - bridgeBrokers("BrokerA", "BrokerB"); - bridgeBrokers("BrokerB", "BrokerA"); - startAllBrokers(); - waitForBridgeFormation(); + protected static final Logger LOG = LoggerFactory.getLogger(TwoBrokerNetworkLoadBalanceTest.class); - // Setup destination - Destination dest = createDestination("TEST.FOO", false); + public void testLoadBalancing() throws Exception { + bridgeBrokers("BrokerA", "BrokerB"); + bridgeBrokers("BrokerB", "BrokerA"); - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); + startAllBrokers(); + waitForBridgeFormation(); - // Setup consumers - MessageConsumer clientB = createConsumer("BrokerB", dest); - - // Send messages - sendMessages("BrokerA", dest, 5000); + // Setup destination + Destination dest = createDestination("TEST.FOO", false); - // Send messages - sendMessages("BrokerB", dest, 1000); + // Setup consumers + MessageConsumer clientA = createConsumer("BrokerA", dest); - // Get message count - final MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - final MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); + // Setup consumers + MessageConsumer clientB = createConsumer("BrokerB", dest); - Wait.waitFor(new Wait.Condition() { - public boolean isSatisified() throws Exception { - return msgsA.getMessageCount() + msgsB.getMessageCount() == 6000; - }}); - - LOG.info("A got: " + msgsA.getMessageCount()); - LOG.info("B got: " + msgsB.getMessageCount()); - - assertTrue("B got is fair share: " + msgsB.getMessageCount(), msgsB.getMessageCount() > 2000); - } - - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - createBroker(new URI( - "broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=false")); - createBroker(new URI( - "broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=false")); - } + // Send messages + sendMessages("BrokerA", dest, 5000); + + // Send messages + sendMessages("BrokerB", dest, 1000); + + // Get message count + final MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); + final MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); + + Wait.waitFor(new Wait.Condition() { + public boolean isSatisified() throws Exception { + return msgsA.getMessageCount() + msgsB.getMessageCount() == 6000; + } + }); + + LOG.info("A got: " + msgsA.getMessageCount()); + LOG.info("B got: " + msgsB.getMessageCount()); + + assertTrue("B got is fair share: " + msgsB.getMessageCount(), msgsB.getMessageCount() > 2000); + } + + public void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); + createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=false")); + createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=false")); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerQueueClientsReconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerQueueClientsReconnectTest.java index 9adc2a3884..e78ab2f3d9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerQueueClientsReconnectTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerQueueClientsReconnectTest.java @@ -51,556 +51,556 @@ import org.slf4j.LoggerFactory; * */ public class TwoBrokerQueueClientsReconnectTest extends JmsMultipleBrokersTestSupport { - protected static final int MESSAGE_COUNT = 100; // Best if a factor of 100 - protected static final int PREFETCH_COUNT = 1; - protected static final int NETWORK_PREFETCH = 1; - private static final Logger LOG = LoggerFactory.getLogger(TwoBrokerQueueClientsReconnectTest.class); + protected static final int MESSAGE_COUNT = 100; // Best if a factor of 100 + protected static final int PREFETCH_COUNT = 1; + protected static final int NETWORK_PREFETCH = 1; + private static final Logger LOG = LoggerFactory.getLogger(TwoBrokerQueueClientsReconnectTest.class); - protected int msgsClient1; - protected int msgsClient2; - protected String broker1; - protected String broker2; + protected int msgsClient1; + protected int msgsClient2; + protected String broker1; + protected String broker2; - public void testClientAReceivesOnly() throws Exception { - broker1 = "BrokerA"; - broker2 = "BrokerB"; + public void testClientAReceivesOnly() throws Exception { + broker1 = "BrokerA"; + broker2 = "BrokerB"; - doOneClientReceivesOnly(); - } + doOneClientReceivesOnly(); + } - public void testClientBReceivesOnly() throws Exception { - broker1 = "BrokerB"; - broker2 = "BrokerA"; + public void testClientBReceivesOnly() throws Exception { + broker1 = "BrokerB"; + broker2 = "BrokerA"; - doOneClientReceivesOnly(); - } + doOneClientReceivesOnly(); + } - public void doOneClientReceivesOnly() throws Exception { - // allow immediate replay back to origin - applyRateLimitNetworkFilter(0); + public void doOneClientReceivesOnly() throws Exception { + // allow immediate replay back to origin + applyRateLimitNetworkFilter(0); - // Bridge brokers - bridgeBrokers(broker1, broker2); - bridgeBrokers(broker2, broker1); + // Bridge brokers + bridgeBrokers(broker1, broker2); + bridgeBrokers(broker2, broker1); - // Run brokers - startAllBrokers(); + // Run brokers + startAllBrokers(); - // Create queue - Destination dest = createDestination("TEST.FOO", false); + // Create queue + Destination dest = createDestination("TEST.FOO", false); - // Create consumers - MessageConsumer client1 = createConsumer(broker1, dest); - MessageConsumer client2 = createConsumer(broker2, dest); + // Create consumers + MessageConsumer client1 = createConsumer(broker1, dest); + MessageConsumer client2 = createConsumer(broker2, dest); - // Give clients time to register with broker - Thread.sleep(500); + // Give clients time to register with broker + Thread.sleep(500); - // Always send messages to broker A - sendMessages("BrokerA", dest, MESSAGE_COUNT); + // Always send messages to broker A + sendMessages("BrokerA", dest, MESSAGE_COUNT); - // Close the second client, messages should be sent to the first client - client2.close(); + // Close the second client, messages should be sent to the first client + client2.close(); - // Let the first client receive all messages - msgsClient1 += receiveAllMessages(client1); - client1.close(); + // Let the first client receive all messages + msgsClient1 += receiveAllMessages(client1); + client1.close(); - // First client should have received 100 messages - assertEquals("Client for " + broker1 + " should have receive all messages.", MESSAGE_COUNT, msgsClient1); - } + // First client should have received 100 messages + assertEquals("Client for " + broker1 + " should have receive all messages.", MESSAGE_COUNT, msgsClient1); + } - public void testClientAReceivesOnlyAfterReconnect() throws Exception { - broker1 = "BrokerA"; - broker2 = "BrokerB"; + public void testClientAReceivesOnlyAfterReconnect() throws Exception { + broker1 = "BrokerA"; + broker2 = "BrokerB"; - doOneClientReceivesOnlyAfterReconnect(); - } + doOneClientReceivesOnlyAfterReconnect(); + } - public void testClientBReceivesOnlyAfterReconnect() throws Exception { - broker1 = "BrokerB"; - broker2 = "BrokerA"; + public void testClientBReceivesOnlyAfterReconnect() throws Exception { + broker1 = "BrokerB"; + broker2 = "BrokerA"; - doOneClientReceivesOnlyAfterReconnect(); - } + doOneClientReceivesOnlyAfterReconnect(); + } - public void doOneClientReceivesOnlyAfterReconnect() throws Exception { - // allow immediate replay back to origin - applyRateLimitNetworkFilter(0); + public void doOneClientReceivesOnlyAfterReconnect() throws Exception { + // allow immediate replay back to origin + applyRateLimitNetworkFilter(0); - // Bridge brokers - bridgeBrokers(broker1, broker2); - bridgeBrokers(broker2, broker1); + // Bridge brokers + bridgeBrokers(broker1, broker2); + bridgeBrokers(broker2, broker1); - // Run brokers - startAllBrokers(); + // Run brokers + startAllBrokers(); - // Create queue - Destination dest = createDestination("TEST.FOO", false); + // Create queue + Destination dest = createDestination("TEST.FOO", false); - // Create first consumer - MessageConsumer client1 = createConsumer(broker1, dest); - MessageConsumer client2 = createConsumer(broker2, dest); + // Create first consumer + MessageConsumer client1 = createConsumer(broker1, dest); + MessageConsumer client2 = createConsumer(broker2, dest); - // Give clients time to register with broker - Thread.sleep(500); + // Give clients time to register with broker + Thread.sleep(500); - // Always send message to broker A - sendMessages("BrokerA", dest, MESSAGE_COUNT); + // Always send message to broker A + sendMessages("BrokerA", dest, MESSAGE_COUNT); - // Let the first client receive the first 20% of messages - msgsClient1 += receiveExactMessages(client1, (int)(MESSAGE_COUNT * 0.20)); + // Let the first client receive the first 20% of messages + msgsClient1 += receiveExactMessages(client1, (int) (MESSAGE_COUNT * 0.20)); - // Disconnect the first client - client1.close(); + // Disconnect the first client + client1.close(); - // Create another client for the first broker - client1 = createConsumer(broker1, dest); - Thread.sleep(500); + // Create another client for the first broker + client1 = createConsumer(broker1, dest); + Thread.sleep(500); - // Close the second client, messages should be sent to the first client - client2.close(); + // Close the second client, messages should be sent to the first client + client2.close(); - // Receive the rest of the messages - msgsClient1 += receiveAllMessages(client1); - client1.close(); + // Receive the rest of the messages + msgsClient1 += receiveAllMessages(client1); + client1.close(); - // The first client should have received 100 messages - assertEquals("Client for " + broker1 + " should have received all messages.", MESSAGE_COUNT, msgsClient1); - } + // The first client should have received 100 messages + assertEquals("Client for " + broker1 + " should have received all messages.", MESSAGE_COUNT, msgsClient1); + } - public void testTwoClientsReceiveClientADisconnects() throws Exception { - broker1 = "BrokerA"; - broker2 = "BrokerB"; + public void testTwoClientsReceiveClientADisconnects() throws Exception { + broker1 = "BrokerA"; + broker2 = "BrokerB"; - doTwoClientsReceiveOneClientDisconnects(); - } + doTwoClientsReceiveOneClientDisconnects(); + } - public void testTwoClientsReceiveClientBDisconnects() throws Exception { - broker1 = "BrokerB"; - broker2 = "BrokerA"; + public void testTwoClientsReceiveClientBDisconnects() throws Exception { + broker1 = "BrokerB"; + broker2 = "BrokerA"; - doTwoClientsReceiveOneClientDisconnects(); - } + doTwoClientsReceiveOneClientDisconnects(); + } - public void doTwoClientsReceiveOneClientDisconnects() throws Exception { - // ensure all message do not flow across the network too quickly - applyRateLimitNetworkFilter(0.8 * MESSAGE_COUNT); + public void doTwoClientsReceiveOneClientDisconnects() throws Exception { + // ensure all message do not flow across the network too quickly + applyRateLimitNetworkFilter(0.8 * MESSAGE_COUNT); - // Bridge brokers - bridgeBrokers(broker1, broker2); - bridgeBrokers(broker2, broker1); + // Bridge brokers + bridgeBrokers(broker1, broker2); + bridgeBrokers(broker2, broker1); - // Run brokers - startAllBrokers(); + // Run brokers + startAllBrokers(); - // Create queue - Destination dest = createDestination("TEST.FOO", false); + // Create queue + Destination dest = createDestination("TEST.FOO", false); - // Create first client - MessageConsumer client1 = createConsumer(broker1, dest); - MessageConsumer client2 = createConsumer(broker2, dest); + // Create first client + MessageConsumer client1 = createConsumer(broker1, dest); + MessageConsumer client2 = createConsumer(broker2, dest); - // Give clients time to register with broker - Thread.sleep(500); + // Give clients time to register with broker + Thread.sleep(500); - // Always send messages to broker A - sendMessages("BrokerA", dest, MESSAGE_COUNT); + // Always send messages to broker A + sendMessages("BrokerA", dest, MESSAGE_COUNT); - LOG.info("Let each client receive 20% of the messages - 40% total"); - msgsClient1 += receiveExactMessages(client1, (int)(MESSAGE_COUNT * 0.20)); - msgsClient2 += receiveExactMessages(client2, (int)(MESSAGE_COUNT * 0.20)); + LOG.info("Let each client receive 20% of the messages - 40% total"); + msgsClient1 += receiveExactMessages(client1, (int) (MESSAGE_COUNT * 0.20)); + msgsClient2 += receiveExactMessages(client2, (int) (MESSAGE_COUNT * 0.20)); - // Disconnect the first client - client1.close(); + // Disconnect the first client + client1.close(); - LOG.info("Let the second client receive the rest of the messages"); - msgsClient2 += receiveAllMessages(client2); - client2.close(); + LOG.info("Let the second client receive the rest of the messages"); + msgsClient2 += receiveAllMessages(client2); + client2.close(); - // First client should have received 20% of the messages - assertEquals("Client for " + broker1 + " should have received 20% of the messages.", (int)(MESSAGE_COUNT * 0.20), msgsClient1); + // First client should have received 20% of the messages + assertEquals("Client for " + broker1 + " should have received 20% of the messages.", (int) (MESSAGE_COUNT * 0.20), msgsClient1); - // Second client should have received 80% of the messages - assertEquals("Client for " + broker2 + " should have received 80% of the messages.", (int)(MESSAGE_COUNT * 0.80), msgsClient2); - } + // Second client should have received 80% of the messages + assertEquals("Client for " + broker2 + " should have received 80% of the messages.", (int) (MESSAGE_COUNT * 0.80), msgsClient2); + } - public void testTwoClientsReceiveClientAReconnects() throws Exception { - broker1 = "BrokerA"; - broker2 = "BrokerB"; + public void testTwoClientsReceiveClientAReconnects() throws Exception { + broker1 = "BrokerA"; + broker2 = "BrokerB"; - doTwoClientsReceiveOneClientReconnects(); - } + doTwoClientsReceiveOneClientReconnects(); + } - public void testTwoClientsReceiveClientBReconnects() throws Exception { - broker1 = "BrokerB"; - broker2 = "BrokerA"; + public void testTwoClientsReceiveClientBReconnects() throws Exception { + broker1 = "BrokerB"; + broker2 = "BrokerA"; - doTwoClientsReceiveOneClientReconnects(); - } + doTwoClientsReceiveOneClientReconnects(); + } - public void doTwoClientsReceiveOneClientReconnects() throws Exception { - // ensure all message do not flow across the network too quickly - applyRateLimitNetworkFilter(0.2 * MESSAGE_COUNT); + public void doTwoClientsReceiveOneClientReconnects() throws Exception { + // ensure all message do not flow across the network too quickly + applyRateLimitNetworkFilter(0.2 * MESSAGE_COUNT); - // Bridge brokers - bridgeBrokers(broker1, broker2); - bridgeBrokers(broker2, broker1); + // Bridge brokers + bridgeBrokers(broker1, broker2); + bridgeBrokers(broker2, broker1); - // Run brokers - startAllBrokers(); + // Run brokers + startAllBrokers(); - // Create queue - Destination dest = createDestination("TEST.FOO", false); + // Create queue + Destination dest = createDestination("TEST.FOO", false); - // Create the first client - MessageConsumer client1 = createConsumer(broker1, dest); - MessageConsumer client2 = createConsumer(broker2, dest); + // Create the first client + MessageConsumer client1 = createConsumer(broker1, dest); + MessageConsumer client2 = createConsumer(broker2, dest); - // Give clients time to register with broker - Thread.sleep(500); + // Give clients time to register with broker + Thread.sleep(500); - // Always send messages to broker A - sendMessages("BrokerA", dest, MESSAGE_COUNT); + // Always send messages to broker A + sendMessages("BrokerA", dest, MESSAGE_COUNT); - // Let each client receive 20% of the messages - 40% total - msgsClient1 += receiveExactMessages(client1, (int)(MESSAGE_COUNT * 0.20)); - msgsClient2 += receiveExactMessages(client2, (int)(MESSAGE_COUNT * 0.20)); + // Let each client receive 20% of the messages - 40% total + msgsClient1 += receiveExactMessages(client1, (int) (MESSAGE_COUNT * 0.20)); + msgsClient2 += receiveExactMessages(client2, (int) (MESSAGE_COUNT * 0.20)); - LOG.info("msgsClient1=" + msgsClient1); - LOG.info("msgsClient2=" + msgsClient2); + LOG.info("msgsClient1=" + msgsClient1); + LOG.info("msgsClient2=" + msgsClient2); - Thread.sleep(1000); - LOG.info("Disconnect the first client"); - client1.close(); + Thread.sleep(1000); + LOG.info("Disconnect the first client"); + client1.close(); - LOG.info("Let the second client receive 20% more of the total messages"); - msgsClient2 += receiveExactMessages(client2, (int)(MESSAGE_COUNT * 0.20)); + LOG.info("Let the second client receive 20% more of the total messages"); + msgsClient2 += receiveExactMessages(client2, (int) (MESSAGE_COUNT * 0.20)); - LOG.info("msgsClient2=" + msgsClient2); + LOG.info("msgsClient2=" + msgsClient2); - // Create another client for broker 1 - client1 = createConsumer(broker1, dest); - Thread.sleep(1000); + // Create another client for broker 1 + client1 = createConsumer(broker1, dest); + Thread.sleep(1000); - // Let each client receive 20% of the messages - 40% total - msgsClient1 += receiveExactMessages(client1, (int)(MESSAGE_COUNT * 0.20)); - client1.close(); - LOG.info("new consumer addition, msgsClient1=" + msgsClient1); + // Let each client receive 20% of the messages - 40% total + msgsClient1 += receiveExactMessages(client1, (int) (MESSAGE_COUNT * 0.20)); + client1.close(); + LOG.info("new consumer addition, msgsClient1=" + msgsClient1); - Thread.sleep(2000); - msgsClient2 += receiveExactMessages(client2, (int)(MESSAGE_COUNT * 0.20)); - client2.close(); - LOG.info("msgsClient2=" + msgsClient2); + Thread.sleep(2000); + msgsClient2 += receiveExactMessages(client2, (int) (MESSAGE_COUNT * 0.20)); + client2.close(); + LOG.info("msgsClient2=" + msgsClient2); - // First client should have received 40 messages - assertEquals("Client for " + broker1 + " should have received 40% of the messages.", (int)(MESSAGE_COUNT * 0.40), msgsClient1); - - // Second client should have received 60 messages - assertEquals("Client for " + broker2 + " should have received 60% of the messages.", (int)(MESSAGE_COUNT * 0.60), msgsClient2); - } - - private void applyRateLimitNetworkFilter(double rateLimit) { - ConditionalNetworkBridgeFilterFactory filterFactory = new ConditionalNetworkBridgeFilterFactory(); - filterFactory.setReplayWhenNoConsumers(true); - filterFactory.setRateLimit((int) rateLimit); - filterFactory.setRateDuration(1000); - - Collection brokerList = brokers.values(); - for (Iterator i = brokerList.iterator(); i.hasNext();) { - BrokerService broker = i.next().broker; - broker.getDestinationPolicy().getDefaultEntry().setNetworkBridgeFilterFactory(filterFactory); - } - } - - public void testTwoClientsReceiveTwoClientReconnects() throws Exception { - // ensure all message do not flow across the network too quickly - applyRateLimitNetworkFilter(0.5 * MESSAGE_COUNT); - - broker1 = "BrokerA"; - broker2 = "BrokerB"; - - // Bridge brokers - bridgeBrokers(broker1, broker2); - bridgeBrokers(broker2, broker1); - - // Run brokers - startAllBrokers(); - - // Create queue - Destination dest = createDestination("TEST.FOO", false); - - // Create the first client - MessageConsumer client1 = createConsumer(broker1, dest); - MessageConsumer client2 = createConsumer(broker2, dest); - - // Give clients time to register with broker - Thread.sleep(500); - - // Always send messages to broker A - sendMessages("BrokerA", dest, MESSAGE_COUNT); - - // Let each client receive 20% of the messages - 40% total - msgsClient1 += receiveExactMessages(client1, (int)(MESSAGE_COUNT * 0.20)); - msgsClient2 += receiveExactMessages(client2, (int)(MESSAGE_COUNT * 0.20)); - - LOG.info("Disconnect both clients"); - client1.close(); - client2.close(); - - // Let each client receive 30% more of the total messages - 60% total - LOG.info("Serially create another two clients for each broker and consume in turn"); - client1 = createConsumer(broker1, dest); - msgsClient1 += receiveExactMessages(client1, (int)(MESSAGE_COUNT * 0.30)); - client1.close(); - - // the close will allow replay or the replay of the remaining messages - client2 = createConsumer(broker2, dest); - msgsClient2 += receiveExactMessages(client2, (int)(MESSAGE_COUNT * 0.30)); - client2.close(); - - // First client should have received 50% of the messages - assertEquals("Client for " + broker1 + " should have received 50% of the messages.", (int)(MESSAGE_COUNT * 0.50), msgsClient1); - - // Second client should have received 50% of the messages - assertEquals("Client for " + broker2 + " should have received 50% of the messages.", (int)(MESSAGE_COUNT * 0.50), msgsClient2); - } - - @SuppressWarnings("unchecked") - public void testDuplicateSend() throws Exception { - broker1 = "BrokerA"; - broker2 = "BrokerB"; - - // enable producer audit for the network connector, off by default b/c of interference with composite - // dests and virtual topics - brokers.get(broker2).broker.getTransportConnectors().get(0).setAuditNetworkProducers(true); - bridgeBrokers(broker1, broker2); - - final AtomicBoolean first = new AtomicBoolean(); - final CountDownLatch gotMessageLatch = new CountDownLatch(1); - - BrokerService brokerService = brokers.get(broker2).broker; - brokerService.setPersistent(true); - brokerService.setDeleteAllMessagesOnStartup(true); - brokerService.setPlugins(new BrokerPlugin[]{ - new BrokerPluginSupport() { - @Override - public void send(final ProducerBrokerExchange producerExchange, - org.apache.activemq.command.Message messageSend) - throws Exception { - super.send(producerExchange, messageSend); - if (first.compareAndSet(false, true)) { - producerExchange.getConnectionContext().setDontSendReponse(true); - Executors.newSingleThreadExecutor().execute(new Runnable() { - @Override - public void run() { - try { - LOG.info("Waiting for recepit"); - assertTrue("message received on time", gotMessageLatch.await(60, TimeUnit.SECONDS)); - LOG.info("Stopping connection post send and receive and multiple producers"); - producerExchange.getConnectionContext().getConnection().stop(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - } - } - } - }); - - // Run brokers - startAllBrokers(); - - waitForBridgeFormation(); - - // Create queue - Destination dest = createDestination("TEST.FOO", false); - - MessageConsumer client2 = createConsumer(broker2, dest); - - sendMessages("BrokerA", dest, 1); - - assertEquals("Client got message", 1, receiveExactMessages(client2, 1)); - client2.close(); - gotMessageLatch.countDown(); - - // message still pending on broker1 - assertEquals("messages message still there", 1, brokers.get(broker1).broker.getAdminView().getTotalMessageCount()); - - client2 = createConsumer(broker2, dest); - - LOG.info("Let the second client receive the rest of the messages"); - assertEquals("no duplicate message", 0, receiveAllMessages(client2)); - assertEquals("no duplicate message", 0, receiveAllMessages(client2)); - - assertEquals("no messages enqueued", 0, brokers.get(broker2).broker.getAdminView().getTotalMessageCount()); - assertTrue("no messages enqueued on origin", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return 0 == brokers.get(broker1).broker.getAdminView().getTotalMessageCount(); + // First client should have received 40 messages + assertEquals("Client for " + broker1 + " should have received 40% of the messages.", (int) (MESSAGE_COUNT * 0.40), msgsClient1); + + // Second client should have received 60 messages + assertEquals("Client for " + broker2 + " should have received 60% of the messages.", (int) (MESSAGE_COUNT * 0.60), msgsClient2); + } + + private void applyRateLimitNetworkFilter(double rateLimit) { + ConditionalNetworkBridgeFilterFactory filterFactory = new ConditionalNetworkBridgeFilterFactory(); + filterFactory.setReplayWhenNoConsumers(true); + filterFactory.setRateLimit((int) rateLimit); + filterFactory.setRateDuration(1000); + + Collection brokerList = brokers.values(); + for (Iterator i = brokerList.iterator(); i.hasNext(); ) { + BrokerService broker = i.next().broker; + broker.getDestinationPolicy().getDefaultEntry().setNetworkBridgeFilterFactory(filterFactory); + } + } + + public void testTwoClientsReceiveTwoClientReconnects() throws Exception { + // ensure all message do not flow across the network too quickly + applyRateLimitNetworkFilter(0.5 * MESSAGE_COUNT); + + broker1 = "BrokerA"; + broker2 = "BrokerB"; + + // Bridge brokers + bridgeBrokers(broker1, broker2); + bridgeBrokers(broker2, broker1); + + // Run brokers + startAllBrokers(); + + // Create queue + Destination dest = createDestination("TEST.FOO", false); + + // Create the first client + MessageConsumer client1 = createConsumer(broker1, dest); + MessageConsumer client2 = createConsumer(broker2, dest); + + // Give clients time to register with broker + Thread.sleep(500); + + // Always send messages to broker A + sendMessages("BrokerA", dest, MESSAGE_COUNT); + + // Let each client receive 20% of the messages - 40% total + msgsClient1 += receiveExactMessages(client1, (int) (MESSAGE_COUNT * 0.20)); + msgsClient2 += receiveExactMessages(client2, (int) (MESSAGE_COUNT * 0.20)); + + LOG.info("Disconnect both clients"); + client1.close(); + client2.close(); + + // Let each client receive 30% more of the total messages - 60% total + LOG.info("Serially create another two clients for each broker and consume in turn"); + client1 = createConsumer(broker1, dest); + msgsClient1 += receiveExactMessages(client1, (int) (MESSAGE_COUNT * 0.30)); + client1.close(); + + // the close will allow replay or the replay of the remaining messages + client2 = createConsumer(broker2, dest); + msgsClient2 += receiveExactMessages(client2, (int) (MESSAGE_COUNT * 0.30)); + client2.close(); + + // First client should have received 50% of the messages + assertEquals("Client for " + broker1 + " should have received 50% of the messages.", (int) (MESSAGE_COUNT * 0.50), msgsClient1); + + // Second client should have received 50% of the messages + assertEquals("Client for " + broker2 + " should have received 50% of the messages.", (int) (MESSAGE_COUNT * 0.50), msgsClient2); + } + + @SuppressWarnings("unchecked") + public void testDuplicateSend() throws Exception { + broker1 = "BrokerA"; + broker2 = "BrokerB"; + + // enable producer audit for the network connector, off by default b/c of interference with composite + // dests and virtual topics + brokers.get(broker2).broker.getTransportConnectors().get(0).setAuditNetworkProducers(true); + bridgeBrokers(broker1, broker2); + + final AtomicBoolean first = new AtomicBoolean(); + final CountDownLatch gotMessageLatch = new CountDownLatch(1); + + BrokerService brokerService = brokers.get(broker2).broker; + brokerService.setPersistent(true); + brokerService.setDeleteAllMessagesOnStartup(true); + brokerService.setPlugins(new BrokerPlugin[]{new BrokerPluginSupport() { + @Override + public void send(final ProducerBrokerExchange producerExchange, + org.apache.activemq.command.Message messageSend) throws Exception { + super.send(producerExchange, messageSend); + if (first.compareAndSet(false, true)) { + producerExchange.getConnectionContext().setDontSendReponse(true); + Executors.newSingleThreadExecutor().execute(new Runnable() { + @Override + public void run() { + try { + LOG.info("Waiting for recepit"); + assertTrue("message received on time", gotMessageLatch.await(60, TimeUnit.SECONDS)); + LOG.info("Stopping connection post send and receive and multiple producers"); + producerExchange.getConnectionContext().getConnection().stop(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + }); } - })); - } + } + }}); - @SuppressWarnings("unchecked") - public void testDuplicateSendWithNoAuditEnqueueCountStat() throws Exception { - broker1 = "BrokerA"; - broker2 = "BrokerB"; + // Run brokers + startAllBrokers(); - NetworkConnector networkConnector = bridgeBrokers(broker1, broker2); + waitForBridgeFormation(); - final AtomicBoolean first = new AtomicBoolean(); - final CountDownLatch gotMessageLatch = new CountDownLatch(1); + // Create queue + Destination dest = createDestination("TEST.FOO", false); - BrokerService brokerService = brokers.get(broker2).broker; - brokerService.setPersistent(true); - brokerService.setDeleteAllMessagesOnStartup(true); - // disable concurrent dispatch otherwise store duplicate suppression will be skipped b/c cursor audit is already - // disabled so verification of stats will fail - ie: duplicate will be dispatched - ((KahaDBPersistenceAdapter)brokerService.getPersistenceAdapter()).setConcurrentStoreAndDispatchQueues(false); - brokerService.setPlugins(new BrokerPlugin[]{ - new BrokerPluginSupport() { - @Override - public void send(final ProducerBrokerExchange producerExchange, - org.apache.activemq.command.Message messageSend) - throws Exception { - super.send(producerExchange, messageSend); - if (first.compareAndSet(false, true)) { - producerExchange.getConnectionContext().setDontSendReponse(true); - Executors.newSingleThreadExecutor().execute(new Runnable() { - @Override - public void run() { - try { - LOG.info("Waiting for recepit"); - assertTrue("message received on time", gotMessageLatch.await(60, TimeUnit.SECONDS)); - LOG.info("Stopping connection post send and receive and multiple producers"); - producerExchange.getConnectionContext().getConnection().stop(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - } - } - } - }); + MessageConsumer client2 = createConsumer(broker2, dest); - // Create queue - ActiveMQDestination dest = createDestination("TEST.FOO", false); + sendMessages("BrokerA", dest, 1); - // statically include our destination - networkConnector.addStaticallyIncludedDestination(dest); + assertEquals("Client got message", 1, receiveExactMessages(client2, 1)); + client2.close(); + gotMessageLatch.countDown(); - // Run brokers - startAllBrokers(); + // message still pending on broker1 + assertEquals("messages message still there", 1, brokers.get(broker1).broker.getAdminView().getTotalMessageCount()); - waitForBridgeFormation(); + client2 = createConsumer(broker2, dest); - sendMessages("BrokerA", dest, 1); + LOG.info("Let the second client receive the rest of the messages"); + assertEquals("no duplicate message", 0, receiveAllMessages(client2)); + assertEquals("no duplicate message", 0, receiveAllMessages(client2)); - // wait for broker2 to get the initial forward - Wait.waitFor(new Wait.Condition(){ - @Override - public boolean isSatisified() throws Exception { - return brokers.get(broker2).broker.getAdminView().getTotalMessageCount() == 1; + assertEquals("no messages enqueued", 0, brokers.get(broker2).broker.getAdminView().getTotalMessageCount()); + assertTrue("no messages enqueued on origin", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return 0 == brokers.get(broker1).broker.getAdminView().getTotalMessageCount(); + } + })); + } + + @SuppressWarnings("unchecked") + public void testDuplicateSendWithNoAuditEnqueueCountStat() throws Exception { + broker1 = "BrokerA"; + broker2 = "BrokerB"; + + NetworkConnector networkConnector = bridgeBrokers(broker1, broker2); + + final AtomicBoolean first = new AtomicBoolean(); + final CountDownLatch gotMessageLatch = new CountDownLatch(1); + + BrokerService brokerService = brokers.get(broker2).broker; + brokerService.setPersistent(true); + brokerService.setDeleteAllMessagesOnStartup(true); + // disable concurrent dispatch otherwise store duplicate suppression will be skipped b/c cursor audit is already + // disabled so verification of stats will fail - ie: duplicate will be dispatched + ((KahaDBPersistenceAdapter) brokerService.getPersistenceAdapter()).setConcurrentStoreAndDispatchQueues(false); + brokerService.setPlugins(new BrokerPlugin[]{new BrokerPluginSupport() { + @Override + public void send(final ProducerBrokerExchange producerExchange, + org.apache.activemq.command.Message messageSend) throws Exception { + super.send(producerExchange, messageSend); + if (first.compareAndSet(false, true)) { + producerExchange.getConnectionContext().setDontSendReponse(true); + Executors.newSingleThreadExecutor().execute(new Runnable() { + @Override + public void run() { + try { + LOG.info("Waiting for recepit"); + assertTrue("message received on time", gotMessageLatch.await(60, TimeUnit.SECONDS)); + LOG.info("Stopping connection post send and receive and multiple producers"); + producerExchange.getConnectionContext().getConnection().stop(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + }); } - }); + } + }}); - // message still pending on broker1 - assertEquals("messages message still there", 1, brokers.get(broker1).broker.getAdminView().getTotalMessageCount()); + // Create queue + ActiveMQDestination dest = createDestination("TEST.FOO", false); - // allow the bridge to be shutdown and restarted - gotMessageLatch.countDown(); + // statically include our destination + networkConnector.addStaticallyIncludedDestination(dest); + // Run brokers + startAllBrokers(); - // verify message is forwarded after restart - assertTrue("no messages enqueued on origin", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return 0 == brokers.get(broker1).broker.getAdminView().getTotalMessageCount(); - } - })); + waitForBridgeFormation(); - assertEquals("one messages pending", 1, brokers.get(broker2).broker.getAdminView().getTotalMessageCount()); - assertEquals("one messages enqueued", 1, brokers.get(broker2).broker.getDestination(dest).getDestinationStatistics().getEnqueues().getCount()); - } + sendMessages("BrokerA", dest, 1); - protected int receiveExactMessages(MessageConsumer consumer, int msgCount) throws Exception { - Message msg; - int i; - for (i = 0; i < msgCount; i++) { - msg = consumer.receive(4000); - if (msg == null) { - LOG.error("Consumer failed to receive exactly " + msgCount + " messages. Actual messages received is: " + i); - break; - } - } + // wait for broker2 to get the initial forward + Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return brokers.get(broker2).broker.getAdminView().getTotalMessageCount() == 1; + } + }); - return i; - } + // message still pending on broker1 + assertEquals("messages message still there", 1, brokers.get(broker1).broker.getAdminView().getTotalMessageCount()); - protected int receiveAllMessages(MessageConsumer consumer) throws Exception { - int msgsReceived = 0; + // allow the bridge to be shutdown and restarted + gotMessageLatch.countDown(); - Message msg; - do { - msg = consumer.receive(1000); - if (msg != null) { - msgsReceived++; - } - } while (msg != null); + // verify message is forwarded after restart + assertTrue("no messages enqueued on origin", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + return 0 == brokers.get(broker1).broker.getAdminView().getTotalMessageCount(); + } + })); - return msgsReceived; - } + assertEquals("one messages pending", 1, brokers.get(broker2).broker.getAdminView().getTotalMessageCount()); + assertEquals("one messages enqueued", 1, brokers.get(broker2).broker.getDestination(dest).getDestinationStatistics().getEnqueues().getCount()); + } - @Override - protected MessageConsumer createConsumer(String brokerName, Destination dest) throws Exception { - Connection conn = createConnection(brokerName); - conn.start(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - return sess.createConsumer(dest); - } + protected int receiveExactMessages(MessageConsumer consumer, int msgCount) throws Exception { + Message msg; + int i; + for (i = 0; i < msgCount; i++) { + msg = consumer.receive(4000); + if (msg == null) { + LOG.error("Consumer failed to receive exactly " + msgCount + " messages. Actual messages received is: " + i); + break; + } + } - @Override - protected void configureBroker(BrokerService broker) { - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setEnableAudit(false); - policyMap.setDefaultEntry(defaultEntry); - broker.setDestinationPolicy(policyMap); - } + return i; + } - @Override - protected NetworkConnector bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker, boolean dynamicOnly, int networkTTL, boolean conduit, boolean failover) throws Exception { - NetworkConnector nc = super.bridgeBrokers(localBroker,remoteBroker, dynamicOnly, networkTTL, conduit, failover); - nc.setPrefetchSize(NETWORK_PREFETCH); - nc.setDecreaseNetworkConsumerPriority(true); - return nc; - } + protected int receiveAllMessages(MessageConsumer consumer) throws Exception { + int msgsReceived = 0; - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=true")); - createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=true")); + Message msg; + do { + msg = consumer.receive(1000); + if (msg != null) { + msgsReceived++; + } + } while (msg != null); - // Configure broker connection factory - ActiveMQConnectionFactory factoryA; - ActiveMQConnectionFactory factoryB; - factoryA = (ActiveMQConnectionFactory)getConnectionFactory("BrokerA"); - factoryB = (ActiveMQConnectionFactory)getConnectionFactory("BrokerB"); + return msgsReceived; + } - // Set prefetch policy - ActiveMQPrefetchPolicy policy = new ActiveMQPrefetchPolicy(); - policy.setAll(PREFETCH_COUNT); + @Override + protected MessageConsumer createConsumer(String brokerName, Destination dest) throws Exception { + Connection conn = createConnection(brokerName); + conn.start(); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + return sess.createConsumer(dest); + } - factoryA.setPrefetchPolicy(policy); - factoryB.setPrefetchPolicy(policy); + @Override + protected void configureBroker(BrokerService broker) { + PolicyMap policyMap = new PolicyMap(); + PolicyEntry defaultEntry = new PolicyEntry(); + defaultEntry.setEnableAudit(false); + policyMap.setDefaultEntry(defaultEntry); + broker.setDestinationPolicy(policyMap); + } - msgsClient1 = 0; - msgsClient2 = 0; - } + @Override + protected NetworkConnector bridgeBrokers(BrokerService localBroker, + BrokerService remoteBroker, + boolean dynamicOnly, + int networkTTL, + boolean conduit, + boolean failover) throws Exception { + NetworkConnector nc = super.bridgeBrokers(localBroker, remoteBroker, dynamicOnly, networkTTL, conduit, failover); + nc.setPrefetchSize(NETWORK_PREFETCH); + nc.setDecreaseNetworkConsumerPriority(true); + return nc; + } + + @Override + public void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); + createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=true")); + createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=true")); + + // Configure broker connection factory + ActiveMQConnectionFactory factoryA; + ActiveMQConnectionFactory factoryB; + factoryA = (ActiveMQConnectionFactory) getConnectionFactory("BrokerA"); + factoryB = (ActiveMQConnectionFactory) getConnectionFactory("BrokerB"); + + // Set prefetch policy + ActiveMQPrefetchPolicy policy = new ActiveMQPrefetchPolicy(); + policy.setAll(PREFETCH_COUNT); + + factoryA.setPrefetchPolicy(policy); + factoryB.setPrefetchPolicy(policy); + + msgsClient1 = 0; + msgsClient2 = 0; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerQueueSendReceiveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerQueueSendReceiveTest.java index d463c14cf5..90d3e0d08d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerQueueSendReceiveTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerQueueSendReceiveTest.java @@ -23,38 +23,38 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * */ -public class TwoBrokerQueueSendReceiveTest extends TwoBrokerTopicSendReceiveTest { +public class TwoBrokerQueueSendReceiveTest extends TwoBrokerTopicSendReceiveTest { - private static final Logger LOG = LoggerFactory.getLogger(TwoBrokerQueueSendReceiveTest.class); + private static final Logger LOG = LoggerFactory.getLogger(TwoBrokerQueueSendReceiveTest.class); - protected void setUp() throws Exception { - topic = false; - super.setUp(); - } + protected void setUp() throws Exception { + topic = false; + super.setUp(); + } - public void testReceiveOnXConsumersNoLeak() throws Exception { - consumer.close(); - sendMessages(); - for (int i=0; i brokers = new HashMap(); + private static final Logger LOG = LoggerFactory.getLogger(TwoBrokerTopicSendReceiveTest.class); - @Override - protected void setUp() throws Exception { - sendFactory = createSenderConnectionFactory(); - receiveFactory = createReceiverConnectionFactory(); + protected ActiveMQConnectionFactory sendFactory; + protected ActiveMQConnectionFactory receiveFactory; + protected HashMap brokers = new HashMap(); - // Give server enough time to setup, - // so we don't lose messages when connection fails - LOG.info("Waiting for brokers Initialize."); - Thread.sleep(5000); - LOG.info("Brokers should be initialized by now.. starting test."); + @Override + protected void setUp() throws Exception { + sendFactory = createSenderConnectionFactory(); + receiveFactory = createReceiverConnectionFactory(); - super.setUp(); - } + // Give server enough time to setup, + // so we don't lose messages when connection fails + LOG.info("Waiting for brokers Initialize."); + Thread.sleep(5000); + LOG.info("Brokers should be initialized by now.. starting test."); - protected ActiveMQConnectionFactory createReceiverConnectionFactory() throws JMSException { - return createConnectionFactory("org/apache/activemq/usecases/receiver.xml", "receiver", - "vm://receiver"); - } + super.setUp(); + } - protected ActiveMQConnectionFactory createSenderConnectionFactory() throws JMSException { - return createConnectionFactory("org/apache/activemq/usecases/sender.xml", "sender", "vm://sender"); - } + protected ActiveMQConnectionFactory createReceiverConnectionFactory() throws JMSException { + return createConnectionFactory("org/apache/activemq/usecases/receiver.xml", "receiver", "vm://receiver"); + } - @Override - protected void tearDown() throws Exception { - super.tearDown(); - for (Iterator iter = brokers.values().iterator(); iter.hasNext();) { - BrokerService broker = iter.next(); - ServiceSupport.dispose(broker); - iter.remove(); - } - } + protected ActiveMQConnectionFactory createSenderConnectionFactory() throws JMSException { + return createConnectionFactory("org/apache/activemq/usecases/sender.xml", "sender", "vm://sender"); + } - @Override - protected Connection createReceiveConnection() throws JMSException { - return receiveFactory.createConnection(); - } + @Override + protected void tearDown() throws Exception { + super.tearDown(); + for (Iterator iter = brokers.values().iterator(); iter.hasNext(); ) { + BrokerService broker = iter.next(); + ServiceSupport.dispose(broker); + iter.remove(); + } + } - @Override - protected Connection createSendConnection() throws JMSException { - return sendFactory.createConnection(); - } + @Override + protected Connection createReceiveConnection() throws JMSException { + return receiveFactory.createConnection(); + } - protected ActiveMQConnectionFactory createConnectionFactory(String config, String brokerName, - String connectUrl) throws JMSException { - try { - BrokerFactoryBean brokerFactory = new BrokerFactoryBean(new ClassPathResource(config)); - brokerFactory.afterPropertiesSet(); - BrokerService broker = brokerFactory.getBroker(); - brokers.put(brokerName, broker); + @Override + protected Connection createSendConnection() throws JMSException { + return sendFactory.createConnection(); + } - return new ActiveMQConnectionFactory(connectUrl); + protected ActiveMQConnectionFactory createConnectionFactory(String config, + String brokerName, + String connectUrl) throws JMSException { + try { + BrokerFactoryBean brokerFactory = new BrokerFactoryBean(new ClassPathResource(config)); + brokerFactory.afterPropertiesSet(); + BrokerService broker = brokerFactory.getBroker(); + brokers.put(brokerName, broker); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } + return new ActiveMQConnectionFactory(connectUrl); + + } + catch (Exception e) { + e.printStackTrace(); + } + return null; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveUsingJavaConfigurationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveUsingJavaConfigurationTest.java index 22544363e5..365f5c8f0d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveUsingJavaConfigurationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveUsingJavaConfigurationTest.java @@ -22,56 +22,59 @@ import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; /** - * + * */ public class TwoBrokerTopicSendReceiveUsingJavaConfigurationTest extends TwoBrokerTopicSendReceiveTest { - BrokerService receiveBroker; - BrokerService sendBroker; - protected ActiveMQConnectionFactory createReceiverConnectionFactory() throws JMSException { - try { - receiveBroker = new BrokerService(); - receiveBroker.setBrokerName("receiveBroker"); - receiveBroker.setUseJmx(false); - receiveBroker.setPersistent(false); - receiveBroker.addConnector("tcp://localhost:62002"); - receiveBroker.addNetworkConnector("static:failover:tcp://localhost:62001"); - receiveBroker.start(); + BrokerService receiveBroker; + BrokerService sendBroker; - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:62002"); - return factory; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } + protected ActiveMQConnectionFactory createReceiverConnectionFactory() throws JMSException { + try { + receiveBroker = new BrokerService(); + receiveBroker.setBrokerName("receiveBroker"); + receiveBroker.setUseJmx(false); + receiveBroker.setPersistent(false); + receiveBroker.addConnector("tcp://localhost:62002"); + receiveBroker.addNetworkConnector("static:failover:tcp://localhost:62001"); + receiveBroker.start(); - protected ActiveMQConnectionFactory createSenderConnectionFactory() throws JMSException { - try { - sendBroker = new BrokerService(); - sendBroker.setBrokerName("sendBroker"); - sendBroker.setUseJmx(false); - sendBroker.setPersistent(false); - sendBroker.addConnector("tcp://localhost:62001"); - sendBroker.addNetworkConnector("static:failover:tcp://localhost:62002"); - sendBroker.start(); + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:62002"); + return factory; + } + catch (Exception e) { + e.printStackTrace(); + return null; + } + } - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:62001"); - return factory; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } + protected ActiveMQConnectionFactory createSenderConnectionFactory() throws JMSException { + try { + sendBroker = new BrokerService(); + sendBroker.setBrokerName("sendBroker"); + sendBroker.setUseJmx(false); + sendBroker.setPersistent(false); + sendBroker.addConnector("tcp://localhost:62001"); + sendBroker.addNetworkConnector("static:failover:tcp://localhost:62002"); + sendBroker.start(); - protected void tearDown() throws Exception { - super.tearDown(); - if (sendBroker != null) { - sendBroker.stop(); - } - if (receiveBroker != null) { - receiveBroker.stop(); - } - } + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:62001"); + return factory; + } + catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + protected void tearDown() throws Exception { + super.tearDown(); + if (sendBroker != null) { + sendBroker.stop(); + } + if (receiveBroker != null) { + receiveBroker.stop(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveUsingTcpTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveUsingTcpTest.java index 933cfd6b2b..6ea557782f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveUsingTcpTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveUsingTcpTest.java @@ -25,56 +25,58 @@ import org.apache.activemq.xbean.BrokerFactoryBean; import org.springframework.core.io.ClassPathResource; /** - * + * */ public class TwoBrokerTopicSendReceiveUsingTcpTest extends TwoBrokerTopicSendReceiveTest { - private BrokerService receiverBroker; - private BrokerService senderBroker; - protected void setUp() throws Exception { - BrokerFactoryBean brokerFactory; + private BrokerService receiverBroker; + private BrokerService senderBroker; - brokerFactory = new BrokerFactoryBean(new ClassPathResource("org/apache/activemq/usecases/receiver.xml")); - brokerFactory.afterPropertiesSet(); - receiverBroker = brokerFactory.getBroker(); + protected void setUp() throws Exception { + BrokerFactoryBean brokerFactory; - brokerFactory = new BrokerFactoryBean(new ClassPathResource("org/apache/activemq/usecases/sender.xml")); - brokerFactory.afterPropertiesSet(); - senderBroker = brokerFactory.getBroker(); + brokerFactory = new BrokerFactoryBean(new ClassPathResource("org/apache/activemq/usecases/receiver.xml")); + brokerFactory.afterPropertiesSet(); + receiverBroker = brokerFactory.getBroker(); - super.setUp(); - } + brokerFactory = new BrokerFactoryBean(new ClassPathResource("org/apache/activemq/usecases/sender.xml")); + brokerFactory.afterPropertiesSet(); + senderBroker = brokerFactory.getBroker(); - protected void tearDown() throws Exception { - super.tearDown(); + super.setUp(); + } - if (receiverBroker != null) { - receiverBroker.stop(); - } - if (senderBroker != null) { - senderBroker.stop(); - } - } + protected void tearDown() throws Exception { + super.tearDown(); - - protected ActiveMQConnectionFactory createReceiverConnectionFactory() throws JMSException { - try { - ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory(((TransportConnector)receiverBroker.getTransportConnectors().get(0)).getConnectUri()); - return fac; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } + if (receiverBroker != null) { + receiverBroker.stop(); + } + if (senderBroker != null) { + senderBroker.stop(); + } + } - protected ActiveMQConnectionFactory createSenderConnectionFactory() throws JMSException { - try { - ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory(((TransportConnector)senderBroker.getTransportConnectors().get(0)).getConnectUri()); - return fac; - } catch (Exception e) { - e.printStackTrace(); - return null; - } + protected ActiveMQConnectionFactory createReceiverConnectionFactory() throws JMSException { + try { + ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory(((TransportConnector) receiverBroker.getTransportConnectors().get(0)).getConnectUri()); + return fac; + } + catch (Exception e) { + e.printStackTrace(); + return null; + } + } - } + protected ActiveMQConnectionFactory createSenderConnectionFactory() throws JMSException { + try { + ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory(((TransportConnector) senderBroker.getTransportConnectors().get(0)).getConnectUri()); + return fac; + } + catch (Exception e) { + e.printStackTrace(); + return null; + } + + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerVirtualDestDinamicallyIncludedDestTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerVirtualDestDinamicallyIncludedDestTest.java index be175354c6..b4d3df9ce8 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerVirtualDestDinamicallyIncludedDestTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerVirtualDestDinamicallyIncludedDestTest.java @@ -34,196 +34,197 @@ import java.io.IOException; import java.net.URI; public class TwoBrokerVirtualDestDinamicallyIncludedDestTest extends JmsMultipleBrokersTestSupport { - protected static final int MESSAGE_COUNT = 10; - boolean dynamicOnly = true; - int networkTTL = 1; - boolean conduit = true; - boolean suppressDuplicateQueueSubscriptions = true; - boolean decreaseNetworkConsumerPriority = true; - /** - * BrokerA -> BrokerB && BrokerB -> BrokerA - */ - public void testTopicDinamicallyIncludedBehavior() throws Exception { + protected static final int MESSAGE_COUNT = 10; + boolean dynamicOnly = true; + int networkTTL = 1; + boolean conduit = true; + boolean suppressDuplicateQueueSubscriptions = true; + boolean decreaseNetworkConsumerPriority = true; - startAllBrokers(); + /** + * BrokerA -> BrokerB && BrokerB -> BrokerA + */ + public void testTopicDinamicallyIncludedBehavior() throws Exception { - // Setup destination - Destination dest = createDestination("test", true); + startAllBrokers(); - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); - MessageConsumer clientB = createConsumer("BrokerB", dest); + // Setup destination + Destination dest = createDestination("test", true); - Thread.sleep(2*1000); + // Setup consumers + MessageConsumer clientA = createConsumer("BrokerA", dest); + MessageConsumer clientB = createConsumer("BrokerB", dest); - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); + Thread.sleep(2 * 1000); - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - msgsA.waitForMessagesToArrive(MESSAGE_COUNT); - assertEquals(MESSAGE_COUNT, msgsA.getMessageCount()); + // Send messages + sendMessages("BrokerA", dest, MESSAGE_COUNT); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - msgsB.waitForMessagesToArrive(MESSAGE_COUNT); - assertEquals(0, msgsB.getMessageCount()); + // Get message count + MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); + msgsA.waitForMessagesToArrive(MESSAGE_COUNT); + assertEquals(MESSAGE_COUNT, msgsA.getMessageCount()); - } + MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); + msgsB.waitForMessagesToArrive(MESSAGE_COUNT); + assertEquals(0, msgsB.getMessageCount()); - /** - * BrokerA -> BrokerB && BrokerB -> BrokerA - */ - public void testVirtualDestinationsDinamicallyIncludedBehavior1() throws Exception { + } - startAllBrokers(); + /** + * BrokerA -> BrokerB && BrokerB -> BrokerA + */ + public void testVirtualDestinationsDinamicallyIncludedBehavior1() throws Exception { - // Setup destination - Destination dest = createDestination("global.test", true); + startAllBrokers(); - // Setup consumers - MessageConsumer clientB1 = createConsumer("BrokerB", dest); - MessageConsumer clientB2 = createConsumer("BrokerB", createDestination("Consumer.foo-bar.global.test", false)); + // Setup destination + Destination dest = createDestination("global.test", true); - Thread.sleep(2*1000); + // Setup consumers + MessageConsumer clientB1 = createConsumer("BrokerB", dest); + MessageConsumer clientB2 = createConsumer("BrokerB", createDestination("Consumer.foo-bar.global.test", false)); - int messageCount = MESSAGE_COUNT; - // Send messages - sendMessages("BrokerA", dest, messageCount); + Thread.sleep(2 * 1000); - // Get message count - MessageIdList msgsB1 = getConsumerMessages("BrokerB", clientB1); - msgsB1.waitForMessagesToArrive(messageCount); - assertEquals(messageCount, msgsB1.getMessageCount()); + int messageCount = MESSAGE_COUNT; + // Send messages + sendMessages("BrokerA", dest, messageCount); - MessageIdList msgsB2 = getConsumerMessages("BrokerB", clientB2); - msgsB2.waitForMessagesToArrive(messageCount); - assertEquals(messageCount, msgsB2.getMessageCount()); + // Get message count + MessageIdList msgsB1 = getConsumerMessages("BrokerB", clientB1); + msgsB1.waitForMessagesToArrive(messageCount); + assertEquals(messageCount, msgsB1.getMessageCount()); - } + MessageIdList msgsB2 = getConsumerMessages("BrokerB", clientB2); + msgsB2.waitForMessagesToArrive(messageCount); + assertEquals(messageCount, msgsB2.getMessageCount()); - /** - * BrokerA -> BrokerB && BrokerB -> BrokerA - */ - public void testVirtualDestinationsDinamicallyIncludedBehavior2() throws Exception { + } - startAllBrokers(); + /** + * BrokerA -> BrokerB && BrokerB -> BrokerA + */ + public void testVirtualDestinationsDinamicallyIncludedBehavior2() throws Exception { - // Setup destination - Destination dest = createDestination("global.test", true); + startAllBrokers(); - // Setup consumers - //MessageConsumer clientB1 = createConsumer("BrokerB", dest); - MessageConsumer clientB2 = createConsumer("BrokerB", createDestination("Consumer.foo-bar.global.test", false)); + // Setup destination + Destination dest = createDestination("global.test", true); - Thread.sleep(2*1000); + // Setup consumers + //MessageConsumer clientB1 = createConsumer("BrokerB", dest); + MessageConsumer clientB2 = createConsumer("BrokerB", createDestination("Consumer.foo-bar.global.test", false)); - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); + Thread.sleep(2 * 1000); - // Get message count - MessageIdList msgsB2 = getConsumerMessages("BrokerB", clientB2); - msgsB2.waitForMessagesToArrive(MESSAGE_COUNT); - assertEquals(MESSAGE_COUNT, msgsB2.getMessageCount()); + // Send messages + sendMessages("BrokerA", dest, MESSAGE_COUNT); - } - - /** - * BrokerA -> BrokerB && BrokerB -> BrokerA - */ - public void testVirtualDestinationsDinamicallyIncludedBehavior3() throws Exception { - final String topic = "global.test"; - final String vq = "Consumer.foo." + topic; + // Get message count + MessageIdList msgsB2 = getConsumerMessages("BrokerB", clientB2); + msgsB2.waitForMessagesToArrive(MESSAGE_COUNT); + assertEquals(MESSAGE_COUNT, msgsB2.getMessageCount()); - startAllBrokers(); - final int msgs1 = 1001; - final int msgs2 = 1456; - - // Setup destination - Destination tDest = createDestination(topic, true); - Destination vqDest = createDestination(vq, false); + } - // Setup consumers - MessageConsumer clientB1t = createConsumer("BrokerA", tDest); - MessageConsumer clientB2t = createConsumer("BrokerB", tDest); - MessageConsumer clientB1vq = createConsumer("BrokerA", vqDest); - - Thread.sleep(2*1000); - - // Send messages - sendMessages("BrokerA", tDest, msgs1); - sendMessages("BrokerB", tDest, msgs2); + /** + * BrokerA -> BrokerB && BrokerB -> BrokerA + */ + public void testVirtualDestinationsDinamicallyIncludedBehavior3() throws Exception { + final String topic = "global.test"; + final String vq = "Consumer.foo." + topic; - Thread.sleep(5000); - - // Get message count - MessageIdList msgsB1t = getConsumerMessages("BrokerA", clientB1t); - msgsB1t.waitForMessagesToArrive(msgs1 + msgs2); - assertEquals(msgs1 + msgs2, msgsB1t.getMessageCount()); - MessageIdList msgsB2t = getConsumerMessages("BrokerB", clientB2t); - msgsB2t.waitForMessagesToArrive(msgs1 + msgs2); - assertEquals(msgs1 + msgs2, msgsB2t.getMessageCount()); - MessageIdList msgsB1vq = getConsumerMessages("BrokerA", clientB1vq); - msgsB1vq.waitForMessagesToArrive(msgs1 + msgs2); - assertEquals(msgs1 + msgs2, msgsB1vq.getMessageCount()); - - assertEquals(0, getQueueSize("BrokerA", (ActiveMQDestination)vqDest)); - assertEquals(0, getQueueSize("BrokerB", (ActiveMQDestination)vqDest)); - destroyAllBrokers(); - } - - public long getQueueSize(String broker, ActiveMQDestination destination) throws Exception { - BrokerItem bi = brokers.get(broker); - return bi.broker.getDestination(destination).getDestinationStatistics().getMessages().getCount(); - } + startAllBrokers(); + final int msgs1 = 1001; + final int msgs2 = 1456; - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - String options = new String("?useJmx=false&deleteAllMessagesOnStartup=true"); - createAndConfigureBroker(new URI("broker:(tcp://localhost:61616)/BrokerA" + options)); - createAndConfigureBroker(new URI("broker:(tcp://localhost:61617)/BrokerB" + options)); + // Setup destination + Destination tDest = createDestination(topic, true); + Destination vqDest = createDestination(vq, false); - // Setup broker networks - NetworkConnector nc1 = bridgeBrokers("BrokerA", "BrokerB", dynamicOnly, networkTTL, conduit); - nc1.setDecreaseNetworkConsumerPriority(decreaseNetworkConsumerPriority); - nc1.setSuppressDuplicateQueueSubscriptions(suppressDuplicateQueueSubscriptions); - nc1.addStaticallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.TOPIC_TYPE)); - //nc1.addExcludedDestination(ActiveMQDestination.createDestination("Consumer.*.global.>", ActiveMQDestination.QUEUE_TYPE)); - nc1.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.QUEUE_TYPE)); - nc1.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.TOPIC_TYPE)); - nc1.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("Consumer.*.global.>", ActiveMQDestination.QUEUE_TYPE)); + // Setup consumers + MessageConsumer clientB1t = createConsumer("BrokerA", tDest); + MessageConsumer clientB2t = createConsumer("BrokerB", tDest); + MessageConsumer clientB1vq = createConsumer("BrokerA", vqDest); - NetworkConnector nc2 = bridgeBrokers("BrokerB", "BrokerA", dynamicOnly, networkTTL, conduit); - nc2.setDecreaseNetworkConsumerPriority(decreaseNetworkConsumerPriority); - nc2.setSuppressDuplicateQueueSubscriptions(suppressDuplicateQueueSubscriptions); - nc2.addStaticallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.TOPIC_TYPE)); - //nc2.addExcludedDestination(ActiveMQDestination.createDestination("Consumer.*.global.>", ActiveMQDestination.QUEUE_TYPE)); - nc2.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.QUEUE_TYPE)); - nc2.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.TOPIC_TYPE)); - nc2.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("Consumer.*.global.>", ActiveMQDestination.QUEUE_TYPE)); - } + Thread.sleep(2 * 1000); - private BrokerService createAndConfigureBroker(URI uri) throws Exception { - BrokerService broker = createBroker(uri); + // Send messages + sendMessages("BrokerA", tDest, msgs1); + sendMessages("BrokerB", tDest, msgs2); - configurePersistenceAdapter(broker); + Thread.sleep(5000); - // make all topics virtual and consumers use the default prefix - VirtualDestinationInterceptor virtualDestinationInterceptor = new VirtualDestinationInterceptor(); - VirtualTopic vTopic = new VirtualTopic(); - vTopic.setLocal(true); - virtualDestinationInterceptor.setVirtualDestinations(new VirtualDestination[]{vTopic}); - DestinationInterceptor[] destinationInterceptors = new DestinationInterceptor[]{virtualDestinationInterceptor}; - broker.setDestinationInterceptors(destinationInterceptors); - return broker; - } + // Get message count + MessageIdList msgsB1t = getConsumerMessages("BrokerA", clientB1t); + msgsB1t.waitForMessagesToArrive(msgs1 + msgs2); + assertEquals(msgs1 + msgs2, msgsB1t.getMessageCount()); + MessageIdList msgsB2t = getConsumerMessages("BrokerB", clientB2t); + msgsB2t.waitForMessagesToArrive(msgs1 + msgs2); + assertEquals(msgs1 + msgs2, msgsB2t.getMessageCount()); + MessageIdList msgsB1vq = getConsumerMessages("BrokerA", clientB1vq); + msgsB1vq.waitForMessagesToArrive(msgs1 + msgs2); + assertEquals(msgs1 + msgs2, msgsB1vq.getMessageCount()); - protected void configurePersistenceAdapter(BrokerService broker) throws IOException { - File dataFileDir = new File("target/test-amq-data/kahadb/" + broker.getBrokerName()); - KahaDBStore kaha = new KahaDBStore(); - kaha.setDirectory(dataFileDir); - kaha.deleteAllMessages(); - broker.setPersistenceAdapter(kaha); - } + assertEquals(0, getQueueSize("BrokerA", (ActiveMQDestination) vqDest)); + assertEquals(0, getQueueSize("BrokerB", (ActiveMQDestination) vqDest)); + destroyAllBrokers(); + } + + public long getQueueSize(String broker, ActiveMQDestination destination) throws Exception { + BrokerItem bi = brokers.get(broker); + return bi.broker.getDestination(destination).getDestinationStatistics().getMessages().getCount(); + } + + public void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); + String options = new String("?useJmx=false&deleteAllMessagesOnStartup=true"); + createAndConfigureBroker(new URI("broker:(tcp://localhost:61616)/BrokerA" + options)); + createAndConfigureBroker(new URI("broker:(tcp://localhost:61617)/BrokerB" + options)); + + // Setup broker networks + NetworkConnector nc1 = bridgeBrokers("BrokerA", "BrokerB", dynamicOnly, networkTTL, conduit); + nc1.setDecreaseNetworkConsumerPriority(decreaseNetworkConsumerPriority); + nc1.setSuppressDuplicateQueueSubscriptions(suppressDuplicateQueueSubscriptions); + nc1.addStaticallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.TOPIC_TYPE)); + //nc1.addExcludedDestination(ActiveMQDestination.createDestination("Consumer.*.global.>", ActiveMQDestination.QUEUE_TYPE)); + nc1.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.QUEUE_TYPE)); + nc1.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.TOPIC_TYPE)); + nc1.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("Consumer.*.global.>", ActiveMQDestination.QUEUE_TYPE)); + + NetworkConnector nc2 = bridgeBrokers("BrokerB", "BrokerA", dynamicOnly, networkTTL, conduit); + nc2.setDecreaseNetworkConsumerPriority(decreaseNetworkConsumerPriority); + nc2.setSuppressDuplicateQueueSubscriptions(suppressDuplicateQueueSubscriptions); + nc2.addStaticallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.TOPIC_TYPE)); + //nc2.addExcludedDestination(ActiveMQDestination.createDestination("Consumer.*.global.>", ActiveMQDestination.QUEUE_TYPE)); + nc2.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.QUEUE_TYPE)); + nc2.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.TOPIC_TYPE)); + nc2.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("Consumer.*.global.>", ActiveMQDestination.QUEUE_TYPE)); + } + + private BrokerService createAndConfigureBroker(URI uri) throws Exception { + BrokerService broker = createBroker(uri); + + configurePersistenceAdapter(broker); + + // make all topics virtual and consumers use the default prefix + VirtualDestinationInterceptor virtualDestinationInterceptor = new VirtualDestinationInterceptor(); + VirtualTopic vTopic = new VirtualTopic(); + vTopic.setLocal(true); + virtualDestinationInterceptor.setVirtualDestinations(new VirtualDestination[]{vTopic}); + DestinationInterceptor[] destinationInterceptors = new DestinationInterceptor[]{virtualDestinationInterceptor}; + broker.setDestinationInterceptors(destinationInterceptors); + return broker; + } + + protected void configurePersistenceAdapter(BrokerService broker) throws IOException { + File dataFileDir = new File("target/test-amq-data/kahadb/" + broker.getBrokerName()); + KahaDBStore kaha = new KahaDBStore(); + kaha.setDirectory(dataFileDir); + kaha.deleteAllMessages(); + broker.setPersistenceAdapter(kaha); + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerVirtualTopicForwardingTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerVirtualTopicForwardingTest.java index a53cc08ea9..369cf3c8db 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerVirtualTopicForwardingTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerVirtualTopicForwardingTest.java @@ -39,165 +39,162 @@ import static org.apache.activemq.TestSupport.*; */ public class TwoBrokerVirtualTopicForwardingTest extends JmsMultipleBrokersTestSupport { - public void testBridgeVirtualTopicQueues() throws Exception { + public void testBridgeVirtualTopicQueues() throws Exception { - bridgeAndConfigureBrokers("BrokerA", "BrokerB"); - startAllBrokers(); - waitForBridgeFormation(); + bridgeAndConfigureBrokers("BrokerA", "BrokerB"); + startAllBrokers(); + waitForBridgeFormation(); - MessageConsumer clientA = createConsumer("BrokerA", createDestination("Consumer.A.VirtualTopic.tempTopic", false)); - MessageConsumer clientB = createConsumer("BrokerB", createDestination("Consumer.B.VirtualTopic.tempTopic", false)); + MessageConsumer clientA = createConsumer("BrokerA", createDestination("Consumer.A.VirtualTopic.tempTopic", false)); + MessageConsumer clientB = createConsumer("BrokerB", createDestination("Consumer.B.VirtualTopic.tempTopic", false)); + // give a sec to let advisories propagate + Thread.sleep(500); - // give a sec to let advisories propagate - Thread.sleep(500); + ActiveMQQueue queueA = new ActiveMQQueue("Consumer.A.VirtualTopic.tempTopic"); + Destination destination = getDestination(brokers.get("BrokerA").broker, queueA); + assertEquals(1, destination.getConsumers().size()); - ActiveMQQueue queueA = new ActiveMQQueue("Consumer.A.VirtualTopic.tempTopic"); - Destination destination = getDestination(brokers.get("BrokerA").broker, queueA); - assertEquals(1, destination.getConsumers().size()); + ActiveMQQueue queueB = new ActiveMQQueue("Consumer.B.VirtualTopic.tempTopic"); + destination = getDestination(brokers.get("BrokerA").broker, queueB); + assertEquals(1, destination.getConsumers().size()); - ActiveMQQueue queueB = new ActiveMQQueue("Consumer.B.VirtualTopic.tempTopic"); - destination = getDestination(brokers.get("BrokerA").broker, queueB); - assertEquals(1, destination.getConsumers().size()); + ActiveMQTopic virtualTopic = new ActiveMQTopic("VirtualTopic.tempTopic"); + assertNull(getDestination(brokers.get("BrokerA").broker, virtualTopic)); + assertNull(getDestination(brokers.get("BrokerB").broker, virtualTopic)); - ActiveMQTopic virtualTopic = new ActiveMQTopic("VirtualTopic.tempTopic"); - assertNull(getDestination(brokers.get("BrokerA").broker, virtualTopic)); - assertNull(getDestination(brokers.get("BrokerB").broker, virtualTopic)); + // send some messages + sendMessages("BrokerA", virtualTopic, 1); - // send some messages - sendMessages("BrokerA", virtualTopic, 1); + MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); + MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); + msgsA.waitForMessagesToArrive(1); + msgsB.waitForMessagesToArrive(1); - msgsA.waitForMessagesToArrive(1); - msgsB.waitForMessagesToArrive(1); + // ensure we don't get any more messages + Thread.sleep(2000); - // ensure we don't get any more messages - Thread.sleep(2000); + assertEquals(1, msgsA.getMessageCount()); + assertEquals(1, msgsB.getMessageCount()); - assertEquals(1, msgsA.getMessageCount()); - assertEquals(1, msgsB.getMessageCount()); + } - } + public void testDontBridgeQueuesWithOnlyQueueConsumers() throws Exception { + dontBridgeVirtualTopicConsumerQueues("BrokerA", "BrokerB"); - public void testDontBridgeQueuesWithOnlyQueueConsumers() throws Exception{ - dontBridgeVirtualTopicConsumerQueues("BrokerA", "BrokerB"); + startAllBrokers(); + waitForBridgeFormation(); - startAllBrokers(); - waitForBridgeFormation(); + MessageConsumer clientA = createConsumer("BrokerA", createDestination("Consumer.A.VirtualTopic.tempTopic", false)); + MessageConsumer clientB = createConsumer("BrokerB", createDestination("Consumer.B.VirtualTopic.tempTopic", false)); - MessageConsumer clientA = createConsumer("BrokerA", createDestination("Consumer.A.VirtualTopic.tempTopic", false)); - MessageConsumer clientB = createConsumer("BrokerB", createDestination("Consumer.B.VirtualTopic.tempTopic", false)); + // give a sec to let advisories propagate + Thread.sleep(500); + ActiveMQQueue queueA = new ActiveMQQueue("Consumer.A.VirtualTopic.tempTopic"); + Destination destination = getDestination(brokers.get("BrokerA").broker, queueA); + assertEquals(1, destination.getConsumers().size()); - // give a sec to let advisories propagate - Thread.sleep(500); + ActiveMQQueue queueB = new ActiveMQQueue("Consumer.B.VirtualTopic.tempTopic"); + destination = getDestination(brokers.get("BrokerA").broker, queueB); + assertNull(destination); - ActiveMQQueue queueA = new ActiveMQQueue("Consumer.A.VirtualTopic.tempTopic"); - Destination destination = getDestination(brokers.get("BrokerA").broker, queueA); - assertEquals(1, destination.getConsumers().size()); + ActiveMQTopic virtualTopic = new ActiveMQTopic("VirtualTopic.tempTopic"); + assertNull(getDestination(brokers.get("BrokerA").broker, virtualTopic)); + assertNull(getDestination(brokers.get("BrokerB").broker, virtualTopic)); - ActiveMQQueue queueB = new ActiveMQQueue("Consumer.B.VirtualTopic.tempTopic"); - destination = getDestination(brokers.get("BrokerA").broker, queueB); - assertNull(destination); + // send some messages + sendMessages("BrokerA", virtualTopic, 1); - ActiveMQTopic virtualTopic = new ActiveMQTopic("VirtualTopic.tempTopic"); - assertNull(getDestination(brokers.get("BrokerA").broker, virtualTopic)); - assertNull(getDestination(brokers.get("BrokerB").broker, virtualTopic)); + MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); + MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - // send some messages - sendMessages("BrokerA", virtualTopic, 1); + msgsA.waitForMessagesToArrive(1); + msgsB.waitForMessagesToArrive(0); - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); + // ensure we don't get any more messages + Thread.sleep(2000); - msgsA.waitForMessagesToArrive(1); - msgsB.waitForMessagesToArrive(0); + assertEquals(1, msgsA.getMessageCount()); + assertEquals(0, msgsB.getMessageCount()); + } - // ensure we don't get any more messages - Thread.sleep(2000); + public void testDontBridgeQueuesWithBothTypesConsumers() throws Exception { + dontBridgeVirtualTopicConsumerQueues("BrokerA", "BrokerB"); - assertEquals(1, msgsA.getMessageCount()); - assertEquals(0, msgsB.getMessageCount()); - } + startAllBrokers(); + waitForBridgeFormation(); - public void testDontBridgeQueuesWithBothTypesConsumers() throws Exception{ - dontBridgeVirtualTopicConsumerQueues("BrokerA", "BrokerB"); + MessageConsumer clientA = createConsumer("BrokerA", createDestination("Consumer.A.VirtualTopic.tempTopic", false)); + MessageConsumer clientB = createConsumer("BrokerB", createDestination("Consumer.B.VirtualTopic.tempTopic", false)); + MessageConsumer clientC = createConsumer("BrokerB", createDestination("VirtualTopic.tempTopic", true)); - startAllBrokers(); - waitForBridgeFormation(); + // give a sec to let advisories propagate + Thread.sleep(500); - MessageConsumer clientA = createConsumer("BrokerA", createDestination("Consumer.A.VirtualTopic.tempTopic", false)); - MessageConsumer clientB = createConsumer("BrokerB", createDestination("Consumer.B.VirtualTopic.tempTopic", false)); - MessageConsumer clientC = createConsumer("BrokerB", createDestination("VirtualTopic.tempTopic", true)); + ActiveMQQueue queueA = new ActiveMQQueue("Consumer.A.VirtualTopic.tempTopic"); + Destination destination = getDestination(brokers.get("BrokerA").broker, queueA); + assertEquals(1, destination.getConsumers().size()); + ActiveMQQueue queueB = new ActiveMQQueue("Consumer.B.VirtualTopic.tempTopic"); + destination = getDestination(brokers.get("BrokerA").broker, queueB); + assertNull(destination); - // give a sec to let advisories propagate - Thread.sleep(500); + ActiveMQTopic virtualTopic = new ActiveMQTopic("VirtualTopic.tempTopic"); + assertNotNull(getDestination(brokers.get("BrokerA").broker, virtualTopic)); + assertNotNull(getDestination(brokers.get("BrokerB").broker, virtualTopic)); - ActiveMQQueue queueA = new ActiveMQQueue("Consumer.A.VirtualTopic.tempTopic"); - Destination destination = getDestination(brokers.get("BrokerA").broker, queueA); - assertEquals(1, destination.getConsumers().size()); + // send some messages + sendMessages("BrokerA", virtualTopic, 1); - ActiveMQQueue queueB = new ActiveMQQueue("Consumer.B.VirtualTopic.tempTopic"); - destination = getDestination(brokers.get("BrokerA").broker, queueB); - assertNull(destination); + MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); + MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - ActiveMQTopic virtualTopic = new ActiveMQTopic("VirtualTopic.tempTopic"); - assertNotNull(getDestination(brokers.get("BrokerA").broker, virtualTopic)); - assertNotNull(getDestination(brokers.get("BrokerB").broker, virtualTopic)); + msgsA.waitForMessagesToArrive(1); + msgsB.waitForMessagesToArrive(1); - // send some messages - sendMessages("BrokerA", virtualTopic, 1); + // ensure we don't get any more messages + Thread.sleep(2000); - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); + assertEquals(1, msgsA.getMessageCount()); + assertEquals(1, msgsB.getMessageCount()); + } - msgsA.waitForMessagesToArrive(1); - msgsB.waitForMessagesToArrive(1); + private void bridgeAndConfigureBrokers(String local, String remote) throws Exception { + NetworkConnector bridge = bridgeBrokers(local, remote); + bridge.setDecreaseNetworkConsumerPriority(true); + } - // ensure we don't get any more messages - Thread.sleep(2000); + private void dontBridgeVirtualTopicConsumerQueues(String local, String remote) throws Exception { + NetworkConnector bridge = bridgeBrokers(local, remote); + bridge.setDecreaseNetworkConsumerPriority(true); - assertEquals(1, msgsA.getMessageCount()); - assertEquals(1, msgsB.getMessageCount()); - } + LinkedList excludedDestinations = new LinkedList(); + excludedDestinations.add(new ActiveMQQueue("Consumer.*.VirtualTopic.>")); - private void bridgeAndConfigureBrokers(String local, String remote) throws Exception { - NetworkConnector bridge = bridgeBrokers(local, remote); - bridge.setDecreaseNetworkConsumerPriority(true); - } + bridge.setExcludedDestinations(excludedDestinations); - private void dontBridgeVirtualTopicConsumerQueues(String local, String remote) throws Exception { - NetworkConnector bridge = bridgeBrokers(local, remote); - bridge.setDecreaseNetworkConsumerPriority(true); + } - LinkedList excludedDestinations = new LinkedList(); - excludedDestinations.add(new ActiveMQQueue("Consumer.*.VirtualTopic.>")); + public void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); + String options = new String("?useJmx=false&deleteAllMessagesOnStartup=true"); + createAndConfigureBroker(new URI("broker:(tcp://localhost:61616)/BrokerA" + options)); + createAndConfigureBroker(new URI("broker:(tcp://localhost:61617)/BrokerB" + options)); + } - bridge.setExcludedDestinations(excludedDestinations); + private BrokerService createAndConfigureBroker(URI uri) throws Exception { + BrokerService broker = createBroker(uri); + configurePersistenceAdapter(broker); + return broker; + } - } - - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - String options = new String("?useJmx=false&deleteAllMessagesOnStartup=true"); - createAndConfigureBroker(new URI("broker:(tcp://localhost:61616)/BrokerA" + options)); - createAndConfigureBroker(new URI("broker:(tcp://localhost:61617)/BrokerB" + options)); - } - - private BrokerService createAndConfigureBroker(URI uri) throws Exception { - BrokerService broker = createBroker(uri); - configurePersistenceAdapter(broker); - return broker; - } - - protected void configurePersistenceAdapter(BrokerService broker) throws IOException { - File dataFileDir = new File("target/test-amq-data/kahadb/" + broker.getBrokerName()); - KahaDBStore kaha = new KahaDBStore(); - kaha.setDirectory(dataFileDir); - broker.setPersistenceAdapter(kaha); - } + protected void configurePersistenceAdapter(BrokerService broker) throws IOException { + File dataFileDir = new File("target/test-amq-data/kahadb/" + broker.getBrokerName()); + KahaDBStore kaha = new KahaDBStore(); + kaha.setDirectory(dataFileDir); + broker.setPersistenceAdapter(kaha); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoMulticastDiscoveryBrokerTopicSendReceiveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoMulticastDiscoveryBrokerTopicSendReceiveTest.java index f05f993c98..6270fb17ca 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoMulticastDiscoveryBrokerTopicSendReceiveTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoMulticastDiscoveryBrokerTopicSendReceiveTest.java @@ -21,21 +21,21 @@ import javax.jms.JMSException; import org.apache.activemq.ActiveMQConnectionFactory; /** - * reproduced: https://issues.apache.org/jira/browse/AMQ-4107 + * reproduced: https://issues.apache.org/jira/browse/AMQ-4107 */ public class TwoMulticastDiscoveryBrokerTopicSendReceiveTest extends TwoBrokerTopicSendReceiveTest { - protected ActiveMQConnectionFactory createReceiverConnectionFactory() throws JMSException { - return createConnectionFactory("org/apache/activemq/usecases/receiver-discovery.xml", "receiver", "vm://receiver"); - } + protected ActiveMQConnectionFactory createReceiverConnectionFactory() throws JMSException { + return createConnectionFactory("org/apache/activemq/usecases/receiver-discovery.xml", "receiver", "vm://receiver"); + } - protected ActiveMQConnectionFactory createSenderConnectionFactory() throws JMSException { - return createConnectionFactory("org/apache/activemq/usecases/sender-discovery.xml", "sender", "vm://sender"); - } - - protected void setUp() throws Exception{ - System.setProperty("groupId", getClass().getName()+"-"+System.currentTimeMillis()); - messageCount = 100000; - super.setUp(); - } + protected ActiveMQConnectionFactory createSenderConnectionFactory() throws JMSException { + return createConnectionFactory("org/apache/activemq/usecases/sender-discovery.xml", "sender", "vm://sender"); + } + + protected void setUp() throws Exception { + System.setProperty("groupId", getClass().getName() + "-" + System.currentTimeMillis()); + messageCount = 100000; + super.setUp(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoSecureBrokerRequestReplyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoSecureBrokerRequestReplyTest.java index dca3b08914..63525cddd7 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoSecureBrokerRequestReplyTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoSecureBrokerRequestReplyTest.java @@ -30,60 +30,59 @@ import javax.jms.Session; import javax.jms.TemporaryQueue; public class TwoSecureBrokerRequestReplyTest extends JmsMultipleBrokersTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(TwoSecureBrokerRequestReplyTest.class); - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); + private static final Logger LOG = LoggerFactory.getLogger(TwoSecureBrokerRequestReplyTest.class); - createBroker(new ClassPathResource("org/apache/activemq/usecases/sender-secured.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/receiver-secured.xml")); - } + public void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); - public void testRequestReply() throws Exception { - ActiveMQQueue requestReplyDest = new ActiveMQQueue("RequestReply"); + createBroker(new ClassPathResource("org/apache/activemq/usecases/sender-secured.xml")); + createBroker(new ClassPathResource("org/apache/activemq/usecases/receiver-secured.xml")); + } - startAllBrokers(); - waitForBridgeFormation(); - waitForMinTopicRegionConsumerCount("sender", 1); - waitForMinTopicRegionConsumerCount("receiver", 1); + public void testRequestReply() throws Exception { + ActiveMQQueue requestReplyDest = new ActiveMQQueue("RequestReply"); + startAllBrokers(); + waitForBridgeFormation(); + waitForMinTopicRegionConsumerCount("sender", 1); + waitForMinTopicRegionConsumerCount("receiver", 1); - ConnectionFactory factory = getConnectionFactory("sender"); - ActiveMQConnection conn = (ActiveMQConnection) factory.createConnection("system", "manager"); - conn.setWatchTopicAdvisories(false); - conn.start(); - Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + ConnectionFactory factory = getConnectionFactory("sender"); + ActiveMQConnection conn = (ActiveMQConnection) factory.createConnection("system", "manager"); + conn.setWatchTopicAdvisories(false); + conn.start(); + Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - ConnectionFactory replyFactory = getConnectionFactory("receiver"); - for (int i = 0; i < 2000; i++) { - TemporaryQueue tempDest = session.createTemporaryQueue(); - MessageProducer producer = session.createProducer(requestReplyDest); - javax.jms.Message message = session.createTextMessage("req-" + i); - message.setJMSReplyTo(tempDest); + ConnectionFactory replyFactory = getConnectionFactory("receiver"); + for (int i = 0; i < 2000; i++) { + TemporaryQueue tempDest = session.createTemporaryQueue(); + MessageProducer producer = session.createProducer(requestReplyDest); + javax.jms.Message message = session.createTextMessage("req-" + i); + message.setJMSReplyTo(tempDest); - ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer) session.createConsumer(tempDest); - producer.send(message); + ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer) session.createConsumer(tempDest); + producer.send(message); - ActiveMQConnection replyConnection = (ActiveMQConnection) replyFactory.createConnection("system", "manager"); - replyConnection.setWatchTopicAdvisories(false); - replyConnection.start(); - Session replySession = replyConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQMessageConsumer replyConsumer = (ActiveMQMessageConsumer) replySession.createConsumer(requestReplyDest); - javax.jms.Message msg = replyConsumer.receive(10000); - assertNotNull("request message not null: " + i, msg); - MessageProducer replyProducer = replySession.createProducer(msg.getJMSReplyTo()); - replyProducer.send(session.createTextMessage("reply-" + i)); - replyConnection.close(); + ActiveMQConnection replyConnection = (ActiveMQConnection) replyFactory.createConnection("system", "manager"); + replyConnection.setWatchTopicAdvisories(false); + replyConnection.start(); + Session replySession = replyConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQMessageConsumer replyConsumer = (ActiveMQMessageConsumer) replySession.createConsumer(requestReplyDest); + javax.jms.Message msg = replyConsumer.receive(10000); + assertNotNull("request message not null: " + i, msg); + MessageProducer replyProducer = replySession.createProducer(msg.getJMSReplyTo()); + replyProducer.send(session.createTextMessage("reply-" + i)); + replyConnection.close(); - javax.jms.Message reply = consumer.receive(10000); - assertNotNull("reply message : " + i + ", to: " + tempDest + ", by consumer:" + consumer.getConsumerId(), reply); - consumer.close(); - tempDest.delete(); - LOG.info("message #" + i + " processed"); - } - - } + javax.jms.Message reply = consumer.receive(10000); + assertNotNull("reply message : " + i + ", to: " + tempDest + ", by consumer:" + consumer.getConsumerId(), reply); + consumer.close(); + tempDest.delete(); + LOG.info("message #" + i + " processed"); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/UnlimitedEnqueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/UnlimitedEnqueueTest.java index f2c555596d..e5c287f22a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/UnlimitedEnqueueTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/UnlimitedEnqueueTest.java @@ -45,93 +45,95 @@ import org.slf4j.LoggerFactory; import static org.junit.Assert.assertTrue; -public class UnlimitedEnqueueTest { +public class UnlimitedEnqueueTest { - private static final Logger LOG = LoggerFactory.getLogger(UnlimitedEnqueueTest.class); - BrokerService brokerService = null; - final long numMessages = 5000; - final long numThreads = 10; - final int payLoadSize = 100*1024; + private static final Logger LOG = LoggerFactory.getLogger(UnlimitedEnqueueTest.class); + BrokerService brokerService = null; + final long numMessages = 5000; + final long numThreads = 10; + final int payLoadSize = 100 * 1024; - @Test - public void testEnqueueIsOnlyLimitedByDisk() throws Exception { - ExecutorService executor = Executors.newCachedThreadPool(); - for (int i=0; i 1; + assertTrue("Temp Store is filling ", Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + LOG.info("Temp Usage, " + brokerService.getSystemUsage().getTempUsage() + ", full=" + brokerService.getSystemUsage().getTempUsage().isFull() + ", % usage: " + brokerService.getSystemUsage().getTempUsage().getPercentUsage()); + return brokerService.getSystemUsage().getTempUsage().getPercentUsage() > 1; + } + }, TimeUnit.MINUTES.toMillis(4))); + executor.shutdownNow(); + } + + @Before + public void createBrokerService() throws Exception { + brokerService = new BrokerService(); + brokerService.setDeleteAllMessagesOnStartup(true); + brokerService.setAdvisorySupport(false); + + // optional, reduce the usage limit so that spooling will occur faster + brokerService.getSystemUsage().getMemoryUsage().setLimit(10 * 1024 * 1024); + brokerService.getSystemUsage().getTempUsage().setLimit((numMessages * payLoadSize) + (1000 * payLoadSize)); + + PolicyMap policyMap = new PolicyMap(); + List entries = new ArrayList(); + PolicyEntry policy = new PolicyEntry(); + + // NB: ensure queue cursor limit is below the default 70% usage that the destination will use + // if they are the same, the queue memory limit and flow control will kick in first + policy.setCursorMemoryHighWaterMark(20); + + // on by default + //policy.setProducerFlowControl(true); + policy.setQueue(">"); + + // policy that will spool references to disk + policy.setPendingQueuePolicy(new FilePendingQueueMessageStoragePolicy()); + entries.add(policy); + policyMap.setPolicyEntries(entries); + brokerService.setDestinationPolicy(policyMap); + + brokerService.start(); + } + + public class Producer implements Runnable { + + private final long numberOfMessages; + + public Producer(final long n) { + this.numberOfMessages = n; + } + + public void run() { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerService.getVmConnectorURI()); + try { + Connection conn = factory.createConnection(); + conn.start(); + byte[] bytes = new byte[payLoadSize]; + for (int i = 0; i < numberOfMessages; i++) { + Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = session.createQueue("test-queue"); + MessageProducer producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.PERSISTENT); + BytesMessage message = session.createBytesMessage(); + message.writeBytes(bytes); + try { + producer.send(message); + } + catch (ResourceAllocationException e) { + e.printStackTrace(); + } + session.close(); } - }, TimeUnit.MINUTES.toMillis(4))); - executor.shutdownNow(); - } - - @Before - public void createBrokerService() throws Exception { - brokerService = new BrokerService(); - brokerService.setDeleteAllMessagesOnStartup(true); - brokerService.setAdvisorySupport(false); - - // optional, reduce the usage limit so that spooling will occur faster - brokerService.getSystemUsage().getMemoryUsage().setLimit(10 * 1024 * 1024); - brokerService.getSystemUsage().getTempUsage().setLimit((numMessages * payLoadSize) + (1000 * payLoadSize)); - - PolicyMap policyMap = new PolicyMap(); - List entries = new ArrayList(); - PolicyEntry policy = new PolicyEntry(); - - // NB: ensure queue cursor limit is below the default 70% usage that the destination will use - // if they are the same, the queue memory limit and flow control will kick in first - policy.setCursorMemoryHighWaterMark(20); - - // on by default - //policy.setProducerFlowControl(true); - policy.setQueue(">"); - - // policy that will spool references to disk - policy.setPendingQueuePolicy(new FilePendingQueueMessageStoragePolicy()); - entries.add(policy); - policyMap.setPolicyEntries(entries); - brokerService.setDestinationPolicy(policyMap); - - brokerService.start(); - } - - public class Producer implements Runnable{ - - private final long numberOfMessages; - - public Producer(final long n){ - this.numberOfMessages = n; - } - - public void run(){ - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerService.getVmConnectorURI()); - try { - Connection conn = factory.createConnection(); - conn.start(); - byte[] bytes = new byte[payLoadSize]; - for (int i = 0; i < numberOfMessages; i++) { - Session session = conn.createSession(false,Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue("test-queue"); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - BytesMessage message = session.createBytesMessage(); - message.writeBytes(bytes); - try { - producer.send(message); - } catch (ResourceAllocationException e) { - e.printStackTrace(); - } - session.close(); - } - } catch (JMSException e) { - // expect interrupted exception on shutdownNow - } - } - } + } + catch (JMSException e) { + // expect interrupted exception on shutdownNow + } + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/VerifyNetworkConsumersDisconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/VerifyNetworkConsumersDisconnectTest.java index eb5a3e28c6..3d5aa85fd5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/VerifyNetworkConsumersDisconnectTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/VerifyNetworkConsumersDisconnectTest.java @@ -28,6 +28,7 @@ import java.util.concurrent.atomic.AtomicInteger; import javax.jms.Destination; import javax.jms.MessageConsumer; import javax.management.ObjectName; + import org.apache.activemq.JmsMultipleBrokersTestSupport; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.jmx.ManagementContext; @@ -40,225 +41,233 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class VerifyNetworkConsumersDisconnectTest extends JmsMultipleBrokersTestSupport implements UncaughtExceptionHandler { - public static final int BROKER_COUNT = 3; - public static final int CONSUMER_COUNT = 5; - public static final int MESSAGE_COUNT = 0; - public static final boolean DUPLEX = false; - public static final boolean CONDUIT = true; - public static final int NETWORK_TTL = 6; - private static final Logger LOG = LoggerFactory.getLogger(VerifyNetworkConsumersDisconnectTest.class); - public static final int TIMEOUT = 30000; + public static final int BROKER_COUNT = 3; + public static final int CONSUMER_COUNT = 5; + public static final int MESSAGE_COUNT = 0; + public static final boolean DUPLEX = false; + public static final boolean CONDUIT = true; - protected Map consumerMap; - final Map unhandledExceptions = new HashMap(); + public static final int NETWORK_TTL = 6; + private static final Logger LOG = LoggerFactory.getLogger(VerifyNetworkConsumersDisconnectTest.class); + public static final int TIMEOUT = 30000; - private void assertNoUnhandledExceptions() { - for( Entry e: unhandledExceptions.entrySet()) { - LOG.error("Thread:" + e.getKey() + " Had unexpected: " + e.getValue()); - } - assertTrue("There are no unhandled exceptions, see: log for detail on: " + unhandledExceptions, - unhandledExceptions.isEmpty()); - } + protected Map consumerMap; + final Map unhandledExceptions = new HashMap(); - public NetworkConnector bridge(String from, String to) throws Exception { - NetworkConnector networkConnector = bridgeBrokers(from, to, true, NETWORK_TTL, CONDUIT); - networkConnector.setSuppressDuplicateQueueSubscriptions(true); - networkConnector.setDecreaseNetworkConsumerPriority(true); - networkConnector.setDuplex(DUPLEX); - return networkConnector; - } + private void assertNoUnhandledExceptions() { + for (Entry e : unhandledExceptions.entrySet()) { + LOG.error("Thread:" + e.getKey() + " Had unexpected: " + e.getValue()); + } + assertTrue("There are no unhandled exceptions, see: log for detail on: " + unhandledExceptions, unhandledExceptions.isEmpty()); + } - /*why conduit proxy proxy consumers gets us in a knot w.r.t removal - DC-7 for CA-9, add DB-15, remove CA-9, add CB-8 - CB-8 add DC-7 - CB-8 - why not dead? - CB-8 for BA-6, add BD-15, remove BA-6 - BD-15 for DA-11, add DC-7 - */ - public void testConsumerOnEachBroker() throws Exception { - bridge("Broker0", "Broker1"); - if (!DUPLEX) bridge("Broker1", "Broker0"); + public NetworkConnector bridge(String from, String to) throws Exception { + NetworkConnector networkConnector = bridgeBrokers(from, to, true, NETWORK_TTL, CONDUIT); + networkConnector.setSuppressDuplicateQueueSubscriptions(true); + networkConnector.setDecreaseNetworkConsumerPriority(true); + networkConnector.setDuplex(DUPLEX); + return networkConnector; + } - bridge("Broker1", "Broker2"); - if (!DUPLEX) bridge("Broker2", "Broker1"); + /*why conduit proxy proxy consumers gets us in a knot w.r.t removal + DC-7 for CA-9, add DB-15, remove CA-9, add CB-8 + CB-8 add DC-7 + CB-8 - why not dead? + CB-8 for BA-6, add BD-15, remove BA-6 + BD-15 for DA-11, add DC-7 + */ + public void testConsumerOnEachBroker() throws Exception { + bridge("Broker0", "Broker1"); + if (!DUPLEX) + bridge("Broker1", "Broker0"); - startAllBrokers(); - waitForBridgeFormation(brokers.get("Broker0").broker, 1, 0); - waitForBridgeFormation(brokers.get("Broker2").broker, 1, 0); - waitForBridgeFormation(brokers.get("Broker1").broker, 1, 0); - waitForBridgeFormation(brokers.get("Broker1").broker, 1, 1); + bridge("Broker1", "Broker2"); + if (!DUPLEX) + bridge("Broker2", "Broker1"); - Destination dest = createDestination("TEST.FOO", false); + startAllBrokers(); + waitForBridgeFormation(brokers.get("Broker0").broker, 1, 0); + waitForBridgeFormation(brokers.get("Broker2").broker, 1, 0); + waitForBridgeFormation(brokers.get("Broker1").broker, 1, 0); + waitForBridgeFormation(brokers.get("Broker1").broker, 1, 1); - // Setup consumers - for (int i = 0; i < BROKER_COUNT; i++) { - consumerMap.put("Consumer:" + i + ":0", createConsumer("Broker" + i, dest)); - } + Destination dest = createDestination("TEST.FOO", false); - assertExactConsumersConnect("Broker0", 3, 1, TIMEOUT); - assertExactConsumersConnect("Broker2", 3, 1, TIMEOUT); - // piggy in the middle - assertExactConsumersConnect("Broker1", 3, 1, TIMEOUT); + // Setup consumers + for (int i = 0; i < BROKER_COUNT; i++) { + consumerMap.put("Consumer:" + i + ":0", createConsumer("Broker" + i, dest)); + } - assertNoUnhandledExceptions(); + assertExactConsumersConnect("Broker0", 3, 1, TIMEOUT); + assertExactConsumersConnect("Broker2", 3, 1, TIMEOUT); + // piggy in the middle + assertExactConsumersConnect("Broker1", 3, 1, TIMEOUT); - LOG.info("Complete the mesh - 0->2"); + assertNoUnhandledExceptions(); - // shorter route - NetworkConnector nc = bridge("Broker0", "Broker2"); - nc.setBrokerName("Broker0"); - nc.start(); + LOG.info("Complete the mesh - 0->2"); + // shorter route + NetworkConnector nc = bridge("Broker0", "Broker2"); + nc.setBrokerName("Broker0"); + nc.start(); - if (!DUPLEX) { - LOG.info("... complete the mesh - 2->0"); - nc = bridge("Broker2", "Broker0"); - nc.setBrokerName("Broker2"); - nc.start(); - } + if (!DUPLEX) { + LOG.info("... complete the mesh - 2->0"); + nc = bridge("Broker2", "Broker0"); + nc.setBrokerName("Broker2"); + nc.start(); + } - // wait for consumers to get propagated - for (int i = 0; i < BROKER_COUNT; i++) { - assertExactConsumersConnect("Broker" + i, 3, 1, TIMEOUT); - } + // wait for consumers to get propagated + for (int i = 0; i < BROKER_COUNT; i++) { + assertExactConsumersConnect("Broker" + i, 3, 1, TIMEOUT); + } - // reverse order close - consumerMap.get("Consumer:" + 2 + ":0").close(); - TimeUnit.SECONDS.sleep(1); - consumerMap.get("Consumer:" + 1 + ":0").close(); - TimeUnit.SECONDS.sleep(1); - consumerMap.get("Consumer:" + 0 + ":0").close(); + // reverse order close + consumerMap.get("Consumer:" + 2 + ":0").close(); + TimeUnit.SECONDS.sleep(1); + consumerMap.get("Consumer:" + 1 + ":0").close(); + TimeUnit.SECONDS.sleep(1); + consumerMap.get("Consumer:" + 0 + ":0").close(); - LOG.info("Check for no consumers.."); - for (int i = 0; i < BROKER_COUNT; i++) { - assertExactConsumersConnect("Broker" + i, 0, 0, TIMEOUT); - } + LOG.info("Check for no consumers.."); + for (int i = 0; i < BROKER_COUNT; i++) { + assertExactConsumersConnect("Broker" + i, 0, 0, TIMEOUT); + } - } + } - public void testXConsumerOnEachBroker() throws Exception { - bridge("Broker0", "Broker1"); - if (!DUPLEX) bridge("Broker1", "Broker0"); + public void testXConsumerOnEachBroker() throws Exception { + bridge("Broker0", "Broker1"); + if (!DUPLEX) + bridge("Broker1", "Broker0"); - bridge("Broker1", "Broker2"); - if (!DUPLEX) bridge("Broker2", "Broker1"); + bridge("Broker1", "Broker2"); + if (!DUPLEX) + bridge("Broker2", "Broker1"); - startAllBrokers(); + startAllBrokers(); - waitForBridgeFormation(brokers.get("Broker0").broker, 1, 0); - waitForBridgeFormation(brokers.get("Broker2").broker, 1, 0); - waitForBridgeFormation(brokers.get("Broker1").broker, 1, 0); - waitForBridgeFormation(brokers.get("Broker1").broker, 1, 1); + waitForBridgeFormation(brokers.get("Broker0").broker, 1, 0); + waitForBridgeFormation(brokers.get("Broker2").broker, 1, 0); + waitForBridgeFormation(brokers.get("Broker1").broker, 1, 0); + waitForBridgeFormation(brokers.get("Broker1").broker, 1, 1); - Destination dest = createDestination("TEST.FOO", false); + Destination dest = createDestination("TEST.FOO", false); - // Setup consumers - for (int i = 0; i < BROKER_COUNT; i++) { - for (int j=0; j< CONSUMER_COUNT; j++) + // Setup consumers + for (int i = 0; i < BROKER_COUNT; i++) { + for (int j = 0; j < CONSUMER_COUNT; j++) consumerMap.put("Consumer:" + i + ":" + j, createConsumer("Broker" + i, dest)); - } + } - for (int i = 0; i < BROKER_COUNT; i++) { - assertExactConsumersConnect("Broker" + i, CONSUMER_COUNT + (BROKER_COUNT -1), 1, TIMEOUT); - } + for (int i = 0; i < BROKER_COUNT; i++) { + assertExactConsumersConnect("Broker" + i, CONSUMER_COUNT + (BROKER_COUNT - 1), 1, TIMEOUT); + } - assertNoUnhandledExceptions(); + assertNoUnhandledExceptions(); - LOG.info("Complete the mesh - 0->2"); + LOG.info("Complete the mesh - 0->2"); - // shorter route - NetworkConnector nc = bridge("Broker0", "Broker2"); - nc.setBrokerName("Broker0"); - nc.start(); + // shorter route + NetworkConnector nc = bridge("Broker0", "Broker2"); + nc.setBrokerName("Broker0"); + nc.start(); - waitForBridgeFormation(brokers.get("Broker0").broker, 1, 1); + waitForBridgeFormation(brokers.get("Broker0").broker, 1, 1); - if (!DUPLEX) { - LOG.info("... complete the mesh - 2->0"); - nc = bridge("Broker2", "Broker0"); - nc.setBrokerName("Broker2"); - nc.start(); - } + if (!DUPLEX) { + LOG.info("... complete the mesh - 2->0"); + nc = bridge("Broker2", "Broker0"); + nc.setBrokerName("Broker2"); + nc.start(); + } - waitForBridgeFormation(brokers.get("Broker2").broker, 1, 1); + waitForBridgeFormation(brokers.get("Broker2").broker, 1, 1); - for (int i = 0; i < BROKER_COUNT; i++) { - assertExactConsumersConnect("Broker" + i, CONSUMER_COUNT + (BROKER_COUNT -1), 1, TIMEOUT); - } + for (int i = 0; i < BROKER_COUNT; i++) { + assertExactConsumersConnect("Broker" + i, CONSUMER_COUNT + (BROKER_COUNT - 1), 1, TIMEOUT); + } - // reverse order close - for (int i=0; i consumerIds = new LinkedList(); - for (ObjectName objectName : queueViewMBean.getSubscriptions()) { - consumerIds.add(objectName.getKeyProperty("consumerId")); - } - LOG.info("Sub IDs: " + consumerIds); - if (currentCount == count) { - stability.incrementAndGet(); - } else { - stability.set(0); - } - return stability.get() > numChecks; - } catch (Exception e) { - LOG.warn(": ", e); - return false; - } + protected void assertExactConsumersConnect(final String brokerName, + final int count, + final int numChecks, + long timeout) throws Exception { + final ManagementContext context = brokers.get(brokerName).broker.getManagementContext(); + final AtomicInteger stability = new AtomicInteger(0); + assertTrue("Expected consumers count: " + count + " on: " + brokerName, Wait.waitFor(new Wait.Condition() { + @Override + public boolean isSatisified() throws Exception { + try { + QueueViewMBean queueViewMBean = (QueueViewMBean) context.newProxyInstance(brokers.get(brokerName).broker.getAdminView().getQueues()[0], QueueViewMBean.class, false); + long currentCount = queueViewMBean.getConsumerCount(); + LOG.info("On " + brokerName + " current consumer count for " + queueViewMBean + ", " + currentCount); + LinkedList consumerIds = new LinkedList(); + for (ObjectName objectName : queueViewMBean.getSubscriptions()) { + consumerIds.add(objectName.getKeyProperty("consumerId")); + } + LOG.info("Sub IDs: " + consumerIds); + if (currentCount == count) { + stability.incrementAndGet(); + } + else { + stability.set(0); + } + return stability.get() > numChecks; } - }, timeout)); - } + catch (Exception e) { + LOG.warn(": ", e); + return false; + } + } + }, timeout)); + } - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); + public void setUp() throws Exception { + super.setAutoFail(true); + super.setUp(); - unhandledExceptions.clear(); - Thread.setDefaultUncaughtExceptionHandler(this); - - // Setup n brokers - for (int i = 0; i < BROKER_COUNT; i++) { - createBroker(new URI("broker:(tcp://localhost:6161" + i + ")/Broker" + i + "?persistent=false&useJmx=true&brokerId=Broker" + i)); - } + unhandledExceptions.clear(); + Thread.setDefaultUncaughtExceptionHandler(this); - consumerMap = new LinkedHashMap(); - } + // Setup n brokers + for (int i = 0; i < BROKER_COUNT; i++) { + createBroker(new URI("broker:(tcp://localhost:6161" + i + ")/Broker" + i + "?persistent=false&useJmx=true&brokerId=Broker" + i)); + } - @Override - protected void configureBroker(BrokerService brokerService) { - PolicyEntry policyEntry = new PolicyEntry(); - policyEntry.setExpireMessagesPeriod(0); - PolicyMap policyMap = new PolicyMap(); - policyMap.setDefaultEntry(policyEntry); - brokerService.setDestinationPolicy(policyMap); - } + consumerMap = new LinkedHashMap(); + } - public void uncaughtException(Thread t, Throwable e) { - synchronized(unhandledExceptions) { - unhandledExceptions.put(t, e); - } - } + @Override + protected void configureBroker(BrokerService brokerService) { + PolicyEntry policyEntry = new PolicyEntry(); + policyEntry.setExpireMessagesPeriod(0); + PolicyMap policyMap = new PolicyMap(); + policyMap.setDefaultEntry(policyEntry); + brokerService.setDestinationPolicy(policyMap); + } + + public void uncaughtException(Thread t, Throwable e) { + synchronized (unhandledExceptions) { + unhandledExceptions.put(t, e); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/VirtualTopicNetworkClusterReactivationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/VirtualTopicNetworkClusterReactivationTest.java index f6e002562c..5d24d8be22 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/VirtualTopicNetworkClusterReactivationTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/VirtualTopicNetworkClusterReactivationTest.java @@ -34,143 +34,139 @@ import java.net.URI; */ public class VirtualTopicNetworkClusterReactivationTest extends JmsMultipleBrokersTestSupport { - private static final String BROKER_A = "brokerA"; - private static final String BROKER_B = "brokerB"; - private static final String BROKER_A_TRANSPORT_URL = "tcp://localhost:61616"; - private static final String BROKER_B_TRANSPORT_URL = "tcp://localhost:61617"; - private static final long DEFAULT_SLEEP_MS = 1000; + private static final String BROKER_A = "brokerA"; + private static final String BROKER_B = "brokerB"; + private static final String BROKER_A_TRANSPORT_URL = "tcp://localhost:61616"; + private static final String BROKER_B_TRANSPORT_URL = "tcp://localhost:61617"; + private static final long DEFAULT_SLEEP_MS = 1000; - private ActiveMQTopic topic = new ActiveMQTopic("VirtualTopic.FOO.TEST"); - private ActiveMQQueue queue = new ActiveMQQueue("Consumer.FOO.VirtualTopic.FOO.TEST"); + private ActiveMQTopic topic = new ActiveMQTopic("VirtualTopic.FOO.TEST"); + private ActiveMQQueue queue = new ActiveMQQueue("Consumer.FOO.VirtualTopic.FOO.TEST"); + /** + * This test shows how to use pub/sub to mimic durable subscribers in a network of brokers. + * + * When using durable subscribers in a broker cluster, you can encounter a situation where a + * subscription gets orphaned on a broker when the client disconnects and reattaches to another + * broker in the cluster. Since the clientID/durableName only need to be unique within a single + * broker, it's possible to have a durable sub on multiple brokers in a cluster. + * + * FOR EXAMPLE: + * Broker A and B are networked together in both directions to form a full mesh. If durable + * subscriber 'foo' subscribes to failover(A,B) and ends up on B, and a producer on A, messages + * will be demand forwarded from A to B. But if the durable sub 'foo' disconnects from B, + * then reconnects to failover(A,B) but this time gets connected to A, the subscription on + * B will still be there are continue to receive messages (and possibly have missed messages + * sent there while gone) + * + * We can avoid all of this mess with virtual topics as seen below: + * + * @throws JMSException + */ + public void testDurableSubReconnectFromAtoB() throws JMSException { + // create consumer on broker B + ActiveMQConnectionFactory bConnFactory = new ActiveMQConnectionFactory(BROKER_B_TRANSPORT_URL + "?jms.prefetchPolicy.queuePrefetch=0"); + Connection bConn = bConnFactory.createConnection(); + bConn.start(); + Session bSession = bConn.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer bSessionConsumer = bSession.createConsumer(queue); - /** - * This test shows how to use pub/sub to mimic durable subscribers in a network of brokers. - * - * When using durable subscribers in a broker cluster, you can encounter a situation where a - * subscription gets orphaned on a broker when the client disconnects and reattaches to another - * broker in the cluster. Since the clientID/durableName only need to be unique within a single - * broker, it's possible to have a durable sub on multiple brokers in a cluster. - * - * FOR EXAMPLE: - * Broker A and B are networked together in both directions to form a full mesh. If durable - * subscriber 'foo' subscribes to failover(A,B) and ends up on B, and a producer on A, messages - * will be demand forwarded from A to B. But if the durable sub 'foo' disconnects from B, - * then reconnects to failover(A,B) but this time gets connected to A, the subscription on - * B will still be there are continue to receive messages (and possibly have missed messages - * sent there while gone) - * - * We can avoid all of this mess with virtual topics as seen below: - * - * - * @throws JMSException - */ - public void testDurableSubReconnectFromAtoB() throws JMSException { - // create consumer on broker B - ActiveMQConnectionFactory bConnFactory = new ActiveMQConnectionFactory(BROKER_B_TRANSPORT_URL+ "?jms.prefetchPolicy.queuePrefetch=0"); - Connection bConn = bConnFactory.createConnection(); - bConn.start(); - Session bSession = bConn.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer bSessionConsumer = bSession.createConsumer(queue); + // create producer on A + ActiveMQConnectionFactory aConnFactory = new ActiveMQConnectionFactory(BROKER_A_TRANSPORT_URL); + Connection aProducerConn = aConnFactory.createConnection(); + aProducerConn.start(); + Session aProducerSession = aProducerConn.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = aProducerSession.createProducer(topic); + produce(producer, aProducerSession, 5); - // create producer on A - ActiveMQConnectionFactory aConnFactory = new ActiveMQConnectionFactory(BROKER_A_TRANSPORT_URL); - Connection aProducerConn = aConnFactory.createConnection(); - aProducerConn.start(); + // sleep for a sec to let the messages get bridged over to broker B + sleep(); - Session aProducerSession = aProducerConn.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = aProducerSession.createProducer(topic); - produce(producer, aProducerSession, 5); + // consumer on B has not consumed any messages, and for some reason goes away: + bSessionConsumer.close(); + bSession.close(); + bConn.close(); - // sleep for a sec to let the messages get bridged over to broker B - sleep(); + // let the bridge catch up + sleep(); - // consumer on B has not consumed any messages, and for some reason goes away: - bSessionConsumer.close(); - bSession.close(); - bConn.close(); + // and now consumer reattaches to A and wants the messages that were sent to B + Connection aConsumerConn = aConnFactory.createConnection(); + aConsumerConn.start(); + Session aConsumerSession = aConsumerConn.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer aSessionConsumer = aConsumerSession.createConsumer(queue); - // let the bridge catch up - sleep(); + sleep(); - // and now consumer reattaches to A and wants the messages that were sent to B - Connection aConsumerConn = aConnFactory.createConnection(); - aConsumerConn.start(); - Session aConsumerSession = aConsumerConn.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer aSessionConsumer = aConsumerSession.createConsumer(queue); + // they should all be there + consume(aSessionConsumer, 5); - sleep(); + } - // they should all be there - consume(aSessionConsumer, 5); + private void consume(MessageConsumer durable, int numMessagesExpected) throws JMSException { + for (int i = 0; i < numMessagesExpected; i++) { + Message message = durable.receive(1000); + assertNotNull(message); + TextMessage textMessage = (TextMessage) message; + System.out.println("received: " + textMessage.getText()); + assertEquals("message: " + i, textMessage.getText()); + } + } - } + private void produce(MessageProducer producer, Session sess, int numMessages) throws JMSException { + for (int i = 0; i < numMessages; i++) { + producer.send(sess.createTextMessage("message: " + i)); + } + } + @Override + protected void setUp() throws Exception { + maxSetupTime = 1000; + super.setAutoFail(true); + super.setUp(); + final String options = "?persistent=true&useJmx=false&deleteAllMessagesOnStartup=true"; - private void consume(MessageConsumer durable, int numMessagesExpected) throws JMSException { - for (int i = 0; i < numMessagesExpected; i++) { - Message message = durable.receive(1000); - assertNotNull(message); - TextMessage textMessage = (TextMessage) message; - System.out.println("received: " + textMessage.getText()); - assertEquals("message: " +i, textMessage.getText()); - } - } + BrokerService brokerServiceA = createBroker(new URI(String.format("broker:(%s)/%s%s", BROKER_A_TRANSPORT_URL, BROKER_A, options))); + brokerServiceA.setDestinationPolicy(buildPolicyMap()); + brokerServiceA.setDestinations(new ActiveMQDestination[]{queue}); - private void produce(MessageProducer producer, Session sess, int numMessages) throws JMSException { - for (int i = 0; i < numMessages; i++) { - producer.send(sess.createTextMessage("message: " + i)); - } - } + BrokerService brokerServiceB = createBroker(new URI(String.format("broker:(%s)/%s%s", BROKER_B_TRANSPORT_URL, BROKER_B, options))); + brokerServiceB.setDestinationPolicy(buildPolicyMap()); + brokerServiceB.setDestinations(new ActiveMQDestination[]{queue}); - @Override - protected void setUp() throws Exception { - maxSetupTime = 1000; - super.setAutoFail(true); - super.setUp(); - final String options = "?persistent=true&useJmx=false&deleteAllMessagesOnStartup=true"; + // bridge brokers to each other statically (static: discovery) + bridgeBrokers(BROKER_A, BROKER_B); + bridgeBrokers(BROKER_B, BROKER_A); - BrokerService brokerServiceA = createBroker(new URI(String.format("broker:(%s)/%s%s", BROKER_A_TRANSPORT_URL, BROKER_A, options))); - brokerServiceA.setDestinationPolicy(buildPolicyMap()); - brokerServiceA.setDestinations(new ActiveMQDestination[]{queue}); + startAllBrokers(); + } - BrokerService brokerServiceB = createBroker(new URI(String.format("broker:(%s)/%s%s", BROKER_B_TRANSPORT_URL, BROKER_B, options))); - brokerServiceB.setDestinationPolicy(buildPolicyMap()); - brokerServiceB.setDestinations(new ActiveMQDestination[]{queue}); + private PolicyMap buildPolicyMap() { + PolicyMap policyMap = new PolicyMap(); + PolicyEntry policyEntry = new PolicyEntry(); + policyEntry.setOptimizedDispatch(true); + ConditionalNetworkBridgeFilterFactory networkBridgeFilterFactory = new ConditionalNetworkBridgeFilterFactory(); + networkBridgeFilterFactory.setReplayWhenNoConsumers(true); + policyEntry.setNetworkBridgeFilterFactory(networkBridgeFilterFactory); + policyEntry.setEnableAudit(false); + policyMap.put(new ActiveMQQueue("Consumer.*.VirtualTopic.>"), policyEntry); + return policyMap; + } + private void sleep() { + try { + Thread.sleep(DEFAULT_SLEEP_MS); + } + catch (InterruptedException igonred) { + } + } - - // bridge brokers to each other statically (static: discovery) - bridgeBrokers(BROKER_A, BROKER_B); - bridgeBrokers(BROKER_B, BROKER_A); - - startAllBrokers(); - } - - private PolicyMap buildPolicyMap() { - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policyEntry = new PolicyEntry(); - policyEntry.setOptimizedDispatch(true); - ConditionalNetworkBridgeFilterFactory networkBridgeFilterFactory = new ConditionalNetworkBridgeFilterFactory(); - networkBridgeFilterFactory.setReplayWhenNoConsumers(true); - policyEntry.setNetworkBridgeFilterFactory(networkBridgeFilterFactory); - policyEntry.setEnableAudit(false); - policyMap.put(new ActiveMQQueue("Consumer.*.VirtualTopic.>"), policyEntry); - return policyMap; - } - - private void sleep() { - try { - Thread.sleep(DEFAULT_SLEEP_MS); - } catch (InterruptedException igonred) { - } - } - - private void sleep(int milliSecondTime) { - try { - Thread.sleep(milliSecondTime); - } catch (InterruptedException igonred) { - } - } + private void sleep(int milliSecondTime) { + try { + Thread.sleep(milliSecondTime); + } + catch (InterruptedException igonred) { + } + } } \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/ConsumerThread.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/ConsumerThread.java index 6b4bad2a8b..11475f3f4c 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/ConsumerThread.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/ConsumerThread.java @@ -23,58 +23,62 @@ import javax.jms.*; public class ConsumerThread extends Thread { - private static final Logger LOG = LoggerFactory.getLogger(ConsumerThread.class); + private static final Logger LOG = LoggerFactory.getLogger(ConsumerThread.class); - int messageCount = 1000; - int received = 0; - Destination dest; - Session sess; - boolean breakOnNull = true; + int messageCount = 1000; + int received = 0; + Destination dest; + Session sess; + boolean breakOnNull = true; - public ConsumerThread(Session sess, Destination dest) { - this.dest = dest; - this.sess = sess; - } + public ConsumerThread(Session sess, Destination dest) { + this.dest = dest; + this.sess = sess; + } - @Override - public void run() { + @Override + public void run() { MessageConsumer consumer = null; - try { - consumer = sess.createConsumer(dest); - while (received < messageCount) { - Message msg = consumer.receive(3000); - if (msg != null) { - LOG.info("Received " + received + ": " + ((TextMessage)msg).getText()); - received++; - } else { - if (breakOnNull) { - break; - } - } + try { + consumer = sess.createConsumer(dest); + while (received < messageCount) { + Message msg = consumer.receive(3000); + if (msg != null) { + LOG.info("Received " + received + ": " + ((TextMessage) msg).getText()); + received++; } - } catch (JMSException e) { - e.printStackTrace(); - } finally { - if (consumer != null) { - try { - consumer.close(); - } catch (JMSException e) { - e.printStackTrace(); - } + else { + if (breakOnNull) { + break; + } } - } - } + } + } + catch (JMSException e) { + e.printStackTrace(); + } + finally { + if (consumer != null) { + try { + consumer.close(); + } + catch (JMSException e) { + e.printStackTrace(); + } + } + } + } - public int getReceived() { - return received; - } + public int getReceived() { + return received; + } - public void setMessageCount(int messageCount) { - this.messageCount = messageCount; - } + public void setMessageCount(int messageCount) { + this.messageCount = messageCount; + } - public void setBreakOnNull(boolean breakOnNull) { - this.breakOnNull = breakOnNull; - } + public void setBreakOnNull(boolean breakOnNull) { + this.breakOnNull = breakOnNull; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/DefaultTestAppender.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/DefaultTestAppender.java index 97ca4b3f5d..7355b64dba 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/DefaultTestAppender.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/DefaultTestAppender.java @@ -23,61 +23,61 @@ import org.apache.log4j.spi.ErrorHandler; import org.apache.log4j.spi.Filter; public abstract class DefaultTestAppender implements Appender { - - String name = this.getClass().getSimpleName(); - - @Override - public void addFilter(Filter newFilter) { - } + String name = this.getClass().getSimpleName(); - @Override - public Filter getFilter() { - return null; - } + @Override + public void addFilter(Filter newFilter) { - @Override - public void clearFilters() { + } - } + @Override + public Filter getFilter() { + return null; + } - @Override - public void close() { + @Override + public void clearFilters() { - } + } - @Override - public String getName() { - return name; - } + @Override + public void close() { - @Override - public void setErrorHandler(ErrorHandler errorHandler) { + } - } + @Override + public String getName() { + return name; + } - @Override - public ErrorHandler getErrorHandler() { - return null; - } + @Override + public void setErrorHandler(ErrorHandler errorHandler) { - @Override - public void setLayout(Layout layout) { + } - } + @Override + public ErrorHandler getErrorHandler() { + return null; + } - @Override - public Layout getLayout() { - return null; - } + @Override + public void setLayout(Layout layout) { - @Override - public void setName(String name) { - this.name = name; - } + } - @Override - public boolean requiresLayout() { - return false; - } + @Override + public Layout getLayout() { + return null; + } + + @Override + public void setName(String name) { + this.name = name; + } + + @Override + public boolean requiresLayout() { + return false; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/LinkedNodeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/LinkedNodeTest.java index 86c526213c..becd42a716 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/LinkedNodeTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/LinkedNodeTest.java @@ -23,151 +23,154 @@ import junit.framework.TestCase; */ public class LinkedNodeTest extends TestCase { - static class IntLinkedNode extends LinkedNode { - public final int v; + static class IntLinkedNode extends LinkedNode { - public IntLinkedNode(int v) { - this.v = v; - }; + public final int v; - @Override - public String toString() { - return "" + v; - } - } + public IntLinkedNode(int v) { + this.v = v; + } - IntLinkedNode i1 = new IntLinkedNode(1); - IntLinkedNode i2 = new IntLinkedNode(2); - IntLinkedNode i3 = new IntLinkedNode(3); - IntLinkedNode i4 = new IntLinkedNode(4); - IntLinkedNode i5 = new IntLinkedNode(5); - IntLinkedNode i6 = new IntLinkedNode(6); + ; - public void testLinkAfter() { + @Override + public String toString() { + return "" + v; + } + } - i1.linkAfter(i2.linkAfter(i3)); - // Order should be 1,2,3 + IntLinkedNode i1 = new IntLinkedNode(1); + IntLinkedNode i2 = new IntLinkedNode(2); + IntLinkedNode i3 = new IntLinkedNode(3); + IntLinkedNode i4 = new IntLinkedNode(4); + IntLinkedNode i5 = new IntLinkedNode(5); + IntLinkedNode i6 = new IntLinkedNode(6); - assertTrue(i1.getNext() == i2); - assertTrue(i1.getNext().getNext() == i3); - assertNull(i1.getNext().getNext().getNext()); + public void testLinkAfter() { - assertTrue(i3.getPrevious() == i2); - assertTrue(i3.getPrevious().getPrevious() == i1); - assertNull(i3.getPrevious().getPrevious().getPrevious()); + i1.linkAfter(i2.linkAfter(i3)); + // Order should be 1,2,3 - assertTrue(i1.isHeadNode()); - assertFalse(i1.isTailNode()); - assertFalse(i2.isHeadNode()); - assertFalse(i2.isTailNode()); - assertTrue(i3.isTailNode()); - assertFalse(i3.isHeadNode()); + assertTrue(i1.getNext() == i2); + assertTrue(i1.getNext().getNext() == i3); + assertNull(i1.getNext().getNext().getNext()); - i1.linkAfter(i4.linkAfter(i5)); + assertTrue(i3.getPrevious() == i2); + assertTrue(i3.getPrevious().getPrevious() == i1); + assertNull(i3.getPrevious().getPrevious().getPrevious()); - // Order should be 1,4,5,2,3 + assertTrue(i1.isHeadNode()); + assertFalse(i1.isTailNode()); + assertFalse(i2.isHeadNode()); + assertFalse(i2.isTailNode()); + assertTrue(i3.isTailNode()); + assertFalse(i3.isHeadNode()); - assertTrue(i1.getNext() == i4); - assertTrue(i1.getNext().getNext() == i5); - assertTrue(i1.getNext().getNext().getNext() == i2); - assertTrue(i1.getNext().getNext().getNext().getNext() == i3); - assertNull(i1.getNext().getNext().getNext().getNext().getNext()); + i1.linkAfter(i4.linkAfter(i5)); - assertTrue(i3.getPrevious() == i2); - assertTrue(i3.getPrevious().getPrevious() == i5); - assertTrue(i3.getPrevious().getPrevious().getPrevious() == i4); - assertTrue(i3.getPrevious().getPrevious().getPrevious().getPrevious() == i1); - assertNull(i3.getPrevious().getPrevious().getPrevious().getPrevious().getPrevious()); + // Order should be 1,4,5,2,3 - assertTrue(i1.isHeadNode()); - assertFalse(i1.isTailNode()); - assertFalse(i4.isHeadNode()); - assertFalse(i4.isTailNode()); - assertFalse(i5.isHeadNode()); - assertFalse(i5.isTailNode()); - assertFalse(i2.isHeadNode()); - assertFalse(i2.isTailNode()); - assertTrue(i3.isTailNode()); - assertFalse(i3.isHeadNode()); + assertTrue(i1.getNext() == i4); + assertTrue(i1.getNext().getNext() == i5); + assertTrue(i1.getNext().getNext().getNext() == i2); + assertTrue(i1.getNext().getNext().getNext().getNext() == i3); + assertNull(i1.getNext().getNext().getNext().getNext().getNext()); - } + assertTrue(i3.getPrevious() == i2); + assertTrue(i3.getPrevious().getPrevious() == i5); + assertTrue(i3.getPrevious().getPrevious().getPrevious() == i4); + assertTrue(i3.getPrevious().getPrevious().getPrevious().getPrevious() == i1); + assertNull(i3.getPrevious().getPrevious().getPrevious().getPrevious().getPrevious()); - public void testLinkBefore() { + assertTrue(i1.isHeadNode()); + assertFalse(i1.isTailNode()); + assertFalse(i4.isHeadNode()); + assertFalse(i4.isTailNode()); + assertFalse(i5.isHeadNode()); + assertFalse(i5.isTailNode()); + assertFalse(i2.isHeadNode()); + assertFalse(i2.isTailNode()); + assertTrue(i3.isTailNode()); + assertFalse(i3.isHeadNode()); - i3.linkBefore(i2.linkBefore(i1)); + } - assertTrue(i1.getNext() == i2); - assertTrue(i1.getNext().getNext() == i3); - assertNull(i1.getNext().getNext().getNext()); + public void testLinkBefore() { - assertTrue(i3.getPrevious() == i2); - assertTrue(i3.getPrevious().getPrevious() == i1); - assertNull(i3.getPrevious().getPrevious().getPrevious()); + i3.linkBefore(i2.linkBefore(i1)); - assertTrue(i1.isHeadNode()); - assertFalse(i1.isTailNode()); - assertFalse(i2.isHeadNode()); - assertFalse(i2.isTailNode()); - assertTrue(i3.isTailNode()); - assertFalse(i3.isHeadNode()); + assertTrue(i1.getNext() == i2); + assertTrue(i1.getNext().getNext() == i3); + assertNull(i1.getNext().getNext().getNext()); - i2.linkBefore(i5.linkBefore(i4)); + assertTrue(i3.getPrevious() == i2); + assertTrue(i3.getPrevious().getPrevious() == i1); + assertNull(i3.getPrevious().getPrevious().getPrevious()); - // Order should be 1,4,5,2,3 + assertTrue(i1.isHeadNode()); + assertFalse(i1.isTailNode()); + assertFalse(i2.isHeadNode()); + assertFalse(i2.isTailNode()); + assertTrue(i3.isTailNode()); + assertFalse(i3.isHeadNode()); - assertTrue(i1.getNext() == i4); - assertTrue(i1.getNext().getNext() == i5); - assertTrue(i1.getNext().getNext().getNext() == i2); - assertTrue(i1.getNext().getNext().getNext().getNext() == i3); - assertNull(i1.getNext().getNext().getNext().getNext().getNext()); + i2.linkBefore(i5.linkBefore(i4)); - assertTrue(i3.getPrevious() == i2); - assertTrue(i3.getPrevious().getPrevious() == i5); - assertTrue(i3.getPrevious().getPrevious().getPrevious() == i4); - assertTrue(i3.getPrevious().getPrevious().getPrevious().getPrevious() == i1); - assertNull(i3.getPrevious().getPrevious().getPrevious().getPrevious().getPrevious()); + // Order should be 1,4,5,2,3 - assertTrue(i1.isHeadNode()); - assertFalse(i1.isTailNode()); - assertFalse(i4.isHeadNode()); - assertFalse(i4.isTailNode()); - assertFalse(i5.isHeadNode()); - assertFalse(i5.isTailNode()); - assertFalse(i2.isHeadNode()); - assertFalse(i2.isTailNode()); - assertTrue(i3.isTailNode()); - assertFalse(i3.isHeadNode()); + assertTrue(i1.getNext() == i4); + assertTrue(i1.getNext().getNext() == i5); + assertTrue(i1.getNext().getNext().getNext() == i2); + assertTrue(i1.getNext().getNext().getNext().getNext() == i3); + assertNull(i1.getNext().getNext().getNext().getNext().getNext()); - } + assertTrue(i3.getPrevious() == i2); + assertTrue(i3.getPrevious().getPrevious() == i5); + assertTrue(i3.getPrevious().getPrevious().getPrevious() == i4); + assertTrue(i3.getPrevious().getPrevious().getPrevious().getPrevious() == i1); + assertNull(i3.getPrevious().getPrevious().getPrevious().getPrevious().getPrevious()); - public void testUnlink() { + assertTrue(i1.isHeadNode()); + assertFalse(i1.isTailNode()); + assertFalse(i4.isHeadNode()); + assertFalse(i4.isTailNode()); + assertFalse(i5.isHeadNode()); + assertFalse(i5.isTailNode()); + assertFalse(i2.isHeadNode()); + assertFalse(i2.isTailNode()); + assertTrue(i3.isTailNode()); + assertFalse(i3.isHeadNode()); - i1.linkAfter(i2.linkAfter(i3)); - i3.linkAfter(i4); - i1.linkBefore(i5); - i1.linkAfter(i6); + } - // Order should be 5,1,6,2,3,4 - i4.unlink(); - i5.unlink(); - i6.unlink(); + public void testUnlink() { - // Order should be 1,2,3 + i1.linkAfter(i2.linkAfter(i3)); + i3.linkAfter(i4); + i1.linkBefore(i5); + i1.linkAfter(i6); - assertTrue(i1.getNext() == i2); - assertTrue(i1.getNext().getNext() == i3); - assertNull(i1.getNext().getNext().getNext()); + // Order should be 5,1,6,2,3,4 + i4.unlink(); + i5.unlink(); + i6.unlink(); - assertTrue(i3.getPrevious() == i2); - assertTrue(i3.getPrevious().getPrevious() == i1); - assertNull(i3.getPrevious().getPrevious().getPrevious()); + // Order should be 1,2,3 - assertTrue(i1.isHeadNode()); - assertFalse(i1.isTailNode()); - assertFalse(i2.isHeadNode()); - assertFalse(i2.isTailNode()); - assertTrue(i3.isTailNode()); - assertFalse(i3.isHeadNode()); - } + assertTrue(i1.getNext() == i2); + assertTrue(i1.getNext().getNext() == i3); + assertNull(i1.getNext().getNext().getNext()); + + assertTrue(i3.getPrevious() == i2); + assertTrue(i3.getPrevious().getPrevious() == i1); + assertNull(i3.getPrevious().getPrevious().getPrevious()); + + assertTrue(i1.isHeadNode()); + assertFalse(i1.isTailNode()); + assertFalse(i2.isHeadNode()); + assertFalse(i2.isTailNode()); + assertTrue(i3.isTailNode()); + assertFalse(i3.isHeadNode()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/MessageIdList.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/MessageIdList.java index c644c67dd7..828449fe2e 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/MessageIdList.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/MessageIdList.java @@ -36,246 +36,240 @@ import org.slf4j.LoggerFactory; * chain these instances together with the {@link #setParent(MessageListener)} * method so that you can aggregate the total number of messages consumed across * a number of consumers. - * - * */ public class MessageIdList extends Assert implements MessageListener { - private static final Logger LOG = LoggerFactory.getLogger(MessageIdList.class); + private static final Logger LOG = LoggerFactory.getLogger(MessageIdList.class); - private final List messageIds = new ArrayList(); - private final Object semaphore; - private boolean verbose; - private MessageListener parent; - private long maximumDuration = 15000L; - private long processingDelay; + private final List messageIds = new ArrayList(); + private final Object semaphore; + private boolean verbose; + private MessageListener parent; + private long maximumDuration = 15000L; + private long processingDelay; - private CountDownLatch countDownLatch; + private CountDownLatch countDownLatch; - public MessageIdList() { - this(new Object()); - } + public MessageIdList() { + this(new Object()); + } - public MessageIdList(Object semaphore) { - this.semaphore = semaphore; - } + public MessageIdList(Object semaphore) { + this.semaphore = semaphore; + } - @Override - public boolean equals(Object that) { - if (that instanceof MessageIdList) { - MessageIdList thatList = (MessageIdList)that; - return getMessageIds().equals(thatList.getMessageIds()); - } - return false; - } + @Override + public boolean equals(Object that) { + if (that instanceof MessageIdList) { + MessageIdList thatList = (MessageIdList) that; + return getMessageIds().equals(thatList.getMessageIds()); + } + return false; + } - @Override - public int hashCode() { - synchronized (semaphore) { - return messageIds.hashCode() + 1; - } - } + @Override + public int hashCode() { + synchronized (semaphore) { + return messageIds.hashCode() + 1; + } + } - @Override - public String toString() { - synchronized (semaphore) { - return messageIds.toString(); - } - } + @Override + public String toString() { + synchronized (semaphore) { + return messageIds.toString(); + } + } - /** - * @return all the messages on the list so far, clearing the buffer - */ - public List flushMessages() { - synchronized (semaphore) { - List answer = new ArrayList(messageIds); - messageIds.clear(); - return answer; - } - } + /** + * @return all the messages on the list so far, clearing the buffer + */ + public List flushMessages() { + synchronized (semaphore) { + List answer = new ArrayList(messageIds); + messageIds.clear(); + return answer; + } + } - public synchronized List getMessageIds() { - synchronized (semaphore) { - return new ArrayList(messageIds); - } - } + public synchronized List getMessageIds() { + synchronized (semaphore) { + return new ArrayList(messageIds); + } + } - @Override - public void onMessage(Message message) { - String id = null; - try { - id = message.getJMSMessageID(); - synchronized (semaphore) { - messageIds.add(id); - semaphore.notifyAll(); - } - if (countDownLatch != null) { - countDownLatch.countDown(); - } - if (LOG.isDebugEnabled()) { - LOG.debug("Received message: " + message); - } - } catch (JMSException e) { - e.printStackTrace(); - } - if (parent != null) { - parent.onMessage(message); - } - if (processingDelay > 0) { + @Override + public void onMessage(Message message) { + String id = null; + try { + id = message.getJMSMessageID(); + synchronized (semaphore) { + messageIds.add(id); + semaphore.notifyAll(); + } + if (countDownLatch != null) { + countDownLatch.countDown(); + } + if (LOG.isDebugEnabled()) { + LOG.debug("Received message: " + message); + } + } + catch (JMSException e) { + e.printStackTrace(); + } + if (parent != null) { + parent.onMessage(message); + } + if (processingDelay > 0) { + try { + Thread.sleep(processingDelay); + } + catch (InterruptedException e) { + } + } + } + + public int getMessageCount() { + synchronized (semaphore) { + return messageIds.size(); + } + } + + public void waitForMessagesToArrive(int messageCount) { + LOG.info("Waiting for " + messageCount + " message(s) to arrive"); + + long start = System.currentTimeMillis(); + + synchronized (semaphore) { + for (int i = 0; i < messageCount; i++) { try { - Thread.sleep(processingDelay); - } catch (InterruptedException e) { + if (hasReceivedMessages(messageCount)) { + break; + } + long duration = System.currentTimeMillis() - start; + if (duration >= maximumDuration) { + break; + } + + semaphore.wait(maximumDuration - duration); } - } - } - - public int getMessageCount() { - synchronized (semaphore) { - return messageIds.size(); - } - } - - public void waitForMessagesToArrive(int messageCount) { - LOG.info("Waiting for " + messageCount + " message(s) to arrive"); - - long start = System.currentTimeMillis(); - - synchronized (semaphore) - { - for (int i = 0; i < messageCount; i++) - { - try - { - if (hasReceivedMessages(messageCount)) - { - break; - } - long duration = System.currentTimeMillis() - start; - if (duration >= maximumDuration) - { - break; - } - - semaphore.wait(maximumDuration - duration); - } - catch (InterruptedException e) - { - LOG.info("Caught: " + e); - } + catch (InterruptedException e) { + LOG.info("Caught: " + e); } - } - long end = System.currentTimeMillis() - start; + } + } + long end = System.currentTimeMillis() - start; - LOG.info("End of wait for " + end + " millis and received: " + getMessageCount() + " messages"); - } + LOG.info("End of wait for " + end + " millis and received: " + getMessageCount() + " messages"); + } - /** - * Performs a testing assertion that the correct number of messages have - * been received without waiting - * - * @param messageCount - */ - public void assertMessagesReceivedNoWait(int messageCount) { - assertEquals("expected number of messages when received", messageCount, getMessageCount()); - } + /** + * Performs a testing assertion that the correct number of messages have + * been received without waiting + * + * @param messageCount + */ + public void assertMessagesReceivedNoWait(int messageCount) { + assertEquals("expected number of messages when received", messageCount, getMessageCount()); + } - /** - * Performs a testing assertion that the correct number of messages have - * been received waiting for the messages to arrive up to a fixed amount of - * time. - * - * @param messageCount - */ - public void assertMessagesReceived(int messageCount) { - waitForMessagesToArrive(messageCount); + /** + * Performs a testing assertion that the correct number of messages have + * been received waiting for the messages to arrive up to a fixed amount of + * time. + * + * @param messageCount + */ + public void assertMessagesReceived(int messageCount) { + waitForMessagesToArrive(messageCount); - assertMessagesReceivedNoWait(messageCount); - } + assertMessagesReceivedNoWait(messageCount); + } - /** - * Asserts that there are at least the given number of messages received - * without waiting. - */ - public void assertAtLeastMessagesReceived(int messageCount) { - int actual = getMessageCount(); - assertTrue("at least: " + messageCount + " messages received. Actual: " + actual, actual >= messageCount); - } + /** + * Asserts that there are at least the given number of messages received + * without waiting. + */ + public void assertAtLeastMessagesReceived(int messageCount) { + int actual = getMessageCount(); + assertTrue("at least: " + messageCount + " messages received. Actual: " + actual, actual >= messageCount); + } - /** - * Asserts that there are at most the number of messages received without - * waiting - * - * @param messageCount - */ - public void assertAtMostMessagesReceived(int messageCount) { - int actual = getMessageCount(); - assertTrue("at most: " + messageCount + " messages received. Actual: " + actual, actual <= messageCount); - } + /** + * Asserts that there are at most the number of messages received without + * waiting + * + * @param messageCount + */ + public void assertAtMostMessagesReceived(int messageCount) { + int actual = getMessageCount(); + assertTrue("at most: " + messageCount + " messages received. Actual: " + actual, actual <= messageCount); + } - public boolean hasReceivedMessage() { - return getMessageCount() == 0; - } + public boolean hasReceivedMessage() { + return getMessageCount() == 0; + } - public boolean hasReceivedMessages(int messageCount) { - return getMessageCount() >= messageCount; - } + public boolean hasReceivedMessages(int messageCount) { + return getMessageCount() >= messageCount; + } - public boolean isVerbose() { - return verbose; - } + public boolean isVerbose() { + return verbose; + } - public void setVerbose(boolean verbose) { - this.verbose = verbose; - } + public void setVerbose(boolean verbose) { + this.verbose = verbose; + } - public MessageListener getParent() { - return parent; - } + public MessageListener getParent() { + return parent; + } - /** - * Allows a parent listener to be specified such as to aggregate messages - * consumed across consumers - */ - public void setParent(MessageListener parent) { - this.parent = parent; - } + /** + * Allows a parent listener to be specified such as to aggregate messages + * consumed across consumers + */ + public void setParent(MessageListener parent) { + this.parent = parent; + } - /** - * @return the maximumDuration - */ - public long getMaximumDuration() { - return this.maximumDuration; - } + /** + * @return the maximumDuration + */ + public long getMaximumDuration() { + return this.maximumDuration; + } - /** - * @param maximumDuration the maximumDuration to set - */ - public void setMaximumDuration(long maximumDuration) { - this.maximumDuration = maximumDuration; - } + /** + * @param maximumDuration the maximumDuration to set + */ + public void setMaximumDuration(long maximumDuration) { + this.maximumDuration = maximumDuration; + } - public void setCountDownLatch(CountDownLatch countDownLatch) { - this.countDownLatch = countDownLatch; - } + public void setCountDownLatch(CountDownLatch countDownLatch) { + this.countDownLatch = countDownLatch; + } - /** - * Gets the amount of time the message listener will spend sleeping to - * simulate a processing delay. - * - * @return - */ - public long getProcessingDelay() { - return processingDelay; - } + /** + * Gets the amount of time the message listener will spend sleeping to + * simulate a processing delay. + * + * @return + */ + public long getProcessingDelay() { + return processingDelay; + } - /** - * Sets the amount of time the message listener will spend sleeping to - * simulate a processing delay. - * - * @param processingDelay - */ - public void setProcessingDelay(long processingDelay) { - this.processingDelay = processingDelay; - } + /** + * Sets the amount of time the message listener will spend sleeping to + * simulate a processing delay. + * + * @param processingDelay + */ + public void setProcessingDelay(long processingDelay) { + this.processingDelay = processingDelay; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/ProducerThread.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/ProducerThread.java index c7cf90dbcf..8fe00baf08 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/ProducerThread.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/ProducerThread.java @@ -23,60 +23,63 @@ import javax.jms.*; public class ProducerThread extends Thread { - private static final Logger LOG = LoggerFactory.getLogger(ProducerThread.class); + private static final Logger LOG = LoggerFactory.getLogger(ProducerThread.class); - int messageCount = 1000; - Destination dest; - protected Session sess; - int sleep = 0; - int sentCount = 0; + int messageCount = 1000; + Destination dest; + protected Session sess; + int sleep = 0; + int sentCount = 0; - public ProducerThread(Session sess, Destination dest) { - this.dest = dest; - this.sess = sess; - } + public ProducerThread(Session sess, Destination dest) { + this.dest = dest; + this.sess = sess; + } - public void run() { - MessageProducer producer = null; - try { - producer = sess.createProducer(dest); - for (sentCount = 0; sentCount < messageCount; sentCount++) { - producer.send(createMessage(sentCount)); - LOG.info("Sent 'test message: " + sentCount + "'"); - if (sleep > 0) { - Thread.sleep(sleep); - } + public void run() { + MessageProducer producer = null; + try { + producer = sess.createProducer(dest); + for (sentCount = 0; sentCount < messageCount; sentCount++) { + producer.send(createMessage(sentCount)); + LOG.info("Sent 'test message: " + sentCount + "'"); + if (sleep > 0) { + Thread.sleep(sleep); } - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (producer != null) { - try { - producer.close(); - } catch (JMSException e) { - e.printStackTrace(); - } + } + } + catch (Exception e) { + e.printStackTrace(); + } + finally { + if (producer != null) { + try { + producer.close(); } - } - } + catch (JMSException e) { + e.printStackTrace(); + } + } + } + } - protected Message createMessage(int i) throws Exception { - return sess.createTextMessage("test message: " + i); - } + protected Message createMessage(int i) throws Exception { + return sess.createTextMessage("test message: " + i); + } - public void setMessageCount(int messageCount) { - this.messageCount = messageCount; - } + public void setMessageCount(int messageCount) { + this.messageCount = messageCount; + } - public void setSleep(int sleep) { - this.sleep = sleep; - } + public void setSleep(int sleep) { + this.sleep = sleep; + } - public int getMessageCount() { - return messageCount; - } + public int getMessageCount() { + return messageCount; + } - public int getSentCount() { - return sentCount; - } + public int getSentCount() { + return sentCount; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/ReflectionSupportTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/ReflectionSupportTest.java index 89759219f2..aa8da347e2 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/ReflectionSupportTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/ReflectionSupportTest.java @@ -30,86 +30,89 @@ import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTopic; public class ReflectionSupportTest extends TestCase { - - List favorites = new ArrayList(); - String favoritesString = "[queue://test, topic://test]"; - List nonFavorites = new ArrayList(); - String nonFavoritesString = "[topic://test1]"; - - public void setUp() { - favorites.add(new ActiveMQQueue("test")); - favorites.add(new ActiveMQTopic("test")); - nonFavorites.add(new ActiveMQTopic("test1")); - } - public void testSetProperties() throws URISyntaxException { - SimplePojo pojo = new SimplePojo(); - HashMap map = new HashMap(); - map.put("age", "27"); - map.put("name", "Hiram"); - map.put("enabled", "true"); - map.put("uri", "test://value"); - map.put("favorites", favoritesString); - map.put("nonFavorites", nonFavoritesString); - map.put("others", null); - map.put("systems", "windows,mac"); - - IntrospectionSupport.setProperties(pojo, map); - - assertEquals(27, pojo.getAge()); - assertEquals("Hiram", pojo.getName()); - assertEquals(true, pojo.isEnabled()); - assertEquals(new URI("test://value"), pojo.getUri()); - assertEquals(favorites, pojo.getFavorites()); - assertEquals(nonFavorites, pojo.getNonFavorites()); - assertNull(pojo.getOthers()); - assertEquals("windows", pojo.getSystems()[0]); - assertEquals("mac", pojo.getSystems()[1]); - } - - public void testGetProperties() { - SimplePojo pojo = new SimplePojo(); - pojo.setAge(31); - pojo.setName("Dejan"); - pojo.setEnabled(true); - pojo.setFavorites(favorites); - pojo.setNonFavorites(nonFavorites); - pojo.setOthers(null); - pojo.setSystems(new String[]{"windows", "mac"}); - - Properties props = new Properties(); - - IntrospectionSupport.getProperties(pojo, props, null); - - assertEquals("Dejan", props.get("name")); - assertEquals("31", props.get("age")); - assertEquals("true", props.get("enabled")); - assertEquals(favoritesString, props.get("favorites")); - assertEquals(nonFavoritesString, props.get("nonFavorites")); - assertNull(props.get("others")); - assertEquals("windows,mac", props.get("systems")); - } - - public void testSetBoolean() { - - TestWitBoolean target = new TestWitBoolean(); - assertTrue(!target.getKeepAlive()); + List favorites = new ArrayList(); + String favoritesString = "[queue://test, topic://test]"; + List nonFavorites = new ArrayList(); + String nonFavoritesString = "[topic://test1]"; - IntrospectionSupport.setProperty(target, "keepAlive", "TRUE"); - assertTrue(target.getKeepAlive()); - - IntrospectionSupport.setProperty(target, "keepAlive", "false"); - assertTrue(!target.getKeepAlive()); - } + public void setUp() { + favorites.add(new ActiveMQQueue("test")); + favorites.add(new ActiveMQTopic("test")); + nonFavorites.add(new ActiveMQTopic("test1")); + } - public static class TestWitBoolean { - private Boolean keepAlive = new Boolean(false); - public Boolean getKeepAlive() { - return keepAlive; - } - public void setKeepAlive(Boolean keepAlive) { - this.keepAlive = keepAlive; - } - } + public void testSetProperties() throws URISyntaxException { + SimplePojo pojo = new SimplePojo(); + HashMap map = new HashMap(); + map.put("age", "27"); + map.put("name", "Hiram"); + map.put("enabled", "true"); + map.put("uri", "test://value"); + map.put("favorites", favoritesString); + map.put("nonFavorites", nonFavoritesString); + map.put("others", null); + map.put("systems", "windows,mac"); + + IntrospectionSupport.setProperties(pojo, map); + + assertEquals(27, pojo.getAge()); + assertEquals("Hiram", pojo.getName()); + assertEquals(true, pojo.isEnabled()); + assertEquals(new URI("test://value"), pojo.getUri()); + assertEquals(favorites, pojo.getFavorites()); + assertEquals(nonFavorites, pojo.getNonFavorites()); + assertNull(pojo.getOthers()); + assertEquals("windows", pojo.getSystems()[0]); + assertEquals("mac", pojo.getSystems()[1]); + } + + public void testGetProperties() { + SimplePojo pojo = new SimplePojo(); + pojo.setAge(31); + pojo.setName("Dejan"); + pojo.setEnabled(true); + pojo.setFavorites(favorites); + pojo.setNonFavorites(nonFavorites); + pojo.setOthers(null); + pojo.setSystems(new String[]{"windows", "mac"}); + + Properties props = new Properties(); + + IntrospectionSupport.getProperties(pojo, props, null); + + assertEquals("Dejan", props.get("name")); + assertEquals("31", props.get("age")); + assertEquals("true", props.get("enabled")); + assertEquals(favoritesString, props.get("favorites")); + assertEquals(nonFavoritesString, props.get("nonFavorites")); + assertNull(props.get("others")); + assertEquals("windows,mac", props.get("systems")); + } + + public void testSetBoolean() { + + TestWitBoolean target = new TestWitBoolean(); + assertTrue(!target.getKeepAlive()); + + IntrospectionSupport.setProperty(target, "keepAlive", "TRUE"); + assertTrue(target.getKeepAlive()); + + IntrospectionSupport.setProperty(target, "keepAlive", "false"); + assertTrue(!target.getKeepAlive()); + } + + public static class TestWitBoolean { + + private Boolean keepAlive = new Boolean(false); + + public Boolean getKeepAlive() { + return keepAlive; + } + + public void setKeepAlive(Boolean keepAlive) { + this.keepAlive = keepAlive; + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/SimplePojo.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/SimplePojo.java index 841e2a9c56..b0ba089778 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/SimplePojo.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/SimplePojo.java @@ -24,61 +24,76 @@ import org.apache.activemq.command.ActiveMQDestination; public class SimplePojo { - String name; - int age; - boolean enabled; - URI uri; - List favorites = new ArrayList(); - List nonFavorites = new ArrayList(); - List others = new ArrayList(); - String[] systems; - - public int getAge() { - return age; - } - public void setAge(int age) { - this.age = age; - } - public boolean isEnabled() { - return enabled; - } - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public URI getUri() { - return uri; - } - public void setUri(URI uri) { - this.uri = uri; - } - public List getFavorites() { - return favorites; - } - public void setFavorites(List favorites) { - this.favorites = favorites; - } - public List getNonFavorites() { - return nonFavorites; - } - public void setNonFavorites(List nonFavorites) { - this.nonFavorites = nonFavorites; - } - public List getOthers() { - return others; - } - public void setOthers(List others) { - this.others = others; - } - public String[] getSystems() { - return systems; - } - public void setSystems(String[] systems) { - this.systems = systems; - } + String name; + int age; + boolean enabled; + URI uri; + List favorites = new ArrayList(); + List nonFavorites = new ArrayList(); + List others = new ArrayList(); + String[] systems; + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public URI getUri() { + return uri; + } + + public void setUri(URI uri) { + this.uri = uri; + } + + public List getFavorites() { + return favorites; + } + + public void setFavorites(List favorites) { + this.favorites = favorites; + } + + public List getNonFavorites() { + return nonFavorites; + } + + public void setNonFavorites(List nonFavorites) { + this.nonFavorites = nonFavorites; + } + + public List getOthers() { + return others; + } + + public void setOthers(List others) { + this.others = others; + } + + public String[] getSystems() { + return systems; + } + + public void setSystems(String[] systems) { + this.systems = systems; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/ConnectorXBeanConfigTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/ConnectorXBeanConfigTest.java index ad96459d73..caf29e2d10 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/ConnectorXBeanConfigTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/ConnectorXBeanConfigTest.java @@ -41,173 +41,177 @@ import org.slf4j.LoggerFactory; */ public class ConnectorXBeanConfigTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(ConnectorXBeanConfigTest.class); - protected BrokerService brokerService; + private static final Logger LOG = LoggerFactory.getLogger(ConnectorXBeanConfigTest.class); + protected BrokerService brokerService; - public void testConnectorConfiguredCorrectly() throws Exception { + public void testConnectorConfiguredCorrectly() throws Exception { - TransportConnector connector = brokerService.getTransportConnectors().get(0); + TransportConnector connector = brokerService.getTransportConnectors().get(0); - assertEquals(new URI("tcp://localhost:61636"), connector.getUri()); - assertTrue(connector.getTaskRunnerFactory() == brokerService.getTaskRunnerFactory()); + assertEquals(new URI("tcp://localhost:61636"), connector.getUri()); + assertTrue(connector.getTaskRunnerFactory() == brokerService.getTaskRunnerFactory()); - NetworkConnector netConnector = brokerService.getNetworkConnectors().get(0); - List excludedDestinations = netConnector.getExcludedDestinations(); - assertEquals(new ActiveMQQueue("exclude.test.foo"), excludedDestinations.get(0)); - assertEquals(new ActiveMQTopic("exclude.test.bar"), excludedDestinations.get(1)); + NetworkConnector netConnector = brokerService.getNetworkConnectors().get(0); + List excludedDestinations = netConnector.getExcludedDestinations(); + assertEquals(new ActiveMQQueue("exclude.test.foo"), excludedDestinations.get(0)); + assertEquals(new ActiveMQTopic("exclude.test.bar"), excludedDestinations.get(1)); - List dynamicallyIncludedDestinations = netConnector.getDynamicallyIncludedDestinations(); - assertEquals(new ActiveMQQueue("include.test.foo"), dynamicallyIncludedDestinations.get(0)); - assertEquals(new ActiveMQTopic("include.test.bar"), dynamicallyIncludedDestinations.get(1)); - } + List dynamicallyIncludedDestinations = netConnector.getDynamicallyIncludedDestinations(); + assertEquals(new ActiveMQQueue("include.test.foo"), dynamicallyIncludedDestinations.get(0)); + assertEquals(new ActiveMQTopic("include.test.bar"), dynamicallyIncludedDestinations.get(1)); + } - public void testBrokerRestartIsAllowed() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); + public void testBrokerRestartIsAllowed() throws Exception { + brokerService.stop(); + brokerService.waitUntilStopped(); - // redundant start is now ignored - brokerService.start(); - } + // redundant start is now ignored + brokerService.start(); + } - public void testForceBrokerRestart() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); + public void testForceBrokerRestart() throws Exception { + brokerService.stop(); + brokerService.waitUntilStopped(); - brokerService.start(true); // force restart - brokerService.waitUntilStarted(); + brokerService.start(true); // force restart + brokerService.waitUntilStarted(); - LOG.info("try and connect to restarted broker"); - //send and receive a message from a restarted broker - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61636"); - Connection conn = factory.createConnection(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); - Destination dest = new ActiveMQQueue("test"); - MessageConsumer consumer = sess.createConsumer(dest); - MessageProducer producer = sess.createProducer(dest); - producer.send(sess.createTextMessage("test")); - TextMessage msg = (TextMessage)consumer.receive(1000); - assertEquals("test", msg.getText()); - } + LOG.info("try and connect to restarted broker"); + //send and receive a message from a restarted broker + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61636"); + Connection conn = factory.createConnection(); + Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + conn.start(); + Destination dest = new ActiveMQQueue("test"); + MessageConsumer consumer = sess.createConsumer(dest); + MessageProducer producer = sess.createProducer(dest); + producer.send(sess.createTextMessage("test")); + TextMessage msg = (TextMessage) consumer.receive(1000); + assertEquals("test", msg.getText()); + } + public void testBrokerWontStop() throws Exception { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?async=false"); + factory.setDispatchAsync(false); + factory.setAlwaysSessionAsync(false); + Connection conn = factory.createConnection(); + final Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); + conn.start(); + final Destination dest = new ActiveMQQueue("TEST"); + final CountDownLatch stop = new CountDownLatch(1); + final CountDownLatch sendSecond = new CountDownLatch(1); + final CountDownLatch shutdown = new CountDownLatch(1); + final CountDownLatch test = new CountDownLatch(1); - public void testBrokerWontStop() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?async=false"); - factory.setDispatchAsync(false); - factory.setAlwaysSessionAsync(false); - Connection conn = factory.createConnection(); - final Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); - conn.start(); - final Destination dest = new ActiveMQQueue("TEST"); - final CountDownLatch stop = new CountDownLatch(1); - final CountDownLatch sendSecond = new CountDownLatch(1); - final CountDownLatch shutdown = new CountDownLatch(1); - final CountDownLatch test = new CountDownLatch(1); + ActiveMQConnectionFactory testFactory = new ActiveMQConnectionFactory("vm://localhost?async=false"); + Connection testConn = testFactory.createConnection(); + testConn.start(); + Destination testDestination = sess.createQueue("NEW"); + Session testSess = testConn.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer testProducer = testSess.createProducer(testDestination); - ActiveMQConnectionFactory testFactory = new ActiveMQConnectionFactory("vm://localhost?async=false"); - Connection testConn = testFactory.createConnection(); - testConn.start(); - Destination testDestination = sess.createQueue("NEW"); - Session testSess = testConn.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer testProducer = testSess.createProducer(testDestination); - - final Thread consumerThread = new Thread() { - @Override - public void run() { - try { - MessageProducer producer = sess.createProducer(dest); - producer.send(sess.createTextMessage("msg1")); - MessageConsumer consumer = sess.createConsumer(dest); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - try { - // send a message that will block - Thread.sleep(2000); - sendSecond.countDown(); - // try to stop the broker - Thread.sleep(5000); - stop.countDown(); - // run the test - Thread.sleep(5000); - test.countDown(); - shutdown.await(); - } catch (InterruptedException ie) { - } - } - }); - } catch (Exception e) { - e.printStackTrace(); - } + final Thread consumerThread = new Thread() { + @Override + public void run() { + try { + MessageProducer producer = sess.createProducer(dest); + producer.send(sess.createTextMessage("msg1")); + MessageConsumer consumer = sess.createConsumer(dest); + consumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + try { + // send a message that will block + Thread.sleep(2000); + sendSecond.countDown(); + // try to stop the broker + Thread.sleep(5000); + stop.countDown(); + // run the test + Thread.sleep(5000); + test.countDown(); + shutdown.await(); + } + catch (InterruptedException ie) { + } + } + }); } - }; - - consumerThread.start(); - - final Thread producerThread = new Thread() { - @Override - public void run() { - try { - sendSecond.await(); - MessageProducer producer = sess.createProducer(dest); - producer.send(sess.createTextMessage("msg2")); - } catch (Exception e) { - e.printStackTrace(); - } + catch (Exception e) { + e.printStackTrace(); } - }; + } + }; - producerThread.start(); + consumerThread.start(); - final Thread stopThread = new Thread() { - @Override - public void run() { - try { - stop.await(); - brokerService.stop(); - } catch (Exception e) { - e.printStackTrace(); - } + final Thread producerThread = new Thread() { + @Override + public void run() { + try { + sendSecond.await(); + MessageProducer producer = sess.createProducer(dest); + producer.send(sess.createTextMessage("msg2")); } - }; + catch (Exception e) { + e.printStackTrace(); + } + } + }; - stopThread.start(); + producerThread.start(); - test.await(); - try { - testSess.createConsumer(testDestination); - fail("Should have failed creating a consumer!"); - } catch (Exception e) { - e.printStackTrace(); - } + final Thread stopThread = new Thread() { + @Override + public void run() { + try { + stop.await(); + brokerService.stop(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + }; - try { - testProducer.send(testSess.createTextMessage("msg3")); - fail("Should have failed sending a message!"); - } catch (Exception e) { - e.printStackTrace(); - } + stopThread.start(); - shutdown.countDown(); + test.await(); + try { + testSess.createConsumer(testDestination); + fail("Should have failed creating a consumer!"); + } + catch (Exception e) { + e.printStackTrace(); + } + try { + testProducer.send(testSess.createTextMessage("msg3")); + fail("Should have failed sending a message!"); + } + catch (Exception e) { + e.printStackTrace(); + } - } + shutdown.countDown(); - @Override - protected void setUp() throws Exception { - brokerService = createBroker(); - brokerService.start(); - } + } - @Override - protected void tearDown() throws Exception { - if (brokerService != null) { - brokerService.stop(); - } - } + @Override + protected void setUp() throws Exception { + brokerService = createBroker(); + brokerService.start(); + } - protected BrokerService createBroker() throws Exception { - String uri = "org/apache/activemq/xbean/connector-test.xml"; - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } + @Override + protected void tearDown() throws Exception { + if (brokerService != null) { + brokerService.stop(); + } + } + + protected BrokerService createBroker() throws Exception { + String uri = "org/apache/activemq/xbean/connector-test.xml"; + return BrokerFactory.createBroker(new URI("xbean:" + uri)); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/JDBCPersistenceAdapterXBeanConfigTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/JDBCPersistenceAdapterXBeanConfigTest.java index 100f244993..886cc0422f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/JDBCPersistenceAdapterXBeanConfigTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/JDBCPersistenceAdapterXBeanConfigTest.java @@ -17,44 +17,46 @@ package org.apache.activemq.xbean; import java.net.URI; + import junit.framework.TestCase; + import org.apache.activemq.broker.BrokerFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.store.PersistenceAdapter; import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter; /** - * + * */ public class JDBCPersistenceAdapterXBeanConfigTest extends TestCase { - protected BrokerService brokerService; + protected BrokerService brokerService; - public void testConfiguredCorrectly() throws Exception { + public void testConfiguredCorrectly() throws Exception { - PersistenceAdapter persistenceAdapter = brokerService.getPersistenceAdapter(); - assertNotNull(persistenceAdapter); - assertTrue(persistenceAdapter instanceof JDBCPersistenceAdapter); + PersistenceAdapter persistenceAdapter = brokerService.getPersistenceAdapter(); + assertNotNull(persistenceAdapter); + assertTrue(persistenceAdapter instanceof JDBCPersistenceAdapter); - JDBCPersistenceAdapter jpa = (JDBCPersistenceAdapter)persistenceAdapter; - assertEquals("BROKER1.", jpa.getStatements().getTablePrefix()); + JDBCPersistenceAdapter jpa = (JDBCPersistenceAdapter) persistenceAdapter; + assertEquals("BROKER1.", jpa.getStatements().getTablePrefix()); - } + } - protected void setUp() throws Exception { - brokerService = createBroker(); - brokerService.start(); - } + protected void setUp() throws Exception { + brokerService = createBroker(); + brokerService.start(); + } - protected void tearDown() throws Exception { - if (brokerService != null) { - brokerService.stop(); - } - } + protected void tearDown() throws Exception { + if (brokerService != null) { + brokerService.stop(); + } + } - protected BrokerService createBroker() throws Exception { - String uri = "org/apache/activemq/xbean/jdbc-persistence-adapter-test.xml"; - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } + protected BrokerService createBroker() throws Exception { + String uri = "org/apache/activemq/xbean/jdbc-persistence-adapter-test.xml"; + return BrokerFactory.createBroker(new URI("xbean:" + uri)); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/JDBCPersistenceXBeanConfigTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/JDBCPersistenceXBeanConfigTest.java index 5a34932e12..460dc850d9 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/JDBCPersistenceXBeanConfigTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/JDBCPersistenceXBeanConfigTest.java @@ -26,37 +26,37 @@ import org.apache.activemq.store.PersistenceAdapter; import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter; /** - * + * */ public class JDBCPersistenceXBeanConfigTest extends TestCase { - protected BrokerService brokerService; + protected BrokerService brokerService; - public void testConfiguredCorrectly() throws Exception { + public void testConfiguredCorrectly() throws Exception { - PersistenceAdapter persistenceAdapter = brokerService.getPersistenceAdapter(); - assertNotNull(persistenceAdapter); - assertTrue(persistenceAdapter instanceof JDBCPersistenceAdapter); + PersistenceAdapter persistenceAdapter = brokerService.getPersistenceAdapter(); + assertNotNull(persistenceAdapter); + assertTrue(persistenceAdapter instanceof JDBCPersistenceAdapter); - JDBCPersistenceAdapter jpa = (JDBCPersistenceAdapter)persistenceAdapter; - assertEquals("BROKER1.", jpa.getStatements().getTablePrefix()); + JDBCPersistenceAdapter jpa = (JDBCPersistenceAdapter) persistenceAdapter; + assertEquals("BROKER1.", jpa.getStatements().getTablePrefix()); - } + } - protected void setUp() throws Exception { - brokerService = createBroker(); - brokerService.start(); - } + protected void setUp() throws Exception { + brokerService = createBroker(); + brokerService.start(); + } - protected void tearDown() throws Exception { - if (brokerService != null) { - brokerService.stop(); - } - } + protected void tearDown() throws Exception { + if (brokerService != null) { + brokerService.stop(); + } + } - protected BrokerService createBroker() throws Exception { - String uri = "org/apache/activemq/xbean/jdbc-persistence-test.xml"; - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } + protected BrokerService createBroker() throws Exception { + String uri = "org/apache/activemq/xbean/jdbc-persistence-test.xml"; + return BrokerFactory.createBroker(new URI("xbean:" + uri)); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/ManagementContextXBeanConfigTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/ManagementContextXBeanConfigTest.java index bd724a9841..734cd1c1bb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/ManagementContextXBeanConfigTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/ManagementContextXBeanConfigTest.java @@ -42,65 +42,65 @@ import org.slf4j.LoggerFactory; */ public class ManagementContextXBeanConfigTest extends TestCase { - protected BrokerService brokerService; - private static final transient Logger LOG = LoggerFactory.getLogger(ManagementContextXBeanConfigTest.class); + protected BrokerService brokerService; + private static final transient Logger LOG = LoggerFactory.getLogger(ManagementContextXBeanConfigTest.class); - public void testManagementContextConfiguredCorrectly() throws Exception { - assertEquals(2011, brokerService.getManagementContext().getConnectorPort()); - assertEquals("test.domain", brokerService.getManagementContext().getJmxDomainName()); - // Make sure the broker is registered in the right jmx domain. - Hashtable map = new Hashtable(); - map.put("type", "Broker"); - map.put("brokerName", JMXSupport.encodeObjectNamePart("localhost")); - ObjectName on = new ObjectName("test.domain", map); - Object value = brokerService.getManagementContext().getAttribute(on, "TotalEnqueueCount"); - assertNotNull(value); - } + public void testManagementContextConfiguredCorrectly() throws Exception { + assertEquals(2011, brokerService.getManagementContext().getConnectorPort()); + assertEquals("test.domain", brokerService.getManagementContext().getJmxDomainName()); + // Make sure the broker is registered in the right jmx domain. + Hashtable map = new Hashtable(); + map.put("type", "Broker"); + map.put("brokerName", JMXSupport.encodeObjectNamePart("localhost")); + ObjectName on = new ObjectName("test.domain", map); + Object value = brokerService.getManagementContext().getAttribute(on, "TotalEnqueueCount"); + assertNotNull(value); + } - public void testSuccessAuthentication() throws Exception { - JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:2011/jmxrmi"); - Map env = new HashMap(); - env.put(JMXConnector.CREDENTIALS, new String[]{"admin", "activemq"}); - JMXConnector connector = JMXConnectorFactory.connect(url, env); - assertAuthentication(connector); - } + public void testSuccessAuthentication() throws Exception { + JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:2011/jmxrmi"); + Map env = new HashMap(); + env.put(JMXConnector.CREDENTIALS, new String[]{"admin", "activemq"}); + JMXConnector connector = JMXConnectorFactory.connect(url, env); + assertAuthentication(connector); + } - public void testFailAuthentication() throws Exception { - JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:2011/jmxrmi"); - try { - JMXConnector connector = JMXConnectorFactory.connect(url, null); - assertAuthentication(connector); - } catch (SecurityException e) { - return; - } - fail("Should have thrown an exception"); - } + public void testFailAuthentication() throws Exception { + JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:2011/jmxrmi"); + try { + JMXConnector connector = JMXConnectorFactory.connect(url, null); + assertAuthentication(connector); + } + catch (SecurityException e) { + return; + } + fail("Should have thrown an exception"); + } - public void assertAuthentication(JMXConnector connector) throws Exception { - connector.connect(); - MBeanServerConnection connection = connector.getMBeanServerConnection(); - ObjectName name = new ObjectName("test.domain:type=Broker,brokerName=localhost"); - BrokerViewMBean mbean = MBeanServerInvocationHandler - .newProxyInstance(connection, name, BrokerViewMBean.class, true); - LOG.info("Broker " + mbean.getBrokerId() + " - " + mbean.getBrokerName()); - } + public void assertAuthentication(JMXConnector connector) throws Exception { + connector.connect(); + MBeanServerConnection connection = connector.getMBeanServerConnection(); + ObjectName name = new ObjectName("test.domain:type=Broker,brokerName=localhost"); + BrokerViewMBean mbean = MBeanServerInvocationHandler.newProxyInstance(connection, name, BrokerViewMBean.class, true); + LOG.info("Broker " + mbean.getBrokerId() + " - " + mbean.getBrokerName()); + } - @Override - protected void setUp() throws Exception { - brokerService = createBroker(); - brokerService.start(); - } + @Override + protected void setUp() throws Exception { + brokerService = createBroker(); + brokerService.start(); + } - @Override - protected void tearDown() throws Exception { - if (brokerService != null) { - brokerService.stop(); - } - } + @Override + protected void tearDown() throws Exception { + if (brokerService != null) { + brokerService.stop(); + } + } - protected BrokerService createBroker() throws Exception { - String uri = "org/apache/activemq/xbean/management-context-test.xml"; - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } + protected BrokerService createBroker() throws Exception { + String uri = "org/apache/activemq/xbean/management-context-test.xml"; + return BrokerFactory.createBroker(new URI("xbean:" + uri)); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithEmbeddedBrokerAndPersistenceTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithEmbeddedBrokerAndPersistenceTest.java index 5397dc223e..516dd16731 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithEmbeddedBrokerAndPersistenceTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithEmbeddedBrokerAndPersistenceTest.java @@ -18,12 +18,12 @@ package org.apache.activemq.xbean; /** * - * + * */ public class MultipleTestsWithEmbeddedBrokerAndPersistenceTest extends MultipleTestsWithEmbeddedBrokerTest { - protected boolean isPersistent() { - return true; - } + protected boolean isPersistent() { + return true; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithEmbeddedBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithEmbeddedBrokerTest.java index 64a2c41a5a..41eeb9e7f5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithEmbeddedBrokerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithEmbeddedBrokerTest.java @@ -26,32 +26,33 @@ import org.slf4j.LoggerFactory; * */ public class MultipleTestsWithEmbeddedBrokerTest extends EmbeddedBrokerTestSupport { - private static final Logger LOG = LoggerFactory.getLogger(MultipleTestsWithEmbeddedBrokerTest.class); - protected Connection connection; + private static final Logger LOG = LoggerFactory.getLogger(MultipleTestsWithEmbeddedBrokerTest.class); - public void test1() throws Exception { - } + protected Connection connection; - public void test2() throws Exception { - } + public void test1() throws Exception { + } - @Override - protected void setUp() throws Exception { - LOG.info("### starting up the test case: " + getName()); + public void test2() throws Exception { + } - super.setUp(); - connection = connectionFactory.createConnection(); - connection.start(); - LOG.info("### started up the test case: " + getName()); - } + @Override + protected void setUp() throws Exception { + LOG.info("### starting up the test case: " + getName()); - @Override - protected void tearDown() throws Exception { - connection.close(); + super.setUp(); + connection = connectionFactory.createConnection(); + connection.start(); + LOG.info("### started up the test case: " + getName()); + } - super.tearDown(); + @Override + protected void tearDown() throws Exception { + connection.close(); - LOG.info("### closed down the test case: " + getName()); - } + super.tearDown(); + + LOG.info("### closed down the test case: " + getName()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithSpringFactoryBeanTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithSpringFactoryBeanTest.java index 8017abd512..724a4c3f5f 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithSpringFactoryBeanTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithSpringFactoryBeanTest.java @@ -29,53 +29,51 @@ import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** - * * @author Neil Clayton - * */ public class MultipleTestsWithSpringFactoryBeanTest extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(MultipleTestsWithSpringFactoryBeanTest.class); - - protected AbstractApplicationContext context; - protected BrokerService service; - private Connection connection; - public void test1() throws Exception { - } - - public void test2() throws Exception { - } - - protected void setUp() throws Exception { - LOG.info("### starting up the test case: " + getName()); - - super.setUp(); - context = new ClassPathXmlApplicationContext("org/apache/activemq/xbean/spring2.xml"); - service = (BrokerService) context.getBean("broker"); - - // already started - service.start(); - - connection = createConnectionFactory().createConnection(); - connection.start(); - LOG.info("### started up the test case: " + getName()); - } + private static final Logger LOG = LoggerFactory.getLogger(MultipleTestsWithSpringFactoryBeanTest.class); - protected void tearDown() throws Exception { - connection.close(); - - // stopped as part of the context - service.stop(); - context.close(); - super.tearDown(); - - LOG.info("### closed down the test case: " + getName()); - } + protected AbstractApplicationContext context; + protected BrokerService service; + private Connection connection; - protected ConnectionFactory createConnectionFactory() { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(); - factory.setBrokerURL("vm://localhost"); - return factory; - } + public void test1() throws Exception { + } + + public void test2() throws Exception { + } + + protected void setUp() throws Exception { + LOG.info("### starting up the test case: " + getName()); + + super.setUp(); + context = new ClassPathXmlApplicationContext("org/apache/activemq/xbean/spring2.xml"); + service = (BrokerService) context.getBean("broker"); + + // already started + service.start(); + + connection = createConnectionFactory().createConnection(); + connection.start(); + LOG.info("### started up the test case: " + getName()); + } + + protected void tearDown() throws Exception { + connection.close(); + + // stopped as part of the context + service.stop(); + context.close(); + super.tearDown(); + + LOG.info("### closed down the test case: " + getName()); + } + + protected ConnectionFactory createConnectionFactory() { + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(); + factory.setBrokerURL("vm://localhost"); + return factory; + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithSpringXBeanFactoryBeanTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithSpringXBeanFactoryBeanTest.java index 252631488a..6ed4ce6c75 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithSpringXBeanFactoryBeanTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithSpringXBeanFactoryBeanTest.java @@ -20,25 +20,23 @@ import org.apache.activemq.broker.BrokerService; import org.springframework.context.support.ClassPathXmlApplicationContext; /** - * + * */ public class MultipleTestsWithSpringXBeanFactoryBeanTest extends MultipleTestsWithEmbeddedBrokerTest { - private ClassPathXmlApplicationContext context; + private ClassPathXmlApplicationContext context; - protected BrokerService createBroker() throws Exception { - context = new ClassPathXmlApplicationContext("org/apache/activemq/xbean/spring2.xml"); - return (BrokerService) context.getBean("broker"); - } + protected BrokerService createBroker() throws Exception { + context = new ClassPathXmlApplicationContext("org/apache/activemq/xbean/spring2.xml"); + return (BrokerService) context.getBean("broker"); + } - protected void tearDown() throws Exception { - super.tearDown(); - if (context != null) { - context.destroy(); - } - } - - + protected void tearDown() throws Exception { + super.tearDown(); + if (context != null) { + context.destroy(); + } + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithXBeanFactoryBeanTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithXBeanFactoryBeanTest.java index f6b15072c1..8236902ce5 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithXBeanFactoryBeanTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithXBeanFactoryBeanTest.java @@ -20,17 +20,16 @@ import org.apache.activemq.broker.BrokerService; import org.springframework.core.io.ClassPathResource; /** - * + * */ public class MultipleTestsWithXBeanFactoryBeanTest extends MultipleTestsWithEmbeddedBrokerTest { - protected BrokerService createBroker() throws Exception { - BrokerFactoryBean factory = new BrokerFactoryBean(); - factory.setConfig(new ClassPathResource("org/apache/activemq/xbean/activemq2.xml")); - factory.afterPropertiesSet(); - return factory.getBroker(); - } - + protected BrokerService createBroker() throws Exception { + BrokerFactoryBean factory = new BrokerFactoryBean(); + factory.setConfig(new ClassPathResource("org/apache/activemq/xbean/activemq2.xml")); + factory.afterPropertiesSet(); + return factory.getBroker(); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/XBeanConfigTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/XBeanConfigTest.java index c29a08cc2e..a43af8babb 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/XBeanConfigTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/XBeanConfigTest.java @@ -37,85 +37,84 @@ import org.slf4j.LoggerFactory; */ public class XBeanConfigTest extends TestCase { - private static final Logger LOG = LoggerFactory.getLogger(XBeanConfigTest.class); + private static final Logger LOG = LoggerFactory.getLogger(XBeanConfigTest.class); - protected BrokerService brokerService; - protected Broker broker; - protected ConnectionContext context; - protected ConnectionInfo info; + protected BrokerService brokerService; + protected Broker broker; + protected ConnectionContext context; + protected ConnectionInfo info; - public void testBrokerConfiguredCorrectly() throws Exception { + public void testBrokerConfiguredCorrectly() throws Exception { - // Validate the system properties are being evaluated in xbean. - assertEquals("testbroker", brokerService.getBrokerName()); + // Validate the system properties are being evaluated in xbean. + assertEquals("testbroker", brokerService.getBrokerName()); - Topic topic = (Topic)broker.addDestination(context, new ActiveMQTopic("FOO.BAR"),true); - DispatchPolicy dispatchPolicy = topic.getDispatchPolicy(); - assertTrue("dispatchPolicy should be RoundRobinDispatchPolicy: " + dispatchPolicy, dispatchPolicy instanceof RoundRobinDispatchPolicy); + Topic topic = (Topic) broker.addDestination(context, new ActiveMQTopic("FOO.BAR"), true); + DispatchPolicy dispatchPolicy = topic.getDispatchPolicy(); + assertTrue("dispatchPolicy should be RoundRobinDispatchPolicy: " + dispatchPolicy, dispatchPolicy instanceof RoundRobinDispatchPolicy); - SubscriptionRecoveryPolicy subscriptionRecoveryPolicy = topic.getSubscriptionRecoveryPolicy(); - subscriptionRecoveryPolicy = ((RetainedMessageSubscriptionRecoveryPolicy)subscriptionRecoveryPolicy).getWrapped(); + SubscriptionRecoveryPolicy subscriptionRecoveryPolicy = topic.getSubscriptionRecoveryPolicy(); + subscriptionRecoveryPolicy = ((RetainedMessageSubscriptionRecoveryPolicy) subscriptionRecoveryPolicy).getWrapped(); - assertTrue("subscriptionRecoveryPolicy should be LastImageSubscriptionRecoveryPolicy: " + subscriptionRecoveryPolicy, - subscriptionRecoveryPolicy instanceof LastImageSubscriptionRecoveryPolicy); + assertTrue("subscriptionRecoveryPolicy should be LastImageSubscriptionRecoveryPolicy: " + subscriptionRecoveryPolicy, subscriptionRecoveryPolicy instanceof LastImageSubscriptionRecoveryPolicy); - LOG.info("destination: " + topic); - LOG.info("dispatchPolicy: " + dispatchPolicy); - LOG.info("subscriptionRecoveryPolicy: " + subscriptionRecoveryPolicy); + LOG.info("destination: " + topic); + LOG.info("dispatchPolicy: " + dispatchPolicy); + LOG.info("subscriptionRecoveryPolicy: " + subscriptionRecoveryPolicy); - topic = (Topic)broker.addDestination(context, new ActiveMQTopic("ORDERS.BOOKS"),true); - dispatchPolicy = topic.getDispatchPolicy(); - assertTrue("dispatchPolicy should be StrictOrderDispatchPolicy: " + dispatchPolicy, dispatchPolicy instanceof StrictOrderDispatchPolicy); + topic = (Topic) broker.addDestination(context, new ActiveMQTopic("ORDERS.BOOKS"), true); + dispatchPolicy = topic.getDispatchPolicy(); + assertTrue("dispatchPolicy should be StrictOrderDispatchPolicy: " + dispatchPolicy, dispatchPolicy instanceof StrictOrderDispatchPolicy); - subscriptionRecoveryPolicy = topic.getSubscriptionRecoveryPolicy(); - subscriptionRecoveryPolicy = ((RetainedMessageSubscriptionRecoveryPolicy)subscriptionRecoveryPolicy).getWrapped(); - assertTrue("subscriptionRecoveryPolicy should be TimedSubscriptionRecoveryPolicy: " + subscriptionRecoveryPolicy, - subscriptionRecoveryPolicy instanceof TimedSubscriptionRecoveryPolicy); - TimedSubscriptionRecoveryPolicy timedSubscriptionPolicy = (TimedSubscriptionRecoveryPolicy)subscriptionRecoveryPolicy; - assertEquals("getRecoverDuration()", 60000, timedSubscriptionPolicy.getRecoverDuration()); + subscriptionRecoveryPolicy = topic.getSubscriptionRecoveryPolicy(); + subscriptionRecoveryPolicy = ((RetainedMessageSubscriptionRecoveryPolicy) subscriptionRecoveryPolicy).getWrapped(); + assertTrue("subscriptionRecoveryPolicy should be TimedSubscriptionRecoveryPolicy: " + subscriptionRecoveryPolicy, subscriptionRecoveryPolicy instanceof TimedSubscriptionRecoveryPolicy); + TimedSubscriptionRecoveryPolicy timedSubscriptionPolicy = (TimedSubscriptionRecoveryPolicy) subscriptionRecoveryPolicy; + assertEquals("getRecoverDuration()", 60000, timedSubscriptionPolicy.getRecoverDuration()); - LOG.info("destination: " + topic); - LOG.info("dispatchPolicy: " + dispatchPolicy); - LOG.info("subscriptionRecoveryPolicy: " + subscriptionRecoveryPolicy); - } + LOG.info("destination: " + topic); + LOG.info("dispatchPolicy: " + dispatchPolicy); + LOG.info("subscriptionRecoveryPolicy: " + subscriptionRecoveryPolicy); + } - @Override - protected void setUp() throws Exception { - System.setProperty("brokername", "testbroker"); - brokerService = createBroker(); - broker = brokerService.getBroker(); + @Override + protected void setUp() throws Exception { + System.setProperty("brokername", "testbroker"); + brokerService = createBroker(); + broker = brokerService.getBroker(); - // started automatically - // brokerService.start(); + // started automatically + // brokerService.start(); - context = new ConnectionContext(); - context.setBroker(broker); - info = new ConnectionInfo(); - info.setClientId("James"); - info.setUserName("James"); - info.setConnectionId(new ConnectionId("1234")); + context = new ConnectionContext(); + context.setBroker(broker); + info = new ConnectionInfo(); + info.setClientId("James"); + info.setUserName("James"); + info.setConnectionId(new ConnectionId("1234")); - try { - broker.addConnection(context, info); - } catch (Throwable e) { - e.printStackTrace(); - fail(e.getMessage()); - } + try { + broker.addConnection(context, info); + } + catch (Throwable e) { + e.printStackTrace(); + fail(e.getMessage()); + } - assertNotNull("No broker created!"); - } + assertNotNull("No broker created!"); + } - @Override - protected void tearDown() throws Exception { - if (brokerService != null) { - brokerService.stop(); - } - } + @Override + protected void tearDown() throws Exception { + if (brokerService != null) { + brokerService.stop(); + } + } - protected BrokerService createBroker() throws Exception { - String uri = "org/apache/activemq/xbean/activemq-policy.xml"; - LOG.info("Loading broker configuration from the classpath with URI: " + uri); - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } + protected BrokerService createBroker() throws Exception { + String uri = "org/apache/activemq/xbean/activemq-policy.xml"; + LOG.info("Loading broker configuration from the classpath with URI: " + uri); + return BrokerFactory.createBroker(new URI("xbean:" + uri)); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/XBeanStartFalseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/XBeanStartFalseTest.java index 13f50648b4..f36f72cf9a 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/XBeanStartFalseTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/XBeanStartFalseTest.java @@ -24,10 +24,10 @@ import org.apache.activemq.broker.BrokerFactory; import org.apache.activemq.broker.BrokerService; public class XBeanStartFalseTest extends TestCase { - - public void testStartFalse() throws Exception { - BrokerService broker = BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/xbean/activemq2.xml")); - assertFalse("Broker is started", broker.isStarted()); - } + + public void testStartFalse() throws Exception { + BrokerService broker = BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/xbean/activemq2.xml")); + assertFalse("Broker is started", broker.isStarted()); + } } diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/XBeanXmlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/XBeanXmlTest.java index 3a98114dab..f596d35b37 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/XBeanXmlTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/XBeanXmlTest.java @@ -20,7 +20,7 @@ import org.apache.activemq.broker.SpringTest; public class XBeanXmlTest extends SpringTest { - public void testSenderWithSpringXml() throws Exception { - assertSenderConfig("org/apache/activemq/xbean/spring.xml"); - } + public void testSenderWithSpringXml() throws Exception { + assertSenderConfig("org/apache/activemq/xbean/spring.xml"); + } } diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/ExtrasTestLogger.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/ExtrasTestLogger.java index 371488861d..abca67aaeb 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/ExtrasTestLogger.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/ExtrasTestLogger.java @@ -21,8 +21,8 @@ import org.jboss.logging.Logger; import org.jboss.logging.annotations.MessageLogger; @MessageLogger(projectCode = "AMQTEST") -public interface ExtrasTestLogger extends BasicLogger -{ +public interface ExtrasTestLogger extends BasicLogger { + /** * The integration test logger. */ diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ActiveMQMessageHandlerTest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ActiveMQMessageHandlerTest.java index db867c4034..2a48be49b6 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ActiveMQMessageHandlerTest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ActiveMQMessageHandlerTest.java @@ -51,38 +51,26 @@ import org.junit.Test; import org.junit.runner.RunWith; @RunWith(BMUnitRunner.class) -public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase -{ +public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase { - protected boolean usePersistence() - { + protected boolean usePersistence() { return true; } - @Override - public boolean useSecurity() - { + public boolean useSecurity() { return false; } @Test - @BMRules - ( - rules = - { - @BMRule - ( - name = "interrupt", - targetClass = "org.apache.activemq.artemis.core.protocol.core.impl.ActiveMQSessionContext", - targetMethod = "xaEnd", - targetLocation = "ENTRY", - action = "org.apache.activemq.artemis.tests.extras.byteman.ActiveMQMessageHandlerTest.interrupt();" - ) - } - ) - public void testSimpleMessageReceivedOnQueue() throws Exception - { + @BMRules( + rules = {@BMRule( + name = "interrupt", + targetClass = "org.apache.activemq.artemis.core.protocol.core.impl.ActiveMQSessionContext", + targetMethod = "xaEnd", + targetLocation = "ENTRY", + action = "org.apache.activemq.artemis.tests.extras.byteman.ActiveMQMessageHandlerTest.interrupt();")}) + public void testSimpleMessageReceivedOnQueue() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); resourceAdapter = qResourceAdapter; @@ -144,22 +132,14 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase } @Test - @BMRules - ( - rules = - { - @BMRule - ( - name = "interrupt", - targetClass = "org.apache.activemq.artemis.core.protocol.core.impl.ActiveMQSessionContext", - targetMethod = "xaEnd", - targetLocation = "ENTRY", - action = "org.apache.activemq.artemis.tests.extras.byteman.ActiveMQMessageHandlerTest.interrupt();" - ) - } - ) - public void testSimpleMessageReceivedOnQueueTwoPhase() throws Exception - { + @BMRules( + rules = {@BMRule( + name = "interrupt", + targetClass = "org.apache.activemq.artemis.core.protocol.core.impl.ActiveMQSessionContext", + targetMethod = "xaEnd", + targetLocation = "ENTRY", + action = "org.apache.activemq.artemis.tests.extras.byteman.ActiveMQMessageHandlerTest.interrupt();")}) + public void testSimpleMessageReceivedOnQueueTwoPhase() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); resourceAdapter = qResourceAdapter; @@ -208,7 +188,6 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase Binding binding = server.getPostOffice().getBinding(SimpleString.toSimpleString(MDBQUEUEPREFIXED)); assertEquals(1, getMessageCount(((Queue) binding.getBindable()))); - server.stop(); server.start(); @@ -223,11 +202,10 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase static volatile ActiveMQResourceAdapter resourceAdapter; static boolean resourceAdapterStopped = false; - public static void interrupt() throws InterruptedException - { + + public static void interrupt() throws InterruptedException { //Thread.currentThread().interrupt(); - if (!resourceAdapterStopped) - { + if (!resourceAdapterStopped) { resourceAdapter.stop(); resourceAdapterStopped = true; throw new InterruptedException("foo"); @@ -237,75 +215,61 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase Transaction currentTX; - public class XADummyEndpoint extends DummyMessageEndpoint - { + public class XADummyEndpoint extends DummyMessageEndpoint { + final boolean twoPhase; ClientSession session; int afterDeliveryCounts = 0; - public XADummyEndpoint(CountDownLatch latch, boolean twoPhase) throws SystemException - { + public XADummyEndpoint(CountDownLatch latch, boolean twoPhase) throws SystemException { super(latch); this.twoPhase = twoPhase; - try - { + try { session = locator.createSessionFactory().createSession(true, false, false); } - catch (Throwable e) - { + catch (Throwable e) { throw new RuntimeException(e); } } @Override - public void beforeDelivery(Method method) throws NoSuchMethodException, ResourceException - { + public void beforeDelivery(Method method) throws NoSuchMethodException, ResourceException { super.beforeDelivery(method); - try - { + try { DummyTMLocator.tm.begin(); currentTX = DummyTMLocator.tm.getTransaction(); currentTX.enlistResource(xaResource); - if (twoPhase) - { + if (twoPhase) { currentTX.enlistResource(new DummyXAResource()); } } - catch (Throwable e) - { + catch (Throwable e) { throw new RuntimeException(e.getMessage(), e); } } - public void onMessage(Message message) - { + public void onMessage(Message message) { super.onMessage(message); -// try -// { -// lastMessage = (ActiveMQMessage) message; -// currentTX.enlistResource(session); -// ClientProducer prod = session.createProducer() -// } -// catch (Exception e) -// { -// e.printStackTrace(); -// } - + // try + // { + // lastMessage = (ActiveMQMessage) message; + // currentTX.enlistResource(session); + // ClientProducer prod = session.createProducer() + // } + // catch (Exception e) + // { + // e.printStackTrace(); + // } } - - @Override - public void afterDelivery() throws ResourceException - { + public void afterDelivery() throws ResourceException { afterDeliveryCounts++; - try - { + try { currentTX.commit(); } - catch (Throwable e) - { + catch (Throwable e) { //its unsure as to whether the EJB/JCA layer will handle this or throw it to us, // either way we don't do anything else so its fine just to throw. // NB this will only happen with 2 phase commit @@ -316,108 +280,93 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase } @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { resourceAdapter = null; resourceAdapterStopped = false; super.setUp(); DummyTMLocator.startTM(); } - @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { DummyTMLocator.stopTM(); super.tearDown(); } - public static class DummyTMLocator - { + public static class DummyTMLocator { + public static TransactionManagerImple tm; - public static void stopTM() - { - try - { + + public static void stopTM() { + try { TransactionReaper.terminate(true); TxControl.disable(true); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } tm = null; } - public static void startTM() - { + + public static void startTM() { tm = new TransactionManagerImple(); TxControl.enable(); } - public TransactionManager getTM() - { + + public TransactionManager getTM() { return tm; } } - static class DummyXAResource implements XAResource - { + static class DummyXAResource implements XAResource { + @Override - public void commit(Xid xid, boolean b) throws XAException - { + public void commit(Xid xid, boolean b) throws XAException { } @Override - public void end(Xid xid, int i) throws XAException - { + public void end(Xid xid, int i) throws XAException { } @Override - public void forget(Xid xid) throws XAException - { + public void forget(Xid xid) throws XAException { } @Override - public int getTransactionTimeout() throws XAException - { + public int getTransactionTimeout() throws XAException { return 0; } @Override - public boolean isSameRM(XAResource xaResource) throws XAException - { + public boolean isSameRM(XAResource xaResource) throws XAException { return false; } @Override - public int prepare(Xid xid) throws XAException - { + public int prepare(Xid xid) throws XAException { return 0; } @Override - public Xid[] recover(int i) throws XAException - { + public Xid[] recover(int i) throws XAException { return new Xid[0]; } @Override - public void rollback(Xid xid) throws XAException - { + public void rollback(Xid xid) throws XAException { } @Override - public boolean setTransactionTimeout(int i) throws XAException - { + public boolean setTransactionTimeout(int i) throws XAException { return false; } @Override - public void start(Xid xid, int i) throws XAException - { + public void start(Xid xid, int i) throws XAException { } } diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/BMFailoverTest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/BMFailoverTest.java index 53f2c13541..333da9cf22 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/BMFailoverTest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/BMFailoverTest.java @@ -51,8 +51,8 @@ import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; @RunWith(BMUnitRunner.class) -public class BMFailoverTest extends FailoverTestBase -{ +public class BMFailoverTest extends FailoverTestBase { + private ServerLocator locator; private ClientSessionFactoryInternal sf; private ClientSessionFactoryInternal sf2; @@ -60,56 +60,43 @@ public class BMFailoverTest extends FailoverTestBase @Before @Override - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); stopped = false; locator = getServerLocator(); } private static boolean stopped = false; - public static void stopAndThrow() throws ActiveMQUnBlockedException - { - if (!stopped) - { - try - { + + public static void stopAndThrow() throws ActiveMQUnBlockedException { + if (!stopped) { + try { serverToStop.getServer().stop(true); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } - try - { + try { Thread.sleep(2000); } - catch (InterruptedException e) - { + catch (InterruptedException e) { e.printStackTrace(); } stopped = true; throw ActiveMQClientMessageBundle.BUNDLE.unblockingACall(null); } } + @Test - @BMRules - ( - rules = - { - @BMRule - ( - name = "trace ActiveMQSessionContext xaEnd", - targetClass = "org.apache.activemq.artemis.core.protocol.core.impl.ActiveMQSessionContext", - targetMethod = "xaEnd", - targetLocation = "AT EXIT", - action = "org.apache.activemq.artemis.tests.extras.byteman.BMFailoverTest.stopAndThrow()" - ) - } - ) + @BMRules( + rules = {@BMRule( + name = "trace ActiveMQSessionContext xaEnd", + targetClass = "org.apache.activemq.artemis.core.protocol.core.impl.ActiveMQSessionContext", + targetMethod = "xaEnd", + targetLocation = "AT EXIT", + action = "org.apache.activemq.artemis.tests.extras.byteman.BMFailoverTest.stopAndThrow()")}) //https://bugzilla.redhat.com/show_bug.cgi?id=1152410 - public void testFailOnEndAndRetry() throws Exception - { + public void testFailOnEndAndRetry() throws Exception { serverToStop = liveServer; createSessionFactory(); @@ -120,8 +107,7 @@ public class BMFailoverTest extends FailoverTestBase ClientProducer producer = session.createProducer(FailoverTestBase.ADDRESS); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { producer.send(createMessage(session, i, true)); } @@ -132,8 +118,7 @@ public class BMFailoverTest extends FailoverTestBase session.start(xid, XAResource.TMNOFLAGS); session.start(); // Receive MSGs but don't ack! - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage message = consumer.receive(1000); Assert.assertNotNull(message); @@ -142,35 +127,28 @@ public class BMFailoverTest extends FailoverTestBase Assert.assertEquals(i, message.getIntProperty("counter").intValue()); } - try - { + try { //top level prepare session.end(xid, XAResource.TMSUCCESS); } - catch (XAException e) - { - try - { + catch (XAException e) { + try { //top level abort session.end(xid, XAResource.TMFAIL); } - catch (XAException e1) - { - try - { + catch (XAException e1) { + try { //rollback session.rollback(xid); } - catch (XAException e2) - { + catch (XAException e2) { } } } xid = RandomUtil.randomXid(); session.start(xid, XAResource.TMNOFLAGS); - for (int i = 0; i < 50; i++) - { + for (int i = 0; i < 50; i++) { ClientMessage message = consumer.receive(1000); Assert.assertNotNull(message); @@ -184,25 +162,16 @@ public class BMFailoverTest extends FailoverTestBase } @Test - @BMRules - ( - rules = - { - @BMRule - ( - name = "trace clientsessionimpl commit", - targetClass = "org.apache.activemq.artemis.core.client.impl.ClientSessionImpl", - targetMethod = "start(javax.transaction.xa.Xid, int)", - targetLocation = "AT EXIT", - action = "org.apache.activemq.artemis.tests.extras.byteman.BMFailoverTest.serverToStop.getServer().stop(true)" - ) - } - ) - public void testFailoverOnCommit2() throws Exception - { + @BMRules( + rules = {@BMRule( + name = "trace clientsessionimpl commit", + targetClass = "org.apache.activemq.artemis.core.client.impl.ClientSessionImpl", + targetMethod = "start(javax.transaction.xa.Xid, int)", + targetLocation = "AT EXIT", + action = "org.apache.activemq.artemis.tests.extras.byteman.BMFailoverTest.serverToStop.getServer().stop(true)")}) + public void testFailoverOnCommit2() throws Exception { serverToStop = liveServer; - locator = getServerLocator() - .setFailoverOnInitialConnection(true); + locator = getServerLocator().setFailoverOnInitialConnection(true); SimpleString inQueue = new SimpleString("inQueue"); SimpleString outQueue = new SimpleString("outQueue"); createSessionFactory(); @@ -210,8 +179,7 @@ public class BMFailoverTest extends FailoverTestBase // closeable will take care of closing it try (ClientSession session = sf.createSession(false, true, true); - ClientProducer sendInitialProducer = session.createProducer();) - { + ClientProducer sendInitialProducer = session.createProducer();) { session.createQueue(inQueue, inQueue, null, true); session.createQueue(outQueue, outQueue, null, true); sendInitialProducer.send(inQueue, createMessage(session, 0, true)); @@ -238,13 +206,11 @@ public class BMFailoverTest extends FailoverTestBase //the mdb would ack the message before calling onMessage() m.acknowledge(); - try - { + try { //this may fail but thats ok, it depends on the race and when failover actually happens xaSessionRec.end(xidRec, XAResource.TMSUCCESS); } - catch (XAException ignore) - { + catch (XAException ignore) { } //we always reset the client on the RA @@ -252,8 +218,7 @@ public class BMFailoverTest extends FailoverTestBase // closeable will take care of closing it try (ClientSession session = sf.createSession(false, true, true); - ClientProducer sendInitialProducer = session.createProducer();) - { + ClientProducer sendInitialProducer = session.createProducer();) { sendInitialProducer.send(inQueue, createMessage(session, 0, true)); } @@ -278,47 +243,34 @@ public class BMFailoverTest extends FailoverTestBase xaSessionRec.getXAResource().prepare(xidRec); xaSessionRec.getXAResource().commit(xidRec, false); - //let's close the consumer so anything pending is handled consumer.close(); assertEquals(1, getMessageCount(inQ)); } - @Test - @BMRules - ( - rules = - { - @BMRule - ( - name = "trace clientsessionimpl commit", - targetClass = "org.apache.activemq.artemis.core.client.impl.ClientSessionImpl", - targetMethod = "commit", - targetLocation = "ENTRY", - action = "org.apache.activemq.artemis.tests.extras.byteman.BMFailoverTest.serverToStop.getServer().stop(true)" - ) - } - ) - public void testFailoverOnCommit() throws Exception - { + @BMRules( + rules = {@BMRule( + name = "trace clientsessionimpl commit", + targetClass = "org.apache.activemq.artemis.core.client.impl.ClientSessionImpl", + targetMethod = "commit", + targetLocation = "ENTRY", + action = "org.apache.activemq.artemis.tests.extras.byteman.BMFailoverTest.serverToStop.getServer().stop(true)")}) + public void testFailoverOnCommit() throws Exception { serverToStop = liveServer; - locator = getServerLocator() - .setFailoverOnInitialConnection(true); + locator = getServerLocator().setFailoverOnInitialConnection(true); createSessionFactory(); ClientSession session = createSessionAndQueue(); ClientProducer producer = addClientProducer(session.createProducer(FailoverTestBase.ADDRESS)); sendMessages(session, producer, 10); - try - { + try { session.commit(); fail("should have thrown an exception"); } - catch (ActiveMQTransactionOutcomeUnknownException e) - { + catch (ActiveMQTransactionOutcomeUnknownException e) { //pass } sendMessages(session, producer, 10); @@ -328,25 +280,16 @@ public class BMFailoverTest extends FailoverTestBase } @Test - @BMRules - ( - rules = - { - @BMRule - ( - name = "trace clientsessionimpl commit", - targetClass = "org.apache.activemq.artemis.core.client.impl.ClientSessionImpl", - targetMethod = "commit", - targetLocation = "ENTRY", - action = "org.apache.activemq.artemis.tests.extras.byteman.BMFailoverTest.serverToStop.getServer().stop(true)" - ) - } - ) - public void testFailoverOnReceiveCommit() throws Exception - { + @BMRules( + rules = {@BMRule( + name = "trace clientsessionimpl commit", + targetClass = "org.apache.activemq.artemis.core.client.impl.ClientSessionImpl", + targetMethod = "commit", + targetLocation = "ENTRY", + action = "org.apache.activemq.artemis.tests.extras.byteman.BMFailoverTest.serverToStop.getServer().stop(true)")}) + public void testFailoverOnReceiveCommit() throws Exception { serverToStop = liveServer; - locator = getServerLocator() - .setFailoverOnInitialConnection(true); + locator = getServerLocator().setFailoverOnInitialConnection(true); createSessionFactory(); ClientSession session = createSessionAndQueue(); @@ -358,23 +301,19 @@ public class BMFailoverTest extends FailoverTestBase ClientConsumer consumer = session.createConsumer(FailoverTestBase.ADDRESS); session.start(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage m = consumer.receive(500); assertNotNull(m); m.acknowledge(); } - try - { + try { session.commit(); fail("should have thrown an exception"); } - catch (ActiveMQTransactionOutcomeUnknownException e) - { + catch (ActiveMQTransactionOutcomeUnknownException e) { //pass } - catch (ActiveMQTransactionRolledBackException e1) - { + catch (ActiveMQTransactionRolledBackException e1) { //pass } Queue bindable = (Queue) backupServer.getServer().getPostOffice().getBinding(FailoverTestBase.ADDRESS).getBindable(); @@ -383,57 +322,49 @@ public class BMFailoverTest extends FailoverTestBase } @Override - protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live) - { + protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live) { return getNettyAcceptorTransportConfiguration(live); } @Override - protected TransportConfiguration getConnectorTransportConfiguration(final boolean live) - { + protected TransportConfiguration getConnectorTransportConfiguration(final boolean live) { return getNettyConnectorTransportConfiguration(live); } - private ClientSession createSessionAndQueue() throws Exception - { + private ClientSession createSessionAndQueue() throws Exception { ClientSession session = createSession(sf, false, false); session.createQueue(FailoverTestBase.ADDRESS, FailoverTestBase.ADDRESS, null, true); return session; } - private ClientSession createXASessionAndQueue() throws Exception - { + private ClientSession createXASessionAndQueue() throws Exception { ClientSession session = addClientSession(sf.createSession(true, true, true)); session.createQueue(FailoverTestBase.ADDRESS, FailoverTestBase.ADDRESS, null, true); return session; } - protected ClientSession - createSession(ClientSessionFactory sf1, boolean autoCommitSends, boolean autoCommitAcks) throws Exception - { + protected ClientSession createSession(ClientSessionFactory sf1, + boolean autoCommitSends, + boolean autoCommitAcks) throws Exception { return addClientSession(sf1.createSession(autoCommitSends, autoCommitAcks)); } - protected ClientSession - createSession(ClientSessionFactory sf1, boolean xa, boolean autoCommitSends, boolean autoCommitAcks) throws Exception - { + protected ClientSession createSession(ClientSessionFactory sf1, + boolean xa, + boolean autoCommitSends, + boolean autoCommitAcks) throws Exception { return addClientSession(sf1.createSession(xa, autoCommitSends, autoCommitAcks)); } - - private void createSessionFactory() throws Exception - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setReconnectAttempts(-1); + private void createSessionFactory() throws Exception { + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setReconnectAttempts(-1); sf = createSessionFactoryAndWaitForTopology(locator, 2); } - private void createSessionFactory2() throws Exception - { + private void createSessionFactory2() throws Exception { sf2 = createSessionFactoryAndWaitForTopology(locator, 2); } } diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/BridgeServerLocatorConfigurationTest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/BridgeServerLocatorConfigurationTest.java index 6660de042b..8f835dea8a 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/BridgeServerLocatorConfigurationTest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/BridgeServerLocatorConfigurationTest.java @@ -35,21 +35,17 @@ import org.junit.Test; import org.junit.runner.RunWith; @RunWith(BMUnitRunner.class) -public class BridgeServerLocatorConfigurationTest extends ActiveMQTestBase -{ +public class BridgeServerLocatorConfigurationTest extends ActiveMQTestBase { private static final long BRIDGE_TTL = 1234L; private static final String BRIDGE_NAME = "bridge1"; - protected boolean isNetty() - { + protected boolean isNetty() { return false; } - private String getConnector() - { - if (isNetty()) - { + private String getConnector() { + if (isNetty()) { return NETTY_CONNECTOR_FACTORY; } return INVM_CONNECTOR_FACTORY; @@ -57,9 +53,9 @@ public class BridgeServerLocatorConfigurationTest extends ActiveMQTestBase @Test @BMRule(name = "check connection ttl", - targetClass = "org.apache.activemq.artemis.tests.extras.byteman.BridgeServerLocatorConfigurationTest", - targetMethod = "getBridgeTTL(ActiveMQServer, String)", targetLocation = "EXIT", - action = "$! = $0.getConfiguredBridge($1).serverLocator.getConnectionTTL();") + targetClass = "org.apache.activemq.artemis.tests.extras.byteman.BridgeServerLocatorConfigurationTest", + targetMethod = "getBridgeTTL(ActiveMQServer, String)", targetLocation = "EXIT", + action = "$! = $0.getConfiguredBridge($1).serverLocator.getConnectionTTL();") /** * Checks the connection ttl by using byteman to override the methods on this class to return the value of private variables in the Bridge. * @throws Exception @@ -67,25 +63,20 @@ public class BridgeServerLocatorConfigurationTest extends ActiveMQTestBase * The byteman rule on this test overwrites the {@link #getBridgeTTL} method to retrieve the bridge called {@link @BRIDGE_NAME}. * It the overrides the return value to be the value of the connection ttl. Note that the unused String parameter is required to * ensure that byteman populates the $1 variable, otherwise it will not bind correctly. - */ - public void testConnectionTTLOnBridge() throws Exception - { + */ public void testConnectionTTLOnBridge() throws Exception { Map server0Params = new HashMap(); ActiveMQServer serverWithBridge = createClusteredServerWithParams(isNetty(), 0, true, server0Params); Map server1Params = new HashMap(); - if (isNetty()) - { + if (isNetty()) { server1Params.put("port", org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.DEFAULT_PORT + 1); } - else - { + else { server1Params.put(TransportConstants.SERVER_ID_PROP_NAME, 1); } ActiveMQServer server1 = createClusteredServerWithParams(isNetty(), 1, true, server1Params); ServerLocator locator = null; - try - { + try { final String testAddress = "testAddress"; final String queueName0 = "queue0"; final String forwardAddress = "forwardAddress"; @@ -100,31 +91,18 @@ public class BridgeServerLocatorConfigurationTest extends ActiveMQTestBase ArrayList staticConnectors = new ArrayList(); staticConnectors.add(server1tc.getName()); - BridgeConfiguration bridgeConfiguration = new BridgeConfiguration() - .setName(BRIDGE_NAME) - .setQueueName(queueName0) - .setForwardingAddress(forwardAddress) - .setConnectionTTL(BRIDGE_TTL) - .setRetryInterval(1000) - .setReconnectAttempts(0) - .setReconnectAttemptsOnSameNode(0) - .setConfirmationWindowSize(1024) - .setStaticConnectors(staticConnectors); + BridgeConfiguration bridgeConfiguration = new BridgeConfiguration().setName(BRIDGE_NAME).setQueueName(queueName0).setForwardingAddress(forwardAddress).setConnectionTTL(BRIDGE_TTL).setRetryInterval(1000).setReconnectAttempts(0).setReconnectAttemptsOnSameNode(0).setConfirmationWindowSize(1024).setStaticConnectors(staticConnectors); List bridgeConfigs = new ArrayList(); bridgeConfigs.add(bridgeConfiguration); serverWithBridge.getConfiguration().setBridgeConfigurations(bridgeConfigs); - CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName0); + CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName0); List queueConfigs0 = new ArrayList(); queueConfigs0.add(queueConfig0); serverWithBridge.getConfiguration().setQueueConfigurations(queueConfigs0); - CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration() - .setAddress(forwardAddress) - .setName(queueName1); + CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration().setAddress(forwardAddress).setName(queueName1); List queueConfigs1 = new ArrayList(); queueConfigs1.add(queueConfig1); server1.getConfiguration().setQueueConfigurations(queueConfigs1); @@ -139,10 +117,8 @@ public class BridgeServerLocatorConfigurationTest extends ActiveMQTestBase assertEquals(BRIDGE_TTL, bridgeTTL); } - finally - { - if (locator != null) - { + finally { + if (locator != null) { locator.close(); } @@ -155,27 +131,26 @@ public class BridgeServerLocatorConfigurationTest extends ActiveMQTestBase /** * Method for byteman to wrap around and do its magic with to return the ttl from private members * rather than -1 + * * @param bridgeServer * @param bridgeName * @return */ - private long getBridgeTTL(ActiveMQServer bridgeServer, String bridgeName) - { + private long getBridgeTTL(ActiveMQServer bridgeServer, String bridgeName) { return -1L; } /** * Byteman seems to need this method so that it gets back the concrete type not the interface + * * @param bridgeServer * @return */ - private BridgeImpl getConfiguredBridge(ActiveMQServer bridgeServer) - { + private BridgeImpl getConfiguredBridge(ActiveMQServer bridgeServer) { return getConfiguredBridge(bridgeServer, BRIDGE_NAME); } - private BridgeImpl getConfiguredBridge(ActiveMQServer bridgeServer, String bridgeName) - { - return (BridgeImpl)bridgeServer.getClusterManager().getBridges().get(bridgeName); + private BridgeImpl getConfiguredBridge(ActiveMQServer bridgeServer, String bridgeName) { + return (BridgeImpl) bridgeServer.getClusterManager().getBridges().get(bridgeName); } } diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ClosingConnectionTest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ClosingConnectionTest.java index 249505d0a8..e5698f26aa 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ClosingConnectionTest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ClosingConnectionTest.java @@ -40,8 +40,8 @@ import org.junit.Test; import org.junit.runner.RunWith; @RunWith(BMUnitRunner.class) -public class ClosingConnectionTest extends ActiveMQTestBase -{ +public class ClosingConnectionTest extends ActiveMQTestBase { + public static final SimpleString ADDRESS = new SimpleString("SimpleAddress"); private ServerLocator locator; @@ -52,16 +52,13 @@ public class ClosingConnectionTest extends ActiveMQTestBase private static boolean readyToKill = false; - protected boolean isNetty() - { + protected boolean isNetty() { return true; } - @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); mBeanServer = MBeanServerFactory.createMBeanServer(); server = newActiveMQServer(); @@ -73,24 +70,18 @@ public class ClosingConnectionTest extends ActiveMQTestBase readyToKill = false; } - public static void killConnection() throws InterruptedException - { - if (readyToKill) - { + public static void killConnection() throws InterruptedException { + if (readyToKill) { // We have to kill the connection in a new thread otherwise Netty won't interrupt the current thread - Thread closeConnectionThread = new Thread(new Runnable() - { + Thread closeConnectionThread = new Thread(new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { ActiveMQServerControl serverControl = ManagementControlHelper.createActiveMQServerControl(mBeanServer); serverControl.closeConnectionsForUser("guest"); readyToKill = false; } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -98,8 +89,7 @@ public class ClosingConnectionTest extends ActiveMQTestBase closeConnectionThread.start(); - try - { + try { /* We want to simulate a long-running remoting thread here. If closing the connection in the closeConnectionThread * interrupts this thread then it will cause sleep() to throw and InterruptedException. Therefore we catch * the InterruptedException and re-interrupt the current thread so the interrupt will be passed properly @@ -107,8 +97,7 @@ public class ClosingConnectionTest extends ActiveMQTestBase */ Thread.sleep(1500); } - catch (InterruptedException e) - { + catch (InterruptedException e) { Thread.currentThread().interrupt(); } } @@ -118,26 +107,16 @@ public class ClosingConnectionTest extends ActiveMQTestBase * Test for https://bugzilla.redhat.com/show_bug.cgi?id=1193085 * */ @Test - @BMRules - ( - rules = - { - @BMRule - ( - name = "rule to kill connection", - targetClass = "org.apache.activemq.artemis.core.io.nio.NIOSequentialFile", - targetMethod = "open(int, boolean)", - targetLocation = "AT INVOKE java.nio.channels.FileChannel.size()", - action = "org.apache.activemq.artemis.tests.extras.byteman.ClosingConnectionTest.killConnection();" - - ) - } - ) - public void testKillConnection() throws Exception - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + @BMRules(rules = { + @BMRule( + name = "rule to kill connection", + targetClass = "org.apache.activemq.artemis.core.io.nio.NIOSequentialFile", + targetMethod = "open(int, boolean)", + targetLocation = "AT INVOKE java.nio.channels.FileChannel.size()", + action = "org.apache.activemq.artemis.tests.extras.byteman.ClosingConnectionTest.killConnection();") + }) + public void testKillConnection() throws Exception { + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession("guest", null, false, true, true, false, 0); @@ -149,24 +128,20 @@ public class ClosingConnectionTest extends ActiveMQTestBase ClientMessage message = session.createMessage(true); message.getBodyBuffer().writeBytes(new byte[1024]); - for (int i = 0; i < 200; i++) - { + for (int i = 0; i < 200; i++) { producer.send(message); } assertTrue(server.locateQueue(ADDRESS).getPageSubscription().getPagingStore().isPaging()); readyToKill = true; - try - { - for (int i = 0; i < 8; i++) - { + try { + for (int i = 0; i < 8; i++) { producer.send(message); } fail("Sending message here should result in failure."); } - catch (Exception e) - { + catch (Exception e) { IntegrationTestLogger.LOGGER.info("Caught exception: " + e.getMessage()); } @@ -177,14 +152,11 @@ public class ClosingConnectionTest extends ActiveMQTestBase session.close(); } - private ActiveMQServer newActiveMQServer() throws Exception - { + private ActiveMQServer newActiveMQServer() throws Exception { ActiveMQServer server = createServer(true, createDefaultConfig(isNetty())); server.setMBeanServer(mBeanServer); - AddressSettings defaultSetting = new AddressSettings() - .setPageSizeBytes(10 * 1024) - .setMaxSizeBytes(20 * 1024); + AddressSettings defaultSetting = new AddressSettings().setPageSizeBytes(10 * 1024).setMaxSizeBytes(20 * 1024); server.getAddressSettingsRepository().addMatch("#", defaultSetting); diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ClusteredGroupingTest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ClusteredGroupingTest.java index 732c5ed50d..a623a6d636 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ClusteredGroupingTest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ClusteredGroupingTest.java @@ -37,39 +37,28 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @RunWith(BMUnitRunner.class) -public class ClusteredGroupingTest extends ClusterTestBase -{ +public class ClusteredGroupingTest extends ClusterTestBase { + @Test - @BMRules - ( - rules = - { - @BMRule - ( - name = "blow-up", - targetClass = "org.apache.activemq.artemis.core.server.group.impl.LocalGroupingHandler", - targetMethod = "removeGrouping", - targetLocation = "ENTRY", - action = "org.apache.activemq.artemis.tests.extras.byteman.ClusteredGroupingTest.pause($1);" - ), - @BMRule - ( - name = "blow-up2", - targetClass = "org.apache.activemq.artemis.core.server.group.impl.GroupHandlingAbstract", - targetMethod = "forceRemove", - targetLocation = "ENTRY", - action = "org.apache.activemq.artemis.tests.extras.byteman.ClusteredGroupingTest.restart2();" - ) - } - ) - public void test2serversLocalGoesDown() throws Exception - { + @BMRules( + rules = {@BMRule( + name = "blow-up", + targetClass = "org.apache.activemq.artemis.core.server.group.impl.LocalGroupingHandler", + targetMethod = "removeGrouping", + targetLocation = "ENTRY", + action = "org.apache.activemq.artemis.tests.extras.byteman.ClusteredGroupingTest.pause($1);"), @BMRule( + name = "blow-up2", + targetClass = "org.apache.activemq.artemis.core.server.group.impl.GroupHandlingAbstract", + targetMethod = "forceRemove", + targetLocation = "ENTRY", + action = "org.apache.activemq.artemis.tests.extras.byteman.ClusteredGroupingTest.restart2();")}) + public void test2serversLocalGoesDown() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupClusterConnection("cluster0", "queues", MessageLoadBalancingType.ON_DEMAND, 1, 0, 500, isNetty(), 0, 1); - setupClusterConnection("cluster1", "queues", MessageLoadBalancingType.ON_DEMAND, 1, 0, 500, isNetty(), 1, 0); + setupClusterConnection("cluster1", "queues", MessageLoadBalancingType.ON_DEMAND, 1, 0, 500, isNetty(), 1, 0); setUpGroupHandler(GroupingHandlerConfiguration.TYPE.LOCAL, 0); setUpGroupHandler(GroupingHandlerConfiguration.TYPE.REMOTE, 1); @@ -99,54 +88,41 @@ public class ClusteredGroupingTest extends ClusterTestBase assertTrue(latch2.await(20000, TimeUnit.MILLISECONDS)); - try - { - try - { + try { + try { sendWithProperty(0, "queues.testaddress", 1, true, Message.HDR_GROUP_ID, new SimpleString("id1")); } - catch (ActiveMQNonExistentQueueException e) - { + catch (ActiveMQNonExistentQueueException e) { fail("did not handle removal of queue"); } } - finally - { + finally { latch.countDown(); } } @Test - @BMRules - ( - rules = - { - @BMRule - ( - name = "blow-up", - targetClass = "org.apache.activemq.artemis.core.server.group.impl.RemoteGroupingHandler", - targetMethod = "onNotification", - targetLocation = "ENTRY", - action = "org.apache.activemq.artemis.tests.extras.byteman.ClusteredGroupingTest.pause2($1);" - ), - @BMRule(name = "blow-up2", - targetClass = "org.apache.activemq.artemis.core.server.group.impl.RemoteGroupingHandler", - targetMethod = "remove", - targetLocation = "ENTRY", - action = "org.apache.activemq.artemis.tests.extras.byteman.ClusteredGroupingTest.restart2();") - } - ) - public void test3serversLocalGoesDown() throws Exception - { + @BMRules( + rules = {@BMRule( + name = "blow-up", + targetClass = "org.apache.activemq.artemis.core.server.group.impl.RemoteGroupingHandler", + targetMethod = "onNotification", + targetLocation = "ENTRY", + action = "org.apache.activemq.artemis.tests.extras.byteman.ClusteredGroupingTest.pause2($1);"), @BMRule(name = "blow-up2", + targetClass = "org.apache.activemq.artemis.core.server.group.impl.RemoteGroupingHandler", + targetMethod = "remove", + targetLocation = "ENTRY", + action = "org.apache.activemq.artemis.tests.extras.byteman.ClusteredGroupingTest.restart2();")}) + public void test3serversLocalGoesDown() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); - setupClusterConnection("cluster0", "queues", MessageLoadBalancingType.ON_DEMAND, 1, 0, 500, isNetty(), 0, 1, 2); + setupClusterConnection("cluster0", "queues", MessageLoadBalancingType.ON_DEMAND, 1, 0, 500, isNetty(), 0, 1, 2); - setupClusterConnection("cluster1", "queues", MessageLoadBalancingType.ON_DEMAND, 1, 0, 500, isNetty(), 1, 0, 2); + setupClusterConnection("cluster1", "queues", MessageLoadBalancingType.ON_DEMAND, 1, 0, 500, isNetty(), 1, 0, 2); - setupClusterConnection("cluster2", "queues", MessageLoadBalancingType.ON_DEMAND, 1, 0, 500, isNetty(), 2, 0, 1); + setupClusterConnection("cluster2", "queues", MessageLoadBalancingType.ON_DEMAND, 1, 0, 500, isNetty(), 2, 0, 1); setUpGroupHandler(GroupingHandlerConfiguration.TYPE.LOCAL, 0); setUpGroupHandler(GroupingHandlerConfiguration.TYPE.REMOTE, 1); @@ -182,19 +158,15 @@ public class ClusteredGroupingTest extends ClusterTestBase assertTrue(latch2.await(20000, TimeUnit.MILLISECONDS)); - try - { - try - { + try { + try { sendWithProperty(1, "queues.testaddress", 1, true, Message.HDR_GROUP_ID, new SimpleString("id1")); } - catch (ActiveMQNonExistentQueueException e) - { + catch (ActiveMQNonExistentQueueException e) { fail("did not handle removal of queue"); } } - finally - { + finally { latch.countDown(); } @@ -202,36 +174,27 @@ public class ClusteredGroupingTest extends ClusterTestBase } @Test - @BMRules - ( - rules = - { - @BMRule - ( - name = "blow-up", - targetClass = "org.apache.activemq.artemis.core.server.group.impl.LocalGroupingHandler", - targetMethod = "onNotification", - targetLocation = "ENTRY", - action = "org.apache.activemq.artemis.tests.extras.byteman.ClusteredGroupingTest.pause2($1);" - ), - @BMRule(name = "blow-up2", - targetClass = "org.apache.activemq.artemis.core.server.group.impl.LocalGroupingHandler", - targetMethod = "remove", - targetLocation = "ENTRY", - action = "org.apache.activemq.artemis.tests.extras.byteman.ClusteredGroupingTest.restart2();") - } - ) - public void testLocal3serversLocalGoesDown() throws Exception - { + @BMRules( + rules = {@BMRule( + name = "blow-up", + targetClass = "org.apache.activemq.artemis.core.server.group.impl.LocalGroupingHandler", + targetMethod = "onNotification", + targetLocation = "ENTRY", + action = "org.apache.activemq.artemis.tests.extras.byteman.ClusteredGroupingTest.pause2($1);"), @BMRule(name = "blow-up2", + targetClass = "org.apache.activemq.artemis.core.server.group.impl.LocalGroupingHandler", + targetMethod = "remove", + targetLocation = "ENTRY", + action = "org.apache.activemq.artemis.tests.extras.byteman.ClusteredGroupingTest.restart2();")}) + public void testLocal3serversLocalGoesDown() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); - setupClusterConnection("cluster0", "queues", MessageLoadBalancingType.ON_DEMAND, 1, 0, 500, isNetty(), 0, 1, 2); + setupClusterConnection("cluster0", "queues", MessageLoadBalancingType.ON_DEMAND, 1, 0, 500, isNetty(), 0, 1, 2); - setupClusterConnection("cluster1", "queues", MessageLoadBalancingType.ON_DEMAND, 1, 0, 500, isNetty(), 1, 0, 2); + setupClusterConnection("cluster1", "queues", MessageLoadBalancingType.ON_DEMAND, 1, 0, 500, isNetty(), 1, 0, 2); - setupClusterConnection("cluster2", "queues", MessageLoadBalancingType.ON_DEMAND, 1, 0, 500, isNetty(), 2, 0, 1); + setupClusterConnection("cluster2", "queues", MessageLoadBalancingType.ON_DEMAND, 1, 0, 500, isNetty(), 2, 0, 1); setUpGroupHandler(GroupingHandlerConfiguration.TYPE.LOCAL, 0); setUpGroupHandler(GroupingHandlerConfiguration.TYPE.REMOTE, 1); @@ -267,19 +230,15 @@ public class ClusteredGroupingTest extends ClusterTestBase assertTrue(latch2.await(20000, TimeUnit.MILLISECONDS)); - try - { - try - { + try { + try { sendWithProperty(0, "queues.testaddress", 1, true, Message.HDR_GROUP_ID, new SimpleString("id1")); } - catch (ActiveMQNonExistentQueueException e) - { + catch (ActiveMQNonExistentQueueException e) { fail("did not handle removal of queue"); } } - finally - { + finally { latch.countDown(); } @@ -287,39 +246,30 @@ public class ClusteredGroupingTest extends ClusterTestBase } @Test - @BMRules - ( - rules = - { - @BMRule - ( - name = "blow-up", - targetClass = "org.apache.activemq.artemis.core.server.group.impl.LocalGroupingHandler", - targetMethod = "onNotification", - targetLocation = "ENTRY", - action = "org.apache.activemq.artemis.tests.extras.byteman.ClusteredGroupingTest.pause2($1);" - ), - @BMRule(name = "blow-up2", - targetClass = "org.apache.activemq.artemis.core.server.group.impl.LocalGroupingHandler", - targetMethod = "remove", - targetLocation = "ENTRY", - action = "org.apache.activemq.artemis.tests.extras.byteman.ClusteredGroupingTest.restart2();") - } - ) - public void testLocal4serversLocalGoesDown() throws Exception - { + @BMRules( + rules = {@BMRule( + name = "blow-up", + targetClass = "org.apache.activemq.artemis.core.server.group.impl.LocalGroupingHandler", + targetMethod = "onNotification", + targetLocation = "ENTRY", + action = "org.apache.activemq.artemis.tests.extras.byteman.ClusteredGroupingTest.pause2($1);"), @BMRule(name = "blow-up2", + targetClass = "org.apache.activemq.artemis.core.server.group.impl.LocalGroupingHandler", + targetMethod = "remove", + targetLocation = "ENTRY", + action = "org.apache.activemq.artemis.tests.extras.byteman.ClusteredGroupingTest.restart2();")}) + public void testLocal4serversLocalGoesDown() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); setupServer(3, isFileStorage(), isNetty()); - setupClusterConnection("cluster0", "queues", MessageLoadBalancingType.ON_DEMAND, 1, 0, 500, isNetty(), 0, 1, 2, 3); + setupClusterConnection("cluster0", "queues", MessageLoadBalancingType.ON_DEMAND, 1, 0, 500, isNetty(), 0, 1, 2, 3); - setupClusterConnection("cluster1", "queues", MessageLoadBalancingType.ON_DEMAND, 1, 0, 500, isNetty(), 1, 0, 2, 3); + setupClusterConnection("cluster1", "queues", MessageLoadBalancingType.ON_DEMAND, 1, 0, 500, isNetty(), 1, 0, 2, 3); - setupClusterConnection("cluster2", "queues", MessageLoadBalancingType.ON_DEMAND, 1, 0, 500, isNetty(), 2, 0, 1, 3); + setupClusterConnection("cluster2", "queues", MessageLoadBalancingType.ON_DEMAND, 1, 0, 500, isNetty(), 2, 0, 1, 3); - setupClusterConnection("cluster3", "queues", MessageLoadBalancingType.ON_DEMAND, 1, 0, 500, isNetty(), 3, 1, 2, 3); + setupClusterConnection("cluster3", "queues", MessageLoadBalancingType.ON_DEMAND, 1, 0, 500, isNetty(), 3, 1, 2, 3); setUpGroupHandler(GroupingHandlerConfiguration.TYPE.LOCAL, 0); setUpGroupHandler(GroupingHandlerConfiguration.TYPE.REMOTE, 1); @@ -360,19 +310,15 @@ public class ClusteredGroupingTest extends ClusterTestBase assertTrue(latch2.await(20000, TimeUnit.MILLISECONDS)); - try - { - try - { + try { + try { sendWithProperty(0, "queues.testaddress", 1, true, Message.HDR_GROUP_ID, new SimpleString("id1")); } - catch (ActiveMQNonExistentQueueException e) - { + catch (ActiveMQNonExistentQueueException e) { fail("did not handle removal of queue"); } } - finally - { + finally { latch.countDown(); } //now restart server @@ -384,14 +330,11 @@ public class ClusteredGroupingTest extends ClusterTestBase assertHandlersAreSame(getServer(0), getServer(1), getServer(2), getServer(3)); } - private void assertHandlersAreSame(ActiveMQServer server, ActiveMQServer... qServers) - { + private void assertHandlersAreSame(ActiveMQServer server, ActiveMQServer... qServers) { SimpleString id = server.getGroupingHandler().getProposal(new SimpleString("id1.queue0"), false).getClusterName(); - for (ActiveMQServer qServer : qServers) - { + for (ActiveMQServer qServer : qServers) { Response proposal = qServer.getGroupingHandler().getProposal(new SimpleString("id1.queue0"), false); - if (proposal != null) - { + if (proposal != null) { assertEquals(qServer.getIdentity() + " is incorrect", id, proposal.getChosenClusterName()); } } @@ -401,51 +344,39 @@ public class ClusteredGroupingTest extends ClusterTestBase static CountDownLatch latch2; static Thread main; - public static void pause(SimpleString clusterName) - { - if (clusterName.toString().startsWith("queue0")) - { - try - { + public static void pause(SimpleString clusterName) { + if (clusterName.toString().startsWith("queue0")) { + try { latch2.countDown(); latch.await(); } - catch (InterruptedException e) - { + catch (InterruptedException e) { e.printStackTrace(); } } } - public static void pause2(Notification notification) - { - if (notification.getType() == CoreNotificationType.BINDING_REMOVED) - { - SimpleString clusterName = notification.getProperties() - .getSimpleStringProperty(ManagementHelper.HDR_CLUSTER_NAME); + public static void pause2(Notification notification) { + if (notification.getType() == CoreNotificationType.BINDING_REMOVED) { + SimpleString clusterName = notification.getProperties().getSimpleStringProperty(ManagementHelper.HDR_CLUSTER_NAME); boolean inMain = main == Thread.currentThread(); - if (clusterName.toString().startsWith("queue0") && !inMain) - { - try - { + if (clusterName.toString().startsWith("queue0") && !inMain) { + try { latch2.countDown(); latch.await(); } - catch (InterruptedException e) - { + catch (InterruptedException e) { e.printStackTrace(); } } } } - public static void restart2() - { + public static void restart2() { latch.countDown(); } - public boolean isNetty() - { + public boolean isNetty() { return true; } } diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/GroupingTest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/GroupingTest.java index 0a2cff6540..d7d418122a 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/GroupingTest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/GroupingTest.java @@ -40,48 +40,36 @@ import javax.jms.TextMessage; * GroupingTest */ @RunWith(BMUnitRunner.class) -public class GroupingTest extends JMSTestBase -{ +public class GroupingTest extends JMSTestBase { + private Queue queue; static boolean pause = false; @Before @Override - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); queue = createQueue("TestQueue"); } - protected ConnectionFactory getCF() throws Exception - { + protected ConnectionFactory getCF() throws Exception { return cf; } - @Test - @BMRules - ( - rules = - { - @BMRule - ( - name = "trace clientsessionimpl commit", - targetClass = "org.apache.activemq.artemis.core.server.impl.ServerSessionImpl", - targetMethod = "rollback", - targetLocation = "EXIT", - action = "org.apache.activemq.artemis.tests.extras.byteman.GroupingTest.pause();" - ) - } - ) - public void testGroupingRollbackOnClose() throws Exception - { + @BMRules( + rules = {@BMRule( + name = "trace clientsessionimpl commit", + targetClass = "org.apache.activemq.artemis.core.server.impl.ServerSessionImpl", + targetMethod = "rollback", + targetLocation = "EXIT", + action = "org.apache.activemq.artemis.tests.extras.byteman.GroupingTest.pause();")}) + public void testGroupingRollbackOnClose() throws Exception { Connection sendConnection = null; Connection connection = null; Connection connection2 = null; - try - { + try { ActiveMQConnectionFactory fact = (ActiveMQConnectionFactory) getCF(); fact.setReconnectAttempts(0); //fact.setConsumerWindowSize(1000); @@ -105,16 +93,12 @@ public class GroupingTest extends JMSTestBase final String jmsxgroupID = null; - Thread t = new Thread(new Runnable() - { + Thread t = new Thread(new Runnable() { @Override - public void run() - { + public void run() { - try - { - for (int j = 0; j < 10000; j++) - { + try { + for (int j = 0; j < 10000; j++) { TextMessage message = sendSession.createTextMessage(); message.setText("Message" + j); @@ -124,8 +108,7 @@ public class GroupingTest extends JMSTestBase producer.send(message); } } - catch (JMSException e) - { + catch (JMSException e) { e.printStackTrace(); } } @@ -133,8 +116,7 @@ public class GroupingTest extends JMSTestBase t.start(); //consume 5 msgs from 1st first consumer - for (int j = 0; j < 5; j++) - { + for (int j = 0; j < 5; j++) { TextMessage tm = (TextMessage) consumer1.receive(10000); assertNotNull(tm); @@ -148,8 +130,7 @@ public class GroupingTest extends JMSTestBase rc.fail(new ActiveMQNotConnectedException()); pause = false; - for (int j = 0; j < 10000; j++) - { + for (int j = 0; j < 10000; j++) { TextMessage tm = (TextMessage) consumer2.receive(5000); assertNotNull(tm); @@ -159,31 +140,23 @@ public class GroupingTest extends JMSTestBase assertEquals(tm.getStringProperty("JMSXGroupID"), "foo"); } } - finally - { - if (sendConnection != null) - { + finally { + if (sendConnection != null) { sendConnection.close(); } - if (connection2 != null) - { + if (connection2 != null) { connection2.close(); } } } - - public static void pause() - { - if (pause) - { - try - { + public static void pause() { + if (pause) { + try { System.out.println("pausing after rollback"); Thread.sleep(500); } - catch (InterruptedException e) - { + catch (InterruptedException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } System.out.println("finished pausing after rollback"); diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/HierarchicalObjectRepositoryTest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/HierarchicalObjectRepositoryTest.java index 679776a3b4..361cbc70d4 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/HierarchicalObjectRepositoryTest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/HierarchicalObjectRepositoryTest.java @@ -32,12 +32,12 @@ import org.junit.Test; import org.junit.runner.RunWith; @RunWith(BMUnitRunner.class) -@BMRules(rules = { @BMRule(name = "modify map during iteration", +@BMRules(rules = {@BMRule(name = "modify map during iteration", targetClass = "org.apache.activemq.artemis.core.settings.impl.HierarchicalObjectRepository", targetMethod = "getPossibleMatches(String)", targetLocation = "AT INVOKE java.util.HashMap.put", - action = "org.apache.activemq.artemis.tests.extras.byteman.HierarchicalObjectRepositoryTest.bum()"), }) -public class HierarchicalObjectRepositoryTest -{ + action = "org.apache.activemq.artemis.tests.extras.byteman.HierarchicalObjectRepositoryTest.bum()"),}) +public class HierarchicalObjectRepositoryTest { + private static final String A = "a."; private static final int TOTAL = 100; private static CountDownLatch latch; @@ -46,8 +46,7 @@ public class HierarchicalObjectRepositoryTest private HierarchicalObjectRepository repo; @Before - public void setUp() - { + public void setUp() { latch = new CountDownLatch(1); latch2 = new CountDownLatch(1); executor = Executors.newSingleThreadExecutor(); @@ -55,46 +54,38 @@ public class HierarchicalObjectRepositoryTest addToRepo(repo, A); } - static void addToRepo(HierarchicalObjectRepository repo0, String pattern) - { - for (int i = 0; i < TOTAL; i++) - { + static void addToRepo(HierarchicalObjectRepository repo0, String pattern) { + for (int i = 0; i < TOTAL; i++) { repo0.addMatch(pattern + i + ".*", String.valueOf(i)); } } @After - public void tearDown() throws InterruptedException - { + public void tearDown() throws InterruptedException { latch.countDown(); latch2.countDown(); executor.shutdown(); executor.awaitTermination(1, TimeUnit.SECONDS); } - private class Clearer implements Runnable - { + private class Clearer implements Runnable { + private final int code; - public Clearer(int code) - { + public Clearer(int code) { this.code = code; } @Override - public void run() - { - try - { + public void run() { + try { latch.await(); } - catch (InterruptedException e) - { + catch (InterruptedException e) { throw new RuntimeException(e); } - switch (code) - { + switch (code) { case 0: repo.clear(); break; @@ -102,8 +93,7 @@ public class HierarchicalObjectRepositoryTest addToRepo(repo, "bb."); break; case 2: - for (int i = TOTAL / 2; i < TOTAL; i++) - { + for (int i = TOTAL / 2; i < TOTAL; i++) { repo.removeMatch(A + i + ".*"); } break; @@ -116,38 +106,32 @@ public class HierarchicalObjectRepositoryTest } @Test - public void testConcurrentModificationsClear() - { + public void testConcurrentModificationsClear() { executor.execute(new Clearer(0)); repo.getMatch(A + (TOTAL - 10) + ".foobar"); Assert.assertEquals("Byteman rule failed?", 0, latch.getCount()); } @Test - public void testConcurrentModificationsAdd() - { + public void testConcurrentModificationsAdd() { executor.execute(new Clearer(1)); repo.getMatch(A + (TOTAL - 10) + ".foobar"); Assert.assertEquals("Byteman rule failed?", 0, latch.getCount()); } @Test - public void testConcurrentModificationsRemove() - { + public void testConcurrentModificationsRemove() { executor.execute(new Clearer(2)); repo.getMatch(A + (TOTAL - 10) + ".foobar"); Assert.assertEquals("Byteman rule failed?", 0, latch.getCount()); } - public static void bum() - { + public static void bum() { latch.countDown(); - try - { + try { latch2.await(3, TimeUnit.SECONDS); } - catch (InterruptedException e) - { + catch (InterruptedException e) { // no op } } diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/InterruptedMessageHandlerTest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/InterruptedMessageHandlerTest.java index e5d638f6e2..5858c45747 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/InterruptedMessageHandlerTest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/InterruptedMessageHandlerTest.java @@ -49,46 +49,39 @@ import org.junit.Test; import org.junit.runner.RunWith; @RunWith(BMUnitRunner.class) -public class InterruptedMessageHandlerTest extends ActiveMQRATestBase -{ +public class InterruptedMessageHandlerTest extends ActiveMQRATestBase { - protected boolean usePersistence() - { + protected boolean usePersistence() { return true; } @Override - public boolean useSecurity() - { + public boolean useSecurity() { return false; } @Test @BMRules( - rules = { @BMRule( + rules = {@BMRule( name = "throw ActiveMQException(CONNETION_TIMEOUT) during rollback", targetClass = "org.apache.activemq.artemis.core.client.impl.ClientSessionImpl", targetMethod = "flushAcks", targetLocation = "AFTER INVOKE flushAcks", - action = "org.apache.activemq.artemis.tests.extras.byteman.InterruptedMessageHandlerTest.throwActiveMQQExceptionConnectionTimeout();"), - @BMRule( - name = "check that outcome of XA transaction is TwoPhaseOutcome.FINISH_ERROR=8", - targetClass = "com.arjuna.ats.internal.jta.resources.arjunacore.XAResourceRecord", - targetMethod = "topLevelAbort", - targetLocation = "AT EXIT", - action = "org.apache.activemq.artemis.tests.extras.byteman.InterruptedMessageHandlerTest.assertTxOutComeIsOfStatusFinishedError($!);") }) - public void testSimpleMessageReceivedOnQueueTwoPhaseFailPrepareByConnectionTimout() throws Exception - { + action = "org.apache.activemq.artemis.tests.extras.byteman.InterruptedMessageHandlerTest.throwActiveMQQExceptionConnectionTimeout();"), @BMRule( + name = "check that outcome of XA transaction is TwoPhaseOutcome.FINISH_ERROR=8", + targetClass = "com.arjuna.ats.internal.jta.resources.arjunacore.XAResourceRecord", + targetMethod = "topLevelAbort", + targetLocation = "AT EXIT", + action = "org.apache.activemq.artemis.tests.extras.byteman.InterruptedMessageHandlerTest.assertTxOutComeIsOfStatusFinishedError($!);")}) + public void testSimpleMessageReceivedOnQueueTwoPhaseFailPrepareByConnectionTimout() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); resourceAdapter = qResourceAdapter; - MyBootstrapContext ctx = new MyBootstrapContext(); qResourceAdapter.setConnectorClassName(NETTY_CONNECTOR_FACTORY); qResourceAdapter.start(ctx); - ActiveMQActivationSpec spec = new ActiveMQActivationSpec(); spec.setMaxSession(1); spec.setCallTimeout(1000L); @@ -128,31 +121,25 @@ public class InterruptedMessageHandlerTest extends ActiveMQRATestBase server.stop(); - assertEquals("Two phase outcome must be of TwoPhaseOutcome.FINISH_ERROR.", TwoPhaseOutcome.FINISH_ERROR, - txTwoPhaseOutCome.intValue()); + assertEquals("Two phase outcome must be of TwoPhaseOutcome.FINISH_ERROR.", TwoPhaseOutcome.FINISH_ERROR, txTwoPhaseOutCome.intValue()); } static volatile ActiveMQResourceAdapter resourceAdapter; static boolean resourceAdapterStopped = false; - public static void interrupt() throws InterruptedException - { - if (!resourceAdapterStopped) - { + public static void interrupt() throws InterruptedException { + if (!resourceAdapterStopped) { resourceAdapter.stop(); resourceAdapterStopped = true; throw new InterruptedException("foo"); } } - public static void throwActiveMQQExceptionConnectionTimeout() throws ActiveMQException, XAException - { + public static void throwActiveMQQExceptionConnectionTimeout() throws ActiveMQException, XAException { StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); - for (StackTraceElement element : stackTraceElements) - { - if (element.getClassName().contains("ClientSessionImpl") && element.getMethodName().contains("rollback")) - { + for (StackTraceElement element : stackTraceElements) { + if (element.getClassName().contains("ClientSessionImpl") && element.getMethodName().contains("rollback")) { throw new ActiveMQException(ActiveMQExceptionType.CONNECTION_TIMEDOUT); } } @@ -160,72 +147,59 @@ public class InterruptedMessageHandlerTest extends ActiveMQRATestBase static Integer txTwoPhaseOutCome = null; - public static void assertTxOutComeIsOfStatusFinishedError(int txOutCome) - { + public static void assertTxOutComeIsOfStatusFinishedError(int txOutCome) { // check only first trigger of byteman rule - if (txTwoPhaseOutCome == null) - { + if (txTwoPhaseOutCome == null) { txTwoPhaseOutCome = Integer.valueOf(txOutCome); } } Transaction currentTX; - public class XADummyEndpoint extends DummyMessageEndpoint - { + public class XADummyEndpoint extends DummyMessageEndpoint { + final boolean twoPhase; ClientSession session; int afterDeliveryCounts = 0; - public XADummyEndpoint(CountDownLatch latch, boolean twoPhase) throws SystemException - { + public XADummyEndpoint(CountDownLatch latch, boolean twoPhase) throws SystemException { super(latch); this.twoPhase = twoPhase; - try - { + try { session = locator.createSessionFactory().createSession(true, false, false); } - catch (Throwable e) - { + catch (Throwable e) { throw new RuntimeException(e); } } @Override - public void beforeDelivery(Method method) throws NoSuchMethodException, ResourceException - { + public void beforeDelivery(Method method) throws NoSuchMethodException, ResourceException { super.beforeDelivery(method); - try - { + try { DummyTMLocator.tm.begin(); currentTX = DummyTMLocator.tm.getTransaction(); currentTX.enlistResource(xaResource); - if (twoPhase) - { + if (twoPhase) { currentTX.enlistResource(new DummyXAResource()); } } - catch (Throwable e) - { + catch (Throwable e) { throw new RuntimeException(e.getMessage(), e); } } - public void onMessage(Message message) - { + public void onMessage(Message message) { super.onMessage(message); } @Override - public void afterDelivery() throws ResourceException - { + public void afterDelivery() throws ResourceException { afterDeliveryCounts++; - try - { + try { currentTX.commit(); } - catch (Throwable e) - { + catch (Throwable e) { // its unsure as to whether the EJB/JCA layer will handle this or throw it to us, // either way we don't do anything else so its fine just to throw. // NB this will only happen with 2 phase commit @@ -236,8 +210,7 @@ public class InterruptedMessageHandlerTest extends ActiveMQRATestBase } @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { resourceAdapter = null; resourceAdapterStopped = false; super.setUp(); @@ -245,139 +218,116 @@ public class InterruptedMessageHandlerTest extends ActiveMQRATestBase } @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { DummyTMLocator.stopTM(); super.tearDown(); } - public static class DummyTMLocator - { + public static class DummyTMLocator { + public static TransactionManagerImple tm; - public static void stopTM() - { - try - { + public static void stopTM() { + try { TransactionReaper.terminate(true); TxControl.disable(true); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } tm = null; } - public static void startTM() - { + public static void startTM() { tm = new TransactionManagerImple(); TxControl.enable(); } - public TransactionManager getTM() - { + public TransactionManager getTM() { return tm; } } - static class DummyXAResource implements XAResource - { + static class DummyXAResource implements XAResource { + @Override - public void commit(Xid xid, boolean b) throws XAException - { + public void commit(Xid xid, boolean b) throws XAException { } @Override - public void end(Xid xid, int i) throws XAException - { + public void end(Xid xid, int i) throws XAException { } @Override - public void forget(Xid xid) throws XAException - { + public void forget(Xid xid) throws XAException { } @Override - public int getTransactionTimeout() throws XAException - { + public int getTransactionTimeout() throws XAException { return 0; } @Override - public boolean isSameRM(XAResource xaResource) throws XAException - { + public boolean isSameRM(XAResource xaResource) throws XAException { return false; } @Override - public int prepare(Xid xid) throws XAException - { + public int prepare(Xid xid) throws XAException { return 0; } @Override - public Xid[] recover(int i) throws XAException - { + public Xid[] recover(int i) throws XAException { return new Xid[0]; } @Override - public void rollback(Xid xid) throws XAException - { + public void rollback(Xid xid) throws XAException { } @Override - public boolean setTransactionTimeout(int i) throws XAException - { + public boolean setTransactionTimeout(int i) throws XAException { return false; } @Override - public void start(Xid xid, int i) throws XAException - { + public void start(Xid xid, int i) throws XAException { } } - public class XADummyEndpointWithDummyXAResourceFailEnd extends XADummyEndpoint - { + public class XADummyEndpointWithDummyXAResourceFailEnd extends XADummyEndpoint { - public XADummyEndpointWithDummyXAResourceFailEnd(CountDownLatch latch, boolean twoPhase) throws SystemException - { + public XADummyEndpointWithDummyXAResourceFailEnd(CountDownLatch latch, boolean twoPhase) throws SystemException { super(latch, twoPhase); } @Override - public void beforeDelivery(Method method) throws NoSuchMethodException, ResourceException - { - try - { + public void beforeDelivery(Method method) throws NoSuchMethodException, ResourceException { + try { DummyTMLocator.tm.begin(); currentTX = DummyTMLocator.tm.getTransaction(); currentTX.enlistResource(xaResource); - if (twoPhase) - { + if (twoPhase) { currentTX.enlistResource(new DummyXAResourceFailEnd()); } } - catch (Throwable e) - { + catch (Throwable e) { throw new RuntimeException(e.getMessage(), e); } } } - static class DummyXAResourceFailEnd extends DummyXAResource - { + static class DummyXAResourceFailEnd extends DummyXAResource { + @Override - public void end(Xid xid, int i) throws XAException - { + public void end(Xid xid, int i) throws XAException { throw new XAException(XAException.XAER_RMFAIL); } } diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/JMSBridgeReconnectionTest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/JMSBridgeReconnectionTest.java index 8af466fea4..6a935b4afe 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/JMSBridgeReconnectionTest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/JMSBridgeReconnectionTest.java @@ -31,78 +31,45 @@ import org.jboss.byteman.contrib.bmunit.BMRules; import org.jboss.byteman.contrib.bmunit.BMUnitRunner; import org.junit.Test; import org.junit.runner.RunWith; + import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @RunWith(BMUnitRunner.class) -public class JMSBridgeReconnectionTest extends BridgeTestBase -{ +public class JMSBridgeReconnectionTest extends BridgeTestBase { @Test - @BMRules - ( - rules = - { - @BMRule - ( - name = "trace clientsessionimpl send", - targetClass = "org.apache.activemq.artemis.core.protocol.core.impl.ChannelImpl", - targetMethod = "send", - targetLocation = "ENTRY", - action = "org.apache.activemq.artemis.tests.extras.byteman.JMSBridgeReconnectionTest.pause($1);" - ), - @BMRule - ( - name = "trace sendRegularMessage", - targetClass = "org.apache.activemq.artemis.core.client.impl.ClientProducerImpl", - targetMethod = "sendRegularMessage", - targetLocation = "ENTRY", - action = "org.apache.activemq.artemis.tests.extras.byteman.JMSBridgeReconnectionTest.pause2($1,$2,$3);" - ) - } - ) - public void performCrashDestinationStopBridge() throws Exception - { + @BMRules( + rules = {@BMRule( + name = "trace clientsessionimpl send", + targetClass = "org.apache.activemq.artemis.core.protocol.core.impl.ChannelImpl", + targetMethod = "send", + targetLocation = "ENTRY", + action = "org.apache.activemq.artemis.tests.extras.byteman.JMSBridgeReconnectionTest.pause($1);"), @BMRule( + name = "trace sendRegularMessage", + targetClass = "org.apache.activemq.artemis.core.client.impl.ClientProducerImpl", + targetMethod = "sendRegularMessage", + targetLocation = "ENTRY", + action = "org.apache.activemq.artemis.tests.extras.byteman.JMSBridgeReconnectionTest.pause2($1,$2,$3);")}) + public void performCrashDestinationStopBridge() throws Exception { activeMQServer = jmsServer1; ConnectionFactoryFactory factInUse0 = cff0; ConnectionFactoryFactory factInUse1 = cff1; - final JMSBridgeImpl bridge = - new JMSBridgeImpl(factInUse0, - factInUse1, - sourceQueueFactory, - targetQueueFactory, - null, - null, - null, - null, - null, - 1000, - -1, - QualityOfServiceMode.DUPLICATES_OK, - 10, - -1, - null, - null, - false); + final JMSBridgeImpl bridge = new JMSBridgeImpl(factInUse0, factInUse1, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 1000, -1, QualityOfServiceMode.DUPLICATES_OK, 10, -1, null, null, false); addActiveMQComponent(bridge); bridge.setTransactionManager(newTransactionManager()); bridge.start(); final CountDownLatch latch = new CountDownLatch(20); - Thread clientThread = new Thread(new Runnable() - { + Thread clientThread = new Thread(new Runnable() { @Override - public void run() - { - while (bridge.isStarted()) - { - try - { + public void run() { + while (bridge.isStarted()) { + try { sendMessages(cf0, sourceQueue, 0, 1, false, false); latch.countDown(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -120,28 +87,21 @@ public class JMSBridgeReconnectionTest extends BridgeTestBase assertTrue(!clientThread.isAlive()); } - public static void pause(Packet packet) - { - if (packet.getType() == PacketImpl.SESS_SEND) - { + public static void pause(Packet packet) { + if (packet.getType() == PacketImpl.SESS_SEND) { SessionSendMessage sendMessage = (SessionSendMessage) packet; - if (sendMessage.getMessage().containsProperty("__AMQ_CID") && count < 0 && !stopped) - { - try - { + if (sendMessage.getMessage().containsProperty("__AMQ_CID") && count < 0 && !stopped) { + try { activeMQServer.stop(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } stopped = true; - try - { + try { Thread.sleep(5000); } - catch (InterruptedException e) - { + catch (InterruptedException e) { e.printStackTrace(); } stopLatch.countDown(); @@ -153,10 +113,9 @@ public class JMSBridgeReconnectionTest extends BridgeTestBase static boolean stopped = false; static int count = 20; static CountDownLatch stopLatch = new CountDownLatch(1); - public static void pause2(MessageInternal msgI, boolean sendBlocking, final ClientProducerCredits theCredits) - { - if (msgI.containsProperty("__AMQ_CID")) - { + + public static void pause2(MessageInternal msgI, boolean sendBlocking, final ClientProducerCredits theCredits) { + if (msgI.containsProperty("__AMQ_CID")) { count--; } } diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/LatencyTest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/LatencyTest.java index 6f08e1efee..52578330a7 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/LatencyTest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/LatencyTest.java @@ -28,36 +28,25 @@ import org.junit.Test; import org.junit.runner.RunWith; @RunWith(BMUnitRunner.class) -public class LatencyTest extends ActiveMQTestBase -{ +public class LatencyTest extends ActiveMQTestBase { + /* * simple test to make sure connect still works with some network latency built into netty * */ @Test - @BMRules - ( - rules = - { - @BMRule - ( - name = "trace ClientBootstrap.connect", - targetClass = "org.jboss.netty.bootstrap.ClientBootstrap", - targetMethod = "connect", - targetLocation = "ENTRY", - action = "System.out.println(\"netty connecting\")" - ), - @BMRule - ( - name = "sleep OioWorker.run", - targetClass = "org.jboss.netty.channel.socket.oio.OioWorker", - targetMethod = "run", - targetLocation = "ENTRY", - action = "Thread.sleep(500)" - ) - } - ) - public void testLatency() throws Exception - { + @BMRules( + rules = {@BMRule( + name = "trace ClientBootstrap.connect", + targetClass = "org.jboss.netty.bootstrap.ClientBootstrap", + targetMethod = "connect", + targetLocation = "ENTRY", + action = "System.out.println(\"netty connecting\")"), @BMRule( + name = "sleep OioWorker.run", + targetClass = "org.jboss.netty.channel.socket.oio.OioWorker", + targetMethod = "run", + targetLocation = "ENTRY", + action = "Thread.sleep(500)")}) + public void testLatency() throws Exception { ActiveMQServer server = createServer(createDefaultNettyConfig()); server.start(); ServerLocator locator = createNettyNonHALocator(); diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/MessageCopyTest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/MessageCopyTest.java index 32cf4abcf1..2e37e56791 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/MessageCopyTest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/MessageCopyTest.java @@ -33,50 +33,34 @@ import org.junit.Test; import org.junit.runner.RunWith; @RunWith(BMUnitRunner.class) -public class MessageCopyTest -{ - @Test - @BMRules - ( +public class MessageCopyTest { - rules = - { - @BMRule - ( - name = "message-copy0", - targetClass = "org.apache.activemq.artemis.core.server.impl.ServerMessageImpl", - targetMethod = "copy()", - targetLocation = "ENTRY", - action = "System.out.println(\"copy\"), waitFor(\"encode-done\")" - ), - @BMRule - ( - name = "message-copy-done", - targetClass = "org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionSendMessage", - targetMethod = "encode(org.apache.activemq.artemis.spi.core.protocol.RemotingConnection)", - targetLocation = "EXIT", - action = "System.out.println(\"encodeDone\"), signalWake(\"encode-done\", true)" - ), - @BMRule - ( - name = "message-copy1", - targetClass = "org.apache.activemq.artemis.core.buffers.impl.ChannelBufferWrapper", - targetMethod = "copy(int, int)", - condition = "Thread.currentThread().getName().equals(\"T1\")", - targetLocation = "EXIT", - action = "System.out.println(\"setIndex at \" + Thread.currentThread().getName()), waitFor(\"finish-read\")" - ), - @BMRule( - name = "JMSServer.stop wait-init", - targetClass = "org.apache.activemq.artemis.tests.extras.byteman.MessageCopyTest", - targetMethod = "simulateRead", - targetLocation = "EXIT", - action = "signalWake(\"finish-read\", true)" - ) - } - ) - public void testMessageCopyIssue() throws Exception - { + @Test + @BMRules( + + rules = {@BMRule( + name = "message-copy0", + targetClass = "org.apache.activemq.artemis.core.server.impl.ServerMessageImpl", + targetMethod = "copy()", + targetLocation = "ENTRY", + action = "System.out.println(\"copy\"), waitFor(\"encode-done\")"), @BMRule( + name = "message-copy-done", + targetClass = "org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionSendMessage", + targetMethod = "encode(org.apache.activemq.artemis.spi.core.protocol.RemotingConnection)", + targetLocation = "EXIT", + action = "System.out.println(\"encodeDone\"), signalWake(\"encode-done\", true)"), @BMRule( + name = "message-copy1", + targetClass = "org.apache.activemq.artemis.core.buffers.impl.ChannelBufferWrapper", + targetMethod = "copy(int, int)", + condition = "Thread.currentThread().getName().equals(\"T1\")", + targetLocation = "EXIT", + action = "System.out.println(\"setIndex at \" + Thread.currentThread().getName()), waitFor(\"finish-read\")"), @BMRule( + name = "JMSServer.stop wait-init", + targetClass = "org.apache.activemq.artemis.tests.extras.byteman.MessageCopyTest", + targetMethod = "simulateRead", + targetLocation = "EXIT", + action = "signalWake(\"finish-read\", true)")}) + public void testMessageCopyIssue() throws Exception { final long RUNS = 1; final ServerMessageImpl msg = new ServerMessageImpl(123, 18); @@ -91,33 +75,26 @@ public class MessageCopyTest final CountDownLatch latchAlign = new CountDownLatch(T1_number + T2_number); final CountDownLatch latchReady = new CountDownLatch(1); - class T1 extends Thread - { - T1() - { + class T1 extends Thread { + + T1() { super("T1"); } @Override - public void run() - { + public void run() { latchAlign.countDown(); - try - { + try { latchReady.await(); } - catch (Exception ignored) - { + catch (Exception ignored) { } - for (int i = 0; i < RUNS; i++) - { - try - { + for (int i = 0; i < RUNS; i++) { + try { ServerMessageImpl newMsg = (ServerMessageImpl) msg.copy(); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); errors.incrementAndGet(); } @@ -125,36 +102,29 @@ public class MessageCopyTest } } - class T2 extends Thread - { - T2() - { + class T2 extends Thread { + + T2() { super("T2"); } @Override - public void run() - { + public void run() { latchAlign.countDown(); - try - { + try { latchReady.await(); } - catch (Exception ignored) - { + catch (Exception ignored) { } - for (int i = 0; i < RUNS; i++) - { - try - { + for (int i = 0; i < RUNS; i++) { + try { SessionSendMessage ssm = new SessionSendMessage(msg); ActiveMQBuffer buf = ssm.encode(null); System.out.println("reading at buf = " + buf); simulateRead(buf); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); errors.incrementAndGet(); } @@ -162,18 +132,15 @@ public class MessageCopyTest } } - ArrayList threads = new ArrayList(); - for (int i = 0; i < T1_number; i++) - { + for (int i = 0; i < T1_number; i++) { T1 t = new T1(); threads.add(t); t.start(); } - for (int i = 0; i < T2_number; i++) - { + for (int i = 0; i < T2_number; i++) { T2 t2 = new T2(); threads.add(t2); t2.start(); @@ -183,21 +150,18 @@ public class MessageCopyTest latchReady.countDown(); - for (Thread t : threads) - { + for (Thread t : threads) { t.join(); } Assert.assertEquals(0, errors.get()); } - private void simulateRead(ActiveMQBuffer buf) - { + private void simulateRead(ActiveMQBuffer buf) { buf.setIndex(buf.capacity() / 2, buf.capacity() / 2); // ok this is not actually happening during the read process, but changing this shouldn't affect the buffer on copy buf.writeBytes(new byte[1024]); } - } diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/OrphanedConsumerTest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/OrphanedConsumerTest.java index 2325599958..211aee5c15 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/OrphanedConsumerTest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/OrphanedConsumerTest.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.tests.extras.byteman; - import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.client.ClientConsumer; import org.apache.activemq.artemis.api.core.client.ClientMessage; @@ -36,25 +35,19 @@ import org.junit.Test; import org.junit.runner.RunWith; @RunWith(BMUnitRunner.class) -public class OrphanedConsumerTest extends ActiveMQTestBase -{ +public class OrphanedConsumerTest extends ActiveMQTestBase { private static boolean conditionActive = true; - public static final boolean isConditionActive() - { + public static final boolean isConditionActive() { return conditionActive; } - - public static final void setConditionActive(boolean _conditionActive) - { + public static final void setConditionActive(boolean _conditionActive) { conditionActive = _conditionActive; } - - public static void throwException() throws Exception - { + public static void throwException() throws Exception { throw new InterruptedException("nice.. I interrupted this!"); } @@ -72,25 +65,20 @@ public class OrphanedConsumerTest extends ActiveMQTestBase /** * This static method is an entry point for the byteman rules on {@link #testOrphanedConsumers()} - * */ - public static void leavingCloseOnTestCountersWhileClosing() - { - if (staticServer.getConnectionCount() == 0) - { + */ + public static void leavingCloseOnTestCountersWhileClosing() { + if (staticServer.getConnectionCount() == 0) { verification = new AssertionError("The connection was closed before the consumers and sessions, this may cause issues on management leaving Orphaned Consumers!"); } - if (staticServer.getSessions().size() == 0) - { + if (staticServer.getSessions().size() == 0) { verification = new AssertionError("The session was closed before the consumers, this may cause issues on management leaving Orphaned Consumers!"); } } - @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); setConditionActive(true); /** I'm using the internal method here because closing @@ -99,102 +87,76 @@ public class OrphanedConsumerTest extends ActiveMQTestBase locator = internalCreateNonHALocator(true); } - @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { super.tearDown(); setConditionActive(false); staticServer = null; } - /** * This is like being two tests in one: * I - validating that any exception during the close wouldn't stop connection from being closed * II - validating that the connection is only removed at the end of the process and you wouldn't see - * inconsistencies on management + * inconsistencies on management + * * @throws Exception */ @Test - @BMRules - ( - rules = - { - @BMRule - ( - name = "closeExit", - targetClass = "org.apache.activemq.artemis.core.server.impl.ServerConsumerImpl", - targetMethod = "close", - targetLocation = "AT EXIT", - condition = "org.apache.activemq.artemis.tests.extras.byteman.OrphanedConsumerTest.isConditionActive()", - action = "System.out.println(\"throwing stuff\");throw new InterruptedException()" - ), - @BMRule - ( - name = "closeEnter", - targetClass = "org.apache.activemq.artemis.core.server.impl.ServerConsumerImpl", - targetMethod = "close", - targetLocation = "ENTRY", - condition = "org.apache.activemq.artemis.tests.extras.byteman.OrphanedConsumerTest.isConditionActive()", - action = "org.apache.activemq.artemis.tests.extras.byteman.OrphanedConsumerTest.leavingCloseOnTestCountersWhileClosing()" - ) - - } - ) - public void testOrphanedConsumers() throws Exception - { + @BMRules( + rules = {@BMRule( + name = "closeExit", + targetClass = "org.apache.activemq.artemis.core.server.impl.ServerConsumerImpl", + targetMethod = "close", + targetLocation = "AT EXIT", + condition = "org.apache.activemq.artemis.tests.extras.byteman.OrphanedConsumerTest.isConditionActive()", + action = "System.out.println(\"throwing stuff\");throw new InterruptedException()"), @BMRule( + name = "closeEnter", + targetClass = "org.apache.activemq.artemis.core.server.impl.ServerConsumerImpl", + targetMethod = "close", + targetLocation = "ENTRY", + condition = "org.apache.activemq.artemis.tests.extras.byteman.OrphanedConsumerTest.isConditionActive()", + action = "org.apache.activemq.artemis.tests.extras.byteman.OrphanedConsumerTest.leavingCloseOnTestCountersWhileClosing()") + }) + public void testOrphanedConsumers() throws Exception { internalTestOrphanedConsumers(false); } - /** * This is like being two tests in one: * I - validating that any exception during the close wouldn't stop connection from being closed * II - validating that the connection is only removed at the end of the process and you wouldn't see - * inconsistencies on management + * inconsistencies on management + * * @throws Exception */ @Test - @BMRules - ( - rules = - { - @BMRule - ( - name = "closeExit", - targetClass = "org.apache.activemq.artemis.core.server.impl.ServerConsumerImpl", - targetMethod = "close", - targetLocation = "AT EXIT", - condition = "org.apache.activemq.artemis.tests.extras.byteman.OrphanedConsumerTest.isConditionActive()", - action = "System.out.println(\"throwing stuff\");throw new InterruptedException()" - ), - @BMRule - ( - name = "closeEnter", - targetClass = "org.apache.activemq.artemis.core.server.impl.ServerConsumerImpl", - targetMethod = "close", - targetLocation = "ENTRY", - condition = "org.apache.activemq.artemis.tests.extras.byteman.OrphanedConsumerTest.isConditionActive()", - action = "org.apache.activemq.artemis.tests.extras.byteman.OrphanedConsumerTest.leavingCloseOnTestCountersWhileClosing()" - ) - - } - ) - public void testOrphanedConsumersByManagement() throws Exception - { + @BMRules( + rules = {@BMRule( + name = "closeExit", + targetClass = "org.apache.activemq.artemis.core.server.impl.ServerConsumerImpl", + targetMethod = "close", + targetLocation = "AT EXIT", + condition = "org.apache.activemq.artemis.tests.extras.byteman.OrphanedConsumerTest.isConditionActive()", + action = "System.out.println(\"throwing stuff\");throw new InterruptedException()"), @BMRule( + name = "closeEnter", + targetClass = "org.apache.activemq.artemis.core.server.impl.ServerConsumerImpl", + targetMethod = "close", + targetLocation = "ENTRY", + condition = "org.apache.activemq.artemis.tests.extras.byteman.OrphanedConsumerTest.isConditionActive()", + action = "org.apache.activemq.artemis.tests.extras.byteman.OrphanedConsumerTest.leavingCloseOnTestCountersWhileClosing()") + }) + public void testOrphanedConsumersByManagement() throws Exception { internalTestOrphanedConsumers(true); } /** - * * @param useManagement true = it will use a management operation to make the connection failure, false through ping * @throws Exception */ - private void internalTestOrphanedConsumers(boolean useManagement) throws Exception - { + private void internalTestOrphanedConsumers(boolean useManagement) throws Exception { final int NUMBER_OF_MESSAGES = 2; server = createServer(true, true); server.start(); @@ -203,15 +165,9 @@ public class OrphanedConsumerTest extends ActiveMQTestBase // We are not interested on consumer-window-size on this test // We want that every message is delivered // as we asserting for number of consumers available and round-robin on delivery - locator.setConsumerWindowSize(-1) - .setBlockOnNonDurableSend(false) - .setBlockOnDurableSend(false) - .setBlockOnAcknowledge(true) - .setConnectionTTL(1000) - .setClientFailureCheckPeriod(100) - .setReconnectAttempts(0); + locator.setConsumerWindowSize(-1).setBlockOnNonDurableSend(false).setBlockOnDurableSend(false).setBlockOnAcknowledge(true).setConnectionTTL(1000).setClientFailureCheckPeriod(100).setReconnectAttempts(0); - ClientSessionFactoryImpl sf = (ClientSessionFactoryImpl)createSessionFactory(locator); + ClientSessionFactoryImpl sf = (ClientSessionFactoryImpl) createSessionFactory(locator); ClientSession session = sf.createSession(true, true, 0); @@ -223,33 +179,27 @@ public class OrphanedConsumerTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer("queue1"); ClientConsumer consumer2 = session.createConsumer("queue2"); - Queue queue1 = server.locateQueue(new SimpleString("queue1")); Queue queue2 = server.locateQueue(new SimpleString("queue2")); session.start(); - - if (!useManagement) - { + if (!useManagement) { sf.stopPingingAfterOne(); - for (long timeout = System.currentTimeMillis() + 6000; timeout > System.currentTimeMillis() && server.getConnectionCount() != 0; ) - { + for (long timeout = System.currentTimeMillis() + 6000; timeout > System.currentTimeMillis() && server.getConnectionCount() != 0; ) { Thread.sleep(100); } // an extra second to avoid races of something closing the session while we are asserting it Thread.sleep(1000); } - else - { + else { server.getActiveMQServerControl().closeConnectionsForAddress("127.0.0.1"); } - if (verification != null) - { + if (verification != null) { throw verification; } @@ -258,24 +208,16 @@ public class OrphanedConsumerTest extends ActiveMQTestBase setConditionActive(false); - locator = internalCreateNonHALocator(true) - .setBlockOnNonDurableSend(false) - .setBlockOnDurableSend(false) - .setBlockOnAcknowledge(true) - .setReconnectAttempts(0) - .setConsumerWindowSize(-1); + locator = internalCreateNonHALocator(true).setBlockOnNonDurableSend(false).setBlockOnDurableSend(false).setBlockOnAcknowledge(true).setReconnectAttempts(0).setConsumerWindowSize(-1); - sf = (ClientSessionFactoryImpl)locator.createSessionFactory(); + sf = (ClientSessionFactoryImpl) locator.createSessionFactory(); session = sf.createSession(true, true, 0); - session.start(); - prod = session.createProducer("queue"); - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { ClientMessage message = session.createMessage(true); message.putIntProperty("i", i); prod.send(message); @@ -284,8 +226,7 @@ public class OrphanedConsumerTest extends ActiveMQTestBase consumer = session.createConsumer("queue1"); consumer2 = session.createConsumer("queue2"); - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { assertNotNull(consumer.receive(5000)); assertNotNull(consumer2.receive(5000)); } @@ -293,5 +234,4 @@ public class OrphanedConsumerTest extends ActiveMQTestBase session.close(); } - } \ No newline at end of file diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/PagingLeakTest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/PagingLeakTest.java index c5d7a13680..518bcd91be 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/PagingLeakTest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/PagingLeakTest.java @@ -43,64 +43,47 @@ import org.junit.Test; import org.junit.runner.RunWith; @RunWith(BMUnitRunner.class) -public class PagingLeakTest extends ActiveMQTestBase -{ +public class PagingLeakTest extends ActiveMQTestBase { private static final AtomicInteger pagePosInstances = new AtomicInteger(0); - public static void newPosition() - { + public static void newPosition() { pagePosInstances.incrementAndGet(); } - public static void deletePosition() - { + public static void deletePosition() { pagePosInstances.decrementAndGet(); } @Before - public void setup() - { + public void setup() { pagePosInstances.set(0); } @Test - @BMRules - ( - rules = - { - @BMRule - ( - name = "newPosition", - targetClass = "org.apache.activemq.artemis.core.paging.cursor.impl.PagePositionImpl", - targetMethod = "()", - targetLocation = "ENTRY", - action = "org.apache.activemq.artemis.tests.extras.byteman.PagingLeakTest.newPosition()" - ), - @BMRule - ( - name = "finalPosition", - targetClass = "org.apache.activemq.artemis.core.paging.cursor.impl.PagePositionImpl", - targetMethod = "finalize", - targetLocation = "ENTRY", - action = "org.apache.activemq.artemis.tests.extras.byteman.PagingLeakTest.deletePosition()" - ) - } - ) - public void testValidateLeak() throws Throwable - { + @BMRules( + rules = {@BMRule( + name = "newPosition", + targetClass = "org.apache.activemq.artemis.core.paging.cursor.impl.PagePositionImpl", + targetMethod = "()", + targetLocation = "ENTRY", + action = "org.apache.activemq.artemis.tests.extras.byteman.PagingLeakTest.newPosition()"), @BMRule( + name = "finalPosition", + targetClass = "org.apache.activemq.artemis.core.paging.cursor.impl.PagePositionImpl", + targetMethod = "finalize", + targetLocation = "ENTRY", + action = "org.apache.activemq.artemis.tests.extras.byteman.PagingLeakTest.deletePosition()")}) + public void testValidateLeak() throws Throwable { System.out.println("location::" + getBindingsDir()); List positions = new ArrayList(); - for (int i = 0; i < 300; i++) - { + for (int i = 0; i < 300; i++) { positions.add(new PagePositionImpl(3, 3)); } long timeout = System.currentTimeMillis() + 5000; - while (pagePosInstances.get() != 300 && timeout > System.currentTimeMillis()) - { + while (pagePosInstances.get() != 300 && timeout > System.currentTimeMillis()) { forceGC(); } @@ -110,8 +93,7 @@ public class PagingLeakTest extends ActiveMQTestBase positions.clear(); timeout = System.currentTimeMillis() + 5000; - while (pagePosInstances.get() != 0 && timeout > System.currentTimeMillis()) - { + while (pagePosInstances.get() != 0 && timeout > System.currentTimeMillis()) { forceGC(); } @@ -128,17 +110,14 @@ public class PagingLeakTest extends ActiveMQTestBase server.start(); - AddressSettings settings = new AddressSettings() - .setPageSizeBytes(2 * 1024) - .setMaxSizeBytes(20 * 1024) - .setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE); + AddressSettings settings = new AddressSettings().setPageSizeBytes(2 * 1024).setMaxSizeBytes(20 * 1024).setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE); server.getAddressSettingsRepository().addMatch("#", settings); final SimpleString address = new SimpleString("pgdAddress"); - class Consumer extends Thread - { + class Consumer extends Thread { + final ServerLocator locator; final ClientSessionFactory sf; final ClientSession session; @@ -147,8 +126,7 @@ public class PagingLeakTest extends ActiveMQTestBase final int sleepTime; final int maxConsumed; - Consumer(int sleepTime, String suffix, int maxConsumed) throws Exception - { + Consumer(int sleepTime, String suffix, int maxConsumed) throws Exception { server.createQueue(address, address.concat(suffix), null, true, false); this.sleepTime = sleepTime; @@ -160,48 +138,39 @@ public class PagingLeakTest extends ActiveMQTestBase this.maxConsumed = maxConsumed; } - public void run() - { - try - { + public void run() { + try { session.start(); long lastTime = System.currentTimeMillis(); - for (long i = 0; i < maxConsumed; i++) - { + for (long i = 0; i < maxConsumed; i++) { ClientMessage msg = consumer.receive(5000); - if (msg == null) - { + if (msg == null) { errors.add(new Exception("didn't receive a message")); return; } msg.acknowledge(); - - if (sleepTime > 0) - { + if (sleepTime > 0) { Thread.sleep(sleepTime); } - if (i % 1000 == 0) - { + if (i % 1000 == 0) { System.out.println("Consumed " + i + " events in " + (System.currentTimeMillis() - lastTime)); lastTime = System.currentTimeMillis(); } } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } } - int numberOfMessages = 500; Consumer consumer1 = new Consumer(10, "-1", 150); @@ -212,25 +181,20 @@ public class PagingLeakTest extends ActiveMQTestBase final ClientSession session = sf.createSession(true, true); final ClientProducer producer = session.createProducer(address); - byte[] b = new byte[1024]; - - for (long i = 0; i < numberOfMessages; i++) - { + for (long i = 0; i < numberOfMessages; i++) { ClientMessage msg = session.createMessage(true); msg.getBodyBuffer().writeBytes(b); producer.send(msg); - if (i == 100) - { + if (i == 100) { System.out.println("Starting consumers!!!"); consumer1.start(); consumer2.start(); } - if (i % 250 == 0) - { + if (i % 250 == 0) { validateInstances(); } @@ -244,25 +208,21 @@ public class PagingLeakTest extends ActiveMQTestBase validateInstances(); Throwable elast = null; - for (Throwable e : errors) - { + for (Throwable e : errors) { e.printStackTrace(); elast = e; } - if (elast != null) - { + if (elast != null) { throw elast; } } - private void validateInstances() - { + private void validateInstances() { forceGC(); int count2 = pagePosInstances.get(); Assert.assertTrue("There is a leak, you shouldn't have this many instances (" + count2 + ")", count2 < 5000); } - } diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ReplicationBackupTest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ReplicationBackupTest.java index 802f967235..248204fce0 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ReplicationBackupTest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ReplicationBackupTest.java @@ -31,8 +31,8 @@ import org.junit.runner.RunWith; import java.util.concurrent.CountDownLatch; @RunWith(BMUnitRunner.class) -public class ReplicationBackupTest extends ActiveMQTestBase -{ +public class ReplicationBackupTest extends ActiveMQTestBase { + private static final CountDownLatch ruleFired = new CountDownLatch(1); private ActiveMQServer backupServer; private ActiveMQServer liveServer; @@ -42,32 +42,20 @@ public class ReplicationBackupTest extends ActiveMQTestBase * state != STARTED */ @Test - @BMRules - ( - rules = - { - @BMRule - ( - name = "prevent backup annoucement", - targetClass = "org.apache.activemq.artemis.core.server.impl.SharedNothingLiveActivation", - targetMethod = "run", - targetLocation = "AT EXIT", - action = "org.apache.activemq.artemis.tests.extras.byteman.ReplicationBackupTest.breakIt();" - ) - } - ) - public void testReplicatedBackupAnnouncement() throws Exception - { + @BMRules( + rules = {@BMRule( + name = "prevent backup annoucement", + targetClass = "org.apache.activemq.artemis.core.server.impl.SharedNothingLiveActivation", + targetMethod = "run", + targetLocation = "AT EXIT", + action = "org.apache.activemq.artemis.tests.extras.byteman.ReplicationBackupTest.breakIt();")}) + public void testReplicatedBackupAnnouncement() throws Exception { TransportConfiguration liveConnector = TransportConfigurationUtils.getNettyConnector(true, 0); TransportConfiguration liveAcceptor = TransportConfigurationUtils.getNettyAcceptor(true, 0); TransportConfiguration backupConnector = TransportConfigurationUtils.getNettyConnector(false, 0); TransportConfiguration backupAcceptor = TransportConfigurationUtils.getNettyAcceptor(false, 0); - Configuration backupConfig = createDefaultInVMConfig() - .setBindingsDirectory(getBindingsDir(0, true)) - .setJournalDirectory(getJournalDir(0, true)) - .setPagingDirectory(getPageDir(0, true)) - .setLargeMessagesDirectory(getLargeMessagesDir(0, true)); + Configuration backupConfig = createDefaultInVMConfig().setBindingsDirectory(getBindingsDir(0, true)).setJournalDirectory(getJournalDir(0, true)).setPagingDirectory(getPageDir(0, true)).setLargeMessagesDirectory(getLargeMessagesDir(0, true)); Configuration liveConfig = createDefaultInVMConfig(); @@ -76,17 +64,13 @@ public class ReplicationBackupTest extends ActiveMQTestBase liveServer = createServer(liveConfig); // start the live server in a new thread so we can start the backup simultaneously to induce a potential race - Thread startThread = new Thread(new Runnable() - { + Thread startThread = new Thread(new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { liveServer.start(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -100,18 +84,15 @@ public class ReplicationBackupTest extends ActiveMQTestBase ActiveMQTestBase.waitForRemoteBackup(null, 3, true, backupServer); } - public static void breakIt() - { + public static void breakIt() { ruleFired.countDown(); - try - { + try { /* before the fix this sleep would put the "live" server into a state where the acceptors were started * but the server's state != STARTED which would cause the backup to fail to announce */ Thread.sleep(2000); } - catch (InterruptedException e) - { + catch (InterruptedException e) { e.printStackTrace(); } } diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ScaleDownFailoverTest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ScaleDownFailoverTest.java index 5358baef37..7b672b83d6 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ScaleDownFailoverTest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ScaleDownFailoverTest.java @@ -32,15 +32,14 @@ import org.junit.Test; import org.junit.runner.RunWith; @RunWith(BMUnitRunner.class) -public class ScaleDownFailoverTest extends ClusterTestBase -{ +public class ScaleDownFailoverTest extends ClusterTestBase { + protected static int stopCount = 0; private static ActiveMQServer[] staticServers; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); stopCount = 0; setupLiveServer(0, isFileStorage(), false, isNetty(), true); @@ -54,8 +53,7 @@ public class ScaleDownFailoverTest extends ClusterTestBase ((LiveOnlyPolicyConfiguration) servers[0].getConfiguration().getHAPolicyConfiguration()).setScaleDownConfiguration(scaleDownConfiguration); ((LiveOnlyPolicyConfiguration) servers[1].getConfiguration().getHAPolicyConfiguration()).setScaleDownConfiguration(scaleDownConfiguration2); ((LiveOnlyPolicyConfiguration) servers[2].getConfiguration().getHAPolicyConfiguration()).setScaleDownConfiguration(scaleDownConfiguration3); - if (isGrouped()) - { + if (isGrouped()) { scaleDownConfiguration.setGroupName("bill"); scaleDownConfiguration2.setGroupName("bill"); scaleDownConfiguration3.setGroupName("bill"); @@ -74,29 +72,23 @@ public class ScaleDownFailoverTest extends ClusterTestBase setupSessionFactory(2, isNetty()); } - protected boolean isNetty() - { + protected boolean isNetty() { return true; } - protected boolean isGrouped() - { + protected boolean isGrouped() { return false; } - @Test - @BMRule - ( - name = "blow-up", - targetClass = "org.apache.activemq.artemis.api.core.client.ServerLocator", - targetMethod = "createSessionFactory(org.apache.activemq.artemis.api.core.TransportConfiguration, int, boolean)", - isInterface = true, - targetLocation = "ENTRY", - action = "org.apache.activemq.artemis.tests.extras.byteman.ScaleDownFailoverTest.fail($1);" - ) - public void testScaleDownWhenFirstServerFails() throws Exception - { + @BMRule( + name = "blow-up", + targetClass = "org.apache.activemq.artemis.api.core.client.ServerLocator", + targetMethod = "createSessionFactory(org.apache.activemq.artemis.api.core.TransportConfiguration, int, boolean)", + isInterface = true, + targetLocation = "ENTRY", + action = "org.apache.activemq.artemis.tests.extras.byteman.ScaleDownFailoverTest.fail($1);") + public void testScaleDownWhenFirstServerFails() throws Exception { final int TEST_SIZE = 2; final String addressName = "testAddress"; final String queueName1 = "testQueue1"; @@ -157,21 +149,14 @@ public class ScaleDownFailoverTest extends ClusterTestBase removeConsumer(0); } - public static void fail(TransportConfiguration tc) - { + public static void fail(TransportConfiguration tc) { // only kill one server - if (stopCount == 0) - { - try - { - for (ActiveMQServer activeMQServer : staticServers) - { - if (activeMQServer != null) - { - for (TransportConfiguration transportConfiguration : activeMQServer.getConfiguration().getAcceptorConfigurations()) - { - if (transportConfiguration.getParams().get(TransportConstants.PORT_PROP_NAME).equals(tc.getParams().get(TransportConstants.PORT_PROP_NAME))) - { + if (stopCount == 0) { + try { + for (ActiveMQServer activeMQServer : staticServers) { + if (activeMQServer != null) { + for (TransportConfiguration transportConfiguration : activeMQServer.getConfiguration().getAcceptorConfigurations()) { + if (transportConfiguration.getParams().get(TransportConstants.PORT_PROP_NAME).equals(tc.getParams().get(TransportConstants.PORT_PROP_NAME))) { activeMQServer.stop(); stopCount++; System.out.println("Stopping server listening at: " + tc.getParams().get(TransportConstants.PORT_PROP_NAME)); @@ -180,8 +165,7 @@ public class ScaleDownFailoverTest extends ClusterTestBase } } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ScaleDownFailureTest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ScaleDownFailureTest.java index 5c64aa5947..e592b16371 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ScaleDownFailureTest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ScaleDownFailureTest.java @@ -29,17 +29,15 @@ import org.junit.Test; import org.junit.runner.RunWith; @RunWith(BMUnitRunner.class) -public class ScaleDownFailureTest extends ClusterTestBase -{ +public class ScaleDownFailureTest extends ClusterTestBase { + @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); setupLiveServer(0, isFileStorage(), false, isNetty(), true); setupLiveServer(1, isFileStorage(), false, isNetty(), true); - if (isGrouped()) - { + if (isGrouped()) { ScaleDownConfiguration scaleDownConfiguration = new ScaleDownConfiguration(); scaleDownConfiguration.setGroupName("bill"); ((LiveOnlyPolicyConfiguration) servers[0].getConfiguration().getHAPolicyConfiguration()).setScaleDownConfiguration(scaleDownConfiguration); @@ -52,28 +50,23 @@ public class ScaleDownFailureTest extends ClusterTestBase setupSessionFactory(1, isNetty()); } - protected boolean isNetty() - { + protected boolean isNetty() { return true; } - protected boolean isGrouped() - { + protected boolean isGrouped() { return false; } @Test - @BMRule - ( - name = "blow-up", - targetClass = "org.apache.activemq.artemis.api.core.client.ServerLocator", - targetMethod = "createSessionFactory(org.apache.activemq.artemis.api.core.TransportConfiguration, int, boolean)", - isInterface = true, - targetLocation = "ENTRY", - action = "throw new Exception()" - ) - public void testScaleDownWhenRemoteServerIsUnavailable() throws Exception - { + @BMRule( + name = "blow-up", + targetClass = "org.apache.activemq.artemis.api.core.client.ServerLocator", + targetMethod = "createSessionFactory(org.apache.activemq.artemis.api.core.TransportConfiguration, int, boolean)", + isInterface = true, + targetLocation = "ENTRY", + action = "throw new Exception()") + public void testScaleDownWhenRemoteServerIsUnavailable() throws Exception { final int TEST_SIZE = 1; final String addressName = "testAddress"; final String queueName1 = "testQueue1"; diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ScaleDownGroupedFailoverTest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ScaleDownGroupedFailoverTest.java index 190e763f1c..d7521cbb80 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ScaleDownGroupedFailoverTest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ScaleDownGroupedFailoverTest.java @@ -16,10 +16,9 @@ */ package org.apache.activemq.artemis.tests.extras.byteman; -public class ScaleDownGroupedFailoverTest extends ScaleDownFailoverTest -{ - protected boolean isGrouped() - { +public class ScaleDownGroupedFailoverTest extends ScaleDownFailoverTest { + + protected boolean isGrouped() { return true; } } diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ScaleDownGroupedFailureTest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ScaleDownGroupedFailureTest.java index e63cf98e95..a136eaced7 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ScaleDownGroupedFailureTest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/ScaleDownGroupedFailureTest.java @@ -16,10 +16,9 @@ */ package org.apache.activemq.artemis.tests.extras.byteman; -public class ScaleDownGroupedFailureTest extends ScaleDownFailureTest -{ - protected boolean isGrouped() - { +public class ScaleDownGroupedFailureTest extends ScaleDownFailureTest { + + protected boolean isGrouped() { return true; } } diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/StartStopDeadlockTest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/StartStopDeadlockTest.java index e852d0f05c..d7d5db6722 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/StartStopDeadlockTest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/StartStopDeadlockTest.java @@ -38,55 +38,40 @@ import java.util.concurrent.atomic.AtomicInteger; * This test validates a deadlock identified by https://bugzilla.redhat.com/show_bug.cgi?id=959616 */ @RunWith(BMUnitRunner.class) -public class StartStopDeadlockTest extends ActiveMQTestBase -{ +public class StartStopDeadlockTest extends ActiveMQTestBase { + /* * simple test to make sure connect still works with some network latency built into netty * */ @Test - @BMRules - ( + @BMRules( - rules = - { - @BMRule - ( - name = "Server.start wait-init", - targetClass = "org.apache.activemq.artemis.core.server.impl.ActiveMQServerImpl", - targetMethod = "initialisePart2", - targetLocation = "ENTRY", - condition = "incrementCounter(\"server-Init\") == 2", - action = "System.out.println(\"server backup init\"), waitFor(\"start-init\")" - ), - @BMRule( - name = "JMSServer.stop wait-init", - targetClass = "org.apache.activemq.artemis.jms.server.impl.JMSServerManagerImpl", - targetMethod = "stop", - targetLocation = "ENTRY", - action = "signalWake(\"start-init\", true)" - ), - @BMRule( - name = "StartStopDeadlockTest tearDown", - targetClass = "org.apache.activemq.artemis.tests.extras.byteman.StartStopDeadlockTest", - targetMethod = "tearDown", - targetLocation = "ENTRY", - action = "deleteCounter(\"server-Init\")" - ) - } - ) - public void testDeadlock() throws Exception - { + rules = {@BMRule( + name = "Server.start wait-init", + targetClass = "org.apache.activemq.artemis.core.server.impl.ActiveMQServerImpl", + targetMethod = "initialisePart2", + targetLocation = "ENTRY", + condition = "incrementCounter(\"server-Init\") == 2", + action = "System.out.println(\"server backup init\"), waitFor(\"start-init\")"), @BMRule( + name = "JMSServer.stop wait-init", + targetClass = "org.apache.activemq.artemis.jms.server.impl.JMSServerManagerImpl", + targetMethod = "stop", + targetLocation = "ENTRY", + action = "signalWake(\"start-init\", true)"), @BMRule( + name = "StartStopDeadlockTest tearDown", + targetClass = "org.apache.activemq.artemis.tests.extras.byteman.StartStopDeadlockTest", + targetMethod = "tearDown", + targetLocation = "ENTRY", + action = "deleteCounter(\"server-Init\")")}) + public void testDeadlock() throws Exception { // A live server that will always be crashed - Configuration confLive = createDefaultNettyConfig() - .setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration()); + Configuration confLive = createDefaultNettyConfig().setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration()); final ActiveMQServer serverLive = addServer(ActiveMQServers.newActiveMQServer(confLive)); serverLive.start(); - // A backup that will be waiting to be activated - Configuration config = createDefaultNettyConfig() - .setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration()); + Configuration config = createDefaultNettyConfig().setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration()); final ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, true)); @@ -100,40 +85,31 @@ public class StartStopDeadlockTest extends ActiveMQTestBase final CountDownLatch align = new CountDownLatch(2); final CountDownLatch startLatch = new CountDownLatch(1); - - Thread tCrasher = new Thread("tStart") - { + Thread tCrasher = new Thread("tStart") { @Override - public void run() - { - try - { + public void run() { + try { align.countDown(); startLatch.await(); System.out.println("Crashing...."); serverLive.stop(true); } - catch (Exception e) - { + catch (Exception e) { errors.incrementAndGet(); e.printStackTrace(); } } }; - Thread tStop = new Thread("tStop") - { + Thread tStop = new Thread("tStop") { @Override - public void run() - { - try - { + public void run() { + try { align.countDown(); startLatch.await(); jmsServer.stop(); } - catch (Exception e) - { + catch (Exception e) { errors.incrementAndGet(); e.printStackTrace(); } diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/StompInternalStateTest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/StompInternalStateTest.java index fd0b0464b8..aca3059790 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/StompInternalStateTest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/byteman/StompInternalStateTest.java @@ -40,8 +40,8 @@ import org.junit.Test; import org.junit.runner.RunWith; @RunWith(BMUnitRunner.class) -public class StompInternalStateTest extends ActiveMQTestBase -{ +public class StompInternalStateTest extends ActiveMQTestBase { + private static final String STOMP_QUEUE_NAME = "jms.queue.StompTestQueue"; private String resultTestStompProtocolManagerLeak = null; @@ -49,26 +49,17 @@ public class StompInternalStateTest extends ActiveMQTestBase protected ActiveMQServer server = null; @Test - @BMRules - ( - rules = - { - @BMRule - ( - name = "StompProtocolManager Leak Server Rule", - targetClass = "org.apache.activemq.artemis.core.protocol.stomp.StompProtocolManager", - targetMethod = "onNotification(org.apache.activemq.artemis.core.server.management.Notification)", - targetLocation = "EXIT", - helper = "org.apache.activemq.artemis.tests.extras.byteman.StompInternalStateTest", - action = "verifyBindingAddRemove($1, $0.destinations)" - ) - } - ) - public void testStompProtocolManagerLeak() throws Exception - { + @BMRules( + rules = {@BMRule( + name = "StompProtocolManager Leak Server Rule", + targetClass = "org.apache.activemq.artemis.core.protocol.stomp.StompProtocolManager", + targetMethod = "onNotification(org.apache.activemq.artemis.core.server.management.Notification)", + targetLocation = "EXIT", + helper = "org.apache.activemq.artemis.tests.extras.byteman.StompInternalStateTest", + action = "verifyBindingAddRemove($1, $0.destinations)")}) + public void testStompProtocolManagerLeak() throws Exception { ClientSession session = null; - try - { + try { assertNull(resultTestStompProtocolManagerLeak); ServerLocator locator = createNettyNonHALocator(); ClientSessionFactory factory = createSessionFactory(locator); @@ -78,46 +69,36 @@ public class StompInternalStateTest extends ActiveMQTestBase assertNull(resultTestStompProtocolManagerLeak); } - finally - { - if (session != null) - { + finally { + if (session != null) { session.close(); } } } @Override - protected Configuration createDefaultConfig(final boolean netty) throws Exception - { + protected Configuration createDefaultConfig(final boolean netty) throws Exception { Map params = new HashMap<>(); params.put(TransportConstants.PROTOCOLS_PROP_NAME, StompProtocolManagerFactory.STOMP_PROTOCOL_NAME); params.put(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_STOMP_PORT); params.put(TransportConstants.STOMP_CONSUMERS_CREDIT, "-1"); TransportConfiguration stompTransport = new TransportConfiguration(NettyAcceptorFactory.class.getName(), params); - Configuration config = super.createDefaultConfig(netty) - .setPersistenceEnabled(false) - .addAcceptorConfiguration(stompTransport); + Configuration config = super.createDefaultConfig(netty).setPersistenceEnabled(false).addAcceptorConfiguration(stompTransport); return config; } @SuppressWarnings("unchecked") - public void verifyBindingAddRemove(Notification noti, Object obj) - { - Set destinations = (Set)obj; - if (noti.getType() == CoreNotificationType.BINDING_ADDED) - { - if (!destinations.contains(STOMP_QUEUE_NAME)) - { + public void verifyBindingAddRemove(Notification noti, Object obj) { + Set destinations = (Set) obj; + if (noti.getType() == CoreNotificationType.BINDING_ADDED) { + if (!destinations.contains(STOMP_QUEUE_NAME)) { resultTestStompProtocolManagerLeak += "didn't save the queue when binding added " + destinations; } } - else if (noti.getType() == CoreNotificationType.BINDING_REMOVED) - { - if (destinations.contains(STOMP_QUEUE_NAME)) - { + else if (noti.getType() == CoreNotificationType.BINDING_REMOVED) { + if (destinations.contains(STOMP_QUEUE_NAME)) { resultTestStompProtocolManagerLeak = "didn't remove the queue when binding removed " + destinations; } } @@ -125,8 +106,7 @@ public class StompInternalStateTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(createDefaultNettyConfig()); server.start(); diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/bridge/BridgeTestBase.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/bridge/BridgeTestBase.java index 0602664251..dead469218 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/bridge/BridgeTestBase.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/bridge/BridgeTestBase.java @@ -65,8 +65,8 @@ import org.junit.After; import org.junit.Assert; import org.junit.Before; -public abstract class BridgeTestBase extends ActiveMQTestBase -{ +public abstract class BridgeTestBase extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; protected ConnectionFactoryFactory cff0, cff1; @@ -104,15 +104,11 @@ public abstract class BridgeTestBase extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); // Start the servers - Configuration conf0 = createBasicConfig() - .setJournalDirectory(getJournalDir(0, false)) - .setBindingsDirectory(getBindingsDir(0, false)) - .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY)); + Configuration conf0 = createBasicConfig().setJournalDirectory(getJournalDir(0, false)).setBindingsDirectory(getBindingsDir(0, false)).addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY)); server0 = addServer(ActiveMQServers.newActiveMQServer(conf0, false)); @@ -124,10 +120,7 @@ public abstract class BridgeTestBase extends ActiveMQTestBase params1 = new HashMap(); params1.put(TransportConstants.SERVER_ID_PROP_NAME, 1); - Configuration conf1 = createBasicConfig() - .setJournalDirectory(getJournalDir(1, false)) - .setBindingsDirectory(getBindingsDir(1, false)) - .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, params1)); + Configuration conf1 = createBasicConfig().setJournalDirectory(getJournalDir(1, false)).setBindingsDirectory(getBindingsDir(1, false)).addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, params1)); server1 = addServer(ActiveMQServers.newActiveMQServer(conf1, false)); @@ -153,21 +146,17 @@ public abstract class BridgeTestBase extends ActiveMQTestBase } - protected void createQueue(final String queueName, final int index) throws Exception - { + protected void createQueue(final String queueName, final int index) throws Exception { JMSServerManager server = jmsServer0; - if (index == 1) - { + if (index == 1) { server = jmsServer1; } - assertTrue("queue '/queue/" + queueName + "' created", - server.createQueue(false, queueName, null, true, "/queue/" + queueName)); + assertTrue("queue '/queue/" + queueName + "' created", server.createQueue(false, queueName, null, true, "/queue/" + queueName)); } @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { checkEmpty(sourceQueue, 0); checkEmpty(localTargetQueue, 0); checkEmpty(targetQueue, 1); @@ -175,12 +164,10 @@ public abstract class BridgeTestBase extends ActiveMQTestBase // Check no subscriptions left lying around checkNoSubscriptions(sourceTopic, 0); - if (cff0 instanceof ActiveMQConnectionFactory) - { + if (cff0 instanceof ActiveMQConnectionFactory) { ((ActiveMQConnectionFactory) cff0).close(); } - if (cff1 instanceof ActiveMQConnectionFactory) - { + if (cff1 instanceof ActiveMQConnectionFactory) { ((ActiveMQConnectionFactory) cff1).close(); } stopComponent(jmsServer0); @@ -219,16 +206,10 @@ public abstract class BridgeTestBase extends ActiveMQTestBase super.tearDown(); } - - protected void setUpAdministeredObjects() throws Exception - { - cff0LowProducerWindow = new ConnectionFactoryFactory() - { - public ConnectionFactory createConnectionFactory() throws Exception - { - ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, - new TransportConfiguration( - INVM_CONNECTOR_FACTORY)); + protected void setUpAdministeredObjects() throws Exception { + cff0LowProducerWindow = new ConnectionFactoryFactory() { + public ConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); // Note! We disable automatic reconnection on the session factory. The bridge needs to do the reconnection cf.setReconnectAttempts(0); @@ -242,14 +223,9 @@ public abstract class BridgeTestBase extends ActiveMQTestBase }; - - cff0 = new ConnectionFactoryFactory() - { - public ConnectionFactory createConnectionFactory() throws Exception - { - ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, - new TransportConfiguration( - INVM_CONNECTOR_FACTORY)); + cff0 = new ConnectionFactoryFactory() { + public ConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); // Note! We disable automatic reconnection on the session factory. The bridge needs to do the reconnection cf.setReconnectAttempts(0); @@ -262,13 +238,9 @@ public abstract class BridgeTestBase extends ActiveMQTestBase }; - cff0xa = new ConnectionFactoryFactory() - { - public Object createConnectionFactory() throws Exception - { - ActiveMQXAConnectionFactory cf = (ActiveMQXAConnectionFactory) ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.XA_CF, - new TransportConfiguration( - INVM_CONNECTOR_FACTORY)); + cff0xa = new ConnectionFactoryFactory() { + public Object createConnectionFactory() throws Exception { + ActiveMQXAConnectionFactory cf = (ActiveMQXAConnectionFactory) ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.XA_CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); // Note! We disable automatic reconnection on the session factory. The bridge needs to do the reconnection cf.setReconnectAttempts(0); @@ -284,15 +256,10 @@ public abstract class BridgeTestBase extends ActiveMQTestBase cf0 = (ConnectionFactory) cff0.createConnectionFactory(); cf0xa = (XAConnectionFactory) cff0xa.createConnectionFactory(); - cff1 = new ConnectionFactoryFactory() - { + cff1 = new ConnectionFactoryFactory() { - public ConnectionFactory createConnectionFactory() throws Exception - { - ActiveMQJMSConnectionFactory cf = (ActiveMQJMSConnectionFactory) ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, - new TransportConfiguration( - INVM_CONNECTOR_FACTORY, - params1)); + public ConnectionFactory createConnectionFactory() throws Exception { + ActiveMQJMSConnectionFactory cf = (ActiveMQJMSConnectionFactory) ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY, params1)); // Note! We disable automatic reconnection on the session factory. The bridge needs to do the reconnection cf.setReconnectAttempts(0); @@ -304,15 +271,10 @@ public abstract class BridgeTestBase extends ActiveMQTestBase } }; - cff1xa = new ConnectionFactoryFactory() - { + cff1xa = new ConnectionFactoryFactory() { - public XAConnectionFactory createConnectionFactory() throws Exception - { - ActiveMQXAConnectionFactory cf = (ActiveMQXAConnectionFactory) ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.XA_CF, - new TransportConfiguration( - INVM_CONNECTOR_FACTORY, - params1)); + public XAConnectionFactory createConnectionFactory() throws Exception { + ActiveMQXAConnectionFactory cf = (ActiveMQXAConnectionFactory) ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.XA_CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY, params1)); // Note! We disable automatic reconnection on the session factory. The bridge needs to do the reconnection cf.setReconnectAttempts(0); @@ -327,40 +289,32 @@ public abstract class BridgeTestBase extends ActiveMQTestBase cf1 = (ConnectionFactory) cff1.createConnectionFactory(); cf1xa = (XAConnectionFactory) cff1xa.createConnectionFactory(); - sourceQueueFactory = new DestinationFactory() - { - public Destination createDestination() throws Exception - { + sourceQueueFactory = new DestinationFactory() { + public Destination createDestination() throws Exception { return (Destination) context0.lookup("/queue/sourceQueue"); } }; sourceQueue = (Queue) sourceQueueFactory.createDestination(); - targetQueueFactory = new DestinationFactory() - { - public Destination createDestination() throws Exception - { + targetQueueFactory = new DestinationFactory() { + public Destination createDestination() throws Exception { return (Destination) context1.lookup("/queue/targetQueue"); } }; targetQueue = (Queue) targetQueueFactory.createDestination(); - sourceTopicFactory = new DestinationFactory() - { - public Destination createDestination() throws Exception - { + sourceTopicFactory = new DestinationFactory() { + public Destination createDestination() throws Exception { return (Destination) context0.lookup("/topic/sourceTopic"); } }; sourceTopic = (Topic) sourceTopicFactory.createDestination(); - localTargetQueueFactory = new DestinationFactory() - { - public Destination createDestination() throws Exception - { + localTargetQueueFactory = new DestinationFactory() { + public Destination createDestination() throws Exception { return (Destination) context0.lookup("/queue/localTargetQueue"); } }; @@ -373,12 +327,10 @@ public abstract class BridgeTestBase extends ActiveMQTestBase final int start, final int numMessages, final boolean persistent, - final boolean largeMessage) throws Exception - { + final boolean largeMessage) throws Exception { Connection conn = null; - try - { + try { conn = cf.createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -387,27 +339,22 @@ public abstract class BridgeTestBase extends ActiveMQTestBase prod.setDeliveryMode(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT); - for (int i = start; i < start + numMessages; i++) - { - if (largeMessage) - { + for (int i = start; i < start + numMessages; i++) { + if (largeMessage) { BytesMessage msg = sess.createBytesMessage(); ((ActiveMQMessage) msg).setInputStream(ActiveMQTestBase.createFakeLargeStream(1024L * 1024L)); msg.setStringProperty("msg", "message" + i); prod.send(msg); } - else - { + else { TextMessage tm = sess.createTextMessage("message" + i); prod.send(tm); } } } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -418,12 +365,10 @@ public abstract class BridgeTestBase extends ActiveMQTestBase final QualityOfServiceMode qosMode, final int numMessages, final boolean longWaitForFirst, - final boolean largeMessage) throws Exception - { + final boolean largeMessage) throws Exception { Connection conn = null; - try - { + try { conn = cf.createConnection(); conn.start(); @@ -440,29 +385,24 @@ public abstract class BridgeTestBase extends ActiveMQTestBase // We always wait longer for the first one - it may take some time to arrive especially if we are // waiting for recovery to kick in - while (true) - { + while (true) { Message tm = cons.receive(count == 0 ? (longWaitForFirst ? 60000 : 10000) : 5000); - if (tm == null) - { + if (tm == null) { break; } // log.info("Got message " + tm.getText()); - if (largeMessage) - { + if (largeMessage) { BytesMessage bmsg = (BytesMessage) tm; msgs.add(tm.getStringProperty("msg")); byte[] buffRead = new byte[1024]; - for (int i = 0; i < 1024; i++) - { + for (int i = 0; i < 1024; i++) { Assert.assertEquals(1024, bmsg.readBytes(buffRead)); } } - else - { + else { msgs.add(((TextMessage) tm).getText()); } @@ -470,23 +410,19 @@ public abstract class BridgeTestBase extends ActiveMQTestBase } - if (qosMode == QualityOfServiceMode.ONCE_AND_ONLY_ONCE || qosMode == QualityOfServiceMode.DUPLICATES_OK) - { + if (qosMode == QualityOfServiceMode.ONCE_AND_ONLY_ONCE || qosMode == QualityOfServiceMode.DUPLICATES_OK) { // All the messages should be received - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { Assert.assertTrue("quality=" + qosMode + ", #=" + i + ", message=" + msgs, msgs.contains("message" + i)); } // Should be no more - if (qosMode == QualityOfServiceMode.ONCE_AND_ONLY_ONCE) - { + if (qosMode == QualityOfServiceMode.ONCE_AND_ONLY_ONCE) { Assert.assertEquals(numMessages, msgs.size()); } } - else if (qosMode == QualityOfServiceMode.AT_MOST_ONCE) - { + else if (qosMode == QualityOfServiceMode.AT_MOST_ONCE) { // No *guarantee* that any messages will be received // but you still might get some depending on how/where the crash occurred } @@ -494,10 +430,8 @@ public abstract class BridgeTestBase extends ActiveMQTestBase BridgeTestBase.log.trace("Check complete"); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -507,11 +441,9 @@ public abstract class BridgeTestBase extends ActiveMQTestBase final Destination dest, final int start, final int numMessages, - final boolean largeMessage) throws Exception - { + final boolean largeMessage) throws Exception { Connection conn = null; - try - { + try { conn = cf.createConnection(); conn.start(); @@ -522,65 +454,53 @@ public abstract class BridgeTestBase extends ActiveMQTestBase // Consume the messages - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { Message tm = cons.receive(30000); Assert.assertNotNull(tm); - if (largeMessage) - { + if (largeMessage) { BytesMessage bmsg = (BytesMessage) tm; Assert.assertEquals("message" + (i + start), tm.getStringProperty("msg")); byte[] buffRead = new byte[1024]; - for (int j = 0; j < 1024; j++) - { + for (int j = 0; j < 1024; j++) { Assert.assertEquals(1024, bmsg.readBytes(buffRead)); } } - else - { + else { Assert.assertEquals("message" + (i + start), ((TextMessage) tm).getText()); } } } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } - public boolean checkEmpty(final Queue queue, final int index) throws Exception - { + public boolean checkEmpty(final Queue queue, final int index) throws Exception { ManagementService managementService = server0.getManagementService(); - if (index == 1) - { + if (index == 1) { managementService = server1.getManagementService(); } JMSQueueControl queueControl = (JMSQueueControl) managementService.getResource(ResourceNames.JMS_QUEUE + queue.getQueueName()); //server may be closed - if (queueControl != null) - { + if (queueControl != null) { queueControl.flushExecutor(); Long messageCount = queueControl.getMessageCount(); - if (messageCount > 0) - { + if (messageCount > 0) { queueControl.removeMessages(null); } } return true; } - protected void checkNoSubscriptions(final Topic topic, final int index) throws Exception - { + protected void checkNoSubscriptions(final Topic topic, final int index) throws Exception { ManagementService managementService = server0.getManagementService(); - if (index == 1) - { + if (index == 1) { managementService = server1.getManagementService(); } TopicControl topicControl = (TopicControl) managementService.getResource(ResourceNames.JMS_TOPIC + topic.getTopicName()); @@ -588,19 +508,16 @@ public abstract class BridgeTestBase extends ActiveMQTestBase } - protected void removeAllMessages(final String queueName, final int index) throws Exception - { + protected void removeAllMessages(final String queueName, final int index) throws Exception { ManagementService managementService = server0.getManagementService(); - if (index == 1) - { + if (index == 1) { managementService = server1.getManagementService(); } JMSQueueControl queueControl = (JMSQueueControl) managementService.getResource(ResourceNames.JMS_QUEUE + queueName); queueControl.removeMessages(null); } - protected TransactionManager newTransactionManager() - { + protected TransactionManager newTransactionManager() { return new TransactionManagerImple(); } diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/bridge/ClusteredBridgeTestBase.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/bridge/ClusteredBridgeTestBase.java index 8a782ba39c..75c0979109 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/bridge/ClusteredBridgeTestBase.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/bridge/ClusteredBridgeTestBase.java @@ -62,20 +62,18 @@ import org.junit.Before; * This class serves as a base class for jms bridge tests in * clustered scenarios. */ -public abstract class ClusteredBridgeTestBase extends ActiveMQTestBase -{ +public abstract class ClusteredBridgeTestBase extends ActiveMQTestBase { + private static int index = 0; protected Map groups = new HashMap(); @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); Iterator iter = groups.values().iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { iter.next().start(); } TxControl.enable(); @@ -83,11 +81,9 @@ public abstract class ClusteredBridgeTestBase extends ActiveMQTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { Iterator iter = groups.values().iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { iter.next().stop(); } @@ -99,11 +95,9 @@ public abstract class ClusteredBridgeTestBase extends ActiveMQTestBase } //create a live/backup pair. - protected ServerGroup createServerGroup(String name) throws Exception - { + protected ServerGroup createServerGroup(String name) throws Exception { ServerGroup server = groups.get(name); - if (server == null) - { + if (server == null) { server = new ServerGroup(name, groups.size()); server.create(); groups.put(name, server); @@ -112,8 +106,8 @@ public abstract class ClusteredBridgeTestBase extends ActiveMQTestBase } //each ServerGroup represents a live/backup pair - protected class ServerGroup - { + protected class ServerGroup { + private static final int ID_OFFSET = 100; private String name; private int id; @@ -133,19 +127,16 @@ public abstract class ClusteredBridgeTestBase extends ActiveMQTestBase * @param name - name of the group * @param id - id of the live (should be < 100) */ - public ServerGroup(String name, int id) - { + public ServerGroup(String name, int id) { this.name = name; this.id = id; } - public String getName() - { + public String getName() { return name; } - public void create() throws Exception - { + public void create() throws Exception { Map params0 = new HashMap(); params0.put(TransportConstants.SERVER_ID_PROP_NAME, id); liveConnector = new TransportConfiguration(INVM_CONNECTOR_FACTORY, params0, "in-vm-live"); @@ -155,13 +146,7 @@ public abstract class ClusteredBridgeTestBase extends ActiveMQTestBase backupConnector = new TransportConfiguration(INVM_CONNECTOR_FACTORY, params, "in-vm-backup"); //live - Configuration conf0 = createBasicConfig() - .setJournalDirectory(getJournalDir(id, false)) - .setBindingsDirectory(getBindingsDir(id, false)) - .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, params0)) - .addConnectorConfiguration(liveConnector.getName(), liveConnector) - .setHAPolicyConfiguration(new ReplicatedPolicyConfiguration()) - .addClusterConfiguration(basicClusterConnectionConfig(liveConnector.getName())); + Configuration conf0 = createBasicConfig().setJournalDirectory(getJournalDir(id, false)).setBindingsDirectory(getBindingsDir(id, false)).addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, params0)).addConnectorConfiguration(liveConnector.getName(), liveConnector).setHAPolicyConfiguration(new ReplicatedPolicyConfiguration()).addClusterConfiguration(basicClusterConnectionConfig(liveConnector.getName())); ActiveMQServer server0 = addServer(ActiveMQServers.newActiveMQServer(conf0, true)); @@ -170,14 +155,7 @@ public abstract class ClusteredBridgeTestBase extends ActiveMQTestBase liveNode.setRegistry(new JndiBindingRegistry(liveContext)); //backup - Configuration config = createBasicConfig() - .setJournalDirectory(getJournalDir(id, true)) - .setBindingsDirectory(getBindingsDir(id, true)) - .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, params)) - .addConnectorConfiguration(backupConnector.getName(), backupConnector) - .addConnectorConfiguration(liveConnector.getName(), liveConnector) - .setHAPolicyConfiguration(new ReplicaPolicyConfiguration()) - .addClusterConfiguration(basicClusterConnectionConfig(backupConnector.getName(), liveConnector.getName())); + Configuration config = createBasicConfig().setJournalDirectory(getJournalDir(id, true)).setBindingsDirectory(getBindingsDir(id, true)).addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, params)).addConnectorConfiguration(backupConnector.getName(), backupConnector).addConnectorConfiguration(liveConnector.getName(), liveConnector).setHAPolicyConfiguration(new ReplicaPolicyConfiguration()).addClusterConfiguration(basicClusterConnectionConfig(backupConnector.getName(), liveConnector.getName())); ActiveMQServer backup = addServer(ActiveMQServers.newActiveMQServer(config, true)); @@ -187,39 +165,31 @@ public abstract class ClusteredBridgeTestBase extends ActiveMQTestBase backupNode.setRegistry(new JndiBindingRegistry(context)); } - public void start() throws Exception - { + public void start() throws Exception { liveNode.start(); waitForServerToStart(liveNode.getActiveMQServer()); backupNode.start(); waitForRemoteBackupSynchronization(backupNode.getActiveMQServer()); - locator = ActiveMQClient.createServerLocatorWithHA(liveConnector) - .setReconnectAttempts(-1); + locator = ActiveMQClient.createServerLocatorWithHA(liveConnector).setReconnectAttempts(-1); sessionFactory = locator.createSessionFactory(); } - public void stop() throws Exception - { + public void stop() throws Exception { sessionFactory.close(); locator.close(); liveNode.stop(); backupNode.stop(); } - public void createQueue(String queueName) throws Exception - { + public void createQueue(String queueName) throws Exception { liveNode.createQueue(true, queueName, null, true, "/queue/" + queueName); } - public ConnectionFactoryFactory getConnectionFactoryFactory() - { - ConnectionFactoryFactory cff = new ConnectionFactoryFactory() - { - public ConnectionFactory createConnectionFactory() throws Exception - { - ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithHA(JMSFactoryType.XA_CF, - liveConnector); + public ConnectionFactoryFactory getConnectionFactoryFactory() { + ConnectionFactoryFactory cff = new ConnectionFactoryFactory() { + public ConnectionFactory createConnectionFactory() throws Exception { + ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithHA(JMSFactoryType.XA_CF, liveConnector); cf.getServerLocator().setReconnectAttempts(-1); return cf; } @@ -228,25 +198,20 @@ public abstract class ClusteredBridgeTestBase extends ActiveMQTestBase return cff; } - public DestinationFactory getDestinationFactory(final String queueName) - { + public DestinationFactory getDestinationFactory(final String queueName) { - DestinationFactory destFactory = new DestinationFactory() - { - public Destination createDestination() throws Exception - { + DestinationFactory destFactory = new DestinationFactory() { + public Destination createDestination() throws Exception { return (Destination) liveContext.lookup("/queue/" + queueName); } }; return destFactory; } - public void sendMessages(String queueName, int num) throws ActiveMQException - { + public void sendMessages(String queueName, int num) throws ActiveMQException { ClientSession session = sessionFactory.createSession(); ClientProducer producer = session.createProducer("jms.queue." + queueName); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { ClientMessage m = session.createMessage(true); m.putStringProperty("bridge-message", "hello " + index); index++; @@ -255,13 +220,11 @@ public abstract class ClusteredBridgeTestBase extends ActiveMQTestBase session.close(); } - public void receiveMessages(String queueName, int num, boolean checkDup) throws ActiveMQException - { + public void receiveMessages(String queueName, int num, boolean checkDup) throws ActiveMQException { ClientSession session = sessionFactory.createSession(); session.start(); ClientConsumer consumer = session.createConsumer("jms.queue." + queueName); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { ClientMessage m = consumer.receive(30000); assertNotNull("i=" + i, m); assertNotNull(m.getStringProperty("bridge-message")); @@ -269,15 +232,12 @@ public abstract class ClusteredBridgeTestBase extends ActiveMQTestBase } ClientMessage m = consumer.receive(500); - if (checkDup) - { + if (checkDup) { assertNull(m); } - else - { + else { //drain messages - while (m != null) - { + while (m != null) { m = consumer.receive(200); } } @@ -285,17 +245,13 @@ public abstract class ClusteredBridgeTestBase extends ActiveMQTestBase session.close(); } - public void crashLive() throws Exception - { + public void crashLive() throws Exception { final CountDownLatch latch = new CountDownLatch(1); - sessionFactory.addFailoverListener(new FailoverEventListener() - { + sessionFactory.addFailoverListener(new FailoverEventListener() { @Override - public void failoverEvent(FailoverEventType eventType) - { - if (eventType == FailoverEventType.FAILOVER_COMPLETED) - { + public void failoverEvent(FailoverEventType eventType) { + if (eventType == FailoverEventType.FAILOVER_COMPLETED) { latch.countDown(); } } diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/bridge/JMSBridgeClusteredTest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/bridge/JMSBridgeClusteredTest.java index b3d9d25a8b..f3d37dc64a 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/bridge/JMSBridgeClusteredTest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/bridge/JMSBridgeClusteredTest.java @@ -32,8 +32,8 @@ import org.junit.Test; *
    * Tests of jms bridge using HA connection factories. */ -public class JMSBridgeClusteredTest extends ClusteredBridgeTestBase -{ +public class JMSBridgeClusteredTest extends ClusteredBridgeTestBase { + private ServerGroup sourceServer; private ServerGroup targetServer; @@ -42,8 +42,7 @@ public class JMSBridgeClusteredTest extends ClusteredBridgeTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); sourceServer = createServerGroup("source-server"); @@ -57,26 +56,22 @@ public class JMSBridgeClusteredTest extends ClusteredBridgeTestBase } @Test - public void testBridgeOnFailoverXA() throws Exception - { + public void testBridgeOnFailoverXA() throws Exception { performSourceAndTargetCrashAndFailover(QualityOfServiceMode.ONCE_AND_ONLY_ONCE); } @Test - public void testBridgeOnFailoverDupsOk() throws Exception - { + public void testBridgeOnFailoverDupsOk() throws Exception { performSourceAndTargetCrashAndFailover(QualityOfServiceMode.DUPLICATES_OK); } @Test - public void testBridgeOnFailoverAtMostOnce() throws Exception - { + public void testBridgeOnFailoverAtMostOnce() throws Exception { performSourceAndTargetCrashAndFailover(QualityOfServiceMode.AT_MOST_ONCE); } @Test - public void testCrashAndFailoverWithMessagesXA() throws Exception - { + public void testCrashAndFailoverWithMessagesXA() throws Exception { performSourceAndTargetCrashAndFailoverWithMessages(QualityOfServiceMode.ONCE_AND_ONLY_ONCE); } @@ -88,13 +83,11 @@ public class JMSBridgeClusteredTest extends ClusteredBridgeTestBase //this test are valid for ONCE_AND_ONLY_ONCE and AT_MOST_ONCE. //with DUPS_OK the test failed because some messages are delivered again //after failover, which is fine as in this mode duplication is allowed. - public void performSourceAndTargetCrashAndFailoverWithMessages(QualityOfServiceMode mode) throws Exception - { + public void performSourceAndTargetCrashAndFailoverWithMessages(QualityOfServiceMode mode) throws Exception { JMSBridgeImpl bridge = null; TransactionManager txMgr = null; - try - { + try { ConnectionFactoryFactory sourceCFF = sourceServer.getConnectionFactoryFactory(); ConnectionFactoryFactory targetCFF = targetServer.getConnectionFactoryFactory(); DestinationFactory sourceQueueFactory = sourceServer.getDestinationFactory(sourceQueueName); @@ -102,23 +95,7 @@ public class JMSBridgeClusteredTest extends ClusteredBridgeTestBase //even number final int batchSize = 4; - bridge = new JMSBridgeImpl(sourceCFF, - targetCFF, - sourceQueueFactory, - targetQueueFactory, - null, - null, - null, - null, - null, - 1000, - -1, - mode, - batchSize, - -1, - null, - null, - false); + bridge = new JMSBridgeImpl(sourceCFF, targetCFF, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 1000, -1, mode, batchSize, -1, null, null, false); txMgr = newTransactionManager(); bridge.setTransactionManager(txMgr); @@ -154,10 +131,8 @@ public class JMSBridgeClusteredTest extends ClusteredBridgeTestBase sendMessages(sourceServer, sourceQueueName, NUM_MESSAGES); receiveMessages(targetServer, targetQueueName, batchSize); } - finally - { - if (bridge != null) - { + finally { + if (bridge != null) { bridge.stop(); } } @@ -168,36 +143,18 @@ public class JMSBridgeClusteredTest extends ClusteredBridgeTestBase * separate live/backup pairs. Source and Target CF are ha. * Test the bridge work when the live servers crash. */ - private void performSourceAndTargetCrashAndFailover(QualityOfServiceMode mode) throws Exception - { + private void performSourceAndTargetCrashAndFailover(QualityOfServiceMode mode) throws Exception { JMSBridgeImpl bridge = null; TransactionManager txMgr = null; - try - { + try { ConnectionFactoryFactory sourceCFF = sourceServer.getConnectionFactoryFactory(); ConnectionFactoryFactory targetCFF = targetServer.getConnectionFactoryFactory(); DestinationFactory sourceQueueFactory = sourceServer.getDestinationFactory(sourceQueueName); DestinationFactory targetQueueFactory = targetServer.getDestinationFactory(targetQueueName); - bridge = new JMSBridgeImpl(sourceCFF, - targetCFF, - sourceQueueFactory, - targetQueueFactory, - null, - null, - null, - null, - null, - 1000, - -1, - mode, - 10, - 1000, - null, - null, - false); + bridge = new JMSBridgeImpl(sourceCFF, targetCFF, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 1000, -1, mode, 10, 1000, null, null, false); txMgr = newTransactionManager(); bridge.setTransactionManager(txMgr); @@ -226,48 +183,41 @@ public class JMSBridgeClusteredTest extends ClusteredBridgeTestBase sendMessages(sourceServer, sourceQueueName, NUM_MESSAGES); receiveMessages(targetServer, targetQueueName, NUM_MESSAGES, mode == QualityOfServiceMode.ONCE_AND_ONLY_ONCE); } - finally - { - if (bridge != null) - { + finally { + if (bridge != null) { bridge.stop(); } } } - private void sendMessages(ServerGroup server, String queueName, int num) throws ActiveMQException - { + private void sendMessages(ServerGroup server, String queueName, int num) throws ActiveMQException { server.sendMessages(queueName, num); } - private void receiveMessages(ServerGroup server, String queueName, int num, boolean checkDup) throws ActiveMQException - { - try - { + private void receiveMessages(ServerGroup server, + String queueName, + int num, + boolean checkDup) throws ActiveMQException { + try { server.receiveMessages(queueName, num, checkDup); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { e.printStackTrace(); throw e; } } - private void receiveMessages(ServerGroup server, String queueName, int num) throws ActiveMQException - { - try - { + private void receiveMessages(ServerGroup server, String queueName, int num) throws ActiveMQException { + try { server.receiveMessages(queueName, num, false); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { e.printStackTrace(); throw e; } } - protected TransactionManager newTransactionManager() - { + protected TransactionManager newTransactionManager() { return new TransactionManagerImple(); } diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/bridge/JMSBridgeReconnectionTest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/bridge/JMSBridgeReconnectionTest.java index 6007e54011..6821a16868 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/bridge/JMSBridgeReconnectionTest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/bridge/JMSBridgeReconnectionTest.java @@ -37,8 +37,8 @@ import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.xa.XAResource; -public class JMSBridgeReconnectionTest extends BridgeTestBase -{ +public class JMSBridgeReconnectionTest extends BridgeTestBase { + /** * */ @@ -51,89 +51,63 @@ public class JMSBridgeReconnectionTest extends BridgeTestBase // Once and only once @Test - public void testCrashAndReconnectDestBasic_OnceAndOnlyOnce_P() throws Exception - { + public void testCrashAndReconnectDestBasic_OnceAndOnlyOnce_P() throws Exception { performCrashAndReconnectDestBasic(QualityOfServiceMode.ONCE_AND_ONLY_ONCE, true, false); } @Test - public void testCrashAndReconnectDestBasic_OnceAndOnlyOnce_P_LargeMessage() throws Exception - { + public void testCrashAndReconnectDestBasic_OnceAndOnlyOnce_P_LargeMessage() throws Exception { performCrashAndReconnectDestBasic(QualityOfServiceMode.ONCE_AND_ONLY_ONCE, true, true); } @Test - public void testCrashAndReconnectDestBasic_OnceAndOnlyOnce_NP() throws Exception - { + public void testCrashAndReconnectDestBasic_OnceAndOnlyOnce_NP() throws Exception { performCrashAndReconnectDestBasic(QualityOfServiceMode.ONCE_AND_ONLY_ONCE, false, false); } // dups ok @Test - public void testCrashAndReconnectDestBasic_DuplicatesOk_P() throws Exception - { + public void testCrashAndReconnectDestBasic_DuplicatesOk_P() throws Exception { performCrashAndReconnectDestBasic(QualityOfServiceMode.DUPLICATES_OK, true, false); } @Test - public void testCrashAndReconnectDestBasic_DuplicatesOk_NP() throws Exception - { + public void testCrashAndReconnectDestBasic_DuplicatesOk_NP() throws Exception { performCrashAndReconnectDestBasic(QualityOfServiceMode.DUPLICATES_OK, false, false); } // At most once @Test - public void testCrashAndReconnectDestBasic_AtMostOnce_P() throws Exception - { + public void testCrashAndReconnectDestBasic_AtMostOnce_P() throws Exception { performCrashAndReconnectDestBasic(QualityOfServiceMode.AT_MOST_ONCE, true, false); } @Test - public void testCrashAndReconnectDestBasic_AtMostOnce_NP() throws Exception - { + public void testCrashAndReconnectDestBasic_AtMostOnce_NP() throws Exception { performCrashAndReconnectDestBasic(QualityOfServiceMode.AT_MOST_ONCE, false, false); } // Crash tests specific to XA transactions @Test - public void testCrashAndReconnectDestCrashBeforePrepare_P() throws Exception - { + public void testCrashAndReconnectDestCrashBeforePrepare_P() throws Exception { performCrashAndReconnectDestCrashBeforePrepare(true); } @Test - public void testCrashAndReconnectDestCrashBeforePrepare_NP() throws Exception - { + public void testCrashAndReconnectDestCrashBeforePrepare_NP() throws Exception { performCrashAndReconnectDestCrashBeforePrepare(false); } // Crash before bridge is started @Test - public void testRetryConnectionOnStartup() throws Exception - { + public void testRetryConnectionOnStartup() throws Exception { jmsServer1.stop(); - JMSBridgeImpl bridge = new JMSBridgeImpl(cff0, - cff1, - sourceQueueFactory, - targetQueueFactory, - null, - null, - null, - null, - null, - 1000, - -1, - QualityOfServiceMode.DUPLICATES_OK, - 10, - -1, - null, - null, - false); + JMSBridgeImpl bridge = new JMSBridgeImpl(cff0, cff1, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 1000, -1, QualityOfServiceMode.DUPLICATES_OK, 10, -1, null, null, false); bridge.setTransactionManager(newTransactionManager()); addActiveMQComponent(bridge); bridge.start(); @@ -156,27 +130,10 @@ public class JMSBridgeReconnectionTest extends BridgeTestBase * https://jira.jboss.org/jira/browse/HORNETQ-287 */ @Test - public void testStopBridgeWithFailureWhenStarted() throws Exception - { + public void testStopBridgeWithFailureWhenStarted() throws Exception { jmsServer1.stop(); - JMSBridgeImpl bridge = new JMSBridgeImpl(cff0, - cff1, - sourceQueueFactory, - targetQueueFactory, - null, - null, - null, - null, - null, - 500, - -1, - QualityOfServiceMode.DUPLICATES_OK, - 10, - -1, - null, - null, - false); + JMSBridgeImpl bridge = new JMSBridgeImpl(cff0, cff1, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 500, -1, QualityOfServiceMode.DUPLICATES_OK, 10, -1, null, null, false); bridge.setTransactionManager(newTransactionManager()); bridge.start(); @@ -201,36 +158,17 @@ public class JMSBridgeReconnectionTest extends BridgeTestBase */ private void performCrashAndReconnectDestBasic(final QualityOfServiceMode qosMode, final boolean persistent, - final boolean largeMessage) throws Exception - { + final boolean largeMessage) throws Exception { JMSBridgeImpl bridge = null; ConnectionFactoryFactory factInUse0 = cff0; ConnectionFactoryFactory factInUse1 = cff1; - if (qosMode.equals(QualityOfServiceMode.ONCE_AND_ONLY_ONCE)) - { + if (qosMode.equals(QualityOfServiceMode.ONCE_AND_ONLY_ONCE)) { factInUse0 = cff0xa; factInUse1 = cff1xa; } - bridge = - new JMSBridgeImpl(factInUse0, - factInUse1, - sourceQueueFactory, - targetQueueFactory, - null, - null, - null, - null, - null, - 1000, - -1, - qosMode, - 10, - -1, - null, - null, - false); + bridge = new JMSBridgeImpl(factInUse0, factInUse1, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 1000, -1, qosMode, 10, -1, null, null, false); addActiveMQComponent(bridge); bridge.setTransactionManager(newTransactionManager()); bridge.start(); @@ -282,47 +220,23 @@ public class JMSBridgeReconnectionTest extends BridgeTestBase } @Test - public void performCrashDestinationStopBridge() throws Exception - { + public void performCrashDestinationStopBridge() throws Exception { ConnectionFactoryFactory factInUse0 = cff0; ConnectionFactoryFactory factInUse1 = cff1; - final JMSBridgeImpl bridge = - new JMSBridgeImpl(factInUse0, - factInUse1, - sourceQueueFactory, - targetQueueFactory, - null, - null, - null, - null, - null, - 1000, - -1, - QualityOfServiceMode.DUPLICATES_OK, - 10, - -1, - null, - null, - false); - + final JMSBridgeImpl bridge = new JMSBridgeImpl(factInUse0, factInUse1, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 1000, -1, QualityOfServiceMode.DUPLICATES_OK, 10, -1, null, null, false); addActiveMQComponent(bridge); bridge.setTransactionManager(newTransactionManager()); bridge.start(); - Thread clientThread = new Thread(new Runnable() - { + Thread clientThread = new Thread(new Runnable() { @Override - public void run() - { - while (bridge.isStarted()) - { - try - { + public void run() { + while (bridge.isStarted()) { + try { sendMessages(cf0, sourceQueue, 0, 1, false, false); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -350,28 +264,19 @@ public class JMSBridgeReconnectionTest extends BridgeTestBase } @Test - public void performCrashAndReconnect() throws Exception - { + public void performCrashAndReconnect() throws Exception { performCrashAndReconnect(true); } @Test - public void performCrashAndNoReconnect() throws Exception - { + public void performCrashAndNoReconnect() throws Exception { performCrashAndReconnect(false); } - - private void performCrashAndReconnect(boolean restart) throws Exception - { - cff1xa = new ConnectionFactoryFactory() - { - public Object createConnectionFactory() throws Exception - { - ActiveMQXAConnectionFactory cf = (ActiveMQXAConnectionFactory) ActiveMQJMSClient.createConnectionFactoryWithHA(JMSFactoryType.XA_CF, - new TransportConfiguration( - INVM_CONNECTOR_FACTORY, - params1)); + private void performCrashAndReconnect(boolean restart) throws Exception { + cff1xa = new ConnectionFactoryFactory() { + public Object createConnectionFactory() throws Exception { + ActiveMQXAConnectionFactory cf = (ActiveMQXAConnectionFactory) ActiveMQJMSClient.createConnectionFactoryWithHA(JMSFactoryType.XA_CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY, params1)); // Note! We disable automatic reconnection on the session factory. The bridge needs to do the reconnection cf.setReconnectAttempts(-1); @@ -388,24 +293,7 @@ public class JMSBridgeReconnectionTest extends BridgeTestBase DummyTransaction tx = new DummyTransaction(); tm.tx = tx; - JMSBridgeImpl bridge = - new JMSBridgeImpl(cff0xa, - cff1xa, - sourceQueueFactory, - targetQueueFactory, - null, - null, - null, - null, - null, - 1000, - -1, - QualityOfServiceMode.ONCE_AND_ONLY_ONCE, - 10, - 5000, - null, - null, - false); + JMSBridgeImpl bridge = new JMSBridgeImpl(cff0xa, cff1xa, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 1000, -1, QualityOfServiceMode.ONCE_AND_ONLY_ONCE, 10, 5000, null, null, false); addActiveMQComponent(bridge); bridge.setTransactionManager(tm); @@ -417,8 +305,7 @@ public class JMSBridgeReconnectionTest extends BridgeTestBase jmsServer1.stop(); - if (restart) - { + if (restart) { jmsServer1.start(); } // Wait a while before starting up to simulate the dest being down for a while @@ -428,67 +315,60 @@ public class JMSBridgeReconnectionTest extends BridgeTestBase bridge.stop(); - if (restart) - { + if (restart) { assertTrue(tx.rolledback); assertTrue(tx.targetConnected); } - else - { + else { assertTrue(tx.rolledback); assertFalse(tx.targetConnected); } } - private class DummyTransaction implements Transaction - { + private class DummyTransaction implements Transaction { + boolean rolledback = false; ClientSession targetSession; boolean targetConnected = false; + @Override - public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, SystemException - { + public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, SystemException { } @Override - public void rollback() throws IllegalStateException, SystemException - { + public void rollback() throws IllegalStateException, SystemException { rolledback = true; targetConnected = !targetSession.isClosed(); } @Override - public void setRollbackOnly() throws IllegalStateException, SystemException - { + public void setRollbackOnly() throws IllegalStateException, SystemException { } @Override - public int getStatus() throws SystemException - { + public int getStatus() throws SystemException { return 0; } @Override - public boolean enlistResource(XAResource xaResource) throws RollbackException, IllegalStateException, SystemException - { + public boolean enlistResource(XAResource xaResource) throws RollbackException, IllegalStateException, SystemException { targetSession = (ClientSession) xaResource; return false; } @Override - public boolean delistResource(XAResource xaResource, int i) throws IllegalStateException, SystemException - { + public boolean delistResource(XAResource xaResource, int i) throws IllegalStateException, SystemException { return false; } @Override - public void registerSynchronization(Synchronization synchronization) throws RollbackException, IllegalStateException, SystemException - { + public void registerSynchronization(Synchronization synchronization) throws RollbackException, IllegalStateException, SystemException { } } + /* * Send some messages * Crash the destination server @@ -497,26 +377,8 @@ public class JMSBridgeReconnectionTest extends BridgeTestBase * Send some more messages * Verify all messages are received */ - private void performCrashAndReconnectDestCrashBeforePrepare(final boolean persistent) throws Exception - { - JMSBridgeImpl bridge = - new JMSBridgeImpl(cff0xa, - cff1xa, - sourceQueueFactory, - targetQueueFactory, - null, - null, - null, - null, - null, - 1000, - -1, - QualityOfServiceMode.ONCE_AND_ONLY_ONCE, - 10, - 5000, - null, - null, - false); + private void performCrashAndReconnectDestCrashBeforePrepare(final boolean persistent) throws Exception { + JMSBridgeImpl bridge = new JMSBridgeImpl(cff0xa, cff1xa, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 1000, -1, QualityOfServiceMode.ONCE_AND_ONLY_ONCE, 10, 5000, null, null, false); addActiveMQComponent(bridge); bridge.setTransactionManager(newTransactionManager()); diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/bridge/JMSBridgeTest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/bridge/JMSBridgeTest.java index 96dc0d7786..ce08f0eb8d 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/bridge/JMSBridgeTest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/bridge/JMSBridgeTest.java @@ -46,45 +46,39 @@ import org.apache.activemq.artemis.utils.DefaultSensitiveStringCodec; import org.junit.Assert; import org.junit.Test; -public class JMSBridgeTest extends BridgeTestBase -{ +public class JMSBridgeTest extends BridgeTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; // MaxBatchSize but no MaxBatchTime @Test - public void testNoMaxBatchTime_AtMostOnce_P() throws Exception - { + public void testNoMaxBatchTime_AtMostOnce_P() throws Exception { testNoMaxBatchTime(QualityOfServiceMode.AT_MOST_ONCE, true); } @Test - public void testNoMaxBatchTime_DuplicatesOk_P() throws Exception - { + public void testNoMaxBatchTime_DuplicatesOk_P() throws Exception { testNoMaxBatchTime(QualityOfServiceMode.DUPLICATES_OK, true); } @Test - public void testNoMaxBatchTime_OnceAndOnlyOnce_P() throws Exception - { + public void testNoMaxBatchTime_OnceAndOnlyOnce_P() throws Exception { testNoMaxBatchTime(QualityOfServiceMode.ONCE_AND_ONLY_ONCE, true); } @Test - public void testNoMaxBatchTime_AtMostOnce_NP() throws Exception - { + public void testNoMaxBatchTime_AtMostOnce_NP() throws Exception { testNoMaxBatchTime(QualityOfServiceMode.AT_MOST_ONCE, false); } @Test - public void testNoMaxBatchTime_DuplicatesOk_NP() throws Exception - { + public void testNoMaxBatchTime_DuplicatesOk_NP() throws Exception { testNoMaxBatchTime(QualityOfServiceMode.DUPLICATES_OK, false); } @Test - public void testNoMaxBatchTime_OnceAndOnlyOnce_NP() throws Exception - { + public void testNoMaxBatchTime_OnceAndOnlyOnce_NP() throws Exception { testNoMaxBatchTime(QualityOfServiceMode.ONCE_AND_ONLY_ONCE, false); } @@ -93,76 +87,64 @@ public class JMSBridgeTest extends BridgeTestBase // MaxBatchSize but no MaxBatchTime @Test - public void testNoMaxBatchTimeSameServer_AtMostOnce_P() throws Exception - { + public void testNoMaxBatchTimeSameServer_AtMostOnce_P() throws Exception { testNoMaxBatchTimeSameServer(QualityOfServiceMode.AT_MOST_ONCE, true); } @Test - public void testNoMaxBatchTimeSameServer_DuplicatesOk_P() throws Exception - { + public void testNoMaxBatchTimeSameServer_DuplicatesOk_P() throws Exception { testNoMaxBatchTimeSameServer(QualityOfServiceMode.DUPLICATES_OK, true); } @Test - public void testNoMaxBatchTimeSameServer_OnceAndOnlyOnce_P() throws Exception - { + public void testNoMaxBatchTimeSameServer_OnceAndOnlyOnce_P() throws Exception { testNoMaxBatchTimeSameServer(QualityOfServiceMode.ONCE_AND_ONLY_ONCE, true); } @Test - public void testNoMaxBatchTimeSameServer_AtMostOnce_NP() throws Exception - { + public void testNoMaxBatchTimeSameServer_AtMostOnce_NP() throws Exception { testNoMaxBatchTimeSameServer(QualityOfServiceMode.AT_MOST_ONCE, false); } @Test - public void testNoMaxBatchTimeSameServer_DuplicatesOk_NP() throws Exception - { + public void testNoMaxBatchTimeSameServer_DuplicatesOk_NP() throws Exception { testNoMaxBatchTimeSameServer(QualityOfServiceMode.DUPLICATES_OK, false); } @Test - public void testNoMaxBatchTimeSameServer_OnceAndOnlyOnce_NP() throws Exception - { + public void testNoMaxBatchTimeSameServer_OnceAndOnlyOnce_NP() throws Exception { testNoMaxBatchTimeSameServer(QualityOfServiceMode.ONCE_AND_ONLY_ONCE, false); } // MaxBatchTime but no MaxBatchSize @Test - public void testMaxBatchTime_AtMostOnce_P() throws Exception - { + public void testMaxBatchTime_AtMostOnce_P() throws Exception { testMaxBatchTime(QualityOfServiceMode.AT_MOST_ONCE, true); } @Test - public void testMaxBatchTime_DuplicatesOk_P() throws Exception - { + public void testMaxBatchTime_DuplicatesOk_P() throws Exception { testMaxBatchTime(QualityOfServiceMode.DUPLICATES_OK, true); } @Test - public void testMaxBatchTime_OnceAndOnlyOnce_P() throws Exception - { + public void testMaxBatchTime_OnceAndOnlyOnce_P() throws Exception { testMaxBatchTime(QualityOfServiceMode.ONCE_AND_ONLY_ONCE, true); } @Test - public void testMaxBatchTime_AtMostOnce_NP() throws Exception - { + public void testMaxBatchTime_AtMostOnce_NP() throws Exception { testMaxBatchTime(QualityOfServiceMode.AT_MOST_ONCE, false); } @Test - public void testMaxBatchTime_DuplicatesOk_NP() throws Exception - { + public void testMaxBatchTime_DuplicatesOk_NP() throws Exception { testMaxBatchTime(QualityOfServiceMode.DUPLICATES_OK, false); } @Test - public void testMaxBatchTime_OnceAndOnlyOnce_NP() throws Exception - { + public void testMaxBatchTime_OnceAndOnlyOnce_NP() throws Exception { testMaxBatchTime(QualityOfServiceMode.ONCE_AND_ONLY_ONCE, false); } @@ -171,128 +153,108 @@ public class JMSBridgeTest extends BridgeTestBase // MaxBatchTime but no MaxBatchSize @Test - public void testMaxBatchTimeSameServer_AtMostOnce_P() throws Exception - { + public void testMaxBatchTimeSameServer_AtMostOnce_P() throws Exception { testMaxBatchTimeSameServer(QualityOfServiceMode.AT_MOST_ONCE, true); } @Test - public void testMaxBatchTimeSameServer_DuplicatesOk_P() throws Exception - { + public void testMaxBatchTimeSameServer_DuplicatesOk_P() throws Exception { testMaxBatchTimeSameServer(QualityOfServiceMode.DUPLICATES_OK, true); } @Test - public void testMaxBatchTimeSameServer_OnceAndOnlyOnce_P() throws Exception - { + public void testMaxBatchTimeSameServer_OnceAndOnlyOnce_P() throws Exception { testMaxBatchTimeSameServer(QualityOfServiceMode.ONCE_AND_ONLY_ONCE, true); } @Test - public void testMaxBatchTimeSameServer_AtMostOnce_NP() throws Exception - { + public void testMaxBatchTimeSameServer_AtMostOnce_NP() throws Exception { testMaxBatchTimeSameServer(QualityOfServiceMode.AT_MOST_ONCE, false); } @Test - public void testMaxBatchTimeSameServer_DuplicatesOk_NP() throws Exception - { + public void testMaxBatchTimeSameServer_DuplicatesOk_NP() throws Exception { testMaxBatchTimeSameServer(QualityOfServiceMode.DUPLICATES_OK, false); } @Test - public void testMaxBatchTimeSameServer_OnceAndOnlyOnce_NP() throws Exception - { + public void testMaxBatchTimeSameServer_OnceAndOnlyOnce_NP() throws Exception { testMaxBatchTimeSameServer(QualityOfServiceMode.ONCE_AND_ONLY_ONCE, false); } // Stress with batch size of 50 @Test - public void testStress_AtMostOnce_P_50() throws Exception - { + public void testStress_AtMostOnce_P_50() throws Exception { testStress(QualityOfServiceMode.AT_MOST_ONCE, true, 50); } @Test - public void testStress_DuplicatesOk_P_50() throws Exception - { + public void testStress_DuplicatesOk_P_50() throws Exception { testStress(QualityOfServiceMode.DUPLICATES_OK, true, 50); } @Test - public void testStress_OnceAndOnlyOnce_P_50() throws Exception - { + public void testStress_OnceAndOnlyOnce_P_50() throws Exception { testStress(QualityOfServiceMode.ONCE_AND_ONLY_ONCE, true, 50); } @Test - public void testStress_AtMostOnce_NP_50() throws Exception - { + public void testStress_AtMostOnce_NP_50() throws Exception { testStress(QualityOfServiceMode.AT_MOST_ONCE, false, 50); } @Test - public void testStress_DuplicatesOk_NP_50() throws Exception - { + public void testStress_DuplicatesOk_NP_50() throws Exception { testStress(QualityOfServiceMode.DUPLICATES_OK, false, 50); } @Test - public void testStress_OnceAndOnlyOnce_NP_50() throws Exception - { + public void testStress_OnceAndOnlyOnce_NP_50() throws Exception { testStress(QualityOfServiceMode.ONCE_AND_ONLY_ONCE, false, 50); } // Stress with batch size of 1 @Test - public void testStress_AtMostOnce_P_1() throws Exception - { + public void testStress_AtMostOnce_P_1() throws Exception { testStress(QualityOfServiceMode.AT_MOST_ONCE, true, 1); } @Test - public void testStress_DuplicatesOk_P_1() throws Exception - { + public void testStress_DuplicatesOk_P_1() throws Exception { testStress(QualityOfServiceMode.DUPLICATES_OK, true, 1); } @Test - public void testStress_OnceAndOnlyOnce_P_1() throws Exception - { + public void testStress_OnceAndOnlyOnce_P_1() throws Exception { testStress(QualityOfServiceMode.ONCE_AND_ONLY_ONCE, true, 1); } @Test - public void testStress_AtMostOnce_NP_1() throws Exception - { + public void testStress_AtMostOnce_NP_1() throws Exception { testStress(QualityOfServiceMode.AT_MOST_ONCE, false, 1); } @Test - public void testStress_DuplicatesOk_NP_1() throws Exception - { + public void testStress_DuplicatesOk_NP_1() throws Exception { testStress(QualityOfServiceMode.DUPLICATES_OK, false, 1); } @Test - public void testStress_OnceAndOnlyOnce_NP_1() throws Exception - { + public void testStress_OnceAndOnlyOnce_NP_1() throws Exception { testStress(QualityOfServiceMode.ONCE_AND_ONLY_ONCE, false, 1); } // Max batch time @Test - public void testStressMaxBatchTime_OnceAndOnlyOnce_NP() throws Exception - { + public void testStressMaxBatchTime_OnceAndOnlyOnce_NP() throws Exception { testStressBatchTime(QualityOfServiceMode.ONCE_AND_ONLY_ONCE, false, 200); } @Test - public void testStressMaxBatchTime_OnceAndOnlyOnce_P() throws Exception - { + public void testStressMaxBatchTime_OnceAndOnlyOnce_P() throws Exception { testStressBatchTime(QualityOfServiceMode.ONCE_AND_ONLY_ONCE, true, 200); } @@ -301,109 +263,79 @@ public class JMSBridgeTest extends BridgeTestBase // Stress with batch size of 50 @Test - public void testStressSameServer_AtMostOnce_P_50() throws Exception - { + public void testStressSameServer_AtMostOnce_P_50() throws Exception { testStressSameServer(QualityOfServiceMode.AT_MOST_ONCE, true, 50); } @Test - public void testStressSameServer_DuplicatesOk_P_50() throws Exception - { + public void testStressSameServer_DuplicatesOk_P_50() throws Exception { testStressSameServer(QualityOfServiceMode.DUPLICATES_OK, true, 50); } @Test - public void testStressSameServer_OnceAndOnlyOnce_P_50() throws Exception - { + public void testStressSameServer_OnceAndOnlyOnce_P_50() throws Exception { testStress(QualityOfServiceMode.ONCE_AND_ONLY_ONCE, true, 50); } @Test - public void testStressSameServer_AtMostOnce_NP_50() throws Exception - { + public void testStressSameServer_AtMostOnce_NP_50() throws Exception { testStressSameServer(QualityOfServiceMode.AT_MOST_ONCE, false, 50); } @Test - public void testStressSameServer_DuplicatesOk_NP_50() throws Exception - { + public void testStressSameServer_DuplicatesOk_NP_50() throws Exception { testStressSameServer(QualityOfServiceMode.DUPLICATES_OK, false, 50); } @Test - public void testStressSameServer_OnceAndOnlyOnce_NP_50() throws Exception - { + public void testStressSameServer_OnceAndOnlyOnce_NP_50() throws Exception { testStressSameServer(QualityOfServiceMode.ONCE_AND_ONLY_ONCE, false, 50); } // Stress with batch size of 1 @Test - public void testStressSameServer_AtMostOnce_P_1() throws Exception - { + public void testStressSameServer_AtMostOnce_P_1() throws Exception { testStressSameServer(QualityOfServiceMode.AT_MOST_ONCE, true, 1); } @Test - public void testStressSameServer_DuplicatesOk_P_1() throws Exception - { + public void testStressSameServer_DuplicatesOk_P_1() throws Exception { testStressSameServer(QualityOfServiceMode.DUPLICATES_OK, true, 1); } @Test - public void testStressSameServer_OnceAndOnlyOnce_P_1() throws Exception - { + public void testStressSameServer_OnceAndOnlyOnce_P_1() throws Exception { testStressSameServer(QualityOfServiceMode.ONCE_AND_ONLY_ONCE, true, 1); } @Test - public void testStressSameServer_AtMostOnce_NP_1() throws Exception - { + public void testStressSameServer_AtMostOnce_NP_1() throws Exception { testStressSameServer(QualityOfServiceMode.AT_MOST_ONCE, false, 1); } @Test - public void testStressSameServer_DuplicatesOk_NP_1() throws Exception - { + public void testStressSameServer_DuplicatesOk_NP_1() throws Exception { testStressSameServer(QualityOfServiceMode.DUPLICATES_OK, false, 1); } @Test - public void testStressSameServer_OnceAndOnlyOnce_NP_1() throws Exception - { + public void testStressSameServer_OnceAndOnlyOnce_NP_1() throws Exception { testStressSameServer(QualityOfServiceMode.ONCE_AND_ONLY_ONCE, false, 1); } @Test - public void testStartBridgeFirst() throws Exception - { + public void testStartBridgeFirst() throws Exception { //stop the source server, we want to start the bridge first jmsServer0.stop(); JMSBridgeImpl bridge = null; ConnectionFactoryFactory factInUse0 = cff0; ConnectionFactoryFactory factInUse1 = cff1; - try - { + try { final int NUM_MESSAGES = 10; - bridge = new JMSBridgeImpl(factInUse0, - factInUse1, - sourceQueueFactory, - targetQueueFactory, - null, - null, - null, - null, - null, - 5000, - 10, - QualityOfServiceMode.AT_MOST_ONCE, - NUM_MESSAGES, - -1, - null, - null, - false); + bridge = new JMSBridgeImpl(factInUse0, factInUse1, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 5000, 10, QualityOfServiceMode.AT_MOST_ONCE, NUM_MESSAGES, -1, null, null, false); bridge.start(); @@ -445,10 +377,8 @@ public class JMSBridgeTest extends BridgeTestBase checkAllMessageReceivedInOrder(cf1, targetQueue, 0, NUM_MESSAGES - 1, false); } - finally - { - if (bridge != null) - { + finally { + if (bridge != null) { JMSBridgeTest.log.info("Stopping bridge"); bridge.stop(); } @@ -456,8 +386,7 @@ public class JMSBridgeTest extends BridgeTestBase } @Test - public void testParams() throws Exception - { + public void testParams() throws Exception { JMSBridgeImpl bridge = null; QualityOfServiceMode qosMode = QualityOfServiceMode.AT_MOST_ONCE; @@ -484,278 +413,107 @@ public class JMSBridgeTest extends BridgeTestBase String clientID = null; - try - { - bridge = - new JMSBridgeImpl(null, - cff1, - sourceQueueFactory, - targetQueueFactory, - sourceUsername, - sourcePassword, - destUsername, - destPassword, - selector, - failureRetryInterval, - maxRetries, - qosMode, - batchSize, - maxBatchTime, - subName, - clientID, - false); + try { + bridge = new JMSBridgeImpl(null, cff1, sourceQueueFactory, targetQueueFactory, sourceUsername, sourcePassword, destUsername, destPassword, selector, failureRetryInterval, maxRetries, qosMode, batchSize, maxBatchTime, subName, clientID, false); fail("expected exception"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { // Ok } - finally - { + finally { stopComponent(bridge); } - try - { - bridge = new JMSBridgeImpl(cff0, - null, - sourceQueueFactory, - targetQueueFactory, - sourceUsername, - sourcePassword, - destUsername, - destPassword, - selector, - failureRetryInterval, - maxRetries, - qosMode, - batchSize, - maxBatchTime, - subName, - clientID, - false); + try { + bridge = new JMSBridgeImpl(cff0, null, sourceQueueFactory, targetQueueFactory, sourceUsername, sourcePassword, destUsername, destPassword, selector, failureRetryInterval, maxRetries, qosMode, batchSize, maxBatchTime, subName, clientID, false); fail("expected exception"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { // Ok } - finally - { + finally { stopComponent(bridge); } - try - { - bridge = new JMSBridgeImpl(cff0, - cff1, - null, - targetQueueFactory, - sourceUsername, - sourcePassword, - destUsername, - destPassword, - selector, - failureRetryInterval, - maxRetries, - qosMode, - batchSize, - maxBatchTime, - subName, - clientID, - false); + try { + bridge = new JMSBridgeImpl(cff0, cff1, null, targetQueueFactory, sourceUsername, sourcePassword, destUsername, destPassword, selector, failureRetryInterval, maxRetries, qosMode, batchSize, maxBatchTime, subName, clientID, false); fail("expected exception"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { // Ok } - finally - { + finally { stopComponent(bridge); } - try - { - bridge = new JMSBridgeImpl(cff0, - cff1, - sourceQueueFactory, - null, - sourceUsername, - sourcePassword, - destUsername, - destPassword, - selector, - failureRetryInterval, - maxRetries, - qosMode, - batchSize, - maxBatchTime, - subName, - clientID, - false); + try { + bridge = new JMSBridgeImpl(cff0, cff1, sourceQueueFactory, null, sourceUsername, sourcePassword, destUsername, destPassword, selector, failureRetryInterval, maxRetries, qosMode, batchSize, maxBatchTime, subName, clientID, false); fail("expected exception"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { // Ok } - finally - { + finally { stopComponent(bridge); } - try - { - bridge = new JMSBridgeImpl(cff0, - cff1, - sourceQueueFactory, - targetQueueFactory, - sourceUsername, - sourcePassword, - destUsername, - destPassword, - selector, - -2, - maxRetries, - qosMode, - batchSize, - maxBatchTime, - subName, - clientID, - false); + try { + bridge = new JMSBridgeImpl(cff0, cff1, sourceQueueFactory, targetQueueFactory, sourceUsername, sourcePassword, destUsername, destPassword, selector, -2, maxRetries, qosMode, batchSize, maxBatchTime, subName, clientID, false); fail("expected exception"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { // Ok } - finally - { + finally { stopComponent(bridge); } - try - { - bridge = new JMSBridgeImpl(cff0, - cff1, - sourceQueueFactory, - targetQueueFactory, - sourceUsername, - sourcePassword, - destUsername, - destPassword, - selector, - -1, - 10, - qosMode, - batchSize, - maxBatchTime, - subName, - clientID, - false); + try { + bridge = new JMSBridgeImpl(cff0, cff1, sourceQueueFactory, targetQueueFactory, sourceUsername, sourcePassword, destUsername, destPassword, selector, -1, 10, qosMode, batchSize, maxBatchTime, subName, clientID, false); fail("expected exception"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { // Ok } - finally - { + finally { stopComponent(bridge); } - try - { - bridge = new JMSBridgeImpl(cff0, - cff1, - sourceQueueFactory, - null, - sourceUsername, - sourcePassword, - destUsername, - destPassword, - selector, - failureRetryInterval, - maxRetries, - qosMode, - 0, - maxBatchTime, - subName, - clientID, - false); + try { + bridge = new JMSBridgeImpl(cff0, cff1, sourceQueueFactory, null, sourceUsername, sourcePassword, destUsername, destPassword, selector, failureRetryInterval, maxRetries, qosMode, 0, maxBatchTime, subName, clientID, false); fail("expected exception"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { // Ok } - finally - { + finally { stopComponent(bridge); } - try - { - bridge = new JMSBridgeImpl(cff0, - cff1, - sourceQueueFactory, - null, - sourceUsername, - sourcePassword, - destUsername, - destPassword, - selector, - failureRetryInterval, - maxRetries, - qosMode, - batchSize, - -2, - subName, - clientID, - false); + try { + bridge = new JMSBridgeImpl(cff0, cff1, sourceQueueFactory, null, sourceUsername, sourcePassword, destUsername, destPassword, selector, failureRetryInterval, maxRetries, qosMode, batchSize, -2, subName, clientID, false); fail("expected exception"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { // Ok } - finally - { + finally { stopComponent(bridge); } } @Test - public void testStartStopStart() throws Exception - { + public void testStartStopStart() throws Exception { JMSBridgeImpl bridge = null; Connection connSource = null; Connection connTarget = null; - try - { + try { final int NUM_MESSAGES = 10; - bridge = new JMSBridgeImpl(cff0, - cff1, - sourceQueueFactory, - targetQueueFactory, - null, - null, - null, - null, - null, - 5000, - 10, - QualityOfServiceMode.AT_MOST_ONCE, - 1, - -1, - null, - null, - false); + bridge = new JMSBridgeImpl(cff0, cff1, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 5000, 10, QualityOfServiceMode.AT_MOST_ONCE, 1, -1, null, null, false); bridge.start(); @@ -769,8 +527,7 @@ public class JMSBridgeTest extends BridgeTestBase MessageProducer prod = sessSend.createProducer(sourceQueue); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = sessSend.createTextMessage("message" + i); prod.send(tm); } @@ -781,8 +538,7 @@ public class JMSBridgeTest extends BridgeTestBase connTarget.start(); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = (TextMessage) cons.receive(10000); Assert.assertNotNull(tm); Assert.assertEquals("message" + i, tm.getText()); @@ -791,20 +547,16 @@ public class JMSBridgeTest extends BridgeTestBase Message m = cons.receiveNoWait(); Assert.assertNull(m); } - finally - { - if (connSource != null) - { + finally { + if (connSource != null) { connSource.close(); } - if (connTarget != null) - { + if (connTarget != null) { connTarget.close(); } - if (bridge != null) - { + if (bridge != null) { bridge.stop(); } @@ -813,37 +565,19 @@ public class JMSBridgeTest extends BridgeTestBase } @Test - public void testSelector() throws Exception - { + public void testSelector() throws Exception { JMSBridgeImpl bridge = null; Connection connSource = null; Connection connTarget = null; - try - { + try { final int NUM_MESSAGES = 10; String selector = "vegetable='radish'"; - bridge = new JMSBridgeImpl(cff0, - cff1, - sourceQueueFactory, - targetQueueFactory, - null, - null, - null, - null, - selector, - 5000, - 10, - QualityOfServiceMode.AT_MOST_ONCE, - 1, - -1, - null, - null, - false); + bridge = new JMSBridgeImpl(cff0, cff1, sourceQueueFactory, targetQueueFactory, null, null, null, null, selector, 5000, 10, QualityOfServiceMode.AT_MOST_ONCE, 1, -1, null, null, false); bridge.start(); @@ -853,16 +587,13 @@ public class JMSBridgeTest extends BridgeTestBase MessageProducer prod = sessSend.createProducer(sourceQueue); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = sessSend.createTextMessage("message" + i); - if (i >= NUM_MESSAGES / 2) - { + if (i >= NUM_MESSAGES / 2) { tm.setStringProperty("vegetable", "radish"); } - else - { + else { tm.setStringProperty("vegetable", "cauliflower"); } @@ -877,8 +608,7 @@ public class JMSBridgeTest extends BridgeTestBase connTarget.start(); - for (int i = NUM_MESSAGES / 2; i < NUM_MESSAGES; i++) - { + for (int i = NUM_MESSAGES / 2; i < NUM_MESSAGES; i++) { TextMessage tm = (TextMessage) cons.receive(10000); Assert.assertNotNull(tm); @@ -891,20 +621,16 @@ public class JMSBridgeTest extends BridgeTestBase Assert.assertNull(m); } - finally - { - if (connSource != null) - { + finally { + if (connSource != null) { connSource.close(); } - if (connTarget != null) - { + if (connTarget != null) { connTarget.close(); } - if (bridge != null) - { + if (bridge != null) { bridge.stop(); } @@ -913,8 +639,7 @@ public class JMSBridgeTest extends BridgeTestBase } @Test - public void testMaskPassword() throws Exception - { + public void testMaskPassword() throws Exception { JMSBridgeImpl bridge = null; Connection connSource = null; @@ -924,13 +649,10 @@ public class JMSBridgeTest extends BridgeTestBase DefaultSensitiveStringCodec codec = new DefaultSensitiveStringCodec(); String mask = (String) codec.encode("guest"); - try - { + try { final int NUM_MESSAGES = 10; - bridge = new JMSBridgeImpl(cff0, cff1, sourceQueueFactory, - targetQueueFactory, "guest", mask, "guest", mask, null, 5000, - 10, QualityOfServiceMode.AT_MOST_ONCE, 1, -1, null, null, false); + bridge = new JMSBridgeImpl(cff0, cff1, sourceQueueFactory, targetQueueFactory, "guest", mask, "guest", mask, null, 5000, 10, QualityOfServiceMode.AT_MOST_ONCE, 1, -1, null, null, false); bridge.setUseMaskedPassword(true); @@ -938,13 +660,11 @@ public class JMSBridgeTest extends BridgeTestBase connSource = cf0.createConnection(); - Session sessSend = connSource.createSession(false, - Session.AUTO_ACKNOWLEDGE); + Session sessSend = connSource.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = sessSend.createProducer(sourceQueue); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = sessSend.createTextMessage("message" + i); prod.send(tm); @@ -952,15 +672,13 @@ public class JMSBridgeTest extends BridgeTestBase connTarget = cf1.createConnection(); - Session sessRec = connTarget.createSession(false, - Session.AUTO_ACKNOWLEDGE); + Session sessRec = connTarget.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer cons = sessRec.createConsumer(targetQueue); connTarget.start(); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = (TextMessage) cons.receive(10000); Assert.assertNotNull(tm); @@ -973,20 +691,16 @@ public class JMSBridgeTest extends BridgeTestBase Assert.assertNull(m); } - finally - { - if (connSource != null) - { + finally { + if (connSource != null) { connSource.close(); } - if (connTarget != null) - { + if (connTarget != null) { connTarget.close(); } - if (bridge != null) - { + if (bridge != null) { bridge.stop(); } @@ -995,8 +709,7 @@ public class JMSBridgeTest extends BridgeTestBase } @Test - public void testPasswordCodec() throws Exception - { + public void testPasswordCodec() throws Exception { JMSBridgeImpl bridge = null; Connection connSource = null; @@ -1010,13 +723,10 @@ public class JMSBridgeTest extends BridgeTestBase String mask = (String) codec.encode("guest"); - try - { + try { final int NUM_MESSAGES = 10; - bridge = new JMSBridgeImpl(cff0, cff1, sourceQueueFactory, - targetQueueFactory, "guest", mask, "guest", mask, null, 5000, - 10, QualityOfServiceMode.AT_MOST_ONCE, 1, -1, null, null, false); + bridge = new JMSBridgeImpl(cff0, cff1, sourceQueueFactory, targetQueueFactory, "guest", mask, "guest", mask, null, 5000, 10, QualityOfServiceMode.AT_MOST_ONCE, 1, -1, null, null, false); bridge.setUseMaskedPassword(true); bridge.setPasswordCodec(codec.getClass().getName() + ";key=bridgekey"); @@ -1025,13 +735,11 @@ public class JMSBridgeTest extends BridgeTestBase connSource = cf0.createConnection(); - Session sessSend = connSource.createSession(false, - Session.AUTO_ACKNOWLEDGE); + Session sessSend = connSource.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = sessSend.createProducer(sourceQueue); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = sessSend.createTextMessage("message" + i); prod.send(tm); @@ -1039,15 +747,13 @@ public class JMSBridgeTest extends BridgeTestBase connTarget = cf1.createConnection(); - Session sessRec = connTarget.createSession(false, - Session.AUTO_ACKNOWLEDGE); + Session sessRec = connTarget.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer cons = sessRec.createConsumer(targetQueue); connTarget.start(); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = (TextMessage) cons.receive(10000); Assert.assertNotNull(tm); @@ -1060,20 +766,16 @@ public class JMSBridgeTest extends BridgeTestBase Assert.assertNull(m); } - finally - { - if (connSource != null) - { + finally { + if (connSource != null) { connSource.close(); } - if (connTarget != null) - { + if (connTarget != null) { connTarget.close(); } - if (bridge != null) - { + if (bridge != null) { bridge.stop(); } @@ -1082,19 +784,16 @@ public class JMSBridgeTest extends BridgeTestBase } @Test - public void testStartBridgeWithJTATransactionAlreadyRunningLargeMessage() throws Exception - { + public void testStartBridgeWithJTATransactionAlreadyRunningLargeMessage() throws Exception { internalTestStartBridgeWithJTATransactionAlreadyRunning(true); } @Test - public void testStartBridgeWithJTATransactionAlreadyRunningRegularMessage() throws Exception - { + public void testStartBridgeWithJTATransactionAlreadyRunningRegularMessage() throws Exception { internalTestStartBridgeWithJTATransactionAlreadyRunning(false); } - public void internalTestStartBridgeWithJTATransactionAlreadyRunning(final boolean largeMessage) throws Exception - { + public void internalTestStartBridgeWithJTATransactionAlreadyRunning(final boolean largeMessage) throws Exception { JMSBridgeImpl bridge = null; Transaction toResume = null; @@ -1103,8 +802,7 @@ public class JMSBridgeTest extends BridgeTestBase TransactionManager mgr = newTransactionManager(); - try - { + try { toResume = mgr.suspend(); @@ -1114,98 +812,54 @@ public class JMSBridgeTest extends BridgeTestBase final int NUM_MESSAGES = 10; - bridge = new JMSBridgeImpl(cff0, - cff1, - sourceTopicFactory, - targetQueueFactory, - null, - null, - null, - null, - null, - 5000, - 10, - QualityOfServiceMode.AT_MOST_ONCE, - 1, - -1, - null, - null, - false); + bridge = new JMSBridgeImpl(cff0, cff1, sourceTopicFactory, targetQueueFactory, null, null, null, null, null, 5000, 10, QualityOfServiceMode.AT_MOST_ONCE, 1, -1, null, null, false); bridge.start(); sendMessages(cf0, sourceTopic, 0, NUM_MESSAGES, false, largeMessage); checkAllMessageReceivedInOrder(cf1, targetQueue, 0, NUM_MESSAGES, largeMessage); } - finally - { - if (started != null) - { - try - { + finally { + if (started != null) { + try { started.rollback(); } - catch (Exception e) - { + catch (Exception e) { JMSBridgeTest.log.error("Failed to rollback", e); } } - if (toResume != null) - { - try - { + if (toResume != null) { + try { mgr.resume(toResume); } - catch (Exception e) - { + catch (Exception e) { JMSBridgeTest.log.error("Failed to resume", e); } } - if (bridge != null) - { + if (bridge != null) { bridge.stop(); } } } @Test - public void testNonDurableSubscriberLargeMessage() throws Exception - { + public void testNonDurableSubscriberLargeMessage() throws Exception { internalTestNonDurableSubscriber(true, 1); } @Test - public void testNonDurableSubscriberRegularMessage() throws Exception - { + public void testNonDurableSubscriberRegularMessage() throws Exception { internalTestNonDurableSubscriber(false, 1); } - public void internalTestNonDurableSubscriber(final boolean largeMessage, final int batchSize) throws Exception - { + public void internalTestNonDurableSubscriber(final boolean largeMessage, final int batchSize) throws Exception { JMSBridgeImpl bridge = null; - try - { + try { final int NUM_MESSAGES = 10; - bridge = new JMSBridgeImpl(cff0, - cff1, - sourceTopicFactory, - targetQueueFactory, - null, - null, - null, - null, - null, - 5000, - 10, - QualityOfServiceMode.AT_MOST_ONCE, - batchSize, - -1, - null, - null, - false); + bridge = new JMSBridgeImpl(cff0, cff1, sourceTopicFactory, targetQueueFactory, null, null, null, null, null, 5000, 10, QualityOfServiceMode.AT_MOST_ONCE, batchSize, -1, null, null, false); bridge.start(); @@ -1213,52 +867,30 @@ public class JMSBridgeTest extends BridgeTestBase checkAllMessageReceivedInOrder(cf1, targetQueue, 0, NUM_MESSAGES, largeMessage); } - finally - { - if (bridge != null) - { + finally { + if (bridge != null) { bridge.stop(); } } } @Test - public void testDurableSubscriberLargeMessage() throws Exception - { + public void testDurableSubscriberLargeMessage() throws Exception { internalTestDurableSubscriber(true, 1); } @Test - public void testDurableSubscriberRegularMessage() throws Exception - { + public void testDurableSubscriberRegularMessage() throws Exception { internalTestDurableSubscriber(false, 1); } - public void internalTestDurableSubscriber(final boolean largeMessage, final int batchSize) throws Exception - { + public void internalTestDurableSubscriber(final boolean largeMessage, final int batchSize) throws Exception { JMSBridgeImpl bridge = null; - try - { + try { final int NUM_MESSAGES = 10; - bridge = new JMSBridgeImpl(cff0, - cff1, - sourceTopicFactory, - targetQueueFactory, - null, - null, - null, - null, - null, - 5000, - 10, - QualityOfServiceMode.AT_MOST_ONCE, - batchSize, - -1, - "subTest", - "clientid123", - false); + bridge = new JMSBridgeImpl(cff0, cff1, sourceTopicFactory, targetQueueFactory, null, null, null, null, null, 5000, 10, QualityOfServiceMode.AT_MOST_ONCE, batchSize, -1, "subTest", "clientid123", false); bridge.start(); @@ -1266,10 +898,8 @@ public class JMSBridgeTest extends BridgeTestBase checkAllMessageReceivedInOrder(cf1, targetQueue, 0, NUM_MESSAGES, largeMessage); } - finally - { - if (bridge != null) - { + finally { + if (bridge != null) { bridge.stop(); } @@ -1283,46 +913,26 @@ public class JMSBridgeTest extends BridgeTestBase } @Test - public void testMessageIDInHeaderOn() throws Exception - { + public void testMessageIDInHeaderOn() throws Exception { messageIDInHeader(true); } @Test - public void testMessageIDInHeaderOff() throws Exception - { + public void testMessageIDInHeaderOff() throws Exception { messageIDInHeader(false); } - private void messageIDInHeader(final boolean on) throws Exception - { + private void messageIDInHeader(final boolean on) throws Exception { JMSBridgeImpl bridge = null; Connection connSource = null; Connection connTarget = null; - try - { + try { final int NUM_MESSAGES = 10; - bridge = new JMSBridgeImpl(cff0, - cff1, - sourceQueueFactory, - targetQueueFactory, - null, - null, - null, - null, - null, - 5000, - 10, - QualityOfServiceMode.AT_MOST_ONCE, - 1, - -1, - null, - null, - on); + bridge = new JMSBridgeImpl(cff0, cff1, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 5000, 10, QualityOfServiceMode.AT_MOST_ONCE, 1, -1, null, null, on); bridge.start(); @@ -1338,8 +948,7 @@ public class JMSBridgeTest extends BridgeTestBase MessageProducer prod = sessSource.createProducer(sourceQueue); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = sessSource.createTextMessage("message" + i); // We add some properties to make sure they get passed through ok @@ -1376,8 +985,7 @@ public class JMSBridgeTest extends BridgeTestBase List msgs = new ArrayList(); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = (TextMessage) cons.receive(5000); Assert.assertNotNull(tm); @@ -1397,8 +1005,7 @@ public class JMSBridgeTest extends BridgeTestBase Assert.assertEquals("mygroup543", tm.getStringProperty("JMSXGroupID")); - if (on) - { + if (on) { String header = tm.getStringProperty(ActiveMQJMSConstants.AMQ_MESSAGING_BRIDGE_MESSAGE_ID_LIST); Assert.assertNotNull(header); @@ -1409,16 +1016,14 @@ public class JMSBridgeTest extends BridgeTestBase } } - if (on) - { + if (on) { // Now we send them again back to the source Iterator iter = msgs.iterator(); List ids2 = new ArrayList(); - while (iter.hasNext()) - { + while (iter.hasNext()) { Message msg = iter.next(); prod.send(msg); @@ -1428,8 +1033,7 @@ public class JMSBridgeTest extends BridgeTestBase // And consume them again - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = (TextMessage) cons.receive(5000); Assert.assertNotNull(tm); @@ -1458,78 +1062,52 @@ public class JMSBridgeTest extends BridgeTestBase } } - finally - { - if (bridge != null) - { + finally { + if (bridge != null) { bridge.stop(); } - if (connSource != null) - { + if (connSource != null) { connSource.close(); } - if (connTarget != null) - { + if (connTarget != null) { connTarget.close(); } } } @Test - public void testPropertiesPreservedPOn() throws Exception - { + public void testPropertiesPreservedPOn() throws Exception { propertiesPreserved(true, true); } @Test - public void testPropertiesPreservedNPoff() throws Exception - { + public void testPropertiesPreservedNPoff() throws Exception { propertiesPreserved(false, true); } @Test - public void testPropertiesPreservedNPOn() throws Exception - { + public void testPropertiesPreservedNPOn() throws Exception { propertiesPreserved(false, true); } @Test - public void testPropertiesPreservedPoff() throws Exception - { + public void testPropertiesPreservedPoff() throws Exception { propertiesPreserved(true, true); } - private void propertiesPreserved(final boolean persistent, final boolean messageIDInHeader) throws Exception - { + private void propertiesPreserved(final boolean persistent, final boolean messageIDInHeader) throws Exception { JMSBridgeImpl bridge = null; Connection connSource = null; Connection connTarget = null; - try - { + try { final int NUM_MESSAGES = 10; - bridge = new JMSBridgeImpl(cff0, - cff1, - sourceQueueFactory, - targetQueueFactory, - null, - null, - null, - null, - null, - 5000, - 10, - QualityOfServiceMode.AT_MOST_ONCE, - 1, - -1, - null, - null, - messageIDInHeader); + bridge = new JMSBridgeImpl(cff0, cff1, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 5000, 10, QualityOfServiceMode.AT_MOST_ONCE, 1, -1, null, null, messageIDInHeader); bridge.start(); @@ -1561,8 +1139,7 @@ public class JMSBridgeTest extends BridgeTestBase long expiration = tm.getJMSExpiration(); - Assert.assertEquals(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT, - tm.getJMSDeliveryMode()); + Assert.assertEquals(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT, tm.getJMSDeliveryMode()); tm = (TextMessage) cons.receive(1000); @@ -1570,8 +1147,7 @@ public class JMSBridgeTest extends BridgeTestBase Assert.assertEquals("blahmessage", tm.getText()); - Assert.assertEquals(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT, - tm.getJMSDeliveryMode()); + Assert.assertEquals(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT, tm.getJMSDeliveryMode()); Assert.assertEquals(7, tm.getJMSPriority()); @@ -1591,8 +1167,7 @@ public class JMSBridgeTest extends BridgeTestBase prod.send(tm); - Assert.assertEquals(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT, - tm.getJMSDeliveryMode()); + Assert.assertEquals(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT, tm.getJMSDeliveryMode()); tm = (TextMessage) cons.receive(1000); @@ -1600,8 +1175,7 @@ public class JMSBridgeTest extends BridgeTestBase Assert.assertEquals("blahmessage2", tm.getText()); - Assert.assertEquals(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT, - tm.getJMSDeliveryMode()); + Assert.assertEquals(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT, tm.getJMSDeliveryMode()); Assert.assertEquals(7, tm.getJMSPriority()); @@ -1655,55 +1229,33 @@ public class JMSBridgeTest extends BridgeTestBase m = cons.receive(5000); } - finally - { - if (bridge != null) - { + finally { + if (bridge != null) { bridge.stop(); } - if (connSource != null) - { + if (connSource != null) { connSource.close(); } - if (connTarget != null) - { + if (connTarget != null) { connTarget.close(); } } } @Test - public void testNoMessageIDInHeader() throws Exception - { + public void testNoMessageIDInHeader() throws Exception { JMSBridgeImpl bridge = null; Connection connSource = null; Connection connTarget = null; - try - { + try { final int NUM_MESSAGES = 10; - bridge = new JMSBridgeImpl(cff0, - cff1, - sourceQueueFactory, - targetQueueFactory, - null, - null, - null, - null, - null, - 5000, - 10, - QualityOfServiceMode.AT_MOST_ONCE, - 1, - -1, - null, - null, - false); + bridge = new JMSBridgeImpl(cff0, cff1, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 5000, 10, QualityOfServiceMode.AT_MOST_ONCE, 1, -1, null, null, false); bridge.start(); @@ -1717,8 +1269,7 @@ public class JMSBridgeTest extends BridgeTestBase MessageProducer prod = sessSource.createProducer(sourceQueue); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = sessSource.createTextMessage("message" + i); // We add some headers to make sure they get passed through ok @@ -1737,8 +1288,7 @@ public class JMSBridgeTest extends BridgeTestBase connTarget.start(); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = (TextMessage) cons.receive(5000); Assert.assertNotNull(tm); @@ -1754,20 +1304,16 @@ public class JMSBridgeTest extends BridgeTestBase Assert.assertNull(header); } } - finally - { - if (bridge != null) - { + finally { + if (bridge != null) { bridge.stop(); } - if (connSource != null) - { + if (connSource != null) { connSource.close(); } - if (connTarget != null) - { + if (connTarget != null) { connTarget.close(); } } @@ -1775,8 +1321,9 @@ public class JMSBridgeTest extends BridgeTestBase // Private ------------------------------------------------------------------------------- - private void testStress(final QualityOfServiceMode qosMode, final boolean persistent, final int batchSize) throws Exception - { + private void testStress(final QualityOfServiceMode qosMode, + final boolean persistent, + final int batchSize) throws Exception { Connection connSource = null; JMSBridgeImpl bridge = null; @@ -1785,32 +1332,14 @@ public class JMSBridgeTest extends BridgeTestBase ConnectionFactoryFactory factInUse0 = cff0; ConnectionFactoryFactory factInUse1 = cff1; - if (qosMode.equals(QualityOfServiceMode.ONCE_AND_ONLY_ONCE)) - { + if (qosMode.equals(QualityOfServiceMode.ONCE_AND_ONLY_ONCE)) { factInUse0 = cff0xa; factInUse1 = cff1xa; ServiceUtils.setTransactionManager(newTransactionManager()); } - try - { - bridge = new JMSBridgeImpl(factInUse0, - factInUse1, - sourceQueueFactory, - targetQueueFactory, - null, - null, - null, - null, - null, - 5000, - 10, - qosMode, - batchSize, - -1, - null, - null, - false); + try { + bridge = new JMSBridgeImpl(factInUse0, factInUse1, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 5000, 10, qosMode, batchSize, -1, null, null, false); bridge.start(); @@ -1836,41 +1365,35 @@ public class JMSBridgeTest extends BridgeTestBase t.join(); - if (sender.ex != null) - { + if (sender.ex != null) { // An error occurred during the send throw sender.ex; } } - finally - { - if (t != null) - { + finally { + if (t != null) { t.join(10000); } - if (connSource != null) - { - try - { + if (connSource != null) { + try { connSource.close(); } - catch (Exception e) - { + catch (Exception e) { JMSBridgeTest.log.error("Failed to close connection", e); } } - if (bridge != null) - { + if (bridge != null) { bridge.stop(); } } } - private void testStressBatchTime(final QualityOfServiceMode qosMode, final boolean persistent, final int maxBatchTime) throws Exception - { + private void testStressBatchTime(final QualityOfServiceMode qosMode, + final boolean persistent, + final int maxBatchTime) throws Exception { Connection connSource = null; JMSBridgeImpl bridge = null; @@ -1879,32 +1402,14 @@ public class JMSBridgeTest extends BridgeTestBase ConnectionFactoryFactory factInUse0 = cff0; ConnectionFactoryFactory factInUse1 = cff1; - if (qosMode.equals(QualityOfServiceMode.ONCE_AND_ONLY_ONCE)) - { + if (qosMode.equals(QualityOfServiceMode.ONCE_AND_ONLY_ONCE)) { factInUse0 = cff0xa; factInUse1 = cff1xa; ServiceUtils.setTransactionManager(newTransactionManager()); } - try - { - bridge = new JMSBridgeImpl(factInUse0, - factInUse1, - sourceQueueFactory, - targetQueueFactory, - null, - null, - null, - null, - null, - 5000, - 10, - qosMode, - 2, - maxBatchTime, - null, - null, - false); + try { + bridge = new JMSBridgeImpl(factInUse0, factInUse1, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 5000, 10, qosMode, 2, maxBatchTime, null, null, false); bridge.start(); @@ -1930,42 +1435,36 @@ public class JMSBridgeTest extends BridgeTestBase t.join(); - if (sender.ex != null) - { + if (sender.ex != null) { // An error occurred during the send throw sender.ex; } } - finally - { - if (t != null) - { + finally { + if (t != null) { t.join(10000); } - if (connSource != null) - { - try - { + if (connSource != null) { + try { connSource.close(); } - catch (Exception e) - { + catch (Exception e) { JMSBridgeTest.log.error("Failed to close connection", e); } } - if (bridge != null) - { + if (bridge != null) { bridge.stop(); } } } // Both source and destination on same rm - private void testStressSameServer(final QualityOfServiceMode qosMode, final boolean persistent, final int batchSize) throws Exception - { + private void testStressSameServer(final QualityOfServiceMode qosMode, + final boolean persistent, + final int batchSize) throws Exception { Connection connSource = null; JMSBridgeImpl bridge = null; @@ -1973,30 +1472,12 @@ public class JMSBridgeTest extends BridgeTestBase Thread t = null; ConnectionFactoryFactory factInUse0 = cff0; - if (qosMode.equals(QualityOfServiceMode.ONCE_AND_ONLY_ONCE)) - { + if (qosMode.equals(QualityOfServiceMode.ONCE_AND_ONLY_ONCE)) { factInUse0 = cff0xa; } - try - { - bridge = new JMSBridgeImpl(factInUse0, - factInUse0, - sourceQueueFactory, - localTargetQueueFactory, - null, - null, - null, - null, - null, - 5000, - 10, - qosMode, - batchSize, - -1, - null, - null, - false); + try { + bridge = new JMSBridgeImpl(factInUse0, factInUse0, sourceQueueFactory, localTargetQueueFactory, null, null, null, null, null, 5000, 10, qosMode, batchSize, -1, null, null, false); bridge.start(); @@ -2022,72 +1503,46 @@ public class JMSBridgeTest extends BridgeTestBase t.join(); - if (sender.ex != null) - { + if (sender.ex != null) { // An error occurred during the send throw sender.ex; } } - finally - { - if (t != null) - { + finally { + if (t != null) { t.join(10000); } - if (connSource != null) - { - try - { + if (connSource != null) { + try { connSource.close(); } - catch (Exception e) - { + catch (Exception e) { JMSBridgeTest.log.error("Failed to close connection", e); } } - if (bridge != null) - { + if (bridge != null) { bridge.stop(); } } } - private void testNoMaxBatchTime(final QualityOfServiceMode qosMode, final boolean persistent) throws Exception - { + private void testNoMaxBatchTime(final QualityOfServiceMode qosMode, final boolean persistent) throws Exception { JMSBridgeImpl bridge = null; ConnectionFactoryFactory factInUse0 = cff0; ConnectionFactoryFactory factInUse1 = cff1; - if (qosMode.equals(QualityOfServiceMode.ONCE_AND_ONLY_ONCE)) - { + if (qosMode.equals(QualityOfServiceMode.ONCE_AND_ONLY_ONCE)) { factInUse0 = cff0xa; factInUse1 = cff1xa; ServiceUtils.setTransactionManager(newTransactionManager()); } - try - { + try { final int NUM_MESSAGES = 10; - bridge = new JMSBridgeImpl(factInUse0, - factInUse1, - sourceQueueFactory, - targetQueueFactory, - null, - null, - null, - null, - null, - 5000, - 10, - qosMode, - NUM_MESSAGES, - -1, - null, - null, - false); + bridge = new JMSBridgeImpl(factInUse0, factInUse1, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 5000, 10, qosMode, NUM_MESSAGES, -1, null, null, false); bridge.start(); @@ -2123,48 +1578,28 @@ public class JMSBridgeTest extends BridgeTestBase checkAllMessageReceivedInOrder(cf1, targetQueue, 0, NUM_MESSAGES - 1, false); } - finally - { - if (bridge != null) - { + finally { + if (bridge != null) { JMSBridgeTest.log.info("Stopping bridge"); bridge.stop(); } } } - private void testNoMaxBatchTimeSameServer(final QualityOfServiceMode qosMode, final boolean persistent) throws Exception - { + private void testNoMaxBatchTimeSameServer(final QualityOfServiceMode qosMode, + final boolean persistent) throws Exception { JMSBridgeImpl bridge = null; ConnectionFactoryFactory factInUse0 = cff0; - if (qosMode.equals(QualityOfServiceMode.ONCE_AND_ONLY_ONCE)) - { + if (qosMode.equals(QualityOfServiceMode.ONCE_AND_ONLY_ONCE)) { factInUse0 = cff0xa; ServiceUtils.setTransactionManager(newTransactionManager()); } - try - { + try { final int NUM_MESSAGES = 10; - bridge = new JMSBridgeImpl(factInUse0, - factInUse0, - sourceQueueFactory, - localTargetQueueFactory, - null, - null, - null, - null, - null, - 5000, - 10, - qosMode, - NUM_MESSAGES, - -1, - null, - null, - false); + bridge = new JMSBridgeImpl(factInUse0, factInUse0, sourceQueueFactory, localTargetQueueFactory, null, null, null, null, null, 5000, 10, qosMode, NUM_MESSAGES, -1, null, null, false); bridge.start(); @@ -2200,51 +1635,30 @@ public class JMSBridgeTest extends BridgeTestBase checkAllMessageReceivedInOrder(cf0, localTargetQueue, 0, NUM_MESSAGES - 1, false); } - finally - { - if (bridge != null) - { + finally { + if (bridge != null) { bridge.stop(); } } } - private void testMaxBatchTime(final QualityOfServiceMode qosMode, final boolean persistent) throws Exception - { + private void testMaxBatchTime(final QualityOfServiceMode qosMode, final boolean persistent) throws Exception { JMSBridgeImpl bridge = null; ConnectionFactoryFactory factInUse0 = cff0; ConnectionFactoryFactory factInUse1 = cff1; - if (qosMode.equals(QualityOfServiceMode.ONCE_AND_ONLY_ONCE)) - { + if (qosMode.equals(QualityOfServiceMode.ONCE_AND_ONLY_ONCE)) { factInUse0 = cff0xa; factInUse1 = cff1xa; ServiceUtils.setTransactionManager(newTransactionManager()); } - try - { + try { final long MAX_BATCH_TIME = 3000; final int MAX_BATCH_SIZE = 100000; // something big so it won't reach it - bridge = new JMSBridgeImpl(factInUse0, - factInUse1, - sourceQueueFactory, - targetQueueFactory, - null, - null, - null, - null, - null, - 3000, - 10, - qosMode, - MAX_BATCH_SIZE, - MAX_BATCH_TIME, - null, - null, - false); + bridge = new JMSBridgeImpl(factInUse0, factInUse1, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 3000, 10, qosMode, MAX_BATCH_SIZE, MAX_BATCH_TIME, null, null, false); bridge.start(); @@ -2262,49 +1676,29 @@ public class JMSBridgeTest extends BridgeTestBase checkAllMessageReceivedInOrder(cf1, targetQueue, 0, NUM_MESSAGES, false); } - finally - { - if (bridge != null) - { + finally { + if (bridge != null) { bridge.stop(); } } } - private void testMaxBatchTimeSameServer(final QualityOfServiceMode qosMode, final boolean persistent) throws Exception - { + private void testMaxBatchTimeSameServer(final QualityOfServiceMode qosMode, + final boolean persistent) throws Exception { JMSBridgeImpl bridge = null; ConnectionFactoryFactory factInUse0 = cff0; - if (qosMode.equals(QualityOfServiceMode.ONCE_AND_ONLY_ONCE)) - { + if (qosMode.equals(QualityOfServiceMode.ONCE_AND_ONLY_ONCE)) { factInUse0 = cff0xa; ServiceUtils.setTransactionManager(newTransactionManager()); } - try - { + try { final long MAX_BATCH_TIME = 3000; final int MAX_BATCH_SIZE = 100000; // something big so it won't reach it - bridge = new JMSBridgeImpl(factInUse0, - factInUse0, - sourceQueueFactory, - localTargetQueueFactory, - null, - null, - null, - null, - null, - 3000, - 10, - qosMode, - MAX_BATCH_SIZE, - MAX_BATCH_TIME, - null, - null, - false); + bridge = new JMSBridgeImpl(factInUse0, factInUse0, sourceQueueFactory, localTargetQueueFactory, null, null, null, null, null, 3000, 10, qosMode, MAX_BATCH_SIZE, MAX_BATCH_TIME, null, null, false); bridge.start(); @@ -2324,77 +1718,36 @@ public class JMSBridgeTest extends BridgeTestBase checkAllMessageReceivedInOrder(cf0, localTargetQueue, 0, NUM_MESSAGES, false); } - finally - { - if (bridge != null) - { + finally { + if (bridge != null) { bridge.stop(); } } } @Test - public void testSetTMClass() throws Exception - { + public void testSetTMClass() throws Exception { TransactionManagerLocatorImpl.tm = new DummyTransactionManager(); JMSBridgeImpl bridge = null; - try - { - bridge = new JMSBridgeImpl(cff0, - cff0, - sourceQueueFactory, - localTargetQueueFactory, - null, - null, - null, - null, - null, - 3000, - 10, - QualityOfServiceMode.ONCE_AND_ONLY_ONCE, - 10000, - 3000, - null, - null, - false); + try { + bridge = new JMSBridgeImpl(cff0, cff0, sourceQueueFactory, localTargetQueueFactory, null, null, null, null, null, 3000, 10, QualityOfServiceMode.ONCE_AND_ONLY_ONCE, 10000, 3000, null, null, false); bridge.start(); } - finally - { - if (bridge != null) - { + finally { + if (bridge != null) { bridge.stop(); } } } @Test - public void testMBeanServer() throws Exception - { + public void testMBeanServer() throws Exception { MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); ObjectName objectName = new ObjectName("example.jmsbridge:service=JMSBridge"); - JMSBridgeImpl bridge = new JMSBridgeImpl(cff0, - cff0, - sourceQueueFactory, - localTargetQueueFactory, - null, - null, - null, - null, - null, - 5000, - 10, - QualityOfServiceMode.AT_MOST_ONCE, - 1, - -1, - null, - null, - false, - mbeanServer, - objectName.getCanonicalName()); + JMSBridgeImpl bridge = new JMSBridgeImpl(cff0, cff0, sourceQueueFactory, localTargetQueueFactory, null, null, null, null, null, 5000, 10, QualityOfServiceMode.AT_MOST_ONCE, 1, -1, null, null, false, mbeanServer, objectName.getCanonicalName()); Assert.assertTrue(mbeanServer.isRegistered(objectName)); @@ -2403,15 +1756,14 @@ public class JMSBridgeTest extends BridgeTestBase Assert.assertFalse(mbeanServer.isRegistered(objectName)); } - public TransactionManager getNewTm() - { + public TransactionManager getNewTm() { return newTransactionManager(); } // Inner classes ------------------------------------------------------------------- - private static class StressSender implements Runnable - { + private static class StressSender implements Runnable { + int numMessages; Session sess; @@ -2420,12 +1772,9 @@ public class JMSBridgeTest extends BridgeTestBase Exception ex; - public void run() - { - try - { - for (int i = 0; i < numMessages; i++) - { + public void run() { + try { + for (int i = 0; i < numMessages; i++) { TextMessage tm = sess.createTextMessage("message" + i); prod.send(tm); @@ -2433,8 +1782,7 @@ public class JMSBridgeTest extends BridgeTestBase JMSBridgeTest.log.trace("Sent message " + i); } } - catch (Exception e) - { + catch (Exception e) { JMSBridgeTest.log.error("Failed to send", e); ex = e; } diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/bridge/TransactionManagerLocatorImpl.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/bridge/TransactionManagerLocatorImpl.java index e07b616f0d..c883f471ea 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/bridge/TransactionManagerLocatorImpl.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/bridge/TransactionManagerLocatorImpl.java @@ -21,18 +21,16 @@ import javax.transaction.TransactionManager; import org.apache.activemq.artemis.service.extensions.transactions.TransactionManagerLocator; -public class TransactionManagerLocatorImpl implements TransactionManagerLocator -{ +public class TransactionManagerLocatorImpl implements TransactionManagerLocator { + public static TransactionManager tm = null; @Override - public TransactionManager getTransactionManager() - { + public TransactionManager getTransactionManager() { return tm; } - public void setTransactionManager(TransactionManager transactionManager) - { + public void setTransactionManager(TransactionManager transactionManager) { tm = transactionManager; } } diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/xa/JMSXDeliveryCountTest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/xa/JMSXDeliveryCountTest.java index 2d36fce958..ee2c67d305 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/xa/JMSXDeliveryCountTest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/xa/JMSXDeliveryCountTest.java @@ -46,11 +46,10 @@ import org.junit.Before; import org.junit.Test; /** - * * A JMSXDeliveryCountTest */ -public class JMSXDeliveryCountTest extends JMSTestBase -{ +public class JMSXDeliveryCountTest extends JMSTestBase { + Queue queue1; Topic topic1; @@ -58,8 +57,7 @@ public class JMSXDeliveryCountTest extends JMSTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); xacf = ActiveMQJMSClient.createConnectionFactory("tcp://localhost:61616", "test"); @@ -72,8 +70,7 @@ public class JMSXDeliveryCountTest extends JMSTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { TxControl.disable(true); TransactionReaper.terminate(false); @@ -83,12 +80,10 @@ public class JMSXDeliveryCountTest extends JMSTestBase } @Test - public void testSimpleJMSXDeliveryCount() throws Exception - { + public void testSimpleJMSXDeliveryCount() throws Exception { Connection conn = null; - try - { + try { conn = cf.createConnection(); Session s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer p = s.createProducer(queue1); @@ -103,42 +98,36 @@ public class JMSXDeliveryCountTest extends JMSTestBase conn.start(); - TextMessage tm = (TextMessage)c.receive(1000); + TextMessage tm = (TextMessage) c.receive(1000); Assert.assertEquals("xoxo", tm.getText()); - Assert.assertTrue("JMSXDeliveryCount is supposed to exist as a property", - tm.propertyExists("JMSXDeliveryCount")); + Assert.assertTrue("JMSXDeliveryCount is supposed to exist as a property", tm.propertyExists("JMSXDeliveryCount")); Assert.assertEquals(1, tm.getIntProperty("JMSXDeliveryCount")); s.recover(); - tm = (TextMessage)c.receive(1000); + tm = (TextMessage) c.receive(1000); Assert.assertEquals("xoxo", tm.getText()); - Assert.assertTrue("JMSXDeliveryCount is supposed to exist as a property", - tm.propertyExists("JMSXDeliveryCount")); + Assert.assertTrue("JMSXDeliveryCount is supposed to exist as a property", tm.propertyExists("JMSXDeliveryCount")); Assert.assertEquals(2, tm.getIntProperty("JMSXDeliveryCount")); tm.acknowledge(); conn.close(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testJMSXDeliveryCountNotDeliveredMessagesNotUpdated() throws Exception - { + public void testJMSXDeliveryCountNotDeliveredMessagesNotUpdated() throws Exception { Connection conn = null; - try - { + try { conn = cf.createConnection(); Session s = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); @@ -155,7 +144,7 @@ public class JMSXDeliveryCountTest extends JMSTestBase conn.start(); - TextMessage tm = (TextMessage)c.receive(1000); + TextMessage tm = (TextMessage) c.receive(1000); Assert.assertEquals("message1", tm.getText()); Assert.assertFalse(tm.getJMSRedelivered()); @@ -167,31 +156,31 @@ public class JMSXDeliveryCountTest extends JMSTestBase c = s.createConsumer(queue1); - tm = (TextMessage)c.receive(1000); + tm = (TextMessage) c.receive(1000); Assert.assertEquals("message1", tm.getText()); Assert.assertTrue(tm.getJMSRedelivered()); Assert.assertEquals(2, tm.getIntProperty("JMSXDeliveryCount")); - tm = (TextMessage)c.receive(1000); + tm = (TextMessage) c.receive(1000); Assert.assertEquals("message2", tm.getText()); Assert.assertFalse(tm.getJMSRedelivered()); Assert.assertEquals(1, tm.getIntProperty("JMSXDeliveryCount")); - tm = (TextMessage)c.receive(1000); + tm = (TextMessage) c.receive(1000); Assert.assertEquals("message3", tm.getText()); Assert.assertFalse(tm.getJMSRedelivered()); Assert.assertEquals(1, tm.getIntProperty("JMSXDeliveryCount")); - tm = (TextMessage)c.receive(1000); + tm = (TextMessage) c.receive(1000); Assert.assertEquals("message4", tm.getText()); Assert.assertFalse(tm.getJMSRedelivered()); Assert.assertEquals(1, tm.getIntProperty("JMSXDeliveryCount")); - tm = (TextMessage)c.receive(1000); + tm = (TextMessage) c.receive(1000); Assert.assertEquals("message5", tm.getText()); Assert.assertFalse(tm.getJMSRedelivered()); @@ -199,22 +188,18 @@ public class JMSXDeliveryCountTest extends JMSTestBase tm.acknowledge(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testRedeliveryOnQueue() throws Exception - { + public void testRedeliveryOnQueue() throws Exception { Connection conn = null; - try - { + try { conn = cf.createConnection(); Session sess1 = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -227,8 +212,7 @@ public class JMSXDeliveryCountTest extends JMSTestBase final int NUM_RECOVERIES = 8; - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = sess1.createTextMessage(); tm.setText("testing" + i); prod.send(tm); @@ -242,41 +226,33 @@ public class JMSXDeliveryCountTest extends JMSTestBase TextMessage tm = null; - for (int j = 0; j < NUM_RECOVERIES; j++) - { - for (int i = 0; i < NUM_MESSAGES; i++) - { - tm = (TextMessage)cons.receive(3000); + for (int j = 0; j < NUM_RECOVERIES; j++) { + for (int i = 0; i < NUM_MESSAGES; i++) { + tm = (TextMessage) cons.receive(3000); Assert.assertNotNull(tm); Assert.assertEquals("testing" + i, tm.getText()); - Assert.assertTrue("JMSXDeliveryCount is supposed to exist as a property", - tm.propertyExists("JMSXDeliveryCount")); + Assert.assertTrue("JMSXDeliveryCount is supposed to exist as a property", tm.propertyExists("JMSXDeliveryCount")); Assert.assertEquals(j + 1, tm.getIntProperty("JMSXDeliveryCount")); } - if (j != NUM_RECOVERIES - 1) - { + if (j != NUM_RECOVERIES - 1) { sess2.recover(); } } tm.acknowledge(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testRedeliveryOnTopic() throws Exception - { + public void testRedeliveryOnTopic() throws Exception { Connection conn = null; - try - { + try { conn = cf.createConnection(); conn.setClientID("myclientid"); @@ -310,8 +286,7 @@ public class JMSXDeliveryCountTest extends JMSTestBase MessageProducer prod = sessSend.createProducer(topic1); prod.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm1 = sessSend.createTextMessage("testing" + i); prod.send(tm1); } @@ -328,22 +303,18 @@ public class JMSXDeliveryCountTest extends JMSTestBase sess3.unsubscribe("subxyz"); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testDeliveryCountUpdatedOnCloseTransacted() throws Exception - { + public void testDeliveryCountUpdatedOnCloseTransacted() throws Exception { Connection conn = null; - try - { + try { conn = cf.createConnection(); Session producerSess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -357,21 +328,20 @@ public class JMSXDeliveryCountTest extends JMSTestBase producer.send(tm); - TextMessage rm = (TextMessage)consumer.receive(1000); + TextMessage rm = (TextMessage) consumer.receive(1000); Assert.assertNotNull(rm); Assert.assertEquals(tm.getText(), rm.getText()); - Assert.assertTrue("JMSXDeliveryCount is supposed to exist as a property", - tm.propertyExists("JMSXDeliveryCount")); + Assert.assertTrue("JMSXDeliveryCount is supposed to exist as a property", tm.propertyExists("JMSXDeliveryCount")); Assert.assertEquals(1, rm.getIntProperty("JMSXDeliveryCount")); Assert.assertFalse(rm.getJMSRedelivered()); consumerSess.rollback(); - rm = (TextMessage)consumer.receive(1000); + rm = (TextMessage) consumer.receive(1000); Assert.assertNotNull(rm); @@ -383,7 +353,7 @@ public class JMSXDeliveryCountTest extends JMSTestBase consumerSess.rollback(); - rm = (TextMessage)consumer.receive(1000); + rm = (TextMessage) consumer.receive(1000); Assert.assertNotNull(rm); @@ -401,7 +371,7 @@ public class JMSXDeliveryCountTest extends JMSTestBase consumer = consumerSess.createConsumer(queue1); - rm = (TextMessage)consumer.receive(1000); + rm = (TextMessage) consumer.receive(1000); Assert.assertNotNull(rm); @@ -413,22 +383,18 @@ public class JMSXDeliveryCountTest extends JMSTestBase consumerSess.commit(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testDeliveryCountUpdatedOnCloseClientAck() throws Exception - { + public void testDeliveryCountUpdatedOnCloseClientAck() throws Exception { Connection conn = null; - try - { + try { conn = cf.createConnection(); Session producerSess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -442,7 +408,7 @@ public class JMSXDeliveryCountTest extends JMSTestBase producer.send(tm); - TextMessage rm = (TextMessage)consumer.receive(1000); + TextMessage rm = (TextMessage) consumer.receive(1000); Assert.assertNotNull(rm); @@ -454,7 +420,7 @@ public class JMSXDeliveryCountTest extends JMSTestBase consumerSess.recover(); - rm = (TextMessage)consumer.receive(1000); + rm = (TextMessage) consumer.receive(1000); Assert.assertNotNull(rm); @@ -466,7 +432,7 @@ public class JMSXDeliveryCountTest extends JMSTestBase consumerSess.recover(); - rm = (TextMessage)consumer.receive(1000); + rm = (TextMessage) consumer.receive(1000); Assert.assertNotNull(rm); @@ -484,7 +450,7 @@ public class JMSXDeliveryCountTest extends JMSTestBase consumer = consumerSess.createConsumer(queue1); - rm = (TextMessage)consumer.receive(1000); + rm = (TextMessage) consumer.receive(1000); Assert.assertNotNull(rm); @@ -496,18 +462,15 @@ public class JMSXDeliveryCountTest extends JMSTestBase rm.acknowledge(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testDeliveryCountUpdatedOnCloseXA() throws Exception - { + public void testDeliveryCountUpdatedOnCloseXA() throws Exception { XAConnection xaConn = null; Connection conn = null; @@ -517,8 +480,7 @@ public class JMSXDeliveryCountTest extends JMSTestBase Transaction tx = null; - try - { + try { toResume = mgr.suspend(); conn = cf.createConnection(); @@ -548,7 +510,7 @@ public class JMSXDeliveryCountTest extends JMSTestBase tx.enlistResource(consumerSess.getXAResource()); - TextMessage rm = (TextMessage)consumer.receive(1000); + TextMessage rm = (TextMessage) consumer.receive(1000); Assert.assertNotNull(rm); @@ -572,7 +534,7 @@ public class JMSXDeliveryCountTest extends JMSTestBase tx.enlistResource(consumerSess.getXAResource()); - rm = (TextMessage)consumer.receive(1000); + rm = (TextMessage) consumer.receive(1000); Assert.assertNotNull(rm); @@ -596,7 +558,7 @@ public class JMSXDeliveryCountTest extends JMSTestBase tx.enlistResource(consumerSess.getXAResource()); - rm = (TextMessage)consumer.receive(1000); + rm = (TextMessage) consumer.receive(1000); Assert.assertNotNull(rm); @@ -630,7 +592,7 @@ public class JMSXDeliveryCountTest extends JMSTestBase tx.enlistResource(consumerSess.getXAResource()); - rm = (TextMessage)consumer.receive(1000); + rm = (TextMessage) consumer.receive(1000); Assert.assertNotNull(rm); @@ -644,43 +606,34 @@ public class JMSXDeliveryCountTest extends JMSTestBase tx.delistResource(consumerSess.getXAResource(), XAResource.TMSUCCESS); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } - if (tx != null) - { - try - { + if (tx != null) { + try { mgr.commit(); } - catch (Exception ignore) - { + catch (Exception ignore) { } } - if (xaConn != null) - { + if (xaConn != null) { xaConn.close(); } - if (toResume != null) - { - try - { + if (toResume != null) { + try { mgr.resume(toResume); } - catch (Exception ignore) - { + catch (Exception ignore) { } } } } - class Receiver implements Runnable - { + class Receiver implements Runnable { + MessageConsumer cons; int numMessages; @@ -697,8 +650,7 @@ public class JMSXDeliveryCountTest extends JMSTestBase final Session sess, final MessageConsumer cons, final int numMessages, - final int numRecoveries) - { + final int numRecoveries) { this.sess = sess; this.cons = cons; this.numMessages = numMessages; @@ -706,44 +658,35 @@ public class JMSXDeliveryCountTest extends JMSTestBase this.name = name; } - public void run() - { - try - { + public void run() { + try { Message lastMessage = null; - for (int j = 0; j < numRecoveries; j++) - { + for (int j = 0; j < numRecoveries; j++) { - for (int i = 0; i < numMessages; i++) - { - TextMessage tm = (TextMessage)cons.receive(); + for (int i = 0; i < numMessages; i++) { + TextMessage tm = (TextMessage) cons.receive(); lastMessage = tm; - if (tm == null) - { + if (tm == null) { failed = true; } - if (!tm.getText().equals("testing" + i)) - { + if (!tm.getText().equals("testing" + i)) { failed = true; } - if (tm.getIntProperty("JMSXDeliveryCount") != j + 1) - { + if (tm.getIntProperty("JMSXDeliveryCount") != j + 1) { failed = true; } } - if (j != numRecoveries - 1) - { + if (j != numRecoveries - 1) { sess.recover(); } } lastMessage.acknowledge(); } - catch (Exception e) - { + catch (Exception e) { failed = true; } } @@ -757,55 +700,44 @@ public class JMSXDeliveryCountTest extends JMSTestBase // Inner classes -------------------------------------------------------------------------------- - static class DummyXAResource implements XAResource - { - DummyXAResource() - { + static class DummyXAResource implements XAResource { + + DummyXAResource() { } - public void commit(final Xid arg0, final boolean arg1) throws XAException - { + public void commit(final Xid arg0, final boolean arg1) throws XAException { } - public void end(final Xid arg0, final int arg1) throws XAException - { + public void end(final Xid arg0, final int arg1) throws XAException { } - public void forget(final Xid arg0) throws XAException - { + public void forget(final Xid arg0) throws XAException { } - public int getTransactionTimeout() throws XAException - { + public int getTransactionTimeout() throws XAException { return 0; } - public boolean isSameRM(final XAResource arg0) throws XAException - { + public boolean isSameRM(final XAResource arg0) throws XAException { return false; } - public int prepare(final Xid arg0) throws XAException - { + public int prepare(final Xid arg0) throws XAException { return XAResource.XA_OK; } - public Xid[] recover(final int arg0) throws XAException - { + public Xid[] recover(final int arg0) throws XAException { return null; } - public void rollback(final Xid arg0) throws XAException - { + public void rollback(final Xid arg0) throws XAException { } - public boolean setTransactionTimeout(final int arg0) throws XAException - { + public boolean setTransactionTimeout(final int arg0) throws XAException { return false; } - public void start(final Xid arg0, final int arg1) throws XAException - { + public void start(final Xid arg0, final int arg1) throws XAException { } diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/xa/XATest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/xa/XATest.java index cc5f4f7519..fbc975de51 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/xa/XATest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/jms/xa/XATest.java @@ -46,8 +46,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class XATest extends JMSTestBase -{ +public class XATest extends JMSTestBase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -68,8 +67,7 @@ public class XATest extends JMSTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); xacf = ActiveMQJMSClient.createConnectionFactory("tcp://localhost:61616", "test"); @@ -86,33 +84,26 @@ public class XATest extends JMSTestBase @Override @After - public void tearDown() throws Exception - { - if (TxUtils.isUncommitted(tm)) - { + public void tearDown() throws Exception { + if (TxUtils.isUncommitted(tm)) { // roll it back - try - { + try { tm.rollback(); } - catch (Throwable ignore) - { + catch (Throwable ignore) { // The connection will probably be closed so this may well throw an exception } } - if (tm.getTransaction() != null) - { + if (tm.getTransaction() != null) { Transaction tx = tm.suspend(); - if (tx != null) - { + if (tx != null) { ExtrasTestLogger.LOGGER.warn("Transaction still associated with thread " + tx + " at status " + TxUtils.getStatusAsString(tx.getStatus())); } } - if (suspendedTx != null) - { + if (suspendedTx != null) { tm.resume(suspendedTx); } @@ -127,15 +118,13 @@ public class XATest extends JMSTestBase // Public -------------------------------------------------------- @Test - public void test2PCSendCommit1PCOptimization() throws Exception - { + public void test2PCSendCommit1PCOptimization() throws Exception { // Since both resources have same RM, TM will probably use 1PC optimization XAConnection conn = null; Connection conn2 = null; - try - { + try { conn = xacf.createXAConnection(); tm.begin(); @@ -172,27 +161,22 @@ public class XATest extends JMSTestBase Assert.assertNotNull(m2); Assert.assertEquals("XATest2", m2.getText()); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } } @Test - public void test2PCSendCommit() throws Exception - { + public void test2PCSendCommit() throws Exception { XAConnection conn = null; Connection conn2 = null; - try - { + try { conn = xacf.createXAConnection(); tm.begin(); @@ -234,26 +218,21 @@ public class XATest extends JMSTestBase Assert.assertNotNull(m2); Assert.assertEquals("XATest2", m2.getText()); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } } @Test - public void test2PCSendFailOnPrepare() throws Exception - { + public void test2PCSendFailOnPrepare() throws Exception { XAConnection conn = null; Connection conn2 = null; - try - { + try { conn = xacf.createXAConnection(); tm.begin(); @@ -286,14 +265,12 @@ public class XATest extends JMSTestBase tx.delistResource(res3, XAResource.TMSUCCESS); tx.delistResource(res4, XAResource.TMSUCCESS); - try - { + try { tm.commit(); Assert.fail("should not get here"); } - catch (Exception e) - { + catch (Exception e) { // We should expect this } @@ -304,26 +281,21 @@ public class XATest extends JMSTestBase Message m2 = cons.receive(100); Assert.assertNull(m2); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } } @Test - public void test2PCSendRollback() throws Exception - { + public void test2PCSendRollback() throws Exception { XAConnection conn = null; Connection conn2 = null; - try - { + try { conn = xacf.createXAConnection(); tm.begin(); @@ -360,29 +332,24 @@ public class XATest extends JMSTestBase Assert.assertNull(m2); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } } @Test - public void test2PCReceiveCommit1PCOptimization() throws Exception - { + public void test2PCReceiveCommit1PCOptimization() throws Exception { // Since both resources have some RM, TM will probably use 1PC optimization XAConnection conn = null; Connection conn2 = null; - try - { + try { conn2 = cf.createConnection(); conn2.start(); Session sessProducer = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -438,14 +405,11 @@ public class XATest extends JMSTestBase tm.commit(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } @@ -453,13 +417,11 @@ public class XATest extends JMSTestBase } @Test - public void test2PCReceiveCommit() throws Exception - { + public void test2PCReceiveCommit() throws Exception { XAConnection conn = null; Connection conn2 = null; - try - { + try { conn2 = cf.createConnection(); conn2.start(); Session sessProducer = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -516,14 +478,11 @@ public class XATest extends JMSTestBase tm.commit(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } @@ -531,15 +490,13 @@ public class XATest extends JMSTestBase } @Test - public void test2PCReceiveRollback1PCOptimization() throws Exception - { + public void test2PCReceiveRollback1PCOptimization() throws Exception { // Since both resources have some RM, TM will probably use 1PC optimization XAConnection conn = null; Connection conn2 = null; - try - { + try { conn2 = cf.createConnection(); Session sessProducer = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = sessProducer.createProducer(queue1); @@ -599,27 +556,22 @@ public class XATest extends JMSTestBase tm.commit(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } } @Test - public void test2PCReceiveRollback() throws Exception - { + public void test2PCReceiveRollback() throws Exception { XAConnection conn = null; Connection conn2 = null; - try - { + try { conn2 = cf.createConnection(); Session sessProducer = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = sessProducer.createProducer(queue1); @@ -681,14 +633,11 @@ public class XATest extends JMSTestBase tm.commit(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } @@ -696,13 +645,11 @@ public class XATest extends JMSTestBase } @Test - public void test1PCSendCommit() throws Exception - { + public void test1PCSendCommit() throws Exception { XAConnection conn = null; Connection conn2 = null; - try - { + try { conn = xacf.createXAConnection(); tm.begin(); @@ -735,14 +682,11 @@ public class XATest extends JMSTestBase Assert.assertNotNull(m2); Assert.assertEquals("XATest2", m2.getText()); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } @@ -750,13 +694,11 @@ public class XATest extends JMSTestBase } @Test - public void test1PCReceiveCommit() throws Exception - { + public void test1PCReceiveCommit() throws Exception { XAConnection conn = null; Connection conn2 = null; - try - { + try { conn2 = cf.createConnection(); conn2.start(); Session sessProducer = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -805,14 +747,11 @@ public class XATest extends JMSTestBase tm.commit(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } @@ -820,13 +759,11 @@ public class XATest extends JMSTestBase } @Test - public void test1PCReceiveRollback() throws Exception - { + public void test1PCReceiveRollback() throws Exception { XAConnection conn = null; Connection conn2 = null; - try - { + try { conn2 = cf.createConnection(); Session sessProducer = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = sessProducer.createProducer(queue1); @@ -886,14 +823,11 @@ public class XATest extends JMSTestBase tm.commit(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } @@ -901,15 +835,13 @@ public class XATest extends JMSTestBase } @Test - public void testMultipleSessionsOneTxCommitAcknowledge1PCOptimization() throws Exception - { + public void testMultipleSessionsOneTxCommitAcknowledge1PCOptimization() throws Exception { XAConnection conn = null; Connection conn2 = null; // Since both resources have some RM, TM will probably use 1PC optimization - try - { + try { // First send 2 messages conn2 = cf.createConnection(); Session sessProducer = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -963,14 +895,11 @@ public class XATest extends JMSTestBase Assert.assertNull(r3); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } @@ -978,13 +907,11 @@ public class XATest extends JMSTestBase } @Test - public void testMultipleSessionsOneTxCommitAcknowledge() throws Exception - { + public void testMultipleSessionsOneTxCommitAcknowledge() throws Exception { XAConnection conn = null; Connection conn2 = null; - try - { + try { // First send 2 messages conn2 = cf.createConnection(); Session sessProducer = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -1040,14 +967,11 @@ public class XATest extends JMSTestBase Assert.assertNull(r3); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } @@ -1055,15 +979,13 @@ public class XATest extends JMSTestBase } @Test - public void testMultipleSessionsOneTxRollbackAcknowledge1PCOptimization() throws Exception - { + public void testMultipleSessionsOneTxRollbackAcknowledge1PCOptimization() throws Exception { XAConnection conn = null; Connection conn2 = null; // Since both resources have some RM, TM will probably use 1PC optimization - try - { + try { // First send 2 messages conn2 = cf.createConnection(); Session sessProducer = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -1141,21 +1063,17 @@ public class XATest extends JMSTestBase boolean session1First = false; - if (r.getText().equals("jellyfish1")) - { + if (r.getText().equals("jellyfish1")) { session1First = true; } - else if (r.getText().equals("jellyfish3")) - { + else if (r.getText().equals("jellyfish3")) { session1First = false; } - else - { + else { Assert.fail("Unexpected message"); } - if (session1First) - { + if (session1First) { r = (TextMessage) cons.receive(5000); Assert.assertNotNull(r); @@ -1175,8 +1093,7 @@ public class XATest extends JMSTestBase Assert.assertEquals("jellyfish4", r.getText()); } - else - { + else { r = (TextMessage) cons.receive(5000); Assert.assertNotNull(r); @@ -1201,14 +1118,11 @@ public class XATest extends JMSTestBase Assert.assertNull(r); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } @@ -1216,13 +1130,11 @@ public class XATest extends JMSTestBase } @Test - public void testMultipleSessionsOneTxRollbackAcknowledge() throws Exception - { + public void testMultipleSessionsOneTxRollbackAcknowledge() throws Exception { XAConnection conn = null; Connection conn2 = null; - try - { + try { // First send 2 messages conn2 = cf.createConnection(); Session sessProducer = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -1305,21 +1217,17 @@ public class XATest extends JMSTestBase boolean session1First = false; - if (r.getText().equals("jellyfish1")) - { + if (r.getText().equals("jellyfish1")) { session1First = true; } - else if (r.getText().equals("jellyfish3")) - { + else if (r.getText().equals("jellyfish3")) { session1First = false; } - else - { + else { Assert.fail("Unexpected message"); } - if (session1First) - { + if (session1First) { r = (TextMessage) cons.receive(5000); Assert.assertNotNull(r); @@ -1339,8 +1247,7 @@ public class XATest extends JMSTestBase Assert.assertEquals("jellyfish4", r.getText()); } - else - { + else { r = (TextMessage) cons.receive(5000); Assert.assertNotNull(r); @@ -1364,27 +1271,22 @@ public class XATest extends JMSTestBase Assert.assertNull(r); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } } @Test - public void testMultipleSessionsOneTxRollbackAcknowledgeForceFailureInCommit() throws Exception - { + public void testMultipleSessionsOneTxRollbackAcknowledgeForceFailureInCommit() throws Exception { XAConnection conn = null; Connection conn2 = null; - try - { + try { // First send 4 messages conn2 = cf.createConnection(); Session sessProducer = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -1449,13 +1351,11 @@ public class XATest extends JMSTestBase // the original consumer has closed, so it will cancelled to the server // the server cancel is asynch, so we need to sleep for a bit to make sure it completes ExtrasTestLogger.LOGGER.trace("Forcing failure"); - try - { + try { tm.commit(); Assert.fail("should not get here"); } - catch (Exception e) - { + catch (Exception e) { // We should expect this } @@ -1493,14 +1393,11 @@ public class XATest extends JMSTestBase Assert.assertNull(r); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } @@ -1508,16 +1405,14 @@ public class XATest extends JMSTestBase } @Test - public void testMultipleSessionsOneTxCommitSend1PCOptimization() throws Exception - { + public void testMultipleSessionsOneTxCommitSend1PCOptimization() throws Exception { // Since both resources have some RM, TM will probably use 1PC optimization XAConnection conn = null; Connection conn2 = null; - try - { + try { conn = xacf.createXAConnection(); conn.start(); @@ -1563,30 +1458,25 @@ public class XATest extends JMSTestBase Assert.assertEquals("echidna2", r2.getText()); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } } @Test - public void testMultipleSessionsOneTxCommitSend() throws Exception - { + public void testMultipleSessionsOneTxCommitSend() throws Exception { // Since both resources have some RM, TM will probably use 1PC optimization XAConnection conn = null; Connection conn2 = null; - try - { + try { conn = xacf.createXAConnection(); conn.start(); @@ -1635,14 +1525,11 @@ public class XATest extends JMSTestBase Assert.assertEquals("echidna2", r2.getText()); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } @@ -1651,16 +1538,14 @@ public class XATest extends JMSTestBase } @Test - public void testMultipleSessionsOneTxRollbackSend1PCOptimization() throws Exception - { + public void testMultipleSessionsOneTxRollbackSend1PCOptimization() throws Exception { // Since both resources have some RM, TM will probably use 1PC optimization XAConnection conn = null; Connection conn2 = null; - try - { + try { conn = xacf.createXAConnection(); conn.start(); @@ -1701,28 +1586,23 @@ public class XATest extends JMSTestBase Assert.assertNull(r1); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } } @Test - public void testMultipleSessionsOneTxRollbackSend() throws Exception - { + public void testMultipleSessionsOneTxRollbackSend() throws Exception { XAConnection conn = null; Connection conn2 = null; - try - { + try { conn = xacf.createXAConnection(); conn.start(); @@ -1765,28 +1645,23 @@ public class XATest extends JMSTestBase TextMessage r1 = (TextMessage) cons.receive(100); Assert.assertNull(r1); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } } @Test - public void testOneSessionTwoTransactionsCommitAcknowledge() throws Exception - { + public void testOneSessionTwoTransactionsCommitAcknowledge() throws Exception { XAConnection conn = null; Connection conn2 = null; - try - { + try { // First send 2 messages conn2 = cf.createConnection(); Session sessProducer = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -1850,28 +1725,23 @@ public class XATest extends JMSTestBase tm.commit(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } } @Test - public void testOneSessionTwoTransactionsRollbackAcknowledge() throws Exception - { + public void testOneSessionTwoTransactionsRollbackAcknowledge() throws Exception { XAConnection conn = null; Connection conn2 = null; - try - { + try { // First send 2 messages conn2 = cf.createConnection(); Session sessProducer = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -1949,14 +1819,11 @@ public class XATest extends JMSTestBase Assert.assertNull(r3); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } @@ -1965,14 +1832,12 @@ public class XATest extends JMSTestBase } @Test - public void testOneSessionTwoTransactionsCommitSend() throws Exception - { + public void testOneSessionTwoTransactionsCommitSend() throws Exception { XAConnection conn = null; Connection conn2 = null; - try - { + try { conn = xacf.createXAConnection(); // Create a session @@ -2030,14 +1895,11 @@ public class XATest extends JMSTestBase Assert.assertEquals("kangaroo1", r3.getText()); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } @@ -2046,8 +1908,7 @@ public class XATest extends JMSTestBase } @Test - public void testIsSamRM() throws Exception - { + public void testIsSamRM() throws Exception { XAConnection conn = null; conn = xacf.createXAConnection(); @@ -2063,66 +1924,53 @@ public class XATest extends JMSTestBase Assert.assertTrue(res1.isSameRM(res2)); } - static class DummyXAResource implements XAResource - { + static class DummyXAResource implements XAResource { + boolean failOnPrepare; - DummyXAResource() - { + DummyXAResource() { } - DummyXAResource(final boolean failOnPrepare) - { + DummyXAResource(final boolean failOnPrepare) { this.failOnPrepare = failOnPrepare; } - public void commit(final Xid arg0, final boolean arg1) throws XAException - { + public void commit(final Xid arg0, final boolean arg1) throws XAException { } - public void end(final Xid arg0, final int arg1) throws XAException - { + public void end(final Xid arg0, final int arg1) throws XAException { } - public void forget(final Xid arg0) throws XAException - { + public void forget(final Xid arg0) throws XAException { } - public int getTransactionTimeout() throws XAException - { + public int getTransactionTimeout() throws XAException { return 0; } - public boolean isSameRM(final XAResource arg0) throws XAException - { + public boolean isSameRM(final XAResource arg0) throws XAException { return false; } - public int prepare(final Xid arg0) throws XAException - { - if (failOnPrepare) - { + public int prepare(final Xid arg0) throws XAException { + if (failOnPrepare) { throw new XAException(XAException.XAER_RMFAIL); } return XAResource.XA_OK; } - public Xid[] recover(final int arg0) throws XAException - { + public Xid[] recover(final int arg0) throws XAException { return null; } - public void rollback(final Xid arg0) throws XAException - { + public void rollback(final Xid arg0) throws XAException { } - public boolean setTransactionTimeout(final int arg0) throws XAException - { + public boolean setTransactionTimeout(final int arg0) throws XAException { return false; } - public void start(final Xid arg0, final int arg1) throws XAException - { + public void start(final Xid arg0, final int arg1) throws XAException { } diff --git a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/protocols/hornetq/HornetQProtocolTest.java b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/protocols/hornetq/HornetQProtocolTest.java index 20802f01f0..789e73a6a6 100644 --- a/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/protocols/hornetq/HornetQProtocolTest.java +++ b/tests/extra-tests/src/test/java/org/apache/activemq/artemis/tests/extras/protocols/hornetq/HornetQProtocolTest.java @@ -38,15 +38,14 @@ import java.util.HashMap; import java.util.Map; import java.util.UUID; -public class HornetQProtocolTest extends ActiveMQTestBase -{ +public class HornetQProtocolTest extends ActiveMQTestBase { + protected ActiveMQServer server; private static final Logger LOG = LoggerFactory.getLogger(HornetQProtocolTest.class); @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { HashMap params = new HashMap(); params.put(org.hornetq.core.remoting.impl.netty.TransportConstants.PORT_PROP_NAME, "" + 5445); params.put(org.hornetq.core.remoting.impl.netty.TransportConstants.PROTOCOLS_PROP_NAME, "HORNETQ"); @@ -61,8 +60,7 @@ public class HornetQProtocolTest extends ActiveMQTestBase } @Test - public void testMessagePropertiesAreTransformedBetweenCoreAndHQProtocols() throws Exception - { + public void testMessagePropertiesAreTransformedBetweenCoreAndHQProtocols() throws Exception { org.hornetq.api.core.client.ClientSession hqSession = createHQClientSession(); ClientSession coreSession = createCoreClientSession(); @@ -80,8 +78,7 @@ public class HornetQProtocolTest extends ActiveMQTestBase ClientConsumer coreConsumer = coreSession.createConsumer(queueName); // Check that HornetQ Properties are correctly converted to core properties. - for (int i = 0; i < 2; i++) - { + for (int i = 0; i < 2; i++) { hqProducer.send(createHQTestMessage(hqSession)); } @@ -97,8 +94,7 @@ public class HornetQProtocolTest extends ActiveMQTestBase } @Test - public void testDuplicateIDPropertyWithHornetQProtocol() throws Exception - { + public void testDuplicateIDPropertyWithHornetQProtocol() throws Exception { org.hornetq.api.core.client.ClientSession session = createHQClientSession(); String queueName = "test.hq.queue"; @@ -129,8 +125,7 @@ public class HornetQProtocolTest extends ActiveMQTestBase } @Test - public void testDuplicateIDPropertyWithHornetQAndCoreProtocol() throws Exception - { + public void testDuplicateIDPropertyWithHornetQAndCoreProtocol() throws Exception { org.hornetq.api.core.client.ClientSession hqSession = createHQClientSession(); String queueName = "test.hq.queue"; @@ -153,7 +148,6 @@ public class HornetQProtocolTest extends ActiveMQTestBase assertTrue(m.containsProperty(Message.HDR_DUPLICATE_DETECTION_ID)); assertNotNull(m); - hqProducer.send(message); m = coreConsumer.receive(1000); assertNull(m); @@ -163,24 +157,21 @@ public class HornetQProtocolTest extends ActiveMQTestBase assertNull(m); } - private org.hornetq.api.core.client.ClientMessage createHQTestMessage(org.hornetq.api.core.client.ClientSession session) - { + private org.hornetq.api.core.client.ClientMessage createHQTestMessage(org.hornetq.api.core.client.ClientSession session) { org.hornetq.api.core.client.ClientMessage message = session.createMessage(false); String v = UUID.randomUUID().toString(); message.putStringProperty(org.hornetq.api.core.Message.HDR_DUPLICATE_DETECTION_ID.toString(), v); return message; } - private ClientMessage createCoreTestMessage(ClientSession session) - { + private ClientMessage createCoreTestMessage(ClientSession session) { ClientMessage message = session.createMessage(false); String v = UUID.randomUUID().toString(); message.putStringProperty(org.hornetq.api.core.Message.HDR_DUPLICATE_DETECTION_ID.toString(), v); return message; } - private org.hornetq.api.core.client.ClientSession createHQClientSession() throws Exception - { + private org.hornetq.api.core.client.ClientSession createHQClientSession() throws Exception { Map map = new HashMap(); map.put("host", "localhost"); map.put("port", 5445); @@ -191,8 +182,7 @@ public class HornetQProtocolTest extends ActiveMQTestBase return sf.createSession(); } - private ClientSession createCoreClientSession() throws Exception - { + private ClientSession createCoreClientSession() throws Exception { Map map = new HashMap(); map.put("host", "localhost"); map.put("port", 61616); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/DuplicateDetectionTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/DuplicateDetectionTest.java index 93020e5d94..05a48e90a7 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/DuplicateDetectionTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/DuplicateDetectionTest.java @@ -41,8 +41,8 @@ import javax.transaction.xa.XAException; import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; -public class DuplicateDetectionTest extends ActiveMQTestBase -{ +public class DuplicateDetectionTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private ActiveMQServer server; @@ -52,8 +52,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase private final int cacheSize = 10; @Test - public void testSimpleDuplicateDetecion() throws Exception - { + public void testSimpleDuplicateDetecion() throws Exception { ClientSession session = sf.createSession(false, true, true); session.start(); @@ -113,20 +112,17 @@ public class DuplicateDetectionTest extends ActiveMQTestBase } @Test - public void testDuplicateIDCacheMemoryRetentionForNonTemporaryQueues() throws Exception - { + public void testDuplicateIDCacheMemoryRetentionForNonTemporaryQueues() throws Exception { testDuplicateIDCacheMemoryRetention(false); } @Test - public void testDuplicateIDCacheMemoryRetentionForTemporaryQueues() throws Exception - { + public void testDuplicateIDCacheMemoryRetentionForTemporaryQueues() throws Exception { testDuplicateIDCacheMemoryRetention(true); } @Test - public void testDuplicateIDCacheJournalRetentionForNonTemporaryQueues() throws Exception - { + public void testDuplicateIDCacheJournalRetentionForNonTemporaryQueues() throws Exception { testDuplicateIDCacheMemoryRetention(false); server.stop(); @@ -139,8 +135,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase } @Test - public void testDuplicateIDCacheJournalRetentionForTemporaryQueues() throws Exception - { + public void testDuplicateIDCacheJournalRetentionForTemporaryQueues() throws Exception { testDuplicateIDCacheMemoryRetention(true); server.stop(); @@ -152,12 +147,10 @@ public class DuplicateDetectionTest extends ActiveMQTestBase Assert.assertEquals(0, ((PostOfficeImpl) server.getPostOffice()).getDuplicateIDCaches().size()); } - public void testDuplicateIDCacheMemoryRetention(boolean temporary) throws Exception - { + public void testDuplicateIDCacheMemoryRetention(boolean temporary) throws Exception { final int TEST_SIZE = 100; - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true); + locator = createInVMNonHALocator().setBlockOnNonDurableSend(true); sf = createSessionFactory(locator); @@ -169,16 +162,13 @@ public class DuplicateDetectionTest extends ActiveMQTestBase final SimpleString addressName = new SimpleString("DuplicateDetectionTestAddress"); - for (int i = 0; i < TEST_SIZE; i++) - { + for (int i = 0; i < TEST_SIZE; i++) { final SimpleString queueName = new SimpleString("DuplicateDetectionTestQueue_" + i); - if (temporary) - { + if (temporary) { session.createTemporaryQueue(addressName, queueName, null); } - else - { + else { session.createQueue(addressName, queueName, null, true); } @@ -224,8 +214,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase } @Test - public void testSimpleDuplicateDetectionWithString() throws Exception - { + public void testSimpleDuplicateDetectionWithString() throws Exception { ClientSession session = sf.createSession(false, true, true); session.start(); @@ -285,8 +274,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase } @Test - public void testCacheSize() throws Exception - { + public void testCacheSize() throws Exception { ClientSession session = sf.createSession(false, true, true); session.start(); @@ -312,8 +300,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase ClientProducer producer3 = session.createProducer(queueName3); ClientConsumer consumer3 = session.createConsumer(queueName3); - for (int i = 0; i < cacheSize; i++) - { + for (int i = 0; i < cacheSize; i++) { SimpleString dupID = new SimpleString("dupID" + i); ClientMessage message = createMessage(session, i); @@ -325,8 +312,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase producer3.send(message); } - for (int i = 0; i < cacheSize; i++) - { + for (int i = 0; i < cacheSize; i++) { ClientMessage message = consumer1.receive(1000); Assert.assertNotNull(message); Assert.assertEquals(i, message.getObjectProperty(propKey)); @@ -339,8 +325,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase } DuplicateDetectionTest.log.info("Now sending more"); - for (int i = 0; i < cacheSize; i++) - { + for (int i = 0; i < cacheSize; i++) { SimpleString dupID = new SimpleString("dupID" + i); ClientMessage message = createMessage(session, i); @@ -359,8 +344,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase message = consumer3.receiveImmediate(); Assert.assertNull(message); - for (int i = 0; i < cacheSize; i++) - { + for (int i = 0; i < cacheSize; i++) { SimpleString dupID = new SimpleString("dupID2-" + i); message = createMessage(session, i); @@ -372,8 +356,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase producer3.send(message); } - for (int i = 0; i < cacheSize; i++) - { + for (int i = 0; i < cacheSize; i++) { message = consumer1.receive(1000); Assert.assertNotNull(message); Assert.assertEquals(i, message.getObjectProperty(propKey)); @@ -385,8 +368,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase Assert.assertEquals(i, message.getObjectProperty(propKey)); } - for (int i = 0; i < cacheSize; i++) - { + for (int i = 0; i < cacheSize; i++) { SimpleString dupID = new SimpleString("dupID2-" + i); message = createMessage(session, i); @@ -407,8 +389,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase // Should be able to send the first lot again now - since the second lot pushed the // first lot out of the cache - for (int i = 0; i < cacheSize; i++) - { + for (int i = 0; i < cacheSize; i++) { SimpleString dupID = new SimpleString("dupID" + i); message = createMessage(session, i); @@ -420,8 +401,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase producer3.send(message); } - for (int i = 0; i < cacheSize; i++) - { + for (int i = 0; i < cacheSize; i++) { message = consumer1.receive(1000); Assert.assertNotNull(message); Assert.assertEquals(i, message.getObjectProperty(propKey)); @@ -435,8 +415,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase } @Test - public void testTransactedDuplicateDetection1() throws Exception - { + public void testTransactedDuplicateDetection1() throws Exception { ClientSession session = sf.createSession(false, false, false); session.start(); @@ -478,8 +457,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase } @Test - public void testTransactedDuplicateDetection2() throws Exception - { + public void testTransactedDuplicateDetection2() throws Exception { ClientSession session = sf.createSession(false, false, false); session.start(); @@ -515,8 +493,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase } @Test - public void testTransactedDuplicateDetection3() throws Exception - { + public void testTransactedDuplicateDetection3() throws Exception { ClientSession session = sf.createSession(false, false, false); session.start(); @@ -551,12 +528,10 @@ public class DuplicateDetectionTest extends ActiveMQTestBase message.putBytesProperty(Message.HDR_DUPLICATE_DETECTION_ID, dupID2.getData()); producer.send(message); - try - { + try { session.commit(); } - catch (Exception e) - { + catch (Exception e) { session.rollback(); } @@ -571,8 +546,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase } @Test - public void testRollbackThenSend() throws Exception - { + public void testRollbackThenSend() throws Exception { ClientSession session = sf.createSession(false, false, false); session.start(); @@ -610,8 +584,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase * Even if not all entries have dupl id header */ @Test - public void testEntireTransactionRejected() throws Exception - { + public void testEntireTransactionRejected() throws Exception { ClientSession session = sf.createSession(false, false, false); session.start(); @@ -664,17 +637,13 @@ public class DuplicateDetectionTest extends ActiveMQTestBase assertNotNull(message); message.acknowledge(); - - try - { + try { session.commit(); } - catch (ActiveMQDuplicateIdException die) - { + catch (ActiveMQDuplicateIdException die) { session.rollback(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } @@ -686,7 +655,6 @@ public class DuplicateDetectionTest extends ActiveMQTestBase message = consumer.receiveImmediate(); Assert.assertNull(message); - message = consumer2.receive(5000); assertNotNull(message); @@ -696,8 +664,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase } @Test - public void testXADuplicateDetection1() throws Exception - { + public void testXADuplicateDetection1() throws Exception { ClientSession session = sf.createSession(true, false, false); Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); @@ -766,8 +733,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase } @Test - public void testXADuplicateDetection2() throws Exception - { + public void testXADuplicateDetection2() throws Exception { ClientSession session = sf.createSession(true, false, false); Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); @@ -838,8 +804,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase } @Test - public void testXADuplicateDetection3() throws Exception - { + public void testXADuplicateDetection3() throws Exception { ClientSession session = sf.createSession(true, false, false); Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); @@ -909,8 +874,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase } @Test - public void testXADuplicateDetectionPrepareAndRollback() throws Exception - { + public void testXADuplicateDetectionPrepareAndRollback() throws Exception { ClientSession session = sf.createSession(true, false, false); Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); @@ -972,8 +936,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase } @Test - public void testXADuplicateDetectionPrepareAndRollbackStopServer() throws Exception - { + public void testXADuplicateDetectionPrepareAndRollbackStopServer() throws Exception { ClientSession session = sf.createSession(true, false, false); Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); @@ -1051,8 +1014,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase } @Test - public void testXADuplicateDetection4() throws Exception - { + public void testXADuplicateDetection4() throws Exception { ClientSession session = sf.createSession(true, false, false); Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); @@ -1100,13 +1062,11 @@ public class DuplicateDetectionTest extends ActiveMQTestBase session.end(xid2, XAResource.TMSUCCESS); - try - { + try { session.prepare(xid2); fail("Should throw an exception here!"); } - catch (XAException expected) - { + catch (XAException expected) { assertTrue(expected.getCause().toString().contains("DUPLICATE_ID_REJECTED")); } @@ -1131,8 +1091,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase session.commit(xid3, false); } - private ClientMessage createMessage(final ClientSession session, final int i) - { + private ClientMessage createMessage(final ClientSession session, final int i) { ClientMessage message = session.createMessage(false); message.putIntProperty(propKey, i); @@ -1141,12 +1100,10 @@ public class DuplicateDetectionTest extends ActiveMQTestBase } @Test - public void testDuplicateCachePersisted() throws Exception - { + public void testDuplicateCachePersisted() throws Exception { server.stop(); - config = createDefaultInVMConfig() - .setIDCacheSize(cacheSize); + config = createDefaultInVMConfig().setIDCacheSize(cacheSize); server = createServer(config); @@ -1216,14 +1173,12 @@ public class DuplicateDetectionTest extends ActiveMQTestBase } @Test - public void testDuplicateCachePersisted2() throws Exception - { + public void testDuplicateCachePersisted2() throws Exception { server.stop(); final int theCacheSize = 5; - config = createDefaultInVMConfig() - .setIDCacheSize(theCacheSize); + config = createDefaultInVMConfig().setIDCacheSize(theCacheSize); server = createServer(config); @@ -1243,8 +1198,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(queueName); - for (int i = 0; i < theCacheSize; i++) - { + for (int i = 0; i < theCacheSize; i++) { ClientMessage message = createMessage(session, i); SimpleString dupID = new SimpleString("abcdefg" + i); message.putBytesProperty(Message.HDR_DUPLICATE_DETECTION_ID, dupID.getData()); @@ -1275,8 +1229,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase consumer = session.createConsumer(queueName); - for (int i = 0; i < theCacheSize; i++) - { + for (int i = 0; i < theCacheSize; i++) { ClientMessage message = createMessage(session, i); SimpleString dupID = new SimpleString("abcdefg" + i); message.putBytesProperty(Message.HDR_DUPLICATE_DETECTION_ID, dupID.getData()); @@ -1287,15 +1240,13 @@ public class DuplicateDetectionTest extends ActiveMQTestBase } @Test - public void testDuplicateCachePersistedRestartWithSmallerCache() throws Exception - { + public void testDuplicateCachePersistedRestartWithSmallerCache() throws Exception { server.stop(); final int initialCacheSize = 10; final int subsequentCacheSize = 5; - config = createDefaultInVMConfig() - .setIDCacheSize(initialCacheSize); + config = createDefaultInVMConfig().setIDCacheSize(initialCacheSize); server = createServer(config); @@ -1315,8 +1266,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(queueName); - for (int i = 0; i < initialCacheSize; i++) - { + for (int i = 0; i < initialCacheSize; i++) { ClientMessage message = createMessage(session, i); SimpleString dupID = new SimpleString("abcdefg" + i); message.putBytesProperty(Message.HDR_DUPLICATE_DETECTION_ID, dupID.getData()); @@ -1351,20 +1301,17 @@ public class DuplicateDetectionTest extends ActiveMQTestBase consumer = session.createConsumer(queueName); - for (int i = 0; i < initialCacheSize; i++) - { + for (int i = 0; i < initialCacheSize; i++) { ClientMessage message = createMessage(session, i); SimpleString dupID = new SimpleString("abcdefg" + i); message.putBytesProperty(Message.HDR_DUPLICATE_DETECTION_ID, dupID.getData()); producer.send(message); - if (i >= subsequentCacheSize) - { + if (i >= subsequentCacheSize) { // Message should get through ClientMessage message2 = consumer.receive(1000); Assert.assertEquals(i, message2.getObjectProperty(propKey)); } - else - { + else { ClientMessage message2 = consumer.receiveImmediate(); Assert.assertNull(message2); } @@ -1372,15 +1319,13 @@ public class DuplicateDetectionTest extends ActiveMQTestBase } @Test - public void testDuplicateCachePersistedRestartWithSmallerCacheEnsureDeleted() throws Exception - { + public void testDuplicateCachePersistedRestartWithSmallerCacheEnsureDeleted() throws Exception { server.stop(); final int initialCacheSize = 10; final int subsequentCacheSize = 5; - config = createDefaultInVMConfig() - .setIDCacheSize(initialCacheSize); + config = createDefaultInVMConfig().setIDCacheSize(initialCacheSize); server = createServer(config); @@ -1400,8 +1345,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(queueName); - for (int i = 0; i < initialCacheSize; i++) - { + for (int i = 0; i < initialCacheSize; i++) { ClientMessage message = createMessage(session, i); SimpleString dupID = new SimpleString("abcdefg" + i); message.putBytesProperty(Message.HDR_DUPLICATE_DETECTION_ID, dupID.getData()); @@ -1448,20 +1392,17 @@ public class DuplicateDetectionTest extends ActiveMQTestBase consumer = session.createConsumer(queueName); - for (int i = 0; i < initialCacheSize; i++) - { + for (int i = 0; i < initialCacheSize; i++) { ClientMessage message = createMessage(session, i); SimpleString dupID = new SimpleString("abcdefg" + i); message.putBytesProperty(Message.HDR_DUPLICATE_DETECTION_ID, dupID.getData()); producer.send(message); - if (i >= subsequentCacheSize) - { + if (i >= subsequentCacheSize) { // Message should get through ClientMessage message2 = consumer.receive(1000); Assert.assertEquals(i, message2.getObjectProperty(propKey)); } - else - { + else { ClientMessage message2 = consumer.receiveImmediate(); Assert.assertNull(message2); } @@ -1469,13 +1410,10 @@ public class DuplicateDetectionTest extends ActiveMQTestBase } @Test - public void testNoPersist() throws Exception - { + public void testNoPersist() throws Exception { server.stop(); - config = createDefaultInVMConfig() - .setIDCacheSize(cacheSize) - .setPersistIDCache(false); + config = createDefaultInVMConfig().setIDCacheSize(cacheSize).setPersistIDCache(false); server = createServer(config); @@ -1545,13 +1483,10 @@ public class DuplicateDetectionTest extends ActiveMQTestBase } @Test - public void testNoPersistTransactional() throws Exception - { + public void testNoPersistTransactional() throws Exception { server.stop(); - config = createDefaultInVMConfig() - .setIDCacheSize(cacheSize) - .setPersistIDCache(false); + config = createDefaultInVMConfig().setIDCacheSize(cacheSize).setPersistIDCache(false); server = createServer(config); @@ -1625,8 +1560,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase } @Test - public void testPersistTransactional() throws Exception - { + public void testPersistTransactional() throws Exception { ClientSession session = sf.createSession(false, false, false); session.start(); @@ -1685,16 +1619,13 @@ public class DuplicateDetectionTest extends ActiveMQTestBase message.putBytesProperty(Message.HDR_DUPLICATE_DETECTION_ID, dupID.getData()); producer.send(message); - try - { + try { session.commit(); } - catch (ActiveMQDuplicateIdException die) - { + catch (ActiveMQDuplicateIdException die) { session.rollback(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } @@ -1705,16 +1636,13 @@ public class DuplicateDetectionTest extends ActiveMQTestBase message.putBytesProperty(Message.HDR_DUPLICATE_DETECTION_ID, dupID2.getData()); producer.send(message); - try - { + try { session.commit(); } - catch (ActiveMQDuplicateIdException die) - { + catch (ActiveMQDuplicateIdException die) { session.rollback(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } @@ -1723,13 +1651,10 @@ public class DuplicateDetectionTest extends ActiveMQTestBase } @Test - public void testNoPersistXA1() throws Exception - { + public void testNoPersistXA1() throws Exception { server.stop(); - config = createDefaultInVMConfig() - .setIDCacheSize(cacheSize) - .setPersistIDCache(false); + config = createDefaultInVMConfig().setIDCacheSize(cacheSize).setPersistIDCache(false); server = createServer(config); @@ -1817,8 +1742,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase } @Test - public void testNoPersistXA2() throws Exception - { + public void testNoPersistXA2() throws Exception { ClientSession session = sf.createSession(true, false, false); Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); @@ -1895,8 +1819,7 @@ public class DuplicateDetectionTest extends ActiveMQTestBase } @Test - public void testPersistXA1() throws Exception - { + public void testPersistXA1() throws Exception { ClientSession session = addClientSession(sf.createSession(true, false, false)); Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); @@ -1962,18 +1885,15 @@ public class DuplicateDetectionTest extends ActiveMQTestBase producer.send(message); session.end(xid2, XAResource.TMSUCCESS); - try - { + try { session.prepare(xid2); fail("Should throw an exception here!"); } - catch (XAException expected) - { + catch (XAException expected) { } session.rollback(xid2); - Xid xid3 = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); session.start(xid3, XAResource.TMNOFLAGS); @@ -1991,12 +1911,10 @@ public class DuplicateDetectionTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - config = createDefaultInVMConfig() - .setIDCacheSize(cacheSize); + config = createDefaultInVMConfig().setIDCacheSize(cacheSize); server = createServer(true, config); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/IntegrationTestLogger.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/IntegrationTestLogger.java index 6533585a47..80bd4d9187 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/IntegrationTestLogger.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/IntegrationTestLogger.java @@ -21,8 +21,8 @@ import org.jboss.logging.Logger; import org.jboss.logging.annotations.MessageLogger; @MessageLogger(projectCode = "AMQTEST") -public interface IntegrationTestLogger extends BasicLogger -{ +public interface IntegrationTestLogger extends BasicLogger { + /** * The integration test logger. */ diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/InterceptorTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/InterceptorTest.java index 77d5c8fa90..c87833b8c7 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/InterceptorTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/InterceptorTest.java @@ -47,8 +47,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class InterceptorTest extends ActiveMQTestBase -{ +public class InterceptorTest extends ActiveMQTestBase { + private ActiveMQServer server; private final SimpleString QUEUE = new SimpleString("InterceptorTestQueue"); @@ -57,8 +57,7 @@ public class InterceptorTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(false, true); @@ -70,12 +69,10 @@ public class InterceptorTest extends ActiveMQTestBase private static final String key = "fruit"; - private class MyInterceptor1 implements Interceptor - { - public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException - { - if (packet.getType() == PacketImpl.SESS_SEND) - { + private class MyInterceptor1 implements Interceptor { + + public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { + if (packet.getType() == PacketImpl.SESS_SEND) { SessionSendMessage p = (SessionSendMessage) packet; ServerMessage sm = (ServerMessage) p.getMessage(); @@ -88,20 +85,17 @@ public class InterceptorTest extends ActiveMQTestBase } - private class InterceptUserOnCreateQueue implements Interceptor - { - public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException - { - if (packet.getType() == PacketImpl.CREATE_QUEUE) - { + private class InterceptUserOnCreateQueue implements Interceptor { + + public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { + if (packet.getType() == PacketImpl.CREATE_QUEUE) { String userName = getUsername(packet, connection); CreateQueueMessage createQueue = (CreateQueueMessage) packet; createQueue.setFilterString(new SimpleString("userName='" + userName + "'")); System.out.println("userName = " + userName); } - else if (packet.getType() == PacketImpl.SESS_SEND) - { + else if (packet.getType() == PacketImpl.SESS_SEND) { String userName = getUsername(packet, connection); MessagePacket msgPacket = (MessagePacket) packet; msgPacket.getMessage().putStringProperty("userName", userName); @@ -112,9 +106,7 @@ public class InterceptorTest extends ActiveMQTestBase return true; } - - public String getUsername(final Packet packet, final RemotingConnection connection) - { + public String getUsername(final Packet packet, final RemotingConnection connection) { RemotingConnectionImpl impl = (RemotingConnectionImpl) connection; ChannelImpl channel = (ChannelImpl) impl.getChannel(packet.getChannelID(), -1); ServerSessionPacketHandler sessionHandler = (ServerSessionPacketHandler) channel.getHandler(); @@ -123,20 +115,17 @@ public class InterceptorTest extends ActiveMQTestBase } - private class InterceptUserOnCreateConsumer implements Interceptor - { - public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException - { - if (packet.getType() == PacketImpl.SESS_CREATECONSUMER) - { + private class InterceptUserOnCreateConsumer implements Interceptor { + + public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { + if (packet.getType() == PacketImpl.SESS_CREATECONSUMER) { String userName = getUsername(packet, connection); SessionCreateConsumerMessage createQueue = (SessionCreateConsumerMessage) packet; createQueue.setFilterString(new SimpleString("userName='" + userName + "'")); System.out.println("userName = " + userName); } - else if (packet.getType() == PacketImpl.SESS_SEND) - { + else if (packet.getType() == PacketImpl.SESS_SEND) { String userName = getUsername(packet, connection); MessagePacket msgPacket = (MessagePacket) packet; msgPacket.getMessage().putStringProperty("userName", userName); @@ -147,9 +136,7 @@ public class InterceptorTest extends ActiveMQTestBase return true; } - - public String getUsername(final Packet packet, final RemotingConnection connection) - { + public String getUsername(final Packet packet, final RemotingConnection connection) { RemotingConnectionImpl impl = (RemotingConnectionImpl) connection; ChannelImpl channel = (ChannelImpl) impl.getChannel(packet.getChannelID(), -1); ServerSessionPacketHandler sessionHandler = (ServerSessionPacketHandler) channel.getHandler(); @@ -158,12 +145,10 @@ public class InterceptorTest extends ActiveMQTestBase } - private class MyOutgoingInterceptor1 implements Interceptor - { - public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException - { - if (packet.getType() == PacketImpl.SESS_RECEIVE_MSG) - { + private class MyOutgoingInterceptor1 implements Interceptor { + + public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { + if (packet.getType() == PacketImpl.SESS_RECEIVE_MSG) { SessionReceiveMessage p = (SessionReceiveMessage) packet; ServerMessage sm = (ServerMessage) p.getMessage(); @@ -176,12 +161,10 @@ public class InterceptorTest extends ActiveMQTestBase } - private class MyInterceptor2 implements Interceptor - { - public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException - { - if (packet.getType() == PacketImpl.SESS_SEND) - { + private class MyInterceptor2 implements Interceptor { + + public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { + if (packet.getType() == PacketImpl.SESS_SEND) { return false; } @@ -190,17 +173,14 @@ public class InterceptorTest extends ActiveMQTestBase } - private class MyOutgoingInterceptor2 implements Interceptor - { - public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException - { - if (isForceDeliveryResponse(packet)) - { + private class MyOutgoingInterceptor2 implements Interceptor { + + public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { + if (isForceDeliveryResponse(packet)) { return true; } - if (packet.getType() == PacketImpl.SESS_RECEIVE_MSG) - { + if (packet.getType() == PacketImpl.SESS_RECEIVE_MSG) { return false; } @@ -208,12 +188,10 @@ public class InterceptorTest extends ActiveMQTestBase } } - private class MyInterceptor3 implements Interceptor - { - public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException - { - if (packet.getType() == PacketImpl.SESS_RECEIVE_MSG) - { + private class MyInterceptor3 implements Interceptor { + + public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { + if (packet.getType() == PacketImpl.SESS_RECEIVE_MSG) { SessionReceiveMessage p = (SessionReceiveMessage) packet; ClientMessage cm = (ClientMessage) p.getMessage(); @@ -226,12 +204,10 @@ public class InterceptorTest extends ActiveMQTestBase } - private class MyOutgoingInterceptor3 implements Interceptor - { - public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException - { - if (packet.getType() == PacketImpl.SESS_SEND) - { + private class MyOutgoingInterceptor3 implements Interceptor { + + public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { + if (packet.getType() == PacketImpl.SESS_SEND) { SessionSendMessage p = (SessionSendMessage) packet; ClientMessage cm = (ClientMessage) p.getMessage(); @@ -244,17 +220,14 @@ public class InterceptorTest extends ActiveMQTestBase } - private class MyInterceptor4 implements Interceptor - { - public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException - { - if (isForceDeliveryResponse(packet)) - { + private class MyInterceptor4 implements Interceptor { + + public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { + if (isForceDeliveryResponse(packet)) { return true; } - if (packet.getType() == PacketImpl.SESS_RECEIVE_MSG) - { + if (packet.getType() == PacketImpl.SESS_RECEIVE_MSG) { return false; } @@ -263,17 +236,14 @@ public class InterceptorTest extends ActiveMQTestBase } - private class MyOutgoingInterceptor4 implements Interceptor - { - public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException - { - if (isForceDeliveryResponse(packet)) - { + private class MyOutgoingInterceptor4 implements Interceptor { + + public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { + if (isForceDeliveryResponse(packet)) { return true; } - if (packet.getType() == PacketImpl.SESS_SEND) - { + if (packet.getType() == PacketImpl.SESS_SEND) { return false; } @@ -285,13 +255,10 @@ public class InterceptorTest extends ActiveMQTestBase /** * @param packet */ - private boolean isForceDeliveryResponse(final Packet packet) - { - if (packet.getType() == PacketImpl.SESS_RECEIVE_MSG) - { + private boolean isForceDeliveryResponse(final Packet packet) { + if (packet.getType() == PacketImpl.SESS_RECEIVE_MSG) { SessionReceiveMessage msg = (SessionReceiveMessage) packet; - if (msg.getMessage().containsProperty(ClientConsumerImpl.FORCED_DELIVERY_MESSAGE)) - { + if (msg.getMessage().containsProperty(ClientConsumerImpl.FORCED_DELIVERY_MESSAGE)) { return true; } } @@ -299,8 +266,8 @@ public class InterceptorTest extends ActiveMQTestBase return false; } - private class MyInterceptor5 implements Interceptor - { + private class MyInterceptor5 implements Interceptor { + private final String key; private final int num; @@ -309,32 +276,26 @@ public class InterceptorTest extends ActiveMQTestBase private volatile boolean wasCalled; - MyInterceptor5(final String key, final int num) - { + MyInterceptor5(final String key, final int num) { this.key = key; this.num = num; } - public void setReject(final boolean reject) - { + public void setReject(final boolean reject) { this.reject = reject; } - public boolean wasCalled() - { + public boolean wasCalled() { return wasCalled; } - public void setWasCalled(final boolean wasCalled) - { + public void setWasCalled(final boolean wasCalled) { this.wasCalled = wasCalled; } - public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException - { - if (packet.getType() == PacketImpl.SESS_SEND) - { + public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { + if (packet.getType() == PacketImpl.SESS_SEND) { SessionSendMessage p = (SessionSendMessage) packet; ServerMessage sm = (ServerMessage) p.getMessage(); @@ -352,8 +313,8 @@ public class InterceptorTest extends ActiveMQTestBase } - private class MyInterceptor6 implements Interceptor - { + private class MyInterceptor6 implements Interceptor { + private final String key; private final int num; @@ -362,38 +323,31 @@ public class InterceptorTest extends ActiveMQTestBase private volatile boolean wasCalled; - MyInterceptor6(final String key, final int num) - { + MyInterceptor6(final String key, final int num) { this.key = key; this.num = num; } - public void setReject(final boolean reject) - { + public void setReject(final boolean reject) { this.reject = reject; } - public boolean wasCalled() - { + public boolean wasCalled() { return wasCalled; } - public void setWasCalled(final boolean wasCalled) - { + public void setWasCalled(final boolean wasCalled) { this.wasCalled = wasCalled; } - public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException - { + public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { - if (isForceDeliveryResponse(packet)) - { + if (isForceDeliveryResponse(packet)) { return true; } - if (packet.getType() == PacketImpl.SESS_RECEIVE_MSG) - { + if (packet.getType() == PacketImpl.SESS_RECEIVE_MSG) { SessionReceiveMessage p = (SessionReceiveMessage) packet; Message sm = p.getMessage(); @@ -412,8 +366,7 @@ public class InterceptorTest extends ActiveMQTestBase } @Test - public void testServerInterceptorChangeProperty() throws Exception - { + public void testServerInterceptorChangeProperty() throws Exception { MyInterceptor1 interceptor = new MyInterceptor1(); server.getRemotingService().addIncomingInterceptor(interceptor); @@ -428,8 +381,7 @@ public class InterceptorTest extends ActiveMQTestBase final int numMessages = 10; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.putIntProperty("count", i); @@ -443,8 +395,7 @@ public class InterceptorTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(1000); assertNotNull(message); @@ -456,8 +407,7 @@ public class InterceptorTest extends ActiveMQTestBase server.getRemotingService().removeIncomingInterceptor(interceptor); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.putStringProperty(InterceptorTest.key, "apple"); @@ -465,8 +415,7 @@ public class InterceptorTest extends ActiveMQTestBase producer.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(1000); Assert.assertEquals("apple", message.getStringProperty(InterceptorTest.key)); @@ -477,8 +426,7 @@ public class InterceptorTest extends ActiveMQTestBase // This is testing if it's possible to intercept usernames and do some real stuff as users want @Test - public void testInterceptUsernameOnQueues() throws Exception - { + public void testInterceptUsernameOnQueues() throws Exception { SimpleString ANOTHER_QUEUE = QUEUE.concat("another"); ActiveMQSecurityManagerImpl securityManager = (ActiveMQSecurityManagerImpl) server.getSecurityManager(); @@ -502,7 +450,6 @@ public class InterceptorTest extends ActiveMQTestBase ClientProducer prodAnother = sessionAnotherUser.createProducer(QUEUE); - ClientMessage msg = session.createMessage(true); prod.send(msg); session.commit(); @@ -522,7 +469,6 @@ public class InterceptorTest extends ActiveMQTestBase msg.acknowledge(); assertNull(consumer.receiveImmediate()); - msg = consumerAnother.receive(1000); assertNotNull(msg); assertEquals("an", msg.getStringProperty("userName")); @@ -535,8 +481,7 @@ public class InterceptorTest extends ActiveMQTestBase // This is testing if it's possible to intercept usernames and do some real stuff as users want @Test - public void testInterceptUsernameOnConsumer() throws Exception - { + public void testInterceptUsernameOnConsumer() throws Exception { ActiveMQSecurityManagerImpl securityManager = (ActiveMQSecurityManagerImpl) server.getSecurityManager(); securityManager.getConfiguration().addUser("dumb", "dumber"); securityManager.getConfiguration().addUser("an", "other"); @@ -556,7 +501,6 @@ public class InterceptorTest extends ActiveMQTestBase ClientProducer prodAnother = sessionAnotherUser.createProducer(QUEUE); - ClientMessage msg = session.createMessage(true); prod.send(msg); session.commit(); @@ -576,7 +520,6 @@ public class InterceptorTest extends ActiveMQTestBase msg.acknowledge(); assertNull(consumer.receiveImmediate()); - msg = consumerAnother.receive(1000); assertNotNull(msg); assertEquals("an", msg.getStringProperty("userName")); @@ -588,13 +531,11 @@ public class InterceptorTest extends ActiveMQTestBase } @Test - public void testServerInterceptorRejectPacket() throws Exception - { + public void testServerInterceptorRejectPacket() throws Exception { MyInterceptor2 interceptor = new MyInterceptor2(); server.getRemotingService().addIncomingInterceptor(interceptor); - locator.setBlockOnNonDurableSend(false); ClientSessionFactory sf = createSessionFactory(locator); @@ -607,8 +548,7 @@ public class InterceptorTest extends ActiveMQTestBase final int numMessages = 10; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); producer.send(message); @@ -626,8 +566,7 @@ public class InterceptorTest extends ActiveMQTestBase } @Test - public void testClientInterceptorChangeProperty() throws Exception - { + public void testClientInterceptorChangeProperty() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); MyInterceptor3 interceptor = new MyInterceptor3(); @@ -642,8 +581,7 @@ public class InterceptorTest extends ActiveMQTestBase final int numMessages = 10; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.putStringProperty(InterceptorTest.key, "apple"); @@ -655,8 +593,7 @@ public class InterceptorTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(1000); Assert.assertEquals("orange", message.getStringProperty(InterceptorTest.key)); @@ -664,8 +601,7 @@ public class InterceptorTest extends ActiveMQTestBase sf.getServerLocator().removeIncomingInterceptor(interceptor); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.putStringProperty(InterceptorTest.key, "apple"); @@ -673,8 +609,7 @@ public class InterceptorTest extends ActiveMQTestBase producer.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(1000); Assert.assertEquals("apple", message.getStringProperty(InterceptorTest.key)); @@ -684,8 +619,7 @@ public class InterceptorTest extends ActiveMQTestBase } @Test - public void testClientOutgoingInterceptorChangeProperty() throws Exception - { + public void testClientOutgoingInterceptorChangeProperty() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); MyOutgoingInterceptor3 interceptor = new MyOutgoingInterceptor3(); @@ -700,8 +634,7 @@ public class InterceptorTest extends ActiveMQTestBase final int numMessages = 10; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.putStringProperty(InterceptorTest.key, "apple"); @@ -713,8 +646,7 @@ public class InterceptorTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(1000); Assert.assertEquals("orange", message.getStringProperty(InterceptorTest.key)); @@ -722,8 +654,7 @@ public class InterceptorTest extends ActiveMQTestBase sf.getServerLocator().removeOutgoingInterceptor(interceptor); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.putStringProperty(InterceptorTest.key, "apple"); @@ -731,8 +662,7 @@ public class InterceptorTest extends ActiveMQTestBase producer.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(1000); Assert.assertEquals("apple", message.getStringProperty(InterceptorTest.key)); @@ -742,8 +672,7 @@ public class InterceptorTest extends ActiveMQTestBase } @Test - public void testClientInterceptorRejectPacket() throws Exception - { + public void testClientInterceptorRejectPacket() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); MyInterceptor4 interceptor = new MyInterceptor4(); @@ -758,8 +687,7 @@ public class InterceptorTest extends ActiveMQTestBase final int numMessages = 10; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); producer.send(message); @@ -777,8 +705,7 @@ public class InterceptorTest extends ActiveMQTestBase } @Test - public void testClientOutgoingInterceptorRejectPacketOnNonBlockingSend() throws Exception - { + public void testClientOutgoingInterceptorRejectPacketOnNonBlockingSend() throws Exception { locator.setBlockOnNonDurableSend(false); ClientSessionFactory sf = createSessionFactory(locator); @@ -794,8 +721,7 @@ public class InterceptorTest extends ActiveMQTestBase final int numMessages = 10; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); producer.send(message); @@ -813,8 +739,7 @@ public class InterceptorTest extends ActiveMQTestBase } @Test - public void testClientOutgoingInterceptorRejectPacketOnBlockingSend() throws Exception - { + public void testClientOutgoingInterceptorRejectPacketOnBlockingSend() throws Exception { // must make the call block to exercise the right logic locator.setBlockOnNonDurableSend(true); ClientSessionFactory sf = createSessionFactory(locator); @@ -831,21 +756,18 @@ public class InterceptorTest extends ActiveMQTestBase ClientMessage message = session.createMessage(false); - try - { + try { producer.send(message); Assert.fail(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { // expected exception Assert.assertTrue(e.getType().getCode() == ActiveMQExceptionType.INTERCEPTOR_REJECTED_PACKET.getCode()); } } @Test - public void testServerMultipleInterceptors() throws Exception - { + public void testServerMultipleInterceptors() throws Exception { MyInterceptor5 interceptor1 = new MyInterceptor5("a", 1); MyInterceptor5 interceptor2 = new MyInterceptor5("b", 2); MyInterceptor5 interceptor3 = new MyInterceptor5("c", 3); @@ -866,8 +788,7 @@ public class InterceptorTest extends ActiveMQTestBase final int numMessages = 10; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); producer.send(message); @@ -877,8 +798,7 @@ public class InterceptorTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(1000); Assert.assertEquals(1, message.getIntProperty("a").intValue()); @@ -889,15 +809,13 @@ public class InterceptorTest extends ActiveMQTestBase server.getRemotingService().removeIncomingInterceptor(interceptor2); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); producer.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(1000); Assert.assertEquals(1, message.getIntProperty("a").intValue()); @@ -914,8 +832,7 @@ public class InterceptorTest extends ActiveMQTestBase interceptor3.setWasCalled(false); interceptor4.setWasCalled(false); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); producer.send(message); @@ -934,8 +851,7 @@ public class InterceptorTest extends ActiveMQTestBase } @Test - public void testClientMultipleInterceptors() throws Exception - { + public void testClientMultipleInterceptors() throws Exception { MyInterceptor6 interceptor1 = new MyInterceptor6("a", 1); MyInterceptor6 interceptor2 = new MyInterceptor6("b", 2); MyInterceptor6 interceptor3 = new MyInterceptor6("c", 3); @@ -956,8 +872,7 @@ public class InterceptorTest extends ActiveMQTestBase final int numMessages = 10; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); producer.send(message); @@ -967,8 +882,7 @@ public class InterceptorTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(1000); Assert.assertEquals(1, message.getIntProperty("a").intValue()); @@ -979,15 +893,13 @@ public class InterceptorTest extends ActiveMQTestBase sf.getServerLocator().removeIncomingInterceptor(interceptor2); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); producer.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(1000); Assert.assertEquals(1, message.getIntProperty("a").intValue()); @@ -1004,8 +916,7 @@ public class InterceptorTest extends ActiveMQTestBase interceptor3.setWasCalled(false); interceptor4.setWasCalled(false); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); producer.send(message); @@ -1024,8 +935,7 @@ public class InterceptorTest extends ActiveMQTestBase } @Test - public void testServerOutgoingInterceptorChangeProperty() throws Exception - { + public void testServerOutgoingInterceptorChangeProperty() throws Exception { MyOutgoingInterceptor1 interceptor = new MyOutgoingInterceptor1(); server.getRemotingService().addOutgoingInterceptor(interceptor); @@ -1040,8 +950,7 @@ public class InterceptorTest extends ActiveMQTestBase final int numMessages = 10; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.putIntProperty("count", i); @@ -1055,8 +964,7 @@ public class InterceptorTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(1000); assertNotNull(message); @@ -1068,8 +976,7 @@ public class InterceptorTest extends ActiveMQTestBase server.getRemotingService().removeOutgoingInterceptor(interceptor); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.putStringProperty(InterceptorTest.key, "apple"); @@ -1077,8 +984,7 @@ public class InterceptorTest extends ActiveMQTestBase producer.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(1000); Assert.assertEquals("apple", message.getStringProperty(InterceptorTest.key)); @@ -1088,8 +994,7 @@ public class InterceptorTest extends ActiveMQTestBase } @Test - public void testServerOutgoingInterceptorRejectMessage() throws Exception - { + public void testServerOutgoingInterceptorRejectMessage() throws Exception { MyOutgoingInterceptor2 interceptor = new MyOutgoingInterceptor2(); server.getRemotingService().addOutgoingInterceptor(interceptor); @@ -1106,8 +1011,7 @@ public class InterceptorTest extends ActiveMQTestBase final int numMessages = 10; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); producer.send(message); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/SimpleNotificationService.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/SimpleNotificationService.java index 05fbbe82af..0b74c368fb 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/SimpleNotificationService.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/SimpleNotificationService.java @@ -23,8 +23,7 @@ import org.apache.activemq.artemis.core.server.management.Notification; import org.apache.activemq.artemis.core.server.management.NotificationListener; import org.apache.activemq.artemis.core.server.management.NotificationService; -public class SimpleNotificationService implements NotificationService -{ +public class SimpleNotificationService implements NotificationService { // Constants ----------------------------------------------------- @@ -38,24 +37,19 @@ public class SimpleNotificationService implements NotificationService // NotificationService implementation ---------------------------- - public void addNotificationListener(final NotificationListener listener) - { + public void addNotificationListener(final NotificationListener listener) { listeners.add(listener); } - public void enableNotifications(final boolean enable) - { + public void enableNotifications(final boolean enable) { } - public void removeNotificationListener(final NotificationListener listener) - { + public void removeNotificationListener(final NotificationListener listener) { listeners.remove(listener); } - public void sendNotification(final Notification notification) throws Exception - { - for (NotificationListener listener : listeners) - { + public void sendNotification(final Notification notification) throws Exception { + for (NotificationListener listener : listeners) { listener.onNotification(notification); } } @@ -70,19 +64,16 @@ public class SimpleNotificationService implements NotificationService // Inner classes ------------------------------------------------- - public static class Listener implements NotificationListener - { + public static class Listener implements NotificationListener { private final List notifications = new ArrayList(); - public void onNotification(final Notification notification) - { + public void onNotification(final Notification notification) { System.out.println(">>>>>>>>" + notification); notifications.add(notification); } - public List getNotifications() - { + public List getNotifications() { return notifications; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/SimpleTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/SimpleTest.java index 6fe73a771e..f0db2068c1 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/SimpleTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/SimpleTest.java @@ -33,8 +33,8 @@ import java.util.UUID; /** * A simple test-case used for documentation purposes. */ -public class SimpleTest extends ActiveMQTestBase -{ +public class SimpleTest extends ActiveMQTestBase { + protected ActiveMQServer server; protected ClientSession session; @@ -45,8 +45,7 @@ public class SimpleTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { /** * Invoke org.apache.activemq.artemis.tests.util.ActiveMQTestBase's setUp() to bootstrap everything properly. */ @@ -81,8 +80,7 @@ public class SimpleTest extends ActiveMQTestBase } @Test - public void simpleTest() throws Exception - { + public void simpleTest() throws Exception { final String data = "Simple Text " + UUID.randomUUID().toString(); final String queueName = "simpleQueue"; final String addressName = "simpleAddress"; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/SingleServerSimpleTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/SingleServerSimpleTest.java index e41c85962c..b71e31de7d 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/SingleServerSimpleTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/SingleServerSimpleTest.java @@ -28,8 +28,8 @@ import java.util.UUID; /** * A simple test-case used for documentation purposes. */ -public class SingleServerSimpleTest extends SingleServerTestBase -{ +public class SingleServerSimpleTest extends SingleServerTestBase { + /** * Because this class extends org.apache.activemq.artemis.tests.util.SingleServerTestBase and only uses a single * instance of ActiveMQServer then no explicit setUp is required. The class simply needs tests which will use @@ -37,8 +37,7 @@ public class SingleServerSimpleTest extends SingleServerTestBase */ @Test - public void simpleTest() throws Exception - { + public void simpleTest() throws Exception { final String data = "Simple Text " + UUID.randomUUID().toString(); final String queueName = "simpleQueue"; final String addressName = "simpleAddress"; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/String64KLimitTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/String64KLimitTest.java index bf5e32bb5c..a19c58b97f 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/String64KLimitTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/String64KLimitTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration; + import org.junit.Before; import org.junit.Test; @@ -36,15 +37,13 @@ import org.apache.activemq.artemis.tests.util.RandomUtil; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; /** - * * There is a bug in JDK1.3, 1.4 whereby writeUTF fails if more than 64K bytes are written * we need to work with all size of strings * * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4806007 * http://jira.jboss.com/jira/browse/JBAS-2641 */ -public class String64KLimitTest extends ActiveMQTestBase -{ +public class String64KLimitTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -60,19 +59,16 @@ public class String64KLimitTest extends ActiveMQTestBase // Public -------------------------------------------------------- - protected String genString(final int len) - { + protected String genString(final int len) { char[] chars = new char[len]; - for (int i = 0; i < len; i++) - { - chars[i] = (char)(65 + i % 26); + for (int i = 0; i < len; i++) { + chars[i] = (char) (65 + i % 26); } return new String(chars); } @Test - public void test64KLimitWithWriteString() throws Exception - { + public void test64KLimitWithWriteString() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -136,8 +132,7 @@ public class String64KLimitTest extends ActiveMQTestBase } @Test - public void test64KLimitWithWriteUTF() throws Exception - { + public void test64KLimitWithWriteUTF() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -162,24 +157,20 @@ public class String64KLimitTest extends ActiveMQTestBase ClientMessage tm2 = session.createMessage(false); tm2.getBodyBuffer().writeUTF(s2); - try - { + try { ClientMessage tm3 = session.createMessage(false); tm3.getBodyBuffer().writeUTF(s3); Assert.fail("can not write UTF string bigger than 64K"); } - catch (Exception e) - { + catch (Exception e) { } - try - { + try { ClientMessage tm4 = session.createMessage(false); tm4.getBodyBuffer().writeUTF(s4); Assert.fail("can not write UTF string bigger than 64K"); } - catch (Exception e) - { + catch (Exception e) { } producer.send(tm1); @@ -203,12 +194,10 @@ public class String64KLimitTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - Configuration config = createBasicConfig() - .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY)); + Configuration config = createBasicConfig().addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY)); server = addServer(ActiveMQServers.newActiveMQServer(config, false)); server.start(); locator = createInVMNonHALocator(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/aerogear/AeroGearBasicServerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/aerogear/AeroGearBasicServerTest.java index af2250a9bf..a667770f09 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/aerogear/AeroGearBasicServerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/aerogear/AeroGearBasicServerTest.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.tests.integration.aerogear; - import org.apache.activemq.artemis.api.core.Message; import org.apache.activemq.artemis.api.core.client.ClientConsumer; import org.apache.activemq.artemis.api.core.client.ClientMessage; @@ -51,8 +50,7 @@ import java.util.HashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -public class AeroGearBasicServerTest extends ActiveMQTestBase -{ +public class AeroGearBasicServerTest extends ActiveMQTestBase { private ActiveMQServer server; private ServerLocator locator; @@ -60,8 +58,7 @@ public class AeroGearBasicServerTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); /* * there will be a thread kept alive by the http connection, we could disable the thread check but this means that the tests @@ -87,15 +84,7 @@ public class AeroGearBasicServerTest extends ActiveMQTestBase params.put(AeroGearConstants.SOUND_NAME, "sound1"); params.put(AeroGearConstants.VARIANTS_NAME, "variant1,variant2"); - Configuration configuration = createDefaultInVMConfig() - .addConnectorServiceConfiguration( - new ConnectorServiceConfiguration() - .setFactoryClassName(AeroGearConnectorServiceFactory.class.getName()) - .setParams(params) - .setName("TestAeroGearService")) - .addQueueConfiguration(new CoreQueueConfiguration() - .setAddress("testQueue") - .setName("testQueue")); + Configuration configuration = createDefaultInVMConfig().addConnectorServiceConfiguration(new ConnectorServiceConfiguration().setFactoryClassName(AeroGearConnectorServiceFactory.class.getName()).setParams(params).setName("TestAeroGearService")).addQueueConfiguration(new CoreQueueConfiguration().setAddress("testQueue").setName("testQueue")); server = addServer(createServer(configuration)); server.start(); @@ -104,18 +93,15 @@ public class AeroGearBasicServerTest extends ActiveMQTestBase @Override @After - public void tearDown() throws Exception - { - if (jetty != null) - { + public void tearDown() throws Exception { + if (jetty != null) { jetty.stop(); } super.tearDown(); } @Test - public void aerogearSimpleReceiveTest() throws Exception - { + public void aerogearSimpleReceiveTest() throws Exception { CountDownLatch latch = new CountDownLatch(1); AeroGearHandler aeroGearHandler = new AeroGearHandler(latch); jetty.addHandler(aeroGearHandler); @@ -212,19 +198,20 @@ public class AeroGearBasicServerTest extends ActiveMQTestBase assertNull(message); } - class AeroGearHandler extends AbstractHandler - { + class AeroGearHandler extends AbstractHandler { + JSONObject jsonObject; private CountDownLatch latch; - public AeroGearHandler(CountDownLatch latch) - { + public AeroGearHandler(CountDownLatch latch) { this.latch = latch; } @Override - public void handle(String target, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException - { + public void handle(String target, + HttpServletRequest httpServletRequest, + HttpServletResponse httpServletResponse, + int i) throws IOException, ServletException { Request request = (Request) httpServletRequest; httpServletResponse.setContentType("text/html"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); @@ -232,33 +219,30 @@ public class AeroGearBasicServerTest extends ActiveMQTestBase byte[] bytes = new byte[httpServletRequest.getContentLength()]; httpServletRequest.getInputStream().read(bytes); String json = new String(bytes); - try - { + try { jsonObject = new JSONObject(json); } - catch (JSONException e) - { + catch (JSONException e) { jsonObject = null; } latch.countDown(); } - public void resetLatch(CountDownLatch latch) - { + public void resetLatch(CountDownLatch latch) { this.latch = latch; } } @Test - public void aerogearReconnectTest() throws Exception - { + public void aerogearReconnectTest() throws Exception { jetty.stop(); final CountDownLatch reconnectLatch = new CountDownLatch(1); - jetty.addHandler(new AbstractHandler() - { + jetty.addHandler(new AbstractHandler() { @Override - public void handle(String target, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException - { + public void handle(String target, + HttpServletRequest httpServletRequest, + HttpServletResponse httpServletResponse, + int i) throws IOException, ServletException { Request request = (Request) httpServletRequest; httpServletResponse.setContentType("text/html"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); @@ -275,22 +259,18 @@ public class AeroGearBasicServerTest extends ActiveMQTestBase ClientMessage m = session.createMessage(true); m.putStringProperty(AeroGearConstants.AEROGEAR_ALERT.toString(), "hello from ActiveMQ!"); - producer.send(m, new SendAcknowledgementHandler() - { + producer.send(m, new SendAcknowledgementHandler() { @Override - public void sendAcknowledged(Message message) - { + public void sendAcknowledged(Message message) { latch.countDown(); } }); m = session.createMessage(true); m.putStringProperty(AeroGearConstants.AEROGEAR_ALERT.toString(), "another hello from ActiveMQ!"); - producer.send(m, new SendAcknowledgementHandler() - { + producer.send(m, new SendAcknowledgementHandler() { @Override - public void sendAcknowledged(Message message) - { + public void sendAcknowledged(Message message) { latch.countDown(); } }); @@ -304,14 +284,14 @@ public class AeroGearBasicServerTest extends ActiveMQTestBase } @Test - public void aerogear401() throws Exception - { + public void aerogear401() throws Exception { final CountDownLatch latch = new CountDownLatch(1); - jetty.addHandler(new AbstractHandler() - { + jetty.addHandler(new AbstractHandler() { @Override - public void handle(String target, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException - { + public void handle(String target, + HttpServletRequest httpServletRequest, + HttpServletResponse httpServletResponse, + int i) throws IOException, ServletException { Request request = (Request) httpServletRequest; httpServletResponse.setContentType("text/html"); httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); @@ -341,15 +321,14 @@ public class AeroGearBasicServerTest extends ActiveMQTestBase assertNotNull(message); } - @Test - public void aerogear404() throws Exception - { - jetty.addHandler(new AbstractHandler() - { + public void aerogear404() throws Exception { + jetty.addHandler(new AbstractHandler() { @Override - public void handle(String target, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException - { + public void handle(String target, + HttpServletRequest httpServletRequest, + HttpServletResponse httpServletResponse, + int i) throws IOException, ServletException { Request request = (Request) httpServletRequest; httpServletResponse.setContentType("text/html"); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AckBatchSizeTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AckBatchSizeTest.java index 6185df5d05..2e5bb96124 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AckBatchSizeTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AckBatchSizeTest.java @@ -29,8 +29,8 @@ import org.apache.activemq.artemis.core.server.Queue; import org.junit.Assert; import org.junit.Test; -public class AckBatchSizeTest extends ActiveMQTestBase -{ +public class AckBatchSizeTest extends ActiveMQTestBase { + public final SimpleString addressA = new SimpleString("addressA"); public final SimpleString queueA = new SimpleString("queueA"); @@ -45,8 +45,7 @@ public class AckBatchSizeTest extends ActiveMQTestBase * tests that wed don't acknowledge until the correct ackBatchSize is reached * */ - private int getMessageEncodeSize(final SimpleString address) throws Exception - { + private int getMessageEncodeSize(final SimpleString address) throws Exception { ServerLocator locator = createInVMNonHALocator(); ClientSessionFactory cf = createSessionFactory(locator); ClientSession session = cf.createSession(false, true, true); @@ -60,29 +59,24 @@ public class AckBatchSizeTest extends ActiveMQTestBase } @Test - public void testAckBatchSize() throws Exception - { + public void testAckBatchSize() throws Exception { ActiveMQServer server = createServer(false); server.start(); int numMessages = 100; - ServerLocator locator = createInVMNonHALocator() - .setAckBatchSize(numMessages * getMessageEncodeSize(addressA)) - .setBlockOnAcknowledge(true); + ServerLocator locator = createInVMNonHALocator().setAckBatchSize(numMessages * getMessageEncodeSize(addressA)).setBlockOnAcknowledge(true); ClientSessionFactory cf = createSessionFactory(locator); ClientSession sendSession = cf.createSession(false, true, true); ClientSession session = cf.createSession(false, true, true); session.createQueue(addressA, queueA, false); ClientProducer cp = sendSession.createProducer(addressA); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { cp.send(sendSession.createMessage(false)); } ClientConsumer consumer = session.createConsumer(queueA); session.start(); - for (int i = 0; i < numMessages - 1; i++) - { + for (int i = 0; i < numMessages - 1; i++) { ClientMessage m = consumer.receive(5000); m.acknowledge(); @@ -101,14 +95,11 @@ public class AckBatchSizeTest extends ActiveMQTestBase * tests that when the ackBatchSize is 0 we ack every message directly * */ @Test - public void testAckBatchSizeZero() throws Exception - { + public void testAckBatchSizeZero() throws Exception { ActiveMQServer server = createServer(false); server.start(); - ServerLocator locator = createInVMNonHALocator() - .setAckBatchSize(0) - .setBlockOnAcknowledge(true); + ServerLocator locator = createInVMNonHALocator().setAckBatchSize(0).setBlockOnAcknowledge(true); ClientSessionFactory cf = createSessionFactory(locator); ClientSession sendSession = cf.createSession(false, true, true); int numMessages = 100; @@ -116,8 +107,7 @@ public class AckBatchSizeTest extends ActiveMQTestBase ClientSession session = cf.createSession(false, true, true); session.createQueue(addressA, queueA, false); ClientProducer cp = sendSession.createProducer(addressA); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { cp.send(sendSession.createMessage(false)); } @@ -125,13 +115,11 @@ public class AckBatchSizeTest extends ActiveMQTestBase session.start(); Queue q = (Queue) server.getPostOffice().getBinding(queueA).getBindable(); ClientMessage[] messages = new ClientMessage[numMessages]; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { messages[i] = consumer.receive(5000); Assert.assertNotNull(messages[i]); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { messages[i].acknowledge(); Assert.assertEquals(numMessages - i - 1, q.getDeliveringCount()); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AcknowledgeTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AcknowledgeTest.java index d761701d30..79bf5b3fde 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AcknowledgeTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AcknowledgeTest.java @@ -44,8 +44,8 @@ import org.apache.activemq.artemis.utils.UUID; import org.junit.Assert; import org.junit.Test; -public class AcknowledgeTest extends ActiveMQTestBase -{ +public class AcknowledgeTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; public final SimpleString addressA = new SimpleString("addressA"); @@ -57,13 +57,10 @@ public class AcknowledgeTest extends ActiveMQTestBase public final SimpleString queueC = new SimpleString("queueC"); @Test - public void testReceiveAckLastMessageOnly() throws Exception - { + public void testReceiveAckLastMessageOnly() throws Exception { ActiveMQServer server = createServer(false); server.start(); - ServerLocator locator = createInVMNonHALocator() - .setAckBatchSize(0) - .setBlockOnAcknowledge(true); + ServerLocator locator = createInVMNonHALocator().setAckBatchSize(0).setBlockOnAcknowledge(true); ClientSessionFactory cf = createSessionFactory(locator); ClientSession sendSession = cf.createSession(false, true, true); ClientSession session = cf.createSession(false, true, true); @@ -71,14 +68,12 @@ public class AcknowledgeTest extends ActiveMQTestBase ClientProducer cp = sendSession.createProducer(addressA); ClientConsumer cc = session.createConsumer(queueA); int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { cp.send(sendSession.createMessage(false)); } session.start(); ClientMessage cm = null; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { cm = cc.receive(5000); Assert.assertNotNull(cm); } @@ -91,8 +86,7 @@ public class AcknowledgeTest extends ActiveMQTestBase } @Test - public void testAsyncConsumerNoAck() throws Exception - { + public void testAsyncConsumerNoAck() throws Exception { ActiveMQServer server = createServer(false); server.start(); @@ -104,8 +98,7 @@ public class AcknowledgeTest extends ActiveMQTestBase ClientProducer cp = sendSession.createProducer(addressA); ClientConsumer cc = session.createConsumer(queueA); int numMessages = 3; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { cp.send(sendSession.createMessage(false)); } @@ -114,12 +107,10 @@ public class AcknowledgeTest extends ActiveMQTestBase final CountDownLatch latch = new CountDownLatch(numMessages); session.start(); - cc.setMessageHandler(new MessageHandler() - { + cc.setMessageHandler(new MessageHandler() { int c = 0; - public void onMessage(final ClientMessage message) - { + public void onMessage(final ClientMessage message) { log.info("Got message " + c++); latch.countDown(); } @@ -132,13 +123,10 @@ public class AcknowledgeTest extends ActiveMQTestBase } @Test - public void testAsyncConsumerAck() throws Exception - { + public void testAsyncConsumerAck() throws Exception { ActiveMQServer server = createServer(false); server.start(); - ServerLocator locator = createInVMNonHALocator() - .setBlockOnAcknowledge(true) - .setAckBatchSize(0); + ServerLocator locator = createInVMNonHALocator().setBlockOnAcknowledge(true).setAckBatchSize(0); ClientSessionFactory cf = createSessionFactory(locator); ClientSession sendSession = cf.createSession(false, true, true); final ClientSession session = cf.createSession(false, true, true); @@ -146,28 +134,21 @@ public class AcknowledgeTest extends ActiveMQTestBase ClientProducer cp = sendSession.createProducer(addressA); ClientConsumer cc = session.createConsumer(queueA); int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { cp.send(sendSession.createMessage(false)); } final CountDownLatch latch = new CountDownLatch(numMessages); session.start(); - cc.setMessageHandler(new MessageHandler() - { - public void onMessage(final ClientMessage message) - { - try - { + cc.setMessageHandler(new MessageHandler() { + public void onMessage(final ClientMessage message) { + try { message.acknowledge(); } - catch (ActiveMQException e) - { - try - { + catch (ActiveMQException e) { + try { session.close(); } - catch (ActiveMQException e1) - { + catch (ActiveMQException e1) { e1.printStackTrace(); } } @@ -181,21 +162,17 @@ public class AcknowledgeTest extends ActiveMQTestBase session.close(); } - /** * This is validating a case where a consumer will try to ack a message right after failover, but the consumer at the target server didn't * receive the message yet. * on that case the system should rollback any acks done and redeliver any messages */ @Test - public void testInvalidACK() throws Exception - { + public void testInvalidACK() throws Exception { ActiveMQServer server = createServer(false); server.start(); - ServerLocator locator = createInVMNonHALocator() - .setAckBatchSize(0) - .setBlockOnAcknowledge(true); + ServerLocator locator = createInVMNonHALocator().setAckBatchSize(0).setBlockOnAcknowledge(true); ClientSessionFactory cf = createSessionFactory(locator); @@ -215,8 +192,7 @@ public class AcknowledgeTest extends ActiveMQTestBase ClientProducer cp = sendSession.createProducer(addressA); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage msg = sendSession.createMessage(true); msg.putIntProperty("seq", i); cp.send(msg); @@ -233,24 +209,20 @@ public class AcknowledgeTest extends ActiveMQTestBase // as we need to guarantee the order on cancellation on this test Thread.sleep(1000); - try - { + try { // pretending to be an unbehaved client doing an invalid ack right after failover ((ClientSessionInternal) sessionConsumer).acknowledge(new FakeConsumerWithID(0), new FakeMessageWithID(12343)); fail("supposed to throw an exception here"); } - catch (Exception e) - { + catch (Exception e) { } - try - { + try { // pretending to be an unbehaved client doing an invalid ack right after failover ((ClientSessionInternal) sessionConsumer).acknowledge(new FakeConsumerWithID(3), new FakeMessageWithID(12343)); fail("supposed to throw an exception here"); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } @@ -258,9 +230,7 @@ public class AcknowledgeTest extends ActiveMQTestBase consumer = sessionConsumer.createConsumer(queueA); - - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { msg = consumer.receive(5000); assertNotNull(msg); assertEquals(i, msg.getIntProperty("seq").intValue()); @@ -269,15 +239,11 @@ public class AcknowledgeTest extends ActiveMQTestBase } } - @Test - public void testAsyncConsumerAckLastMessageOnly() throws Exception - { + public void testAsyncConsumerAckLastMessageOnly() throws Exception { ActiveMQServer server = createServer(false); server.start(); - ServerLocator locator = createInVMNonHALocator() - .setBlockOnAcknowledge(true) - .setAckBatchSize(0); + ServerLocator locator = createInVMNonHALocator().setBlockOnAcknowledge(true).setAckBatchSize(0); ClientSessionFactory cf = createSessionFactory(locator); ClientSession sendSession = cf.createSession(false, true, true); final ClientSession session = cf.createSession(false, true, true); @@ -285,30 +251,22 @@ public class AcknowledgeTest extends ActiveMQTestBase ClientProducer cp = sendSession.createProducer(addressA); ClientConsumer cc = session.createConsumer(queueA); int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { cp.send(sendSession.createMessage(false)); } final CountDownLatch latch = new CountDownLatch(numMessages); session.start(); - cc.setMessageHandler(new MessageHandler() - { - public void onMessage(final ClientMessage message) - { - if (latch.getCount() == 1) - { - try - { + cc.setMessageHandler(new MessageHandler() { + public void onMessage(final ClientMessage message) { + if (latch.getCount() == 1) { + try { message.acknowledge(); } - catch (ActiveMQException e) - { - try - { + catch (ActiveMQException e) { + try { session.close(); } - catch (ActiveMQException e1) - { + catch (ActiveMQException e1) { e1.printStackTrace(); } } @@ -323,504 +281,420 @@ public class AcknowledgeTest extends ActiveMQTestBase session.close(); } + class FakeConsumerWithID implements ClientConsumer { - class FakeConsumerWithID implements ClientConsumer - { final long id; - FakeConsumerWithID(long id) - { + FakeConsumerWithID(long id) { this.id = id; } @Override - public ConsumerContext getConsumerContext() - { + public ConsumerContext getConsumerContext() { return new ActiveMQConsumerContext(this.id); } @Override - public ClientMessage receive() throws ActiveMQException - { + public ClientMessage receive() throws ActiveMQException { return null; } @Override - public ClientMessage receive(long timeout) throws ActiveMQException - { + public ClientMessage receive(long timeout) throws ActiveMQException { return null; } @Override - public ClientMessage receiveImmediate() throws ActiveMQException - { + public ClientMessage receiveImmediate() throws ActiveMQException { return null; } @Override - public MessageHandler getMessageHandler() throws ActiveMQException - { + public MessageHandler getMessageHandler() throws ActiveMQException { return null; } @Override - public FakeConsumerWithID setMessageHandler(MessageHandler handler) throws ActiveMQException - { + public FakeConsumerWithID setMessageHandler(MessageHandler handler) throws ActiveMQException { return this; } @Override - public void close() throws ActiveMQException - { + public void close() throws ActiveMQException { } @Override - public boolean isClosed() - { + public boolean isClosed() { return false; } @Override - public Exception getLastException() - { + public Exception getLastException() { return null; } } - class FakeMessageWithID implements Message - { + class FakeMessageWithID implements Message { final long id; - FakeMessageWithID(final long id) - { + FakeMessageWithID(final long id) { this.id = id; } @Override - public long getMessageID() - { + public long getMessageID() { return id; } @Override - public UUID getUserID() - { + public UUID getUserID() { return null; } @Override - public FakeMessageWithID setUserID(UUID userID) - { + public FakeMessageWithID setUserID(UUID userID) { return this; } @Override - public SimpleString getAddress() - { + public SimpleString getAddress() { return null; } @Override - public Message setAddress(SimpleString address) - { + public Message setAddress(SimpleString address) { return null; } @Override - public byte getType() - { + public byte getType() { return 0; } @Override - public boolean isDurable() - { + public boolean isDurable() { return false; } @Override - public FakeMessageWithID setDurable(boolean durable) - { + public FakeMessageWithID setDurable(boolean durable) { return this; } @Override - public long getExpiration() - { + public long getExpiration() { return 0; } @Override - public boolean isExpired() - { + public boolean isExpired() { return false; } @Override - public FakeMessageWithID setExpiration(long expiration) - { + public FakeMessageWithID setExpiration(long expiration) { return this; } @Override - public long getTimestamp() - { + public long getTimestamp() { return 0; } @Override - public FakeMessageWithID setTimestamp(long timestamp) - { + public FakeMessageWithID setTimestamp(long timestamp) { return this; } @Override - public byte getPriority() - { + public byte getPriority() { return 0; } @Override - public FakeMessageWithID setPriority(byte priority) - { + public FakeMessageWithID setPriority(byte priority) { return this; } @Override - public int getEncodeSize() - { + public int getEncodeSize() { return 0; } @Override - public boolean isLargeMessage() - { + public boolean isLargeMessage() { return false; } @Override - public ActiveMQBuffer getBodyBuffer() - { + public ActiveMQBuffer getBodyBuffer() { return null; } @Override - public ActiveMQBuffer getBodyBufferCopy() - { + public ActiveMQBuffer getBodyBufferCopy() { return null; } @Override - public Message putBooleanProperty(SimpleString key, boolean value) - { + public Message putBooleanProperty(SimpleString key, boolean value) { return null; } @Override - public Message putBooleanProperty(String key, boolean value) - { + public Message putBooleanProperty(String key, boolean value) { return null; } @Override - public Message putByteProperty(SimpleString key, byte value) - { + public Message putByteProperty(SimpleString key, byte value) { return null; } @Override - public Message putByteProperty(String key, byte value) - { + public Message putByteProperty(String key, byte value) { return null; } @Override - public Message putBytesProperty(SimpleString key, byte[] value) - { + public Message putBytesProperty(SimpleString key, byte[] value) { return null; } @Override - public Message putBytesProperty(String key, byte[] value) - { + public Message putBytesProperty(String key, byte[] value) { return null; } @Override - public Message putShortProperty(SimpleString key, short value) - { + public Message putShortProperty(SimpleString key, short value) { return null; } @Override - public Message putShortProperty(String key, short value) - { + public Message putShortProperty(String key, short value) { return null; } @Override - public Message putCharProperty(SimpleString key, char value) - { + public Message putCharProperty(SimpleString key, char value) { return null; } @Override - public Message putCharProperty(String key, char value) - { + public Message putCharProperty(String key, char value) { return null; } @Override - public Message putIntProperty(SimpleString key, int value) - { + public Message putIntProperty(SimpleString key, int value) { return null; } @Override - public Message putIntProperty(String key, int value) - { + public Message putIntProperty(String key, int value) { return null; } @Override - public Message putLongProperty(SimpleString key, long value) - { + public Message putLongProperty(SimpleString key, long value) { return null; } @Override - public Message putLongProperty(String key, long value) - { + public Message putLongProperty(String key, long value) { return null; } @Override - public Message putFloatProperty(SimpleString key, float value) - { + public Message putFloatProperty(SimpleString key, float value) { return null; } @Override - public Message putFloatProperty(String key, float value) - { + public Message putFloatProperty(String key, float value) { return null; } @Override - public Message putDoubleProperty(SimpleString key, double value) - { + public Message putDoubleProperty(SimpleString key, double value) { return null; } @Override - public Message putDoubleProperty(String key, double value) - { + public Message putDoubleProperty(String key, double value) { return null; } @Override - public Message putStringProperty(SimpleString key, SimpleString value) - { + public Message putStringProperty(SimpleString key, SimpleString value) { return null; } @Override - public Message putStringProperty(String key, String value) - { + public Message putStringProperty(String key, String value) { return null; } @Override - public Message putObjectProperty(SimpleString key, Object value) throws ActiveMQPropertyConversionException - { + public Message putObjectProperty(SimpleString key, Object value) throws ActiveMQPropertyConversionException { return null; } @Override - public Message putObjectProperty(String key, Object value) throws ActiveMQPropertyConversionException - { + public Message putObjectProperty(String key, Object value) throws ActiveMQPropertyConversionException { return null; } @Override - public Object removeProperty(SimpleString key) - { + public Object removeProperty(SimpleString key) { return null; } @Override - public Object removeProperty(String key) - { + public Object removeProperty(String key) { return null; } @Override - public boolean containsProperty(SimpleString key) - { + public boolean containsProperty(SimpleString key) { return false; } @Override - public boolean containsProperty(String key) - { + public boolean containsProperty(String key) { return false; } @Override - public Boolean getBooleanProperty(SimpleString key) throws ActiveMQPropertyConversionException - { + public Boolean getBooleanProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override - public Boolean getBooleanProperty(String key) throws ActiveMQPropertyConversionException - { + public Boolean getBooleanProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override - public Byte getByteProperty(SimpleString key) throws ActiveMQPropertyConversionException - { + public Byte getByteProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override - public Byte getByteProperty(String key) throws ActiveMQPropertyConversionException - { + public Byte getByteProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override - public Double getDoubleProperty(SimpleString key) throws ActiveMQPropertyConversionException - { + public Double getDoubleProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override - public Double getDoubleProperty(String key) throws ActiveMQPropertyConversionException - { + public Double getDoubleProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override - public Integer getIntProperty(SimpleString key) throws ActiveMQPropertyConversionException - { + public Integer getIntProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override - public Integer getIntProperty(String key) throws ActiveMQPropertyConversionException - { + public Integer getIntProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override - public Long getLongProperty(SimpleString key) throws ActiveMQPropertyConversionException - { + public Long getLongProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override - public Long getLongProperty(String key) throws ActiveMQPropertyConversionException - { + public Long getLongProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override - public Object getObjectProperty(SimpleString key) - { + public Object getObjectProperty(SimpleString key) { return null; } @Override - public Object getObjectProperty(String key) - { + public Object getObjectProperty(String key) { return null; } @Override - public Short getShortProperty(SimpleString key) throws ActiveMQPropertyConversionException - { + public Short getShortProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override - public Short getShortProperty(String key) throws ActiveMQPropertyConversionException - { + public Short getShortProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override - public Float getFloatProperty(SimpleString key) throws ActiveMQPropertyConversionException - { + public Float getFloatProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override - public Float getFloatProperty(String key) throws ActiveMQPropertyConversionException - { + public Float getFloatProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override - public String getStringProperty(SimpleString key) throws ActiveMQPropertyConversionException - { + public String getStringProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override - public String getStringProperty(String key) throws ActiveMQPropertyConversionException - { + public String getStringProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override - public SimpleString getSimpleStringProperty(SimpleString key) throws ActiveMQPropertyConversionException - { + public SimpleString getSimpleStringProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override - public SimpleString getSimpleStringProperty(String key) throws ActiveMQPropertyConversionException - { + public SimpleString getSimpleStringProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override - public byte[] getBytesProperty(SimpleString key) throws ActiveMQPropertyConversionException - { + public byte[] getBytesProperty(SimpleString key) throws ActiveMQPropertyConversionException { return new byte[0]; } @Override - public byte[] getBytesProperty(String key) throws ActiveMQPropertyConversionException - { + public byte[] getBytesProperty(String key) throws ActiveMQPropertyConversionException { return new byte[0]; } @Override - public Set getPropertyNames() - { + public Set getPropertyNames() { return null; } @Override - public Map toMap() - { + public Map toMap() { return null; } @Override - public FakeMessageWithID writeBodyBufferBytes(byte[] bytes) - { + public FakeMessageWithID writeBodyBufferBytes(byte[] bytes) { return this; } @Override - public FakeMessageWithID writeBodyBufferString(String string) - { + public FakeMessageWithID writeBodyBufferString(String string) { return this; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ActiveMQCrashTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ActiveMQCrashTest.java index 0070f1e278..701bc714db 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ActiveMQCrashTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ActiveMQCrashTest.java @@ -38,12 +38,10 @@ import org.junit.Before; import org.junit.Test; /** - * * From https://jira.jboss.org/jira/browse/HORNETQ-144 - * */ -public class ActiveMQCrashTest extends ActiveMQTestBase -{ +public class ActiveMQCrashTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; public ActiveMQServer server; @@ -52,10 +50,8 @@ public class ActiveMQCrashTest extends ActiveMQTestBase private ServerLocator locator; @Test - public void testHang() throws Exception - { - Configuration configuration = createDefaultInVMConfig() - .setPersistenceEnabled(false); + public void testHang() throws Exception { + Configuration configuration = createDefaultInVMConfig().setPersistenceEnabled(false); server = addServer(ActiveMQServers.newActiveMQServer(configuration)); @@ -70,10 +66,8 @@ public class ActiveMQCrashTest extends ActiveMQTestBase ClientSession session = clientSessionFactory.createSession(); - session.setSendAcknowledgementHandler(new SendAcknowledgementHandler() - { - public void sendAcknowledged(final Message message) - { + session.setSendAcknowledgementHandler(new SendAcknowledgementHandler() { + public void sendAcknowledged(final Message message) { ackReceived = true; } }); @@ -93,43 +87,34 @@ public class ActiveMQCrashTest extends ActiveMQTestBase session.close(); } - public static class AckInterceptor implements Interceptor - { + public static class AckInterceptor implements Interceptor { + private final ActiveMQServer server; - AckInterceptor(final ActiveMQServer server) - { + AckInterceptor(final ActiveMQServer server) { this.server = server; } - public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException - { + public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { ActiveMQCrashTest.log.info("AckInterceptor.intercept " + packet); - if (packet.getType() == PacketImpl.SESS_SEND) - { - try - { + if (packet.getType() == PacketImpl.SESS_SEND) { + try { ActiveMQCrashTest.log.info("Stopping server"); - new Thread() - { + new Thread() { @Override - public void run() - { - try - { + public void run() { + try { server.stop(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } }.start(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } @@ -142,8 +127,7 @@ public class ActiveMQCrashTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = createInVMNonHALocator(); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AddressSettingsTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AddressSettingsTest.java index ad0ed80f73..d684a6774b 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AddressSettingsTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AddressSettingsTest.java @@ -30,8 +30,8 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Assert; import org.junit.Test; -public class AddressSettingsTest extends ActiveMQTestBase -{ +public class AddressSettingsTest extends ActiveMQTestBase { + private final SimpleString addressA = new SimpleString("addressA"); private final SimpleString addressA2 = new SimpleString("add.addressA"); @@ -61,17 +61,12 @@ public class AddressSettingsTest extends ActiveMQTestBase private final SimpleString dlqC = new SimpleString("dlqC"); @Test - public void testSimpleHierarchyWithDLA() throws Exception - { + public void testSimpleHierarchyWithDLA() throws Exception { ActiveMQServer server = createServer(false); server.start(); - AddressSettings addressSettings = new AddressSettings() - .setDeadLetterAddress(dlaA) - .setMaxDeliveryAttempts(1); - AddressSettings addressSettings2 = new AddressSettings() - .setDeadLetterAddress(dlaB) - .setMaxDeliveryAttempts(1); + AddressSettings addressSettings = new AddressSettings().setDeadLetterAddress(dlaA).setMaxDeliveryAttempts(1); + AddressSettings addressSettings2 = new AddressSettings().setDeadLetterAddress(dlaB).setMaxDeliveryAttempts(1); HierarchicalRepository repos = server.getAddressSettingsRepository(); repos.addMatch(addressA.toString(), addressSettings); repos.addMatch(addressB.toString(), addressSettings2); @@ -118,17 +113,12 @@ public class AddressSettingsTest extends ActiveMQTestBase } @Test - public void test2LevelHierarchyWithDLA() throws Exception - { + public void test2LevelHierarchyWithDLA() throws Exception { ActiveMQServer server = createServer(false); server.start(); - AddressSettings addressSettings = new AddressSettings() - .setDeadLetterAddress(dlaA) - .setMaxDeliveryAttempts(1); - AddressSettings addressSettings2 = new AddressSettings() - .setDeadLetterAddress(dlaB) - .setMaxDeliveryAttempts(1); + AddressSettings addressSettings = new AddressSettings().setDeadLetterAddress(dlaA).setMaxDeliveryAttempts(1); + AddressSettings addressSettings2 = new AddressSettings().setDeadLetterAddress(dlaB).setMaxDeliveryAttempts(1); HierarchicalRepository repos = server.getAddressSettingsRepository(); repos.addMatch(addressA.toString(), addressSettings); repos.addMatch("#", addressSettings2); @@ -175,16 +165,11 @@ public class AddressSettingsTest extends ActiveMQTestBase } @Test - public void test2LevelWordHierarchyWithDLA() throws Exception - { + public void test2LevelWordHierarchyWithDLA() throws Exception { ActiveMQServer server = createServer(false); server.start(); - AddressSettings addressSettings = new AddressSettings() - .setDeadLetterAddress(dlaA) - .setMaxDeliveryAttempts(1); - AddressSettings addressSettings2 = new AddressSettings() - .setDeadLetterAddress(dlaB) - .setMaxDeliveryAttempts(1); + AddressSettings addressSettings = new AddressSettings().setDeadLetterAddress(dlaA).setMaxDeliveryAttempts(1); + AddressSettings addressSettings2 = new AddressSettings().setDeadLetterAddress(dlaB).setMaxDeliveryAttempts(1); HierarchicalRepository repos = server.getAddressSettingsRepository(); repos.addMatch(addressA.toString(), addressSettings); repos.addMatch("*", addressSettings2); @@ -230,20 +215,13 @@ public class AddressSettingsTest extends ActiveMQTestBase } @Test - public void test3LevelHierarchyWithDLA() throws Exception - { + public void test3LevelHierarchyWithDLA() throws Exception { ActiveMQServer server = createServer(false); server.start(); - AddressSettings addressSettings = new AddressSettings() - .setDeadLetterAddress(dlaA) - .setMaxDeliveryAttempts(1); - AddressSettings addressSettings2 = new AddressSettings() - .setDeadLetterAddress(dlaB) - .setMaxDeliveryAttempts(1); - AddressSettings addressSettings3 = new AddressSettings() - .setDeadLetterAddress(dlaC) - .setMaxDeliveryAttempts(1); + AddressSettings addressSettings = new AddressSettings().setDeadLetterAddress(dlaA).setMaxDeliveryAttempts(1); + AddressSettings addressSettings2 = new AddressSettings().setDeadLetterAddress(dlaB).setMaxDeliveryAttempts(1); + AddressSettings addressSettings3 = new AddressSettings().setDeadLetterAddress(dlaC).setMaxDeliveryAttempts(1); HierarchicalRepository repos = server.getAddressSettingsRepository(); repos.addMatch(addressA2.toString(), addressSettings); repos.addMatch("add.*", addressSettings2); @@ -306,18 +284,13 @@ public class AddressSettingsTest extends ActiveMQTestBase } @Test - public void testOverrideHierarchyWithDLA() throws Exception - { + public void testOverrideHierarchyWithDLA() throws Exception { ActiveMQServer server = createServer(false); server.start(); - AddressSettings addressSettings = new AddressSettings() - .setMaxDeliveryAttempts(1); - AddressSettings addressSettings2 = new AddressSettings() - .setMaxDeliveryAttempts(1); - AddressSettings addressSettings3 = new AddressSettings() - .setDeadLetterAddress(dlaC) - .setMaxDeliveryAttempts(1); + AddressSettings addressSettings = new AddressSettings().setMaxDeliveryAttempts(1); + AddressSettings addressSettings2 = new AddressSettings().setMaxDeliveryAttempts(1); + AddressSettings addressSettings3 = new AddressSettings().setDeadLetterAddress(dlaC).setMaxDeliveryAttempts(1); HierarchicalRepository repos = server.getAddressSettingsRepository(); repos.addMatch(addressA2.toString(), addressSettings); repos.addMatch("add.*", addressSettings2); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AutoCloseCoreTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AutoCloseCoreTest.java index 747ada687d..e8ddde22cb 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AutoCloseCoreTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AutoCloseCoreTest.java @@ -22,25 +22,21 @@ import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.tests.util.SingleServerTestBase; import org.junit.Test; -public class AutoCloseCoreTest extends SingleServerTestBase -{ +public class AutoCloseCoreTest extends SingleServerTestBase { @Test - public void testAutClose() throws Exception - { + public void testAutClose() throws Exception { ServerLocator locatorx; ClientSession sessionx; ClientSessionFactory factoryx; try (ServerLocator locator = createInVMNonHALocator(); ClientSessionFactory factory = locator.createSessionFactory(); - ClientSession session = factory.createSession(false, false)) - { + ClientSession session = factory.createSession(false, false)) { locatorx = locator; sessionx = session; factoryx = factory; } - assertTrue(locatorx.isClosed()); assertTrue(sessionx.isClosed()); assertTrue(factoryx.isClosed()); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AutoCreateJmsQueueTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AutoCreateJmsQueueTest.java index b4f63fafb0..4a12d9d3cf 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AutoCreateJmsQueueTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AutoCreateJmsQueueTest.java @@ -38,11 +38,10 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class AutoCreateJmsQueueTest extends JMSTestBase -{ +public class AutoCreateJmsQueueTest extends JMSTestBase { + @Test - public void testAutoCreateOnSendToQueue() throws Exception - { + public void testAutoCreateOnSendToQueue() throws Exception { Connection connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -52,8 +51,7 @@ public class AutoCreateJmsQueueTest extends JMSTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage mess = session.createTextMessage("msg" + i); producer.send(mess); } @@ -63,8 +61,7 @@ public class AutoCreateJmsQueueTest extends JMSTestBase MessageConsumer messageConsumer = session.createConsumer(queue); connection.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { Message m = messageConsumer.receive(5000); Assert.assertNotNull(m); } @@ -73,8 +70,7 @@ public class AutoCreateJmsQueueTest extends JMSTestBase } @Test - public void testAutoCreateOnSendToQueueAnonymousProducer() throws Exception - { + public void testAutoCreateOnSendToQueueAnonymousProducer() throws Exception { Connection connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -84,8 +80,7 @@ public class AutoCreateJmsQueueTest extends JMSTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage mess = session.createTextMessage("msg" + i); producer.send(queue, mess); } @@ -95,8 +90,7 @@ public class AutoCreateJmsQueueTest extends JMSTestBase MessageConsumer messageConsumer = session.createConsumer(queue); connection.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { Message m = messageConsumer.receive(5000); Assert.assertNotNull(m); } @@ -105,11 +99,10 @@ public class AutoCreateJmsQueueTest extends JMSTestBase } @Test - public void testAutoCreateOnSendToQueueSecurity() throws Exception - { - ((ActiveMQSecurityManagerImpl)server.getSecurityManager()).getConfiguration().addUser("guest", "guest"); - ((ActiveMQSecurityManagerImpl)server.getSecurityManager()).getConfiguration().setDefaultUser("guest"); - ((ActiveMQSecurityManagerImpl)server.getSecurityManager()).getConfiguration().addRole("guest", "rejectAll"); + public void testAutoCreateOnSendToQueueSecurity() throws Exception { + ((ActiveMQSecurityManagerImpl) server.getSecurityManager()).getConfiguration().addUser("guest", "guest"); + ((ActiveMQSecurityManagerImpl) server.getSecurityManager()).getConfiguration().setDefaultUser("guest"); + ((ActiveMQSecurityManagerImpl) server.getSecurityManager()).getConfiguration().addRole("guest", "rejectAll"); Role role = new Role("rejectAll", false, false, false, false, false, false, false); Set roles = new HashSet(); roles.add(role); @@ -119,13 +112,11 @@ public class AutoCreateJmsQueueTest extends JMSTestBase javax.jms.Queue queue = ActiveMQJMSClient.createQueue("test"); - try - { + try { MessageProducer producer = session.createProducer(queue); Assert.fail("Creating a producer here should throw a JMSSecurityException"); } - catch (Exception e) - { + catch (Exception e) { Assert.assertTrue(e instanceof JMSSecurityException); } @@ -133,20 +124,17 @@ public class AutoCreateJmsQueueTest extends JMSTestBase } @Test - public void testAutoCreateOnSendToTopic() throws Exception - { + public void testAutoCreateOnSendToTopic() throws Exception { Connection connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); javax.jms.Topic topic = ActiveMQJMSClient.createTopic("test"); - try - { + try { MessageProducer producer = session.createProducer(topic); Assert.fail("Creating a producer here should throw an exception"); } - catch (Exception e) - { + catch (Exception e) { Assert.assertTrue(e instanceof InvalidDestinationException); } @@ -154,8 +142,7 @@ public class AutoCreateJmsQueueTest extends JMSTestBase } @Test - public void testAutoCreateOnConsumeFromQueue() throws Exception - { + public void testAutoCreateOnConsumeFromQueue() throws Exception { Connection connection = null; connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -175,21 +162,18 @@ public class AutoCreateJmsQueueTest extends JMSTestBase } @Test - public void testAutoCreateOnConsumeFromTopic() throws Exception - { + public void testAutoCreateOnConsumeFromTopic() throws Exception { Connection connection = null; connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); javax.jms.Topic topic = ActiveMQJMSClient.createTopic("test"); - try - { + try { MessageConsumer messageConsumer = session.createConsumer(topic); Assert.fail("Creating a consumer here should throw an exception"); } - catch (Exception e) - { + catch (Exception e) { Assert.assertTrue(e instanceof InvalidDestinationException); } @@ -198,20 +182,18 @@ public class AutoCreateJmsQueueTest extends JMSTestBase @Before @Override - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - ((ActiveMQSecurityManagerImpl)server.getSecurityManager()).getConfiguration().addUser("guest", "guest"); - ((ActiveMQSecurityManagerImpl)server.getSecurityManager()).getConfiguration().setDefaultUser("guest"); - ((ActiveMQSecurityManagerImpl)server.getSecurityManager()).getConfiguration().addRole("guest", "allowAll"); + ((ActiveMQSecurityManagerImpl) server.getSecurityManager()).getConfiguration().addUser("guest", "guest"); + ((ActiveMQSecurityManagerImpl) server.getSecurityManager()).getConfiguration().setDefaultUser("guest"); + ((ActiveMQSecurityManagerImpl) server.getSecurityManager()).getConfiguration().addRole("guest", "allowAll"); Role role = new Role("allowAll", true, true, true, true, true, true, true); Set roles = new HashSet(); roles.add(role); server.getSecurityRepository().addMatch("#", roles); } - protected boolean useSecurity() - { + protected boolean useSecurity() { return true; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AutoDeleteJmsQueueTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AutoDeleteJmsQueueTest.java index 7ef045128c..018667e9ba 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AutoDeleteJmsQueueTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AutoDeleteJmsQueueTest.java @@ -30,11 +30,10 @@ import org.apache.activemq.artemis.core.server.Queue; import org.junit.Assert; import org.junit.Test; -public class AutoDeleteJmsQueueTest extends JMSTestBase -{ +public class AutoDeleteJmsQueueTest extends JMSTestBase { + @Test - public void testAutoDelete() throws Exception - { + public void testAutoDelete() throws Exception { Connection connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -44,8 +43,7 @@ public class AutoDeleteJmsQueueTest extends JMSTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage mess = session.createTextMessage("msg" + i); producer.send(mess); } @@ -55,8 +53,7 @@ public class AutoDeleteJmsQueueTest extends JMSTestBase MessageConsumer messageConsumer = session.createConsumer(queue); connection.start(); - for (int i = 0; i < numMessages - 1; i++) - { + for (int i = 0; i < numMessages - 1; i++) { Message m = messageConsumer.receive(5000); Assert.assertNotNull(m); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AutogroupIdTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AutogroupIdTest.java index 37ffcee5fe..0866312071 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AutogroupIdTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AutogroupIdTest.java @@ -34,8 +34,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class AutogroupIdTest extends ActiveMQTestBase -{ +public class AutogroupIdTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; public final SimpleString addressA = new SimpleString("addressA"); @@ -56,8 +56,7 @@ public class AutogroupIdTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(false); @@ -74,8 +73,7 @@ public class AutogroupIdTest extends ActiveMQTestBase * */ @Test - public void testGroupIdAutomaticallySet() throws Exception - { + public void testGroupIdAutomaticallySet() throws Exception { locator.setAutoGroup(true); ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(false, true, true); @@ -100,8 +98,7 @@ public class AutogroupIdTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { producer.send(session.createMessage(false)); } waitForLatch(latch); @@ -119,8 +116,7 @@ public class AutogroupIdTest extends ActiveMQTestBase * tests when the autogroupid is set only 2 consumers (out of 3) gets all the messages from 2 producers * */ @Test - public void testGroupIdAutomaticallySetMultipleProducers() throws Exception - { + public void testGroupIdAutomaticallySetMultipleProducers() throws Exception { locator.setAutoGroup(true); ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(false, true, true); @@ -147,12 +143,10 @@ public class AutogroupIdTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { producer.send(session.createMessage(false)); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { producer2.send(session.createMessage(false)); } waitForLatch(latch); @@ -168,8 +162,7 @@ public class AutogroupIdTest extends ActiveMQTestBase * tests that even though we have a grouping round robin distributor we don't pin the consumer as autogroup is false * */ @Test - public void testGroupIdAutomaticallyNotSet() throws Exception - { + public void testGroupIdAutomaticallyNotSet() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(false, true, true); @@ -192,8 +185,7 @@ public class AutogroupIdTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { producer.send(session.createMessage(false)); } waitForLatch(latch); @@ -205,26 +197,22 @@ public class AutogroupIdTest extends ActiveMQTestBase } - private static class MyMessageHandler implements MessageHandler - { + private static class MyMessageHandler implements MessageHandler { + int messagesReceived = 0; private final CountDownLatch latch; - public MyMessageHandler(final CountDownLatch latch) - { + public MyMessageHandler(final CountDownLatch latch) { this.latch = latch; } - public void onMessage(final ClientMessage message) - { + public void onMessage(final ClientMessage message) { messagesReceived++; - try - { + try { message.acknowledge(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { e.printStackTrace(); } latch.countDown(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/BlockingSendTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/BlockingSendTest.java index 78cffbe86f..5cd97fdd48 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/BlockingSendTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/BlockingSendTest.java @@ -27,8 +27,7 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Assert; import org.junit.Test; -public class BlockingSendTest extends ActiveMQTestBase -{ +public class BlockingSendTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -41,8 +40,7 @@ public class BlockingSendTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testSinglePersistentBlockingNonSync() throws Exception - { + public void testSinglePersistentBlockingNonSync() throws Exception { ActiveMQServer server = createServer(true); ClientSession session = null; ClientSessionFactory factory = null; @@ -55,8 +53,7 @@ public class BlockingSendTest extends ActiveMQTestBase server.start(); System.out.println("sync = " + server.getConfiguration().isJournalSyncNonTransactional()); - locator = createInVMNonHALocator() - .setBlockOnDurableSend(true); + locator = createInVMNonHALocator().setBlockOnDurableSend(true); factory = createSessionFactory(locator); session = factory.createSession(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/CommitRollbackTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/CommitRollbackTest.java index 8e97063d5c..5ff6b0fed8 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/CommitRollbackTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/CommitRollbackTest.java @@ -34,8 +34,8 @@ import org.apache.activemq.artemis.core.server.Queue; import org.junit.Assert; import org.junit.Test; -public class CommitRollbackTest extends ActiveMQTestBase -{ +public class CommitRollbackTest extends ActiveMQTestBase { + public final SimpleString addressA = new SimpleString("addressA"); public final SimpleString addressB = new SimpleString("addressB"); @@ -47,8 +47,7 @@ public class CommitRollbackTest extends ActiveMQTestBase public final SimpleString queueC = new SimpleString("queueC"); @Test - public void testReceiveWithCommit() throws Exception - { + public void testReceiveWithCommit() throws Exception { ActiveMQServer server = createServer(false); server.start(); @@ -60,13 +59,11 @@ public class CommitRollbackTest extends ActiveMQTestBase ClientProducer cp = sendSession.createProducer(addressA); ClientConsumer cc = session.createConsumer(queueA); int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { cp.send(sendSession.createMessage(false)); } session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage cm = cc.receive(5000); Assert.assertNotNull(cm); cm.acknowledge(); @@ -80,8 +77,7 @@ public class CommitRollbackTest extends ActiveMQTestBase } @Test - public void testReceiveWithRollback() throws Exception - { + public void testReceiveWithRollback() throws Exception { ActiveMQServer server = createServer(false); server.start(); @@ -93,13 +89,11 @@ public class CommitRollbackTest extends ActiveMQTestBase ClientProducer cp = sendSession.createProducer(addressA); ClientConsumer cc = session.createConsumer(queueA); int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { cp.send(sendSession.createMessage(false)); } session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage cm = cc.receive(5000); Assert.assertNotNull(cm); cm.acknowledge(); @@ -107,8 +101,7 @@ public class CommitRollbackTest extends ActiveMQTestBase Queue q = (Queue) server.getPostOffice().getBinding(queueA).getBindable(); Assert.assertEquals(numMessages, q.getDeliveringCount()); session.rollback(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage cm = cc.receive(5000); Assert.assertNotNull(cm); cm.acknowledge(); @@ -119,8 +112,7 @@ public class CommitRollbackTest extends ActiveMQTestBase } @Test - public void testReceiveWithRollbackMultipleConsumersDifferentQueues() throws Exception - { + public void testReceiveWithRollbackMultipleConsumersDifferentQueues() throws Exception { ActiveMQServer server = createServer(false); server.start(); @@ -135,14 +127,12 @@ public class CommitRollbackTest extends ActiveMQTestBase ClientConsumer cc = session.createConsumer(queueA); ClientConsumer cc2 = session.createConsumer(queueB); int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { cp.send(sendSession.createMessage(false)); cp2.send(sendSession.createMessage(false)); } session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage cm = cc.receive(5000); Assert.assertNotNull(cm); cm.acknowledge(); @@ -165,13 +155,10 @@ public class CommitRollbackTest extends ActiveMQTestBase } @Test - public void testAsyncConsumerCommit() throws Exception - { + public void testAsyncConsumerCommit() throws Exception { ActiveMQServer server = createServer(false); server.start(); - ServerLocator locator = createInVMNonHALocator() - .setBlockOnAcknowledge(true) - .setAckBatchSize(0); + ServerLocator locator = createInVMNonHALocator().setBlockOnAcknowledge(true).setAckBatchSize(0); ClientSessionFactory cf = createSessionFactory(locator); ClientSession sendSession = cf.createSession(false, true, true); final ClientSession session = cf.createSession(false, true, false); @@ -179,28 +166,21 @@ public class CommitRollbackTest extends ActiveMQTestBase ClientProducer cp = sendSession.createProducer(addressA); ClientConsumer cc = session.createConsumer(queueA); int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { cp.send(sendSession.createMessage(false)); } final CountDownLatch latch = new CountDownLatch(numMessages); session.start(); - cc.setMessageHandler(new MessageHandler() - { - public void onMessage(final ClientMessage message) - { - try - { + cc.setMessageHandler(new MessageHandler() { + public void onMessage(final ClientMessage message) { + try { message.acknowledge(); } - catch (ActiveMQException e) - { - try - { + catch (ActiveMQException e) { + try { session.close(); } - catch (ActiveMQException e1) - { + catch (ActiveMQException e1) { e1.printStackTrace(); } } @@ -220,13 +200,10 @@ public class CommitRollbackTest extends ActiveMQTestBase } @Test - public void testAsyncConsumerRollback() throws Exception - { + public void testAsyncConsumerRollback() throws Exception { ActiveMQServer server = createServer(false); server.start(); - ServerLocator locator = createInVMNonHALocator() - .setBlockOnAcknowledge(true) - .setAckBatchSize(0); + ServerLocator locator = createInVMNonHALocator().setBlockOnAcknowledge(true).setAckBatchSize(0); ClientSessionFactory cf = createSessionFactory(locator); ClientSession sendSession = cf.createSession(false, true, true); final ClientSession session = cf.createSession(false, true, false); @@ -234,8 +211,7 @@ public class CommitRollbackTest extends ActiveMQTestBase ClientProducer cp = sendSession.createProducer(addressA); ClientConsumer cc = session.createConsumer(queueA); int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { cp.send(sendSession.createMessage(false)); } CountDownLatch latch = new CountDownLatch(numMessages); @@ -259,32 +235,26 @@ public class CommitRollbackTest extends ActiveMQTestBase } - private static class ackHandler implements MessageHandler - { + private static class ackHandler implements MessageHandler { + private final ClientSession session; private final CountDownLatch latch; - public ackHandler(final ClientSession session, final CountDownLatch latch) - { + public ackHandler(final ClientSession session, final CountDownLatch latch) { this.session = session; this.latch = latch; } - public void onMessage(final ClientMessage message) - { - try - { + public void onMessage(final ClientMessage message) { + try { message.acknowledge(); } - catch (ActiveMQException e) - { - try - { + catch (ActiveMQException e) { + try { session.close(); } - catch (ActiveMQException e1) - { + catch (ActiveMQException e1) { e1.printStackTrace(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConcurrentCreateDeleteProduceTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConcurrentCreateDeleteProduceTest.java index 205b8d1f5f..2f34455b94 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConcurrentCreateDeleteProduceTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConcurrentCreateDeleteProduceTest.java @@ -40,14 +40,12 @@ import org.junit.Test; * the NPE happened during depaging what let the server to recover itself on the next depage. * To verify a fix on this test against the previous version of QueueImpl look for NPEs on System.err */ -public class ConcurrentCreateDeleteProduceTest extends ActiveMQTestBase -{ +public class ConcurrentCreateDeleteProduceTest extends ActiveMQTestBase { volatile boolean running = true; private final SimpleString ADDRESS = new SimpleString("ADQUEUE"); - AtomicInteger sequence = new AtomicInteger(0); private ActiveMQServer server; private ServerLocator locator; @@ -56,29 +54,19 @@ public class ConcurrentCreateDeleteProduceTest extends ActiveMQTestBase private static final int PAGE_SIZE = 10 * 1024; - @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false) - .setJournalSyncTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false).setJournalSyncTransactional(false); - server = createServer(true, config, - PAGE_SIZE, - PAGE_MAX, - new HashMap()); + server = createServer(true, config, PAGE_SIZE, PAGE_MAX, new HashMap()); server.start(); - locator = createNonHALocator(false) - .setBlockOnDurableSend(false) - .setBlockOnAcknowledge(true); + locator = createNonHALocator(false).setBlockOnDurableSend(false).setBlockOnAcknowledge(true); } @Test - public void testConcurrentProduceCreateAndDelete() throws Throwable - { + public void testConcurrentProduceCreateAndDelete() throws Throwable { ClientSessionFactory factory = locator.createSessionFactory(); ClientSession session = factory.createSession(true, true); ClientProducer producer = session.createProducer(ADDRESS); @@ -89,14 +77,12 @@ public class ConcurrentCreateDeleteProduceTest extends ActiveMQTestBase Consumer[] consumers = new Consumer[10]; - for (int i = 0; i < consumers.length; i++) - { + for (int i = 0; i < consumers.length; i++) { consumers[i] = new Consumer(); consumers[i].start(); } - for (int i = 0; i < 50000 && running; i++) - { + for (int i = 0; i < 50000 && running; i++) { producer.send(session.createMessage(true)); //Thread.sleep(10); } @@ -105,49 +91,39 @@ public class ConcurrentCreateDeleteProduceTest extends ActiveMQTestBase running = false; - - for (Consumer consumer : consumers) - { + for (Consumer consumer : consumers) { consumer.join(); - if (consumer.ex != null) - { + if (consumer.ex != null) { throw consumer.ex; } } } + class Consumer extends Thread { - class Consumer extends Thread - { volatile Throwable ex; - public void run() - { + public void run() { ClientSessionFactory factory; ClientSession session; - try - { + try { factory = locator.createSessionFactory(); session = factory.createSession(false, false); session.start(); int msgcount = 0; - for (int i = 0; i < 100 && running; i++) - { + for (int i = 0; i < 100 && running; i++) { SimpleString queueName = ADDRESS.concat("_" + sequence.incrementAndGet()); session.createQueue(ADDRESS, queueName, true); ClientConsumer consumer = session.createConsumer(queueName); - while (running) - { + while (running) { ClientMessage msg = consumer.receive(5000); - if (msg == null) - { + if (msg == null) { break; } - if (msgcount++ == 500) - { + if (msgcount++ == 500) { msgcount = 0; break; } @@ -159,8 +135,7 @@ public class ConcurrentCreateDeleteProduceTest extends ActiveMQTestBase } session.close(); } - catch (Throwable e) - { + catch (Throwable e) { this.ex = e; e.printStackTrace(); running = false; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConsumerCloseTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConsumerCloseTest.java index a962f7dc82..704445d378 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConsumerCloseTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConsumerCloseTest.java @@ -40,8 +40,7 @@ import org.junit.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -public class ConsumerCloseTest extends ActiveMQTestBase -{ +public class ConsumerCloseTest extends ActiveMQTestBase { private ClientSessionFactory sf; private ActiveMQServer server; @@ -60,38 +59,29 @@ public class ConsumerCloseTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testCanNotUseAClosedConsumer() throws Exception - { + public void testCanNotUseAClosedConsumer() throws Exception { final ClientConsumer consumer = session.createConsumer(queue); consumer.close(); Assert.assertTrue(consumer.isClosed()); - expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() - { - public void run() throws ActiveMQException - { + expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() { + public void run() throws ActiveMQException { consumer.receive(); } }); - expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() - { - public void run() throws ActiveMQException - { + expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() { + public void run() throws ActiveMQException { consumer.receiveImmediate(); } }); - expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() - { - public void run() throws ActiveMQException - { - consumer.setMessageHandler(new MessageHandler() - { - public void onMessage(final ClientMessage message) - { + expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() { + public void run() throws ActiveMQException { + consumer.setMessageHandler(new MessageHandler() { + public void onMessage(final ClientMessage message) { } }); } @@ -100,16 +90,14 @@ public class ConsumerCloseTest extends ActiveMQTestBase // https://jira.jboss.org/jira/browse/JBMESSAGING-1526 @Test - public void testCloseWithManyMessagesInBufferAndSlowConsumer() throws Exception - { + public void testCloseWithManyMessagesInBufferAndSlowConsumer() throws Exception { ClientConsumer consumer = session.createConsumer(queue); ClientProducer producer = session.createProducer(address); final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); producer.send(message); @@ -117,17 +105,14 @@ public class ConsumerCloseTest extends ActiveMQTestBase final CountDownLatch received = new CountDownLatch(1); final CountDownLatch waitingToProceed = new CountDownLatch(1); - class MyHandler implements MessageHandler - { - public void onMessage(final ClientMessage message) - { - try - { + class MyHandler implements MessageHandler { + + public void onMessage(final ClientMessage message) { + try { received.countDown(); waitingToProceed.await(); } - catch (Exception e) - { + catch (Exception e) { } } } @@ -141,14 +126,12 @@ public class ConsumerCloseTest extends ActiveMQTestBase long timeout = System.currentTimeMillis() + 1000; // Instead of waiting a long time (like 1 second) we just make sure the buffer is full on the client - while (((ClientConsumerImpl) consumer).getBufferSize() < 2 && System.currentTimeMillis() > timeout) - { + while (((ClientConsumerImpl) consumer).getBufferSize() < 2 && System.currentTimeMillis() > timeout) { Thread.sleep(10); } waitingToProceed.countDown(); - // Close shouldn't wait for all messages to be processed before closing long start = System.currentTimeMillis(); consumer.close(); @@ -159,9 +142,7 @@ public class ConsumerCloseTest extends ActiveMQTestBase } @Test - public void testCloseWithScheduledRedelivery() throws Exception - { - + public void testCloseWithScheduledRedelivery() throws Exception { AddressSettings settings = new AddressSettings().setRedeliveryDelay(50000); server.getAddressSettingsRepository().addMatch("#", settings); @@ -172,8 +153,7 @@ public class ConsumerCloseTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); producer.send(message); @@ -186,19 +166,16 @@ public class ConsumerCloseTest extends ActiveMQTestBase long timeout = System.currentTimeMillis() + 1000; - while (((ClientConsumerImpl) consumer).getBufferSize() < 2 && System.currentTimeMillis() > timeout) - { + while (((ClientConsumerImpl) consumer).getBufferSize() < 2 && System.currentTimeMillis() > timeout) { Thread.sleep(10); } consumer.close(); - consumer = session.createConsumer(queue); // We received one, so we must receive the others now - for (int i = 0; i < numMessages - 1; i++) - { + for (int i = 0; i < numMessages - 1; i++) { msg = consumer.receive(1000); assertNotNull("Expected message at i=" + i, msg); msg.acknowledge(); @@ -216,9 +193,7 @@ public class ConsumerCloseTest extends ActiveMQTestBase } @Test - public void testCloseWithScheduledRedeliveryWithTX() throws Exception - { - + public void testCloseWithScheduledRedeliveryWithTX() throws Exception { AddressSettings settings = new AddressSettings().setRedeliveryDelay(1000); server.getAddressSettingsRepository().addMatch("#", settings); @@ -227,8 +202,7 @@ public class ConsumerCloseTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.putIntProperty("count", i); producer.send(message); @@ -247,8 +221,7 @@ public class ConsumerCloseTest extends ActiveMQTestBase long timeout = System.currentTimeMillis() + 1000; - while (((ClientConsumerImpl) consumer).getBufferSize() < 2 && System.currentTimeMillis() > timeout) - { + while (((ClientConsumerImpl) consumer).getBufferSize() < 2 && System.currentTimeMillis() > timeout) { Thread.sleep(10); } @@ -256,12 +229,10 @@ public class ConsumerCloseTest extends ActiveMQTestBase session.rollback(); - consumer = session.createConsumer(queue); // We received one, so we must receive the others now - for (int i = 0; i < numMessages - 1; i++) - { + for (int i = 0; i < numMessages - 1; i++) { msg = consumer.receive(1000); assertNotNull("Expected message at i=" + i, msg); msg.acknowledge(); @@ -278,7 +249,6 @@ public class ConsumerCloseTest extends ActiveMQTestBase assertNull(consumer.receiveImmediate()); - // Close shouldn't wait for all messages to be processed before closing long start = System.currentTimeMillis(); consumer.close(); @@ -294,8 +264,7 @@ public class ConsumerCloseTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); Configuration config = createDefaultInVMConfig(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConsumerFilterTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConsumerFilterTest.java index 871ac3dc46..4d5328ece5 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConsumerFilterTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConsumerFilterTest.java @@ -29,8 +29,8 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Before; import org.junit.Test; -public class ConsumerFilterTest extends ActiveMQTestBase -{ +public class ConsumerFilterTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private ActiveMQServer server; @@ -40,8 +40,7 @@ public class ConsumerFilterTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(false); @@ -61,13 +60,11 @@ public class ConsumerFilterTest extends ActiveMQTestBase } @Test - public void testLargeToken() throws Exception - { + public void testLargeToken() throws Exception { StringBuffer token = new StringBuffer(); token.append("'"); - for (int i = 0; i < 5000; i++) - { + for (int i = 0; i < 5000; i++) { token.append("a"); } token.append("'"); @@ -77,9 +74,7 @@ public class ConsumerFilterTest extends ActiveMQTestBase } @Test - public void testNonMatchingMessagesFollowedByMatchingMessages() throws Exception - { - + public void testNonMatchingMessagesFollowedByMatchingMessages() throws Exception { ClientMessage message = session.createMessage(false); @@ -109,11 +104,9 @@ public class ConsumerFilterTest extends ActiveMQTestBase } @Test - public void testNonMatchingMessagesFollowedByMatchingMessagesMany() throws Exception - { + public void testNonMatchingMessagesFollowedByMatchingMessagesMany() throws Exception { - for (int i = 0; i < QueueImpl.MAX_DELIVERIES_IN_LOOP * 2; i++) - { + for (int i = 0; i < QueueImpl.MAX_DELIVERIES_IN_LOOP * 2; i++) { ClientMessage message = session.createMessage(false); message.putStringProperty("animal", "hippo"); @@ -123,8 +116,7 @@ public class ConsumerFilterTest extends ActiveMQTestBase assertNull(consumer.receiveImmediate()); - for (int i = 0; i < QueueImpl.MAX_DELIVERIES_IN_LOOP * 2; i++) - { + for (int i = 0; i < QueueImpl.MAX_DELIVERIES_IN_LOOP * 2; i++) { ClientMessage message = session.createMessage(false); message.putStringProperty("animal", "giraffe"); @@ -132,8 +124,7 @@ public class ConsumerFilterTest extends ActiveMQTestBase producer.send(message); } - for (int i = 0; i < QueueImpl.MAX_DELIVERIES_IN_LOOP * 2; i++) - { + for (int i = 0; i < QueueImpl.MAX_DELIVERIES_IN_LOOP * 2; i++) { ClientMessage received = consumer.receiveImmediate(); assertNotNull(received); @@ -147,8 +138,7 @@ public class ConsumerFilterTest extends ActiveMQTestBase } @Test - public void testTwoConsumers() throws Exception - { + public void testTwoConsumers() throws Exception { ClientConsumer consumer2 = session.createConsumer("foo", "animal='elephant'"); //Create and consume message that matches the first consumer's filter @@ -222,8 +212,7 @@ public class ConsumerFilterTest extends ActiveMQTestBase } @Test - public void testLinkedListOrder() throws Exception - { + public void testLinkedListOrder() throws Exception { ServerLocator locator = createInVMNonHALocator(); ClientSessionFactory sf = createSessionFactory(locator); @@ -279,8 +268,7 @@ public class ConsumerFilterTest extends ActiveMQTestBase * @param consumer * @throws Exception */ - private void readConsumer(String consumerName, ClientConsumer consumer) throws Exception - { + private void readConsumer(String consumerName, ClientConsumer consumer) throws Exception { ClientMessage message = consumer.receive(5000); assertNotNull(message); System.out.println("consumer = " + consumerName + " message, color=" + message.getStringProperty("color") + ", msg = " + message.getStringProperty("value")); @@ -292,8 +280,7 @@ public class ConsumerFilterTest extends ActiveMQTestBase * @param producer * @throws Exception */ - private void sendMessage(ClientSession session, ClientProducer producer, String color, String msg) throws Exception - { + private void sendMessage(ClientSession session, ClientProducer producer, String color, String msg) throws Exception { ClientMessage anyMessage = session.createMessage(true); anyMessage.putStringProperty("color", color); anyMessage.putStringProperty("value", msg); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConsumerRoundRobinTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConsumerRoundRobinTest.java index 1cfb8ec239..8caef8cafb 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConsumerRoundRobinTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConsumerRoundRobinTest.java @@ -31,8 +31,8 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -public class ConsumerRoundRobinTest extends ActiveMQTestBase -{ +public class ConsumerRoundRobinTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; public final SimpleString addressA = new SimpleString("addressA"); @@ -40,8 +40,7 @@ public class ConsumerRoundRobinTest extends ActiveMQTestBase public final SimpleString queueA = new SimpleString("queueA"); @Test - public void testConsumersRoundRobinCorrectly() throws Exception - { + public void testConsumersRoundRobinCorrectly() throws Exception { ActiveMQServer server = createServer(false); server.start(); ServerLocator locator = createInVMNonHALocator(); @@ -62,18 +61,15 @@ public class ConsumerRoundRobinTest extends ActiveMQTestBase ClientProducer cp = session.createProducer(addressA); int numMessage = 10; - for (int i = 0; i < numMessage; i++) - { + for (int i = 0; i < numMessage; i++) { ClientMessage cm = session.createMessage(false); cm.getBodyBuffer().writeInt(i); cp.send(cm); } int currMessage = 0; - for (int i = 0; i < numMessage / 5; i++) - { + for (int i = 0; i < numMessage / 5; i++) { log.info("i is " + i); - for (int j = 0; j < 5; j++) - { + for (int j = 0; j < 5; j++) { log.info("j is " + j); ClientMessage cm = consumers[j].receive(5000); Assert.assertNotNull(cm); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConsumerStuckTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConsumerStuckTest.java index 80baaa3fd5..8d173ae09c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConsumerStuckTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConsumerStuckTest.java @@ -31,21 +31,19 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Before; import org.junit.Test; -public class ConsumerStuckTest extends ActiveMQTestBase -{ +public class ConsumerStuckTest extends ActiveMQTestBase { + private ActiveMQServer server; private final SimpleString QUEUE = new SimpleString("ConsumerTestQueue"); - protected boolean isNetty() - { + protected boolean isNetty() { return true; } @Before @Override - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(false, isNetty()); @@ -54,13 +52,9 @@ public class ConsumerStuckTest extends ActiveMQTestBase } @Test - public void testClientStuckTest() throws Exception - { + public void testClientStuckTest() throws Exception { - ServerLocator locator = createNettyNonHALocator() - .setConnectionTTL(1000) - .setClientFailureCheckPeriod(100) - .setConsumerWindowSize(10 * 1024 * 1024); + ServerLocator locator = createNettyNonHALocator().setConnectionTTL(1000).setClientFailureCheckPeriod(100).setConsumerWindowSize(10 * 1024 * 1024); ClientSessionFactory sf = locator.createSessionFactory(); ((ClientSessionFactoryImpl) sf).stopPingingAfterOne(); @@ -73,43 +67,33 @@ public class ConsumerStuckTest extends ActiveMQTestBase final int numMessages = 10000; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); producer.send(message); } - final ClientConsumer consumer = session.createConsumer(QUEUE); session.start(); final NettyConnection nettyConnection = (NettyConnection) remotingConnection.getTransportConnection(); - - Thread tReceive = new Thread() - { - public void run() - { + Thread tReceive = new Thread() { + public void run() { boolean first = true; - try - { - while (!Thread.interrupted()) - { + try { + while (!Thread.interrupted()) { ClientMessage received = consumer.receive(500); System.out.println("Received " + received); - if (first) - { + if (first) { first = false; nettyConnection.getNettyChannel().config().setAutoRead(false); } - if (received != null) - { + if (received != null) { received.acknowledge(); } } } - catch (Throwable e) - { + catch (Throwable e) { Thread.currentThread().interrupt(); e.printStackTrace(); } @@ -118,8 +102,7 @@ public class ConsumerStuckTest extends ActiveMQTestBase tReceive.start(); - try - { + try { assertEquals(1, server.getSessions().size()); @@ -131,15 +114,13 @@ public class ConsumerStuckTest extends ActiveMQTestBase long timeStart = System.currentTimeMillis(); - while (timeout > System.currentTimeMillis() && (server.getSessions().size() != 0 || server.getConnectionCount() != 0)) - { + while (timeout > System.currentTimeMillis() && (server.getSessions().size() != 0 || server.getConnectionCount() != 0)) { Thread.sleep(10); } System.out.println("Time = " + System.currentTimeMillis() + " time diff = " + (System.currentTimeMillis() - timeStart) + ", connections Size = " + server.getConnectionCount() + " sessions = " + server.getSessions().size()); - if (server.getSessions().size() != 0) - { + if (server.getSessions().size() != 0) { System.out.println(threadDump("Thread dump")); fail("The cleanup wasn't able to finish cleaning the session. It's probably stuck, look at the thread dump generated by the test for more information"); } @@ -148,16 +129,13 @@ public class ConsumerStuckTest extends ActiveMQTestBase System.out.println("sessions = " + server.getSessions().size()); - - if (server.getSessions().size() != 0) - { + if (server.getSessions().size() != 0) { System.out.println(threadDump("Thread dump")); fail("The cleanup wasn't able to finish cleaning the session. It's probably stuck, look at the thread dump generated by the test for more information"); } assertEquals(0, server.getConnectionCount()); } - finally - { + finally { nettyConnection.getNettyChannel().config().setAutoRead(true); tReceive.interrupt(); tReceive.join(); @@ -165,13 +143,9 @@ public class ConsumerStuckTest extends ActiveMQTestBase } @Test - public void testClientStuckTestWithDirectDelivery() throws Exception - { + public void testClientStuckTestWithDirectDelivery() throws Exception { - ServerLocator locator = createNettyNonHALocator() - .setConnectionTTL(1000) - .setClientFailureCheckPeriod(100) - .setConsumerWindowSize(10 * 1024 * 1024); + ServerLocator locator = createNettyNonHALocator().setConnectionTTL(1000).setClientFailureCheckPeriod(100).setConsumerWindowSize(10 * 1024 * 1024); ClientSessionFactory sf = locator.createSessionFactory(); ((ClientSessionFactoryImpl) sf).stopPingingAfterOne(); @@ -180,7 +154,6 @@ public class ConsumerStuckTest extends ActiveMQTestBase session.createQueue(QUEUE, QUEUE, null, false); - final int numMessages = 10000; final ClientConsumer consumer = session.createConsumer(QUEUE); @@ -188,31 +161,23 @@ public class ConsumerStuckTest extends ActiveMQTestBase final NettyConnection nettyConnection = (NettyConnection) remotingConnection.getTransportConnection(); - - Thread tReceive = new Thread() - { - public void run() - { + Thread tReceive = new Thread() { + public void run() { boolean first = true; - try - { - while (!Thread.interrupted()) - { + try { + while (!Thread.interrupted()) { ClientMessage received = consumer.receive(500); System.out.println("Received " + received); - if (first) - { + if (first) { first = false; nettyConnection.getNettyChannel().config().setAutoRead(false); } - if (received != null) - { + if (received != null) { received.acknowledge(); } } } - catch (Throwable e) - { + catch (Throwable e) { Thread.currentThread().interrupt(); e.printStackTrace(); } @@ -221,40 +186,32 @@ public class ConsumerStuckTest extends ActiveMQTestBase tReceive.start(); - Thread sender = new Thread() - { - public void run() - { + Thread sender = new Thread() { + public void run() { try ( ServerLocator locator = createNettyNonHALocator(); ClientSessionFactory factory = locator.createSessionFactory(); ClientSession session = factory.createSession(false, true, true, true); ClientProducer producer = session.createProducer(QUEUE); - ) - { - for (int i = 0; i < numMessages; i++) - { + ) { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); producer.send(message); } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } }; - sender.start(); - try - { + try { long timeout = System.currentTimeMillis() + 20000; - while (System.currentTimeMillis() < timeout && server.getSessions().size() != 2) - { + while (System.currentTimeMillis() < timeout && server.getSessions().size() != 2) { Thread.sleep(10); } @@ -266,8 +223,7 @@ public class ConsumerStuckTest extends ActiveMQTestBase timeout = System.currentTimeMillis() + 20000; - while (System.currentTimeMillis() < timeout && server.getSessions().size() != 1) - { + while (System.currentTimeMillis() < timeout && server.getSessions().size() != 1) { Thread.sleep(10); } @@ -275,10 +231,7 @@ public class ConsumerStuckTest extends ActiveMQTestBase System.out.println("sessions = " + server.getSessions().size()); - - - if (server.getSessions().size() != 1) - { + if (server.getSessions().size() != 1) { System.out.println(threadDump("Thread dump")); fail("The cleanup wasn't able to finish cleaning the session. It's probably stuck, look at the thread dump generated by the test for more information"); } @@ -287,14 +240,12 @@ public class ConsumerStuckTest extends ActiveMQTestBase timeout = System.currentTimeMillis() + 20000; - while (System.currentTimeMillis() < timeout && server.getConnectionCount() != 0) - { + while (System.currentTimeMillis() < timeout && server.getConnectionCount() != 0) { Thread.sleep(10); } assertEquals(0, server.getConnectionCount()); } - finally - { + finally { nettyConnection.getNettyChannel().config().setAutoRead(true); tReceive.interrupt(); tReceive.join(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConsumerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConsumerTest.java index 0973691459..bb976f30ef 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConsumerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConsumerTest.java @@ -48,19 +48,14 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) -public class ConsumerTest extends ActiveMQTestBase -{ +public class ConsumerTest extends ActiveMQTestBase { + @Parameterized.Parameters(name = "isNetty={0}") - public static Collection getParameters() - { - return Arrays.asList(new Object[][]{ - {true}, - {false} - }); + public static Collection getParameters() { + return Arrays.asList(new Object[][]{{true}, {false}}); } - public ConsumerTest(boolean netty) - { + public ConsumerTest(boolean netty) { this.netty = netty; } @@ -71,15 +66,13 @@ public class ConsumerTest extends ActiveMQTestBase private ServerLocator locator; - protected boolean isNetty() - { + protected boolean isNetty() { return netty; } @Before @Override - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(false, isNetty()); @@ -90,13 +83,10 @@ public class ConsumerTest extends ActiveMQTestBase } @Test - public void testStressConnection() throws Exception - { + public void testStressConnection() throws Exception { - for (int i = 0; i < 10; i++) - { - ServerLocator locatorSendx = createFactory(isNetty()) - .setReconnectAttempts(-1); + for (int i = 0; i < 10; i++) { + ServerLocator locatorSendx = createFactory(isNetty()).setReconnectAttempts(-1); ClientSessionFactory factoryx = locatorSendx.createSessionFactory(); factoryx.close(); locatorSendx.close(); @@ -104,10 +94,8 @@ public class ConsumerTest extends ActiveMQTestBase } - @Test - public void testConsumerAckImmediateAutoCommitTrue() throws Exception - { + public void testConsumerAckImmediateAutoCommitTrue() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(false, true, true, true); @@ -118,16 +106,14 @@ public class ConsumerTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); producer.send(message); } ClientConsumer consumer = session.createConsumer(QUEUE); session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message2 = consumer.receive(1000); Assert.assertEquals("m" + i, message2.getBodyBuffer().readString()); @@ -140,8 +126,7 @@ public class ConsumerTest extends ActiveMQTestBase } @Test - public void testConsumerAckImmediateAutoCommitFalse() throws Exception - { + public void testConsumerAckImmediateAutoCommitFalse() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); @@ -153,16 +138,14 @@ public class ConsumerTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); producer.send(message); } ClientConsumer consumer = session.createConsumer(QUEUE); session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message2 = consumer.receive(1000); Assert.assertEquals("m" + i, message2.getBodyBuffer().readString()); @@ -175,8 +158,7 @@ public class ConsumerTest extends ActiveMQTestBase } @Test - public void testConsumerAckImmediateAckIgnored() throws Exception - { + public void testConsumerAckImmediateAckIgnored() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); @@ -188,21 +170,18 @@ public class ConsumerTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); producer.send(message); } ClientConsumer consumer = session.createConsumer(QUEUE); session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message2 = consumer.receive(1000); Assert.assertEquals("m" + i, message2.getBodyBuffer().readString()); - if (i < 50) - { + if (i < 50) { message2.acknowledge(); } } @@ -214,8 +193,7 @@ public class ConsumerTest extends ActiveMQTestBase } @Test - public void testConsumerAckImmediateCloseSession() throws Exception - { + public void testConsumerAckImmediateCloseSession() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); @@ -227,21 +205,18 @@ public class ConsumerTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); producer.send(message); } ClientConsumer consumer = session.createConsumer(QUEUE); session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message2 = consumer.receive(1000); Assert.assertEquals("m" + i, message2.getBodyBuffer().readString()); - if (i < 50) - { + if (i < 50) { message2.acknowledge(); } } @@ -256,8 +231,7 @@ public class ConsumerTest extends ActiveMQTestBase } @Test - public void testAcksWithSmallSendWindow() throws Exception - { + public void testAcksWithSmallSendWindow() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(false, true, true); @@ -268,41 +242,31 @@ public class ConsumerTest extends ActiveMQTestBase final int numMessages = 10000; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); producer.send(message); } session.close(); sf.close(); final CountDownLatch latch = new CountDownLatch(numMessages); - server.getRemotingService().addIncomingInterceptor(new Interceptor() - { - public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException - { - if (packet.getType() == PacketImpl.SESS_ACKNOWLEDGE) - { + server.getRemotingService().addIncomingInterceptor(new Interceptor() { + public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { + if (packet.getType() == PacketImpl.SESS_ACKNOWLEDGE) { latch.countDown(); } return true; } }); - ServerLocator locator = createInVMNonHALocator() - .setConfirmationWindowSize(100) - .setAckBatchSize(-1); + ServerLocator locator = createInVMNonHALocator().setConfirmationWindowSize(100).setAckBatchSize(-1); ClientSessionFactory sfReceive = createSessionFactory(locator); ClientSession sessionRec = sfReceive.createSession(false, true, true); ClientConsumer consumer = sessionRec.createConsumer(QUEUE); - consumer.setMessageHandler(new MessageHandler() - { - public void onMessage(final ClientMessage message) - { - try - { + consumer.setMessageHandler(new MessageHandler() { + public void onMessage(final ClientMessage message) { + try { message.acknowledge(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { e.printStackTrace(); } } @@ -315,8 +279,7 @@ public class ConsumerTest extends ActiveMQTestBase // https://jira.jboss.org/browse/HORNETQ-410 @Test - public void testConsumeWithNoConsumerFlowControl() throws Exception - { + public void testConsumeWithNoConsumerFlowControl() throws Exception { ServerLocator locator = createInVMNonHALocator(); @@ -334,16 +297,14 @@ public class ConsumerTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); producer.send(message); } ClientConsumer consumer = session.createConsumer(QUEUE); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(10000); assertNotNull(message); message.acknowledge(); @@ -356,8 +317,7 @@ public class ConsumerTest extends ActiveMQTestBase } @Test - public void testClearListener() throws Exception - { + public void testClearListener() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(false, true, true); @@ -366,10 +326,8 @@ public class ConsumerTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(QUEUE); - consumer.setMessageHandler(new MessageHandler() - { - public void onMessage(final ClientMessage msg) - { + consumer.setMessageHandler(new MessageHandler() { + public void onMessage(final ClientMessage msg) { } }); @@ -380,8 +338,7 @@ public class ConsumerTest extends ActiveMQTestBase } @Test - public void testNoReceiveWithListener() throws Exception - { + public void testNoReceiveWithListener() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(false, true, true); @@ -390,34 +347,27 @@ public class ConsumerTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(QUEUE); - consumer.setMessageHandler(new MessageHandler() - { - public void onMessage(final ClientMessage msg) - { + consumer.setMessageHandler(new MessageHandler() { + public void onMessage(final ClientMessage msg) { } }); - try - { + try { consumer.receiveImmediate(); Assert.fail("Should throw exception"); } - catch (ActiveMQIllegalStateException ise) - { + catch (ActiveMQIllegalStateException ise) { //ok } - catch (ActiveMQException me) - { + catch (ActiveMQException me) { Assert.fail("Wrong exception code"); } session.close(); } - @Test - public void testReceiveAndResend() throws Exception - { + public void testReceiveAndResend() throws Exception { final Set sessions = new ConcurrentHashSet(); final AtomicInteger errors = new AtomicInteger(0); @@ -430,8 +380,7 @@ public class ConsumerTest extends ActiveMQTestBase final CountDownLatch latchReceive = new CountDownLatch(numberOfSessions * numberOfMessages); ClientSessionFactory sf = locator.createSessionFactory(); - for (int i = 0; i < numberOfSessions; i++) - { + for (int i = 0; i < numberOfSessions; i++) { ClientSession session = sf.createSession(false, true, true); @@ -439,25 +388,19 @@ public class ConsumerTest extends ActiveMQTestBase session.createQueue(QUEUE, QUEUE.concat("" + i), null, false); - if (i == 0) - { + if (i == 0) { session.createQueue(QUEUE_RESPONSE, QUEUE_RESPONSE); } - ClientConsumer consumer = session.createConsumer(QUEUE.concat("" + i)); sessions.add(consumer); { - consumer.setMessageHandler(new MessageHandler() - { - public void onMessage(final ClientMessage msg) - { - try - { - ServerLocator locatorSendx = createFactory(isNetty()) - .setReconnectAttempts(-1); + consumer.setMessageHandler(new MessageHandler() { + public void onMessage(final ClientMessage msg) { + try { + ServerLocator locatorSendx = createFactory(isNetty()).setReconnectAttempts(-1); ClientSessionFactory factoryx = locatorSendx.createSessionFactory(); ClientSession sessionSend = factoryx.createSession(true, true); @@ -465,7 +408,6 @@ public class ConsumerTest extends ActiveMQTestBase sessions.add(locatorSendx); sessions.add(factoryx); - final ClientProducer prod = sessionSend.createProducer(QUEUE_RESPONSE); sessionSend.start(); @@ -477,20 +419,17 @@ public class ConsumerTest extends ActiveMQTestBase sessionSend.commit(); sessionSend.close(); factoryx.close(); - if (Thread.currentThread().isInterrupted()) - { + if (Thread.currentThread().isInterrupted()) { System.err.println("Netty has interrupted a thread!!!"); errors.incrementAndGet(); } } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); errors.incrementAndGet(); } - finally - { + finally { latchReceive.countDown(); } } @@ -500,31 +439,24 @@ public class ConsumerTest extends ActiveMQTestBase session.start(); } - - Thread tCons = new Thread() - { - public void run() - { - try - { + Thread tCons = new Thread() { + public void run() { + try { final ServerLocator locatorSend = createFactory(isNetty()); final ClientSessionFactory factory = locatorSend.createSessionFactory(); final ClientSession sessionSend = factory.createSession(true, true); ClientConsumer cons = sessionSend.createConsumer(QUEUE_RESPONSE); sessionSend.start(); - for (int i = 0; i < numberOfMessages * numberOfSessions; i++) - { + for (int i = 0; i < numberOfMessages * numberOfSessions; i++) { ClientMessage msg = cons.receive(5000); - if (msg == null) - { + if (msg == null) { break; } msg.acknowledge(); } - if (cons.receiveImmediate() != null) - { + if (cons.receiveImmediate() != null) { System.out.println("ERROR: Received an extra message"); errors.incrementAndGet(); } @@ -532,8 +464,7 @@ public class ConsumerTest extends ActiveMQTestBase factory.close(); locatorSend.close(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); errors.incrementAndGet(); @@ -547,15 +478,12 @@ public class ConsumerTest extends ActiveMQTestBase ClientSession mainSessionSend = sf.createSession(true, true); ClientProducer mainProd = mainSessionSend.createProducer(QUEUE); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { mainProd.send(mainSessionSend.createMessage(true)); } - latchReceive.await(2, TimeUnit.MINUTES); - tCons.join(); sf.close(); @@ -566,8 +494,7 @@ public class ConsumerTest extends ActiveMQTestBase // https://jira.jboss.org/jira/browse/HORNETQ-111 // Test that, on rollback credits are released for messages cleared in the buffer @Test - public void testConsumerCreditsOnRollback() throws Exception - { + public void testConsumerCreditsOnRollback() throws Exception { locator.setConsumerWindowSize(10000); ClientSessionFactory sf = createSessionFactory(locator); @@ -582,8 +509,7 @@ public class ConsumerTest extends ActiveMQTestBase final byte[] bytes = new byte[1000]; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.getBodyBuffer().writeBytes(bytes); @@ -598,20 +524,17 @@ public class ConsumerTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(QUEUE); session.start(); - for (int i = 0; i < 110; i++) - { + for (int i = 0; i < 110; i++) { ClientMessage message = consumer.receive(); int count = message.getIntProperty("count"); boolean redelivered = message.getDeliveryCount() > 1; - if (count % 2 == 0 && !redelivered) - { + if (count % 2 == 0 && !redelivered) { session.rollback(); } - else - { + else { session.commit(); } } @@ -622,10 +545,8 @@ public class ConsumerTest extends ActiveMQTestBase // https://jira.jboss.org/jira/browse/HORNETQ-111 // Test that, on rollback credits are released for messages cleared in the buffer @Test - public void testConsumerCreditsOnRollbackLargeMessages() throws Exception - { - locator.setConsumerWindowSize(10000) - .setMinLargeMessageSize(1000); + public void testConsumerCreditsOnRollbackLargeMessages() throws Exception { + locator.setConsumerWindowSize(10000).setMinLargeMessageSize(1000); ClientSessionFactory sf = createSessionFactory(locator); @@ -639,8 +560,7 @@ public class ConsumerTest extends ActiveMQTestBase final byte[] bytes = new byte[10000]; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.getBodyBuffer().writeBytes(bytes); @@ -655,20 +575,17 @@ public class ConsumerTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(QUEUE); session.start(); - for (int i = 0; i < 110; i++) - { + for (int i = 0; i < 110; i++) { ClientMessage message = consumer.receive(); int count = message.getIntProperty("count"); boolean redelivered = message.getDeliveryCount() > 1; - if (count % 2 == 0 && !redelivered) - { + if (count % 2 == 0 && !redelivered) { session.rollback(); } - else - { + else { session.commit(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConsumerWindowSizeTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConsumerWindowSizeTest.java index 227a7d730c..4166d47ffd 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConsumerWindowSizeTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ConsumerWindowSizeTest.java @@ -46,8 +46,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class ConsumerWindowSizeTest extends ActiveMQTestBase -{ +public class ConsumerWindowSizeTest extends ActiveMQTestBase { + private final SimpleString addressA = new SimpleString("addressA"); private final SimpleString queueA = new SimpleString("queueA"); @@ -60,22 +60,19 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase private ServerLocator locator; - protected boolean isNetty() - { + protected boolean isNetty() { return false; } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = createFactory(isNetty()); } - private int getMessageEncodeSize(final SimpleString address) throws Exception - { + private int getMessageEncodeSize(final SimpleString address) throws Exception { ServerLocator locator = createInVMNonHALocator(); ClientSessionFactory cf = createSessionFactory(locator); ClientSession session = cf.createSession(false, true, true); @@ -90,8 +87,7 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase // https://jira.jboss.org/jira/browse/HORNETQ-385 @Test - public void testReceiveImmediateWithZeroWindow() throws Exception - { + public void testReceiveImmediateWithZeroWindow() throws Exception { ActiveMQServer server = createServer(false, isNetty()); server.start(); @@ -108,8 +104,7 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase ArrayList consumers = new ArrayList(); ArrayList sessions = new ArrayList(); - for (int i = 0; i < numConsumers; i++) - { + for (int i = 0; i < numConsumers; i++) { ClientSession session1 = sf.createSession(); ClientConsumer consumer = session1.createConsumer("testWindow"); consumers.add(consumer); @@ -135,8 +130,7 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase ClientMessage received = consumer.receive(1000); Assert.assertNotNull(received); - for (ClientSession tmpSess : sessions) - { + for (ClientSession tmpSess : sessions) { tmpSess.close(); } @@ -146,12 +140,10 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase // https://jira.jboss.org/jira/browse/HORNETQ-385 @Test - public void testReceiveImmediateWithZeroWindow2() throws Exception - { + public void testReceiveImmediateWithZeroWindow2() throws Exception { ActiveMQServer server = createServer(true); ServerLocator locator = createInVMNonHALocator(); - try - { + try { server.start(); locator.setConsumerWindowSize(0); @@ -191,16 +183,14 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase session1.close(); sessionProd.close(); } - finally - { + finally { locator.close(); } } // https://jira.jboss.org/jira/browse/HORNETQ-385 @Test - public void testReceiveImmediateWithZeroWindow3() throws Exception - { + public void testReceiveImmediateWithZeroWindow3() throws Exception { ActiveMQServer server = createServer(false, isNetty()); server.start(); @@ -217,8 +207,7 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase ArrayList consumers = new ArrayList(); ArrayList sessions = new ArrayList(); - for (int i = 0; i < numConsumers; i++) - { + for (int i = 0; i < numConsumers; i++) { ClientSession session1 = sf.createSession(); ClientConsumer consumer = session1.createConsumer("testWindow"); consumers.add(consumer); @@ -245,8 +234,7 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase ClientMessage received = consumer.receive(1000); Assert.assertNotNull(received); - for (ClientSession tmpSess : sessions) - { + for (ClientSession tmpSess : sessions) { tmpSess.close(); } @@ -254,8 +242,7 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase } @Test - public void testReceiveImmediateWithZeroWindow4() throws Exception - { + public void testReceiveImmediateWithZeroWindow4() throws Exception { ActiveMQServer server = createServer(false, isNetty()); server.start(); @@ -272,8 +259,7 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase ArrayList consumers = new ArrayList(); ArrayList sessions = new ArrayList(); - for (int i = 0; i < numConsumers; i++) - { + for (int i = 0; i < numConsumers; i++) { ClientSession session1 = sf.createSession(); ClientConsumer consumer = session1.createConsumer("testWindow"); consumers.add(consumer); @@ -300,8 +286,7 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase ClientMessage received = consumer.receive(5000); Assert.assertNotNull(received); - for (ClientSession tmpSess : sessions) - { + for (ClientSession tmpSess : sessions) { tmpSess.close(); } @@ -309,8 +294,7 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase } @Test - public void testMultipleImmediate() throws Exception - { + public void testMultipleImmediate() throws Exception { final int NUMBER_OF_MESSAGES = 200; ActiveMQServer server = createServer(false, isNetty()); @@ -332,25 +316,19 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase final CountDownLatch latchStart = new CountDownLatch(1); final AtomicInteger received = new AtomicInteger(0); - for (int i = 0; i < threads.length; i++) - { - threads[i] = new Thread() - { - public void run() - { - try - { + for (int i = 0; i < threads.length; i++) { + threads[i] = new Thread() { + public void run() { + try { ClientSession session = sf.createSession(false, false); ClientConsumer consumer = session.createConsumer("testWindow"); session.start(); latchStart.await(10, TimeUnit.SECONDS); - while (true) - { + while (true) { ClientMessage msg = consumer.receiveImmediate(); - if (msg == null) - { + if (msg == null) { break; } msg.acknowledge(); @@ -362,35 +340,30 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase } } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); errors.incrementAndGet(); } } }; - threads[i].start(); } - ClientSession senderSession = sf.createSession(false, false); ClientProducer producer = senderSession.createProducer("testWindow"); ClientMessage sent = senderSession.createMessage(true); sent.putStringProperty("hello", "world"); - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { producer.send(sent); senderSession.commit(); } latchStart.countDown(); - for (Thread t : threads) - { + for (Thread t : threads) { t.join(); } @@ -400,8 +373,7 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase } @Test - public void testSingleImmediate() throws Exception - { + public void testSingleImmediate() throws Exception { final int NUMBER_OF_MESSAGES = 200; ActiveMQServer server = createServer(false, isNetty()); @@ -420,15 +392,13 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase final AtomicInteger received = new AtomicInteger(0); - ClientSession senderSession = sf.createSession(false, false); ClientProducer producer = senderSession.createProducer("testWindow"); ClientMessage sent = senderSession.createMessage(true); sent.putStringProperty("hello", "world"); - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { producer.send(sent); } @@ -438,12 +408,10 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer("testWindow"); session.start(); - while (true) - { + while (true) { ClientMessage msg = consumer.receiveImmediate(); - if (msg == null) - { + if (msg == null) { System.out.println("Returning null"); break; } @@ -458,15 +426,13 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase Assert.assertEquals(NUMBER_OF_MESSAGES, received.get()); } - /* * tests send window size. we do this by having 2 receivers on the q. since we roundrobin the consumer for delivery we * know if consumer 1 has received n messages then consumer 2 must have also have received n messages or at least up * to its window size * */ @Test - public void testSendWindowSize() throws Exception - { + public void testSendWindowSize() throws Exception { ActiveMQServer messagingService = createServer(false, isNetty()); locator.setBlockOnNonDurableSend(false); @@ -484,21 +450,18 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase ClientConsumer cc = session.createConsumer(queueA); session.start(); receiveSession.start(); - for (int i = 0; i < numMessage * 4; i++) - { + for (int i = 0; i < numMessage * 4; i++) { cp.send(sendSession.createMessage(false)); } - for (int i = 0; i < numMessage * 2; i++) - { + for (int i = 0; i < numMessage * 2; i++) { ClientMessage m = receivingConsumer.receive(5000); Assert.assertNotNull(m); m.acknowledge(); } receiveSession.close(); - for (int i = 0; i < numMessage * 2; i++) - { + for (int i = 0; i < numMessage * 2; i++) { ClientMessage m = cc.receive(5000); Assert.assertNotNull(m); m.acknowledge(); @@ -511,15 +474,13 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase } @Test - public void testSlowConsumerBufferingOne() throws Exception - { + public void testSlowConsumerBufferingOne() throws Exception { ActiveMQServer server = createServer(false, isNetty()); ClientSession sessionB = null; ClientSession session = null; - try - { + try { final int numberOfMessages = 100; server.start(); @@ -545,13 +506,11 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase ClientProducer prod = session.createProducer(ADDRESS); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { prod.send(createTextMessage(session, "Msg" + i)); } - for (int i = 0; i < numberOfMessages - 1; i++) - { + for (int i = 0; i < numberOfMessages - 1; i++) { ClientMessage msg = cons1.receive(1000); Assert.assertNotNull("expected message at i = " + i, msg); msg.acknowledge(); @@ -570,46 +529,37 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase Assert.assertEquals(0, getMessageCount(server, ADDRESS.toString())); } - finally - { - try - { - if (session != null) - { + finally { + try { + if (session != null) { session.close(); } - if (sessionB != null) - { + if (sessionB != null) { sessionB.close(); } } - catch (Exception ignored) - { + catch (Exception ignored) { } } } @Test - public void testSlowConsumerNoBuffer() throws Exception - { + public void testSlowConsumerNoBuffer() throws Exception { internalTestSlowConsumerNoBuffer(false); } // I believe this test became invalid after we started using another thread to deliver the large message - public void disabled_testSlowConsumerNoBufferLargeMessages() throws Exception - { + public void disabled_testSlowConsumerNoBufferLargeMessages() throws Exception { internalTestSlowConsumerNoBuffer(true); } - private void internalTestSlowConsumerNoBuffer(final boolean largeMessages) throws Exception - { + private void internalTestSlowConsumerNoBuffer(final boolean largeMessages) throws Exception { ActiveMQServer server = createServer(false, isNetty()); ClientSession sessionB = null; ClientSession session = null; - try - { + try { final int numberOfMessages = 100; server.start(); @@ -618,8 +568,7 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase ClientSessionFactory sf = createSessionFactory(locator); - if (largeMessages) - { + if (largeMessages) { sf.getServerLocator().setMinLargeMessageSize(100); } @@ -644,8 +593,7 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase Assert.assertNull(consNeverUsed.receive(1)); ClientMessage msg = createTextMessage(session, "This one will expire"); - if (largeMessages) - { + if (largeMessages) { msg.getBodyBuffer().writeBytes(new byte[600]); } @@ -667,20 +615,17 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase ClientConsumer cons1 = session.createConsumer(ADDRESS); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { msg = createTextMessage(session, "Msg" + i); - if (largeMessages) - { + if (largeMessages) { msg.getBodyBuffer().writeBytes(new byte[600]); } prod.send(msg); } - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { msg = cons1.receive(1000); Assert.assertNotNull("expected message at i = " + i, msg); Assert.assertEquals("Msg" + i, getTextMessage(msg)); @@ -698,54 +643,44 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase Assert.assertEquals(0, getMessageCount(server, ADDRESS.toString())); } - finally - { - try - { - if (session != null) - { + finally { + try { + if (session != null) { session.close(); } - if (sessionB != null) - { + if (sessionB != null) { sessionB.close(); } } - catch (Exception ignored) - { + catch (Exception ignored) { } } } @Test - public void testSlowConsumerNoBuffer2() throws Exception - { + public void testSlowConsumerNoBuffer2() throws Exception { internalTestSlowConsumerNoBuffer2(false); } @Test - public void testSlowConsumerNoBuffer2LargeMessages() throws Exception - { + public void testSlowConsumerNoBuffer2LargeMessages() throws Exception { internalTestSlowConsumerNoBuffer2(true); } - private void internalTestSlowConsumerNoBuffer2(final boolean largeMessages) throws Exception - { + private void internalTestSlowConsumerNoBuffer2(final boolean largeMessages) throws Exception { ActiveMQServer server = createServer(false, isNetty()); ClientSession session1 = null; ClientSession session2 = null; - try - { + try { final int numberOfMessages = 10; server.start(); locator.setConsumerWindowSize(0); - if (largeMessages) - { + if (largeMessages) { locator.setMinLargeMessageSize(100); } @@ -769,11 +704,9 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase ClientProducer prod = session1.createProducer(ADDRESS); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = createTextMessage(session1, "Msg" + i); - if (largeMessages) - { + if (largeMessages) { msg.getBodyBuffer().writeBytes(new byte[600]); } prod.send(msg); @@ -781,8 +714,7 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase ClientConsumerInternal cons2 = (ClientConsumerInternal) session2.createConsumer(ADDRESS); - for (int i = 0; i < numberOfMessages / 2; i++) - { + for (int i = 0; i < numberOfMessages / 2; i++) { ClientMessage msg = cons1.receive(1000); Assert.assertNotNull("expected message at i = " + i, msg); @@ -793,13 +725,10 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase msg.acknowledge(); - Assert.assertEquals("A slow consumer shouldn't buffer anything on the client side!", - 0, - cons1.getBufferSize()); + Assert.assertEquals("A slow consumer shouldn't buffer anything on the client side!", 0, cons1.getBufferSize()); } - for (int i = numberOfMessages / 2; i < numberOfMessages; i++) - { + for (int i = numberOfMessages / 2; i < numberOfMessages; i++) { ClientMessage msg = cons2.receive(1000); Assert.assertNotNull("expected message at i = " + i, msg); @@ -812,9 +741,7 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase msg.acknowledge(); - Assert.assertEquals("A slow consumer shouldn't buffer anything on the client side!", - 0, - cons2.getBufferSize()); + Assert.assertEquals("A slow consumer shouldn't buffer anything on the client side!", 0, cons2.getBufferSize()); } session1.close(); // just to make sure everything is flushed and no pending packets on the sending buffer, or @@ -840,11 +767,9 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase // Note we make sure we send the messages *before* cons2 is created - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = createTextMessage(session1, "Msg" + i); - if (largeMessages) - { + if (largeMessages) { msg.getBodyBuffer().writeBytes(new byte[600]); } prod.send(msg); @@ -854,8 +779,7 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase // Now we receive on cons2 first - for (int i = 0; i < numberOfMessages / 2; i++) - { + for (int i = 0; i < numberOfMessages / 2; i++) { ClientMessage msg = cons2.receive(1000); Assert.assertNotNull("expected message at i = " + i, msg); @@ -863,14 +787,11 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase msg.acknowledge(); - Assert.assertEquals("A slow consumer shouldn't buffer anything on the client side!", - 0, - cons2.getBufferSize()); + Assert.assertEquals("A slow consumer shouldn't buffer anything on the client side!", 0, cons2.getBufferSize()); } - for (int i = numberOfMessages / 2; i < numberOfMessages; i++) - { + for (int i = numberOfMessages / 2; i < numberOfMessages; i++) { ClientMessage msg = cons1.receive(1000); Assert.assertNotNull("expected message at i = " + i, msg); @@ -879,9 +800,7 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase msg.acknowledge(); - Assert.assertEquals("A slow consumer shouldn't buffer anything on the client side!", - 0, - cons1.getBufferSize()); + Assert.assertEquals("A slow consumer shouldn't buffer anything on the client side!", 0, cons1.getBufferSize()); } session1.close(); @@ -891,40 +810,32 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase Assert.assertEquals(0, getMessageCount(server, ADDRESS.toString())); } - finally - { - try - { - if (session1 != null) - { + finally { + try { + if (session1 != null) { session1.close(); } - if (session2 != null) - { + if (session2 != null) { session2.close(); } } - catch (Exception ignored) - { + catch (Exception ignored) { } } } @Test - public void testSaveBuffersOnLargeMessage() throws Exception - { + public void testSaveBuffersOnLargeMessage() throws Exception { ActiveMQServer server = createServer(false, isNetty()); ClientSession session1 = null; - try - { + try { final int numberOfMessages = 10; server.start(); - locator.setConsumerWindowSize(0) - .setMinLargeMessageSize(100); + locator.setConsumerWindowSize(0).setMinLargeMessageSize(100); ClientSessionFactory sf = createSessionFactory(locator); @@ -942,15 +853,13 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase ClientProducer prod = session1.createProducer(ADDRESS); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = session1.createMessage(true); msg.getBodyBuffer().writeBytes(new byte[600]); prod.send(msg); } - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = cons1.receive(1000); Assert.assertNotNull("expected message at i = " + i, msg); @@ -958,9 +867,7 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase msg.acknowledge(); - Assert.assertEquals("A slow consumer shouldn't buffer anything on the client side!", - 0, - cons1.getBufferSize()); + Assert.assertEquals("A slow consumer shouldn't buffer anything on the client side!", 0, cons1.getBufferSize()); } session1.close(); // just to make sure everything is flushed and no pending packets on the sending buffer, or @@ -969,60 +876,49 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase Assert.assertEquals(0, getMessageCount(server, ADDRESS.toString())); } - finally - { - try - { - if (session1 != null) - { + finally { + try { + if (session1 != null) { session1.close(); } } - catch (Exception ignored) - { + catch (Exception ignored) { } } } - class FakeOutputStream extends OutputStream - { + class FakeOutputStream extends OutputStream { /* (non-Javadoc) * @see java.io.OutputStream#write(int) */ @Override - public void write(int b) throws IOException - { + public void write(int b) throws IOException { } } @Test - public void testSlowConsumerOnMessageHandlerNoBuffers() throws Exception - { + public void testSlowConsumerOnMessageHandlerNoBuffers() throws Exception { internalTestSlowConsumerOnMessageHandlerNoBuffers(false); } @Test - public void testSlowConsumerOnMessageHandlerNoBuffersLargeMessage() throws Exception - { + public void testSlowConsumerOnMessageHandlerNoBuffersLargeMessage() throws Exception { internalTestSlowConsumerOnMessageHandlerNoBuffers(true); } @Test - public void testFlowControl() throws Exception - { + public void testFlowControl() throws Exception { internalTestFlowControlOnRollback(false); } @Test - public void testFlowControlLargeMessage() throws Exception - { + public void testFlowControlLargeMessage() throws Exception { internalTestFlowControlOnRollback(true); } - private void internalTestFlowControlOnRollback(final boolean isLargeMessage) throws Exception - { + private void internalTestFlowControlOnRollback(final boolean isLargeMessage) throws Exception { ActiveMQServer server = createServer(false, isNetty()); @@ -1031,21 +927,18 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase ClientSession session = null; - try - { + try { final int numberOfMessages = 100; server.start(); locator.setConsumerWindowSize(300000); - if (isLargeMessage) - { + if (isLargeMessage) { // something to ensure we are using large messages locator.setMinLargeMessageSize(100); } - else - { + else { // To make sure large messages won't kick in, we set anything large locator.setMinLargeMessageSize(Integer.MAX_VALUE); } @@ -1058,11 +951,9 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase session.createQueue(ADDRESS, ADDRESS, true); - ClientProducer producer = session.createProducer(ADDRESS); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = session.createMessage(true); msg.putIntProperty("count", i); msg.getBodyBuffer().writeBytes(new byte[1024]); @@ -1075,12 +966,10 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase session.start(); - for (int repeat = 0; repeat < 100; repeat++) - { + for (int repeat = 0; repeat < 100; repeat++) { long timeout = System.currentTimeMillis() + 2000; // At least 10 messages on the buffer - while (timeout > System.currentTimeMillis() && consumer.getBufferSize() <= 10) - { + while (timeout > System.currentTimeMillis() && consumer.getBufferSize() <= 10) { Thread.sleep(10); } Assert.assertTrue(consumer.getBufferSize() >= 10); @@ -1092,9 +981,7 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase session.rollback(); } - - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = consumer.receive(5000); Assert.assertNotNull(msg); msg.getBodyBuffer().readByte(); @@ -1103,39 +990,31 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase } } - finally - { - try - { - if (session != null) - { + finally { + try { + if (session != null) { session.close(); } } - catch (Exception ignored) - { + catch (Exception ignored) { } } } - - public void internalTestSlowConsumerOnMessageHandlerNoBuffers(final boolean largeMessages) throws Exception - { + public void internalTestSlowConsumerOnMessageHandlerNoBuffers(final boolean largeMessages) throws Exception { ActiveMQServer server = createServer(false, isNetty()); ClientSession sessionB = null; ClientSession session = null; - try - { + try { final int numberOfMessages = 100; server.start(); locator.setConsumerWindowSize(0); - if (largeMessages) - { + if (largeMessages) { locator.setMinLargeMessageSize(100); } @@ -1162,8 +1041,8 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase final CountDownLatch latchRead = new CountDownLatch(1); // It should receive two messages and then give up - class LocalHandler implements MessageHandler - { + class LocalHandler implements MessageHandler { + boolean failed = false; int count = 0; @@ -1171,10 +1050,8 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase /* (non-Javadoc) * @see MessageHandler#onMessage(ClientMessage) */ - public synchronized void onMessage(final ClientMessage message) - { - try - { + public synchronized void onMessage(final ClientMessage message) { + try { String str = getTextMessage(message); failed = failed || !str.equals("Msg" + count); @@ -1182,26 +1059,22 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase message.acknowledge(); latchReceived.countDown(); - if (count++ == 1) - { + if (count++ == 1) { // it will hold here for a while - if (!latchDone.await(TIMEOUT, TimeUnit.SECONDS)) // a timed wait, so if the test fails, one less - // thread around - { + if (!latchDone.await(TIMEOUT, TimeUnit.SECONDS)) { + // a timed wait, so if the test fails, one less thread around new Exception("ClientConsuemrWindowSizeTest Handler couldn't receive signal in less than 5 seconds").printStackTrace(); failed = true; } - if (largeMessages) - { + if (largeMessages) { message.getBodyBuffer().readBytes(new byte[600]); } latchRead.countDown(); } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); // Hudson / JUnit report failed = true; } @@ -1214,11 +1087,9 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase ClientProducer prod = session.createProducer(ADDRESS); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = createTextMessage(session, "Msg" + i); - if (largeMessages) - { + if (largeMessages) { msg.getBodyBuffer().writeBytes(new byte[600]); } prod.send(msg); @@ -1230,8 +1101,7 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase Assert.assertEquals(0, consReceiveOneAndHold.getBufferSize()); - for (int i = 2; i < numberOfMessages; i++) - { + for (int i = 2; i < numberOfMessages; i++) { ClientMessage msg = cons1.receive(1000); Assert.assertNotNull("expected message at i = " + i, msg); Assert.assertEquals("Msg" + i, getTextMessage(msg)); @@ -1256,48 +1126,39 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase Assert.assertFalse("MessageHandler received a failure", handler.failed); } - finally - { - try - { - if (session != null) - { + finally { + try { + if (session != null) { session.close(); } - if (sessionB != null) - { + if (sessionB != null) { sessionB.close(); } } - catch (Exception ignored) - { + catch (Exception ignored) { } } } @Test - public void testSlowConsumerOnMessageHandlerBufferOne() throws Exception - { + public void testSlowConsumerOnMessageHandlerBufferOne() throws Exception { internalTestSlowConsumerOnMessageHandlerBufferOne(false); } - private void internalTestSlowConsumerOnMessageHandlerBufferOne(final boolean largeMessage) throws Exception - { + private void internalTestSlowConsumerOnMessageHandlerBufferOne(final boolean largeMessage) throws Exception { ActiveMQServer server = createServer(false, isNetty()); ClientSession sessionB = null; ClientSession session = null; - try - { + try { final int numberOfMessages = 100; server.start(); locator.setConsumerWindowSize(1); - if (largeMessage) - { + if (largeMessage) { locator.setMinLargeMessageSize(100); } @@ -1322,8 +1183,8 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase final CountDownLatch latchDone = new CountDownLatch(1); // It should receive two messages and then give up - class LocalHandler implements MessageHandler - { + class LocalHandler implements MessageHandler { + boolean failed = false; int count = 0; @@ -1331,14 +1192,11 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase /* (non-Javadoc) * @see MessageHandler#onMessage(ClientMessage) */ - public synchronized void onMessage(final ClientMessage message) - { - try - { + public synchronized void onMessage(final ClientMessage message) { + try { log.info("received msg " + message); String str = getTextMessage(message); - if (ConsumerWindowSizeTest.isTrace) - { + if (ConsumerWindowSizeTest.isTrace) { ConsumerWindowSizeTest.log.trace("Received message " + str); } @@ -1350,18 +1208,15 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase latchReceived.countDown(); latchReceivedBuffered.countDown(); - if (count++ == 1) - { + if (count++ == 1) { // it will hold here for a while - if (!latchDone.await(TIMEOUT, TimeUnit.SECONDS)) - { + if (!latchDone.await(TIMEOUT, TimeUnit.SECONDS)) { new Exception("ClientConsuemrWindowSizeTest Handler couldn't receive signal in less than 5 seconds").printStackTrace(); failed = true; } } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); // Hudson / JUnit report failed = true; } @@ -1372,11 +1227,9 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase ClientProducer prod = session.createProducer(ADDRESS); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = createTextMessage(session, "Msg" + i); - if (largeMessage) - { + if (largeMessage) { msg.getBodyBuffer().writeBytes(new byte[600]); } prod.send(msg); @@ -1389,8 +1242,7 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase log.info("bs " + consReceiveOneAndHold.getBufferSize()); long timeout = System.currentTimeMillis() + 1000 * TIMEOUT; - while (consReceiveOneAndHold.getBufferSize() == 0 && System.currentTimeMillis() < timeout) - { + while (consReceiveOneAndHold.getBufferSize() == 0 && System.currentTimeMillis() < timeout) { log.info("bs " + consReceiveOneAndHold.getBufferSize()); Thread.sleep(10); } @@ -1399,8 +1251,7 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase ClientConsumer cons1 = session.createConsumer(ADDRESS); - for (int i = 3; i < numberOfMessages; i++) - { + for (int i = 3; i < numberOfMessages; i++) { ClientMessage msg = cons1.receive(1000); Assert.assertNotNull("expected message at i = " + i, msg); String text = getTextMessage(msg); @@ -1423,49 +1274,40 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase Assert.assertFalse("MessageHandler received a failure", handler.failed); } - finally - { - try - { - if (session != null) - { + finally { + try { + if (session != null) { session.close(); } - if (sessionB != null) - { + if (sessionB != null) { sessionB.close(); } } - catch (Exception ignored) - { + catch (Exception ignored) { ignored.printStackTrace(); } } } @Test - public void testNoWindowRoundRobin() throws Exception - { + public void testNoWindowRoundRobin() throws Exception { testNoWindowRoundRobin(false); } - private void testNoWindowRoundRobin(final boolean largeMessages) throws Exception - { + private void testNoWindowRoundRobin(final boolean largeMessages) throws Exception { ActiveMQServer server = createServer(false, isNetty()); ClientSession sessionA = null; ClientSession sessionB = null; - try - { + try { final int numberOfMessages = 100; server.start(); locator.setConsumerWindowSize(-1); - if (largeMessages) - { + if (largeMessages) { locator.setMinLargeMessageSize(100); } @@ -1496,16 +1338,13 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase Assert.assertEquals(1, bindings.getBindings().size()); - for (Binding binding : bindings.getBindings()) - { + for (Binding binding : bindings.getBindings()) { Collection consumers = ((QueueBinding) binding).getQueue().getConsumers(); - for (Consumer consumer : consumers) - { + for (Consumer consumer : consumers) { ServerConsumerImpl consumerImpl = (ServerConsumerImpl) consumer; long timeout = System.currentTimeMillis() + 5000; - while (timeout > System.currentTimeMillis() && consumerImpl.getAvailableCredits() != null) - { + while (timeout > System.currentTimeMillis() && consumerImpl.getAvailableCredits() != null) { Thread.sleep(10); } @@ -1516,11 +1355,9 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase ClientProducer prod = sessionA.createProducer(ADDRESS); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = createTextMessage(sessionA, "Msg" + i); - if (largeMessages) - { + if (largeMessages) { msg.getBodyBuffer().writeBytes(new byte[600]); } prod.send(msg); @@ -1531,14 +1368,12 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase boolean foundA = false; boolean foundB = false; - do - { + do { foundA = consA.getBufferSize() == numberOfMessages / 2; foundB = consB.getBufferSize() == numberOfMessages / 2; Thread.sleep(10); - } - while ((!foundA || !foundB) && System.currentTimeMillis() < timeout); + } while ((!foundA || !foundB) && System.currentTimeMillis() < timeout); Assert.assertTrue("ConsumerA didn't receive the expected number of messages on buffer (consA=" + consA.getBufferSize() + ", consB=" + @@ -1546,33 +1381,26 @@ public class ConsumerWindowSizeTest extends ActiveMQTestBase ") foundA = " + foundA + " foundB = " + - foundB, - foundA); + foundB, foundA); Assert.assertTrue("ConsumerB didn't receive the expected number of messages on buffer (consA=" + consA.getBufferSize() + ", consB=" + consB.getBufferSize() + ") foundA = " + foundA + " foundB = " + - foundB, - foundB); + foundB, foundB); } - finally - { - try - { - if (sessionA != null) - { + finally { + try { + if (sessionA != null) { sessionA.close(); } - if (sessionB != null) - { + if (sessionB != null) { sessionB.close(); } } - catch (Exception ignored) - { + catch (Exception ignored) { } } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/CoreClientTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/CoreClientTest.java index f196f58344..18ef2808e9 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/CoreClientTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/CoreClientTest.java @@ -32,8 +32,8 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Assert; import org.junit.Test; -public class CoreClientTest extends ActiveMQTestBase -{ +public class CoreClientTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; // Constants ----------------------------------------------------- @@ -47,19 +47,16 @@ public class CoreClientTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testCoreClientNetty() throws Exception - { + public void testCoreClientNetty() throws Exception { testCoreClient(true); } @Test - public void testCoreClientInVM() throws Exception - { + public void testCoreClientInVM() throws Exception { testCoreClient(false); } - private void testCoreClient(final boolean netty) throws Exception - { + private void testCoreClient(final boolean netty) throws Exception { final SimpleString QUEUE = new SimpleString("CoreClientTestQueue"); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(createDefaultConfig(netty), false)); @@ -77,13 +74,8 @@ public class CoreClientTest extends ActiveMQTestBase final int numMessages = 1000; - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte)1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putStringProperty("foo", "bar"); @@ -104,8 +96,7 @@ public class CoreClientTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message2 = consumer.receive(); ActiveMQBuffer buffer = message2.getBodyBuffer(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/CreateQueueIdempotentTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/CreateQueueIdempotentTest.java index 393a950be4..90ed01ab93 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/CreateQueueIdempotentTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/CreateQueueIdempotentTest.java @@ -31,23 +31,20 @@ import org.junit.Test; import java.util.concurrent.atomic.AtomicInteger; -public class CreateQueueIdempotentTest extends ActiveMQTestBase -{ +public class CreateQueueIdempotentTest extends ActiveMQTestBase { private ActiveMQServer server; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = addServer(ActiveMQServers.newActiveMQServer(createDefaultInVMConfig(), true)); server.start(); } @Test - public void testSequentialCreateQueueIdempotency() throws Exception - { + public void testSequentialCreateQueueIdempotency() throws Exception { final SimpleString QUEUE = new SimpleString("SequentialCreateQueueIdempotency"); ServerLocator locator = createInVMNonHALocator(); @@ -58,24 +55,20 @@ public class CreateQueueIdempotentTest extends ActiveMQTestBase session.createQueue(QUEUE, QUEUE, null, true); - try - { + try { session.createQueue(QUEUE, QUEUE, null, true); fail("Expected exception, queue already exists"); } - catch (ActiveMQQueueExistsException qee) - { + catch (ActiveMQQueueExistsException qee) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } } @Test - public void testConcurrentCreateQueueIdempotency() throws Exception - { + public void testConcurrentCreateQueueIdempotency() throws Exception { final String QUEUE = "ConcurrentCreateQueueIdempotency"; AtomicInteger queuesCreated = new AtomicInteger(0); AtomicInteger failedAttempts = new AtomicInteger(0); @@ -84,20 +77,16 @@ public class CreateQueueIdempotentTest extends ActiveMQTestBase QueueCreator[] queueCreators = new QueueCreator[NUM_THREADS]; - - for (int i = 0; i < NUM_THREADS; i++) - { + for (int i = 0; i < NUM_THREADS; i++) { QueueCreator queueCreator = new QueueCreator(QUEUE, queuesCreated, failedAttempts); queueCreators[i] = queueCreator; } - for (int i = 0; i < NUM_THREADS; i++) - { + for (int i = 0; i < NUM_THREADS; i++) { queueCreators[i].start(); } - for (int i = 0; i < NUM_THREADS; i++) - { + for (int i = 0; i < NUM_THREADS; i++) { queueCreators[i].join(); } @@ -118,28 +107,24 @@ public class CreateQueueIdempotentTest extends ActiveMQTestBase // Inner classes ------------------------------------------------- - class QueueCreator extends Thread - { + class QueueCreator extends Thread { + private String queueName = null; private AtomicInteger queuesCreated = null; private AtomicInteger failedAttempts = null; - - QueueCreator(String queueName, AtomicInteger queuesCreated, AtomicInteger failedAttempts) - { + QueueCreator(String queueName, AtomicInteger queuesCreated, AtomicInteger failedAttempts) { this.queueName = queueName; this.queuesCreated = queuesCreated; this.failedAttempts = failedAttempts; } @Override - public void run() - { + public void run() { ServerLocator locator = null; ClientSession session = null; - try - { + try { locator = createInVMNonHALocator(); ClientSessionFactory sf = createSessionFactory(locator); session = sf.createSession(false, true, true); @@ -147,28 +132,21 @@ public class CreateQueueIdempotentTest extends ActiveMQTestBase session.createQueue(QUEUE, QUEUE, null, true); queuesCreated.incrementAndGet(); } - catch (ActiveMQQueueExistsException qne) - { + catch (ActiveMQQueueExistsException qne) { failedAttempts.incrementAndGet(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } - finally - { - if (locator != null) - { + finally { + if (locator != null) { locator.close(); } - if (session != null) - { - try - { + if (session != null) { + try { session.close(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { e.printStackTrace(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/DeadLetterAddressTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/DeadLetterAddressTest.java index 288b1c2a8a..1a76ff4726 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/DeadLetterAddressTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/DeadLetterAddressTest.java @@ -42,8 +42,8 @@ import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -public class DeadLetterAddressTest extends ActiveMQTestBase -{ +public class DeadLetterAddressTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private ActiveMQServer server; @@ -52,14 +52,11 @@ public class DeadLetterAddressTest extends ActiveMQTestBase private ServerLocator locator; @Test - public void testBasicSend() throws Exception - { + public void testBasicSend() throws Exception { SimpleString dla = new SimpleString("DLA"); SimpleString qName = new SimpleString("q1"); SimpleString adName = new SimpleString("ad1"); - AddressSettings addressSettings = new AddressSettings() - .setMaxDeliveryAttempts(1) - .setDeadLetterAddress(dla); + AddressSettings addressSettings = new AddressSettings().setMaxDeliveryAttempts(1).setDeadLetterAddress(dla); server.getAddressSettingsRepository().addMatch(adName.toString(), addressSettings); SimpleString dlq = new SimpleString("DLQ1"); clientSession.createQueue(dla, dlq, null, false); @@ -87,13 +84,10 @@ public class DeadLetterAddressTest extends ActiveMQTestBase // HORNETQ- 1084 @Test - public void testBasicSendWithDLAButNoBinding() throws Exception - { + public void testBasicSendWithDLAButNoBinding() throws Exception { SimpleString dla = new SimpleString("DLA"); SimpleString qName = new SimpleString("q1"); - AddressSettings addressSettings = new AddressSettings() - .setMaxDeliveryAttempts(1) - .setDeadLetterAddress(dla); + AddressSettings addressSettings = new AddressSettings().setMaxDeliveryAttempts(1).setDeadLetterAddress(dla); server.getAddressSettingsRepository().addMatch(qName.toString(), addressSettings); //SimpleString dlq = new SimpleString("DLQ1"); //clientSession.createQueue(dla, dlq, null, false); @@ -111,18 +105,15 @@ public class DeadLetterAddressTest extends ActiveMQTestBase m = clientConsumer.receiveImmediate(); Assert.assertNull(m); clientConsumer.close(); - Queue q = (Queue)server.getPostOffice().getBinding(qName).getBindable(); + Queue q = (Queue) server.getPostOffice().getBinding(qName).getBindable(); Assert.assertEquals(0, q.getDeliveringCount()); } @Test - public void testBasicSend2times() throws Exception - { + public void testBasicSend2times() throws Exception { SimpleString dla = new SimpleString("DLA"); SimpleString qName = new SimpleString("q1"); - AddressSettings addressSettings = new AddressSettings() - .setMaxDeliveryAttempts(2) - .setDeadLetterAddress(dla); + AddressSettings addressSettings = new AddressSettings().setMaxDeliveryAttempts(2).setDeadLetterAddress(dla); server.getAddressSettingsRepository().addMatch(qName.toString(), addressSettings); SimpleString dlq = new SimpleString("DLQ1"); clientSession.createQueue(dla, dlq, null, false); @@ -154,13 +145,10 @@ public class DeadLetterAddressTest extends ActiveMQTestBase } @Test - public void testReceiveWithListeners() throws Exception - { + public void testReceiveWithListeners() throws Exception { SimpleString dla = new SimpleString("DLA"); SimpleString qName = new SimpleString("q1"); - AddressSettings addressSettings = new AddressSettings() - .setMaxDeliveryAttempts(2) - .setDeadLetterAddress(dla); + AddressSettings addressSettings = new AddressSettings().setMaxDeliveryAttempts(2).setDeadLetterAddress(dla); server.getAddressSettingsRepository().addMatch(qName.toString(), addressSettings); SimpleString dlq = new SimpleString("DLQ1"); clientSession.createQueue(dla, dlq, null, false); @@ -180,29 +168,25 @@ public class DeadLetterAddressTest extends ActiveMQTestBase Assert.assertEquals(m.getBodyBuffer().readString(), "heyho!"); } - class TestHandler implements MessageHandler - { + class TestHandler implements MessageHandler { + private final CountDownLatch latch; int count = 0; private final ClientSession clientSession; - public TestHandler(CountDownLatch latch, ClientSession clientSession) - { + public TestHandler(CountDownLatch latch, ClientSession clientSession) { this.latch = latch; this.clientSession = clientSession; } - public void onMessage(ClientMessage message) - { + public void onMessage(ClientMessage message) { count++; latch.countDown(); - try - { + try { clientSession.rollback(true); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } throw new RuntimeException(); @@ -210,13 +194,10 @@ public class DeadLetterAddressTest extends ActiveMQTestBase } @Test - public void testBasicSendToMultipleQueues() throws Exception - { + public void testBasicSendToMultipleQueues() throws Exception { SimpleString dla = new SimpleString("DLA"); SimpleString qName = new SimpleString("q1"); - AddressSettings addressSettings = new AddressSettings() - .setMaxDeliveryAttempts(1) - .setDeadLetterAddress(dla); + AddressSettings addressSettings = new AddressSettings().setMaxDeliveryAttempts(1).setDeadLetterAddress(dla); server.getAddressSettingsRepository().addMatch(qName.toString(), addressSettings); SimpleString dlq = new SimpleString("DLQ1"); SimpleString dlq2 = new SimpleString("DLQ2"); @@ -251,8 +232,7 @@ public class DeadLetterAddressTest extends ActiveMQTestBase } @Test - public void testBasicSendToNoQueue() throws Exception - { + public void testBasicSendToNoQueue() throws Exception { SimpleString qName = new SimpleString("q1"); AddressSettings addressSettings = new AddressSettings().setMaxDeliveryAttempts(1); server.getAddressSettingsRepository().addMatch(qName.toString(), addressSettings); @@ -273,15 +253,12 @@ public class DeadLetterAddressTest extends ActiveMQTestBase } @Test - public void testHeadersSet() throws Exception - { + public void testHeadersSet() throws Exception { final int MAX_DELIVERIES = 16; final int NUM_MESSAGES = 5; SimpleString dla = new SimpleString("DLA"); SimpleString qName = new SimpleString("q1"); - AddressSettings addressSettings = new AddressSettings() - .setMaxDeliveryAttempts(MAX_DELIVERIES) - .setDeadLetterAddress(dla); + AddressSettings addressSettings = new AddressSettings().setMaxDeliveryAttempts(MAX_DELIVERIES).setDeadLetterAddress(dla); server.getAddressSettingsRepository().addMatch(qName.toString(), addressSettings); SimpleString dlq = new SimpleString("DLQ1"); clientSession.createQueue(dla, dlq, null, false); @@ -292,8 +269,7 @@ public class DeadLetterAddressTest extends ActiveMQTestBase ClientProducer producer = sendSession.createProducer(qName); Map origIds = new HashMap(); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { ClientMessage tm = createTextMessage(clientSession, "Message:" + i); producer.send(tm); } @@ -301,16 +277,13 @@ public class DeadLetterAddressTest extends ActiveMQTestBase ClientConsumer clientConsumer = clientSession.createConsumer(qName); clientSession.start(); - for (int i = 0; i < MAX_DELIVERIES; i++) - { - for (int j = 0; j < NUM_MESSAGES; j++) - { + for (int i = 0; i < MAX_DELIVERIES; i++) { + for (int j = 0; j < NUM_MESSAGES; j++) { ClientMessage tm = clientConsumer.receive(1000); Assert.assertNotNull(tm); tm.acknowledge(); - if (i == 0) - { + if (i == 0) { origIds.put("Message:" + j, tm.getMessageID()); } Assert.assertEquals("Message:" + j, tm.getBodyBuffer().readString()); @@ -321,20 +294,18 @@ public class DeadLetterAddressTest extends ActiveMQTestBase long timeout = System.currentTimeMillis() + 5000; // DLA transfer is asynchronous fired on the rollback - while (System.currentTimeMillis() < timeout && getMessageCount(((Queue)server.getPostOffice().getBinding(qName).getBindable())) != 0) - { + while (System.currentTimeMillis() < timeout && getMessageCount(((Queue) server.getPostOffice().getBinding(qName).getBindable())) != 0) { Thread.sleep(1); } - Assert.assertEquals(0, getMessageCount(((Queue)server.getPostOffice().getBinding(qName).getBindable()))); + Assert.assertEquals(0, getMessageCount(((Queue) server.getPostOffice().getBinding(qName).getBindable()))); ClientMessage m = clientConsumer.receiveImmediate(); Assert.assertNull(m); // All the messages should now be in the DLQ ClientConsumer cc3 = clientSession.createConsumer(dlq); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { ClientMessage tm = cc3.receive(1000); Assert.assertNotNull(tm); @@ -343,9 +314,9 @@ public class DeadLetterAddressTest extends ActiveMQTestBase Assert.assertEquals("Message:" + i, text); // Check the headers - SimpleString origDest = (SimpleString)tm.getObjectProperty(Message.HDR_ORIGINAL_ADDRESS); + SimpleString origDest = (SimpleString) tm.getObjectProperty(Message.HDR_ORIGINAL_ADDRESS); - Long origMessageId = (Long)tm.getObjectProperty(Message.HDR_ORIG_MESSAGE_ID); + Long origMessageId = (Long) tm.getObjectProperty(Message.HDR_ORIG_MESSAGE_ID); Assert.assertEquals(qName, origDest); @@ -359,17 +330,14 @@ public class DeadLetterAddressTest extends ActiveMQTestBase } @Test - public void testDeadlLetterAddressWithDefaultAddressSettings() throws Exception - { + public void testDeadlLetterAddressWithDefaultAddressSettings() throws Exception { int deliveryAttempt = 3; SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); SimpleString deadLetterAddress = RandomUtil.randomSimpleString(); SimpleString deadLetterQueue = RandomUtil.randomSimpleString(); - AddressSettings addressSettings = new AddressSettings() - .setMaxDeliveryAttempts(deliveryAttempt) - .setDeadLetterAddress(deadLetterAddress); + AddressSettings addressSettings = new AddressSettings().setMaxDeliveryAttempts(deliveryAttempt).setDeadLetterAddress(deadLetterAddress); server.getAddressSettingsRepository().setDefault(addressSettings); clientSession.createQueue(address, queue, false); @@ -381,8 +349,7 @@ public class DeadLetterAddressTest extends ActiveMQTestBase clientSession.start(); ClientConsumer clientConsumer = clientSession.createConsumer(queue); - for (int i = 0; i < deliveryAttempt; i++) - { + for (int i = 0; i < deliveryAttempt; i++) { ClientMessage m = clientConsumer.receive(500); Assert.assertNotNull(m); DeadLetterAddressTest.log.info("i is " + i); @@ -402,17 +369,14 @@ public class DeadLetterAddressTest extends ActiveMQTestBase } @Test - public void testDeadlLetterAddressWithWildcardAddressSettings() throws Exception - { + public void testDeadlLetterAddressWithWildcardAddressSettings() throws Exception { int deliveryAttempt = 3; SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); SimpleString deadLetterAddress = RandomUtil.randomSimpleString(); SimpleString deadLetterQueue = RandomUtil.randomSimpleString(); - AddressSettings addressSettings = new AddressSettings() - .setMaxDeliveryAttempts(deliveryAttempt) - .setDeadLetterAddress(deadLetterAddress); + AddressSettings addressSettings = new AddressSettings().setMaxDeliveryAttempts(deliveryAttempt).setDeadLetterAddress(deadLetterAddress); server.getAddressSettingsRepository().addMatch("*", addressSettings); clientSession.createQueue(address, queue, false); @@ -424,8 +388,7 @@ public class DeadLetterAddressTest extends ActiveMQTestBase clientSession.start(); ClientConsumer clientConsumer = clientSession.createConsumer(queue); - for (int i = 0; i < deliveryAttempt; i++) - { + for (int i = 0; i < deliveryAttempt; i++) { ClientMessage m = clientConsumer.receive(500); Assert.assertNotNull(m); Assert.assertEquals(i + 1, m.getDeliveryCount()); @@ -443,8 +406,7 @@ public class DeadLetterAddressTest extends ActiveMQTestBase } @Test - public void testDeadLetterAddressWithOverridenSublevelAddressSettings() throws Exception - { + public void testDeadLetterAddressWithOverridenSublevelAddressSettings() throws Exception { int defaultDeliveryAttempt = 3; int specificeDeliveryAttempt = defaultDeliveryAttempt + 1; @@ -455,13 +417,9 @@ public class DeadLetterAddressTest extends ActiveMQTestBase SimpleString specificDeadLetterAddress = RandomUtil.randomSimpleString(); SimpleString specificDeadLetterQueue = RandomUtil.randomSimpleString(); - AddressSettings defaultAddressSettings = new AddressSettings() - .setMaxDeliveryAttempts(defaultDeliveryAttempt) - .setDeadLetterAddress(defaultDeadLetterAddress); + AddressSettings defaultAddressSettings = new AddressSettings().setMaxDeliveryAttempts(defaultDeliveryAttempt).setDeadLetterAddress(defaultDeadLetterAddress); server.getAddressSettingsRepository().addMatch("*", defaultAddressSettings); - AddressSettings specificAddressSettings = new AddressSettings() - .setMaxDeliveryAttempts(specificeDeliveryAttempt) - .setDeadLetterAddress(specificDeadLetterAddress); + AddressSettings specificAddressSettings = new AddressSettings().setMaxDeliveryAttempts(specificeDeliveryAttempt).setDeadLetterAddress(specificDeadLetterAddress); server.getAddressSettingsRepository().addMatch(address.toString(), specificAddressSettings); clientSession.createQueue(address, queue, false); @@ -477,8 +435,7 @@ public class DeadLetterAddressTest extends ActiveMQTestBase ClientConsumer defaultDeadLetterConsumer = clientSession.createConsumer(defaultDeadLetterQueue); ClientConsumer specificDeadLetterConsumer = clientSession.createConsumer(specificDeadLetterQueue); - for (int i = 0; i < defaultDeliveryAttempt; i++) - { + for (int i = 0; i < defaultDeliveryAttempt; i++) { ClientMessage m = clientConsumer.receive(500); Assert.assertNotNull(m); Assert.assertEquals(i + 1, m.getDeliveryCount()); @@ -502,8 +459,7 @@ public class DeadLetterAddressTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = addServer(ActiveMQServers.newActiveMQServer(createDefaultInVMConfig(), false)); server.start(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/DeliveryOrderTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/DeliveryOrderTest.java index fc97b83011..5cbe1c8a21 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/DeliveryOrderTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/DeliveryOrderTest.java @@ -35,8 +35,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class DeliveryOrderTest extends ActiveMQTestBase -{ +public class DeliveryOrderTest extends ActiveMQTestBase { + public final SimpleString addressA = new SimpleString("addressA"); public final SimpleString queueA = new SimpleString("queueA"); @@ -53,8 +53,7 @@ public class DeliveryOrderTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = createInVMNonHALocator(); server = createServer(false); @@ -63,27 +62,23 @@ public class DeliveryOrderTest extends ActiveMQTestBase } @Test - public void testSendDeliveryOrderOnCommit() throws Exception - { + public void testSendDeliveryOrderOnCommit() throws Exception { ClientSession sendSession = cf.createSession(false, false, true); ClientProducer cp = sendSession.createProducer(addressA); int numMessages = 1000; sendSession.createQueue(addressA, queueA, false); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage cm = sendSession.createMessage(false); cm.getBodyBuffer().writeInt(i); cp.send(cm); - if (i % 10 == 0) - { + if (i % 10 == 0) { sendSession.commit(); } sendSession.commit(); } ClientConsumer c = sendSession.createConsumer(queueA); sendSession.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage cm = c.receive(5000); Assert.assertNotNull(cm); Assert.assertEquals(i, cm.getBodyBuffer().readInt()); @@ -92,30 +87,26 @@ public class DeliveryOrderTest extends ActiveMQTestBase } @Test - public void testReceiveDeliveryOrderOnRollback() throws Exception - { + public void testReceiveDeliveryOrderOnRollback() throws Exception { ClientSession sendSession = cf.createSession(false, true, false); ClientProducer cp = sendSession.createProducer(addressA); int numMessages = 1000; sendSession.createQueue(addressA, queueA, false); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage cm = sendSession.createMessage(false); cm.getBodyBuffer().writeInt(i); cp.send(cm); } ClientConsumer c = sendSession.createConsumer(queueA); sendSession.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage cm = c.receive(5000); Assert.assertNotNull(cm); cm.acknowledge(); Assert.assertEquals(i, cm.getBodyBuffer().readInt()); } sendSession.rollback(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage cm = c.receive(5000); Assert.assertNotNull(cm); cm.acknowledge(); @@ -125,8 +116,7 @@ public class DeliveryOrderTest extends ActiveMQTestBase } @Test - public void testMultipleConsumersMessageOrder() throws Exception - { + public void testMultipleConsumersMessageOrder() throws Exception { ClientSession sendSession = cf.createSession(false, true, true); ClientSession recSession = cf.createSession(false, true, true); sendSession.createQueue(addressA, queueA, false); @@ -136,55 +126,47 @@ public class DeliveryOrderTest extends ActiveMQTestBase ClientConsumer[] clientConsumers = new ClientConsumer[numReceivers]; Receiver[] receivers = new Receiver[numReceivers]; CountDownLatch latch = new CountDownLatch(numMessage); - for (int i = 0; i < numReceivers; i++) - { + for (int i = 0; i < numReceivers; i++) { clientConsumers[i] = recSession.createConsumer(queueA); receivers[i] = new Receiver(latch); clientConsumers[i].setMessageHandler(receivers[i]); } recSession.start(); ClientProducer clientProducer = sendSession.createProducer(addressA); - for (int i = 0; i < numMessage; i++) - { + for (int i = 0; i < numMessage; i++) { ClientMessage cm = sendSession.createMessage(false); cm.getBodyBuffer().writeInt(count.getAndIncrement()); clientProducer.send(cm); } Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); - for (Receiver receiver : receivers) - { + for (Receiver receiver : receivers) { Assert.assertFalse("" + receiver.lastMessage, receiver.failed); } sendSession.close(); recSession.close(); } - class Receiver implements MessageHandler - { + class Receiver implements MessageHandler { + final CountDownLatch latch; int lastMessage = -1; boolean failed = false; - public Receiver(final CountDownLatch latch) - { + public Receiver(final CountDownLatch latch) { this.latch = latch; } - public void onMessage(final ClientMessage message) - { + public void onMessage(final ClientMessage message) { int i = message.getBodyBuffer().readInt(); - try - { + try { message.acknowledge(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { e.printStackTrace(); } - if (i <= lastMessage) - { + if (i <= lastMessage) { failed = true; } lastMessage = i; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/DurableQueueTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/DurableQueueTest.java index 955a0e7583..86ed638084 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/DurableQueueTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/DurableQueueTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.client; + import org.apache.activemq.artemis.core.server.impl.ActiveMQServerImpl; import org.junit.Before; @@ -33,8 +34,7 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.tests.util.RandomUtil; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -public class DurableQueueTest extends ActiveMQTestBase -{ +public class DurableQueueTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -55,8 +55,7 @@ public class DurableQueueTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testConsumeFromDurableQueue() throws Exception - { + public void testConsumeFromDurableQueue() throws Exception { SimpleString queue = RandomUtil.randomSimpleString(); SimpleString address = RandomUtil.randomSimpleString(); @@ -76,8 +75,7 @@ public class DurableQueueTest extends ActiveMQTestBase } @Test - public void testConsumeFromDurableQueueAfterServerRestart() throws Exception - { + public void testConsumeFromDurableQueueAfterServerRestart() throws Exception { SimpleString queue = RandomUtil.randomSimpleString(); SimpleString address = RandomUtil.randomSimpleString(); @@ -105,8 +103,7 @@ public class DurableQueueTest extends ActiveMQTestBase } @Test - public void testUserEncoding() throws Exception - { + public void testUserEncoding() throws Exception { final String userName = "myUser"; session.close(); session = sf.createSession(userName, "myPass", false, true, true, false, 0); @@ -125,8 +122,7 @@ public class DurableQueueTest extends ActiveMQTestBase } @Test - public void testProduceAndConsumeFromDurableQueueAfterServerRestart() throws Exception - { + public void testProduceAndConsumeFromDurableQueueAfterServerRestart() throws Exception { SimpleString queue = RandomUtil.randomSimpleString(); SimpleString address = RandomUtil.randomSimpleString(); @@ -160,8 +156,7 @@ public class DurableQueueTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(true); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ExpireTestOnRestartTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ExpireTestOnRestartTest.java index a3591ae508..2be9db152f 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ExpireTestOnRestartTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ExpireTestOnRestartTest.java @@ -31,23 +31,16 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Before; import org.junit.Test; -public class ExpireTestOnRestartTest extends ActiveMQTestBase -{ +public class ExpireTestOnRestartTest extends ActiveMQTestBase { ActiveMQServer server; - @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(true); - AddressSettings setting = new AddressSettings() - .setExpiryAddress(SimpleString.toSimpleString("exp")) - .setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE) - .setPageSizeBytes(100 * 1024) - .setMaxSizeBytes(200 * 1024); + AddressSettings setting = new AddressSettings().setExpiryAddress(SimpleString.toSimpleString("exp")).setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE).setPageSizeBytes(100 * 1024).setMaxSizeBytes(200 * 1024); server.getConfiguration().setJournalSyncNonTransactional(false); server.getConfiguration().setMessageExpiryScanPeriod(-1); server.getConfiguration().setJournalSyncTransactional(false); @@ -57,8 +50,7 @@ public class ExpireTestOnRestartTest extends ActiveMQTestBase // The biggest problem on this test was the exceptions that happened. I couldn't find any wrong state beyond the exceptions @Test - public void testRestartWithExpire() throws Exception - { + public void testRestartWithExpire() throws Exception { int NUMBER_OF_EXPIRED_MESSAGES = 1000; ServerLocator locator = createInVMNonHALocator(); locator.setBlockOnDurableSend(false); @@ -69,15 +61,13 @@ public class ExpireTestOnRestartTest extends ActiveMQTestBase session.createQueue("exp", "exp", true); ClientProducer prod = session.createProducer("test"); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage message = session.createMessage(true); message.getBodyBuffer().writeBytes(new byte[1024 * 10]); prod.send(message); } - for (int i = 0; i < NUMBER_OF_EXPIRED_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_EXPIRED_MESSAGES; i++) { ClientMessage message = session.createMessage(true); message.putIntProperty("i", i); message.getBodyBuffer().writeBytes(new byte[1024 * 10]); @@ -101,11 +91,9 @@ public class ExpireTestOnRestartTest extends ActiveMQTestBase factory = locator.createSessionFactory(); session = factory.createSession(false, false); - ClientConsumer cons = session.createConsumer("test"); session.start(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage msg = cons.receive(5000); assertNotNull(msg); msg.acknowledge(); @@ -115,16 +103,13 @@ public class ExpireTestOnRestartTest extends ActiveMQTestBase cons.close(); long timeout = System.currentTimeMillis() + 60000; - while (queue.getPageSubscription().getPagingStore().isPaging() && timeout > System.currentTimeMillis()) - { + while (queue.getPageSubscription().getPagingStore().isPaging() && timeout > System.currentTimeMillis()) { Thread.sleep(1); } assertFalse(queue.getPageSubscription().getPagingStore().isPaging()); - cons = session.createConsumer("exp"); - for (int i = 0; i < NUMBER_OF_EXPIRED_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_EXPIRED_MESSAGES; i++) { ClientMessage msg = cons.receive(5000); assertNotNull(msg); msg.acknowledge(); @@ -134,15 +119,13 @@ public class ExpireTestOnRestartTest extends ActiveMQTestBase int extras = 0; ClientMessage msg; - while ((msg = cons.receiveImmediate()) != null) - { + while ((msg = cons.receiveImmediate()) != null) { System.out.println(msg); extras++; } assertEquals("Received extra messages on expire address", 0, extras); - session.commit(); session.close(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ExpiryAddressTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ExpiryAddressTest.java index ba11db7366..5a660f42a5 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ExpiryAddressTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ExpiryAddressTest.java @@ -35,8 +35,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class ExpiryAddressTest extends ActiveMQTestBase -{ +public class ExpiryAddressTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private ActiveMQServer server; @@ -45,8 +45,7 @@ public class ExpiryAddressTest extends ActiveMQTestBase private ServerLocator locator; @Test - public void testBasicSend() throws Exception - { + public void testBasicSend() throws Exception { SimpleString ea = new SimpleString("EA"); SimpleString adSend = new SimpleString("a1"); SimpleString qName = new SimpleString("q1"); @@ -79,8 +78,7 @@ public class ExpiryAddressTest extends ActiveMQTestBase } @Test - public void testBasicSendWithRetroActiveAddressSettings() throws Exception - { + public void testBasicSendWithRetroActiveAddressSettings() throws Exception { // apply "original" address settings SimpleString expiryAddress1 = new SimpleString("expiryAddress1"); SimpleString qName = new SimpleString("q1"); @@ -130,8 +128,7 @@ public class ExpiryAddressTest extends ActiveMQTestBase } @Test - public void testBasicSendToMultipleQueues() throws Exception - { + public void testBasicSendToMultipleQueues() throws Exception { SimpleString ea = new SimpleString("EA"); SimpleString qName = new SimpleString("q1"); SimpleString eq = new SimpleString("EQ1"); @@ -191,8 +188,7 @@ public class ExpiryAddressTest extends ActiveMQTestBase } @Test - public void testBasicSendToNoQueue() throws Exception - { + public void testBasicSendToNoQueue() throws Exception { SimpleString ea = new SimpleString("EA"); SimpleString qName = new SimpleString("q1"); SimpleString eq = new SimpleString("EQ1"); @@ -213,8 +209,7 @@ public class ExpiryAddressTest extends ActiveMQTestBase } @Test - public void testHeadersSet() throws Exception - { + public void testHeadersSet() throws Exception { final int NUM_MESSAGES = 5; SimpleString ea = new SimpleString("DLA"); SimpleString qName = new SimpleString("q1"); @@ -231,8 +226,7 @@ public class ExpiryAddressTest extends ActiveMQTestBase ClientProducer producer = sendSession.createProducer(qName); long expiration = System.currentTimeMillis(); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { ClientMessage tm = createTextMessage(clientSession, "Message:" + i); tm.setExpiration(expiration); producer.send(tm); @@ -246,8 +240,7 @@ public class ExpiryAddressTest extends ActiveMQTestBase ClientConsumer cc3 = clientSession.createConsumer(eq); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { ClientMessage tm = cc3.receive(1000); Assert.assertNotNull(tm); @@ -256,7 +249,7 @@ public class ExpiryAddressTest extends ActiveMQTestBase Assert.assertEquals("Message:" + i, text); // Check the headers - Long actualExpiryTime = (Long)tm.getObjectProperty(Message.HDR_ACTUAL_EXPIRY_TIME); + Long actualExpiryTime = (Long) tm.getObjectProperty(Message.HDR_ACTUAL_EXPIRY_TIME); Assert.assertTrue(actualExpiryTime >= expiration); } @@ -267,8 +260,7 @@ public class ExpiryAddressTest extends ActiveMQTestBase } @Test - public void testExpireWithDefaultAddressSettings() throws Exception - { + public void testExpireWithDefaultAddressSettings() throws Exception { SimpleString ea = new SimpleString("EA"); SimpleString qName = new SimpleString("q1"); SimpleString eq = new SimpleString("EA1"); @@ -296,8 +288,7 @@ public class ExpiryAddressTest extends ActiveMQTestBase } @Test - public void testExpireWithWildcardAddressSettings() throws Exception - { + public void testExpireWithWildcardAddressSettings() throws Exception { SimpleString ea = new SimpleString("EA"); SimpleString qName = new SimpleString("q1"); SimpleString eq = new SimpleString("EA1"); @@ -325,8 +316,7 @@ public class ExpiryAddressTest extends ActiveMQTestBase } @Test - public void testExpireWithOverridenSublevelAddressSettings() throws Exception - { + public void testExpireWithOverridenSublevelAddressSettings() throws Exception { SimpleString address = new SimpleString("prefix.address"); SimpleString queue = RandomUtil.randomSimpleString(); SimpleString defaultExpiryAddress = RandomUtil.randomSimpleString(); @@ -368,14 +358,12 @@ public class ExpiryAddressTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = addServer(ActiveMQServers.newActiveMQServer(createDefaultInVMConfig(), false)); server.start(); // then we create a client as normal - locator = createInVMNonHALocator() - .setBlockOnAcknowledge(true); + locator = createInVMNonHALocator().setBlockOnAcknowledge(true); ClientSessionFactory sessionFactory = createSessionFactory(locator); // There are assertions over sizes that needs to be done after the ACK // was received on server diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ExpiryLargeMessageTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ExpiryLargeMessageTest.java index 471951cb01..38d4515326 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ExpiryLargeMessageTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ExpiryLargeMessageTest.java @@ -37,8 +37,7 @@ import org.junit.Test; /** * This test will send large messages in page-mode, DLQ then, expiry then, and they should be received fine */ -public class ExpiryLargeMessageTest extends ActiveMQTestBase -{ +public class ExpiryLargeMessageTest extends ActiveMQTestBase { private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @@ -63,19 +62,12 @@ public class ExpiryLargeMessageTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testExpiryMessagesThenDLQ() throws Exception - { + public void testExpiryMessagesThenDLQ() throws Exception { ActiveMQServer server = createServer(true); server.getConfiguration().setMessageExpiryScanPeriod(600000); - AddressSettings setting = new AddressSettings() - .setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE) - .setMaxDeliveryAttempts(5) - .setMaxSizeBytes(50 * 1024) - .setPageSizeBytes(10 * 1024) - .setExpiryAddress(EXPIRY) - .setDeadLetterAddress(DLQ); + AddressSettings setting = new AddressSettings().setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE).setMaxDeliveryAttempts(5).setMaxSizeBytes(50 * 1024).setPageSizeBytes(10 * 1024).setExpiryAddress(EXPIRY).setDeadLetterAddress(DLQ); server.getAddressSettingsRepository().addMatch(MY_QUEUE.toString(), setting); server.getAddressSettingsRepository().addMatch(EXPIRY.toString(), setting); @@ -95,28 +87,24 @@ public class ExpiryLargeMessageTest extends ActiveMQTestBase byte[] bufferSample = new byte[messageSize]; - for (int i = 0; i < bufferSample.length; i++) - { + for (int i = 0; i < bufferSample.length; i++) { bufferSample[i] = getSamplebyte(i); } ClientProducer producer = session.createProducer(MY_QUEUE); long timeToExpiry = System.currentTimeMillis() + 1000; - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage message = session.createMessage(true); message.putIntProperty("count", i); // Send a few regular messages first, then all is just large messages - if (i % 2 == 0) - { + if (i % 2 == 0) { message.putBooleanProperty("tst-large", false); message.getBodyBuffer().writeBytes(bufferSample); } - else - { + else { message.putBooleanProperty("tst-large", true); message.setBodyInputStream(createFakeLargeStream(messageSize)); } @@ -139,8 +127,7 @@ public class ExpiryLargeMessageTest extends ActiveMQTestBase Thread.sleep(1500); long timeout = System.currentTimeMillis() + 5000; - while (timeout > System.currentTimeMillis() && getMessageCount(queueExpiry) != numberOfMessages) - { + while (timeout > System.currentTimeMillis() && getMessageCount(queueExpiry) != numberOfMessages) { // What the Expiry Scan would be doing myQueue.expireReferences(); Thread.sleep(50); @@ -154,8 +141,7 @@ public class ExpiryLargeMessageTest extends ActiveMQTestBase session.start(); // Consume half of the messages to make sure all the messages are paging (on the second try) - for (int i = 0; i < numberOfMessages / 2; i++) - { + for (int i = 0; i < numberOfMessages / 2; i++) { ClientMessage msg = cons.receive(5000); assertNotNull(msg); msg.acknowledge(); @@ -165,24 +151,20 @@ public class ExpiryLargeMessageTest extends ActiveMQTestBase cons.close(); - for (int rep = 0; rep < 6; rep++) - { + for (int rep = 0; rep < 6; rep++) { cons = session.createConsumer(EXPIRY); session.start(); log.info("Trying " + rep); - for (int i = 0; i < numberOfMessages / 2; i++) - { + for (int i = 0; i < numberOfMessages / 2; i++) { ClientMessage message = cons.receive(5000); assertNotNull(message); - if (i % 10 == 0) - { + if (i % 10 == 0) { System.out.println("Received " + i); } - for (int location = 0; location < messageSize; location++) - { + for (int location = 0; location < messageSize; location++) { assertEquals(getSamplebyte(location), message.getBodyBuffer().readByte()); } message.acknowledge(); @@ -195,8 +177,7 @@ public class ExpiryLargeMessageTest extends ActiveMQTestBase session.close(); sf.close(); - if (rep == 0) - { + if (rep == 0) { // restart the server at the first try server.stop(); server.start(); @@ -216,8 +197,7 @@ public class ExpiryLargeMessageTest extends ActiveMQTestBase session.close(); sf.close(); - for (int rep = 0; rep < 2; rep++) - { + for (int rep = 0; rep < 2; rep++) { sf = createSessionFactory(locator); session = sf.createSession(false, false); @@ -226,24 +206,20 @@ public class ExpiryLargeMessageTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numberOfMessages / 2; i++) - { + for (int i = 0; i < numberOfMessages / 2; i++) { ClientMessage message = cons.receive(5000); assertNotNull(message); - if (i % 10 == 0) - { + if (i % 10 == 0) { System.out.println("Received " + i); } - for (int location = 0; location < messageSize; location++) - { + for (int location = 0; location < messageSize; location++) { assertEquals(getSamplebyte(location), message.getBodyBuffer().readByte()); } message.acknowledge(); } - if (rep == 0) - { + if (rep == 0) { session.rollback(); session.close(); sf.close(); @@ -269,19 +245,12 @@ public class ExpiryLargeMessageTest extends ActiveMQTestBase * @throws Exception */ @Test - public void testCompatilityWithLinks() throws Exception - { + public void testCompatilityWithLinks() throws Exception { ActiveMQServer server = createServer(true); server.getConfiguration().setMessageExpiryScanPeriod(600000); - AddressSettings setting = new AddressSettings() - .setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE) - .setMaxDeliveryAttempts(5) - .setMaxSizeBytes(-1) - .setPageSizeBytes(10 * 1024) - .setExpiryAddress(EXPIRY) - .setDeadLetterAddress(DLQ); + AddressSettings setting = new AddressSettings().setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE).setMaxDeliveryAttempts(5).setMaxSizeBytes(-1).setPageSizeBytes(10 * 1024).setExpiryAddress(EXPIRY).setDeadLetterAddress(DLQ); server.getAddressSettingsRepository().addMatch(MY_QUEUE.toString(), setting); server.getAddressSettingsRepository().addMatch(EXPIRY.toString(), setting); @@ -301,16 +270,14 @@ public class ExpiryLargeMessageTest extends ActiveMQTestBase byte[] bufferSample = new byte[messageSize]; - for (int i = 0; i < bufferSample.length; i++) - { + for (int i = 0; i < bufferSample.length; i++) { bufferSample[i] = getSamplebyte(i); } ClientProducer producer = session.createProducer(MY_QUEUE); long timeToExpiry = System.currentTimeMillis() + 1000; - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage message = session.createMessage(true); message.putIntProperty("count", i); @@ -369,18 +336,15 @@ public class ExpiryLargeMessageTest extends ActiveMQTestBase cons = session.createConsumer(EXPIRY); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage message = cons.receive(5000); assertNotNull(message); - if (i % 10 == 0) - { + if (i % 10 == 0) { System.out.println("Received " + i); } - for (int location = 0; location < messageSize; location++) - { + for (int location = 0; location < messageSize; location++) { assertEquals(getSamplebyte(location), message.getBodyBuffer().readByte()); } message.acknowledge(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/FailureDeadlockTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/FailureDeadlockTest.java index e42285b6c2..aafb79e0ff 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/FailureDeadlockTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/FailureDeadlockTest.java @@ -39,8 +39,8 @@ import javax.jms.ExceptionListener; import javax.jms.JMSException; import javax.jms.Session; -public class FailureDeadlockTest extends ActiveMQTestBase -{ +public class FailureDeadlockTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private ActiveMQServer server; @@ -53,8 +53,7 @@ public class FailureDeadlockTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(false, createDefaultInVMConfig()); jmsServer = new JMSServerManagerImpl(server); @@ -69,30 +68,24 @@ public class FailureDeadlockTest extends ActiveMQTestBase // Test that two failures concurrently executing and calling the same exception listener // don't deadlock @Test - public void testDeadlock() throws Exception - { - for (int i = 0; i < 100; i++) - { + public void testDeadlock() throws Exception { + for (int i = 0; i < 100; i++) { final Connection conn1 = cf1.createConnection(); Session sess1 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE); - RemotingConnection rc1 = ((ClientSessionInternal)((ActiveMQSession)sess1).getCoreSession()).getConnection(); + RemotingConnection rc1 = ((ClientSessionInternal) ((ActiveMQSession) sess1).getCoreSession()).getConnection(); final Connection conn2 = cf2.createConnection(); Session sess2 = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE); - RemotingConnection rc2 = ((ClientSessionInternal)((ActiveMQSession)sess2).getCoreSession()).getConnection(); + RemotingConnection rc2 = ((ClientSessionInternal) ((ActiveMQSession) sess2).getCoreSession()).getConnection(); - ExceptionListener listener1 = new ExceptionListener() - { - public void onException(final JMSException exception) - { - try - { + ExceptionListener listener1 = new ExceptionListener() { + public void onException(final JMSException exception) { + try { conn2.close(); } - catch (Exception e) - { + catch (Exception e) { FailureDeadlockTest.log.error("Failed to close connection2", e); } } @@ -120,18 +113,16 @@ public class FailureDeadlockTest extends ActiveMQTestBase } } - private class Failer extends Thread - { + private class Failer extends Thread { + RemotingConnection conn; - Failer(final RemotingConnection conn) - { + Failer(final RemotingConnection conn) { this.conn = conn; } @Override - public void run() - { + public void run() { conn.fail(new ActiveMQNotConnectedException("blah")); } } @@ -140,24 +131,20 @@ public class FailureDeadlockTest extends ActiveMQTestBase // Make sure that failing a connection removes it from the connection manager and can't be returned in a subsequent // call @Test - public void testUsingDeadConnection() throws Exception - { - for (int i = 0; i < 100; i++) - { + public void testUsingDeadConnection() throws Exception { + for (int i = 0; i < 100; i++) { final Connection conn1 = cf1.createConnection(); Session sess1 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE); - RemotingConnection rc1 = ((ClientSessionInternal)((ActiveMQSession)sess1).getCoreSession()).getConnection(); + RemotingConnection rc1 = ((ClientSessionInternal) ((ActiveMQSession) sess1).getCoreSession()).getConnection(); - rc1.fail(new ActiveMQNotConnectedException( "blah")); + rc1.fail(new ActiveMQNotConnectedException("blah")); - try - { + try { conn1.createSession(false, Session.AUTO_ACKNOWLEDGE); Assert.fail("should throw exception"); } - catch (JMSException e) - { + catch (JMSException e) { //pass } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/FlowControlOnIgnoreLargeMessageBodyTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/FlowControlOnIgnoreLargeMessageBodyTest.java index 1e960b2adc..4901de1d8b 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/FlowControlOnIgnoreLargeMessageBodyTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/FlowControlOnIgnoreLargeMessageBodyTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.client; + import org.junit.Before; import org.junit.Test; @@ -36,8 +37,8 @@ import javax.naming.NamingException; import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; import org.apache.activemq.artemis.tests.util.JMSTestBase; -public class FlowControlOnIgnoreLargeMessageBodyTest extends JMSTestBase -{ +public class FlowControlOnIgnoreLargeMessageBodyTest extends JMSTestBase { + IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private Topic topic; @@ -56,24 +57,22 @@ public class FlowControlOnIgnoreLargeMessageBodyTest extends JMSTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); jmsServer.createTopic(true, "topicIn", "/topic/topicIn"); - topic = (Topic)namingContext.lookup("/topic/topicIn"); + topic = (Topic) namingContext.lookup("/topic/topicIn"); } @Override - protected boolean usePersistence() - { + protected boolean usePersistence() { return false; } /** * LoadProducer */ - class LoadProducer extends Thread - { + class LoadProducer extends Thread { + private final ConnectionFactory cf; private final Topic topic; @@ -86,45 +85,41 @@ public class FlowControlOnIgnoreLargeMessageBodyTest extends JMSTestBase private int sentMessages = 0; - LoadProducer(final String name, final Topic topic, final ConnectionFactory cf, final int messagesCount) throws Exception - { + LoadProducer(final String name, + final Topic topic, + final ConnectionFactory cf, + final int messagesCount) throws Exception { super(name); this.cf = cf; this.topic = topic; this.messagesCount = messagesCount; } - public void sendStopRequest() - { + public void sendStopRequest() { stopped = false; requestForStop = true; } - public boolean isStopped() - { + public boolean isStopped() { return stopped; } @Override - public void run() - { + public void run() { stopped = false; Connection connection = null; Session session = null; MessageProducer prod; log.info("Starting producer for " + topic + " - " + getName()); - try - { + try { connection = cf.createConnection(); session = connection.createSession(true, Session.SESSION_TRANSACTED); prod = session.createProducer(topic); prod.setDeliveryMode(DeliveryMode.PERSISTENT); - for (int i = 1; i <= messagesCount && !requestForStop; i++) - { - if (error) - { + for (int i = 1; i <= messagesCount && !requestForStop; i++) { + if (error) { break; } sentMessages++; @@ -132,46 +127,37 @@ public class FlowControlOnIgnoreLargeMessageBodyTest extends JMSTestBase msg.setIntProperty(FlowControlOnIgnoreLargeMessageBodyTest.ATTR_MSG_COUNTER, i); msg.writeBytes(new byte[FlowControlOnIgnoreLargeMessageBodyTest.MSG_SIZE]); prod.send(msg); - if (i % 10 == 0) - { + if (i % 10 == 0) { session.commit(); } - if (i % 100 == 0) - { + if (i % 100 == 0) { log.info("Address " + topic + " sent " + i + " messages"); } } System.out.println("Ending producer for " + topic + " - " + getName() + " messages " + sentMessages); } - catch (Exception e) - { + catch (Exception e) { error = true; e.printStackTrace(); } - finally - { - try - { + finally { + try { session.commit(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } - try - { + try { connection.close(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } stopped = true; } - public int getSentMessages() - { + public int getSentMessages() { return sentMessages; } } @@ -179,8 +165,8 @@ public class FlowControlOnIgnoreLargeMessageBodyTest extends JMSTestBase /** * LoadConsumer */ - class LoadConsumer extends Thread - { + class LoadConsumer extends Thread { + private final ConnectionFactory cf; private final Topic topic; @@ -202,8 +188,7 @@ public class FlowControlOnIgnoreLargeMessageBodyTest extends JMSTestBase final Topic topic, final ConnectionFactory cf, final int receiveTimeout, - final int numberOfMessages) - { + final int numberOfMessages) { super(name); this.cf = cf; this.topic = topic; @@ -212,27 +197,23 @@ public class FlowControlOnIgnoreLargeMessageBodyTest extends JMSTestBase this.consumerCreated = consumerCreated; } - public void sendStopRequest() - { + public void sendStopRequest() { stopped = false; requestForStop = true; } - public boolean isStopped() - { + public boolean isStopped() { return stopped; } @Override - public void run() - { + public void run() { Connection connection = null; Session session = null; stopped = false; requestForStop = false; System.out.println("Starting consumer for " + topic + " - " + getName()); - try - { + try { connection = cf.createConnection(); connection.setClientID(getName()); @@ -247,109 +228,81 @@ public class FlowControlOnIgnoreLargeMessageBodyTest extends JMSTestBase int counter = 0; - while (counter < numberOfMessages && !requestForStop && !error) - { - if (counter == 0) - { + while (counter < numberOfMessages && !requestForStop && !error) { + if (counter == 0) { System.out.println("Starting to consume for " + topic + " - " + getName()); } - BytesMessage msg = (BytesMessage)subscriber.receive(receiveTimeout); - if (msg == null) - { + BytesMessage msg = (BytesMessage) subscriber.receive(receiveTimeout); + if (msg == null) { System.out.println("Cannot get message in specified timeout: " + topic + " - " + getName()); error = true; } - else - { + else { counter++; - if (msg.getIntProperty(FlowControlOnIgnoreLargeMessageBodyTest.ATTR_MSG_COUNTER) != counter) - { + if (msg.getIntProperty(FlowControlOnIgnoreLargeMessageBodyTest.ATTR_MSG_COUNTER) != counter) { error = true; } } - if (counter % 10 == 0) - { + if (counter % 10 == 0) { session.commit(); } - if (counter % 100 == 0) - { + if (counter % 100 == 0) { log.info("## " + getName() + " " + topic + " received " + counter); } receivedMessages = counter; } session.commit(); } - catch (Exception e) - { + catch (Exception e) { System.out.println("Exception in consumer " + getName() + " : " + e.getMessage()); e.printStackTrace(); } - finally - { - if (session != null) - { - try - { + finally { + if (session != null) { + try { session.close(); } - catch (JMSException e) - { + catch (JMSException e) { System.err.println("Cannot close session " + e.getMessage()); } } - if (connection != null) - { - try - { + if (connection != null) { + try { connection.close(); } - catch (JMSException e) - { + catch (JMSException e) { System.err.println("Cannot close connection " + e.getMessage()); } } } stopped = true; System.out.println("Stopping consumer for " + topic + - " - " + - getName() + - ", received " + - getReceivedMessages()); + " - " + + getName() + + ", received " + + getReceivedMessages()); } - public int getReceivedMessages() - { + public int getReceivedMessages() { return receivedMessages; } } @Test - public void testFlowControl() - { + public void testFlowControl() { Context context = null; - try - { - LoadProducer producer = new LoadProducer("producer", - topic, - cf, - FlowControlOnIgnoreLargeMessageBodyTest.TOTAL_MESSAGES_COUNT); + try { + LoadProducer producer = new LoadProducer("producer", topic, cf, FlowControlOnIgnoreLargeMessageBodyTest.TOTAL_MESSAGES_COUNT); LoadConsumer[] consumers = new LoadConsumer[CONSUMERS_COUNT]; CountDownLatch latch = new CountDownLatch(CONSUMERS_COUNT); - for (int i = 0; i < consumers.length; i++) - { - consumers[i] = new LoadConsumer(latch, - "consumer " + i, - topic, - cf, - receiveTimeout, - FlowControlOnIgnoreLargeMessageBodyTest.TOTAL_MESSAGES_COUNT); + for (int i = 0; i < consumers.length; i++) { + consumers[i] = new LoadConsumer(latch, "consumer " + i, topic, cf, receiveTimeout, FlowControlOnIgnoreLargeMessageBodyTest.TOTAL_MESSAGES_COUNT); } - for (LoadConsumer consumer : consumers) - { + for (LoadConsumer consumer : consumers) { consumer.start(); } @@ -357,55 +310,43 @@ public class FlowControlOnIgnoreLargeMessageBodyTest extends JMSTestBase producer.start(); producer.join(); - for (LoadConsumer consumer : consumers) - { + for (LoadConsumer consumer : consumers) { consumer.join(); } String errorMessage = null; - if (producer.getSentMessages() != FlowControlOnIgnoreLargeMessageBodyTest.TOTAL_MESSAGES_COUNT) - { + if (producer.getSentMessages() != FlowControlOnIgnoreLargeMessageBodyTest.TOTAL_MESSAGES_COUNT) { errorMessage = "Producer did not send defined count of messages"; } - else - { - for (LoadConsumer consumer : consumers) - { - if (consumer.getReceivedMessages() != FlowControlOnIgnoreLargeMessageBodyTest.TOTAL_MESSAGES_COUNT) - { + else { + for (LoadConsumer consumer : consumers) { + if (consumer.getReceivedMessages() != FlowControlOnIgnoreLargeMessageBodyTest.TOTAL_MESSAGES_COUNT) { errorMessage = "Consumer did not send defined count of messages"; break; } } } - if (errorMessage != null) - { + if (errorMessage != null) { System.err.println(" ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR "); System.err.println(errorMessage); } - else - { + else { System.out.println(" OK "); } assertFalse(error); assertNull(errorMessage); } - catch (Exception e) - { + catch (Exception e) { log.warn(e.getMessage(), e); } - finally - { - if (context != null) - { - try - { + finally { + if (context != null) { + try { context.close(); } - catch (NamingException ex) - { + catch (NamingException ex) { log.warn(ex.getMessage(), ex); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/HangConsumerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/HangConsumerTest.java index 4332fbda7a..37247215a0 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/HangConsumerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/HangConsumerTest.java @@ -76,8 +76,7 @@ import org.junit.Test; * and it will make sure we can still perform certain operations on the queue such as produce * and verify the counters */ -public class HangConsumerTest extends ActiveMQTestBase -{ +public class HangConsumerTest extends ActiveMQTestBase { private ActiveMQServer server; @@ -89,12 +88,10 @@ public class HangConsumerTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - Configuration config = createDefaultInVMConfig() - .setMessageExpiryScanPeriod(10); + Configuration config = createDefaultInVMConfig().setMessageExpiryScanPeriod(10); ActiveMQSecurityManager securityManager = new ActiveMQSecurityManagerImpl(); @@ -106,11 +103,9 @@ public class HangConsumerTest extends ActiveMQTestBase } @Test - public void testHangOnDelivery() throws Exception - { + public void testHangOnDelivery() throws Exception { queue = server.createQueue(QUEUE, QUEUE, null, true, false); - try - { + try { ClientSessionFactory factory = locator.createSessionFactory(); ClientSession sessionProducer = factory.createSession(false, false, false); @@ -167,8 +162,7 @@ public class HangConsumerTest extends ActiveMQTestBase sessionProducer.close(); sessionConsumer.close(); } - finally - { + finally { releaseConsumers(); } } @@ -176,38 +170,34 @@ public class HangConsumerTest extends ActiveMQTestBase /** * */ - protected void releaseConsumers() - { + protected void releaseConsumers() { callbackSemaphore.release(); } /** * @throws InterruptedException */ - protected void awaitBlocking() throws InterruptedException - { + protected void awaitBlocking() throws InterruptedException { assertTrue(this.inCall.await(5000)); } /** * @throws InterruptedException */ - protected void blockConsumers() throws InterruptedException - { + protected void blockConsumers() throws InterruptedException { this.callbackSemaphore.acquire(); } /** * This would recreate the scenario where a queue was duplicated + * * @throws Exception */ @Test - public void testHangDuplicateQueues() throws Exception - { + public void testHangDuplicateQueues() throws Exception { final Semaphore blocked = new Semaphore(1); final CountDownLatch latchDelete = new CountDownLatch(1); - class MyQueueWithBlocking extends QueueImpl - { + class MyQueueWithBlocking extends QueueImpl { /** * @param id @@ -236,27 +226,12 @@ public class HangConsumerTest extends ActiveMQTestBase final PostOffice postOffice, final StorageManager storageManager, final HierarchicalRepository addressSettingsRepository, - final Executor executor) - { - super(id, - address, - name, - filter, - pageSubscription, - user, - durable, - temporary, - autoCreated, - scheduledExecutor, - postOffice, - storageManager, - addressSettingsRepository, - executor); + final Executor executor) { + super(id, address, name, filter, pageSubscription, user, durable, temporary, autoCreated, scheduledExecutor, postOffice, storageManager, addressSettingsRepository, executor); } @Override - public synchronized int deleteMatchingReferences(final int flushLimit, final Filter filter) throws Exception - { + public synchronized int deleteMatchingReferences(final int flushLimit, final Filter filter) throws Exception { latchDelete.countDown(); blocked.acquire(); blocked.release(); @@ -264,18 +239,16 @@ public class HangConsumerTest extends ActiveMQTestBase } @Override - public void deliverScheduledMessages() - { + public void deliverScheduledMessages() { } } - class LocalFactory extends QueueFactoryImpl - { + class LocalFactory extends QueueFactoryImpl { + public LocalFactory(final ExecutorFactory executorFactory, final ScheduledExecutorService scheduledExecutor, final HierarchicalRepository addressSettingsRepository, - final StorageManager storageManager) - { + final StorageManager storageManager) { super(executorFactory, scheduledExecutor, addressSettingsRepository, storageManager); } @@ -288,35 +261,18 @@ public class HangConsumerTest extends ActiveMQTestBase final SimpleString user, final boolean durable, final boolean temporary, - final boolean autoCreated) - { - queue = new MyQueueWithBlocking(persistenceID, - address, - name, - filter, - user, - pageSubscription, - durable, - temporary, - autoCreated, - scheduledExecutor, - postOffice, - storageManager, - addressSettingsRepository, - executorFactory.getExecutor()); + final boolean autoCreated) { + queue = new MyQueueWithBlocking(persistenceID, address, name, filter, user, pageSubscription, durable, temporary, autoCreated, scheduledExecutor, postOffice, storageManager, addressSettingsRepository, executorFactory.getExecutor()); return queue; } } - LocalFactory queueFactory = new LocalFactory(server.getExecutorFactory(), - server.getScheduledPool(), - server.getAddressSettingsRepository(), - server.getStorageManager()); + LocalFactory queueFactory = new LocalFactory(server.getExecutorFactory(), server.getScheduledPool(), server.getAddressSettingsRepository(), server.getStorageManager()); queueFactory.setPostOffice(server.getPostOffice()); - ((ActiveMQServerImpl)server).replaceQueueFactory(queueFactory); + ((ActiveMQServerImpl) server).replaceQueueFactory(queueFactory); queue = server.createQueue(QUEUE, QUEUE, null, true, false); @@ -330,17 +286,13 @@ public class HangConsumerTest extends ActiveMQTestBase producer.send(session.createMessage(true)); session.commit(); - Thread tDelete = new Thread() - { + Thread tDelete = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { server.destroyQueue(QUEUE); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -350,12 +302,10 @@ public class HangConsumerTest extends ActiveMQTestBase Assert.assertTrue(latchDelete.await(10, TimeUnit.SECONDS)); - try - { + try { server.createQueue(QUEUE, QUEUE, null, true, false); } - catch (Exception expected) - { + catch (Exception expected) { } blocked.release(); @@ -377,11 +327,11 @@ public class HangConsumerTest extends ActiveMQTestBase /** * This would force a journal duplication on bindings even with the scenario that generated fixed, * the server shouldn't hold of from starting + * * @throws Exception */ @Test - public void testForceDuplicationOnBindings() throws Exception - { + public void testForceDuplicationOnBindings() throws Exception { queue = server.createQueue(QUEUE, QUEUE, null, true, false); ClientSessionFactory factory = locator.createSessionFactory(); @@ -395,7 +345,6 @@ public class HangConsumerTest extends ActiveMQTestBase long queueID = server.getStorageManager().generateID(); long txID = server.getStorageManager().generateID(); - // Forcing a situation where the server would unexpectedly create a duplicated queue. The server should still start normally LocalQueueBinding newBinding = new LocalQueueBinding(QUEUE, new QueueImpl(queueID, QUEUE, QUEUE, null, null, true, false, false, null, null, null, null, null), server.getNodeID()); server.getStorageManager().addQueueBinding(txID, newBinding); @@ -413,13 +362,11 @@ public class HangConsumerTest extends ActiveMQTestBase // An exception during delivery shouldn't make the message disappear @Test - public void testExceptionWhileDelivering() throws Exception - { + public void testExceptionWhileDelivering() throws Exception { queue = server.createQueue(QUEUE, QUEUE, null, true, false); HangInterceptor hangInt = new HangInterceptor(); - try - { + try { locator.addIncomingInterceptor(hangInt); ClientSessionFactory factory = locator.createSessionFactory(); @@ -455,8 +402,7 @@ public class HangConsumerTest extends ActiveMQTestBase session.commit(); } - finally - { + finally { hangInt.open(); } @@ -464,17 +410,14 @@ public class HangConsumerTest extends ActiveMQTestBase /** * This will simulate what would happen with topic creationg where a single record is supposed to be created on the journal + * * @throws Exception */ @Test - public void testDuplicateDestinationsOnTopic() throws Exception - { - try - { - for (int i = 0; i < 5; i++) - { - if (server.locateQueue(SimpleString.toSimpleString("jms.topic.tt")) == null) - { + public void testDuplicateDestinationsOnTopic() throws Exception { + try { + for (int i = 0; i < 5; i++) { + if (server.locateQueue(SimpleString.toSimpleString("jms.topic.tt")) == null) { server.createQueue(SimpleString.toSimpleString("jms.topic.tt"), SimpleString.toSimpleString("jms.topic.tt"), SimpleString.toSimpleString(ActiveMQServerImpl.GENERIC_IGNORED_FILTER), true, false); } @@ -482,14 +425,7 @@ public class HangConsumerTest extends ActiveMQTestBase SequentialFileFactory messagesFF = new NIOSequentialFileFactory(server.getConfiguration().getBindingsLocation(), null, 1); - JournalImpl messagesJournal = new JournalImpl(1024 * 1024, - 2, - 0, - 0, - messagesFF, - "activemq-bindings", - "bindings", - 1); + JournalImpl messagesJournal = new JournalImpl(1024 * 1024, 2, 0, 0, messagesFF, "activemq-bindings", "bindings", 1); messagesJournal.start(); @@ -498,11 +434,9 @@ public class HangConsumerTest extends ActiveMQTestBase messagesJournal.load(infos, null, null); int bindings = 0; - for (RecordInfo info : infos) - { + for (RecordInfo info : infos) { System.out.println("info: " + info); - if (info.getUserRecordType() == JournalRecordIds.QUEUE_BINDING_RECORD) - { + if (info.getUserRecordType() == JournalRecordIds.QUEUE_BINDING_RECORD) { bindings++; } } @@ -510,39 +444,32 @@ public class HangConsumerTest extends ActiveMQTestBase System.out.println("Bindings: " + bindings); messagesJournal.stop(); - if (i < 4) server.start(); + if (i < 4) + server.start(); } } - finally - { - try - { + finally { + try { server.stop(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } } - - ReusableLatch inCall = new ReusableLatch(1); Semaphore callbackSemaphore = new Semaphore(1); + class MyCallback implements SessionCallback { - class MyCallback implements SessionCallback - { @Override - public boolean hasCredits(ServerConsumer consumerID) - { + public boolean hasCredits(ServerConsumer consumerID) { return true; } final SessionCallback targetCallback; - MyCallback(SessionCallback parameter) - { + MyCallback(SessionCallback parameter) { this.targetCallback = parameter; } @@ -550,13 +477,11 @@ public class HangConsumerTest extends ActiveMQTestBase * @see SessionCallback#sendProducerCreditsMessage(int, SimpleString) */ @Override - public void sendProducerCreditsMessage(int credits, SimpleString address) - { + public void sendProducerCreditsMessage(int credits, SimpleString address) { targetCallback.sendProducerCreditsMessage(credits, address); } - public void sendProducerCreditsFailMessage(int credits, SimpleString address) - { + public void sendProducerCreditsFailMessage(int credits, SimpleString address) { targetCallback.sendProducerCreditsFailMessage(credits, address); } @@ -564,25 +489,20 @@ public class HangConsumerTest extends ActiveMQTestBase * @see SessionCallback#sendMessage(org.apache.activemq.artemis.core.server.ServerMessage, long, int) */ @Override - public int sendMessage(ServerMessage message, ServerConsumer consumer, int deliveryCount) - { + public int sendMessage(ServerMessage message, ServerConsumer consumer, int deliveryCount) { inCall.countDown(); - try - { + try { callbackSemaphore.acquire(); } - catch (InterruptedException e) - { + catch (InterruptedException e) { inCall.countUp(); return -1; } - try - { + try { return targetCallback.sendMessage(message, consumer, deliveryCount); } - finally - { + finally { callbackSemaphore.release(); inCall.countUp(); } @@ -592,8 +512,7 @@ public class HangConsumerTest extends ActiveMQTestBase * @see SessionCallback#sendLargeMessage(org.apache.activemq.artemis.core.server.ServerMessage, long, long, int) */ @Override - public int sendLargeMessage(ServerMessage message, ServerConsumer consumer, long bodySize, int deliveryCount) - { + public int sendLargeMessage(ServerMessage message, ServerConsumer consumer, long bodySize, int deliveryCount) { return targetCallback.sendLargeMessage(message, consumer, bodySize, deliveryCount); } @@ -601,8 +520,10 @@ public class HangConsumerTest extends ActiveMQTestBase * @see SessionCallback#sendLargeMessageContinuation(long, byte[], boolean, boolean) */ @Override - public int sendLargeMessageContinuation(ServerConsumer consumer, byte[] body, boolean continues, boolean requiresResponse) - { + public int sendLargeMessageContinuation(ServerConsumer consumer, + byte[] body, + boolean continues, + boolean requiresResponse) { return targetCallback.sendLargeMessageContinuation(consumer, body, continues, requiresResponse); } @@ -610,8 +531,7 @@ public class HangConsumerTest extends ActiveMQTestBase * @see SessionCallback#closed() */ @Override - public void closed() - { + public void closed() { targetCallback.closed(); } @@ -619,8 +539,7 @@ public class HangConsumerTest extends ActiveMQTestBase * @see SessionCallback#addReadyListener(ReadyListener) */ @Override - public void addReadyListener(ReadyListener listener) - { + public void addReadyListener(ReadyListener listener) { targetCallback.addReadyListener(listener); } @@ -628,99 +547,76 @@ public class HangConsumerTest extends ActiveMQTestBase * @see SessionCallback#removeReadyListener(ReadyListener) */ @Override - public void removeReadyListener(ReadyListener listener) - { + public void removeReadyListener(ReadyListener listener) { targetCallback.removeReadyListener(listener); } @Override - public void disconnect(ServerConsumer consumerId, String queueName) - { + public void disconnect(ServerConsumer consumerId, String queueName) { //To change body of implemented methods use File | Settings | File Templates. } - } - class MyActiveMQServer extends ActiveMQServerImpl - { - - + class MyActiveMQServer extends ActiveMQServerImpl { public MyActiveMQServer(Configuration configuration, MBeanServer mbeanServer, - ActiveMQSecurityManager securityManager) - { + ActiveMQSecurityManager securityManager) { super(configuration, mbeanServer, securityManager); } @Override - protected ServerSessionImpl internalCreateSession(String name, String username, String password, int minLargeMessageSize, RemotingConnection connection, boolean autoCommitSends, boolean autoCommitAcks, boolean preAcknowledge, boolean xa, String defaultAddress, SessionCallback callback, OperationContext context, ServerSessionFactory sessionFactory, boolean autoCreateQueue) throws Exception - { - return new ServerSessionImpl(name, - username, - password, - minLargeMessageSize, - autoCommitSends, - autoCommitAcks, - preAcknowledge, - getConfiguration().isPersistDeliveryCountBeforeDelivery(), - xa, - connection, - getStorageManager(), - getPostOffice(), - getResourceManager(), - getSecurityStore(), - getManagementService(), - this, - getConfiguration().getManagementAddress(), - defaultAddress == null ? null - : new SimpleString(defaultAddress), - new MyCallback(callback), - context, - null); + protected ServerSessionImpl internalCreateSession(String name, + String username, + String password, + int minLargeMessageSize, + RemotingConnection connection, + boolean autoCommitSends, + boolean autoCommitAcks, + boolean preAcknowledge, + boolean xa, + String defaultAddress, + SessionCallback callback, + OperationContext context, + ServerSessionFactory sessionFactory, + boolean autoCreateQueue) throws Exception { + return new ServerSessionImpl(name, username, password, minLargeMessageSize, autoCommitSends, autoCommitAcks, preAcknowledge, getConfiguration().isPersistDeliveryCountBeforeDelivery(), xa, connection, getStorageManager(), getPostOffice(), getResourceManager(), getSecurityStore(), getManagementService(), this, getConfiguration().getManagementAddress(), defaultAddress == null ? null : new SimpleString(defaultAddress), new MyCallback(callback), context, null); } } - class HangInterceptor implements Interceptor - { + class HangInterceptor implements Interceptor { + Semaphore semaphore = new Semaphore(1); ReusableLatch reusableLatch = new ReusableLatch(1); volatile ActiveMQException pendingException = null; - public void close() throws Exception - { + public void close() throws Exception { semaphore.acquire(); } - public void open() throws Exception - { + public void open() throws Exception { semaphore.release(); } @Override - public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException - { - if (packet instanceof SessionReceiveMessage) - { + public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { + if (packet instanceof SessionReceiveMessage) { System.out.println("Receiving message"); - try - { + try { reusableLatch.countDown(); semaphore.acquire(); semaphore.release(); reusableLatch.countUp(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } - if (pendingException != null) - { + if (pendingException != null) { ActiveMQException exToThrow = pendingException; pendingException = null; throw exToThrow; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/HeuristicXATest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/HeuristicXATest.java index 78b1547289..27baa74de1 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/HeuristicXATest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/HeuristicXATest.java @@ -39,8 +39,8 @@ import javax.management.MBeanServerFactory; import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; -public class HeuristicXATest extends ActiveMQTestBase -{ +public class HeuristicXATest extends ActiveMQTestBase { + // Constants ----------------------------------------------------- final SimpleString ADDRESS = new SimpleString("ADDRESS"); @@ -59,10 +59,8 @@ public class HeuristicXATest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testInvalidCall() throws Exception - { - Configuration configuration = createDefaultInVMConfig() - .setJMXManagementEnabled(true); + public void testInvalidCall() throws Exception { + Configuration configuration = createDefaultInVMConfig().setJMXManagementEnabled(true); ActiveMQServer server = createServer(false, configuration); server.setMBeanServer(mbeanServer); @@ -74,21 +72,17 @@ public class HeuristicXATest extends ActiveMQTestBase } @Test - public void testHeuristicCommit() throws Exception - { + public void testHeuristicCommit() throws Exception { internalTest(true); } @Test - public void testHeuristicRollback() throws Exception - { + public void testHeuristicRollback() throws Exception { internalTest(false); } - private void internalTest(final boolean isCommit) throws Exception - { - Configuration configuration = createDefaultInVMConfig() - .setJMXManagementEnabled(true); + private void internalTest(final boolean isCommit) throws Exception { + Configuration configuration = createDefaultInVMConfig().setJMXManagementEnabled(true); ActiveMQServer server = createServer(false, configuration); server.setMBeanServer(mbeanServer); @@ -128,30 +122,25 @@ public class HeuristicXATest extends ActiveMQTestBase Assert.assertEquals(0, jmxServer.listHeuristicCommittedTransactions().length); Assert.assertEquals(0, jmxServer.listHeuristicRolledBackTransactions().length); - if (isCommit) - { + if (isCommit) { jmxServer.commitPreparedTransaction(XidImpl.toBase64String(xid)); } - else - { + else { jmxServer.rollbackPreparedTransaction(XidImpl.toBase64String(xid)); } Assert.assertEquals(0, jmxServer.listPreparedTransactions().length); - if (isCommit) - { + if (isCommit) { Assert.assertEquals(1, jmxServer.listHeuristicCommittedTransactions().length); Assert.assertEquals(0, jmxServer.listHeuristicRolledBackTransactions().length); } - else - { + else { Assert.assertEquals(0, jmxServer.listHeuristicCommittedTransactions().length); Assert.assertEquals(1, jmxServer.listHeuristicRolledBackTransactions().length); } - if (isCommit) - { - Assert.assertEquals(1, getMessageCount(((Queue)server.getPostOffice().getBinding(ADDRESS).getBindable()))); + if (isCommit) { + Assert.assertEquals(1, getMessageCount(((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()))); session = sf.createSession(false, false, false); @@ -166,25 +155,21 @@ public class HeuristicXATest extends ActiveMQTestBase session.close(); } - Assert.assertEquals(0, getMessageCount(((Queue)server.getPostOffice().getBinding(ADDRESS).getBindable()))); + Assert.assertEquals(0, getMessageCount(((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()))); } @Test - public void testHeuristicCommitWithRestart() throws Exception - { + public void testHeuristicCommitWithRestart() throws Exception { doHeuristicCompletionWithRestart(true); } @Test - public void testHeuristicRollbackWithRestart() throws Exception - { + public void testHeuristicRollbackWithRestart() throws Exception { doHeuristicCompletionWithRestart(false); } - private void doHeuristicCompletionWithRestart(final boolean isCommit) throws Exception - { - Configuration configuration = createDefaultInVMConfig() - .setJMXManagementEnabled(true); + private void doHeuristicCompletionWithRestart(final boolean isCommit) throws Exception { + Configuration configuration = createDefaultInVMConfig().setJMXManagementEnabled(true); ActiveMQServer server = createServer(true, configuration); server.setMBeanServer(mbeanServer); @@ -220,21 +205,18 @@ public class HeuristicXATest extends ActiveMQTestBase Assert.assertEquals(1, preparedTransactions.length); System.out.println(preparedTransactions[0]); - if (isCommit) - { + if (isCommit) { jmxServer.commitPreparedTransaction(XidImpl.toBase64String(xid)); } - else - { + else { jmxServer.rollbackPreparedTransaction(XidImpl.toBase64String(xid)); } preparedTransactions = jmxServer.listPreparedTransactions(); Assert.assertEquals(0, preparedTransactions.length); - if (isCommit) - { - Assert.assertEquals(1, getMessageCount(((Queue)server.getPostOffice().getBinding(ADDRESS).getBindable()))); + if (isCommit) { + Assert.assertEquals(1, getMessageCount(((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()))); session = sf.createSession(false, false, false); @@ -249,21 +231,19 @@ public class HeuristicXATest extends ActiveMQTestBase session.close(); } - Assert.assertEquals(0, getMessageCount(((Queue)server.getPostOffice().getBinding(ADDRESS).getBindable()))); + Assert.assertEquals(0, getMessageCount(((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()))); server.stop(); server.start(); jmxServer = ManagementControlHelper.createActiveMQServerControl(mbeanServer); - if (isCommit) - { + if (isCommit) { String[] listHeuristicCommittedTransactions = jmxServer.listHeuristicCommittedTransactions(); Assert.assertEquals(1, listHeuristicCommittedTransactions.length); System.out.println(listHeuristicCommittedTransactions[0]); } - else - { + else { String[] listHeuristicRolledBackTransactions = jmxServer.listHeuristicRolledBackTransactions(); Assert.assertEquals(1, listHeuristicRolledBackTransactions.length); System.out.println(listHeuristicRolledBackTransactions[0]); @@ -271,21 +251,17 @@ public class HeuristicXATest extends ActiveMQTestBase } @Test - public void testRecoverHeuristicCommitWithRestart() throws Exception - { + public void testRecoverHeuristicCommitWithRestart() throws Exception { doRecoverHeuristicCompletedTxWithRestart(true); } @Test - public void testRecoverHeuristicRollbackWithRestart() throws Exception - { + public void testRecoverHeuristicRollbackWithRestart() throws Exception { doRecoverHeuristicCompletedTxWithRestart(false); } - private void doRecoverHeuristicCompletedTxWithRestart(final boolean heuristicCommit) throws Exception - { - Configuration configuration = createDefaultInVMConfig() - .setJMXManagementEnabled(true); + private void doRecoverHeuristicCompletedTxWithRestart(final boolean heuristicCommit) throws Exception { + Configuration configuration = createDefaultInVMConfig().setJMXManagementEnabled(true); ActiveMQServer server = createServer(true, configuration); server.setMBeanServer(mbeanServer); @@ -321,21 +297,18 @@ public class HeuristicXATest extends ActiveMQTestBase Assert.assertEquals(1, preparedTransactions.length); System.out.println(preparedTransactions[0]); - if (heuristicCommit) - { + if (heuristicCommit) { jmxServer.commitPreparedTransaction(XidImpl.toBase64String(xid)); } - else - { + else { jmxServer.rollbackPreparedTransaction(XidImpl.toBase64String(xid)); } preparedTransactions = jmxServer.listPreparedTransactions(); Assert.assertEquals(0, preparedTransactions.length); - if (heuristicCommit) - { - Assert.assertEquals(1, getMessageCount(((Queue)server.getPostOffice().getBinding(ADDRESS).getBindable()))); + if (heuristicCommit) { + Assert.assertEquals(1, getMessageCount(((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()))); session = sf.createSession(false, false, false); @@ -350,7 +323,7 @@ public class HeuristicXATest extends ActiveMQTestBase session.close(); } - Assert.assertEquals(0, getMessageCount(((Queue)server.getPostOffice().getBinding(ADDRESS).getBindable()))); + Assert.assertEquals(0, getMessageCount(((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()))); server.stop(); @@ -358,14 +331,12 @@ public class HeuristicXATest extends ActiveMQTestBase // we need to recreate the locator and session sf sf = createSessionFactory(locator); jmxServer = ManagementControlHelper.createActiveMQServerControl(mbeanServer); - if (heuristicCommit) - { + if (heuristicCommit) { String[] listHeuristicCommittedTransactions = jmxServer.listHeuristicCommittedTransactions(); Assert.assertEquals(1, listHeuristicCommittedTransactions.length); System.out.println(listHeuristicCommittedTransactions[0]); } - else - { + else { String[] listHeuristicRolledBackTransactions = jmxServer.listHeuristicRolledBackTransactions(); Assert.assertEquals(1, listHeuristicRolledBackTransactions.length); System.out.println(listHeuristicRolledBackTransactions[0]); @@ -381,21 +352,17 @@ public class HeuristicXATest extends ActiveMQTestBase } @Test - public void testForgetHeuristicCommitAndRestart() throws Exception - { + public void testForgetHeuristicCommitAndRestart() throws Exception { doForgetHeuristicCompletedTxAndRestart(true); } @Test - public void testForgetHeuristicRollbackAndRestart() throws Exception - { + public void testForgetHeuristicRollbackAndRestart() throws Exception { doForgetHeuristicCompletedTxAndRestart(false); } - private void doForgetHeuristicCompletedTxAndRestart(final boolean heuristicCommit) throws Exception - { - Configuration configuration = createDefaultInVMConfig() - .setJMXManagementEnabled(true); + private void doForgetHeuristicCompletedTxAndRestart(final boolean heuristicCommit) throws Exception { + Configuration configuration = createDefaultInVMConfig().setJMXManagementEnabled(true); ActiveMQServer server = createServer(true, configuration); server.setMBeanServer(mbeanServer); @@ -429,12 +396,10 @@ public class HeuristicXATest extends ActiveMQTestBase Assert.assertEquals(1, preparedTransactions.length); System.out.println(preparedTransactions[0]); - if (heuristicCommit) - { + if (heuristicCommit) { jmxServer.commitPreparedTransaction(XidImpl.toBase64String(xid)); } - else - { + else { jmxServer.rollbackPreparedTransaction(XidImpl.toBase64String(xid)); } @@ -445,12 +410,10 @@ public class HeuristicXATest extends ActiveMQTestBase session.close(); - if (heuristicCommit) - { + if (heuristicCommit) { Assert.assertEquals(0, jmxServer.listHeuristicCommittedTransactions().length); } - else - { + else { Assert.assertEquals(0, jmxServer.listHeuristicRolledBackTransactions().length); } @@ -463,12 +426,10 @@ public class HeuristicXATest extends ActiveMQTestBase Xid[] recoveredXids = session.recover(XAResource.TMSTARTRSCAN); Assert.assertEquals(0, recoveredXids.length); jmxServer = ManagementControlHelper.createActiveMQServerControl(mbeanServer); - if (heuristicCommit) - { + if (heuristicCommit) { Assert.assertEquals(0, jmxServer.listHeuristicCommittedTransactions().length); } - else - { + else { Assert.assertEquals(0, jmxServer.listHeuristicRolledBackTransactions().length); } @@ -481,8 +442,7 @@ public class HeuristicXATest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); mbeanServer = MBeanServerFactory.createMBeanServer(); locator = createInVMNonHALocator(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/InVMNonPersistentMessageBufferTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/InVMNonPersistentMessageBufferTest.java index 167ea2f180..52c2c05f41 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/InVMNonPersistentMessageBufferTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/InVMNonPersistentMessageBufferTest.java @@ -31,8 +31,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class InVMNonPersistentMessageBufferTest extends ActiveMQTestBase -{ +public class InVMNonPersistentMessageBufferTest extends ActiveMQTestBase { + public static final String address = "testaddress"; public static final String queueName = "testqueue"; @@ -55,8 +55,7 @@ public class InVMNonPersistentMessageBufferTest extends ActiveMQTestBase */ @Test - public void testSimpleSendReceive() throws Exception - { + public void testSimpleSendReceive() throws Exception { ClientMessage message = session.createMessage(false); final String body = RandomUtil.randomString(); @@ -71,8 +70,7 @@ public class InVMNonPersistentMessageBufferTest extends ActiveMQTestBase } @Test - public void testSimpleSendReceiveWithEmptyBody() throws Exception - { + public void testSimpleSendReceiveWithEmptyBody() throws Exception { ClientMessage message = session.createMessage(false); ClientMessage received = sendAndReceive(message); @@ -83,8 +81,7 @@ public class InVMNonPersistentMessageBufferTest extends ActiveMQTestBase } @Test - public void testSendSameMessageMultipleTimes() throws Exception - { + public void testSendSameMessageMultipleTimes() throws Exception { ClientMessage message = session.createMessage(false); final String body = RandomUtil.randomString(); @@ -93,8 +90,7 @@ public class InVMNonPersistentMessageBufferTest extends ActiveMQTestBase int bodySize = message.getBodySize(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage received = sendAndReceive(message); Assert.assertNotNull(received); @@ -108,14 +104,12 @@ public class InVMNonPersistentMessageBufferTest extends ActiveMQTestBase } @Test - public void testSendMessageResetSendAgainDifferentBody() throws Exception - { + public void testSendMessageResetSendAgainDifferentBody() throws Exception { ClientMessage message = session.createMessage(false); String body = RandomUtil.randomString(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { // Make the body a bit longer each time body += "XX"; @@ -135,17 +129,14 @@ public class InVMNonPersistentMessageBufferTest extends ActiveMQTestBase message.getBodyBuffer().clear(); - Assert.assertEquals(PacketImpl.PACKET_HEADERS_SIZE + DataConstants.SIZE_INT, message.getBodyBuffer() - .writerIndex()); + Assert.assertEquals(PacketImpl.PACKET_HEADERS_SIZE + DataConstants.SIZE_INT, message.getBodyBuffer().writerIndex()); - Assert.assertEquals(PacketImpl.PACKET_HEADERS_SIZE + DataConstants.SIZE_INT, message.getBodyBuffer() - .readerIndex()); + Assert.assertEquals(PacketImpl.PACKET_HEADERS_SIZE + DataConstants.SIZE_INT, message.getBodyBuffer().readerIndex()); } } @Test - public void testCannotReadPastEndOfMessageBody() throws Exception - { + public void testCannotReadPastEndOfMessageBody() throws Exception { ClientMessage message = session.createMessage(false); final String body = RandomUtil.randomString(); @@ -158,29 +149,25 @@ public class InVMNonPersistentMessageBufferTest extends ActiveMQTestBase Assert.assertEquals(body, received.getBodyBuffer().readString()); - try - { + try { received.getBodyBuffer().readByte(); Assert.fail("Should throw exception"); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { // OK } } @Test - public void testCanReReadBodyAfterReaderReset() throws Exception - { + public void testCanReReadBodyAfterReaderReset() throws Exception { ClientMessage message = session.createMessage(false); final String body = RandomUtil.randomString(); message.getBodyBuffer().writeString(body); - Assert.assertEquals(PacketImpl.PACKET_HEADERS_SIZE + DataConstants.SIZE_INT, message.getBodyBuffer() - .readerIndex()); + Assert.assertEquals(PacketImpl.PACKET_HEADERS_SIZE + DataConstants.SIZE_INT, message.getBodyBuffer().readerIndex()); String body2 = message.getBodyBuffer().readString(); @@ -188,8 +175,7 @@ public class InVMNonPersistentMessageBufferTest extends ActiveMQTestBase message.getBodyBuffer().resetReaderIndex(); - Assert.assertEquals(PacketImpl.PACKET_HEADERS_SIZE + DataConstants.SIZE_INT, message.getBodyBuffer() - .readerIndex()); + Assert.assertEquals(PacketImpl.PACKET_HEADERS_SIZE + DataConstants.SIZE_INT, message.getBodyBuffer().readerIndex()); String body3 = message.getBodyBuffer().readString(); @@ -203,8 +189,7 @@ public class InVMNonPersistentMessageBufferTest extends ActiveMQTestBase received.getBodyBuffer().resetReaderIndex(); - Assert.assertEquals(PacketImpl.PACKET_HEADERS_SIZE + DataConstants.SIZE_INT, received.getBodyBuffer() - .readerIndex()); + Assert.assertEquals(PacketImpl.PACKET_HEADERS_SIZE + DataConstants.SIZE_INT, received.getBodyBuffer().readerIndex()); String body4 = received.getBodyBuffer().readString(); @@ -212,32 +197,26 @@ public class InVMNonPersistentMessageBufferTest extends ActiveMQTestBase } - protected ServerLocator createFactory() throws Exception - { - if (isNetty()) - { + protected ServerLocator createFactory() throws Exception { + if (isNetty()) { return createNettyNonHALocator(); } - else - { + else { return createInVMNonHALocator(); } } - protected boolean isNetty() - { + protected boolean isNetty() { return false; } - protected boolean isPersistent() - { + protected boolean isPersistent() { return false; } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(isPersistent(), isNetty()); @@ -259,8 +238,7 @@ public class InVMNonPersistentMessageBufferTest extends ActiveMQTestBase session.start(); } - private ClientMessage sendAndReceive(final ClientMessage message) throws Exception - { + private ClientMessage sendAndReceive(final ClientMessage message) throws Exception { producer.send(message); ClientMessage received = consumer.receive(10000); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/InVMPersistentMessageBufferTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/InVMPersistentMessageBufferTest.java index d9f3df66ac..5fccbbb8fc 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/InVMPersistentMessageBufferTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/InVMPersistentMessageBufferTest.java @@ -16,17 +16,15 @@ */ package org.apache.activemq.artemis.tests.integration.client; -public class InVMPersistentMessageBufferTest extends InVMNonPersistentMessageBufferTest -{ +public class InVMPersistentMessageBufferTest extends InVMNonPersistentMessageBufferTest { + @Override - public boolean isPersistent() - { + public boolean isPersistent() { return true; } @Override - public boolean isNetty() - { + public boolean isNetty() { return false; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/IncompatibleVersionTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/IncompatibleVersionTest.java index 45f39b4deb..2323e5dca2 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/IncompatibleVersionTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/IncompatibleVersionTest.java @@ -49,8 +49,8 @@ import org.junit.Test; import static org.apache.activemq.artemis.tests.util.RandomUtil.randomString; -public class IncompatibleVersionTest extends ActiveMQTestBase -{ +public class IncompatibleVersionTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; // Constants ----------------------------------------------------- @@ -69,8 +69,7 @@ public class IncompatibleVersionTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(false, false); server.getConfiguration().setConnectionTTLOverride(500); @@ -79,13 +78,12 @@ public class IncompatibleVersionTest extends ActiveMQTestBase locator = createInVMNonHALocator(); ClientSessionFactory csf = createSessionFactory(locator); - connection = (CoreRemotingConnection)csf.getConnection(); + connection = (CoreRemotingConnection) csf.getConnection(); } @Override @After - public void tearDown() - { + public void tearDown() { connection.destroy(); closeServerLocator(locator); @@ -94,102 +92,74 @@ public class IncompatibleVersionTest extends ActiveMQTestBase } @Test - public void testCompatibleClientVersion() throws Exception - { + public void testCompatibleClientVersion() throws Exception { doTestClientVersionCompatibility(true); } @Test - public void testIncompatibleClientVersion() throws Exception - { + public void testIncompatibleClientVersion() throws Exception { doTestClientVersionCompatibility(false); } @Test - public void testCompatibleClientVersionWithRealConnection1() throws Exception - { + public void testCompatibleClientVersionWithRealConnection1() throws Exception { assertTrue(doTestClientVersionCompatibilityWithRealConnection("1-3,5,7-10", 1)); } @Test - public void testCompatibleClientVersionWithRealConnection2() throws Exception - { + public void testCompatibleClientVersionWithRealConnection2() throws Exception { assertTrue(doTestClientVersionCompatibilityWithRealConnection("1-3,5,7-10", 5)); } @Test - public void testCompatibleClientVersionWithRealConnection3() throws Exception - { + public void testCompatibleClientVersionWithRealConnection3() throws Exception { assertTrue(doTestClientVersionCompatibilityWithRealConnection("1-3,5,7-10", 10)); } @Test - public void testIncompatibleClientVersionWithRealConnection1() throws Exception - { + public void testIncompatibleClientVersionWithRealConnection1() throws Exception { assertFalse(doTestClientVersionCompatibilityWithRealConnection("1-3,5,7-10", 0)); } @Test - public void testIncompatibleClientVersionWithRealConnection2() throws Exception - { + public void testIncompatibleClientVersionWithRealConnection2() throws Exception { assertFalse(doTestClientVersionCompatibilityWithRealConnection("1-3,5,7-10", 4)); } @Test - public void testIncompatibleClientVersionWithRealConnection3() throws Exception - { + public void testIncompatibleClientVersionWithRealConnection3() throws Exception { assertFalse(doTestClientVersionCompatibilityWithRealConnection("1-3,5,7-10", 100)); } - private void doTestClientVersionCompatibility(boolean compatible) throws Exception - { + private void doTestClientVersionCompatibility(boolean compatible) throws Exception { Channel channel1 = connection.getChannel(1, -1); long sessionChannelID = connection.generateChannelID(); int version = VersionLoader.getVersion().getIncrementingVersion(); - if (!compatible) - { + if (!compatible) { version = -1; } - Packet request = new CreateSessionMessage(randomString(), - sessionChannelID, - version, - null, - null, - ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - false, - true, - true, - false, - ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, - null); + Packet request = new CreateSessionMessage(randomString(), sessionChannelID, version, null, null, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, false, true, true, false, ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, null); - if (compatible) - { + if (compatible) { CreateSessionResponseMessage packet = (CreateSessionResponseMessage) channel1.sendBlocking(request, PacketImpl.CREATESESSION_RESP); assertNotNull(packet); // 1 connection on the server assertEquals(1, server.getConnectionCount()); } - else - { - try - { + else { + try { channel1.sendBlocking(request, PacketImpl.CREATESESSION_RESP); fail(); } - catch (ActiveMQIncompatibleClientServerException icsv) - { + catch (ActiveMQIncompatibleClientServerException icsv) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } long start = System.currentTimeMillis(); - while (System.currentTimeMillis() < start + 3 * RemotingServiceImpl.CONNECTION_TTL_CHECK_INTERVAL) - { - if (server.getConnectionCount() == 0) - { + while (System.currentTimeMillis() < start + 3 * RemotingServiceImpl.CONNECTION_TTL_CHECK_INTERVAL) { + if (server.getConnectionCount() == 0) { break; } } @@ -198,8 +168,7 @@ public class IncompatibleVersionTest extends ActiveMQTestBase } } - private boolean doTestClientVersionCompatibilityWithRealConnection(String verList, int ver) throws Exception - { + private boolean doTestClientVersionCompatibilityWithRealConnection(String verList, int ver) throws Exception { String propFileName = "compatibility-test-activemq-version.properties"; String serverStartedString = "IncompatibleVersionTest---server---started"; @@ -212,33 +181,22 @@ public class IncompatibleVersionTest extends ActiveMQTestBase Process serverProcess = null; boolean result = false; - try - { - serverProcess = SpawnedVMSupport.spawnVM("org.apache.activemq.artemis.tests.integration.client.IncompatibleVersionTest", - new String[]{"-D" + VersionLoader.VERSION_PROP_FILE_KEY + "=" + propFileName}, - "server", - serverStartedString); + try { + serverProcess = SpawnedVMSupport.spawnVM("org.apache.activemq.artemis.tests.integration.client.IncompatibleVersionTest", new String[]{"-D" + VersionLoader.VERSION_PROP_FILE_KEY + "=" + propFileName}, "server", serverStartedString); Thread.sleep(2000); - Process client = SpawnedVMSupport.spawnVM("org.apache.activemq.artemis.tests.integration.client.IncompatibleVersionTest", - new String[]{"-D" + VersionLoader.VERSION_PROP_FILE_KEY + "=" + propFileName}, - "client"); + Process client = SpawnedVMSupport.spawnVM("org.apache.activemq.artemis.tests.integration.client.IncompatibleVersionTest", new String[]{"-D" + VersionLoader.VERSION_PROP_FILE_KEY + "=" + propFileName}, "client"); - if (client.waitFor() == 0) - { + if (client.waitFor() == 0) { result = true; } } - finally - { - if (serverProcess != null) - { - try - { + finally { + if (serverProcess != null) { + try { serverProcess.destroy(); } - catch (Throwable t) - { + catch (Throwable t) { /* ignore */ } } @@ -247,13 +205,10 @@ public class IncompatibleVersionTest extends ActiveMQTestBase return result; } - private static class ServerStarter - { - public void perform(String startedString) throws Exception - { - Configuration config = new ConfigurationImpl() - .setSecurityEnabled(false) - .addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY)); + private static class ServerStarter { + + public void perform(String startedString) throws Exception { + Configuration config = new ConfigurationImpl().setSecurityEnabled(false).addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY)); ActiveMQServer server = ActiveMQServers.newActiveMQServer(config, false); server.start(); @@ -261,48 +216,40 @@ public class IncompatibleVersionTest extends ActiveMQTestBase } } - private class ClientStarter - { - public void perform() throws Exception - { + private class ClientStarter { + + public void perform() throws Exception { ServerLocator locator = null; ClientSessionFactory sf = null; - try - { + try { locator = createNettyNonHALocator(); sf = locator.createSessionFactory(); ClientSession session = sf.createSession(false, true, true); log.info("### client: connected. server incrementingVersion = " + session.getVersion()); session.close(); } - finally - { + finally { closeSessionFactory(sf); closeServerLocator(locator); } } } - public static void main(String[] args) throws Exception - { + public static void main(String[] args) throws Exception { IncompatibleVersionTest incompatibleVersionTest = new IncompatibleVersionTest(); incompatibleVersionTest.execute(args); } - private void execute(String[] args) throws Exception - { - if (args[0].equals("server")) - { + private void execute(String[] args) throws Exception { + if (args[0].equals("server")) { ServerStarter ss = new ServerStarter(); ss.perform(args[1]); } - else if (args[0].equals("client")) - { + else if (args[0].equals("client")) { ClientStarter cs = new ClientStarter(); cs.perform(); } - else - { + else { throw new Exception("args[0] must be \"server\" or \"client\""); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/InterruptedLargeMessageTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/InterruptedLargeMessageTest.java index c673c258d9..1b80ec65ea 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/InterruptedLargeMessageTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/InterruptedLargeMessageTest.java @@ -61,8 +61,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class InterruptedLargeMessageTest extends LargeMessageTestBase -{ +public class InterruptedLargeMessageTest extends LargeMessageTestBase { // Constants ----------------------------------------------------- static final int RECEIVE_WAIT_TIME = 60000; @@ -75,35 +74,29 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); LargeMessageTestInterceptorIgnoreLastPacket.clearInterrupt(); locator = createFactory(isNetty()); } - protected boolean isNetty() - { + protected boolean isNetty() { return false; } @Test - public void testInterruptLargeMessageSend() throws Exception - { + public void testInterruptLargeMessageSend() throws Exception { ClientSession session = null; LargeMessageTestInterceptorIgnoreLastPacket.clearInterrupt(); ActiveMQServer server = createServer(true, isNetty()); - server.getConfiguration() - .getIncomingInterceptorClassNames() - .add(LargeMessageTestInterceptorIgnoreLastPacket.class.getName()); + server.getConfiguration().getIncomingInterceptorClassNames().add(LargeMessageTestInterceptorIgnoreLastPacket.class.getName()); server.start(); - locator.setBlockOnNonDurableSend(false) - .setBlockOnDurableSend(false); + locator.setBlockOnNonDurableSend(false).setBlockOnDurableSend(false); ClientSessionFactory sf = createSessionFactory(locator); @@ -121,8 +114,7 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase Thread.sleep(500); - for (ServerSession srvSession : server.getSessions()) - { + for (ServerSession srvSession : server.getSessions()) { ((ServerSessionImpl) srvSession).clearLargeMessage(); } @@ -138,17 +130,14 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase } @Test - public void testCloseConsumerDuringTransmission() throws Exception - { + public void testCloseConsumerDuringTransmission() throws Exception { ActiveMQServer server = createServer(true, isNetty()); LargeMessageTestInterceptorIgnoreLastPacket.disableInterrupt(); server.start(); - locator.setBlockOnNonDurableSend(false) - .setBlockOnDurableSend(false) - .addIncomingInterceptor(new LargeMessageTestInterceptorIgnoreLastPacket()); + locator.setBlockOnNonDurableSend(false).setBlockOnDurableSend(false).addIncomingInterceptor(new LargeMessageTestInterceptorIgnoreLastPacket()); ClientSessionFactory sf = createSessionFactory(locator); @@ -172,17 +161,13 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase session.start(); - Thread t = new Thread() - { + Thread t = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { System.out.println("Receiving message"); ClientMessage msg = cons.receive(5000); - if (msg == null) - { + if (msg == null) { System.err.println("Message not received"); unexpectedErrors.incrementAndGet(); return; @@ -190,8 +175,7 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase msg.checkCompletion(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { e.printStackTrace(); expectedErrors.incrementAndGet(); } @@ -215,9 +199,7 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase } @Test - public void testSendNonPersistentQueue() throws Exception - { - + public void testSendNonPersistentQueue() throws Exception { ClientSession session = null; @@ -226,8 +208,7 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase server.start(); - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true); + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true); ClientSessionFactory sf = createSessionFactory(locator); @@ -237,8 +218,7 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase ClientProducer producer = session.createProducer(ADDRESS); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { Message clientFile = createLargeClientMessageStreaming(session, LARGE_MESSAGE_SIZE, true); producer.send(clientFile); @@ -253,14 +233,11 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase session.start(); - for (int h = 0; h < 5; h++) - { - for (int i = 0; i < 10; i++) - { + for (int h = 0; h < 5; h++) { + for (int i = 0; i < 10; i++) { ClientMessage clientMessage = cons.receive(5000); Assert.assertNotNull(clientMessage); - for (int countByte = 0; countByte < LARGE_MESSAGE_SIZE; countByte++) - { + for (int countByte = 0; countByte < LARGE_MESSAGE_SIZE; countByte++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(countByte), clientMessage.getBodyBuffer().readByte()); } clientMessage.acknowledge(); @@ -277,15 +254,12 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase } @Test - public void testSendPaging() throws Exception - { - + public void testSendPaging() throws Exception { ClientSession session = null; LargeMessageTestInterceptorIgnoreLastPacket.disableInterrupt(); - ActiveMQServer server = - createServer(true, createDefaultConfig(isNetty()), 10000, 20000, new HashMap()); + ActiveMQServer server = createServer(true, createDefaultConfig(isNetty()), 10000, 20000, new HashMap()); // server.getConfiguration() // .getIncomingInterceptorClassNames() @@ -293,8 +267,7 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase server.start(); - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true); + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true); ClientSessionFactory sf = createSessionFactory(locator); @@ -306,8 +279,7 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase ClientProducer producer = session.createProducer(ADDRESS); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { Message clientFile = createLargeClientMessageStreaming(session, LARGE_MESSAGE_SIZE, true); producer.send(clientFile); @@ -316,8 +288,7 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase validateNoFilesOnLargeDir(server.getConfiguration().getLargeMessagesDirectory(), 10); - for (int h = 0; h < 5; h++) - { + for (int h = 0; h < 5; h++) { session.close(); sf.close(); @@ -334,22 +305,18 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase session.start(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage clientMessage = cons.receive(5000); Assert.assertNotNull(clientMessage); - for (int countByte = 0; countByte < LARGE_MESSAGE_SIZE; countByte++) - { + for (int countByte = 0; countByte < LARGE_MESSAGE_SIZE; countByte++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(countByte), clientMessage.getBodyBuffer().readByte()); } clientMessage.acknowledge(); } - if (h == 4) - { + if (h == 4) { session.commit(); } - else - { + else { session.rollback(); } @@ -365,23 +332,18 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase } @Test - public void testSendPreparedXA() throws Exception - { + public void testSendPreparedXA() throws Exception { ClientSession session = null; LargeMessageTestInterceptorIgnoreLastPacket.disableInterrupt(); - ActiveMQServer server = - createServer(true, createDefaultConfig(isNetty()), 10000, 20000, new HashMap()); + ActiveMQServer server = createServer(true, createDefaultConfig(isNetty()), 10000, 20000, new HashMap()); - server.getConfiguration() - .getIncomingInterceptorClassNames() - .add(LargeMessageTestInterceptorIgnoreLastPacket.class.getName()); + server.getConfiguration().getIncomingInterceptorClassNames().add(LargeMessageTestInterceptorIgnoreLastPacket.class.getName()); server.start(); - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true); + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true); ClientSessionFactory sf = createSessionFactory(locator); @@ -396,8 +358,7 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase session.start(xid1, XAResource.TMNOFLAGS); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { Message clientFile = createLargeClientMessageStreaming(session, LARGE_MESSAGE_SIZE, true); clientFile.putIntProperty("txid", 1); producer.send(clientFile); @@ -408,8 +369,7 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase session.start(xid2, XAResource.TMNOFLAGS); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { Message clientFile = createLargeClientMessageStreaming(session, LARGE_MESSAGE_SIZE, true); clientFile.putIntProperty("txid", 2); clientFile.putIntProperty("i", i); @@ -425,14 +385,12 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase server.stop(false); server.start(); - for (int start = 0; start < 2; start++) - { + for (int start = 0; start < 2; start++) { System.out.println("Start " + start); sf = createSessionFactory(locator); - if (start == 0) - { + if (start == 0) { session = sf.createSession(true, false, false); session.commit(xid1, false); session.close(); @@ -441,8 +399,7 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase session = sf.createSession(false, false, false); ClientConsumer cons1 = session.createConsumer(ADDRESS); session.start(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { log.info("I = " + i); ClientMessage msg = cons1.receive(5000); Assert.assertNotNull(msg); @@ -450,12 +407,10 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase msg.acknowledge(); } - if (start == 1) - { + if (start == 1) { session.commit(); } - else - { + else { session.rollback(); } @@ -486,11 +441,9 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase } @Test - public void testRestartBeforeDelete() throws Exception - { + public void testRestartBeforeDelete() throws Exception { - class NoPostACKQueue extends QueueImpl - { + class NoPostACKQueue extends QueueImpl { public NoPostACKQueue(long id, SimpleString address, @@ -505,38 +458,21 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase PostOffice postOffice, StorageManager storageManager, HierarchicalRepository addressSettingsRepository, - Executor executor) - { - super(id, - address, - name, - filter, - pageSubscription, - user, - durable, - temporary, - autoCreated, - scheduledExecutor, - postOffice, - storageManager, - addressSettingsRepository, - executor); + Executor executor) { + super(id, address, name, filter, pageSubscription, user, durable, temporary, autoCreated, scheduledExecutor, postOffice, storageManager, addressSettingsRepository, executor); } @Override - public void postAcknowledge(final MessageReference ref) - { + public void postAcknowledge(final MessageReference ref) { System.out.println("Ignoring postACK on message " + ref); } @Override - public void deliverScheduledMessages() - { + public void deliverScheduledMessages() { } } - class NoPostACKQueueFactory implements QueueFactory - { + class NoPostACKQueueFactory implements QueueFactory { final StorageManager storageManager; @@ -552,8 +488,7 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase PostOffice postOffice, ScheduledExecutorService scheduledExecutor, HierarchicalRepository addressSettingsRepository, - final ExecutorFactory execFactory) - { + final ExecutorFactory execFactory) { this.storageManager = storageManager; this.postOffice = postOffice; this.scheduledExecutor = scheduledExecutor; @@ -569,35 +504,19 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase SimpleString user, boolean durable, boolean temporary, - boolean autoCreated) - { + boolean autoCreated) { - return new NoPostACKQueue(persistenceID, - address, - name, - filter, - user, - pageSubscription, - durable, - temporary, - autoCreated, - scheduledExecutor, - postOffice, - storageManager, - addressSettingsRepository, - execFactory.getExecutor()); + return new NoPostACKQueue(persistenceID, address, name, filter, user, pageSubscription, durable, temporary, autoCreated, scheduledExecutor, postOffice, storageManager, addressSettingsRepository, execFactory.getExecutor()); } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.server.QueueFactory#setPostOffice(org.apache.activemq.artemis.core.postoffice.PostOffice) */ - public void setPostOffice(PostOffice postOffice) - { + public void setPostOffice(PostOffice postOffice) { } } - ClientSession session = null; LargeMessageTestInterceptorIgnoreLastPacket.disableInterrupt(); @@ -607,14 +526,9 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase QueueFactory original = server.getQueueFactory(); - ((ActiveMQServerImpl) server).replaceQueueFactory(new NoPostACKQueueFactory(server.getStorageManager(), - server.getPostOffice(), - server.getScheduledPool(), - server.getAddressSettingsRepository(), - server.getExecutorFactory())); + ((ActiveMQServerImpl) server).replaceQueueFactory(new NoPostACKQueueFactory(server.getStorageManager(), server.getPostOffice(), server.getScheduledPool(), server.getAddressSettingsRepository(), server.getExecutorFactory())); - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true); + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true); ClientSessionFactory sf = createSessionFactory(locator); @@ -624,8 +538,7 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase ClientProducer producer = session.createProducer(ADDRESS); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { Message clientFile = createLargeClientMessageStreaming(session, LARGE_MESSAGE_SIZE, true); producer.send(clientFile); @@ -640,15 +553,12 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase session.start(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage msg = cons.receive(5000); Assert.assertNotNull(msg); - msg.saveToOutputStream(new java.io.OutputStream() - { + msg.saveToOutputStream(new java.io.OutputStream() { @Override - public void write(int b) throws IOException - { + public void write(int b) throws IOException { } }); msg.acknowledge(); @@ -665,8 +575,7 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase } @Test - public void testConsumeAfterRestart() throws Exception - { + public void testConsumeAfterRestart() throws Exception { ClientSession session = null; LargeMessageTestInterceptorIgnoreLastPacket.clearInterrupt(); @@ -676,8 +585,7 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase QueueFactory original = server.getQueueFactory(); - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true); + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true); ClientSessionFactory sf = createSessionFactory(locator); @@ -687,8 +595,7 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase ClientProducer producer = session.createProducer(ADDRESS); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { Message clientFile = createLargeClientMessageStreaming(session, LARGE_MESSAGE_SIZE, true); producer.send(clientFile); @@ -709,15 +616,12 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase session.start(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage msg = cons.receive(5000); Assert.assertNotNull(msg); - msg.saveToOutputStream(new java.io.OutputStream() - { + msg.saveToOutputStream(new java.io.OutputStream() { @Override - public void write(int b) throws IOException - { + public void write(int b) throws IOException { } }); msg.acknowledge(); @@ -733,22 +637,18 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase validateNoFilesOnLargeDir(); } - public static class LargeMessageTestInterceptorIgnoreLastPacket implements Interceptor - { + public static class LargeMessageTestInterceptorIgnoreLastPacket implements Interceptor { - public static void clearInterrupt() - { + public static void clearInterrupt() { intMessages = true; latch = new CountDownLatch(1); } - public static void disableInterrupt() - { + public static void disableInterrupt() { intMessages = false; } - public static void awaitInterrupt() throws Exception - { + public static void awaitInterrupt() throws Exception { latch.await(); } @@ -757,13 +657,10 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase private static CountDownLatch latch = new CountDownLatch(1); @Override - public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException - { - if (packet instanceof SessionContinuationMessage) - { + public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException { + if (packet instanceof SessionContinuationMessage) { SessionContinuationMessage msg = (SessionContinuationMessage) packet; - if (!msg.isContinues() && intMessages) - { + if (!msg.isContinues() && intMessages) { System.out.println("Ignored a message"); latch.countDown(); return false; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/JMSMessageCounterTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/JMSMessageCounterTest.java index 9f80230360..c1cf4ec773 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/JMSMessageCounterTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/JMSMessageCounterTest.java @@ -28,18 +28,15 @@ import org.apache.activemq.artemis.api.jms.management.JMSQueueControl; import org.apache.activemq.artemis.tests.util.JMSTestBase; import org.junit.Test; -public class JMSMessageCounterTest extends JMSTestBase -{ +public class JMSMessageCounterTest extends JMSTestBase { @Override - protected boolean usePersistence() - { + protected boolean usePersistence() { return true; } @Test - public void testMessageCounter() throws Exception - { + public void testMessageCounter() throws Exception { Connection conn = cf.createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -50,8 +47,7 @@ public class JMSMessageCounterTest extends JMSTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage mess = sess.createTextMessage("msg" + i); producer.send(mess); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/JMSPagingFileDeleteTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/JMSPagingFileDeleteTest.java index af709ef0e6..11b557cc89 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/JMSPagingFileDeleteTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/JMSPagingFileDeleteTest.java @@ -35,8 +35,8 @@ import javax.jms.Topic; /** * This will perform cleanup tests on paging while using JMS topics */ -public class JMSPagingFileDeleteTest extends JMSTestBase -{ +public class JMSPagingFileDeleteTest extends JMSTestBase { + static IntegrationTestLogger log = IntegrationTestLogger.LOGGER; Topic topic1; @@ -62,23 +62,19 @@ public class JMSPagingFileDeleteTest extends JMSTestBase private static final int MESSAGE_NUM = 50; @Override - protected boolean usePersistence() - { + protected boolean usePersistence() { return true; } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); topic1 = createTopic("topic1"); // Paging Setting - AddressSettings setting = new AddressSettings() - .setPageSizeBytes(JMSPagingFileDeleteTest.PAGE_SIZE) - .setMaxSizeBytes(JMSPagingFileDeleteTest.PAGE_MAX); + AddressSettings setting = new AddressSettings().setPageSizeBytes(JMSPagingFileDeleteTest.PAGE_SIZE).setMaxSizeBytes(JMSPagingFileDeleteTest.PAGE_MAX); server.getAddressSettingsRepository().addMatch("#", setting); } @@ -88,14 +84,11 @@ public class JMSPagingFileDeleteTest extends JMSTestBase * @throws Exception */ @Test - public void testTopicsWithNonDurableSubscription() throws Exception - { + public void testTopicsWithNonDurableSubscription() throws Exception { connection = null; - try - { - for (int repeat = 0; repeat < 2; repeat++) - { + try { + for (int repeat = 0; repeat < 2; repeat++) { connection = cf.createConnection(); connection.setClientID("cid"); @@ -109,8 +102,7 @@ public class JMSPagingFileDeleteTest extends JMSTestBase System.out.println("---------- Send messages. ----------"); BytesMessage bytesMessage = session.createBytesMessage(); bytesMessage.writeBytes(new byte[JMSPagingFileDeleteTest.MESSAGE_SIZE]); - for (int i = 0; i < JMSPagingFileDeleteTest.MESSAGE_NUM; i++) - { + for (int i = 0; i < JMSPagingFileDeleteTest.MESSAGE_NUM; i++) { producer.send(bytesMessage); } System.out.println("Sent " + JMSPagingFileDeleteTest.MESSAGE_NUM + " messages."); @@ -129,10 +121,8 @@ public class JMSPagingFileDeleteTest extends JMSTestBase //subscriber1.close(); // << you can't call this on this test //session.close(); // << can't call this on this test - long timeout = System.currentTimeMillis() + 5000; - while (timeout > System.currentTimeMillis() && pagingStore.isPaging()) - { + while (timeout > System.currentTimeMillis() && pagingStore.isPaging()) { Thread.sleep(100); } printPageStoreInfo(pagingStore); @@ -140,23 +130,18 @@ public class JMSPagingFileDeleteTest extends JMSTestBase } } - finally - { - if (connection != null) - { + finally { + if (connection != null) { connection.close(); } } } - @Test - public void testTopics() throws Exception - { + public void testTopics() throws Exception { connection = null; - try - { + try { connection = cf.createConnection(); connection.setClientID("cid"); @@ -170,8 +155,7 @@ public class JMSPagingFileDeleteTest extends JMSTestBase System.out.println("---------- Send messages. ----------"); BytesMessage bytesMessage = session.createBytesMessage(); bytesMessage.writeBytes(new byte[JMSPagingFileDeleteTest.MESSAGE_SIZE]); - for (int i = 0; i < JMSPagingFileDeleteTest.MESSAGE_NUM; i++) - { + for (int i = 0; i < JMSPagingFileDeleteTest.MESSAGE_NUM; i++) { producer.send(bytesMessage); } System.out.println("Sent " + JMSPagingFileDeleteTest.MESSAGE_NUM + " messages."); @@ -188,8 +172,7 @@ public class JMSPagingFileDeleteTest extends JMSTestBase // -----------------(Step3) Subscribe to all the messages from the topic.-------------- System.out.println("---------- Receive all messages. ----------"); - for (int i = 0; i < JMSPagingFileDeleteTest.MESSAGE_NUM; i++) - { + for (int i = 0; i < JMSPagingFileDeleteTest.MESSAGE_NUM; i++) { Message message1 = subscriber1.receive(JMSPagingFileDeleteTest.RECEIVE_TIMEOUT); assertNotNull(message1); Message message2 = subscriber2.receive(JMSPagingFileDeleteTest.RECEIVE_TIMEOUT); @@ -198,8 +181,7 @@ public class JMSPagingFileDeleteTest extends JMSTestBase pagingStore = server.getPagingManager().getPageStore(new SimpleString("jms.topic.topic1")); long timeout = System.currentTimeMillis() + 5000; - while (timeout > System.currentTimeMillis() && pagingStore.isPaging()) - { + while (timeout > System.currentTimeMillis() && pagingStore.isPaging()) { Thread.sleep(100); } assertFalse(pagingStore.isPaging()); @@ -221,24 +203,20 @@ public class JMSPagingFileDeleteTest extends JMSTestBase timeout = System.currentTimeMillis() + 10000; - while (timeout > System.currentTimeMillis() && pagingStore.getNumberOfPages() != 1) - { + while (timeout > System.currentTimeMillis() && pagingStore.getNumberOfPages() != 1) { Thread.sleep(100); } assertEquals(1, pagingStore.getNumberOfPages()); //I expected number of the page is 1, but It was not. } - finally - { - if (connection != null) - { + finally { + if (connection != null) { connection.close(); } } } - private void stopAndStartServer() throws Exception - { + private void stopAndStartServer() throws Exception { System.out.println("---------- Restart server. ----------"); connection.close(); @@ -252,8 +230,7 @@ public class JMSPagingFileDeleteTest extends JMSTestBase reconnect(); } - private void reconnect() throws Exception - { + private void reconnect() throws Exception { connection = cf.createConnection(); connection.setClientID("cid"); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -262,8 +239,7 @@ public class JMSPagingFileDeleteTest extends JMSTestBase connection.start(); } - private void printPageStoreInfo(PagingStore pagingStore) throws Exception - { + private void printPageStoreInfo(PagingStore pagingStore) throws Exception { System.out.println("---------- Paging Store Info ----------"); System.out.println(" CurrentPage = " + pagingStore.getCurrentPage()); System.out.println(" FirstPage = " + pagingStore.getFirstPage()); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/JmsNettyNioStressTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/JmsNettyNioStressTest.java index 3d03e32dfb..dbd4e2444c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/JmsNettyNioStressTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/JmsNettyNioStressTest.java @@ -62,8 +62,7 @@ import java.util.concurrent.atomic.AtomicInteger; * counting strategy is used to verify that the count has reached the expected * value. */ -public class JmsNettyNioStressTest extends ActiveMQTestBase -{ +public class JmsNettyNioStressTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -77,13 +76,11 @@ public class JmsNettyNioStressTest extends ActiveMQTestBase // Remove this method to re-enable those tests @Test - public void testStressSendNetty() throws Exception - { + public void testStressSendNetty() throws Exception { doTestStressSend(true); } - public void doTestStressSend(final boolean netty) throws Exception - { + public void doTestStressSend(final boolean netty) throws Exception { // first set up the server Map params = new HashMap(); params.put(TransportConstants.PORT_PROP_NAME, 61616); @@ -93,10 +90,7 @@ public class JmsNettyNioStressTest extends ActiveMQTestBase params.put(TransportConstants.NIO_REMOTING_THREADS_PROPNAME, 1); params.put(TransportConstants.BATCH_DELAY, 50); TransportConfiguration transportConfig = new TransportConfiguration(ActiveMQTestBase.NETTY_ACCEPTOR_FACTORY, params); - Configuration config = createBasicConfig() - .setJMXManagementEnabled(false) - .clearAcceptorConfigurations() - .addAcceptorConfiguration(transportConfig); + Configuration config = createBasicConfig().setJMXManagementEnabled(false).clearAcceptorConfigurations().addAcceptorConfiguration(transportConfig); ActiveMQServer server = createServer(true, config); server.getConfiguration().setThreadPoolMaxSize(2); server.start(); @@ -108,8 +102,7 @@ public class JmsNettyNioStressTest extends ActiveMQTestBase connectionParams.put(TransportConstants.USE_NIO_PROP_NAME, true); connectionParams.put(TransportConstants.BATCH_DELAY, 50); connectionParams.put(TransportConstants.NIO_REMOTING_THREADS_PROPNAME, 6); - final TransportConfiguration transpConf = new TransportConfiguration(NettyConnectorFactory.class.getName(), - connectionParams); + final TransportConfiguration transpConf = new TransportConfiguration(NettyConnectorFactory.class.getName(), connectionParams); final ServerLocator locator = createNonHALocator(netty); // each thread will do this number of transactions @@ -154,23 +147,18 @@ public class JmsNettyNioStressTest extends ActiveMQTestBase connectionConsumer.start(); // these threads produce messages on the the first queue - for (int i = 0; i < numProducers; i++) - { - new Thread() - { + for (int i = 0; i < numProducers; i++) { + new Thread() { @Override - public void run() - { + public void run() { Session session = null; - try - { + try { session = connectionProducer.createSession(true, Session.SESSION_TRANSACTED); MessageProducer messageProducer = session.createProducer(ActiveMQDestination.createQueue("queue")); messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { BytesMessage message = session.createBytesMessage(); message.writeBytes(new byte[3000]); message.setStringProperty("Service", "LoadShedService"); @@ -182,20 +170,15 @@ public class JmsNettyNioStressTest extends ActiveMQTestBase totalCount.incrementAndGet(); } } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } - finally - { - if (session != null) - { - try - { + finally { + if (session != null) { + try { session.close(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -205,25 +188,19 @@ public class JmsNettyNioStressTest extends ActiveMQTestBase } // these threads just consume from the one and produce on a second queue - for (int i = 0; i < numConsumerProducers; i++) - { - new Thread() - { + for (int i = 0; i < numConsumerProducers; i++) { + new Thread() { @Override - public void run() - { + public void run() { Session session = null; - try - { + try { session = connectionConsumerProducer.createSession(true, Session.SESSION_TRANSACTED); MessageConsumer consumer = session.createConsumer(ActiveMQDestination.createQueue("queue")); MessageProducer messageProducer = session.createProducer(ActiveMQDestination.createQueue("queue2")); messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { BytesMessage message = (BytesMessage) consumer.receive(5000); - if (message == null) - { + if (message == null) { return; } message = session.createBytesMessage(); @@ -236,20 +213,15 @@ public class JmsNettyNioStressTest extends ActiveMQTestBase totalCount.incrementAndGet(); } } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } - finally - { - if (session != null) - { - try - { + finally { + if (session != null) { + try { session.close(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -259,23 +231,17 @@ public class JmsNettyNioStressTest extends ActiveMQTestBase } // these threads consume from the second queue - for (int i = 0; i < numConsumers; i++) - { - new Thread() - { + for (int i = 0; i < numConsumers; i++) { + new Thread() { @Override - public void run() - { + public void run() { Session session = null; - try - { + try { session = connectionConsumer.createSession(true, Session.SESSION_TRANSACTED); MessageConsumer consumer = session.createConsumer(ActiveMQDestination.createQueue("queue2")); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { BytesMessage message = (BytesMessage) consumer.receive(5000); - if (message == null) - { + if (message == null) { return; } session.commit(); @@ -283,20 +249,15 @@ public class JmsNettyNioStressTest extends ActiveMQTestBase totalCount.incrementAndGet(); } } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } - finally - { - if (session != null) - { - try - { + finally { + if (session != null) { + try { session.close(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -309,8 +270,7 @@ public class JmsNettyNioStressTest extends ActiveMQTestBase // which would indicate that the system didn't stall int timeoutCounter = 0; int maxSecondsToWait = 60; - while (timeoutCounter < maxSecondsToWait && totalCount.get() < totalExpectedCount) - { + while (timeoutCounter < maxSecondsToWait && totalCount.get() < totalExpectedCount) { timeoutCounter++; Thread.sleep(1000); System.out.println("Not done yet.. " + (maxSecondsToWait - timeoutCounter) + "; " + totalCount.get()); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/JournalCrashTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/JournalCrashTest.java index cbc2904dc0..f9e31d0bf1 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/JournalCrashTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/JournalCrashTest.java @@ -39,8 +39,8 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Assert; import org.junit.Test; -public class JournalCrashTest extends ActiveMQTestBase -{ +public class JournalCrashTest extends ActiveMQTestBase { + private static final int FIRST_RUN = 4; private static final int SECOND_RUN = 8; @@ -57,13 +57,8 @@ public class JournalCrashTest extends ActiveMQTestBase private ServerLocator locator; - protected void startServer() throws Exception - { - Configuration config = createDefaultInVMConfig() - .setJournalFileSize(ActiveMQDefaultConfiguration.getDefaultJournalFileSize()) - .setJournalCompactMinFiles(ActiveMQDefaultConfiguration.getDefaultJournalCompactMinFiles()) - .setJournalCompactPercentage(ActiveMQDefaultConfiguration.getDefaultJournalCompactPercentage()) - .setJournalMinFiles(2); + protected void startServer() throws Exception { + Configuration config = createDefaultInVMConfig().setJournalFileSize(ActiveMQDefaultConfiguration.getDefaultJournalFileSize()).setJournalCompactMinFiles(ActiveMQDefaultConfiguration.getDefaultJournalCompactMinFiles()).setJournalCompactPercentage(ActiveMQDefaultConfiguration.getDefaultJournalCompactPercentage()).setJournalMinFiles(2); server = super.createServer(true, config); @@ -72,8 +67,7 @@ public class JournalCrashTest extends ActiveMQTestBase factory = createSessionFactory(locator); } - protected void stopServer() throws Exception - { + protected void stopServer() throws Exception { locator.close(); closeSessionFactory(factory); @@ -87,12 +81,9 @@ public class JournalCrashTest extends ActiveMQTestBase /** * The test needs another VM, that will be "killed" right after commit. This main will do this job. */ - public static void main(final String[] arg) - { - try - { - if (arg.length != 3) - { + public static void main(final String[] arg) { + try { + if (arg.length != 3) { throw new IllegalArgumentException(Arrays.toString(arg)); } String testDir = arg[0]; @@ -110,33 +101,27 @@ public class JournalCrashTest extends ActiveMQTestBase Runtime.getRuntime().halt(100); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(System.out); System.exit(1); } } - public void sendMessages(final int start, final int end) throws Exception - { + public void sendMessages(final int start, final int end) throws Exception { ClientSession session = null; - try - { + try { session = factory.createSession(false, false); - try - { + try { session.createQueue(QUEUE, QUEUE, true); } - catch (Exception ignored) - { + catch (Exception ignored) { } ClientProducer prod = session.createProducer(QUEUE); - for (int i = start; i < end; i++) - { + for (int i = start; i < end; i++) { ClientMessage msg = session.createMessage(true); msg.putIntProperty(new SimpleString("key"), i); msg.getBodyBuffer().writeUTF("message " + i); @@ -147,15 +132,13 @@ public class JournalCrashTest extends ActiveMQTestBase session.close(); // server.stop(); -- this test was not supposed to stop the server, it should crash } - finally - { + finally { session.close(); } } @Test - public void testRestartJournal() throws Throwable - { + public void testRestartJournal() throws Throwable { runExternalProcess(getTestDir(), 0, JournalCrashTest.FIRST_RUN); runExternalProcess(getTestDir(), JournalCrashTest.FIRST_RUN, JournalCrashTest.SECOND_RUN); runExternalProcess(getTestDir(), JournalCrashTest.SECOND_RUN, JournalCrashTest.THIRD_RUN); @@ -164,16 +147,14 @@ public class JournalCrashTest extends ActiveMQTestBase printJournal(); ClientSession session = null; - try - { + try { startServer(); session = factory.createSession(true, true); ClientConsumer consumer = session.createConsumer(QUEUE); session.start(); - for (int i = 0; i < JournalCrashTest.FOURTH_RUN; i++) - { + for (int i = 0; i < JournalCrashTest.FOURTH_RUN; i++) { ClientMessage msg = consumer.receive(5000); Assert.assertNotNull("Msg at " + i, msg); @@ -184,14 +165,11 @@ public class JournalCrashTest extends ActiveMQTestBase } session.close(); } - finally - { - try - { + finally { + try { session.close(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } @@ -201,17 +179,9 @@ public class JournalCrashTest extends ActiveMQTestBase * @throws Exception * @throws InterruptedException */ - private void runExternalProcess(final String tempDir, final int start, final int end) throws Exception - { + private void runExternalProcess(final String tempDir, final int start, final int end) throws Exception { System.err.println("running external process..."); - Process process = SpawnedVMSupport.spawnVM(this.getClass().getCanonicalName(), - "-Xms128m", "-Xmx128m", - new String[]{}, - true, - true, - tempDir, - Integer.toString(start), - Integer.toString(end)); + Process process = SpawnedVMSupport.spawnVM(this.getClass().getCanonicalName(), "-Xms128m", "-Xmx128m", new String[]{}, true, true, tempDir, Integer.toString(start), Integer.toString(end)); Assert.assertEquals(100, process.waitFor()); } @@ -219,17 +189,9 @@ public class JournalCrashTest extends ActiveMQTestBase /** * @throws Exception */ - private void printJournal() throws Exception - { + private void printJournal() throws Exception { NIOSequentialFileFactory factory = new NIOSequentialFileFactory(new File(getJournalDir()), 100); - JournalImpl journal = new JournalImpl(ActiveMQDefaultConfiguration.getDefaultJournalFileSize(), - 2, - 0, - 0, - factory, - "activemq-data", - "amq", - 100); + JournalImpl journal = new JournalImpl(ActiveMQDefaultConfiguration.getDefaultJournalFileSize(), 2, 0, 0, factory, "activemq-data", "amq", 100); ArrayList records = new ArrayList(); ArrayList transactions = new ArrayList(); @@ -237,13 +199,13 @@ public class JournalCrashTest extends ActiveMQTestBase journal.start(); journal.load(records, transactions, null); -// System.out.println("==============================================="); -// System.out.println("Journal records at the end:"); -// -// for (RecordInfo record : records) -// { -// System.out.println(record.id + ", update = " + record.isUpdate); -// } + // System.out.println("==============================================="); + // System.out.println("Journal records at the end:"); + // + // for (RecordInfo record : records) + // { + // System.out.println(record.id + ", update = " + record.isUpdate); + // } journal.stop(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/LargeMessageAvoidLargeMessagesTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/LargeMessageAvoidLargeMessagesTest.java index 7d8aac14f2..2d92e4243c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/LargeMessageAvoidLargeMessagesTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/LargeMessageAvoidLargeMessagesTest.java @@ -35,31 +35,24 @@ import org.junit.Test; * The test extends the LargeMessageTest and tests * the functionality of option avoid-large-messages */ -public class LargeMessageAvoidLargeMessagesTest extends LargeMessageTest -{ +public class LargeMessageAvoidLargeMessagesTest extends LargeMessageTest { - public LargeMessageAvoidLargeMessagesTest() - { + public LargeMessageAvoidLargeMessagesTest() { isCompressedTest = true; } @Override - protected boolean isNetty() - { + protected boolean isNetty() { return false; } @Override - protected ServerLocator createFactory(final boolean isNetty) throws Exception - { - return super.createFactory(isNetty) - .setMinLargeMessageSize(10240) - .setCompressLargeMessage(true); + protected ServerLocator createFactory(final boolean isNetty) throws Exception { + return super.createFactory(isNetty).setMinLargeMessageSize(10240).setCompressLargeMessage(true); } @Test - public void testSimpleSendOnAvoid() throws Exception - { + public void testSimpleSendOnAvoid() throws Exception { ActiveMQServer server = createServer(true, isNetty()); server.start(); @@ -90,8 +83,7 @@ public class LargeMessageAvoidLargeMessagesTest extends LargeMessageTest ClientMessage msg1 = consumer.receive(1000); Assert.assertNotNull(msg1); - for (int i = 0; i < input.getSize(); i++) - { + for (int i = 0; i < input.getSize(); i++) { byte b = msg1.getBodyBuffer().readByte(); Assert.assertEquals("incorrect char ", input.getChar(i), b); } @@ -101,12 +93,9 @@ public class LargeMessageAvoidLargeMessagesTest extends LargeMessageTest session.close(); } - - //send some messages that can be compressed into regular size. @Test - public void testSendRegularAfterCompression() throws Exception - { + public void testSendRegularAfterCompression() throws Exception { ActiveMQServer server = createServer(true, isNetty()); server.start(); @@ -124,8 +113,7 @@ public class LargeMessageAvoidLargeMessagesTest extends LargeMessageTest adjustLargeCompression(true, input, 1024); int num = 1; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { ClientMessage clientFile = session.createMessage(true); clientFile.setBodyInputStream(input.clone()); @@ -138,13 +126,11 @@ public class LargeMessageAvoidLargeMessagesTest extends LargeMessageTest validateNoFilesOnLargeDir(); ClientConsumer consumer = session.createConsumer(ADDRESS); - for (int j = 0; j < num; j++) - { + for (int j = 0; j < num; j++) { ClientMessage msg1 = consumer.receive(1000); Assert.assertNotNull(msg1); - for (int i = 0; i < input.getSize(); i++) - { + for (int i = 0; i < input.getSize(); i++) { byte b = msg1.getBodyBuffer().readByte(); Assert.assertEquals("incorrect char ", input.getChar(i), b); } @@ -159,8 +145,7 @@ public class LargeMessageAvoidLargeMessagesTest extends LargeMessageTest //send some messages that cannot be compressed into regular messages @Test - public void testSendLargeAfterUnableToSendRegular() throws Exception - { + public void testSendLargeAfterUnableToSendRegular() throws Exception { ActiveMQServer server = createServer(true, isNetty()); server.start(); @@ -180,8 +165,7 @@ public class LargeMessageAvoidLargeMessagesTest extends LargeMessageTest adjustLargeCompression(false, input, 40 * minLargeSize); int num = 10; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { ClientMessage clientFile = session.createMessage(true); clientFile.setBodyInputStream(input.clone()); @@ -196,13 +180,11 @@ public class LargeMessageAvoidLargeMessagesTest extends LargeMessageTest validateNoFilesOnLargeDir(server.getConfiguration().getLargeMessagesDirectory(), num); ClientConsumer consumer = session.createConsumer(ADDRESS); - for (int j = 0; j < num; j++) - { + for (int j = 0; j < num; j++) { ClientMessage msg1 = consumer.receive(1000); Assert.assertNotNull(msg1); - for (int i = 0; i < input.getSize(); i++) - { + for (int i = 0; i < input.getSize(); i++) { byte b = msg1.getBodyBuffer().readByte(); Assert.assertEquals("incorrect char", input.getChar(i), b); } @@ -216,8 +198,7 @@ public class LargeMessageAvoidLargeMessagesTest extends LargeMessageTest } @Test - public void testMixedCompressionSendReceive() throws Exception - { + public void testMixedCompressionSendReceive() throws Exception { ActiveMQServer server = createServer(true, isNetty()); server.start(); @@ -238,15 +219,12 @@ public class LargeMessageAvoidLargeMessagesTest extends LargeMessageTest adjustLargeCompression(false, largeInput, 50 * minLargeSize); int num = 6; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { ClientMessage clientFile = session.createMessage(true); - if (i % 2 == 0) - { + if (i % 2 == 0) { clientFile.setBodyInputStream(regularInput.clone()); } - else - { + else { clientFile.setBodyInputStream(largeInput.clone()); } @@ -261,23 +239,18 @@ public class LargeMessageAvoidLargeMessagesTest extends LargeMessageTest validateNoFilesOnLargeDir(server.getConfiguration().getLargeMessagesDirectory(), num / 2); ClientConsumer consumer = session.createConsumer(ADDRESS); - for (int j = 0; j < num; j++) - { + for (int j = 0; j < num; j++) { ClientMessage msg1 = consumer.receive(1000); Assert.assertNotNull(msg1); - if (j % 2 == 0) - { - for (int i = 0; i < regularInput.getSize(); i++) - { + if (j % 2 == 0) { + for (int i = 0; i < regularInput.getSize(); i++) { byte b = msg1.getBodyBuffer().readByte(); Assert.assertEquals("incorrect char ", regularInput.getChar(i), b); } } - else - { - for (int i = 0; i < largeInput.getSize(); i++) - { + else { + for (int i = 0; i < largeInput.getSize(); i++) { byte b = msg1.getBodyBuffer().readByte(); Assert.assertEquals("incorrect char ", largeInput.getChar(i), b); } @@ -295,8 +268,7 @@ public class LargeMessageAvoidLargeMessagesTest extends LargeMessageTest //because after compression, the messages are regulars at server. @Override @Test - public void testDLALargeMessage() throws Exception - { + public void testDLALargeMessage() throws Exception { final int messageSize = (int) (3.5 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE); ClientSession session = null; @@ -309,15 +281,12 @@ public class LargeMessageAvoidLargeMessagesTest extends LargeMessageTest session = addClientSession(sf.createSession(false, false, false)); - session.createQueue(ADDRESS, ADDRESS, - true); + session.createQueue(ADDRESS, ADDRESS, true); session.createQueue(ADDRESS, ADDRESS.concat("-2"), true); SimpleString ADDRESS_DLA = ADDRESS.concat("-dla"); - AddressSettings addressSettings = new AddressSettings() - .setDeadLetterAddress(ADDRESS_DLA) - .setMaxDeliveryAttempts(1); + AddressSettings addressSettings = new AddressSettings().setDeadLetterAddress(ADDRESS_DLA).setMaxDeliveryAttempts(1); server.getAddressSettingsRepository().addMatch("*", addressSettings); @@ -346,10 +315,8 @@ public class LargeMessageAvoidLargeMessagesTest extends LargeMessageTest Assert.assertNotNull(msg1); - for (int i = 0; i < messageSize; i++) - { - Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg1 - .getBodyBuffer().readByte()); + for (int i = 0; i < messageSize; i++) { + Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg1.getBodyBuffer().readByte()); } session.close(); @@ -371,10 +338,8 @@ public class LargeMessageAvoidLargeMessagesTest extends LargeMessageTest Assert.assertNotNull(msg1); - for (int i = 0; i < messageSize; i++) - { - Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg1 - .getBodyBuffer().readByte()); + for (int i = 0; i < messageSize; i++) { + Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg1.getBodyBuffer().readByte()); } msg1.acknowledge(); @@ -390,10 +355,8 @@ public class LargeMessageAvoidLargeMessagesTest extends LargeMessageTest Assert.assertNotNull(msg1); - for (int i = 0; i < messageSize; i++) - { - Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg1 - .getBodyBuffer().readByte()); + for (int i = 0; i < messageSize; i++) { + Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg1.getBodyBuffer().readByte()); } msg1.acknowledge(); @@ -407,8 +370,7 @@ public class LargeMessageAvoidLargeMessagesTest extends LargeMessageTest @Override @Test - public void testSendServerMessage() throws Exception - { + public void testSendServerMessage() throws Exception { // doesn't make sense as compressed } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/LargeMessageCompressTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/LargeMessageCompressTest.java index 305dbfb290..0762956895 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/LargeMessageCompressTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/LargeMessageCompressTest.java @@ -42,30 +42,25 @@ import org.junit.Test; *
    * Just extend the LargeMessageTest */ -public class LargeMessageCompressTest extends LargeMessageTest -{ +public class LargeMessageCompressTest extends LargeMessageTest { + // Constructors -------------------------------------------------- - public LargeMessageCompressTest() - { + public LargeMessageCompressTest() { isCompressedTest = true; } @Override - protected boolean isNetty() - { + protected boolean isNetty() { return false; } @Override - protected ServerLocator createFactory(final boolean isNetty) throws Exception - { - return super.createFactory(isNetty) - .setCompressLargeMessage(true); + protected ServerLocator createFactory(final boolean isNetty) throws Exception { + return super.createFactory(isNetty).setCompressLargeMessage(true); } @Test - public void testLargeMessageCompression() throws Exception - { + public void testLargeMessageCompression() throws Exception { final int messageSize = (int) (3.5 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE); ActiveMQServer server = createServer(true, isNetty()); @@ -92,8 +87,7 @@ public class LargeMessageCompressTest extends LargeMessageTest ClientMessage msg1 = consumer.receive(1000); Assert.assertNotNull(msg1); - for (int i = 0; i < messageSize; i++) - { + for (int i = 0; i < messageSize; i++) { byte b = msg1.getBodyBuffer().readByte(); assertEquals("position = " + i, getSamplebyte(i), b); } @@ -109,8 +103,7 @@ public class LargeMessageCompressTest extends LargeMessageTest } @Test - public void testLargeMessageCompression2() throws Exception - { + public void testLargeMessageCompression2() throws Exception { final int messageSize = (int) (3.5 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE); ActiveMQServer server = createServer(true, isNetty()); @@ -157,8 +150,7 @@ public class LargeMessageCompressTest extends LargeMessageTest //verify FileInputStream input = new FileInputStream(testFile); - for (int i = 0; i < messageSize; i++) - { + for (int i = 0; i < messageSize; i++) { byte b = (byte) input.read(); assertEquals("position = " + i, getSamplebyte(i), b); } @@ -169,8 +161,7 @@ public class LargeMessageCompressTest extends LargeMessageTest } @Test - public void testLargeMessageCompression3() throws Exception - { + public void testLargeMessageCompression3() throws Exception { final int messageSize = (int) (3.5 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE); ActiveMQServer server = createServer(true, isNetty()); @@ -215,8 +206,7 @@ public class LargeMessageCompressTest extends LargeMessageTest //verify FileInputStream input = new FileInputStream(testFile); - for (int i = 0; i < messageSize; i++) - { + for (int i = 0; i < messageSize; i++) { byte b = (byte) input.read(); assertEquals("position = " + i, getSamplebyte(i), b); } @@ -226,12 +216,10 @@ public class LargeMessageCompressTest extends LargeMessageTest validateNoFilesOnLargeDir(); } - // This test will send 1 Gig of spaces. There shouldn't be enough memory to uncompress the file in memory // but this will make sure we can work through compressed channels on saving it to stream @Test - public void testHugeStreamingSpacesCompressed() throws Exception - { + public void testHugeStreamingSpacesCompressed() throws Exception { final long messageSize = 1024L * 1024L * 1024L; System.out.println("Message size = " + messageSize); @@ -253,33 +241,27 @@ public class LargeMessageCompressTest extends LargeMessageTest ClientMessage clientMessage = session.createMessage(true); - clientMessage.setBodyInputStream(new InputStream() - { + clientMessage.setBodyInputStream(new InputStream() { private long count; private boolean closed = false; @Override - public void close() throws IOException - { + public void close() throws IOException { super.close(); closed = true; } @Override - public int read() throws IOException - { - if (closed) - { + public int read() throws IOException { + if (closed) { throw new IOException("Stream was closed"); } - if (count++ < messageSize) - { + if (count++ < messageSize) { return ' '; } - else - { + else { return -1; } } @@ -300,19 +282,15 @@ public class LargeMessageCompressTest extends LargeMessageTest final AtomicLong numberOfSpaces = new AtomicLong(); - msg1.saveToOutputStream(new OutputStream() - { + msg1.saveToOutputStream(new OutputStream() { @Override - public void write(int content) - { - if (content == ' ') - { + public void write(int content) { + if (content == ' ') { numberOfSpaces.incrementAndGet(); } } }); - assertEquals(messageSize, numberOfSpaces.get()); msg1.acknowledge(); @@ -322,13 +300,10 @@ public class LargeMessageCompressTest extends LargeMessageTest session.close(); } - @Test - public void testLargeMessageCompressionRestartAndCheckSize() throws Exception - { + public void testLargeMessageCompressionRestartAndCheckSize() throws Exception { final int messageSize = 1024 * 1024; - ActiveMQServer server = createServer(true, isNetty()); server.start(); @@ -342,8 +317,7 @@ public class LargeMessageCompressTest extends LargeMessageTest ClientProducer producer = session.createProducer(ADDRESS); byte[] msgs = new byte[1024 * 1024]; - for (int i = 0; i < msgs.length; i++) - { + for (int i = 0; i < msgs.length; i++) { msgs[i] = RandomUtil.randomByte(); } @@ -395,8 +369,7 @@ public class LargeMessageCompressTest extends LargeMessageTest //verify FileInputStream input = new FileInputStream(testFile); - for (int i = 0; i < messageSize; i++) - { + for (int i = 0; i < messageSize; i++) { byte b = (byte) input.read(); assertEquals("position = " + i, msgs[i], b); } @@ -406,11 +379,9 @@ public class LargeMessageCompressTest extends LargeMessageTest validateNoFilesOnLargeDir(); } - @Override @Test - public void testSendServerMessage() throws Exception - { + public void testSendServerMessage() throws Exception { // doesn't make sense as compressed } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/LargeMessageTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/LargeMessageTest.java index 10e1324053..28f6f14150 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/LargeMessageTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/LargeMessageTest.java @@ -54,8 +54,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class LargeMessageTest extends LargeMessageTestBase -{ +public class LargeMessageTest extends LargeMessageTestBase { // Constants ----------------------------------------------------- static final int RECEIVE_WAIT_TIME = 10000; @@ -72,16 +71,13 @@ public class LargeMessageTest extends LargeMessageTestBase // Public -------------------------------------------------------- - protected boolean isNetty() - { + protected boolean isNetty() { return false; } @Test - public void testRollbackPartiallyConsumedBuffer() throws Exception - { - for (int i = 0; i < 1; i++) - { + public void testRollbackPartiallyConsumedBuffer() throws Exception { + for (int i = 0; i < 1; i++) { log.info("#test " + i); internalTestRollbackPartiallyConsumedBuffer(false); tearDown(); @@ -92,27 +88,21 @@ public class LargeMessageTest extends LargeMessageTestBase } @Test - public void testRollbackPartiallyConsumedBufferWithRedeliveryDelay() throws Exception - { + public void testRollbackPartiallyConsumedBufferWithRedeliveryDelay() throws Exception { internalTestRollbackPartiallyConsumedBuffer(true); } - - private void internalTestRollbackPartiallyConsumedBuffer(final boolean redeliveryDelay) throws Exception - { + private void internalTestRollbackPartiallyConsumedBuffer(final boolean redeliveryDelay) throws Exception { final int messageSize = 100 * 1024; - final ClientSession session; ActiveMQServer server = createServer(true, isNetty()); AddressSettings settings = new AddressSettings(); - if (redeliveryDelay) - { + if (redeliveryDelay) { settings.setRedeliveryDelay(100); - if (locator.isCompressLargeMessage()) - { + if (locator.isCompressLargeMessage()) { locator.setConsumerWindowSize(0); } } @@ -130,8 +120,7 @@ public class LargeMessageTest extends LargeMessageTestBase ClientProducer producer = session.createProducer(ADDRESS); - for (int i = 0; i < 20; i++) - { + for (int i = 0; i < 20; i++) { Message clientFile = createLargeClientMessageStreaming(session, messageSize, true); clientFile.putIntProperty("value", i); @@ -149,36 +138,29 @@ public class LargeMessageTest extends LargeMessageTestBase ClientConsumer consumer = session.createConsumer(ADDRESS); - consumer.setMessageHandler(new MessageHandler() - { + consumer.setMessageHandler(new MessageHandler() { int counter = 0; - public void onMessage(ClientMessage message) - { + public void onMessage(ClientMessage message) { message.getBodyBuffer().readByte(); // System.out.println("message:" + message); - try - { - if (counter++ < 20) - { + try { + if (counter++ < 20) { Thread.sleep(100); // System.out.println("Rollback"); message.acknowledge(); session.rollback(); } - else - { + else { message.acknowledge(); session.commit(); } - if (counter == 40) - { + if (counter == 40) { latch.countDown(); } } - catch (Exception e) - { + catch (Exception e) { latch.countDown(); e.printStackTrace(); errors.incrementAndGet(); @@ -196,8 +178,7 @@ public class LargeMessageTest extends LargeMessageTestBase } @Test - public void testCloseConsumer() throws Exception - { + public void testCloseConsumer() throws Exception { final int messageSize = (int) (3.5 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE); ClientSession session = null; @@ -230,13 +211,11 @@ public class LargeMessageTest extends LargeMessageTestBase consumer.close(); - try - { + try { msg1.getBodyBuffer().readByte(); Assert.fail("Exception was expected"); } - catch (final Exception ignored) - { + catch (final Exception ignored) { // empty on purpose } @@ -246,8 +225,7 @@ public class LargeMessageTest extends LargeMessageTestBase } @Test - public void testDeleteOnNoBinding() throws Exception - { + public void testDeleteOnNoBinding() throws Exception { final int messageSize = (int) (3.5 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE); ActiveMQServer server = createServer(true, isNetty()); @@ -270,8 +248,7 @@ public class LargeMessageTest extends LargeMessageTestBase } @Test - public void testDeleteOnDrop() throws Exception - { + public void testDeleteOnDrop() throws Exception { fillAddress(); final int messageSize = (int) (3.5 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE); @@ -291,31 +268,21 @@ public class LargeMessageTest extends LargeMessageTestBase validateNoFilesOnLargeDir(); } - - private void fillAddress() throws Exception - { + private void fillAddress() throws Exception { final int PAGE_MAX = 100 * 1024; final int PAGE_SIZE = 10 * 1024; final int MESSAGE_SIZE = 1024; // 1k - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); - ActiveMQServer server = createServer(true, - config, - PAGE_SIZE, - PAGE_MAX, - new HashMap()); + ActiveMQServer server = createServer(true, config, PAGE_SIZE, PAGE_MAX, new HashMap()); server.start(); server.getAddressSettingsRepository().getMatch("#").setAddressFullMessagePolicy(AddressFullMessagePolicy.DROP); - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator = createInVMNonHALocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); ClientSessionFactory sf = createSessionFactory(locator); @@ -331,13 +298,11 @@ public class LargeMessageTest extends LargeMessageTestBase ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= MESSAGE_SIZE; j++) - { + for (int j = 1; j <= MESSAGE_SIZE; j++) { bb.put(getSamplebyte(j)); } - for (int i = 0; i < 5000; i++) - { + for (int i = 0; i < 5000; i++) { message = session.createMessage(true); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); @@ -347,8 +312,7 @@ public class LargeMessageTest extends LargeMessageTestBase message.putIntProperty(new SimpleString("id"), i); producer.send(message); - if (i % 1000 == 0) - { + if (i % 1000 == 0) { session.commit(); } } @@ -357,29 +321,23 @@ public class LargeMessageTest extends LargeMessageTestBase } @Test - public void testLargeBufferTransacted() throws Exception - { + public void testLargeBufferTransacted() throws Exception { doTestLargeBuffer(true); } @Test - public void testLargeBufferNotTransacted() throws Exception - { + public void testLargeBufferNotTransacted() throws Exception { doTestLargeBuffer(false); } - public void doTestLargeBuffer(boolean transacted) throws Exception - { + public void doTestLargeBuffer(boolean transacted) throws Exception { final int journalsize = 100 * 1024; final int messageSize = 3 * journalsize; // final int messageSize = 5 * 1024; ClientSession session = null; - Configuration config = createDefaultConfig(isNetty()) - .setJournalFileSize(journalsize) - .setJournalBufferSize_AIO(10 * 1024) - .setJournalBufferSize_NIO(10 * 1024); + Configuration config = createDefaultConfig(isNetty()).setJournalFileSize(journalsize).setJournalBufferSize_AIO(10 * 1024).setJournalBufferSize_NIO(10 * 1024); ActiveMQServer server = createServer(true, config); @@ -394,15 +352,13 @@ public class LargeMessageTest extends LargeMessageTestBase ClientProducer producer = session.createProducer(ADDRESS); Message clientFile = session.createMessage(true); - for (int i = 0; i < messageSize; i++) - { + for (int i = 0; i < messageSize; i++) { clientFile.getBodyBuffer().writeByte(getSamplebyte(i)); } producer.send(clientFile); - if (transacted) - { + if (transacted) { session.commit(); } @@ -414,8 +370,7 @@ public class LargeMessageTest extends LargeMessageTestBase Assert.assertNotNull(msg1); - for (int i = 0; i < messageSize; i++) - { + for (int i = 0; i < messageSize; i++) { // System.out.print(msg1.getBodyBuffer().readByte() + " "); // if (i % 100 == 0) System.out.println(); assertEquals("position = " + i, getSamplebyte(i), msg1.getBodyBuffer().readByte()); @@ -425,8 +380,7 @@ public class LargeMessageTest extends LargeMessageTestBase consumer.close(); - if (transacted) - { + if (transacted) { session.commit(); } @@ -436,8 +390,7 @@ public class LargeMessageTest extends LargeMessageTestBase } @Test - public void testDLALargeMessage() throws Exception - { + public void testDLALargeMessage() throws Exception { final int messageSize = (int) (3.5 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE); ClientSession session = null; @@ -455,9 +408,7 @@ public class LargeMessageTest extends LargeMessageTestBase SimpleString ADDRESS_DLA = ADDRESS.concat("-dla"); - AddressSettings addressSettings = new AddressSettings() - .setDeadLetterAddress(ADDRESS_DLA) - .setMaxDeliveryAttempts(1); + AddressSettings addressSettings = new AddressSettings().setDeadLetterAddress(ADDRESS_DLA).setMaxDeliveryAttempts(1); server.getAddressSettingsRepository().addMatch("*", addressSettings); @@ -486,8 +437,7 @@ public class LargeMessageTest extends LargeMessageTestBase Assert.assertNotNull(msg1); - for (int i = 0; i < messageSize; i++) - { + for (int i = 0; i < messageSize; i++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg1.getBodyBuffer().readByte()); } @@ -510,8 +460,7 @@ public class LargeMessageTest extends LargeMessageTestBase Assert.assertNotNull(msg1); - for (int i = 0; i < messageSize; i++) - { + for (int i = 0; i < messageSize; i++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg1.getBodyBuffer().readByte()); } @@ -527,8 +476,7 @@ public class LargeMessageTest extends LargeMessageTestBase Assert.assertNotNull(msg1); - for (int i = 0; i < messageSize; i++) - { + for (int i = 0; i < messageSize; i++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg1.getBodyBuffer().readByte()); } @@ -542,8 +490,7 @@ public class LargeMessageTest extends LargeMessageTestBase } @Test - public void testDeliveryCount() throws Exception - { + public void testDeliveryCount() throws Exception { final int messageSize = (int) (3.5 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE); ClientSession session = null; @@ -576,8 +523,7 @@ public class LargeMessageTest extends LargeMessageTestBase log.info("body buffer is " + msg.getBodyBuffer()); - for (int i = 0; i < messageSize; i++) - { + for (int i = 0; i < messageSize; i++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg.getBodyBuffer().readByte()); } session.rollback(); @@ -591,8 +537,7 @@ public class LargeMessageTest extends LargeMessageTestBase msg = consumer.receive(10000); Assert.assertNotNull(msg); msg.acknowledge(); - for (int i = 0; i < messageSize; i++) - { + for (int i = 0; i < messageSize; i++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg.getBodyBuffer().readByte()); } Assert.assertEquals(2, msg.getDeliveryCount()); @@ -606,8 +551,7 @@ public class LargeMessageTest extends LargeMessageTestBase } @Test - public void testDLAOnExpiryNonDurableMessage() throws Exception - { + public void testDLAOnExpiryNonDurableMessage() throws Exception { final int messageSize = (int) (3.5 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE); ClientSession session = null; @@ -621,10 +565,7 @@ public class LargeMessageTest extends LargeMessageTestBase SimpleString ADDRESS_DLA = ADDRESS.concat("-dla"); SimpleString ADDRESS_EXPIRY = ADDRESS.concat("-expiry"); - AddressSettings addressSettings = new AddressSettings() - .setDeadLetterAddress(ADDRESS_DLA) - .setExpiryAddress(ADDRESS_EXPIRY) - .setMaxDeliveryAttempts(1); + AddressSettings addressSettings = new AddressSettings().setDeadLetterAddress(ADDRESS_DLA).setExpiryAddress(ADDRESS_EXPIRY).setMaxDeliveryAttempts(1); server.getAddressSettingsRepository().addMatch("*", addressSettings); @@ -658,8 +599,7 @@ public class LargeMessageTest extends LargeMessageTestBase Assert.assertNotNull(msg1); msg1.acknowledge(); - for (int j = 0; j < messageSize; j++) - { + for (int j = 0; j < messageSize; j++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(j), msg1.getBodyBuffer().readByte()); } @@ -667,8 +607,7 @@ public class LargeMessageTest extends LargeMessageTestBase consumerExpiry.close(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { consumerExpiry = session.createConsumer(ADDRESS_DLA); @@ -676,8 +615,7 @@ public class LargeMessageTest extends LargeMessageTestBase Assert.assertNotNull(msg1); msg1.acknowledge(); - for (int j = 0; j < messageSize; j++) - { + for (int j = 0; j < messageSize; j++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(j), msg1.getBodyBuffer().readByte()); } @@ -700,8 +638,7 @@ public class LargeMessageTest extends LargeMessageTestBase msg1.acknowledge(); - for (int i = 0; i < messageSize; i++) - { + for (int i = 0; i < messageSize; i++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg1.getBodyBuffer().readByte()); } @@ -722,8 +659,7 @@ public class LargeMessageTest extends LargeMessageTestBase } @Test - public void testDLAOnExpiry() throws Exception - { + public void testDLAOnExpiry() throws Exception { final int messageSize = (int) (3.5 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE); ClientSession session = null; @@ -737,10 +673,7 @@ public class LargeMessageTest extends LargeMessageTestBase SimpleString ADDRESS_DLA = ADDRESS.concat("-dla"); SimpleString ADDRESS_EXPIRY = ADDRESS.concat("-expiry"); - AddressSettings addressSettings = new AddressSettings() - .setDeadLetterAddress(ADDRESS_DLA) - .setExpiryAddress(ADDRESS_EXPIRY) - .setMaxDeliveryAttempts(1); + AddressSettings addressSettings = new AddressSettings().setDeadLetterAddress(ADDRESS_DLA).setExpiryAddress(ADDRESS_EXPIRY).setMaxDeliveryAttempts(1); server.getAddressSettingsRepository().addMatch("*", addressSettings); @@ -773,8 +706,7 @@ public class LargeMessageTest extends LargeMessageTestBase Assert.assertNotNull(msg1); msg1.acknowledge(); - for (int j = 0; j < messageSize; j++) - { + for (int j = 0; j < messageSize; j++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(j), msg1.getBodyBuffer().readByte()); } @@ -782,16 +714,14 @@ public class LargeMessageTest extends LargeMessageTestBase consumerExpiry.close(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { consumerExpiry = session.createConsumer(ADDRESS_DLA); msg1 = consumerExpiry.receive(5000); Assert.assertNotNull(msg1); msg1.acknowledge(); - for (int j = 0; j < messageSize; j++) - { + for (int j = 0; j < messageSize; j++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(j), msg1.getBodyBuffer().readByte()); } @@ -819,8 +749,7 @@ public class LargeMessageTest extends LargeMessageTestBase Assert.assertNotNull(msg1); msg1.acknowledge(); - for (int i = 0; i < messageSize; i++) - { + for (int i = 0; i < messageSize; i++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg1.getBodyBuffer().readByte()); } @@ -836,14 +765,12 @@ public class LargeMessageTest extends LargeMessageTestBase } @Test - public void testExpiryLargeMessage() throws Exception - { + public void testExpiryLargeMessage() throws Exception { final int messageSize = 3 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; ClientSession session = null; - try - { + try { ActiveMQServer server = createServer(true, isNetty()); server.start(); @@ -884,8 +811,7 @@ public class LargeMessageTest extends LargeMessageTestBase Assert.assertNotNull(msg1); - for (int i = 0; i < messageSize; i++) - { + for (int i = 0; i < messageSize; i++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg1.getBodyBuffer().readByte()); } @@ -908,8 +834,7 @@ public class LargeMessageTest extends LargeMessageTestBase Assert.assertNotNull(msg1); - for (int i = 0; i < messageSize; i++) - { + for (int i = 0; i < messageSize; i++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg1.getBodyBuffer().readByte()); } @@ -921,38 +846,31 @@ public class LargeMessageTest extends LargeMessageTestBase validateNoFilesOnLargeDir(); } - finally - { - try - { + finally { + try { session.close(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } } @Test - public void testSentWithDuplicateIDBridge() throws Exception - { + public void testSentWithDuplicateIDBridge() throws Exception { internalTestSentWithDuplicateID(true); } @Test - public void testSentWithDuplicateID() throws Exception - { + public void testSentWithDuplicateID() throws Exception { internalTestSentWithDuplicateID(false); } - private void internalTestSentWithDuplicateID(final boolean isSimulateBridge) throws Exception - { + private void internalTestSentWithDuplicateID(final boolean isSimulateBridge) throws Exception { final int messageSize = 3 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; ClientSession session = null; - try - { + try { ActiveMQServer server = createServer(true, isNetty()); server.start(); @@ -967,16 +885,13 @@ public class LargeMessageTest extends LargeMessageTestBase String someDuplicateInfo = "Anything"; - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { Message clientFile = createLargeClientMessageStreaming(session, messageSize, true); - if (isSimulateBridge) - { + if (isSimulateBridge) { clientFile.putBytesProperty(MessageImpl.HDR_BRIDGE_DUPLICATE_ID, someDuplicateInfo.getBytes()); } - else - { + else { clientFile.putBytesProperty(Message.HDR_DUPLICATE_DETECTION_ID, someDuplicateInfo.getBytes()); } @@ -989,8 +904,7 @@ public class LargeMessageTest extends LargeMessageTestBase ClientMessage msg = consumer.receive(10000); - for (int i = 0; i < messageSize; i++) - { + for (int i = 0; i < messageSize; i++) { assertEquals(getSamplebyte(i), msg.getBodyBuffer().readByte()); } @@ -1005,37 +919,30 @@ public class LargeMessageTest extends LargeMessageTestBase validateNoFilesOnLargeDir(); } - finally - { - try - { + finally { + try { session.close(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } } @Test - public void testResendSmallStreamMessage() throws Exception - { + public void testResendSmallStreamMessage() throws Exception { internalTestResendMessage(50000); } @Test - public void testResendLargeStreamMessage() throws Exception - { + public void testResendLargeStreamMessage() throws Exception { internalTestResendMessage(150 * 1024); } - public void internalTestResendMessage(final long messageSize) throws Exception - { + public void internalTestResendMessage(final long messageSize) throws Exception { clearDataRecreateServerDirs(); ClientSession session = null; - try - { + try { ActiveMQServer server = createServer(true, isNetty()); server.start(); @@ -1088,42 +995,34 @@ public class LargeMessageTest extends LargeMessageTestBase validateNoFilesOnLargeDir(); } - finally - { - try - { + finally { + try { session.close(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } } @Test - public void testResendCachedSmallStreamMessage() throws Exception - { + public void testResendCachedSmallStreamMessage() throws Exception { internalTestResendMessage(50000); } @Test - public void testResendCachedLargeStreamMessage() throws Exception - { + public void testResendCachedLargeStreamMessage() throws Exception { internalTestCachedResendMessage(150 * 1024); } - public void internalTestCachedResendMessage(final long messageSize) throws Exception - { + public void internalTestCachedResendMessage(final long messageSize) throws Exception { ClientSession session = null; - try - { + try { ActiveMQServer server = createServer(true, isNetty()); server.start(); - locator.setMinLargeMessageSize(200) - .setCacheLargeMessagesClient(true); + locator.setMinLargeMessageSize(200).setCacheLargeMessagesClient(true); ClientSessionFactory sf = addSessionFactory(createSessionFactory(locator)); @@ -1168,14 +1067,11 @@ public class LargeMessageTest extends LargeMessageTestBase validateNoFilesOnLargeDir(); } - finally - { - try - { + finally { + try { session.close(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } } @@ -1184,910 +1080,265 @@ public class LargeMessageTest extends LargeMessageTestBase * @param messageSize * @param msg */ - private void compareString(final long messageSize, ClientMessage msg) - { + private void compareString(final long messageSize, ClientMessage msg) { assertNotNull(msg); - for (long i = 0; i < messageSize; i++) - { + for (long i = 0; i < messageSize; i++) { Assert.assertEquals("position " + i, ActiveMQTestBase.getSamplebyte(i), msg.getBodyBuffer().readByte()); } } @Test - public void testFilePersistenceOneHugeMessage() throws Exception - { - testChunks(false, - false, - false, - true, - true, - false, - false, - false, - false, - 1, - 100 * 1024L * 1024L, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0, - 10 * 1024 * 1024, - 1024 * 1024); + public void testFilePersistenceOneHugeMessage() throws Exception { + testChunks(false, false, false, true, true, false, false, false, false, 1, 100 * 1024L * 1024L, LargeMessageTest.RECEIVE_WAIT_TIME, 0, 10 * 1024 * 1024, 1024 * 1024); } @Test - public void testFilePersistenceOneMessageStreaming() throws Exception - { - testChunks(false, - false, - false, - true, - true, - false, - false, - false, - false, - 1, - 100 * 1024L * 1024L, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testFilePersistenceOneMessageStreaming() throws Exception { + testChunks(false, false, false, true, true, false, false, false, false, 1, 100 * 1024L * 1024L, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testFilePersistenceSmallMessageStreaming() throws Exception - { - testChunks(false, - false, - false, - true, - true, - false, - false, - false, - false, - 100, - 1024, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testFilePersistenceSmallMessageStreaming() throws Exception { + testChunks(false, false, false, true, true, false, false, false, false, 100, 1024, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testFilePersistenceOneHugeMessageConsumer() throws Exception - { - testChunks(false, - false, - false, - true, - true, - false, - false, - false, - true, - 1, - 100 * 1024 * 1024, - 120000, - 0, - 10 * 1024 * 1024, - 1024 * 1024); + public void testFilePersistenceOneHugeMessageConsumer() throws Exception { + testChunks(false, false, false, true, true, false, false, false, true, 1, 100 * 1024 * 1024, 120000, 0, 10 * 1024 * 1024, 1024 * 1024); } @Test - public void testFilePersistence() throws Exception - { - testChunks(false, - false, - true, - false, - true, - false, - false, - true, - false, - 100, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testFilePersistence() throws Exception { + testChunks(false, false, true, false, true, false, false, true, false, 100, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testFilePersistenceConsumer() throws Exception - { - testChunks(false, - false, - true, - false, - true, - false, - false, - true, - true, - 2, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testFilePersistenceConsumer() throws Exception { + testChunks(false, false, true, false, true, false, false, true, true, 2, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testFilePersistenceXA() throws Exception - { - testChunks(true, - false, - true, - false, - true, - false, - false, - true, - false, - 100, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testFilePersistenceXA() throws Exception { + testChunks(true, false, true, false, true, false, false, true, false, 100, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testFilePersistenceXAStream() throws Exception - { - testChunks(true, - false, - false, - true, - true, - false, - false, - false, - false, - 1, - 1024 * 1024, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testFilePersistenceXAStream() throws Exception { + testChunks(true, false, false, true, true, false, false, false, false, 1, 1024 * 1024, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testFilePersistenceXAStreamRestart() throws Exception - { - testChunks(true, - true, - false, - true, - true, - false, - false, - false, - false, - 1, - 1024 * 1024, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testFilePersistenceXAStreamRestart() throws Exception { + testChunks(true, true, false, true, true, false, false, false, false, 1, 1024 * 1024, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testFilePersistenceXAConsumer() throws Exception - { - testChunks(true, - false, - true, - false, - true, - false, - false, - true, - true, - 100, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testFilePersistenceXAConsumer() throws Exception { + testChunks(true, false, true, false, true, false, false, true, true, 100, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testFilePersistenceXAConsumerRestart() throws Exception - { - testChunks(true, - true, - true, - false, - true, - false, - false, - true, - true, - 100, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testFilePersistenceXAConsumerRestart() throws Exception { + testChunks(true, true, true, false, true, false, false, true, true, 100, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testFilePersistenceBlocked() throws Exception - { - testChunks(false, - false, - true, - false, - true, - false, - true, - true, - false, - 100, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testFilePersistenceBlocked() throws Exception { + testChunks(false, false, true, false, true, false, true, true, false, 100, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testFilePersistenceBlockedConsumer() throws Exception - { - testChunks(false, - false, - true, - false, - true, - false, - true, - true, - true, - 100, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testFilePersistenceBlockedConsumer() throws Exception { + testChunks(false, false, true, false, true, false, true, true, true, 100, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testFilePersistenceBlockedXA() throws Exception - { - testChunks(true, - false, - true, - false, - true, - false, - true, - true, - false, - 100, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testFilePersistenceBlockedXA() throws Exception { + testChunks(true, false, true, false, true, false, true, true, false, 100, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testFilePersistenceBlockedXAConsumer() throws Exception - { - testChunks(true, - false, - true, - false, - true, - false, - true, - true, - true, - 100, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testFilePersistenceBlockedXAConsumer() throws Exception { + testChunks(true, false, true, false, true, false, true, true, true, 100, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testFilePersistenceBlockedPreACK() throws Exception - { - testChunks(false, - false, - true, - false, - true, - true, - true, - true, - false, - 1, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testFilePersistenceBlockedPreACK() throws Exception { + testChunks(false, false, true, false, true, true, true, true, false, 1, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testFilePersistenceBlockedPreACKConsumer() throws Exception - { - testChunks(false, - false, - true, - false, - true, - true, - true, - true, - true, - 1, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testFilePersistenceBlockedPreACKConsumer() throws Exception { + testChunks(false, false, true, false, true, true, true, true, true, 1, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testFilePersistenceBlockedPreACKXA() throws Exception - { - testChunks(true, - false, - true, - false, - true, - true, - true, - true, - false, - 100, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testFilePersistenceBlockedPreACKXA() throws Exception { + testChunks(true, false, true, false, true, true, true, true, false, 100, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testFilePersistenceBlockedPreACKXARestart() throws Exception - { - testChunks(true, - true, - true, - false, - true, - true, - true, - true, - false, - 100, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testFilePersistenceBlockedPreACKXARestart() throws Exception { + testChunks(true, true, true, false, true, true, true, true, false, 100, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testFilePersistenceBlockedPreACKXAConsumer() throws Exception - { - testChunks(true, - false, - true, - false, - true, - true, - true, - true, - true, - 100, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testFilePersistenceBlockedPreACKXAConsumer() throws Exception { + testChunks(true, false, true, false, true, true, true, true, true, 100, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testFilePersistenceBlockedPreACKXAConsumerRestart() throws Exception - { - testChunks(true, - true, - true, - false, - true, - true, - true, - true, - true, - 100, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testFilePersistenceBlockedPreACKXAConsumerRestart() throws Exception { + testChunks(true, true, true, false, true, true, true, true, true, 100, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testFilePersistenceDelayed() throws Exception - { - testChunks(false, - false, - true, - false, - true, - false, - false, - false, - false, - 1, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 2000); + public void testFilePersistenceDelayed() throws Exception { + testChunks(false, false, true, false, true, false, false, false, false, 1, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 2000); } @Test - public void testFilePersistenceDelayedConsumer() throws Exception - { - testChunks(false, - false, - true, - false, - true, - false, - false, - false, - true, - 1, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 2000); + public void testFilePersistenceDelayedConsumer() throws Exception { + testChunks(false, false, true, false, true, false, false, false, true, 1, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 2000); } @Test - public void testFilePersistenceDelayedXA() throws Exception - { - testChunks(true, - false, - true, - false, - true, - false, - false, - false, - false, - 1, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 2000); + public void testFilePersistenceDelayedXA() throws Exception { + testChunks(true, false, true, false, true, false, false, false, false, 1, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 2000); } @Test - public void testFilePersistenceDelayedXAConsumer() throws Exception - { - testChunks(true, - false, - true, - false, - true, - false, - false, - false, - true, - 1, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 2000); + public void testFilePersistenceDelayedXAConsumer() throws Exception { + testChunks(true, false, true, false, true, false, false, false, true, 1, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 2000); } @Test - public void testNullPersistence() throws Exception - { - testChunks(false, - false, - true, - false, - false, - false, - false, - true, - true, - 1, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testNullPersistence() throws Exception { + testChunks(false, false, true, false, false, false, false, true, true, 1, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testNullPersistenceConsumer() throws Exception - { - testChunks(false, - false, - true, - false, - false, - false, - false, - true, - true, - 1, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testNullPersistenceConsumer() throws Exception { + testChunks(false, false, true, false, false, false, false, true, true, 1, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testNullPersistenceXA() throws Exception - { - testChunks(true, - false, - true, - false, - false, - false, - false, - true, - false, - 1, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testNullPersistenceXA() throws Exception { + testChunks(true, false, true, false, false, false, false, true, false, 1, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testNullPersistenceXAConsumer() throws Exception - { - testChunks(true, - false, - true, - false, - false, - false, - false, - true, - true, - 1, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testNullPersistenceXAConsumer() throws Exception { + testChunks(true, false, true, false, false, false, false, true, true, 1, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testNullPersistenceDelayed() throws Exception - { - testChunks(false, - false, - true, - false, - false, - false, - false, - false, - false, - 100, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 100); + public void testNullPersistenceDelayed() throws Exception { + testChunks(false, false, true, false, false, false, false, false, false, 100, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 100); } @Test - public void testNullPersistenceDelayedConsumer() throws Exception - { - testChunks(false, - false, - true, - false, - false, - false, - false, - false, - true, - 100, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 100); + public void testNullPersistenceDelayedConsumer() throws Exception { + testChunks(false, false, true, false, false, false, false, false, true, 100, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 100); } @Test - public void testNullPersistenceDelayedXA() throws Exception - { - testChunks(true, - false, - true, - false, - false, - false, - false, - false, - false, - 100, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 100); + public void testNullPersistenceDelayedXA() throws Exception { + testChunks(true, false, true, false, false, false, false, false, false, 100, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 100); } @Test - public void testNullPersistenceDelayedXAConsumer() throws Exception - { - testChunks(true, - false, - true, - false, - false, - false, - false, - false, - true, - 100, - LARGE_MESSAGE_SIZE, - LargeMessageTest.RECEIVE_WAIT_TIME, - 100); + public void testNullPersistenceDelayedXAConsumer() throws Exception { + testChunks(true, false, true, false, false, false, false, false, true, 100, LARGE_MESSAGE_SIZE, LargeMessageTest.RECEIVE_WAIT_TIME, 100); } @Test - public void testPageOnLargeMessage() throws Exception - { + public void testPageOnLargeMessage() throws Exception { testPageOnLargeMessage(true, false); } @Test - public void testSendSmallMessageXA() throws Exception - { - testChunks(true, - false, - true, - false, - true, - false, - false, - true, - false, - 100, - 4, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testSendSmallMessageXA() throws Exception { + testChunks(true, false, true, false, true, false, false, true, false, 100, 4, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testSendSmallMessageXAConsumer() throws Exception - { - testChunks(true, - false, - true, - false, - true, - false, - false, - true, - true, - 100, - 4, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testSendSmallMessageXAConsumer() throws Exception { + testChunks(true, false, true, false, true, false, false, true, true, 100, 4, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testSendSmallMessageNullPersistenceXA() throws Exception - { - testChunks(true, - false, - true, - false, - false, - false, - false, - true, - false, - 100, - 100, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testSendSmallMessageNullPersistenceXA() throws Exception { + testChunks(true, false, true, false, false, false, false, true, false, 100, 100, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testSendSmallMessageNullPersistenceXAConsumer() throws Exception - { - testChunks(true, - false, - true, - false, - false, - false, - false, - true, - true, - 100, - 100, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testSendSmallMessageNullPersistenceXAConsumer() throws Exception { + testChunks(true, false, true, false, false, false, false, true, true, 100, 100, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testSendRegularMessageNullPersistenceDelayed() throws Exception - { - testChunks(false, - false, - true, - false, - false, - false, - false, - false, - false, - 100, - 100, - LargeMessageTest.RECEIVE_WAIT_TIME, - 1000); + public void testSendRegularMessageNullPersistenceDelayed() throws Exception { + testChunks(false, false, true, false, false, false, false, false, false, 100, 100, LargeMessageTest.RECEIVE_WAIT_TIME, 1000); } @Test - public void testSendRegularMessageNullPersistenceDelayedConsumer() throws Exception - { - testChunks(false, - false, - true, - false, - false, - false, - false, - false, - true, - 100, - 100, - LargeMessageTest.RECEIVE_WAIT_TIME, - 1000); + public void testSendRegularMessageNullPersistenceDelayedConsumer() throws Exception { + testChunks(false, false, true, false, false, false, false, false, true, 100, 100, LargeMessageTest.RECEIVE_WAIT_TIME, 1000); } @Test - public void testSendRegularMessageNullPersistenceDelayedXA() throws Exception - { - testChunks(true, - false, - true, - false, - false, - false, - false, - false, - false, - 100, - 100, - LargeMessageTest.RECEIVE_WAIT_TIME, - 1000); + public void testSendRegularMessageNullPersistenceDelayedXA() throws Exception { + testChunks(true, false, true, false, false, false, false, false, false, 100, 100, LargeMessageTest.RECEIVE_WAIT_TIME, 1000); } @Test - public void testSendRegularMessageNullPersistenceDelayedXAConsumer() throws Exception - { - testChunks(true, - false, - true, - false, - false, - false, - false, - false, - true, - 100, - 100, - LargeMessageTest.RECEIVE_WAIT_TIME, - 1000); + public void testSendRegularMessageNullPersistenceDelayedXAConsumer() throws Exception { + testChunks(true, false, true, false, false, false, false, false, true, 100, 100, LargeMessageTest.RECEIVE_WAIT_TIME, 1000); } @Test - public void testSendRegularMessagePersistence() throws Exception - { - testChunks(false, - false, - true, - false, - true, - false, - false, - true, - false, - 100, - 100, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testSendRegularMessagePersistence() throws Exception { + testChunks(false, false, true, false, true, false, false, true, false, 100, 100, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testSendRegularMessagePersistenceConsumer() throws Exception - { - testChunks(false, - false, - true, - false, - true, - false, - false, - true, - true, - 100, - 100, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testSendRegularMessagePersistenceConsumer() throws Exception { + testChunks(false, false, true, false, true, false, false, true, true, 100, 100, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testSendRegularMessagePersistenceXA() throws Exception - { - testChunks(true, - false, - true, - false, - true, - false, - false, - true, - false, - 100, - 100, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testSendRegularMessagePersistenceXA() throws Exception { + testChunks(true, false, true, false, true, false, false, true, false, 100, 100, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testSendRegularMessagePersistenceXAConsumer() throws Exception - { - testChunks(true, - false, - true, - false, - true, - false, - false, - true, - true, - 100, - 100, - LargeMessageTest.RECEIVE_WAIT_TIME, - 0); + public void testSendRegularMessagePersistenceXAConsumer() throws Exception { + testChunks(true, false, true, false, true, false, false, true, true, 100, 100, LargeMessageTest.RECEIVE_WAIT_TIME, 0); } @Test - public void testSendRegularMessagePersistenceDelayed() throws Exception - { - testChunks(false, - false, - true, - false, - true, - false, - false, - false, - false, - 100, - 100, - LargeMessageTest.RECEIVE_WAIT_TIME, - 1000); + public void testSendRegularMessagePersistenceDelayed() throws Exception { + testChunks(false, false, true, false, true, false, false, false, false, 100, 100, LargeMessageTest.RECEIVE_WAIT_TIME, 1000); } @Test - public void testSendRegularMessagePersistenceDelayedConsumer() throws Exception - { - testChunks(false, - false, - true, - false, - true, - false, - false, - false, - true, - 100, - 100, - LargeMessageTest.RECEIVE_WAIT_TIME, - 1000); + public void testSendRegularMessagePersistenceDelayedConsumer() throws Exception { + testChunks(false, false, true, false, true, false, false, false, true, 100, 100, LargeMessageTest.RECEIVE_WAIT_TIME, 1000); } @Test - public void testSendRegularMessagePersistenceDelayedXA() throws Exception - { - testChunks(false, - false, - true, - false, - true, - false, - false, - false, - false, - 100, - 100, - LargeMessageTest.RECEIVE_WAIT_TIME, - 1000); + public void testSendRegularMessagePersistenceDelayedXA() throws Exception { + testChunks(false, false, true, false, true, false, false, false, false, 100, 100, LargeMessageTest.RECEIVE_WAIT_TIME, 1000); } @Test - public void testSendRegularMessagePersistenceDelayedXAConsumer() throws Exception - { - testChunks(false, - false, - true, - false, - true, - false, - false, - false, - true, - 100, - 100, - LargeMessageTest.RECEIVE_WAIT_TIME, - 1000); + public void testSendRegularMessagePersistenceDelayedXAConsumer() throws Exception { + testChunks(false, false, true, false, true, false, false, false, true, 100, 100, LargeMessageTest.RECEIVE_WAIT_TIME, 1000); } @Test - public void testTwoBindingsTwoStartedConsumers() throws Exception - { + public void testTwoBindingsTwoStartedConsumers() throws Exception { // there are two bindings.. one is ACKed, the other is not, the server is restarted // The other binding is acked... The file must be deleted @@ -2146,19 +1397,16 @@ public class LargeMessageTest extends LargeMessageTestBase } @Test - public void testTwoBindingsAndRestart() throws Exception - { + public void testTwoBindingsAndRestart() throws Exception { testTwoBindings(true); } @Test - public void testTwoBindingsNoRestart() throws Exception - { + public void testTwoBindingsNoRestart() throws Exception { testTwoBindings(false); } - public void testTwoBindings(final boolean restart) throws Exception - { + public void testTwoBindings(final boolean restart) throws Exception { // there are two bindings.. one is ACKed, the other is not, the server is restarted // The other binding is acked... The file must be deleted ActiveMQServer server = createServer(true, isNetty()); @@ -2185,8 +1433,7 @@ public class LargeMessageTest extends LargeMessageTestBase readMessage(session, queue[1], numberOfBytes); - if (restart) - { + if (restart) { session.close(); server.stop(); @@ -2208,31 +1455,26 @@ public class LargeMessageTest extends LargeMessageTestBase } @Test - public void testSendRollbackXADurable() throws Exception - { + public void testSendRollbackXADurable() throws Exception { internalTestSendRollback(true, true); } @Test - public void testSendRollbackXANonDurable() throws Exception - { + public void testSendRollbackXANonDurable() throws Exception { internalTestSendRollback(true, false); } @Test - public void testSendRollbackDurable() throws Exception - { + public void testSendRollbackDurable() throws Exception { internalTestSendRollback(false, true); } @Test - public void testSendRollbackNonDurable() throws Exception - { + public void testSendRollbackNonDurable() throws Exception { internalTestSendRollback(false, false); } - private void internalTestSendRollback(final boolean isXA, final boolean durable) throws Exception - { + private void internalTestSendRollback(final boolean isXA, final boolean durable) throws Exception { ClientSession session = null; ActiveMQServer server = createServer(true, isNetty()); @@ -2247,8 +1489,7 @@ public class LargeMessageTest extends LargeMessageTestBase Xid xid = null; - if (isXA) - { + if (isXA) { xid = RandomUtil.randomXid(); session.start(xid, XAResource.TMNOFLAGS); } @@ -2257,13 +1498,11 @@ public class LargeMessageTest extends LargeMessageTestBase Message clientFile = createLargeClientMessageStreaming(session, 50000, durable); - for (int i = 0; i < 1; i++) - { + for (int i = 0; i < 1; i++) { producer.send(clientFile); } - if (isXA) - { + if (isXA) { session.end(xid, XAResource.TMSUCCESS); session.prepare(xid); session.close(); @@ -2274,8 +1513,7 @@ public class LargeMessageTest extends LargeMessageTestBase session.rollback(xid); } - else - { + else { session.rollback(); } @@ -2285,19 +1523,16 @@ public class LargeMessageTest extends LargeMessageTestBase } @Test - public void testSimpleRollback() throws Exception - { + public void testSimpleRollback() throws Exception { simpleRollbackInternalTest(false); } @Test - public void testSimpleRollbackXA() throws Exception - { + public void testSimpleRollbackXA() throws Exception { simpleRollbackInternalTest(true); } - public void simpleRollbackInternalTest(final boolean isXA) throws Exception - { + public void simpleRollbackInternalTest(final boolean isXA) throws Exception { // there are two bindings.. one is ACKed, the other is not, the server is restarted // The other binding is acked... The file must be deleted ActiveMQServer server = createServer(true, isNetty()); @@ -2310,8 +1545,7 @@ public class LargeMessageTest extends LargeMessageTestBase Xid xid = null; - if (isXA) - { + if (isXA) { xid = newXID(); session.start(xid, XAResource.TMNOFLAGS); } @@ -2326,23 +1560,20 @@ public class LargeMessageTest extends LargeMessageTestBase ClientConsumer consumer = session.createConsumer(ADDRESS); - for (int n = 0; n < 10; n++) - { + for (int n = 0; n < 10; n++) { Message clientFile = createLargeClientMessageStreaming(session, numberOfBytes, n % 2 == 0); producer.send(clientFile); Assert.assertNull(consumer.receiveImmediate()); - if (isXA) - { + if (isXA) { session.end(xid, XAResource.TMSUCCESS); session.rollback(xid); xid = newXID(); session.start(xid, XAResource.TMNOFLAGS); } - else - { + else { session.rollback(); } @@ -2352,20 +1583,17 @@ public class LargeMessageTest extends LargeMessageTestBase Assert.assertNull(consumer.receiveImmediate()); - if (isXA) - { + if (isXA) { session.end(xid, XAResource.TMSUCCESS); session.commit(xid, true); xid = newXID(); session.start(xid, XAResource.TMNOFLAGS); } - else - { + else { session.commit(); } - for (int i = 0; i < 2; i++) - { + for (int i = 0; i < 2; i++) { ClientMessage clientMessage = consumer.receive(5000); @@ -2375,32 +1603,26 @@ public class LargeMessageTest extends LargeMessageTestBase clientMessage.acknowledge(); - if (isXA) - { - if (i == 0) - { + if (isXA) { + if (i == 0) { session.end(xid, XAResource.TMSUCCESS); session.prepare(xid); session.rollback(xid); xid = newXID(); session.start(xid, XAResource.TMNOFLAGS); } - else - { + else { session.end(xid, XAResource.TMSUCCESS); session.commit(xid, true); xid = newXID(); session.start(xid, XAResource.TMNOFLAGS); } } - else - { - if (i == 0) - { + else { + if (i == 0) { session.rollback(); } - else - { + else { session.commit(); } } @@ -2413,22 +1635,19 @@ public class LargeMessageTest extends LargeMessageTestBase } @Test - public void testBufferMultipleLargeMessages() throws Exception - { + public void testBufferMultipleLargeMessages() throws Exception { ClientSession session = null; ActiveMQServer server = null; final int SIZE = 10 * 1024; final int NUMBER_OF_MESSAGES = 30; - try - { + try { server = createServer(true, isNetty()); server.start(); - locator.setMinLargeMessageSize(1024) - .setConsumerWindowSize(1024 * 1024); + locator.setMinLargeMessageSize(1024).setConsumerWindowSize(1024 * 1024); ClientSessionFactory sf = addSessionFactory(createSessionFactory(locator)); @@ -2438,8 +1657,7 @@ public class LargeMessageTest extends LargeMessageTestBase ClientProducer producer = session.createProducer(ADDRESS); - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { ClientMessage clientFile = session.createMessage(true); clientFile.setBodyInputStream(ActiveMQTestBase.createFakeLargeStream(SIZE)); producer.send(clientFile); @@ -2454,85 +1672,68 @@ public class LargeMessageTest extends LargeMessageTestBase // Wait the consumer to be complete with 10 messages before getting others long timeout = System.currentTimeMillis() + 10000; - while (consumer.getBufferSize() < NUMBER_OF_MESSAGES && timeout > System.currentTimeMillis()) - { + while (consumer.getBufferSize() < NUMBER_OF_MESSAGES && timeout > System.currentTimeMillis()) { Thread.sleep(10); } Assert.assertEquals(NUMBER_OF_MESSAGES, consumer.getBufferSize()); // Reads the messages, rollback.. read them again - for (int trans = 0; trans < 2; trans++) - { + for (int trans = 0; trans < 2; trans++) { - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { ClientMessage msg = consumer.receive(10000); Assert.assertNotNull(msg); // it will ignore the buffer (not read it) on the first try - if (trans == 0) - { - for (int byteRead = 0; byteRead < SIZE; byteRead++) - { + if (trans == 0) { + for (int byteRead = 0; byteRead < SIZE; byteRead++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(byteRead), msg.getBodyBuffer().readByte()); } } msg.acknowledge(); } - if (trans == 0) - { + if (trans == 0) { session.rollback(); } - else - { + else { session.commit(); } } - Assert.assertEquals(0, - ((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()).getDeliveringCount()); - Assert.assertEquals(0, - getMessageCount(((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()))); + Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()).getDeliveringCount()); + Assert.assertEquals(0, getMessageCount(((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()))); } - finally - { - try - { + finally { + try { session.close(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } - try - { + try { server.stop(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } } @Test - public void testReceiveMultipleMessages() throws Exception - { + public void testReceiveMultipleMessages() throws Exception { ClientSession session = null; ActiveMQServer server = null; final int SIZE = 10 * 1024; final int NUMBER_OF_MESSAGES = 1000; - try - { + try { server = createServer(true, isNetty()); server.start(); - locator.setMinLargeMessageSize(1024) - .setConsumerWindowSize(1024 * 1024); + locator.setMinLargeMessageSize(1024).setConsumerWindowSize(1024 * 1024); ClientSessionFactory sf = addSessionFactory(createSessionFactory(locator)); @@ -2542,8 +1743,7 @@ public class LargeMessageTest extends LargeMessageTestBase ClientProducer producer = session.createProducer(ADDRESS); - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { ClientMessage clientFile = session.createMessage(true); clientFile.setBodyInputStream(ActiveMQTestBase.createFakeLargeStream(SIZE)); producer.send(clientFile); @@ -2555,76 +1755,61 @@ public class LargeMessageTest extends LargeMessageTestBase session.start(); // Reads the messages, rollback.. read them again - for (int trans = 0; trans < 2; trans++) - { + for (int trans = 0; trans < 2; trans++) { ClientConsumerInternal consumer = (ClientConsumerInternal) session.createConsumer(ADDRESS); // Wait the consumer to be complete with 10 messages before getting others long timeout = System.currentTimeMillis() + 10000; - while (consumer.getBufferSize() < 10 && timeout > System.currentTimeMillis()) - { + while (consumer.getBufferSize() < 10 && timeout > System.currentTimeMillis()) { Thread.sleep(10); } - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { ClientMessage msg = consumer.receive(10000); Assert.assertNotNull(msg); // it will ignore the buffer (not read it) on the first try - if (trans == 0) - { - for (int byteRead = 0; byteRead < SIZE; byteRead++) - { + if (trans == 0) { + for (int byteRead = 0; byteRead < SIZE; byteRead++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(byteRead), msg.getBodyBuffer().readByte()); } } msg.acknowledge(); } - if (trans == 0) - { + if (trans == 0) { session.rollback(); } - else - { + else { session.commit(); } consumer.close(); } - Assert.assertEquals(0, - ((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()).getDeliveringCount()); - Assert.assertEquals(0, - getMessageCount(((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()))); + Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()).getDeliveringCount()); + Assert.assertEquals(0, getMessageCount(((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()))); } - finally - { - try - { + finally { + try { session.close(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } - try - { + try { server.stop(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } } // JBPAPP-6237 @Test - public void testPageOnLargeMessageMultipleQueues() throws Exception - { + public void testPageOnLargeMessageMultipleQueues() throws Exception { Configuration config = createDefaultConfig(isNetty()); final int PAGE_MAX = 20 * 1024; @@ -2642,9 +1827,7 @@ public class LargeMessageTest extends LargeMessageTestBase final int numberOfBytesBigMessage = 400000; - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); ClientSessionFactory sf = addSessionFactory(createSessionFactory(locator)); @@ -2657,16 +1840,14 @@ public class LargeMessageTest extends LargeMessageTestBase ClientMessage message = null; - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { message = session.createMessage(true); message.getBodyBuffer().writerIndex(0); message.getBodyBuffer().writeBytes(new byte[numberOfBytes]); - for (int j = 1; j <= numberOfBytes; j++) - { + for (int j = 1; j <= numberOfBytes; j++) { message.getBodyBuffer().writeInt(j); } @@ -2677,8 +1858,7 @@ public class LargeMessageTest extends LargeMessageTestBase clientFile.putBooleanProperty("TestLarge", true); producer.send(clientFile); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { message = session.createMessage(true); message.getBodyBuffer().writeBytes(new byte[numberOfBytes]); @@ -2695,16 +1875,14 @@ public class LargeMessageTest extends LargeMessageTestBase sf = createSessionFactory(locator); - for (int ad = 0; ad < 2; ad++) - { + for (int ad = 0; ad < 2; ad++) { session = sf.createSession(false, false, false); ClientConsumer consumer = session.createConsumer(ADDRESS.concat("-" + ad)); session.start(); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage message2 = consumer.receive(LargeMessageTest.RECEIVE_WAIT_TIME); Assert.assertNotNull(message2); @@ -2716,8 +1894,7 @@ public class LargeMessageTest extends LargeMessageTestBase session.commit(); - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { ClientMessage messageLarge = consumer.receive(RECEIVE_WAIT_TIME); assertTrue(messageLarge.getBooleanProperty("TestLarge")); @@ -2729,8 +1906,7 @@ public class LargeMessageTest extends LargeMessageTestBase messageLarge.saveToOutputStream(bout); byte[] body = bout.toByteArray(); assertEquals(numberOfBytesBigMessage, body.length); - for (int bi = 0; bi < body.length; bi++) - { + for (int bi = 0; bi < body.length; bi++) { assertEquals(getSamplebyte(bi), body[bi]); } @@ -2740,8 +1916,7 @@ public class LargeMessageTest extends LargeMessageTestBase session.commit(); } - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage message2 = consumer.receive(LargeMessageTest.RECEIVE_WAIT_TIME); Assert.assertNotNull(message2); @@ -2759,11 +1934,9 @@ public class LargeMessageTest extends LargeMessageTestBase } } - // JBPAPP-6237 @Test - public void testPageOnLargeMessageMultipleQueues2() throws Exception - { + public void testPageOnLargeMessageMultipleQueues2() throws Exception { Configuration config = createDefaultConfig(isNetty()); final int PAGE_MAX = 20 * 1024; @@ -2781,10 +1954,7 @@ public class LargeMessageTest extends LargeMessageTestBase final int numberOfBytesBigMessage = 400000; - locator.setBlockOnNonDurableSend(false) - .setBlockOnDurableSend(false) - .setBlockOnAcknowledge(false) - .setCompressLargeMessage(true); + locator.setBlockOnNonDurableSend(false).setBlockOnDurableSend(false).setBlockOnAcknowledge(false).setCompressLargeMessage(true); ClientSessionFactory sf = addSessionFactory(createSessionFactory(locator)); @@ -2796,8 +1966,7 @@ public class LargeMessageTest extends LargeMessageTestBase ClientProducer producer = session.createProducer(ADDRESS); int msgId = 0; - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage message = session.createMessage(true); message.putIntProperty("msgID", msgId++); @@ -2808,17 +1977,14 @@ public class LargeMessageTest extends LargeMessageTestBase message.getBodyBuffer().writeBytes(new byte[numberOfBytes]); - for (int j = 1; j <= numberOfBytes; j++) - { + for (int j = 1; j <= numberOfBytes; j++) { message.getBodyBuffer().writeInt(j); } producer.send(message); } - - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage clientFile = createLargeClientMessageStreaming(session, numberOfBytesBigMessage); clientFile.putBooleanProperty("TestLarge", true); producer.send(clientFile); @@ -2826,18 +1992,15 @@ public class LargeMessageTest extends LargeMessageTestBase session.close(); - for (int ad = 0; ad < 2; ad++) - { + for (int ad = 0; ad < 2; ad++) { session = sf.createSession(false, false, false); ClientConsumer consumer = session.createConsumer(ADDRESS.concat("-" + ad)); session.start(); - for (int received = 0; received < 5; received++) - { - for (int i = 0; i < 100; i++) - { + for (int received = 0; received < 5; received++) { + for (int i = 0; i < 100; i++) { ClientMessage message2 = consumer.receive(LargeMessageTest.RECEIVE_WAIT_TIME); Assert.assertNotNull(message2); @@ -2849,8 +2012,7 @@ public class LargeMessageTest extends LargeMessageTestBase Assert.assertNotNull(message2); } - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage messageLarge = consumer.receive(RECEIVE_WAIT_TIME); Assert.assertNotNull(messageLarge); @@ -2878,14 +2040,12 @@ public class LargeMessageTest extends LargeMessageTestBase } @Test - public void testSendStreamingSingleMessage() throws Exception - { + public void testSendStreamingSingleMessage() throws Exception { ClientSession session = null; ActiveMQServer server = null; final int SIZE = 10 * 1024 * 1024; - try - { + try { server = createServer(true, isNetty()); @@ -2924,28 +2084,21 @@ public class LargeMessageTest extends LargeMessageTestBase session.commit(); - Assert.assertEquals(0, - ((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()).getDeliveringCount()); - Assert.assertEquals(0, - getMessageCount(((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()))); + Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()).getDeliveringCount()); + Assert.assertEquals(0, getMessageCount(((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()))); } - finally - { - try - { + finally { + try { session.close(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } - try - { + try { server.stop(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } } @@ -2954,8 +2107,7 @@ public class LargeMessageTest extends LargeMessageTestBase * Receive messages but never reads them, leaving the buffer pending */ @Test - public void testIgnoreStreaming() throws Exception - { + public void testIgnoreStreaming() throws Exception { ClientSession session = null; ActiveMQServer server = null; @@ -2976,8 +2128,7 @@ public class LargeMessageTest extends LargeMessageTestBase ClientProducer producer = session.createProducer(ADDRESS); - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { ClientMessage msg = session.createMessage(true); msg.setBodyInputStream(ActiveMQTestBase.createFakeLargeStream(SIZE)); msg.putIntProperty(new SimpleString("key"), i); @@ -2996,8 +2147,7 @@ public class LargeMessageTest extends LargeMessageTestBase ClientConsumer consumer = session.createConsumer(ADDRESS); - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { ClientMessage msg = consumer.receive(50000); Assert.assertNotNull(msg); @@ -3010,18 +2160,15 @@ public class LargeMessageTest extends LargeMessageTestBase session.commit(); - Assert.assertEquals(0, - ((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()).getDeliveringCount()); - Assert.assertEquals(0, - getMessageCount(((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()))); + Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()).getDeliveringCount()); + Assert.assertEquals(0, getMessageCount(((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()))); log.debug("Thread done"); } // The ClientConsumer should be able to also send ServerLargeMessages as that's done by the CoreBridge @Test - public void testSendServerMessage() throws Exception - { + public void testSendServerMessage() throws Exception { ActiveMQServer server = createServer(true); server.start(); @@ -3030,13 +2177,11 @@ public class LargeMessageTest extends LargeMessageTestBase ClientSession session = sf.createSession(false, false); - LargeServerMessageImpl fileMessage = - new LargeServerMessageImpl((JournalStorageManager) server.getStorageManager()); + LargeServerMessageImpl fileMessage = new LargeServerMessageImpl((JournalStorageManager) server.getStorageManager()); fileMessage.setMessageID(1005); - for (int i = 0; i < LARGE_MESSAGE_SIZE; i++) - { + for (int i = 0; i < LARGE_MESSAGE_SIZE; i++) { fileMessage.addBytes(new byte[]{ActiveMQTestBase.getSamplebyte(i)}); } @@ -3065,8 +2210,7 @@ public class LargeMessageTest extends LargeMessageTestBase Assert.assertEquals(msg.getBodySize(), LARGE_MESSAGE_SIZE); - for (int i = 0; i < LARGE_MESSAGE_SIZE; i++) - { + for (int i = 0; i < LARGE_MESSAGE_SIZE; i++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg.getBodyBuffer().readByte()); } @@ -3081,14 +2225,12 @@ public class LargeMessageTest extends LargeMessageTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = createFactory(isNetty()); } - protected void testPageOnLargeMessage(final boolean realFiles, final boolean sendBlocking) throws Exception - { + protected void testPageOnLargeMessage(final boolean realFiles, final boolean sendBlocking) throws Exception { Configuration config = createDefaultConfig(isNetty()); final int PAGE_MAX = 20 * 1024; @@ -3108,11 +2250,8 @@ public class LargeMessageTest extends LargeMessageTestBase ClientSessionFactory sf = addSessionFactory(createSessionFactory(locator)); - if (sendBlocking) - { - sf.getServerLocator().setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + if (sendBlocking) { + sf.getServerLocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); } ClientSession session = sf.createSession(null, null, false, true, true, false, 0); @@ -3123,15 +2262,13 @@ public class LargeMessageTest extends LargeMessageTestBase ClientMessage message = null; - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { message = session.createMessage(true); // TODO: Why do I need to reset the writerIndex? message.getBodyBuffer().writerIndex(0); - for (int j = 1; j <= numberOfBytes; j++) - { + for (int j = 1; j <= numberOfBytes; j++) { message.getBodyBuffer().writeInt(j); } @@ -3144,8 +2281,7 @@ public class LargeMessageTest extends LargeMessageTestBase session.close(); - if (realFiles) - { + if (realFiles) { server.stop(); server = createServer(true, config, PAGE_SIZE, PAGE_MAX, map); @@ -3160,8 +2296,7 @@ public class LargeMessageTest extends LargeMessageTestBase session.start(); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage message2 = consumer.receive(LargeMessageTest.RECEIVE_WAIT_TIME); Assert.assertNotNull(message2); @@ -3172,8 +2307,7 @@ public class LargeMessageTest extends LargeMessageTestBase message.getBodyBuffer().readerIndex(0); - for (int j = 1; j <= numberOfBytes; j++) - { + for (int j = 1; j <= numberOfBytes; j++) { Assert.assertEquals(j, message.getBodyBuffer().readInt()); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/LibaioDependencyCheckTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/LibaioDependencyCheckTest.java index 9044b286a4..f54f509c65 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/LibaioDependencyCheckTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/LibaioDependencyCheckTest.java @@ -27,8 +27,7 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; * * This test should be placed on each one of the tests modules to make sure the library is loaded correctly. */ -public class LibaioDependencyCheckTest extends ActiveMQTestBase -{ +public class LibaioDependencyCheckTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -41,10 +40,8 @@ public class LibaioDependencyCheckTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testDependency() throws Exception - { - if (System.getProperties().get("os.name").equals("Linux")) - { + public void testDependency() throws Exception { + if (System.getProperties().get("os.name").equals("Linux")) { assertTrue("Libaio is not available on this platform", LibaioContext.isLoaded()); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageConcurrencyTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageConcurrencyTest.java index e5313d38f7..5cd6f58d5e 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageConcurrencyTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageConcurrencyTest.java @@ -36,8 +36,8 @@ import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; -public class MessageConcurrencyTest extends ActiveMQTestBase -{ +public class MessageConcurrencyTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private ActiveMQServer server; @@ -50,8 +50,7 @@ public class MessageConcurrencyTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(false); @@ -63,8 +62,7 @@ public class MessageConcurrencyTest extends ActiveMQTestBase // Test that a created message can be sent via multiple producers on different sessions concurrently @Test - public void testMessageConcurrency() throws Exception - { + public void testMessageConcurrency() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); ClientSession createSession = sf.createSession(); @@ -77,8 +75,7 @@ public class MessageConcurrencyTest extends ActiveMQTestBase final int numMessages = 1000; - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { ClientSession sendSession = sf.createSession(); sendSessions.add(sendSession); @@ -92,29 +89,25 @@ public class MessageConcurrencyTest extends ActiveMQTestBase sender.start(); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { byte[] body = RandomUtil.randomBytes(1000); ClientMessage message = createSession.createMessage(false); message.getBodyBuffer().writeBytes(body); - for (Sender sender : senders) - { + for (Sender sender : senders) { sender.queue.add(message); } } - for (Sender sender : senders) - { + for (Sender sender : senders) { sender.join(); assertFalse(sender.failed); } - for (ClientSession sendSession : sendSessions) - { + for (ClientSession sendSession : sendSessions) { sendSession.close(); } @@ -125,8 +118,7 @@ public class MessageConcurrencyTest extends ActiveMQTestBase // Test that a created message can be sent via multiple producers after being consumed from a single consumer @Test - public void testMessageConcurrencyAfterConsumption() throws Exception - { + public void testMessageConcurrencyAfterConsumption() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); ClientSession consumeSession = sf.createSession(); @@ -137,7 +129,6 @@ public class MessageConcurrencyTest extends ActiveMQTestBase ClientConsumer consumer = consumeSession.createConsumer(QUEUE_NAME); - consumeSession.start(); Set sendSessions = new HashSet(); @@ -148,8 +139,7 @@ public class MessageConcurrencyTest extends ActiveMQTestBase final int numMessages = 1000; - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { ClientSession sendSession = sf.createSession(); sendSessions.add(sendSession); @@ -163,19 +153,15 @@ public class MessageConcurrencyTest extends ActiveMQTestBase sender.start(); } - consumer.setMessageHandler(new MessageHandler() - { - public void onMessage(ClientMessage message) - { - for (Sender sender : senders) - { + consumer.setMessageHandler(new MessageHandler() { + public void onMessage(ClientMessage message) { + for (Sender sender : senders) { sender.queue.add(message); } } }); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { byte[] body = RandomUtil.randomBytes(1000); ClientMessage message = consumeSession.createMessage(false); @@ -185,15 +171,13 @@ public class MessageConcurrencyTest extends ActiveMQTestBase mainProducer.send(message); } - for (Sender sender : senders) - { + for (Sender sender : senders) { sender.join(); assertFalse(sender.failed); } - for (ClientSession sendSession : sendSessions) - { + for (ClientSession sendSession : sendSessions) { sendSession.close(); } @@ -206,16 +190,15 @@ public class MessageConcurrencyTest extends ActiveMQTestBase sf.close(); } - private class Sender extends Thread - { + private class Sender extends Thread { + private final BlockingQueue queue = new LinkedBlockingQueue(); private final ClientProducer producer; private final int numMessages; - Sender(final int numMessages, final ClientProducer producer) - { + Sender(final int numMessages, final ClientProducer producer) { this.numMessages = numMessages; this.producer = producer; @@ -223,19 +206,15 @@ public class MessageConcurrencyTest extends ActiveMQTestBase volatile boolean failed; - public void run() - { - try - { - for (int i = 0; i < numMessages; i++) - { + public void run() { + try { + for (int i = 0; i < numMessages; i++) { ClientMessage msg = queue.take(); producer.send(msg); } } - catch (Exception e) - { + catch (Exception e) { log.error("Failed to send message", e); failed = true; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageConsumerRollbackTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageConsumerRollbackTest.java index abf63dce0f..fb07dc8318 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageConsumerRollbackTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageConsumerRollbackTest.java @@ -35,8 +35,7 @@ import org.apache.activemq.artemis.jms.client.ActiveMQTextMessage; import org.junit.Before; import org.junit.Test; -public class MessageConsumerRollbackTest extends ActiveMQTestBase -{ +public class MessageConsumerRollbackTest extends ActiveMQTestBase { ActiveMQServer server; @@ -49,8 +48,7 @@ public class MessageConsumerRollbackTest extends ActiveMQTestBase private static final String outQueue = "outQueue"; @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(true, true); @@ -84,8 +82,7 @@ public class MessageConsumerRollbackTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testRollbackMultipleConsumers() throws Exception - { + public void testRollbackMultipleConsumers() throws Exception { int numberOfMessages = 3000; int numberOfConsumers = 10; @@ -99,30 +96,24 @@ public class MessageConsumerRollbackTest extends ActiveMQTestBase LocalConsumer[] consumers = new LocalConsumer[numberOfConsumers]; - for (int i = 0; i < numberOfConsumers; i++) - { + for (int i = 0; i < numberOfConsumers; i++) { consumers[i] = new LocalConsumer(count, commitLatch); consumers[i].start(); } - commitLatch.await(2, TimeUnit.MINUTES); - - for (LocalConsumer consumer : consumers) - { + for (LocalConsumer consumer : consumers) { consumer.stop(); } - ClientConsumer consumer = session.createConsumer(outQueue); session.start(); HashSet values = new HashSet(); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = consumer.receive(1000); assertNotNull(msg); int value = msg.getIntProperty("out_msg"); @@ -131,11 +122,9 @@ public class MessageConsumerRollbackTest extends ActiveMQTestBase values.add(value); } - assertNull(consumer.receiveImmediate()); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { assertTrue(values.contains(i)); } @@ -150,12 +139,10 @@ public class MessageConsumerRollbackTest extends ActiveMQTestBase * @param session * @throws Exception */ - private void sendMessages(int numberOfMessages, ClientSession session) throws Exception - { + private void sendMessages(int numberOfMessages, ClientSession session) throws Exception { ClientProducer producer = session.createProducer(inQueue); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ActiveMQTextMessage txt = new ActiveMQTextMessage(session); txt.setIntProperty("msg", i); txt.setText("Message Number (" + i + ")"); @@ -166,8 +153,7 @@ public class MessageConsumerRollbackTest extends ActiveMQTestBase session.commit(); } - private class LocalConsumer implements MessageHandler - { + private class LocalConsumer implements MessageHandler { // One of the tests will need this boolean rollbackFirstMessage = true; @@ -186,21 +172,18 @@ public class MessageConsumerRollbackTest extends ActiveMQTestBase CountDownLatch commitLatch; - public LocalConsumer(AtomicInteger counter, CountDownLatch commitLatch) - { + public LocalConsumer(AtomicInteger counter, CountDownLatch commitLatch) { this.counter = counter; this.commitLatch = commitLatch; } - public void stop() throws Exception - { + public void stop() throws Exception { session.close(); factoryLocator.close(); consumerLocator.close(); } - public void start() throws Exception - { + public void start() throws Exception { consumerLocator = createNettyNonHALocator(); factoryLocator = createSessionFactory(consumerLocator); @@ -216,11 +199,9 @@ public class MessageConsumerRollbackTest extends ActiveMQTestBase session.start(); } - public void onMessage(ClientMessage message) - { + public void onMessage(ClientMessage message) { - try - { + try { message.acknowledge(); ClientMessage outmsg = session.createMessage(true); @@ -229,34 +210,27 @@ public class MessageConsumerRollbackTest extends ActiveMQTestBase producer.send(outmsg); - - if (rollbackFirstMessage) - { + if (rollbackFirstMessage) { session.rollback(); rollbackFirstMessage = false; return; } - if (counter.incrementAndGet() % 200 == 0) - { + if (counter.incrementAndGet() % 200 == 0) { System.out.println("rollback " + message); session.rollback(); } - else - { + else { commitLatch.countDown(); session.commit(); } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); - try - { + try { session.rollback(); } - catch (Exception ignored) - { + catch (Exception ignored) { ignored.printStackTrace(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageCounterTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageCounterTest.java index d9a5c69238..a847b78d86 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageCounterTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageCounterTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.client; + import org.junit.Before; import org.junit.Test; @@ -31,8 +32,8 @@ import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -public class MessageCounterTest extends ActiveMQTestBase -{ +public class MessageCounterTest extends ActiveMQTestBase { + private ActiveMQServer server; private final SimpleString QUEUE = new SimpleString("ConsumerTestQueue"); @@ -41,8 +42,7 @@ public class MessageCounterTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(false); @@ -52,10 +52,8 @@ public class MessageCounterTest extends ActiveMQTestBase } @Test - public void testMessageCounter() throws Exception - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true); + public void testMessageCounter() throws Exception { + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true); ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(null, null, false, false, false, false, 0); @@ -66,8 +64,7 @@ public class MessageCounterTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); producer.send(message); } @@ -79,8 +76,7 @@ public class MessageCounterTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(QUEUE, null, false); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(1000); Assert.assertNotNull(message); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageDurabilityTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageDurabilityTest.java index 4df0e92943..101383d38d 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageDurabilityTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageDurabilityTest.java @@ -32,8 +32,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class MessageDurabilityTest extends ActiveMQTestBase -{ +public class MessageDurabilityTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -54,8 +53,7 @@ public class MessageDurabilityTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testNonDurableMessageOnNonDurableQueue() throws Exception - { + public void testNonDurableMessageOnNonDurableQueue() throws Exception { boolean durable = true; SimpleString address = RandomUtil.randomSimpleString(); @@ -69,23 +67,19 @@ public class MessageDurabilityTest extends ActiveMQTestBase restart(); session.start(); - try - { + try { session.createConsumer(queue); } - catch (ActiveMQNonExistentQueueException neqe) - { + catch (ActiveMQNonExistentQueueException neqe) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } } @Test - public void testNonDurableMessageOnDurableQueue() throws Exception - { + public void testNonDurableMessageOnDurableQueue() throws Exception { boolean durable = true; SimpleString address = RandomUtil.randomSimpleString(); @@ -107,8 +101,7 @@ public class MessageDurabilityTest extends ActiveMQTestBase } @Test - public void testDurableMessageOnDurableQueue() throws Exception - { + public void testDurableMessageOnDurableQueue() throws Exception { boolean durable = true; SimpleString address = RandomUtil.randomSimpleString(); @@ -133,8 +126,7 @@ public class MessageDurabilityTest extends ActiveMQTestBase * we can send a durable msg to a non durable queue but the msg won't be persisted */ @Test - public void testDurableMessageOnNonDurableQueue() throws Exception - { + public void testDurableMessageOnNonDurableQueue() throws Exception { boolean durable = true; SimpleString address = RandomUtil.randomSimpleString(); @@ -149,10 +141,8 @@ public class MessageDurabilityTest extends ActiveMQTestBase session.start(); - ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.QUEUE_DOES_NOT_EXIST, new ActiveMQAction() - { - public void run() throws ActiveMQException - { + ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.QUEUE_DOES_NOT_EXIST, new ActiveMQAction() { + public void run() throws ActiveMQException { session.createConsumer(queue); } }); @@ -162,8 +152,7 @@ public class MessageDurabilityTest extends ActiveMQTestBase * we can send a durable msg to a temp queue but the msg won't be persisted */ @Test - public void testDurableMessageOnTemporaryQueue() throws Exception - { + public void testDurableMessageOnTemporaryQueue() throws Exception { boolean durable = true; SimpleString address = RandomUtil.randomSimpleString(); @@ -177,10 +166,8 @@ public class MessageDurabilityTest extends ActiveMQTestBase restart(); session.start(); - ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.QUEUE_DOES_NOT_EXIST, new ActiveMQAction() - { - public void run() throws ActiveMQException - { + ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.QUEUE_DOES_NOT_EXIST, new ActiveMQAction() { + public void run() throws ActiveMQException { session.createConsumer(queue); } }); @@ -192,8 +179,7 @@ public class MessageDurabilityTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(true); @@ -205,8 +191,7 @@ public class MessageDurabilityTest extends ActiveMQTestBase // Private ------------------------------------------------------- - private void restart() throws Exception - { + private void restart() throws Exception { session.close(); server.stop(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageExpirationTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageExpirationTest.java index ce48671c61..f6525d91fc 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageExpirationTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageExpirationTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.client; + import org.junit.Before; import org.junit.Test; @@ -35,8 +36,7 @@ import org.apache.activemq.artemis.core.settings.impl.AddressSettings; import org.apache.activemq.artemis.tests.util.RandomUtil; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -public class MessageExpirationTest extends ActiveMQTestBase -{ +public class MessageExpirationTest extends ActiveMQTestBase { private static final int EXPIRATION = 1000; @@ -49,8 +49,7 @@ public class MessageExpirationTest extends ActiveMQTestBase private ServerLocator locator; @Test - public void testMessageExpiredWithoutExpiryAddress() throws Exception - { + public void testMessageExpiredWithoutExpiryAddress() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -74,14 +73,13 @@ public class MessageExpirationTest extends ActiveMQTestBase } @Test - public void testMessageExpiredWithoutExpiryAddressWithExpiryDelayOverride() throws Exception - { + public void testMessageExpiredWithoutExpiryAddressWithExpiryDelayOverride() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); session.close(); - session = addClientSession(sf.createSession(false, false, false)); + session = addClientSession(sf.createSession(false, false, false)); session.createQueue(address, queue, false); ClientProducer producer = session.createProducer(address); @@ -110,8 +108,6 @@ public class MessageExpirationTest extends ActiveMQTestBase // we receive the message and then rollback... then we wait some time > expiration, the message must be gone session.rollback(); - - Thread.sleep(MessageExpirationTest.EXPIRATION * 2); session.start(); @@ -133,8 +129,7 @@ public class MessageExpirationTest extends ActiveMQTestBase } @Test - public void testMessageExpirationOnServer() throws Exception - { + public void testMessageExpirationOnServer() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -152,8 +147,8 @@ public class MessageExpirationTest extends ActiveMQTestBase Thread.sleep(500); - Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(queue).getBindable()).getDeliveringCount()); - Assert.assertEquals(0, getMessageCount(((Queue)server.getPostOffice().getBinding(queue).getBindable()))); + Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(queue).getBindable()).getDeliveringCount()); + Assert.assertEquals(0, getMessageCount(((Queue) server.getPostOffice().getBinding(queue).getBindable()))); ClientMessage message2 = consumer.receiveImmediate(); Assert.assertNull(message2); @@ -163,8 +158,7 @@ public class MessageExpirationTest extends ActiveMQTestBase } @Test - public void testMessageExpirationOnClient() throws Exception - { + public void testMessageExpirationOnClient() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -183,28 +177,25 @@ public class MessageExpirationTest extends ActiveMQTestBase ClientMessage message2 = consumer.receiveImmediate(); Assert.assertNull(message2); - Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(queue).getBindable()).getDeliveringCount()); - Assert.assertEquals(0, getMessageCount(((Queue)server.getPostOffice().getBinding(queue).getBindable()))); + Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(queue).getBindable()).getDeliveringCount()); + Assert.assertEquals(0, getMessageCount(((Queue) server.getPostOffice().getBinding(queue).getBindable()))); consumer.close(); session.deleteQueue(queue); } @Test - public void testMessageExpiredWithExpiryAddress() throws Exception - { + public void testMessageExpiredWithExpiryAddress() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); final SimpleString expiryAddress = RandomUtil.randomSimpleString(); SimpleString expiryQueue = RandomUtil.randomSimpleString(); - server.getAddressSettingsRepository().addMatch(address.toString(), new AddressSettings() - { + server.getAddressSettingsRepository().addMatch(address.toString(), new AddressSettings() { private static final long serialVersionUID = -6476053400596299130L; @Override - public SimpleString getExpiryAddress() - { + public SimpleString getExpiryAddress() { return expiryAddress; } }); @@ -243,8 +234,7 @@ public class MessageExpirationTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(false); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageGroupingConnectionFactoryTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageGroupingConnectionFactoryTest.java index aeba169124..b468c981b1 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageGroupingConnectionFactoryTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageGroupingConnectionFactoryTest.java @@ -36,8 +36,8 @@ import java.util.ArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -public class MessageGroupingConnectionFactoryTest extends ActiveMQTestBase -{ +public class MessageGroupingConnectionFactoryTest extends ActiveMQTestBase { + private ActiveMQServer server; private ClientSession clientSession; @@ -45,27 +45,23 @@ public class MessageGroupingConnectionFactoryTest extends ActiveMQTestBase private final SimpleString qName = new SimpleString("MessageGroupingTestQueue"); @Test - public void testBasicGroupingUsingConnection() throws Exception - { + public void testBasicGroupingUsingConnection() throws Exception { doTestBasicGroupingUsingConnectionFactory(); } @Test - public void testBasicGroupingMultipleProducers() throws Exception - { + public void testBasicGroupingMultipleProducers() throws Exception { doTestBasicGroupingMultipleProducers(); } - private void doTestBasicGroupingUsingConnectionFactory() throws Exception - { + private void doTestBasicGroupingUsingConnectionFactory() throws Exception { ClientProducer clientProducer = clientSession.createProducer(qName); ClientConsumer consumer = clientSession.createConsumer(qName); ClientConsumer consumer2 = clientSession.createConsumer(qName); clientSession.start(); int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(clientSession, "m" + i); clientProducer.send(message); } @@ -81,8 +77,7 @@ public class MessageGroupingConnectionFactoryTest extends ActiveMQTestBase consumer2.close(); } - private void doTestBasicGroupingMultipleProducers() throws Exception - { + private void doTestBasicGroupingMultipleProducers() throws Exception { ClientProducer clientProducer = clientSession.createProducer(qName); ClientProducer clientProducer2 = clientSession.createProducer(qName); ClientProducer clientProducer3 = clientSession.createProducer(qName); @@ -91,8 +86,7 @@ public class MessageGroupingConnectionFactoryTest extends ActiveMQTestBase clientSession.start(); int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(clientSession, "m" + i); clientProducer.send(message); clientProducer2.send(message); @@ -112,43 +106,36 @@ public class MessageGroupingConnectionFactoryTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = addServer(ActiveMQServers.newActiveMQServer(createDefaultInVMConfig(), false)); server.start(); - ServerLocator locator = createInVMNonHALocator() - .setGroupID("grp1"); + ServerLocator locator = createInVMNonHALocator().setGroupID("grp1"); ClientSessionFactory sessionFactory = createSessionFactory(locator); clientSession = addClientSession(sessionFactory.createSession(false, true, true)); clientSession.createQueue(qName, qName, null, false); } - private static class DummyMessageHandler implements MessageHandler - { + private static class DummyMessageHandler implements MessageHandler { + ArrayList list = new ArrayList(); private final CountDownLatch latch; private final boolean acknowledge; - public DummyMessageHandler(final CountDownLatch latch, final boolean acknowledge) - { + public DummyMessageHandler(final CountDownLatch latch, final boolean acknowledge) { this.latch = latch; this.acknowledge = acknowledge; } - public void onMessage(final ClientMessage message) - { + public void onMessage(final ClientMessage message) { list.add(message); - if (acknowledge) - { - try - { + if (acknowledge) { + try { message.acknowledge(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { // ignore } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageGroupingTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageGroupingTest.java index 8b1b80b9c5..ab12ff2622 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageGroupingTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageGroupingTest.java @@ -43,8 +43,8 @@ import java.util.ArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -public class MessageGroupingTest extends ActiveMQTestBase -{ +public class MessageGroupingTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private ActiveMQServer server; @@ -57,57 +57,47 @@ public class MessageGroupingTest extends ActiveMQTestBase private ServerLocator locator; @Test - public void testBasicGrouping() throws Exception - { + public void testBasicGrouping() throws Exception { doTestBasicGrouping(); } @Test - public void testMultipleGrouping() throws Exception - { + public void testMultipleGrouping() throws Exception { doTestMultipleGrouping(); } @Test - public void testMultipleGroupingSingleConsumerWithDirectDelivery() throws Exception - { + public void testMultipleGroupingSingleConsumerWithDirectDelivery() throws Exception { doTestMultipleGroupingSingleConsumer(true); } @Test - public void testMultipleGroupingSingleConsumerWithoutDirectDelivery() throws Exception - { + public void testMultipleGroupingSingleConsumerWithoutDirectDelivery() throws Exception { doTestMultipleGroupingSingleConsumer(false); } @Test - public void testMultipleGroupingTXCommit() throws Exception - { + public void testMultipleGroupingTXCommit() throws Exception { doTestMultipleGroupingTXCommit(); } @Test - public void testMultipleGroupingTXRollback() throws Exception - { + public void testMultipleGroupingTXRollback() throws Exception { doTestMultipleGroupingTXRollback(); } @Test - public void testMultipleGroupingXACommit() throws Exception - { + public void testMultipleGroupingXACommit() throws Exception { dotestMultipleGroupingXACommit(); } @Test - public void testMultipleGroupingXARollback() throws Exception - { + public void testMultipleGroupingXARollback() throws Exception { doTestMultipleGroupingXARollback(); } - @Test - public void testLoadBalanceGroups() throws Exception - { + public void testLoadBalanceGroups() throws Exception { Assume.assumeFalse("only makes sense withOUT auto-group", clientSessionFactory.getServerLocator().isAutoGroup()); ClientProducer clientProducer = clientSession.createProducer(qName); @@ -118,49 +108,39 @@ public class MessageGroupingTest extends ActiveMQTestBase int[] counts = new int[consumers.length]; clientSession.start(); - try - { + try { //Add all messages for a particular group before moving onto the next - for (int group = 0; group < 10; group++) - { - for (int messageId = 0; messageId < 3; messageId++) - { + for (int group = 0; group < 10; group++) { + for (int messageId = 0; messageId < 3; messageId++) { ClientMessage message = clientSession.createMessage(false); message.putStringProperty("_AMQ_GROUP_ID", "" + group); clientProducer.send(message); } } - for (int c = 0; c < consumers.length; c++) - { - while (true) - { + for (int c = 0; c < consumers.length; c++) { + while (true) { ClientMessage msg = consumers[c].receiveImmediate(); - if (msg == null) - { + if (msg == null) { break; } counts[c]++; } } - for (int count : counts) - { + for (int count : counts) { Assert.assertNotEquals("You shouldn't have all messages bound to a single consumer", 30, count); Assert.assertNotEquals("But you shouldn't have also a single consumer bound to none", 0, count); } } - finally - { + finally { consumer1.close(); consumer2.close(); consumer3.close(); } } - - private void doTestBasicGrouping() throws Exception - { + private void doTestBasicGrouping() throws Exception { ClientProducer clientProducer = clientSession.createProducer(qName); ClientConsumer consumer = clientSession.createConsumer(qName); ClientConsumer consumer2 = clientSession.createConsumer(qName); @@ -168,8 +148,7 @@ public class MessageGroupingTest extends ActiveMQTestBase SimpleString groupId = new SimpleString("grp1"); int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(clientSession, "m" + i); message.putStringProperty(Message.HDR_GROUP_ID, groupId); clientProducer.send(message); @@ -188,8 +167,7 @@ public class MessageGroupingTest extends ActiveMQTestBase } @Test - public void testMultipleGroupingConsumeHalf() throws Exception - { + public void testMultipleGroupingConsumeHalf() throws Exception { ClientProducer clientProducer = clientSession.createProducer(qName); ClientConsumer consumer = clientSession.createConsumer(qName); ClientConsumer consumer2 = clientSession.createConsumer(qName); @@ -201,22 +179,18 @@ public class MessageGroupingTest extends ActiveMQTestBase SimpleString groupId = new SimpleString("grp1"); SimpleString groupId2 = new SimpleString("grp2"); int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(clientSession, "m" + i); - if (i % 2 == 0 || i == 0) - { + if (i % 2 == 0 || i == 0) { message.putStringProperty(Message.HDR_GROUP_ID, groupId); } - else - { + else { message.putStringProperty(Message.HDR_GROUP_ID, groupId2); } clientProducer.send(message); } - for (int i = 0; i < numMessages / 2; i++) - { + for (int i = 0; i < numMessages / 2; i++) { ClientMessage cm = consumer.receive(500); Assert.assertNotNull(cm); Assert.assertEquals(cm.getBodyBuffer().readString(), "m" + i); @@ -233,32 +207,26 @@ public class MessageGroupingTest extends ActiveMQTestBase consumer.close(); } - private void doTestMultipleGroupingSingleConsumer(final boolean directDelivery) throws Exception - { + private void doTestMultipleGroupingSingleConsumer(final boolean directDelivery) throws Exception { ClientProducer clientProducer = clientSession.createProducer(qName); ClientConsumer consumer = clientSession.createConsumer(qName); - if (directDelivery) - { + if (directDelivery) { clientSession.start(); } SimpleString groupId = new SimpleString("grp1"); SimpleString groupId2 = new SimpleString("grp2"); int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(clientSession, "m" + i); - if (i % 2 == 0 || i == 0) - { + if (i % 2 == 0 || i == 0) { message.putStringProperty(Message.HDR_GROUP_ID, groupId); } - else - { + else { message.putStringProperty(Message.HDR_GROUP_ID, groupId2); } clientProducer.send(message); } - if (!directDelivery) - { + if (!directDelivery) { clientSession.start(); } CountDownLatch latch = new CountDownLatch(numMessages); @@ -267,16 +235,14 @@ public class MessageGroupingTest extends ActiveMQTestBase Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); Assert.assertEquals(dummyMessageHandler.list.size(), 100); int i = 0; - for (ClientMessage message : dummyMessageHandler.list) - { + for (ClientMessage message : dummyMessageHandler.list) { Assert.assertEquals(message.getBodyBuffer().readString(), "m" + i); i += 1; } consumer.close(); } - private void doTestMultipleGroupingTXCommit() throws Exception - { + private void doTestMultipleGroupingTXCommit() throws Exception { ServerLocator locator = createInVMNonHALocator(); ClientSessionFactory sessionFactory = createSessionFactory(locator); ClientSession clientSession = sessionFactory.createSession(false, false, false); @@ -292,15 +258,12 @@ public class MessageGroupingTest extends ActiveMQTestBase SimpleString groupId = new SimpleString("grp1"); SimpleString groupId2 = new SimpleString("grp2"); int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(clientSession, "m" + i); - if (i % 2 == 0 || i == 0) - { + if (i % 2 == 0 || i == 0) { message.putStringProperty(Message.HDR_GROUP_ID, groupId); } - else - { + else { message.putStringProperty(Message.HDR_GROUP_ID, groupId2); } clientProducer.send(message); @@ -315,15 +278,13 @@ public class MessageGroupingTest extends ActiveMQTestBase clientSession.commit(); Assert.assertEquals(dummyMessageHandler.list.size(), 50); int i = 0; - for (ClientMessage message : dummyMessageHandler.list) - { + for (ClientMessage message : dummyMessageHandler.list) { Assert.assertEquals(message.getBodyBuffer().readString(), "m" + i); i += 2; } Assert.assertEquals(dummyMessageHandler2.list.size(), 50); i = 1; - for (ClientMessage message : dummyMessageHandler2.list) - { + for (ClientMessage message : dummyMessageHandler2.list) { Assert.assertEquals(message.getBodyBuffer().readString(), "m" + i); i += 2; } @@ -335,8 +296,7 @@ public class MessageGroupingTest extends ActiveMQTestBase locator.close(); } - private void doTestMultipleGroupingTXRollback() throws Exception - { + private void doTestMultipleGroupingTXRollback() throws Exception { log.info("*** starting test"); ServerLocator locator = createInVMNonHALocator(); locator.setBlockOnAcknowledge(true); @@ -353,15 +313,12 @@ public class MessageGroupingTest extends ActiveMQTestBase SimpleString groupId = new SimpleString("grp1"); SimpleString groupId2 = new SimpleString("grp2"); int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(clientSession, "m" + i); - if (i % 2 == 0 || i == 0) - { + if (i % 2 == 0 || i == 0) { message.putStringProperty(Message.HDR_GROUP_ID, groupId); } - else - { + else { message.putStringProperty(Message.HDR_GROUP_ID, groupId2); } clientProducer.send(message); @@ -375,15 +332,13 @@ public class MessageGroupingTest extends ActiveMQTestBase Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); Assert.assertEquals(50, dummyMessageHandler.list.size(), dummyMessageHandler.list.size()); int i = 0; - for (ClientMessage message : dummyMessageHandler.list) - { + for (ClientMessage message : dummyMessageHandler.list) { Assert.assertEquals(message.getBodyBuffer().readString(), "m" + i); i += 2; } Assert.assertEquals(dummyMessageHandler2.list.size(), 50); i = 1; - for (ClientMessage message : dummyMessageHandler2.list) - { + for (ClientMessage message : dummyMessageHandler2.list) { Assert.assertEquals(message.getBodyBuffer().readString(), "m" + i); i += 2; } @@ -394,15 +349,13 @@ public class MessageGroupingTest extends ActiveMQTestBase Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); Assert.assertEquals(dummyMessageHandler.list.size(), 50); i = 0; - for (ClientMessage message : dummyMessageHandler.list) - { + for (ClientMessage message : dummyMessageHandler.list) { Assert.assertEquals(message.getBodyBuffer().readString(), "m" + i); i += 2; } Assert.assertEquals(dummyMessageHandler2.list.size(), 50); i = 1; - for (ClientMessage message : dummyMessageHandler2.list) - { + for (ClientMessage message : dummyMessageHandler2.list) { Assert.assertEquals(message.getBodyBuffer().readString(), "m" + i); i += 2; } @@ -412,8 +365,7 @@ public class MessageGroupingTest extends ActiveMQTestBase locator.close(); } - private void dotestMultipleGroupingXACommit() throws Exception - { + private void dotestMultipleGroupingXACommit() throws Exception { ServerLocator locator = createInVMNonHALocator(); ClientSessionFactory sessionFactory = createSessionFactory(locator); ClientSession clientSession = sessionFactory.createSession(true, false, false); @@ -428,15 +380,12 @@ public class MessageGroupingTest extends ActiveMQTestBase SimpleString groupId = new SimpleString("grp1"); SimpleString groupId2 = new SimpleString("grp2"); int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(clientSession, "m" + i); - if (i % 2 == 0 || i == 0) - { + if (i % 2 == 0 || i == 0) { message.putStringProperty(Message.HDR_GROUP_ID, groupId); } - else - { + else { message.putStringProperty(Message.HDR_GROUP_ID, groupId2); } clientProducer.send(message); @@ -452,15 +401,13 @@ public class MessageGroupingTest extends ActiveMQTestBase clientSession.commit(xid, false); Assert.assertEquals(dummyMessageHandler.list.size(), 50); int i = 0; - for (ClientMessage message : dummyMessageHandler.list) - { + for (ClientMessage message : dummyMessageHandler.list) { Assert.assertEquals(message.getBodyBuffer().readString(), "m" + i); i += 2; } Assert.assertEquals(dummyMessageHandler2.list.size(), 50); i = 1; - for (ClientMessage message : dummyMessageHandler2.list) - { + for (ClientMessage message : dummyMessageHandler2.list) { Assert.assertEquals(message.getBodyBuffer().readString(), "m" + i); i += 2; } @@ -472,8 +419,7 @@ public class MessageGroupingTest extends ActiveMQTestBase locator.close(); } - private void doTestMultipleGroupingXARollback() throws Exception - { + private void doTestMultipleGroupingXARollback() throws Exception { ServerLocator locator = createInVMNonHALocator(); locator.setBlockOnAcknowledge(true); ClientSessionFactory sessionFactory = createSessionFactory(locator); @@ -489,15 +435,12 @@ public class MessageGroupingTest extends ActiveMQTestBase SimpleString groupId = new SimpleString("grp1"); SimpleString groupId2 = new SimpleString("grp2"); int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(clientSession, "m" + i); - if (i % 2 == 0 || i == 0) - { + if (i % 2 == 0 || i == 0) { message.putStringProperty(Message.HDR_GROUP_ID, groupId); } - else - { + else { message.putStringProperty(Message.HDR_GROUP_ID, groupId2); } clientProducer.send(message); @@ -512,15 +455,13 @@ public class MessageGroupingTest extends ActiveMQTestBase clientSession.end(xid, XAResource.TMSUCCESS); Assert.assertEquals(dummyMessageHandler.list.size(), 50); int i = 0; - for (ClientMessage message : dummyMessageHandler.list) - { + for (ClientMessage message : dummyMessageHandler.list) { Assert.assertEquals(message.getBodyBuffer().readString(), "m" + i); i += 2; } Assert.assertEquals(dummyMessageHandler2.list.size(), 50); i = 1; - for (ClientMessage message : dummyMessageHandler2.list) - { + for (ClientMessage message : dummyMessageHandler2.list) { Assert.assertEquals(message.getBodyBuffer().readString(), "m" + i); i += 2; } @@ -535,15 +476,13 @@ public class MessageGroupingTest extends ActiveMQTestBase clientSession.commit(xid, false); Assert.assertEquals(dummyMessageHandler.list.size(), 50); i = 0; - for (ClientMessage message : dummyMessageHandler.list) - { + for (ClientMessage message : dummyMessageHandler.list) { Assert.assertEquals(message.getBodyBuffer().readString(), "m" + i); i += 2; } Assert.assertEquals(dummyMessageHandler2.list.size(), 50); i = 1; - for (ClientMessage message : dummyMessageHandler2.list) - { + for (ClientMessage message : dummyMessageHandler2.list) { Assert.assertEquals(message.getBodyBuffer().readString(), "m" + i); i += 2; } @@ -553,8 +492,7 @@ public class MessageGroupingTest extends ActiveMQTestBase locator.close(); } - private void doTestMultipleGrouping() throws Exception - { + private void doTestMultipleGrouping() throws Exception { ClientProducer clientProducer = clientSession.createProducer(qName); ClientConsumer consumer = clientSession.createConsumer(qName); ClientConsumer consumer2 = clientSession.createConsumer(qName); @@ -563,15 +501,12 @@ public class MessageGroupingTest extends ActiveMQTestBase SimpleString groupId = new SimpleString("grp1"); SimpleString groupId2 = new SimpleString("grp2"); int numMessages = 4; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(clientSession, "m" + i); - if (i % 2 == 0 || i == 0) - { + if (i % 2 == 0 || i == 0) { message.putStringProperty(Message.HDR_GROUP_ID, groupId); } - else - { + else { message.putStringProperty(Message.HDR_GROUP_ID, groupId2); } clientProducer.send(message); @@ -585,15 +520,13 @@ public class MessageGroupingTest extends ActiveMQTestBase Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); Assert.assertEquals(numMessages / 2, dummyMessageHandler.list.size()); int i = 0; - for (ClientMessage message : dummyMessageHandler.list) - { + for (ClientMessage message : dummyMessageHandler.list) { Assert.assertEquals(message.getBodyBuffer().readString(), "m" + i); i += 2; } Assert.assertEquals(numMessages / 2, dummyMessageHandler2.list.size()); i = 1; - for (ClientMessage message : dummyMessageHandler2.list) - { + for (ClientMessage message : dummyMessageHandler2.list) { Assert.assertEquals(message.getBodyBuffer().readString(), "m" + i); i += 2; } @@ -603,8 +536,7 @@ public class MessageGroupingTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); Configuration configuration = createDefaultInVMConfig(); server = addServer(ActiveMQServers.newActiveMQServer(configuration, false)); @@ -615,39 +547,33 @@ public class MessageGroupingTest extends ActiveMQTestBase clientSession.createQueue(qName, qName, null, false); } - private static class DummyMessageHandler implements MessageHandler - { + private static class DummyMessageHandler implements MessageHandler { + ArrayList list = new ArrayList(); private CountDownLatch latch; private final boolean acknowledge; - public DummyMessageHandler(final CountDownLatch latch, final boolean acknowledge) - { + public DummyMessageHandler(final CountDownLatch latch, final boolean acknowledge) { this.latch = latch; this.acknowledge = acknowledge; } - public void onMessage(final ClientMessage message) - { + public void onMessage(final ClientMessage message) { list.add(message); - if (acknowledge) - { - try - { + if (acknowledge) { + try { message.acknowledge(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { // ignore } } latch.countDown(); } - public void reset(final CountDownLatch latch) - { + public void reset(final CountDownLatch latch) { list.clear(); this.latch = latch; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageHandlerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageHandlerTest.java index aeb280310a..66aad72550 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageHandlerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageHandlerTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.client; + import org.junit.Before; import org.junit.Test; @@ -36,8 +37,8 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -public class MessageHandlerTest extends ActiveMQTestBase -{ +public class MessageHandlerTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private ActiveMQServer server; @@ -50,8 +51,7 @@ public class MessageHandlerTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(false); @@ -64,8 +64,7 @@ public class MessageHandlerTest extends ActiveMQTestBase } @Test - public void testSetMessageHandlerWithMessagesPending() throws Exception - { + public void testSetMessageHandlerWithMessagesPending() throws Exception { ClientSession session = sf.createSession(false, true, true); session.createQueue(QUEUE, QUEUE, null, false); @@ -74,8 +73,7 @@ public class MessageHandlerTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); producer.send(message); } @@ -88,18 +86,15 @@ public class MessageHandlerTest extends ActiveMQTestBase // Message should be in consumer - class MyHandler implements MessageHandler - { - public void onMessage(final ClientMessage message) - { - try - { + class MyHandler implements MessageHandler { + + public void onMessage(final ClientMessage message) { + try { Thread.sleep(10); message.acknowledge(); } - catch (Exception e) - { + catch (Exception e) { } } } @@ -124,8 +119,7 @@ public class MessageHandlerTest extends ActiveMQTestBase } @Test - public void testSetResetMessageHandler() throws Exception - { + public void testSetResetMessageHandler() throws Exception { final ClientSession session = sf.createSession(false, true, true); session.createQueue(QUEUE, QUEUE, null, false); @@ -134,8 +128,7 @@ public class MessageHandlerTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); message.putIntProperty(new SimpleString("i"), i); @@ -149,8 +142,8 @@ public class MessageHandlerTest extends ActiveMQTestBase // Message should be in consumer - class MyHandler implements MessageHandler - { + class MyHandler implements MessageHandler { + int messageReceived = 0; boolean failed; @@ -159,18 +152,14 @@ public class MessageHandlerTest extends ActiveMQTestBase private final CountDownLatch latch; - public MyHandler(final CountDownLatch latch) - { + public MyHandler(final CountDownLatch latch) { this.latch = latch; } - public void onMessage(final ClientMessage message) - { + public void onMessage(final ClientMessage message) { - try - { - if (!started) - { + try { + if (!started) { failed = true; } @@ -180,8 +169,7 @@ public class MessageHandlerTest extends ActiveMQTestBase latch.countDown(); - if (latch.getCount() == 0) - { + if (latch.getCount() == 0) { message.acknowledge(); started = false; @@ -190,8 +178,7 @@ public class MessageHandlerTest extends ActiveMQTestBase } } - catch (Exception e) - { + catch (Exception e) { } } } @@ -202,7 +189,6 @@ public class MessageHandlerTest extends ActiveMQTestBase session.start(); - waitForLatch(latch); Thread.sleep(100); @@ -225,8 +211,7 @@ public class MessageHandlerTest extends ActiveMQTestBase } @Test - public void testSetUnsetMessageHandler() throws Exception - { + public void testSetUnsetMessageHandler() throws Exception { final ClientSession session = sf.createSession(false, true, true); session.createQueue(QUEUE, QUEUE, null, false); @@ -235,8 +220,7 @@ public class MessageHandlerTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); message.putIntProperty(new SimpleString("i"), i); producer.send(message); @@ -250,8 +234,8 @@ public class MessageHandlerTest extends ActiveMQTestBase // Message should be in consumer - class MyHandler implements MessageHandler - { + class MyHandler implements MessageHandler { + int messageReceived = 0; boolean failed; @@ -260,25 +244,20 @@ public class MessageHandlerTest extends ActiveMQTestBase private final CountDownLatch latch; - public MyHandler(final CountDownLatch latch) - { + public MyHandler(final CountDownLatch latch) { this.latch = latch; } - public void onMessage(final ClientMessage message) - { + public void onMessage(final ClientMessage message) { - try - { - if (!started) - { + try { + if (!started) { failed = true; } messageReceived++; latch.countDown(); - if (latch.getCount() == 0) - { + if (latch.getCount() == 0) { message.acknowledge(); started = false; @@ -286,8 +265,7 @@ public class MessageHandlerTest extends ActiveMQTestBase } } - catch (Exception e) - { + catch (Exception e) { } } } @@ -312,8 +290,7 @@ public class MessageHandlerTest extends ActiveMQTestBase } @Test - public void testSetUnsetResetMessageHandler() throws Exception - { + public void testSetUnsetResetMessageHandler() throws Exception { final ClientSession session = sf.createSession(false, true, true); session.createQueue(QUEUE, QUEUE, null, false); @@ -322,8 +299,7 @@ public class MessageHandlerTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); message.putIntProperty(new SimpleString("i"), i); producer.send(message); @@ -337,8 +313,8 @@ public class MessageHandlerTest extends ActiveMQTestBase // Message should be in consumer - class MyHandler implements MessageHandler - { + class MyHandler implements MessageHandler { + int messageReceived = 0; boolean failed; @@ -347,25 +323,20 @@ public class MessageHandlerTest extends ActiveMQTestBase private final CountDownLatch latch; - public MyHandler(final CountDownLatch latch) - { + public MyHandler(final CountDownLatch latch) { this.latch = latch; } - public void onMessage(final ClientMessage message) - { + public void onMessage(final ClientMessage message) { - try - { - if (!started) - { + try { + if (!started) { failed = true; } messageReceived++; latch.countDown(); - if (latch.getCount() == 0) - { + if (latch.getCount() == 0) { message.acknowledge(); started = false; @@ -373,8 +344,7 @@ public class MessageHandlerTest extends ActiveMQTestBase } } - catch (Exception e) - { + catch (Exception e) { } } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessagePriorityTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessagePriorityTest.java index f4e5495c0d..f7b5f24a0e 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessagePriorityTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessagePriorityTest.java @@ -33,14 +33,12 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class MessagePriorityTest extends ActiveMQTestBase -{ +public class MessagePriorityTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; - // Attributes ---------------------------------------------------- private ActiveMQServer server; @@ -57,8 +55,7 @@ public class MessagePriorityTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testMessagePriority() throws Exception - { + public void testMessagePriority() throws Exception { SimpleString queue = RandomUtil.randomSimpleString(); SimpleString address = RandomUtil.randomSimpleString(); @@ -66,8 +63,7 @@ public class MessagePriorityTest extends ActiveMQTestBase ClientProducer producer = session.createProducer(address); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage m = createTextMessage(session, Integer.toString(i)); m.setPriority((byte) i); producer.send(m); @@ -78,8 +74,7 @@ public class MessagePriorityTest extends ActiveMQTestBase session.start(); // expect to consumer message with higher priority first - for (int i = 9; i >= 0; i--) - { + for (int i = 9; i >= 0; i--) { ClientMessage m = consumer.receive(500); Assert.assertNotNull(m); Assert.assertEquals(i, m.getPriority()); @@ -96,8 +91,7 @@ public class MessagePriorityTest extends ActiveMQTestBase * We need to implement client-side message priority to handle this case: https://jira.jboss.org/jira/browse/JBMESSAGING-1560 */ @Test - public void testMessagePriorityWithClientSidePrioritization() throws Exception - { + public void testMessagePriorityWithClientSidePrioritization() throws Exception { SimpleString queue = RandomUtil.randomSimpleString(); SimpleString address = RandomUtil.randomSimpleString(); @@ -109,8 +103,7 @@ public class MessagePriorityTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(queue); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage m = createTextMessage(session, Integer.toString(i)); m.setPriority((byte) i); producer.send(m); @@ -121,8 +114,7 @@ public class MessagePriorityTest extends ActiveMQTestBase Thread.sleep(1000); // expect to consume message with higher priority first - for (int i = 9; i >= 0; i--) - { + for (int i = 9; i >= 0; i--) { ClientMessage m = consumer.receive(500); log.info("received msg " + m.getPriority()); @@ -136,8 +128,7 @@ public class MessagePriorityTest extends ActiveMQTestBase } @Test - public void testMessageOrderWithSamePriority() throws Exception - { + public void testMessageOrderWithSamePriority() throws Exception { SimpleString queue = RandomUtil.randomSimpleString(); SimpleString address = RandomUtil.randomSimpleString(); @@ -175,8 +166,7 @@ public class MessagePriorityTest extends ActiveMQTestBase messages[9] = createTextMessage(session, "j"); messages[9].setPriority((byte) 9); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { producer.send(messages[i]); } @@ -206,8 +196,7 @@ public class MessagePriorityTest extends ActiveMQTestBase // https://jira.jboss.org/jira/browse/HORNETQ-275 @Test - public void testOutOfOrderAcknowledgement() throws Exception - { + public void testOutOfOrderAcknowledgement() throws Exception { SimpleString queue = RandomUtil.randomSimpleString(); SimpleString address = RandomUtil.randomSimpleString(); @@ -219,8 +208,7 @@ public class MessagePriorityTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage m = createTextMessage(session, Integer.toString(i)); m.setPriority((byte) i); producer.send(m); @@ -252,8 +240,7 @@ public class MessagePriorityTest extends ActiveMQTestBase // then if received in priority order, and acked // the ack would ack all messages up to the one received - resulting in acking // messages that hadn't been delivered yet - for (int i = 8; i >= 0; i--) - { + for (int i = 8; i >= 0; i--) { m = consumer.receive(500); Assert.assertNotNull(m); Assert.assertEquals(i, m.getPriority()); @@ -266,10 +253,8 @@ public class MessagePriorityTest extends ActiveMQTestBase session.deleteQueue(queue); } - @Test - public void testManyMessages() throws Exception - { + public void testManyMessages() throws Exception { SimpleString queue = RandomUtil.randomSimpleString(); SimpleString address = RandomUtil.randomSimpleString(); @@ -277,16 +262,14 @@ public class MessagePriorityTest extends ActiveMQTestBase ClientProducer producer = session.createProducer(address); - for (int i = 0; i < 777; i++) - { + for (int i = 0; i < 777; i++) { ClientMessage msg = session.createMessage(true); msg.setPriority((byte) 5); msg.putBooleanProperty("fast", false); producer.send(msg); } - for (int i = 0; i < 333; i++) - { + for (int i = 0; i < 333; i++) { ClientMessage msg = session.createMessage(true); msg.setPriority((byte) 6); msg.putBooleanProperty("fast", true); @@ -297,17 +280,14 @@ public class MessagePriorityTest extends ActiveMQTestBase session.start(); - - for (int i = 0; i < 333; i++) - { + for (int i = 0; i < 333; i++) { ClientMessage msg = consumer.receive(5000); assertNotNull(msg); msg.acknowledge(); assertTrue(msg.getBooleanProperty("fast")); } - for (int i = 0; i < 777; i++) - { + for (int i = 0; i < 777; i++) { ClientMessage msg = consumer.receive(5000); assertNotNull(msg); msg.acknowledge(); @@ -321,22 +301,18 @@ public class MessagePriorityTest extends ActiveMQTestBase session.close(); } - // Package protected --------------------------------------------- // Protected ----------------------------------------------------- @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); Configuration config = createDefaultInVMConfig(); server = addServer(ActiveMQServers.newActiveMQServer(config, false)); server.start(); - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true); + locator = createInVMNonHALocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true); sf = createSessionFactory(locator); session = addClientSession(sf.createSession(false, true, true)); } @@ -345,8 +321,7 @@ public class MessagePriorityTest extends ActiveMQTestBase private static void expectMessage(final byte expectedPriority, final String expectedStringInBody, - final ClientConsumer consumer) throws Exception - { + final ClientConsumer consumer) throws Exception { ClientMessage m = consumer.receive(500); Assert.assertNotNull(m); Assert.assertEquals(expectedPriority, m.getPriority()); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageRateTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageRateTest.java index b83e8b2ddb..f40f6edcd0 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageRateTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MessageRateTest.java @@ -34,8 +34,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class MessageRateTest extends ActiveMQTestBase -{ +public class MessageRateTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -52,8 +51,7 @@ public class MessageRateTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testProduceRate() throws Exception - { + public void testProduceRate() throws Exception { ActiveMQServer server = createServer(false); server.start(); @@ -66,8 +64,7 @@ public class MessageRateTest extends ActiveMQTestBase ClientProducer producer = session.createProducer(ADDRESS); long start = System.currentTimeMillis(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { producer.send(session.createMessage(false)); } long end = System.currentTimeMillis(); @@ -78,8 +75,7 @@ public class MessageRateTest extends ActiveMQTestBase } @Test - public void testConsumeRate() throws Exception - { + public void testConsumeRate() throws Exception { ActiveMQServer server = createServer(false); server.start(); @@ -93,8 +89,7 @@ public class MessageRateTest extends ActiveMQTestBase ClientProducer producer = session.createProducer(ADDRESS); - for (int i = 0; i < 12; i++) - { + for (int i = 0; i < 12; i++) { producer.send(session.createMessage(false)); } @@ -104,8 +99,7 @@ public class MessageRateTest extends ActiveMQTestBase long start = System.currentTimeMillis(); - for (int i = 0; i < 12; i++) - { + for (int i = 0; i < 12; i++) { consumer.receive(1000); } @@ -116,10 +110,8 @@ public class MessageRateTest extends ActiveMQTestBase session.close(); } - @Test - public void testConsumeRate2() throws Exception - { + public void testConsumeRate2() throws Exception { ActiveMQServer server = createServer(false); server.start(); @@ -132,8 +124,7 @@ public class MessageRateTest extends ActiveMQTestBase ClientProducer producer = session.createProducer(ADDRESS); - for (int i = 0; i < 12; i++) - { + for (int i = 0; i < 12; i++) { producer.send(session.createMessage(false)); } @@ -143,8 +134,7 @@ public class MessageRateTest extends ActiveMQTestBase long start = System.currentTimeMillis(); - for (int i = 0; i < 12; i++) - { + for (int i = 0; i < 12; i++) { consumer.receive(1000); } @@ -156,8 +146,7 @@ public class MessageRateTest extends ActiveMQTestBase } @Test - public void testConsumeRateListener() throws Exception - { + public void testConsumeRateListener() throws Exception { ActiveMQServer server = createServer(false); server.start(); @@ -171,8 +160,7 @@ public class MessageRateTest extends ActiveMQTestBase ClientProducer producer = session.createProducer(ADDRESS); - for (int i = 0; i < 12; i++) - { + for (int i = 0; i < 12; i++) { producer.send(session.createMessage(false)); } @@ -182,18 +170,14 @@ public class MessageRateTest extends ActiveMQTestBase final CountDownLatch messages = new CountDownLatch(12); - consumer.setMessageHandler(new MessageHandler() - { + consumer.setMessageHandler(new MessageHandler() { - public void onMessage(final ClientMessage message) - { - try - { + public void onMessage(final ClientMessage message) { + try { message.acknowledge(); messages.countDown(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); // Hudson report failures.incrementAndGet(); } @@ -213,8 +197,7 @@ public class MessageRateTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = createInVMNonHALocator(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MultipleThreadFilterOneTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MultipleThreadFilterOneTest.java index c2f6510f5e..41dde1043c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MultipleThreadFilterOneTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/MultipleThreadFilterOneTest.java @@ -38,8 +38,7 @@ import org.apache.activemq.artemis.core.settings.impl.AddressSettings; * Multiple Threads producing Messages, with Multiple Consumers with different queues, each queue with a different filter * This is similar to MultipleThreadFilterTwoTest but it uses multiple queues */ -public class MultipleThreadFilterOneTest extends ActiveMQTestBase -{ +public class MultipleThreadFilterOneTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -63,8 +62,8 @@ public class MultipleThreadFilterOneTest extends ActiveMQTestBase // Public -------------------------------------------------------- - class SomeProducer extends Thread - { + class SomeProducer extends Thread { + final ClientSessionFactory factory; final ServerLocator locator; @@ -73,34 +72,27 @@ public class MultipleThreadFilterOneTest extends ActiveMQTestBase public final AtomicInteger errors = new AtomicInteger(0); - public SomeProducer() throws Exception - { + public SomeProducer() throws Exception { locator = createNonHALocator(isNetty); factory = locator.createSessionFactory(); prodSession = factory.createSession(false, false); sendMessages(numberOfMessages / 2); } - public void run() - { - try - { + public void run() { + try { sendMessages(numberOfMessages / 2); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); errors.incrementAndGet(); } - finally - { - try - { + finally { + try { prodSession.close(); locator.close(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { ignored.printStackTrace(); } @@ -110,18 +102,15 @@ public class MultipleThreadFilterOneTest extends ActiveMQTestBase /** * @throws ActiveMQException */ - private void sendMessages(int msgs) throws ActiveMQException - { + private void sendMessages(int msgs) throws ActiveMQException { ClientProducer producer = prodSession.createProducer(ADDRESS); - for (int i = 0; i < msgs; i++) - { + for (int i = 0; i < msgs; i++) { ClientMessage message = prodSession.createMessage(true); message.putIntProperty("prodNR", i % nThreads); producer.send(message); - if (i % 100 == 0) - { + if (i % 100 == 0) { prodSession.commit(); } } @@ -131,8 +120,8 @@ public class MultipleThreadFilterOneTest extends ActiveMQTestBase } } - class SomeConsumer extends Thread - { + class SomeConsumer extends Thread { + final ClientSessionFactory factory; final ServerLocator locator; @@ -145,8 +134,7 @@ public class MultipleThreadFilterOneTest extends ActiveMQTestBase final AtomicInteger errors = new AtomicInteger(0); - public SomeConsumer(int nr) throws Exception - { + public SomeConsumer(int nr) throws Exception { locator = createNonHALocator(isNetty); factory = locator.createSessionFactory(); consumerSession = factory.createSession(false, false); @@ -156,21 +144,17 @@ public class MultipleThreadFilterOneTest extends ActiveMQTestBase this.nr = nr; } - public void run() - { - try - { + public void run() { + try { consumerSession.start(); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = consumer.receive(15000); Assert.assertNotNull(msg); Assert.assertEquals(nr, msg.getIntProperty("prodNR").intValue()); msg.acknowledge(); - if (i % 500 == 0) - { + if (i % 500 == 0) { System.out.println("Consumed " + i); consumerSession.commit(); } @@ -180,13 +164,11 @@ public class MultipleThreadFilterOneTest extends ActiveMQTestBase consumerSession.commit(); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); errors.incrementAndGet(); } - finally - { + finally { close(); } @@ -195,56 +177,46 @@ public class MultipleThreadFilterOneTest extends ActiveMQTestBase /** * */ - public void close() - { - try - { + public void close() { + try { consumerSession.close(); locator.close(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { ignored.printStackTrace(); } } } @Test - public void testSendingNetty() throws Exception - { + public void testSendingNetty() throws Exception { testSending(true, false); } @Test - public void testSendingNettyPaging() throws Exception - { + public void testSendingNettyPaging() throws Exception { testSending(true, true); } @Test - public void testSendingInVM() throws Exception - { + public void testSendingInVM() throws Exception { testSending(false, false); } @Test - public void testSendingInVMPaging() throws Exception - { + public void testSendingInVMPaging() throws Exception { testSending(false, true); } - private void testSending(boolean isNetty, boolean isPaging) throws Exception - { + private void testSending(boolean isNetty, boolean isPaging) throws Exception { boolean useDeadConsumer = true; this.isNetty = isNetty; ActiveMQServer server; - if (isPaging) - { + if (isPaging) { server = createServer(true, createDefaultConfig(isNetty), PAGE_SIZE, PAGE_MAX, new HashMap()); } - else - { + else { server = createServer(true, isNetty); } @@ -257,50 +229,40 @@ public class MultipleThreadFilterOneTest extends ActiveMQTestBase SomeConsumer[] deadConsumers = null; - try - { + try { - for (int i = 0; i < nThreads; i++) - { + for (int i = 0; i < nThreads; i++) { consumers[i] = new SomeConsumer(i); } - for (int i = 0; i < nThreads; i++) - { + for (int i = 0; i < nThreads; i++) { producers[i] = new SomeProducer(); } - if (useDeadConsumer) - { + if (useDeadConsumer) { deadConsumers = new SomeConsumer[20]; - for (int i = 0; i < 20; i++) - { + for (int i = 0; i < 20; i++) { deadConsumers[i] = new SomeConsumer(i + nThreads); } } - for (int i = 0; i < nThreads; i++) - { + for (int i = 0; i < nThreads; i++) { consumers[i].start(); producers[i].start(); } - for (SomeProducer producer : producers) - { + for (SomeProducer producer : producers) { producer.join(); Assert.assertEquals(0, producer.errors.get()); } - for (SomeConsumer consumer : consumers) - { + for (SomeConsumer consumer : consumers) { consumer.join(); Assert.assertEquals(0, consumer.errors.get()); } - if (useDeadConsumer) - { - for (SomeConsumer cons : deadConsumers) - { + if (useDeadConsumer) { + for (SomeConsumer cons : deadConsumers) { cons.close(); } } @@ -308,8 +270,7 @@ public class MultipleThreadFilterOneTest extends ActiveMQTestBase waitForNotPaging(server.locateQueue(new SimpleString("Q1"))); } - finally - { + finally { server.stop(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NIOvsOIOTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NIOvsOIOTest.java index 40e8bab8a7..1848e4369d 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NIOvsOIOTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NIOvsOIOTest.java @@ -42,8 +42,8 @@ import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; -public class NIOvsOIOTest extends ActiveMQTestBase -{ +public class NIOvsOIOTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; // Constants ----------------------------------------------------- @@ -57,19 +57,16 @@ public class NIOvsOIOTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testNIOPerf() throws Exception - { + public void testNIOPerf() throws Exception { testPerf(true); } @Test - public void testOIOPerf() throws Exception - { + public void testOIOPerf() throws Exception { testPerf(false); } - private void doTest(String dest) throws Exception - { + private void doTest(String dest) throws Exception { final int numSenders = 1; @@ -85,8 +82,7 @@ public class NIOvsOIOTest extends ActiveMQTestBase ServerLocator locator = createInVMNonHALocator(); - for (int i = 0; i < numReceivers; i++) - { + for (int i = 0; i < numReceivers; i++) { ClientSessionFactory sf = createSessionFactory(locator); @@ -99,8 +95,7 @@ public class NIOvsOIOTest extends ActiveMQTestBase receivers[i].start(); } - for (int i = 0; i < numSenders; i++) - { + for (int i = 0; i < numSenders; i++) { ClientSessionFactory sf = createSessionFactory(locator); factories.add(sf); @@ -112,47 +107,40 @@ public class NIOvsOIOTest extends ActiveMQTestBase long start = System.currentTimeMillis(); - for (int i = 0; i < numSenders; i++) - { + for (int i = 0; i < numSenders; i++) { senders[i].start(); } - for (int i = 0; i < numSenders; i++) - { + for (int i = 0; i < numSenders; i++) { senders[i].join(); } - for (int i = 0; i < numReceivers; i++) - { + for (int i = 0; i < numReceivers; i++) { receivers[i].await(); } long end = System.currentTimeMillis(); - double rate = 1000 * (double)(numMessages * numSenders) / (end - start); + double rate = 1000 * (double) (numMessages * numSenders) / (end - start); logAndSystemOut("Rate is " + rate + " msgs sec"); - for (int i = 0; i < numSenders; i++) - { + for (int i = 0; i < numSenders; i++) { senders[i].terminate(); } - for (int i = 0; i < numReceivers; i++) - { + for (int i = 0; i < numReceivers; i++) { receivers[i].terminate(); } - for (ClientSessionFactory sf: factories) - { + for (ClientSessionFactory sf : factories) { sf.close(); } locator.close(); } - private void testPerf(boolean nio) throws Exception - { + private void testPerf(boolean nio) throws Exception { Configuration config = createDefaultInVMConfig(); Map params = new HashMap(); @@ -163,9 +151,7 @@ public class NIOvsOIOTest extends ActiveMQTestBase ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false)); - AddressSettings addressSettings = new AddressSettings() - .setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK) - .setMaxSizeBytes(10 * 1024 * 1024); + AddressSettings addressSettings = new AddressSettings().setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK).setMaxSizeBytes(10 * 1024 * 1024); final String dest = "test-destination"; @@ -175,14 +161,13 @@ public class NIOvsOIOTest extends ActiveMQTestBase server.start(); - for (int i = 0; i < 2; i++) - { + for (int i = 0; i < 2; i++) { doTest(dest); } } - private class Sender extends Thread - { + private class Sender extends Thread { + private final ClientSessionFactory sf; private final int numMessages; @@ -195,8 +180,7 @@ public class NIOvsOIOTest extends ActiveMQTestBase private final int id; - Sender(int id, ClientSessionFactory sf, final int numMessages, final String dest) - { + Sender(int id, ClientSessionFactory sf, final int numMessages, final String dest) { this.id = id; this.sf = sf; @@ -206,26 +190,21 @@ public class NIOvsOIOTest extends ActiveMQTestBase this.dest = dest; } - void prepare() throws Exception - { + void prepare() throws Exception { session = sf.createSession(true, true); producer = session.createProducer(dest); } @Override - public void run() - { + public void run() { ClientMessage msg = session.createMessage(false); - for (int i = 0; i < numMessages; i++) - { - try - { + for (int i = 0; i < numMessages; i++) { + try { producer.send(msg); } - catch (Exception e) - { + catch (Exception e) { log.error("Caught exception", e); } @@ -234,14 +213,13 @@ public class NIOvsOIOTest extends ActiveMQTestBase } } - public void terminate() throws Exception - { + public void terminate() throws Exception { session.close(); } } - private class Receiver implements MessageHandler - { + private class Receiver implements MessageHandler { + private final ClientSessionFactory sf; private final int numMessages; @@ -256,8 +234,7 @@ public class NIOvsOIOTest extends ActiveMQTestBase private String queueName; - Receiver(int id, ClientSessionFactory sf, final int numMessages, final String dest) - { + Receiver(int id, ClientSessionFactory sf, final int numMessages, final String dest) { this.id = id; this.sf = sf; @@ -267,8 +244,7 @@ public class NIOvsOIOTest extends ActiveMQTestBase this.dest = dest; } - void prepare() throws Exception - { + void prepare() throws Exception { session = sf.createSession(true, true, 0); queueName = UUIDGenerator.getInstance().generateStringUUID(); @@ -280,35 +256,29 @@ public class NIOvsOIOTest extends ActiveMQTestBase consumer.setMessageHandler(this); } - void start() throws Exception - { + void start() throws Exception { session.start(); } private final CountDownLatch latch = new CountDownLatch(1); - void await() throws Exception - { + void await() throws Exception { waitForLatch(latch); } private int count; - public void onMessage(ClientMessage msg) - { - try - { + public void onMessage(ClientMessage msg) { + try { msg.acknowledge(); } - catch (Exception e) - { + catch (Exception e) { log.error("Caught exception", e); } count++; - if (count == numMessages) - { + if (count == numMessages) { latch.countDown(); } @@ -316,8 +286,7 @@ public class NIOvsOIOTest extends ActiveMQTestBase } - public void terminate() throws Exception - { + public void terminate() throws Exception { consumer.close(); session.deleteQueue(queueName); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NettyConnectorTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NettyConnectorTest.java index 39a9ee3d11..ebbe5f51ac 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NettyConnectorTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NettyConnectorTest.java @@ -28,14 +28,13 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Before; import org.junit.Test; -public class NettyConnectorTest extends ActiveMQTestBase -{ +public class NettyConnectorTest extends ActiveMQTestBase { + private ActiveMQServer server; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(false, createDefaultNettyConfig()); @@ -44,8 +43,7 @@ public class NettyConnectorTest extends ActiveMQTestBase //make sure the 'connect-timeout' passed to netty. @Test - public void testConnectionTimeoutConfig() throws Exception - { + public void testConnectionTimeoutConfig() throws Exception { final int timeout = 23456; TransportConfiguration transport = new TransportConfiguration(NETTY_CONNECTOR_FACTORY); transport.getParams().put(TransportConstants.NETTY_CONNECT_TIMEOUT, timeout); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NettyConsumerWindowSizeTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NettyConsumerWindowSizeTest.java index dc170df452..7ffa5eb596 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NettyConsumerWindowSizeTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NettyConsumerWindowSizeTest.java @@ -16,16 +16,14 @@ */ package org.apache.activemq.artemis.tests.integration.client; -public class NettyConsumerWindowSizeTest extends ConsumerWindowSizeTest -{ +public class NettyConsumerWindowSizeTest extends ConsumerWindowSizeTest { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @Override - protected boolean isNetty() - { + protected boolean isNetty() { return true; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NettyNonPersistentMessageBufferTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NettyNonPersistentMessageBufferTest.java index 6e7c9ced3d..ef908a2e34 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NettyNonPersistentMessageBufferTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NettyNonPersistentMessageBufferTest.java @@ -16,17 +16,15 @@ */ package org.apache.activemq.artemis.tests.integration.client; -public class NettyNonPersistentMessageBufferTest extends InVMNonPersistentMessageBufferTest -{ +public class NettyNonPersistentMessageBufferTest extends InVMNonPersistentMessageBufferTest { + @Override - public boolean isPersistent() - { + public boolean isPersistent() { return false; } @Override - public boolean isNetty() - { + public boolean isNetty() { return true; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NettyPersistentMessageBufferTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NettyPersistentMessageBufferTest.java index 4f7354e2ed..d9b5829b72 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NettyPersistentMessageBufferTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NettyPersistentMessageBufferTest.java @@ -16,17 +16,15 @@ */ package org.apache.activemq.artemis.tests.integration.client; -public class NettyPersistentMessageBufferTest extends InVMNonPersistentMessageBufferTest -{ +public class NettyPersistentMessageBufferTest extends InVMNonPersistentMessageBufferTest { + @Override - public boolean isPersistent() - { + public boolean isPersistent() { return true; } @Override - public boolean isNetty() - { + public boolean isNetty() { return true; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NettyProducerFlowControlTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NettyProducerFlowControlTest.java index a0184c2dc5..75553ef4b9 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NettyProducerFlowControlTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NettyProducerFlowControlTest.java @@ -16,11 +16,10 @@ */ package org.apache.activemq.artemis.tests.integration.client; -public class NettyProducerFlowControlTest extends ProducerFlowControlTest -{ +public class NettyProducerFlowControlTest extends ProducerFlowControlTest { + @Override - protected boolean isNetty() - { + protected boolean isNetty() { return true; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NewDeadLetterAddressTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NewDeadLetterAddressTest.java index 1ed6e0cdb5..869f25e30f 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NewDeadLetterAddressTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/NewDeadLetterAddressTest.java @@ -32,24 +32,20 @@ import org.junit.Before; import org.junit.Test; /** - * * A NewDeadLetterAddressTest */ -public class NewDeadLetterAddressTest extends ActiveMQTestBase -{ +public class NewDeadLetterAddressTest extends ActiveMQTestBase { + private ActiveMQServer server; private ClientSession clientSession; private ServerLocator locator; @Test - public void testSendToDLAWhenNoRoute() throws Exception - { + public void testSendToDLAWhenNoRoute() throws Exception { SimpleString dla = new SimpleString("DLA"); SimpleString address = new SimpleString("empty_address"); - AddressSettings addressSettings = new AddressSettings() - .setDeadLetterAddress(dla) - .setSendToDLAOnNoRoute(true); + AddressSettings addressSettings = new AddressSettings().setDeadLetterAddress(dla).setSendToDLAOnNoRoute(true); server.getAddressSettingsRepository().addMatch(address.toString(), addressSettings); SimpleString dlq = new SimpleString("DLQ1"); clientSession.createQueue(dla, dlq, null, false); @@ -65,8 +61,7 @@ public class NewDeadLetterAddressTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = addServer(ActiveMQServers.newActiveMQServer(createDefaultInVMConfig(), false)); server.start(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/OrderTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/OrderTest.java index dfa34628f5..c87dbb069e 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/OrderTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/OrderTest.java @@ -35,8 +35,7 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(Parameterized.class) -public class OrderTest extends ActiveMQTestBase -{ +public class OrderTest extends ActiveMQTestBase { private boolean persistent; @@ -44,29 +43,22 @@ public class OrderTest extends ActiveMQTestBase private ServerLocator locator; - public OrderTest(boolean persistent) - { + public OrderTest(boolean persistent) { this.persistent = persistent; } - @Parameterized.Parameters(name = "persistent={0}") - public static Collection getParams() - { - return Arrays.asList(new Object[][]{ - {true}, - {false} - }); - } + @Parameterized.Parameters(name = "persistent={0}") + public static Collection getParams() { + return Arrays.asList(new Object[][]{{true}, {false}}); + } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = createNettyNonHALocator(); } - // Static -------------------------------------------------------- // Constructors -------------------------------------------------- @@ -74,14 +66,11 @@ public class OrderTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testSimpleStorage() throws Exception - { + public void testSimpleStorage() throws Exception { server = createServer(persistent, true); server.start(); - locator.setBlockOnNonDurableSend(false) - .setBlockOnDurableSend(false) - .setBlockOnAcknowledge(true); + locator.setBlockOnNonDurableSend(false).setBlockOnDurableSend(false).setBlockOnAcknowledge(true); ClientSessionFactory sf = createSessionFactory(locator); @@ -91,8 +80,7 @@ public class OrderTest extends ActiveMQTestBase ClientProducer prod = session.createProducer("queue"); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage msg = session.createMessage(i % 2 == 0); msg.putIntProperty("id", i); prod.send(msg); @@ -102,11 +90,9 @@ public class OrderTest extends ActiveMQTestBase boolean started = false; - for (int start = 0; start < 2; start++) - { + for (int start = 0; start < 2; start++) { - if (persistent && start == 1) - { + if (persistent && start == 1) { started = true; server.stop(); server.start(); @@ -119,10 +105,8 @@ public class OrderTest extends ActiveMQTestBase ClientConsumer cons = session.createConsumer("queue"); - for (int i = 0; i < 100; i++) - { - if (!started || started && i % 2 == 0) - { + for (int i = 0; i < 100; i++) { + if (!started || started && i % 2 == 0) { ClientMessage msg = cons.receive(10000); Assert.assertEquals(i, msg.getIntProperty("id").intValue()); @@ -133,10 +117,8 @@ public class OrderTest extends ActiveMQTestBase cons = session.createConsumer("queue"); - for (int i = 0; i < 100; i++) - { - if (!started || started && i % 2 == 0) - { + for (int i = 0; i < 100; i++) { + if (!started || started && i % 2 == 0) { ClientMessage msg = cons.receive(10000); Assert.assertEquals(i, msg.getIntProperty("id").intValue()); @@ -148,15 +130,12 @@ public class OrderTest extends ActiveMQTestBase } @Test - public void testOrderOverSessionClose() throws Exception - { + public void testOrderOverSessionClose() throws Exception { server = createServer(persistent, true); server.start(); - locator.setBlockOnNonDurableSend(false) - .setBlockOnDurableSend(false) - .setBlockOnAcknowledge(false); + locator.setBlockOnNonDurableSend(false).setBlockOnDurableSend(false).setBlockOnAcknowledge(false); ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(true, true, 0); @@ -166,8 +145,7 @@ public class OrderTest extends ActiveMQTestBase ClientProducer prod = session.createProducer("queue"); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = session.createMessage(i % 2 == 0); msg.putIntProperty("id", i); prod.send(msg); @@ -175,8 +153,7 @@ public class OrderTest extends ActiveMQTestBase session.close(); - for (int i = 0; i < numberOfMessages; ) - { + for (int i = 0; i < numberOfMessages; ) { session = sf.createSession(); session.start(); @@ -185,8 +162,7 @@ public class OrderTest extends ActiveMQTestBase int max = i + 10; - for (; i < max; i++) - { + for (; i < max; i++) { ClientMessage msg = consumer.receive(1000); msg.acknowledge(); @@ -195,11 +171,9 @@ public class OrderTest extends ActiveMQTestBase } // Receive a few more messages but don't consume them - for (int j = 0; j < 10 && i < numberOfMessages; j++) - { + for (int j = 0; j < 10 && i < numberOfMessages; j++) { ClientMessage msg = consumer.receiveImmediate(); - if (msg == null) - { + if (msg == null) { break; } } @@ -209,8 +183,7 @@ public class OrderTest extends ActiveMQTestBase } @Test - public void testOrderOverSessionCloseWithRedeliveryDelay() throws Exception - { + public void testOrderOverSessionCloseWithRedeliveryDelay() throws Exception { server = createServer(persistent, true); server.getAddressSettingsRepository().clear(); @@ -219,9 +192,7 @@ public class OrderTest extends ActiveMQTestBase server.start(); - locator.setBlockOnNonDurableSend(false) - .setBlockOnDurableSend(false) - .setBlockOnAcknowledge(false); + locator.setBlockOnNonDurableSend(false).setBlockOnDurableSend(false).setBlockOnAcknowledge(false); ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(true, true, 0); @@ -232,8 +203,7 @@ public class OrderTest extends ActiveMQTestBase ClientProducer prod = session.createProducer("queue"); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = session.createMessage(i % 2 == 0); msg.putIntProperty("id", i); prod.send(msg); @@ -247,24 +217,20 @@ public class OrderTest extends ActiveMQTestBase ClientConsumer cons = session.createConsumer("queue"); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = cons.receive(5000); msg.acknowledge(); assertEquals(i, msg.getIntProperty("id").intValue()); } session.close(); - session = sf.createSession(false, false); session.start(); cons = session.createConsumer("queue"); - - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = cons.receive(5000); assertNotNull(msg); msg.acknowledge(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/PagingOrderTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/PagingOrderTest.java index 84d3a068ac..8c2d9cdb64 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/PagingOrderTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/PagingOrderTest.java @@ -59,8 +59,7 @@ import java.util.concurrent.atomic.AtomicInteger; * A PagingOrderTest. PagingTest has a lot of tests already. I decided to create a newer one more * specialized on Ordering and counters */ -public class PagingOrderTest extends ActiveMQTestBase -{ +public class PagingOrderTest extends ActiveMQTestBase { private static final int PAGE_MAX = 100 * 1024; @@ -75,12 +74,10 @@ public class PagingOrderTest extends ActiveMQTestBase private Connection conn; @Test - public void testOrder1() throws Throwable - { + public void testOrder1() throws Throwable { boolean persistentMessages = true; - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); ActiveMQServer server = createServer(true, config, PAGE_SIZE, PAGE_MAX, new HashMap()); @@ -90,14 +87,7 @@ public class PagingOrderTest extends ActiveMQTestBase final int numberOfMessages = 500; - ServerLocator locator = createInVMNonHALocator() - .setClientFailureCheckPeriod(1000) - .setConnectionTTL(2000) - .setReconnectAttempts(0) - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true) - .setConsumerWindowSize(1024 * 1024); + ServerLocator locator = createInVMNonHALocator().setClientFailureCheckPeriod(1000).setConnectionTTL(2000).setReconnectAttempts(0).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true).setConsumerWindowSize(1024 * 1024); ClientSessionFactory sf = createSessionFactory(locator); @@ -111,13 +101,11 @@ public class PagingOrderTest extends ActiveMQTestBase ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= messageSize; j++) - { + for (int j = 1; j <= messageSize; j++) { bb.put(getSamplebyte(j)); } - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage message = session.createMessage(persistentMessages); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); @@ -127,8 +115,7 @@ public class PagingOrderTest extends ActiveMQTestBase message.putIntProperty(new SimpleString("id"), i); producer.send(message); - if (i % 1000 == 0) - { + if (i % 1000 == 0) { session.commit(); } } @@ -143,14 +130,12 @@ public class PagingOrderTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(ADDRESS); - for (int i = 0; i < numberOfMessages / 2; i++) - { + for (int i = 0; i < numberOfMessages / 2; i++) { ClientMessage message = consumer.receive(5000); assertNotNull(message); assertEquals(i, message.getIntProperty("id").intValue()); - if (i < 100) - { + if (i < 100) { // Do not consume the last one so we could restart message.acknowledge(); } @@ -167,8 +152,7 @@ public class PagingOrderTest extends ActiveMQTestBase consumer = session.createConsumer(ADDRESS); - for (int i = 100; i < numberOfMessages; i++) - { + for (int i = 100; i < numberOfMessages; i++) { ClientMessage message = consumer.receive(5000); assertNotNull(message); assertEquals(i, message.getIntProperty("id").intValue()); @@ -179,12 +163,10 @@ public class PagingOrderTest extends ActiveMQTestBase } @Test - public void testPageCounter() throws Throwable - { + public void testPageCounter() throws Throwable { boolean persistentMessages = true; - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); ActiveMQServer server = createServer(true, config, PAGE_SIZE, PAGE_MAX, new HashMap()); @@ -194,14 +176,7 @@ public class PagingOrderTest extends ActiveMQTestBase final int numberOfMessages = 500; - ServerLocator locator = createInVMNonHALocator() - .setClientFailureCheckPeriod(1000) - .setConnectionTTL(2000) - .setReconnectAttempts(0) - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true) - .setConsumerWindowSize(1024 * 1024); + ServerLocator locator = createInVMNonHALocator().setClientFailureCheckPeriod(1000).setConnectionTTL(2000).setReconnectAttempts(0).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true).setConsumerWindowSize(1024 * 1024); ClientSessionFactory sf = createSessionFactory(locator); @@ -217,27 +192,22 @@ public class PagingOrderTest extends ActiveMQTestBase ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= messageSize; j++) - { + for (int j = 1; j <= messageSize; j++) { bb.put(getSamplebyte(j)); } final AtomicInteger errors = new AtomicInteger(0); - Thread t1 = new Thread() - { + Thread t1 = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { ServerLocator sl = createInVMNonHALocator(); ClientSessionFactory sf = sl.createSessionFactory(); ClientSession sess = sf.createSession(true, true, 0); sess.start(); ClientConsumer cons = sess.createConsumer(ADDRESS); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = cons.receive(5000); assertNotNull(msg); assertEquals(i, msg.getIntProperty("id").intValue()); @@ -248,8 +218,7 @@ public class PagingOrderTest extends ActiveMQTestBase sess.close(); sl.close(); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); errors.incrementAndGet(); } @@ -259,8 +228,7 @@ public class PagingOrderTest extends ActiveMQTestBase t1.start(); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage message = session.createMessage(persistentMessages); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); @@ -270,8 +238,7 @@ public class PagingOrderTest extends ActiveMQTestBase message.putIntProperty(new SimpleString("id"), i); producer.send(message); - if (i % 20 == 0) - { + if (i % 20 == 0) { session.commit(); } } @@ -300,18 +267,14 @@ public class PagingOrderTest extends ActiveMQTestBase q1 = null; q2 = null; - for (Binding bind : bindings.getBindings()) - { - if (bind instanceof LocalQueueBinding) - { + for (Binding bind : bindings.getBindings()) { + if (bind instanceof LocalQueueBinding) { LocalQueueBinding qb = (LocalQueueBinding) bind; - if (qb.getQueue().getName().equals(ADDRESS)) - { + if (qb.getQueue().getName().equals(ADDRESS)) { q1 = qb.getQueue(); } - if (qb.getQueue().getName().equals(new SimpleString("inactive"))) - { + if (qb.getQueue().getName().equals(new SimpleString("inactive"))) { q2 = qb.getQueue(); } } @@ -330,12 +293,10 @@ public class PagingOrderTest extends ActiveMQTestBase } @Test - public void testPageCounter2() throws Throwable - { + public void testPageCounter2() throws Throwable { boolean persistentMessages = true; - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); ActiveMQServer server = createServer(true, config, PAGE_SIZE, PAGE_MAX, new HashMap()); @@ -345,14 +306,7 @@ public class PagingOrderTest extends ActiveMQTestBase final int numberOfMessages = 500; - ServerLocator locator = createInVMNonHALocator() - .setClientFailureCheckPeriod(1000) - .setConnectionTTL(2000) - .setReconnectAttempts(0) - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true) - .setConsumerWindowSize(1024 * 1024); + ServerLocator locator = createInVMNonHALocator().setClientFailureCheckPeriod(1000).setConnectionTTL(2000).setReconnectAttempts(0).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true).setConsumerWindowSize(1024 * 1024); ClientSessionFactory sf = createSessionFactory(locator); @@ -368,27 +322,22 @@ public class PagingOrderTest extends ActiveMQTestBase ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= messageSize; j++) - { + for (int j = 1; j <= messageSize; j++) { bb.put(getSamplebyte(j)); } final AtomicInteger errors = new AtomicInteger(0); - Thread t1 = new Thread() - { + Thread t1 = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { ServerLocator sl = createInVMNonHALocator(); ClientSessionFactory sf = sl.createSessionFactory(); ClientSession sess = sf.createSession(true, true, 0); sess.start(); ClientConsumer cons = sess.createConsumer(ADDRESS); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage msg = cons.receive(5000); assertNotNull(msg); assertEquals(i, msg.getIntProperty("id").intValue()); @@ -397,8 +346,7 @@ public class PagingOrderTest extends ActiveMQTestBase sess.close(); sl.close(); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); errors.incrementAndGet(); } @@ -406,8 +354,7 @@ public class PagingOrderTest extends ActiveMQTestBase } }; - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage message = session.createMessage(persistentMessages); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); @@ -417,8 +364,7 @@ public class PagingOrderTest extends ActiveMQTestBase message.putIntProperty(new SimpleString("id"), i); producer.send(message); - if (i % 20 == 0) - { + if (i % 20 == 0) { session.commit(); } } @@ -430,8 +376,7 @@ public class PagingOrderTest extends ActiveMQTestBase assertEquals(0, errors.get()); long timeout = System.currentTimeMillis() + 10000; - while (numberOfMessages - 100 != getMessageCount(q1) && System.currentTimeMillis() < timeout) - { + while (numberOfMessages - 100 != getMessageCount(q1) && System.currentTimeMillis() < timeout) { Thread.sleep(500); } @@ -442,12 +387,10 @@ public class PagingOrderTest extends ActiveMQTestBase } @Test - public void testOrderOverRollback() throws Throwable - { + public void testOrderOverRollback() throws Throwable { boolean persistentMessages = true; - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); ActiveMQServer server = createServer(true, config, PAGE_SIZE, PAGE_MAX, new HashMap()); @@ -457,14 +400,7 @@ public class PagingOrderTest extends ActiveMQTestBase final int numberOfMessages = 3000; - ServerLocator locator = createInVMNonHALocator() - .setClientFailureCheckPeriod(1000) - .setConnectionTTL(2000) - .setReconnectAttempts(0) - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true) - .setConsumerWindowSize(1024 * 1024); + ServerLocator locator = createInVMNonHALocator().setClientFailureCheckPeriod(1000).setConnectionTTL(2000).setReconnectAttempts(0).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true).setConsumerWindowSize(1024 * 1024); ClientSessionFactory sf = createSessionFactory(locator); @@ -478,13 +414,11 @@ public class PagingOrderTest extends ActiveMQTestBase ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= messageSize; j++) - { + for (int j = 1; j <= messageSize; j++) { bb.put(getSamplebyte(j)); } - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage message = session.createMessage(persistentMessages); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); @@ -494,8 +428,7 @@ public class PagingOrderTest extends ActiveMQTestBase message.putIntProperty(new SimpleString("id"), i); producer.send(message); - if (i % 1000 == 0) - { + if (i % 1000 == 0) { session.commit(); } } @@ -510,8 +443,7 @@ public class PagingOrderTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(ADDRESS); - for (int i = 0; i < numberOfMessages / 2; i++) - { + for (int i = 0; i < numberOfMessages / 2; i++) { ClientMessage message = consumer.receive(5000); assertNotNull(message); assertEquals(i, message.getIntProperty("id").intValue()); @@ -528,8 +460,7 @@ public class PagingOrderTest extends ActiveMQTestBase consumer = session.createConsumer(ADDRESS); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage message = consumer.receive(5000); assertNotNull(message); assertEquals(i, message.getIntProperty("id").intValue()); @@ -540,12 +471,10 @@ public class PagingOrderTest extends ActiveMQTestBase } @Test - public void testOrderOverRollback2() throws Throwable - { + public void testOrderOverRollback2() throws Throwable { boolean persistentMessages = true; - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); ActiveMQServer server = createServer(true, config, PAGE_SIZE, PAGE_MAX, new HashMap()); @@ -555,14 +484,7 @@ public class PagingOrderTest extends ActiveMQTestBase final int numberOfMessages = 200; - ServerLocator locator = createInVMNonHALocator() - .setClientFailureCheckPeriod(1000) - .setConnectionTTL(2000) - .setReconnectAttempts(0) - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true) - .setConsumerWindowSize(0); + ServerLocator locator = createInVMNonHALocator().setClientFailureCheckPeriod(1000).setConnectionTTL(2000).setReconnectAttempts(0).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true).setConsumerWindowSize(0); ClientSessionFactory sf = createSessionFactory(locator); @@ -576,13 +498,11 @@ public class PagingOrderTest extends ActiveMQTestBase ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= messageSize; j++) - { + for (int j = 1; j <= messageSize; j++) { bb.put(getSamplebyte(j)); } - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage message = session.createMessage(persistentMessages); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); @@ -592,8 +512,7 @@ public class PagingOrderTest extends ActiveMQTestBase message.putIntProperty(new SimpleString("id"), i); producer.send(message); - if (i % 1000 == 0) - { + if (i % 1000 == 0) { session.commit(); } } @@ -612,8 +531,7 @@ public class PagingOrderTest extends ActiveMQTestBase int numberOfRefs = queue.getNumberOfReferences(); // consume all non-paged references - for (int ref = 0; ref < numberOfRefs; ref++) - { + for (int ref = 0; ref < numberOfRefs; ref++) { ClientMessage msg = consumer.receive(5000); assertNotNull(msg); msg.acknowledge(); @@ -653,14 +571,7 @@ public class PagingOrderTest extends ActiveMQTestBase server.start(); - locator = createInVMNonHALocator() - .setClientFailureCheckPeriod(1000) - .setConnectionTTL(2000) - .setReconnectAttempts(0) - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true) - .setConsumerWindowSize(0); + locator = createInVMNonHALocator().setClientFailureCheckPeriod(1000).setConnectionTTL(2000).setReconnectAttempts(0).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true).setConsumerWindowSize(0); sf = createSessionFactory(locator); @@ -670,8 +581,7 @@ public class PagingOrderTest extends ActiveMQTestBase consumer = session.createConsumer(ADDRESS); - for (int i = msgIDRolledBack; i < numberOfMessages; i++) - { + for (int i = msgIDRolledBack; i < numberOfMessages; i++) { ClientMessage message = consumer.receive(5000); assertNotNull(message); assertEquals(i, message.getIntProperty("id").intValue()); @@ -684,11 +594,9 @@ public class PagingOrderTest extends ActiveMQTestBase } @Test - public void testPagingOverCreatedDestinationTopics() throws Exception - { + public void testPagingOverCreatedDestinationTopics() throws Exception { - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); ActiveMQServer server = createServer(true, config, PAGE_SIZE, -1, new HashMap()); @@ -699,29 +607,9 @@ public class PagingOrderTest extends ActiveMQTestBase jmsServer.createTopic(true, "tt", "/topic/TT"); - server.getActiveMQServerControl().addAddressSettings("jms.topic.TT", - "DLQ", - "DLQ", - -1, - false, - 5, - 1024 * 1024, - 1024 * 10, - 5, - 5, - 1, - 1000, - 0, - false, - "PAGE", - -1, - 10, - "KILL", - true, - true); + server.getActiveMQServerControl().addAddressSettings("jms.topic.TT", "DLQ", "DLQ", -1, false, 5, 1024 * 1024, 1024 * 10, 5, 5, 1, 1000, 0, false, "PAGE", -1, 10, "KILL", true, true); - ActiveMQJMSConnectionFactory cf = (ActiveMQJMSConnectionFactory) ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, - new TransportConfiguration(INVM_CONNECTOR_FACTORY)); + ActiveMQJMSConnectionFactory cf = (ActiveMQJMSConnectionFactory) ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); Connection conn = cf.createConnection(); conn.setClientID("tst"); @@ -763,11 +651,9 @@ public class PagingOrderTest extends ActiveMQTestBase } @Test - public void testPagingOverCreatedDestinationQueues() throws Exception - { + public void testPagingOverCreatedDestinationQueues() throws Exception { - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); ActiveMQServer server = createServer(true, config, -1, -1, new HashMap()); server.getAddressSettingsRepository().getMatch("#").setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK); @@ -777,31 +663,11 @@ public class PagingOrderTest extends ActiveMQTestBase jmsServer.setRegistry(new JndiBindingRegistry(context)); jmsServer.start(); - server.getActiveMQServerControl().addAddressSettings("jms.queue.Q1", - "DLQ", - "DLQ", - -1, - false, - 5, - 100 * 1024, - 10 * 1024, - 5, - 5, - 1, - 1000, - 0, - false, - "PAGE", - -1, - 10, - "KILL", - true, - true); + server.getActiveMQServerControl().addAddressSettings("jms.queue.Q1", "DLQ", "DLQ", -1, false, 5, 100 * 1024, 10 * 1024, 5, 5, 1, 1000, 0, false, "PAGE", -1, 10, "KILL", true, true); jmsServer.createQueue(true, "Q1", null, true, "/queue/Q1"); - ActiveMQJMSConnectionFactory cf = (ActiveMQJMSConnectionFactory) ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, - new TransportConfiguration(INVM_CONNECTOR_FACTORY)); + ActiveMQJMSConnectionFactory cf = (ActiveMQJMSConnectionFactory) ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); conn = cf.createConnection(); conn.setClientID("tst"); @@ -814,8 +680,7 @@ public class PagingOrderTest extends ActiveMQTestBase bmt.writeBytes(new byte[1024]); - for (int i = 0; i < 500; i++) - { + for (int i = 0; i < 500; i++) { prod.send(bmt); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/PagingSyncTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/PagingSyncTest.java index 55fdefc6af..635a91176b 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/PagingSyncTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/PagingSyncTest.java @@ -37,8 +37,7 @@ import org.junit.Test; *
    * PagingTest has a lot of tests already. I decided to create a newer one more specialized on Ordering and counters */ -public class PagingSyncTest extends ActiveMQTestBase -{ +public class PagingSyncTest extends ActiveMQTestBase { private static final int PAGE_MAX = 100 * 1024; @@ -51,12 +50,10 @@ public class PagingSyncTest extends ActiveMQTestBase static final SimpleString ADDRESS = new SimpleString("SimpleAddress"); @Test - public void testOrder1() throws Throwable - { + public void testOrder1() throws Throwable { boolean persistentMessages = true; - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); ActiveMQServer server = createServer(true, config, PAGE_SIZE, PAGE_MAX, new HashMap()); @@ -66,14 +63,7 @@ public class PagingSyncTest extends ActiveMQTestBase final int numberOfMessages = 500; - ServerLocator locator = createInVMNonHALocator() - .setClientFailureCheckPeriod(1000) - .setConnectionTTL(2000) - .setReconnectAttempts(0) - .setBlockOnNonDurableSend(false) - .setBlockOnDurableSend(false) - .setBlockOnAcknowledge(false) - .setConsumerWindowSize(1024 * 1024); + ServerLocator locator = createInVMNonHALocator().setClientFailureCheckPeriod(1000).setConnectionTTL(2000).setReconnectAttempts(0).setBlockOnNonDurableSend(false).setBlockOnDurableSend(false).setBlockOnAcknowledge(false).setConsumerWindowSize(1024 * 1024); ClientSessionFactory sf = createSessionFactory(locator); @@ -87,13 +77,11 @@ public class PagingSyncTest extends ActiveMQTestBase ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= messageSize; j++) - { + for (int j = 1; j <= messageSize; j++) { bb.put(getSamplebyte(j)); } - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage message = session.createMessage(persistentMessages); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/PagingTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/PagingTest.java index b87063935e..6bb28c2c34 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/PagingTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/PagingTest.java @@ -79,8 +79,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class PagingTest extends ActiveMQTestBase -{ +public class PagingTest extends ActiveMQTestBase { + private ServerLocator locator; private ActiveMQServer server; private ClientSessionFactory sf; @@ -98,15 +98,13 @@ public class PagingTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = createInVMNonHALocator(); } @Test - public void testPageOnLargeMessageMultipleQueues() throws Exception - { + public void testPageOnLargeMessageMultipleQueues() throws Exception { Configuration config = createDefaultInVMConfig(); final int PAGE_MAX = 20 * 1024; @@ -122,9 +120,7 @@ public class PagingTest extends ActiveMQTestBase final int numberOfBytes = 1024; - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); ClientSessionFactory sf = addSessionFactory(createSessionFactory(locator)); @@ -137,23 +133,20 @@ public class PagingTest extends ActiveMQTestBase ClientMessage message = null; - for (int i = 0; i < 201; i++) - { + for (int i = 0; i < 201; i++) { message = session.createMessage(true); message.getBodyBuffer().writerIndex(0); message.getBodyBuffer().writeBytes(new byte[numberOfBytes]); - for (int j = 1; j <= numberOfBytes; j++) - { + for (int j = 1; j <= numberOfBytes; j++) { message.getBodyBuffer().writeInt(j); } producer.send(message); } - session.close(); server.stop(); @@ -163,16 +156,14 @@ public class PagingTest extends ActiveMQTestBase sf = createSessionFactory(locator); - for (int ad = 0; ad < 2; ad++) - { + for (int ad = 0; ad < 2; ad++) { session = sf.createSession(false, false, false); ClientConsumer consumer = session.createConsumer(ADDRESS.concat("-" + ad)); session.start(); - for (int i = 0; i < 201; i++) - { + for (int i = 0; i < 201; i++) { ClientMessage message2 = consumer.receive(LargeMessageTest.RECEIVE_WAIT_TIME); Assert.assertNotNull(message2); @@ -182,17 +173,13 @@ public class PagingTest extends ActiveMQTestBase Assert.assertNotNull(message2); } - try - { - if (ad > -1) - { + try { + if (ad > -1) { session.commit(); } - else - { + else { session.rollback(); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage message2 = consumer.receive(LargeMessageTest.RECEIVE_WAIT_TIME); Assert.assertNotNull(message2); @@ -205,8 +192,7 @@ public class PagingTest extends ActiveMQTestBase } } - catch (Throwable e) - { + catch (Throwable e) { System.err.println("here!!!!!!!"); e.printStackTrace(); System.exit(-1); @@ -219,27 +205,18 @@ public class PagingTest extends ActiveMQTestBase } @Test - public void testPageCleanup() throws Exception - { + public void testPageCleanup() throws Exception { clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); - server = - createServer(true, config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); final int numberOfMessages = 5000; - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator = createInVMNonHALocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); @@ -255,13 +232,11 @@ public class PagingTest extends ActiveMQTestBase ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= MESSAGE_SIZE; j++) - { + for (int j = 1; j <= MESSAGE_SIZE; j++) { bb.put(getSamplebyte(j)); } - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = session.createMessage(true); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); @@ -269,8 +244,7 @@ public class PagingTest extends ActiveMQTestBase bodyLocal.writeBytes(body); producer.send(message); - if (i % 1000 == 0) - { + if (i % 1000 == 0) { session.commit(); } } @@ -288,8 +262,7 @@ public class PagingTest extends ActiveMQTestBase session = sf.createSession(false, false, false); producer = session.createProducer(PagingTest.ADDRESS); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = session.createMessage(true); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); @@ -297,8 +270,7 @@ public class PagingTest extends ActiveMQTestBase bodyLocal.writeBytes(body); producer.send(message); - if (i % 1000 == 0) - { + if (i % 1000 == 0) { session.commit(); } } @@ -320,14 +292,11 @@ public class PagingTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(PagingTest.ADDRESS); ClientMessage msg = null; - - for (int i = 0; i < numberOfMessages * 2; i++) - { + for (int i = 0; i < numberOfMessages * 2; i++) { msg = consumer.receive(1000); assertNotNull(msg); msg.acknowledge(); - if (i % 500 == 0) - { + if (i % 500 == 0) { session.commit(); } } @@ -354,30 +323,20 @@ public class PagingTest extends ActiveMQTestBase System.out.println("pgComplete = " + pgComplete); } - // First page is complete but it wasn't deleted @Test - public void testFirstPageCompleteNotDeleted() throws Exception - { + public void testFirstPageCompleteNotDeleted() throws Exception { clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); - server = - createServer(true, config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); final int numberOfMessages = 20; - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator = createInVMNonHALocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); @@ -395,13 +354,11 @@ public class PagingTest extends ActiveMQTestBase ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= MESSAGE_SIZE; j++) - { + for (int j = 1; j <= MESSAGE_SIZE; j++) { bb.put(getSamplebyte(j)); } - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = session.createMessage(true); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); @@ -412,8 +369,7 @@ public class PagingTest extends ActiveMQTestBase producer.send(message); - if ((i + 1) % 5 == 0) - { + if ((i + 1) % 5 == 0) { session.commit(); queue.getPageSubscription().getPagingStore().forceAnotherPage(); } @@ -431,8 +387,7 @@ public class PagingTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(ADDRESS); session.start(); - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { ClientMessage msg = consumer.receive(2000); assertNotNull(msg); assertEquals(i, msg.getIntProperty("count").intValue()); @@ -457,8 +412,7 @@ public class PagingTest extends ActiveMQTestBase consumer = session.createConsumer(ADDRESS); session.start(); - for (int i = 5; i < numberOfMessages; i++) - { + for (int i = 5; i < numberOfMessages; i++) { ClientMessage msg = consumer.receive(2000); assertNotNull(msg); assertEquals(i, msg.getIntProperty("count").intValue()); @@ -476,28 +430,18 @@ public class PagingTest extends ActiveMQTestBase } @Test - public void testPreparedACKAndRestart() throws Exception - { + public void testPreparedACKAndRestart() throws Exception { clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); final int numberOfMessages = 50; - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true) - .setAckBatchSize(0); + locator = createInVMNonHALocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true).setAckBatchSize(0); sf = createSessionFactory(locator); @@ -513,8 +457,7 @@ public class PagingTest extends ActiveMQTestBase ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= MESSAGE_SIZE; j++) - { + for (int j = 1; j <= MESSAGE_SIZE; j++) { bb.put(getSamplebyte(j)); } @@ -523,8 +466,7 @@ public class PagingTest extends ActiveMQTestBase forcePage(queue); // Send many messages, 5 on each page - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage message = session.createMessage(true); message.putIntProperty("count", i); @@ -535,8 +477,7 @@ public class PagingTest extends ActiveMQTestBase producer.send(message); - if ((i + 1) % 5 == 0) - { + if ((i + 1) % 5 == 0) { System.out.println("Forcing at " + i); session.commit(); queue.getPageSubscription().getPagingStore().forceAnotherPage(); @@ -568,10 +509,8 @@ public class PagingTest extends ActiveMQTestBase Xid neverCommittedXID = newXID(); - for (int i = 1; i < numberOfMessages; i++) - { - if (i == 20) - { + for (int i = 1; i < numberOfMessages; i++) { + if (i == 20) { // I elected a single message to be in prepared state, it won't ever be committed session.end(xidConsumeCommit, XAResource.TMSUCCESS); session.commit(xidConsumeCommit, true); @@ -582,8 +521,7 @@ public class PagingTest extends ActiveMQTestBase System.out.println("ACK " + i); message.acknowledge(); assertEquals(i, message.getIntProperty("count").intValue()); - if (i == 20) - { + if (i == 20) { session.end(neverCommittedXID, XAResource.TMSUCCESS); session.prepare(neverCommittedXID); xidConsumeCommit = newXID(); @@ -613,8 +551,7 @@ public class PagingTest extends ActiveMQTestBase producer = session.createProducer(ADDRESS); - for (int i = numberOfMessages; i < numberOfMessages * 2; i++) - { + for (int i = numberOfMessages; i < numberOfMessages * 2; i++) { ClientMessage message = session.createMessage(true); message.putIntProperty("count", i); @@ -625,8 +562,7 @@ public class PagingTest extends ActiveMQTestBase producer.send(message); - if ((i + 1) % 5 == 0) - { + if ((i + 1) % 5 == 0) { session.commit(); queue.getPageSubscription().getPagingStore().forceAnotherPage(); } @@ -636,8 +572,7 @@ public class PagingTest extends ActiveMQTestBase session.start(); - for (int i = numberOfMessages; i < numberOfMessages * 2; i++) - { + for (int i = numberOfMessages; i < numberOfMessages * 2; i++) { ClientMessage message = cons.receive(5000); assertNotNull(message); assertEquals(i, message.getIntProperty("count").intValue()); @@ -680,39 +615,23 @@ public class PagingTest extends ActiveMQTestBase * @param queue * @throws InterruptedException */ - private void forcePage(Queue queue) throws InterruptedException - { - for (long timeout = System.currentTimeMillis() + 5000; timeout > System.currentTimeMillis() && !queue.getPageSubscription() - .getPagingStore() - .isPaging(); ) - { + private void forcePage(Queue queue) throws InterruptedException { + for (long timeout = System.currentTimeMillis() + 5000; timeout > System.currentTimeMillis() && !queue.getPageSubscription().getPagingStore().isPaging(); ) { Thread.sleep(10); } assertTrue(queue.getPageSubscription().getPagingStore().isPaging()); } @Test - public void testMoveExpire() throws Exception - { + public void testMoveExpire() throws Exception { clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalDirectory(getJournalDir()) - .setJournalSyncNonTransactional(false) - .setJournalCompactMinFiles(0) // disable compact + Configuration config = createDefaultInVMConfig().setJournalDirectory(getJournalDir()).setJournalSyncNonTransactional(false).setJournalCompactMinFiles(0) // disable compact .setMessageExpiryScanPeriod(500); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); - AddressSettings defaultSetting = new AddressSettings() - .setPageSizeBytes(PAGE_SIZE) - .setMaxSizeBytes(PAGE_MAX) - .setExpiryAddress(new SimpleString("EXP")) - .setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE); + AddressSettings defaultSetting = new AddressSettings().setPageSizeBytes(PAGE_SIZE).setMaxSizeBytes(PAGE_MAX).setExpiryAddress(new SimpleString("EXP")).setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE); server.getAddressSettingsRepository().clear(); @@ -722,11 +641,7 @@ public class PagingTest extends ActiveMQTestBase final int numberOfMessages = 5000; - locator = createInVMNonHALocator() - .setConsumerWindowSize(10 * 1024 * 1024) - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator = createInVMNonHALocator().setConsumerWindowSize(10 * 1024 * 1024).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); ClientSessionFactory sf = locator.createSessionFactory(); @@ -747,17 +662,14 @@ public class PagingTest extends ActiveMQTestBase ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= MESSAGE_SIZE; j++) - { + for (int j = 1; j <= MESSAGE_SIZE; j++) { bb.put(getSamplebyte(j)); } - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage message = session.createMessage(true); - if (i < 1000) - { + if (i < 1000) { message.setExpiration(System.currentTimeMillis() + 1000); } @@ -768,16 +680,14 @@ public class PagingTest extends ActiveMQTestBase bodyLocal.writeBytes(body); producer.send(message); - if (i % 1000 == 0) - { + if (i % 1000 == 0) { session.commit(); } } session.commit(); producer.close(); - for (long timeout = System.currentTimeMillis() + 60000; timeout > System.currentTimeMillis() && getMessageCount(qEXP) < 1000; ) - { + for (long timeout = System.currentTimeMillis() + 60000; timeout > System.currentTimeMillis() && getMessageCount(qEXP) < 1000; ) { System.out.println("count = " + getMessageCount(qEXP)); Thread.sleep(100); } @@ -788,8 +698,7 @@ public class PagingTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(ADDRESS); - for (int i = 0; i < numberOfMessages - 1000; i++) - { + for (int i = 0; i < numberOfMessages - 1000; i++) { ClientMessage message = consumer.receive(5000); assertNotNull(message); message.acknowledge(); @@ -800,8 +709,7 @@ public class PagingTest extends ActiveMQTestBase assertNull(consumer.receiveImmediate()); - for (long timeout = System.currentTimeMillis() + 5000; timeout > System.currentTimeMillis() && getMessageCount(queue1) != 0; ) - { + for (long timeout = System.currentTimeMillis() + 5000; timeout > System.currentTimeMillis() && getMessageCount(queue1) != 0; ) { Thread.sleep(100); } assertEquals(0, getMessageCount(queue1)); @@ -810,8 +718,7 @@ public class PagingTest extends ActiveMQTestBase consumer = session.createConsumer("EXP"); - for (int i = 0; i < 1000; i++) - { + for (int i = 0; i < 1000; i++) { ClientMessage message = consumer.receive(5000); assertNotNull(message); message.acknowledge(); @@ -831,30 +738,18 @@ public class PagingTest extends ActiveMQTestBase } @Test - public void testDeleteQueueRestart() throws Exception - { + public void testDeleteQueueRestart() throws Exception { clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalDirectory(getJournalDir()) - .setJournalSyncNonTransactional(false) - .setJournalCompactMinFiles(0); // disable compact + Configuration config = createDefaultInVMConfig().setJournalDirectory(getJournalDir()).setJournalSyncNonTransactional(false).setJournalCompactMinFiles(0); // disable compact - ActiveMQServer server = - createServer(true, config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + ActiveMQServer server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); final int numberOfMessages = 5000; - locator = createInVMNonHALocator() - .setConsumerWindowSize(10 * 1024 * 1024) - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator = createInVMNonHALocator().setConsumerWindowSize(10 * 1024 * 1024).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); SimpleString QUEUE2 = ADDRESS.concat("-2"); @@ -878,13 +773,11 @@ public class PagingTest extends ActiveMQTestBase ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= MESSAGE_SIZE; j++) - { + for (int j = 1; j <= MESSAGE_SIZE; j++) { bb.put(getSamplebyte(j)); } - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = session.createMessage(true); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); @@ -892,8 +785,7 @@ public class PagingTest extends ActiveMQTestBase bodyLocal.writeBytes(body); producer.send(message); - if (i % 1000 == 0) - { + if (i % 1000 == 0) { session.commit(); } } @@ -904,8 +796,7 @@ public class PagingTest extends ActiveMQTestBase long timeout = System.currentTimeMillis() + 5000; // I want the buffer full to make sure there are pending messages on the server's side - while (System.currentTimeMillis() < timeout && cons.getBufferSize() < 1000 && cons2.getBufferSize() < 1000) - { + while (System.currentTimeMillis() < timeout && cons.getBufferSize() < 1000 && cons2.getBufferSize() < 1000) { System.out.println("cons1 buffer = " + cons.getBufferSize() + ", cons2 buffer = " + cons2.getBufferSize()); Thread.sleep(100); } @@ -930,44 +821,35 @@ public class PagingTest extends ActiveMQTestBase final HashMap recordsType = countJournal(config); - for (Map.Entry entry : recordsType.entrySet()) - { + for (Map.Entry entry : recordsType.entrySet()) { System.out.println(entry.getKey() + "=" + entry.getValue()); } - assertNull("The system is acking page records instead of just delete data", - recordsType.get(new Integer(JournalRecordIds.ACKNOWLEDGE_CURSOR))); + assertNull("The system is acking page records instead of just delete data", recordsType.get(new Integer(JournalRecordIds.ACKNOWLEDGE_CURSOR))); Pair, List> journalData = loadMessageJournal(config); HashSet deletedQueueReferences = new HashSet(); - for (RecordInfo info : journalData.getA()) - { - if (info.getUserRecordType() == JournalRecordIds.ADD_REF) - { + for (RecordInfo info : journalData.getA()) { + if (info.getUserRecordType() == JournalRecordIds.ADD_REF) { DescribeJournal.ReferenceDescribe ref = (ReferenceDescribe) DescribeJournal.newObjectEncoding(info); - if (ref.refEncoding.queueID == deletedQueueID) - { + if (ref.refEncoding.queueID == deletedQueueID) { deletedQueueReferences.add(new Long(info.id)); } } - else if (info.getUserRecordType() == JournalRecordIds.ACKNOWLEDGE_REF) - { + else if (info.getUserRecordType() == JournalRecordIds.ACKNOWLEDGE_REF) { AckDescribe ref = (AckDescribe) DescribeJournal.newObjectEncoding(info); - if (ref.refEncoding.queueID == deletedQueueID) - { + if (ref.refEncoding.queueID == deletedQueueID) { deletedQueueReferences.remove(new Long(info.id)); } } } - if (!deletedQueueReferences.isEmpty()) - { - for (Long value : deletedQueueReferences) - { + if (!deletedQueueReferences.isEmpty()) { + for (Long value : deletedQueueReferences) { System.out.println("Deleted Queue still has a reference:" + value); } @@ -983,13 +865,11 @@ public class PagingTest extends ActiveMQTestBase cons = (ClientConsumerInternal) session.createConsumer(ADDRESS); session.start(); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = cons.receive(5000); assertNotNull(message); message.acknowledge(); - if (i % 1000 == 0) - { + if (i % 1000 == 0) { session.commit(); } } @@ -1002,8 +882,7 @@ public class PagingTest extends ActiveMQTestBase assertEquals(0, getMessageCount(queue)); timeout = System.currentTimeMillis() + 10000; - while (timeout > System.currentTimeMillis() && queue.getPageSubscription().getPagingStore().isPaging()) - { + while (timeout > System.currentTimeMillis() && queue.getPageSubscription().getPagingStore().isPaging()) { Thread.sleep(100); } assertFalse(queue.getPageSubscription().getPagingStore().isPaging()); @@ -1011,20 +890,13 @@ public class PagingTest extends ActiveMQTestBase server.stop(); } - @Test - public void testPreparePersistent() throws Exception - { + public void testPreparePersistent() throws Exception { clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); @@ -1036,9 +908,7 @@ public class PagingTest extends ActiveMQTestBase locator = createInVMNonHALocator(); - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); @@ -1054,13 +924,11 @@ public class PagingTest extends ActiveMQTestBase ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= MESSAGE_SIZE; j++) - { + for (int j = 1; j <= MESSAGE_SIZE; j++) { bb.put(getSamplebyte(j)); } - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = session.createMessage(true); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); @@ -1070,8 +938,7 @@ public class PagingTest extends ActiveMQTestBase message.putIntProperty(new SimpleString("id"), i); producer.send(message); - if (i % 1000 == 0) - { + if (i % 1000 == 0) { session.commit(); } } @@ -1084,11 +951,7 @@ public class PagingTest extends ActiveMQTestBase server.stop(); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); locator = createInVMNonHALocator(); @@ -1101,18 +964,15 @@ public class PagingTest extends ActiveMQTestBase LinkedList xids = new LinkedList(); int msgReceived = 0; - for (int i = 0; i < numberOfTX; i++) - { + for (int i = 0; i < numberOfTX; i++) { ClientSession sessionConsumer = sf.createSession(true, false, false); Xid xid = newXID(); xids.add(xid); sessionConsumer.start(xid, XAResource.TMNOFLAGS); sessionConsumer.start(); ClientConsumer consumer = sessionConsumer.createConsumer(PagingTest.ADDRESS); - for (int msgCount = 0; msgCount < messagesPerTX; msgCount++) - { - if (msgReceived == numberOfMessages) - { + for (int msgCount = 0; msgCount < messagesPerTX; msgCount++) { + if (msgReceived == numberOfMessages) { break; } msgReceived++; @@ -1140,11 +1000,7 @@ public class PagingTest extends ActiveMQTestBase server.stop(); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); waitForServerToStart(server); @@ -1163,21 +1019,17 @@ public class PagingTest extends ActiveMQTestBase assertEquals(numberOfMessages, getMessageCount(queue)); ClientMessage msg = consumer.receive(5000); - if (msg != null) - { - while (true) - { + if (msg != null) { + while (true) { ClientMessage msg2 = consumer.receive(1000); - if (msg2 == null) - { + if (msg2 == null) { break; } } } assertNull(msg); - for (int i = xids.size() - 1; i >= 0; i--) - { + for (int i = xids.size() - 1; i >= 0; i--) { Xid xid = xids.get(i); session.rollback(xid); } @@ -1192,16 +1044,14 @@ public class PagingTest extends ActiveMQTestBase consumer = session.createConsumer(PagingTest.ADDRESS); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { msg = consumer.receive(1000); assertNotNull(msg); msg.acknowledge(); assertEquals(i, msg.getIntProperty("id").intValue()); - if (i % 500 == 0) - { + if (i % 500 == 0) { session.commit(); } } @@ -1220,12 +1070,10 @@ public class PagingTest extends ActiveMQTestBase } @Test - public void testSendOverBlockingNoFlowControl() throws Exception - { + public void testSendOverBlockingNoFlowControl() throws Exception { clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.getAddressSettingsRepository().getMatch("#").setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK); @@ -1236,12 +1084,7 @@ public class PagingTest extends ActiveMQTestBase final int numberOfMessages = 500; - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true) - .setProducerWindowSize(-1) - .setMinLargeMessageSize(1024 * 1024); + locator = createInVMNonHALocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true).setProducerWindowSize(-1).setMinLargeMessageSize(1024 * 1024); sf = createSessionFactory(locator); @@ -1257,13 +1100,11 @@ public class PagingTest extends ActiveMQTestBase ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= biggerMessageSize; j++) - { + for (int j = 1; j <= biggerMessageSize; j++) { bb.put(getSamplebyte(j)); } - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = session.createMessage(true); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); @@ -1274,8 +1115,7 @@ public class PagingTest extends ActiveMQTestBase producer.send(message); - if (i % 10 == 0) - { + if (i % 10 == 0) { session.commit(); } } @@ -1285,14 +1125,12 @@ public class PagingTest extends ActiveMQTestBase ClientConsumer cons = session.createConsumer(ADDRESS); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = cons.receive(5000); assertNotNull(message); message.acknowledge(); - if (i % 10 == 0) - { + if (i % 10 == 0) { session.commit(); } } @@ -1302,27 +1140,18 @@ public class PagingTest extends ActiveMQTestBase } @Test - public void testReceiveImmediate() throws Exception - { + public void testReceiveImmediate() throws Exception { clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); final int numberOfMessages = 1000; - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator = createInVMNonHALocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); @@ -1338,13 +1167,11 @@ public class PagingTest extends ActiveMQTestBase ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= MESSAGE_SIZE; j++) - { + for (int j = 1; j <= MESSAGE_SIZE; j++) { bb.put(getSamplebyte(j)); } - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = session.createMessage(true); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); @@ -1354,8 +1181,7 @@ public class PagingTest extends ActiveMQTestBase message.putIntProperty(new SimpleString("id"), i); producer.send(message); - if (i % 1000 == 0) - { + if (i % 1000 == 0) { session.commit(); } } @@ -1369,11 +1195,7 @@ public class PagingTest extends ActiveMQTestBase server.stop(); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); locator = createInVMNonHALocator(); @@ -1387,21 +1209,18 @@ public class PagingTest extends ActiveMQTestBase ClientSession sessionConsumer = sf.createSession(false, false, false); sessionConsumer.start(); ClientConsumer consumer = sessionConsumer.createConsumer(PagingTest.ADDRESS); - for (int msgCount = 0; msgCount < numberOfMessages; msgCount++) - { + for (int msgCount = 0; msgCount < numberOfMessages; msgCount++) { log.info("Received " + msgCount); msgReceived++; ClientMessage msg = consumer.receiveImmediate(); - if (msg == null) - { + if (msg == null) { log.info("It's null. leaving now"); sessionConsumer.commit(); fail("Didn't receive a message"); } msg.acknowledge(); - if (msgCount % 5 == 0) - { + if (msgCount % 5 == 0) { log.info("commit"); sessionConsumer.commit(); } @@ -1418,8 +1237,7 @@ public class PagingTest extends ActiveMQTestBase assertEquals(0, getMessageCount(queue)); long timeout = System.currentTimeMillis() + 5000; - while (timeout > System.currentTimeMillis() && queue.getPageSubscription().getPagingStore().isPaging()) - { + while (timeout > System.currentTimeMillis() && queue.getPageSubscription().getPagingStore().isPaging()) { Thread.sleep(100); } assertFalse(queue.getPageSubscription().getPagingStore().isPaging()); @@ -1430,29 +1248,20 @@ public class PagingTest extends ActiveMQTestBase * This test will remove all the page directories during a restart, simulating a crash scenario. The server should still start after this */ @Test - public void testDeletePhysicalPages() throws Exception - { + public void testDeletePhysicalPages() throws Exception { clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setPersistDeliveryCountBeforeDelivery(true); + Configuration config = createDefaultInVMConfig().setPersistDeliveryCountBeforeDelivery(true); config.setJournalSyncNonTransactional(false); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); final int numberOfMessages = 1000; - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator = createInVMNonHALocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); @@ -1468,13 +1277,11 @@ public class PagingTest extends ActiveMQTestBase ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= MESSAGE_SIZE; j++) - { + for (int j = 1; j <= MESSAGE_SIZE; j++) { bb.put(getSamplebyte(j)); } - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = session.createMessage(true); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); @@ -1484,8 +1291,7 @@ public class PagingTest extends ActiveMQTestBase message.putIntProperty(new SimpleString("id"), i); producer.send(message); - if (i % 1000 == 0) - { + if (i % 1000 == 0) { session.commit(); } } @@ -1499,11 +1305,7 @@ public class PagingTest extends ActiveMQTestBase server.stop(); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); locator = createInVMNonHALocator(); @@ -1517,21 +1319,18 @@ public class PagingTest extends ActiveMQTestBase ClientSession sessionConsumer = sf.createSession(false, false, false); sessionConsumer.start(); ClientConsumer consumer = sessionConsumer.createConsumer(PagingTest.ADDRESS); - for (int msgCount = 0; msgCount < numberOfMessages; msgCount++) - { + for (int msgCount = 0; msgCount < numberOfMessages; msgCount++) { log.info("Received " + msgCount); msgReceived++; ClientMessage msg = consumer.receiveImmediate(); - if (msg == null) - { + if (msg == null) { log.info("It's null. leaving now"); sessionConsumer.commit(); fail("Didn't receive a message"); } msg.acknowledge(); - if (msgCount % 5 == 0) - { + if (msgCount % 5 == 0) { log.info("commit"); sessionConsumer.commit(); } @@ -1548,8 +1347,7 @@ public class PagingTest extends ActiveMQTestBase assertEquals(0, getMessageCount(queue)); long timeout = System.currentTimeMillis() + 5000; - while (timeout > System.currentTimeMillis() && queue.getPageSubscription().getPagingStore().isPaging()) - { + while (timeout > System.currentTimeMillis() && queue.getPageSubscription().getPagingStore().isPaging()) { Thread.sleep(100); } assertFalse(queue.getPageSubscription().getPagingStore().isPaging()); @@ -1560,17 +1358,10 @@ public class PagingTest extends ActiveMQTestBase // a dumb user, or anything that will remove the data deleteDirectory(new File(getPageDir())); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator = createInVMNonHALocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); @@ -1581,8 +1372,7 @@ public class PagingTest extends ActiveMQTestBase producer = session.createProducer(PagingTest.ADDRESS); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = session.createMessage(true); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); @@ -1592,8 +1382,7 @@ public class PagingTest extends ActiveMQTestBase message.putIntProperty(new SimpleString("id"), i); producer.send(message); - if (i % 1000 == 0) - { + if (i % 1000 == 0) { session.commit(); } } @@ -1602,11 +1391,7 @@ public class PagingTest extends ActiveMQTestBase server.stop(); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); locator = createInVMNonHALocator(); @@ -1620,21 +1405,18 @@ public class PagingTest extends ActiveMQTestBase sessionConsumer = sf.createSession(false, false, false); sessionConsumer.start(); consumer = sessionConsumer.createConsumer(PagingTest.ADDRESS); - for (int msgCount = 0; msgCount < numberOfMessages; msgCount++) - { + for (int msgCount = 0; msgCount < numberOfMessages; msgCount++) { log.info("Received " + msgCount); msgReceived++; ClientMessage msg = consumer.receiveImmediate(); - if (msg == null) - { + if (msg == null) { log.info("It's null. leaving now"); sessionConsumer.commit(); fail("Didn't receive a message"); } msg.acknowledge(); - if (msgCount % 5 == 0) - { + if (msgCount % 5 == 0) { log.info("commit"); sessionConsumer.commit(); } @@ -1647,18 +1429,12 @@ public class PagingTest extends ActiveMQTestBase } @Test - public void testMissingTXEverythingAcked() throws Exception - { + public void testMissingTXEverythingAcked() throws Exception { clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); @@ -1668,12 +1444,8 @@ public class PagingTest extends ActiveMQTestBase final int messagesPerTX = numberOfMessages / numberOfTX; - try - { - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + try { + locator = createInVMNonHALocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); @@ -1691,13 +1463,11 @@ public class PagingTest extends ActiveMQTestBase ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= MESSAGE_SIZE; j++) - { + for (int j = 1; j <= MESSAGE_SIZE; j++) { bb.put(getSamplebyte(j)); } - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = session.createMessage(true); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); @@ -1707,22 +1477,18 @@ public class PagingTest extends ActiveMQTestBase message.putIntProperty(new SimpleString("id"), i); producer.send(message); - if (i % messagesPerTX == 0) - { + if (i % messagesPerTX == 0) { session.commit(); } } session.commit(); session.close(); } - finally - { - try - { + finally { + try { server.stop(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } @@ -1730,35 +1496,22 @@ public class PagingTest extends ActiveMQTestBase List list = new ArrayList(); - JournalImpl jrn = new JournalImpl(config.getJournalFileSize(), - 2, - 0, - 0, - new NIOSequentialFileFactory(server.getConfiguration().getJournalLocation(), 1), - "activemq-data", - "amq", - 1); + JournalImpl jrn = new JournalImpl(config.getJournalFileSize(), 2, 0, 0, new NIOSequentialFileFactory(server.getConfiguration().getJournalLocation(), 1), "activemq-data", "amq", 1); jrn.start(); jrn.load(records, list, null); // Delete everything from the journal - for (RecordInfo info : records) - { + for (RecordInfo info : records) { if (!info.isUpdate && info.getUserRecordType() != JournalRecordIds.PAGE_CURSOR_COUNTER_VALUE && info.getUserRecordType() != JournalRecordIds.PAGE_CURSOR_COUNTER_INC && - info.getUserRecordType() != JournalRecordIds.PAGE_CURSOR_COMPLETE) - { + info.getUserRecordType() != JournalRecordIds.PAGE_CURSOR_COMPLETE) { jrn.appendDeleteRecord(info.id, false); } } jrn.stop(); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); @@ -1772,30 +1525,19 @@ public class PagingTest extends ActiveMQTestBase pg.close(); - long[] queues = new long[]{ - server.locateQueue(new SimpleString("q1")).getID(), - server.locateQueue(new SimpleString("q2")).getID()}; + long[] queues = new long[]{server.locateQueue(new SimpleString("q1")).getID(), server.locateQueue(new SimpleString("q2")).getID()}; - for (long q : queues) - { - for (int i = 0; i < msgs.size(); i++) - { + for (long q : queues) { + for (int i = 0; i < msgs.size(); i++) { server.getStorageManager().storeCursorAcknowledge(q, new PagePositionImpl(pg.getPageId(), i)); } } server.stop(); - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator = createInVMNonHALocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); @@ -1830,18 +1572,12 @@ public class PagingTest extends ActiveMQTestBase } @Test - public void testMissingTXEverythingAcked2() throws Exception - { + public void testMissingTXEverythingAcked2() throws Exception { clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); @@ -1851,12 +1587,8 @@ public class PagingTest extends ActiveMQTestBase final int messagesPerTX = numberOfMessages / numberOfTX; - try - { - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + try { + locator = createInVMNonHALocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); @@ -1876,13 +1608,11 @@ public class PagingTest extends ActiveMQTestBase ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= MESSAGE_SIZE; j++) - { + for (int j = 1; j <= MESSAGE_SIZE; j++) { bb.put(getSamplebyte(j)); } - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = session.createMessage(true); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); @@ -1892,8 +1622,7 @@ public class PagingTest extends ActiveMQTestBase message.putStringProperty("id", "str-" + i); producer.send(message); - if ((i + 1) % messagesPerTX == 0) - { + if ((i + 1) % messagesPerTX == 0) { session.commit(); } } @@ -1901,12 +1630,10 @@ public class PagingTest extends ActiveMQTestBase session.start(); - for (int i = 1; i <= 2; i++) - { + for (int i = 1; i <= 2; i++) { ClientConsumer cons = session.createConsumer("q" + i); - for (int j = 0; j < 3; j++) - { + for (int j = 0; j < 3; j++) { ClientMessage msg = cons.receive(5000); assertNotNull(msg); @@ -1922,32 +1649,22 @@ public class PagingTest extends ActiveMQTestBase session.close(); } - finally - { + finally { locator.close(); - try - { + try { server.stop(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); - locator = createInVMNonHALocator(); - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); ClientSessionFactory csf = createSessionFactory(locator); @@ -1955,12 +1672,10 @@ public class PagingTest extends ActiveMQTestBase session.start(); - for (int i = 1; i <= 2; i++) - { + for (int i = 1; i <= 2; i++) { ClientConsumer cons = session.createConsumer("q" + i); - for (int j = 3; j < 6; j++) - { + for (int j = 3; j < 6; j++) { ClientMessage msg = cons.receive(5000); assertNotNull(msg); @@ -1979,46 +1694,33 @@ public class PagingTest extends ActiveMQTestBase long timeout = System.currentTimeMillis() + 5000; - while (System.currentTimeMillis() < timeout && server.getPagingManager().getPageStore(ADDRESS).isPaging()) - { + while (System.currentTimeMillis() < timeout && server.getPagingManager().getPageStore(ADDRESS).isPaging()) { Thread.sleep(100); } } @Test - public void testTwoQueuesOneNoRouting() throws Exception - { + public void testTwoQueuesOneNoRouting() throws Exception { boolean persistentMessages = true; clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); final int numberOfMessages = 1000; - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator = createInVMNonHALocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); ClientSession session = sf.createSession(false, false, false); session.createQueue(PagingTest.ADDRESS, PagingTest.ADDRESS, null, true); - session.createQueue(PagingTest.ADDRESS, - PagingTest.ADDRESS.concat("-invalid"), - new SimpleString(ActiveMQServerImpl.GENERIC_IGNORED_FILTER), - true); + session.createQueue(PagingTest.ADDRESS, PagingTest.ADDRESS.concat("-invalid"), new SimpleString(ActiveMQServerImpl.GENERIC_IGNORED_FILTER), true); ClientProducer producer = session.createProducer(PagingTest.ADDRESS); @@ -2026,8 +1728,7 @@ public class PagingTest extends ActiveMQTestBase byte[] body = new byte[MESSAGE_SIZE]; - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = session.createMessage(persistentMessages); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); @@ -2037,8 +1738,7 @@ public class PagingTest extends ActiveMQTestBase message.putIntProperty(new SimpleString("id"), i); producer.send(message); - if (i % 1000 == 0) - { + if (i % 1000 == 0) { session.commit(); } } @@ -2049,15 +1749,13 @@ public class PagingTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(PagingTest.ADDRESS); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = consumer.receive(5000); assertNotNull(message); message.acknowledge(); assertEquals(i, message.getIntProperty("id").intValue()); - if (i % 1000 == 0) - { + if (i % 1000 == 0) { session.commit(); } } @@ -2072,8 +1770,7 @@ public class PagingTest extends ActiveMQTestBase store.getCursorProvider().cleanup(); long timeout = System.currentTimeMillis() + 5000; - while (store.isPaging() && timeout > System.currentTimeMillis()) - { + while (store.isPaging() && timeout > System.currentTimeMillis()) { Thread.sleep(100); } @@ -2082,59 +1779,38 @@ public class PagingTest extends ActiveMQTestBase } @Test - public void testSendReceivePagingPersistent() throws Exception - { + public void testSendReceivePagingPersistent() throws Exception { internaltestSendReceivePaging(true); } @Test - public void testSendReceivePagingNonPersistent() throws Exception - { + public void testSendReceivePagingNonPersistent() throws Exception { internaltestSendReceivePaging(false); } @Test - public void testWithDiverts() throws Exception - { + public void testWithDiverts() throws Exception { internalMultiQueuesTest(true); } @Test - public void testWithMultiQueues() throws Exception - { + public void testWithMultiQueues() throws Exception { internalMultiQueuesTest(false); } - public void internalMultiQueuesTest(final boolean divert) throws Exception - { + public void internalMultiQueuesTest(final boolean divert) throws Exception { clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); - if (divert) - { - DivertConfiguration divert1 = new DivertConfiguration() - .setName("dv1") - .setRoutingName("nm1") - .setAddress(PagingTest.ADDRESS.toString()) - .setForwardingAddress(PagingTest.ADDRESS.toString() + "-1") - .setExclusive(true); + if (divert) { + DivertConfiguration divert1 = new DivertConfiguration().setName("dv1").setRoutingName("nm1").setAddress(PagingTest.ADDRESS.toString()).setForwardingAddress(PagingTest.ADDRESS.toString() + "-1").setExclusive(true); config.addDivertConfiguration(divert1); - DivertConfiguration divert2 = new DivertConfiguration() - .setName("dv2") - .setRoutingName("nm2") - .setAddress(PagingTest.ADDRESS.toString()) - .setForwardingAddress(PagingTest.ADDRESS.toString() + "-2") - .setExclusive(true); + DivertConfiguration divert2 = new DivertConfiguration().setName("dv2").setRoutingName("nm2").setAddress(PagingTest.ADDRESS.toString()).setForwardingAddress(PagingTest.ADDRESS.toString() + "-2").setExclusive(true); config.addDivertConfiguration(divert2); } @@ -2147,37 +1823,31 @@ public class PagingTest extends ActiveMQTestBase ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= MESSAGE_SIZE; j++) - { + for (int j = 1; j <= MESSAGE_SIZE; j++) { bb.put(getSamplebyte(j)); } final AtomicBoolean running = new AtomicBoolean(true); - class TCount extends Thread - { + class TCount extends Thread { + Queue queue; - TCount(Queue queue) - { + TCount(Queue queue) { this.queue = queue; } @Override - public void run() - { - try - { - while (running.get()) - { + public void run() { + try { + while (running.get()) { // this will be overusing what some users do. flush / getCount getMessagesAdded(queue); getMessageCount(queue); Thread.sleep(10); } } - catch (InterruptedException e) - { + catch (InterruptedException e) { log.info("Thread interrupted"); } } @@ -2186,26 +1856,20 @@ public class PagingTest extends ActiveMQTestBase TCount tcount1 = null; TCount tcount2 = null; - try - { + try { { - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator = createInVMNonHALocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); ClientSession session = sf.createSession(false, false, false); - if (divert) - { + if (divert) { session.createQueue(PagingTest.ADDRESS + "-1", PagingTest.ADDRESS + "-1", null, true); session.createQueue(PagingTest.ADDRESS + "-2", PagingTest.ADDRESS + "-2", null, true); } - else - { + else { session.createQueue(PagingTest.ADDRESS.toString(), PagingTest.ADDRESS + "-1", null, true); session.createQueue(PagingTest.ADDRESS.toString(), PagingTest.ADDRESS + "-2", null, true); @@ -2215,10 +1879,8 @@ public class PagingTest extends ActiveMQTestBase ClientMessage message = null; - for (int i = 0; i < numberOfMessages; i++) - { - if (i % 500 == 0) - { + for (int i = 0; i < numberOfMessages; i++) { + if (i % 500 == 0) { log.info("Sent " + i + " messages"); session.commit(); } @@ -2243,11 +1905,7 @@ public class PagingTest extends ActiveMQTestBase locator.close(); } - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); Queue queue1 = server.locateQueue(PagingTest.ADDRESS.concat("-1")); @@ -2274,26 +1932,21 @@ public class PagingTest extends ActiveMQTestBase Thread[] threads = new Thread[2]; - for (int start = 1; start <= 2; start++) - { + for (int start = 1; start <= 2; start++) { final String addressToSubscribe = PagingTest.ADDRESS + "-" + start; - threads[start - 1] = new Thread() - { + threads[start - 1] = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { ClientSession session = sf2.createSession(null, null, false, true, true, false, 0); ClientConsumer consumer = session.createConsumer(addressToSubscribe); session.start(); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage message2 = consumer.receive(PagingTest.RECEIVE_TIMEOUT); Assert.assertNotNull(message2); @@ -2304,25 +1957,19 @@ public class PagingTest extends ActiveMQTestBase Assert.assertNotNull(message2); - if (i % 100 == 0) - { - if (i % 5000 == 0) - { + if (i % 100 == 0) { + if (i % 5000 == 0) { log.info(addressToSubscribe + " consumed " + i + " messages"); } session.commit(); } - try - { + try { assertBodiesEqual(body, message2.getBodyBuffer()); } - catch (AssertionError e) - { + catch (AssertionError e) { PagingTest.log.info("Expected buffer:" + ActiveMQTestBase.dumpBytesHex(body, 40)); - PagingTest.log.info("Arriving buffer:" + ActiveMQTestBase.dumpBytesHex(message2.getBodyBuffer() - .toByteBuffer() - .array(), 40)); + PagingTest.log.info("Arriving buffer:" + ActiveMQTestBase.dumpBytesHex(message2.getBodyBuffer().toByteBuffer().array(), 40)); throw e; } } @@ -2333,8 +1980,7 @@ public class PagingTest extends ActiveMQTestBase session.close(); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); errors.incrementAndGet(); } @@ -2343,13 +1989,11 @@ public class PagingTest extends ActiveMQTestBase }; } - for (int i = 0; i < 2; i++) - { + for (int i = 0; i < 2; i++) { threads[i].start(); } - for (int i = 0; i < 2; i++) - { + for (int i = 0; i < 2; i++) { threads[i].join(); } @@ -2358,10 +2002,8 @@ public class PagingTest extends ActiveMQTestBase assertEquals(0, errors.get()); - for (int i = 0; i < 20 && server.getPagingManager().getTransactions().size() != 0; i++) - { - if (server.getPagingManager().getTransactions().size() != 0) - { + for (int i = 0; i < 20 && server.getPagingManager().getTransactions().size() != 0; i++) { + if (server.getPagingManager().getTransactions().size() != 0) { // The delete may be asynchronous, giving some time case it eventually happen asynchronously Thread.sleep(500); } @@ -2370,46 +2012,35 @@ public class PagingTest extends ActiveMQTestBase assertEquals(0, server.getPagingManager().getTransactions().size()); } - finally - { + finally { running.set(false); - if (tcount1 != null) - { + if (tcount1 != null) { tcount1.interrupt(); tcount1.join(); } - if (tcount2 != null) - { + if (tcount2 != null) { tcount2.interrupt(); tcount2.join(); } - try - { + try { server.stop(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } } @Test - public void testMultiQueuesNonPersistentAndPersistent() throws Exception - { + public void testMultiQueuesNonPersistentAndPersistent() throws Exception { clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); @@ -2419,17 +2050,14 @@ public class PagingTest extends ActiveMQTestBase ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= MESSAGE_SIZE; j++) - { + for (int j = 1; j <= MESSAGE_SIZE; j++) { bb.put(getSamplebyte(j)); } { locator = createInVMNonHALocator(); - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); @@ -2443,10 +2071,8 @@ public class PagingTest extends ActiveMQTestBase ClientMessage message = null; - for (int i = 0; i < numberOfMessages; i++) - { - if (i % 500 == 0) - { + for (int i = 0; i < numberOfMessages; i++) { + if (i % 500 == 0) { session.commit(); } message = session.createMessage(true); @@ -2470,11 +2096,7 @@ public class PagingTest extends ActiveMQTestBase locator.close(); } - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); ServerLocator locator1 = createInVMNonHALocator(); @@ -2482,21 +2104,17 @@ public class PagingTest extends ActiveMQTestBase final AtomicInteger errors = new AtomicInteger(0); - Thread t = new Thread() - { + Thread t = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { ClientSession session = sf2.createSession(null, null, false, true, true, false, 0); ClientConsumer consumer = session.createConsumer(PagingTest.ADDRESS + "-1"); session.start(); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage message2 = consumer.receive(PagingTest.RECEIVE_TIMEOUT); Assert.assertNotNull(message2); @@ -2507,21 +2125,16 @@ public class PagingTest extends ActiveMQTestBase Assert.assertNotNull(message2); - if (i % 1000 == 0) - { + if (i % 1000 == 0) { session.commit(); } - try - { + try { assertBodiesEqual(body, message2.getBodyBuffer()); } - catch (AssertionError e) - { + catch (AssertionError e) { PagingTest.log.info("Expected buffer:" + ActiveMQTestBase.dumpBytesHex(body, 40)); - PagingTest.log.info("Arriving buffer:" + ActiveMQTestBase.dumpBytesHex(message2.getBodyBuffer() - .toByteBuffer() - .array(), 40)); + PagingTest.log.info("Arriving buffer:" + ActiveMQTestBase.dumpBytesHex(message2.getBodyBuffer().toByteBuffer().array(), 40)); throw e; } } @@ -2532,8 +2145,7 @@ public class PagingTest extends ActiveMQTestBase session.close(); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); errors.incrementAndGet(); } @@ -2546,16 +2158,14 @@ public class PagingTest extends ActiveMQTestBase assertEquals(0, errors.get()); - for (int i = 0; i < 20 && server.getPagingManager().getPageStore(ADDRESS).isPaging(); i++) - { + for (int i = 0; i < 20 && server.getPagingManager().getPageStore(ADDRESS).isPaging(); i++) { // The delete may be asynchronous, giving some time case it eventually happen asynchronously Thread.sleep(500); } assertFalse(server.getPagingManager().getPageStore(ADDRESS).isPaging()); - for (int i = 0; i < 20 && server.getPagingManager().getTransactions().size() != 0; i++) - { + for (int i = 0; i < 20 && server.getPagingManager().getTransactions().size() != 0; i++) { // The delete may be asynchronous, giving some time case it eventually happen asynchronously Thread.sleep(500); } @@ -2564,29 +2174,20 @@ public class PagingTest extends ActiveMQTestBase } - private void internaltestSendReceivePaging(final boolean persistentMessages) throws Exception - { + private void internaltestSendReceivePaging(final boolean persistentMessages) throws Exception { clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); final int numberOfIntegers = 256; final int numberOfMessages = 1000; - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator = createInVMNonHALocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); @@ -2605,13 +2206,11 @@ public class PagingTest extends ActiveMQTestBase ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= numberOfIntegers; j++) - { + for (int j = 1; j <= numberOfIntegers; j++) { bb.putInt(j); } - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = session.createMessage(persistentMessages); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); @@ -2629,11 +2228,7 @@ public class PagingTest extends ActiveMQTestBase server.stop(); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); locator = createInVMNonHALocator(); @@ -2645,8 +2240,7 @@ public class PagingTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage message2 = consumer.receive(PagingTest.RECEIVE_TIMEOUT); Assert.assertNotNull(message2); @@ -2659,21 +2253,16 @@ public class PagingTest extends ActiveMQTestBase Assert.assertNotNull(message2); - if (i % 1000 == 0) - { + if (i % 1000 == 0) { session.commit(); } - try - { + try { assertBodiesEqual(body, message2.getBodyBuffer()); } - catch (AssertionError e) - { + catch (AssertionError e) { PagingTest.log.info("Expected buffer:" + ActiveMQTestBase.dumpBytesHex(body, 40)); - PagingTest.log.info("Arriving buffer:" + ActiveMQTestBase.dumpBytesHex(message2.getBodyBuffer() - .toByteBuffer() - .array(), 40)); + PagingTest.log.info("Arriving buffer:" + ActiveMQTestBase.dumpBytesHex(message2.getBodyBuffer().toByteBuffer().array(), 40)); throw e; } } @@ -2683,8 +2272,7 @@ public class PagingTest extends ActiveMQTestBase session.close(); } - private void assertBodiesEqual(final byte[] body, final ActiveMQBuffer buffer) - { + private void assertBodiesEqual(final byte[] body, final ActiveMQBuffer buffer) { byte[] other = new byte[body.length]; buffer.readBytes(other); @@ -2700,24 +2288,16 @@ public class PagingTest extends ActiveMQTestBase * - Check order */ @Test - public void testDepageDuringTransaction() throws Exception - { + public void testDepageDuringTransaction() throws Exception { clearDataRecreateServerDirs(); Configuration config = createDefaultInVMConfig(); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator = createInVMNonHALocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); @@ -2733,14 +2313,12 @@ public class PagingTest extends ActiveMQTestBase ClientMessage message = null; int numberOfMessages = 0; - while (true) - { + while (true) { message = session.createMessage(true); message.getBodyBuffer().writeBytes(body); // Stop sending message as soon as we start paging - if (server.getPagingManager().getPageStore(PagingTest.ADDRESS).isPaging()) - { + if (server.getPagingManager().getPageStore(PagingTest.ADDRESS).isPaging()) { break; } numberOfMessages++; @@ -2756,18 +2334,15 @@ public class PagingTest extends ActiveMQTestBase ClientProducer producerTransacted = sessionTransacted.createProducer(PagingTest.ADDRESS); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { message = session.createMessage(true); message.getBodyBuffer().writeBytes(body); message.putIntProperty(new SimpleString("id"), i); // Consume messages to force an eventual out of order delivery - if (i == 5) - { + if (i == 5) { ClientConsumer consumer = session.createConsumer(PagingTest.ADDRESS); - for (int j = 0; j < numberOfMessages; j++) - { + for (int j = 0; j < numberOfMessages; j++) { ClientMessage msg = consumer.receive(PagingTest.RECEIVE_TIMEOUT); msg.acknowledge(); Assert.assertNotNull(msg); @@ -2792,8 +2367,7 @@ public class PagingTest extends ActiveMQTestBase sessionTransacted.close(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { message = consumer.receive(PagingTest.RECEIVE_TIMEOUT); Assert.assertNotNull(message); @@ -2823,25 +2397,17 @@ public class PagingTest extends ActiveMQTestBase * Test under discussion at : http://community.jboss.org/thread/154061?tstart=0 */ @Test - public void testDepageDuringTransaction2() throws Exception - { + public void testDepageDuringTransaction2() throws Exception { boolean IS_DURABLE_MESSAGE = true; clearDataRecreateServerDirs(); Configuration config = createDefaultInVMConfig(); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator = createInVMNonHALocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); @@ -2864,16 +2430,14 @@ public class PagingTest extends ActiveMQTestBase ClientMessage message = null; int numberOfMessages = 0; - while (true) - { + while (true) { message = session.createMessage(IS_DURABLE_MESSAGE); message.getBodyBuffer().writeBytes(body); message.putIntProperty("id", numberOfMessages); message.putBooleanProperty("new", false); // Stop sending message as soon as we start paging - if (server.getPagingManager().getPageStore(PagingTest.ADDRESS).isPaging()) - { + if (server.getPagingManager().getPageStore(PagingTest.ADDRESS).isPaging()) { break; } numberOfMessages++; @@ -2885,18 +2449,15 @@ public class PagingTest extends ActiveMQTestBase session.start(); - for (int i = 1; i < 10; i++) - { + for (int i = 1; i < 10; i++) { message = session.createMessage(true); message.getBodyBuffer().writeBytes(body); message.putIntProperty(new SimpleString("id"), i); // Consume messages to force an eventual out of order delivery - if (i == 5) - { + if (i == 5) { ClientConsumer consumer = session.createConsumer(PagingTest.ADDRESS); - for (int j = 0; j < numberOfMessages; j++) - { + for (int j = 0; j < numberOfMessages; j++) { ClientMessage msg = consumer.receive(PagingTest.RECEIVE_TIMEOUT); msg.acknowledge(); assertEquals(j, msg.getIntProperty("id").intValue()); @@ -2925,8 +2486,7 @@ public class PagingTest extends ActiveMQTestBase sessionTransacted.close(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { message = consumer.receive(PagingTest.RECEIVE_TIMEOUT); Assert.assertNotNull(message); @@ -2949,24 +2509,16 @@ public class PagingTest extends ActiveMQTestBase } @Test - public void testDepageDuringTransaction3() throws Exception - { + public void testDepageDuringTransaction3() throws Exception { clearDataRecreateServerDirs(); Configuration config = createDefaultInVMConfig(); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator = createInVMNonHALocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); @@ -2982,8 +2534,7 @@ public class PagingTest extends ActiveMQTestBase sessionNonTX.start(); - for (int i = 0; i < 50; i++) - { + for (int i = 0; i < 50; i++) { ClientMessage message = sessionNonTX.createMessage(true); message.getBodyBuffer().writeBytes(body); message.putIntProperty(new SimpleString("id"), i); @@ -2991,10 +2542,8 @@ public class PagingTest extends ActiveMQTestBase producerTransacted.send(message); - if (i % 2 == 0) - { - for (int j = 0; j < 20; j++) - { + if (i % 2 == 0) { + for (int j = 0; j < 20; j++) { ClientMessage msgSend = sessionNonTX.createMessage(true); msgSend.putStringProperty(new SimpleString("tst"), new SimpleString("i=" + i + ", j=" + j)); msgSend.getBodyBuffer().writeBytes(new byte[10 * 1024]); @@ -3002,11 +2551,9 @@ public class PagingTest extends ActiveMQTestBase } assertTrue(server.getPagingManager().getPageStore(PagingTest.ADDRESS).isPaging()); } - else - { + else { ClientConsumer consumer = sessionNonTX.createConsumer(PagingTest.ADDRESS); - for (int j = 0; j < 20; j++) - { + for (int j = 0; j < 20; j++) { ClientMessage msgReceived = consumer.receive(10000); assertNotNull(msgReceived); msgReceived.acknowledge(); @@ -3016,11 +2563,9 @@ public class PagingTest extends ActiveMQTestBase } ClientConsumer consumerNonTX = sessionNonTX.createConsumer(PagingTest.ADDRESS); - while (true) - { + while (true) { ClientMessage msgReceived = consumerNonTX.receive(1000); - if (msgReceived == null) - { + if (msgReceived == null) { break; } msgReceived.acknowledge(); @@ -3035,8 +2580,7 @@ public class PagingTest extends ActiveMQTestBase sessionTransacted.close(); - for (int i = 0; i < 50; i++) - { + for (int i = 0; i < 50; i++) { ClientMessage message = consumer.receive(PagingTest.RECEIVE_TIMEOUT); Assert.assertNotNull(message); @@ -3057,19 +2601,12 @@ public class PagingTest extends ActiveMQTestBase } @Test - public void testDepageDuringTransaction4() throws Exception - { + public void testDepageDuringTransaction4() throws Exception { clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false) - .setJournalSyncTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false).setJournalSyncTransactional(false); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); @@ -3077,35 +2614,27 @@ public class PagingTest extends ActiveMQTestBase final int numberOfMessages = 10000; - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(false); + locator = createInVMNonHALocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(false); sf = createSessionFactory(locator); final byte[] body = new byte[MESSAGE_SIZE]; - Thread producerThread = new Thread() - { + Thread producerThread = new Thread() { @Override - public void run() - { + public void run() { ClientSession sessionProducer = null; - try - { + try { sessionProducer = sf.createSession(false, false); ClientProducer producer = sessionProducer.createProducer(ADDRESS); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = sessionProducer.createMessage(true); msg.getBodyBuffer().writeBytes(body); msg.putIntProperty("count", i); producer.send(msg); - if (i % 100 == 0 && i != 0) - { + if (i % 100 == 0 && i != 0) { sessionProducer.commit(); // Thread.sleep(500); } @@ -3114,22 +2643,17 @@ public class PagingTest extends ActiveMQTestBase sessionProducer.commit(); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); // >> junit report errors.incrementAndGet(); } - finally - { - try - { - if (sessionProducer != null) - { + finally { + try { + if (sessionProducer != null) { sessionProducer.close(); } } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); errors.incrementAndGet(); } @@ -3145,14 +2669,12 @@ public class PagingTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(PagingTest.ADDRESS); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = consumer.receive(5000); assertNotNull(msg); assertEquals(i, msg.getIntProperty("count").intValue()); msg.acknowledge(); - if (i > 0 && i % 10 == 0) - { + if (i > 0 && i % 10 == 0) { session.commit(); } } @@ -3170,19 +2692,12 @@ public class PagingTest extends ActiveMQTestBase } @Test - public void testOrderingNonTX() throws Exception - { + public void testOrderingNonTX() throws Exception { clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false) - .setJournalSyncTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false).setJournalSyncTransactional(false); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_SIZE * 2, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_SIZE * 2, new HashMap()); server.getConfiguration(); server.getConfiguration(); @@ -3193,9 +2708,7 @@ public class PagingTest extends ActiveMQTestBase final int numberOfMessages = 2000; - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); @@ -3203,26 +2716,21 @@ public class PagingTest extends ActiveMQTestBase final byte[] body = new byte[MESSAGE_SIZE]; - Thread producerThread = new Thread() - { + Thread producerThread = new Thread() { @Override - public void run() - { + public void run() { ClientSession sessionProducer = null; - try - { + try { sessionProducer = sf.createSession(true, true); ClientProducer producer = sessionProducer.createProducer(ADDRESS); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = sessionProducer.createMessage(true); msg.getBodyBuffer().writeBytes(body); msg.putIntProperty("count", i); producer.send(msg); - if (i == 1000) - { + if (i == 1000) { // The session is not TX, but we do this just to perform a round trip to the server // and make sure there are no pending messages sessionProducer.commit(); @@ -3237,22 +2745,17 @@ public class PagingTest extends ActiveMQTestBase log.info("Producer gone"); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); // >> junit report errors.incrementAndGet(); } - finally - { - try - { - if (sessionProducer != null) - { + finally { + try { + if (sessionProducer != null) { sessionProducer.close(); } } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); errors.incrementAndGet(); } @@ -3270,12 +2773,10 @@ public class PagingTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(PagingTest.ADDRESS); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = consumer.receive(5000); assertNotNull(msg); - if (i != msg.getIntProperty("count").intValue()) - { + if (i != msg.getIntProperty("count").intValue()) { log.info("Received " + i + " with property = " + msg.getIntProperty("count")); log.info("###### different"); } @@ -3291,29 +2792,21 @@ public class PagingTest extends ActiveMQTestBase } @Test - public void testPageOnSchedulingNoRestart() throws Exception - { + public void testPageOnSchedulingNoRestart() throws Exception { internalTestPageOnScheduling(false); } @Test - public void testPageOnSchedulingRestart() throws Exception - { + public void testPageOnSchedulingRestart() throws Exception { internalTestPageOnScheduling(true); } - public void internalTestPageOnScheduling(final boolean restart) throws Exception - { + public void internalTestPageOnScheduling(final boolean restart) throws Exception { clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); @@ -3321,9 +2814,7 @@ public class PagingTest extends ActiveMQTestBase final int numberOfBytes = 1024; - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); ClientSession session = sf.createSession(null, null, false, true, true, false, 0); @@ -3336,43 +2827,34 @@ public class PagingTest extends ActiveMQTestBase byte[] body = new byte[numberOfBytes]; - for (int j = 0; j < numberOfBytes; j++) - { + for (int j = 0; j < numberOfBytes; j++) { body[j] = ActiveMQTestBase.getSamplebyte(j); } long scheduledTime = System.currentTimeMillis() + 5000; - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = session.createMessage(true); message.getBodyBuffer().writeBytes(body); message.putIntProperty(new SimpleString("id"), i); - PagingStore store = server.getPagingManager() - .getPageStore(PagingTest.ADDRESS); + PagingStore store = server.getPagingManager().getPageStore(PagingTest.ADDRESS); // Worse scenario possible... only schedule what's on pages - if (store.getCurrentPage() != null) - { + if (store.getCurrentPage() != null) { message.putLongProperty(Message.HDR_SCHEDULED_DELIVERY_TIME, scheduledTime); } producer.send(message); } - if (restart) - { + if (restart) { session.close(); server.stop(); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); sf = createSessionFactory(locator); @@ -3384,8 +2866,7 @@ public class PagingTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage message2 = consumer.receive(PagingTest.RECEIVE_TIMEOUT); @@ -3396,21 +2877,16 @@ public class PagingTest extends ActiveMQTestBase Assert.assertNotNull(message2); Long scheduled = (Long) message2.getObjectProperty(Message.HDR_SCHEDULED_DELIVERY_TIME); - if (scheduled != null) - { + if (scheduled != null) { Assert.assertTrue("Scheduling didn't work", System.currentTimeMillis() >= scheduledTime); } - try - { + try { assertBodiesEqual(body, message2.getBodyBuffer()); } - catch (AssertionError e) - { + catch (AssertionError e) { PagingTest.log.info("Expected buffer:" + ActiveMQTestBase.dumpBytesHex(body, 40)); - PagingTest.log.info("Arriving buffer:" + ActiveMQTestBase.dumpBytesHex(message2.getBodyBuffer() - .toByteBuffer() - .array(), 40)); + PagingTest.log.info("Arriving buffer:" + ActiveMQTestBase.dumpBytesHex(message2.getBodyBuffer().toByteBuffer().array(), 40)); throw e; } } @@ -3421,17 +2897,12 @@ public class PagingTest extends ActiveMQTestBase } @Test - public void testRollbackOnSend() throws Exception - { + public void testRollbackOnSend() throws Exception { clearDataRecreateServerDirs(); Configuration config = createDefaultInVMConfig(); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); @@ -3439,9 +2910,7 @@ public class PagingTest extends ActiveMQTestBase final int numberOfMessages = 10; - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); ClientSession session = sf.createSession(null, null, false, false, true, false, 0); @@ -3452,14 +2921,12 @@ public class PagingTest extends ActiveMQTestBase ClientMessage message = null; - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = session.createMessage(true); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); - for (int j = 1; j <= numberOfIntegers; j++) - { + for (int j = 1; j <= numberOfIntegers; j++) { bodyLocal.writeInt(j); } @@ -3480,17 +2947,12 @@ public class PagingTest extends ActiveMQTestBase } @Test - public void testCommitOnSend() throws Exception - { + public void testCommitOnSend() throws Exception { clearDataRecreateServerDirs(); Configuration config = createDefaultInVMConfig(); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); @@ -3498,9 +2960,7 @@ public class PagingTest extends ActiveMQTestBase final int numberOfMessages = 500; - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); ClientSession session = sf.createSession(null, null, false, false, false, false, 0); @@ -3511,14 +2971,12 @@ public class PagingTest extends ActiveMQTestBase ClientMessage message = null; - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = session.createMessage(true); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); - for (int j = 1; j <= numberOfIntegers; j++) - { + for (int j = 1; j <= numberOfIntegers; j++) { bodyLocal.writeInt(j); } @@ -3537,11 +2995,7 @@ public class PagingTest extends ActiveMQTestBase server.stop(); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); @@ -3552,10 +3006,8 @@ public class PagingTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(PagingTest.ADDRESS); session.start(); - for (int i = 0; i < numberOfMessages; i++) - { - if (i == 55) - { + for (int i = 0; i < numberOfMessages; i++) { + if (i == 55) { System.out.println("i = 55"); } ClientMessage msg = consumer.receive(5000); @@ -3568,25 +3020,18 @@ public class PagingTest extends ActiveMQTestBase } @Test - public void testParialConsume() throws Exception - { + public void testParialConsume() throws Exception { clearDataRecreateServerDirs(); Configuration config = createDefaultInVMConfig(); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); final int numberOfMessages = 1000; - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); ClientSession session = sf.createSession(null, null, false, false, false, false, 0); @@ -3597,8 +3042,7 @@ public class PagingTest extends ActiveMQTestBase ClientMessage message = null; - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = session.createMessage(true); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); @@ -3618,11 +3062,7 @@ public class PagingTest extends ActiveMQTestBase server.stop(); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); @@ -3636,8 +3076,7 @@ public class PagingTest extends ActiveMQTestBase session.start(); // 347 = I just picked any odd number, not rounded, to make sure it's not at the beginning of any page - for (int i = 0; i < 347; i++) - { + for (int i = 0; i < 347; i++) { ClientMessage msg = consumer.receive(5000); assertEquals(i, msg.getIntProperty("id").intValue()); Assert.assertNotNull(msg); @@ -3651,11 +3090,7 @@ public class PagingTest extends ActiveMQTestBase server.stop(); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); @@ -3668,8 +3103,7 @@ public class PagingTest extends ActiveMQTestBase consumer = session.createConsumer(PagingTest.ADDRESS); session.start(); - for (int i = 347; i < numberOfMessages; i++) - { + for (int i = 347; i < numberOfMessages; i++) { ClientMessage msg = consumer.receive(5000); assertEquals(i, msg.getIntProperty("id").intValue()); Assert.assertNotNull(msg); @@ -3681,20 +3115,17 @@ public class PagingTest extends ActiveMQTestBase } @Test - public void testPageMultipleDestinations() throws Exception - { + public void testPageMultipleDestinations() throws Exception { internalTestPageMultipleDestinations(false); } @Test - public void testPageMultipleDestinationsTransacted() throws Exception - { + public void testPageMultipleDestinationsTransacted() throws Exception { internalTestPageMultipleDestinations(true); } @Test - public void testDropMessages() throws Exception - { + public void testDropMessages() throws Exception { clearDataRecreateServerDirs(); HashMap settings = new HashMap(); @@ -3710,9 +3141,7 @@ public class PagingTest extends ActiveMQTestBase final int numberOfMessages = 1000; - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); ClientSession session = sf.createSession(null, null, false, true, true, false, 0); @@ -3723,8 +3152,7 @@ public class PagingTest extends ActiveMQTestBase ClientMessage message = null; - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { byte[] body = new byte[1024]; message = session.createMessage(true); @@ -3737,8 +3165,7 @@ public class PagingTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < 6; i++) - { + for (int i = 0; i < 6; i++) { ClientMessage message2 = consumer.receive(PagingTest.RECEIVE_TIMEOUT); Assert.assertNotNull(message2); @@ -3748,12 +3175,9 @@ public class PagingTest extends ActiveMQTestBase Assert.assertNull(consumer.receiveImmediate()); - Assert.assertEquals(0, server.getPagingManager() - .getPageStore(PagingTest.ADDRESS) - .getAddressSize()); + Assert.assertEquals(0, server.getPagingManager().getPageStore(PagingTest.ADDRESS).getAddressSize()); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { byte[] body = new byte[1024]; message = session.createMessage(true); @@ -3762,8 +3186,7 @@ public class PagingTest extends ActiveMQTestBase producer.send(message); } - for (int i = 0; i < 6; i++) - { + for (int i = 0; i < 6; i++) { ClientMessage message2 = consumer.receive(PagingTest.RECEIVE_TIMEOUT); Assert.assertNotNull(message2); @@ -3779,8 +3202,7 @@ public class PagingTest extends ActiveMQTestBase producer = session.createProducer(PagingTest.ADDRESS); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { byte[] body = new byte[1024]; message = session.createMessage(true); @@ -3795,8 +3217,7 @@ public class PagingTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < 6; i++) - { + for (int i = 0; i < 6; i++) { ClientMessage message2 = consumer.receive(PagingTest.RECEIVE_TIMEOUT); Assert.assertNotNull(message2); @@ -3814,8 +3235,7 @@ public class PagingTest extends ActiveMQTestBase } @Test - public void testDropMessagesExpiring() throws Exception - { + public void testDropMessagesExpiring() throws Exception { clearDataRecreateServerDirs(); HashMap settings = new HashMap(); @@ -3844,34 +3264,28 @@ public class PagingTest extends ActiveMQTestBase ClientSession sessionConsumer = sf.createSession(); - class MyHandler implements MessageHandler - { + class MyHandler implements MessageHandler { + int count; - public void onMessage(ClientMessage message1) - { - try - { + public void onMessage(ClientMessage message1) { + try { Thread.sleep(1); } - catch (Exception e) - { + catch (Exception e) { } count++; - if (count % 1000 == 0) - { + if (count % 1000 == 0) { log.info("received " + count); } - try - { + try { message1.acknowledge(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -3883,8 +3297,7 @@ public class PagingTest extends ActiveMQTestBase consumer.setMessageHandler(new MyHandler()); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { byte[] body = new byte[1024]; message = sessionProducer.createMessage(false); @@ -3899,31 +3312,23 @@ public class PagingTest extends ActiveMQTestBase sessionConsumer.close(); } - private void internalTestPageMultipleDestinations(final boolean transacted) throws Exception - { + private void internalTestPageMultipleDestinations(final boolean transacted) throws Exception { Configuration config = createDefaultInVMConfig(); final int NUMBER_OF_BINDINGS = 100; int NUMBER_OF_MESSAGES = 2; - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(null, null, false, !transacted, true, false, 0); - for (int i = 0; i < NUMBER_OF_BINDINGS; i++) - { + for (int i = 0; i < NUMBER_OF_BINDINGS; i++) { session.createQueue(PagingTest.ADDRESS, new SimpleString("someQueue" + i), null, true); } @@ -3936,12 +3341,10 @@ public class PagingTest extends ActiveMQTestBase message = session.createMessage(true); message.getBodyBuffer().writeBytes(body); - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { producer.send(message); - if (transacted) - { + if (transacted) { session.commit(); } } @@ -3950,11 +3353,7 @@ public class PagingTest extends ActiveMQTestBase server.stop(); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); sf = createSessionFactory(locator); @@ -3963,11 +3362,9 @@ public class PagingTest extends ActiveMQTestBase session.start(); - for (int msg = 0; msg < NUMBER_OF_MESSAGES; msg++) - { + for (int msg = 0; msg < NUMBER_OF_MESSAGES; msg++) { - for (int i = 0; i < NUMBER_OF_BINDINGS; i++) - { + for (int i = 0; i < NUMBER_OF_BINDINGS; i++) { ClientConsumer consumer = session.createConsumer(new SimpleString("someQueue" + i)); ClientMessage message2 = consumer.receive(PagingTest.RECEIVE_TIMEOUT); @@ -3985,8 +3382,7 @@ public class PagingTest extends ActiveMQTestBase session.close(); - for (int i = 0; i < NUMBER_OF_BINDINGS; i++) - { + for (int i = 0; i < NUMBER_OF_BINDINGS; i++) { Queue queue = (Queue) server.getPostOffice().getBinding(new SimpleString("someQueue" + i)).getBindable(); Assert.assertEquals("Queue someQueue" + i + " was supposed to be empty", 0, getMessageCount(queue)); @@ -3995,20 +3391,14 @@ public class PagingTest extends ActiveMQTestBase } @Test - public void testSyncPage() throws Exception - { + public void testSyncPage() throws Exception { Configuration config = createDefaultInVMConfig(); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); - try - { + try { server.createQueue(PagingTest.ADDRESS, PagingTest.ADDRESS, null, true, false); final CountDownLatch pageUp = new CountDownLatch(0); @@ -4031,14 +3421,11 @@ public class PagingTest extends ActiveMQTestBase server.stop(); } - finally - { - try - { + finally { + try { server.stop(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } OperationContextImpl.clearContext(); @@ -4047,15 +3434,10 @@ public class PagingTest extends ActiveMQTestBase } @Test - public void testSyncPageTX() throws Exception - { + public void testSyncPageTX() throws Exception { Configuration config = createDefaultInVMConfig(); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); @@ -4079,8 +3461,7 @@ public class PagingTest extends ActiveMQTestBase } @Test - public void testPagingOneDestinationOnly() throws Exception - { + public void testPagingOneDestinationOnly() throws Exception { SimpleString PAGED_ADDRESS = new SimpleString("paged"); SimpleString NON_PAGED_ADDRESS = new SimpleString("non-paged"); @@ -4090,9 +3471,7 @@ public class PagingTest extends ActiveMQTestBase addresses.put("#", new AddressSettings()); - AddressSettings pagedDestination = new AddressSettings() - .setPageSizeBytes(1024) - .setMaxSizeBytes(10 * 1024); + AddressSettings pagedDestination = new AddressSettings().setPageSizeBytes(1024).setMaxSizeBytes(10 * 1024); addresses.put(PAGED_ADDRESS.toString(), pagedDestination); @@ -4113,8 +3492,7 @@ public class PagingTest extends ActiveMQTestBase int NUMBER_OF_MESSAGES = 100; - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { ClientMessage msg = session.createMessage(true); msg.getBodyBuffer().writeBytes(new byte[512]); @@ -4136,8 +3514,7 @@ public class PagingTest extends ActiveMQTestBase ClientMessage[] ackList = new ClientMessage[NUMBER_OF_MESSAGES]; - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { ClientMessage msg = consumerNonPaged.receive(5000); Assert.assertNotNull(msg); ackList[i] = msg; @@ -4145,8 +3522,7 @@ public class PagingTest extends ActiveMQTestBase Assert.assertNull(consumerNonPaged.receiveImmediate()); - for (ClientMessage ack : ackList) - { + for (ClientMessage ack : ackList) { ack.acknowledge(); } @@ -4156,8 +3532,7 @@ public class PagingTest extends ActiveMQTestBase ackList = null; - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { ClientMessage msg = consumerPaged.receive(5000); Assert.assertNotNull(msg); msg.acknowledge(); @@ -4170,8 +3545,7 @@ public class PagingTest extends ActiveMQTestBase } @Test - public void testPagingDifferentSizes() throws Exception - { + public void testPagingDifferentSizes() throws Exception { SimpleString PAGED_ADDRESS_A = new SimpleString("paged-a"); SimpleString PAGED_ADDRESS_B = new SimpleString("paged-b"); @@ -4181,17 +3555,13 @@ public class PagingTest extends ActiveMQTestBase addresses.put("#", new AddressSettings()); - AddressSettings pagedDestinationA = new AddressSettings() - .setPageSizeBytes(1024) - .setMaxSizeBytes(10 * 1024); + AddressSettings pagedDestinationA = new AddressSettings().setPageSizeBytes(1024).setMaxSizeBytes(10 * 1024); int NUMBER_MESSAGES_BEFORE_PAGING = 11; addresses.put(PAGED_ADDRESS_A.toString(), pagedDestinationA); - AddressSettings pagedDestinationB = new AddressSettings() - .setPageSizeBytes(2024) - .setMaxSizeBytes(25 * 1024); + AddressSettings pagedDestinationB = new AddressSettings().setPageSizeBytes(2024).setMaxSizeBytes(25 * 1024); addresses.put(PAGED_ADDRESS_B.toString(), pagedDestinationB); @@ -4211,8 +3581,7 @@ public class PagingTest extends ActiveMQTestBase int NUMBER_OF_MESSAGES = 100; - for (int i = 0; i < NUMBER_MESSAGES_BEFORE_PAGING; i++) - { + for (int i = 0; i < NUMBER_MESSAGES_BEFORE_PAGING; i++) { ClientMessage msg = session.createMessage(true); msg.getBodyBuffer().writeBytes(new byte[512]); @@ -4225,8 +3594,7 @@ public class PagingTest extends ActiveMQTestBase Assert.assertTrue(server.getPagingManager().getPageStore(PAGED_ADDRESS_A).isPaging()); Assert.assertFalse(server.getPagingManager().getPageStore(PAGED_ADDRESS_B).isPaging()); - for (int i = 0; i < NUMBER_MESSAGES_BEFORE_PAGING; i++) - { + for (int i = 0; i < NUMBER_MESSAGES_BEFORE_PAGING; i++) { ClientMessage msg = session.createMessage(true); msg.getBodyBuffer().writeBytes(new byte[512]); @@ -4239,8 +3607,7 @@ public class PagingTest extends ActiveMQTestBase Assert.assertTrue(server.getPagingManager().getPageStore(PAGED_ADDRESS_A).isPaging()); Assert.assertTrue(server.getPagingManager().getPageStore(PAGED_ADDRESS_B).isPaging()); - for (int i = NUMBER_MESSAGES_BEFORE_PAGING * 2; i < NUMBER_OF_MESSAGES; i++) - { + for (int i = NUMBER_MESSAGES_BEFORE_PAGING * 2; i < NUMBER_OF_MESSAGES; i++) { ClientMessage msg = session.createMessage(true); msg.getBodyBuffer().writeBytes(new byte[512]); @@ -4261,8 +3628,7 @@ public class PagingTest extends ActiveMQTestBase ClientConsumer consumerB = session.createConsumer(PAGED_ADDRESS_B); - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { ClientMessage msg = consumerA.receive(5000); Assert.assertNotNull("Couldn't receive a message on consumerA, iteration = " + i, msg); msg.acknowledge(); @@ -4274,8 +3640,7 @@ public class PagingTest extends ActiveMQTestBase Assert.assertTrue(server.getPagingManager().getPageStore(PAGED_ADDRESS_B).isPaging()); - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { ClientMessage msg = consumerB.receive(5000); Assert.assertNotNull(msg); msg.acknowledge(); @@ -4290,15 +3655,12 @@ public class PagingTest extends ActiveMQTestBase } @Test - public void testPageAndDepageRapidly() throws Exception - { + public void testPageAndDepageRapidly() throws Exception { boolean persistentMessages = true; clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false) - .setJournalFileSize(10 * 1024 * 1024); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false).setJournalFileSize(10 * 1024 * 1024); server = createServer(true, config, 512 * 1024, 1024 * 1024, new HashMap()); @@ -4308,10 +3670,7 @@ public class PagingTest extends ActiveMQTestBase final int numberOfMessages = 200; - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator = createInVMNonHALocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); @@ -4323,45 +3682,36 @@ public class PagingTest extends ActiveMQTestBase final AtomicInteger errors = new AtomicInteger(0); - Thread consumeThread = new Thread() - { + Thread consumeThread = new Thread() { @Override - public void run() - { + public void run() { ClientSession sessionConsumer = null; - try - { + try { sessionConsumer = sf.createSession(false, false); sessionConsumer.start(); ClientConsumer cons = sessionConsumer.createConsumer(ADDRESS); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = cons.receive(PagingTest.RECEIVE_TIMEOUT); assertNotNull(msg); msg.acknowledge(); - if (i % 20 == 0) - { + if (i % 20 == 0) { sessionConsumer.commit(); } } sessionConsumer.commit(); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); errors.incrementAndGet(); } - finally - { - try - { + finally { + try { sessionConsumer.close(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { e.printStackTrace(); errors.incrementAndGet(); } @@ -4376,8 +3726,7 @@ public class PagingTest extends ActiveMQTestBase byte[] body = new byte[messageSize]; - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = session.createMessage(persistentMessages); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); @@ -4397,10 +3746,7 @@ public class PagingTest extends ActiveMQTestBase long timeout = System.currentTimeMillis() + 5000; - while (System.currentTimeMillis() < timeout && (server.getPagingManager().getPageStore(ADDRESS).isPaging() || server.getPagingManager() - .getPageStore(ADDRESS) - .getNumberOfPages() != 1)) - { + while (System.currentTimeMillis() < timeout && (server.getPagingManager().getPageStore(ADDRESS).isPaging() || server.getPagingManager().getPageStore(ADDRESS).getNumberOfPages() != 1)) { Thread.sleep(1); } @@ -4411,31 +3757,19 @@ public class PagingTest extends ActiveMQTestBase } @Test - public void testTwoQueuesDifferentFilters() throws Exception - { + public void testTwoQueuesDifferentFilters() throws Exception { boolean persistentMessages = true; clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); final int numberOfMessages = 200; - locator = createInVMNonHALocator() - .setClientFailureCheckPeriod(120000) - .setConnectionTTL(5000000) - .setCallTimeout(120000) - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator = createInVMNonHALocator().setClientFailureCheckPeriod(120000).setConnectionTTL(5000000).setCallTimeout(120000).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); @@ -4444,12 +3778,8 @@ public class PagingTest extends ActiveMQTestBase // note: if you want to change this, numberOfMessages has to be a multiple of NQUEUES int NQUEUES = 2; - for (int i = 0; i < NQUEUES; i++) - { - session.createQueue(PagingTest.ADDRESS, - PagingTest.ADDRESS.concat("=" + i), - new SimpleString("propTest=" + i), - true); + for (int i = 0; i < NQUEUES; i++) { + session.createQueue(PagingTest.ADDRESS, PagingTest.ADDRESS.concat("=" + i), new SimpleString("propTest=" + i), true); } ClientProducer producer = session.createProducer(PagingTest.ADDRESS); @@ -4458,8 +3788,7 @@ public class PagingTest extends ActiveMQTestBase byte[] body = new byte[MESSAGE_SIZE]; - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = session.createMessage(persistentMessages); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); @@ -4470,8 +3799,7 @@ public class PagingTest extends ActiveMQTestBase message.putIntProperty("id", i); producer.send(message); - if (i % 1000 == 0) - { + if (i % 1000 == 0) { session.commit(); } } @@ -4480,12 +3808,10 @@ public class PagingTest extends ActiveMQTestBase session.start(); - for (int nqueue = 0; nqueue < NQUEUES; nqueue++) - { + for (int nqueue = 0; nqueue < NQUEUES; nqueue++) { ClientConsumer consumer = session.createConsumer(PagingTest.ADDRESS.concat("=" + nqueue)); - for (int i = 0; i < (numberOfMessages / NQUEUES); i++) - { + for (int i = 0; i < (numberOfMessages / NQUEUES); i++) { message = consumer.receive(500000); assertNotNull(message); message.acknowledge(); @@ -4504,8 +3830,7 @@ public class PagingTest extends ActiveMQTestBase store.getCursorProvider().cleanup(); long timeout = System.currentTimeMillis() + 5000; - while (store.isPaging() && timeout > System.currentTimeMillis()) - { + while (store.isPaging() && timeout > System.currentTimeMillis()) { Thread.sleep(100); } @@ -4514,20 +3839,14 @@ public class PagingTest extends ActiveMQTestBase } @Test - public void testTwoQueues() throws Exception - { + public void testTwoQueues() throws Exception { boolean persistentMessages = true; clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); @@ -4535,15 +3854,8 @@ public class PagingTest extends ActiveMQTestBase final int numberOfMessages = 1000; - try - { - ServerLocator locator = createInVMNonHALocator() - .setClientFailureCheckPeriod(120000) - .setConnectionTTL(5000000) - .setCallTimeout(120000) - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + try { + ServerLocator locator = createInVMNonHALocator().setClientFailureCheckPeriod(120000).setConnectionTTL(5000000).setCallTimeout(120000).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); ClientSessionFactory sf = locator.createSessionFactory(); @@ -4558,8 +3870,7 @@ public class PagingTest extends ActiveMQTestBase byte[] body = new byte[messageSize]; - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = session.createMessage(persistentMessages); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); @@ -4569,8 +3880,7 @@ public class PagingTest extends ActiveMQTestBase message.putIntProperty("propTest", i % 2 == 0 ? 1 : 2); producer.send(message); - if (i % 1000 == 0) - { + if (i % 1000 == 0) { session.commit(); } } @@ -4579,12 +3889,10 @@ public class PagingTest extends ActiveMQTestBase session.start(); - for (int msg = 1; msg <= 2; msg++) - { + for (int msg = 1; msg <= 2; msg++) { ClientConsumer consumer = session.createConsumer(PagingTest.ADDRESS.concat("=" + msg)); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = consumer.receive(5000); assertNotNull(message); message.acknowledge(); @@ -4605,8 +3913,7 @@ public class PagingTest extends ActiveMQTestBase store.getCursorProvider().cleanup(); long timeout = System.currentTimeMillis() + 5000; - while (store.isPaging() && timeout > System.currentTimeMillis()) - { + while (store.isPaging() && timeout > System.currentTimeMillis()) { Thread.sleep(100); } @@ -4618,45 +3925,29 @@ public class PagingTest extends ActiveMQTestBase locator.close(); } - finally - { - try - { + finally { + try { server.stop(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } } @Test - public void testTwoQueuesAndOneInativeQueue() throws Exception - { + public void testTwoQueuesAndOneInativeQueue() throws Exception { boolean persistentMessages = true; clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); - try - { - ServerLocator locator = createInVMNonHALocator() - .setClientFailureCheckPeriod(120000) - .setConnectionTTL(5000000) - .setCallTimeout(120000) - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + try { + ServerLocator locator = createInVMNonHALocator().setClientFailureCheckPeriod(120000).setConnectionTTL(5000000).setCallTimeout(120000).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); ClientSessionFactory sf = locator.createSessionFactory(); @@ -4666,10 +3957,7 @@ public class PagingTest extends ActiveMQTestBase session.createQueue(PagingTest.ADDRESS, PagingTest.ADDRESS.concat("=2"), null, true); // A queue with an impossible filter - session.createQueue(PagingTest.ADDRESS, - PagingTest.ADDRESS.concat("-3"), - new SimpleString("nothing='something'"), - true); + session.createQueue(PagingTest.ADDRESS, PagingTest.ADDRESS.concat("-3"), new SimpleString("nothing='something'"), true); PagingStore store = server.getPagingManager().getPageStore(ADDRESS); @@ -4691,8 +3979,7 @@ public class PagingTest extends ActiveMQTestBase session.start(); - for (int msg = 1; msg <= 2; msg++) - { + for (int msg = 1; msg <= 2; msg++) { ClientConsumer consumer = session.createConsumer(PagingTest.ADDRESS.concat("=" + msg)); message = consumer.receive(5000); @@ -4715,33 +4002,24 @@ public class PagingTest extends ActiveMQTestBase locator.close(); } - finally - { - try - { + finally { + try { server.stop(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } } @Test - public void testTwoQueuesConsumeOneRestart() throws Exception - { + public void testTwoQueuesConsumeOneRestart() throws Exception { boolean persistentMessages = true; clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); @@ -4749,15 +4027,8 @@ public class PagingTest extends ActiveMQTestBase final int numberOfMessages = 1000; - try - { - ServerLocator locator = createInVMNonHALocator() - .setClientFailureCheckPeriod(120000) - .setConnectionTTL(5000000) - .setCallTimeout(120000) - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + try { + ServerLocator locator = createInVMNonHALocator().setClientFailureCheckPeriod(120000).setConnectionTTL(5000000).setCallTimeout(120000).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); ClientSessionFactory sf = locator.createSessionFactory(); @@ -4772,8 +4043,7 @@ public class PagingTest extends ActiveMQTestBase byte[] body = new byte[messageSize]; - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = session.createMessage(persistentMessages); ActiveMQBuffer bodyLocal = message.getBodyBuffer(); @@ -4783,8 +4053,7 @@ public class PagingTest extends ActiveMQTestBase message.putIntProperty("propTest", i % 2 == 0 ? 1 : 2); producer.send(message); - if (i % 1000 == 0) - { + if (i % 1000 == 0) { session.commit(); } } @@ -4803,8 +4072,7 @@ public class PagingTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(PagingTest.ADDRESS.concat("=2")); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { message = consumer.receive(5000); assertNotNull(message); message.acknowledge(); @@ -4821,8 +4089,7 @@ public class PagingTest extends ActiveMQTestBase PagingStore store = server.getPagingManager().getPageStore(ADDRESS); // It's async, so need to wait a bit for it happening - while (timeout > System.currentTimeMillis() && store.isPaging()) - { + while (timeout > System.currentTimeMillis() && store.isPaging()) { Thread.sleep(100); } @@ -4839,31 +4106,23 @@ public class PagingTest extends ActiveMQTestBase locator.close(); } - finally - { - try - { + finally { + try { server.stop(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } } @Test - public void testDLAOnLargeMessageAndPaging() throws Exception - { + public void testDLAOnLargeMessageAndPaging() throws Exception { clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setThreadPoolMaxSize(5) - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setThreadPoolMaxSize(5).setJournalSyncNonTransactional(false); Map settings = new HashMap(); - AddressSettings dla = new AddressSettings() - .setMaxDeliveryAttempts(5) - .setDeadLetterAddress(new SimpleString("DLA")); + AddressSettings dla = new AddressSettings().setMaxDeliveryAttempts(5).setDeadLetterAddress(new SimpleString("DLA")); settings.put(ADDRESS.toString(), dla); server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, settings); @@ -4875,8 +4134,7 @@ public class PagingTest extends ActiveMQTestBase ServerLocator locator = null; ClientSessionFactory sf = null; ClientSession session = null; - try - { + try { locator = createInVMNonHALocator(); locator.setBlockOnNonDurableSend(true); @@ -4897,8 +4155,7 @@ public class PagingTest extends ActiveMQTestBase ClientProducer producer = session.createProducer(PagingTest.ADDRESS); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { log.debug("send message #" + i); ClientMessage message = session.createMessage(true); @@ -4908,8 +4165,7 @@ public class PagingTest extends ActiveMQTestBase producer.send(message); - if ((i + 1) % 2 == 0) - { + if ((i + 1) % 2 == 0) { session.commit(); } } @@ -4920,10 +4176,8 @@ public class PagingTest extends ActiveMQTestBase ClientConsumer cons = session.createConsumer(ADDRESS); - for (int msgNr = 0; msgNr < 2; msgNr++) - { - for (int i = 0; i < 5; i++) - { + for (int msgNr = 0; msgNr < 2; msgNr++) { + for (int i = 0; i < 5; i++) { ClientMessage msg = cons.receive(5000); assertNotNull(msg); @@ -4932,8 +4186,7 @@ public class PagingTest extends ActiveMQTestBase assertEquals("str" + msgNr, msg.getStringProperty("id")); - for (int j = 0; j < messageSize; j++) - { + for (int j = 0; j < messageSize; j++) { assertEquals(getSamplebyte(j), msg.getBodyBuffer().readByte()); } @@ -4943,8 +4196,7 @@ public class PagingTest extends ActiveMQTestBase pgStoreDLA.startPaging(); } - for (int i = 2; i < 100; i++) - { + for (int i = 2; i < 100; i++) { log.debug("Received message " + i); ClientMessage message = cons.receive(5000); assertNotNull("Message " + i + " wasn't received", message); @@ -4952,25 +4204,20 @@ public class PagingTest extends ActiveMQTestBase final AtomicInteger bytesOutput = new AtomicInteger(0); - message.setOutputStream(new OutputStream() - { + message.setOutputStream(new OutputStream() { @Override - public void write(int b) throws IOException - { + public void write(int b) throws IOException { bytesOutput.incrementAndGet(); } }); - try - { - if (!message.waitOutputStreamCompletion(10000)) - { + try { + if (!message.waitOutputStreamCompletion(10000)) { log.info(threadDump("dump")); fail("Couldn't finish large message receiving"); } } - catch (Throwable e) - { + catch (Throwable e) { log.info("output bytes = " + bytesOutput); log.info(threadDump("dump")); fail("Couldn't finish large message receiving for id=" + message.getStringProperty("id") + @@ -4986,8 +4233,7 @@ public class PagingTest extends ActiveMQTestBase cons = session.createConsumer("DLA"); - for (int i = 0; i < 2; i++) - { + for (int i = 0; i < 2; i++) { assertNotNull(cons.receive(5000)); } @@ -5011,8 +4257,7 @@ public class PagingTest extends ActiveMQTestBase cons = session.createConsumer(ADDRESS); - for (int i = 2; i < 100; i++) - { + for (int i = 2; i < 100; i++) { log.debug("Received message " + i); ClientMessage message = cons.receive(5000); assertNotNull(message); @@ -5021,11 +4266,9 @@ public class PagingTest extends ActiveMQTestBase message.acknowledge(); - message.setOutputStream(new OutputStream() - { + message.setOutputStream(new OutputStream() { @Override - public void write(int b) throws IOException - { + public void write(int b) throws IOException { } }); @@ -5039,16 +4282,14 @@ public class PagingTest extends ActiveMQTestBase cons = session.createConsumer("DLA"); - for (int msgNr = 0; msgNr < 2; msgNr++) - { + for (int msgNr = 0; msgNr < 2; msgNr++) { ClientMessage msg = cons.receive(10000); assertNotNull(msg); assertEquals("str" + msgNr, msg.getStringProperty("id")); - for (int i = 0; i < messageSize; i++) - { + for (int i = 0; i < messageSize; i++) { assertEquals(getSamplebyte(i), msg.getBodyBuffer().readByte()); } @@ -5071,8 +4312,7 @@ public class PagingTest extends ActiveMQTestBase pgStoreAddress.getCursorProvider().cleanup(); - while (timeout > System.currentTimeMillis() && pgStoreAddress.isPaging()) - { + while (timeout > System.currentTimeMillis() && pgStoreAddress.isPaging()) { Thread.sleep(50); } @@ -5080,35 +4320,26 @@ public class PagingTest extends ActiveMQTestBase session.commit(); } - finally - { + finally { session.close(); sf.close(); locator.close(); - try - { + try { server.stop(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } } @Test - public void testExpireLargeMessageOnPaging() throws Exception - { + public void testExpireLargeMessageOnPaging() throws Exception { clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setMessageExpiryScanPeriod(500) - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setMessageExpiryScanPeriod(500).setJournalSyncNonTransactional(false); Map settings = new HashMap(); - AddressSettings dla = new AddressSettings() - .setMaxDeliveryAttempts(5) - .setDeadLetterAddress(new SimpleString("DLA")) - .setExpiryAddress(new SimpleString("DLA")); + AddressSettings dla = new AddressSettings().setMaxDeliveryAttempts(5).setDeadLetterAddress(new SimpleString("DLA")).setExpiryAddress(new SimpleString("DLA")); settings.put(ADDRESS.toString(), dla); server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, settings); @@ -5117,12 +4348,8 @@ public class PagingTest extends ActiveMQTestBase final int messageSize = 20; - try - { - ServerLocator locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + try { + ServerLocator locator = createInVMNonHALocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); ClientSessionFactory sf = locator.createSessionFactory(); @@ -5140,8 +4367,7 @@ public class PagingTest extends ActiveMQTestBase ClientMessage message = null; - for (int i = 0; i < 500; i++) - { + for (int i = 0; i < 500; i++) { if (i % 100 == 0) log.info("send message #" + i); message = session.createMessage(true); @@ -5150,15 +4376,12 @@ public class PagingTest extends ActiveMQTestBase message.setExpiration(System.currentTimeMillis() + 2000); - if (i % 2 == 0) - { + if (i % 2 == 0) { message.setBodyInputStream(createFakeLargeStream(messageSize)); } - else - { + else { byte[] bytes = new byte[messageSize]; - for (int s = 0; s < bytes.length; s++) - { + for (int s = 0; s < bytes.length; s++) { bytes[s] = getSamplebyte(s); } message.getBodyBuffer().writeBytes(bytes); @@ -5166,11 +4389,9 @@ public class PagingTest extends ActiveMQTestBase producer.send(message); - if ((i + 1) % 2 == 0) - { + if ((i + 1) % 2 == 0) { session.commit(); - if (i < 400) - { + if (i < 400) { pgStoreAddress.forceAnotherPage(); } } @@ -5202,18 +4423,15 @@ public class PagingTest extends ActiveMQTestBase ClientConsumer cons = session.createConsumer("DLA"); - for (int i = 0; i < 500; i++) - { + for (int i = 0; i < 500; i++) { log.info("Received message " + i); message = cons.receive(10000); assertNotNull(message); message.acknowledge(); - message.saveToOutputStream(new OutputStream() - { + message.saveToOutputStream(new OutputStream() { @Override - public void write(int b) throws IOException - { + public void write(int b) throws IOException { } }); @@ -5229,8 +4447,7 @@ public class PagingTest extends ActiveMQTestBase pgStoreAddress = server.getPagingManager().getPageStore(ADDRESS); - while (timeout > System.currentTimeMillis() && pgStoreAddress.isPaging()) - { + while (timeout > System.currentTimeMillis() && pgStoreAddress.isPaging()) { Thread.sleep(50); } @@ -5238,15 +4455,12 @@ public class PagingTest extends ActiveMQTestBase session.close(); } - finally - { + finally { locator.close(); - try - { + try { server.stop(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } } @@ -5258,13 +4472,10 @@ public class PagingTest extends ActiveMQTestBase * -Djava.util.logging.manager=org.jboss.logmanager.LogManager -Dlogging.configuration=file:/tests/config/logging.properties * * Note: Idea should get these from the pom and you shouldn't need to do this. - */ - public void testFailMessagesNonDurable() throws Exception - { + */ public void testFailMessagesNonDurable() throws Exception { AssertionLoggerHandler.startCapture(); - try - { + try { clearDataRecreateServerDirs(); Configuration config = createDefaultInVMConfig(); @@ -5280,9 +4491,7 @@ public class PagingTest extends ActiveMQTestBase server.start(); - locator.setBlockOnNonDurableSend(false) - .setBlockOnDurableSend(false) - .setBlockOnAcknowledge(true); + locator.setBlockOnNonDurableSend(false).setBlockOnDurableSend(false).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); ClientSession session = sf.createSession(true, true, 0); @@ -5296,8 +4505,7 @@ public class PagingTest extends ActiveMQTestBase int biggerMessageSize = 1024; byte[] body = new byte[biggerMessageSize]; ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= biggerMessageSize; j++) - { + for (int j = 1; j <= biggerMessageSize; j++) { bb.put(getSamplebyte(j)); } @@ -5305,8 +4513,7 @@ public class PagingTest extends ActiveMQTestBase // Send enough messages to fill up the address, but don't test for an immediate exception because we do not block // on non-durable send. Instead of receiving an exception immediately the exception will be logged on the server. - for (int i = 0; i < 32; i++) - { + for (int i = 0; i < 32; i++) { producer.send(message); } @@ -5320,8 +4527,7 @@ public class PagingTest extends ActiveMQTestBase session.start(); // Once the destination is full and the client has run out of credits then it will receive an exception - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { validateExceptionOnSending(producer, message); } @@ -5333,30 +4539,25 @@ public class PagingTest extends ActiveMQTestBase boolean exception = false; - try - { - for (int i = 0; i < 1000; i++) - { + try { + for (int i = 0; i < 1000; i++) { // this send will succeed on the server producer.send(message); } } - catch (Exception e) - { + catch (Exception e) { exception = true; } assertTrue("Expected to throw an exception", exception); } - finally - { + finally { AssertionLoggerHandler.stopCapture(); } } @Test - public void testFailMessagesDurable() throws Exception - { + public void testFailMessagesDurable() throws Exception { clearDataRecreateServerDirs(); Configuration config = createDefaultInVMConfig(); @@ -5372,9 +4573,7 @@ public class PagingTest extends ActiveMQTestBase server.start(); - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); ClientSession session = sf.createSession(true, true, 0); @@ -5388,8 +4587,7 @@ public class PagingTest extends ActiveMQTestBase int biggerMessageSize = 1024; byte[] body = new byte[biggerMessageSize]; ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= biggerMessageSize; j++) - { + for (int j = 1; j <= biggerMessageSize; j++) { bb.put(getSamplebyte(j)); } @@ -5398,14 +4596,11 @@ public class PagingTest extends ActiveMQTestBase // Send enough messages to fill up the address and test for an exception. // The address will actually fill up after 3 messages. Also, it takes 32 messages for the client's // credits to run out. - for (int i = 0; i < 50; i++) - { - if (i > 2) - { + for (int i = 0; i < 50; i++) { + if (i > 2) { validateExceptionOnSending(producer, message); } - else - { + else { producer.send(message); } } @@ -5422,16 +4617,13 @@ public class PagingTest extends ActiveMQTestBase boolean exception = false; - try - { - for (int i = 0; i < 1000; i++) - { + try { + for (int i = 0; i < 1000; i++) { // this send will succeed on the server producer.send(message); } } - catch (Exception e) - { + catch (Exception e) { exception = true; } @@ -5439,8 +4631,7 @@ public class PagingTest extends ActiveMQTestBase } @Test - public void testFailMessagesDuplicates() throws Exception - { + public void testFailMessagesDuplicates() throws Exception { clearDataRecreateServerDirs(); Configuration config = createDefaultInVMConfig(); @@ -5456,9 +4647,7 @@ public class PagingTest extends ActiveMQTestBase server.start(); - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); sf = createSessionFactory(locator); ClientSession session = addClientSession(sf.createSession(true, true, 0)); @@ -5472,8 +4661,7 @@ public class PagingTest extends ActiveMQTestBase int biggerMessageSize = 1024; byte[] body = new byte[biggerMessageSize]; ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= biggerMessageSize; j++) - { + for (int j = 1; j <= biggerMessageSize; j++) { bb.put(getSamplebyte(j)); } @@ -5515,8 +4703,7 @@ public class PagingTest extends ActiveMQTestBase consumer = session.createConsumer(ADDRESS); - for (int i = 0; i < 3; i++) - { + for (int i = 0; i < 3; i++) { msgReceived = consumer.receive(5000); assertNotNull(msgReceived); msgReceived.acknowledge(); @@ -5527,17 +4714,14 @@ public class PagingTest extends ActiveMQTestBase /** * This method validates if sending a message will throw an exception */ - private void validateExceptionOnSending(ClientProducer producer, ClientMessage message) - { + private void validateExceptionOnSending(ClientProducer producer, ClientMessage message) { ActiveMQException expected = null; - try - { + try { // after the address is full this send should fail (since the address full policy is FAIL) producer.send(message); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { expected = e; } @@ -5545,36 +4729,26 @@ public class PagingTest extends ActiveMQTestBase assertEquals(ActiveMQExceptionType.ADDRESS_FULL, expected.getType()); } - @Test - public void testSpreadMessagesWithFilterWithDeadConsumer() throws Exception - { + public void testSpreadMessagesWithFilterWithDeadConsumer() throws Exception { testSpreadMessagesWithFilter(true); } @Test - public void testSpreadMessagesWithFilterWithoutDeadConsumer() throws Exception - { + public void testSpreadMessagesWithFilterWithoutDeadConsumer() throws Exception { testSpreadMessagesWithFilter(false); } @Test - public void testRouteOnTopWithMultipleQueues() throws Exception - { + public void testRouteOnTopWithMultipleQueues() throws Exception { - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); - ServerLocator locator = createInVMNonHALocator() - .setBlockOnDurableSend(false); + ServerLocator locator = createInVMNonHALocator().setBlockOnDurableSend(false); ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(false, true, 0); @@ -5596,7 +4770,6 @@ public class PagingTest extends ActiveMQTestBase prod.send(msg); session.commit(); - session.start(); ClientConsumer cons1 = session.createConsumer("Q1"); msg = cons1.receive(5000); @@ -5607,10 +4780,8 @@ public class PagingTest extends ActiveMQTestBase msg = cons2.receive(5000); assertNotNull(msg); - queue.getPageSubscription().getPagingStore().forceAnotherPage(); - msg = session.createMessage(true); msg.putIntProperty("dest", 1); prod.send(msg); @@ -5620,34 +4791,25 @@ public class PagingTest extends ActiveMQTestBase assertNotNull(msg); msg.acknowledge(); - queue.getPageSubscription().cleanupEntries(false); - System.out.println("Waiting there"); server.stop(); } // https://issues.jboss.org/browse/HORNETQ-1042 - spread messages because of filters - public void testSpreadMessagesWithFilter(boolean deadConsumer) throws Exception - { + public void testSpreadMessagesWithFilter(boolean deadConsumer) throws Exception { clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); - try - { + try { ServerLocator locator = createInVMNonHALocator(); locator.setBlockOnDurableSend(false); ClientSessionFactory sf = locator.createSessionFactory(); @@ -5656,8 +4818,7 @@ public class PagingTest extends ActiveMQTestBase session.createQueue(ADDRESS.toString(), "Q1", "destQ=1 or both=true", true); session.createQueue(ADDRESS.toString(), "Q2", "destQ=2 or both=true", true); - if (deadConsumer) - { + if (deadConsumer) { // This queue won't receive any messages session.createQueue(ADDRESS.toString(), "Q3", "destQ=3", true); } @@ -5668,16 +4829,13 @@ public class PagingTest extends ActiveMQTestBase final AtomicInteger consumerQ3Msgs = new AtomicInteger(0); - if (deadConsumer) - { + if (deadConsumer) { sessionConsumerQ3 = sf.createSession(true, true); ClientConsumer consumerQ3 = sessionConsumerQ3.createConsumer("Q3"); - consumerQ3.setMessageHandler(new MessageHandler() - { + consumerQ3.setMessageHandler(new MessageHandler() { - public void onMessage(ClientMessage message) - { + public void onMessage(ClientMessage message) { System.out.println("Received an unexpected message"); consumerQ3Msgs.incrementAndGet(); } @@ -5698,16 +4856,14 @@ public class PagingTest extends ActiveMQTestBase ClientProducer producer = session.createProducer(ADDRESS); // send an initial burst that will put the system into page mode. The initial burst will be towards Q1 only - for (int i = 0; i < initialBurst; i++) - { + for (int i = 0; i < initialBurst; i++) { ClientMessage m = session.createMessage(true); m.getBodyBuffer().writeBytes(bodyWrite); m.putIntProperty("destQ", 1); m.putBooleanProperty("both", false); m.putBooleanProperty("initialBurst", true); producer.send(m); - if (i % 100 == 0) - { + if (i % 100 == 0) { session.commit(); } } @@ -5716,8 +4872,7 @@ public class PagingTest extends ActiveMQTestBase pageStore.forceAnotherPage(); - for (int i = 0; i < messagesSentAfterBurst; i++) - { + for (int i = 0; i < messagesSentAfterBurst; i++) { { ClientMessage m = session.createMessage(true); m.getBodyBuffer().writeBytes(bodyWrite); @@ -5728,8 +4883,7 @@ public class PagingTest extends ActiveMQTestBase producer.send(m); } - if (i % 10 != 0) - { + if (i % 10 != 0) { ClientMessage m = session.createMessage(true); m.getBodyBuffer().writeBytes(bodyWrite); m.putIntProperty("destQ", 2); @@ -5739,11 +4893,9 @@ public class PagingTest extends ActiveMQTestBase producer.send(m); } - if (i > 0 && i % 10 == 0) - { + if (i > 0 && i % 10 == 0) { session.commit(); - if (i + 10 < messagesSentAfterBurst) - { + if (i + 10 < messagesSentAfterBurst) { pageStore.forceAnotherPage(); } } @@ -5759,8 +4911,7 @@ public class PagingTest extends ActiveMQTestBase // initial burst - for (int i = 0; i < initialBurst; i++) - { + for (int i = 0; i < initialBurst; i++) { ClientMessage m = consumerQ1.receive(5000); assertNotNull(m); assertEquals(1, m.getIntProperty("destQ").intValue()); @@ -5770,8 +4921,7 @@ public class PagingTest extends ActiveMQTestBase // This will consume messages from the beginning of the queue only ClientConsumer consumerInitial = session.createConsumer("Q_initial"); - for (int i = 0; i < initialBurst; i++) - { + for (int i = 0; i < initialBurst; i++) { ClientMessage m = consumerInitial.receive(5000); assertNotNull(m); assertEquals(1, m.getIntProperty("destQ").intValue()); @@ -5783,12 +4933,10 @@ public class PagingTest extends ActiveMQTestBase // messages from Q1 - for (int i = 0; i < messagesSentAfterBurst; i++) - { + for (int i = 0; i < messagesSentAfterBurst; i++) { ClientMessage m = consumerQ1.receive(5000); assertNotNull(m); - if (!m.getBooleanProperty("both")) - { + if (!m.getBooleanProperty("both")) { assertEquals(1, m.getIntProperty("destQ").intValue()); } assertEquals(i, m.getIntProperty("i").intValue()); @@ -5797,13 +4945,11 @@ public class PagingTest extends ActiveMQTestBase session.commit(); } - for (int i = 0; i < messagesSentAfterBurst; i++) - { + for (int i = 0; i < messagesSentAfterBurst; i++) { ClientMessage m = consumerQ2.receive(5000); assertNotNull(m); - if (!m.getBooleanProperty("both")) - { + if (!m.getBooleanProperty("both")) { assertEquals(2, m.getIntProperty("destQ").intValue()); } assertEquals(i, m.getIntProperty("i").intValue()); @@ -5814,8 +4960,7 @@ public class PagingTest extends ActiveMQTestBase waitForNotPaging(serverQueue); - if (sessionConsumerQ3 != null) - { + if (sessionConsumerQ3 != null) { sessionConsumerQ3.close(); } assertEquals(0, consumerQ3Msgs.intValue()); @@ -5824,8 +4969,7 @@ public class PagingTest extends ActiveMQTestBase locator.close(); } - finally - { + finally { server.stop(); } } @@ -5833,25 +4977,17 @@ public class PagingTest extends ActiveMQTestBase // We send messages to pages, create a big hole (a few pages without any messages), ack everything // and expect it to move to the next page @Test - public void testPageHole() throws Throwable - { + public void testPageHole() throws Throwable { clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); - try - { - ServerLocator locator = createInVMNonHALocator() - .setBlockOnDurableSend(true); + try { + ServerLocator locator = createInVMNonHALocator().setBlockOnDurableSend(true); ClientSessionFactory sf = locator.createSessionFactory(); ClientSession session = sf.createSession(true, true, 0); @@ -5868,14 +5004,12 @@ public class PagingTest extends ActiveMQTestBase msg.putIntProperty("dest", 1); prod.send(msg); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { msg = session.createMessage(true); msg.putIntProperty("dest", 2); prod.send(msg); - if (i > 0 && i % 10 == 0) - { + if (i > 0 && i % 10 == 0) { store.forceAnotherPage(); } } @@ -5889,8 +5023,7 @@ public class PagingTest extends ActiveMQTestBase msgReceivedCons1.acknowledge(); ClientConsumer cons2 = session.createConsumer("Q2"); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage msgReceivedCons2 = cons2.receive(1000); assertNotNull(msgReceivedCons2); msgReceivedCons2.acknowledge(); @@ -5898,11 +5031,9 @@ public class PagingTest extends ActiveMQTestBase session.commit(); // It will send another message when it's mid consumed - if (i == 20) - { + if (i == 20) { // wait at least one page to be deleted before sending a new one - for (long timeout = System.currentTimeMillis() + 5000; timeout > System.currentTimeMillis() && store.checkPageFileExists(2); ) - { + for (long timeout = System.currentTimeMillis() + 5000; timeout > System.currentTimeMillis() && store.checkPageFileExists(2); ) { Thread.sleep(10); } msg = session.createMessage(true); @@ -5924,45 +5055,33 @@ public class PagingTest extends ActiveMQTestBase waitForNotPaging(store); } - finally - { + finally { server.stop(); } } - @Test - public void testMultiFiltersBrowsing() throws Throwable - { + public void testMultiFiltersBrowsing() throws Throwable { internalTestMultiFilters(true); } @Test - public void testMultiFiltersRegularConsumer() throws Throwable - { + public void testMultiFiltersRegularConsumer() throws Throwable { internalTestMultiFilters(false); } - public void internalTestMultiFilters(boolean browsing) throws Throwable - { + public void internalTestMultiFilters(boolean browsing) throws Throwable { clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); - try - { - ServerLocator locator = createInVMNonHALocator() - .setBlockOnDurableSend(true); + try { + ServerLocator locator = createInVMNonHALocator().setBlockOnDurableSend(true); ClientSessionFactory sf = locator.createSessionFactory(); ClientSession session = sf.createSession(true, true, 0); @@ -5975,29 +5094,25 @@ public class PagingTest extends ActiveMQTestBase ClientMessage msg = null; store.startPaging(); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { msg = session.createMessage(true); msg.putStringProperty("color", "red"); msg.putIntProperty("count", i); prod.send(msg); - if (i > 0 && i % 10 == 0) - { + if (i > 0 && i % 10 == 0) { store.startPaging(); store.forceAnotherPage(); } } - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { msg = session.createMessage(true); msg.putStringProperty("color", "green"); msg.putIntProperty("count", i); prod.send(msg); - if (i > 0 && i % 10 == 0) - { + if (i > 0 && i % 10 == 0) { store.startPaging(); store.forceAnotherPage(); } @@ -6010,26 +5125,21 @@ public class PagingTest extends ActiveMQTestBase session = sf.createSession(false, false, 0); session.start(); - ClientConsumer cons1; - if (browsing) - { + if (browsing) { cons1 = session.createConsumer("Q1", "color='green'", true); } - else - { + else { cons1 = session.createConsumer("Q1", "color='red'", false); } - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { msg = cons1.receive(5000); System.out.println("Received " + msg); assertNotNull(msg); - if (!browsing) - { + if (!browsing) { msg.acknowledge(); } } @@ -6038,32 +5148,23 @@ public class PagingTest extends ActiveMQTestBase session.close(); } - finally - { + finally { server.stop(); } } - @Test - public void testPendingACKOutOfOrder() throws Throwable - { + public void testPendingACKOutOfOrder() throws Throwable { clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); - try - { + try { ServerLocator locator = createInVMNonHALocator(); locator.setBlockOnDurableSend(false); ClientSessionFactory sf = locator.createSessionFactory(); @@ -6075,18 +5176,14 @@ public class PagingTest extends ActiveMQTestBase store.startPaging(); - ClientProducer prod = session.createProducer(ADDRESS); - - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage msg = session.createMessage(true); msg.putIntProperty("count", i); prod.send(msg); session.commit(); - if ((i + 1) % 5 == 0 && i < 50) - { + if ((i + 1) % 5 == 0 && i < 50) { store.forceAnotherPage(); } } @@ -6095,13 +5192,11 @@ public class PagingTest extends ActiveMQTestBase ClientConsumer cons1 = session.createConsumer("Q1"); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage msg = cons1.receive(5000); assertNotNull(msg); - if (i == 13) - { + if (i == 13) { msg.individualAcknowledge(); } } @@ -6124,9 +5219,7 @@ public class PagingTest extends ActiveMQTestBase cons1 = session.createConsumer("Q1"); session.start(); - - for (int i = 0; i < 99; i++) - { + for (int i = 0; i < 99; i++) { ClientMessage msg = cons1.receive(5000); assertNotNull(msg); System.out.println("count = " + msg.getIntProperty("count")); @@ -6135,12 +5228,10 @@ public class PagingTest extends ActiveMQTestBase assertNull(cons1.receiveImmediate()); - session.close(); waitForNotPaging(store); } - finally - { + finally { server.stop(); } @@ -6148,23 +5239,16 @@ public class PagingTest extends ActiveMQTestBase // Test a scenario where a page was complete and now needs to be cleared @Test - public void testPageCompleteWasLive() throws Throwable - { + public void testPageCompleteWasLive() throws Throwable { clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); - try - { + try { ServerLocator locator = createInVMNonHALocator(); locator.setBlockOnDurableSend(false); ClientSessionFactory sf = locator.createSessionFactory(); @@ -6177,7 +5261,6 @@ public class PagingTest extends ActiveMQTestBase store.startPaging(); - ClientProducer prod = session.createProducer(ADDRESS); ClientMessage msg = session.createMessage(true); @@ -6222,32 +5305,22 @@ public class PagingTest extends ActiveMQTestBase session.close(); - waitForNotPaging(store); } - finally - { + finally { server.stop(); } } - @Test - public void testNoCursors() throws Exception - { - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + public void testNoCursors() throws Exception { + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); - ServerLocator locator = createInVMNonHALocator(); ClientSessionFactory sf = locator.createSessionFactory(); ClientSession session = sf.createSession(); @@ -6255,8 +5328,7 @@ public class PagingTest extends ActiveMQTestBase session.createQueue(ADDRESS, ADDRESS, true); ClientProducer prod = session.createProducer(ADDRESS); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { Message msg = session.createMessage(true); msg.getBodyBuffer().writeBytes(new byte[1024]); prod.send(msg); @@ -6277,25 +5349,18 @@ public class PagingTest extends ActiveMQTestBase // Test a scenario where a page was complete and now needs to be cleared @Test - public void testMoveMessages() throws Throwable - { + public void testMoveMessages() throws Throwable { clearDataRecreateServerDirs(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false); - server = createServer(true, - config, - PagingTest.PAGE_SIZE, - PagingTest.PAGE_MAX, - new HashMap()); + server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap()); server.start(); final int LARGE_MESSAGE_SIZE = 1024 * 1024; - try - { + try { ServerLocator locator = createInVMNonHALocator(); locator.setBlockOnDurableSend(false); ClientSessionFactory sf = locator.createSessionFactory(); @@ -6306,15 +5371,12 @@ public class PagingTest extends ActiveMQTestBase PagingStore store = server.getPagingManager().getPageStore(new SimpleString("Q1")); - ClientProducer prod = session.createProducer("Q1"); - for (int i = 0; i < 50; i++) - { + for (int i = 0; i < 50; i++) { ClientMessage msg = session.createMessage(true); msg.putIntProperty("count", i); - if (i > 0 && i % 10 == 0) - { + if (i > 0 && i % 10 == 0) { msg.setBodyInputStream(createFakeLargeStream(LARGE_MESSAGE_SIZE)); } prod.send(msg); @@ -6322,17 +5384,14 @@ public class PagingTest extends ActiveMQTestBase session.commit(); store.startPaging(); - for (int i = 50; i < 100; i++) - { + for (int i = 50; i < 100; i++) { ClientMessage msg = session.createMessage(true); msg.putIntProperty("count", i); - if (i % 10 == 0) - { + if (i % 10 == 0) { msg.setBodyInputStream(createFakeLargeStream(LARGE_MESSAGE_SIZE)); } prod.send(msg); - if (i % 10 == 0) - { + if (i % 10 == 0) { session.commit(); store.forceAnotherPage(); } @@ -6360,16 +5419,13 @@ public class PagingTest extends ActiveMQTestBase ClientConsumer cons = session.createConsumer("Q2"); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage msg = cons.receive(10000); assertNotNull(msg); - if (i > 0 && i % 10 == 0) - { + if (i > 0 && i % 10 == 0) { byte[] largeMessageRead = new byte[LARGE_MESSAGE_SIZE]; msg.getBodyBuffer().readBytes(largeMessageRead); - for (int j = 0; j < LARGE_MESSAGE_SIZE; j++) - { + for (int j = 0; j < LARGE_MESSAGE_SIZE; j++) { assertEquals(largeMessageRead[j], getSamplebyte(j)); } } @@ -6386,76 +5442,61 @@ public class PagingTest extends ActiveMQTestBase locator.close(); } - finally - { + finally { server.stop(); } } - @Override - protected Configuration createDefaultInVMConfig() throws Exception - { - return super.createDefaultInVMConfig() - .setJournalSyncNonTransactional(false); + protected Configuration createDefaultInVMConfig() throws Exception { + return super.createDefaultInVMConfig().setJournalSyncNonTransactional(false); } - private static final class DummyOperationContext implements OperationContext - { + private static final class DummyOperationContext implements OperationContext { + private final CountDownLatch pageUp; private final CountDownLatch pageDone; - public DummyOperationContext(CountDownLatch pageUp, CountDownLatch pageDone) - { + public DummyOperationContext(CountDownLatch pageUp, CountDownLatch pageDone) { this.pageDone = pageDone; this.pageUp = pageUp; } - public void onError(int errorCode, String errorMessage) - { + public void onError(int errorCode, String errorMessage) { } - public void done() - { + public void done() { } - public void storeLineUp() - { + public void storeLineUp() { } - public boolean waitCompletion(long timeout) throws Exception - { + public boolean waitCompletion(long timeout) throws Exception { return false; } - public void waitCompletion() throws Exception - { + public void waitCompletion() throws Exception { } - public void replicationLineUp() - { + public void replicationLineUp() { } - public void replicationDone() - { + public void replicationDone() { } - public void pageSyncLineUp() - { + public void pageSyncLineUp() { pageUp.countDown(); } - public void pageSyncDone() - { + public void pageSyncDone() { pageDone.countDown(); } - public void executeOnCompletion(IOCallback runnable) - { + public void executeOnCompletion(IOCallback runnable) { } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ProducerCloseTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ProducerCloseTest.java index 63b48bc20b..9f1e9b277c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ProducerCloseTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ProducerCloseTest.java @@ -30,8 +30,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class ProducerCloseTest extends ActiveMQTestBase -{ +public class ProducerCloseTest extends ActiveMQTestBase { private ActiveMQServer server; private ClientSessionFactory sf; @@ -39,8 +38,7 @@ public class ProducerCloseTest extends ActiveMQTestBase private ServerLocator locator; @Test - public void testCanNotUseAClosedProducer() throws Exception - { + public void testCanNotUseAClosedProducer() throws Exception { final ClientProducer producer = session.createProducer(RandomUtil.randomSimpleString()); Assert.assertFalse(producer.isClosed()); @@ -49,10 +47,8 @@ public class ProducerCloseTest extends ActiveMQTestBase Assert.assertTrue(producer.isClosed()); - ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() - { - public void run() throws ActiveMQException - { + ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() { + public void run() throws ActiveMQException { producer.send(session.createMessage(false)); } }); @@ -64,8 +60,7 @@ public class ProducerCloseTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); Configuration config = createDefaultInVMConfig(); server = createServer(false, config); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ProducerFlowControlTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ProducerFlowControlTest.java index 3266637b3c..2567d68ab0 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ProducerFlowControlTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ProducerFlowControlTest.java @@ -47,8 +47,8 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -public class ProducerFlowControlTest extends ActiveMQTestBase -{ +public class ProducerFlowControlTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private ServerLocator locator; @@ -59,15 +59,13 @@ public class ProducerFlowControlTest extends ActiveMQTestBase private ActiveMQServer server; - protected boolean isNetty() - { + protected boolean isNetty() { return false; } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = createFactory(isNetty()); } @@ -75,110 +73,92 @@ public class ProducerFlowControlTest extends ActiveMQTestBase // TODO need to test crashing a producer with unused credits returns them to the pool @Test - public void testFlowControlSingleConsumer() throws Exception - { + public void testFlowControlSingleConsumer() throws Exception { testFlowControl(1000, 500, 10 * 1024, 1024, 1024, 1024, 1, 1, 0, false); } @Test - public void testFlowControlAnon() throws Exception - { + public void testFlowControlAnon() throws Exception { testFlowControl(1000, 500, 10 * 1024, 1024, 1024, 1024, 1, 1, 0, true); } @Test - public void testFlowControlSingleConsumerLargeMaxSize() throws Exception - { + public void testFlowControlSingleConsumerLargeMaxSize() throws Exception { testFlowControl(1000, 500, 1024 * 1024, 1024, 1024, 1024, 1, 1, 0, false); } @Test - public void testFlowControlMultipleConsumers() throws Exception - { + public void testFlowControlMultipleConsumers() throws Exception { testFlowControl(1000, 500, -1, 1024, 1024, 1024, 5, 1, 0, false); } @Test - public void testFlowControlZeroConsumerWindowSize() throws Exception - { + public void testFlowControlZeroConsumerWindowSize() throws Exception { testFlowControl(1000, 500, 10 * 1024, 1024, 0, 1024, 1, 1, 0, false); } @Test - public void testFlowControlZeroAckBatchSize() throws Exception - { + public void testFlowControlZeroAckBatchSize() throws Exception { testFlowControl(1000, 500, 10 * 1024, 1024, 1024, 0, 1, 1, 0, false); } @Test - public void testFlowControlSingleConsumerSlowConsumer() throws Exception - { + public void testFlowControlSingleConsumerSlowConsumer() throws Exception { testFlowControl(100, 500, 1024, 512, 512, 512, 1, 1, 10, false); } @Test - public void testFlowControlSmallMessages() throws Exception - { + public void testFlowControlSmallMessages() throws Exception { testFlowControl(1000, 0, 10 * 1024, 1024, 1024, 1024, 1, 1, 0, false); } @Test - public void testFlowControlLargerMessagesSmallWindowSize() throws Exception - { + public void testFlowControlLargerMessagesSmallWindowSize() throws Exception { testFlowControl(1000, 10 * 1024, 10 * 1024, 1024, 1024, 1024, 1, 1, 0, false); } @Test - public void testFlowControlMultipleProducers() throws Exception - { + public void testFlowControlMultipleProducers() throws Exception { testFlowControl(1000, 500, 1024 * 1024, 1024, 1024, 1024, 1, 5, 0, false); } @Test - public void testFlowControlMultipleProducersAndConsumers() throws Exception - { + public void testFlowControlMultipleProducersAndConsumers() throws Exception { testFlowControl(500, 500, 100 * 1024, 1024, 1024, 1024, 1, 3, 3, false); } @Test - public void testFlowControlMultipleProducersAnon() throws Exception - { + public void testFlowControlMultipleProducersAnon() throws Exception { testFlowControl(1000, 500, 1024 * 1024, 1024, 1024, 1024, 1, 5, 0, true); } @Test - public void testFlowControlLargeMessages2() throws Exception - { + public void testFlowControlLargeMessages2() throws Exception { testFlowControl(1000, 10000, -1, 1024, 0, 0, 1, 1, 0, false, 1000, true); } @Test - public void testFlowControlLargeMessages3() throws Exception - { + public void testFlowControlLargeMessages3() throws Exception { testFlowControl(1000, 10000, 100 * 1024, 1024, 1024, 0, 1, 1, 0, false, 1000, true); } @Test - public void testFlowControlLargeMessages4() throws Exception - { + public void testFlowControlLargeMessages4() throws Exception { testFlowControl(1000, 10000, 100 * 1024, 1024, 1024, 1024, 1, 1, 0, false, 1000, true); } @Test - public void testFlowControlLargeMessages5() throws Exception - { + public void testFlowControlLargeMessages5() throws Exception { testFlowControl(1000, 10000, 100 * 1024, 1024, -1, 1024, 1, 1, 0, false, 1000, true); } @Test - public void testFlowControlLargeMessages6() throws Exception - { + public void testFlowControlLargeMessages6() throws Exception { testFlowControl(1000, 10000, 100 * 1024, 1024, 1024, 1024, 1, 1, 0, true, 1000, true); } @Test - public void testFlowControlLargeMessages7() throws Exception - { + public void testFlowControlLargeMessages7() throws Exception { testFlowControl(1000, 10000, 100 * 1024, 1024, 1024, 1024, 2, 2, 0, true, 1000, true); } @@ -191,20 +171,8 @@ public class ProducerFlowControlTest extends ActiveMQTestBase final int numConsumers, final int numProducers, final long consumerDelay, - final boolean anon) throws Exception - { - testFlowControl(numMessages, - messageSize, - maxSize, - producerWindowSize, - consumerWindowSize, - ackBatchSize, - numConsumers, - numProducers, - consumerDelay, - anon, - -1, - false); + final boolean anon) throws Exception { + testFlowControl(numMessages, messageSize, maxSize, producerWindowSize, consumerWindowSize, ackBatchSize, numConsumers, numProducers, consumerDelay, anon, -1, false); } private void testFlowControl(final int numMessages, @@ -218,15 +186,12 @@ public class ProducerFlowControlTest extends ActiveMQTestBase final long consumerDelay, final boolean anon, final int minLargeMessageSize, - final boolean realFiles) throws Exception - { + final boolean realFiles) throws Exception { final SimpleString address = new SimpleString("testaddress"); server = createServer(realFiles, isNetty()); - AddressSettings addressSettings = new AddressSettings() - .setMaxSizeBytes(maxSize) - .setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK); + AddressSettings addressSettings = new AddressSettings().setMaxSizeBytes(maxSize).setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK); HierarchicalRepository repos = server.getAddressSettingsRepository(); repos.addMatch(address.toString(), addressSettings); @@ -234,12 +199,9 @@ public class ProducerFlowControlTest extends ActiveMQTestBase server.start(); waitForServerToStart(server); - locator.setProducerWindowSize(producerWindowSize) - .setConsumerWindowSize(consumerWindowSize) - .setAckBatchSize(ackBatchSize); + locator.setProducerWindowSize(producerWindowSize).setConsumerWindowSize(consumerWindowSize).setAckBatchSize(ackBatchSize); - if (minLargeMessageSize != -1) - { + if (minLargeMessageSize != -1) { locator.setMinLargeMessageSize(minLargeMessageSize); } @@ -250,25 +212,22 @@ public class ProducerFlowControlTest extends ActiveMQTestBase final String queueName = "testqueue"; - for (int i = 0; i < numConsumers; i++) - { + for (int i = 0; i < numConsumers; i++) { session.createQueue(address, new SimpleString(queueName + i), null, false); } final byte[] bytes = RandomUtil.randomBytes(messageSize); - class MyHandler implements MessageHandler - { + class MyHandler implements MessageHandler { + int count = 0; final CountDownLatch latch = new CountDownLatch(1); volatile Exception exception; - public void onMessage(final ClientMessage message) - { - try - { + public void onMessage(final ClientMessage message) { + try { byte[] bytesRead = new byte[messageSize]; message.getBodyBuffer().readBytes(bytesRead); @@ -277,19 +236,16 @@ public class ProducerFlowControlTest extends ActiveMQTestBase message.acknowledge(); - if (++count == numMessages * numProducers) - { + if (++count == numMessages * numProducers) { latch.countDown(); } - if (consumerDelay > 0) - { + if (consumerDelay > 0) { Thread.sleep(consumerDelay); } } - catch (Exception e) - { + catch (Exception e) { ProducerFlowControlTest.log.error("Failed to handle message", e); exception = e; @@ -301,8 +257,7 @@ public class ProducerFlowControlTest extends ActiveMQTestBase MyHandler[] handlers = new MyHandler[numConsumers]; - for (int i = 0; i < numConsumers; i++) - { + for (int i = 0; i < numConsumers; i++) { handlers[i] = new MyHandler(); ClientConsumer consumer = session.createConsumer(new SimpleString(queueName + i)); @@ -312,42 +267,34 @@ public class ProducerFlowControlTest extends ActiveMQTestBase ClientProducer[] producers = new ClientProducer[numProducers]; - for (int i = 0; i < numProducers; i++) - { - if (anon) - { + for (int i = 0; i < numProducers; i++) { + if (anon) { producers[i] = session.createProducer(); } - else - { + else { producers[i] = session.createProducer(address); } } long start = System.currentTimeMillis(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.getBodyBuffer().writeBytes(bytes); - for (int j = 0; j < numProducers; j++) - { - if (anon) - { + for (int j = 0; j < numProducers; j++) { + if (anon) { producers[j].send(address, message); } - else - { + else { producers[j].send(message); } } } - for (int i = 0; i < numConsumers; i++) - { + for (int i = 0; i < numConsumers; i++) { Assert.assertTrue(handlers[i].latch.await(5, TimeUnit.MINUTES)); Assert.assertNull(handlers[i].exception); @@ -361,15 +308,12 @@ public class ProducerFlowControlTest extends ActiveMQTestBase } @Test - public void testClosingSessionUnblocksBlockedProducer() throws Exception - { + public void testClosingSessionUnblocksBlockedProducer() throws Exception { final SimpleString address = new SimpleString("testaddress"); server = createServer(false, isNetty()); - AddressSettings addressSettings = new AddressSettings() - .setMaxSizeBytes(1024) - .setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK); + AddressSettings addressSettings = new AddressSettings().setMaxSizeBytes(1024).setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK); HierarchicalRepository repos = server.getAddressSettingsRepository(); repos.addMatch(address.toString(), addressSettings); @@ -377,9 +321,7 @@ public class ProducerFlowControlTest extends ActiveMQTestBase server.start(); waitForServerToStart(server); - locator.setProducerWindowSize(1024) - .setConsumerWindowSize(1024) - .setAckBatchSize(1024); + locator.setProducerWindowSize(1024).setConsumerWindowSize(1024).setAckBatchSize(1024); sf = createSessionFactory(locator); session = sf.createSession(false, true, true, true); @@ -398,36 +340,29 @@ public class ProducerFlowControlTest extends ActiveMQTestBase final AtomicBoolean closed = new AtomicBoolean(false); - Thread t = new Thread(new Runnable() - { - public void run() - { - try - { + Thread t = new Thread(new Runnable() { + public void run() { + try { Thread.sleep(500); closed.set(true); session.close(); } - catch (Exception e) - { + catch (Exception e) { } } }); t.start(); - try - { + try { // This will block - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { producer.send(message); } } - catch (ActiveMQObjectClosedException expected) - { + catch (ActiveMQObjectClosedException expected) { } Assert.assertTrue(closed.get()); @@ -436,15 +371,12 @@ public class ProducerFlowControlTest extends ActiveMQTestBase } @Test - public void testFlowControlMessageNotRouted() throws Exception - { + public void testFlowControlMessageNotRouted() throws Exception { final SimpleString address = new SimpleString("testaddress"); server = createServer(false, isNetty()); - AddressSettings addressSettings = new AddressSettings() - .setMaxSizeBytes(1024) - .setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK); + AddressSettings addressSettings = new AddressSettings().setMaxSizeBytes(1024).setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK); HierarchicalRepository repos = server.getAddressSettingsRepository(); repos.addMatch(address.toString(), addressSettings); @@ -452,9 +384,7 @@ public class ProducerFlowControlTest extends ActiveMQTestBase server.start(); waitForServerToStart(server); - locator.setProducerWindowSize(1024) - .setConsumerWindowSize(1024) - .setAckBatchSize(1024); + locator.setProducerWindowSize(1024).setConsumerWindowSize(1024).setAckBatchSize(1024); sf = createSessionFactory(locator); @@ -466,8 +396,7 @@ public class ProducerFlowControlTest extends ActiveMQTestBase final int numMessages = 1000; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.getBodyBuffer().writeBytes(bytes); @@ -478,8 +407,7 @@ public class ProducerFlowControlTest extends ActiveMQTestBase // Not technically a flow control test, but what the hell @Test - public void testMultipleConsumers() throws Exception - { + public void testMultipleConsumers() throws Exception { server = createServer(false, isNetty()); server.start(); @@ -511,15 +439,13 @@ public class ProducerFlowControlTest extends ActiveMQTestBase final int numMessages = 1000; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { producer.send(message); } session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage msg = consumer1.receive(1000); Assert.assertNotNull(msg); @@ -543,8 +469,7 @@ public class ProducerFlowControlTest extends ActiveMQTestBase } @Test - public void testProducerCreditsCaching1() throws Exception - { + public void testProducerCreditsCaching1() throws Exception { server = createServer(false, isNetty()); server.start(); @@ -558,28 +483,24 @@ public class ProducerFlowControlTest extends ActiveMQTestBase ClientProducerCredits credits = null; - for (int i = 0; i < ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE * 2; i++) - { + for (int i = 0; i < ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE * 2; i++) { ClientProducer prod = session.createProducer("address"); ClientProducerCredits newCredits = ((ClientProducerInternal) prod).getProducerCredits(); - if (credits != null) - { + if (credits != null) { Assert.assertTrue(newCredits == credits); } credits = newCredits; Assert.assertEquals(1, ((ClientSessionInternal) session).getProducerCreditManager().creditsMapSize()); - Assert.assertEquals(0, ((ClientSessionInternal) session).getProducerCreditManager() - .unReferencedCreditsSize()); + Assert.assertEquals(0, ((ClientSessionInternal) session).getProducerCreditManager().unReferencedCreditsSize()); } } @Test - public void testProducerCreditsCaching2() throws Exception - { + public void testProducerCreditsCaching2() throws Exception { server = createServer(false, isNetty()); server.start(); @@ -592,14 +513,12 @@ public class ProducerFlowControlTest extends ActiveMQTestBase ClientProducerCredits credits = null; - for (int i = 0; i < ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE * 2; i++) - { + for (int i = 0; i < ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE * 2; i++) { ClientProducer prod = session.createProducer("address"); ClientProducerCredits newCredits = ((ClientProducerInternal) prod).getProducerCredits(); - if (credits != null) - { + if (credits != null) { Assert.assertTrue(newCredits == credits); } @@ -608,14 +527,12 @@ public class ProducerFlowControlTest extends ActiveMQTestBase prod.close(); Assert.assertEquals(1, ((ClientSessionInternal) session).getProducerCreditManager().creditsMapSize()); - Assert.assertEquals(1, ((ClientSessionInternal) session).getProducerCreditManager() - .unReferencedCreditsSize()); + Assert.assertEquals(1, ((ClientSessionInternal) session).getProducerCreditManager().unReferencedCreditsSize()); } } @Test - public void testProducerCreditsCaching3() throws Exception - { + public void testProducerCreditsCaching3() throws Exception { server = createServer(false, isNetty()); server.start(); @@ -629,28 +546,24 @@ public class ProducerFlowControlTest extends ActiveMQTestBase ClientProducerCredits credits = null; - for (int i = 0; i < ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE; i++) - { + for (int i = 0; i < ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE; i++) { ClientProducer prod = session.createProducer("address" + i); ClientProducerCredits newCredits = ((ClientProducerInternal) prod).getProducerCredits(); - if (credits != null) - { + if (credits != null) { Assert.assertFalse(newCredits == credits); } credits = newCredits; Assert.assertEquals(i + 1, ((ClientSessionInternal) session).getProducerCreditManager().creditsMapSize()); - Assert.assertEquals(0, ((ClientSessionInternal) session).getProducerCreditManager() - .unReferencedCreditsSize()); + Assert.assertEquals(0, ((ClientSessionInternal) session).getProducerCreditManager().unReferencedCreditsSize()); } } @Test - public void testProducerCreditsCaching4() throws Exception - { + public void testProducerCreditsCaching4() throws Exception { server = createServer(false, isNetty()); server.start(); @@ -663,14 +576,12 @@ public class ProducerFlowControlTest extends ActiveMQTestBase ClientProducerCredits credits = null; - for (int i = 0; i < ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE; i++) - { + for (int i = 0; i < ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE; i++) { ClientProducer prod = session.createProducer("address" + i); ClientProducerCredits newCredits = ((ClientProducerInternal) prod).getProducerCredits(); - if (credits != null) - { + if (credits != null) { Assert.assertFalse(newCredits == credits); } @@ -679,14 +590,12 @@ public class ProducerFlowControlTest extends ActiveMQTestBase prod.close(); Assert.assertEquals(i + 1, ((ClientSessionInternal) session).getProducerCreditManager().creditsMapSize()); - Assert.assertEquals(i + 1, ((ClientSessionInternal) session).getProducerCreditManager() - .unReferencedCreditsSize()); + Assert.assertEquals(i + 1, ((ClientSessionInternal) session).getProducerCreditManager().unReferencedCreditsSize()); } } @Test - public void testProducerCreditsCaching5() throws Exception - { + public void testProducerCreditsCaching5() throws Exception { server = createServer(false, isNetty()); server.start(); @@ -702,56 +611,46 @@ public class ProducerFlowControlTest extends ActiveMQTestBase List creditsList = new ArrayList(); - for (int i = 0; i < ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE; i++) - { + for (int i = 0; i < ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE; i++) { ClientProducer prod = session.createProducer("address" + i); ClientProducerCredits newCredits = ((ClientProducerInternal) prod).getProducerCredits(); - if (credits != null) - { + if (credits != null) { Assert.assertFalse(newCredits == credits); } credits = newCredits; Assert.assertEquals(i + 1, ((ClientSessionInternal) session).getProducerCreditManager().creditsMapSize()); - Assert.assertEquals(0, ((ClientSessionInternal) session).getProducerCreditManager() - .unReferencedCreditsSize()); + Assert.assertEquals(0, ((ClientSessionInternal) session).getProducerCreditManager().unReferencedCreditsSize()); creditsList.add(credits); } Iterator iter = creditsList.iterator(); - for (int i = 0; i < ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE; i++) - { + for (int i = 0; i < ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE; i++) { ClientProducer prod = session.createProducer("address" + i); ClientProducerCredits newCredits = ((ClientProducerInternal) prod).getProducerCredits(); Assert.assertTrue(newCredits == iter.next()); - Assert.assertEquals(ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE, - ((ClientSessionInternal) session).getProducerCreditManager().creditsMapSize()); - Assert.assertEquals(0, ((ClientSessionInternal) session).getProducerCreditManager() - .unReferencedCreditsSize()); + Assert.assertEquals(ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE, ((ClientSessionInternal) session).getProducerCreditManager().creditsMapSize()); + Assert.assertEquals(0, ((ClientSessionInternal) session).getProducerCreditManager().unReferencedCreditsSize()); } - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { session.createProducer("address" + (i + ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE)); - Assert.assertEquals(ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE + i + 1, - ((ClientSessionInternal) session).getProducerCreditManager().creditsMapSize()); - Assert.assertEquals(0, ((ClientSessionInternal) session).getProducerCreditManager() - .unReferencedCreditsSize()); + Assert.assertEquals(ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE + i + 1, ((ClientSessionInternal) session).getProducerCreditManager().creditsMapSize()); + Assert.assertEquals(0, ((ClientSessionInternal) session).getProducerCreditManager().unReferencedCreditsSize()); } } @Test - public void testProducerCreditsCaching6() throws Exception - { + public void testProducerCreditsCaching6() throws Exception { server = createServer(false, isNetty()); server.start(); @@ -762,21 +661,18 @@ public class ProducerFlowControlTest extends ActiveMQTestBase session.createQueue("address", "queue1", null, false); - for (int i = 0; i < ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE; i++) - { + for (int i = 0; i < ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE; i++) { ClientProducer prod = session.createProducer((String) null); prod.send("address", session.createMessage(false)); Assert.assertEquals(1, ((ClientSessionInternal) session).getProducerCreditManager().creditsMapSize()); - Assert.assertEquals(1, ((ClientSessionInternal) session).getProducerCreditManager() - .unReferencedCreditsSize()); + Assert.assertEquals(1, ((ClientSessionInternal) session).getProducerCreditManager().unReferencedCreditsSize()); } } @Test - public void testProducerCreditsCaching7() throws Exception - { + public void testProducerCreditsCaching7() throws Exception { server = createServer(false, isNetty()); server.start(); @@ -788,45 +684,36 @@ public class ProducerFlowControlTest extends ActiveMQTestBase session.createQueue("address", "queue1", null, false); - for (int i = 0; i < ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE; i++) - { + for (int i = 0; i < ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE; i++) { ClientProducer prod = session.createProducer((String) null); prod.send("address" + i, session.createMessage(false)); Assert.assertEquals(i + 1, ((ClientSessionInternal) session).getProducerCreditManager().creditsMapSize()); - Assert.assertEquals(i + 1, ((ClientSessionInternal) session).getProducerCreditManager() - .unReferencedCreditsSize()); + Assert.assertEquals(i + 1, ((ClientSessionInternal) session).getProducerCreditManager().unReferencedCreditsSize()); } - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientProducer prod = session.createProducer((String) null); prod.send("address" + i, session.createMessage(false)); - Assert.assertEquals(ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE, - ((ClientSessionInternal) session).getProducerCreditManager().creditsMapSize()); - Assert.assertEquals(ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE, - ((ClientSessionInternal) session).getProducerCreditManager().unReferencedCreditsSize()); + Assert.assertEquals(ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE, ((ClientSessionInternal) session).getProducerCreditManager().creditsMapSize()); + Assert.assertEquals(ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE, ((ClientSessionInternal) session).getProducerCreditManager().unReferencedCreditsSize()); } - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientProducer prod = session.createProducer((String) null); prod.send("address2-" + i, session.createMessage(false)); - Assert.assertEquals(ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE, - ((ClientSessionInternal) session).getProducerCreditManager().creditsMapSize()); - Assert.assertEquals(ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE, - ((ClientSessionInternal) session).getProducerCreditManager().unReferencedCreditsSize()); + Assert.assertEquals(ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE, ((ClientSessionInternal) session).getProducerCreditManager().creditsMapSize()); + Assert.assertEquals(ClientProducerCreditManagerImpl.MAX_UNREFERENCED_CREDITS_CACHE_SIZE, ((ClientSessionInternal) session).getProducerCreditManager().unReferencedCreditsSize()); } } @Test - public void testProducerCreditsRefCounting() throws Exception - { + public void testProducerCreditsRefCounting() throws Exception { server = createServer(false, isNetty()); server.start(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ProducerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ProducerTest.java index 89114f3c2d..d5eea12425 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ProducerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ProducerTest.java @@ -39,16 +39,15 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class ProducerTest extends ActiveMQTestBase -{ +public class ProducerTest extends ActiveMQTestBase { + private ActiveMQServer server; private final SimpleString QUEUE = new SimpleString("ConsumerTestQueue"); @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(false); @@ -57,22 +56,17 @@ public class ProducerTest extends ActiveMQTestBase } @Test - public void testProducerWithSmallWindowSizeAndLargeMessage() throws Exception - { + public void testProducerWithSmallWindowSizeAndLargeMessage() throws Exception { final CountDownLatch latch = new CountDownLatch(1); - server.getRemotingService().addIncomingInterceptor(new Interceptor() - { - public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException - { - if (packet.getType() == PacketImpl.SESS_SEND) - { + server.getRemotingService().addIncomingInterceptor(new Interceptor() { + public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { + if (packet.getType() == PacketImpl.SESS_SEND) { latch.countDown(); } return true; } }); - ServerLocator locator = createInVMNonHALocator() - .setConfirmationWindowSize(100); + ServerLocator locator = createInVMNonHALocator().setConfirmationWindowSize(100); ClientSessionFactory cf = locator.createSessionFactory(); ClientSession session = cf.createSession(false, true, true); ClientProducer producer = session.createProducer(QUEUE); @@ -85,14 +79,10 @@ public class ProducerTest extends ActiveMQTestBase locator.close(); } - @Test - public void testProducerMultiThread() throws Exception - { + public void testProducerMultiThread() throws Exception { final ServerLocator locator = createInVMNonHALocator(); - AddressSettings setting = new AddressSettings() - .setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK) - .setMaxSizeBytes(10 * 1024); + AddressSettings setting = new AddressSettings().setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK).setMaxSizeBytes(10 * 1024); server.stop(); server.getConfiguration().getAddressesSettings().clear(); server.getConfiguration().getAddressesSettings().put(QUEUE.toString(), setting); @@ -100,26 +90,19 @@ public class ProducerTest extends ActiveMQTestBase server.createQueue(QUEUE, QUEUE, null, true, false); - - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { final CountDownLatch latch = new CountDownLatch(1); System.out.println("Try " + i); ClientSessionFactory cf = locator.createSessionFactory(); final ClientSession session = cf.createSession(false, true, true); - Thread t = new Thread() - { - public void run() - { - try - { + Thread t = new Thread() { + public void run() { + try { ClientProducer producer = session.createProducer(); - for (int i = 0; i < 62; i++) - { - if (i == 61) - { + for (int i = 0; i < 62; i++) { + if (i == 61) { // the point where the send would block latch.countDown(); } @@ -128,8 +111,7 @@ public class ProducerTest extends ActiveMQTestBase producer.send(QUEUE, msg); } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -141,8 +123,7 @@ public class ProducerTest extends ActiveMQTestBase t.join(5000); - if (!t.isAlive()) - { + if (!t.isAlive()) { t.interrupt(); } @@ -151,11 +132,9 @@ public class ProducerTest extends ActiveMQTestBase ClientSession sessionConsumer = cf.createSession(); sessionConsumer.start(); ClientConsumer cons = sessionConsumer.createConsumer(QUEUE); - while (true) - { + while (true) { ClientMessage msg = cons.receiveImmediate(); - if (msg == null) - { + if (msg == null) { break; } msg.acknowledge(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/QueueBrowserTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/QueueBrowserTest.java index d4747792ce..2aba9256f3 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/QueueBrowserTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/QueueBrowserTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.client; + import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Before; @@ -32,8 +33,8 @@ import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.Queue; -public class QueueBrowserTest extends ActiveMQTestBase -{ +public class QueueBrowserTest extends ActiveMQTestBase { + private ActiveMQServer server; private final SimpleString QUEUE = new SimpleString("ConsumerTestQueue"); @@ -42,8 +43,7 @@ public class QueueBrowserTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(false); @@ -56,8 +56,7 @@ public class QueueBrowserTest extends ActiveMQTestBase private ClientSessionFactory sf; @Test - public void testSimpleConsumerBrowser() throws Exception - { + public void testSimpleConsumerBrowser() throws Exception { locator.setBlockOnNonDurableSend(true); sf = createSessionFactory(locator); @@ -69,16 +68,14 @@ public class QueueBrowserTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); producer.send(message); } ClientConsumer consumer = session.createConsumer(QUEUE, null, true); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message2 = consumer.receive(1000); Assert.assertEquals("m" + i, message2.getBodyBuffer().readString()); @@ -88,8 +85,7 @@ public class QueueBrowserTest extends ActiveMQTestBase consumer = session.createConsumer(QUEUE, null, true); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message2 = consumer.receive(1000); Assert.assertEquals("m" + i, message2.getBodyBuffer().readString()); @@ -99,12 +95,10 @@ public class QueueBrowserTest extends ActiveMQTestBase session.close(); - } @Test - public void testConsumerBrowserWithSelector() throws Exception - { + public void testConsumerBrowserWithSelector() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); @@ -116,8 +110,7 @@ public class QueueBrowserTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); message.putIntProperty(new SimpleString("x"), i); producer.send(message); @@ -125,8 +118,7 @@ public class QueueBrowserTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(QUEUE, new SimpleString("x >= 50"), true); - for (int i = 50; i < numMessages; i++) - { + for (int i = 50; i < numMessages; i++) { ClientMessage message2 = consumer.receive(1000); Assert.assertEquals("m" + i, message2.getBodyBuffer().readString()); @@ -136,8 +128,7 @@ public class QueueBrowserTest extends ActiveMQTestBase consumer = session.createConsumer(QUEUE, null, true); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message2 = consumer.receive(1000); Assert.assertEquals("m" + i, message2.getBodyBuffer().readString()); @@ -149,8 +140,7 @@ public class QueueBrowserTest extends ActiveMQTestBase } @Test - public void testConsumerBrowserWithStringSelector() throws Exception - { + public void testConsumerBrowserWithStringSelector() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); @@ -162,11 +152,9 @@ public class QueueBrowserTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); - if (i % 2 == 0) - { + if (i % 2 == 0) { message.putStringProperty(new SimpleString("color"), new SimpleString("RED")); } producer.send(message); @@ -174,8 +162,7 @@ public class QueueBrowserTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(QUEUE, new SimpleString("color = 'RED'"), true); - for (int i = 0; i < numMessages; i += 2) - { + for (int i = 0; i < numMessages; i += 2) { ClientMessage message2 = consumer.receive(1000); Assert.assertEquals("m" + i, message2.getBodyBuffer().readString()); @@ -183,12 +170,10 @@ public class QueueBrowserTest extends ActiveMQTestBase session.close(); - } @Test - public void testConsumerMultipleBrowser() throws Exception - { + public void testConsumerMultipleBrowser() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); @@ -200,8 +185,7 @@ public class QueueBrowserTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); producer.send(message); } @@ -210,8 +194,7 @@ public class QueueBrowserTest extends ActiveMQTestBase ClientConsumer consumer2 = session.createConsumer(QUEUE, null, true); ClientConsumer consumer3 = session.createConsumer(QUEUE, null, true); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message2 = consumer.receive(1000); Assert.assertEquals("m" + i, message2.getBodyBuffer().readString()); message2 = consumer2.receive(1000); @@ -225,8 +208,7 @@ public class QueueBrowserTest extends ActiveMQTestBase } @Test - public void testConsumerMultipleBrowserWithSelector() throws Exception - { + public void testConsumerMultipleBrowserWithSelector() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); @@ -238,8 +220,7 @@ public class QueueBrowserTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); message.putIntProperty(new SimpleString("x"), i); producer.send(message); @@ -249,41 +230,34 @@ public class QueueBrowserTest extends ActiveMQTestBase ClientConsumer consumer2 = session.createConsumer(QUEUE, new SimpleString("x >= 50"), true); ClientConsumer consumer3 = session.createConsumer(QUEUE, null, true); - for (int i = 0; i < 50; i++) - { + for (int i = 0; i < 50; i++) { ClientMessage message2 = consumer.receive(1000); Assert.assertEquals("m" + i, message2.getBodyBuffer().readString()); } - for (int i = 50; i < numMessages; i++) - { + for (int i = 50; i < numMessages; i++) { ClientMessage message2 = consumer2.receive(1000); Assert.assertEquals("m" + i, message2.getBodyBuffer().readString()); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message2 = consumer3.receive(1000); Assert.assertEquals("m" + i, message2.getBodyBuffer().readString()); } session.close(); - } @Test - public void testConsumerBrowserMessages() throws Exception - { + public void testConsumerBrowserMessages() throws Exception { testConsumerBrowserMessagesArentAcked(false); } @Test - public void testConsumerBrowserMessagesPreACK() throws Exception - { + public void testConsumerBrowserMessagesPreACK() throws Exception { testConsumerBrowserMessagesArentAcked(false); } - private void testConsumerBrowserMessagesArentAcked(final boolean preACK) throws Exception - { + private void testConsumerBrowserMessagesArentAcked(final boolean preACK) throws Exception { ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(null, null, false, true, true, preACK, 0); @@ -294,31 +268,28 @@ public class QueueBrowserTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); producer.send(message); } ClientConsumer consumer = session.createConsumer(QUEUE, null, true); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message2 = consumer.receive(1000); Assert.assertEquals("m" + i, message2.getBodyBuffer().readString()); } // assert that all the messages are there and none have been acked - Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(QUEUE).getBindable()).getDeliveringCount()); - Assert.assertEquals(100, getMessageCount(((Queue)server.getPostOffice().getBinding(QUEUE).getBindable()))); + Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(QUEUE).getBindable()).getDeliveringCount()); + Assert.assertEquals(100, getMessageCount(((Queue) server.getPostOffice().getBinding(QUEUE).getBindable()))); session.close(); } @Test - public void testConsumerBrowserMessageAckDoesNothing() throws Exception - { + public void testConsumerBrowserMessageAckDoesNothing() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(false, true, true); @@ -329,16 +300,14 @@ public class QueueBrowserTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); producer.send(message); } ClientConsumer consumer = session.createConsumer(QUEUE, null, true); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message2 = consumer.receive(1000); message2.acknowledge(); @@ -346,16 +315,15 @@ public class QueueBrowserTest extends ActiveMQTestBase Assert.assertEquals("m" + i, message2.getBodyBuffer().readString()); } // assert that all the messages are there and none have been acked - Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(QUEUE).getBindable()).getDeliveringCount()); - Assert.assertEquals(100, getMessageCount(((Queue)server.getPostOffice().getBinding(QUEUE).getBindable()))); + Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(QUEUE).getBindable()).getDeliveringCount()); + Assert.assertEquals(100, getMessageCount(((Queue) server.getPostOffice().getBinding(QUEUE).getBindable()))); session.close(); } @Test - public void testBrowseWithZeroConsumerWindowSize() throws Exception - { + public void testBrowseWithZeroConsumerWindowSize() throws Exception { locator.setConsumerWindowSize(0); ClientSessionFactory sf = createSessionFactory(locator); @@ -370,8 +338,7 @@ public class QueueBrowserTest extends ActiveMQTestBase byte[] bytes = new byte[240]; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.getBodyBuffer().writeBytes(bytes); @@ -388,8 +355,7 @@ public class QueueBrowserTest extends ActiveMQTestBase ClientConsumer browser = session.createConsumer(QUEUE, true); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message2 = browser.receive(1000); assertEquals(i, message2.getIntProperty("foo").intValue()); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ReceiveImmediateTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ReceiveImmediateTest.java index 97c52a3352..6a310c6c17 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ReceiveImmediateTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ReceiveImmediateTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.client; + import org.junit.Before; import org.junit.Test; @@ -36,8 +37,8 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.Queue; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -public class ReceiveImmediateTest extends ActiveMQTestBase -{ +public class ReceiveImmediateTest extends ActiveMQTestBase { + private ActiveMQServer server; private final SimpleString QUEUE = new SimpleString("ReceiveImmediateTest.queue"); @@ -48,8 +49,7 @@ public class ReceiveImmediateTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); Configuration config = createDefaultInVMConfig(); server = createServer(false, config); @@ -60,35 +60,28 @@ public class ReceiveImmediateTest extends ActiveMQTestBase private ClientSessionFactory sf; @Test - public void testConsumerReceiveImmediateWithNoMessages() throws Exception - { + public void testConsumerReceiveImmediateWithNoMessages() throws Exception { doConsumerReceiveImmediateWithNoMessages(false); } @Test - public void testConsumerReceiveImmediate() throws Exception - { + public void testConsumerReceiveImmediate() throws Exception { doConsumerReceiveImmediate(false); } @Test - public void testBrowserReceiveImmediateWithNoMessages() throws Exception - { + public void testBrowserReceiveImmediateWithNoMessages() throws Exception { doConsumerReceiveImmediateWithNoMessages(true); } @Test - public void testBrowserReceiveImmediate() throws Exception - { + public void testBrowserReceiveImmediate() throws Exception { doConsumerReceiveImmediate(true); } @Test - public void testConsumerReceiveImmediateWithSessionStop() throws Exception - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnAcknowledge(true) - .setAckBatchSize(0); + public void testConsumerReceiveImmediateWithSessionStop() throws Exception { + locator.setBlockOnNonDurableSend(true).setBlockOnAcknowledge(true).setAckBatchSize(0); sf = createSessionFactory(locator); ClientSession session = sf.createSession(false, true, true); @@ -116,8 +109,7 @@ public class ReceiveImmediateTest extends ActiveMQTestBase // https://jira.jboss.org/browse/HORNETQ-450 @Test - public void testReceivedImmediateFollowedByReceive() throws Exception - { + public void testReceivedImmediateFollowedByReceive() throws Exception { locator.setBlockOnNonDurableSend(true); sf = createSessionFactory(locator); @@ -150,8 +142,7 @@ public class ReceiveImmediateTest extends ActiveMQTestBase // https://jira.jboss.org/browse/HORNETQ-450 @Test - public void testReceivedImmediateFollowedByAsyncConsume() throws Exception - { + public void testReceivedImmediateFollowedByAsyncConsume() throws Exception { locator.setBlockOnNonDurableSend(true); sf = createSessionFactory(locator); @@ -178,10 +169,8 @@ public class ReceiveImmediateTest extends ActiveMQTestBase final AtomicBoolean receivedAsync = new AtomicBoolean(false); - consumer.setMessageHandler(new MessageHandler() - { - public void onMessage(ClientMessage message) - { + consumer.setMessageHandler(new MessageHandler() { + public void onMessage(ClientMessage message) { receivedAsync.set(true); } }); @@ -193,11 +182,8 @@ public class ReceiveImmediateTest extends ActiveMQTestBase session.close(); } - private void doConsumerReceiveImmediateWithNoMessages(final boolean browser) throws Exception - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnAcknowledge(true) - .setAckBatchSize(0); + private void doConsumerReceiveImmediateWithNoMessages(final boolean browser) throws Exception { + locator.setBlockOnNonDurableSend(true).setBlockOnAcknowledge(true).setAckBatchSize(0); sf = createSessionFactory(locator); @@ -214,11 +200,8 @@ public class ReceiveImmediateTest extends ActiveMQTestBase session.close(); } - private void doConsumerReceiveImmediate(final boolean browser) throws Exception - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnAcknowledge(true) - .setAckBatchSize(0); + private void doConsumerReceiveImmediate(final boolean browser) throws Exception { + locator.setBlockOnNonDurableSend(true).setBlockOnAcknowledge(true).setAckBatchSize(0); sf = createSessionFactory(locator); ClientSession session = sf.createSession(false, true, true); @@ -229,8 +212,7 @@ public class ReceiveImmediateTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); producer.send(message); } @@ -238,25 +220,22 @@ public class ReceiveImmediateTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(QUEUE, null, browser); session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message2 = consumer.receiveImmediate(); Assert.assertNotNull("did not receive message " + i, message2); Assert.assertEquals("m" + i, message2.getBodyBuffer().readString()); - if (!browser) - { + if (!browser) { message2.acknowledge(); } } - Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(QUEUE).getBindable()).getDeliveringCount()); + Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(QUEUE).getBindable()).getDeliveringCount()); Assert.assertNull(consumer.receiveImmediate()); - Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(QUEUE).getBindable()).getDeliveringCount()); + Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(QUEUE).getBindable()).getDeliveringCount()); int messagesOnServer = browser ? numMessages : 0; - Assert.assertEquals(messagesOnServer, - getMessageCount(((Queue)server.getPostOffice().getBinding(QUEUE).getBindable()))); + Assert.assertEquals(messagesOnServer, getMessageCount(((Queue) server.getPostOffice().getBinding(QUEUE).getBindable()))); consumer.close(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ReceiveTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ReceiveTest.java index 9813cbd0a0..6ebc41f164 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ReceiveTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ReceiveTest.java @@ -33,8 +33,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class ReceiveTest extends ActiveMQTestBase -{ +public class ReceiveTest extends ActiveMQTestBase { + SimpleString addressA = new SimpleString("addressA"); SimpleString queueA = new SimpleString("queueA"); @@ -45,8 +45,7 @@ public class ReceiveTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = createInVMNonHALocator(); @@ -55,8 +54,7 @@ public class ReceiveTest extends ActiveMQTestBase } @Test - public void testBasicReceive() throws Exception - { + public void testBasicReceive() throws Exception { ClientSessionFactory cf = createSessionFactory(locator); ClientSession sendSession = cf.createSession(false, true, true); ClientProducer cp = sendSession.createProducer(addressA); @@ -71,8 +69,7 @@ public class ReceiveTest extends ActiveMQTestBase } @Test - public void testReceiveTimesoutCorrectly() throws Exception - { + public void testReceiveTimesoutCorrectly() throws Exception { ClientSessionFactory cf = createSessionFactory(locator); ClientSession session = cf.createSession(false, true, true); @@ -86,8 +83,7 @@ public class ReceiveTest extends ActiveMQTestBase } @Test - public void testReceiveOnClosedException() throws Exception - { + public void testReceiveOnClosedException() throws Exception { ClientSessionFactory cf = createSessionFactory(locator); ClientSession session = cf.createSession(false, true, true); @@ -95,56 +91,46 @@ public class ReceiveTest extends ActiveMQTestBase ClientConsumer cc = session.createConsumer(queueA); session.start(); session.close(); - try - { + try { cc.receive(); Assert.fail("should throw exception"); } - catch (ActiveMQObjectClosedException oce) - { + catch (ActiveMQObjectClosedException oce) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { Assert.fail("Invalid Exception type:" + e.getType()); } session.close(); } @Test - public void testReceiveThrowsExceptionWhenHandlerSet() throws Exception - { + public void testReceiveThrowsExceptionWhenHandlerSet() throws Exception { ClientSessionFactory cf = createSessionFactory(locator); ClientSession session = cf.createSession(false, true, true); session.createQueue(addressA, queueA, false); ClientConsumer cc = session.createConsumer(queueA); session.start(); - cc.setMessageHandler(new MessageHandler() - { - public void onMessage(final ClientMessage message) - { + cc.setMessageHandler(new MessageHandler() { + public void onMessage(final ClientMessage message) { } }); - try - { + try { cc.receive(); Assert.fail("should throw exception"); } - catch (ActiveMQIllegalStateException ise) - { + catch (ActiveMQIllegalStateException ise) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { Assert.fail("Invalid Exception type:" + e.getType()); } session.close(); } @Test - public void testReceiveImmediate() throws Exception - { + public void testReceiveImmediate() throws Exception { // forces perfect round robin locator.setConsumerWindowSize(1); @@ -162,8 +148,7 @@ public class ReceiveTest extends ActiveMQTestBase Assert.assertNotNull(cc2.receive(5000)); Assert.assertNotNull(cc.receive(5000)); - if (cc.receiveImmediate() == null) - { + if (cc.receiveImmediate() == null) { Assert.assertNotNull(cc2.receiveImmediate()); } session.close(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/RedeliveryConsumerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/RedeliveryConsumerTest.java index dea83e66ba..aeb07649d6 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/RedeliveryConsumerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/RedeliveryConsumerTest.java @@ -40,8 +40,7 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Assert; import org.junit.Test; -public class RedeliveryConsumerTest extends ActiveMQTestBase -{ +public class RedeliveryConsumerTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -64,37 +63,31 @@ public class RedeliveryConsumerTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testRedeliveryMessageStrict() throws Exception - { + public void testRedeliveryMessageStrict() throws Exception { testDedeliveryMessageOnPersistent(true); } @Test - public void testRedeliveryMessageSimpleCancel() throws Exception - { + public void testRedeliveryMessageSimpleCancel() throws Exception { testDedeliveryMessageOnPersistent(false); } @Test - public void testDeliveryNonPersistent() throws Exception - { + public void testDeliveryNonPersistent() throws Exception { testDelivery(false); } @Test - public void testDeliveryPersistent() throws Exception - { + public void testDeliveryPersistent() throws Exception { testDelivery(true); } - public void testDelivery(final boolean persistent) throws Exception - { + public void testDelivery(final boolean persistent) throws Exception { setUp(true); ClientSession session = factory.createSession(false, false, false); ClientProducer prod = session.createProducer(ADDRESS); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { prod.send(createTextMessage(session, Integer.toString(i), persistent)); } @@ -104,11 +97,9 @@ public class RedeliveryConsumerTest extends ActiveMQTestBase session = factory.createSession(null, null, false, true, true, true, 0); session.start(); - for (int loopAck = 0; loopAck < 5; loopAck++) - { + for (int loopAck = 0; loopAck < 5; loopAck++) { ClientConsumer browser = session.createConsumer(ADDRESS, null, true); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage msg = browser.receive(1000); Assert.assertNotNull("element i=" + i + " loopAck = " + loopAck + " was expected", msg); msg.acknowledge(); @@ -129,10 +120,8 @@ public class RedeliveryConsumerTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(ADDRESS); - for (int loopAck = 0; loopAck < 5; loopAck++) - { - for (int i = 0; i < 10; i++) - { + for (int loopAck = 0; loopAck < 5; loopAck++) { + for (int i = 0; i < 10; i++) { ClientMessage msg = consumer.receive(1000); Assert.assertNotNull(msg); Assert.assertEquals(Integer.toString(i), getTextMessage(msg)); @@ -143,8 +132,7 @@ public class RedeliveryConsumerTest extends ActiveMQTestBase session.rollback(); } - if (persistent) - { + if (persistent) { session.close(); server.stop(); server.start(); @@ -154,20 +142,16 @@ public class RedeliveryConsumerTest extends ActiveMQTestBase consumer = session.createConsumer(ADDRESS); } - for (int loopAck = 1; loopAck <= 5; loopAck++) - { - for (int i = 0; i < 10; i++) - { + for (int loopAck = 1; loopAck <= 5; loopAck++) { + for (int i = 0; i < 10; i++) { ClientMessage msg = consumer.receive(1000); Assert.assertNotNull(msg); msg.acknowledge(); Assert.assertEquals(Integer.toString(i), getTextMessage(msg)); Assert.assertEquals(loopAck, msg.getDeliveryCount()); } - if (loopAck < 5) - { - if (persistent) - { + if (loopAck < 5) { + if (persistent) { session.close(); server.stop(); server.start(); @@ -176,8 +160,7 @@ public class RedeliveryConsumerTest extends ActiveMQTestBase session.start(); consumer = session.createConsumer(ADDRESS); } - else - { + else { session.rollback(); } } @@ -186,8 +169,7 @@ public class RedeliveryConsumerTest extends ActiveMQTestBase session.close(); } - protected void testDedeliveryMessageOnPersistent(final boolean strictUpdate) throws Exception - { + protected void testDedeliveryMessageOnPersistent(final boolean strictUpdate) throws Exception { setUp(strictUpdate); ClientSession session = factory.createSession(false, false, false); @@ -208,8 +190,7 @@ public class RedeliveryConsumerTest extends ActiveMQTestBase // if strictUpdate == true, this will simulate a crash, where the server is stopped without closing/rolling back // the session, but the delivery count still persisted, so the final delivery count is 2 too. - if (!strictUpdate) - { + if (!strictUpdate) { // If non Strict, at least rollback/cancel should still update the delivery-counts session.rollback(true); @@ -235,15 +216,12 @@ public class RedeliveryConsumerTest extends ActiveMQTestBase session.close(); } - @Test - public void testInfiniteDedeliveryMessageOnPersistent() throws Exception - { + public void testInfiniteDedeliveryMessageOnPersistent() throws Exception { internaltestInfiniteDedeliveryMessageOnPersistent(false); } - private void internaltestInfiniteDedeliveryMessageOnPersistent(final boolean strict) throws Exception - { + private void internaltestInfiniteDedeliveryMessageOnPersistent(final boolean strict) throws Exception { setUp(strict); ClientSession session = factory.createSession(false, false, false); @@ -254,10 +232,8 @@ public class RedeliveryConsumerTest extends ActiveMQTestBase session.commit(); session.close(); - int expectedCount = 1; - for (int i = 0; i < 700; i++) - { + for (int i = 0; i < 700; i++) { session = factory.createSession(false, false, false); session.start(); ClientConsumer consumer = session.createConsumer(ADDRESS); @@ -265,8 +241,7 @@ public class RedeliveryConsumerTest extends ActiveMQTestBase assertNotNull(msg); assertEquals(expectedCount, msg.getDeliveryCount()); - if (i % 100 == 0) - { + if (i % 100 == 0) { expectedCount++; msg.acknowledge(); session.rollback(); @@ -279,8 +254,7 @@ public class RedeliveryConsumerTest extends ActiveMQTestBase setUp(false); - for (int i = 0; i < 700; i++) - { + for (int i = 0; i < 700; i++) { session = factory.createSession(false, false, false); session.start(); ClientConsumer consumer = session.createConsumer(ADDRESS); @@ -292,51 +266,34 @@ public class RedeliveryConsumerTest extends ActiveMQTestBase server.stop(); - - JournalImpl journal = new JournalImpl(server.getConfiguration().getJournalFileSize(), - 2, - 0, - 0, - new NIOSequentialFileFactory(server.getConfiguration().getJournalLocation(), 1), - "activemq-data", - "amq", - 1); - + JournalImpl journal = new JournalImpl(server.getConfiguration().getJournalFileSize(), 2, 0, 0, new NIOSequentialFileFactory(server.getConfiguration().getJournalLocation(), 1), "activemq-data", "amq", 1); final AtomicInteger updates = new AtomicInteger(); journal.start(); - journal.load(new LoaderCallback() - { + journal.load(new LoaderCallback() { - public void failedTransaction(long transactionID, List records, List recordsToDelete) - { + public void failedTransaction(long transactionID, List records, List recordsToDelete) { } - public void updateRecord(RecordInfo info) - { - if (info.userRecordType == JournalRecordIds.UPDATE_DELIVERY_COUNT) - { + public void updateRecord(RecordInfo info) { + if (info.userRecordType == JournalRecordIds.UPDATE_DELIVERY_COUNT) { updates.incrementAndGet(); } } - public void deleteRecord(long id) - { + public void deleteRecord(long id) { } - public void addRecord(RecordInfo info) - { + public void addRecord(RecordInfo info) { } - public void addPreparedTransaction(PreparedTransactionInfo preparedTransaction) - { + public void addPreparedTransaction(PreparedTransactionInfo preparedTransaction) { } }); journal.stop(); - assertEquals(7, updates.get()); } @@ -349,10 +306,8 @@ public class RedeliveryConsumerTest extends ActiveMQTestBase * @param persistDeliveryCountBeforeDelivery * @throws Exception */ - private void setUp(final boolean persistDeliveryCountBeforeDelivery) throws Exception - { - Configuration config = createDefaultInVMConfig() - .setPersistDeliveryCountBeforeDelivery(persistDeliveryCountBeforeDelivery); + private void setUp(final boolean persistDeliveryCountBeforeDelivery) throws Exception { + Configuration config = createDefaultInVMConfig().setPersistDeliveryCountBeforeDelivery(persistDeliveryCountBeforeDelivery); server = createServer(true, config); @@ -361,12 +316,10 @@ public class RedeliveryConsumerTest extends ActiveMQTestBase factory = createSessionFactory(locator); ClientSession session = addClientSession(factory.createSession(false, false, false)); - try - { + try { session.createQueue(ADDRESS, ADDRESS, true); } - catch (ActiveMQException expected) - { + catch (ActiveMQException expected) { // in case of restart } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/RequestorTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/RequestorTest.java index ccd4245547..e087fa8c47 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/RequestorTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/RequestorTest.java @@ -37,16 +37,14 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class RequestorTest extends ActiveMQTestBase -{ +public class RequestorTest extends ActiveMQTestBase { private ActiveMQServer server; private ClientSessionFactory sf; private ServerLocator locator; @Test - public void testRequest() throws Exception - { + public void testRequest() throws Exception { final SimpleString key = RandomUtil.randomSimpleString(); long value = RandomUtil.randomLong(); SimpleString requestAddress = new SimpleString("AdTest"); @@ -74,14 +72,11 @@ public class RequestorTest extends ActiveMQTestBase } @Test - public void testManyRequestsOverBlocked() throws Exception - { + public void testManyRequestsOverBlocked() throws Exception { final SimpleString key = RandomUtil.randomSimpleString(); long value = RandomUtil.randomLong(); - AddressSettings settings = new AddressSettings() - .setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK) - .setMaxSizeBytes(1024); + AddressSettings settings = new AddressSettings().setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK).setMaxSizeBytes(1024); server.getAddressSettingsRepository().addMatch("#", settings); SimpleString requestAddress = new SimpleString("RequestAddress"); @@ -97,11 +92,8 @@ public class RequestorTest extends ActiveMQTestBase ClientConsumer requestConsumer = sessionRequest.createConsumer(requestQueue); requestConsumer.setMessageHandler(new SimpleMessageHandler(key, sessionRequest)); - - for (int i = 0; i < 2000; i++) - { - if (i % 100 == 0) - { + for (int i = 0; i < 2000; i++) { + if (i % 100 == 0) { System.out.println(i); } final ClientSession session = sf.createSession(false, true, true); @@ -125,8 +117,7 @@ public class RequestorTest extends ActiveMQTestBase } @Test - public void testTwoRequests() throws Exception - { + public void testTwoRequests() throws Exception { final SimpleString key = RandomUtil.randomSimpleString(); long value = RandomUtil.randomLong(); SimpleString requestAddress = RandomUtil.randomSimpleString(); @@ -161,8 +152,7 @@ public class RequestorTest extends ActiveMQTestBase } @Test - public void testRequestWithRequestConsumerWhichDoesNotReply() throws Exception - { + public void testRequestWithRequestConsumerWhichDoesNotReply() throws Exception { SimpleString requestAddress = RandomUtil.randomSimpleString(); SimpleString requestQueue = RandomUtil.randomSimpleString(); @@ -174,11 +164,9 @@ public class RequestorTest extends ActiveMQTestBase session.createTemporaryQueue(requestAddress, requestQueue); ClientConsumer requestConsumer = session.createConsumer(requestQueue); - requestConsumer.setMessageHandler(new MessageHandler() - { + requestConsumer.setMessageHandler(new MessageHandler() { // return a message with the negative request's value - public void onMessage(final ClientMessage request) - { + public void onMessage(final ClientMessage request) { // do nothing -> no reply } }); @@ -193,8 +181,7 @@ public class RequestorTest extends ActiveMQTestBase } @Test - public void testClientRequestorConstructorWithClosedSession() throws Exception - { + public void testClientRequestorConstructorWithClosedSession() throws Exception { final SimpleString requestAddress = RandomUtil.randomSimpleString(); ClientSessionFactory sf = createSessionFactory(locator); @@ -202,22 +189,17 @@ public class RequestorTest extends ActiveMQTestBase session.close(); - ActiveMQAction activeMQAction = new ActiveMQAction() - { - public void run() throws Exception - { + ActiveMQAction activeMQAction = new ActiveMQAction() { + public void run() throws Exception { new ClientRequestor(session, requestAddress); } }; - ActiveMQTestBase.expectActiveMQException("ClientRequestor's session must not be closed", - ActiveMQExceptionType.OBJECT_CLOSED, - activeMQAction); + ActiveMQTestBase.expectActiveMQException("ClientRequestor's session must not be closed", ActiveMQExceptionType.OBJECT_CLOSED, activeMQAction); } @Test - public void testClose() throws Exception - { + public void testClose() throws Exception { final SimpleString key = RandomUtil.randomSimpleString(); long value = RandomUtil.randomLong(); SimpleString requestAddress = RandomUtil.randomSimpleString(); @@ -246,46 +228,38 @@ public class RequestorTest extends ActiveMQTestBase requestor.close(); - ActiveMQAction activeMQAction = new ActiveMQAction() - { - public void run() throws Exception - { + ActiveMQAction activeMQAction = new ActiveMQAction() { + public void run() throws Exception { requestor.request(session.createMessage(false), 500); } }; - ActiveMQTestBase.expectActiveMQException("can not send a request on a closed ClientRequestor", - ActiveMQExceptionType.OBJECT_CLOSED, activeMQAction); + ActiveMQTestBase.expectActiveMQException("can not send a request on a closed ClientRequestor", ActiveMQExceptionType.OBJECT_CLOSED, activeMQAction); } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(false, createDefaultInVMConfig()); server.start(); - locator = createInVMNonHALocator() - .setAckBatchSize(0); + locator = createInVMNonHALocator().setAckBatchSize(0); sf = createSessionFactory(locator); } - private final class SimpleMessageHandler implements MessageHandler - { + private final class SimpleMessageHandler implements MessageHandler { + private final SimpleString key; private final ClientSession session; - private SimpleMessageHandler(final SimpleString key, final ClientSession session) - { + private SimpleMessageHandler(final SimpleString key, final ClientSession session) { this.key = key; this.session = session; } - public void onMessage(final ClientMessage request) - { - try - { + public void onMessage(final ClientMessage request) { + try { ClientMessage reply = session.createMessage(false); SimpleString replyTo = (SimpleString) request.getObjectProperty(ClientMessageImpl.REPLYTO_HEADER_NAME); long value = (Long) request.getObjectProperty(key); @@ -294,8 +268,7 @@ public class RequestorTest extends ActiveMQTestBase replyProducer.send(reply); request.acknowledge(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { e.printStackTrace(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/RoutingTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/RoutingTest.java index 39e25aac5e..8e4314cfa0 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/RoutingTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/RoutingTest.java @@ -29,8 +29,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class RoutingTest extends ActiveMQTestBase -{ +public class RoutingTest extends ActiveMQTestBase { + public final SimpleString addressA = new SimpleString("addressA"); public final SimpleString queueA = new SimpleString("queueA"); public final SimpleString queueB = new SimpleString("queueB"); @@ -42,8 +42,7 @@ public class RoutingTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = createInVMNonHALocator(); server = createServer(false); @@ -53,16 +52,14 @@ public class RoutingTest extends ActiveMQTestBase } @Test - public void testRouteToMultipleQueues() throws Exception - { + public void testRouteToMultipleQueues() throws Exception { ClientSession sendSession = cf.createSession(false, true, true); sendSession.createQueue(addressA, queueA, false); sendSession.createQueue(addressA, queueB, false); sendSession.createQueue(addressA, queueC, false); int numMessages = 300; ClientProducer p = sendSession.createProducer(addressA); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { p.send(sendSession.createMessage(false)); } ClientSession session = cf.createSession(false, true, true); @@ -70,8 +67,7 @@ public class RoutingTest extends ActiveMQTestBase ClientConsumer c2 = session.createConsumer(queueB); ClientConsumer c3 = session.createConsumer(queueC); session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage m = c1.receive(5000); Assert.assertNotNull(m); m.acknowledge(); @@ -90,21 +86,18 @@ public class RoutingTest extends ActiveMQTestBase } @Test - public void testRouteToSingleNonDurableQueue() throws Exception - { + public void testRouteToSingleNonDurableQueue() throws Exception { ClientSession sendSession = cf.createSession(false, true, true); sendSession.createQueue(addressA, queueA, false); int numMessages = 300; ClientProducer p = sendSession.createProducer(addressA); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { p.send(sendSession.createMessage(false)); } ClientSession session = cf.createSession(false, true, true); ClientConsumer c1 = session.createConsumer(queueA); session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage m = c1.receive(5000); Assert.assertNotNull(m); m.acknowledge(); @@ -115,21 +108,18 @@ public class RoutingTest extends ActiveMQTestBase } @Test - public void testRouteToSingleDurableQueue() throws Exception - { + public void testRouteToSingleDurableQueue() throws Exception { ClientSession sendSession = cf.createSession(false, true, true); sendSession.createQueue(addressA, queueA, true); int numMessages = 300; ClientProducer p = sendSession.createProducer(addressA); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { p.send(sendSession.createMessage(false)); } ClientSession session = cf.createSession(false, true, true); ClientConsumer c1 = session.createConsumer(queueA); session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage m = c1.receive(5000); Assert.assertNotNull(m); m.acknowledge(); @@ -140,14 +130,12 @@ public class RoutingTest extends ActiveMQTestBase } @Test - public void testRouteToSingleQueueWithFilter() throws Exception - { + public void testRouteToSingleQueueWithFilter() throws Exception { ClientSession sendSession = cf.createSession(false, true, true); sendSession.createQueue(addressA, queueA, new SimpleString("foo = 'bar'"), false); int numMessages = 300; ClientProducer p = sendSession.createProducer(addressA); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage clientMessage = sendSession.createMessage(false); clientMessage.putStringProperty(new SimpleString("foo"), new SimpleString("bar")); p.send(clientMessage); @@ -155,8 +143,7 @@ public class RoutingTest extends ActiveMQTestBase ClientSession session = cf.createSession(false, true, true); ClientConsumer c1 = session.createConsumer(queueA); session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage m = c1.receive(5000); Assert.assertNotNull(m); m.acknowledge(); @@ -167,27 +154,22 @@ public class RoutingTest extends ActiveMQTestBase } @Test - public void testRouteToMultipleQueueWithFilters() throws Exception - { + public void testRouteToMultipleQueueWithFilters() throws Exception { ClientSession sendSession = cf.createSession(false, true, true); sendSession.createQueue(addressA, queueA, new SimpleString("foo = 'bar'"), false); sendSession.createQueue(addressA, queueB, new SimpleString("x = 1"), false); sendSession.createQueue(addressA, queueC, new SimpleString("b = false"), false); int numMessages = 300; ClientProducer p = sendSession.createProducer(addressA); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage clientMessage = sendSession.createMessage(false); - if (i % 3 == 0) - { + if (i % 3 == 0) { clientMessage.putStringProperty(new SimpleString("foo"), new SimpleString("bar")); } - else if (i % 3 == 1) - { + else if (i % 3 == 1) { clientMessage.putIntProperty(new SimpleString("x"), 1); } - else - { + else { clientMessage.putBooleanProperty(new SimpleString("b"), false); } p.send(clientMessage); @@ -197,8 +179,7 @@ public class RoutingTest extends ActiveMQTestBase ClientConsumer c2 = session.createConsumer(queueB); ClientConsumer c3 = session.createConsumer(queueC); session.start(); - for (int i = 0; i < numMessages / 3; i++) - { + for (int i = 0; i < numMessages / 3; i++) { ClientMessage m = c1.receive(5000); Assert.assertNotNull(m); m.acknowledge(); @@ -217,21 +198,18 @@ public class RoutingTest extends ActiveMQTestBase } @Test - public void testRouteToSingleTemporaryQueue() throws Exception - { + public void testRouteToSingleTemporaryQueue() throws Exception { ClientSession sendSession = cf.createSession(false, true, true); sendSession.createTemporaryQueue(addressA, queueA); int numMessages = 300; ClientProducer p = sendSession.createProducer(addressA); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { p.send(sendSession.createMessage(false)); } ClientSession session = cf.createSession(false, true, true); ClientConsumer c1 = session.createConsumer(queueA); session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage m = c1.receive(5000); Assert.assertNotNull(m); m.acknowledge(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SelfExpandingBufferTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SelfExpandingBufferTest.java index be94e656f0..bb92a19178 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SelfExpandingBufferTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SelfExpandingBufferTest.java @@ -31,8 +31,7 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Assert; import org.junit.Test; -public class SelfExpandingBufferTest extends ActiveMQTestBase -{ +public class SelfExpandingBufferTest extends ActiveMQTestBase { private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @@ -41,31 +40,26 @@ public class SelfExpandingBufferTest extends ActiveMQTestBase SimpleString ADDRESS = new SimpleString("Address"); @Test - public void testSelfExpandingBufferNettyPersistent() throws Exception - { + public void testSelfExpandingBufferNettyPersistent() throws Exception { testSelfExpandingBuffer(true, true); } @Test - public void testSelfExpandingBufferInVMPersistent() throws Exception - { + public void testSelfExpandingBufferInVMPersistent() throws Exception { testSelfExpandingBuffer(false, true); } @Test - public void testSelfExpandingBufferNettyNonPersistent() throws Exception - { + public void testSelfExpandingBufferNettyNonPersistent() throws Exception { testSelfExpandingBuffer(true, false); } @Test - public void testSelfExpandingBufferInVMNonPersistent() throws Exception - { + public void testSelfExpandingBufferInVMNonPersistent() throws Exception { testSelfExpandingBuffer(false, false); } - private void testSelfExpandingBuffer(final boolean netty, final boolean persistent) throws Exception - { + private void testSelfExpandingBuffer(final boolean netty, final boolean persistent) throws Exception { setUpService(netty, persistent); ClientSessionFactory factory; @@ -76,8 +70,7 @@ public class SelfExpandingBufferTest extends ActiveMQTestBase ClientSession session = factory.createSession(false, true, true); - try - { + try { session.createQueue(ADDRESS, ADDRESS, true); @@ -127,8 +120,7 @@ public class SelfExpandingBufferTest extends ActiveMQTestBase ActiveMQTestBase.assertEqualsByteArrays(bytes, receivedBytes); } - finally - { + finally { session.close(); } } @@ -137,8 +129,7 @@ public class SelfExpandingBufferTest extends ActiveMQTestBase // Protected ----------------------------------------------------- - protected void setUpService(final boolean netty, final boolean persistent) throws Exception - { + protected void setUpService(final boolean netty, final boolean persistent) throws Exception { service = createServer(persistent, createDefaultConfig(netty)); service.start(); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ServerLocatorConnectTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ServerLocatorConnectTest.java index c5fa30b1dd..21711c74c8 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ServerLocatorConnectTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/ServerLocatorConnectTest.java @@ -34,14 +34,13 @@ import org.apache.activemq.artemis.uri.ServerLocatorParser; import org.junit.Before; import org.junit.Test; -public class ServerLocatorConnectTest extends ActiveMQTestBase -{ +public class ServerLocatorConnectTest extends ActiveMQTestBase { + private ActiveMQServer server; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); Configuration configuration = createDefaultConfig(isNetty()); server = createServer(false, configuration); @@ -49,8 +48,7 @@ public class ServerLocatorConnectTest extends ActiveMQTestBase } @Test - public void testURL() throws Exception - { + public void testURL() throws Exception { ServerLocatorParser parser = new ServerLocatorParser(); // This URL was failing in some ConnectionFactoryTests. // The issue seemed to be the # to be creating extra spaces on the parsing @@ -69,8 +67,7 @@ public class ServerLocatorConnectTest extends ActiveMQTestBase "port=61616&host=localhost#"); // try it a few times to make sure it fails if it's broken - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ServerLocator locator = parser.newObject(uri, null); ClientSessionFactory csf = createSessionFactory(locator); csf.close(); @@ -80,8 +77,7 @@ public class ServerLocatorConnectTest extends ActiveMQTestBase } @Test - public void testSingleConnectorSingleServer() throws Exception - { + public void testSingleConnectorSingleServer() throws Exception { ServerLocator locator = ActiveMQClient.createServerLocatorWithoutHA(createTransportConfiguration(isNetty(), false, generateParams(0, isNetty()))); ClientSessionFactory csf = createSessionFactory(locator); csf.close(); @@ -89,8 +85,7 @@ public class ServerLocatorConnectTest extends ActiveMQTestBase } @Test - public void testSingleConnectorSingleServerConnect() throws Exception - { + public void testSingleConnectorSingleServerConnect() throws Exception { ServerLocatorInternal locator = (ServerLocatorInternal) ActiveMQClient.createServerLocatorWithoutHA(createTransportConfiguration(isNetty(), false, generateParams(0, isNetty()))); ClientSessionFactoryInternal csf = locator.connect(); assertNotNull(csf); @@ -99,15 +94,8 @@ public class ServerLocatorConnectTest extends ActiveMQTestBase } @Test - public void testMultipleConnectorSingleServerConnect() throws Exception - { - ServerLocatorInternal locator = (ServerLocatorInternal) ActiveMQClient.createServerLocatorWithoutHA( - createTransportConfiguration(isNetty(), false, generateParams(0, isNetty())), - createTransportConfiguration(isNetty(), false, generateParams(1, isNetty())), - createTransportConfiguration(isNetty(), false, generateParams(2, isNetty())), - createTransportConfiguration(isNetty(), false, generateParams(3, isNetty())), - createTransportConfiguration(isNetty(), false, generateParams(4, isNetty())) - ); + public void testMultipleConnectorSingleServerConnect() throws Exception { + ServerLocatorInternal locator = (ServerLocatorInternal) ActiveMQClient.createServerLocatorWithoutHA(createTransportConfiguration(isNetty(), false, generateParams(0, isNetty())), createTransportConfiguration(isNetty(), false, generateParams(1, isNetty())), createTransportConfiguration(isNetty(), false, generateParams(2, isNetty())), createTransportConfiguration(isNetty(), false, generateParams(3, isNetty())), createTransportConfiguration(isNetty(), false, generateParams(4, isNetty()))); ClientSessionFactoryInternal csf = locator.connect(); assertNotNull(csf); assertEquals(csf.numConnections(), 1); @@ -115,15 +103,8 @@ public class ServerLocatorConnectTest extends ActiveMQTestBase } @Test - public void testMultipleConnectorSingleServerConnectReconnect() throws Exception - { - ServerLocatorInternal locator = (ServerLocatorInternal) ActiveMQClient.createServerLocatorWithoutHA( - createTransportConfiguration(isNetty(), false, generateParams(0, isNetty())), - createTransportConfiguration(isNetty(), false, generateParams(1, isNetty())), - createTransportConfiguration(isNetty(), false, generateParams(2, isNetty())), - createTransportConfiguration(isNetty(), false, generateParams(3, isNetty())), - createTransportConfiguration(isNetty(), false, generateParams(4, isNetty())) - ); + public void testMultipleConnectorSingleServerConnectReconnect() throws Exception { + ServerLocatorInternal locator = (ServerLocatorInternal) ActiveMQClient.createServerLocatorWithoutHA(createTransportConfiguration(isNetty(), false, generateParams(0, isNetty())), createTransportConfiguration(isNetty(), false, generateParams(1, isNetty())), createTransportConfiguration(isNetty(), false, generateParams(2, isNetty())), createTransportConfiguration(isNetty(), false, generateParams(3, isNetty())), createTransportConfiguration(isNetty(), false, generateParams(4, isNetty()))); locator.setReconnectAttempts(-1); ClientSessionFactoryInternal csf = locator.connect(); assertNotNull(csf); @@ -132,26 +113,16 @@ public class ServerLocatorConnectTest extends ActiveMQTestBase } @Test - public void testMultipleConnectorSingleServerNoConnect() throws Exception - { - ServerLocatorInternal locator = (ServerLocatorInternal) ActiveMQClient.createServerLocatorWithoutHA( - createTransportConfiguration(isNetty(), false, generateParams(1, isNetty())), - createTransportConfiguration(isNetty(), false, generateParams(2, isNetty())), - createTransportConfiguration(isNetty(), false, generateParams(3, isNetty())), - createTransportConfiguration(isNetty(), false, generateParams(4, isNetty())), - createTransportConfiguration(isNetty(), false, generateParams(5, isNetty())) - ); + public void testMultipleConnectorSingleServerNoConnect() throws Exception { + ServerLocatorInternal locator = (ServerLocatorInternal) ActiveMQClient.createServerLocatorWithoutHA(createTransportConfiguration(isNetty(), false, generateParams(1, isNetty())), createTransportConfiguration(isNetty(), false, generateParams(2, isNetty())), createTransportConfiguration(isNetty(), false, generateParams(3, isNetty())), createTransportConfiguration(isNetty(), false, generateParams(4, isNetty())), createTransportConfiguration(isNetty(), false, generateParams(5, isNetty()))); ClientSessionFactoryInternal csf = null; - try - { + try { csf = locator.connect(); } - catch (ActiveMQNotConnectedException nce) - { + catch (ActiveMQNotConnectedException nce) { //ok } - catch (Exception e) - { + catch (Exception e) { assertTrue(e instanceof ActiveMQException); fail("Invalid Exception type:" + ((ActiveMQException) e).getType()); } @@ -160,15 +131,8 @@ public class ServerLocatorConnectTest extends ActiveMQTestBase } @Test - public void testMultipleConnectorSingleServerNoConnectAttemptReconnect() throws Exception - { - ServerLocatorInternal locator = (ServerLocatorInternal) ActiveMQClient.createServerLocatorWithoutHA( - createTransportConfiguration(isNetty(), false, generateParams(1, isNetty())), - createTransportConfiguration(isNetty(), false, generateParams(2, isNetty())), - createTransportConfiguration(isNetty(), false, generateParams(3, isNetty())), - createTransportConfiguration(isNetty(), false, generateParams(4, isNetty())), - createTransportConfiguration(isNetty(), false, generateParams(5, isNetty())) - ); + public void testMultipleConnectorSingleServerNoConnectAttemptReconnect() throws Exception { + ServerLocatorInternal locator = (ServerLocatorInternal) ActiveMQClient.createServerLocatorWithoutHA(createTransportConfiguration(isNetty(), false, generateParams(1, isNetty())), createTransportConfiguration(isNetty(), false, generateParams(2, isNetty())), createTransportConfiguration(isNetty(), false, generateParams(3, isNetty())), createTransportConfiguration(isNetty(), false, generateParams(4, isNetty())), createTransportConfiguration(isNetty(), false, generateParams(5, isNetty()))); locator.setReconnectAttempts(-1); CountDownLatch countDownLatch = new CountDownLatch(1); Connector target = new Connector(locator, countDownLatch); @@ -181,32 +145,27 @@ public class ServerLocatorConnectTest extends ActiveMQTestBase assertNull(target.csf); } - public boolean isNetty() - { + public boolean isNetty() { return true; } - static class Connector implements Runnable - { + static class Connector implements Runnable { + private final ServerLocatorInternal locator; ClientSessionFactory csf = null; CountDownLatch latch; Exception e; - public Connector(ServerLocatorInternal locator, CountDownLatch latch) - { + public Connector(ServerLocatorInternal locator, CountDownLatch latch) { this.locator = locator; this.latch = latch; } - public void run() - { - try - { + public void run() { + try { csf = locator.connect(); } - catch (Exception e) - { + catch (Exception e) { this.e = e; } latch.countDown(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionCloseOnGCTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionCloseOnGCTest.java index 61c37d58a2..080322b973 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionCloseOnGCTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionCloseOnGCTest.java @@ -28,15 +28,14 @@ import org.junit.Test; import java.lang.ref.WeakReference; -public class SessionCloseOnGCTest extends ActiveMQTestBase -{ +public class SessionCloseOnGCTest extends ActiveMQTestBase { + private ActiveMQServer server; private ServerLocator locator; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(false); @@ -50,8 +49,7 @@ public class SessionCloseOnGCTest extends ActiveMQTestBase * Also... we want to make sure the SessionFactory will close itself when there are not references into it */ @Test - public void testValidateFactoryGC1() throws Exception - { + public void testValidateFactoryGC1() throws Exception { ClientSessionFactory factory = locator.createSessionFactory(); ClientSession s1 = factory.createSession(); @@ -81,8 +79,7 @@ public class SessionCloseOnGCTest extends ActiveMQTestBase } @Test - public void testValidateFactoryGC2() throws Exception - { + public void testValidateFactoryGC2() throws Exception { locator.setUseGlobalPools(false); ClientSessionFactory factory = locator.createSessionFactory(); @@ -114,8 +111,7 @@ public class SessionCloseOnGCTest extends ActiveMQTestBase } @Test - public void testValidateFactoryGC3() throws Exception - { + public void testValidateFactoryGC3() throws Exception { ClientSessionFactory factory = locator.createSessionFactory(); ClientSession s1 = factory.createSession(); @@ -143,8 +139,7 @@ public class SessionCloseOnGCTest extends ActiveMQTestBase } @Test - public void testValidateFactoryGC4() throws Exception - { + public void testValidateFactoryGC4() throws Exception { ClientSessionFactory factory = locator.createSessionFactory(); ClientSession s1 = factory.createSession(); @@ -169,8 +164,7 @@ public class SessionCloseOnGCTest extends ActiveMQTestBase } @Test - public void testValidateFactoryGC5() throws Exception - { + public void testValidateFactoryGC5() throws Exception { ClientSessionFactory factory = locator.createSessionFactory(); WeakReference fref = new WeakReference(factory); @@ -184,8 +178,7 @@ public class SessionCloseOnGCTest extends ActiveMQTestBase } @Test - public void testCloseOneSessionOnGC() throws Exception - { + public void testCloseOneSessionOnGC() throws Exception { ClientSessionFactoryImpl sf = (ClientSessionFactoryImpl) locator.createSessionFactory(); ClientSession session = sf.createSession(false, true, true); @@ -204,8 +197,7 @@ public class SessionCloseOnGCTest extends ActiveMQTestBase } @Test - public void testCloseSeveralSessionOnGC() throws Exception - { + public void testCloseSeveralSessionOnGC() throws Exception { ClientSessionFactoryImpl sf = (ClientSessionFactoryImpl) locator.createSessionFactory(); ClientSession session1 = sf.createSession(false, true, true); @@ -227,14 +219,12 @@ public class SessionCloseOnGCTest extends ActiveMQTestBase int count = 0; final int TOTAL_SLEEP_TIME = 400; final int MAX_COUNT = 20; - while (count++ < MAX_COUNT) - { + while (count++ < MAX_COUNT) { /* * The assertion is vulnerable to races, both in the session closing as well as the return * value of the sessions.size() (i.e. HashSet.size()). */ - synchronized (this) - { + synchronized (this) { // synchronized block will (as a side effect) force sync all field values if (sf.numSessions() == 0) break; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionCloseTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionCloseTest.java index 7f3a80ccd5..90d9cdd298 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionCloseTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionCloseTest.java @@ -35,8 +35,7 @@ import org.junit.Test; import javax.transaction.xa.XAException; import javax.transaction.xa.XAResource; -public class SessionCloseTest extends ActiveMQTestBase -{ +public class SessionCloseTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -53,8 +52,7 @@ public class SessionCloseTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testCanNotUseAClosedSession() throws Exception - { + public void testCanNotUseAClosedSession() throws Exception { final ClientSession session = sf.createSession(false, true, true); @@ -62,84 +60,62 @@ public class SessionCloseTest extends ActiveMQTestBase Assert.assertTrue(session.isClosed()); - ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() - { - public void run() throws ActiveMQException - { + ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() { + public void run() throws ActiveMQException { session.createProducer(); } }); - ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() - { - public void run() throws ActiveMQException - { + ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() { + public void run() throws ActiveMQException { session.createConsumer(RandomUtil.randomSimpleString()); } }); - ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() - { - public void run() throws ActiveMQException - { - session.createQueue(RandomUtil.randomSimpleString(), - RandomUtil.randomSimpleString(), - RandomUtil.randomBoolean()); + ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() { + public void run() throws ActiveMQException { + session.createQueue(RandomUtil.randomSimpleString(), RandomUtil.randomSimpleString(), RandomUtil.randomBoolean()); } }); - ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() - { - public void run() throws ActiveMQException - { + ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() { + public void run() throws ActiveMQException { session.createTemporaryQueue(RandomUtil.randomSimpleString(), RandomUtil.randomSimpleString()); } }); - ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() - { - public void run() throws ActiveMQException - { + ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() { + public void run() throws ActiveMQException { session.start(); } }); - ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() - { - public void run() throws ActiveMQException - { + ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() { + public void run() throws ActiveMQException { session.stop(); } }); - ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() - { - public void run() throws ActiveMQException - { + ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() { + public void run() throws ActiveMQException { session.commit(); } }); - ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() - { - public void run() throws ActiveMQException - { + ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() { + public void run() throws ActiveMQException { session.rollback(); } }); - ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() - { - public void run() throws ActiveMQException - { + ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() { + public void run() throws ActiveMQException { session.queueQuery(RandomUtil.randomSimpleString()); } }); - ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() - { - public void run() throws ActiveMQException - { + ActiveMQTestBase.expectActiveMQException(ActiveMQExceptionType.OBJECT_CLOSED, new ActiveMQAction() { + public void run() throws ActiveMQException { session.addressQuery(RandomUtil.randomSimpleString()); } }); @@ -147,8 +123,7 @@ public class SessionCloseTest extends ActiveMQTestBase } @Test - public void testCanNotUseXAWithClosedSession() throws Exception - { + public void testCanNotUseXAWithClosedSession() throws Exception { final ClientSession session = sf.createSession(true, false, false); @@ -157,58 +132,44 @@ public class SessionCloseTest extends ActiveMQTestBase Assert.assertTrue(session.isXA()); Assert.assertTrue(session.isClosed()); - ActiveMQTestBase.expectXAException(XAException.XA_RETRY, new ActiveMQAction() - { - public void run() throws XAException - { + ActiveMQTestBase.expectXAException(XAException.XA_RETRY, new ActiveMQAction() { + public void run() throws XAException { session.commit(RandomUtil.randomXid(), RandomUtil.randomBoolean()); } }); - ActiveMQTestBase.expectXAException(XAException.XAER_RMFAIL, new ActiveMQAction() - { - public void run() throws XAException - { + ActiveMQTestBase.expectXAException(XAException.XAER_RMFAIL, new ActiveMQAction() { + public void run() throws XAException { session.end(RandomUtil.randomXid(), XAResource.TMSUCCESS); } }); - ActiveMQTestBase.expectXAException(XAException.XAER_RMFAIL, new ActiveMQAction() - { - public void run() throws XAException - { + ActiveMQTestBase.expectXAException(XAException.XAER_RMFAIL, new ActiveMQAction() { + public void run() throws XAException { session.forget(RandomUtil.randomXid()); } }); - ActiveMQTestBase.expectXAException(XAException.XAER_RMFAIL, new ActiveMQAction() - { - public void run() throws XAException - { + ActiveMQTestBase.expectXAException(XAException.XAER_RMFAIL, new ActiveMQAction() { + public void run() throws XAException { session.prepare(RandomUtil.randomXid()); } }); - ActiveMQTestBase.expectXAException(XAException.XAER_RMFAIL, new ActiveMQAction() - { - public void run() throws XAException - { + ActiveMQTestBase.expectXAException(XAException.XAER_RMFAIL, new ActiveMQAction() { + public void run() throws XAException { session.recover(XAResource.TMSTARTRSCAN); } }); - ActiveMQTestBase.expectXAException(XAException.XAER_RMFAIL, new ActiveMQAction() - { - public void run() throws XAException - { + ActiveMQTestBase.expectXAException(XAException.XAER_RMFAIL, new ActiveMQAction() { + public void run() throws XAException { session.rollback(RandomUtil.randomXid()); } }); - ActiveMQTestBase.expectXAException(XAException.XAER_RMFAIL, new ActiveMQAction() - { - public void run() throws XAException - { + ActiveMQTestBase.expectXAException(XAException.XAER_RMFAIL, new ActiveMQAction() { + public void run() throws XAException { session.start(RandomUtil.randomXid(), XAResource.TMNOFLAGS); } }); @@ -216,8 +177,7 @@ public class SessionCloseTest extends ActiveMQTestBase } @Test - public void testCloseHierarchy() throws Exception - { + public void testCloseHierarchy() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -242,8 +202,7 @@ public class SessionCloseTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = addServer(ActiveMQServers.newActiveMQServer(createDefaultInVMConfig(), false)); server.start(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionClosedOnRemotingConnectionFailureTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionClosedOnRemotingConnectionFailureTest.java index 08cb847ea0..8c80988a84 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionClosedOnRemotingConnectionFailureTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionClosedOnRemotingConnectionFailureTest.java @@ -33,15 +33,14 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class SessionClosedOnRemotingConnectionFailureTest extends ActiveMQTestBase -{ +public class SessionClosedOnRemotingConnectionFailureTest extends ActiveMQTestBase { + private ActiveMQServer server; private ClientSessionFactory sf; @Test - public void testSessionClosedOnRemotingConnectionFailure() throws Exception - { + public void testSessionClosedOnRemotingConnectionFailure() throws Exception { ClientSession session = addClientSession(sf.createSession()); session.createQueue("fooaddress", "fooqueue"); @@ -70,33 +69,27 @@ public class SessionClosedOnRemotingConnectionFailureTest extends ActiveMQTestBa // Now try and use the producer - try - { + try { prod.send(session.createMessage(false)); Assert.fail("Should throw exception"); } - catch (ActiveMQObjectClosedException oce) - { + catch (ActiveMQObjectClosedException oce) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } - try - { + try { cons.receive(); Assert.fail("Should throw exception"); } - catch (ActiveMQObjectClosedException oce) - { + catch (ActiveMQObjectClosedException oce) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } @@ -105,8 +98,7 @@ public class SessionClosedOnRemotingConnectionFailureTest extends ActiveMQTestBa @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); Configuration config = createDefaultInVMConfig(); server = createServer(false, config); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionCreateAndDeleteQueueTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionCreateAndDeleteQueueTest.java index 42f550c447..5f5d2dedce 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionCreateAndDeleteQueueTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionCreateAndDeleteQueueTest.java @@ -31,8 +31,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class SessionCreateAndDeleteQueueTest extends ActiveMQTestBase -{ +public class SessionCreateAndDeleteQueueTest extends ActiveMQTestBase { + private ActiveMQServer server; private final SimpleString address = new SimpleString("address"); @@ -41,10 +41,8 @@ public class SessionCreateAndDeleteQueueTest extends ActiveMQTestBase private ServerLocator locator; - @Test - public void testDurableFalse() throws Exception - { + public void testDurableFalse() throws Exception { ClientSession session = createSessionFactory(locator).createSession(false, true, true); session.createQueue(address, queueName, false); Binding binding = server.getPostOffice().getBinding(queueName); @@ -55,8 +53,7 @@ public class SessionCreateAndDeleteQueueTest extends ActiveMQTestBase } @Test - public void testDurableTrue() throws Exception - { + public void testDurableTrue() throws Exception { ClientSession session = createSessionFactory(locator).createSession(false, true, true); session.createQueue(address, queueName, true); Binding binding = server.getPostOffice().getBinding(queueName); @@ -67,8 +64,7 @@ public class SessionCreateAndDeleteQueueTest extends ActiveMQTestBase } @Test - public void testTemporaryFalse() throws Exception - { + public void testTemporaryFalse() throws Exception { ClientSession session = createSessionFactory(locator).createSession(false, true, true); session.createQueue(address, queueName, false); Binding binding = server.getPostOffice().getBinding(queueName); @@ -79,8 +75,7 @@ public class SessionCreateAndDeleteQueueTest extends ActiveMQTestBase } @Test - public void testTemporaryTrue() throws Exception - { + public void testTemporaryTrue() throws Exception { ClientSession session = createSessionFactory(locator).createSession(false, true, true); session.createTemporaryQueue(address, queueName); Binding binding = server.getPostOffice().getBinding(queueName); @@ -91,8 +86,7 @@ public class SessionCreateAndDeleteQueueTest extends ActiveMQTestBase } @Test - public void testcreateWithFilter() throws Exception - { + public void testcreateWithFilter() throws Exception { ClientSession session = createSessionFactory(locator).createSession(false, true, true); SimpleString filterString = new SimpleString("x=y"); session.createQueue(address, queueName, filterString, false); @@ -104,8 +98,7 @@ public class SessionCreateAndDeleteQueueTest extends ActiveMQTestBase } @Test - public void testAddressSettingUSed() throws Exception - { + public void testAddressSettingUSed() throws Exception { server.getAddressSettingsRepository().addMatch(address.toString(), new AddressSettings().setLastValueQueue(true)); ClientSession session = createSessionFactory(locator).createSession(false, true, true); SimpleString filterString = new SimpleString("x=y"); @@ -117,8 +110,7 @@ public class SessionCreateAndDeleteQueueTest extends ActiveMQTestBase } @Test - public void testDeleteQueue() throws Exception - { + public void testDeleteQueue() throws Exception { ClientSession session = createSessionFactory(locator).createSession(false, true, true); session.createQueue(address, queueName, false); Binding binding = server.getPostOffice().getBinding(queueName); @@ -130,20 +122,16 @@ public class SessionCreateAndDeleteQueueTest extends ActiveMQTestBase } @Test - public void testDeleteQueueNotExist() throws Exception - { + public void testDeleteQueueNotExist() throws Exception { ClientSession session = createSessionFactory(locator).createSession(false, true, true); - try - { + try { session.deleteQueue(queueName); Assert.fail("should throw exception"); } - catch (ActiveMQNonExistentQueueException neqe) - { + catch (ActiveMQNonExistentQueueException neqe) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } session.close(); @@ -151,8 +139,7 @@ public class SessionCreateAndDeleteQueueTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(false); server.start(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionCreateConsumerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionCreateConsumerTest.java index a19f796212..4d0697379c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionCreateConsumerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionCreateConsumerTest.java @@ -29,8 +29,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class SessionCreateConsumerTest extends ActiveMQTestBase -{ +public class SessionCreateConsumerTest extends ActiveMQTestBase { + private final String queueName = "ClientSessionCreateConsumerTestQ"; private ServerLocator locator; @@ -40,84 +40,69 @@ public class SessionCreateConsumerTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { locator = createInVMNonHALocator(); super.setUp(); service = createServer(false); service.start(); - locator.setProducerMaxRate(99) - .setBlockOnNonDurableSend(true) - .setBlockOnNonDurableSend(true); + locator.setProducerMaxRate(99).setBlockOnNonDurableSend(true).setBlockOnNonDurableSend(true); cf = createSessionFactory(locator); clientSession = (ClientSessionInternal) addClientSession(cf.createSession(false, true, true)); } @Test - public void testCreateConsumer() throws Exception - { + public void testCreateConsumer() throws Exception { clientSession.createQueue(queueName, queueName, false); ClientConsumer consumer = clientSession.createConsumer(queueName); Assert.assertNotNull(consumer); } @Test - public void testCreateConsumerNoQ() throws Exception - { - try - { + public void testCreateConsumerNoQ() throws Exception { + try { clientSession.createConsumer(queueName); Assert.fail("should throw exception"); } - catch (ActiveMQNonExistentQueueException neqe) - { + catch (ActiveMQNonExistentQueueException neqe) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } } @Test - public void testCreateConsumerWithFilter() throws Exception - { + public void testCreateConsumerWithFilter() throws Exception { clientSession.createQueue(queueName, queueName, false); ClientConsumer consumer = clientSession.createConsumer(queueName, "foo=bar"); Assert.assertNotNull(consumer); } @Test - public void testCreateConsumerWithInvalidFilter() throws Exception - { + public void testCreateConsumerWithInvalidFilter() throws Exception { clientSession.createQueue(queueName, queueName, false); - try - { + try { clientSession.createConsumer(queueName, "this is not valid filter"); Assert.fail("should throw exception"); } - catch (ActiveMQInvalidFilterExpressionException ifee) - { + catch (ActiveMQInvalidFilterExpressionException ifee) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } } @Test - public void testCreateConsumerWithBrowseOnly() throws Exception - { + public void testCreateConsumerWithBrowseOnly() throws Exception { clientSession.createQueue(queueName, queueName, false); ClientConsumer consumer = clientSession.createConsumer(queueName, null, true); Assert.assertNotNull(consumer); } @Test - public void testCreateConsumerWithOverrides() throws Exception - { + public void testCreateConsumerWithOverrides() throws Exception { clientSession.createQueue(queueName, queueName, false); ClientConsumer consumer = clientSession.createConsumer(queueName, null, 100, 100, false); Assert.assertNotNull(consumer); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionCreateProducerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionCreateProducerTest.java index 4da269d6c0..a8f7e05431 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionCreateProducerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionCreateProducerTest.java @@ -28,30 +28,26 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class SessionCreateProducerTest extends ActiveMQTestBase -{ +public class SessionCreateProducerTest extends ActiveMQTestBase { + private ServerLocator locator; private ClientSessionInternal clientSession; private ClientSessionFactory cf; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = createInVMNonHALocator(); ActiveMQServer service = createServer(false); service.start(); - locator.setProducerMaxRate(99) - .setBlockOnNonDurableSend(true) - .setBlockOnNonDurableSend(true); + locator.setProducerMaxRate(99).setBlockOnNonDurableSend(true).setBlockOnNonDurableSend(true); cf = createSessionFactory(locator); clientSession = (ClientSessionInternal) addClientSession(cf.createSession(false, true, true)); } @Test - public void testCreateAnonProducer() throws Exception - { + public void testCreateAnonProducer() throws Exception { ClientProducer producer = clientSession.createProducer(); Assert.assertNull(producer.getAddress()); Assert.assertEquals(cf.getServerLocator().getProducerMaxRate(), producer.getMaxRate()); @@ -61,8 +57,7 @@ public class SessionCreateProducerTest extends ActiveMQTestBase } @Test - public void testCreateProducer1() throws Exception - { + public void testCreateProducer1() throws Exception { ClientProducer producer = clientSession.createProducer("testAddress"); Assert.assertNotNull(producer.getAddress()); Assert.assertEquals(cf.getServerLocator().getProducerMaxRate(), producer.getMaxRate()); @@ -72,20 +67,16 @@ public class SessionCreateProducerTest extends ActiveMQTestBase } @Test - public void testProducerOnClosedSession() throws Exception - { + public void testProducerOnClosedSession() throws Exception { clientSession.close(); - try - { + try { clientSession.createProducer(); Assert.fail("should throw exception"); } - catch (ActiveMQObjectClosedException oce) - { + catch (ActiveMQObjectClosedException oce) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionFactoryTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionFactoryTest.java index 0d7dffda21..938cc8e79f 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionFactoryTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionFactoryTest.java @@ -35,12 +35,9 @@ import org.junit.Test; import java.util.Arrays; -public class SessionFactoryTest extends ActiveMQTestBase -{ - private final DiscoveryGroupConfiguration groupConfiguration = new DiscoveryGroupConfiguration() - .setBroadcastEndpointFactory(new UDPBroadcastEndpointFactory() - .setGroupAddress(getUDPDiscoveryAddress()) - .setGroupPort(getUDPDiscoveryPort())); +public class SessionFactoryTest extends ActiveMQTestBase { + + private final DiscoveryGroupConfiguration groupConfiguration = new DiscoveryGroupConfiguration().setBroadcastEndpointFactory(new UDPBroadcastEndpointFactory().setGroupAddress(getUDPDiscoveryAddress()).setGroupPort(getUDPDiscoveryPort())); private ActiveMQServer liveService; @@ -48,16 +45,14 @@ public class SessionFactoryTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); startServer(); } @Test - public void testCloseUnusedClientSessionFactoryWithoutGlobalPools() throws Exception - { + public void testCloseUnusedClientSessionFactoryWithoutGlobalPools() throws Exception { ServerLocator locator = ActiveMQClient.createServerLocatorWithoutHA(liveTC); ClientSessionFactory csf = createSessionFactory(locator); @@ -65,34 +60,10 @@ public class SessionFactoryTest extends ActiveMQTestBase } @Test - public void testDiscoveryConstructor() throws Exception - { + public void testDiscoveryConstructor() throws Exception { ServerLocator locator = ActiveMQClient.createServerLocatorWithoutHA(groupConfiguration); - assertFactoryParams(locator, - null, - groupConfiguration, - ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, - ActiveMQClient.DEFAULT_CONNECTION_TTL, - ActiveMQClient.DEFAULT_CALL_TIMEOUT, - ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, - ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, - ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, - ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, - ActiveMQClient.DEFAULT_AUTO_GROUP, - ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, - ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_RETRY_INTERVAL, - ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, - ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS); + assertFactoryParams(locator, null, groupConfiguration, ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, ActiveMQClient.DEFAULT_CONNECTION_TTL, ActiveMQClient.DEFAULT_CALL_TIMEOUT, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, ActiveMQClient.DEFAULT_AUTO_GROUP, ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_RETRY_INTERVAL, ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS); ClientSessionFactory cf = createSessionFactory(locator); ClientSession session = cf.createSession(false, true, true); @@ -106,35 +77,11 @@ public class SessionFactoryTest extends ActiveMQTestBase } @Test - public void testStaticConnectorListConstructor() throws Exception - { + public void testStaticConnectorListConstructor() throws Exception { TransportConfiguration[] tc = new TransportConfiguration[]{liveTC}; ServerLocator locator = ActiveMQClient.createServerLocatorWithoutHA(tc); - assertFactoryParams(locator, - tc, - null, - ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, - ActiveMQClient.DEFAULT_CONNECTION_TTL, - ActiveMQClient.DEFAULT_CALL_TIMEOUT, - ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, - ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, - ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, - ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, - ActiveMQClient.DEFAULT_AUTO_GROUP, - ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, - ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_RETRY_INTERVAL, - ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, - ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS); + assertFactoryParams(locator, tc, null, ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, ActiveMQClient.DEFAULT_CONNECTION_TTL, ActiveMQClient.DEFAULT_CALL_TIMEOUT, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, ActiveMQClient.DEFAULT_AUTO_GROUP, ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_RETRY_INTERVAL, ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS); ClientSessionFactory cf = createSessionFactory(locator); ClientSession session = cf.createSession(false, true, true); @@ -146,8 +93,7 @@ public class SessionFactoryTest extends ActiveMQTestBase } @Test - public void testGettersAndSetters() throws Exception - { + public void testGettersAndSetters() throws Exception { long clientFailureCheckPeriod = RandomUtil.randomPositiveLong(); long connectionTTL = RandomUtil.randomPositiveLong(); long callTimeout = RandomUtil.randomPositiveLong(); @@ -171,28 +117,7 @@ public class SessionFactoryTest extends ActiveMQTestBase int reconnectAttempts = RandomUtil.randomPositiveInt(); TransportConfiguration[] tc = new TransportConfiguration[]{liveTC}; - ServerLocator locator = ActiveMQClient.createServerLocatorWithoutHA(tc) - .setClientFailureCheckPeriod(clientFailureCheckPeriod) - .setConnectionTTL(connectionTTL) - .setCallTimeout(callTimeout) - .setMinLargeMessageSize(minLargeMessageSize) - .setConsumerWindowSize(consumerWindowSize) - .setConsumerMaxRate(consumerMaxRate) - .setConfirmationWindowSize(confirmationWindowSize) - .setProducerMaxRate(producerMaxRate) - .setBlockOnAcknowledge(blockOnAcknowledge) - .setBlockOnDurableSend(blockOnDurableSend) - .setBlockOnNonDurableSend(blockOnNonDurableSend) - .setAutoGroup(autoGroup) - .setPreAcknowledge(preAcknowledge) - .setConnectionLoadBalancingPolicyClassName(loadBalancingPolicyClassName) - .setAckBatchSize(ackBatchSize) - .setUseGlobalPools(useGlobalPools) - .setScheduledThreadPoolMaxSize(scheduledThreadPoolMaxSize) - .setThreadPoolMaxSize(threadPoolMaxSize) - .setRetryInterval(retryInterval) - .setRetryIntervalMultiplier(retryIntervalMultiplier) - .setReconnectAttempts(reconnectAttempts); + ServerLocator locator = ActiveMQClient.createServerLocatorWithoutHA(tc).setClientFailureCheckPeriod(clientFailureCheckPeriod).setConnectionTTL(connectionTTL).setCallTimeout(callTimeout).setMinLargeMessageSize(minLargeMessageSize).setConsumerWindowSize(consumerWindowSize).setConsumerMaxRate(consumerMaxRate).setConfirmationWindowSize(confirmationWindowSize).setProducerMaxRate(producerMaxRate).setBlockOnAcknowledge(blockOnAcknowledge).setBlockOnDurableSend(blockOnDurableSend).setBlockOnNonDurableSend(blockOnNonDurableSend).setAutoGroup(autoGroup).setPreAcknowledge(preAcknowledge).setConnectionLoadBalancingPolicyClassName(loadBalancingPolicyClassName).setAckBatchSize(ackBatchSize).setUseGlobalPools(useGlobalPools).setScheduledThreadPoolMaxSize(scheduledThreadPoolMaxSize).setThreadPoolMaxSize(threadPoolMaxSize).setRetryInterval(retryInterval).setRetryIntervalMultiplier(retryIntervalMultiplier).setReconnectAttempts(reconnectAttempts); assertEqualsTransportConfigurations(tc, locator.getStaticTransportConfigurations()); Assert.assertEquals(clientFailureCheckPeriod, locator.getClientFailureCheckPeriod()); @@ -218,8 +143,7 @@ public class SessionFactoryTest extends ActiveMQTestBase Assert.assertEquals(reconnectAttempts, locator.getReconnectAttempts()); } - private void testSettersThrowException(final ClientSessionFactory cf) - { + private void testSettersThrowException(final ClientSessionFactory cf) { long clientFailureCheckPeriod = RandomUtil.randomPositiveLong(); long connectionTTL = RandomUtil.randomPositiveLong(); long callTimeout = RandomUtil.randomPositiveLong(); @@ -242,193 +166,151 @@ public class SessionFactoryTest extends ActiveMQTestBase double retryIntervalMultiplier = RandomUtil.randomDouble(); int reconnectAttempts = RandomUtil.randomPositiveInt(); - try - { + try { cf.getServerLocator().setClientFailureCheckPeriod(clientFailureCheckPeriod); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.getServerLocator().setConnectionTTL(connectionTTL); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.getServerLocator().setCallTimeout(callTimeout); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.getServerLocator().setMinLargeMessageSize(minLargeMessageSize); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.getServerLocator().setConsumerWindowSize(consumerWindowSize); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.getServerLocator().setConsumerMaxRate(consumerMaxRate); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.getServerLocator().setConfirmationWindowSize(confirmationWindowSize); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.getServerLocator().setProducerMaxRate(producerMaxRate); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.getServerLocator().setBlockOnAcknowledge(blockOnAcknowledge); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.getServerLocator().setBlockOnDurableSend(blockOnDurableSend); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.getServerLocator().setBlockOnNonDurableSend(blockOnNonDurableSend); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.getServerLocator().setAutoGroup(autoGroup); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.getServerLocator().setPreAcknowledge(preAcknowledge); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.getServerLocator().setConnectionLoadBalancingPolicyClassName(loadBalancingPolicyClassName); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.getServerLocator().setAckBatchSize(ackBatchSize); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.getServerLocator().setUseGlobalPools(useGlobalPools); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.getServerLocator().setScheduledThreadPoolMaxSize(scheduledThreadPoolMaxSize); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.getServerLocator().setThreadPoolMaxSize(threadPoolMaxSize); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.getServerLocator().setRetryInterval(retryInterval); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.getServerLocator().setRetryIntervalMultiplier(retryIntervalMultiplier); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.getServerLocator().setReconnectAttempts(reconnectAttempts); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } @@ -480,15 +362,11 @@ public class SessionFactoryTest extends ActiveMQTestBase final int threadPoolMaxSize, final long retryInterval, final double retryIntervalMultiplier, - final int reconnectAttempts) - { - if (staticConnectors == null) - { - Assert.assertTrue("no static connectors", - Arrays.equals(new String[]{}, locator.getStaticTransportConfigurations())); + final int reconnectAttempts) { + if (staticConnectors == null) { + Assert.assertTrue("no static connectors", Arrays.equals(new String[]{}, locator.getStaticTransportConfigurations())); } - else - { + else { assertEqualsTransportConfigurations(staticConnectors, locator.getStaticTransportConfigurations()); } Assert.assertEquals(locator.getDiscoveryGroupConfiguration(), discoveryGroupConfiguration); @@ -505,8 +383,7 @@ public class SessionFactoryTest extends ActiveMQTestBase Assert.assertEquals(locator.isBlockOnNonDurableSend(), blockOnNonDurableSend); Assert.assertEquals(locator.isAutoGroup(), autoGroup); Assert.assertEquals(locator.isPreAcknowledge(), preAcknowledge); - Assert.assertEquals(locator.getConnectionLoadBalancingPolicyClassName(), - loadBalancingPolicyClassName); + Assert.assertEquals(locator.getConnectionLoadBalancingPolicyClassName(), loadBalancingPolicyClassName); Assert.assertEquals(locator.getAckBatchSize(), ackBatchSize); Assert.assertEquals(locator.isUseGlobalPools(), useGlobalPools); Assert.assertEquals(locator.getScheduledThreadPoolMaxSize(), scheduledThreadPoolMaxSize); @@ -516,8 +393,7 @@ public class SessionFactoryTest extends ActiveMQTestBase Assert.assertEquals(locator.getReconnectAttempts(), reconnectAttempts); } - private void startServer() throws Exception - { + private void startServer() throws Exception { liveTC = new TransportConfiguration(INVM_CONNECTOR_FACTORY); final long broadcastPeriod = 250; @@ -526,19 +402,9 @@ public class SessionFactoryTest extends ActiveMQTestBase final int localBindPort = 5432; - BroadcastGroupConfiguration broadcastGroupConfiguration = new BroadcastGroupConfiguration() - .setName(bcGroupName) - .setBroadcastPeriod(broadcastPeriod) - .setConnectorInfos(Arrays.asList(liveTC.getName())) - .setEndpointFactory(new UDPBroadcastEndpointFactory() - .setGroupAddress(getUDPDiscoveryAddress()) - .setGroupPort(getUDPDiscoveryPort()) - .setLocalBindPort(localBindPort)); + BroadcastGroupConfiguration broadcastGroupConfiguration = new BroadcastGroupConfiguration().setName(bcGroupName).setBroadcastPeriod(broadcastPeriod).setConnectorInfos(Arrays.asList(liveTC.getName())).setEndpointFactory(new UDPBroadcastEndpointFactory().setGroupAddress(getUDPDiscoveryAddress()).setGroupPort(getUDPDiscoveryPort()).setLocalBindPort(localBindPort)); - Configuration liveConf = createDefaultInVMConfig() - .addConnectorConfiguration(liveTC.getName(), liveTC) - .setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration()) - .addBroadcastGroupConfiguration(broadcastGroupConfiguration); + Configuration liveConf = createDefaultInVMConfig().addConnectorConfiguration(liveTC.getName(), liveTC).setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration()).addBroadcastGroupConfiguration(broadcastGroupConfiguration); liveService = createServer(false, liveConf); liveService.start(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionSendAcknowledgementHandlerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionSendAcknowledgementHandlerTest.java index 7307b65285..09be52ea48 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionSendAcknowledgementHandlerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionSendAcknowledgementHandlerTest.java @@ -33,8 +33,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class SessionSendAcknowledgementHandlerTest extends ActiveMQTestBase -{ +public class SessionSendAcknowledgementHandlerTest extends ActiveMQTestBase { + private ActiveMQServer server; private final SimpleString address = new SimpleString("address"); @@ -43,8 +43,7 @@ public class SessionSendAcknowledgementHandlerTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(false); @@ -52,8 +51,7 @@ public class SessionSendAcknowledgementHandlerTest extends ActiveMQTestBase } @Test - public void testSetInvalidSendACK() throws Exception - { + public void testSetInvalidSendACK() throws Exception { ServerLocator locator = createInVMNonHALocator(); locator.setConfirmationWindowSize(-1); @@ -62,17 +60,13 @@ public class SessionSendAcknowledgementHandlerTest extends ActiveMQTestBase ClientSession session = csf.createSession(null, null, false, true, true, false, 1); boolean failed = false; - try - { - session.setSendAcknowledgementHandler(new SendAcknowledgementHandler() - { - public void sendAcknowledged(Message message) - { + try { + session.setSendAcknowledgementHandler(new SendAcknowledgementHandler() { + public void sendAcknowledged(Message message) { } }); } - catch (Throwable expected) - { + catch (Throwable expected) { failed = true; } @@ -82,31 +76,26 @@ public class SessionSendAcknowledgementHandlerTest extends ActiveMQTestBase } @Test - public void testSendAcknowledgementsNoWindowSize() throws Exception - { + public void testSendAcknowledgementsNoWindowSize() throws Exception { verifySendAcknowledgements(0); } @Test - public void testSendAcknowledgements() throws Exception - { + public void testSendAcknowledgements() throws Exception { verifySendAcknowledgements(1024); } @Test - public void testSendAcknowledgementsNoWindowSizeProducerOnly() throws Exception - { + public void testSendAcknowledgementsNoWindowSizeProducerOnly() throws Exception { verifySendAcknowledgementsProducerOnly(0); } @Test - public void testSendAcknowledgementsProducer() throws Exception - { + public void testSendAcknowledgementsProducer() throws Exception { verifySendAcknowledgementsProducerOnly(1024); } - public void verifySendAcknowledgements(int windowSize) throws Exception - { + public void verifySendAcknowledgements(int windowSize) throws Exception { ServerLocator locator = createInVMNonHALocator(); locator.setConfirmationWindowSize(windowSize); @@ -126,8 +115,7 @@ public class SessionSendAcknowledgementHandlerTest extends ActiveMQTestBase session.setSendAcknowledgementHandler(handler); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage msg = session.createMessage(false); ClientMessage msg2 = session.createMessage(false); @@ -136,12 +124,10 @@ public class SessionSendAcknowledgementHandlerTest extends ActiveMQTestBase } Assert.assertTrue("session must have acked, " + handler, handler.latch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue("producer specific handler must have acked, " + producerHandler, - producerHandler.latch.await(5, TimeUnit.SECONDS)); + Assert.assertTrue("producer specific handler must have acked, " + producerHandler, producerHandler.latch.await(5, TimeUnit.SECONDS)); } - public void verifySendAcknowledgementsProducerOnly(int windowSize) throws Exception - { + public void verifySendAcknowledgementsProducerOnly(int windowSize) throws Exception { ServerLocator locator = createInVMNonHALocator(); locator.setConfirmationWindowSize(windowSize); @@ -157,38 +143,32 @@ public class SessionSendAcknowledgementHandlerTest extends ActiveMQTestBase LatchAckHandler producerHandler = new LatchAckHandler("producer", new CountDownLatch(numMessages)); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage msg2 = session.createMessage(false); prod.send(address, msg2, producerHandler); } - Assert.assertTrue("producer specific handler must have acked, " + producerHandler, - producerHandler.latch.await(5, TimeUnit.SECONDS)); + Assert.assertTrue("producer specific handler must have acked, " + producerHandler, producerHandler.latch.await(5, TimeUnit.SECONDS)); } - public static final class LatchAckHandler implements SendAcknowledgementHandler - { + public static final class LatchAckHandler implements SendAcknowledgementHandler { public CountDownLatch latch; private final String name; - public LatchAckHandler(String name, CountDownLatch latch) - { + public LatchAckHandler(String name, CountDownLatch latch) { this.name = name; this.latch = latch; } @Override - public void sendAcknowledged(Message message) - { + public void sendAcknowledged(Message message) { latch.countDown(); } @Override - public String toString() - { + public String toString() { return "SendAckHandler(name=" + name + ", latch=" + latch + ")"; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionStopStartTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionStopStartTest.java index 4d1d237873..9b6fffaf46 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionStopStartTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionStopStartTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.client; + import org.junit.Before; import org.junit.Test; @@ -36,8 +37,8 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -public class SessionStopStartTest extends ActiveMQTestBase -{ +public class SessionStopStartTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private ActiveMQServer server; @@ -48,8 +49,7 @@ public class SessionStopStartTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(false); @@ -58,8 +58,7 @@ public class SessionStopStartTest extends ActiveMQTestBase } @Test - public void testStopStartConsumerSyncReceiveImmediate() throws Exception - { + public void testStopStartConsumerSyncReceiveImmediate() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); final ClientSession session = sf.createSession(false, true, true); @@ -70,8 +69,7 @@ public class SessionStopStartTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); message.putIntProperty(new SimpleString("i"), i); producer.send(message); @@ -81,8 +79,7 @@ public class SessionStopStartTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numMessages / 2; i++) - { + for (int i = 0; i < numMessages / 2; i++) { ClientMessage cm = consumer.receive(5000); Assert.assertNotNull(cm); cm.acknowledge(); @@ -92,8 +89,7 @@ public class SessionStopStartTest extends ActiveMQTestBase Assert.assertNull(cm); session.start(); - for (int i = 0; i < numMessages / 2; i++) - { + for (int i = 0; i < numMessages / 2; i++) { cm = consumer.receive(5000); Assert.assertNotNull(cm); cm.acknowledge(); @@ -103,8 +99,7 @@ public class SessionStopStartTest extends ActiveMQTestBase } @Test - public void testStopStartConsumerSyncReceive() throws Exception - { + public void testStopStartConsumerSyncReceive() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); final ClientSession session = sf.createSession(false, true, true); @@ -115,8 +110,7 @@ public class SessionStopStartTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); message.putIntProperty(new SimpleString("i"), i); producer.send(message); @@ -126,8 +120,7 @@ public class SessionStopStartTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numMessages / 2; i++) - { + for (int i = 0; i < numMessages / 2; i++) { ClientMessage cm = consumer.receive(5000); Assert.assertNotNull(cm); cm.acknowledge(); @@ -140,8 +133,7 @@ public class SessionStopStartTest extends ActiveMQTestBase Assert.assertNull(cm); session.start(); - for (int i = 0; i < numMessages / 2; i++) - { + for (int i = 0; i < numMessages / 2; i++) { cm = consumer.receive(5000); Assert.assertNotNull(cm); cm.acknowledge(); @@ -151,8 +143,7 @@ public class SessionStopStartTest extends ActiveMQTestBase } @Test - public void testStopStartConsumerAsyncSyncStoppedByHandler() throws Exception - { + public void testStopStartConsumerAsyncSyncStoppedByHandler() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); final ClientSession session = sf.createSession(false, true, true); @@ -163,8 +154,7 @@ public class SessionStopStartTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); message.putIntProperty(new SimpleString("i"), i); producer.send(message); @@ -178,28 +168,24 @@ public class SessionStopStartTest extends ActiveMQTestBase // Message should be in consumer - class MyHandler implements MessageHandler - { + class MyHandler implements MessageHandler { + boolean failed; boolean started = true; int count = 0; - public void onMessage(final ClientMessage message) - { + public void onMessage(final ClientMessage message) { - try - { - if (!started) - { + try { + if (!started) { failed = true; } count++; - if (count == 10) - { + if (count == 10) { message.acknowledge(); session.stop(); started = false; @@ -207,8 +193,7 @@ public class SessionStopStartTest extends ActiveMQTestBase latch.countDown(); } - catch (Exception e) - { + catch (Exception e) { } } } @@ -225,11 +210,9 @@ public class SessionStopStartTest extends ActiveMQTestBase Assert.assertNull(consumer.getLastException()); consumer.setMessageHandler(null); session.start(); - for (int i = 0; i < 90; i++) - { + for (int i = 0; i < 90; i++) { ClientMessage msg = consumer.receive(1000); - if (msg == null) - { + if (msg == null) { System.out.println("ClientConsumerTest.testStopConsumer"); } Assert.assertNotNull("message " + i, msg); @@ -242,8 +225,7 @@ public class SessionStopStartTest extends ActiveMQTestBase } @Test - public void testStopStartConsumerAsyncSync() throws Exception - { + public void testStopStartConsumerAsyncSync() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); final ClientSession session = sf.createSession(false, true, true); @@ -254,8 +236,7 @@ public class SessionStopStartTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); message.putIntProperty(new SimpleString("i"), i); producer.send(message); @@ -269,26 +250,22 @@ public class SessionStopStartTest extends ActiveMQTestBase // Message should be in consumer - class MyHandler implements MessageHandler - { + class MyHandler implements MessageHandler { + boolean failed; boolean started = true; - public void onMessage(final ClientMessage message) - { + public void onMessage(final ClientMessage message) { - try - { - if (!started) - { + try { + if (!started) { failed = true; } latch.countDown(); - if (latch.getCount() == 0) - { + if (latch.getCount() == 0) { message.acknowledge(); started = false; @@ -296,8 +273,7 @@ public class SessionStopStartTest extends ActiveMQTestBase } } - catch (Exception e) - { + catch (Exception e) { } } } @@ -308,12 +284,10 @@ public class SessionStopStartTest extends ActiveMQTestBase waitForLatch(latch); - try - { + try { session.stop(); } - catch (Exception e) - { + catch (Exception e) { SessionStopStartTest.log.warn(e.getMessage(), e); throw e; } @@ -324,11 +298,9 @@ public class SessionStopStartTest extends ActiveMQTestBase Assert.assertNull(consumer.getLastException()); consumer.setMessageHandler(null); session.start(); - for (int i = 0; i < 90; i++) - { + for (int i = 0; i < 90; i++) { ClientMessage msg = consumer.receive(1000); - if (msg == null) - { + if (msg == null) { System.out.println("ClientConsumerTest.testStopConsumer"); } Assert.assertNotNull("message " + i, msg); @@ -341,8 +313,7 @@ public class SessionStopStartTest extends ActiveMQTestBase } @Test - public void testStopStartConsumerAsyncASyncStoppeeByHandler() throws Exception - { + public void testStopStartConsumerAsyncASyncStoppeeByHandler() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); final ClientSession session = sf.createSession(false, true, true); @@ -353,8 +324,7 @@ public class SessionStopStartTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); message.putIntProperty(new SimpleString("i"), i); producer.send(message); @@ -368,8 +338,8 @@ public class SessionStopStartTest extends ActiveMQTestBase // Message should be in consumer - class MyHandler implements MessageHandler - { + class MyHandler implements MessageHandler { + int messageReceived = 0; boolean failed; @@ -380,31 +350,25 @@ public class SessionStopStartTest extends ActiveMQTestBase private boolean stop = true; - public MyHandler(final CountDownLatch latch) - { + public MyHandler(final CountDownLatch latch) { this.latch = latch; } - public MyHandler(final CountDownLatch latch, final boolean stop) - { + public MyHandler(final CountDownLatch latch, final boolean stop) { this(latch); this.stop = stop; } - public void onMessage(final ClientMessage message) - { + public void onMessage(final ClientMessage message) { - try - { - if (!started) - { + try { + if (!started) { failed = true; } messageReceived++; latch.countDown(); - if (stop && latch.getCount() == 0) - { + if (stop && latch.getCount() == 0) { message.acknowledge(); session.stop(); @@ -412,8 +376,7 @@ public class SessionStopStartTest extends ActiveMQTestBase } } - catch (Exception e) - { + catch (Exception e) { } } } @@ -444,8 +407,7 @@ public class SessionStopStartTest extends ActiveMQTestBase } @Test - public void testStopStartConsumerAsyncASync() throws Exception - { + public void testStopStartConsumerAsyncASync() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); final ClientSession session = sf.createSession(false, true, true); @@ -456,8 +418,7 @@ public class SessionStopStartTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); message.putIntProperty(new SimpleString("i"), i); producer.send(message); @@ -471,8 +432,8 @@ public class SessionStopStartTest extends ActiveMQTestBase // Message should be in consumer - class MyHandler implements MessageHandler - { + class MyHandler implements MessageHandler { + int messageReceived = 0; boolean failed; @@ -483,31 +444,25 @@ public class SessionStopStartTest extends ActiveMQTestBase private boolean stop = true; - public MyHandler(final CountDownLatch latch) - { + public MyHandler(final CountDownLatch latch) { this.latch = latch; } - public MyHandler(final CountDownLatch latch, final boolean stop) - { + public MyHandler(final CountDownLatch latch, final boolean stop) { this(latch); this.stop = stop; } - public void onMessage(final ClientMessage message) - { + public void onMessage(final ClientMessage message) { - try - { - if (!started) - { + try { + if (!started) { failed = true; } messageReceived++; latch.countDown(); - if (stop && latch.getCount() == 0) - { + if (stop && latch.getCount() == 0) { message.acknowledge(); consumer.setMessageHandler(null); @@ -515,8 +470,7 @@ public class SessionStopStartTest extends ActiveMQTestBase } } - catch (Exception e) - { + catch (Exception e) { } } } @@ -546,8 +500,7 @@ public class SessionStopStartTest extends ActiveMQTestBase session.close(); } - private int getMessageEncodeSize(final SimpleString address) throws Exception - { + private int getMessageEncodeSize(final SimpleString address) throws Exception { ServerLocator locator = createInVMNonHALocator(); ClientSessionFactory cf = createSessionFactory(locator); ClientSession session = cf.createSession(false, true, true); @@ -561,8 +514,7 @@ public class SessionStopStartTest extends ActiveMQTestBase } @Test - public void testStopStartMultipleConsumers() throws Exception - { + public void testStopStartMultipleConsumers() throws Exception { locator.setConsumerWindowSize(getMessageEncodeSize(QUEUE) * 33); ClientSessionFactory sf = createSessionFactory(locator); @@ -574,8 +526,7 @@ public class SessionStopStartTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); message.putIntProperty(new SimpleString("i"), i); producer.send(message); @@ -616,8 +567,7 @@ public class SessionStopStartTest extends ActiveMQTestBase } @Test - public void testStopStartAlreadyStartedSession() throws Exception - { + public void testStopStartAlreadyStartedSession() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); final ClientSession session = sf.createSession(false, true, true); @@ -628,8 +578,7 @@ public class SessionStopStartTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); message.putIntProperty(new SimpleString("i"), i); producer.send(message); @@ -639,16 +588,14 @@ public class SessionStopStartTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numMessages / 2; i++) - { + for (int i = 0; i < numMessages / 2; i++) { ClientMessage cm = consumer.receive(5000); Assert.assertNotNull(cm); cm.acknowledge(); } session.start(); - for (int i = 0; i < numMessages / 2; i++) - { + for (int i = 0; i < numMessages / 2; i++) { ClientMessage cm = consumer.receive(5000); Assert.assertNotNull(cm); cm.acknowledge(); @@ -658,8 +605,7 @@ public class SessionStopStartTest extends ActiveMQTestBase } @Test - public void testStopAlreadyStoppedSession() throws Exception - { + public void testStopAlreadyStoppedSession() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); final ClientSession session = sf.createSession(false, true, true); @@ -670,8 +616,7 @@ public class SessionStopStartTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = createTextMessage(session, "m" + i); message.putIntProperty(new SimpleString("i"), i); producer.send(message); @@ -681,8 +626,7 @@ public class SessionStopStartTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numMessages / 2; i++) - { + for (int i = 0; i < numMessages / 2; i++) { ClientMessage cm = consumer.receive(5000); Assert.assertNotNull(cm); cm.acknowledge(); @@ -696,8 +640,7 @@ public class SessionStopStartTest extends ActiveMQTestBase Assert.assertNull(cm); session.start(); - for (int i = 0; i < numMessages / 2; i++) - { + for (int i = 0; i < numMessages / 2; i++) { cm = consumer.receive(5000); Assert.assertNotNull(cm); cm.acknowledge(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionTest.java index 56539de0c2..f4645df619 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionTest.java @@ -44,8 +44,8 @@ import org.junit.Test; /** * This test covers the API for ClientSession although XA tests are tested separately. */ -public class SessionTest extends ActiveMQTestBase -{ +public class SessionTest extends ActiveMQTestBase { + private final String queueName = "ClientSessionTestQ"; private ServerLocator locator; @@ -54,8 +54,7 @@ public class SessionTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = createInVMNonHALocator(); @@ -65,8 +64,7 @@ public class SessionTest extends ActiveMQTestBase } @Test - public void testFailureListener() throws Exception - { + public void testFailureListener() throws Exception { cf = createSessionFactory(locator); ClientSession clientSession = addClientSession(cf.createSession(false, true, true)); @@ -78,30 +76,25 @@ public class SessionTest extends ActiveMQTestBase } @Test - public void testFailureListenerRemoved() throws Exception - { + public void testFailureListenerRemoved() throws Exception { cf = createSessionFactory(locator); - try - { + try { ClientSession clientSession = cf.createSession(false, true, true); - class MyFailureListener implements SessionFailureListener - { + class MyFailureListener implements SessionFailureListener { + boolean called = false; @Override - public void connectionFailed(final ActiveMQException me, boolean failedOver) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver) { called = true; } @Override - public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) { connectionFailed(me, failedOver); } - public void beforeReconnect(final ActiveMQException me) - { + public void beforeReconnect(final ActiveMQException me) { } } @@ -113,8 +106,7 @@ public class SessionTest extends ActiveMQTestBase server.stop(); Assert.assertFalse(listener.called); } - finally - { + finally { ((ClientSessionFactoryInternal) cf).causeExit(); cf.close(); } @@ -123,8 +115,7 @@ public class SessionTest extends ActiveMQTestBase // Closing a session if the underlying remoting connection is dead should cleanly // release all resources @Test - public void testCloseSessionOnDestroyedConnection() throws Exception - { + public void testCloseSessionOnDestroyedConnection() throws Exception { // Make sure we have a short connection TTL so sessions will be quickly closed on the server server.stop(); long ttl = 500; @@ -149,19 +140,16 @@ public class SessionTest extends ActiveMQTestBase long start = System.currentTimeMillis(); - while (true) - { + while (true) { int cons = server.getRemotingService().getConnections().size(); - if (cons == 0) - { + if (cons == 0) { break; } long now = System.currentTimeMillis(); - if (now - start > 10000) - { + if (now - start > 10000) { throw new Exception("Timed out waiting for connections to close"); } @@ -170,8 +158,7 @@ public class SessionTest extends ActiveMQTestBase } @Test - public void testBindingQuery() throws Exception - { + public void testBindingQuery() throws Exception { cf = createSessionFactory(locator); ClientSession clientSession = cf.createSession(false, true, true); clientSession.createQueue("a1", "q1", false); @@ -197,8 +184,7 @@ public class SessionTest extends ActiveMQTestBase } @Test - public void testQueueQuery() throws Exception - { + public void testQueueQuery() throws Exception { cf = createSessionFactory(locator); ClientSession clientSession = cf.createSession(false, true, true); clientSession.createQueue("a1", queueName, false); @@ -218,16 +204,14 @@ public class SessionTest extends ActiveMQTestBase clientSession.close(); } - private void flushQueue() throws Exception - { + private void flushQueue() throws Exception { Queue queue = server.locateQueue(SimpleString.toSimpleString(queueName)); assertNotNull(queue); queue.flushExecutor(); } @Test - public void testQueueQueryWithFilter() throws Exception - { + public void testQueueQueryWithFilter() throws Exception { cf = createSessionFactory(locator); ClientSession clientSession = cf.createSession(false, true, true); clientSession.createQueue("a1", queueName, "foo=bar", false); @@ -243,8 +227,7 @@ public class SessionTest extends ActiveMQTestBase } @Test - public void testQueueQueryNoQ() throws Exception - { + public void testQueueQueryNoQ() throws Exception { cf = createSessionFactory(locator); ClientSession clientSession = cf.createSession(false, true, true); QueueQuery resp = clientSession.queueQuery(new SimpleString(queueName)); @@ -254,8 +237,7 @@ public class SessionTest extends ActiveMQTestBase } @Test - public void testClose() throws Exception - { + public void testClose() throws Exception { cf = createSessionFactory(locator); ClientSession clientSession = cf.createSession(false, true, true); clientSession.createQueue(queueName, queueName, false); @@ -272,8 +254,7 @@ public class SessionTest extends ActiveMQTestBase } @Test - public void testCreateMessageNonDurable() throws Exception - { + public void testCreateMessageNonDurable() throws Exception { cf = createSessionFactory(locator); ClientSession clientSession = cf.createSession(false, true, true); ClientMessage clientMessage = clientSession.createMessage(false); @@ -282,8 +263,7 @@ public class SessionTest extends ActiveMQTestBase } @Test - public void testCreateMessageDurable() throws Exception - { + public void testCreateMessageDurable() throws Exception { cf = createSessionFactory(locator); ClientSession clientSession = cf.createSession(false, true, true); ClientMessage clientMessage = clientSession.createMessage(true); @@ -292,8 +272,7 @@ public class SessionTest extends ActiveMQTestBase } @Test - public void testCreateMessageType() throws Exception - { + public void testCreateMessageType() throws Exception { cf = createSessionFactory(locator); ClientSession clientSession = cf.createSession(false, true, true); ClientMessage clientMessage = clientSession.createMessage((byte) 99, false); @@ -302,8 +281,7 @@ public class SessionTest extends ActiveMQTestBase } @Test - public void testCreateMessageOverrides() throws Exception - { + public void testCreateMessageOverrides() throws Exception { cf = createSessionFactory(locator); ClientSession clientSession = cf.createSession(false, true, true); ClientMessage clientMessage = clientSession.createMessage((byte) 88, false, 100L, 300L, (byte) 33); @@ -315,8 +293,7 @@ public class SessionTest extends ActiveMQTestBase } @Test - public void testGetVersion() throws Exception - { + public void testGetVersion() throws Exception { cf = createSessionFactory(locator); ClientSession clientSession = cf.createSession(false, true, true); Assert.assertEquals(server.getVersion().getIncrementingVersion(), clientSession.getVersion()); @@ -324,8 +301,7 @@ public class SessionTest extends ActiveMQTestBase } @Test - public void testStart() throws Exception - { + public void testStart() throws Exception { cf = createSessionFactory(locator); ClientSession clientSession = cf.createSession(false, true, true); clientSession.createQueue(queueName, queueName, false); @@ -334,8 +310,7 @@ public class SessionTest extends ActiveMQTestBase } @Test - public void testStop() throws Exception - { + public void testStop() throws Exception { cf = createSessionFactory(locator); ClientSession clientSession = cf.createSession(false, true, true); clientSession.createQueue(queueName, queueName, false); @@ -345,8 +320,7 @@ public class SessionTest extends ActiveMQTestBase } @Test - public void testCommitWithSend() throws Exception - { + public void testCommitWithSend() throws Exception { cf = createSessionFactory(locator); ClientSession clientSession = cf.createSession(false, false, true); clientSession.createQueue(queueName, queueName, false); @@ -369,8 +343,7 @@ public class SessionTest extends ActiveMQTestBase } @Test - public void testRollbackWithSend() throws Exception - { + public void testRollbackWithSend() throws Exception { cf = createSessionFactory(locator); ClientSession clientSession = cf.createSession(false, false, true); clientSession.createQueue(queueName, queueName, false); @@ -396,10 +369,8 @@ public class SessionTest extends ActiveMQTestBase } @Test - public void testCommitWithReceive() throws Exception - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true); + public void testCommitWithReceive() throws Exception { + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true); cf = createSessionFactory(locator); ClientSession sendSession = cf.createSession(false, true, true); ClientProducer cp = sendSession.createProducer(queueName); @@ -456,10 +427,8 @@ public class SessionTest extends ActiveMQTestBase } @Test - public void testRollbackWithReceive() throws Exception - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true); + public void testRollbackWithReceive() throws Exception { + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true); cf = createSessionFactory(locator); ClientSession sendSession = cf.createSession(false, true, true); ClientProducer cp = sendSession.createProducer(queueName); @@ -516,8 +485,7 @@ public class SessionTest extends ActiveMQTestBase } @Test - public void testGetNodeId() throws Exception - { + public void testGetNodeId() throws Exception { cf = createSessionFactory(locator); ClientSession clientSession = addClientSession(cf.createSession(false, true, true)); String nodeId = ((ClientSessionInternal) clientSession).getNodeId(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SimpleSendMultipleQueuesTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SimpleSendMultipleQueuesTest.java index 1362fa1d76..9795ecc01f 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SimpleSendMultipleQueuesTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SimpleSendMultipleQueuesTest.java @@ -29,8 +29,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class SimpleSendMultipleQueuesTest extends ActiveMQTestBase -{ +public class SimpleSendMultipleQueuesTest extends ActiveMQTestBase { + public static final String address = "testaddress"; public static final String queueName = "testqueue"; @@ -50,19 +50,17 @@ public class SimpleSendMultipleQueuesTest extends ActiveMQTestBase private ServerLocator locator; @Test - public void testSimpleSend() throws Exception - { - for (int i = 0; i < 1000; i++) - { + public void testSimpleSend() throws Exception { + for (int i = 0; i < 1000; i++) { ClientMessage message = session.createMessage(false); final String body = RandomUtil.randomString(); message.getBodyBuffer().writeString(body); - // log.info("sending message"); + // log.info("sending message"); producer.send(message); - // log.info("sent message"); + // log.info("sent message"); ClientMessage received1 = consumer1.receive(1000); Assert.assertNotNull(received1); @@ -80,8 +78,7 @@ public class SimpleSendMultipleQueuesTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(false, true); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SlowConsumerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SlowConsumerTest.java index f20be835c5..cecfe50e1a 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SlowConsumerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SlowConsumerTest.java @@ -47,23 +47,18 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) -public class SlowConsumerTest extends ActiveMQTestBase -{ +public class SlowConsumerTest extends ActiveMQTestBase { + private boolean isNetty = false; // this will ensure that all tests in this class are run twice, // once with "true" passed to the class' constructor and once with "false" @Parameterized.Parameters(name = "isNetty={0}") - public static Collection getParameters() - { - return Arrays.asList(new Object[][]{ - {true}, - {false} - }); + public static Collection getParameters() { + return Arrays.asList(new Object[][]{{true}, {false}}); } - public SlowConsumerTest(boolean isNetty) - { + public SlowConsumerTest(boolean isNetty) { this.isNetty = isNetty; } @@ -75,16 +70,12 @@ public class SlowConsumerTest extends ActiveMQTestBase @Before @Override - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(false, isNetty); - AddressSettings addressSettings = new AddressSettings() - .setSlowConsumerCheckPeriod(2) - .setSlowConsumerThreshold(10) - .setSlowConsumerPolicy(SlowConsumerPolicy.KILL); + AddressSettings addressSettings = new AddressSettings().setSlowConsumerCheckPeriod(2).setSlowConsumerThreshold(10).setSlowConsumerPolicy(SlowConsumerPolicy.KILL); server.start(); @@ -94,8 +85,7 @@ public class SlowConsumerTest extends ActiveMQTestBase } @Test - public void testSlowConsumerKilled() throws Exception - { + public void testSlowConsumerKilled() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = addClientSession(sf.createSession(false, true, true, false)); @@ -106,8 +96,7 @@ public class SlowConsumerTest extends ActiveMQTestBase final int numMessages = 25; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { producer.send(createTextMessage(session, "m" + i)); } @@ -116,20 +105,17 @@ public class SlowConsumerTest extends ActiveMQTestBase Thread.sleep(3000); - try - { + try { consumer.receiveImmediate(); fail(); } - catch (ActiveMQObjectClosedException e) - { + catch (ActiveMQObjectClosedException e) { assertEquals(e.getType(), ActiveMQExceptionType.OBJECT_CLOSED); } } @Test - public void testSlowConsumerNotification() throws Exception - { + public void testSlowConsumerNotification() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); @@ -137,10 +123,7 @@ public class SlowConsumerTest extends ActiveMQTestBase session.createQueue(QUEUE, QUEUE, null, false); - AddressSettings addressSettings = new AddressSettings() - .setSlowConsumerCheckPeriod(2) - .setSlowConsumerThreshold(10) - .setSlowConsumerPolicy(SlowConsumerPolicy.NOTIFY); + AddressSettings addressSettings = new AddressSettings().setSlowConsumerCheckPeriod(2).setSlowConsumerThreshold(10).setSlowConsumerPolicy(SlowConsumerPolicy.NOTIFY); server.getAddressSettingsRepository().removeMatch(QUEUE.toString()); server.getAddressSettingsRepository().addMatch(QUEUE.toString(), addressSettings); @@ -149,8 +132,7 @@ public class SlowConsumerTest extends ActiveMQTestBase final int numMessages = 25; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { producer.send(createTextMessage(session, "m" + i)); } @@ -162,31 +144,25 @@ public class SlowConsumerTest extends ActiveMQTestBase final CountDownLatch notifLatch = new CountDownLatch(1); - notifConsumer.setMessageHandler(new MessageHandler() - { + notifConsumer.setMessageHandler(new MessageHandler() { @Override - public void onMessage(ClientMessage message) - { + public void onMessage(ClientMessage message) { assertEquals(CoreNotificationType.CONSUMER_SLOW.toString(), message.getObjectProperty(ManagementHelper.HDR_NOTIFICATION_TYPE).toString()); assertEquals(QUEUE.toString(), message.getObjectProperty(ManagementHelper.HDR_ADDRESS).toString()); assertEquals(Integer.valueOf(1), message.getIntProperty(ManagementHelper.HDR_CONSUMER_COUNT)); - if (isNetty) - { + if (isNetty) { assertTrue(message.getSimpleStringProperty(ManagementHelper.HDR_REMOTE_ADDRESS).toString().startsWith("/127.0.0.1")); } - else - { + else { assertEquals(SimpleString.toSimpleString("invm:0"), message.getSimpleStringProperty(ManagementHelper.HDR_REMOTE_ADDRESS)); } assertNotNull(message.getSimpleStringProperty(ManagementHelper.HDR_CONNECTION_NAME)); assertNotNull(message.getSimpleStringProperty(ManagementHelper.HDR_CONSUMER_NAME)); assertNotNull(message.getSimpleStringProperty(ManagementHelper.HDR_SESSION_NAME)); - try - { + try { message.acknowledge(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { e.printStackTrace(); } notifLatch.countDown(); @@ -200,8 +176,7 @@ public class SlowConsumerTest extends ActiveMQTestBase } @Test - public void testSlowConsumerSpared() throws Exception - { + public void testSlowConsumerSpared() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = addClientSession(sf.createSession(true, true)); @@ -212,8 +187,7 @@ public class SlowConsumerTest extends ActiveMQTestBase final int numMessages = 5; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { producer.send(createTextMessage(session, "m" + i)); } @@ -222,15 +196,13 @@ public class SlowConsumerTest extends ActiveMQTestBase Thread.sleep(3000); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { assertNotNull(consumer.receive(500)); } } @Test - public void testFastThenSlowConsumerSpared() throws Exception - { + public void testFastThenSlowConsumerSpared() throws Exception { locator.setAckBatchSize(0); ClientSessionFactory sf = createSessionFactory(locator); @@ -245,24 +217,19 @@ public class SlowConsumerTest extends ActiveMQTestBase final AtomicLong messagesProduced = new AtomicLong(0); - Thread t = new Thread(new Runnable() - { + Thread t = new Thread(new Runnable() { @Override - public void run() - { + public void run() { long start = System.currentTimeMillis(); ClientMessage m = createTextMessage(producerSession, "m", true); // send messages as fast as possible for 3 seconds - while (System.currentTimeMillis() < (start + 3000)) - { - try - { + while (System.currentTimeMillis() < (start + 3000)) { + try { producer.send(m); messagesProduced.incrementAndGet(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { e.printStackTrace(); return; } @@ -271,16 +238,13 @@ public class SlowConsumerTest extends ActiveMQTestBase start = System.currentTimeMillis(); // send 1 msg/second for 10 seconds - while (System.currentTimeMillis() < (start + 10000)) - { - try - { + while (System.currentTimeMillis() < (start + 10000)) { + try { producer.send(m); messagesProduced.incrementAndGet(); Thread.sleep(1000); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); return; } @@ -296,23 +260,19 @@ public class SlowConsumerTest extends ActiveMQTestBase ClientMessage m = null; long messagesConsumed = 0; - do - { + do { m = consumer.receive(1500); - if (m != null) - { + if (m != null) { m.acknowledge(); messagesConsumed++; } - } - while (m != null); + } while (m != null); assertEquals(messagesProduced.longValue(), messagesConsumed); } @Test - public void testSlowWildcardConsumer() throws Exception - { + public void testSlowWildcardConsumer() throws Exception { SimpleString addressAB = new SimpleString("a.b"); SimpleString addressAC = new SimpleString("a.c"); SimpleString address = new SimpleString("a.*"); @@ -320,10 +280,7 @@ public class SlowConsumerTest extends ActiveMQTestBase SimpleString queueName2 = new SimpleString("Q2"); SimpleString queueName = new SimpleString("Q"); - AddressSettings addressSettings = new AddressSettings() - .setSlowConsumerCheckPeriod(2) - .setSlowConsumerThreshold(10) - .setSlowConsumerPolicy(SlowConsumerPolicy.KILL); + AddressSettings addressSettings = new AddressSettings().setSlowConsumerCheckPeriod(2).setSlowConsumerThreshold(10).setSlowConsumerPolicy(SlowConsumerPolicy.KILL); server.getAddressSettingsRepository().addMatch(address.toString(), addressSettings); @@ -338,8 +295,7 @@ public class SlowConsumerTest extends ActiveMQTestBase final int numMessages = 20; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { producer.send(createTextMessage(session, "m1" + i)); producer2.send(createTextMessage(session, "m2" + i)); } @@ -349,13 +305,11 @@ public class SlowConsumerTest extends ActiveMQTestBase Thread.sleep(3000); - try - { + try { consumer.receiveImmediate(); fail(); } - catch (ActiveMQObjectClosedException e) - { + catch (ActiveMQObjectClosedException e) { assertEquals(e.getType(), ActiveMQExceptionType.OBJECT_CLOSED); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/TemporaryQueueTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/TemporaryQueueTest.java index 5be1bd442d..380b6649fd 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/TemporaryQueueTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/TemporaryQueueTest.java @@ -54,8 +54,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -public class TemporaryQueueTest extends SingleServerTestBase -{ +public class TemporaryQueueTest extends SingleServerTestBase { // Constants ----------------------------------------------------- private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @@ -71,8 +70,7 @@ public class TemporaryQueueTest extends SingleServerTestBase // Public -------------------------------------------------------- @Test - public void testConsumeFromTemporaryQueue() throws Exception - { + public void testConsumeFromTemporaryQueue() throws Exception { SimpleString queue = RandomUtil.randomSimpleString(); SimpleString address = RandomUtil.randomSimpleString(); @@ -95,12 +93,9 @@ public class TemporaryQueueTest extends SingleServerTestBase session.close(); } - @Test - public void testMemoryLeakOnAddressSettingForTemporaryQueue() throws Exception - { - for (int i = 0; i < 1000; i++) - { + public void testMemoryLeakOnAddressSettingForTemporaryQueue() throws Exception { + for (int i = 0; i < 1000; i++) { SimpleString queue = RandomUtil.randomSimpleString(); SimpleString address = RandomUtil.randomSimpleString(); session.createTemporaryQueue(address, queue); @@ -109,7 +104,6 @@ public class TemporaryQueueTest extends SingleServerTestBase session = sf.createSession(); } - session.close(); sf.close(); @@ -120,8 +114,7 @@ public class TemporaryQueueTest extends SingleServerTestBase } @Test - public void testPaginStoreIsRemovedWhenQueueIsDeleted() throws Exception - { + public void testPaginStoreIsRemovedWhenQueueIsDeleted() throws Exception { SimpleString queue = RandomUtil.randomSimpleString(); SimpleString address = RandomUtil.randomSimpleString(); @@ -151,8 +144,7 @@ public class TemporaryQueueTest extends SingleServerTestBase } @Test - public void testConsumeFromTemporaryQueueCreatedByOtherSession() throws Exception - { + public void testConsumeFromTemporaryQueueCreatedByOtherSession() throws Exception { SimpleString queue = RandomUtil.randomSimpleString(); SimpleString address = RandomUtil.randomSimpleString(); @@ -173,97 +165,44 @@ public class TemporaryQueueTest extends SingleServerTestBase } @Test - public void testDeleteTemporaryQueueAfterConnectionIsClosed() throws Exception - { + public void testDeleteTemporaryQueueAfterConnectionIsClosed() throws Exception { SimpleString queue = RandomUtil.randomSimpleString(); SimpleString address = RandomUtil.randomSimpleString(); session.createTemporaryQueue(address, queue); - RemotingConnectionImpl conn = (RemotingConnectionImpl) server.getRemotingService() - .getConnections() - .iterator() - .next(); + RemotingConnectionImpl conn = (RemotingConnectionImpl) server.getRemotingService().getConnections().iterator().next(); final CountDownLatch latch = new CountDownLatch(1); - conn.addCloseListener(new CloseListener() - { - public void connectionClosed() - { + conn.addCloseListener(new CloseListener() { + public void connectionClosed() { latch.countDown(); } }); session.close(); sf.close(); // wait for the closing listeners to be fired - assertTrue("connection close listeners not fired", latch.await(2 * TemporaryQueueTest.CONNECTION_TTL, - TimeUnit.MILLISECONDS)); + assertTrue("connection close listeners not fired", latch.await(2 * TemporaryQueueTest.CONNECTION_TTL, TimeUnit.MILLISECONDS)); sf = addSessionFactory(createSessionFactory(locator)); session = sf.createSession(false, true, true); session.start(); - try - { + try { session.createConsumer(queue); fail("temp queue must not exist after the remoting connection is closed"); } - catch (ActiveMQNonExistentQueueException neqe) - { + catch (ActiveMQNonExistentQueueException neqe) { //ol } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } session.close(); } - @Test - public void testQueueWithWildcard() throws Exception - { - session.createQueue("a.b", "queue1"); - session.createTemporaryQueue("a.#", "queue2"); - session.createTemporaryQueue("a.#", "queue3"); - - ClientProducer producer = session.createProducer("a.b"); - producer.send(session.createMessage(false)); - - ClientConsumer cons = session.createConsumer("queue2"); - - session.start(); - - ClientMessage msg = cons.receive(5000); - - assertNotNull(msg); - - msg.acknowledge(); - - cons.close(); - - cons = session.createConsumer("queue3"); - - session.start(); - - msg = cons.receive(5000); - - assertNotNull(msg); - - msg.acknowledge(); - - cons.close(); - - session.deleteQueue("queue2"); - session.deleteQueue("queue3"); - - session.close(); - } - - - @Test - public void testQueueWithWildcard2() throws Exception - { + public void testQueueWithWildcard() throws Exception { session.createQueue("a.b", "queue1"); session.createTemporaryQueue("a.#", "queue2"); session.createTemporaryQueue("a.#", "queue3"); @@ -302,8 +241,46 @@ public class TemporaryQueueTest extends SingleServerTestBase } @Test - public void testQueueWithWildcard3() throws Exception - { + public void testQueueWithWildcard2() throws Exception { + session.createQueue("a.b", "queue1"); + session.createTemporaryQueue("a.#", "queue2"); + session.createTemporaryQueue("a.#", "queue3"); + + ClientProducer producer = session.createProducer("a.b"); + producer.send(session.createMessage(false)); + + ClientConsumer cons = session.createConsumer("queue2"); + + session.start(); + + ClientMessage msg = cons.receive(5000); + + assertNotNull(msg); + + msg.acknowledge(); + + cons.close(); + + cons = session.createConsumer("queue3"); + + session.start(); + + msg = cons.receive(5000); + + assertNotNull(msg); + + msg.acknowledge(); + + cons.close(); + + session.deleteQueue("queue2"); + session.deleteQueue("queue3"); + + session.close(); + } + + @Test + public void testQueueWithWildcard3() throws Exception { session.createQueue("a.b", "queue1"); session.createTemporaryQueue("a.#", "queue2"); session.createTemporaryQueue("a.#", "queue2.1"); @@ -312,8 +289,7 @@ public class TemporaryQueueTest extends SingleServerTestBase } @Test - public void testDeleteTemporaryQueueAfterConnectionIsClosed_2() throws Exception - { + public void testDeleteTemporaryQueueAfterConnectionIsClosed_2() throws Exception { SimpleString queue = RandomUtil.randomSimpleString(); SimpleString address = RandomUtil.randomSimpleString(); @@ -337,14 +313,8 @@ public class TemporaryQueueTest extends SingleServerTestBase } @Test - public void testRecreateConsumerOverServerFailure() throws Exception - { - ServerLocator serverWithReattach = createInVMNonHALocator() - .setReconnectAttempts(-1) - .setRetryInterval(1000) - .setConfirmationWindowSize(-1) - .setConnectionTTL(TemporaryQueueTest.CONNECTION_TTL) - .setClientFailureCheckPeriod(TemporaryQueueTest.CONNECTION_TTL / 3); + public void testRecreateConsumerOverServerFailure() throws Exception { + ServerLocator serverWithReattach = createInVMNonHALocator().setReconnectAttempts(-1).setRetryInterval(1000).setConfirmationWindowSize(-1).setConnectionTTL(TemporaryQueueTest.CONNECTION_TTL).setClientFailureCheckPeriod(TemporaryQueueTest.CONNECTION_TTL / 3); ClientSessionFactory reattachSF = createSessionFactory(serverWithReattach); ClientSession session = reattachSF.createSession(false, false); @@ -370,53 +340,45 @@ public class TemporaryQueueTest extends SingleServerTestBase serverWithReattach.close(); - } @Test - public void testTemporaryQueuesWithFilter() throws Exception - { + public void testTemporaryQueuesWithFilter() throws Exception { int countTmpQueue = 0; final AtomicInteger errors = new AtomicInteger(0); - class MyHandler implements MessageHandler - { + class MyHandler implements MessageHandler { + final String color; final CountDownLatch latch; final ClientSession sess; - public MyHandler(ClientSession sess, String color, int expectedMessages) - { + public MyHandler(ClientSession sess, String color, int expectedMessages) { this.sess = sess; latch = new CountDownLatch(expectedMessages); this.color = color; } - public boolean waitCompletion() throws Exception - { + public boolean waitCompletion() throws Exception { return latch.await(10, TimeUnit.SECONDS); } - public void onMessage(ClientMessage message) - { - try - { + public void onMessage(ClientMessage message) { + try { message.acknowledge(); sess.commit(); latch.countDown(); - if (!message.getStringProperty("color").equals(color)) - { + if (!message.getStringProperty("color").equals(color)) { log.warn("Unexpected color " + message.getStringProperty("color") + " when we were expecting " + color); errors.incrementAndGet(); } } - catch (Exception e) - { + catch (Exception e) { log.warn(e.getMessage(), e); errors.incrementAndGet(); } @@ -428,8 +390,7 @@ public class TemporaryQueueTest extends SingleServerTestBase int iterations = 100; int msgs = 100; - for (int i = 0; i < iterations; i++) - { + for (int i = 0; i < iterations; i++) { ClientSessionFactory clientsConnecton = addSessionFactory(createSessionFactory(locator)); ClientSession localSession = clientsConnecton.createSession(); @@ -437,7 +398,6 @@ public class TemporaryQueueTest extends SingleServerTestBase localSession.start(); - log.info("Iteration " + i); String queueRed = address + "_red_" + (countTmpQueue++); String queueBlue = address + "_blue_" + (countTmpQueue++); @@ -456,16 +416,14 @@ public class TemporaryQueueTest extends SingleServerTestBase blueClientConsumer.setMessageHandler(blueHandler); sessConsumerBlue.start(); - try - { + try { ClientMessage msgBlue = session.createMessage(false); msgBlue.putStringProperty("color", "blue"); ClientMessage msgRed = session.createMessage(false); msgRed.putStringProperty("color", "red"); - for (int nmsg = 0; nmsg < msgs; nmsg++) - { + for (int nmsg = 0; nmsg < msgs; nmsg++) { prod.send(msgBlue); prod.send(msgRed); @@ -479,8 +437,7 @@ public class TemporaryQueueTest extends SingleServerTestBase assertEquals(0, errors.get()); } - finally - { + finally { localSession.close(); clientsConnecton.close(); } @@ -489,8 +446,7 @@ public class TemporaryQueueTest extends SingleServerTestBase } @Test - public void testDeleteTemporaryQueueWhenClientCrash() throws Exception - { + public void testDeleteTemporaryQueueWhenClientCrash() throws Exception { session.close(); sf.close(); @@ -500,13 +456,10 @@ public class TemporaryQueueTest extends SingleServerTestBase // server must received at least one ping from the client to pass // so that the server connection TTL is configured with the client value final CountDownLatch pingOnServerLatch = new CountDownLatch(1); - server.getRemotingService().addIncomingInterceptor(new Interceptor() - { + server.getRemotingService().addIncomingInterceptor(new Interceptor() { - public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException - { - if (packet.getType() == PacketImpl.PING) - { + public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { + if (packet.getType() == PacketImpl.PING) { pingOnServerLatch.countDown(); } return true; @@ -519,17 +472,13 @@ public class TemporaryQueueTest extends SingleServerTestBase session = sf.createSession(false, true, true); session.createTemporaryQueue(address, queue); - assertTrue("server has not received any ping from the client", - pingOnServerLatch.await(2 * RemotingServiceImpl.CONNECTION_TTL_CHECK_INTERVAL, - TimeUnit.MILLISECONDS)); + assertTrue("server has not received any ping from the client", pingOnServerLatch.await(2 * RemotingServiceImpl.CONNECTION_TTL_CHECK_INTERVAL, TimeUnit.MILLISECONDS)); assertEquals(1, server.getConnectionCount()); RemotingConnection remotingConnection = server.getRemotingService().getConnections().iterator().next(); final CountDownLatch serverCloseLatch = new CountDownLatch(1); - remotingConnection.addCloseListener(new CloseListener() - { - public void connectionClosed() - { + remotingConnection.addCloseListener(new CloseListener() { + public void connectionClosed() { serverCloseLatch.countDown(); } }); @@ -537,14 +486,10 @@ public class TemporaryQueueTest extends SingleServerTestBase ((ClientSessionInternal) session).getConnection().fail(new ActiveMQInternalErrorException("simulate a client failure")); // let some time for the server to clean the connections - assertTrue("server has not closed the connection", - serverCloseLatch.await(2 * RemotingServiceImpl.CONNECTION_TTL_CHECK_INTERVAL + - 2 * - TemporaryQueueTest.CONNECTION_TTL, TimeUnit.MILLISECONDS)); + assertTrue("server has not closed the connection", serverCloseLatch.await(2 * RemotingServiceImpl.CONNECTION_TTL_CHECK_INTERVAL + 2 * TemporaryQueueTest.CONNECTION_TTL, TimeUnit.MILLISECONDS)); // The next getCount will be asynchronously done at the end of failure. We will wait some time until it has reached there. - for (long timeout = System.currentTimeMillis() + 5000; timeout > System.currentTimeMillis() && server.getConnectionCount() > 0;) - { + for (long timeout = System.currentTimeMillis() + 5000; timeout > System.currentTimeMillis() && server.getConnectionCount() > 0; ) { Thread.sleep(1); } @@ -559,16 +504,13 @@ public class TemporaryQueueTest extends SingleServerTestBase session = sf.createSession(false, true, true); session.start(); - ActiveMQAction activeMQAction = new ActiveMQAction() - { - public void run() throws ActiveMQException - { + ActiveMQAction activeMQAction = new ActiveMQAction() { + public void run() throws ActiveMQException { session.createConsumer(queue); } }; - ActiveMQTestBase.expectActiveMQException("temp queue must not exist after the server detected the client crash", - ActiveMQExceptionType.QUEUE_DOES_NOT_EXIST, activeMQAction); + ActiveMQTestBase.expectActiveMQException("temp queue must not exist after the server detected the client crash", ActiveMQExceptionType.QUEUE_DOES_NOT_EXIST, activeMQAction); session.close(); @@ -576,12 +518,9 @@ public class TemporaryQueueTest extends SingleServerTestBase } @Test - public void testBlockingWithTemporaryQueue() throws Exception - { + public void testBlockingWithTemporaryQueue() throws Exception { - AddressSettings setting = new AddressSettings() - .setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK) - .setMaxSizeBytes(1024 * 1024); + AddressSettings setting = new AddressSettings().setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK).setMaxSizeBytes(1024 * 1024); server.getAddressSettingsRepository().addMatch("TestAD", setting); @@ -600,23 +539,18 @@ public class TemporaryQueueTest extends SingleServerTestBase final int TOTAL_MSG = 1000; - Thread t = new Thread() - { + Thread t = new Thread() { @Override - public void run() - { - try - { - for (int i = 0; i < TOTAL_MSG; i++) - { + public void run() { + try { + for (int i = 0; i < TOTAL_MSG; i++) { ClientMessage msg = session.createMessage(false); msg.getBodyBuffer().writeBytes(new byte[1024]); prod.send(msg); msgs.incrementAndGet(); } } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); errors.incrementAndGet(); } @@ -627,13 +561,11 @@ public class TemporaryQueueTest extends SingleServerTestBase t.start(); - while (msgs.get() == 0) - { + while (msgs.get() == 0) { Thread.sleep(100); } - while (t.isAlive() && errors.get() == 0 && !prod.getProducerCredits().isBlocked()) - { + while (t.isAlive() && errors.get() == 0 && !prod.getProducerCredits().isBlocked()) { Thread.sleep(100); } @@ -647,10 +579,8 @@ public class TemporaryQueueTest extends SingleServerTestBase int toReceive = TOTAL_MSG - msgs.get(); - for (ServerSession sessionIterator : server.getSessions()) - { - if (sessionIterator.getMetaData("consumer") != null) - { + for (ServerSession sessionIterator : server.getSessions()) { + if (sessionIterator.getMetaData("consumer") != null) { System.out.println("Failing session"); ServerSessionImpl impl = (ServerSessionImpl) sessionIterator; impl.getRemotingConnection().fail(new ActiveMQDisconnectedException("failure e")); @@ -660,8 +590,7 @@ public class TemporaryQueueTest extends SingleServerTestBase int secondReceive = 0; ClientMessage msg = null; - while (secondReceive < toReceive && (msg = newConsumer.receive(5000)) != null) - { + while (secondReceive < toReceive && (msg = newConsumer.receive(5000)) != null) { msg.acknowledge(); secondReceive++; } @@ -672,7 +601,6 @@ public class TemporaryQueueTest extends SingleServerTestBase t.join(); - } // Package protected --------------------------------------------- diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/TransactionDurabilityTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/TransactionDurabilityTest.java index 6de9633c65..c15cea4a9a 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/TransactionDurabilityTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/TransactionDurabilityTest.java @@ -28,8 +28,7 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Assert; import org.junit.Test; -public class TransactionDurabilityTest extends ActiveMQTestBase -{ +public class TransactionDurabilityTest extends ActiveMQTestBase { /* * This tests the following situation: @@ -47,8 +46,7 @@ public class TransactionDurabilityTest extends ActiveMQTestBase * */ @Test - public void testRolledBackAcknowledgeWithSameMessageAckedByOtherSession() throws Exception - { + public void testRolledBackAcknowledgeWithSameMessageAckedByOtherSession() throws Exception { final SimpleString testAddress = new SimpleString("testAddress"); final SimpleString queue1 = new SimpleString("queue1"); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/TransactionalSendTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/TransactionalSendTest.java index 8f37bf6fe9..3185d1559b 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/TransactionalSendTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/TransactionalSendTest.java @@ -28,8 +28,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class TransactionalSendTest extends ActiveMQTestBase -{ +public class TransactionalSendTest extends ActiveMQTestBase { + public final SimpleString addressA = new SimpleString("addressA"); public final SimpleString queueA = new SimpleString("queueA"); @@ -42,15 +42,13 @@ public class TransactionalSendTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = createInVMNonHALocator(); } @Test - public void testSendWithCommit() throws Exception - { + public void testSendWithCommit() throws Exception { ActiveMQServer server = createServer(false); server.start(); ClientSessionFactory cf = createSessionFactory(locator); @@ -58,8 +56,7 @@ public class TransactionalSendTest extends ActiveMQTestBase session.createQueue(addressA, queueA, false); ClientProducer cp = session.createProducer(addressA); int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { cp.send(session.createMessage(false)); } Queue q = (Queue) server.getPostOffice().getBinding(queueA).getBindable(); @@ -67,8 +64,7 @@ public class TransactionalSendTest extends ActiveMQTestBase session.commit(); Assert.assertEquals(getMessageCount(q), numMessages); // now send some more - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { cp.send(session.createMessage(false)); } Assert.assertEquals(numMessages, getMessageCount(q)); @@ -78,8 +74,7 @@ public class TransactionalSendTest extends ActiveMQTestBase } @Test - public void testSendWithRollback() throws Exception - { + public void testSendWithRollback() throws Exception { ActiveMQServer server = createServer(false); server.start(); ClientSessionFactory cf = createSessionFactory(locator); @@ -87,8 +82,7 @@ public class TransactionalSendTest extends ActiveMQTestBase session.createQueue(addressA, queueA, false); ClientProducer cp = session.createProducer(addressA); int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { cp.send(session.createMessage(false)); } Queue q = (Queue) server.getPostOffice().getBinding(queueA).getBindable(); @@ -96,8 +90,7 @@ public class TransactionalSendTest extends ActiveMQTestBase session.rollback(); Assert.assertEquals(getMessageCount(q), 0); // now send some more - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { cp.send(session.createMessage(false)); } Assert.assertEquals(0, getMessageCount(q)); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/TransientQueueTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/TransientQueueTest.java index cdeea7fbbb..beea77efda 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/TransientQueueTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/TransientQueueTest.java @@ -28,12 +28,10 @@ import org.apache.activemq.artemis.tests.util.SingleServerTestBase; import org.apache.activemq.artemis.tests.util.RandomUtil; import org.junit.Test; -public class TransientQueueTest extends SingleServerTestBase -{ +public class TransientQueueTest extends SingleServerTestBase { @Test - public void testSimpleTransientQueue() throws Exception - { + public void testSimpleTransientQueue() throws Exception { SimpleString queue = RandomUtil.randomSimpleString(); SimpleString address = RandomUtil.randomSimpleString(); @@ -54,8 +52,7 @@ public class TransientQueueTest extends SingleServerTestBase } @Test - public void testMultipleConsumers() throws Exception - { + public void testMultipleConsumers() throws Exception { SimpleString queue = SimpleString.toSimpleString("queue"); SimpleString address = SimpleString.toSimpleString("address"); @@ -79,19 +76,15 @@ public class TransientQueueTest extends SingleServerTestBase session.start(); session2.start(); - ClientProducer producer = session.createProducer(address); - for (int i = 0; i < 1000; i++) - { + for (int i = 0; i < 1000; i++) { ClientMessage msg = session.createMessage(false); producer.send(msg); } - ClientMessage msg; - for (int i = 0; i < 500; i++) - { + for (int i = 0; i < 500; i++) { msg = consumer1.receive(1000); assertNotNull(msg); @@ -101,13 +94,10 @@ public class TransientQueueTest extends SingleServerTestBase msg.acknowledge(); } - assertNull(consumer1.receiveImmediate()); assertNull(consumer2.receiveImmediate()); - - for (int i = 0; i < 1000; i++) - { + for (int i = 0; i < 1000; i++) { msg = session.createMessage(false); producer.send(msg); } @@ -120,7 +110,6 @@ public class TransientQueueTest extends SingleServerTestBase assertNotNull(msg); msg.acknowledge(); - consumer1.close(); consumer2.close(); @@ -141,49 +130,40 @@ public class TransientQueueTest extends SingleServerTestBase } @Test - public void testQueueDifferentConfigs() throws Exception - { + public void testQueueDifferentConfigs() throws Exception { SimpleString queue = RandomUtil.randomSimpleString(); SimpleString address = RandomUtil.randomSimpleString(); - server.locateQueue(queue); SimpleString address2 = RandomUtil.randomSimpleString(); session.createSharedQueue(address, queue, false); assertEquals(1, server.getConnectionCount()); - ServerLocator locator2 = createLocator(); ClientSessionFactory sf2 = locator2.createSessionFactory(); ClientSession session2 = sf2.createSession(false, false); addClientSession(session2); - boolean exHappened = false; - try - { + try { // There's already a queue with that name, we are supposed to throw an exception session2.createSharedQueue(address2, queue, false); } - catch (ActiveMQInvalidTransientQueueUseException e) - { + catch (ActiveMQInvalidTransientQueueUseException e) { exHappened = true; } assertTrue(exHappened); - exHappened = false; - try - { + try { // There's already a queue with that name, we are supposed to throw an exception session2.createSharedQueue(address, queue, SimpleString.toSimpleString("a=1"), false); } - catch (ActiveMQInvalidTransientQueueUseException e) - { + catch (ActiveMQInvalidTransientQueueUseException e) { exHappened = true; } @@ -194,44 +174,33 @@ public class TransientQueueTest extends SingleServerTestBase assertNull(server.locateQueue(queue)); - session.createSharedQueue(address, queue, SimpleString.toSimpleString("q=1"), false); exHappened = false; - try - { + try { // There's already a queue with that name, we are supposed to throw an exception session2.createSharedQueue(address, queue, SimpleString.toSimpleString("q=2"), false); } - catch (ActiveMQInvalidTransientQueueUseException e) - { + catch (ActiveMQInvalidTransientQueueUseException e) { exHappened = true; } assertTrue(exHappened); - exHappened = false; - try - { + try { // There's already a queue with that name, we are supposed to throw an exception session2.createSharedQueue(address, queue, false); } - catch (ActiveMQInvalidTransientQueueUseException e) - { + catch (ActiveMQInvalidTransientQueueUseException e) { exHappened = true; } assertTrue(exHappened); } - protected ServerLocator createLocator() - { - return super.createLocator() - .setConsumerWindowSize(0) - .setBlockOnAcknowledge(true) - .setBlockOnDurableSend(false) - .setBlockOnNonDurableSend(false); + protected ServerLocator createLocator() { + return super.createLocator().setConsumerWindowSize(0).setBlockOnAcknowledge(true).setBlockOnDurableSend(false).setBlockOnNonDurableSend(false); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/WildCardRoutingTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/WildCardRoutingTest.java index b8ab7b18e8..64968dd5e4 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/WildCardRoutingTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/WildCardRoutingTest.java @@ -31,16 +31,15 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class WildCardRoutingTest extends ActiveMQTestBase -{ +public class WildCardRoutingTest extends ActiveMQTestBase { + private ActiveMQServer server; private ServerLocator locator; private ClientSession clientSession; private ClientSessionFactory sf; @Test - public void testBasicWildcardRouting() throws Exception - { + public void testBasicWildcardRouting() throws Exception { SimpleString addressAB = new SimpleString("a.b"); SimpleString addressAC = new SimpleString("a.c"); SimpleString address = new SimpleString("a.*"); @@ -69,8 +68,7 @@ public class WildCardRoutingTest extends ActiveMQTestBase } @Test - public void testBasicWildcardRoutingQueuesDontExist() throws Exception - { + public void testBasicWildcardRoutingQueuesDontExist() throws Exception { SimpleString addressAB = new SimpleString("a.b"); SimpleString addressAC = new SimpleString("a.c"); SimpleString address = new SimpleString("a.*"); @@ -101,8 +99,7 @@ public class WildCardRoutingTest extends ActiveMQTestBase } @Test - public void testBasicWildcardRoutingQueuesDontExist2() throws Exception - { + public void testBasicWildcardRoutingQueuesDontExist2() throws Exception { SimpleString addressAB = new SimpleString("a.b"); SimpleString addressAC = new SimpleString("a.c"); SimpleString address = new SimpleString("a.*"); @@ -141,8 +138,7 @@ public class WildCardRoutingTest extends ActiveMQTestBase } @Test - public void testBasicWildcardRoutingWithHash() throws Exception - { + public void testBasicWildcardRoutingWithHash() throws Exception { SimpleString addressAB = new SimpleString("a.b"); SimpleString addressAC = new SimpleString("a.c"); SimpleString address = new SimpleString("a.#"); @@ -171,8 +167,7 @@ public class WildCardRoutingTest extends ActiveMQTestBase } @Test - public void testWildcardRoutingQueuesAddedAfter() throws Exception - { + public void testWildcardRoutingQueuesAddedAfter() throws Exception { SimpleString addressAB = new SimpleString("a.b"); SimpleString addressAC = new SimpleString("a.c"); SimpleString address = new SimpleString("a.*"); @@ -201,8 +196,7 @@ public class WildCardRoutingTest extends ActiveMQTestBase } @Test - public void testWildcardRoutingQueuesAddedThenDeleted() throws Exception - { + public void testWildcardRoutingQueuesAddedThenDeleted() throws Exception { SimpleString addressAB = new SimpleString("a.b"); SimpleString addressAC = new SimpleString("a.c"); SimpleString address = new SimpleString("a.*"); @@ -235,8 +229,7 @@ public class WildCardRoutingTest extends ActiveMQTestBase } @Test - public void testWildcardRoutingLotsOfQueuesAddedThenDeleted() throws Exception - { + public void testWildcardRoutingLotsOfQueuesAddedThenDeleted() throws Exception { SimpleString addressAB = new SimpleString("a.b"); SimpleString addressAC = new SimpleString("a.c"); SimpleString addressAD = new SimpleString("a.d"); @@ -333,8 +326,7 @@ public class WildCardRoutingTest extends ActiveMQTestBase } @Test - public void testWildcardRoutingLotsOfQueuesAddedThenDeletedHash() throws Exception - { + public void testWildcardRoutingLotsOfQueuesAddedThenDeletedHash() throws Exception { SimpleString addressAB = new SimpleString("a.b"); SimpleString addressAC = new SimpleString("a.c"); SimpleString addressAD = new SimpleString("a.d"); @@ -431,8 +423,7 @@ public class WildCardRoutingTest extends ActiveMQTestBase } @Test - public void testWildcardRoutingWithSingleHash() throws Exception - { + public void testWildcardRoutingWithSingleHash() throws Exception { SimpleString addressAB = new SimpleString("a.b"); SimpleString addressAC = new SimpleString("a.c"); SimpleString address = new SimpleString("#"); @@ -461,8 +452,7 @@ public class WildCardRoutingTest extends ActiveMQTestBase } @Test - public void testWildcardRoutingWithHash() throws Exception - { + public void testWildcardRoutingWithHash() throws Exception { SimpleString addressAB = new SimpleString("a.b.f"); SimpleString addressAC = new SimpleString("a.c.f"); SimpleString address = new SimpleString("a.#.f"); @@ -491,8 +481,7 @@ public class WildCardRoutingTest extends ActiveMQTestBase } @Test - public void testWildcardRoutingWithHashMultiLengthAddresses() throws Exception - { + public void testWildcardRoutingWithHashMultiLengthAddresses() throws Exception { SimpleString addressAB = new SimpleString("a.b.c.f"); SimpleString addressAC = new SimpleString("a.c.f"); SimpleString addressAD = new SimpleString("a.d"); @@ -522,8 +511,7 @@ public class WildCardRoutingTest extends ActiveMQTestBase } @Test - public void testWildcardRoutingWithDoubleStar() throws Exception - { + public void testWildcardRoutingWithDoubleStar() throws Exception { SimpleString addressAB = new SimpleString("a.b"); SimpleString addressAC = new SimpleString("a.c"); SimpleString address = new SimpleString("*.*"); @@ -552,8 +540,7 @@ public class WildCardRoutingTest extends ActiveMQTestBase } @Test - public void testWildcardRoutingPartialMatchStar() throws Exception - { + public void testWildcardRoutingPartialMatchStar() throws Exception { SimpleString addressAB = new SimpleString("a.b"); SimpleString addressAC = new SimpleString("a.c"); SimpleString address = new SimpleString("*.b"); @@ -578,8 +565,7 @@ public class WildCardRoutingTest extends ActiveMQTestBase } @Test - public void testWildcardRoutingVariableLengths() throws Exception - { + public void testWildcardRoutingVariableLengths() throws Exception { SimpleString addressAB = new SimpleString("a.b.c"); SimpleString addressAC = new SimpleString("a.c"); SimpleString address = new SimpleString("a.#"); @@ -606,8 +592,7 @@ public class WildCardRoutingTest extends ActiveMQTestBase } @Test - public void testWildcardRoutingVariableLengthsStar() throws Exception - { + public void testWildcardRoutingVariableLengthsStar() throws Exception { SimpleString addressAB = new SimpleString("a.b.c"); SimpleString addressAC = new SimpleString("a.c"); SimpleString address = new SimpleString("a.*"); @@ -632,8 +617,7 @@ public class WildCardRoutingTest extends ActiveMQTestBase } @Test - public void testWildcardRoutingMultipleStars() throws Exception - { + public void testWildcardRoutingMultipleStars() throws Exception { SimpleString addressAB = new SimpleString("a.b.c"); SimpleString addressAC = new SimpleString("a.c"); SimpleString address = new SimpleString("*.*"); @@ -658,8 +642,7 @@ public class WildCardRoutingTest extends ActiveMQTestBase } @Test - public void testWildcardRoutingStarInMiddle() throws Exception - { + public void testWildcardRoutingStarInMiddle() throws Exception { SimpleString addressAB = new SimpleString("a.b.c"); SimpleString addressAC = new SimpleString("a.c"); SimpleString address = new SimpleString("*.b.*"); @@ -684,8 +667,7 @@ public class WildCardRoutingTest extends ActiveMQTestBase } @Test - public void testWildcardRoutingStarAndHash() throws Exception - { + public void testWildcardRoutingStarAndHash() throws Exception { SimpleString addressAB = new SimpleString("a.b.c.d"); SimpleString addressAC = new SimpleString("a.c"); SimpleString address = new SimpleString("*.b.#"); @@ -710,8 +692,7 @@ public class WildCardRoutingTest extends ActiveMQTestBase } @Test - public void testWildcardRoutingHashAndStar() throws Exception - { + public void testWildcardRoutingHashAndStar() throws Exception { SimpleString addressAB = new SimpleString("a.b.c"); SimpleString addressAC = new SimpleString("a.c"); SimpleString address = new SimpleString("#.b.*"); @@ -736,8 +717,7 @@ public class WildCardRoutingTest extends ActiveMQTestBase } @Test - public void testLargeWildcardRouting() throws Exception - { + public void testLargeWildcardRouting() throws Exception { SimpleString addressAB = new SimpleString("a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.s.t.u.v.w.x.y.z"); SimpleString addressAC = new SimpleString("a.c"); SimpleString address = new SimpleString("a.#"); @@ -775,12 +755,9 @@ public class WildCardRoutingTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - Configuration configuration = createDefaultInVMConfig() - .setWildcardRoutingEnabled(true) - .setTransactionTimeoutScanPeriod(500); + Configuration configuration = createDefaultInVMConfig().setWildcardRoutingEnabled(true).setTransactionTimeoutScanPeriod(500); server = addServer(ActiveMQServers.newActiveMQServer(configuration, false)); server.start(); server.getManagementService().enableNotifications(false); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/ClientCrashTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/ClientCrashTest.java index 575518b4f5..0b33ffd76a 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/ClientCrashTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/ClientCrashTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.clientcrash; + import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; import org.apache.activemq.artemis.tests.util.SpawnedVMSupport; import org.junit.Before; @@ -36,8 +37,8 @@ import org.apache.activemq.artemis.jms.client.ActiveMQTextMessage; * A test that makes sure that an ActiveMQ Artemis server cleans up the associated * resources when one of its client crashes. */ -public class ClientCrashTest extends ClientTestBase -{ +public class ClientCrashTest extends ClientTestBase { + // using short values so this test can run fast static final int PING_PERIOD = 100; @@ -68,8 +69,7 @@ public class ClientCrashTest extends ClientTestBase // Public -------------------------------------------------------- @Test - public void testCrashClient() throws Exception - { + public void testCrashClient() throws Exception { assertActiveConnections(1); ClientSession session = sf.createSession(false, true, true); @@ -83,7 +83,6 @@ public class ClientCrashTest extends ClientTestBase ClientConsumer consumer = session.createConsumer(ClientCrashTest.QUEUE); ClientProducer producer = session.createProducer(ClientCrashTest.QUEUE); - session.start(); // receive a message from the queue @@ -94,11 +93,7 @@ public class ClientCrashTest extends ClientTestBase assertActiveConnections(1 + 1); // One local and one from the other vm assertActiveSession(1 + 1); - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte)1); + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.getBodyBuffer().writeString(ClientCrashTest.MESSAGE_TEXT_FROM_SERVER); producer.send(message); @@ -122,8 +117,7 @@ public class ClientCrashTest extends ClientTestBase } @Test - public void testCrashClient2() throws Exception - { + public void testCrashClient2() throws Exception { // set the redelivery delay to avoid an attempt to redeliver the message to the dead client AddressSettings addressSettings = new AddressSettings().setRedeliveryDelay(ClientCrashTest.CONNECTION_TTL + ClientCrashTest.PING_PERIOD); server.getAddressSettingsRepository().addMatch(ClientCrashTest.QUEUE2.toString(), addressSettings); @@ -168,8 +162,7 @@ public class ClientCrashTest extends ClientTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = createNettyNonHALocator(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/ClientExitTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/ClientExitTest.java index cc49797252..d890d50494 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/ClientExitTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/ClientExitTest.java @@ -35,8 +35,7 @@ import org.junit.Test; * This is not technically a crash test, but it uses the same type of topology as the crash tests * (local server, remote VM client). */ -public class ClientExitTest extends ClientTestBase -{ +public class ClientExitTest extends ClientTestBase { // Constants ------------------------------------------------------------------------------------ private static final String MESSAGE_TEXT = RandomUtil.randomString(); @@ -58,12 +57,9 @@ public class ClientExitTest extends ClientTestBase // Public --------------------------------------------------------------------------------------- @Test - public void testGracefulClientExit() throws Exception - { + public void testGracefulClientExit() throws Exception { // spawn a JVM that creates a JMS client, which sends a test message - Process p = SpawnedVMSupport.spawnVM(GracefulClient.class.getName(), - ClientExitTest.QUEUE.toString(), - ClientExitTest.MESSAGE_TEXT); + Process p = SpawnedVMSupport.spawnVM(GracefulClient.class.getName(), ClientExitTest.QUEUE.toString(), ClientExitTest.MESSAGE_TEXT); // read the message from the queue @@ -98,8 +94,7 @@ public class ClientExitTest extends ClientTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); ServerLocator locator = createNettyNonHALocator(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/ClientTestBase.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/ClientTestBase.java index 6150756d7b..42ea2c5fa1 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/ClientTestBase.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/ClientTestBase.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.clientcrash; + import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Before; @@ -23,15 +24,13 @@ import org.junit.Assert; import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.core.server.ActiveMQServer; -public abstract class ClientTestBase extends ActiveMQTestBase -{ +public abstract class ClientTestBase extends ActiveMQTestBase { protected ActiveMQServer server; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); Configuration config = createDefaultNettyConfig(); @@ -39,35 +38,28 @@ public abstract class ClientTestBase extends ActiveMQTestBase server.start(); } - protected void assertActiveConnections(final int expectedActiveConnections) throws Exception - { + protected void assertActiveConnections(final int expectedActiveConnections) throws Exception { assertActiveConnections(expectedActiveConnections, 0); } - protected void assertActiveConnections(final int expectedActiveConnections, long timeout) throws Exception - { + protected void assertActiveConnections(final int expectedActiveConnections, long timeout) throws Exception { timeout += System.currentTimeMillis(); - while (timeout > System.currentTimeMillis() && server.getActiveMQServerControl().getConnectionCount() != expectedActiveConnections) - { + while (timeout > System.currentTimeMillis() && server.getActiveMQServerControl().getConnectionCount() != expectedActiveConnections) { Thread.sleep(100); } Assert.assertEquals(expectedActiveConnections, server.getActiveMQServerControl().getConnectionCount()); } - protected void assertActiveSession(final int expectedActiveSession) throws Exception - { + protected void assertActiveSession(final int expectedActiveSession) throws Exception { assertActiveSession(expectedActiveSession, 0); } - protected void assertActiveSession(final int expectedActiveSession, long timeout) throws Exception - { + protected void assertActiveSession(final int expectedActiveSession, long timeout) throws Exception { timeout += System.currentTimeMillis(); - while (timeout > System.currentTimeMillis() && server.getSessions().size() != expectedActiveSession) - { + while (timeout > System.currentTimeMillis() && server.getSessions().size() != expectedActiveSession) { Thread.sleep(100); } Assert.assertEquals(expectedActiveSession, server.getSessions().size()); } - } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/CrashClient.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/CrashClient.java index 300e365d43..b006790dc5 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/CrashClient.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/CrashClient.java @@ -32,18 +32,15 @@ import org.apache.activemq.artemis.jms.client.ActiveMQTextMessage; /** * Code to be run in an external VM, via main() */ -public class CrashClient -{ +public class CrashClient { // Constants ------------------------------------------------------------------------------------ private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; // Static --------------------------------------------------------------------------------------- - public static void main(final String[] args) throws Exception - { - try - { + public static void main(final String[] args) throws Exception { + try { CrashClient.log.debug("args = " + Arrays.asList(args)); ServerLocator locator = ActiveMQClient.createServerLocatorWithoutHA(new TransportConfiguration(NettyConnectorFactory.class.getName())); @@ -51,16 +48,11 @@ public class CrashClient locator.setConnectionTTL(ClientCrashTest.CONNECTION_TTL); ClientSessionFactory sf = locator.createSessionFactory(); - ClientSession session = sf.createSession(false, true, true); ClientProducer producer = session.createProducer(ClientCrashTest.QUEUE); // it has to be durable otherwise it may race dying before the client is killed - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - true, - 0, - System.currentTimeMillis(), - (byte)1); + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, true, 0, System.currentTimeMillis(), (byte) 1); message.getBodyBuffer().writeString(ClientCrashTest.MESSAGE_TEXT_FROM_CLIENT); producer.send(message); @@ -68,8 +60,7 @@ public class CrashClient // exit without closing the session properly System.exit(9); } - catch (Throwable t) - { + catch (Throwable t) { CrashClient.log.error(t.getMessage(), t); System.exit(1); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/CrashClient2.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/CrashClient2.java index da6ad285c3..f83a941912 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/CrashClient2.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/CrashClient2.java @@ -32,18 +32,15 @@ import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; /** * Code to be run in an external VM, via main() */ -public class CrashClient2 -{ +public class CrashClient2 { // Constants ------------------------------------------------------------------------------------ private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; // Static --------------------------------------------------------------------------------------- - public static void main(final String[] args) throws Exception - { - try - { + public static void main(final String[] args) throws Exception { + try { log.debug("args = " + Arrays.asList(args)); ServerLocator locator = ActiveMQClient.createServerLocatorWithoutHA(new TransportConfiguration(NettyConnectorFactory.class.getName())); @@ -51,7 +48,6 @@ public class CrashClient2 locator.setConnectionTTL(ClientCrashTest.CONNECTION_TTL); ClientSessionFactory sf = locator.createSessionFactory(); - ClientSession session = sf.createSession(true, true, 1000000); ClientProducer producer = session.createProducer(ClientCrashTest.QUEUE2); @@ -69,8 +65,7 @@ public class CrashClient2 ClientMessage msg = cons.receive(10000); - if (msg == null) - { + if (msg == null) { log.error("Didn't receive msg"); System.exit(1); @@ -79,8 +74,7 @@ public class CrashClient2 // exit without closing the session properly System.exit(9); } - catch (Throwable t) - { + catch (Throwable t) { log.error(t.getMessage(), t); System.exit(1); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/DummyInterceptor.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/DummyInterceptor.java index a637dc8f89..79d2de570b 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/DummyInterceptor.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/DummyInterceptor.java @@ -27,8 +27,8 @@ import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionRec import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; -public class DummyInterceptor implements Interceptor -{ +public class DummyInterceptor implements Interceptor { + protected IntegrationTestLogger log = IntegrationTestLogger.LOGGER; boolean sendException = false; @@ -37,29 +37,23 @@ public class DummyInterceptor implements Interceptor AtomicInteger syncCounter = new AtomicInteger(0); - public int getCounter() - { + public int getCounter() { return syncCounter.get(); } - public void clearCounter() - { + public void clearCounter() { syncCounter.set(0); } - public boolean intercept(final Packet packet, final RemotingConnection conn) throws ActiveMQException - { + public boolean intercept(final Packet packet, final RemotingConnection conn) throws ActiveMQException { log.debug("DummyFilter packet = " + packet.getClass().getName()); syncCounter.addAndGet(1); - if (sendException) - { + if (sendException) { throw new ActiveMQInternalErrorException(); } - if (changeMessage) - { - if (packet instanceof SessionReceiveMessage) - { - SessionReceiveMessage deliver = (SessionReceiveMessage)packet; + if (changeMessage) { + if (packet instanceof SessionReceiveMessage) { + SessionReceiveMessage deliver = (SessionReceiveMessage) packet; log.debug("msg = " + deliver.getMessage().getClass().getName()); deliver.getMessage().putStringProperty(new SimpleString("DummyInterceptor"), new SimpleString("was here")); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/DummyInterceptorB.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/DummyInterceptorB.java index 05f65d4c33..4640c38c57 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/DummyInterceptorB.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/DummyInterceptorB.java @@ -24,25 +24,21 @@ import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; import org.apache.activemq.artemis.core.protocol.core.Packet; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; -public class DummyInterceptorB implements Interceptor -{ +public class DummyInterceptorB implements Interceptor { protected IntegrationTestLogger log = IntegrationTestLogger.LOGGER; static AtomicInteger syncCounter = new AtomicInteger(0); - public static int getCounter() - { + public static int getCounter() { return DummyInterceptorB.syncCounter.get(); } - public static void clearCounter() - { + public static void clearCounter() { DummyInterceptorB.syncCounter.set(0); } - public boolean intercept(final Packet packet, final RemotingConnection conn) throws ActiveMQException - { + public boolean intercept(final Packet packet, final RemotingConnection conn) throws ActiveMQException { DummyInterceptorB.syncCounter.addAndGet(1); log.debug("DummyFilter packet = " + packet); return true; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/GracefulClient.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/GracefulClient.java index f8d58b363e..d57cf22f2b 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/GracefulClient.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/clientcrash/GracefulClient.java @@ -31,36 +31,28 @@ import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; /** * Code to be run in an external VM, via main() */ -public class GracefulClient -{ +public class GracefulClient { // Constants ------------------------------------------------------------------------------------ private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; // Static --------------------------------------------------------------------------------------- - public static void main(final String[] args) throws Exception - { - if (args.length != 2) - { + public static void main(final String[] args) throws Exception { + if (args.length != 2) { throw new Exception("require 2 arguments: queue name + message text"); } String queueName = args[0]; String messageText = args[1]; - try - { + try { ServerLocator locator = ActiveMQClient.createServerLocatorWithoutHA(new TransportConfiguration(NettyConnectorFactory.class.getName())); ClientSessionFactory sf = locator.createSessionFactory(); ClientSession session = sf.createSession(false, true, true); ClientProducer producer = session.createProducer(queueName); ClientConsumer consumer = session.createConsumer(queueName); - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte) 1); + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.getBodyBuffer().writeString(messageText); producer.send(message); @@ -73,8 +65,7 @@ public class GracefulClient session.close(); System.exit(0); } - catch (Throwable t) - { + catch (Throwable t) { GracefulClient.log.error(t.getMessage(), t); System.exit(1); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/ClusterControllerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/ClusterControllerTest.java index cf352fdd08..7a20c9ac36 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/ClusterControllerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/ClusterControllerTest.java @@ -27,22 +27,18 @@ import org.apache.activemq.artemis.tests.integration.cluster.distribution.Cluste import org.junit.Before; import org.junit.Test; +public class ClusterControllerTest extends ClusterTestBase { -public class ClusterControllerTest extends ClusterTestBase -{ @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); setupServer(0, isFileStorage(), true); setupServer(1, isFileStorage(), true); - getServer(0).getConfiguration().getAcceptorConfigurations().add(createTransportConfiguration(false, true, - generateParams(0, false))); - getServer(1).getConfiguration().getAcceptorConfigurations().add(createTransportConfiguration(false, true, - generateParams(1, false))); + getServer(0).getConfiguration().getAcceptorConfigurations().add(createTransportConfiguration(false, true, generateParams(0, false))); + getServer(1).getConfiguration().getAcceptorConfigurations().add(createTransportConfiguration(false, true, generateParams(1, false))); getServer(0).getConfiguration().setSecurityEnabled(true); getServer(1).getConfiguration().setSecurityEnabled(true); @@ -57,10 +53,8 @@ public class ClusterControllerTest extends ClusterTestBase } @Test - public void controlWithDifferentConnector() throws Exception - { - try (ServerLocatorImpl locator = (ServerLocatorImpl) createInVMNonHALocator()) - { + public void controlWithDifferentConnector() throws Exception { + try (ServerLocatorImpl locator = (ServerLocatorImpl) createInVMNonHALocator()) { locator.setProtocolManagerFactory(ActiveMQServerSideProtocolManagerFactory.getInstance()); ClusterController controller = new ClusterController(getServer(0), getServer(0).getScheduledPool()); ClusterControl clusterControl = controller.connectToNodeInCluster((ClientSessionFactoryInternal) locator.createSessionFactory()); @@ -69,20 +63,16 @@ public class ClusterControllerTest extends ClusterTestBase } @Test - public void controlWithDifferentPassword() throws Exception - { - try (ServerLocatorImpl locator = (ServerLocatorImpl) createInVMNonHALocator()) - { + public void controlWithDifferentPassword() throws Exception { + try (ServerLocatorImpl locator = (ServerLocatorImpl) createInVMNonHALocator()) { locator.setProtocolManagerFactory(ActiveMQServerSideProtocolManagerFactory.getInstance()); ClusterController controller = new ClusterController(getServer(1), getServer(1).getScheduledPool()); ClusterControl clusterControl = controller.connectToNodeInCluster((ClientSessionFactoryInternal) locator.createSessionFactory()); - try - { + try { clusterControl.authorize(); fail("should throw ActiveMQClusterSecurityException"); } - catch (Exception e) - { + catch (Exception e) { assertTrue("should throw ActiveMQClusterSecurityException", e instanceof ActiveMQClusterSecurityException); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/NodeManagerAction.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/NodeManagerAction.java index 8afe1ce215..07bcc13f7b 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/NodeManagerAction.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/NodeManagerAction.java @@ -21,8 +21,8 @@ import java.io.File; import org.apache.activemq.artemis.core.server.NodeManager; import org.apache.activemq.artemis.core.server.impl.FileLockNodeManager; -public class NodeManagerAction -{ +public class NodeManagerAction { + public static final int START_LIVE = 0; public static final int START_BACKUP = 1; public static final int CRASH_LIVE = 2; @@ -36,23 +36,18 @@ public class NodeManagerAction public static final int DOESNT_HAVE_LIVE = 12; public static final int DOESNT_HAVE_BACKUP = 13; - private final int[] work; boolean hasLiveLock = false; boolean hasBackupLock = false; - public NodeManagerAction(int... work) - { + public NodeManagerAction(int... work) { this.work = work; } - public void performWork(NodeManager nodeManager) throws Exception - { - for (int action : work) - { - switch (action) - { + public void performWork(NodeManager nodeManager) throws Exception { + for (int action : work) { + switch (action) { case START_LIVE: nodeManager.startLiveNode(); hasLiveLock = true; @@ -82,28 +77,24 @@ public class NodeManagerAction nodeManager.releaseBackup(); hasBackupLock = false; case HAS_LIVE: - if (!hasLiveLock) - { + if (!hasLiveLock) { throw new IllegalStateException("live lock not held"); } break; case HAS_BACKUP: - if (!hasBackupLock) - { + if (!hasBackupLock) { throw new IllegalStateException("backup lock not held"); } break; case DOESNT_HAVE_LIVE: - if (hasLiveLock) - { + if (hasLiveLock) { throw new IllegalStateException("live lock held"); } break; case DOESNT_HAVE_BACKUP: - if (hasBackupLock) - { + if (hasBackupLock) { throw new IllegalStateException("backup lock held"); } break; @@ -111,33 +102,27 @@ public class NodeManagerAction } } - public String[] getWork() - { + public String[] getWork() { String[] strings = new String[work.length]; - for (int i = 0, stringsLength = strings.length; i < stringsLength; i++) - { + for (int i = 0, stringsLength = strings.length; i < stringsLength; i++) { strings[i] = "" + work[i]; } return strings; } - public static void main(String[] args) throws Exception - { + public static void main(String[] args) throws Exception { int[] work1 = new int[args.length]; - for (int i = 0; i < args.length; i++) - { + for (int i = 0; i < args.length; i++) { work1[i] = Integer.parseInt(args[i]); } NodeManagerAction nodeManagerAction = new NodeManagerAction(work1); FileLockNodeManager nodeManager = new FileLockNodeManager(new File("."), false); nodeManager.start(); - try - { + try { nodeManagerAction.performWork(nodeManager); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); System.exit(9); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/NodeManagerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/NodeManagerTest.java index feb523686c..e9be8bd513 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/NodeManagerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/NodeManagerTest.java @@ -36,44 +36,38 @@ import static org.apache.activemq.artemis.tests.integration.cluster.NodeManagerA import static org.apache.activemq.artemis.tests.integration.cluster.NodeManagerAction.START_LIVE; import static org.apache.activemq.artemis.tests.integration.cluster.NodeManagerAction.STOP_BACKUP; -public class NodeManagerTest extends ActiveMQTestBase -{ +public class NodeManagerTest extends ActiveMQTestBase { + @Test - public void testLive() throws Exception - { + public void testLive() throws Exception { NodeManagerAction live1 = new NodeManagerAction(START_LIVE, HAS_LIVE, DOESNT_HAVE_BACKUP, CRASH_LIVE, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE, START_LIVE, HAS_LIVE, DOESNT_HAVE_BACKUP, CRASH_LIVE, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE); performWork(live1); } @Test - public void testSimpleLiveAndBackup() throws Exception - { + public void testSimpleLiveAndBackup() throws Exception { NodeManagerAction live1 = new NodeManagerAction(START_LIVE, HAS_LIVE, DOESNT_HAVE_BACKUP, CRASH_LIVE, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE); NodeManagerAction backup1 = new NodeManagerAction(DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE, START_BACKUP, HAS_BACKUP, AWAIT_LIVE, RELEASE_BACKUP, HAS_LIVE, PAUSE_LIVE, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE); performWork(live1, backup1); } @Test - public void testSimpleBackupAndLive() throws Exception - { + public void testSimpleBackupAndLive() throws Exception { NodeManagerAction live1 = new NodeManagerAction(START_LIVE, HAS_LIVE, DOESNT_HAVE_BACKUP, CRASH_LIVE, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE); NodeManagerAction backup1 = new NodeManagerAction(DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE, START_BACKUP, HAS_BACKUP, AWAIT_LIVE, RELEASE_BACKUP, HAS_LIVE, PAUSE_LIVE, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE); performWork(backup1, live1); } @Test - public void testSimpleLiveAnd2Backups() throws Exception - { + public void testSimpleLiveAnd2Backups() throws Exception { NodeManagerAction live1 = new NodeManagerAction(START_LIVE, HAS_LIVE, DOESNT_HAVE_BACKUP, CRASH_LIVE, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE); NodeManagerAction backup1 = new NodeManagerAction(DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE, START_BACKUP, HAS_BACKUP, AWAIT_LIVE, RELEASE_BACKUP, HAS_LIVE, CRASH_LIVE, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE); NodeManagerAction backup2 = new NodeManagerAction(DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE, START_BACKUP, HAS_BACKUP, AWAIT_LIVE, RELEASE_BACKUP, HAS_LIVE, CRASH_LIVE, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE); performWork(live1, backup1, backup2); } - @Test - public void testSimple2BackupsAndLive() throws Exception - { + public void testSimple2BackupsAndLive() throws Exception { NodeManagerAction live1 = new NodeManagerAction(START_LIVE, HAS_LIVE, DOESNT_HAVE_BACKUP, CRASH_LIVE, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE); NodeManagerAction backup1 = new NodeManagerAction(DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE, START_BACKUP, HAS_BACKUP, AWAIT_LIVE, RELEASE_BACKUP, HAS_LIVE, CRASH_LIVE, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE); NodeManagerAction backup2 = new NodeManagerAction(DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE, START_BACKUP, HAS_BACKUP, AWAIT_LIVE, RELEASE_BACKUP, HAS_LIVE, CRASH_LIVE, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE); @@ -81,8 +75,7 @@ public class NodeManagerTest extends ActiveMQTestBase } @Test - public void testSimpleLiveAnd2BackupsPaused() throws Exception - { + public void testSimpleLiveAnd2BackupsPaused() throws Exception { NodeManagerAction live1 = new NodeManagerAction(START_LIVE, HAS_LIVE, DOESNT_HAVE_BACKUP, CRASH_LIVE, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE); NodeManagerAction backup1 = new NodeManagerAction(DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE, START_BACKUP, HAS_BACKUP, AWAIT_LIVE, RELEASE_BACKUP, HAS_LIVE, PAUSE_LIVE, START_LIVE, HAS_LIVE, DOESNT_HAVE_BACKUP, CRASH_LIVE, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE); NodeManagerAction backup2 = new NodeManagerAction(DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE, START_BACKUP, HAS_BACKUP, AWAIT_LIVE, RELEASE_BACKUP, HAS_LIVE, PAUSE_LIVE, START_LIVE, HAS_LIVE, DOESNT_HAVE_BACKUP, CRASH_LIVE, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE); @@ -90,8 +83,7 @@ public class NodeManagerTest extends ActiveMQTestBase } @Test - public void testSimple2BackupsPausedAndLive() throws Exception - { + public void testSimple2BackupsPausedAndLive() throws Exception { NodeManagerAction live1 = new NodeManagerAction(START_LIVE, HAS_LIVE, DOESNT_HAVE_BACKUP, CRASH_LIVE, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE); NodeManagerAction backup1 = new NodeManagerAction(DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE, START_BACKUP, HAS_BACKUP, AWAIT_LIVE, RELEASE_BACKUP, HAS_LIVE, PAUSE_LIVE, START_LIVE, HAS_LIVE, DOESNT_HAVE_BACKUP, CRASH_LIVE, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE); NodeManagerAction backup2 = new NodeManagerAction(DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE, START_BACKUP, HAS_BACKUP, AWAIT_LIVE, RELEASE_BACKUP, HAS_LIVE, PAUSE_LIVE, START_LIVE, HAS_LIVE, DOESNT_HAVE_BACKUP, CRASH_LIVE, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE); @@ -99,8 +91,7 @@ public class NodeManagerTest extends ActiveMQTestBase } @Test - public void testBackupsOnly() throws Exception - { + public void testBackupsOnly() throws Exception { NodeManagerAction backup1 = new NodeManagerAction(DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE, START_BACKUP, HAS_BACKUP, STOP_BACKUP, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE); NodeManagerAction backup2 = new NodeManagerAction(DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE, START_BACKUP, HAS_BACKUP, STOP_BACKUP, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE); NodeManagerAction backup3 = new NodeManagerAction(DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE, START_BACKUP, HAS_BACKUP, STOP_BACKUP, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE); @@ -116,90 +107,74 @@ public class NodeManagerTest extends ActiveMQTestBase } @Test - public void testLiveAndBackupLiveForcesFailback() throws Exception - { + public void testLiveAndBackupLiveForcesFailback() throws Exception { NodeManagerAction live1 = new NodeManagerAction(START_LIVE, HAS_LIVE, DOESNT_HAVE_BACKUP, CRASH_LIVE, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE, START_LIVE, HAS_LIVE, DOESNT_HAVE_BACKUP, CRASH_LIVE); NodeManagerAction backup1 = new NodeManagerAction(DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE, START_BACKUP, HAS_BACKUP, AWAIT_LIVE, RELEASE_BACKUP, HAS_LIVE, CRASH_LIVE, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE, AWAIT_LIVE, HAS_LIVE, PAUSE_LIVE); performWork(live1, backup1); } @Test - public void testLiveAnd2BackupsLiveForcesFailback() throws Exception - { + public void testLiveAnd2BackupsLiveForcesFailback() throws Exception { NodeManagerAction live1 = new NodeManagerAction(START_LIVE, HAS_LIVE, DOESNT_HAVE_BACKUP, CRASH_LIVE, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE, START_LIVE, HAS_LIVE, DOESNT_HAVE_BACKUP, CRASH_LIVE); NodeManagerAction backup1 = new NodeManagerAction(DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE, START_BACKUP, HAS_BACKUP, AWAIT_LIVE, RELEASE_BACKUP, HAS_LIVE, CRASH_LIVE, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE, AWAIT_LIVE, RELEASE_BACKUP, HAS_LIVE, CRASH_LIVE); NodeManagerAction backup2 = new NodeManagerAction(DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE, START_BACKUP, HAS_BACKUP, AWAIT_LIVE, RELEASE_BACKUP, HAS_LIVE, CRASH_LIVE, DOESNT_HAVE_BACKUP, DOESNT_HAVE_LIVE, AWAIT_LIVE, RELEASE_BACKUP, HAS_LIVE, CRASH_LIVE); performWork(live1, backup1, backup2); } - public void performWork(NodeManagerAction... actions) throws Exception - { + public void performWork(NodeManagerAction... actions) throws Exception { NodeManager nodeManager = new InVMNodeManager(false); List nodeRunners = new ArrayList(); Thread[] threads = new Thread[actions.length]; - for (NodeManagerAction action : actions) - { + for (NodeManagerAction action : actions) { NodeRunner nodeRunner = new NodeRunner(nodeManager, action); nodeRunners.add(nodeRunner); } - for (int i = 0, nodeRunnersSize = nodeRunners.size(); i < nodeRunnersSize; i++) - { + for (int i = 0, nodeRunnersSize = nodeRunners.size(); i < nodeRunnersSize; i++) { NodeRunner nodeRunner = nodeRunners.get(i); threads[i] = new Thread(nodeRunner); threads[i].start(); } - for (Thread thread : threads) - { - try - { + for (Thread thread : threads) { + try { thread.join(5000); } - catch (InterruptedException e) - { + catch (InterruptedException e) { // } - if (thread.isAlive()) - { + if (thread.isAlive()) { thread.interrupt(); fail("thread still running"); } } - for (NodeRunner nodeRunner : nodeRunners) - { - if (nodeRunner.e != null) - { + for (NodeRunner nodeRunner : nodeRunners) { + if (nodeRunner.e != null) { nodeRunner.e.printStackTrace(); fail(nodeRunner.e.getMessage()); } } } - static class NodeRunner implements Runnable - { + static class NodeRunner implements Runnable { + private NodeManagerAction action; private NodeManager manager; Throwable e; - public NodeRunner(NodeManager nodeManager, NodeManagerAction action) - { + public NodeRunner(NodeManager nodeManager, NodeManagerAction action) { this.manager = nodeManager; this.action = action; } - public void run() - { - try - { + public void run() { + try { action.performWork(manager); } - catch (Throwable e) - { + catch (Throwable e) { this.e = e; } } } - } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/RealNodeManagerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/RealNodeManagerTest.java index 51acdcbcf0..1696063266 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/RealNodeManagerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/RealNodeManagerTest.java @@ -28,11 +28,10 @@ import org.apache.activemq.artemis.utils.UUID; import org.junit.Assert; import org.junit.Test; -public class RealNodeManagerTest extends NodeManagerTest -{ +public class RealNodeManagerTest extends NodeManagerTest { + @Test - public void testId() throws Exception - { + public void testId() throws Exception { NodeManager nodeManager = new FileLockNodeManager(new File(getTemporaryDir()), false); nodeManager.start(); UUID id1 = nodeManager.getUUID(); @@ -43,22 +42,17 @@ public class RealNodeManagerTest extends NodeManagerTest } @Override - public void performWork(NodeManagerAction... actions) throws Exception - { + public void performWork(NodeManagerAction... actions) throws Exception { List processes = new ArrayList(); - for (NodeManagerAction action : actions) - { + for (NodeManagerAction action : actions) { Process p = SpawnedVMSupport.spawnVM(NodeManagerAction.class.getName(), "-Xms512m", "-Xmx512m", new String[0], true, true, action.getWork()); processes.add(p); } - for (Process process : processes) - { + for (Process process : processes) { process.waitFor(); } - for (Process process : processes) - { - if (process.exitValue() == 9) - { + for (Process process : processes) { + if (process.exitValue() == 9) { Assert.fail("failed see output"); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/BridgeFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/BridgeFailoverTest.java index 61caa28169..9021e2642a 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/BridgeFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/BridgeFailoverTest.java @@ -32,12 +32,10 @@ import org.apache.activemq.artemis.core.server.cluster.impl.BridgeImpl; import org.apache.activemq.artemis.tests.integration.cluster.util.MultiServerTestBase; import org.junit.Test; -public class BridgeFailoverTest extends MultiServerTestBase -{ +public class BridgeFailoverTest extends MultiServerTestBase { @Test - public void testSimpleConnectOnMultipleNodes() throws Exception - { + public void testSimpleConnectOnMultipleNodes() throws Exception { BridgeConfiguration bridgeConfiguration = new BridgeConfiguration(); String ORIGINAL_QUEUE = "noCluster.originalQueue"; @@ -56,14 +54,9 @@ public class BridgeFailoverTest extends MultiServerTestBase bridgeConfiguration.setReconnectAttempts(-1); servers[2].getConfiguration().getBridgeConfigurations().add(bridgeConfiguration); - for (ActiveMQServer server : servers) - { - server.getConfiguration().getQueueConfigurations().add(new CoreQueueConfiguration() - .setAddress(ORIGINAL_QUEUE) - .setName(ORIGINAL_QUEUE)); - server.getConfiguration().getQueueConfigurations().add(new CoreQueueConfiguration() - .setAddress(TARGET_QUEUE) - .setName(TARGET_QUEUE)); + for (ActiveMQServer server : servers) { + server.getConfiguration().getQueueConfigurations().add(new CoreQueueConfiguration().setAddress(ORIGINAL_QUEUE).setName(ORIGINAL_QUEUE)); + server.getConfiguration().getQueueConfigurations().add(new CoreQueueConfiguration().setAddress(TARGET_QUEUE).setName(TARGET_QUEUE)); } startServers(); @@ -75,15 +68,13 @@ public class BridgeFailoverTest extends MultiServerTestBase ClientSession session = addClientSession(factory.createSession(false, false)); ClientProducer producer = addClientProducer(session.createProducer(ORIGINAL_QUEUE)); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage msg = session.createMessage(true); msg.putIntProperty("i", i); producer.send(msg); } session.commit(); - ServerLocator locatorConsumer = createLocator(false, 4); ClientSessionFactory factoryConsumer = addSessionFactory(locatorConsumer.createSessionFactory()); ClientSession sessionConsumer = addClientSession(factoryConsumer.createSession(false, false)); @@ -91,8 +82,7 @@ public class BridgeFailoverTest extends MultiServerTestBase sessionConsumer.start(); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage message = consumer.receive(10000); assertNotNull(message); message.acknowledge(); @@ -102,19 +92,16 @@ public class BridgeFailoverTest extends MultiServerTestBase } @Test - public void testFailoverOnBridgeNoRetryOnSameNode() throws Exception - { + public void testFailoverOnBridgeNoRetryOnSameNode() throws Exception { internalTestFailoverOnBridge(0); } @Test - public void testFailoverOnBridgeForeverRetryOnSameNode() throws Exception - { + public void testFailoverOnBridgeForeverRetryOnSameNode() throws Exception { internalTestFailoverOnBridge(-1); } - public void internalTestFailoverOnBridge(int retriesSameNode) throws Exception - { + public void internalTestFailoverOnBridge(int retriesSameNode) throws Exception { BridgeConfiguration bridgeConfiguration = new BridgeConfiguration(); String ORIGINAL_QUEUE = "noCluster.originalQueue"; @@ -135,14 +122,9 @@ public class BridgeFailoverTest extends MultiServerTestBase bridgeConfiguration.setHA(true); servers[2].getConfiguration().getBridgeConfigurations().add(bridgeConfiguration); - for (ActiveMQServer server : servers) - { - server.getConfiguration().getQueueConfigurations().add(new CoreQueueConfiguration() - .setAddress(ORIGINAL_QUEUE) - .setName(ORIGINAL_QUEUE)); - server.getConfiguration().getQueueConfigurations().add(new CoreQueueConfiguration() - .setAddress(TARGET_QUEUE) - .setName(TARGET_QUEUE)); + for (ActiveMQServer server : servers) { + server.getConfiguration().getQueueConfigurations().add(new CoreQueueConfiguration().setAddress(ORIGINAL_QUEUE).setName(ORIGINAL_QUEUE)); + server.getConfiguration().getQueueConfigurations().add(new CoreQueueConfiguration().setAddress(TARGET_QUEUE).setName(TARGET_QUEUE)); } startServers(); @@ -152,8 +134,7 @@ public class BridgeFailoverTest extends MultiServerTestBase long timeout = System.currentTimeMillis() + 5000; - while (bridge.getTargetNodeFromTopology() == null && timeout > System.currentTimeMillis()) - { + while (bridge.getTargetNodeFromTopology() == null && timeout > System.currentTimeMillis()) { Thread.sleep(100); } @@ -166,15 +147,13 @@ public class BridgeFailoverTest extends MultiServerTestBase ClientSession session = addClientSession(factory.createSession(false, false)); ClientProducer producer = addClientProducer(session.createProducer(ORIGINAL_QUEUE)); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage msg = session.createMessage(true); msg.putIntProperty("i", i); producer.send(msg); } session.commit(); - ServerLocator locatorConsumer = createLocator(false, 4); ClientSessionFactory factoryConsumer = addSessionFactory(locatorConsumer.createSessionFactory()); ClientSession sessionConsumer = addClientSession(factoryConsumer.createSession(false, false)); @@ -182,8 +161,7 @@ public class BridgeFailoverTest extends MultiServerTestBase sessionConsumer.start(); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage message = consumer.receive(10000); assertNotNull(message); message.acknowledge(); @@ -195,15 +173,13 @@ public class BridgeFailoverTest extends MultiServerTestBase factoryConsumer.close(); sessionConsumer.close(); - crashAndWaitForFailure(servers[4], locatorConsumer); locatorConsumer.close(); waitForServerToStart(backupServers[4]); - for (int i = 100; i < 200; i++) - { + for (int i = 100; i < 200; i++) { ClientMessage msg = session.createMessage(true); msg.putIntProperty("i", i); producer.send(msg); @@ -211,7 +187,6 @@ public class BridgeFailoverTest extends MultiServerTestBase session.commit(); - locatorConsumer = createLocator(false, 9); factoryConsumer = addSessionFactory(locatorConsumer.createSessionFactory()); sessionConsumer = addClientSession(factoryConsumer.createSession()); @@ -220,8 +195,7 @@ public class BridgeFailoverTest extends MultiServerTestBase sessionConsumer.start(); - for (int i = 0; i < 200; i++) - { + for (int i = 0; i < 200; i++) { ClientMessage message = consumer.receive(10000); assertNotNull(message); message.acknowledge(); @@ -232,8 +206,7 @@ public class BridgeFailoverTest extends MultiServerTestBase } @Test - public void testInitialConnectionNodeAlreadyDown() throws Exception - { + public void testInitialConnectionNodeAlreadyDown() throws Exception { BridgeConfiguration bridgeConfiguration = new BridgeConfiguration(); String ORIGINAL_QUEUE = "noCluster.originalQueue"; @@ -252,14 +225,9 @@ public class BridgeFailoverTest extends MultiServerTestBase bridgeConfiguration.setReconnectAttempts(-1); servers[2].getConfiguration().getBridgeConfigurations().add(bridgeConfiguration); - for (ActiveMQServer server : servers) - { - server.getConfiguration().getQueueConfigurations().add(new CoreQueueConfiguration() - .setAddress(ORIGINAL_QUEUE) - .setName(ORIGINAL_QUEUE)); - server.getConfiguration().getQueueConfigurations().add(new CoreQueueConfiguration() - .setAddress(TARGET_QUEUE) - .setName(TARGET_QUEUE)); + for (ActiveMQServer server : servers) { + server.getConfiguration().getQueueConfigurations().add(new CoreQueueConfiguration().setAddress(ORIGINAL_QUEUE).setName(ORIGINAL_QUEUE)); + server.getConfiguration().getQueueConfigurations().add(new CoreQueueConfiguration().setAddress(TARGET_QUEUE).setName(TARGET_QUEUE)); } startBackups(0, 1, 3, 4); @@ -273,7 +241,6 @@ public class BridgeFailoverTest extends MultiServerTestBase startBackups(2); startServers(2); - // The server where the bridge source is configured at ServerLocator locator = createLocator(false, 2); // connecting to the backup @@ -281,15 +248,13 @@ public class BridgeFailoverTest extends MultiServerTestBase ClientSession session = addClientSession(factory.createSession(false, false)); ClientProducer producer = addClientProducer(session.createProducer(ORIGINAL_QUEUE)); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage msg = session.createMessage(true); msg.putIntProperty("i", i); producer.send(msg); } session.commit(); - ServerLocator locatorConsumer = createLocator(false, 9); ClientSessionFactory factoryConsumer = addSessionFactory(locatorConsumer.createSessionFactory()); ClientSession sessionConsumer = addClientSession(factoryConsumer.createSession(false, false)); @@ -297,8 +262,7 @@ public class BridgeFailoverTest extends MultiServerTestBase sessionConsumer.start(); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage message = consumer.receive(10000); assertNotNull(message); message.acknowledge(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/BridgeReconnectTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/BridgeReconnectTest.java index 097eeef4c6..c74c5fe1df 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/BridgeReconnectTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/BridgeReconnectTest.java @@ -50,8 +50,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -public class BridgeReconnectTest extends BridgeTestBase -{ +public class BridgeReconnectTest extends BridgeTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private static final int NUM_MESSAGES = 100; @@ -85,8 +85,7 @@ public class BridgeReconnectTest extends BridgeTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server0Params = new HashMap(); server1Params = new HashMap(); @@ -100,18 +99,15 @@ public class BridgeReconnectTest extends BridgeTestBase staticConnectors.add(server1tc.getName()); } - protected boolean isNetty() - { + protected boolean isNetty() { return false; } /** * @return */ - private String getConnector() - { - if (isNetty()) - { + private String getConnector() { + if (isNetty()) { return NETTY_CONNECTOR_FACTORY; } return INVM_CONNECTOR_FACTORY; @@ -123,8 +119,7 @@ public class BridgeReconnectTest extends BridgeTestBase * @see https://bugzilla.redhat.com/show_bug.cgi?id=900764 */ @Test - public void testFailoverDeploysBridge() throws Exception - { + public void testFailoverDeploysBridge() throws Exception { NodeManager nodeManager = new InVMNodeManager(false); server0 = createActiveMQServer(0, server0Params, isNetty(), nodeManager); server2 = createBackupActiveMQServer(2, server2Params, isNetty(), 0, nodeManager); @@ -146,16 +141,12 @@ public class BridgeReconnectTest extends BridgeTestBase server0.getConfiguration().setBridgeConfigurations(bridgeConfigs); server2.getConfiguration().setBridgeConfigurations(bridgeConfigs); - CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName); + CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName); List queueConfigs0 = new ArrayList(); queueConfigs0.add(queueConfig0); server1.getConfiguration().setQueueConfigurations(queueConfigs0); - CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration() - .setAddress(forwardAddress) - .setName(queueName); + CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration().setAddress(forwardAddress).setName(queueName); List queueConfigs1 = new ArrayList(); queueConfigs1.add(queueConfig1); server0.getConfiguration().setQueueConfigurations(queueConfigs1); @@ -179,8 +170,7 @@ public class BridgeReconnectTest extends BridgeTestBase // Fail bridge and reconnecting immediately @Test - public void testFailoverAndReconnectImmediately() throws Exception - { + public void testFailoverAndReconnectImmediately() throws Exception { NodeManager nodeManager = new InVMNodeManager(false); server0 = createActiveMQServer(0, server0Params, isNetty(), nodeManager); server2 = createBackupActiveMQServer(2, server2Params, isNetty(), 0, nodeManager); @@ -201,16 +191,12 @@ public class BridgeReconnectTest extends BridgeTestBase bridgeConfigs.add(bridgeConfiguration); server0.getConfiguration().setBridgeConfigurations(bridgeConfigs); - CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName); + CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName); List queueConfigs0 = new ArrayList(); queueConfigs0.add(queueConfig0); server0.getConfiguration().setQueueConfigurations(queueConfigs0); - CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration() - .setAddress(forwardAddress) - .setName(queueName); + CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration().setAddress(forwardAddress).setName(queueName); List queueConfigs1 = new ArrayList(); queueConfigs1.add(queueConfig1); server1.getConfiguration().setQueueConfigurations(queueConfigs1); @@ -244,45 +230,30 @@ public class BridgeReconnectTest extends BridgeTestBase SimpleString propKey = new SimpleString("propkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(true); message.putIntProperty(propKey, i); prod0.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage r1 = cons2.receive(1500); assertNotNull(r1); assertEquals(i, r1.getObjectProperty(propKey)); } closeServers(); - assertNoMoreConnections(); } - private BridgeConfiguration createBridgeConfig() - { - return new BridgeConfiguration() - .setName(bridgeName) - .setQueueName(queueName) - .setForwardingAddress(forwardAddress) - .setRetryInterval(retryInterval) - .setRetryIntervalMultiplier(retryIntervalMultiplier) - .setReconnectAttempts(reconnectAttempts) - .setReconnectAttemptsOnSameNode(0) - .setConfirmationWindowSize(confirmationWindowSize) - .setStaticConnectors(staticConnectors) - .setPassword(CLUSTER_PASSWORD); + private BridgeConfiguration createBridgeConfig() { + return new BridgeConfiguration().setName(bridgeName).setQueueName(queueName).setForwardingAddress(forwardAddress).setRetryInterval(retryInterval).setRetryIntervalMultiplier(retryIntervalMultiplier).setReconnectAttempts(reconnectAttempts).setReconnectAttemptsOnSameNode(0).setConfirmationWindowSize(confirmationWindowSize).setStaticConnectors(staticConnectors).setPassword(CLUSTER_PASSWORD); } // Fail bridge and attempt failover a few times before succeeding @Test - public void testFailoverAndReconnectAfterAFewTries() throws Exception - { + public void testFailoverAndReconnectAfterAFewTries() throws Exception { NodeManager nodeManager = new InVMNodeManager(false); server0 = createActiveMQServer(0, server0Params, isNetty(), nodeManager); @@ -301,16 +272,12 @@ public class BridgeReconnectTest extends BridgeTestBase bridgeConfigs.add(bridgeConfiguration); server0.getConfiguration().setBridgeConfigurations(bridgeConfigs); - CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName); + CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName); List queueConfigs0 = new ArrayList(); queueConfigs0.add(queueConfig0); server0.getConfiguration().setQueueConfigurations(queueConfigs0); - CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration() - .setAddress(forwardAddress) - .setName(queueName); + CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration().setAddress(forwardAddress).setName(queueName); List queueConfigs1 = new ArrayList(); queueConfigs1.add(queueConfig1); server1.getConfiguration().setQueueConfigurations(queueConfigs1); @@ -320,8 +287,7 @@ public class BridgeReconnectTest extends BridgeTestBase // Now we will simulate a failure of the bridge connection between server0 and server1 server0.stop(true); - locator = addServerLocator(ActiveMQClient.createServerLocatorWithHA(server2tc)) - .setReconnectAttempts(100); + locator = addServerLocator(ActiveMQClient.createServerLocatorWithHA(server2tc)).setReconnectAttempts(100); ClientSessionFactory csf0 = addSessionFactory(locator.createSessionFactory(server2tc)); session0 = csf0.createSession(false, true, true); @@ -338,16 +304,14 @@ public class BridgeReconnectTest extends BridgeTestBase SimpleString propKey = new SimpleString("propkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(false); message.putIntProperty(propKey, i); prod0.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage r1 = cons2.receive(1500); assertNotNull(r1); assertEquals(i, r1.getObjectProperty(propKey)); @@ -359,8 +323,7 @@ public class BridgeReconnectTest extends BridgeTestBase // Fail bridge and reconnect same node, no backup specified @Test - public void testReconnectSameNode() throws Exception - { + public void testReconnectSameNode() throws Exception { server0 = createActiveMQServer(0, isNetty(), server0Params); TransportConfiguration server0tc = new TransportConfiguration(getConnector(), server0Params, "server0tc"); @@ -374,16 +337,12 @@ public class BridgeReconnectTest extends BridgeTestBase bridgeConfigs.add(bridgeConfiguration); server0.getConfiguration().setBridgeConfigurations(bridgeConfigs); - CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName); + CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName); List queueConfigs0 = new ArrayList(); queueConfigs0.add(queueConfig0); server0.getConfiguration().setQueueConfigurations(queueConfigs0); - CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration() - .setAddress(forwardAddress) - .setName(queueName); + CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration().setAddress(forwardAddress).setName(queueName); List queueConfigs1 = new ArrayList(); queueConfigs1.add(queueConfig1); server1.getConfiguration().setQueueConfigurations(queueConfigs1); @@ -422,16 +381,14 @@ public class BridgeReconnectTest extends BridgeTestBase SimpleString propKey = new SimpleString("propkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(false); message.putIntProperty(propKey, i); prod0.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage r1 = cons1.receive(1500); assertNotNull(r1); assertEquals(i, r1.getObjectProperty(propKey)); @@ -444,19 +401,16 @@ public class BridgeReconnectTest extends BridgeTestBase // We test that we can pause more than client failure check period (to prompt the pinger to failing) // before reconnecting @Test - public void testShutdownServerCleanlyAndReconnectSameNodeWithSleep() throws Exception - { + public void testShutdownServerCleanlyAndReconnectSameNodeWithSleep() throws Exception { testShutdownServerCleanlyAndReconnectSameNode(true); } @Test - public void testShutdownServerCleanlyAndReconnectSameNode() throws Exception - { + public void testShutdownServerCleanlyAndReconnectSameNode() throws Exception { testShutdownServerCleanlyAndReconnectSameNode(false); } - private void testShutdownServerCleanlyAndReconnectSameNode(final boolean sleep) throws Exception - { + private void testShutdownServerCleanlyAndReconnectSameNode(final boolean sleep) throws Exception { server0 = createActiveMQServer(0, isNetty(), server0Params); TransportConfiguration server0tc = new TransportConfiguration(getConnector(), server0Params, "server0tc"); @@ -465,33 +419,18 @@ public class BridgeReconnectTest extends BridgeTestBase reconnectAttempts = -1; final long clientFailureCheckPeriod = 1000; - BridgeConfiguration bridgeConfiguration = new BridgeConfiguration() - .setName(bridgeName) - .setQueueName(queueName) - .setForwardingAddress(forwardAddress) - .setClientFailureCheckPeriod(clientFailureCheckPeriod) - .setRetryInterval(retryInterval) - .setRetryIntervalMultiplier(retryIntervalMultiplier) - .setReconnectAttempts(reconnectAttempts) - .setReconnectAttemptsOnSameNode(0) - .setConfirmationWindowSize(confirmationWindowSize) - .setStaticConnectors(staticConnectors) - .setPassword(CLUSTER_PASSWORD); + BridgeConfiguration bridgeConfiguration = new BridgeConfiguration().setName(bridgeName).setQueueName(queueName).setForwardingAddress(forwardAddress).setClientFailureCheckPeriod(clientFailureCheckPeriod).setRetryInterval(retryInterval).setRetryIntervalMultiplier(retryIntervalMultiplier).setReconnectAttempts(reconnectAttempts).setReconnectAttemptsOnSameNode(0).setConfirmationWindowSize(confirmationWindowSize).setStaticConnectors(staticConnectors).setPassword(CLUSTER_PASSWORD); List bridgeConfigs = new ArrayList(); bridgeConfigs.add(bridgeConfiguration); server0.getConfiguration().setBridgeConfigurations(bridgeConfigs); - CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName); + CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName); List queueConfigs0 = new ArrayList(); queueConfigs0.add(queueConfig0); server0.getConfiguration().setQueueConfigurations(queueConfigs0); - CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration() - .setAddress(forwardAddress) - .setName(queueName); + CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration().setAddress(forwardAddress).setName(queueName); List queueConfigs1 = new ArrayList(); queueConfigs1.add(queueConfig1); server1.getConfiguration().setQueueConfigurations(queueConfigs1); @@ -509,8 +448,7 @@ public class BridgeReconnectTest extends BridgeTestBase BridgeReconnectTest.log.info("stopping server1"); server1.stop(); - if (sleep) - { + if (sleep) { Thread.sleep(2 * clientFailureCheckPeriod); } @@ -529,8 +467,7 @@ public class BridgeReconnectTest extends BridgeTestBase SimpleString propKey = new SimpleString("propkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(false); message.putIntProperty(propKey, i); @@ -539,8 +476,7 @@ public class BridgeReconnectTest extends BridgeTestBase BridgeReconnectTest.log.info("sent messages"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage r1 = cons1.receive(30000); assertNotNull("received expected msg", r1); assertEquals("property value matches", i, r1.getObjectProperty(propKey)); @@ -555,8 +491,7 @@ public class BridgeReconnectTest extends BridgeTestBase /** * @throws Exception */ - private void closeServers() throws Exception - { + private void closeServers() throws Exception { if (session0 != null) session0.close(); if (session1 != null) @@ -564,8 +499,7 @@ public class BridgeReconnectTest extends BridgeTestBase if (session2 != null) session2.close(); - if (locator != null) - { + if (locator != null) { locator.close(); } @@ -575,8 +509,7 @@ public class BridgeReconnectTest extends BridgeTestBase server2.stop(); } - private void assertNoMoreConnections() - { + private void assertNoMoreConnections() { assertEquals(0, server0.getRemotingService().getConnections().size()); assertEquals(0, server1.getRemotingService().getConnections().size()); if (server2 != null) @@ -584,8 +517,7 @@ public class BridgeReconnectTest extends BridgeTestBase } @Test - public void testFailoverThenFailAgainAndReconnect() throws Exception - { + public void testFailoverThenFailAgainAndReconnect() throws Exception { server0 = createActiveMQServer(0, isNetty(), server0Params); TransportConfiguration server0tc = new TransportConfiguration(getConnector(), server0Params, "server0tc"); @@ -598,16 +530,12 @@ public class BridgeReconnectTest extends BridgeTestBase bridgeConfigs.add(bridgeConfiguration); server0.getConfiguration().setBridgeConfigurations(bridgeConfigs); - CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName); + CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName); List queueConfigs0 = new ArrayList(); queueConfigs0.add(queueConfig0); server0.getConfiguration().setQueueConfigurations(queueConfigs0); - CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration() - .setAddress(forwardAddress) - .setName(queueName); + CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration().setAddress(forwardAddress).setName(queueName); List queueConfigs1 = new ArrayList(); queueConfigs1.add(queueConfig1); server1.getConfiguration().setQueueConfigurations(queueConfigs1); @@ -637,8 +565,7 @@ public class BridgeReconnectTest extends BridgeTestBase SimpleString propKey = new SimpleString("propkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(false); message.putIntProperty(propKey, i); @@ -647,52 +574,43 @@ public class BridgeReconnectTest extends BridgeTestBase int outOfOrder = -1; int supposed = -1; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage r1 = cons1.receive(1500); assertNotNull(r1); - if (outOfOrder == -1 && i != r1.getIntProperty(propKey).intValue()) - { + if (outOfOrder == -1 && i != r1.getIntProperty(propKey).intValue()) { outOfOrder = r1.getIntProperty(propKey).intValue(); supposed = i; } } - if (outOfOrder != -1) - { + if (outOfOrder != -1) { fail("Message " + outOfOrder + " was received out of order, it was supposed to be " + supposed); } log.info("=========== second failure, sending message"); - // Fail again - should reconnect forwardingConnection = ((BridgeImpl) bridge).getForwardingConnection(); InVMConnector.failOnCreateConnection = true; InVMConnector.numberOfFailures = reconnectAttempts - 1; forwardingConnection.fail(new ActiveMQException(ActiveMQExceptionType.UNBLOCKED)); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(false); message.putIntProperty(propKey, i); prod0.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage r1 = cons1.receive(1500); assertNotNull("Didn't receive message", r1); - if (outOfOrder == -1 && i != r1.getIntProperty(propKey).intValue()) - { + if (outOfOrder == -1 && i != r1.getIntProperty(propKey).intValue()) { outOfOrder = r1.getIntProperty(propKey).intValue(); supposed = i; } } - - if (outOfOrder != -1) - { + if (outOfOrder != -1) { fail("Message " + outOfOrder + " was received out of order, it was supposed to be " + supposed); } closeServers(); @@ -701,8 +619,7 @@ public class BridgeReconnectTest extends BridgeTestBase } @Test - public void testDeliveringCountOnBridgeConnectionFailure() throws Exception - { + public void testDeliveringCountOnBridgeConnectionFailure() throws Exception { server0 = createActiveMQServer(0, isNetty(), server0Params); TransportConfiguration server0tc = new TransportConfiguration(getConnector(), server0Params, "server0tc"); @@ -715,16 +632,12 @@ public class BridgeReconnectTest extends BridgeTestBase bridgeConfigs.add(bridgeConfiguration); server0.getConfiguration().setBridgeConfigurations(bridgeConfigs); - CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName); + CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName); List queueConfigs0 = new ArrayList(); queueConfigs0.add(queueConfig0); server0.getConfiguration().setQueueConfigurations(queueConfigs0); - CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration() - .setAddress(forwardAddress) - .setName(queueName); + CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration().setAddress(forwardAddress).setName(queueName); List queueConfigs1 = new ArrayList(); queueConfigs1.add(queueConfig1); server1.getConfiguration().setQueueConfigurations(queueConfigs1); @@ -756,52 +669,44 @@ public class BridgeReconnectTest extends BridgeTestBase System.out.println("DeliveringCount: " + queue.getDeliveringCount()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(false); message.putIntProperty(propKey, i); prod0.send(message); - if (i == 50) - { + if (i == 50) { forwardingConnection.fail(new ActiveMQException(ActiveMQExceptionType.UNBLOCKED)); } } System.out.println("Check.. DeliveringCount: " + queue.getDeliveringCount()); - assertEquals("Delivering count of a source queue should be zero on connection failure", - 0, queue.getDeliveringCount()); + assertEquals("Delivering count of a source queue should be zero on connection failure", 0, queue.getDeliveringCount()); closeServers(); assertNoMoreConnections(); } - private void startServers() throws Exception - { + private void startServers() throws Exception { if (server2 != null) server2.start(); server1.start(); server0.start(); } - private RemotingConnection getForwardingConnection(final Bridge bridge) throws Exception - { + private RemotingConnection getForwardingConnection(final Bridge bridge) throws Exception { long start = System.currentTimeMillis(); - do - { + do { RemotingConnection forwardingConnection = ((BridgeImpl) bridge).getForwardingConnection(); - if (forwardingConnection != null) - { + if (forwardingConnection != null) { return forwardingConnection; } Thread.sleep(10); - } - while (System.currentTimeMillis() - start < 50000); + } while (System.currentTimeMillis() - start < 50000); throw new IllegalStateException("Failed to get forwarding connection"); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/BridgeStartTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/BridgeStartTest.java index 700ac525b1..bfc134dcd6 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/BridgeStartTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/BridgeStartTest.java @@ -45,20 +45,14 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) -public class BridgeStartTest extends ActiveMQTestBase -{ +public class BridgeStartTest extends ActiveMQTestBase { @Parameterized.Parameters(name = "isNetty={0}") - public static Collection getParameters() - { - return Arrays.asList(new Object[][]{ - {true}, - {false} - }); + public static Collection getParameters() { + return Arrays.asList(new Object[][]{{true}, {false}}); } - public BridgeStartTest(boolean netty) - { + public BridgeStartTest(boolean netty) { this.netty = netty; } @@ -66,39 +60,32 @@ public class BridgeStartTest extends ActiveMQTestBase private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; - protected boolean isNetty() - { + protected boolean isNetty() { return netty; } - private String getConnector() - { - if (isNetty()) - { + private String getConnector() { + if (isNetty()) { return NETTY_CONNECTOR_FACTORY; } return INVM_CONNECTOR_FACTORY; } @Test - public void testStartStop() throws Exception - { + public void testStartStop() throws Exception { Map server0Params = new HashMap(); ActiveMQServer server0 = createClusteredServerWithParams(isNetty(), 0, true, server0Params); Map server1Params = new HashMap(); - if (isNetty()) - { + if (isNetty()) { server1Params.put("port", org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.DEFAULT_PORT + 1); } - else - { + else { server1Params.put(TransportConstants.SERVER_ID_PROP_NAME, 1); } ActiveMQServer server1 = createClusteredServerWithParams(isNetty(), 1, true, server1Params); ServerLocator locator = null; - try - { + try { final String testAddress = "testAddress"; final String queueName0 = "queue0"; final String forwardAddress = "forwardAddress"; @@ -116,30 +103,18 @@ public class BridgeStartTest extends ActiveMQTestBase final String bridgeName = "bridge1"; - BridgeConfiguration bridgeConfiguration = new BridgeConfiguration() - .setName(bridgeName) - .setQueueName(queueName0) - .setForwardingAddress(forwardAddress) - .setRetryInterval(1000) - .setReconnectAttempts(0) - .setReconnectAttemptsOnSameNode(0) - .setConfirmationWindowSize(1024) - .setStaticConnectors(staticConnectors); + BridgeConfiguration bridgeConfiguration = new BridgeConfiguration().setName(bridgeName).setQueueName(queueName0).setForwardingAddress(forwardAddress).setRetryInterval(1000).setReconnectAttempts(0).setReconnectAttemptsOnSameNode(0).setConfirmationWindowSize(1024).setStaticConnectors(staticConnectors); List bridgeConfigs = new ArrayList(); bridgeConfigs.add(bridgeConfiguration); server0.getConfiguration().setBridgeConfigurations(bridgeConfigs); - CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName0); + CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName0); List queueConfigs0 = new ArrayList(); queueConfigs0.add(queueConfig0); server0.getConfiguration().setQueueConfigurations(queueConfigs0); - CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration() - .setAddress(forwardAddress) - .setName(queueName1); + CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration().setAddress(forwardAddress).setName(queueName1); List queueConfigs1 = new ArrayList(); queueConfigs1.add(queueConfig1); server1.getConfiguration().setQueueConfigurations(queueConfigs1); @@ -169,8 +144,7 @@ public class BridgeStartTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("testkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(false); message.putIntProperty(propKey, i); @@ -178,8 +152,7 @@ public class BridgeStartTest extends ActiveMQTestBase producer0.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(200); Assert.assertNotNull(message); @@ -197,8 +170,7 @@ public class BridgeStartTest extends ActiveMQTestBase bridge.flushExecutor(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(false); message.putIntProperty(propKey, i); @@ -210,8 +182,7 @@ public class BridgeStartTest extends ActiveMQTestBase bridge.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(1000); Assert.assertNotNull(message); @@ -231,10 +202,8 @@ public class BridgeStartTest extends ActiveMQTestBase sf1.close(); } - finally - { - if (locator != null) - { + finally { + if (locator != null) { locator.close(); } @@ -246,8 +215,7 @@ public class BridgeStartTest extends ActiveMQTestBase } @Test - public void testTargetServerUpAndDown() throws Exception - { + public void testTargetServerUpAndDown() throws Exception { // This test needs to use real files, since it requires duplicate detection, since when the target server is // shutdown, messages will get resent when it is started, so the dup id cache needs // to be persisted @@ -256,12 +224,10 @@ public class BridgeStartTest extends ActiveMQTestBase ActiveMQServer server0 = createClusteredServerWithParams(isNetty(), 0, true, server0Params); Map server1Params = new HashMap(); - if (isNetty()) - { + if (isNetty()) { server1Params.put("port", org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.DEFAULT_PORT + 1); } - else - { + else { server1Params.put(TransportConstants.SERVER_ID_PROP_NAME, 1); } ActiveMQServer server1 = createClusteredServerWithParams(isNetty(), 1, true, server1Params); @@ -283,36 +249,23 @@ public class BridgeStartTest extends ActiveMQTestBase final String bridgeName = "bridge1"; - BridgeConfiguration bridgeConfiguration = new BridgeConfiguration() - .setName(bridgeName) - .setQueueName(queueName0) - .setForwardingAddress(forwardAddress) - .setRetryInterval(500) - .setReconnectAttempts(-1) - .setReconnectAttemptsOnSameNode(0) - .setConfirmationWindowSize(1024) - .setStaticConnectors(staticConnectors); + BridgeConfiguration bridgeConfiguration = new BridgeConfiguration().setName(bridgeName).setQueueName(queueName0).setForwardingAddress(forwardAddress).setRetryInterval(500).setReconnectAttempts(-1).setReconnectAttemptsOnSameNode(0).setConfirmationWindowSize(1024).setStaticConnectors(staticConnectors); List bridgeConfigs = new ArrayList(); bridgeConfigs.add(bridgeConfiguration); server0.getConfiguration().setBridgeConfigurations(bridgeConfigs); - CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName0); + CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName0); List queueConfigs0 = new ArrayList(); queueConfigs0.add(queueConfig0); server0.getConfiguration().setQueueConfigurations(queueConfigs0); - CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration() - .setAddress(forwardAddress) - .setName(queueName1); + CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration().setAddress(forwardAddress).setName(queueName1); List queueConfigs1 = new ArrayList(); queueConfigs1.add(queueConfig1); server1.getConfiguration().setQueueConfigurations(queueConfigs1); ServerLocator locator = null; - try - { + try { // Don't start server 1 yet server0.start(); @@ -321,7 +274,6 @@ public class BridgeStartTest extends ActiveMQTestBase locator = ActiveMQClient.createServerLocatorWithoutHA(server0tc, server1tc); ClientSessionFactory sf0 = locator.createSessionFactory(server0tc); - ClientSession session0 = sf0.createSession(false, true, true); ClientProducer producer0 = session0.createProducer(new SimpleString(testAddress)); @@ -330,8 +282,7 @@ public class BridgeStartTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("testkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(false); message.putIntProperty(propKey, i); @@ -353,8 +304,7 @@ public class BridgeStartTest extends ActiveMQTestBase session1.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(1000); Assert.assertNotNull(message); @@ -366,8 +316,7 @@ public class BridgeStartTest extends ActiveMQTestBase Assert.assertNull(consumer1.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(false); message.putIntProperty(propKey, i); @@ -375,8 +324,7 @@ public class BridgeStartTest extends ActiveMQTestBase producer0.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(1000); Assert.assertNotNull(message); @@ -398,8 +346,7 @@ public class BridgeStartTest extends ActiveMQTestBase BridgeStartTest.log.info("stopped server 1"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(false); message.putIntProperty(propKey, i); @@ -424,8 +371,7 @@ public class BridgeStartTest extends ActiveMQTestBase BridgeStartTest.log.info("started session"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(1000); Assert.assertNotNull(message); @@ -447,10 +393,8 @@ public class BridgeStartTest extends ActiveMQTestBase locator.close(); } - finally - { - if (locator != null) - { + finally { + if (locator != null) { locator.close(); } @@ -461,18 +405,15 @@ public class BridgeStartTest extends ActiveMQTestBase } @Test - public void testTargetServerNotAvailableNoReconnectTries() throws Exception - { + public void testTargetServerNotAvailableNoReconnectTries() throws Exception { Map server0Params = new HashMap(); ActiveMQServer server0 = createClusteredServerWithParams(isNetty(), 0, false, server0Params); Map server1Params = new HashMap(); - if (isNetty()) - { + if (isNetty()) { server1Params.put("port", org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.DEFAULT_PORT + 1); } - else - { + else { server1Params.put(TransportConstants.SERVER_ID_PROP_NAME, 1); } ActiveMQServer server1 = createClusteredServerWithParams(isNetty(), 1, false, server1Params); @@ -482,8 +423,7 @@ public class BridgeStartTest extends ActiveMQTestBase final String forwardAddress = "forwardAddress"; final String queueName1 = "queue1"; ServerLocator locator = null; - try - { + try { Map connectors = new HashMap(); TransportConfiguration server0tc = new TransportConfiguration(getConnector(), server0Params); TransportConfiguration server1tc = new TransportConfiguration(getConnector(), server1Params); @@ -496,31 +436,18 @@ public class BridgeStartTest extends ActiveMQTestBase final String bridgeName = "bridge1"; - BridgeConfiguration bridgeConfiguration = new BridgeConfiguration() - .setName(bridgeName) - .setQueueName(queueName0) - .setForwardingAddress(forwardAddress) - .setRetryInterval(1000) - .setReconnectAttempts(0) - .setReconnectAttemptsOnSameNode(0) - .setUseDuplicateDetection(false) - .setConfirmationWindowSize(1024) - .setStaticConnectors(staticConnectors); + BridgeConfiguration bridgeConfiguration = new BridgeConfiguration().setName(bridgeName).setQueueName(queueName0).setForwardingAddress(forwardAddress).setRetryInterval(1000).setReconnectAttempts(0).setReconnectAttemptsOnSameNode(0).setUseDuplicateDetection(false).setConfirmationWindowSize(1024).setStaticConnectors(staticConnectors); List bridgeConfigs = new ArrayList(); bridgeConfigs.add(bridgeConfiguration); server0.getConfiguration().setBridgeConfigurations(bridgeConfigs); - CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName0); + CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName0); List queueConfigs0 = new ArrayList(); queueConfigs0.add(queueConfig0); server0.getConfiguration().setQueueConfigurations(queueConfigs0); - CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration() - .setAddress(forwardAddress) - .setName(queueName1); + CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration().setAddress(forwardAddress).setName(queueName1); List queueConfigs1 = new ArrayList(); queueConfigs1.add(queueConfig1); server1.getConfiguration().setQueueConfigurations(queueConfigs1); @@ -533,7 +460,6 @@ public class BridgeStartTest extends ActiveMQTestBase locator = ActiveMQClient.createServerLocatorWithoutHA(server0tc, server1tc); ClientSessionFactory sf0 = locator.createSessionFactory(server0tc); - ClientSession session0 = sf0.createSession(false, true, true); ClientProducer producer0 = session0.createProducer(new SimpleString(testAddress)); @@ -542,8 +468,7 @@ public class BridgeStartTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("testkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(false); message.putIntProperty(propKey, i); @@ -578,8 +503,7 @@ public class BridgeStartTest extends ActiveMQTestBase // Messages should now be received - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(3000); Assert.assertNotNull(message); @@ -600,10 +524,8 @@ public class BridgeStartTest extends ActiveMQTestBase sf0.close(); } - finally - { - if (locator != null) - { + finally { + if (locator != null) { locator.close(); } @@ -615,18 +537,15 @@ public class BridgeStartTest extends ActiveMQTestBase } @Test - public void testManualStopStart() throws Exception - { + public void testManualStopStart() throws Exception { Map server0Params = new HashMap(); ActiveMQServer server0 = createClusteredServerWithParams(isNetty(), 0, false, server0Params); Map server1Params = new HashMap(); - if (isNetty()) - { + if (isNetty()) { server1Params.put("port", org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.DEFAULT_PORT + 1); } - else - { + else { server1Params.put(TransportConstants.SERVER_ID_PROP_NAME, 1); } ActiveMQServer server1 = createClusteredServerWithParams(isNetty(), 1, false, server1Params); @@ -636,8 +555,7 @@ public class BridgeStartTest extends ActiveMQTestBase final String forwardAddress = "forwardAddress"; final String queueName1 = "queue1"; ServerLocator locator = null; - try - { + try { Map connectors = new HashMap(); TransportConfiguration server0tc = new TransportConfiguration(getConnector(), server0Params); TransportConfiguration server1tc = new TransportConfiguration(getConnector(), server1Params); @@ -650,30 +568,18 @@ public class BridgeStartTest extends ActiveMQTestBase final String bridgeName = "bridge1"; - BridgeConfiguration bridgeConfiguration = new BridgeConfiguration() - .setName(bridgeName) - .setQueueName(queueName0) - .setForwardingAddress(forwardAddress) - .setRetryInterval(1000) - .setReconnectAttempts(1) - .setReconnectAttemptsOnSameNode(0) - .setConfirmationWindowSize(1024) - .setStaticConnectors(staticConnectors); + BridgeConfiguration bridgeConfiguration = new BridgeConfiguration().setName(bridgeName).setQueueName(queueName0).setForwardingAddress(forwardAddress).setRetryInterval(1000).setReconnectAttempts(1).setReconnectAttemptsOnSameNode(0).setConfirmationWindowSize(1024).setStaticConnectors(staticConnectors); List bridgeConfigs = new ArrayList(); bridgeConfigs.add(bridgeConfiguration); server0.getConfiguration().setBridgeConfigurations(bridgeConfigs); - CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName0); + CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName0); List queueConfigs0 = new ArrayList(); queueConfigs0.add(queueConfig0); server0.getConfiguration().setQueueConfigurations(queueConfigs0); - CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration() - .setAddress(forwardAddress) - .setName(queueName1); + CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration().setAddress(forwardAddress).setName(queueName1); List queueConfigs1 = new ArrayList(); queueConfigs1.add(queueConfig1); server1.getConfiguration().setQueueConfigurations(queueConfigs1); @@ -687,7 +593,6 @@ public class BridgeStartTest extends ActiveMQTestBase locator = ActiveMQClient.createServerLocatorWithoutHA(server0tc, server1tc); ClientSessionFactory sf0 = locator.createSessionFactory(server0tc); - ClientSession session0 = sf0.createSession(false, true, true); ClientProducer producer0 = session0.createProducer(new SimpleString(testAddress)); @@ -696,8 +601,7 @@ public class BridgeStartTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("testkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(false); message.putIntProperty(propKey, i); @@ -712,8 +616,7 @@ public class BridgeStartTest extends ActiveMQTestBase session1.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(1000); Assert.assertNotNull(message); @@ -735,8 +638,7 @@ public class BridgeStartTest extends ActiveMQTestBase bridge.flushExecutor(); - for (int i = numMessages; i < numMessages * 2; i++) - { + for (int i = numMessages; i < numMessages * 2; i++) { ClientMessage message = session0.createMessage(false); message.putIntProperty(propKey, i); @@ -753,8 +655,7 @@ public class BridgeStartTest extends ActiveMQTestBase // The previous messages will get resent, but with duplicate detection they will be rejected // at the target - for (int i = numMessages; i < numMessages * 2; i++) - { + for (int i = numMessages; i < numMessages * 2; i++) { ClientMessage message = consumer1.receive(1000); Assert.assertNotNull(message); @@ -770,8 +671,7 @@ public class BridgeStartTest extends ActiveMQTestBase bridge.flushExecutor(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(false); message.putIntProperty(propKey, i); @@ -783,8 +683,7 @@ public class BridgeStartTest extends ActiveMQTestBase bridge.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(1000); Assert.assertNotNull(message); @@ -804,10 +703,8 @@ public class BridgeStartTest extends ActiveMQTestBase sf0.close(); } - finally - { - if (locator != null) - { + finally { + if (locator != null) { locator.close(); } server0.stop(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/BridgeTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/BridgeTest.java index 470ae07b3d..f7592be4be 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/BridgeTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/BridgeTest.java @@ -80,8 +80,7 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) -public class BridgeTest extends ActiveMQTestBase -{ +public class BridgeTest extends ActiveMQTestBase { private ActiveMQServer server0; private ActiveMQServer server1; @@ -89,74 +88,56 @@ public class BridgeTest extends ActiveMQTestBase private final boolean netty; - @Parameterized.Parameters(name = "isNetty={0}") - public static Collection getParameters() - { - return Arrays.asList(new Object[][]{ - {true}, - {false} - }); + public static Collection getParameters() { + return Arrays.asList(new Object[][]{{true}, {false}}); } - public BridgeTest(boolean isNetty) - { + public BridgeTest(boolean isNetty) { this.netty = isNetty; } - protected boolean isNetty() - { + protected boolean isNetty() { return netty; } - @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { StopInterceptor.reset(); super.setUp(); } - - private String getConnector() - { - if (isNetty()) - { + private String getConnector() { + if (isNetty()) { return NETTY_CONNECTOR_FACTORY; } - else - { + else { return INVM_CONNECTOR_FACTORY; } } @Test - public void testSimpleBridge() throws Exception - { + public void testSimpleBridge() throws Exception { internaltestSimpleBridge(false, false); } @Test - public void testSimpleBridgeFiles() throws Exception - { + public void testSimpleBridgeFiles() throws Exception { internaltestSimpleBridge(false, true); } @Test - public void testSimpleBridgeLargeMessageNullPersistence() throws Exception - { + public void testSimpleBridgeLargeMessageNullPersistence() throws Exception { internaltestSimpleBridge(true, false); } @Test - public void testSimpleBridgeLargeMessageFiles() throws Exception - { + public void testSimpleBridgeLargeMessageFiles() throws Exception { internaltestSimpleBridge(true, true); } - public void internaltestSimpleBridge(final boolean largeMessage, final boolean useFiles) throws Exception - { + public void internaltestSimpleBridge(final boolean largeMessage, final boolean useFiles) throws Exception { Map server0Params = new HashMap(); server0 = createClusteredServerWithParams(isNetty(), 0, useFiles, server0Params); @@ -184,30 +165,18 @@ public class BridgeTest extends ActiveMQTestBase ArrayList connectorConfig = new ArrayList(); connectorConfig.add(server1tc.getName()); - BridgeConfiguration bridgeConfiguration = new BridgeConfiguration() - .setName("bridge1") - .setQueueName(queueName0) - .setForwardingAddress(forwardAddress) - .setRetryInterval(1000) - .setReconnectAttemptsOnSameNode(-1) - .setUseDuplicateDetection(false) - .setConfirmationWindowSize(numMessages * messageSize / 2) - .setStaticConnectors(connectorConfig); + BridgeConfiguration bridgeConfiguration = new BridgeConfiguration().setName("bridge1").setQueueName(queueName0).setForwardingAddress(forwardAddress).setRetryInterval(1000).setReconnectAttemptsOnSameNode(-1).setUseDuplicateDetection(false).setConfirmationWindowSize(numMessages * messageSize / 2).setStaticConnectors(connectorConfig); List bridgeConfigs = new ArrayList(); bridgeConfigs.add(bridgeConfiguration); server0.getConfiguration().setBridgeConfigurations(bridgeConfigs); - CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName0); + CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName0); List queueConfigs0 = new ArrayList(); queueConfigs0.add(queueConfig0); server0.getConfiguration().setQueueConfigurations(queueConfigs0); - CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration() - .setAddress(forwardAddress) - .setName(queueName1); + CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration().setAddress(forwardAddress).setName(queueName1); List queueConfigs1 = new ArrayList(); queueConfigs1.add(queueConfig1); server1.getConfiguration().setQueueConfigurations(queueConfigs1); @@ -233,12 +202,10 @@ public class BridgeTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("testkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(true); - if (largeMessage) - { + if (largeMessage) { message.setBodyInputStream(ActiveMQTestBase.createFakeLargeStream(10 * 1024)); } @@ -249,16 +216,14 @@ public class BridgeTest extends ActiveMQTestBase producer0.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(5000); Assert.assertNotNull(message); Assert.assertEquals(i, message.getObjectProperty(propKey)); - if (largeMessage) - { + if (largeMessage) { readLargeMessages(message, 10); } @@ -276,22 +241,18 @@ public class BridgeTest extends ActiveMQTestBase sf1.close(); closeFields(); - if (server0.getConfiguration().isPersistenceEnabled()) - { + if (server0.getConfiguration().isPersistenceEnabled()) { assertEquals(0, loadQueues(server0).size()); } } - @Test - public void testLostMessageSimpleMessage() throws Exception - { + public void testLostMessageSimpleMessage() throws Exception { internalTestMessageLoss(false); } @Test - public void testLostMessageLargeMessage() throws Exception - { + public void testLostMessageLargeMessage() throws Exception { internalTestMessageLoss(true); } @@ -300,30 +261,25 @@ public class BridgeTest extends ActiveMQTestBase * What will cause the bridge to fail with a timeout * The bridge should still recover the failure and reconnect on that case */ - public void internalTestMessageLoss(final boolean largeMessage) throws Exception - { - class MyInterceptor implements Interceptor - { + public void internalTestMessageLoss(final boolean largeMessage) throws Exception { + class MyInterceptor implements Interceptor { + public boolean ignoreSends = true; public CountDownLatch latch; - MyInterceptor(int numberOfIgnores) - { + MyInterceptor(int numberOfIgnores) { latch = new CountDownLatch(numberOfIgnores); } - public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException - { + public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException { if (ignoreSends && packet instanceof SessionSendMessage || ignoreSends && packet instanceof SessionSendLargeMessage || - ignoreSends && packet instanceof SessionSendContinuationMessage && !((SessionSendContinuationMessage) packet).isContinues()) - { + ignoreSends && packet instanceof SessionSendContinuationMessage && !((SessionSendContinuationMessage) packet).isContinues()) { IntegrationTestLogger.LOGGER.info("IGNORED: " + packet); latch.countDown(); return false; } - else - { + else { IntegrationTestLogger.LOGGER.info(packet); return true; } @@ -358,32 +314,18 @@ public class BridgeTest extends ActiveMQTestBase ArrayList connectorConfig = new ArrayList(); connectorConfig.add(server1tc.getName()); - BridgeConfiguration bridgeConfiguration = new BridgeConfiguration() - .setName("bridge1") - .setQueueName(queueName0) - .setForwardingAddress(forwardAddress) - .setRetryInterval(100) - .setReconnectAttempts(-1) - .setReconnectAttemptsOnSameNode(-1) - .setUseDuplicateDetection(false) - .setConfirmationWindowSize(numMessages * messageSize / 2) - .setStaticConnectors(connectorConfig) - .setCallTimeout(500); + BridgeConfiguration bridgeConfiguration = new BridgeConfiguration().setName("bridge1").setQueueName(queueName0).setForwardingAddress(forwardAddress).setRetryInterval(100).setReconnectAttempts(-1).setReconnectAttemptsOnSameNode(-1).setUseDuplicateDetection(false).setConfirmationWindowSize(numMessages * messageSize / 2).setStaticConnectors(connectorConfig).setCallTimeout(500); List bridgeConfigs = new ArrayList(); bridgeConfigs.add(bridgeConfiguration); server0.getConfiguration().setBridgeConfigurations(bridgeConfigs); - CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName0); + CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName0); List queueConfigs0 = new ArrayList(); queueConfigs0.add(queueConfig0); server0.getConfiguration().setQueueConfigurations(queueConfigs0); - CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration() - .setAddress(forwardAddress) - .setName(queueName1); + CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration().setAddress(forwardAddress).setName(queueName1); List queueConfigs1 = new ArrayList(); queueConfigs1.add(queueConfig1); server1.getConfiguration().setQueueConfigurations(queueConfigs1); @@ -412,12 +354,10 @@ public class BridgeTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("testkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(true); - if (largeMessage) - { + if (largeMessage) { message.setBodyInputStream(ActiveMQTestBase.createFakeLargeStream(10 * 1024)); } @@ -433,16 +373,14 @@ public class BridgeTest extends ActiveMQTestBase server1.getRemotingService().removeIncomingInterceptor(myInterceptor); IntegrationTestLogger.LOGGER.info("No longer ignoring packets."); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(30000); Assert.assertNotNull(message); Assert.assertEquals(i, message.getObjectProperty(propKey)); - if (largeMessage) - { + if (largeMessage) { readLargeMessages(message, 10); } @@ -465,14 +403,11 @@ public class BridgeTest extends ActiveMQTestBase /** * @param server1Params */ - private void addTargetParameters(final Map server1Params) - { - if (isNetty()) - { + private void addTargetParameters(final Map server1Params) { + if (isNetty()) { server1Params.put("port", org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.DEFAULT_PORT + 1); } - else - { + else { server1Params.put(TransportConstants.SERVER_ID_PROP_NAME, 1); } } @@ -480,42 +415,35 @@ public class BridgeTest extends ActiveMQTestBase /** * @param message */ - private void readLargeMessages(final ClientMessage message, int kiloBlocks) - { + private void readLargeMessages(final ClientMessage message, int kiloBlocks) { byte[] byteRead = new byte[1024]; - for (int j = 0; j < kiloBlocks; j++) - { + for (int j = 0; j < kiloBlocks; j++) { message.getBodyBuffer().readBytes(byteRead); } } @Test - public void testWithFilter() throws Exception - { + public void testWithFilter() throws Exception { internalTestWithFilter(false, false); } @Test - public void testWithFilterFiles() throws Exception - { + public void testWithFilterFiles() throws Exception { internalTestWithFilter(false, true); } @Test - public void testWithFilterLargeMessages() throws Exception - { + public void testWithFilterLargeMessages() throws Exception { internalTestWithFilter(true, false); } @Test - public void testWithFilterLargeMessagesFiles() throws Exception - { + public void testWithFilterLargeMessagesFiles() throws Exception { internalTestWithFilter(true, true); } - public void internalTestWithFilter(final boolean largeMessage, final boolean useFiles) throws Exception - { + public void internalTestWithFilter(final boolean largeMessage, final boolean useFiles) throws Exception { final int numMessages = 10; @@ -542,31 +470,18 @@ public class BridgeTest extends ActiveMQTestBase ArrayList staticConnectors = new ArrayList(); staticConnectors.add(server1tc.getName()); - BridgeConfiguration bridgeConfiguration = new BridgeConfiguration() - .setName("bridge1") - .setQueueName(queueName0) - .setForwardingAddress(forwardAddress) - .setFilterString(filterString) - .setRetryInterval(1000) - .setReconnectAttemptsOnSameNode(-1) - .setUseDuplicateDetection(false) - .setConfirmationWindowSize(0) - .setStaticConnectors(staticConnectors); + BridgeConfiguration bridgeConfiguration = new BridgeConfiguration().setName("bridge1").setQueueName(queueName0).setForwardingAddress(forwardAddress).setFilterString(filterString).setRetryInterval(1000).setReconnectAttemptsOnSameNode(-1).setUseDuplicateDetection(false).setConfirmationWindowSize(0).setStaticConnectors(staticConnectors); List bridgeConfigs = new ArrayList(); bridgeConfigs.add(bridgeConfiguration); server0.getConfiguration().setBridgeConfigurations(bridgeConfigs); - CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName0); + CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName0); List queueConfigs0 = new ArrayList(); queueConfigs0.add(queueConfig0); server0.getConfiguration().setQueueConfigurations(queueConfigs0); - CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration() - .setAddress(forwardAddress) - .setName(queueName1); + CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration().setAddress(forwardAddress).setName(queueName1); List queueConfigs1 = new ArrayList(); queueConfigs1.add(queueConfig1); server1.getConfiguration().setQueueConfigurations(queueConfigs1); @@ -593,16 +508,14 @@ public class BridgeTest extends ActiveMQTestBase final SimpleString selectorKey = new SimpleString("animal"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(true); message.putIntProperty(propKey, i); message.putStringProperty(selectorKey, new SimpleString("monkey")); - if (largeMessage) - { + if (largeMessage) { message.setBodyInputStream(ActiveMQTestBase.createFakeLargeStream(10 * 1024)); } @@ -611,24 +524,21 @@ public class BridgeTest extends ActiveMQTestBase Assert.assertNull(consumer1.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(true); message.putIntProperty(propKey, i); message.putStringProperty(selectorKey, new SimpleString("goat")); - if (largeMessage) - { + if (largeMessage) { message.setBodyInputStream(ActiveMQTestBase.createFakeLargeStream(10 * 1024)); } producer0.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(4000); Assert.assertNotNull(message); @@ -639,8 +549,7 @@ public class BridgeTest extends ActiveMQTestBase message.acknowledge(); - if (largeMessage) - { + if (largeMessage) { readLargeMessages(message, 10); } } @@ -659,8 +568,7 @@ public class BridgeTest extends ActiveMQTestBase sf1.close(); closeFields(); - if (useFiles) - { + if (useFiles) { Map counters = loadQueues(server0); assertEquals(1, counters.size()); Long key = counters.keySet().iterator().next(); @@ -670,13 +578,11 @@ public class BridgeTest extends ActiveMQTestBase assertEquals(numMessages, counters.get(key).intValue()); } - } // Created to verify JBPAPP-6057 @Test - public void testStartLater() throws Exception - { + public void testStartLater() throws Exception { Map server0Params = new HashMap(); server0 = createClusteredServerWithParams(isNetty(), 0, true, server0Params); @@ -698,23 +604,13 @@ public class BridgeTest extends ActiveMQTestBase ArrayList staticConnectors = new ArrayList(); staticConnectors.add(server1tc.getName()); - BridgeConfiguration bridgeConfiguration = new BridgeConfiguration() - .setName("bridge1") - .setQueueName(queueName0) - .setForwardingAddress(forwardAddress) - .setRetryInterval(100) - .setReconnectAttemptsOnSameNode(-1) - .setUseDuplicateDetection(false) - .setConfirmationWindowSize(1024) - .setStaticConnectors(staticConnectors); + BridgeConfiguration bridgeConfiguration = new BridgeConfiguration().setName("bridge1").setQueueName(queueName0).setForwardingAddress(forwardAddress).setRetryInterval(100).setReconnectAttemptsOnSameNode(-1).setUseDuplicateDetection(false).setConfirmationWindowSize(1024).setStaticConnectors(staticConnectors); List bridgeConfigs = new ArrayList(); bridgeConfigs.add(bridgeConfiguration); server0.getConfiguration().setBridgeConfigurations(bridgeConfigs); - CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName0); + CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName0); List queueConfigs0 = new ArrayList(); queueConfigs0.add(queueConfig0); server0.getConfiguration().setQueueConfigurations(queueConfigs0); @@ -734,8 +630,7 @@ public class BridgeTest extends ActiveMQTestBase final SimpleString selectorKey = new SimpleString("animal"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(true); message.getBodyBuffer().writeBytes(new byte[1024]); @@ -755,12 +650,10 @@ public class BridgeTest extends ActiveMQTestBase ClientSession session1 = sf1.createSession(false, true, true); - try - { + try { session1.createQueue(forwardAddress, queueName1); } - catch (Throwable ignored) - { + catch (Throwable ignored) { ignored.printStackTrace(); } @@ -768,8 +661,7 @@ public class BridgeTest extends ActiveMQTestBase session1.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(5000); assertNotNull(message); message.acknowledge(); @@ -795,12 +687,10 @@ public class BridgeTest extends ActiveMQTestBase closeFields(); assertEquals(0, loadQueues(server0).size()); - } @Test - public void testWithDuplicates() throws Exception - { + public void testWithDuplicates() throws Exception { Map server0Params = new HashMap(); server0 = createClusteredServerWithParams(isNetty(), 0, true, server0Params); @@ -822,22 +712,13 @@ public class BridgeTest extends ActiveMQTestBase ArrayList staticConnectors = new ArrayList(); staticConnectors.add(server1tc.getName()); - BridgeConfiguration bridgeConfiguration = new BridgeConfiguration() - .setName("bridge1") - .setQueueName(queueName0) - .setForwardingAddress(forwardAddress) - .setRetryInterval(100) - .setReconnectAttemptsOnSameNode(-1) - .setConfirmationWindowSize(0) - .setStaticConnectors(staticConnectors); + BridgeConfiguration bridgeConfiguration = new BridgeConfiguration().setName("bridge1").setQueueName(queueName0).setForwardingAddress(forwardAddress).setRetryInterval(100).setReconnectAttemptsOnSameNode(-1).setConfirmationWindowSize(0).setStaticConnectors(staticConnectors); List bridgeConfigs = new ArrayList(); bridgeConfigs.add(bridgeConfiguration); server0.getConfiguration().setBridgeConfigurations(bridgeConfigs); - CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName0); + CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName0); List queueConfigs0 = new ArrayList(); queueConfigs0.add(queueConfig0); server0.getConfiguration().setQueueConfigurations(queueConfigs0); @@ -857,8 +738,7 @@ public class BridgeTest extends ActiveMQTestBase final SimpleString selectorKey = new SimpleString("animal"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(true); message.getBodyBuffer().writeBytes(new byte[1024]); @@ -879,20 +759,17 @@ public class BridgeTest extends ActiveMQTestBase Queue queue = server0.locateQueue(new SimpleString(queueName0)); LinkedListIterator iterator = queue.iterator(); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { iterator.hasNext(); ids[i] = iterator.next().getMessage().getMessageID(); } iterator.close(); - DuplicateIDCache duplicateTargetCache = server1.getPostOffice() - .getDuplicateIDCache(PostOfficeImpl.BRIDGE_CACHE_STR.concat(forwardAddress)); + DuplicateIDCache duplicateTargetCache = server1.getPostOffice().getDuplicateIDCache(PostOfficeImpl.BRIDGE_CACHE_STR.concat(forwardAddress)); TransactionImpl tx = new TransactionImpl(server1.getStorageManager()); - for (long id : ids) - { + for (long id : ids) { byte[] duplicateArray = BridgeImpl.getDuplicateBytes(server0.getNodeManager().getUUID(), id); duplicateTargetCache.addToCache(duplicateArray, tx); } @@ -905,12 +782,10 @@ public class BridgeTest extends ActiveMQTestBase ClientSession session1 = sf1.createSession(false, true, true); - try - { + try { session1.createQueue(forwardAddress, queueName1); } - catch (Throwable ignored) - { + catch (Throwable ignored) { ignored.printStackTrace(); } @@ -918,8 +793,7 @@ public class BridgeTest extends ActiveMQTestBase session1.start(); - for (int i = 100; i < numMessages; i++) - { + for (int i = 100; i < numMessages; i++) { ClientMessage message = consumer1.receive(5000); assertNotNull(message); assertEquals(i, message.getIntProperty(propKey).intValue()); @@ -947,30 +821,25 @@ public class BridgeTest extends ActiveMQTestBase closeFields(); assertEquals(0, loadQueues(server0).size()); - } - private void closeFields() throws Exception - { + private void closeFields() throws Exception { locator.close(); server0.stop(); server1.stop(); } @Test - public void testWithTransformer() throws Exception - { + public void testWithTransformer() throws Exception { internaltestWithTransformer(false); } @Test - public void testWithTransformerFiles() throws Exception - { + public void testWithTransformerFiles() throws Exception { internaltestWithTransformer(true); } - public void internaltestWithTransformer(final boolean useFiles) throws Exception - { + public void internaltestWithTransformer(final boolean useFiles) throws Exception { Map server0Params = new HashMap(); server0 = createClusteredServerWithParams(isNetty(), 0, false, server0Params); @@ -993,32 +862,18 @@ public class BridgeTest extends ActiveMQTestBase ArrayList staticConnectors = new ArrayList(); staticConnectors.add(server1tc.getName()); - BridgeConfiguration bridgeConfiguration = new BridgeConfiguration() - .setName("bridge1") - .setQueueName(queueName0) - .setForwardingAddress(forwardAddress) - .setTransformerClassName(SimpleTransformer.class.getName()) - .setRetryInterval(1000) - .setReconnectAttemptsOnSameNode(-1) - .setUseDuplicateDetection(false) - .setConfirmationWindowSize(1024) - .setStaticConnectors(staticConnectors); - + BridgeConfiguration bridgeConfiguration = new BridgeConfiguration().setName("bridge1").setQueueName(queueName0).setForwardingAddress(forwardAddress).setTransformerClassName(SimpleTransformer.class.getName()).setRetryInterval(1000).setReconnectAttemptsOnSameNode(-1).setUseDuplicateDetection(false).setConfirmationWindowSize(1024).setStaticConnectors(staticConnectors); List bridgeConfigs = new ArrayList(); bridgeConfigs.add(bridgeConfiguration); server0.getConfiguration().setBridgeConfigurations(bridgeConfigs); - CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName0); + CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName0); List queueConfigs0 = new ArrayList(); queueConfigs0.add(queueConfig0); server0.getConfiguration().setQueueConfigurations(queueConfigs0); - CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration() - .setAddress(forwardAddress) - .setName(queueName1); + CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration().setAddress(forwardAddress).setName(queueName1); List queueConfigs1 = new ArrayList(); queueConfigs1.add(queueConfig1); server1.getConfiguration().setQueueConfigurations(queueConfigs1); @@ -1045,8 +900,7 @@ public class BridgeTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("wibble"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(true); message.putStringProperty(propKey, new SimpleString("bing")); @@ -1056,8 +910,7 @@ public class BridgeTest extends ActiveMQTestBase producer0.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(200); Assert.assertNotNull(message); @@ -1084,15 +937,13 @@ public class BridgeTest extends ActiveMQTestBase sf1.close(); - if (server0.getConfiguration().isPersistenceEnabled()) - { + if (server0.getConfiguration().isPersistenceEnabled()) { assertEquals(0, loadQueues(server0).size()); } } @Test - public void testSawtoothLoad() throws Exception - { + public void testSawtoothLoad() throws Exception { Map server0Params = new HashMap(); ActiveMQServer server0 = createClusteredServerWithParams(isNetty(), 0, true, server0Params); server0.getConfiguration().setThreadPoolMaxSize(10); @@ -1117,36 +968,23 @@ public class BridgeTest extends ActiveMQTestBase ArrayList staticConnectors = new ArrayList(); staticConnectors.add(server1tc.getName()); - BridgeConfiguration bridgeConfiguration = new BridgeConfiguration() - .setName("bridge1") - .setQueueName(queueName0) - .setForwardingAddress(forwardAddress) - .setRetryInterval(1000) - .setReconnectAttemptsOnSameNode(-1) - .setUseDuplicateDetection(false) - .setConfirmationWindowSize(0) - .setStaticConnectors(staticConnectors); + BridgeConfiguration bridgeConfiguration = new BridgeConfiguration().setName("bridge1").setQueueName(queueName0).setForwardingAddress(forwardAddress).setRetryInterval(1000).setReconnectAttemptsOnSameNode(-1).setUseDuplicateDetection(false).setConfirmationWindowSize(0).setStaticConnectors(staticConnectors); List bridgeConfigs = new ArrayList(); bridgeConfigs.add(bridgeConfiguration); server0.getConfiguration().setBridgeConfigurations(bridgeConfigs); - CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName0); + CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName0); List queueConfigs0 = new ArrayList(); queueConfigs0.add(queueConfig0); server0.getConfiguration().setQueueConfigurations(queueConfigs0); - CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration() - .setAddress(forwardAddress) - .setName(queueName1); + CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration().setAddress(forwardAddress).setName(queueName1); List queueConfigs1 = new ArrayList(); queueConfigs1.add(queueConfig1); server1.getConfiguration().setQueueConfigurations(queueConfigs1); - try - { + try { server1.start(); server0.start(); @@ -1159,13 +997,11 @@ public class BridgeTest extends ActiveMQTestBase // We shouldn't have more than 10K messages pending final Semaphore semop = new Semaphore(10000); - class ConsumerThread extends Thread - { + class ConsumerThread extends Thread { + @Override - public void run() - { - try - { + public void run() { + try { ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(server1tc)); ClientSessionFactory sf = createSessionFactory(locator); @@ -1176,16 +1012,14 @@ public class BridgeTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(queueName1); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(5000); Assert.assertNotNull(message); message.acknowledge(); semop.release(); - if (i % 1000 == 0) - { + if (i % 1000 == 0) { session.commit(); } } @@ -1197,30 +1031,26 @@ public class BridgeTest extends ActiveMQTestBase locator.close(); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); errors.incrementAndGet(); } } } - class ProducerThread extends Thread - { + class ProducerThread extends Thread { + final int nmsg; - ProducerThread(int nmsg) - { + ProducerThread(int nmsg) { this.nmsg = nmsg; } @Override - public void run() - { + public void run() { ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(server0tc)); - locator.setBlockOnDurableSend(false) - .setBlockOnNonDurableSend(false); + locator.setBlockOnDurableSend(false).setBlockOnNonDurableSend(false); ClientSessionFactory sf = null; @@ -1228,28 +1058,23 @@ public class BridgeTest extends ActiveMQTestBase ClientProducer producer = null; - try - { + try { sf = createSessionFactory(locator); session = sf.createSession(false, true, true); producer = session.createProducer(new SimpleString(testAddress)); - for (int i = 0; i < nmsg; i++) - { + for (int i = 0; i < nmsg; i++) { assertEquals(0, errors.get()); ClientMessage message = session.createMessage(true); message.putIntProperty("seq", i); - - if (i % 100 == 0) - { + if (i % 100 == 0) { message.setPriority((byte) (RandomUtil.randomPositiveInt() % 9)); } - else - { + else { message.setPriority((byte) 5); } @@ -1259,85 +1084,70 @@ public class BridgeTest extends ActiveMQTestBase assertTrue(semop.tryAcquire(1, 10, TimeUnit.SECONDS)); } } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(System.out); errors.incrementAndGet(); } - finally - { - try - { + finally { + try { session.close(); sf.close(); locator.close(); } - catch (Exception ignored) - { + catch (Exception ignored) { errors.incrementAndGet(); } } } } - for (int repeat = 0; repeat < totalrepeats; repeat++) - { + for (int repeat = 0; repeat < totalrepeats; repeat++) { ArrayList threads = new ArrayList(); threads.add(new ConsumerThread()); threads.add(new ProducerThread(numMessages / 2)); threads.add(new ProducerThread(numMessages / 2)); - for (Thread t : threads) - { + for (Thread t : threads) { t.start(); } - for (Thread t : threads) - { + for (Thread t : threads) { t.join(); } assertEquals(0, errors.get()); } } - finally - { - try - { + finally { + try { server0.stop(); } - catch (Exception ignored) - { + catch (Exception ignored) { } - try - { + try { server1.stop(); } - catch (Exception ignored) - { + catch (Exception ignored) { } } assertEquals(0, loadQueues(server0).size()); - } @Test - public void testBridgeWithPaging() throws Exception - { + public void testBridgeWithPaging() throws Exception { ActiveMQServer server0 = null; ActiveMQServer server1 = null; final int PAGE_MAX = 10 * 1024; final int PAGE_SIZE = 1 * 1024; - try - { + try { Map server0Params = new HashMap(); server0 = createClusteredServerWithParams(isNetty(), 0, true, PAGE_SIZE, PAGE_MAX, server0Params); @@ -1365,15 +1175,7 @@ public class BridgeTest extends ActiveMQTestBase ArrayList staticConnectors = new ArrayList(); staticConnectors.add(server1tc.getName()); - BridgeConfiguration bridgeConfiguration = new BridgeConfiguration() - .setName("bridge1") - .setQueueName(queueName0) - .setForwardingAddress(forwardAddress) - .setRetryInterval(1) - .setReconnectAttemptsOnSameNode(-1) - .setUseDuplicateDetection(false) - .setConfirmationWindowSize(1) - .setStaticConnectors(staticConnectors); + BridgeConfiguration bridgeConfiguration = new BridgeConfiguration().setName("bridge1").setQueueName(queueName0).setForwardingAddress(forwardAddress).setRetryInterval(1).setReconnectAttemptsOnSameNode(-1).setUseDuplicateDetection(false).setConfirmationWindowSize(1).setStaticConnectors(staticConnectors); bridgeConfiguration.setCallTimeout(1000); @@ -1383,16 +1185,12 @@ public class BridgeTest extends ActiveMQTestBase bridgeConfigs.add(bridgeConfiguration); server0.getConfiguration().setBridgeConfigurations(bridgeConfigs); - CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName0); + CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName0); List queueConfigs0 = new ArrayList(); queueConfigs0.add(queueConfig0); server0.getConfiguration().setQueueConfigurations(queueConfigs0); - CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration() - .setAddress(forwardAddress) - .setName(queueName1); + CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration().setAddress(forwardAddress).setName(queueName1); List queueConfigs1 = new ArrayList(); queueConfigs1.add(queueConfig1); server1.getConfiguration().setQueueConfigurations(queueConfigs1); @@ -1425,8 +1223,7 @@ public class BridgeTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("testkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(true); message.getBodyBuffer().writeBytes(new byte[512]); @@ -1441,24 +1238,20 @@ public class BridgeTest extends ActiveMQTestBase StopInterceptor.thread.join(15000); - if (StopInterceptor.thread.isAlive()) - { + if (StopInterceptor.thread.isAlive()) { System.out.println(threadDump("Still alive, stop didn't work!!!")); fail("Thread that should restart the server still alive"); } - // Restarting the server server0.start(); HashMap receivedMsg = new HashMap(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(5000); - if (message == null) - { + if (message == null) { break; } @@ -1466,40 +1259,35 @@ public class BridgeTest extends ActiveMQTestBase AtomicInteger msgCount = receivedMsg.get(msgKey); - if (msgKey.intValue() != i) - { + if (msgKey.intValue() != i) { System.err.println("Message " + msgCount + " received out of order, expected to be " + i + " it's acceptable but not the ideal!"); } - if (msgCount == null) - { + if (msgCount == null) { msgCount = new AtomicInteger(); receivedMsg.put(msgKey, msgCount); } msgCount.incrementAndGet(); - if (i % 500 == 0) System.out.println("received " + i); + if (i % 500 == 0) + System.out.println("received " + i); } boolean failed = false; - if (consumer1.receiveImmediate() != null) - { + if (consumer1.receiveImmediate() != null) { System.err.println("Unexpected message received"); failed = true; } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { AtomicInteger msgCount = receivedMsg.get(Integer.valueOf(i)); - if (msgCount == null) - { + if (msgCount == null) { System.err.println("Msg " + i + " wasn't received"); failed = true; } - else if (msgCount.get() > 1) - { + else if (msgCount.get() > 1) { System.err.println("msg " + i + " was received " + msgCount.get() + " times"); failed = true; } @@ -1517,48 +1305,37 @@ public class BridgeTest extends ActiveMQTestBase sf1.close(); } - finally - { - if (locator != null) - { + finally { + if (locator != null) { locator.close(); } - try - { + try { server0.stop(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } - try - { + try { server1.stop(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } - assertEquals(0, loadQueues(server0).size()); - } - // Stops a server after 100 messages received - public static class StopInterceptor implements Interceptor - { + public static class StopInterceptor implements Interceptor { + static ActiveMQServer serverToStop; static Thread thread; static final ReusableLatch latch = new ReusableLatch(0); - - public static void reset() - { + public static void reset() { latch.setCount(1); serverToStop = null; count = 0; @@ -1568,28 +1345,21 @@ public class BridgeTest extends ActiveMQTestBase static int count = 0; @Override - public synchronized boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException - { + public synchronized boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException { - if (packet instanceof SessionSendMessage && ++count == 100) - { - try - { + if (packet instanceof SessionSendMessage && ++count == 100) { + try { System.out.println("Stopping server after " + count + " messages"); - thread = new Thread("***Server Restarter***") - { + thread = new Thread("***Server Restarter***") { - public void run() - { - try - { + public void run() { + try { System.out.println("Stopping server"); latch.countDown(); serverToStop.stop(false); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -1600,8 +1370,7 @@ public class BridgeTest extends ActiveMQTestBase latch.await(); return true; } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -1610,8 +1379,7 @@ public class BridgeTest extends ActiveMQTestBase } @Test - public void testBridgeWithLargeMessage() throws Exception - { + public void testBridgeWithLargeMessage() throws Exception { ActiveMQServer server0 = null; ActiveMQServer server1 = null; @@ -1619,8 +1387,7 @@ public class BridgeTest extends ActiveMQTestBase final int PAGE_SIZE = 10 * 1024; ServerLocator locator = null; - try - { + try { Map server0Params = new HashMap(); server0 = createClusteredServerWithParams(isNetty(), 0, true, PAGE_SIZE, PAGE_MAX, server0Params); @@ -1645,30 +1412,18 @@ public class BridgeTest extends ActiveMQTestBase ArrayList staticConnectors = new ArrayList(); staticConnectors.add(server1tc.getName()); - BridgeConfiguration bridgeConfiguration = new BridgeConfiguration() - .setName("bridge1") - .setQueueName(queueName0) - .setForwardingAddress(forwardAddress) - .setRetryInterval(1000) - .setReconnectAttemptsOnSameNode(-1) - .setUseDuplicateDetection(false) - .setConfirmationWindowSize(1024) - .setStaticConnectors(staticConnectors); + BridgeConfiguration bridgeConfiguration = new BridgeConfiguration().setName("bridge1").setQueueName(queueName0).setForwardingAddress(forwardAddress).setRetryInterval(1000).setReconnectAttemptsOnSameNode(-1).setUseDuplicateDetection(false).setConfirmationWindowSize(1024).setStaticConnectors(staticConnectors); List bridgeConfigs = new ArrayList(); bridgeConfigs.add(bridgeConfiguration); server0.getConfiguration().setBridgeConfigurations(bridgeConfigs); - CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName0); + CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName0); List queueConfigs0 = new ArrayList(); queueConfigs0.add(queueConfig0); server0.getConfiguration().setQueueConfigurations(queueConfigs0); - CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration() - .setAddress(forwardAddress) - .setName(queueName1); + CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration().setAddress(forwardAddress).setName(queueName1); List queueConfigs1 = new ArrayList(); queueConfigs1.add(queueConfig1); server1.getConfiguration().setQueueConfigurations(queueConfigs1); @@ -1696,8 +1451,7 @@ public class BridgeTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("testkey"); final int LARGE_MESSAGE_SIZE = 1024; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(true); message.setBodyInputStream(createFakeLargeStream(LARGE_MESSAGE_SIZE)); @@ -1708,8 +1462,7 @@ public class BridgeTest extends ActiveMQTestBase session0.commit(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(5000); Assert.assertNotNull(message); @@ -1718,8 +1471,7 @@ public class BridgeTest extends ActiveMQTestBase ActiveMQBuffer buff = message.getBodyBuffer(); - for (int posMsg = 0; posMsg < LARGE_MESSAGE_SIZE; posMsg++) - { + for (int posMsg = 0; posMsg < LARGE_MESSAGE_SIZE; posMsg++) { assertEquals(getSamplebyte(posMsg), buff.readByte()); } @@ -1738,28 +1490,21 @@ public class BridgeTest extends ActiveMQTestBase sf1.close(); - } - finally - { - if (locator != null) - { + finally { + if (locator != null) { locator.close(); } - try - { + try { server0.stop(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } - try - { + try { server1.stop(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } @@ -1767,8 +1512,7 @@ public class BridgeTest extends ActiveMQTestBase } @Test - public void testNullForwardingAddress() throws Exception - { + public void testNullForwardingAddress() throws Exception { Map server0Params = new HashMap(); server0 = createClusteredServerWithParams(isNetty(), 0, false, server0Params); @@ -1795,30 +1539,19 @@ public class BridgeTest extends ActiveMQTestBase ArrayList staticConnectors = new ArrayList(); staticConnectors.add(server1tc.getName()); // do not set forwarding address (defaults to null) to use messages' original address - BridgeConfiguration bridgeConfiguration = new BridgeConfiguration() - .setName("bridge1") - .setQueueName(queueName0) - .setRetryInterval(1000) - .setReconnectAttemptsOnSameNode(-1) - .setUseDuplicateDetection(false) - .setConfirmationWindowSize(numMessages * messageSize / 2) - .setStaticConnectors(staticConnectors); + BridgeConfiguration bridgeConfiguration = new BridgeConfiguration().setName("bridge1").setQueueName(queueName0).setRetryInterval(1000).setReconnectAttemptsOnSameNode(-1).setUseDuplicateDetection(false).setConfirmationWindowSize(numMessages * messageSize / 2).setStaticConnectors(staticConnectors); List bridgeConfigs = new ArrayList(); bridgeConfigs.add(bridgeConfiguration); server0.getConfiguration().setBridgeConfigurations(bridgeConfigs); - CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName0); + CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName0); List queueConfigs0 = new ArrayList(); queueConfigs0.add(queueConfig0); server0.getConfiguration().setQueueConfigurations(queueConfigs0); // on server #1, we bind queueName1 to same address testAddress - CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName1); + CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName1); List queueConfigs1 = new ArrayList(); queueConfigs1.add(queueConfig1); server1.getConfiguration().setQueueConfigurations(queueConfigs1); @@ -1845,8 +1578,7 @@ public class BridgeTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("testkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(true); message.putIntProperty(propKey, i); @@ -1856,8 +1588,7 @@ public class BridgeTest extends ActiveMQTestBase producer0.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(200); Assert.assertNotNull(message); @@ -1880,18 +1611,15 @@ public class BridgeTest extends ActiveMQTestBase } @Test - public void testInjectedTransformer() throws Exception - { + public void testInjectedTransformer() throws Exception { final SimpleString ADDRESS = new SimpleString("myAddress"); final SimpleString QUEUE = new SimpleString("myQueue"); final String BRIDGE = "myBridge"; ServiceRegistryImpl serviceRegistry = new ServiceRegistryImpl(); - Transformer transformer = new Transformer() - { + Transformer transformer = new Transformer() { @Override - public ServerMessage transform(ServerMessage message) - { + public ServerMessage transform(ServerMessage message) { return null; } }; @@ -1903,14 +1631,10 @@ public class BridgeTest extends ActiveMQTestBase server.deployQueue(ADDRESS, QUEUE, null, false, false); List connectors = new ArrayList<>(); connectors.add("in-vm"); - server.deployBridge(new BridgeConfiguration() - .setName(BRIDGE) - .setQueueName(QUEUE.toString()) - .setForwardingAddress(ADDRESS.toString()) - .setStaticConnectors(connectors)); + server.deployBridge(new BridgeConfiguration().setName(BRIDGE).setQueueName(QUEUE.toString()).setForwardingAddress(ADDRESS.toString()).setStaticConnectors(connectors)); Bridge bridge = server.getClusterManager().getBridges().get(BRIDGE); assertNotNull(bridge); - assertEquals(transformer, ((BridgeImpl)bridge).getTransformer()); + assertEquals(transformer, ((BridgeImpl) bridge).getTransformer()); } /** @@ -1920,19 +1644,10 @@ public class BridgeTest extends ActiveMQTestBase * @return a Map containing the reference counts per queue * @throws Exception */ - protected Map loadQueues(ActiveMQServer serverToInvestigate) throws Exception - { - SequentialFileFactory messagesFF = new NIOSequentialFileFactory(serverToInvestigate.getConfiguration() - .getJournalLocation(), 1); + protected Map loadQueues(ActiveMQServer serverToInvestigate) throws Exception { + SequentialFileFactory messagesFF = new NIOSequentialFileFactory(serverToInvestigate.getConfiguration().getJournalLocation(), 1); - JournalImpl messagesJournal = new JournalImpl(serverToInvestigate.getConfiguration().getJournalFileSize(), - serverToInvestigate.getConfiguration().getJournalMinFiles(), - 0, - 0, - messagesFF, - "activemq-data", - "amq", - 1); + JournalImpl messagesJournal = new JournalImpl(serverToInvestigate.getConfiguration().getJournalFileSize(), serverToInvestigate.getConfiguration().getJournalMinFiles(), 0, 0, messagesFF, "activemq-data", "amq", 1); List records = new LinkedList(); List preparedTransactions = new LinkedList(); @@ -1943,20 +1658,16 @@ public class BridgeTest extends ActiveMQTestBase // These are more immutable integers Map messageRefCounts = new HashMap(); - for (RecordInfo info : records) - { + for (RecordInfo info : records) { Object o = DescribeJournal.newObjectEncoding(info); - if (info.getUserRecordType() == JournalRecordIds.ADD_REF) - { + if (info.getUserRecordType() == JournalRecordIds.ADD_REF) { DescribeJournal.ReferenceDescribe ref = (DescribeJournal.ReferenceDescribe) o; AtomicInteger count = messageRefCounts.get(ref.refEncoding.queueID); - if (count == null) - { + if (count == null) { count = new AtomicInteger(1); messageRefCounts.put(ref.refEncoding.queueID, count); } - else - { + else { count.incrementAndGet(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/BridgeTestBase.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/BridgeTestBase.java index 57e7f633b5..a05bcbe6d7 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/BridgeTestBase.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/BridgeTestBase.java @@ -31,61 +31,46 @@ import org.apache.activemq.artemis.core.server.NodeManager; import org.apache.activemq.artemis.tests.util.InVMNodeManagerServer; import org.junit.After; -public abstract class BridgeTestBase extends ActiveMQTestBase -{ +public abstract class BridgeTestBase extends ActiveMQTestBase { @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { InVMConnector.failOnCreateConnection = false; super.tearDown(); } - protected ActiveMQServer createActiveMQServer(final int id, final boolean netty, final Map params) throws Exception - { + protected ActiveMQServer createActiveMQServer(final int id, + final boolean netty, + final Map params) throws Exception { return createActiveMQServer(id, params, netty, null); } protected ActiveMQServer createActiveMQServer(final int id, final Map params, final boolean netty, - final NodeManager nodeManager) throws Exception - { + final NodeManager nodeManager) throws Exception { TransportConfiguration tc = new TransportConfiguration(); - if (netty) - { - params.put(org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.PORT_PROP_NAME, - org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.DEFAULT_PORT + id); + if (netty) { + params.put(org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.PORT_PROP_NAME, org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.DEFAULT_PORT + id); tc = new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params); } - else - { + else { params.put(org.apache.activemq.artemis.core.remoting.impl.invm.TransportConstants.SERVER_ID_PROP_NAME, id); tc = new TransportConfiguration(INVM_ACCEPTOR_FACTORY, params); } - Configuration serviceConf = createBasicConfig() - .setJournalType(getDefaultJournalType()) - .setBindingsDirectory(getBindingsDir(id, false)) - .setJournalMinFiles(2) - .setJournalDirectory(getJournalDir(id, false)) - .setPagingDirectory(getPageDir(id, false)) - .setLargeMessagesDirectory(getLargeMessagesDir(id, false)) + Configuration serviceConf = createBasicConfig().setJournalType(getDefaultJournalType()).setBindingsDirectory(getBindingsDir(id, false)).setJournalMinFiles(2).setJournalDirectory(getJournalDir(id, false)).setPagingDirectory(getPageDir(id, false)).setLargeMessagesDirectory(getLargeMessagesDir(id, false)) // these tests don't need any big storage so limiting the size of the journal files to speed up the test - .setJournalFileSize(100 * 1024) - .addAcceptorConfiguration(tc) - .setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration()); + .setJournalFileSize(100 * 1024).addAcceptorConfiguration(tc).setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration()); ActiveMQServer server; - if (nodeManager == null) - { + if (nodeManager == null) { server = ActiveMQServers.newActiveMQServer(serviceConf, true); } - else - { + else { server = new InVMNodeManagerServer(serviceConf, nodeManager); } @@ -96,50 +81,34 @@ public abstract class BridgeTestBase extends ActiveMQTestBase final Map params, final boolean netty, final int liveId, - final NodeManager nodeManager) throws Exception - { + final NodeManager nodeManager) throws Exception { TransportConfiguration tc = new TransportConfiguration(); - if (netty) - { - params.put(org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.PORT_PROP_NAME, - org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.DEFAULT_PORT + id); + if (netty) { + params.put(org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.PORT_PROP_NAME, org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.DEFAULT_PORT + id); tc = new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params); } - else - { + else { params.put(org.apache.activemq.artemis.core.remoting.impl.invm.TransportConstants.SERVER_ID_PROP_NAME, id); tc = new TransportConfiguration(INVM_ACCEPTOR_FACTORY, params); } - Configuration serviceConf = createBasicConfig() - .setJournalType(getDefaultJournalType()) - .setBindingsDirectory(getBindingsDir(liveId, false)) - .setJournalMinFiles(2) - .setJournalDirectory(getJournalDir(liveId, false)) - .setPagingDirectory(getPageDir(liveId, false)) - .setLargeMessagesDirectory(getLargeMessagesDir(liveId, false)) + Configuration serviceConf = createBasicConfig().setJournalType(getDefaultJournalType()).setBindingsDirectory(getBindingsDir(liveId, false)).setJournalMinFiles(2).setJournalDirectory(getJournalDir(liveId, false)).setPagingDirectory(getPageDir(liveId, false)).setLargeMessagesDirectory(getLargeMessagesDir(liveId, false)) // these tests don't need any big storage so limiting the size of the journal files to speed up the test - .setJournalFileSize(100 * 1024) - .addAcceptorConfiguration(tc) - .setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration()); + .setJournalFileSize(100 * 1024).addAcceptorConfiguration(tc).setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration()); ActiveMQServer server; - if (nodeManager == null) - { + if (nodeManager == null) { server = ActiveMQServers.newActiveMQServer(serviceConf, true); } - else - { + else { server = new InVMNodeManagerServer(serviceConf, nodeManager); } return addServer(server); } - - protected void waitForServerStart(ActiveMQServer server) throws Exception - { + protected void waitForServerStart(ActiveMQServer server) throws Exception { if (!server.waitForActivation(5000L, TimeUnit.MILLISECONDS)) throw new IllegalStateException("Timed out waiting for server starting = " + server); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/BridgeWithDiscoveryGroupStartTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/BridgeWithDiscoveryGroupStartTest.java index 83c9eccb32..e65ec9962a 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/BridgeWithDiscoveryGroupStartTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/BridgeWithDiscoveryGroupStartTest.java @@ -49,54 +49,40 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) -public class BridgeWithDiscoveryGroupStartTest extends ActiveMQTestBase -{ +public class BridgeWithDiscoveryGroupStartTest extends ActiveMQTestBase { @Parameterized.Parameters(name = "isNetty={0}") - public static Collection getParameters() - { - return Arrays.asList(new Object[][]{ - {true}, - {false} - }); + public static Collection getParameters() { + return Arrays.asList(new Object[][]{{true}, {false}}); } - public BridgeWithDiscoveryGroupStartTest(boolean netty) - { + public BridgeWithDiscoveryGroupStartTest(boolean netty) { this.netty = netty; } - private final boolean netty; - - private static final int TIMEOUT = 2000; - protected boolean isNetty() - { + protected boolean isNetty() { return netty; } @Test - public void testStartStop() throws Exception - { + public void testStartStop() throws Exception { Map server0Params = new HashMap(); ActiveMQServer server0 = createClusteredServerWithParams(isNetty(), 0, true, server0Params); Map server1Params = new HashMap(); - if (isNetty()) - { + if (isNetty()) { server1Params.put("port", TransportConstants.DEFAULT_PORT + 1); } - else - { + else { server1Params.put(org.apache.activemq.artemis.core.remoting.impl.invm.TransportConstants.SERVER_ID_PROP_NAME, 1); } ActiveMQServer server1 = createClusteredServerWithParams(isNetty(), 1, true, server1Params); ServerLocator locator = null; - try - { + try { Map connectors = new HashMap(); TransportConfiguration server0tc = new TransportConfiguration(getConnector(), server0Params); TransportConfiguration server1tc = new TransportConfiguration(getConnector(), server1Params); @@ -112,25 +98,16 @@ public class BridgeWithDiscoveryGroupStartTest extends ActiveMQTestBase final String groupAddress = getUDPDiscoveryAddress(); final int port = getUDPDiscoveryPort(); - ArrayList list = new ArrayList(); list.add(server1tc.getName()); UDPBroadcastEndpointFactory endpoint = new UDPBroadcastEndpointFactory().setGroupAddress(groupAddress).setGroupPort(port); - BroadcastGroupConfiguration bcConfig = new BroadcastGroupConfiguration() - .setName("bg1") - .setBroadcastPeriod(250) - .setConnectorInfos(list) - .setEndpointFactory(endpoint); + BroadcastGroupConfiguration bcConfig = new BroadcastGroupConfiguration().setName("bg1").setBroadcastPeriod(250).setConnectorInfos(list).setEndpointFactory(endpoint); server0.getConfiguration().getBroadcastGroupConfigurations().add(bcConfig); - DiscoveryGroupConfiguration dcConfig = new DiscoveryGroupConfiguration() - .setName("dg1") - .setRefreshTimeout(5000) - .setDiscoveryInitialWaitTimeout(5000) - .setBroadcastEndpointFactory(endpoint); + DiscoveryGroupConfiguration dcConfig = new DiscoveryGroupConfiguration().setName("dg1").setRefreshTimeout(5000).setDiscoveryInitialWaitTimeout(5000).setBroadcastEndpointFactory(endpoint); server0.getConfiguration().getDiscoveryGroupConfigurations().put(dcConfig.getName(), dcConfig); @@ -138,30 +115,18 @@ public class BridgeWithDiscoveryGroupStartTest extends ActiveMQTestBase ArrayList staticConnectors = new ArrayList(); staticConnectors.add(server1tc.getName()); - BridgeConfiguration bridgeConfiguration = new BridgeConfiguration() - .setName(bridgeName) - .setQueueName(queueName0) - .setForwardingAddress(forwardAddress) - .setRetryInterval(1000) - .setReconnectAttempts(0) - .setReconnectAttemptsOnSameNode(0) - .setConfirmationWindowSize(1024) - .setStaticConnectors(staticConnectors); + BridgeConfiguration bridgeConfiguration = new BridgeConfiguration().setName(bridgeName).setQueueName(queueName0).setForwardingAddress(forwardAddress).setRetryInterval(1000).setReconnectAttempts(0).setReconnectAttemptsOnSameNode(0).setConfirmationWindowSize(1024).setStaticConnectors(staticConnectors); List bridgeConfigs = new ArrayList(); bridgeConfigs.add(bridgeConfiguration); server0.getConfiguration().setBridgeConfigurations(bridgeConfigs); - CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName0); + CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName0); List queueConfigs0 = new ArrayList(); queueConfigs0.add(queueConfig0); server0.getConfiguration().setQueueConfigurations(queueConfigs0); - CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration() - .setAddress(forwardAddress) - .setName(queueName1); + CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration().setAddress(forwardAddress).setName(queueName1); List queueConfigs1 = new ArrayList(); queueConfigs1.add(queueConfig1); server1.getConfiguration().setQueueConfigurations(queueConfigs1); @@ -188,8 +153,7 @@ public class BridgeWithDiscoveryGroupStartTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("testkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(false); message.putIntProperty(propKey, i); @@ -197,8 +161,7 @@ public class BridgeWithDiscoveryGroupStartTest extends ActiveMQTestBase producer0.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(BridgeWithDiscoveryGroupStartTest.TIMEOUT); Assert.assertNotNull(message); @@ -215,8 +178,7 @@ public class BridgeWithDiscoveryGroupStartTest extends ActiveMQTestBase bridge.stop(); bridge.flushExecutor(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(false); message.putIntProperty(propKey, i); @@ -228,8 +190,7 @@ public class BridgeWithDiscoveryGroupStartTest extends ActiveMQTestBase bridge.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(BridgeWithDiscoveryGroupStartTest.TIMEOUT); Assert.assertNotNull(message); @@ -249,10 +210,8 @@ public class BridgeWithDiscoveryGroupStartTest extends ActiveMQTestBase sf1.close(); } - finally - { - if (locator != null) - { + finally { + if (locator != null) { locator.close(); } server0.stop(); @@ -265,14 +224,11 @@ public class BridgeWithDiscoveryGroupStartTest extends ActiveMQTestBase /** * @return */ - private String getConnector() - { - if (isNetty()) - { + private String getConnector() { + if (isNetty()) { return NettyConnectorFactory.class.getName(); } - else - { + else { return InVMConnectorFactory.class.getName(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/SimpleTransformer.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/SimpleTransformer.java index 1a6d9432d5..5399e528c3 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/SimpleTransformer.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/SimpleTransformer.java @@ -21,14 +21,12 @@ import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.server.ServerMessage; import org.apache.activemq.artemis.core.server.cluster.Transformer; -public class SimpleTransformer implements Transformer -{ - public ServerMessage transform(final ServerMessage message) - { - SimpleString oldProp = (SimpleString)message.getObjectProperty(new SimpleString("wibble")); +public class SimpleTransformer implements Transformer { - if (!oldProp.equals(new SimpleString("bing"))) - { + public ServerMessage transform(final ServerMessage message) { + SimpleString oldProp = (SimpleString) message.getObjectProperty(new SimpleString("wibble")); + + if (!oldProp.equals(new SimpleString("bing"))) { throw new IllegalStateException("Wrong property value!!"); } @@ -42,8 +40,7 @@ public class SimpleTransformer implements Transformer String str = buffer.readString(); - if (!str.equals("doo be doo be doo be doo")) - { + if (!str.equals("doo be doo be doo be doo")) { throw new IllegalStateException("Wrong body!!"); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/ClusterHeadersRemovedTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/ClusterHeadersRemovedTest.java index 421a2fb3ce..517274f653 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/ClusterHeadersRemovedTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/ClusterHeadersRemovedTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.cluster.distribution; + import org.apache.activemq.artemis.core.server.cluster.impl.MessageLoadBalancingType; import org.junit.Before; @@ -27,26 +28,23 @@ import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.core.message.impl.MessageImpl; -public class ClusterHeadersRemovedTest extends ClusterTestBase -{ +public class ClusterHeadersRemovedTest extends ClusterTestBase { + @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); } - protected boolean isNetty() - { + protected boolean isNetty() { return false; } @Test - public void testHeadersRemoved() throws Exception - { + public void testHeadersRemoved() throws Exception { setupClusterConnection("cluster1", 0, 1, "queues", MessageLoadBalancingType.ON_DEMAND, 1, isNetty(), false); setupClusterConnection("clusterX", 1, -1, "queues", MessageLoadBalancingType.ON_DEMAND, 1, isNetty(), false); startServers(1, 0); @@ -68,26 +66,22 @@ public class ClusterHeadersRemovedTest extends ClusterTestBase ClientSession session0 = sf.createSession(false, true, true); - try - { + try { ClientProducer producer = session0.createProducer("queues.testaddress"); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage message = session0.createMessage(true); producer.send(message); } } - finally - { + finally { session0.close(); } ClientConsumer consumer = super.getConsumer(1); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage message = consumer.receive(5000); assertNotNull(message); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/ClusterTestBase.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/ClusterTestBase.java index f1e3c06f4e..ae81eed0c2 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/ClusterTestBase.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/ClusterTestBase.java @@ -84,33 +84,20 @@ import org.junit.After; import org.junit.Assert; import org.junit.Before; -public abstract class ClusterTestBase extends ActiveMQTestBase -{ +public abstract class ClusterTestBase extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; - private static final int[] PORTS = { - TransportConstants.DEFAULT_PORT, - TransportConstants.DEFAULT_PORT + 1, - TransportConstants.DEFAULT_PORT + 2, - TransportConstants.DEFAULT_PORT + 3, - TransportConstants.DEFAULT_PORT + 4, - TransportConstants.DEFAULT_PORT + 5, - TransportConstants.DEFAULT_PORT + 6, - TransportConstants.DEFAULT_PORT + 7, - TransportConstants.DEFAULT_PORT + 8, - TransportConstants.DEFAULT_PORT + 9,}; + private static final int[] PORTS = {TransportConstants.DEFAULT_PORT, TransportConstants.DEFAULT_PORT + 1, TransportConstants.DEFAULT_PORT + 2, TransportConstants.DEFAULT_PORT + 3, TransportConstants.DEFAULT_PORT + 4, TransportConstants.DEFAULT_PORT + 5, TransportConstants.DEFAULT_PORT + 6, TransportConstants.DEFAULT_PORT + 7, TransportConstants.DEFAULT_PORT + 8, TransportConstants.DEFAULT_PORT + 9,}; - protected int getLargeMessageSize() - { + protected int getLargeMessageSize() { return 500; } - protected boolean isLargeMessage() - { + protected boolean isLargeMessage() { return false; } - private static final long TIMEOUT_START_SERVER = 10; private static final SimpleString COUNT_PROP = new SimpleString("count_prop"); @@ -133,8 +120,7 @@ public abstract class ClusterTestBase extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); forceGC(); @@ -151,8 +137,7 @@ public abstract class ClusterTestBase extends ActiveMQTestBase nodeManagers = new NodeManager[ClusterTestBase.MAX_SERVERS]; - for (int i = 0, nodeManagersLength = nodeManagers.length; i < nodeManagersLength; i++) - { + for (int i = 0, nodeManagersLength = nodeManagers.length; i < nodeManagersLength; i++) { nodeManagers[i] = new InVMNodeManager(isSharedStore(), new File(getJournalDir(i, true))); } @@ -163,18 +148,15 @@ public abstract class ClusterTestBase extends ActiveMQTestBase /** * Whether the servers share the storage or not. */ - protected boolean isSharedStore() - { + protected boolean isSharedStore() { return false; } @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { logTopologyDiagram(); - for (int i = 0; i < MAX_SERVERS; i++) - { + for (int i = 0; i < MAX_SERVERS; i++) { addActiveMQComponent(nodeManagers[i]); } servers = null; @@ -195,8 +177,8 @@ public abstract class ClusterTestBase extends ActiveMQTestBase private static final int MAX_CONSUMERS = 100; - protected static class ConsumerHolder - { + protected static class ConsumerHolder { + final ClientConsumer consumer; final ClientSession session; @@ -205,28 +187,23 @@ public abstract class ClusterTestBase extends ActiveMQTestBase final int node; - public ClientConsumer getConsumer() - { + public ClientConsumer getConsumer() { return consumer; } - public ClientSession getSession() - { + public ClientSession getSession() { return session; } - public int getId() - { + public int getId() { return id; } - public int getNode() - { + public int getNode() { return node; } - ConsumerHolder(final int id, final ClientConsumer consumer, final ClientSession session, int node) - { + ConsumerHolder(final int id, final ClientConsumer consumer, final ClientSession session, int node) { this.id = id; this.node = node; @@ -234,47 +211,36 @@ public abstract class ClusterTestBase extends ActiveMQTestBase this.session = session; } - void close() - { - if (consumer != null) - { - try - { + void close() { + if (consumer != null) { + try { consumer.close(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { // ignore } } - if (session != null) - { - try - { + if (session != null) { + try { session.close(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { // ignore } } } @Override - public String toString() - { + public String toString() { return "id=" + id + ", consumer=" + consumer + ", session=" + session; } } - protected ClientConsumer getConsumer(final int node) - { + protected ClientConsumer getConsumer(final int node) { return consumers[node].consumer; } - - protected void waitForFailoverTopology(final int bNode, final int... nodes) throws Exception - { + protected void waitForFailoverTopology(final int bNode, final int... nodes) throws Exception { ActiveMQServer server = servers[bNode]; log.debug("waiting for " + Arrays.toString(nodes) + " on the topology for server = " + server); @@ -284,45 +250,35 @@ public abstract class ClusterTestBase extends ActiveMQTestBase final int waitMillis = 2000; final int sleepTime = 50; int nWaits = 0; - while (server.getClusterManager() == null && nWaits++ < waitMillis / sleepTime) - { + while (server.getClusterManager() == null && nWaits++ < waitMillis / sleepTime) { Thread.sleep(sleepTime); } Set ccs = server.getClusterManager().getClusterConnections(); - if (ccs.size() != 1) - { + if (ccs.size() != 1) { throw new IllegalStateException("You need a single cluster connection on this version of waitForTopology on ServiceTestBase"); } boolean exists = false; - for (int node : nodes) - { + for (int node : nodes) { ClusterConnectionImpl clusterConnection = (ClusterConnectionImpl) ccs.iterator().next(); Topology topology = clusterConnection.getTopology(); - TransportConfiguration nodeConnector = - servers[node].getClusterManager().getClusterConnections().iterator().next().getConnector(); - do - { + TransportConfiguration nodeConnector = servers[node].getClusterManager().getClusterConnections().iterator().next().getConnector(); + do { Collection members = topology.getMembers(); - for (TopologyMemberImpl member : members) - { - if (member.getConnector().getA() != null && member.getConnector().getA().equals(nodeConnector)) - { + for (TopologyMemberImpl member : members) { + if (member.getConnector().getA() != null && member.getConnector().getA().equals(nodeConnector)) { exists = true; break; } } - if (exists) - { + if (exists) { break; } Thread.sleep(10); - } - while (System.currentTimeMillis() - start < WAIT_TIMEOUT); - if (!exists) - { + } while (System.currentTimeMillis() - start < WAIT_TIMEOUT); + if (!exists) { String msg = "Timed out waiting for cluster topology of " + Arrays.toString(nodes) + " (received " + topology.getMembers().size() + @@ -339,52 +295,38 @@ public abstract class ClusterTestBase extends ActiveMQTestBase } } - private void logTopologyDiagram() - { + private void logTopologyDiagram() { StringBuffer topologyDiagram = new StringBuffer(); - for (ActiveMQServer activeMQServer : servers) - { - if (activeMQServer != null) - { + for (ActiveMQServer activeMQServer : servers) { + if (activeMQServer != null) { topologyDiagram.append("\n").append(activeMQServer.getIdentity()).append("\n"); - if (activeMQServer.isStarted()) - { + if (activeMQServer.isStarted()) { Set ccs = activeMQServer.getClusterManager().getClusterConnections(); - if (ccs.size() >= 1) - { + if (ccs.size() >= 1) { ClusterConnectionImpl clusterConnection = (ClusterConnectionImpl) ccs.iterator().next(); Collection members = clusterConnection.getTopology().getMembers(); - for (TopologyMemberImpl member : members) - { + for (TopologyMemberImpl member : members) { String nodeId = member.getNodeId(); String liveServer = null; String backupServer = null; - for (ActiveMQServer server : servers) - { - if (server != null && server.getNodeID() != null && server.isActive() && server.getNodeID().toString().equals(nodeId)) - { - if (server.isActive()) - { + for (ActiveMQServer server : servers) { + if (server != null && server.getNodeID() != null && server.isActive() && server.getNodeID().toString().equals(nodeId)) { + if (server.isActive()) { liveServer = server.getIdentity(); - if (member.getLive() != null) - { + if (member.getLive() != null) { liveServer += "(notified)"; } - else - { + else { liveServer += "(not notified)"; } } - else - { + else { backupServer = server.getIdentity(); - if (member.getBackup() != null) - { + if (member.getBackup() != null) { liveServer += "(notified)"; } - else - { + else { liveServer += "(not notified)"; } } @@ -394,13 +336,11 @@ public abstract class ClusterTestBase extends ActiveMQTestBase topologyDiagram.append("\t").append("|\n").append("\t->").append(liveServer).append("/").append(backupServer).append("\n"); } } - else - { + else { topologyDiagram.append("-> no cluster connections\n"); } } - else - { + else { topologyDiagram.append("-> stopped\n"); } } @@ -409,12 +349,10 @@ public abstract class ClusterTestBase extends ActiveMQTestBase log.info(topologyDiagram.toString()); } - protected void waitForMessages(final int node, final String address, final int count) throws Exception - { + protected void waitForMessages(final int node, final String address, final int count) throws Exception { ActiveMQServer server = servers[node]; - if (server == null) - { + if (server == null) { throw new IllegalArgumentException("No server at " + node); } @@ -424,35 +362,29 @@ public abstract class ClusterTestBase extends ActiveMQTestBase int messageCount = 0; - do - { + do { messageCount = getMessageCount(po, address); - if (messageCount == count) - { + if (messageCount == count) { return; } Thread.sleep(10); - } - while (System.currentTimeMillis() - start < ActiveMQTestBase.WAIT_TIMEOUT); + } while (System.currentTimeMillis() - start < ActiveMQTestBase.WAIT_TIMEOUT); throw new IllegalStateException("Timed out waiting for messages (messageCount = " + messageCount + ", expecting = " + count); } - protected void waitForServerRestart(final int node) throws Exception - { + protected void waitForServerRestart(final int node) throws Exception { long waitTimeout = ActiveMQTestBase.WAIT_TIMEOUT; - if (!isSharedStore()) - { + if (!isSharedStore()) { //it should be greater than //QuorumManager.WAIT_TIME_AFTER_FIRST_LIVE_STOPPING_MSG (60 sec) waitTimeout = 1000 * (SharedNothingBackupQuorum.WAIT_TIME_AFTER_FIRST_LIVE_STOPPING_MSG + 5); } - if (!servers[node].waitForActivation(waitTimeout, TimeUnit.MILLISECONDS)) - { + if (!servers[node].waitForActivation(waitTimeout, TimeUnit.MILLISECONDS)) { String msg = "Timed out waiting for server starting = " + node; log.error(msg); @@ -465,8 +397,7 @@ public abstract class ClusterTestBase extends ActiveMQTestBase final String address, final int expectedBindingCount, final int expectedConsumerCount, - final boolean local) throws Exception - { + final boolean local) throws Exception { log.debug("waiting for bindings on node " + node + " address " + address + @@ -479,30 +410,24 @@ public abstract class ClusterTestBase extends ActiveMQTestBase ActiveMQServer server = servers[node]; - if (server == null) - { + if (server == null) { throw new IllegalArgumentException("No server at " + node); } long timeout = ActiveMQTestBase.WAIT_TIMEOUT; - - if (waitForBindings(server, address, local, expectedBindingCount, expectedConsumerCount, timeout)) - { + if (waitForBindings(server, address, local, expectedBindingCount, expectedConsumerCount, timeout)) { return; } - PostOffice po = server.getPostOffice(); Bindings bindings = po.getBindingsForAddress(new SimpleString(address)); System.out.println("======================================================================="); System.out.println("Binding information for address = " + address + " on node " + node); - for (Binding binding : bindings.getBindings()) - { - if (binding.isConnected() && (binding instanceof LocalQueueBinding && local || binding instanceof RemoteQueueBinding && !local)) - { + for (Binding binding : bindings.getBindings()) { + if (binding.isConnected() && (binding instanceof LocalQueueBinding && local || binding instanceof RemoteQueueBinding && !local)) { QueueBinding qBinding = (QueueBinding) binding; System.out.println("Binding = " + qBinding + ", queue=" + qBinding.getQueue()); @@ -512,32 +437,22 @@ public abstract class ClusterTestBase extends ActiveMQTestBase StringWriter writer = new StringWriter(); PrintWriter out = new PrintWriter(writer); - try - { - for (ActiveMQServer activeMQServer : servers) - { - if (activeMQServer != null) - { + try { + for (ActiveMQServer activeMQServer : servers) { + if (activeMQServer != null) { out.println(clusterDescription(activeMQServer)); - out.println(debugBindings(activeMQServer, activeMQServer.getConfiguration() - .getManagementNotificationAddress() - .toString())); + out.println(debugBindings(activeMQServer, activeMQServer.getConfiguration().getManagementNotificationAddress().toString())); } } - for (ActiveMQServer activeMQServer : servers) - { + for (ActiveMQServer activeMQServer : servers) { out.println("Management bindings on " + activeMQServer); - if (activeMQServer != null) - { - out.println(debugBindings(activeMQServer, activeMQServer.getConfiguration() - .getManagementNotificationAddress() - .toString())); + if (activeMQServer != null) { + out.println(debugBindings(activeMQServer, activeMQServer.getConfiguration().getManagementNotificationAddress().toString())); } } } - catch (Throwable dontCare) - { + catch (Throwable dontCare) { } logAndSystemOut(writer.toString()); @@ -545,20 +460,17 @@ public abstract class ClusterTestBase extends ActiveMQTestBase throw new IllegalStateException("Didn't get the expected number of bindings, look at the logging for more information"); } - protected String debugBindings(final ActiveMQServer server, final String address) throws Exception - { + protected String debugBindings(final ActiveMQServer server, final String address) throws Exception { StringWriter str = new StringWriter(); PrintWriter out = new PrintWriter(str); - if (server == null) - { + if (server == null) { return "server is shutdown"; } PostOffice po = server.getPostOffice(); - if (po == null) - { + if (po == null) { return "server is shutdown"; } Bindings bindings = po.getBindingsForAddress(new SimpleString(address)); @@ -566,8 +478,7 @@ public abstract class ClusterTestBase extends ActiveMQTestBase out.println("======================================================================="); out.println("Binding information for address = " + address + " on " + server); - for (Binding binding : bindings.getBindings()) - { + for (Binding binding : bindings.getBindings()) { QueueBinding qBinding = (QueueBinding) binding; out.println("Binding = " + qBinding + ", queue=" + qBinding.getQueue()); @@ -582,12 +493,10 @@ public abstract class ClusterTestBase extends ActiveMQTestBase final String address, final String queueName, final String filterVal, - final boolean durable) throws Exception - { + final boolean durable) throws Exception { ClientSessionFactory sf = sfs[node]; - if (sf == null) - { + if (sf == null) { throw new IllegalArgumentException("No sf at " + node); } @@ -595,8 +504,7 @@ public abstract class ClusterTestBase extends ActiveMQTestBase String filterString = null; - if (filterVal != null) - { + if (filterVal != null) { filterString = ClusterTestBase.FILTER_PROP.toString() + "='" + filterVal + "'"; } @@ -607,12 +515,10 @@ public abstract class ClusterTestBase extends ActiveMQTestBase session.close(); } - protected void deleteQueue(final int node, final String queueName) throws Exception - { + protected void deleteQueue(final int node, final String queueName) throws Exception { ClientSessionFactory sf = sfs[node]; - if (sf == null) - { + if (sf == null) { throw new IllegalArgumentException("No sf at " + node); } @@ -623,24 +529,26 @@ public abstract class ClusterTestBase extends ActiveMQTestBase session.close(); } - protected void addConsumer(final int consumerID, final int node, final String queueName, final String filterVal) throws Exception - { + protected void addConsumer(final int consumerID, + final int node, + final String queueName, + final String filterVal) throws Exception { addConsumer(consumerID, node, queueName, filterVal, true); } - protected void addConsumer(final int consumerID, final int node, final String queueName, final String filterVal, boolean autoCommitAcks) throws Exception - { - try - { - if (consumers[consumerID] != null) - { + protected void addConsumer(final int consumerID, + final int node, + final String queueName, + final String filterVal, + boolean autoCommitAcks) throws Exception { + try { + if (consumers[consumerID] != null) { throw new IllegalArgumentException("Already a consumer at " + node); } ClientSessionFactory sf = sfs[node]; - if (sf == null) - { + if (sf == null) { throw new IllegalArgumentException("No sf at " + node); } @@ -648,8 +556,7 @@ public abstract class ClusterTestBase extends ActiveMQTestBase String filterString = null; - if (filterVal != null) - { + if (filterVal != null) { filterString = ClusterTestBase.FILTER_PROP.toString() + "='" + filterVal + "'"; } @@ -659,8 +566,7 @@ public abstract class ClusterTestBase extends ActiveMQTestBase consumers[consumerID] = new ConsumerHolder(consumerID, consumer, session, node); } - catch (Exception e) - { + catch (Exception e) { // Proxy the failure and print a dump into System.out, so it is captured by Jenkins reports e.printStackTrace(); System.out.println(ActiveMQTestBase.threadDump(" - fired by ClusterTestBase::addConsumer")); @@ -669,12 +575,10 @@ public abstract class ClusterTestBase extends ActiveMQTestBase } } - protected void removeConsumer(final int consumerID) - { + protected void removeConsumer(final int consumerID) { ConsumerHolder holder = consumers[consumerID]; - if (holder == null) - { + if (holder == null) { throw new IllegalArgumentException("No consumer at " + consumerID); } @@ -683,16 +587,13 @@ public abstract class ClusterTestBase extends ActiveMQTestBase consumers[consumerID] = null; } - protected void closeAllConsumers() - { + protected void closeAllConsumers() { if (consumers == null) return; - for (int i = 0; i < consumers.length; i++) - { + for (int i = 0; i < consumers.length; i++) { ConsumerHolder holder = consumers[i]; - if (holder != null) - { + if (holder != null) { holder.close(); consumers[i] = null; } @@ -700,12 +601,9 @@ public abstract class ClusterTestBase extends ActiveMQTestBase } @Override - protected void closeAllSessionFactories() - { - if (sfs != null) - { - for (int i = 0; i < sfs.length; i++) - { + protected void closeAllSessionFactories() { + if (sfs != null) { + for (int i = 0; i < sfs.length; i++) { closeSessionFactory(sfs[i]); sfs[i] = null; } @@ -714,22 +612,18 @@ public abstract class ClusterTestBase extends ActiveMQTestBase } @Override - protected void closeAllServerLocatorsFactories() - { - for (int i = 0; i < locators.length; i++) - { + protected void closeAllServerLocatorsFactories() { + for (int i = 0; i < locators.length; i++) { closeServerLocator(locators[i]); locators[i] = null; } super.closeAllServerLocatorsFactories(); } - protected void closeSessionFactory(final int node) - { + protected void closeSessionFactory(final int node) { ClientSessionFactory sf = sfs[node]; - if (sf == null) - { + if (sf == null) { throw new IllegalArgumentException("No sf at " + node); } @@ -743,8 +637,7 @@ public abstract class ClusterTestBase extends ActiveMQTestBase final int msgStart, final int msgEnd, final boolean durable, - final String filterVal) throws Exception - { + final String filterVal) throws Exception { sendInRange(node, address, msgStart, msgEnd, durable, filterVal, null); } @@ -754,55 +647,46 @@ public abstract class ClusterTestBase extends ActiveMQTestBase final int msgEnd, final boolean durable, final String filterVal, - final AtomicInteger duplicateDetectionSeq) throws Exception - { + final AtomicInteger duplicateDetectionSeq) throws Exception { ClientSessionFactory sf = sfs[node]; - if (sf == null) - { + if (sf == null) { throw new IllegalArgumentException("No sf at " + node); } ClientSession session = sf.createSession(false, false, false); - try - { + try { ClientProducer producer = session.createProducer(address); - for (int i = msgStart; i < msgEnd; i++) - { + for (int i = msgStart; i < msgEnd; i++) { ClientMessage message = session.createMessage(durable); - if (filterVal != null) - { + if (filterVal != null) { message.putStringProperty(ClusterTestBase.FILTER_PROP, new SimpleString(filterVal)); } - if (duplicateDetectionSeq != null) - { + if (duplicateDetectionSeq != null) { String str = Integer.toString(duplicateDetectionSeq.incrementAndGet()); message.putStringProperty(Message.HDR_DUPLICATE_DETECTION_ID, new SimpleString(str)); } message.putIntProperty(ClusterTestBase.COUNT_PROP, i); - if (isLargeMessage()) - { + if (isLargeMessage()) { message.setBodyInputStream(createFakeLargeStream(getLargeMessageSize())); } producer.send(message); - if (i % 100 == 0) - { + if (i % 100 == 0) { session.commit(); } } session.commit(); } - finally - { + finally { session.close(); } } @@ -812,8 +696,7 @@ public abstract class ClusterTestBase extends ActiveMQTestBase final int numMessages, final boolean durable, final SimpleString key, - final SimpleString val) throws Exception - { + final SimpleString val) throws Exception { sendInRange(node, address, 0, numMessages, durable, key, val); } @@ -823,27 +706,22 @@ public abstract class ClusterTestBase extends ActiveMQTestBase final int msgEnd, final boolean durable, final SimpleString key, - final SimpleString val) throws Exception - { + final SimpleString val) throws Exception { ClientSessionFactory sf = sfs[node]; - if (sf == null) - { + if (sf == null) { throw new IllegalArgumentException("No sf at " + node); } ClientSession session = sf.createSession(false, true, true); - try - { + try { ClientProducer producer = session.createProducer(address); - for (int i = msgStart; i < msgEnd; i++) - { + for (int i = msgStart; i < msgEnd; i++) { ClientMessage message = session.createMessage(durable); - if (isLargeMessage()) - { + if (isLargeMessage()) { message.setBodyInputStream(createFakeLargeStream(getLargeMessageSize())); } @@ -853,36 +731,28 @@ public abstract class ClusterTestBase extends ActiveMQTestBase producer.send(message); } } - finally - { + finally { session.close(); } } - protected void setUpGroupHandler(final GroupingHandlerConfiguration.TYPE type, final int node) - { + protected void setUpGroupHandler(final GroupingHandlerConfiguration.TYPE type, final int node) { setUpGroupHandler(type, node, 5000); } - protected void setUpGroupHandler(final GroupingHandlerConfiguration.TYPE type, final int node, final int timeout) - { + protected void setUpGroupHandler(final GroupingHandlerConfiguration.TYPE type, final int node, final int timeout) { setUpGroupHandler(type, node, timeout, -1, ActiveMQDefaultConfiguration.getDefaultGroupingHandlerReaperPeriod()); } - protected void setUpGroupHandler(final GroupingHandlerConfiguration.TYPE type, final int node, final int timeout, final long groupTimeout, - final long reaperPeriod) - { - servers[node].getConfiguration().setGroupingHandlerConfiguration(new GroupingHandlerConfiguration() - .setName(new SimpleString("grouparbitrator")) - .setType(type) - .setAddress(new SimpleString("queues")) - .setTimeout(timeout) - .setGroupTimeout(groupTimeout) - .setReaperPeriod(reaperPeriod)); + protected void setUpGroupHandler(final GroupingHandlerConfiguration.TYPE type, + final int node, + final int timeout, + final long groupTimeout, + final long reaperPeriod) { + servers[node].getConfiguration().setGroupingHandlerConfiguration(new GroupingHandlerConfiguration().setName(new SimpleString("grouparbitrator")).setType(type).setAddress(new SimpleString("queues")).setTimeout(timeout).setGroupTimeout(groupTimeout).setReaperPeriod(reaperPeriod)); } - protected void setUpGroupHandler(final GroupingHandler groupingHandler, final int node) - { + protected void setUpGroupHandler(final GroupingHandler groupingHandler, final int node) { servers[node].setGroupingHandler(groupingHandler); } @@ -890,8 +760,7 @@ public abstract class ClusterTestBase extends ActiveMQTestBase final String address, final int numMessages, final boolean durable, - final String filterVal) throws Exception - { + final String filterVal) throws Exception { send(node, address, numMessages, durable, filterVal, null); } @@ -900,31 +769,32 @@ public abstract class ClusterTestBase extends ActiveMQTestBase final int numMessages, final boolean durable, final String filterVal, - final AtomicInteger duplicateDetectionCounter) throws Exception - { + final AtomicInteger duplicateDetectionCounter) throws Exception { sendInRange(node, address, 0, numMessages, durable, filterVal, duplicateDetectionCounter); } protected void verifyReceiveAllInRange(final boolean ack, final int msgStart, final int msgEnd, - final int... consumerIDs) throws Exception - { + final int... consumerIDs) throws Exception { verifyReceiveAllInRangeNotBefore(ack, -1, msgStart, msgEnd, consumerIDs); } - protected void verifyReceiveAllInRange(final int msgStart, final int msgEnd, final int... consumerIDs) throws Exception - { + protected void verifyReceiveAllInRange(final int msgStart, + final int msgEnd, + final int... consumerIDs) throws Exception { verifyReceiveAllInRangeNotBefore(false, -1, msgStart, msgEnd, consumerIDs); } - protected void verifyReceiveAllWithGroupIDRoundRobin(final int msgStart, final int msgEnd, final int... consumerIDs) throws Exception - { + protected void verifyReceiveAllWithGroupIDRoundRobin(final int msgStart, + final int msgEnd, + final int... consumerIDs) throws Exception { verifyReceiveAllWithGroupIDRoundRobin(true, -1, msgStart, msgEnd, consumerIDs); } - protected int verifyReceiveAllOnSingleConsumer(final int msgStart, final int msgEnd, final int... consumerIDs) throws Exception - { + protected int verifyReceiveAllOnSingleConsumer(final int msgStart, + final int msgEnd, + final int... consumerIDs) throws Exception { return verifyReceiveAllOnSingleConsumer(true, msgStart, msgEnd, consumerIDs); } @@ -932,24 +802,19 @@ public abstract class ClusterTestBase extends ActiveMQTestBase final long firstReceiveTime, final int msgStart, final int msgEnd, - final int... consumerIDs) throws Exception - { + final int... consumerIDs) throws Exception { HashMap groupIdsReceived = new HashMap(); - for (int i = 0; i < consumerIDs.length; i++) - { + for (int i = 0; i < consumerIDs.length; i++) { ConsumerHolder holder = consumers[consumerIDs[i]]; - if (holder == null) - { + if (holder == null) { throw new IllegalArgumentException("No consumer at " + consumerIDs[i]); } - for (int j = msgStart; j < msgEnd; j++) - { + for (int j = msgStart; j < msgEnd; j++) { ClientMessage message = holder.consumer.receive(2000); - if (message == null) - { + if (message == null) { log.info("*** dumping consumers:"); dumpConsumers(); @@ -957,24 +822,20 @@ public abstract class ClusterTestBase extends ActiveMQTestBase Assert.assertNotNull("consumer " + consumerIDs[i] + " did not receive message " + j, message); } - if (ack) - { + if (ack) { message.acknowledge(); } - if (firstReceiveTime != -1) - { + if (firstReceiveTime != -1) { Assert.assertTrue("Message received too soon", System.currentTimeMillis() >= firstReceiveTime); } SimpleString id = (SimpleString) message.getObjectProperty(Message.HDR_GROUP_ID); - if (groupIdsReceived.get(id) == null) - { + if (groupIdsReceived.get(id) == null) { groupIdsReceived.put(id, i); } - else if (groupIdsReceived.get(id) != i) - { + else if (groupIdsReceived.get(id) != i) { Assert.fail("consumer " + groupIdsReceived.get(id) + " already bound to groupid " + id + @@ -991,32 +852,25 @@ public abstract class ClusterTestBase extends ActiveMQTestBase protected int verifyReceiveAllOnSingleConsumer(final boolean ack, final int msgStart, final int msgEnd, - final int... consumerIDs) throws Exception - { + final int... consumerIDs) throws Exception { int groupIdsReceived = -1; - for (int i = 0; i < consumerIDs.length; i++) - { + for (int i = 0; i < consumerIDs.length; i++) { ConsumerHolder holder = consumers[consumerIDs[i]]; - if (holder == null) - { + if (holder == null) { throw new IllegalArgumentException("No consumer at " + consumerIDs[i]); } ClientMessage message = holder.consumer.receive(2000); - if (message != null) - { + if (message != null) { groupIdsReceived = i; - for (int j = msgStart + 1; j < msgEnd; j++) - { + for (int j = msgStart + 1; j < msgEnd; j++) { message = holder.consumer.receive(2000); - if (message == null) - { + if (message == null) { Assert.fail("consumer " + i + " did not receive all messages"); } - if (ack) - { + if (ack) { message.acknowledge(); } } @@ -1031,26 +885,21 @@ public abstract class ClusterTestBase extends ActiveMQTestBase final long firstReceiveTime, final int msgStart, final int msgEnd, - final int... consumerIDs) throws Exception - { + final int... consumerIDs) throws Exception { boolean outOfOrder = false; String firstOutOfOrderMessage = null; - for (int consumerID : consumerIDs) - { + for (int consumerID : consumerIDs) { ConsumerHolder holder = consumers[consumerID]; - if (holder == null) - { + if (holder == null) { throw new IllegalArgumentException("No consumer at " + consumerID); } - for (int j = msgStart; j < msgEnd; j++) - { + for (int j = msgStart; j < msgEnd; j++) { ClientMessage message = holder.consumer.receive(WAIT_TIMEOUT); - if (message == null) - { + if (message == null) { log.info("*** dumping consumers:"); dumpConsumers(); @@ -1058,25 +907,20 @@ public abstract class ClusterTestBase extends ActiveMQTestBase Assert.fail("consumer " + consumerID + " did not receive message " + j); } - if (isLargeMessage()) - { + if (isLargeMessage()) { checkMessageBody(message); } - if (ack) - { + if (ack) { message.acknowledge(); } - if (firstReceiveTime != -1) - { + if (firstReceiveTime != -1) { Assert.assertTrue("Message received too soon", System.currentTimeMillis() >= firstReceiveTime); } - if (j != (Integer) message.getObjectProperty(ClusterTestBase.COUNT_PROP)) - { - if (firstOutOfOrderMessage == null) - { + if (j != (Integer) message.getObjectProperty(ClusterTestBase.COUNT_PROP)) { + if (firstOutOfOrderMessage == null) { firstOutOfOrderMessage = "expected " + j + " received " + message.getObjectProperty(ClusterTestBase.COUNT_PROP); @@ -1094,12 +938,9 @@ public abstract class ClusterTestBase extends ActiveMQTestBase Assert.assertFalse("Messages were consumed out of order::" + firstOutOfOrderMessage, outOfOrder); } - private void dumpConsumers() throws Exception - { - for (int i = 0; i < consumers.length; i++) - { - if (consumers[i] != null && !consumers[i].consumer.isClosed()) - { + private void dumpConsumers() throws Exception { + for (int i = 0; i < consumers.length; i++) { + if (consumers[i] != null && !consumers[i].consumer.isClosed()) { log.info("Dumping consumer " + i); checkReceive(i); @@ -1107,20 +948,16 @@ public abstract class ClusterTestBase extends ActiveMQTestBase } } - protected String clusterDescription(ActiveMQServer server) - { + protected String clusterDescription(ActiveMQServer server) { String br = "-------------------------\n"; String out = br; out += "ActiveMQ Artemis server " + server + "\n"; ClusterManager clusterManager = server.getClusterManager(); - if (clusterManager == null) - { + if (clusterManager == null) { out += "N/A"; } - else - { - for (ClusterConnection cc : clusterManager.getClusterConnections()) - { + else { + for (ClusterConnection cc : clusterManager.getClusterConnections()) { out += cc.describe() + "\n"; out += cc.getTopology().describe(); } @@ -1129,68 +966,56 @@ public abstract class ClusterTestBase extends ActiveMQTestBase return out + br; } - protected void verifyReceiveAll(final boolean ack, final int numMessages, final int... consumerIDs) throws Exception - { + protected void verifyReceiveAll(final boolean ack, + final int numMessages, + final int... consumerIDs) throws Exception { verifyReceiveAllInRange(ack, 0, numMessages, consumerIDs); } - protected void verifyReceiveAll(final int numMessages, final int... consumerIDs) throws Exception - { + protected void verifyReceiveAll(final int numMessages, final int... consumerIDs) throws Exception { verifyReceiveAllInRange(false, 0, numMessages, consumerIDs); } protected void verifyReceiveAllNotBefore(final long firstReceiveTime, final int numMessages, - final int... consumerIDs) throws Exception - { + final int... consumerIDs) throws Exception { verifyReceiveAllInRangeNotBefore(false, firstReceiveTime, 0, numMessages, consumerIDs); } - protected void checkReceive(final int... consumerIDs) throws Exception - { - for (int consumerID : consumerIDs) - { + protected void checkReceive(final int... consumerIDs) throws Exception { + for (int consumerID : consumerIDs) { ConsumerHolder holder = consumers[consumerID]; - if (holder == null) - { + if (holder == null) { throw new IllegalArgumentException("No consumer at " + consumerID); } ClientMessage message; - do - { + do { message = holder.consumer.receive(500); - if (message != null) - { + if (message != null) { log.info("check receive Consumer " + consumerID + " received message " + message.getObjectProperty(ClusterTestBase.COUNT_PROP)); } - else - { + else { log.info("check receive Consumer " + consumerID + " null message"); } - } - while (message != null); + } while (message != null); } } - protected void verifyReceiveRoundRobin(final int numMessages, final int... consumerIDs) throws Exception - { + protected void verifyReceiveRoundRobin(final int numMessages, final int... consumerIDs) throws Exception { int count = 0; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { // We may use a negative number in some tests to ignore the consumer, case we know the server is down - if (consumerIDs[count] >= 0) - { + if (consumerIDs[count] >= 0) { ConsumerHolder holder = consumers[consumerIDs[count]]; - if (holder == null) - { + if (holder == null) { throw new IllegalArgumentException("No consumer at " + consumerIDs[i]); } @@ -1198,9 +1023,7 @@ public abstract class ClusterTestBase extends ActiveMQTestBase Assert.assertNotNull("consumer " + consumerIDs[count] + " did not receive message " + i, message); - Assert.assertEquals("consumer " + consumerIDs[count] + " message " + i, - i, - message.getObjectProperty(ClusterTestBase.COUNT_PROP)); + Assert.assertEquals("consumer " + consumerIDs[count] + " message " + i, i, message.getObjectProperty(ClusterTestBase.COUNT_PROP)); message.acknowledge(); @@ -1210,8 +1033,7 @@ public abstract class ClusterTestBase extends ActiveMQTestBase count++; - if (count == consumerIDs.length) - { + if (count == consumerIDs.length) { count = 0; } } @@ -1221,34 +1043,31 @@ public abstract class ClusterTestBase extends ActiveMQTestBase * With some tests we cannot guarantee the order in which the bridges in the cluster startup so the round robin order is not predefined. * In which case we test the messages are round robin'd in any specific order that contains all the consumers */ - protected void verifyReceiveRoundRobinInSomeOrder(final int numMessages, final int... consumerIDs) throws Exception - { - if (numMessages < consumerIDs.length) - { + protected void verifyReceiveRoundRobinInSomeOrder(final int numMessages, final int... consumerIDs) throws Exception { + if (numMessages < consumerIDs.length) { throw new IllegalStateException("You must send more messages than consumers specified or the algorithm " + "won't work"); } verifyReceiveRoundRobinInSomeOrder(true, numMessages, consumerIDs); } - class OrderedConsumerHolder implements Comparable - { + class OrderedConsumerHolder implements Comparable { + ConsumerHolder consumer; int order; - public int compareTo(final OrderedConsumerHolder o) - { + public int compareTo(final OrderedConsumerHolder o) { int thisOrder = order; int otherOrder = o.order; return thisOrder < otherOrder ? -1 : thisOrder == otherOrder ? 0 : 1; } } - protected void verifyReceiveRoundRobinInSomeOrder(final boolean ack, final int numMessages, final int... consumerIDs) throws Exception - { - if (numMessages < consumerIDs.length) - { + protected void verifyReceiveRoundRobinInSomeOrder(final boolean ack, + final int numMessages, + final int... consumerIDs) throws Exception { + if (numMessages < consumerIDs.length) { throw new IllegalStateException("not enough messages"); } @@ -1256,8 +1075,7 @@ public abstract class ClusterTestBase extends ActiveMQTestBase List sorted = new ArrayList(); - for (int consumerID : consumerIDs) - { + for (int consumerID : consumerIDs) { ConsumerHolder holder = consumers[consumerID]; ClientMessage msg = holder.consumer.receive(10000); @@ -1273,8 +1091,7 @@ public abstract class ClusterTestBase extends ActiveMQTestBase sorted.add(orderedHolder); - if (ack) - { + if (ack) { msg.acknowledge(); } } @@ -1287,10 +1104,8 @@ public abstract class ClusterTestBase extends ActiveMQTestBase int count = 0; - for (OrderedConsumerHolder holder : sorted) - { - if (holder.order != count) - { + for (OrderedConsumerHolder holder : sorted) { + if (holder.order != count) { throw new IllegalStateException("Out of order"); } @@ -1300,30 +1115,25 @@ public abstract class ClusterTestBase extends ActiveMQTestBase // Now check the rest are in order too outer: - while (count < numMessages) - { - for (OrderedConsumerHolder holder : sorted) - { + while (count < numMessages) { + for (OrderedConsumerHolder holder : sorted) { ClientMessage msg = holder.consumer.consumer.receive(10000); Assert.assertNotNull("msg must exist", msg); int p = msg.getIntProperty(ClusterTestBase.COUNT_PROP); - if (p != count) - { + if (p != count) { throw new IllegalStateException("Out of order 2"); } - if (ack) - { + if (ack) { msg.acknowledge(); } count++; - if (count == numMessages) - { + if (count == numMessages) { break outer; } @@ -1333,18 +1143,15 @@ public abstract class ClusterTestBase extends ActiveMQTestBase protected void verifyReceiveRoundRobinInSomeOrderWithCounts(final boolean ack, final int[] messageCounts, - final int... consumerIDs) throws Exception - { + final int... consumerIDs) throws Exception { List> receivedCounts = new ArrayList>(); Set counts = new HashSet(); - for (int consumerID : consumerIDs) - { + for (int consumerID : consumerIDs) { ConsumerHolder holder = consumers[consumerID]; - if (holder == null) - { + if (holder == null) { throw new IllegalArgumentException("No consumer at " + consumerID); } @@ -1353,17 +1160,14 @@ public abstract class ClusterTestBase extends ActiveMQTestBase receivedCounts.add(list); ClientMessage message; - do - { + do { message = holder.consumer.receive(1000); - if (message != null) - { + if (message != null) { int count = (Integer) message.getObjectProperty(ClusterTestBase.COUNT_PROP); checkMessageBody(message); - // log.info("consumer " + consumerIDs[i] + " received message " + count); Assert.assertFalse(counts.contains(count)); @@ -1372,31 +1176,25 @@ public abstract class ClusterTestBase extends ActiveMQTestBase list.add(count); - if (ack) - { + if (ack) { message.acknowledge(); } } - } - while (message != null); + } while (message != null); } - for (int messageCount : messageCounts) - { + for (int messageCount : messageCounts) { Assert.assertTrue(counts.contains(messageCount)); } @SuppressWarnings("unchecked") LinkedList[] lists = new LinkedList[consumerIDs.length]; - for (int i = 0; i < messageCounts.length; i++) - { - for (LinkedList list : receivedCounts) - { + for (int i = 0; i < messageCounts.length; i++) { + for (LinkedList list : receivedCounts) { int elem = list.get(0); - if (elem == messageCounts[i]) - { + if (elem == messageCounts[i]) { lists[i] = list; break; @@ -1405,8 +1203,7 @@ public abstract class ClusterTestBase extends ActiveMQTestBase } int index = 0; - for (int messageCount : messageCounts) - { + for (int messageCount : messageCounts) { LinkedList list = lists[index]; Assert.assertNotNull(list); @@ -1417,8 +1214,7 @@ public abstract class ClusterTestBase extends ActiveMQTestBase index++; - if (index == consumerIDs.length) - { + if (index == consumerIDs.length) { index = 0; } } @@ -1428,38 +1224,31 @@ public abstract class ClusterTestBase extends ActiveMQTestBase /** * @param message */ - private void checkMessageBody(ClientMessage message) - { - if (isLargeMessage()) - { - for (int posMsg = 0; posMsg < getLargeMessageSize(); posMsg++) - { + private void checkMessageBody(ClientMessage message) { + if (isLargeMessage()) { + for (int posMsg = 0; posMsg < getLargeMessageSize(); posMsg++) { assertEquals(getSamplebyte(posMsg), message.getBodyBuffer().readByte()); } } } - protected void verifyReceiveRoundRobinInSomeOrderNoAck(final int numMessages, final int... consumerIDs) throws Exception - { - if (numMessages < consumerIDs.length) - { + protected void verifyReceiveRoundRobinInSomeOrderNoAck(final int numMessages, + final int... consumerIDs) throws Exception { + if (numMessages < consumerIDs.length) { throw new IllegalStateException("You must send more messages than consumers specified or the algorithm " + "won't work"); } verifyReceiveRoundRobinInSomeOrder(false, numMessages, consumerIDs); } - protected int[] getReceivedOrder(final int consumerID) throws Exception - { + protected int[] getReceivedOrder(final int consumerID) throws Exception { return getReceivedOrder(consumerID, false); } - protected int[] getReceivedOrder(final int consumerID, final boolean ack) throws Exception - { + protected int[] getReceivedOrder(final int consumerID, final boolean ack) throws Exception { ConsumerHolder consumer = consumers[consumerID]; - if (consumer == null) - { + if (consumer == null) { throw new IllegalArgumentException("No consumer at " + consumerID); } @@ -1467,19 +1256,15 @@ public abstract class ClusterTestBase extends ActiveMQTestBase ClientMessage message = null; - do - { + do { message = consumer.consumer.receive(500); - if (message != null) - { + if (message != null) { - if (isLargeMessage()) - { + if (isLargeMessage()) { checkMessageBody(message); } - if (ack) - { + if (ack) { message.acknowledge(); } @@ -1487,20 +1272,17 @@ public abstract class ClusterTestBase extends ActiveMQTestBase ints.add(count); } - } - while (message != null); + } while (message != null); int[] res = new int[ints.size()]; int j = 0; - for (Integer i : ints) - { + for (Integer i : ints) { res[j++] = i; } - if (ack) - { + if (ack) { // just to flush acks consumers[consumerID].session.commit(); } @@ -1508,14 +1290,11 @@ public abstract class ClusterTestBase extends ActiveMQTestBase return res; } - protected void verifyNotReceive(final int... consumerIDs) throws Exception - { - for (int i = 0; i < consumerIDs.length; i++) - { + protected void verifyNotReceive(final int... consumerIDs) throws Exception { + for (int i = 0; i < consumerIDs.length; i++) { ConsumerHolder holder = consumers[consumerIDs[i]]; - if (holder == null) - { + if (holder == null) { throw new IllegalArgumentException("No consumer at " + consumerIDs[i]); } @@ -1523,15 +1302,12 @@ public abstract class ClusterTestBase extends ActiveMQTestBase } } - protected void setupSessionFactory(final int node, final boolean netty) throws Exception - { + protected void setupSessionFactory(final int node, final boolean netty) throws Exception { setupSessionFactory(node, netty, false); } - protected void setupSessionFactory(final int node, final boolean netty, boolean ha) throws Exception - { - if (sfs[node] != null) - { + protected void setupSessionFactory(final int node, final boolean netty, boolean ha) throws Exception { + if (sfs[node] != null) { throw new IllegalArgumentException("Already a factory at " + node); } @@ -1539,28 +1315,23 @@ public abstract class ClusterTestBase extends ActiveMQTestBase TransportConfiguration serverTotc; - if (netty) - { + if (netty) { serverTotc = new TransportConfiguration(ActiveMQTestBase.NETTY_CONNECTOR_FACTORY, params); } - else - { + else { serverTotc = new TransportConfiguration(INVM_CONNECTOR_FACTORY, params); } - if (ha) - { + if (ha) { locators[node] = ActiveMQClient.createServerLocatorWithHA(serverTotc); } - else - { + else { locators[node] = ActiveMQClient.createServerLocatorWithoutHA(serverTotc); } locators[node].setProtocolManagerFactory(ActiveMQServerSideProtocolManagerFactory.getInstance()); - locators[node].setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true); + locators[node].setBlockOnNonDurableSend(true).setBlockOnDurableSend(true); addServerLocator(locators[node]); ClientSessionFactory sf = createSessionFactory(locators[node]); @@ -1569,10 +1340,8 @@ public abstract class ClusterTestBase extends ActiveMQTestBase sfs[node] = sf; } - protected void setupSessionFactory(final int node, final boolean netty, int reconnectAttempts) throws Exception - { - if (sfs[node] != null) - { + protected void setupSessionFactory(final int node, final boolean netty, int reconnectAttempts) throws Exception { + if (sfs[node] != null) { throw new IllegalArgumentException("Already a server at " + node); } @@ -1580,19 +1349,14 @@ public abstract class ClusterTestBase extends ActiveMQTestBase TransportConfiguration serverTotc; - if (netty) - { + if (netty) { serverTotc = new TransportConfiguration(ActiveMQTestBase.NETTY_CONNECTOR_FACTORY, params); } - else - { + else { serverTotc = new TransportConfiguration(INVM_CONNECTOR_FACTORY, params); } - locators[node] = ActiveMQClient.createServerLocatorWithoutHA(serverTotc) - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setReconnectAttempts(reconnectAttempts); + locators[node] = ActiveMQClient.createServerLocatorWithoutHA(serverTotc).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setReconnectAttempts(reconnectAttempts); addServerLocator(locators[node]); ClientSessionFactory sf = createSessionFactory(locators[node]); @@ -1600,10 +1364,11 @@ public abstract class ClusterTestBase extends ActiveMQTestBase sfs[node] = sf; } - protected void setupSessionFactory(final int node, final int backupNode, final boolean netty, final boolean blocking) throws Exception - { - if (sfs[node] != null) - { + protected void setupSessionFactory(final int node, + final int backupNode, + final boolean netty, + final boolean blocking) throws Exception { + if (sfs[node] != null) { throw new IllegalArgumentException("Already a server at " + node); } @@ -1611,12 +1376,7 @@ public abstract class ClusterTestBase extends ActiveMQTestBase TransportConfiguration serverToTC = createTransportConfiguration(netty, false, params); - locators[node] = addServerLocator(ActiveMQClient.createServerLocatorWithHA(serverToTC)) - .setRetryInterval(100) - .setRetryIntervalMultiplier(1d) - .setReconnectAttempts(-1) - .setBlockOnNonDurableSend(blocking) - .setBlockOnDurableSend(blocking); + locators[node] = addServerLocator(ActiveMQClient.createServerLocatorWithHA(serverToTC)).setRetryInterval(100).setRetryIntervalMultiplier(1d).setReconnectAttempts(-1).setBlockOnNonDurableSend(blocking).setBlockOnDurableSend(blocking); final String identity = "TestClientConnector,live=" + node + ",backup=" + backupNode; ((ServerLocatorInternal) locators[node]).setIdentity(identity); @@ -1625,28 +1385,26 @@ public abstract class ClusterTestBase extends ActiveMQTestBase sfs[node] = sf; } - protected void setupSessionFactory(final int node, final int backupNode, final boolean netty) throws Exception - { + protected void setupSessionFactory(final int node, final int backupNode, final boolean netty) throws Exception { this.setupSessionFactory(node, backupNode, netty, true); } - protected ActiveMQServer getServer(final int node) - { - if (servers[node] == null) - { + protected ActiveMQServer getServer(final int node) { + if (servers[node] == null) { throw new IllegalArgumentException("No server at node " + node); } return servers[node]; } - protected void setupServer(final int node, final boolean fileStorage, final boolean netty) throws Exception - { + protected void setupServer(final int node, final boolean fileStorage, final boolean netty) throws Exception { setupLiveServer(node, fileStorage, false, netty, false); } - protected void setupLiveServer(final int node, final boolean fileStorage, final boolean netty, boolean isLive) throws Exception - { + protected void setupLiveServer(final int node, + final boolean fileStorage, + final boolean netty, + boolean isLive) throws Exception { setupLiveServer(node, fileStorage, false, netty, isLive); } @@ -1654,55 +1412,39 @@ public abstract class ClusterTestBase extends ActiveMQTestBase final boolean fileStorage, final boolean sharedStorage, final boolean netty, - boolean liveOnly) throws Exception - { - if (servers[node] != null) - { + boolean liveOnly) throws Exception { + if (servers[node] != null) { throw new IllegalArgumentException("Already a server at node " + node); } HAPolicyConfiguration haPolicyConfiguration = null; - if (liveOnly) - { + if (liveOnly) { haPolicyConfiguration = new LiveOnlyPolicyConfiguration(); } - else - { + else { if (sharedStorage) haPolicyConfiguration = new SharedStoreMasterPolicyConfiguration(); else haPolicyConfiguration = new ReplicatedPolicyConfiguration(); } - Configuration configuration = createBasicConfig(node) - .setJournalMaxIO_AIO(1000) - .setThreadPoolMaxSize(10) - .clearAcceptorConfigurations() - .addAcceptorConfiguration(createTransportConfiguration(netty, true, generateParams(node, netty))) - .setHAPolicyConfiguration(haPolicyConfiguration) - .setResolveProtocols(false); + Configuration configuration = createBasicConfig(node).setJournalMaxIO_AIO(1000).setThreadPoolMaxSize(10).clearAcceptorConfigurations().addAcceptorConfiguration(createTransportConfiguration(netty, true, generateParams(node, netty))).setHAPolicyConfiguration(haPolicyConfiguration).setResolveProtocols(false); ActiveMQServer server; - if (fileStorage) - { - if (sharedStorage) - { + if (fileStorage) { + if (sharedStorage) { server = createInVMFailoverServer(true, configuration, nodeManagers[node], node); } - else - { + else { server = createServer(configuration); } } - else - { - if (sharedStorage) - { + else { + if (sharedStorage) { server = createInVMFailoverServer(false, configuration, nodeManagers[node], node); } - else - { + else { server = createServer(false, configuration); } } @@ -1732,10 +1474,8 @@ public abstract class ClusterTestBase extends ActiveMQTestBase final int liveNode, final boolean fileStorage, final boolean sharedStorage, - final boolean netty) throws Exception - { - if (servers[node] != null) - { + final boolean netty) throws Exception { + if (servers[node] != null) { throw new IllegalArgumentException("Already a server at node " + node); } @@ -1743,21 +1483,14 @@ public abstract class ClusterTestBase extends ActiveMQTestBase TransportConfiguration backupConfig = createTransportConfiguration(netty, false, generateParams(node, netty)); TransportConfiguration acceptorConfig = createTransportConfiguration(netty, true, generateParams(node, netty)); - Configuration configuration = createBasicConfig(sharedStorage ? liveNode : node) - .clearAcceptorConfigurations() - .addAcceptorConfiguration(acceptorConfig) - .addConnectorConfiguration(liveConfig.getName(), liveConfig) - .addConnectorConfiguration(backupConfig.getName(), backupConfig) - .setHAPolicyConfiguration(sharedStorage ? new SharedStoreSlavePolicyConfiguration() : new ReplicaPolicyConfiguration()); + Configuration configuration = createBasicConfig(sharedStorage ? liveNode : node).clearAcceptorConfigurations().addAcceptorConfiguration(acceptorConfig).addConnectorConfiguration(liveConfig.getName(), liveConfig).addConnectorConfiguration(backupConfig.getName(), backupConfig).setHAPolicyConfiguration(sharedStorage ? new SharedStoreSlavePolicyConfiguration() : new ReplicaPolicyConfiguration()); ActiveMQServer server; - if (sharedStorage) - { + if (sharedStorage) { server = createInVMFailoverServer(true, configuration, nodeManagers[liveNode], liveNode); } - else - { + else { boolean enablePersistency = fileStorage ? true : configuration.isPersistenceEnabled(); server = addServer(ActiveMQServers.newActiveMQServer(configuration, enablePersistency)); } @@ -1770,10 +1503,8 @@ public abstract class ClusterTestBase extends ActiveMQTestBase final int port, final boolean fileStorage, final boolean netty, - final boolean sharedStorage) throws Exception - { - if (servers[node] != null) - { + final boolean sharedStorage) throws Exception { + if (servers[node] != null) { throw new IllegalArgumentException("Already a server at node " + node); } @@ -1786,48 +1517,27 @@ public abstract class ClusterTestBase extends ActiveMQTestBase UDPBroadcastEndpointFactory endpoint = new UDPBroadcastEndpointFactory().setGroupAddress(groupAddress).setGroupPort(port); - BroadcastGroupConfiguration bcConfig = new BroadcastGroupConfiguration() - .setName("bg1") - .setBroadcastPeriod(200) - .setConnectorInfos(connectorPairs) - .setEndpointFactory(endpoint); + BroadcastGroupConfiguration bcConfig = new BroadcastGroupConfiguration().setName("bg1").setBroadcastPeriod(200).setConnectorInfos(connectorPairs).setEndpointFactory(endpoint); - DiscoveryGroupConfiguration dcConfig = new DiscoveryGroupConfiguration() - .setName("dg1") - .setRefreshTimeout(1000) - .setDiscoveryInitialWaitTimeout(1000) - .setBroadcastEndpointFactory(endpoint); + DiscoveryGroupConfiguration dcConfig = new DiscoveryGroupConfiguration().setName("dg1").setRefreshTimeout(1000).setDiscoveryInitialWaitTimeout(1000).setBroadcastEndpointFactory(endpoint); - Configuration configuration = createBasicConfig(node) - .setJournalMaxIO_AIO(1000) - .clearAcceptorConfigurations() - .addAcceptorConfiguration(createTransportConfiguration(netty, true, params)) - .addConnectorConfiguration(connector.getName(), connector) - .addBroadcastGroupConfiguration(bcConfig) - .addDiscoveryGroupConfiguration(dcConfig.getName(), dcConfig) - .setHAPolicyConfiguration(sharedStorage ? new SharedStoreMasterPolicyConfiguration() : new ReplicatedPolicyConfiguration()); + Configuration configuration = createBasicConfig(node).setJournalMaxIO_AIO(1000).clearAcceptorConfigurations().addAcceptorConfiguration(createTransportConfiguration(netty, true, params)).addConnectorConfiguration(connector.getName(), connector).addBroadcastGroupConfiguration(bcConfig).addDiscoveryGroupConfiguration(dcConfig.getName(), dcConfig).setHAPolicyConfiguration(sharedStorage ? new SharedStoreMasterPolicyConfiguration() : new ReplicatedPolicyConfiguration()); ActiveMQServer server; - if (fileStorage) - { - if (sharedStorage) - { + if (fileStorage) { + if (sharedStorage) { server = createInVMFailoverServer(true, configuration, nodeManagers[node], node); } - else - { + else { server = addServer(ActiveMQServers.newActiveMQServer(configuration)); server.setIdentity("Server " + node); } } - else - { - if (sharedStorage) - { + else { + if (sharedStorage) { server = createInVMFailoverServer(false, configuration, nodeManagers[node], node); } - else - { + else { server = addServer(ActiveMQServers.newActiveMQServer(configuration, false)); server.setIdentity("Server " + node); } @@ -1841,10 +1551,8 @@ public abstract class ClusterTestBase extends ActiveMQTestBase final int port, final boolean fileStorage, final boolean netty, - final boolean sharedStorage) throws Exception - { - if (servers[node] != null) - { + final boolean sharedStorage) throws Exception { + if (servers[node] != null) { throw new IllegalArgumentException("Already a server at node " + node); } @@ -1857,45 +1565,26 @@ public abstract class ClusterTestBase extends ActiveMQTestBase UDPBroadcastEndpointFactory endpoint = new UDPBroadcastEndpointFactory().setGroupAddress(groupAddress).setGroupPort(port); - BroadcastGroupConfiguration bcConfig = new BroadcastGroupConfiguration() - .setName("bg1") - .setBroadcastPeriod(1000) - .setConnectorInfos(connectorPairs) - .setEndpointFactory(endpoint); + BroadcastGroupConfiguration bcConfig = new BroadcastGroupConfiguration().setName("bg1").setBroadcastPeriod(1000).setConnectorInfos(connectorPairs).setEndpointFactory(endpoint); - DiscoveryGroupConfiguration dcConfig = new DiscoveryGroupConfiguration() - .setName("dg1") - .setRefreshTimeout(5000) - .setDiscoveryInitialWaitTimeout(5000) - .setBroadcastEndpointFactory(endpoint); + DiscoveryGroupConfiguration dcConfig = new DiscoveryGroupConfiguration().setName("dg1").setRefreshTimeout(5000).setDiscoveryInitialWaitTimeout(5000).setBroadcastEndpointFactory(endpoint); - Configuration configuration = createBasicConfig(sharedStorage ? liveNode : node) - .clearAcceptorConfigurations() - .addAcceptorConfiguration(createTransportConfiguration(netty, true, params)) - .addConnectorConfiguration(connector.getName(), connector) - .addBroadcastGroupConfiguration(bcConfig) - .addDiscoveryGroupConfiguration(dcConfig.getName(), dcConfig) - .setHAPolicyConfiguration(sharedStorage ? new SharedStoreSlavePolicyConfiguration() : new ReplicatedPolicyConfiguration()); + Configuration configuration = createBasicConfig(sharedStorage ? liveNode : node).clearAcceptorConfigurations().addAcceptorConfiguration(createTransportConfiguration(netty, true, params)).addConnectorConfiguration(connector.getName(), connector).addBroadcastGroupConfiguration(bcConfig).addDiscoveryGroupConfiguration(dcConfig.getName(), dcConfig).setHAPolicyConfiguration(sharedStorage ? new SharedStoreSlavePolicyConfiguration() : new ReplicatedPolicyConfiguration()); ActiveMQServer server; - if (sharedStorage) - { + if (sharedStorage) { server = createInVMFailoverServer(fileStorage, configuration, nodeManagers[liveNode], liveNode); } - else - { + else { boolean enablePersistency = fileStorage ? configuration.isPersistenceEnabled() : false; server = addServer(ActiveMQServers.newActiveMQServer(configuration, enablePersistency)); } servers[node] = server; } - protected void clearServer(final int... nodes) - { - for (int i = 0; i < nodes.length; i++) - { - if (servers[nodes[i]] == null) - { + protected void clearServer(final int... nodes) { + for (int i = 0; i < nodes.length; i++) { + if (servers[nodes[i]] == null) { throw new IllegalArgumentException("No server at node " + nodes[i]); } @@ -1903,10 +1592,8 @@ public abstract class ClusterTestBase extends ActiveMQTestBase } } - protected void clearAllServers() - { - for (int i = 0; i < servers.length; i++) - { + protected void clearAllServers() { + for (int i = 0; i < servers.length; i++) { servers[i] = null; } } @@ -1918,12 +1605,10 @@ public abstract class ClusterTestBase extends ActiveMQTestBase final MessageLoadBalancingType messageLoadBalancingType, final int maxHops, final boolean netty, - final boolean allowDirectConnectionsOnly) - { + final boolean allowDirectConnectionsOnly) { ActiveMQServer serverFrom = servers[nodeFrom]; - if (serverFrom == null) - { + if (serverFrom == null) { throw new IllegalStateException("No server at node " + nodeFrom); } @@ -1932,8 +1617,7 @@ public abstract class ClusterTestBase extends ActiveMQTestBase List pairs = null; - if (nodeTo != -1) - { + if (nodeTo != -1) { TransportConfiguration serverTotc = createTransportConfiguration(netty, false, generateParams(nodeTo, netty)); serverFrom.getConfiguration().getConnectorConfigurations().put(serverTotc.getName(), serverTotc); pairs = new ArrayList(); @@ -1941,16 +1625,7 @@ public abstract class ClusterTestBase extends ActiveMQTestBase } Configuration config = serverFrom.getConfiguration(); - ClusterConnectionConfiguration clusterConf = new ClusterConnectionConfiguration() - .setName(name) - .setAddress(address) - .setConnectorName(name) - .setRetryInterval(100) - .setMessageLoadBalancingType(messageLoadBalancingType) - .setMaxHops(maxHops) - .setConfirmationWindowSize(1024) - .setStaticConnectors(pairs) - .setAllowDirectConnectionsOnly(allowDirectConnectionsOnly); + ClusterConnectionConfiguration clusterConf = new ClusterConnectionConfiguration().setName(name).setAddress(address).setConnectorName(name).setRetryInterval(100).setMessageLoadBalancingType(messageLoadBalancingType).setMaxHops(maxHops).setConfirmationWindowSize(1024).setStaticConnectors(pairs).setAllowDirectConnectionsOnly(allowDirectConnectionsOnly); config.getClusterConfigurations().add(clusterConf); } @@ -1964,12 +1639,10 @@ public abstract class ClusterTestBase extends ActiveMQTestBase final int reconnectAttempts, final long retryInterval, final boolean netty, - final boolean allowDirectConnectionsOnly) - { + final boolean allowDirectConnectionsOnly) { ActiveMQServer serverFrom = servers[nodeFrom]; - if (serverFrom == null) - { + if (serverFrom == null) { throw new IllegalStateException("No server at node " + nodeFrom); } @@ -1978,8 +1651,7 @@ public abstract class ClusterTestBase extends ActiveMQTestBase List pairs = null; - if (nodeTo != -1) - { + if (nodeTo != -1) { TransportConfiguration serverTotc = createTransportConfiguration(netty, false, generateParams(nodeTo, netty)); serverFrom.getConfiguration().getConnectorConfigurations().put(serverTotc.getName(), serverTotc); pairs = new ArrayList(); @@ -1987,17 +1659,7 @@ public abstract class ClusterTestBase extends ActiveMQTestBase } Configuration config = serverFrom.getConfiguration(); - ClusterConnectionConfiguration clusterConf = new ClusterConnectionConfiguration() - .setName(name) - .setAddress(address) - .setConnectorName(name) - .setReconnectAttempts(reconnectAttempts) - .setRetryInterval(retryInterval) - .setMessageLoadBalancingType(messageLoadBalancingType) - .setMaxHops(maxHops) - .setConfirmationWindowSize(1024) - .setStaticConnectors(pairs) - .setAllowDirectConnectionsOnly(allowDirectConnectionsOnly); + ClusterConnectionConfiguration clusterConf = new ClusterConnectionConfiguration().setName(name).setAddress(address).setConnectorName(name).setReconnectAttempts(reconnectAttempts).setRetryInterval(retryInterval).setMessageLoadBalancingType(messageLoadBalancingType).setMaxHops(maxHops).setConfirmationWindowSize(1024).setStaticConnectors(pairs).setAllowDirectConnectionsOnly(allowDirectConnectionsOnly); config.getClusterConfigurations().add(clusterConf); } @@ -2008,12 +1670,10 @@ public abstract class ClusterTestBase extends ActiveMQTestBase final int maxHops, final boolean netty, final int nodeFrom, - final int... nodesTo) - { + final int... nodesTo) { ActiveMQServer serverFrom = servers[nodeFrom]; - if (serverFrom == null) - { + if (serverFrom == null) { throw new IllegalStateException("No server at node " + nodeFrom); } @@ -2021,18 +1681,13 @@ public abstract class ClusterTestBase extends ActiveMQTestBase serverFrom.getConfiguration().getConnectorConfigurations().put(connectorFrom.getName(), connectorFrom); List pairs = new ArrayList(); - for (int element : nodesTo) - { + for (int element : nodesTo) { TransportConfiguration serverTotc = createTransportConfiguration(netty, false, generateParams(element, netty)); serverFrom.getConfiguration().getConnectorConfigurations().put(serverTotc.getName(), serverTotc); pairs.add(serverTotc.getName()); } Configuration config = serverFrom.getConfiguration(); - ClusterConnectionConfiguration clusterConf = - createClusterConfig(name, address, messageLoadBalancingType, - maxHops, - connectorFrom, - pairs); + ClusterConnectionConfiguration clusterConf = createClusterConfig(name, address, messageLoadBalancingType, maxHops, connectorFrom, pairs); config.getClusterConfigurations().add(clusterConf); } @@ -2045,12 +1700,10 @@ public abstract class ClusterTestBase extends ActiveMQTestBase final long retryInterval, final boolean netty, final int nodeFrom, - final int... nodesTo) - { + final int... nodesTo) { ActiveMQServer serverFrom = servers[nodeFrom]; - if (serverFrom == null) - { + if (serverFrom == null) { throw new IllegalStateException("No server at node " + nodeFrom); } @@ -2058,43 +1711,25 @@ public abstract class ClusterTestBase extends ActiveMQTestBase serverFrom.getConfiguration().getConnectorConfigurations().put(connectorFrom.getName(), connectorFrom); List pairs = new ArrayList(); - for (int element : nodesTo) - { + for (int element : nodesTo) { TransportConfiguration serverTotc = createTransportConfiguration(netty, false, generateParams(element, netty)); serverFrom.getConfiguration().getConnectorConfigurations().put(serverTotc.getName(), serverTotc); pairs.add(serverTotc.getName()); } Configuration config = serverFrom.getConfiguration(); - ClusterConnectionConfiguration clusterConf = new ClusterConnectionConfiguration() - .setName(name) - .setAddress(address) - .setConnectorName(connectorFrom.getName()) - .setRetryInterval(retryInterval) - .setReconnectAttempts(reconnectAttempts) - .setCallTimeout(100) - .setCallFailoverTimeout(100) - .setMessageLoadBalancingType(messageLoadBalancingType) - .setMaxHops(maxHops) - .setConfirmationWindowSize(1024) - .setStaticConnectors(pairs); + ClusterConnectionConfiguration clusterConf = new ClusterConnectionConfiguration().setName(name).setAddress(address).setConnectorName(connectorFrom.getName()).setRetryInterval(retryInterval).setReconnectAttempts(reconnectAttempts).setCallTimeout(100).setCallFailoverTimeout(100).setMessageLoadBalancingType(messageLoadBalancingType).setMaxHops(maxHops).setConfirmationWindowSize(1024).setStaticConnectors(pairs); config.getClusterConfigurations().add(clusterConf); } - private ClusterConnectionConfiguration createClusterConfig(final String name, final String address, - final MessageLoadBalancingType messageLoadBalancingType, final int maxHops, - TransportConfiguration connectorFrom, List pairs) - { - return new ClusterConnectionConfiguration() - .setName(name) - .setAddress(address) - .setConnectorName(connectorFrom.getName()) - .setRetryInterval(250) - .setMessageLoadBalancingType(messageLoadBalancingType) - .setMaxHops(maxHops) - .setConfirmationWindowSize(1024) - .setStaticConnectors(pairs); + private ClusterConnectionConfiguration createClusterConfig(final String name, + final String address, + final MessageLoadBalancingType messageLoadBalancingType, + final int maxHops, + TransportConfiguration connectorFrom, + List pairs) { + return new ClusterConnectionConfiguration().setName(name).setAddress(address).setConnectorName(connectorFrom.getName()).setRetryInterval(250).setMessageLoadBalancingType(messageLoadBalancingType).setMaxHops(maxHops).setConfirmationWindowSize(1024).setStaticConnectors(pairs); } protected void setupClusterConnectionWithBackups(final String name, @@ -2103,12 +1738,10 @@ public abstract class ClusterTestBase extends ActiveMQTestBase final int maxHops, final boolean netty, final int nodeFrom, - final int[] nodesTo) - { + final int[] nodesTo) { ActiveMQServer serverFrom = servers[nodeFrom]; - if (serverFrom == null) - { + if (serverFrom == null) { throw new IllegalStateException("No server at node " + nodeFrom); } @@ -2116,23 +1749,14 @@ public abstract class ClusterTestBase extends ActiveMQTestBase serverFrom.getConfiguration().getConnectorConfigurations().put(name, connectorFrom); List pairs = new ArrayList(); - for (int element : nodesTo) - { + for (int element : nodesTo) { TransportConfiguration serverTotc = createTransportConfiguration(netty, false, generateParams(element, netty)); serverFrom.getConfiguration().getConnectorConfigurations().put(serverTotc.getName(), serverTotc); pairs.add(serverTotc.getName()); } Configuration config = serverFrom.getConfiguration(); - ClusterConnectionConfiguration clusterConf = new ClusterConnectionConfiguration() - .setName(name) - .setAddress(address) - .setConnectorName(name) - .setRetryInterval(250) - .setMessageLoadBalancingType(messageLoadBalancingType) - .setMaxHops(maxHops) - .setConfirmationWindowSize(1024) - .setStaticConnectors(pairs); + ClusterConnectionConfiguration clusterConf = new ClusterConnectionConfiguration().setName(name).setAddress(address).setConnectorName(name).setRetryInterval(250).setMessageLoadBalancingType(messageLoadBalancingType).setMaxHops(maxHops).setConfirmationWindowSize(1024).setStaticConnectors(pairs); config.getClusterConfigurations().add(clusterConf); } @@ -2143,43 +1767,29 @@ public abstract class ClusterTestBase extends ActiveMQTestBase final String address, final MessageLoadBalancingType messageLoadBalancingType, final int maxHops, - final boolean netty) - { + final boolean netty) { ActiveMQServer server = servers[node]; - if (server == null) - { + if (server == null) { throw new IllegalStateException("No server at node " + node); } TransportConfiguration connectorConfig = createTransportConfiguration(netty, false, generateParams(node, netty)); server.getConfiguration().getConnectorConfigurations().put(name, connectorConfig); Configuration config = server.getConfiguration(); - ClusterConnectionConfiguration clusterConf = new ClusterConnectionConfiguration() - .setName(name) - .setAddress(address) - .setConnectorName(name) - .setRetryInterval(100) - .setDuplicateDetection(true) - .setMessageLoadBalancingType(messageLoadBalancingType) - .setMaxHops(maxHops) - .setConfirmationWindowSize(1024) - .setDiscoveryGroupName(discoveryGroupName); + ClusterConnectionConfiguration clusterConf = new ClusterConnectionConfiguration().setName(name).setAddress(address).setConnectorName(name).setRetryInterval(100).setDuplicateDetection(true).setMessageLoadBalancingType(messageLoadBalancingType).setMaxHops(maxHops).setConfirmationWindowSize(1024).setDiscoveryGroupName(discoveryGroupName); List clusterConfs = config.getClusterConfigurations(); clusterConfs.add(clusterConf); } - protected void startServers(final int... nodes) throws Exception - { - for (int node : nodes) - { + protected void startServers(final int... nodes) throws Exception { + for (int node : nodes) { log.info("#test start node " + node); final long currentTime = System.currentTimeMillis(); boolean waitForSelf = currentTime - timeStarts[node] < TIMEOUT_START_SERVER; boolean waitForPrevious = node > 0 && currentTime - timeStarts[node - 1] < TIMEOUT_START_SERVER; - if (waitForPrevious || waitForSelf) - { + if (waitForPrevious || waitForSelf) { Thread.sleep(TIMEOUT_START_SERVER); } timeStarts[node] = System.currentTimeMillis(); @@ -2191,14 +1801,10 @@ public abstract class ClusterTestBase extends ActiveMQTestBase } } - protected void stopClusterConnections(final int... nodes) throws Exception - { - for (int node : nodes) - { - if (servers[node].isStarted()) - { - for (ClusterConnection cc : servers[node].getClusterManager().getClusterConnections()) - { + protected void stopClusterConnections(final int... nodes) throws Exception { + for (int node : nodes) { + if (servers[node].isStarted()) { + for (ClusterConnection cc : servers[node].getClusterManager().getClusterConnections()) { cc.stop(); cc.flushExecutor(); } @@ -2206,18 +1812,13 @@ public abstract class ClusterTestBase extends ActiveMQTestBase } } - protected void stopServers(final int... nodes) throws Exception - { + protected void stopServers(final int... nodes) throws Exception { log.info("Stopping nodes " + Arrays.toString(nodes)); Exception exception = null; - for (int node : nodes) - { - if (servers[node] != null && servers[node].isStarted()) - { - try - { - if (System.currentTimeMillis() - timeStarts[node] < TIMEOUT_START_SERVER) - { + for (int node : nodes) { + if (servers[node] != null && servers[node].isStarted()) { + try { + if (System.currentTimeMillis() - timeStarts[node] < TIMEOUT_START_SERVER) { // We can't stop and start a node too fast (faster than what the Topology could realize about this Thread.sleep(TIMEOUT_START_SERVER); } @@ -2228,8 +1829,7 @@ public abstract class ClusterTestBase extends ActiveMQTestBase servers[node].stop(); log.info("server " + node + " stopped"); } - catch (Exception e) - { + catch (Exception e) { exception = e; } } @@ -2238,8 +1838,7 @@ public abstract class ClusterTestBase extends ActiveMQTestBase throw exception; } - protected boolean isFileStorage() - { + protected boolean isFileStorage() { return true; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/ClusterWithBackupTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/ClusterWithBackupTest.java index 0e5c2a1a25..c806e3b957 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/ClusterWithBackupTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/ClusterWithBackupTest.java @@ -15,35 +15,32 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.cluster.distribution; + import org.apache.activemq.artemis.core.server.cluster.impl.MessageLoadBalancingType; import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; import org.junit.Before; import org.junit.Test; -public class ClusterWithBackupTest extends ClusterTestBase -{ +public class ClusterWithBackupTest extends ClusterTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); setupServers(); } - protected boolean isNetty() - { + protected boolean isNetty() { return false; } @Test - public void testBasicRoundRobin() throws Throwable - { - try - { + public void testBasicRoundRobin() throws Throwable { + try { setupCluster(); startServers(0, 1, 2, 3, 4, 5); @@ -74,21 +71,18 @@ public class ClusterWithBackupTest extends ClusterTestBase verifyNotReceive(0, 0, 1, 2); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); log.error(e.getMessage(), e); throw e; } } - protected void setupCluster() throws Exception - { + protected void setupCluster() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); } - protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception - { + protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception { setupClusterConnection("cluster0", "queues", messageLoadBalancingType, 1, isNetty(), 3, 4, 5); setupClusterConnection("cluster1", "queues", messageLoadBalancingType, 1, isNetty(), 4, 3, 5); @@ -102,8 +96,7 @@ public class ClusterWithBackupTest extends ClusterTestBase setupClusterConnection("cluster2", "queues", messageLoadBalancingType, 1, isNetty(), 2, 3, 4); } - protected void setupServers() throws Exception - { + protected void setupServers() throws Exception { // The backups setupBackupServer(0, 3, isFileStorage(), true, isNetty()); setupBackupServer(1, 4, isFileStorage(), true, isNetty()); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/ClusteredGroupingTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/ClusteredGroupingTest.java index d4446a8190..7408ab6dec 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/ClusteredGroupingTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/ClusteredGroupingTest.java @@ -50,12 +50,10 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -public class ClusteredGroupingTest extends ClusterTestBase -{ +public class ClusteredGroupingTest extends ClusterTestBase { @Test - public void testGroupingGroupTimeoutWithUnproposal() throws Exception - { + public void testGroupingGroupTimeoutWithUnproposal() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); @@ -92,26 +90,22 @@ public class ClusteredGroupingTest extends ClusterTestBase final CountDownLatch latch = new CountDownLatch(4); - getServer(1).getManagementService().addNotificationListener(new NotificationListener() - { + getServer(1).getManagementService().addNotificationListener(new NotificationListener() { @Override - public void onNotification(Notification notification) - { - if (!(notification.getType() instanceof CoreNotificationType)) return; - if (notification.getType() == CoreNotificationType.UNPROPOSAL) - { + public void onNotification(Notification notification) { + if (!(notification.getType() instanceof CoreNotificationType)) + return; + if (notification.getType() == CoreNotificationType.UNPROPOSAL) { latch.countDown(); } } }); - getServer(2).getManagementService().addNotificationListener(new NotificationListener() - { + getServer(2).getManagementService().addNotificationListener(new NotificationListener() { @Override - public void onNotification(Notification notification) - { - if (!(notification.getType() instanceof CoreNotificationType)) return; - if (notification.getType() == CoreNotificationType.UNPROPOSAL) - { + public void onNotification(Notification notification) { + if (!(notification.getType() instanceof CoreNotificationType)) + return; + if (notification.getType() == CoreNotificationType.UNPROPOSAL) { latch.countDown(); } } @@ -131,15 +125,12 @@ public class ClusteredGroupingTest extends ClusterTestBase assertTrue(latch.await(5, TimeUnit.SECONDS)); long timeLimit = System.currentTimeMillis() + 5000; - while (timeLimit > System.currentTimeMillis() && queue0Server2.getGroupsUsed().size() != 0) - { + while (timeLimit > System.currentTimeMillis() && queue0Server2.getGroupsUsed().size() != 0) { Thread.sleep(10); } - assertEquals("Unproposal should cleanup the queue group as well", 0, queue0Server2.getGroupsUsed().size()); - removeConsumer(0); assertTrue(latch.await(5, TimeUnit.SECONDS)); @@ -163,8 +154,7 @@ public class ClusteredGroupingTest extends ClusterTestBase } @Test - public void testGroupingGroupTimeoutSendRemote() throws Exception - { + public void testGroupingGroupTimeoutSendRemote() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); @@ -201,26 +191,22 @@ public class ClusteredGroupingTest extends ClusterTestBase final CountDownLatch latch = new CountDownLatch(4); - getServer(1).getManagementService().addNotificationListener(new NotificationListener() - { + getServer(1).getManagementService().addNotificationListener(new NotificationListener() { @Override - public void onNotification(Notification notification) - { - if (!(notification.getType() instanceof CoreNotificationType)) return; - if (notification.getType() == CoreNotificationType.UNPROPOSAL) - { + public void onNotification(Notification notification) { + if (!(notification.getType() instanceof CoreNotificationType)) + return; + if (notification.getType() == CoreNotificationType.UNPROPOSAL) { latch.countDown(); } } }); - getServer(2).getManagementService().addNotificationListener(new NotificationListener() - { + getServer(2).getManagementService().addNotificationListener(new NotificationListener() { @Override - public void onNotification(Notification notification) - { - if (!(notification.getType() instanceof CoreNotificationType)) return; - if (notification.getType() == CoreNotificationType.UNPROPOSAL) - { + public void onNotification(Notification notification) { + if (!(notification.getType() instanceof CoreNotificationType)) + return; + if (notification.getType() == CoreNotificationType.UNPROPOSAL) { latch.countDown(); } } @@ -256,8 +242,7 @@ public class ClusteredGroupingTest extends ClusterTestBase } @Test - public void testGroupingSimple() throws Exception - { + public void testGroupingSimple() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); @@ -298,13 +283,11 @@ public class ClusteredGroupingTest extends ClusterTestBase verifyReceiveAll(10, 0); - } // Fail a node where there's a consumer only.. with messages being sent by a node that is not the local @Test - public void testGroupingSimpleFail2nd() throws Exception - { + public void testGroupingSimpleFail2nd() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); @@ -364,14 +347,12 @@ public class ClusteredGroupingTest extends ClusterTestBase msg.acknowledge(); assertNull(consumers[2].getConsumer().receiveImmediate()); - // it should be bound to server1 as we used the group from server1 sendWithProperty(2, "queues.testaddress", 1, false, Message.HDR_GROUP_ID, groupIDOnConsumer1); msg = consumers[1].getConsumer().receive(1000); assertNotNull(msg); msg.acknowledge(); - closeAllConsumers(); closeAllSessionFactories(); @@ -387,14 +368,12 @@ public class ClusteredGroupingTest extends ClusterTestBase startServers(2, 0); assertTrue("The group start should have waited the timeout on groups", System.currentTimeMillis() >= time + TIMEOUT_GROUPS); - setupSessionFactory(0, isNetty()); setupSessionFactory(2, isNetty()); addConsumer(0, 0, "queue0", null); addConsumer(2, 2, "queue0", null); - waitForBindings(0, "queues.testaddress", 1, 1, false); waitForBindings(2, "queues.testaddress", 1, 1, false); @@ -403,8 +382,7 @@ public class ClusteredGroupingTest extends ClusterTestBase // server1 is dead, so either 0 or 2 should receive since the group is now dead msg = consumers[0].getConsumer().receive(500); - if (msg == null) - { + if (msg == null) { msg = consumers[2].getConsumer().receive(500); } @@ -415,12 +393,10 @@ public class ClusteredGroupingTest extends ClusterTestBase assertNotNull(msg); msg.acknowledge(); - } @Test - public void testGroupTimeout() throws Exception - { + public void testGroupTimeout() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); @@ -461,15 +437,13 @@ public class ClusteredGroupingTest extends ClusterTestBase sendWithProperty(0, "queues.testaddress", 1, false, Message.HDR_GROUP_ID, new SimpleString("id2")); sendWithProperty(0, "queues.testaddress", 1, false, Message.HDR_GROUP_ID, new SimpleString("id3")); - assertNotNull(servers[0].getGroupingHandler().getProposal(SimpleString.toSimpleString("id1.queue0"), false)); // Group timeout Thread.sleep(1000); long timeLimit = System.currentTimeMillis() + 5000; - while (timeLimit > System.currentTimeMillis() && servers[0].getGroupingHandler().getProposal(SimpleString.toSimpleString("id1.queue0"), false) != null) - { + while (timeLimit > System.currentTimeMillis() && servers[0].getGroupingHandler().getProposal(SimpleString.toSimpleString("id1.queue0"), false) != null) { Thread.sleep(10); } Thread.sleep(1000); @@ -479,17 +453,14 @@ public class ClusteredGroupingTest extends ClusterTestBase sendWithProperty(0, "queues.testaddress", 1, false, Message.HDR_GROUP_ID, new SimpleString("id1")); sendWithProperty(1, "queues.testaddress", 1, false, Message.HDR_GROUP_ID, new SimpleString("id1")); - // Verify why this is failing... whyt it's creating a new one here???? assertNotNull(servers[0].getGroupingHandler().getProposal(SimpleString.toSimpleString("id1.queue0"), false)); assertNotNull(servers[1].getGroupingHandler().getProposal(SimpleString.toSimpleString("id1.queue0"), false)); - timeLimit = System.currentTimeMillis() + 1500; // We will keep bothering server1 as it will ping server0 eventually - while (timeLimit > System.currentTimeMillis() && servers[1].getGroupingHandler().getProposal(SimpleString.toSimpleString("id1.queue0"), true) != null) - { + while (timeLimit > System.currentTimeMillis() && servers[1].getGroupingHandler().getProposal(SimpleString.toSimpleString("id1.queue0"), true) != null) { assertNotNull(servers[0].getGroupingHandler().getProposal(SimpleString.toSimpleString("id1.queue0"), false)); Thread.sleep(10); } @@ -498,8 +469,7 @@ public class ClusteredGroupingTest extends ClusterTestBase Thread.sleep(1000); timeLimit = System.currentTimeMillis() + 5000; - while (timeLimit > System.currentTimeMillis() && servers[0].getGroupingHandler().getProposal(SimpleString.toSimpleString("id1.queue0"), false) != null) - { + while (timeLimit > System.currentTimeMillis() && servers[0].getGroupingHandler().getProposal(SimpleString.toSimpleString("id1.queue0"), false) != null) { Thread.sleep(10); } @@ -507,8 +477,7 @@ public class ClusteredGroupingTest extends ClusterTestBase } @Test - public void testGroupingWith3Nodes() throws Exception - { + public void testGroupingWith3Nodes() throws Exception { final String ADDRESS = "queues.testaddress"; final String QUEUE = "queue0"; @@ -562,15 +531,13 @@ public class ClusteredGroupingTest extends ClusterTestBase final AtomicInteger totalMessageProduced = new AtomicInteger(0); // create a bunch of groups and save a few group IDs for use later - for (int i = 0; i < 500; i++) - { + for (int i = 0; i < 500; i++) { ClientMessage message = session.createMessage(true); String group = UUID.randomUUID().toString(); message.putStringProperty(Message.HDR_GROUP_ID, new SimpleString(group)); SimpleString dupID = new SimpleString(UUID.randomUUID().toString()); message.putStringProperty(Message.HDR_DUPLICATE_DETECTION_ID, dupID); - if (i % 100 == 0) - { + if (i % 100 == 0) { groups.add(group); } producer.send(message); @@ -593,13 +560,10 @@ public class ClusteredGroupingTest extends ClusterTestBase final long timeToRun = System.currentTimeMillis() + 5000; // spin up a bunch of threads to pump messages into some of the groups - for (final String groupx : groups) - { - final Runnable r = new Runnable() - { + for (final String groupx : groups) { + final Runnable r = new Runnable() { @Override - public void run() - { + public void run() { String group = groupx; @@ -610,30 +574,25 @@ public class ClusteredGroupingTest extends ClusterTestBase ClientProducer producer = null; int targetServer = 0; - try - { + try { int count = producerCounter.incrementAndGet(); - if (count % 3 == 0) - { + if (count % 3 == 0) { factory = sf2; targetServer = 2; } - else if (count % 2 == 0) - { + else if (count % 2 == 0) { factory = sf1; targetServer = 1; } - else - { + else { factory = sf0; } IntegrationTestLogger.LOGGER.debug("Creating producer session factory to node " + targetServer); session = addClientSession(factory.createSession(false, true, true)); producer = addClientProducer(session.createProducer(ADDRESS)); } - catch (Exception e) - { + catch (Exception e) { errors.incrementAndGet(); IntegrationTestLogger.LOGGER.warn("Producer thread couldn't establish connection", e); return; @@ -641,26 +600,22 @@ public class ClusteredGroupingTest extends ClusterTestBase int messageCount = 0; - while (timeToRun > System.currentTimeMillis()) - { + while (timeToRun > System.currentTimeMillis()) { ClientMessage message = session.createMessage(true); message.putStringProperty(Message.HDR_GROUP_ID, new SimpleString(group)); SimpleString dupID = new SimpleString(basicID + ":" + messageCount); message.putStringProperty(Message.HDR_DUPLICATE_DETECTION_ID, dupID); - try - { + try { producer.send(message); totalMessageProduced.incrementAndGet(); messageCount++; } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { IntegrationTestLogger.LOGGER.warn("Producer thread threw exception while sending messages to " + targetServer + ": " + e.getMessage()); // in case of a failure we change the group to make possible errors more likely group = group + "afterFail"; } - catch (Exception e) - { + catch (Exception e) { IntegrationTestLogger.LOGGER.warn("Producer thread threw unexpected exception while sending messages to " + targetServer + ": " + e.getMessage()); group = group + "afterFail"; break; @@ -674,28 +629,21 @@ public class ClusteredGroupingTest extends ClusterTestBase executorService.execute(r); } - - Runnable r = new Runnable() - { + Runnable r = new Runnable() { @Override - public void run() - { - try - { - try - { + public void run() { + try { + try { Thread.sleep(2000); } - catch (InterruptedException e) - { + catch (InterruptedException e) { e.printStackTrace(); // ignore } System.out.println("Cycling server"); cycleServer(1); } - finally - { + finally { okToConsume.countDown(); } } @@ -708,20 +656,15 @@ public class ClusteredGroupingTest extends ClusterTestBase final CountDownLatch okToEndTest = new CountDownLatch(groups.size()); // spin up a bunch of threads to consume messages - for (final String group : groups) - { - r = new Runnable() - { + for (final String group : groups) { + r = new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { IntegrationTestLogger.LOGGER.info("Waiting to start consumer thread..."); okToConsume.await(20, TimeUnit.SECONDS); } - catch (InterruptedException e) - { + catch (InterruptedException e) { e.printStackTrace(); return; } @@ -731,22 +674,17 @@ public class ClusteredGroupingTest extends ClusterTestBase ClientConsumer consumer = null; int targetServer = 0; - try - { - synchronized (consumerCounter) - { - if (consumerCounter.get() % 3 == 0) - { + try { + synchronized (consumerCounter) { + if (consumerCounter.get() % 3 == 0) { factory = sf2; targetServer = 2; } - else if (consumerCounter.get() % 2 == 0) - { + else if (consumerCounter.get() % 2 == 0) { factory = sf1; targetServer = 1; } - else - { + else { factory = sf0; } IntegrationTestLogger.LOGGER.info("Creating consumer session factory to node " + targetServer); @@ -756,33 +694,27 @@ public class ClusteredGroupingTest extends ClusterTestBase consumerCounter.incrementAndGet(); } } - catch (Exception e) - { + catch (Exception e) { IntegrationTestLogger.LOGGER.info("Consumer thread couldn't establish connection", e); errors.incrementAndGet(); return; } - while (true) - { - try - { + while (true) { + try { ClientMessage m = consumer.receive(1000); - if (m == null) - { + if (m == null) { okToEndTest.countDown(); return; } m.acknowledge(); IntegrationTestLogger.LOGGER.trace("Consumed message " + m.getStringProperty(Message.HDR_DUPLICATE_DETECTION_ID) + " from server " + targetServer + ". Total consumed: " + totalMessagesConsumed.incrementAndGet()); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { errors.incrementAndGet(); IntegrationTestLogger.LOGGER.warn("Consumer thread threw exception while receiving messages from server " + targetServer + ".: " + e.getMessage()); } - catch (Exception e) - { + catch (Exception e) { errors.incrementAndGet(); IntegrationTestLogger.LOGGER.warn("Consumer thread threw unexpected exception while receiving messages from server " + targetServer + ".: " + e.getMessage()); return; @@ -804,22 +736,18 @@ public class ClusteredGroupingTest extends ClusterTestBase assertEquals(totalMessageProduced.longValue(), totalMessagesConsumed.longValue()); } - private void cycleServer(int node) - { - try - { + private void cycleServer(int node) { + try { stopServers(node); startServers(node); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @Test - public void testGroupingBindingNotPresentAtStart() throws Exception - { + public void testGroupingBindingNotPresentAtStart() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); @@ -897,10 +825,8 @@ public class ClusteredGroupingTest extends ClusterTestBase verifyReceiveAll(1, 0, 1, 2); } - @Test - public void testGroupingBindingsRemoved() throws Exception - { + public void testGroupingBindingsRemoved() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); @@ -978,8 +904,7 @@ public class ClusteredGroupingTest extends ClusterTestBase } @Test - public void testTimeoutOnSending() throws Exception - { + public void testTimeoutOnSending() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); @@ -996,102 +921,83 @@ public class ClusteredGroupingTest extends ClusterTestBase final CountDownLatch latch = new CountDownLatch(BindingsImpl.MAX_GROUP_RETRY); - setUpGroupHandler(new GroupingHandler() - { - + setUpGroupHandler(new GroupingHandler() { @Override - public void awaitBindings() throws Exception - { + public void awaitBindings() throws Exception { } @Override - public void addListener(UnproposalListener listener) - { + public void addListener(UnproposalListener listener) { } @Override - public void resendPending() throws Exception - { + public void resendPending() throws Exception { } @Override - public void remove(SimpleString groupid, SimpleString clusterName) throws Exception - { + public void remove(SimpleString groupid, SimpleString clusterName) throws Exception { } @Override - public void forceRemove(SimpleString groupid, SimpleString clusterName) throws Exception - { + public void forceRemove(SimpleString groupid, SimpleString clusterName) throws Exception { } - public SimpleString getName() - { + public SimpleString getName() { return null; } @Override - public void remove(SimpleString id, SimpleString groupId, int distance) - { + public void remove(SimpleString id, SimpleString groupId, int distance) { //To change body of implemented methods use File | Settings | File Templates. } @Override - public void start() throws Exception - { + public void start() throws Exception { //To change body of implemented methods use File | Settings | File Templates. } @Override - public void stop() throws Exception - { + public void stop() throws Exception { //To change body of implemented methods use File | Settings | File Templates. } @Override - public boolean isStarted() - { + public boolean isStarted() { return false; } - public Response propose(final Proposal proposal) throws Exception - { + public Response propose(final Proposal proposal) throws Exception { return null; } - public void proposed(final Response response) throws Exception - { + public void proposed(final Response response) throws Exception { System.out.println("ClusteredGroupingTest.proposed"); } - public void sendProposalResponse(final Response response, final int distance) throws Exception - { + public void sendProposalResponse(final Response response, final int distance) throws Exception { System.out.println("ClusteredGroupingTest.send"); } - public Response receive(final Proposal proposal, final int distance) throws Exception - { + public Response receive(final Proposal proposal, final int distance) throws Exception { latch.countDown(); return null; } - public void onNotification(final Notification notification) - { + public void onNotification(final Notification notification) { System.out.println("ClusteredGroupingTest.onNotification " + notification); } - public void addGroupBinding(final GroupBinding groupBinding) - { + public void addGroupBinding(final GroupBinding groupBinding) { System.out.println("ClusteredGroupingTest.addGroupBinding"); } - public Response getProposal(final SimpleString fullID, boolean touchTime) - { + public Response getProposal(final SimpleString fullID, boolean touchTime) { return null; } @@ -1119,24 +1025,20 @@ public class ClusteredGroupingTest extends ClusterTestBase waitForBindings(1, "queues.testaddress", 2, 2, false); waitForBindings(2, "queues.testaddress", 2, 2, false); - try - { + try { sendWithProperty(1, "queues.testaddress", 1, false, Message.HDR_GROUP_ID, new SimpleString("id1")); // it should get the Retries on the latch assertTrue(latch.await(10, TimeUnit.SECONDS)); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); // To change body of catch statement use File | Settings | File Templates. } } - @Test - public void testGroupingSendTo2queues() throws Exception - { + public void testGroupingSendTo2queues() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); @@ -1182,8 +1084,7 @@ public class ClusteredGroupingTest extends ClusterTestBase } @Test - public void testGroupingSendTo3queues() throws Exception - { + public void testGroupingSendTo3queues() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); @@ -1233,8 +1134,7 @@ public class ClusteredGroupingTest extends ClusterTestBase } @Test - public void testGroupingSendTo3queuesRemoteArbitrator() throws Exception - { + public void testGroupingSendTo3queuesRemoteArbitrator() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); @@ -1280,8 +1180,7 @@ public class ClusteredGroupingTest extends ClusterTestBase } @Test - public void testGroupingSendTo3queuesNoConsumerOnLocalQueue() throws Exception - { + public void testGroupingSendTo3queuesNoConsumerOnLocalQueue() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); @@ -1330,8 +1229,7 @@ public class ClusteredGroupingTest extends ClusterTestBase } @Test - public void testGroupingRoundRobin() throws Exception - { + public void testGroupingRoundRobin() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); @@ -1376,8 +1274,7 @@ public class ClusteredGroupingTest extends ClusterTestBase } @Test - public void testGroupingSendTo3queuesQueueRemoved() throws Exception - { + public void testGroupingSendTo3queuesQueueRemoved() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); @@ -1446,8 +1343,7 @@ public class ClusteredGroupingTest extends ClusterTestBase } @Test - public void testGroupingSendTo3queuesPinnedNodeGoesDown() throws Exception - { + public void testGroupingSendTo3queuesPinnedNodeGoesDown() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); @@ -1509,8 +1405,7 @@ public class ClusteredGroupingTest extends ClusterTestBase } @Test - public void testGroupingSendTo3queuesPinnedNodeGoesDownSendBeforeStop() throws Exception - { + public void testGroupingSendTo3queuesPinnedNodeGoesDownSendBeforeStop() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); @@ -1572,8 +1467,7 @@ public class ClusteredGroupingTest extends ClusterTestBase } @Test - public void testGroupingSendTo3queuesPinnedNodeGoesDownSendAfterRestart() throws Exception - { + public void testGroupingSendTo3queuesPinnedNodeGoesDownSendAfterRestart() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); @@ -1630,8 +1524,7 @@ public class ClusteredGroupingTest extends ClusterTestBase } @Test - public void testGroupingMultipleQueuesOnAddress() throws Exception - { + public void testGroupingMultipleQueuesOnAddress() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); @@ -1681,8 +1574,7 @@ public class ClusteredGroupingTest extends ClusterTestBase } - public void testGroupingMultipleSending() throws Exception - { + public void testGroupingMultipleSending() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); @@ -1721,25 +1613,22 @@ public class ClusteredGroupingTest extends ClusterTestBase CountDownLatch latch = new CountDownLatch(1); Thread[] threads = new Thread[9]; int range = 0; - for (int i = 0; i < 9; i++, range += 10) - { + for (int i = 0; i < 9; i++, range += 10) { threads[i] = new Thread(new ThreadSender(range, range + 10, 1, new SimpleString("id" + i), latch, i < 8)); } - for (Thread thread : threads) - { + for (Thread thread : threads) { thread.start(); } verifyReceiveAllWithGroupIDRoundRobin(0, 30, 0, 1, 2); } - public boolean isNetty() - { + public boolean isNetty() { return true; } - class ThreadSender implements Runnable - { + class ThreadSender implements Runnable { + private final int msgStart; private final int msgEnd; @@ -1757,8 +1646,7 @@ public class ClusteredGroupingTest extends ClusterTestBase final int node, final SimpleString id, final CountDownLatch latch, - final boolean wait) - { + final boolean wait) { this.msgStart = msgStart; this.msgEnd = msgEnd; this.node = node; @@ -1767,29 +1655,22 @@ public class ClusteredGroupingTest extends ClusterTestBase this.wait = wait; } - public void run() - { - if (wait) - { - try - { + public void run() { + if (wait) { + try { latch.await(5, TimeUnit.SECONDS); } - catch (InterruptedException e) - { + catch (InterruptedException e) { e.printStackTrace(); // To change body of catch statement use File | Settings | File Templates. } } - else - { + else { latch.countDown(); } - try - { + try { sendInRange(node, "queues.testaddress", msgStart, msgEnd, false, Message.HDR_GROUP_ID, id); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); // To change body of catch statement use File | Settings | File Templates. } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/ClusteredRequestResponseTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/ClusteredRequestResponseTest.java index 9dc4123165..efbbac8243 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/ClusteredRequestResponseTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/ClusteredRequestResponseTest.java @@ -20,33 +20,27 @@ import org.apache.activemq.artemis.core.server.cluster.impl.MessageLoadBalancing import org.junit.Before; import org.junit.Test; - -public class ClusteredRequestResponseTest extends ClusterTestBase -{ +public class ClusteredRequestResponseTest extends ClusterTestBase { @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); setupServers(); } - protected boolean isNetty() - { + protected boolean isNetty() { return false; } @Test - public void testRequestResponse() throws Exception - { + public void testRequestResponse() throws Exception { setupCluster(); startServers(0, 1, 2, 3, 4); - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { waitForTopology(servers[i], 5); } @@ -89,14 +83,12 @@ public class ClusteredRequestResponseTest extends ClusterTestBase * * TODO: I believe this test is invalid. I'm just ignoring it for now. It will probably go away */ - public void invalidTest_testRequestResponseNoWaitForBindings() throws Exception - { + public void invalidTest_testRequestResponseNoWaitForBindings() throws Exception { setupCluster(); startServers(0, 1, 2, 3, 4); - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { waitForTopology(servers[i], 5); } @@ -128,13 +120,11 @@ public class ClusteredRequestResponseTest extends ClusterTestBase verifyReceiveAll(10, 0); } - protected void setupCluster() throws Exception - { + protected void setupCluster() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); } - protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception - { + protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception { setupClusterConnection("cluster0", "queues", messageLoadBalancingType, 1, isNetty(), 0, 1, 2, 3, 4); setupClusterConnection("cluster1", "queues", messageLoadBalancingType, 1, isNetty(), 1, 0, 2, 3, 4); @@ -146,8 +136,7 @@ public class ClusteredRequestResponseTest extends ClusterTestBase setupClusterConnection("cluster4", "queues", messageLoadBalancingType, 1, isNetty(), 4, 0, 1, 2, 3); } - protected void setupServers() throws Exception - { + protected void setupServers() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/LargeMessageRedistributionTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/LargeMessageRedistributionTest.java index f68dd43ae1..e7824a7897 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/LargeMessageRedistributionTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/LargeMessageRedistributionTest.java @@ -16,11 +16,9 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.distribution; -public class LargeMessageRedistributionTest extends MessageRedistributionTest -{ +public class LargeMessageRedistributionTest extends MessageRedistributionTest { - public boolean isLargeMessage() - { + public boolean isLargeMessage() { return true; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/MessageLoadBalancingTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/MessageLoadBalancingTest.java index 3cd9e61547..37c23305d9 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/MessageLoadBalancingTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/MessageLoadBalancingTest.java @@ -23,32 +23,28 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class MessageLoadBalancingTest extends ClusterTestBase -{ +public class MessageLoadBalancingTest extends ClusterTestBase { + @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); start(); } - private void start() throws Exception - { + private void start() throws Exception { setupServers(); setRedistributionDelay(0); } - protected boolean isNetty() - { + protected boolean isNetty() { return false; } @Test - public void testMessageLoadBalancingOff() throws Exception - { + public void testMessageLoadBalancingOff() throws Exception { setupCluster(MessageLoadBalancingType.OFF); startServers(0, 1); @@ -80,8 +76,7 @@ public class MessageLoadBalancingTest extends ClusterTestBase ClientMessage message = getConsumer(1).receive(1000); Assert.assertNull(message); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { message = getConsumer(0).receive(5000); Assert.assertNotNull("" + i, message); message.acknowledge(); @@ -91,29 +86,25 @@ public class MessageLoadBalancingTest extends ClusterTestBase Assert.assertNull(clientMessage); } - protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception - { + protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception { setupClusterConnection("cluster0", "queues", messageLoadBalancingType, 1, isNetty(), 0, 1); setupClusterConnection("cluster1", "queues", messageLoadBalancingType, 1, isNetty(), 1, 0); } - protected void setRedistributionDelay(final long delay) - { + protected void setRedistributionDelay(final long delay) { AddressSettings as = new AddressSettings().setRedistributionDelay(delay); getServer(0).getAddressSettingsRepository().addMatch("queues.*", as); getServer(1).getAddressSettingsRepository().addMatch("queues.*", as); } - protected void setupServers() throws Exception - { + protected void setupServers() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); } - protected void stopServers() throws Exception - { + protected void stopServers() throws Exception { closeAllConsumers(); closeAllSessionFactories(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/MessageRedistributionTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/MessageRedistributionTest.java index d294e75f95..7d36cc2033 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/MessageRedistributionTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/MessageRedistributionTest.java @@ -41,48 +41,37 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class MessageRedistributionTest extends ClusterTestBase -{ +public class MessageRedistributionTest extends ClusterTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); start(); } - private void start() throws Exception - { + private void start() throws Exception { setupServers(); setRedistributionDelay(0); } - protected boolean isNetty() - { + protected boolean isNetty() { return false; } //https://issues.jboss.org/browse/HORNETQ-1061 @Test - public void testRedistributionWithMessageGroups() throws Exception - { + public void testRedistributionWithMessageGroups() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); MessageRedistributionTest.log.info("Doing test"); - - getServer(0).getConfiguration().setGroupingHandlerConfiguration(new GroupingHandlerConfiguration() - .setName(new SimpleString("handler")) - .setType(GroupingHandlerConfiguration.TYPE.LOCAL) - .setAddress(new SimpleString("queues"))); - getServer(1).getConfiguration().setGroupingHandlerConfiguration(new GroupingHandlerConfiguration() - .setName(new SimpleString("handler")) - .setType(GroupingHandlerConfiguration.TYPE.REMOTE) - .setAddress(new SimpleString("queues"))); + getServer(0).getConfiguration().setGroupingHandlerConfiguration(new GroupingHandlerConfiguration().setName(new SimpleString("handler")).setType(GroupingHandlerConfiguration.TYPE.LOCAL).setAddress(new SimpleString("queues"))); + getServer(1).getConfiguration().setGroupingHandlerConfiguration(new GroupingHandlerConfiguration().setName(new SimpleString("handler")).setType(GroupingHandlerConfiguration.TYPE.REMOTE).setAddress(new SimpleString("queues"))); startServers(0, 1); @@ -114,8 +103,7 @@ public class MessageRedistributionTest extends ClusterTestBase send(0, "queues.testaddress", 10, false, null); //consume half of the grouped messages from node 1 - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { ClientMessage message = getConsumer(1).receive(1000); Assert.assertNotNull(message); message.acknowledge(); @@ -123,8 +111,7 @@ public class MessageRedistributionTest extends ClusterTestBase } //now consume the non grouped messages from node 1 where they are pinned - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { ClientMessage message = getConsumer(0).receive(5000); Assert.assertNotNull("" + i, message); message.acknowledge(); @@ -141,11 +128,9 @@ public class MessageRedistributionTest extends ClusterTestBase removeConsumer(1); //consume the non grouped messages - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { ClientMessage message = getConsumer(0).receive(5000); - if (message == null) - { + if (message == null) { System.out.println(); } Assert.assertNotNull("" + i, message); @@ -161,8 +146,7 @@ public class MessageRedistributionTest extends ClusterTestBase addConsumer(1, 1, "queue0", null); //now we see the grouped messages are still on the same node - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { ClientMessage message = getConsumer(1).receive(1000); Assert.assertNotNull(message); message.acknowledge(); @@ -173,8 +157,7 @@ public class MessageRedistributionTest extends ClusterTestBase //https://issues.jboss.org/browse/HORNETQ-1057 @Test - public void testRedistributionStopsWhenConsumerAdded() throws Exception - { + public void testRedistributionStopsWhenConsumerAdded() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); MessageRedistributionTest.log.info("Doing test"); @@ -211,8 +194,7 @@ public class MessageRedistributionTest extends ClusterTestBase } @Test - public void testRedistributionWhenConsumerIsClosed() throws Exception - { + public void testRedistributionWhenConsumerIsClosed() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); MessageRedistributionTest.log.info("Doing test"); @@ -253,8 +235,7 @@ public class MessageRedistributionTest extends ClusterTestBase } @Test - public void testRedistributionWhenConsumerIsClosedDifferentQueues() throws Exception - { + public void testRedistributionWhenConsumerIsClosedDifferentQueues() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); startServers(0, 1, 2); @@ -267,7 +248,6 @@ public class MessageRedistributionTest extends ClusterTestBase createQueue(1, "queues.testaddress", "queue1", null, true); createQueue(2, "queues.testaddress", "queue2", null, true); - ClientSession sess0 = sfs[0].createSession(); ClientConsumer consumer0 = sess0.createConsumer("queue0"); @@ -281,8 +261,7 @@ public class MessageRedistributionTest extends ClusterTestBase final int NUMBER_OF_MESSAGES = 1000; - for (int i = 0; i < 1000; i++) - { + for (int i = 0; i < 1000; i++) { producer0.send(sess0.createMessage(true).putIntProperty("count", i)); } @@ -290,8 +269,7 @@ public class MessageRedistributionTest extends ClusterTestBase sess1.start(); sess2.start(); - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { ClientMessage msg = consumer0.receive(5000); Assert.assertNotNull(msg); msg.acknowledge(); @@ -305,8 +283,7 @@ public class MessageRedistributionTest extends ClusterTestBase Thread.sleep(500); // wait some time giving time to redistribution break something // (it shouldn't redistribute anything here since there are no queues on the other nodes) - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { ClientMessage msg = consumer2.receive(5000); Assert.assertNotNull(msg); msg.acknowledge(); @@ -317,8 +294,7 @@ public class MessageRedistributionTest extends ClusterTestBase Assert.assertNull(consumer0.receiveImmediate()); consumer1 = sess1.createConsumer("queue1"); - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { ClientMessage msg = consumer1.receive(5000); Assert.assertNotNull(msg); msg.acknowledge(); @@ -333,8 +309,7 @@ public class MessageRedistributionTest extends ClusterTestBase } @Test - public void testRedistributionWhenConsumerIsClosedNotConsumersOnAllNodes() throws Exception - { + public void testRedistributionWhenConsumerIsClosedNotConsumersOnAllNodes() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); startServers(0, 1, 2); @@ -369,8 +344,7 @@ public class MessageRedistributionTest extends ClusterTestBase } @Test - public void testNoRedistributionWhenConsumerIsClosedForwardWhenNoConsumersTrue() throws Exception - { + public void testNoRedistributionWhenConsumerIsClosedForwardWhenNoConsumersTrue() throws Exception { // x setupCluster(MessageLoadBalancingType.STRICT); @@ -422,8 +396,7 @@ public class MessageRedistributionTest extends ClusterTestBase } @Test - public void testNoRedistributionWhenConsumerIsClosedNoConsumersOnOtherNodes() throws Exception - { + public void testNoRedistributionWhenConsumerIsClosedNoConsumersOnOtherNodes() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); startServers(0, 1, 2); @@ -472,8 +445,7 @@ public class MessageRedistributionTest extends ClusterTestBase } @Test - public void testRedistributeWithScheduling() throws Exception - { + public void testRedistributeWithScheduling() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); AddressSettings setting = new AddressSettings().setRedeliveryDelay(10000); @@ -492,8 +464,7 @@ public class MessageRedistributionTest extends ClusterTestBase ClientProducer prod0 = session0.createProducer("queues.testaddress"); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage msg = session0.createMessage(true); msg.putIntProperty("key", i); @@ -520,8 +491,7 @@ public class MessageRedistributionTest extends ClusterTestBase ArrayList xids = new ArrayList(); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { Xid xid = newXID(); session0.start(xid, XAResource.TMNOFLAGS); @@ -565,13 +535,11 @@ public class MessageRedistributionTest extends ClusterTestBase session0 = sfs[0].createSession(true, false, false); - for (Xid xid : xids) - { + for (Xid xid : xids) { session0.rollback(xid); } - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage msg = consumer1.receive(15000); Assert.assertNotNull(msg); msg.acknowledge(); @@ -582,8 +550,7 @@ public class MessageRedistributionTest extends ClusterTestBase } @Test - public void testRedistributionWhenConsumerIsClosedQueuesWithFilters() throws Exception - { + public void testRedistributionWhenConsumerIsClosedQueuesWithFilters() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); startServers(0, 1, 2); @@ -623,8 +590,7 @@ public class MessageRedistributionTest extends ClusterTestBase } @Test - public void testRedistributionWhenConsumerIsClosedConsumersWithFilters() throws Exception - { + public void testRedistributionWhenConsumerIsClosedConsumersWithFilters() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); startServers(0, 1, 2); @@ -664,8 +630,7 @@ public class MessageRedistributionTest extends ClusterTestBase } @Test - public void testRedistributionWhenRemoteConsumerIsAdded() throws Exception - { + public void testRedistributionWhenRemoteConsumerIsAdded() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); startServers(0, 1, 2); @@ -699,10 +664,8 @@ public class MessageRedistributionTest extends ClusterTestBase } @Test - public void testBackAndForth() throws Exception - { - for (int i = 0; i < 10; i++) - { + public void testBackAndForth() throws Exception { + for (int i = 0; i < 10; i++) { setupCluster(MessageLoadBalancingType.ON_DEMAND); startServers(0, 1, 2); @@ -792,27 +755,22 @@ public class MessageRedistributionTest extends ClusterTestBase // https://issues.jboss.org/browse/HORNETQ-1072 @Test - public void testBackAndForth2WithDuplicDetection() throws Exception - { + public void testBackAndForth2WithDuplicDetection() throws Exception { internalTestBackAndForth2(true); } @Test - public void testBackAndForth2() throws Exception - { + public void testBackAndForth2() throws Exception { internalTestBackAndForth2(false); } - public void internalTestBackAndForth2(final boolean useDuplicateDetection) throws Exception - { + public void internalTestBackAndForth2(final boolean useDuplicateDetection) throws Exception { AtomicInteger duplDetection = null; - if (useDuplicateDetection) - { + if (useDuplicateDetection) { duplDetection = new AtomicInteger(0); } - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { setupCluster(MessageLoadBalancingType.ON_DEMAND); startServers(0, 1); @@ -876,8 +834,7 @@ public class MessageRedistributionTest extends ClusterTestBase } @Test - public void testRedistributionToQueuesWhereNotAllMessagesMatch() throws Exception - { + public void testRedistributionToQueuesWhereNotAllMessagesMatch() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); startServers(0, 1, 2); @@ -915,8 +872,7 @@ public class MessageRedistributionTest extends ClusterTestBase } @Test - public void testDelayedRedistribution() throws Exception - { + public void testDelayedRedistribution() throws Exception { final long delay = 1000; setRedistributionDelay(delay); @@ -955,8 +911,7 @@ public class MessageRedistributionTest extends ClusterTestBase } @Test - public void testDelayedRedistributionCancelled() throws Exception - { + public void testDelayedRedistributionCancelled() throws Exception { final long delay = 1000; setRedistributionDelay(delay); @@ -998,8 +953,7 @@ public class MessageRedistributionTest extends ClusterTestBase } @Test - public void testRedistributionNumberOfMessagesGreaterThanBatchSize() throws Exception - { + public void testRedistributionNumberOfMessagesGreaterThanBatchSize() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); startServers(0, 1, 2); @@ -1036,8 +990,7 @@ public class MessageRedistributionTest extends ClusterTestBase * https://jira.jboss.org/jira/browse/HORNETQ-359 */ @Test - public void testRedistributionWhenNewNodeIsAddedWithConsumer() throws Exception - { + public void testRedistributionWhenNewNodeIsAddedWithConsumer() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); startServers(0); @@ -1068,14 +1021,10 @@ public class MessageRedistributionTest extends ClusterTestBase } @Test - public void testRedistributionWithPagingOnTarget() throws Exception - { + public void testRedistributionWithPagingOnTarget() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); - AddressSettings as = new AddressSettings() - .setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE) - .setPageSizeBytes(10000) - .setMaxSizeBytes(20000); + AddressSettings as = new AddressSettings().setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE).setPageSizeBytes(10000).setMaxSizeBytes(20000); getServer(0).getAddressSettingsRepository().addMatch("queues.*", as); getServer(1).getAddressSettingsRepository().addMatch("queues.*", as); @@ -1108,14 +1057,11 @@ public class MessageRedistributionTest extends ClusterTestBase ClientConsumer consumer0 = session0.createConsumer("queue0"); session0.start(); - ClientSession session1 = sfs[1].createSession(true, true, 0); ClientConsumer consumer1 = session1.createConsumer("queue0"); session1.start(); - - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage msg = session0.createMessage(true); msg.putIntProperty("i", i); // send two identical messages so they are routed on the cluster @@ -1137,8 +1083,7 @@ public class MessageRedistributionTest extends ClusterTestBase session1.close(); } - protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception - { + protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception { setupClusterConnection("cluster0", "queues", messageLoadBalancingType, 1, isNetty(), 0, 1, 2); setupClusterConnection("cluster1", "queues", messageLoadBalancingType, 1, isNetty(), 1, 0, 2); @@ -1146,8 +1091,7 @@ public class MessageRedistributionTest extends ClusterTestBase setupClusterConnection("cluster2", "queues", messageLoadBalancingType, 1, isNetty(), 2, 0, 1); } - protected void setRedistributionDelay(final long delay) - { + protected void setRedistributionDelay(final long delay) { AddressSettings as = new AddressSettings().setRedistributionDelay(delay); getServer(0).getAddressSettingsRepository().addMatch("queues.*", as); @@ -1155,15 +1099,13 @@ public class MessageRedistributionTest extends ClusterTestBase getServer(2).getAddressSettingsRepository().addMatch("queues.*", as); } - protected void setupServers() throws Exception - { + protected void setupServers() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); } - protected void stopServers() throws Exception - { + protected void stopServers() throws Exception { closeAllConsumers(); closeAllSessionFactories(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/MessageRedistributionWithDiscoveryTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/MessageRedistributionWithDiscoveryTest.java index af15179338..4faa93b9ea 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/MessageRedistributionWithDiscoveryTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/MessageRedistributionWithDiscoveryTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.cluster.distribution; + import org.apache.activemq.artemis.core.server.cluster.impl.MessageLoadBalancingType; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Assert; @@ -33,34 +34,29 @@ import org.apache.activemq.artemis.api.core.client.ClientProducer; import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.core.settings.impl.AddressSettings; -public class MessageRedistributionWithDiscoveryTest extends ClusterTestBase -{ +public class MessageRedistributionWithDiscoveryTest extends ClusterTestBase { + protected final String groupAddress = ActiveMQTestBase.getUDPDiscoveryAddress(); protected final int groupPort = ActiveMQTestBase.getUDPDiscoveryPort(); - protected boolean isNetty() - { + protected boolean isNetty() { return false; } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); setupCluster(); } - protected void setupCluster() throws Exception - { + protected void setupCluster() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); } - protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception - { - for (int i = 0; i < 5; i++) - { + protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception { + for (int i = 0; i < 5; i++) { setServer(messageLoadBalancingType, i); } } @@ -69,18 +65,10 @@ public class MessageRedistributionWithDiscoveryTest extends ClusterTestBase * @param messageLoadBalancingType * @throws Exception */ - protected void setServer(final MessageLoadBalancingType messageLoadBalancingType, int server) throws Exception - { - setupLiveServerWithDiscovery(server, - groupAddress, - groupPort, - isFileStorage(), - isNetty(), - false); + protected void setServer(final MessageLoadBalancingType messageLoadBalancingType, int server) throws Exception { + setupLiveServerWithDiscovery(server, groupAddress, groupPort, isFileStorage(), isNetty(), false); - AddressSettings setting = new AddressSettings() - .setRedeliveryDelay(0) - .setRedistributionDelay(0); + AddressSettings setting = new AddressSettings().setRedeliveryDelay(0).setRedistributionDelay(0); servers[server].getAddressSettingsRepository().addMatch("#", setting); @@ -88,8 +76,7 @@ public class MessageRedistributionWithDiscoveryTest extends ClusterTestBase } @Test - public void testRedistributeWithPreparedAndRestart() throws Exception - { + public void testRedistributeWithPreparedAndRestart() throws Exception { startServers(0); setupSessionFactory(0, isNetty()); @@ -100,8 +87,7 @@ public class MessageRedistributionWithDiscoveryTest extends ClusterTestBase ClientProducer prod0 = session0.createProducer("queues.testaddress"); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage msg = session0.createMessage(true); msg.putIntProperty("key", i); @@ -121,8 +107,7 @@ public class MessageRedistributionWithDiscoveryTest extends ClusterTestBase ArrayList xids = new ArrayList(); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { Xid xid = newXID(); session0.start(xid, XAResource.TMNOFLAGS); @@ -177,13 +162,11 @@ public class MessageRedistributionWithDiscoveryTest extends ClusterTestBase session0 = sfs[0].createSession(true, false, false); - for (Xid xid : xids) - { + for (Xid xid : xids) { session0.rollback(xid); } - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage msg = consumer1.receive(15000); Assert.assertNotNull(msg); msg.acknowledge(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettyFileStorageSymmetricClusterTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettyFileStorageSymmetricClusterTest.java index 081ce361d3..da7c40ddb2 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettyFileStorageSymmetricClusterTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettyFileStorageSymmetricClusterTest.java @@ -16,21 +16,18 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.distribution; - import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; -public class NettyFileStorageSymmetricClusterTest extends SymmetricClusterTest -{ +public class NettyFileStorageSymmetricClusterTest extends SymmetricClusterTest { + IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @Override - protected boolean isNetty() - { + protected boolean isNetty() { return true; } - protected boolean isFileStorage() - { + protected boolean isFileStorage() { return true; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettyFileStorageSymmetricClusterWithBackupTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettyFileStorageSymmetricClusterWithBackupTest.java index 3be7155f50..377bdacd69 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettyFileStorageSymmetricClusterWithBackupTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettyFileStorageSymmetricClusterWithBackupTest.java @@ -16,18 +16,15 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.distribution; -public class NettyFileStorageSymmetricClusterWithBackupTest extends SymmetricClusterWithBackupTest -{ +public class NettyFileStorageSymmetricClusterWithBackupTest extends SymmetricClusterWithBackupTest { + @Override - protected boolean isNetty() - { + protected boolean isNetty() { return true; } - protected boolean isFileStorage() - { + protected boolean isFileStorage() { return true; } - } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettyFileStorageSymmetricClusterWithDiscoveryTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettyFileStorageSymmetricClusterWithDiscoveryTest.java index 2c155e99a6..8b0903571b 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettyFileStorageSymmetricClusterWithDiscoveryTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettyFileStorageSymmetricClusterWithDiscoveryTest.java @@ -16,23 +16,19 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.distribution; - import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; -public class NettyFileStorageSymmetricClusterWithDiscoveryTest extends SymmetricClusterWithDiscoveryTest -{ +public class NettyFileStorageSymmetricClusterWithDiscoveryTest extends SymmetricClusterWithDiscoveryTest { + IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @Override - protected boolean isNetty() - { + protected boolean isNetty() { return true; } - protected boolean isFileStorage() - { + protected boolean isFileStorage() { return true; } - } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettyOneWayChainClusterTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettyOneWayChainClusterTest.java index 6f9de4d424..61182a5dc1 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettyOneWayChainClusterTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettyOneWayChainClusterTest.java @@ -16,13 +16,10 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.distribution; +public class NettyOneWayChainClusterTest extends OneWayChainClusterTest { - -public class NettyOneWayChainClusterTest extends OneWayChainClusterTest -{ @Override - protected boolean isNetty() - { + protected boolean isNetty() { return true; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettyOneWayTwoNodeClusterTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettyOneWayTwoNodeClusterTest.java index 509fe2c5f6..a0738678ac 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettyOneWayTwoNodeClusterTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettyOneWayTwoNodeClusterTest.java @@ -16,14 +16,10 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.distribution; - - -public class NettyOneWayTwoNodeClusterTest extends OnewayTwoNodeClusterTest -{ +public class NettyOneWayTwoNodeClusterTest extends OnewayTwoNodeClusterTest { @Override - protected boolean isNetty() - { + protected boolean isNetty() { return true; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettySymmetricClusterTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettySymmetricClusterTest.java index 23efb90c42..cc3a266298 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettySymmetricClusterTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettySymmetricClusterTest.java @@ -16,11 +16,10 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.distribution; -public class NettySymmetricClusterTest extends SymmetricClusterTest -{ +public class NettySymmetricClusterTest extends SymmetricClusterTest { + @Override - protected boolean isNetty() - { + protected boolean isNetty() { return true; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettySymmetricClusterWithBackupTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettySymmetricClusterWithBackupTest.java index 4b8dd949d9..bf79e4afb1 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettySymmetricClusterWithBackupTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettySymmetricClusterWithBackupTest.java @@ -16,13 +16,10 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.distribution; - -public class NettySymmetricClusterWithBackupTest extends SymmetricClusterWithBackupTest -{ +public class NettySymmetricClusterWithBackupTest extends SymmetricClusterWithBackupTest { @Override - protected boolean isNetty() - { + protected boolean isNetty() { return true; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettySymmetricClusterWithDiscoveryTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettySymmetricClusterWithDiscoveryTest.java index f81fa2c460..eafc4f97ce 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettySymmetricClusterWithDiscoveryTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/NettySymmetricClusterWithDiscoveryTest.java @@ -16,11 +16,10 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.distribution; -public class NettySymmetricClusterWithDiscoveryTest extends SymmetricClusterWithDiscoveryTest -{ +public class NettySymmetricClusterWithDiscoveryTest extends SymmetricClusterWithDiscoveryTest { + @Override - protected boolean isNetty() - { + protected boolean isNetty() { return true; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/OneWayChainClusterTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/OneWayChainClusterTest.java index 9d8c5312be..71d96967ee 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/OneWayChainClusterTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/OneWayChainClusterTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.cluster.distribution; + import org.apache.activemq.artemis.core.server.cluster.impl.MessageLoadBalancingType; import org.junit.Before; @@ -28,14 +29,13 @@ import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; import java.util.Map; import java.util.Set; -public class OneWayChainClusterTest extends ClusterTestBase -{ +public class OneWayChainClusterTest extends ClusterTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); setupServer(0, isFileStorage(), isNetty()); @@ -45,14 +45,12 @@ public class OneWayChainClusterTest extends ClusterTestBase setupServer(4, isFileStorage(), isNetty()); } - protected boolean isNetty() - { + protected boolean isNetty() { return false; } @Test - public void testBasicRoundRobin() throws Exception - { + public void testBasicRoundRobin() throws Exception { setupClusterConnection("cluster0-1", 0, 1, "queues", MessageLoadBalancingType.ON_DEMAND, 4, isNetty(), true); setupClusterConnection("cluster1-2", 1, 2, "queues", MessageLoadBalancingType.ON_DEMAND, 4, isNetty(), true); setupClusterConnection("cluster2-3", 2, 3, "queues", MessageLoadBalancingType.ON_DEMAND, 4, isNetty(), true); @@ -82,8 +80,7 @@ public class OneWayChainClusterTest extends ClusterTestBase } @Test - public void testBasicNonLoadBalanced() throws Exception - { + public void testBasicNonLoadBalanced() throws Exception { setupClusterConnection("cluster0-1", 0, 1, "queues", MessageLoadBalancingType.ON_DEMAND, 4, isNetty(), true); setupClusterConnection("cluster1-2", 1, 2, "queues", MessageLoadBalancingType.ON_DEMAND, 4, isNetty(), true); setupClusterConnection("cluster2-3", 2, 3, "queues", MessageLoadBalancingType.ON_DEMAND, 4, isNetty(), true); @@ -116,8 +113,7 @@ public class OneWayChainClusterTest extends ClusterTestBase } @Test - public void testRoundRobinForwardWhenNoConsumersTrue() throws Exception - { + public void testRoundRobinForwardWhenNoConsumersTrue() throws Exception { setupClusterConnection("cluster0-1", 0, 1, "queues", MessageLoadBalancingType.STRICT, 4, isNetty(), true); setupClusterConnection("cluster1-2", 1, 2, "queues", MessageLoadBalancingType.STRICT, 4, isNetty(), true); setupClusterConnection("cluster2-3", 2, 3, "queues", MessageLoadBalancingType.STRICT, 4, isNetty(), true); @@ -148,8 +144,7 @@ public class OneWayChainClusterTest extends ClusterTestBase } @Test - public void testRoundRobinForwardWhenNoConsumersFalseNoLocalQueue() throws Exception - { + public void testRoundRobinForwardWhenNoConsumersFalseNoLocalQueue() throws Exception { setupClusterConnection("cluster0-1", 0, 1, "queues", MessageLoadBalancingType.ON_DEMAND, 4, isNetty(), true); setupClusterConnection("cluster1-2", 1, 2, "queues", MessageLoadBalancingType.ON_DEMAND, 4, isNetty(), true); setupClusterConnection("cluster2-3", 2, 3, "queues", MessageLoadBalancingType.ON_DEMAND, 4, isNetty(), true); @@ -175,8 +170,7 @@ public class OneWayChainClusterTest extends ClusterTestBase } @Test - public void testRoundRobinForwardWhenNoConsumersFalse() throws Exception - { + public void testRoundRobinForwardWhenNoConsumersFalse() throws Exception { setupClusterConnection("cluster0-1", 0, 1, "queues", MessageLoadBalancingType.ON_DEMAND, 4, isNetty(), true); setupClusterConnection("cluster1-2", 1, 2, "queues", MessageLoadBalancingType.ON_DEMAND, 4, isNetty(), true); setupClusterConnection("cluster2-3", 2, 3, "queues", MessageLoadBalancingType.ON_DEMAND, 4, isNetty(), true); @@ -209,8 +203,7 @@ public class OneWayChainClusterTest extends ClusterTestBase } @Test - public void testRoundRobinForwardWhenNoConsumersFalseLocalConsumer() throws Exception - { + public void testRoundRobinForwardWhenNoConsumersFalseLocalConsumer() throws Exception { setupClusterConnection("cluster0-1", 0, 1, "queues", MessageLoadBalancingType.ON_DEMAND, 4, isNetty(), true); setupClusterConnection("cluster1-2", 1, 2, "queues", MessageLoadBalancingType.ON_DEMAND, 4, isNetty(), true); setupClusterConnection("cluster2-3", 2, 3, "queues", MessageLoadBalancingType.ON_DEMAND, 4, isNetty(), true); @@ -243,8 +236,7 @@ public class OneWayChainClusterTest extends ClusterTestBase } @Test - public void testHopsTooLow() throws Exception - { + public void testHopsTooLow() throws Exception { setupClusterConnection("cluster0-1", 0, 1, "queues", MessageLoadBalancingType.ON_DEMAND, 3, isNetty(), true); setupClusterConnection("cluster1-2", 1, 2, "queues", MessageLoadBalancingType.ON_DEMAND, 3, isNetty(), true); setupClusterConnection("cluster2-3", 2, 3, "queues", MessageLoadBalancingType.ON_DEMAND, 3, isNetty(), true); @@ -272,8 +264,7 @@ public class OneWayChainClusterTest extends ClusterTestBase } @Test - public void testStartStopMiddleOfChain() throws Exception - { + public void testStartStopMiddleOfChain() throws Exception { setupClusterConnection("cluster0-1", 0, 1, "queues", MessageLoadBalancingType.ON_DEMAND, 4, isNetty(), true); setupClusterConnection("cluster1-2", 1, 2, "queues", MessageLoadBalancingType.ON_DEMAND, 4, isNetty(), true); setupClusterConnection("cluster2-3", 2, 3, "queues", MessageLoadBalancingType.ON_DEMAND, 4, isNetty(), true); @@ -320,7 +311,6 @@ public class OneWayChainClusterTest extends ClusterTestBase startServers(2); - Thread.sleep(1000); waitForTopology(servers[1], 5); @@ -332,7 +322,6 @@ public class OneWayChainClusterTest extends ClusterTestBase log.info(clusterDescription(servers[3])); log.info(clusterDescription(servers[4])); - send(0, "queues.testaddress", 10, false, null); verifyReceiveRoundRobin(10, 0, 1); @@ -340,8 +329,7 @@ public class OneWayChainClusterTest extends ClusterTestBase } @Test - public void testChainClusterConnections() throws Exception - { + public void testChainClusterConnections() throws Exception { setupClusterConnection("cluster0-1", 0, 1, "queues", MessageLoadBalancingType.ON_DEMAND, 4, isNetty(), true); setupClusterConnection("cluster1-2", 1, 2, "queues", MessageLoadBalancingType.ON_DEMAND, 4, isNetty(), true); setupClusterConnection("cluster2-3", 2, 3, "queues", MessageLoadBalancingType.ON_DEMAND, 4, isNetty(), true); @@ -356,11 +344,9 @@ public class OneWayChainClusterTest extends ClusterTestBase long timeout = System.currentTimeMillis() + 5000; Map records = null; - while (timeout > System.currentTimeMillis()) - { - records = ccon.getRecords(); - if (records != null && records.size() == 1) - { + while (timeout > System.currentTimeMillis()) { + records = ccon.getRecords(); + if (records != null && records.size() == 1) { break; } } @@ -371,7 +357,7 @@ public class OneWayChainClusterTest extends ClusterTestBase assertEquals(1, connectionSet.size()); ccon = (ClusterConnectionImpl) connectionSet.iterator().next(); - records = ccon.getRecords(); + records = ccon.getRecords(); assertNotNull(records); assertEquals(records.size(), 1); getServer(2).getClusterManager().getClusterConnections(); @@ -379,7 +365,7 @@ public class OneWayChainClusterTest extends ClusterTestBase assertEquals(1, connectionSet.size()); ccon = (ClusterConnectionImpl) connectionSet.iterator().next(); - records = ccon.getRecords(); + records = ccon.getRecords(); assertNotNull(records); assertEquals(records.size(), 1); getServer(3).getClusterManager().getClusterConnections(); @@ -387,7 +373,7 @@ public class OneWayChainClusterTest extends ClusterTestBase assertEquals(1, connectionSet.size()); ccon = (ClusterConnectionImpl) connectionSet.iterator().next(); - records = ccon.getRecords(); + records = ccon.getRecords(); assertNotNull(records); assertEquals(records.size(), 1); @@ -396,7 +382,7 @@ public class OneWayChainClusterTest extends ClusterTestBase assertEquals(1, connectionSet.size()); ccon = (ClusterConnectionImpl) connectionSet.iterator().next(); - records = ccon.getRecords(); + records = ccon.getRecords(); assertNotNull(records); assertEquals(records.size(), 1); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/OnewayTwoNodeClusterTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/OnewayTwoNodeClusterTest.java index a98f881df4..8424de5735 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/OnewayTwoNodeClusterTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/OnewayTwoNodeClusterTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.cluster.distribution; + import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.cluster.impl.MessageLoadBalancingType; import org.junit.Before; @@ -25,41 +26,34 @@ import org.junit.Assert; import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; +public class OnewayTwoNodeClusterTest extends ClusterTestBase { -public class OnewayTwoNodeClusterTest extends ClusterTestBase -{ private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupCluster(MessageLoadBalancingType.ON_DEMAND); - } - private void setupCluster(MessageLoadBalancingType messageLoadBalancingType) - { - for (ActiveMQServer server : servers) - { - if (server != null) - { + private void setupCluster(MessageLoadBalancingType messageLoadBalancingType) { + for (ActiveMQServer server : servers) { + if (server != null) { server.getConfiguration().getClusterConfigurations().clear(); } } // server #0 is connected to server #1 setupClusterConnection("cluster1", 0, 1, "queues", messageLoadBalancingType, 1, 0, 500, isNetty(), true); // server #1 is connected to nobody - setupClusterConnection("clusterX", 1, -1, "queues", messageLoadBalancingType, 1, 0, 500, isNetty(), true); + setupClusterConnection("clusterX", 1, -1, "queues", messageLoadBalancingType, 1, 0, 500, isNetty(), true); } - protected boolean isNetty() - { + protected boolean isNetty() { return false; } @@ -67,8 +61,7 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase * make sure source can shutdown if target is never started */ @Test - public void testNeverStartTargetStartSourceThenStopSource() throws Exception - { + public void testNeverStartTargetStartSourceThenStopSource() throws Exception { startServers(0); // Give it a little time for the bridge to try to start @@ -78,12 +71,11 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testStartTargetServerBeforeSourceServer() throws Exception - { + public void testStartTargetServerBeforeSourceServer() throws Exception { startServers(1, 0); - setupSessionFactory(0, isNetty(), true); - setupSessionFactory(1, isNetty(), true); + setupSessionFactory(0, isNetty(), true); + setupSessionFactory(1, isNetty(), true); String myFilter = "zebra"; @@ -101,16 +93,14 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testStartSourceServerBeforeTargetServer() throws Exception - { + public void testStartSourceServerBeforeTargetServer() throws Exception { startServers(0, 1); waitForTopology(servers[0], 2); waitForTopology(servers[1], 2); - - setupSessionFactory(0, isNetty(), true); - setupSessionFactory(1, isNetty(), true); + setupSessionFactory(0, isNetty(), true); + setupSessionFactory(1, isNetty(), true); String myFilter = "bison"; @@ -128,15 +118,14 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testStopAndStartTarget() throws Exception - { + public void testStopAndStartTarget() throws Exception { startServers(0, 1); waitForTopology(servers[0], 2); waitForTopology(servers[1], 2); - setupSessionFactory(0, isNetty(), true); - setupSessionFactory(1, isNetty(), true); + setupSessionFactory(0, isNetty(), true); + setupSessionFactory(1, isNetty(), true); String myFilter = "bison"; @@ -169,8 +158,7 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase waitForTopology(servers[0], 2); - log.info("Server 1 id=" + servers[1].getNodeID()); - + log.info("Server 1 id=" + servers[1].getNodeID()); long end = System.currentTimeMillis(); @@ -179,7 +167,7 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase Assert.assertTrue("Took too long to restart", end - start <= 5000); - setupSessionFactory(1, isNetty(), true); + setupSessionFactory(1, isNetty(), true); addConsumer(0, 1, "queue0", null); @@ -196,12 +184,11 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testBasicLocalReceive() throws Exception - { + public void testBasicLocalReceive() throws Exception { startServers(1, 0); - setupSessionFactory(0, isNetty(), true); - setupSessionFactory(1, isNetty(), true); + setupSessionFactory(0, isNetty(), true); + setupSessionFactory(1, isNetty(), true); createQueue(0, "queues.testaddress", "queue0", null, false); addConsumer(0, 0, "queue0", null); @@ -217,12 +204,11 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testBasicRoundRobin() throws Exception - { + public void testBasicRoundRobin() throws Exception { startServers(1, 0); - setupSessionFactory(0, isNetty(), true); - setupSessionFactory(1, isNetty(), true); + setupSessionFactory(0, isNetty(), true); + setupSessionFactory(1, isNetty(), true); createQueue(0, "queues.testaddress", "queue0", null, false); @@ -244,12 +230,11 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testRoundRobinMultipleQueues() throws Exception - { + public void testRoundRobinMultipleQueues() throws Exception { startServers(1, 0); - setupSessionFactory(0, isNetty(), true); - setupSessionFactory(1, isNetty(), true); + setupSessionFactory(0, isNetty(), true); + setupSessionFactory(1, isNetty(), true); createQueue(0, "queues.testaddress", "queue0", null, false); createQueue(1, "queues.testaddress", "queue0", null, false); @@ -284,12 +269,11 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testMultipleNonLoadBalancedQueues() throws Exception - { + public void testMultipleNonLoadBalancedQueues() throws Exception { startServers(1, 0); - setupSessionFactory(0, isNetty(), true); - setupSessionFactory(1, isNetty(), true); + setupSessionFactory(0, isNetty(), true); + setupSessionFactory(1, isNetty(), true); createQueue(0, "queues.testaddress", "queue0", null, false); createQueue(0, "queues.testaddress", "queue1", null, false); @@ -326,12 +310,11 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testMixtureLoadBalancedAndNonLoadBalancedQueues() throws Exception - { + public void testMixtureLoadBalancedAndNonLoadBalancedQueues() throws Exception { startServers(1, 0); - setupSessionFactory(0, isNetty(), true); - setupSessionFactory(1, isNetty(), true); + setupSessionFactory(0, isNetty(), true); + setupSessionFactory(1, isNetty(), true); createQueue(0, "queues.testaddress", "queue0", null, false); createQueue(0, "queues.testaddress", "queue1", null, false); @@ -390,12 +373,11 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testMixtureLoadBalancedAndNonLoadBalancedQueuesRemoveSomeQueuesAndConsumers() throws Exception - { + public void testMixtureLoadBalancedAndNonLoadBalancedQueuesRemoveSomeQueuesAndConsumers() throws Exception { startServers(1, 0); - setupSessionFactory(0, isNetty(), true); - setupSessionFactory(1, isNetty(), true); + setupSessionFactory(0, isNetty(), true); + setupSessionFactory(1, isNetty(), true); createQueue(0, "queues.testaddress", "queue0", null, false); createQueue(0, "queues.testaddress", "queue1", null, false); @@ -471,11 +453,10 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testMixtureLoadBalancedAndNonLoadBalancedQueuesAddQueuesOnTargetBeforeStartSource() throws Exception - { + public void testMixtureLoadBalancedAndNonLoadBalancedQueuesAddQueuesOnTargetBeforeStartSource() throws Exception { startServers(1); - setupSessionFactory(1, isNetty(), true); + setupSessionFactory(1, isNetty(), true); createQueue(1, "queues.testaddress", "queue5", null, false); createQueue(1, "queues.testaddress", "queue6", null, false); @@ -535,11 +516,10 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testMixtureLoadBalancedAndNonLoadBalancedQueuesAddQueuesOnSourceBeforeStartTarget() throws Exception - { + public void testMixtureLoadBalancedAndNonLoadBalancedQueuesAddQueuesOnSourceBeforeStartTarget() throws Exception { startServers(0); - setupSessionFactory(0, isNetty(), true); + setupSessionFactory(0, isNetty(), true); createQueue(0, "queues.testaddress", "queue0", null, false); createQueue(0, "queues.testaddress", "queue1", null, false); @@ -563,7 +543,7 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase startServers(1); - setupSessionFactory(1, isNetty(), true); + setupSessionFactory(1, isNetty(), true); createQueue(1, "queues.testaddress", "queue5", null, false); createQueue(1, "queues.testaddress", "queue6", null, false); @@ -599,12 +579,11 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testNotRouteToNonMatchingAddress() throws Exception - { + public void testNotRouteToNonMatchingAddress() throws Exception { startServers(1, 0); - setupSessionFactory(0, isNetty(), true); - setupSessionFactory(1, isNetty(), true); + setupSessionFactory(0, isNetty(), true); + setupSessionFactory(1, isNetty(), true); createQueue(0, "queues.testaddress", "queue0", null, false); createQueue(1, "queues.testaddress", "queue1", null, false); @@ -635,12 +614,11 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testNonLoadBalancedQueuesWithFilters() throws Exception - { + public void testNonLoadBalancedQueuesWithFilters() throws Exception { startServers(1, 0); - setupSessionFactory(0, isNetty(), true); - setupSessionFactory(1, isNetty(), true); + setupSessionFactory(0, isNetty(), true); + setupSessionFactory(1, isNetty(), true); String filter1 = "giraffe"; String filter2 = "aardvark"; @@ -697,12 +675,11 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testRoundRobinMultipleQueuesWithFilters() throws Exception - { + public void testRoundRobinMultipleQueuesWithFilters() throws Exception { startServers(1, 0); - setupSessionFactory(0, isNetty(), true); - setupSessionFactory(1, isNetty(), true); + setupSessionFactory(0, isNetty(), true); + setupSessionFactory(1, isNetty(), true); String filter1 = "giraffe"; String filter2 = "aardvark"; @@ -762,12 +739,11 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testRouteWhenNoConsumersFalseNonBalancedQueues() throws Exception - { + public void testRouteWhenNoConsumersFalseNonBalancedQueues() throws Exception { startServers(1, 0); - setupSessionFactory(0, isNetty(), true); - setupSessionFactory(1, isNetty(), true); + setupSessionFactory(0, isNetty(), true); + setupSessionFactory(1, isNetty(), true); createQueue(0, "queues.testaddress", "queue0", null, false); createQueue(0, "queues.testaddress", "queue1", null, false); @@ -796,12 +772,11 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testRouteWhenNoConsumersTrueNonBalancedQueues() throws Exception - { + public void testRouteWhenNoConsumersTrueNonBalancedQueues() throws Exception { startServers(1, 0); - setupSessionFactory(0, isNetty(), true); - setupSessionFactory(1, isNetty(), true); + setupSessionFactory(0, isNetty(), true); + setupSessionFactory(1, isNetty(), true); createQueue(0, "queues.testaddress", "queue0", null, false); createQueue(0, "queues.testaddress", "queue1", null, false); @@ -830,13 +805,12 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testRouteWhenNoConsumersFalseLoadBalancedQueues() throws Exception - { + public void testRouteWhenNoConsumersFalseLoadBalancedQueues() throws Exception { setupCluster(MessageLoadBalancingType.STRICT); startServers(1, 0); setupSessionFactory(0, isNetty(), true); - setupSessionFactory(1, isNetty(), true); + setupSessionFactory(1, isNetty(), true); createQueue(0, "queues.testaddress", "queue0", null, false); createQueue(0, "queues.testaddress", "queue1", null, false); @@ -871,12 +845,11 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testRouteWhenNoConsumersFalseLoadBalancedQueuesLocalConsumer() throws Exception - { + public void testRouteWhenNoConsumersFalseLoadBalancedQueuesLocalConsumer() throws Exception { startServers(1, 0); setupSessionFactory(0, isNetty(), true); - setupSessionFactory(1, isNetty(), true); + setupSessionFactory(1, isNetty(), true); createQueue(0, "queues.testaddress", "queue0", null, false); createQueue(0, "queues.testaddress", "queue1", null, false); @@ -907,14 +880,13 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testRouteWhenNoConsumersFalseLoadBalancedQueuesNoLocalQueue() throws Exception - { + public void testRouteWhenNoConsumersFalseLoadBalancedQueuesNoLocalQueue() throws Exception { setupCluster(MessageLoadBalancingType.STRICT); startServers(1, 0); - setupSessionFactory(0, isNetty(), true); - setupSessionFactory(1, isNetty(), true); + setupSessionFactory(0, isNetty(), true); + setupSessionFactory(1, isNetty(), true); createQueue(0, "queues.testaddress", "queue0", null, false); createQueue(0, "queues.testaddress", "queue1", null, false); @@ -940,12 +912,11 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testRouteWhenNoConsumersTrueLoadBalancedQueues() throws Exception - { + public void testRouteWhenNoConsumersTrueLoadBalancedQueues() throws Exception { setupCluster(MessageLoadBalancingType.STRICT); startServers(1, 0); - setupSessionFactory(0, isNetty(), true); + setupSessionFactory(0, isNetty(), true); setupSessionFactory(1, isNetty(), true); createQueue(0, "queues.testaddress", "queue0", null, false); @@ -977,16 +948,15 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testRouteWhenNoConsumersTrueLoadBalancedQueuesLocalConsumer() throws Exception - { + public void testRouteWhenNoConsumersTrueLoadBalancedQueuesLocalConsumer() throws Exception { servers[0].getConfiguration().getClusterConfigurations().clear(); // server #0 is connected to server #1 - setupClusterConnection("cluster1", 0, 1, "queues", MessageLoadBalancingType.STRICT, 1, isNetty(), true); + setupClusterConnection("cluster1", 0, 1, "queues", MessageLoadBalancingType.STRICT, 1, isNetty(), true); startServers(1, 0); - setupSessionFactory(0, isNetty(), true); - setupSessionFactory(1, isNetty(), true); + setupSessionFactory(0, isNetty(), true); + setupSessionFactory(1, isNetty(), true); createQueue(0, "queues.testaddress", "queue0", null, false); createQueue(0, "queues.testaddress", "queue1", null, false); @@ -1017,16 +987,15 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testRouteWhenNoConsumersTrueLoadBalancedQueuesNoLocalQueue() throws Exception - { + public void testRouteWhenNoConsumersTrueLoadBalancedQueuesNoLocalQueue() throws Exception { servers[0].getConfiguration().getClusterConfigurations().clear(); // server #0 is connected to server #1 - setupClusterConnection("cluster1", 0, 1, "queues", MessageLoadBalancingType.STRICT, 1, isNetty(), true); + setupClusterConnection("cluster1", 0, 1, "queues", MessageLoadBalancingType.STRICT, 1, isNetty(), true); startServers(1, 0); - setupSessionFactory(0, isNetty(), true); - setupSessionFactory(1, isNetty(), true); + setupSessionFactory(0, isNetty(), true); + setupSessionFactory(1, isNetty(), true); createQueue(0, "queues.testaddress", "queue0", null, false); createQueue(0, "queues.testaddress", "queue1", null, false); @@ -1052,12 +1021,11 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testNonLoadBalancedQueuesWithConsumersWithFilters() throws Exception - { + public void testNonLoadBalancedQueuesWithConsumersWithFilters() throws Exception { startServers(1, 0); - setupSessionFactory(0, isNetty(), true); - setupSessionFactory(1, isNetty(), true); + setupSessionFactory(0, isNetty(), true); + setupSessionFactory(1, isNetty(), true); String filter1 = "giraffe"; String filter2 = "aardvark"; @@ -1110,14 +1078,13 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testRoundRobinMultipleQueuesWithConsumersWithFilters() throws Exception - { + public void testRoundRobinMultipleQueuesWithConsumersWithFilters() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); startServers(1, 0); - setupSessionFactory(0, isNetty(), true); - setupSessionFactory(1, isNetty(), true); + setupSessionFactory(0, isNetty(), true); + setupSessionFactory(1, isNetty(), true); String filter1 = "giraffe"; String filter2 = "aardvark"; @@ -1182,15 +1149,14 @@ public class OnewayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testMultipleClusterConnections() throws Exception - { - setupClusterConnection("cluster2", 0, 1, "q2", MessageLoadBalancingType.ON_DEMAND, 1, isNetty(), true); - setupClusterConnection("cluster3", 0, 1, "q3", MessageLoadBalancingType.ON_DEMAND, 1, isNetty(), true); + public void testMultipleClusterConnections() throws Exception { + setupClusterConnection("cluster2", 0, 1, "q2", MessageLoadBalancingType.ON_DEMAND, 1, isNetty(), true); + setupClusterConnection("cluster3", 0, 1, "q3", MessageLoadBalancingType.ON_DEMAND, 1, isNetty(), true); startServers(1, 0); - setupSessionFactory(0, isNetty(), true); - setupSessionFactory(1, isNetty(), true); + setupSessionFactory(0, isNetty(), true); + setupSessionFactory(1, isNetty(), true); // Make sure the different connections don't conflict diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/SimpleSymmetricClusterTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/SimpleSymmetricClusterTest.java index 53f99a23c1..ebc6dd7de2 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/SimpleSymmetricClusterTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/SimpleSymmetricClusterTest.java @@ -20,8 +20,7 @@ import org.apache.activemq.artemis.core.server.cluster.impl.MessageLoadBalancing import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; import org.junit.Test; -public class SimpleSymmetricClusterTest extends ClusterTestBase -{ +public class SimpleSymmetricClusterTest extends ClusterTestBase { // Constants ----------------------------------------------------- @@ -35,14 +34,12 @@ public class SimpleSymmetricClusterTest extends ClusterTestBase // Public -------------------------------------------------------- - public boolean isNetty() - { + public boolean isNetty() { return false; } @Test - public void testSimpleWithBackup() throws Exception - { + public void testSimpleWithBackup() throws Exception { // The backups setupBackupServer(0, 3, isFileStorage(), true, isNetty()); setupBackupServer(1, 4, isFileStorage(), true, isNetty()); @@ -65,34 +62,28 @@ public class SimpleSymmetricClusterTest extends ClusterTestBase setupClusterConnection("cluster2", "queues", MessageLoadBalancingType.ON_DEMAND, 1, isNetty(), 2, 3, 4); - startServers(0, 1, 2, 3, 4, 5); log.info(""); - for (int i = 0; i <= 5; i++) - { + for (int i = 0; i <= 5; i++) { log.info(servers[i].describe()); log.info(debugBindings(servers[i], servers[i].getConfiguration().getManagementNotificationAddress().toString())); } log.info(""); log.info(""); - for (int i = 0; i <= 5; i++) - { + for (int i = 0; i <= 5; i++) { log.info(servers[i].describe()); log.info(debugBindings(servers[i], servers[i].getConfiguration().getManagementNotificationAddress().toString())); } log.info(""); - stopServers(0, 1, 2, 3, 4, 5); } - @Test - public void testSimple() throws Exception - { + public void testSimple() throws Exception { setupServer(0, true, isNetty()); setupServer(1, true, isNetty()); setupServer(2, true, isNetty()); @@ -130,8 +121,7 @@ public class SimpleSymmetricClusterTest extends ClusterTestBase } @Test - public void testSimple_TwoNodes() throws Exception - { + public void testSimple_TwoNodes() throws Exception { setupServer(0, false, isNetty()); setupServer(1, false, isNetty()); @@ -161,10 +151,8 @@ public class SimpleSymmetricClusterTest extends ClusterTestBase static int loopNumber; - public void _testLoop() throws Throwable - { - for (int i = 0; i < 10; i++) - { + public void _testLoop() throws Throwable { + for (int i = 0; i < 10; i++) { loopNumber = i; log.info("#test " + i); testSimple(); @@ -173,10 +161,8 @@ public class SimpleSymmetricClusterTest extends ClusterTestBase } } - @Test - public void testSimple2() throws Exception - { + public void testSimple2() throws Exception { setupServer(0, true, isNetty()); setupServer(1, true, isNetty()); setupServer(2, true, isNetty()); @@ -195,25 +181,21 @@ public class SimpleSymmetricClusterTest extends ClusterTestBase startServers(0, 1, 2, 3, 4); - for (int i = 0; i <= 4; i++) - { + for (int i = 0; i <= 4; i++) { waitForTopology(servers[i], 5); } log.info("All the servers have been started already!"); - for (int i = 0; i <= 4; i++) - { + for (int i = 0; i <= 4; i++) { setupSessionFactory(i, isNetty()); } - for (int i = 0; i <= 4; i++) - { + for (int i = 0; i <= 4; i++) { createQueue(i, "queues.testaddress", "queue0", null, false); } - for (int i = 0; i <= 4; i++) - { + for (int i = 0; i <= 4; i++) { addConsumer(i, i, "queue0", null); } @@ -228,8 +210,7 @@ public class SimpleSymmetricClusterTest extends ClusterTestBase } @Test - public void testSimpleRoundRobbin() throws Exception - { + public void testSimpleRoundRobbin() throws Exception { //TODO make this test to crash a node setupServer(0, true, isNetty()); @@ -271,11 +252,9 @@ public class SimpleSymmetricClusterTest extends ClusterTestBase stopServers(2); - waitForBindings(0, "queues.testaddress", 1, 1, false); waitForBindings(1, "queues.testaddress", 1, 1, false); - send(0, "queues.testaddress", 100, true, null); verifyReceiveRoundRobin(100, 0, 1); @@ -283,7 +262,6 @@ public class SimpleSymmetricClusterTest extends ClusterTestBase sfs[2] = null; consumers[2] = null; - startServers(2); setupSessionFactory(2, isNetty()); @@ -304,9 +282,7 @@ public class SimpleSymmetricClusterTest extends ClusterTestBase verifyReceiveRoundRobinInSomeOrder(33, 2, 0, 1); } - - public void _testSimpleRoundRobbinNoFailure() throws Exception - { + public void _testSimpleRoundRobbinNoFailure() throws Exception { //TODO make this test to crash a node setupServer(0, true, isNetty()); setupServer(1, true, isNetty()); @@ -344,7 +320,6 @@ public class SimpleSymmetricClusterTest extends ClusterTestBase stopServers(2); - send(0, "queues.testaddress", 100, true, null); verifyReceiveRoundRobin(100, 0, 1, -1); @@ -368,7 +343,6 @@ public class SimpleSymmetricClusterTest extends ClusterTestBase verifyReceiveRoundRobin(100, -1, -1, 2); - } // Package protected --------------------------------------------- diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/SymmetricClusterTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/SymmetricClusterTest.java index 0838877d49..ade1a427d1 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/SymmetricClusterTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/SymmetricClusterTest.java @@ -27,29 +27,25 @@ import org.junit.Test; * * Most of the cases are covered in OneWayTwoNodeClusterTest - we don't duplicate them all here */ -public class SymmetricClusterTest extends ClusterTestBase -{ +public class SymmetricClusterTest extends ClusterTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); setupServers(); } - protected boolean isNetty() - { + protected boolean isNetty() { return false; } @Test - public void testStopAllStartAll() throws Throwable - { - try - { + public void testStopAllStartAll() throws Throwable { + try { setupCluster(); startServers(); @@ -141,8 +137,7 @@ public class SymmetricClusterTest extends ClusterTestBase verifyNotReceive(0, 1, 2, 3, 4); } - catch (Throwable e) - { + catch (Throwable e) { System.out.println(ActiveMQTestBase.threadDump("SymmetricClusterTest::testStopAllStartAll")); throw e; } @@ -150,8 +145,7 @@ public class SymmetricClusterTest extends ClusterTestBase } @Test - public void testBasicRoundRobin() throws Exception - { + public void testBasicRoundRobin() throws Exception { setupCluster(); startServers(); @@ -193,10 +187,8 @@ public class SymmetricClusterTest extends ClusterTestBase verifyNotReceive(0, 1, 2, 3, 4); } - @Test - public void testBasicRoundRobinManyMessages() throws Exception - { + public void testBasicRoundRobinManyMessages() throws Exception { setupCluster(); startServers(); @@ -239,8 +231,7 @@ public class SymmetricClusterTest extends ClusterTestBase } @Test - public void testRoundRobinMultipleQueues() throws Exception - { + public void testRoundRobinMultipleQueues() throws Exception { SymmetricClusterTest.log.info("starting"); setupCluster(); @@ -330,8 +321,7 @@ public class SymmetricClusterTest extends ClusterTestBase } @Test - public void testMultipleNonLoadBalancedQueues() throws Exception - { + public void testMultipleNonLoadBalancedQueues() throws Exception { setupCluster(); startServers(); @@ -396,8 +386,7 @@ public class SymmetricClusterTest extends ClusterTestBase } @Test - public void testMixtureLoadBalancedAndNonLoadBalancedQueues() throws Exception - { + public void testMixtureLoadBalancedAndNonLoadBalancedQueues() throws Exception { setupCluster(); startServers(); @@ -504,8 +493,7 @@ public class SymmetricClusterTest extends ClusterTestBase } @Test - public void testMixtureLoadBalancedAndNonLoadBalancedQueuesRemoveSomeQueuesAndConsumers() throws Exception - { + public void testMixtureLoadBalancedAndNonLoadBalancedQueuesRemoveSomeQueuesAndConsumers() throws Exception { setupCluster(); startServers(); @@ -646,8 +634,7 @@ public class SymmetricClusterTest extends ClusterTestBase } @Test - public void testMixtureLoadBalancedAndNonLoadBalancedQueuesAddQueuesAndConsumersBeforeAllServersAreStarted() throws Exception - { + public void testMixtureLoadBalancedAndNonLoadBalancedQueuesAddQueuesAndConsumersBeforeAllServersAreStarted() throws Exception { setupCluster(); startServers(0); @@ -762,8 +749,7 @@ public class SymmetricClusterTest extends ClusterTestBase } @Test - public void testMixtureLoadBalancedAndNonLoadBalancedQueuesWithFilters() throws Exception - { + public void testMixtureLoadBalancedAndNonLoadBalancedQueuesWithFilters() throws Exception { setupCluster(); startServers(); @@ -891,8 +877,7 @@ public class SymmetricClusterTest extends ClusterTestBase } @Test - public void testMixtureLoadBalancedAndNonLoadBalancedQueuesWithConsumersWithFilters() throws Exception - { + public void testMixtureLoadBalancedAndNonLoadBalancedQueuesWithConsumersWithFilters() throws Exception { setupCluster(); startServers(); @@ -1020,8 +1005,7 @@ public class SymmetricClusterTest extends ClusterTestBase } @Test - public void testRouteWhenNoConsumersTrueLoadBalancedQueues() throws Exception - { + public void testRouteWhenNoConsumersTrueLoadBalancedQueues() throws Exception { setupCluster(MessageLoadBalancingType.STRICT); startServers(); @@ -1074,8 +1058,7 @@ public class SymmetricClusterTest extends ClusterTestBase } @Test - public void testRouteWhenNoConsumersFalseLocalConsumerLoadBalancedQueues() throws Exception - { + public void testRouteWhenNoConsumersFalseLocalConsumerLoadBalancedQueues() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); startServers(); @@ -1129,8 +1112,7 @@ public class SymmetricClusterTest extends ClusterTestBase } @Test - public void testRouteWhenNoConsumersFalseNonLoadBalancedQueues2() throws Exception - { + public void testRouteWhenNoConsumersFalseNonLoadBalancedQueues2() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); startServers(); @@ -1183,8 +1165,7 @@ public class SymmetricClusterTest extends ClusterTestBase } @Test - public void testRouteWhenNoConsumersFalseNonLoadBalancedQueues() throws Exception - { + public void testRouteWhenNoConsumersFalseNonLoadBalancedQueues() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); startServers(); @@ -1237,8 +1218,7 @@ public class SymmetricClusterTest extends ClusterTestBase } @Test - public void testRouteWhenNoConsumersTrueNonLoadBalancedQueues() throws Exception - { + public void testRouteWhenNoConsumersTrueNonLoadBalancedQueues() throws Exception { setupCluster(MessageLoadBalancingType.STRICT); startServers(); @@ -1291,8 +1271,7 @@ public class SymmetricClusterTest extends ClusterTestBase } @Test - public void testNoLocalQueueNonLoadBalancedQueues() throws Exception - { + public void testNoLocalQueueNonLoadBalancedQueues() throws Exception { setupCluster(MessageLoadBalancingType.STRICT); startServers(); @@ -1330,8 +1309,7 @@ public class SymmetricClusterTest extends ClusterTestBase } @Test - public void testNoLocalQueueLoadBalancedQueues() throws Exception - { + public void testNoLocalQueueLoadBalancedQueues() throws Exception { setupCluster(MessageLoadBalancingType.STRICT); startServers(); @@ -1368,13 +1346,11 @@ public class SymmetricClusterTest extends ClusterTestBase verifyReceiveRoundRobinInSomeOrder(10, 1, 2, 3, 4); } - public void _testStartStopServers() throws Exception - { + public void _testStartStopServers() throws Exception { doTestStartStopServers(1, 3000); } - public void doTestStartStopServers(long pauseBeforeServerRestarts, long pauseAfterServerRestarts) throws Exception - { + public void doTestStartStopServers(long pauseBeforeServerRestarts, long pauseAfterServerRestarts) throws Exception { setupCluster(); startServers(); @@ -1567,8 +1543,7 @@ public class SymmetricClusterTest extends ClusterTestBase } @Test - public void testStopSuccessiveServers() throws Exception - { + public void testStopSuccessiveServers() throws Exception { setupCluster(); startServers(); @@ -1752,9 +1727,7 @@ public class SymmetricClusterTest extends ClusterTestBase * This test verifies that addresses matching a simple string filter such as 'jms' result in bindings being created * on appropriate nodes in the cluster. It also verifies that addresses not matching the simple string filter do not * result in bindings being created. - */ - public void testClusterAddressCreatesBindingsForSimpleStringAddressFilters() throws Exception - { + */ public void testClusterAddressCreatesBindingsForSimpleStringAddressFilters() throws Exception { setupCluster("jms", "jms", "jms", "jms", "jms"); startServers(); @@ -1793,9 +1766,7 @@ public class SymmetricClusterTest extends ClusterTestBase /** * This test verifies that a string exclude filter '!jms.eu.uk' results in bindings not being created for this * address for nodes in a cluster. But ensures that other addresses are matched and bindings created. - */ - public void testClusterAddressDoesNotCreatesBindingsForStringExcludesAddressFilters() throws Exception - { + */ public void testClusterAddressDoesNotCreatesBindingsForStringExcludesAddressFilters() throws Exception { setupCluster("jms.eu.de,!jms.eu.uk", "jms.eu.de,!jms.eu.uk", "jms.eu.de,!jms.eu.uk", "jms.eu.de,!jms.eu.uk", "jms.eu.de,!jms.eu.uk"); startServers(); @@ -1833,16 +1804,12 @@ public class SymmetricClusterTest extends ClusterTestBase /** * This test verifies that remote bindings are only created for queues that match jms.eu or jms.us excluding * jms.eu.uk and jms.us.bos. Represented by the address filter 'jms.eu,!jms.eu.uk,jms.us,!jms.us.bos' + * * @throws Exception */ @Test - public void testClusterAddressFiltersExcludesAndIncludesAddressesInList() throws Exception - { - setupCluster("jms.eu,!jms.eu.uk,jms.us,!jms.us.bos", - "jms.eu,!jms.eu.uk,jms.us,!jms.us.bos", - "jms.eu,!jms.eu.uk,jms.us,!jms.us.bos", - "jms.eu,!jms.eu.uk,jms.us,!jms.us.bos", - "jms.eu,!jms.eu.uk,jms.us,!jms.us.bos"); + public void testClusterAddressFiltersExcludesAndIncludesAddressesInList() throws Exception { + setupCluster("jms.eu,!jms.eu.uk,jms.us,!jms.us.bos", "jms.eu,!jms.eu.uk,jms.us,!jms.us.bos", "jms.eu,!jms.eu.uk,jms.us,!jms.us.bos", "jms.eu,!jms.eu.uk,jms.us,!jms.us.bos", "jms.eu,!jms.eu.uk,jms.us,!jms.us.bos"); startServers(); @@ -1925,8 +1892,7 @@ public class SymmetricClusterTest extends ClusterTestBase waitForBindings(4, "jms.us.bos", 0, 0, false); } - protected void setupCluster(String addr1, String addr2, String addr3, String addr4, String addr5) throws Exception - { + protected void setupCluster(String addr1, String addr2, String addr3, String addr4, String addr5) throws Exception { setupClusterConnection("cluster0", addr1, MessageLoadBalancingType.STRICT, 1, isNetty(), 0, 1, 2, 3, 4); setupClusterConnection("cluster1", addr2, MessageLoadBalancingType.STRICT, 1, isNetty(), 1, 0, 2, 3, 4); @@ -1937,13 +1903,11 @@ public class SymmetricClusterTest extends ClusterTestBase setupClusterConnection("cluster4", addr5, MessageLoadBalancingType.STRICT, 1, isNetty(), 4, 0, 1, 2, 3); } - protected void setupCluster() throws Exception - { + protected void setupCluster() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); } - protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception - { + protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception { setupClusterConnection("cluster0", "queues", messageLoadBalancingType, 1, isNetty(), 0, 1, 2, 3, 4); setupClusterConnection("cluster1", "queues", messageLoadBalancingType, 1, isNetty(), 1, 0, 2, 3, 4); @@ -1955,8 +1919,7 @@ public class SymmetricClusterTest extends ClusterTestBase setupClusterConnection("cluster4", "queues", messageLoadBalancingType, 1, isNetty(), 4, 0, 1, 2, 3); } - protected void setupServers() throws Exception - { + protected void setupServers() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); @@ -1964,13 +1927,11 @@ public class SymmetricClusterTest extends ClusterTestBase setupServer(4, isFileStorage(), isNetty()); } - protected void startServers() throws Exception - { + protected void startServers() throws Exception { startServers(0, 1, 2, 3, 4); } - protected void stopServers() throws Exception - { + protected void stopServers() throws Exception { closeAllConsumers(); closeAllSessionFactories(); @@ -1980,10 +1941,8 @@ public class SymmetricClusterTest extends ClusterTestBase stopServers(0, 1, 2, 3, 4); } - @Override - protected boolean isFileStorage() - { + protected boolean isFileStorage() { return false; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/SymmetricClusterWithBackupTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/SymmetricClusterWithBackupTest.java index 9dc3b2f4b8..543e31f88d 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/SymmetricClusterWithBackupTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/SymmetricClusterWithBackupTest.java @@ -22,16 +22,14 @@ import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Test; -public class SymmetricClusterWithBackupTest extends SymmetricClusterTest -{ +public class SymmetricClusterWithBackupTest extends SymmetricClusterTest { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @Override @Test - public void testStopAllStartAll() throws Throwable - { - try - { + public void testStopAllStartAll() throws Throwable { + try { setupCluster(); startServers(); @@ -120,8 +118,7 @@ public class SymmetricClusterWithBackupTest extends SymmetricClusterTest verifyNotReceive(0, 1, 2, 3, 4); } - catch (Throwable e) - { + catch (Throwable e) { System.out.println(ActiveMQTestBase.threadDump("SymmetricClusterWithBackupTest::testStopAllStartAll")); throw e; } @@ -129,8 +126,7 @@ public class SymmetricClusterWithBackupTest extends SymmetricClusterTest @Override @Test - public void testMixtureLoadBalancedAndNonLoadBalancedQueuesAddQueuesAndConsumersBeforeAllServersAreStarted() throws Exception - { + public void testMixtureLoadBalancedAndNonLoadBalancedQueuesAddQueuesAndConsumersBeforeAllServersAreStarted() throws Exception { setupCluster(); startServers(5, 0); @@ -244,8 +240,7 @@ public class SymmetricClusterWithBackupTest extends SymmetricClusterTest } @Override - public void _testStartStopServers() throws Exception - { + public void _testStartStopServers() throws Exception { setupCluster(); startServers(); @@ -442,95 +437,33 @@ public class SymmetricClusterWithBackupTest extends SymmetricClusterTest } @Override - protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception - { + protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception { // The lives - setupClusterConnectionWithBackups("cluster0", - "queues", - messageLoadBalancingType, - 1, - isNetty(), - 0, - new int[]{1, 2, 3, 4}); + setupClusterConnectionWithBackups("cluster0", "queues", messageLoadBalancingType, 1, isNetty(), 0, new int[]{1, 2, 3, 4}); - setupClusterConnectionWithBackups("cluster1", - "queues", - messageLoadBalancingType, - 1, - isNetty(), - 1, - new int[]{0, 2, 3, 4}); + setupClusterConnectionWithBackups("cluster1", "queues", messageLoadBalancingType, 1, isNetty(), 1, new int[]{0, 2, 3, 4}); - setupClusterConnectionWithBackups("cluster2", - "queues", - messageLoadBalancingType, - 1, - isNetty(), - 2, - new int[]{0, 1, 3, 4}); + setupClusterConnectionWithBackups("cluster2", "queues", messageLoadBalancingType, 1, isNetty(), 2, new int[]{0, 1, 3, 4}); - setupClusterConnectionWithBackups("cluster3", - "queues", - messageLoadBalancingType, - 1, - isNetty(), - 3, - new int[]{0, 1, 2, 4}); + setupClusterConnectionWithBackups("cluster3", "queues", messageLoadBalancingType, 1, isNetty(), 3, new int[]{0, 1, 2, 4}); - setupClusterConnectionWithBackups("cluster4", - "queues", - messageLoadBalancingType, - 1, - isNetty(), - 4, - new int[]{0, 1, 2, 3}); + setupClusterConnectionWithBackups("cluster4", "queues", messageLoadBalancingType, 1, isNetty(), 4, new int[]{0, 1, 2, 3}); // The backups - setupClusterConnectionWithBackups("cluster0", - "queues", - messageLoadBalancingType, - 1, - isNetty(), - 5, - new int[]{0, 1, 2, 3, 4}); + setupClusterConnectionWithBackups("cluster0", "queues", messageLoadBalancingType, 1, isNetty(), 5, new int[]{0, 1, 2, 3, 4}); - setupClusterConnectionWithBackups("cluster1", - "queues", - messageLoadBalancingType, - 1, - isNetty(), - 6, - new int[]{0, 1, 2, 3, 4}); + setupClusterConnectionWithBackups("cluster1", "queues", messageLoadBalancingType, 1, isNetty(), 6, new int[]{0, 1, 2, 3, 4}); - setupClusterConnectionWithBackups("cluster2", - "queues", - messageLoadBalancingType, - 1, - isNetty(), - 7, - new int[]{0, 1, 2, 3, 4}); + setupClusterConnectionWithBackups("cluster2", "queues", messageLoadBalancingType, 1, isNetty(), 7, new int[]{0, 1, 2, 3, 4}); - setupClusterConnectionWithBackups("cluster3", - "queues", - messageLoadBalancingType, - 1, - isNetty(), - 8, - new int[]{0, 1, 2, 3, 4}); + setupClusterConnectionWithBackups("cluster3", "queues", messageLoadBalancingType, 1, isNetty(), 8, new int[]{0, 1, 2, 3, 4}); - setupClusterConnectionWithBackups("cluster4", - "queues", - messageLoadBalancingType, - 1, - isNetty(), - 9, - new int[]{0, 1, 2, 3, 4}); + setupClusterConnectionWithBackups("cluster4", "queues", messageLoadBalancingType, 1, isNetty(), 9, new int[]{0, 1, 2, 3, 4}); } @Override - protected void setupServers() throws Exception - { + protected void setupServers() throws Exception { // The backups setupBackupServer(5, 0, isFileStorage(), true, isNetty()); setupBackupServer(6, 1, isFileStorage(), true, isNetty()); @@ -547,8 +480,7 @@ public class SymmetricClusterWithBackupTest extends SymmetricClusterTest } @Override - protected void startServers() throws Exception - { + protected void startServers() throws Exception { // Need to set backup, since when restarting backup after it has failed over, backup will have been set to false getServer(5).getConfiguration().setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration()); @@ -561,8 +493,7 @@ public class SymmetricClusterWithBackupTest extends SymmetricClusterTest } @Override - protected void stopServers() throws Exception - { + protected void stopServers() throws Exception { closeAllConsumers(); closeAllSessionFactories(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/SymmetricClusterWithDiscoveryTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/SymmetricClusterWithDiscoveryTest.java index c4dad42cd3..6ae436e0fb 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/SymmetricClusterWithDiscoveryTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/SymmetricClusterWithDiscoveryTest.java @@ -16,33 +16,29 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.distribution; - import org.apache.activemq.artemis.core.server.cluster.impl.MessageLoadBalancingType; import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -public class SymmetricClusterWithDiscoveryTest extends SymmetricClusterTest -{ +public class SymmetricClusterWithDiscoveryTest extends SymmetricClusterTest { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; protected final String groupAddress = ActiveMQTestBase.getUDPDiscoveryAddress(); protected final int groupPort = ActiveMQTestBase.getUDPDiscoveryPort(); - protected boolean isNetty() - { + protected boolean isNetty() { return false; } @Override - protected void setupCluster() throws Exception - { + protected void setupCluster() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); } @Override - protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception - { + protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception { setupDiscoveryClusterConnection("cluster0", 0, "dg1", "queues", messageLoadBalancingType, 1, isNetty()); setupDiscoveryClusterConnection("cluster1", 1, "dg1", "queues", messageLoadBalancingType, 1, isNetty()); @@ -55,46 +51,19 @@ public class SymmetricClusterWithDiscoveryTest extends SymmetricClusterTest } @Override - protected void setupServers() throws Exception - { - setupLiveServerWithDiscovery(0, - groupAddress, - groupPort, - isFileStorage(), - isNetty(), - false); - setupLiveServerWithDiscovery(1, - groupAddress, - groupPort, - isFileStorage(), - isNetty(), - false); - setupLiveServerWithDiscovery(2, - groupAddress, - groupPort, - isFileStorage(), - isNetty(), - false); - setupLiveServerWithDiscovery(3, - groupAddress, - groupPort, - isFileStorage(), - isNetty(), - false); - setupLiveServerWithDiscovery(4, - groupAddress, - groupPort, - isFileStorage(), - isNetty(), - false); + protected void setupServers() throws Exception { + setupLiveServerWithDiscovery(0, groupAddress, groupPort, isFileStorage(), isNetty(), false); + setupLiveServerWithDiscovery(1, groupAddress, groupPort, isFileStorage(), isNetty(), false); + setupLiveServerWithDiscovery(2, groupAddress, groupPort, isFileStorage(), isNetty(), false); + setupLiveServerWithDiscovery(3, groupAddress, groupPort, isFileStorage(), isNetty(), false); + setupLiveServerWithDiscovery(4, groupAddress, groupPort, isFileStorage(), isNetty(), false); } /* * This is like testStopStartServers but we make sure we pause longer than discovery group timeout * before restarting (5 seconds) */ - public void _testStartStopServersWithPauseBeforeRestarting() throws Exception - { + public void _testStartStopServersWithPauseBeforeRestarting() throws Exception { doTestStartStopServers(10000, 3000); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/TemporaryQueueClusterTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/TemporaryQueueClusterTest.java index 9987192ed8..a698df2885 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/TemporaryQueueClusterTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/TemporaryQueueClusterTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.cluster.distribution; + import org.apache.activemq.artemis.core.server.cluster.impl.MessageLoadBalancingType; import org.junit.Before; @@ -26,20 +27,17 @@ import org.apache.activemq.artemis.api.core.client.ClientConsumer; import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.apache.activemq.artemis.api.core.client.ClientSession; -public class TemporaryQueueClusterTest extends ClusterTestBase -{ +public class TemporaryQueueClusterTest extends ClusterTestBase { @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); setupServers(); } - protected boolean isNetty() - { + protected boolean isNetty() { return false; } @@ -50,8 +48,7 @@ public class TemporaryQueueClusterTest extends ClusterTestBase * (assuming we wait for the bindings) */ @Test - public void testSendToTempQueueFromAnotherClusterNode() throws Exception - { + public void testSendToTempQueueFromAnotherClusterNode() throws Exception { setupCluster(); startServers(0, 1); @@ -62,7 +59,7 @@ public class TemporaryQueueClusterTest extends ClusterTestBase String tempAddress = "queues.tempaddress"; String tempQueue = "tempqueue"; // create temp queue on node #0 - ClientSession session = sfs[0].createSession(false, true, true); + ClientSession session = sfs[0].createSession(false, true, true); session.createTemporaryQueue(tempAddress, tempQueue); ClientConsumer consumer = session.createConsumer(tempQueue); @@ -75,11 +72,9 @@ public class TemporaryQueueClusterTest extends ClusterTestBase session.start(); // check consumer bound to node #0 receives from the temp queue - for (int j = 0; j < 10; j++) - { + for (int j = 0; j < 10; j++) { ClientMessage message = consumer.receive(5000); - if (message == null) - { + if (message == null) { Assert.assertNotNull("consumer did not receive message on temp queue " + j, message); } message.acknowledge(); @@ -90,19 +85,16 @@ public class TemporaryQueueClusterTest extends ClusterTestBase session.close(); } - protected void setupCluster() throws Exception - { + protected void setupCluster() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); } - protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception - { + protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception { setupClusterConnection("cluster0", "queues", messageLoadBalancingType, 1, isNetty(), 0, 1); setupClusterConnection("cluster1", "queues", messageLoadBalancingType, 1, isNetty(), 1, 0); } - protected void setupServers() throws Exception - { + protected void setupServers() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/TwoWayTwoNodeClusterTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/TwoWayTwoNodeClusterTest.java index 52fbe3151c..8a0ae8b25d 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/TwoWayTwoNodeClusterTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/TwoWayTwoNodeClusterTest.java @@ -21,40 +21,35 @@ import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; import org.junit.Before; import org.junit.Test; -public class TwoWayTwoNodeClusterTest extends ClusterTestBase -{ +public class TwoWayTwoNodeClusterTest extends ClusterTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); setupServers(); setupClusters(); } - protected void setupServers() throws Exception - { + protected void setupServers() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); } - protected void setupClusters() - { + protected void setupClusters() { setupClusterConnection("cluster0", 0, 1, "queues", MessageLoadBalancingType.ON_DEMAND, 1, isNetty(), false); setupClusterConnection("cluster1", 1, 0, "queues", MessageLoadBalancingType.ON_DEMAND, 1, isNetty(), false); } - protected boolean isNetty() - { + protected boolean isNetty() { return false; } @Test - public void testStartStop() throws Exception - { + public void testStartStop() throws Exception { startServers(0, 1); @@ -81,8 +76,7 @@ public class TwoWayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testStartPauseStartOther() throws Exception - { + public void testStartPauseStartOther() throws Exception { startServers(0); @@ -110,19 +104,16 @@ public class TwoWayTwoNodeClusterTest extends ClusterTestBase } @Test - public void testRestartServers() throws Throwable - { + public void testRestartServers() throws Throwable { String name = Thread.currentThread().getName(); - try - { + try { Thread.currentThread().setName("ThreadOnTestRestartTest"); startServers(0, 1); waitForTopology(servers[0], 2); waitForTopology(servers[1], 2); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { log.info("Sleep #test " + i); log.info("#stop #test #" + i); Thread.sleep(500); @@ -135,16 +126,14 @@ public class TwoWayTwoNodeClusterTest extends ClusterTestBase waitForTopology(servers[1], 2, -1, 2000); } } - finally - { + finally { Thread.currentThread().setName(name); } } @Test - public void testStopStart() throws Exception - { + public void testStopStart() throws Exception { startServers(0, 1); setupSessionFactory(0, isNetty()); @@ -184,7 +173,7 @@ public class TwoWayTwoNodeClusterTest extends ClusterTestBase setupSessionFactory(1, isNetty()); - // createQueue(1, "queues", "queue0", null, false); + // createQueue(1, "queues", "queue0", null, false); addConsumer(1, 1, "queue0", null); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/TwoWayTwoNodeClusterWithDiscoveryTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/TwoWayTwoNodeClusterWithDiscoveryTest.java index 024966ff7d..58f5e6db88 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/TwoWayTwoNodeClusterWithDiscoveryTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/distribution/TwoWayTwoNodeClusterWithDiscoveryTest.java @@ -18,8 +18,7 @@ package org.apache.activemq.artemis.tests.integration.cluster.distribution; import org.apache.activemq.artemis.core.server.cluster.impl.MessageLoadBalancingType; -public class TwoWayTwoNodeClusterWithDiscoveryTest extends TwoWayTwoNodeClusterTest -{ +public class TwoWayTwoNodeClusterWithDiscoveryTest extends TwoWayTwoNodeClusterTest { // Constants ----------------------------------------------------- @@ -40,15 +39,13 @@ public class TwoWayTwoNodeClusterWithDiscoveryTest extends TwoWayTwoNodeClusterT // Protected ----------------------------------------------------- @Override - protected void setupClusters() - { + protected void setupClusters() { setupDiscoveryClusterConnection("cluster0", 0, "dg1", "queues", MessageLoadBalancingType.ON_DEMAND, 1, isNetty()); setupDiscoveryClusterConnection("cluster1", 1, "dg1", "queues", MessageLoadBalancingType.ON_DEMAND, 1, isNetty()); } @Override - protected void setupServers() throws Exception - { + protected void setupServers() throws Exception { setupLiveServerWithDiscovery(0, groupAddress, groupPort, isFileStorage(), isNetty(), false); setupLiveServerWithDiscovery(1, groupAddress, groupPort, isFileStorage(), isNetty(), false); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/AlmostLargeAsynchronousFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/AlmostLargeAsynchronousFailoverTest.java index 924eaeb1d0..e788868faa 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/AlmostLargeAsynchronousFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/AlmostLargeAsynchronousFailoverTest.java @@ -22,28 +22,22 @@ import org.apache.activemq.artemis.core.client.impl.ServerLocatorInternal; /** * Validating failover when the size of the message Size > flow Control && message Size < minLargeMessageSize */ -public class AlmostLargeAsynchronousFailoverTest extends AsynchronousFailoverTest -{ +public class AlmostLargeAsynchronousFailoverTest extends AsynchronousFailoverTest { @Override - protected void createConfigs() throws Exception - { + protected void createConfigs() throws Exception { super.createConfigs(); liveServer.getServer().getConfiguration().setJournalFileSize(1024 * 1024); backupServer.getServer().getConfiguration().setJournalFileSize(1024 * 1024); } @Override - protected ServerLocatorInternal getServerLocator() throws Exception - { - return (ServerLocatorInternal) super.getServerLocator() - .setMinLargeMessageSize(1024 * 1024) - .setProducerWindowSize(10 * 1024); + protected ServerLocatorInternal getServerLocator() throws Exception { + return (ServerLocatorInternal) super.getServerLocator().setMinLargeMessageSize(1024 * 1024).setProducerWindowSize(10 * 1024); } @Override - protected void addPayload(ClientMessage message) - { + protected void addPayload(ClientMessage message) { message.putBytesProperty("payload", new byte[20 * 1024]); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/AsynchronousFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/AsynchronousFailoverTest.java index b0ee92f108..8ff44078df 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/AsynchronousFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/AsynchronousFailoverTest.java @@ -47,8 +47,8 @@ import org.junit.Test; *
    * Test Failover where failure is prompted by another thread */ -public class AsynchronousFailoverTest extends FailoverTestBase -{ +public class AsynchronousFailoverTest extends FailoverTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private volatile CountDownSessionFailureListener listener; @@ -58,18 +58,13 @@ public class AsynchronousFailoverTest extends FailoverTestBase private final Object lockFail = new Object(); @Test - public void testNonTransactional() throws Throwable - { - runTest(new TestRunner() - { - public void run() - { - try - { + public void testNonTransactional() throws Throwable { + runTest(new TestRunner() { + public void run() { + try { doTestNonTransactional(this); } - catch (Throwable e) - { + catch (Throwable e) { AsynchronousFailoverTest.log.error("Test failed", e); addException(e); } @@ -78,29 +73,22 @@ public class AsynchronousFailoverTest extends FailoverTestBase } @Test - public void testTransactional() throws Throwable - { - runTest(new TestRunner() - { + public void testTransactional() throws Throwable { + runTest(new TestRunner() { volatile boolean running = false; - public void run() - { - try - { + public void run() { + try { assertFalse(running); running = true; - try - { + try { doTestTransactional(this); } - finally - { + finally { running = false; } } - catch (Throwable e) - { + catch (Throwable e) { AsynchronousFailoverTest.log.error("Test failed", e); addException(e); } @@ -108,39 +96,32 @@ public class AsynchronousFailoverTest extends FailoverTestBase }); } - abstract class TestRunner implements Runnable - { + abstract class TestRunner implements Runnable { + volatile boolean failed; ArrayList errors = new ArrayList(); - boolean isFailed() - { + boolean isFailed() { return failed; } - void setFailed() - { + void setFailed() { failed = true; } - void reset() - { + void reset() { failed = false; } - synchronized void addException(Throwable e) - { + synchronized void addException(Throwable e) { errors.add(e); } - void checkForExceptions() throws Throwable - { - if (errors.size() > 0) - { + void checkForExceptions() throws Throwable { + if (errors.size() > 0) { log.warn("Exceptions on test:"); - for (Throwable e : errors) - { + for (Throwable e : errors) { log.warn(e.getMessage(), e); } // throwing the first error that happened on the Runnable @@ -151,25 +132,17 @@ public class AsynchronousFailoverTest extends FailoverTestBase } - private void runTest(final TestRunner runnable) throws Throwable - { + private void runTest(final TestRunner runnable) throws Throwable { final int numIts = 1; DelegatingSession.debug = true; - try - { - for (int i = 0; i < numIts; i++) - { + try { + for (int i = 0; i < numIts; i++) { AsynchronousFailoverTest.log.info("Iteration " + i); - ServerLocator locator = getServerLocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setReconnectAttempts(-1) - .setConfirmationWindowSize(10 * 1024 * 1024); + ServerLocator locator = getServerLocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setReconnectAttempts(-1).setConfirmationWindowSize(10 * 1024 * 1024); sf = createSessionFactoryAndWaitForTopology(locator, 2); - try - { + try { ClientSession createSession = sf.createSession(true, true); @@ -192,10 +165,8 @@ public class AsynchronousFailoverTest extends FailoverTestBase AsynchronousFailoverTest.log.info("Failing asynchronously"); // Simulate failure on connection - synchronized (lockFail) - { - if (log.isDebugEnabled()) - { + synchronized (lockFail) { + if (log.isDebugEnabled()) { log.debug("#test crashing test"); } crash(createSession); @@ -218,8 +189,7 @@ public class AsynchronousFailoverTest extends FailoverTestBase createSession.close(); - if (sf.numSessions() != 0) - { + if (sf.numSessions() != 0) { DelegatingSession.dumpSessionCreationStacks(); } @@ -227,15 +197,13 @@ public class AsynchronousFailoverTest extends FailoverTestBase locator.close(); } - finally - { + finally { locator.close(); Assert.assertEquals(0, sf.numConnections()); } - if (i != numIts - 1) - { + if (i != numIts - 1) { tearDown(); runnable.checkForExceptions(); runnable.reset(); @@ -243,20 +211,16 @@ public class AsynchronousFailoverTest extends FailoverTestBase } } } - finally - { + finally { DelegatingSession.debug = false; } } - protected void addPayload(ClientMessage msg) - { + protected void addPayload(ClientMessage msg) { } - private void doTestNonTransactional(final TestRunner runner) throws Exception - { - while (!runner.isFailed()) - { + private void doTestNonTransactional(final TestRunner runner) throws Exception { + while (!runner.isFailed()) { AsynchronousFailoverTest.log.info("looping"); ClientSession session = sf.createSession(true, true, 0); @@ -269,13 +233,10 @@ public class AsynchronousFailoverTest extends FailoverTestBase final int numMessages = 1000; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { boolean retry = false; - do - { - try - { + do { + try { ClientMessage message = session.createMessage(true); message.getBodyBuffer().writeString("message" + i); @@ -288,8 +249,7 @@ public class AsynchronousFailoverTest extends FailoverTestBase retry = false; } - catch (ActiveMQUnBlockedException ube) - { + catch (ActiveMQUnBlockedException ube) { AsynchronousFailoverTest.log.info("exception when sending message with counter " + i); ube.printStackTrace(); @@ -297,50 +257,41 @@ public class AsynchronousFailoverTest extends FailoverTestBase retry = true; } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } - } - while (retry); + } while (retry); } // create the consumer with retry if failover occurs during createConsumer call ClientConsumer consumer = null; boolean retry = false; - do - { - try - { + do { + try { consumer = session.createConsumer(FailoverTestBase.ADDRESS); retry = false; } - catch (ActiveMQUnBlockedException ube) - { + catch (ActiveMQUnBlockedException ube) { AsynchronousFailoverTest.log.info("exception when creating consumer"); retry = true; } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } - } - while (retry); + } while (retry); session.start(); List counts = new ArrayList(1000); int lastCount = -1; boolean counterGap = false; - while (true) - { + while (true) { ClientMessage message = consumer.receive(500); - if (message == null) - { + if (message == null) { break; } @@ -348,16 +299,12 @@ public class AsynchronousFailoverTest extends FailoverTestBase // are missing or duplicated int count = message.getIntProperty("counter"); counts.add(count); - if (count != lastCount + 1) - { - if (counterGap) - { + if (count != lastCount + 1) { + if (counterGap) { Assert.fail("got another counter gap at " + count + ": " + counts); } - else - { - if (lastCount != -1) - { + else { + if (lastCount != -1) { AsynchronousFailoverTest.log.info("got first counter gap at " + count); counterGap = true; } @@ -375,22 +322,18 @@ public class AsynchronousFailoverTest extends FailoverTestBase } } - private void doTestTransactional(final TestRunner runner) throws Throwable - { + private void doTestTransactional(final TestRunner runner) throws Throwable { // For duplication detection int executionId = 0; - while (!runner.isFailed()) - { + while (!runner.isFailed()) { ClientSession session = null; executionId++; log.info("#test doTestTransactional starting now. Execution " + executionId); - try - { - + try { boolean retry = false; @@ -401,14 +344,11 @@ public class AsynchronousFailoverTest extends FailoverTestBase listener = new CountDownSessionFailureListener(session); session.addFailureListener(listener); - do - { - try - { + do { + try { ClientProducer producer = session.createProducer(FailoverTestBase.ADDRESS); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(true); message.getBodyBuffer().writeString("message" + i); @@ -421,8 +361,7 @@ public class AsynchronousFailoverTest extends FailoverTestBase addPayload(message); - if (log.isDebugEnabled()) - { + if (log.isDebugEnabled()) { log.debug("Sending message " + message); } @@ -434,36 +373,30 @@ public class AsynchronousFailoverTest extends FailoverTestBase retry = false; } - catch (ActiveMQDuplicateIdException die) - { + catch (ActiveMQDuplicateIdException die) { logAndSystemOut("#test duplicate id rejected on sending"); break; } - catch (ActiveMQTransactionRolledBackException trbe) - { + catch (ActiveMQTransactionRolledBackException trbe) { log.info("#test transaction rollback retrying on sending"); // OK retry = true; } - catch (ActiveMQUnBlockedException ube) - { + catch (ActiveMQUnBlockedException ube) { log.info("#test transaction rollback retrying on sending"); // OK retry = true; } - catch (ActiveMQTransactionOutcomeUnknownException toue) - { + catch (ActiveMQTransactionOutcomeUnknownException toue) { log.info("#test transaction rollback retrying on sending"); // OK retry = true; } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { log.info("#test Exception " + e, e); throw e; } - } - while (retry); + } while (retry); logAndSystemOut("#test Finished sending, starting consumption now"); @@ -472,38 +405,30 @@ public class AsynchronousFailoverTest extends FailoverTestBase retry = false; ClientConsumer consumer = null; - do - { + do { ArrayList msgs = new ArrayList(); - try - { - if (consumer == null) - { + try { + if (consumer == null) { consumer = session.createConsumer(FailoverTestBase.ADDRESS); session.start(); } - for (int i = 0; i < numMessages; i++) - { - if (log.isDebugEnabled()) - { + for (int i = 0; i < numMessages; i++) { + if (log.isDebugEnabled()) { log.debug("Consumer receiving message " + i); } ClientMessage message = consumer.receive(10000); - if (message == null) - { + if (message == null) { break; } - if (log.isDebugEnabled()) - { + if (log.isDebugEnabled()) { log.debug("Received message " + message); } int count = message.getIntProperty("counter"); - if (count != i) - { + if (count != i) { log.warn("count was received out of order, " + count + "!=" + i); } @@ -513,58 +438,46 @@ public class AsynchronousFailoverTest extends FailoverTestBase } log.info("#test commit"); - try - { + try { session.commit(); } - catch (ActiveMQTransactionRolledBackException trbe) - { + catch (ActiveMQTransactionRolledBackException trbe) { //we know the tx has been rolled back so we just consume again retry = true; continue; } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { // This could eventually happen // We will get rid of this when we implement 2 phase commit on failover log.warn("exception during commit, it will be ignored for now" + e.getMessage(), e); } - try - { - if (blocked) - { - assertTrue("msgs.size is expected to be 0 or " + numMessages + " but it was " + msgs.size(), - msgs.size() == 0 || msgs.size() == numMessages); + try { + if (blocked) { + assertTrue("msgs.size is expected to be 0 or " + numMessages + " but it was " + msgs.size(), msgs.size() == 0 || msgs.size() == numMessages); } - else - { - assertTrue("msgs.size is expected to be " + numMessages + " but it was " + msgs.size(), - msgs.size() == numMessages); + else { + assertTrue("msgs.size is expected to be " + numMessages + " but it was " + msgs.size(), msgs.size() == numMessages); } } - catch (Throwable e) - { + catch (Throwable e) { log.info(threadDump("Thread dump, messagesReceived = " + msgs.size())); logAndSystemOut(e.getMessage() + " messages received"); - for (Integer msg : msgs) - { + for (Integer msg : msgs) { logAndSystemOut(msg.toString()); } throw e; } int i = 0; - for (Integer msg : msgs) - { + for (Integer msg : msgs) { assertEquals(i++, (int) msg); } retry = false; blocked = false; } - catch (ActiveMQTransactionRolledBackException trbe) - { + catch (ActiveMQTransactionRolledBackException trbe) { logAndSystemOut("Transaction rolled back with " + msgs.size(), trbe); // TODO: https://jira.jboss.org/jira/browse/HORNETQ-369 // ATM RolledBack exception is being called with the transaction is committed. @@ -572,8 +485,7 @@ public class AsynchronousFailoverTest extends FailoverTestBase blocked = true; retry = true; } - catch (ActiveMQTransactionOutcomeUnknownException tou) - { + catch (ActiveMQTransactionOutcomeUnknownException tou) { logAndSystemOut("Transaction rolled back with " + msgs.size(), tou); // TODO: https://jira.jboss.org/jira/browse/HORNETQ-369 // ATM RolledBack exception is being called with the transaction is committed. @@ -581,26 +493,21 @@ public class AsynchronousFailoverTest extends FailoverTestBase blocked = true; retry = true; } - catch (ActiveMQUnBlockedException ube) - { + catch (ActiveMQUnBlockedException ube) { logAndSystemOut("Unblocked with " + msgs.size(), ube); // TODO: https://jira.jboss.org/jira/browse/HORNETQ-369 // This part of the test is never being called. blocked = true; retry = true; } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { logAndSystemOut(e.getMessage(), e); throw e; } - } - while (retry); + } while (retry); } - finally - { - if (session != null) - { + finally { + if (session != null) { session.close(); } } @@ -610,14 +517,12 @@ public class AsynchronousFailoverTest extends FailoverTestBase } @Override - protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live) - { + protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live) { return TransportConfigurationUtils.getInVMAcceptor(live); } @Override - protected TransportConfiguration getConnectorTransportConfiguration(final boolean live) - { + protected TransportConfiguration getConnectorTransportConfiguration(final boolean live) { return TransportConfigurationUtils.getInVMConnector(live); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/AutomaticColocatedQuorumVoteTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/AutomaticColocatedQuorumVoteTest.java index deb4011b6f..e762a2f772 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/AutomaticColocatedQuorumVoteTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/AutomaticColocatedQuorumVoteTest.java @@ -47,37 +47,30 @@ import java.util.Map; import java.util.Set; @RunWith(value = Parameterized.class) -public class AutomaticColocatedQuorumVoteTest extends ActiveMQTestBase -{ +public class AutomaticColocatedQuorumVoteTest extends ActiveMQTestBase { + private final boolean replicated; @Parameterized.Parameters(name = "replicated={0}") - public static Collection getParameters() - { - return Arrays.asList(new Object[][] - { - {true}, - {false} - }); + public static Collection getParameters() { + return Arrays.asList(new Object[][]{{true}, {false}}); } - public AutomaticColocatedQuorumVoteTest(boolean replicated) - { + public AutomaticColocatedQuorumVoteTest(boolean replicated) { this.replicated = replicated; } + @Test - public void testSimpleDistributionBackupStrategyFull() throws Exception - { + public void testSimpleDistributionBackupStrategyFull() throws Exception { ActiveMQServer server0 = createServer(0, 1, false); ActiveMQServer server1 = createServer(1, 0, false); TransportConfiguration liveConnector0 = getConnectorTransportConfiguration("liveConnector" + 0, 0); TransportConfiguration liveConnector1 = getConnectorTransportConfiguration("liveConnector" + 1, 1); try - ( - ServerLocator serverLocator = ActiveMQClient.createServerLocatorWithoutHA(liveConnector0) - ) - { + ( + ServerLocator serverLocator = ActiveMQClient.createServerLocatorWithoutHA(liveConnector0) + ) { server0.start(); server1.start(); ClientSessionFactory sessionFactory0 = serverLocator.createSessionFactory(liveConnector0); @@ -87,9 +80,9 @@ public class AutomaticColocatedQuorumVoteTest extends ActiveMQTestBase Topology topology = serverLocator.getTopology(); Collection members = topology.getMembers(); Assert.assertEquals(members.size(), 2); - Map backupServers0 = server0.getClusterManager().getHAManager().getBackupServers(); + Map backupServers0 = server0.getClusterManager().getHAManager().getBackupServers(); Assert.assertEquals(backupServers0.size(), 1); - Map backupServers1 = server1.getClusterManager().getHAManager().getBackupServers(); + Map backupServers1 = server1.getClusterManager().getHAManager().getBackupServers(); Assert.assertEquals(backupServers1.size(), 1); ActiveMQServer backupServer0 = backupServers0.values().iterator().next(); ActiveMQServer backupServer1 = backupServers1.values().iterator().next(); @@ -111,8 +104,7 @@ public class AutomaticColocatedQuorumVoteTest extends ActiveMQTestBase Assert.assertEquals(2, connectorConfigurations1.size()); Assert.assertEquals("61717", connectorConfigurations1.get("liveConnector1").getParams().get("port")); Assert.assertEquals("61616", connectorConfigurations1.get("remoteConnector1").getParams().get("port")); - if (!replicated) - { + if (!replicated) { Assert.assertEquals(server0.getConfiguration().getJournalDirectory(), backupServer1.getConfiguration().getJournalDirectory()); Assert.assertEquals(server0.getConfiguration().getBindingsDirectory(), backupServer1.getConfiguration().getBindingsDirectory()); Assert.assertEquals(server0.getConfiguration().getLargeMessagesDirectory(), backupServer1.getConfiguration().getLargeMessagesDirectory()); @@ -122,8 +114,7 @@ public class AutomaticColocatedQuorumVoteTest extends ActiveMQTestBase Assert.assertEquals(server1.getConfiguration().getLargeMessagesDirectory(), backupServer0.getConfiguration().getLargeMessagesDirectory()); Assert.assertEquals(server1.getConfiguration().getPagingDirectory(), backupServer0.getConfiguration().getPagingDirectory()); } - else - { + else { Assert.assertNotEquals(server0.getConfiguration().getJournalDirectory(), backupServer1.getConfiguration().getJournalDirectory()); Assert.assertNotEquals(server0.getConfiguration().getBindingsDirectory(), backupServer1.getConfiguration().getBindingsDirectory()); Assert.assertNotEquals(server0.getConfiguration().getLargeMessagesDirectory(), backupServer1.getConfiguration().getLargeMessagesDirectory()); @@ -134,14 +125,11 @@ public class AutomaticColocatedQuorumVoteTest extends ActiveMQTestBase Assert.assertNotEquals(server1.getConfiguration().getPagingDirectory(), backupServer0.getConfiguration().getPagingDirectory()); } } - finally - { - try - { + finally { + try { server0.stop(); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); } server1.stop(); @@ -149,18 +137,16 @@ public class AutomaticColocatedQuorumVoteTest extends ActiveMQTestBase } @Test - public void testSimpleDistributionBackupStrategyScaleDown() throws Exception - { + public void testSimpleDistributionBackupStrategyScaleDown() throws Exception { ActiveMQServer server0 = createServer(0, 1, true); ActiveMQServer server1 = createServer(1, 0, true); TransportConfiguration liveConnector0 = getConnectorTransportConfiguration("liveConnector" + 0, 0); TransportConfiguration liveConnector1 = getConnectorTransportConfiguration("liveConnector" + 1, 1); try - ( + ( ServerLocator serverLocator = ActiveMQClient.createServerLocatorWithoutHA(liveConnector0) - ) - { + ) { server0.start(); server1.start(); ClientSessionFactory sessionFactory0 = serverLocator.createSessionFactory(liveConnector0); @@ -170,9 +156,9 @@ public class AutomaticColocatedQuorumVoteTest extends ActiveMQTestBase Topology topology = serverLocator.getTopology(); Collection members = topology.getMembers(); Assert.assertEquals(members.size(), 2); - Map backupServers0 = server0.getClusterManager().getHAManager().getBackupServers(); + Map backupServers0 = server0.getClusterManager().getHAManager().getBackupServers(); Assert.assertEquals(backupServers0.size(), 1); - Map backupServers1 = server1.getClusterManager().getHAManager().getBackupServers(); + Map backupServers1 = server1.getClusterManager().getHAManager().getBackupServers(); Assert.assertEquals(backupServers1.size(), 1); ActiveMQServer backupServer0 = backupServers0.values().iterator().next(); ActiveMQServer backupServer1 = backupServers1.values().iterator().next(); @@ -192,8 +178,7 @@ public class AutomaticColocatedQuorumVoteTest extends ActiveMQTestBase Assert.assertEquals(2, connectorConfigurations1.size()); Assert.assertEquals("61617", connectorConfigurations1.get("liveConnector1").getParams().get("port")); Assert.assertEquals("61616", connectorConfigurations1.get("remoteConnector1").getParams().get("port")); - if (!replicated) - { + if (!replicated) { Assert.assertEquals(server0.getConfiguration().getJournalDirectory(), backupServer1.getConfiguration().getJournalDirectory()); Assert.assertEquals(server0.getConfiguration().getBindingsDirectory(), backupServer1.getConfiguration().getBindingsDirectory()); Assert.assertEquals(server0.getConfiguration().getLargeMessagesDirectory(), backupServer1.getConfiguration().getLargeMessagesDirectory()); @@ -203,8 +188,7 @@ public class AutomaticColocatedQuorumVoteTest extends ActiveMQTestBase Assert.assertEquals(server1.getConfiguration().getLargeMessagesDirectory(), backupServer0.getConfiguration().getLargeMessagesDirectory()); Assert.assertEquals(server1.getConfiguration().getPagingDirectory(), backupServer0.getConfiguration().getPagingDirectory()); } - else - { + else { Assert.assertNotEquals(server0.getConfiguration().getJournalDirectory(), backupServer1.getConfiguration().getJournalDirectory()); Assert.assertNotEquals(server0.getConfiguration().getBindingsDirectory(), backupServer1.getConfiguration().getBindingsDirectory()); Assert.assertNotEquals(server0.getConfiguration().getLargeMessagesDirectory(), backupServer1.getConfiguration().getLargeMessagesDirectory()); @@ -215,14 +199,11 @@ public class AutomaticColocatedQuorumVoteTest extends ActiveMQTestBase Assert.assertNotEquals(server1.getConfiguration().getPagingDirectory(), backupServer0.getConfiguration().getPagingDirectory()); } } - finally - { - try - { + finally { + try { server0.stop(); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); } server1.stop(); @@ -230,8 +211,7 @@ public class AutomaticColocatedQuorumVoteTest extends ActiveMQTestBase } @Test - public void testSimpleDistributionOfBackupsMaxBackupsExceeded() throws Exception - { + public void testSimpleDistributionOfBackupsMaxBackupsExceeded() throws Exception { ActiveMQServer server0 = createServer(0, 1, false); ActiveMQServer server1 = createServer(1, 0, false); ActiveMQServer server2 = createServer(2, 0, false); @@ -241,12 +221,10 @@ public class AutomaticColocatedQuorumVoteTest extends ActiveMQTestBase TransportConfiguration liveConnector2 = getConnectorTransportConfiguration("liveConnector" + 2, 2); TransportConfiguration liveConnector3 = getConnectorTransportConfiguration("liveConnector" + 3, 3); - try - ( - ServerLocator serverLocator = ActiveMQClient.createServerLocatorWithoutHA(liveConnector0) - ) - { + ( + ServerLocator serverLocator = ActiveMQClient.createServerLocatorWithoutHA(liveConnector0) + ) { server0.start(); server1.start(); ClientSessionFactory sessionFactory0 = serverLocator.createSessionFactory(liveConnector0); @@ -256,9 +234,9 @@ public class AutomaticColocatedQuorumVoteTest extends ActiveMQTestBase Topology topology = serverLocator.getTopology(); Collection members = topology.getMembers(); Assert.assertEquals(members.size(), 2); - Map backupServers0 = server0.getClusterManager().getHAManager().getBackupServers(); + Map backupServers0 = server0.getClusterManager().getHAManager().getBackupServers(); Assert.assertEquals(backupServers0.size(), 1); - Map backupServers1 = server1.getClusterManager().getHAManager().getBackupServers(); + Map backupServers1 = server1.getClusterManager().getHAManager().getBackupServers(); Assert.assertEquals(backupServers1.size(), 1); ActiveMQServer backupServer0 = backupServers0.values().iterator().next(); ActiveMQServer backupServer1 = backupServers1.values().iterator().next(); @@ -274,9 +252,9 @@ public class AutomaticColocatedQuorumVoteTest extends ActiveMQTestBase waitForRemoteBackup(sessionFactory2, 10); waitForRemoteBackup(sessionFactory3, 10); Assert.assertEquals(members.size(), 2); - Map backupServers2 = server2.getClusterManager().getHAManager().getBackupServers(); + Map backupServers2 = server2.getClusterManager().getHAManager().getBackupServers(); Assert.assertEquals(backupServers2.size(), 1); - Map backupServers3 = server3.getClusterManager().getHAManager().getBackupServers(); + Map backupServers3 = server3.getClusterManager().getHAManager().getBackupServers(); Assert.assertEquals(backupServers3.size(), 1); ActiveMQServer backupServer2 = backupServers2.values().iterator().next(); ActiveMQServer backupServer3 = backupServers3.values().iterator().next(); @@ -287,8 +265,7 @@ public class AutomaticColocatedQuorumVoteTest extends ActiveMQTestBase Assert.assertEquals(server2.getNodeID(), backupServer3.getNodeID()); Assert.assertEquals(server3.getNodeID(), backupServer2.getNodeID()); } - finally - { + finally { server0.stop(); server1.stop(); server2.stop(); @@ -296,8 +273,7 @@ public class AutomaticColocatedQuorumVoteTest extends ActiveMQTestBase } } - private ActiveMQServer createServer(int node, int remoteNode, boolean scaleDown) throws Exception - { + private ActiveMQServer createServer(int node, int remoteNode, boolean scaleDown) throws Exception { TransportConfiguration liveConnector = getConnectorTransportConfiguration("liveConnector" + node, node); TransportConfiguration remoteConnector = getConnectorTransportConfiguration("remoteConnector" + node, remoteNode); TransportConfiguration liveAcceptor = getAcceptorTransportConfiguration(node); @@ -307,25 +283,17 @@ public class AutomaticColocatedQuorumVoteTest extends ActiveMQTestBase return server; } - private Configuration getConfiguration(String identity, boolean scaleDown, TransportConfiguration liveConnector, TransportConfiguration liveAcceptor, TransportConfiguration... otherLiveNodes) throws Exception - { - Configuration configuration = createDefaultInVMConfig() - .clearAcceptorConfigurations() - .addAcceptorConfiguration(liveAcceptor) - .addConnectorConfiguration(liveConnector.getName(), liveConnector) - .setJournalDirectory(getJournalDir() + identity) - .setBindingsDirectory(getBindingsDir() + identity) - .setLargeMessagesDirectory(getLargeMessagesDir() + identity) - .setPagingDirectory(getPageDir() + identity) - .addQueueConfiguration(new CoreQueueConfiguration() - .setAddress("jms.queue.testQueue") - .setName("jms.queue.testQueue")); + private Configuration getConfiguration(String identity, + boolean scaleDown, + TransportConfiguration liveConnector, + TransportConfiguration liveAcceptor, + TransportConfiguration... otherLiveNodes) throws Exception { + Configuration configuration = createDefaultInVMConfig().clearAcceptorConfigurations().addAcceptorConfiguration(liveAcceptor).addConnectorConfiguration(liveConnector.getName(), liveConnector).setJournalDirectory(getJournalDir() + identity).setBindingsDirectory(getBindingsDir() + identity).setLargeMessagesDirectory(getLargeMessagesDir() + identity).setPagingDirectory(getPageDir() + identity).addQueueConfiguration(new CoreQueueConfiguration().setAddress("jms.queue.testQueue").setName("jms.queue.testQueue")); List transportConfigurationList = new ArrayList<>(); final ColocatedPolicyConfiguration haPolicy = new ColocatedPolicyConfiguration(); - for (TransportConfiguration otherLiveNode : otherLiveNodes) - { + for (TransportConfiguration otherLiveNode : otherLiveNodes) { configuration.addConnectorConfiguration(otherLiveNode.getName(), otherLiveNode); transportConfigurationList.add(otherLiveNode.getName()); haPolicy.getExcludedConnectors().add(otherLiveNode.getName()); @@ -341,25 +309,21 @@ public class AutomaticColocatedQuorumVoteTest extends ActiveMQTestBase haPolicy.setMaxBackups(1); haPolicy.setRequestBackup(true); configuration.setHAPolicyConfiguration(haPolicy); - if (!replicated) - { + if (!replicated) { SharedStoreMasterPolicyConfiguration ssmc = new SharedStoreMasterPolicyConfiguration(); SharedStoreSlavePolicyConfiguration sssc = new SharedStoreSlavePolicyConfiguration(); haPolicy.setLiveConfig(ssmc); haPolicy.setBackupConfig(sssc); - if (scaleDown) - { + if (scaleDown) { sssc.setScaleDownConfiguration(new ScaleDownConfiguration()); } } - else - { + else { ReplicatedPolicyConfiguration rpc = new ReplicatedPolicyConfiguration(); ReplicaPolicyConfiguration rpc2 = new ReplicaPolicyConfiguration(); haPolicy.setLiveConfig(rpc); haPolicy.setBackupConfig(rpc2); - if (scaleDown) - { + if (scaleDown) { rpc2.setScaleDownConfiguration(new ScaleDownConfiguration()); } } @@ -367,15 +331,13 @@ public class AutomaticColocatedQuorumVoteTest extends ActiveMQTestBase return configuration; } - private TransportConfiguration getAcceptorTransportConfiguration(int node) - { + private TransportConfiguration getAcceptorTransportConfiguration(int node) { HashMap params = new HashMap<>(); params.put("port", "" + (61616 + node)); return new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params); } - private TransportConfiguration getConnectorTransportConfiguration(String name, int node) - { + private TransportConfiguration getConnectorTransportConfiguration(String name, int node) { HashMap params = new HashMap<>(); params.put("port", "" + (61616 + node)); return new TransportConfiguration(NETTY_CONNECTOR_FACTORY, params, name); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/BackupAuthenticationTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/BackupAuthenticationTest.java index 464690731e..f488f3e74c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/BackupAuthenticationTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/BackupAuthenticationTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.cluster.failover; + import org.apache.activemq.artemis.api.core.ActiveMQException; import org.junit.Before; @@ -31,21 +32,20 @@ import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; import org.apache.activemq.artemis.tests.util.TransportConfigurationUtils; -public class BackupAuthenticationTest extends FailoverTestBase -{ +public class BackupAuthenticationTest extends FailoverTestBase { + private static CountDownLatch latch; + @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { startBackupServer = false; latch = new CountDownLatch(1); super.setUp(); } @Test - public void testPasswordSetting() throws Exception - { + public void testPasswordSetting() throws Exception { waitForServerToStart(liveServer.getServer()); backupServer.start(); assertTrue(latch.await(5, TimeUnit.SECONDS)); @@ -61,8 +61,7 @@ public class BackupAuthenticationTest extends FailoverTestBase } @Override - protected void createConfigs() throws Exception - { + protected void createConfigs() throws Exception { createReplicatedConfigs(); backupConfig.setClusterPassword("crocodile"); liveConfig.setIncomingInterceptorClassNames(Arrays.asList(NotifyingInterceptor.class.getName())); @@ -71,29 +70,23 @@ public class BackupAuthenticationTest extends FailoverTestBase } @Override - protected TransportConfiguration getAcceptorTransportConfiguration(boolean live) - { + protected TransportConfiguration getAcceptorTransportConfiguration(boolean live) { return TransportConfigurationUtils.getInVMAcceptor(live); } @Override - protected TransportConfiguration getConnectorTransportConfiguration(boolean live) - { + protected TransportConfiguration getConnectorTransportConfiguration(boolean live) { return TransportConfigurationUtils.getInVMConnector(live); } - public static final class NotifyingInterceptor implements Interceptor - { + public static final class NotifyingInterceptor implements Interceptor { @Override - public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException - { - if (packet.getType() == PacketImpl.BACKUP_REGISTRATION) - { + public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException { + if (packet.getType() == PacketImpl.BACKUP_REGISTRATION) { latch.countDown(); } - else if (packet.getType() == PacketImpl.CLUSTER_CONNECT) - { + else if (packet.getType() == PacketImpl.CLUSTER_CONNECT) { latch.countDown(); } return true; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/BackupSyncJournalTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/BackupSyncJournalTest.java index a4c96991d0..be5870ecc2 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/BackupSyncJournalTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/BackupSyncJournalTest.java @@ -48,8 +48,8 @@ import org.apache.activemq.artemis.utils.UUID; import org.junit.Before; import org.junit.Test; -public class BackupSyncJournalTest extends FailoverTestBase -{ +public class BackupSyncJournalTest extends FailoverTestBase { + protected static final int BACKUP_WAIT_TIME = 20; private ServerLocatorInternal locator; protected ClientSessionFactoryInternal sessionFactory; @@ -59,49 +59,39 @@ public class BackupSyncJournalTest extends FailoverTestBase private final int defaultNMsgs = 20; private int n_msgs = defaultNMsgs; - protected void setNumberOfMessages(int nmsg) - { + protected void setNumberOfMessages(int nmsg) { this.n_msgs = nmsg; } - protected int getNumberOfMessages() - { + protected int getNumberOfMessages() { return n_msgs; } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { startBackupServer = false; super.setUp(); setNumberOfMessages(defaultNMsgs); - locator = (ServerLocatorInternal) getServerLocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setReconnectAttempts(-1); + locator = (ServerLocatorInternal) getServerLocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setReconnectAttempts(-1); sessionFactory = createSessionFactoryAndWaitForTopology(locator, 1); syncDelay = new BackupSyncDelay(backupServer, liveServer); } @Test - public void testNodeID() throws Exception - { + public void testNodeID() throws Exception { startBackupFinishSyncing(); assertTrue("must be running", backupServer.isStarted()); - assertEquals("backup and live should have the same nodeID", liveServer.getServer().getNodeID(), - backupServer.getServer().getNodeID()); + assertEquals("backup and live should have the same nodeID", liveServer.getServer().getNodeID(), backupServer.getServer().getNodeID()); } @Test - public void testReserveFileIdValuesOnBackup() throws Exception - { + public void testReserveFileIdValuesOnBackup() throws Exception { final int totalRounds = 50; createProducerSendSomeMessages(); JournalImpl messageJournal = getMessageJournalFromServer(liveServer); - for (int i = 0; i < totalRounds; i++) - { + for (int i = 0; i < totalRounds; i++) { messageJournal.forceMoveNextFile(); sendMessages(session, producer, n_msgs); } @@ -110,8 +100,7 @@ public class BackupSyncJournalTest extends FailoverTestBase // in case of paging I must close the current page otherwise we will get a pending counter // what would make the verification on similar journal to fail after the recovery - if (store.isPaging()) - { + if (store.isPaging()) { store.forceAnotherPage(); } backupServer.start(); @@ -124,8 +113,7 @@ public class BackupSyncJournalTest extends FailoverTestBase // in case of paging I must close the current page otherwise we will get a pending counter // what would make the verification on similar journal to fail after the recovery - if (store.isPaging()) - { + if (store.isPaging()) { store.forceAnotherPage(); } @@ -135,19 +123,16 @@ public class BackupSyncJournalTest extends FailoverTestBase // SEND more messages, now with the backup replicating sendMessages(session, producer, n_msgs); - // in case of paging I must close the current page otherwise we will get a pending counter // what would make the verification on similar journal to fail after the recovery - if (store.isPaging()) - { + if (store.isPaging()) { store.forceAnotherPage(); } Set> liveIds = getFileIds(messageJournal); int size = messageJournal.getFileSize(); PagingStore ps = liveServer.getServer().getPagingManager().getPageStore(ADDRESS); - if (ps.getPageSizeBytes() == PAGE_SIZE) - { + if (ps.getPageSizeBytes() == PAGE_SIZE) { assertTrue("isStarted", ps.isStarted()); assertFalse("start paging should return false, because we expect paging to be running", ps.startPaging()); } @@ -157,27 +142,23 @@ public class BackupSyncJournalTest extends FailoverTestBase Set> backupIds = getFileIds(backupMsgJournal); int total = 0; - for (Pair pair : liveIds) - { + for (Pair pair : liveIds) { total += pair.getB(); } int totalBackup = 0; - for (Pair pair : backupIds) - { + for (Pair pair : backupIds) { totalBackup += pair.getB(); } assertEquals("number of records must match ", total, totalBackup); // "+ 2": there two other calls that send N_MSGS. - for (int i = 0; i < totalRounds + 3; i++) - { + for (int i = 0; i < totalRounds + 3; i++) { receiveMsgsInRange(0, n_msgs); } assertNoMoreMessages(); } - protected void assertNoMoreMessages() throws ActiveMQException - { + protected void assertNoMoreMessages() throws ActiveMQException { session.start(); ClientConsumer consumer = session.createConsumer(ADDRESS); ClientMessage msg = consumer.receiveImmediate(); @@ -187,18 +168,15 @@ public class BackupSyncJournalTest extends FailoverTestBase } - protected void startBackupFinishSyncing() throws Exception - { + protected void startBackupFinishSyncing() throws Exception { syncDelay.deliverUpToDateMsg(); backupServer.start(); waitForRemoteBackup(sessionFactory, BACKUP_WAIT_TIME, true, backupServer.getServer()); } @Test - public void testReplicationDuringSync() throws Exception - { - try - { + public void testReplicationDuringSync() throws Exception { + try { createProducerSendSomeMessages(); backupServer.start(); waitForRemoteBackup(sessionFactory, BACKUP_WAIT_TIME, false, backupServer.getServer()); @@ -212,8 +190,7 @@ public class BackupSyncJournalTest extends FailoverTestBase receiveMsgsInRange(0, n_msgs); assertNoMoreMessages(); } - catch (AssertionError error) - { + catch (AssertionError error) { printJournal(liveServer); printJournal(backupServer); // test failed @@ -221,24 +198,20 @@ public class BackupSyncJournalTest extends FailoverTestBase } } - void printJournal(TestableServer server) - { - try - { + void printJournal(TestableServer server) { + try { System.out.println("\n\n BINDINGS JOURNAL\n\n"); Configuration config = server.getServer().getConfiguration(); DescribeJournal.describeBindingsJournal(config.getBindingsLocation()); System.out.println("\n\n MESSAGES JOURNAL\n\n"); DescribeJournal.describeMessagesJournal(config.getJournalLocation()); } - catch (Exception ignored) - { + catch (Exception ignored) { ignored.printStackTrace(); } } - protected void finishSyncAndFailover() throws Exception - { + protected void finishSyncAndFailover() throws Exception { syncDelay.deliverUpToDateMsg(); waitForRemoteBackup(sessionFactory, BACKUP_WAIT_TIME, true, backupServer.getServer()); assertFalse("should not be initialized", backupServer.getServer().isActive()); @@ -254,8 +227,7 @@ public class BackupSyncJournalTest extends FailoverTestBase * @throws java.io.IOException * @throws InterruptedException */ - private void assertNodeIdWasSaved() throws Exception - { + private void assertNodeIdWasSaved() throws Exception { assertTrue("backup initialized", backupServer.getServer().waitForActivation(5, TimeUnit.SECONDS)); // assert that nodeID was saved (to the right file!) @@ -265,8 +237,7 @@ public class BackupSyncJournalTest extends FailoverTestBase File serverLockFile = new File(journalDirectory, "server.lock"); assertTrue("server.lock must exist!\n " + serverLockFile, serverLockFile.exists()); RandomAccessFile raFile = new RandomAccessFile(serverLockFile, "r"); - try - { + try { // verify the nodeID was written correctly FileChannel channel = raFile.getChannel(); final int size = 16; @@ -280,15 +251,13 @@ public class BackupSyncJournalTest extends FailoverTestBase SimpleString storedNodeId = new SimpleString(uuid.toString()); assertEquals("nodeId must match", backupServer.getServer().getNodeID(), storedNodeId); } - finally - { + finally { raFile.close(); } } @Test - public void testMessageSyncSimple() throws Exception - { + public void testMessageSyncSimple() throws Exception { createProducerSendSomeMessages(); startBackupCrashLive(); receiveMsgsInRange(0, n_msgs); @@ -301,8 +270,7 @@ public class BackupSyncJournalTest extends FailoverTestBase * @throws Exception */ @Test - public void testFailBack() throws Exception - { + public void testFailBack() throws Exception { createProducerSendSomeMessages(); startBackupCrashLive(); receiveMsgsInRange(0, n_msgs); @@ -322,8 +290,7 @@ public class BackupSyncJournalTest extends FailoverTestBase assertTrue("Fail-back must initialize live!", liveServer.getServer().waitForActivation(15, TimeUnit.SECONDS)); assertFalse("must be LIVE!", liveServer.getServer().getHAPolicy().isBackup()); int i = 0; - while (backupServer.isStarted() && i++ < 100) - { + while (backupServer.isStarted() && i++ < 100) { Thread.sleep(100); } assertFalse("Backup should stop!", backupServer.getServer().isStarted()); @@ -333,8 +300,7 @@ public class BackupSyncJournalTest extends FailoverTestBase } @Test - public void testMessageSync() throws Exception - { + public void testMessageSync() throws Exception { createProducerSendSomeMessages(); receiveMsgsInRange(0, n_msgs / 2); startBackupCrashLive(); @@ -342,8 +308,7 @@ public class BackupSyncJournalTest extends FailoverTestBase assertNoMoreMessages(); } - private void startBackupCrashLive() throws Exception - { + private void startBackupCrashLive() throws Exception { assertFalse("backup is started?", backupServer.isStarted()); liveServer.removeInterceptor(syncDelay); backupServer.start(); @@ -352,8 +317,7 @@ public class BackupSyncJournalTest extends FailoverTestBase backupServer.getServer().waitForActivation(5, TimeUnit.SECONDS); } - protected void createProducerSendSomeMessages() throws ActiveMQException - { + protected void createProducerSendSomeMessages() throws ActiveMQException { session = addClientSession(sessionFactory.createSession(true, true)); session.createQueue(ADDRESS, ADDRESS, null, true); if (producer != null) @@ -363,8 +327,7 @@ public class BackupSyncJournalTest extends FailoverTestBase session.commit(); } - protected void receiveMsgsInRange(int start, int end) throws ActiveMQException - { + protected void receiveMsgsInRange(int start, int end) throws ActiveMQException { session.start(); ClientConsumer consumer = addClientConsumer(session.createConsumer(ADDRESS)); receiveMessages(consumer, start, end, true); @@ -372,11 +335,9 @@ public class BackupSyncJournalTest extends FailoverTestBase session.commit(); } - private Set> getFileIds(JournalImpl journal) - { + private Set> getFileIds(JournalImpl journal) { Set> results = new HashSet>(); - for (JournalFile jf : journal.getDataFiles()) - { + for (JournalFile jf : journal.getDataFiles()) { results.add(getPair(jf)); } results.add(getPair(journal.getCurrentFile())); @@ -387,32 +348,27 @@ public class BackupSyncJournalTest extends FailoverTestBase * @param jf * @return */ - private Pair getPair(JournalFile jf) - { + private Pair getPair(JournalFile jf) { return new Pair(jf.getFileID(), jf.getPosCount()); } - static JournalImpl getMessageJournalFromServer(TestableServer server) - { + static JournalImpl getMessageJournalFromServer(TestableServer server) { JournalStorageManager sm = (JournalStorageManager) server.getServer().getStorageManager(); return (JournalImpl) sm.getMessageJournal(); } @Override - protected void createConfigs() throws Exception - { + protected void createConfigs() throws Exception { createReplicatedConfigs(); } @Override - protected TransportConfiguration getAcceptorTransportConfiguration(boolean live) - { + protected TransportConfiguration getAcceptorTransportConfiguration(boolean live) { return TransportConfigurationUtils.getInVMAcceptor(live); } @Override - protected TransportConfiguration getConnectorTransportConfiguration(boolean live) - { + protected TransportConfiguration getConnectorTransportConfiguration(boolean live) { return TransportConfigurationUtils.getInVMConnector(live); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/BackupSyncLargeMessageTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/BackupSyncLargeMessageTest.java index 7f4b5e86ae..7f70d302ad 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/BackupSyncLargeMessageTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/BackupSyncLargeMessageTest.java @@ -35,46 +35,38 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -public class BackupSyncLargeMessageTest extends BackupSyncJournalTest -{ +public class BackupSyncLargeMessageTest extends BackupSyncJournalTest { @Override - protected void assertMessageBody(final int i, final ClientMessage message) - { + protected void assertMessageBody(final int i, final ClientMessage message) { assertLargeMessageBody(i, message); } @Override - protected ServerLocatorInternal getServerLocator() throws Exception - { - return (ServerLocatorInternal) super.getServerLocator() - .setMinLargeMessageSize(MIN_LARGE_MESSAGE); + protected ServerLocatorInternal getServerLocator() throws Exception { + return (ServerLocatorInternal) super.getServerLocator().setMinLargeMessageSize(MIN_LARGE_MESSAGE); } @Override - protected void setBody(final int i, final ClientMessage message) - { + protected void setBody(final int i, final ClientMessage message) { setLargeMessageBody(i, message); } // ------------------------ @Test - public void testDeleteLargeMessages() throws Exception - { + public void testDeleteLargeMessages() throws Exception { // 200 will increase the odds of a failure setNumberOfMessages(200); File dir = new File(backupServer.getServer().getConfiguration().getLargeMessagesDirectory()); - assertEquals("Should not have any large messages... previous test failed to clean up?", 0, - getAllMessageFileIds(dir).size()); + assertEquals("Should not have any large messages... previous test failed to clean up?", 0, getAllMessageFileIds(dir).size()); createProducerSendSomeMessages(); startBackupFinishSyncing(); receiveMsgsInRange(0, getNumberOfMessages() / 2); finishSyncAndFailover(); final int target = getNumberOfMessages() / 2; long timeout = System.currentTimeMillis() + 5000; - while (getAllMessageFileIds(dir).size() != target && System.currentTimeMillis() < timeout) - { + while (getAllMessageFileIds(dir).size() != target && System.currentTimeMillis() < timeout) { Thread.sleep(50); } assertEquals("we really ought to delete these after delivery", target, getAllMessageFileIds(dir).size()); @@ -84,13 +76,11 @@ public class BackupSyncLargeMessageTest extends BackupSyncJournalTest * @throws Exception */ @Test - public void testDeleteLargeMessagesDuringSync() throws Exception - { + public void testDeleteLargeMessagesDuringSync() throws Exception { setNumberOfMessages(200); File backupLMdir = new File(backupServer.getServer().getConfiguration().getLargeMessagesDirectory()); File liveLMDir = new File(liveServer.getServer().getConfiguration().getLargeMessagesDirectory()); - assertEquals("Should not have any large messages... previous test failed to clean up?", 0, - getAllMessageFileIds(backupLMdir).size()); + assertEquals("Should not have any large messages... previous test failed to clean up?", 0, getAllMessageFileIds(backupLMdir).size()); createProducerSendSomeMessages(); backupServer.start(); @@ -106,21 +96,19 @@ public class BackupSyncLargeMessageTest extends BackupSyncJournalTest Set backupLM = getAllMessageFileIds(backupLMdir); Set liveLM = getAllMessageFileIds(liveLMDir); assertEquals("live and backup should have the same files ", liveLM, backupLM); - assertEquals("we really ought to delete these after delivery: " + backupLM, getNumberOfMessages() / 2, - backupLM.size()); - assertEquals("we really ought to delete these after delivery", getNumberOfMessages() / 2, - getAllMessageFileIds(backupLMdir).size()); + assertEquals("we really ought to delete these after delivery: " + backupLM, getNumberOfMessages() / 2, backupLM.size()); + assertEquals("we really ought to delete these after delivery", getNumberOfMessages() / 2, getAllMessageFileIds(backupLMdir).size()); } /** * LargeMessages are passed from the client to the server in chunks. Here we test the backup * starting the data synchronization with the live in the middle of a multiple chunks large * message upload from the client to the live server. + * * @throws Exception */ @Test - public void testBackupStartsWhenLiveIsReceivingLargeMessage() throws Exception - { + public void testBackupStartsWhenLiveIsReceivingLargeMessage() throws Exception { final ClientSession session = addClientSession(sessionFactory.createSession(true, true)); session.createQueue(FailoverTestBase.ADDRESS, FailoverTestBase.ADDRESS, null, true); final ClientProducer producer = session.createProducer(FailoverTestBase.ADDRESS); @@ -132,25 +120,20 @@ public class BackupSyncLargeMessageTest extends BackupSyncJournalTest final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); - Runnable r = new Runnable() - { + Runnable r = new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { latch.countDown(); producer.send(message); sendMessages(session, producer, 20); session.commit(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { e.printStackTrace(); caughtException.set(true); } - finally - { + finally { latch2.countDown(); } } @@ -167,8 +150,7 @@ public class BackupSyncLargeMessageTest extends BackupSyncJournalTest ClientMessage msg = consumer.receive(2000); ActiveMQBuffer buffer = msg.getBodyBuffer(); - for (int j = 0; j < largeMessageSize; j++) - { + for (int j = 0; j < largeMessageSize; j++) { Assert.assertTrue("large msg , expecting " + largeMessageSize + " bytes, got " + j, buffer.readable()); Assert.assertEquals("equal at " + j, ActiveMQTestBase.getSamplebyte(j), buffer.readByte()); } @@ -178,16 +160,12 @@ public class BackupSyncLargeMessageTest extends BackupSyncJournalTest session.commit(); } - private Set getAllMessageFileIds(File dir) - { + private Set getAllMessageFileIds(File dir) { Set idsOnBkp = new TreeSet(); String[] fileList = dir.list(); - if (fileList != null) - { - for (String filename : fileList) - { - if (filename.endsWith(".msg")) - { + if (fileList != null) { + for (String filename : fileList) { + if (filename.endsWith(".msg")) { idsOnBkp.add(Long.valueOf(filename.split("\\.")[0])); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/BackupSyncPagingTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/BackupSyncPagingTest.java index ec4e91ec03..052544b0c3 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/BackupSyncPagingTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/BackupSyncPagingTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.cluster.failover; + import org.junit.Before; import org.junit.Test; @@ -28,33 +29,28 @@ import org.apache.activemq.artemis.core.server.NodeManager; import org.apache.activemq.artemis.core.settings.impl.AddressFullMessagePolicy; import org.apache.activemq.artemis.core.settings.impl.AddressSettings; -public class BackupSyncPagingTest extends BackupSyncJournalTest -{ +public class BackupSyncPagingTest extends BackupSyncJournalTest { @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); setNumberOfMessages(100); } @Override - protected ActiveMQServer createInVMFailoverServer(final boolean realFiles, final Configuration configuration, - final NodeManager nodeManager, int id) - { + protected ActiveMQServer createInVMFailoverServer(final boolean realFiles, + final Configuration configuration, + final NodeManager nodeManager, + int id) { Map conf = new HashMap(); - AddressSettings as = new AddressSettings() - .setMaxSizeBytes(PAGE_MAX) - .setPageSizeBytes(PAGE_SIZE) - .setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE); + AddressSettings as = new AddressSettings().setMaxSizeBytes(PAGE_MAX).setPageSizeBytes(PAGE_SIZE).setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE); conf.put(ADDRESS.toString(), as); return createInVMFailoverServer(realFiles, configuration, PAGE_SIZE, PAGE_MAX, conf, nodeManager, id); } @Test - public void testReplicationWithPageFileComplete() throws Exception - { + public void testReplicationWithPageFileComplete() throws Exception { // we could get a first page complete easier with this number setNumberOfMessages(20); createProducerSendSomeMessages(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ClusterWithBackupFailoverTestBase.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ClusterWithBackupFailoverTestBase.java index 3e886e864d..d3b106fb4c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ClusterWithBackupFailoverTestBase.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ClusterWithBackupFailoverTestBase.java @@ -28,8 +28,8 @@ import org.apache.activemq.artemis.tests.integration.cluster.util.TestableServer import org.junit.Before; import org.junit.Test; -public abstract class ClusterWithBackupFailoverTestBase extends ClusterTestBase -{ +public abstract class ClusterWithBackupFailoverTestBase extends ClusterTestBase { + protected static final String QUEUE_NAME = "queue0"; protected static final String QUEUES_TESTADDRESS = "queues.testaddress"; private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @@ -40,27 +40,23 @@ public abstract class ClusterWithBackupFailoverTestBase extends ClusterTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); setupServers(); } - protected boolean isNetty() - { + protected boolean isNetty() { return false; } @Test - public void testFailLiveNodes() throws Throwable - { + public void testFailLiveNodes() throws Throwable { setupCluster(); startServers(3, 4, 5, 0, 1, 2); //startServers(0, 1, 2, 3, 4, 5); - for (int i = 0; i < 3; i++) - { + for (int i = 0; i < 3; i++) { waitForTopology(servers[i], 3, 3); } @@ -177,8 +173,7 @@ public abstract class ClusterWithBackupFailoverTestBase extends ClusterTestBase removeConsumer(2); } - private void waitForBindings() throws Exception - { + private void waitForBindings() throws Exception { waitForBindings(0, QUEUES_TESTADDRESS, 1, 1, true); waitForBindings(1, QUEUES_TESTADDRESS, 1, 1, true); waitForBindings(2, QUEUES_TESTADDRESS, 1, 1, true); @@ -189,14 +184,12 @@ public abstract class ClusterWithBackupFailoverTestBase extends ClusterTestBase } @Test - public void testFailBackupNodes() throws Exception - { + public void testFailBackupNodes() throws Exception { setupCluster(); startServers(3, 4, 5, 0, 1, 2); - for (int i = 0; i < 3; i++) - { + for (int i = 0; i < 3; i++) { waitForTopology(servers[i], 3, 3); } @@ -267,25 +260,20 @@ public abstract class ClusterWithBackupFailoverTestBase extends ClusterTestBase removeConsumer(2); } - protected void setupCluster() throws Exception - { + protected void setupCluster() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); } - - protected void failNode(final int node) throws Exception - { + protected void failNode(final int node) throws Exception { failNode(node, node); } - /** * @param node The node which we should fail * @param originalLiveNode The number of the original node, to locate session to fail * @throws Exception */ - protected void failNode(final int node, final int originalLiveNode) throws Exception - { + protected void failNode(final int node, final int originalLiveNode) throws Exception { ClusterWithBackupFailoverTestBase.log.info("*** failing node " + node); ActiveMQServer server = getServer(node); @@ -297,14 +285,11 @@ public abstract class ClusterWithBackupFailoverTestBase extends ClusterTestBase tstServer.crash(sessionsArray); } - private ClientSession[] exploreSessions(final int node) - { + private ClientSession[] exploreSessions(final int node) { HashSet sessions = new HashSet(); - for (ConsumerHolder holder : consumers) - { - if (holder != null && holder.getNode() == node && holder.getSession() != null) - { + for (ConsumerHolder holder : consumers) { + if (holder != null && holder.getNode() == node && holder.getSession() != null) { sessions.add(holder.getSession()); } } @@ -314,8 +299,7 @@ public abstract class ClusterWithBackupFailoverTestBase extends ClusterTestBase } @Test - public void testFailAllNodes() throws Exception - { + public void testFailAllNodes() throws Exception { setupCluster(); startServers(0, 1, 2, 3, 4, 5); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/DelayInterceptor.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/DelayInterceptor.java index 8a4003257b..4f1468aa85 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/DelayInterceptor.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/DelayInterceptor.java @@ -22,17 +22,14 @@ import org.apache.activemq.artemis.core.protocol.core.Packet; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; -public class DelayInterceptor implements Interceptor -{ - public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException - { - if (packet.getType() == PacketImpl.SESS_SEND) - { +public class DelayInterceptor implements Interceptor { + + public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { + if (packet.getType() == PacketImpl.SESS_SEND) { // Lose the send return false; } - else - { + else { return true; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/DelayInterceptor2.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/DelayInterceptor2.java index addc83a1dd..0edf2a7890 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/DelayInterceptor2.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/DelayInterceptor2.java @@ -25,16 +25,14 @@ import org.apache.activemq.artemis.core.protocol.core.Packet; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; -public class DelayInterceptor2 implements Interceptor -{ +public class DelayInterceptor2 implements Interceptor { + private volatile boolean loseResponse = true; private final CountDownLatch latch = new CountDownLatch(1); - public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException - { - if (packet.getType() == PacketImpl.NULL_RESPONSE && loseResponse) - { + public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { + if (packet.getType() == PacketImpl.NULL_RESPONSE && loseResponse) { // Lose the response from the commit - only lose the first one loseResponse = false; @@ -43,14 +41,12 @@ public class DelayInterceptor2 implements Interceptor return false; } - else - { + else { return true; } } - public boolean await() throws InterruptedException - { + public boolean await() throws InterruptedException { return latch.await(10, TimeUnit.SECONDS); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/DelayInterceptor3.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/DelayInterceptor3.java index fdb2133207..0f1365e1c7 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/DelayInterceptor3.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/DelayInterceptor3.java @@ -22,18 +22,14 @@ import org.apache.activemq.artemis.core.protocol.core.Packet; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; -public class DelayInterceptor3 implements Interceptor -{ +public class DelayInterceptor3 implements Interceptor { - public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException - { - if (packet.getType() == PacketImpl.SESS_COMMIT) - { + public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { + if (packet.getType() == PacketImpl.SESS_COMMIT) { // lose the commit return false; } - else - { + else { return true; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/DiscoveryClusterWithBackupFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/DiscoveryClusterWithBackupFailoverTest.java index 9d16b45f71..0f33681a06 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/DiscoveryClusterWithBackupFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/DiscoveryClusterWithBackupFailoverTest.java @@ -16,19 +16,16 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.failover; - import org.apache.activemq.artemis.core.server.cluster.impl.MessageLoadBalancingType; -public class DiscoveryClusterWithBackupFailoverTest extends ClusterWithBackupFailoverTestBase -{ +public class DiscoveryClusterWithBackupFailoverTest extends ClusterWithBackupFailoverTestBase { protected final String groupAddress = getUDPDiscoveryAddress(); protected final int groupPort = getUDPDiscoveryPort(); @Override - protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception - { + protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception { // The lives setupDiscoveryClusterConnection("cluster0", 0, "dg1", "queues", messageLoadBalancingType, 1, isNetty()); @@ -43,8 +40,7 @@ public class DiscoveryClusterWithBackupFailoverTest extends ClusterWithBackupFai } @Override - protected void setupServers() throws Exception - { + protected void setupServers() throws Exception { // The lives setupLiveServerWithDiscovery(0, groupAddress, groupPort, isFileStorage(), isNetty(), true); setupLiveServerWithDiscovery(1, groupAddress, groupPort, isFileStorage(), isNetty(), true); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/FailBackAutoTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/FailBackAutoTest.java index 39c8abcd51..6530b681d4 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/FailBackAutoTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/FailBackAutoTest.java @@ -40,8 +40,8 @@ import org.apache.activemq.artemis.tests.util.TransportConfigurationUtils; import org.junit.Before; import org.junit.Test; -public class FailBackAutoTest extends FailoverTestBase -{ +public class FailBackAutoTest extends FailoverTestBase { + private final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private static final int NUM_MESSAGES = 100; private ServerLocatorInternal locator; @@ -49,16 +49,14 @@ public class FailBackAutoTest extends FailoverTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = getServerLocator(); } @Test - public void testAutoFailback() throws Exception - { - ((SharedStoreSlavePolicy)backupServer.getServer().getHAPolicy()).setRestartBackup(false); + public void testAutoFailback() throws Exception { + ((SharedStoreSlavePolicy) backupServer.getServer().getHAPolicy()).setRestartBackup(false); createSessionFactory(); final CountDownLatch latch = new CountDownLatch(1); @@ -120,15 +118,13 @@ public class FailBackAutoTest extends FailoverTestBase * @throws Exception * @throws Exception */ - private void verifyMessageOnServer(final int server, final int numberOfMessages) throws Exception - { + private void verifyMessageOnServer(final int server, final int numberOfMessages) throws Exception { ServerLocator backupLocator = createInVMLocator(server); ClientSessionFactory factorybkp = addSessionFactory(createSessionFactory(backupLocator)); ClientSession sessionbkp = factorybkp.createSession(false, false); sessionbkp.start(); ClientConsumer consumerbkp = sessionbkp.createConsumer(ADDRESS); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = consumerbkp.receive(1000); assertNotNull(msg); msg.acknowledge(); @@ -140,8 +136,7 @@ public class FailBackAutoTest extends FailoverTestBase } @Test - public void testAutoFailbackThenFailover() throws Exception - { + public void testAutoFailbackThenFailover() throws Exception { createSessionFactory(); ClientSession session = sendAndConsume(sf, true); @@ -202,9 +197,8 @@ public class FailBackAutoTest extends FailoverTestBase * @throws Exception */ @Test - public void testFailBack() throws Exception - { - ((SharedStoreSlavePolicy)backupServer.getServer().getHAPolicy()).setRestartBackup(false); + public void testFailBack() throws Exception { + ((SharedStoreSlavePolicy) backupServer.getServer().getHAPolicy()).setRestartBackup(false); createSessionFactory(); ClientSession session = sendAndConsume(sf, true); @@ -236,73 +230,48 @@ public class FailBackAutoTest extends FailoverTestBase receiveMessages(consumer, 0, NUM_MESSAGES, true); } - private void createSessionFactory() throws Exception - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setFailoverOnInitialConnection(true) // unnecessary? - .setReconnectAttempts(-1); + private void createSessionFactory() throws Exception { + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setFailoverOnInitialConnection(true) // unnecessary? + .setReconnectAttempts(-1); sf = createSessionFactoryAndWaitForTopology(locator, 2); } - private void wrapUpSessionFactory() - { + private void wrapUpSessionFactory() { sf.close(); assertEquals(0, sf.numSessions()); assertEquals(0, sf.numConnections()); } @Override - protected void createConfigs() throws Exception - { + protected void createConfigs() throws Exception { nodeManager = new InVMNodeManager(false); TransportConfiguration liveConnector = getConnectorTransportConfiguration(true); TransportConfiguration backupConnector = getConnectorTransportConfiguration(false); - backupConfig = super.createDefaultInVMConfig() - .clearAcceptorConfigurations() - .addAcceptorConfiguration(getAcceptorTransportConfiguration(false)) - .setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration() - .setFailbackDelay(1000) - .setRestartBackup(true)) - .addConnectorConfiguration(liveConnector.getName(), liveConnector) - .addConnectorConfiguration(backupConnector.getName(), backupConnector) - .addClusterConfiguration(basicClusterConnectionConfig(backupConnector.getName(), liveConnector.getName())); + backupConfig = super.createDefaultInVMConfig().clearAcceptorConfigurations().addAcceptorConfiguration(getAcceptorTransportConfiguration(false)).setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration().setFailbackDelay(1000).setRestartBackup(true)).addConnectorConfiguration(liveConnector.getName(), liveConnector).addConnectorConfiguration(backupConnector.getName(), backupConnector).addClusterConfiguration(basicClusterConnectionConfig(backupConnector.getName(), liveConnector.getName())); backupServer = createTestableServer(backupConfig); - liveConfig = super.createDefaultInVMConfig() - .clearAcceptorConfigurations() - .addAcceptorConfiguration(getAcceptorTransportConfiguration(true)) - .setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration() - .setFailbackDelay(100)) - .addClusterConfiguration(basicClusterConnectionConfig(liveConnector.getName(), backupConnector.getName())) - .addConnectorConfiguration(liveConnector.getName(), liveConnector) - .addConnectorConfiguration(backupConnector.getName(), backupConnector); + liveConfig = super.createDefaultInVMConfig().clearAcceptorConfigurations().addAcceptorConfiguration(getAcceptorTransportConfiguration(true)).setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration().setFailbackDelay(100)).addClusterConfiguration(basicClusterConnectionConfig(liveConnector.getName(), backupConnector.getName())).addConnectorConfiguration(liveConnector.getName(), liveConnector).addConnectorConfiguration(backupConnector.getName(), backupConnector); liveServer = createTestableServer(liveConfig); } @Override - protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live) - { + protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live) { return TransportConfigurationUtils.getInVMAcceptor(live); } @Override - protected TransportConfiguration getConnectorTransportConfiguration(final boolean live) - { + protected TransportConfiguration getConnectorTransportConfiguration(final boolean live) { return TransportConfigurationUtils.getInVMConnector(live); } - - private ClientSession sendAndConsume(final ClientSessionFactory sf, final boolean createQueue) throws Exception - { + private ClientSession sendAndConsume(final ClientSessionFactory sf, final boolean createQueue) throws Exception { ClientSession session = sf.createSession(false, true, true); - if (createQueue) - { + if (createQueue) { session.createQueue(ADDRESS, ADDRESS, null, true); } @@ -310,13 +279,8 @@ public class FailBackAutoTest extends FailoverTestBase final int numMessages = 1000; - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte) 1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); message.getBodyBuffer().writeString("aardvarks"); producer.send(message); @@ -326,8 +290,7 @@ public class FailBackAutoTest extends FailoverTestBase session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message2 = consumer.receive(); assertEquals("aardvarks", message2.getBodyBuffer().readString()); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/FailBackManualTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/FailBackManualTest.java index 45377e6cdf..82456d5c5f 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/FailBackManualTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/FailBackManualTest.java @@ -37,25 +37,20 @@ import org.apache.activemq.artemis.tests.util.TransportConfigurationUtils; import org.junit.Before; import org.junit.Test; -public class FailBackManualTest extends FailoverTestBase -{ +public class FailBackManualTest extends FailoverTestBase { + private ServerLocatorInternal locator; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = getServerLocator(); } @Test - public void testNoAutoFailback() throws Exception - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setFailoverOnInitialConnection(true) - .setReconnectAttempts(-1); + public void testNoAutoFailback() throws Exception { + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setFailoverOnInitialConnection(true).setReconnectAttempts(-1); ClientSessionFactoryInternal sf = createSessionFactoryAndWaitForTopology(locator, 2); @@ -71,8 +66,7 @@ public class FailBackManualTest extends FailoverTestBase backupServer.start(); - assertTrue(listener.getLatch() - .await(5, TimeUnit.SECONDS)); + assertTrue(listener.getLatch().await(5, TimeUnit.SECONDS)); ClientProducer producer = session.createProducer(ADDRESS); @@ -105,55 +99,35 @@ public class FailBackManualTest extends FailoverTestBase assertEquals(0, sf.numConnections()); } - @Override - protected void createConfigs() throws Exception - { + protected void createConfigs() throws Exception { nodeManager = new InVMNodeManager(false); TransportConfiguration liveConnector = getConnectorTransportConfiguration(true); TransportConfiguration backupConnector = getConnectorTransportConfiguration(false); - backupConfig = super.createDefaultInVMConfig() - .clearAcceptorConfigurations() - .addAcceptorConfiguration(getAcceptorTransportConfiguration(false)) - .setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration() - .setAllowFailBack(false)) - .addConnectorConfiguration(liveConnector.getName(), liveConnector) - .addConnectorConfiguration(backupConnector.getName(), backupConnector) - .addClusterConfiguration(basicClusterConnectionConfig(backupConnector.getName(), liveConnector.getName())); + backupConfig = super.createDefaultInVMConfig().clearAcceptorConfigurations().addAcceptorConfiguration(getAcceptorTransportConfiguration(false)).setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration().setAllowFailBack(false)).addConnectorConfiguration(liveConnector.getName(), liveConnector).addConnectorConfiguration(backupConnector.getName(), backupConnector).addClusterConfiguration(basicClusterConnectionConfig(backupConnector.getName(), liveConnector.getName())); backupServer = createTestableServer(backupConfig); - liveConfig = super.createDefaultInVMConfig() - .clearAcceptorConfigurations() - .addAcceptorConfiguration(getAcceptorTransportConfiguration(true)) - .setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration()) - .addConnectorConfiguration(liveConnector.getName(), liveConnector) - .addConnectorConfiguration(backupConnector.getName(), backupConnector) - .addClusterConfiguration(basicClusterConnectionConfig(liveConnector.getName(), backupConnector.getName())); + liveConfig = super.createDefaultInVMConfig().clearAcceptorConfigurations().addAcceptorConfiguration(getAcceptorTransportConfiguration(true)).setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration()).addConnectorConfiguration(liveConnector.getName(), liveConnector).addConnectorConfiguration(backupConnector.getName(), backupConnector).addClusterConfiguration(basicClusterConnectionConfig(liveConnector.getName(), backupConnector.getName())); liveServer = createTestableServer(liveConfig); } @Override - protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live) - { + protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live) { return TransportConfigurationUtils.getInVMAcceptor(live); } @Override - protected TransportConfiguration getConnectorTransportConfiguration(final boolean live) - { + protected TransportConfiguration getConnectorTransportConfiguration(final boolean live) { return TransportConfigurationUtils.getInVMConnector(live); } - - private ClientSession sendAndConsume(final ClientSessionFactory sf, final boolean createQueue) throws Exception - { + private ClientSession sendAndConsume(final ClientSessionFactory sf, final boolean createQueue) throws Exception { ClientSession session = sf.createSession(false, true, true); - if (createQueue) - { + if (createQueue) { session.createQueue(ADDRESS, ADDRESS, null, false); } @@ -161,16 +135,10 @@ public class FailBackManualTest extends FailoverTestBase final int numMessages = 1000; - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte) 1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); - message.getBodyBuffer() - .writeString("aardvarks"); + message.getBodyBuffer().writeString("aardvarks"); producer.send(message); } @@ -178,12 +146,10 @@ public class FailBackManualTest extends FailoverTestBase session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message2 = consumer.receive(); - assertEquals("aardvarks", message2.getBodyBuffer() - .readString()); + assertEquals("aardvarks", message2.getBodyBuffer().readString()); assertEquals(i, message2.getObjectProperty(new SimpleString("count"))); @@ -203,29 +169,23 @@ public class FailBackManualTest extends FailoverTestBase * @throws Exception */ @Override - protected void setBody(final int i, final ClientMessage message) - { - message.getBodyBuffer() - .writeString("message" + i); + protected void setBody(final int i, final ClientMessage message) { + message.getBodyBuffer().writeString("message" + i); } - static class ServerStarter implements Runnable - { + static class ServerStarter implements Runnable { + private final TestableServer server; - public ServerStarter(TestableServer server) - { + public ServerStarter(TestableServer server) { this.server = server; } - public void run() - { - try - { + public void run() { + try { server.start(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/FailoverListenerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/FailoverListenerTest.java index 52ff34afee..03c08add22 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/FailoverListenerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/FailoverListenerTest.java @@ -41,16 +41,15 @@ import org.apache.activemq.artemis.tests.util.TransportConfigurationUtils; import org.junit.Before; import org.junit.Test; -public class FailoverListenerTest extends FailoverTestBase -{ +public class FailoverListenerTest extends FailoverTestBase { + private final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private ServerLocatorInternal locator; private ClientSessionFactoryInternal sf; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = getServerLocator(); } @@ -62,8 +61,7 @@ public class FailoverListenerTest extends FailoverTestBase * @throws Exception */ @Test - public void testFailoverListenerCall() throws Exception - { + public void testFailoverListenerCall() throws Exception { createSessionFactory(2); CountDownLatch failureLatch = new CountDownLatch(1); CountDownLatch failureDoneLatch = new CountDownLatch(1); @@ -79,7 +77,6 @@ public class FailoverListenerTest extends FailoverTestBase log.info("Server Crash!!!"); - assertTrue(failureDoneLatch.await(5, TimeUnit.SECONDS)); //the backup server should be online by now assertEquals(FailoverEventType.FAILOVER_COMPLETED, listener.getFailoverEventType().get(1)); @@ -122,15 +119,13 @@ public class FailoverListenerTest extends FailoverTestBase /** * @throws Exception */ - private void verifyMessageOnServer(final int server, final int numberOfMessages) throws Exception - { + private void verifyMessageOnServer(final int server, final int numberOfMessages) throws Exception { ServerLocator backupLocator = createInVMLocator(server); ClientSessionFactory factorybkp = addSessionFactory(createSessionFactory(backupLocator)); ClientSession sessionbkp = factorybkp.createSession(false, false); sessionbkp.start(); ClientConsumer consumerbkp = sessionbkp.createConsumer(ADDRESS); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = consumerbkp.receive(1000); assertNotNull(msg); msg.acknowledge(); @@ -148,12 +143,9 @@ public class FailoverListenerTest extends FailoverTestBase * @throws Exception */ @Test - public void testFailoverFailed() throws Exception - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setFailoverOnInitialConnection(true) // unnecessary? - .setReconnectAttempts(1); + public void testFailoverFailed() throws Exception { + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setFailoverOnInitialConnection(true) // unnecessary? + .setReconnectAttempts(1); sf = createSessionFactoryAndWaitForTopology(locator, 2); //make sure no backup server is running @@ -177,71 +169,47 @@ public class FailoverListenerTest extends FailoverTestBase wrapUpSessionFactory(); } - private void createSessionFactory(int members) throws Exception - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setFailoverOnInitialConnection(true) // unnecessary? - .setReconnectAttempts(-1); + private void createSessionFactory(int members) throws Exception { + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setFailoverOnInitialConnection(true) // unnecessary? + .setReconnectAttempts(-1); sf = createSessionFactoryAndWaitForTopology(locator, members); } - private void wrapUpSessionFactory() - { + private void wrapUpSessionFactory() { sf.close(); assertEquals("Expecting 0 sessions", 0, sf.numSessions()); assertEquals("Expecting 0 connections", 0, sf.numConnections()); } @Override - protected void createConfigs() throws Exception - { + protected void createConfigs() throws Exception { nodeManager = new InVMNodeManager(false); TransportConfiguration liveConnector = getConnectorTransportConfiguration(true); TransportConfiguration backupConnector = getConnectorTransportConfiguration(false); - backupConfig = super.createDefaultInVMConfig() - .clearAcceptorConfigurations() - .addAcceptorConfiguration(getAcceptorTransportConfiguration(false)) - .setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration() - .setFailbackDelay(1000)) - .addConnectorConfiguration(liveConnector.getName(), liveConnector) - .addConnectorConfiguration(backupConnector.getName(), backupConnector) - .addClusterConfiguration(basicClusterConnectionConfig(backupConnector.getName(), liveConnector.getName())); + backupConfig = super.createDefaultInVMConfig().clearAcceptorConfigurations().addAcceptorConfiguration(getAcceptorTransportConfiguration(false)).setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration().setFailbackDelay(1000)).addConnectorConfiguration(liveConnector.getName(), liveConnector).addConnectorConfiguration(backupConnector.getName(), backupConnector).addClusterConfiguration(basicClusterConnectionConfig(backupConnector.getName(), liveConnector.getName())); backupServer = createTestableServer(backupConfig); - liveConfig = super.createDefaultInVMConfig() - .clearAcceptorConfigurations() - .addAcceptorConfiguration(getAcceptorTransportConfiguration(true)) - .setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration() - .setFailbackDelay(1000)) - .addClusterConfiguration(basicClusterConnectionConfig(liveConnector.getName(), backupConnector.getName())) - .addConnectorConfiguration(liveConnector.getName(), liveConnector) - .addConnectorConfiguration(backupConnector.getName(), backupConnector); + liveConfig = super.createDefaultInVMConfig().clearAcceptorConfigurations().addAcceptorConfiguration(getAcceptorTransportConfiguration(true)).setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration().setFailbackDelay(1000)).addClusterConfiguration(basicClusterConnectionConfig(liveConnector.getName(), backupConnector.getName())).addConnectorConfiguration(liveConnector.getName(), liveConnector).addConnectorConfiguration(backupConnector.getName(), backupConnector); liveServer = createTestableServer(liveConfig); } @Override - protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live) - { + protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live) { return TransportConfigurationUtils.getInVMAcceptor(live); } @Override - protected TransportConfiguration getConnectorTransportConfiguration(final boolean live) - { + protected TransportConfiguration getConnectorTransportConfiguration(final boolean live) { return TransportConfigurationUtils.getInVMConnector(live); } - - private ClientSession sendAndConsume(final ClientSessionFactory sf, final boolean createQueue) throws Exception - { + private ClientSession sendAndConsume(final ClientSessionFactory sf, final boolean createQueue) throws Exception { ClientSession session = sf.createSession(false, true, true); - if (createQueue) - { + if (createQueue) { session.createQueue(ADDRESS, ADDRESS, null, true); } @@ -249,13 +217,8 @@ public class FailoverListenerTest extends FailoverTestBase final int numMessages = 1000; - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte) 1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); message.getBodyBuffer().writeString("aardvarks"); producer.send(message); @@ -265,8 +228,7 @@ public class FailoverListenerTest extends FailoverTestBase session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message2 = consumer.receive(); assertEquals("aardvarks", message2.getBodyBuffer().readString()); @@ -285,9 +247,7 @@ public class FailoverListenerTest extends FailoverTestBase return session; } - - public class SessionFactoryFailoverListener implements FailoverEventListener - { + public class SessionFactoryFailoverListener implements FailoverEventListener { private final ArrayList failoverTypeEvent = new ArrayList(); @@ -295,28 +255,23 @@ public class FailoverListenerTest extends FailoverTestBase private final CountDownLatch failureDoneLatch; - public SessionFactoryFailoverListener(CountDownLatch failureLatch, CountDownLatch failureDoneLatch) - { + public SessionFactoryFailoverListener(CountDownLatch failureLatch, CountDownLatch failureDoneLatch) { this.failureLatch = failureLatch; this.failureDoneLatch = failureDoneLatch; } - public ArrayList getFailoverEventType() - { + public ArrayList getFailoverEventType() { return this.failoverTypeEvent; } @Override - public void failoverEvent(FailoverEventType eventType) - { + public void failoverEvent(FailoverEventType eventType) { this.failoverTypeEvent.add(eventType); log.info("Failover event just happen : " + eventType.toString()); - if (eventType == FailoverEventType.FAILURE_DETECTED) - { + if (eventType == FailoverEventType.FAILURE_DETECTED) { failureLatch.countDown(); } - else if (eventType == FailoverEventType.FAILOVER_COMPLETED || eventType == FailoverEventType.FAILOVER_FAILED) - { + else if (eventType == FailoverEventType.FAILOVER_COMPLETED || eventType == FailoverEventType.FAILOVER_FAILED) { failureDoneLatch.countDown(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/FailoverOnFlowControlTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/FailoverOnFlowControlTest.java index e3dfc53d8e..3ed22f1a74 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/FailoverOnFlowControlTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/FailoverOnFlowControlTest.java @@ -37,47 +37,34 @@ import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; import org.apache.activemq.artemis.tests.util.TransportConfigurationUtils; -public class FailoverOnFlowControlTest extends FailoverTestBase -{ +public class FailoverOnFlowControlTest extends FailoverTestBase { private static IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @Test - public void testOverflowSend() throws Exception - { - ServerLocator locator = getServerLocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setReconnectAttempts(-1) - .setProducerWindowSize(1000) - .setRetryInterval(123); + public void testOverflowSend() throws Exception { + ServerLocator locator = getServerLocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setReconnectAttempts(-1).setProducerWindowSize(1000).setRetryInterval(123); final ArrayList sessionList = new ArrayList(); - Interceptor interceptorClient = new Interceptor() - { + Interceptor interceptorClient = new Interceptor() { AtomicInteger count = new AtomicInteger(0); - public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException - { + + public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException { log.debug("Intercept..." + packet.getClass().getName()); - if (packet instanceof SessionProducerCreditsMessage ) - { - SessionProducerCreditsMessage credit = (SessionProducerCreditsMessage)packet; + if (packet instanceof SessionProducerCreditsMessage) { + SessionProducerCreditsMessage credit = (SessionProducerCreditsMessage) packet; log.debug("Credits: " + credit.getCredits()); - if (count.incrementAndGet() == 2) - { + if (count.incrementAndGet() == 2) { log.debug("### crashing server"); - try - { + try { InVMConnection.setFlushEnabled(false); crash(false, sessionList.get(0)); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } - finally - { + finally { InVMConnection.setFlushEnabled(true); } return false; @@ -97,11 +84,9 @@ public class FailoverOnFlowControlTest extends FailoverTestBase ClientProducer producer = session.createProducer(ADDRESS); - final int numMessages = 10; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(true); message.getBodyBuffer().writeBytes(new byte[5000]); @@ -114,32 +99,25 @@ public class FailoverOnFlowControlTest extends FailoverTestBase session.close(); } - @Override - protected void createConfigs() throws Exception - { + protected void createConfigs() throws Exception { super.createConfigs(); liveServer.getServer().getConfiguration().setJournalFileSize(1024 * 1024); backupServer.getServer().getConfiguration().setJournalFileSize(1024 * 1024); } @Override - protected ServerLocatorInternal getServerLocator() throws Exception - { - return (ServerLocatorInternal) super.getServerLocator() - .setMinLargeMessageSize(1024 * 1024) - .setProducerWindowSize(10 * 1024); + protected ServerLocatorInternal getServerLocator() throws Exception { + return (ServerLocatorInternal) super.getServerLocator().setMinLargeMessageSize(1024 * 1024).setProducerWindowSize(10 * 1024); } @Override - protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live) - { + protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live) { return TransportConfigurationUtils.getInVMAcceptor(live); } @Override - protected TransportConfiguration getConnectorTransportConfiguration(final boolean live) - { + protected TransportConfiguration getConnectorTransportConfiguration(final boolean live) { return TransportConfigurationUtils.getInVMConnector(live); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/FailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/FailoverTest.java index 8115d82fcd..f46019ccb2 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/FailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/FailoverTest.java @@ -63,8 +63,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class FailoverTest extends FailoverTestBase -{ +public class FailoverTest extends FailoverTestBase { private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @@ -75,8 +74,7 @@ public class FailoverTest extends FailoverTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = getServerLocator(); } @@ -84,38 +82,31 @@ public class FailoverTest extends FailoverTestBase protected ClientSession createSession(ClientSessionFactory sf1, boolean autoCommitSends, boolean autoCommitAcks, - int ackBatchSize) throws Exception - { + int ackBatchSize) throws Exception { return addClientSession(sf1.createSession(autoCommitSends, autoCommitAcks, ackBatchSize)); } - protected ClientSession createSession(ClientSessionFactory sf1, boolean autoCommitSends, boolean autoCommitAcks) throws Exception - { + protected ClientSession createSession(ClientSessionFactory sf1, + boolean autoCommitSends, + boolean autoCommitAcks) throws Exception { return addClientSession(sf1.createSession(autoCommitSends, autoCommitAcks)); } - protected ClientSession createSession(ClientSessionFactory sf1) throws Exception - { + protected ClientSession createSession(ClientSessionFactory sf1) throws Exception { return addClientSession(sf1.createSession()); } protected ClientSession createSession(ClientSessionFactory sf1, boolean xa, boolean autoCommitSends, - boolean autoCommitAcks) throws Exception - { + boolean autoCommitAcks) throws Exception { return addClientSession(sf1.createSession(xa, autoCommitSends, autoCommitAcks)); } // https://issues.jboss.org/browse/HORNETQ-685 @Test - public void testTimeoutOnFailover() throws Exception - { - locator.setCallTimeout(1000) - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setAckBatchSize(0) - .setReconnectAttempts(-1); + public void testTimeoutOnFailover() throws Exception { + locator.setCallTimeout(1000).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setAckBatchSize(0).setReconnectAttempts(-1); ((InVMNodeManager) nodeManager).failoverPause = 500; @@ -130,37 +121,28 @@ public class FailoverTest extends FailoverTestBase final CountDownLatch latch = new CountDownLatch(10); final CountDownLatch latchFailed = new CountDownLatch(1); - Runnable r = new Runnable() - { - public void run() - { - for (int i = 0; i < 500; i++) - { + Runnable r = new Runnable() { + public void run() { + for (int i = 0; i < 500; i++) { ClientMessage message = session.createMessage(true); message.putIntProperty("counter", i); - try - { + try { System.out.println("Sent " + i); producer.send(message); - if (i < 10) - { + if (i < 10) { latch.countDown(); - if (latch.getCount() == 0) - { + if (latch.getCount() == 0) { latchFailed.await(10, TimeUnit.SECONDS); } } } - catch (Exception e) - { + catch (Exception e) { // this is our retry - try - { + try { if (!producer.isClosed()) producer.send(message); } - catch (ActiveMQException e1) - { + catch (ActiveMQException e1) { e1.printStackTrace(); } } @@ -173,16 +155,14 @@ public class FailoverTest extends FailoverTestBase crash(session); latchFailed.countDown(); t.join(30000); - if (t.isAlive()) - { + if (t.isAlive()) { t.interrupt(); Assert.fail("Thread still alive"); } Assert.assertTrue(backupServer.getServer().waitForActivation(5, TimeUnit.SECONDS)); ClientConsumer consumer = session.createConsumer(FailoverTestBase.ADDRESS); session.start(); - for (int i = 0; i < 500; i++) - { + for (int i = 0; i < 500; i++) { ClientMessage m = consumer.receive(1000); Assert.assertNotNull("message #=" + i, m); // assertEquals(i, m.getIntProperty("counter").intValue()); @@ -191,15 +171,8 @@ public class FailoverTest extends FailoverTestBase // https://issues.jboss.org/browse/HORNETQ-685 @Test - public void testTimeoutOnFailoverConsume() throws Exception - { - locator.setCallTimeout(5000) - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setAckBatchSize(0) - .setBlockOnAcknowledge(true) - .setReconnectAttempts(-1) - .setAckBatchSize(0); + public void testTimeoutOnFailoverConsume() throws Exception { + locator.setCallTimeout(5000).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setAckBatchSize(0).setBlockOnAcknowledge(true).setReconnectAttempts(-1).setAckBatchSize(0); ((InVMNodeManager) nodeManager).failoverPause = 5000L; @@ -211,8 +184,7 @@ public class FailoverTest extends FailoverTestBase final ClientProducer producer = session.createProducer(FailoverTestBase.ADDRESS); - for (int i = 0; i < 500; i++) - { + for (int i = 0; i < 500; i++) { ClientMessage message = session.createMessage(true); message.putIntProperty("counter", i); producer.send(message); @@ -226,31 +198,25 @@ public class FailoverTest extends FailoverTestBase final Map received = new HashMap(); - consumer.setMessageHandler(new MessageHandler() - { + consumer.setMessageHandler(new MessageHandler() { - public void onMessage(ClientMessage message) - { + public void onMessage(ClientMessage message) { Integer counter = message.getIntProperty("counter"); received.put(counter, message); - try - { + try { log.debug("acking message = id = " + message.getMessageID() + ", counter = " + message.getIntProperty("counter")); message.acknowledge(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { e.printStackTrace(); return; } log.debug("Acked counter = " + counter); - if (counter.equals(10)) - { + if (counter.equals(10)) { latch.countDown(); } - if (received.size() == 500) - { + if (received.size() == 500) { endLatch.countDown(); } } @@ -266,16 +232,8 @@ public class FailoverTest extends FailoverTestBase } @Test - public void testTimeoutOnFailoverConsumeBlocked() throws Exception - { - locator.setCallTimeout(5000) - .setBlockOnNonDurableSend(true) - .setConsumerWindowSize(0) - .setBlockOnDurableSend(true) - .setAckBatchSize(0) - .setBlockOnAcknowledge(true) - .setReconnectAttempts(-1) - .setAckBatchSize(0); + public void testTimeoutOnFailoverConsumeBlocked() throws Exception { + locator.setCallTimeout(5000).setBlockOnNonDurableSend(true).setConsumerWindowSize(0).setBlockOnDurableSend(true).setAckBatchSize(0).setBlockOnAcknowledge(true).setReconnectAttempts(-1).setAckBatchSize(0); ((InVMNodeManager) nodeManager).failoverPause = 5000L; @@ -287,8 +245,7 @@ public class FailoverTest extends FailoverTestBase final ClientProducer producer = session.createProducer(FailoverTestBase.ADDRESS); - for (int i = 0; i < 500; i++) - { + for (int i = 0; i < 500; i++) { ClientMessage message = session.createMessage(true); message.putIntProperty("counter", i); message.putBooleanProperty("end", i == 499); @@ -303,72 +260,56 @@ public class FailoverTest extends FailoverTestBase final Map received = new HashMap(); - Thread t = new Thread() - { + Thread t = new Thread() { @Override - public void run() - { + public void run() { ClientMessage message = null; - try - { - while ((message = getMessage()) != null) - { + try { + while ((message = getMessage()) != null) { Integer counter = message.getIntProperty("counter"); received.put(counter, message); - try - { + try { log.info("acking message = id = " + message.getMessageID() + ", counter = " + message.getIntProperty("counter")); message.acknowledge(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { e.printStackTrace(); continue; } log.info("Acked counter = " + counter); - if (counter.equals(10)) - { + if (counter.equals(10)) { latch.countDown(); } - if (received.size() == 500) - { + if (received.size() == 500) { endLatch.countDown(); } - if (message.getBooleanProperty("end")) - { + if (message.getBooleanProperty("end")) { break; } } } - catch (Exception e) - { + catch (Exception e) { Assert.fail("failing due to exception " + e); } } - private ClientMessage getMessage() - { - while (true) - { - try - { + private ClientMessage getMessage() { + while (true) { + try { ClientMessage msg = consumer.receive(20000); - if (msg == null) - { + if (msg == null) { log.info("Returning null message on consuming"); } return msg; } - catch (ActiveMQObjectClosedException oce) - { + catch (ActiveMQObjectClosedException oce) { throw new RuntimeException(oce); } - catch (ActiveMQException ignored) - { + catch (ActiveMQException ignored) { // retry ignored.printStackTrace(); } @@ -388,13 +329,8 @@ public class FailoverTest extends FailoverTestBase // https://issues.jboss.org/browse/HORNETQ-685 @Test - public void testTimeoutOnFailoverTransactionCommit() throws Exception - { - locator.setCallTimeout(2000) - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setAckBatchSize(0) - .setReconnectAttempts(-1); + public void testTimeoutOnFailoverTransactionCommit() throws Exception { + locator.setCallTimeout(2000).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setAckBatchSize(0).setReconnectAttempts(-1); ((InVMNodeManager) nodeManager).failoverPause = 5000L; @@ -410,8 +346,7 @@ public class FailoverTest extends FailoverTestBase session.start(xid, XAResource.TMNOFLAGS); - for (int i = 0; i < 500; i++) - { + for (int i = 0; i < 500; i++) { ClientMessage message = session.createMessage(true); message.putIntProperty("counter", i); @@ -422,20 +357,17 @@ public class FailoverTest extends FailoverTestBase session.prepare(xid); crash(false, session); - try - { + try { session.commit(xid, false); } - catch (XAException e) - { + catch (XAException e) { //there is still an edge condition that we must deal with session.commit(xid, false); } ClientConsumer consumer = session.createConsumer(FailoverTestBase.ADDRESS); session.start(); - for (int i = 0; i < 500; i++) - { + for (int i = 0; i < 500; i++) { ClientMessage m = consumer.receive(1000); Assert.assertNotNull(m); Assert.assertEquals(i, m.getIntProperty("counter").intValue()); @@ -444,13 +376,8 @@ public class FailoverTest extends FailoverTestBase // https://issues.jboss.org/browse/HORNETQ-685 @Test - public void testTimeoutOnFailoverTransactionRollback() throws Exception - { - locator.setCallTimeout(2000) - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setAckBatchSize(0) - .setReconnectAttempts(-1); + public void testTimeoutOnFailoverTransactionRollback() throws Exception { + locator.setCallTimeout(2000).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setAckBatchSize(0).setReconnectAttempts(-1); ((InVMNodeManager) nodeManager).failoverPause = 5000L; @@ -466,8 +393,7 @@ public class FailoverTest extends FailoverTestBase session.start(xid, XAResource.TMNOFLAGS); - for (int i = 0; i < 500; i++) - { + for (int i = 0; i < 500; i++) { ClientMessage message = session.createMessage(true); message.putIntProperty("counter", i); @@ -478,12 +404,10 @@ public class FailoverTest extends FailoverTestBase session.prepare(xid); crash(false, session); - try - { + try { session.rollback(xid); } - catch (XAException e) - { + catch (XAException e) { //there is still an edge condition that we must deal with session.rollback(xid); } @@ -502,12 +426,8 @@ public class FailoverTest extends FailoverTestBase * @throws Exception */ @Test - public void testNonTransactedWithZeroConsumerWindowSize() throws Exception - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setAckBatchSize(0) - .setReconnectAttempts(-1); + public void testNonTransactedWithZeroConsumerWindowSize() throws Exception { + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setAckBatchSize(0).setReconnectAttempts(-1); createClientSessionFactory(); @@ -517,8 +437,7 @@ public class FailoverTest extends FailoverTestBase ClientProducer producer = session.createProducer(FailoverTestBase.ADDRESS); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { ClientMessage message = session.createMessage(true); setBody(i, message); @@ -532,11 +451,9 @@ public class FailoverTest extends FailoverTestBase final CountDownLatch latch = new CountDownLatch(NUM_MESSAGES); - consumer.setMessageHandler(new MessageHandler() - { + consumer.setMessageHandler(new MessageHandler() { - public void onMessage(ClientMessage message) - { + public void onMessage(ClientMessage message) { latch.countDown(); } @@ -550,14 +467,12 @@ public class FailoverTest extends FailoverTestBase } - protected void createClientSessionFactory() throws Exception - { + protected void createClientSessionFactory() throws Exception { sf = (ClientSessionFactoryInternal) createSessionFactory(locator); } @Test - public void testNonTransacted() throws Exception - { + public void testNonTransacted() throws Exception { createSessionFactory(); ClientSession session = createSession(sf, true, true); @@ -591,21 +506,18 @@ public class FailoverTest extends FailoverTestBase * @throws Exception */ @Test - public void testFailBack() throws Exception - { + public void testFailBack() throws Exception { boolean doFailBack = true; HAPolicy haPolicy = backupServer.getServer().getHAPolicy(); - if (haPolicy instanceof ReplicaPolicy) - { - ((ReplicaPolicy)haPolicy).setMaxSavedReplicatedJournalsSize(0); + if (haPolicy instanceof ReplicaPolicy) { + ((ReplicaPolicy) haPolicy).setMaxSavedReplicatedJournalsSize(0); } simpleReplication(doFailBack); } @Test - public void testFailBackLiveRestartsBackupIsGone() throws Exception - { + public void testFailBackLiveRestartsBackupIsGone() throws Exception { locator.setFailoverOnInitialConnection(true); createSessionFactory(); ClientSession session = createSessionAndQueue(); @@ -651,15 +563,13 @@ public class FailoverTest extends FailoverTestBase } @Test - public void testSimpleReplication() throws Exception - { + public void testSimpleReplication() throws Exception { boolean doFailBack = false; simpleReplication(doFailBack); } @Test - public void testWithoutUsingTheBackup() throws Exception - { + public void testWithoutUsingTheBackup() throws Exception { locator.setFailoverOnInitialConnection(true); createSessionFactory(); ClientSession session = createSessionAndQueue(); @@ -710,8 +620,7 @@ public class FailoverTest extends FailoverTestBase * @param doFailBack * @throws Exception */ - private void simpleReplication(boolean doFailBack) throws Exception - { + private void simpleReplication(boolean doFailBack) throws Exception { locator.setFailoverOnInitialConnection(true); createSessionFactory(); ClientSession session = createSessionAndQueue(); @@ -736,22 +645,19 @@ public class FailoverTest extends FailoverTestBase session.commit(); Assert.assertEquals("backup must be running with the same nodeID", liveId, backupServer.getServer().getNodeID()); - if (doFailBack) - { + if (doFailBack) { Assert.assertFalse("must NOT be a backup", liveServer.getServer().getHAPolicy().isBackup()); adaptLiveConfigForReplicatedFailBack(liveServer); beforeRestart(liveServer); liveServer.start(); Assert.assertTrue("live initialized...", liveServer.getServer().waitForActivation(40, TimeUnit.SECONDS)); int i = 0; - while (backupServer.isStarted() && i++ < 100) - { + while (backupServer.isStarted() && i++ < 100) { Thread.sleep(100); } Assert.assertFalse("Backup should stop!", backupServer.isStarted()); } - else - { + else { backupServer.stop(); beforeRestart(backupServer); backupServer.start(); @@ -770,24 +676,19 @@ public class FailoverTest extends FailoverTestBase * @param consumer * @throws ActiveMQException */ - private void assertNoMoreMessages(ClientConsumer consumer) throws ActiveMQException - { + private void assertNoMoreMessages(ClientConsumer consumer) throws ActiveMQException { ClientMessage msg = consumer.receiveImmediate(); Assert.assertNull("there should be no more messages to receive! " + msg, msg); } - protected void createSessionFactory() throws Exception - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setReconnectAttempts(-1); + protected void createSessionFactory() throws Exception { + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setReconnectAttempts(-1); sf = createSessionFactoryAndWaitForTopology(locator, 2); } @Test - public void testConsumeTransacted() throws Exception - { + public void testConsumeTransacted() throws Exception { createSessionFactory(); ClientSession session = createSessionAndQueue(); @@ -804,8 +705,7 @@ public class FailoverTest extends FailoverTestBase session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(1000); Assert.assertNotNull("Just crashed? " + (i == 6) + " " + i, message); @@ -814,23 +714,19 @@ public class FailoverTest extends FailoverTestBase // TODO: The test won't pass if you uncomment this line // assertEquals(i, (int)message.getIntProperty("counter")); - if (i == 5) - { + if (i == 5) { crash(session); } } - try - { + try { session.commit(); Assert.fail("session must have rolled back on failover"); } - catch (ActiveMQTransactionRolledBackException trbe) - { + catch (ActiveMQTransactionRolledBackException trbe) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { Assert.fail("Invalid Exception type:" + e.getType()); } @@ -840,8 +736,7 @@ public class FailoverTest extends FailoverTestBase session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(1000); Assert.assertNotNull("Expecting message #" + i, message); @@ -858,8 +753,7 @@ public class FailoverTest extends FailoverTestBase * @return * @throws Exception */ - protected ClientSession createSessionAndQueue() throws Exception - { + protected ClientSession createSessionAndQueue() throws Exception { ClientSession session = createSession(sf, false, false); session.createQueue(FailoverTestBase.ADDRESS, FailoverTestBase.ADDRESS, null, true); @@ -868,12 +762,8 @@ public class FailoverTest extends FailoverTestBase // https://jira.jboss.org/jira/browse/HORNETQ-285 @Test - public void testFailoverOnInitialConnection() throws Exception - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setFailoverOnInitialConnection(true) - .setReconnectAttempts(-1); + public void testFailoverOnInitialConnection() throws Exception { + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setFailoverOnInitialConnection(true).setReconnectAttempts(-1); sf = createSessionFactoryAndWaitForTopology(locator, 2); @@ -886,7 +776,6 @@ public class FailoverTest extends FailoverTestBase ClientProducer producer = session.createProducer(FailoverTestBase.ADDRESS); - sendMessages(session, producer, NUM_MESSAGES); ClientConsumer consumer = session.createConsumer(FailoverTestBase.ADDRESS); @@ -899,8 +788,7 @@ public class FailoverTest extends FailoverTestBase } @Test - public void testTransactedMessagesSentSoRollback() throws Exception - { + public void testTransactedMessagesSentSoRollback() throws Exception { createSessionFactory(); ClientSession session = createSessionAndQueue(); @@ -913,18 +801,15 @@ public class FailoverTest extends FailoverTestBase Assert.assertTrue(session.isRollbackOnly()); - try - { + try { session.commit(); Assert.fail("Should throw exception"); } - catch (ActiveMQTransactionRolledBackException trbe) - { + catch (ActiveMQTransactionRolledBackException trbe) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { Assert.fail("Invalid Exception type:" + e.getType()); } @@ -944,8 +829,7 @@ public class FailoverTest extends FailoverTestBase * it can be reused again */ @Test - public void testTransactedMessagesSentSoRollbackAndContinueWork() throws Exception - { + public void testTransactedMessagesSentSoRollbackAndContinueWork() throws Exception { createSessionFactory(); ClientSession session = createSessionAndQueue(); @@ -958,18 +842,15 @@ public class FailoverTest extends FailoverTestBase Assert.assertTrue(session.isRollbackOnly()); - try - { + try { session.commit(); Assert.fail("Should throw exception"); } - catch (ActiveMQTransactionRolledBackException trbe) - { + catch (ActiveMQTransactionRolledBackException trbe) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { Assert.fail("Invalid Exception type:" + e.getType()); } @@ -996,8 +877,7 @@ public class FailoverTest extends FailoverTestBase } @Test - public void testTransactedMessagesNotSentSoNoRollback() throws Exception - { + public void testTransactedMessagesNotSentSoNoRollback() throws Exception { createSessionFactory(); ClientSession session = createSessionAndQueue(); @@ -1030,8 +910,7 @@ public class FailoverTest extends FailoverTestBase } @Test - public void testTransactedMessagesWithConsumerStartedBeforeFailover() throws Exception - { + public void testTransactedMessagesWithConsumerStartedBeforeFailover() throws Exception { createSessionFactory(); ClientSession session = createSessionAndQueue(); @@ -1070,8 +949,7 @@ public class FailoverTest extends FailoverTestBase } @Test - public void testTransactedMessagesConsumedSoRollback() throws Exception - { + public void testTransactedMessagesConsumedSoRollback() throws Exception { createSessionFactory(); ClientSession session1 = createSessionAndQueue(); @@ -1094,25 +972,21 @@ public class FailoverTest extends FailoverTestBase Assert.assertTrue(session2.isRollbackOnly()); - try - { + try { session2.commit(); Assert.fail("Should throw exception"); } - catch (ActiveMQTransactionRolledBackException trbe) - { + catch (ActiveMQTransactionRolledBackException trbe) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { Assert.fail("Invalid Exception type:" + e.getType()); } } @Test - public void testTransactedMessagesNotConsumedSoNoRollback() throws Exception - { + public void testTransactedMessagesNotConsumedSoNoRollback() throws Exception { createSessionFactory(); ClientSession session1 = createSessionAndQueue(); @@ -1140,8 +1014,7 @@ public class FailoverTest extends FailoverTestBase consumer = session2.createConsumer(FailoverTestBase.ADDRESS); - for (int i = NUM_MESSAGES / 2; i < NUM_MESSAGES; i++) - { + for (int i = NUM_MESSAGES / 2; i < NUM_MESSAGES; i++) { ClientMessage message = consumer.receive(1000); Assert.assertNotNull("expecting message " + i, message); @@ -1159,8 +1032,7 @@ public class FailoverTest extends FailoverTestBase } @Test - public void testXAMessagesSentSoRollbackOnEnd() throws Exception - { + public void testXAMessagesSentSoRollbackOnEnd() throws Exception { createSessionFactory(); ClientSession session = createSession(sf, true, false, false); @@ -1177,14 +1049,12 @@ public class FailoverTest extends FailoverTestBase crash(session); - try - { + try { session.end(xid, XAResource.TMSUCCESS); Assert.fail("Should throw exception"); } - catch (XAException e) - { + catch (XAException e) { Assert.assertEquals(XAException.XAER_RMFAIL, e.errorCode); } @@ -1199,8 +1069,7 @@ public class FailoverTest extends FailoverTestBase @Test //start a tx but sending messages after crash - public void testXAMessagesSentSoRollbackOnEnd2() throws Exception - { + public void testXAMessagesSentSoRollbackOnEnd2() throws Exception { createSessionFactory(); ClientSession session = createSession(sf, true, false, false); @@ -1219,15 +1088,13 @@ public class FailoverTest extends FailoverTestBase producer.send(createMessage(session, 1, true)); - try - { + try { session.end(xid, XAResource.TMSUCCESS); Assert.fail("Should throw exception"); } - catch (XAException e) - { -// Assert.assertEquals(XAException.XAER_NOTA, e.errorCode); + catch (XAException e) { + // Assert.assertEquals(XAException.XAER_NOTA, e.errorCode); } ClientConsumer consumer = session.createConsumer(FailoverTestBase.ADDRESS); @@ -1240,8 +1107,7 @@ public class FailoverTest extends FailoverTestBase } @Test - public void testXAMessagesSentSoRollbackOnPrepare() throws Exception - { + public void testXAMessagesSentSoRollbackOnPrepare() throws Exception { createSessionFactory(); final ClientSession session = createSession(sf, true, false, false); @@ -1260,14 +1126,12 @@ public class FailoverTest extends FailoverTestBase crash(session); - try - { + try { session.prepare(xid); Assert.fail("Should throw exception"); } - catch (XAException e) - { + catch (XAException e) { Assert.assertEquals(XAException.XAER_RMFAIL, e.errorCode); // XXXX session.rollback(); } @@ -1286,8 +1150,7 @@ public class FailoverTest extends FailoverTestBase // This might happen if 1PC optimisation kicks in @Test - public void testXAMessagesSentSoRollbackOnCommit() throws Exception - { + public void testXAMessagesSentSoRollbackOnCommit() throws Exception { createSessionFactory(); ClientSession session = createSession(sf, true, false, false); @@ -1298,7 +1161,6 @@ public class FailoverTest extends FailoverTestBase ClientProducer producer = session.createProducer(FailoverTestBase.ADDRESS); - session.start(xid, XAResource.TMNOFLAGS); sendMessagesSomeDurable(session, producer); @@ -1307,14 +1169,12 @@ public class FailoverTest extends FailoverTestBase crash(session); - try - { + try { session.commit(xid, true); Assert.fail("Should throw exception"); } - catch (XAException e) - { + catch (XAException e) { Assert.assertEquals(XAException.XAER_NOTA, e.errorCode); } @@ -1328,8 +1188,7 @@ public class FailoverTest extends FailoverTestBase } @Test - public void testXAMessagesNotSentSoNoRollbackOnCommit() throws Exception - { + public void testXAMessagesNotSentSoNoRollbackOnCommit() throws Exception { createSessionFactory(); ClientSession session = createSession(sf, true, false, false); @@ -1340,7 +1199,6 @@ public class FailoverTest extends FailoverTestBase ClientProducer producer = session.createProducer(FailoverTestBase.ADDRESS); - session.start(xid, XAResource.TMNOFLAGS); sendMessagesSomeDurable(session, producer); @@ -1371,8 +1229,7 @@ public class FailoverTest extends FailoverTestBase } @Test - public void testXAMessagesConsumedSoRollbackOnEnd() throws Exception - { + public void testXAMessagesConsumedSoRollbackOnEnd() throws Exception { createSessionFactory(); ClientSession session1 = createSessionAndQueue(); @@ -1397,29 +1254,25 @@ public class FailoverTest extends FailoverTestBase crash(session2); - try - { + try { session2.end(xid, XAResource.TMSUCCESS); Assert.fail("Should throw exception"); } - catch (XAException e) - { + catch (XAException e) { Assert.assertEquals(XAException.XAER_RMFAIL, e.errorCode); } } @Test - public void testXAMessagesConsumedSoRollbackOnEnd2() throws Exception - { + public void testXAMessagesConsumedSoRollbackOnEnd2() throws Exception { createSessionFactory(); ClientSession session1 = createSessionAndQueue(); ClientProducer producer = session1.createProducer(FailoverTestBase.ADDRESS); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { // some are durable, some are not! producer.send(createMessage(session1, i, true)); } @@ -1440,14 +1293,12 @@ public class FailoverTest extends FailoverTestBase receiveMessages(consumer); - try - { + try { session2.end(xid, XAResource.TMSUCCESS); Assert.fail("Should throw exception"); } - catch (XAException e) - { + catch (XAException e) { } // Since the end was not accepted, the messages should be redelivered @@ -1455,8 +1306,7 @@ public class FailoverTest extends FailoverTestBase } @Test - public void testXAMessagesConsumedSoRollbackOnPrepare() throws Exception - { + public void testXAMessagesConsumedSoRollbackOnPrepare() throws Exception { createSessionFactory(); ClientSession session1 = createSessionAndQueue(); @@ -1483,22 +1333,19 @@ public class FailoverTest extends FailoverTestBase crash(session2); - try - { + try { session2.prepare(xid); Assert.fail("Should throw exception"); } - catch (XAException e) - { + catch (XAException e) { Assert.assertEquals(XAException.XAER_RMFAIL, e.errorCode); } } // 1PC optimisation @Test - public void testXAMessagesConsumedSoRollbackOnCommit() throws Exception - { + public void testXAMessagesConsumedSoRollbackOnCommit() throws Exception { createSessionFactory(); ClientSession session1 = createSessionAndQueue(); @@ -1526,14 +1373,12 @@ public class FailoverTest extends FailoverTestBase crash(session2); - try - { + try { session2.commit(xid, true); Assert.fail("Should throw exception"); } - catch (XAException e) - { + catch (XAException e) { // it should be rolled back Assert.assertEquals(XAException.XAER_NOTA, e.errorCode); } @@ -1544,12 +1389,9 @@ public class FailoverTest extends FailoverTestBase } @Test - public void testCreateNewFactoryAfterFailover() throws Exception - { + public void testCreateNewFactoryAfterFailover() throws Exception { this.disableCheckThread(); - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setFailoverOnInitialConnection(true); + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setFailoverOnInitialConnection(true); sf = createSessionFactoryAndWaitForTopology(locator, 2); ClientSession session = sendAndConsume(sf, true); @@ -1558,18 +1400,14 @@ public class FailoverTest extends FailoverTestBase session.close(); - long timeout; timeout = System.currentTimeMillis() + 5000; - while (timeout > System.currentTimeMillis()) - { - try - { + while (timeout > System.currentTimeMillis()) { + try { createClientSessionFactory(); break; } - catch (Exception e) - { + catch (Exception e) { // retrying Thread.sleep(100); } @@ -1579,8 +1417,7 @@ public class FailoverTest extends FailoverTestBase } @Test - public void testFailoverMultipleSessionsWithConsumers() throws Exception - { + public void testFailoverMultipleSessionsWithConsumers() throws Exception { createSessionFactory(); final int numSessions = 5; @@ -1589,14 +1426,12 @@ public class FailoverTest extends FailoverTestBase Map> sessionConsumerMap = new HashMap>(); - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { ClientSession session = createSession(sf, true, true); List consumers = new ArrayList(); - for (int j = 0; j < numConsumersPerSession; j++) - { + for (int j = 0; j < numConsumersPerSession; j++) { SimpleString queueName = new SimpleString("queue" + i + "-" + j); session.createQueue(FailoverTestBase.ADDRESS, queueName, null, true); @@ -1613,7 +1448,6 @@ public class FailoverTest extends FailoverTestBase ClientProducer producer = sendSession.createProducer(FailoverTestBase.ADDRESS); - sendMessages(sendSession, producer, NUM_MESSAGES); Set sessionSet = sessionConsumerMap.keySet(); @@ -1621,15 +1455,12 @@ public class FailoverTest extends FailoverTestBase sessionSet.toArray(sessions); crash(sessions); - for (ClientSession session : sessionConsumerMap.keySet()) - { + for (ClientSession session : sessionConsumerMap.keySet()) { session.start(); } - for (List consumerList : sessionConsumerMap.values()) - { - for (ClientConsumer consumer : consumerList) - { + for (List consumerList : sessionConsumerMap.values()) { + for (ClientConsumer consumer : consumerList) { receiveMessages(consumer); } } @@ -1639,8 +1470,7 @@ public class FailoverTest extends FailoverTestBase * Browser will get reset to beginning after failover */ @Test - public void testFailWithBrowser() throws Exception - { + public void testFailWithBrowser() throws Exception { createSessionFactory(); ClientSession session = createSession(sf, true, true); @@ -1661,18 +1491,15 @@ public class FailoverTest extends FailoverTestBase receiveDurableMessages(consumer); } - protected void sendMessagesSomeDurable(ClientSession session, ClientProducer producer) throws Exception - { - for (int i = 0; i < NUM_MESSAGES; i++) - { + protected void sendMessagesSomeDurable(ClientSession session, ClientProducer producer) throws Exception { + for (int i = 0; i < NUM_MESSAGES; i++) { // some are durable, some are not! producer.send(createMessage(session, i, isDurable(i))); } } @Test - public void testFailThenReceiveMoreMessagesAfterFailover() throws Exception - { + public void testFailThenReceiveMoreMessagesAfterFailover() throws Exception { createSessionFactory(); ClientSession session = createSession(sf, true, true); @@ -1688,8 +1515,7 @@ public class FailoverTest extends FailoverTestBase session.start(); // Receive MSGs but don't ack! - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { ClientMessage message = consumer.receive(1000); Assert.assertNotNull(message); @@ -1706,32 +1532,26 @@ public class FailoverTest extends FailoverTestBase receiveDurableMessages(consumer); } - protected void receiveDurableMessages(ClientConsumer consumer) throws ActiveMQException - { + protected void receiveDurableMessages(ClientConsumer consumer) throws ActiveMQException { // During failover non-persistent messages may disappear but in certain cases they may survive. // For that reason the test is validating all the messages but being permissive with non-persistent messages // The test will just ack any non-persistent message, however when arriving it must be in order ClientMessage repeatMessage = null; - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { ClientMessage message; - if (repeatMessage != null) - { + if (repeatMessage != null) { message = repeatMessage; repeatMessage = null; } - else - { + else { message = consumer.receive(1000); } - if (message != null) - { + if (message != null) { int msgInternalCounter = message.getIntProperty("counter").intValue(); - if (msgInternalCounter == i + 1) - { + if (msgInternalCounter == i + 1) { // The test can only jump to the next message if the current iteration is meant for non-durable Assert.assertFalse("a message on counter=" + i + " was expected", isDurable(i)); // message belongs to the next iteration.. let's just ignore it @@ -1740,13 +1560,11 @@ public class FailoverTest extends FailoverTestBase } } - if (isDurable(i)) - { + if (isDurable(i)) { Assert.assertNotNull(message); } - if (message != null) - { + if (message != null) { assertMessageBody(i, message); Assert.assertEquals(i, message.getIntProperty("counter").intValue()); message.acknowledge(); @@ -1754,18 +1572,13 @@ public class FailoverTest extends FailoverTestBase } } - private boolean isDurable(int i) - { + private boolean isDurable(int i) { return i % 2 == 0; } @Test - public void testFailThenReceiveMoreMessagesAfterFailover2() throws Exception - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true) - .setReconnectAttempts(-1); + public void testFailThenReceiveMoreMessagesAfterFailover2() throws Exception { + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true).setReconnectAttempts(-1); sf = createSessionFactoryAndWaitForTopology(locator, 2); @@ -1786,59 +1599,47 @@ public class FailoverTest extends FailoverTestBase // Send some more - for (int i = NUM_MESSAGES; i < NUM_MESSAGES * 2; i++) - { + for (int i = NUM_MESSAGES; i < NUM_MESSAGES * 2; i++) { producer.send(createMessage(session, i, isDurable(i))); } receiveMessages(consumer, NUM_MESSAGES, NUM_MESSAGES * 2, true); } - protected void receiveMessages(ClientConsumer consumer) throws ActiveMQException - { + protected void receiveMessages(ClientConsumer consumer) throws ActiveMQException { receiveMessages(consumer, 0, NUM_MESSAGES, true); } @Test - public void testSimpleSendAfterFailoverDurableTemporary() throws Exception - { + public void testSimpleSendAfterFailoverDurableTemporary() throws Exception { doSimpleSendAfterFailover(true, true); } @Test - public void testSimpleSendAfterFailoverNonDurableTemporary() throws Exception - { + public void testSimpleSendAfterFailoverNonDurableTemporary() throws Exception { doSimpleSendAfterFailover(false, true); } @Test - public void testSimpleSendAfterFailoverDurableNonTemporary() throws Exception - { + public void testSimpleSendAfterFailoverDurableNonTemporary() throws Exception { doSimpleSendAfterFailover(true, false); } @Test - public void testSimpleSendAfterFailoverNonDurableNonTemporary() throws Exception - { + public void testSimpleSendAfterFailoverNonDurableNonTemporary() throws Exception { doSimpleSendAfterFailover(false, false); } - private void doSimpleSendAfterFailover(final boolean durable, final boolean temporary) throws Exception - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true) - .setReconnectAttempts(-1); + private void doSimpleSendAfterFailover(final boolean durable, final boolean temporary) throws Exception { + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true).setReconnectAttempts(-1); sf = createSessionFactoryAndWaitForTopology(locator, 2); ClientSession session = createSession(sf, true, true, 0); - if (temporary) - { + if (temporary) { session.createTemporaryQueue(FailoverTestBase.ADDRESS, FailoverTestBase.ADDRESS, null); } - else - { + else { session.createQueue(FailoverTestBase.ADDRESS, FailoverTestBase.ADDRESS, null, durable); } @@ -1856,12 +1657,8 @@ public class FailoverTest extends FailoverTestBase } @Test - public void testForceBlockingReturn() throws Exception - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true) - .setReconnectAttempts(-1); + public void testForceBlockingReturn() throws Exception { + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true).setReconnectAttempts(-1); createClientSessionFactory(); @@ -1874,21 +1671,18 @@ public class FailoverTest extends FailoverTestBase final ClientProducer producer = session.createProducer(FailoverTestBase.ADDRESS); - class Sender extends Thread - { + class Sender extends Thread { + @Override - public void run() - { + public void run() { ClientMessage message = session.createMessage(true); message.getBodyBuffer().writeString("message"); - try - { + try { producer.send(message); } - catch (ActiveMQException e1) - { + catch (ActiveMQException e1) { this.e = e1; } } @@ -1910,18 +1704,14 @@ public class FailoverTest extends FailoverTestBase Assert.assertEquals(sender.e.getType(), ActiveMQExceptionType.UNBLOCKED); - Assert.assertEquals(((ActiveMQException)sender.e.getCause()).getType(), ActiveMQExceptionType.DISCONNECTED); + Assert.assertEquals(((ActiveMQException) sender.e.getCause()).getType(), ActiveMQExceptionType.DISCONNECTED); session.close(); } @Test - public void testCommitOccurredUnblockedAndResendNoDuplicates() throws Exception - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setReconnectAttempts(-1) - .setBlockOnAcknowledge(true); + public void testCommitOccurredUnblockedAndResendNoDuplicates() throws Exception { + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setReconnectAttempts(-1).setBlockOnAcknowledge(true); sf = createSessionFactoryAndWaitForTopology(locator, 2); @@ -1933,12 +1723,10 @@ public class FailoverTest extends FailoverTestBase String txID = "my-tx-id"; - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { ClientMessage message = session.createMessage(true); - if (i == 0) - { + if (i == 0) { // Only need to add it on one message per tx message.putStringProperty(Message.HDR_DUPLICATE_DETECTION_ID, new SimpleString(txID)); } @@ -1950,55 +1738,46 @@ public class FailoverTest extends FailoverTestBase producer.send(message); } - class Committer extends Thread - { + class Committer extends Thread { + DelayInterceptor2 interceptor = new DelayInterceptor2(); @Override - public void run() - { - try - { + public void run() { + try { sf.getServerLocator().addIncomingInterceptor(interceptor); session.commit(); } - catch (ActiveMQTransactionRolledBackException trbe) - { + catch (ActiveMQTransactionRolledBackException trbe) { // Ok - now we retry the commit after removing the interceptor sf.getServerLocator().removeIncomingInterceptor(interceptor); - try - { + try { session.commit(); failed = false; } - catch (ActiveMQException e2) - { + catch (ActiveMQException e2) { throw new RuntimeException(e2); } } - catch (ActiveMQTransactionOutcomeUnknownException toue) - { + catch (ActiveMQTransactionOutcomeUnknownException toue) { // Ok - now we retry the commit after removing the interceptor sf.getServerLocator().removeIncomingInterceptor(interceptor); - try - { + try { session.commit(); failed = false; } - catch (ActiveMQException e2) - { + catch (ActiveMQException e2) { throw new RuntimeException(e2); } } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { //ignore } } @@ -2031,12 +1810,10 @@ public class FailoverTest extends FailoverTestBase // We now try and resend the messages since we get a transaction rolled back exception // but the commit actually succeeded, duplicate detection should kick in and prevent dups - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { ClientMessage message = session2.createMessage(true); - if (i == 0) - { + if (i == 0) { // Only need to add it on one message per tx message.putStringProperty(Message.HDR_DUPLICATE_DETECTION_ID, new SimpleString(txID)); } @@ -2048,17 +1825,14 @@ public class FailoverTest extends FailoverTestBase producer.send(message); } - try - { + try { session2.commit(); Assert.fail("expecting DUPLICATE_ID_REJECTED exception"); } - catch (ActiveMQDuplicateIdException dide) - { + catch (ActiveMQDuplicateIdException dide) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { Assert.fail("Invalid Exception type:" + e.getType()); } @@ -2074,12 +1848,8 @@ public class FailoverTest extends FailoverTestBase } @Test - public void testCommitDidNotOccurUnblockedAndResend() throws Exception - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true) - .setReconnectAttempts(-1); + public void testCommitDidNotOccurUnblockedAndResend() throws Exception { + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true).setReconnectAttempts(-1); sf = createSessionFactoryAndWaitForTopology(locator, 2); @@ -2087,57 +1857,47 @@ public class FailoverTest extends FailoverTestBase session.createQueue(FailoverTestBase.ADDRESS, FailoverTestBase.ADDRESS, null, true); - ClientProducer producer = session.createProducer(FailoverTestBase.ADDRESS); sendMessages(session, producer, NUM_MESSAGES); - class Committer extends Thread - { + class Committer extends Thread { + @Override - public void run() - { + public void run() { Interceptor interceptor = new DelayInterceptor3(); - try - { + try { liveServer.addInterceptor(interceptor); session.commit(); } - catch (ActiveMQTransactionRolledBackException trbe) - { + catch (ActiveMQTransactionRolledBackException trbe) { // Ok - now we retry the commit after removing the interceptor liveServer.removeInterceptor(interceptor); - try - { + try { session.commit(); failed = false; } - catch (ActiveMQException e2) - { + catch (ActiveMQException e2) { } } - catch (ActiveMQTransactionOutcomeUnknownException toue) - { + catch (ActiveMQTransactionOutcomeUnknownException toue) { // Ok - now we retry the commit after removing the interceptor liveServer.removeInterceptor(interceptor); - try - { + try { session.commit(); failed = false; } - catch (ActiveMQException e2) - { + catch (ActiveMQException e2) { } } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { //ignore } } @@ -2178,11 +1938,9 @@ public class FailoverTest extends FailoverTestBase } @Test - public void testBackupServerNotRemoved() throws Exception - { + public void testBackupServerNotRemoved() throws Exception { // HORNETQ-720 Disabling test for replicating backups. - if (!(backupServer.getServer().getHAPolicy() instanceof SharedStoreSlavePolicy)) - { + if (!(backupServer.getServer().getHAPolicy() instanceof SharedStoreSlavePolicy)) { waitForComponent(backupServer, 1); return; } @@ -2215,8 +1973,7 @@ public class FailoverTest extends FailoverTestBase } @Test - public void testLiveAndBackupLiveComesBack() throws Exception - { + public void testLiveAndBackupLiveComesBack() throws Exception { locator.setFailoverOnInitialConnection(true); createSessionFactory(); final CountDownLatch latch = new CountDownLatch(1); @@ -2248,8 +2005,7 @@ public class FailoverTest extends FailoverTestBase } @Test - public void testLiveAndBackupLiveComesBackNewFactory() throws Exception - { + public void testLiveAndBackupLiveComesBackNewFactory() throws Exception { locator.setFailoverOnInitialConnection(true); createSessionFactory(); @@ -2298,12 +2054,8 @@ public class FailoverTest extends FailoverTestBase } @Test - public void testLiveAndBackupBackupComesBackNewFactory() throws Exception - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setFailoverOnInitialConnection(true) - .setReconnectAttempts(-1); + public void testLiveAndBackupBackupComesBackNewFactory() throws Exception { + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setFailoverOnInitialConnection(true).setReconnectAttempts(-1); sf = createSessionFactoryAndWaitForTopology(locator, 2); @@ -2320,8 +2072,7 @@ public class FailoverTest extends FailoverTestBase // To reload security or other settings that are read during startup beforeRestart(backupServer); - if (!backupServer.getServer().getHAPolicy().isSharedStore()) - { + if (!backupServer.getServer().getHAPolicy().isSharedStore()) { // XXX // this test would not make sense in the remote replication use case, without the following backupServer.getServer().setHAPolicy(new SharedStoreMasterPolicy()); @@ -2363,40 +2114,30 @@ public class FailoverTest extends FailoverTestBase // Protected ----------------------------------------------------- @Override - protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live) - { + protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live) { return TransportConfigurationUtils.getInVMAcceptor(live); } @Override - protected TransportConfiguration getConnectorTransportConfiguration(final boolean live) - { + protected TransportConfiguration getConnectorTransportConfiguration(final boolean live) { return TransportConfigurationUtils.getInVMConnector(live); } - protected void beforeRestart(TestableServer liveServer1) - { + protected void beforeRestart(TestableServer liveServer1) { // no-op } - protected ClientSession sendAndConsume(final ClientSessionFactory sf1, final boolean createQueue) throws Exception - { + protected ClientSession sendAndConsume(final ClientSessionFactory sf1, final boolean createQueue) throws Exception { ClientSession session = createSession(sf1, false, true, true); - if (createQueue) - { + if (createQueue) { session.createQueue(FailoverTestBase.ADDRESS, FailoverTestBase.ADDRESS, null, false); } ClientProducer producer = session.createProducer(FailoverTestBase.ADDRESS); - for (int i = 0; i < NUM_MESSAGES; i++) - { - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte) 1); + for (int i = 0; i < NUM_MESSAGES; i++) { + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); message.getBodyBuffer().writeString("aardvarks"); producer.send(message); @@ -2406,8 +2147,7 @@ public class FailoverTest extends FailoverTestBase session.start(); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { ClientMessage message2 = consumer.receive(); Assert.assertEquals("aardvarks", message2.getBodyBuffer().readString()); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/FailoverTestBase.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/FailoverTestBase.java index fa23f7ef40..4dd5ad3c1d 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/FailoverTestBase.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/FailoverTestBase.java @@ -53,8 +53,7 @@ import org.junit.After; import org.junit.Assert; import org.junit.Before; -public abstract class FailoverTestBase extends ActiveMQTestBase -{ +public abstract class FailoverTestBase extends ActiveMQTestBase { // Constants ----------------------------------------------------- protected static final SimpleString ADDRESS = new SimpleString("FailoverTestAddress"); @@ -84,8 +83,7 @@ public abstract class FailoverTestBase extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); createConfigs(); @@ -93,42 +91,36 @@ public abstract class FailoverTestBase extends ActiveMQTestBase liveServer.start(); waitForServerToStart(liveServer.getServer()); - if (backupServer != null) - { + if (backupServer != null) { setBackupIdentity(); - if (startBackupServer) - { + if (startBackupServer) { backupServer.start(); waitForBackup(); } } } - protected void waitForBackup() - { + protected void waitForBackup() { waitForRemoteBackupSynchronization(backupServer.getServer()); } - protected void setBackupIdentity() - { - backupServer.setIdentity(this.getClass() - .getSimpleName() + "/backupServers"); + protected void setBackupIdentity() { + backupServer.setIdentity(this.getClass().getSimpleName() + "/backupServers"); } - protected void setLiveIdentity() - { + protected void setLiveIdentity() { liveServer.setIdentity(this.getClass().getSimpleName() + "/liveServer"); } - protected TestableServer createTestableServer(Configuration config) - { - boolean isBackup = config.getHAPolicyConfiguration() instanceof ReplicaPolicyConfiguration || - config.getHAPolicyConfiguration() instanceof SharedStoreSlavePolicyConfiguration; + protected TestableServer createTestableServer(Configuration config) { + boolean isBackup = config.getHAPolicyConfiguration() instanceof ReplicaPolicyConfiguration || config.getHAPolicyConfiguration() instanceof SharedStoreSlavePolicyConfiguration; return new SameProcessActiveMQServer(createInVMFailoverServer(true, config, nodeManager, isBackup ? 2 : 1)); } - protected TestableServer createColocatedTestableServer(Configuration config, NodeManager liveNodeManager,NodeManager backupNodeManager, int id) - { + protected TestableServer createColocatedTestableServer(Configuration config, + NodeManager liveNodeManager, + NodeManager backupNodeManager, + int id) { return new SameProcessActiveMQServer(createColocatedInVMFailoverServer(true, config, liveNodeManager, backupNodeManager, id)); } @@ -138,14 +130,11 @@ public abstract class FailoverTestBase extends ActiveMQTestBase * @param i * @param message */ - protected static void setLargeMessageBody(final int i, final ClientMessage message) - { - try - { + protected static void setLargeMessageBody(final int i, final ClientMessage message) { + try { message.setBodyInputStream(ActiveMQTestBase.createFakeLargeStream(LARGE_MESSAGE_SIZE)); } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } } @@ -156,47 +145,30 @@ public abstract class FailoverTestBase extends ActiveMQTestBase * @param i * @param message */ - protected static void assertLargeMessageBody(final int i, final ClientMessage message) - { + protected static void assertLargeMessageBody(final int i, final ClientMessage message) { ActiveMQBuffer buffer = message.getBodyBuffer(); - for (int j = 0; j < LARGE_MESSAGE_SIZE; j++) - { + for (int j = 0; j < LARGE_MESSAGE_SIZE; j++) { Assert.assertTrue("msg " + i + ", expecting " + LARGE_MESSAGE_SIZE + " bytes, got " + j, buffer.readable()); Assert.assertEquals("equal at " + j, ActiveMQTestBase.getSamplebyte(j), buffer.readByte()); } } - protected void createConfigs() throws Exception - { + protected void createConfigs() throws Exception { nodeManager = new InVMNodeManager(false); TransportConfiguration liveConnector = getConnectorTransportConfiguration(true); TransportConfiguration backupConnector = getConnectorTransportConfiguration(false); - backupConfig = super.createDefaultInVMConfig() - .clearAcceptorConfigurations() - .addAcceptorConfiguration(getAcceptorTransportConfiguration(false)) - .setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration() - .setFailbackDelay(1000)) - .addConnectorConfiguration(liveConnector.getName(), liveConnector) - .addConnectorConfiguration(backupConnector.getName(), backupConnector) - .addClusterConfiguration(basicClusterConnectionConfig(backupConnector.getName(), liveConnector.getName())); + backupConfig = super.createDefaultInVMConfig().clearAcceptorConfigurations().addAcceptorConfiguration(getAcceptorTransportConfiguration(false)).setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration().setFailbackDelay(1000)).addConnectorConfiguration(liveConnector.getName(), liveConnector).addConnectorConfiguration(backupConnector.getName(), backupConnector).addClusterConfiguration(basicClusterConnectionConfig(backupConnector.getName(), liveConnector.getName())); backupServer = createTestableServer(backupConfig); - liveConfig = super.createDefaultInVMConfig() - .clearAcceptorConfigurations() - .addAcceptorConfiguration(getAcceptorTransportConfiguration(true)) - .setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration() - .setFailbackDelay(1000)) - .addClusterConfiguration(basicClusterConnectionConfig(liveConnector.getName())) - .addConnectorConfiguration(liveConnector.getName(), liveConnector); + liveConfig = super.createDefaultInVMConfig().clearAcceptorConfigurations().addAcceptorConfiguration(getAcceptorTransportConfiguration(true)).setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration().setFailbackDelay(1000)).addClusterConfiguration(basicClusterConnectionConfig(liveConnector.getName())).addConnectorConfiguration(liveConnector.getName(), liveConnector); liveServer = createTestableServer(liveConfig); } - protected void createReplicatedConfigs() throws Exception - { + protected void createReplicatedConfigs() throws Exception { final TransportConfiguration liveConnector = getConnectorTransportConfiguration(true); final TransportConfiguration backupConnector = getConnectorTransportConfiguration(false); final TransportConfiguration backupAcceptor = getAcceptorTransportConfiguration(false); @@ -206,37 +178,26 @@ public abstract class FailoverTestBase extends ActiveMQTestBase ReplicatedBackupUtils.configureReplicationPair(backupConfig, backupConnector, backupAcceptor, liveConfig, liveConnector, null); - backupConfig.setBindingsDirectory(getBindingsDir(0, true)) - .setJournalDirectory(getJournalDir(0, true)) - .setPagingDirectory(getPageDir(0, true)) - .setLargeMessagesDirectory(getLargeMessagesDir(0, true)) - .setSecurityEnabled(false); + backupConfig.setBindingsDirectory(getBindingsDir(0, true)).setJournalDirectory(getJournalDir(0, true)).setPagingDirectory(getPageDir(0, true)).setLargeMessagesDirectory(getLargeMessagesDir(0, true)).setSecurityEnabled(false); setupHAPolicyConfiguration(); nodeManager = new InVMNodeManager(true, backupConfig.getJournalLocation()); backupServer = createTestableServer(backupConfig); - liveConfig.clearAcceptorConfigurations() - .addAcceptorConfiguration(getAcceptorTransportConfiguration(true)); + liveConfig.clearAcceptorConfigurations().addAcceptorConfiguration(getAcceptorTransportConfiguration(true)); liveServer = createTestableServer(liveConfig); } - protected void setupHAPolicyConfiguration() - { - ((ReplicaPolicyConfiguration) backupConfig.getHAPolicyConfiguration()) - .setMaxSavedReplicatedJournalsSize(0) - .setAllowFailBack(true) - .setFailbackDelay(5000); + protected void setupHAPolicyConfiguration() { + ((ReplicaPolicyConfiguration) backupConfig.getHAPolicyConfiguration()).setMaxSavedReplicatedJournalsSize(0).setAllowFailBack(true).setFailbackDelay(5000); } - protected final void adaptLiveConfigForReplicatedFailBack(TestableServer server) - { + protected final void adaptLiveConfigForReplicatedFailBack(TestableServer server) { Configuration configuration = server.getServer().getConfiguration(); final TransportConfiguration backupConnector = getConnectorTransportConfiguration(false); - if (server.getServer().getHAPolicy().isSharedStore()) - { + if (server.getServer().getHAPolicy().isSharedStore()) { ClusterConnectionConfiguration cc = configuration.getClusterConfigurations().get(0); Assert.assertNotNull("cluster connection configuration", cc); Assert.assertNotNull("static connectors", cc.getStaticConnectors()); @@ -251,8 +212,7 @@ public abstract class FailoverTestBase extends ActiveMQTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { logAndSystemOut("#test tearDown"); InVMConnector.failOnCreateConnection = false; @@ -266,29 +226,24 @@ public abstract class FailoverTestBase extends ActiveMQTestBase nodeManager = null; - try - { + try { ServerSocket serverSocket = new ServerSocket(61616); serverSocket.close(); } - catch (IOException e) - { + catch (IOException e) { throw e; } - try - { + try { ServerSocket serverSocket = new ServerSocket(61617); serverSocket.close(); } - catch (IOException e) - { + catch (IOException e) { throw e; } } - protected ClientSessionFactoryInternal - createSessionFactoryAndWaitForTopology(ServerLocator locator, int topologyMembers) throws Exception - { + protected ClientSessionFactoryInternal createSessionFactoryAndWaitForTopology(ServerLocator locator, + int topologyMembers) throws Exception { CountDownLatch countDownLatch = new CountDownLatch(topologyMembers); locator.addClusterTopologyListener(new LatchClusterTopologyListener(countDownLatch)); @@ -307,15 +262,12 @@ public abstract class FailoverTestBase extends ActiveMQTestBase * @param seconds * @throws Exception */ - protected void waitForBackup(ClientSessionFactoryInternal sessionFactory, int seconds) throws Exception - { + protected void waitForBackup(ClientSessionFactoryInternal sessionFactory, int seconds) throws Exception { final ActiveMQServerImpl actualServer = (ActiveMQServerImpl) backupServer.getServer(); - if (actualServer.getHAPolicy().isSharedStore()) - { + if (actualServer.getHAPolicy().isSharedStore()) { waitForServerToStart(actualServer); } - else - { + else { waitForRemoteBackup(sessionFactory, seconds, true, actualServer); } } @@ -324,20 +276,15 @@ public abstract class FailoverTestBase extends ActiveMQTestBase protected abstract TransportConfiguration getConnectorTransportConfiguration(final boolean live); - protected ServerLocatorInternal getServerLocator() throws Exception - { - return (ServerLocatorInternal) addServerLocator(ActiveMQClient.createServerLocatorWithHA(getConnectorTransportConfiguration(true), getConnectorTransportConfiguration(false))) - .setRetryInterval(50); + protected ServerLocatorInternal getServerLocator() throws Exception { + return (ServerLocatorInternal) addServerLocator(ActiveMQClient.createServerLocatorWithHA(getConnectorTransportConfiguration(true), getConnectorTransportConfiguration(false))).setRetryInterval(50); } - - protected void crash(final ClientSession... sessions) throws Exception - { + protected void crash(final ClientSession... sessions) throws Exception { liveServer.crash(sessions); } - protected void crash(final boolean waitFailure, final ClientSession... sessions) throws Exception - { + protected void crash(final boolean waitFailure, final ClientSession... sessions) throws Exception { liveServer.crash(waitFailure, sessions); } @@ -345,35 +292,30 @@ public abstract class FailoverTestBase extends ActiveMQTestBase // Inner classes ------------------------------------------------- - public static final class LatchClusterTopologyListener implements ClusterTopologyListener - { + public static final class LatchClusterTopologyListener implements ClusterTopologyListener { + final CountDownLatch latch; List liveNode = new ArrayList(); List backupNode = new ArrayList(); - public LatchClusterTopologyListener(CountDownLatch latch) - { + public LatchClusterTopologyListener(CountDownLatch latch) { this.latch = latch; } @Override - public void nodeUP(TopologyMember topologyMember, boolean last) - { - if (topologyMember.getLive() != null && !liveNode.contains(topologyMember.getLive().getName())) - { + public void nodeUP(TopologyMember topologyMember, boolean last) { + if (topologyMember.getLive() != null && !liveNode.contains(topologyMember.getLive().getName())) { liveNode.add(topologyMember.getLive().getName()); latch.countDown(); } - if (topologyMember.getBackup() != null && !backupNode.contains(topologyMember.getBackup().getName())) - { + if (topologyMember.getBackup() != null && !backupNode.contains(topologyMember.getBackup().getName())) { backupNode.add(topologyMember.getBackup().getName()); latch.countDown(); } } @Override - public void nodeDown(final long uniqueEventID, String nodeID) - { + public void nodeDown(final long uniqueEventID, String nodeID) { //To change body of implemented methods use File | Settings | File Templates. } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/GroupingFailoverReplicationTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/GroupingFailoverReplicationTest.java index 72667bdeb9..1b1388970d 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/GroupingFailoverReplicationTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/GroupingFailoverReplicationTest.java @@ -16,11 +16,10 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.failover; -public class GroupingFailoverReplicationTest extends GroupingFailoverTestBase -{ +public class GroupingFailoverReplicationTest extends GroupingFailoverTestBase { + @Override - protected boolean isSharedStore() - { + protected boolean isSharedStore() { return false; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/GroupingFailoverSharedServerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/GroupingFailoverSharedServerTest.java index c7aebfa27c..a2849447b6 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/GroupingFailoverSharedServerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/GroupingFailoverSharedServerTest.java @@ -16,12 +16,10 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.failover; -public class GroupingFailoverSharedServerTest extends GroupingFailoverTestBase -{ +public class GroupingFailoverSharedServerTest extends GroupingFailoverTestBase { @Override - protected boolean isSharedStore() - { + protected boolean isSharedStore() { return true; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/GroupingFailoverTestBase.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/GroupingFailoverTestBase.java index 7ca26e7cbe..0826077d72 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/GroupingFailoverTestBase.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/GroupingFailoverTestBase.java @@ -33,12 +33,10 @@ import org.apache.activemq.artemis.tests.integration.cluster.distribution.Cluste import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Test; -public abstract class GroupingFailoverTestBase extends ClusterTestBase -{ +public abstract class GroupingFailoverTestBase extends ClusterTestBase { @Test - public void testGroupingLocalHandlerFails() throws Exception - { + public void testGroupingLocalHandlerFails() throws Exception { setupBackupServer(2, 0, isFileStorage(), isSharedStore(), isNetty()); setupLiveServer(0, isFileStorage(), isSharedStore(), isNetty(), false); @@ -56,11 +54,10 @@ public abstract class GroupingFailoverTestBase extends ClusterTestBase setUpGroupHandler(GroupingHandlerConfiguration.TYPE.REMOTE, 1); setUpGroupHandler(GroupingHandlerConfiguration.TYPE.LOCAL, 2); - if (!isSharedStore()) - { - ((ReplicatedPolicyConfiguration)servers[0].getConfiguration().getHAPolicyConfiguration()).setGroupName("group1"); - ((ReplicatedPolicyConfiguration)servers[1].getConfiguration().getHAPolicyConfiguration()).setGroupName("group2"); - ((ReplicaPolicyConfiguration)servers[2].getConfiguration().getHAPolicyConfiguration()).setGroupName("group1"); + if (!isSharedStore()) { + ((ReplicatedPolicyConfiguration) servers[0].getConfiguration().getHAPolicyConfiguration()).setGroupName("group1"); + ((ReplicatedPolicyConfiguration) servers[1].getConfiguration().getHAPolicyConfiguration()).setGroupName("group2"); + ((ReplicaPolicyConfiguration) servers[2].getConfiguration().getHAPolicyConfiguration()).setGroupName("group1"); } startServers(0, 1, 2); @@ -88,8 +85,7 @@ public abstract class GroupingFailoverTestBase extends ClusterTestBase verifyReceiveAll(10, 0); - if (!isSharedStore()) - { + if (!isSharedStore()) { waitForBackupTopologyAnnouncement(sfs[0]); } @@ -112,32 +108,26 @@ public abstract class GroupingFailoverTestBase extends ClusterTestBase verifyReceiveAll(10, 2); } - public void waitForBackupTopologyAnnouncement(ClientSessionFactory sf) throws Exception - { + public void waitForBackupTopologyAnnouncement(ClientSessionFactory sf) throws Exception { long start = System.currentTimeMillis(); ServerLocator locator = sf.getServerLocator(); - do - { + do { Collection members = locator.getTopology().getMembers(); - for (TopologyMemberImpl member : members) - { - if (member.getBackup() != null) - { + for (TopologyMemberImpl member : members) { + if (member.getBackup() != null) { return; } } Thread.sleep(10); - } - while (System.currentTimeMillis() - start < ActiveMQTestBase.WAIT_TIMEOUT); + } while (System.currentTimeMillis() - start < ActiveMQTestBase.WAIT_TIMEOUT); throw new IllegalStateException("Timed out waiting for backup announce"); } @Test - public void testGroupingLocalHandlerFailsMultipleGroups() throws Exception - { + public void testGroupingLocalHandlerFailsMultipleGroups() throws Exception { setupBackupServer(2, 0, isFileStorage(), isSharedStore(), isNetty()); setupLiveServer(0, isFileStorage(), isSharedStore(), isNetty(), false); @@ -156,11 +146,10 @@ public abstract class GroupingFailoverTestBase extends ClusterTestBase setUpGroupHandler(GroupingHandlerConfiguration.TYPE.LOCAL, 2); - if (!isSharedStore()) - { - ((ReplicatedPolicyConfiguration)servers[0].getConfiguration().getHAPolicyConfiguration()).setGroupName("group1"); - ((ReplicatedPolicyConfiguration)servers[1].getConfiguration().getHAPolicyConfiguration()).setGroupName("group2"); - ((ReplicaPolicyConfiguration)servers[2].getConfiguration().getHAPolicyConfiguration()).setGroupName("group1"); + if (!isSharedStore()) { + ((ReplicatedPolicyConfiguration) servers[0].getConfiguration().getHAPolicyConfiguration()).setGroupName("group1"); + ((ReplicatedPolicyConfiguration) servers[1].getConfiguration().getHAPolicyConfiguration()).setGroupName("group2"); + ((ReplicaPolicyConfiguration) servers[2].getConfiguration().getHAPolicyConfiguration()).setGroupName("group1"); } startServers(0, 1, 2); @@ -197,9 +186,8 @@ public abstract class GroupingFailoverTestBase extends ClusterTestBase verifyReceiveAllWithGroupIDRoundRobin(0, 30, 0, 1); - if (!isSharedStore()) - { - SharedNothingBackupActivation backupActivation = (SharedNothingBackupActivation) servers[2].getActivation(); + if (!isSharedStore()) { + SharedNothingBackupActivation backupActivation = (SharedNothingBackupActivation) servers[2].getActivation(); assertTrue(backupActivation.waitForBackupSync(10, TimeUnit.SECONDS)); } @@ -231,8 +219,7 @@ public abstract class GroupingFailoverTestBase extends ClusterTestBase verifyReceiveAllWithGroupIDRoundRobin(2, 30, 1, 2); } - public boolean isNetty() - { + public boolean isNetty() { return true; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/LargeMessageFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/LargeMessageFailoverTest.java index 9ab44b7e14..f192506463 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/LargeMessageFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/LargeMessageFailoverTest.java @@ -20,21 +20,18 @@ import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.apache.activemq.artemis.core.client.impl.ServerLocatorInternal; import org.junit.Test; -public class LargeMessageFailoverTest extends FailoverTest -{ +public class LargeMessageFailoverTest extends FailoverTest { @Override @Test - public void testLiveAndBackupLiveComesBackNewFactory() throws Exception - { + public void testLiveAndBackupLiveComesBackNewFactory() throws Exception { // skip test because it triggers OutOfMemoryError. Thread.sleep(1000); } @Override @Test - public void testLiveAndBackupBackupComesBackNewFactory() throws Exception - { + public void testLiveAndBackupBackupComesBackNewFactory() throws Exception { // skip test because it triggers OutOfMemoryError. Thread.sleep(1000); } @@ -44,17 +41,13 @@ public class LargeMessageFailoverTest extends FailoverTest * @param message */ @Override - protected void assertMessageBody(final int i, final ClientMessage message) - { + protected void assertMessageBody(final int i, final ClientMessage message) { assertLargeMessageBody(i, message); } - @Override - protected ServerLocatorInternal getServerLocator() throws Exception - { - return (ServerLocatorInternal) super.getServerLocator() - .setMinLargeMessageSize(MIN_LARGE_MESSAGE); + protected ServerLocatorInternal getServerLocator() throws Exception { + return (ServerLocatorInternal) super.getServerLocator().setMinLargeMessageSize(MIN_LARGE_MESSAGE); } /** @@ -62,8 +55,7 @@ public class LargeMessageFailoverTest extends FailoverTest * @param message */ @Override - protected void setBody(final int i, final ClientMessage message) - { + protected void setBody(final int i, final ClientMessage message) { setLargeMessageBody(i, message); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/LiveToLiveFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/LiveToLiveFailoverTest.java index 1ee6591ab3..d74cee933b 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/LiveToLiveFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/LiveToLiveFailoverTest.java @@ -36,94 +36,60 @@ import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -public class LiveToLiveFailoverTest extends FailoverTest -{ +public class LiveToLiveFailoverTest extends FailoverTest { + private InVMNodeManager nodeManager0; private InVMNodeManager nodeManager1; private ClientSessionFactoryInternal sf2; @Override - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); } @Override - protected void createConfigs() throws Exception - { + protected void createConfigs() throws Exception { nodeManager0 = new InVMNodeManager(false); nodeManager1 = new InVMNodeManager(false); TransportConfiguration liveConnector0 = getConnectorTransportConfiguration(true, 0); TransportConfiguration liveConnector1 = getConnectorTransportConfiguration(true, 1); - backupConfig = super.createDefaultInVMConfig(1) - .clearAcceptorConfigurations() - .addAcceptorConfiguration(getAcceptorTransportConfiguration(true, 1)) - .setHAPolicyConfiguration(new ColocatedPolicyConfiguration() - .setRequestBackup(true) - .setLiveConfig(new SharedStoreMasterPolicyConfiguration()) - .setBackupConfig(new SharedStoreSlavePolicyConfiguration() - .setFailbackDelay(1000) - .setScaleDownConfiguration(new ScaleDownConfiguration() - .addConnector(liveConnector1.getName())))) - .addConnectorConfiguration(liveConnector0.getName(), liveConnector0) - .addConnectorConfiguration(liveConnector1.getName(), liveConnector1) - .addClusterConfiguration(basicClusterConnectionConfig(liveConnector1.getName(), liveConnector0.getName())); + backupConfig = super.createDefaultInVMConfig(1).clearAcceptorConfigurations().addAcceptorConfiguration(getAcceptorTransportConfiguration(true, 1)).setHAPolicyConfiguration(new ColocatedPolicyConfiguration().setRequestBackup(true).setLiveConfig(new SharedStoreMasterPolicyConfiguration()).setBackupConfig(new SharedStoreSlavePolicyConfiguration().setFailbackDelay(1000).setScaleDownConfiguration(new ScaleDownConfiguration().addConnector(liveConnector1.getName())))).addConnectorConfiguration(liveConnector0.getName(), liveConnector0).addConnectorConfiguration(liveConnector1.getName(), liveConnector1).addClusterConfiguration(basicClusterConnectionConfig(liveConnector1.getName(), liveConnector0.getName())); backupServer = createColocatedTestableServer(backupConfig, nodeManager1, nodeManager0, 1); - liveConfig = super.createDefaultInVMConfig(0) - .clearAcceptorConfigurations() - .addAcceptorConfiguration(getAcceptorTransportConfiguration(true, 0)) - .setHAPolicyConfiguration(new ColocatedPolicyConfiguration() - .setRequestBackup(true) - .setBackupRequestRetryInterval(1000) - .setLiveConfig(new SharedStoreMasterPolicyConfiguration()) - .setBackupConfig(new SharedStoreSlavePolicyConfiguration() - .setFailbackDelay(1000) - .setScaleDownConfiguration(new ScaleDownConfiguration()))) - .addConnectorConfiguration(liveConnector0.getName(), liveConnector0) - .addConnectorConfiguration(liveConnector1.getName(), liveConnector1) - .addClusterConfiguration(basicClusterConnectionConfig(liveConnector0.getName(), liveConnector1.getName())); + liveConfig = super.createDefaultInVMConfig(0).clearAcceptorConfigurations().addAcceptorConfiguration(getAcceptorTransportConfiguration(true, 0)).setHAPolicyConfiguration(new ColocatedPolicyConfiguration().setRequestBackup(true).setBackupRequestRetryInterval(1000).setLiveConfig(new SharedStoreMasterPolicyConfiguration()).setBackupConfig(new SharedStoreSlavePolicyConfiguration().setFailbackDelay(1000).setScaleDownConfiguration(new ScaleDownConfiguration()))).addConnectorConfiguration(liveConnector0.getName(), liveConnector0).addConnectorConfiguration(liveConnector1.getName(), liveConnector1).addClusterConfiguration(basicClusterConnectionConfig(liveConnector0.getName(), liveConnector1.getName())); liveServer = createColocatedTestableServer(liveConfig, nodeManager0, nodeManager1, 0); } @Override - protected void setLiveIdentity() - { + protected void setLiveIdentity() { liveServer.setIdentity(this.getClass().getSimpleName() + "/liveServer0"); } @Override - protected void setBackupIdentity() - { + protected void setBackupIdentity() { backupServer.setIdentity(this.getClass().getSimpleName() + "/liveServer1"); } @Override - protected void waitForBackup() - { + protected void waitForBackup() { Map backupServers0 = liveServer.getServer().getClusterManager().getHAManager().getBackupServers(); Map backupServers1 = backupServer.getServer().getClusterManager().getHAManager().getBackupServers(); final long toWait = 10000; final long time = System.currentTimeMillis(); - while (true) - { - if (backupServers0.size() == 1 && backupServers1.size() == 1) - { + while (true) { + if (backupServers0.size() == 1 && backupServers1.size() == 1) { break; } - if (System.currentTimeMillis() > (time + toWait)) - { - fail("backup started? ( live server0 backups = " + backupServers0.size() + " live server1 backups = " + backupServers1.size() + ")" ); + if (System.currentTimeMillis() > (time + toWait)) { + fail("backup started? ( live server0 backups = " + backupServers0.size() + " live server1 backups = " + backupServers1.size() + ")"); } - try - { + try { Thread.sleep(100); } - catch (InterruptedException e) - { + catch (InterruptedException e) { fail(e.getMessage()); } } @@ -131,9 +97,8 @@ public class LiveToLiveFailoverTest extends FailoverTest waitForRemoteBackupSynchronization(backupServers1.values().iterator().next()); } - protected final ClientSessionFactoryInternal - createSessionFactoryAndWaitForTopology(ServerLocator locator, int topologyMembers) throws Exception - { + protected final ClientSessionFactoryInternal createSessionFactoryAndWaitForTopology(ServerLocator locator, + int topologyMembers) throws Exception { CountDownLatch countDownLatch = new CountDownLatch(topologyMembers * 2); locator.addClusterTopologyListener(new LatchClusterTopologyListener(countDownLatch)); @@ -148,8 +113,7 @@ public class LiveToLiveFailoverTest extends FailoverTest sf = (ClientSessionFactoryInternal) locator.createSessionFactory(liveServer.getServer().getNodeID().toString()); addSessionFactory(sf); - if (sf2 == null) - { + if (sf2 == null) { sf2 = (ClientSessionFactoryInternal) locator.createSessionFactory(backupServer.getServer().getNodeID().toString()); ClientSession session2 = createSession(sf2, false, false); @@ -160,9 +124,9 @@ public class LiveToLiveFailoverTest extends FailoverTest return sf; } - protected final ClientSessionFactoryInternal - createSessionFactoryAndWaitForTopology(ServerLocator locator, TransportConfiguration transportConfiguration, int topologyMembers) throws Exception - { + protected final ClientSessionFactoryInternal createSessionFactoryAndWaitForTopology(ServerLocator locator, + TransportConfiguration transportConfiguration, + int topologyMembers) throws Exception { CountDownLatch countDownLatch = new CountDownLatch(topologyMembers * 2); locator.addClusterTopologyListener(new LatchClusterTopologyListener(countDownLatch)); @@ -177,8 +141,7 @@ public class LiveToLiveFailoverTest extends FailoverTest sf = (ClientSessionFactoryInternal) locator.createSessionFactory(liveServer.getServer().getNodeID().toString()); addSessionFactory(sf); - if (sf2 == null) - { + if (sf2 == null) { sf2 = (ClientSessionFactoryInternal) locator.createSessionFactory(backupServer.getServer().getNodeID().toString()); ClientSession session2 = createSession(sf2, false, false); @@ -188,29 +151,22 @@ public class LiveToLiveFailoverTest extends FailoverTest return sf; } - protected void createClientSessionFactory() throws Exception - { - if (liveServer.getServer().isStarted()) - { + protected void createClientSessionFactory() throws Exception { + if (liveServer.getServer().isStarted()) { sf = (ClientSessionFactoryInternal) createSessionFactory(locator); sf = (ClientSessionFactoryInternal) locator.createSessionFactory(liveServer.getServer().getNodeID().toString()); } - else - { + else { sf = (ClientSessionFactoryInternal) createSessionFactory(locator); } } - protected void createSessionFactory() throws Exception - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setReconnectAttempts(-1); + protected void createSessionFactory() throws Exception { + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setReconnectAttempts(-1); - sf = createSessionFactoryAndWaitForTopology(locator, getConnectorTransportConfiguration(true, 0), 2); + sf = createSessionFactoryAndWaitForTopology(locator, getConnectorTransportConfiguration(true, 0), 2); - if (sf2 == null) - { + if (sf2 == null) { sf2 = (ClientSessionFactoryInternal) locator.createSessionFactory(backupServer.getServer().getNodeID().toString()); addSessionFactory(sf2); ClientSession session2 = createSession(sf2, false, false); @@ -218,19 +174,16 @@ public class LiveToLiveFailoverTest extends FailoverTest } } - private TransportConfiguration getConnectorTransportConfiguration(boolean live, int server) - { + private TransportConfiguration getConnectorTransportConfiguration(boolean live, int server) { return TransportConfigurationUtils.getInVMConnector(live, server); } - private TransportConfiguration getAcceptorTransportConfiguration(boolean live, int server) - { + private TransportConfiguration getAcceptorTransportConfiguration(boolean live, int server) { return TransportConfigurationUtils.getInVMAcceptor(live, server); } @Test - public void scaleDownDelay() throws Exception - { + public void scaleDownDelay() throws Exception { createSessionFactory(); ClientSession session = createSession(sf, true, true); @@ -261,12 +214,8 @@ public class LiveToLiveFailoverTest extends FailoverTest // https://jira.jboss.org/jira/browse/HORNETQ-285 @Test - public void testFailoverOnInitialConnection() throws Exception - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setFailoverOnInitialConnection(true) - .setReconnectAttempts(-1); + public void testFailoverOnInitialConnection() throws Exception { + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setFailoverOnInitialConnection(true).setReconnectAttempts(-1); sf = createSessionFactoryAndWaitForTopology(locator, 2); @@ -279,7 +228,6 @@ public class LiveToLiveFailoverTest extends FailoverTest ClientProducer producer = session.createProducer(ADDRESS); - sendMessages(session, producer, NUM_MESSAGES); ClientConsumer consumer = session.createConsumer(ADDRESS); @@ -292,12 +240,9 @@ public class LiveToLiveFailoverTest extends FailoverTest } @Test - public void testCreateNewFactoryAfterFailover() throws Exception - { + public void testCreateNewFactoryAfterFailover() throws Exception { this.disableCheckThread(); - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setFailoverOnInitialConnection(true); + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setFailoverOnInitialConnection(true); sf = createSessionFactoryAndWaitForTopology(locator, 2); ClientSession session = sendAndConsume(sf, true); @@ -306,18 +251,14 @@ public class LiveToLiveFailoverTest extends FailoverTest session.close(); - long timeout; timeout = System.currentTimeMillis() + 5000; - while (timeout > System.currentTimeMillis()) - { - try - { + while (timeout > System.currentTimeMillis()) { + try { createClientSessionFactory(); break; } - catch (Exception e) - { + catch (Exception e) { // retrying Thread.sleep(100); } @@ -329,81 +270,68 @@ public class LiveToLiveFailoverTest extends FailoverTest //invalid tests for Live to Live failover //all the timeout ones aren't as we don't migrate timeouts, any failback or server restart //or replicating tests aren't either - public void testLiveAndBackupBackupComesBackNewFactory() throws Exception - { + public void testLiveAndBackupBackupComesBackNewFactory() throws Exception { } - public void testLiveAndBackupLiveComesBackNewFactory() - { - } - @Override - public void testTimeoutOnFailoverConsumeBlocked() throws Exception - { + + public void testLiveAndBackupLiveComesBackNewFactory() { } @Override - public void testFailoverMultipleSessionsWithConsumers() throws Exception - { + public void testTimeoutOnFailoverConsumeBlocked() throws Exception { + } + + @Override + public void testFailoverMultipleSessionsWithConsumers() throws Exception { // } @Override - public void testTimeoutOnFailover() throws Exception - { + public void testTimeoutOnFailover() throws Exception { } @Override - public void testTimeoutOnFailoverTransactionRollback() throws Exception - { + public void testTimeoutOnFailoverTransactionRollback() throws Exception { } @Override - public void testTimeoutOnFailoverConsume() throws Exception - { + public void testTimeoutOnFailoverConsume() throws Exception { } @Override - public void testTimeoutOnFailoverTransactionCommit() throws Exception - { + public void testTimeoutOnFailoverTransactionCommit() throws Exception { } @Override - public void testFailBack() throws Exception - { + public void testFailBack() throws Exception { } @Override - public void testFailBackLiveRestartsBackupIsGone() throws Exception - { - } - @Override - public void testLiveAndBackupLiveComesBack() throws Exception - { + public void testFailBackLiveRestartsBackupIsGone() throws Exception { } @Override - public void testSimpleReplication() throws Exception - { + public void testLiveAndBackupLiveComesBack() throws Exception { } @Override - public void testFailThenReceiveMoreMessagesAfterFailover2() throws Exception - { + public void testSimpleReplication() throws Exception { } @Override - public void testWithoutUsingTheBackup() throws Exception - { + public void testFailThenReceiveMoreMessagesAfterFailover2() throws Exception { + } + + @Override + public void testWithoutUsingTheBackup() throws Exception { } //todo check to see which failing tests are valid, @Override - public void testSimpleSendAfterFailoverDurableNonTemporary() throws Exception - { + public void testSimpleSendAfterFailoverDurableNonTemporary() throws Exception { } @Override - public void testCommitOccurredUnblockedAndResendNoDuplicates() throws Exception - { + public void testCommitOccurredUnblockedAndResendNoDuplicates() throws Exception { } /*@Override diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/MultipleBackupsFailoverTestBase.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/MultipleBackupsFailoverTestBase.java index c3c055372e..5b32c84496 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/MultipleBackupsFailoverTestBase.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/MultipleBackupsFailoverTestBase.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.cluster.failover; + import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -36,8 +37,8 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.jms.client.ActiveMQTextMessage; import org.junit.Assert; -public abstract class MultipleBackupsFailoverTestBase extends ActiveMQTestBase -{ +public abstract class MultipleBackupsFailoverTestBase extends ActiveMQTestBase { + IntegrationTestLogger log = IntegrationTestLogger.LOGGER; protected abstract boolean isNetty(); @@ -45,57 +46,44 @@ public abstract class MultipleBackupsFailoverTestBase extends ActiveMQTestBase protected int waitForNewLive(long seconds, boolean waitForNewBackup, Map servers, - int... nodes) - { + int... nodes) { long time = System.currentTimeMillis(); long toWait = seconds * 1000; int newLive = -1; - while (true) - { - for (int node : nodes) - { + while (true) { + for (int node : nodes) { TestableServer backupServer = servers.get(node); - if (newLive == -1 && backupServer.isActive()) - { + if (newLive == -1 && backupServer.isActive()) { newLive = node; } - else if (newLive != -1) - { - if (waitForNewBackup) - { - if (node != newLive && servers.get(node).isStarted()) - { + else if (newLive != -1) { + if (waitForNewBackup) { + if (node != newLive && servers.get(node).isStarted()) { return newLive; } } - else - { + else { return newLive; } } } - try - { + try { Thread.sleep(100); } - catch (InterruptedException e) - { + catch (InterruptedException e) { // ignore } - if (System.currentTimeMillis() > (time + toWait)) - { + if (System.currentTimeMillis() > (time + toWait)) { Assert.fail("backup server never started"); } } } - protected ClientSession sendAndConsume(final ClientSessionFactory sf, final boolean createQueue) throws Exception - { + protected ClientSession sendAndConsume(final ClientSessionFactory sf, final boolean createQueue) throws Exception { ClientSession session = sf.createSession(false, true, true); - if (createQueue) - { + if (createQueue) { session.createQueue(FailoverTestBase.ADDRESS, FailoverTestBase.ADDRESS, null, false); } @@ -103,13 +91,8 @@ public abstract class MultipleBackupsFailoverTestBase extends ActiveMQTestBase final int numMessages = 1000; - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte)1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); message.getBodyBuffer().writeString("aardvarks"); producer.send(message); @@ -119,8 +102,7 @@ public abstract class MultipleBackupsFailoverTestBase extends ActiveMQTestBase session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message2 = consumer.receive(10000); Assert.assertNotNull(message2); @@ -140,30 +122,26 @@ public abstract class MultipleBackupsFailoverTestBase extends ActiveMQTestBase } protected ClientSessionFactoryInternal createSessionFactoryAndWaitForTopology(ServerLocator locator, - int topologyMembers) throws Exception - { + int topologyMembers) throws Exception { return createSessionFactoryAndWaitForTopology(locator, topologyMembers, null); } protected ClientSessionFactoryInternal createSessionFactoryAndWaitForTopology(ServerLocator locator, int topologyMembers, - ActiveMQServer server) throws Exception - { + ActiveMQServer server) throws Exception { ClientSessionFactoryInternal sf; CountDownLatch countDownLatch = new CountDownLatch(topologyMembers); FailoverTestBase.LatchClusterTopologyListener topListener = new FailoverTestBase.LatchClusterTopologyListener(countDownLatch); locator.addClusterTopologyListener(topListener); - sf = (ClientSessionFactoryInternal)locator.createSessionFactory(); + sf = (ClientSessionFactoryInternal) locator.createSessionFactory(); addSessionFactory(sf); boolean ok = countDownLatch.await(5, TimeUnit.SECONDS); locator.removeClusterTopologyListener(topListener); - if (!ok) - { - if (server != null) - { + if (!ok) { + if (server != null) { log.info("failed topology, Topology on server = " + server.getClusterManager().describe()); } } @@ -171,11 +149,9 @@ public abstract class MultipleBackupsFailoverTestBase extends ActiveMQTestBase return sf; } - public ServerLocator getServerLocator(int... nodes) - { + public ServerLocator getServerLocator(int... nodes) { TransportConfiguration[] configs = new TransportConfiguration[nodes.length]; - for (int i = 0, configsLength = configs.length; i < configsLength; i++) - { + for (int i = 0, configsLength = configs.length; i < configsLength; i++) { configs[i] = createTransportConfiguration(isNetty(), false, generateParams(nodes[i], isNetty())); } return addServerLocator(new ServerLocatorImpl(true, configs)); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/MultipleLivesMultipleBackupsFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/MultipleLivesMultipleBackupsFailoverTest.java index 828cb2a762..a6ab97bace 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/MultipleLivesMultipleBackupsFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/MultipleLivesMultipleBackupsFailoverTest.java @@ -37,16 +37,15 @@ import java.util.Map; /** */ -public class MultipleLivesMultipleBackupsFailoverTest extends MultipleBackupsFailoverTestBase -{ +public class MultipleLivesMultipleBackupsFailoverTest extends MultipleBackupsFailoverTestBase { + protected Map servers = new HashMap(); private ServerLocator locator2; private ServerLocator locator; private final boolean sharedStore = true; @Test - public void testMultipleFailovers2LiveServers() throws Exception - { + public void testMultipleFailovers2LiveServers() throws Exception { NodeManager nodeManager1 = new InVMNodeManager(!sharedStore); NodeManager nodeManager2 = new InVMNodeManager(!sharedStore); createLiveConfig(nodeManager1, 0, 3, 4, 5); @@ -74,11 +73,7 @@ public class MultipleLivesMultipleBackupsFailoverTest extends MultipleBackupsFai waitForServerToStart(servers.get(4).getServer()); - locator = getServerLocator(0) - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true) - .setReconnectAttempts(-1); + locator = getServerLocator(0).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true).setReconnectAttempts(-1); ClientSessionFactoryInternal sf = createSessionFactoryAndWaitForTopology(locator, 4, servers.get(0).getServer()); ClientSession session = sendAndConsume(sf, true); @@ -89,11 +84,7 @@ public class MultipleLivesMultipleBackupsFailoverTest extends MultipleBackupsFai int liveAfter0 = waitForNewLive(10000, true, servers, 1, 2); - locator2 = getServerLocator(3) - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true) - .setReconnectAttempts(-1); + locator2 = getServerLocator(3).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true).setReconnectAttempts(-1); ClientSessionFactoryInternal sf2 = createSessionFactoryAndWaitForTopology(locator2, 4); ClientSession session2 = sendAndConsume(sf2, true); @@ -103,30 +94,26 @@ public class MultipleLivesMultipleBackupsFailoverTest extends MultipleBackupsFai int liveAfter3 = waitForNewLive(10000, true, servers, 4, 5); locator.close(); locator2.close(); - if (liveAfter0 == 2) - { + if (liveAfter0 == 2) { Thread.sleep(500); servers.get(1).stop(); Thread.sleep(500); servers.get(2).stop(); } - else - { + else { Thread.sleep(500); servers.get(2).stop(); Thread.sleep(500); servers.get(1).stop(); } - if (liveAfter3 == 4) - { + if (liveAfter3 == 4) { Thread.sleep(500); servers.get(5).stop(); Thread.sleep(500); servers.get(4).stop(); } - else - { + else { Thread.sleep(500); servers.get(4).stop(); Thread.sleep(500); @@ -139,19 +126,10 @@ public class MultipleLivesMultipleBackupsFailoverTest extends MultipleBackupsFai int nodeid, boolean createClusterConnections, int[] otherBackupNodes, - int... otherClusterNodes) throws Exception - { - Configuration config1 = super.createDefaultInVMConfig() - .clearAcceptorConfigurations() - .addAcceptorConfiguration(createTransportConfiguration(isNetty(), true, generateParams(nodeid, isNetty()))) - .setHAPolicyConfiguration(sharedStore ? new SharedStoreSlavePolicyConfiguration() : new ReplicaPolicyConfiguration()) - .setBindingsDirectory(getBindingsDir() + "_" + liveNode) - .setJournalDirectory(getJournalDir() + "_" + liveNode) - .setPagingDirectory(getPageDir() + "_" + liveNode) - .setLargeMessagesDirectory(getLargeMessagesDir() + "_" + liveNode); + int... otherClusterNodes) throws Exception { + Configuration config1 = super.createDefaultInVMConfig().clearAcceptorConfigurations().addAcceptorConfiguration(createTransportConfiguration(isNetty(), true, generateParams(nodeid, isNetty()))).setHAPolicyConfiguration(sharedStore ? new SharedStoreSlavePolicyConfiguration() : new ReplicaPolicyConfiguration()).setBindingsDirectory(getBindingsDir() + "_" + liveNode).setJournalDirectory(getJournalDir() + "_" + liveNode).setPagingDirectory(getPageDir() + "_" + liveNode).setLargeMessagesDirectory(getLargeMessagesDir() + "_" + liveNode); - for (int node : otherBackupNodes) - { + for (int node : otherBackupNodes) { TransportConfiguration liveConnector = createTransportConfiguration(isNetty(), false, generateParams(node, isNetty())); config1.addConnectorConfiguration(liveConnector.getName(), liveConnector); } @@ -160,8 +138,7 @@ public class MultipleLivesMultipleBackupsFailoverTest extends MultipleBackupsFai config1.addConnectorConfiguration(backupConnector.getName(), backupConnector); String[] clusterNodes = new String[otherClusterNodes.length]; - for (int i = 0; i < otherClusterNodes.length; i++) - { + for (int i = 0; i < otherClusterNodes.length; i++) { TransportConfiguration connector = createTransportConfiguration(isNetty(), false, generateParams(otherClusterNodes[i], isNetty())); config1.addConnectorConfiguration(connector.getName(), connector); clusterNodes[i] = connector.getName(); @@ -171,23 +148,13 @@ public class MultipleLivesMultipleBackupsFailoverTest extends MultipleBackupsFai servers.put(nodeid, new SameProcessActiveMQServer(createInVMFailoverServer(true, config1, nodeManager, liveNode))); } - protected void createLiveConfig(NodeManager nodeManager, int liveNode, int... otherLiveNodes) throws Exception - { - TransportConfiguration liveConnector = createTransportConfiguration(isNetty(), false,generateParams(liveNode, isNetty())); + protected void createLiveConfig(NodeManager nodeManager, int liveNode, int... otherLiveNodes) throws Exception { + TransportConfiguration liveConnector = createTransportConfiguration(isNetty(), false, generateParams(liveNode, isNetty())); - Configuration config0 = super.createDefaultInVMConfig() - .clearAcceptorConfigurations() - .addAcceptorConfiguration(createTransportConfiguration(isNetty(), true, generateParams(liveNode, isNetty()))) - .setHAPolicyConfiguration(sharedStore ? new SharedStoreMasterPolicyConfiguration() : new ReplicatedPolicyConfiguration()) - .setBindingsDirectory(getBindingsDir() + "_" + liveNode) - .setJournalDirectory(getJournalDir() + "_" + liveNode) - .setPagingDirectory(getPageDir() + "_" + liveNode) - .setLargeMessagesDirectory(getLargeMessagesDir() + "_" + liveNode) - .addConnectorConfiguration(liveConnector.getName(), liveConnector); + Configuration config0 = super.createDefaultInVMConfig().clearAcceptorConfigurations().addAcceptorConfiguration(createTransportConfiguration(isNetty(), true, generateParams(liveNode, isNetty()))).setHAPolicyConfiguration(sharedStore ? new SharedStoreMasterPolicyConfiguration() : new ReplicatedPolicyConfiguration()).setBindingsDirectory(getBindingsDir() + "_" + liveNode).setJournalDirectory(getJournalDir() + "_" + liveNode).setPagingDirectory(getPageDir() + "_" + liveNode).setLargeMessagesDirectory(getLargeMessagesDir() + "_" + liveNode).addConnectorConfiguration(liveConnector.getName(), liveConnector); String[] pairs = new String[otherLiveNodes.length]; - for (int i = 0; i < otherLiveNodes.length; i++) - { + for (int i = 0; i < otherLiveNodes.length; i++) { TransportConfiguration otherLiveConnector = createTransportConfiguration(isNetty(), false, generateParams(otherLiveNodes[i], isNetty())); config0.addConnectorConfiguration(otherLiveConnector.getName(), otherLiveConnector); pairs[i] = otherLiveConnector.getName(); @@ -198,8 +165,7 @@ public class MultipleLivesMultipleBackupsFailoverTest extends MultipleBackupsFai } @Override - protected boolean isNetty() - { + protected boolean isNetty() { return false; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/MultipleServerFailoverTestBase.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/MultipleServerFailoverTestBase.java index 4fe3e1f907..4c0a23e3b8 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/MultipleServerFailoverTestBase.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/MultipleServerFailoverTestBase.java @@ -41,8 +41,7 @@ import org.junit.Before; import java.util.ArrayList; import java.util.List; -public abstract class MultipleServerFailoverTestBase extends ActiveMQTestBase -{ +public abstract class MultipleServerFailoverTestBase extends ActiveMQTestBase { // Constants ----------------------------------------------------- protected static final SimpleString ADDRESS = new SimpleString("jms.queues.FailoverTestAddress"); @@ -71,56 +70,44 @@ public abstract class MultipleServerFailoverTestBase extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); liveServers = new ArrayList(); backupServers = new ArrayList(); backupConfigs = new ArrayList(); liveConfigs = new ArrayList(); - for (int i = 0; i < getLiveServerCount(); i++) - { + for (int i = 0; i < getLiveServerCount(); i++) { HAPolicyConfiguration haPolicyConfiguration = null; - if (isSharedStore()) - { + if (isSharedStore()) { haPolicyConfiguration = new SharedStoreMasterPolicyConfiguration(); - ((SharedStoreMasterPolicyConfiguration)haPolicyConfiguration).setFailbackDelay(1000); + ((SharedStoreMasterPolicyConfiguration) haPolicyConfiguration).setFailbackDelay(1000); } - else - { + else { haPolicyConfiguration = new ReplicatedPolicyConfiguration(); - if (getNodeGroupName() != null) - { - ((ReplicatedPolicyConfiguration)haPolicyConfiguration).setGroupName(getNodeGroupName() + "-" + i); + if (getNodeGroupName() != null) { + ((ReplicatedPolicyConfiguration) haPolicyConfiguration).setGroupName(getNodeGroupName() + "-" + i); } } - Configuration configuration = createDefaultConfig(isNetty()) - .clearAcceptorConfigurations() - .addAcceptorConfiguration(getAcceptorTransportConfiguration(true, i)) - .setHAPolicyConfiguration(haPolicyConfiguration); + Configuration configuration = createDefaultConfig(isNetty()).clearAcceptorConfigurations().addAcceptorConfiguration(getAcceptorTransportConfiguration(true, i)).setHAPolicyConfiguration(haPolicyConfiguration); - if (!isSharedStore()) - { + if (!isSharedStore()) { configuration.setBindingsDirectory(getBindingsDir(i, false)); configuration.setJournalDirectory(getJournalDir(i, false)); configuration.setPagingDirectory(getPageDir(i, false)); configuration.setLargeMessagesDirectory(getLargeMessagesDir(i, false)); } - else - { + else { //todo } TransportConfiguration livetc = getConnectorTransportConfiguration(true, i); configuration.addConnectorConfiguration(livetc.getName(), livetc); List connectors = new ArrayList(); - for (int j = 0; j < getLiveServerCount(); j++) - { - if (j != i) - { + for (int j = 0; j < getLiveServerCount(); j++) { + if (j != i) { TransportConfiguration staticTc = getConnectorTransportConfiguration(true, j); configuration.getConnectorConfigurations().put(staticTc.getName(), staticTc); connectors.add(staticTc.getName()); @@ -136,55 +123,43 @@ public abstract class MultipleServerFailoverTestBase extends ActiveMQTestBase activeMQServer.setIdentity("Live-" + i); liveServers.add(activeMQServer); } - for (int i = 0; i < getBackupServerCount(); i++) - { + for (int i = 0; i < getBackupServerCount(); i++) { HAPolicyConfiguration haPolicyConfiguration = null; - if (isSharedStore()) - { + if (isSharedStore()) { haPolicyConfiguration = new SharedStoreSlavePolicyConfiguration(); - ((SharedStoreSlavePolicyConfiguration)haPolicyConfiguration).setFailbackDelay(1000); + ((SharedStoreSlavePolicyConfiguration) haPolicyConfiguration).setFailbackDelay(1000); } - else - { + else { haPolicyConfiguration = new ReplicaPolicyConfiguration(); - ((ReplicaPolicyConfiguration)haPolicyConfiguration).setFailbackDelay(1000); - if (getNodeGroupName() != null) - { - ((ReplicaPolicyConfiguration)haPolicyConfiguration).setGroupName(getNodeGroupName() + "-" + i); + ((ReplicaPolicyConfiguration) haPolicyConfiguration).setFailbackDelay(1000); + if (getNodeGroupName() != null) { + ((ReplicaPolicyConfiguration) haPolicyConfiguration).setGroupName(getNodeGroupName() + "-" + i); } } - Configuration configuration = createDefaultConfig(isNetty()) - .clearAcceptorConfigurations() - .addAcceptorConfiguration(getAcceptorTransportConfiguration(false, i)) - .setHAPolicyConfiguration(haPolicyConfiguration); + Configuration configuration = createDefaultConfig(isNetty()).clearAcceptorConfigurations().addAcceptorConfiguration(getAcceptorTransportConfiguration(false, i)).setHAPolicyConfiguration(haPolicyConfiguration); - if (!isSharedStore()) - { + if (!isSharedStore()) { configuration.setBindingsDirectory(getBindingsDir(i, true)); configuration.setJournalDirectory(getJournalDir(i, true)); configuration.setPagingDirectory(getPageDir(i, true)); configuration.setLargeMessagesDirectory(getLargeMessagesDir(i, true)); } - else - { + else { //todo } TransportConfiguration backuptc = getConnectorTransportConfiguration(false, i); configuration.addConnectorConfiguration(backuptc.getName(), backuptc); List connectors = new ArrayList(); - for (int j = 0; j < getBackupServerCount(); j++) - { + for (int j = 0; j < getBackupServerCount(); j++) { TransportConfiguration staticTc = getConnectorTransportConfiguration(true, j); configuration.addConnectorConfiguration(staticTc.getName(), staticTc); connectors.add(staticTc.getName()); } - for (int j = 0; j < getBackupServerCount(); j++) - { - if (j != i) - { + for (int j = 0; j < getBackupServerCount(); j++) { + if (j != i) { TransportConfiguration staticTc = getConnectorTransportConfiguration(false, j); configuration.getConnectorConfigurations().put(staticTc.getName(), staticTc); connectors.add(staticTc.getName()); @@ -201,78 +176,61 @@ public abstract class MultipleServerFailoverTestBase extends ActiveMQTestBase } } - protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live, int node) - { + protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live, int node) { TransportConfiguration transportConfiguration; - if (isNetty()) - { + if (isNetty()) { transportConfiguration = TransportConfigurationUtils.getNettyAcceptor(live, node, (live ? "live-" : "backup-") + node); } - else - { + else { transportConfiguration = TransportConfigurationUtils.getInVMAcceptor(live, node, (live ? "live-" : "backup-") + node); } return transportConfiguration; } - protected TransportConfiguration getConnectorTransportConfiguration(final boolean live, int node) - { + protected TransportConfiguration getConnectorTransportConfiguration(final boolean live, int node) { TransportConfiguration transportConfiguration; - if (isNetty()) - { + if (isNetty()) { transportConfiguration = TransportConfigurationUtils.getNettyConnector(live, node, (live ? "live-" : "backup-") + node); } - else - { + else { transportConfiguration = TransportConfigurationUtils.getInVMConnector(live, node, (live ? "live-" : "backup-") + node); } return transportConfiguration; } - protected ServerLocatorInternal getServerLocator(int node) throws Exception - { - return (ServerLocatorInternal) addServerLocator(ActiveMQClient.createServerLocatorWithHA(getConnectorTransportConfiguration(true, node))) - .setRetryInterval(50) - .setReconnectAttempts(-1) - .setInitialConnectAttempts(-1); + protected ServerLocatorInternal getServerLocator(int node) throws Exception { + return (ServerLocatorInternal) addServerLocator(ActiveMQClient.createServerLocatorWithHA(getConnectorTransportConfiguration(true, node))).setRetryInterval(50).setReconnectAttempts(-1).setInitialConnectAttempts(-1); } - protected ServerLocatorInternal getBackupServerLocator(int node) throws Exception - { - return (ServerLocatorInternal) addServerLocator(ActiveMQClient.createServerLocatorWithHA(getConnectorTransportConfiguration(false, node))) - .setRetryInterval(50) - .setReconnectAttempts(-1) - .setInitialConnectAttempts(-1); + protected ServerLocatorInternal getBackupServerLocator(int node) throws Exception { + return (ServerLocatorInternal) addServerLocator(ActiveMQClient.createServerLocatorWithHA(getConnectorTransportConfiguration(false, node))).setRetryInterval(50).setReconnectAttempts(-1).setInitialConnectAttempts(-1); } protected ClientSession createSession(ClientSessionFactory sf, boolean autoCommitSends, boolean autoCommitAcks, - int ackBatchSize) throws Exception - { + int ackBatchSize) throws Exception { return addClientSession(sf.createSession(autoCommitSends, autoCommitAcks, ackBatchSize)); } - protected ClientSession createSession(ClientSessionFactory sf, boolean autoCommitSends, boolean autoCommitAcks) throws Exception - { + protected ClientSession createSession(ClientSessionFactory sf, + boolean autoCommitSends, + boolean autoCommitAcks) throws Exception { return addClientSession(sf.createSession(autoCommitSends, autoCommitAcks)); } - protected ClientSession createSession(ClientSessionFactory sf) throws Exception - { + protected ClientSession createSession(ClientSessionFactory sf) throws Exception { return addClientSession(sf.createSession()); } protected ClientSession createSession(ClientSessionFactory sf, boolean xa, boolean autoCommitSends, - boolean autoCommitAcks) throws Exception - { + boolean autoCommitAcks) throws Exception { return addClientSession(sf.createSession(xa, autoCommitSends, autoCommitAcks)); } - protected void waitForDistribution(SimpleString address, ActiveMQServer server, int messageCount) throws Exception - { + protected void waitForDistribution(SimpleString address, ActiveMQServer server, int messageCount) throws Exception { ActiveMQServerLogger.LOGGER.debug("waiting for distribution of messages on server " + server); long start = System.currentTimeMillis(); @@ -281,17 +239,14 @@ public abstract class MultipleServerFailoverTestBase extends ActiveMQTestBase Queue q = (Queue) server.getPostOffice().getBinding(address).getBindable(); - do - { + do { - if (getMessageCount(q) >= messageCount) - { + if (getMessageCount(q) >= messageCount) { return; } Thread.sleep(10); - } - while (System.currentTimeMillis() - start < timeout); + } while (System.currentTimeMillis() - start < timeout); throw new Exception(); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyAsynchronousFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyAsynchronousFailoverTest.java index f3b2c67971..3fabe3bce3 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyAsynchronousFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyAsynchronousFailoverTest.java @@ -18,17 +18,15 @@ package org.apache.activemq.artemis.tests.integration.cluster.failover; import org.apache.activemq.artemis.api.core.TransportConfiguration; -public class NettyAsynchronousFailoverTest extends AsynchronousFailoverTest -{ +public class NettyAsynchronousFailoverTest extends AsynchronousFailoverTest { + @Override - protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live) - { + protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live) { return getNettyAcceptorTransportConfiguration(live); } @Override - protected TransportConfiguration getConnectorTransportConfiguration(final boolean live) - { + protected TransportConfiguration getConnectorTransportConfiguration(final boolean live) { return getNettyConnectorTransportConfiguration(live); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyAsynchronousReattachTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyAsynchronousReattachTest.java index 6096e88a08..b8a19cc9b7 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyAsynchronousReattachTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyAsynchronousReattachTest.java @@ -21,16 +21,13 @@ import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.core.client.impl.ClientSessionInternal; import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; -public class NettyAsynchronousReattachTest extends NettyAsynchronousFailoverTest -{ +public class NettyAsynchronousReattachTest extends NettyAsynchronousFailoverTest { private final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @Override - protected void crash(final ClientSession... sessions) throws Exception - { - for (ClientSession session : sessions) - { + protected void crash(final ClientSession... sessions) throws Exception { + for (ClientSession session : sessions) { log.debug("Crashing session " + session); ClientSessionInternal internalSession = (ClientSessionInternal) session; internalSession.getConnection().fail(new ActiveMQNotConnectedException("oops")); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyDiscoveryClusterWithBackupFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyDiscoveryClusterWithBackupFailoverTest.java index 00fa2db0e8..b3c181f7c8 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyDiscoveryClusterWithBackupFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyDiscoveryClusterWithBackupFailoverTest.java @@ -16,11 +16,10 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.failover; -public class NettyDiscoveryClusterWithBackupFailoverTest extends DiscoveryClusterWithBackupFailoverTest -{ +public class NettyDiscoveryClusterWithBackupFailoverTest extends DiscoveryClusterWithBackupFailoverTest { + @Override - protected boolean isNetty() - { + protected boolean isNetty() { return true; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyFailoverTest.java index 01a765a717..775a7d905a 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyFailoverTest.java @@ -32,32 +32,25 @@ import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.core.client.impl.ClientSessionFactoryInternal; import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants; -public class NettyFailoverTest extends FailoverTest -{ +public class NettyFailoverTest extends FailoverTest { + @Override - protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live) - { + protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live) { return getNettyAcceptorTransportConfiguration(live); } @Override - protected TransportConfiguration getConnectorTransportConfiguration(final boolean live) - { + protected TransportConfiguration getConnectorTransportConfiguration(final boolean live) { return getNettyConnectorTransportConfiguration(live); } @Test - public void testFailoverWithHostAlias() throws Exception - { + public void testFailoverWithHostAlias() throws Exception { Map params = new HashMap(); params.put(TransportConstants.HOST_PROP_NAME, "127.0.0.1"); TransportConfiguration tc = createTransportConfiguration(true, false, params); - ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithHA(tc)) - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true) - .setReconnectAttempts(-1); + ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithHA(tc)).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true).setReconnectAttempts(-1); ClientSessionFactoryInternal sf = createSessionFactoryAndWaitForTopology(locator, 2); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyFileStorageDiscoveryClusterWithBackupFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyFileStorageDiscoveryClusterWithBackupFailoverTest.java index 4ec7067935..b602eeafe4 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyFileStorageDiscoveryClusterWithBackupFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyFileStorageDiscoveryClusterWithBackupFailoverTest.java @@ -16,11 +16,10 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.failover; -public class NettyFileStorageDiscoveryClusterWithBackupFailoverTest extends DiscoveryClusterWithBackupFailoverTest -{ +public class NettyFileStorageDiscoveryClusterWithBackupFailoverTest extends DiscoveryClusterWithBackupFailoverTest { + @Override - protected boolean isNetty() - { + protected boolean isNetty() { return true; } } \ No newline at end of file diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyFileStorageStaticClusterWithBackupFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyFileStorageStaticClusterWithBackupFailoverTest.java index b85bb1b276..13c5316d87 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyFileStorageStaticClusterWithBackupFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyFileStorageStaticClusterWithBackupFailoverTest.java @@ -16,11 +16,10 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.failover; -public class NettyFileStorageStaticClusterWithBackupFailoverTest extends StaticClusterWithBackupFailoverTest -{ +public class NettyFileStorageStaticClusterWithBackupFailoverTest extends StaticClusterWithBackupFailoverTest { + @Override - protected boolean isNetty() - { + protected boolean isNetty() { return true; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyReplicatedFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyReplicatedFailoverTest.java index f5d4018aa2..4be48e9427 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyReplicatedFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyReplicatedFailoverTest.java @@ -21,41 +21,33 @@ import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.tests.integration.cluster.util.SameProcessActiveMQServer; import org.apache.activemq.artemis.tests.integration.cluster.util.TestableServer; -public class NettyReplicatedFailoverTest extends NettyFailoverTest -{ +public class NettyReplicatedFailoverTest extends NettyFailoverTest { @Override - protected TestableServer createTestableServer(Configuration config) - { + protected TestableServer createTestableServer(Configuration config) { return new SameProcessActiveMQServer(createServer(true, config)); } @Override - protected void createConfigs() throws Exception - { + protected void createConfigs() throws Exception { createReplicatedConfigs(); } @Override - protected final void crash(boolean waitFailure, ClientSession... sessions) throws Exception - { - if (sessions.length > 0) - { - for (ClientSession session : sessions) - { + protected final void crash(boolean waitFailure, ClientSession... sessions) throws Exception { + if (sessions.length > 0) { + for (ClientSession session : sessions) { waitForRemoteBackup(session.getSessionFactory(), 5, true, backupServer.getServer()); } } - else - { + else { waitForRemoteBackup(null, 5, true, backupServer.getServer()); } super.crash(waitFailure, sessions); } @Override - protected final void crash(ClientSession... sessions) throws Exception - { + protected final void crash(ClientSession... sessions) throws Exception { crash(true, sessions); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyStaticClusterWithBackupFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyStaticClusterWithBackupFailoverTest.java index aee82fbb7a..803b415471 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyStaticClusterWithBackupFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/NettyStaticClusterWithBackupFailoverTest.java @@ -16,11 +16,10 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.failover; -public class NettyStaticClusterWithBackupFailoverTest extends StaticClusterWithBackupFailoverTest -{ +public class NettyStaticClusterWithBackupFailoverTest extends StaticClusterWithBackupFailoverTest { + @Override - protected boolean isNetty() - { + protected boolean isNetty() { return true; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/PagingFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/PagingFailoverTest.java index 216e3003fc..45d48377cf 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/PagingFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/PagingFailoverTest.java @@ -42,8 +42,7 @@ import java.util.HashMap; *
    * TODO: validate replication failover also */ -public class PagingFailoverTest extends FailoverTestBase -{ +public class PagingFailoverTest extends FailoverTestBase { // Constants ----------------------------------------------------- private static final SimpleString ADDRESS = new SimpleString("SimpleAddress"); @@ -62,41 +61,33 @@ public class PagingFailoverTest extends FailoverTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = getServerLocator(); } @Test - public void testPageFailBeforeConsume() throws Exception - { + public void testPageFailBeforeConsume() throws Exception { internalTestPage(false, true); } @Test - public void testPage() throws Exception - { + public void testPage() throws Exception { internalTestPage(false, false); } @Test - public void testPageTransactioned() throws Exception - { + public void testPageTransactioned() throws Exception { internalTestPage(true, false); } @Test - public void testPageTransactionedFailBeforeConsume() throws Exception - { + public void testPageTransactionedFailBeforeConsume() throws Exception { internalTestPage(true, true); } - public void internalTestPage(final boolean transacted, final boolean failBeforeConsume) throws Exception - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setReconnectAttempts(-1); + public void internalTestPage(final boolean transacted, final boolean failBeforeConsume) throws Exception { + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setReconnectAttempts(-1); sf = createSessionFactoryAndWaitForTopology(locator, 2); session = addClientSession(sf.createSession(!transacted, !transacted, 0)); @@ -107,10 +98,8 @@ public class PagingFailoverTest extends FailoverTestBase final int TOTAL_MESSAGES = 2000; - for (int i = 0; i < TOTAL_MESSAGES; i++) - { - if (transacted && i % 10 == 0) - { + for (int i = 0; i < TOTAL_MESSAGES; i++) { + if (transacted && i % 10 == 0) { session.commit(); } ClientMessage msg = session.createMessage(true); @@ -120,8 +109,7 @@ public class PagingFailoverTest extends FailoverTestBase session.commit(); - if (failBeforeConsume) - { + if (failBeforeConsume) { crash(session); waitForBackup(null, 5); } @@ -136,13 +124,11 @@ public class PagingFailoverTest extends FailoverTestBase final int MIDDLE = TOTAL_MESSAGES / 2; - for (int i = 0; i < MIDDLE; i++) - { + for (int i = 0; i < MIDDLE; i++) { ClientMessage msg = cons.receive(20000); Assert.assertNotNull(msg); msg.acknowledge(); - if (transacted && i % 10 == 0) - { + if (transacted && i % 10 == 0) { session.commit(); } Assert.assertEquals(i, msg.getObjectProperty(new SimpleString("key"))); @@ -154,8 +140,7 @@ public class PagingFailoverTest extends FailoverTestBase Thread.sleep(1000); - if (!failBeforeConsume) - { + if (!failBeforeConsume) { crash(session); // failSession(session, latch); } @@ -168,8 +153,7 @@ public class PagingFailoverTest extends FailoverTestBase session.start(); - for (int i = MIDDLE; i < TOTAL_MESSAGES; i++) - { + for (int i = MIDDLE; i < TOTAL_MESSAGES; i++) { ClientMessage msg = cons.receive(5000); Assert.assertNotNull(msg); @@ -180,11 +164,8 @@ public class PagingFailoverTest extends FailoverTestBase } @Test - public void testExpireMessage() throws Exception - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setReconnectAttempts(-1); + public void testExpireMessage() throws Exception { + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setReconnectAttempts(-1); ClientSessionFactoryInternal sf = createSessionFactoryAndWaitForTopology(locator, 2); session = sf.createSession(true, true, 0); @@ -195,8 +176,7 @@ public class PagingFailoverTest extends FailoverTestBase final int TOTAL_MESSAGES = 1000; - for (int i = 0; i < TOTAL_MESSAGES; i++) - { + for (int i = 0; i < TOTAL_MESSAGES; i++) { ClientMessage msg = session.createMessage(true); msg.putIntProperty(new SimpleString("key"), i); msg.setExpiration(System.currentTimeMillis() + 1000); @@ -211,8 +191,7 @@ public class PagingFailoverTest extends FailoverTestBase long timeout = System.currentTimeMillis() + 60000; - while (timeout > System.currentTimeMillis() && queue.getPageSubscription().isPaging()) - { + while (timeout > System.currentTimeMillis() && queue.getPageSubscription().isPaging()) { Thread.sleep(100); // Simulating what would happen on expire queue.expireReferences(); @@ -222,33 +201,27 @@ public class PagingFailoverTest extends FailoverTestBase } - // Package protected --------------------------------------------- // Protected ----------------------------------------------------- @Override - protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live) - { + protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live) { return TransportConfigurationUtils.getInVMAcceptor(live); } @Override - protected TransportConfiguration getConnectorTransportConfiguration(final boolean live) - { + protected TransportConfiguration getConnectorTransportConfiguration(final boolean live) { return TransportConfigurationUtils.getInVMConnector(live); } @Override - protected ActiveMQServer createServer(final boolean realFiles, final Configuration configuration) - { - return addServer(createInVMFailoverServer(true, configuration, PAGE_SIZE, PAGE_MAX, - new HashMap(), nodeManager, 2)); + protected ActiveMQServer createServer(final boolean realFiles, final Configuration configuration) { + return addServer(createInVMFailoverServer(true, configuration, PAGE_SIZE, PAGE_MAX, new HashMap(), nodeManager, 2)); } @Override - protected TestableServer createTestableServer(Configuration config) - { + protected TestableServer createTestableServer(Configuration config) { return new SameProcessActiveMQServer(createServer(true, config)); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/QuorumFailOverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/QuorumFailOverTest.java index 6f366ae917..cdba3f795d 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/QuorumFailOverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/QuorumFailOverTest.java @@ -30,32 +30,29 @@ import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; import org.apache.activemq.artemis.tests.integration.cluster.util.BackupSyncDelay; import org.junit.Test; -public class QuorumFailOverTest extends StaticClusterWithBackupFailoverTest -{ +public class QuorumFailOverTest extends StaticClusterWithBackupFailoverTest { + @Override - protected void setupServers() throws Exception - { + protected void setupServers() throws Exception { super.setupServers(); //we need to know who is connected to who - ((ReplicatedPolicyConfiguration)servers[0].getConfiguration().getHAPolicyConfiguration()).setGroupName("group0"); - ((ReplicatedPolicyConfiguration)servers[1].getConfiguration().getHAPolicyConfiguration()).setGroupName("group1"); - ((ReplicatedPolicyConfiguration)servers[2].getConfiguration().getHAPolicyConfiguration()).setGroupName("group2"); - ((ReplicaPolicyConfiguration)servers[3].getConfiguration().getHAPolicyConfiguration()).setGroupName("group0"); - ((ReplicaPolicyConfiguration)servers[4].getConfiguration().getHAPolicyConfiguration()).setGroupName("group1"); - ((ReplicaPolicyConfiguration)servers[5].getConfiguration().getHAPolicyConfiguration()).setGroupName("group2"); + ((ReplicatedPolicyConfiguration) servers[0].getConfiguration().getHAPolicyConfiguration()).setGroupName("group0"); + ((ReplicatedPolicyConfiguration) servers[1].getConfiguration().getHAPolicyConfiguration()).setGroupName("group1"); + ((ReplicatedPolicyConfiguration) servers[2].getConfiguration().getHAPolicyConfiguration()).setGroupName("group2"); + ((ReplicaPolicyConfiguration) servers[3].getConfiguration().getHAPolicyConfiguration()).setGroupName("group0"); + ((ReplicaPolicyConfiguration) servers[4].getConfiguration().getHAPolicyConfiguration()).setGroupName("group1"); + ((ReplicaPolicyConfiguration) servers[5].getConfiguration().getHAPolicyConfiguration()).setGroupName("group2"); } @Test - public void testQuorumVoting() throws Exception - { + public void testQuorumVoting() throws Exception { int[] liveServerIDs = new int[]{0, 1, 2}; setupCluster(); startServers(0, 1, 2); new BackupSyncDelay(servers[4], servers[1], PacketImpl.REPLICATION_SCHEDULED_FAILOVER); startServers(3, 4, 5); - for (int i : liveServerIDs) - { + for (int i : liveServerIDs) { waitForTopology(servers[i], 3, 3); } @@ -63,8 +60,7 @@ public class QuorumFailOverTest extends StaticClusterWithBackupFailoverTest waitForFailoverTopology(4, 0, 1, 2); waitForFailoverTopology(5, 0, 1, 2); - for (int i : liveServerIDs) - { + for (int i : liveServerIDs) { setupSessionFactory(i, i + 3, isNetty(), false); createQueue(i, QUEUES_TESTADDRESS, QUEUE_NAME, null, true); addConsumer(i, i, QUEUE_NAME, null); @@ -99,39 +95,32 @@ public class QuorumFailOverTest extends StaticClusterWithBackupFailoverTest } @Override - protected boolean isSharedStorage() - { + protected boolean isSharedStorage() { return false; } - private static class TopologyListener implements ClusterTopologyListener - { - final String prefix; - final Map> nodes = - new ConcurrentHashMap>(); + private static class TopologyListener implements ClusterTopologyListener { - public TopologyListener(String string) - { + final String prefix; + final Map> nodes = new ConcurrentHashMap>(); + + public TopologyListener(String string) { prefix = string; } @Override - public void nodeUP(TopologyMember topologyMember, boolean last) - { - Pair connectorPair = - new Pair(topologyMember.getLive(), topologyMember.getBackup()); + public void nodeUP(TopologyMember topologyMember, boolean last) { + Pair connectorPair = new Pair(topologyMember.getLive(), topologyMember.getBackup()); nodes.put(topologyMember.getBackupGroupName(), connectorPair); } @Override - public void nodeDown(long eventUID, String nodeID) - { + public void nodeDown(long eventUID, String nodeID) { nodes.remove(nodeID); } @Override - public String toString() - { + public String toString() { return "TopologyListener(" + prefix + ", #=" + nodes.size() + ")"; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/QuorumVoteServerConnectTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/QuorumVoteServerConnectTest.java index 7cccb57bc3..283705b37d 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/QuorumVoteServerConnectTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/QuorumVoteServerConnectTest.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.failover; - import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.core.server.cluster.qourum.BooleanVote; import org.apache.activemq.artemis.core.server.cluster.qourum.QuorumVoteServerConnect; @@ -29,56 +28,37 @@ import java.util.Arrays; import java.util.Collection; @RunWith(Parameterized.class) -public class QuorumVoteServerConnectTest extends ActiveMQTestBase -{ +public class QuorumVoteServerConnectTest extends ActiveMQTestBase { private final int size; private final int trueVotes; @Parameterized.Parameters(name = "size={0} trueVotes={1}") - public static Collection primeNumbers() - { - return Arrays.asList(new Object[][] - { - {1, 0}, - {2, 0}, - {3, 1}, - {4, 2}, - {5, 3} , - {6, 3}, - {7, 4}, - {8, 4}, - {9, 5} , - {10, 5} - }); + public static Collection primeNumbers() { + return Arrays.asList(new Object[][]{{1, 0}, {2, 0}, {3, 1}, {4, 2}, {5, 3}, {6, 3}, {7, 4}, {8, 4}, {9, 5}, {10, 5}}); } - public QuorumVoteServerConnectTest(int size, int trueVotes) - { + public QuorumVoteServerConnectTest(int size, int trueVotes) { this.size = size; this.trueVotes = trueVotes; } + @Test - public void testClusterSize() - { + public void testClusterSize() { QuorumVoteServerConnect quorum = new QuorumVoteServerConnect(size, new FakeStorageManager()); - for (int i = 0; i < trueVotes - 1; i++) - { + for (int i = 0; i < trueVotes - 1; i++) { quorum.vote(new BooleanVote(true)); } - if (size <= 2) - { + if (size <= 2) { assertTrue(quorum.getDecision()); } - else - { + else { assertFalse(quorum.getDecision()); } quorum = new QuorumVoteServerConnect(size, new FakeStorageManager()); - for (int i = 0; i < trueVotes; i++) - { + for (int i = 0; i < trueVotes; i++) { quorum.vote(new BooleanVote(true)); } assertTrue(quorum.getDecision()); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedAsynchronousFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedAsynchronousFailoverTest.java index c4bbbde4c2..2f6cf04eb5 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedAsynchronousFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedAsynchronousFailoverTest.java @@ -16,11 +16,10 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.failover; -public class ReplicatedAsynchronousFailoverTest extends AsynchronousFailoverTest -{ +public class ReplicatedAsynchronousFailoverTest extends AsynchronousFailoverTest { + @Override - protected void createConfigs() throws Exception - { + protected void createConfigs() throws Exception { createReplicatedConfigs(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedDistributionTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedDistributionTest.java index e5db567d39..d707865fb4 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedDistributionTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedDistributionTest.java @@ -35,8 +35,7 @@ import org.junit.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -public class ReplicatedDistributionTest extends ClusterTestBase -{ +public class ReplicatedDistributionTest extends ClusterTestBase { private static final SimpleString ADDRESS = new SimpleString("test.SomeAddress"); private ClientSession sessionOne; @@ -45,13 +44,10 @@ public class ReplicatedDistributionTest extends ClusterTestBase private ClientProducer producer; @Test - public void testRedistribution() throws Exception - { + public void testRedistribution() throws Exception { commonTestCode(); - - for (int i = 0; i < 50; i++) - { + for (int i = 0; i < 50; i++) { ClientMessage msg = consThree.receive(15000); Assert.assertNotNull(msg); @@ -85,8 +81,7 @@ public class ReplicatedDistributionTest extends ClusterTestBase // consThree = sessionThree.createConsumer(ADDRESS); - for (int i = 50; i < 100; i++) - { + for (int i = 50; i < 100; i++) { ClientMessage msg = consThree.receive(15000); Assert.assertNotNull(msg); @@ -112,12 +107,10 @@ public class ReplicatedDistributionTest extends ClusterTestBase } @Test - public void testSimpleRedistribution() throws Exception - { + public void testSimpleRedistribution() throws Exception { commonTestCode(); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage msg = consThree.receive(15000); Assert.assertNotNull(msg); @@ -126,8 +119,7 @@ public class ReplicatedDistributionTest extends ClusterTestBase int received = msg.getIntProperty("key"); - if (i != received) - { + if (i != received) { // Shouldn't this be a failure? System.out.println(i + "!=" + received); } @@ -143,15 +135,13 @@ public class ReplicatedDistributionTest extends ClusterTestBase Assert.assertNull(consOne.receiveImmediate()); } - private void commonTestCode() throws Exception - { + private void commonTestCode() throws Exception { waitForBindings(3, "test.SomeAddress", 1, 1, true); waitForBindings(1, "test.SomeAddress", 1, 1, false); producer = sessionOne.createProducer(ReplicatedDistributionTest.ADDRESS); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage msg = sessionOne.createMessage(true); msg.putIntProperty(new SimpleString("key"), i); producer.send(msg); @@ -164,8 +154,7 @@ public class ReplicatedDistributionTest extends ClusterTestBase * @param session * @throws InterruptedException */ - private void fail(final ClientSession session) throws InterruptedException - { + private void fail(final ClientSession session) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); @@ -185,8 +174,7 @@ public class ReplicatedDistributionTest extends ClusterTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); setupLiveServer(1, true, isSharedStore(), true, false); @@ -201,8 +189,7 @@ public class ReplicatedDistributionTest extends ClusterTestBase AddressSettings as = new AddressSettings().setRedistributionDelay(0); - for (int i : new int[]{1, 2, 3}) - { + for (int i : new int[]{1, 2, 3}) { getServer(i).getAddressSettingsRepository().addMatch("test.*", as); getServer(i).start(); } @@ -222,8 +209,7 @@ public class ReplicatedDistributionTest extends ClusterTestBase } @Override - protected boolean isSharedStore() - { + protected boolean isSharedStore() { return false; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedFailoverTest.java index 2d75b365b7..a93335292f 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedFailoverTest.java @@ -26,33 +26,28 @@ import org.junit.rules.TestRule; import org.junit.rules.TestWatcher; import org.junit.runner.Description; -public class ReplicatedFailoverTest extends FailoverTest -{ +public class ReplicatedFailoverTest extends FailoverTest { + boolean isReplicatedFailbackTest = false; @Rule - public TestRule watcher = new TestWatcher() - { + public TestRule watcher = new TestWatcher() { @Override - protected void starting(Description description) - { + protected void starting(Description description) { isReplicatedFailbackTest = description.getMethodName().equals("testReplicatedFailback"); } }; - protected void beforeWaitForRemoteBackupSynchronization() - { + protected void beforeWaitForRemoteBackupSynchronization() { } + @Test /* * default maxSavedReplicatedJournalsSize is 2, this means the backup will fall back to replicated only twice, after this * it is stopped permanently * - * */ - public void testReplicatedFailback() throws Exception - { - try - { + * */ public void testReplicatedFailback() throws Exception { + try { beforeWaitForRemoteBackupSynchronization(); waitForRemoteBackupSynchronization(backupServer.getServer()); @@ -115,68 +110,50 @@ public class ReplicatedFailoverTest extends FailoverTest //the server wouldnt have reset to backup assertFalse(backupServer.getServer().getHAPolicy().isBackup()); } - finally - { - if (sf != null) - { + finally { + if (sf != null) { sf.close(); } } } @Override - protected void createConfigs() throws Exception - { + protected void createConfigs() throws Exception { createReplicatedConfigs(); } @Override - protected void setupHAPolicyConfiguration() - { - if (isReplicatedFailbackTest) - { - ((ReplicatedPolicyConfiguration) liveConfig.getHAPolicyConfiguration()) - .setCheckForLiveServer(true); - ((ReplicaPolicyConfiguration) backupConfig.getHAPolicyConfiguration()) - .setMaxSavedReplicatedJournalsSize(2) - .setAllowFailBack(true) - .setFailbackDelay(2000); + protected void setupHAPolicyConfiguration() { + if (isReplicatedFailbackTest) { + ((ReplicatedPolicyConfiguration) liveConfig.getHAPolicyConfiguration()).setCheckForLiveServer(true); + ((ReplicaPolicyConfiguration) backupConfig.getHAPolicyConfiguration()).setMaxSavedReplicatedJournalsSize(2).setAllowFailBack(true).setFailbackDelay(2000); } - else - { + else { super.setupHAPolicyConfiguration(); } } @Override - protected void crash(boolean waitFailure, ClientSession... sessions) throws Exception - { - if (sessions.length > 0) - { - for (ClientSession session : sessions) - { + protected void crash(boolean waitFailure, ClientSession... sessions) throws Exception { + if (sessions.length > 0) { + for (ClientSession session : sessions) { waitForRemoteBackup(session.getSessionFactory(), 5, true, backupServer.getServer()); } } - else - { + else { waitForRemoteBackup(null, 5, true, backupServer.getServer()); } super.crash(waitFailure, sessions); } @Override - protected void crash(ClientSession... sessions) throws Exception - { - if (sessions.length > 0) - { - for (ClientSession session : sessions) - { + protected void crash(ClientSession... sessions) throws Exception { + if (sessions.length > 0) { + for (ClientSession session : sessions) { waitForRemoteBackup(session.getSessionFactory(), 5, true, backupServer.getServer()); } } - else - { + else { waitForRemoteBackup(null, 5, true, backupServer.getServer()); } super.crash(sessions); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedFailoverUsingNodeGroupNameTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedFailoverUsingNodeGroupNameTest.java index 2b80cbf028..6acd0fdbb4 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedFailoverUsingNodeGroupNameTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedFailoverUsingNodeGroupNameTest.java @@ -19,21 +19,19 @@ package org.apache.activemq.artemis.tests.integration.cluster.failover; import org.apache.activemq.artemis.core.config.ha.ReplicaPolicyConfiguration; import org.apache.activemq.artemis.core.config.ha.ReplicatedPolicyConfiguration; -public class ReplicatedFailoverUsingNodeGroupNameTest extends ReplicatedFailoverTest -{ +public class ReplicatedFailoverUsingNodeGroupNameTest extends ReplicatedFailoverTest { + @Override - protected void createReplicatedConfigs() throws Exception - { + protected void createReplicatedConfigs() throws Exception { super.createReplicatedConfigs(); - ((ReplicatedPolicyConfiguration)liveConfig.getHAPolicyConfiguration()).setGroupName("liveNodeGroup1"); - ((ReplicaPolicyConfiguration)backupConfig.getHAPolicyConfiguration()).setGroupName("liveNodeGroup1"); + ((ReplicatedPolicyConfiguration) liveConfig.getHAPolicyConfiguration()).setGroupName("liveNodeGroup1"); + ((ReplicaPolicyConfiguration) backupConfig.getHAPolicyConfiguration()).setGroupName("liveNodeGroup1"); } @Override - protected void setupHAPolicyConfiguration() - { + protected void setupHAPolicyConfiguration() { super.setupHAPolicyConfiguration(); - ((ReplicatedPolicyConfiguration)liveConfig.getHAPolicyConfiguration()).setGroupName("liveNodeGroup1"); - ((ReplicaPolicyConfiguration)backupConfig.getHAPolicyConfiguration()).setGroupName("liveNodeGroup1"); + ((ReplicatedPolicyConfiguration) liveConfig.getHAPolicyConfiguration()).setGroupName("liveNodeGroup1"); + ((ReplicaPolicyConfiguration) backupConfig.getHAPolicyConfiguration()).setGroupName("liveNodeGroup1"); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedLargeMessageFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedLargeMessageFailoverTest.java index ff8741e293..771455ac80 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedLargeMessageFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedLargeMessageFailoverTest.java @@ -16,48 +16,37 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.failover; - import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.core.client.impl.ClientSessionInternal; -public class ReplicatedLargeMessageFailoverTest extends LargeMessageFailoverTest -{ +public class ReplicatedLargeMessageFailoverTest extends LargeMessageFailoverTest { @Override - protected void createConfigs() throws Exception - { + protected void createConfigs() throws Exception { createReplicatedConfigs(); } @Override - protected void crash(boolean waitFailure, ClientSession... sessions) throws Exception - { - if (sessions.length > 0) - { - for (ClientSession session : sessions) - { - waitForRemoteBackup(((ClientSessionInternal)session).getSessionFactory(), 5, true, backupServer.getServer()); + protected void crash(boolean waitFailure, ClientSession... sessions) throws Exception { + if (sessions.length > 0) { + for (ClientSession session : sessions) { + waitForRemoteBackup(((ClientSessionInternal) session).getSessionFactory(), 5, true, backupServer.getServer()); } } - else - { + else { waitForRemoteBackup(null, 5, true, backupServer.getServer()); } super.crash(waitFailure, sessions); } @Override - protected void crash(ClientSession... sessions) throws Exception - { - if (sessions.length > 0) - { - for (ClientSession session : sessions) - { - waitForRemoteBackup(((ClientSessionInternal)session).getSessionFactory(), 5, true, backupServer.getServer()); + protected void crash(ClientSession... sessions) throws Exception { + if (sessions.length > 0) { + for (ClientSession session : sessions) { + waitForRemoteBackup(((ClientSessionInternal) session).getSessionFactory(), 5, true, backupServer.getServer()); } } - else - { + else { waitForRemoteBackup(null, 5, true, backupServer.getServer()); } super.crash(sessions); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedLargeMessageWithDelayFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedLargeMessageWithDelayFailoverTest.java index 32f569bb9c..6ff5d6bba8 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedLargeMessageWithDelayFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedLargeMessageWithDelayFailoverTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.cluster.failover; + import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.tests.integration.cluster.util.BackupSyncDelay; import org.junit.After; @@ -23,14 +24,13 @@ import org.junit.Before; /** * See {@link BackupSyncDelay} for the rationale about these 'WithDelay' tests. */ -public class ReplicatedLargeMessageWithDelayFailoverTest extends ReplicatedLargeMessageFailoverTest -{ +public class ReplicatedLargeMessageWithDelayFailoverTest extends ReplicatedLargeMessageFailoverTest { + private BackupSyncDelay syncDelay; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { startBackupServer = false; super.setUp(); syncDelay = new BackupSyncDelay(backupServer, liveServer); @@ -38,14 +38,12 @@ public class ReplicatedLargeMessageWithDelayFailoverTest extends ReplicatedLarge } @Override - protected void crash(ClientSession... sessions) throws Exception - { + protected void crash(ClientSession... sessions) throws Exception { crash(true, sessions); } @Override - protected void crash(boolean waitFailure, ClientSession... sessions) throws Exception - { + protected void crash(boolean waitFailure, ClientSession... sessions) throws Exception { syncDelay.deliverUpToDateMsg(); waitForBackup(null, 30); super.crash(waitFailure, sessions); @@ -53,8 +51,7 @@ public class ReplicatedLargeMessageWithDelayFailoverTest extends ReplicatedLarge @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { syncDelay.deliverUpToDateMsg(); super.tearDown(); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedManyMultipleServerFailoverNoNodeGroupNameTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedManyMultipleServerFailoverNoNodeGroupNameTest.java index d4ed44c8c5..d76b362b63 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedManyMultipleServerFailoverNoNodeGroupNameTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedManyMultipleServerFailoverNoNodeGroupNameTest.java @@ -16,11 +16,10 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.failover; -public class ReplicatedManyMultipleServerFailoverNoNodeGroupNameTest extends ReplicatedManyMultipleServerFailoverTest -{ +public class ReplicatedManyMultipleServerFailoverNoNodeGroupNameTest extends ReplicatedManyMultipleServerFailoverTest { + @Override - public String getNodeGroupName() - { + public String getNodeGroupName() { return null; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedManyMultipleServerFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedManyMultipleServerFailoverTest.java index de1b7bd417..717d253064 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedManyMultipleServerFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedManyMultipleServerFailoverTest.java @@ -16,17 +16,15 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.failover; -public class ReplicatedManyMultipleServerFailoverTest extends ReplicatedMultipleServerFailoverTest -{ +public class ReplicatedManyMultipleServerFailoverTest extends ReplicatedMultipleServerFailoverTest { + @Override - public int getLiveServerCount() - { + public int getLiveServerCount() { return 6; } @Override - public int getBackupServerCount() - { + public int getBackupServerCount() { return 6; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedMultipleServerFailoverExtraBackupsTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedMultipleServerFailoverExtraBackupsTest.java index 15b7d3988d..ffd77dd785 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedMultipleServerFailoverExtraBackupsTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedMultipleServerFailoverExtraBackupsTest.java @@ -29,14 +29,13 @@ import org.apache.activemq.artemis.tests.integration.cluster.util.TestableServer import org.apache.activemq.artemis.core.config.ha.ReplicaPolicyConfiguration; import org.junit.Test; -public class ReplicatedMultipleServerFailoverExtraBackupsTest extends ReplicatedMultipleServerFailoverTest -{ +public class ReplicatedMultipleServerFailoverExtraBackupsTest extends ReplicatedMultipleServerFailoverTest { + @Override @Test - public void testStartLiveFirst() throws Exception - { - ((ReplicaPolicyConfiguration)backupServers.get(2).getServer().getConfiguration().getHAPolicyConfiguration()).setGroupName(getNodeGroupName() + "-0"); - ((ReplicaPolicyConfiguration)backupServers.get(3).getServer().getConfiguration().getHAPolicyConfiguration()).setGroupName(getNodeGroupName() + "-1"); + public void testStartLiveFirst() throws Exception { + ((ReplicaPolicyConfiguration) backupServers.get(2).getServer().getConfiguration().getHAPolicyConfiguration()).setGroupName(getNodeGroupName() + "-0"); + ((ReplicaPolicyConfiguration) backupServers.get(3).getServer().getConfiguration().getHAPolicyConfiguration()).setGroupName(getNodeGroupName() + "-1"); startServers(liveServers); startServers(backupServers); @@ -48,28 +47,23 @@ public class ReplicatedMultipleServerFailoverExtraBackupsTest extends Replicated sendCrashBackupReceive(); } - private void waitForBackups() throws InterruptedException - { - for (TestableServer backupServer : backupServers) - { + private void waitForBackups() throws InterruptedException { + for (TestableServer backupServer : backupServers) { waitForComponent(backupServer.getServer(), 5); } } - private void startServers(List servers) throws Exception - { - for (TestableServer testableServer : servers) - { + private void startServers(List servers) throws Exception { + for (TestableServer testableServer : servers) { testableServer.start(); } } @Override @Test - public void testStartBackupFirst() throws Exception - { - ((ReplicaPolicyConfiguration)backupServers.get(2).getServer().getConfiguration().getHAPolicyConfiguration()).setGroupName(getNodeGroupName() + "-0"); - ((ReplicaPolicyConfiguration)backupServers.get(3).getServer().getConfiguration().getHAPolicyConfiguration()).setGroupName(getNodeGroupName() + "-1"); + public void testStartBackupFirst() throws Exception { + ((ReplicaPolicyConfiguration) backupServers.get(2).getServer().getConfiguration().getHAPolicyConfiguration()).setGroupName(getNodeGroupName() + "-0"); + ((ReplicaPolicyConfiguration) backupServers.get(3).getServer().getConfiguration().getHAPolicyConfiguration()).setGroupName(getNodeGroupName() + "-1"); startServers(backupServers); startServers(liveServers); @@ -79,8 +73,7 @@ public class ReplicatedMultipleServerFailoverExtraBackupsTest extends Replicated sendCrashReceive(); } - protected void sendCrashBackupReceive() throws Exception - { + protected void sendCrashBackupReceive() throws Exception { ServerLocator locator0 = getBackupServerLocator(0); ServerLocator locator1 = getBackupServerLocator(1); @@ -92,8 +85,7 @@ public class ReplicatedMultipleServerFailoverExtraBackupsTest extends Replicated ClientProducer producer = session0.createProducer(ADDRESS); - for (int i = 0; i < 200; i++) - { + for (int i = 0; i < 200; i++) { ClientMessage message = session0.createMessage(true); setBody(i, message); @@ -109,16 +101,13 @@ public class ReplicatedMultipleServerFailoverExtraBackupsTest extends Replicated waitForDistribution(ADDRESS, backupServers.get(1).getServer(), 100); List toCrash = new ArrayList(); - for (TestableServer backupServer : backupServers) - { - if (!backupServer.getServer().getHAPolicy().isBackup()) - { + for (TestableServer backupServer : backupServers) { + if (!backupServer.getServer().getHAPolicy().isBackup()) { toCrash.add(backupServer); } } - for (TestableServer testableServer : toCrash) - { + for (TestableServer testableServer : toCrash) { testableServer.crash(); } @@ -127,9 +116,7 @@ public class ReplicatedMultipleServerFailoverExtraBackupsTest extends Replicated session0.start(); session1.start(); - - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage message = consumer0.receive(1000); assertNotNull("expecting durable msg " + i, message); message.acknowledge(); @@ -140,10 +127,8 @@ public class ReplicatedMultipleServerFailoverExtraBackupsTest extends Replicated } } - @Override - public int getBackupServerCount() - { + public int getBackupServerCount() { return 4; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedMultipleServerFailoverNoGroupNodeNameTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedMultipleServerFailoverNoGroupNodeNameTest.java index d9dd93cc87..5a53c48ab1 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedMultipleServerFailoverNoGroupNodeNameTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedMultipleServerFailoverNoGroupNodeNameTest.java @@ -16,11 +16,10 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.failover; -public class ReplicatedMultipleServerFailoverNoGroupNodeNameTest extends ReplicatedMultipleServerFailoverTest -{ +public class ReplicatedMultipleServerFailoverNoGroupNodeNameTest extends ReplicatedMultipleServerFailoverTest { + @Override - public String getNodeGroupName() - { + public String getNodeGroupName() { return null; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedMultipleServerFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedMultipleServerFailoverTest.java index cedd805fc2..2f3a669350 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedMultipleServerFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedMultipleServerFailoverTest.java @@ -25,17 +25,14 @@ import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.tests.integration.cluster.util.TestableServer; import org.junit.Test; -public class ReplicatedMultipleServerFailoverTest extends MultipleServerFailoverTestBase -{ +public class ReplicatedMultipleServerFailoverTest extends MultipleServerFailoverTestBase { + @Test - public void testStartLiveFirst() throws Exception - { - for (TestableServer liveServer : liveServers) - { + public void testStartLiveFirst() throws Exception { + for (TestableServer liveServer : liveServers) { liveServer.start(); } - for (TestableServer backupServer : backupServers) - { + for (TestableServer backupServer : backupServers) { backupServer.start(); } waitForTopology(liveServers.get(0).getServer(), liveServers.size(), backupServers.size()); @@ -43,54 +40,44 @@ public class ReplicatedMultipleServerFailoverTest extends MultipleServerFailover } @Test - public void testStartBackupFirst() throws Exception - { - for (TestableServer backupServer : backupServers) - { + public void testStartBackupFirst() throws Exception { + for (TestableServer backupServer : backupServers) { backupServer.start(); } - for (TestableServer liveServer : liveServers) - { + for (TestableServer liveServer : liveServers) { liveServer.start(); } waitForTopology(liveServers.get(0).getServer(), liveServers.size(), liveServers.size()); sendCrashReceive(); } - protected void sendCrashReceive() throws Exception - { + protected void sendCrashReceive() throws Exception { ServerLocator[] locators = new ServerLocator[liveServers.size()]; - try - { - for (int i = 0; i < locators.length; i++) - { + try { + for (int i = 0; i < locators.length; i++) { locators[i] = getServerLocator(i); } ClientSessionFactory[] factories = new ClientSessionFactory[liveServers.size()]; - for (int i = 0; i < factories.length; i++) - { + for (int i = 0; i < factories.length; i++) { factories[i] = createSessionFactory(locators[i]); } ClientSession[] sessions = new ClientSession[liveServers.size()]; - for (int i = 0; i < factories.length; i++) - { + for (int i = 0; i < factories.length; i++) { sessions[i] = createSession(factories[i], true, true); sessions[i].createQueue(ADDRESS, ADDRESS, null, true); } //make sure bindings are ready before sending messages - for (int i = 0; i < liveServers.size(); i++) - { + for (int i = 0; i < liveServers.size(); i++) { this.waitForBindings(liveServers.get(i).getServer(), ADDRESS.toString(), true, 1, 0, 2000); this.waitForBindings(liveServers.get(i).getServer(), ADDRESS.toString(), false, 1, 0, 2000); } ClientProducer producer = sessions[0].createProducer(ADDRESS); - for (int i = 0; i < liveServers.size() * 100; i++) - { + for (int i = 0; i < liveServers.size() * 100; i++) { ClientMessage message = sessions[0].createMessage(true); setBody(i, message); @@ -102,27 +89,21 @@ public class ReplicatedMultipleServerFailoverTest extends MultipleServerFailover producer.close(); - for (TestableServer liveServer : liveServers) - { + for (TestableServer liveServer : liveServers) { waitForDistribution(ADDRESS, liveServer.getServer(), 100); } - - for (TestableServer liveServer : liveServers) - { + for (TestableServer liveServer : liveServers) { liveServer.crash(); } ClientConsumer[] consumers = new ClientConsumer[liveServers.size()]; - for (int i = 0; i < factories.length; i++) - { + for (int i = 0; i < factories.length; i++) { consumers[i] = sessions[i].createConsumer(ADDRESS); sessions[i].start(); } - for (int i = 0; i < 100; i++) - { - for (ClientConsumer consumer : consumers) - { + for (int i = 0; i < 100; i++) { + for (ClientConsumer consumer : consumers) { ClientMessage message = consumer.receive(1000); assertNotNull("expecting durable msg " + i, message); message.acknowledge(); @@ -130,18 +111,13 @@ public class ReplicatedMultipleServerFailoverTest extends MultipleServerFailover } } - finally - { - for (ServerLocator locator : locators) - { - if (locator != null) - { - try - { + finally { + for (ServerLocator locator : locators) { + if (locator != null) { + try { locator.close(); } - catch (Exception e) - { + catch (Exception e) { //ignore } } @@ -150,32 +126,27 @@ public class ReplicatedMultipleServerFailoverTest extends MultipleServerFailover } @Override - public int getLiveServerCount() - { + public int getLiveServerCount() { return 2; } @Override - public int getBackupServerCount() - { + public int getBackupServerCount() { return 2; } @Override - public boolean isNetty() - { + public boolean isNetty() { return false; } @Override - public boolean isSharedStore() - { + public boolean isSharedStore() { return false; } @Override - public String getNodeGroupName() - { + public String getNodeGroupName() { return "nodeGroup"; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedNettyAsynchronousFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedNettyAsynchronousFailoverTest.java index eadc15db8b..26fd83d0df 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedNettyAsynchronousFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedNettyAsynchronousFailoverTest.java @@ -16,12 +16,10 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.failover; -public class ReplicatedNettyAsynchronousFailoverTest extends NettyAsynchronousFailoverTest -{ +public class ReplicatedNettyAsynchronousFailoverTest extends NettyAsynchronousFailoverTest { @Override - protected void createConfigs() throws Exception - { + protected void createConfigs() throws Exception { createReplicatedConfigs(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedPagedFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedPagedFailoverTest.java index d889dd98d9..254c679a30 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedPagedFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedPagedFailoverTest.java @@ -25,20 +25,19 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.NodeManager; import org.apache.activemq.artemis.core.settings.impl.AddressSettings; -public class ReplicatedPagedFailoverTest extends ReplicatedFailoverTest -{ +public class ReplicatedPagedFailoverTest extends ReplicatedFailoverTest { + @Override - protected ActiveMQServer createInVMFailoverServer(final boolean realFiles, final Configuration configuration, - final NodeManager nodeManager, int id) - { - return createInVMFailoverServer(realFiles, configuration, PAGE_SIZE, PAGE_MAX, - new HashMap(), nodeManager, id); + protected ActiveMQServer createInVMFailoverServer(final boolean realFiles, + final Configuration configuration, + final NodeManager nodeManager, + int id) { + return createInVMFailoverServer(realFiles, configuration, PAGE_SIZE, PAGE_MAX, new HashMap(), nodeManager, id); } @Override @Test - public void testFailWithBrowser() throws Exception - { + public void testFailWithBrowser() throws Exception { // paged messages are not available for browsing } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedPagingFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedPagingFailoverTest.java index b25c7180f8..8e5f3854e7 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedPagingFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedPagingFailoverTest.java @@ -16,12 +16,10 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.failover; -public class ReplicatedPagingFailoverTest extends PagingFailoverTest -{ +public class ReplicatedPagingFailoverTest extends PagingFailoverTest { @Override - protected void createConfigs() throws Exception - { + protected void createConfigs() throws Exception { createReplicatedConfigs(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedWithDelayFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedWithDelayFailoverTest.java index a72b267a95..072f995f11 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedWithDelayFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/ReplicatedWithDelayFailoverTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.cluster.failover; + import org.apache.activemq.artemis.tests.integration.cluster.util.BackupSyncDelay; import org.junit.Before; @@ -23,15 +24,13 @@ import org.apache.activemq.artemis.api.core.client.ClientSession; /** * See {@link BackupSyncDelay} for the rationale about these 'WithDelay' tests. */ -public class ReplicatedWithDelayFailoverTest extends ReplicatedFailoverTest -{ +public class ReplicatedWithDelayFailoverTest extends ReplicatedFailoverTest { private BackupSyncDelay syncDelay; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { startBackupServer = false; super.setUp(); syncDelay = new BackupSyncDelay(backupServer, liveServer); @@ -40,21 +39,18 @@ public class ReplicatedWithDelayFailoverTest extends ReplicatedFailoverTest } @Override - protected void beforeWaitForRemoteBackupSynchronization() - { + protected void beforeWaitForRemoteBackupSynchronization() { syncDelay.deliverUpToDateMsg(); } @Override - protected void crash(ClientSession... sessions) throws Exception - { + protected void crash(ClientSession... sessions) throws Exception { syncDelay.deliverUpToDateMsg(); super.crash(sessions); } @Override - protected void crash(boolean waitFailure, ClientSession... sessions) throws Exception - { + protected void crash(boolean waitFailure, ClientSession... sessions) throws Exception { syncDelay.deliverUpToDateMsg(); waitForBackup(null, 5); super.crash(waitFailure, sessions); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/SecurityFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/SecurityFailoverTest.java index 9bf2eb5441..4653a1e69e 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/SecurityFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/SecurityFailoverTest.java @@ -29,23 +29,14 @@ import org.apache.activemq.artemis.core.server.impl.InVMNodeManager; import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManagerImpl; import org.apache.activemq.artemis.tests.integration.cluster.util.TestableServer; -public class SecurityFailoverTest extends FailoverTest -{ +public class SecurityFailoverTest extends FailoverTest { protected ClientSession createSession(ClientSessionFactory sf, boolean isXA, boolean autoCommitSends, boolean autoCommitAcks, - int ackBatchSize) throws Exception - { - ClientSession session = - sf.createSession("a", - "b", - isXA, - autoCommitSends, - autoCommitAcks, - sf.getServerLocator().isPreAcknowledge(), - ackBatchSize); + int ackBatchSize) throws Exception { + ClientSession session = sf.createSession("a", "b", isXA, autoCommitSends, autoCommitAcks, sf.getServerLocator().isPreAcknowledge(), ackBatchSize); addClientSession(session); return session; } @@ -54,24 +45,21 @@ public class SecurityFailoverTest extends FailoverTest protected ClientSession createSession(ClientSessionFactory sf, boolean autoCommitSends, boolean autoCommitAcks, - int ackBatchSize) throws Exception - { - ClientSession session = - sf.createSession("a", "b", false, autoCommitSends, autoCommitAcks, sf.getServerLocator() - .isPreAcknowledge(), ackBatchSize); + int ackBatchSize) throws Exception { + ClientSession session = sf.createSession("a", "b", false, autoCommitSends, autoCommitAcks, sf.getServerLocator().isPreAcknowledge(), ackBatchSize); addClientSession(session); return session; } @Override - protected ClientSession createSession(ClientSessionFactory sf, boolean autoCommitSends, boolean autoCommitAcks) throws Exception - { + protected ClientSession createSession(ClientSessionFactory sf, + boolean autoCommitSends, + boolean autoCommitAcks) throws Exception { return createSession(sf, autoCommitSends, autoCommitAcks, sf.getServerLocator().getAckBatchSize()); } @Override - protected ClientSession createSession(ClientSessionFactory sf) throws Exception - { + protected ClientSession createSession(ClientSessionFactory sf) throws Exception { return createSession(sf, true, true, sf.getServerLocator().getAckBatchSize()); } @@ -79,8 +67,7 @@ public class SecurityFailoverTest extends FailoverTest protected ClientSession createSession(ClientSessionFactory sf, boolean xa, boolean autoCommitSends, - boolean autoCommitAcks) throws Exception - { + boolean autoCommitAcks) throws Exception { return createSession(sf, xa, autoCommitSends, autoCommitAcks, sf.getServerLocator().getAckBatchSize()); } @@ -88,50 +75,32 @@ public class SecurityFailoverTest extends FailoverTest * @throws Exception */ @Override - protected void createConfigs() throws Exception - { + protected void createConfigs() throws Exception { nodeManager = new InVMNodeManager(false); TransportConfiguration liveConnector = getConnectorTransportConfiguration(true); TransportConfiguration backupConnector = getConnectorTransportConfiguration(false); - backupConfig = super.createDefaultInVMConfig() - .clearAcceptorConfigurations() - .addAcceptorConfiguration(getAcceptorTransportConfiguration(false)) - .setSecurityEnabled(true) - .setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration() - .setFailbackDelay(1000)) - .addConnectorConfiguration(liveConnector.getName(), liveConnector) - .addConnectorConfiguration(backupConnector.getName(), backupConnector) - .addClusterConfiguration(basicClusterConnectionConfig(backupConnector.getName(), liveConnector.getName())); + backupConfig = super.createDefaultInVMConfig().clearAcceptorConfigurations().addAcceptorConfiguration(getAcceptorTransportConfiguration(false)).setSecurityEnabled(true).setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration().setFailbackDelay(1000)).addConnectorConfiguration(liveConnector.getName(), liveConnector).addConnectorConfiguration(backupConnector.getName(), backupConnector).addClusterConfiguration(basicClusterConnectionConfig(backupConnector.getName(), liveConnector.getName())); backupServer = createTestableServer(backupConfig); ActiveMQSecurityManagerImpl securityManager = installSecurity(backupServer); securityManager.getConfiguration().setDefaultUser(null); - liveConfig = super.createDefaultInVMConfig() - .clearAcceptorConfigurations() - .addAcceptorConfiguration(getAcceptorTransportConfiguration(true)) - .setSecurityEnabled(true) - .setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration()) - .addClusterConfiguration(basicClusterConnectionConfig(liveConnector.getName())) - .addConnectorConfiguration(liveConnector.getName(), liveConnector); + liveConfig = super.createDefaultInVMConfig().clearAcceptorConfigurations().addAcceptorConfiguration(getAcceptorTransportConfiguration(true)).setSecurityEnabled(true).setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration()).addClusterConfiguration(basicClusterConnectionConfig(liveConnector.getName())).addConnectorConfiguration(liveConnector.getName(), liveConnector); liveServer = createTestableServer(liveConfig); installSecurity(liveServer); } @Override - protected void beforeRestart(TestableServer server) - { + protected void beforeRestart(TestableServer server) { installSecurity(server); } - /** * @return */ - protected ActiveMQSecurityManagerImpl installSecurity(TestableServer server) - { + protected ActiveMQSecurityManagerImpl installSecurity(TestableServer server) { ActiveMQSecurityManagerImpl securityManager = (ActiveMQSecurityManagerImpl) server.getServer().getSecurityManager(); securityManager.getConfiguration().addUser("a", "b"); Role role = new Role("arole", true, true, true, true, true, true, true); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/SharedStoreBackupTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/SharedStoreBackupTest.java index 927f1dbbb2..0b9c30fabc 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/SharedStoreBackupTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/SharedStoreBackupTest.java @@ -26,12 +26,10 @@ import org.apache.activemq.artemis.tests.util.TransportConfigurationUtils; import org.junit.Assert; import org.junit.Test; -public class SharedStoreBackupTest extends FailoverTestBase -{ +public class SharedStoreBackupTest extends FailoverTestBase { @Test - public void testStartSharedBackupWithScalingDownPolicyDisabled() throws Exception - { + public void testStartSharedBackupWithScalingDownPolicyDisabled() throws Exception { System.out.println("is backup active: " + backupServer.isActive()); liveServer.stop(); // wait max 10s for backup to activate @@ -40,65 +38,44 @@ public class SharedStoreBackupTest extends FailoverTestBase /** * Returns true if backup started in given timeout. False otherwise. + * * @param backupServer backup server - * @param waitTimeout timeout in milliseconds + * @param waitTimeout timeout in milliseconds * @return returns true if backup started in given timeout. False otherwise */ - private boolean waitForBackupToBecomeActive(TestableServer backupServer, long waitTimeout) throws Exception - { + private boolean waitForBackupToBecomeActive(TestableServer backupServer, long waitTimeout) throws Exception { long startTime = System.currentTimeMillis(); boolean isBackupStarted; // wait given timeout for backup to activate - while (!(isBackupStarted = backupServer.isActive()) && System.currentTimeMillis() - startTime < waitTimeout) - { + while (!(isBackupStarted = backupServer.isActive()) && System.currentTimeMillis() - startTime < waitTimeout) { Thread.sleep(300); } return isBackupStarted; } @Override - protected void createConfigs() throws Exception - { + protected void createConfigs() throws Exception { nodeManager = new InVMNodeManager(false); TransportConfiguration liveConnector = getConnectorTransportConfiguration(true); TransportConfiguration backupConnector = getConnectorTransportConfiguration(false); System.out.println("backup config created - mnovak"); - backupConfig = - super.createDefaultConfig(false) - .clearAcceptorConfigurations() - .addAcceptorConfiguration(getAcceptorTransportConfiguration(false)) - .setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration().setFailbackDelay(1000) - .setScaleDownConfiguration(new ScaleDownConfiguration().setEnabled(false)) - .setRestartBackup(false)) - .addConnectorConfiguration(liveConnector.getName(), liveConnector) - .addConnectorConfiguration(backupConnector.getName(), backupConnector) - .addClusterConfiguration(basicClusterConnectionConfig(backupConnector.getName(), - liveConnector.getName())); + backupConfig = super.createDefaultConfig(false).clearAcceptorConfigurations().addAcceptorConfiguration(getAcceptorTransportConfiguration(false)).setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration().setFailbackDelay(1000).setScaleDownConfiguration(new ScaleDownConfiguration().setEnabled(false)).setRestartBackup(false)).addConnectorConfiguration(liveConnector.getName(), liveConnector).addConnectorConfiguration(backupConnector.getName(), backupConnector).addClusterConfiguration(basicClusterConnectionConfig(backupConnector.getName(), liveConnector.getName())); backupServer = createTestableServer(backupConfig); - liveConfig = - super.createDefaultConfig(false) - .clearAcceptorConfigurations() - .addAcceptorConfiguration(getAcceptorTransportConfiguration(true)) - .setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration().setFailbackDelay(1000) - .setFailoverOnServerShutdown(true)) - .addClusterConfiguration(basicClusterConnectionConfig(liveConnector.getName())) - .addConnectorConfiguration(liveConnector.getName(), liveConnector); + liveConfig = super.createDefaultConfig(false).clearAcceptorConfigurations().addAcceptorConfiguration(getAcceptorTransportConfiguration(true)).setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration().setFailbackDelay(1000).setFailoverOnServerShutdown(true)).addClusterConfiguration(basicClusterConnectionConfig(liveConnector.getName())).addConnectorConfiguration(liveConnector.getName(), liveConnector); liveServer = createTestableServer(liveConfig); } @Override - protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live) - { + protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live) { return TransportConfigurationUtils.getInVMAcceptor(live); } @Override - protected TransportConfiguration getConnectorTransportConfiguration(final boolean live) - { + protected TransportConfiguration getConnectorTransportConfiguration(final boolean live) { return TransportConfigurationUtils.getInVMConnector(live); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/SharedStoreDistributionTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/SharedStoreDistributionTest.java index a200508810..ee972e9279 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/SharedStoreDistributionTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/SharedStoreDistributionTest.java @@ -16,11 +16,10 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.failover; -public class SharedStoreDistributionTest extends ReplicatedDistributionTest -{ +public class SharedStoreDistributionTest extends ReplicatedDistributionTest { + @Override - protected boolean isSharedStore() - { + protected boolean isSharedStore() { return true; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/SingleLiveMultipleBackupsFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/SingleLiveMultipleBackupsFailoverTest.java index 3baf73ce29..066da1690b 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/SingleLiveMultipleBackupsFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/SingleLiveMultipleBackupsFailoverTest.java @@ -37,8 +37,7 @@ import java.util.Map; /** */ -public class SingleLiveMultipleBackupsFailoverTest extends MultipleBackupsFailoverTestBase -{ +public class SingleLiveMultipleBackupsFailoverTest extends MultipleBackupsFailoverTestBase { protected Map servers = new HashMap(); protected ServerLocatorImpl locator; @@ -46,10 +45,8 @@ public class SingleLiveMultipleBackupsFailoverTest extends MultipleBackupsFailov final boolean sharedStore = true; IntegrationTestLogger log = IntegrationTestLogger.LOGGER; - public void _testLoop() throws Exception - { - for (int i = 0; i < 100; i++) - { + public void _testLoop() throws Exception { + for (int i = 0; i < 100; i++) { log.info("#test " + i); testMultipleFailovers(); tearDown(); @@ -58,8 +55,7 @@ public class SingleLiveMultipleBackupsFailoverTest extends MultipleBackupsFailov } @Test - public void testMultipleFailovers() throws Exception - { + public void testMultipleFailovers() throws Exception { nodeManager = new InVMNodeManager(!sharedStore); createLiveConfig(0); createBackupConfig(0, 1, 0, 2, 3, 4, 5); @@ -84,10 +80,7 @@ public class SingleLiveMultipleBackupsFailoverTest extends MultipleBackupsFailov // for logging and debugging topology.setOwner("testMultipleFailovers"); - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true) - .setReconnectAttempts(-1); + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true).setReconnectAttempts(-1); ClientSessionFactoryInternal sf = createSessionFactoryAndWaitForTopology(locator, 2); int backupNode; @@ -129,23 +122,13 @@ public class SingleLiveMultipleBackupsFailoverTest extends MultipleBackupsFailov locator.close(); } - protected void createBackupConfig(int liveNode, int nodeid, int... nodes) throws Exception - { + protected void createBackupConfig(int liveNode, int nodeid, int... nodes) throws Exception { TransportConfiguration backupConnector = createTransportConfiguration(isNetty(), false, generateParams(nodeid, isNetty())); - Configuration config1 = super.createDefaultInVMConfig() - .clearAcceptorConfigurations() - .addAcceptorConfiguration(createTransportConfiguration(isNetty(), true, generateParams(nodeid, isNetty()))) - .setHAPolicyConfiguration(sharedStore ? new SharedStoreSlavePolicyConfiguration() : new ReplicatedPolicyConfiguration()) - .addConnectorConfiguration(backupConnector.getName(), backupConnector) - .setBindingsDirectory(getBindingsDir() + "_" + liveNode) - .setJournalDirectory(getJournalDir() + "_" + liveNode) - .setPagingDirectory(getPageDir() + "_" + liveNode) - .setLargeMessagesDirectory(getLargeMessagesDir() + "_" + liveNode); + Configuration config1 = super.createDefaultInVMConfig().clearAcceptorConfigurations().addAcceptorConfiguration(createTransportConfiguration(isNetty(), true, generateParams(nodeid, isNetty()))).setHAPolicyConfiguration(sharedStore ? new SharedStoreSlavePolicyConfiguration() : new ReplicatedPolicyConfiguration()).addConnectorConfiguration(backupConnector.getName(), backupConnector).setBindingsDirectory(getBindingsDir() + "_" + liveNode).setJournalDirectory(getJournalDir() + "_" + liveNode).setPagingDirectory(getPageDir() + "_" + liveNode).setLargeMessagesDirectory(getLargeMessagesDir() + "_" + liveNode); String[] staticConnectors = new String[nodes.length]; - for (int i = 0; i < nodes.length; i++) - { + for (int i = 0; i < nodes.length; i++) { TransportConfiguration liveConnector = createTransportConfiguration(isNetty(), false, generateParams(nodes[i], isNetty())); config1.addConnectorConfiguration(liveConnector.getName(), liveConnector); staticConnectors[i] = liveConnector.getName(); @@ -155,20 +138,10 @@ public class SingleLiveMultipleBackupsFailoverTest extends MultipleBackupsFailov servers.put(nodeid, new SameProcessActiveMQServer(createInVMFailoverServer(true, config1, nodeManager, nodeid))); } - protected void createLiveConfig(int liveNode) throws Exception - { + protected void createLiveConfig(int liveNode) throws Exception { TransportConfiguration liveConnector = createTransportConfiguration(isNetty(), false, generateParams(liveNode, isNetty())); - Configuration config0 = super.createDefaultInVMConfig() - .clearAcceptorConfigurations() - .addAcceptorConfiguration(createTransportConfiguration(isNetty(), true, generateParams(liveNode, isNetty()))) - .setHAPolicyConfiguration(sharedStore ? new SharedStoreMasterPolicyConfiguration() : new ReplicatedPolicyConfiguration()) - .addClusterConfiguration(basicClusterConnectionConfig(liveConnector.getName())) - .addConnectorConfiguration(liveConnector.getName(), liveConnector) - .setBindingsDirectory(getBindingsDir() + "_" + liveNode) - .setJournalDirectory(getJournalDir() + "_" + liveNode) - .setPagingDirectory(getPageDir() + "_" + liveNode) - .setLargeMessagesDirectory(getLargeMessagesDir() + "_" + liveNode); + Configuration config0 = super.createDefaultInVMConfig().clearAcceptorConfigurations().addAcceptorConfiguration(createTransportConfiguration(isNetty(), true, generateParams(liveNode, isNetty()))).setHAPolicyConfiguration(sharedStore ? new SharedStoreMasterPolicyConfiguration() : new ReplicatedPolicyConfiguration()).addClusterConfiguration(basicClusterConnectionConfig(liveConnector.getName())).addConnectorConfiguration(liveConnector.getName(), liveConnector).setBindingsDirectory(getBindingsDir() + "_" + liveNode).setJournalDirectory(getJournalDir() + "_" + liveNode).setPagingDirectory(getPageDir() + "_" + liveNode).setLargeMessagesDirectory(getLargeMessagesDir() + "_" + liveNode); SameProcessActiveMQServer server = new SameProcessActiveMQServer(createInVMFailoverServer(true, config0, nodeManager, liveNode)); addActiveMQComponent(server); @@ -176,8 +149,7 @@ public class SingleLiveMultipleBackupsFailoverTest extends MultipleBackupsFailov } @Override - protected boolean isNetty() - { + protected boolean isNetty() { return false; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/StaticClusterWithBackupFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/StaticClusterWithBackupFailoverTest.java index 5555f7e88e..fa39efd2ac 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/StaticClusterWithBackupFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/StaticClusterWithBackupFailoverTest.java @@ -18,69 +18,29 @@ package org.apache.activemq.artemis.tests.integration.cluster.failover; import org.apache.activemq.artemis.core.server.cluster.impl.MessageLoadBalancingType; -public class StaticClusterWithBackupFailoverTest extends ClusterWithBackupFailoverTestBase -{ +public class StaticClusterWithBackupFailoverTest extends ClusterWithBackupFailoverTestBase { @Override - protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception - { - setupClusterConnectionWithBackups("cluster0", - "queues", - messageLoadBalancingType, - 1, - isNetty(), - 0, - new int[]{1, 2}); + protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception { + setupClusterConnectionWithBackups("cluster0", "queues", messageLoadBalancingType, 1, isNetty(), 0, new int[]{1, 2}); - setupClusterConnectionWithBackups("cluster1", - "queues", - messageLoadBalancingType, - 1, - isNetty(), - 1, - new int[]{0, 2}); + setupClusterConnectionWithBackups("cluster1", "queues", messageLoadBalancingType, 1, isNetty(), 1, new int[]{0, 2}); - setupClusterConnectionWithBackups("cluster2", - "queues", - messageLoadBalancingType, - 1, - isNetty(), - 2, - new int[]{0, 1}); + setupClusterConnectionWithBackups("cluster2", "queues", messageLoadBalancingType, 1, isNetty(), 2, new int[]{0, 1}); - setupClusterConnectionWithBackups("cluster0", - "queues", - messageLoadBalancingType, - 1, - isNetty(), - 3, - new int[]{1, 2}); + setupClusterConnectionWithBackups("cluster0", "queues", messageLoadBalancingType, 1, isNetty(), 3, new int[]{1, 2}); - setupClusterConnectionWithBackups("cluster1", - "queues", - messageLoadBalancingType, - 1, - isNetty(), - 4, - new int[]{0, 2}); + setupClusterConnectionWithBackups("cluster1", "queues", messageLoadBalancingType, 1, isNetty(), 4, new int[]{0, 2}); - setupClusterConnectionWithBackups("cluster2", - "queues", - messageLoadBalancingType, - 1, - isNetty(), - 5, - new int[]{0, 1}); + setupClusterConnectionWithBackups("cluster2", "queues", messageLoadBalancingType, 1, isNetty(), 5, new int[]{0, 1}); } - protected boolean isSharedStorage() - { + protected boolean isSharedStorage() { return true; } @Override - protected void setupServers() throws Exception - { + protected void setupServers() throws Exception { // The backups setupBackupServer(3, 0, isFileStorage(), isSharedStorage(), isNetty()); setupBackupServer(4, 1, isFileStorage(), isSharedStorage(), isNetty()); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/remote/FailoverWithSharedStoreTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/remote/FailoverWithSharedStoreTest.java index ebdada850a..b9d22959bc 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/remote/FailoverWithSharedStoreTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/remote/FailoverWithSharedStoreTest.java @@ -25,24 +25,19 @@ import org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnectorFactor import org.apache.activemq.artemis.tests.integration.cluster.distribution.ClusterTestBase; import org.junit.Test; -public class FailoverWithSharedStoreTest extends ClusterTestBase -{ +public class FailoverWithSharedStoreTest extends ClusterTestBase { @Test - public void testNoConnection() throws Exception - { + public void testNoConnection() throws Exception { ServerLocator locator = ActiveMQClient.createServerLocatorWithHA(new TransportConfiguration(NettyConnectorFactory.class.getName())); - try - { + try { createSessionFactory(locator); fail(); } - catch (ActiveMQNotConnectedException nce) - { + catch (ActiveMQNotConnectedException nce) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/ha/HAAutomaticBackupSharedStore.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/ha/HAAutomaticBackupSharedStore.java index 6aa9effabd..8e82c2d635 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/ha/HAAutomaticBackupSharedStore.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/ha/HAAutomaticBackupSharedStore.java @@ -26,12 +26,10 @@ import org.apache.activemq.artemis.tests.integration.cluster.distribution.Cluste import org.junit.Before; import org.junit.Test; +public class HAAutomaticBackupSharedStore extends ClusterTestBase { -public class HAAutomaticBackupSharedStore extends ClusterTestBase -{ @Before - public void setup() throws Exception - { + public void setup() throws Exception { super.setUp(); setupServers(); @@ -48,8 +46,7 @@ public class HAAutomaticBackupSharedStore extends ClusterTestBase } @Test - public void basicDiscovery() throws Exception - { + public void basicDiscovery() throws Exception { startServers(0, 1, 2, 3, 4, 5); createQueue(3, "queues.testaddress", "queue0", null, false); @@ -58,8 +55,7 @@ public class HAAutomaticBackupSharedStore extends ClusterTestBase } - protected void setupServers() throws Exception - { + protected void setupServers() throws Exception { // The lives setupLiveServer(0, isFileStorage(), true, isNetty(), false); setupLiveServer(1, isFileStorage(), true, isNetty(), false); @@ -67,8 +63,7 @@ public class HAAutomaticBackupSharedStore extends ClusterTestBase } - private void setUpHAPolicy(int node) - { + private void setUpHAPolicy(int node) { ActiveMQServer server = getServer(node); ColocatedPolicyConfiguration haPolicyConfiguration = new ColocatedPolicyConfiguration(); HAPolicyConfiguration liveConfiguration = new SharedStoreMasterPolicyConfiguration(); @@ -79,8 +74,7 @@ public class HAAutomaticBackupSharedStore extends ClusterTestBase server.getConfiguration().setHAPolicyConfiguration(haPolicyConfiguration); } - public boolean isNetty() - { + public boolean isNetty() { return true; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/MultiThreadRandomReattachTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/MultiThreadRandomReattachTest.java index 32ac0d2ddf..31fe17e0a1 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/MultiThreadRandomReattachTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/MultiThreadRandomReattachTest.java @@ -20,14 +20,12 @@ import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.apache.activemq.artemis.core.config.Configuration; /** - * * A MultiThreadRandomReattachTest */ -public class MultiThreadRandomReattachTest extends MultiThreadRandomReattachTestBase -{ +public class MultiThreadRandomReattachTest extends MultiThreadRandomReattachTestBase { + @Override - protected void start() throws Exception - { + protected void start() throws Exception { Configuration liveConf = createDefaultInVMConfig(); server = createServer(false, liveConf); server.start(); @@ -35,15 +33,13 @@ public class MultiThreadRandomReattachTest extends MultiThreadRandomReattachTest } @Override - protected void setBody(final ClientMessage message) throws Exception - { + protected void setBody(final ClientMessage message) throws Exception { // Give each msg a body message.getBodyBuffer().writeBytes(new byte[250]); } @Override - protected boolean checkSize(final ClientMessage message) - { + protected boolean checkSize(final ClientMessage message) { return message.getBodyBuffer().readableBytes() == 250; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/MultiThreadRandomReattachTestBase.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/MultiThreadRandomReattachTestBase.java index e6686689fc..365bd6039a 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/MultiThreadRandomReattachTestBase.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/MultiThreadRandomReattachTestBase.java @@ -42,8 +42,8 @@ import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReattachSupportTestBase -{ +public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReattachSupportTestBase { + private final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; // Constants ----------------------------------------------------- @@ -66,13 +66,10 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt // Public -------------------------------------------------------- @Test - public void testA() throws Exception - { - runTestMultipleThreads(new RunnableT() - { + public void testA() throws Exception { + runTestMultipleThreads(new RunnableT() { @Override - public void run(final ClientSessionFactory sf, final int threadNum) throws Exception - { + public void run(final ClientSessionFactory sf, final int threadNum) throws Exception { doTestA(sf, threadNum); } }, NUM_THREADS, false); @@ -80,143 +77,110 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt } @Test - public void testB() throws Exception - { - runTestMultipleThreads(new RunnableT() - { + public void testB() throws Exception { + runTestMultipleThreads(new RunnableT() { @Override - public void run(final ClientSessionFactory sf, final int threadNum) throws Exception - { + public void run(final ClientSessionFactory sf, final int threadNum) throws Exception { doTestB(sf, threadNum); } }, NUM_THREADS, false); } @Test - public void testC() throws Exception - { - runTestMultipleThreads(new RunnableT() - { + public void testC() throws Exception { + runTestMultipleThreads(new RunnableT() { @Override - public void run(final ClientSessionFactory sf, final int threadNum) throws Exception - { + public void run(final ClientSessionFactory sf, final int threadNum) throws Exception { doTestC(sf, threadNum); } }, NUM_THREADS, false); } @Test - public void testD() throws Exception - { - runTestMultipleThreads(new RunnableT() - { + public void testD() throws Exception { + runTestMultipleThreads(new RunnableT() { @Override - public void run(final ClientSessionFactory sf, final int threadNum) throws Exception - { + public void run(final ClientSessionFactory sf, final int threadNum) throws Exception { doTestD(sf, threadNum); } }, NUM_THREADS, false); } @Test - public void testE() throws Exception - { - runTestMultipleThreads(new RunnableT() - { + public void testE() throws Exception { + runTestMultipleThreads(new RunnableT() { @Override - public void run(final ClientSessionFactory sf, final int threadNum) throws Exception - { + public void run(final ClientSessionFactory sf, final int threadNum) throws Exception { doTestE(sf, threadNum); } }, NUM_THREADS, false); } @Test - public void testF() throws Exception - { - runTestMultipleThreads(new RunnableT() - { + public void testF() throws Exception { + runTestMultipleThreads(new RunnableT() { @Override - public void run(final ClientSessionFactory sf, final int threadNum) throws Exception - { + public void run(final ClientSessionFactory sf, final int threadNum) throws Exception { doTestF(sf, threadNum); } }, NUM_THREADS, false); } @Test - public void testG() throws Exception - { - runTestMultipleThreads(new RunnableT() - { + public void testG() throws Exception { + runTestMultipleThreads(new RunnableT() { @Override - public void run(final ClientSessionFactory sf, final int threadNum) throws Exception - { + public void run(final ClientSessionFactory sf, final int threadNum) throws Exception { doTestG(sf, threadNum); } }, NUM_THREADS, false); } @Test - public void testH() throws Exception - { - runTestMultipleThreads(new RunnableT() - { + public void testH() throws Exception { + runTestMultipleThreads(new RunnableT() { @Override - public void run(final ClientSessionFactory sf, final int threadNum) throws Exception - { + public void run(final ClientSessionFactory sf, final int threadNum) throws Exception { doTestH(sf, threadNum); } }, NUM_THREADS, false); } @Test - public void testI() throws Exception - { - runTestMultipleThreads(new RunnableT() - { + public void testI() throws Exception { + runTestMultipleThreads(new RunnableT() { @Override - public void run(final ClientSessionFactory sf, final int threadNum) throws Exception - { + public void run(final ClientSessionFactory sf, final int threadNum) throws Exception { doTestI(sf, threadNum); } }, NUM_THREADS, false); } @Test - public void testJ() throws Exception - { - runTestMultipleThreads(new RunnableT() - { + public void testJ() throws Exception { + runTestMultipleThreads(new RunnableT() { @Override - public void run(final ClientSessionFactory sf, final int threadNum) throws Exception - { + public void run(final ClientSessionFactory sf, final int threadNum) throws Exception { doTestJ(sf, threadNum); } }, NUM_THREADS, false); } @Test - public void testK() throws Exception - { - runTestMultipleThreads(new RunnableT() - { + public void testK() throws Exception { + runTestMultipleThreads(new RunnableT() { @Override - public void run(final ClientSessionFactory sf, final int threadNum) throws Exception - { + public void run(final ClientSessionFactory sf, final int threadNum) throws Exception { doTestK(sf, threadNum); } }, NUM_THREADS, false); } @Test - public void testL() throws Exception - { - runTestMultipleThreads(new RunnableT() - { + public void testL() throws Exception { + runTestMultipleThreads(new RunnableT() { @Override - public void run(final ClientSessionFactory sf, final int threadNum) throws Exception - { + public void run(final ClientSessionFactory sf, final int threadNum) throws Exception { doTestL(sf); } }, NUM_THREADS, true, 10); @@ -234,13 +198,10 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt // } @Test - public void testN() throws Exception - { - runTestMultipleThreads(new RunnableT() - { + public void testN() throws Exception { + runTestMultipleThreads(new RunnableT() { @Override - public void run(final ClientSessionFactory sf, final int threadNum) throws Exception - { + public void run(final ClientSessionFactory sf, final int threadNum) throws Exception { doTestN(sf, threadNum); } }, NUM_THREADS, false); @@ -248,13 +209,10 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt // Added do replicate HORNETQ-264 @Test - public void testO() throws Exception - { - runTestMultipleThreads(new RunnableT() - { + public void testO() throws Exception { + runTestMultipleThreads(new RunnableT() { @Override - public void run(final ClientSessionFactory sf, final int threadNum) throws Exception - { + public void run(final ClientSessionFactory sf, final int threadNum) throws Exception { doTestO(sf, threadNum); } }, NUM_THREADS, false); @@ -271,16 +229,14 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt protected abstract boolean checkSize(ClientMessage message); - protected ClientSession createAutoCommitSession(final ClientSessionFactory sf) throws Exception - { + protected ClientSession createAutoCommitSession(final ClientSessionFactory sf) throws Exception { ClientSession session = sf.createSession(false, true, true); session.addMetaData("someData", RandomUtil.randomString()); session.addMetaData("someData2", RandomUtil.randomString()); return session; } - protected ClientSession createTransactionalSession(final ClientSessionFactory sf) throws Exception - { + protected ClientSession createTransactionalSession(final ClientSessionFactory sf) throws Exception { ClientSession session = sf.createSession(false, false, false); session.addMetaData("someData", RandomUtil.randomString()); session.addMetaData("someData2", RandomUtil.randomString()); @@ -288,8 +244,9 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt return session; } - protected void doTestA(final ClientSessionFactory sf, final int threadNum, final ClientSession session2) throws Exception - { + protected void doTestA(final ClientSessionFactory sf, + final int threadNum, + final ClientSession session2) throws Exception { SimpleString subName = new SimpleString("sub" + threadNum); ClientSession session = addClientSession(sf.createSession(false, true, true)); @@ -312,15 +269,13 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt boolean ok = handler.latch.await(LATCH_WAIT, TimeUnit.MILLISECONDS); - if (!ok) - { + if (!ok) { throw new Exception("Timed out waiting for messages on handler " + System.identityHashCode(handler) + - " threadnum " + - threadNum); + " threadnum " + + threadNum); } - if (handler.failure != null) - { + if (handler.failure != null) { throw new Exception("Handler failed: " + handler.failure); } @@ -333,8 +288,7 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt session.close(); } - protected void doTestA(final ClientSessionFactory sf, final int threadNum) throws Exception - { + protected void doTestA(final ClientSessionFactory sf, final int threadNum) throws Exception { long start = System.currentTimeMillis(); ClientSession s = sf.createSession(false, false, false); @@ -346,8 +300,7 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt Set consumers = new HashSet(); Set sessions = new HashSet(); - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString(threadNum + "sub" + i); ClientSession sessConsume = createAutoCommitSession(sf); @@ -372,8 +325,7 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt Set handlers = new HashSet(); - for (ClientConsumer consumer : consumers) - { + for (ClientConsumer consumer : consumers) { MyHandler handler = new MyHandler(threadNum, numMessages); consumer.setMessageHandler(handler); @@ -381,32 +333,27 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt handlers.add(handler); } - for (MyHandler handler : handlers) - { + for (MyHandler handler : handlers) { boolean ok = handler.latch.await(LATCH_WAIT, TimeUnit.MILLISECONDS); - if (!ok) - { + if (!ok) { throw new Exception("Timed out waiting for messages on handler " + System.identityHashCode(handler) + - " threadnum " + - threadNum); + " threadnum " + + threadNum); } - if (handler.failure != null) - { + if (handler.failure != null) { throw new Exception("Handler failed: " + handler.failure); } } sessSend.close(); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.close(); } - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString(threadNum + "sub" + i); s.deleteQueue(subName); @@ -419,8 +366,7 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt log.info("duration " + (end - start)); } - protected void doTestB(final ClientSessionFactory sf, final int threadNum) throws Exception - { + protected void doTestB(final ClientSessionFactory sf, final int threadNum) throws Exception { long start = System.currentTimeMillis(); ClientSession s = sf.createSession(false, false, false); @@ -432,8 +378,7 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt Set consumers = new HashSet(); Set sessions = new HashSet(); - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString(threadNum + "sub" + i); ClientSession sessConsume = createAutoCommitSession(sf); @@ -454,15 +399,13 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt sendMessages(sessSend, producer, numMessages, threadNum); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.start(); } Set handlers = new HashSet(); - for (ClientConsumer consumer : consumers) - { + for (ClientConsumer consumer : consumers) { MyHandler handler = new MyHandler(threadNum, numMessages); consumer.setMessageHandler(handler); @@ -470,32 +413,27 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt handlers.add(handler); } - for (MyHandler handler : handlers) - { + for (MyHandler handler : handlers) { boolean ok = handler.latch.await(LATCH_WAIT, TimeUnit.MILLISECONDS); - if (!ok) - { + if (!ok) { throw new Exception("Timed out waiting for messages on handler " + System.identityHashCode(handler) + - " threadnum " + - threadNum); + " threadnum " + + threadNum); } - if (handler.failure != null) - { + if (handler.failure != null) { throw new Exception("Handler failed: " + handler.failure); } } sessSend.close(); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.close(); } - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString(threadNum + "sub" + i); s.deleteQueue(subName); @@ -509,14 +447,12 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt } - protected void doTestC(final ClientSessionFactory sf, final int threadNum) throws Exception - { + protected void doTestC(final ClientSessionFactory sf, final int threadNum) throws Exception { long start = System.currentTimeMillis(); ClientSession s = sf.createSession(false, false, false); s.addMetaData("some-data", RandomUtil.randomString()); - final int numMessages = 100; final int numSessions = 10; @@ -524,8 +460,7 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt Set consumers = new HashSet(); Set sessions = new HashSet(); - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString(threadNum + "sub" + i); ClientSession sessConsume = createTransactionalSession(sf); @@ -544,7 +479,6 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt ClientSession sessSend = sf.createSession(false, false, false); sessSend.addMetaData("some-data", RandomUtil.randomString()); - ClientProducer producer = sessSend.createProducer(MultiThreadRandomReattachTestBase.ADDRESS); sendMessages(sessSend, producer, numMessages, threadNum); @@ -557,8 +491,7 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt Set handlers = new HashSet(); - for (ClientConsumer consumer : consumers) - { + for (ClientConsumer consumer : consumers) { MyHandler handler = new MyHandler(threadNum, numMessages); consumer.setMessageHandler(handler); @@ -566,50 +499,42 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt handlers.add(handler); } - for (MyHandler handler : handlers) - { + for (MyHandler handler : handlers) { boolean ok = handler.latch.await(LATCH_WAIT, TimeUnit.MILLISECONDS); - if (!ok) - { + if (!ok) { throw new Exception("Timed out waiting for messages on handler " + System.identityHashCode(handler) + - " threadnum " + - threadNum); + " threadnum " + + threadNum); } - if (handler.failure != null) - { + if (handler.failure != null) { throw new Exception("Handler failed: " + handler.failure); } handler.reset(); } - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.rollback(); } - for (MyHandler handler : handlers) - { + for (MyHandler handler : handlers) { boolean ok = handler.latch.await(LATCH_WAIT, TimeUnit.MILLISECONDS); Assert.assertTrue(ok); } - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.commit(); } sessSend.close(); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.close(); } - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString(threadNum + "sub" + i); s.deleteQueue(subName); @@ -622,14 +547,12 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt log.info("duration " + (end - start)); } - protected void doTestD(final ClientSessionFactory sf, final int threadNum) throws Exception - { + protected void doTestD(final ClientSessionFactory sf, final int threadNum) throws Exception { long start = System.currentTimeMillis(); ClientSession s = sf.createSession(false, false, false); s.addMetaData("some-data", RandomUtil.randomString()); - final int numMessages = 100; final int numSessions = 10; @@ -637,8 +560,7 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt Set consumers = new HashSet(); Set sessions = new HashSet(); - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString(threadNum + " sub" + i); ClientSession sessConsume = sf.createSession(false, false, false); @@ -656,7 +578,6 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt ClientSession sessSend = sf.createSession(false, false, false); sessSend.addMetaData("some-data", RandomUtil.randomString()); - ClientProducer producer = sessSend.createProducer(MultiThreadRandomReattachTestBase.ADDRESS); sendMessages(sessSend, producer, numMessages, threadNum); @@ -667,15 +588,13 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt sessSend.commit(); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.start(); } Set handlers = new HashSet(); - for (ClientConsumer consumer : consumers) - { + for (ClientConsumer consumer : consumers) { MyHandler handler = new MyHandler(threadNum, numMessages); consumer.setMessageHandler(handler); @@ -683,19 +602,16 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt handlers.add(handler); } - for (MyHandler handler : handlers) - { + for (MyHandler handler : handlers) { boolean ok = handler.latch.await(LATCH_WAIT, TimeUnit.MILLISECONDS); - if (!ok) - { + if (!ok) { throw new Exception("Timed out waiting for messages on handler " + System.identityHashCode(handler) + - " threadnum " + - threadNum); + " threadnum " + + threadNum); } - if (handler.failure != null) - { + if (handler.failure != null) { throw new Exception("Handler failed: " + handler.failure); } } @@ -703,19 +619,16 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt handlers.clear(); // Set handlers to null - for (ClientConsumer consumer : consumers) - { + for (ClientConsumer consumer : consumers) { consumer.setMessageHandler(null); } - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.rollback(); } // New handlers - for (ClientConsumer consumer : consumers) - { + for (ClientConsumer consumer : consumers) { MyHandler handler = new MyHandler(threadNum, numMessages); consumer.setMessageHandler(handler); @@ -723,36 +636,30 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt handlers.add(handler); } - for (MyHandler handler : handlers) - { + for (MyHandler handler : handlers) { boolean ok = handler.latch.await(LATCH_WAIT, TimeUnit.MILLISECONDS); - if (!ok) - { + if (!ok) { throw new Exception("Timed out waiting for messages on handler " + System.identityHashCode(handler) + - " threadnum " + - threadNum); + " threadnum " + + threadNum); } - if (handler.failure != null) - { + if (handler.failure != null) { throw new Exception("Handler failed on rollback: " + handler.failure); } } - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.commit(); } sessSend.close(); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.close(); } - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString(threadNum + " sub" + i); s.deleteQueue(subName); @@ -767,14 +674,12 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt // Now with synchronous receive() - protected void doTestE(final ClientSessionFactory sf, final int threadNum) throws Exception - { + protected void doTestE(final ClientSessionFactory sf, final int threadNum) throws Exception { long start = System.currentTimeMillis(); ClientSession s = sf.createSession(false, false, false); s.addMetaData("some-data", RandomUtil.randomString()); - final int numMessages = 100; final int numSessions = 10; @@ -782,14 +687,12 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt Set consumers = new HashSet(); Set sessions = new HashSet(); - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString(threadNum + "sub" + i); ClientSession sessConsume = sf.createSession(false, true, true); sessConsume.addMetaData("some-data", RandomUtil.randomString()); - sessConsume.start(); sessConsume.createQueue(MultiThreadRandomReattachTestBase.ADDRESS, subName, null, false); @@ -811,13 +714,11 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt consumeMessages(consumers, numMessages, threadNum); sessSend.close(); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.close(); } - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString(threadNum + "sub" + i); s.deleteQueue(subName); @@ -830,14 +731,12 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt log.info("duration " + (end - start)); } - protected void doTestF(final ClientSessionFactory sf, final int threadNum) throws Exception - { + protected void doTestF(final ClientSessionFactory sf, final int threadNum) throws Exception { long start = System.currentTimeMillis(); ClientSession s = sf.createSession(false, false, false); s.addMetaData("data", RandomUtil.randomString()); - final int numMessages = 100; final int numSessions = 10; @@ -845,8 +744,7 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt Set consumers = new HashSet(); Set sessions = new HashSet(); - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString(threadNum + "sub" + i); ClientSession sessConsume = sf.createSession(false, true, true); @@ -868,21 +766,18 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt sendMessages(sessSend, producer, numMessages, threadNum); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.start(); } consumeMessages(consumers, numMessages, threadNum); sessSend.close(); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.close(); } - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString(threadNum + "sub" + i); s.deleteQueue(subName); @@ -895,8 +790,7 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt log.info("duration " + (end - start)); } - protected void doTestG(final ClientSessionFactory sf, final int threadNum) throws Exception - { + protected void doTestG(final ClientSessionFactory sf, final int threadNum) throws Exception { long start = System.currentTimeMillis(); ClientSession s = sf.createSession(false, false, false); @@ -909,14 +803,12 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt Set consumers = new HashSet(); Set sessions = new HashSet(); - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString(threadNum + "sub" + i); ClientSession sessConsume = sf.createSession(false, false, false); sessConsume.addMetaData("data", RandomUtil.randomString()); - sessConsume.start(); sessConsume.createQueue(MultiThreadRandomReattachTestBase.ADDRESS, subName, null, false); @@ -931,7 +823,6 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt ClientSession sessSend = sf.createSession(false, false, false); sessSend.addMetaData("data", RandomUtil.randomString()); - ClientProducer producer = sessSend.createProducer(MultiThreadRandomReattachTestBase.ADDRESS); sendMessages(sessSend, producer, numMessages, threadNum); @@ -944,26 +835,22 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt consumeMessages(consumers, numMessages, threadNum); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.rollback(); } consumeMessages(consumers, numMessages, threadNum); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.commit(); } sessSend.close(); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.close(); } - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString(threadNum + "sub" + i); s.deleteQueue(subName); @@ -976,14 +863,12 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt log.info("duration " + (end - start)); } - protected void doTestH(final ClientSessionFactory sf, final int threadNum) throws Exception - { + protected void doTestH(final ClientSessionFactory sf, final int threadNum) throws Exception { long start = System.currentTimeMillis(); ClientSession s = sf.createSession(false, false, false); s.addMetaData("data", RandomUtil.randomString()); - final int numMessages = 100; final int numSessions = 10; @@ -991,14 +876,12 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt Set consumers = new HashSet(); Set sessions = new HashSet(); - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString(threadNum + "sub" + i); ClientSession sessConsume = sf.createSession(false, false, false); sessConsume.addMetaData("data", RandomUtil.randomString()); - sessConsume.createQueue(MultiThreadRandomReattachTestBase.ADDRESS, subName, null, false); ClientConsumer consumer = sessConsume.createConsumer(subName); @@ -1021,33 +904,28 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt sessSend.commit(); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.start(); } consumeMessages(consumers, numMessages, threadNum); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.rollback(); } consumeMessages(consumers, numMessages, threadNum); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.commit(); } sessSend.close(); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.close(); } - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString(threadNum + "sub" + i); s.deleteQueue(subName); @@ -1060,28 +938,22 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt log.info("duration " + (end - start)); } - protected void doTestI(final ClientSessionFactory sf, final int threadNum) throws Exception - { + protected void doTestI(final ClientSessionFactory sf, final int threadNum) throws Exception { ClientSession sessCreate = sf.createSession(false, true, true); sessCreate.addMetaData("data", RandomUtil.randomString()); - - sessCreate.createQueue(MultiThreadRandomReattachTestBase.ADDRESS, - new SimpleString(threadNum + MultiThreadRandomReattachTestBase.ADDRESS.toString()), - null, - false); + sessCreate.createQueue(MultiThreadRandomReattachTestBase.ADDRESS, new SimpleString(threadNum + MultiThreadRandomReattachTestBase.ADDRESS.toString()), null, false); ClientSession sess = sf.createSession(false, true, true); sess.addMetaData("data", RandomUtil.randomString()); - sess.start(); ClientConsumer consumer = sess.createConsumer(new SimpleString(threadNum + MultiThreadRandomReattachTestBase.ADDRESS.toString())); ClientProducer producer = sess.createProducer(MultiThreadRandomReattachTestBase.ADDRESS); - ClientMessage message = sess.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte)1); + ClientMessage message = sess.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); producer.send(message); ClientMessage message2 = consumer.receive(MultiThreadRandomReattachTestBase.RECEIVE_TIMEOUT); @@ -1097,16 +969,11 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt sessCreate.close(); } - protected void doTestJ(final ClientSessionFactory sf, final int threadNum) throws Exception - { + protected void doTestJ(final ClientSessionFactory sf, final int threadNum) throws Exception { ClientSession sessCreate = sf.createSession(false, true, true); sessCreate.addMetaData("data", RandomUtil.randomString()); - - sessCreate.createQueue(MultiThreadRandomReattachTestBase.ADDRESS, - new SimpleString(threadNum + MultiThreadRandomReattachTestBase.ADDRESS.toString()), - null, - false); + sessCreate.createQueue(MultiThreadRandomReattachTestBase.ADDRESS, new SimpleString(threadNum + MultiThreadRandomReattachTestBase.ADDRESS.toString()), null, false); ClientSession sess = sf.createSession(false, true, true); sess.addMetaData("data", RandomUtil.randomString()); @@ -1117,7 +984,7 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt ClientProducer producer = sess.createProducer(MultiThreadRandomReattachTestBase.ADDRESS); - ClientMessage message = sess.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte)1); + ClientMessage message = sess.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); producer.send(message); ClientMessage message2 = consumer.receive(MultiThreadRandomReattachTestBase.RECEIVE_TIMEOUT); @@ -1133,20 +1000,15 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt sessCreate.close(); } - protected void doTestK(final ClientSessionFactory sf, final int threadNum) throws Exception - { + protected void doTestK(final ClientSessionFactory sf, final int threadNum) throws Exception { ClientSession s = sf.createSession(false, false, false); s.addMetaData("data", RandomUtil.randomString()); - s.createQueue(MultiThreadRandomReattachTestBase.ADDRESS, - new SimpleString(threadNum + MultiThreadRandomReattachTestBase.ADDRESS.toString()), - null, - false); + s.createQueue(MultiThreadRandomReattachTestBase.ADDRESS, new SimpleString(threadNum + MultiThreadRandomReattachTestBase.ADDRESS.toString()), null, false); final int numConsumers = 100; - for (int i = 0; i < numConsumers; i++) - { + for (int i = 0; i < numConsumers; i++) { ClientConsumer consumer = s.createConsumer(new SimpleString(threadNum + MultiThreadRandomReattachTestBase.ADDRESS.toString())); consumer.close(); @@ -1160,12 +1022,10 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt /* * This test tests failure during create connection */ - protected void doTestL(final ClientSessionFactory sf) throws Exception - { + protected void doTestL(final ClientSessionFactory sf) throws Exception { final int numSessions = 100; - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { ClientSession session = sf.createSession(false, false, false); session.addMetaData("data", RandomUtil.randomString()); @@ -1174,14 +1034,10 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt } } - protected void doTestN(final ClientSessionFactory sf, final int threadNum) throws Exception - { + protected void doTestN(final ClientSessionFactory sf, final int threadNum) throws Exception { ClientSession sessCreate = sf.createSession(false, true, true); - sessCreate.createQueue(MultiThreadRandomReattachTestBase.ADDRESS, - new SimpleString(threadNum + MultiThreadRandomReattachTestBase.ADDRESS.toString()), - null, - false); + sessCreate.createQueue(MultiThreadRandomReattachTestBase.ADDRESS, new SimpleString(threadNum + MultiThreadRandomReattachTestBase.ADDRESS.toString()), null, false); ClientSession sess = sf.createSession(false, true, true); sess.addMetaData("data", RandomUtil.randomString()); @@ -1196,7 +1052,7 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt ClientProducer producer = sess.createProducer(MultiThreadRandomReattachTestBase.ADDRESS); - ClientMessage message = sess.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte)1); + ClientMessage message = sess.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); producer.send(message); sess.start(); @@ -1218,14 +1074,10 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt sessCreate.close(); } - protected void doTestO(final ClientSessionFactory sf, final int threadNum) throws Exception - { + protected void doTestO(final ClientSessionFactory sf, final int threadNum) throws Exception { ClientSession sessCreate = sf.createSession(false, true, true); - sessCreate.createQueue(MultiThreadRandomReattachTestBase.ADDRESS, - new SimpleString(threadNum + MultiThreadRandomReattachTestBase.ADDRESS.toString()), - null, - false); + sessCreate.createQueue(MultiThreadRandomReattachTestBase.ADDRESS, new SimpleString(threadNum + MultiThreadRandomReattachTestBase.ADDRESS.toString()), null, false); ClientSession sess = sf.createSession(false, true, true); @@ -1233,8 +1085,7 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt ClientConsumer consumer = sess.createConsumer(new SimpleString(threadNum + MultiThreadRandomReattachTestBase.ADDRESS.toString())); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { Assert.assertNull(consumer.receiveImmediate()); } @@ -1245,18 +1096,15 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt sessCreate.close(); } - protected int getLatchWait() - { + protected int getLatchWait() { return 60000; } - protected int getNumIterations() - { + protected int getNumIterations() { return 2; } - protected int getNumThreads() - { + protected int getNumThreads() { return 10; } @@ -1264,16 +1112,14 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt private void runTestMultipleThreads(final RunnableT runnable, final int numThreads, - final boolean failOnCreateConnection) throws Exception - { + final boolean failOnCreateConnection) throws Exception { runTestMultipleThreads(runnable, numThreads, failOnCreateConnection, 1000); } private void runTestMultipleThreads(final RunnableT runnable, final int numThreads, final boolean failOnCreateConnection, - final long failDelay) throws Exception - { + final long failDelay) throws Exception { runMultipleThreadsFailoverTest(runnable, numThreads, getNumIterations(), failOnCreateConnection, failDelay); } @@ -1282,17 +1128,13 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt * @return */ @Override - protected ServerLocator createLocator() throws Exception - { - ServerLocator locator = createInVMNonHALocator() - .setReconnectAttempts(-1) - .setConfirmationWindowSize(1024 * 1024); + protected ServerLocator createLocator() throws Exception { + ServerLocator locator = createInVMNonHALocator().setReconnectAttempts(-1).setConfirmationWindowSize(1024 * 1024); return locator; } @Override - protected void stop() throws Exception - { + protected void stop() throws Exception { ActiveMQTestBase.stopComponent(server); System.gc(); @@ -1303,15 +1145,9 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt private void sendMessages(final ClientSession sessSend, final ClientProducer producer, final int numMessages, - final int threadNum) throws Exception - { - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = sessSend.createMessage(ActiveMQBytesMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte)1); + final int threadNum) throws Exception { + for (int i = 0; i < numMessages; i++) { + ClientMessage message = sessSend.createMessage(ActiveMQBytesMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("threadnum"), threadNum); message.putIntProperty(new SimpleString("count"), i); setBody(message); @@ -1319,19 +1155,17 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt } } - private void consumeMessages(final Set consumers, final int numMessages, final int threadNum) throws Exception - { + private void consumeMessages(final Set consumers, + final int numMessages, + final int threadNum) throws Exception { // We make sure the messages arrive in the order they were sent from a particular producer Map> counts = new HashMap>(); - for (int i = 0; i < numMessages; i++) - { - for (ClientConsumer consumer : consumers) - { + for (int i = 0; i < numMessages; i++) { + for (ClientConsumer consumer : consumers) { Map consumerCounts = counts.get(consumer); - if (consumerCounts == null) - { + if (consumerCounts == null) { consumerCounts = new HashMap(); counts.put(consumer, consumerCounts); } @@ -1340,25 +1174,22 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt Assert.assertNotNull(msg); - int tn = (Integer)msg.getObjectProperty(new SimpleString("threadnum")); - int cnt = (Integer)msg.getObjectProperty(new SimpleString("count")); + int tn = (Integer) msg.getObjectProperty(new SimpleString("threadnum")); + int cnt = (Integer) msg.getObjectProperty(new SimpleString("count")); Integer c = consumerCounts.get(tn); - if (c == null) - { + if (c == null) { c = new Integer(cnt); } - if (tn == threadNum && cnt != c.intValue()) - { + if (tn == threadNum && cnt != c.intValue()) { throw new Exception("Invalid count, expected " + tn + ": " + c + " got " + cnt); } c++; // Wrap - if (c == numMessages) - { + if (c == numMessages) { c = 0; } @@ -1371,8 +1202,8 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt // Inner classes ------------------------------------------------- - private class MyHandler implements MessageHandler - { + private class MyHandler implements MessageHandler { + CountDownLatch latch = new CountDownLatch(1); private final Map counts = new HashMap(); @@ -1385,8 +1216,7 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt volatile boolean done; - synchronized void reset() - { + synchronized void reset() { counts.clear(); done = false; @@ -1396,63 +1226,53 @@ public abstract class MultiThreadRandomReattachTestBase extends MultiThreadReatt latch = new CountDownLatch(1); } - MyHandler(final int threadNum, final int numMessages) - { + MyHandler(final int threadNum, final int numMessages) { tn = threadNum; this.numMessages = numMessages; } - public synchronized void onMessage(final ClientMessage message) - { - try - { + public synchronized void onMessage(final ClientMessage message) { + try { message.acknowledge(); } - catch (ActiveMQException me) - { + catch (ActiveMQException me) { log.error("Failed to process", me); } - if (done) - { + if (done) { return; } - int threadNum = (Integer)message.getObjectProperty(new SimpleString("threadnum")); - int cnt = (Integer)message.getObjectProperty(new SimpleString("count")); + int threadNum = (Integer) message.getObjectProperty(new SimpleString("threadnum")); + int cnt = (Integer) message.getObjectProperty(new SimpleString("count")); Integer c = counts.get(threadNum); - if (c == null) - { + if (c == null) { c = new Integer(cnt); } - if (tn == threadNum && cnt != c.intValue()) - { + if (tn == threadNum && cnt != c.intValue()) { failure = "Invalid count, expected " + threadNum + ":" + c + " got " + cnt; log.error(failure); latch.countDown(); } - if (!checkSize(message)) - { + if (!checkSize(message)) { failure = "Invalid size on message"; log.error(failure); latch.countDown(); } - if (tn == threadNum && c == numMessages - 1) - { + if (tn == threadNum && c == numMessages - 1) { done = true; latch.countDown(); } c++; // Wrap around at numMessages - if (c == numMessages) - { + if (c == numMessages) { c = 0; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/MultiThreadReattachSupportTestBase.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/MultiThreadReattachSupportTestBase.java index 784f06c155..3a41924868 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/MultiThreadReattachSupportTestBase.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/MultiThreadReattachSupportTestBase.java @@ -35,8 +35,7 @@ import java.util.List; import java.util.Timer; import java.util.TimerTask; -public abstract class MultiThreadReattachSupportTestBase extends ActiveMQTestBase -{ +public abstract class MultiThreadReattachSupportTestBase extends ActiveMQTestBase { private final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @@ -50,23 +49,20 @@ public abstract class MultiThreadReattachSupportTestBase extends ActiveMQTestBas @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); timer = new Timer(); } @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { timer.cancel(); timer = null; super.tearDown(); } - protected boolean shouldFail() - { + protected boolean shouldFail() { return true; } @@ -74,46 +70,40 @@ public abstract class MultiThreadReattachSupportTestBase extends ActiveMQTestBas final int numThreads, final int numIts, final boolean failOnCreateConnection, - final long failDelay) throws Exception - { - for (int its = 0; its < numIts; its++) - { + final long failDelay) throws Exception { + for (int its = 0; its < numIts; its++) { log.info("Beginning iteration " + its); start(); final ServerLocator locator = createLocator(); - final ClientSessionFactoryInternal sf = (ClientSessionFactoryInternal)createSessionFactory(locator); + final ClientSessionFactoryInternal sf = (ClientSessionFactoryInternal) createSessionFactory(locator); final ClientSession session = addClientSession(sf.createSession(false, true, true)); Failer failer = startFailer(failDelay, session, failOnCreateConnection); - class Runner extends Thread - { + class Runner extends Thread { + private volatile Throwable throwable; private final RunnableT test; private final int threadNum; - Runner(final RunnableT test, final int threadNum) - { + Runner(final RunnableT test, final int threadNum) { this.test = test; this.threadNum = threadNum; } @Override - public void run() - { - try - { + public void run() { + try { test.run(sf, threadNum); } - catch (Throwable t) - { + catch (Throwable t) { throwable = t; log.error("Failed to run test", t); @@ -121,17 +111,15 @@ public abstract class MultiThreadReattachSupportTestBase extends ActiveMQTestBas // Case a failure happened here, it should print the Thread dump // Sending it to System.out, as it would show on the Tests report System.out.println(ActiveMQTestBase.threadDump(" - fired by MultiThreadRandomReattachTestBase::runTestMultipleThreads (" + t.getLocalizedMessage() + - ")")); + ")")); } } } - do - { + do { List threads = new ArrayList(); - for (int i = 0; i < numThreads; i++) - { + for (int i = 0; i < numThreads; i++) { Runner runner = new Runner(runnable, i); threads.add(runner); @@ -139,20 +127,17 @@ public abstract class MultiThreadReattachSupportTestBase extends ActiveMQTestBas runner.start(); } - for (Runner thread : threads) - { + for (Runner thread : threads) { thread.join(); - if (thread.throwable != null) - { + if (thread.throwable != null) { throw new Exception("Exception on thread " + thread, thread.throwable); } } runnable.checkFail(); - } - while (!failer.isExecuted()); + } while (!failer.isExecuted()); InVMConnector.resetFailures(); @@ -172,14 +157,12 @@ public abstract class MultiThreadReattachSupportTestBase extends ActiveMQTestBas // Private ------------------------------------------------------- - private Failer startFailer(final long time, final ClientSession session, final boolean failOnCreateConnection) - { + private Failer startFailer(final long time, final ClientSession session, final boolean failOnCreateConnection) { Failer failer = new Failer(session, failOnCreateConnection); // This is useful for debugging.. just change shouldFail to return false, and Failer will not be executed - if (shouldFail()) - { - timer.schedule(failer, (long)(time * Math.random()), 100); + if (shouldFail()) { + timer.schedule(failer, (long) (time * Math.random()), 100); } return failer; @@ -187,26 +170,22 @@ public abstract class MultiThreadReattachSupportTestBase extends ActiveMQTestBas // Inner classes ------------------------------------------------- - protected abstract class RunnableT extends Thread - { + protected abstract class RunnableT extends Thread { + private volatile String failReason; private volatile Throwable throwable; - public void setFailed(final String reason, final Throwable throwable) - { + public void setFailed(final String reason, final Throwable throwable) { failReason = reason; this.throwable = throwable; } - public void checkFail() - { - if (throwable != null) - { + public void checkFail() { + if (throwable != null) { log.error("Test failed: " + failReason, throwable); } - if (failReason != null) - { + if (failReason != null) { Assert.fail(failReason); } } @@ -214,35 +193,31 @@ public abstract class MultiThreadReattachSupportTestBase extends ActiveMQTestBas public abstract void run(final ClientSessionFactory sf, final int threadNum) throws Exception; } - private class Failer extends TimerTask - { + private class Failer extends TimerTask { + private final ClientSession session; private boolean executed; private final boolean failOnCreateConnection; - public Failer(final ClientSession session, final boolean failOnCreateConnection) - { + public Failer(final ClientSession session, final boolean failOnCreateConnection) { this.session = session; this.failOnCreateConnection = failOnCreateConnection; } @Override - public synchronized void run() - { + public synchronized void run() { log.info("** Failing connection"); - RemotingConnectionImpl conn = (RemotingConnectionImpl)((ClientSessionInternal)session).getConnection(); + RemotingConnectionImpl conn = (RemotingConnectionImpl) ((ClientSessionInternal) session).getConnection(); - if (failOnCreateConnection) - { + if (failOnCreateConnection) { InVMConnector.numberOfFailures = 1; InVMConnector.failOnCreateConnection = true; } - else - { + else { conn.fail(new ActiveMQNotConnectedException("blah")); } @@ -253,8 +228,7 @@ public abstract class MultiThreadReattachSupportTestBase extends ActiveMQTestBas executed = true; } - public synchronized boolean isExecuted() - { + public synchronized boolean isExecuted() { return executed; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/NettyMultiThreadRandomReattachTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/NettyMultiThreadRandomReattachTest.java index 91cfffddfd..0465567b41 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/NettyMultiThreadRandomReattachTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/NettyMultiThreadRandomReattachTest.java @@ -19,11 +19,10 @@ package org.apache.activemq.artemis.tests.integration.cluster.reattach; import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.core.config.Configuration; -public class NettyMultiThreadRandomReattachTest extends MultiThreadRandomReattachTest -{ +public class NettyMultiThreadRandomReattachTest extends MultiThreadRandomReattachTest { + @Override - protected void start() throws Exception - { + protected void start() throws Exception { Configuration liveConf = createDefaultNettyConfig(); server = createServer(false, liveConf); server.start(); @@ -31,12 +30,8 @@ public class NettyMultiThreadRandomReattachTest extends MultiThreadRandomReattac } @Override - protected ServerLocator createLocator() throws Exception - { - return createNettyNonHALocator() - .setReconnectAttempts(-1) - .setConfirmationWindowSize(1024 * 1024) - .setAckBatchSize(0); + protected ServerLocator createLocator() throws Exception { + return createNettyNonHALocator().setReconnectAttempts(-1).setConfirmationWindowSize(1024 * 1024).setAckBatchSize(0); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/OrderReattachTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/OrderReattachTest.java index 8d617c60c4..8878e58fd0 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/OrderReattachTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/OrderReattachTest.java @@ -42,8 +42,7 @@ import org.apache.activemq.artemis.jms.client.ActiveMQTextMessage; import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -public class OrderReattachTest extends ActiveMQTestBase -{ +public class OrderReattachTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- final SimpleString ADDRESS = new SimpleString("address"); @@ -60,21 +59,15 @@ public class OrderReattachTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testOrderOnSendInVM() throws Throwable - { + public void testOrderOnSendInVM() throws Throwable { doTestOrderOnSend(false); } - public void doTestOrderOnSend(final boolean isNetty) throws Throwable - { + public void doTestOrderOnSend(final boolean isNetty) throws Throwable { server = createServer(false, isNetty); server.start(); - ServerLocator locator = createFactory(isNetty) - .setReconnectAttempts(-1) - .setConfirmationWindowSize(1024 * 1024) - .setBlockOnNonDurableSend(false) - .setBlockOnAcknowledge(false); + ServerLocator locator = createFactory(isNetty).setReconnectAttempts(-1).setConfirmationWindowSize(1024 * 1024).setBlockOnNonDurableSend(false).setBlockOnAcknowledge(false); ClientSessionFactory sf = createSessionFactory(locator); @@ -84,47 +77,37 @@ public class OrderReattachTest extends ActiveMQTestBase final CountDownLatch ready = new CountDownLatch(1); - // this test will use a queue. Whenever the test wants a failure.. it can just send TRUE to failureQueue // This Thread will be reading the queue - Thread failer = new Thread() - { + Thread failer = new Thread() { @Override - public void run() - { + public void run() { ready.countDown(); - while (true) - { - try - { + while (true) { + try { Boolean poll = false; - try - { + try { poll = failureQueue.poll(60, TimeUnit.SECONDS); } - catch (InterruptedException e) - { + catch (InterruptedException e) { e.printStackTrace(); break; } Thread.sleep(1); - final RemotingConnectionImpl conn = (RemotingConnectionImpl)((ClientSessionInternal)session).getConnection(); + final RemotingConnectionImpl conn = (RemotingConnectionImpl) ((ClientSessionInternal) session).getConnection(); // True means... fail session - if (poll) - { + if (poll) { conn.fail(new ActiveMQNotConnectedException("poop")); } - else - { + else { // false means... finish thread break; } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -135,35 +118,27 @@ public class OrderReattachTest extends ActiveMQTestBase ready.await(); - try - { + try { doSend2(1, sf, failureQueue); } - finally - { - try - { + finally { + try { session.close(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } - try - { + try { locator.close(); } - catch (Exception e) - { + catch (Exception e) { // } - try - { + try { sf.close(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } @@ -174,8 +149,9 @@ public class OrderReattachTest extends ActiveMQTestBase } - public void doSend2(final int order, final ClientSessionFactory sf, final LinkedBlockingDeque failureQueue) throws Exception - { + public void doSend2(final int order, + final ClientSessionFactory sf, + final LinkedBlockingDeque failureQueue) throws Exception { ClientSession s = sf.createSession(false, false, false); final int numMessages = 500; @@ -185,8 +161,7 @@ public class OrderReattachTest extends ActiveMQTestBase Set consumers = new HashSet(); Set sessions = new HashSet(); - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString("sub" + i); // failureQueue.push(true); @@ -206,45 +181,35 @@ public class OrderReattachTest extends ActiveMQTestBase ClientProducer producer = sessSend.createProducer(ADDRESS); - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte)1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); - if (i % 10 == 0) - { + if (i % 10 == 0) { // failureQueue.push(true); } message.putIntProperty(new SimpleString("count"), i); producer.send(message); } - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.start(); } - class MyHandler implements MessageHandler - { + class MyHandler implements MessageHandler { + final CountDownLatch latch = new CountDownLatch(1); int count; Exception failure; - public void onMessage(final ClientMessage message) - { - if (count >= numMessages) - { + public void onMessage(final ClientMessage message) { + if (count >= numMessages) { failure = new Exception("too many messages"); latch.countDown(); } - if (message.getIntProperty("count") != count) - { + if (message.getIntProperty("count") != count) { failure = new Exception("counter " + count + " was not as expected (" + message.getIntProperty("count") + ")"); log.warn("Failure on receiving message ", failure); failure.printStackTrace(); @@ -253,13 +218,11 @@ public class OrderReattachTest extends ActiveMQTestBase count++; - if (count % 100 == 0) - { + if (count % 100 == 0) { failureQueue.push(true); } - if (count == numMessages) - { + if (count == numMessages) { latch.countDown(); } } @@ -267,8 +230,7 @@ public class OrderReattachTest extends ActiveMQTestBase Set handlers = new HashSet(); - for (ClientConsumer consumer : consumers) - { + for (ClientConsumer consumer : consumers) { MyHandler handler = new MyHandler(); consumer.setMessageHandler(handler); @@ -276,14 +238,12 @@ public class OrderReattachTest extends ActiveMQTestBase handlers.add(handler); } - for (MyHandler handler : handlers) - { + for (MyHandler handler : handlers) { boolean ok = handler.latch.await(60000, TimeUnit.MILLISECONDS); Assert.assertTrue(ok); - if (handler.failure != null) - { + if (handler.failure != null) { throw handler.failure; } } @@ -292,14 +252,12 @@ public class OrderReattachTest extends ActiveMQTestBase sessSend.close(); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { // failureQueue.push(true); session.close(); } - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { failureQueue.push(true); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/RandomReattachTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/RandomReattachTest.java index 87f30168a5..8dc0f62257 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/RandomReattachTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/RandomReattachTest.java @@ -47,8 +47,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class RandomReattachTest extends ActiveMQTestBase -{ +public class RandomReattachTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; // Constants ----------------------------------------------------- @@ -70,198 +70,152 @@ public class RandomReattachTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testA() throws Exception - { - runTest(new RunnableT() - { + public void testA() throws Exception { + runTest(new RunnableT() { @Override - public void run(final ClientSessionFactory sf) throws Exception - { + public void run(final ClientSessionFactory sf) throws Exception { doTestA(sf); } }); } @Test - public void testB() throws Exception - { - runTest(new RunnableT() - { + public void testB() throws Exception { + runTest(new RunnableT() { @Override - public void run(final ClientSessionFactory sf) throws Exception - { + public void run(final ClientSessionFactory sf) throws Exception { doTestB(sf); } }); } @Test - public void testC() throws Exception - { - runTest(new RunnableT() - { + public void testC() throws Exception { + runTest(new RunnableT() { @Override - public void run(final ClientSessionFactory sf) throws Exception - { + public void run(final ClientSessionFactory sf) throws Exception { doTestC(sf); } }); } @Test - public void testD() throws Exception - { - runTest(new RunnableT() - { + public void testD() throws Exception { + runTest(new RunnableT() { @Override - public void run(final ClientSessionFactory sf) throws Exception - { + public void run(final ClientSessionFactory sf) throws Exception { doTestD(sf); } }); } @Test - public void testE() throws Exception - { - runTest(new RunnableT() - { + public void testE() throws Exception { + runTest(new RunnableT() { @Override - public void run(final ClientSessionFactory sf) throws Exception - { + public void run(final ClientSessionFactory sf) throws Exception { doTestE(sf); } }); } @Test - public void testF() throws Exception - { - runTest(new RunnableT() - { + public void testF() throws Exception { + runTest(new RunnableT() { @Override - public void run(final ClientSessionFactory sf) throws Exception - { + public void run(final ClientSessionFactory sf) throws Exception { doTestF(sf); } }); } @Test - public void testG() throws Exception - { - runTest(new RunnableT() - { + public void testG() throws Exception { + runTest(new RunnableT() { @Override - public void run(final ClientSessionFactory sf) throws Exception - { + public void run(final ClientSessionFactory sf) throws Exception { doTestG(sf); } }); } @Test - public void testH() throws Exception - { - runTest(new RunnableT() - { + public void testH() throws Exception { + runTest(new RunnableT() { @Override - public void run(final ClientSessionFactory sf) throws Exception - { + public void run(final ClientSessionFactory sf) throws Exception { doTestH(sf); } }); } @Test - public void testI() throws Exception - { - runTest(new RunnableT() - { + public void testI() throws Exception { + runTest(new RunnableT() { @Override - public void run(final ClientSessionFactory sf) throws Exception - { + public void run(final ClientSessionFactory sf) throws Exception { doTestI(sf); } }); } @Test - public void testJ() throws Exception - { - runTest(new RunnableT() - { + public void testJ() throws Exception { + runTest(new RunnableT() { @Override - public void run(final ClientSessionFactory sf) throws Exception - { + public void run(final ClientSessionFactory sf) throws Exception { doTestJ(sf); } }); } @Test - public void testK() throws Exception - { - runTest(new RunnableT() - { + public void testK() throws Exception { + runTest(new RunnableT() { @Override - public void run(final ClientSessionFactory sf) throws Exception - { + public void run(final ClientSessionFactory sf) throws Exception { doTestK(sf); } }); } @Test - public void testL() throws Exception - { - runTest(new RunnableT() - { + public void testL() throws Exception { + runTest(new RunnableT() { @Override - public void run(final ClientSessionFactory sf) throws Exception - { + public void run(final ClientSessionFactory sf) throws Exception { doTestL(sf); } }); } @Test - public void testN() throws Exception - { - runTest(new RunnableT() - { + public void testN() throws Exception { + runTest(new RunnableT() { @Override - public void run(final ClientSessionFactory sf) throws Exception - { + public void run(final ClientSessionFactory sf) throws Exception { doTestN(sf); } }); } - public void runTest(final RunnableT runnable) throws Exception - { + public void runTest(final RunnableT runnable) throws Exception { final int numIts = getNumIterations(); - for (int its = 0; its < numIts; its++) - { + for (int its = 0; its < numIts; its++) { RandomReattachTest.log.info("####" + getName() + " iteration #" + its); start(); - ServerLocator locator = createInVMNonHALocator() - .setReconnectAttempts(-1) - .setConfirmationWindowSize(1024 * 1024); + ServerLocator locator = createInVMNonHALocator().setReconnectAttempts(-1).setConfirmationWindowSize(1024 * 1024); ClientSessionFactory sf = createSessionFactory(locator); - ClientSession session = sf.createSession(false, false, false); Failer failer = startFailer(1000, session); - do - { + do { runnable.run(sf); - } - while (!failer.isExecuted()); + } while (!failer.isExecuted()); } } @@ -269,8 +223,7 @@ public class RandomReattachTest extends ActiveMQTestBase // Protected ----------------------------------------------------- - protected void doTestA(final ClientSessionFactory sf) throws Exception - { + protected void doTestA(final ClientSessionFactory sf) throws Exception { long start = System.currentTimeMillis(); ClientSession s = sf.createSession(false, false, false); @@ -282,8 +235,7 @@ public class RandomReattachTest extends ActiveMQTestBase Set consumers = new HashSet(); Set sessions = new HashSet(); - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString("sub" + i); ClientSession sessConsume = sf.createSession(false, true, true); @@ -303,28 +255,21 @@ public class RandomReattachTest extends ActiveMQTestBase ClientProducer producer = sessSend.createProducer(RandomReattachTest.ADDRESS); - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte)1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); producer.send(message); } - class MyHandler extends AssertionCheckMessageHandler - { + class MyHandler extends AssertionCheckMessageHandler { + final CountDownLatch latch = new CountDownLatch(1); int count; @Override - public void onMessageAssert(final ClientMessage message) - { - if (count == numMessages) - { + public void onMessageAssert(final ClientMessage message) { + if (count == numMessages) { Assert.fail("Too many messages"); } @@ -332,17 +277,14 @@ public class RandomReattachTest extends ActiveMQTestBase count++; - try - { + try { message.acknowledge(); } - catch (ActiveMQException me) - { + catch (ActiveMQException me) { RandomReattachTest.log.error("Failed to process", me); } - if (count == numMessages) - { + if (count == numMessages) { latch.countDown(); } } @@ -350,8 +292,7 @@ public class RandomReattachTest extends ActiveMQTestBase Set handlers = new HashSet(); - for (ClientConsumer consumer : consumers) - { + for (ClientConsumer consumer : consumers) { MyHandler handler = new MyHandler(); consumer.setMessageHandler(handler); @@ -359,8 +300,7 @@ public class RandomReattachTest extends ActiveMQTestBase handlers.add(handler); } - for (MyHandler handler : handlers) - { + for (MyHandler handler : handlers) { boolean ok = handler.latch.await(5000, TimeUnit.MILLISECONDS); handler.checkAssertions(); @@ -369,13 +309,11 @@ public class RandomReattachTest extends ActiveMQTestBase } sessSend.close(); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.close(); } - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString("sub" + i); s.deleteQueue(subName); @@ -388,8 +326,7 @@ public class RandomReattachTest extends ActiveMQTestBase RandomReattachTest.log.info("duration " + (end - start)); } - protected void doTestB(final ClientSessionFactory sf) throws Exception - { + protected void doTestB(final ClientSessionFactory sf) throws Exception { long start = System.currentTimeMillis(); ClientSession s = sf.createSession(false, false, false); @@ -401,8 +338,7 @@ public class RandomReattachTest extends ActiveMQTestBase Set consumers = new HashSet(); Set sessions = new HashSet(); - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString("sub" + i); ClientSession sessConsume = sf.createSession(false, true, true); @@ -420,33 +356,25 @@ public class RandomReattachTest extends ActiveMQTestBase ClientProducer producer = sessSend.createProducer(RandomReattachTest.ADDRESS); - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte)1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); producer.send(message); } - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.start(); } - class MyHandler extends AssertionCheckMessageHandler - { + class MyHandler extends AssertionCheckMessageHandler { + final CountDownLatch latch = new CountDownLatch(1); int count; @Override - public void onMessageAssert(final ClientMessage message) - { - if (count == numMessages) - { + public void onMessageAssert(final ClientMessage message) { + if (count == numMessages) { Assert.fail("Too many messages"); } @@ -454,8 +382,7 @@ public class RandomReattachTest extends ActiveMQTestBase count++; - if (count == numMessages) - { + if (count == numMessages) { latch.countDown(); } } @@ -463,8 +390,7 @@ public class RandomReattachTest extends ActiveMQTestBase Set handlers = new HashSet(); - for (ClientConsumer consumer : consumers) - { + for (ClientConsumer consumer : consumers) { MyHandler handler = new MyHandler(); consumer.setMessageHandler(handler); @@ -472,8 +398,7 @@ public class RandomReattachTest extends ActiveMQTestBase handlers.add(handler); } - for (MyHandler handler : handlers) - { + for (MyHandler handler : handlers) { boolean ok = handler.latch.await(10000, TimeUnit.MILLISECONDS); handler.checkAssertions(); @@ -483,13 +408,11 @@ public class RandomReattachTest extends ActiveMQTestBase sessSend.close(); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.close(); } - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString("sub" + i); s.deleteQueue(subName); @@ -503,8 +426,7 @@ public class RandomReattachTest extends ActiveMQTestBase } - protected void doTestC(final ClientSessionFactory sf) throws Exception - { + protected void doTestC(final ClientSessionFactory sf) throws Exception { long start = System.currentTimeMillis(); ClientSession s = sf.createSession(false, false, false); @@ -516,8 +438,7 @@ public class RandomReattachTest extends ActiveMQTestBase Set consumers = new HashSet(); Set sessions = new HashSet(); - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString("sub" + i); ClientSession sessConsume = sf.createSession(false, false, false); @@ -537,43 +458,31 @@ public class RandomReattachTest extends ActiveMQTestBase ClientProducer producer = sessSend.createProducer(RandomReattachTest.ADDRESS); - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte)1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); producer.send(message); } sessSend.rollback(); - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte)1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); producer.send(message); } sessSend.commit(); - class MyHandler extends AssertionCheckMessageHandler - { + class MyHandler extends AssertionCheckMessageHandler { + final CountDownLatch latch = new CountDownLatch(1); int count; @Override - public void onMessageAssert(final ClientMessage message) - { - if (count == numMessages) - { + public void onMessageAssert(final ClientMessage message) { + if (count == numMessages) { Assert.fail("Too many messages, expected " + count); } @@ -581,18 +490,15 @@ public class RandomReattachTest extends ActiveMQTestBase count++; - try - { + try { message.acknowledge(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { e.printStackTrace(); throw new RuntimeException(e.getMessage(), e); } - if (count == numMessages) - { + if (count == numMessages) { latch.countDown(); } } @@ -600,8 +506,7 @@ public class RandomReattachTest extends ActiveMQTestBase Set handlers = new HashSet(); - for (ClientConsumer consumer : consumers) - { + for (ClientConsumer consumer : consumers) { MyHandler handler = new MyHandler(); consumer.setMessageHandler(handler); @@ -609,8 +514,7 @@ public class RandomReattachTest extends ActiveMQTestBase handlers.add(handler); } - for (MyHandler handler : handlers) - { + for (MyHandler handler : handlers) { boolean ok = handler.latch.await(10000, TimeUnit.MILLISECONDS); Assert.assertTrue(ok); @@ -621,8 +525,7 @@ public class RandomReattachTest extends ActiveMQTestBase handlers.clear(); // New handlers - for (ClientConsumer consumer : consumers) - { + for (ClientConsumer consumer : consumers) { MyHandler handler = new MyHandler(); consumer.setMessageHandler(handler); @@ -630,13 +533,11 @@ public class RandomReattachTest extends ActiveMQTestBase handlers.add(handler); } - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.rollback(); } - for (MyHandler handler : handlers) - { + for (MyHandler handler : handlers) { boolean ok = handler.latch.await(10000, TimeUnit.MILLISECONDS); Assert.assertTrue(ok); @@ -644,19 +545,16 @@ public class RandomReattachTest extends ActiveMQTestBase handler.checkAssertions(); } - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.commit(); } sessSend.close(); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.close(); } - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString("sub" + i); s.deleteQueue(subName); @@ -669,8 +567,7 @@ public class RandomReattachTest extends ActiveMQTestBase RandomReattachTest.log.info("duration " + (end - start)); } - protected void doTestD(final ClientSessionFactory sf) throws Exception - { + protected void doTestD(final ClientSessionFactory sf) throws Exception { long start = System.currentTimeMillis(); ClientSession s = sf.createSession(false, false, false); @@ -682,8 +579,7 @@ public class RandomReattachTest extends ActiveMQTestBase Set consumers = new HashSet(); Set sessions = new HashSet(); - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString("sub" + i); ClientSession sessConsume = sf.createSession(false, false, false); @@ -701,48 +597,35 @@ public class RandomReattachTest extends ActiveMQTestBase ClientProducer producer = sessSend.createProducer(RandomReattachTest.ADDRESS); - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte)1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); producer.send(message); } sessSend.rollback(); - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte)1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); producer.send(message); } sessSend.commit(); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.start(); } - class MyHandler extends AssertionCheckMessageHandler - { + class MyHandler extends AssertionCheckMessageHandler { + final CountDownLatch latch = new CountDownLatch(1); int count; @Override - public void onMessageAssert(final ClientMessage message) - { - if (count == numMessages) - { + public void onMessageAssert(final ClientMessage message) { + if (count == numMessages) { Assert.fail("Too many messages, " + count); } @@ -750,8 +633,7 @@ public class RandomReattachTest extends ActiveMQTestBase count++; - if (count == numMessages) - { + if (count == numMessages) { latch.countDown(); } } @@ -759,8 +641,7 @@ public class RandomReattachTest extends ActiveMQTestBase Set handlers = new HashSet(); - for (ClientConsumer consumer : consumers) - { + for (ClientConsumer consumer : consumers) { MyHandler handler = new MyHandler(); consumer.setMessageHandler(handler); @@ -768,8 +649,7 @@ public class RandomReattachTest extends ActiveMQTestBase handlers.add(handler); } - for (MyHandler handler : handlers) - { + for (MyHandler handler : handlers) { boolean ok = handler.latch.await(20000, TimeUnit.MILLISECONDS); Assert.assertTrue(ok); @@ -780,8 +660,7 @@ public class RandomReattachTest extends ActiveMQTestBase handlers.clear(); // New handlers - for (ClientConsumer consumer : consumers) - { + for (ClientConsumer consumer : consumers) { MyHandler handler = new MyHandler(); consumer.setMessageHandler(handler); @@ -789,13 +668,11 @@ public class RandomReattachTest extends ActiveMQTestBase handlers.add(handler); } - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.rollback(); } - for (MyHandler handler : handlers) - { + for (MyHandler handler : handlers) { boolean ok = handler.latch.await(10000, TimeUnit.MILLISECONDS); Assert.assertTrue(ok); @@ -803,19 +680,16 @@ public class RandomReattachTest extends ActiveMQTestBase handler.checkAssertions(); } - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.commit(); } sessSend.close(); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.close(); } - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString("sub" + i); s.deleteQueue(subName); @@ -830,8 +704,7 @@ public class RandomReattachTest extends ActiveMQTestBase // Now with synchronous receive() - protected void doTestE(final ClientSessionFactory sf) throws Exception - { + protected void doTestE(final ClientSessionFactory sf) throws Exception { long start = System.currentTimeMillis(); ClientSession s = sf.createSession(false, false, false); @@ -843,8 +716,7 @@ public class RandomReattachTest extends ActiveMQTestBase Set consumers = new HashSet(); Set sessions = new HashSet(); - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString("sub" + i); ClientSession sessConsume = sf.createSession(false, true, true); @@ -864,21 +736,14 @@ public class RandomReattachTest extends ActiveMQTestBase ClientProducer producer = sessSend.createProducer(RandomReattachTest.ADDRESS); - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte)1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); producer.send(message); } - for (int i = 0; i < numMessages; i++) - { - for (ClientConsumer consumer : consumers) - { + for (int i = 0; i < numMessages; i++) { + for (ClientConsumer consumer : consumers) { ClientMessage msg = consumer.receive(RandomReattachTest.RECEIVE_TIMEOUT); Assert.assertNotNull(msg); @@ -889,10 +754,8 @@ public class RandomReattachTest extends ActiveMQTestBase } } - for (int i = 0; i < numMessages; i++) - { - for (ClientConsumer consumer : consumers) - { + for (int i = 0; i < numMessages; i++) { + for (ClientConsumer consumer : consumers) { ClientMessage msg = consumer.receiveImmediate(); Assert.assertNull(msg); @@ -900,13 +763,11 @@ public class RandomReattachTest extends ActiveMQTestBase } sessSend.close(); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.close(); } - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString("sub" + i); s.deleteQueue(subName); @@ -919,8 +780,7 @@ public class RandomReattachTest extends ActiveMQTestBase RandomReattachTest.log.info("duration " + (end - start)); } - protected void doTestF(final ClientSessionFactory sf) throws Exception - { + protected void doTestF(final ClientSessionFactory sf) throws Exception { long start = System.currentTimeMillis(); ClientSession s = sf.createSession(false, false, false); @@ -932,8 +792,7 @@ public class RandomReattachTest extends ActiveMQTestBase Set consumers = new HashSet(); Set sessions = new HashSet(); - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString("sub" + i); ClientSession sessConsume = sf.createSession(false, true, true); @@ -951,30 +810,21 @@ public class RandomReattachTest extends ActiveMQTestBase ClientProducer producer = sessSend.createProducer(RandomReattachTest.ADDRESS); - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte)1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); producer.send(message); } - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.start(); } - for (int i = 0; i < numMessages; i++) - { - for (ClientConsumer consumer : consumers) - { + for (int i = 0; i < numMessages; i++) { + for (ClientConsumer consumer : consumers) { ClientMessage msg = consumer.receive(RandomReattachTest.RECEIVE_TIMEOUT); - if (msg == null) - { + if (msg == null) { throw new IllegalStateException("Failed to receive message " + i); } @@ -986,10 +836,8 @@ public class RandomReattachTest extends ActiveMQTestBase } } - for (int i = 0; i < numMessages; i++) - { - for (ClientConsumer consumer : consumers) - { + for (int i = 0; i < numMessages; i++) { + for (ClientConsumer consumer : consumers) { ClientMessage msg = consumer.receiveImmediate(); Assert.assertNull(msg); @@ -997,13 +845,11 @@ public class RandomReattachTest extends ActiveMQTestBase } sessSend.close(); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.close(); } - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString("sub" + i); s.deleteQueue(subName); @@ -1011,15 +857,14 @@ public class RandomReattachTest extends ActiveMQTestBase s.close(); - Assert.assertEquals(1, ((ClientSessionFactoryImpl)sf).numSessions()); + Assert.assertEquals(1, ((ClientSessionFactoryImpl) sf).numSessions()); long end = System.currentTimeMillis(); RandomReattachTest.log.info("duration " + (end - start)); } - protected void doTestG(final ClientSessionFactory sf) throws Exception - { + protected void doTestG(final ClientSessionFactory sf) throws Exception { long start = System.currentTimeMillis(); ClientSession s = sf.createSession(false, false, false); @@ -1031,8 +876,7 @@ public class RandomReattachTest extends ActiveMQTestBase Set consumers = new HashSet(); Set sessions = new HashSet(); - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString("sub" + i); ClientSession sessConsume = sf.createSession(false, false, false); @@ -1052,36 +896,24 @@ public class RandomReattachTest extends ActiveMQTestBase ClientProducer producer = sessSend.createProducer(RandomReattachTest.ADDRESS); - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte)1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); producer.send(message); } sessSend.rollback(); - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte)1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); producer.send(message); } sessSend.commit(); - for (int i = 0; i < numMessages; i++) - { - for (ClientConsumer consumer : consumers) - { + for (int i = 0; i < numMessages; i++) { + for (ClientConsumer consumer : consumers) { ClientMessage msg = consumer.receive(RandomReattachTest.RECEIVE_TIMEOUT); Assert.assertNotNull(msg); @@ -1092,22 +924,18 @@ public class RandomReattachTest extends ActiveMQTestBase } } - for (ClientConsumer consumer : consumers) - { + for (ClientConsumer consumer : consumers) { ClientMessage msg = consumer.receiveImmediate(); Assert.assertNull(msg); } - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.rollback(); } - for (int i = 0; i < numMessages; i++) - { - for (ClientConsumer consumer : consumers) - { + for (int i = 0; i < numMessages; i++) { + for (ClientConsumer consumer : consumers) { ClientMessage msg = consumer.receive(RandomReattachTest.RECEIVE_TIMEOUT); Assert.assertNotNull(msg); @@ -1118,29 +946,24 @@ public class RandomReattachTest extends ActiveMQTestBase } } - for (int i = 0; i < numMessages; i++) - { - for (ClientConsumer consumer : consumers) - { + for (int i = 0; i < numMessages; i++) { + for (ClientConsumer consumer : consumers) { ClientMessage msg = consumer.receiveImmediate(); Assert.assertNull(msg); } } - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.commit(); } sessSend.close(); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.close(); } - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString("sub" + i); s.deleteQueue(subName); @@ -1153,8 +976,7 @@ public class RandomReattachTest extends ActiveMQTestBase RandomReattachTest.log.info("duration " + (end - start)); } - protected void doTestH(final ClientSessionFactory sf) throws Exception - { + protected void doTestH(final ClientSessionFactory sf) throws Exception { long start = System.currentTimeMillis(); ClientSession s = sf.createSession(false, false, false); @@ -1166,8 +988,7 @@ public class RandomReattachTest extends ActiveMQTestBase Set consumers = new HashSet(); Set sessions = new HashSet(); - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString("sub" + i); ClientSession sessConsume = sf.createSession(false, false, false); @@ -1185,41 +1006,28 @@ public class RandomReattachTest extends ActiveMQTestBase ClientProducer producer = sessSend.createProducer(RandomReattachTest.ADDRESS); - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte)1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); producer.send(message); } sessSend.rollback(); - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte)1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = sessSend.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); producer.send(message); } sessSend.commit(); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.start(); } - for (int i = 0; i < numMessages; i++) - { - for (ClientConsumer consumer : consumers) - { + for (int i = 0; i < numMessages; i++) { + for (ClientConsumer consumer : consumers) { ClientMessage msg = consumer.receive(RandomReattachTest.RECEIVE_TIMEOUT); Assert.assertNotNull(msg); @@ -1230,25 +1038,20 @@ public class RandomReattachTest extends ActiveMQTestBase } } - for (int i = 0; i < numMessages; i++) - { - for (ClientConsumer consumer : consumers) - { + for (int i = 0; i < numMessages; i++) { + for (ClientConsumer consumer : consumers) { ClientMessage msg = consumer.receiveImmediate(); Assert.assertNull(msg); } } - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.rollback(); } - for (int i = 0; i < numMessages; i++) - { - for (ClientConsumer consumer : consumers) - { + for (int i = 0; i < numMessages; i++) { + for (ClientConsumer consumer : consumers) { ClientMessage msg = consumer.receive(RandomReattachTest.RECEIVE_TIMEOUT); Assert.assertNotNull(msg); @@ -1259,29 +1062,24 @@ public class RandomReattachTest extends ActiveMQTestBase } } - for (int i = 0; i < numMessages; i++) - { - for (ClientConsumer consumer : consumers) - { + for (int i = 0; i < numMessages; i++) { + for (ClientConsumer consumer : consumers) { ClientMessage msg = consumer.receiveImmediate(); Assert.assertNull(msg); } } - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.commit(); } sessSend.close(); - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.close(); } - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { SimpleString subName = new SimpleString("sub" + i); s.deleteQueue(subName); @@ -1294,8 +1092,7 @@ public class RandomReattachTest extends ActiveMQTestBase RandomReattachTest.log.info("duration " + (end - start)); } - protected void doTestI(final ClientSessionFactory sf) throws Exception - { + protected void doTestI(final ClientSessionFactory sf) throws Exception { ClientSession sessCreate = sf.createSession(false, true, true); sessCreate.createQueue(RandomReattachTest.ADDRESS, RandomReattachTest.ADDRESS, null, false); @@ -1308,11 +1105,7 @@ public class RandomReattachTest extends ActiveMQTestBase ClientProducer producer = sess.createProducer(RandomReattachTest.ADDRESS); - ClientMessage message = sess.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte)1); + ClientMessage message = sess.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); producer.send(message); ClientMessage message2 = consumer.receive(RandomReattachTest.RECEIVE_TIMEOUT); @@ -1328,8 +1121,7 @@ public class RandomReattachTest extends ActiveMQTestBase sessCreate.close(); } - protected void doTestJ(final ClientSessionFactory sf) throws Exception - { + protected void doTestJ(final ClientSessionFactory sf) throws Exception { ClientSession sessCreate = sf.createSession(false, true, true); sessCreate.createQueue(RandomReattachTest.ADDRESS, RandomReattachTest.ADDRESS, null, false); @@ -1342,11 +1134,7 @@ public class RandomReattachTest extends ActiveMQTestBase ClientProducer producer = sess.createProducer(RandomReattachTest.ADDRESS); - ClientMessage message = sess.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte)1); + ClientMessage message = sess.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); producer.send(message); ClientMessage message2 = consumer.receive(RandomReattachTest.RECEIVE_TIMEOUT); @@ -1362,16 +1150,14 @@ public class RandomReattachTest extends ActiveMQTestBase sessCreate.close(); } - protected void doTestK(final ClientSessionFactory sf) throws Exception - { + protected void doTestK(final ClientSessionFactory sf) throws Exception { ClientSession s = sf.createSession(false, false, false); s.createQueue(RandomReattachTest.ADDRESS, RandomReattachTest.ADDRESS, null, false); final int numConsumers = 100; - for (int i = 0; i < numConsumers; i++) - { + for (int i = 0; i < numConsumers; i++) { ClientConsumer consumer = s.createConsumer(RandomReattachTest.ADDRESS); consumer.close(); @@ -1382,26 +1168,20 @@ public class RandomReattachTest extends ActiveMQTestBase s.close(); } - protected void doTestL(final ClientSessionFactory sf) throws Exception - { + protected void doTestL(final ClientSessionFactory sf) throws Exception { final int numSessions = 10; - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { ClientSession session = sf.createSession(false, false, false); session.close(); } } - protected void doTestN(final ClientSessionFactory sf) throws Exception - { + protected void doTestN(final ClientSessionFactory sf) throws Exception { ClientSession sessCreate = sf.createSession(false, true, true); - sessCreate.createQueue(RandomReattachTest.ADDRESS, - new SimpleString(RandomReattachTest.ADDRESS.toString()), - null, - false); + sessCreate.createQueue(RandomReattachTest.ADDRESS, new SimpleString(RandomReattachTest.ADDRESS.toString()), null, false); ClientSession sess = sf.createSession(false, true, true); @@ -1415,11 +1195,7 @@ public class RandomReattachTest extends ActiveMQTestBase ClientProducer producer = sess.createProducer(RandomReattachTest.ADDRESS); - ClientMessage message = sess.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte)1); + ClientMessage message = sess.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); producer.send(message); sess.start(); @@ -1441,15 +1217,13 @@ public class RandomReattachTest extends ActiveMQTestBase sessCreate.close(); } - protected int getNumIterations() - { + protected int getNumIterations() { return 2; } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); timer = new Timer(true); @@ -1457,8 +1231,7 @@ public class RandomReattachTest extends ActiveMQTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { timer.cancel(); super.tearDown(); @@ -1466,23 +1239,20 @@ public class RandomReattachTest extends ActiveMQTestBase // Private ------------------------------------------------------- - private Failer startFailer(final long time, final ClientSession session) - { - Failer failer = new Failer((ClientSessionInternal)session); + private Failer startFailer(final long time, final ClientSession session) { + Failer failer = new Failer((ClientSessionInternal) session); - timer.schedule(failer, (long)(time * Math.random()), 100); + timer.schedule(failer, (long) (time * Math.random()), 100); return failer; } - private void start() throws Exception - { + private void start() throws Exception { server = addServer(ActiveMQServers.newActiveMQServer(createDefaultInVMConfig(), false)); server.start(); } - private void stop() throws Exception - { + private void stop() throws Exception { server.stop(); Assert.assertEquals(0, InVMRegistry.instance.size()); @@ -1492,20 +1262,18 @@ public class RandomReattachTest extends ActiveMQTestBase // Inner classes ------------------------------------------------- - class Failer extends TimerTask - { + class Failer extends TimerTask { + private final ClientSessionInternal session; private boolean executed; - public Failer(final ClientSessionInternal session) - { + public Failer(final ClientSessionInternal session) { this.session = session; } @Override - public synchronized void run() - { + public synchronized void run() { RandomReattachTest.log.info("** Failing connection"); session.getConnection().fail(new ActiveMQNotConnectedException("oops")); @@ -1517,25 +1285,20 @@ public class RandomReattachTest extends ActiveMQTestBase executed = true; } - public synchronized boolean isExecuted() - { + public synchronized boolean isExecuted() { return executed; } } - public abstract class RunnableT - { + public abstract class RunnableT { + abstract void run(final ClientSessionFactory sf) throws Exception; } - abstract static class AssertionCheckMessageHandler implements MessageHandler - { + abstract static class AssertionCheckMessageHandler implements MessageHandler { - - public void checkAssertions() - { - for (AssertionError e : errors) - { + public void checkAssertions() { + for (AssertionError e : errors) { // it will throw the first error throw e; } @@ -1546,14 +1309,11 @@ public class RandomReattachTest extends ActiveMQTestBase /* (non-Javadoc) * @see MessageHandler#onMessage(ClientMessage) */ - public void onMessage(ClientMessage message) - { - try - { + public void onMessage(ClientMessage message) { + try { onMessageAssert(message); } - catch (AssertionError e) - { + catch (AssertionError e) { e.printStackTrace(); // System.out -> junit reports errors.add(e); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/ReattachTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/ReattachTest.java index d31cda3043..12123ce47b 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/ReattachTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/reattach/ReattachTest.java @@ -48,8 +48,8 @@ import java.util.TimerTask; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; -public class ReattachTest extends ActiveMQTestBase -{ +public class ReattachTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private static final SimpleString ADDRESS = new SimpleString("FailoverTestAddress"); @@ -60,18 +60,14 @@ public class ReattachTest extends ActiveMQTestBase * Test failure on connection, but server is still up so should immediately reconnect */ @Test - public void testImmediateReattach() throws Exception - { + public void testImmediateReattach() throws Exception { final long retryInterval = 500; final double retryMultiplier = 1d; final int reconnectAttempts = 1; - locator.setRetryInterval(retryInterval) - .setRetryIntervalMultiplier(retryMultiplier) - .setReconnectAttempts(reconnectAttempts) - .setConfirmationWindowSize(1024 * 1024); + locator.setRetryInterval(retryInterval).setRetryIntervalMultiplier(retryMultiplier).setReconnectAttempts(reconnectAttempts).setConfirmationWindowSize(1024 * 1024); ClientSessionFactoryInternal sf = (ClientSessionFactoryInternal) createSessionFactory(locator); @@ -81,19 +77,13 @@ public class ReattachTest extends ActiveMQTestBase final int numIterations = 10; - for (int j = 0; j < numIterations; j++) - { + for (int j = 0; j < numIterations; j++) { ClientProducer producer = session.createProducer(ReattachTest.ADDRESS); final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte) 1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); message.getBodyBuffer().writeString("aardvarks"); producer.send(message); @@ -107,8 +97,7 @@ public class ReattachTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(500); Assert.assertNotNull(message); @@ -138,36 +127,27 @@ public class ReattachTest extends ActiveMQTestBase * Test failure on connection, but server is still up so should immediately reconnect */ @Test - public void testOverflowCredits() throws Exception - { + public void testOverflowCredits() throws Exception { final long retryInterval = 500; final double retryMultiplier = 1d; final int reconnectAttempts = 1; - locator.setRetryInterval(retryInterval) - .setRetryIntervalMultiplier(retryMultiplier) - .setReconnectAttempts(reconnectAttempts) - .setConfirmationWindowSize(1024 * 1024) - .setProducerWindowSize(1000); + locator.setRetryInterval(retryInterval).setRetryIntervalMultiplier(retryMultiplier).setReconnectAttempts(reconnectAttempts).setConfirmationWindowSize(1024 * 1024).setProducerWindowSize(1000); final AtomicInteger count = new AtomicInteger(0); - Interceptor intercept = new Interceptor() - { + Interceptor intercept = new Interceptor() { - public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException - { + public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException { System.out.println("Intercept..." + packet.getClass().getName()); - if (packet instanceof SessionProducerCreditsMessage) - { + if (packet instanceof SessionProducerCreditsMessage) { SessionProducerCreditsMessage credit = (SessionProducerCreditsMessage) packet; System.out.println("Credits: " + credit.getCredits()); - if (count.incrementAndGet() == 2) - { + if (count.incrementAndGet() == 2) { System.out.println("Failing"); connection.fail(new ActiveMQException(ActiveMQExceptionType.UNSUPPORTED_PACKET, "bye")); return false; @@ -189,13 +169,8 @@ public class ReattachTest extends ActiveMQTestBase final int numMessages = 10; - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte) 1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); message.getBodyBuffer().writeBytes(new byte[5000]); producer.send(message); @@ -211,18 +186,14 @@ public class ReattachTest extends ActiveMQTestBase * allow connection to be recreated */ @Test - public void testDelayedReattach() throws Exception - { + public void testDelayedReattach() throws Exception { final long retryInterval = 500; final double retryMultiplier = 1d; final int reconnectAttempts = -1; - locator.setRetryInterval(retryInterval) - .setRetryIntervalMultiplier(retryMultiplier) - .setReconnectAttempts(reconnectAttempts) - .setConfirmationWindowSize(1024 * 1024); + locator.setRetryInterval(retryInterval).setRetryIntervalMultiplier(retryMultiplier).setReconnectAttempts(reconnectAttempts).setConfirmationWindowSize(1024 * 1024); ClientSessionFactoryInternal sf = (ClientSessionFactoryInternal) createSessionFactory(locator); @@ -234,13 +205,8 @@ public class ReattachTest extends ActiveMQTestBase final int numMessages = 1000; - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte) 1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); message.getBodyBuffer().writeString("aardvarks"); producer.send(message); @@ -252,17 +218,13 @@ public class ReattachTest extends ActiveMQTestBase RemotingConnection conn = ((ClientSessionInternal) session).getConnection(); - Thread t = new Thread() - { + Thread t = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { Thread.sleep(retryInterval * 3); } - catch (InterruptedException ignore) - { + catch (InterruptedException ignore) { } InVMConnector.failOnCreateConnection = false; @@ -275,8 +237,7 @@ public class ReattachTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(500); Assert.assertNotNull(message); @@ -301,8 +262,7 @@ public class ReattachTest extends ActiveMQTestBase // Test an async (e.g. pinger) failure coming in while a connection manager is already reconnecting @Test - public void testAsyncFailureWhileReattaching() throws Exception - { + public void testAsyncFailureWhileReattaching() throws Exception { final long retryInterval = 500; final double retryMultiplier = 1d; @@ -311,10 +271,7 @@ public class ReattachTest extends ActiveMQTestBase final long asyncFailDelay = 2000; - locator.setRetryInterval(retryInterval) - .setRetryIntervalMultiplier(retryMultiplier) - .setReconnectAttempts(reconnectAttempts) - .setConfirmationWindowSize(1024 * 1024); + locator.setRetryInterval(retryInterval).setRetryIntervalMultiplier(retryMultiplier).setReconnectAttempts(reconnectAttempts).setConfirmationWindowSize(1024 * 1024); ClientSessionFactoryInternal sf = (ClientSessionFactoryInternal) createSessionFactory(locator); @@ -322,24 +279,21 @@ public class ReattachTest extends ActiveMQTestBase ClientSession session2 = sf.createSession(false, true, true); - class MyFailureListener implements SessionFailureListener - { + class MyFailureListener implements SessionFailureListener { + volatile boolean failed; @Override - public void connectionFailed(final ActiveMQException me, boolean failedOver) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver) { failed = true; } @Override - public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) { connectionFailed(me, failedOver); } - public void beforeReconnect(final ActiveMQException exception) - { + public void beforeReconnect(final ActiveMQException exception) { } } @@ -353,13 +307,8 @@ public class ReattachTest extends ActiveMQTestBase final int numMessages = 1000; - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte) 1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); message.getBodyBuffer().writeString("aardvarks"); producer.send(message); @@ -374,17 +323,13 @@ public class ReattachTest extends ActiveMQTestBase final RemotingConnection conn2 = ((ClientSessionInternal) session2).getConnection(); - Thread t = new Thread() - { + Thread t = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { Thread.sleep(asyncFailDelay); } - catch (InterruptedException ignore) - { + catch (InterruptedException ignore) { } conn2.fail(new ActiveMQNotConnectedException("Did not receive pong from server")); @@ -399,8 +344,7 @@ public class ReattachTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(500); Assert.assertNotNull(message); @@ -426,18 +370,14 @@ public class ReattachTest extends ActiveMQTestBase } @Test - public void testReattachAttemptsFailsToReconnect() throws Exception - { + public void testReattachAttemptsFailsToReconnect() throws Exception { final long retryInterval = 500; final double retryMultiplier = 1d; final int reconnectAttempts = 3; - locator.setRetryInterval(retryInterval) - .setRetryIntervalMultiplier(retryMultiplier) - .setReconnectAttempts(reconnectAttempts) - .setConfirmationWindowSize(1024 * 1024); + locator.setRetryInterval(retryInterval).setRetryIntervalMultiplier(retryMultiplier).setReconnectAttempts(reconnectAttempts).setConfirmationWindowSize(1024 * 1024); ClientSessionFactoryInternal sf = (ClientSessionFactoryInternal) createSessionFactory(locator); @@ -449,13 +389,8 @@ public class ReattachTest extends ActiveMQTestBase final int numMessages = 1000; - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte) 1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); message.getBodyBuffer().writeString("aardvarks"); producer.send(message); @@ -469,17 +404,13 @@ public class ReattachTest extends ActiveMQTestBase // Sleep for longer than max retries so should fail to reconnect - Thread t = new Thread() - { + Thread t = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { Thread.sleep(retryInterval * (reconnectAttempts + 1)); } - catch (InterruptedException ignore) - { + catch (InterruptedException ignore) { } InVMConnector.failOnCreateConnection = false; @@ -492,18 +423,15 @@ public class ReattachTest extends ActiveMQTestBase // Should throw exception since didn't reconnect - try - { + try { session.start(); Assert.fail("Should throw exception"); } - catch (ActiveMQObjectClosedException oce) - { + catch (ActiveMQObjectClosedException oce) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } @@ -515,14 +443,12 @@ public class ReattachTest extends ActiveMQTestBase } @Test - public void testCreateSessionFailAfterSendSeveralThreads() throws Throwable - { + public void testCreateSessionFailAfterSendSeveralThreads() throws Throwable { Timer timer = new Timer(); ClientSession session = null; - try - { + try { final long retryInterval = 50; @@ -530,10 +456,7 @@ public class ReattachTest extends ActiveMQTestBase final int reconnectAttempts = -1; - locator.setRetryInterval(retryInterval) - .setRetryIntervalMultiplier(retryMultiplier) - .setReconnectAttempts(reconnectAttempts) - .setConfirmationWindowSize(1024 * 1024); + locator.setRetryInterval(retryInterval).setRetryIntervalMultiplier(retryMultiplier).setReconnectAttempts(reconnectAttempts).setConfirmationWindowSize(1024 * 1024); final ClientSessionFactoryInternal sf = (ClientSessionFactoryInternal) createSessionFactory(locator); @@ -547,27 +470,23 @@ public class ReattachTest extends ActiveMQTestBase final CountDownLatch alignLatch = new CountDownLatch(numberOfThreads); final CountDownLatch startFlag = new CountDownLatch(1); - class CreateSessionThread extends Thread - { + class CreateSessionThread extends Thread { + Throwable failure; @Override - public void run() - { - try - { + public void run() { + try { alignLatch.countDown(); startFlag.await(); - for (int i = 0; i < numberOfSessionsToCreate; i++) - { + for (int i = 0; i < numberOfSessionsToCreate; i++) { Thread.yield(); ClientSession session = sf.createSession(false, true, true); session.close(); } } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); failure = e; } @@ -575,25 +494,20 @@ public class ReattachTest extends ActiveMQTestBase } CreateSessionThread[] threads = new CreateSessionThread[numberOfThreads]; - for (int i = 0; i < numberOfThreads; i++) - { + for (int i = 0; i < numberOfThreads; i++) { threads[i] = new CreateSessionThread(); threads[i].start(); } waitForLatch(alignLatch); - timer.schedule(new TimerTask() - { + timer.schedule(new TimerTask() { @Override - public void run() - { - try - { + public void run() { + try { connFailure.fail(new ActiveMQNotConnectedException()); } - catch (Exception e) - { + catch (Exception e) { ReattachTest.log.warn("Error on the timer " + e); } } @@ -604,48 +518,39 @@ public class ReattachTest extends ActiveMQTestBase Throwable failure = null; - for (CreateSessionThread thread : threads) - { + for (CreateSessionThread thread : threads) { thread.join(); - if (thread.failure != null) - { + if (thread.failure != null) { System.out.println("Thread " + thread.getName() + " failed - " + thread.failure); failure = thread.failure; } } - if (failure != null) - { + if (failure != null) { throw failure; } sf.close(); } - finally - { + finally { timer.cancel(); - if (session != null) - { + if (session != null) { session.close(); } } } @Test - public void testCreateSessionFailBeforeSendSeveralThreads() throws Throwable - { + public void testCreateSessionFailBeforeSendSeveralThreads() throws Throwable { final long retryInterval = 500; final double retryMultiplier = 1d; final int reconnectAttempts = -1; - locator.setRetryInterval(retryInterval) - .setRetryIntervalMultiplier(retryMultiplier) - .setReconnectAttempts(reconnectAttempts) - .setConfirmationWindowSize(1024 * 1024); + locator.setRetryInterval(retryInterval).setRetryIntervalMultiplier(retryMultiplier).setReconnectAttempts(reconnectAttempts).setConfirmationWindowSize(1024 * 1024); final ClientSessionFactoryInternal sf = (ClientSessionFactoryInternal) createSessionFactory(locator); @@ -656,23 +561,20 @@ public class ReattachTest extends ActiveMQTestBase final CountDownLatch alignLatch = new CountDownLatch(numberOfThreads); final CountDownLatch startFlag = new CountDownLatch(1); - class CreateSessionThread extends Thread - { + class CreateSessionThread extends Thread { + Throwable failure; @Override - public void run() - { - try - { + public void run() { + try { alignLatch.countDown(); startFlag.await(); ClientSession session = sf.createSession(false, true, true); session.close(); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); failure = e; } @@ -680,25 +582,20 @@ public class ReattachTest extends ActiveMQTestBase } CreateSessionThread[] threads = new CreateSessionThread[numberOfThreads]; - for (int i = 0; i < numberOfThreads; i++) - { + for (int i = 0; i < numberOfThreads; i++) { threads[i] = new CreateSessionThread(); threads[i].start(); } // Sleep 3 times retryInterval, so it should at least have 3 retries - Thread t = new Thread() - { + Thread t = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { Thread.sleep(retryInterval * 3); } - catch (InterruptedException ignore) - { + catch (InterruptedException ignore) { } InVMConnector.failOnCreateConnection = false; @@ -713,18 +610,15 @@ public class ReattachTest extends ActiveMQTestBase Throwable failure = null; - for (CreateSessionThread thread : threads) - { + for (CreateSessionThread thread : threads) { thread.join(); - if (thread.failure != null) - { + if (thread.failure != null) { System.out.println("Thread " + thread.getName() + " failed - " + thread.failure); failure = thread.failure; } } - if (failure != null) - { + if (failure != null) { throw failure; } @@ -734,18 +628,14 @@ public class ReattachTest extends ActiveMQTestBase } @Test - public void testCreateQueue() throws Exception - { + public void testCreateQueue() throws Exception { final long retryInterval = 50; final double retryMultiplier = 1d; final int reconnectAttempts = -1; - locator.setRetryInterval(retryInterval) - .setRetryIntervalMultiplier(retryMultiplier) - .setReconnectAttempts(reconnectAttempts) - .setConfirmationWindowSize(1024 * 1024); + locator.setRetryInterval(retryInterval).setRetryIntervalMultiplier(retryMultiplier).setReconnectAttempts(reconnectAttempts).setConfirmationWindowSize(1024 * 1024); ClientSessionFactoryInternal sf = (ClientSessionFactoryInternal) createSessionFactory(locator); @@ -759,17 +649,13 @@ public class ReattachTest extends ActiveMQTestBase conn.fail(new ActiveMQNotConnectedException()); - Thread t = new Thread() - { + Thread t = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { Thread.sleep(retryInterval * 3); } - catch (InterruptedException ignore) - { + catch (InterruptedException ignore) { } InVMConnector.failOnCreateConnection = false; @@ -778,8 +664,7 @@ public class ReattachTest extends ActiveMQTestBase t.start(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { session.createQueue("address", "queue" + i); } @@ -808,18 +693,14 @@ public class ReattachTest extends ActiveMQTestBase } @Test - public void testReattachAttemptsSucceedsInReconnecting() throws Exception - { + public void testReattachAttemptsSucceedsInReconnecting() throws Exception { final long retryInterval = 500; final double retryMultiplier = 1d; final int reconnectAttempts = 10; - locator.setRetryInterval(retryInterval) - .setRetryIntervalMultiplier(retryMultiplier) - .setReconnectAttempts(reconnectAttempts) - .setConfirmationWindowSize(1024 * 1024); + locator.setRetryInterval(retryInterval).setRetryIntervalMultiplier(retryMultiplier).setReconnectAttempts(reconnectAttempts).setConfirmationWindowSize(1024 * 1024); ClientSessionFactoryInternal sf = (ClientSessionFactoryInternal) createSessionFactory(locator); @@ -831,13 +712,8 @@ public class ReattachTest extends ActiveMQTestBase final int numMessages = 1000; - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte) 1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); message.getBodyBuffer().writeString("aardvarks"); producer.send(message); @@ -854,8 +730,7 @@ public class ReattachTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(500); Assert.assertNotNull(message); @@ -877,18 +752,14 @@ public class ReattachTest extends ActiveMQTestBase } @Test - public void testRetryInterval() throws Exception - { + public void testRetryInterval() throws Exception { final long retryInterval = 500; final double retryMultiplier = 1d; final int reconnectAttempts = -1; - locator.setRetryInterval(retryInterval) - .setRetryIntervalMultiplier(retryMultiplier) - .setReconnectAttempts(reconnectAttempts) - .setConfirmationWindowSize(1024 * 1024); + locator.setRetryInterval(retryInterval).setRetryIntervalMultiplier(retryMultiplier).setReconnectAttempts(reconnectAttempts).setConfirmationWindowSize(1024 * 1024); ClientSessionFactoryInternal sf = (ClientSessionFactoryInternal) createSessionFactory(locator); @@ -900,13 +771,8 @@ public class ReattachTest extends ActiveMQTestBase final int numMessages = 1000; - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte) 1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); message.getBodyBuffer().writeString("aardvarks"); producer.send(message); @@ -920,17 +786,13 @@ public class ReattachTest extends ActiveMQTestBase long start = System.currentTimeMillis(); - Thread t = new Thread() - { + Thread t = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { Thread.sleep(retryInterval / 2); } - catch (InterruptedException ignore) - { + catch (InterruptedException ignore) { } InVMConnector.failOnCreateConnection = false; } @@ -942,8 +804,7 @@ public class ReattachTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(500); Assert.assertNotNull(message); @@ -971,18 +832,14 @@ public class ReattachTest extends ActiveMQTestBase } @Test - public void testExponentialBackoff() throws Exception - { + public void testExponentialBackoff() throws Exception { final long retryInterval = 500; final double retryMultiplier = 2d; final int reconnectAttempts = -1; - locator.setRetryInterval(retryInterval) - .setRetryIntervalMultiplier(retryMultiplier) - .setReconnectAttempts(reconnectAttempts) - .setConfirmationWindowSize(1024 * 1024); + locator.setRetryInterval(retryInterval).setRetryIntervalMultiplier(retryMultiplier).setReconnectAttempts(reconnectAttempts).setConfirmationWindowSize(1024 * 1024); ClientSessionFactoryInternal sf = (ClientSessionFactoryInternal) createSessionFactory(locator); @@ -994,13 +851,8 @@ public class ReattachTest extends ActiveMQTestBase final int numMessages = 1000; - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte) 1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); message.getBodyBuffer().writeString("aardvarks"); producer.send(message); @@ -1019,8 +871,7 @@ public class ReattachTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(500); Assert.assertNotNull(message); @@ -1048,8 +899,7 @@ public class ReattachTest extends ActiveMQTestBase } @Test - public void testExponentialBackoffMaxRetryInterval() throws Exception - { + public void testExponentialBackoffMaxRetryInterval() throws Exception { final long retryInterval = 500; final double retryMultiplier = 2d; @@ -1058,11 +908,7 @@ public class ReattachTest extends ActiveMQTestBase final long maxRetryInterval = 1000; - locator.setRetryInterval(retryInterval) - .setRetryIntervalMultiplier(retryMultiplier) - .setReconnectAttempts(reconnectAttempts) - .setMaxRetryInterval(maxRetryInterval) - .setConfirmationWindowSize(1024 * 1024); + locator.setRetryInterval(retryInterval).setRetryIntervalMultiplier(retryMultiplier).setReconnectAttempts(reconnectAttempts).setMaxRetryInterval(maxRetryInterval).setConfirmationWindowSize(1024 * 1024); ClientSessionFactoryInternal sf = (ClientSessionFactoryInternal) createSessionFactory(locator); @@ -1074,13 +920,8 @@ public class ReattachTest extends ActiveMQTestBase final int numMessages = 1000; - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte) 1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.putIntProperty(new SimpleString("count"), i); message.getBodyBuffer().writeString("aardvarks"); producer.send(message); @@ -1099,8 +940,7 @@ public class ReattachTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(500); Assert.assertNotNull(message); @@ -1135,8 +975,7 @@ public class ReattachTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(false, false); @@ -1148,8 +987,7 @@ public class ReattachTest extends ActiveMQTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { InVMConnector.resetFailures(); super.tearDown(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/restart/ClusterRestartTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/restart/ClusterRestartTest.java index c9e23fbd15..02f852dd1c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/restart/ClusterRestartTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/restart/ClusterRestartTest.java @@ -26,13 +26,12 @@ import org.apache.activemq.artemis.core.postoffice.Binding; import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; import org.apache.activemq.artemis.tests.integration.cluster.distribution.ClusterTestBase; -public class ClusterRestartTest extends ClusterTestBase -{ +public class ClusterRestartTest extends ClusterTestBase { + IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @Test - public void testRestartWithQueuesCreateInDiffOrder() throws Exception - { + public void testRestartWithQueuesCreateInDiffOrder() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); @@ -96,8 +95,7 @@ public class ClusterRestartTest extends ClusterTestBase } @Test - public void testRestartWithQueuesCreateInDiffOrder2() throws Exception - { + public void testRestartWithQueuesCreateInDiffOrder2() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); @@ -156,22 +154,16 @@ public class ClusterRestartTest extends ClusterTestBase System.out.println("*****************************************************************************"); } - private void printBindings(final int num) throws Exception - { - for (int i = 0; i < num; i++) - { - Collection bindings0 = getServer(i).getPostOffice() - .getBindingsForAddress(new SimpleString("queues.testaddress")) - .getBindings(); - for (Binding binding : bindings0) - { + private void printBindings(final int num) throws Exception { + for (int i = 0; i < num; i++) { + Collection bindings0 = getServer(i).getPostOffice().getBindingsForAddress(new SimpleString("queues.testaddress")).getBindings(); + for (Binding binding : bindings0) { System.out.println(binding + " on node " + i + " at " + binding.getID()); } } } - public boolean isNetty() - { + public boolean isNetty() { return true; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/HAClientTopologyTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/HAClientTopologyTest.java index 1ccec8b523..21bce504a5 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/HAClientTopologyTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/HAClientTopologyTest.java @@ -22,22 +22,19 @@ import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.core.server.cluster.impl.MessageLoadBalancingType; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -public class HAClientTopologyTest extends TopologyClusterTestBase -{ +public class HAClientTopologyTest extends TopologyClusterTestBase { + @Override - protected boolean isNetty() - { + protected boolean isNetty() { return false; } @Override - protected void setupCluster() throws Exception - { + protected void setupCluster() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); } - protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception - { + protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception { setupClusterConnection("cluster0", "queues", messageLoadBalancingType, 1, isNetty(), 0, 1, 2, 3, 4); setupClusterConnection("cluster1", "queues", messageLoadBalancingType, 1, isNetty(), 1, 0, 2, 3, 4); setupClusterConnection("cluster2", "queues", messageLoadBalancingType, 1, isNetty(), 2, 0, 1, 3, 4); @@ -46,8 +43,7 @@ public class HAClientTopologyTest extends TopologyClusterTestBase } @Override - protected void setupServers() throws Exception - { + protected void setupServers() throws Exception { setupServer(0, isFileStorage(), isNetty()); setupServer(1, isFileStorage(), isNetty()); setupServer(2, isFileStorage(), isNetty()); @@ -56,12 +52,10 @@ public class HAClientTopologyTest extends TopologyClusterTestBase } @Override - protected ServerLocator createHAServerLocator() - { + protected ServerLocator createHAServerLocator() { TransportConfiguration tc = ActiveMQTestBase.createTransportConfiguration(isNetty(), false, ActiveMQTestBase.generateParams(0, isNetty())); ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithHA(tc)); - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true); + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true); return locator; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/HAClientTopologyWithDiscoveryTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/HAClientTopologyWithDiscoveryTest.java index cef51a8afd..c63980fc04 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/HAClientTopologyWithDiscoveryTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/HAClientTopologyWithDiscoveryTest.java @@ -22,26 +22,23 @@ import org.apache.activemq.artemis.api.core.client.ActiveMQClient; import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.core.server.cluster.impl.MessageLoadBalancingType; -public class HAClientTopologyWithDiscoveryTest extends TopologyClusterTestBase -{ +public class HAClientTopologyWithDiscoveryTest extends TopologyClusterTestBase { + protected final String groupAddress = getUDPDiscoveryAddress(); protected final int groupPort = getUDPDiscoveryPort(); @Override - protected boolean isNetty() - { + protected boolean isNetty() { return false; } @Override - protected void setupCluster() throws Exception - { + protected void setupCluster() throws Exception { setupCluster(MessageLoadBalancingType.ON_DEMAND); } - protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception - { + protected void setupCluster(final MessageLoadBalancingType messageLoadBalancingType) throws Exception { setupDiscoveryClusterConnection("cluster0", 0, "dg1", "queues", messageLoadBalancingType, 1, isNetty()); setupDiscoveryClusterConnection("cluster1", 1, "dg1", "queues", messageLoadBalancingType, 1, isNetty()); setupDiscoveryClusterConnection("cluster2", 2, "dg1", "queues", messageLoadBalancingType, 1, isNetty()); @@ -50,8 +47,7 @@ public class HAClientTopologyWithDiscoveryTest extends TopologyClusterTestBase } @Override - protected void setupServers() throws Exception - { + protected void setupServers() throws Exception { setupLiveServerWithDiscovery(0, groupAddress, groupPort, isFileStorage(), isNetty(), false); setupLiveServerWithDiscovery(1, groupAddress, groupPort, isFileStorage(), isNetty(), false); setupLiveServerWithDiscovery(2, groupAddress, groupPort, isFileStorage(), isNetty(), false); @@ -60,14 +56,9 @@ public class HAClientTopologyWithDiscoveryTest extends TopologyClusterTestBase } @Override - protected ServerLocator createHAServerLocator() - { - ServerLocator locator = ActiveMQClient.createServerLocatorWithHA(new DiscoveryGroupConfiguration() - .setBroadcastEndpointFactory(new UDPBroadcastEndpointFactory() - .setGroupAddress(groupAddress) - .setGroupPort(groupPort))); - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true); + protected ServerLocator createHAServerLocator() { + ServerLocator locator = ActiveMQClient.createServerLocatorWithHA(new DiscoveryGroupConfiguration().setBroadcastEndpointFactory(new UDPBroadcastEndpointFactory().setGroupAddress(groupAddress).setGroupPort(groupPort))); + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true); addServerLocator(locator); return locator; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/IsolatedTopologyTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/IsolatedTopologyTest.java index 3e1c53d526..85f6d32d92 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/IsolatedTopologyTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/IsolatedTopologyTest.java @@ -33,12 +33,10 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -public class IsolatedTopologyTest extends ActiveMQTestBase -{ +public class IsolatedTopologyTest extends ActiveMQTestBase { @Test - public void testIsolatedClusters() throws Exception - { + public void testIsolatedClusters() throws Exception { ActiveMQServer server1 = createServer1(); @@ -58,33 +56,13 @@ public class IsolatedTopologyTest extends ActiveMQTestBase String node1 = server1.getNodeID().toString(); String node2 = server2.getNodeID().toString(); - checkTopology(server1, - "cc1", - node1, - node2, - createInVMTransportConnectorConfig(1, "srv1"), - createInVMTransportConnectorConfig(3, "srv1")); + checkTopology(server1, "cc1", node1, node2, createInVMTransportConnectorConfig(1, "srv1"), createInVMTransportConnectorConfig(3, "srv1")); - checkTopology(server2, - "cc1", - node1, - node2, - createInVMTransportConnectorConfig(1, "srv1"), - createInVMTransportConnectorConfig(3, "srv1")); + checkTopology(server2, "cc1", node1, node2, createInVMTransportConnectorConfig(1, "srv1"), createInVMTransportConnectorConfig(3, "srv1")); - checkTopology(server1, - "cc2", - node1, - node2, - createInVMTransportConnectorConfig(2, "srv1"), - createInVMTransportConnectorConfig(4, "srv1")); + checkTopology(server1, "cc2", node1, node2, createInVMTransportConnectorConfig(2, "srv1"), createInVMTransportConnectorConfig(4, "srv1")); - checkTopology(server2, - "cc2", - node1, - node2, - createInVMTransportConnectorConfig(2, "srv1"), - createInVMTransportConnectorConfig(4, "srv1")); + checkTopology(server2, "cc2", node1, node2, createInVMTransportConnectorConfig(2, "srv1"), createInVMTransportConnectorConfig(4, "srv1")); Thread.sleep(500); } @@ -93,8 +71,7 @@ public class IsolatedTopologyTest extends ActiveMQTestBase final String nodeId1, final String nodeId2, final TransportConfiguration cfg1, - final TransportConfiguration cfg2) - { + final TransportConfiguration cfg2) { Topology topology = serverParameter.getClusterManager().getClusterConnection(clusterName).getTopology(); TopologyMemberImpl member1 = topology.getMember(nodeId1); @@ -103,119 +80,65 @@ public class IsolatedTopologyTest extends ActiveMQTestBase Assert.assertEquals(member2.getLive().getParams().toString(), cfg2.getParams().toString()); } - private ActiveMQServer createServer1() throws Exception - { + private ActiveMQServer createServer1() throws Exception { Map params = new HashMap(); params.put(TransportConstants.CLUSTER_CONNECTION, "cc1"); params.put(org.apache.activemq.artemis.core.remoting.impl.invm.TransportConstants.SERVER_ID_PROP_NAME, "1"); - TransportConfiguration acceptor1VM1 = new TransportConfiguration(ActiveMQTestBase.INVM_ACCEPTOR_FACTORY, - params, - "acceptor-cc1"); + TransportConfiguration acceptor1VM1 = new TransportConfiguration(ActiveMQTestBase.INVM_ACCEPTOR_FACTORY, params, "acceptor-cc1"); params = new HashMap(); params.put(TransportConstants.CLUSTER_CONNECTION, "cc2"); params.put(org.apache.activemq.artemis.core.remoting.impl.invm.TransportConstants.SERVER_ID_PROP_NAME, "2"); - TransportConfiguration acceptor2VM1 = new TransportConfiguration(ActiveMQTestBase.INVM_ACCEPTOR_FACTORY, - params, - "acceptor-cc2"); + TransportConfiguration acceptor2VM1 = new TransportConfiguration(ActiveMQTestBase.INVM_ACCEPTOR_FACTORY, params, "acceptor-cc2"); List connectTo = new ArrayList(); connectTo.add("other-cc1"); - ClusterConnectionConfiguration server1CC1 = new ClusterConnectionConfiguration() - .setName("cc1") - .setAddress("jms") - .setConnectorName("local-cc1") - .setRetryInterval(250) - .setConfirmationWindowSize(1024) - .setMessageLoadBalancingType(MessageLoadBalancingType.ON_DEMAND) - .setStaticConnectors(connectTo); + ClusterConnectionConfiguration server1CC1 = new ClusterConnectionConfiguration().setName("cc1").setAddress("jms").setConnectorName("local-cc1").setRetryInterval(250).setConfirmationWindowSize(1024).setMessageLoadBalancingType(MessageLoadBalancingType.ON_DEMAND).setStaticConnectors(connectTo); ArrayList connectTo2 = new ArrayList(); connectTo2.add("other-cc2"); - ClusterConnectionConfiguration server1CC2 = new ClusterConnectionConfiguration() - .setName("cc2") - .setAddress("jms") - .setConnectorName("local-cc2") - .setRetryInterval(250) - .setConfirmationWindowSize(1024) - .setMessageLoadBalancingType(MessageLoadBalancingType.ON_DEMAND) - .setStaticConnectors(connectTo2); + ClusterConnectionConfiguration server1CC2 = new ClusterConnectionConfiguration().setName("cc2").setAddress("jms").setConnectorName("local-cc2").setRetryInterval(250).setConfirmationWindowSize(1024).setMessageLoadBalancingType(MessageLoadBalancingType.ON_DEMAND).setStaticConnectors(connectTo2); // Server1 with two acceptors, each acceptor on a different cluster connection // talking to a different connector. // i.e. two cluster connections isolated on the same node - Configuration config1 = createBasicConfig(1) - .addConnectorConfiguration("local-cc1", createInVMTransportConnectorConfig(1, "local-cc1")) - .addConnectorConfiguration("local-cc2", createInVMTransportConnectorConfig(2, "local-cc2")) - .addConnectorConfiguration("other-cc1", createInVMTransportConnectorConfig(3, "other-cc1")) - .addConnectorConfiguration("other-cc2", createInVMTransportConnectorConfig(4, "other-cc2")) - .addAcceptorConfiguration(acceptor1VM1) - .addAcceptorConfiguration(acceptor2VM1) - .addClusterConfiguration(server1CC1) - .addClusterConfiguration(server1CC2); + Configuration config1 = createBasicConfig(1).addConnectorConfiguration("local-cc1", createInVMTransportConnectorConfig(1, "local-cc1")).addConnectorConfiguration("local-cc2", createInVMTransportConnectorConfig(2, "local-cc2")).addConnectorConfiguration("other-cc1", createInVMTransportConnectorConfig(3, "other-cc1")).addConnectorConfiguration("other-cc2", createInVMTransportConnectorConfig(4, "other-cc2")).addAcceptorConfiguration(acceptor1VM1).addAcceptorConfiguration(acceptor2VM1).addClusterConfiguration(server1CC1).addClusterConfiguration(server1CC2); return createServer(false, config1); } - private ActiveMQServer createServer2() throws Exception - { + private ActiveMQServer createServer2() throws Exception { Map params = new HashMap(); params.put(TransportConstants.CLUSTER_CONNECTION, "cc1"); params.put(org.apache.activemq.artemis.core.remoting.impl.invm.TransportConstants.SERVER_ID_PROP_NAME, "3"); - TransportConfiguration acceptor1VM1 = new TransportConfiguration(ActiveMQTestBase.INVM_ACCEPTOR_FACTORY, - params, - "acceptor-cc1"); + TransportConfiguration acceptor1VM1 = new TransportConfiguration(ActiveMQTestBase.INVM_ACCEPTOR_FACTORY, params, "acceptor-cc1"); params = new HashMap(); params.put(TransportConstants.CLUSTER_CONNECTION, "cc2"); params.put(org.apache.activemq.artemis.core.remoting.impl.invm.TransportConstants.SERVER_ID_PROP_NAME, "4"); - TransportConfiguration acceptor2VM1 = new TransportConfiguration(ActiveMQTestBase.INVM_ACCEPTOR_FACTORY, - params, - "acceptor-cc2"); + TransportConfiguration acceptor2VM1 = new TransportConfiguration(ActiveMQTestBase.INVM_ACCEPTOR_FACTORY, params, "acceptor-cc2"); List connectTo = new ArrayList(); connectTo.add("other-cc1"); - ClusterConnectionConfiguration server1CC1 = new ClusterConnectionConfiguration() - .setName("cc1") - .setAddress("jms") - .setConnectorName("local-cc1") - .setRetryInterval(250) - .setConfirmationWindowSize(1024) - .setMessageLoadBalancingType(MessageLoadBalancingType.ON_DEMAND) - .setStaticConnectors(connectTo); + ClusterConnectionConfiguration server1CC1 = new ClusterConnectionConfiguration().setName("cc1").setAddress("jms").setConnectorName("local-cc1").setRetryInterval(250).setConfirmationWindowSize(1024).setMessageLoadBalancingType(MessageLoadBalancingType.ON_DEMAND).setStaticConnectors(connectTo); List connectTo2 = new ArrayList(); connectTo2.add("other-cc2"); - ClusterConnectionConfiguration server1CC2 = new ClusterConnectionConfiguration() - .setName("cc2") - .setAddress("jms") - .setConnectorName("local-cc2") - .setRetryInterval(250) - .setConfirmationWindowSize(1024) - .setMessageLoadBalancingType(MessageLoadBalancingType.ON_DEMAND) - .setStaticConnectors(connectTo2); + ClusterConnectionConfiguration server1CC2 = new ClusterConnectionConfiguration().setName("cc2").setAddress("jms").setConnectorName("local-cc2").setRetryInterval(250).setConfirmationWindowSize(1024).setMessageLoadBalancingType(MessageLoadBalancingType.ON_DEMAND).setStaticConnectors(connectTo2); // Server2 with two acceptors, each acceptor on a different cluster connection // talking to a different connector. // i.e. two cluster connections isolated on the same node - Configuration config1 = createBasicConfig(2) - .addAcceptorConfiguration(acceptor1VM1) - .addAcceptorConfiguration(acceptor2VM1) - .addConnectorConfiguration("local-cc1", createInVMTransportConnectorConfig(3, "local-cc1")) - .addConnectorConfiguration("local-cc2", createInVMTransportConnectorConfig(4, "local-cc2")) - .addConnectorConfiguration("other-cc1", createInVMTransportConnectorConfig(1, "other-cc1")) - .addConnectorConfiguration("other-cc2", createInVMTransportConnectorConfig(2, "other-cc2")) - .addClusterConfiguration(server1CC1) - .addClusterConfiguration(server1CC2); + Configuration config1 = createBasicConfig(2).addAcceptorConfiguration(acceptor1VM1).addAcceptorConfiguration(acceptor2VM1).addConnectorConfiguration("local-cc1", createInVMTransportConnectorConfig(3, "local-cc1")).addConnectorConfiguration("local-cc2", createInVMTransportConnectorConfig(4, "local-cc2")).addConnectorConfiguration("other-cc1", createInVMTransportConnectorConfig(1, "other-cc1")).addConnectorConfiguration("other-cc2", createInVMTransportConnectorConfig(2, "other-cc2")).addClusterConfiguration(server1CC1).addClusterConfiguration(server1CC2); return createServer(false, config1); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/NettyHAClientTopologyTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/NettyHAClientTopologyTest.java index 4938a5e4d0..33c384ef7e 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/NettyHAClientTopologyTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/NettyHAClientTopologyTest.java @@ -16,12 +16,10 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.topology; -public class NettyHAClientTopologyTest extends HAClientTopologyTest -{ +public class NettyHAClientTopologyTest extends HAClientTopologyTest { @Override - protected boolean isNetty() - { + protected boolean isNetty() { return true; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/NettyHAClientTopologyWithDiscoveryTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/NettyHAClientTopologyWithDiscoveryTest.java index e337ae77d4..0066ae188a 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/NettyHAClientTopologyWithDiscoveryTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/NettyHAClientTopologyWithDiscoveryTest.java @@ -16,12 +16,10 @@ */ package org.apache.activemq.artemis.tests.integration.cluster.topology; -public class NettyHAClientTopologyWithDiscoveryTest extends HAClientTopologyWithDiscoveryTest -{ +public class NettyHAClientTopologyWithDiscoveryTest extends HAClientTopologyWithDiscoveryTest { @Override - protected boolean isNetty() - { + protected boolean isNetty() { return true; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/NonHATopologyTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/NonHATopologyTest.java index 701722dd2b..4bad2595a7 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/NonHATopologyTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/NonHATopologyTest.java @@ -39,58 +39,40 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; * * Created to verify HORNETQ-913 / AS7-4548 */ -public class NonHATopologyTest extends ActiveMQTestBase -{ +public class NonHATopologyTest extends ActiveMQTestBase { @Test - public void testNetty() throws Exception - { + public void testNetty() throws Exception { internalTest(true); } @Test - public void testInVM() throws Exception - { + public void testInVM() throws Exception { internalTest(false); } - public void internalTest(boolean isNetty) throws Exception - { + public void internalTest(boolean isNetty) throws Exception { ActiveMQServer server = null; ServerLocatorInternal locator = null; - try - { + try { server = createServer(false, isNetty); - if (!isNetty) - { - server.getConfiguration() - .getAcceptorConfigurations() - .add(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY)); - server.getConfiguration() - .getConnectorConfigurations() - .put("netty", new TransportConfiguration(NETTY_CONNECTOR_FACTORY)); + if (!isNetty) { + server.getConfiguration().getAcceptorConfigurations().add(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY)); + server.getConfiguration().getConnectorConfigurations().put("netty", new TransportConfiguration(NETTY_CONNECTOR_FACTORY)); ArrayList list = new ArrayList(); list.add("netty"); Configuration config = server.getConfiguration(); - config.getClusterConfigurations().add(new ClusterConnectionConfiguration() - .setName("tst") - .setAddress("jms") - .setConnectorName("netty") - .setRetryInterval(1000) - .setConfirmationWindowSize(1000) - .setMessageLoadBalancingType(MessageLoadBalancingType.ON_DEMAND) - .setStaticConnectors(list) - .setAllowDirectConnectionsOnly(true)); + config.getClusterConfigurations().add(new ClusterConnectionConfiguration().setName("tst").setAddress("jms").setConnectorName("netty").setRetryInterval(1000).setConfirmationWindowSize(1000).setMessageLoadBalancingType(MessageLoadBalancingType.ON_DEMAND).setStaticConnectors(list).setAllowDirectConnectionsOnly(true)); } server.start(); - locator = (ServerLocatorInternal)createNonHALocator(isNetty); + locator = (ServerLocatorInternal) createNonHALocator(isNetty); ClientSessionFactory factory = createSessionFactory(locator); @@ -100,36 +82,28 @@ public class NonHATopologyTest extends ActiveMQTestBase factory.close(); - if (!isNetty) - { + if (!isNetty) { TopologyMemberImpl member = topology.getMembers().iterator().next(); - if (isNetty) - { + if (isNetty) { assertEquals(NettyConnectorFactory.class.getName(), member.getLive().getFactoryClassName()); } - else - { + else { assertEquals(InVMConnectorFactory.class.getName(), member.getLive().getFactoryClassName()); } } } - finally - { - try - { + finally { + try { locator.close(); } - catch (Exception ignored) - { + catch (Exception ignored) { } - try - { + try { server.stop(); } - catch (Exception ignored) - { + catch (Exception ignored) { } server = null; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/TopologyClusterTestBase.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/TopologyClusterTestBase.java index 3f28d3198b..ba9eb2aca6 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/TopologyClusterTestBase.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/topology/TopologyClusterTestBase.java @@ -47,11 +47,10 @@ import java.util.concurrent.CountDownLatch; import static java.util.concurrent.TimeUnit.SECONDS; -public abstract class TopologyClusterTestBase extends ClusterTestBase -{ +public abstract class TopologyClusterTestBase extends ClusterTestBase { + + private static final class LatchListener implements ClusterTopologyListener { - private static final class LatchListener implements ClusterTopologyListener - { private final CountDownLatch upLatch; private final List nodes; private final CountDownLatch downLatch; @@ -61,30 +60,25 @@ public abstract class TopologyClusterTestBase extends ClusterTestBase * @param nodes * @param downLatch */ - private LatchListener(CountDownLatch upLatch, List nodes, CountDownLatch downLatch) - { + private LatchListener(CountDownLatch upLatch, List nodes, CountDownLatch downLatch) { this.upLatch = upLatch; this.nodes = nodes; this.downLatch = downLatch; } @Override - public synchronized void nodeUP(TopologyMember topologyMember, boolean last) - { + public synchronized void nodeUP(TopologyMember topologyMember, boolean last) { final String nodeID = topologyMember.getNodeId(); - if (!nodes.contains(nodeID)) - { + if (!nodes.contains(nodeID)) { nodes.add(nodeID); upLatch.countDown(); } } @Override - public synchronized void nodeDown(final long uniqueEventID, String nodeID) - { - if (nodes.contains(nodeID)) - { + public synchronized void nodeDown(final long uniqueEventID, String nodeID) { + if (nodes.contains(nodeID)) { nodes.remove(nodeID); downLatch.countDown(); } @@ -103,8 +97,7 @@ public abstract class TopologyClusterTestBase extends ClusterTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); setupServers(); @@ -115,74 +108,59 @@ public abstract class TopologyClusterTestBase extends ClusterTestBase /** * Check that the actual list of received nodeIDs correspond to the expected order of nodes */ - protected void checkOrder(int[] expected, String[] nodeIDs, List actual) - { + protected void checkOrder(int[] expected, String[] nodeIDs, List actual) { Assert.assertEquals(expected.length, actual.size()); - for (int i = 0; i < expected.length; i++) - { + for (int i = 0; i < expected.length; i++) { Assert.assertEquals("did not receive expected nodeID at " + i, nodeIDs[expected[i]], actual.get(i)); } } - protected void checkContains(int[] expected, String[] nodeIDs, List actual) - { + protected void checkContains(int[] expected, String[] nodeIDs, List actual) { long start = System.currentTimeMillis(); - do - { - if (expected.length != actual.size()) - { + do { + if (expected.length != actual.size()) { continue; } boolean ok = true; - for (int element : expected) - { + for (int element : expected) { ok = (ok && actual.contains(nodeIDs[element])); } - if (ok) - { + if (ok) { return; } } while (System.currentTimeMillis() - start < 5000); Assert.fail("did not contain all expected node ID: " + actual); } - protected String[] getNodeIDs(int... nodes) - { + protected String[] getNodeIDs(int... nodes) { String[] nodeIDs = new String[nodes.length]; - for (int i = 0; i < nodes.length; i++) - { + for (int i = 0; i < nodes.length; i++) { nodeIDs[i] = servers[i].getNodeID().toString(); } return nodeIDs; } - protected ClientSession checkSessionOrReconnect(ClientSession session, ServerLocator locator) throws Exception - { - try - { + protected ClientSession checkSessionOrReconnect(ClientSession session, ServerLocator locator) throws Exception { + try { String rand = RandomUtil.randomString(); session.createQueue(rand, rand); session.deleteQueue(rand); return session; } - catch (ActiveMQObjectClosedException oce) - { + catch (ActiveMQObjectClosedException oce) { ClientSessionFactory sf = createSessionFactory(locator); return sf.createSession(); } - catch (ActiveMQUnBlockedException obe) - { + catch (ActiveMQUnBlockedException obe) { ClientSessionFactory sf = createSessionFactory(locator); return sf.createSession(); } } - protected void waitForClusterConnections(final int node, final int expected) throws Exception - { + protected void waitForClusterConnections(final int node, final int expected) throws Exception { ActiveMQServer server = servers[node]; - if (server == null) - { + if (server == null) { throw new IllegalArgumentException("No server at " + node); } @@ -191,39 +169,31 @@ public abstract class TopologyClusterTestBase extends ClusterTestBase long start = System.currentTimeMillis(); int nodesCount; - do - { + do { nodesCount = 0; - for (ClusterConnection clusterConn : clusterManager.getClusterConnections()) - { + for (ClusterConnection clusterConn : clusterManager.getClusterConnections()) { Map nodes = clusterConn.getNodes(); - for (String id : nodes.keySet()) - { - if (clusterConn.isNodeActive(id)) - { + for (String id : nodes.keySet()) { + if (clusterConn.isNodeActive(id)) { nodesCount++; } } } - if (nodesCount == expected) - { + if (nodesCount == expected) { return; } Thread.sleep(10); - } - while (System.currentTimeMillis() - start < ActiveMQTestBase.WAIT_TIMEOUT); + } while (System.currentTimeMillis() - start < ActiveMQTestBase.WAIT_TIMEOUT); log.error(clusterDescription(servers[node])); Assert.assertEquals("Timed out waiting for cluster connections for server " + node, expected, nodesCount); } - @Test - public void testReceiveNotificationsWhenOtherNodesAreStartedAndStopped() throws Throwable - { + public void testReceiveNotificationsWhenOtherNodesAreStartedAndStopped() throws Throwable { startServers(0); ServerLocator locator = createHAServerLocator(); @@ -264,8 +234,7 @@ public abstract class TopologyClusterTestBase extends ClusterTestBase } @Test - public void testReceiveNotifications() throws Throwable - { + public void testReceiveNotifications() throws Throwable { startServers(0, 1, 2, 3, 4); String[] nodeIDs = getNodeIDs(0, 1, 2, 3, 4); @@ -314,10 +283,8 @@ public abstract class TopologyClusterTestBase extends ClusterTestBase sf.close(); } - @Test - public void testStopNodes() throws Throwable - { + public void testStopNodes() throws Throwable { startServers(0, 1, 2, 3, 4); String[] nodeIDs = getNodeIDs(0, 1, 2, 3, 4); @@ -363,25 +330,20 @@ public abstract class TopologyClusterTestBase extends ClusterTestBase stopServers(1); Assert.assertFalse(servers[1].isStarted()); - try - { + try { session = checkSessionOrReconnect(session, locator); Assert.fail(); } - catch (ActiveMQException expected) - { + catch (ActiveMQException expected) { Assert.assertEquals(ActiveMQExceptionType.NOT_CONNECTED, expected.getType()); } } @Test - public void testWrongPasswordTriggersClusterConnectionStop() throws Exception - { + public void testWrongPasswordTriggersClusterConnectionStop() throws Exception { Configuration config = servers[4].getConfiguration(); - for (ActiveMQServer s : servers) - { - if (s != null) - { + for (ActiveMQServer s : servers) { + if (s != null) { s.getConfiguration().setSecurityEnabled(true); } } @@ -389,10 +351,8 @@ public abstract class TopologyClusterTestBase extends ClusterTestBase config.setClusterPassword(config.getClusterPassword() + "-1-2-3-"); startServers(0, 1, 2, 4, 3); int n = 0; - while (n++ < 10) - { - if (!servers[4].getClusterManager().isStarted()) - { + while (n++ < 10) { + if (!servers[4].getClusterManager().isStarted()) { break; } Thread.sleep(100); @@ -412,8 +372,7 @@ public abstract class TopologyClusterTestBase extends ClusterTestBase } @Test - public void testMultipleClientSessionFactories() throws Throwable - { + public void testMultipleClientSessionFactories() throws Throwable { startServers(0, 1, 2, 3, 4); String[] nodeIDs = getNodeIDs(0, 1, 2, 3, 4); @@ -431,12 +390,7 @@ public abstract class TopologyClusterTestBase extends ClusterTestBase locator.addClusterTopologyListener(new LatchListener(upLatch, nodes, downLatch)); - ClientSessionFactory[] sfs = new ClientSessionFactory[]{ - locator.createSessionFactory(), - locator.createSessionFactory(), - locator.createSessionFactory(), - locator.createSessionFactory(), - locator.createSessionFactory()}; + ClientSessionFactory[] sfs = new ClientSessionFactory[]{locator.createSessionFactory(), locator.createSessionFactory(), locator.createSessionFactory(), locator.createSessionFactory(), locator.createSessionFactory()}; Assert.assertTrue("Was not notified that all servers are UP", upLatch.await(10, SECONDS)); checkContains(new int[]{0, 1, 2, 3, 4}, nodeIDs, nodes); @@ -444,15 +398,13 @@ public abstract class TopologyClusterTestBase extends ClusterTestBase stopServers(4, 2, 3, 1); boolean ok = downLatch.await(10, SECONDS); - if (!ok) - { + if (!ok) { log.warn("TopologyClusterTestBase.testMultipleClientSessionFactories will fail"); } Assert.assertTrue("Was not notified that all servers are Down", ok); checkContains(new int[]{0}, nodeIDs, nodes); - for (ClientSessionFactory sf : sfs) - { + for (ClientSessionFactory sf : sfs) { sf.close(); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/util/BackupSyncDelay.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/util/BackupSyncDelay.java index d1fd1f348e..7b264402c4 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/util/BackupSyncDelay.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/util/BackupSyncDelay.java @@ -56,15 +56,13 @@ import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; *
  • not send an answer to it, when we deliver the packet later. * */ -public class BackupSyncDelay implements Interceptor -{ +public class BackupSyncDelay implements Interceptor { private final ReplicationChannelHandler handler; private final ActiveMQServer backup; private final ActiveMQServer live; - public void deliverUpToDateMsg() - { + public void deliverUpToDateMsg() { live.getRemotingService().removeIncomingInterceptor(this); if (backup.isStarted()) handler.deliver(); @@ -75,8 +73,7 @@ public class BackupSyncDelay implements Interceptor * @param live * @param packetCode which packet is going to be intercepted. */ - public BackupSyncDelay(ActiveMQServer backup, ActiveMQServer live, byte packetCode) - { + public BackupSyncDelay(ActiveMQServer backup, ActiveMQServer live, byte packetCode) { this.backup = backup; this.live = live; live.getRemotingService().addIncomingInterceptor(this); @@ -87,18 +84,14 @@ public class BackupSyncDelay implements Interceptor * @param backupServer * @param liveServer */ - public BackupSyncDelay(TestableServer backupServer, TestableServer liveServer) - { + public BackupSyncDelay(TestableServer backupServer, TestableServer liveServer) { this(backupServer.getServer(), liveServer.getServer(), PacketImpl.REPLICATION_START_FINISH_SYNC); } @Override - public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException - { - if (packet.getType() == PacketImpl.BACKUP_REGISTRATION) - { - try - { + public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException { + if (packet.getType() == PacketImpl.BACKUP_REGISTRATION) { + try { SharedNothingBackupActivation activation = (SharedNothingBackupActivation) backup.getActivation(); ReplicationEndpoint repEnd = activation.getReplicationEndpoint(); handler.addSubHandler(repEnd); @@ -107,21 +100,19 @@ public class BackupSyncDelay implements Interceptor handler.setChannel(repChannel); live.getRemotingService().removeIncomingInterceptor(this); } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } } return true; } - public static class ReplicationChannelHandler implements ChannelHandler - { + public static class ReplicationChannelHandler implements ChannelHandler { - public ReplicationChannelHandler(byte type) - { + public ReplicationChannelHandler(byte type) { this.typeToIntercept = type; } + private ReplicationEndpoint handler; private Packet onHold; private Channel channel; @@ -131,64 +122,52 @@ public class BackupSyncDelay implements Interceptor private boolean mustHold = true; private final byte typeToIntercept; - public void addSubHandler(ReplicationEndpoint handler) - { + public void addSubHandler(ReplicationEndpoint handler) { this.handler = handler; } - public synchronized void deliver() - { + public synchronized void deliver() { deliver = true; if (!receivedUpToDate) return; if (delivered) return; - if (onHold == null) - { + if (onHold == null) { throw new NullPointerException("Don't have the 'sync is done' packet to deliver"); } // Use wrapper to avoid sending a response ChannelWrapper wrapper = new ChannelWrapper(channel); handler.setChannel(wrapper); - try - { + try { handler.handlePacket(onHold); delivered = true; } - finally - { + finally { handler.setChannel(channel); channel.setHandler(handler); onHold = null; } } - public void setChannel(Channel channel) - { + public void setChannel(Channel channel) { this.channel = channel; } - public void setHold(boolean hold) - { + public void setHold(boolean hold) { mustHold = hold; } @Override - public synchronized void handlePacket(Packet packet) - { - if (onHold != null && deliver) - { + public synchronized void handlePacket(Packet packet) { + if (onHold != null && deliver) { deliver(); } - if (typeToIntercept == PacketImpl.REPLICATION_START_FINISH_SYNC) - { - if (packet.getType() == PacketImpl.REPLICATION_START_FINISH_SYNC && mustHold) - { - ReplicationStartSyncMessage syncMsg = (ReplicationStartSyncMessage)packet; - if (syncMsg.isSynchronizationFinished() && !deliver) - { + if (typeToIntercept == PacketImpl.REPLICATION_START_FINISH_SYNC) { + if (packet.getType() == PacketImpl.REPLICATION_START_FINISH_SYNC && mustHold) { + ReplicationStartSyncMessage syncMsg = (ReplicationStartSyncMessage) packet; + if (syncMsg.isSynchronizationFinished() && !deliver) { receivedUpToDate = true; assert onHold == null; onHold = packet; @@ -198,8 +177,7 @@ public class BackupSyncDelay implements Interceptor } } } - else if (typeToIntercept == packet.getType()) - { + else if (typeToIntercept == packet.getType()) { channel.send(new ReplicationResponseMessage()); return; } @@ -209,175 +187,147 @@ public class BackupSyncDelay implements Interceptor } - public static class ChannelWrapper implements Channel - { + public static class ChannelWrapper implements Channel { private final Channel channel; - public ChannelWrapper(Channel channel) - { + public ChannelWrapper(Channel channel) { this.channel = channel; } @Override - public String toString() - { + public String toString() { return "ChannelWrapper(" + channel + ")"; } @Override - public long getID() - { + public long getID() { return channel.getID(); } @Override - public boolean send(Packet packet) - { + public boolean send(Packet packet) { // no-op // channel.send(packet); return true; } @Override - public boolean sendBatched(Packet packet) - { + public boolean sendBatched(Packet packet) { throw new UnsupportedOperationException(); } @Override - public boolean sendAndFlush(Packet packet) - { + public boolean sendAndFlush(Packet packet) { throw new UnsupportedOperationException(); } @Override - public Packet sendBlocking(Packet packet, byte expected) throws ActiveMQException - { + public Packet sendBlocking(Packet packet, byte expected) throws ActiveMQException { throw new UnsupportedOperationException(); } @Override - public void setHandler(ChannelHandler handler) - { + public void setHandler(ChannelHandler handler) { throw new UnsupportedOperationException(); } - public ChannelHandler getHandler() - { + public ChannelHandler getHandler() { throw new UnsupportedOperationException(); } @Override - public void close() - { + public void close() { throw new UnsupportedOperationException(); } @Override - public void transferConnection(CoreRemotingConnection newConnection) - { + public void transferConnection(CoreRemotingConnection newConnection) { throw new UnsupportedOperationException(); } @Override - public void replayCommands(int lastConfirmedCommandID) - { + public void replayCommands(int lastConfirmedCommandID) { throw new UnsupportedOperationException(); } @Override - public int getLastConfirmedCommandID() - { + public int getLastConfirmedCommandID() { throw new UnsupportedOperationException(); } @Override - public void lock() - { + public void lock() { throw new UnsupportedOperationException(); } @Override - public void unlock() - { + public void unlock() { throw new UnsupportedOperationException(); } @Override - public void returnBlocking() - { + public void returnBlocking() { throw new UnsupportedOperationException(); } @Override - public void returnBlocking(Throwable cause) - { + public void returnBlocking(Throwable cause) { throw new UnsupportedOperationException(); } @Override - public Lock getLock() - { + public Lock getLock() { throw new UnsupportedOperationException(); } @Override - public CoreRemotingConnection getConnection() - { + public CoreRemotingConnection getConnection() { throw new UnsupportedOperationException(); } @Override - public void confirm(Packet packet) - { + public void confirm(Packet packet) { throw new UnsupportedOperationException(); } @Override - public void setCommandConfirmationHandler(CommandConfirmationHandler handler) - { + public void setCommandConfirmationHandler(CommandConfirmationHandler handler) { throw new UnsupportedOperationException(); } @Override - public void flushConfirmations() - { + public void flushConfirmations() { throw new UnsupportedOperationException(); } @Override - public void handlePacket(Packet packet) - { + public void handlePacket(Packet packet) { throw new UnsupportedOperationException(); } @Override - public void clearCommands() - { + public void clearCommands() { throw new UnsupportedOperationException(); } @Override - public int getConfirmationWindowSize() - { + public int getConfirmationWindowSize() { throw new UnsupportedOperationException(); } @Override - public void setTransferring(boolean transferring) - { + public void setTransferring(boolean transferring) { throw new UnsupportedOperationException(); } @Override - public boolean supports(byte packetID) - { + public boolean supports(byte packetID) { return true; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/util/MultiServerTestBase.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/util/MultiServerTestBase.java index 6b3605ea19..a22d23eb9a 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/util/MultiServerTestBase.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/util/MultiServerTestBase.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.cluster.util; + import org.apache.activemq.artemis.core.server.cluster.impl.MessageLoadBalancingType; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.core.config.ha.ReplicaPolicyConfiguration; @@ -37,9 +38,7 @@ import org.apache.activemq.artemis.core.server.ActiveMQServers; import org.apache.activemq.artemis.core.server.NodeManager; import org.apache.activemq.artemis.core.server.impl.InVMNodeManager; -public class MultiServerTestBase extends ActiveMQTestBase -{ - +public class MultiServerTestBase extends ActiveMQTestBase { protected ActiveMQServer[] servers; @@ -47,73 +46,57 @@ public class MultiServerTestBase extends ActiveMQTestBase protected NodeManager[] nodeManagers; - protected int getNumberOfServers() - { + protected int getNumberOfServers() { return 5; } - protected boolean useBackups() - { + protected boolean useBackups() { return true; } - protected boolean useRealFiles() - { + protected boolean useRealFiles() { return true; } - protected boolean useNetty() - { + protected boolean useNetty() { return false; } - protected boolean useSharedStorage() - { + protected boolean useSharedStorage() { return true; } - - protected final ServerLocator createLocator(final boolean ha, final int serverID) - { + protected final ServerLocator createLocator(final boolean ha, final int serverID) { TransportConfiguration targetConfig = createTransportConfiguration(useNetty(), false, generateParams(serverID, useNetty())); - if (ha) - { + if (ha) { ServerLocator locator = ActiveMQClient.createServerLocatorWithHA(targetConfig); return addServerLocator(locator); } - else - { + else { ServerLocator locator = ActiveMQClient.createServerLocatorWithoutHA(targetConfig); return addServerLocator(locator); } } - @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); servers = new ActiveMQServer[getNumberOfServers()]; - if (useBackups()) - { + if (useBackups()) { backupServers = new ActiveMQServer[getNumberOfServers()]; } - if (useBackups()) - { + if (useBackups()) { nodeManagers = new NodeManager[getNumberOfServers()]; } - - for (int i = 0; i < getNumberOfServers(); i++) - { + for (int i = 0; i < getNumberOfServers(); i++) { Pair nodeServer = setupLiveServer(i, useRealFiles(), useSharedStorage()); this.servers[i] = nodeServer.getA(); - if (useBackups()) - { + if (useBackups()) { this.nodeManagers[i] = nodeServer.getB(); // The backup id here will be only useful if doing replication @@ -123,51 +106,40 @@ public class MultiServerTestBase extends ActiveMQTestBase } } - protected void startServers() throws Exception - { - for (ActiveMQServer server : servers) - { + protected void startServers() throws Exception { + for (ActiveMQServer server : servers) { server.start(); } - for (ActiveMQServer server: servers) - { + for (ActiveMQServer server : servers) { waitForServerToStart(server); } - if (backupServers != null) - { - for (ActiveMQServer server : backupServers) - { + if (backupServers != null) { + for (ActiveMQServer server : backupServers) { server.start(); } - for (ActiveMQServer server: backupServers) - { + for (ActiveMQServer server : backupServers) { waitForServerToStart(server); } } - for (ActiveMQServer server : servers) - { + for (ActiveMQServer server : servers) { waitForTopology(server, getNumberOfServers(), useBackups() ? getNumberOfServers() : 0); } } - public void startServers(int ... serverID) throws Exception - { - for (int s : serverID) - { + public void startServers(int... serverID) throws Exception { + for (int s : serverID) { servers[s].start(); waitForServerToStart(servers[s]); } } - public void startBackups(int ... serverID) throws Exception - { - for (int s : serverID) - { + public void startBackups(int... serverID) throws Exception { + for (int s : serverID) { backupServers[s].start(); waitForServerToStart(backupServers[s]); } @@ -175,32 +147,22 @@ public class MultiServerTestBase extends ActiveMQTestBase } protected Pair setupLiveServer(final int node, - final boolean realFiles, - final boolean sharedStorage) throws Exception - { + final boolean realFiles, + final boolean sharedStorage) throws Exception { NodeManager nodeManager = null; TransportConfiguration serverConfigAcceptor = createTransportConfiguration(useNetty(), true, generateParams(node, useNetty())); TransportConfiguration thisConnector = createTransportConfiguration(useNetty(), false, generateParams(node, useNetty())); - if (sharedStorage) - { + if (sharedStorage) { nodeManager = new InVMNodeManager(false); } - Configuration configuration = createBasicConfig(node) - .setJournalMaxIO_AIO(1000) - .setThreadPoolMaxSize(10) - .clearAcceptorConfigurations() - .addAcceptorConfiguration(serverConfigAcceptor) - .addConnectorConfiguration("thisConnector", thisConnector) - .setHAPolicyConfiguration(sharedStorage ? new SharedStoreMasterPolicyConfiguration() : new ReplicatedPolicyConfiguration()); + Configuration configuration = createBasicConfig(node).setJournalMaxIO_AIO(1000).setThreadPoolMaxSize(10).clearAcceptorConfigurations().addAcceptorConfiguration(serverConfigAcceptor).addConnectorConfiguration("thisConnector", thisConnector).setHAPolicyConfiguration(sharedStorage ? new SharedStoreMasterPolicyConfiguration() : new ReplicatedPolicyConfiguration()); List targetServersOnConnection = new ArrayList(); - for (int targetNode = 0; targetNode < getNumberOfServers(); targetNode++) - { - if (targetNode == node) - { + for (int targetNode = 0; targetNode < getNumberOfServers(); targetNode++) { + if (targetNode == node) { continue; } String targetConnectorName = "target-" + targetNode; @@ -216,88 +178,62 @@ public class MultiServerTestBase extends ActiveMQTestBase configuration.getConnectorConfigurations().put(backupConnectorName, backupConnector); } - ClusterConnectionConfiguration clusterConf = new ClusterConnectionConfiguration() - .setName("localCluster" + node) - .setAddress("cluster-queues") - .setConnectorName("thisConnector") - .setRetryInterval(100) - .setConfirmationWindowSize(1024) - .setMessageLoadBalancingType(MessageLoadBalancingType.ON_DEMAND) - .setStaticConnectors(targetServersOnConnection); + ClusterConnectionConfiguration clusterConf = new ClusterConnectionConfiguration().setName("localCluster" + node).setAddress("cluster-queues").setConnectorName("thisConnector").setRetryInterval(100).setConfirmationWindowSize(1024).setMessageLoadBalancingType(MessageLoadBalancingType.ON_DEMAND).setStaticConnectors(targetServersOnConnection); configuration.getClusterConfigurations().add(clusterConf); ActiveMQServer server; - if (sharedStorage) - { + if (sharedStorage) { server = createInVMFailoverServer(realFiles, configuration, nodeManager, node); } - else - { + else { server = createServer(realFiles, configuration); } server.setIdentity(this.getClass().getSimpleName() + "/Live(" + node + ")"); - addServer(server); return new Pair(server, nodeManager); } protected ActiveMQServer setupBackupServer(final int node, - final int liveNode, - final NodeManager nodeManager) throws Exception - { + final int liveNode, + final NodeManager nodeManager) throws Exception { TransportConfiguration serverConfigAcceptor = createTransportConfiguration(useNetty(), true, generateParams(node, useNetty())); TransportConfiguration thisConnector = createTransportConfiguration(useNetty(), false, generateParams(node, useNetty())); - Configuration configuration = createBasicConfig(useSharedStorage() ? liveNode : node) - .clearAcceptorConfigurations() - .addAcceptorConfiguration(serverConfigAcceptor) - .addConnectorConfiguration("thisConnector", thisConnector) - .setHAPolicyConfiguration(useSharedStorage() ? new SharedStoreSlavePolicyConfiguration() : new ReplicaPolicyConfiguration()); + Configuration configuration = createBasicConfig(useSharedStorage() ? liveNode : node).clearAcceptorConfigurations().addAcceptorConfiguration(serverConfigAcceptor).addConnectorConfiguration("thisConnector", thisConnector).setHAPolicyConfiguration(useSharedStorage() ? new SharedStoreSlavePolicyConfiguration() : new ReplicaPolicyConfiguration()); List targetServersOnConnection = new ArrayList(); - for (int targetNode = 0; targetNode < getNumberOfServers(); targetNode++) - { -// if (targetNode == node) -// { -// // moving on from itself -// continue; -// } + for (int targetNode = 0; targetNode < getNumberOfServers(); targetNode++) { + // if (targetNode == node) + // { + // // moving on from itself + // continue; + // } String targetConnectorName = "targetConnector-" + targetNode; TransportConfiguration targetServer = createTransportConfiguration(useNetty(), false, generateParams(targetNode, useNetty())); configuration.addConnectorConfiguration(targetConnectorName, targetServer); targetServersOnConnection.add(targetConnectorName); } - ClusterConnectionConfiguration clusterConf = new ClusterConnectionConfiguration() - .setName("localCluster" + node) - .setAddress("cluster-queues") - .setConnectorName("thisConnector") - .setRetryInterval(100) - .setConfirmationWindowSize(1024) - .setMessageLoadBalancingType(MessageLoadBalancingType.ON_DEMAND) - .setStaticConnectors(targetServersOnConnection); + ClusterConnectionConfiguration clusterConf = new ClusterConnectionConfiguration().setName("localCluster" + node).setAddress("cluster-queues").setConnectorName("thisConnector").setRetryInterval(100).setConfirmationWindowSize(1024).setMessageLoadBalancingType(MessageLoadBalancingType.ON_DEMAND).setStaticConnectors(targetServersOnConnection); configuration.getClusterConfigurations().add(clusterConf); ActiveMQServer server; - if (useSharedStorage()) - { + if (useSharedStorage()) { server = createInVMFailoverServer(true, configuration, nodeManager, liveNode); } - else - { + else { server = addServer(ActiveMQServers.newActiveMQServer(configuration, useRealFiles())); } server.setIdentity(this.getClass().getSimpleName() + "/Backup(" + node + " of live " + liveNode + ")"); return server; } - } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/util/RemoteServerConfiguration.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/util/RemoteServerConfiguration.java index d93d6053e9..8aee92b235 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/util/RemoteServerConfiguration.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/util/RemoteServerConfiguration.java @@ -25,11 +25,9 @@ import org.apache.activemq.artemis.core.config.Configuration; * Therefore they must have a no argument constructor, and if they are inner classes they must be * static. */ -public abstract class RemoteServerConfiguration -{ +public abstract class RemoteServerConfiguration { - public RemoteServerConfiguration() - { + public RemoteServerConfiguration() { } public abstract Configuration getConfiguration(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/util/SameProcessActiveMQServer.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/util/SameProcessActiveMQServer.java index 45b7f03bd2..c7854beaef 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/util/SameProcessActiveMQServer.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/util/SameProcessActiveMQServer.java @@ -26,62 +26,51 @@ import org.junit.Assert; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -public class SameProcessActiveMQServer implements TestableServer -{ +public class SameProcessActiveMQServer implements TestableServer { + private final ActiveMQServer server; - public SameProcessActiveMQServer(ActiveMQServer server) - { + public SameProcessActiveMQServer(ActiveMQServer server) { this.server = server; } @Override - public boolean isActive() - { + public boolean isActive() { return server.isActive(); } - public void setIdentity(String identity) - { + public void setIdentity(String identity) { server.setIdentity(identity); } - public boolean isStarted() - { + public boolean isStarted() { return server.isStarted(); } - public void addInterceptor(Interceptor interceptor) - { + public void addInterceptor(Interceptor interceptor) { server.getRemotingService().addIncomingInterceptor(interceptor); } - public void removeInterceptor(Interceptor interceptor) - { + public void removeInterceptor(Interceptor interceptor) { server.getRemotingService().removeIncomingInterceptor(interceptor); } - public void start() throws Exception - { + public void start() throws Exception { server.start(); } - public void stop() throws Exception - { + public void stop() throws Exception { server.stop(); } - public CountDownLatch crash(ClientSession... sessions) throws Exception - { + public CountDownLatch crash(ClientSession... sessions) throws Exception { return crash(true, sessions); } - public CountDownLatch crash(boolean waitFailure, ClientSession... sessions) throws Exception - { + public CountDownLatch crash(boolean waitFailure, ClientSession... sessions) throws Exception { CountDownLatch latch = new CountDownLatch(sessions.length); CountDownSessionFailureListener[] listeners = new CountDownSessionFailureListener[sessions.length]; - for (int i = 0; i < sessions.length; i++) - { + for (int i = 0; i < sessions.length; i++) { listeners[i] = new CountDownSessionFailureListener(latch, sessions[i]); sessions[i].addFailureListener(listeners[i]); } @@ -92,19 +81,17 @@ public class SameProcessActiveMQServer implements TestableServer Assert.assertTrue("server should be running!", server.isStarted()); server.stop(true); - if (waitFailure) - { + if (waitFailure) { // Wait to be informed of failure boolean ok = latch.await(10000, TimeUnit.MILLISECONDS); Assert.assertTrue("Failed to stop the server! Latch count is " + latch.getCount() + " out of " + - sessions.length, ok); + sessions.length, ok); } return latch; } - public ActiveMQServer getServer() - { + public ActiveMQServer getServer() { return server; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/util/TestableServer.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/util/TestableServer.java index 23ccfc2b2c..b6738e0c4a 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/util/TestableServer.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/util/TestableServer.java @@ -23,8 +23,8 @@ import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.core.server.ActiveMQComponent; import org.apache.activemq.artemis.core.server.ActiveMQServer; -public interface TestableServer extends ActiveMQComponent -{ +public interface TestableServer extends ActiveMQComponent { + ActiveMQServer getServer(); void stop() throws Exception; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/discovery/DiscoveryBaseTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/discovery/DiscoveryBaseTest.java index f489747489..06bc14ef7b 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/discovery/DiscoveryBaseTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/discovery/DiscoveryBaseTest.java @@ -39,8 +39,8 @@ import org.apache.activemq.artemis.core.server.management.NotificationService; import org.apache.activemq.artemis.utils.UUIDGenerator; import org.junit.Assert; -public class DiscoveryBaseTest extends ActiveMQTestBase -{ +public class DiscoveryBaseTest extends ActiveMQTestBase { + protected static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; protected final String address1 = getUDPDiscoveryAddress(); @@ -49,13 +49,12 @@ public class DiscoveryBaseTest extends ActiveMQTestBase protected final String address3 = getUDPDiscoveryAddress(2); - /** * @param discoveryGroup * @throws Exception */ - protected static void verifyBroadcast(BroadcastGroup broadcastGroup, DiscoveryGroup discoveryGroup) throws Exception - { + protected static void verifyBroadcast(BroadcastGroup broadcastGroup, + DiscoveryGroup discoveryGroup) throws Exception { broadcastGroup.broadcastConnectors(); Assert.assertTrue("broadcast received", discoveryGroup.waitForBroadcast(2000)); } @@ -64,22 +63,17 @@ public class DiscoveryBaseTest extends ActiveMQTestBase * @param discoveryGroup * @throws Exception */ - protected static void verifyNonBroadcast(BroadcastGroup broadcastGroup, DiscoveryGroup discoveryGroup) - throws Exception - { + protected static void verifyNonBroadcast(BroadcastGroup broadcastGroup, + DiscoveryGroup discoveryGroup) throws Exception { broadcastGroup.broadcastConnectors(); Assert.assertFalse("NO broadcast received", discoveryGroup.waitForBroadcast(2000)); } - - - protected TransportConfiguration generateTC() - { + protected TransportConfiguration generateTC() { return generateTC(""); } - protected TransportConfiguration generateTC(String debug) - { + protected TransportConfiguration generateTC(String debug) { String className = "org.foo.bar." + debug + "|" + UUIDGenerator.getInstance().generateStringUUID() + ""; String name = UUIDGenerator.getInstance().generateStringUUID(); Map params = new HashMap(); @@ -90,66 +84,55 @@ public class DiscoveryBaseTest extends ActiveMQTestBase return tc; } - protected static class MyListener implements DiscoveryListener - { + protected static class MyListener implements DiscoveryListener { + volatile boolean called; - public void connectorsChanged(List newConnectors) - { + public void connectorsChanged(List newConnectors) { called = true; } } - protected static void assertEqualsDiscoveryEntries(List expected, List actual) - { + protected static void assertEqualsDiscoveryEntries(List expected, + List actual) { assertNotNull(actual); List sortedExpected = new ArrayList(expected); - Collections.sort(sortedExpected, new Comparator() - { + Collections.sort(sortedExpected, new Comparator() { - public int compare(TransportConfiguration o1, TransportConfiguration o2) - { + public int compare(TransportConfiguration o1, TransportConfiguration o2) { return o2.toString().compareTo(o1.toString()); } }); List sortedActual = new ArrayList(actual); - Collections.sort(sortedActual, new Comparator() - { - public int compare(DiscoveryEntry o1, DiscoveryEntry o2) - { + Collections.sort(sortedActual, new Comparator() { + public int compare(DiscoveryEntry o1, DiscoveryEntry o2) { return o2.getConnector().toString().compareTo(o1.getConnector().toString()); } }); - if (sortedExpected.size() != sortedActual.size()) - { + if (sortedExpected.size() != sortedActual.size()) { dump(sortedExpected, sortedActual); } assertEquals(sortedExpected.size(), sortedActual.size()); - for (int i = 0; i < sortedExpected.size(); i++) - { - if (!sortedExpected.get(i).equals(sortedActual.get(i).getConnector())) - { + for (int i = 0; i < sortedExpected.size(); i++) { + if (!sortedExpected.get(i).equals(sortedActual.get(i).getConnector())) { dump(sortedExpected, sortedActual); } assertEquals(sortedExpected.get(i), sortedActual.get(i).getConnector()); } } - protected static void dump(List sortedExpected, List sortedActual) - { + protected static void dump(List sortedExpected, List sortedActual) { System.out.println("wrong broadcasts received"); System.out.println("expected"); System.out.println("----------------------------"); - for (TransportConfiguration transportConfiguration : sortedExpected) - { + for (TransportConfiguration transportConfiguration : sortedExpected) { System.out.println("transportConfiguration = " + transportConfiguration); } System.out.println("----------------------------"); System.out.println("actual"); System.out.println("----------------------------"); - for (DiscoveryEntry discoveryEntry : sortedActual) - { + for (DiscoveryEntry discoveryEntry : sortedActual) { System.out.println("transportConfiguration = " + discoveryEntry.getConnector()); } System.out.println("----------------------------"); @@ -163,92 +146,78 @@ public class DiscoveryBaseTest extends ActiveMQTestBase final InetAddress localAddress, int localPort, final InetAddress groupAddress, - final int groupPort) throws Exception - { - return new BroadcastGroupImpl(new FakeNodeManager(nodeID), name, 0, null, new UDPBroadcastEndpointFactory() - .setGroupAddress(groupAddress.getHostAddress()) - .setGroupPort(groupPort) - .setLocalBindAddress(localAddress != null ? localAddress.getHostAddress() : null) - .setLocalBindPort(localPort)); + final int groupPort) throws Exception { + return new BroadcastGroupImpl(new FakeNodeManager(nodeID), name, 0, null, new UDPBroadcastEndpointFactory().setGroupAddress(groupAddress.getHostAddress()).setGroupPort(groupPort).setLocalBindAddress(localAddress != null ? localAddress.getHostAddress() : null).setLocalBindPort(localPort)); } - protected DiscoveryGroup newDiscoveryGroup(final String nodeID, final String name, final InetAddress localBindAddress, - final InetAddress groupAddress, final int groupPort, final long timeout) throws Exception - { + protected DiscoveryGroup newDiscoveryGroup(final String nodeID, + final String name, + final InetAddress localBindAddress, + final InetAddress groupAddress, + final int groupPort, + final long timeout) throws Exception { return newDiscoveryGroup(nodeID, name, localBindAddress, groupAddress, groupPort, timeout, null); } - protected DiscoveryGroup newDiscoveryGroup(final String nodeID, final String name, final InetAddress localBindAddress, - final InetAddress groupAddress, final int groupPort, final long timeout, NotificationService notif) throws Exception - { - return new DiscoveryGroup(nodeID, name, timeout, new UDPBroadcastEndpointFactory() - .setGroupAddress(groupAddress.getHostAddress()) - .setGroupPort(groupPort) - .setLocalBindAddress(localBindAddress != null ? localBindAddress.getHostAddress() : null), notif); + protected DiscoveryGroup newDiscoveryGroup(final String nodeID, + final String name, + final InetAddress localBindAddress, + final InetAddress groupAddress, + final int groupPort, + final long timeout, + NotificationService notif) throws Exception { + return new DiscoveryGroup(nodeID, name, timeout, new UDPBroadcastEndpointFactory().setGroupAddress(groupAddress.getHostAddress()).setGroupPort(groupPort).setLocalBindAddress(localBindAddress != null ? localBindAddress.getHostAddress() : null), notif); } - protected final class FakeNodeManager extends NodeManager - { + protected final class FakeNodeManager extends NodeManager { - public FakeNodeManager(String nodeID) - { + public FakeNodeManager(String nodeID) { super(false, null); this.setNodeID(nodeID); } @Override - public void awaitLiveNode() throws Exception - { + public void awaitLiveNode() throws Exception { } @Override - public void startBackup() throws Exception - { + public void startBackup() throws Exception { } @Override - public void startLiveNode() throws Exception - { + public void startLiveNode() throws Exception { } @Override - public void pauseLiveServer() throws Exception - { + public void pauseLiveServer() throws Exception { } @Override - public void crashLiveServer() throws Exception - { + public void crashLiveServer() throws Exception { } @Override - public void releaseBackup() throws Exception - { + public void releaseBackup() throws Exception { } @Override - public SimpleString readNodeId() - { + public SimpleString readNodeId() { return null; } @Override - public boolean isAwaitingFailback() throws Exception - { + public boolean isAwaitingFailback() throws Exception { return false; } @Override - public boolean isBackupLive() throws Exception - { + public boolean isBackupLive() throws Exception { return false; } @Override - public void interrupt() - { + public void interrupt() { } } - } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/discovery/DiscoveryStayAliveTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/discovery/DiscoveryStayAliveTest.java index 9c960fa50e..c3c864594e 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/discovery/DiscoveryStayAliveTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/discovery/DiscoveryStayAliveTest.java @@ -34,56 +34,38 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class DiscoveryStayAliveTest extends DiscoveryBaseTest -{ - +public class DiscoveryStayAliveTest extends DiscoveryBaseTest { ScheduledExecutorService scheduledExecutorService; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - scheduledExecutorService = new ScheduledThreadPoolExecutor(1, - new ActiveMQThreadFactory("ActiveMQ-scheduled-threads", - false, - Thread.currentThread().getContextClassLoader())); + scheduledExecutorService = new ScheduledThreadPoolExecutor(1, new ActiveMQThreadFactory("ActiveMQ-scheduled-threads", false, Thread.currentThread().getContextClassLoader())); } - public void tearDown() throws Exception - { + public void tearDown() throws Exception { scheduledExecutorService.shutdown(); super.tearDown(); } @Test - public void testDiscoveryRunning() throws Throwable - { + public void testDiscoveryRunning() throws Throwable { final InetAddress groupAddress = InetAddress.getByName(address1); final int groupPort = getUDPDiscoveryPort(); final int timeout = 500; - - final DiscoveryGroup dg = newDiscoveryGroup(RandomUtil.randomString(), - RandomUtil.randomString(), - null, - groupAddress, - groupPort, - timeout); + final DiscoveryGroup dg = newDiscoveryGroup(RandomUtil.randomString(), RandomUtil.randomString(), null, groupAddress, groupPort, timeout); final AtomicInteger errors = new AtomicInteger(0); - Thread t = new Thread() - { - public void run() - { - try - { + Thread t = new Thread() { + public void run() { + try { dg.internalRunning(); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); errors.incrementAndGet(); } @@ -92,19 +74,14 @@ public class DiscoveryStayAliveTest extends DiscoveryBaseTest }; t.start(); - - BroadcastGroupImpl bg = new BroadcastGroupImpl(new FakeNodeManager("test-nodeID"), - RandomUtil.randomString(), - 1, scheduledExecutorService, new UDPBroadcastEndpointFactory().setGroupAddress(address1). - setGroupPort(groupPort)); + BroadcastGroupImpl bg = new BroadcastGroupImpl(new FakeNodeManager("test-nodeID"), RandomUtil.randomString(), 1, scheduledExecutorService, new UDPBroadcastEndpointFactory().setGroupAddress(address1). + setGroupPort(groupPort)); bg.start(); bg.addConnector(generateTC()); - - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { BroadcastEndpointFactory factoryEndpoint = new UDPBroadcastEndpointFactory().setGroupAddress(address1). setGroupPort(groupPort); sendBadData(factoryEndpoint); @@ -123,29 +100,23 @@ public class DiscoveryStayAliveTest extends DiscoveryBaseTest } - - private static void sendBadData(BroadcastEndpointFactory factoryEndpoint) throws Exception - { + private static void sendBadData(BroadcastEndpointFactory factoryEndpoint) throws Exception { BroadcastEndpoint endpoint = factoryEndpoint.createBroadcastEndpoint(); - ActiveMQBuffer buffer = ActiveMQBuffers.dynamicBuffer(500); buffer.writeString("This is a test1!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); buffer.writeString("This is a test2!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); - byte[] bytes = new byte[buffer.writerIndex()]; buffer.readBytes(bytes); // messing up with the string!!! - for (int i = bytes.length - 10; i < bytes.length; i++) - { + for (int i = bytes.length - 10; i < bytes.length; i++) { bytes[i] = 0; } - endpoint.openBroadcaster(); endpoint.broadcast(bytes); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/discovery/DiscoveryTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/discovery/DiscoveryTest.java index 67e7404f38..8dc236e844 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/discovery/DiscoveryTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/discovery/DiscoveryTest.java @@ -63,40 +63,33 @@ import org.junit.Test; * Also: Make sure you add integration-tests/src/tests/resources to your project path on the * tests/integration-tests */ -public class DiscoveryTest extends DiscoveryBaseTest -{ +public class DiscoveryTest extends DiscoveryBaseTest { + private static final String TEST_JGROUPS_CONF_FILE = "test-jgroups-file_ping.xml"; BroadcastGroup bg = null, bg1 = null, bg2 = null, bg3 = null; DiscoveryGroup dg = null, dg1 = null, dg2 = null, dg3 = null; - @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { /** This file path is defined at {@link #TEST_JGROUPS_CONF_FILE} */ deleteDirectory(new File("./target/tmp/amqtest.ping.dir")); - for (ActiveMQComponent component : new ActiveMQComponent[]{bg, bg1, bg2, bg3, dg, dg1, dg2, dg3}) - { + for (ActiveMQComponent component : new ActiveMQComponent[]{bg, bg1, bg2, bg3, dg, dg1, dg2, dg3}) { stopComponent(component); } super.tearDown(); } - @Test - public void testSimpleBroadcast() throws Exception - { + public void testSimpleBroadcast() throws Exception { final InetAddress groupAddress = InetAddress.getByName(address1); final int groupPort = getUDPDiscoveryPort(); final int timeout = 500; final String nodeID = RandomUtil.randomString(); - bg = new BroadcastGroupImpl(new FakeNodeManager(nodeID), - RandomUtil.randomString(), - 0, null, new UDPBroadcastEndpointFactory().setGroupAddress(address1).setGroupPort(groupPort)); + bg = new BroadcastGroupImpl(new FakeNodeManager(nodeID), RandomUtil.randomString(), 0, null, new UDPBroadcastEndpointFactory().setGroupAddress(address1).setGroupPort(groupPort)); bg.start(); @@ -104,12 +97,7 @@ public class DiscoveryTest extends DiscoveryBaseTest bg.addConnector(live1); - dg = newDiscoveryGroup(RandomUtil.randomString(), - RandomUtil.randomString(), - null, - groupAddress, - groupPort, - timeout); + dg = newDiscoveryGroup(RandomUtil.randomString(), RandomUtil.randomString(), null, groupAddress, groupPort, timeout); dg.start(); @@ -119,16 +107,11 @@ public class DiscoveryTest extends DiscoveryBaseTest assertEqualsDiscoveryEntries(Arrays.asList(live1), entries); } - @Test - public void testSimpleBroadcastJGropus() throws Exception - { + public void testSimpleBroadcastJGropus() throws Exception { final String nodeID = RandomUtil.randomString(); - bg = new BroadcastGroupImpl(new FakeNodeManager(nodeID), "broadcast", 100, null, - new JGroupsFileBroadcastEndpointFactory() - .setChannelName("tst") - .setFile(TEST_JGROUPS_CONF_FILE)); + bg = new BroadcastGroupImpl(new FakeNodeManager(nodeID), "broadcast", 100, null, new JGroupsFileBroadcastEndpointFactory().setChannelName("tst").setFile(TEST_JGROUPS_CONF_FILE)); bg.start(); @@ -136,11 +119,7 @@ public class DiscoveryTest extends DiscoveryBaseTest bg.addConnector(live1); - dg = new DiscoveryGroup(nodeID + "1", "broadcast", 5000L, - new JGroupsFileBroadcastEndpointFactory() - .setChannelName("tst") - .setFile(TEST_JGROUPS_CONF_FILE), - null); + dg = new DiscoveryGroup(nodeID + "1", "broadcast", 5000L, new JGroupsFileBroadcastEndpointFactory().setChannelName("tst").setFile(TEST_JGROUPS_CONF_FILE), null); dg.start(); @@ -156,18 +135,14 @@ public class DiscoveryTest extends DiscoveryBaseTest * @throws Exception */ @Test - public void testJGropusChannelReferenceCounting() throws Exception - { - BroadcastEndpointFactory factory = new JGroupsFileBroadcastEndpointFactory() - .setChannelName("tst") - .setFile(TEST_JGROUPS_CONF_FILE); + public void testJGropusChannelReferenceCounting() throws Exception { + BroadcastEndpointFactory factory = new JGroupsFileBroadcastEndpointFactory().setChannelName("tst").setFile(TEST_JGROUPS_CONF_FILE); BroadcastEndpoint broadcaster = factory.createBroadcastEndpoint(); broadcaster.openBroadcaster(); int num = 100; BroadcastEndpoint[] receivers = new BroadcastEndpoint[num]; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { receivers[i] = factory.createBroadcastEndpoint(); receivers[i].openClient(); } @@ -175,8 +150,7 @@ public class DiscoveryTest extends DiscoveryBaseTest final byte[] data = new byte[]{1, 2, 3, 4, 5}; broadcaster.broadcast(data); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { byte[] received = receivers[i].receiveBroadcast(5000, TimeUnit.MILLISECONDS); assertNotNull(received); assertEquals(5, received.length); @@ -187,8 +161,7 @@ public class DiscoveryTest extends DiscoveryBaseTest assertEquals(5, received[4]); } - for (int i = 0; i < num - 1; i++) - { + for (int i = 0; i < num - 1; i++) { receivers[i].close(false); } @@ -218,18 +191,14 @@ public class DiscoveryTest extends DiscoveryBaseTest * @throws Exception */ @Test - public void testJGropusChannelReferenceCounting1() throws Exception - { - BroadcastEndpointFactory factory = new JGroupsFileBroadcastEndpointFactory() - .setChannelName("tst") - .setFile(TEST_JGROUPS_CONF_FILE); + public void testJGropusChannelReferenceCounting1() throws Exception { + BroadcastEndpointFactory factory = new JGroupsFileBroadcastEndpointFactory().setChannelName("tst").setFile(TEST_JGROUPS_CONF_FILE); BroadcastEndpoint broadcaster = factory.createBroadcastEndpoint(); broadcaster.openBroadcaster(); int num = 50; BroadcastEndpoint[] receivers = new BroadcastEndpoint[num]; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { receivers[i] = factory.createBroadcastEndpoint(); receivers[i].openClient(); } @@ -237,8 +206,7 @@ public class DiscoveryTest extends DiscoveryBaseTest final byte[] data = new byte[]{1, 2, 3, 4, 5}; broadcaster.broadcast(data); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { byte[] received = receivers[i].receiveBroadcast(5000, TimeUnit.MILLISECONDS); assertNotNull(received); assertEquals(5, received.length); @@ -249,22 +217,19 @@ public class DiscoveryTest extends DiscoveryBaseTest assertEquals(5, received[4]); } - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { receivers[i].close(false); } //new ones - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { receivers[i] = factory.createBroadcastEndpoint(); receivers[i].openClient(); } broadcaster.broadcast(data); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { byte[] received = receivers[i].receiveBroadcast(5000, TimeUnit.MILLISECONDS); assertNotNull(received); assertEquals(5, received.length); @@ -275,8 +240,7 @@ public class DiscoveryTest extends DiscoveryBaseTest assertEquals(5, received[4]); } - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { receivers[i].close(false); } broadcaster.close(true); @@ -289,29 +253,23 @@ public class DiscoveryTest extends DiscoveryBaseTest * @throws Exception */ @Test - public void testJGropusChannelReferenceCounting2() throws Exception - { - BroadcastEndpointFactory factory = new JGroupsFileBroadcastEndpointFactory() - .setChannelName("tst") - .setFile(TEST_JGROUPS_CONF_FILE); + public void testJGropusChannelReferenceCounting2() throws Exception { + BroadcastEndpointFactory factory = new JGroupsFileBroadcastEndpointFactory().setChannelName("tst").setFile(TEST_JGROUPS_CONF_FILE); BroadcastEndpoint broadcaster = factory.createBroadcastEndpoint(); broadcaster.openBroadcaster(); int num = 50; BroadcastEndpoint[] receivers = new BroadcastEndpoint[num]; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { receivers[i] = factory.createBroadcastEndpoint(); receivers[i].openClient(); } - for (int i = 0; i < num / 2; i++) - { + for (int i = 0; i < num / 2; i++) { receivers[i].close(false); } - for (int i = 0; i < num / 2; i++) - { + for (int i = 0; i < num / 2; i++) { receivers[i] = factory.createBroadcastEndpoint(); receivers[i].openClient(); } @@ -319,8 +277,7 @@ public class DiscoveryTest extends DiscoveryBaseTest int num2 = 10; BroadcastEndpoint[] moreReceivers = new BroadcastEndpoint[num2]; - for (int i = 0; i < num2; i++) - { + for (int i = 0; i < num2; i++) { moreReceivers[i] = factory.createBroadcastEndpoint(); moreReceivers[i].openClient(); } @@ -328,8 +285,7 @@ public class DiscoveryTest extends DiscoveryBaseTest final byte[] data = new byte[]{1, 2, 3, 4, 5}; broadcaster.broadcast(data); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { byte[] received = receivers[i].receiveBroadcast(5000, TimeUnit.MILLISECONDS); assertNotNull(received); assertEquals(5, received.length); @@ -340,8 +296,7 @@ public class DiscoveryTest extends DiscoveryBaseTest assertEquals(5, received[4]); } - for (int i = 0; i < num2; i++) - { + for (int i = 0; i < num2; i++) { byte[] received = moreReceivers[i].receiveBroadcast(5000, TimeUnit.MILLISECONDS); assertNotNull(received); assertEquals(5, received.length); @@ -352,13 +307,11 @@ public class DiscoveryTest extends DiscoveryBaseTest assertEquals(5, received[4]); } - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { receivers[i].close(false); } - for (int i = 0; i < num2; i++) - { + for (int i = 0; i < num2; i++) { moreReceivers[i].close(false); } @@ -366,15 +319,11 @@ public class DiscoveryTest extends DiscoveryBaseTest } @Test - public void testStraightSendReceiveJGroups() throws Exception - { + public void testStraightSendReceiveJGroups() throws Exception { BroadcastEndpoint broadcaster = null; BroadcastEndpoint client = null; - try - { - JGroupsFileBroadcastEndpointFactory endpointFactory = new JGroupsFileBroadcastEndpointFactory() - .setChannelName("tst") - .setFile(TEST_JGROUPS_CONF_FILE); + try { + JGroupsFileBroadcastEndpointFactory endpointFactory = new JGroupsFileBroadcastEndpointFactory().setChannelName("tst").setFile(TEST_JGROUPS_CONF_FILE); broadcaster = endpointFactory.createBroadcastEndpoint(); broadcaster.openBroadcaster(); @@ -397,23 +346,19 @@ public class DiscoveryTest extends DiscoveryBaseTest assertEquals(randomBytes.length, btreceived.length); - for (int i = 0; i < randomBytes.length; i++) - { + for (int i = 0; i < randomBytes.length; i++) { assertEquals(randomBytes[i], btreceived[i]); } } - finally - { - try - { + finally { + try { if (broadcaster != null) broadcaster.close(true); if (client != null) client.close(false); } - catch (Exception ignored) - { + catch (Exception ignored) { ignored.printStackTrace(); } } @@ -421,8 +366,7 @@ public class DiscoveryTest extends DiscoveryBaseTest } @Test - public void testSimpleBroadcastSpecificNIC() throws Exception - { + public void testSimpleBroadcastSpecificNIC() throws Exception { final InetAddress groupAddress = InetAddress.getByName(address1); final int groupPort = getUDPDiscoveryPort(); final int timeout = 500; @@ -437,24 +381,20 @@ public class DiscoveryTest extends DiscoveryBaseTest InetAddress localAddress = null; outer: - while (networkInterfaces.hasMoreElements()) - { + while (networkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = networkInterfaces.nextElement(); if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp() || - !networkInterface.supportsMulticast()) - { + !networkInterface.supportsMulticast()) { continue; } Enumeration en = networkInterface.getInetAddresses(); - while (en.hasMoreElements()) - { + while (en.hasMoreElements()) { InetAddress ia = en.nextElement(); - if (ia.getAddress().length == 4) - { + if (ia.getAddress().length == 4) { localAddress = ia; break outer; @@ -462,8 +402,7 @@ public class DiscoveryTest extends DiscoveryBaseTest } } - if (localAddress == null) - { + if (localAddress == null) { log.warn("Can't find address to use"); return; @@ -471,12 +410,7 @@ public class DiscoveryTest extends DiscoveryBaseTest log.info("Local address is " + localAddress); - bg = newBroadcast(nodeID, - RandomUtil.randomString(), - localAddress, - 6552, - groupAddress, - groupPort); + bg = newBroadcast(nodeID, RandomUtil.randomString(), localAddress, 6552, groupAddress, groupPort); bg.start(); @@ -484,12 +418,7 @@ public class DiscoveryTest extends DiscoveryBaseTest bg.addConnector(live1); - dg = newDiscoveryGroup(RandomUtil.randomString(), - RandomUtil.randomString(), - localAddress, - groupAddress, - groupPort, - timeout); + dg = newDiscoveryGroup(RandomUtil.randomString(), RandomUtil.randomString(), localAddress, groupAddress, groupPort, timeout); dg.start(); @@ -501,20 +430,14 @@ public class DiscoveryTest extends DiscoveryBaseTest } @Test - public void testSimpleBroadcastWithStopStartDiscoveryGroup() throws Exception - { + public void testSimpleBroadcastWithStopStartDiscoveryGroup() throws Exception { final InetAddress groupAddress = InetAddress.getByName(address1); final int groupPort = getUDPDiscoveryPort(); final int timeout = 500; final String nodeID = RandomUtil.randomString(); - bg = newBroadcast(nodeID, - RandomUtil.randomString(), - null, - -1, - groupAddress, - groupPort); + bg = newBroadcast(nodeID, RandomUtil.randomString(), null, -1, groupAddress, groupPort); bg.start(); @@ -522,12 +445,7 @@ public class DiscoveryTest extends DiscoveryBaseTest bg.addConnector(live1); - dg = newDiscoveryGroup(RandomUtil.randomString(), - RandomUtil.randomString(), - null, - groupAddress, - groupPort, - timeout); + dg = newDiscoveryGroup(RandomUtil.randomString(), RandomUtil.randomString(), null, groupAddress, groupPort, timeout); dg.start(); @@ -549,20 +467,14 @@ public class DiscoveryTest extends DiscoveryBaseTest } @Test - public void testIgnoreTrafficFromOwnNode() throws Exception - { + public void testIgnoreTrafficFromOwnNode() throws Exception { final InetAddress groupAddress = InetAddress.getByName(address1); final int groupPort = getUDPDiscoveryPort(); final int timeout = 500; String nodeID = RandomUtil.randomString(); - bg = newBroadcast(nodeID, - RandomUtil.randomString(), - null, - -1, - groupAddress, - groupPort); + bg = newBroadcast(nodeID, RandomUtil.randomString(), null, -1, groupAddress, groupPort); bg.start(); @@ -570,12 +482,7 @@ public class DiscoveryTest extends DiscoveryBaseTest bg.addConnector(live1); - dg = newDiscoveryGroup(nodeID, - RandomUtil.randomString(), - null, - groupAddress, - groupPort, - timeout); + dg = newDiscoveryGroup(nodeID, RandomUtil.randomString(), null, groupAddress, groupPort, timeout); dg.start(); @@ -589,18 +496,12 @@ public class DiscoveryTest extends DiscoveryBaseTest } @Test - public void testSimpleBroadcastDifferentPort() throws Exception - { + public void testSimpleBroadcastDifferentPort() throws Exception { final InetAddress groupAddress = InetAddress.getByName(getUDPDiscoveryAddress()); final int groupPort = getUDPDiscoveryPort(); final int timeout = 500; - bg = newBroadcast(RandomUtil.randomString(), - RandomUtil.randomString(), - null, - -1, - groupAddress, - groupPort); + bg = newBroadcast(RandomUtil.randomString(), RandomUtil.randomString(), null, -1, groupAddress, groupPort); bg.start(); @@ -610,12 +511,7 @@ public class DiscoveryTest extends DiscoveryBaseTest final int port2 = getUDPDiscoveryPort(1); - dg = newDiscoveryGroup(RandomUtil.randomString(), - RandomUtil.randomString(), - null, - groupAddress, - port2, - timeout); + dg = newDiscoveryGroup(RandomUtil.randomString(), RandomUtil.randomString(), null, groupAddress, port2, timeout); dg.start(); @@ -623,18 +519,12 @@ public class DiscoveryTest extends DiscoveryBaseTest } @Test - public void testSimpleBroadcastDifferentAddressAndPort() throws Exception - { + public void testSimpleBroadcastDifferentAddressAndPort() throws Exception { final InetAddress groupAddress = InetAddress.getByName(address1); final int groupPort = getUDPDiscoveryPort(); final int timeout = 500; - bg = newBroadcast(RandomUtil.randomString(), - RandomUtil.randomString(), - null, - -1, - groupAddress, - groupPort); + bg = newBroadcast(RandomUtil.randomString(), RandomUtil.randomString(), null, -1, groupAddress, groupPort); bg.start(); @@ -645,12 +535,7 @@ public class DiscoveryTest extends DiscoveryBaseTest final InetAddress groupAddress2 = InetAddress.getByName(address2); final int port2 = getUDPDiscoveryPort(1); - dg = newDiscoveryGroup(RandomUtil.randomString(), - RandomUtil.randomString(), - null, - groupAddress2, - port2, - timeout); + dg = newDiscoveryGroup(RandomUtil.randomString(), RandomUtil.randomString(), null, groupAddress2, port2, timeout); dg.start(); @@ -658,8 +543,7 @@ public class DiscoveryTest extends DiscoveryBaseTest } @Test - public void testMultipleGroups() throws Exception - { + public void testMultipleGroups() throws Exception { final int groupPort1 = getUDPDiscoveryPort(); final int groupPort2 = getUDPDiscoveryPort(1); @@ -680,26 +564,11 @@ public class DiscoveryTest extends DiscoveryBaseTest String node3 = UUIDGenerator.getInstance().generateStringUUID(); - bg1 = newBroadcast(node1, - RandomUtil.randomString(), - null, - -1, - groupAddress1, - groupPort1); + bg1 = newBroadcast(node1, RandomUtil.randomString(), null, -1, groupAddress1, groupPort1); - bg2 = newBroadcast(node2, - RandomUtil.randomString(), - null, - -1, - groupAddress2, - groupPort2); + bg2 = newBroadcast(node2, RandomUtil.randomString(), null, -1, groupAddress2, groupPort2); - bg3 = newBroadcast(node3, - RandomUtil.randomString(), - null, - -1, - groupAddress3, - groupPort3); + bg3 = newBroadcast(node3, RandomUtil.randomString(), null, -1, groupAddress3, groupPort3); bg2.start(); bg1.start(); @@ -715,28 +584,13 @@ public class DiscoveryTest extends DiscoveryBaseTest bg2.addConnector(live2); bg3.addConnector(live3); - dg1 = newDiscoveryGroup("group-1::" + RandomUtil.randomString(), - "group-1::" + RandomUtil.randomString(), - null, - groupAddress1, - groupPort1, - timeout); + dg1 = newDiscoveryGroup("group-1::" + RandomUtil.randomString(), "group-1::" + RandomUtil.randomString(), null, groupAddress1, groupPort1, timeout); dg1.start(); - dg2 = newDiscoveryGroup("group-2::" + RandomUtil.randomString(), - "group-2::" + RandomUtil.randomString(), - null, - groupAddress2, - groupPort2, - timeout); + dg2 = newDiscoveryGroup("group-2::" + RandomUtil.randomString(), "group-2::" + RandomUtil.randomString(), null, groupAddress2, groupPort2, timeout); dg2.start(); - dg3 = newDiscoveryGroup("group-3::" + RandomUtil.randomString(), - "group-3::" + RandomUtil.randomString(), - null, - groupAddress3, - groupPort3, - timeout); + dg3 = newDiscoveryGroup("group-3::" + RandomUtil.randomString(), "group-3::" + RandomUtil.randomString(), null, groupAddress3, groupPort3, timeout); dg3.start(); bg1.broadcastConnectors(); @@ -806,20 +660,14 @@ public class DiscoveryTest extends DiscoveryBaseTest // } @Test - public void testDiscoveryListenersCalled() throws Exception - { + public void testDiscoveryListenersCalled() throws Exception { final InetAddress groupAddress = InetAddress.getByName(address1); final int groupPort = getUDPDiscoveryPort(); final int timeout = 500; String nodeID = RandomUtil.randomString(); - bg = newBroadcast(nodeID, - RandomUtil.randomString(), - null, - -1, - groupAddress, - groupPort); + bg = newBroadcast(nodeID, RandomUtil.randomString(), null, -1, groupAddress, groupPort); bg.start(); @@ -827,12 +675,7 @@ public class DiscoveryTest extends DiscoveryBaseTest bg.addConnector(live1); - dg = newDiscoveryGroup(RandomUtil.randomString(), - RandomUtil.randomString(), - null, - groupAddress, - groupPort, - timeout); + dg = newDiscoveryGroup(RandomUtil.randomString(), RandomUtil.randomString(), null, groupAddress, groupPort, timeout); MyListener listener1 = new MyListener(); MyListener listener2 = new MyListener(); @@ -863,8 +706,7 @@ public class DiscoveryTest extends DiscoveryBaseTest } @Test - public void testConnectorsUpdatedMultipleBroadcasters() throws Exception - { + public void testConnectorsUpdatedMultipleBroadcasters() throws Exception { final InetAddress groupAddress = InetAddress.getByName(address1); final int groupPort = getUDPDiscoveryPort(); final int timeout = 500; @@ -873,28 +715,13 @@ public class DiscoveryTest extends DiscoveryBaseTest String node2 = RandomUtil.randomString(); String node3 = RandomUtil.randomString(); - bg1 = newBroadcast(node1, - RandomUtil.randomString(), - null, - -1, - groupAddress, - groupPort); + bg1 = newBroadcast(node1, RandomUtil.randomString(), null, -1, groupAddress, groupPort); bg1.start(); - bg2 = newBroadcast(node2, - RandomUtil.randomString(), - null, - -1, - groupAddress, - groupPort); + bg2 = newBroadcast(node2, RandomUtil.randomString(), null, -1, groupAddress, groupPort); bg2.start(); - bg3 = newBroadcast(node3, - RandomUtil.randomString(), - null, - -1, - groupAddress, - groupPort); + bg3 = newBroadcast(node3, RandomUtil.randomString(), null, -1, groupAddress, groupPort); bg3.start(); TransportConfiguration live1 = generateTC(); @@ -906,12 +733,7 @@ public class DiscoveryTest extends DiscoveryBaseTest TransportConfiguration live3 = generateTC(); bg3.addConnector(live3); - dg = newDiscoveryGroup(RandomUtil.randomString(), - RandomUtil.randomString(), - null, - groupAddress, - groupPort, - timeout); + dg = newDiscoveryGroup(RandomUtil.randomString(), RandomUtil.randomString(), null, groupAddress, groupPort, timeout); MyListener listener1 = new MyListener(); dg.registerListener(listener1); @@ -1031,20 +853,14 @@ public class DiscoveryTest extends DiscoveryBaseTest } @Test - public void testMultipleDiscoveryGroups() throws Exception - { + public void testMultipleDiscoveryGroups() throws Exception { final InetAddress groupAddress = InetAddress.getByName(address1); final int groupPort = getUDPDiscoveryPort(); final int timeout = 500; String nodeID = RandomUtil.randomString(); - bg = newBroadcast(nodeID, - RandomUtil.randomString(), - null, - -1, - groupAddress, - groupPort); + bg = newBroadcast(nodeID, RandomUtil.randomString(), null, -1, groupAddress, groupPort); bg.start(); @@ -1052,26 +868,11 @@ public class DiscoveryTest extends DiscoveryBaseTest bg.addConnector(live1); - dg1 = newDiscoveryGroup(RandomUtil.randomString(), - RandomUtil.randomString(), - null, - groupAddress, - groupPort, - timeout); + dg1 = newDiscoveryGroup(RandomUtil.randomString(), RandomUtil.randomString(), null, groupAddress, groupPort, timeout); - dg2 = newDiscoveryGroup(RandomUtil.randomString(), - RandomUtil.randomString(), - null, - groupAddress, - groupPort, - timeout); + dg2 = newDiscoveryGroup(RandomUtil.randomString(), RandomUtil.randomString(), null, groupAddress, groupPort, timeout); - dg3 = newDiscoveryGroup(RandomUtil.randomString(), - RandomUtil.randomString(), - null, - groupAddress, - groupPort, - timeout); + dg3 = newDiscoveryGroup(RandomUtil.randomString(), RandomUtil.randomString(), null, groupAddress, groupPort, timeout); dg1.start(); dg2.start(); @@ -1102,8 +903,7 @@ public class DiscoveryTest extends DiscoveryBaseTest } @Test - public void testDiscoveryGroupNotifications() throws Exception - { + public void testDiscoveryGroupNotifications() throws Exception { SimpleNotificationService notifService = new SimpleNotificationService(); SimpleNotificationService.Listener notifListener = new SimpleNotificationService.Listener(); notifService.addNotificationListener(notifListener); @@ -1112,12 +912,7 @@ public class DiscoveryTest extends DiscoveryBaseTest final int groupPort = getUDPDiscoveryPort(); final int timeout = 500; - dg = newDiscoveryGroup(RandomUtil.randomString(), - RandomUtil.randomString(), - null, - groupAddress, - groupPort, - timeout, notifService); + dg = newDiscoveryGroup(RandomUtil.randomString(), RandomUtil.randomString(), null, groupAddress, groupPort, timeout, notifService); Assert.assertEquals(0, notifListener.getNotifications().size()); @@ -1126,23 +921,18 @@ public class DiscoveryTest extends DiscoveryBaseTest Assert.assertEquals(1, notifListener.getNotifications().size()); Notification notif = notifListener.getNotifications().get(0); Assert.assertEquals(CoreNotificationType.DISCOVERY_GROUP_STARTED, notif.getType()); - Assert.assertEquals(dg.getName(), notif.getProperties() - .getSimpleStringProperty(new SimpleString("name")) - .toString()); + Assert.assertEquals(dg.getName(), notif.getProperties().getSimpleStringProperty(new SimpleString("name")).toString()); dg.stop(); Assert.assertEquals(2, notifListener.getNotifications().size()); notif = notifListener.getNotifications().get(1); Assert.assertEquals(CoreNotificationType.DISCOVERY_GROUP_STOPPED, notif.getType()); - Assert.assertEquals(dg.getName(), notif.getProperties() - .getSimpleStringProperty(new SimpleString("name")) - .toString()); + Assert.assertEquals(dg.getName(), notif.getProperties().getSimpleStringProperty(new SimpleString("name")).toString()); } @Test - public void testBroadcastGroupNotifications() throws Exception - { + public void testBroadcastGroupNotifications() throws Exception { SimpleNotificationService notifService = new SimpleNotificationService(); SimpleNotificationService.Listener notifListener = new SimpleNotificationService.Listener(); notifService.addNotificationListener(notifListener); @@ -1150,12 +940,7 @@ public class DiscoveryTest extends DiscoveryBaseTest final InetAddress groupAddress = InetAddress.getByName(address1); final int groupPort = getUDPDiscoveryPort(); - bg = newBroadcast(RandomUtil.randomString(), - RandomUtil.randomString(), - null, - -1, - groupAddress, - groupPort); + bg = newBroadcast(RandomUtil.randomString(), RandomUtil.randomString(), null, -1, groupAddress, groupPort); bg.setNotificationService(notifService); @@ -1166,17 +951,13 @@ public class DiscoveryTest extends DiscoveryBaseTest Assert.assertEquals(1, notifListener.getNotifications().size()); Notification notif = notifListener.getNotifications().get(0); Assert.assertEquals(CoreNotificationType.BROADCAST_GROUP_STARTED, notif.getType()); - Assert.assertEquals(bg.getName(), notif.getProperties() - .getSimpleStringProperty(new SimpleString("name")) - .toString()); + Assert.assertEquals(bg.getName(), notif.getProperties().getSimpleStringProperty(new SimpleString("name")).toString()); bg.stop(); Assert.assertEquals(2, notifListener.getNotifications().size()); notif = notifListener.getNotifications().get(1); Assert.assertEquals(CoreNotificationType.BROADCAST_GROUP_STOPPED, notif.getType()); - Assert.assertEquals(bg.getName(), notif.getProperties() - .getSimpleStringProperty(new SimpleString("name")) - .toString()); + Assert.assertEquals(bg.getName(), notif.getProperties().getSimpleStringProperty(new SimpleString("name")).toString()); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/divert/DivertTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/divert/DivertTest.java index 23c01910b4..c1b89e4324 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/divert/DivertTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/divert/DivertTest.java @@ -43,25 +43,19 @@ import org.junit.Test; import java.util.Collection; import java.util.concurrent.TimeUnit; -public class DivertTest extends ActiveMQTestBase -{ +public class DivertTest extends ActiveMQTestBase { + private static final int TIMEOUT = 500; @Test - public void testSingleNonExclusiveDivert() throws Exception - { + public void testSingleNonExclusiveDivert() throws Exception { final String testAddress = "testAddress"; final String forwardAddress = "forwardAddress"; - DivertConfiguration divertConf = new DivertConfiguration() - .setName("divert1") - .setRoutingName("divert1") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress); + DivertConfiguration divertConf = new DivertConfiguration().setName("divert1").setRoutingName("divert1").setAddress(testAddress).setForwardingAddress(forwardAddress); - Configuration config = createDefaultInVMConfig() - .addDivertConfiguration(divertConf); + Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false)); @@ -93,8 +87,7 @@ public class DivertTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("testkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.putIntProperty(propKey, i); @@ -102,8 +95,7 @@ public class DivertTest extends ActiveMQTestBase producer.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -115,8 +107,7 @@ public class DivertTest extends ActiveMQTestBase Assert.assertNull(consumer1.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer2.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -129,29 +120,19 @@ public class DivertTest extends ActiveMQTestBase Assert.assertNull(consumer2.receiveImmediate()); } - @Test - public void testSingleDivertWithExpiry() throws Exception - { + public void testSingleDivertWithExpiry() throws Exception { final String testAddress = "testAddress"; final String forwardAddress = "forwardAddress"; final String expiryAddress = "expiryAddress"; - AddressSettings expirySettings = new AddressSettings() - .setExpiryAddress(new SimpleString(expiryAddress)); + AddressSettings expirySettings = new AddressSettings().setExpiryAddress(new SimpleString(expiryAddress)); - DivertConfiguration divertConf = new DivertConfiguration() - .setName("divert1") - .setRoutingName("divert1") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress); + DivertConfiguration divertConf = new DivertConfiguration().setName("divert1").setRoutingName("divert1").setAddress(testAddress).setForwardingAddress(forwardAddress); - Configuration config = createDefaultInVMConfig() - .addDivertConfiguration(divertConf) - .clearAddressesSettings() - .addAddressesSetting("#", expirySettings); + Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf).clearAddressesSettings().addAddressesSetting("#", expirySettings); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, true)); @@ -185,8 +166,7 @@ public class DivertTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("testkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(true); message.putIntProperty(propKey, i); @@ -197,21 +177,18 @@ public class DivertTest extends ActiveMQTestBase } session.commit(); - // this context is validating if these messages are routed correctly { int count1 = 0; ClientMessage message = null; - while ((message = consumer1.receiveImmediate()) != null) - { + while ((message = consumer1.receiveImmediate()) != null) { message.acknowledge(); count1++; } int count2 = 0; message = null; - while ((message = consumer2.receiveImmediate()) != null) - { + while ((message = consumer2.receiveImmediate()) != null) { message.acknowledge(); count2++; } @@ -231,22 +208,18 @@ public class DivertTest extends ActiveMQTestBase int countOriginal2 = 0; ClientConsumer consumerExpiry = session.createConsumer(expiryAddress); - for (int i = 0; i < numMessages * 2; i++) - { + for (int i = 0; i < numMessages * 2; i++) { ClientMessage message = consumerExpiry.receive(5000); System.out.println("Received message " + message); assertNotNull(message); - if (message.getStringProperty(MessageImpl.HDR_ORIGINAL_QUEUE).equals("queue1")) - { + if (message.getStringProperty(MessageImpl.HDR_ORIGINAL_QUEUE).equals("queue1")) { countOriginal1++; } - else if (message.getStringProperty(MessageImpl.HDR_ORIGINAL_QUEUE).equals("queue2")) - { + else if (message.getStringProperty(MessageImpl.HDR_ORIGINAL_QUEUE).equals("queue2")) { countOriginal2++; } - else - { + else { System.out.println("message not part of any expired queue" + message); } } @@ -256,20 +229,14 @@ public class DivertTest extends ActiveMQTestBase } @Test - public void testSingleNonExclusiveDivert2() throws Exception - { + public void testSingleNonExclusiveDivert2() throws Exception { final String testAddress = "testAddress"; final String forwardAddress = "forwardAddress"; - DivertConfiguration divertConf = new DivertConfiguration() - .setName("divert1") - .setRoutingName("divert1") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress); + DivertConfiguration divertConf = new DivertConfiguration().setName("divert1").setRoutingName("divert1").setAddress(testAddress).setForwardingAddress(forwardAddress); - Configuration config = createDefaultInVMConfig() - .addDivertConfiguration(divertConf); + Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false)); @@ -313,8 +280,7 @@ public class DivertTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("testkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.putIntProperty(propKey, i); @@ -322,8 +288,7 @@ public class DivertTest extends ActiveMQTestBase producer.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -335,8 +300,7 @@ public class DivertTest extends ActiveMQTestBase Assert.assertNull(consumer1.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer2.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -348,8 +312,7 @@ public class DivertTest extends ActiveMQTestBase Assert.assertNull(consumer2.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer3.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -361,8 +324,7 @@ public class DivertTest extends ActiveMQTestBase Assert.assertNull(consumer3.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer4.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -376,20 +338,14 @@ public class DivertTest extends ActiveMQTestBase } @Test - public void testSingleNonExclusiveDivert3() throws Exception - { + public void testSingleNonExclusiveDivert3() throws Exception { final String testAddress = "testAddress"; final String forwardAddress = "forwardAddress"; - DivertConfiguration divertConf = new DivertConfiguration() - .setName("divert1") - .setRoutingName("divert1") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress); + DivertConfiguration divertConf = new DivertConfiguration().setName("divert1").setRoutingName("divert1").setAddress(testAddress).setForwardingAddress(forwardAddress); - Configuration config = createDefaultInVMConfig() - .addDivertConfiguration(divertConf); + Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false)); @@ -414,8 +370,7 @@ public class DivertTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("testkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.putIntProperty(propKey, i); @@ -423,8 +378,7 @@ public class DivertTest extends ActiveMQTestBase producer.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -438,21 +392,14 @@ public class DivertTest extends ActiveMQTestBase } @Test - public void testSingleExclusiveDivert() throws Exception - { + public void testSingleExclusiveDivert() throws Exception { final String testAddress = "testAddress"; final String forwardAddress = "forwardAddress"; - DivertConfiguration divertConf = new DivertConfiguration() - .setName("divert1") - .setRoutingName("divert1") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress) - .setExclusive(true); + DivertConfiguration divertConf = new DivertConfiguration().setName("divert1").setRoutingName("divert1").setAddress(testAddress).setForwardingAddress(forwardAddress).setExclusive(true); - Configuration config = createDefaultInVMConfig() - .addDivertConfiguration(divertConf); + Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false)); @@ -493,8 +440,7 @@ public class DivertTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("testkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.putIntProperty(propKey, i); @@ -502,8 +448,7 @@ public class DivertTest extends ActiveMQTestBase producer.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -523,36 +468,20 @@ public class DivertTest extends ActiveMQTestBase } @Test - public void testMultipleNonExclusiveDivert() throws Exception - { + public void testMultipleNonExclusiveDivert() throws Exception { final String testAddress = "testAddress"; final String forwardAddress1 = "forwardAddress1"; final String forwardAddress2 = "forwardAddress2"; final String forwardAddress3 = "forwardAddress3"; - DivertConfiguration divertConf1 = new DivertConfiguration() - .setName("divert1") - .setRoutingName("divert1") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress1); + DivertConfiguration divertConf1 = new DivertConfiguration().setName("divert1").setRoutingName("divert1").setAddress(testAddress).setForwardingAddress(forwardAddress1); - DivertConfiguration divertConf2 = new DivertConfiguration() - .setName("divert2") - .setRoutingName("divert2") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress2); + DivertConfiguration divertConf2 = new DivertConfiguration().setName("divert2").setRoutingName("divert2").setAddress(testAddress).setForwardingAddress(forwardAddress2); - DivertConfiguration divertConf3 = new DivertConfiguration() - .setName("divert3") - .setRoutingName("divert3") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress3); + DivertConfiguration divertConf3 = new DivertConfiguration().setName("divert3").setRoutingName("divert3").setAddress(testAddress).setForwardingAddress(forwardAddress3); - Configuration config = createDefaultInVMConfig() - .addDivertConfiguration(divertConf1) - .addDivertConfiguration(divertConf2) - .addDivertConfiguration(divertConf3); + Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf1).addDivertConfiguration(divertConf2).addDivertConfiguration(divertConf3); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false)); @@ -595,8 +524,7 @@ public class DivertTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("testkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.putIntProperty(propKey, i); @@ -604,8 +532,7 @@ public class DivertTest extends ActiveMQTestBase producer.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -617,8 +544,7 @@ public class DivertTest extends ActiveMQTestBase Assert.assertNull(consumer1.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer2.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -630,8 +556,7 @@ public class DivertTest extends ActiveMQTestBase Assert.assertNull(consumer2.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer3.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -643,8 +568,7 @@ public class DivertTest extends ActiveMQTestBase Assert.assertNull(consumer3.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer4.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -658,39 +582,20 @@ public class DivertTest extends ActiveMQTestBase } @Test - public void testMultipleExclusiveDivert() throws Exception - { + public void testMultipleExclusiveDivert() throws Exception { final String testAddress = "testAddress"; final String forwardAddress1 = "forwardAddress1"; final String forwardAddress2 = "forwardAddress2"; final String forwardAddress3 = "forwardAddress3"; - DivertConfiguration divertConf1 = new DivertConfiguration() - .setName("divert1") - .setRoutingName("divert1") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress1) - .setExclusive(true); + DivertConfiguration divertConf1 = new DivertConfiguration().setName("divert1").setRoutingName("divert1").setAddress(testAddress).setForwardingAddress(forwardAddress1).setExclusive(true); - DivertConfiguration divertConf2 = new DivertConfiguration() - .setName("divert2") - .setRoutingName("divert2") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress2) - .setExclusive(true); + DivertConfiguration divertConf2 = new DivertConfiguration().setName("divert2").setRoutingName("divert2").setAddress(testAddress).setForwardingAddress(forwardAddress2).setExclusive(true); - DivertConfiguration divertConf3 = new DivertConfiguration() - .setName("divert3") - .setRoutingName("divert3") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress3) - .setExclusive(true); + DivertConfiguration divertConf3 = new DivertConfiguration().setName("divert3").setRoutingName("divert3").setAddress(testAddress).setForwardingAddress(forwardAddress3).setExclusive(true); - Configuration config = createDefaultInVMConfig() - .addDivertConfiguration(divertConf1) - .addDivertConfiguration(divertConf2) - .addDivertConfiguration(divertConf3); + Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf1).addDivertConfiguration(divertConf2).addDivertConfiguration(divertConf3); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false)); @@ -734,8 +639,7 @@ public class DivertTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("testkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.putIntProperty(propKey, i); @@ -743,8 +647,7 @@ public class DivertTest extends ActiveMQTestBase producer.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -756,8 +659,7 @@ public class DivertTest extends ActiveMQTestBase Assert.assertNull(consumer1.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer2.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -769,8 +671,7 @@ public class DivertTest extends ActiveMQTestBase Assert.assertNull(consumer2.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer3.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -786,38 +687,20 @@ public class DivertTest extends ActiveMQTestBase } @Test - public void testMixExclusiveAndNonExclusiveDiverts() throws Exception - { + public void testMixExclusiveAndNonExclusiveDiverts() throws Exception { final String testAddress = "testAddress"; final String forwardAddress1 = "forwardAddress1"; final String forwardAddress2 = "forwardAddress2"; final String forwardAddress3 = "forwardAddress3"; - DivertConfiguration divertConf1 = new DivertConfiguration() - .setName("divert1") - .setRoutingName("divert1") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress1) - .setExclusive(true); + DivertConfiguration divertConf1 = new DivertConfiguration().setName("divert1").setRoutingName("divert1").setAddress(testAddress).setForwardingAddress(forwardAddress1).setExclusive(true); - DivertConfiguration divertConf2 = new DivertConfiguration() - .setName("divert2") - .setRoutingName("divert2") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress2) - .setExclusive(true); + DivertConfiguration divertConf2 = new DivertConfiguration().setName("divert2").setRoutingName("divert2").setAddress(testAddress).setForwardingAddress(forwardAddress2).setExclusive(true); - DivertConfiguration divertConf3 = new DivertConfiguration() - .setName("divert3") - .setRoutingName("divert3") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress3); + DivertConfiguration divertConf3 = new DivertConfiguration().setName("divert3").setRoutingName("divert3").setAddress(testAddress).setForwardingAddress(forwardAddress3); - Configuration config = createDefaultInVMConfig() - .addDivertConfiguration(divertConf1) - .addDivertConfiguration(divertConf2) - .addDivertConfiguration(divertConf3); + Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf1).addDivertConfiguration(divertConf2).addDivertConfiguration(divertConf3); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false)); @@ -860,8 +743,7 @@ public class DivertTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("testkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.putIntProperty(propKey, i); @@ -869,8 +751,7 @@ public class DivertTest extends ActiveMQTestBase producer.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -882,8 +763,7 @@ public class DivertTest extends ActiveMQTestBase Assert.assertNull(consumer1.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer2.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -902,8 +782,7 @@ public class DivertTest extends ActiveMQTestBase // If no exclusive diverts match then non exclusive ones should be called @Test - public void testSingleExclusiveNonMatchingAndNonExclusiveDiverts() throws Exception - { + public void testSingleExclusiveNonMatchingAndNonExclusiveDiverts() throws Exception { final String testAddress = "testAddress"; final String forwardAddress1 = "forwardAddress1"; @@ -912,30 +791,13 @@ public class DivertTest extends ActiveMQTestBase final String filter = "animal='antelope'"; - DivertConfiguration divertConf1 = new DivertConfiguration() - .setName("divert1") - .setRoutingName("divert1") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress1) - .setExclusive(true) - .setFilterString(filter); + DivertConfiguration divertConf1 = new DivertConfiguration().setName("divert1").setRoutingName("divert1").setAddress(testAddress).setForwardingAddress(forwardAddress1).setExclusive(true).setFilterString(filter); - DivertConfiguration divertConf2 = new DivertConfiguration() - .setName("divert2") - .setRoutingName("divert2") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress2); + DivertConfiguration divertConf2 = new DivertConfiguration().setName("divert2").setRoutingName("divert2").setAddress(testAddress).setForwardingAddress(forwardAddress2); - DivertConfiguration divertConf3 = new DivertConfiguration() - .setName("divert3") - .setRoutingName("divert3") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress3); + DivertConfiguration divertConf3 = new DivertConfiguration().setName("divert3").setRoutingName("divert3").setAddress(testAddress).setForwardingAddress(forwardAddress3); - Configuration config = createDefaultInVMConfig() - .addDivertConfiguration(divertConf1) - .addDivertConfiguration(divertConf2) - .addDivertConfiguration(divertConf3); + Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf1).addDivertConfiguration(divertConf2).addDivertConfiguration(divertConf3); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false)); @@ -979,8 +841,7 @@ public class DivertTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("testkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.putStringProperty(new SimpleString("animal"), new SimpleString("giraffe")); @@ -1003,8 +864,7 @@ public class DivertTest extends ActiveMQTestBase Assert.assertNull(consumer1.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer2.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -1016,8 +876,7 @@ public class DivertTest extends ActiveMQTestBase Assert.assertNull(consumer2.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer3.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -1029,8 +888,7 @@ public class DivertTest extends ActiveMQTestBase Assert.assertNull(consumer3.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer4.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -1042,8 +900,7 @@ public class DivertTest extends ActiveMQTestBase Assert.assertNull(consumer4.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.putStringProperty(new SimpleString("animal"), new SimpleString("antelope")); @@ -1053,8 +910,7 @@ public class DivertTest extends ActiveMQTestBase producer.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -1074,36 +930,20 @@ public class DivertTest extends ActiveMQTestBase } @Test - public void testRoundRobinDiverts() throws Exception - { + public void testRoundRobinDiverts() throws Exception { final String testAddress = "testAddress"; final String forwardAddress1 = "forwardAddress1"; final String forwardAddress2 = "forwardAddress2"; final String forwardAddress3 = "forwardAddress3"; - DivertConfiguration divertConf1 = new DivertConfiguration() - .setName("divert1") - .setRoutingName("thename") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress1); + DivertConfiguration divertConf1 = new DivertConfiguration().setName("divert1").setRoutingName("thename").setAddress(testAddress).setForwardingAddress(forwardAddress1); - DivertConfiguration divertConf2 = new DivertConfiguration() - .setName("divert2") - .setRoutingName("thename") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress2); + DivertConfiguration divertConf2 = new DivertConfiguration().setName("divert2").setRoutingName("thename").setAddress(testAddress).setForwardingAddress(forwardAddress2); - DivertConfiguration divertConf3 = new DivertConfiguration() - .setName("divert3") - .setRoutingName("thename") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress3); + DivertConfiguration divertConf3 = new DivertConfiguration().setName("divert3").setRoutingName("thename").setAddress(testAddress).setForwardingAddress(forwardAddress3); - Configuration config = createDefaultInVMConfig() - .addDivertConfiguration(divertConf1) - .addDivertConfiguration(divertConf2) - .addDivertConfiguration(divertConf3); + Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf1).addDivertConfiguration(divertConf2).addDivertConfiguration(divertConf3); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false)); @@ -1147,8 +987,7 @@ public class DivertTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("testkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.putIntProperty(propKey, i); @@ -1156,8 +995,7 @@ public class DivertTest extends ActiveMQTestBase producer.send(message); } - for (int i = 0; i < numMessages; ) - { + for (int i = 0; i < numMessages; ) { ClientMessage message = consumer1.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -1168,8 +1006,7 @@ public class DivertTest extends ActiveMQTestBase i++; - if (i == numMessages) - { + if (i == numMessages) { break; } @@ -1183,8 +1020,7 @@ public class DivertTest extends ActiveMQTestBase i++; - if (i == numMessages) - { + if (i == numMessages) { break; } @@ -1203,8 +1039,7 @@ public class DivertTest extends ActiveMQTestBase Assert.assertNull(consumer2.receiveImmediate()); Assert.assertNull(consumer3.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer4.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -1218,36 +1053,20 @@ public class DivertTest extends ActiveMQTestBase } @Test - public void testDeployDivertsSameUniqueName() throws Exception - { + public void testDeployDivertsSameUniqueName() throws Exception { final String testAddress = "testAddress"; final String forwardAddress1 = "forwardAddress1"; final String forwardAddress2 = "forwardAddress2"; final String forwardAddress3 = "forwardAddress3"; - DivertConfiguration divertConf1 = new DivertConfiguration() - .setName("divert1") - .setRoutingName("thename1") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress1); + DivertConfiguration divertConf1 = new DivertConfiguration().setName("divert1").setRoutingName("thename1").setAddress(testAddress).setForwardingAddress(forwardAddress1); - DivertConfiguration divertConf2 = new DivertConfiguration() - .setName("divert1") - .setRoutingName("thename2") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress2); + DivertConfiguration divertConf2 = new DivertConfiguration().setName("divert1").setRoutingName("thename2").setAddress(testAddress).setForwardingAddress(forwardAddress2); - DivertConfiguration divertConf3 = new DivertConfiguration() - .setName("divert2") - .setRoutingName("thename3") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress3); + DivertConfiguration divertConf3 = new DivertConfiguration().setName("divert2").setRoutingName("thename3").setAddress(testAddress).setForwardingAddress(forwardAddress3); - Configuration config = createDefaultInVMConfig() - .addDivertConfiguration(divertConf1) - .addDivertConfiguration(divertConf2) - .addDivertConfiguration(divertConf3); + Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf1).addDivertConfiguration(divertConf2).addDivertConfiguration(divertConf3); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false)); @@ -1293,8 +1112,7 @@ public class DivertTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("testkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.putIntProperty(propKey, i); @@ -1302,8 +1120,7 @@ public class DivertTest extends ActiveMQTestBase producer.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -1317,8 +1134,7 @@ public class DivertTest extends ActiveMQTestBase Assert.assertNull(consumer2.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer3.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -1330,8 +1146,7 @@ public class DivertTest extends ActiveMQTestBase Assert.assertNull(consumer3.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer4.receive(DivertTest.TIMEOUT); Assert.assertNotNull(message); @@ -1345,17 +1160,14 @@ public class DivertTest extends ActiveMQTestBase } @Test - public void testInjectedTransformer() throws Exception - { + public void testInjectedTransformer() throws Exception { final SimpleString ADDRESS = new SimpleString("myAddress"); final String DIVERT = "myDivert"; ServiceRegistryImpl serviceRegistry = new ServiceRegistryImpl(); - Transformer transformer = new Transformer() - { + Transformer transformer = new Transformer() { @Override - public ServerMessage transform(ServerMessage message) - { + public ServerMessage transform(ServerMessage message) { return null; } }; @@ -1365,17 +1177,12 @@ public class DivertTest extends ActiveMQTestBase server.start(); server.waitForActivation(100, TimeUnit.MILLISECONDS); server.deployQueue(ADDRESS, SimpleString.toSimpleString("myQueue"), null, false, false); - server.deployDivert(new DivertConfiguration() - .setName(DIVERT) - .setAddress(ADDRESS.toString()) - .setForwardingAddress(ADDRESS.toString())); + server.deployDivert(new DivertConfiguration().setName(DIVERT).setAddress(ADDRESS.toString()).setForwardingAddress(ADDRESS.toString())); Collection bindings = server.getPostOffice().getBindingsForAddress(ADDRESS).getBindings(); Divert divert = null; - for (Binding binding : bindings) - { - if (binding instanceof DivertBinding) - { - divert = ((DivertBinding)binding).getDivert(); + for (Binding binding : bindings) { + if (binding instanceof DivertBinding) { + divert = ((DivertBinding) binding).getDivert(); } } assertNotNull(divert); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/divert/PersistentDivertTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/divert/PersistentDivertTest.java index 92178ee47b..38489303ad 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/divert/PersistentDivertTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/divert/PersistentDivertTest.java @@ -32,24 +32,21 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Assert; import org.junit.Test; -public class PersistentDivertTest extends ActiveMQTestBase -{ +public class PersistentDivertTest extends ActiveMQTestBase { + final int minLargeMessageSize = ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE * 2; @Test - public void testPersistentDivert() throws Exception - { + public void testPersistentDivert() throws Exception { doTestPersistentDivert(false); } @Test - public void testPersistentDiverLargeMessage() throws Exception - { + public void testPersistentDiverLargeMessage() throws Exception { doTestPersistentDivert(true); } - public void doTestPersistentDivert(final boolean largeMessage) throws Exception - { + public void doTestPersistentDivert(final boolean largeMessage) throws Exception { final String testAddress = "testAddress"; final String forwardAddress1 = "forwardAddress1"; @@ -58,37 +55,19 @@ public class PersistentDivertTest extends ActiveMQTestBase final String forwardAddress3 = "forwardAddress3"; - DivertConfiguration divertConf1 = new DivertConfiguration() - .setName("divert1") - .setRoutingName("divert1") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress1); + DivertConfiguration divertConf1 = new DivertConfiguration().setName("divert1").setRoutingName("divert1").setAddress(testAddress).setForwardingAddress(forwardAddress1); - DivertConfiguration divertConf2 = new DivertConfiguration() - .setName("divert2") - .setRoutingName("divert2") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress2); + DivertConfiguration divertConf2 = new DivertConfiguration().setName("divert2").setRoutingName("divert2").setAddress(testAddress).setForwardingAddress(forwardAddress2); - DivertConfiguration divertConf3 = new DivertConfiguration() - .setName("divert3") - .setRoutingName("divert3") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress3); + DivertConfiguration divertConf3 = new DivertConfiguration().setName("divert3").setRoutingName("divert3").setAddress(testAddress).setForwardingAddress(forwardAddress3); - Configuration config = createDefaultInVMConfig() - .addDivertConfiguration(divertConf1) - .addDivertConfiguration(divertConf2) - .addDivertConfiguration(divertConf3); + Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf1).addDivertConfiguration(divertConf2).addDivertConfiguration(divertConf3); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config)); server.start(); - ServerLocator locator = createInVMNonHALocator() - .setBlockOnAcknowledge(true) - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true); + ServerLocator locator = createInVMNonHALocator().setBlockOnAcknowledge(true).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true); ClientSessionFactory sf = createSessionFactory(locator); @@ -126,12 +105,10 @@ public class PersistentDivertTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("testkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(true); - if (largeMessage) - { + if (largeMessage) { message.setBodyInputStream(ActiveMQTestBase.createFakeLargeStream(minLargeMessageSize)); } @@ -140,16 +117,14 @@ public class PersistentDivertTest extends ActiveMQTestBase producer.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(5000); Assert.assertNotNull(message); Assert.assertEquals(i, message.getObjectProperty(propKey)); - if (largeMessage) - { + if (largeMessage) { checkLargeMessage(message); } @@ -158,16 +133,14 @@ public class PersistentDivertTest extends ActiveMQTestBase Assert.assertNull(consumer1.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer2.receive(5000); Assert.assertNotNull(message); Assert.assertEquals(i, message.getObjectProperty(propKey)); - if (largeMessage) - { + if (largeMessage) { checkLargeMessage(message); } @@ -176,16 +149,14 @@ public class PersistentDivertTest extends ActiveMQTestBase Assert.assertNull(consumer2.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer3.receive(5000); Assert.assertNotNull(message); Assert.assertEquals(i, message.getObjectProperty(propKey)); - if (largeMessage) - { + if (largeMessage) { checkLargeMessage(message); } @@ -194,16 +165,14 @@ public class PersistentDivertTest extends ActiveMQTestBase Assert.assertNull(consumer3.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer4.receive(5000); Assert.assertNotNull(message); Assert.assertEquals(i, message.getObjectProperty(propKey)); - if (largeMessage) - { + if (largeMessage) { checkLargeMessage(message); } @@ -216,28 +185,23 @@ public class PersistentDivertTest extends ActiveMQTestBase /** * @param message */ - private void checkLargeMessage(final ClientMessage message) - { - for (int j = 0; j < minLargeMessageSize; j++) - { + private void checkLargeMessage(final ClientMessage message) { + for (int j = 0; j < minLargeMessageSize; j++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(j), message.getBodyBuffer().readByte()); } } @Test - public void testPersistentDivertRestartBeforeConsume() throws Exception - { + public void testPersistentDivertRestartBeforeConsume() throws Exception { doTestPersistentDivertRestartBeforeConsume(false); } @Test - public void testPersistentDivertRestartBeforeConsumeLargeMessage() throws Exception - { + public void testPersistentDivertRestartBeforeConsumeLargeMessage() throws Exception { doTestPersistentDivertRestartBeforeConsume(true); } - public void doTestPersistentDivertRestartBeforeConsume(final boolean largeMessage) throws Exception - { + public void doTestPersistentDivertRestartBeforeConsume(final boolean largeMessage) throws Exception { final String testAddress = "testAddress"; final String forwardAddress1 = "forwardAddress1"; @@ -246,37 +210,19 @@ public class PersistentDivertTest extends ActiveMQTestBase final String forwardAddress3 = "forwardAddress3"; - DivertConfiguration divertConf1 = new DivertConfiguration() - .setName("divert1") - .setRoutingName("divert1") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress1); + DivertConfiguration divertConf1 = new DivertConfiguration().setName("divert1").setRoutingName("divert1").setAddress(testAddress).setForwardingAddress(forwardAddress1); - DivertConfiguration divertConf2 = new DivertConfiguration() - .setName("divert2") - .setRoutingName("divert2") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress2); + DivertConfiguration divertConf2 = new DivertConfiguration().setName("divert2").setRoutingName("divert2").setAddress(testAddress).setForwardingAddress(forwardAddress2); - DivertConfiguration divertConf3 = new DivertConfiguration() - .setName("divert3") - .setRoutingName("divert3") - .setAddress(testAddress) - .setForwardingAddress(forwardAddress3); + DivertConfiguration divertConf3 = new DivertConfiguration().setName("divert3").setRoutingName("divert3").setAddress(testAddress).setForwardingAddress(forwardAddress3); - Configuration config = createDefaultInVMConfig() - .addDivertConfiguration(divertConf1) - .addDivertConfiguration(divertConf2) - .addDivertConfiguration(divertConf3); + Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf1).addDivertConfiguration(divertConf2).addDivertConfiguration(divertConf3); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config)); server.start(); - ServerLocator locator = createInVMNonHALocator() - .setBlockOnAcknowledge(true) - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true); + ServerLocator locator = createInVMNonHALocator().setBlockOnAcknowledge(true).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true); ClientSessionFactory sf = createSessionFactory(locator); @@ -304,14 +250,12 @@ public class PersistentDivertTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("testkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(true); message.putIntProperty(propKey, i); - if (largeMessage) - { + if (largeMessage) { message.setBodyInputStream(ActiveMQTestBase.createFakeLargeStream(minLargeMessageSize)); } @@ -328,8 +272,7 @@ public class PersistentDivertTest extends ActiveMQTestBase server.start(); - ServerLocator locator2 = createInVMNonHALocator() - .setBlockOnDurableSend(true); + ServerLocator locator2 = createInVMNonHALocator().setBlockOnDurableSend(true); sf = createSessionFactory(locator2); session = sf.createSession(false, true, true); @@ -344,14 +287,12 @@ public class PersistentDivertTest extends ActiveMQTestBase ClientConsumer consumer4 = session.createConsumer(queueName4); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(5000); Assert.assertNotNull(message); - if (largeMessage) - { + if (largeMessage) { checkLargeMessage(message); } @@ -362,14 +303,12 @@ public class PersistentDivertTest extends ActiveMQTestBase Assert.assertNull(consumer1.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer2.receive(5000); Assert.assertNotNull(message); - if (largeMessage) - { + if (largeMessage) { checkLargeMessage(message); } @@ -380,14 +319,12 @@ public class PersistentDivertTest extends ActiveMQTestBase Assert.assertNull(consumer2.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer3.receive(5000); Assert.assertNotNull(message); - if (largeMessage) - { + if (largeMessage) { checkLargeMessage(message); } @@ -398,14 +335,12 @@ public class PersistentDivertTest extends ActiveMQTestBase Assert.assertNull(consumer3.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer4.receive(5000); Assert.assertNotNull(message); - if (largeMessage) - { + if (largeMessage) { checkLargeMessage(message); } @@ -426,8 +361,7 @@ public class PersistentDivertTest extends ActiveMQTestBase server.start(); - ServerLocator locator3 = createInVMNonHALocator() - .setBlockOnDurableSend(true); + ServerLocator locator3 = createInVMNonHALocator().setBlockOnDurableSend(true); sf = createSessionFactory(locator3); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/embedded/ValidateAIOTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/embedded/ValidateAIOTest.java index 8d395c6b30..9c86d69c0b 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/embedded/ValidateAIOTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/embedded/ValidateAIOTest.java @@ -26,21 +26,18 @@ import org.junit.Test; /** * Validate if the embedded server will start even with AIO selected */ -public class ValidateAIOTest extends ActiveMQTestBase -{ +public class ValidateAIOTest extends ActiveMQTestBase { + @Test - public void testValidateAIO() throws Exception - { + public void testValidateAIO() throws Exception { Configuration config = createDefaultInVMConfig() // This will force AsyncIO .setJournalType(JournalType.ASYNCIO); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, true)); - try - { + try { server.start(); } - finally - { + finally { server.stop(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/http/CoreClientOverHttpTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/http/CoreClientOverHttpTest.java index a9c77c78ce..071389f84b 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/http/CoreClientOverHttpTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/http/CoreClientOverHttpTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.http; + import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Before; @@ -40,8 +41,8 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.ActiveMQServers; import org.apache.activemq.artemis.jms.client.ActiveMQTextMessage; -public class CoreClientOverHttpTest extends ActiveMQTestBase -{ +public class CoreClientOverHttpTest extends ActiveMQTestBase { + private static final SimpleString QUEUE = new SimpleString("CoreClientOverHttpTestQueue"); private Configuration conf; private ActiveMQServer server; @@ -49,15 +50,12 @@ public class CoreClientOverHttpTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); HashMap params = new HashMap(); params.put(TransportConstants.HTTP_ENABLED_PROP_NAME, true); - conf = createDefaultInVMConfig() - .clearAcceptorConfigurations() - .addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params)); + conf = createDefaultInVMConfig().clearAcceptorConfigurations().addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params)); server = addServer(ActiveMQServers.newActiveMQServer(conf, false)); server.start(); @@ -65,8 +63,7 @@ public class CoreClientOverHttpTest extends ActiveMQTestBase } @Test - public void testCoreHttpClient() throws Exception - { + public void testCoreHttpClient() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(false, true, true); @@ -76,13 +73,8 @@ public class CoreClientOverHttpTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte)1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.getBodyBuffer().writeString("CoreClientOverHttpTest"); producer.send(message); } @@ -91,8 +83,7 @@ public class CoreClientOverHttpTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message2 = consumer.receive(); Assert.assertEquals("CoreClientOverHttpTest", message2.getBodyBuffer().readString()); @@ -104,8 +95,7 @@ public class CoreClientOverHttpTest extends ActiveMQTestBase } @Test - public void testCoreHttpClientIdle() throws Exception - { + public void testCoreHttpClientIdle() throws Exception { locator.setConnectionTTL(500); ClientSessionFactory sf = createSessionFactory(locator); @@ -122,8 +112,7 @@ public class CoreClientOverHttpTest extends ActiveMQTestBase // https://issues.jboss.org/browse/JBPAPP-5542 @Test - public void testCoreHttpClient8kPlus() throws Exception - { + public void testCoreHttpClient8kPlus() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(false, true, true); @@ -135,13 +124,8 @@ public class CoreClientOverHttpTest extends ActiveMQTestBase String[] content = new String[numMessages]; - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte)1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); content[i] = this.getFixedSizeString(((i % 5) + 1) * 1024 * 8); message.getBodyBuffer().writeString(content[i]); producer.send(message); @@ -151,8 +135,7 @@ public class CoreClientOverHttpTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message2 = consumer.receive(); Assert.assertEquals(content[i], message2.getBodyBuffer().readString()); @@ -163,13 +146,11 @@ public class CoreClientOverHttpTest extends ActiveMQTestBase session.close(); } - private String getFixedSizeString(int size) - { + private String getFixedSizeString(int size) { StringBuffer sb = new StringBuffer(); Random r = new Random(); - for (int i = 0; i < size; i++) - { - char chr = (char)r.nextInt(256); + for (int i = 0; i < size; i++) { + char chr = (char) r.nextInt(256); sb.append(chr); } String result = sb.toString(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/ActiveMQConnectionFactoryTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/ActiveMQConnectionFactoryTest.java index bafa19cb0a..c4ddd2c4bf 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/ActiveMQConnectionFactoryTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/ActiveMQConnectionFactoryTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.jms; + import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.core.config.ha.SharedStoreMasterPolicyConfiguration; @@ -47,11 +48,10 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; import org.apache.activemq.artemis.tests.util.RandomUtil; /** - * * ActiveMQConnectionFactoryTest */ -public class ActiveMQConnectionFactoryTest extends ActiveMQTestBase -{ +public class ActiveMQConnectionFactoryTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private final String groupAddress = getUDPDiscoveryAddress(); @@ -63,53 +63,22 @@ public class ActiveMQConnectionFactoryTest extends ActiveMQTestBase private TransportConfiguration liveTC; @Test - public void testDefaultConstructor() throws Exception - { + public void testDefaultConstructor() throws Exception { ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF); - assertFactoryParams(cf, - null, - null, - null, - ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, - ActiveMQClient.DEFAULT_CONNECTION_TTL, - ActiveMQClient.DEFAULT_CALL_TIMEOUT, - ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, - ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, - ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, - ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, - ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, - ActiveMQClient.DEFAULT_AUTO_GROUP, - ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT, - ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, - ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_RETRY_INTERVAL, - ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, - ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS); + assertFactoryParams(cf, null, null, null, ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, ActiveMQClient.DEFAULT_CONNECTION_TTL, ActiveMQClient.DEFAULT_CALL_TIMEOUT, ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, ActiveMQClient.DEFAULT_AUTO_GROUP, ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT, ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_RETRY_INTERVAL, ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS); Connection conn = null; - try - { + try { conn = cf.createConnection(); conn.createSession(false, Session.AUTO_ACKNOWLEDGE); Assert.fail("Should throw exception"); } - catch (JMSException e) - { + catch (JMSException e) { // Ok } - if (conn != null) - { + if (conn != null) { conn.close(); } @@ -119,38 +88,10 @@ public class ActiveMQConnectionFactoryTest extends ActiveMQTestBase } @Test - public void testDefaultConstructorAndSetConnectorPairs() throws Exception - { + public void testDefaultConstructorAndSetConnectorPairs() throws Exception { ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, liveTC); - assertFactoryParams(cf, - new TransportConfiguration[]{liveTC}, - null, - null, - ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, - ActiveMQClient.DEFAULT_CONNECTION_TTL, - ActiveMQClient.DEFAULT_CALL_TIMEOUT, - ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, - ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, - ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, - ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, - ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, - ActiveMQClient.DEFAULT_AUTO_GROUP, - ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT, - ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, - ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_RETRY_INTERVAL, - ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, - ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS); + assertFactoryParams(cf, new TransportConfiguration[]{liveTC}, null, null, ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, ActiveMQClient.DEFAULT_CONNECTION_TTL, ActiveMQClient.DEFAULT_CALL_TIMEOUT, ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, ActiveMQClient.DEFAULT_AUTO_GROUP, ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT, ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_RETRY_INTERVAL, ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS); Connection conn = cf.createConnection(); @@ -162,41 +103,10 @@ public class ActiveMQConnectionFactoryTest extends ActiveMQTestBase } @Test - public void testDiscoveryConstructor() throws Exception - { - DiscoveryGroupConfiguration groupConfiguration = new DiscoveryGroupConfiguration() - .setBroadcastEndpointFactory(new UDPBroadcastEndpointFactory() - .setGroupAddress(groupAddress) - .setGroupPort(groupPort)); + public void testDiscoveryConstructor() throws Exception { + DiscoveryGroupConfiguration groupConfiguration = new DiscoveryGroupConfiguration().setBroadcastEndpointFactory(new UDPBroadcastEndpointFactory().setGroupAddress(groupAddress).setGroupPort(groupPort)); ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(groupConfiguration, JMSFactoryType.CF); - assertFactoryParams(cf, - null, - groupConfiguration, - null, - ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, - ActiveMQClient.DEFAULT_CONNECTION_TTL, - ActiveMQClient.DEFAULT_CALL_TIMEOUT, - ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, - ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, - ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, - ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, - ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, - ActiveMQClient.DEFAULT_AUTO_GROUP, - ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT, - ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, - ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_RETRY_INTERVAL, - ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, - ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS); + assertFactoryParams(cf, null, groupConfiguration, null, ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, ActiveMQClient.DEFAULT_CONNECTION_TTL, ActiveMQClient.DEFAULT_CALL_TIMEOUT, ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, ActiveMQClient.DEFAULT_AUTO_GROUP, ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT, ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_RETRY_INTERVAL, ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS); Connection conn = cf.createConnection(); conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -207,37 +117,9 @@ public class ActiveMQConnectionFactoryTest extends ActiveMQTestBase } @Test - public void testStaticConnectorListConstructor() throws Exception - { + public void testStaticConnectorListConstructor() throws Exception { ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, liveTC); - assertFactoryParams(cf, - new TransportConfiguration[]{liveTC}, - null, - null, - ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, - ActiveMQClient.DEFAULT_CONNECTION_TTL, - ActiveMQClient.DEFAULT_CALL_TIMEOUT, - ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, - ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, - ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, - ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, - ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, - ActiveMQClient.DEFAULT_AUTO_GROUP, - ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT, - ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, - ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_RETRY_INTERVAL, - ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, - ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS); + assertFactoryParams(cf, new TransportConfiguration[]{liveTC}, null, null, ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, ActiveMQClient.DEFAULT_CONNECTION_TTL, ActiveMQClient.DEFAULT_CALL_TIMEOUT, ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, ActiveMQClient.DEFAULT_AUTO_GROUP, ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT, ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_RETRY_INTERVAL, ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS); Connection conn = cf.createConnection(); conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -249,37 +131,9 @@ public class ActiveMQConnectionFactoryTest extends ActiveMQTestBase } @Test - public void testStaticConnectorLiveConstructor() throws Exception - { + public void testStaticConnectorLiveConstructor() throws Exception { ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, liveTC); - assertFactoryParams(cf, - new TransportConfiguration[]{liveTC}, - null, - null, - ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, - ActiveMQClient.DEFAULT_CONNECTION_TTL, - ActiveMQClient.DEFAULT_CALL_TIMEOUT, - ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, - ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, - ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, - ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, - ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, - ActiveMQClient.DEFAULT_AUTO_GROUP, - ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT, - ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, - ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_RETRY_INTERVAL, - ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, - ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS); + assertFactoryParams(cf, new TransportConfiguration[]{liveTC}, null, null, ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, ActiveMQClient.DEFAULT_CONNECTION_TTL, ActiveMQClient.DEFAULT_CALL_TIMEOUT, ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, ActiveMQClient.DEFAULT_AUTO_GROUP, ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT, ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_RETRY_INTERVAL, ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS); Connection conn = cf.createConnection(); conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -291,10 +145,8 @@ public class ActiveMQConnectionFactoryTest extends ActiveMQTestBase conn.close(); } - @Test - public void testGettersAndSetters() - { + public void testGettersAndSetters() { ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, liveTC); long clientFailureCheckPeriod = RandomUtil.randomPositiveLong(); @@ -361,8 +213,7 @@ public class ActiveMQConnectionFactoryTest extends ActiveMQTestBase cf.close(); } - private void testSettersThrowException(final ActiveMQConnectionFactory cf) - { + private void testSettersThrowException(final ActiveMQConnectionFactory cf) { String discoveryAddress = RandomUtil.randomString(); int discoveryPort = RandomUtil.randomPositiveInt(); @@ -393,211 +244,165 @@ public class ActiveMQConnectionFactoryTest extends ActiveMQTestBase int reconnectAttempts = RandomUtil.randomPositiveInt(); boolean failoverOnServerShutdown = RandomUtil.randomBoolean(); - try - { + try { cf.setClientID(clientID); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.setClientFailureCheckPeriod(clientFailureCheckPeriod); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.setConnectionTTL(connectionTTL); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.setCallTimeout(callTimeout); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.setMinLargeMessageSize(minLargeMessageSize); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.setConsumerWindowSize(consumerWindowSize); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.setConsumerMaxRate(consumerMaxRate); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.setConfirmationWindowSize(confirmationWindowSize); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.setProducerMaxRate(producerMaxRate); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.setBlockOnAcknowledge(blockOnAcknowledge); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.setBlockOnDurableSend(blockOnDurableSend); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.setBlockOnNonDurableSend(blockOnNonDurableSend); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.setAutoGroup(autoGroup); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.setPreAcknowledge(preAcknowledge); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.setConnectionLoadBalancingPolicyClassName(loadBalancingPolicyClassName); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.setDupsOKBatchSize(dupsOKBatchSize); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.setTransactionBatchSize(transactionBatchSize); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.setUseGlobalPools(useGlobalPools); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.setScheduledThreadPoolMaxSize(scheduledThreadPoolMaxSize); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.setThreadPoolMaxSize(threadPoolMaxSize); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.setRetryInterval(retryInterval); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.setRetryIntervalMultiplier(retryIntervalMultiplier); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { cf.setReconnectAttempts(reconnectAttempts); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } @@ -656,19 +461,15 @@ public class ActiveMQConnectionFactoryTest extends ActiveMQTestBase final int threadPoolMaxSize, final long retryInterval, final double retryIntervalMultiplier, - final int reconnectAttempts) - { + final int reconnectAttempts) { TransportConfiguration[] cfStaticConnectors = cf.getStaticConnectors(); - if (staticConnectors == null) - { + if (staticConnectors == null) { Assert.assertNull(staticConnectors); } - else - { + else { Assert.assertEquals(staticConnectors.length, cfStaticConnectors.length); - for (int i = 0; i < staticConnectors.length; i++) - { + for (int i = 0; i < staticConnectors.length; i++) { Assert.assertEquals(staticConnectors[i], cfStaticConnectors[i]); } } @@ -700,25 +501,20 @@ public class ActiveMQConnectionFactoryTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); startServer(); } - private void startServer() throws Exception - { + private void startServer() throws Exception { liveTC = new TransportConfiguration(INVM_CONNECTOR_FACTORY); Map connectors = new HashMap(); connectors.put(liveTC.getName(), liveTC); List connectorNames = new ArrayList(); connectorNames.add(liveTC.getName()); - Configuration liveConf = createBasicConfig() - .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY)) - .setConnectorConfigurations(connectors) - .setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration()); + Configuration liveConf = createBasicConfig().addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY)).setConnectorConfigurations(connectors).setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration()); final long broadcastPeriod = 250; @@ -726,14 +522,7 @@ public class ActiveMQConnectionFactoryTest extends ActiveMQTestBase final int localBindPort = 5432; - BroadcastGroupConfiguration bcConfig1 = new BroadcastGroupConfiguration() - .setName(bcGroupName) - .setBroadcastPeriod(broadcastPeriod) - .setConnectorInfos(connectorNames) - .setEndpointFactory(new UDPBroadcastEndpointFactory() - .setGroupAddress(groupAddress) - .setGroupPort(groupPort) - .setLocalBindPort(localBindPort)); + BroadcastGroupConfiguration bcConfig1 = new BroadcastGroupConfiguration().setName(bcGroupName).setBroadcastPeriod(broadcastPeriod).setConnectorInfos(connectorNames).setEndpointFactory(new UDPBroadcastEndpointFactory().setGroupAddress(groupAddress).setGroupPort(groupPort).setLocalBindPort(localBindPort)); List bcConfigs1 = new ArrayList(); bcConfigs1.add(bcConfig1); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/FloodServerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/FloodServerTest.java index 61db62018d..36ae11f013 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/FloodServerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/FloodServerTest.java @@ -44,11 +44,9 @@ import java.util.ArrayList; import java.util.List; /** - * * A FloodServerTest */ -public class FloodServerTest extends ActiveMQTestBase -{ +public class FloodServerTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @@ -77,8 +75,7 @@ public class FloodServerTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); Configuration config = createDefaultNettyConfig(); @@ -99,8 +96,7 @@ public class FloodServerTest extends ActiveMQTestBase // Inner classes ------------------------------------------------- - private void registerConnectionFactory() throws Exception - { + private void registerConnectionFactory() throws Exception { int retryInterval = 1000; double retryIntervalMultiplier = 1.0; int reconnectAttempts = -1; @@ -109,51 +105,15 @@ public class FloodServerTest extends ActiveMQTestBase List connectorConfigs = new ArrayList(); connectorConfigs.add(new TransportConfiguration(NettyConnectorFactory.class.getName())); - serverManager.createConnectionFactory("ManualReconnectionToSingleServerTest", - false, - JMSFactoryType.CF, - registerConnectors(server, connectorConfigs), - null, - 1000, - ActiveMQClient.DEFAULT_CONNECTION_TTL, - callTimeout, - ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, - ActiveMQClient.DEFAULT_CACHE_LARGE_MESSAGE_CLIENT, - ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES, - ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, - ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, - false, - false, - false, - ActiveMQClient.DEFAULT_AUTO_GROUP, - false, - ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, - ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, - retryInterval, - retryIntervalMultiplier, - 1000, - reconnectAttempts, - ActiveMQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION, - null, - "/cf"); + serverManager.createConnectionFactory("ManualReconnectionToSingleServerTest", false, JMSFactoryType.CF, registerConnectors(server, connectorConfigs), null, 1000, ActiveMQClient.DEFAULT_CONNECTION_TTL, callTimeout, ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, ActiveMQClient.DEFAULT_CACHE_LARGE_MESSAGE_CLIENT, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES, ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, false, false, false, ActiveMQClient.DEFAULT_AUTO_GROUP, false, ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, retryInterval, retryIntervalMultiplier, 1000, reconnectAttempts, ActiveMQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION, null, "/cf"); } @Test - public void testFoo() - { + public void testFoo() { } - public void _testFlood() throws Exception - { - ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("/cf"); + public void _testFlood() throws Exception { + ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("/cf"); final int numProducers = 20; @@ -163,42 +123,36 @@ public class FloodServerTest extends ActiveMQTestBase ProducerThread[] producers = new ProducerThread[numProducers]; - for (int i = 0; i < numProducers; i++) - { + for (int i = 0; i < numProducers; i++) { producers[i] = new ProducerThread(cf, numMessages); } ConsumerThread[] consumers = new ConsumerThread[numConsumers]; - for (int i = 0; i < numConsumers; i++) - { + for (int i = 0; i < numConsumers; i++) { consumers[i] = new ConsumerThread(cf, numMessages); } - for (int i = 0; i < numConsumers; i++) - { + for (int i = 0; i < numConsumers; i++) { consumers[i].start(); } - for (int i = 0; i < numProducers; i++) - { + for (int i = 0; i < numProducers; i++) { producers[i].start(); } - for (int i = 0; i < numConsumers; i++) - { + for (int i = 0; i < numConsumers; i++) { consumers[i].join(); } - for (int i = 0; i < numProducers; i++) - { + for (int i = 0; i < numProducers; i++) { producers[i].join(); } } - class ProducerThread extends Thread - { + class ProducerThread extends Thread { + private final Connection connection; private final Session session; @@ -207,8 +161,7 @@ public class FloodServerTest extends ActiveMQTestBase private final int numMessages; - ProducerThread(final ConnectionFactory cf, final int numMessages) throws Exception - { + ProducerThread(final ConnectionFactory cf, final int numMessages) throws Exception { connection = cf.createConnection(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -221,18 +174,15 @@ public class FloodServerTest extends ActiveMQTestBase } @Override - public void run() - { - try - { + public void run() { + try { byte[] bytes = new byte[1000]; BytesMessage message = session.createBytesMessage(); message.writeBytes(bytes); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { producer.send(message); // if (i % 1000 == 0) @@ -243,15 +193,14 @@ public class FloodServerTest extends ActiveMQTestBase connection.close(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } } - class ConsumerThread extends Thread - { + class ConsumerThread extends Thread { + private final Connection connection; private final Session session; @@ -260,8 +209,7 @@ public class FloodServerTest extends ActiveMQTestBase private final int numMessages; - ConsumerThread(final ConnectionFactory cf, final int numMessages) throws Exception - { + ConsumerThread(final ConnectionFactory cf, final int numMessages) throws Exception { connection = cf.createConnection(); connection.start(); @@ -274,16 +222,12 @@ public class FloodServerTest extends ActiveMQTestBase } @Override - public void run() - { - try - { - for (int i = 0; i < numMessages; i++) - { + public void run() { + try { + for (int i = 0; i < numMessages; i++) { Message msg = consumer.receive(); - if (msg == null) - { + if (msg == null) { FloodServerTest.log.error("message is null"); break; } @@ -296,8 +240,7 @@ public class FloodServerTest extends ActiveMQTestBase connection.close(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/JMSSecurityTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/JMSSecurityTest.java index 13a281e588..1fd74df7e3 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/JMSSecurityTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/JMSSecurityTest.java @@ -27,33 +27,28 @@ import org.apache.activemq.artemis.tests.util.JMSTestBase; import org.junit.Before; import org.junit.Test; -public class JMSSecurityTest extends JMSTestBase -{ +public class JMSSecurityTest extends JMSTestBase { + @Override - public boolean useSecurity() - { + public boolean useSecurity() { return true; } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); } @Test - public void testSecurityOnJMSContext() throws Exception - { + public void testSecurityOnJMSContext() throws Exception { ActiveMQSecurityManagerImpl securityManager = (ActiveMQSecurityManagerImpl) server.getSecurityManager(); securityManager.getConfiguration().addUser("IDo", "Exist"); - try - { + try { JMSContext ctx = cf.createContext("Idont", "exist"); ctx.close(); } - catch (JMSSecurityRuntimeException e) - { + catch (JMSSecurityRuntimeException e) { // expected } JMSContext ctx = cf.createContext("IDo", "Exist"); @@ -61,18 +56,15 @@ public class JMSSecurityTest extends JMSTestBase } @Test - public void testCreateQueueConnection() throws Exception - { + public void testCreateQueueConnection() throws Exception { ActiveMQSecurityManagerImpl securityManager = (ActiveMQSecurityManagerImpl) server.getSecurityManager(); securityManager.getConfiguration().addUser("IDo", "Exist"); - try - { - QueueConnection queueC = ((QueueConnectionFactory)cf).createQueueConnection("IDont", "Exist"); + try { + QueueConnection queueC = ((QueueConnectionFactory) cf).createQueueConnection("IDont", "Exist"); fail("supposed to throw exception"); queueC.close(); } - catch (JMSSecurityException e) - { + catch (JMSSecurityException e) { // expected } JMSContext ctx = cf.createContext("IDo", "Exist"); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/JmsProducerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/JmsProducerTest.java index b27949eac2..5e237c2c3d 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/JmsProducerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/JmsProducerTest.java @@ -37,16 +37,15 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class JmsProducerTest extends JMSTestBase -{ +public class JmsProducerTest extends JMSTestBase { + private JMSProducer producer; private Random random; private JMSContext context; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); context = createContext(); @@ -55,16 +54,14 @@ public class JmsProducerTest extends JMSTestBase } @Override - protected void testCaseCfExtraConfig(ConnectionFactoryConfiguration configuration) - { + protected void testCaseCfExtraConfig(ConnectionFactoryConfiguration configuration) { configuration.setConfirmationWindowSize(0); configuration.setPreAcknowledge(false); configuration.setBlockOnDurableSend(false); } @Test - public void testSetters() - { + public void testSetters() { long v = random.nextLong(); producer.setDeliveryDelay(v); Assert.assertEquals(v, producer.getDeliveryDelay()); @@ -78,30 +75,25 @@ public class JmsProducerTest extends JMSTestBase Assert.assertEquals(id, producer.getJMSCorrelationID()); //set a property of an invalid type (ArrayList) - try - { + try { producer.setProperty("name1", new ArrayList(2)); fail("didn't get expected MessageFormatRuntimeException"); } - catch (MessageFormatRuntimeException e) - { + catch (MessageFormatRuntimeException e) { //expected. } } @Test - public void testDisMsgID() - { + public void testDisMsgID() { producer.setDisableMessageID(true); Assert.assertEquals(true, producer.getDisableMessageID()); producer.setDisableMessageID(false); Assert.assertEquals(false, producer.getDisableMessageID()); } - @Test - public void multipleSendsUsingSetters() throws Exception - { + public void multipleSendsUsingSetters() throws Exception { jmsServer.createQueue(true, "q1", null, true, "/queues/q1"); server.createQueue(SimpleString.toSimpleString("q1"), SimpleString.toSimpleString("q1"), null, true, false); @@ -111,8 +103,7 @@ public class JmsProducerTest extends JMSTestBase context.createProducer().setProperty("prop1", 3).setProperty("prop2", 4).send(q1, "Text2"); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { context.createProducer().send(q1, "Text" + i); } @@ -137,8 +128,7 @@ public class JmsProducerTest extends JMSTestBase assertEquals(3, text.getIntProperty("prop1")); assertEquals(4, text.getIntProperty("prop2")); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { assertEquals("Text" + i, consumer.receiveBody(String.class, 1000)); } @@ -147,8 +137,7 @@ public class JmsProducerTest extends JMSTestBase } @Test - public void testDeliveryMode() - { + public void testDeliveryMode() { producer.setDeliveryMode(DeliveryMode.PERSISTENT); Assert.assertEquals(DeliveryMode.PERSISTENT, producer.getDeliveryMode()); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); @@ -156,40 +145,33 @@ public class JmsProducerTest extends JMSTestBase } @Test - public void testGetNonExistentProperties() throws Exception - { + public void testGetNonExistentProperties() throws Exception { Throwable expected = null; { //byte byte value0 = 0; - try - { + try { value0 = Byte.valueOf(null); } - catch (Throwable t) - { + catch (Throwable t) { expected = t; } - try - { + try { byte value1 = producer.getByteProperty("testGetNonExistentProperties"); - if (expected == null) - { + if (expected == null) { assertEquals("value0: " + value0 + " value1: " + value1, value1 == value0); } - else - { + else { fail("non existent byte property expects exception, but got value: " + value1); } } - catch (Throwable t) - { - if (expected == null) throw t; - if (!t.getClass().equals(expected.getClass())) - { + catch (Throwable t) { + if (expected == null) + throw t; + if (!t.getClass().equals(expected.getClass())) { throw new Exception("Expected exception: " + expected.getClass().getName() + " but got: " + t.getClass(), t); } @@ -200,33 +182,27 @@ public class JmsProducerTest extends JMSTestBase //boolean expected = null; boolean value0 = false; - try - { + try { value0 = Boolean.valueOf(null); } - catch (Throwable t) - { + catch (Throwable t) { expected = t; } - try - { + try { boolean value1 = producer.getBooleanProperty("testGetNonExistentProperties"); - if (expected == null) - { + if (expected == null) { assertEquals("value0: " + value0 + " value1: " + value1, value1, value0); } - else - { + else { fail("non existent boolean property expects exception, but got value: " + value1); } } - catch (Throwable t) - { - if (expected == null) throw t; - if (!t.getClass().equals(expected.getClass())) - { + catch (Throwable t) { + if (expected == null) + throw t; + if (!t.getClass().equals(expected.getClass())) { throw new Exception("Expected exception: " + expected.getClass().getName() + " but got: " + t.getClass(), t); } @@ -237,33 +213,27 @@ public class JmsProducerTest extends JMSTestBase //double expected = null; double value0 = 0; - try - { + try { value0 = Double.valueOf(null); } - catch (Throwable t) - { + catch (Throwable t) { expected = t; } - try - { + try { double value1 = producer.getDoubleProperty("testGetNonExistentProperties"); - if (expected == null) - { + if (expected == null) { assertTrue("value0: " + value0 + " value1: " + value1, value1 == value0); } - else - { + else { fail("non existent double property expects exception, but got value: " + value1); } } - catch (Throwable t) - { - if (expected == null) throw t; - if (!t.getClass().equals(expected.getClass())) - { + catch (Throwable t) { + if (expected == null) + throw t; + if (!t.getClass().equals(expected.getClass())) { throw new Exception("Expected exception: " + expected.getClass().getName() + " but got: " + t.getClass(), t); } @@ -274,33 +244,27 @@ public class JmsProducerTest extends JMSTestBase //float expected = null; float value0 = 0; - try - { + try { value0 = Float.valueOf(null); } - catch (Throwable t) - { + catch (Throwable t) { expected = t; } - try - { + try { float value1 = producer.getFloatProperty("testGetNonExistentProperties"); - if (expected == null) - { + if (expected == null) { assertTrue("value0: " + value0 + " value1: " + value1, value1 == value0); } - else - { + else { fail("non existent double property expects exception, but got value: " + value1); } } - catch (Throwable t) - { - if (expected == null) throw t; - if (!t.getClass().equals(expected.getClass())) - { + catch (Throwable t) { + if (expected == null) + throw t; + if (!t.getClass().equals(expected.getClass())) { throw new Exception("Expected exception: " + expected.getClass().getName() + " but got: " + t.getClass(), t); } @@ -311,33 +275,27 @@ public class JmsProducerTest extends JMSTestBase //int expected = null; int value0 = 0; - try - { + try { value0 = Integer.valueOf(null); } - catch (Throwable t) - { + catch (Throwable t) { expected = t; } - try - { + try { int value1 = producer.getIntProperty("testGetNonExistentProperties"); - if (expected == null) - { + if (expected == null) { assertTrue("value0: " + value0 + " value1: " + value1, value1 == value0); } - else - { + else { fail("non existent double property expects exception, but got value: " + value1); } } - catch (Throwable t) - { - if (expected == null) throw t; - if (!t.getClass().equals(expected.getClass())) - { + catch (Throwable t) { + if (expected == null) + throw t; + if (!t.getClass().equals(expected.getClass())) { throw new Exception("Expected exception: " + expected.getClass().getName() + " but got: " + t.getClass(), t); } @@ -348,33 +306,27 @@ public class JmsProducerTest extends JMSTestBase //long expected = null; long value0 = 0; - try - { + try { value0 = Integer.valueOf(null); } - catch (Throwable t) - { + catch (Throwable t) { expected = t; } - try - { + try { long value1 = producer.getLongProperty("testGetNonExistentProperties"); - if (expected == null) - { + if (expected == null) { assertEquals("value0: " + value0 + " value1: " + value1, value1, value0); } - else - { + else { fail("non existent double property expects exception, but got value: " + value1); } } - catch (Throwable t) - { - if (expected == null) throw t; - if (!t.getClass().equals(expected.getClass())) - { + catch (Throwable t) { + if (expected == null) + throw t; + if (!t.getClass().equals(expected.getClass())) { throw new Exception("Expected exception: " + expected.getClass().getName() + " but got: " + t.getClass(), t); } @@ -385,33 +337,27 @@ public class JmsProducerTest extends JMSTestBase //short expected = null; short value0 = 0; - try - { + try { value0 = Short.valueOf(null); } - catch (Throwable t) - { + catch (Throwable t) { expected = t; } - try - { + try { short value1 = producer.getShortProperty("testGetNonExistentProperties"); - if (expected == null) - { + if (expected == null) { assertTrue("value0: " + value0 + " value1: " + value1, value1 == value0); } - else - { + else { fail("non existent double property expects exception, but got value: " + value1); } } - catch (Throwable t) - { - if (expected == null) throw t; - if (!t.getClass().equals(expected.getClass())) - { + catch (Throwable t) { + if (expected == null) + throw t; + if (!t.getClass().equals(expected.getClass())) { throw new Exception("Expected exception: " + expected.getClass().getName() + " but got: " + t.getClass(), t); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/ManualReconnectionToSingleServerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/ManualReconnectionToSingleServerTest.java index 9152294532..1d869011e3 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/ManualReconnectionToSingleServerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/ManualReconnectionToSingleServerTest.java @@ -51,8 +51,7 @@ import java.util.concurrent.CountDownLatch; import static java.util.concurrent.TimeUnit.SECONDS; -public class ManualReconnectionToSingleServerTest extends ActiveMQTestBase -{ +public class ManualReconnectionToSingleServerTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @@ -73,10 +72,8 @@ public class ManualReconnectionToSingleServerTest extends ActiveMQTestBase private static final int NUM = 20; - private final ExceptionListener exceptionListener = new ExceptionListener() - { - public void onException(final JMSException e) - { + private final ExceptionListener exceptionListener = new ExceptionListener() { + public void onException(final JMSException e) { exceptionLatch.countDown(); disconnect(); connect(); @@ -89,30 +86,27 @@ public class ManualReconnectionToSingleServerTest extends ActiveMQTestBase private ActiveMQServer server; @Test - public void testExceptionListener() throws Exception - { + public void testExceptionListener() throws Exception { connect(); - ConnectionFactory cf = (ConnectionFactory)context.lookup("/cf"); - Destination dest = (Destination)context.lookup(QUEUE_NAME); + ConnectionFactory cf = (ConnectionFactory) context.lookup("/cf"); + Destination dest = (Destination) context.lookup(QUEUE_NAME); Connection conn = cf.createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = sess.createProducer(dest); - for (int i = 0; i < NUM; i++) - { + for (int i = 0; i < NUM; i++) { Message message = sess.createTextMessage(new Date().toString()); message.setIntProperty("counter", i + 1); prod.send(message); - if (i == NUM / 2) - { + if (i == NUM / 2) { conn.close(); serverManager.stop(); Thread.sleep(5000); serverManager.start(); - cf = (ConnectionFactory)context.lookup("/cf"); - dest = (Destination)context.lookup(QUEUE_NAME); + cf = (ConnectionFactory) context.lookup("/cf"); + dest = (Destination) context.lookup(QUEUE_NAME); conn = cf.createConnection(); sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); prod = sess.createProducer(dest); @@ -141,8 +135,7 @@ public class ManualReconnectionToSingleServerTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); context = new InVMNamingContext(); @@ -157,12 +150,7 @@ public class ManualReconnectionToSingleServerTest extends ActiveMQTestBase ArrayList configs = new ArrayList(); configs.add(new TransportConfiguration(NETTY_CONNECTOR_FACTORY)); - ConnectionFactoryConfiguration cfConfig = new ConnectionFactoryConfigurationImpl() - .setName("cf") - .setConnectorNames(registerConnectors(server, configs)) - .setBindings("/cf") - .setRetryInterval(1000) - .setReconnectAttempts(-1); + ConnectionFactoryConfiguration cfConfig = new ConnectionFactoryConfigurationImpl().setName("cf").setConnectorNames(registerConnectors(server, configs)).setBindings("/cf").setRetryInterval(1000).setReconnectAttempts(-1); configuration.getConnectionFactoryConfigurations().add(cfConfig); serverManager.start(); @@ -177,53 +165,43 @@ public class ManualReconnectionToSingleServerTest extends ActiveMQTestBase // Inner classes ------------------------------------------------- - protected void disconnect() - { + protected void disconnect() { ManualReconnectionToSingleServerTest.log.info("calling disconnect"); - if (connection == null) - { + if (connection == null) { ManualReconnectionToSingleServerTest.log.info("connection is null"); return; } - try - { + try { connection.setExceptionListener(null); ManualReconnectionToSingleServerTest.log.info("closing the connection"); connection.close(); connection = null; ManualReconnectionToSingleServerTest.log.info("connection closed"); } - catch (Exception e) - { + catch (Exception e) { ManualReconnectionToSingleServerTest.log.info("** got exception"); e.printStackTrace(); } } - protected void connect() - { + protected void connect() { int retries = 0; final int retryLimit = 1000; - try - { - if (context == null) - { + try { + if (context == null) { return; } Context initialContext = context; Queue queue; ConnectionFactory cf; - while (true) - { - try - { - queue = (Queue)initialContext.lookup(QUEUE_NAME); - cf = (ConnectionFactory)initialContext.lookup("/cf"); + while (true) { + try { + queue = (Queue) initialContext.lookup(QUEUE_NAME); + cf = (ConnectionFactory) initialContext.lookup("/cf"); break; } - catch (Exception e) - { + catch (Exception e) { if (retries++ > retryLimit) throw e; // retry until server is up @@ -237,40 +215,32 @@ public class ManualReconnectionToSingleServerTest extends ActiveMQTestBase consumer.setMessageListener(listener); connection.start(); } - catch (Exception e) - { - if (connection != null) - { - try - { + catch (Exception e) { + if (connection != null) { + try { connection.close(); } - catch (JMSException e1) - { + catch (JMSException e1) { e1.printStackTrace(); } } } } - private class Listener implements MessageListener - { + private class Listener implements MessageListener { + private int count = 0; - public void onMessage(final Message msg) - { + public void onMessage(final Message msg) { count++; - try - { + try { msg.getIntProperty("counter"); } - catch (JMSException e) - { + catch (JMSException e) { e.printStackTrace(); } - if (count == NUM) - { + if (count == NUM) { allMessagesReceived.countDown(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/SimpleJNDIClientTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/SimpleJNDIClientTest.java index d5f45ebdbc..26ea9ab873 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/SimpleJNDIClientTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/SimpleJNDIClientTest.java @@ -53,11 +53,10 @@ import org.junit.Before; import org.junit.Test; /** - * * ActiveMQConnectionFactoryTest */ -public class SimpleJNDIClientTest extends ActiveMQTestBase -{ +public class SimpleJNDIClientTest extends ActiveMQTestBase { + private final String groupAddress = getUDPDiscoveryAddress(); private final int groupPort = getUDPDiscoveryPort(); @@ -67,8 +66,7 @@ public class SimpleJNDIClientTest extends ActiveMQTestBase private TransportConfiguration liveTC; @Test - public void testMultipleConnectionFactories() throws NamingException, JMSException - { + public void testMultipleConnectionFactories() throws NamingException, JMSException { Hashtable props = new Hashtable<>(); props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory"); props.put("connectionFactory.VmConnectionFactory", "vm://0"); @@ -83,8 +81,7 @@ public class SimpleJNDIClientTest extends ActiveMQTestBase } @Test - public void testVMCF0() throws NamingException, JMSException - { + public void testVMCF0() throws NamingException, JMSException { Hashtable props = new Hashtable<>(); props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory"); props.put("connectionFactory.ConnectionFactory", "vm://0"); @@ -96,8 +93,7 @@ public class SimpleJNDIClientTest extends ActiveMQTestBase } @Test - public void testVMCF1() throws NamingException, JMSException - { + public void testVMCF1() throws NamingException, JMSException { Hashtable props = new Hashtable<>(); props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory"); props.put("connectionFactory.ConnectionFactory", "vm://1"); @@ -109,8 +105,7 @@ public class SimpleJNDIClientTest extends ActiveMQTestBase } @Test - public void testXACF() throws NamingException, JMSException - { + public void testXACF() throws NamingException, JMSException { Hashtable props = new Hashtable<>(); props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory"); props.put("connectionFactory.myConnectionFactory", "vm://0?type=XA_CF"); @@ -122,8 +117,7 @@ public class SimpleJNDIClientTest extends ActiveMQTestBase } @Test - public void testQueueCF() throws NamingException, JMSException - { + public void testQueueCF() throws NamingException, JMSException { Hashtable props = new Hashtable<>(); props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory"); props.put("connectionFactory.myConnectionFactory", "vm://0?type=QUEUE_CF"); @@ -135,8 +129,7 @@ public class SimpleJNDIClientTest extends ActiveMQTestBase } @Test - public void testQueueXACF() throws NamingException, JMSException - { + public void testQueueXACF() throws NamingException, JMSException { Hashtable props = new Hashtable<>(); props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory"); props.put("connectionFactory.myConnectionFactory", "vm://0?type=QUEUE_XA_CF"); @@ -148,8 +141,7 @@ public class SimpleJNDIClientTest extends ActiveMQTestBase } @Test - public void testTopicCF() throws NamingException, JMSException - { + public void testTopicCF() throws NamingException, JMSException { Hashtable props = new Hashtable<>(); props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory"); props.put("connectionFactory.myConnectionFactory", "vm://0?type=TOPIC_CF"); @@ -161,8 +153,7 @@ public class SimpleJNDIClientTest extends ActiveMQTestBase } @Test - public void testTopicXACF() throws NamingException, JMSException - { + public void testTopicXACF() throws NamingException, JMSException { Hashtable props = new Hashtable<>(); props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory"); props.put("connectionFactory.myConnectionFactory", "vm://0?type=TOPIC_XA_CF"); @@ -174,8 +165,7 @@ public class SimpleJNDIClientTest extends ActiveMQTestBase } @Test - public void testRemoteCFWithTCP() throws NamingException, JMSException - { + public void testRemoteCFWithTCP() throws NamingException, JMSException { Hashtable props = new Hashtable<>(); props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory"); props.put("connectionFactory.myConnectionFactory", "tcp://127.0.0.1:61616"); @@ -187,8 +177,7 @@ public class SimpleJNDIClientTest extends ActiveMQTestBase } @Test - public void testRemoteCFWithTCPandHA() throws NamingException, JMSException - { + public void testRemoteCFWithTCPandHA() throws NamingException, JMSException { Hashtable props = new Hashtable<>(); props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory"); props.put("connectionFactory.myConnectionFactory", "tcp://127.0.0.1:61616?ha=true"); @@ -200,8 +189,7 @@ public class SimpleJNDIClientTest extends ActiveMQTestBase } @Test - public void testRemoteCFWithJGroups() throws Exception - { + public void testRemoteCFWithJGroups() throws Exception { Hashtable props = new Hashtable<>(); props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory"); props.put("connectionFactory.myConnectionFactory", "jgroups://mychannelid?file=test-jgroups-file_ping.xml"); @@ -212,8 +200,7 @@ public class SimpleJNDIClientTest extends ActiveMQTestBase } @Test - public void testRemoteCFWithJgroupsWithTransportConfigFile() throws Exception - { + public void testRemoteCFWithJgroupsWithTransportConfigFile() throws Exception { Hashtable props = new Hashtable<>(); props.put(Context.INITIAL_CONTEXT_FACTORY, org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory.class.getCanonicalName()); props.put("connectionFactory.myConnectionFactory", "jgroups://testChannelName?file=test-jgroups-file_ping.xml&" + @@ -233,13 +220,12 @@ public class SimpleJNDIClientTest extends ActiveMQTestBase } @Test - public void testRemoteCFWithJgroupsWithTransportConfigProps() throws Exception - { + public void testRemoteCFWithJgroupsWithTransportConfigProps() throws Exception { Hashtable props = new Hashtable<>(); props.put(Context.INITIAL_CONTEXT_FACTORY, ActiveMQInitialContextFactory.class.getCanonicalName()); props.put("connectionFactory.ConnectionFactory", "jgroups://testChannelName?properties=param=value&" + - ActiveMQInitialContextFactory.REFRESH_TIMEOUT + "=5000&" + - ActiveMQInitialContextFactory.DISCOVERY_INITIAL_WAIT_TIMEOUT + "=6000"); + ActiveMQInitialContextFactory.REFRESH_TIMEOUT + "=5000&" + + ActiveMQInitialContextFactory.DISCOVERY_INITIAL_WAIT_TIMEOUT + "=6000"); Context ctx = new InitialContext(props); ActiveMQConnectionFactory cf = (ActiveMQConnectionFactory) ctx.lookup("ConnectionFactory"); @@ -250,21 +236,18 @@ public class SimpleJNDIClientTest extends ActiveMQTestBase BroadcastEndpointFactory broadcastEndpointFactory = cf.getDiscoveryGroupConfiguration().getBroadcastEndpointFactory(); Assert.assertTrue(broadcastEndpointFactory instanceof JGroupsPropertiesBroadcastEndpointFactory); - JGroupsPropertiesBroadcastEndpointFactory endpointFactory = (JGroupsPropertiesBroadcastEndpointFactory) broadcastEndpointFactory; + JGroupsPropertiesBroadcastEndpointFactory endpointFactory = (JGroupsPropertiesBroadcastEndpointFactory) broadcastEndpointFactory; Assert.assertEquals(endpointFactory.getProperties(), "param=value"); Assert.assertEquals(endpointFactory.getChannelName(), "testChannelName"); } - - @Test - public void testRemoteCFWithJgroupsWithTransportConfigNullProps() throws Exception - { + public void testRemoteCFWithJgroupsWithTransportConfigNullProps() throws Exception { Hashtable props = new Hashtable<>(); props.put(Context.INITIAL_CONTEXT_FACTORY, ActiveMQInitialContextFactory.class.getCanonicalName()); props.put("connectionFactory.ConnectionFactory", "jgroups://testChannelName?" + - ActiveMQInitialContextFactory.REFRESH_TIMEOUT + "=5000&" + - ActiveMQInitialContextFactory.DISCOVERY_INITIAL_WAIT_TIMEOUT + "=6000"); + ActiveMQInitialContextFactory.REFRESH_TIMEOUT + "=5000&" + + ActiveMQInitialContextFactory.DISCOVERY_INITIAL_WAIT_TIMEOUT + "=6000"); Context ctx = new InitialContext(props); ActiveMQConnectionFactory cf = (ActiveMQConnectionFactory) ctx.lookup("ConnectionFactory"); @@ -275,15 +258,13 @@ public class SimpleJNDIClientTest extends ActiveMQTestBase BroadcastEndpointFactory broadcastEndpointFactory = cf.getDiscoveryGroupConfiguration().getBroadcastEndpointFactory(); Assert.assertTrue(broadcastEndpointFactory instanceof JGroupsPropertiesBroadcastEndpointFactory); - JGroupsPropertiesBroadcastEndpointFactory endpointFactory = (JGroupsPropertiesBroadcastEndpointFactory) broadcastEndpointFactory; + JGroupsPropertiesBroadcastEndpointFactory endpointFactory = (JGroupsPropertiesBroadcastEndpointFactory) broadcastEndpointFactory; Assert.assertEquals(endpointFactory.getProperties(), null); Assert.assertEquals(endpointFactory.getChannelName(), "testChannelName"); } - @Test - public void testRemoteCFWithUDP() throws NamingException, JMSException - { + public void testRemoteCFWithUDP() throws NamingException, JMSException { Hashtable props = new Hashtable<>(); props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory"); props.put("connectionFactory.myConnectionFactory", "udp://" + getUDPDiscoveryAddress() + ":" + getUDPDiscoveryPort()); @@ -295,8 +276,7 @@ public class SimpleJNDIClientTest extends ActiveMQTestBase } @Test - public void testRemoteCFWithUDPWithTransportConfig() throws NamingException, JMSException - { + public void testRemoteCFWithUDPWithTransportConfig() throws NamingException, JMSException { Hashtable props = new Hashtable<>(); props.put(Context.INITIAL_CONTEXT_FACTORY, ActiveMQInitialContextFactory.class.getCanonicalName()); props.put("connectionFactory.myConnectionFactory", "udp://" + getUDPDiscoveryAddress() + ":" + getUDPDiscoveryPort() + "?" + @@ -321,8 +301,7 @@ public class SimpleJNDIClientTest extends ActiveMQTestBase } @Test - public void testRemoteCFWithMultipleHosts() throws NamingException, JMSException - { + public void testRemoteCFWithMultipleHosts() throws NamingException, JMSException { Hashtable props = new Hashtable<>(); props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory"); props.put("connectionFactory.myConnectionFactory", "tcp://127.0.0.1:61616/httpEnabled=true&foo=bar,tcp://127.0.0.2:61617?httpEnabled=false?clientID=myClientID"); @@ -334,8 +313,7 @@ public class SimpleJNDIClientTest extends ActiveMQTestBase } @Test - public void testRemoteCFWithTransportConfig() throws NamingException, JMSException - { + public void testRemoteCFWithTransportConfig() throws NamingException, JMSException { Hashtable props = new Hashtable<>(); props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory"); props.put("connectionFactory.myConnectionFactory", "tcp://127.0.0.1:61616?" + @@ -407,15 +385,13 @@ public class SimpleJNDIClientTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); startServer(); } - private void startServer() throws Exception - { + private void startServer() throws Exception { liveTC = new TransportConfiguration(INVM_CONNECTOR_FACTORY); Map connectors = new HashMap(); connectors.put(liveTC.getName(), liveTC); @@ -425,12 +401,7 @@ public class SimpleJNDIClientTest extends ActiveMQTestBase Map params = new HashMap(); params.put(org.apache.activemq.artemis.core.remoting.impl.invm.TransportConstants.SERVER_ID_PROP_NAME, 1); - Configuration liveConf = createBasicConfig() - .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY)) - .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, params)) - .addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY)) - .setConnectorConfigurations(connectors) - .setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration()); + Configuration liveConf = createBasicConfig().addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY)).addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, params)).addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY)).setConnectorConfigurations(connectors).setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration()); final long broadcastPeriod = 250; @@ -438,14 +409,7 @@ public class SimpleJNDIClientTest extends ActiveMQTestBase final int localBindPort = 5432; - BroadcastGroupConfiguration bcConfig1 = new BroadcastGroupConfiguration() - .setName(bcGroupName) - .setBroadcastPeriod(broadcastPeriod) - .setConnectorInfos(connectorNames) - .setEndpointFactory(new UDPBroadcastEndpointFactory() - .setGroupAddress(groupAddress) - .setGroupPort(groupPort) - .setLocalBindPort(localBindPort)); + BroadcastGroupConfiguration bcConfig1 = new BroadcastGroupConfiguration().setName(bcGroupName).setBroadcastPeriod(broadcastPeriod).setConnectorInfos(connectorNames).setEndpointFactory(new UDPBroadcastEndpointFactory().setGroupAddress(groupAddress).setGroupPort(groupPort).setLocalBindPort(localBindPort)); List bcConfigs1 = new ArrayList(); bcConfigs1.add(bcConfig1); @@ -456,8 +420,7 @@ public class SimpleJNDIClientTest extends ActiveMQTestBase } @Test - public void testQueue() throws NamingException, JMSException - { + public void testQueue() throws NamingException, JMSException { Hashtable props = new Hashtable<>(); props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory"); props.put("queue.myQueue", "myQueue"); @@ -472,8 +435,7 @@ public class SimpleJNDIClientTest extends ActiveMQTestBase } @Test - public void testDynamicQueue() throws NamingException, JMSException - { + public void testDynamicQueue() throws NamingException, JMSException { Hashtable props = new Hashtable<>(); props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory"); Context ctx = new InitialContext(props); @@ -483,8 +445,7 @@ public class SimpleJNDIClientTest extends ActiveMQTestBase } @Test - public void testTopic() throws NamingException, JMSException - { + public void testTopic() throws NamingException, JMSException { Hashtable props = new Hashtable<>(); props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory"); props.put("topic.myTopic", "myTopic"); @@ -499,8 +460,7 @@ public class SimpleJNDIClientTest extends ActiveMQTestBase } @Test - public void testDynamicTopic() throws NamingException, JMSException - { + public void testDynamicTopic() throws NamingException, JMSException { Hashtable props = new Hashtable<>(); props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory"); Context ctx = new InitialContext(props); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/AutoGroupingTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/AutoGroupingTest.java index 01f62ca3f2..ed7cf68e8f 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/AutoGroupingTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/AutoGroupingTest.java @@ -24,16 +24,11 @@ import org.apache.activemq.artemis.api.jms.ActiveMQJMSClient; import org.apache.activemq.artemis.api.jms.JMSFactoryType; import org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory; -public class AutoGroupingTest extends GroupingTest -{ +public class AutoGroupingTest extends GroupingTest { @Override - protected ConnectionFactory getCF() throws Exception - { - ActiveMQJMSConnectionFactory cf1 = - (ActiveMQJMSConnectionFactory) ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, - new TransportConfiguration( - INVM_CONNECTOR_FACTORY)); + protected ConnectionFactory getCF() throws Exception { + ActiveMQJMSConnectionFactory cf1 = (ActiveMQJMSConnectionFactory) ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); cf1.setAutoGroup(true); @@ -41,8 +36,7 @@ public class AutoGroupingTest extends GroupingTest } @Override - protected void setProperty(Message message) - { + protected void setProperty(Message message) { } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/ConnectionTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/ConnectionTest.java index 071b08497b..d1fedeb557 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/ConnectionTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/ConnectionTest.java @@ -38,41 +38,36 @@ import org.junit.After; import org.junit.Assert; import org.junit.Test; -public class ConnectionTest extends JMSTestBase -{ +public class ConnectionTest extends JMSTestBase { private Connection conn2; @Test - public void testThroughNewConnectionFactory() throws Exception - { + public void testThroughNewConnectionFactory() throws Exception { testThroughNewConnectionFactory(new ActiveMQConnectionFactory("vm://0")); testThroughNewConnectionFactory(new ActiveMQConnectionFactory("tcp://localhost:61616?&blockOnNonDurableSend=true&" + - "retryIntervalMultiplier=1.0&maxRetryInterval=2000&producerMaxRate=-1&" + - "blockOnDurableSend=true&connectionTTL=60000&compressLargeMessage=false&reconnectAttempts=0&" + - "cacheLargeMessagesClient=false&scheduledThreadPoolMaxSize=5&useGlobalPools=true&" + - "callFailoverTimeout=-1&initialConnectAttempts=1&clientFailureCheckPeriod=30000&" + - "blockOnAcknowledge=true&consumerWindowSize=1048576&minLargeMessageSize=102400&" + - "autoGroup=false&threadPoolMaxSize=-1&confirmationWindowSize=-1&" + - "transactionBatchSize=1048576&callTimeout=30000&preAcknowledge=false&" + - "connectionLoadBalancingPolicyClassName=org.apache.activemq.artemis.api.core.client.loadbalance." + - "RoundRobinConnectionLoadBalancingPolicy&dupsOKBatchSize=1048576&initialMessagePacketSize=1500&" + - "consumerMaxRate=-1&retryInterval=2000&failoverOnInitialConnection=false&producerWindowSize=65536&" + - "port=61616&host=localhost#")); + "retryIntervalMultiplier=1.0&maxRetryInterval=2000&producerMaxRate=-1&" + + "blockOnDurableSend=true&connectionTTL=60000&compressLargeMessage=false&reconnectAttempts=0&" + + "cacheLargeMessagesClient=false&scheduledThreadPoolMaxSize=5&useGlobalPools=true&" + + "callFailoverTimeout=-1&initialConnectAttempts=1&clientFailureCheckPeriod=30000&" + + "blockOnAcknowledge=true&consumerWindowSize=1048576&minLargeMessageSize=102400&" + + "autoGroup=false&threadPoolMaxSize=-1&confirmationWindowSize=-1&" + + "transactionBatchSize=1048576&callTimeout=30000&preAcknowledge=false&" + + "connectionLoadBalancingPolicyClassName=org.apache.activemq.artemis.api.core.client.loadbalance." + + "RoundRobinConnectionLoadBalancingPolicy&dupsOKBatchSize=1048576&initialMessagePacketSize=1500&" + + "consumerMaxRate=-1&retryInterval=2000&failoverOnInitialConnection=false&producerWindowSize=65536&" + + "port=61616&host=localhost#")); } - private void testThroughNewConnectionFactory(ActiveMQConnectionFactory factory) throws Exception - { + private void testThroughNewConnectionFactory(ActiveMQConnectionFactory factory) throws Exception { Connection conn = factory.createConnection(); conn.close(); - try (JMSContext ctx = factory.createContext()) - { - ctx.createProducer().send(ctx.createQueue("queue"),"Test"); + try (JMSContext ctx = factory.createContext()) { + ctx.createProducer().send(ctx.createQueue("queue"), "Test"); } - try (JMSContext ctx = factory.createContext()) - { + try (JMSContext ctx = factory.createContext()) { Assert.assertNotNull(ctx.createConsumer(ctx.createQueue("queue")).receiveNoWait()); Assert.assertNull(ctx.createConsumer(ctx.createQueue("queue")).receiveNoWait()); } @@ -80,29 +75,24 @@ public class ConnectionTest extends JMSTestBase factory.close(); } - @Test - public void testSetSameIdToDifferentConnections() throws Exception - { + public void testSetSameIdToDifferentConnections() throws Exception { String id = "somethingElse" + name.getMethodName(); conn = cf.createConnection(); conn2 = cf.createConnection(); conn.getClientID(); conn.setClientID(id); - try - { + try { conn2.setClientID(id); Assert.fail("should not happen."); } - catch (InvalidClientIDException expected) - { + catch (InvalidClientIDException expected) { // expected } } @Test - public void testGetSetConnectionFactory() throws Exception - { + public void testGetSetConnectionFactory() throws Exception { conn = cf.createConnection(); conn.getClientID(); @@ -111,8 +101,7 @@ public class ConnectionTest extends JMSTestBase } @Test - public void testTXTypeInvalid() throws Exception - { + public void testTXTypeInvalid() throws Exception { conn = cf.createConnection(); Session sess = conn.createSession(false, Session.SESSION_TRANSACTED); @@ -136,8 +125,7 @@ public class ConnectionTest extends JMSTestBase } @Test - public void testXAInstanceof() throws Exception - { + public void testXAInstanceof() throws Exception { conn = cf.createConnection(); assertFalse(conn instanceof XAConnection); @@ -147,8 +135,7 @@ public class ConnectionTest extends JMSTestBase } @Test - public void testConnectionFactorySerialization() throws Exception - { + public void testConnectionFactorySerialization() throws Exception { //first try cf without any connection being created ConnectionFactory newCF = getCFThruSerialization(cf); testCreateConnection(newCF); @@ -156,24 +143,20 @@ public class ConnectionTest extends JMSTestBase //now serialize a cf after a connection has been created //https://issues.jboss.org/browse/WFLY-327 Connection aConn = null; - try - { + try { aConn = cf.createConnection(); newCF = getCFThruSerialization(cf); testCreateConnection(newCF); } - finally - { - if (aConn != null) - { + finally { + if (aConn != null) { aConn.close(); } } } - private ConnectionFactory getCFThruSerialization(ConnectionFactory fact) throws Exception - { + private ConnectionFactory getCFThruSerialization(ConnectionFactory fact) throws Exception { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); @@ -187,11 +170,9 @@ public class ConnectionTest extends JMSTestBase return newCF; } - private void testCreateConnection(ConnectionFactory fact) throws Exception - { + private void testCreateConnection(ConnectionFactory fact) throws Exception { Connection newConn = null; - try - { + try { newConn = fact.createConnection(); newConn.start(); newConn.stop(); @@ -200,10 +181,8 @@ public class ConnectionTest extends JMSTestBase Session session2 = newConn.createSession(true, Session.SESSION_TRANSACTED); session2.close(); } - finally - { - if (newConn != null) - { + finally { + if (newConn != null) { newConn.close(); } } @@ -211,10 +190,8 @@ public class ConnectionTest extends JMSTestBase @Override @After - public void tearDown() throws Exception - { - if (conn2 != null) - { + public void tearDown() throws Exception { + if (conn2 != null) { conn2.close(); } super.tearDown(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/CreateQueueTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/CreateQueueTest.java index bb5412b2af..5572f213ac 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/CreateQueueTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/CreateQueueTest.java @@ -27,8 +27,7 @@ import org.apache.activemq.artemis.tests.util.JMSTestBase; import org.apache.activemq.artemis.jms.client.ActiveMQDestination; import org.junit.Test; -public class CreateQueueTest extends JMSTestBase -{ +public class CreateQueueTest extends JMSTestBase { // Constants ----------------------------------------------------- private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @@ -42,8 +41,7 @@ public class CreateQueueTest extends JMSTestBase // Public -------------------------------------------------------- @Test - public void testCreateQueueTempQueue() throws Exception - { + public void testCreateQueueTempQueue() throws Exception { conn = cf.createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -68,8 +66,7 @@ public class CreateQueueTest extends JMSTestBase } @Test - public void testCreateQueue() throws Exception - { + public void testCreateQueue() throws Exception { conn = cf.createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -95,8 +92,7 @@ public class CreateQueueTest extends JMSTestBase } @Test - public void testCreateTopic() throws Exception - { + public void testCreateTopic() throws Exception { conn = cf.createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -121,8 +117,7 @@ public class CreateQueueTest extends JMSTestBase } @Test - public void testCreateTopicTempTopic() throws Exception - { + public void testCreateTopicTempTopic() throws Exception { conn = cf.createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/ExpiryMessageTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/ExpiryMessageTest.java index dbb46a5f5a..6a64ddfe02 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/ExpiryMessageTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/ExpiryMessageTest.java @@ -28,8 +28,7 @@ import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.tests.util.JMSTestBase; import org.junit.Test; -public class ExpiryMessageTest extends JMSTestBase -{ +public class ExpiryMessageTest extends JMSTestBase { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -41,15 +40,12 @@ public class ExpiryMessageTest extends JMSTestBase // Public -------------------------------------------------------- @Override - protected Configuration createDefaultConfig(boolean netty) throws Exception - { - return super.createDefaultConfig(netty) - .setMessageExpiryScanPeriod(1000); + protected Configuration createDefaultConfig(boolean netty) throws Exception { + return super.createDefaultConfig(netty).setMessageExpiryScanPeriod(1000); } @Test - public void testSendTopicNoSubscription() throws Exception - { + public void testSendTopicNoSubscription() throws Exception { Topic topic = createTopic("test-topic"); TopicControl control = ManagementControlHelper.createTopicControl(topic, mbeanServer); @@ -69,8 +65,7 @@ public class ExpiryMessageTest extends JMSTestBase MessageProducer prod = sess.createProducer(topic); prod.setTimeToLive(1000); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { TextMessage txt = sess.createTextMessage("txt"); prod.send(txt); } @@ -85,14 +80,12 @@ public class ExpiryMessageTest extends JMSTestBase long timeout = System.currentTimeMillis() + 10000; // We will wait some time, but we will wait as minimal as possible - while (control.getMessageCount() != 0 && System.currentTimeMillis() > timeout) - { + while (control.getMessageCount() != 0 && System.currentTimeMillis() > timeout) { Thread.sleep(100); } assertEquals(0, control.getMessageCount()); - } // Package protected --------------------------------------------- diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/GroupIDTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/GroupIDTest.java index c62c908ac5..861b568dfd 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/GroupIDTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/GroupIDTest.java @@ -26,12 +26,10 @@ import org.apache.activemq.artemis.api.jms.ActiveMQJMSClient; import org.apache.activemq.artemis.api.jms.JMSFactoryType; import org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory; -public class GroupIDTest extends GroupingTest -{ +public class GroupIDTest extends GroupingTest { @Override - protected ConnectionFactory getCF() throws Exception - { + protected ConnectionFactory getCF() throws Exception { ActiveMQJMSConnectionFactory cf = (ActiveMQJMSConnectionFactory) ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); cf.setGroupID("wibble"); @@ -39,15 +37,12 @@ public class GroupIDTest extends GroupingTest return cf; } - @Test - public void testManyGroups() - { + public void testManyGroups() { // this test does not make sense here } @Override - protected void setProperty(Message message) - { + protected void setProperty(Message message) { } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/GroupingTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/GroupingTest.java index a884ca462b..10e6b95036 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/GroupingTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/GroupingTest.java @@ -40,32 +40,28 @@ import javax.jms.TextMessage; /** * GroupingTest */ -public class GroupingTest extends JMSTestBase -{ +public class GroupingTest extends JMSTestBase { + private Queue queue; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); queue = createQueue("TestQueue"); } - protected void setProperty(Message message) - { - ((ActiveMQMessage)message).getCoreMessage().putStringProperty(org.apache.activemq.artemis.api.core.Message.HDR_GROUP_ID, new SimpleString("foo")); + protected void setProperty(Message message) { + ((ActiveMQMessage) message).getCoreMessage().putStringProperty(org.apache.activemq.artemis.api.core.Message.HDR_GROUP_ID, new SimpleString("foo")); } - protected ConnectionFactory getCF() throws Exception - { + protected ConnectionFactory getCF() throws Exception { return cf; } @Test - public void testGrouping() throws Exception - { + public void testGrouping() throws Exception { ConnectionFactory fact = getCF(); Connection connection = fact.createConnection(); @@ -81,8 +77,7 @@ public class GroupingTest extends JMSTestBase String jmsxgroupID = null; - for (int j = 0; j < 100; j++) - { + for (int j = 0; j < 100; j++) { TextMessage message = session.createTextMessage(); message.setText("Message" + j); @@ -95,20 +90,17 @@ public class GroupingTest extends JMSTestBase assertNotNull(prop); - if (jmsxgroupID != null) - { + if (jmsxgroupID != null) { assertEquals(jmsxgroupID, prop); } - else - { + else { jmsxgroupID = prop; } } //All msgs should go to the first consumer - for (int j = 0; j < 100; j++) - { - TextMessage tm = (TextMessage)consumer1.receive(10000); + for (int j = 0; j < 100; j++) { + TextMessage tm = (TextMessage) consumer1.receive(10000); assertNotNull(tm); @@ -119,15 +111,12 @@ public class GroupingTest extends JMSTestBase connection.close(); - } - @Test - public void testManyGroups() throws Exception - { + public void testManyGroups() throws Exception { ConnectionFactory fact = getCF(); - Assume.assumeFalse("only makes sense withOUT auto-group", ((ActiveMQConnectionFactory)fact).isAutoGroup()); + Assume.assumeFalse("only makes sense withOUT auto-group", ((ActiveMQConnectionFactory) fact).isAutoGroup()); Connection connection = fact.createConnection(); @@ -141,8 +130,7 @@ public class GroupingTest extends JMSTestBase connection.start(); - for (int j = 0; j < 1000; j++) - { + for (int j = 0; j < 1000; j++) { TextMessage message = session.createTextMessage(); message.setText("Message" + j); @@ -161,7 +149,6 @@ public class GroupingTest extends JMSTestBase int msg2 = flushMessages(consumer2); int msg3 = flushMessages(consumer3); - assertNotSame(0, msg1); assertNotSame(0, msg2); assertNotSame(0, msg2); @@ -170,15 +157,12 @@ public class GroupingTest extends JMSTestBase consumer2.close(); consumer3.close(); - connection.close(); - } @Test - public void testGroupingRollbackOnClose() throws Exception - { + public void testGroupingRollbackOnClose() throws Exception { ActiveMQConnectionFactory fact = (ActiveMQConnectionFactory) getCF(); fact.setConsumerWindowSize(1000); fact.setTransactionBatchSize(0); @@ -199,8 +183,7 @@ public class GroupingTest extends JMSTestBase String jmsxgroupID = null; - for (int j = 0; j < 100; j++) - { + for (int j = 0; j < 100; j++) { TextMessage message = session.createTextMessage(); message.setText("Message" + j); @@ -213,20 +196,17 @@ public class GroupingTest extends JMSTestBase assertNotNull(prop); - if (jmsxgroupID != null) - { + if (jmsxgroupID != null) { assertEquals(jmsxgroupID, prop); } - else - { + else { jmsxgroupID = prop; } } session.commit(); //consume 5 msgs from 1st first consumer - for (int j = 0; j < 1; j++) - { - TextMessage tm = (TextMessage)consumer1.receive(10000); + for (int j = 0; j < 1; j++) { + TextMessage tm = (TextMessage) consumer1.receive(10000); assertNotNull(tm); @@ -238,12 +218,11 @@ public class GroupingTest extends JMSTestBase //session.rollback(); //session.close(); //consume all msgs from 2nd first consumer - // ClientSession amqs = ((ActiveMQSession) session).getCoreSession(); - // ((DelegatingSession) amqs).getChannel().close(); + // ClientSession amqs = ((ActiveMQSession) session).getCoreSession(); + // ((DelegatingSession) amqs).getChannel().close(); rc.fail(new ActiveMQNotConnectedException()); - for (int j = 0; j < 10; j++) - { - TextMessage tm = (TextMessage)consumer2.receive(10000); + for (int j = 0; j < 10; j++) { + TextMessage tm = (TextMessage) consumer2.receive(10000); assertNotNull(tm); @@ -258,14 +237,11 @@ public class GroupingTest extends JMSTestBase connection2.close(); } - private int flushMessages(MessageConsumer consumer) throws JMSException - { + private int flushMessages(MessageConsumer consumer) throws JMSException { int received = 0; - while (true) - { - TextMessage msg = (TextMessage)consumer.receiveNoWait(); - if (msg == null) - { + while (true) { + TextMessage msg = (TextMessage) consumer.receiveNoWait(); + if (msg == null) { break; } msg.acknowledge(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/MessageProducerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/MessageProducerTest.java index 26365ad4da..425e72729c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/MessageProducerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/MessageProducerTest.java @@ -30,73 +30,58 @@ import org.junit.Test; /** * */ -public class MessageProducerTest extends JMSTestBase -{ +public class MessageProducerTest extends JMSTestBase { @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); conn = cf.createConnection(); } @Test - public void testNoDefaultDestination() throws JMSException - { + public void testNoDefaultDestination() throws JMSException { Session session = conn.createSession(); - try - { + try { MessageProducer producer = session.createProducer(null); Message m = session.createMessage(); - try - { + try { producer.send(m); Assert.fail("must not be reached"); } - catch (UnsupportedOperationException cause) - { + catch (UnsupportedOperationException cause) { // expected } } - finally - { + finally { session.close(); } } @Test - public void testHasDefaultDestination() throws Exception - { + public void testHasDefaultDestination() throws Exception { Session session = conn.createSession(); - try - { + try { Queue queue = createQueue(name.getMethodName()); Queue queue2 = createQueue(name.getMethodName() + "2"); MessageProducer producer = session.createProducer(queue); Message m = session.createMessage(); - try - { + try { producer.send(queue2, m); Assert.fail("must not be reached"); } - catch (UnsupportedOperationException cause) - { + catch (UnsupportedOperationException cause) { // expected } - try - { + try { producer.send(queue, m); - Assert.fail("tck7 requires an UnsupportedOperationException " - + "even if the destination is the same as the default one"); + Assert.fail("tck7 requires an UnsupportedOperationException " + "even if the destination is the same as the default one"); } - catch (UnsupportedOperationException cause) - { + catch (UnsupportedOperationException cause) { // expected } } - finally - { + finally { session.close(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/MessageTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/MessageTest.java index 591f123dff..92525a94da 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/MessageTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/MessageTest.java @@ -31,8 +31,7 @@ import org.apache.activemq.artemis.tests.util.JMSTestBase; import org.junit.Assert; import org.junit.Test; -public class MessageTest extends JMSTestBase -{ +public class MessageTest extends JMSTestBase { // Constants ----------------------------------------------------- private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @@ -57,11 +56,9 @@ public class MessageTest extends JMSTestBase * @see https://jira.jboss.org/jira/browse/HORNETQ-242 */ @Test - public void testStreamMessageReadsNull() throws Exception - { + public void testStreamMessageReadsNull() throws Exception { Connection conn = cf.createConnection(); - try - { + try { Queue queue = createQueue("testQueue"); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -78,7 +75,6 @@ public class MessageTest extends JMSTestBase msg.writeInt(2); msg.writeInt(3); - StreamMessage received = (StreamMessage) sendAndConsumeMessage(msg, prod, cons); Assert.assertNotNull(received); @@ -87,125 +83,103 @@ public class MessageTest extends JMSTestBase assertEquals(2, received.readObject()); assertEquals(3, received.readObject()); - try - { + try { received.readObject(); fail("Should throw exception"); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { //Ok } - try - { + try { received.readBoolean(); fail("Should throw exception"); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { //Ok } - try - { + try { received.readByte(); fail("Should throw exception"); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { //Ok } - try - { + try { received.readChar(); fail("Should throw exception"); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { //Ok } - try - { + try { received.readDouble(); fail("Should throw exception"); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { //Ok } - try - { + try { received.readFloat(); fail("Should throw exception"); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { //Ok } - try - { + try { received.readInt(); fail("Should throw exception"); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { //Ok } - try - { + try { received.readLong(); fail("Should throw exception"); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { //Ok } - try - { + try { received.readShort(); fail("Should throw exception"); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { //Ok } - try - { + try { received.readString(); fail("Should throw exception"); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { //Ok } } - finally - { + finally { conn.close(); } } @Test - public void testNullProperties() throws Exception - { + public void testNullProperties() throws Exception { conn = cf.createConnection(); Queue queue = createQueue("testQueue"); @@ -249,8 +223,7 @@ public class MessageTest extends JMSTestBase // Private ------------------------------------------------------- - private void checkProperties(final Message message) throws Exception - { + private void checkProperties(final Message message) throws Exception { Assert.assertNull(message.getObjectProperty(MessageTest.propName1)); Assert.assertNull(message.getStringProperty(MessageTest.propName1)); Assert.assertNull(message.getStringProperty(MessageTest.propName2)); @@ -258,68 +231,54 @@ public class MessageTest extends JMSTestBase Assert.assertNull(message.getStringProperty(MessageTest.propName3)); Assert.assertNull(message.getObjectProperty(MessageTest.propName3)); - try - { + try { MessageTest.log.info(message.getIntProperty(MessageTest.propName1)); Assert.fail("Should throw exception"); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { // Ok } - try - { + try { MessageTest.log.info(message.getShortProperty(MessageTest.propName1)); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { // Ok } - try - { + try { MessageTest.log.info(message.getByteProperty(MessageTest.propName1)); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { // Ok } Assert.assertEquals(false, message.getBooleanProperty(MessageTest.propName1)); - try - { + try { MessageTest.log.info(message.getLongProperty(MessageTest.propName1)); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { // Ok } - try - { + try { MessageTest.log.info(message.getFloatProperty(MessageTest.propName1)); } - catch (NullPointerException e) - { + catch (NullPointerException e) { // Ok } - try - { + try { MessageTest.log.info(message.getDoubleProperty(MessageTest.propName1)); } - catch (NullPointerException e) - { + catch (NullPointerException e) { // Ok } } // https://issues.jboss.org/browse/HORNETQ-988 @Test - public void testShouldNotThrowException() throws Exception - { + public void testShouldNotThrowException() throws Exception { Connection conn = null; createTopic(true, "Topic1"); - try - { + try { conn = cf.createConnection(); conn.start(); @@ -350,18 +309,16 @@ public class MessageTest extends JMSTestBase assertNotNull(consGeral.receive(5000)); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } - - private Message sendAndConsumeMessage(final Message msg, final MessageProducer prod, final MessageConsumer cons) throws Exception - { + private Message sendAndConsumeMessage(final Message msg, + final MessageProducer prod, + final MessageConsumer cons) throws Exception { prod.send(msg); Message received = cons.receive(MessageTest.TIMEOUT); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/NewQueueRequestorTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/NewQueueRequestorTest.java index ddb04e46e1..c3e2b1d340 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/NewQueueRequestorTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/NewQueueRequestorTest.java @@ -33,25 +33,23 @@ import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; import org.apache.activemq.artemis.tests.util.JMSTestBase; import org.junit.Test; -public class NewQueueRequestorTest extends JMSTestBase -{ +public class NewQueueRequestorTest extends JMSTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @Test - public void testQueueRequestor() throws Exception - { + public void testQueueRequestor() throws Exception { QueueConnection conn1 = null, conn2 = null; - try - { + try { Queue queue1 = createQueue(true, "myQueue"); - conn1 = (QueueConnection)cf.createConnection(); + conn1 = (QueueConnection) cf.createConnection(); QueueSession sess1 = conn1.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); QueueRequestor requestor = new QueueRequestor(sess1, queue1); conn1.start(); // And the responder - conn2 = (QueueConnection)cf.createConnection(); + conn2 = (QueueConnection) cf.createConnection(); QueueSession sess2 = conn2.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); TestMessageListener listener = new TestMessageListener(sess2); QueueReceiver receiver = sess2.createReceiver(queue1); @@ -60,15 +58,14 @@ public class NewQueueRequestorTest extends JMSTestBase Message m1 = sess1.createMessage(); log.trace("Sending request message"); - TextMessage m2 = (TextMessage)requestor.request(m1); + TextMessage m2 = (TextMessage) requestor.request(m1); assertNotNull(m2); assertEquals("This is the response", m2.getText()); requestor.close(); } - finally - { + finally { conn1.close(); conn2.close(); } @@ -82,28 +79,24 @@ public class NewQueueRequestorTest extends JMSTestBase // Inner classes ------------------------------------------------- - class TestMessageListener implements MessageListener - { + class TestMessageListener implements MessageListener { + private final QueueSession sess; private final QueueSender sender; - public TestMessageListener(final QueueSession sess) throws JMSException - { + public TestMessageListener(final QueueSession sess) throws JMSException { this.sess = sess; sender = sess.createSender(null); } - public void onMessage(final Message m) - { - try - { + public void onMessage(final Message m) { + try { Destination queue = m.getJMSReplyTo(); Message m2 = sess.createTextMessage("This is the response"); sender.send(queue, m2); } - catch (JMSException e) - { + catch (JMSException e) { log.error(e); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/NoLocalSubscriberTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/NoLocalSubscriberTest.java index 2aec01e3bd..1bca7eaf60 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/NoLocalSubscriberTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/NoLocalSubscriberTest.java @@ -32,13 +32,11 @@ import javax.jms.TopicSubscriber; import org.apache.activemq.artemis.tests.util.JMSTestBase; import org.apache.activemq.artemis.tests.util.RandomUtil; -public class NoLocalSubscriberTest extends JMSTestBase -{ +public class NoLocalSubscriberTest extends JMSTestBase { // Constants ----------------------------------------------------- private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; - // Static -------------------------------------------------------- // Attributes ---------------------------------------------------- @@ -52,18 +50,15 @@ public class NoLocalSubscriberTest extends JMSTestBase * can be sent by *another* connection and will be received by the nolocal consumer */ @Test - public void testNoLocal() throws Exception - { - if (log.isTraceEnabled()) - { + public void testNoLocal() throws Exception { + if (log.isTraceEnabled()) { log.trace("testNoLocal"); } Connection defaultConn = null; Connection newConn = null; - try - { + try { Topic topic1 = createTopic("topic1"); defaultConn = cf.createConnection(); Session defaultSess = defaultConn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -76,17 +71,15 @@ public class NoLocalSubscriberTest extends JMSTestBase String text = RandomUtil.randomString(); // message is created only once from the same connection than the noLocalConsumer TextMessage messageSent = defaultSess.createTextMessage(text); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { defaultProd.send(messageSent); } Message received = null; - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { received = defaultConsumer.receive(5000); assertNotNull(received); - assertEquals(text, ((TextMessage)received).getText()); + assertEquals(text, ((TextMessage) received).getText()); } newConn = cf.createConnection(); @@ -102,7 +95,7 @@ public class NoLocalSubscriberTest extends JMSTestBase received = newConsumer.receive(5000); assertNotNull(received); - assertEquals(text, ((TextMessage)received).getText()); + assertEquals(text, ((TextMessage) received).getText()); text = RandomUtil.randomString(); messageSent.setText(text); @@ -112,24 +105,20 @@ public class NoLocalSubscriberTest extends JMSTestBase received = noLocalConsumer.receive(5000); assertNotNull("nolocal consumer did not get message", received); - assertEquals(text, ((TextMessage)received).getText()); + assertEquals(text, ((TextMessage) received).getText()); } - finally - { - if (defaultConn != null) - { + finally { + if (defaultConn != null) { defaultConn.close(); } - if (newConn != null) - { + if (newConn != null) { newConn.close(); } } } @Test - public void testNoLocalReconnect() throws Exception - { + public void testNoLocalReconnect() throws Exception { ConnectionFactory connectionFactory = cf; String uniqueID = Long.toString(System.currentTimeMillis()); String topicName = "exampleTopic"; @@ -145,8 +134,7 @@ public class NoLocalSubscriberTest extends JMSTestBase Connection connection = connectionFactory.createConnection("guest", "guest"); connection.setClientID(clientID); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber topicSubscriber = - session.createDurableSubscriber(topic, subscriptionName, messageSelector, noLocal); + TopicSubscriber topicSubscriber = session.createDurableSubscriber(topic, subscriptionName, messageSelector, noLocal); topicSubscriber.close(); connection.close(); } @@ -179,14 +167,13 @@ public class NoLocalSubscriberTest extends JMSTestBase Connection connection = connectionFactory.createConnection("guest", "guest"); connection.setClientID(clientID); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber topicSubscriber = - session.createDurableSubscriber(topic, subscriptionName, messageSelector, noLocal); + TopicSubscriber topicSubscriber = session.createDurableSubscriber(topic, subscriptionName, messageSelector, noLocal); connection.start(); // now drain the subscription // we should not receive message M3, but we should receive message M4 // However for some reason Artemis doesn't receive either - TextMessage textMessage = (TextMessage)topicSubscriber.receive(1000); + TextMessage textMessage = (TextMessage) topicSubscriber.receive(1000); assertNotNull(textMessage); assertEquals("M4", textMessage.getText()); @@ -198,8 +185,7 @@ public class NoLocalSubscriberTest extends JMSTestBase } @Test - public void testNoLocalReconnect2() throws Exception - { + public void testNoLocalReconnect2() throws Exception { ConnectionFactory connectionFactory = cf; String uniqueID = Long.toString(System.currentTimeMillis()); @@ -218,8 +204,7 @@ public class NoLocalSubscriberTest extends JMSTestBase originalConnection = connectionFactory.createConnection("guest", "guest"); originalConnection.setClientID(clientID); Session session = originalConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber topicSubscriber = - session.createDurableSubscriber(topic, subscriptionName, messageSelector, noLocal); + TopicSubscriber topicSubscriber = session.createDurableSubscriber(topic, subscriptionName, messageSelector, noLocal); topicSubscriber.close(); session.close(); } @@ -248,14 +233,13 @@ public class NoLocalSubscriberTest extends JMSTestBase { Session session = originalConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber topicSubscriber = - session.createDurableSubscriber(topic, subscriptionName, messageSelector, noLocal); + TopicSubscriber topicSubscriber = session.createDurableSubscriber(topic, subscriptionName, messageSelector, noLocal); originalConnection.start(); // now drain the subscription // we should not receive message M3, but we should receive message M4 // However for some reason Artemis doesn't receive either - TextMessage textMessage = (TextMessage)topicSubscriber.receive(1000); + TextMessage textMessage = (TextMessage) topicSubscriber.receive(1000); assertNotNull(textMessage); assertEquals("M4", textMessage.getText()); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/PreACKJMSTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/PreACKJMSTest.java index 8d25d63034..e702c959e1 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/PreACKJMSTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/PreACKJMSTest.java @@ -31,8 +31,7 @@ import javax.jms.TextMessage; import java.util.ArrayList; import java.util.List; -public class PreACKJMSTest extends JMSTestBase -{ +public class PreACKJMSTest extends JMSTestBase { // Constants ----------------------------------------------------- @@ -47,25 +46,21 @@ public class PreACKJMSTest extends JMSTestBase // Public -------------------------------------------------------- @Test - public void testPreACKAuto() throws Exception - { + public void testPreACKAuto() throws Exception { internalTestPreACK(Session.AUTO_ACKNOWLEDGE); } @Test - public void testPreACKClientACK() throws Exception - { + public void testPreACKClientACK() throws Exception { internalTestPreACK(Session.CLIENT_ACKNOWLEDGE); } @Test - public void testPreACKDupsOK() throws Exception - { + public void testPreACKDupsOK() throws Exception { internalTestPreACK(Session.DUPS_OK_ACKNOWLEDGE); } - public void internalTestPreACK(final int sessionType) throws Exception - { + public void internalTestPreACK(final int sessionType) throws Exception { conn = cf.createConnection(); Session sess = conn.createSession(false, sessionType); @@ -100,8 +95,7 @@ public class PreACKJMSTest extends JMSTestBase assertNull("ConnectionFactory is on PreACK mode, the message shouldn't be received", msg2); } - public void disabled_testPreACKTransactional() throws Exception - { + public void disabled_testPreACKTransactional() throws Exception { conn = cf.createConnection(); Session sess = conn.createSession(true, Session.SESSION_TRANSACTED); @@ -146,16 +140,14 @@ public class PreACKJMSTest extends JMSTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); queue = createQueue("queue1"); } @Override protected void createCF(final List connectorConfigs, - final String... jndiBindings) throws Exception - { + final String... jndiBindings) throws Exception { int retryInterval = 1000; double retryIntervalMultiplier = 1.0; int reconnectAttempts = -1; @@ -163,41 +155,7 @@ public class PreACKJMSTest extends JMSTestBase ArrayList connectors = registerConnectors(server, connectorConfigs); - jmsServer.createConnectionFactory("ManualReconnectionToSingleServerTest", - false, - JMSFactoryType.CF, - connectors, - null, - ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, - ActiveMQClient.DEFAULT_CONNECTION_TTL, - callTimeout, - ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, - ActiveMQClient.DEFAULT_CACHE_LARGE_MESSAGE_CLIENT, - ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES, - ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, - ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, - ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, - ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, - ActiveMQClient.DEFAULT_AUTO_GROUP, - true, - ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, - ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, - retryInterval, - retryIntervalMultiplier, - ActiveMQClient.DEFAULT_MAX_RETRY_INTERVAL, - reconnectAttempts, - ActiveMQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION, - null, - jndiBindings); + jmsServer.createConnectionFactory("ManualReconnectionToSingleServerTest", false, JMSFactoryType.CF, connectors, null, ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, ActiveMQClient.DEFAULT_CONNECTION_TTL, callTimeout, ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, ActiveMQClient.DEFAULT_CACHE_LARGE_MESSAGE_CLIENT, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES, ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, ActiveMQClient.DEFAULT_AUTO_GROUP, true, ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, retryInterval, retryIntervalMultiplier, ActiveMQClient.DEFAULT_MAX_RETRY_INTERVAL, reconnectAttempts, ActiveMQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION, null, jndiBindings); } // Private ------------------------------------------------------- diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/ReSendMessageTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/ReSendMessageTest.java index 62a057a581..d2a2b81494 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/ReSendMessageTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/ReSendMessageTest.java @@ -42,8 +42,7 @@ import java.util.List; /** * Receive Messages and resend them, like the bridge would do */ -public class ReSendMessageTest extends JMSTestBase -{ +public class ReSendMessageTest extends JMSTestBase { // Constants ----------------------------------------------------- @@ -58,19 +57,16 @@ public class ReSendMessageTest extends JMSTestBase // Public -------------------------------------------------------- @Test - public void testResendWithLargeMessage() throws Exception - { + public void testResendWithLargeMessage() throws Exception { conn = cf.createConnection(); conn.start(); Session sess = conn.createSession(true, Session.SESSION_TRANSACTED); ArrayList msgs = new ArrayList(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { BytesMessage bm = sess.createBytesMessage(); - bm.setObjectProperty(ActiveMQJMSConstants.JMS_ACTIVEMQ_INPUT_STREAM, - ActiveMQTestBase.createFakeLargeStream(2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE)); + bm.setObjectProperty(ActiveMQJMSConstants.JMS_ACTIVEMQ_INPUT_STREAM, ActiveMQTestBase.createFakeLargeStream(2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE)); msgs.add(bm); MapMessage mm = sess.createMapMessage(); @@ -95,16 +91,14 @@ public class ReSendMessageTest extends JMSTestBase } @Test - public void testResendWithMapMessagesOnly() throws Exception - { + public void testResendWithMapMessagesOnly() throws Exception { conn = cf.createConnection(); conn.start(); Session sess = conn.createSession(true, Session.SESSION_TRANSACTED); ArrayList msgs = new ArrayList(); - for (int i = 0; i < 1; i++) - { + for (int i = 0; i < 1; i++) { MapMessage mm = sess.createMapMessage(); mm.setBoolean("boolean", true); mm.setByte("byte", (byte) 3); @@ -127,12 +121,10 @@ public class ReSendMessageTest extends JMSTestBase internalTestResend(msgs, sess); } - public void internalTestResend(final ArrayList msgs, final Session sess) throws Exception - { + public void internalTestResend(final ArrayList msgs, final Session sess) throws Exception { MessageProducer prod = sess.createProducer(queue); - for (Message msg : msgs) - { + for (Message msg : msgs) { prod.send(msg); } @@ -140,8 +132,7 @@ public class ReSendMessageTest extends JMSTestBase MessageConsumer cons = sess.createConsumer(queue); - for (int i = 0; i < msgs.size(); i++) - { + for (int i = 0; i < msgs.size(); i++) { Message msg = cons.receive(5000); Assert.assertNotNull(msg); @@ -152,8 +143,7 @@ public class ReSendMessageTest extends JMSTestBase sess.commit(); - for (Message originalMessage : msgs) - { + for (Message originalMessage : msgs) { Message copiedMessage = cons.receive(5000); Assert.assertNotNull(copiedMessage); @@ -161,60 +151,48 @@ public class ReSendMessageTest extends JMSTestBase sess.commit(); - if (copiedMessage instanceof BytesMessage) - { + if (copiedMessage instanceof BytesMessage) { BytesMessage copiedBytes = (BytesMessage) copiedMessage; - for (int i = 0; i < copiedBytes.getBodyLength(); i++) - { + for (int i = 0; i < copiedBytes.getBodyLength(); i++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), copiedBytes.readByte()); } } - else if (copiedMessage instanceof MapMessage) - { + else if (copiedMessage instanceof MapMessage) { MapMessage copiedMap = (MapMessage) copiedMessage; MapMessage originalMap = (MapMessage) originalMessage; - if (originalMap.getString("str") != null) - { + if (originalMap.getString("str") != null) { Assert.assertEquals(originalMap.getString("str"), copiedMap.getString("str")); } - if (originalMap.getObject("long") != null) - { + if (originalMap.getObject("long") != null) { Assert.assertEquals(originalMap.getLong("long"), copiedMap.getLong("long")); } - if (originalMap.getObject("int") != null) - { + if (originalMap.getObject("int") != null) { Assert.assertEquals(originalMap.getInt("int"), copiedMap.getInt("int")); } - if (originalMap.getObject("object") != null) - { + if (originalMap.getObject("object") != null) { Assert.assertEquals(originalMap.getObject("object"), copiedMap.getObject("object")); } } - else if (copiedMessage instanceof ObjectMessage) - { - Assert.assertNotSame(((ObjectMessage) originalMessage).getObject(), - ((ObjectMessage) copiedMessage).getObject()); - Assert.assertEquals(((ObjectMessage) originalMessage).getObject(), - ((ObjectMessage) copiedMessage).getObject()); + else if (copiedMessage instanceof ObjectMessage) { + Assert.assertNotSame(((ObjectMessage) originalMessage).getObject(), ((ObjectMessage) copiedMessage).getObject()); + Assert.assertEquals(((ObjectMessage) originalMessage).getObject(), ((ObjectMessage) copiedMessage).getObject()); } - else if (copiedMessage instanceof TextMessage) - { + else if (copiedMessage instanceof TextMessage) { Assert.assertEquals(((TextMessage) originalMessage).getText(), ((TextMessage) copiedMessage).getText()); } } } - public static class SomeSerializable implements Serializable - { + public static class SomeSerializable implements Serializable { + private static final long serialVersionUID = -8576054940441747312L; final String txt; @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (txt == null ? 0 : txt.hashCode()); @@ -222,37 +200,29 @@ public class ReSendMessageTest extends JMSTestBase } @Override - public boolean equals(final Object obj) - { - if (this == obj) - { + public boolean equals(final Object obj) { + if (this == obj) { return true; } - if (obj == null) - { + if (obj == null) { return false; } - if (getClass() != obj.getClass()) - { + if (getClass() != obj.getClass()) { return false; } SomeSerializable other = (SomeSerializable) obj; - if (txt == null) - { - if (other.txt != null) - { + if (txt == null) { + if (other.txt != null) { return false; } } - else if (!txt.equals(other.txt)) - { + else if (!txt.equals(other.txt)) { return false; } return true; } - SomeSerializable(final String txt) - { + SomeSerializable(final String txt) { this.txt = txt; } } @@ -262,54 +232,18 @@ public class ReSendMessageTest extends JMSTestBase // Protected ----------------------------------------------------- @Override protected void createCF(final List connectorConfigs, - final String... jndiBindings) throws Exception - { + final String... jndiBindings) throws Exception { int retryInterval = 1000; double retryIntervalMultiplier = 1.0; int reconnectAttempts = -1; int callTimeout = 30000; - jmsServer.createConnectionFactory("ManualReconnectionToSingleServerTest", - false, - JMSFactoryType.CF, - registerConnectors(server, connectorConfigs), - null, - ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, - ActiveMQClient.DEFAULT_CONNECTION_TTL, - callTimeout, - ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, - true, - ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES, - ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, - ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, - ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, - ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, - ActiveMQClient.DEFAULT_AUTO_GROUP, - ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, - ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, - retryInterval, - retryIntervalMultiplier, - ActiveMQClient.DEFAULT_MAX_RETRY_INTERVAL, - reconnectAttempts, - ActiveMQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION, - null, - jndiBindings); + jmsServer.createConnectionFactory("ManualReconnectionToSingleServerTest", false, JMSFactoryType.CF, registerConnectors(server, connectorConfigs), null, ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, ActiveMQClient.DEFAULT_CONNECTION_TTL, callTimeout, ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, true, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES, ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, ActiveMQClient.DEFAULT_AUTO_GROUP, ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, retryInterval, retryIntervalMultiplier, ActiveMQClient.DEFAULT_MAX_RETRY_INTERVAL, reconnectAttempts, ActiveMQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION, null, jndiBindings); } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); queue = createQueue("queue1"); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/ReceiveNoWaitTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/ReceiveNoWaitTest.java index a4536165ee..4e5eb1ce39 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/ReceiveNoWaitTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/ReceiveNoWaitTest.java @@ -29,17 +29,15 @@ import javax.jms.Session; import javax.jms.TextMessage; /** - * * A ReceiveNoWaitTest */ -public class ReceiveNoWaitTest extends JMSTestBase -{ +public class ReceiveNoWaitTest extends JMSTestBase { + private Queue queue; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); queue = createQueue("TestQueue"); @@ -51,12 +49,10 @@ public class ReceiveNoWaitTest extends JMSTestBase * https://jira.jboss.org/jira/browse/HORNETQ-284 */ @Test - public void testReceiveNoWait() throws Exception - { + public void testReceiveNoWait() throws Exception { assertNotNull(queue); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { Connection connection = cf.createConnection(); Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); @@ -65,8 +61,7 @@ public class ReceiveNoWaitTest extends JMSTestBase producer.setDeliveryMode(DeliveryMode.PERSISTENT); - for (int j = 0; j < 100; j++) - { + for (int j = 0; j < 100; j++) { String text = "Message" + j; TextMessage message = session.createTextMessage(); @@ -80,12 +75,10 @@ public class ReceiveNoWaitTest extends JMSTestBase MessageConsumer consumer = session.createConsumer(queue); - for (int j = 0; j < 100; j++) - { - TextMessage m = (TextMessage)consumer.receiveNoWait(); + for (int j = 0; j < 100; j++) { + TextMessage m = (TextMessage) consumer.receiveNoWait(); - if (m == null) - { + if (m == null) { throw new IllegalStateException("msg null"); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/RemoteConnectionStressTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/RemoteConnectionStressTest.java index 8a9ae906c4..ea0526a28f 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/RemoteConnectionStressTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/RemoteConnectionStressTest.java @@ -40,15 +40,14 @@ import javax.management.MBeanServerFactory; /** * test Written to replicate https://issues.jboss.org/browse/HORNETQ-1312 */ -public class RemoteConnectionStressTest extends ActiveMQTestBase -{ +public class RemoteConnectionStressTest extends ActiveMQTestBase { + ActiveMQServer server; MBeanServer mbeanServer; JMSServerManagerImpl jmsServer; @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); mbeanServer = MBeanServerFactory.createMBeanServer(); @@ -65,11 +64,8 @@ public class RemoteConnectionStressTest extends ActiveMQTestBase } @Test - public void testSimpleRemoteConnections() throws Exception - { - for (int i = 0; i < 1000; i++) - { - + public void testSimpleRemoteConnections() throws Exception { + for (int i = 0; i < 1000; i++) { TransportConfiguration config = new TransportConfiguration(NETTY_CONNECTOR_FACTORY); ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, config); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/SessionClosedOnRemotingConnectionFailureTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/SessionClosedOnRemotingConnectionFailureTest.java index 6e05ec2485..515858dfd5 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/SessionClosedOnRemotingConnectionFailureTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/SessionClosedOnRemotingConnectionFailureTest.java @@ -42,11 +42,9 @@ import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; import org.apache.activemq.artemis.tests.util.JMSTestBase; /** - * * A SessionClosedOnRemotingConnectionFailureTest */ -public class SessionClosedOnRemotingConnectionFailureTest extends JMSTestBase -{ +public class SessionClosedOnRemotingConnectionFailureTest extends JMSTestBase { // Constants ----------------------------------------------------- private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @@ -60,56 +58,19 @@ public class SessionClosedOnRemotingConnectionFailureTest extends JMSTestBase // Public -------------------------------------------------------- @Test - public void testSessionClosedOnRemotingConnectionFailure() throws Exception - { + public void testSessionClosedOnRemotingConnectionFailure() throws Exception { List connectorConfigs = new ArrayList(); connectorConfigs.add(new TransportConfiguration(INVM_CONNECTOR_FACTORY)); + jmsServer.createConnectionFactory("cffoo", false, JMSFactoryType.CF, registerConnectors(server, connectorConfigs), null, ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, ActiveMQClient.DEFAULT_CONNECTION_TTL, ActiveMQClient.DEFAULT_CALL_TIMEOUT, ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, ActiveMQClient.DEFAULT_CACHE_LARGE_MESSAGE_CLIENT, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES, ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, ActiveMQClient.DEFAULT_AUTO_GROUP, ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_RETRY_INTERVAL, ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, ActiveMQClient.DEFAULT_MAX_RETRY_INTERVAL, 0, ActiveMQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION, null, "/cffoo"); - jmsServer.createConnectionFactory("cffoo", - false, - JMSFactoryType.CF, - registerConnectors(server, connectorConfigs), - null, - ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, - ActiveMQClient.DEFAULT_CONNECTION_TTL, - ActiveMQClient.DEFAULT_CALL_TIMEOUT, - ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, - ActiveMQClient.DEFAULT_CACHE_LARGE_MESSAGE_CLIENT, - ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES, - ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, - ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, - ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, - ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, - ActiveMQClient.DEFAULT_AUTO_GROUP, - ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, - ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_RETRY_INTERVAL, - ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, - ActiveMQClient.DEFAULT_MAX_RETRY_INTERVAL, - 0, - ActiveMQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION, - null, - "/cffoo"); - - cf = (ConnectionFactory)namingContext.lookup("/cffoo"); + cf = (ConnectionFactory) namingContext.lookup("/cffoo"); Connection conn = cf.createConnection(); Queue queue = createQueue("testQueue"); - try - { + try { Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = session.createProducer(queue); @@ -124,31 +85,27 @@ public class SessionClosedOnRemotingConnectionFailureTest extends JMSTestBase // Now fail the underlying connection - RemotingConnection connection = ((ClientSessionInternal)((ActiveMQSession)session).getCoreSession()).getConnection(); + RemotingConnection connection = ((ClientSessionInternal) ((ActiveMQSession) session).getCoreSession()).getConnection(); connection.fail(new ActiveMQNotConnectedException()); // Now try and use the producer - try - { + try { prod.send(session.createMessage()); Assert.fail("Should throw exception"); } - catch (JMSException e) - { + catch (JMSException e) { // assertEquals(ActiveMQException.OBJECT_CLOSED, e.getCode()); } - try - { + try { cons.receive(); Assert.fail("Should throw exception"); } - catch (JMSException e) - { + catch (JMSException e) { // assertEquals(ActiveMQException.OBJECT_CLOSED, e.getCode()); } @@ -156,14 +113,11 @@ public class SessionClosedOnRemotingConnectionFailureTest extends JMSTestBase conn.close(); } - finally - { - try - { + finally { + try { conn.close(); } - catch (Throwable igonred) - { + catch (Throwable igonred) { } } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/SessionTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/SessionTest.java index 0c4801e1d8..8fdce00e05 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/SessionTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/SessionTest.java @@ -26,18 +26,15 @@ import org.apache.activemq.artemis.tests.util.JMSTestBase; import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; import org.junit.Test; -public class SessionTest extends JMSTestBase -{ +public class SessionTest extends JMSTestBase { @Test - public void testIillegalStateException() throws Exception - { + public void testIillegalStateException() throws Exception { Connection defaultConn = null; QueueConnection qConn = null; Connection connClientID = null; ActiveMQConnectionFactory activeMQConnectionFactory = (ActiveMQConnectionFactory) cf; - try - { + try { String clientID = "somethingElse" + name.getMethodName(); defaultConn = cf.createConnection(); qConn = activeMQConnectionFactory.createQueueConnection(); @@ -48,112 +45,88 @@ public class SessionTest extends JMSTestBase Topic topic = createTopic("topic"); QueueSession qSess = qConn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); - try - { + try { qSess.createDurableConsumer(topic, "mySub1"); } - catch (javax.jms.IllegalStateException ex) - { + catch (javax.jms.IllegalStateException ex) { //ok expected. } - try - { + try { qSess.createDurableConsumer(topic, "mySub1", "TEST = 'test'", false); } - catch (javax.jms.IllegalStateException ex) - { + catch (javax.jms.IllegalStateException ex) { //ok expected. } - try - { + try { qSess.createSharedConsumer(topic, "mySub1"); } - catch (javax.jms.IllegalStateException ex) - { + catch (javax.jms.IllegalStateException ex) { //ok expected. } - try - { + try { qSess.createSharedConsumer(topic, "mySub1", "TEST = 'test'"); } - catch (javax.jms.IllegalStateException ex) - { + catch (javax.jms.IllegalStateException ex) { //ok expected. } - try - { + try { qSess.createSharedDurableConsumer(topic, "mySub1"); } - catch (javax.jms.IllegalStateException ex) - { + catch (javax.jms.IllegalStateException ex) { //ok expected. } - try - { + try { qSess.createSharedDurableConsumer(topic, "mySub1", "TEST = 'test'"); } - catch (javax.jms.IllegalStateException ex) - { + catch (javax.jms.IllegalStateException ex) { //ok expected. } Session defaultSess = defaultConn.createSession(); - try - { + try { defaultSess.createDurableSubscriber(topic, "mySub1"); } - catch (javax.jms.IllegalStateException ex) - { + catch (javax.jms.IllegalStateException ex) { //ok expected. } - try - { + try { defaultSess.createDurableSubscriber(topic, "mySub1", "TEST = 'test'", true); } - catch (javax.jms.IllegalStateException ex) - { + catch (javax.jms.IllegalStateException ex) { //ok expected. } - try - { + try { defaultSess.createDurableConsumer(topic, "mySub1"); } - catch (javax.jms.IllegalStateException ex) - { + catch (javax.jms.IllegalStateException ex) { //ok expected. } - try - { + try { defaultSess.createDurableConsumer(topic, "mySub1", "TEST = 'test'", true); } - catch (javax.jms.IllegalStateException ex) - { + catch (javax.jms.IllegalStateException ex) { //ok expected. } } - finally - { - if (defaultConn != null) - { + finally { + if (defaultConn != null) { defaultConn.close(); } - if (qConn != null) - { + if (qConn != null) { qConn.close(); } - if (connClientID != null) - { + if (connClientID != null) { connClientID.close(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/StoreConfigTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/StoreConfigTest.java index cf67509686..a6b85dfdcf 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/StoreConfigTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/StoreConfigTest.java @@ -34,49 +34,37 @@ import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.jms.server.config.impl.ConnectionFactoryConfigurationImpl; import org.apache.activemq.artemis.tests.util.JMSTestBase; -public class StoreConfigTest extends JMSTestBase -{ +public class StoreConfigTest extends JMSTestBase { @Override - protected boolean usePersistence() - { + protected boolean usePersistence() { return true; } @Test - public void testCreateCF() throws Exception - { + public void testCreateCF() throws Exception { server.getConfiguration().getConnectorConfigurations().put("tst", new TransportConfiguration(INVM_CONNECTOR_FACTORY)); server.getConfiguration().getConnectorConfigurations().put("np", new TransportConfiguration(INVM_CONNECTOR_FACTORY)); List transportConfigurations = new ArrayList(); transportConfigurations.add("tst"); - ConnectionFactoryConfigurationImpl factCFG = (ConnectionFactoryConfigurationImpl) new ConnectionFactoryConfigurationImpl() - .setName("tst") - .setConnectorNames(transportConfigurations); + ConnectionFactoryConfigurationImpl factCFG = (ConnectionFactoryConfigurationImpl) new ConnectionFactoryConfigurationImpl().setName("tst").setConnectorNames(transportConfigurations); - jmsServer.createConnectionFactory(true, factCFG, "/someCF", "/someCF2" ); + jmsServer.createConnectionFactory(true, factCFG, "/someCF", "/someCF2"); + ConnectionFactoryConfigurationImpl nonPersisted = (ConnectionFactoryConfigurationImpl) new ConnectionFactoryConfigurationImpl().setName("np").setConnectorNames(transportConfigurations); - ConnectionFactoryConfigurationImpl nonPersisted = (ConnectionFactoryConfigurationImpl) new ConnectionFactoryConfigurationImpl() - .setName("np") - .setConnectorNames(transportConfigurations); + jmsServer.createConnectionFactory(false, nonPersisted, "/nonPersisted"); - jmsServer.createConnectionFactory(false, nonPersisted, "/nonPersisted" ); - - - try - { + try { jmsServer.addConnectionFactoryToBindingRegistry("np", "/someCF"); fail("Failure expected and the API let duplicates"); } - catch (NamingException expected) - { + catch (NamingException expected) { // expected } - openCon("/someCF"); openCon("/someCF2"); openCon("/nonPersisted"); @@ -94,21 +82,18 @@ public class StoreConfigTest extends JMSTestBase jmsServer.start(); jmsServer.addConnectionFactoryToBindingRegistry("tst", "/newJNDI"); - try - { + try { jmsServer.addConnectionFactoryToBindingRegistry("tst", "/newJNDI"); fail("Failure expected and the API let duplicates"); } - catch (NamingException expected) - { - // expected + catch (NamingException expected) { + // expected } openCon("/someCF"); openCon("/someCF2"); openCon("/newJNDI"); assertNullJNDI("/nonPersisted"); - jmsServer.stop(); assertNullJNDI("/newJNDI"); @@ -121,8 +106,7 @@ public class StoreConfigTest extends JMSTestBase } @Test - public void testCreateTopic() throws Exception - { + public void testCreateTopic() throws Exception { server.getConfiguration().getConnectorConfigurations().put("tst", new TransportConfiguration(INVM_CONNECTOR_FACTORY)); server.getConfiguration().getConnectorConfigurations().put("np", new TransportConfiguration(INVM_CONNECTOR_FACTORY)); @@ -130,9 +114,7 @@ public class StoreConfigTest extends JMSTestBase List transportConfigurations = new ArrayList(); transportConfigurations.add("tst"); - ConnectionFactoryConfigurationImpl factCFG = (ConnectionFactoryConfigurationImpl) new ConnectionFactoryConfigurationImpl() - .setName("tst") - .setConnectorNames(transportConfigurations); + ConnectionFactoryConfigurationImpl factCFG = (ConnectionFactoryConfigurationImpl) new ConnectionFactoryConfigurationImpl().setName("tst").setConnectorNames(transportConfigurations); jmsServer.createConnectionFactory(true, factCFG, "/someCF"); @@ -159,10 +141,8 @@ public class StoreConfigTest extends JMSTestBase assertNullJNDI("/t2"); assertNullJNDI("/t.2"); - jmsServer.start(); - checkDestination("/t1"); checkDestination("/t.1"); @@ -181,7 +161,6 @@ public class StoreConfigTest extends JMSTestBase assertNullJNDI("/t2"); assertNullJNDI("/t.2"); - assertTrue(jmsServer.removeTopicFromBindingRegistry("topicOne", "/tI")); assertFalse(jmsServer.removeTopicFromBindingRegistry("topicOne", "nothing")); @@ -200,7 +179,6 @@ public class StoreConfigTest extends JMSTestBase checkDestination("/t1"); checkDestination("/t.1"); - jmsServer.removeTopicFromBindingRegistry("topicOne"); assertTrue(jmsServer.createTopic(true, "topicOne", "/topicx.1", "/topicx.2")); @@ -213,14 +191,11 @@ public class StoreConfigTest extends JMSTestBase checkDestination("/topicx.2"); } - - - private void checkDestination(String name) throws Exception - { + private void checkDestination(String name) throws Exception { ConnectionFactory cf = (ConnectionFactory) namingContext.lookup("/someCF"); Connection conn = cf.createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination dest = (Destination)namingContext.lookup(name); + Destination dest = (Destination) namingContext.lookup(name); conn.start(); MessageConsumer cons = sess.createConsumer(dest); @@ -232,22 +207,16 @@ public class StoreConfigTest extends JMSTestBase } - - - @Test - public void testCreateQueue() throws Exception - { + public void testCreateQueue() throws Exception { server.getConfiguration().getConnectorConfigurations().put("tst", new TransportConfiguration(INVM_CONNECTOR_FACTORY)); -// server.getConfiguration().getConnectorConfigurations().put("np", new TransportConfiguration(INVM_CONNECTOR_FACTORY)); + // server.getConfiguration().getConnectorConfigurations().put("np", new TransportConfiguration(INVM_CONNECTOR_FACTORY)); List transportConfigurations = new ArrayList(); transportConfigurations.add("tst"); - ConnectionFactoryConfigurationImpl factCFG = (ConnectionFactoryConfigurationImpl) new ConnectionFactoryConfigurationImpl() - .setName("tst") - .setConnectorNames(transportConfigurations); + ConnectionFactoryConfigurationImpl factCFG = (ConnectionFactoryConfigurationImpl) new ConnectionFactoryConfigurationImpl().setName("tst").setConnectorNames(transportConfigurations); jmsServer.createConnectionFactory(true, factCFG, "/someCF"); @@ -275,10 +244,8 @@ public class StoreConfigTest extends JMSTestBase assertNullJNDI("/q2"); assertNullJNDI("/q.2"); - jmsServer.start(); - checkDestination("/q1"); checkDestination("/q.1"); @@ -297,7 +264,6 @@ public class StoreConfigTest extends JMSTestBase assertNullJNDI("/q2"); assertNullJNDI("/q.2"); - assertTrue(jmsServer.removeQueueFromBindingRegistry("queue1", "/q1")); assertFalse(jmsServer.removeQueueFromBindingRegistry("queue1", "nothing")); @@ -316,7 +282,6 @@ public class StoreConfigTest extends JMSTestBase jmsServer.removeQueueFromBindingRegistry("queue1"); - assertTrue(jmsServer.createQueue(true, "queue1", null, true, "/newq1", "/newq.1")); assertNullJNDI("/q1"); assertNullJNDI("/q.1"); @@ -325,33 +290,29 @@ public class StoreConfigTest extends JMSTestBase checkDestination("/newq1"); checkDestination("newq.1"); - jmsServer.stop(); } /** * */ - private void assertNullJNDI(String name) - { + private void assertNullJNDI(String name) { Object obj = null; - try - { + try { obj = namingContext.lookup(name); } - catch (Exception expected) - { + catch (Exception expected) { } assertNull(obj); } - /** + + /** * @throws NamingException * @throws JMSException */ - private void openCon(String name) throws NamingException, JMSException - { - ConnectionFactory cf = (ConnectionFactory)namingContext.lookup(name); + private void openCon(String name) throws NamingException, JMSException { + ConnectionFactory cf = (ConnectionFactory) namingContext.lookup(name); Connection conn = cf.createConnection(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/TextMessageTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/TextMessageTest.java index 8ed5f9a1f3..6c6acac292 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/TextMessageTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/TextMessageTest.java @@ -32,8 +32,7 @@ import javax.jms.Session; import javax.jms.TextMessage; import java.util.List; -public class TextMessageTest extends JMSTestBase -{ +public class TextMessageTest extends JMSTestBase { // Constants ----------------------------------------------------- @@ -48,8 +47,7 @@ public class TextMessageTest extends JMSTestBase // Public -------------------------------------------------------- @Test - public void testSendReceiveNullBody() throws Exception - { + public void testSendReceiveNullBody() throws Exception { conn = cf.createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -81,60 +79,50 @@ public class TextMessageTest extends JMSTestBase } @Test - public void testSendReceiveWithBody0() throws Exception - { + public void testSendReceiveWithBody0() throws Exception { testSendReceiveWithBody(0); } @Test - public void testSendReceiveWithBody1() throws Exception - { + public void testSendReceiveWithBody1() throws Exception { testSendReceiveWithBody(1); } @Test - public void testSendReceiveWithBody9() throws Exception - { + public void testSendReceiveWithBody9() throws Exception { testSendReceiveWithBody(9); } @Test - public void testSendReceiveWithBody20() throws Exception - { + public void testSendReceiveWithBody20() throws Exception { testSendReceiveWithBody(20); } @Test - public void testSendReceiveWithBody10000() throws Exception - { + public void testSendReceiveWithBody10000() throws Exception { testSendReceiveWithBody(10000); } @Test - public void testSendReceiveWithBody0xffff() throws Exception - { + public void testSendReceiveWithBody0xffff() throws Exception { testSendReceiveWithBody(0xffff); } @Test - public void testSendReceiveWithBody0xffffplus1() throws Exception - { + public void testSendReceiveWithBody0xffffplus1() throws Exception { testSendReceiveWithBody(0xffff + 1); } @Test - public void testSendReceiveWithBody0xfffftimes2() throws Exception - { + public void testSendReceiveWithBody0xfffftimes2() throws Exception { testSendReceiveWithBody(2 * 0xffff); } - private void testSendReceiveWithBody(final int bodyLength) throws Exception - { + private void testSendReceiveWithBody(final int bodyLength) throws Exception { conn = cf.createConnection(); char[] chrs = new char[bodyLength]; - for (int i = 0; i < bodyLength; i++) - { + for (int i = 0; i < bodyLength; i++) { chrs[i] = RandomUtil.randomChar(); } String str = new String(chrs); @@ -184,55 +172,19 @@ public class TextMessageTest extends JMSTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); queue = createQueue("queue1"); } @Override protected void createCF(final List connectorConfigs, - final String... jndiBindings) throws Exception - { + final String... jndiBindings) throws Exception { int retryInterval = 1000; double retryIntervalMultiplier = 1.0; int reconnectAttempts = -1; int callTimeout = 30000; - jmsServer.createConnectionFactory("ManualReconnectionToSingleServerTest", - false, - JMSFactoryType.CF, - registerConnectors(server, connectorConfigs), - null, - ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, - ActiveMQClient.DEFAULT_CONNECTION_TTL, - callTimeout, - ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, - true, - ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES, - ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, - ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, - ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, - ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, - ActiveMQClient.DEFAULT_AUTO_GROUP, - ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, - ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, - retryInterval, - retryIntervalMultiplier, - ActiveMQClient.DEFAULT_MAX_RETRY_INTERVAL, - reconnectAttempts, - ActiveMQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION, - null, - jndiBindings); + jmsServer.createConnectionFactory("ManualReconnectionToSingleServerTest", false, JMSFactoryType.CF, registerConnectors(server, connectorConfigs), null, ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, ActiveMQClient.DEFAULT_CONNECTION_TTL, callTimeout, ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, true, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES, ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, ActiveMQClient.DEFAULT_AUTO_GROUP, ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, retryInterval, retryIntervalMultiplier, ActiveMQClient.DEFAULT_MAX_RETRY_INTERVAL, reconnectAttempts, ActiveMQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION, null, jndiBindings); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/TopicCleanupTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/TopicCleanupTest.java index ce0f77827a..10746800a4 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/TopicCleanupTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/client/TopicCleanupTest.java @@ -38,23 +38,18 @@ import org.junit.Test; * The server was then written to perform a cleanup, and that cleanup should always work. * This test will create the dirty situation where the test should recover from */ -public class TopicCleanupTest extends JMSTestBase -{ +public class TopicCleanupTest extends JMSTestBase { - protected boolean usePersistence() - { + protected boolean usePersistence() { return true; } @Test - public void testSendTopic() throws Exception - { + public void testSendTopic() throws Exception { Topic topic = createTopic("topic"); Connection conn = cf.createConnection(); - - try - { + try { conn.setClientID("someID"); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -75,13 +70,10 @@ public class TopicCleanupTest extends JMSTestBase StorageManager storage = server.getStorageManager(); - - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { long txid = storage.generateID(); - final Queue queue = new QueueImpl(storage.generateID(), SimpleString.toSimpleString("jms.topic.topic"), SimpleString.toSimpleString("jms.topic.topic"), FilterImpl.createFilter(ActiveMQServerImpl.GENERIC_IGNORED_FILTER), null, true, false, false, server.getScheduledPool(), server.getPostOffice(), - storage, server.getAddressSettingsRepository(), server.getExecutorFactory().getExecutor()); + final Queue queue = new QueueImpl(storage.generateID(), SimpleString.toSimpleString("jms.topic.topic"), SimpleString.toSimpleString("jms.topic.topic"), FilterImpl.createFilter(ActiveMQServerImpl.GENERIC_IGNORED_FILTER), null, true, false, false, server.getScheduledPool(), server.getPostOffice(), storage, server.getAddressSettingsRepository(), server.getExecutorFactory().getExecutor()); LocalQueueBinding binding = new LocalQueueBinding(queue.getAddress(), queue, server.getNodeID()); @@ -95,14 +87,11 @@ public class TopicCleanupTest extends JMSTestBase jmsServer.start(); } - finally - { - try - { + finally { + try { conn.close(); } - catch (Throwable igonred) - { + catch (Throwable igonred) { } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/BindingsClusterTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/BindingsClusterTest.java index bf14a50dab..29c0edc7fa 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/BindingsClusterTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/BindingsClusterTest.java @@ -46,24 +46,21 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @RunWith(value = Parameterized.class) -public class BindingsClusterTest extends JMSClusteredTestBase -{ +public class BindingsClusterTest extends JMSClusteredTestBase { + private final boolean crash; - public BindingsClusterTest(boolean crash) - { + public BindingsClusterTest(boolean crash) { this.crash = crash; } @Parameterized.Parameters(name = "crash={0}") - public static Collection getParameters() - { + public static Collection getParameters() { return Arrays.asList(new Object[][]{{true}, {false}}); } @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { //todo fix if needed super.setUp(); jmsServer1.getActiveMQServer().setIdentity("Server 1"); @@ -71,14 +68,12 @@ public class BindingsClusterTest extends JMSClusteredTestBase } @Override - protected boolean enablePersistence() - { + protected boolean enablePersistence() { return true; } @Test - public void testSendToSingleDisconnectedBinding() throws Exception - { + public void testSendToSingleDisconnectedBinding() throws Exception { Connection conn1 = cf1.createConnection(); conn1.setClientID("someClient1"); @@ -91,8 +86,7 @@ public class BindingsClusterTest extends JMSClusteredTestBase conn2.start(); - try - { + try { Topic topic1 = createTopic("t1", true); @@ -116,10 +110,8 @@ public class BindingsClusterTest extends JMSClusteredTestBase prod1.setDeliveryMode(DeliveryMode.PERSISTENT); - prod1.send(session1.createTextMessage("m1")); - printBindings(jmsServer1.getActiveMQServer(), "jms.topic.t1"); printBindings(jmsServer2.getActiveMQServer(), "jms.topic.t1"); @@ -138,8 +130,7 @@ public class BindingsClusterTest extends JMSClusteredTestBase prod1.send(session1.createTextMessage("m3")); - cf2 = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(InVMConnectorFactory.class.getName(), - generateInVMParams(2))); + cf2 = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(InVMConnectorFactory.class.getName(), generateInVMParams(2))); conn2 = cf2.createConnection(); @@ -171,8 +162,7 @@ public class BindingsClusterTest extends JMSClusteredTestBase cons2.close(); } - finally - { + finally { conn1.close(); conn2.close(); } @@ -182,8 +172,7 @@ public class BindingsClusterTest extends JMSClusteredTestBase } @Test - public void testSendToSingleDisconnectedBindingWhenLocalAvailable() throws Exception - { + public void testSendToSingleDisconnectedBindingWhenLocalAvailable() throws Exception { Connection conn1 = cf1.createConnection(); conn1.setClientID("someClient2"); @@ -196,8 +185,7 @@ public class BindingsClusterTest extends JMSClusteredTestBase conn2.start(); - try - { + try { Topic topic1 = createTopic("t1", true); @@ -223,10 +211,8 @@ public class BindingsClusterTest extends JMSClusteredTestBase prod1.setDeliveryMode(DeliveryMode.PERSISTENT); - prod1.send(session1.createTextMessage("m1")); - printBindings(jmsServer1.getActiveMQServer(), "jms.topic.t1"); printBindings(jmsServer2.getActiveMQServer(), "jms.topic.t1"); @@ -249,8 +235,7 @@ public class BindingsClusterTest extends JMSClusteredTestBase prod1.send(session1.createTextMessage("m5")); prod1.send(session1.createTextMessage("m6")); - cf2 = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(InVMConnectorFactory.class.getName(), - generateInVMParams(2))); + cf2 = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(InVMConnectorFactory.class.getName(), generateInVMParams(2))); conn2 = cf2.createConnection(); @@ -278,7 +263,6 @@ public class BindingsClusterTest extends JMSClusteredTestBase assertEquals("m2", received.getText()); - received = (TextMessage) cons1.receive(5000); assertNotNull(received); @@ -299,8 +283,7 @@ public class BindingsClusterTest extends JMSClusteredTestBase cons2.close(); } - finally - { + finally { conn1.close(); conn2.close(); } @@ -310,8 +293,7 @@ public class BindingsClusterTest extends JMSClusteredTestBase } @Test - public void testRemoteBindingRemovedOnReconnectLocalAvailable() throws Exception - { + public void testRemoteBindingRemovedOnReconnectLocalAvailable() throws Exception { Connection conn1 = cf1.createConnection(); conn1.setClientID("someClient2"); @@ -324,8 +306,7 @@ public class BindingsClusterTest extends JMSClusteredTestBase conn2.start(); - try - { + try { Topic topic1 = createTopic("t1", true); @@ -345,11 +326,9 @@ public class BindingsClusterTest extends JMSClusteredTestBase prod1.setDeliveryMode(DeliveryMode.PERSISTENT); - prod1.send(session1.createTextMessage("m1")); prod1.send(session1.createTextMessage("m2")); - printBindings(jmsServer1.getActiveMQServer(), "jms.topic.t1"); printBindings(jmsServer2.getActiveMQServer(), "jms.topic.t1"); @@ -387,7 +366,6 @@ public class BindingsClusterTest extends JMSClusteredTestBase assertEquals("m3", received.getText()); - received = (TextMessage) cons1.receive(5000); assertNotNull(received); @@ -414,8 +392,7 @@ public class BindingsClusterTest extends JMSClusteredTestBase cons2.close(); } - finally - { + finally { conn1.close(); conn2.close(); } @@ -424,29 +401,23 @@ public class BindingsClusterTest extends JMSClusteredTestBase jmsServer2.destroyTopic("t1"); } - private void crash() throws Exception - { - if (crash) - { + private void crash() throws Exception { + if (crash) { jmsServer2.stop(); } - else - { + else { final CountDownLatch latch = new CountDownLatch(1); ClusterConnectionImpl next = (ClusterConnectionImpl) server1.getClusterManager().getClusterConnections().iterator().next(); BridgeImpl bridge = (BridgeImpl) next.getRecords().values().iterator().next().getBridge(); RemotingConnection forwardingConnection = getForwardingConnection(bridge); - forwardingConnection.addFailureListener(new FailureListener() - { + forwardingConnection.addFailureListener(new FailureListener() { @Override - public void connectionFailed(ActiveMQException exception, boolean failedOver) - { + public void connectionFailed(ActiveMQException exception, boolean failedOver) { latch.countDown(); } @Override - public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) { connectionFailed(me, failedOver); } }); @@ -455,30 +426,24 @@ public class BindingsClusterTest extends JMSClusteredTestBase } } - private void restart() throws Exception - { - if (crash) - { + private void restart() throws Exception { + if (crash) { jmsServer2.start(); } } - private RemotingConnection getForwardingConnection(final Bridge bridge) throws Exception - { + private RemotingConnection getForwardingConnection(final Bridge bridge) throws Exception { long start = System.currentTimeMillis(); - do - { + do { RemotingConnection forwardingConnection = ((BridgeImpl) bridge).getForwardingConnection(); - if (forwardingConnection != null) - { + if (forwardingConnection != null) { return forwardingConnection; } Thread.sleep(10); - } - while (System.currentTimeMillis() - start < 50000); + } while (System.currentTimeMillis() - start < 50000); throw new IllegalStateException("Failed to get forwarding connection"); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/JMSFailoverListenerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/JMSFailoverListenerTest.java index e537610ff5..a4e867c86a 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/JMSFailoverListenerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/JMSFailoverListenerTest.java @@ -66,8 +66,8 @@ import java.util.Map; *
    * A simple test to test setFailoverListener when using the JMS API. */ -public class JMSFailoverListenerTest extends ActiveMQTestBase -{ +public class JMSFailoverListenerTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; // Constants ----------------------------------------------------- @@ -106,10 +106,8 @@ public class JMSFailoverListenerTest extends ActiveMQTestBase // Public -------------------------------------------------------- - @Test - public void testAutomaticFailover() throws Exception - { + public void testAutomaticFailover() throws Exception { ActiveMQConnectionFactory jbcf = ActiveMQJMSClient.createConnectionFactoryWithHA(JMSFactoryType.CF, livetc); jbcf.setReconnectAttempts(-1); jbcf.setBlockOnDurableSend(true); @@ -149,8 +147,7 @@ public class JMSFailoverListenerTest extends ActiveMQTestBase byte[] body = RandomUtil.randomBytes(bodySize); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { BytesMessage bm = sess.createBytesMessage(); bm.writeBytes(body); @@ -167,8 +164,7 @@ public class JMSFailoverListenerTest extends ActiveMQTestBase JMSUtil.crash(liveServer, ((ActiveMQSession) sess).getCoreSession()); Assert.assertEquals(FailoverEventType.FAILURE_DETECTED, listener.get(0)); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { JMSFailoverListenerTest.log.info("got message " + i); BytesMessage bm = (BytesMessage) consumer.receive(1000); @@ -188,19 +184,13 @@ public class JMSFailoverListenerTest extends ActiveMQTestBase } @Test - public void testManualFailover() throws Exception - { - ActiveMQConnectionFactory jbcfLive = - ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, - new TransportConfiguration(INVM_CONNECTOR_FACTORY)); + public void testManualFailover() throws Exception { + ActiveMQConnectionFactory jbcfLive = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); jbcfLive.setBlockOnNonDurableSend(true); jbcfLive.setBlockOnDurableSend(true); - ActiveMQConnectionFactory jbcfBackup = - ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, - new TransportConfiguration(INVM_CONNECTOR_FACTORY, - backupParams)); + ActiveMQConnectionFactory jbcfBackup = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY, backupParams)); jbcfBackup.setBlockOnNonDurableSend(true); jbcfBackup.setBlockOnDurableSend(true); jbcfBackup.setInitialConnectAttempts(-1); @@ -226,8 +216,7 @@ public class JMSFailoverListenerTest extends ActiveMQTestBase MessageProducer producerLive = sessLive.createProducer(queue); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage tm = sessLive.createTextMessage("message" + i); producerLive.send(tm); @@ -249,8 +238,7 @@ public class JMSFailoverListenerTest extends ActiveMQTestBase connBackup.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage tm = (TextMessage) consumerBackup.receive(1000); Assert.assertNotNull(tm); @@ -272,8 +260,7 @@ public class JMSFailoverListenerTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); startServers(); } @@ -281,8 +268,7 @@ public class JMSFailoverListenerTest extends ActiveMQTestBase /** * @throws Exception */ - protected void startServers() throws Exception - { + protected void startServers() throws Exception { NodeManager nodeManager = new InVMNodeManager(false); backuptc = new TransportConfiguration(INVM_CONNECTOR_FACTORY, backupParams); livetc = new TransportConfiguration(INVM_CONNECTOR_FACTORY); @@ -292,20 +278,7 @@ public class JMSFailoverListenerTest extends ActiveMQTestBase backupParams.put(TransportConstants.SERVER_ID_PROP_NAME, 1); - backupConf = createBasicConfig() - .addAcceptorConfiguration(backupAcceptortc) - .addConnectorConfiguration(livetc.getName(), livetc) - .addConnectorConfiguration(backuptc.getName(), backuptc) - .setJournalType(getDefaultJournalType()) - .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, backupParams)) - .setBindingsDirectory(getBindingsDir()) - .setJournalMinFiles(2) - .setJournalDirectory(getJournalDir()) - .setPagingDirectory(getPageDir()) - .setLargeMessagesDirectory(getLargeMessagesDir()) - .setPersistenceEnabled(true) - .setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration()) - .addClusterConfiguration(basicClusterConnectionConfig(backuptc.getName(), livetc.getName())); + backupConf = createBasicConfig().addAcceptorConfiguration(backupAcceptortc).addConnectorConfiguration(livetc.getName(), livetc).addConnectorConfiguration(backuptc.getName(), backuptc).setJournalType(getDefaultJournalType()).addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, backupParams)).setBindingsDirectory(getBindingsDir()).setJournalMinFiles(2).setJournalDirectory(getJournalDir()).setPagingDirectory(getPageDir()).setLargeMessagesDirectory(getLargeMessagesDir()).setPersistenceEnabled(true).setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration()).addClusterConfiguration(basicClusterConnectionConfig(backuptc.getName(), livetc.getName())); backupServer = addServer(new InVMNodeManagerServer(backupConf, nodeManager)); @@ -317,20 +290,7 @@ public class JMSFailoverListenerTest extends ActiveMQTestBase log.info("Starting backup"); backupJMSServer.start(); - liveConf = createBasicConfig() - .setJournalDirectory(getJournalDir()) - .setBindingsDirectory(getBindingsDir()) - .addAcceptorConfiguration(liveAcceptortc) - .setJournalType(getDefaultJournalType()) - .setBindingsDirectory(getBindingsDir()) - .setJournalMinFiles(2) - .setJournalDirectory(getJournalDir()) - .setPagingDirectory(getPageDir()) - .setLargeMessagesDirectory(getLargeMessagesDir()) - .addConnectorConfiguration(livetc.getName(), livetc) - .setPersistenceEnabled(true) - .setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration()) - .addClusterConfiguration(basicClusterConnectionConfig(livetc.getName())); + liveConf = createBasicConfig().setJournalDirectory(getJournalDir()).setBindingsDirectory(getBindingsDir()).addAcceptorConfiguration(liveAcceptortc).setJournalType(getDefaultJournalType()).setBindingsDirectory(getBindingsDir()).setJournalMinFiles(2).setJournalDirectory(getJournalDir()).setPagingDirectory(getPageDir()).setLargeMessagesDirectory(getLargeMessagesDir()).addConnectorConfiguration(livetc.getName(), livetc).setPersistenceEnabled(true).setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration()).addClusterConfiguration(basicClusterConnectionConfig(livetc.getName())); liveServer = addServer(new InVMNodeManagerServer(liveConf, nodeManager)); @@ -350,34 +310,26 @@ public class JMSFailoverListenerTest extends ActiveMQTestBase // Inner classes ------------------------------------------------- + private static class MyFailoverListener implements FailoverEventListener { - private static class MyFailoverListener implements FailoverEventListener - { private List eventTypeList = Collections.synchronizedList(new ArrayList()); - - public FailoverEventType get(int element) - { + public FailoverEventType get(int element) { waitForElements(element + 1); return eventTypeList.get(element); } - public int size() - { + public int size() { return eventTypeList.size(); } - private void waitForElements(int elements) - { + private void waitForElements(int elements) { long timeout = System.currentTimeMillis() + 5000; - while (timeout > System.currentTimeMillis() && eventTypeList.size() < elements) - { - try - { + while (timeout > System.currentTimeMillis() && eventTypeList.size() < elements) { + try { Thread.sleep(1); } - catch (Throwable e) - { + catch (Throwable e) { fail(e.getMessage()); } } @@ -385,8 +337,7 @@ public class JMSFailoverListenerTest extends ActiveMQTestBase Assert.assertTrue(eventTypeList.size() >= elements); } - public void failoverEvent(FailoverEventType eventType) - { + public void failoverEvent(FailoverEventType eventType) { eventTypeList.add(eventType); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/JMSFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/JMSFailoverTest.java index d96041a387..cf0502d5b3 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/JMSFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/JMSFailoverTest.java @@ -74,8 +74,8 @@ import java.util.concurrent.atomic.AtomicBoolean; * A simple test to test failover when using the JMS API. * Most of the failover tests are done on the Core API. */ -public class JMSFailoverTest extends ActiveMQTestBase -{ +public class JMSFailoverTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; // Constants ----------------------------------------------------- @@ -115,8 +115,7 @@ public class JMSFailoverTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testCreateQueue() throws Exception - { + public void testCreateQueue() throws Exception { liveJMSServer.createQueue(true, "queue1", null, true, "/queue/queue1"); assertNotNull(ctx1.lookup("/queue/queue1")); @@ -126,8 +125,7 @@ public class JMSFailoverTest extends ActiveMQTestBase Connection conn = null; - try - { + try { conn = JMSUtil.createConnectionAndWaitForTopology(jbcf, 2, 5); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -138,18 +136,15 @@ public class JMSFailoverTest extends ActiveMQTestBase assertNotNull(ctx2.lookup("/queue/queue1")); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testCreateTopic() throws Exception - { + public void testCreateTopic() throws Exception { liveJMSServer.createTopic(true, "topic", "/topic/t1"); assertNotNull(ctx1.lookup("//topic/t1")); @@ -159,8 +154,7 @@ public class JMSFailoverTest extends ActiveMQTestBase Connection conn = null; - try - { + try { conn = JMSUtil.createConnectionAndWaitForTopology(jbcf, 2, 5); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -171,18 +165,15 @@ public class JMSFailoverTest extends ActiveMQTestBase assertNotNull(ctx2.lookup("/topic/t1")); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testAutomaticFailover() throws Exception - { + public void testAutomaticFailover() throws Exception { ActiveMQConnectionFactory jbcf = ActiveMQJMSClient.createConnectionFactoryWithHA(JMSFactoryType.CF, livetc); jbcf.setReconnectAttempts(-1); jbcf.setBlockOnDurableSend(true); @@ -222,8 +213,7 @@ public class JMSFailoverTest extends ActiveMQTestBase byte[] body = RandomUtil.randomBytes(bodySize); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { BytesMessage bm = sess.createBytesMessage(); bm.writeBytes(body); @@ -239,8 +229,7 @@ public class JMSFailoverTest extends ActiveMQTestBase JMSUtil.crash(liveServer, ((ActiveMQSession) sess).getCoreSession()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { JMSFailoverTest.log.info("got message " + i); BytesMessage bm = (BytesMessage) consumer.receive(1000); @@ -259,19 +248,13 @@ public class JMSFailoverTest extends ActiveMQTestBase } @Test - public void testManualFailover() throws Exception - { - ActiveMQConnectionFactory jbcfLive = - ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, - new TransportConfiguration(INVM_CONNECTOR_FACTORY)); + public void testManualFailover() throws Exception { + ActiveMQConnectionFactory jbcfLive = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); jbcfLive.setBlockOnNonDurableSend(true); jbcfLive.setBlockOnDurableSend(true); - ActiveMQConnectionFactory jbcfBackup = - ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, - new TransportConfiguration(INVM_CONNECTOR_FACTORY, - backupParams)); + ActiveMQConnectionFactory jbcfBackup = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY, backupParams)); jbcfBackup.setBlockOnNonDurableSend(true); jbcfBackup.setBlockOnDurableSend(true); jbcfBackup.setInitialConnectAttempts(-1); @@ -299,8 +282,7 @@ public class JMSFailoverTest extends ActiveMQTestBase MessageProducer producerLive = sessLive.createProducer(queue); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage tm = sessLive.createTextMessage("message" + i); producerLive.send(tm); @@ -322,8 +304,7 @@ public class JMSFailoverTest extends ActiveMQTestBase connBackup.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage tm = (TextMessage) consumerBackup.receive(1000); Assert.assertNotNull(tm); @@ -338,10 +319,8 @@ public class JMSFailoverTest extends ActiveMQTestBase connBackup.close(); } - @Test - public void testSendReceiveLargeMessages() throws Exception - { + public void testSendReceiveLargeMessages() throws Exception { SimpleString QUEUE = new SimpleString("jms.queue.somequeue"); ActiveMQConnectionFactory jbcf = ActiveMQJMSClient.createConnectionFactoryWithHA(JMSFactoryType.CF, livetc, backuptc); @@ -352,25 +331,20 @@ public class JMSFailoverTest extends ActiveMQTestBase //jbcf.setConsumerWindowSize(0); //jbcf.setMinLargeMessageSize(1024); - final CountDownLatch flagAlign = new CountDownLatch(1); final CountDownLatch waitToKill = new CountDownLatch(1); final AtomicBoolean killed = new AtomicBoolean(false); - jbcf.getServerLocator().addIncomingInterceptor(new Interceptor() - { + jbcf.getServerLocator().addIncomingInterceptor(new Interceptor() { int count = 0; @Override - public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException - { + public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException { - if (packet instanceof SessionReceiveContinuationMessage) - { - if (count++ == 300 && !killed.get()) - { + if (packet instanceof SessionReceiveContinuationMessage) { + if (count++ == 300 && !killed.get()) { System.out.println("sending countDown on latch waitToKill"); killed.set(true); waitToKill.countDown(); @@ -380,36 +354,28 @@ public class JMSFailoverTest extends ActiveMQTestBase } }); - Connection conn = JMSUtil.createConnectionAndWaitForTopology(jbcf, 2, 5); Session sess = conn.createSession(true, Session.SESSION_TRANSACTED); final ClientSession coreSession = ((ActiveMQSession) sess).getCoreSession(); - // The thread that will fail the server - Thread spoilerThread = new Thread() - { - public void run() - { + Thread spoilerThread = new Thread() { + public void run() { flagAlign.countDown(); // a large timeout just to help in case of debugging - try - { + try { waitToKill.await(120, TimeUnit.SECONDS); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } - try - { + try { System.out.println("Killing server..."); JMSUtil.crash(liveServer, coreSession); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -422,13 +388,11 @@ public class JMSFailoverTest extends ActiveMQTestBase MessageProducer producer = sess.createProducer(queue); producer.setDeliveryMode(DeliveryMode.PERSISTENT); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { TextMessage message = sess.createTextMessage(new String(new byte[10 * 1024])); producer.send(message); - if (i % 10 == 0) - { + if (i % 10 == 0) { sess.commit(); } } @@ -441,63 +405,51 @@ public class JMSFailoverTest extends ActiveMQTestBase assertTrue(flagAlign.await(10, TimeUnit.SECONDS)); - MessageConsumer consumer = sess.createConsumer(queue); // We won't receive the whole thing here.. we just want to validate if message will arrive or not... // this test is not meant to validate transactionality during Failover as that would require XA and recovery - for (int i = 0; i < 90; i++) - { + for (int i = 0; i < 90; i++) { TextMessage message = null; int retryNrs = 0; - do - { + do { retryNrs++; - try - { + try { message = (TextMessage) consumer.receive(5000); assertNotNull(message); break; } - catch (JMSException e) - { + catch (JMSException e) { new Exception("Exception on receive message", e).printStackTrace(); } } while (retryNrs < 10); assertNotNull(message); - try - { + try { sess.commit(); } - catch (Exception e) - { + catch (Exception e) { new Exception("Exception during commit", e); sess.rollback(); } } - conn.close(); - spoilerThread.join(); - } - // Package protected --------------------------------------------- // Protected ----------------------------------------------------- @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); startServers(); } @@ -505,8 +457,7 @@ public class JMSFailoverTest extends ActiveMQTestBase /** * @throws Exception */ - protected void startServers() throws Exception - { + protected void startServers() throws Exception { final boolean sharedStore = true; NodeManager nodeManager = new InVMNodeManager(!sharedStore); backuptc = new TransportConfiguration(INVM_CONNECTOR_FACTORY, backupParams); @@ -518,21 +469,7 @@ public class JMSFailoverTest extends ActiveMQTestBase backupParams.put(TransportConstants.SERVER_ID_PROP_NAME, 1); - backupConf = createBasicConfig() - .addAcceptorConfiguration(backupAcceptortc) - .addConnectorConfiguration(livetc.getName(), livetc) - .addConnectorConfiguration(backuptc.getName(), backuptc) - .setSecurityEnabled(false) - .setJournalType(getDefaultJournalType()) - .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, backupParams)) - .setBindingsDirectory(getBindingsDir()) - .setJournalMinFiles(2) - .setJournalDirectory(getJournalDir()) - .setPagingDirectory(getPageDir()) - .setLargeMessagesDirectory(getLargeMessagesDir()) - .setPersistenceEnabled(true) - .setHAPolicyConfiguration(sharedStore ? new SharedStoreSlavePolicyConfiguration() : new ReplicaPolicyConfiguration()) - .addClusterConfiguration(basicClusterConnectionConfig(backuptc.getName(), livetc.getName())); + backupConf = createBasicConfig().addAcceptorConfiguration(backupAcceptortc).addConnectorConfiguration(livetc.getName(), livetc).addConnectorConfiguration(backuptc.getName(), backuptc).setSecurityEnabled(false).setJournalType(getDefaultJournalType()).addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, backupParams)).setBindingsDirectory(getBindingsDir()).setJournalMinFiles(2).setJournalDirectory(getJournalDir()).setPagingDirectory(getPageDir()).setLargeMessagesDirectory(getLargeMessagesDir()).setPersistenceEnabled(true).setHAPolicyConfiguration(sharedStore ? new SharedStoreSlavePolicyConfiguration() : new ReplicaPolicyConfiguration()).addClusterConfiguration(basicClusterConnectionConfig(backuptc.getName(), livetc.getName())); backupServer = addServer(new InVMNodeManagerServer(backupConf, nodeManager)); @@ -544,21 +481,7 @@ public class JMSFailoverTest extends ActiveMQTestBase log.info("Starting backup"); backupJMSServer.start(); - liveConf = createBasicConfig() - .setJournalDirectory(getJournalDir()) - .setBindingsDirectory(getBindingsDir()) - .setSecurityEnabled(false) - .addAcceptorConfiguration(liveAcceptortc) - .setJournalType(getDefaultJournalType()) - .setBindingsDirectory(getBindingsDir()) - .setJournalMinFiles(2) - .setJournalDirectory(getJournalDir()) - .setPagingDirectory(getPageDir()) - .setLargeMessagesDirectory(getLargeMessagesDir()) - .addConnectorConfiguration(livetc.getName(), livetc) - .setPersistenceEnabled(true) - .setHAPolicyConfiguration(sharedStore ? new SharedStoreMasterPolicyConfiguration() : new ReplicatedPolicyConfiguration()) - .addClusterConfiguration(basicClusterConnectionConfig(livetc.getName())); + liveConf = createBasicConfig().setJournalDirectory(getJournalDir()).setBindingsDirectory(getBindingsDir()).setSecurityEnabled(false).addAcceptorConfiguration(liveAcceptortc).setJournalType(getDefaultJournalType()).setBindingsDirectory(getBindingsDir()).setJournalMinFiles(2).setJournalDirectory(getJournalDir()).setPagingDirectory(getPageDir()).setLargeMessagesDirectory(getLargeMessagesDir()).addConnectorConfiguration(livetc.getName(), livetc).setPersistenceEnabled(true).setHAPolicyConfiguration(sharedStore ? new SharedStoreMasterPolicyConfiguration() : new ReplicatedPolicyConfiguration()).addClusterConfiguration(basicClusterConnectionConfig(livetc.getName())); liveServer = addServer(new InVMNodeManagerServer(liveConf, nodeManager)); @@ -578,12 +501,11 @@ public class JMSFailoverTest extends ActiveMQTestBase // Inner classes ------------------------------------------------- - private static class MyExceptionListener implements ExceptionListener - { + private static class MyExceptionListener implements ExceptionListener { + volatile JMSException e; - public void onException(final JMSException e) - { + public void onException(final JMSException e) { this.e = e; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/JMSReconnectTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/JMSReconnectTest.java index 76809b1418..3c429d9edf 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/JMSReconnectTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/JMSReconnectTest.java @@ -49,27 +49,23 @@ import javax.jms.Session; import javax.jms.TextMessage; import javax.jms.Topic; -public class JMSReconnectTest extends ActiveMQTestBase -{ +public class JMSReconnectTest extends ActiveMQTestBase { private ActiveMQServer server; //In this test we re-attach to the same node without restarting the server @Test - public void testReattachSameNode() throws Exception - { + public void testReattachSameNode() throws Exception { testReconnectOrReattachSameNode(true); } //In this test, we reconnect to the same node without restarting the server @Test - public void testReconnectSameNode() throws Exception - { + public void testReconnectSameNode() throws Exception { testReconnectOrReattachSameNode(false); } - private void testReconnectOrReattachSameNode(boolean reattach) throws Exception - { + private void testReconnectOrReattachSameNode(boolean reattach) throws Exception { ActiveMQConnectionFactory jbcf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); jbcf.setBlockOnDurableSend(true); @@ -77,8 +73,7 @@ public class JMSReconnectTest extends ActiveMQTestBase jbcf.setReconnectAttempts(-1); - if (reattach) - { + if (reattach) { jbcf.setConfirmationWindowSize(1024 * 1024); } @@ -100,9 +95,9 @@ public class JMSReconnectTest extends ActiveMQTestBase Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - ClientSession coreSession = ((ActiveMQSession)sess).getCoreSession(); + ClientSession coreSession = ((ActiveMQSession) sess).getCoreSession(); - RemotingConnection coreConn = ((ClientSessionInternal)coreSession).getConnection(); + RemotingConnection coreConn = ((ClientSessionInternal) coreSession).getConnection(); SimpleString jmsQueueName = new SimpleString(ActiveMQDestination.JMS_QUEUE_ADDRESS_PREFIX + "myqueue"); @@ -118,8 +113,7 @@ public class JMSReconnectTest extends ActiveMQTestBase byte[] body = RandomUtil.randomBytes(bodySize); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { BytesMessage bm = sess.createBytesMessage(); bm.writeBytes(body); @@ -137,43 +131,37 @@ public class JMSReconnectTest extends ActiveMQTestBase //It should reconnect to the same node - for (int i = 0; i < numMessages; i++) - { - BytesMessage bm = (BytesMessage)consumer.receive(1000); + for (int i = 0; i < numMessages; i++) { + BytesMessage bm = (BytesMessage) consumer.receive(1000); Assert.assertNotNull(bm); Assert.assertEquals(body.length, bm.getBodyLength()); } - TextMessage tm = (TextMessage)consumer.receiveNoWait(); + TextMessage tm = (TextMessage) consumer.receiveNoWait(); Assert.assertNull(tm); conn.close(); - - Assert.assertNotNull(listener.e); Assert.assertTrue(me == listener.e.getCause()); } @Test - public void testReconnectSameNodeServerRestartedWithNonDurableSub() throws Exception - { + public void testReconnectSameNodeServerRestartedWithNonDurableSub() throws Exception { testReconnectSameNodeServerRestartedWithNonDurableSubOrTempQueue(true); } @Test - public void testReconnectSameNodeServerRestartedWithTempQueue() throws Exception - { + public void testReconnectSameNodeServerRestartedWithTempQueue() throws Exception { testReconnectSameNodeServerRestartedWithNonDurableSubOrTempQueue(false); } //Test that non durable JMS sub gets recreated in auto reconnect - private void testReconnectSameNodeServerRestartedWithNonDurableSubOrTempQueue(final boolean nonDurableSub) throws Exception - { + private void testReconnectSameNodeServerRestartedWithNonDurableSubOrTempQueue(final boolean nonDurableSub) throws Exception { ActiveMQConnectionFactory jbcf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); jbcf.setReconnectAttempts(-1); @@ -186,18 +174,16 @@ public class JMSReconnectTest extends ActiveMQTestBase Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - ClientSession coreSession = ((ActiveMQSession)sess).getCoreSession(); + ClientSession coreSession = ((ActiveMQSession) sess).getCoreSession(); Destination dest; - if (nonDurableSub) - { + if (nonDurableSub) { coreSession.createQueue(ActiveMQDestination.JMS_TOPIC_ADDRESS_PREFIX + "mytopic", "blahblah", null, false); dest = ActiveMQJMSClient.createTopic("mytopic"); } - else - { + else { dest = sess.createTemporaryQueue(); } @@ -217,8 +203,7 @@ public class JMSReconnectTest extends ActiveMQTestBase byte[] body = RandomUtil.randomBytes(1000); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { BytesMessage bm = sess.createBytesMessage(); bm.writeBytes(body); @@ -228,16 +213,15 @@ public class JMSReconnectTest extends ActiveMQTestBase conn.start(); - for (int i = 0; i < numMessages; i++) - { - BytesMessage bm = (BytesMessage)consumer.receive(1000); + for (int i = 0; i < numMessages; i++) { + BytesMessage bm = (BytesMessage) consumer.receive(1000); Assert.assertNotNull(bm); Assert.assertEquals(body.length, bm.getBodyLength()); } - TextMessage tm = (TextMessage)consumer.receiveNoWait(); + TextMessage tm = (TextMessage) consumer.receiveNoWait(); Assert.assertNull(tm); @@ -248,8 +232,7 @@ public class JMSReconnectTest extends ActiveMQTestBase //If the server is shutdown after a non durable sub is created, then close on the connection should proceed normally @Test - public void testNoReconnectCloseAfterFailToReconnectWithTopicConsumer() throws Exception - { + public void testNoReconnectCloseAfterFailToReconnectWithTopicConsumer() throws Exception { ActiveMQConnectionFactory jbcf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); jbcf.setReconnectAttempts(0); @@ -258,7 +241,7 @@ public class JMSReconnectTest extends ActiveMQTestBase Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - ClientSession coreSession = ((ActiveMQSession)sess).getCoreSession(); + ClientSession coreSession = ((ActiveMQSession) sess).getCoreSession(); coreSession.createQueue(ActiveMQDestination.JMS_TOPIC_ADDRESS_PREFIX + "mytopic", "blahblah", null, false); @@ -280,8 +263,7 @@ public class JMSReconnectTest extends ActiveMQTestBase //If server is shutdown, and then connection is closed, after a temp queue has been created, the close should complete normally @Test - public void testNoReconnectCloseAfterFailToReconnectWithTempQueue() throws Exception - { + public void testNoReconnectCloseAfterFailToReconnectWithTempQueue() throws Exception { ActiveMQConnectionFactory jbcf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); jbcf.setReconnectAttempts(0); @@ -303,15 +285,13 @@ public class JMSReconnectTest extends ActiveMQTestBase conn.close(); } - // Package protected --------------------------------------------- // Protected ----------------------------------------------------- @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = addServer(ActiveMQServers.newActiveMQServer(createDefaultInVMConfig(), true)); @@ -322,12 +302,11 @@ public class JMSReconnectTest extends ActiveMQTestBase // Inner classes ------------------------------------------------- - private static class MyExceptionListener implements ExceptionListener - { + private static class MyExceptionListener implements ExceptionListener { + volatile JMSException e; - public void onException(final JMSException e) - { + public void onException(final JMSException e) { this.e = e; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/LargeMessageOverBridgeTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/LargeMessageOverBridgeTest.java index 839752975e..1c7bf20bc5 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/LargeMessageOverBridgeTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/LargeMessageOverBridgeTest.java @@ -40,36 +40,28 @@ import java.util.Arrays; import java.util.Collection; @RunWith(value = Parameterized.class) -public class LargeMessageOverBridgeTest extends JMSClusteredTestBase -{ +public class LargeMessageOverBridgeTest extends JMSClusteredTestBase { private final boolean persistent; @Override - protected boolean enablePersistence() - { + protected boolean enablePersistence() { return persistent; } @Parameterized.Parameters(name = "persistent={0}") - public static Collection getParameters() - { - return Arrays.asList(new Object[][]{ - {true}, - {false} - }); + public static Collection getParameters() { + return Arrays.asList(new Object[][]{{true}, {false}}); } @Override - protected final ConfigurationImpl createBasicConfig(final int serverID) - { + protected final ConfigurationImpl createBasicConfig(final int serverID) { ConfigurationImpl configuration = super.createBasicConfig(serverID); configuration.setJournalFileSize(1024 * 1024); return configuration; } - public LargeMessageOverBridgeTest(boolean persistent) - { + public LargeMessageOverBridgeTest(boolean persistent) { this.persistent = persistent; } @@ -79,8 +71,7 @@ public class LargeMessageOverBridgeTest extends JMSClusteredTestBase * @throws Exception */ @Test - public void testSendHalfLargeTextMessage() throws Exception - { + public void testSendHalfLargeTextMessage() throws Exception { createQueue("Q1"); Queue queue = (Queue) context1.lookup("queue/Q1"); @@ -95,13 +86,11 @@ public class LargeMessageOverBridgeTest extends JMSClusteredTestBase StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < 51180; i++) - { + for (int i = 0; i < 51180; i++) { buffer.append('a'); } - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { TextMessage msg = session1.createTextMessage(buffer.toString()); prod1.send(msg); } @@ -122,11 +111,10 @@ public class LargeMessageOverBridgeTest extends JMSClusteredTestBase * @throws Exception */ @Test - public void testSendMapMessageOverCluster() throws Exception - { + public void testSendMapMessageOverCluster() throws Exception { createQueue("Q1"); - Queue queue = (Queue)context1.lookup("queue/Q1"); + Queue queue = (Queue) context1.lookup("queue/Q1"); Connection conn1 = cf1.createConnection(); Session session1 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod1 = session1.createProducer(queue); @@ -138,24 +126,21 @@ public class LargeMessageOverBridgeTest extends JMSClusteredTestBase StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < 3810002; i++) - { + for (int i = 0; i < 3810002; i++) { buffer.append('a'); } final int NUMBER_OF_MESSAGES = 1; - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { MapMessage msg = session1.createMapMessage(); msg.setString("str", buffer.toString()); msg.setIntProperty("i", i); prod1.send(msg); } - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { - MapMessage msg = (MapMessage)cons2.receive(5000); + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { + MapMessage msg = (MapMessage) cons2.receive(5000); assertEquals(buffer.toString(), msg.getString("str")); } @@ -166,25 +151,20 @@ public class LargeMessageOverBridgeTest extends JMSClusteredTestBase } - /** * the hack to create the failing condition in certain tests * * @param config */ - private void installHack(Configuration config) - { - if (this.getName().equals("testSendBytesAsLargeOnBridgeOnly")) - { - for (ClusterConnectionConfiguration conn : config.getClusterConfigurations()) - { + private void installHack(Configuration config) { + if (this.getName().equals("testSendBytesAsLargeOnBridgeOnly")) { + for (ClusterConnectionConfiguration conn : config.getClusterConfigurations()) { conn.setMinLargeMessageSize(1000); } } } - protected Configuration createConfigServer(final int source, final int destination) throws Exception - { + protected Configuration createConfigServer(final int source, final int destination) throws Exception { Configuration config = super.createConfigServer(source, destination); installHack(config); @@ -192,18 +172,15 @@ public class LargeMessageOverBridgeTest extends JMSClusteredTestBase return config; } - /** * This was causing a text message to ber eventually converted into large message when sent over the bridge * * @throws Exception */ @Test - public void testSendBytesAsLargeOnBridgeOnly() throws Exception - { + public void testSendBytesAsLargeOnBridgeOnly() throws Exception { createQueue("Q1"); - Queue queue = (Queue) context1.lookup("queue/Q1"); Connection conn1 = cf1.createConnection(); Session session1 = conn1.createSession(true, Session.SESSION_TRANSACTED); @@ -216,13 +193,11 @@ public class LargeMessageOverBridgeTest extends JMSClusteredTestBase byte[] bytes = new byte[10 * 1024]; - for (int i = 0; i < bytes.length; i++) - { + for (int i = 0; i < bytes.length; i++) { bytes[i] = getSamplebyte(i); } - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { BytesMessage msg = session1.createBytesMessage(); msg.writeBytes(bytes); prod1.send(msg); @@ -230,15 +205,12 @@ public class LargeMessageOverBridgeTest extends JMSClusteredTestBase session1.commit(); - - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { BytesMessage msg2 = (BytesMessage) cons2.receive(5000); assertNotNull(msg2); msg2.acknowledge(); - for (int j = 0; j < bytes.length; j++) - { + for (int j = 0; j < bytes.length; j++) { assertEquals("Position " + i, msg2.readByte(), bytes[j]); } } @@ -253,14 +225,11 @@ public class LargeMessageOverBridgeTest extends JMSClusteredTestBase * @throws Exception */ @Test - public void testSendLargeForBridge() throws Exception - { + public void testSendLargeForBridge() throws Exception { createQueue("Q1"); - Queue queue = (Queue) context1.lookup("queue/Q1"); - ActiveMQConnectionFactory cf1 = ActiveMQJMSClient.createConnectionFactoryWithHA(JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY, generateInVMParams(1))); cf1.setMinLargeMessageSize(200 * 1024); @@ -275,13 +244,11 @@ public class LargeMessageOverBridgeTest extends JMSClusteredTestBase byte[] bytes = new byte[150 * 1024]; - for (int i = 0; i < bytes.length; i++) - { + for (int i = 0; i < bytes.length; i++) { bytes[i] = getSamplebyte(i); } - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { BytesMessage msg = session1.createBytesMessage(); msg.writeBytes(bytes); prod1.send(msg); @@ -289,15 +256,12 @@ public class LargeMessageOverBridgeTest extends JMSClusteredTestBase session1.commit(); - - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { BytesMessage msg2 = (BytesMessage) cons2.receive(5000); assertNotNull(msg2); msg2.acknowledge(); - for (int j = 0; j < bytes.length; j++) - { + for (int j = 0; j < bytes.length; j++) { assertEquals("Position " + i, msg2.readByte(), bytes[j]); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/MultipleThreadsOpeningTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/MultipleThreadsOpeningTest.java index cb186f8fd7..47669daf2d 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/MultipleThreadsOpeningTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/MultipleThreadsOpeningTest.java @@ -27,14 +27,11 @@ import org.apache.activemq.artemis.tests.util.JMSClusteredTestBase; import org.apache.activemq.artemis.core.remoting.impl.invm.InVMConnectorFactory; import org.junit.Test; -public class MultipleThreadsOpeningTest extends JMSClusteredTestBase -{ +public class MultipleThreadsOpeningTest extends JMSClusteredTestBase { @Test - public void testMultipleOpen() throws Exception - { - cf1 = ActiveMQJMSClient.createConnectionFactoryWithHA(JMSFactoryType.CF, new TransportConfiguration(InVMConnectorFactory.class.getName(), - generateInVMParams(1))); + public void testMultipleOpen() throws Exception { + cf1 = ActiveMQJMSClient.createConnectionFactoryWithHA(JMSFactoryType.CF, new TransportConfiguration(InVMConnectorFactory.class.getName(), generateInVMParams(1))); final int numberOfOpens = 2000; int numberOfThreads = 20; @@ -42,40 +39,35 @@ public class MultipleThreadsOpeningTest extends JMSClusteredTestBase final CountDownLatch flagAlignSemaphore = new CountDownLatch(numberOfThreads); final CountDownLatch flagStartRace = new CountDownLatch(1); - class ThreadOpen extends Thread - { + class ThreadOpen extends Thread { + int errors = 0; - public void run() - { + public void run() { - try - { + try { flagAlignSemaphore.countDown(); flagStartRace.await(); - for (int i = 0; i < numberOfOpens; i++) - { - if (i % 1000 == 0) System.out.println("tests " + i); + for (int i = 0; i < numberOfOpens; i++) { + if (i % 1000 == 0) + System.out.println("tests " + i); Connection conn = cf1.createConnection(); Session sess = conn.createSession(true, Session.AUTO_ACKNOWLEDGE); sess.close(); conn.close(); } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); errors++; } } } - ThreadOpen[] threads = new ThreadOpen[numberOfThreads]; - for (int i = 0; i < numberOfThreads; i++) - { + for (int i = 0; i < numberOfThreads; i++) { threads[i] = new ThreadOpen(); threads[i].start(); } @@ -83,9 +75,7 @@ public class MultipleThreadsOpeningTest extends JMSClusteredTestBase flagAlignSemaphore.await(); flagStartRace.countDown(); - - for (ThreadOpen t : threads) - { + for (ThreadOpen t : threads) { // 5 minutes seems long but this may take a bit of time in a slower box t.join(300000); assertFalse(t.isAlive()); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/ReplicatedJMSFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/ReplicatedJMSFailoverTest.java index 128f02f1dd..0f55271f4c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/ReplicatedJMSFailoverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/ReplicatedJMSFailoverTest.java @@ -24,26 +24,16 @@ import org.apache.activemq.artemis.core.remoting.impl.invm.TransportConstants; import org.apache.activemq.artemis.core.server.ActiveMQServers; import org.apache.activemq.artemis.jms.server.impl.JMSServerManagerImpl; -public class ReplicatedJMSFailoverTest extends JMSFailoverTest -{ +public class ReplicatedJMSFailoverTest extends JMSFailoverTest { /** * @throws Exception */ @Override - protected void startServers() throws Exception - { + protected void startServers() throws Exception { backupParams.put(TransportConstants.SERVER_ID_PROP_NAME, 1); - backupConf = createBasicConfig() - .setJournalType(getDefaultJournalType()) - .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, backupParams)) - .setBindingsDirectory(getBindingsDir(0, true)) - .setJournalMinFiles(2) - .setJournalDirectory(getJournalDir(0, true)) - .setPagingDirectory(getPageDir(0, true)) - .setLargeMessagesDirectory(getLargeMessagesDir(0, true)) - .setHAPolicyConfiguration(new ReplicaPolicyConfiguration()); + backupConf = createBasicConfig().setJournalType(getDefaultJournalType()).addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, backupParams)).setBindingsDirectory(getBindingsDir(0, true)).setJournalMinFiles(2).setJournalDirectory(getJournalDir(0, true)).setPagingDirectory(getPageDir(0, true)).setLargeMessagesDirectory(getLargeMessagesDir(0, true)).setHAPolicyConfiguration(new ReplicaPolicyConfiguration()); backupServer = addServer(ActiveMQServers.newActiveMQServer(backupConf, true)); @@ -53,16 +43,7 @@ public class ReplicatedJMSFailoverTest extends JMSFailoverTest backupJMSServer.start(); - liveConf = createBasicConfig() - .setJournalType(getDefaultJournalType()) - .addConnectorConfiguration("toBackup", new TransportConfiguration(INVM_CONNECTOR_FACTORY, backupParams)) - .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY)) - .setBindingsDirectory(getBindingsDir(0, false)) - .setJournalMinFiles(2) - .setJournalDirectory(getJournalDir(0, false)) - .setPagingDirectory(getPageDir(0, false)) - .setLargeMessagesDirectory(getLargeMessagesDir(0, false)) - .setHAPolicyConfiguration(new ReplicatedPolicyConfiguration()); + liveConf = createBasicConfig().setJournalType(getDefaultJournalType()).addConnectorConfiguration("toBackup", new TransportConfiguration(INVM_CONNECTOR_FACTORY, backupParams)).addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY)).setBindingsDirectory(getBindingsDir(0, false)).setJournalMinFiles(2).setJournalDirectory(getJournalDir(0, false)).setPagingDirectory(getPageDir(0, false)).setLargeMessagesDirectory(getLargeMessagesDir(0, false)).setHAPolicyConfiguration(new ReplicatedPolicyConfiguration()); liveServer = addServer(ActiveMQServers.newActiveMQServer(liveConf, true)); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/TemporaryQueueClusterTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/TemporaryQueueClusterTest.java index 4b2d861619..6f2c68a4aa 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/TemporaryQueueClusterTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/TemporaryQueueClusterTest.java @@ -26,8 +26,7 @@ import javax.jms.Queue; import javax.jms.Session; import javax.jms.TextMessage; -public class TemporaryQueueClusterTest extends JMSClusteredTestBase -{ +public class TemporaryQueueClusterTest extends JMSClusteredTestBase { // Constants ----------------------------------------------------- @@ -40,8 +39,7 @@ public class TemporaryQueueClusterTest extends JMSClusteredTestBase // Public -------------------------------------------------------- @Test - public void testClusteredQueue() throws Exception - { + public void testClusteredQueue() throws Exception { System.out.println("Server1 = " + server1.getNodeID()); System.out.println("Server2 = " + server2.getNodeID()); jmsServer1.createQueue(false, "target", null, true, "/queue/target"); @@ -54,8 +52,7 @@ public class TemporaryQueueClusterTest extends JMSClusteredTestBase conn2.start(); - try - { + try { Session session1 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue targetQueue1 = session1.createQueue("target"); @@ -73,23 +70,20 @@ public class TemporaryQueueClusterTest extends JMSClusteredTestBase prod1.send(msg); - TextMessage msgReceived = (TextMessage)cons2.receive(5000); + TextMessage msgReceived = (TextMessage) cons2.receive(5000); assertNotNull(msgReceived); assertEquals(msgReceived.getText(), msg.getText()); } - finally - { + finally { conn1.close(); conn2.close(); } } - @Test - public void testTemporaryQueue() throws Exception - { + public void testTemporaryQueue() throws Exception { jmsServer1.createQueue(false, "target", null, false, "/queue/target"); jmsServer2.createQueue(false, "target", null, false, "/queue/target"); @@ -99,8 +93,7 @@ public class TemporaryQueueClusterTest extends JMSClusteredTestBase conn1.start(); conn2.start(); - try - { + try { Session session1 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue targetQueue1 = session1.createQueue("target"); Queue tempQueue = session1.createTemporaryQueue(); @@ -114,18 +107,15 @@ public class TemporaryQueueClusterTest extends JMSClusteredTestBase // sleep a little bit to have the temp queue propagated to server #2 Thread.sleep(3000); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { TextMessage message = session1.createTextMessage("" + i); message.setJMSReplyTo(tempQueue); prod1.send(message); } - for (int i = 0; i < 10; i++) - { - if (i % 2 == 0) - { - TextMessage received = (TextMessage)cons2.receive(5000); + for (int i = 0; i < 10; i++) { + if (i % 2 == 0) { + TextMessage received = (TextMessage) cons2.receive(5000); System.out.println(received.getText()); System.out.println("check temp queue on server #2"); MessageProducer tempProducer = session2.createProducer(received.getJMSReplyTo()); @@ -134,17 +124,14 @@ public class TemporaryQueueClusterTest extends JMSClusteredTestBase } } - for (int i = 0; i < 10; i++) - { - if (i % 2 == 0) - { - TextMessage received = (TextMessage)tempCons1.receive(5000); + for (int i = 0; i < 10; i++) { + if (i % 2 == 0) { + TextMessage received = (TextMessage) tempCons1.receive(5000); System.out.println(received.getText()); } } } - finally - { + finally { conn1.close(); conn2.close(); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/TopicClusterTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/TopicClusterTest.java index c93d13da14..3d52e4c020 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/TopicClusterTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/cluster/TopicClusterTest.java @@ -27,8 +27,7 @@ import javax.jms.Session; import javax.jms.TextMessage; import javax.jms.Topic; -public class TopicClusterTest extends JMSClusteredTestBase -{ +public class TopicClusterTest extends JMSClusteredTestBase { // Constants ----------------------------------------------------- @@ -41,8 +40,7 @@ public class TopicClusterTest extends JMSClusteredTestBase // Public -------------------------------------------------------- @Test - public void testDeleteTopicAfterClusteredSend() throws Exception - { + public void testDeleteTopicAfterClusteredSend() throws Exception { Connection conn1 = cf1.createConnection(); conn1.setClientID("someClient1"); @@ -55,8 +53,7 @@ public class TopicClusterTest extends JMSClusteredTestBase conn2.start(); - try - { + try { Topic topic1 = createTopic("t1"); @@ -74,9 +71,7 @@ public class TopicClusterTest extends JMSClusteredTestBase prod1.setDeliveryMode(DeliveryMode.PERSISTENT); - - for (int i = 0; i < 2; i++) - { + for (int i = 0; i < 2; i++) { prod1.send(session1.createTextMessage("someMessage")); } @@ -88,8 +83,7 @@ public class TopicClusterTest extends JMSClusteredTestBase cons2.close(); } - finally - { + finally { conn1.close(); conn2.close(); } @@ -97,7 +91,6 @@ public class TopicClusterTest extends JMSClusteredTestBase jmsServer1.destroyTopic("t1"); jmsServer2.destroyTopic("t1"); - } // Package protected --------------------------------------------- diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/CloseConnectionFactoryOnGCest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/CloseConnectionFactoryOnGCest.java index 68bb3fc73e..38f2ff7529 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/CloseConnectionFactoryOnGCest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/CloseConnectionFactoryOnGCest.java @@ -28,32 +28,24 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; import org.apache.activemq.artemis.tests.util.JMSTestBase; /** - * * A CloseConnectionOnGCTest */ -public class CloseConnectionFactoryOnGCest extends JMSTestBase -{ +public class CloseConnectionFactoryOnGCest extends JMSTestBase { - public void testCloseCFOnGC() throws Exception - { + public void testCloseCFOnGC() throws Exception { final AtomicInteger valueGC = new AtomicInteger(0); - ServerLocatorImpl.finalizeCallback = new Runnable() - { - public void run() - { + ServerLocatorImpl.finalizeCallback = new Runnable() { + public void run() { valueGC.incrementAndGet(); } }; - try - { + try { // System.setOut(out); - for (int i = 0; i < 100; i++) - { - ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, - new TransportConfiguration(INVM_CONNECTOR_FACTORY)); + for (int i = 0; i < 100; i++) { + ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); Connection conn = cf.createConnection(); cf = null; conn.close(); @@ -61,8 +53,7 @@ public class CloseConnectionFactoryOnGCest extends JMSTestBase } forceGC(); } - finally - { + finally { ServerLocatorImpl.finalizeCallback = null; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/CloseConnectionOnGCTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/CloseConnectionOnGCTest.java index 06e6babfc6..adb92e7f19 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/CloseConnectionOnGCTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/CloseConnectionOnGCTest.java @@ -36,17 +36,15 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** - * * A CloseConnectionOnGCTest */ -public class CloseConnectionOnGCTest extends JMSTestBase -{ +public class CloseConnectionOnGCTest extends JMSTestBase { + private ActiveMQConnectionFactory cf; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); @@ -55,8 +53,7 @@ public class CloseConnectionOnGCTest extends JMSTestBase } @Test - public void testCloseOneConnectionOnGC() throws Exception - { + public void testCloseOneConnectionOnGC() throws Exception { // Debug - don't remove this until intermittent failure with this test is fixed int initialConns = server.getRemotingService().getConnections().size(); @@ -69,10 +66,8 @@ public class CloseConnectionOnGCTest extends JMSTestBase Assert.assertEquals(1, server.getRemotingService().getConnections().size()); final CountDownLatch latch = new CountDownLatch(1); Iterator connectionIterator = server.getRemotingService().getConnections().iterator(); - connectionIterator.next().addCloseListener(new CloseListener() - { - public void connectionClosed() - { + connectionIterator.next().addCloseListener(new CloseListener() { + public void connectionClosed() { latch.countDown(); } }); @@ -86,8 +81,7 @@ public class CloseConnectionOnGCTest extends JMSTestBase } @Test - public void testCloseSeveralConnectionOnGC() throws Exception - { + public void testCloseSeveralConnectionOnGC() throws Exception { Connection conn1 = cf.createConnection(); Connection conn2 = cf.createConnection(); Connection conn3 = cf.createConnection(); @@ -100,13 +94,10 @@ public class CloseConnectionOnGCTest extends JMSTestBase final CountDownLatch latch = new CountDownLatch(3); Iterator connectionIterator = server.getRemotingService().getConnections().iterator(); - while (connectionIterator.hasNext()) - { + while (connectionIterator.hasNext()) { RemotingConnection remotingConnection = connectionIterator.next(); - remotingConnection.addCloseListener(new CloseListener() - { - public void connectionClosed() - { + remotingConnection.addCloseListener(new CloseListener() { + public void connectionClosed() { latch.countDown(); } }); @@ -124,8 +115,7 @@ public class CloseConnectionOnGCTest extends JMSTestBase } @Test - public void testCloseSeveralConnectionsWithSessionsOnGC() throws Exception - { + public void testCloseSeveralConnectionsWithSessionsOnGC() throws Exception { Connection conn1 = cf.createConnection(); Connection conn2 = cf.createConnection(); Connection conn3 = cf.createConnection(); @@ -143,13 +133,10 @@ public class CloseConnectionOnGCTest extends JMSTestBase Session sess7 = conn3.createSession(false, Session.AUTO_ACKNOWLEDGE); final CountDownLatch latch = new CountDownLatch(3); Iterator connectionIterator = server.getRemotingService().getConnections().iterator(); - while (connectionIterator.hasNext()) - { + while (connectionIterator.hasNext()) { RemotingConnection remotingConnection = connectionIterator.next(); - remotingConnection.addCloseListener(new CloseListener() - { - public void connectionClosed() - { + remotingConnection.addCloseListener(new CloseListener() { + public void connectionClosed() { latch.countDown(); } }); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/CloseDestroyedConnectionTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/CloseDestroyedConnectionTest.java index 600739c4f7..bb1fa4a113 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/CloseDestroyedConnectionTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/CloseDestroyedConnectionTest.java @@ -38,8 +38,8 @@ import javax.jms.JMSException; import javax.jms.Queue; import javax.jms.Session; -public class CloseDestroyedConnectionTest extends JMSTestBase -{ +public class CloseDestroyedConnectionTest extends JMSTestBase { + private ActiveMQConnectionFactory cf; private ActiveMQSession session1; private Connection conn2; @@ -47,40 +47,34 @@ public class CloseDestroyedConnectionTest extends JMSTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - cf = - ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, - new TransportConfiguration(INVM_CONNECTOR_FACTORY)); + cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); cf.setBlockOnDurableSend(true); cf.setPreAcknowledge(true); } @Test - public void testClosingTemporaryTopicDeletesQueue() throws JMSException, ActiveMQException - { + public void testClosingTemporaryTopicDeletesQueue() throws JMSException, ActiveMQException { conn = cf.createConnection(); Assert.assertEquals(1, server.getRemotingService().getConnections().size()); - session1 = (ActiveMQSession)conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQTemporaryTopic topic = (ActiveMQTemporaryTopic)session1.createTemporaryTopic(); + session1 = (ActiveMQSession) conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQTemporaryTopic topic = (ActiveMQTemporaryTopic) session1.createTemporaryTopic(); String address = topic.getAddress(); session1.close(); conn.close(); conn2 = cf.createConnection(); - session2 = (ActiveMQSession)conn2.createSession(false, Session.AUTO_ACKNOWLEDGE); + session2 = (ActiveMQSession) conn2.createSession(false, Session.AUTO_ACKNOWLEDGE); ClientSession cs = session2.getCoreSession(); - try - { + try { cs.createConsumer(address); fail("the address from the TemporaryTopic still exists!"); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { assertEquals("expecting 'queue does not exist'", ActiveMQExceptionType.QUEUE_DOES_NOT_EXIST, e.getType()); } } @@ -89,8 +83,7 @@ public class CloseDestroyedConnectionTest extends JMSTestBase * Closing a connection that is destroyed should cleanly close everything without throwing exceptions */ @Test - public void testCloseDestroyedConnection() throws Exception - { + public void testCloseDestroyedConnection() throws Exception { long connectionTTL = 500; cf.setClientFailureCheckPeriod(connectionTTL / 2); // Need to set connection ttl to a low figure so connections get removed quickly on the server @@ -119,7 +112,7 @@ public class CloseDestroyedConnectionTest extends JMSTestBase // Now fail the underlying connection - ClientSessionInternal sessi = (ClientSessionInternal)((ActiveMQSession)sess).getCoreSession(); + ClientSessionInternal sessi = (ClientSessionInternal) ((ActiveMQSession) sess).getCoreSession(); RemotingConnection rc = sessi.getConnection(); @@ -131,19 +124,16 @@ public class CloseDestroyedConnectionTest extends JMSTestBase long start = System.currentTimeMillis(); - while (true) - { + while (true) { int cons = server.getRemotingService().getConnections().size(); - if (cons == 0) - { + if (cons == 0) { break; } long now = System.currentTimeMillis(); - if (now - start > 10000) - { + if (now - start > 10000) { throw new Exception("Timed out waiting for connections to close"); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/ConcurrentSessionCloseTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/ConcurrentSessionCloseTest.java index 2c5f0371b2..4317b137db 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/ConcurrentSessionCloseTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/ConcurrentSessionCloseTest.java @@ -29,17 +29,15 @@ import javax.jms.Session; import java.util.concurrent.atomic.AtomicBoolean; /** - * * A ConcurrentSessionCloseTest */ -public class ConcurrentSessionCloseTest extends JMSTestBase -{ +public class ConcurrentSessionCloseTest extends JMSTestBase { + private ActiveMQConnectionFactory cf; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); @@ -47,12 +45,10 @@ public class ConcurrentSessionCloseTest extends JMSTestBase // https://jira.jboss.org/browse/HORNETQ-525 @Test - public void testConcurrentClose() throws Exception - { + public void testConcurrentClose() throws Exception { final Connection con = cf.createConnection(); - for (int j = 0; j < 100; j++) - { + for (int j = 0; j < 100; j++) { final AtomicBoolean failed = new AtomicBoolean(false); int threadCount = 10; @@ -61,23 +57,18 @@ public class ConcurrentSessionCloseTest extends JMSTestBase Thread[] threads = new Thread[threadCount]; - for (int i = 0; i < threadCount; i++) - { - threads[i] = new Thread(group, "thread " + i) - { + for (int i = 0; i < threadCount; i++) { + threads[i] = new Thread(group, "thread " + i) { @Override - public void run() - { - try - { + public void run() { + try { con.start(); Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); session.close(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); failed.set(true); @@ -88,8 +79,7 @@ public class ConcurrentSessionCloseTest extends JMSTestBase threads[i].start(); } - for (int i = 0; i < threadCount; i++) - { + for (int i = 0; i < threadCount; i++) { threads[i].join(); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/ConnectionFactorySerializationTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/ConnectionFactorySerializationTest.java index 803dfee793..f86d98d96c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/ConnectionFactorySerializationTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/ConnectionFactorySerializationTest.java @@ -49,8 +49,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class ConnectionFactorySerializationTest extends JMSTestBase -{ +public class ConnectionFactorySerializationTest extends JMSTestBase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -61,16 +60,14 @@ public class ConnectionFactorySerializationTest extends JMSTestBase // Constructors -------------------------------------------------- @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); } // Public -------------------------------------------------------- @Test - public void testConnectionFactoryUDP() throws Exception - { + public void testConnectionFactoryUDP() throws Exception { createDiscoveryFactoryUDP(); cf = (ActiveMQConnectionFactory) namingContext.lookup("/MyConnectionFactory"); @@ -92,8 +89,7 @@ public class ConnectionFactorySerializationTest extends JMSTestBase } @Test - public void testConnectionFactoryJgroupsFile() throws Exception - { + public void testConnectionFactoryJgroupsFile() throws Exception { createDiscoveryFactoryJGroupsFile(); cf = (ActiveMQConnectionFactory) namingContext.lookup("/MyConnectionFactory"); @@ -113,8 +109,7 @@ public class ConnectionFactorySerializationTest extends JMSTestBase } @Test - public void testConnectionFactoryJgroupsProperties() throws Exception - { + public void testConnectionFactoryJgroupsProperties() throws Exception { createDiscoveryFactoryJGroupsProperties(); cf = (ActiveMQConnectionFactory) namingContext.lookup("/MyConnectionFactory"); @@ -134,8 +129,7 @@ public class ConnectionFactorySerializationTest extends JMSTestBase } @Test - public void testConnectionFactoryStatic1() throws Exception - { + public void testConnectionFactoryStatic1() throws Exception { createStaticFactory(true); cf = (ActiveMQConnectionFactory) namingContext.lookup("/MyConnectionFactory"); @@ -152,14 +146,12 @@ public class ConnectionFactorySerializationTest extends JMSTestBase Map ctParams = tc0.getParams(); Map y0Params = y0.getParams(); Assert.assertEquals(ctParams.size(), y0Params.size()); - for (String key : y0Params.keySet()) - { + for (String key : y0Params.keySet()) { Assert.assertEquals(ctParams.get(key), y0Params.get(key)); } } - private void createDiscoveryFactoryUDP() throws Exception - { + private void createDiscoveryFactoryUDP() throws Exception { // Deploy a connection factory with discovery List bindings = new ArrayList(); bindings.add("MyConnectionFactory"); @@ -167,83 +159,47 @@ public class ConnectionFactorySerializationTest extends JMSTestBase final int port = 1234; String localBindAddress = getLocalHost().getHostAddress(); - UDPBroadcastEndpointFactory config = new UDPBroadcastEndpointFactory() - .setGroupAddress(groupAddress) - .setGroupPort(port) - .setLocalBindAddress(localBindAddress) - .setLocalBindPort(8580); + UDPBroadcastEndpointFactory config = new UDPBroadcastEndpointFactory().setGroupAddress(groupAddress).setGroupPort(port).setLocalBindAddress(localBindAddress).setLocalBindPort(8580); - DiscoveryGroupConfiguration dcConfig = new DiscoveryGroupConfiguration() - .setName("dg1") - .setRefreshTimeout(5000) - .setDiscoveryInitialWaitTimeout(5000) - .setBroadcastEndpointFactory(config); + DiscoveryGroupConfiguration dcConfig = new DiscoveryGroupConfiguration().setName("dg1").setRefreshTimeout(5000).setDiscoveryInitialWaitTimeout(5000).setBroadcastEndpointFactory(config); jmsServer.getActiveMQServer().getConfiguration().getDiscoveryGroupConfigurations().put(dcConfig.getName(), dcConfig); - jmsServer.createConnectionFactory("MyConnectionFactory", - false, - JMSFactoryType.CF, - dcConfig.getName(), - "/MyConnectionFactory"); + jmsServer.createConnectionFactory("MyConnectionFactory", false, JMSFactoryType.CF, dcConfig.getName(), "/MyConnectionFactory"); } - private void createDiscoveryFactoryJGroupsFile() throws Exception - { + private void createDiscoveryFactoryJGroupsFile() throws Exception { // Deploy a connection factory with discovery List bindings = new ArrayList(); bindings.add("MyConnectionFactory"); - JGroupsFileBroadcastEndpointFactory config = new JGroupsFileBroadcastEndpointFactory() - .setChannelName("myChannel") - .setFile("/META-INF/myfile.xml"); + JGroupsFileBroadcastEndpointFactory config = new JGroupsFileBroadcastEndpointFactory().setChannelName("myChannel").setFile("/META-INF/myfile.xml"); - DiscoveryGroupConfiguration dcConfig = new DiscoveryGroupConfiguration() - .setName("dg1") - .setRefreshTimeout(5000) - .setDiscoveryInitialWaitTimeout(5000) - .setBroadcastEndpointFactory(config); + DiscoveryGroupConfiguration dcConfig = new DiscoveryGroupConfiguration().setName("dg1").setRefreshTimeout(5000).setDiscoveryInitialWaitTimeout(5000).setBroadcastEndpointFactory(config); jmsServer.getActiveMQServer().getConfiguration().getDiscoveryGroupConfigurations().put(dcConfig.getName(), dcConfig); - jmsServer.createConnectionFactory("MyConnectionFactory", - false, - JMSFactoryType.CF, - dcConfig.getName(), - "/MyConnectionFactory"); + jmsServer.createConnectionFactory("MyConnectionFactory", false, JMSFactoryType.CF, dcConfig.getName(), "/MyConnectionFactory"); } - private void createDiscoveryFactoryJGroupsProperties() throws Exception - { + private void createDiscoveryFactoryJGroupsProperties() throws Exception { // Deploy a connection factory with discovery List bindings = new ArrayList(); bindings.add("MyConnectionFactory"); - JGroupsPropertiesBroadcastEndpointFactory config = new JGroupsPropertiesBroadcastEndpointFactory() - .setChannelName("myChannel") - .setProperties("param=1,param2=2"); + JGroupsPropertiesBroadcastEndpointFactory config = new JGroupsPropertiesBroadcastEndpointFactory().setChannelName("myChannel").setProperties("param=1,param2=2"); - DiscoveryGroupConfiguration dcConfig = new DiscoveryGroupConfiguration() - .setName("dg1") - .setRefreshTimeout(5000) - .setDiscoveryInitialWaitTimeout(5000) - .setBroadcastEndpointFactory(config); + DiscoveryGroupConfiguration dcConfig = new DiscoveryGroupConfiguration().setName("dg1").setRefreshTimeout(5000).setDiscoveryInitialWaitTimeout(5000).setBroadcastEndpointFactory(config); jmsServer.getActiveMQServer().getConfiguration().getDiscoveryGroupConfigurations().put(dcConfig.getName(), dcConfig); - jmsServer.createConnectionFactory("MyConnectionFactory", - false, - JMSFactoryType.CF, - dcConfig.getName(), - "/MyConnectionFactory"); + jmsServer.createConnectionFactory("MyConnectionFactory", false, JMSFactoryType.CF, dcConfig.getName(), "/MyConnectionFactory"); } - private void createStaticFactory(boolean b) throws Exception - { + private void createStaticFactory(boolean b) throws Exception { HashMap params = new HashMap<>(); Set allowableConnectorKeys = TransportConstants.ALLOWABLE_CONNECTOR_KEYS; - for (String allowableConnectorKey : allowableConnectorKeys) - { + for (String allowableConnectorKey : allowableConnectorKeys) { String value = RandomUtil.randomString(); params.put(allowableConnectorKey, value); } @@ -255,8 +211,7 @@ public class ConnectionFactorySerializationTest extends JMSTestBase jmsServer.getActiveMQServer().getConfiguration().getConnectorConfigurations().put(main.getName(), main); HashMap params2 = new HashMap<>(); - for (String allowableConnectorKey : allowableConnectorKeys) - { + for (String allowableConnectorKey : allowableConnectorKeys) { String value = RandomUtil.randomString(); params2.put(allowableConnectorKey, value); } @@ -270,71 +225,33 @@ public class ConnectionFactorySerializationTest extends JMSTestBase ArrayList connectorNames = new ArrayList(); connectorNames.add(main.getName()); connectorNames.add(main2.getName()); - ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl() - .setName("MyConnectionFactory") - .setHA(b) - .setConnectorNames(connectorNames) - .setClientID("clientID") - .setClientFailureCheckPeriod(-1) - .setConnectionTTL(-2) - .setFactoryType(JMSFactoryType.CF) - .setCallTimeout(-3) - .setCallFailoverTimeout(-4) - .setCacheLargeMessagesClient(b) - .setMinLargeMessageSize(-5) - .setConsumerWindowSize(-6) - .setConsumerMaxRate(-7) - .setConfirmationWindowSize(-8) - .setProducerWindowSize(-9) - .setProducerMaxRate(-10) - .setBlockOnAcknowledge(b) - .setBlockOnDurableSend(b) - .setBlockOnNonDurableSend(b) - .setAutoGroup(b) - .setPreAcknowledge(b) - .setLoadBalancingPolicyClassName("foobar") - .setTransactionBatchSize(-11) - .setDupsOKBatchSize(-12) - .setUseGlobalPools(b) - .setScheduledThreadPoolMaxSize(-13) - .setThreadPoolMaxSize(-14) - .setRetryInterval(-15) - .setRetryIntervalMultiplier(-16) - .setMaxRetryInterval(-17) - .setReconnectAttempts(-18) - .setFailoverOnInitialConnection(b) - .setGroupID("groupID"); + ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl().setName("MyConnectionFactory").setHA(b).setConnectorNames(connectorNames).setClientID("clientID").setClientFailureCheckPeriod(-1).setConnectionTTL(-2).setFactoryType(JMSFactoryType.CF).setCallTimeout(-3).setCallFailoverTimeout(-4).setCacheLargeMessagesClient(b).setMinLargeMessageSize(-5).setConsumerWindowSize(-6).setConsumerMaxRate(-7).setConfirmationWindowSize(-8).setProducerWindowSize(-9).setProducerMaxRate(-10).setBlockOnAcknowledge(b).setBlockOnDurableSend(b).setBlockOnNonDurableSend(b).setAutoGroup(b).setPreAcknowledge(b).setLoadBalancingPolicyClassName("foobar").setTransactionBatchSize(-11).setDupsOKBatchSize(-12).setUseGlobalPools(b).setScheduledThreadPoolMaxSize(-13).setThreadPoolMaxSize(-14).setRetryInterval(-15).setRetryIntervalMultiplier(-16).setMaxRetryInterval(-17).setReconnectAttempts(-18).setFailoverOnInitialConnection(b).setGroupID("groupID"); jmsServer.createConnectionFactory(false, configuration, "/MyConnectionFactory"); } - private void populate(StringBuilder sb, BeanUtilsBean bean, ActiveMQConnectionFactory factory) throws IllegalAccessException, InvocationTargetException - { + private void populate(StringBuilder sb, + BeanUtilsBean bean, + ActiveMQConnectionFactory factory) throws IllegalAccessException, InvocationTargetException { PropertyDescriptor[] descriptors = bean.getPropertyUtils().getPropertyDescriptors(factory); - for (PropertyDescriptor descriptor : descriptors) - { - if (descriptor.getWriteMethod() != null && descriptor.getReadMethod() != null) - { - if (descriptor.getPropertyType() == String.class) - { + for (PropertyDescriptor descriptor : descriptors) { + if (descriptor.getWriteMethod() != null && descriptor.getReadMethod() != null) { + if (descriptor.getPropertyType() == String.class) { String value = RandomUtil.randomString(); bean.setProperty(factory, descriptor.getName(), value); sb.append("&").append(descriptor.getName()).append("=").append(value); } - else if (descriptor.getPropertyType() == int.class) - { + else if (descriptor.getPropertyType() == int.class) { int value = RandomUtil.randomPositiveInt(); bean.setProperty(factory, descriptor.getName(), value); sb.append("&").append(descriptor.getName()).append("=").append(value); } - else if (descriptor.getPropertyType() == long.class) - { + else if (descriptor.getPropertyType() == long.class) { long value = RandomUtil.randomPositiveLong(); bean.setProperty(factory, descriptor.getName(), value); sb.append("&").append(descriptor.getName()).append("=").append(value); } - else if (descriptor.getPropertyType() == double.class) - { + else if (descriptor.getPropertyType() == double.class) { double value = RandomUtil.randomDouble(); bean.setProperty(factory, descriptor.getName(), value); sb.append("&").append(descriptor.getName()).append("=").append(value); @@ -343,20 +260,18 @@ public class ConnectionFactorySerializationTest extends JMSTestBase } } - private static void checkEquals(Object factory, Object factory2) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException - { + private static void checkEquals(Object factory, + Object factory2) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { BeanUtilsBean bean = new BeanUtilsBean(); PropertyDescriptor[] descriptors = bean.getPropertyUtils().getPropertyDescriptors(factory); - for (PropertyDescriptor descriptor : descriptors) - { - if (descriptor.getWriteMethod() != null && descriptor.getReadMethod() != null) - { - Assert.assertEquals(descriptor.getName() + " incorrect", bean.getProperty(factory, descriptor.getName()),bean.getProperty(factory2, descriptor.getName())); + for (PropertyDescriptor descriptor : descriptors) { + if (descriptor.getWriteMethod() != null && descriptor.getReadMethod() != null) { + Assert.assertEquals(descriptor.getName() + " incorrect", bean.getProperty(factory, descriptor.getName()), bean.getProperty(factory2, descriptor.getName())); } } } - private static byte[] serialize(T obj) throws IOException - { + + private static byte[] serialize(T obj) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(obj); @@ -364,8 +279,8 @@ public class ConnectionFactorySerializationTest extends JMSTestBase return baos.toByteArray(); } - private static T deserialize(byte[] b, Class cl) throws IOException, ClassNotFoundException - { + private static T deserialize(byte[] b, + Class cl) throws IOException, ClassNotFoundException { ByteArrayInputStream bais = new ByteArrayInputStream(b); ObjectInputStream ois = new ObjectInputStream(bais); Object o = ois.readObject(); @@ -376,15 +291,12 @@ public class ConnectionFactorySerializationTest extends JMSTestBase // Protected ----------------------------------------------------- - protected static InetAddress getLocalHost() throws UnknownHostException - { + protected static InetAddress getLocalHost() throws UnknownHostException { InetAddress addr; - try - { + try { addr = InetAddress.getLocalHost(); } - catch (ArrayIndexOutOfBoundsException e) - { //this is workaround for mac osx bug see AS7-3223 and JGRP-1404 + catch (ArrayIndexOutOfBoundsException e) { //this is workaround for mac osx bug see AS7-3223 and JGRP-1404 addr = InetAddress.getByName(null); } return addr; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/ConnectionFactoryWithJGroupsSerializationTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/ConnectionFactoryWithJGroupsSerializationTest.java index bf507600f7..1be398da2c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/ConnectionFactoryWithJGroupsSerializationTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/ConnectionFactoryWithJGroupsSerializationTest.java @@ -40,54 +40,20 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class ConnectionFactoryWithJGroupsSerializationTest extends JMSTestBase -{ +public class ConnectionFactoryWithJGroupsSerializationTest extends JMSTestBase { protected static ActiveMQConnectionFactory jmsCf1; protected static ActiveMQConnectionFactory jmsCf2; - private final String jgroupsConfigString = "UDP(oob_thread_pool.max_threads=300;" - + "bind_addr=127.0.0.1;oob_thread_pool.keep_alive_time=1000;" - + "max_bundle_size=31k;mcast_send_buf_size=640000;" - + "internal_thread_pool.keep_alive_time=60000;" - + "internal_thread_pool.rejection_policy=discard;" - + "mcast_recv_buf_size=25000000;bind_port=55200;" - + "internal_thread_pool.queue_max_size=100;" - + "mcast_port=45688;thread_pool.min_threads=20;" - + "oob_thread_pool.rejection_policy=discard;" - + "thread_pool.max_threads=300;enable_diagnostics=false;" - + "thread_pool.enabled=true;internal_thread_pool.queue_enabled=true;" - + "ucast_recv_buf_size=20000000;ucast_send_buf_size=640000;" - + "internal_thread_pool.enabled=true;oob_thread_pool.enabled=true;" - + "ip_ttl=2;thread_pool.rejection_policy=discard;thread_pool.keep_alive_time=5000;" - + "internal_thread_pool.max_threads=10;thread_pool.queue_enabled=true;" - + "mcast_addr=230.0.0.4;singleton_name=udp;max_bundle_timeout=30;" - + "oob_thread_pool.queue_enabled=false;internal_thread_pool.min_threads=1;" - + "bundler_type=old;oob_thread_pool.min_threads=20;" - + "thread_pool.queue_max_size=1000):PING(num_initial_members=3;" - + "timeout=2000):MERGE3(min_interval=20000;max_interval=100000)" - + ":FD_SOCK(bind_addr=127.0.0.1;start_port=54200):FD_ALL(interval=3000;" - + "timeout=15000):VERIFY_SUSPECT(bind_addr=127.0.0.1;" - + "timeout=1500):pbcast.NAKACK2(max_msg_batch_size=100;" - + "xmit_table_msgs_per_row=10000;xmit_table_max_compaction_time=10000;" - + "xmit_table_num_rows=100;xmit_interval=1000):UNICAST3(xmit_table_msgs_per_row=10000;" - + "xmit_table_max_compaction_time=10000;xmit_table_num_rows=20)" - + ":pbcast.STABLE(desired_avg_gossip=50000;max_bytes=400000;" - + "stability_delay=1000):pbcast.GMS(print_local_addr=true;" - + "view_bundling=true;join_timeout=3000;view_ack_collection_timeout=5000;" - + "resume_task_timeout=7500):UFC(max_credits=1m;min_threshold=0.40)" - + ":MFC(max_credits=1m;min_threshold=0.40):FRAG2(frag_size=30k)" - + ":RSVP(resend_interval=500;ack_on_delivery=false;timeout=60000)"; + private final String jgroupsConfigString = "UDP(oob_thread_pool.max_threads=300;" + "bind_addr=127.0.0.1;oob_thread_pool.keep_alive_time=1000;" + "max_bundle_size=31k;mcast_send_buf_size=640000;" + "internal_thread_pool.keep_alive_time=60000;" + "internal_thread_pool.rejection_policy=discard;" + "mcast_recv_buf_size=25000000;bind_port=55200;" + "internal_thread_pool.queue_max_size=100;" + "mcast_port=45688;thread_pool.min_threads=20;" + "oob_thread_pool.rejection_policy=discard;" + "thread_pool.max_threads=300;enable_diagnostics=false;" + "thread_pool.enabled=true;internal_thread_pool.queue_enabled=true;" + "ucast_recv_buf_size=20000000;ucast_send_buf_size=640000;" + "internal_thread_pool.enabled=true;oob_thread_pool.enabled=true;" + "ip_ttl=2;thread_pool.rejection_policy=discard;thread_pool.keep_alive_time=5000;" + "internal_thread_pool.max_threads=10;thread_pool.queue_enabled=true;" + "mcast_addr=230.0.0.4;singleton_name=udp;max_bundle_timeout=30;" + "oob_thread_pool.queue_enabled=false;internal_thread_pool.min_threads=1;" + "bundler_type=old;oob_thread_pool.min_threads=20;" + "thread_pool.queue_max_size=1000):PING(num_initial_members=3;" + "timeout=2000):MERGE3(min_interval=20000;max_interval=100000)" + ":FD_SOCK(bind_addr=127.0.0.1;start_port=54200):FD_ALL(interval=3000;" + "timeout=15000):VERIFY_SUSPECT(bind_addr=127.0.0.1;" + "timeout=1500):pbcast.NAKACK2(max_msg_batch_size=100;" + "xmit_table_msgs_per_row=10000;xmit_table_max_compaction_time=10000;" + "xmit_table_num_rows=100;xmit_interval=1000):UNICAST3(xmit_table_msgs_per_row=10000;" + "xmit_table_max_compaction_time=10000;xmit_table_num_rows=20)" + ":pbcast.STABLE(desired_avg_gossip=50000;max_bytes=400000;" + "stability_delay=1000):pbcast.GMS(print_local_addr=true;" + "view_bundling=true;join_timeout=3000;view_ack_collection_timeout=5000;" + "resume_task_timeout=7500):UFC(max_credits=1m;min_threshold=0.40)" + ":MFC(max_credits=1m;min_threshold=0.40):FRAG2(frag_size=30k)" + ":RSVP(resend_interval=500;ack_on_delivery=false;timeout=60000)"; JChannel channel = null; Queue testQueue = null; @Override @Before - public void setUp() throws Exception - { - try - { + public void setUp() throws Exception { + try { super.setUp(); PlainConfigurator configurator = new PlainConfigurator(jgroupsConfigString); @@ -97,42 +63,22 @@ public class ConnectionFactoryWithJGroupsSerializationTest extends JMSTestBase String channelName2 = "channel2"; BroadcastEndpointFactory jgroupsBroadcastCfg1 = new ChannelBroadcastEndpointFactory(channel, channelName1); - BroadcastEndpointFactory jgroupsBroadcastCfg2 = new JGroupsFileBroadcastEndpointFactory() - .setChannelName(channelName2) - .setFile(jgroupsConfigString); + BroadcastEndpointFactory jgroupsBroadcastCfg2 = new JGroupsFileBroadcastEndpointFactory().setChannelName(channelName2).setFile(jgroupsConfigString); - DiscoveryGroupConfiguration dcConfig1 = new DiscoveryGroupConfiguration() - .setName("dg1") - .setRefreshTimeout(5000) - .setDiscoveryInitialWaitTimeout(5000) - .setBroadcastEndpointFactory(jgroupsBroadcastCfg1); + DiscoveryGroupConfiguration dcConfig1 = new DiscoveryGroupConfiguration().setName("dg1").setRefreshTimeout(5000).setDiscoveryInitialWaitTimeout(5000).setBroadcastEndpointFactory(jgroupsBroadcastCfg1); - DiscoveryGroupConfiguration dcConfig2 = new DiscoveryGroupConfiguration() - .setName("dg2") - .setRefreshTimeout(5000) - .setDiscoveryInitialWaitTimeout(5000) - .setBroadcastEndpointFactory(jgroupsBroadcastCfg2); + DiscoveryGroupConfiguration dcConfig2 = new DiscoveryGroupConfiguration().setName("dg2").setRefreshTimeout(5000).setDiscoveryInitialWaitTimeout(5000).setBroadcastEndpointFactory(jgroupsBroadcastCfg2); jmsServer.getActiveMQServer().getConfiguration().getDiscoveryGroupConfigurations().put(dcConfig1.getName(), dcConfig1); jmsServer.getActiveMQServer().getConfiguration().getDiscoveryGroupConfigurations().put(dcConfig2.getName(), dcConfig2); - jmsServer.createConnectionFactory("ConnectionFactory1", - false, - JMSFactoryType.CF, - dcConfig1.getName(), - "/ConnectionFactory1"); + jmsServer.createConnectionFactory("ConnectionFactory1", false, JMSFactoryType.CF, dcConfig1.getName(), "/ConnectionFactory1"); - - jmsServer.createConnectionFactory("ConnectionFactory2", - false, - JMSFactoryType.CF, - dcConfig2.getName(), - "/ConnectionFactory2"); + jmsServer.createConnectionFactory("ConnectionFactory2", false, JMSFactoryType.CF, dcConfig2.getName(), "/ConnectionFactory2"); testQueue = createQueue("testQueueFor1389"); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); throw e; } @@ -147,17 +93,14 @@ public class ConnectionFactoryWithJGroupsSerializationTest extends JMSTestBase //So the first one will get serialization exception in the test //while the second will not. @Test - public void testSerialization() throws Exception - { + public void testSerialization() throws Exception { jmsCf1 = (ActiveMQConnectionFactory) namingContext.lookup("/ConnectionFactory1"); jmsCf2 = (ActiveMQConnectionFactory) namingContext.lookup("/ConnectionFactory2"); - try - { + try { serialize(jmsCf1); } - catch (java.io.NotSerializableException e) - { + catch (java.io.NotSerializableException e) { //this is expected } @@ -170,8 +113,7 @@ public class ConnectionFactoryWithJGroupsSerializationTest extends JMSTestBase } @Test - public void testCopyConfiguration() throws Exception - { + public void testCopyConfiguration() throws Exception { Assert.assertEquals(2, jmsServer.getActiveMQServer().getConfiguration().getDiscoveryGroupConfigurations().size()); Configuration copiedconfig = jmsServer.getActiveMQServer().getConfiguration().copy(); Assert.assertEquals(2, copiedconfig.getDiscoveryGroupConfigurations().size()); @@ -179,15 +121,11 @@ public class ConnectionFactoryWithJGroupsSerializationTest extends JMSTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { // small hack, the channel here is cached, so checking that it's not closed by any endpoint - BroadcastEndpoint broadcastEndpoint = jmsServer.getActiveMQServer().getConfiguration() - .getDiscoveryGroupConfigurations().get("dg1") - .getBroadcastEndpointFactory().createBroadcastEndpoint(); + BroadcastEndpoint broadcastEndpoint = jmsServer.getActiveMQServer().getConfiguration().getDiscoveryGroupConfigurations().get("dg1").getBroadcastEndpointFactory().createBroadcastEndpoint(); broadcastEndpoint.close(true); - if (channel != null) - { + if (channel != null) { assertFalse(channel.isClosed()); channel.close(); } @@ -195,8 +133,7 @@ public class ConnectionFactoryWithJGroupsSerializationTest extends JMSTestBase super.tearDown(); } - private static byte[] serialize(T obj) throws IOException - { + private static byte[] serialize(T obj) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(obj); @@ -204,8 +141,8 @@ public class ConnectionFactoryWithJGroupsSerializationTest extends JMSTestBase return baos.toByteArray(); } - private static T deserialize(byte[] b, Class cl) throws IOException, ClassNotFoundException - { + private static T deserialize(byte[] b, + Class cl) throws IOException, ClassNotFoundException { ByteArrayInputStream bais = new ByteArrayInputStream(b); ObjectInputStream ois = new ObjectInputStream(bais); Object o = ois.readObject(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/ExceptionListenerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/ExceptionListenerTest.java index 45e40116a5..26f17844bf 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/ExceptionListenerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/ExceptionListenerTest.java @@ -42,11 +42,10 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** - * * ExceptionListenerTest */ -public class ExceptionListenerTest extends ActiveMQTestBase -{ +public class ExceptionListenerTest extends ActiveMQTestBase { + private ActiveMQServer server; private JMSServerManagerImpl jmsServer; @@ -57,8 +56,7 @@ public class ExceptionListenerTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = addServer(ActiveMQServers.newActiveMQServer(createDefaultInVMConfig(), false)); @@ -71,34 +69,31 @@ public class ExceptionListenerTest extends ActiveMQTestBase cf.setPreAcknowledge(true); } - private class MyExceptionListener implements ExceptionListener - { + private class MyExceptionListener implements ExceptionListener { + volatile int numCalls; private final CountDownLatch latch; - public MyExceptionListener(final CountDownLatch latch) - { + public MyExceptionListener(final CountDownLatch latch) { this.latch = latch; } - public synchronized void onException(final JMSException arg0) - { + public synchronized void onException(final JMSException arg0) { numCalls++; latch.countDown(); } } @Test - public void testListenerCalledForOneConnection() throws Exception - { + public void testListenerCalledForOneConnection() throws Exception { Connection conn = cf.createConnection(); CountDownLatch latch = new CountDownLatch(1); MyExceptionListener listener = new MyExceptionListener(latch); conn.setExceptionListener(listener); - ClientSessionInternal coreSession = (ClientSessionInternal)((ActiveMQConnection)conn).getInitialSession(); + ClientSessionInternal coreSession = (ClientSessionInternal) ((ActiveMQConnection) conn).getInitialSession(); coreSession.getConnection().fail(new ActiveMQInternalErrorException("blah")); @@ -110,8 +105,7 @@ public class ExceptionListenerTest extends ActiveMQTestBase } @Test - public void testListenerCalledForOneConnectionAndSessions() throws Exception - { + public void testListenerCalledForOneConnectionAndSessions() throws Exception { Connection conn = cf.createConnection(); CountDownLatch latch = new CountDownLatch(1); @@ -125,13 +119,13 @@ public class ExceptionListenerTest extends ActiveMQTestBase Session sess3 = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - ClientSessionInternal coreSession0 = (ClientSessionInternal)((ActiveMQConnection)conn).getInitialSession(); + ClientSessionInternal coreSession0 = (ClientSessionInternal) ((ActiveMQConnection) conn).getInitialSession(); - ClientSessionInternal coreSession1 = (ClientSessionInternal)((ActiveMQSession)sess1).getCoreSession(); + ClientSessionInternal coreSession1 = (ClientSessionInternal) ((ActiveMQSession) sess1).getCoreSession(); - ClientSessionInternal coreSession2 = (ClientSessionInternal)((ActiveMQSession)sess2).getCoreSession(); + ClientSessionInternal coreSession2 = (ClientSessionInternal) ((ActiveMQSession) sess2).getCoreSession(); - ClientSessionInternal coreSession3 = (ClientSessionInternal)((ActiveMQSession)sess3).getCoreSession(); + ClientSessionInternal coreSession3 = (ClientSessionInternal) ((ActiveMQSession) sess3).getCoreSession(); coreSession0.getConnection().fail(new ActiveMQInternalErrorException("blah")); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/InvalidConnectorTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/InvalidConnectorTest.java index 40480d6365..46c2d767e1 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/InvalidConnectorTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/InvalidConnectorTest.java @@ -30,58 +30,22 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -public class InvalidConnectorTest extends JMSTestBase -{ +public class InvalidConnectorTest extends JMSTestBase { + @Test - public void testInvalidConnector() throws Exception - { + public void testInvalidConnector() throws Exception { Map params = new HashMap(); params.put(TransportConstants.HOST_PROP_NAME, "0.0.0.0"); List connectorConfigs = new ArrayList(); connectorConfigs.add(new TransportConfiguration(NETTY_CONNECTOR_FACTORY, params)); - int retryInterval = 1000; double retryIntervalMultiplier = 1.0; int reconnectAttempts = -1; int callTimeout = 30000; - jmsServer.createConnectionFactory("invalid-cf", - false, - JMSFactoryType.CF, - registerConnectors(server, connectorConfigs), - null, - ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, - ActiveMQClient.DEFAULT_CONNECTION_TTL, - callTimeout, - ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, - ActiveMQClient.DEFAULT_CACHE_LARGE_MESSAGE_CLIENT, - ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES, - ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, - ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, - ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, - ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, - ActiveMQClient.DEFAULT_AUTO_GROUP, - ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, - ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, - retryInterval, - retryIntervalMultiplier, - ActiveMQClient.DEFAULT_MAX_RETRY_INTERVAL, - reconnectAttempts, - ActiveMQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION, - null, - "/invalid-cf"); + jmsServer.createConnectionFactory("invalid-cf", false, JMSFactoryType.CF, registerConnectors(server, connectorConfigs), null, ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, ActiveMQClient.DEFAULT_CONNECTION_TTL, callTimeout, ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, ActiveMQClient.DEFAULT_CACHE_LARGE_MESSAGE_CLIENT, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES, ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, ActiveMQClient.DEFAULT_AUTO_GROUP, ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, retryInterval, retryIntervalMultiplier, ActiveMQClient.DEFAULT_MAX_RETRY_INTERVAL, reconnectAttempts, ActiveMQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION, null, "/invalid-cf"); ActiveMQConnectionFactory invalidCf = (ActiveMQConnectionFactory) namingContext.lookup("/invalid-cf"); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/consumer/ConsumerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/consumer/ConsumerTest.java index 9c8fa8d4ae..fe0276ce24 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/consumer/ConsumerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/consumer/ConsumerTest.java @@ -46,8 +46,8 @@ import javax.jms.TextMessage; import java.util.Enumeration; import java.util.concurrent.atomic.AtomicInteger; -public class ConsumerTest extends JMSTestBase -{ +public class ConsumerTest extends JMSTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private static final String Q_NAME = "ConsumerTestQueue"; @@ -62,8 +62,7 @@ public class ConsumerTest extends JMSTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); topic = ActiveMQJMSClient.createTopic(T_NAME); @@ -76,8 +75,7 @@ public class ConsumerTest extends JMSTestBase } @Test - public void testTransactionalSessionRollback() throws Exception - { + public void testTransactionalSessionRollback() throws Exception { conn = cf.createConnection(); Session sess = conn.createSession(true, Session.SESSION_TRANSACTED); @@ -117,22 +115,19 @@ public class ConsumerTest extends JMSTestBase } @Test - public void testPreCommitAcks() throws Exception - { + public void testPreCommitAcks() throws Exception { conn = cf.createConnection(); Session session = conn.createSession(false, ActiveMQJMSConstants.PRE_ACKNOWLEDGE); jBossQueue = ActiveMQJMSClient.createQueue(ConsumerTest.Q_NAME); MessageProducer producer = session.createProducer(jBossQueue); MessageConsumer consumer = session.createConsumer(jBossQueue); int noOfMessages = 100; - for (int i = 0; i < noOfMessages; i++) - { + for (int i = 0; i < noOfMessages; i++) { producer.send(session.createTextMessage("m" + i)); } conn.start(); - for (int i = 0; i < noOfMessages; i++) - { + for (int i = 0; i < noOfMessages; i++) { Message m = consumer.receive(500); Assert.assertNotNull(m); } @@ -143,28 +138,24 @@ public class ConsumerTest extends JMSTestBase } @Test - public void testIndividualACK() throws Exception - { + public void testIndividualACK() throws Exception { Connection conn = cf.createConnection(); Session session = conn.createSession(false, ActiveMQJMSConstants.INDIVIDUAL_ACKNOWLEDGE); jBossQueue = ActiveMQJMSClient.createQueue(ConsumerTest.Q_NAME); MessageProducer producer = session.createProducer(jBossQueue); MessageConsumer consumer = session.createConsumer(jBossQueue); int noOfMessages = 100; - for (int i = 0; i < noOfMessages; i++) - { + for (int i = 0; i < noOfMessages; i++) { producer.send(session.createTextMessage("m" + i)); } conn.start(); // Consume even numbers first - for (int i = 0; i < noOfMessages; i++) - { + for (int i = 0; i < noOfMessages; i++) { Message m = consumer.receive(500); Assert.assertNotNull(m); - if (i % 2 == 0) - { + if (i % 2 == 0) { m.acknowledge(); } } @@ -176,10 +167,8 @@ public class ConsumerTest extends JMSTestBase consumer = session.createConsumer(jBossQueue); // Consume odd numbers first - for (int i = 0; i < noOfMessages; i++) - { - if (i % 2 == 0) - { + for (int i = 0; i < noOfMessages; i++) { + if (i % 2 == 0) { continue; } @@ -196,16 +185,14 @@ public class ConsumerTest extends JMSTestBase } @Test - public void testIndividualACKMessageConsumer() throws Exception - { + public void testIndividualACKMessageConsumer() throws Exception { Connection conn = cf.createConnection(); Session session = conn.createSession(false, ActiveMQJMSConstants.INDIVIDUAL_ACKNOWLEDGE); jBossQueue = ActiveMQJMSClient.createQueue(ConsumerTest.Q_NAME); MessageProducer producer = session.createProducer(jBossQueue); MessageConsumer consumer = session.createConsumer(jBossQueue); int noOfMessages = 100; - for (int i = 0; i < noOfMessages; i++) - { + for (int i = 0; i < noOfMessages; i++) { producer.setPriority(2); producer.send(session.createTextMessage("m" + i)); } @@ -216,34 +203,28 @@ public class ConsumerTest extends JMSTestBase final ReusableLatch latch = new ReusableLatch(); latch.setCount(noOfMessages); - class MessageAckEven implements MessageListener - { + class MessageAckEven implements MessageListener { + int count = 0; - public void onMessage(Message msg) - { - try - { + public void onMessage(Message msg) { + try { TextMessage txtmsg = (TextMessage) msg; - if (!txtmsg.getText().equals("m" + count)) - { + if (!txtmsg.getText().equals("m" + count)) { errors.incrementAndGet(); } - if (count % 2 == 0) - { + if (count % 2 == 0) { msg.acknowledge(); } count++; } - catch (Exception e) - { + catch (Exception e) { errors.incrementAndGet(); } - finally - { + finally { latch.countDown(); } } @@ -261,10 +242,8 @@ public class ConsumerTest extends JMSTestBase consumer = session.createConsumer(jBossQueue); // Consume odd numbers first - for (int i = 0; i < noOfMessages; i++) - { - if (i % 2 == 0) - { + for (int i = 0; i < noOfMessages; i++) { + if (i % 2 == 0) { continue; } @@ -281,8 +260,7 @@ public class ConsumerTest extends JMSTestBase } @Test - public void testPreCommitAcksSetOnConnectionFactory() throws Exception - { + public void testPreCommitAcksSetOnConnectionFactory() throws Exception { ((ActiveMQConnectionFactory) cf).setPreAcknowledge(true); conn = cf.createConnection(); @@ -291,14 +269,12 @@ public class ConsumerTest extends JMSTestBase MessageProducer producer = session.createProducer(jBossQueue); MessageConsumer consumer = session.createConsumer(jBossQueue); int noOfMessages = 100; - for (int i = 0; i < noOfMessages; i++) - { + for (int i = 0; i < noOfMessages; i++) { producer.send(session.createTextMessage("m" + i)); } conn.start(); - for (int i = 0; i < noOfMessages; i++) - { + for (int i = 0; i < noOfMessages; i++) { Message m = consumer.receive(500); Assert.assertNotNull(m); } @@ -310,8 +286,7 @@ public class ConsumerTest extends JMSTestBase } @Test - public void testPreCommitAcksWithMessageExpiry() throws Exception - { + public void testPreCommitAcksWithMessageExpiry() throws Exception { ConsumerTest.log.info("starting test"); conn = cf.createConnection(); @@ -320,8 +295,7 @@ public class ConsumerTest extends JMSTestBase MessageProducer producer = session.createProducer(jBossQueue); MessageConsumer consumer = session.createConsumer(jBossQueue); int noOfMessages = 1000; - for (int i = 0; i < noOfMessages; i++) - { + for (int i = 0; i < noOfMessages; i++) { TextMessage textMessage = session.createTextMessage("m" + i); producer.setTimeToLive(1); producer.send(textMessage); @@ -341,8 +315,7 @@ public class ConsumerTest extends JMSTestBase } @Test - public void testPreCommitAcksWithMessageExpirySetOnConnectionFactory() throws Exception - { + public void testPreCommitAcksWithMessageExpirySetOnConnectionFactory() throws Exception { ((ActiveMQConnectionFactory) cf).setPreAcknowledge(true); conn = cf.createConnection(); Session session = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); @@ -350,8 +323,7 @@ public class ConsumerTest extends JMSTestBase MessageProducer producer = session.createProducer(jBossQueue); MessageConsumer consumer = session.createConsumer(jBossQueue); int noOfMessages = 1000; - for (int i = 0; i < noOfMessages; i++) - { + for (int i = 0; i < noOfMessages; i++) { TextMessage textMessage = session.createTextMessage("m" + i); producer.setTimeToLive(1); producer.send(textMessage); @@ -368,10 +340,8 @@ public class ConsumerTest extends JMSTestBase // which can cause delivering count to flip to 1 } - @Test - public void testBrowserAndConsumerSimultaneous() throws Exception - { + public void testBrowserAndConsumerSimultaneous() throws Exception { ((ActiveMQConnectionFactory) cf).setConsumerWindowSize(0); conn = cf.createConnection(); @@ -382,19 +352,16 @@ public class ConsumerTest extends JMSTestBase QueueBrowser browser = session.createBrowser(jBossQueue); Enumeration enumMessages = browser.getEnumeration(); - MessageConsumer consumer = session.createConsumer(jBossQueue); int noOfMessages = 10; - for (int i = 0; i < noOfMessages; i++) - { + for (int i = 0; i < noOfMessages; i++) { TextMessage textMessage = session.createTextMessage("m" + i); textMessage.setIntProperty("i", i); producer.send(textMessage); } conn.start(); - for (int i = 0; i < noOfMessages; i++) - { + for (int i = 0; i < noOfMessages; i++) { TextMessage msg = (TextMessage) enumMessages.nextElement(); Assert.assertNotNull(msg); Assert.assertEquals(i, msg.getIntProperty("i")); @@ -417,8 +384,7 @@ public class ConsumerTest extends JMSTestBase } @Test - public void testBrowserAndConsumerSimultaneousDifferentConnections() throws Exception - { + public void testBrowserAndConsumerSimultaneousDifferentConnections() throws Exception { ((ActiveMQConnectionFactory) cf).setConsumerWindowSize(0); conn = cf.createConnection(); @@ -430,8 +396,7 @@ public class ConsumerTest extends JMSTestBase MessageProducer producer = session.createProducer(jBossQueue); MessageConsumer consumer = sessionConsumer.createConsumer(jBossQueue); int noOfMessages = 1000; - for (int i = 0; i < noOfMessages; i++) - { + for (int i = 0; i < noOfMessages; i++) { TextMessage textMessage = session.createTextMessage("m" + i); textMessage.setIntProperty("i", i); producer.send(textMessage); @@ -442,8 +407,7 @@ public class ConsumerTest extends JMSTestBase QueueBrowser browser = session.createBrowser(jBossQueue); Enumeration enumMessages = browser.getEnumeration(); - for (int i = 0; i < noOfMessages; i++) - { + for (int i = 0; i < noOfMessages; i++) { TextMessage msg = (TextMessage) enumMessages.nextElement(); Assert.assertNotNull(msg); Assert.assertEquals(i, msg.getIntProperty("i")); @@ -461,8 +425,7 @@ public class ConsumerTest extends JMSTestBase } @Test - public void testBrowserOnly() throws Exception - { + public void testBrowserOnly() throws Exception { ((ActiveMQConnectionFactory) cf).setConsumerWindowSize(0); conn = cf.createConnection(); @@ -470,8 +433,7 @@ public class ConsumerTest extends JMSTestBase jBossQueue = ActiveMQJMSClient.createQueue(ConsumerTest.Q_NAME); MessageProducer producer = session.createProducer(jBossQueue); int noOfMessages = 10; - for (int i = 0; i < noOfMessages; i++) - { + for (int i = 0; i < noOfMessages; i++) { TextMessage textMessage = session.createTextMessage("m" + i); textMessage.setIntProperty("i", i); producer.send(textMessage); @@ -480,8 +442,7 @@ public class ConsumerTest extends JMSTestBase QueueBrowser browser = session.createBrowser(jBossQueue); Enumeration enumMessages = browser.getEnumeration(); - for (int i = 0; i < noOfMessages; i++) - { + for (int i = 0; i < noOfMessages; i++) { Assert.assertTrue(enumMessages.hasMoreElements()); TextMessage msg = (TextMessage) enumMessages.nextElement(); Assert.assertNotNull(msg); @@ -499,16 +460,13 @@ public class ConsumerTest extends JMSTestBase } @Test - public void testClearExceptionListener() throws Exception - { + public void testClearExceptionListener() throws Exception { conn = cf.createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); jBossQueue = ActiveMQJMSClient.createQueue(ConsumerTest.Q_NAME); MessageConsumer consumer = session.createConsumer(jBossQueue); - consumer.setMessageListener(new MessageListener() - { - public void onMessage(final Message msg) - { + consumer.setMessageListener(new MessageListener() { + public void onMessage(final Message msg) { } }); @@ -517,39 +475,32 @@ public class ConsumerTest extends JMSTestBase } @Test - public void testCantReceiveWhenListenerIsSet() throws Exception - { + public void testCantReceiveWhenListenerIsSet() throws Exception { conn = cf.createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); jBossQueue = ActiveMQJMSClient.createQueue(ConsumerTest.Q_NAME); MessageConsumer consumer = session.createConsumer(jBossQueue); - consumer.setMessageListener(new MessageListener() - { - public void onMessage(final Message msg) - { + consumer.setMessageListener(new MessageListener() { + public void onMessage(final Message msg) { } }); - try - { + try { consumer.receiveNoWait(); Assert.fail("Should throw exception"); } - catch (JMSException e) - { + catch (JMSException e) { // Ok } } @Test - public void testSharedConsumer() throws Exception - { + public void testSharedConsumer() throws Exception { conn = cf.createConnection(); conn.start(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); topic = ActiveMQJMSClient.createTopic(T_NAME); - MessageConsumer cons = session.createSharedConsumer(topic, "test1"); MessageProducer producer = session.createProducer(topic); @@ -562,14 +513,12 @@ public class ConsumerTest extends JMSTestBase } @Test - public void testSharedDurableConsumer() throws Exception - { + public void testSharedDurableConsumer() throws Exception { conn = cf.createConnection(); conn.start(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); topic = ActiveMQJMSClient.createTopic(T_NAME); - MessageConsumer cons = session.createSharedDurableConsumer(topic, "test1"); MessageProducer producer = session.createProducer(topic); @@ -582,8 +531,7 @@ public class ConsumerTest extends JMSTestBase } @Test - public void testSharedDurableConsumerWithClientID() throws Exception - { + public void testSharedDurableConsumerWithClientID() throws Exception { conn = cf.createConnection(); conn.setClientID("C1"); conn.start(); @@ -597,12 +545,10 @@ public class ConsumerTest extends JMSTestBase Connection conn3 = cf.createConnection(); boolean exception = false; - try - { + try { conn3.setClientID("C2"); } - catch (Exception e) - { + catch (Exception e) { exception = true; } @@ -612,7 +558,6 @@ public class ConsumerTest extends JMSTestBase topic = ActiveMQJMSClient.createTopic(T_NAME); - MessageConsumer cons = session.createSharedDurableConsumer(topic, "test1"); MessageProducer producer = session.createProducer(topic); @@ -625,8 +570,7 @@ public class ConsumerTest extends JMSTestBase } @Test - public void testValidateExceptionsThroughSharedConsumers() throws Exception - { + public void testValidateExceptionsThroughSharedConsumers() throws Exception { conn = cf.createConnection(); conn.setClientID("C1"); conn.start(); @@ -634,21 +578,17 @@ public class ConsumerTest extends JMSTestBase Connection conn2 = cf.createConnection(); conn2.setClientID("C2"); - MessageConsumer cons = session.createSharedConsumer(topic, "cons1"); boolean exceptionHappened = false; - try - { + try { MessageConsumer cons2Error = session.createSharedConsumer(topic2, "cons1"); } - catch (JMSException e) - { + catch (JMSException e) { exceptionHappened = true; } Assert.assertTrue(exceptionHappened); - MessageProducer producer = session.createProducer(topic2); // This is durable, different than the one on topic... So it should go through @@ -656,24 +596,19 @@ public class ConsumerTest extends JMSTestBase conn.start(); - producer.send(session.createTextMessage("hello!")); TextMessage msg = (TextMessage) cons2.receive(5000); Assert.assertNotNull(msg); - exceptionHappened = false; - try - { + try { session.unsubscribe("cons1"); } - catch (JMSException e) - { + catch (JMSException e) { exceptionHappened = true; } - Assert.assertTrue(exceptionHappened); cons2.close(); conn.close(); @@ -682,8 +617,7 @@ public class ConsumerTest extends JMSTestBase } @Test - public void testUnsubscribeDurable() throws Exception - { + public void testUnsubscribeDurable() throws Exception { conn = cf.createConnection(); conn.setClientID("C1"); conn.start(); @@ -693,8 +627,7 @@ public class ConsumerTest extends JMSTestBase MessageProducer prod = session.createProducer(topic); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { prod.send(session.createTextMessage("msg" + i)); } @@ -711,8 +644,7 @@ public class ConsumerTest extends JMSTestBase } @Test - public void testShareDurale() throws Exception - { + public void testShareDurale() throws Exception { ((ActiveMQConnectionFactory) cf).setConsumerWindowSize(0); conn = cf.createConnection(); conn.start(); @@ -724,14 +656,11 @@ public class ConsumerTest extends JMSTestBase MessageProducer prod = session.createProducer(topic); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { prod.send(session.createTextMessage("msg" + i)); } - - for (int i = 0; i < 50; i++) - { + for (int i = 0; i < 50; i++) { Message msg = cons.receive(5000); Assert.assertNotNull(msg); msg = cons2.receive(5000); @@ -745,12 +674,10 @@ public class ConsumerTest extends JMSTestBase boolean exceptionHappened = false; - try - { + try { session.unsubscribe("c1"); } - catch (JMSException e) - { + catch (JMSException e) { exceptionHappened = true; } @@ -758,12 +685,10 @@ public class ConsumerTest extends JMSTestBase cons2.close(); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { prod.send(session.createTextMessage("msg" + i)); } - session.unsubscribe("c1"); cons = session.createSharedDurableConsumer(topic, "c1"); @@ -772,10 +697,8 @@ public class ConsumerTest extends JMSTestBase Assert.assertNull(cons.receiveNoWait()); } - @Test - public void testShareDuraleWithJMSContext() throws Exception - { + public void testShareDuraleWithJMSContext() throws Exception { ((ActiveMQConnectionFactory) cf).setConsumerWindowSize(0); JMSContext conn = cf.createContext(JMSContext.AUTO_ACKNOWLEDGE); @@ -783,17 +706,14 @@ public class ConsumerTest extends JMSTestBase JMSProducer producer = conn.createProducer(); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { producer.setProperty("count", i).send(topic, "test" + i); } - JMSContext conn2 = conn.createContext(JMSContext.AUTO_ACKNOWLEDGE); JMSConsumer consumer2 = conn2.createSharedDurableConsumer(topic, "c1"); - for (int i = 0; i < 50; i++) - { + for (int i = 0; i < 50; i++) { String txt = consumer.receiveBody(String.class, 5000); System.out.println("TXT:" + txt); Assert.assertNotNull(txt); @@ -808,13 +728,10 @@ public class ConsumerTest extends JMSTestBase boolean exceptionHappened = false; - - try - { + try { conn.unsubscribe("c1"); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); exceptionHappened = true; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/divert/DivertAndACKClientTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/divert/DivertAndACKClientTest.java index 2193111110..fc7190503b 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/divert/DivertAndACKClientTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/divert/DivertAndACKClientTest.java @@ -38,12 +38,10 @@ import java.util.List; * * https://jira.jboss.org/jira/browse/HORNETQ-165 */ -public class DivertAndACKClientTest extends JMSTestBase -{ +public class DivertAndACKClientTest extends JMSTestBase { @Test - public void testAutoACK() throws Exception - { + public void testAutoACK() throws Exception { Queue queueSource = createQueue("Source"); Queue queueTarget = createQueue("Dest"); @@ -58,7 +56,7 @@ public class DivertAndACKClientTest extends JMSTestBase connection.start(); final MessageConsumer consumer = session.createConsumer(queueTarget); - TextMessage receivedMessage = (TextMessage)consumer.receive(1000); + TextMessage receivedMessage = (TextMessage) consumer.receive(1000); Assert.assertNotNull(receivedMessage); @@ -66,8 +64,7 @@ public class DivertAndACKClientTest extends JMSTestBase } @Test - public void testClientACK() throws Exception - { + public void testClientACK() throws Exception { Queue queueSource = createQueue("Source"); Queue queueTarget = createQueue("Dest"); @@ -82,7 +79,7 @@ public class DivertAndACKClientTest extends JMSTestBase connection.start(); final MessageConsumer consumer = session.createConsumer(queueTarget); - TextMessage receivedMessage = (TextMessage)consumer.receive(1000); + TextMessage receivedMessage = (TextMessage) consumer.receive(1000); Assert.assertNotNull(receivedMessage); receivedMessage.acknowledge(); @@ -90,71 +87,29 @@ public class DivertAndACKClientTest extends JMSTestBase } @Override - protected boolean usePersistence() - { + protected boolean usePersistence() { return true; } @Override - protected Configuration createDefaultConfig(final boolean netty) throws Exception - { - DivertConfiguration divert = new DivertConfiguration() - .setName("local-divert") - .setRoutingName("some-name") - .setAddress("jms.queue.Source") - .setForwardingAddress("jms.queue.Dest") - .setExclusive(true); + protected Configuration createDefaultConfig(final boolean netty) throws Exception { + DivertConfiguration divert = new DivertConfiguration().setName("local-divert").setRoutingName("some-name").setAddress("jms.queue.Source").setForwardingAddress("jms.queue.Dest").setExclusive(true); - Configuration config = super.createDefaultConfig(netty) - .addDivertConfiguration(divert); + Configuration config = super.createDefaultConfig(netty).addDivertConfiguration(divert); return config; } @Override protected void createCF(final List connectorConfigs, - final String ... jndiBindings) throws Exception - { + final String... jndiBindings) throws Exception { int retryInterval = 1000; double retryIntervalMultiplier = 1.0; int reconnectAttempts = -1; int callTimeout = 30000; - jmsServer.createConnectionFactory("ManualReconnectionToSingleServerTest", - false, - JMSFactoryType.CF, - registerConnectors(server, connectorConfigs), - null, - ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, - ActiveMQClient.DEFAULT_CONNECTION_TTL, - callTimeout, - ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, - ActiveMQClient.DEFAULT_CACHE_LARGE_MESSAGE_CLIENT, - ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES, - ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, - ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, - true, // this test needs to block on ACK - ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, - ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, - ActiveMQClient.DEFAULT_AUTO_GROUP, - ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, - ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, - retryInterval, - retryIntervalMultiplier, - ActiveMQClient.DEFAULT_MAX_RETRY_INTERVAL, - reconnectAttempts, - ActiveMQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION, - null, - jndiBindings); + jmsServer.createConnectionFactory("ManualReconnectionToSingleServerTest", false, JMSFactoryType.CF, registerConnectors(server, connectorConfigs), null, ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, ActiveMQClient.DEFAULT_CONNECTION_TTL, callTimeout, ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, ActiveMQClient.DEFAULT_CACHE_LARGE_MESSAGE_CLIENT, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES, ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, true, // this test needs to block on ACK + ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, ActiveMQClient.DEFAULT_AUTO_GROUP, ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, retryInterval, retryIntervalMultiplier, ActiveMQClient.DEFAULT_MAX_RETRY_INTERVAL, reconnectAttempts, ActiveMQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION, null, jndiBindings); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/jms2client/BodyTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/jms2client/BodyTest.java index ec95cdd504..88de391b8c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/jms2client/BodyTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/jms2client/BodyTest.java @@ -29,17 +29,14 @@ import org.apache.activemq.artemis.tests.util.JMSTestBase; import org.junit.Before; import org.junit.Test; -public class BodyTest extends JMSTestBase -{ +public class BodyTest extends JMSTestBase { private static final String Q_NAME = "SomeQueue"; private javax.jms.Queue queue; - @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); jmsServer.createQueue(false, Q_NAME, null, true, Q_NAME); @@ -47,12 +44,10 @@ public class BodyTest extends JMSTestBase } @Test - public void testBodyConversion() throws Throwable - { + public void testBodyConversion() throws Throwable { try ( Connection conn = cf.createConnection(); - ) - { + ) { Session sess = conn.createSession(); MessageProducer producer = sess.createProducer(queue); @@ -66,13 +61,11 @@ public class BodyTest extends JMSTestBase Message msg = cons.receiveNoWait(); assertNotNull(msg); - try - { + try { msg.getBody(String.class); fail("Exception expected"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/jms2client/InvalidDestinationTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/jms2client/InvalidDestinationTest.java index d76f51d088..f2f0f3899f 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/jms2client/InvalidDestinationTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/jms2client/InvalidDestinationTest.java @@ -34,23 +34,21 @@ import org.apache.activemq.artemis.tests.util.JMSTestBase; import org.junit.Before; import org.junit.Test; -public class InvalidDestinationTest extends JMSTestBase -{ +public class InvalidDestinationTest extends JMSTestBase { + private JMSContext context; private Queue queue1; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); context = createContext(); queue1 = createQueue(JmsContextTest.class.getSimpleName() + "Queue"); } @Test - public void invalidDestinationRuntimeExceptionTests() throws Exception - { + public void invalidDestinationRuntimeExceptionTests() throws Exception { JMSProducer producer = context.createProducer(); Destination invalidDestination = null; Topic invalidTopic = null; @@ -62,324 +60,252 @@ public class InvalidDestinationTest extends JMSTestBase mapMsgSend.put("i", 1); TextMessage expTextMessage = context.createTextMessage(message); - try - { + try { producer.send(invalidDestination, expTextMessage); } - catch (InvalidDestinationRuntimeException e) - { + catch (InvalidDestinationRuntimeException e) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("Expected InvalidDestinationRuntimeException, received " + e); } - try - { + try { producer.send(invalidDestination, message); } - catch (InvalidDestinationRuntimeException e) - { + catch (InvalidDestinationRuntimeException e) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("Expected InvalidDestinationRuntimeException, received " + e); } ObjectMessage om = context.createObjectMessage(); StringBuffer sb = new StringBuffer(message); om.setObject(sb); - try - { + try { producer.send(invalidDestination, om); } - catch (InvalidDestinationRuntimeException e) - { + catch (InvalidDestinationRuntimeException e) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("Expected InvalidDestinationRuntimeException, received " + e); } - try - { + try { producer.send(invalidDestination, bytesMsgSend); } - catch (InvalidDestinationRuntimeException e) - { + catch (InvalidDestinationRuntimeException e) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("Expected InvalidDestinationRuntimeException, received " + e); } - try - { + try { producer.send(invalidDestination, mapMsgSend); } - catch (InvalidDestinationRuntimeException e) - { + catch (InvalidDestinationRuntimeException e) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("Expected InvalidDestinationRuntimeException, received " + e); } - try - { + try { context.createConsumer(invalidDestination); } - catch (InvalidDestinationRuntimeException e) - { + catch (InvalidDestinationRuntimeException e) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("Expected InvalidDestinationRuntimeException, received " + e); } - try - { + try { context.createConsumer(invalidDestination, "lastMessage = TRUE"); } - catch (InvalidDestinationRuntimeException e) - { + catch (InvalidDestinationRuntimeException e) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("Expected InvalidDestinationRuntimeException, received " + e); } - try - { + try { context.createConsumer(invalidDestination, "lastMessage = TRUE", false); } - catch (InvalidDestinationRuntimeException e) - { + catch (InvalidDestinationRuntimeException e) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("Expected InvalidDestinationRuntimeException, received " + e); } - try - { + try { context.createDurableConsumer(invalidTopic, "InvalidDestinationRuntimeException"); } - catch (InvalidDestinationRuntimeException e) - { + catch (InvalidDestinationRuntimeException e) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("Expected InvalidDestinationRuntimeException, received " + e); } - try - { + try { context.createDurableConsumer(invalidTopic, "InvalidDestinationRuntimeException", "lastMessage = TRUE", false); } - catch (InvalidDestinationRuntimeException e) - { + catch (InvalidDestinationRuntimeException e) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("Expected InvalidDestinationRuntimeException, received " + e); } - try - { + try { context.createSharedDurableConsumer(invalidTopic, "InvalidDestinationRuntimeException"); } - catch (InvalidDestinationRuntimeException e) - { + catch (InvalidDestinationRuntimeException e) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("Expected InvalidDestinationRuntimeException, received " + e); } - try - { + try { context.createSharedDurableConsumer(invalidTopic, "InvalidDestinationRuntimeException", "lastMessage = TRUE"); } - catch (InvalidDestinationRuntimeException e) - { + catch (InvalidDestinationRuntimeException e) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("Expected InvalidDestinationRuntimeException, received " + e); } - try - { + try { context.unsubscribe("InvalidSubscriptionName"); } - catch (InvalidDestinationRuntimeException e) - { + catch (InvalidDestinationRuntimeException e) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("Expected InvalidDestinationRuntimeException, received " + e); } - try - { + try { context.createSharedConsumer(invalidTopic, "InvalidDestinationRuntimeException"); } - catch (InvalidDestinationRuntimeException e) - { + catch (InvalidDestinationRuntimeException e) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("Expected InvalidDestinationRuntimeException, received " + e); } - try - { + try { context.createSharedConsumer(invalidTopic, "InvalidDestinationRuntimeException", "lastMessage = TRUE"); } - catch (InvalidDestinationRuntimeException e) - { + catch (InvalidDestinationRuntimeException e) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("Expected InvalidDestinationRuntimeException, received " + e); } } @Test - public void invalidDestinationExceptionTests() throws Exception - { + public void invalidDestinationExceptionTests() throws Exception { Destination invalidDestination = null; Topic invalidTopic = null; Connection conn = cf.createConnection(); - try - { + try { Session session = conn.createSession(); - try - { + try { session.createDurableSubscriber(invalidTopic, "InvalidDestinationException"); } - catch (InvalidDestinationException e) - { + catch (InvalidDestinationException e) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("Expected InvalidDestinationException, received " + e); } - try - { + try { session.createDurableSubscriber(invalidTopic, "InvalidDestinationException", "lastMessage = TRUE", false); } - catch (InvalidDestinationException e) - { + catch (InvalidDestinationException e) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("Expected InvalidDestinationException, received " + e); } System.out.println("Testing Session.createDurableConsumer(Topic, String) for InvalidDestinationException"); - try - { + try { session.createDurableConsumer(invalidTopic, "InvalidDestinationException"); } - catch (InvalidDestinationException e) - { + catch (InvalidDestinationException e) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("Expected InvalidDestinationException, received " + e); } - try - { + try { session.createDurableConsumer(invalidTopic, "InvalidDestinationException", "lastMessage = TRUE", false); } - catch (InvalidDestinationException e) - { + catch (InvalidDestinationException e) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("Expected InvalidDestinationException, received " + e); } - try - { + try { session.createSharedConsumer(invalidTopic, "InvalidDestinationException"); } - catch (InvalidDestinationException e) - { + catch (InvalidDestinationException e) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("Expected InvalidDestinationException, received " + e); } - try - { + try { session.createSharedConsumer(invalidTopic, "InvalidDestinationException", "lastMessage = TRUE"); } - catch (InvalidDestinationException e) - { + catch (InvalidDestinationException e) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("Expected InvalidDestinationException, received " + e); } - try - { + try { session.createSharedDurableConsumer(invalidTopic, "InvalidDestinationException"); } - catch (InvalidDestinationException e) - { + catch (InvalidDestinationException e) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("Expected InvalidDestinationException, received " + e); } - try - { + try { session.createSharedDurableConsumer(invalidTopic, "InvalidDestinationException", "lastMessage = TRUE"); } - catch (InvalidDestinationException e) - { + catch (InvalidDestinationException e) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("Expected InvalidDestinationException, received " + e); } } - finally - { + finally { conn.close(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/jms2client/JmsContextTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/jms2client/JmsContextTest.java index 8226f79cd5..58b284b8ee 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/jms2client/JmsContextTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/jms2client/JmsContextTest.java @@ -45,8 +45,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class JmsContextTest extends JMSTestBase -{ +public class JmsContextTest extends JMSTestBase { private JMSContext context; private final Random random = new Random(); @@ -54,22 +53,19 @@ public class JmsContextTest extends JMSTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); context = createContext(); queue1 = createQueue(JmsContextTest.class.getSimpleName() + "Queue"); } @Test - public void testCreateContext() - { + public void testCreateContext() { Assert.assertNotNull(context); } @Test - public void testRollbackTest() - { + public void testRollbackTest() { JMSContext ctx = addContext(cf.createContext(JMSContext.SESSION_TRANSACTED)); JMSProducer producer = ctx.createProducer(); @@ -95,12 +91,10 @@ public class JmsContextTest extends JMSTestBase cons.close(); - } @Test - public void testDupsOK() - { + public void testDupsOK() { JMSContext ctx = addContext(cf.createContext(JMSContext.DUPS_OK_ACKNOWLEDGE)); assertEquals(JMSContext.DUPS_OK_ACKNOWLEDGE, ctx.getSessionMode()); @@ -119,8 +113,7 @@ public class JmsContextTest extends JMSTestBase } @Test - public void testReceiveBytes() throws Exception - { + public void testReceiveBytes() throws Exception { JMSProducer producer = context.createProducer(); JMSConsumer consumer = context.createConsumer(queue1); @@ -145,8 +138,7 @@ public class JmsContextTest extends JMSTestBase } @Test - public void testReceiveText() throws Exception - { + public void testReceiveText() throws Exception { JMSProducer producer = context.createProducer(); JMSConsumer consumer = context.createConsumer(queue1); @@ -158,7 +150,6 @@ public class JmsContextTest extends JMSTestBase TextMessage sendMsg = context.createTextMessage(randomStr); producer.send(queue1, sendMsg); - TextMessage receiveMsg = (TextMessage) consumer.receiveNoWait(); assertEquals(randomStr, receiveMsg.getText()); @@ -166,8 +157,7 @@ public class JmsContextTest extends JMSTestBase } @Test - public void testDelay() throws Exception - { + public void testDelay() throws Exception { JMSProducer producer = context.createProducer(); JMSConsumer consumer = context.createConsumer(queue1); @@ -191,8 +181,7 @@ public class JmsContextTest extends JMSTestBase } @Test - public void testExpire() throws Exception - { + public void testExpire() throws Exception { JMSProducer producer = context.createProducer(); producer.setTimeToLive(500); @@ -236,8 +225,7 @@ public class JmsContextTest extends JMSTestBase } @Test - public void testDeliveryMode() throws Exception - { + public void testDeliveryMode() throws Exception { JMSProducer producer = context.createProducer(); JMSConsumer consumer = context.createConsumer(queue1); @@ -257,39 +245,32 @@ public class JmsContextTest extends JMSTestBase } @Test - public void testInvalidMessage() - { + public void testInvalidMessage() { JMSProducer producer = context.createProducer(); - try - { + try { producer.send(queue1, (Message) null); Assert.fail("null msg"); } - catch (MessageFormatRuntimeException expected) - { + catch (MessageFormatRuntimeException expected) { // no-op } } @Test - public void testInvalidDestination() - { + public void testInvalidDestination() { JMSProducer producer = context.createProducer(); Message msg = context.createMessage(); - try - { + try { producer.send((Destination) null, msg); Assert.fail("null Destination"); } - catch (InvalidDestinationRuntimeException expected) - { + catch (InvalidDestinationRuntimeException expected) { // no-op } } @Test - public void testSendStreamMessage() throws JMSException, InterruptedException - { + public void testSendStreamMessage() throws JMSException, InterruptedException { JmsProducerCompletionListenerTest.CountingCompletionListener cl = new JmsProducerCompletionListenerTest.CountingCompletionListener(1); JMSProducer producer = context.createProducer(); producer.setAsync(cl); @@ -314,33 +295,28 @@ public class JmsContextTest extends JMSTestBase } @Test - public void testSetClientIdLate() - { + public void testSetClientIdLate() { JMSProducer producer = context.createProducer(); Message msg = context.createMessage(); producer.send(queue1, msg); - try - { + try { context.setClientID("id"); Assert.fail("expected exception"); } - catch (IllegalStateRuntimeException e) - { + catch (IllegalStateRuntimeException e) { // no op } } @Test - public void testCloseSecondContextConnectionRemainsOpen() throws JMSException - { + public void testCloseSecondContextConnectionRemainsOpen() throws JMSException { JMSContext localContext = context.createContext(JMSContext.CLIENT_ACKNOWLEDGE); Assert.assertEquals("client_ack", JMSContext.CLIENT_ACKNOWLEDGE, localContext.getSessionMode()); JMSProducer producer = localContext.createProducer(); JMSConsumer consumer = localContext.createConsumer(queue1); final int pass = 1; - for (int idx = 0; idx < 2; idx++) - { + for (int idx = 0; idx < 2; idx++) { Message m = localContext.createMessage(); int intProperty = random.nextInt(); m.setIntProperty("random", intProperty); @@ -351,8 +327,7 @@ public class JmsContextTest extends JMSTestBase Assert.assertNotNull("must have a msg", msg); Assert.assertEquals(intProperty, msg.getIntProperty("random")); /* In the second pass we close the connection before ack'ing */ - if (idx == pass) - { + if (idx == pass) { localContext.close(); } /** @@ -361,49 +336,42 @@ public class JmsContextTest extends JMSTestBase * session must throw an {@code IllegalStateRuntimeException}. Closing a closed connection * must NOT throw an exception. */ - try - { + try { msg.acknowledge(); Assert.assertEquals("connection should be open on pass 0. It is " + pass, 0, idx); } // HORNETQ-1209 "JMS 2.0" XXX JMSContext javadoc says we must expect a // IllegalStateRuntimeException here. But Message.ack...() says it must throws the // non-runtime variant. - catch (javax.jms.IllegalStateException expected) - { + catch (javax.jms.IllegalStateException expected) { Assert.assertEquals("we only close the connection on pass " + pass, pass, idx); } } } @Test(expected = JMSRuntimeException.class) - public void testInvalidSessionModesValueMinusOne() - { + public void testInvalidSessionModesValueMinusOne() { context.createContext(-1); } @Test(expected = JMSRuntimeException.class) - public void testInvalidSessionModesValue4() - { + public void testInvalidSessionModesValue4() { context.createContext(4); } @Test - public void testGetAnotherContextFromIt() - { + public void testGetAnotherContextFromIt() { JMSContext c2 = context.createContext(Session.DUPS_OK_ACKNOWLEDGE); Assert.assertNotNull(c2); Assert.assertEquals(Session.DUPS_OK_ACKNOWLEDGE, c2.getSessionMode()); Message m2 = c2.createMessage(); Assert.assertNotNull(m2); c2.close(); // should close its session, but not its (shared) connection - try - { + try { c2.createMessage(); Assert.fail("session should be closed..."); } - catch (JMSRuntimeException expected) - { + catch (JMSRuntimeException expected) { // expected } Message m1 = context.createMessage(); @@ -411,8 +379,7 @@ public class JmsContextTest extends JMSTestBase } @Test - public void testSetGetClientIdNewContext() - { + public void testSetGetClientIdNewContext() { final String id = "123"; JMSContext c = context;// createContext(); c.setClientID(id); @@ -421,8 +388,7 @@ public class JmsContextTest extends JMSTestBase } @Test - public void testGetClientId() - { + public void testGetClientId() { JMSContext context2 = addContext(context.createContext(Session.AUTO_ACKNOWLEDGE)); final String id = "ID: " + random.nextInt(); context.setClientID(id); @@ -430,15 +396,13 @@ public class JmsContextTest extends JMSTestBase } @Test - public void testCreateConsumerWithSelector() throws JMSException - { + public void testCreateConsumerWithSelector() throws JMSException { final String filterName = "magicIndexMessage"; final int total = 5; JMSProducer producer = context.createProducer(); JMSConsumer consumerNoSelect = context.createConsumer(queue1); JMSConsumer consumer = context.createConsumer(queue1, filterName + "=TRUE"); - for (int i = 0; i < total; i++) - { + for (int i = 0; i < total; i++) { Message msg = context.createTextMessage("message " + i); msg.setBooleanProperty(filterName, i == 3); producer.send(queue1, msg); @@ -447,8 +411,7 @@ public class JmsContextTest extends JMSTestBase Assert.assertNotNull(msg0); msg0.acknowledge(); Assert.assertNull("no more messages", consumer.receiveNoWait()); - for (int i = 0; i < total - 1; i++) - { + for (int i = 0; i < total - 1; i++) { Message msg = consumerNoSelect.receive(100); Assert.assertNotNull(msg); msg.acknowledge(); @@ -457,8 +420,7 @@ public class JmsContextTest extends JMSTestBase } @Test - public void testContextStopAndCloseFromMessageListeners() throws Exception - { + public void testContextStopAndCloseFromMessageListeners() throws Exception { final JMSContext context1 = context.createContext(Session.AUTO_ACKNOWLEDGE); JMSConsumer consumer1 = context1.createConsumer(queue1); @@ -507,18 +469,14 @@ public class JmsContextTest extends JMSTestBase } @Test - public void recoverAckTest() throws Exception - { + public void recoverAckTest() throws Exception { // Create JMSContext with CLIENT_ACKNOWLEDGE - - try (JMSContext context = cf.createContext(JMSContext.CLIENT_ACKNOWLEDGE)) - { + try (JMSContext context = cf.createContext(JMSContext.CLIENT_ACKNOWLEDGE)) { int numMessages = 10; TextMessage textMessage = null; - // Create JMSConsumer from JMSContext JMSConsumer consumer = context.createConsumer(queue1); @@ -526,8 +484,7 @@ public class JmsContextTest extends JMSTestBase JMSProducer producer = context.createProducer(); // send messages - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { String message = "text message " + i; textMessage = context.createTextMessage(message); textMessage.setStringProperty("COM_SUN_JMS_TESTNAME", "recoverAckTest" + i); @@ -535,8 +492,7 @@ public class JmsContextTest extends JMSTestBase } // receive messages but do not acknowledge - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { textMessage = (TextMessage) consumer.receive(5000); assertNotNull(textMessage); } @@ -544,8 +500,7 @@ public class JmsContextTest extends JMSTestBase context.recover(); // receive messages a second time followed by acknowledge - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { textMessage = (TextMessage) consumer.receive(5000); assertNotNull(textMessage); } @@ -555,8 +510,7 @@ public class JmsContextTest extends JMSTestBase } // doing this check with another context / consumer to make sure it was acked. - try (JMSContext context = cf.createContext(JMSContext.CLIENT_ACKNOWLEDGE)) - { + try (JMSContext context = cf.createContext(JMSContext.CLIENT_ACKNOWLEDGE)) { // Create JMSConsumer from JMSContext JMSConsumer consumer = context.createConsumer(queue1); @@ -565,11 +519,9 @@ public class JmsContextTest extends JMSTestBase } @Test - public void bytesMessage() throws Exception - { + public void bytesMessage() throws Exception { context = cf.createContext(); - try - { + try { JMSProducer producer = context.createProducer(); BytesMessage bMsg = context.createBytesMessage(); bMsg.setStringProperty("COM_SUN_JMS_TESTNAME", "sendAndRecvMsgOfEachTypeCLTest"); @@ -583,15 +535,13 @@ public class JmsContextTest extends JMSTestBase assertEquals(listener.message.readByte(), (byte) 1); assertEquals(listener.message.readInt(), 22); } - finally - { + finally { context.close(); } } @Test - public void illegalStateRuntimeExceptionTests() throws Exception - { + public void illegalStateRuntimeExceptionTests() throws Exception { JMSProducer producer = context.createProducer(); JMSConsumer consumer = context.createConsumer(queue1); System.out.println("Creating TextMessage"); @@ -604,54 +554,47 @@ public class JmsContextTest extends JMSTestBase assertNull(listener.ex); } - private static class SimpleCompletionListener implements CompletionListener - { + private static class SimpleCompletionListener implements CompletionListener { + private CountDownLatch latch; private BytesMessage message; - public SimpleCompletionListener(CountDownLatch latch) - { + public SimpleCompletionListener(CountDownLatch latch) { this.latch = latch; } @Override - public void onCompletion(Message message) - { + public void onCompletion(Message message) { this.message = (BytesMessage) message; latch.countDown(); } @Override - public void onException(Message message, Exception exception) - { + public void onException(Message message, Exception exception) { //To change body of implemented methods use File | Settings | File Templates. } } - private static class InvalidMessageListener implements MessageListener - { + private static class InvalidMessageListener implements MessageListener { + private int id; private CountDownLatch latch; private JMSContext context; private volatile Throwable error; - public InvalidMessageListener(JMSContext context, CountDownLatch latch, int id) - { + public InvalidMessageListener(JMSContext context, CountDownLatch latch, int id) { this.id = id; this.latch = latch; this.context = context; } - public Throwable getError() - { + public Throwable getError() { return error; } @Override - public void onMessage(Message arg0) - { - switch (id) - { + public void onMessage(Message arg0) { + switch (id) { case 1: stopContext(); break; @@ -664,61 +607,50 @@ public class JmsContextTest extends JMSTestBase latch.countDown(); } - private void stopContext() - { - try - { + private void stopContext() { + try { context.stop(); } - catch (Throwable t) - { + catch (Throwable t) { error = t; } } - private void closeContext() - { - try - { + private void closeContext() { + try { context.close(); } - catch (Throwable t) - { + catch (Throwable t) { error = t; } } } - private class JMSCOntextStopCompletionListener implements CompletionListener - { + private class JMSCOntextStopCompletionListener implements CompletionListener { + private JMSContext context; private CountDownLatch latch; private Exception ex; - public JMSCOntextStopCompletionListener(JMSContext context, CountDownLatch latch) - { + public JMSCOntextStopCompletionListener(JMSContext context, CountDownLatch latch) { this.context = context; this.latch = latch; } @Override - public void onCompletion(Message message) - { - try - { + public void onCompletion(Message message) { + try { context.stop(); } - catch (Exception e) - { + catch (Exception e) { this.ex = e; } latch.countDown(); } @Override - public void onException(Message message, Exception exception) - { + public void onException(Message message, Exception exception) { } } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/jms2client/JmsProducerCompletionListenerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/jms2client/JmsProducerCompletionListenerTest.java index 5f599f72bd..5d11e45cc7 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/jms2client/JmsProducerCompletionListenerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/jms2client/JmsProducerCompletionListenerTest.java @@ -41,8 +41,8 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(Parameterized.class) -public class JmsProducerCompletionListenerTest extends JMSTestBase -{ +public class JmsProducerCompletionListenerTest extends JMSTestBase { + static final int TOTAL_MSGS = 20; private JMSContext context; @@ -52,26 +52,22 @@ public class JmsProducerCompletionListenerTest extends JMSTestBase private final int confirmationWindowSize; @Parameterized.Parameters(name = "confirmationWindowSize={0}") - public static Iterable data() - { + public static Iterable data() { return Arrays.asList(new Object[][]{{-1}, {0}, {10}, {1000}}); } - public JmsProducerCompletionListenerTest(int confirmationWindowSize) - { + public JmsProducerCompletionListenerTest(int confirmationWindowSize) { this.confirmationWindowSize = confirmationWindowSize; } @Override - protected void testCaseCfExtraConfig(ConnectionFactoryConfiguration configuration) - { + protected void testCaseCfExtraConfig(ConnectionFactoryConfiguration configuration) { configuration.setConfirmationWindowSize(confirmationWindowSize); } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); context = createContext(); producer = context.createProducer(); @@ -79,8 +75,7 @@ public class JmsProducerCompletionListenerTest extends JMSTestBase } @Test - public void testCompletionListener() throws InterruptedException - { + public void testCompletionListener() throws InterruptedException { CountingCompletionListener cl = new CountingCompletionListener(TOTAL_MSGS); Assert.assertEquals(null, producer.getAsync()); producer.setAsync(cl); @@ -96,37 +91,30 @@ public class JmsProducerCompletionListenerTest extends JMSTestBase } @Test - public void testNullCompletionListener() throws Exception - { + public void testNullCompletionListener() throws Exception { Connection connection = null; - try - { + try { connection = cf.createConnection(); Session session = connection.createSession(); MessageProducer prod = session.createProducer(queue); prod.send(session.createMessage(), null); Assert.fail("Didn't get expected exception!"); } - catch (IllegalArgumentException expected) - { + catch (IllegalArgumentException expected) { //ok } - finally - { - if (connection != null) - { + finally { + if (connection != null) { connection.close(); } } } @Test - public void testInvalidCallFromListener() throws InterruptedException - { + public void testInvalidCallFromListener() throws InterruptedException { JMSConsumer consumer = context.createConsumer(queue); List listeners = new ArrayList(); - for (int i = 0; i < 3; i++) - { + for (int i = 0; i < 3; i++) { InvalidCompletionListener cl = new InvalidCompletionListener(context, i); listeners.add(cl); producer.setAsync(cl); @@ -134,16 +122,14 @@ public class JmsProducerCompletionListenerTest extends JMSTestBase } receiveMessages(consumer, 0, 1, true); context.close(); - for (InvalidCompletionListener cl : listeners) - { + for (InvalidCompletionListener cl : listeners) { Assert.assertTrue(cl.latch.await(1, TimeUnit.SECONDS)); Assert.assertNotNull(cl.error); Assert.assertTrue(cl.error instanceof IllegalStateRuntimeException); } } - public static final class InvalidCompletionListener implements CompletionListener - { + public static final class InvalidCompletionListener implements CompletionListener { private final JMSContext context; public final CountDownLatch latch = new CountDownLatch(1); @@ -154,20 +140,16 @@ public class JmsProducerCompletionListenerTest extends JMSTestBase * @param context * @param call */ - public InvalidCompletionListener(JMSContext context, int call) - { + public InvalidCompletionListener(JMSContext context, int call) { this.call = call; this.context = context; } @Override - public void onCompletion(Message message) - { + public void onCompletion(Message message) { latch.countDown(); - try - { - switch (call) - { + try { + switch (call) { case 0: context.rollback(); break; @@ -181,50 +163,43 @@ public class JmsProducerCompletionListenerTest extends JMSTestBase throw new IllegalArgumentException("call code " + call); } } - catch (Exception error1) - { + catch (Exception error1) { this.error = error1; } } @Override - public void onException(Message message, Exception exception) - { + public void onException(Message message, Exception exception) { // TODO Auto-generated method stub } } - public static final class CountingCompletionListener implements CompletionListener - { + public static final class CountingCompletionListener implements CompletionListener { public int completion; public int error; public CountDownLatch completionLatch; public Message lastMessage; - public CountingCompletionListener(int n) - { + public CountingCompletionListener(int n) { completionLatch = new CountDownLatch(n); } @Override - public void onCompletion(Message message) - { + public void onCompletion(Message message) { completion++; completionLatch.countDown(); lastMessage = message; } @Override - public void onException(Message message, Exception exception) - { + public void onException(Message message, Exception exception) { error++; } @Override - public String toString() - { + public String toString() { return JmsProducerCompletionListenerTest.class.getSimpleName() + ":" + CountingCompletionListener.class.getSimpleName() + ":" + completionLatch; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/jms2client/NonExistentQueueTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/jms2client/NonExistentQueueTest.java index a8afa8cbe4..913ef9a1d1 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/jms2client/NonExistentQueueTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/jms2client/NonExistentQueueTest.java @@ -38,8 +38,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class NonExistentQueueTest extends JMSTestBase -{ +public class NonExistentQueueTest extends JMSTestBase { private JMSContext context; private final Random random = new Random(); @@ -47,32 +46,26 @@ public class NonExistentQueueTest extends JMSTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); context = createContext(); queue = createQueue(JmsContextTest.class.getSimpleName() + "Queue1"); } - @Test - public void sendToNonExistentDestination() throws Exception - { + public void sendToNonExistentDestination() throws Exception { Destination destination = ActiveMQJMSClient.createTopic("DoesNotExist"); TransportConfiguration transportConfiguration = new TransportConfiguration(InVMConnectorFactory.class.getName()); - ConnectionFactory localConnectionFactory = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, - transportConfiguration); + ConnectionFactory localConnectionFactory = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, transportConfiguration); // Using JMS 1 API Connection connection = localConnectionFactory.createConnection(); Session session = connection.createSession(); - try - { + try { MessageProducer messageProducer = session.createProducer(null); messageProducer.send(destination, session.createMessage()); Assert.fail("Succeeded in sending message to a non-existent destination using JMS 1 API!"); } - catch (JMSException e) - { // Expected } + catch (JMSException e) { // Expected } } @@ -80,15 +73,12 @@ public class NonExistentQueueTest extends JMSTestBase JMSContext context = localConnectionFactory.createContext(); JMSProducer jmsProducer = context.createProducer().setDeliveryMode(DeliveryMode.PERSISTENT); - try - { + try { jmsProducer.send(destination, context.createMessage()); Assert.fail("Succeeded in sending message to a non-existent destination using JMS 2 API!"); } - catch (JMSRuntimeException e) - { // Expected } + catch (JMSRuntimeException e) { // Expected } } - } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/jms2client/SharedConsumerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/jms2client/SharedConsumerTest.java index deeec33673..ad58314ec1 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/jms2client/SharedConsumerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/jms2client/SharedConsumerTest.java @@ -29,8 +29,8 @@ import org.apache.activemq.artemis.tests.util.JMSTestBase; import org.junit.Before; import org.junit.Test; -public class SharedConsumerTest extends JMSTestBase -{ +public class SharedConsumerTest extends JMSTestBase { + private JMSContext context; private final Random random = new Random(); private Topic topic1; @@ -38,8 +38,7 @@ public class SharedConsumerTest extends JMSTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); context = createContext(); topic1 = createTopic(JmsContextTest.class.getSimpleName() + "Topic1"); @@ -47,23 +46,19 @@ public class SharedConsumerTest extends JMSTestBase } @Test - public void sharedDurableSubSimpleRoundRobin() throws Exception - { + public void sharedDurableSubSimpleRoundRobin() throws Exception { context = cf.createContext(); - try - { + try { JMSConsumer con1 = context.createSharedDurableConsumer(topic1, "mySharedCon"); JMSConsumer con2 = context.createSharedDurableConsumer(topic1, "mySharedCon"); context.start(); JMSProducer producer = context.createProducer(); int numMessages = 10; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { producer.send(topic1, "msg:" + i); } - for (int i = 0; i < numMessages; i += 2) - { + for (int i = 0; i < numMessages; i += 2) { String msg = con1.receiveBody(String.class, 5000); System.out.println("msg = " + msg); msg = con2.receiveBody(String.class, 5000); @@ -71,18 +66,15 @@ public class SharedConsumerTest extends JMSTestBase } } - finally - { + finally { context.close(); } } @Test - public void sharedDurableUnsubscribeNewTopic() throws Exception - { + public void sharedDurableUnsubscribeNewTopic() throws Exception { context = cf.createContext(); - try - { + try { JMSConsumer con1 = context.createSharedDurableConsumer(topic1, "mySharedCon"); JMSConsumer con2 = context.createSharedDurableConsumer(topic1, "mySharedCon"); con1.close(); @@ -90,18 +82,15 @@ public class SharedConsumerTest extends JMSTestBase context.unsubscribe("mySharedCon"); con1 = context.createSharedDurableConsumer(topic2, "mySharedCon"); } - finally - { + finally { context.close(); } } @Test - public void sharedNonDurableUnsubscribeDifferentTopic() throws Exception - { + public void sharedNonDurableUnsubscribeDifferentTopic() throws Exception { context = cf.createContext(); - try - { + try { JMSConsumer con1 = context.createSharedConsumer(topic1, "mySharedCon"); JMSConsumer con2 = context.createSharedConsumer(topic1, "mySharedCon"); con1.close(); @@ -112,198 +101,154 @@ public class SharedConsumerTest extends JMSTestBase assertNull(binding); con1 = context.createSharedConsumer(topic2, "mySharedCon"); } - finally - { + finally { context.close(); } } @Test - public void sharedNonDurableSubOnDifferentSelector() throws Exception - { + public void sharedNonDurableSubOnDifferentSelector() throws Exception { context = cf.createContext(); - try - { + try { context.createSharedConsumer(topic1, "mySharedCon", "sel = 'sel1'"); - try - { + try { context.createSharedConsumer(topic1, "mySharedCon", "sel = 'sel2'"); fail("expected JMSRuntimeException"); } - catch (JMSRuntimeException jmse) - { + catch (JMSRuntimeException jmse) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("threw wrong exception expected JMSRuntimeException got " + e); } } - finally - { + finally { context.close(); } } @Test - public void sharedNonDurableSubOnDifferentSelectorSrcFilterNull() throws Exception - { + public void sharedNonDurableSubOnDifferentSelectorSrcFilterNull() throws Exception { context = cf.createContext(); - try - { + try { context.createSharedConsumer(topic1, "mySharedCon"); - try - { + try { context.createSharedConsumer(topic1, "mySharedCon", "sel = 'sel2'"); fail("expected JMSRuntimeException"); } - catch (JMSRuntimeException jmse) - { + catch (JMSRuntimeException jmse) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("threw wrong exception expected JMSRuntimeException got " + e); } } - finally - { + finally { context.close(); } } @Test - public void sharedNonDurableSubOnDifferentSelectorTargetFilterNull() throws Exception - { + public void sharedNonDurableSubOnDifferentSelectorTargetFilterNull() throws Exception { context = cf.createContext(); - try - { + try { context.createSharedConsumer(topic1, "mySharedCon", "sel = 'sel1'"); - try - { + try { context.createSharedConsumer(topic1, "mySharedCon"); fail("expected JMSRuntimeException"); } - catch (JMSRuntimeException jmse) - { + catch (JMSRuntimeException jmse) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("threw wrong exception expected JMSRuntimeException got " + e); } } - finally - { + finally { context.close(); } } - @Test - public void sharedDurableSubOnDifferentTopic() throws Exception - { + public void sharedDurableSubOnDifferentTopic() throws Exception { context = cf.createContext(); - try - { + try { context.createSharedDurableConsumer(topic1, "mySharedCon"); - try - { + try { context.createSharedDurableConsumer(topic2, "mySharedCon"); fail("expected JMSRuntimeException"); } - catch (JMSRuntimeException jmse) - { + catch (JMSRuntimeException jmse) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("threw wrong exception expected JMSRuntimeException got " + e); } } - finally - { + finally { context.close(); } } @Test - public void sharedDurableSubOnDifferentSelector() throws Exception - { + public void sharedDurableSubOnDifferentSelector() throws Exception { context = cf.createContext(); - try - { + try { context.createSharedDurableConsumer(topic1, "mySharedCon", "sel = 'sel1'"); - try - { + try { context.createSharedDurableConsumer(topic1, "mySharedCon", "sel = 'sel2'"); fail("expected JMSRuntimeException"); } - catch (JMSRuntimeException jmse) - { + catch (JMSRuntimeException jmse) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("threw wrong exception expected JMSRuntimeException got " + e); } } - finally - { + finally { context.close(); } } @Test - public void sharedDurableSubOnDifferentSelectorSrcFilterNull() throws Exception - { + public void sharedDurableSubOnDifferentSelectorSrcFilterNull() throws Exception { context = cf.createContext(); - try - { + try { context.createSharedDurableConsumer(topic1, "mySharedCon"); - try - { + try { context.createSharedDurableConsumer(topic1, "mySharedCon", "sel = 'sel2'"); fail("expected JMSRuntimeException"); } - catch (JMSRuntimeException jmse) - { + catch (JMSRuntimeException jmse) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("threw wrong exception expected JMSRuntimeException got " + e); } } - finally - { + finally { context.close(); } } @Test - public void sharedDurableSubOnDifferentSelectorTargetFilterNull() throws Exception - { + public void sharedDurableSubOnDifferentSelectorTargetFilterNull() throws Exception { context = cf.createContext(); - try - { + try { context.createSharedDurableConsumer(topic1, "mySharedCon", "sel = 'sel1'"); - try - { + try { context.createSharedDurableConsumer(topic1, "mySharedCon"); fail("expected JMSRuntimeException"); } - catch (JMSRuntimeException jmse) - { + catch (JMSRuntimeException jmse) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("threw wrong exception expected JMSRuntimeException got " + e); } } - finally - { + finally { context.close(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/largemessage/JMSLargeMessageTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/largemessage/JMSLargeMessageTest.java index 74d2ae1f6a..36f3bd5ca3 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/largemessage/JMSLargeMessageTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/largemessage/JMSLargeMessageTest.java @@ -37,8 +37,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; -public class JMSLargeMessageTest extends JMSTestBase -{ +public class JMSLargeMessageTest extends JMSTestBase { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -52,22 +51,19 @@ public class JMSLargeMessageTest extends JMSTestBase // Public -------------------------------------------------------- @Override - protected boolean usePersistence() - { + protected boolean usePersistence() { return true; } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); queue1 = createQueue("queue1"); } @Test - public void testSimpleLargeMessage() throws Exception - { + public void testSimpleLargeMessage() throws Exception { conn = cf.createConnection(); @@ -97,12 +93,10 @@ public class JMSLargeMessageTest extends JMSTestBase System.out.println("Message = " + rm); - for (int i = 0; i < 1024 * 1024; i += 1024) - { + for (int i = 0; i < 1024 * 1024; i += 1024) { int numberOfBytes = rm.readBytes(data); Assert.assertEquals(1024, numberOfBytes); - for (int j = 0; j < 1024; j++) - { + for (int j = 0; j < 1024; j++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i + j), data[j]); } } @@ -111,8 +105,7 @@ public class JMSLargeMessageTest extends JMSTestBase } @Test - public void testSimpleLargeMessage2() throws Exception - { + public void testSimpleLargeMessage2() throws Exception { conn = cf.createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -143,8 +136,7 @@ public class JMSLargeMessageTest extends JMSTestBase int numberOfBytes = rm.readBytes(data); Assert.assertEquals(10, numberOfBytes); - for (int j = 0; j < numberOfBytes; j++) - { + for (int j = 0; j < numberOfBytes; j++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(j), data[j]); } @@ -152,21 +144,18 @@ public class JMSLargeMessageTest extends JMSTestBase } @Test - public void testExceptionsOnSettingNonStreaming() throws Exception - { + public void testExceptionsOnSettingNonStreaming() throws Exception { conn = cf.createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); TextMessage msg = session.createTextMessage(); - try - { + try { msg.setObjectProperty("JMS_AMQ_InputStream", ActiveMQTestBase.createFakeLargeStream(10)); Assert.fail("Exception was expected"); } - catch (JMSException e) - { + catch (JMSException e) { } msg.setText("hello"); @@ -187,21 +176,17 @@ public class JMSLargeMessageTest extends JMSTestBase TextMessage rm = (TextMessage) cons.receive(10000); - try - { - rm.setObjectProperty("JMS_AMQ_OutputStream", new OutputStream() - { + try { + rm.setObjectProperty("JMS_AMQ_OutputStream", new OutputStream() { @Override - public void write(final int b) throws IOException - { + public void write(final int b) throws IOException { System.out.println("b = " + b); } }); Assert.fail("Exception was expected"); } - catch (JMSException e) - { + catch (JMSException e) { } Assert.assertEquals("hello", rm.getText()); @@ -211,8 +196,7 @@ public class JMSLargeMessageTest extends JMSTestBase } @Test - public void testWaitOnOutputStream() throws Exception - { + public void testWaitOnOutputStream() throws Exception { int msgSize = 1024 * 1024; conn = cf.createConnection(); @@ -244,17 +228,14 @@ public class JMSLargeMessageTest extends JMSTestBase final AtomicInteger numberOfErrors = new AtomicInteger(0); - OutputStream out = new OutputStream() - { + OutputStream out = new OutputStream() { int position = 0; @Override - public void write(final int b) throws IOException - { + public void write(final int b) throws IOException { numberOfBytes.incrementAndGet(); - if (ActiveMQTestBase.getSamplebyte(position++) != b) - { + if (ActiveMQTestBase.getSamplebyte(position++) != b) { System.out.println("Wrong byte at position " + position); numberOfErrors.incrementAndGet(); } @@ -262,13 +243,11 @@ public class JMSLargeMessageTest extends JMSTestBase }; - try - { + try { rm.setObjectProperty("JMS_AMQ_InputStream", ActiveMQTestBase.createFakeLargeStream(100)); Assert.fail("Exception expected!"); } - catch (MessageNotWriteableException expected) - { + catch (MessageNotWriteableException expected) { } rm.setObjectProperty("JMS_AMQ_SaveStream", out); @@ -279,10 +258,8 @@ public class JMSLargeMessageTest extends JMSTestBase } - @Test - public void testHugeString() throws Exception - { + public void testHugeString() throws Exception { int msgSize = 1024 * 1024; conn = cf.createConnection(); @@ -294,8 +271,7 @@ public class JMSLargeMessageTest extends JMSTestBase TextMessage m = session.createTextMessage(); StringBuffer buffer = new StringBuffer(); - while (buffer.length() < msgSize) - { + while (buffer.length() < msgSize) { buffer.append(UUIDGenerator.getInstance().generateStringUUID()); } @@ -337,18 +313,16 @@ public class JMSLargeMessageTest extends JMSTestBase // Inner classes ------------------------------------------------- - class ThreadReader extends Thread - { + class ThreadReader extends Thread { + CountDownLatch latch; - ThreadReader(final CountDownLatch latch) - { + ThreadReader(final CountDownLatch latch) { this.latch = latch; } @Override - public void run() - { + public void run() { } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/JMSServerDeployerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/JMSServerDeployerTest.java index a7d1a2de32..f85de1583d 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/JMSServerDeployerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/JMSServerDeployerTest.java @@ -36,8 +36,7 @@ import javax.jms.Queue; import javax.jms.Topic; import javax.naming.Context; -public class JMSServerDeployerTest extends ActiveMQTestBase -{ +public class JMSServerDeployerTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @@ -57,8 +56,7 @@ public class JMSServerDeployerTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testDeployUnusualQueueNames() throws Exception - { + public void testDeployUnusualQueueNames() throws Exception { doTestDeployQueuesWithUnusualNames("queue.with.dots.in.name", "/myqueue"); doTestDeployQueuesWithUnusualNames("queue with spaces in name", "/myqueue2"); @@ -67,13 +65,11 @@ public class JMSServerDeployerTest extends ActiveMQTestBase doTestDeployQueuesWithUnusualNames("queue\\with\\backslashes\\in\\name", "/myqueue4"); - doTestDeployQueuesWithUnusualNames("queue with # chars and * chars in name", - "/myqueue5"); + doTestDeployQueuesWithUnusualNames("queue with # chars and * chars in name", "/myqueue5"); } @Test - public void testDeployUnusualTopicNames() throws Exception - { + public void testDeployUnusualTopicNames() throws Exception { doTestDeployTopicsWithUnusualNames("topic.with.dots.in.name", "/mytopic"); doTestDeployTopicsWithUnusualNames("topic with spaces in name", "/mytopic2"); @@ -82,13 +78,10 @@ public class JMSServerDeployerTest extends ActiveMQTestBase doTestDeployTopicsWithUnusualNames("topic\\with\\backslashes\\in\\name", "/mytopic4"); - doTestDeployTopicsWithUnusualNames("topic with # chars and * chars in name", - "/mytopic5"); + doTestDeployTopicsWithUnusualNames("topic with # chars and * chars in name", "/mytopic5"); } - private void doTestDeployQueuesWithUnusualNames(final String queueName, - final String jndiName) throws Exception - { + private void doTestDeployQueuesWithUnusualNames(final String queueName, final String jndiName) throws Exception { jmsServer.createQueue(false, queueName, null, false, jndiName); Queue queue = (Queue) context.lookup(jndiName); @@ -96,9 +89,7 @@ public class JMSServerDeployerTest extends ActiveMQTestBase Assert.assertEquals(queueName, queue.getQueueName()); } - private void doTestDeployTopicsWithUnusualNames(final String topicName, - final String jndiName) throws Exception - { + private void doTestDeployTopicsWithUnusualNames(final String topicName, final String jndiName) throws Exception { jmsServer.createTopic(false, topicName, jndiName); Topic topic = (Topic) context.lookup(jndiName); @@ -112,22 +103,12 @@ public class JMSServerDeployerTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - DiscoveryGroupConfiguration dcg = new DiscoveryGroupConfiguration() - .setName("mygroup") - .setRefreshTimeout(5432) - .setDiscoveryInitialWaitTimeout(5432) - .setBroadcastEndpointFactory(new UDPBroadcastEndpointFactory() - .setGroupAddress("243.7.7.7") - .setGroupPort(12345) - .setLocalBindAddress("172.16.8.10")); + DiscoveryGroupConfiguration dcg = new DiscoveryGroupConfiguration().setName("mygroup").setRefreshTimeout(5432).setDiscoveryInitialWaitTimeout(5432).setBroadcastEndpointFactory(new UDPBroadcastEndpointFactory().setGroupAddress("243.7.7.7").setGroupPort(12345).setLocalBindAddress("172.16.8.10")); - config = createBasicConfig() - .addConnectorConfiguration("netty", new TransportConfiguration(NettyConnectorFactory.class.getName())) - .addDiscoveryGroupConfiguration("mygroup", dcg); + config = createBasicConfig().addConnectorConfiguration("netty", new TransportConfiguration(NettyConnectorFactory.class.getName())).addDiscoveryGroupConfiguration("mygroup", dcg); ActiveMQServer server = createServer(false, config); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/JMSServerStartStopTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/JMSServerStartStopTest.java index 65a6ab65b5..64f052c43a 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/JMSServerStartStopTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/JMSServerStartStopTest.java @@ -44,8 +44,8 @@ import javax.jms.TextMessage; import java.util.HashSet; import java.util.Set; -public class JMSServerStartStopTest extends ActiveMQTestBase -{ +public class JMSServerStartStopTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private JMSServerManager jmsServer; @@ -57,8 +57,7 @@ public class JMSServerStartStopTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { FileConfiguration fc = new FileConfiguration(); FileJMSConfiguration fileConfiguration = new FileJMSConfiguration(); FileDeploymentManager deploymentManager = new FileDeploymentManager("server-start-stop-config1.xml"); @@ -75,12 +74,10 @@ public class JMSServerStartStopTest extends ActiveMQTestBase } @Test - public void testStopStart1() throws Exception - { + public void testStopStart1() throws Exception { final int numMessages = 5; - for (int j = 0; j < numMessages; j++) - { + for (int j = 0; j < numMessages; j++) { JMSServerStartStopTest.log.info("Iteration " + j); jmsServer.start(); @@ -91,8 +88,7 @@ public class JMSServerStartStopTest extends ActiveMQTestBase jbcf.setBlockOnNonDurableSend(true); Connection conn = jbcf.createConnection(); - try - { + try { Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = sess.createQueue("myJMSQueue"); @@ -103,8 +99,7 @@ public class JMSServerStartStopTest extends ActiveMQTestBase producer.send(tm); } - finally - { + finally { conn.close(); jbcf.close(); @@ -130,8 +125,7 @@ public class JMSServerStartStopTest extends ActiveMQTestBase conn.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage tm = (TextMessage) consumer.receive(10000); Assert.assertNotNull("not null", tm); @@ -146,8 +140,7 @@ public class JMSServerStartStopTest extends ActiveMQTestBase // https://jira.jboss.org/jira/browse/HORNETQ-315 @Test - public void testCloseConnectionAfterServerIsShutdown() throws Exception - { + public void testCloseConnectionAfterServerIsShutdown() throws Exception { jmsServer.start(); jbcf = createConnectionFactory(); @@ -165,11 +158,8 @@ public class JMSServerStartStopTest extends ActiveMQTestBase /** * @return */ - private ActiveMQConnectionFactory createConnectionFactory() - { - ActiveMQConnectionFactory cf = - ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, - new TransportConfiguration(NETTY_CONNECTOR_FACTORY)); + private ActiveMQConnectionFactory createConnectionFactory() { + ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(NETTY_CONNECTOR_FACTORY)); connectionFactories.add(cf); return cf; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/config/JMSConfigurationTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/config/JMSConfigurationTest.java index d4778220a1..bb659c6900 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/config/JMSConfigurationTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/config/JMSConfigurationTest.java @@ -44,11 +44,10 @@ import javax.naming.Context; import java.util.ArrayList; import java.util.List; -public class JMSConfigurationTest extends ActiveMQTestBase -{ +public class JMSConfigurationTest extends ActiveMQTestBase { + @Test - public void testSetupJMSConfiguration() throws Exception - { + public void testSetupJMSConfiguration() throws Exception { Context context = new InVMNamingContext(); ActiveMQServer coreServer = new ActiveMQServerImpl(createDefaultInVMConfig()); @@ -58,24 +57,12 @@ public class JMSConfigurationTest extends ActiveMQTestBase List transportConfigs = new ArrayList(); transportConfigs.add(connectorConfig); - ConnectionFactoryConfiguration cfConfig = new ConnectionFactoryConfigurationImpl() - .setName(RandomUtil.randomString()) - .setConnectorNames(registerConnectors(coreServer, transportConfigs)) - .setBindings("/cf/binding1", "/cf/binding2"); + ConnectionFactoryConfiguration cfConfig = new ConnectionFactoryConfigurationImpl().setName(RandomUtil.randomString()).setConnectorNames(registerConnectors(coreServer, transportConfigs)).setBindings("/cf/binding1", "/cf/binding2"); jmsConfiguration.getConnectionFactoryConfigurations().add(cfConfig); - JMSQueueConfigurationImpl queueConfig = new JMSQueueConfigurationImpl() - .setName(RandomUtil.randomString()) - .setDurable(false) - .setBindings( - "/queue/binding1", - "/queue/binding2"); + JMSQueueConfigurationImpl queueConfig = new JMSQueueConfigurationImpl().setName(RandomUtil.randomString()).setDurable(false).setBindings("/queue/binding1", "/queue/binding2"); jmsConfiguration.getQueueConfigurations().add(queueConfig); - TopicConfiguration topicConfig = new TopicConfigurationImpl() - .setName(RandomUtil.randomString()) - .setBindings( - "/topic/binding1", - "/topic/binding2"); + TopicConfiguration topicConfig = new TopicConfigurationImpl().setName(RandomUtil.randomString()).setBindings("/topic/binding1", "/topic/binding2"); jmsConfiguration.getTopicConfigurations().add(topicConfig); JMSServerManager server = new JMSServerManagerImpl(coreServer, jmsConfiguration); @@ -83,31 +70,28 @@ public class JMSConfigurationTest extends ActiveMQTestBase server.setRegistry(new JndiBindingRegistry(context)); server.start(); - for (String binding : cfConfig.getBindings()) - { + for (String binding : cfConfig.getBindings()) { Object o = context.lookup(binding); Assert.assertNotNull(o); Assert.assertTrue(o instanceof ConnectionFactory); - ConnectionFactory cf = (ConnectionFactory)o; + ConnectionFactory cf = (ConnectionFactory) o; Connection connection = cf.createConnection(); connection.close(); } - for (String binding : queueConfig.getBindings()) - { + for (String binding : queueConfig.getBindings()) { Object o = context.lookup(binding); Assert.assertNotNull(o); Assert.assertTrue(o instanceof Queue); - Queue queue = (Queue)o; + Queue queue = (Queue) o; Assert.assertEquals(queueConfig.getName(), queue.getQueueName()); } - for (String binding : topicConfig.getBindings()) - { + for (String binding : topicConfig.getBindings()) { Object o = context.lookup(binding); Assert.assertNotNull(o); Assert.assertTrue(o instanceof Topic); - Topic topic = (Topic)o; + Topic topic = (Topic) o; Assert.assertEquals(topicConfig.getName(), topic.getTopicName()); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/config/JMSServerConfigParserTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/config/JMSServerConfigParserTest.java index 8ef0e0b633..31719362cc 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/config/JMSServerConfigParserTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/config/JMSServerConfigParserTest.java @@ -26,8 +26,7 @@ import org.apache.activemq.artemis.jms.server.config.JMSQueueConfiguration; import org.apache.activemq.artemis.jms.server.config.TopicConfiguration; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -public class JMSServerConfigParserTest extends ActiveMQTestBase -{ +public class JMSServerConfigParserTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -39,10 +38,8 @@ public class JMSServerConfigParserTest extends ActiveMQTestBase // Public -------------------------------------------------------- - @Test - public void testParsing() throws Exception - { + public void testParsing() throws Exception { Configuration config = createDefaultInVMConfig() // anything so the parsing will work .addConnectorConfiguration("netty", new TransportConfiguration()); @@ -59,12 +56,10 @@ public class JMSServerConfigParserTest extends ActiveMQTestBase JMSQueueConfiguration queueConfig = jmsconfig.getQueueConfigurations().get(0); assertEquals("fullConfigurationQueue", queueConfig.getName()); - assertEquals(1, jmsconfig.getTopicConfigurations().size()); TopicConfiguration topicConfig = jmsconfig.getTopicConfigurations().get(0); assertEquals("fullConfigurationTopic", topicConfig.getName()); - } // Package protected --------------------------------------------- diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/ConnectionFactoryControlTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/ConnectionFactoryControlTest.java index 289404fef0..4873c92884 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/ConnectionFactoryControlTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/ConnectionFactoryControlTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.jms.server.management; + import java.util.ArrayList; import java.util.List; @@ -42,8 +43,7 @@ import org.apache.activemq.artemis.jms.server.management.JMSNotificationType; /** * A Connection Factory Control Test */ -public class ConnectionFactoryControlTest extends ManagementTestBase -{ +public class ConnectionFactoryControlTest extends ManagementTestBase { // Constants ----------------------------------------------------- @@ -62,20 +62,19 @@ public class ConnectionFactoryControlTest extends ManagementTestBase // Public -------------------------------------------------------- @Test - public void testCreateCF() throws Exception - { + public void testCreateCF() throws Exception { JMSServerControl control = createJMSControl(); control.createConnectionFactory("test", false, false, 0, "invm", "test"); ConnectionFactoryControl controlCF = createCFControl("test"); - ActiveMQConnectionFactory cf = (ActiveMQConnectionFactory)ctx.lookup("test"); + ActiveMQConnectionFactory cf = (ActiveMQConnectionFactory) ctx.lookup("test"); Assert.assertFalse(cf.isCompressLargeMessage()); controlCF.setCompressLargeMessages(true); - cf = (ActiveMQConnectionFactory)ctx.lookup("test"); + cf = (ActiveMQConnectionFactory) ctx.lookup("test"); Assert.assertTrue(cf.isCompressLargeMessage()); server.stop(); @@ -84,7 +83,7 @@ public class ConnectionFactoryControlTest extends ManagementTestBase startServer(); - cf = (ActiveMQConnectionFactory)ctx.lookup("test"); + cf = (ActiveMQConnectionFactory) ctx.lookup("test"); Assert.assertTrue(cf.isCompressLargeMessage()); } @@ -92,19 +91,14 @@ public class ConnectionFactoryControlTest extends ManagementTestBase //make sure notifications are always received no matter whether //a CF is created via JMSServerControl or by JMSServerManager directly. @Test - public void testCreateCFNotification() throws Exception - { + public void testCreateCFNotification() throws Exception { JMSUtil.JMXListener listener = new JMSUtil.JMXListener(); this.mbeanServer.addNotificationListener(ObjectNameBuilder.DEFAULT.getJMSServerObjectName(), listener, null, null); List connectors = new ArrayList(); connectors.add("invm"); - this.jmsServerManager.createConnectionFactory("NewCF", - false, - JMSFactoryType.CF, - connectors, - "/NewConnectionFactory"); + this.jmsServerManager.createConnectionFactory("NewCF", false, JMSFactoryType.CF, connectors, "/NewConnectionFactory"); Notification notif = listener.getNotification(); @@ -132,16 +126,13 @@ public class ConnectionFactoryControlTest extends ManagementTestBase Assert.assertEquals("test", notif.getMessage()); } - - // Package protected --------------------------------------------- // Protected ----------------------------------------------------- @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); startServer(); @@ -151,11 +142,8 @@ public class ConnectionFactoryControlTest extends ManagementTestBase /** * @throws Exception */ - protected void startServer() throws Exception - { - Configuration config = createDefaultInVMConfig() - .addConnectorConfiguration("invm", new TransportConfiguration(INVM_CONNECTOR_FACTORY)) - .setJMXManagementEnabled(true); + protected void startServer() throws Exception { + Configuration config = createDefaultInVMConfig().addConnectorConfiguration("invm", new TransportConfiguration(INVM_CONNECTOR_FACTORY)).setJMXManagementEnabled(true); server = addServer(ActiveMQServers.newActiveMQServer(config, mbeanServer, true)); server.start(); @@ -168,13 +156,11 @@ public class ConnectionFactoryControlTest extends ManagementTestBase jmsServerManager.activated(); } - protected ConnectionFactoryControl createCFControl(String name) throws Exception - { + protected ConnectionFactoryControl createCFControl(String name) throws Exception { return ManagementControlHelper.createConnectionFactoryControl(name, mbeanServer); } - protected JMSServerControl createJMSControl() throws Exception - { + protected JMSServerControl createJMSControl() throws Exception { return ManagementControlHelper.createJMSServerControl(mbeanServer); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSMessagingProxy.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSMessagingProxy.java index a0783e6645..2606b31542 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSMessagingProxy.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSMessagingProxy.java @@ -24,8 +24,7 @@ import javax.jms.Session; import org.apache.activemq.artemis.api.jms.management.JMSManagementHelper; -public class JMSMessagingProxy -{ +public class JMSMessagingProxy { // Constants ----------------------------------------------------- @@ -41,8 +40,9 @@ public class JMSMessagingProxy // Constructors -------------------------------------------------- - public JMSMessagingProxy(final QueueSession session, final Queue managementQueue, final String resourceName) throws Exception - { + public JMSMessagingProxy(final QueueSession session, + final Queue managementQueue, + final String resourceName) throws Exception { this.session = session; this.resourceName = resourceName; @@ -56,33 +56,27 @@ public class JMSMessagingProxy // Protected ----------------------------------------------------- - public Object retrieveAttributeValue(final String attributeName) - { - try - { + public Object retrieveAttributeValue(final String attributeName) { + try { Message m = session.createMessage(); JMSManagementHelper.putAttribute(m, resourceName, attributeName); Message reply = requestor.request(m); return JMSManagementHelper.getResult(reply); } - catch (Exception e) - { + catch (Exception e) { throw new IllegalStateException(e); } } - public Object invokeOperation(final String operationName, final Object... args) throws Exception - { + public Object invokeOperation(final String operationName, final Object... args) throws Exception { Message m = session.createMessage(); JMSManagementHelper.putOperationInvocation(m, resourceName, operationName, args); Message reply = requestor.request(m); - if (JMSManagementHelper.hasOperationSucceeded(reply)) - { + if (JMSManagementHelper.hasOperationSucceeded(reply)) { return JMSManagementHelper.getResult(reply); } - else - { - throw new Exception((String)JMSManagementHelper.getResult(reply)); + else { + throw new Exception((String) JMSManagementHelper.getResult(reply)); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSQueueControlTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSQueueControlTest.java index 39c932e795..b98a165cbe 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSQueueControlTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSQueueControlTest.java @@ -70,8 +70,8 @@ import java.util.Set; *
    * on this testContaining WithRealData will use real data on the journals */ -public class JMSQueueControlTest extends ManagementTestBase -{ +public class JMSQueueControlTest extends ManagementTestBase { + private ActiveMQServer server; private JMSServerManagerImpl serverManager; @@ -83,8 +83,7 @@ public class JMSQueueControlTest extends ManagementTestBase protected Context context; @Test - public void testGetAttributes() throws Exception - { + public void testGetAttributes() throws Exception { JMSQueueControl queueControl = createManagementControl(); Assert.assertEquals(queue.getName(), queueControl.getName()); @@ -93,8 +92,7 @@ public class JMSQueueControlTest extends ManagementTestBase } @Test - public void testGetXXXCount() throws Exception - { + public void testGetXXXCount() throws Exception { JMSQueueControl queueControl = createManagementControl(); Assert.assertEquals(0, getMessageCount(queueControl)); @@ -130,8 +128,7 @@ public class JMSQueueControlTest extends ManagementTestBase } @Test - public void testListMessagesWithNullFilter() throws Exception - { + public void testListMessagesWithNullFilter() throws Exception { JMSQueueControl queueControl = createManagementControl(); Assert.assertEquals(0, getMessageCount(queueControl)); @@ -153,16 +150,14 @@ public class JMSQueueControlTest extends ManagementTestBase } @Test - public void testListDeliveringMessages() throws Exception - { + public void testListDeliveringMessages() throws Exception { JMSQueueControl queueControl = createManagementControl(); Assert.assertEquals(0, queueControl.getMessageCount()); String[] ids = JMSUtil.sendMessages(queue, 20); - ActiveMQJMSConnectionFactory cf = (ActiveMQJMSConnectionFactory)ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, - new TransportConfiguration(InVMConnectorFactory.class.getName())); + ActiveMQJMSConnectionFactory cf = (ActiveMQJMSConnectionFactory) ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(InVMConnectorFactory.class.getName())); Connection conn = cf.createConnection(); conn.start(); @@ -170,9 +165,7 @@ public class JMSQueueControlTest extends ManagementTestBase MessageConsumer consumer = session.createConsumer(queue); - - for (int i = 0; i < 20; i++) - { + for (int i = 0; i < 20; i++) { Assert.assertNotNull(consumer.receive(5000)); } @@ -183,19 +176,14 @@ public class JMSQueueControlTest extends ManagementTestBase // Just one consumer.. so just one queue Assert.assertEquals(1, deliverings.size()); - - for (Map.Entry[]> deliveryEntry : deliverings.entrySet()) - { + for (Map.Entry[]> deliveryEntry : deliverings.entrySet()) { System.out.println("Key:" + deliveryEntry.getKey()); - for (int i = 0; i < 20; i++) - { + for (int i = 0; i < 20; i++) { Assert.assertEquals(ids[i], deliveryEntry.getValue()[i].get("JMSMessageID").toString()); } } - - session.rollback(); session.close(); @@ -203,8 +191,7 @@ public class JMSQueueControlTest extends ManagementTestBase } @Test - public void testListMessagesAsJSONWithNullFilter() throws Exception - { + public void testListMessagesAsJSONWithNullFilter() throws Exception { JMSQueueControl queueControl = createManagementControl(); Assert.assertEquals(0, getMessageCount(queueControl)); @@ -229,8 +216,7 @@ public class JMSQueueControlTest extends ManagementTestBase } @Test - public void testRemoveMessage() throws Exception - { + public void testRemoveMessage() throws Exception { JMSQueueControl queueControl = createManagementControl(); Assert.assertEquals(0, getMessageCount(queueControl)); @@ -246,8 +232,7 @@ public class JMSQueueControlTest extends ManagementTestBase // retrieve the first message info Set keySet = data[0].keySet(); Iterator it = keySet.iterator(); - while (it.hasNext()) - { + while (it.hasNext()) { System.out.println(it.next()); } String messageID = (String) data[0].get("JMSMessageID"); @@ -258,27 +243,23 @@ public class JMSQueueControlTest extends ManagementTestBase } @Test - public void testRemoveMessageWithUnknownMessage() throws Exception - { + public void testRemoveMessageWithUnknownMessage() throws Exception { String unknownMessageID = RandomUtil.randomString(); JMSQueueControl queueControl = createManagementControl(); Assert.assertEquals(0, getMessageCount(queueControl)); - try - { + try { queueControl.removeMessage(unknownMessageID); Assert.fail("should throw an exception is the message ID is unknown"); } - catch (Exception e) - { + catch (Exception e) { } } @Test - public void testRemoveAllMessages() throws Exception - { + public void testRemoveAllMessages() throws Exception { JMSQueueControl queueControl = createManagementControl(); Assert.assertEquals(0, getMessageCount(queueControl)); @@ -301,8 +282,7 @@ public class JMSQueueControlTest extends ManagementTestBase } @Test - public void testRemoveMatchingMessages() throws Exception - { + public void testRemoveMatchingMessages() throws Exception { JMSQueueControl queueControl = createManagementControl(); Assert.assertEquals(0, getMessageCount(queueControl)); @@ -337,8 +317,7 @@ public class JMSQueueControlTest extends ManagementTestBase } @Test - public void testChangeMessagePriority() throws Exception - { + public void testChangeMessagePriority() throws Exception { JMSQueueControl queueControl = createManagementControl(); JMSUtil.sendMessages(queue, 1); @@ -366,8 +345,7 @@ public class JMSQueueControlTest extends ManagementTestBase } @Test - public void testChangeMessagePriorityWithInvalidPriority() throws Exception - { + public void testChangeMessagePriorityWithInvalidPriority() throws Exception { byte invalidPriority = (byte) 23; JMSQueueControl queueControl = createManagementControl(); @@ -376,13 +354,11 @@ public class JMSQueueControlTest extends ManagementTestBase Assert.assertEquals(1, getMessageCount(queueControl)); - try - { + try { queueControl.changeMessagePriority(messageIDs[0], invalidPriority); Assert.fail("must throw an exception if the new priority is not a valid value"); } - catch (Exception e) - { + catch (Exception e) { } Connection connection = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); @@ -396,25 +372,21 @@ public class JMSQueueControlTest extends ManagementTestBase } @Test - public void testChangeMessagePriorityWithUnknownMessageID() throws Exception - { + public void testChangeMessagePriorityWithUnknownMessageID() throws Exception { String unknownMessageID = RandomUtil.randomString(); JMSQueueControl queueControl = createManagementControl(); - try - { + try { queueControl.changeMessagePriority(unknownMessageID, 7); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { } } @Test - public void testChangeMessagesPriority() throws Exception - { + public void testChangeMessagesPriority() throws Exception { String key = "key"; long matchingValue = RandomUtil.randomLong(); long unmatchingValue = matchingValue + 1; @@ -453,21 +425,18 @@ public class JMSQueueControlTest extends ManagementTestBase } @Test - public void testGetExpiryAddress() throws Exception - { + public void testGetExpiryAddress() throws Exception { final SimpleString expiryAddress = RandomUtil.randomSimpleString(); JMSQueueControl queueControl = createManagementControl(); Assert.assertNull(queueControl.getExpiryAddress()); - server.getAddressSettingsRepository().addMatch(queue.getAddress(), new AddressSettings() - { + server.getAddressSettingsRepository().addMatch(queue.getAddress(), new AddressSettings() { private static final long serialVersionUID = -7668739851356971411L; @Override - public SimpleString getExpiryAddress() - { + public SimpleString getExpiryAddress() { return expiryAddress; } }); @@ -476,8 +445,7 @@ public class JMSQueueControlTest extends ManagementTestBase } @Test - public void testSetExpiryAddress() throws Exception - { + public void testSetExpiryAddress() throws Exception { final String expiryAddress = RandomUtil.randomString(); JMSQueueControl queueControl = createManagementControl(); @@ -491,18 +459,15 @@ public class JMSQueueControlTest extends ManagementTestBase } @Test - public void testDuplicateJNDI() throws Exception - { + public void testDuplicateJNDI() throws Exception { String someQueue = RandomUtil.randomString(); String someOtherQueue = RandomUtil.randomString(); serverManager.createQueue(false, someQueue, null, true, someQueue, "/duplicate"); boolean exception = false; - try - { + try { serverManager.createQueue(false, someOtherQueue, null, true, someOtherQueue, "/duplicate"); } - catch (Exception e) - { + catch (Exception e) { exception = true; } @@ -510,8 +475,7 @@ public class JMSQueueControlTest extends ManagementTestBase } @Test - public void testExpireMessage() throws Exception - { + public void testExpireMessage() throws Exception { JMSQueueControl queueControl = createManagementControl(); String expiryQueueName = RandomUtil.randomString(); ActiveMQQueue expiryQueue = (ActiveMQQueue) ActiveMQJMSClient.createQueue(expiryQueueName); @@ -519,7 +483,7 @@ public class JMSQueueControlTest extends ManagementTestBase AddressSettings addressSettings = new AddressSettings().setExpiryAddress(new SimpleString(expiryQueue.getAddress())); server.getAddressSettingsRepository().addMatch(queue.getAddress(), addressSettings); -// queueControl.setExpiryAddress(expiryQueue.getAddress()); + // queueControl.setExpiryAddress(expiryQueue.getAddress()); JMSQueueControl expiryQueueControl = ManagementControlHelper.createJMSQueueControl(expiryQueue, mbeanServer); @@ -545,25 +509,21 @@ public class JMSQueueControlTest extends ManagementTestBase } @Test - public void testExpireMessageWithUnknownMessageID() throws Exception - { + public void testExpireMessageWithUnknownMessageID() throws Exception { String unknownMessageID = RandomUtil.randomString(); JMSQueueControl queueControl = createManagementControl(); - try - { + try { queueControl.expireMessage(unknownMessageID); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { } } @Test - public void testExpireMessagesWithFilter() throws Exception - { + public void testExpireMessagesWithFilter() throws Exception { String key = new String("key"); long matchingValue = RandomUtil.randomLong(); long unmatchingValue = matchingValue + 1; @@ -590,8 +550,7 @@ public class JMSQueueControlTest extends ManagementTestBase } @Test - public void testCountMessagesWithFilter() throws Exception - { + public void testCountMessagesWithFilter() throws Exception { String key = "key"; long matchingValue = RandomUtil.randomLong(); long unmatchingValue = matchingValue + 1; @@ -614,21 +573,18 @@ public class JMSQueueControlTest extends ManagementTestBase } @Test - public void testGetDeadLetterAddress() throws Exception - { + public void testGetDeadLetterAddress() throws Exception { final SimpleString deadLetterAddress = RandomUtil.randomSimpleString(); JMSQueueControl queueControl = createManagementControl(); Assert.assertNull(queueControl.getDeadLetterAddress()); - server.getAddressSettingsRepository().addMatch(queue.getAddress(), new AddressSettings() - { + server.getAddressSettingsRepository().addMatch(queue.getAddress(), new AddressSettings() { private static final long serialVersionUID = -5979378001862611598L; @Override - public SimpleString getDeadLetterAddress() - { + public SimpleString getDeadLetterAddress() { return deadLetterAddress; } }); @@ -637,8 +593,7 @@ public class JMSQueueControlTest extends ManagementTestBase } @Test - public void testSetDeadLetterAddress() throws Exception - { + public void testSetDeadLetterAddress() throws Exception { final String deadLetterAddress = RandomUtil.randomString(); JMSQueueControl queueControl = createManagementControl(); @@ -652,8 +607,7 @@ public class JMSQueueControlTest extends ManagementTestBase } @Test - public void testSendMessageToDeadLetterAddress() throws Exception - { + public void testSendMessageToDeadLetterAddress() throws Exception { String deadLetterQueue = RandomUtil.randomString(); serverManager.createQueue(false, deadLetterQueue, null, true, deadLetterQueue); ActiveMQQueue dlq = (ActiveMQQueue) ActiveMQJMSClient.createQueue(deadLetterQueue); @@ -678,7 +632,7 @@ public class JMSQueueControlTest extends ManagementTestBase Assert.assertEquals(2, getMessageCount(queueControl)); Assert.assertEquals(0, getMessageCount(dlqControl)); -// queueControl.setDeadLetterAddress(dlq.getAddress()); + // queueControl.setDeadLetterAddress(dlq.getAddress()); boolean movedToDeadLetterAddress = queueControl.sendMessageToDeadLetterAddress(message.getJMSMessageID()); Assert.assertTrue(movedToDeadLetterAddress); @@ -695,26 +649,22 @@ public class JMSQueueControlTest extends ManagementTestBase } @Test - public void testSendMessageToDeadLetterAddressWithUnknownMessageID() throws Exception - { + public void testSendMessageToDeadLetterAddressWithUnknownMessageID() throws Exception { String unknownMessageID = RandomUtil.randomString(); JMSQueueControl queueControl = createManagementControl(); - try - { + try { queueControl.sendMessageToDeadLetterAddress(unknownMessageID); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { } } @Test - public void testSendMessagesToDeadLetterAddress() throws Exception - { + public void testSendMessagesToDeadLetterAddress() throws Exception { String key = "key"; long matchingValue = RandomUtil.randomLong(); long unmatchingValue = matchingValue + 1; @@ -740,7 +690,7 @@ public class JMSQueueControlTest extends ManagementTestBase Assert.assertEquals(2, getMessageCount(queueControl)); Assert.assertEquals(0, getMessageCount(dlqControl)); -// queueControl.setDeadLetterAddress(dlq.getAddress()); + // queueControl.setDeadLetterAddress(dlq.getAddress()); int deadMessageCount = queueControl.sendMessagesToDeadLetterAddress(filter); Assert.assertEquals(1, deadMessageCount); @@ -763,8 +713,7 @@ public class JMSQueueControlTest extends ManagementTestBase } @Test - public void testMoveMessages() throws Exception - { + public void testMoveMessages() throws Exception { String otherQueueName = RandomUtil.randomString(); serverManager.createQueue(false, otherQueueName, null, true, otherQueueName); @@ -791,25 +740,21 @@ public class JMSQueueControlTest extends ManagementTestBase } @Test - public void testMoveMessagesToUknownQueue() throws Exception - { + public void testMoveMessagesToUknownQueue() throws Exception { String unknownQueue = RandomUtil.randomString(); JMSQueueControl queueControl = createManagementControl(); - try - { + try { queueControl.moveMessages(null, unknownQueue); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { } } @Test - public void testMoveMatchingMessages() throws Exception - { + public void testMoveMatchingMessages() throws Exception { String key = "key"; long matchingValue = RandomUtil.randomLong(); long unmatchingValue = matchingValue + 1; @@ -848,8 +793,7 @@ public class JMSQueueControlTest extends ManagementTestBase } @Test - public void testMoveMessage() throws Exception - { + public void testMoveMessage() throws Exception { String otherQueueName = RandomUtil.randomString(); serverManager.createQueue(false, otherQueueName, null, true, otherQueueName); @@ -870,10 +814,8 @@ public class JMSQueueControlTest extends ManagementTestBase serverManager.destroyQueue(otherQueueName); } - @Test - public void testMoveMessagesWithDuplicateIDSet() throws Exception - { + public void testMoveMessagesWithDuplicateIDSet() throws Exception { String otherQueueName = RandomUtil.randomString(); serverManager.createQueue(false, otherQueueName, null, true, otherQueueName); @@ -888,15 +830,13 @@ public class JMSQueueControlTest extends ManagementTestBase ClientProducer prod1 = session.createProducer(queue.getAddress()); ClientProducer prod2 = session.createProducer(otherQueue.getAddress()); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage msg = session.createMessage(true); msg.putStringProperty(org.apache.activemq.artemis.api.core.Message.HDR_DUPLICATE_DETECTION_ID, new SimpleString("dupl-" + i)); prod1.send(msg); - if (i < 5) - { + if (i < 5) { prod2.send(msg); } } @@ -904,8 +844,7 @@ public class JMSQueueControlTest extends ManagementTestBase session.commit(); JMSQueueControl queueControl = createManagementControl(); - JMSQueueControl otherQueueControl = ManagementControlHelper.createJMSQueueControl((ActiveMQQueue) otherQueue, - mbeanServer); + JMSQueueControl otherQueueControl = ManagementControlHelper.createJMSQueueControl((ActiveMQQueue) otherQueue, mbeanServer); Assert.assertEquals(10, getMessageCount(queueControl)); @@ -925,8 +864,7 @@ public class JMSQueueControlTest extends ManagementTestBase ClientConsumer cons2 = session.createConsumer(otherQueue.getAddress()); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage msg = cons2.receive(10000); assertNotNull(msg); @@ -949,10 +887,8 @@ public class JMSQueueControlTest extends ManagementTestBase serverManager.destroyQueue(otherQueueName); } - @Test - public void testMoveIndividualMessagesWithDuplicateIDSetUsingI() throws Exception - { + public void testMoveIndividualMessagesWithDuplicateIDSetUsingI() throws Exception { String otherQueueName = RandomUtil.randomString(); serverManager.createQueue(false, otherQueueName, null, true, otherQueueName); @@ -969,8 +905,7 @@ public class JMSQueueControlTest extends ManagementTestBase String[] ids = new String[10]; - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage msg = session.createMessage(true); msg.putStringProperty(org.apache.activemq.artemis.api.core.Message.HDR_DUPLICATE_DETECTION_ID, new SimpleString("dupl-" + i)); @@ -980,8 +915,7 @@ public class JMSQueueControlTest extends ManagementTestBase prod1.send(msg); ids[i] = "ID:" + msg.getUserID().toString(); - if (i < 5) - { + if (i < 5) { msg.setUserID(UUIDGenerator.getInstance().generateUUID()); prod2.send(msg); } @@ -990,13 +924,11 @@ public class JMSQueueControlTest extends ManagementTestBase session.commit(); JMSQueueControl queueControl = createManagementControl(); - JMSQueueControl otherQueueControl = ManagementControlHelper.createJMSQueueControl((ActiveMQQueue) otherQueue, - mbeanServer); + JMSQueueControl otherQueueControl = ManagementControlHelper.createJMSQueueControl((ActiveMQQueue) otherQueue, mbeanServer); Assert.assertEquals(10, getMessageCount(queueControl)); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { queueControl.moveMessage(ids[i], otherQueueName, true); } @@ -1012,8 +944,7 @@ public class JMSQueueControlTest extends ManagementTestBase ClientConsumer cons2 = session.createConsumer(otherQueue.getAddress()); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage msg = cons2.receive(10000); assertNotNull(msg); @@ -1037,8 +968,7 @@ public class JMSQueueControlTest extends ManagementTestBase } @Test - public void testMoveMessagesWithDuplicateIDSetSingleMessage() throws Exception - { + public void testMoveMessagesWithDuplicateIDSetSingleMessage() throws Exception { String otherQueueName = RandomUtil.randomString(); serverManager.createQueue(false, otherQueueName, null, true, otherQueueName); @@ -1061,8 +991,7 @@ public class JMSQueueControlTest extends ManagementTestBase prod2.send(msg); JMSQueueControl queueControl = createManagementControl(); - JMSQueueControl otherQueueControl = ManagementControlHelper.createJMSQueueControl((ActiveMQQueue) otherQueue, - mbeanServer); + JMSQueueControl otherQueueControl = ManagementControlHelper.createJMSQueueControl((ActiveMQQueue) otherQueue, mbeanServer); Assert.assertEquals(1, getMessageCount(queueControl)); Assert.assertEquals(1, getMessageCount(otherQueueControl)); @@ -1105,8 +1034,7 @@ public class JMSQueueControlTest extends ManagementTestBase } @Test - public void testMoveMessageWithUnknownMessageID() throws Exception - { + public void testMoveMessageWithUnknownMessageID() throws Exception { String unknownMessageID = RandomUtil.randomString(); String otherQueueName = RandomUtil.randomString(); @@ -1115,32 +1043,25 @@ public class JMSQueueControlTest extends ManagementTestBase JMSQueueControl queueControl = createManagementControl(); Assert.assertEquals(0, getMessageCount(queueControl)); - try - { + try { queueControl.moveMessage(unknownMessageID, otherQueueName); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { } serverManager.destroyQueue(otherQueueName); } @Test - public void testDeleteWithPaging() throws Exception - { - AddressSettings pagedSetting = new AddressSettings() - .setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE) - .setPageSizeBytes(10 * 1024) - .setMaxSizeBytes(100 * 1024); + public void testDeleteWithPaging() throws Exception { + AddressSettings pagedSetting = new AddressSettings().setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE).setPageSizeBytes(10 * 1024).setMaxSizeBytes(100 * 1024); server.getAddressSettingsRepository().addMatch("#", pagedSetting); serverManager.createQueue(true, "pagedTest", null, true, "/queue/pagedTest"); ActiveMQQueue pagedQueue = (ActiveMQQueue) context.lookup("/queue/pagedTest"); - ServerLocator locator = createInVMNonHALocator(); ClientSessionFactory sf = createSessionFactory(locator); @@ -1152,8 +1073,7 @@ public class JMSQueueControlTest extends ManagementTestBase ClientMessage msg = session.createMessage(true); msg.getBodyBuffer().writeBytes(new byte[90 * 1024]); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { prod.send(msg); } @@ -1161,35 +1081,27 @@ public class JMSQueueControlTest extends ManagementTestBase assertEquals(100, control.removeMessages(" ")); - session.start(); ClientConsumer consumer = session.createConsumer(pagedQueue.getAddress()); assertNull(consumer.receive(300)); - session.close(); sf.close(); locator.close(); } - @Test - public void testDeleteWithPagingAndFilter() throws Exception - { - AddressSettings pagedSetting = new AddressSettings() - .setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE) - .setPageSizeBytes(10 * 1024) - .setMaxSizeBytes(100 * 1024); + public void testDeleteWithPagingAndFilter() throws Exception { + AddressSettings pagedSetting = new AddressSettings().setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE).setPageSizeBytes(10 * 1024).setMaxSizeBytes(100 * 1024); server.getAddressSettingsRepository().addMatch("#", pagedSetting); serverManager.createQueue(true, "pagedTest", null, true, "/queue/pagedTest"); ActiveMQQueue pagedQueue = (ActiveMQQueue) context.lookup("/queue/pagedTest"); - ServerLocator locator = createInVMNonHALocator(); ClientSessionFactory sf = createSessionFactory(locator); @@ -1197,8 +1109,7 @@ public class JMSQueueControlTest extends ManagementTestBase ClientSession session = sf.createSession(true, true); ClientProducer prod = session.createProducer(pagedQueue.getAddress()); - for (int i = 0; i < 200; i++) - { + for (int i = 0; i < 200; i++) { ClientMessage msg = session.createMessage(true); msg.getBodyBuffer().writeBytes(new byte[90 * 1024]); msg.putBooleanProperty("even", i % 2 == 0); @@ -1213,9 +1124,7 @@ public class JMSQueueControlTest extends ManagementTestBase ClientConsumer consumer = session.createConsumer(pagedQueue.getAddress()); - - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage msg = consumer.receive(1000); assertNotNull(msg); msg.acknowledge(); @@ -1224,17 +1133,14 @@ public class JMSQueueControlTest extends ManagementTestBase assertNull(consumer.receive(300)); - session.close(); - sf.close(); locator.close(); } @Test - public void testMoveMessageToUnknownQueue() throws Exception - { + public void testMoveMessageToUnknownQueue() throws Exception { String unknwonQueue = RandomUtil.randomString(); String[] messageIDs = JMSUtil.sendMessages(queue, 1); @@ -1242,24 +1148,20 @@ public class JMSQueueControlTest extends ManagementTestBase JMSQueueControl queueControl = createManagementControl(); Assert.assertEquals(1, getMessageCount(queueControl)); - try - { + try { queueControl.moveMessage(messageIDs[0], unknwonQueue); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { } JMSUtil.consumeMessages(1, queue); } @Test - public void testPauseAndResume() - { + public void testPauseAndResume() { - try - { + try { JMSQueueControl queueControl = createManagementControl(); Assert.assertFalse(queueControl.isPaused()); @@ -1268,8 +1170,7 @@ public class JMSQueueControlTest extends ManagementTestBase queueControl.resume(); Assert.assertFalse(queueControl.isPaused()); } - catch (Exception e) - { + catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } @@ -1281,8 +1182,7 @@ public class JMSQueueControlTest extends ManagementTestBase * @throws Exception */ @Test - public void testQueueAddJndiWithRealData() throws Exception - { + public void testQueueAddJndiWithRealData() throws Exception { String testQueueName = "testQueueAddJndi"; serverManager.createQueue(true, testQueueName, null, true, testQueueName); ActiveMQQueue testQueue = (ActiveMQQueue) ActiveMQJMSClient.createQueue(testQueueName); @@ -1292,18 +1192,15 @@ public class JMSQueueControlTest extends ManagementTestBase String newJndi = "newTestQueueAddJndi"; - for (String b : bindings) - { + for (String b : bindings) { assertFalse(b.equals(newJndi)); } queueControl.addBinding(newJndi); bindings = queueControl.getRegistryBindings(); boolean newBindingAdded = false; - for (String b : bindings) - { - if (b.equals(newJndi)) - { + for (String b : bindings) { + if (b.equals(newJndi)) { newBindingAdded = true; } } @@ -1319,10 +1216,8 @@ public class JMSQueueControlTest extends ManagementTestBase bindings = queueControl.getRegistryBindings(); newBindingAdded = false; - for (String b : bindings) - { - if (b.equals(newJndi)) - { + for (String b : bindings) { + if (b.equals(newJndi)) { newBindingAdded = true; } } @@ -1332,8 +1227,7 @@ public class JMSQueueControlTest extends ManagementTestBase //make sure notifications are always received no matter whether //a Queue is created via JMSServerControl or by JMSServerManager directly. @Test - public void testCreateQueueNotification() throws Exception - { + public void testCreateQueueNotification() throws Exception { JMSUtil.JMXListener listener = new JMSUtil.JMXListener(); this.mbeanServer.addNotificationListener(ObjectNameBuilder.DEFAULT.getJMSServerObjectName(), listener, null, null); @@ -1375,12 +1269,10 @@ public class JMSQueueControlTest extends ManagementTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - Configuration config = createDefaultInVMConfig() - .setJMXManagementEnabled(true); + Configuration config = createDefaultInVMConfig().setJMXManagementEnabled(true); server = createServer(this.getName().contains("WithRealData"), config); server.setMBeanServer(mbeanServer); @@ -1395,22 +1287,18 @@ public class JMSQueueControlTest extends ManagementTestBase queue = (ActiveMQQueue) ActiveMQJMSClient.createQueue(queueName); } - protected JMSQueueControl createManagementControl() throws Exception - { + protected JMSQueueControl createManagementControl() throws Exception { return createManagementControl(queue); } - protected JMSQueueControl createManagementControl(ActiveMQQueue queueParameter) throws Exception - { + protected JMSQueueControl createManagementControl(ActiveMQQueue queueParameter) throws Exception { return ManagementControlHelper.createJMSQueueControl(queueParameter, mbeanServer); } // Private ------------------------------------------------------- - private Connection createConnection() throws JMSException - { - ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, - new TransportConfiguration(InVMConnectorFactory.class.getName())); + private Connection createConnection() throws JMSException { + ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(InVMConnectorFactory.class.getName())); cf.setBlockOnDurableSend(true); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSQueueControlUsingJMSTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSQueueControlUsingJMSTest.java index f3a52e704a..1d79d7dbe7 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSQueueControlUsingJMSTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSQueueControlUsingJMSTest.java @@ -34,11 +34,9 @@ import javax.jms.Session; import java.util.Map; /** - * * A JMSQueueControlUsingJMSTest */ -public class JMSQueueControlUsingJMSTest extends JMSQueueControlTest -{ +public class JMSQueueControlUsingJMSTest extends JMSQueueControlTest { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -55,8 +53,7 @@ public class JMSQueueControlUsingJMSTest extends JMSQueueControlTest @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(InVMConnectorFactory.class.getName())); @@ -68,277 +65,223 @@ public class JMSQueueControlUsingJMSTest extends JMSQueueControlTest @Ignore @Override @Test - public void testListDeliveringMessages() throws Exception - { + public void testListDeliveringMessages() throws Exception { // I'm not implementing the required proxy for this test on this JMS test } - @Override - protected JMSQueueControl createManagementControl() throws Exception - { + protected JMSQueueControl createManagementControl() throws Exception { ActiveMQQueue managementQueue = (ActiveMQQueue) ActiveMQJMSClient.createQueue("activemq.management"); - final JMSMessagingProxy proxy = new JMSMessagingProxy(session, - managementQueue, - ResourceNames.JMS_QUEUE + queue.getQueueName()); + final JMSMessagingProxy proxy = new JMSMessagingProxy(session, managementQueue, ResourceNames.JMS_QUEUE + queue.getQueueName()); - return new JMSQueueControl() - { + return new JMSQueueControl() { @Override - public void flushExecutor() - { - try - { + public void flushExecutor() { + try { proxy.invokeOperation("flushExecutor"); } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } - public boolean changeMessagePriority(final String messageID, final int newPriority) throws Exception - { - return (Boolean)proxy.invokeOperation("changeMessagePriority", messageID, newPriority); + public boolean changeMessagePriority(final String messageID, final int newPriority) throws Exception { + return (Boolean) proxy.invokeOperation("changeMessagePriority", messageID, newPriority); } - public int changeMessagesPriority(final String filter, final int newPriority) throws Exception - { - return (Integer)proxy.invokeOperation("changeMessagesPriority", filter, newPriority); + public int changeMessagesPriority(final String filter, final int newPriority) throws Exception { + return (Integer) proxy.invokeOperation("changeMessagesPriority", filter, newPriority); } - public long countMessages(final String filter) throws Exception - { - return ((Number)proxy.invokeOperation("countMessages", filter)).intValue(); + public long countMessages(final String filter) throws Exception { + return ((Number) proxy.invokeOperation("countMessages", filter)).intValue(); } - public boolean expireMessage(final String messageID) throws Exception - { - return (Boolean)proxy.invokeOperation("expireMessage", messageID); + public boolean expireMessage(final String messageID) throws Exception { + return (Boolean) proxy.invokeOperation("expireMessage", messageID); } - public int expireMessages(final String filter) throws Exception - { - return (Integer)proxy.invokeOperation("expireMessages", filter); + public int expireMessages(final String filter) throws Exception { + return (Integer) proxy.invokeOperation("expireMessages", filter); } - public int getConsumerCount() - { - return (Integer)proxy.retrieveAttributeValue("consumerCount"); + public int getConsumerCount() { + return (Integer) proxy.retrieveAttributeValue("consumerCount"); } - public String getDeadLetterAddress() - { - return (String)proxy.retrieveAttributeValue("deadLetterAddress"); + public String getDeadLetterAddress() { + return (String) proxy.retrieveAttributeValue("deadLetterAddress"); } - public int getDeliveringCount() - { - return (Integer)proxy.retrieveAttributeValue("deliveringCount"); + public int getDeliveringCount() { + return (Integer) proxy.retrieveAttributeValue("deliveringCount"); } - public String getExpiryAddress() - { - return (String)proxy.retrieveAttributeValue("expiryAddress"); + public String getExpiryAddress() { + return (String) proxy.retrieveAttributeValue("expiryAddress"); } - public String getFirstMessageAsJSON() throws Exception - { - return (String)proxy.retrieveAttributeValue("firstMessageAsJSON"); + public String getFirstMessageAsJSON() throws Exception { + return (String) proxy.retrieveAttributeValue("firstMessageAsJSON"); } - public Long getFirstMessageTimestamp() throws Exception - { - return (Long)proxy.retrieveAttributeValue("firstMessageTimestamp"); + public Long getFirstMessageTimestamp() throws Exception { + return (Long) proxy.retrieveAttributeValue("firstMessageTimestamp"); } - public Long getFirstMessageAge() throws Exception - { - return (Long)proxy.retrieveAttributeValue("firstMessageAge"); + public Long getFirstMessageAge() throws Exception { + return (Long) proxy.retrieveAttributeValue("firstMessageAge"); } - public long getMessageCount() - { - return ((Number)proxy.retrieveAttributeValue("messageCount")).longValue(); + public long getMessageCount() { + return ((Number) proxy.retrieveAttributeValue("messageCount")).longValue(); } - public long getMessagesAdded() - { - return (Integer)proxy.retrieveAttributeValue("messagesAdded"); + public long getMessagesAdded() { + return (Integer) proxy.retrieveAttributeValue("messagesAdded"); } - public String getName() - { - return (String)proxy.retrieveAttributeValue("name"); + public String getName() { + return (String) proxy.retrieveAttributeValue("name"); } - public long getScheduledCount() - { - return (Long)proxy.retrieveAttributeValue("scheduledCount"); + public long getScheduledCount() { + return (Long) proxy.retrieveAttributeValue("scheduledCount"); } - public boolean isTemporary() - { - return (Boolean)proxy.retrieveAttributeValue("temporary"); + public boolean isTemporary() { + return (Boolean) proxy.retrieveAttributeValue("temporary"); } - public String listMessageCounter() throws Exception - { - return (String)proxy.invokeOperation("listMessageCounter"); + public String listMessageCounter() throws Exception { + return (String) proxy.invokeOperation("listMessageCounter"); } - public void resetMessageCounter() throws Exception - { + public void resetMessageCounter() throws Exception { proxy.invokeOperation("resetMessageCounter"); } - public String listMessageCounterAsHTML() throws Exception - { - return (String)proxy.invokeOperation("listMessageCounterAsHTML"); + public String listMessageCounterAsHTML() throws Exception { + return (String) proxy.invokeOperation("listMessageCounterAsHTML"); } - public String listMessageCounterHistory() throws Exception - { - return (String)proxy.invokeOperation("listMessageCounterHistory"); + public String listMessageCounterHistory() throws Exception { + return (String) proxy.invokeOperation("listMessageCounterHistory"); } @Override - public Map[] listScheduledMessages() throws Exception - { + public Map[] listScheduledMessages() throws Exception { return null; } @Override - public String listScheduledMessagesAsJSON() throws Exception - { + public String listScheduledMessagesAsJSON() throws Exception { return null; } @Override - public Map[]> listDeliveringMessages() throws Exception - { + public Map[]> listDeliveringMessages() throws Exception { return null; } @Override - public String listDeliveringMessagesAsJSON() throws Exception - { + public String listDeliveringMessagesAsJSON() throws Exception { return null; } - public String listMessageCounterHistoryAsHTML() throws Exception - { - return (String)proxy.invokeOperation("listMessageCounterHistoryAsHTML"); + public String listMessageCounterHistoryAsHTML() throws Exception { + return (String) proxy.invokeOperation("listMessageCounterHistoryAsHTML"); } - public Map[] listMessages(final String filter) throws Exception - { - Object[] res = (Object[])proxy.invokeOperation("listMessages", filter); + public Map[] listMessages(final String filter) throws Exception { + Object[] res = (Object[]) proxy.invokeOperation("listMessages", filter); Map[] results = new Map[res.length]; - for (int i = 0; i < res.length; i++) - { - results[i] = (Map)res[i]; + for (int i = 0; i < res.length; i++) { + results[i] = (Map) res[i]; } return results; } - public String listMessagesAsJSON(final String filter) throws Exception - { - return (String)proxy.invokeOperation("listMessagesAsJSON", filter); + public String listMessagesAsJSON(final String filter) throws Exception { + return (String) proxy.invokeOperation("listMessagesAsJSON", filter); } - public boolean moveMessage(String messageID, String otherQueueName, boolean rejectDuplicates) throws Exception - { - return (Boolean)proxy.invokeOperation("moveMessage", messageID, otherQueueName, rejectDuplicates); + public boolean moveMessage(String messageID, + String otherQueueName, + boolean rejectDuplicates) throws Exception { + return (Boolean) proxy.invokeOperation("moveMessage", messageID, otherQueueName, rejectDuplicates); } - public int moveMessages(String filter, String otherQueueName, boolean rejectDuplicates) throws Exception - { - return (Integer)proxy.invokeOperation("moveMessages", filter, otherQueueName, rejectDuplicates); + public int moveMessages(String filter, String otherQueueName, boolean rejectDuplicates) throws Exception { + return (Integer) proxy.invokeOperation("moveMessages", filter, otherQueueName, rejectDuplicates); } - public int moveMessages(final String filter, final String otherQueueName) throws Exception - { - return (Integer)proxy.invokeOperation("moveMessages", filter, otherQueueName); + public int moveMessages(final String filter, final String otherQueueName) throws Exception { + return (Integer) proxy.invokeOperation("moveMessages", filter, otherQueueName); } - public boolean moveMessage(final String messageID, final String otherQueueName) throws Exception - { - return (Boolean)proxy.invokeOperation("moveMessage", messageID, otherQueueName); + public boolean moveMessage(final String messageID, final String otherQueueName) throws Exception { + return (Boolean) proxy.invokeOperation("moveMessage", messageID, otherQueueName); } - public int removeMessages(final String filter) throws Exception - { - return (Integer)proxy.invokeOperation("removeMessages", filter); + public int removeMessages(final String filter) throws Exception { + return (Integer) proxy.invokeOperation("removeMessages", filter); } - public boolean removeMessage(final String messageID) throws Exception - { - return (Boolean)proxy.invokeOperation("removeMessage", messageID); + public boolean removeMessage(final String messageID) throws Exception { + return (Boolean) proxy.invokeOperation("removeMessage", messageID); } - public boolean sendMessageToDeadLetterAddress(final String messageID) throws Exception - { - return (Boolean)proxy.invokeOperation("sendMessageToDeadLetterAddress", messageID); + public boolean sendMessageToDeadLetterAddress(final String messageID) throws Exception { + return (Boolean) proxy.invokeOperation("sendMessageToDeadLetterAddress", messageID); } - public int sendMessagesToDeadLetterAddress(final String filterStr) throws Exception - { - return (Integer)proxy.invokeOperation("sendMessagesToDeadLetterAddress", filterStr); + public int sendMessagesToDeadLetterAddress(final String filterStr) throws Exception { + return (Integer) proxy.invokeOperation("sendMessagesToDeadLetterAddress", filterStr); } - public void setDeadLetterAddress(final String deadLetterAddress) throws Exception - { + public void setDeadLetterAddress(final String deadLetterAddress) throws Exception { proxy.invokeOperation("setDeadLetterAddress", deadLetterAddress); } - public void setExpiryAddress(final String expiryAddress) throws Exception - { + public void setExpiryAddress(final String expiryAddress) throws Exception { proxy.invokeOperation("setExpiryAddress", expiryAddress); } - public String getAddress() - { - return (String)proxy.retrieveAttributeValue("address"); + public String getAddress() { + return (String) proxy.retrieveAttributeValue("address"); } - public boolean isPaused() throws Exception - { - return (Boolean)proxy.invokeOperation("isPaused"); + public boolean isPaused() throws Exception { + return (Boolean) proxy.invokeOperation("isPaused"); } - public void pause() throws Exception - { + public void pause() throws Exception { proxy.invokeOperation("pause"); } - public void resume() throws Exception - { + public void resume() throws Exception { proxy.invokeOperation("resume"); } - public String getSelector() - { - return (String)proxy.retrieveAttributeValue("selector"); + public String getSelector() { + return (String) proxy.retrieveAttributeValue("selector"); } - public void addBinding(String jndi) throws Exception - { + public void addBinding(String jndi) throws Exception { // TODO: Add a test for this proxy.invokeOperation("addBindings", jndi); } - public String[] getRegistryBindings() - { + public String[] getRegistryBindings() { // TODO: Add a test for this return null; } - public String listConsumersAsJSON() throws Exception - { - return (String)proxy.invokeOperation("listConsumersAsJSON"); + public String listConsumersAsJSON() throws Exception { + return (String) proxy.invokeOperation("listConsumersAsJSON"); } }; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSServerControl2Test.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSServerControl2Test.java index 12a48b2c6c..b1a7e6da9d 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSServerControl2Test.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSServerControl2Test.java @@ -61,8 +61,8 @@ import java.util.Arrays; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -public class JMSServerControl2Test extends ManagementTestBase -{ +public class JMSServerControl2Test extends ManagementTestBase { + private static final long CONNECTION_TTL = 1000; private static final long PING_PERIOD = JMSServerControl2Test.CONNECTION_TTL / 2; @@ -75,10 +75,8 @@ public class JMSServerControl2Test extends ManagementTestBase // Static -------------------------------------------------------- - private void startActiveMQServer(final String acceptorFactory) throws Exception - { - Configuration config = createBasicConfig() - .addAcceptorConfiguration(new TransportConfiguration(acceptorFactory)); + private void startActiveMQServer(final String acceptorFactory) throws Exception { + Configuration config = createBasicConfig().addAcceptorConfiguration(new TransportConfiguration(acceptorFactory)); server = addServer(ActiveMQServers.newActiveMQServer(config, mbeanServer, true)); server.start(); @@ -91,120 +89,100 @@ public class JMSServerControl2Test extends ManagementTestBase } @Test - public void testListClientConnectionsForInVM() throws Exception - { + public void testListClientConnectionsForInVM() throws Exception { doListClientConnections(InVMAcceptorFactory.class.getName(), InVMConnectorFactory.class.getName()); } @Test - public void testListClientConnectionsForNetty() throws Exception - { + public void testListClientConnectionsForNetty() throws Exception { doListClientConnections(NettyAcceptorFactory.class.getName(), NettyConnectorFactory.class.getName()); } @Test - public void testCloseConnectionsForAddressForInVM() throws Exception - { + public void testCloseConnectionsForAddressForInVM() throws Exception { doCloseConnectionsForAddress(InVMAcceptorFactory.class.getName(), InVMConnectorFactory.class.getName()); } @Test - public void testCloseConnectionsForAddressForNetty() throws Exception - { + public void testCloseConnectionsForAddressForNetty() throws Exception { doCloseConnectionsForAddress(NettyAcceptorFactory.class.getName(), NettyConnectorFactory.class.getName()); } @Test - public void testCloseConnectionsForUnknownAddressForInVM() throws Exception - { + public void testCloseConnectionsForUnknownAddressForInVM() throws Exception { doCloseConnectionsForUnknownAddress(InVMAcceptorFactory.class.getName(), InVMConnectorFactory.class.getName()); } @Test - public void testCloseConnectionsForUnknownAddressForNetty() throws Exception - { + public void testCloseConnectionsForUnknownAddressForNetty() throws Exception { doCloseConnectionsForUnknownAddress(NettyAcceptorFactory.class.getName(), NettyConnectorFactory.class.getName()); } @Test - public void testCloseConsumerConnectionsForAddressForInVM() throws Exception - { + public void testCloseConsumerConnectionsForAddressForInVM() throws Exception { doCloseConsumerConnectionsForAddress(InVMAcceptorFactory.class.getName(), InVMConnectorFactory.class.getName()); } @Test - public void testCloseConsumerConnectionsForAddressForNetty() throws Exception - { + public void testCloseConsumerConnectionsForAddressForNetty() throws Exception { doCloseConsumerConnectionsForAddress(NettyAcceptorFactory.class.getName(), NettyConnectorFactory.class.getName()); } @Test - public void testCloseConsumerConnectionsForWildcardAddressForInVM() throws Exception - { + public void testCloseConsumerConnectionsForWildcardAddressForInVM() throws Exception { doCloseConsumerConnectionsForWildcardAddress(InVMAcceptorFactory.class.getName(), InVMConnectorFactory.class.getName()); } @Test - public void testCloseConsumerConnectionsForWildcardAddressForNetty() throws Exception - { + public void testCloseConsumerConnectionsForWildcardAddressForNetty() throws Exception { doCloseConsumerConnectionsForWildcardAddress(NettyAcceptorFactory.class.getName(), NettyConnectorFactory.class.getName()); } @Test - public void testCloseConnectionsForUserForInVM() throws Exception - { + public void testCloseConnectionsForUserForInVM() throws Exception { doCloseConnectionsForUser(InVMAcceptorFactory.class.getName(), InVMConnectorFactory.class.getName()); } @Test - public void testCloseConnectionsForUserForNetty() throws Exception - { + public void testCloseConnectionsForUserForNetty() throws Exception { doCloseConnectionsForUser(NettyAcceptorFactory.class.getName(), NettyConnectorFactory.class.getName()); } @Test - public void testListSessionsForInVM() throws Exception - { + public void testListSessionsForInVM() throws Exception { doListSessions(InVMAcceptorFactory.class.getName(), InVMConnectorFactory.class.getName()); } @Test - public void testListSessionsForNetty() throws Exception - { + public void testListSessionsForNetty() throws Exception { doListSessions(NettyAcceptorFactory.class.getName(), NettyConnectorFactory.class.getName()); } @Test - public void testListConnectionIDsForInVM() throws Exception - { + public void testListConnectionIDsForInVM() throws Exception { doListConnectionIDs(InVMAcceptorFactory.class.getName(), InVMConnectorFactory.class.getName()); } @Test - public void testListConnectionIDsForNetty() throws Exception - { + public void testListConnectionIDsForNetty() throws Exception { doListConnectionIDs(NettyAcceptorFactory.class.getName(), NettyConnectorFactory.class.getName()); } @Test - public void testListConnectionsAsJSONForNetty() throws Exception - { + public void testListConnectionsAsJSONForNetty() throws Exception { doListConnectionsAsJSON(NettyAcceptorFactory.class.getName(), NettyConnectorFactory.class.getName()); } @Test - public void testListConnectionsAsJSONForInVM() throws Exception - { + public void testListConnectionsAsJSONForInVM() throws Exception { doListConnectionsAsJSON(InVMAcceptorFactory.class.getName(), InVMConnectorFactory.class.getName()); } @Test - public void testListConsumersAsJSON() throws Exception - { + public void testListConsumersAsJSON() throws Exception { String queueName = RandomUtil.randomString(); - try - { + try { startActiveMQServer(NETTY_ACCEPTOR_FACTORY); serverManager.createQueue(false, queueName, null, true, queueName); Queue queue = ActiveMQJMSClient.createQueue(queueName); @@ -218,9 +196,7 @@ public class JMSServerControl2Test extends ManagementTestBase JMSConnectionInfo[] infos = JMSConnectionInfo.from(jsonStr); assertEquals(0, infos.length); - ConnectionFactory cf1 = JMSUtil.createFactory(NettyConnectorFactory.class.getName(), - JMSServerControl2Test.CONNECTION_TTL, - JMSServerControl2Test.PING_PERIOD); + ConnectionFactory cf1 = JMSUtil.createFactory(NettyConnectorFactory.class.getName(), JMSServerControl2Test.CONNECTION_TTL, JMSServerControl2Test.PING_PERIOD); Connection connection = cf1.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); TemporaryTopic temporaryTopic = session.createTemporaryTopic(); @@ -300,16 +276,13 @@ public class JMSServerControl2Test extends ManagementTestBase connection.close(); } - finally - { - if (serverManager != null) - { + finally { + if (serverManager != null) { serverManager.destroyQueue(queueName); serverManager.stop(); } - if (server != null) - { + if (server != null) { server.stop(); } } @@ -319,14 +292,12 @@ public class JMSServerControl2Test extends ManagementTestBase * test for durable subscriber */ @Test - public void testListConsumersAsJSON2() throws Exception - { + public void testListConsumersAsJSON2() throws Exception { String topicName = RandomUtil.randomString(); String clientID = RandomUtil.randomString(); String subName = RandomUtil.randomString(); - try - { + try { startActiveMQServer(NettyAcceptorFactory.class.getName()); serverManager.createTopic(false, topicName, topicName); Topic topic = ActiveMQJMSClient.createTopic(topicName); @@ -340,9 +311,7 @@ public class JMSServerControl2Test extends ManagementTestBase JMSConnectionInfo[] infos = JMSConnectionInfo.from(jsonStr); assertEquals(0, infos.length); - ConnectionFactory cf1 = JMSUtil.createFactory(NettyConnectorFactory.class.getName(), - JMSServerControl2Test.CONNECTION_TTL, - JMSServerControl2Test.PING_PERIOD); + ConnectionFactory cf1 = JMSUtil.createFactory(NettyConnectorFactory.class.getName(), JMSServerControl2Test.CONNECTION_TTL, JMSServerControl2Test.PING_PERIOD); Connection connection = cf1.createConnection(); connection.setClientID(clientID); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -374,16 +343,13 @@ public class JMSServerControl2Test extends ManagementTestBase connection.close(); } - finally - { - if (serverManager != null) - { + finally { + if (serverManager != null) { serverManager.destroyTopic(topicName); serverManager.stop(); } - if (server != null) - { + if (server != null) { server.stop(); } } @@ -391,16 +357,14 @@ public class JMSServerControl2Test extends ManagementTestBase //https://jira.jboss.org/browse/HORNETQ-416 @Test - public void testProducerInfo() throws Exception - { + public void testProducerInfo() throws Exception { String queueName = RandomUtil.randomString(); System.out.println("queueName is: " + queueName); Connection connection = null; - try - { + try { startActiveMQServer(NettyAcceptorFactory.class.getName()); serverManager.createQueue(false, queueName, null, true, queueName); Queue queue = ActiveMQJMSClient.createQueue(queueName); @@ -409,31 +373,26 @@ public class JMSServerControl2Test extends ManagementTestBase long startTime = System.currentTimeMillis(); - ConnectionFactory cf1 = JMSUtil.createFactory(NettyConnectorFactory.class.getName(), - JMSServerControl2Test.CONNECTION_TTL, - JMSServerControl2Test.PING_PERIOD); + ConnectionFactory cf1 = JMSUtil.createFactory(NettyConnectorFactory.class.getName(), JMSServerControl2Test.CONNECTION_TTL, JMSServerControl2Test.PING_PERIOD); connection = cf1.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(queue); TextMessage msgSent = null; - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { msgSent = session.createTextMessage("mymessage-" + i); producer.send(msgSent); System.out.println("sending msgID " + msgSent.getJMSMessageID()); } - connection.start(); // create a regular message consumer MessageConsumer consumer = session.createConsumer(queue); TextMessage receivedMsg = null; - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { receivedMsg = (TextMessage) consumer.receive(3000); assertNotNull(receivedMsg); } @@ -453,15 +412,13 @@ public class JMSServerControl2Test extends ManagementTestBase assertTrue(sessInfos.length > 0); boolean lastMsgFound = false; - for (JMSSessionInfo sInfo : sessInfos) - { + for (JMSSessionInfo sInfo : sessInfos) { System.out.println("Session name: " + sInfo.getSessionID()); assertNotNull(sInfo.getSessionID()); long createTime = sInfo.getCreationTime(); assertTrue(startTime <= createTime && createTime <= System.currentTimeMillis()); String lastID = control.getLastSentMessageID(sInfo.getSessionID(), "jms.queue." + queueName); - if (lastID != null) - { + if (lastID != null) { assertEquals(lastMsgID, lastID); lastMsgFound = true; } @@ -472,47 +429,37 @@ public class JMSServerControl2Test extends ManagementTestBase connection.close(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); throw e; } - finally - { - try - { - if (connection != null) - { + finally { + try { + if (connection != null) { connection.close(); } - if (serverManager != null) - { + if (serverManager != null) { serverManager.destroyQueue(queueName); serverManager.stop(); } } - catch (Throwable ignored) - { + catch (Throwable ignored) { ignored.printStackTrace(); } - if (server != null) - { + if (server != null) { server.stop(); } } } - @Test - public void testStartActivationListConnections() throws Exception - { + public void testStartActivationListConnections() throws Exception { ActiveMQActivation activation = null; ActiveMQResourceAdapter ra = null; - try - { + try { startActiveMQServer(InVMAcceptorFactory.class.getName()); ActiveMQJMSClient.createQueue("test"); serverManager.createQueue(false, "test", null, true, "test"); @@ -559,47 +506,40 @@ public class JMSServerControl2Test extends ManagementTestBase assertEquals("my-client-id", jmsConnectionInfos[0].getClientID()); } - finally - { + finally { if (activation != null) activation.stop(); if (ra != null) ra.stop(); - try - { + try { /*if (connection != null) { connection.close(); }*/ - if (serverManager != null) - { + if (serverManager != null) { //serverManager.destroyQueue(queueName); serverManager.stop(); } } - catch (Throwable ignored) - { + catch (Throwable ignored) { ignored.printStackTrace(); } - if (server != null) - { + if (server != null) { server.stop(); } } } @Test - public void testStartActivationOverrideListConnections() throws Exception - { + public void testStartActivationOverrideListConnections() throws Exception { ActiveMQActivation activation = null; ActiveMQResourceAdapter ra = null; - try - { + try { startActiveMQServer(InVMAcceptorFactory.class.getName()); ActiveMQJMSClient.createQueue("test"); serverManager.createQueue(false, "test", null, true, "test"); @@ -648,34 +588,29 @@ public class JMSServerControl2Test extends ManagementTestBase assertEquals("my-client-id", jmsConnectionInfos[0].getClientID()); } - finally - { + finally { if (activation != null) activation.stop(); if (ra != null) ra.stop(); - try - { + try { /*if (connection != null) { connection.close(); }*/ - if (serverManager != null) - { + if (serverManager != null) { //serverManager.destroyQueue(queueName); serverManager.stop(); } } - catch (Throwable ignored) - { + catch (Throwable ignored) { ignored.printStackTrace(); } - if (server != null) - { + if (server != null) { server.stop(); } } @@ -684,34 +619,27 @@ public class JMSServerControl2Test extends ManagementTestBase // Protected ----------------------------------------------------- - protected JMSServerControl createManagementControl() throws Exception - { + protected JMSServerControl createManagementControl() throws Exception { return ManagementControlHelper.createJMSServerControl(mbeanServer); } // Private ------------------------------------------------------- - private void doListConnectionIDs(final String acceptorFactory, final String connectorFactory) throws Exception - { - try - { + private void doListConnectionIDs(final String acceptorFactory, final String connectorFactory) throws Exception { + try { startActiveMQServer(acceptorFactory); JMSServerControl control = createManagementControl(); Assert.assertEquals(0, control.listConnectionIDs().length); - ConnectionFactory cf1 = JMSUtil.createFactory(connectorFactory, - JMSServerControl2Test.CONNECTION_TTL, - JMSServerControl2Test.PING_PERIOD); + ConnectionFactory cf1 = JMSUtil.createFactory(connectorFactory, JMSServerControl2Test.CONNECTION_TTL, JMSServerControl2Test.PING_PERIOD); Connection connection = cf1.createConnection(); String[] connectionIDs = control.listConnectionIDs(); Assert.assertEquals(1, connectionIDs.length); - ConnectionFactory cf2 = JMSUtil.createFactory(connectorFactory, - JMSServerControl2Test.CONNECTION_TTL, - JMSServerControl2Test.PING_PERIOD); + ConnectionFactory cf2 = JMSUtil.createFactory(connectorFactory, JMSServerControl2Test.CONNECTION_TTL, JMSServerControl2Test.PING_PERIOD); Connection connection2 = cf2.createConnection(); Assert.assertEquals(2, control.listConnectionIDs().length); @@ -723,24 +651,19 @@ public class JMSServerControl2Test extends ManagementTestBase waitForConnectionIDs(0, control); } - finally - { - if (serverManager != null) - { + finally { + if (serverManager != null) { serverManager.stop(); } - if (server != null) - { + if (server != null) { server.stop(); } } } - private void doListConnectionsAsJSON(final String acceptorFactory, final String connectorFactory) throws Exception - { - try - { + private void doListConnectionsAsJSON(final String acceptorFactory, final String connectorFactory) throws Exception { + try { startActiveMQServer(acceptorFactory); JMSServerControl control = createManagementControl(); @@ -752,33 +675,27 @@ public class JMSServerControl2Test extends ManagementTestBase JMSConnectionInfo[] infos = JMSConnectionInfo.from(jsonStr); assertEquals(0, infos.length); - ConnectionFactory cf1 = JMSUtil.createFactory(connectorFactory, - JMSServerControl2Test.CONNECTION_TTL, - JMSServerControl2Test.PING_PERIOD); + ConnectionFactory cf1 = JMSUtil.createFactory(connectorFactory, JMSServerControl2Test.CONNECTION_TTL, JMSServerControl2Test.PING_PERIOD); Connection connection = cf1.createConnection(); jsonStr = control.listConnectionsAsJSON(); assertNotNull(jsonStr); infos = JMSConnectionInfo.from(jsonStr); assertEquals(1, infos.length); - for (JMSConnectionInfo info : infos) - { + for (JMSConnectionInfo info : infos) { assertNotNull(info.getConnectionID()); assertNotNull(info.getClientAddress()); assertTrue(startTime <= info.getCreationTime() && info.getCreationTime() <= System.currentTimeMillis()); } - ConnectionFactory cf2 = JMSUtil.createFactory(connectorFactory, - JMSServerControl2Test.CONNECTION_TTL, - JMSServerControl2Test.PING_PERIOD); + ConnectionFactory cf2 = JMSUtil.createFactory(connectorFactory, JMSServerControl2Test.CONNECTION_TTL, JMSServerControl2Test.PING_PERIOD); Connection connection2 = cf2.createConnection(); jsonStr = control.listConnectionsAsJSON(); assertNotNull(jsonStr); infos = JMSConnectionInfo.from(jsonStr); assertEquals(2, infos.length); - for (JMSConnectionInfo info : infos) - { + for (JMSConnectionInfo info : infos) { assertNotNull(info.getConnectionID()); assertNotNull(info.getClientAddress()); assertTrue(startTime <= info.getCreationTime() && info.getCreationTime() <= System.currentTimeMillis()); @@ -812,33 +729,26 @@ public class JMSServerControl2Test extends ManagementTestBase infos = JMSConnectionInfo.from(jsonStr); assertEquals(0, infos.length); } - finally - { - if (serverManager != null) - { + finally { + if (serverManager != null) { serverManager.stop(); } - if (server != null) - { + if (server != null) { server.stop(); } } } - private void waitForConnectionIDs(final int num, final JMSServerControl control) throws Exception - { + private void waitForConnectionIDs(final int num, final JMSServerControl control) throws Exception { final long timeout = 10000; long start = System.currentTimeMillis(); - while (true) - { - if (control.listConnectionIDs().length == num) - { + while (true) { + if (control.listConnectionIDs().length == num) { return; } - if (System.currentTimeMillis() - start > timeout) - { + if (System.currentTimeMillis() - start > timeout) { throw new IllegalStateException("Timed out waiting for number of connections"); } @@ -846,19 +756,15 @@ public class JMSServerControl2Test extends ManagementTestBase } } - private void doListSessions(final String acceptorFactory, final String connectorFactory) throws Exception - { - try - { + private void doListSessions(final String acceptorFactory, final String connectorFactory) throws Exception { + try { startActiveMQServer(acceptorFactory); JMSServerControl control = createManagementControl(); Assert.assertEquals(0, control.listConnectionIDs().length); - ConnectionFactory cf = JMSUtil.createFactory(connectorFactory, - JMSServerControl2Test.CONNECTION_TTL, - JMSServerControl2Test.PING_PERIOD); + ConnectionFactory cf = JMSUtil.createFactory(connectorFactory, JMSServerControl2Test.CONNECTION_TTL, JMSServerControl2Test.PING_PERIOD); Connection connection = cf.createConnection(); String[] connectionIDs = control.listConnectionIDs(); @@ -877,40 +783,32 @@ public class JMSServerControl2Test extends ManagementTestBase Assert.assertEquals(0, control.listConnectionIDs().length); } - finally - { - if (serverManager != null) - { + finally { + if (serverManager != null) { serverManager.stop(); } - if (server != null) - { + if (server != null) { server.stop(); } } } - private void doListClientConnections(final String acceptorFactory, final String connectorFactory) throws Exception - { - try - { + private void doListClientConnections(final String acceptorFactory, final String connectorFactory) throws Exception { + try { startActiveMQServer(acceptorFactory); JMSServerControl control = createManagementControl(); Assert.assertEquals(0, control.listRemoteAddresses().length); - ConnectionFactory cf = JMSUtil.createFactory(connectorFactory, - JMSServerControl2Test.CONNECTION_TTL, - JMSServerControl2Test.PING_PERIOD); + ConnectionFactory cf = JMSUtil.createFactory(connectorFactory, JMSServerControl2Test.CONNECTION_TTL, JMSServerControl2Test.PING_PERIOD); Connection connection = cf.createConnection(); String[] remoteAddresses = control.listRemoteAddresses(); Assert.assertEquals(1, remoteAddresses.length); - for (String remoteAddress : remoteAddresses) - { + for (String remoteAddress : remoteAddresses) { System.out.println(remoteAddress); } @@ -921,24 +819,20 @@ public class JMSServerControl2Test extends ManagementTestBase remoteAddresses = control.listRemoteAddresses(); Assert.assertEquals("got " + Arrays.asList(remoteAddresses), 0, remoteAddresses.length); } - finally - { - if (serverManager != null) - { + finally { + if (serverManager != null) { serverManager.stop(); } - if (server != null) - { + if (server != null) { server.stop(); } } } - private void doCloseConnectionsForAddress(final String acceptorFactory, final String connectorFactory) throws Exception - { - try - { + private void doCloseConnectionsForAddress(final String acceptorFactory, + final String connectorFactory) throws Exception { + try { startActiveMQServer(acceptorFactory); JMSServerControl control = createManagementControl(); @@ -946,9 +840,7 @@ public class JMSServerControl2Test extends ManagementTestBase Assert.assertEquals(0, server.getConnectionCount()); Assert.assertEquals(0, control.listRemoteAddresses().length); - ConnectionFactory cf = JMSUtil.createFactory(connectorFactory, - JMSServerControl2Test.CONNECTION_TTL, - JMSServerControl2Test.PING_PERIOD); + ConnectionFactory cf = JMSUtil.createFactory(connectorFactory, JMSServerControl2Test.CONNECTION_TTL, JMSServerControl2Test.PING_PERIOD); Connection connection = cf.createConnection(); Assert.assertEquals(1, server.getConnectionCount()); @@ -958,10 +850,8 @@ public class JMSServerControl2Test extends ManagementTestBase String remoteAddress = remoteAddresses[0]; final CountDownLatch exceptionLatch = new CountDownLatch(1); - connection.setExceptionListener(new ExceptionListener() - { - public void onException(final JMSException e) - { + connection.setExceptionListener(new ExceptionListener() { + public void onException(final JMSException e) { exceptionLatch.countDown(); } }); @@ -977,26 +867,22 @@ public class JMSServerControl2Test extends ManagementTestBase connection.close(); } - finally - { - if (serverManager != null) - { + finally { + if (serverManager != null) { serverManager.stop(); } - if (server != null) - { + if (server != null) { server.stop(); } } } - private void doCloseConnectionsForUnknownAddress(final String acceptorFactory, final String connectorFactory) throws Exception - { + private void doCloseConnectionsForUnknownAddress(final String acceptorFactory, + final String connectorFactory) throws Exception { String unknownAddress = RandomUtil.randomString(); - try - { + try { startActiveMQServer(acceptorFactory); JMSServerControl control = createManagementControl(); @@ -1004,9 +890,7 @@ public class JMSServerControl2Test extends ManagementTestBase Assert.assertEquals(0, server.getConnectionCount()); Assert.assertEquals(0, control.listRemoteAddresses().length); - ConnectionFactory cf = JMSUtil.createFactory(connectorFactory, - JMSServerControl2Test.CONNECTION_TTL, - JMSServerControl2Test.PING_PERIOD); + ConnectionFactory cf = JMSUtil.createFactory(connectorFactory, JMSServerControl2Test.CONNECTION_TTL, JMSServerControl2Test.PING_PERIOD); Connection connection = cf.createConnection(); Assert.assertEquals(1, server.getConnectionCount()); @@ -1014,10 +898,8 @@ public class JMSServerControl2Test extends ManagementTestBase Assert.assertEquals(1, remoteAddresses.length); final CountDownLatch exceptionLatch = new CountDownLatch(1); - connection.setExceptionListener(new ExceptionListener() - { - public void onException(final JMSException e) - { + connection.setExceptionListener(new ExceptionListener() { + public void onException(final JMSException e) { exceptionLatch.countDown(); } }); @@ -1033,27 +915,23 @@ public class JMSServerControl2Test extends ManagementTestBase connection.close(); } - finally - { - if (serverManager != null) - { + finally { + if (serverManager != null) { serverManager.stop(); } - if (server != null) - { + if (server != null) { server.stop(); } } } - private void doCloseConsumerConnectionsForAddress(final String acceptorFactory, final String connectorFactory) throws Exception - { + private void doCloseConsumerConnectionsForAddress(final String acceptorFactory, + final String connectorFactory) throws Exception { String queueName = RandomUtil.randomString(); String queueName2 = RandomUtil.randomString(); - try - { + try { startActiveMQServer(acceptorFactory); serverManager.createQueue(false, queueName, null, true, queueName); Queue queue = ActiveMQJMSClient.createQueue(queueName); @@ -1069,9 +947,7 @@ public class JMSServerControl2Test extends ManagementTestBase Assert.assertEquals(0, queueControl.getConsumerCount()); Assert.assertEquals(0, queueControl2.getConsumerCount()); - ConnectionFactory cf = JMSUtil.createFactory(connectorFactory, - JMSServerControl2Test.CONNECTION_TTL, - JMSServerControl2Test.PING_PERIOD); + ConnectionFactory cf = JMSUtil.createFactory(connectorFactory, JMSServerControl2Test.CONNECTION_TTL, JMSServerControl2Test.PING_PERIOD); Connection connection = cf.createConnection(); Session session = connection.createSession(); MessageConsumer messageConsumer = session.createConsumer(queue); @@ -1089,10 +965,8 @@ public class JMSServerControl2Test extends ManagementTestBase Assert.assertEquals(1, queueControl2.getConsumerCount()); final CountDownLatch exceptionLatch = new CountDownLatch(1); - connection.setExceptionListener(new ExceptionListener() - { - public void onException(final JMSException e) - { + connection.setExceptionListener(new ExceptionListener() { + public void onException(final JMSException e) { exceptionLatch.countDown(); } }); @@ -1111,28 +985,24 @@ public class JMSServerControl2Test extends ManagementTestBase connection2.close(); } - finally - { - if (serverManager != null) - { + finally { + if (serverManager != null) { serverManager.stop(); } - if (server != null) - { + if (server != null) { server.stop(); } } } - private void doCloseConsumerConnectionsForWildcardAddress(final String acceptorFactory, final String connectorFactory) throws Exception - { + private void doCloseConsumerConnectionsForWildcardAddress(final String acceptorFactory, + final String connectorFactory) throws Exception { String queueName1 = "x." + RandomUtil.randomString(); String queueName2 = "x." + RandomUtil.randomString(); String queueName3 = "y." + RandomUtil.randomString(); - try - { + try { startActiveMQServer(acceptorFactory); serverManager.createQueue(false, queueName1, null, true, queueName1); Queue queue = ActiveMQJMSClient.createQueue(queueName1); @@ -1152,9 +1022,7 @@ public class JMSServerControl2Test extends ManagementTestBase Assert.assertEquals(0, queueControl2.getConsumerCount()); Assert.assertEquals(0, queueControl3.getConsumerCount()); - ConnectionFactory cf = JMSUtil.createFactory(connectorFactory, - JMSServerControl2Test.CONNECTION_TTL, - JMSServerControl2Test.PING_PERIOD); + ConnectionFactory cf = JMSUtil.createFactory(connectorFactory, JMSServerControl2Test.CONNECTION_TTL, JMSServerControl2Test.PING_PERIOD); Connection connection = cf.createConnection(); Session session = connection.createSession(); MessageConsumer messageConsumer = session.createConsumer(queue); @@ -1177,18 +1045,14 @@ public class JMSServerControl2Test extends ManagementTestBase Assert.assertEquals(1, queueControl3.getConsumerCount()); final CountDownLatch exceptionLatch = new CountDownLatch(2); - connection.setExceptionListener(new ExceptionListener() - { - public void onException(final JMSException e) - { + connection.setExceptionListener(new ExceptionListener() { + public void onException(final JMSException e) { exceptionLatch.countDown(); } }); - connection2.setExceptionListener(new ExceptionListener() - { - public void onException(final JMSException e) - { + connection2.setExceptionListener(new ExceptionListener() { + public void onException(final JMSException e) { exceptionLatch.countDown(); } }); @@ -1210,27 +1074,23 @@ public class JMSServerControl2Test extends ManagementTestBase connection2.close(); connection3.close(); } - finally - { - if (serverManager != null) - { + finally { + if (serverManager != null) { serverManager.stop(); } - if (server != null) - { + if (server != null) { server.stop(); } } } - private void doCloseConnectionsForUser(final String acceptorFactory, final String connectorFactory) throws Exception - { + private void doCloseConnectionsForUser(final String acceptorFactory, + final String connectorFactory) throws Exception { String queueName = RandomUtil.randomString(); String queueName2 = RandomUtil.randomString(); - try - { + try { startActiveMQServer(acceptorFactory); serverManager.createQueue(false, queueName, null, true, queueName); Queue queue = ActiveMQJMSClient.createQueue(queueName); @@ -1246,9 +1106,7 @@ public class JMSServerControl2Test extends ManagementTestBase Assert.assertEquals(0, queueControl.getConsumerCount()); Assert.assertEquals(0, queueControl2.getConsumerCount()); - ConnectionFactory cf = JMSUtil.createFactory(connectorFactory, - JMSServerControl2Test.CONNECTION_TTL, - JMSServerControl2Test.PING_PERIOD); + ConnectionFactory cf = JMSUtil.createFactory(connectorFactory, JMSServerControl2Test.CONNECTION_TTL, JMSServerControl2Test.PING_PERIOD); Connection connection = cf.createConnection("fakeUser", "fakePassword"); Session session = connection.createSession(); MessageConsumer messageConsumer = session.createConsumer(queue); @@ -1266,10 +1124,8 @@ public class JMSServerControl2Test extends ManagementTestBase Assert.assertEquals(1, queueControl2.getConsumerCount()); final CountDownLatch exceptionLatch = new CountDownLatch(1); - connection.setExceptionListener(new ExceptionListener() - { - public void onException(final JMSException e) - { + connection.setExceptionListener(new ExceptionListener() { + public void onException(final JMSException e) { exceptionLatch.countDown(); } }); @@ -1288,15 +1144,12 @@ public class JMSServerControl2Test extends ManagementTestBase connection2.close(); } - finally - { - if (serverManager != null) - { + finally { + if (serverManager != null) { serverManager.stop(); } - if (server != null) - { + if (server != null) { server.stop(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSServerControlRestartTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSServerControlRestartTest.java index b31873bc22..f0c345107d 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSServerControlRestartTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSServerControlRestartTest.java @@ -46,16 +46,14 @@ import javax.jms.QueueRequestor; import javax.jms.QueueSession; import javax.jms.Session; -public class JMSServerControlRestartTest extends ManagementTestBase -{ +public class JMSServerControlRestartTest extends ManagementTestBase { protected InVMNamingContext context; private JMSServerManager serverManager; @Test - public void testCreateDurableQueueUsingJMXAndRestartServer() throws Exception - { + public void testCreateDurableQueueUsingJMXAndRestartServer() throws Exception { String queueName = RandomUtil.randomString(); String binding = RandomUtil.randomString(); @@ -87,8 +85,7 @@ public class JMSServerControlRestartTest extends ManagementTestBase } @Test - public void testCreateDurableQueueUsingJMSAndRestartServer() throws Exception - { + public void testCreateDurableQueueUsingJMSAndRestartServer() throws Exception { String queueName = RandomUtil.randomString(); String binding = RandomUtil.randomString(); @@ -134,19 +131,15 @@ public class JMSServerControlRestartTest extends ManagementTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); serverManager = createJMSServer(); serverManager.start(); } - private JMSServerManager createJMSServer() throws Exception - { - Configuration config = createDefaultInVMConfig() - .setJMXManagementEnabled(true) - .setJournalType(JournalType.NIO); + private JMSServerManager createJMSServer() throws Exception { + Configuration config = createDefaultInVMConfig().setJMXManagementEnabled(true).setJournalType(JournalType.NIO); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, mbeanServer)); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSServerControlTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSServerControlTest.java index d4f827a767..8200791c63 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSServerControlTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSServerControlTest.java @@ -75,8 +75,7 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -public class JMSServerControlTest extends ManagementTestBase -{ +public class JMSServerControlTest extends ManagementTestBase { // Attributes ---------------------------------------------------- protected InVMNamingContext context; @@ -89,13 +88,10 @@ public class JMSServerControlTest extends ManagementTestBase // Static -------------------------------------------------------- - private static String toCSV(final Object[] objects) - { + private static String toCSV(final Object[] objects) { StringBuilder str = new StringBuilder(); - for (int i = 0; i < objects.length; i++) - { - if (i > 0) - { + for (int i = 0; i < objects.length; i++) { + if (i > 0) { str.append(", "); } str.append(objects[i]); @@ -110,22 +106,19 @@ public class JMSServerControlTest extends ManagementTestBase /** * Number of consumers used by the test itself */ - protected int getNumberOfConsumers() - { + protected int getNumberOfConsumers() { return 0; } @Test - public void testGetVersion() throws Exception - { + public void testGetVersion() throws Exception { JMSServerControl control = createManagementControl(); String version = control.getVersion(); Assert.assertEquals(serverManager.getVersion(), version); } @Test - public void testCreateQueueWithBindings() throws Exception - { + public void testCreateQueueWithBindings() throws Exception { String[] bindings = new String[3]; bindings[0] = RandomUtil.randomString(); bindings[1] = RandomUtil.randomString(); @@ -162,8 +155,7 @@ public class JMSServerControlTest extends ManagementTestBase } @Test - public void testCreateQueueWithCommaBindings() throws Exception - { + public void testCreateQueueWithCommaBindings() throws Exception { String[] bindings = new String[3]; bindings[0] = "first,first"; bindings[1] = "second,second"; @@ -200,8 +192,7 @@ public class JMSServerControlTest extends ManagementTestBase } @Test - public void testCreateQueueWithSelector() throws Exception - { + public void testCreateQueueWithSelector() throws Exception { String[] bindings = new String[3]; bindings[0] = RandomUtil.randomString(); bindings[1] = RandomUtil.randomString(); @@ -222,29 +213,17 @@ public class JMSServerControlTest extends ManagementTestBase Queue queue = (Queue) o; // assertEquals(((ActiveMQDestination)queue).get); Assert.assertEquals(queueName, queue.getQueueName()); - Assert.assertEquals(selector, server.getPostOffice() - .getBinding(new SimpleString("jms.queue." + queueName)) - .getFilter() - .getFilterString() - .toString()); + Assert.assertEquals(selector, server.getPostOffice().getBinding(new SimpleString("jms.queue." + queueName)).getFilter().getFilterString().toString()); o = ActiveMQTestBase.checkBinding(context, bindings[1]); Assert.assertTrue(o instanceof Queue); queue = (Queue) o; Assert.assertEquals(queueName, queue.getQueueName()); - Assert.assertEquals(selector, server.getPostOffice() - .getBinding(new SimpleString("jms.queue." + queueName)) - .getFilter() - .getFilterString() - .toString()); + Assert.assertEquals(selector, server.getPostOffice().getBinding(new SimpleString("jms.queue." + queueName)).getFilter().getFilterString().toString()); o = ActiveMQTestBase.checkBinding(context, bindings[2]); Assert.assertTrue(o instanceof Queue); queue = (Queue) o; Assert.assertEquals(queueName, queue.getQueueName()); - Assert.assertEquals(selector, server.getPostOffice() - .getBinding(new SimpleString("jms.queue." + queueName)) - .getFilter() - .getFilterString() - .toString()); + Assert.assertEquals(selector, server.getPostOffice().getBinding(new SimpleString("jms.queue." + queueName)).getFilter().getFilterString().toString()); checkResource(ObjectNameBuilder.DEFAULT.getJMSQueueObjectName(queueName)); Assert.assertNotNull(fakeJMSStorageManager.destinationMap.get(queueName)); @@ -255,8 +234,7 @@ public class JMSServerControlTest extends ManagementTestBase } @Test - public void testCreateNonDurableQueue() throws Exception - { + public void testCreateNonDurableQueue() throws Exception { String queueName = RandomUtil.randomString(); String binding = RandomUtil.randomString(); @@ -270,8 +248,7 @@ public class JMSServerControlTest extends ManagementTestBase Assert.assertTrue(o instanceof Queue); Queue queue = (Queue) o; Assert.assertEquals(queueName, queue.getQueueName()); - QueueBinding queueBinding = (QueueBinding) server.getPostOffice() - .getBinding(new SimpleString("jms.queue." + queueName)); + QueueBinding queueBinding = (QueueBinding) server.getPostOffice().getBinding(new SimpleString("jms.queue." + queueName)); Assert.assertFalse(queueBinding.getQueue().isDurable()); checkResource(ObjectNameBuilder.DEFAULT.getJMSQueueObjectName(queueName)); @@ -281,8 +258,7 @@ public class JMSServerControlTest extends ManagementTestBase } @Test - public void testDestroyQueue() throws Exception - { + public void testDestroyQueue() throws Exception { String queueJNDIBinding = RandomUtil.randomString(); String queueName = RandomUtil.randomString(); @@ -304,8 +280,7 @@ public class JMSServerControlTest extends ManagementTestBase } @Test - public void testDestroyQueueWithConsumers() throws Exception - { + public void testDestroyQueueWithConsumers() throws Exception { String queueJNDIBinding = RandomUtil.randomString(); String queueName = RandomUtil.randomString(); @@ -318,11 +293,9 @@ public class JMSServerControlTest extends ManagementTestBase ActiveMQTestBase.checkBinding(context, queueJNDIBinding); checkResource(ObjectNameBuilder.DEFAULT.getJMSQueueObjectName(queueName)); - ActiveMQConnectionFactory cf = - new ActiveMQConnectionFactory(false, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(false, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection(); - try - { + try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // create a consumer will create a Core queue bound to the topic address ActiveMQMessageConsumer cons = (ActiveMQMessageConsumer) session.createConsumer(ActiveMQJMSClient.createQueue(queueName)); @@ -335,34 +308,28 @@ public class JMSServerControlTest extends ManagementTestBase Assert.assertNull(fakeJMSStorageManager.destinationMap.get(queueName)); long time = System.currentTimeMillis(); - while (!cons.isClosed() && time + 5000 > System.currentTimeMillis()) - { + while (!cons.isClosed() && time + 5000 > System.currentTimeMillis()) { Thread.sleep(100); } Assert.assertTrue(cons.isClosed()); - try - { + try { cons.receive(5000); Assert.fail("should throw exception"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { Assert.assertTrue(e.getCause() instanceof ActiveMQObjectClosedException); } } - finally - { - if (connection != null) - { + finally { + if (connection != null) { connection.close(); } } } @Test - public void testDestroyQueueWithConsumersWithoutForcingTheConsumersToClose() throws Exception - { + public void testDestroyQueueWithConsumersWithoutForcingTheConsumersToClose() throws Exception { String queueJNDIBinding = RandomUtil.randomString(); String queueName = RandomUtil.randomString(); @@ -378,21 +345,18 @@ public class JMSServerControlTest extends ManagementTestBase ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(false, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection(); connection.start(); - try - { + try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(ActiveMQJMSClient.createQueue(queueName)); producer.send(session.createTextMessage()); // create a consumer will create a Core queue bound to the topic address ActiveMQMessageConsumer cons = (ActiveMQMessageConsumer) session.createConsumer(ActiveMQJMSClient.createQueue(queueName)); - try - { + try { control.destroyQueue(queueName, false); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { Assert.assertTrue(e.getMessage().startsWith("AMQ119025")); } @@ -405,19 +369,15 @@ public class JMSServerControlTest extends ManagementTestBase Assert.assertNotNull(cons.receive(5000)); } - finally - { - if (connection != null) - { + finally { + if (connection != null) { connection.close(); } } } - @Test - public void testDestroyTopicWithConsumersWithoutForcingTheConsumersToClose() throws Exception - { + public void testDestroyTopicWithConsumersWithoutForcingTheConsumersToClose() throws Exception { String topicJNDIBinding = RandomUtil.randomString(); String topicName = RandomUtil.randomString(); @@ -433,21 +393,18 @@ public class JMSServerControlTest extends ManagementTestBase ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(false, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection(); connection.start(); - try - { + try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // create a consumer will create a Core queue bound to the topic address ActiveMQMessageConsumer cons = (ActiveMQMessageConsumer) session.createConsumer(ActiveMQJMSClient.createTopic(topicName)); MessageProducer producer = session.createProducer(ActiveMQJMSClient.createTopic(topicName)); producer.send(session.createTextMessage()); - try - { + try { control.destroyTopic(topicName, false); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { Assert.assertTrue(e.getMessage().startsWith("AMQ119025")); } @@ -457,19 +414,15 @@ public class JMSServerControlTest extends ManagementTestBase Assert.assertNotNull(cons.receive(5000)); } - finally - { - if (connection != null) - { + finally { + if (connection != null) { connection.close(); } } } - @Test - public void testDestroyTopicWithConsumers() throws Exception - { + public void testDestroyTopicWithConsumers() throws Exception { String topicJNDIBinding = RandomUtil.randomString(); String topicName = RandomUtil.randomString(); @@ -482,11 +435,9 @@ public class JMSServerControlTest extends ManagementTestBase ActiveMQTestBase.checkBinding(context, topicJNDIBinding); checkResource(ObjectNameBuilder.DEFAULT.getJMSTopicObjectName(topicName)); - ActiveMQConnectionFactory cf = - new ActiveMQConnectionFactory(false, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(false, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection(); - try - { + try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // create a consumer will create a Core queue bound to the topic address ActiveMQMessageConsumer cons = (ActiveMQMessageConsumer) session.createConsumer(ActiveMQJMSClient.createTopic(topicName)); @@ -497,34 +448,28 @@ public class JMSServerControlTest extends ManagementTestBase checkNoResource(ObjectNameBuilder.DEFAULT.getJMSTopicObjectName(topicName)); long time = System.currentTimeMillis(); - while (!cons.isClosed() && time + 5000 > System.currentTimeMillis()) - { + while (!cons.isClosed() && time + 5000 > System.currentTimeMillis()) { Thread.sleep(100); } Assert.assertTrue(cons.isClosed()); - try - { + try { cons.receive(5000); Assert.fail("should throw exception"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { Assert.assertTrue(e.getCause() instanceof ActiveMQObjectClosedException); } } - finally - { - if (connection != null) - { + finally { + if (connection != null) { connection.close(); } } } @Test - public void testDestroyQueueWithConsumersNetty() throws Exception - { + public void testDestroyQueueWithConsumersNetty() throws Exception { String queueJNDIBinding = RandomUtil.randomString(); String queueName = RandomUtil.randomString(); @@ -537,12 +482,10 @@ public class JMSServerControlTest extends ManagementTestBase ActiveMQTestBase.checkBinding(context, queueJNDIBinding); checkResource(ObjectNameBuilder.DEFAULT.getJMSQueueObjectName(queueName)); - ActiveMQConnectionFactory cf = - new ActiveMQConnectionFactory(false, new TransportConfiguration(ActiveMQTestBase.NETTY_CONNECTOR_FACTORY)); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(false, new TransportConfiguration(ActiveMQTestBase.NETTY_CONNECTOR_FACTORY)); cf.setReconnectAttempts(-1); ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection(); - try - { + try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // create a consumer will create a Core queue bound to the topic address MessageConsumer cons = session.createConsumer(ActiveMQJMSClient.createQueue(queueName)); @@ -555,35 +498,29 @@ public class JMSServerControlTest extends ManagementTestBase Assert.assertNull(fakeJMSStorageManager.destinationMap.get(queueName)); long timeout = System.currentTimeMillis() + 1000; - while (timeout > System.currentTimeMillis() && !((ActiveMQMessageConsumer)cons).isClosed()) - { + while (timeout > System.currentTimeMillis() && !((ActiveMQMessageConsumer) cons).isClosed()) { Thread.sleep(1); } - Assert.assertTrue(((ActiveMQMessageConsumer)cons).isClosed()); + Assert.assertTrue(((ActiveMQMessageConsumer) cons).isClosed()); - try - { + try { cons.receive(5000); Assert.fail("should throw exception"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { Assert.assertTrue(e.getCause() instanceof ActiveMQObjectClosedException); } } - finally - { - if (connection != null) - { + finally { + if (connection != null) { connection.close(); } } } @Test - public void testGetQueueNames() throws Exception - { + public void testGetQueueNames() throws Exception { String queueJNDIBinding = RandomUtil.randomString(); String queueName = RandomUtil.randomString(); @@ -602,8 +539,7 @@ public class JMSServerControlTest extends ManagementTestBase } @Test - public void testCreateTopic() throws Exception - { + public void testCreateTopic() throws Exception { String[] bindings = new String[3]; bindings[0] = RandomUtil.randomString(); bindings[1] = RandomUtil.randomString(); @@ -640,8 +576,7 @@ public class JMSServerControlTest extends ManagementTestBase } @Test - public void testDestroyTopic() throws Exception - { + public void testDestroyTopic() throws Exception { String topicJNDIBinding = RandomUtil.randomString(); String topicName = RandomUtil.randomString(); @@ -654,16 +589,14 @@ public class JMSServerControlTest extends ManagementTestBase checkResource(ObjectNameBuilder.DEFAULT.getJMSTopicObjectName(topicName)); Topic topic = (Topic) context.lookup(topicJNDIBinding); Assert.assertNotNull(topic); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(false, - new TransportConfiguration(InVMConnectorFactory.class.getName())); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(false, new TransportConfiguration(InVMConnectorFactory.class.getName())); Connection connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // create a consumer will create a Core queue bound to the topic address session.createConsumer(topic); String topicAddress = ActiveMQDestination.createTopicAddressFromName(topicName).toString(); - AddressControl addressControl = (AddressControl) server.getManagementService() - .getResource(ResourceNames.CORE_ADDRESS + topicAddress); + AddressControl addressControl = (AddressControl) server.getManagementService().getResource(ResourceNames.CORE_ADDRESS + topicAddress); Assert.assertNotNull(addressControl); Assert.assertTrue(addressControl.getQueueNames().length > 0); @@ -679,8 +612,7 @@ public class JMSServerControlTest extends ManagementTestBase } @Test - public void testListAllConsumers() throws Exception - { + public void testListAllConsumers() throws Exception { String topicJNDIBinding = RandomUtil.randomString(); String topicName = RandomUtil.randomString(); @@ -693,8 +625,7 @@ public class JMSServerControlTest extends ManagementTestBase checkResource(ObjectNameBuilder.DEFAULT.getJMSTopicObjectName(topicName)); Topic topic = (Topic) context.lookup(topicJNDIBinding); Assert.assertNotNull(topic); - ActiveMQConnectionFactory cf = - new ActiveMQConnectionFactory(false, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(false, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); Connection connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // create a consumer will create a Core queue bound to the topic address @@ -711,8 +642,7 @@ public class JMSServerControlTest extends ManagementTestBase Assert.assertEquals(getNumberOfConsumers(), jsonArray.length()); String topicAddress = ActiveMQDestination.createTopicAddressFromName(topicName).toString(); - AddressControl addressControl = (AddressControl) server.getManagementService() - .getResource(ResourceNames.CORE_ADDRESS + topicAddress); + AddressControl addressControl = (AddressControl) server.getManagementService().getResource(ResourceNames.CORE_ADDRESS + topicAddress); Assert.assertNotNull(addressControl); Assert.assertTrue(addressControl.getQueueNames().length > 0); @@ -728,8 +658,7 @@ public class JMSServerControlTest extends ManagementTestBase } @Test - public void testGetTopicNames() throws Exception - { + public void testGetTopicNames() throws Exception { String topicJNDIBinding = RandomUtil.randomString(); String topicName = RandomUtil.randomString(); @@ -748,18 +677,13 @@ public class JMSServerControlTest extends ManagementTestBase } @Test - public void testCreateConnectionFactory_3b() throws Exception - { - server.getConfiguration() - .getConnectorConfigurations() - .put("tst", new TransportConfiguration(INVM_CONNECTOR_FACTORY)); + public void testCreateConnectionFactory_3b() throws Exception { + server.getConfiguration().getConnectorConfigurations().put("tst", new TransportConfiguration(INVM_CONNECTOR_FACTORY)); - doCreateConnectionFactory(new ConnectionFactoryCreator() - { + doCreateConnectionFactory(new ConnectionFactoryCreator() { public void createConnectionFactory(final JMSServerControl control, final String cfName, - final Object[] bindings) throws Exception - { + final Object[] bindings) throws Exception { String jndiBindings = JMSServerControlTest.toCSV(bindings); control.createConnectionFactory(cfName, false, false, 0, "tst", jndiBindings); @@ -768,8 +692,7 @@ public class JMSServerControlTest extends ManagementTestBase } @Test - public void testCreateConnectionFactory_CompleteList() throws Exception - { + public void testCreateConnectionFactory_CompleteList() throws Exception { JMSServerControl control = createManagementControl(); control.createConnectionFactory("test", //name true, // ha @@ -807,7 +730,6 @@ public class JMSServerControlTest extends ManagementTestBase true, // failoverOnInitialConnection "tst"); // groupID - ActiveMQQueueConnectionFactory cf = (ActiveMQQueueConnectionFactory) context.lookup("tst"); Assert.assertEquals(true, cf.isHA()); @@ -892,22 +814,17 @@ public class JMSServerControlTest extends ManagementTestBase Assert.assertFalse(mbeanServer.isRegistered(nameBuilder.getConnectionFactoryObjectName("test"))); - - try - { + try { cf = (ActiveMQQueueConnectionFactory) context.lookup("tst"); Assert.fail("Failure expected"); } - catch (NamingException e) - { + catch (NamingException e) { } - } @Test - public void testDestroyConnectionFactoryWithNullBindings() throws Exception - { + public void testDestroyConnectionFactoryWithNullBindings() throws Exception { // Create Connection Factory with Null Bindings JMSServerControl control = createManagementControl(); control.createConnectionFactory("test-cf", // Name @@ -923,17 +840,14 @@ public class JMSServerControlTest extends ManagementTestBase } @Test - public void testListPreparedTransactionDetails() throws Exception - { + public void testListPreparedTransactionDetails() throws Exception { Xid xid = newXID(); JMSServerControl control = createManagementControl(); String cfJNDIBinding = "/cf"; String cfName = "cf"; - server.getConfiguration() - .getConnectorConfigurations() - .put("tst", new TransportConfiguration(INVM_CONNECTOR_FACTORY)); + server.getConfiguration().getConnectorConfigurations().put("tst", new TransportConfiguration(INVM_CONNECTOR_FACTORY)); control.createConnectionFactory(cfName, false, false, 3, "tst", cfJNDIBinding); @@ -963,8 +877,7 @@ public class JMSServerControlTest extends ManagementTestBase } @Test - public void testListPreparedTranscationDetailsAsHTML() throws Exception - { + public void testListPreparedTranscationDetailsAsHTML() throws Exception { Xid xid = newXID(); JMSServerControl control = createManagementControl(); @@ -972,9 +885,7 @@ public class JMSServerControlTest extends ManagementTestBase String cfJNDIBinding = "/cf"; String cfName = "cf"; - server.getConfiguration() - .getConnectorConfigurations() - .put("tst", new TransportConfiguration(INVM_CONNECTOR_FACTORY)); + server.getConfiguration().getConnectorConfigurations().put("tst", new TransportConfiguration(INVM_CONNECTOR_FACTORY)); control.createConnectionFactory(cfName, false, false, 3, "tst", cfJNDIBinding); @@ -1003,14 +914,11 @@ public class JMSServerControlTest extends ManagementTestBase control.listPreparedTransactionDetailsAsHTML(); } - @Test - public void testRemoteClientIDConnection() throws Exception - { + public void testRemoteClientIDConnection() throws Exception { JMSServerControl control = createManagementControl(); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(false, - new TransportConfiguration(InVMConnectorFactory.class.getName())); + ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(false, new TransportConfiguration(InVMConnectorFactory.class.getName())); Connection connection = cf.createConnection(); connection.setClientID("someID"); @@ -1018,12 +926,10 @@ public class JMSServerControlTest extends ManagementTestBase Connection connection2 = cf.createConnection(); boolean failed = false; - try - { + try { connection2.setClientID("someID"); } - catch (JMSException e) - { + catch (JMSException e) { failed = true; } @@ -1033,16 +939,13 @@ public class JMSServerControlTest extends ManagementTestBase connection2.setClientID("someID"); - failed = false; Connection connection3 = cf.createConnection(); - try - { + try { connection3.setClientID("someID"); } - catch (JMSException e) - { + catch (JMSException e) { failed = true; } @@ -1055,8 +958,7 @@ public class JMSServerControlTest extends ManagementTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); startServer(); @@ -1065,12 +967,8 @@ public class JMSServerControlTest extends ManagementTestBase /** * @throws Exception */ - protected void startServer() throws Exception - { - Configuration config = createDefaultNettyConfig() - .setJMXManagementEnabled(true) - .addConnectorConfiguration("netty", new TransportConfiguration(ActiveMQTestBase.NETTY_CONNECTOR_FACTORY)) - .addConnectorConfiguration("invm", new TransportConfiguration(INVM_CONNECTOR_FACTORY)); + protected void startServer() throws Exception { + Configuration config = createDefaultNettyConfig().setJMXManagementEnabled(true).addConnectorConfiguration("netty", new TransportConfiguration(ActiveMQTestBase.NETTY_CONNECTOR_FACTORY)).addConnectorConfiguration("invm", new TransportConfiguration(INVM_CONNECTOR_FACTORY)); server = addServer(ActiveMQServers.newActiveMQServer(config, mbeanServer, true)); @@ -1085,24 +983,18 @@ public class JMSServerControlTest extends ManagementTestBase serverManager.replaceStorageManager(fakeJMSStorageManager); } - protected JMSServerControl createManagementControl() throws Exception - { + protected JMSServerControl createManagementControl() throws Exception { return ManagementControlHelper.createJMSServerControl(mbeanServer); } // Private ------------------------------------------------------- - private void doCreateConnectionFactory(final ConnectionFactoryCreator creator) throws Exception - { - Object[] cfJNDIBindings = new Object[]{ - RandomUtil.randomString(), - RandomUtil.randomString(), - RandomUtil.randomString()}; + private void doCreateConnectionFactory(final ConnectionFactoryCreator creator) throws Exception { + Object[] cfJNDIBindings = new Object[]{RandomUtil.randomString(), RandomUtil.randomString(), RandomUtil.randomString()}; String cfName = RandomUtil.randomString(); - for (Object cfJNDIBinding : cfJNDIBindings) - { + for (Object cfJNDIBinding : cfJNDIBindings) { ActiveMQTestBase.checkNoBinding(context, cfJNDIBinding.toString()); } checkNoResource(ObjectNameBuilder.DEFAULT.getConnectionFactoryObjectName(cfName)); @@ -1110,8 +1002,7 @@ public class JMSServerControlTest extends ManagementTestBase JMSServerControl control = createManagementControl(); creator.createConnectionFactory(control, cfName, cfJNDIBindings); - for (Object cfJNDIBinding : cfJNDIBindings) - { + for (Object cfJNDIBinding : cfJNDIBindings) { Object o = ActiveMQTestBase.checkBinding(context, cfJNDIBinding.toString()); Assert.assertTrue(o instanceof ConnectionFactory); ConnectionFactory cf = (ConnectionFactory) o; @@ -1128,13 +1019,13 @@ public class JMSServerControlTest extends ManagementTestBase // Inner classes ------------------------------------------------- - interface ConnectionFactoryCreator - { + interface ConnectionFactoryCreator { + void createConnectionFactory(JMSServerControl control, String cfName, Object[] bindings) throws Exception; } - class FakeJMSStorageManager implements JMSStorageManager - { + class FakeJMSStorageManager implements JMSStorageManager { + Map destinationMap = new HashMap(); Map connectionFactoryMap = new HashMap(); @@ -1143,89 +1034,73 @@ public class JMSServerControlTest extends ManagementTestBase JMSStorageManager delegate; - public FakeJMSStorageManager(JMSStorageManager delegate) - { + public FakeJMSStorageManager(JMSStorageManager delegate) { this.delegate = delegate; } - public void storeDestination(PersistedDestination destination) throws Exception - { + public void storeDestination(PersistedDestination destination) throws Exception { destinationMap.put(destination.getName(), destination); delegate.storeDestination(destination); } - public void deleteDestination(PersistedType type, String name) throws Exception - { + public void deleteDestination(PersistedType type, String name) throws Exception { destinationMap.remove(name); delegate.deleteDestination(type, name); } - public List recoverDestinations() - { + public List recoverDestinations() { return delegate.recoverDestinations(); } - public void deleteConnectionFactory(String connectionFactory) throws Exception - { + public void deleteConnectionFactory(String connectionFactory) throws Exception { connectionFactoryMap.remove(connectionFactory); delegate.deleteConnectionFactory(connectionFactory); } - public void storeConnectionFactory(PersistedConnectionFactory connectionFactory) throws Exception - { + public void storeConnectionFactory(PersistedConnectionFactory connectionFactory) throws Exception { connectionFactoryMap.put(connectionFactory.getName(), connectionFactory); delegate.storeConnectionFactory(connectionFactory); } - public List recoverConnectionFactories() - { + public List recoverConnectionFactories() { return delegate.recoverConnectionFactories(); } - public void addBindings(PersistedType type, String name, String... address) throws Exception - { + public void addBindings(PersistedType type, String name, String... address) throws Exception { persistedJNDIMap.putIfAbsent(name, new ArrayList()); - for (String ad : address) - { + for (String ad : address) { persistedJNDIMap.get(name).add(ad); } delegate.addBindings(type, name, address); } - public List recoverPersistedBindings() throws Exception - { + public List recoverPersistedBindings() throws Exception { return delegate.recoverPersistedBindings(); } - public void deleteBindings(PersistedType type, String name, String address) throws Exception - { + public void deleteBindings(PersistedType type, String name, String address) throws Exception { persistedJNDIMap.get(name).remove(address); delegate.deleteBindings(type, name, address); } - public void deleteBindings(PersistedType type, String name) throws Exception - { + public void deleteBindings(PersistedType type, String name) throws Exception { persistedJNDIMap.get(name).clear(); delegate.deleteBindings(type, name); } - public void start() throws Exception - { + public void start() throws Exception { delegate.start(); } - public void stop() throws Exception - { + public void stop() throws Exception { delegate.stop(); } - public boolean isStarted() - { + public boolean isStarted() { return delegate.isStarted(); } - public void load() throws Exception - { + public void load() throws Exception { delegate.load(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSServerControlUsingJMSTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSServerControlUsingJMSTest.java index 5913b06283..abf4d3fc84 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSServerControlUsingJMSTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSServerControlUsingJMSTest.java @@ -34,8 +34,7 @@ import javax.jms.QueueConnection; import javax.jms.QueueSession; import javax.jms.Session; -public class JMSServerControlUsingJMSTest extends JMSServerControlTest -{ +public class JMSServerControlUsingJMSTest extends JMSServerControlTest { // Constants ----------------------------------------------------- @@ -47,11 +46,9 @@ public class JMSServerControlUsingJMSTest extends JMSServerControlTest // Static -------------------------------------------------------- - private static String[] toStringArray(final Object[] res) - { + private static String[] toStringArray(final Object[] res) { String[] names = new String[res.length]; - for (int i = 0; i < res.length; i++) - { + for (int i = 0; i < res.length; i++) { names[i] = res[i].toString(); } return names; @@ -60,8 +57,7 @@ public class JMSServerControlUsingJMSTest extends JMSServerControlTest // The JMS test won't support the server being restarted, hence we have to do a slight different test on that case @Override @Test - public void testCreateConnectionFactory_CompleteList() throws Exception - { + public void testCreateConnectionFactory_CompleteList() throws Exception { JMSServerControl control = createManagementControl(); control.createConnectionFactory("test", //name true, // ha @@ -99,8 +95,7 @@ public class JMSServerControlUsingJMSTest extends JMSServerControlTest true, // failoverOnInitialConnection "tst"); // groupID - - ActiveMQQueueConnectionFactory cf = (ActiveMQQueueConnectionFactory)context.lookup("tst"); + ActiveMQQueueConnectionFactory cf = (ActiveMQQueueConnectionFactory) context.lookup("tst"); Assert.assertEquals(true, cf.isHA()); Assert.assertEquals("tst", cf.getClientID()); @@ -137,187 +132,154 @@ public class JMSServerControlUsingJMSTest extends JMSServerControlTest // JMSServerControlTest overrides -------------------------------- @Override - protected int getNumberOfConsumers() - { + protected int getNumberOfConsumers() { return 1; } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, - new TransportConfiguration(InVMConnectorFactory.class.getName())); + ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(InVMConnectorFactory.class.getName())); connection = cf.createQueueConnection(); session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); connection.start(); } @Override - protected JMSServerControl createManagementControl() throws Exception - { + protected JMSServerControl createManagementControl() throws Exception { ActiveMQQueue managementQueue = (ActiveMQQueue) ActiveMQJMSClient.createQueue("activemq.management"); final JMSMessagingProxy proxy = new JMSMessagingProxy(session, managementQueue, ResourceNames.JMS_SERVER); - return new JMSServerControl() - { + return new JMSServerControl() { - public boolean closeConnectionsForAddress(final String ipAddress) throws Exception - { - return (Boolean)proxy.invokeOperation("closeConnectionsForAddress", ipAddress); + public boolean closeConnectionsForAddress(final String ipAddress) throws Exception { + return (Boolean) proxy.invokeOperation("closeConnectionsForAddress", ipAddress); } - public boolean closeConsumerConnectionsForAddress(final String address) throws Exception - { - return (Boolean)proxy.invokeOperation("closeConsumerConnectionsForAddress", address); + public boolean closeConsumerConnectionsForAddress(final String address) throws Exception { + return (Boolean) proxy.invokeOperation("closeConsumerConnectionsForAddress", address); } - public boolean closeConnectionsForUser(final String userName) throws Exception - { - return (Boolean)proxy.invokeOperation("closeConnectionsForUser", userName); + public boolean closeConnectionsForUser(final String userName) throws Exception { + return (Boolean) proxy.invokeOperation("closeConnectionsForUser", userName); } - public boolean createQueue(final String name) throws Exception - { - return (Boolean)proxy.invokeOperation("createQueue", name); + public boolean createQueue(final String name) throws Exception { + return (Boolean) proxy.invokeOperation("createQueue", name); } - public boolean createQueue(String name, String jndiBindings, String selector) throws Exception - { - return (Boolean)proxy.invokeOperation("createQueue", name, jndiBindings, selector); + public boolean createQueue(String name, String jndiBindings, String selector) throws Exception { + return (Boolean) proxy.invokeOperation("createQueue", name, jndiBindings, selector); } - public boolean createQueue(String name, String jndiBindings, String selector, boolean durable) throws Exception - { - return (Boolean)proxy.invokeOperation("createQueue", name, jndiBindings, selector, durable); + public boolean createQueue(String name, + String jndiBindings, + String selector, + boolean durable) throws Exception { + return (Boolean) proxy.invokeOperation("createQueue", name, jndiBindings, selector, durable); } - public boolean createTopic(final String name) throws Exception - { - return (Boolean)proxy.invokeOperation("createTopic", name); + public boolean createTopic(final String name) throws Exception { + return (Boolean) proxy.invokeOperation("createTopic", name); } - public void destroyConnectionFactory(final String name) throws Exception - { + public void destroyConnectionFactory(final String name) throws Exception { proxy.invokeOperation("destroyConnectionFactory", name); } - public boolean destroyQueue(final String name) throws Exception - { - return (Boolean)proxy.invokeOperation("destroyQueue", name); + public boolean destroyQueue(final String name) throws Exception { + return (Boolean) proxy.invokeOperation("destroyQueue", name); } @Override - public boolean destroyQueue(String name, boolean removeConsumers) throws Exception - { - return (Boolean)proxy.invokeOperation("destroyQueue", name, removeConsumers); + public boolean destroyQueue(String name, boolean removeConsumers) throws Exception { + return (Boolean) proxy.invokeOperation("destroyQueue", name, removeConsumers); } - public boolean destroyTopic(final String name) throws Exception - { - return (Boolean)proxy.invokeOperation("destroyTopic", name); + public boolean destroyTopic(final String name) throws Exception { + return (Boolean) proxy.invokeOperation("destroyTopic", name); } - public boolean destroyTopic(final String name, boolean removeConsumers) throws Exception - { - return (Boolean)proxy.invokeOperation("destroyTopic", name, removeConsumers); + public boolean destroyTopic(final String name, boolean removeConsumers) throws Exception { + return (Boolean) proxy.invokeOperation("destroyTopic", name, removeConsumers); } - public String getVersion() - { - return (String)proxy.retrieveAttributeValue("version"); + public String getVersion() { + return (String) proxy.retrieveAttributeValue("version"); } - public boolean isStarted() - { - return (Boolean)proxy.retrieveAttributeValue("started"); + public boolean isStarted() { + return (Boolean) proxy.retrieveAttributeValue("started"); } - public String[] getQueueNames() - { - return JMSServerControlUsingJMSTest.toStringArray((Object[])proxy.retrieveAttributeValue("queueNames")); + public String[] getQueueNames() { + return JMSServerControlUsingJMSTest.toStringArray((Object[]) proxy.retrieveAttributeValue("queueNames")); } - public String[] getTopicNames() - { - return JMSServerControlUsingJMSTest.toStringArray((Object[])proxy.retrieveAttributeValue("topicNames")); + public String[] getTopicNames() { + return JMSServerControlUsingJMSTest.toStringArray((Object[]) proxy.retrieveAttributeValue("topicNames")); } - public String[] getConnectionFactoryNames() - { - return JMSServerControlUsingJMSTest.toStringArray((Object[])proxy.retrieveAttributeValue("connectionFactoryNames")); + public String[] getConnectionFactoryNames() { + return JMSServerControlUsingJMSTest.toStringArray((Object[]) proxy.retrieveAttributeValue("connectionFactoryNames")); } - public String[] listConnectionIDs() throws Exception - { - return (String[])proxy.invokeOperation("listConnectionIDs"); + public String[] listConnectionIDs() throws Exception { + return (String[]) proxy.invokeOperation("listConnectionIDs"); } - public String listConnectionsAsJSON() throws Exception - { - return (String)proxy.invokeOperation("listConnectionsAsJSON"); + public String listConnectionsAsJSON() throws Exception { + return (String) proxy.invokeOperation("listConnectionsAsJSON"); } - public String listConsumersAsJSON(String connectionID) throws Exception - { - return (String)proxy.invokeOperation("listConsumersAsJSON", connectionID); + public String listConsumersAsJSON(String connectionID) throws Exception { + return (String) proxy.invokeOperation("listConsumersAsJSON", connectionID); } - public String[] listRemoteAddresses() throws Exception - { - return (String[])proxy.invokeOperation("listRemoteAddresses"); + public String[] listRemoteAddresses() throws Exception { + return (String[]) proxy.invokeOperation("listRemoteAddresses"); } - public String[] listRemoteAddresses(final String ipAddress) throws Exception - { - return (String[])proxy.invokeOperation("listRemoteAddresses", ipAddress); + public String[] listRemoteAddresses(final String ipAddress) throws Exception { + return (String[]) proxy.invokeOperation("listRemoteAddresses", ipAddress); } - public String[] listSessions(final String connectionID) throws Exception - { - return (String[])proxy.invokeOperation("listSessions", connectionID); + public String[] listSessions(final String connectionID) throws Exception { + return (String[]) proxy.invokeOperation("listSessions", connectionID); } - public boolean createQueue(String name, String jndiBinding) throws Exception - { - return (Boolean)proxy.invokeOperation("createQueue", name, jndiBinding); + public boolean createQueue(String name, String jndiBinding) throws Exception { + return (Boolean) proxy.invokeOperation("createQueue", name, jndiBinding); } - public boolean createTopic(String name, String jndiBinding) throws Exception - { - return (Boolean)proxy.invokeOperation("createTopic", name, jndiBinding); + public boolean createTopic(String name, String jndiBinding) throws Exception { + return (Boolean) proxy.invokeOperation("createTopic", name, jndiBinding); } - public String[] listTargetDestinations(String sessionID) throws Exception - { + public String[] listTargetDestinations(String sessionID) throws Exception { return null; } - public String getLastSentMessageID(String sessionID, String address) throws Exception - { + public String getLastSentMessageID(String sessionID, String address) throws Exception { return null; } - public String getSessionCreationTime(String sessionID) throws Exception - { - return (String)proxy.invokeOperation("getSessionCreationTime", sessionID); + public String getSessionCreationTime(String sessionID) throws Exception { + return (String) proxy.invokeOperation("getSessionCreationTime", sessionID); } - public String listSessionsAsJSON(String connectionID) throws Exception - { - return (String)proxy.invokeOperation("listSessionsAsJSON", connectionID); + public String listSessionsAsJSON(String connectionID) throws Exception { + return (String) proxy.invokeOperation("listSessionsAsJSON", connectionID); } - public String listPreparedTransactionDetailsAsJSON() throws Exception - { - return (String)proxy.invokeOperation("listPreparedTransactionDetailsAsJSON"); + public String listPreparedTransactionDetailsAsJSON() throws Exception { + return (String) proxy.invokeOperation("listPreparedTransactionDetailsAsJSON"); } - public String listPreparedTransactionDetailsAsHTML() throws Exception - { - return (String)proxy.invokeOperation("listPreparedTransactionDetailsAsHTML"); + public String listPreparedTransactionDetailsAsHTML() throws Exception { + return (String) proxy.invokeOperation("listPreparedTransactionDetailsAsHTML"); } public void createConnectionFactory(String name, @@ -325,8 +287,7 @@ public class JMSServerControlUsingJMSTest extends JMSServerControlTest boolean useDiscovery, int cfType, String[] connectorNames, - Object[] bindings) throws Exception - { + Object[] bindings) throws Exception { proxy.invokeOperation("createConnectionFactory", name, ha, useDiscovery, cfType, connectorNames, bindings); } @@ -336,14 +297,12 @@ public class JMSServerControlUsingJMSTest extends JMSServerControlTest boolean useDiscovery, int cfType, String connectors, - String jndiBindings) throws Exception - { + String jndiBindings) throws Exception { proxy.invokeOperation("createConnectionFactory", name, ha, useDiscovery, cfType, connectors, jndiBindings); } - public String listAllConsumersAsJSON() throws Exception - { - return (String)proxy.invokeOperation("listAllConsumersAsJSON"); + public String listAllConsumersAsJSON() throws Exception { + return (String) proxy.invokeOperation("listAllConsumersAsJSON"); } public void createConnectionFactory(String name, @@ -380,44 +339,8 @@ public class JMSServerControlUsingJMSTest extends JMSServerControlTest long maxRetryInterval, int reconnectAttempts, boolean failoverOnInitialConnection, - String groupId) throws Exception - { - proxy.invokeOperation("createConnectionFactory", - name, - ha, - useDiscovery, - cfType, - connectors, - jndiBindings, - clientID, - clientFailureCheckPeriod, - connectionTTL, - callTimeout, - callFailoverTimeout, - minLargeMessageSize, - compressLargeMessages, - consumerWindowSize, - consumerMaxRate, - confirmationWindowSize, - producerWindowSize, - producerMaxRate, - blockOnAcknowledge, - blockOnDurableSend, - blockOnNonDurableSend, - autoGroup, - preAcknowledge, - loadBalancingPolicyClassName, - transactionBatchSize, - dupsOKBatchSize, - useGlobalPools, - scheduledThreadPoolMaxSize, - threadPoolMaxSize, - retryInterval, - retryIntervalMultiplier, - maxRetryInterval, - reconnectAttempts, - failoverOnInitialConnection, - groupId); + String groupId) throws Exception { + proxy.invokeOperation("createConnectionFactory", name, ha, useDiscovery, cfType, connectors, jndiBindings, clientID, clientFailureCheckPeriod, connectionTTL, callTimeout, callFailoverTimeout, minLargeMessageSize, compressLargeMessages, consumerWindowSize, consumerMaxRate, confirmationWindowSize, producerWindowSize, producerMaxRate, blockOnAcknowledge, blockOnDurableSend, blockOnNonDurableSend, autoGroup, preAcknowledge, loadBalancingPolicyClassName, transactionBatchSize, dupsOKBatchSize, useGlobalPools, scheduledThreadPoolMaxSize, threadPoolMaxSize, retryInterval, retryIntervalMultiplier, maxRetryInterval, reconnectAttempts, failoverOnInitialConnection, groupId); } public void createConnectionFactory(String name, @@ -454,49 +377,12 @@ public class JMSServerControlUsingJMSTest extends JMSServerControlTest long maxRetryInterval, int reconnectAttempts, boolean failoverOnInitialConnection, - String groupId) throws Exception - { - proxy.invokeOperation("createConnectionFactory", - name, - ha, - useDiscovery, - cfType, - connectors, - jndiBindings, - clientID, - clientFailureCheckPeriod, - connectionTTL, - callTimeout, - callFailoverTimeout, - minLargeMessageSize, - compressLargeMessages, - consumerWindowSize, - consumerMaxRate, - confirmationWindowSize, - producerWindowSize, - producerMaxRate, - blockOnAcknowledge, - blockOnDurableSend, - blockOnNonDurableSend, - autoGroup, - preAcknowledge, - loadBalancingPolicyClassName, - transactionBatchSize, - dupsOKBatchSize, - useGlobalPools, - scheduledThreadPoolMaxSize, - threadPoolMaxSize, - retryInterval, - retryIntervalMultiplier, - maxRetryInterval, - reconnectAttempts, - failoverOnInitialConnection, - groupId); + String groupId) throws Exception { + proxy.invokeOperation("createConnectionFactory", name, ha, useDiscovery, cfType, connectors, jndiBindings, clientID, clientFailureCheckPeriod, connectionTTL, callTimeout, callFailoverTimeout, minLargeMessageSize, compressLargeMessages, consumerWindowSize, consumerMaxRate, confirmationWindowSize, producerWindowSize, producerMaxRate, blockOnAcknowledge, blockOnDurableSend, blockOnNonDurableSend, autoGroup, preAcknowledge, loadBalancingPolicyClassName, transactionBatchSize, dupsOKBatchSize, useGlobalPools, scheduledThreadPoolMaxSize, threadPoolMaxSize, retryInterval, retryIntervalMultiplier, maxRetryInterval, reconnectAttempts, failoverOnInitialConnection, groupId); } - public String closeConnectionWithClientID(String clientID) throws Exception - { - return (String)proxy.invokeOperation("closeConnectionWithClientID", clientID); + public String closeConnectionWithClientID(String clientID) throws Exception { + return (String) proxy.invokeOperation("closeConnectionWithClientID", clientID); } }; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSUtil.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSUtil.java index 0ae1a146bb..2912c00188 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSUtil.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSUtil.java @@ -56,8 +56,7 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; import org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory; import org.apache.activemq.artemis.tests.util.RandomUtil; -public class JMSUtil -{ +public class JMSUtil { // Constants ----------------------------------------------------- @@ -65,10 +64,8 @@ public class JMSUtil // Static -------------------------------------------------------- - public static Connection createConnection(final String connectorFactory) throws JMSException - { - ActiveMQJMSConnectionFactory cf = (ActiveMQJMSConnectionFactory) ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, - new TransportConfiguration(connectorFactory)); + public static Connection createConnection(final String connectorFactory) throws JMSException { + ActiveMQJMSConnectionFactory cf = (ActiveMQJMSConnectionFactory) ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(connectorFactory)); cf.setBlockOnNonDurableSend(true); cf.setBlockOnDurableSend(true); @@ -79,10 +76,8 @@ public class JMSUtil public static ConnectionFactory createFactory(final String connectorFactory, final long connectionTTL, - final long clientFailureCheckPeriod) throws JMSException - { - ActiveMQJMSConnectionFactory cf = (ActiveMQJMSConnectionFactory) ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, - new TransportConfiguration(connectorFactory)); + final long clientFailureCheckPeriod) throws JMSException { + ActiveMQJMSConnectionFactory cf = (ActiveMQJMSConnectionFactory) ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(connectorFactory)); cf.setBlockOnNonDurableSend(true); cf.setBlockOnDurableSend(true); @@ -93,13 +88,14 @@ public class JMSUtil return cf; } - static MessageConsumer createConsumer(final Connection connection, final Destination destination) throws JMSException - { + static MessageConsumer createConsumer(final Connection connection, + final Destination destination) throws JMSException { return createConsumer(connection, destination, Session.AUTO_ACKNOWLEDGE); } - static MessageConsumer createConsumer(final Connection connection, final Destination destination, int ackMode) throws JMSException - { + static MessageConsumer createConsumer(final Connection connection, + final Destination destination, + int ackMode) throws JMSException { Session s = connection.createSession(false, ackMode); return s.createConsumer(destination); @@ -108,8 +104,7 @@ public class JMSUtil static TopicSubscriber createDurableSubscriber(final Connection connection, final Topic topic, final String clientID, - final String subscriptionName) throws JMSException - { + final String subscriptionName) throws JMSException { return createDurableSubscriber(connection, topic, clientID, subscriptionName, Session.AUTO_ACKNOWLEDGE); } @@ -117,25 +112,21 @@ public class JMSUtil final Topic topic, final String clientID, final String subscriptionName, - final int ackMode) throws JMSException - { + final int ackMode) throws JMSException { connection.setClientID(clientID); Session s = connection.createSession(false, ackMode); return s.createDurableSubscriber(topic, subscriptionName); } - public static String[] sendMessages(final Destination destination, final int messagesToSend) throws Exception - { - ActiveMQJMSConnectionFactory cf = (ActiveMQJMSConnectionFactory) ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, - new TransportConfiguration(InVMConnectorFactory.class.getName())); + public static String[] sendMessages(final Destination destination, final int messagesToSend) throws Exception { + ActiveMQJMSConnectionFactory cf = (ActiveMQJMSConnectionFactory) ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(InVMConnectorFactory.class.getName())); return JMSUtil.sendMessages(cf, destination, messagesToSend); } public static String[] sendMessages(final ConnectionFactory cf, final Destination destination, - final int messagesToSend) throws Exception - { + final int messagesToSend) throws Exception { String[] messageIDs = new String[messagesToSend]; Connection conn = cf.createConnection(); @@ -143,8 +134,7 @@ public class JMSUtil Session s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = s.createProducer(destination); - for (int i = 0; i < messagesToSend; i++) - { + for (int i = 0; i < messagesToSend; i++) { Message m = s.createTextMessage(RandomUtil.randomString()); producer.send(m); messageIDs[i] = m.getJMSMessageID(); @@ -158,8 +148,7 @@ public class JMSUtil public static Message sendMessageWithProperty(final Session session, final Destination destination, final String key, - final long value) throws JMSException - { + final long value) throws JMSException { MessageProducer producer = session.createProducer(destination); Message message = session.createMessage(); message.setLongProperty(key, value); @@ -167,76 +156,62 @@ public class JMSUtil return message; } - public static void consumeMessages(final int expected, final Destination dest) throws JMSException - { + public static void consumeMessages(final int expected, final Destination dest) throws JMSException { Connection connection = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); - try - { + try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(dest); connection.start(); Message m = null; - for (int i = 0; i < expected; i++) - { + for (int i = 0; i < expected; i++) { m = consumer.receive(500); Assert.assertNotNull("expected to received " + expected + " messages, got only " + (i + 1), m); } m = consumer.receiveNoWait(); Assert.assertNull("received one more message than expected (" + expected + ")", m); } - finally - { - if (connection != null) - { + finally { + if (connection != null) { connection.close(); } } } - public static void waitForServer(ActiveMQServer server) throws InterruptedException - { + public static void waitForServer(ActiveMQServer server) throws InterruptedException { long timetowait = System.currentTimeMillis() + 5000; - while (!server.isStarted()) - { + while (!server.isStarted()) { Thread.sleep(100); - if (server.isStarted()) - { + if (server.isStarted()) { break; } - else if (System.currentTimeMillis() > timetowait) - { + else if (System.currentTimeMillis() > timetowait) { throw new IllegalStateException("server didn't start"); } } } - public static void crash(ActiveMQServer server, ClientSession... sessions) throws Exception - { + public static void crash(ActiveMQServer server, ClientSession... sessions) throws Exception { final CountDownLatch latch = new CountDownLatch(sessions.length); - class MyListener implements SessionFailureListener - { + class MyListener implements SessionFailureListener { + @Override - public void connectionFailed(final ActiveMQException me, boolean failedOver) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver) { latch.countDown(); } @Override - public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) { connectionFailed(me, failedOver); } - public void beforeReconnect(ActiveMQException exception) - { + public void beforeReconnect(ActiveMQException exception) { System.out.println("MyListener.beforeReconnect"); } } - for (ClientSession session : sessions) - { + for (ClientSession session : sessions) { session.addFailureListener(new MyListener()); } @@ -263,9 +238,8 @@ public class JMSUtil // Inner classes ------------------------------------------------- public static ActiveMQConnection createConnectionAndWaitForTopology(ActiveMQConnectionFactory factory, - int topologyMembers, - int timeout) throws Exception - { + int topologyMembers, + int timeout) throws Exception { ActiveMQConnection conn; CountDownLatch countDownLatch = new CountDownLatch(topologyMembers); @@ -276,59 +250,49 @@ public class JMSUtil conn = (ActiveMQConnection) factory.createConnection(); boolean ok = countDownLatch.await(timeout, TimeUnit.SECONDS); - if (!ok) - { + if (!ok) { throw new IllegalStateException("timed out waiting for topology"); } return conn; } - public static void waitForFailoverTopology(final int timeToWait, final ActiveMQServer backupServer, final ActiveMQServer... liveServers) throws Exception - { + public static void waitForFailoverTopology(final int timeToWait, + final ActiveMQServer backupServer, + final ActiveMQServer... liveServers) throws Exception { long start = System.currentTimeMillis(); final int waitMillis = 2000; final int sleepTime = 50; int nWaits = 0; - while ((backupServer.getClusterManager() == null || backupServer.getClusterManager().getClusterConnections().size() != 1) && nWaits++ < waitMillis / sleepTime) - { + while ((backupServer.getClusterManager() == null || backupServer.getClusterManager().getClusterConnections().size() != 1) && nWaits++ < waitMillis / sleepTime) { Thread.sleep(sleepTime); } Set ccs = backupServer.getClusterManager().getClusterConnections(); - if (ccs.size() != 1) - { + if (ccs.size() != 1) { throw new IllegalStateException("You need a single cluster connection on this version of waitForTopology on ServiceTestBase"); } boolean exists = false; - for (ActiveMQServer liveServer : liveServers) - { + for (ActiveMQServer liveServer : liveServers) { ClusterConnectionImpl clusterConnection = (ClusterConnectionImpl) ccs.iterator().next(); Topology topology = clusterConnection.getTopology(); - TransportConfiguration nodeConnector = - liveServer.getClusterManager().getClusterConnections().iterator().next().getConnector(); - do - { + TransportConfiguration nodeConnector = liveServer.getClusterManager().getClusterConnections().iterator().next().getConnector(); + do { Collection members = topology.getMembers(); - for (TopologyMemberImpl member : members) - { - if (member.getConnector().getA() != null && member.getConnector().getA().equals(nodeConnector)) - { + for (TopologyMemberImpl member : members) { + if (member.getConnector().getA() != null && member.getConnector().getA().equals(nodeConnector)) { exists = true; break; } } - if (exists) - { + if (exists) { break; } Thread.sleep(10); - } - while (System.currentTimeMillis() - start < timeToWait); - if (!exists) - { + } while (System.currentTimeMillis() - start < timeToWait); + if (!exists) { String msg = "Timed out waiting for cluster topology of " + backupServer + " (received " + topology.getMembers().size() + @@ -343,18 +307,16 @@ public class JMSUtil } } - public static class JMXListener implements NotificationListener - { + public static class JMXListener implements NotificationListener { + private Notification notif; @Override - public void handleNotification(Notification notification, Object handback) - { + public void handleNotification(Notification notification, Object handback) { notif = notification; } - public Notification getNotification() - { + public Notification getNotification() { return notif; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/NullInitialContext.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/NullInitialContext.java index 6f1207cdf7..4d088695e1 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/NullInitialContext.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/NullInitialContext.java @@ -20,33 +20,27 @@ import javax.naming.InitialContext; import javax.naming.Name; import javax.naming.NamingException; -public class NullInitialContext extends InitialContext -{ +public class NullInitialContext extends InitialContext { @Override - public Object lookup(final Name name) throws NamingException - { + public Object lookup(final Name name) throws NamingException { return null; } @Override - public Object lookup(final String name) throws NamingException - { + public Object lookup(final String name) throws NamingException { return null; } @Override - public void rebind(final Name name, final Object obj) throws NamingException - { + public void rebind(final Name name, final Object obj) throws NamingException { } @Override - public void rebind(final String name, final Object obj) throws NamingException - { + public void rebind(final String name, final Object obj) throws NamingException { } - public NullInitialContext() throws NamingException - { + public NullInitialContext() throws NamingException { super(); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/TopicControlClusterTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/TopicControlClusterTest.java index f81f6ffebe..03c47a1bae 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/TopicControlClusterTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/TopicControlClusterTest.java @@ -25,12 +25,10 @@ import javax.jms.Connection; import javax.jms.Session; import javax.jms.Topic; +public class TopicControlClusterTest extends JMSClusteredTestBase { -public class TopicControlClusterTest extends JMSClusteredTestBase -{ @Test - public void testClusteredSubscriptionCount() throws Exception - { + public void testClusteredSubscriptionCount() throws Exception { Connection conn1 = cf1.createConnection(); conn1.setClientID("someClient1"); @@ -39,8 +37,7 @@ public class TopicControlClusterTest extends JMSClusteredTestBase conn2.setClientID("someClient2"); - try - { + try { Topic topic1 = createTopic("t1"); Topic topic2 = (Topic) context2.lookup("/topic/t1"); @@ -58,8 +55,7 @@ public class TopicControlClusterTest extends JMSClusteredTestBase assertEquals(2, topicControl1.getSubscriptionCount()); assertEquals(1, topicControl2.getSubscriptionCount()); } - finally - { + finally { conn1.close(); conn2.close(); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/TopicControlTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/TopicControlTest.java index 6b4ef3acc4..f46578e54f 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/TopicControlTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/TopicControlTest.java @@ -54,8 +54,7 @@ import java.util.Arrays; import java.util.List; import java.util.Map; -public class TopicControlTest extends ManagementTestBase -{ +public class TopicControlTest extends ManagementTestBase { // Constants ----------------------------------------------------- @@ -80,8 +79,7 @@ public class TopicControlTest extends ManagementTestBase // Public -------------------------------------------------------- @Test - public void testGetAttributes() throws Exception - { + public void testGetAttributes() throws Exception { TopicControl topicControl = createManagementControl(); Assert.assertEquals(topic.getTopicName(), topicControl.getName()); @@ -93,8 +91,7 @@ public class TopicControlTest extends ManagementTestBase } @Test - public void testGetXXXSubscriptionsCount() throws Exception - { + public void testGetXXXSubscriptionsCount() throws Exception { Connection connection_1 = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); // 1 non-durable subscriber, 2 durable subscribers @@ -116,8 +113,7 @@ public class TopicControlTest extends ManagementTestBase } @Test - public void testGetXXXMessagesCount() throws Exception - { + public void testGetXXXMessagesCount() throws Exception { // 1 non-durable subscriber, 2 durable subscribers Connection connection_1 = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); JMSUtil.createConsumer(connection_1, topic); @@ -144,8 +140,7 @@ public class TopicControlTest extends ManagementTestBase } @Test - public void testListXXXSubscriptionsCount() throws Exception - { + public void testListXXXSubscriptionsCount() throws Exception { // 1 non-durable subscriber, 2 durable subscribers Connection connection_1 = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); MessageConsumer cons = JMSUtil.createConsumer(connection_1, topic); @@ -171,8 +166,7 @@ public class TopicControlTest extends ManagementTestBase } @Test - public void testListXXXSubscriptionsAsJSON() throws Exception - { + public void testListXXXSubscriptionsAsJSON() throws Exception { // 1 non-durable subscriber, 2 durable subscribers Connection connection_1 = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); JMSUtil.createConsumer(connection_1, topic); @@ -210,8 +204,7 @@ public class TopicControlTest extends ManagementTestBase } @Test - public void testListSubscriptionsAsJSONWithHierarchicalTopics() throws Exception - { + public void testListSubscriptionsAsJSONWithHierarchicalTopics() throws Exception { serverManager.createTopic(false, "my.jms.#", "jms/all"); serverManager.createTopic(false, "my.jms.A", "jms/A"); ActiveMQTopic myTopic = (ActiveMQTopic) ActiveMQJMSClient.createTopic("my.jms.A"); @@ -225,8 +218,7 @@ public class TopicControlTest extends ManagementTestBase } @Test - public void testCountMessagesForSubscription() throws Exception - { + public void testCountMessagesForSubscription() throws Exception { String key = "key"; long matchingValue = RandomUtil.randomLong(); long unmatchingValue = matchingValue + 1; @@ -240,9 +232,8 @@ public class TopicControlTest extends ManagementTestBase JMSUtil.sendMessageWithProperty(session, topic, key, unmatchingValue); JMSUtil.sendMessageWithProperty(session, topic, key, matchingValue); - for (Binding binding : server.getPostOffice().getBindingsForAddress(topic.getSimpleAddress()).getBindings()) - { - ((LocalQueueBinding)binding).getQueue().flushExecutor(); + for (Binding binding : server.getPostOffice().getBindingsForAddress(topic.getSimpleAddress()).getBindings()) { + ((LocalQueueBinding) binding).getQueue().flushExecutor(); } TopicControl topicControl = createManagementControl(); @@ -258,42 +249,35 @@ public class TopicControlTest extends ManagementTestBase } @Test - public void testCountMessagesForUnknownSubscription() throws Exception - { + public void testCountMessagesForUnknownSubscription() throws Exception { String unknownSubscription = RandomUtil.randomString(); TopicControl topicControl = createManagementControl(); - try - { + try { topicControl.countMessagesForSubscription(clientID, unknownSubscription, null); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { } } @Test - public void testCountMessagesForUnknownClientID() throws Exception - { + public void testCountMessagesForUnknownClientID() throws Exception { String unknownClientID = RandomUtil.randomString(); TopicControl topicControl = createManagementControl(); - try - { + try { topicControl.countMessagesForSubscription(unknownClientID, subscriptionName, null); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { } } @Test - public void testDropDurableSubscriptionWithExistingSubscription() throws Exception - { + public void testDropDurableSubscriptionWithExistingSubscription() throws Exception { Connection connection = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); JMSUtil.createDurableSubscriber(connection, topic, clientID, subscriptionName); @@ -309,8 +293,7 @@ public class TopicControlTest extends ManagementTestBase } @Test - public void testDropDurableSubscriptionWithUnknownSubscription() throws Exception - { + public void testDropDurableSubscriptionWithUnknownSubscription() throws Exception { Connection connection = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); JMSUtil.createDurableSubscriber(connection, topic, clientID, subscriptionName); @@ -318,13 +301,11 @@ public class TopicControlTest extends ManagementTestBase TopicControl topicControl = createManagementControl(); Assert.assertEquals(1, topicControl.getDurableSubscriptionCount()); - try - { + try { topicControl.dropDurableSubscription(clientID, "this subscription does not exist"); Assert.fail("should throw an exception"); } - catch (Exception e) - { + catch (Exception e) { } @@ -334,8 +315,7 @@ public class TopicControlTest extends ManagementTestBase } @Test - public void testDropAllSubscriptions() throws Exception - { + public void testDropAllSubscriptions() throws Exception { Connection connection_1 = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); connection_1.setClientID(clientID); Session sess1 = connection_1.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -378,8 +358,7 @@ public class TopicControlTest extends ManagementTestBase } @Test - public void testRemoveAllMessages() throws Exception - { + public void testRemoveAllMessages() throws Exception { Connection connection_1 = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); JMSUtil.createDurableSubscriber(connection_1, topic, clientID, subscriptionName); Connection connection_2 = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); @@ -399,8 +378,7 @@ public class TopicControlTest extends ManagementTestBase } @Test - public void testListMessagesForSubscription() throws Exception - { + public void testListMessagesForSubscription() throws Exception { Connection connection = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); JMSUtil.createDurableSubscriber(connection, topic, clientID, subscriptionName); @@ -408,16 +386,14 @@ public class TopicControlTest extends ManagementTestBase JMSUtil.sendMessages(topic, 3); TopicControl topicControl = createManagementControl(); - Map[] messages = topicControl.listMessagesForSubscription(ActiveMQDestination.createQueueNameForDurableSubscription(true, clientID, - subscriptionName)); + Map[] messages = topicControl.listMessagesForSubscription(ActiveMQDestination.createQueueNameForDurableSubscription(true, clientID, subscriptionName)); Assert.assertEquals(3, messages.length); connection.close(); } @Test - public void testListMessagesForSubscriptionAsJSON() throws Exception - { + public void testListMessagesForSubscriptionAsJSON() throws Exception { Connection connection = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); JMSUtil.createDurableSubscriber(connection, topic, clientID, subscriptionName); @@ -425,13 +401,11 @@ public class TopicControlTest extends ManagementTestBase String[] ids = JMSUtil.sendMessages(topic, 3); TopicControl topicControl = createManagementControl(); - String jsonString = topicControl.listMessagesForSubscriptionAsJSON(ActiveMQDestination.createQueueNameForDurableSubscription(true, clientID, - subscriptionName)); + String jsonString = topicControl.listMessagesForSubscriptionAsJSON(ActiveMQDestination.createQueueNameForDurableSubscription(true, clientID, subscriptionName)); Assert.assertNotNull(jsonString); JSONArray array = new JSONArray(jsonString); Assert.assertEquals(3, array.length()); - for (int i = 0; i < 3; i++) - { + for (int i = 0; i < 3; i++) { Assert.assertEquals(ids[i], array.getJSONObject(i).get("JMSMessageID")); } @@ -439,44 +413,35 @@ public class TopicControlTest extends ManagementTestBase } @Test - public void testListMessagesForSubscriptionWithUnknownClientID() throws Exception - { + public void testListMessagesForSubscriptionWithUnknownClientID() throws Exception { String unknownClientID = RandomUtil.randomString(); TopicControl topicControl = createManagementControl(); - try - { - topicControl.listMessagesForSubscription(ActiveMQDestination.createQueueNameForDurableSubscription(true, unknownClientID, - subscriptionName)); + try { + topicControl.listMessagesForSubscription(ActiveMQDestination.createQueueNameForDurableSubscription(true, unknownClientID, subscriptionName)); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { } } @Test - public void testListMessagesForSubscriptionWithUnknownSubscription() throws Exception - { + public void testListMessagesForSubscriptionWithUnknownSubscription() throws Exception { String unknownSubscription = RandomUtil.randomString(); TopicControl topicControl = createManagementControl(); - try - { - topicControl.listMessagesForSubscription(ActiveMQDestination.createQueueNameForDurableSubscription(true, clientID, - unknownSubscription)); + try { + topicControl.listMessagesForSubscription(ActiveMQDestination.createQueueNameForDurableSubscription(true, clientID, unknownSubscription)); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { } } @Test - public void testGetMessagesAdded() throws Exception - { + public void testGetMessagesAdded() throws Exception { Connection connection_1 = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); JMSUtil.createConsumer(connection_1, topic); Connection connection_2 = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); @@ -498,8 +463,7 @@ public class TopicControlTest extends ManagementTestBase } @Test - public void testGetMessagesDelivering() throws Exception - { + public void testGetMessagesDelivering() throws Exception { Connection connection_1 = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); MessageConsumer cons_1 = JMSUtil.createConsumer(connection_1, topic, Session.CLIENT_ACKNOWLEDGE); Connection connection_2 = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); @@ -522,8 +486,7 @@ public class TopicControlTest extends ManagementTestBase Message msg_1 = null; Message msg_2 = null; Message msg_3 = null; - for (int i = 0; i < 2; i++) - { + for (int i = 0; i < 2; i++) { msg_1 = cons_1.receive(5000); Assert.assertNotNull(msg_1); msg_2 = cons_2.receive(5000); @@ -549,8 +512,7 @@ public class TopicControlTest extends ManagementTestBase //make sure notifications are always received no matter whether //a Topic is created via JMSServerControl or by JMSServerManager directly. @Test - public void testCreateTopicNotification() throws Exception - { + public void testCreateTopicNotification() throws Exception { JMSUtil.JMXListener listener = new JMSUtil.JMXListener(); this.mbeanServer.addNotificationListener(ObjectNameBuilder.DEFAULT.getJMSServerObjectName(), listener, null, null); @@ -592,12 +554,10 @@ public class TopicControlTest extends ManagementTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - Configuration config = createDefaultInVMConfig() - .setJMXManagementEnabled(true); + Configuration config = createDefaultInVMConfig().setJMXManagementEnabled(true); server = addServer(ActiveMQServers.newActiveMQServer(config, mbeanServer, false)); server.start(); @@ -614,8 +574,7 @@ public class TopicControlTest extends ManagementTestBase topic = (ActiveMQTopic) ActiveMQJMSClient.createTopic(topicName); } - protected TopicControl createManagementControl() throws Exception - { + protected TopicControl createManagementControl() throws Exception { return ManagementControlHelper.createTopicControl(topic, mbeanServer); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/TopicControlUsingJMSTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/TopicControlUsingJMSTest.java index 4f830f35f8..0ec7ac2d4d 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/TopicControlUsingJMSTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/TopicControlUsingJMSTest.java @@ -47,8 +47,7 @@ import javax.jms.TopicSubscriber; import static org.apache.activemq.artemis.tests.util.RandomUtil.randomString; -public class TopicControlUsingJMSTest extends ManagementTestBase -{ +public class TopicControlUsingJMSTest extends ManagementTestBase { // Constants ----------------------------------------------------- @@ -79,20 +78,17 @@ public class TopicControlUsingJMSTest extends ManagementTestBase // Public -------------------------------------------------------- @Test - public void testGetAttributes() throws Exception - { + public void testGetAttributes() throws Exception { Assert.assertEquals(topic.getTopicName(), proxy.retrieveAttributeValue("name")); Assert.assertEquals(topic.getAddress(), proxy.retrieveAttributeValue("address")); Assert.assertEquals(topic.isTemporary(), proxy.retrieveAttributeValue("temporary")); - Object[] bindings = (Object[])proxy.retrieveAttributeValue("" + - "RegistryBindings"); + Object[] bindings = (Object[]) proxy.retrieveAttributeValue("" + "RegistryBindings"); assertEquals(1, bindings.length); Assert.assertEquals(topicBinding, bindings[0]); } @Test - public void testGetXXXSubscriptionsCount() throws Exception - { + public void testGetXXXSubscriptionsCount() throws Exception { Connection connection_1 = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); // 1 non-durable subscriber, 2 durable subscribers @@ -113,8 +109,7 @@ public class TopicControlUsingJMSTest extends ManagementTestBase } @Test - public void testGetXXXMessagesCount() throws Exception - { + public void testGetXXXMessagesCount() throws Exception { // 1 non-durable subscriber, 2 durable subscribers Connection connection_1 = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); JMSUtil.createConsumer(connection_1, topic); @@ -139,8 +134,7 @@ public class TopicControlUsingJMSTest extends ManagementTestBase } @Test - public void testListXXXSubscriptionsCount() throws Exception - { + public void testListXXXSubscriptionsCount() throws Exception { // 1 non-durable subscriber, 2 durable subscribers Connection connection_1 = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); JMSUtil.createConsumer(connection_1, topic); @@ -149,9 +143,9 @@ public class TopicControlUsingJMSTest extends ManagementTestBase Connection connection_3 = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); JMSUtil.createDurableSubscriber(connection_3, topic, clientID + "2", subscriptionName + "2"); - Assert.assertEquals(3, ((Object[])proxy.invokeOperation("listAllSubscriptions")).length); - Assert.assertEquals(1, ((Object[])proxy.invokeOperation("listNonDurableSubscriptions")).length); - Assert.assertEquals(2, ((Object[])proxy.invokeOperation("listDurableSubscriptions")).length); + Assert.assertEquals(3, ((Object[]) proxy.invokeOperation("listAllSubscriptions")).length); + Assert.assertEquals(1, ((Object[]) proxy.invokeOperation("listNonDurableSubscriptions")).length); + Assert.assertEquals(2, ((Object[]) proxy.invokeOperation("listDurableSubscriptions")).length); connection_1.close(); connection_2.close(); @@ -159,8 +153,7 @@ public class TopicControlUsingJMSTest extends ManagementTestBase } @Test - public void testCountMessagesForSubscription() throws Exception - { + public void testCountMessagesForSubscription() throws Exception { String key = "key"; long matchingValue = RandomUtil.randomLong(); long unmatchingValue = matchingValue + 1; @@ -176,49 +169,40 @@ public class TopicControlUsingJMSTest extends ManagementTestBase Assert.assertEquals(3, proxy.retrieveAttributeValue("messageCount")); - Assert.assertEquals(2, - proxy.invokeOperation("countMessagesForSubscription", clientID, subscriptionName, key + " =" + - matchingValue)); - Assert.assertEquals(1, - proxy.invokeOperation("countMessagesForSubscription", clientID, subscriptionName, key + " =" + - unmatchingValue)); + Assert.assertEquals(2, proxy.invokeOperation("countMessagesForSubscription", clientID, subscriptionName, key + " =" + + matchingValue)); + Assert.assertEquals(1, proxy.invokeOperation("countMessagesForSubscription", clientID, subscriptionName, key + " =" + + unmatchingValue)); connection.close(); } @Test - public void testCountMessagesForUnknownSubscription() throws Exception - { + public void testCountMessagesForUnknownSubscription() throws Exception { String unknownSubscription = RandomUtil.randomString(); - try - { + try { proxy.invokeOperation("countMessagesForSubscription", clientID, unknownSubscription, null); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { } } @Test - public void testCountMessagesForUnknownClientID() throws Exception - { + public void testCountMessagesForUnknownClientID() throws Exception { String unknownClientID = RandomUtil.randomString(); - try - { + try { proxy.invokeOperation("countMessagesForSubscription", unknownClientID, subscriptionName, null); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { } } @Test - public void testDropDurableSubscriptionWithExistingSubscription() throws Exception - { + public void testDropDurableSubscriptionWithExistingSubscription() throws Exception { Connection connection = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); JMSUtil.createDurableSubscriber(connection, topic, clientID, subscriptionName); @@ -233,21 +217,18 @@ public class TopicControlUsingJMSTest extends ManagementTestBase } @Test - public void testDropDurableSubscriptionWithUnknownSubscription() throws Exception - { + public void testDropDurableSubscriptionWithUnknownSubscription() throws Exception { Connection connection = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); JMSUtil.createDurableSubscriber(connection, topic, clientID, subscriptionName); Assert.assertEquals(1, proxy.retrieveAttributeValue("durableSubscriptionCount")); - try - { + try { proxy.invokeOperation("dropDurableSubscription", clientID, "this subscription does not exist"); Assert.fail("should throw an exception"); } - catch (Exception e) - { + catch (Exception e) { } @@ -257,18 +238,11 @@ public class TopicControlUsingJMSTest extends ManagementTestBase } @Test - public void testDropAllSubscriptions() throws Exception - { + public void testDropAllSubscriptions() throws Exception { Connection connection_1 = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); - TopicSubscriber durableSubscriber_1 = JMSUtil.createDurableSubscriber(connection_1, - topic, - clientID, - subscriptionName); + TopicSubscriber durableSubscriber_1 = JMSUtil.createDurableSubscriber(connection_1, topic, clientID, subscriptionName); Connection connection_2 = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); - TopicSubscriber durableSubscriber_2 = JMSUtil.createDurableSubscriber(connection_2, - topic, - clientID + "2", - subscriptionName + "2"); + TopicSubscriber durableSubscriber_2 = JMSUtil.createDurableSubscriber(connection_2, topic, clientID + "2", subscriptionName + "2"); Assert.assertEquals(2, proxy.retrieveAttributeValue("subscriptionCount")); @@ -285,8 +259,7 @@ public class TopicControlUsingJMSTest extends ManagementTestBase } @Test - public void testRemoveAllMessages() throws Exception - { + public void testRemoveAllMessages() throws Exception { Connection connection_1 = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); JMSUtil.createDurableSubscriber(connection_1, topic, clientID, subscriptionName); Connection connection_2 = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); @@ -296,7 +269,7 @@ public class TopicControlUsingJMSTest extends ManagementTestBase Assert.assertEquals(3 * 2, proxy.retrieveAttributeValue("messageCount")); - int removedCount = (Integer)proxy.invokeOperation("removeMessages", ""); + int removedCount = (Integer) proxy.invokeOperation("removeMessages", ""); Assert.assertEquals(3 * 2, removedCount); Assert.assertEquals(0, proxy.retrieveAttributeValue("messageCount")); @@ -305,58 +278,45 @@ public class TopicControlUsingJMSTest extends ManagementTestBase } @Test - public void testListMessagesForSubscription() throws Exception - { + public void testListMessagesForSubscription() throws Exception { Connection connection = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); JMSUtil.createDurableSubscriber(connection, topic, clientID, subscriptionName); JMSUtil.sendMessages(topic, 3); - Object[] data = (Object[])proxy.invokeOperation("listMessagesForSubscription", - ActiveMQDestination.createQueueNameForDurableSubscription(true, clientID, - subscriptionName)); + Object[] data = (Object[]) proxy.invokeOperation("listMessagesForSubscription", ActiveMQDestination.createQueueNameForDurableSubscription(true, clientID, subscriptionName)); Assert.assertEquals(3, data.length); connection.close(); } @Test - public void testListMessagesForSubscriptionWithUnknownClientID() throws Exception - { + public void testListMessagesForSubscriptionWithUnknownClientID() throws Exception { String unknownClientID = RandomUtil.randomString(); - try - { - proxy.invokeOperation("listMessagesForSubscription", - ActiveMQDestination.createQueueNameForDurableSubscription(true, unknownClientID, - subscriptionName)); + try { + proxy.invokeOperation("listMessagesForSubscription", ActiveMQDestination.createQueueNameForDurableSubscription(true, unknownClientID, subscriptionName)); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { } } @Test - public void testListMessagesForSubscriptionWithUnknownSubscription() throws Exception - { + public void testListMessagesForSubscriptionWithUnknownSubscription() throws Exception { String unknownSubscription = RandomUtil.randomString(); - try - { - proxy.invokeOperation("listMessagesForSubscription", - ActiveMQDestination.createQueueNameForDurableSubscription(true, clientID, unknownSubscription)); + try { + proxy.invokeOperation("listMessagesForSubscription", ActiveMQDestination.createQueueNameForDurableSubscription(true, clientID, unknownSubscription)); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { } } @Test - public void testGetMessagesAdded() throws Exception - { + public void testGetMessagesAdded() throws Exception { Connection connection_1 = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); JMSUtil.createConsumer(connection_1, topic); Connection connection_2 = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); @@ -376,22 +336,13 @@ public class TopicControlUsingJMSTest extends ManagementTestBase } @Test - public void testGetMessagesDelivering() throws Exception - { + public void testGetMessagesDelivering() throws Exception { Connection connection_1 = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); MessageConsumer cons_1 = JMSUtil.createConsumer(connection_1, topic, Session.CLIENT_ACKNOWLEDGE); Connection connection_2 = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); - MessageConsumer cons_2 = JMSUtil.createDurableSubscriber(connection_2, - topic, - clientID, - subscriptionName, - Session.CLIENT_ACKNOWLEDGE); + MessageConsumer cons_2 = JMSUtil.createDurableSubscriber(connection_2, topic, clientID, subscriptionName, Session.CLIENT_ACKNOWLEDGE); Connection connection_3 = JMSUtil.createConnection(InVMConnectorFactory.class.getName()); - MessageConsumer cons_3 = JMSUtil.createDurableSubscriber(connection_3, - topic, - clientID + "2", - subscriptionName + "2", - Session.CLIENT_ACKNOWLEDGE); + MessageConsumer cons_3 = JMSUtil.createDurableSubscriber(connection_3, topic, clientID + "2", subscriptionName + "2", Session.CLIENT_ACKNOWLEDGE); assertEquals(0, proxy.retrieveAttributeValue("deliveringCount")); @@ -406,8 +357,7 @@ public class TopicControlUsingJMSTest extends ManagementTestBase Message msg_1 = null; Message msg_2 = null; Message msg_3 = null; - for (int i = 0; i < 2; i++) - { + for (int i = 0; i < 2; i++) { msg_1 = cons_1.receive(5000); assertNotNull(msg_1); msg_2 = cons_2.receive(5000); @@ -436,12 +386,10 @@ public class TopicControlUsingJMSTest extends ManagementTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - Configuration config = createDefaultInVMConfig() - .setJMXManagementEnabled(true); + Configuration config = createDefaultInVMConfig().setJMXManagementEnabled(true); server = addServer(ActiveMQServers.newActiveMQServer(config, mbeanServer, false)); server.start(); @@ -457,9 +405,7 @@ public class TopicControlUsingJMSTest extends ManagementTestBase serverManager.createTopic(false, topicName, topicBinding); topic = (ActiveMQTopic) ActiveMQJMSClient.createTopic(topicName); - ActiveMQConnectionFactory cf = - ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, - new TransportConfiguration(INVM_CONNECTOR_FACTORY)); + ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); connection = cf.createQueueConnection(); session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); connection.start(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/AIOImportExportTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/AIOImportExportTest.java index e49e50b6b6..616be766d0 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/AIOImportExportTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/AIOImportExportTest.java @@ -20,17 +20,15 @@ import org.apache.activemq.artemis.core.io.SequentialFileFactory; import org.apache.activemq.artemis.core.io.aio.AIOSequentialFileFactory; import org.junit.BeforeClass; -public class AIOImportExportTest extends NIOImportExportTest -{ +public class AIOImportExportTest extends NIOImportExportTest { + @BeforeClass - public static void hasAIO() - { + public static void hasAIO() { org.junit.Assume.assumeTrue("Test case needs AIO to run", AIOSequentialFileFactory.isSupported()); } @Override - protected SequentialFileFactory getFileFactory() throws Exception - { + protected SequentialFileFactory getFileFactory() throws Exception { return new AIOSequentialFileFactory(getTestDirfile(), 10); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/AIOJournalCompactTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/AIOJournalCompactTest.java index f1ce78534a..9ca2ae3281 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/AIOJournalCompactTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/AIOJournalCompactTest.java @@ -24,26 +24,21 @@ import org.apache.activemq.artemis.core.io.aio.AIOSequentialFileFactory; import org.apache.activemq.artemis.core.journal.impl.JournalConstants; import org.junit.BeforeClass; -public class AIOJournalCompactTest extends NIOJournalCompactTest -{ +public class AIOJournalCompactTest extends NIOJournalCompactTest { + @BeforeClass - public static void hasAIO() - { + public static void hasAIO() { org.junit.Assume.assumeTrue("Test case needs AIO to run", AIOSequentialFileFactory.isSupported()); } @Override - protected SequentialFileFactory getFileFactory() throws Exception - { + protected SequentialFileFactory getFileFactory() throws Exception { File file = new File(getTestDir()); ActiveMQTestBase.deleteDirectory(file); file.mkdir(); - return new AIOSequentialFileFactory(getTestDirfile(), - JournalConstants.DEFAULT_JOURNAL_BUFFER_SIZE_AIO, - 100000, 10, - false); + return new AIOSequentialFileFactory(getTestDirfile(), JournalConstants.DEFAULT_JOURNAL_BUFFER_SIZE_AIO, 100000, 10, false); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/AIOJournalImplTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/AIOJournalImplTest.java index 59f6b95887..7c36cfeb77 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/AIOJournalImplTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/AIOJournalImplTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.journal; + import java.io.File; import org.apache.activemq.artemis.core.io.SequentialFileFactory; @@ -27,53 +28,42 @@ import org.junit.Before; import org.junit.BeforeClass; /** - * * A RealJournalImplTest * you need to define -Djava.library.path=${project-root}/native/src/.libs when calling the JVM * If you are running this test in eclipse you should do: - * I - Run->Open Run Dialog - * II - Find the class on the list (you will find it if you already tried running this testcase before) - * III - Add -Djava.library.path=/native/src/.libs + * I - Run->Open Run Dialog + * II - Find the class on the list (you will find it if you already tried running this testcase before) + * III - Add -Djava.library.path=/native/src/.libs */ -public class AIOJournalImplTest extends JournalImplTestUnit -{ +public class AIOJournalImplTest extends JournalImplTestUnit { + @BeforeClass - public static void hasAIO() - { + public static void hasAIO() { org.junit.Assume.assumeTrue("Test case needs AIO to run", AIOSequentialFileFactory.isSupported()); } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - if (!LibaioContext.isLoaded()) - { - Assert.fail(String.format("libAIO is not loaded on %s %s %s", - System.getProperty("os.name"), - System.getProperty("os.arch"), - System.getProperty("os.version"))); + if (!LibaioContext.isLoaded()) { + Assert.fail(String.format("libAIO is not loaded on %s %s %s", System.getProperty("os.name"), System.getProperty("os.arch"), System.getProperty("os.version"))); } } @Override - protected SequentialFileFactory getFileFactory() throws Exception - { + protected SequentialFileFactory getFileFactory() throws Exception { File file = new File(getTestDir()); deleteDirectory(file); file.mkdir(); - return new AIOSequentialFileFactory(getTestDirfile(), - JournalConstants.DEFAULT_JOURNAL_BUFFER_SIZE_AIO, 1000000, 10, - false); + return new AIOSequentialFileFactory(getTestDirfile(), JournalConstants.DEFAULT_JOURNAL_BUFFER_SIZE_AIO, 1000000, 10, false); } @Override - protected int getAlignment() - { + protected int getAlignment() { return 512; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/AIOSequentialFileFactoryTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/AIOSequentialFileFactoryTest.java index acc65b1c72..87d1aeffcf 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/AIOSequentialFileFactoryTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/AIOSequentialFileFactoryTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.journal; + import java.io.File; import java.nio.ByteBuffer; @@ -26,24 +27,20 @@ import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -public class AIOSequentialFileFactoryTest extends SequentialFileFactoryTestBase -{ +public class AIOSequentialFileFactoryTest extends SequentialFileFactoryTestBase { @BeforeClass - public static void hasAIO() - { + public static void hasAIO() { org.junit.Assume.assumeTrue("Test case needs AIO to run", AIOSequentialFileFactory.isSupported()); } @Override - protected SequentialFileFactory createFactory(String folder) - { + protected SequentialFileFactory createFactory(String folder) { return new AIOSequentialFileFactory(new File(folder), 10); } @Test - public void testBuffer() throws Exception - { + public void testBuffer() throws Exception { SequentialFile file = factory.createSequentialFile("filtetmp.log"); file.open(); ByteBuffer buff = factory.newBuffer(10); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIOBufferedJournalCompactTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIOBufferedJournalCompactTest.java index c4b1accf3b..c467ddb836 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIOBufferedJournalCompactTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIOBufferedJournalCompactTest.java @@ -22,12 +22,10 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.core.io.SequentialFileFactory; import org.apache.activemq.artemis.core.io.nio.NIOSequentialFileFactory; -public class NIOBufferedJournalCompactTest extends NIOJournalCompactTest -{ +public class NIOBufferedJournalCompactTest extends NIOJournalCompactTest { @Override - protected SequentialFileFactory getFileFactory() throws Exception - { + protected SequentialFileFactory getFileFactory() throws Exception { File file = new File(getTestDir()); ActiveMQTestBase.deleteDirectory(file); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIOImportExportTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIOImportExportTest.java index e50143aac7..471de8138c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIOImportExportTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIOImportExportTest.java @@ -23,15 +23,13 @@ import org.apache.activemq.artemis.tests.unit.core.journal.impl.JournalImplTestB import org.apache.activemq.artemis.tests.unit.core.journal.impl.fakes.SimpleEncoding; import org.junit.Test; -public class NIOImportExportTest extends JournalImplTestBase -{ +public class NIOImportExportTest extends JournalImplTestBase { /* (non-Javadoc) * @see JournalImplTestBase#getFileFactory() */ @Override - protected SequentialFileFactory getFileFactory() throws Exception - { + protected SequentialFileFactory getFileFactory() throws Exception { return new NIOSequentialFileFactory(getTestDirfile(), true, 1); } @@ -46,8 +44,7 @@ public class NIOImportExportTest extends JournalImplTestBase // Public -------------------------------------------------------- @Test - public void testExportImport() throws Exception - { + public void testExportImport() throws Exception { setup(10, 10 * 1024, true); createJournal(); @@ -101,8 +98,7 @@ public class NIOImportExportTest extends JournalImplTestBase } @Test - public void testExportImport3() throws Exception - { + public void testExportImport3() throws Exception { setup(10, 10 * 1024, true); createJournal(); @@ -137,7 +133,7 @@ public class NIOImportExportTest extends JournalImplTestBase addTx(11, 12, 13); - EncodingSupport xid = new SimpleEncoding(10, (byte)0); + EncodingSupport xid = new SimpleEncoding(10, (byte) 0); prepare(11, xid); stopJournal(); @@ -165,8 +161,7 @@ public class NIOImportExportTest extends JournalImplTestBase } @Test - public void testExportImport2() throws Exception - { + public void testExportImport2() throws Exception { setup(10, 10 * 1024, true); createJournal(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIOJournalCompactTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIOJournalCompactTest.java index c3148bb86d..2bac6de5b0 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIOJournalCompactTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIOJournalCompactTest.java @@ -56,8 +56,8 @@ import org.junit.After; import org.junit.Assert; import org.junit.Test; -public class NIOJournalCompactTest extends JournalImplTestBase -{ +public class NIOJournalCompactTest extends JournalImplTestBase { + private static final int NUMBER_OF_RECORDS = 1000; IDGenerator idGenerator = new SimpleIDGenerator(100000); @@ -66,20 +66,17 @@ public class NIOJournalCompactTest extends JournalImplTestBase // ============= @Test - public void testControlFile() throws Exception - { + public void testControlFile() throws Exception { ArrayList dataFiles = new ArrayList(); - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { SequentialFile file = fileFactory.createSequentialFile("file-" + i + ".tst"); dataFiles.add(new JournalFileImpl(file, 0, JournalImpl.FORMAT_VERSION)); } ArrayList newFiles = new ArrayList(); - for (int i = 0; i < 3; i++) - { + for (int i = 0; i < 3; i++) { SequentialFile file = fileFactory.createSequentialFile("file-" + i + ".tst.new"); newFiles.add(new JournalFileImpl(file, 0, JournalImpl.FORMAT_VERSION)); } @@ -103,22 +100,19 @@ public class NIOJournalCompactTest extends JournalImplTestBase Assert.assertEquals(renames.size(), renamesRead.size()); Iterator iterDataFiles = strDataFiles.iterator(); - for (JournalFile file : dataFiles) - { + for (JournalFile file : dataFiles) { Assert.assertEquals(file.getFile().getFileName(), iterDataFiles.next()); } Assert.assertFalse(iterDataFiles.hasNext()); Iterator iterNewFiles = strNewFiles.iterator(); - for (JournalFile file : newFiles) - { + for (JournalFile file : newFiles) { Assert.assertEquals(file.getFile().getFileName(), iterNewFiles.next()); } Assert.assertFalse(iterNewFiles.hasNext()); Iterator> iterRename = renames.iterator(); - for (Pair rename : renamesRead) - { + for (Pair rename : renamesRead) { Pair original = iterRename.next(); Assert.assertEquals(original.getA(), rename.getA()); Assert.assertEquals(original.getB(), rename.getB()); @@ -127,70 +121,61 @@ public class NIOJournalCompactTest extends JournalImplTestBase } -// public void testRepeat() throws Exception -// { -// int i = 0 ; -// -// while (true) -// { -// System.out.println("#test (" + (i++) + ")"); -// testCrashRenamingFiles(); -// tearDown(); -// setUp(); -// } -// } + // public void testRepeat() throws Exception + // { + // int i = 0 ; + // + // while (true) + // { + // System.out.println("#test (" + (i++) + ")"); + // testCrashRenamingFiles(); + // tearDown(); + // setUp(); + // } + // } @Test - public void testCrashRenamingFiles() throws Exception - { + public void testCrashRenamingFiles() throws Exception { internalCompactTest(false, false, true, false, false, false, false, false, false, false, true, false, false); } @Test - public void testCrashDuringCompacting() throws Exception - { + public void testCrashDuringCompacting() throws Exception { internalCompactTest(false, false, true, false, false, false, false, false, false, false, false, false, false); } @Test - public void testCompactwithPendingXACommit() throws Exception - { + public void testCompactwithPendingXACommit() throws Exception { internalCompactTest(true, false, false, false, false, false, false, true, false, false, true, true, true); } @Test - public void testCompactwithPendingXAPrepareAndCommit() throws Exception - { + public void testCompactwithPendingXAPrepareAndCommit() throws Exception { internalCompactTest(false, true, false, false, false, false, false, true, false, false, true, true, true); } @Test - public void testCompactwithPendingXAPrepareAndDelayedCommit() throws Exception - { + public void testCompactwithPendingXAPrepareAndDelayedCommit() throws Exception { internalCompactTest(false, true, false, false, false, false, false, true, false, true, true, true, true); } @Test - public void testCompactwithPendingCommit() throws Exception - { + public void testCompactwithPendingCommit() throws Exception { internalCompactTest(true, false, false, false, false, false, false, true, false, false, true, true, true); } @Test - public void testCompactwithDelayedCommit() throws Exception - { + public void testCompactwithDelayedCommit() throws Exception { internalCompactTest(false, true, false, false, false, false, false, true, false, true, true, true, true); } @Test - public void testCompactwithPendingCommitFollowedByDelete() throws Exception - { + public void testCompactwithPendingCommitFollowedByDelete() throws Exception { internalCompactTest(false, false, false, false, false, false, false, true, true, false, true, true, true); } @Test - public void testCompactwithConcurrentUpdateAndDeletes() throws Exception - { + public void testCompactwithConcurrentUpdateAndDeletes() throws Exception { internalCompactTest(false, false, true, false, true, true, false, false, false, false, true, true, true); tearDown(); setUp(); @@ -198,8 +183,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase } @Test - public void testCompactwithConcurrentDeletes() throws Exception - { + public void testCompactwithConcurrentDeletes() throws Exception { internalCompactTest(false, false, true, false, false, true, false, false, false, false, true, true, true); tearDown(); setUp(); @@ -207,20 +191,17 @@ public class NIOJournalCompactTest extends JournalImplTestBase } @Test - public void testCompactwithConcurrentUpdates() throws Exception - { + public void testCompactwithConcurrentUpdates() throws Exception { internalCompactTest(false, false, true, false, true, false, false, false, false, false, true, true, true); } @Test - public void testCompactWithConcurrentAppend() throws Exception - { + public void testCompactWithConcurrentAppend() throws Exception { internalCompactTest(false, false, true, true, false, false, false, false, false, false, true, true, true); } @Test - public void testCompactFirstFileReclaimed() throws Exception - { + public void testCompactFirstFileReclaimed() throws Exception { setup(2, 60 * 1024, false); @@ -242,8 +223,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase journal.appendAddRecord(2, recordType, "finalRecord".getBytes(), true); - for (int i = 10; i < 100; i++) - { + for (int i = 10; i < 100; i++) { journal.appendAddRecord(i, recordType, ("tst" + i).getBytes(), true); journal.forceMoveNextFile(); journal.appendUpdateRecord(i, recordType, ("uptst" + i).getBytes(), true); @@ -267,8 +247,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase } @Test - public void testCompactPrepareRestart() throws Exception - { + public void testCompactPrepareRestart() throws Exception { setup(2, 60 * 1024, false); createJournal(); @@ -311,8 +290,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase } @Test - public void testCompactPrepareRestart2() throws Exception - { + public void testCompactPrepareRestart2() throws Exception { setup(2, 60 * 1024, false); createJournal(); @@ -351,8 +329,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase } @Test - public void testCompactPrepareRestart3() throws Exception - { + public void testCompactPrepareRestart3() throws Exception { setup(2, 60 * 1024, false); createJournal(); @@ -383,8 +360,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase } @Test - public void testOnRollback() throws Exception - { + public void testOnRollback() throws Exception { setup(2, 60 * 1024, false); @@ -415,8 +391,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase } @Test - public void testCompactSecondFileReclaimed() throws Exception - { + public void testCompactSecondFileReclaimed() throws Exception { setup(2, 60 * 1024, false); @@ -451,8 +426,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase } @Test - public void testIncompleteTXDuringcompact() throws Exception - { + public void testIncompleteTXDuringcompact() throws Exception { setup(2, 60 * 1024, false); @@ -482,8 +456,10 @@ public class NIOJournalCompactTest extends JournalImplTestBase } - private void internalCompactTest(final boolean preXA, // prepare before compact - final boolean postXA, // prepare after compact + private void internalCompactTest(final boolean preXA, + // prepare before compact + final boolean postXA, + // prepare after compact final boolean regularAdd, final boolean performAppend, final boolean performUpdate, @@ -494,14 +470,11 @@ public class NIOJournalCompactTest extends JournalImplTestBase final boolean delayCommit, final boolean createControlFile, final boolean deleteControlFile, - final boolean renameFilesAfterCompacting) throws Exception - { - if (performNonTransactionalDelete) - { + final boolean renameFilesAfterCompacting) throws Exception { + if (performNonTransactionalDelete) { performDelete = false; } - if (performDelete) - { + if (performDelete) { performNonTransactionalDelete = false; } @@ -513,53 +486,43 @@ public class NIOJournalCompactTest extends JournalImplTestBase final CountDownLatch latchDone = new CountDownLatch(1); final CountDownLatch latchWait = new CountDownLatch(1); - journal = new JournalImpl(fileSize, minFiles, 0, 0, fileFactory, filePrefix, fileExtension, maxAIO) - { + journal = new JournalImpl(fileSize, minFiles, 0, 0, fileFactory, filePrefix, fileExtension, maxAIO) { @Override protected SequentialFile createControlFile(final List files, final List newFiles, - final Pair pair) throws Exception - { - if (createControlFile) - { + final Pair pair) throws Exception { + if (createControlFile) { return super.createControlFile(files, newFiles, pair); } - else - { + else { throw new IllegalStateException("Simulating a crash during compact creation"); } } @Override - protected void deleteControlFile(final SequentialFile controlFile) throws Exception - { - if (deleteControlFile) - { + protected void deleteControlFile(final SequentialFile controlFile) throws Exception { + if (deleteControlFile) { super.deleteControlFile(controlFile); } } @Override - protected void renameFiles(final List oldFiles, final List newFiles) throws Exception - { - if (renameFilesAfterCompacting) - { + protected void renameFiles(final List oldFiles, + final List newFiles) throws Exception { + if (renameFilesAfterCompacting) { super.renameFiles(oldFiles, newFiles); } } @Override - public void onCompactDone() - { + public void onCompactDone() { latchDone.countDown(); System.out.println("Waiting on Compact"); - try - { + try { ActiveMQTestBase.waitForLatch(latchWait); } - catch (InterruptedException e) - { + catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Done"); @@ -573,26 +536,21 @@ public class NIOJournalCompactTest extends JournalImplTestBase long transactionID = 0; - if (regularAdd) - { + if (regularAdd) { - for (int i = 0; i < NIOJournalCompactTest.NUMBER_OF_RECORDS / 2; i++) - { + for (int i = 0; i < NIOJournalCompactTest.NUMBER_OF_RECORDS / 2; i++) { add(i); - if (i % 10 == 0 && i > 0) - { + if (i % 10 == 0 && i > 0) { journal.forceMoveNextFile(); } update(i); } - for (int i = NIOJournalCompactTest.NUMBER_OF_RECORDS / 2; i < NIOJournalCompactTest.NUMBER_OF_RECORDS; i++) - { + for (int i = NIOJournalCompactTest.NUMBER_OF_RECORDS / 2; i < NIOJournalCompactTest.NUMBER_OF_RECORDS; i++) { addTx(transactionID, i); updateTx(transactionID, i); - if (i % 10 == 0) - { + if (i % 10 == 0) { journal.forceMoveNextFile(); } commit(transactionID++); @@ -600,31 +558,24 @@ public class NIOJournalCompactTest extends JournalImplTestBase } } - if (pendingTransactions) - { - for (long i = 0; i < 100; i++) - { + if (pendingTransactions) { + for (long i = 0; i < 100; i++) { long recordID = idGenerator.generateID(); addTx(transactionID, recordID); updateTx(transactionID, recordID); - if (preXA) - { + if (preXA) { prepare(transactionID, new SimpleEncoding(10, (byte) 0)); } transactedRecords.add(new Pair(transactionID++, recordID)); } } - if (regularAdd) - { - for (int i = 0; i < NIOJournalCompactTest.NUMBER_OF_RECORDS; i++) - { - if (!(i % 10 == 0)) - { + if (regularAdd) { + for (int i = 0; i < NIOJournalCompactTest.NUMBER_OF_RECORDS; i++) { + if (!(i % 10 == 0)) { delete(i); } - else - { + else { liveIDs.add((long) i); } } @@ -632,17 +583,13 @@ public class NIOJournalCompactTest extends JournalImplTestBase journal.forceMoveNextFile(); - Thread t = new Thread() - { + Thread t = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { journal.testCompact(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -654,41 +601,32 @@ public class NIOJournalCompactTest extends JournalImplTestBase int nextID = NIOJournalCompactTest.NUMBER_OF_RECORDS; - if (performAppend) - { - for (int i = 0; i < 50; i++) - { + if (performAppend) { + for (int i = 0; i < 50; i++) { add(nextID++); - if (i % 10 == 0) - { + if (i % 10 == 0) { journal.forceMoveNextFile(); } } - for (int i = 0; i < 50; i++) - { + for (int i = 0; i < 50; i++) { // A Total new transaction (that was created after the compact started) to add new record while compacting // is still working addTx(transactionID, nextID++); commit(transactionID++); - if (i % 10 == 0) - { + if (i % 10 == 0) { journal.forceMoveNextFile(); } } } - if (performUpdate) - { + if (performUpdate) { int count = 0; - for (Long liveID : liveIDs) - { - if (count++ % 2 == 0) - { + for (Long liveID : liveIDs) { + if (count++ % 2 == 0) { update(liveID); } - else - { + else { // A Total new transaction (that was created after the compact started) to update a record that is being // compacted updateTx(transactionID, liveID); @@ -697,18 +635,14 @@ public class NIOJournalCompactTest extends JournalImplTestBase } } - if (performDelete) - { + if (performDelete) { int count = 0; - for (long liveID : liveIDs) - { - if (count++ % 2 == 0) - { + for (long liveID : liveIDs) { + if (count++ % 2 == 0) { System.out.println("Deleting no trans " + liveID); delete(liveID); } - else - { + else { System.out.println("Deleting TX " + liveID); // A Total new transaction (that was created after the compact started) to delete a record that is being // compacted @@ -720,47 +654,37 @@ public class NIOJournalCompactTest extends JournalImplTestBase } } - if (performNonTransactionalDelete) - { - for (long liveID : liveIDs) - { + if (performNonTransactionalDelete) { + for (long liveID : liveIDs) { delete(liveID); } } - if (pendingTransactions && !delayCommit) - { - for (Pair tx : transactedRecords) - { - if (postXA) - { + if (pendingTransactions && !delayCommit) { + for (Pair tx : transactedRecords) { + if (postXA) { prepare(tx.getA(), new SimpleEncoding(10, (byte) 0)); } - if (tx.getA() % 2 == 0) - { + if (tx.getA() % 2 == 0) { commit(tx.getA()); - if (deleteTransactRecords) - { + if (deleteTransactRecords) { delete(tx.getB()); } } - else - { + else { rollback(tx.getA()); } } } /** Some independent adds and updates */ - for (int i = 0; i < 1000; i++) - { + for (int i = 0; i < 1000; i++) { long id = idGenerator.generateID(); add(id); delete(id); - if (i % 100 == 0) - { + if (i % 100 == 0) { journal.forceMoveNextFile(); } } @@ -770,25 +694,19 @@ public class NIOJournalCompactTest extends JournalImplTestBase t.join(); - if (pendingTransactions && delayCommit) - { - for (Pair tx : transactedRecords) - { - if (postXA) - { + if (pendingTransactions && delayCommit) { + for (Pair tx : transactedRecords) { + if (postXA) { prepare(tx.getA(), new SimpleEncoding(10, (byte) 0)); } - if (tx.getA() % 2 == 0) - { + if (tx.getA() % 2 == 0) { commit(tx.getA()); - if (deleteTransactRecords) - { + if (deleteTransactRecords) { delete(tx.getB()); } } - else - { + else { rollback(tx.getA()); } } @@ -798,8 +716,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase add(lastId); - if (createControlFile && deleteControlFile && renameFilesAfterCompacting) - { + if (createControlFile && deleteControlFile && renameFilesAfterCompacting) { journal.testCompact(); } @@ -816,12 +733,10 @@ public class NIOJournalCompactTest extends JournalImplTestBase startJournal(); loadAndCheck(); - } @Test - public void testCompactAddAndUpdateFollowedByADelete() throws Exception - { + public void testCompactAddAndUpdateFollowedByADelete() throws Exception { setup(2, 60 * 1024, false); @@ -875,8 +790,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase } @Test - public void testCompactAddAndUpdateFollowedByADelete2() throws Exception - { + public void testCompactAddAndUpdateFollowedByADelete2() throws Exception { setup(2, 60 * 1024, false); @@ -926,8 +840,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase } @Test - public void testCompactAddAndUpdateFollowedByADelete3() throws Exception - { + public void testCompactAddAndUpdateFollowedByADelete3() throws Exception { setup(2, 60 * 1024, false); @@ -968,8 +881,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase } @Test - public void testCompactAddAndUpdateFollowedByADelete4() throws Exception - { + public void testCompactAddAndUpdateFollowedByADelete4() throws Exception { setup(2, 60 * 1024, false); @@ -1022,8 +934,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase } @Test - public void testCompactAddAndUpdateFollowedByADelete6() throws Exception - { + public void testCompactAddAndUpdateFollowedByADelete6() throws Exception { setup(2, 60 * 1024, false); @@ -1080,8 +991,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase } @Test - public void testDeleteWhileCleanup() throws Exception - { + public void testDeleteWhileCleanup() throws Exception { setup(2, 60 * 1024, false); @@ -1090,31 +1000,27 @@ public class NIOJournalCompactTest extends JournalImplTestBase startJournal(); load(); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { add(i); } journal.forceMoveNextFile(); - for (int i = 10; i < 90; i++) - { + for (int i = 10; i < 90; i++) { delete(i); } startCompact(); // Delete part of the live records while cleanup still working - for (int i = 1; i < 5; i++) - { + for (int i = 1; i < 5; i++) { delete(i); } finishCompact(); // Delete part of the live records after cleanup is done - for (int i = 5; i < 10; i++) - { + for (int i = 5; i < 10; i++) { delete(i); } @@ -1130,8 +1036,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase } @Test - public void testCompactAddAndUpdateFollowedByADelete5() throws Exception - { + public void testCompactAddAndUpdateFollowedByADelete5() throws Exception { setup(2, 60 * 1024, false); @@ -1174,8 +1079,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase } @Test - public void testSimpleCompacting() throws Exception - { + public void testSimpleCompacting() throws Exception { setup(2, 60 * 1024, false); createJournal(); @@ -1187,19 +1091,16 @@ public class NIOJournalCompactTest extends JournalImplTestBase // add and remove some data to force reclaiming { ArrayList ids = new ArrayList(); - for (int i = 0; i < NUMBER_OF_RECORDS; i++) - { + for (int i = 0; i < NUMBER_OF_RECORDS; i++) { long id = idGenerator.generateID(); ids.add(id); add(id); - if (i > 0 && i % 100 == 0) - { + if (i > 0 && i % 100 == 0) { journal.forceMoveNextFile(); } } - for (Long id : ids) - { + for (Long id : ids) { delete(id); } @@ -1210,33 +1111,27 @@ public class NIOJournalCompactTest extends JournalImplTestBase long transactionID = 0; - for (int i = 0; i < NUMBER_OF_RECORDS / 2; i++) - { + for (int i = 0; i < NUMBER_OF_RECORDS / 2; i++) { add(i); - if (i % 10 == 0 && i > 0) - { + if (i % 10 == 0 && i > 0) { journal.forceMoveNextFile(); } update(i); } - for (int i = NUMBER_OF_RECORDS / 2; i < NUMBER_OF_RECORDS; i++) - { + for (int i = NUMBER_OF_RECORDS / 2; i < NUMBER_OF_RECORDS; i++) { addTx(transactionID, i); updateTx(transactionID, i); - if (i % 10 == 0) - { + if (i % 10 == 0) { journal.forceMoveNextFile(); } commit(transactionID++); update(i); } - for (int i = 0; i < NUMBER_OF_RECORDS; i++) - { - if (!(i % 10 == 0)) - { + for (int i = 0; i < NUMBER_OF_RECORDS; i++) { + if (!(i % 10 == 0)) { delete(i); } } @@ -1263,8 +1158,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase } @Test - public void testLiveSize() throws Exception - { + public void testLiveSize() throws Exception { setup(2, 60 * 1024, true); createJournal(); @@ -1275,8 +1169,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase ArrayList expectedSizes = new ArrayList(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { long id = idGenerator.generateID(); listToDelete.add(id); @@ -1303,14 +1196,12 @@ public class NIOJournalCompactTest extends JournalImplTestBase Assert.assertEquals(files.length, files2.length); - for (int i = 0; i < files.length; i++) - { + for (int i = 0; i < files.length; i++) { Assert.assertEquals(expectedSizes.get(i).intValue(), files[i].getLiveSize()); Assert.assertEquals(expectedSizes.get(i).intValue(), files2[i].getLiveSize()); } - for (long id : listToDelete) - { + for (long id : listToDelete) { delete(id); } @@ -1318,8 +1209,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase JournalFile[] files3 = journal.getDataFiles(); - for (JournalFile file : files3) - { + for (JournalFile file : files3) { Assert.assertEquals(0, file.getLiveSize()); } @@ -1330,16 +1220,14 @@ public class NIOJournalCompactTest extends JournalImplTestBase files3 = journal.getDataFiles(); - for (JournalFile file : files3) - { + for (JournalFile file : files3) { Assert.assertEquals(0, file.getLiveSize()); } } @Test - public void testCompactFirstFileWithPendingCommits() throws Exception - { + public void testCompactFirstFileWithPendingCommits() throws Exception { setup(2, 60 * 1024, true); createJournal(); @@ -1347,18 +1235,15 @@ public class NIOJournalCompactTest extends JournalImplTestBase loadAndCheck(); long tx = idGenerator.generateID(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { addTx(tx, idGenerator.generateID()); } journal.forceMoveNextFile(); ArrayList listToDelete = new ArrayList(); - for (int i = 0; i < 10; i++) - { - if (i == 5) - { + for (int i = 0; i < 10; i++) { + if (i == 5) { commit(tx); } long id = idGenerator.generateID(); @@ -1368,8 +1253,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase journal.forceMoveNextFile(); - for (Long id : listToDelete) - { + for (Long id : listToDelete) { delete(id); } @@ -1389,8 +1273,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase } @Test - public void testCompactFirstFileWithPendingCommits3() throws Exception - { + public void testCompactFirstFileWithPendingCommits3() throws Exception { setup(2, 60 * 1024, true); createJournal(); @@ -1398,16 +1281,14 @@ public class NIOJournalCompactTest extends JournalImplTestBase loadAndCheck(); long tx = idGenerator.generateID(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { addTx(tx, idGenerator.generateID()); } journal.forceMoveNextFile(); ArrayList listToDelete = new ArrayList(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { long id = idGenerator.generateID(); listToDelete.add(id); add(id); @@ -1415,8 +1296,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase journal.forceMoveNextFile(); - for (Long id : listToDelete) - { + for (Long id : listToDelete) { delete(id); } @@ -1436,8 +1316,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase } @Test - public void testCompactFirstFileWithPendingCommits2() throws Exception - { + public void testCompactFirstFileWithPendingCommits2() throws Exception { setup(2, 60 * 1024, true); createJournal(); @@ -1445,16 +1324,14 @@ public class NIOJournalCompactTest extends JournalImplTestBase loadAndCheck(); long tx = idGenerator.generateID(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { addTx(tx, idGenerator.generateID()); } journal.forceMoveNextFile(); ArrayList listToDelete = new ArrayList(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { long id = idGenerator.generateID(); listToDelete.add(id); add(id); @@ -1462,8 +1339,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase journal.forceMoveNextFile(); - for (Long id : listToDelete) - { + for (Long id : listToDelete) { delete(id); } @@ -1485,8 +1361,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase } @Test - public void testCompactFirstFileWithPendingCommits4() throws Exception - { + public void testCompactFirstFileWithPendingCommits4() throws Exception { setup(2, 60 * 1024, true); createJournal(); @@ -1496,8 +1371,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase long[] ids = new long[10]; long tx0 = idGenerator.generateID(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ids[i] = idGenerator.generateID(); addTx(tx0, ids[i]); } @@ -1507,8 +1381,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase journal.forceMoveNextFile(); ArrayList listToDelete = new ArrayList(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { long id = idGenerator.generateID(); listToDelete.add(id); add(id); @@ -1516,8 +1389,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase journal.forceMoveNextFile(); - for (Long id : listToDelete) - { + for (Long id : listToDelete) { delete(id); } @@ -1526,8 +1398,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase startCompact(); System.out.println("Committing TX " + tx1); rollback(tx0); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { addTx(tx1, ids[i]); } @@ -1546,8 +1417,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase } @Test - public void testCompactFirstFileWithPendingCommits5() throws Exception - { + public void testCompactFirstFileWithPendingCommits5() throws Exception { setup(2, 60 * 1024, true); createJournal(); @@ -1557,8 +1427,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase long[] ids = new long[10]; long tx0 = idGenerator.generateID(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ids[i] = idGenerator.generateID(); addTx(tx0, ids[i]); } @@ -1568,8 +1437,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase journal.forceMoveNextFile(); ArrayList listToDelete = new ArrayList(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { long id = idGenerator.generateID(); listToDelete.add(id); add(id); @@ -1577,8 +1445,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase journal.forceMoveNextFile(); - for (Long id : listToDelete) - { + for (Long id : listToDelete) { delete(id); } @@ -1587,8 +1454,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase startCompact(); System.out.println("Committing TX " + tx1); rollback(tx0); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { addTx(tx1, ids[i]); } @@ -1607,8 +1473,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase } @Test - public void testCompactFirstFileWithPendingCommits6() throws Exception - { + public void testCompactFirstFileWithPendingCommits6() throws Exception { setup(2, 60 * 1024, true); createJournal(); @@ -1618,8 +1483,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase long[] ids = new long[10]; long tx0 = idGenerator.generateID(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ids[i] = idGenerator.generateID(); addTx(tx0, ids[i]); } @@ -1627,8 +1491,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase commit(tx0); startCompact(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { delete(ids[i]); } finishCompact(); @@ -1640,8 +1503,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase } @Test - public void testCompactFirstFileWithPendingCommits7() throws Exception - { + public void testCompactFirstFileWithPendingCommits7() throws Exception { setup(2, 60 * 1024, true); createJournal(); @@ -1676,8 +1538,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase } @Test - public void testLiveSizeTransactional() throws Exception - { + public void testLiveSizeTransactional() throws Exception { setup(2, 60 * 1024, true); createJournal(); @@ -1688,8 +1549,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase ArrayList expectedSizes = new ArrayList(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { long tx = idGenerator.generateID(); long id = idGenerator.generateID(); listToDelete.add(id); @@ -1725,15 +1585,13 @@ public class NIOJournalCompactTest extends JournalImplTestBase Assert.assertEquals(files.length, files2.length); - for (int i = 0; i < files.length; i++) - { + for (int i = 0; i < files.length; i++) { Assert.assertEquals(expectedSizes.get(i).intValue(), files[i].getLiveSize()); Assert.assertEquals(expectedSizes.get(i).intValue(), files2[i].getLiveSize()); } long tx = idGenerator.generateID(); - for (long id : listToDelete) - { + for (long id : listToDelete) { deleteTx(tx, id); } commit(tx); @@ -1742,8 +1600,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase JournalFile[] files3 = journal.getDataFiles(); - for (JournalFile file : files3) - { + for (JournalFile file : files3) { Assert.assertEquals(0, file.getLiveSize()); } @@ -1754,22 +1611,15 @@ public class NIOJournalCompactTest extends JournalImplTestBase files3 = journal.getDataFiles(); - for (JournalFile file : files3) - { + for (JournalFile file : files3) { Assert.assertEquals(0, file.getLiveSize()); } } @Test - public void testStressDeletesNoSync() throws Exception - { - Configuration config = createBasicConfig() - .setJournalFileSize(100 * 1024) - .setJournalSyncNonTransactional(false) - .setJournalSyncTransactional(false) - .setJournalCompactMinFiles(0) - .setJournalCompactPercentage(0); + public void testStressDeletesNoSync() throws Exception { + Configuration config = createBasicConfig().setJournalFileSize(100 * 1024).setJournalSyncNonTransactional(false).setJournalSyncTransactional(false).setJournalCompactMinFiles(0).setJournalCompactPercentage(0); final AtomicInteger errors = new AtomicInteger(0); @@ -1791,22 +1641,17 @@ public class NIOJournalCompactTest extends JournalImplTestBase ((JournalImpl) storage.getMessageJournal()).setAutoReclaim(false); final LinkedList survivingMsgs = new LinkedList(); - Runnable producerRunnable = new Runnable() - { - public void run() - { - try - { - while (running.get()) - { + Runnable producerRunnable = new Runnable() { + public void run() { + try { + while (running.get()) { final long[] values = new long[100]; long tx = seqGenerator.incrementAndGet(); OperationContextImpl ctx = new OperationContextImpl(executor); storage.setContext(ctx); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { long id = seqGenerator.incrementAndGet(); values[i] = id; @@ -1825,27 +1670,19 @@ public class NIOJournalCompactTest extends JournalImplTestBase storage.commit(tx); - ctx.executeOnCompletion(new IOCallback() - { - public void onError(int errorCode, String errorMessage) - { + ctx.executeOnCompletion(new IOCallback() { + public void onError(int errorCode, String errorMessage) { } - public void done() - { - deleteExecutor.execute(new Runnable() - { - public void run() - { - try - { - for (long messageID : values) - { + public void done() { + deleteExecutor.execute(new Runnable() { + public void run() { + try { + for (long messageID : values) { storage.deleteMessage(messageID); } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); errors.incrementAndGet(); } @@ -1857,30 +1694,24 @@ public class NIOJournalCompactTest extends JournalImplTestBase } } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); errors.incrementAndGet(); } } }; - Runnable compressRunnable = new Runnable() - { - public void run() - { - try - { - while (running.get()) - { + Runnable compressRunnable = new Runnable() { + public void run() { + try { + while (running.get()) { Thread.sleep(500); System.out.println("Compacting"); ((JournalImpl) storage.getMessageJournal()).testCompact(); ((JournalImpl) storage.getMessageJournal()).checkReclaimStatus(); } } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); errors.incrementAndGet(); } @@ -1915,21 +1746,17 @@ public class NIOJournalCompactTest extends JournalImplTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { File testDir = new File(getTestDir()); - File[] files = testDir.listFiles(new FilenameFilter() - { + File[] files = testDir.listFiles(new FilenameFilter() { - public boolean accept(File dir, String name) - { + public boolean accept(File dir, String name) { return name.startsWith(filePrefix) && name.endsWith(fileExtension); } }); - for (File file : files) - { + for (File file : files) { assertEquals("File " + file + " doesn't have the expected number of bytes", fileSize, file.length()); } @@ -1937,8 +1764,7 @@ public class NIOJournalCompactTest extends JournalImplTestBase } @Override - protected SequentialFileFactory getFileFactory() throws Exception - { + protected SequentialFileFactory getFileFactory() throws Exception { return new NIOSequentialFileFactory(getTestDirfile(), 1); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIOJournalImplTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIOJournalImplTest.java index b4ff1470bf..40fb0f379d 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIOJournalImplTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIOJournalImplTest.java @@ -24,13 +24,12 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.core.io.SequentialFileFactory; import org.apache.activemq.artemis.core.io.nio.NIOSequentialFileFactory; -public class NIOJournalImplTest extends JournalImplTestUnit -{ +public class NIOJournalImplTest extends JournalImplTestUnit { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @Override - protected SequentialFileFactory getFileFactory() throws Exception - { + protected SequentialFileFactory getFileFactory() throws Exception { File file = new File(getTestDir()); NIOJournalImplTest.log.debug("deleting directory " + getTestDir()); @@ -43,8 +42,7 @@ public class NIOJournalImplTest extends JournalImplTestUnit } @Override - protected int getAlignment() - { + protected int getAlignment() { return 1; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIONoBufferJournalImplTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIONoBufferJournalImplTest.java index d82b28cd94..584c1b3fec 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIONoBufferJournalImplTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIONoBufferJournalImplTest.java @@ -23,13 +23,12 @@ import org.apache.activemq.artemis.core.io.SequentialFileFactory; import org.apache.activemq.artemis.core.io.nio.NIOSequentialFileFactory; import org.apache.activemq.artemis.tests.unit.core.journal.impl.JournalImplTestUnit; -public class NIONoBufferJournalImplTest extends JournalImplTestUnit -{ +public class NIONoBufferJournalImplTest extends JournalImplTestUnit { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @Override - protected SequentialFileFactory getFileFactory() throws Exception - { + protected SequentialFileFactory getFileFactory() throws Exception { File file = new File(getTestDir()); NIONoBufferJournalImplTest.log.debug("deleting directory " + getTestDir()); @@ -42,8 +41,7 @@ public class NIONoBufferJournalImplTest extends JournalImplTestUnit } @Override - protected int getAlignment() - { + protected int getAlignment() { return 1; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIONonBufferedSequentialFileFactoryTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIONonBufferedSequentialFileFactoryTest.java index 20723003b8..f793a5c7c9 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIONonBufferedSequentialFileFactoryTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIONonBufferedSequentialFileFactoryTest.java @@ -15,18 +15,17 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.journal; + import java.io.File; import org.apache.activemq.artemis.core.io.SequentialFileFactory; import org.apache.activemq.artemis.core.io.nio.NIOSequentialFileFactory; import org.apache.activemq.artemis.tests.unit.core.journal.impl.SequentialFileFactoryTestBase; -public class NIONonBufferedSequentialFileFactoryTest extends SequentialFileFactoryTestBase -{ +public class NIONonBufferedSequentialFileFactoryTest extends SequentialFileFactoryTestBase { @Override - protected SequentialFileFactory createFactory(String folder) - { + protected SequentialFileFactory createFactory(String folder) { return new NIOSequentialFileFactory(new File(folder), false, 1); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIOSequentialFileFactoryTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIOSequentialFileFactoryTest.java index bcab8e60c9..dc72104692 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIOSequentialFileFactoryTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/NIOSequentialFileFactoryTest.java @@ -15,18 +15,17 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.journal; + import java.io.File; import org.apache.activemq.artemis.core.io.SequentialFileFactory; import org.apache.activemq.artemis.core.io.nio.NIOSequentialFileFactory; import org.apache.activemq.artemis.tests.unit.core.journal.impl.SequentialFileFactoryTestBase; -public class NIOSequentialFileFactoryTest extends SequentialFileFactoryTestBase -{ +public class NIOSequentialFileFactoryTest extends SequentialFileFactoryTestBase { @Override - protected SequentialFileFactory createFactory(String folder) - { + protected SequentialFileFactory createFactory(String folder) { return new NIOSequentialFileFactory(new File(folder), true, 1); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/RelativePathTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/RelativePathTest.java index 43ab75989e..349c76650c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/RelativePathTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/RelativePathTest.java @@ -28,11 +28,10 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Assert; import org.junit.Test; -public class RelativePathTest extends ActiveMQTestBase -{ +public class RelativePathTest extends ActiveMQTestBase { + @Test - public void testRelativePathOnDefaultConfig() throws Exception - { + public void testRelativePathOnDefaultConfig() throws Exception { Configuration configuration = createDefaultConfig(false); ActiveMQServer server = createServer(true, configuration, AddressSettings.DEFAULT_PAGE_SIZE, AddressSettings.DEFAULT_MAX_SIZE_BYTES, new HashMap()); @@ -44,8 +43,7 @@ public class RelativePathTest extends ActiveMQTestBase } @Test - public void testDataOutsideHome() throws Exception - { + public void testDataOutsideHome() throws Exception { Configuration configuration = createDefaultConfig(false); File instanceHome = new File(getTemporaryDir(), "artemisHome"); @@ -61,7 +59,7 @@ public class RelativePathTest extends ActiveMQTestBase File bindingsInside = new File(instanceHome, "bind"); -// configuration.setJournal + // configuration.setJournal System.out.println("Journal dir::" + configuration.getJournalDirectory()); System.out.println("Journal loc::" + configuration.getJournalLocation()); @@ -78,8 +76,7 @@ public class RelativePathTest extends ActiveMQTestBase } @Test - public void testRelativePath() throws Exception - { + public void testRelativePath() throws Exception { Configuration configuration = createDefaultConfig(false); File instanceHome = new File(getTemporaryDir(), "artemisHome"); @@ -106,15 +103,12 @@ public class RelativePathTest extends ActiveMQTestBase checkData(bindingsHome, ".bindings"); } - public void checkData(File dataHome, final String extension) - { + public void checkData(File dataHome, final String extension) { Assert.assertTrue("Folder " + dataHome + " doesn't exist", dataHome.exists()); - File[] files = dataHome.listFiles(new FileFilter() - { + File[] files = dataHome.listFiles(new FileFilter() { @Override - public boolean accept(File pathname) - { + public boolean accept(File pathname) { return (extension == null || pathname.toString().endsWith(extension)); } }); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/ValidateTransactionHealthTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/ValidateTransactionHealthTest.java index 7cebc4f3c0..1872f5eb51 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/ValidateTransactionHealthTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/journal/ValidateTransactionHealthTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.journal; + import java.io.File; import java.nio.ByteBuffer; import java.util.List; @@ -37,80 +38,67 @@ import org.junit.Test; /** * This test spawns a remote VM, as we want to "crash" the VM right after the journal is filled with data */ -public class ValidateTransactionHealthTest extends ActiveMQTestBase -{ +public class ValidateTransactionHealthTest extends ActiveMQTestBase { private static final int OK = 10; @Test - public void testAIO() throws Exception - { + public void testAIO() throws Exception { internalTest("aio", getTestDir(), 10000, 100, true, true, 1); } @Test - public void testAIOHugeTransaction() throws Exception - { + public void testAIOHugeTransaction() throws Exception { internalTest("aio", getTestDir(), 10000, 10000, true, true, 1); } @Test - public void testAIOMultiThread() throws Exception - { + public void testAIOMultiThread() throws Exception { internalTest("aio", getTestDir(), 1000, 100, true, true, 10); } @Test - public void testAIONonTransactionalNoExternalProcess() throws Exception - { + public void testAIONonTransactionalNoExternalProcess() throws Exception { internalTest("aio", getTestDir(), 1000, 0, true, false, 10); } @Test - public void testNIO() throws Exception - { + public void testNIO() throws Exception { internalTest("nio", getTestDir(), 10000, 100, true, true, 1); } @Test - public void testNIOHugeTransaction() throws Exception - { + public void testNIOHugeTransaction() throws Exception { internalTest("nio", getTestDir(), 10000, 10000, true, true, 1); } @Test - public void testNIOMultiThread() throws Exception - { + public void testNIOMultiThread() throws Exception { internalTest("nio", getTestDir(), 1000, 100, true, true, 10); } @Test - public void testNIONonTransactional() throws Exception - { + public void testNIONonTransactional() throws Exception { internalTest("nio", getTestDir(), 10000, 0, true, true, 1); } @Test - public void testNIO2() throws Exception - { + public void testNIO2() throws Exception { internalTest("nio2", getTestDir(), 10000, 100, true, true, 1); } @Test - public void testNIO2HugeTransaction() throws Exception - { + public void testNIO2HugeTransaction() throws Exception { internalTest("nio2", getTestDir(), 10000, 10000, true, true, 1); } @Test - public void testNIO2MultiThread() throws Exception - { + public void testNIO2MultiThread() throws Exception { internalTest("nio2", getTestDir(), 1000, 100, true, true, 10); } @Test - public void testNIO2NonTransactional() throws Exception - { + public void testNIO2NonTransactional() throws Exception { internalTest("nio2", getTestDir(), 10000, 0, true, true, 1); } @@ -122,53 +110,39 @@ public class ValidateTransactionHealthTest extends ActiveMQTestBase final int transactionSize, final boolean append, final boolean externalProcess, - final int numberOfThreads) throws Exception - { - try - { - if (type.equals("aio") && !LibaioContext.isLoaded()) - { + final int numberOfThreads) throws Exception { + try { + if (type.equals("aio") && !LibaioContext.isLoaded()) { // Using System.out as this output will go towards junit report System.out.println("AIO not found, test being ignored on this platform"); return; } // This property could be set to false for debug purposes. - if (append) - { - if (externalProcess) - { - Process process = SpawnedVMSupport.spawnVM(ValidateTransactionHealthTest.class.getCanonicalName(), - type, - journalDir, - Long.toString(numberOfRecords), - Integer.toString(transactionSize), - Integer.toString(numberOfThreads)); + if (append) { + if (externalProcess) { + Process process = SpawnedVMSupport.spawnVM(ValidateTransactionHealthTest.class.getCanonicalName(), type, journalDir, Long.toString(numberOfRecords), Integer.toString(transactionSize), Integer.toString(numberOfThreads)); process.waitFor(); Assert.assertEquals(ValidateTransactionHealthTest.OK, process.exitValue()); } - else - { - JournalImpl journal = ValidateTransactionHealthTest.appendData(type, - journalDir, - numberOfRecords, - transactionSize, - numberOfThreads); + else { + JournalImpl journal = ValidateTransactionHealthTest.appendData(type, journalDir, numberOfRecords, transactionSize, numberOfThreads); journal.stop(); } } reload(type, journalDir, numberOfRecords, numberOfThreads); } - finally - { + finally { File file = new File(journalDir); deleteDirectory(file); } } - private void reload(final String type, final String journalDir, final long numberOfRecords, final int numberOfThreads) throws Exception - { + private void reload(final String type, + final String journalDir, + final long numberOfRecords, + final int numberOfThreads) throws Exception { JournalImpl journal = ValidateTransactionHealthTest.createJournal(type, journalDir); journal.start(); @@ -181,16 +155,15 @@ public class ValidateTransactionHealthTest extends ActiveMQTestBase journal.stop(); - if (loadTest.ex != null) - { + if (loadTest.ex != null) { throw loadTest.ex; } } // Inner classes ------------------------------------------------- - static class Loader implements LoaderCallback - { + static class Loader implements LoaderCallback { + int numberOfPreparedTransactions = 0; int numberOfAdds = 0; @@ -205,29 +178,24 @@ public class ValidateTransactionHealthTest extends ActiveMQTestBase long lastID = 0; - public Loader(final long expectedRecords) - { + public Loader(final long expectedRecords) { this.expectedRecords = expectedRecords; } - public void addPreparedTransaction(final PreparedTransactionInfo preparedTransaction) - { + public void addPreparedTransaction(final PreparedTransactionInfo preparedTransaction) { numberOfPreparedTransactions++; } - public void addRecord(final RecordInfo info) - { - if (info.id == lastID) - { + public void addRecord(final RecordInfo info) { + if (info.id == lastID) { System.out.println("id = " + info.id + " last id = " + lastID); } ByteBuffer buffer = ByteBuffer.wrap(info.data); long recordValue = buffer.getLong(); - if (recordValue != info.id) - { + if (recordValue != info.id) { ex = new Exception("Content not as expected (" + recordValue + " != " + info.id + ")"); } @@ -237,35 +205,30 @@ public class ValidateTransactionHealthTest extends ActiveMQTestBase } - public void deleteRecord(final long id) - { + public void deleteRecord(final long id) { numberOfDeletes++; } - public void updateRecord(final RecordInfo info) - { + public void updateRecord(final RecordInfo info) { numberOfUpdates++; } public void failedTransaction(final long transactionID, final List records, - final List recordsToDelete) - { + final List recordsToDelete) { } } // Remote part of the test ================================================================= - public static void main(final String[] args) throws Exception - { + public static void main(final String[] args) throws Exception { - if (args.length != 5) - { + if (args.length != 5) { System.err.println("Use: java -cp " + ValidateTransactionHealthTest.class.getCanonicalName() + - " aio|nio "); + " aio|nio "); System.exit(-1); } System.out.println("Running"); @@ -275,21 +238,15 @@ public class ValidateTransactionHealthTest extends ActiveMQTestBase int transactionSize = Integer.parseInt(args[3]); int numberOfThreads = Integer.parseInt(args[4]); - try - { - ValidateTransactionHealthTest.appendData(journalType, - journalDir, - numberOfElements, - transactionSize, - numberOfThreads); + try { + ValidateTransactionHealthTest.appendData(journalType, journalDir, numberOfElements, transactionSize, numberOfThreads); // We don't stop the journal on the case of an external process... // The test is making sure that committed data can be reloaded fine... // i.e. commits are sync on disk as stated on the transaction. // The journal shouldn't leave any state impeding reloading the server } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(System.out); System.exit(-1); } @@ -302,100 +259,73 @@ public class ValidateTransactionHealthTest extends ActiveMQTestBase final String journalDir, final long numberOfElements, final int transactionSize, - final int numberOfThreads) throws Exception - { + final int numberOfThreads) throws Exception { final JournalImpl journal = ValidateTransactionHealthTest.createJournal(journalType, journalDir); journal.start(); - journal.load(new LoaderCallback() - { + journal.load(new LoaderCallback() { - public void addPreparedTransaction(final PreparedTransactionInfo preparedTransaction) - { + public void addPreparedTransaction(final PreparedTransactionInfo preparedTransaction) { } - public void addRecord(final RecordInfo info) - { + public void addRecord(final RecordInfo info) { } - public void deleteRecord(final long id) - { + public void deleteRecord(final long id) { } - public void updateRecord(final RecordInfo info) - { + public void updateRecord(final RecordInfo info) { } public void failedTransaction(final long transactionID, final List records, - final List recordsToDelete) - { + final List recordsToDelete) { } }); LocalThread[] threads = new LocalThread[numberOfThreads]; final AtomicLong sequenceTransaction = new AtomicLong(); - for (int i = 0; i < numberOfThreads; i++) - { + for (int i = 0; i < numberOfThreads; i++) { threads[i] = new LocalThread(journal, numberOfElements, transactionSize, sequenceTransaction); threads[i].start(); } Exception e = null; - for (LocalThread t : threads) - { + for (LocalThread t : threads) { t.join(); - if (t.e != null) - { + if (t.e != null) { e = t.e; } } - if (e != null) - { + if (e != null) { throw e; } return journal; } - public static JournalImpl createJournal(final String journalType, final String journalDir) - { - JournalImpl journal = new JournalImpl(10485760, - 2, - 0, - 0, - ValidateTransactionHealthTest.getFactory(journalType, journalDir), - "journaltst", - "tst", - 500); + public static JournalImpl createJournal(final String journalType, final String journalDir) { + JournalImpl journal = new JournalImpl(10485760, 2, 0, 0, ValidateTransactionHealthTest.getFactory(journalType, journalDir), "journaltst", "tst", 500); return journal; } - public static SequentialFileFactory getFactory(final String factoryType, final String directory) - { - if (factoryType.equals("aio")) - { - return new AIOSequentialFileFactory(new File(directory), - JournalConstants.DEFAULT_JOURNAL_BUFFER_SIZE_AIO, - JournalConstants.DEFAULT_JOURNAL_BUFFER_TIMEOUT_AIO, - 10, - false); + public static SequentialFileFactory getFactory(final String factoryType, final String directory) { + if (factoryType.equals("aio")) { + return new AIOSequentialFileFactory(new File(directory), JournalConstants.DEFAULT_JOURNAL_BUFFER_SIZE_AIO, JournalConstants.DEFAULT_JOURNAL_BUFFER_TIMEOUT_AIO, 10, false); } - else if (factoryType.equals("nio2")) - { + else if (factoryType.equals("nio2")) { return new NIOSequentialFileFactory(new File(directory), true, 1); } - else - { + else { return new NIOSequentialFileFactory(new File(directory), false, 1); } } - static class LocalThread extends Thread - { + static class LocalThread extends Thread { + final JournalImpl journal; final long numberOfElements; @@ -409,8 +339,7 @@ public class ValidateTransactionHealthTest extends ActiveMQTestBase public LocalThread(final JournalImpl journal, final long numberOfElements, final int transactionSize, - final AtomicLong nextID) - { + final AtomicLong nextID) { super(); this.journal = journal; this.numberOfElements = numberOfElements; @@ -419,52 +348,43 @@ public class ValidateTransactionHealthTest extends ActiveMQTestBase } @Override - public void run() - { - try - { + public void run() { + try { int transactionCounter = 0; long transactionId = nextID.incrementAndGet(); - for (long i = 0; i < numberOfElements; i++) - { + for (long i = 0; i < numberOfElements; i++) { long id = nextID.incrementAndGet(); ByteBuffer buffer = ByteBuffer.allocate(512 * 3); buffer.putLong(id); - if (transactionSize != 0) - { - journal.appendAddRecordTransactional(transactionId, id, (byte)99, buffer.array()); + if (transactionSize != 0) { + journal.appendAddRecordTransactional(transactionId, id, (byte) 99, buffer.array()); - if (++transactionCounter == transactionSize) - { + if (++transactionCounter == transactionSize) { System.out.println("Commit transaction " + transactionId); journal.appendCommitRecord(transactionId, true); transactionCounter = 0; transactionId = nextID.incrementAndGet(); } } - else - { - journal.appendAddRecord(id, (byte)99, buffer.array(), false); + else { + journal.appendAddRecord(id, (byte) 99, buffer.array(), false); } } - if (transactionCounter != 0) - { + if (transactionCounter != 0) { journal.appendCommitRecord(transactionId, true); } - if (transactionSize == 0) - { + if (transactionSize == 0) { journal.debugWait(); } } - catch (Exception e) - { + catch (Exception e) { this.e = e; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/largemessage/LargeMessageTestBase.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/largemessage/LargeMessageTestBase.java index d7cc2393a2..f82b677254 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/largemessage/LargeMessageTestBase.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/largemessage/LargeMessageTestBase.java @@ -47,8 +47,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; -public abstract class LargeMessageTestBase extends ActiveMQTestBase -{ +public abstract class LargeMessageTestBase extends ActiveMQTestBase { // Constants ----------------------------------------------------- private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @@ -79,23 +78,8 @@ public abstract class LargeMessageTestBase extends ActiveMQTestBase final int numberOfMessages, final long numberOfBytes, final int waitOnConsumer, - final long delayDelivery) throws Exception - { - testChunks(isXA, - restartOnXA, - rollbackFirstSend, - useStreamOnConsume, - realFiles, - preAck, - sendingBlocking, - testBrowser, - useMessageConsumer, - numberOfMessages, - numberOfBytes, - waitOnConsumer, - delayDelivery, - -1, - 10 * 1024); + final long delayDelivery) throws Exception { + testChunks(isXA, restartOnXA, rollbackFirstSend, useStreamOnConsume, realFiles, preAck, sendingBlocking, testBrowser, useMessageConsumer, numberOfMessages, numberOfBytes, waitOnConsumer, delayDelivery, -1, 10 * 1024); } protected void testChunks(final boolean isXA, @@ -112,26 +96,20 @@ public abstract class LargeMessageTestBase extends ActiveMQTestBase final int waitOnConsumer, final long delayDelivery, final int producerWindow, - final int minSize) throws Exception - { + final int minSize) throws Exception { clearDataRecreateServerDirs(); ActiveMQServer server = createServer(realFiles); server.start(); ServerLocator locator = createInVMNonHALocator(); - try - { + try { - if (sendingBlocking) - { - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + if (sendingBlocking) { + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); } - if (producerWindow > 0) - { + if (producerWindow > 0) { locator.setConfirmationWindowSize(producerWindow); } @@ -144,8 +122,7 @@ public abstract class LargeMessageTestBase extends ActiveMQTestBase Xid xid = null; session = sf.createSession(null, null, isXA, false, false, preAck, 0); - if (isXA) - { + if (isXA) { xid = newXID(); session.start(xid, XAResource.TMNOFLAGS); } @@ -154,19 +131,16 @@ public abstract class LargeMessageTestBase extends ActiveMQTestBase ClientProducer producer = session.createProducer(ADDRESS); - if (rollbackFirstSend) - { + if (rollbackFirstSend) { sendMessages(numberOfMessages, numberOfBytes, delayDelivery, session, producer); - if (isXA) - { + if (isXA) { session.end(xid, XAResource.TMSUCCESS); session.prepare(xid); session.close(); - if (realFiles && restartOnXA) - { + if (realFiles && restartOnXA) { server.stop(); server.start(); sf = locator.createSessionFactory(); @@ -183,8 +157,7 @@ public abstract class LargeMessageTestBase extends ActiveMQTestBase xid = newXID(); session.start(xid, XAResource.TMNOFLAGS); } - else - { + else { session.rollback(); } @@ -193,15 +166,13 @@ public abstract class LargeMessageTestBase extends ActiveMQTestBase sendMessages(numberOfMessages, numberOfBytes, delayDelivery, session, producer); - if (isXA) - { + if (isXA) { session.end(xid, XAResource.TMSUCCESS); session.prepare(xid); session.close(); - if (realFiles && restartOnXA) - { + if (realFiles && restartOnXA) { server.stop(); server.start(); //we need to recreate sf's @@ -220,15 +191,13 @@ public abstract class LargeMessageTestBase extends ActiveMQTestBase xid = newXID(); session.start(xid, XAResource.TMNOFLAGS); } - else - { + else { session.commit(); } session.close(); - if (realFiles) - { + if (realFiles) { server.stop(); server = createServer(realFiles); @@ -239,86 +208,67 @@ public abstract class LargeMessageTestBase extends ActiveMQTestBase session = sf.createSession(null, null, isXA, false, false, preAck, 0); - if (isXA) - { + if (isXA) { xid = newXID(); session.start(xid, XAResource.TMNOFLAGS); } ClientConsumer consumer = null; - for (int iteration = testBrowser ? 0 : 1; iteration < 2; iteration++) - { + for (int iteration = testBrowser ? 0 : 1; iteration < 2; iteration++) { session.stop(); // first time with a browser consumer = session.createConsumer(ADDRESS, null, iteration == 0); - if (useMessageConsumer) - { + if (useMessageConsumer) { final CountDownLatch latchDone = new CountDownLatch(numberOfMessages); final AtomicInteger errors = new AtomicInteger(0); - MessageHandler handler = new MessageHandler() - { + MessageHandler handler = new MessageHandler() { int msgCounter; - public void onMessage(final ClientMessage message) - { - try - { - if (delayDelivery > 0) - { + public void onMessage(final ClientMessage message) { + try { + if (delayDelivery > 0) { long originalTime = (Long) message.getObjectProperty(new SimpleString("original-time")); - Assert.assertTrue(System.currentTimeMillis() - originalTime + "<" + delayDelivery, - System.currentTimeMillis() - originalTime >= delayDelivery); + Assert.assertTrue(System.currentTimeMillis() - originalTime + "<" + delayDelivery, System.currentTimeMillis() - originalTime >= delayDelivery); } - if (!preAck) - { + if (!preAck) { message.acknowledge(); } Assert.assertNotNull(message); - if (delayDelivery <= 0) - { + if (delayDelivery <= 0) { // right now there is no guarantee of ordered delivered on multiple scheduledMessages with // the same // scheduled delivery time - Assert.assertEquals(msgCounter, - ((Integer) message.getObjectProperty(new SimpleString("counter-message"))).intValue()); + Assert.assertEquals(msgCounter, ((Integer) message.getObjectProperty(new SimpleString("counter-message"))).intValue()); } - if (useStreamOnConsume) - { + if (useStreamOnConsume) { final AtomicLong bytesRead = new AtomicLong(0); - message.saveToOutputStream(new OutputStream() - { + message.saveToOutputStream(new OutputStream() { @Override - public void write(final byte[] b) throws IOException - { - if (b[0] == ActiveMQTestBase.getSamplebyte(bytesRead.get())) - { + public void write(final byte[] b) throws IOException { + if (b[0] == ActiveMQTestBase.getSamplebyte(bytesRead.get())) { bytesRead.addAndGet(b.length); LargeMessageTestBase.log.debug("Read position " + bytesRead.get() + " on consumer"); } - else - { + else { LargeMessageTestBase.log.warn("Received invalid packet at position " + bytesRead.get()); } } @Override - public void write(final int b) throws IOException - { - if (b == ActiveMQTestBase.getSamplebyte(bytesRead.get())) - { + public void write(final int b) throws IOException { + if (b == ActiveMQTestBase.getSamplebyte(bytesRead.get())) { bytesRead.incrementAndGet(); } - else - { + else { LargeMessageTestBase.log.warn("byte not as expected!"); } } @@ -326,39 +276,32 @@ public abstract class LargeMessageTestBase extends ActiveMQTestBase Assert.assertEquals(numberOfBytes, bytesRead.get()); } - else - { + else { ActiveMQBuffer buffer = message.getBodyBuffer(); buffer.resetReaderIndex(); - for (long b = 0; b < numberOfBytes; b++) - { - if (b % (1024L * 1024L) == 0) - { + for (long b = 0; b < numberOfBytes; b++) { + if (b % (1024L * 1024L) == 0) { LargeMessageTestBase.log.debug("Read " + b + " bytes"); } Assert.assertEquals(ActiveMQTestBase.getSamplebyte(b), buffer.readByte()); } - try - { + try { buffer.readByte(); Assert.fail("Supposed to throw an exception"); } - catch (Exception e) - { + catch (Exception e) { } } } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); LargeMessageTestBase.log.warn("Got an error", e); errors.incrementAndGet(); } - finally - { + finally { latchDone.countDown(); msgCounter++; } @@ -372,13 +315,11 @@ public abstract class LargeMessageTestBase extends ActiveMQTestBase Assert.assertTrue(latchDone.await(waitOnConsumer, TimeUnit.MILLISECONDS)); Assert.assertEquals(0, errors.get()); } - else - { + else { session.start(); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { System.currentTimeMillis(); ClientMessage message = consumer.receive(waitOnConsumer + delayDelivery); @@ -387,61 +328,47 @@ public abstract class LargeMessageTestBase extends ActiveMQTestBase System.currentTimeMillis(); - if (delayDelivery > 0) - { + if (delayDelivery > 0) { long originalTime = (Long) message.getObjectProperty(new SimpleString("original-time")); - Assert.assertTrue(System.currentTimeMillis() - originalTime + "<" + delayDelivery, - System.currentTimeMillis() - originalTime >= delayDelivery); + Assert.assertTrue(System.currentTimeMillis() - originalTime + "<" + delayDelivery, System.currentTimeMillis() - originalTime >= delayDelivery); } - if (!preAck) - { + if (!preAck) { message.acknowledge(); } Assert.assertNotNull(message); - if (delayDelivery <= 0) - { + if (delayDelivery <= 0) { // right now there is no guarantee of ordered delivered on multiple scheduledMessages with the same // scheduled delivery time - Assert.assertEquals(i, - ((Integer) message.getObjectProperty(new SimpleString("counter-message"))).intValue()); + Assert.assertEquals(i, ((Integer) message.getObjectProperty(new SimpleString("counter-message"))).intValue()); } - if (useStreamOnConsume) - { + if (useStreamOnConsume) { final AtomicLong bytesRead = new AtomicLong(0); - message.saveToOutputStream(new OutputStream() - { + message.saveToOutputStream(new OutputStream() { @Override - public void write(final byte[] b) throws IOException - { - if (b[0] == ActiveMQTestBase.getSamplebyte(bytesRead.get())) - { + public void write(final byte[] b) throws IOException { + if (b[0] == ActiveMQTestBase.getSamplebyte(bytesRead.get())) { bytesRead.addAndGet(b.length); } - else - { + else { LargeMessageTestBase.log.warn("Received invalid packet at position " + bytesRead.get()); } } @Override - public void write(final int b) throws IOException - { - if (bytesRead.get() % (1024L * 1024L) == 0) - { + public void write(final int b) throws IOException { + if (bytesRead.get() % (1024L * 1024L) == 0) { LargeMessageTestBase.log.debug("Read " + bytesRead.get() + " bytes"); } - if (b == (byte) 'a') - { + if (b == (byte) 'a') { bytesRead.incrementAndGet(); } - else - { + else { LargeMessageTestBase.log.warn("byte not as expected!"); } } @@ -449,15 +376,12 @@ public abstract class LargeMessageTestBase extends ActiveMQTestBase Assert.assertEquals(numberOfBytes, bytesRead.get()); } - else - { + else { ActiveMQBuffer buffer = message.getBodyBuffer(); buffer.resetReaderIndex(); - for (long b = 0; b < numberOfBytes; b++) - { - if (b % (1024L * 1024L) == 0L) - { + for (long b = 0; b < numberOfBytes; b++) { + if (b % (1024L * 1024L) == 0L) { LargeMessageTestBase.log.debug("Read " + b + " bytes"); } Assert.assertEquals(ActiveMQTestBase.getSamplebyte(b), buffer.readByte()); @@ -469,31 +393,25 @@ public abstract class LargeMessageTestBase extends ActiveMQTestBase } consumer.close(); - if (iteration == 0) - { - if (isXA) - { + if (iteration == 0) { + if (isXA) { session.end(xid, XAResource.TMSUCCESS); session.rollback(xid); xid = newXID(); session.start(xid, XAResource.TMNOFLAGS); } - else - { + else { session.rollback(); } } - else - { - if (isXA) - { + else { + if (isXA) { session.end(xid, XAResource.TMSUCCESS); session.commit(xid, true); xid = newXID(); session.start(xid, XAResource.TMNOFLAGS); } - else - { + else { session.commit(); } } @@ -507,15 +425,12 @@ public abstract class LargeMessageTestBase extends ActiveMQTestBase validateNoFilesOnLargeDir(); } - finally - { + finally { locator.close(); - try - { + try { server.stop(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } } @@ -534,52 +449,43 @@ public abstract class LargeMessageTestBase extends ActiveMQTestBase final long numberOfBytes, final long delayDelivery, final ClientSession session, - final ClientProducer producer) throws Exception - { + final ClientProducer producer) throws Exception { LargeMessageTestBase.log.debug("NumberOfBytes = " + numberOfBytes); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage message = session.createMessage(true); // If the test is using more than 1M, we will only use the Streaming, as it require too much memory from the // test - if (numberOfBytes > 1024 * 1024 || i % 2 == 0) - { + if (numberOfBytes > 1024 * 1024 || i % 2 == 0) { LargeMessageTestBase.log.debug("Sending message (stream)" + i); message.setBodyInputStream(ActiveMQTestBase.createFakeLargeStream(numberOfBytes)); } - else - { + else { LargeMessageTestBase.log.debug("Sending message (array)" + i); byte[] bytes = new byte[(int) numberOfBytes]; - for (int j = 0; j < bytes.length; j++) - { + for (int j = 0; j < bytes.length; j++) { bytes[j] = ActiveMQTestBase.getSamplebyte(j); } message.getBodyBuffer().writeBytes(bytes); } message.putIntProperty(new SimpleString("counter-message"), i); - if (delayDelivery > 0) - { + if (delayDelivery > 0) { long time = System.currentTimeMillis(); message.putLongProperty(new SimpleString("original-time"), time); message.putLongProperty(Message.HDR_SCHEDULED_DELIVERY_TIME, time + delayDelivery); producer.send(message); } - else - { + else { producer.send(message); } } } - protected ActiveMQBuffer createLargeBuffer(final int numberOfIntegers) - { + protected ActiveMQBuffer createLargeBuffer(final int numberOfIntegers) { ActiveMQBuffer body = ActiveMQBuffers.fixedBuffer(DataConstants.SIZE_INT * numberOfIntegers); - for (int i = 0; i < numberOfIntegers; i++) - { + for (int i = 0; i < numberOfIntegers; i++) { body.writeInt(i); } @@ -587,13 +493,14 @@ public abstract class LargeMessageTestBase extends ActiveMQTestBase } - protected ClientMessage createLargeClientMessageStreaming(final ClientSession session, final int numberOfBytes) throws Exception - { + protected ClientMessage createLargeClientMessageStreaming(final ClientSession session, + final int numberOfBytes) throws Exception { return createLargeClientMessageStreaming(session, numberOfBytes, true); } - protected ClientMessage createLargeClientMessage(final ClientSession session, final byte[] buffer, final boolean durable) throws Exception - { + protected ClientMessage createLargeClientMessage(final ClientSession session, + final byte[] buffer, + final boolean durable) throws Exception { ClientMessage msgs = session.createMessage(durable); msgs.getBodyBuffer().writeBytes(buffer); return msgs; @@ -601,8 +508,7 @@ public abstract class LargeMessageTestBase extends ActiveMQTestBase protected ClientMessage createLargeClientMessageStreaming(final ClientSession session, final long numberOfBytes, - final boolean persistent) throws Exception - { + final boolean persistent) throws Exception { ClientMessage clientMessage = session.createMessage(persistent); @@ -619,9 +525,9 @@ public abstract class LargeMessageTestBase extends ActiveMQTestBase * @throws FileNotFoundException * @throws IOException */ - protected void readMessage(final ClientSession session, final SimpleString queueToRead, final int numberOfBytes) throws ActiveMQException, - IOException - { + protected void readMessage(final ClientSession session, + final SimpleString queueToRead, + final int numberOfBytes) throws ActiveMQException, IOException { session.start(); ClientConsumer consumer = session.createConsumer(queueToRead); @@ -637,31 +543,25 @@ public abstract class LargeMessageTestBase extends ActiveMQTestBase consumer.close(); } - protected OutputStream createFakeOutputStream() throws Exception - { + protected OutputStream createFakeOutputStream() throws Exception { - return new OutputStream() - { + return new OutputStream() { private boolean closed = false; private int count; @Override - public void close() throws IOException - { + public void close() throws IOException { super.close(); closed = true; } @Override - public void write(final int b) throws IOException - { - if (count++ % 1024 * 1024 == 0) - { + public void write(final int b) throws IOException { + if (count++ % 1024 * 1024 == 0) { LargeMessageTestBase.log.debug("OutputStream received " + count + " bytes"); } - if (closed) - { + if (closed) { throw new IOException("Stream was closed"); } } @@ -673,133 +573,113 @@ public abstract class LargeMessageTestBase extends ActiveMQTestBase //depending on the value of regular argument, it can produce a text stream //whose size is above minLargeMessageSize but whose compressed size is either //below minLargeMessageSize (regular = true) or above it (regular = false) - public static void adjustLargeCompression(boolean regular, TestLargeMessageInputStream stream, int step) throws IOException - { + public static void adjustLargeCompression(boolean regular, + TestLargeMessageInputStream stream, + int step) throws IOException { int absoluteStep = Math.abs(step); - while (true) - { + while (true) { DeflaterReader compressor = new DeflaterReader(stream, new AtomicLong()); - try - { + try { byte[] buffer = new byte[1048 * 50]; int totalCompressed = 0; int n = compressor.read(buffer); - while (n != -1) - { + while (n != -1) { totalCompressed += n; n = compressor.read(buffer); } // check compressed size - if (regular && (totalCompressed < stream.getMinLarge())) - { + if (regular && (totalCompressed < stream.getMinLarge())) { // ok it can be sent as regular stream.resetAdjust(0); break; } - else if ((!regular) && (totalCompressed > stream.getMinLarge())) - { + else if ((!regular) && (totalCompressed > stream.getMinLarge())) { // now it cannot be sent as regular stream.resetAdjust(0); break; } - else - { + else { stream.resetAdjust(regular ? -absoluteStep : absoluteStep); } } - finally - { + finally { compressor.close(); } } } - public static class TestLargeMessageInputStream extends InputStream - { + public static class TestLargeMessageInputStream extends InputStream { + private final int minLarge; private int size; private int pos; private boolean random; - public TestLargeMessageInputStream(int minLarge) - { + public TestLargeMessageInputStream(int minLarge) { this(minLarge, false); } - public TestLargeMessageInputStream(int minLarge, boolean random) - { + public TestLargeMessageInputStream(int minLarge, boolean random) { pos = 0; this.minLarge = minLarge; this.size = minLarge + 1024; this.random = random; } - public int getChar(int index) - { - if (random) - { + public int getChar(int index) { + if (random) { Random r = new Random(); return 'A' + r.nextInt(26); } - else - { + else { return 'A' + index % 26; } } - public void setSize(int size) - { + public void setSize(int size) { this.size = size; } - public TestLargeMessageInputStream(TestLargeMessageInputStream other) - { + public TestLargeMessageInputStream(TestLargeMessageInputStream other) { this.minLarge = other.minLarge; this.size = other.size; this.pos = other.pos; } - public int getSize() - { + public int getSize() { return size; } - public int getMinLarge() - { + public int getMinLarge() { return this.minLarge; } @Override - public int read() throws IOException - { - if (pos == size) return -1; + public int read() throws IOException { + if (pos == size) + return -1; pos++; return getChar(pos - 1); } - public void resetAdjust(int step) - { + public void resetAdjust(int step) { size += step; - if (size <= minLarge) - { + if (size <= minLarge) { throw new IllegalStateException("Couldn't adjust anymore, size smaller than minLarge " + minLarge); } pos = 0; } - public TestLargeMessageInputStream clone() - { + public TestLargeMessageInputStream clone() { return new TestLargeMessageInputStream(this); } - public char[] toArray() throws IOException - { + public char[] toArray() throws IOException { char[] result = new char[size]; - for (int i = 0; i < result.length; i++) - { + for (int i = 0; i < result.length; i++) { result[i] = (char) read(); } return result; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/largemessage/ServerLargeMessageTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/largemessage/ServerLargeMessageTest.java index 0307e335fb..5e7d16eee1 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/largemessage/ServerLargeMessageTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/largemessage/ServerLargeMessageTest.java @@ -31,8 +31,7 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Assert; import org.junit.Test; -public class ServerLargeMessageTest extends ActiveMQTestBase -{ +public class ServerLargeMessageTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -46,8 +45,7 @@ public class ServerLargeMessageTest extends ActiveMQTestBase // The ClientConsumer should be able to also send ServerLargeMessages as that's done by the CoreBridge @Test - public void testSendServerMessage() throws Exception - { + public void testSendServerMessage() throws Exception { ActiveMQServer server = createServer(true); server.start(); @@ -58,20 +56,17 @@ public class ServerLargeMessageTest extends ActiveMQTestBase ClientSession session = sf.createSession(false, false); - try - { + try { LargeServerMessageImpl fileMessage = new LargeServerMessageImpl((JournalStorageManager) server.getStorageManager()); fileMessage.setMessageID(1005); - for (int i = 0; i < 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; i++) - { + for (int i = 0; i < 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; i++) { fileMessage.addBytes(new byte[]{ActiveMQTestBase.getSamplebyte(i)}); } // The server would be doing this fileMessage.putLongProperty(Message.HDR_LARGE_BODY_SIZE, 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE); - fileMessage.releaseResources(); session.createQueue("A", "A"); @@ -94,8 +89,7 @@ public class ServerLargeMessageTest extends ActiveMQTestBase Assert.assertEquals(msg.getBodySize(), 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE); - for (int i = 0; i < 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; i++) - { + for (int i = 0; i < 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; i++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg.getBodyBuffer().readByte()); } @@ -104,8 +98,7 @@ public class ServerLargeMessageTest extends ActiveMQTestBase session.commit(); } - finally - { + finally { sf.close(); locator.close(); server.stop(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/AcceptorControlTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/AcceptorControlTest.java index 0c9a7e4d1d..691d513cf7 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/AcceptorControlTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/AcceptorControlTest.java @@ -36,8 +36,7 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.management.Notification; import org.apache.activemq.artemis.tests.util.RandomUtil; -public class AcceptorControlTest extends ManagementTestBase -{ +public class AcceptorControlTest extends ManagementTestBase { // Static -------------------------------------------------------- // Constructors -------------------------------------------------- @@ -45,14 +44,10 @@ public class AcceptorControlTest extends ManagementTestBase // Public -------------------------------------------------------- @Test - public void testAttributes() throws Exception - { - TransportConfiguration acceptorConfig = new TransportConfiguration(InVMAcceptorFactory.class.getName(), - new HashMap(), - RandomUtil.randomString()); + public void testAttributes() throws Exception { + TransportConfiguration acceptorConfig = new TransportConfiguration(InVMAcceptorFactory.class.getName(), new HashMap(), RandomUtil.randomString()); - Configuration config = createBasicConfig() - .addAcceptorConfiguration(acceptorConfig); + Configuration config = createBasicConfig().addAcceptorConfiguration(acceptorConfig); ActiveMQServer service = createServer(false, config); service.setMBeanServer(mbeanServer); service.start(); @@ -64,13 +59,9 @@ public class AcceptorControlTest extends ManagementTestBase } @Test - public void testStartStop() throws Exception - { - TransportConfiguration acceptorConfig = new TransportConfiguration(InVMAcceptorFactory.class.getName(), - new HashMap(), - RandomUtil.randomString()); - Configuration config = createBasicConfig() - .addAcceptorConfiguration(acceptorConfig); + public void testStartStop() throws Exception { + TransportConfiguration acceptorConfig = new TransportConfiguration(InVMAcceptorFactory.class.getName(), new HashMap(), RandomUtil.randomString()); + Configuration config = createBasicConfig().addAcceptorConfiguration(acceptorConfig); ActiveMQServer service = createServer(false, config); service.setMBeanServer(mbeanServer); service.start(); @@ -89,13 +80,11 @@ public class AcceptorControlTest extends ManagementTestBase Assert.assertFalse(acceptorControl.isStarted()); - try - { + try { sf.createSession(false, true, true); Assert.fail("acceptor must not accept connections when stopped accepting"); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { } acceptorControl.start(); @@ -112,25 +101,19 @@ public class AcceptorControlTest extends ManagementTestBase Assert.assertFalse(acceptorControl.isStarted()); - try - { + try { sf.createSession(false, true, true); Assert.fail("acceptor must not accept connections when stopped accepting"); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { } } @Test - public void testNotifications() throws Exception - { - TransportConfiguration acceptorConfig = new TransportConfiguration(InVMAcceptorFactory.class.getName(), - new HashMap(), - RandomUtil.randomString()); - Configuration config = createBasicConfig() - .addAcceptorConfiguration(acceptorConfig); + public void testNotifications() throws Exception { + TransportConfiguration acceptorConfig = new TransportConfiguration(InVMAcceptorFactory.class.getName(), new HashMap(), RandomUtil.randomString()); + Configuration config = createBasicConfig().addAcceptorConfiguration(acceptorConfig); ActiveMQServer service = createServer(false, config); service.setMBeanServer(mbeanServer); service.start(); @@ -148,24 +131,21 @@ public class AcceptorControlTest extends ManagementTestBase Assert.assertEquals(1, notifListener.getNotifications().size()); Notification notif = notifListener.getNotifications().get(0); Assert.assertEquals(CoreNotificationType.ACCEPTOR_STOPPED, notif.getType()); - Assert.assertEquals(InVMAcceptorFactory.class.getName(), - notif.getProperties().getSimpleStringProperty(new SimpleString("factory")).toString()); + Assert.assertEquals(InVMAcceptorFactory.class.getName(), notif.getProperties().getSimpleStringProperty(new SimpleString("factory")).toString()); acceptorControl.start(); Assert.assertEquals(2, notifListener.getNotifications().size()); notif = notifListener.getNotifications().get(1); Assert.assertEquals(CoreNotificationType.ACCEPTOR_STARTED, notif.getType()); - Assert.assertEquals(InVMAcceptorFactory.class.getName(), - notif.getProperties().getSimpleStringProperty(new SimpleString("factory")).toString()); + Assert.assertEquals(InVMAcceptorFactory.class.getName(), notif.getProperties().getSimpleStringProperty(new SimpleString("factory")).toString()); } // Package protected --------------------------------------------- // Protected ----------------------------------------------------- - protected AcceptorControl createManagementControl(final String name) throws Exception - { + protected AcceptorControl createManagementControl(final String name) throws Exception { return ManagementControlHelper.createAcceptorControl(name, mbeanServer); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/AcceptorControlUsingCoreTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/AcceptorControlUsingCoreTest.java index 9ae2f8eb6e..95cbe5ccab 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/AcceptorControlUsingCoreTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/AcceptorControlUsingCoreTest.java @@ -25,8 +25,7 @@ import org.junit.Test; import java.util.Map; -public class AcceptorControlUsingCoreTest extends AcceptorControlTest -{ +public class AcceptorControlUsingCoreTest extends AcceptorControlTest { // Constants ----------------------------------------------------- @@ -41,8 +40,7 @@ public class AcceptorControlUsingCoreTest extends AcceptorControlTest private ClientSession session; @Override - protected AcceptorControl createManagementControl(final String name) throws Exception - { + protected AcceptorControl createManagementControl(final String name) throws Exception { ServerLocator locator = createInVMNonHALocator(); addServerLocator(locator); ClientSessionFactory sf = createSessionFactory(locator); @@ -50,39 +48,32 @@ public class AcceptorControlUsingCoreTest extends AcceptorControlTest addClientSession(session); session.start(); - return new AcceptorControl() - { + return new AcceptorControl() { private final CoreMessagingProxy proxy = new CoreMessagingProxy(session, ResourceNames.CORE_ACCEPTOR + name); - public String getFactoryClassName() - { - return (String)proxy.retrieveAttributeValue("factoryClassName"); + public String getFactoryClassName() { + return (String) proxy.retrieveAttributeValue("factoryClassName"); } - public String getName() - { - return (String)proxy.retrieveAttributeValue("name"); + public String getName() { + return (String) proxy.retrieveAttributeValue("name"); } @SuppressWarnings("unchecked") - public Map getParameters() - { - return (Map)proxy.retrieveAttributeValue("parameters"); + public Map getParameters() { + return (Map) proxy.retrieveAttributeValue("parameters"); } - public boolean isStarted() - { - return (Boolean)proxy.retrieveAttributeValue("started"); + public boolean isStarted() { + return (Boolean) proxy.retrieveAttributeValue("started"); } - public void start() throws Exception - { + public void start() throws Exception { proxy.invokeOperation("start"); } - public void stop() throws Exception - { + public void stop() throws Exception { proxy.invokeOperation("stop"); } @@ -93,8 +84,7 @@ public class AcceptorControlUsingCoreTest extends AcceptorControlTest @Override @Test - public void testStartStop() throws Exception - { + public void testStartStop() throws Exception { // this test does not make sense when using core messages: // the acceptor must be started to receive the management messages } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ActiveMQServerControlTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ActiveMQServerControlTest.java index 22c96283bb..a3c65f489b 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ActiveMQServerControlTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ActiveMQServerControlTest.java @@ -53,8 +53,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class ActiveMQServerControlTest extends ManagementTestBase -{ +public class ActiveMQServerControlTest extends ManagementTestBase { // Constants ----------------------------------------------------- @@ -68,13 +67,10 @@ public class ActiveMQServerControlTest extends ManagementTestBase // Static -------------------------------------------------------- - private static boolean contains(final String name, final String[] strings) - { + private static boolean contains(final String name, final String[] strings) { boolean found = false; - for (String str : strings) - { - if (name.equals(str)) - { + for (String str : strings) { + if (name.equals(str)) { found = true; break; } @@ -87,15 +83,13 @@ public class ActiveMQServerControlTest extends ManagementTestBase // Public -------------------------------------------------------- @Test - public void testGetAttributes() throws Exception - { + public void testGetAttributes() throws Exception { ActiveMQServerControl serverControl = createManagementControl(); Assert.assertEquals(server.getVersion().getFullVersion(), serverControl.getVersion()); Assert.assertEquals(conf.isClustered(), serverControl.isClustered()); - Assert.assertEquals(conf.isPersistDeliveryCountBeforeDelivery(), - serverControl.isPersistDeliveryCountBeforeDelivery()); + Assert.assertEquals(conf.isPersistDeliveryCountBeforeDelivery(), serverControl.isPersistDeliveryCountBeforeDelivery()); Assert.assertEquals(conf.getScheduledThreadPoolMaxSize(), serverControl.getScheduledThreadPoolMaxSize()); Assert.assertEquals(conf.getThreadPoolMaxSize(), serverControl.getThreadPoolMaxSize()); Assert.assertEquals(conf.getSecurityInvalidationInterval(), serverControl.getSecurityInvalidationInterval()); @@ -107,8 +101,7 @@ public class ActiveMQServerControlTest extends ManagementTestBase Assert.assertEquals(conf.getConnectionTTLOverride(), serverControl.getConnectionTTLOverride()); //Assert.assertEquals(conf.getBackupConnectorName(), serverControl.getBackupConnectorName()); Assert.assertEquals(conf.getManagementAddress().toString(), serverControl.getManagementAddress()); - Assert.assertEquals(conf.getManagementNotificationAddress().toString(), - serverControl.getManagementNotificationAddress()); + Assert.assertEquals(conf.getManagementNotificationAddress().toString(), serverControl.getManagementNotificationAddress()); Assert.assertEquals(conf.getIDCacheSize(), serverControl.getIDCacheSize()); Assert.assertEquals(conf.isPersistIDCache(), serverControl.isPersistIDCache()); Assert.assertEquals(conf.getBindingsDirectory(), serverControl.getBindingsDirectory()); @@ -118,8 +111,7 @@ public class ActiveMQServerControlTest extends ManagementTestBase Assert.assertEquals(conf.isJournalSyncNonTransactional(), serverControl.isJournalSyncNonTransactional()); Assert.assertEquals(conf.getJournalFileSize(), serverControl.getJournalFileSize()); Assert.assertEquals(conf.getJournalMinFiles(), serverControl.getJournalMinFiles()); - if (LibaioContext.isLoaded()) - { + if (LibaioContext.isLoaded()) { Assert.assertEquals(conf.getJournalMaxIO_AIO(), serverControl.getJournalMaxIO()); Assert.assertEquals(conf.getJournalBufferSize_AIO(), serverControl.getJournalBufferSize()); Assert.assertEquals(conf.getJournalBufferTimeout_AIO(), serverControl.getJournalBufferTimeout()); @@ -140,8 +132,7 @@ public class ActiveMQServerControlTest extends ManagementTestBase } @Test - public void testGetConnectors() throws Exception - { + public void testGetConnectors() throws Exception { ActiveMQServerControl serverControl = createManagementControl(); Object[] connectorData = serverControl.getConnectors(); @@ -154,8 +145,7 @@ public class ActiveMQServerControlTest extends ManagementTestBase } @Test - public void testGetConnectorsAsJSON() throws Exception - { + public void testGetConnectorsAsJSON() throws Exception { ActiveMQServerControl serverControl = createManagementControl(); String jsonString = serverControl.getConnectorsAsJSON(); @@ -169,8 +159,7 @@ public class ActiveMQServerControlTest extends ManagementTestBase } @Test - public void testCreateAndDestroyQueue() throws Exception - { + public void testCreateAndDestroyQueue() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString name = RandomUtil.randomSimpleString(); @@ -194,8 +183,7 @@ public class ActiveMQServerControlTest extends ManagementTestBase } @Test - public void testCreateAndDestroyQueue_2() throws Exception - { + public void testCreateAndDestroyQueue_2() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString name = RandomUtil.randomSimpleString(); String filter = "color = 'green'"; @@ -221,8 +209,7 @@ public class ActiveMQServerControlTest extends ManagementTestBase } @Test - public void testCreateAndDestroyQueue_3() throws Exception - { + public void testCreateAndDestroyQueue_3() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString name = RandomUtil.randomSimpleString(); boolean durable = true; @@ -247,8 +234,7 @@ public class ActiveMQServerControlTest extends ManagementTestBase } @Test - public void testCreateAndDestroyQueueWithNullFilter() throws Exception - { + public void testCreateAndDestroyQueueWithNullFilter() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString name = RandomUtil.randomSimpleString(); String filter = null; @@ -274,8 +260,7 @@ public class ActiveMQServerControlTest extends ManagementTestBase } @Test - public void testCreateAndDestroyQueueWithEmptyStringForFilter() throws Exception - { + public void testCreateAndDestroyQueueWithEmptyStringForFilter() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString name = RandomUtil.randomSimpleString(); String filter = ""; @@ -301,8 +286,7 @@ public class ActiveMQServerControlTest extends ManagementTestBase } @Test - public void testGetQueueNames() throws Exception - { + public void testGetQueueNames() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString name = RandomUtil.randomSimpleString(); @@ -321,8 +305,7 @@ public class ActiveMQServerControlTest extends ManagementTestBase } @Test - public void testGetAddressNames() throws Exception - { + public void testGetAddressNames() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString name = RandomUtil.randomSimpleString(); @@ -341,8 +324,7 @@ public class ActiveMQServerControlTest extends ManagementTestBase } @Test - public void testMessageCounterMaxDayCount() throws Exception - { + public void testMessageCounterMaxDayCount() throws Exception { ActiveMQServerControl serverControl = createManagementControl(); Assert.assertEquals(MessageCounterManagerImpl.DEFAULT_MAX_DAY_COUNT, serverControl.getMessageCounterMaxDayCount()); @@ -352,79 +334,65 @@ public class ActiveMQServerControlTest extends ManagementTestBase Assert.assertEquals(newCount, serverControl.getMessageCounterMaxDayCount()); - try - { + try { serverControl.setMessageCounterMaxDayCount(-1); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { } - try - { + try { serverControl.setMessageCounterMaxDayCount(0); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { } Assert.assertEquals(newCount, serverControl.getMessageCounterMaxDayCount()); } @Test - public void testGetMessageCounterSamplePeriod() throws Exception - { + public void testGetMessageCounterSamplePeriod() throws Exception { ActiveMQServerControl serverControl = createManagementControl(); - Assert.assertEquals(MessageCounterManagerImpl.DEFAULT_SAMPLE_PERIOD, - serverControl.getMessageCounterSamplePeriod()); + Assert.assertEquals(MessageCounterManagerImpl.DEFAULT_SAMPLE_PERIOD, serverControl.getMessageCounterSamplePeriod()); long newSample = 20000; serverControl.setMessageCounterSamplePeriod(newSample); Assert.assertEquals(newSample, serverControl.getMessageCounterSamplePeriod()); - try - { + try { serverControl.setMessageCounterSamplePeriod(-1); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { } - try - { + try { serverControl.setMessageCounterSamplePeriod(0); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { } - try - { + try { serverControl.setMessageCounterSamplePeriod(MessageCounterManagerImpl.MIN_SAMPLE_PERIOD - 1); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { } Assert.assertEquals(newSample, serverControl.getMessageCounterSamplePeriod()); } - protected void restartServer() throws Exception - { + protected void restartServer() throws Exception { server.stop(); server.start(); } @Test - public void testSecuritySettings() throws Exception - { + public void testSecuritySettings() throws Exception { ActiveMQServerControl serverControl = createManagementControl(); String addressMatch = "test.#"; String exactAddress = "test.whatever"; @@ -443,13 +411,11 @@ public class ActiveMQServerControlTest extends ManagementTestBase assertEquals(2, roleInfos.length); RoleInfo fooRole = null; RoleInfo barRole = null; - if (roleInfos[0].getName().equals("foo")) - { + if (roleInfos[0].getName().equals("foo")) { fooRole = roleInfos[0]; barRole = roleInfos[1]; } - else - { + else { fooRole = roleInfos[1]; barRole = roleInfos[0]; } @@ -474,8 +440,7 @@ public class ActiveMQServerControlTest extends ManagementTestBase } @Test - public void testAddressSettings() throws Exception - { + public void testAddressSettings() throws Exception { ActiveMQServerControl serverControl = createManagementControl(); String addressMatch = "test.#"; String exactAddress = "test.whatever"; @@ -500,54 +465,13 @@ public class ActiveMQServerControlTest extends ManagementTestBase boolean autoCreateJmsQueues = false; boolean autoDeleteJmsQueues = false; - serverControl.addAddressSettings(addressMatch, - DLA, - expiryAddress, - expiryDelay, - lastValueQueue, - deliveryAttempts, - maxSizeBytes, - pageSizeBytes, - pageMaxCacheSize, - redeliveryDelay, - redeliveryMultiplier, - maxRedeliveryDelay, - redistributionDelay, - sendToDLAOnNoRoute, - addressFullMessagePolicy, - slowConsumerThreshold, - slowConsumerCheckPeriod, - slowConsumerPolicy, - autoCreateJmsQueues, - autoDeleteJmsQueues); - + serverControl.addAddressSettings(addressMatch, DLA, expiryAddress, expiryDelay, lastValueQueue, deliveryAttempts, maxSizeBytes, pageSizeBytes, pageMaxCacheSize, redeliveryDelay, redeliveryMultiplier, maxRedeliveryDelay, redistributionDelay, sendToDLAOnNoRoute, addressFullMessagePolicy, slowConsumerThreshold, slowConsumerCheckPeriod, slowConsumerPolicy, autoCreateJmsQueues, autoDeleteJmsQueues); boolean ex = false; - try - { - serverControl.addAddressSettings(addressMatch, - DLA, - expiryAddress, - expiryDelay, - lastValueQueue, - deliveryAttempts, - 100, - 1000, - pageMaxCacheSize, - redeliveryDelay, - redeliveryMultiplier, - maxRedeliveryDelay, - redistributionDelay, - sendToDLAOnNoRoute, - addressFullMessagePolicy, - slowConsumerThreshold, - slowConsumerCheckPeriod, - slowConsumerPolicy, - autoCreateJmsQueues, - autoDeleteJmsQueues); + try { + serverControl.addAddressSettings(addressMatch, DLA, expiryAddress, expiryDelay, lastValueQueue, deliveryAttempts, 100, 1000, pageMaxCacheSize, redeliveryDelay, redeliveryMultiplier, maxRedeliveryDelay, redistributionDelay, sendToDLAOnNoRoute, addressFullMessagePolicy, slowConsumerThreshold, slowConsumerCheckPeriod, slowConsumerPolicy, autoCreateJmsQueues, autoDeleteJmsQueues); } - catch (Exception expected) - { + catch (Exception expected) { ex = true; } @@ -577,27 +501,7 @@ public class ActiveMQServerControlTest extends ManagementTestBase assertEquals(autoCreateJmsQueues, info.isAutoCreateJmsQueues()); assertEquals(autoDeleteJmsQueues, info.isAutoDeleteJmsQueues()); - serverControl.addAddressSettings(addressMatch, - DLA, - expiryAddress, - expiryDelay, - lastValueQueue, - deliveryAttempts, - -1, - 1000, - pageMaxCacheSize, - redeliveryDelay, - redeliveryMultiplier, - maxRedeliveryDelay, - redistributionDelay, - sendToDLAOnNoRoute, - addressFullMessagePolicy, - slowConsumerThreshold, - slowConsumerCheckPeriod, - slowConsumerPolicy, - autoCreateJmsQueues, - autoDeleteJmsQueues); - + serverControl.addAddressSettings(addressMatch, DLA, expiryAddress, expiryDelay, lastValueQueue, deliveryAttempts, -1, 1000, pageMaxCacheSize, redeliveryDelay, redeliveryMultiplier, maxRedeliveryDelay, redistributionDelay, sendToDLAOnNoRoute, addressFullMessagePolicy, slowConsumerThreshold, slowConsumerCheckPeriod, slowConsumerPolicy, autoCreateJmsQueues, autoDeleteJmsQueues); jsonString = serverControl.getAddressSettingsAsJSON(exactAddress); info = AddressSettingsInfo.from(jsonString); @@ -621,45 +525,20 @@ public class ActiveMQServerControlTest extends ManagementTestBase assertEquals(autoCreateJmsQueues, info.isAutoCreateJmsQueues()); assertEquals(autoDeleteJmsQueues, info.isAutoDeleteJmsQueues()); - ex = false; - try - { - serverControl.addAddressSettings(addressMatch, - DLA, - expiryAddress, - expiryDelay, - lastValueQueue, - deliveryAttempts, - -2, - 1000, - pageMaxCacheSize, - redeliveryDelay, - redeliveryMultiplier, - maxRedeliveryDelay, - redistributionDelay, - sendToDLAOnNoRoute, - addressFullMessagePolicy, - slowConsumerThreshold, - slowConsumerCheckPeriod, - slowConsumerPolicy, - autoCreateJmsQueues, - autoDeleteJmsQueues); + try { + serverControl.addAddressSettings(addressMatch, DLA, expiryAddress, expiryDelay, lastValueQueue, deliveryAttempts, -2, 1000, pageMaxCacheSize, redeliveryDelay, redeliveryMultiplier, maxRedeliveryDelay, redistributionDelay, sendToDLAOnNoRoute, addressFullMessagePolicy, slowConsumerThreshold, slowConsumerCheckPeriod, slowConsumerPolicy, autoCreateJmsQueues, autoDeleteJmsQueues); } - catch (Exception e) - { + catch (Exception e) { ex = true; } - assertTrue("Supposed to have an exception called", ex); - } @Test - public void testNullRouteNameOnDivert() throws Exception - { + public void testNullRouteNameOnDivert() throws Exception { String address = RandomUtil.randomString(); String name = RandomUtil.randomString(); String forwardingAddress = RandomUtil.randomString(); @@ -675,8 +554,7 @@ public class ActiveMQServerControlTest extends ManagementTestBase } @Test - public void testCreateAndDestroyDivert() throws Exception - { + public void testCreateAndDestroyDivert() throws Exception { String address = RandomUtil.randomString(); String name = RandomUtil.randomString(); String routingName = RandomUtil.randomString(); @@ -756,8 +634,7 @@ public class ActiveMQServerControlTest extends ManagementTestBase } @Test - public void testCreateAndDestroyBridge() throws Exception - { + public void testCreateAndDestroyBridge() throws Exception { String name = RandomUtil.randomString(); String sourceAddress = RandomUtil.randomString(); String sourceQueue = RandomUtil.randomString(); @@ -776,23 +653,12 @@ public class ActiveMQServerControlTest extends ManagementTestBase session.createQueue(sourceAddress, sourceQueue); session.createQueue(targetAddress, targetQueue); - serverControl.createBridge(name, - sourceQueue, - targetAddress, - null, // forwardingAddress + serverControl.createBridge(name, sourceQueue, targetAddress, null, // forwardingAddress null, // filterString - ActiveMQClient.DEFAULT_RETRY_INTERVAL, - ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, - ActiveMQClient.INITIAL_CONNECT_ATTEMPTS, - ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS, - false, // duplicateDetection + ActiveMQClient.DEFAULT_RETRY_INTERVAL, ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, ActiveMQClient.INITIAL_CONNECT_ATTEMPTS, ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS, false, // duplicateDetection 1, // confirmationWindowSize - ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, - connectorConfig.getName(), // liveConnector - false, - false, - null, - null); + ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, connectorConfig.getName(), // liveConnector + false, false, null, null); checkResource(ObjectNameBuilder.DEFAULT.getBridgeObjectName(name)); String[] bridgeNames = serverControl.getBridgeNames(); @@ -848,8 +714,7 @@ public class ActiveMQServerControlTest extends ManagementTestBase } @Test - public void testListPreparedTransactionDetails() throws Exception - { + public void testListPreparedTransactionDetails() throws Exception { SimpleString atestq = new SimpleString("BasicXaTestq"); Xid xid = newXID(); @@ -894,8 +759,7 @@ public class ActiveMQServerControlTest extends ManagementTestBase } @Test - public void testListPreparedTransactionDetailsAsHTML() throws Exception - { + public void testListPreparedTransactionDetailsAsHTML() throws Exception { SimpleString atestq = new SimpleString("BasicXaTestq"); Xid xid = newXID(); @@ -934,8 +798,7 @@ public class ActiveMQServerControlTest extends ManagementTestBase } @Test - public void testCommitPreparedTransactions() throws Exception - { + public void testCommitPreparedTransactions() throws Exception { SimpleString recQueue = new SimpleString("BasicXaTestqRec"); SimpleString sendQueue = new SimpleString("BasicXaTestqSend"); @@ -953,13 +816,11 @@ public class ActiveMQServerControlTest extends ManagementTestBase clientProducer.send(m1); locator.close(); - ServerLocator receiveLocator = createInVMNonHALocator(); ClientSessionFactory receiveCsf = createSessionFactory(receiveLocator); ClientSession receiveClientSession = receiveCsf.createSession(true, false, false); ClientConsumer consumer = receiveClientSession.createConsumer(recQueue); - ServerLocator sendLocator = createInVMNonHALocator(); ClientSessionFactory sendCsf = createSessionFactory(sendLocator); ClientSession sendClientSession = sendCsf.createSession(true, false, false); @@ -974,7 +835,6 @@ public class ActiveMQServerControlTest extends ManagementTestBase producer.send(m); - receiveClientSession.end(xid, XAResource.TMSUCCESS); sendClientSession.end(xid2, XAResource.TMSUCCESS); @@ -994,52 +854,40 @@ public class ActiveMQServerControlTest extends ManagementTestBase } @Test - public void testScaleDownWithConnector() throws Exception - { - scaleDown(new ScaleDownHandler() - { + public void testScaleDownWithConnector() throws Exception { + scaleDown(new ScaleDownHandler() { @Override - public void scaleDown(ActiveMQServerControl control) throws Exception - { + public void scaleDown(ActiveMQServerControl control) throws Exception { control.scaleDown("server2-connector"); } }); } @Test - public void testScaleDownWithOutConnector() throws Exception - { - scaleDown(new ScaleDownHandler() - { + public void testScaleDownWithOutConnector() throws Exception { + scaleDown(new ScaleDownHandler() { @Override - public void scaleDown(ActiveMQServerControl control) throws Exception - { + public void scaleDown(ActiveMQServerControl control) throws Exception { control.scaleDown(null); } }); } @Test - public void testForceFailover() throws Exception - { + public void testForceFailover() throws Exception { ActiveMQServerControl serverControl = createManagementControl(); serverControl.forceFailover(); assertFalse(server.isStarted()); } - protected void scaleDown(ScaleDownHandler handler) throws Exception - { + protected void scaleDown(ScaleDownHandler handler) throws Exception { SimpleString address = new SimpleString("testQueue"); HashMap params = new HashMap<>(); params.put(TransportConstants.SERVER_ID_PROP_NAME, "2"); - Configuration config = createDefaultInVMConfig(2) - .clearAcceptorConfigurations() - .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName(), params)); + Configuration config = createDefaultInVMConfig(2).clearAcceptorConfigurations().addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName(), params)); ActiveMQServer server2 = addServer(ActiveMQServers.newActiveMQServer(config, null, true)); - this.conf - .clearConnectorConfigurations() - .addConnectorConfiguration("server2-connector", new TransportConfiguration(INVM_CONNECTOR_FACTORY, params)); + this.conf.clearConnectorConfigurations().addConnectorConfiguration("server2-connector", new TransportConfiguration(INVM_CONNECTOR_FACTORY, params)); server2.start(); server.createQueue(address, address, null, true, false); @@ -1048,8 +896,7 @@ public class ActiveMQServerControlTest extends ManagementTestBase ClientSessionFactory csf = createSessionFactory(locator); ClientSession session = csf.createSession(); ClientProducer producer = session.createProducer(address); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage message = session.createMessage(true); message.getBodyBuffer().writeString("m" + i); producer.send(message); @@ -1063,36 +910,32 @@ public class ActiveMQServerControlTest extends ManagementTestBase session = csf.createSession(); session.start(); ClientConsumer consumer = session.createConsumer(address); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage m = consumer.receive(5000); assertNotNull(m); } } + // Package protected --------------------------------------------- - interface ScaleDownHandler - { + interface ScaleDownHandler { + void scaleDown(ActiveMQServerControl control) throws Exception; } // Protected ----------------------------------------------------- @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); connectorConfig = new TransportConfiguration(INVM_CONNECTOR_FACTORY); - conf = createDefaultInVMConfig() - .setJMXManagementEnabled(true) - .addConnectorConfiguration(connectorConfig.getName(), connectorConfig); + conf = createDefaultInVMConfig().setJMXManagementEnabled(true).addConnectorConfiguration(connectorConfig.getName(), connectorConfig); server = addServer(ActiveMQServers.newActiveMQServer(conf, mbeanServer, true)); server.start(); } - protected ActiveMQServerControl createManagementControl() throws Exception - { + protected ActiveMQServerControl createManagementControl() throws Exception { return ManagementControlHelper.createActiveMQServerControl(mbeanServer); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ActiveMQServerControlUsingCoreTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ActiveMQServerControlUsingCoreTest.java index 2d6f0ab4dd..a7a5181eda 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ActiveMQServerControlUsingCoreTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ActiveMQServerControlUsingCoreTest.java @@ -24,8 +24,7 @@ import org.apache.activemq.artemis.api.core.management.Parameter; import org.apache.activemq.artemis.api.core.management.ResourceNames; import org.junit.Before; -public class ActiveMQServerControlUsingCoreTest extends ActiveMQServerControlTest -{ +public class ActiveMQServerControlUsingCoreTest extends ActiveMQServerControlTest { // Constants ----------------------------------------------------- @@ -33,11 +32,9 @@ public class ActiveMQServerControlUsingCoreTest extends ActiveMQServerControlTes // Static -------------------------------------------------------- - private static String[] toStringArray(final Object[] res) - { + private static String[] toStringArray(final Object[] res) { String[] names = new String[res.length]; - for (int i = 0; i < res.length; i++) - { + for (int i = 0; i < res.length; i++) { names[i] = res[i].toString(); } return names; @@ -54,8 +51,7 @@ public class ActiveMQServerControlUsingCoreTest extends ActiveMQServerControlTes @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = createInVMNonHALocator(); @@ -64,8 +60,7 @@ public class ActiveMQServerControlUsingCoreTest extends ActiveMQServerControlTes session.start(); } - protected void restartServer() throws Exception - { + protected void restartServer() throws Exception { session.close(); super.restartServer(); @@ -79,431 +74,351 @@ public class ActiveMQServerControlUsingCoreTest extends ActiveMQServerControlTes // the core messaging proxy doesn't work when the server is stopped so we cant run these 2 tests @Override - public void testScaleDownWithOutConnector() throws Exception - { + public void testScaleDownWithOutConnector() throws Exception { } @Override - public void testScaleDownWithConnector() throws Exception - { + public void testScaleDownWithConnector() throws Exception { } @Override - protected ActiveMQServerControl createManagementControl() throws Exception - { - return new ActiveMQServerControl() - { + protected ActiveMQServerControl createManagementControl() throws Exception { + return new ActiveMQServerControl() { @Override - public void updateDuplicateIdCache(String address, Object[] ids) - { + public void updateDuplicateIdCache(String address, Object[] ids) { } @Override - public void scaleDown(String connector) throws Exception - { + public void scaleDown(String connector) throws Exception { throw new UnsupportedOperationException(); } private final CoreMessagingProxy proxy = new CoreMessagingProxy(session, ResourceNames.CORE_SERVER); - public boolean isSharedStore() - { + public boolean isSharedStore() { return (Boolean) proxy.retrieveAttributeValue("sharedStore"); } - public boolean closeConnectionsForAddress(final String ipAddress) throws Exception - { + public boolean closeConnectionsForAddress(final String ipAddress) throws Exception { return (Boolean) proxy.invokeOperation("closeConnectionsForAddress", ipAddress); } - public boolean closeConsumerConnectionsForAddress(final String address) throws Exception - { + public boolean closeConsumerConnectionsForAddress(final String address) throws Exception { return (Boolean) proxy.invokeOperation("closeConsumerConnectionsForAddress", address); } - public boolean closeConnectionsForUser(final String userName) throws Exception - { + public boolean closeConnectionsForUser(final String userName) throws Exception { return (Boolean) proxy.invokeOperation("closeConnectionsForUser", userName); } - public boolean commitPreparedTransaction(final String transactionAsBase64) throws Exception - { + public boolean commitPreparedTransaction(final String transactionAsBase64) throws Exception { return (Boolean) proxy.invokeOperation("commitPreparedTransaction", transactionAsBase64); } - public void createQueue(final String address, final String name) throws Exception - { + public void createQueue(final String address, final String name) throws Exception { proxy.invokeOperation("createQueue", address, name); } - public void createQueue(final String address, final String name, final String filter, final boolean durable) throws Exception - { + public void createQueue(final String address, + final String name, + final String filter, + final boolean durable) throws Exception { proxy.invokeOperation("createQueue", address, name, filter, durable); } - public void createQueue(final String address, final String name, final boolean durable) throws Exception - { + public void createQueue(final String address, final String name, final boolean durable) throws Exception { proxy.invokeOperation("createQueue", address, name, durable); } - public void deployQueue(final String address, final String name, final String filter, final boolean durable) throws Exception - { + public void deployQueue(final String address, + final String name, + final String filter, + final boolean durable) throws Exception { proxy.invokeOperation("deployQueue", address, name, filter, durable); } - public void deployQueue(final String address, final String name, final String filterString) throws Exception - { + public void deployQueue(final String address, final String name, final String filterString) throws Exception { proxy.invokeOperation("deployQueue", address, name); } - public void destroyQueue(final String name) throws Exception - { + public void destroyQueue(final String name) throws Exception { proxy.invokeOperation("destroyQueue", name); } - public void disableMessageCounters() throws Exception - { + public void disableMessageCounters() throws Exception { proxy.invokeOperation("disableMessageCounters"); } - public void enableMessageCounters() throws Exception - { + public void enableMessageCounters() throws Exception { proxy.invokeOperation("enableMessageCounters"); } - public String getBindingsDirectory() - { + public String getBindingsDirectory() { return (String) proxy.retrieveAttributeValue("bindingsDirectory"); } - public int getConnectionCount() - { + public int getConnectionCount() { return (Integer) proxy.retrieveAttributeValue("connectionCount"); } - public long getConnectionTTLOverride() - { + public long getConnectionTTLOverride() { return (Long) proxy.retrieveAttributeValue("connectionTTLOverride", Long.class); } - public Object[] getConnectors() throws Exception - { + public Object[] getConnectors() throws Exception { return (Object[]) proxy.retrieveAttributeValue("connectors"); } - public String getConnectorsAsJSON() throws Exception - { + public String getConnectorsAsJSON() throws Exception { return (String) proxy.retrieveAttributeValue("connectorsAsJSON"); } - public String[] getAddressNames() - { + public String[] getAddressNames() { return ActiveMQServerControlUsingCoreTest.toStringArray((Object[]) proxy.retrieveAttributeValue("addressNames")); } - public String[] getQueueNames() - { + public String[] getQueueNames() { return ActiveMQServerControlUsingCoreTest.toStringArray((Object[]) proxy.retrieveAttributeValue("queueNames")); } - public int getIDCacheSize() - { + public int getIDCacheSize() { return (Integer) proxy.retrieveAttributeValue("IDCacheSize"); } - public String[] getInterceptorClassNames() - { + public String[] getInterceptorClassNames() { return ActiveMQServerControlUsingCoreTest.toStringArray((Object[]) proxy.retrieveAttributeValue("incomingInterceptorClassNames")); } - public String[] getIncomingInterceptorClassNames() - { + public String[] getIncomingInterceptorClassNames() { return ActiveMQServerControlUsingCoreTest.toStringArray((Object[]) proxy.retrieveAttributeValue("incomingInterceptorClassNames")); } - public String[] getOutgoingInterceptorClassNames() - { + public String[] getOutgoingInterceptorClassNames() { return ActiveMQServerControlUsingCoreTest.toStringArray((Object[]) proxy.retrieveAttributeValue("outgoingInterceptorClassNames")); } - public String getJournalDirectory() - { + public String getJournalDirectory() { return (String) proxy.retrieveAttributeValue("journalDirectory"); } - public int getJournalFileSize() - { + public int getJournalFileSize() { return (Integer) proxy.retrieveAttributeValue("journalFileSize"); } - public int getJournalMaxIO() - { + public int getJournalMaxIO() { return (Integer) proxy.retrieveAttributeValue("journalMaxIO"); } - public int getJournalMinFiles() - { + public int getJournalMinFiles() { return (Integer) proxy.retrieveAttributeValue("journalMinFiles"); } - public String getJournalType() - { + public String getJournalType() { return (String) proxy.retrieveAttributeValue("journalType"); } - public String getLargeMessagesDirectory() - { + public String getLargeMessagesDirectory() { return (String) proxy.retrieveAttributeValue("largeMessagesDirectory"); } - public String getManagementAddress() - { + public String getManagementAddress() { return (String) proxy.retrieveAttributeValue("managementAddress"); } - public String getManagementNotificationAddress() - { + public String getManagementNotificationAddress() { return (String) proxy.retrieveAttributeValue("managementNotificationAddress"); } - public int getMessageCounterMaxDayCount() - { + public int getMessageCounterMaxDayCount() { return (Integer) proxy.retrieveAttributeValue("messageCounterMaxDayCount"); } - public long getMessageCounterSamplePeriod() - { + public long getMessageCounterSamplePeriod() { return (Long) proxy.retrieveAttributeValue("messageCounterSamplePeriod", Long.class); } - public long getMessageExpiryScanPeriod() - { + public long getMessageExpiryScanPeriod() { return (Long) proxy.retrieveAttributeValue("messageExpiryScanPeriod", Long.class); } - public long getMessageExpiryThreadPriority() - { + public long getMessageExpiryThreadPriority() { return (Long) proxy.retrieveAttributeValue("messageExpiryThreadPriority", Long.class); } - public String getPagingDirectory() - { + public String getPagingDirectory() { return (String) proxy.retrieveAttributeValue("pagingDirectory"); } - public int getScheduledThreadPoolMaxSize() - { + public int getScheduledThreadPoolMaxSize() { return (Integer) proxy.retrieveAttributeValue("scheduledThreadPoolMaxSize"); } - public int getThreadPoolMaxSize() - { + public int getThreadPoolMaxSize() { return (Integer) proxy.retrieveAttributeValue("threadPoolMaxSize"); } - public long getSecurityInvalidationInterval() - { + public long getSecurityInvalidationInterval() { return (Long) proxy.retrieveAttributeValue("securityInvalidationInterval", Long.class); } - public long getTransactionTimeout() - { + public long getTransactionTimeout() { return (Long) proxy.retrieveAttributeValue("transactionTimeout", Long.class); } - public long getTransactionTimeoutScanPeriod() - { + public long getTransactionTimeoutScanPeriod() { return (Long) proxy.retrieveAttributeValue("transactionTimeoutScanPeriod", Long.class); } - public String getVersion() - { + public String getVersion() { return (String) proxy.retrieveAttributeValue("version"); } - public boolean isBackup() - { + public boolean isBackup() { return (Boolean) proxy.retrieveAttributeValue("backup"); } - public boolean isClustered() - { + public boolean isClustered() { return (Boolean) proxy.retrieveAttributeValue("clustered"); } - public boolean isCreateBindingsDir() - { + public boolean isCreateBindingsDir() { return (Boolean) proxy.retrieveAttributeValue("createBindingsDir"); } - public boolean isCreateJournalDir() - { + public boolean isCreateJournalDir() { return (Boolean) proxy.retrieveAttributeValue("createJournalDir"); } - public boolean isJournalSyncNonTransactional() - { + public boolean isJournalSyncNonTransactional() { return (Boolean) proxy.retrieveAttributeValue("journalSyncNonTransactional"); } - public boolean isJournalSyncTransactional() - { + public boolean isJournalSyncTransactional() { return (Boolean) proxy.retrieveAttributeValue("journalSyncTransactional"); } - public void setFailoverOnServerShutdown(boolean failoverOnServerShutdown) throws Exception - { + public void setFailoverOnServerShutdown(boolean failoverOnServerShutdown) throws Exception { proxy.invokeOperation("setFailoverOnServerShutdown", failoverOnServerShutdown); } - public boolean isFailoverOnServerShutdown() - { + public boolean isFailoverOnServerShutdown() { return (Boolean) proxy.retrieveAttributeValue("failoverOnServerShutdown"); } - public void setScaleDown(boolean scaleDown) throws Exception - { + public void setScaleDown(boolean scaleDown) throws Exception { proxy.invokeOperation("setEnabled", scaleDown); } - public boolean isScaleDown() - { + public boolean isScaleDown() { return (Boolean) proxy.retrieveAttributeValue("scaleDown"); } - public boolean isMessageCounterEnabled() - { + public boolean isMessageCounterEnabled() { return (Boolean) proxy.retrieveAttributeValue("messageCounterEnabled"); } - public boolean isPersistDeliveryCountBeforeDelivery() - { + public boolean isPersistDeliveryCountBeforeDelivery() { return (Boolean) proxy.retrieveAttributeValue("persistDeliveryCountBeforeDelivery"); } - public boolean isAsyncConnectionExecutionEnabled() - { + public boolean isAsyncConnectionExecutionEnabled() { return (Boolean) proxy.retrieveAttributeValue("asyncConnectionExecutionEnabled"); } - public boolean isPersistIDCache() - { + public boolean isPersistIDCache() { return (Boolean) proxy.retrieveAttributeValue("persistIDCache"); } - public boolean isSecurityEnabled() - { + public boolean isSecurityEnabled() { return (Boolean) proxy.retrieveAttributeValue("securityEnabled"); } - public boolean isStarted() - { + public boolean isStarted() { return (Boolean) proxy.retrieveAttributeValue("started"); } - public boolean isWildcardRoutingEnabled() - { + public boolean isWildcardRoutingEnabled() { return (Boolean) proxy.retrieveAttributeValue("wildcardRoutingEnabled"); } - public String[] listConnectionIDs() throws Exception - { + public String[] listConnectionIDs() throws Exception { return (String[]) proxy.invokeOperation("listConnectionIDs"); } - public String[] listPreparedTransactions() throws Exception - { + public String[] listPreparedTransactions() throws Exception { return (String[]) proxy.invokeOperation("listPreparedTransactions"); } - public String listPreparedTransactionDetailsAsJSON() throws Exception - { + public String listPreparedTransactionDetailsAsJSON() throws Exception { return (String) proxy.invokeOperation("listPreparedTransactionDetailsAsJSON"); } - public String listPreparedTransactionDetailsAsHTML() throws Exception - { + public String listPreparedTransactionDetailsAsHTML() throws Exception { return (String) proxy.invokeOperation("listPreparedTransactionDetailsAsHTML"); } - public String[] listHeuristicCommittedTransactions() throws Exception - { + public String[] listHeuristicCommittedTransactions() throws Exception { return (String[]) proxy.invokeOperation("listHeuristicCommittedTransactions"); } - public String[] listHeuristicRolledBackTransactions() throws Exception - { + public String[] listHeuristicRolledBackTransactions() throws Exception { return (String[]) proxy.invokeOperation("listHeuristicRolledBackTransactions"); } - public String[] listRemoteAddresses() throws Exception - { + public String[] listRemoteAddresses() throws Exception { return (String[]) proxy.invokeOperation("listRemoteAddresses"); } - public String[] listRemoteAddresses(final String ipAddress) throws Exception - { + public String[] listRemoteAddresses(final String ipAddress) throws Exception { return (String[]) proxy.invokeOperation("listRemoteAddresses", ipAddress); } - public String[] listSessions(final String connectionID) throws Exception - { + public String[] listSessions(final String connectionID) throws Exception { return (String[]) proxy.invokeOperation("listSessions", connectionID); } - public void resetAllMessageCounterHistories() throws Exception - { + public void resetAllMessageCounterHistories() throws Exception { proxy.invokeOperation("resetAllMessageCounterHistories"); } - public void resetAllMessageCounters() throws Exception - { + public void resetAllMessageCounters() throws Exception { proxy.invokeOperation("resetAllMessageCounters"); } - public boolean rollbackPreparedTransaction(final String transactionAsBase64) throws Exception - { + public boolean rollbackPreparedTransaction(final String transactionAsBase64) throws Exception { return (Boolean) proxy.invokeOperation("rollbackPreparedTransaction", transactionAsBase64); } - public void sendQueueInfoToQueue(final String queueName, final String address) throws Exception - { + public void sendQueueInfoToQueue(final String queueName, final String address) throws Exception { proxy.invokeOperation("sendQueueInfoToQueue", queueName, address); } - public void setMessageCounterMaxDayCount(final int count) throws Exception - { + public void setMessageCounterMaxDayCount(final int count) throws Exception { proxy.invokeOperation("setMessageCounterMaxDayCount", count); } - public void setMessageCounterSamplePeriod(final long newPeriod) throws Exception - { + public void setMessageCounterSamplePeriod(final long newPeriod) throws Exception { proxy.invokeOperation("setMessageCounterSamplePeriod", newPeriod); } - public int getJournalBufferSize() - { + public int getJournalBufferSize() { return (Integer) proxy.retrieveAttributeValue("JournalBufferSize"); } - public int getJournalBufferTimeout() - { + public int getJournalBufferTimeout() { return (Integer) proxy.retrieveAttributeValue("JournalBufferTimeout"); } - public int getJournalCompactMinFiles() - { + public int getJournalCompactMinFiles() { return (Integer) proxy.retrieveAttributeValue("JournalCompactMinFiles"); } - public int getJournalCompactPercentage() - { + public int getJournalCompactPercentage() { return (Integer) proxy.retrieveAttributeValue("JournalCompactPercentage"); } - public boolean isPersistenceEnabled() - { + public boolean isPersistenceEnabled() { return (Boolean) proxy.retrieveAttributeValue("PersistenceEnabled"); } @@ -514,31 +429,19 @@ public class ActiveMQServerControlUsingCoreTest extends ActiveMQServerControlTes String deleteDurableQueueRoles, String createNonDurableQueueRoles, String deleteNonDurableQueueRoles, - String manageRoles) throws Exception - { - proxy.invokeOperation("addSecuritySettings", - addressMatch, - sendRoles, - consumeRoles, - createDurableQueueRoles, - deleteDurableQueueRoles, - createNonDurableQueueRoles, - deleteNonDurableQueueRoles, - manageRoles); + String manageRoles) throws Exception { + proxy.invokeOperation("addSecuritySettings", addressMatch, sendRoles, consumeRoles, createDurableQueueRoles, deleteDurableQueueRoles, createNonDurableQueueRoles, deleteNonDurableQueueRoles, manageRoles); } - public void removeSecuritySettings(String addressMatch) throws Exception - { + public void removeSecuritySettings(String addressMatch) throws Exception { proxy.invokeOperation("removeSecuritySettings", addressMatch); } - public Object[] getRoles(String addressMatch) throws Exception - { + public Object[] getRoles(String addressMatch) throws Exception { return (Object[]) proxy.invokeOperation("getRoles", addressMatch); } - public String getRolesAsJSON(String addressMatch) throws Exception - { + public String getRolesAsJSON(String addressMatch) throws Exception { return (String) proxy.invokeOperation("getRolesAsJSON", addressMatch); } @@ -561,33 +464,11 @@ public class ActiveMQServerControlUsingCoreTest extends ActiveMQServerControlTes @Parameter(desc = "how often (in seconds) to check for slow consumers", name = "slowConsumerCheckPeriod") long slowConsumerCheckPeriod, @Parameter(desc = "the policy to use when a slow consumer is detected", name = "slowConsumerPolicy") String slowConsumerPolicy, @Parameter(desc = "allow queues to be created automatically", name = "autoCreateJmsQueues") boolean autoCreateJmsQueues, - @Parameter(desc = "allow auto-created queues to be deleted automatically", name = "autoDeleteJmsQueues") boolean autoDeleteJmsQueues) throws Exception - { - proxy.invokeOperation("addAddressSettings", - addressMatch, - DLA, - expiryAddress, - expiryDelay, - lastValueQueue, - deliveryAttempts, - maxSizeBytes, - pageSizeBytes, - pageMaxCacheSize, - redeliveryDelay, - redeliveryMultiplier, - maxRedeliveryDelay, - redistributionDelay, - sendToDLAOnNoRoute, - addressFullMessagePolicy, - slowConsumerThreshold, - slowConsumerCheckPeriod, - slowConsumerPolicy, - autoCreateJmsQueues, - autoDeleteJmsQueues); + @Parameter(desc = "allow auto-created queues to be deleted automatically", name = "autoDeleteJmsQueues") boolean autoDeleteJmsQueues) throws Exception { + proxy.invokeOperation("addAddressSettings", addressMatch, DLA, expiryAddress, expiryDelay, lastValueQueue, deliveryAttempts, maxSizeBytes, pageSizeBytes, pageMaxCacheSize, redeliveryDelay, redeliveryMultiplier, maxRedeliveryDelay, redistributionDelay, sendToDLAOnNoRoute, addressFullMessagePolicy, slowConsumerThreshold, slowConsumerCheckPeriod, slowConsumerPolicy, autoCreateJmsQueues, autoDeleteJmsQueues); } - public void removeAddressSettings(String addressMatch) throws Exception - { + public void removeAddressSettings(String addressMatch) throws Exception { proxy.invokeOperation("removeAddressSettings", addressMatch); } @@ -597,51 +478,36 @@ public class ActiveMQServerControlUsingCoreTest extends ActiveMQServerControlTes String forwardingAddress, boolean exclusive, String filterString, - String transformerClassName) throws Exception - { - proxy.invokeOperation("createDivert", - name, - routingName, - address, - forwardingAddress, - exclusive, - filterString, - transformerClassName); + String transformerClassName) throws Exception { + proxy.invokeOperation("createDivert", name, routingName, address, forwardingAddress, exclusive, filterString, transformerClassName); } - public void destroyDivert(String name) throws Exception - { + public void destroyDivert(String name) throws Exception { proxy.invokeOperation("destroyDivert", name); } - public String[] getBridgeNames() - { + public String[] getBridgeNames() { return ActiveMQServerControlUsingCoreTest.toStringArray((Object[]) proxy.retrieveAttributeValue("bridgeNames")); } - public void destroyBridge(String name) throws Exception - { + public void destroyBridge(String name) throws Exception { proxy.invokeOperation("destroyBridge", name); } - public void forceFailover() throws Exception - { + public void forceFailover() throws Exception { proxy.invokeOperation("forceFailover"); } - public String getLiveConnectorName() throws Exception - { + public String getLiveConnectorName() throws Exception { return (String) proxy.retrieveAttributeValue("liveConnectorName"); } - public String getAddressSettingsAsJSON(String addressMatch) throws Exception - { + public String getAddressSettingsAsJSON(String addressMatch) throws Exception { return (String) proxy.invokeOperation("getAddressSettingsAsJSON", addressMatch); } - public String[] getDivertNames() - { + public String[] getDivertNames() { return ActiveMQServerControlUsingCoreTest.toStringArray((Object[]) proxy.retrieveAttributeValue("divertNames")); } @@ -661,31 +527,11 @@ public class ActiveMQServerControlUsingCoreTest extends ActiveMQServerControlTes boolean useDiscovery, boolean ha, String user, - String password) throws Exception - { - proxy.invokeOperation("createBridge", - name, - queueName, - forwardingAddress, - filterString, - transformerClassName, - retryInterval, - retryIntervalMultiplier, - initialConnectAttempts, - reconnectAttempts, - useDuplicateDetection, - confirmationWindowSize, - clientFailureCheckPeriod, - connectorNames, - useDiscovery, - ha, - user, - password); + String password) throws Exception { + proxy.invokeOperation("createBridge", name, queueName, forwardingAddress, filterString, transformerClassName, retryInterval, retryIntervalMultiplier, initialConnectAttempts, reconnectAttempts, useDuplicateDetection, confirmationWindowSize, clientFailureCheckPeriod, connectorNames, useDiscovery, ha, user, password); } - - public String listProducersInfoAsJSON() throws Exception - { + public String listProducersInfoAsJSON() throws Exception { return (String) proxy.invokeOperation("listProducersInfoAsJSON"); } }; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/AddressControlTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/AddressControlTest.java index 462e867397..0983ffa9c1 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/AddressControlTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/AddressControlTest.java @@ -41,8 +41,7 @@ import java.util.Set; import static org.apache.activemq.artemis.tests.util.RandomUtil.randomString; -public class AddressControlTest extends ManagementTestBase -{ +public class AddressControlTest extends ManagementTestBase { private ActiveMQServer server; protected ClientSession session; @@ -50,8 +49,7 @@ public class AddressControlTest extends ManagementTestBase private ClientSessionFactory sf; @Test - public void testGetAddress() throws Exception - { + public void testGetAddress() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -65,8 +63,7 @@ public class AddressControlTest extends ManagementTestBase } @Test - public void testGetQueueNames() throws Exception - { + public void testGetQueueNames() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); SimpleString anotherQueue = RandomUtil.randomSimpleString(); @@ -92,8 +89,7 @@ public class AddressControlTest extends ManagementTestBase } @Test - public void testGetBindingNames() throws Exception - { + public void testGetBindingNames() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); String divertName = RandomUtil.randomString(); @@ -118,18 +114,10 @@ public class AddressControlTest extends ManagementTestBase } @Test - public void testGetRoles() throws Exception - { + public void testGetRoles() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); - Role role = new Role(RandomUtil.randomString(), - RandomUtil.randomBoolean(), - RandomUtil.randomBoolean(), - RandomUtil.randomBoolean(), - RandomUtil.randomBoolean(), - RandomUtil.randomBoolean(), - RandomUtil.randomBoolean(), - RandomUtil.randomBoolean()); + Role role = new Role(RandomUtil.randomString(), RandomUtil.randomBoolean(), RandomUtil.randomBoolean(), RandomUtil.randomBoolean(), RandomUtil.randomBoolean(), RandomUtil.randomBoolean(), RandomUtil.randomBoolean(), RandomUtil.randomBoolean()); session.createQueue(address, queue, true); @@ -157,18 +145,10 @@ public class AddressControlTest extends ManagementTestBase } @Test - public void testGetRolesAsJSON() throws Exception - { + public void testGetRolesAsJSON() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); - Role role = new Role(RandomUtil.randomString(), - RandomUtil.randomBoolean(), - RandomUtil.randomBoolean(), - RandomUtil.randomBoolean(), - RandomUtil.randomBoolean(), - RandomUtil.randomBoolean(), - RandomUtil.randomBoolean(), - RandomUtil.randomBoolean()); + Role role = new Role(RandomUtil.randomString(), RandomUtil.randomBoolean(), RandomUtil.randomBoolean(), RandomUtil.randomBoolean(), RandomUtil.randomBoolean(), RandomUtil.randomBoolean(), RandomUtil.randomBoolean(), RandomUtil.randomBoolean()); session.createQueue(address, queue, true); @@ -200,17 +180,14 @@ public class AddressControlTest extends ManagementTestBase } @Test - public void testGetNumberOfPages() throws Exception - { + public void testGetNumberOfPages() throws Exception { session.close(); server.stop(); server.getConfiguration().setPersistenceEnabled(true); SimpleString address = RandomUtil.randomSimpleString(); - AddressSettings addressSettings = new AddressSettings() - .setPageSizeBytes(1024) - .setMaxSizeBytes(10 * 1024); + AddressSettings addressSettings = new AddressSettings().setPageSizeBytes(1024).setMaxSizeBytes(10 * 1024); final int NUMBER_MESSAGES_BEFORE_PAGING = 5; server.getAddressSettingsRepository().addMatch(address.toString(), addressSettings); @@ -227,8 +204,7 @@ public class AddressControlTest extends ManagementTestBase ClientProducer producer = session.createProducer(address); - for (int i = 0; i < NUMBER_MESSAGES_BEFORE_PAGING; i++) - { + for (int i = 0; i < NUMBER_MESSAGES_BEFORE_PAGING; i++) { ClientMessage msg = session.createMessage(true); msg.getBodyBuffer().writeBytes(new byte[512]); producer.send(msg); @@ -266,8 +242,7 @@ public class AddressControlTest extends ManagementTestBase } @Test - public void testGetNumberOfBytesPerPage() throws Exception - { + public void testGetNumberOfBytesPerPage() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); session.createQueue(address, address, true); @@ -296,26 +271,22 @@ public class AddressControlTest extends ManagementTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - Configuration config = createDefaultInVMConfig() - .setJMXManagementEnabled(true); + Configuration config = createDefaultInVMConfig().setJMXManagementEnabled(true); server = createServer(false, config); server.setMBeanServer(mbeanServer); server.start(); - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true); + locator = createInVMNonHALocator().setBlockOnNonDurableSend(true); sf = createSessionFactory(locator); session = sf.createSession(false, true, false); session.start(); addClientSession(session); } - protected AddressControl createManagementControl(final SimpleString address) throws Exception - { + protected AddressControl createManagementControl(final SimpleString address) throws Exception { return ManagementControlHelper.createAddressControl(address, mbeanServer); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/AddressControlUsingCoreTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/AddressControlUsingCoreTest.java index 96012398ca..3b415f0dd7 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/AddressControlUsingCoreTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/AddressControlUsingCoreTest.java @@ -36,8 +36,7 @@ import java.util.Set; import static org.apache.activemq.artemis.tests.util.RandomUtil.randomString; -public class AddressControlUsingCoreTest extends ManagementTestBase -{ +public class AddressControlUsingCoreTest extends ManagementTestBase { // Constants ----------------------------------------------------- @@ -54,8 +53,7 @@ public class AddressControlUsingCoreTest extends ManagementTestBase // Public -------------------------------------------------------- @Test - public void testGetAddress() throws Exception - { + public void testGetAddress() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -69,8 +67,7 @@ public class AddressControlUsingCoreTest extends ManagementTestBase } @Test - public void testGetQueueNames() throws Exception - { + public void testGetQueueNames() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); SimpleString anotherQueue = RandomUtil.randomSimpleString(); @@ -78,17 +75,17 @@ public class AddressControlUsingCoreTest extends ManagementTestBase session.createQueue(address, queue, true); CoreMessagingProxy proxy = createProxy(address); - Object[] queueNames = (Object[])proxy.retrieveAttributeValue("queueNames"); + Object[] queueNames = (Object[]) proxy.retrieveAttributeValue("queueNames"); Assert.assertEquals(1, queueNames.length); Assert.assertEquals(queue.toString(), queueNames[0]); session.createQueue(address, anotherQueue, false); - queueNames = (Object[])proxy.retrieveAttributeValue("queueNames"); + queueNames = (Object[]) proxy.retrieveAttributeValue("queueNames"); Assert.assertEquals(2, queueNames.length); session.deleteQueue(queue); - queueNames = (Object[])proxy.retrieveAttributeValue("queueNames"); + queueNames = (Object[]) proxy.retrieveAttributeValue("queueNames"); Assert.assertEquals(1, queueNames.length); Assert.assertEquals(anotherQueue.toString(), queueNames[0]); @@ -96,8 +93,7 @@ public class AddressControlUsingCoreTest extends ManagementTestBase } @Test - public void testGetBindingNames() throws Exception - { + public void testGetBindingNames() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); String divertName = RandomUtil.randomString(); @@ -105,43 +101,34 @@ public class AddressControlUsingCoreTest extends ManagementTestBase session.createQueue(address, queue, false); CoreMessagingProxy proxy = createProxy(address); - Object[] bindingNames = (Object[])proxy.retrieveAttributeValue("bindingNames"); + Object[] bindingNames = (Object[]) proxy.retrieveAttributeValue("bindingNames"); assertEquals(1, bindingNames.length); assertEquals(queue.toString(), bindingNames[0]); server.getActiveMQServerControl().createDivert(divertName, randomString(), address.toString(), RandomUtil.randomString(), false, null, null); - bindingNames = (Object[])proxy.retrieveAttributeValue("bindingNames"); + bindingNames = (Object[]) proxy.retrieveAttributeValue("bindingNames"); assertEquals(2, bindingNames.length); session.deleteQueue(queue); - bindingNames = (Object[])proxy.retrieveAttributeValue("bindingNames"); + bindingNames = (Object[]) proxy.retrieveAttributeValue("bindingNames"); assertEquals(1, bindingNames.length); assertEquals(divertName.toString(), bindingNames[0]); } @Test - public void testGetRoles() throws Exception - { + public void testGetRoles() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); - Role role = new Role(RandomUtil.randomString(), - RandomUtil.randomBoolean(), - RandomUtil.randomBoolean(), - RandomUtil.randomBoolean(), - RandomUtil.randomBoolean(), - RandomUtil.randomBoolean(), - RandomUtil.randomBoolean(), - RandomUtil.randomBoolean()); + Role role = new Role(RandomUtil.randomString(), RandomUtil.randomBoolean(), RandomUtil.randomBoolean(), RandomUtil.randomBoolean(), RandomUtil.randomBoolean(), RandomUtil.randomBoolean(), RandomUtil.randomBoolean(), RandomUtil.randomBoolean()); session.createQueue(address, queue, true); CoreMessagingProxy proxy = createProxy(address); - Object[] roles = (Object[])proxy.retrieveAttributeValue("roles"); - for (Object role2 : roles) - { - System.out.println(((Object[])role2)[0]); + Object[] roles = (Object[]) proxy.retrieveAttributeValue("roles"); + for (Object role2 : roles) { + System.out.println(((Object[]) role2)[0]); } Assert.assertEquals(0, roles.length); @@ -149,9 +136,9 @@ public class AddressControlUsingCoreTest extends ManagementTestBase newRoles.add(role); server.getSecurityRepository().addMatch(address.toString(), newRoles); - roles = (Object[])proxy.retrieveAttributeValue("roles"); + roles = (Object[]) proxy.retrieveAttributeValue("roles"); Assert.assertEquals(1, roles.length); - Object[] r = (Object[])roles[0]; + Object[] r = (Object[]) roles[0]; Assert.assertEquals(role.getName(), r[0]); Assert.assertEquals(CheckType.SEND.hasRole(role), r[1]); Assert.assertEquals(CheckType.CONSUME.hasRole(role), r[2]); @@ -170,32 +157,27 @@ public class AddressControlUsingCoreTest extends ManagementTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - Configuration config = createDefaultInVMConfig() - .setJMXManagementEnabled(true); + Configuration config = createDefaultInVMConfig().setJMXManagementEnabled(true); server = createServer(false, config); server.setMBeanServer(mbeanServer); server.start(); - ServerLocator locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true); + ServerLocator locator = createInVMNonHALocator().setBlockOnNonDurableSend(true); ClientSessionFactory sf = createSessionFactory(locator); session = sf.createSession(false, true, false); session.start(); } - protected CoreMessagingProxy createProxy(final SimpleString address) throws Exception - { + protected CoreMessagingProxy createProxy(final SimpleString address) throws Exception { CoreMessagingProxy proxy = new CoreMessagingProxy(session, ResourceNames.CORE_ADDRESS + address); return proxy; } - protected AddressControl createManagementControl(final SimpleString address) throws Exception - { + protected AddressControl createManagementControl(final SimpleString address) throws Exception { return ManagementControlHelper.createAddressControl(address, mbeanServer); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/BridgeControlTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/BridgeControlTest.java index b65a95a098..43d7048804 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/BridgeControlTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/BridgeControlTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.management; + import org.apache.activemq.artemis.tests.integration.SimpleNotificationService; import org.junit.Before; import org.junit.Test; @@ -44,16 +45,15 @@ import org.apache.activemq.artemis.core.server.ActiveMQServers; import org.apache.activemq.artemis.core.server.management.Notification; import org.apache.activemq.artemis.tests.util.RandomUtil; -public class BridgeControlTest extends ManagementTestBase -{ +public class BridgeControlTest extends ManagementTestBase { + private ActiveMQServer server_0; private ActiveMQServer server_1; private BridgeConfiguration bridgeConfig; @Test - public void testAttributes() throws Exception - { + public void testAttributes() throws Exception { checkResource(ObjectNameBuilder.DEFAULT.getBridgeObjectName(bridgeConfig.getName())); BridgeControl bridgeControl = createBridgeControl(bridgeConfig.getName(), mbeanServer); @@ -63,8 +63,7 @@ public class BridgeControlTest extends ManagementTestBase Assert.assertEquals(bridgeConfig.getForwardingAddress(), bridgeControl.getForwardingAddress()); Assert.assertEquals(bridgeConfig.getFilterString(), bridgeControl.getFilterString()); Assert.assertEquals(bridgeConfig.getRetryInterval(), bridgeControl.getRetryInterval()); - Assert.assertEquals(bridgeConfig.getRetryIntervalMultiplier(), bridgeControl.getRetryIntervalMultiplier(), - 0.000001); + Assert.assertEquals(bridgeConfig.getRetryIntervalMultiplier(), bridgeControl.getRetryIntervalMultiplier(), 0.000001); Assert.assertEquals(bridgeConfig.getReconnectAttempts(), bridgeControl.getReconnectAttempts()); Assert.assertEquals(bridgeConfig.isUseDuplicateDetection(), bridgeControl.isUseDuplicateDetection()); @@ -75,8 +74,7 @@ public class BridgeControlTest extends ManagementTestBase } @Test - public void testStartStop() throws Exception - { + public void testStartStop() throws Exception { checkResource(ObjectNameBuilder.DEFAULT.getBridgeObjectName(bridgeConfig.getName())); BridgeControl bridgeControl = createBridgeControl(bridgeConfig.getName(), mbeanServer); @@ -91,8 +89,7 @@ public class BridgeControlTest extends ManagementTestBase } @Test - public void testNotifications() throws Exception - { + public void testNotifications() throws Exception { SimpleNotificationService.Listener notifListener = new SimpleNotificationService.Listener(); BridgeControl bridgeControl = createBridgeControl(bridgeConfig.getName(), mbeanServer); @@ -105,71 +102,37 @@ public class BridgeControlTest extends ManagementTestBase Assert.assertEquals(1, notifListener.getNotifications().size()); Notification notif = notifListener.getNotifications().get(0); Assert.assertEquals(CoreNotificationType.BRIDGE_STOPPED, notif.getType()); - Assert.assertEquals(bridgeControl.getName(), notif.getProperties() - .getSimpleStringProperty(new SimpleString("name")) - .toString()); + Assert.assertEquals(bridgeControl.getName(), notif.getProperties().getSimpleStringProperty(new SimpleString("name")).toString()); bridgeControl.start(); Assert.assertEquals(2, notifListener.getNotifications().size()); notif = notifListener.getNotifications().get(1); Assert.assertEquals(CoreNotificationType.BRIDGE_STARTED, notif.getType()); - Assert.assertEquals(bridgeControl.getName(), notif.getProperties() - .getSimpleStringProperty(new SimpleString("name")) - .toString()); + Assert.assertEquals(bridgeControl.getName(), notif.getProperties().getSimpleStringProperty(new SimpleString("name")).toString()); } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); Map acceptorParams = new HashMap(); acceptorParams.put(TransportConstants.SERVER_ID_PROP_NAME, 1); - TransportConfiguration acceptorConfig = new TransportConfiguration(InVMAcceptorFactory.class.getName(), - acceptorParams, - RandomUtil.randomString()); + TransportConfiguration acceptorConfig = new TransportConfiguration(InVMAcceptorFactory.class.getName(), acceptorParams, RandomUtil.randomString()); - TransportConfiguration connectorConfig = new TransportConfiguration(InVMConnectorFactory.class.getName(), - acceptorParams, - RandomUtil.randomString()); + TransportConfiguration connectorConfig = new TransportConfiguration(InVMConnectorFactory.class.getName(), acceptorParams, RandomUtil.randomString()); - CoreQueueConfiguration sourceQueueConfig = new CoreQueueConfiguration() - .setAddress(RandomUtil.randomString()) - .setName(RandomUtil.randomString()) - .setDurable(false); - CoreQueueConfiguration targetQueueConfig = new CoreQueueConfiguration() - .setAddress(RandomUtil.randomString()) - .setName(RandomUtil.randomString()) - .setDurable(false); + CoreQueueConfiguration sourceQueueConfig = new CoreQueueConfiguration().setAddress(RandomUtil.randomString()).setName(RandomUtil.randomString()).setDurable(false); + CoreQueueConfiguration targetQueueConfig = new CoreQueueConfiguration().setAddress(RandomUtil.randomString()).setName(RandomUtil.randomString()).setDurable(false); List connectors = new ArrayList(); connectors.add(connectorConfig.getName()); + Configuration conf_1 = createBasicConfig().addAcceptorConfiguration(acceptorConfig).addQueueConfiguration(targetQueueConfig); - Configuration conf_1 = createBasicConfig() - .addAcceptorConfiguration(acceptorConfig) - .addQueueConfiguration(targetQueueConfig); + bridgeConfig = new BridgeConfiguration().setName(RandomUtil.randomString()).setQueueName(sourceQueueConfig.getName()).setForwardingAddress(targetQueueConfig.getAddress()).setRetryInterval(RandomUtil.randomPositiveLong()).setRetryIntervalMultiplier(RandomUtil.randomDouble()).setInitialConnectAttempts(RandomUtil.randomPositiveInt()).setReconnectAttempts(RandomUtil.randomPositiveInt()).setReconnectAttemptsOnSameNode(RandomUtil.randomPositiveInt()).setUseDuplicateDetection(RandomUtil.randomBoolean()).setConfirmationWindowSize(RandomUtil.randomPositiveInt()).setStaticConnectors(connectors).setPassword(CLUSTER_PASSWORD); - bridgeConfig = new BridgeConfiguration() - .setName(RandomUtil.randomString()) - .setQueueName(sourceQueueConfig.getName()) - .setForwardingAddress(targetQueueConfig.getAddress()) - .setRetryInterval(RandomUtil.randomPositiveLong()) - .setRetryIntervalMultiplier(RandomUtil.randomDouble()) - .setInitialConnectAttempts(RandomUtil.randomPositiveInt()) - .setReconnectAttempts(RandomUtil.randomPositiveInt()) - .setReconnectAttemptsOnSameNode(RandomUtil.randomPositiveInt()) - .setUseDuplicateDetection(RandomUtil.randomBoolean()) - .setConfirmationWindowSize(RandomUtil.randomPositiveInt()) - .setStaticConnectors(connectors) - .setPassword(CLUSTER_PASSWORD); - - Configuration conf_0 = createBasicConfig() - .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())) - .addConnectorConfiguration(connectorConfig.getName(), connectorConfig) - .addQueueConfiguration(sourceQueueConfig) - .addBridgeConfiguration(bridgeConfig); + Configuration conf_0 = createBasicConfig().addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())).addConnectorConfiguration(connectorConfig.getName(), connectorConfig).addQueueConfiguration(sourceQueueConfig).addBridgeConfiguration(bridgeConfig); server_1 = addServer(ActiveMQServers.newActiveMQServer(conf_1, MBeanServerFactory.createMBeanServer(), false)); addServer(server_1); @@ -180,8 +143,7 @@ public class BridgeControlTest extends ManagementTestBase server_0.start(); } - protected BridgeControl createBridgeControl(final String name, final MBeanServer mbeanServer1) throws Exception - { + protected BridgeControl createBridgeControl(final String name, final MBeanServer mbeanServer1) throws Exception { return ManagementControlHelper.createBridgeControl(name, mbeanServer1); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/BridgeControlUsingCoreTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/BridgeControlUsingCoreTest.java index 3e2cd47936..025b1e9428 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/BridgeControlUsingCoreTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/BridgeControlUsingCoreTest.java @@ -41,8 +41,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -public class BridgeControlUsingCoreTest extends ManagementTestBase -{ +public class BridgeControlUsingCoreTest extends ManagementTestBase { // Constants ----------------------------------------------------- @@ -61,47 +60,39 @@ public class BridgeControlUsingCoreTest extends ManagementTestBase // Public -------------------------------------------------------- @Test - public void testAttributes() throws Exception - { + public void testAttributes() throws Exception { checkResource(ObjectNameBuilder.DEFAULT.getBridgeObjectName(bridgeConfig.getName())); CoreMessagingProxy proxy = createProxy(bridgeConfig.getName()); Assert.assertEquals(bridgeConfig.getName(), proxy.retrieveAttributeValue("name")); - Assert.assertEquals(bridgeConfig.getDiscoveryGroupName(), - proxy.retrieveAttributeValue("discoveryGroupName")); + Assert.assertEquals(bridgeConfig.getDiscoveryGroupName(), proxy.retrieveAttributeValue("discoveryGroupName")); Assert.assertEquals(bridgeConfig.getQueueName(), proxy.retrieveAttributeValue("queueName")); - Assert.assertEquals(bridgeConfig.getForwardingAddress(), - proxy.retrieveAttributeValue("forwardingAddress")); + Assert.assertEquals(bridgeConfig.getForwardingAddress(), proxy.retrieveAttributeValue("forwardingAddress")); Assert.assertEquals(bridgeConfig.getFilterString(), proxy.retrieveAttributeValue("filterString")); - Assert.assertEquals(bridgeConfig.getRetryInterval(), - ((Long)proxy.retrieveAttributeValue("retryInterval")).longValue()); - Assert.assertEquals(bridgeConfig.getRetryIntervalMultiplier(), - proxy.retrieveAttributeValue("retryIntervalMultiplier")); - Assert.assertEquals(bridgeConfig.getReconnectAttempts(), - ((Integer)proxy.retrieveAttributeValue("reconnectAttempts")).intValue()); - Assert.assertEquals(bridgeConfig.isUseDuplicateDetection(), - ((Boolean)proxy.retrieveAttributeValue("useDuplicateDetection")).booleanValue()); + Assert.assertEquals(bridgeConfig.getRetryInterval(), ((Long) proxy.retrieveAttributeValue("retryInterval")).longValue()); + Assert.assertEquals(bridgeConfig.getRetryIntervalMultiplier(), proxy.retrieveAttributeValue("retryIntervalMultiplier")); + Assert.assertEquals(bridgeConfig.getReconnectAttempts(), ((Integer) proxy.retrieveAttributeValue("reconnectAttempts")).intValue()); + Assert.assertEquals(bridgeConfig.isUseDuplicateDetection(), ((Boolean) proxy.retrieveAttributeValue("useDuplicateDetection")).booleanValue()); - Object[] data = (Object[])proxy.retrieveAttributeValue("staticConnectors"); + Object[] data = (Object[]) proxy.retrieveAttributeValue("staticConnectors"); Assert.assertEquals(bridgeConfig.getStaticConnectors().get(0), data[0]); - Assert.assertTrue((Boolean)proxy.retrieveAttributeValue("started")); + Assert.assertTrue((Boolean) proxy.retrieveAttributeValue("started")); } @Test - public void testStartStop() throws Exception - { + public void testStartStop() throws Exception { checkResource(ObjectNameBuilder.DEFAULT.getBridgeObjectName(bridgeConfig.getName())); CoreMessagingProxy proxy = createProxy(bridgeConfig.getName()); // started by the server - Assert.assertTrue((Boolean)proxy.retrieveAttributeValue("Started")); + Assert.assertTrue((Boolean) proxy.retrieveAttributeValue("Started")); proxy.invokeOperation("stop"); - Assert.assertFalse((Boolean)proxy.retrieveAttributeValue("Started")); + Assert.assertFalse((Boolean) proxy.retrieveAttributeValue("Started")); proxy.invokeOperation("start"); - Assert.assertTrue((Boolean)proxy.retrieveAttributeValue("Started")); + Assert.assertTrue((Boolean) proxy.retrieveAttributeValue("Started")); } // Package protected --------------------------------------------- @@ -110,52 +101,24 @@ public class BridgeControlUsingCoreTest extends ManagementTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); Map acceptorParams = new HashMap(); acceptorParams.put(TransportConstants.SERVER_ID_PROP_NAME, 1); - TransportConfiguration acceptorConfig = new TransportConfiguration(InVMAcceptorFactory.class.getName(), - acceptorParams, - RandomUtil.randomString()); + TransportConfiguration acceptorConfig = new TransportConfiguration(InVMAcceptorFactory.class.getName(), acceptorParams, RandomUtil.randomString()); - TransportConfiguration connectorConfig = new TransportConfiguration(InVMConnectorFactory.class.getName(), - acceptorParams, - RandomUtil.randomString()); + TransportConfiguration connectorConfig = new TransportConfiguration(InVMConnectorFactory.class.getName(), acceptorParams, RandomUtil.randomString()); - CoreQueueConfiguration sourceQueueConfig = new CoreQueueConfiguration() - .setAddress(RandomUtil.randomString()) - .setName(RandomUtil.randomString()) - .setDurable(false); - CoreQueueConfiguration targetQueueConfig = new CoreQueueConfiguration() - .setAddress(RandomUtil.randomString()) - .setName(RandomUtil.randomString()) - .setDurable(false); + CoreQueueConfiguration sourceQueueConfig = new CoreQueueConfiguration().setAddress(RandomUtil.randomString()).setName(RandomUtil.randomString()).setDurable(false); + CoreQueueConfiguration targetQueueConfig = new CoreQueueConfiguration().setAddress(RandomUtil.randomString()).setName(RandomUtil.randomString()).setDurable(false); List connectors = new ArrayList(); connectors.add(connectorConfig.getName()); - bridgeConfig = new BridgeConfiguration() - .setName(RandomUtil.randomString()) - .setQueueName(sourceQueueConfig.getName()) - .setForwardingAddress(targetQueueConfig.getAddress()) - .setRetryInterval(RandomUtil.randomPositiveLong()) - .setRetryIntervalMultiplier(RandomUtil.randomDouble()) - .setInitialConnectAttempts(RandomUtil.randomPositiveInt()) - .setReconnectAttempts(RandomUtil.randomPositiveInt()) - .setReconnectAttemptsOnSameNode(RandomUtil.randomPositiveInt()) - .setUseDuplicateDetection(RandomUtil.randomBoolean()) - .setConfirmationWindowSize(RandomUtil.randomPositiveInt()) - .setStaticConnectors(connectors); + bridgeConfig = new BridgeConfiguration().setName(RandomUtil.randomString()).setQueueName(sourceQueueConfig.getName()).setForwardingAddress(targetQueueConfig.getAddress()).setRetryInterval(RandomUtil.randomPositiveLong()).setRetryIntervalMultiplier(RandomUtil.randomDouble()).setInitialConnectAttempts(RandomUtil.randomPositiveInt()).setReconnectAttempts(RandomUtil.randomPositiveInt()).setReconnectAttemptsOnSameNode(RandomUtil.randomPositiveInt()).setUseDuplicateDetection(RandomUtil.randomBoolean()).setConfirmationWindowSize(RandomUtil.randomPositiveInt()).setStaticConnectors(connectors); - Configuration conf_1 = createBasicConfig() - .addAcceptorConfiguration(acceptorConfig) - .addQueueConfiguration(targetQueueConfig); + Configuration conf_1 = createBasicConfig().addAcceptorConfiguration(acceptorConfig).addQueueConfiguration(targetQueueConfig); - Configuration conf_0 = createBasicConfig() - .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY)) - .addConnectorConfiguration(connectorConfig.getName(), connectorConfig) - .addQueueConfiguration(sourceQueueConfig) - .addBridgeConfiguration(bridgeConfig); + Configuration conf_0 = createBasicConfig().addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY)).addConnectorConfiguration(connectorConfig.getName(), connectorConfig).addQueueConfiguration(sourceQueueConfig).addBridgeConfiguration(bridgeConfig); server_1 = addServer(ActiveMQServers.newActiveMQServer(conf_1, MBeanServerFactory.createMBeanServer(), false)); server_1.start(); @@ -168,9 +131,7 @@ public class BridgeControlUsingCoreTest extends ManagementTestBase session.start(); } - - protected CoreMessagingProxy createProxy(final String name) throws Exception - { + protected CoreMessagingProxy createProxy(final String name) throws Exception { CoreMessagingProxy proxy = new CoreMessagingProxy(session, ResourceNames.CORE_BRIDGE + name); return proxy; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/BroadcastGroupControlTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/BroadcastGroupControlTest.java index 0793a84990..bc1fb651c4 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/BroadcastGroupControlTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/BroadcastGroupControlTest.java @@ -32,16 +32,14 @@ import org.junit.Test; import java.util.ArrayList; import java.util.List; -public class BroadcastGroupControlTest extends ManagementTestBase -{ +public class BroadcastGroupControlTest extends ManagementTestBase { private ActiveMQServer server; BroadcastGroupConfiguration broadcastGroupConfig; BroadcastGroupControl broadcastGroupControl; @Test - public void testAttributes() throws Exception - { + public void testAttributes() throws Exception { UDPBroadcastEndpointFactory udpCfg = (UDPBroadcastEndpointFactory) broadcastGroupConfig.getEndpointFactory(); Assert.assertEquals(broadcastGroupConfig.getName(), broadcastGroupControl.getName()); Assert.assertEquals(udpCfg.getGroupAddress(), broadcastGroupControl.getGroupAddress()); @@ -52,7 +50,7 @@ public class BroadcastGroupControlTest extends ManagementTestBase Object[] connectorPairs = broadcastGroupControl.getConnectorPairs(); Assert.assertEquals(1, connectorPairs.length); - String connectorPairData = (String)connectorPairs[0]; + String connectorPairData = (String) connectorPairs[0]; Assert.assertEquals(broadcastGroupConfig.getConnectorInfos().get(0), connectorPairData); String jsonString = broadcastGroupControl.getConnectorPairsAsJSON(); Assert.assertNotNull(jsonString); @@ -64,8 +62,7 @@ public class BroadcastGroupControlTest extends ManagementTestBase } @Test - public void testStartStop() throws Exception - { + public void testStartStop() throws Exception { // started by the server Assert.assertTrue(broadcastGroupControl.isStarted()); @@ -76,33 +73,21 @@ public class BroadcastGroupControlTest extends ManagementTestBase Assert.assertTrue(broadcastGroupControl.isStarted()); } - protected BroadcastGroupControl createManagementControl(final String name) throws Exception - { + protected BroadcastGroupControl createManagementControl(final String name) throws Exception { return ManagementControlHelper.createBroadcastGroupControl(name, mbeanServer); } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); TransportConfiguration connectorConfiguration = new TransportConfiguration(NETTY_CONNECTOR_FACTORY); List connectorInfos = new ArrayList(); connectorInfos.add(connectorConfiguration.getName()); - broadcastGroupConfig = new BroadcastGroupConfiguration() - .setName(RandomUtil.randomString()) - .setBroadcastPeriod(RandomUtil.randomPositiveInt()) - .setConnectorInfos(connectorInfos) - .setEndpointFactory(new UDPBroadcastEndpointFactory() - .setGroupAddress("231.7.7.7") - .setGroupPort(1199) - .setLocalBindPort(1198)); + broadcastGroupConfig = new BroadcastGroupConfiguration().setName(RandomUtil.randomString()).setBroadcastPeriod(RandomUtil.randomPositiveInt()).setConnectorInfos(connectorInfos).setEndpointFactory(new UDPBroadcastEndpointFactory().setGroupAddress("231.7.7.7").setGroupPort(1199).setLocalBindPort(1198)); - Configuration config = createDefaultInVMConfig() - .setJMXManagementEnabled(true) - .addConnectorConfiguration(connectorConfiguration.getName(), connectorConfiguration) - .addBroadcastGroupConfiguration(broadcastGroupConfig); + Configuration config = createDefaultInVMConfig().setJMXManagementEnabled(true).addConnectorConfiguration(connectorConfiguration.getName(), connectorConfiguration).addBroadcastGroupConfiguration(broadcastGroupConfig); server = addServer(ActiveMQServers.newActiveMQServer(config, mbeanServer, false)); server.start(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/BroadcastGroupControlUsingCoreTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/BroadcastGroupControlUsingCoreTest.java index 6bcf5242fe..cf63385579 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/BroadcastGroupControlUsingCoreTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/BroadcastGroupControlUsingCoreTest.java @@ -22,69 +22,55 @@ import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.api.core.management.BroadcastGroupControl; import org.apache.activemq.artemis.api.core.management.ResourceNames; -public class BroadcastGroupControlUsingCoreTest extends BroadcastGroupControlTest -{ +public class BroadcastGroupControlUsingCoreTest extends BroadcastGroupControlTest { @Override - protected BroadcastGroupControl createManagementControl(final String name) throws Exception - { + protected BroadcastGroupControl createManagementControl(final String name) throws Exception { ServerLocator locator = createInVMNonHALocator(); ClientSessionFactory sf = addSessionFactory(createSessionFactory(locator)); final ClientSession session = addClientSession(sf.createSession(false, true, true)); session.start(); - return new BroadcastGroupControl() - { - private final CoreMessagingProxy proxy = new CoreMessagingProxy(session, - ResourceNames.CORE_BROADCAST_GROUP + name); + return new BroadcastGroupControl() { + private final CoreMessagingProxy proxy = new CoreMessagingProxy(session, ResourceNames.CORE_BROADCAST_GROUP + name); - public long getBroadcastPeriod() - { - return ((Integer)proxy.retrieveAttributeValue("broadcastPeriod")).longValue(); + public long getBroadcastPeriod() { + return ((Integer) proxy.retrieveAttributeValue("broadcastPeriod")).longValue(); } - public Object[] getConnectorPairs() - { - return (Object[])proxy.retrieveAttributeValue("connectorPairs"); + public Object[] getConnectorPairs() { + return (Object[]) proxy.retrieveAttributeValue("connectorPairs"); } - public String getConnectorPairsAsJSON() - { - return (String)proxy.retrieveAttributeValue("connectorPairsAsJSON"); + public String getConnectorPairsAsJSON() { + return (String) proxy.retrieveAttributeValue("connectorPairsAsJSON"); } - public String getGroupAddress() - { - return (String)proxy.retrieveAttributeValue("groupAddress"); + public String getGroupAddress() { + return (String) proxy.retrieveAttributeValue("groupAddress"); } - public int getGroupPort() - { - return (Integer)proxy.retrieveAttributeValue("groupPort"); + public int getGroupPort() { + return (Integer) proxy.retrieveAttributeValue("groupPort"); } - public int getLocalBindPort() - { - return (Integer)proxy.retrieveAttributeValue("localBindPort"); + public int getLocalBindPort() { + return (Integer) proxy.retrieveAttributeValue("localBindPort"); } - public String getName() - { - return (String)proxy.retrieveAttributeValue("name"); + public String getName() { + return (String) proxy.retrieveAttributeValue("name"); } - public boolean isStarted() - { - return (Boolean)proxy.retrieveAttributeValue("started"); + public boolean isStarted() { + return (Boolean) proxy.retrieveAttributeValue("started"); } - public void start() throws Exception - { + public void start() throws Exception { proxy.invokeOperation("start"); } - public void stop() throws Exception - { + public void stop() throws Exception { proxy.invokeOperation("stop"); } }; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ClusterConnectionControl2Test.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ClusterConnectionControl2Test.java index 85a0d12602..10027b0760 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ClusterConnectionControl2Test.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ClusterConnectionControl2Test.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.management; + import org.apache.activemq.artemis.core.server.cluster.impl.MessageLoadBalancingType; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Before; @@ -45,8 +46,7 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.ActiveMQServers; import org.apache.activemq.artemis.tests.util.RandomUtil; -public class ClusterConnectionControl2Test extends ManagementTestBase -{ +public class ClusterConnectionControl2Test extends ManagementTestBase { // Constants ----------------------------------------------------- @@ -69,8 +69,7 @@ public class ClusterConnectionControl2Test extends ManagementTestBase // Public -------------------------------------------------------- @Test - public void testNodes() throws Exception - { + public void testNodes() throws Exception { ClusterConnectionControl clusterConnectionControl_0 = createManagementControl(clusterConnectionConfig_0.getName()); Assert.assertTrue(clusterConnectionControl_0.isStarted()); Map nodes = clusterConnectionControl_0.getNodes(); @@ -80,12 +79,10 @@ public class ClusterConnectionControl2Test extends ManagementTestBase waitForServerToStart(server1); long start = System.currentTimeMillis(); - while (true) - { + while (true) { nodes = clusterConnectionControl_0.getNodes(); - if (nodes.size() == 1 || System.currentTimeMillis() - start > 30000) - { + if (nodes.size() == 1 || System.currentTimeMillis() - start > 30000) { break; } Thread.sleep(50); @@ -99,8 +96,7 @@ public class ClusterConnectionControl2Test extends ManagementTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); String discoveryName = RandomUtil.randomString(); @@ -116,54 +112,19 @@ public class ClusterConnectionControl2Test extends ManagementTestBase TransportConfiguration connectorConfig_1 = new TransportConfiguration(ActiveMQTestBase.NETTY_CONNECTOR_FACTORY, acceptorParams_1); TransportConfiguration connectorConfig_0 = new TransportConfiguration(ActiveMQTestBase.NETTY_CONNECTOR_FACTORY); - CoreQueueConfiguration queueConfig = new CoreQueueConfiguration() - .setAddress(RandomUtil.randomString()) - .setName(RandomUtil.randomString()) - .setDurable(false); + CoreQueueConfiguration queueConfig = new CoreQueueConfiguration().setAddress(RandomUtil.randomString()).setName(RandomUtil.randomString()).setDurable(false); List connectorInfos = new ArrayList(); connectorInfos.add("netty"); - BroadcastGroupConfiguration broadcastGroupConfig = new BroadcastGroupConfiguration() - .setName(discoveryName) - .setBroadcastPeriod(250) - .setConnectorInfos(connectorInfos) - .setEndpointFactory(new UDPBroadcastEndpointFactory() - .setGroupAddress(groupAddress) - .setGroupPort(groupPort)); + BroadcastGroupConfiguration broadcastGroupConfig = new BroadcastGroupConfiguration().setName(discoveryName).setBroadcastPeriod(250).setConnectorInfos(connectorInfos).setEndpointFactory(new UDPBroadcastEndpointFactory().setGroupAddress(groupAddress).setGroupPort(groupPort)); - DiscoveryGroupConfiguration discoveryGroupConfig = new DiscoveryGroupConfiguration() - .setName(discoveryName) - .setRefreshTimeout(0) - .setDiscoveryInitialWaitTimeout(0) - .setBroadcastEndpointFactory(new UDPBroadcastEndpointFactory() - .setGroupAddress(groupAddress) - .setGroupPort(groupPort)); + DiscoveryGroupConfiguration discoveryGroupConfig = new DiscoveryGroupConfiguration().setName(discoveryName).setRefreshTimeout(0).setDiscoveryInitialWaitTimeout(0).setBroadcastEndpointFactory(new UDPBroadcastEndpointFactory().setGroupAddress(groupAddress).setGroupPort(groupPort)); - clusterConnectionConfig_0 = new ClusterConnectionConfiguration() - .setName(clusterName) - .setAddress(queueConfig.getAddress()) - .setConnectorName("netty") - .setRetryInterval(1000) - .setDuplicateDetection(false) - .setMessageLoadBalancingType(MessageLoadBalancingType.ON_DEMAND) - .setMaxHops(1) - .setConfirmationWindowSize(1024) - .setDiscoveryGroupName(discoveryName); + clusterConnectionConfig_0 = new ClusterConnectionConfiguration().setName(clusterName).setAddress(queueConfig.getAddress()).setConnectorName("netty").setRetryInterval(1000).setDuplicateDetection(false).setMessageLoadBalancingType(MessageLoadBalancingType.ON_DEMAND).setMaxHops(1).setConfirmationWindowSize(1024).setDiscoveryGroupName(discoveryName); - Configuration conf_1 = createBasicConfig() - .addClusterConfiguration(clusterConnectionConfig_0) - .addAcceptorConfiguration(acceptorConfig_1) - .addConnectorConfiguration("netty", connectorConfig_1) - .addQueueConfiguration(queueConfig) - .addDiscoveryGroupConfiguration(discoveryName, discoveryGroupConfig) - .addBroadcastGroupConfiguration(broadcastGroupConfig); + Configuration conf_1 = createBasicConfig().addClusterConfiguration(clusterConnectionConfig_0).addAcceptorConfiguration(acceptorConfig_1).addConnectorConfiguration("netty", connectorConfig_1).addQueueConfiguration(queueConfig).addDiscoveryGroupConfiguration(discoveryName, discoveryGroupConfig).addBroadcastGroupConfiguration(broadcastGroupConfig); - Configuration conf_0 = createBasicConfig(1) - .addClusterConfiguration(clusterConnectionConfig_0) - .addAcceptorConfiguration(acceptorConfig_0) - .addConnectorConfiguration("netty", connectorConfig_0) - .addDiscoveryGroupConfiguration(discoveryName, discoveryGroupConfig) - .addBroadcastGroupConfiguration(broadcastGroupConfig); + Configuration conf_0 = createBasicConfig(1).addClusterConfiguration(clusterConnectionConfig_0).addAcceptorConfiguration(acceptorConfig_0).addConnectorConfiguration("netty", connectorConfig_0).addDiscoveryGroupConfiguration(discoveryName, discoveryGroupConfig).addBroadcastGroupConfiguration(broadcastGroupConfig); mbeanServer_1 = MBeanServerFactory.createMBeanServer(); server1 = addServer(ActiveMQServers.newActiveMQServer(conf_1, mbeanServer_1, false)); @@ -175,14 +136,12 @@ public class ClusterConnectionControl2Test extends ManagementTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { MBeanServerFactory.releaseMBeanServer(mbeanServer_1); super.tearDown(); } - protected ClusterConnectionControl createManagementControl(final String name) throws Exception - { + protected ClusterConnectionControl createManagementControl(final String name) throws Exception { return ManagementControlHelper.createClusterConnectionControl(name, mbeanServer); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ClusterConnectionControlTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ClusterConnectionControlTest.java index bb0fc7b9a8..1fb9c4367c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ClusterConnectionControlTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ClusterConnectionControlTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.management; + import org.apache.activemq.artemis.core.server.cluster.impl.MessageLoadBalancingType; import org.junit.Before; import org.junit.After; @@ -49,8 +50,7 @@ import org.apache.activemq.artemis.tests.integration.SimpleNotificationService; import org.apache.activemq.artemis.tests.util.RandomUtil; import org.apache.activemq.artemis.utils.json.JSONArray; -public class ClusterConnectionControlTest extends ManagementTestBase -{ +public class ClusterConnectionControlTest extends ManagementTestBase { // Constants ----------------------------------------------------- @@ -71,26 +71,22 @@ public class ClusterConnectionControlTest extends ManagementTestBase // Public -------------------------------------------------------- @Test - public void testAttributes1() throws Exception - { + public void testAttributes1() throws Exception { checkResource(ObjectNameBuilder.DEFAULT.getClusterConnectionObjectName(clusterConnectionConfig1.getName())); ClusterConnectionControl clusterConnectionControl = createManagementControl(clusterConnectionConfig1.getName()); Assert.assertEquals(clusterConnectionConfig1.getName(), clusterConnectionControl.getName()); Assert.assertEquals(clusterConnectionConfig1.getAddress(), clusterConnectionControl.getAddress()); - Assert.assertEquals(clusterConnectionConfig1.getDiscoveryGroupName(), - clusterConnectionControl.getDiscoveryGroupName()); + Assert.assertEquals(clusterConnectionConfig1.getDiscoveryGroupName(), clusterConnectionControl.getDiscoveryGroupName()); Assert.assertEquals(clusterConnectionConfig1.getRetryInterval(), clusterConnectionControl.getRetryInterval()); - Assert.assertEquals(clusterConnectionConfig1.isDuplicateDetection(), - clusterConnectionControl.isDuplicateDetection()); - Assert.assertEquals(clusterConnectionConfig1.getMessageLoadBalancingType().getType(), - clusterConnectionControl.getMessageLoadBalancingType()); + Assert.assertEquals(clusterConnectionConfig1.isDuplicateDetection(), clusterConnectionControl.isDuplicateDetection()); + Assert.assertEquals(clusterConnectionConfig1.getMessageLoadBalancingType().getType(), clusterConnectionControl.getMessageLoadBalancingType()); Assert.assertEquals(clusterConnectionConfig1.getMaxHops(), clusterConnectionControl.getMaxHops()); Object[] connectors = clusterConnectionControl.getStaticConnectors(); Assert.assertEquals(1, connectors.length); - String connector = (String)connectors[0]; + String connector = (String) connectors[0]; Assert.assertEquals(clusterConnectionConfig1.getStaticConnectors().get(0), connector); String jsonString = clusterConnectionControl.getStaticConnectorsAsJSON(); @@ -105,21 +101,17 @@ public class ClusterConnectionControlTest extends ManagementTestBase } @Test - public void testAttributes2() throws Exception - { + public void testAttributes2() throws Exception { checkResource(ObjectNameBuilder.DEFAULT.getClusterConnectionObjectName(clusterConnectionConfig2.getName())); ClusterConnectionControl clusterConnectionControl = createManagementControl(clusterConnectionConfig2.getName()); Assert.assertEquals(clusterConnectionConfig2.getName(), clusterConnectionControl.getName()); Assert.assertEquals(clusterConnectionConfig2.getAddress(), clusterConnectionControl.getAddress()); - Assert.assertEquals(clusterConnectionConfig2.getDiscoveryGroupName(), - clusterConnectionControl.getDiscoveryGroupName()); + Assert.assertEquals(clusterConnectionConfig2.getDiscoveryGroupName(), clusterConnectionControl.getDiscoveryGroupName()); Assert.assertEquals(clusterConnectionConfig2.getRetryInterval(), clusterConnectionControl.getRetryInterval()); - Assert.assertEquals(clusterConnectionConfig2.isDuplicateDetection(), - clusterConnectionControl.isDuplicateDetection()); - Assert.assertEquals(clusterConnectionConfig2.getMessageLoadBalancingType().getType(), - clusterConnectionControl.getMessageLoadBalancingType()); + Assert.assertEquals(clusterConnectionConfig2.isDuplicateDetection(), clusterConnectionControl.isDuplicateDetection()); + Assert.assertEquals(clusterConnectionConfig2.getMessageLoadBalancingType().getType(), clusterConnectionControl.getMessageLoadBalancingType()); Assert.assertEquals(clusterConnectionConfig2.getMaxHops(), clusterConnectionControl.getMaxHops()); Object[] connectorPairs = clusterConnectionControl.getStaticConnectors(); @@ -128,13 +120,11 @@ public class ClusterConnectionControlTest extends ManagementTestBase String jsonPairs = clusterConnectionControl.getStaticConnectorsAsJSON(); Assert.assertEquals("[]", jsonPairs); - Assert.assertEquals(clusterConnectionConfig2.getDiscoveryGroupName(), - clusterConnectionControl.getDiscoveryGroupName()); + Assert.assertEquals(clusterConnectionConfig2.getDiscoveryGroupName(), clusterConnectionControl.getDiscoveryGroupName()); } @Test - public void testStartStop() throws Exception - { + public void testStartStop() throws Exception { checkResource(ObjectNameBuilder.DEFAULT.getClusterConnectionObjectName(clusterConnectionConfig1.getName())); ClusterConnectionControl clusterConnectionControl = createManagementControl(clusterConnectionConfig1.getName()); @@ -149,8 +139,7 @@ public class ClusterConnectionControlTest extends ManagementTestBase } @Test - public void testNotifications() throws Exception - { + public void testNotifications() throws Exception { SimpleNotificationService.Listener notifListener = new SimpleNotificationService.Listener(); checkResource(ObjectNameBuilder.DEFAULT.getClusterConnectionObjectName(clusterConnectionConfig1.getName())); ClusterConnectionControl clusterConnectionControl = createManagementControl(clusterConnectionConfig1.getName()); @@ -164,31 +153,24 @@ public class ClusterConnectionControlTest extends ManagementTestBase Assert.assertTrue(notifListener.getNotifications().size() > 0); Notification notif = getFirstNotificationOfType(notifListener.getNotifications(), CoreNotificationType.CLUSTER_CONNECTION_STOPPED); Assert.assertNotNull(notif); - Assert.assertEquals(clusterConnectionControl.getName(), notif.getProperties() - .getSimpleStringProperty(new SimpleString("name")) - .toString()); + Assert.assertEquals(clusterConnectionControl.getName(), notif.getProperties().getSimpleStringProperty(new SimpleString("name")).toString()); clusterConnectionControl.start(); Assert.assertTrue(notifListener.getNotifications().size() > 0); notif = getFirstNotificationOfType(notifListener.getNotifications(), CoreNotificationType.CLUSTER_CONNECTION_STARTED); Assert.assertNotNull(notif); - Assert.assertEquals(clusterConnectionControl.getName(), notif.getProperties() - .getSimpleStringProperty(new SimpleString("name")) - .toString()); + Assert.assertEquals(clusterConnectionControl.getName(), notif.getProperties().getSimpleStringProperty(new SimpleString("name")).toString()); } - private Notification getFirstNotificationOfType(List notifications, CoreNotificationType type) - { + private Notification getFirstNotificationOfType(List notifications, CoreNotificationType type) { Notification result = null; // the notifications can change while we're looping List notificationsClone = new ArrayList<>(notifications); - for (Notification notification : notificationsClone) - { - if (notification.getType().equals(type)) - { + for (Notification notification : notificationsClone) { + if (notification.getType().equals(type)) { result = notification; } } @@ -202,71 +184,29 @@ public class ClusterConnectionControlTest extends ManagementTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); Map acceptorParams = new HashMap(); acceptorParams.put(TransportConstants.SERVER_ID_PROP_NAME, 1); - TransportConfiguration acceptorConfig = new TransportConfiguration(InVMAcceptorFactory.class.getName(), - acceptorParams, - RandomUtil.randomString()); + TransportConfiguration acceptorConfig = new TransportConfiguration(InVMAcceptorFactory.class.getName(), acceptorParams, RandomUtil.randomString()); - TransportConfiguration connectorConfig = new TransportConfiguration(InVMConnectorFactory.class.getName(), - acceptorParams, - RandomUtil.randomString()); + TransportConfiguration connectorConfig = new TransportConfiguration(InVMConnectorFactory.class.getName(), acceptorParams, RandomUtil.randomString()); - CoreQueueConfiguration queueConfig = new CoreQueueConfiguration() - .setAddress(RandomUtil.randomString()) - .setName(RandomUtil.randomString()) - .setDurable(false); + CoreQueueConfiguration queueConfig = new CoreQueueConfiguration().setAddress(RandomUtil.randomString()).setName(RandomUtil.randomString()).setDurable(false); List connectors = new ArrayList(); connectors.add(connectorConfig.getName()); - String discoveryGroupName = RandomUtil.randomString(); - DiscoveryGroupConfiguration discoveryGroupConfig = new DiscoveryGroupConfiguration() - .setName(discoveryGroupName) - .setRefreshTimeout(500) - .setDiscoveryInitialWaitTimeout(0) - .setBroadcastEndpointFactory(new UDPBroadcastEndpointFactory() - .setGroupAddress("230.1.2.3") - .setGroupPort(6745)); + DiscoveryGroupConfiguration discoveryGroupConfig = new DiscoveryGroupConfiguration().setName(discoveryGroupName).setRefreshTimeout(500).setDiscoveryInitialWaitTimeout(0).setBroadcastEndpointFactory(new UDPBroadcastEndpointFactory().setGroupAddress("230.1.2.3").setGroupPort(6745)); - Configuration conf_1 = createBasicConfig() - .addAcceptorConfiguration(acceptorConfig) - .addQueueConfiguration(queueConfig); + Configuration conf_1 = createBasicConfig().addAcceptorConfiguration(acceptorConfig).addQueueConfiguration(queueConfig); - clusterConnectionConfig1 = new ClusterConnectionConfiguration() - .setName(RandomUtil.randomString()) - .setAddress(queueConfig.getAddress()) - .setConnectorName(connectorConfig.getName()) - .setRetryInterval(RandomUtil.randomPositiveLong()) - .setDuplicateDetection(RandomUtil.randomBoolean()) - .setMessageLoadBalancingType(MessageLoadBalancingType.STRICT) - .setMaxHops(RandomUtil.randomPositiveInt()) - .setConfirmationWindowSize(RandomUtil.randomPositiveInt()) - .setMessageLoadBalancingType(MessageLoadBalancingType.ON_DEMAND) - .setStaticConnectors(connectors); + clusterConnectionConfig1 = new ClusterConnectionConfiguration().setName(RandomUtil.randomString()).setAddress(queueConfig.getAddress()).setConnectorName(connectorConfig.getName()).setRetryInterval(RandomUtil.randomPositiveLong()).setDuplicateDetection(RandomUtil.randomBoolean()).setMessageLoadBalancingType(MessageLoadBalancingType.STRICT).setMaxHops(RandomUtil.randomPositiveInt()).setConfirmationWindowSize(RandomUtil.randomPositiveInt()).setMessageLoadBalancingType(MessageLoadBalancingType.ON_DEMAND).setStaticConnectors(connectors); - clusterConnectionConfig2 = new ClusterConnectionConfiguration() - .setName(RandomUtil.randomString()) - .setAddress(queueConfig.getAddress()) - .setConnectorName(connectorConfig.getName()) - .setRetryInterval(RandomUtil.randomPositiveLong()) - .setDuplicateDetection(RandomUtil.randomBoolean()) - .setMessageLoadBalancingType(MessageLoadBalancingType.OFF) - .setMaxHops(RandomUtil.randomPositiveInt()) - .setConfirmationWindowSize(RandomUtil.randomPositiveInt()) - .setMessageLoadBalancingType(MessageLoadBalancingType.ON_DEMAND) - .setDiscoveryGroupName(discoveryGroupName); + clusterConnectionConfig2 = new ClusterConnectionConfiguration().setName(RandomUtil.randomString()).setAddress(queueConfig.getAddress()).setConnectorName(connectorConfig.getName()).setRetryInterval(RandomUtil.randomPositiveLong()).setDuplicateDetection(RandomUtil.randomBoolean()).setMessageLoadBalancingType(MessageLoadBalancingType.OFF).setMaxHops(RandomUtil.randomPositiveInt()).setConfirmationWindowSize(RandomUtil.randomPositiveInt()).setMessageLoadBalancingType(MessageLoadBalancingType.ON_DEMAND).setDiscoveryGroupName(discoveryGroupName); - Configuration conf_0 = createBasicConfig() - .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())) - .addConnectorConfiguration(connectorConfig.getName(), connectorConfig) - .addClusterConfiguration(clusterConnectionConfig1) - .addClusterConfiguration(clusterConnectionConfig2) - .addDiscoveryGroupConfiguration(discoveryGroupName, discoveryGroupConfig); + Configuration conf_0 = createBasicConfig().addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())).addConnectorConfiguration(connectorConfig.getName(), connectorConfig).addClusterConfiguration(clusterConnectionConfig1).addClusterConfiguration(clusterConnectionConfig2).addDiscoveryGroupConfiguration(discoveryGroupName, discoveryGroupConfig); mbeanServer_1 = MBeanServerFactory.createMBeanServer(); server_1 = addServer(ActiveMQServers.newActiveMQServer(conf_1, mbeanServer_1, false)); @@ -278,14 +218,12 @@ public class ClusterConnectionControlTest extends ManagementTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { MBeanServerFactory.releaseMBeanServer(mbeanServer_1); super.tearDown(); } - protected ClusterConnectionControl createManagementControl(final String name) throws Exception - { + protected ClusterConnectionControl createManagementControl(final String name) throws Exception { return ManagementControlHelper.createClusterConnectionControl(name, mbeanServer); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ClusterConnectionControlUsingCoreTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ClusterConnectionControlUsingCoreTest.java index 9e9742cc4d..d502baaffc 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ClusterConnectionControlUsingCoreTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ClusterConnectionControlUsingCoreTest.java @@ -25,8 +25,7 @@ import org.junit.Before; import java.util.Map; -public class ClusterConnectionControlUsingCoreTest extends ClusterConnectionControlTest -{ +public class ClusterConnectionControlUsingCoreTest extends ClusterConnectionControlTest { // Constants ----------------------------------------------------- @@ -42,89 +41,71 @@ public class ClusterConnectionControlUsingCoreTest extends ClusterConnectionCont // ClusterConnectionControlTest overrides -------------------------------- @Override - protected ClusterConnectionControl createManagementControl(final String name) throws Exception - { + protected ClusterConnectionControl createManagementControl(final String name) throws Exception { ClientSessionFactory sf = createSessionFactory(locator); session = sf.createSession(false, true, true); session.start(); - return new ClusterConnectionControl() - { - private final CoreMessagingProxy proxy = new CoreMessagingProxy(session, - ResourceNames.CORE_CLUSTER_CONNECTION + name); + return new ClusterConnectionControl() { + private final CoreMessagingProxy proxy = new CoreMessagingProxy(session, ResourceNames.CORE_CLUSTER_CONNECTION + name); - public Object[] getStaticConnectors() - { + public Object[] getStaticConnectors() { return (Object[]) proxy.retrieveAttributeValue("staticConnectors"); } - public String getStaticConnectorsAsJSON() throws Exception - { + public String getStaticConnectorsAsJSON() throws Exception { return (String) proxy.retrieveAttributeValue("staticConnectorsAsJSON"); } - public String getAddress() - { + public String getAddress() { return (String) proxy.retrieveAttributeValue("address"); } - public String getDiscoveryGroupName() - { + public String getDiscoveryGroupName() { return (String) proxy.retrieveAttributeValue("discoveryGroupName"); } - public int getMaxHops() - { + public int getMaxHops() { return (Integer) proxy.retrieveAttributeValue("maxHops"); } - public long getRetryInterval() - { + public long getRetryInterval() { return (Long) proxy.retrieveAttributeValue("retryInterval"); } - public String getTopology() - { + public String getTopology() { return (String) proxy.retrieveAttributeValue("topology"); } - public Map getNodes() throws Exception - { + public Map getNodes() throws Exception { return (Map) proxy.retrieveAttributeValue("nodes"); } - public boolean isDuplicateDetection() - { + public boolean isDuplicateDetection() { return (Boolean) proxy.retrieveAttributeValue("duplicateDetection"); } - public String getMessageLoadBalancingType() - { + public String getMessageLoadBalancingType() { return (String) proxy.retrieveAttributeValue("messageLoadBalancingType"); } - public String getName() - { + public String getName() { return (String) proxy.retrieveAttributeValue("name"); } - public String getNodeID() - { + public String getNodeID() { return (String) proxy.retrieveAttributeValue("nodeID"); } - public boolean isStarted() - { + public boolean isStarted() { return (Boolean) proxy.retrieveAttributeValue("started"); } - public void start() throws Exception - { + public void start() throws Exception { proxy.invokeOperation("start"); } - public void stop() throws Exception - { + public void stop() throws Exception { proxy.invokeOperation("stop"); } @@ -137,11 +118,9 @@ public class ClusterConnectionControlUsingCoreTest extends ClusterConnectionCont // Protected ----------------------------------------------------- - @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = createInVMNonHALocator(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/CoreMessagingProxy.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/CoreMessagingProxy.java index 1f13b201cd..fca1d1f0a0 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/CoreMessagingProxy.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/CoreMessagingProxy.java @@ -22,8 +22,7 @@ import org.apache.activemq.artemis.api.core.client.ClientRequestor; import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.api.core.management.ManagementHelper; -public class CoreMessagingProxy -{ +public class CoreMessagingProxy { // Constants ----------------------------------------------------- @@ -39,8 +38,7 @@ public class CoreMessagingProxy // Constructors -------------------------------------------------- - public CoreMessagingProxy(final ClientSession session, final String resourceName) throws Exception - { + public CoreMessagingProxy(final ClientSession session, final String resourceName) throws Exception { this.session = session; this.resourceName = resourceName; @@ -55,27 +53,22 @@ public class CoreMessagingProxy // Protected ----------------------------------------------------- - public Object retrieveAttributeValue(final String attributeName) - { + public Object retrieveAttributeValue(final String attributeName) { return retrieveAttributeValue(attributeName, null); } - public Object retrieveAttributeValue(final String attributeName, final Class desiredType) - { + public Object retrieveAttributeValue(final String attributeName, final Class desiredType) { ClientMessage m = session.createMessage(false); ManagementHelper.putAttribute(m, resourceName, attributeName); ClientMessage reply; - try - { + try { reply = requestor.request(m); Object result = ManagementHelper.getResult(reply); - if (desiredType != null && desiredType != result.getClass()) - { + if (desiredType != null && desiredType != result.getClass()) { // Conversions - if (desiredType == Long.class && result.getClass() == Integer.class) - { - Integer in = (Integer)result; + if (desiredType == Long.class && result.getClass() == Integer.class) { + Integer in = (Integer) result; result = new Long(in.intValue()); } @@ -83,30 +76,24 @@ public class CoreMessagingProxy return result; } - catch (Exception e) - { + catch (Exception e) { throw new IllegalStateException(e); } } - public Object invokeOperation(final String operationName, final Object... args) throws Exception - { + public Object invokeOperation(final String operationName, final Object... args) throws Exception { ClientMessage m = session.createMessage(false); ManagementHelper.putOperationInvocation(m, resourceName, operationName, args); ClientMessage reply = requestor.request(m); - if (reply != null) - { - if (ManagementHelper.hasOperationSucceeded(reply)) - { + if (reply != null) { + if (ManagementHelper.hasOperationSucceeded(reply)) { return ManagementHelper.getResult(reply); } - else - { + else { throw new Exception((String) ManagementHelper.getResult(reply)); } } - else - { + else { return null; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/DivertControlTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/DivertControlTest.java index 6c86270364..fd8820505f 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/DivertControlTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/DivertControlTest.java @@ -29,8 +29,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class DivertControlTest extends ManagementTestBase -{ +public class DivertControlTest extends ManagementTestBase { // Constants ----------------------------------------------------- @@ -45,8 +44,7 @@ public class DivertControlTest extends ManagementTestBase // Public -------------------------------------------------------- @Test - public void testAttributes() throws Exception - { + public void testAttributes() throws Exception { checkResource(ObjectNameBuilder.DEFAULT.getDivertObjectName(divertConfig.getName())); DivertControl divertControl = createManagementControl(divertConfig.getName()); @@ -72,41 +70,23 @@ public class DivertControlTest extends ManagementTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - CoreQueueConfiguration queueConfig = new CoreQueueConfiguration() - .setAddress(RandomUtil.randomString()) - .setName(RandomUtil.randomString()) - .setDurable(false); - CoreQueueConfiguration forwardQueueConfig = new CoreQueueConfiguration() - .setAddress(RandomUtil.randomString()) - .setName(RandomUtil.randomString()) - .setDurable(false); + CoreQueueConfiguration queueConfig = new CoreQueueConfiguration().setAddress(RandomUtil.randomString()).setName(RandomUtil.randomString()).setDurable(false); + CoreQueueConfiguration forwardQueueConfig = new CoreQueueConfiguration().setAddress(RandomUtil.randomString()).setName(RandomUtil.randomString()).setDurable(false); - divertConfig = new DivertConfiguration() - .setName(RandomUtil.randomString()) - .setRoutingName(RandomUtil.randomString()) - .setAddress(queueConfig.getAddress()) - .setForwardingAddress(forwardQueueConfig.getAddress()) - .setExclusive(RandomUtil.randomBoolean()); + divertConfig = new DivertConfiguration().setName(RandomUtil.randomString()).setRoutingName(RandomUtil.randomString()).setAddress(queueConfig.getAddress()).setForwardingAddress(forwardQueueConfig.getAddress()).setExclusive(RandomUtil.randomBoolean()); TransportConfiguration connectorConfig = new TransportConfiguration(INVM_CONNECTOR_FACTORY); - Configuration config = createDefaultInVMConfig() - .setJMXManagementEnabled(true) - .addQueueConfiguration(queueConfig) - .addQueueConfiguration(forwardQueueConfig) - .addDivertConfiguration(divertConfig) - .addConnectorConfiguration(connectorConfig.getName(), connectorConfig); + Configuration config = createDefaultInVMConfig().setJMXManagementEnabled(true).addQueueConfiguration(queueConfig).addQueueConfiguration(forwardQueueConfig).addDivertConfiguration(divertConfig).addConnectorConfiguration(connectorConfig.getName(), connectorConfig); server = addServer(ActiveMQServers.newActiveMQServer(config, mbeanServer, false)); server.start(); } - protected DivertControl createManagementControl(final String name) throws Exception - { + protected DivertControl createManagementControl(final String name) throws Exception { return ManagementControlHelper.createDivertControl(name, mbeanServer); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/DivertControlUsingCoreTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/DivertControlUsingCoreTest.java index 99bf3577b2..62788be7d4 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/DivertControlUsingCoreTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/DivertControlUsingCoreTest.java @@ -23,8 +23,7 @@ import org.apache.activemq.artemis.api.core.management.DivertControl; import org.apache.activemq.artemis.api.core.management.ResourceNames; import org.junit.Before; -public class DivertControlUsingCoreTest extends DivertControlTest -{ +public class DivertControlUsingCoreTest extends DivertControlTest { // Constants ----------------------------------------------------- @@ -40,48 +39,39 @@ public class DivertControlUsingCoreTest extends DivertControlTest // DivertControlTest overrides -------------------------------- @Override - protected DivertControl createManagementControl(final String name) throws Exception - { + protected DivertControl createManagementControl(final String name) throws Exception { ClientSessionFactory sf = createSessionFactory(locator); session = sf.createSession(false, true, true); session.start(); - return new DivertControl() - { + return new DivertControl() { private final CoreMessagingProxy proxy = new CoreMessagingProxy(session, ResourceNames.CORE_DIVERT + name); - public String getAddress() - { + public String getAddress() { return (String) proxy.retrieveAttributeValue("address"); } - public String getFilter() - { + public String getFilter() { return (String) proxy.retrieveAttributeValue("filter"); } - public String getForwardingAddress() - { + public String getForwardingAddress() { return (String) proxy.retrieveAttributeValue("forwardingAddress"); } - public String getRoutingName() - { + public String getRoutingName() { return (String) proxy.retrieveAttributeValue("routingName"); } - public String getTransformerClassName() - { + public String getTransformerClassName() { return (String) proxy.retrieveAttributeValue("transformerClassName"); } - public String getUniqueName() - { + public String getUniqueName() { return (String) proxy.retrieveAttributeValue("uniqueName"); } - public boolean isExclusive() - { + public boolean isExclusive() { return (Boolean) proxy.retrieveAttributeValue("exclusive"); } @@ -94,11 +84,9 @@ public class DivertControlUsingCoreTest extends DivertControlTest // Protected ----------------------------------------------------- - @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = createInVMNonHALocator(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/JMXDomainTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/JMXDomainTest.java index 48777eb28b..86a9d02426 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/JMXDomainTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/JMXDomainTest.java @@ -29,24 +29,20 @@ import org.junit.Test; import java.util.HashMap; import java.util.Map; -public class JMXDomainTest extends ManagementTestBase -{ +public class JMXDomainTest extends ManagementTestBase { + ActiveMQServer server_0 = null; ActiveMQServer server_1 = null; @Test - public void test2ActiveMQServersManagedFrom1MBeanServer() throws Exception - { - Configuration config_0 = createDefaultInVMConfig() - .setJMXManagementEnabled(true); + public void test2ActiveMQServersManagedFrom1MBeanServer() throws Exception { + Configuration config_0 = createDefaultInVMConfig().setJMXManagementEnabled(true); String jmxDomain_1 = ActiveMQDefaultConfiguration.getDefaultJmxDomain() + ".1"; Map params = new HashMap(); params.put(TransportConstants.SERVER_ID_PROP_NAME, 1); - Configuration config_1 = createBasicConfig() - .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName(), params)) - .setJMXDomain(jmxDomain_1); + Configuration config_1 = createBasicConfig().addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName(), params)).setJMXDomain(jmxDomain_1); server_0 = addServer(ActiveMQServers.newActiveMQServer(config_0, mbeanServer, false)); server_1 = addServer(ActiveMQServers.newActiveMQServer(config_1, mbeanServer, false)); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementActivationTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementActivationTest.java index 339f761fad..5a538ff5b3 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementActivationTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementActivationTest.java @@ -39,21 +39,19 @@ import java.util.List; * then JMS management operations (e.g. create connection factory, create queue, etc.) should be stored in a cache * and then executed once the server becomes active. The normal use-case for this involves a live/backup pair. */ -public class ManagementActivationTest extends FailoverTestBase -{ +public class ManagementActivationTest extends FailoverTestBase { + private JMSServerManagerImpl backupJmsServer; private InVMNamingContext context; private String connectorName; @Override - protected TransportConfiguration getAcceptorTransportConfiguration(boolean live) - { + protected TransportConfiguration getAcceptorTransportConfiguration(boolean live) { return TransportConfigurationUtils.getInVMAcceptor(live); } @Override - protected TransportConfiguration getConnectorTransportConfiguration(boolean live) - { + protected TransportConfiguration getConnectorTransportConfiguration(boolean live) { TransportConfiguration inVMConnector = TransportConfigurationUtils.getInVMConnector(live); connectorName = inVMConnector.getName(); return inVMConnector; @@ -61,8 +59,7 @@ public class ManagementActivationTest extends FailoverTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); backupJmsServer = new JMSServerManagerImpl(backupServer.getServer()); context = new InVMNamingContext(); @@ -71,24 +68,18 @@ public class ManagementActivationTest extends FailoverTestBase } @Test - public void testCreateConnectionFactory() throws Exception - { + public void testCreateConnectionFactory() throws Exception { List connectorNames = new ArrayList(); connectorNames.add(connectorName); - ConnectionFactoryConfiguration config = new ConnectionFactoryConfigurationImpl() - .setName("test") - .setConnectorNames(connectorNames) - .setBindings("/myConnectionFactory"); + ConnectionFactoryConfiguration config = new ConnectionFactoryConfigurationImpl().setName("test").setConnectorNames(connectorNames).setBindings("/myConnectionFactory"); backupJmsServer.createConnectionFactory(true, config, "/myConnectionFactory"); boolean exception = false; - try - { + try { context.lookup("/myConnectionFactory"); } - catch (NameNotFoundException e) - { + catch (NameNotFoundException e) { exception = true; } @@ -99,22 +90,17 @@ public class ManagementActivationTest extends FailoverTestBase long timeout = System.currentTimeMillis() + 5000; ConnectionFactory factory = null; - while (timeout > System.currentTimeMillis()) - { - try - { + while (timeout > System.currentTimeMillis()) { + try { factory = (ConnectionFactory) context.lookup("/myConnectionFactory"); } - catch (Exception ignored) - { + catch (Exception ignored) { // ignored.printStackTrace(); } - if (factory == null) - { + if (factory == null) { Thread.sleep(100); } - else - { + else { break; } } @@ -123,17 +109,14 @@ public class ManagementActivationTest extends FailoverTestBase } @Test - public void testCreateQueue() throws Exception - { + public void testCreateQueue() throws Exception { backupJmsServer.createQueue(false, "myQueue", null, false, "/myQueue"); boolean exception = false; - try - { + try { context.lookup("/myQueue"); } - catch (NameNotFoundException e) - { + catch (NameNotFoundException e) { exception = true; } @@ -144,22 +127,17 @@ public class ManagementActivationTest extends FailoverTestBase long timeout = System.currentTimeMillis() + 5000; Queue queue = null; - while (timeout > System.currentTimeMillis()) - { - try - { + while (timeout > System.currentTimeMillis()) { + try { queue = (Queue) context.lookup("/myQueue"); } - catch (Exception ignored) - { + catch (Exception ignored) { // ignored.printStackTrace(); } - if (queue == null) - { + if (queue == null) { Thread.sleep(100); } - else - { + else { break; } } @@ -168,17 +146,14 @@ public class ManagementActivationTest extends FailoverTestBase } @Test - public void testCreateTopic() throws Exception - { + public void testCreateTopic() throws Exception { backupJmsServer.createTopic(false, "myTopic", "/myTopic"); boolean exception = false; - try - { + try { context.lookup("/myTopic"); } - catch (NameNotFoundException e) - { + catch (NameNotFoundException e) { exception = true; } @@ -189,22 +164,17 @@ public class ManagementActivationTest extends FailoverTestBase long timeout = System.currentTimeMillis() + 5000; Topic topic = null; - while (timeout > System.currentTimeMillis()) - { - try - { + while (timeout > System.currentTimeMillis()) { + try { topic = (Topic) context.lookup("/myTopic"); } - catch (Exception ignored) - { + catch (Exception ignored) { // ignored.printStackTrace(); } - if (topic == null) - { + if (topic == null) { Thread.sleep(100); } - else - { + else { break; } } @@ -219,19 +189,15 @@ public class ManagementActivationTest extends FailoverTestBase * @throws Exception */ @Test - public void testDestroyConnectionFactory() throws Exception - { + public void testDestroyConnectionFactory() throws Exception { // This test was deadlocking one in 10, so running it a couple times to make sure that won't happen any longer - for (int testrun = 0; testrun < 50; testrun++) - { + for (int testrun = 0; testrun < 50; testrun++) { boolean exception = false; - try - { + try { backupJmsServer.destroyConnectionFactory("fakeConnectionFactory"); } - catch (Exception e) - { + catch (Exception e) { exception = true; } @@ -249,15 +215,12 @@ public class ManagementActivationTest extends FailoverTestBase * @throws Exception */ @Test - public void testRemoveQueue() throws Exception - { + public void testRemoveQueue() throws Exception { boolean exception = false; - try - { + try { backupJmsServer.removeQueueFromBindingRegistry("fakeQueue"); } - catch (Exception e) - { + catch (Exception e) { exception = true; } @@ -271,20 +234,16 @@ public class ManagementActivationTest extends FailoverTestBase * @throws Exception */ @Test - public void testRemoveTopic() throws Exception - { + public void testRemoveTopic() throws Exception { boolean exception = false; - try - { + try { backupJmsServer.removeTopicFromBindingRegistry("fakeTopic"); } - catch (Exception e) - { + catch (Exception e) { exception = true; } assertFalse(exception); } - } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementControlHelper.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementControlHelper.java index 6a3c0353fe..10a9d55a70 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementControlHelper.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementControlHelper.java @@ -37,8 +37,7 @@ import org.apache.activemq.artemis.api.jms.management.JMSQueueControl; import org.apache.activemq.artemis.api.jms.management.JMSServerControl; import org.apache.activemq.artemis.api.jms.management.TopicControl; -public class ManagementControlHelper -{ +public class ManagementControlHelper { // Constants ----------------------------------------------------- @@ -46,98 +45,65 @@ public class ManagementControlHelper // Static -------------------------------------------------------- - public static AcceptorControl createAcceptorControl(final String name, final MBeanServer mbeanServer) throws Exception - { - return (AcceptorControl)ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getAcceptorObjectName(name), - AcceptorControl.class, - mbeanServer); + public static AcceptorControl createAcceptorControl(final String name, + final MBeanServer mbeanServer) throws Exception { + return (AcceptorControl) ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getAcceptorObjectName(name), AcceptorControl.class, mbeanServer); } - public static BroadcastGroupControl createBroadcastGroupControl(final String name, final MBeanServer mbeanServer) throws Exception - { - return (BroadcastGroupControl)ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getBroadcastGroupObjectName(name), - BroadcastGroupControl.class, - mbeanServer); + public static BroadcastGroupControl createBroadcastGroupControl(final String name, + final MBeanServer mbeanServer) throws Exception { + return (BroadcastGroupControl) ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getBroadcastGroupObjectName(name), BroadcastGroupControl.class, mbeanServer); } - public static BridgeControl createBridgeControl(final String name, final MBeanServer mbeanServer) throws Exception - { - return (BridgeControl)ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getBridgeObjectName(name), - BridgeControl.class, - mbeanServer); + public static BridgeControl createBridgeControl(final String name, final MBeanServer mbeanServer) throws Exception { + return (BridgeControl) ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getBridgeObjectName(name), BridgeControl.class, mbeanServer); } - public static DivertControl createDivertControl(final String name, final MBeanServer mbeanServer) throws Exception - { - return (DivertControl)ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getDivertObjectName(name), - DivertControl.class, - mbeanServer); + public static DivertControl createDivertControl(final String name, final MBeanServer mbeanServer) throws Exception { + return (DivertControl) ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getDivertObjectName(name), DivertControl.class, mbeanServer); } public static ClusterConnectionControl createClusterConnectionControl(final String name, - final MBeanServer mbeanServer) throws Exception - { - return (ClusterConnectionControl)ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getClusterConnectionObjectName(name), - ClusterConnectionControl.class, - mbeanServer); + final MBeanServer mbeanServer) throws Exception { + return (ClusterConnectionControl) ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getClusterConnectionObjectName(name), ClusterConnectionControl.class, mbeanServer); } - public static ActiveMQServerControl createActiveMQServerControl(final MBeanServer mbeanServer) throws Exception - { - return (ActiveMQServerControl)ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getActiveMQServerObjectName(), - ActiveMQServerControl.class, - mbeanServer); + public static ActiveMQServerControl createActiveMQServerControl(final MBeanServer mbeanServer) throws Exception { + return (ActiveMQServerControl) ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getActiveMQServerObjectName(), ActiveMQServerControl.class, mbeanServer); } public static QueueControl createQueueControl(final SimpleString address, final SimpleString name, - final MBeanServer mbeanServer) throws Exception - { - return (QueueControl)ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getQueueObjectName(address, - name), - QueueControl.class, - mbeanServer); + final MBeanServer mbeanServer) throws Exception { + return (QueueControl) ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getQueueObjectName(address, name), QueueControl.class, mbeanServer); } - public static AddressControl createAddressControl(final SimpleString address, final MBeanServer mbeanServer) throws Exception - { - return (AddressControl)ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getAddressObjectName(address), - AddressControl.class, - mbeanServer); + public static AddressControl createAddressControl(final SimpleString address, + final MBeanServer mbeanServer) throws Exception { + return (AddressControl) ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getAddressObjectName(address), AddressControl.class, mbeanServer); } - public static JMSQueueControl createJMSQueueControl(final Queue queue, final MBeanServer mbeanServer) throws Exception - { + public static JMSQueueControl createJMSQueueControl(final Queue queue, + final MBeanServer mbeanServer) throws Exception { return ManagementControlHelper.createJMSQueueControl(queue.getQueueName(), mbeanServer); } - public static JMSQueueControl createJMSQueueControl(final String name, final MBeanServer mbeanServer) throws Exception - { - return (JMSQueueControl)ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getJMSQueueObjectName(name), - JMSQueueControl.class, - mbeanServer); + public static JMSQueueControl createJMSQueueControl(final String name, + final MBeanServer mbeanServer) throws Exception { + return (JMSQueueControl) ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getJMSQueueObjectName(name), JMSQueueControl.class, mbeanServer); } - public static JMSServerControl createJMSServerControl(final MBeanServer mbeanServer) throws Exception - { - return (JMSServerControl)ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getJMSServerObjectName(), - JMSServerControl.class, - mbeanServer); + public static JMSServerControl createJMSServerControl(final MBeanServer mbeanServer) throws Exception { + return (JMSServerControl) ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getJMSServerObjectName(), JMSServerControl.class, mbeanServer); } public static ConnectionFactoryControl createConnectionFactoryControl(final String name, - final MBeanServer mbeanServer) throws Exception - { - return (ConnectionFactoryControl)ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getConnectionFactoryObjectName(name), - ConnectionFactoryControl.class, - mbeanServer); + final MBeanServer mbeanServer) throws Exception { + return (ConnectionFactoryControl) ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getConnectionFactoryObjectName(name), ConnectionFactoryControl.class, mbeanServer); } - public static TopicControl createTopicControl(final Topic topic, final MBeanServer mbeanServer) throws Exception - { - return (TopicControl)ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getJMSTopicObjectName(topic.getTopicName()), - TopicControl.class, - mbeanServer); + public static TopicControl createTopicControl(final Topic topic, final MBeanServer mbeanServer) throws Exception { + return (TopicControl) ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getJMSTopicObjectName(topic.getTopicName()), TopicControl.class, mbeanServer); } // Constructors -------------------------------------------------- @@ -152,8 +118,7 @@ public class ManagementControlHelper private static Object createProxy(final ObjectName objectName, final Class mbeanInterface, - final MBeanServer mbeanServer) - { + final MBeanServer mbeanServer) { return MBeanServerInvocationHandler.newProxyInstance(mbeanServer, objectName, mbeanInterface, false); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementHelperTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementHelperTest.java index 7f8602be25..16839e0372 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementHelperTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementHelperTest.java @@ -28,8 +28,7 @@ import org.apache.activemq.artemis.tests.util.RandomUtil; import org.junit.Assert; import org.junit.Test; -public class ManagementHelperTest extends Assert -{ +public class ManagementHelperTest extends Assert { // Constants ----------------------------------------------------- @@ -44,8 +43,7 @@ public class ManagementHelperTest extends Assert // Public -------------------------------------------------------- @Test - public void testArrayOfStringParameter() throws Exception - { + public void testArrayOfStringParameter() throws Exception { String resource = RandomUtil.randomString(); String operationName = RandomUtil.randomString(); String param = RandomUtil.randomString(); @@ -61,15 +59,13 @@ public class ManagementHelperTest extends Assert Assert.assertTrue(parameter_2 instanceof Object[]); Object[] retrievedParams = (Object[]) parameter_2; Assert.assertEquals(params.length, retrievedParams.length); - for (int i = 0; i < retrievedParams.length; i++) - { + for (int i = 0; i < retrievedParams.length; i++) { Assert.assertEquals(params[i], retrievedParams[i]); } } @Test - public void testParams() throws Exception - { + public void testParams() throws Exception { String resource = RandomUtil.randomString(); String operationName = RandomUtil.randomString(); @@ -185,8 +181,7 @@ public class ManagementHelperTest extends Assert } @Test - public void testMapWithArrayValues() throws Exception - { + public void testMapWithArrayValues() throws Exception { String resource = RandomUtil.randomString(); String operationName = RandomUtil.randomString(); @@ -233,8 +228,7 @@ public class ManagementHelperTest extends Assert } @Test - public void testFromCommaSeparatedKeyValues() throws Exception - { + public void testFromCommaSeparatedKeyValues() throws Exception { String str = "key1=1, key2=false, key3=2.0, key4=whatever"; Map map = ManagementHelper.fromCommaSeparatedKeyValues(str); @@ -253,8 +247,7 @@ public class ManagementHelperTest extends Assert } @Test - public void testFromCommaSeparatedArrayOfCommaSeparatedKeyValuesForSingleItem() throws Exception - { + public void testFromCommaSeparatedArrayOfCommaSeparatedKeyValuesForSingleItem() throws Exception { // if there is a single item, no need to enclose it in { } String str = "k11=1, k12=false, k13=2.0, k14=whatever "; @@ -278,8 +271,7 @@ public class ManagementHelperTest extends Assert } @Test - public void testFromCommaSeparatedArrayOfCommaSeparatedKeyValues() throws Exception - { + public void testFromCommaSeparatedArrayOfCommaSeparatedKeyValues() throws Exception { String str = "{ k11=1, k12=false, k13=2.0, k14=whatever },{ k21=2, k22=true, k23=23.0, k24=foo }"; Object[] objects = ManagementHelper.fromCommaSeparatedArrayOfCommaSeparatedKeyValues(str); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementServiceImplTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementServiceImplTest.java index 309dfd7193..cc33b44465 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementServiceImplTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementServiceImplTest.java @@ -38,16 +38,14 @@ import org.apache.activemq.artemis.core.server.management.impl.ManagementService import org.apache.activemq.artemis.tests.integration.server.FakeStorageManager; import org.apache.activemq.artemis.tests.util.RandomUtil; -public class ManagementServiceImplTest extends ActiveMQTestBase -{ +public class ManagementServiceImplTest extends ActiveMQTestBase { + @Test - public void testHandleManagementMessageWithOperation() throws Exception - { + public void testHandleManagementMessageWithOperation() throws Exception { String queue = RandomUtil.randomString(); String address = RandomUtil.randomString(); - Configuration config = createBasicConfig() - .setJMXManagementEnabled(false); + Configuration config = createBasicConfig().setJMXManagementEnabled(false); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false)); server.start(); @@ -62,10 +60,8 @@ public class ManagementServiceImplTest extends ActiveMQTestBase } @Test - public void testHandleManagementMessageWithOperationWhichFails() throws Exception - { - Configuration config = createBasicConfig() - .setJMXManagementEnabled(false); + public void testHandleManagementMessageWithOperationWhichFails() throws Exception { + Configuration config = createBasicConfig().setJMXManagementEnabled(false); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false)); server.start(); @@ -81,10 +77,8 @@ public class ManagementServiceImplTest extends ActiveMQTestBase } @Test - public void testHandleManagementMessageWithUnknowResource() throws Exception - { - Configuration config = createBasicConfig() - .setJMXManagementEnabled(false); + public void testHandleManagementMessageWithUnknowResource() throws Exception { + Configuration config = createBasicConfig().setJMXManagementEnabled(false); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false)); server.start(); @@ -100,10 +94,8 @@ public class ManagementServiceImplTest extends ActiveMQTestBase } @Test - public void testHandleManagementMessageWithUnknownAttribute() throws Exception - { - Configuration config = createBasicConfig() - .setJMXManagementEnabled(false); + public void testHandleManagementMessageWithUnknownAttribute() throws Exception { + Configuration config = createBasicConfig().setJMXManagementEnabled(false); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false)); server.start(); @@ -120,10 +112,8 @@ public class ManagementServiceImplTest extends ActiveMQTestBase } @Test - public void testHandleManagementMessageWithKnownAttribute() throws Exception - { - Configuration config = createBasicConfig() - .setJMXManagementEnabled(false); + public void testHandleManagementMessageWithKnownAttribute() throws Exception { + Configuration config = createBasicConfig().setJMXManagementEnabled(false); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false)); server.start(); @@ -140,10 +130,8 @@ public class ManagementServiceImplTest extends ActiveMQTestBase } @Test - public void testGetResources() throws Exception - { - Configuration config = createBasicConfig() - .setJMXManagementEnabled(false); + public void testGetResources() throws Exception { + Configuration config = createBasicConfig().setJMXManagementEnabled(false); ManagementServiceImpl managementService = new ManagementServiceImpl(null, config); managementService.setStorageManager(new NullStorageManager()); @@ -155,13 +143,13 @@ public class ManagementServiceImplTest extends ActiveMQTestBase Object[] addresses = managementService.getResources(AddressControl.class); Assert.assertEquals(1, addresses.length); Assert.assertTrue(addresses[0] instanceof AddressControl); - AddressControl addressControl = (AddressControl)addresses[0]; + AddressControl addressControl = (AddressControl) addresses[0]; Assert.assertEquals(address.toString(), addressControl.getAddress()); Object[] queues = managementService.getResources(QueueControl.class); Assert.assertEquals(1, queues.length); Assert.assertTrue(queues[0] instanceof QueueControl); - QueueControl queueControl = (QueueControl)queues[0]; + QueueControl queueControl = (QueueControl) queues[0]; Assert.assertEquals(queue.getName().toString(), queueControl.getName()); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementTestBase.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementTestBase.java index f62a302097..a3bc00b30d 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementTestBase.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementTestBase.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.management; + import org.apache.activemq.artemis.api.core.management.QueueControl; import org.apache.activemq.artemis.api.jms.management.JMSQueueControl; import org.junit.Before; @@ -32,8 +33,7 @@ import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -public abstract class ManagementTestBase extends ActiveMQTestBase -{ +public abstract class ManagementTestBase extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -43,15 +43,14 @@ public abstract class ManagementTestBase extends ActiveMQTestBase // Static -------------------------------------------------------- - protected static void consumeMessages(final int expected, final ClientSession session, final SimpleString queue) throws Exception - { + protected static void consumeMessages(final int expected, + final ClientSession session, + final SimpleString queue) throws Exception { ClientConsumer consumer = null; - try - { + try { consumer = session.createConsumer(queue); ClientMessage m = null; - for (int i = 0; i < expected; i++) - { + for (int i = 0; i < expected; i++) { m = consumer.receive(500); Assert.assertNotNull("expected to received " + expected + " messages, got only " + i, m); m.acknowledge(); @@ -60,10 +59,8 @@ public abstract class ManagementTestBase extends ActiveMQTestBase m = consumer.receiveImmediate(); Assert.assertNull("received one more message than expected (" + expected + ")", m); } - finally - { - if (consumer != null) - { + finally { + if (consumer != null) { consumer.close(); } } @@ -79,8 +76,7 @@ public abstract class ManagementTestBase extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); mbeanServer = MBeanServerFactory.createMBeanServer(); @@ -88,54 +84,46 @@ public abstract class ManagementTestBase extends ActiveMQTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { MBeanServerFactory.releaseMBeanServer(mbeanServer); super.tearDown(); } - protected void checkNoResource(final ObjectName on) - { + protected void checkNoResource(final ObjectName on) { Assert.assertFalse("unexpected resource for " + on, mbeanServer.isRegistered(on)); } - protected void checkResource(final ObjectName on) - { + protected void checkResource(final ObjectName on) { Assert.assertTrue("no resource for " + on, mbeanServer.isRegistered(on)); } - protected QueueControl createManagementControl(final String address, final String queue) throws Exception - { + protected QueueControl createManagementControl(final String address, final String queue) throws Exception { return createManagementControl(SimpleString.toSimpleString(address), SimpleString.toSimpleString(queue)); } - protected QueueControl createManagementControl(final SimpleString address, final SimpleString queue) throws Exception - { + protected QueueControl createManagementControl(final SimpleString address, + final SimpleString queue) throws Exception { QueueControl queueControl = ManagementControlHelper.createQueueControl(address, queue, mbeanServer); return queueControl; } - protected long getMessageCount(JMSQueueControl control) throws Exception - { + protected long getMessageCount(JMSQueueControl control) throws Exception { control.flushExecutor(); return control.getMessageCount(); } - protected long getMessagesAdded(JMSQueueControl control) throws Exception - { + protected long getMessagesAdded(JMSQueueControl control) throws Exception { control.flushExecutor(); return control.getMessagesAdded(); } - protected long getMessageCount(QueueControl control) throws Exception - { + protected long getMessageCount(QueueControl control) throws Exception { control.flushExecutor(); return control.getMessageCount(); } - protected long getMessagesAdded(QueueControl control) throws Exception - { + protected long getMessagesAdded(QueueControl control) throws Exception { control.flushExecutor(); return control.getMessagesAdded(); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementWithPagingServerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementWithPagingServerTest.java index e5bd67892d..26db0d617a 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementWithPagingServerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementWithPagingServerTest.java @@ -43,16 +43,15 @@ import java.nio.ByteBuffer; * functionalities that are affected by a server * in paging mode. */ -public class ManagementWithPagingServerTest extends ManagementTestBase -{ +public class ManagementWithPagingServerTest extends ManagementTestBase { + private ActiveMQServer server; private ClientSession session1; private ClientSession session2; private ServerLocator locator; @Test - public void testListMessagesAsJSON() throws Exception - { + public void testListMessagesAsJSON() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -87,7 +86,6 @@ public class ManagementWithPagingServerTest extends ManagementTestBase receiver.join(); assertNull(receiver.getError()); - result = queueControl.listMessagesAsJSON(null); array = new JSONArray(result); @@ -96,8 +94,7 @@ public class ManagementWithPagingServerTest extends ManagementTestBase } @Test - public void testListMessagesAsJSONWithFilter() throws Exception - { + public void testListMessagesAsJSONWithFilter() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -114,21 +111,17 @@ public class ManagementWithPagingServerTest extends ManagementTestBase byte[] body = new byte[64]; ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= 64; j++) - { + for (int j = 1; j <= 64; j++) { bb.put(getSamplebyte(j)); } ClientProducer producer = session1.createProducer(address); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { ClientMessage message = session1.createMessage(true); - if (i % 2 == 0) - { + if (i % 2 == 0) { message.putLongProperty(key, matchingValue); } - else - { + else { message.putLongProperty(key, unmatchingValue); } producer.send(message); @@ -154,8 +147,7 @@ public class ManagementWithPagingServerTest extends ManagementTestBase //of the api doesn't cause any exceptions during internal queue //message iteration. @Test - public void testListMessagesAsJSONWhilePagingOnGoing() throws Exception - { + public void testListMessagesAsJSONWhilePagingOnGoing() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -194,27 +186,20 @@ public class ManagementWithPagingServerTest extends ManagementTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - Configuration config = createDefaultInVMConfig() - .setJMXManagementEnabled(true); + Configuration config = createDefaultInVMConfig().setJMXManagementEnabled(true); server = addServer(ActiveMQServers.newActiveMQServer(config, mbeanServer, true)); - AddressSettings defaultSetting = new AddressSettings() - .setPageSizeBytes(5120) - .setMaxSizeBytes(10240) - .setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE); + AddressSettings defaultSetting = new AddressSettings().setPageSizeBytes(5120).setMaxSizeBytes(10240).setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE); server.getAddressSettingsRepository().addMatch("#", defaultSetting); server.start(); - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(false) - .setConsumerWindowSize(0); + locator = createInVMNonHALocator().setBlockOnNonDurableSend(false).setConsumerWindowSize(0); ClientSessionFactory sf = createSessionFactory(locator); session1 = sf.createSession(false, true, false); session1.start(); @@ -222,156 +207,130 @@ public class ManagementWithPagingServerTest extends ManagementTestBase session2.start(); } - private class SenderThread extends Thread - { + private class SenderThread extends Thread { + private SimpleString address; private int num; private long delay; private volatile Exception error = null; - public SenderThread(SimpleString address, int num, long delay) - { + public SenderThread(SimpleString address, int num, long delay) { this.address = address; this.num = num; this.delay = delay; } @Override - public void run() - { + public void run() { ClientProducer producer; byte[] body = new byte[128]; ByteBuffer bb = ByteBuffer.wrap(body); - for (int j = 1; j <= 128; j++) - { + for (int j = 1; j <= 128; j++) { bb.put(getSamplebyte(j)); } - try - { + try { producer = session1.createProducer(address); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { ClientMessage message = session1.createMessage(true); ActiveMQBuffer buffer = message.getBodyBuffer(); buffer.writeBytes(body); producer.send(message); - try - { + try { Thread.sleep(delay); } - catch (InterruptedException e) - { + catch (InterruptedException e) { //ignore } } } - catch (Exception e) - { + catch (Exception e) { error = e; } } - public Exception getError() - { + public Exception getError() { return this.error; } } - private class ReceiverThread extends Thread - { + private class ReceiverThread extends Thread { + private SimpleString queue; private int num; private long delay; private volatile Exception error = null; - public ReceiverThread(SimpleString queue, int num, long delay) - { + public ReceiverThread(SimpleString queue, int num, long delay) { this.queue = queue; this.num = num; this.delay = delay; } @Override - public void run() - { + public void run() { ClientConsumer consumer; - try - { + try { consumer = session2.createConsumer(queue); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { ClientMessage message = consumer.receive(5000); message.acknowledge(); session2.commit(); - try - { + try { Thread.sleep(delay); } - catch (InterruptedException e) - { + catch (InterruptedException e) { //ignore } } } - catch (Exception e) - { + catch (Exception e) { error = e; } } - public Exception getError() - { + public Exception getError() { return this.error; } } - private class ManagementThread extends Thread - { + private class ManagementThread extends Thread { + private QueueControl queueControl; private volatile boolean stop = false; private Exception error = null; - public ManagementThread(QueueControl queueControl) - { + public ManagementThread(QueueControl queueControl) { this.queueControl = queueControl; } @Override - public void run() - { - try - { - while (!stop) - { + public void run() { + try { + while (!stop) { queueControl.countMessages(null); queueControl.listMessagesAsJSON(null); - try - { + try { Thread.sleep(1000); } - catch (InterruptedException e) - { + catch (InterruptedException e) { //ignore } } } - catch (Exception e) - { + catch (Exception e) { error = e; } } - public Exception getError() - { + public Exception getError() { return error; } - public void exit() - { + public void exit() { stop = true; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementWithStompTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementWithStompTest.java index 6bec99913c..1816d00ae8 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementWithStompTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementWithStompTest.java @@ -44,8 +44,7 @@ import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; -public class ManagementWithStompTest extends ManagementTestBase -{ +public class ManagementWithStompTest extends ManagementTestBase { // Constants ----------------------------------------------------- @@ -65,10 +64,8 @@ public class ManagementWithStompTest extends ManagementTestBase // Public -------------------------------------------------------- - @Test - public void testGetManagementAttributeFromStomp() throws Exception - { + public void testGetManagementAttributeFromStomp() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -85,10 +82,10 @@ public class ManagementWithStompTest extends ManagementTestBase // retrieve the address of the queue frame = "\nSEND\n" + "destination:" + ActiveMQDefaultConfiguration.getDefaultManagementAddress() + "\n" + - "reply-to:" + address + "\n" + - "_AMQ_ResourceName:" + ResourceNames.CORE_QUEUE + queue + "\n" + - "_AMQ_Attribute: Address\n\n" + - Stomp.NULL; + "reply-to:" + address + "\n" + + "_AMQ_ResourceName:" + ResourceNames.CORE_QUEUE + queue + "\n" + + "_AMQ_Attribute: Address\n\n" + + Stomp.NULL; sendFrame(frame); frame = receiveFrame(10000); @@ -110,8 +107,7 @@ public class ManagementWithStompTest extends ManagementTestBase } @Test - public void testInvokeOperationFromStomp() throws Exception - { + public void testInvokeOperationFromStomp() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -128,11 +124,11 @@ public class ManagementWithStompTest extends ManagementTestBase // count number of message with filter "color = 'blue'" frame = "\nSEND\n" + "destination:" + ActiveMQDefaultConfiguration.getDefaultManagementAddress() + "\n" + - "reply-to:" + address + "\n" + - "_AMQ_ResourceName:" + ResourceNames.CORE_QUEUE + queue + "\n" + - "_AMQ_OperationName: countMessages\n\n" + - "[\"color = 'blue'\"]" + - Stomp.NULL; + "reply-to:" + address + "\n" + + "_AMQ_ResourceName:" + ResourceNames.CORE_QUEUE + queue + "\n" + + "_AMQ_OperationName: countMessages\n\n" + + "[\"color = 'blue'\"]" + + Stomp.NULL; sendFrame(frame); frame = receiveFrame(10000); @@ -161,8 +157,7 @@ public class ManagementWithStompTest extends ManagementTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); Map params = new HashMap(); @@ -170,15 +165,13 @@ public class ManagementWithStompTest extends ManagementTestBase params.put(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_STOMP_PORT); TransportConfiguration stompTransport = new TransportConfiguration(NettyAcceptorFactory.class.getName(), params); - Configuration config = createDefaultInVMConfig() - .addAcceptorConfiguration(stompTransport); + Configuration config = createDefaultInVMConfig().addAcceptorConfiguration(stompTransport); server = addServer(ActiveMQServers.newActiveMQServer(config, mbeanServer, false, "brianm", "wombats")); server.start(); - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true); + locator = createInVMNonHALocator().setBlockOnNonDurableSend(true); ClientSessionFactory sf = createSessionFactory(locator); session = sf.createSession(false, true, false); session.start(); @@ -189,34 +182,27 @@ public class ManagementWithStompTest extends ManagementTestBase // Private ------------------------------------------------------- - public void sendFrame(String data) throws Exception - { + public void sendFrame(String data) throws Exception { byte[] bytes = data.getBytes(StandardCharsets.UTF_8); OutputStream outputStream = stompSocket.getOutputStream(); - for (int i = 0; i < bytes.length; i++) - { + for (int i = 0; i < bytes.length; i++) { outputStream.write(bytes[i]); } outputStream.flush(); } - public String receiveFrame(long timeOut) throws Exception - { - stompSocket.setSoTimeout((int)timeOut); + public String receiveFrame(long timeOut) throws Exception { + stompSocket.setSoTimeout((int) timeOut); InputStream is = stompSocket.getInputStream(); int c = 0; - for (;;) - { + for (;;) { c = is.read(); - if (c < 0) - { + if (c < 0) { throw new IOException("socket closed."); } - else if (c == 0) - { + else if (c == 0) { c = is.read(); - if (c != '\n') - { + if (c != '\n') { byte[] ba = inputBuffer.toByteArray(); System.out.println(new String(ba, StandardCharsets.UTF_8)); } @@ -225,15 +211,13 @@ public class ManagementWithStompTest extends ManagementTestBase inputBuffer.reset(); return new String(ba, StandardCharsets.UTF_8); } - else - { + else { inputBuffer.write(c); } } } - protected void waitForReceipt() throws Exception - { + protected void waitForReceipt() throws Exception { String frame = receiveFrame(50000); Assert.assertNotNull(frame); Assert.assertTrue(frame.indexOf("RECEIPT") > -1); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/NotificationTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/NotificationTest.java index 1513853c03..a5a66955d8 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/NotificationTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/NotificationTest.java @@ -39,8 +39,7 @@ import static org.apache.activemq.artemis.api.core.management.CoreNotificationTy import static org.apache.activemq.artemis.api.core.management.CoreNotificationType.CONSUMER_CLOSED; import static org.apache.activemq.artemis.api.core.management.CoreNotificationType.CONSUMER_CREATED; -public class NotificationTest extends ActiveMQTestBase -{ +public class NotificationTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -62,8 +61,7 @@ public class NotificationTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testBINDING_ADDED() throws Exception - { + public void testBINDING_ADDED() throws Exception { SimpleString queue = RandomUtil.randomSimpleString(); SimpleString address = RandomUtil.randomSimpleString(); boolean durable = RandomUtil.randomBoolean(); @@ -73,19 +71,15 @@ public class NotificationTest extends ActiveMQTestBase session.createQueue(address, queue, durable); ClientMessage[] notifications = NotificationTest.consumeMessages(1, notifConsumer); - Assert.assertEquals(BINDING_ADDED.toString(), - notifications[0].getObjectProperty(ManagementHelper.HDR_NOTIFICATION_TYPE).toString()); - Assert.assertEquals(queue.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_ROUTING_NAME) - .toString()); - Assert.assertEquals(address.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_ADDRESS) - .toString()); + Assert.assertEquals(BINDING_ADDED.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_NOTIFICATION_TYPE).toString()); + Assert.assertEquals(queue.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_ROUTING_NAME).toString()); + Assert.assertEquals(address.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_ADDRESS).toString()); session.deleteQueue(queue); } @Test - public void testBINDING_ADDEDWithMatchingFilter() throws Exception - { + public void testBINDING_ADDEDWithMatchingFilter() throws Exception { SimpleString queue = RandomUtil.randomSimpleString(); SimpleString address = RandomUtil.randomSimpleString(); boolean durable = RandomUtil.randomBoolean(); @@ -100,19 +94,15 @@ public class NotificationTest extends ActiveMQTestBase session.createQueue(address, queue, durable); ClientMessage[] notifications = NotificationTest.consumeMessages(1, notifConsumer); - Assert.assertEquals(BINDING_ADDED.toString(), - notifications[0].getObjectProperty(ManagementHelper.HDR_NOTIFICATION_TYPE).toString()); - Assert.assertEquals(queue.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_ROUTING_NAME) - .toString()); - Assert.assertEquals(address.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_ADDRESS) - .toString()); + Assert.assertEquals(BINDING_ADDED.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_NOTIFICATION_TYPE).toString()); + Assert.assertEquals(queue.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_ROUTING_NAME).toString()); + Assert.assertEquals(address.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_ADDRESS).toString()); session.deleteQueue(queue); } @Test - public void testBINDING_ADDEDWithNonMatchingFilter() throws Exception - { + public void testBINDING_ADDEDWithNonMatchingFilter() throws Exception { SimpleString queue = RandomUtil.randomSimpleString(); SimpleString address = RandomUtil.randomSimpleString(); boolean durable = RandomUtil.randomBoolean(); @@ -132,8 +122,7 @@ public class NotificationTest extends ActiveMQTestBase } @Test - public void testBINDING_REMOVED() throws Exception - { + public void testBINDING_REMOVED() throws Exception { SimpleString queue = RandomUtil.randomSimpleString(); SimpleString address = RandomUtil.randomSimpleString(); boolean durable = RandomUtil.randomBoolean(); @@ -145,25 +134,15 @@ public class NotificationTest extends ActiveMQTestBase session.deleteQueue(queue); ClientMessage[] notifications = NotificationTest.consumeMessages(1, notifConsumer); - Assert.assertEquals(BINDING_REMOVED.toString(), - notifications[0].getObjectProperty(ManagementHelper.HDR_NOTIFICATION_TYPE).toString()); - Assert.assertEquals(queue.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_ROUTING_NAME) - .toString()); - Assert.assertEquals(address.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_ADDRESS) - .toString()); + Assert.assertEquals(BINDING_REMOVED.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_NOTIFICATION_TYPE).toString()); + Assert.assertEquals(queue.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_ROUTING_NAME).toString()); + Assert.assertEquals(address.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_ADDRESS).toString()); } @Test - public void testCONSUMER_CREATED() throws Exception - { + public void testCONSUMER_CREATED() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); - ClientSession mySession = sf.createSession("myUser", - "myPassword", - false, - true, - true, - locator.isPreAcknowledge(), - locator.getAckBatchSize()); + ClientSession mySession = sf.createSession("myUser", "myPassword", false, true, true, locator.isPreAcknowledge(), locator.getAckBatchSize()); mySession.start(); @@ -179,12 +158,9 @@ public class NotificationTest extends ActiveMQTestBase SimpleString consumerName = SimpleString.toSimpleString(((ClientSessionInternal) mySession).getName()); ClientMessage[] notifications = NotificationTest.consumeMessages(1, notifConsumer); - Assert.assertEquals(CONSUMER_CREATED.toString(), - notifications[0].getObjectProperty(ManagementHelper.HDR_NOTIFICATION_TYPE).toString()); - Assert.assertEquals(queue.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_ROUTING_NAME) - .toString()); - Assert.assertEquals(address.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_ADDRESS) - .toString()); + Assert.assertEquals(CONSUMER_CREATED.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_NOTIFICATION_TYPE).toString()); + Assert.assertEquals(queue.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_ROUTING_NAME).toString()); + Assert.assertEquals(address.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_ADDRESS).toString()); Assert.assertEquals(1, notifications[0].getObjectProperty(ManagementHelper.HDR_CONSUMER_COUNT)); Assert.assertEquals(SimpleString.toSimpleString("myUser"), notifications[0].getSimpleStringProperty(ManagementHelper.HDR_USER)); Assert.assertEquals(SimpleString.toSimpleString("invm:0"), notifications[0].getSimpleStringProperty(ManagementHelper.HDR_REMOTE_ADDRESS)); @@ -195,16 +171,9 @@ public class NotificationTest extends ActiveMQTestBase } @Test - public void testCONSUMER_CLOSED() throws Exception - { + public void testCONSUMER_CLOSED() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); - ClientSession mySession = sf.createSession("myUser", - "myPassword", - false, - true, - true, - locator.isPreAcknowledge(), - locator.getAckBatchSize()); + ClientSession mySession = sf.createSession("myUser", "myPassword", false, true, true, locator.isPreAcknowledge(), locator.getAckBatchSize()); mySession.start(); @@ -221,12 +190,9 @@ public class NotificationTest extends ActiveMQTestBase consumer.close(); ClientMessage[] notifications = NotificationTest.consumeMessages(1, notifConsumer); - Assert.assertEquals(CONSUMER_CLOSED.toString(), - notifications[0].getObjectProperty(ManagementHelper.HDR_NOTIFICATION_TYPE).toString()); - Assert.assertEquals(queue.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_ROUTING_NAME) - .toString()); - Assert.assertEquals(address.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_ADDRESS) - .toString()); + Assert.assertEquals(CONSUMER_CLOSED.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_NOTIFICATION_TYPE).toString()); + Assert.assertEquals(queue.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_ROUTING_NAME).toString()); + Assert.assertEquals(address.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_ADDRESS).toString()); Assert.assertEquals(0, notifications[0].getObjectProperty(ManagementHelper.HDR_CONSUMER_COUNT)); Assert.assertEquals(SimpleString.toSimpleString("myUser"), notifications[0].getSimpleStringProperty(ManagementHelper.HDR_USER)); Assert.assertEquals(SimpleString.toSimpleString("invm:0"), notifications[0].getSimpleStringProperty(ManagementHelper.HDR_REMOTE_ADDRESS)); @@ -241,8 +207,7 @@ public class NotificationTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = addServer(ActiveMQServers.newActiveMQServer(createDefaultInVMConfig(), false)); @@ -262,28 +227,22 @@ public class NotificationTest extends ActiveMQTestBase // Private ------------------------------------------------------- - private static void flush(final ClientConsumer notifConsumer) throws ActiveMQException - { + private static void flush(final ClientConsumer notifConsumer) throws ActiveMQException { ClientMessage message = null; - do - { + do { message = notifConsumer.receive(500); - } - while (message != null); + } while (message != null); } - protected static ClientMessage[] consumeMessages(final int expected, final ClientConsumer consumer) throws Exception - { + protected static ClientMessage[] consumeMessages(final int expected, + final ClientConsumer consumer) throws Exception { ClientMessage[] messages = new ClientMessage[expected]; ClientMessage m = null; - for (int i = 0; i < expected; i++) - { + for (int i = 0; i < expected; i++) { m = consumer.receive(500); - if (m != null) - { - for (SimpleString key : m.getPropertyNames()) - { + if (m != null) { + for (SimpleString key : m.getPropertyNames()) { System.out.println(key + "=" + m.getObjectProperty(key)); } } @@ -292,11 +251,8 @@ public class NotificationTest extends ActiveMQTestBase m.acknowledge(); } m = consumer.receiveImmediate(); - if (m != null) - { - for (SimpleString key : m.getPropertyNames()) - - { + if (m != null) { + for (SimpleString key : m.getPropertyNames()) { System.out.println(key + "=" + m.getObjectProperty(key)); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/QueueControlTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/QueueControlTest.java index 94f1f92f7d..0de4047de7 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/QueueControlTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/QueueControlTest.java @@ -52,16 +52,14 @@ import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -public class QueueControlTest extends ManagementTestBase -{ +public class QueueControlTest extends ManagementTestBase { private ActiveMQServer server; private ClientSession session; private ServerLocator locator; @Test - public void testAttributes() throws Exception - { + public void testAttributes() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); SimpleString filter = new SimpleString("color = 'blue'"); @@ -80,8 +78,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testGetNullFilter() throws Exception - { + public void testGetNullFilter() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -95,8 +92,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testGetDeadLetterAddress() throws Exception - { + public void testGetDeadLetterAddress() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); final SimpleString deadLetterAddress = RandomUtil.randomSimpleString(); @@ -106,13 +102,11 @@ public class QueueControlTest extends ManagementTestBase QueueControl queueControl = createManagementControl(address, queue); Assert.assertNull(queueControl.getDeadLetterAddress()); - server.getAddressSettingsRepository().addMatch(address.toString(), new AddressSettings() - { + server.getAddressSettingsRepository().addMatch(address.toString(), new AddressSettings() { private static final long serialVersionUID = -4919035864731465338L; @Override - public SimpleString getDeadLetterAddress() - { + public SimpleString getDeadLetterAddress() { return deadLetterAddress; } }); @@ -123,8 +117,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testSetDeadLetterAddress() throws Exception - { + public void testSetDeadLetterAddress() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); String deadLetterAddress = RandomUtil.randomString(); @@ -142,8 +135,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testGetExpiryAddress() throws Exception - { + public void testGetExpiryAddress() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); final SimpleString expiryAddress = RandomUtil.randomSimpleString(); @@ -153,13 +145,11 @@ public class QueueControlTest extends ManagementTestBase QueueControl queueControl = createManagementControl(address, queue); Assert.assertNull(queueControl.getExpiryAddress()); - server.getAddressSettingsRepository().addMatch(address.toString(), new AddressSettings() - { + server.getAddressSettingsRepository().addMatch(address.toString(), new AddressSettings() { private static final long serialVersionUID = 6745306517827764680L; @Override - public SimpleString getExpiryAddress() - { + public SimpleString getExpiryAddress() { return expiryAddress; } }); @@ -170,8 +160,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testSetExpiryAddress() throws Exception - { + public void testSetExpiryAddress() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); String expiryAddress = RandomUtil.randomString(); @@ -192,8 +181,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testGetConsumerCount() throws Exception - { + public void testGetConsumerCount() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -213,8 +201,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testGetConsumerJSON() throws Exception - { + public void testGetConsumerJSON() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -244,8 +231,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testGetMessageCount() throws Exception - { + public void testGetMessageCount() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -266,8 +252,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testGetFirstMessage() throws Exception - { + public void testGetFirstMessage() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -298,8 +283,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testGetMessagesAdded() throws Exception - { + public void testGetMessagesAdded() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -322,8 +306,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testGetMessagesAcknowledged() throws Exception - { + public void testGetMessagesAcknowledged() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -340,16 +323,15 @@ public class QueueControlTest extends ManagementTestBase consumeMessages(1, session, queue); Assert.assertEquals(2, queueControl.getMessagesAcknowledged()); -// ManagementTestBase.consumeMessages(2, session, queue); + // ManagementTestBase.consumeMessages(2, session, queue); -// Assert.assertEquals(2, getMessagesAdded(queueControl)); + // Assert.assertEquals(2, getMessagesAdded(queueControl)); session.deleteQueue(queue); } @Test - public void testGetScheduledCount() throws Exception - { + public void testGetScheduledCount() throws Exception { long delay = 500; SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -365,8 +347,7 @@ public class QueueControlTest extends ManagementTestBase producer.send(message); long timeout = System.currentTimeMillis() + 5000; - while (timeout > System.currentTimeMillis() && queueControl.getScheduledCount() != 1) - { + while (timeout > System.currentTimeMillis() && queueControl.getScheduledCount() != 1) { Thread.sleep(100); } @@ -383,20 +364,15 @@ public class QueueControlTest extends ManagementTestBase //https://issues.jboss.org/browse/HORNETQ-1231 @Test - public void testListDeliveringMessagesWithRASession() throws Exception - { - ServerLocator locator1 = createInVMNonHALocator() - .setBlockOnNonDurableSend(true) - .setConsumerWindowSize(10240) - .setAckBatchSize(0); + public void testListDeliveringMessagesWithRASession() throws Exception { + ServerLocator locator1 = createInVMNonHALocator().setBlockOnNonDurableSend(true).setConsumerWindowSize(10240).setAckBatchSize(0); ClientSessionFactory sf = locator1.createSessionFactory(); final ClientSession transSession = sf.createSession(false, true, false); ClientConsumer consumer = null; SimpleString queue = null; int numMsg = 10; - try - { + try { // a session from RA does this transSession.addMetaData("resource-adapter", "inbound"); transSession.addMetaData("jms-session", ""); @@ -410,8 +386,7 @@ public class QueueControlTest extends ManagementTestBase ClientProducer producer = transSession.createProducer(address); - for (int i = 0; i < numMsg; i++) - { + for (int i = 0; i < numMsg; i++) { ClientMessage message = transSession.createMessage(false); message.putIntProperty(new SimpleString("seqno"), i); producer.send(message); @@ -436,27 +411,21 @@ public class QueueControlTest extends ManagementTestBase final CountDownLatch latch2 = new CountDownLatch(1); final CountDownLatch latch3 = new CountDownLatch(10); - consumer.setMessageHandler(new MessageHandler() - { + consumer.setMessageHandler(new MessageHandler() { @Override - public void onMessage(ClientMessage message) - { - try - { + public void onMessage(ClientMessage message) { + try { message.acknowledge(); } - catch (ActiveMQException e1) - { + catch (ActiveMQException e1) { e1.printStackTrace(); } latch1.countDown(); - try - { + try { latch2.await(10, TimeUnit.SECONDS); } - catch (InterruptedException e) - { + catch (InterruptedException e) { e.printStackTrace(); } latch3.countDown(); @@ -467,15 +436,13 @@ public class QueueControlTest extends ManagementTestBase //now we know the ack of the message is sent but to make sure //the server has received it, we try 5 times int n = 0; - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { Thread.sleep(1000); String jsonStr = queueControl.listDeliveringMessagesAsJSON(); n = countOccurrencesOf(jsonStr, "seqno"); - if (n == numMsg) - { + if (n == numMsg) { break; } } @@ -488,8 +455,7 @@ public class QueueControlTest extends ManagementTestBase transSession.commit(); } - finally - { + finally { consumer.close(); transSession.deleteQueue(queue); transSession.close(); @@ -498,8 +464,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testListDeliveringMessages() throws Exception - { + public void testListDeliveringMessages() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); int intValue = RandomUtil.randomInt(); @@ -515,14 +480,12 @@ public class QueueControlTest extends ManagementTestBase producer.send(message); producer.send(session.createMessage(false)); - ClientConsumer consumer = session.createConsumer(queue); session.start(); ClientMessage msgRec = consumer.receive(5000); assertNotNull(msgRec); assertEquals(msgRec.getIntProperty("key").intValue(), intValue); - ClientSessionFactory sf2 = createSessionFactory(locator); ClientSession session2 = sf2.createSession(false, true, false); ClientConsumer consumer2 = session2.createConsumer(queue); @@ -530,13 +493,12 @@ public class QueueControlTest extends ManagementTestBase ClientMessage msgRec2 = consumer2.receive(5000); assertNotNull(msgRec2); - assertEquals(2, srvqueue.getDeliveringCount()); assertEquals(2, srvqueue.getConsumerCount()); System.out.println(queueControl.listDeliveringMessagesAsJSON()); - Map []> deliveringMap = queueControl.listDeliveringMessages(); + Map[]> deliveringMap = queueControl.listDeliveringMessages(); assertEquals(2, deliveringMap.size()); consumer.close(); @@ -546,8 +508,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testListScheduledMessages() throws Exception - { + public void testListScheduledMessages() throws Exception { long delay = 2000; SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -579,8 +540,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testListScheduledMessagesAsJSON() throws Exception - { + public void testListScheduledMessagesAsJSON() throws Exception { long delay = 2000; SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -616,8 +576,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testGetDeliveringCount() throws Exception - { + public void testGetDeliveringCount() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -643,8 +602,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testListMessagesAsJSONWithNullFilter() throws Exception - { + public void testListMessagesAsJSONWithNullFilter() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); int intValue = RandomUtil.randomInt(); @@ -674,8 +632,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testListMessagesWithFilter() throws Exception - { + public void testListMessagesWithFilter() throws Exception { SimpleString key = new SimpleString("key"); long matchingValue = RandomUtil.randomLong(); long unmatchingValue = matchingValue + 1; @@ -708,8 +665,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testListMessagesWithNullFilter() throws Exception - { + public void testListMessagesWithNullFilter() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -732,8 +688,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testListMessagesWithEmptyFilter() throws Exception - { + public void testListMessagesWithEmptyFilter() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -756,8 +711,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testListMessagesAsJSONWithFilter() throws Exception - { + public void testListMessagesAsJSONWithFilter() throws Exception { SimpleString key = new SimpleString("key"); long matchingValue = RandomUtil.randomLong(); long unmatchingValue = matchingValue + 1; @@ -802,8 +756,7 @@ public class QueueControlTest extends ManagementTestBase * */ @Test - public void testMoveMessages() throws Exception - { + public void testMoveMessages() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); SimpleString otherAddress = RandomUtil.randomSimpleString(); @@ -844,8 +797,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testMoveMessagesToUnknownQueue() throws Exception - { + public void testMoveMessagesToUnknownQueue() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); SimpleString unknownQueue = RandomUtil.randomSimpleString(); @@ -864,13 +816,11 @@ public class QueueControlTest extends ManagementTestBase Assert.assertEquals(1, getMessageCount(queueControl)); // moved all messages to unknown queue - try - { + try { queueControl.moveMessages(null, unknownQueue.toString()); Assert.fail("operation must fail if the other queue does not exist"); } - catch (Exception e) - { + catch (Exception e) { } Assert.assertEquals(1, getMessageCount(queueControl)); @@ -889,8 +839,7 @@ public class QueueControlTest extends ManagementTestBase */ @Test - public void testMoveMessagesWithFilter() throws Exception - { + public void testMoveMessagesWithFilter() throws Exception { SimpleString key = new SimpleString("key"); long matchingValue = RandomUtil.randomLong(); long unmatchingValue = matchingValue + 1; @@ -941,8 +890,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testMoveMessage() throws Exception - { + public void testMoveMessage() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); SimpleString otherAddress = RandomUtil.randomSimpleString(); @@ -979,8 +927,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testMoveMessageToUnknownQueue() throws Exception - { + public void testMoveMessageToUnknownQueue() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); SimpleString unknownQueue = RandomUtil.randomSimpleString(); @@ -1000,13 +947,11 @@ public class QueueControlTest extends ManagementTestBase long messageID = (Long) messages[0].get("messageID"); // moved all messages to unknown queue - try - { + try { queueControl.moveMessage(messageID, unknownQueue.toString()); Assert.fail("operation must fail if the other queue does not exist"); } - catch (Exception e) - { + catch (Exception e) { } Assert.assertEquals(1, getMessageCount(queueControl)); @@ -1024,8 +969,7 @@ public class QueueControlTest extends ManagementTestBase */ @Test - public void testRemoveMessages() throws Exception - { + public void testRemoveMessages() throws Exception { SimpleString key = new SimpleString("key"); long matchingValue = RandomUtil.randomLong(); long unmatchingValue = matchingValue + 1; @@ -1069,8 +1013,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testRemoveMessagesWithLimit() throws Exception - { + public void testRemoveMessagesWithLimit() throws Exception { SimpleString key = new SimpleString("key"); long matchingValue = RandomUtil.randomLong(); long unmatchingValue = matchingValue + 1; @@ -1114,8 +1057,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testRemoveMessagesWithNullFilter() throws Exception - { + public void testRemoveMessagesWithNullFilter() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -1138,8 +1080,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testRemoveMessagesWithEmptyFilter() throws Exception - { + public void testRemoveMessagesWithEmptyFilter() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -1162,8 +1103,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testRemoveMessage() throws Exception - { + public void testRemoveMessage() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -1194,8 +1134,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testRemoveScheduledMessage() throws Exception - { + public void testRemoveScheduledMessage() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -1225,8 +1164,7 @@ public class QueueControlTest extends ManagementTestBase Assert.assertEquals(1, queueControl.getScheduledCount()); // check there is a single message to consume from queue - while (timeout > System.currentTimeMillis() && queueControl.getScheduledCount() == 1) - { + while (timeout > System.currentTimeMillis() && queueControl.getScheduledCount() == 1) { Thread.sleep(100); } @@ -1236,8 +1174,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testRemoveMessage2() throws Exception - { + public void testRemoveMessage2() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -1246,8 +1183,7 @@ public class QueueControlTest extends ManagementTestBase // send messages on queue - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage msg = session.createMessage(false); msg.putIntProperty("count", i); @@ -1257,8 +1193,7 @@ public class QueueControlTest extends ManagementTestBase ClientConsumer cons = session.createConsumer(queue); session.start(); LinkedList msgs = new LinkedList(); - for (int i = 0; i < 50; i++) - { + for (int i = 0; i < 50; i++) { ClientMessage msg = cons.receive(1000); msgs.add(msg); } @@ -1286,8 +1221,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testCountMessagesWithFilter() throws Exception - { + public void testCountMessagesWithFilter() throws Exception { SimpleString key = new SimpleString("key"); long matchingValue = RandomUtil.randomLong(); long unmatchingValue = matchingValue + 1; @@ -1317,13 +1251,11 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testCountMessagesWithInvalidFilter() throws Exception - { + public void testCountMessagesWithInvalidFilter() throws Exception { SimpleString key = new SimpleString("key"); String matchingValue = "MATCH"; String nonMatchingValue = "DIFFERENT"; - SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -1331,15 +1263,13 @@ public class QueueControlTest extends ManagementTestBase ClientProducer producer = session.createProducer(address); // send on queue - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage msg = session.createMessage(false); msg.putStringProperty(key, SimpleString.toSimpleString(matchingValue)); producer.send(msg); } - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage msg = session.createMessage(false); msg.putStringProperty(key, SimpleString.toSimpleString(nonMatchingValue)); producer.send(msg); @@ -1354,11 +1284,9 @@ public class QueueControlTest extends ManagementTestBase assertNull(consumer.receiveImmediate()); - QueueControl queueControl = createManagementControl(address, queue); Assert.assertEquals(110, getMessageCount(queueControl)); - Assert.assertEquals(0, queueControl.countMessages("nonExistentProperty like \'%Temp/88\'")); Assert.assertEquals(100, queueControl.countMessages(key + "=\'" + matchingValue + "\'")); @@ -1370,8 +1298,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testExpireMessagesWithFilter() throws Exception - { + public void testExpireMessagesWithFilter() throws Exception { SimpleString key = new SimpleString("key"); long matchingValue = RandomUtil.randomLong(); long unmatchingValue = matchingValue + 1; @@ -1415,8 +1342,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testExpireMessage() throws Exception - { + public void testExpireMessage() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); SimpleString expiryAddress = RandomUtil.randomSimpleString(); @@ -1456,8 +1382,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testSendMessageToDeadLetterAddress() throws Exception - { + public void testSendMessageToDeadLetterAddress() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); SimpleString deadLetterAddress = RandomUtil.randomSimpleString(); @@ -1500,8 +1425,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testChangeMessagePriority() throws Exception - { + public void testChangeMessagePriority() throws Exception { byte originalPriority = (byte) 1; byte newPriority = (byte) 8; @@ -1536,8 +1460,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testChangeMessagePriorityWithInvalidValue() throws Exception - { + public void testChangeMessagePriorityWithInvalidValue() throws Exception { byte invalidPriority = (byte) 23; SimpleString address = RandomUtil.randomSimpleString(); @@ -1557,13 +1480,11 @@ public class QueueControlTest extends ManagementTestBase Assert.assertEquals(1, messages.length); long messageID = (Long) messages[0].get("messageID"); - try - { + try { queueControl.changeMessagePriority(messageID, invalidPriority); Assert.fail("operation fails when priority value is < 0 or > 9"); } - catch (Exception e) - { + catch (Exception e) { } ClientConsumer consumer = session.createConsumer(queue); @@ -1576,8 +1497,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testListMessageCounter() throws Exception - { + public void testListMessageCounter() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -1629,8 +1549,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testResetMessageCounter() throws Exception - { + public void testResetMessageCounter() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -1682,8 +1601,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testListMessageCounterAsHTML() throws Exception - { + public void testListMessageCounterAsHTML() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -1697,8 +1615,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testListMessageCounterHistory() throws Exception - { + public void testListMessageCounterHistory() throws Exception { long counterPeriod = 1000; SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -1718,8 +1635,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testListMessageCounterHistoryAsHTML() throws Exception - { + public void testListMessageCounterHistoryAsHTML() throws Exception { long counterPeriod = 1000; SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -1739,8 +1655,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testMoveMessagesBack() throws Exception - { + public void testMoveMessagesBack() throws Exception { server.createQueue(new SimpleString("q1"), new SimpleString("q1"), null, true, false); server.createQueue(new SimpleString("q2"), new SimpleString("q2"), null, true, false); @@ -1752,8 +1667,7 @@ public class QueueControlTest extends ManagementTestBase ClientProducer prod1 = session.createProducer("q1"); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage msg = session.createMessage(true); msg.putStringProperty(Message.HDR_DUPLICATE_DETECTION_ID, new SimpleString("dupl-" + i)); @@ -1769,13 +1683,9 @@ public class QueueControlTest extends ManagementTestBase assertNotNull(consumer.receive(5000)); consumer.close(); - QueueControl q1Control = ManagementControlHelper.createQueueControl(new SimpleString("q1"), - new SimpleString("q1"), - mbeanServer); + QueueControl q1Control = ManagementControlHelper.createQueueControl(new SimpleString("q1"), new SimpleString("q1"), mbeanServer); - QueueControl q2Control = ManagementControlHelper.createQueueControl(new SimpleString("q2"), - new SimpleString("q2"), - mbeanServer); + QueueControl q2Control = ManagementControlHelper.createQueueControl(new SimpleString("q2"), new SimpleString("q2"), mbeanServer); assertEquals(10, q1Control.moveMessages(null, "q2")); @@ -1790,8 +1700,7 @@ public class QueueControlTest extends ManagementTestBase session.start(); consumer = session.createConsumer("q1"); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage msg = consumer.receive(5000); assertNotNull(msg); msg.acknowledge(); @@ -1810,8 +1719,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testMoveMessagesBack2() throws Exception - { + public void testMoveMessagesBack2() throws Exception { server.createQueue(new SimpleString("q1"), new SimpleString("q1"), null, true, false); server.createQueue(new SimpleString("q2"), new SimpleString("q2"), null, true, false); @@ -1825,8 +1733,7 @@ public class QueueControlTest extends ManagementTestBase int NUMBER_OF_MSGS = 10; - for (int i = 0; i < NUMBER_OF_MSGS; i++) - { + for (int i = 0; i < NUMBER_OF_MSGS; i++) { ClientMessage msg = session.createMessage(true); msg.putStringProperty(Message.HDR_DUPLICATE_DETECTION_ID, new SimpleString("dupl-" + i)); @@ -1842,13 +1749,9 @@ public class QueueControlTest extends ManagementTestBase assertNotNull(consumer.receive(5000)); consumer.close(); - QueueControl q1Control = ManagementControlHelper.createQueueControl(new SimpleString("q1"), - new SimpleString("q1"), - mbeanServer); + QueueControl q1Control = ManagementControlHelper.createQueueControl(new SimpleString("q1"), new SimpleString("q1"), mbeanServer); - QueueControl q2Control = ManagementControlHelper.createQueueControl(new SimpleString("q2"), - new SimpleString("q2"), - mbeanServer); + QueueControl q2Control = ManagementControlHelper.createQueueControl(new SimpleString("q2"), new SimpleString("q2"), mbeanServer); assertEquals(NUMBER_OF_MSGS, q1Control.moveMessages(null, "q2")); @@ -1856,8 +1759,7 @@ public class QueueControlTest extends ManagementTestBase consumer = session.createConsumer("q2", true); - for (int i = 0; i < NUMBER_OF_MSGS; i++) - { + for (int i = 0; i < NUMBER_OF_MSGS; i++) { ClientMessage msg = consumer.receive(5000); assertNotNull(msg); messageIDs[i] = msg.getMessageID(); @@ -1867,17 +1769,14 @@ public class QueueControlTest extends ManagementTestBase consumer.close(); - for (int i = 0; i < NUMBER_OF_MSGS; i++) - { + for (int i = 0; i < NUMBER_OF_MSGS; i++) { q2Control.moveMessage(messageIDs[i], "q1"); } - session.start(); consumer = session.createConsumer("q1"); - for (int i = 0; i < NUMBER_OF_MSGS; i++) - { + for (int i = 0; i < NUMBER_OF_MSGS; i++) { ClientMessage msg = consumer.receive(5000); assertNotNull(msg); msg.acknowledge(); @@ -1893,14 +1792,12 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testPauseAndResume() - { + public void testPauseAndResume() { long counterPeriod = 1000; SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); - try - { + try { session.createQueue(address, queue, null, false); QueueControl queueControl = createManagementControl(address, queue); @@ -1913,16 +1810,14 @@ public class QueueControlTest extends ManagementTestBase queueControl.resume(); Assert.assertFalse(queueControl.isPaused()); } - catch (Exception e) - { + catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test - public void testResetMessagesAdded() throws Exception - { + public void testResetMessagesAdded() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -1949,8 +1844,7 @@ public class QueueControlTest extends ManagementTestBase } @Test - public void testResetMessagesAcknowledged() throws Exception - { + public void testResetMessagesAcknowledged() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); @@ -1977,14 +1871,13 @@ public class QueueControlTest extends ManagementTestBase //make sure notifications are always received no matter whether //a Queue is created via QueueControl or by JMSServerManager directly. @Test - public void testCreateQueueNotification() throws Exception - { + public void testCreateQueueNotification() throws Exception { JMSUtil.JMXListener listener = new JMSUtil.JMXListener(); this.mbeanServer.addNotificationListener(ObjectNameBuilder.DEFAULT.getActiveMQServerObjectName(), listener, null, null); SimpleString testQueueName = new SimpleString("newQueue"); String testQueueName2 = "newQueue2"; - this.server.createQueue(testQueueName, testQueueName, null, false, false); + this.server.createQueue(testQueueName, testQueueName, null, false, false); Notification notif = listener.getNotification(); @@ -2018,25 +1911,21 @@ public class QueueControlTest extends ManagementTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - Configuration conf = createDefaultInVMConfig() - .setJMXManagementEnabled(true); + Configuration conf = createDefaultInVMConfig().setJMXManagementEnabled(true); server = addServer(ActiveMQServers.newActiveMQServer(conf, mbeanServer, false)); server.start(); - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true) - .setConsumerWindowSize(0); + locator = createInVMNonHALocator().setBlockOnNonDurableSend(true).setConsumerWindowSize(0); ClientSessionFactory sf = createSessionFactory(locator); session = sf.createSession(false, true, false); session.start(); } - protected QueueControl createManagementControl(final SimpleString address, final SimpleString queue) throws Exception - { + protected QueueControl createManagementControl(final SimpleString address, + final SimpleString queue) throws Exception { QueueControl queueControl = ManagementControlHelper.createQueueControl(address, queue, mbeanServer); return queueControl; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/QueueControlUsingCoreTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/QueueControlUsingCoreTest.java index 73bef592e4..d296819cd4 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/QueueControlUsingCoreTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/QueueControlUsingCoreTest.java @@ -27,314 +27,257 @@ import org.apache.activemq.artemis.api.core.management.QueueControl; import org.apache.activemq.artemis.api.core.management.ResourceNames; import org.junit.Before; -public class QueueControlUsingCoreTest extends QueueControlTest -{ +public class QueueControlUsingCoreTest extends QueueControlTest { protected ClientSession session; private ServerLocator locator; @Override - protected QueueControl createManagementControl(final SimpleString address, final SimpleString queue) throws Exception - { - return new QueueControl() - { + protected QueueControl createManagementControl(final SimpleString address, + final SimpleString queue) throws Exception { + return new QueueControl() { private final CoreMessagingProxy proxy = new CoreMessagingProxy(session, ResourceNames.CORE_QUEUE + queue); @Override - public void flushExecutor() - { - try - { + public void flushExecutor() { + try { proxy.invokeOperation("flushExecutor"); } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } - public boolean changeMessagePriority(final long messageID, final int newPriority) throws Exception - { + public boolean changeMessagePriority(final long messageID, final int newPriority) throws Exception { return (Boolean) proxy.invokeOperation("changeMessagePriority", messageID, newPriority); } - public int changeMessagesPriority(final String filter, final int newPriority) throws Exception - { + public int changeMessagesPriority(final String filter, final int newPriority) throws Exception { return (Integer) proxy.invokeOperation("changeMessagesPriority", filter, newPriority); } - public long countMessages(final String filter) throws Exception - { + public long countMessages(final String filter) throws Exception { return ((Number) proxy.invokeOperation("countMessages", filter)).longValue(); } - public boolean expireMessage(final long messageID) throws Exception - { + public boolean expireMessage(final long messageID) throws Exception { return (Boolean) proxy.invokeOperation("expireMessage", messageID); } - public int expireMessages(final String filter) throws Exception - { + public int expireMessages(final String filter) throws Exception { return (Integer) proxy.invokeOperation("expireMessages", filter); } - public String getAddress() - { + public String getAddress() { return (String) proxy.retrieveAttributeValue("address"); } - public int getConsumerCount() - { + public int getConsumerCount() { return (Integer) proxy.retrieveAttributeValue("consumerCount"); } - public String getDeadLetterAddress() - { + public String getDeadLetterAddress() { return (String) proxy.retrieveAttributeValue("deadLetterAddress"); } - public int getDeliveringCount() - { + public int getDeliveringCount() { return (Integer) proxy.retrieveAttributeValue("deliveringCount"); } - public String getExpiryAddress() - { + public String getExpiryAddress() { return (String) proxy.retrieveAttributeValue("expiryAddress"); } - public String getFilter() - { + public String getFilter() { return (String) proxy.retrieveAttributeValue("filter"); } - public long getMessageCount() - { + public long getMessageCount() { return ((Number) proxy.retrieveAttributeValue("messageCount")).longValue(); } - public long getMessagesAdded() - { + public long getMessagesAdded() { return (Integer) proxy.retrieveAttributeValue("messagesAdded"); } - public long getMessagesAcknowledged() - { + public long getMessagesAcknowledged() { return (Integer) proxy.retrieveAttributeValue("messagesAcknowledged"); } - public void resetMessagesAdded() throws Exception - { + public void resetMessagesAdded() throws Exception { proxy.invokeOperation("resetMessagesAdded"); } - public void resetMessagesAcknowledged() throws Exception - { + public void resetMessagesAcknowledged() throws Exception { proxy.invokeOperation("resetMessagesAcknowledged"); } - public String getName() - { + public String getName() { return (String) proxy.retrieveAttributeValue("name"); } - public long getID() - { + public long getID() { return (Long) proxy.retrieveAttributeValue("ID"); } - public long getScheduledCount() - { + public long getScheduledCount() { return (Long) proxy.retrieveAttributeValue("scheduledCount", Long.class); } - public boolean isDurable() - { + public boolean isDurable() { return (Boolean) proxy.retrieveAttributeValue("durable"); } - public boolean isTemporary() - { + public boolean isTemporary() { return (Boolean) proxy.retrieveAttributeValue("temporary"); } - public String listMessageCounter() throws Exception - { + public String listMessageCounter() throws Exception { return (String) proxy.invokeOperation("listMessageCounter"); } - public String listMessageCounterAsHTML() throws Exception - { + public String listMessageCounterAsHTML() throws Exception { return (String) proxy.invokeOperation("listMessageCounterAsHTML"); } - public String listMessageCounterHistory() throws Exception - { + public String listMessageCounterHistory() throws Exception { return (String) proxy.invokeOperation("listMessageCounterHistory"); } - /** * Returns the first message on the queue as JSON */ - public String getFirstMessageAsJSON() throws Exception - { + public String getFirstMessageAsJSON() throws Exception { return (String) proxy.invokeOperation("getFirstMessageAsJSON"); } /** * Returns the timestamp of the first message in milliseconds. */ - public Long getFirstMessageTimestamp() throws Exception - { + public Long getFirstMessageTimestamp() throws Exception { return (Long) proxy.invokeOperation("getFirstMessageTimestamp"); } /** * Returns the age of the first message in milliseconds. */ - public Long getFirstMessageAge() throws Exception - { + public Long getFirstMessageAge() throws Exception { Object value = proxy.invokeOperation("getFirstMessageAge"); - if (value instanceof Integer) - { + if (value instanceof Integer) { return ((Integer) value).longValue(); } return (Long) value; } - public String listMessageCounterHistoryAsHTML() throws Exception - { + public String listMessageCounterHistoryAsHTML() throws Exception { return (String) proxy.invokeOperation("listMessageCounterHistoryAsHTML"); } - public Map[] listMessages(final String filter) throws Exception - { + public Map[] listMessages(final String filter) throws Exception { Object[] res = (Object[]) proxy.invokeOperation("listMessages", filter); Map[] results = new Map[res.length]; - for (int i = 0; i < res.length; i++) - { + for (int i = 0; i < res.length; i++) { results[i] = (Map) res[i]; } return results; } - public String listMessagesAsJSON(final String filter) throws Exception - { + public String listMessagesAsJSON(final String filter) throws Exception { return (String) proxy.invokeOperation("listMessagesAsJSON", filter); } - public Map[] listScheduledMessages() throws Exception - { + public Map[] listScheduledMessages() throws Exception { Object[] res = (Object[]) proxy.invokeOperation("listScheduledMessages"); Map[] results = new Map[res.length]; - for (int i = 0; i < res.length; i++) - { + for (int i = 0; i < res.length; i++) { results[i] = (Map) res[i]; } return results; } - public String listScheduledMessagesAsJSON() throws Exception - { + public String listScheduledMessagesAsJSON() throws Exception { return (String) proxy.invokeOperation("listScheduledMessagesAsJSON"); } - public int moveMessages(final String filter, final String otherQueueName) throws Exception - { + public int moveMessages(final String filter, final String otherQueueName) throws Exception { return (Integer) proxy.invokeOperation("moveMessages", filter, otherQueueName); } - @Override - public int moveMessages( - int flushLimit, - String filter, - String otherQueueName, - boolean rejectDuplicates) throws Exception - { + public int moveMessages(int flushLimit, + String filter, + String otherQueueName, + boolean rejectDuplicates) throws Exception { return (Integer) proxy.invokeOperation("moveMessages", flushLimit, filter, otherQueueName, rejectDuplicates); } - public int moveMessages(final String filter, final String otherQueueName, final boolean rejectDuplicates) throws Exception - { + public int moveMessages(final String filter, + final String otherQueueName, + final boolean rejectDuplicates) throws Exception { return (Integer) proxy.invokeOperation("moveMessages", filter, otherQueueName, rejectDuplicates); } - public boolean moveMessage(final long messageID, final String otherQueueName) throws Exception - { + public boolean moveMessage(final long messageID, final String otherQueueName) throws Exception { return (Boolean) proxy.invokeOperation("moveMessage", messageID, otherQueueName); } - public boolean moveMessage(final long messageID, final String otherQueueName, final boolean rejectDuplicates) throws Exception - { + public boolean moveMessage(final long messageID, + final String otherQueueName, + final boolean rejectDuplicates) throws Exception { return (Boolean) proxy.invokeOperation("moveMessage", messageID, otherQueueName, rejectDuplicates); } - public int removeMessages(final String filter) throws Exception - { + public int removeMessages(final String filter) throws Exception { return (Integer) proxy.invokeOperation("removeMessages", filter); } - public int removeMessages(final int limit, final String filter) throws Exception - { + public int removeMessages(final int limit, final String filter) throws Exception { return (Integer) proxy.invokeOperation("removeMessages", limit, filter); } - public boolean removeMessage(final long messageID) throws Exception - { + public boolean removeMessage(final long messageID) throws Exception { return (Boolean) proxy.invokeOperation("removeMessage", messageID); } - public void resetMessageCounter() throws Exception - { + public void resetMessageCounter() throws Exception { proxy.invokeOperation("resetMessageCounter"); } - public boolean sendMessageToDeadLetterAddress(final long messageID) throws Exception - { + public boolean sendMessageToDeadLetterAddress(final long messageID) throws Exception { return (Boolean) proxy.invokeOperation("sendMessageToDeadLetterAddress", messageID); } - public int sendMessagesToDeadLetterAddress(final String filterStr) throws Exception - { + public int sendMessagesToDeadLetterAddress(final String filterStr) throws Exception { return (Integer) proxy.invokeOperation("sendMessagesToDeadLetterAddress", filterStr); } - public void setDeadLetterAddress(final String deadLetterAddress) throws Exception - { + public void setDeadLetterAddress(final String deadLetterAddress) throws Exception { proxy.invokeOperation("setDeadLetterAddress", deadLetterAddress); } - public void setExpiryAddress(final String expiryAddress) throws Exception - { + public void setExpiryAddress(final String expiryAddress) throws Exception { proxy.invokeOperation("setExpiryAddress", expiryAddress); } - public void pause() throws Exception - { + public void pause() throws Exception { proxy.invokeOperation("pause"); } - public void resume() throws Exception - { + public void resume() throws Exception { proxy.invokeOperation("resume"); } - public boolean isPaused() throws Exception - { + public boolean isPaused() throws Exception { return (Boolean) proxy.invokeOperation("isPaused"); } - public String listConsumersAsJSON() throws Exception - { + public String listConsumersAsJSON() throws Exception { return (String) proxy.invokeOperation("listConsumersAsJSON"); } - public Map[]> listDeliveringMessages() throws Exception - { + public Map[]> listDeliveringMessages() throws Exception { // This map code could be done better, // however that's just to convert stuff for the test class, so I // am not going to spend a lot more time on it (Clebert) @@ -344,14 +287,11 @@ public class QueueControlUsingCoreTest extends QueueControlTest @SuppressWarnings("rawtypes") Map response = new HashMap(); - for (Object key : res.keySet()) - { + for (Object key : res.keySet()) { Object[] value = (Object[]) res.get(key); - Map[] results = new Map[value.length]; - for (int i = 0; i < value.length; i++) - { + for (int i = 0; i < value.length; i++) { results[i] = (Map) value[i]; } @@ -362,8 +302,7 @@ public class QueueControlUsingCoreTest extends QueueControlTest } @Override - public String listDeliveringMessagesAsJSON() throws Exception - { + public String listDeliveringMessagesAsJSON() throws Exception { return (String) proxy.invokeOperation("listDeliveringMessagesAsJSON"); } }; @@ -371,8 +310,7 @@ public class QueueControlUsingCoreTest extends QueueControlTest @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = createInVMNonHALocator(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/SecurityManagementTestBase.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/SecurityManagementTestBase.java index 2b60360ebc..5b6b315410 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/SecurityManagementTestBase.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/SecurityManagementTestBase.java @@ -29,8 +29,7 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Assert; import org.junit.Before; -public abstract class SecurityManagementTestBase extends ActiveMQTestBase -{ +public abstract class SecurityManagementTestBase extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -50,8 +49,7 @@ public abstract class SecurityManagementTestBase extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = setupAndStartActiveMQServer(); @@ -59,19 +57,17 @@ public abstract class SecurityManagementTestBase extends ActiveMQTestBase protected abstract ActiveMQServer setupAndStartActiveMQServer() throws Exception; - protected void doSendManagementMessage(final String user, final String password, final boolean expectSuccess) throws Exception - { + protected void doSendManagementMessage(final String user, + final String password, + final boolean expectSuccess) throws Exception { ServerLocator locator = createInVMNonHALocator(); ClientSessionFactory sf = locator.createSessionFactory(); - try - { + try { ClientSession session = null; - if (user == null) - { + if (user == null) { session = sf.createSession(false, true, true); } - else - { + else { session = sf.createSession(user, password, false, true, true, false, 1); } @@ -82,28 +78,23 @@ public abstract class SecurityManagementTestBase extends ActiveMQTestBase ClientMessage mngmntMessage = session.createMessage(false); ManagementHelper.putAttribute(mngmntMessage, ResourceNames.CORE_SERVER, "started"); ClientMessage reply = requestor.request(mngmntMessage, 500); - if (expectSuccess) - { + if (expectSuccess) { Assert.assertNotNull(reply); - Assert.assertTrue((Boolean)ManagementHelper.getResult(reply)); + Assert.assertTrue((Boolean) ManagementHelper.getResult(reply)); } - else - { + else { Assert.assertNull(reply); } requestor.close(); } - catch (Exception e) - { - if (expectSuccess) - { + catch (Exception e) { + if (expectSuccess) { Assert.fail("got unexpected exception " + e.getClass() + ": " + e.getMessage()); e.printStackTrace(); } } - finally - { + finally { sf.close(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/SecurityManagementWithConfiguredAdminUserTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/SecurityManagementWithConfiguredAdminUserTest.java index e8019f1ccd..977511d24d 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/SecurityManagementWithConfiguredAdminUserTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/SecurityManagementWithConfiguredAdminUserTest.java @@ -27,8 +27,7 @@ import org.junit.Test; import java.util.Set; -public class SecurityManagementWithConfiguredAdminUserTest extends SecurityManagementTestBase -{ +public class SecurityManagementWithConfiguredAdminUserTest extends SecurityManagementTestBase { // Constants ----------------------------------------------------- @@ -49,30 +48,26 @@ public class SecurityManagementWithConfiguredAdminUserTest extends SecurityManag // Public -------------------------------------------------------- /** - * default CLUSTER_ADMIN_USER must work even when there are other - * configured admin users + * default CLUSTER_ADMIN_USER must work even when there are other + * configured admin users */ @Test - public void testSendManagementMessageWithClusterAdminUser() throws Exception - { + public void testSendManagementMessageWithClusterAdminUser() throws Exception { doSendManagementMessage(ActiveMQDefaultConfiguration.getDefaultClusterUser(), CLUSTER_PASSWORD, true); } @Test - public void testSendManagementMessageWithAdminRole() throws Exception - { + public void testSendManagementMessageWithAdminRole() throws Exception { doSendManagementMessage(validAdminUser, validAdminPassword, true); } @Test - public void testSendManagementMessageWithoutAdminRole() throws Exception - { + public void testSendManagementMessageWithoutAdminRole() throws Exception { doSendManagementMessage(invalidAdminUser, invalidAdminPassword, false); } @Test - public void testSendManagementMessageWithoutUserCredentials() throws Exception - { + public void testSendManagementMessageWithoutUserCredentials() throws Exception { doSendManagementMessage(null, null, false); } @@ -81,14 +76,12 @@ public class SecurityManagementWithConfiguredAdminUserTest extends SecurityManag // Protected ----------------------------------------------------- @Override - protected ActiveMQServer setupAndStartActiveMQServer() throws Exception - { - Configuration config = createDefaultInVMConfig() - .setSecurityEnabled(true); + protected ActiveMQServer setupAndStartActiveMQServer() throws Exception { + Configuration config = createDefaultInVMConfig().setSecurityEnabled(true); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false)); server.start(); HierarchicalRepository> securityRepository = server.getSecurityRepository(); - ActiveMQSecurityManagerImpl securityManager = (ActiveMQSecurityManagerImpl)server.getSecurityManager(); + ActiveMQSecurityManagerImpl securityManager = (ActiveMQSecurityManagerImpl) server.getSecurityManager(); securityManager.getConfiguration().addUser(validAdminUser, validAdminPassword); securityManager.getConfiguration().addUser(invalidAdminUser, invalidAdminPassword); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/SecurityManagementWithDefaultConfigurationTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/SecurityManagementWithDefaultConfigurationTest.java index deab39afb0..d4b094dce2 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/SecurityManagementWithDefaultConfigurationTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/SecurityManagementWithDefaultConfigurationTest.java @@ -22,26 +22,20 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.ActiveMQServers; import org.junit.Test; -public class SecurityManagementWithDefaultConfigurationTest extends SecurityManagementTestBase -{ +public class SecurityManagementWithDefaultConfigurationTest extends SecurityManagementTestBase { @Test - public void testSendManagementMessageWithDefaultClusterAdminUser() throws Exception - { - doSendManagementMessage(ActiveMQDefaultConfiguration.getDefaultClusterUser(), - ActiveMQDefaultConfiguration.getDefaultClusterPassword(), - true); + public void testSendManagementMessageWithDefaultClusterAdminUser() throws Exception { + doSendManagementMessage(ActiveMQDefaultConfiguration.getDefaultClusterUser(), ActiveMQDefaultConfiguration.getDefaultClusterPassword(), true); } @Test - public void testSendManagementMessageWithGuest() throws Exception - { + public void testSendManagementMessageWithGuest() throws Exception { doSendManagementMessage("guest", "guest", false); } @Test - public void testSendManagementMessageWithoutUserCredentials() throws Exception - { + public void testSendManagementMessageWithoutUserCredentials() throws Exception { doSendManagementMessage(null, null, false); } @@ -50,11 +44,8 @@ public class SecurityManagementWithDefaultConfigurationTest extends SecurityMana // Protected ----------------------------------------------------- @Override - protected ActiveMQServer setupAndStartActiveMQServer() throws Exception - { - Configuration config = createDefaultInVMConfig() - .setClusterPassword(ActiveMQDefaultConfiguration.getDefaultClusterPassword()) - .setSecurityEnabled(true); + protected ActiveMQServer setupAndStartActiveMQServer() throws Exception { + Configuration config = createDefaultInVMConfig().setClusterPassword(ActiveMQDefaultConfiguration.getDefaultClusterPassword()).setSecurityEnabled(true); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false)); server.start(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/SecurityManagementWithModifiedConfigurationTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/SecurityManagementWithModifiedConfigurationTest.java index 49558e30d9..ef8bb40f86 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/SecurityManagementWithModifiedConfigurationTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/SecurityManagementWithModifiedConfigurationTest.java @@ -22,8 +22,7 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.ActiveMQServers; import org.junit.Test; -public class SecurityManagementWithModifiedConfigurationTest extends SecurityManagementTestBase -{ +public class SecurityManagementWithModifiedConfigurationTest extends SecurityManagementTestBase { // Constants ----------------------------------------------------- @@ -38,28 +37,22 @@ public class SecurityManagementWithModifiedConfigurationTest extends SecurityMan // Public -------------------------------------------------------- @Test - public void testSendManagementMessageWithModifiedClusterAdminUser() throws Exception - { + public void testSendManagementMessageWithModifiedClusterAdminUser() throws Exception { doSendManagementMessage(ActiveMQDefaultConfiguration.getDefaultClusterUser(), configuredClusterPassword, true); } @Test - public void testSendManagementMessageWithDefaultClusterAdminUser() throws Exception - { - doSendManagementMessage(ActiveMQDefaultConfiguration.getDefaultClusterUser(), - ActiveMQDefaultConfiguration.getDefaultClusterPassword(), - false); + public void testSendManagementMessageWithDefaultClusterAdminUser() throws Exception { + doSendManagementMessage(ActiveMQDefaultConfiguration.getDefaultClusterUser(), ActiveMQDefaultConfiguration.getDefaultClusterPassword(), false); } @Test - public void testSendManagementMessageWithGuest() throws Exception - { + public void testSendManagementMessageWithGuest() throws Exception { doSendManagementMessage("guest", "guest", false); } @Test - public void testSendManagementMessageWithoutUserCredentials() throws Exception - { + public void testSendManagementMessageWithoutUserCredentials() throws Exception { doSendManagementMessage(null, null, false); } @@ -68,11 +61,8 @@ public class SecurityManagementWithModifiedConfigurationTest extends SecurityMan // Protected ----------------------------------------------------- @Override - protected ActiveMQServer setupAndStartActiveMQServer() throws Exception - { - Configuration conf = createDefaultInVMConfig() - .setSecurityEnabled(true) - .setClusterPassword(configuredClusterPassword); + protected ActiveMQServer setupAndStartActiveMQServer() throws Exception { + Configuration conf = createDefaultInVMConfig().setSecurityEnabled(true).setClusterPassword(configuredClusterPassword); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(conf, false)); server.start(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/SecurityNotificationTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/SecurityNotificationTest.java index 4f2add3219..015cbf4172 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/SecurityNotificationTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/SecurityNotificationTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.integration.management; +import java.util.HashSet; +import java.util.Set; + import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration; import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.api.core.SimpleString; @@ -37,14 +40,10 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import java.util.HashSet; -import java.util.Set; - import static org.apache.activemq.artemis.api.core.management.CoreNotificationType.SECURITY_AUTHENTICATION_VIOLATION; import static org.apache.activemq.artemis.api.core.management.CoreNotificationType.SECURITY_PERMISSION_VIOLATION; -public class SecurityNotificationTest extends ActiveMQTestBase -{ +public class SecurityNotificationTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -65,8 +64,7 @@ public class SecurityNotificationTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testSECURITY_AUTHENTICATION_VIOLATION() throws Exception - { + public void testSECURITY_AUTHENTICATION_VIOLATION() throws Exception { String unknownUser = RandomUtil.randomString(); SecurityNotificationTest.flush(notifConsumer); @@ -74,24 +72,20 @@ public class SecurityNotificationTest extends ActiveMQTestBase ServerLocator locator = createInVMNonHALocator(); ClientSessionFactory sf = createSessionFactory(locator); - try - { + try { sf.createSession(unknownUser, RandomUtil.randomString(), false, true, true, false, 1); Assert.fail("authentication must fail and a notification of security violation must be sent"); } - catch (Exception e) - { + catch (Exception e) { } ClientMessage[] notifications = SecurityNotificationTest.consumeMessages(1, notifConsumer); - Assert.assertEquals(SECURITY_AUTHENTICATION_VIOLATION.toString(), - notifications[0].getObjectProperty(ManagementHelper.HDR_NOTIFICATION_TYPE).toString()); + Assert.assertEquals(SECURITY_AUTHENTICATION_VIOLATION.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_NOTIFICATION_TYPE).toString()); Assert.assertEquals(unknownUser, notifications[0].getObjectProperty(ManagementHelper.HDR_USER).toString()); } @Test - public void testSECURITY_PERMISSION_VIOLATION() throws Exception - { + public void testSECURITY_PERMISSION_VIOLATION() throws Exception { SimpleString queue = RandomUtil.randomSimpleString(); SimpleString address = RandomUtil.randomSimpleString(); @@ -109,23 +103,18 @@ public class SecurityNotificationTest extends ActiveMQTestBase ClientSessionFactory sf = createSessionFactory(locator); ClientSession guestSession = sf.createSession("guest", "guest", false, true, true, false, 1); - try - { + try { guestSession.createQueue(address, queue, true); Assert.fail("session creation must fail and a notification of security violation must be sent"); } - catch (Exception e) - { + catch (Exception e) { } ClientMessage[] notifications = SecurityNotificationTest.consumeMessages(1, notifConsumer); - Assert.assertEquals(SECURITY_PERMISSION_VIOLATION.toString(), - notifications[0].getObjectProperty(ManagementHelper.HDR_NOTIFICATION_TYPE).toString()); + Assert.assertEquals(SECURITY_PERMISSION_VIOLATION.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_NOTIFICATION_TYPE).toString()); Assert.assertEquals("guest", notifications[0].getObjectProperty(ManagementHelper.HDR_USER).toString()); - Assert.assertEquals(address.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_ADDRESS) - .toString()); - Assert.assertEquals(CheckType.CREATE_DURABLE_QUEUE.toString(), - notifications[0].getObjectProperty(ManagementHelper.HDR_CHECK_TYPE).toString()); + Assert.assertEquals(address.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_ADDRESS).toString()); + Assert.assertEquals(CheckType.CREATE_DURABLE_QUEUE.toString(), notifications[0].getObjectProperty(ManagementHelper.HDR_CHECK_TYPE).toString()); guestSession.close(); } @@ -136,12 +125,10 @@ public class SecurityNotificationTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - Configuration config = createDefaultInVMConfig() - .setSecurityEnabled(true); + Configuration config = createDefaultInVMConfig().setSecurityEnabled(true); server = addServer(ActiveMQServers.newActiveMQServer(config, false)); server.start(); @@ -155,8 +142,7 @@ public class SecurityNotificationTest extends ActiveMQTestBase Role role = new Role("notif", true, true, true, true, true, true, true); Set roles = new HashSet(); roles.add(role); - server.getSecurityRepository().addMatch(ActiveMQDefaultConfiguration.getDefaultManagementNotificationAddress().toString(), - roles); + server.getSecurityRepository().addMatch(ActiveMQDefaultConfiguration.getDefaultManagementNotificationAddress().toString(), roles); securityManager.getConfiguration().addRole("admin", "notif"); @@ -172,28 +158,22 @@ public class SecurityNotificationTest extends ActiveMQTestBase // Private ------------------------------------------------------- - private static void flush(final ClientConsumer notifConsumer) throws ActiveMQException - { + private static void flush(final ClientConsumer notifConsumer) throws ActiveMQException { ClientMessage message = null; - do - { + do { message = notifConsumer.receive(500); - } - while (message != null); + } while (message != null); } - protected static ClientMessage[] consumeMessages(final int expected, final ClientConsumer consumer) throws Exception - { + protected static ClientMessage[] consumeMessages(final int expected, + final ClientConsumer consumer) throws Exception { ClientMessage[] messages = new ClientMessage[expected]; ClientMessage m = null; - for (int i = 0; i < expected; i++) - { + for (int i = 0; i < expected; i++) { m = consumer.receive(500); - if (m != null) - { - for (SimpleString key : m.getPropertyNames()) - { + if (m != null) { + for (SimpleString key : m.getPropertyNames()) { System.out.println(key + "=" + m.getObjectProperty(key)); } } @@ -202,11 +182,8 @@ public class SecurityNotificationTest extends ActiveMQTestBase m.acknowledge(); } m = consumer.receiveImmediate(); - if (m != null) - { - for (SimpleString key : m.getPropertyNames()) - - { + if (m != null) { + for (SimpleString key : m.getPropertyNames()) { System.out.println(key + "=" + m.getObjectProperty(key)); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/FuseMQTTClientProvider.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/FuseMQTTClientProvider.java index f5dbe30e04..f0515ba9f2 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/FuseMQTTClientProvider.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/FuseMQTTClientProvider.java @@ -28,14 +28,13 @@ import org.fusesource.mqtt.client.Topic; import static org.fusesource.hawtbuf.UTF8Buffer.utf8; -public class FuseMQTTClientProvider implements MQTTClientProvider -{ +public class FuseMQTTClientProvider implements MQTTClientProvider { + private final MQTT mqtt = new MQTT(); private BlockingConnection connection; @Override - public void connect(String host) throws Exception - { + public void connect(String host) throws Exception { mqtt.setHost(host); mqtt.setVersion("3.1.1"); // shut off connect retry @@ -47,46 +46,38 @@ public class FuseMQTTClientProvider implements MQTTClientProvider } @Override - public void disconnect() throws Exception - { - if (this.connection != null) - { + public void disconnect() throws Exception { + if (this.connection != null) { this.connection.disconnect(); } } @Override - public void publish(String topic, byte[] payload, int qos) throws Exception - { + public void publish(String topic, byte[] payload, int qos) throws Exception { publish(topic, payload, qos, false); } @Override - public void publish(String topic, byte[] payload, int qos, boolean retained) throws Exception - { + public void publish(String topic, byte[] payload, int qos, boolean retained) throws Exception { connection.publish(topic, payload, QoS.values()[qos], retained); } @Override - public void subscribe(String topic, int qos) throws Exception - { + public void subscribe(String topic, int qos) throws Exception { Topic[] topics = {new Topic(utf8(topic), QoS.values()[qos])}; connection.subscribe(topics); } @Override - public void unsubscribe(String topic) throws Exception - { + public void unsubscribe(String topic) throws Exception { connection.unsubscribe(new String[]{topic}); } @Override - public byte[] receive(int timeout) throws Exception - { + public byte[] receive(int timeout) throws Exception { byte[] result = null; Message message = connection.receive(timeout, TimeUnit.MILLISECONDS); - if (message != null) - { + if (message != null) { result = message.getPayload(); message.ack(); } @@ -94,38 +85,32 @@ public class FuseMQTTClientProvider implements MQTTClientProvider } @Override - public void setSslContext(SSLContext sslContext) - { + public void setSslContext(SSLContext sslContext) { mqtt.setSslContext(sslContext); } @Override - public void setWillMessage(String string) - { + public void setWillMessage(String string) { mqtt.setWillMessage(string); } @Override - public void setWillTopic(String topic) - { + public void setWillTopic(String topic) { mqtt.setWillTopic(topic); } @Override - public void setClientId(String clientId) - { + public void setClientId(String clientId) { mqtt.setClientId(clientId); } @Override - public void kill() throws Exception - { + public void kill() throws Exception { connection.kill(); } @Override - public void setKeepAlive(int keepAlive) throws Exception - { + public void setKeepAlive(int keepAlive) throws Exception { mqtt.setKeepAlive((short) keepAlive); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/MQTTClientProvider.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/MQTTClientProvider.java index f26bfb8b88..284d5f0b3a 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/MQTTClientProvider.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/MQTTClientProvider.java @@ -17,8 +17,8 @@ package org.apache.activemq.artemis.tests.integration.mqtt.imported; -public interface MQTTClientProvider -{ +public interface MQTTClientProvider { + void connect(String host) throws Exception; void disconnect() throws Exception; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/MQTTTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/MQTTTest.java index 2a790e8ce4..9a63da195e 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/MQTTTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/MQTTTest.java @@ -28,7 +28,6 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; - import org.apache.activemq.artemis.core.protocol.mqtt.MQTTConnectionManager; import org.apache.activemq.artemis.core.protocol.mqtt.MQTTSession; import org.apache.activemq.artemis.tests.integration.mqtt.imported.util.Wait; @@ -50,16 +49,14 @@ import org.vertx.java.core.impl.ConcurrentHashSet; /** * MQTT Test imported from ActiveMQ MQTT component. */ -public class MQTTTest extends MQTTTestSupport -{ +public class MQTTTest extends MQTTTestSupport { private static final Logger LOG = LoggerFactory.getLogger(MQTTTest.class); private static final int NUM_MESSAGES = 250; @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { Field sessions = MQTTSession.class.getDeclaredField("SESSIONS"); sessions.setAccessible(true); sessions.set(null, new ConcurrentHashMap<>()); @@ -72,8 +69,7 @@ public class MQTTTest extends MQTTTestSupport } @Test(timeout = 60 * 1000) - public void testSendAndReceiveMQTT() throws Exception - { + public void testSendAndReceiveMQTT() throws Exception { final MQTTClientProvider subscriptionProvider = getMQTTClientProvider(); initializeConnection(subscriptionProvider); @@ -81,21 +77,16 @@ public class MQTTTest extends MQTTTestSupport final CountDownLatch latch = new CountDownLatch(NUM_MESSAGES); - Thread thread = new Thread(new Runnable() - { + Thread thread = new Thread(new Runnable() { @Override - public void run() - { - for (int i = 0; i < NUM_MESSAGES; i++) - { - try - { + public void run() { + for (int i = 0; i < NUM_MESSAGES; i++) { + try { byte[] payload = subscriptionProvider.receive(10000); assertNotNull("Should get a message", payload); latch.countDown(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); break; } @@ -108,8 +99,7 @@ public class MQTTTest extends MQTTTestSupport final MQTTClientProvider publishProvider = getMQTTClientProvider(); initializeConnection(publishProvider); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { String payload = "Message " + i; publishProvider.publish("foo/bah", payload.getBytes(), AT_LEAST_ONCE); } @@ -121,8 +111,7 @@ public class MQTTTest extends MQTTTestSupport } @Test(timeout = 60 * 1000) - public void testUnsubscribeMQTT() throws Exception - { + public void testUnsubscribeMQTT() throws Exception { final MQTTClientProvider subscriptionProvider = getMQTTClientProvider(); initializeConnection(subscriptionProvider); @@ -132,21 +121,16 @@ public class MQTTTest extends MQTTTestSupport final CountDownLatch latch = new CountDownLatch(NUM_MESSAGES / 2); - Thread thread = new Thread(new Runnable() - { + Thread thread = new Thread(new Runnable() { @Override - public void run() - { - for (int i = 0; i < NUM_MESSAGES; i++) - { - try - { + public void run() { + for (int i = 0; i < NUM_MESSAGES; i++) { + try { byte[] payload = subscriptionProvider.receive(10000); assertNotNull("Should get a message", payload); latch.countDown(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); break; } @@ -159,11 +143,9 @@ public class MQTTTest extends MQTTTestSupport final MQTTClientProvider publishProvider = getMQTTClientProvider(); initializeConnection(publishProvider); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { String payload = "Message " + i; - if (i == NUM_MESSAGES / 2) - { + if (i == NUM_MESSAGES / 2) { subscriptionProvider.unsubscribe(topic); } publishProvider.publish(topic, payload.getBytes(), AT_LEAST_ONCE); @@ -176,8 +158,7 @@ public class MQTTTest extends MQTTTestSupport } @Test(timeout = 60 * 1000) - public void testSendAtMostOnceReceiveExactlyOnce() throws Exception - { + public void testSendAtMostOnceReceiveExactlyOnce() throws Exception { /** * Although subscribing with EXACTLY ONCE, the message gets published * with AT_MOST_ONCE - in MQTT the QoS is always determined by the @@ -186,8 +167,7 @@ public class MQTTTest extends MQTTTestSupport final MQTTClientProvider provider = getMQTTClientProvider(); initializeConnection(provider); provider.subscribe("foo", EXACTLY_ONCE); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { String payload = "Test Message: " + i; provider.publish("foo", payload.getBytes(), AT_MOST_ONCE); byte[] message = provider.receive(5000); @@ -198,13 +178,11 @@ public class MQTTTest extends MQTTTestSupport } @Test(timeout = 2 * 60 * 1000) - public void testSendAtLeastOnceReceiveExactlyOnce() throws Exception - { + public void testSendAtLeastOnceReceiveExactlyOnce() throws Exception { final MQTTClientProvider provider = getMQTTClientProvider(); initializeConnection(provider); provider.subscribe("foo", EXACTLY_ONCE); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { String payload = "Test Message: " + i; provider.publish("foo", payload.getBytes(), AT_LEAST_ONCE); byte[] message = provider.receive(5000); @@ -215,13 +193,11 @@ public class MQTTTest extends MQTTTestSupport } @Test(timeout = 2 * 60 * 1000) - public void testSendAtLeastOnceReceiveAtMostOnce() throws Exception - { + public void testSendAtLeastOnceReceiveAtMostOnce() throws Exception { final MQTTClientProvider provider = getMQTTClientProvider(); initializeConnection(provider); provider.subscribe("foo", AT_MOST_ONCE); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { String payload = "Test Message: " + i; provider.publish("foo", payload.getBytes(), AT_LEAST_ONCE); byte[] message = provider.receive(5000); @@ -232,13 +208,11 @@ public class MQTTTest extends MQTTTestSupport } @Test(timeout = 60 * 1000) - public void testSendAndReceiveAtMostOnce() throws Exception - { + public void testSendAndReceiveAtMostOnce() throws Exception { final MQTTClientProvider provider = getMQTTClientProvider(); initializeConnection(provider); provider.subscribe("foo", AT_MOST_ONCE); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { String payload = "Test Message: " + i; provider.publish("foo", payload.getBytes(), AT_MOST_ONCE); byte[] message = provider.receive(5000); @@ -249,13 +223,11 @@ public class MQTTTest extends MQTTTestSupport } @Test(timeout = 2 * 60 * 1000) - public void testSendAndReceiveAtLeastOnce() throws Exception - { + public void testSendAndReceiveAtLeastOnce() throws Exception { final MQTTClientProvider provider = getMQTTClientProvider(); initializeConnection(provider); provider.subscribe("foo", AT_LEAST_ONCE); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { String payload = "Test Message: " + i; provider.publish("foo", payload.getBytes(), AT_LEAST_ONCE); byte[] message = provider.receive(5000); @@ -266,8 +238,7 @@ public class MQTTTest extends MQTTTestSupport } @Test(timeout = 60 * 1000) - public void testSendAndReceiveExactlyOnce() throws Exception - { + public void testSendAndReceiveExactlyOnce() throws Exception { final MQTTClientProvider publisher = getMQTTClientProvider(); initializeConnection(publisher); @@ -275,8 +246,7 @@ public class MQTTTest extends MQTTTestSupport initializeConnection(subscriber); subscriber.subscribe("foo", EXACTLY_ONCE); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { String payload = "Test Message: " + i; publisher.publish("foo", payload.getBytes(), EXACTLY_ONCE); byte[] message = subscriber.receive(5000); @@ -288,11 +258,9 @@ public class MQTTTest extends MQTTTestSupport } @Test(timeout = 60 * 1000) - public void testSendAndReceiveLargeMessages() throws Exception - { + public void testSendAndReceiveLargeMessages() throws Exception { byte[] payload = new byte[1024 * 32]; - for (int i = 0; i < payload.length; i++) - { + for (int i = 0; i < payload.length; i++) { payload[i] = '2'; } final MQTTClientProvider publisher = getMQTTClientProvider(); @@ -302,8 +270,7 @@ public class MQTTTest extends MQTTTestSupport initializeConnection(subscriber); subscriber.subscribe("foo", AT_LEAST_ONCE); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { publisher.publish("foo", payload, AT_LEAST_ONCE); byte[] message = subscriber.receive(5000); assertNotNull("Should get a message", message); @@ -315,8 +282,7 @@ public class MQTTTest extends MQTTTestSupport } @Test(timeout = 60 * 1000) - public void testSendAndReceiveRetainedMessages() throws Exception - { + public void testSendAndReceiveRetainedMessages() throws Exception { final MQTTClientProvider publisher = getMQTTClientProvider(); initializeConnection(publisher); @@ -327,23 +293,20 @@ public class MQTTTest extends MQTTTestSupport publisher.publish("foo", RETAINED.getBytes(), AT_LEAST_ONCE, true); List messages = new ArrayList(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { messages.add("TEST MESSAGE:" + i); } subscriber.subscribe("foo", AT_LEAST_ONCE); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { publisher.publish("foo", messages.get(i).getBytes(), AT_LEAST_ONCE); } byte[] msg = subscriber.receive(5000); assertNotNull(msg); assertEquals(RETAINED, new String(msg)); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { msg = subscriber.receive(5000); assertNotNull(msg); assertEquals(messages.get(i), new String(msg)); @@ -353,8 +316,7 @@ public class MQTTTest extends MQTTTestSupport } @Test(timeout = 30 * 1000) - public void testValidZeroLengthClientId() throws Exception - { + public void testValidZeroLengthClientId() throws Exception { MQTT mqtt = createMQTTConnection(); mqtt.setClientId(""); mqtt.setCleanSession(true); @@ -365,8 +327,7 @@ public class MQTTTest extends MQTTTestSupport } @Test(timeout = 2 * 60 * 1000) - public void testMQTTPathPatterns() throws Exception - { + public void testMQTTPathPatterns() throws Exception { MQTT mqtt = createMQTTConnection(); mqtt.setClientId(""); mqtt.setCleanSession(true); @@ -376,8 +337,7 @@ public class MQTTTest extends MQTTTestSupport final String RETAINED = "RETAINED"; String[] topics = {"TopicA", "/TopicA", "/", "TopicA/", "//"}; - for (String topic : topics) - { + for (String topic : topics) { // test retained message connection.publish(topic, (RETAINED + topic).getBytes(), QoS.AT_LEAST_ONCE, true); @@ -400,8 +360,7 @@ public class MQTTTest extends MQTTTestSupport // test wildcard patterns with above topics String[] wildcards = {"#", "+", "+/#", "/+", "+/", "+/+", "+/+/", "+/+/+"}; - for (String wildcard : wildcards) - { + for (String wildcard : wildcards) { final Pattern pattern = Pattern.compile(wildcard.replaceAll("/?#", "(/?.*)*").replaceAll("\\+", "[^/]*")); connection = mqtt.blockingConnection(); @@ -411,8 +370,7 @@ public class MQTTTest extends MQTTTestSupport // test retained messages Message msg = connection.receive(5, TimeUnit.SECONDS); - do - { + do { assertNotNull("RETAINED null " + wildcard, msg); assertTrue("RETAINED prefix " + wildcard, new String(msg.getPayload()).startsWith(RETAINED)); assertTrue("RETAINED matching " + wildcard + " " + msg.getTopic(), pattern.matcher(msg.getTopic()).matches()); @@ -421,13 +379,11 @@ public class MQTTTest extends MQTTTestSupport } while (msg != null); // test non-retained message - for (String topic : topics) - { + for (String topic : topics) { connection.publish(topic, topic.getBytes(), QoS.AT_LEAST_ONCE, false); } msg = connection.receive(1000, TimeUnit.MILLISECONDS); - do - { + do { assertNotNull("Non-retained Null " + wildcard, msg); assertTrue("Non-retained matching " + wildcard + " " + msg.getTopic(), pattern.matcher(msg.getTopic()).matches()); msg.ack(); @@ -440,11 +396,9 @@ public class MQTTTest extends MQTTTestSupport } @Test(timeout = 60 * 1000) - public void testMQTTRetainQoS() throws Exception - { + public void testMQTTRetainQoS() throws Exception { String[] topics = {"AT_MOST_ONCE", "AT_LEAST_ONCE", "EXACTLY_ONCE"}; - for (int i = 0; i < topics.length; i++) - { + for (int i = 0; i < topics.length; i++) { final String topic = topics[i]; MQTT mqtt = createMQTTConnection(); @@ -452,14 +406,11 @@ public class MQTTTest extends MQTTTestSupport mqtt.setKeepAlive((short) 2); final int[] actualQoS = {-1}; - mqtt.setTracer(new Tracer() - { + mqtt.setTracer(new Tracer() { @Override - public void onReceive(MQTTFrame frame) - { + public void onReceive(MQTTFrame frame) { // validate the QoS - if (frame.messageType() == PUBLISH.TYPE) - { + if (frame.messageType() == PUBLISH.TYPE) { actualQoS[0] = frame.qos().ordinal(); } } @@ -474,8 +425,7 @@ public class MQTTTest extends MQTTTestSupport assertNotNull(msg); assertEquals(topic, new String(msg.getPayload())); int waitCount = 0; - while (actualQoS[0] == -1 && waitCount < 10) - { + while (actualQoS[0] == -1 && waitCount < 10) { Thread.sleep(1000); waitCount++; } @@ -489,21 +439,17 @@ public class MQTTTest extends MQTTTestSupport } @Test(timeout = 60 * 1000) - public void testDuplicateSubscriptions() throws Exception - { + public void testDuplicateSubscriptions() throws Exception { MQTT mqtt = createMQTTConnection(); mqtt.setClientId("foo"); mqtt.setKeepAlive((short) 20); final int[] actualQoS = {-1}; - mqtt.setTracer(new Tracer() - { + mqtt.setTracer(new Tracer() { @Override - public void onReceive(MQTTFrame frame) - { + public void onReceive(MQTTFrame frame) { // validate the QoS - if (frame.messageType() == PUBLISH.TYPE) - { + if (frame.messageType() == PUBLISH.TYPE) { actualQoS[0] = frame.qos().ordinal(); } } @@ -516,8 +462,7 @@ public class MQTTTest extends MQTTTestSupport connection.publish("TopicA", RETAIN.getBytes(), QoS.EXACTLY_ONCE, true); QoS[] qoss = {QoS.AT_MOST_ONCE, QoS.AT_MOST_ONCE, QoS.AT_LEAST_ONCE, QoS.EXACTLY_ONCE}; - for (QoS qos : qoss) - { + for (QoS qos : qoss) { connection.subscribe(new Topic[]{new Topic("TopicA", qos)}); final Message msg = connection.receive(5000, TimeUnit.MILLISECONDS); @@ -525,8 +470,7 @@ public class MQTTTest extends MQTTTestSupport assertEquals(RETAIN, new String(msg.getPayload())); msg.ack(); int waitCount = 0; - while (actualQoS[0] == -1 && waitCount < 10) - { + while (actualQoS[0] == -1 && waitCount < 10) { Thread.sleep(1000); waitCount++; } @@ -540,8 +484,7 @@ public class MQTTTest extends MQTTTestSupport } @Test(timeout = 120 * 1000) - public void testRetainedMessage() throws Exception - { + public void testRetainedMessage() throws Exception { MQTT mqtt = createMQTTConnection(); mqtt.setKeepAlive((short) 60); @@ -549,8 +492,7 @@ public class MQTTTest extends MQTTTestSupport final String TOPICA = "TopicA"; final String[] clientIds = {null, "foo", "durable"}; - for (String clientId : clientIds) - { + for (String clientId : clientIds) { LOG.info("Testing now with Client ID: {}", clientId); mqtt.setClientId(clientId); @@ -611,8 +553,7 @@ public class MQTTTest extends MQTTTestSupport @Ignore @Test(timeout = 120 * 1000) - public void testRetainedMessageOnVirtualTopics() throws Exception - { + public void testRetainedMessageOnVirtualTopics() throws Exception { MQTT mqtt = createMQTTConnection(); mqtt.setKeepAlive((short) 60); @@ -620,8 +561,7 @@ public class MQTTTest extends MQTTTestSupport final String TOPICA = "VirtualTopic/TopicA"; final String[] clientIds = {null, "foo", "durable"}; - for (String clientId : clientIds) - { + for (String clientId : clientIds) { LOG.info("Testing now with Client ID: {}", clientId); mqtt.setClientId(clientId); @@ -682,29 +622,23 @@ public class MQTTTest extends MQTTTestSupport } @Test(timeout = 60 * 1000) - public void testUniqueMessageIds() throws Exception - { + public void testUniqueMessageIds() throws Exception { MQTT mqtt = createMQTTConnection(); mqtt.setClientId("foo"); mqtt.setKeepAlive((short) 2); mqtt.setCleanSession(true); final List publishList = new ArrayList(); - mqtt.setTracer(new Tracer() - { + mqtt.setTracer(new Tracer() { @Override - public void onReceive(MQTTFrame frame) - { + public void onReceive(MQTTFrame frame) { LOG.info("Client received:\n" + frame); - if (frame.messageType() == PUBLISH.TYPE) - { + if (frame.messageType() == PUBLISH.TYPE) { PUBLISH publish = new PUBLISH(); - try - { + try { publish.decode(frame); } - catch (ProtocolException e) - { + catch (ProtocolException e) { fail("Error decoding publish " + e.getMessage()); } publishList.add(publish); @@ -712,8 +646,7 @@ public class MQTTTest extends MQTTTestSupport } @Override - public void onSend(MQTTFrame frame) - { + public void onSend(MQTTFrame frame) { LOG.info("Client sent:\n" + frame); } }); @@ -729,8 +662,7 @@ public class MQTTTest extends MQTTTestSupport connection.publish(TOPIC, TOPIC.getBytes(), QoS.EXACTLY_ONCE, true); String[] subs = {TOPIC, "TopicA/#", "TopicA/+"}; - for (int i = 0; i < qoss.length; i++) - { + for (int i = 0; i < qoss.length; i++) { connection.subscribe(new Topic[]{new Topic(subs[i], qoss[i])}); } @@ -739,14 +671,12 @@ public class MQTTTest extends MQTTTestSupport int received = 0; Message msg = connection.receive(5000, TimeUnit.MILLISECONDS); - do - { + do { assertNotNull(msg); assertEquals(TOPIC, new String(msg.getPayload())); msg.ack(); int waitCount = 0; - while (publishList.size() <= received && waitCount < 10) - { + while (publishList.size() <= received && waitCount < 10) { Thread.sleep(1000); waitCount++; } @@ -756,25 +686,20 @@ public class MQTTTest extends MQTTTestSupport // make sure we received distinct ids for QoS != AT_MOST_ONCE, and 0 for // AT_MOST_ONCE - for (int i = 0; i < publishList.size(); i++) - { - for (int j = i + 1; j < publishList.size(); j++) - { + for (int i = 0; i < publishList.size(); i++) { + for (int j = i + 1; j < publishList.size(); j++) { final PUBLISH publish1 = publishList.get(i); final PUBLISH publish2 = publishList.get(j); boolean qos0 = false; - if (publish1.qos() == QoS.AT_MOST_ONCE) - { + if (publish1.qos() == QoS.AT_MOST_ONCE) { qos0 = true; assertEquals(0, publish1.messageId()); } - if (publish2.qos() == QoS.AT_MOST_ONCE) - { + if (publish2.qos() == QoS.AT_MOST_ONCE) { qos0 = true; assertEquals(0, publish2.messageId()); } - if (!qos0) - { + if (!qos0) { assertNotEquals(publish1.messageId(), publish2.messageId()); } } @@ -785,27 +710,21 @@ public class MQTTTest extends MQTTTestSupport } @Test(timeout = 60 * 1000) - public void testResendMessageId() throws Exception - { + public void testResendMessageId() throws Exception { final MQTT mqtt = createMQTTConnection("resend", false); mqtt.setKeepAlive((short) 5); final List publishList = new ArrayList(); - mqtt.setTracer(new Tracer() - { + mqtt.setTracer(new Tracer() { @Override - public void onReceive(MQTTFrame frame) - { + public void onReceive(MQTTFrame frame) { LOG.info("Client received:\n" + frame); - if (frame.messageType() == PUBLISH.TYPE) - { + if (frame.messageType() == PUBLISH.TYPE) { PUBLISH publish = new PUBLISH(); - try - { + try { publish.decode(frame); } - catch (ProtocolException e) - { + catch (ProtocolException e) { fail("Error decoding publish " + e.getMessage()); } publishList.add(publish); @@ -813,8 +732,7 @@ public class MQTTTest extends MQTTTestSupport } @Override - public void onSend(MQTTFrame frame) - { + public void onSend(MQTTFrame frame) { LOG.info("Client sent:\n" + frame); } }); @@ -828,11 +746,9 @@ public class MQTTTest extends MQTTTestSupport // publish non-retained message connection.publish(TOPIC, TOPIC.getBytes(), QoS.EXACTLY_ONCE, false); - Wait.waitFor(new Wait.Condition() - { + Wait.waitFor(new Wait.Condition() { @Override - public boolean isSatisified() throws Exception - { + public boolean isSatisified() throws Exception { return publishList.size() == 2; } }, 5000); @@ -843,11 +759,9 @@ public class MQTTTest extends MQTTTestSupport connection = mqtt.blockingConnection(); connection.connect(); - Wait.waitFor(new Wait.Condition() - { + Wait.waitFor(new Wait.Condition() { @Override - public boolean isSatisified() throws Exception - { + public boolean isSatisified() throws Exception { return publishList.size() == 4; } }, 5000); @@ -857,41 +771,34 @@ public class MQTTTest extends MQTTTestSupport // In Artemis we send a new ID for every copy of the message. // make sure we received duplicate message ids -// assertTrue(publishList.get(0).messageId() == publishList.get(2).messageId() || publishList.get(0).messageId() == publishList.get(3).messageId()); -// assertTrue(publishList.get(1).messageId() == publishList.get(3).messageId() || publishList.get(1).messageId() == publishList.get(2).messageId()); -// assertTrue(publishList.get(2).dup() && publishList.get(3).dup()); + // assertTrue(publishList.get(0).messageId() == publishList.get(2).messageId() || publishList.get(0).messageId() == publishList.get(3).messageId()); + // assertTrue(publishList.get(1).messageId() == publishList.get(3).messageId() || publishList.get(1).messageId() == publishList.get(2).messageId()); + // assertTrue(publishList.get(2).dup() && publishList.get(3).dup()); connection.unsubscribe(topics); connection.disconnect(); } @Test(timeout = 90 * 1000) - public void testPacketIdGeneratorNonCleanSession() throws Exception - { + public void testPacketIdGeneratorNonCleanSession() throws Exception { final MQTT mqtt = createMQTTConnection("nonclean-packetid", false); mqtt.setKeepAlive((short) 15); final Map publishMap = new ConcurrentHashMap(); - mqtt.setTracer(new Tracer() - { + mqtt.setTracer(new Tracer() { @Override - public void onReceive(MQTTFrame frame) - { + public void onReceive(MQTTFrame frame) { LOG.info("Client received:\n" + frame); - if (frame.messageType() == PUBLISH.TYPE) - { + if (frame.messageType() == PUBLISH.TYPE) { PUBLISH publish = new PUBLISH(); - try - { + try { publish.decode(frame); LOG.info("PUBLISH " + publish); } - catch (ProtocolException e) - { + catch (ProtocolException e) { fail("Error decoding publish " + e.getMessage()); } - if (publishMap.get(publish.messageId()) != null) - { + if (publishMap.get(publish.messageId()) != null) { assertTrue(publish.dup()); } publishMap.put(publish.messageId(), publish); @@ -899,8 +806,7 @@ public class MQTTTest extends MQTTTestSupport } @Override - public void onSend(MQTTFrame frame) - { + public void onSend(MQTTFrame frame) { LOG.info("Client sent:\n" + frame); } }); @@ -912,14 +818,12 @@ public class MQTTTest extends MQTTTestSupport // publish non-retained messages final int TOTAL_MESSAGES = 10; - for (int i = 0; i < TOTAL_MESSAGES; i++) - { + for (int i = 0; i < TOTAL_MESSAGES; i++) { connection.publish(TOPIC, TOPIC.getBytes(), QoS.EXACTLY_ONCE, false); } // receive half the messages in this session - for (int i = 0; i < TOTAL_MESSAGES / 2; i++) - { + for (int i = 0; i < TOTAL_MESSAGES / 2; i++) { final Message msg = connection.receive(1000, TimeUnit.MILLISECONDS); assertNotNull(msg); assertEquals(TOPIC, new String(msg.getPayload())); @@ -932,19 +836,16 @@ public class MQTTTest extends MQTTTestSupport connection.connect(); // receive rest of the messages Message msg = null; - do - { + do { msg = connection.receive(1000, TimeUnit.MILLISECONDS); - if (msg != null) - { + if (msg != null) { assertEquals(TOPIC, new String(msg.getPayload())); msg.ack(); } } while (msg != null); // make sure we received all message ids - for (short id = 1; id <= TOTAL_MESSAGES; id++) - { + for (short id = 1; id <= TOTAL_MESSAGES; id++) { assertNotNull("No message for id " + id, publishMap.get(id)); } @@ -956,36 +857,28 @@ public class MQTTTest extends MQTTTestSupport @Test(timeout = 90 * 1000) // TODO ActiveMQ 5.x does not reset the message id generator even after a clean session. In Artemis we always reset. // If there is a good reason for this we should follow ActiveMQ. - public void testPacketIdGeneratorCleanSession() throws Exception - { + public void testPacketIdGeneratorCleanSession() throws Exception { final String[] cleanClientIds = new String[]{"", "clean-packetid", null}; final Map publishMap = new ConcurrentHashMap(); MQTT[] mqtts = new MQTT[cleanClientIds.length]; - for (int i = 0; i < cleanClientIds.length; i++) - { + for (int i = 0; i < cleanClientIds.length; i++) { mqtts[i] = createMQTTConnection("", true); mqtts[i].setKeepAlive((short) 15); - mqtts[i].setTracer(new Tracer() - { + mqtts[i].setTracer(new Tracer() { @Override - public void onReceive(MQTTFrame frame) - { + public void onReceive(MQTTFrame frame) { LOG.info("Client received:\n" + frame); - if (frame.messageType() == PUBLISH.TYPE) - { + if (frame.messageType() == PUBLISH.TYPE) { PUBLISH publish = new PUBLISH(); - try - { + try { publish.decode(frame); LOG.info("PUBLISH " + publish); } - catch (ProtocolException e) - { + catch (ProtocolException e) { fail("Error decoding publish " + e.getMessage()); } - if (publishMap.get(publish.messageId()) != null) - { + if (publishMap.get(publish.messageId()) != null) { assertTrue(publish.dup()); } publishMap.put(publish.messageId(), publish); @@ -993,16 +886,14 @@ public class MQTTTest extends MQTTTestSupport } @Override - public void onSend(MQTTFrame frame) - { + public void onSend(MQTTFrame frame) { LOG.info("Client sent:\n" + frame); } }); } final Random random = new Random(); - for (short i = 0; i < 10; i++) - { + for (short i = 0; i < 10; i++) { BlockingConnection connection = mqtts[random.nextInt(cleanClientIds.length)].blockingConnection(); connection.connect(); final String TOPIC = "TopicA/"; @@ -1026,18 +917,15 @@ public class MQTTTest extends MQTTTestSupport } @Test(timeout = 60 * 1000) - public void testClientConnectionFailure() throws Exception - { + public void testClientConnectionFailure() throws Exception { MQTT mqtt = createMQTTConnection("reconnect", false); mqtt.setKeepAlive((short) 1); final BlockingConnection connection = mqtt.blockingConnection(); connection.connect(); - Wait.waitFor(new Wait.Condition() - { + Wait.waitFor(new Wait.Condition() { @Override - public boolean isSatisified() throws Exception - { + public boolean isSatisified() throws Exception { return connection.isConnected(); } }); @@ -1054,11 +942,9 @@ public class MQTTTest extends MQTTTestSupport final BlockingConnection newConnection = mqtt.blockingConnection(); newConnection.connect(); - Wait.waitFor(new Wait.Condition() - { + Wait.waitFor(new Wait.Condition() { @Override - public boolean isSatisified() throws Exception - { + public boolean isSatisified() throws Exception { return newConnection.isConnected(); } }); @@ -1072,8 +958,7 @@ public class MQTTTest extends MQTTTestSupport } @Test(timeout = 60 * 1000) - public void testCleanSession() throws Exception - { + public void testCleanSession() throws Exception { final String CLIENTID = "cleansession"; final MQTT mqttNotClean = createMQTTConnection(CLIENTID, false); BlockingConnection notClean = mqttNotClean.blockingConnection(); @@ -1115,107 +1000,104 @@ public class MQTTTest extends MQTTTestSupport outstanding task to add cross protocol support. This task should rework these tests. The tests are included here and commented out to ensure ActiveMQ and Artemis tests are in sync. */ -// @Test(timeout = 60 * 1000) -// public void testSendMQTTReceiveJMS() throws Exception { -// doTestSendMQTTReceiveJMS("foo.*"); -// } + // @Test(timeout = 60 * 1000) + // public void testSendMQTTReceiveJMS() throws Exception { + // doTestSendMQTTReceiveJMS("foo.*"); + // } -// public void doTestSendMQTTReceiveJMS(String destinationName) throws Exception { -// final MQTTClientProvider provider = getMQTTClientProvider(); -// initializeConnection(provider); -// -// // send retained message -// final String RETAINED = "RETAINED"; -// provider.publish("foo/bah", RETAINED.getBytes(), AT_LEAST_ONCE, true); -// -// ActiveMQConnection activeMQConnection = (ActiveMQConnection) cf.createConnection(); -// // MUST set to true to receive retained messages -// activeMQConnection.setUseRetroactiveConsumer(true); -// activeMQConnection.start(); -// Session s = activeMQConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); -// javax.jms.Topic jmsTopic = s.createTopic(destinationName); -// MessageConsumer consumer = s.createConsumer(jmsTopic); -// -// // check whether we received retained message on JMS subscribe -// ActiveMQMessage message = (ActiveMQMessage) consumer.receive(5000); -// assertNotNull("Should get retained message", message); -// ByteSequence bs = message.getContent(); -// assertEquals(RETAINED, new String(bs.data, bs.offset, bs.length)); -// assertTrue(message.getBooleanProperty(RetainedMessageSubscriptionRecoveryPolicy.RETAINED_PROPERTY)); -// -// for (int i = 0; i < NUM_MESSAGES; i++) { -// String payload = "Test Message: " + i; -// provider.publish("foo/bah", payload.getBytes(), AT_LEAST_ONCE); -// message = (ActiveMQMessage) consumer.receive(5000); -// assertNotNull("Should get a message", message); -// bs = message.getContent(); -// assertEquals(payload, new String(bs.data, bs.offset, bs.length)); -// } -// -// activeMQConnection.close(); -// provider.disconnect(); -// } + // public void doTestSendMQTTReceiveJMS(String destinationName) throws Exception { + // final MQTTClientProvider provider = getMQTTClientProvider(); + // initializeConnection(provider); + // + // // send retained message + // final String RETAINED = "RETAINED"; + // provider.publish("foo/bah", RETAINED.getBytes(), AT_LEAST_ONCE, true); + // + // ActiveMQConnection activeMQConnection = (ActiveMQConnection) cf.createConnection(); + // // MUST set to true to receive retained messages + // activeMQConnection.setUseRetroactiveConsumer(true); + // activeMQConnection.start(); + // Session s = activeMQConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + // javax.jms.Topic jmsTopic = s.createTopic(destinationName); + // MessageConsumer consumer = s.createConsumer(jmsTopic); + // + // // check whether we received retained message on JMS subscribe + // ActiveMQMessage message = (ActiveMQMessage) consumer.receive(5000); + // assertNotNull("Should get retained message", message); + // ByteSequence bs = message.getContent(); + // assertEquals(RETAINED, new String(bs.data, bs.offset, bs.length)); + // assertTrue(message.getBooleanProperty(RetainedMessageSubscriptionRecoveryPolicy.RETAINED_PROPERTY)); + // + // for (int i = 0; i < NUM_MESSAGES; i++) { + // String payload = "Test Message: " + i; + // provider.publish("foo/bah", payload.getBytes(), AT_LEAST_ONCE); + // message = (ActiveMQMessage) consumer.receive(5000); + // assertNotNull("Should get a message", message); + // bs = message.getContent(); + // assertEquals(payload, new String(bs.data, bs.offset, bs.length)); + // } + // + // activeMQConnection.close(); + // provider.disconnect(); + // } // TODO As with other tests, this should be enabled as part of the cross protocol support with MQTT. -// @Test(timeout = 2 * 60 * 1000) -// public void testSendJMSReceiveMQTT() throws Exception { -// doTestSendJMSReceiveMQTT("foo.far"); -// } + // @Test(timeout = 2 * 60 * 1000) + // public void testSendJMSReceiveMQTT() throws Exception { + // doTestSendJMSReceiveMQTT("foo.far"); + // } // TODO As with other tests, this should be enabled as part of the cross protocol support with MQTT. -// public void doTestSendJMSReceiveMQTT(String destinationName) throws Exception { -// final MQTTClientProvider provider = getMQTTClientProvider(); -// initializeConnection(provider); -// -// ActiveMQConnection activeMQConnection = (ActiveMQConnection) cf.createConnection(); -// activeMQConnection.setUseRetroactiveConsumer(true); -// activeMQConnection.start(); -// Session s = activeMQConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); -// javax.jms.Topic jmsTopic = s.createTopic(destinationName); -// MessageProducer producer = s.createProducer(jmsTopic); -// -// // send retained message from JMS -// final String RETAINED = "RETAINED"; -// TextMessage sendMessage = s.createTextMessage(RETAINED); -// // mark the message to be retained -// sendMessage.setBooleanProperty(RetainedMessageSubscriptionRecoveryPolicy.RETAIN_PROPERTY, true); -// // MQTT QoS can be set using MQTTProtocolConverter.QOS_PROPERTY_NAME property -// sendMessage.setIntProperty(MQTTProtocolConverter.QOS_PROPERTY_NAME, 0); -// producer.send(sendMessage); -// -// provider.subscribe("foo/+", AT_MOST_ONCE); -// byte[] message = provider.receive(10000); -// assertNotNull("Should get retained message", message); -// assertEquals(RETAINED, new String(message)); -// -// for (int i = 0; i < NUM_MESSAGES; i++) { -// String payload = "This is Test Message: " + i; -// sendMessage = s.createTextMessage(payload); -// producer.send(sendMessage); -// message = provider.receive(5000); -// assertNotNull("Should get a message", message); -// -// assertEquals(payload, new String(message)); -// } -// provider.disconnect(); -// activeMQConnection.close(); -// } + // public void doTestSendJMSReceiveMQTT(String destinationName) throws Exception { + // final MQTTClientProvider provider = getMQTTClientProvider(); + // initializeConnection(provider); + // + // ActiveMQConnection activeMQConnection = (ActiveMQConnection) cf.createConnection(); + // activeMQConnection.setUseRetroactiveConsumer(true); + // activeMQConnection.start(); + // Session s = activeMQConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + // javax.jms.Topic jmsTopic = s.createTopic(destinationName); + // MessageProducer producer = s.createProducer(jmsTopic); + // + // // send retained message from JMS + // final String RETAINED = "RETAINED"; + // TextMessage sendMessage = s.createTextMessage(RETAINED); + // // mark the message to be retained + // sendMessage.setBooleanProperty(RetainedMessageSubscriptionRecoveryPolicy.RETAIN_PROPERTY, true); + // // MQTT QoS can be set using MQTTProtocolConverter.QOS_PROPERTY_NAME property + // sendMessage.setIntProperty(MQTTProtocolConverter.QOS_PROPERTY_NAME, 0); + // producer.send(sendMessage); + // + // provider.subscribe("foo/+", AT_MOST_ONCE); + // byte[] message = provider.receive(10000); + // assertNotNull("Should get retained message", message); + // assertEquals(RETAINED, new String(message)); + // + // for (int i = 0; i < NUM_MESSAGES; i++) { + // String payload = "This is Test Message: " + i; + // sendMessage = s.createTextMessage(payload); + // producer.send(sendMessage); + // message = provider.receive(5000); + // assertNotNull("Should get a message", message); + // + // assertEquals(payload, new String(message)); + // } + // provider.disconnect(); + // activeMQConnection.close(); + // } @Test(timeout = 60 * 1000) - public void testPingKeepsInactivityMonitorAlive() throws Exception - { + public void testPingKeepsInactivityMonitorAlive() throws Exception { MQTT mqtt = createMQTTConnection(); mqtt.setClientId("foo"); mqtt.setKeepAlive((short) 2); final BlockingConnection connection = mqtt.blockingConnection(); connection.connect(); - assertTrue("KeepAlive didn't work properly", Wait.waitFor(new Wait.Condition() - { + assertTrue("KeepAlive didn't work properly", Wait.waitFor(new Wait.Condition() { @Override - public boolean isSatisified() throws Exception - { + public boolean isSatisified() throws Exception { return connection.isConnected(); } })); @@ -1224,8 +1106,7 @@ public class MQTTTest extends MQTTTestSupport } @Test(timeout = 60 * 1000) - public void testTurnOffInactivityMonitor() throws Exception - { + public void testTurnOffInactivityMonitor() throws Exception { stopBroker(); protocolConfig = "transport.useInactivityMonitor=false"; startBroker(); @@ -1236,12 +1117,10 @@ public class MQTTTest extends MQTTTestSupport final BlockingConnection connection = mqtt.blockingConnection(); connection.connect(); - assertTrue("KeepAlive didn't work properly", Wait.waitFor(new Wait.Condition() - { + assertTrue("KeepAlive didn't work properly", Wait.waitFor(new Wait.Condition() { @Override - public boolean isSatisified() throws Exception - { + public boolean isSatisified() throws Exception { return connection.isConnected(); } })); @@ -1252,8 +1131,7 @@ public class MQTTTest extends MQTTTestSupport @Ignore @Test(timeout = 60 * 1000) // TODO Make dollar topics configurable in code base. - public void testPublishDollarTopics() throws Exception - { + public void testPublishDollarTopics() throws Exception { MQTT mqtt = createMQTTConnection(); final String clientId = "publishDollar"; mqtt.setClientId(clientId); @@ -1293,8 +1171,7 @@ public class MQTTTest extends MQTTTestSupport @Ignore @Test(timeout = 60 * 1000) // TODO We currently do not support link stealing. This needs to be enabled for this test to pass. - public void testDuplicateClientId() throws Exception - { + public void testDuplicateClientId() throws Exception { // test link stealing enabled by default final String clientId = "duplicateClient"; MQTT mqtt = createMQTTConnection(clientId, false); @@ -1309,20 +1186,16 @@ public class MQTTTest extends MQTTTestSupport final BlockingConnection connection1 = mqtt1.blockingConnection(); connection1.connect(); - assertTrue("Duplicate client disconnected", Wait.waitFor(new Wait.Condition() - { + assertTrue("Duplicate client disconnected", Wait.waitFor(new Wait.Condition() { @Override - public boolean isSatisified() throws Exception - { + public boolean isSatisified() throws Exception { return connection1.isConnected(); } })); - assertTrue("Old client still connected", Wait.waitFor(new Wait.Condition() - { + assertTrue("Old client still connected", Wait.waitFor(new Wait.Condition() { @Override - public boolean isSatisified() throws Exception - { + public boolean isSatisified() throws Exception { return !connection.isConnected(); } })); @@ -1344,13 +1217,11 @@ public class MQTTTest extends MQTTTestSupport mqtt1 = createMQTTConnection(clientId, false); mqtt1.setKeepAlive((short) 2); final BlockingConnection connection3 = mqtt1.blockingConnection(); - try - { + try { connection3.connect(); fail("Duplicate client connected"); } - catch (Exception e) - { + catch (Exception e) { // ignore } @@ -1360,59 +1231,57 @@ public class MQTTTest extends MQTTTestSupport } // TODO As with other tests, this should be enabled as part of the cross protocol support with MQTT. -// @Test(timeout = 30 * 10000) -// public void testJmsMapping() throws Exception { -// doTestJmsMapping("test.foo"); -// } + // @Test(timeout = 30 * 10000) + // public void testJmsMapping() throws Exception { + // doTestJmsMapping("test.foo"); + // } // TODO As with other tests, this should be enabled as part of the cross protocol support with MQTT. -// public void doTestJmsMapping(String destinationName) throws Exception { -// // start up jms consumer -// Connection jmsConn = cf.createConnection(); -// Session session = jmsConn.createSession(false, Session.AUTO_ACKNOWLEDGE); -// Destination dest = session.createTopic(destinationName); -// MessageConsumer consumer = session.createConsumer(dest); -// jmsConn.start(); -// -// // set up mqtt producer -// MQTT mqtt = createMQTTConnection(); -// mqtt.setClientId("foo3"); -// mqtt.setKeepAlive((short) 2); -// final BlockingConnection connection = mqtt.blockingConnection(); -// connection.connect(); -// -// int messagesToSend = 5; -// -// // publish -// for (int i = 0; i < messagesToSend; ++i) { -// connection.publish("test/foo", "hello world".getBytes(), QoS.AT_LEAST_ONCE, false); -// } -// -// connection.disconnect(); -// -// for (int i = 0; i < messagesToSend; i++) { -// -// javax.jms.Message message = consumer.receive(2 * 1000); -// assertNotNull(message); -// assertTrue(message instanceof BytesMessage); -// BytesMessage bytesMessage = (BytesMessage) message; -// -// int length = (int) bytesMessage.getBodyLength(); -// byte[] buffer = new byte[length]; -// bytesMessage.readBytes(buffer); -// assertEquals("hello world", new String(buffer)); -// } -// -// jmsConn.close(); -// } + // public void doTestJmsMapping(String destinationName) throws Exception { + // // start up jms consumer + // Connection jmsConn = cf.createConnection(); + // Session session = jmsConn.createSession(false, Session.AUTO_ACKNOWLEDGE); + // Destination dest = session.createTopic(destinationName); + // MessageConsumer consumer = session.createConsumer(dest); + // jmsConn.start(); + // + // // set up mqtt producer + // MQTT mqtt = createMQTTConnection(); + // mqtt.setClientId("foo3"); + // mqtt.setKeepAlive((short) 2); + // final BlockingConnection connection = mqtt.blockingConnection(); + // connection.connect(); + // + // int messagesToSend = 5; + // + // // publish + // for (int i = 0; i < messagesToSend; ++i) { + // connection.publish("test/foo", "hello world".getBytes(), QoS.AT_LEAST_ONCE, false); + // } + // + // connection.disconnect(); + // + // for (int i = 0; i < messagesToSend; i++) { + // + // javax.jms.Message message = consumer.receive(2 * 1000); + // assertNotNull(message); + // assertTrue(message instanceof BytesMessage); + // BytesMessage bytesMessage = (BytesMessage) message; + // + // int length = (int) bytesMessage.getBodyLength(); + // byte[] buffer = new byte[length]; + // bytesMessage.readBytes(buffer); + // assertEquals("hello world", new String(buffer)); + // } + // + // jmsConn.close(); + // } @Test(timeout = 30 * 10000) - public void testSubscribeMultipleTopics() throws Exception - { + public void testSubscribeMultipleTopics() throws Exception { byte[] payload = new byte[1024 * 32]; - for (int i = 0; i < payload.length; i++) - { + for (int i = 0; i < payload.length; i++) { payload[i] = '2'; } @@ -1427,14 +1296,12 @@ public class MQTTTest extends MQTTTestSupport Topic[] wildcardTopic = {new Topic("Topic/#", QoS.AT_LEAST_ONCE)}; connection.subscribe(wildcardTopic); - for (Topic topic : topics) - { + for (Topic topic : topics) { connection.publish(topic.name().toString(), payload, QoS.AT_LEAST_ONCE, false); } int received = 0; - for (int i = 0; i < topics.length; ++i) - { + for (int i = 0; i < topics.length; ++i) { Message message = connection.receive(); assertNotNull(message); received++; @@ -1448,11 +1315,9 @@ public class MQTTTest extends MQTTTestSupport } @Test(timeout = 60 * 1000) - public void testReceiveMessageSentWhileOffline() throws Exception - { + public void testReceiveMessageSentWhileOffline() throws Exception { final byte[] payload = new byte[1024 * 32]; - for (int i = 0; i < payload.length; i++) - { + for (int i = 0; i < payload.length; i++) { payload[i] = '2'; } @@ -1471,14 +1336,12 @@ public class MQTTTest extends MQTTTestSupport Topic[] topics = {new Topic("TopicA", QoS.EXACTLY_ONCE)}; connectionSub.subscribe(topics); - for (int i = 0; i < messagesPerRun; ++i) - { + for (int i = 0; i < messagesPerRun; ++i) { connectionPub.publish(topics[0].name().toString(), payload, QoS.AT_LEAST_ONCE, false); } int received = 0; - for (int i = 0; i < messagesPerRun; ++i) - { + for (int i = 0; i < messagesPerRun; ++i) { Message message = connectionSub.receive(5, TimeUnit.SECONDS); assertNotNull(message); received++; @@ -1487,11 +1350,9 @@ public class MQTTTest extends MQTTTestSupport } connectionSub.disconnect(); - for (int j = 0; j < numberOfRuns; j++) - { + for (int j = 0; j < numberOfRuns; j++) { - for (int i = 0; i < messagesPerRun; ++i) - { + for (int i = 0; i < messagesPerRun; ++i) { connectionPub.publish(topics[0].name().toString(), payload, QoS.AT_LEAST_ONCE, false); } @@ -1499,8 +1360,7 @@ public class MQTTTest extends MQTTTestSupport connectionSub.connect(); connectionSub.subscribe(topics); - for (int i = 0; i < messagesPerRun; ++i) - { + for (int i = 0; i < messagesPerRun; ++i) { Message message = connectionSub.receive(5, TimeUnit.SECONDS); assertNotNull(message); received++; @@ -1513,8 +1373,7 @@ public class MQTTTest extends MQTTTestSupport } @Test(timeout = 30 * 1000) - public void testDefaultKeepAliveWhenClientSpecifiesZero() throws Exception - { + public void testDefaultKeepAliveWhenClientSpecifiesZero() throws Exception { stopBroker(); protocolConfig = "transport.defaultKeepAlive=2000"; startBroker(); @@ -1525,20 +1384,17 @@ public class MQTTTest extends MQTTTestSupport final BlockingConnection connection = mqtt.blockingConnection(); connection.connect(); - assertTrue("KeepAlive didn't work properly", Wait.waitFor(new Wait.Condition() - { + assertTrue("KeepAlive didn't work properly", Wait.waitFor(new Wait.Condition() { @Override - public boolean isSatisified() throws Exception - { + public boolean isSatisified() throws Exception { return connection.isConnected(); } })); } @Test(timeout = 60 * 1000) - public void testReuseConnection() throws Exception - { + public void testReuseConnection() throws Exception { MQTT mqtt = createMQTTConnection(); mqtt.setClientId("Test-Client"); @@ -1557,8 +1413,7 @@ public class MQTTTest extends MQTTTestSupport } @Test(timeout = 60 * 1000) - public void testNoMessageReceivedAfterUnsubscribeMQTT() throws Exception - { + public void testNoMessageReceivedAfterUnsubscribeMQTT() throws Exception { Topic[] topics = {new Topic("TopicA", QoS.EXACTLY_ONCE)}; MQTT mqttPub = createMQTTConnection("MQTTPub-Client", true); @@ -1575,8 +1430,7 @@ public class MQTTTest extends MQTTTestSupport connectionSub.subscribe(topics); connectionSub.disconnect(); - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { String payload = "Message " + i; connectionPub.publish(topics[0].name().toString(), payload.getBytes(), QoS.EXACTLY_ONCE, false); } @@ -1585,8 +1439,7 @@ public class MQTTTest extends MQTTTestSupport connectionSub.connect(); int received = 0; - for (int i = 0; i < 5; ++i) - { + for (int i = 0; i < 5; ++i) { Message message = connectionSub.receive(5, TimeUnit.SECONDS); assertNotNull("Missing message " + i, message); LOG.info("Message is " + new String(message.getPayload())); @@ -1599,8 +1452,7 @@ public class MQTTTest extends MQTTTestSupport connectionSub.unsubscribe(new String[]{"TopicA"}); // send more messages - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { String payload = "Message " + i; connectionPub.publish(topics[0].name().toString(), payload.getBytes(), QoS.EXACTLY_ONCE, false); } @@ -1613,8 +1465,7 @@ public class MQTTTest extends MQTTTestSupport } @Test(timeout = 60 * 1000) - public void testMQTT311Connection() throws Exception - { + public void testMQTT311Connection() throws Exception { MQTT mqtt = createMQTTConnection(); mqtt.setClientId("foo"); mqtt.setVersion("3.1.1"); @@ -1624,105 +1475,104 @@ public class MQTTTest extends MQTTTestSupport } // TODO This should be reworked to align with Artemis recovery. -// @Test(timeout = 60 * 1000) -// public void testActiveMQRecoveryPolicy() throws Exception { -// // test with ActiveMQ LastImageSubscriptionRecoveryPolicy -// final PolicyMap policyMap = new PolicyMap(); -// final PolicyEntry policyEntry = new PolicyEntry(); -// policyEntry.setSubscriptionRecoveryPolicy(new LastImageSubscriptionRecoveryPolicy()); -// policyMap.put(new ActiveMQTopic(">"), policyEntry); -// brokerService.setDestinationPolicy(policyMap); -// -// MQTT mqtt = createMQTTConnection("pub-sub", true); -// final int[] retain = new int[1]; -// final int[] nonretain = new int[1]; -// mqtt.setTracer(new Tracer() { -// @Override -// public void onReceive(MQTTFrame frame) { -// if (frame.messageType() == PUBLISH.TYPE) { -// LOG.info("Received message with retain=" + frame.retain()); -// if (frame.retain()) { -// retain[0]++; -// } else { -// nonretain[0]++; -// } -// } -// } -// }); -// -// BlockingConnection connection = mqtt.blockingConnection(); -// connection.connect(); -// final String RETAINED = "RETAINED"; -// connection.publish("one", RETAINED.getBytes(), QoS.AT_LEAST_ONCE, true); -// connection.publish("two", RETAINED.getBytes(), QoS.AT_LEAST_ONCE, true); -// -// final String NONRETAINED = "NONRETAINED"; -// connection.publish("one", NONRETAINED.getBytes(), QoS.AT_LEAST_ONCE, false); -// connection.publish("two", NONRETAINED.getBytes(), QoS.AT_LEAST_ONCE, false); -// -// connection.subscribe(new Topic[]{new Topic("#", QoS.AT_LEAST_ONCE)}); -// for (int i = 0; i < 4; i++) { -// final Message message = connection.receive(30, TimeUnit.SECONDS); -// assertNotNull("Should receive 4 messages", message); -// message.ack(); -// } -// assertEquals("Should receive 2 retained messages", 2, retain[0]); -// assertEquals("Should receive 2 non-retained messages", 2, nonretain[0]); -// } + // @Test(timeout = 60 * 1000) + // public void testActiveMQRecoveryPolicy() throws Exception { + // // test with ActiveMQ LastImageSubscriptionRecoveryPolicy + // final PolicyMap policyMap = new PolicyMap(); + // final PolicyEntry policyEntry = new PolicyEntry(); + // policyEntry.setSubscriptionRecoveryPolicy(new LastImageSubscriptionRecoveryPolicy()); + // policyMap.put(new ActiveMQTopic(">"), policyEntry); + // brokerService.setDestinationPolicy(policyMap); + // + // MQTT mqtt = createMQTTConnection("pub-sub", true); + // final int[] retain = new int[1]; + // final int[] nonretain = new int[1]; + // mqtt.setTracer(new Tracer() { + // @Override + // public void onReceive(MQTTFrame frame) { + // if (frame.messageType() == PUBLISH.TYPE) { + // LOG.info("Received message with retain=" + frame.retain()); + // if (frame.retain()) { + // retain[0]++; + // } else { + // nonretain[0]++; + // } + // } + // } + // }); + // + // BlockingConnection connection = mqtt.blockingConnection(); + // connection.connect(); + // final String RETAINED = "RETAINED"; + // connection.publish("one", RETAINED.getBytes(), QoS.AT_LEAST_ONCE, true); + // connection.publish("two", RETAINED.getBytes(), QoS.AT_LEAST_ONCE, true); + // + // final String NONRETAINED = "NONRETAINED"; + // connection.publish("one", NONRETAINED.getBytes(), QoS.AT_LEAST_ONCE, false); + // connection.publish("two", NONRETAINED.getBytes(), QoS.AT_LEAST_ONCE, false); + // + // connection.subscribe(new Topic[]{new Topic("#", QoS.AT_LEAST_ONCE)}); + // for (int i = 0; i < 4; i++) { + // final Message message = connection.receive(30, TimeUnit.SECONDS); + // assertNotNull("Should receive 4 messages", message); + // message.ack(); + // } + // assertEquals("Should receive 2 retained messages", 2, retain[0]); + // assertEquals("Should receive 2 non-retained messages", 2, nonretain[0]); + // } // TODO As with other tests, this should be enabled as part of the cross protocol support with MQTT. -// @Test(timeout = 60 * 1000) -// public void testSendMQTTReceiveJMSVirtualTopic() throws Exception { -// -// final MQTTClientProvider provider = getMQTTClientProvider(); -// initializeConnection(provider); -// final String DESTINATION_NAME = "Consumer.jms.VirtualTopic.TopicA"; -// -// // send retained message -// final String RETAINED = "RETAINED"; -// final String MQTT_DESTINATION_NAME = "VirtualTopic/TopicA"; -// provider.publish(MQTT_DESTINATION_NAME, RETAINED.getBytes(), AT_LEAST_ONCE, true); -// -// ActiveMQConnection activeMQConnection = (ActiveMQConnection) new ActiveMQConnectionFactory(jmsUri).createConnection(); -// // MUST set to true to receive retained messages -// activeMQConnection.setUseRetroactiveConsumer(true); -// activeMQConnection.start(); -// Session s = activeMQConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); -// Queue jmsQueue = s.createQueue(DESTINATION_NAME); -// MessageConsumer consumer = s.createConsumer(jmsQueue); -// -// // check whether we received retained message on JMS subscribe -// ActiveMQMessage message = (ActiveMQMessage) consumer.receive(5000); -// assertNotNull("Should get retained message", message); -// ByteSequence bs = message.getContent(); -// assertEquals(RETAINED, new String(bs.data, bs.offset, bs.length)); -// assertTrue(message.getBooleanProperty(RetainedMessageSubscriptionRecoveryPolicy.RETAINED_PROPERTY)); -// -// for (int i = 0; i < NUM_MESSAGES; i++) { -// String payload = "Test Message: " + i; -// provider.publish(MQTT_DESTINATION_NAME, payload.getBytes(), AT_LEAST_ONCE); -// message = (ActiveMQMessage) consumer.receive(5000); -// assertNotNull("Should get a message", message); -// bs = message.getContent(); -// assertEquals(payload, new String(bs.data, bs.offset, bs.length)); -// } -// -// // re-create consumer and check we received retained message again -// consumer.close(); -// consumer = s.createConsumer(jmsQueue); -// message = (ActiveMQMessage) consumer.receive(5000); -// assertNotNull("Should get retained message", message); -// bs = message.getContent(); -// assertEquals(RETAINED, new String(bs.data, bs.offset, bs.length)); -// assertTrue(message.getBooleanProperty(RetainedMessageSubscriptionRecoveryPolicy.RETAINED_PROPERTY)); -// -// activeMQConnection.close(); -// provider.disconnect(); -// } + // @Test(timeout = 60 * 1000) + // public void testSendMQTTReceiveJMSVirtualTopic() throws Exception { + // + // final MQTTClientProvider provider = getMQTTClientProvider(); + // initializeConnection(provider); + // final String DESTINATION_NAME = "Consumer.jms.VirtualTopic.TopicA"; + // + // // send retained message + // final String RETAINED = "RETAINED"; + // final String MQTT_DESTINATION_NAME = "VirtualTopic/TopicA"; + // provider.publish(MQTT_DESTINATION_NAME, RETAINED.getBytes(), AT_LEAST_ONCE, true); + // + // ActiveMQConnection activeMQConnection = (ActiveMQConnection) new ActiveMQConnectionFactory(jmsUri).createConnection(); + // // MUST set to true to receive retained messages + // activeMQConnection.setUseRetroactiveConsumer(true); + // activeMQConnection.start(); + // Session s = activeMQConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + // Queue jmsQueue = s.createQueue(DESTINATION_NAME); + // MessageConsumer consumer = s.createConsumer(jmsQueue); + // + // // check whether we received retained message on JMS subscribe + // ActiveMQMessage message = (ActiveMQMessage) consumer.receive(5000); + // assertNotNull("Should get retained message", message); + // ByteSequence bs = message.getContent(); + // assertEquals(RETAINED, new String(bs.data, bs.offset, bs.length)); + // assertTrue(message.getBooleanProperty(RetainedMessageSubscriptionRecoveryPolicy.RETAINED_PROPERTY)); + // + // for (int i = 0; i < NUM_MESSAGES; i++) { + // String payload = "Test Message: " + i; + // provider.publish(MQTT_DESTINATION_NAME, payload.getBytes(), AT_LEAST_ONCE); + // message = (ActiveMQMessage) consumer.receive(5000); + // assertNotNull("Should get a message", message); + // bs = message.getContent(); + // assertEquals(payload, new String(bs.data, bs.offset, bs.length)); + // } + // + // // re-create consumer and check we received retained message again + // consumer.close(); + // consumer = s.createConsumer(jmsQueue); + // message = (ActiveMQMessage) consumer.receive(5000); + // assertNotNull("Should get retained message", message); + // bs = message.getContent(); + // assertEquals(RETAINED, new String(bs.data, bs.offset, bs.length)); + // assertTrue(message.getBooleanProperty(RetainedMessageSubscriptionRecoveryPolicy.RETAINED_PROPERTY)); + // + // activeMQConnection.close(); + // provider.disconnect(); + // } @Test(timeout = 60 * 1000) - public void testPingOnMQTT() throws Exception - { + public void testPingOnMQTT() throws Exception { stopBroker(); protocolConfig = "maxInactivityDuration=-1"; startBroker(); @@ -1732,12 +1582,10 @@ public class MQTTTest extends MQTTTestSupport mqtt.setKeepAlive((short) 2); final BlockingConnection connection = mqtt.blockingConnection(); connection.connect(); - assertTrue("KeepAlive didn't work properly", Wait.waitFor(new Wait.Condition() - { + assertTrue("KeepAlive didn't work properly", Wait.waitFor(new Wait.Condition() { @Override - public boolean isSatisified() throws Exception - { + public boolean isSatisified() throws Exception { return connection.isConnected(); } })); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/MQTTTestSupport.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/MQTTTestSupport.java index 36a2308153..9fa0ffeda2 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/MQTTTestSupport.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/MQTTTestSupport.java @@ -47,8 +47,8 @@ import org.junit.rules.TestName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class MQTTTestSupport extends ActiveMQTestBase -{ +public class MQTTTestSupport extends ActiveMQTestBase { + private ActiveMQServer server; private static final Logger LOG = LoggerFactory.getLogger(MQTTTestSupport.class); @@ -68,34 +68,28 @@ public class MQTTTestSupport extends ActiveMQTestBase @Rule public TestName name = new TestName(); - public MQTTTestSupport() - { + public MQTTTestSupport() { this.protocolScheme = "mqtt"; this.useSSL = false; cf = new ActiveMQConnectionFactory(false, new TransportConfiguration(ActiveMQTestBase.NETTY_CONNECTOR_FACTORY)); } - public File basedir() throws IOException - { + public File basedir() throws IOException { ProtectionDomain protectionDomain = getClass().getProtectionDomain(); return new File(new File(protectionDomain.getCodeSource().getLocation().getPath()), "../..").getCanonicalFile(); } - - public MQTTTestSupport(String connectorScheme, boolean useSSL) - { + public MQTTTestSupport(String connectorScheme, boolean useSSL) { this.protocolScheme = connectorScheme; this.useSSL = useSSL; } - public String getName() - { + public String getName() { return name.getMethodName(); } @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { String basedir = basedir().getPath(); System.setProperty("javax.net.ssl.trustStore", basedir + "/src/test/resources/client.keystore"); System.setProperty("javax.net.ssl.trustStorePassword", "password"); @@ -109,8 +103,7 @@ public class MQTTTestSupport extends ActiveMQTestBase } @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { System.clearProperty("javax.net.ssl.trustStore"); System.clearProperty("javax.net.ssl.trustStorePassword"); System.clearProperty("javax.net.ssl.trustStoreType"); @@ -120,8 +113,7 @@ public class MQTTTestSupport extends ActiveMQTestBase stopBroker(); } - public void startBroker() throws Exception - { + public void startBroker() throws Exception { // TODO Add SSL super.setUp(); server = createServer(true, true); @@ -134,8 +126,7 @@ public class MQTTTestSupport extends ActiveMQTestBase server.waitForActivation(10, TimeUnit.SECONDS); } - protected void addCoreConnector() throws Exception - { + protected void addCoreConnector() throws Exception { // Overrides of this method can add additional configuration options or add multiple // MQTT transport connectors as needed, the port variable is always supposed to be // assigned the primary MQTT connector's port. @@ -149,8 +140,7 @@ public class MQTTTestSupport extends ActiveMQTestBase LOG.info("Added connector {} to broker", getProtocolScheme()); } - protected void addMQTTConnector() throws Exception - { + protected void addMQTTConnector() throws Exception { // Overrides of this method can add additional configuration options or add multiple // MQTT transport connectors as needed, the port variable is always supposed to be // assigned the primary MQTT connector's port. @@ -164,22 +154,18 @@ public class MQTTTestSupport extends ActiveMQTestBase LOG.info("Added connector {} to broker", getProtocolScheme()); } - public void stopBroker() throws Exception - { - if (server.isStarted()) - { + public void stopBroker() throws Exception { + if (server.isStarted()) { server.stop(); server = null; } } - protected String getQueueName() - { + protected String getQueueName() { return getClass().getName() + "." + name.getMethodName(); } - protected String getTopicName() - { + protected String getTopicName() { return getClass().getName() + "." + name.getMethodName(); } @@ -191,14 +177,11 @@ public class MQTTTestSupport extends ActiveMQTestBase * @param provider the MQTTClientProvider instance to initialize. * @throws Exception if an error occurs during initialization. */ - protected void initializeConnection(MQTTClientProvider provider) throws Exception - { - if (!isUseSSL()) - { + protected void initializeConnection(MQTTClientProvider provider) throws Exception { + if (!isUseSSL()) { provider.connect("tcp://localhost:" + port); } - else - { + else { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[]{new DefaultTrustManager()}, new SecureRandom()); provider.setSslContext(ctx); @@ -206,68 +189,54 @@ public class MQTTTestSupport extends ActiveMQTestBase } } - public String getProtocolScheme() - { + public String getProtocolScheme() { return protocolScheme; } - public void setProtocolScheme(String scheme) - { + public void setProtocolScheme(String scheme) { this.protocolScheme = scheme; } - public boolean isUseSSL() - { + public boolean isUseSSL() { return this.useSSL; } - public void setUseSSL(boolean useSSL) - { + public void setUseSSL(boolean useSSL) { this.useSSL = useSSL; } - public boolean isPersistent() - { + public boolean isPersistent() { return persistent; } - public int getPort() - { + public int getPort() { return this.port; } - public boolean isSchedulerSupportEnabled() - { + public boolean isSchedulerSupportEnabled() { return false; } - protected interface Task - { + protected interface Task { + void run() throws Exception; } - protected void within(int time, TimeUnit unit, Task task) throws InterruptedException - { + protected void within(int time, TimeUnit unit, Task task) throws InterruptedException { long timeMS = unit.toMillis(time); long deadline = System.currentTimeMillis() + timeMS; - while (true) - { - try - { + while (true) { + try { task.run(); return; } - catch (Throwable e) - { + catch (Throwable e) { long remaining = deadline - System.currentTimeMillis(); - if (remaining <= 0) - { - if (e instanceof RuntimeException) - { + if (remaining <= 0) { + if (e instanceof RuntimeException) { throw (RuntimeException) e; } - if (e instanceof Error) - { + if (e instanceof Error) { throw (Error) e; } throw new RuntimeException(e); @@ -277,39 +246,32 @@ public class MQTTTestSupport extends ActiveMQTestBase } } - protected MQTTClientProvider getMQTTClientProvider() - { + protected MQTTClientProvider getMQTTClientProvider() { return new FuseMQTTClientProvider(); } - protected MQTT createMQTTConnection() throws Exception - { + protected MQTT createMQTTConnection() throws Exception { MQTT client = createMQTTConnection(null, false); client.setVersion("3.1.1"); return client; } - protected MQTT createMQTTConnection(String clientId, boolean clean) throws Exception - { - if (isUseSSL()) - { + protected MQTT createMQTTConnection(String clientId, boolean clean) throws Exception { + if (isUseSSL()) { return createMQTTSslConnection(clientId, clean); } - else - { + else { return createMQTTTcpConnection(clientId, clean); } } - private MQTT createMQTTTcpConnection(String clientId, boolean clean) throws Exception - { + private MQTT createMQTTTcpConnection(String clientId, boolean clean) throws Exception { MQTT mqtt = new MQTT(); mqtt.setConnectAttemptsMax(1); mqtt.setReconnectAttemptsMax(0); mqtt.setTracer(createTracer()); mqtt.setVersion("3.1.1"); - if (clientId != null) - { + if (clientId != null) { mqtt.setClientId(clientId); } mqtt.setCleanSession(clean); @@ -317,15 +279,13 @@ public class MQTTTestSupport extends ActiveMQTestBase return mqtt; } - private MQTT createMQTTSslConnection(String clientId, boolean clean) throws Exception - { + private MQTT createMQTTSslConnection(String clientId, boolean clean) throws Exception { MQTT mqtt = new MQTT(); mqtt.setConnectAttemptsMax(1); mqtt.setReconnectAttemptsMax(0); mqtt.setTracer(createTracer()); mqtt.setHost("ssl://localhost:" + port); - if (clientId != null) - { + if (clientId != null) { mqtt.setClientId(clientId); } mqtt.setCleanSession(clean); @@ -336,46 +296,37 @@ public class MQTTTestSupport extends ActiveMQTestBase return mqtt; } - protected Tracer createTracer() - { - return new Tracer() - { + protected Tracer createTracer() { + return new Tracer() { @Override - public void onReceive(MQTTFrame frame) - { + public void onReceive(MQTTFrame frame) { LOG.info("Client Received:\n" + frame); } @Override - public void onSend(MQTTFrame frame) - { + public void onSend(MQTTFrame frame) { LOG.info("Client Sent:\n" + frame); } @Override - public void debug(String message, Object... args) - { + public void debug(String message, Object... args) { LOG.info(String.format(message, args)); } }; } - static class DefaultTrustManager implements X509TrustManager - { + static class DefaultTrustManager implements X509TrustManager { @Override - public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException - { + public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override - public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException - { + public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override - public X509Certificate[] getAcceptedIssuers() - { + public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/PahoMQTTTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/PahoMQTTTest.java index 9a1313bac5..73f52c01e1 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/PahoMQTTTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/PahoMQTTTest.java @@ -31,36 +31,30 @@ import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import org.junit.Test; -public class PahoMQTTTest extends MQTTTestSupport -{ +public class PahoMQTTTest extends MQTTTestSupport { private static MQTTLogger LOG = MQTTLogger.LOGGER; @Test(timeout = 300000) - public void testLotsOfClients() throws Exception - { + public void testLotsOfClients() throws Exception { final int CLIENTS = Integer.getInteger("PahoMQTTTest.CLIENTS", 100); LOG.info("Using: {} clients: " + CLIENTS); final AtomicInteger receiveCounter = new AtomicInteger(); MqttClient client = createPahoClient("consumer"); - client.setCallback(new MqttCallback() - { + client.setCallback(new MqttCallback() { @Override - public void connectionLost(Throwable cause) - { + public void connectionLost(Throwable cause) { } @Override - public void messageArrived(String topic, MqttMessage message) throws Exception - { + public void messageArrived(String topic, MqttMessage message) throws Exception { receiveCounter.incrementAndGet(); } @Override - public void deliveryComplete(IMqttDeliveryToken token) - { + public void deliveryComplete(IMqttDeliveryToken token) { } }); client.connect(); @@ -71,35 +65,28 @@ public class PahoMQTTTest extends MQTTTestSupport final CountDownLatch disconnectDoneLatch = new CountDownLatch(CLIENTS); final CountDownLatch sendBarrier = new CountDownLatch(1); - for (int i = 0; i < CLIENTS; i++) - { + for (int i = 0; i < CLIENTS; i++) { Thread.sleep(10); - new Thread(null, null, "client:" + i) - { + new Thread(null, null, "client:" + i) { @Override - public void run() - { - try - { + public void run() { + try { MqttClient client = createPahoClient(Thread.currentThread().getName()); client.connect(); connectedDoneLatch.countDown(); sendBarrier.await(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { Thread.sleep(1000); client.publish("test", "hello".getBytes(), 1, false); } client.disconnect(); client.close(); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); asyncError.set(e); } - finally - { + finally { disconnectDoneLatch.countDown(); } } @@ -113,11 +100,9 @@ public class PahoMQTTTest extends MQTTTestSupport LOG.info("All clients connected... waiting to receive sent messages..."); // We should eventually get all the messages. - within(30, TimeUnit.SECONDS, new Task() - { + within(30, TimeUnit.SECONDS, new Task() { @Override - public void run() throws Exception - { + public void run() throws Exception { assertTrue(receiveCounter.get() == CLIENTS * 10); } }); @@ -129,8 +114,7 @@ public class PahoMQTTTest extends MQTTTestSupport } @Test(timeout = 300000) - public void testSendAndReceiveMQTT() throws Exception - { + public void testSendAndReceiveMQTT() throws Exception { final CountDownLatch latch = new CountDownLatch(1); MqttClient consumer = createPahoClient("consumerId"); @@ -138,23 +122,19 @@ public class PahoMQTTTest extends MQTTTestSupport consumer.connect(); consumer.subscribe("test"); - consumer.setCallback(new MqttCallback() - { + consumer.setCallback(new MqttCallback() { @Override - public void connectionLost(Throwable cause) - { + public void connectionLost(Throwable cause) { } @Override - public void messageArrived(String topic, MqttMessage message) throws Exception - { + public void messageArrived(String topic, MqttMessage message) throws Exception { latch.countDown(); } @Override - public void deliveryComplete(IMqttDeliveryToken token) - { + public void deliveryComplete(IMqttDeliveryToken token) { } }); @@ -167,8 +147,7 @@ public class PahoMQTTTest extends MQTTTestSupport producer.close(); } - private MqttClient createPahoClient(String clientId) throws MqttException - { + private MqttClient createPahoClient(String clientId) throws MqttException { return new MqttClient("tcp://localhost:" + getPort(), clientId, new MemoryPersistence()); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/util/ResourceLoadingSslContext.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/util/ResourceLoadingSslContext.java index 9a4c03f866..7312e62c39 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/util/ResourceLoadingSslContext.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/util/ResourceLoadingSslContext.java @@ -42,8 +42,7 @@ import org.springframework.util.ResourceUtils; /** * Extends the SslContext so that it's easier to configure from spring. */ -public class ResourceLoadingSslContext extends SslContext -{ +public class ResourceLoadingSslContext extends SslContext { private String keyStoreType = "jks"; private String trustStoreType = "jks"; @@ -66,14 +65,11 @@ public class ResourceLoadingSslContext extends SslContext * signature change. */ @PostConstruct - private void postConstruct() - { - try - { + private void postConstruct() { + try { afterPropertiesSet(); } - catch (Exception ex) - { + catch (Exception ex) { throw new RuntimeException(ex); } } @@ -82,26 +78,21 @@ public class ResourceLoadingSslContext extends SslContext * @throws Exception * @org.apache.xbean.InitMethod */ - public void afterPropertiesSet() throws Exception - { + public void afterPropertiesSet() throws Exception { keyManagers.addAll(createKeyManagers()); trustManagers.addAll(createTrustManagers()); - if (secureRandom == null) - { + if (secureRandom == null) { secureRandom = createSecureRandom(); } } - private SecureRandom createSecureRandom() throws NoSuchAlgorithmException - { + private SecureRandom createSecureRandom() throws NoSuchAlgorithmException { return SecureRandom.getInstance(secureRandomAlgorithm); } - private Collection createTrustManagers() throws Exception - { + private Collection createTrustManagers() throws Exception { KeyStore ks = createTrustManagerKeyStore(); - if (ks == null) - { + if (ks == null) { return new ArrayList(0); } @@ -110,11 +101,9 @@ public class ResourceLoadingSslContext extends SslContext return Arrays.asList(tmf.getTrustManagers()); } - private Collection createKeyManagers() throws Exception - { + private Collection createKeyManagers() throws Exception { KeyStore ks = createKeyManagerKeyStore(); - if (ks == null) - { + if (ks == null) { return new ArrayList(0); } @@ -123,160 +112,128 @@ public class ResourceLoadingSslContext extends SslContext return Arrays.asList(tmf.getKeyManagers()); } - private KeyStore createTrustManagerKeyStore() throws Exception - { - if (trustStore == null) - { + private KeyStore createTrustManagerKeyStore() throws Exception { + if (trustStore == null) { return null; } KeyStore ks = KeyStore.getInstance(trustStoreType); InputStream is = resourceFromString(trustStore).getInputStream(); - try - { + try { ks.load(is, trustStorePassword == null ? null : trustStorePassword.toCharArray()); } - finally - { + finally { is.close(); } return ks; } - private KeyStore createKeyManagerKeyStore() throws Exception - { - if (keyStore == null) - { + private KeyStore createKeyManagerKeyStore() throws Exception { + if (keyStore == null) { return null; } KeyStore ks = KeyStore.getInstance(keyStoreType); InputStream is = resourceFromString(keyStore).getInputStream(); - try - { + try { ks.load(is, keyStorePassword == null ? null : keyStorePassword.toCharArray()); } - finally - { + finally { is.close(); } return ks; } - public String getTrustStoreType() - { + public String getTrustStoreType() { return trustStoreType; } - public String getKeyStoreType() - { + public String getKeyStoreType() { return keyStoreType; } - public String getKeyStore() - { + public String getKeyStore() { return keyStore; } - public void setKeyStore(String keyStore) throws MalformedURLException - { + public void setKeyStore(String keyStore) throws MalformedURLException { this.keyStore = keyStore; } - public String getTrustStore() - { + public String getTrustStore() { return trustStore; } - public void setTrustStore(String trustStore) throws MalformedURLException - { + public void setTrustStore(String trustStore) throws MalformedURLException { this.trustStore = trustStore; } - public String getKeyStoreAlgorithm() - { + public String getKeyStoreAlgorithm() { return keyStoreAlgorithm; } - public void setKeyStoreAlgorithm(String keyAlgorithm) - { + public void setKeyStoreAlgorithm(String keyAlgorithm) { this.keyStoreAlgorithm = keyAlgorithm; } - public String getTrustStoreAlgorithm() - { + public String getTrustStoreAlgorithm() { return trustStoreAlgorithm; } - public void setTrustStoreAlgorithm(String trustAlgorithm) - { + public void setTrustStoreAlgorithm(String trustAlgorithm) { this.trustStoreAlgorithm = trustAlgorithm; } - public String getKeyStoreKeyPassword() - { + public String getKeyStoreKeyPassword() { return keyStoreKeyPassword; } - public void setKeyStoreKeyPassword(String keyPassword) - { + public void setKeyStoreKeyPassword(String keyPassword) { this.keyStoreKeyPassword = keyPassword; } - public String getKeyStorePassword() - { + public String getKeyStorePassword() { return keyStorePassword; } - public void setKeyStorePassword(String keyPassword) - { + public void setKeyStorePassword(String keyPassword) { this.keyStorePassword = keyPassword; } - public String getTrustStorePassword() - { + public String getTrustStorePassword() { return trustStorePassword; } - public void setTrustStorePassword(String trustPassword) - { + public void setTrustStorePassword(String trustPassword) { this.trustStorePassword = trustPassword; } - public void setKeyStoreType(String keyType) - { + public void setKeyStoreType(String keyType) { this.keyStoreType = keyType; } - public void setTrustStoreType(String trustType) - { + public void setTrustStoreType(String trustType) { this.trustStoreType = trustType; } - public String getSecureRandomAlgorithm() - { + public String getSecureRandomAlgorithm() { return secureRandomAlgorithm; } - public void setSecureRandomAlgorithm(String secureRandomAlgorithm) - { + public void setSecureRandomAlgorithm(String secureRandomAlgorithm) { this.secureRandomAlgorithm = secureRandomAlgorithm; } - public static Resource resourceFromString(String uri) throws MalformedURLException - { + public static Resource resourceFromString(String uri) throws MalformedURLException { Resource resource; File file = new File(uri); - if (file.exists()) - { + if (file.exists()) { resource = new FileSystemResource(uri); } - else if (ResourceUtils.isUrl(uri)) - { + else if (ResourceUtils.isUrl(uri)) { resource = new UrlResource(uri); } - else - { + else { resource = new ClassPathResource(uri); } return resource; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/util/Wait.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/util/Wait.java index 84fc3a47fd..976b4d3a1f 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/util/Wait.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/mqtt/imported/util/Wait.java @@ -17,37 +17,33 @@ package org.apache.activemq.artemis.tests.integration.mqtt.imported.util; - import java.util.concurrent.TimeUnit; -public class Wait -{ +public class Wait { public static final long MAX_WAIT_MILLIS = 30 * 1000; public static final int SLEEP_MILLIS = 1000; - public interface Condition - { + public interface Condition { + boolean isSatisified() throws Exception; } - public static boolean waitFor(Condition condition) throws Exception - { + public static boolean waitFor(Condition condition) throws Exception { return waitFor(condition, MAX_WAIT_MILLIS); } - public static boolean waitFor(final Condition condition, final long duration) throws Exception - { + public static boolean waitFor(final Condition condition, final long duration) throws Exception { return waitFor(condition, duration, SLEEP_MILLIS); } - public static boolean waitFor(final Condition condition, final long duration, final int sleepMillis) throws Exception - { + public static boolean waitFor(final Condition condition, + final long duration, + final int sleepMillis) throws Exception { final long expiry = System.currentTimeMillis() + duration; boolean conditionSatisified = condition.isSatisified(); - while (!conditionSatisified && System.currentTimeMillis() < expiry) - { + while (!conditionSatisified && System.currentTimeMillis() < expiry) { TimeUnit.MILLISECONDS.sleep(sleepMillis); conditionSatisified = condition.isSatisified(); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/BasicOpenWireTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/BasicOpenWireTest.java index 46955bc63f..49e89310a9 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/BasicOpenWireTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/BasicOpenWireTest.java @@ -37,9 +37,10 @@ import org.junit.Before; import org.junit.Rule; import org.junit.rules.TestName; -public class BasicOpenWireTest extends OpenWireTestBase -{ - @Rule public TestName name = new TestName(); +public class BasicOpenWireTest extends OpenWireTestBase { + + @Rule + public TestName name = new TestName(); protected static final String urlString = "tcp://" + OWHOST + ":" + OWPORT + "?wireFormat.cacheEnabled=true"; protected ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(urlString); @@ -57,8 +58,7 @@ public class BasicOpenWireTest extends OpenWireTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); SimpleString coreQueue = new SimpleString("jms.queue." + queueName); this.server.createQueue(coreQueue, coreQueue, null, false, false); @@ -72,59 +72,48 @@ public class BasicOpenWireTest extends OpenWireTestBase this.server.createQueue(durableQueue, durableQueue, null, true, false); testQueues.put(durableQueueName, durableQueue); - if (!enableSecurity) - { + if (!enableSecurity) { connection = (ActiveMQConnection) factory.createConnection(); } } @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { System.out.println("tear down! " + connection); - try - { - if (connection != null) - { + try { + if (connection != null) { System.out.println("closing connection"); connection.close(); System.out.println("connection closed."); } Iterator iterQueues = testQueues.values().iterator(); - while (iterQueues.hasNext()) - { + while (iterQueues.hasNext()) { SimpleString coreQ = iterQueues.next(); - if (server.locateQueue(coreQ) != null) - { + if (server.locateQueue(coreQ) != null) { this.server.destroyQueue(coreQ); } System.out.println("Destroyed queue: " + coreQ); } testQueues.clear(); } - catch (Throwable e) - { + catch (Throwable e) { System.out.println("Exception !! " + e); e.printStackTrace(); } - finally - { + finally { super.tearDown(); System.out.println("Super done."); } } - public ActiveMQDestination createDestination(Session session, byte type, String name) throws Exception - { - if (name == null) - { + public ActiveMQDestination createDestination(Session session, byte type, String name) throws Exception { + if (name == null) { return createDestination(session, type); } - switch (type) - { + switch (type) { case ActiveMQDestination.QUEUE_TYPE: makeSureCoreQueueExist(name); return (ActiveMQDestination) session.createQueue(name); @@ -139,21 +128,17 @@ public class BasicOpenWireTest extends OpenWireTestBase } } - public void makeSureCoreQueueExist(String qname) throws Exception - { + public void makeSureCoreQueueExist(String qname) throws Exception { SimpleString coreQ = testQueues.get(qname); - if (coreQ == null) - { + if (coreQ == null) { coreQ = new SimpleString("jms.queue." + qname); this.server.createQueue(coreQ, coreQ, null, false, false); testQueues.put(qname, coreQ); } } - public ActiveMQDestination createDestination(Session session, byte type) throws JMSException - { - switch (type) - { + public ActiveMQDestination createDestination(Session session, byte type) throws JMSException { + switch (type) { case ActiveMQDestination.QUEUE_TYPE: return (ActiveMQDestination) session.createQueue(queueName); case ActiveMQDestination.TOPIC_TYPE: @@ -167,10 +152,8 @@ public class BasicOpenWireTest extends OpenWireTestBase } } - protected ActiveMQDestination createDestination2(Session session, byte type) throws JMSException - { - switch (type) - { + protected ActiveMQDestination createDestination2(Session session, byte type) throws JMSException { + switch (type) { case ActiveMQDestination.QUEUE_TYPE: return (ActiveMQDestination) session.createQueue(queueName2); case ActiveMQDestination.TOPIC_TYPE: @@ -184,23 +167,19 @@ public class BasicOpenWireTest extends OpenWireTestBase } } - protected void sendMessages(Session session, Destination destination, int count) throws JMSException - { + protected void sendMessages(Session session, Destination destination, int count) throws JMSException { MessageProducer producer = session.createProducer(destination); sendMessages(session, producer, count); producer.close(); } - protected void sendMessages(Session session, MessageProducer producer, int count) throws JMSException - { - for (int i = 0; i < count; i++) - { + protected void sendMessages(Session session, MessageProducer producer, int count) throws JMSException { + for (int i = 0; i < count; i++) { producer.send(session.createTextMessage(messageTextPrefix + i)); } } - protected void sendMessages(Connection connection, Destination destination, int count) throws JMSException - { + protected void sendMessages(Connection connection, Destination destination, int count) throws JMSException { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); sendMessages(session, destination, count); session.close(); @@ -211,37 +190,27 @@ public class BasicOpenWireTest extends OpenWireTestBase * @param firstSet * @param secondSet */ - protected void assertTextMessagesEqual(String messsage, Message[] firstSet, - Message[] secondSet) throws JMSException - { - assertEquals("Message count does not match: " + messsage, - firstSet.length, secondSet.length); - for (int i = 0; i < secondSet.length; i++) - { + protected void assertTextMessagesEqual(String messsage, + Message[] firstSet, + Message[] secondSet) throws JMSException { + assertEquals("Message count does not match: " + messsage, firstSet.length, secondSet.length); + for (int i = 0; i < secondSet.length; i++) { TextMessage m1 = (TextMessage) firstSet[i]; TextMessage m2 = (TextMessage) secondSet[i]; - assertFalse("Message " + (i + 1) + " did not match : " + messsage - + ": expected {" + m1 + "}, but was {" + m2 + "}", m1 == null - ^ m2 == null); - assertEquals("Message " + (i + 1) + " did not match: " + messsage - + ": expected {" + m1 + "}, but was {" + m2 + "}", m1.getText(), - m2.getText()); + assertFalse("Message " + (i + 1) + " did not match : " + messsage + ": expected {" + m1 + "}, but was {" + m2 + "}", m1 == null ^ m2 == null); + assertEquals("Message " + (i + 1) + " did not match: " + messsage + ": expected {" + m1 + "}, but was {" + m2 + "}", m1.getText(), m2.getText()); } } - protected Connection createConnection() throws JMSException - { + protected Connection createConnection() throws JMSException { return factory.createConnection(); } - protected void safeClose(Session s) - { - try - { + protected void safeClose(Session s) { + try { s.close(); } - catch (Throwable e) - { + catch (Throwable e) { } } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/BasicSecurityTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/BasicSecurityTest.java index 3b8f91c00c..266ad34be2 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/BasicSecurityTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/BasicSecurityTest.java @@ -29,23 +29,20 @@ import org.apache.activemq.command.ActiveMQQueue; import org.junit.Before; import org.junit.Test; -public class BasicSecurityTest extends BasicOpenWireTest -{ +public class BasicSecurityTest extends BasicOpenWireTest { + @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { this.enableSecurity = true; super.setUp(); } @Test - public void testConnectionWithCredentials() throws Exception - { + public void testConnectionWithCredentials() throws Exception { Connection newConn = null; //correct - try - { + try { newConn = factory.createConnection("openwireSender", "SeNdEr"); newConn.start(); newConn.close(); @@ -56,96 +53,76 @@ public class BasicSecurityTest extends BasicOpenWireTest newConn = null; } - finally - { - if (newConn != null) - { + finally { + if (newConn != null) { newConn.close(); } } //wrong password - try - { + try { newConn = factory.createConnection("openwireSender", "WrongPasswD"); newConn.start(); } - catch (JMSSecurityException e) - { + catch (JMSSecurityException e) { //expected } - finally - { - if (newConn != null) - { + finally { + if (newConn != null) { newConn.close(); } } //wrong user - try - { + try { newConn = factory.createConnection("wronguser", "SeNdEr"); newConn.start(); } - catch (JMSSecurityException e) - { + catch (JMSSecurityException e) { //expected } - finally - { - if (newConn != null) - { + finally { + if (newConn != null) { newConn.close(); } } //both wrong - try - { + try { newConn = factory.createConnection("wronguser", "wrongpass"); newConn.start(); } - catch (JMSSecurityException e) - { + catch (JMSSecurityException e) { //expected } - finally - { - if (newConn != null) - { + finally { + if (newConn != null) { newConn.close(); } } //default user - try - { + try { newConn = factory.createConnection(); newConn.start(); } - catch (JMSSecurityException e) - { + catch (JMSSecurityException e) { //expected } - finally - { - if (newConn != null) - { + finally { + if (newConn != null) { newConn.close(); } } } @Test - public void testSendnReceiveAuthorization() throws Exception - { + public void testSendnReceiveAuthorization() throws Exception { Connection sendingConn = null; Connection receivingConn = null; //Sender - try - { + try { Destination dest = new ActiveMQQueue(queueName); receivingConn = factory.createConnection("openwireReceiver", "ReCeIvEr"); @@ -163,12 +140,10 @@ public class BasicSecurityTest extends BasicOpenWireTest producer = receivingSession.createProducer(dest); - try - { + try { producer.send(message); } - catch (JMSSecurityException e) - { + catch (JMSSecurityException e) { //expected producer.close(); } @@ -177,12 +152,10 @@ public class BasicSecurityTest extends BasicOpenWireTest producer.send(message); MessageConsumer consumer = null; - try - { + try { consumer = sendingSession.createConsumer(dest); } - catch (JMSSecurityException e) - { + catch (JMSSecurityException e) { //expected } @@ -192,29 +165,24 @@ public class BasicSecurityTest extends BasicOpenWireTest assertNotNull(received); assertEquals("Hello World", received.getText()); } - finally - { - if (sendingConn != null) - { + finally { + if (sendingConn != null) { sendingConn.close(); } - if (receivingConn != null) - { + if (receivingConn != null) { receivingConn.close(); } } } @Test - public void testCreateTempDestinationAuthorization() throws Exception - { + public void testCreateTempDestinationAuthorization() throws Exception { Connection conn1 = null; Connection conn2 = null; //Sender - try - { + try { conn1 = factory.createConnection("openwireGuest", "GuEsT"); conn1.start(); @@ -223,13 +191,11 @@ public class BasicSecurityTest extends BasicOpenWireTest Session session1 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE); - try - { + try { session1.createTemporaryQueue(); fail("user shouldn't be able to create temp queue"); } - catch (JMSSecurityException e) - { + catch (JMSSecurityException e) { //expected } @@ -238,15 +204,12 @@ public class BasicSecurityTest extends BasicOpenWireTest TemporaryQueue q = session2.createTemporaryQueue(); assertNotNull(q); } - finally - { - if (conn1 != null) - { + finally { + if (conn1 != null) { conn1.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/OpenWireTestBase.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/OpenWireTestBase.java index 3ecf11630c..a83bf47c20 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/OpenWireTestBase.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/OpenWireTestBase.java @@ -44,8 +44,8 @@ import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManagerImpl import org.junit.After; import org.junit.Before; -public class OpenWireTestBase extends ActiveMQTestBase -{ +public class OpenWireTestBase extends ActiveMQTestBase { + public static final String OWHOST = "localhost"; public static final int OWPORT = 61616; @@ -62,24 +62,20 @@ public class OpenWireTestBase extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = this.createServer(realStore, true); Configuration serverConfig = server.getConfiguration(); - serverConfig.getAddressesSettings().put("jms.queue.#", new AddressSettings() - .setAutoCreateJmsQueues(false) - .setDeadLetterAddress(new SimpleString("jms.queue.ActiveMQ.DLQ"))); + serverConfig.getAddressesSettings().put("jms.queue.#", new AddressSettings().setAutoCreateJmsQueues(false).setDeadLetterAddress(new SimpleString("jms.queue.ActiveMQ.DLQ"))); serverConfig.getAcceptorConfigurations().add(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY)); serverConfig.setSecurityEnabled(enableSecurity); extraServerConfig(serverConfig); - if (enableSecurity) - { + if (enableSecurity) { ActiveMQSecurityManagerImpl securityManager = (ActiveMQSecurityManagerImpl) server.getSecurityManager(); securityManager.getConfiguration().addRole("openwireSender", "sender"); securityManager.getConfiguration().addUser("openwireSender", "SeNdEr"); @@ -104,14 +100,12 @@ public class OpenWireTestBase extends ActiveMQTestBase Role destRole = new Role("manager", false, false, false, false, true, true, false); Map> settings = server.getConfiguration().getSecurityRoles(); - if (settings == null) - { + if (settings == null) { settings = new HashMap>(); server.getConfiguration().setSecurityRoles(settings); } Set anySet = settings.get("#"); - if (anySet == null) - { + if (anySet == null) { anySet = new HashSet(); settings.put("#", anySet); } @@ -132,12 +126,10 @@ public class OpenWireTestBase extends ActiveMQTestBase } //override this to add extra server configs - protected void extraServerConfig(Configuration serverConfig) - { + protected void extraServerConfig(Configuration serverConfig) { } - protected void registerConnectionFactory() throws Exception - { + protected void registerConnectionFactory() throws Exception { List connectorConfigs = new ArrayList(); connectorConfigs.add(new TransportConfiguration(INVM_CONNECTOR_FACTORY)); @@ -146,8 +138,8 @@ public class OpenWireTestBase extends ActiveMQTestBase coreCf = (ConnectionFactory) namingContext.lookup("/cf"); } - protected void createCF(final List connectorConfigs, final String... jndiBindings) throws Exception - { + protected void createCF(final List connectorConfigs, + final String... jndiBindings) throws Exception { final int retryInterval = 1000; final double retryIntervalMultiplier = 1.0; final int reconnectAttempts = -1; @@ -156,29 +148,20 @@ public class OpenWireTestBase extends ActiveMQTestBase List connectorNames = registerConnectors(server, connectorConfigs); String cfName = name.getMethodName(); - if (cfName == null) - { + if (cfName == null) { cfName = "cfOpenWire"; } - ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl() - .setName(cfName) - .setConnectorNames(connectorNames) - .setRetryInterval(retryInterval) - .setRetryIntervalMultiplier(retryIntervalMultiplier) - .setCallTimeout(callTimeout) - .setReconnectAttempts(reconnectAttempts); + ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl().setName(cfName).setConnectorNames(connectorNames).setRetryInterval(retryInterval).setRetryIntervalMultiplier(retryIntervalMultiplier).setCallTimeout(callTimeout).setReconnectAttempts(reconnectAttempts); jmsServer.createConnectionFactory(false, configuration, jndiBindings); } - protected JMSServerControl getJMSServerControl() throws Exception - { + protected JMSServerControl getJMSServerControl() throws Exception { return ManagementControlHelper.createJMSServerControl(mbeanServer); } @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { MBeanServerFactory.releaseMBeanServer(mbeanServer); mbeanServer = null; server.stop(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/OpenWireUtilTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/OpenWireUtilTest.java index 64c9d86c1f..825b8b544c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/OpenWireUtilTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/OpenWireUtilTest.java @@ -21,11 +21,10 @@ import static org.junit.Assert.assertEquals; import org.apache.activemq.artemis.core.protocol.openwire.OpenWireUtil; import org.junit.Test; -public class OpenWireUtilTest -{ +public class OpenWireUtilTest { + @Test - public void testWildcardConversion() throws Exception - { + public void testWildcardConversion() throws Exception { String amqTarget = "TEST.ONE.>"; String coreTarget = OpenWireUtil.convertWildcard(amqTarget); assertEquals("TEST.ONE.#", coreTarget); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/SimpleOpenWireTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/SimpleOpenWireTest.java index a26b493820..83c94ee58f 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/SimpleOpenWireTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/SimpleOpenWireTest.java @@ -39,22 +39,20 @@ import org.junit.rules.ExpectedException; import java.util.concurrent.TimeUnit; -public class SimpleOpenWireTest extends BasicOpenWireTest -{ +public class SimpleOpenWireTest extends BasicOpenWireTest { + @Rule public ExpectedException thrown = ExpectedException.none(); @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { this.realStore = true; super.setUp(); } @Test - public void testSimpleQueue() throws Exception - { + public void testSimpleQueue() throws Exception { connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -66,8 +64,7 @@ public class SimpleOpenWireTest extends BasicOpenWireTest final int num = 1; final String msgBase = "MfromAMQ-"; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { TextMessage msg = session.createTextMessage("MfromAMQ-" + i); producer.send(msg); System.out.println("sent: "); @@ -77,8 +74,7 @@ public class SimpleOpenWireTest extends BasicOpenWireTest MessageConsumer consumer = session.createConsumer(dest); System.out.println("receiving messages..."); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { TextMessage msg = (TextMessage) consumer.receive(5000); System.out.println("received: " + msg); String content = msg.getText(); @@ -92,8 +88,7 @@ public class SimpleOpenWireTest extends BasicOpenWireTest } @Test - public void testSimpleTopic() throws Exception - { + public void testSimpleTopic() throws Exception { connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -107,8 +102,7 @@ public class SimpleOpenWireTest extends BasicOpenWireTest final int num = 1; final String msgBase = "MfromAMQ-"; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { TextMessage msg = session.createTextMessage("MfromAMQ-" + i); producer.send(msg); System.out.println("Sent a message"); @@ -116,8 +110,7 @@ public class SimpleOpenWireTest extends BasicOpenWireTest //receive System.out.println("receiving messages..."); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { TextMessage msg = (TextMessage) consumer1.receive(5000); System.out.println("received: " + msg); String content = msg.getText(); @@ -127,8 +120,7 @@ public class SimpleOpenWireTest extends BasicOpenWireTest assertNull(consumer1.receive(500)); System.out.println("receiving messages..."); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { TextMessage msg = (TextMessage) consumer2.receive(5000); System.out.println("received: " + msg); String content = msg.getText(); @@ -140,8 +132,7 @@ public class SimpleOpenWireTest extends BasicOpenWireTest } @Test - public void testSimpleTempTopic() throws Exception - { + public void testSimpleTempTopic() throws Exception { connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -159,8 +150,7 @@ public class SimpleOpenWireTest extends BasicOpenWireTest System.out.println("sending messages"); final int num = 1; final String msgBase = "MfromAMQ-"; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { TextMessage msg = session.createTextMessage("MfromAMQ-" + i); producer.send(msg); System.out.println("Sent a message"); @@ -168,8 +158,7 @@ public class SimpleOpenWireTest extends BasicOpenWireTest //receive System.out.println("receiving messages..."); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { TextMessage msg = (TextMessage) consumer1.receive(5000); System.out.println("received: " + msg); String content = msg.getText(); @@ -179,8 +168,7 @@ public class SimpleOpenWireTest extends BasicOpenWireTest assertNull(consumer1.receive(500)); System.out.println("receiving messages..."); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { TextMessage msg = (TextMessage) consumer2.receive(5000); System.out.println("received: " + msg); String content = msg.getText(); @@ -192,8 +180,7 @@ public class SimpleOpenWireTest extends BasicOpenWireTest } @Test - public void testSimpleTempQueue() throws Exception - { + public void testSimpleTempQueue() throws Exception { connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -209,8 +196,7 @@ public class SimpleOpenWireTest extends BasicOpenWireTest System.out.println("sending messages"); final int num = 1; final String msgBase = "MfromAMQ-"; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { TextMessage msg = session.createTextMessage("MfromAMQ-" + i); producer.send(msg); System.out.println("Sent a message"); @@ -218,8 +204,7 @@ public class SimpleOpenWireTest extends BasicOpenWireTest //receive System.out.println("receiving messages..."); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { TextMessage msg = (TextMessage) consumer1.receive(5000); System.out.println("received: " + msg); String content = msg.getText(); @@ -231,8 +216,7 @@ public class SimpleOpenWireTest extends BasicOpenWireTest } @Test - public void testInvalidDestinationExceptionWhenNoQueueExistsOnCreateProducer() throws Exception - { + public void testInvalidDestinationExceptionWhenNoQueueExistsOnCreateProducer() throws Exception { AddressSettings addressSetting = new AddressSettings(); addressSetting.setAutoCreateJmsQueues(false); @@ -249,8 +233,7 @@ public class SimpleOpenWireTest extends BasicOpenWireTest } @Test - public void testAutoDestinationCreationOnProducerSend() throws JMSException - { + public void testAutoDestinationCreationOnProducerSend() throws JMSException { AddressSettings addressSetting = new AddressSettings(); addressSetting.setAutoCreateJmsQueues(true); @@ -272,8 +255,7 @@ public class SimpleOpenWireTest extends BasicOpenWireTest } @Test - public void testAutoDestinationCreationOnConsumer() throws JMSException - { + public void testAutoDestinationCreationOnConsumer() throws JMSException { AddressSettings addressSetting = new AddressSettings(); addressSetting.setAutoCreateJmsQueues(true); @@ -296,8 +278,7 @@ public class SimpleOpenWireTest extends BasicOpenWireTest } @Test - public void testAutoDestinationNoCreationOnConsumer() throws JMSException - { + public void testAutoDestinationNoCreationOnConsumer() throws JMSException { AddressSettings addressSetting = new AddressSettings(); addressSetting.setAutoCreateJmsQueues(false); @@ -310,13 +291,11 @@ public class SimpleOpenWireTest extends BasicOpenWireTest TextMessage message = session.createTextMessage("bar"); Queue queue = new ActiveMQQueue(address); - try - { + try { MessageConsumer consumer = session.createConsumer(queue); fail("supposed to throw an exception here"); } - catch (JMSException e) - { + catch (JMSException e) { } } @@ -327,12 +306,10 @@ public class SimpleOpenWireTest extends BasicOpenWireTest * @throws Exception */ @Test - public void testOpenWireExample() throws Exception - { + public void testOpenWireExample() throws Exception { Connection exConn = null; - try - { + try { String urlString = "tcp://" + OWHOST + ":" + OWPORT + "?wireFormat.cacheEnabled=true"; ActiveMQConnectionFactory exFact = new ActiveMQConnectionFactory(urlString); @@ -369,10 +346,8 @@ public class SimpleOpenWireTest extends BasicOpenWireTest assertEquals("This is a text message", messageReceived.getText()); } - finally - { - if (exConn != null) - { + finally { + if (exConn != null) { exConn.close(); } } @@ -380,12 +355,10 @@ public class SimpleOpenWireTest extends BasicOpenWireTest } @Test - public void testFailoverTransportReconnect() throws Exception - { + public void testFailoverTransportReconnect() throws Exception { Connection exConn = null; - try - { + try { String urlString = "failover:(tcp://" + OWHOST + ":" + OWPORT + ")"; ActiveMQConnectionFactory exFact = new ActiveMQConnectionFactory(urlString); @@ -410,10 +383,8 @@ public class SimpleOpenWireTest extends BasicOpenWireTest messageProducer.send(session.createTextMessage("Test2")); assertNotNull(consumer.receive(5000)); } - finally - { - if (exConn != null) - { + finally { + if (exConn != null) { exConn.close(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer10Test.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer10Test.java index df79ea9730..ff1c52a13b 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer10Test.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer10Test.java @@ -35,35 +35,25 @@ import org.junit.runners.Parameterized; * adapted from: org.apache.activemq.JMSConsumerTest */ @RunWith(Parameterized.class) -public class JMSConsumer10Test extends BasicOpenWireTest -{ +public class JMSConsumer10Test extends BasicOpenWireTest { + @Parameterized.Parameters(name = "deliveryMode={0} ackMode={1} destinationType={2}") - public static Collection getParams() - { - return Arrays.asList(new Object[][] { - {DeliveryMode.NON_PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.NON_PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.NON_PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE} - }); + public static Collection getParams() { + return Arrays.asList(new Object[][]{{DeliveryMode.NON_PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.NON_PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.NON_PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}}); } public int deliveryMode; public int ackMode; public byte destinationType; - public JMSConsumer10Test(int deliveryMode, int ackMode, byte destinationType) - { + public JMSConsumer10Test(int deliveryMode, int ackMode, byte destinationType) { this.deliveryMode = deliveryMode; this.ackMode = ackMode; this.destinationType = destinationType; } @Test - public void testUnackedWithPrefetch1StayInQueue() throws Exception - { + public void testUnackedWithPrefetch1StayInQueue() throws Exception { // Set prefetch to 1 connection.getPrefetchPolicy().setAll(1); @@ -79,8 +69,7 @@ public class JMSConsumer10Test extends BasicOpenWireTest // Only pick up the first 2 messages. Message message = null; - for (int i = 0; i < 2; i++) - { + for (int i = 0; i < 2; i++) { message = consumer.receive(1000); assertNotNull(message); } @@ -96,8 +85,7 @@ public class JMSConsumer10Test extends BasicOpenWireTest consumer = session.createConsumer(destination); // Pickup the rest of the messages. - for (int i = 0; i < 2; i++) - { + for (int i = 0; i < 2; i++) { message = consumer.receive(1000); assertNotNull(message); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer11Test.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer11Test.java index 4550fcc029..c4be09317d 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer11Test.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer11Test.java @@ -35,27 +35,21 @@ import org.junit.runners.Parameterized; * adapted from: org.apache.activemq.JMSConsumerTest */ @RunWith(Parameterized.class) -public class JMSConsumer11Test extends BasicOpenWireTest -{ +public class JMSConsumer11Test extends BasicOpenWireTest { + @Parameterized.Parameters(name = "deliveryMode={0}") - public static Collection getParams() - { - return Arrays.asList(new Object[][] { - {DeliveryMode.NON_PERSISTENT}, - {DeliveryMode.PERSISTENT} - }); + public static Collection getParams() { + return Arrays.asList(new Object[][]{{DeliveryMode.NON_PERSISTENT}, {DeliveryMode.PERSISTENT}}); } public int deliveryMode; - public JMSConsumer11Test(int deliveryMode) - { + public JMSConsumer11Test(int deliveryMode) { this.deliveryMode = deliveryMode; } @Test - public void testPrefetch1MessageNotDispatched() throws Exception - { + public void testPrefetch1MessageNotDispatched() throws Exception { // Set prefetch to 1 connection.getPrefetchPolicy().setAll(1); connection.start(); @@ -72,8 +66,7 @@ public class JMSConsumer11Test extends BasicOpenWireTest // Since prefetch is still full, the 2nd message should get dispatched // to another consumer.. lets create the 2nd consumer test that it does // make sure it does. - ActiveMQConnection connection2 = (ActiveMQConnection) factory - .createConnection(); + ActiveMQConnection connection2 = (ActiveMQConnection) factory.createConnection(); connection2.start(); Session session2 = connection2.createSession(true, 0); MessageConsumer consumer2 = session2.createConsumer(destination); @@ -100,12 +93,10 @@ public class JMSConsumer11Test extends BasicOpenWireTest System.out.println("received 3: " + m); assertNull(m); - try - { + try { connection2.close(); } - catch (Throwable e) - { + catch (Throwable e) { System.err.println("exception e: " + e); e.printStackTrace(); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer12Test.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer12Test.java index 3d05e6ab00..bdea0ebcc8 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer12Test.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer12Test.java @@ -33,34 +33,26 @@ import org.junit.runners.Parameterized; * adapted from: org.apache.activemq.JMSConsumerTest */ @RunWith(Parameterized.class) -public class JMSConsumer12Test extends BasicOpenWireTest -{ +public class JMSConsumer12Test extends BasicOpenWireTest { + @Parameterized.Parameters(name = "deliveryMode={0} destinationType={1}") - public static Collection getParams() - { - return Arrays.asList(new Object[][] { - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TOPIC_TYPE} - }); + public static Collection getParams() { + return Arrays.asList(new Object[][]{{DeliveryMode.NON_PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TOPIC_TYPE}}); } public int deliveryMode; public byte destinationType; - public JMSConsumer12Test(int deliveryMode, byte destinationType) - { + public JMSConsumer12Test(int deliveryMode, byte destinationType) { this.deliveryMode = deliveryMode; this.destinationType = destinationType; } @Test - public void testDontStart() throws Exception - { + public void testDontStart() throws Exception { - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination = createDestination(session, - destinationType); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQDestination destination = createDestination(session, destinationType); MessageConsumer consumer = session.createConsumer(destination); // Send the messages @@ -71,12 +63,9 @@ public class JMSConsumer12Test extends BasicOpenWireTest } @Test - public void testStartAfterSend() throws Exception - { - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination = createDestination(session, - destinationType); + public void testStartAfterSend() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQDestination destination = createDestination(session, destinationType); MessageConsumer consumer = session.createConsumer(destination); // Send the messages diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer13Test.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer13Test.java index e020c414e9..c19ea6ebe7 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer13Test.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer13Test.java @@ -35,42 +35,28 @@ import org.junit.runners.Parameterized; * adapted from: org.apache.activemq.JMSConsumerTest */ @RunWith(Parameterized.class) -public class JMSConsumer13Test extends BasicOpenWireTest -{ +public class JMSConsumer13Test extends BasicOpenWireTest { + @Parameterized.Parameters(name = "deliveryMode={0} destinationType={1}") - public static Collection getParams() - { - return Arrays.asList(new Object[][] { - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TOPIC_TYPE}, - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE}, - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE}, - {DeliveryMode.PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.PERSISTENT, ActiveMQDestination.TOPIC_TYPE}, - {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE}, - {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE}, - }); + public static Collection getParams() { + return Arrays.asList(new Object[][]{{DeliveryMode.NON_PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TOPIC_TYPE}, {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE}, {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE}, {DeliveryMode.PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.PERSISTENT, ActiveMQDestination.TOPIC_TYPE}, {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE}, {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE},}); } public int deliveryMode; public byte destinationType; - public JMSConsumer13Test(int deliveryMode, byte destinationType) - { + public JMSConsumer13Test(int deliveryMode, byte destinationType) { this.deliveryMode = deliveryMode; this.destinationType = destinationType; } @Test - public void testReceiveMessageWithConsumer() throws Exception - { + public void testReceiveMessageWithConsumer() throws Exception { // Receive a message with the JMS API connection.start(); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination = createDestination(session, - destinationType); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQDestination destination = createDestination(session, destinationType); MessageConsumer consumer = session.createConsumer(destination); // Send the messages diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer1Test.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer1Test.java index 3dad38e8c6..f7347e1630 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer1Test.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer1Test.java @@ -38,21 +38,11 @@ import org.junit.runners.Parameterized; * adapted from: org.apache.activemq.JMSConsumerTest */ @RunWith(Parameterized.class) -public class JMSConsumer1Test extends BasicOpenWireTest -{ +public class JMSConsumer1Test extends BasicOpenWireTest { + @Parameterized.Parameters(name = "deliveryMode={0} destinationType={1}") - public static Collection getParams() - { - return Arrays.asList(new Object[][] { - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TOPIC_TYPE}, - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE}, - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE}, - {DeliveryMode.PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.PERSISTENT, ActiveMQDestination.TOPIC_TYPE}, - {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE}, - {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE} - }); + public static Collection getParams() { + return Arrays.asList(new Object[][]{{DeliveryMode.NON_PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TOPIC_TYPE}, {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE}, {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE}, {DeliveryMode.PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.PERSISTENT, ActiveMQDestination.TOPIC_TYPE}, {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE}, {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE}}); } public ActiveMQDestination destination; @@ -62,38 +52,30 @@ public class JMSConsumer1Test extends BasicOpenWireTest public byte destinationType; public boolean durableConsumer; - public JMSConsumer1Test(int deliveryMode, byte destinationType) - { + public JMSConsumer1Test(int deliveryMode, byte destinationType) { this.deliveryMode = deliveryMode; this.destinationType = destinationType; } @Test - public void testMessageListenerWithConsumerCanBeStopped() throws Exception - { + public void testMessageListenerWithConsumerCanBeStopped() throws Exception { final AtomicInteger counter = new AtomicInteger(0); final CountDownLatch done1 = new CountDownLatch(1); final CountDownLatch done2 = new CountDownLatch(1); // Receive a message with the JMS API connection.start(); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); destination = createDestination(session, destinationType); - ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer) session - .createConsumer(destination); - consumer.setMessageListener(new MessageListener() - { + ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer) session.createConsumer(destination); + consumer.setMessageListener(new MessageListener() { @Override - public void onMessage(Message m) - { + public void onMessage(Message m) { counter.incrementAndGet(); - if (counter.get() == 1) - { + if (counter.get() == 1) { done1.countDown(); } - if (counter.get() == 2) - { + if (counter.get() == 2) { done2.countDown(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer2Test.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer2Test.java index 1fbba33e79..f621740772 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer2Test.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer2Test.java @@ -39,79 +39,64 @@ import org.junit.Test; /** * adapted from: org.apache.activemq.JMSConsumerTest */ -public class JMSConsumer2Test extends BasicOpenWireTest -{ +public class JMSConsumer2Test extends BasicOpenWireTest { + @Test - public void testMessageListenerWithConsumerCanBeStoppedConcurently() throws Exception - { + public void testMessageListenerWithConsumerCanBeStoppedConcurently() throws Exception { final AtomicInteger counter = new AtomicInteger(0); final CountDownLatch closeDone = new CountDownLatch(1); connection.start(); - Session session = connection.createSession(false, - Session.CLIENT_ACKNOWLEDGE); - ActiveMQDestination destination = createDestination(session, - ActiveMQDestination.QUEUE_TYPE); + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); // preload the queue sendMessages(session, destination, 2000); - final ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer) session - .createConsumer(destination); + final ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer) session.createConsumer(destination); - final Map exceptions = Collections - .synchronizedMap(new HashMap()); - Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() - { + final Map exceptions = Collections.synchronizedMap(new HashMap()); + Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override - public void uncaughtException(Thread t, Throwable e) - { + public void uncaughtException(Thread t, Throwable e) { exceptions.put(t, e); } }); - final class AckAndClose implements Runnable - { + final class AckAndClose implements Runnable { + private final Message message; - public AckAndClose(Message m) - { + public AckAndClose(Message m) { this.message = m; } @Override - public void run() - { - try - { + public void run() { + try { int count = counter.incrementAndGet(); - if (count == 590) - { + if (count == 590) { // close in a separate thread is ok by jms consumer.close(); closeDone.countDown(); } - if (count % 200 == 0) - { + if (count % 200 == 0) { // ensure there are some outstanding messages // ack every 200 message.acknowledge(); } } - catch (Exception e) - { + catch (Exception e) { exceptions.put(Thread.currentThread(), e); } } } final ExecutorService executor = Executors.newCachedThreadPool(); - consumer.setMessageListener(new MessageListener() - { + consumer.setMessageListener(new MessageListener() { @Override - public void onMessage(Message m) - { + public void onMessage(Message m) { // ack and close eventually in separate thread executor.execute(new AckAndClose(m)); } @@ -124,13 +109,11 @@ public class JMSConsumer2Test extends BasicOpenWireTest } @Test - public void testDupsOkConsumer() throws Exception - { + public void testDupsOkConsumer() throws Exception { // Receive a message with the JMS API connection.start(); - Session session = connection.createSession(false, - Session.DUPS_OK_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE); ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); MessageConsumer consumer = session.createConsumer(destination); @@ -138,8 +121,7 @@ public class JMSConsumer2Test extends BasicOpenWireTest sendMessages(session, destination, 4); // Make sure only 4 message are delivered. - for (int i = 0; i < 4; i++) - { + for (int i = 0; i < 4; i++) { Message m = consumer.receive(1000); assertNotNull(m); } @@ -153,13 +135,10 @@ public class JMSConsumer2Test extends BasicOpenWireTest } @Test - public void testRedispatchOfUncommittedTx() throws Exception - { + public void testRedispatchOfUncommittedTx() throws Exception { connection.start(); - Session session = connection.createSession(true, - Session.SESSION_TRANSACTED); - ActiveMQDestination destination = createDestination(session, - ActiveMQDestination.QUEUE_TYPE); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); sendMessages(connection, destination, 2); @@ -172,10 +151,8 @@ public class JMSConsumer2Test extends BasicOpenWireTest assertNotNull(m); // install another consumer while message dispatch is unacked/uncommitted - Session redispatchSession = connection.createSession(true, - Session.SESSION_TRANSACTED); - MessageConsumer redispatchConsumer = redispatchSession - .createConsumer(destination); + Session redispatchSession = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageConsumer redispatchConsumer = redispatchSession.createConsumer(destination); System.out.println("redispatch consumer: " + redispatchConsumer); // no commit so will auto rollback and get re-dispatched to @@ -201,12 +178,10 @@ public class JMSConsumer2Test extends BasicOpenWireTest } @Test - public void testRedispatchOfRolledbackTx() throws Exception - { + public void testRedispatchOfRolledbackTx() throws Exception { connection.start(); - Session session = connection.createSession(true, - Session.SESSION_TRANSACTED); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); sendMessages(connection, destination, 2); @@ -216,10 +191,8 @@ public class JMSConsumer2Test extends BasicOpenWireTest assertNotNull(consumer.receive(1000)); // install another consumer while message dispatch is unacked/uncommitted - Session redispatchSession = connection.createSession(true, - Session.SESSION_TRANSACTED); - MessageConsumer redispatchConsumer = redispatchSession - .createConsumer(destination); + Session redispatchSession = connection.createSession(true, Session.SESSION_TRANSACTED); + MessageConsumer redispatchConsumer = redispatchSession.createConsumer(destination); session.rollback(); session.close(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer3Test.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer3Test.java index c786df30ba..cc680f7114 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer3Test.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer3Test.java @@ -35,37 +35,11 @@ import org.junit.runners.Parameterized; * adapted from: org.apache.activemq.JMSConsumerTest */ @RunWith(Parameterized.class) -public class JMSConsumer3Test extends BasicOpenWireTest -{ +public class JMSConsumer3Test extends BasicOpenWireTest { + @Parameterized.Parameters(name = "deliveryMode={0} ackMode={1} destinationType={2}") - public static Collection getParams() - { - return Arrays.asList(new Object[][] { - {DeliveryMode.NON_PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.NON_PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.TOPIC_TYPE}, - {DeliveryMode.NON_PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.TEMP_QUEUE_TYPE}, - {DeliveryMode.NON_PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.TEMP_TOPIC_TYPE}, - {DeliveryMode.NON_PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.NON_PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.TOPIC_TYPE}, - {DeliveryMode.NON_PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.TEMP_QUEUE_TYPE}, - {DeliveryMode.NON_PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.TEMP_TOPIC_TYPE}, - {DeliveryMode.NON_PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.NON_PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.TOPIC_TYPE}, - {DeliveryMode.NON_PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.TEMP_QUEUE_TYPE}, - {DeliveryMode.NON_PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.TEMP_TOPIC_TYPE}, - {DeliveryMode.PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.TOPIC_TYPE}, - {DeliveryMode.PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.TEMP_QUEUE_TYPE}, - {DeliveryMode.PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.TEMP_TOPIC_TYPE}, - {DeliveryMode.PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.TOPIC_TYPE}, - {DeliveryMode.PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.TEMP_QUEUE_TYPE}, - {DeliveryMode.PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.TEMP_TOPIC_TYPE}, - {DeliveryMode.PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.TOPIC_TYPE}, - {DeliveryMode.PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.TEMP_QUEUE_TYPE}, - {DeliveryMode.PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.TEMP_TOPIC_TYPE} - }); + public static Collection getParams() { + return Arrays.asList(new Object[][]{{DeliveryMode.NON_PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.NON_PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.TOPIC_TYPE}, {DeliveryMode.NON_PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.TEMP_QUEUE_TYPE}, {DeliveryMode.NON_PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.TEMP_TOPIC_TYPE}, {DeliveryMode.NON_PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.NON_PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.TOPIC_TYPE}, {DeliveryMode.NON_PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.TEMP_QUEUE_TYPE}, {DeliveryMode.NON_PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.TEMP_TOPIC_TYPE}, {DeliveryMode.NON_PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.NON_PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.TOPIC_TYPE}, {DeliveryMode.NON_PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.TEMP_QUEUE_TYPE}, {DeliveryMode.NON_PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.TEMP_TOPIC_TYPE}, {DeliveryMode.PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.TOPIC_TYPE}, {DeliveryMode.PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.TEMP_QUEUE_TYPE}, {DeliveryMode.PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.TEMP_TOPIC_TYPE}, {DeliveryMode.PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.TOPIC_TYPE}, {DeliveryMode.PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.TEMP_QUEUE_TYPE}, {DeliveryMode.PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.TEMP_TOPIC_TYPE}, {DeliveryMode.PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.TOPIC_TYPE}, {DeliveryMode.PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.TEMP_QUEUE_TYPE}, {DeliveryMode.PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.TEMP_TOPIC_TYPE}}); } public ActiveMQDestination destination; @@ -75,18 +49,16 @@ public class JMSConsumer3Test extends BasicOpenWireTest public byte destinationType; public boolean durableConsumer; - public JMSConsumer3Test(int deliveryMode, int ackMode, byte destinationType) - { + public JMSConsumer3Test(int deliveryMode, int ackMode, byte destinationType) { this.deliveryMode = deliveryMode; this.ackMode = ackMode; this.destinationType = destinationType; } @Test - public void testMutiReceiveWithPrefetch1() throws Exception - { + public void testMutiReceiveWithPrefetch1() throws Exception { // Set prefetch to 1 - ((ActiveMQConnection)connection).getPrefetchPolicy().setAll(1); + ((ActiveMQConnection) connection).getPrefetchPolicy().setAll(1); connection.start(); // Use all the ack modes @@ -100,8 +72,7 @@ public class JMSConsumer3Test extends BasicOpenWireTest System.out.println("messages are sent."); // Make sure 4 messages were delivered. Message message = null; - for (int i = 0; i < 4; i++) - { + for (int i = 0; i < 4; i++) { message = consumer.receive(5000); System.out.println("message received: " + message + " ack mode: " + ackMode); assertNotNull(message); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer4Test.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer4Test.java index 14f8776245..45d96b2979 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer4Test.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer4Test.java @@ -37,40 +37,31 @@ import org.junit.runners.Parameterized; * adapted from: org.apache.activemq.JMSConsumerTest */ @RunWith(Parameterized.class) -public class JMSConsumer4Test extends BasicOpenWireTest -{ +public class JMSConsumer4Test extends BasicOpenWireTest { + @Parameterized.Parameters(name = "deliveryMode={0} destinationType={1}") - public static Collection getParams() - { - return Arrays.asList(new Object[][] { - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TOPIC_TYPE}, - {DeliveryMode.PERSISTENT, ActiveMQDestination.TOPIC_TYPE} - }); + public static Collection getParams() { + return Arrays.asList(new Object[][]{{DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TOPIC_TYPE}, {DeliveryMode.PERSISTENT, ActiveMQDestination.TOPIC_TYPE}}); } public int deliveryMode; public byte destinationType; - public JMSConsumer4Test(int deliveryMode, byte destinationType) - { + public JMSConsumer4Test(int deliveryMode, byte destinationType) { this.deliveryMode = deliveryMode; this.destinationType = destinationType; } @Test - public void testDurableConsumerSelectorChange() throws Exception - { + public void testDurableConsumerSelectorChange() throws Exception { // Receive a message with the JMS API connection.setClientID("test"); connection.start(); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination = createDestination(session, - destinationType); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQDestination destination = createDestination(session, destinationType); MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(deliveryMode); - MessageConsumer consumer = session.createDurableSubscriber( - (Topic) destination, "test", "color='red'", false); + MessageConsumer consumer = session.createDurableSubscriber((Topic) destination, "test", "color='red'", false); // Send the messages TextMessage message = session.createTextMessage("1st"); @@ -83,8 +74,7 @@ public class JMSConsumer4Test extends BasicOpenWireTest // Change the subscription. consumer.close(); - consumer = session.createDurableSubscriber((Topic) destination, "test", - "color='blue'", false); + consumer = session.createDurableSubscriber((Topic) destination, "test", "color='blue'", false); message = session.createTextMessage("2nd"); message.setStringProperty("color", "red"); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer5Test.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer5Test.java index 7924b8ded8..b66d82423b 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer5Test.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer5Test.java @@ -40,41 +40,27 @@ import org.junit.runners.Parameterized; * adapted from: org.apache.activemq.JMSConsumerTest */ @RunWith(Parameterized.class) -public class JMSConsumer5Test extends BasicOpenWireTest -{ +public class JMSConsumer5Test extends BasicOpenWireTest { + @Parameterized.Parameters(name = "deliveryMode={0} destinationType={1}") - public static Collection getParams() - { - return Arrays.asList(new Object[][] { - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TOPIC_TYPE}, - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE}, - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE}, - {DeliveryMode.PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.PERSISTENT, ActiveMQDestination.TOPIC_TYPE}, - {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE}, - {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE} - }); + public static Collection getParams() { + return Arrays.asList(new Object[][]{{DeliveryMode.NON_PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TOPIC_TYPE}, {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE}, {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE}, {DeliveryMode.PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.PERSISTENT, ActiveMQDestination.TOPIC_TYPE}, {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE}, {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE}}); } public int deliveryMode; public byte destinationType; - public JMSConsumer5Test(int deliveryMode, byte destinationType) - { + public JMSConsumer5Test(int deliveryMode, byte destinationType) { this.deliveryMode = deliveryMode; this.destinationType = destinationType; } @Test - public void testSendReceiveBytesMessage() throws Exception - { + public void testSendReceiveBytesMessage() throws Exception { // Receive a message with the JMS API connection.start(); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination = createDestination(session, - destinationType); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQDestination destination = createDestination(session, destinationType); MessageConsumer consumer = session.createConsumer(destination); MessageProducer producer = session.createProducer(destination); @@ -93,31 +79,25 @@ public class JMSConsumer5Test extends BasicOpenWireTest } @Test - public void testSetMessageListenerAfterStart() throws Exception - { + public void testSetMessageListenerAfterStart() throws Exception { final AtomicInteger counter = new AtomicInteger(0); final CountDownLatch done = new CountDownLatch(1); // Receive a message with the JMS API connection.start(); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination = createDestination(session, - destinationType); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQDestination destination = createDestination(session, destinationType); MessageConsumer consumer = session.createConsumer(destination); // Send the messages sendMessages(session, destination, 4); // See if the message get sent to the listener - consumer.setMessageListener(new MessageListener() - { + consumer.setMessageListener(new MessageListener() { @Override - public void onMessage(Message m) - { + public void onMessage(Message m) { counter.incrementAndGet(); - if (counter.get() == 4) - { + if (counter.get() == 4) { System.out.println("ok finished all 4, done sleep"); done.countDown(); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer6Test.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer6Test.java index beaf8108a0..0c1b1b128d 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer6Test.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer6Test.java @@ -16,23 +16,22 @@ */ package org.apache.activemq.artemis.tests.integration.openwire.amq; -import java.util.Arrays; -import java.util.Collection; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageListener; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; +import java.util.Arrays; +import java.util.Collection; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import org.apache.activemq.ActiveMQMessageConsumer; import org.apache.activemq.ActiveMQSession; -import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.artemis.tests.integration.openwire.BasicOpenWireTest; +import org.apache.activemq.command.ActiveMQDestination; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -41,27 +40,21 @@ import org.junit.runners.Parameterized; * adapted from: org.apache.activemq.JMSConsumerTest */ @RunWith(Parameterized.class) -public class JMSConsumer6Test extends BasicOpenWireTest -{ +public class JMSConsumer6Test extends BasicOpenWireTest { + @Parameterized.Parameters(name = "destinationType={0}") - public static Collection getParams() - { - return Arrays.asList(new Object[][] { - {ActiveMQDestination.QUEUE_TYPE}, - {ActiveMQDestination.TOPIC_TYPE} - }); + public static Collection getParams() { + return Arrays.asList(new Object[][]{{ActiveMQDestination.QUEUE_TYPE}, {ActiveMQDestination.TOPIC_TYPE}}); } public byte destinationType; - public JMSConsumer6Test(byte destinationType) - { + public JMSConsumer6Test(byte destinationType) { this.destinationType = destinationType; } @Test - public void testPassMessageListenerIntoCreateConsumer() throws Exception - { + public void testPassMessageListenerIntoCreateConsumer() throws Exception { final AtomicInteger counter = new AtomicInteger(0); final CountDownLatch done = new CountDownLatch(1); @@ -70,19 +63,15 @@ public class JMSConsumer6Test extends BasicOpenWireTest connection.start(); ActiveMQSession session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQDestination destination = createDestination(session, destinationType); - MessageConsumer consumer = session.createConsumer(destination, - new MessageListener() - { - @Override - public void onMessage(Message m) - { - counter.incrementAndGet(); - if (counter.get() == 4) - { - done.countDown(); - } + MessageConsumer consumer = session.createConsumer(destination, new MessageListener() { + @Override + public void onMessage(Message m) { + counter.incrementAndGet(); + if (counter.get() == 4) { + done.countDown(); } - }); + } + }); assertNotNull(consumer); // Send the messages @@ -96,24 +85,19 @@ public class JMSConsumer6Test extends BasicOpenWireTest } @Test - public void testAckOfExpired() throws Exception - { + public void testAckOfExpired() throws Exception { connection.start(); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination = createDestination(session, - destinationType); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQDestination destination = createDestination(session, destinationType); MessageConsumer consumer = session.createConsumer(destination); connection.setStatsEnabled(true); - Session sendSession = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + Session sendSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = sendSession.createProducer(destination); producer.setTimeToLive(1000); final int count = 4; - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { TextMessage message = sendSession.createTextMessage("" + i); producer.send(message); } @@ -122,26 +106,22 @@ public class JMSConsumer6Test extends BasicOpenWireTest Thread.sleep(2000); producer.setTimeToLive(0); - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { TextMessage message = sendSession.createTextMessage("no expiry" + i); producer.send(message); } ActiveMQMessageConsumer amqConsumer = (ActiveMQMessageConsumer) consumer; - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { TextMessage msg = (TextMessage) amqConsumer.receive(); assertNotNull(msg); - assertTrue("message has \"no expiry\" text: " + msg.getText(), msg - .getText().contains("no expiry")); + assertTrue("message has \"no expiry\" text: " + msg.getText(), msg.getText().contains("no expiry")); // force an ack when there are expired messages amqConsumer.acknowledge(); } - assertEquals("consumer has expiredMessages", count, amqConsumer - .getConsumerStats().getExpiredMessageCount().getCount()); + assertEquals("consumer has expiredMessages", count, amqConsumer.getConsumerStats().getExpiredMessageCount().getCount()); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer7Test.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer7Test.java index 59bcc03762..d0147976d9 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer7Test.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer7Test.java @@ -40,31 +40,25 @@ import org.junit.runners.Parameterized; * adapted from: org.apache.activemq.JMSConsumerTest */ @RunWith(Parameterized.class) -public class JMSConsumer7Test extends BasicOpenWireTest -{ +public class JMSConsumer7Test extends BasicOpenWireTest { + @Parameterized.Parameters(name = "deliveryMode={0} ackMode={1} destinationType={2}") - public static Collection getParams() - { - return Arrays.asList(new Object[][] { - {DeliveryMode.NON_PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE} - }); + public static Collection getParams() { + return Arrays.asList(new Object[][]{{DeliveryMode.NON_PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}}); } public int deliveryMode; public int ackMode; public byte destinationType; - public JMSConsumer7Test(int deliveryMode, int ackMode, byte destinationType) - { + public JMSConsumer7Test(int deliveryMode, int ackMode, byte destinationType) { this.deliveryMode = deliveryMode; this.ackMode = ackMode; this.destinationType = destinationType; } @Test - public void testMessageListenerOnMessageCloseUnackedWithPrefetch1StayInQueue() throws Exception - { + public void testMessageListenerOnMessageCloseUnackedWithPrefetch1StayInQueue() throws Exception { final AtomicInteger counter = new AtomicInteger(0); final CountDownLatch sendDone = new CountDownLatch(1); final CountDownLatch got2Done = new CountDownLatch(1); @@ -80,21 +74,16 @@ public class JMSConsumer7Test extends BasicOpenWireTest // Use all the ack modes Session session = connection.createSession(false, ackMode); - ActiveMQDestination destination = createDestination(session, - destinationType); + ActiveMQDestination destination = createDestination(session, destinationType); MessageConsumer consumer = session.createConsumer(destination); - consumer.setMessageListener(new MessageListener() - { + consumer.setMessageListener(new MessageListener() { @Override - public void onMessage(Message m) - { - try - { + public void onMessage(Message m) { + try { TextMessage tm = (TextMessage) m; assertEquals("" + counter.get(), tm.getText()); counter.incrementAndGet(); - if (counter.get() == 2) - { + if (counter.get() == 2) { sendDone.await(); connection.close(); got2Done.countDown(); @@ -102,8 +91,7 @@ public class JMSConsumer7Test extends BasicOpenWireTest System.out.println("acking tm: " + tm.getText()); tm.acknowledge(); } - catch (Throwable e) - { + catch (Throwable e) { System.out.println("ack failed!!"); e.printStackTrace(); } @@ -127,26 +115,21 @@ public class JMSConsumer7Test extends BasicOpenWireTest final CountDownLatch done2 = new CountDownLatch(1); session = connection.createSession(false, ackMode); consumer = session.createConsumer(destination); - consumer.setMessageListener(new MessageListener() - { + consumer.setMessageListener(new MessageListener() { @Override - public void onMessage(Message m) - { - try - { + public void onMessage(Message m) { + try { TextMessage tm = (TextMessage) m; System.out.println("2nd received: " + tm.getText()); // order is not guaranteed as the connection is started before // the listener is set. // assertEquals("" + counter.get(), tm.getText()); counter.incrementAndGet(); - if (counter.get() == 4) - { + if (counter.get() == 4) { done2.countDown(); } } - catch (Throwable e) - { + catch (Throwable e) { System.err.println("Unexpected exception: " + e); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer8Test.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer8Test.java index 0a48fea9d7..f4505f1d7f 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer8Test.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer8Test.java @@ -40,33 +40,25 @@ import org.junit.runners.Parameterized; * adapted from: org.apache.activemq.JMSConsumerTest */ @RunWith(Parameterized.class) -public class JMSConsumer8Test extends BasicOpenWireTest -{ +public class JMSConsumer8Test extends BasicOpenWireTest { + @Parameterized.Parameters(name = "deliveryMode={0} ackMode={1} destinationType={2}") - public static Collection getParams() - { - return Arrays.asList(new Object[][] { - {DeliveryMode.NON_PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.NON_PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE} - }); + public static Collection getParams() { + return Arrays.asList(new Object[][]{{DeliveryMode.NON_PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.NON_PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}}); } public int deliveryMode; public int ackMode; public byte destinationType; - public JMSConsumer8Test(int deliveryMode, int ackMode, byte destinationType) - { + public JMSConsumer8Test(int deliveryMode, int ackMode, byte destinationType) { this.deliveryMode = deliveryMode; this.ackMode = ackMode; this.destinationType = destinationType; } @Test - public void testMessageListenerAutoAckOnCloseWithPrefetch1() throws Exception - { + public void testMessageListenerAutoAckOnCloseWithPrefetch1() throws Exception { final AtomicInteger counter = new AtomicInteger(0); final CountDownLatch sendDone = new CountDownLatch(1); @@ -83,29 +75,23 @@ public class JMSConsumer8Test extends BasicOpenWireTest // Use all the ack modes Session session = connection.createSession(false, ackMode); - ActiveMQDestination destination = createDestination(session, - destinationType); + ActiveMQDestination destination = createDestination(session, destinationType); MessageConsumer consumer = session.createConsumer(destination); - consumer.setMessageListener(new MessageListener() - { + consumer.setMessageListener(new MessageListener() { @Override - public void onMessage(Message m) - { - try - { + public void onMessage(Message m) { + try { TextMessage tm = (TextMessage) m; assertEquals("" + counter.get(), tm.getText()); counter.incrementAndGet(); m.acknowledge(); - if (counter.get() == 2) - { + if (counter.get() == 2) { sendDone.await(); connection.close(); got2Done.countDown(); } } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); } } @@ -128,22 +114,17 @@ public class JMSConsumer8Test extends BasicOpenWireTest final CountDownLatch done2 = new CountDownLatch(1); session = connection.createSession(false, ackMode); consumer = session.createConsumer(destination); - consumer.setMessageListener(new MessageListener() - { + consumer.setMessageListener(new MessageListener() { @Override - public void onMessage(Message m) - { - try - { + public void onMessage(Message m) { + try { TextMessage tm = (TextMessage) m; counter.incrementAndGet(); - if (counter.get() == 4) - { + if (counter.get() == 4) { done2.countDown(); } } - catch (Throwable e) - { + catch (Throwable e) { System.err.println("Unexpected exception " + e); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer9Test.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer9Test.java index ee878df08e..f6da123804 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer9Test.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSConsumer9Test.java @@ -38,35 +38,23 @@ import org.junit.runners.Parameterized; * adapted from: org.apache.activemq.JMSConsumerTest */ @RunWith(Parameterized.class) -public class JMSConsumer9Test extends BasicOpenWireTest -{ +public class JMSConsumer9Test extends BasicOpenWireTest { + @Parameterized.Parameters(name = "deliveryMode={0} destinationType={1}") - public static Collection getParams() - { - return Arrays.asList(new Object[][] { - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TOPIC_TYPE}, - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE}, - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE}, - {DeliveryMode.PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.PERSISTENT, ActiveMQDestination.TOPIC_TYPE}, - {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE}, - {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE} - }); + public static Collection getParams() { + return Arrays.asList(new Object[][]{{DeliveryMode.NON_PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TOPIC_TYPE}, {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE}, {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE}, {DeliveryMode.PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.PERSISTENT, ActiveMQDestination.TOPIC_TYPE}, {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE}, {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE}}); } public int deliveryMode; public byte destinationType; - public JMSConsumer9Test(int deliveryMode, byte destinationType) - { + public JMSConsumer9Test(int deliveryMode, byte destinationType) { this.deliveryMode = deliveryMode; this.destinationType = destinationType; } @Test - public void testMessageListenerWithConsumerWithPrefetch1() throws Exception - { + public void testMessageListenerWithConsumerWithPrefetch1() throws Exception { final AtomicInteger counter = new AtomicInteger(0); final CountDownLatch done = new CountDownLatch(1); @@ -75,19 +63,14 @@ public class JMSConsumer9Test extends BasicOpenWireTest connection.getPrefetchPolicy().setAll(1); connection.start(); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination = createDestination(session, - destinationType); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQDestination destination = createDestination(session, destinationType); MessageConsumer consumer = session.createConsumer(destination); - consumer.setMessageListener(new MessageListener() - { + consumer.setMessageListener(new MessageListener() { @Override - public void onMessage(Message m) - { + public void onMessage(Message m) { counter.incrementAndGet(); - if (counter.get() == 4) - { + if (counter.get() == 4) { done.countDown(); } } @@ -103,27 +86,21 @@ public class JMSConsumer9Test extends BasicOpenWireTest assertEquals(4, counter.get()); } - public void testMessageListenerWithConsumer() throws Exception - { + public void testMessageListenerWithConsumer() throws Exception { final AtomicInteger counter = new AtomicInteger(0); final CountDownLatch done = new CountDownLatch(1); // Receive a message with the JMS API connection.start(); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination = createDestination(session, - destinationType); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + ActiveMQDestination destination = createDestination(session, destinationType); MessageConsumer consumer = session.createConsumer(destination); - consumer.setMessageListener(new MessageListener() - { + consumer.setMessageListener(new MessageListener() { @Override - public void onMessage(Message m) - { + public void onMessage(Message m) { counter.incrementAndGet(); - if (counter.get() == 4) - { + if (counter.get() == 4) { done.countDown(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSDurableTopicRedeliverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSDurableTopicRedeliverTest.java index 990a1c94e5..ca96492cb8 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSDurableTopicRedeliverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSDurableTopicRedeliverTest.java @@ -26,13 +26,11 @@ import org.junit.Test; /** * adapted from: org.apache.activemq.JMSDurableTopicRedeliverTest */ -public class JMSDurableTopicRedeliverTest extends JmsTopicRedeliverTest -{ +public class JMSDurableTopicRedeliverTest extends JmsTopicRedeliverTest { @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { durable = true; super.setUp(); } @@ -43,15 +41,12 @@ public class JMSDurableTopicRedeliverTest extends JmsTopicRedeliverTest * @throws Exception */ @Test - public void testRedeliverNewSession() throws Exception - { + public void testRedeliverNewSession() throws Exception { String text = "TEST: " + System.currentTimeMillis(); Message sendMessage = session.createTextMessage(text); - if (verbose) - { - System.out.println("About to send a message: " + sendMessage - + " with text: " + text); + if (verbose) { + System.out.println("About to send a message: " + sendMessage + " with text: " + text); } producer.send(producerDestination, sendMessage); @@ -66,8 +61,7 @@ public class JMSDurableTopicRedeliverTest extends JmsTopicRedeliverTest consumer.close(); // receive then acknowledge - consumeSession = connection.createSession(false, - Session.CLIENT_ACKNOWLEDGE); + consumeSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); consumer = createConsumer(getName()); Message ackMessage = consumer.receive(1000); assertNotNull(ackMessage); @@ -81,16 +75,13 @@ public class JMSDurableTopicRedeliverTest extends JmsTopicRedeliverTest consumeSession.close(); consumer.close(); - consumeSession = connection.createSession(false, - Session.CLIENT_ACKNOWLEDGE); + consumeSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); consumer = createConsumer(getName()); assertNull(consumer.receive(1000)); } - protected String getName() - { + protected String getName() { return "JMSDurableTopicRedeliverTest"; } - } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSIndividualAckTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSIndividualAckTest.java index 00fa05d8a0..d4073da9cb 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSIndividualAckTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSIndividualAckTest.java @@ -32,8 +32,7 @@ import org.junit.Test; /** * adapted from: org.apache.activemq.JMSIndividualAckTest */ -public class JMSIndividualAckTest extends BasicOpenWireTest -{ +public class JMSIndividualAckTest extends BasicOpenWireTest { /** * Tests if acknowledged messages are being consumed. @@ -41,8 +40,7 @@ public class JMSIndividualAckTest extends BasicOpenWireTest * @throws JMSException */ @Test - public void testAckedMessageAreConsumed() throws JMSException - { + public void testAckedMessageAreConsumed() throws JMSException { connection.start(); Session session = connection.createSession(false, ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE); Queue queue = (Queue) this.createDestination(session, ActiveMQDestination.QUEUE_TYPE); @@ -73,8 +71,7 @@ public class JMSIndividualAckTest extends BasicOpenWireTest * @throws JMSException */ @Test - public void testLastMessageAcked() throws JMSException - { + public void testLastMessageAcked() throws JMSException { connection.start(); Session session = connection.createSession(false, ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE); Queue queue = (Queue) this.createDestination(session, ActiveMQDestination.QUEUE_TYPE); @@ -98,8 +95,7 @@ public class JMSIndividualAckTest extends BasicOpenWireTest // Reset the session. session.close(); - session = connection.createSession(false, - ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE); + session = connection.createSession(false, ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE); // Attempt to Consume the message... consumer = session.createConsumer(queue); @@ -121,8 +117,7 @@ public class JMSIndividualAckTest extends BasicOpenWireTest * @throws JMSException */ @Test - public void testUnAckedMessageAreNotConsumedOnSessionClose() throws JMSException - { + public void testUnAckedMessageAreNotConsumedOnSessionClose() throws JMSException { connection.start(); Session session = connection.createSession(false, ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE); Queue queue = (Queue) this.createDestination(session, ActiveMQDestination.QUEUE_TYPE); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSMessageTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSMessageTest.java index b7903db215..43cf62e0af 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSMessageTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSMessageTest.java @@ -45,15 +45,11 @@ import org.junit.runners.Parameterized; * adapted from: org.apache.activemq.JMSMessageTest */ @RunWith(Parameterized.class) -public class JMSMessageTest extends BasicOpenWireTest -{ +public class JMSMessageTest extends BasicOpenWireTest { + @Parameterized.Parameters(name = "deliveryMode={0} destinationType={1}") - public static Collection getParams() - { - return Arrays.asList(new Object[][] { - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, - }); + public static Collection getParams() { + return Arrays.asList(new Object[][]{{DeliveryMode.NON_PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.PERSISTENT, ActiveMQDestination.QUEUE_TYPE},}); } public int deliveryMode = DeliveryMode.NON_PERSISTENT; @@ -61,20 +57,17 @@ public class JMSMessageTest extends BasicOpenWireTest public ActiveMQDestination destination; public boolean durableConsumer; - public JMSMessageTest(int deliveryMode, byte destinationType) - { + public JMSMessageTest(int deliveryMode, byte destinationType) { this.deliveryMode = deliveryMode; this.destinationType = destinationType; } @Test - public void testTextMessage() throws Exception - { + public void testTextMessage() throws Exception { // Receive a message with the JMS API connection.start(); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); destination = createDestination(session, destinationType); MessageConsumer consumer = session.createConsumer(destination); MessageProducer producer = session.createProducer(destination); @@ -97,13 +90,11 @@ public class JMSMessageTest extends BasicOpenWireTest } @Test - public void testBytesMessageLength() throws Exception - { + public void testBytesMessageLength() throws Exception { // Receive a message with the JMS API connection.start(); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); destination = createDestination(session, destinationType); MessageConsumer consumer = session.createConsumer(destination); MessageProducer producer = session.createProducer(destination); @@ -129,12 +120,10 @@ public class JMSMessageTest extends BasicOpenWireTest } @Test - public void testObjectMessage() throws Exception - { + public void testObjectMessage() throws Exception { // Receive a message with the JMS API connection.start(); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); destination = createDestination(session, destinationType); MessageConsumer consumer = session.createConsumer(destination); MessageProducer producer = session.createProducer(destination); @@ -156,13 +145,11 @@ public class JMSMessageTest extends BasicOpenWireTest } @Test - public void testBytesMessage() throws Exception - { + public void testBytesMessage() throws Exception { // Receive a message with the JMS API connection.start(); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); destination = createDestination(session, destinationType); MessageConsumer consumer = session.createConsumer(destination); MessageProducer producer = session.createProducer(destination); @@ -180,13 +167,11 @@ public class JMSMessageTest extends BasicOpenWireTest assertNotNull(message); assertTrue(message.readBoolean()); - try - { + try { message.readByte(); fail("Expected exception not thrown."); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { } } @@ -194,13 +179,11 @@ public class JMSMessageTest extends BasicOpenWireTest } @Test - public void testStreamMessage() throws Exception - { + public void testStreamMessage() throws Exception { // Receive a message with the JMS API connection.start(); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); destination = createDestination(session, destinationType); MessageConsumer consumer = session.createConsumer(destination); MessageProducer producer = session.createProducer(destination); @@ -219,40 +202,33 @@ public class JMSMessageTest extends BasicOpenWireTest // Invalid conversion should throw exception and not move the stream // position. - try - { + try { message.readByte(); fail("Should have received NumberFormatException"); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } - assertEquals("This is a test to see how it works.", - message.readString()); + assertEquals("This is a test to see how it works.", message.readString()); // Invalid conversion should throw exception and not move the stream // position. - try - { + try { message.readByte(); fail("Should have received MessageEOFException"); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { } } assertNull(consumer.receiveNoWait()); } @Test - public void testMapMessage() throws Exception - { + public void testMapMessage() throws Exception { // Receive a message with the JMS API connection.start(); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); destination = createDestination(session, destinationType); MessageConsumer consumer = session.createConsumer(destination); MessageProducer producer = session.createProducer(destination); @@ -273,8 +249,7 @@ public class JMSMessageTest extends BasicOpenWireTest assertNull(consumer.receiveNoWait()); } - static class ForeignMessage implements TextMessage - { + static class ForeignMessage implements TextMessage { public int deliveryMode; @@ -291,312 +266,259 @@ public class JMSMessageTest extends BasicOpenWireTest private final HashMap props = new HashMap(); @Override - public String getJMSMessageID() throws JMSException - { + public String getJMSMessageID() throws JMSException { return messageId; } @Override - public void setJMSMessageID(String arg0) throws JMSException - { + public void setJMSMessageID(String arg0) throws JMSException { messageId = arg0; } @Override - public long getJMSTimestamp() throws JMSException - { + public long getJMSTimestamp() throws JMSException { return timestamp; } @Override - public void setJMSTimestamp(long arg0) throws JMSException - { + public void setJMSTimestamp(long arg0) throws JMSException { timestamp = arg0; } @Override - public byte[] getJMSCorrelationIDAsBytes() throws JMSException - { + public byte[] getJMSCorrelationIDAsBytes() throws JMSException { return null; } @Override - public void setJMSCorrelationIDAsBytes(byte[] arg0) throws JMSException - { + public void setJMSCorrelationIDAsBytes(byte[] arg0) throws JMSException { } @Override - public void setJMSCorrelationID(String arg0) throws JMSException - { + public void setJMSCorrelationID(String arg0) throws JMSException { correlationId = arg0; } @Override - public String getJMSCorrelationID() throws JMSException - { + public String getJMSCorrelationID() throws JMSException { return correlationId; } @Override - public Destination getJMSReplyTo() throws JMSException - { + public Destination getJMSReplyTo() throws JMSException { return replyTo; } @Override - public void setJMSReplyTo(Destination arg0) throws JMSException - { + public void setJMSReplyTo(Destination arg0) throws JMSException { replyTo = arg0; } @Override - public Destination getJMSDestination() throws JMSException - { + public Destination getJMSDestination() throws JMSException { return destination; } @Override - public void setJMSDestination(Destination arg0) throws JMSException - { + public void setJMSDestination(Destination arg0) throws JMSException { destination = arg0; } @Override - public int getJMSDeliveryMode() throws JMSException - { + public int getJMSDeliveryMode() throws JMSException { return deliveryMode; } @Override - public void setJMSDeliveryMode(int arg0) throws JMSException - { + public void setJMSDeliveryMode(int arg0) throws JMSException { deliveryMode = arg0; } @Override - public boolean getJMSRedelivered() throws JMSException - { + public boolean getJMSRedelivered() throws JMSException { return redelivered; } @Override - public void setJMSRedelivered(boolean arg0) throws JMSException - { + public void setJMSRedelivered(boolean arg0) throws JMSException { redelivered = arg0; } @Override - public String getJMSType() throws JMSException - { + public String getJMSType() throws JMSException { return type; } @Override - public void setJMSType(String arg0) throws JMSException - { + public void setJMSType(String arg0) throws JMSException { type = arg0; } @Override - public long getJMSExpiration() throws JMSException - { + public long getJMSExpiration() throws JMSException { return expiration; } @Override - public void setJMSExpiration(long arg0) throws JMSException - { + public void setJMSExpiration(long arg0) throws JMSException { expiration = arg0; } @Override - public int getJMSPriority() throws JMSException - { + public int getJMSPriority() throws JMSException { return priority; } @Override - public void setJMSPriority(int arg0) throws JMSException - { + public void setJMSPriority(int arg0) throws JMSException { priority = arg0; } @Override - public void clearProperties() throws JMSException - { + public void clearProperties() throws JMSException { } @Override - public boolean propertyExists(String arg0) throws JMSException - { + public boolean propertyExists(String arg0) throws JMSException { return false; } @Override - public boolean getBooleanProperty(String arg0) throws JMSException - { + public boolean getBooleanProperty(String arg0) throws JMSException { return false; } @Override - public byte getByteProperty(String arg0) throws JMSException - { + public byte getByteProperty(String arg0) throws JMSException { return 0; } @Override - public short getShortProperty(String arg0) throws JMSException - { + public short getShortProperty(String arg0) throws JMSException { return 0; } @Override - public int getIntProperty(String arg0) throws JMSException - { + public int getIntProperty(String arg0) throws JMSException { return 0; } @Override - public long getLongProperty(String arg0) throws JMSException - { + public long getLongProperty(String arg0) throws JMSException { return 0; } @Override - public float getFloatProperty(String arg0) throws JMSException - { + public float getFloatProperty(String arg0) throws JMSException { return 0; } @Override - public double getDoubleProperty(String arg0) throws JMSException - { + public double getDoubleProperty(String arg0) throws JMSException { return 0; } @Override - public String getStringProperty(String arg0) throws JMSException - { + public String getStringProperty(String arg0) throws JMSException { return (String) props.get(arg0); } @Override - public Object getObjectProperty(String arg0) throws JMSException - { + public Object getObjectProperty(String arg0) throws JMSException { return props.get(arg0); } @Override - public Enumeration getPropertyNames() throws JMSException - { + public Enumeration getPropertyNames() throws JMSException { return new Vector(props.keySet()).elements(); } @Override - public void setBooleanProperty(String arg0, boolean arg1) throws JMSException - { + public void setBooleanProperty(String arg0, boolean arg1) throws JMSException { } @Override - public void setByteProperty(String arg0, byte arg1) throws JMSException - { + public void setByteProperty(String arg0, byte arg1) throws JMSException { } @Override - public void setShortProperty(String arg0, short arg1) throws JMSException - { + public void setShortProperty(String arg0, short arg1) throws JMSException { } @Override - public void setIntProperty(String arg0, int arg1) throws JMSException - { + public void setIntProperty(String arg0, int arg1) throws JMSException { } @Override - public void setLongProperty(String arg0, long arg1) throws JMSException - { + public void setLongProperty(String arg0, long arg1) throws JMSException { } @Override - public void setFloatProperty(String arg0, float arg1) throws JMSException - { + public void setFloatProperty(String arg0, float arg1) throws JMSException { } @Override - public void setDoubleProperty(String arg0, double arg1) throws JMSException - { + public void setDoubleProperty(String arg0, double arg1) throws JMSException { } @Override - public void setStringProperty(String arg0, String arg1) throws JMSException - { + public void setStringProperty(String arg0, String arg1) throws JMSException { props.put(arg0, arg1); } @Override - public void setObjectProperty(String arg0, Object arg1) throws JMSException - { + public void setObjectProperty(String arg0, Object arg1) throws JMSException { props.put(arg0, arg1); } @Override - public void acknowledge() throws JMSException - { + public void acknowledge() throws JMSException { } @Override - public void clearBody() throws JMSException - { + public void clearBody() throws JMSException { } @Override - public void setText(String arg0) throws JMSException - { + public void setText(String arg0) throws JMSException { text = arg0; } @Override - public String getText() throws JMSException - { + public String getText() throws JMSException { return text; } @Override - public T getBody(Class arg0) throws JMSException - { + public T getBody(Class arg0) throws JMSException { // TODO Auto-generated method stub return null; } @Override - public long getJMSDeliveryTime() throws JMSException - { + public long getJMSDeliveryTime() throws JMSException { // TODO Auto-generated method stub return 0; } @Override - public boolean isBodyAssignableTo(Class arg0) throws JMSException - { + public boolean isBodyAssignableTo(Class arg0) throws JMSException { // TODO Auto-generated method stub return false; } @Override - public void setJMSDeliveryTime(long arg0) throws JMSException - { + public void setJMSDeliveryTime(long arg0) throws JMSException { // TODO Auto-generated method stub } } @Test - public void testForeignMessage() throws Exception - { + public void testForeignMessage() throws Exception { // Receive a message with the JMS API connection.start(); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); destination = createDestination(session, destinationType); MessageConsumer consumer = session.createConsumer(destination); MessageProducer producer = session.createProducer(destination); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSQueueRedeliverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSQueueRedeliverTest.java index db403e6464..756928b610 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSQueueRedeliverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSQueueRedeliverTest.java @@ -21,12 +21,11 @@ import org.junit.Before; /** * adapted from: org.apache.activemq.JMSQueueRedeliverTest */ -public class JMSQueueRedeliverTest extends JmsTopicRedeliverTest -{ +public class JMSQueueRedeliverTest extends JmsTopicRedeliverTest { + @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { topic = false; super.setUp(); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSUsecase1Test.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSUsecase1Test.java index 489e34cfe5..b4b0811fba 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSUsecase1Test.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSUsecase1Test.java @@ -36,39 +36,26 @@ import org.junit.runners.Parameterized; * adapted from: org.apache.activemq.JMSUsecaseTest */ @RunWith(Parameterized.class) -public class JMSUsecase1Test extends BasicOpenWireTest -{ +public class JMSUsecase1Test extends BasicOpenWireTest { + @Parameterized.Parameters(name = "deliveryMode={0} destinationType={1}") - public static Collection getParams() - { - return Arrays.asList(new Object[][] { - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE}, - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TOPIC_TYPE}, - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE}, - {DeliveryMode.PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE}, - {DeliveryMode.PERSISTENT, ActiveMQDestination.TOPIC_TYPE}, - {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE} - }); + public static Collection getParams() { + return Arrays.asList(new Object[][]{{DeliveryMode.NON_PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE}, {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TOPIC_TYPE}, {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE}, {DeliveryMode.PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE}, {DeliveryMode.PERSISTENT, ActiveMQDestination.TOPIC_TYPE}, {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE}}); } public int deliveryMode; public byte destinationType; - public JMSUsecase1Test(int deliveryMode, byte destinationType) - { + public JMSUsecase1Test(int deliveryMode, byte destinationType) { this.deliveryMode = deliveryMode; this.destinationType = destinationType; } @Test - public void testSendReceive() throws Exception - { + public void testSendReceive() throws Exception { // Send a message to the broker. connection.start(); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQDestination destination = createDestination(session, destinationType); System.out.println("destionation: " + destination); MessageProducer producer = session.createProducer(destination); @@ -83,14 +70,11 @@ public class JMSUsecase1Test extends BasicOpenWireTest } @Test - public void testSendReceiveTransacted() throws Exception - { + public void testSendReceiveTransacted() throws Exception { // Send a message to the broker. connection.start(); - Session session = connection.createSession(true, - Session.SESSION_TRANSACTED); - ActiveMQDestination destination = createDestination(session, - destinationType); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + ActiveMQDestination destination = createDestination(session, destinationType); MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(this.deliveryMode); MessageConsumer consumer = session.createConsumer(destination); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSUsecaseTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSUsecaseTest.java index 0e2a4552c9..05685f6b11 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSUsecaseTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JMSUsecaseTest.java @@ -38,35 +38,26 @@ import org.junit.runners.Parameterized; * adapted from: org.apache.activemq.JMSUsecaseTest */ @RunWith(Parameterized.class) -public class JMSUsecaseTest extends BasicOpenWireTest -{ +public class JMSUsecaseTest extends BasicOpenWireTest { + @Parameterized.Parameters(name = "deliveryMode={0} destinationType={1}") - public static Collection getParams() - { - return Arrays.asList(new Object[][] { - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE}, - {DeliveryMode.PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, - {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE} - }); + public static Collection getParams() { + return Arrays.asList(new Object[][]{{DeliveryMode.NON_PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE}, {DeliveryMode.PERSISTENT, ActiveMQDestination.QUEUE_TYPE}, {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE}}); } public int deliveryMode; public byte destinationType; - public JMSUsecaseTest(int deliveryMode, byte destinationType) - { + public JMSUsecaseTest(int deliveryMode, byte destinationType) { this.deliveryMode = deliveryMode; this.destinationType = destinationType; } @Test - public void testQueueBrowser() throws Exception - { + public void testQueueBrowser() throws Exception { // Send a message to the broker. connection.start(); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQDestination destination = createDestination(session, destinationType); MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(this.deliveryMode); @@ -75,8 +66,7 @@ public class JMSUsecaseTest extends BasicOpenWireTest QueueBrowser browser = session.createBrowser((Queue) destination); Enumeration enumeration = browser.getEnumeration(); - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { Thread.sleep(100); assertTrue(enumeration.hasMoreElements()); Message m = (Message) enumeration.nextElement(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsAutoAckListenerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsAutoAckListenerTest.java index 5456176ceb..a61e462b76 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsAutoAckListenerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsAutoAckListenerTest.java @@ -32,13 +32,12 @@ import org.junit.Test; /** * adapted from: org.apache.activemq.JmsAutoAckListenerTest */ -public class JmsAutoAckListenerTest extends BasicOpenWireTest implements MessageListener -{ +public class JmsAutoAckListenerTest extends BasicOpenWireTest implements MessageListener { + private final CountDownLatch latch = new CountDownLatch(1); @Test - public void testAckedMessageAreConsumed() throws Exception - { + public void testAckedMessageAreConsumed() throws Exception { connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue(queueName); @@ -59,8 +58,7 @@ public class JmsAutoAckListenerTest extends BasicOpenWireTest implements Message session.close(); } - public void onMessage(Message message) - { + public void onMessage(Message message) { System.out.println("Received message: " + message); assertNotNull(message); latch.countDown(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsAutoAckTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsAutoAckTest.java index 668db0fb2c..564424437b 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsAutoAckTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsAutoAckTest.java @@ -29,19 +29,17 @@ import org.junit.Test; /** * adapted from: org.apache.activemq.JmsAutoAckTest */ -public class JmsAutoAckTest extends BasicOpenWireTest -{ +public class JmsAutoAckTest extends BasicOpenWireTest { + /** * Tests if acknowleged messages are being consumed. * * @throws javax.jms.JMSException */ @Test - public void testAckedMessageAreConsumed() throws JMSException - { + public void testAckedMessageAreConsumed() throws JMSException { connection.start(); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue(queueName); MessageProducer producer = session.createProducer(queue); producer.send(session.createTextMessage("Hello")); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsClientAckTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsClientAckTest.java index cf29d6c9a3..013fe55980 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsClientAckTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsClientAckTest.java @@ -29,19 +29,17 @@ import org.junit.Test; /** * adapted from: org.apache.activemq.JmsClientAckTest */ -public class JmsClientAckTest extends BasicOpenWireTest -{ +public class JmsClientAckTest extends BasicOpenWireTest { + /** * Tests if acknowledged messages are being consumed. * * @throws JMSException */ @Test - public void testAckedMessageAreConsumed() throws JMSException - { + public void testAckedMessageAreConsumed() throws JMSException { connection.start(); - Session session = connection.createSession(false, - Session.CLIENT_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); Queue queue = session.createQueue(getQueueName()); MessageProducer producer = session.createProducer(queue); producer.send(session.createTextMessage("Hello")); @@ -70,11 +68,9 @@ public class JmsClientAckTest extends BasicOpenWireTest * @throws JMSException */ @Test - public void testLastMessageAcked() throws JMSException - { + public void testLastMessageAcked() throws JMSException { connection.start(); - Session session = connection.createSession(false, - Session.CLIENT_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); Queue queue = session.createQueue(getQueueName()); MessageProducer producer = session.createProducer(queue); producer.send(session.createTextMessage("Hello")); @@ -109,11 +105,9 @@ public class JmsClientAckTest extends BasicOpenWireTest * @throws JMSException */ @Test - public void testUnAckedMessageAreNotConsumedOnSessionClose() throws JMSException - { + public void testUnAckedMessageAreNotConsumedOnSessionClose() throws JMSException { connection.start(); - Session session = connection.createSession(false, - Session.CLIENT_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); Queue queue = session.createQueue(getQueueName()); MessageProducer producer = session.createProducer(queue); producer.send(session.createTextMessage("Hello")); @@ -138,8 +132,7 @@ public class JmsClientAckTest extends BasicOpenWireTest session.close(); } - protected String getQueueName() - { + protected String getQueueName() { return queueName; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsConnectionStartStopTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsConnectionStartStopTest.java index 2f91cf76ac..31cbb93e45 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsConnectionStartStopTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsConnectionStartStopTest.java @@ -40,14 +40,13 @@ import org.junit.Test; /** * adapted from: org.apache.activemq.JmsConnectionStartStopTest */ -public class JmsConnectionStartStopTest extends BasicOpenWireTest -{ +public class JmsConnectionStartStopTest extends BasicOpenWireTest { + private Connection startedConnection; private Connection stoppedConnection; @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); startedConnection = factory.createConnection(); startedConnection.start(); @@ -58,8 +57,7 @@ public class JmsConnectionStartStopTest extends BasicOpenWireTest * @see junit.framework.TestCase#tearDown() */ @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { stoppedConnection.close(); startedConnection.close(); super.tearDown(); @@ -72,12 +70,9 @@ public class JmsConnectionStartStopTest extends BasicOpenWireTest * @throws JMSException */ @Test - public void testStoppedConsumerHoldsMessagesTillStarted() throws JMSException - { - Session startedSession = startedConnection.createSession(false, - Session.AUTO_ACKNOWLEDGE); - Session stoppedSession = stoppedConnection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + public void testStoppedConsumerHoldsMessagesTillStarted() throws JMSException { + Session startedSession = startedConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Session stoppedSession = stoppedConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Setup the consumers. Topic topic = startedSession.createTopic("test"); @@ -111,8 +106,7 @@ public class JmsConnectionStartStopTest extends BasicOpenWireTest * @throws Exception */ @Test - public void testMultipleConnectionStops() throws Exception - { + public void testMultipleConnectionStops() throws Exception { testStoppedConsumerHoldsMessagesTillStarted(); stoppedConnection.stop(); testStoppedConsumerHoldsMessagesTillStarted(); @@ -121,66 +115,51 @@ public class JmsConnectionStartStopTest extends BasicOpenWireTest } @Test - public void testConcurrentSessionCreateWithStart() throws Exception - { - ThreadPoolExecutor executor = new ThreadPoolExecutor(50, - Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, - new SynchronousQueue()); + public void testConcurrentSessionCreateWithStart() throws Exception { + ThreadPoolExecutor executor = new ThreadPoolExecutor(50, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue()); final Vector exceptions = new Vector(); final AtomicInteger counter = new AtomicInteger(0); final Random rand = new Random(); - Runnable createSessionTask = new Runnable() - { + Runnable createSessionTask = new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { TimeUnit.MILLISECONDS.sleep(rand.nextInt(10)); stoppedConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); counter.incrementAndGet(); } - catch (Exception e) - { + catch (Exception e) { exceptions.add(e); } - catch (Throwable t) - { + catch (Throwable t) { } } }; - Runnable startStopTask = new Runnable() - { + Runnable startStopTask = new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { TimeUnit.MILLISECONDS.sleep(rand.nextInt(10)); stoppedConnection.start(); stoppedConnection.stop(); } - catch (Exception e) - { + catch (Exception e) { exceptions.add(e); } - catch (Throwable t) - { + catch (Throwable t) { } } }; - for (int i = 0; i < 1000; i++) - { + for (int i = 0; i < 1000; i++) { executor.execute(createSessionTask); executor.execute(startStopTask); } executor.shutdown(); - assertTrue("executor terminated", - executor.awaitTermination(30, TimeUnit.SECONDS)); + assertTrue("executor terminated", executor.awaitTermination(30, TimeUnit.SECONDS)); assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsConsumerResetActiveListenerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsConsumerResetActiveListenerTest.java index 5e0d7203d2..80405b983e 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsConsumerResetActiveListenerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsConsumerResetActiveListenerTest.java @@ -37,8 +37,7 @@ import org.junit.Test; /** * adapted from: org.apache.activemq.JmsConsumerResetActiveListenerTest */ -public class JmsConsumerResetActiveListenerTest extends BasicOpenWireTest -{ +public class JmsConsumerResetActiveListenerTest extends BasicOpenWireTest { /** * verify the (undefined by spec) behaviour of setting a listener while @@ -47,35 +46,27 @@ public class JmsConsumerResetActiveListenerTest extends BasicOpenWireTest * @throws Exception */ @Test - public void testSetListenerFromListener() throws Exception - { - Session session = connection.createSession(false, - Session.CLIENT_ACKNOWLEDGE); + public void testSetListenerFromListener() throws Exception { + Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); Destination dest = session.createQueue(queueName); final MessageConsumer consumer = session.createConsumer(dest); final CountDownLatch latch = new CountDownLatch(2); final AtomicBoolean first = new AtomicBoolean(true); final Vector results = new Vector(); - consumer.setMessageListener(new MessageListener() - { + consumer.setMessageListener(new MessageListener() { - public void onMessage(Message message) - { - if (first.compareAndSet(true, false)) - { - try - { + public void onMessage(Message message) { + if (first.compareAndSet(true, false)) { + try { consumer.setMessageListener(this); results.add(message); } - catch (JMSException e) - { + catch (JMSException e) { results.add(e); } } - else - { + else { results.add(message); } latch.countDown(); @@ -97,8 +88,7 @@ public class JmsConsumerResetActiveListenerTest extends BasicOpenWireTest assertEquals("result is first", "First", ((TextMessage) result).getText()); result = results.get(1); assertTrue(result instanceof TextMessage); - assertEquals("result is first", "Second", - ((TextMessage) result).getText()); + assertEquals("result is first", "Second", ((TextMessage) result).getText()); } /** @@ -107,37 +97,28 @@ public class JmsConsumerResetActiveListenerTest extends BasicOpenWireTest * @throws Exception */ @Test - public void testNewConsumerSetListenerFromListener() throws Exception - { - final Session session = connection.createSession(false, - Session.CLIENT_ACKNOWLEDGE); + public void testNewConsumerSetListenerFromListener() throws Exception { + final Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); final Destination dest = session.createQueue(queueName); final MessageConsumer consumer = session.createConsumer(dest); final CountDownLatch latch = new CountDownLatch(2); final AtomicBoolean first = new AtomicBoolean(true); final Vector results = new Vector(); - consumer.setMessageListener(new MessageListener() - { + consumer.setMessageListener(new MessageListener() { - public void onMessage(Message message) - { - if (first.compareAndSet(true, false)) - { - try - { - MessageConsumer anotherConsumer = session - .createConsumer(dest); + public void onMessage(Message message) { + if (first.compareAndSet(true, false)) { + try { + MessageConsumer anotherConsumer = session.createConsumer(dest); anotherConsumer.setMessageListener(this); results.add(message); } - catch (JMSException e) - { + catch (JMSException e) { results.add(e); } } - else - { + else { results.add(message); } latch.countDown(); @@ -159,8 +140,7 @@ public class JmsConsumerResetActiveListenerTest extends BasicOpenWireTest assertEquals("result is first", "First", ((TextMessage) result).getText()); result = results.get(1); assertTrue(result instanceof TextMessage); - assertEquals("result is first", "Second", - ((TextMessage) result).getText()); + assertEquals("result is first", "Second", ((TextMessage) result).getText()); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsCreateConsumerInOnMessageTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsCreateConsumerInOnMessageTest.java index 8bcf1d2224..dc86fa3461 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsCreateConsumerInOnMessageTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsCreateConsumerInOnMessageTest.java @@ -30,8 +30,8 @@ import org.junit.Test; /** * adapted from: org.apache.activemq.JmsCreateConsumerInOnMessageTest */ -public class JmsCreateConsumerInOnMessageTest extends BasicOpenWireTest implements MessageListener -{ +public class JmsCreateConsumerInOnMessageTest extends BasicOpenWireTest implements MessageListener { + private Session publisherSession; private Session consumerSession; private MessageConsumer consumer; @@ -46,15 +46,11 @@ public class JmsCreateConsumerInOnMessageTest extends BasicOpenWireTest implemen * @throws Exception */ @Test - public void testCreateConsumer() throws Exception - { + public void testCreateConsumer() throws Exception { connection.setClientID("connection:" + "JmsCreateConsumerInOnMessageTest"); - publisherSession = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); - consumerSession = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); - topic = (Topic) super.createDestination(consumerSession, - ActiveMQDestination.TOPIC_TYPE); + publisherSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + topic = (Topic) super.createDestination(consumerSession, ActiveMQDestination.TOPIC_TYPE); consumer = consumerSession.createConsumer(topic); consumer.setMessageListener(this); producer = publisherSession.createProducer(topic); @@ -63,11 +59,9 @@ public class JmsCreateConsumerInOnMessageTest extends BasicOpenWireTest implemen producer.send(msg); System.out.println("message sent: " + msg); - synchronized (lock) - { + synchronized (lock) { long timeout = System.currentTimeMillis() + 3000; - while (testConsumer == null && timeout > System.currentTimeMillis()) - { + while (testConsumer == null && timeout > System.currentTimeMillis()) { lock.wait(1000); } } @@ -79,20 +73,16 @@ public class JmsCreateConsumerInOnMessageTest extends BasicOpenWireTest implemen * * @param message */ - public void onMessage(Message message) - { + public void onMessage(Message message) { System.out.println("____________onmessage " + message); - try - { - synchronized (lock) - { + try { + synchronized (lock) { testConsumer = consumerSession.createConsumer(topic); consumerSession.createProducer(topic); lock.notify(); } } - catch (Exception ex) - { + catch (Exception ex) { ex.printStackTrace(); assertTrue(false); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsDurableQueueWildcardSendReceiveTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsDurableQueueWildcardSendReceiveTest.java index 3976704780..a7be9998bb 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsDurableQueueWildcardSendReceiveTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsDurableQueueWildcardSendReceiveTest.java @@ -21,24 +21,21 @@ import javax.jms.DeliveryMode; /** * adapted from: org.apache.activemq.JmsDurableQueueWildcardSendReceiveTest */ -public class JmsDurableQueueWildcardSendReceiveTest extends JmsTopicSendReceiveTest -{ - public void setUp() throws Exception - { +public class JmsDurableQueueWildcardSendReceiveTest extends JmsTopicSendReceiveTest { + + public void setUp() throws Exception { topic = false; deliveryMode = DeliveryMode.PERSISTENT; super.setUp(); } @Override - protected String getConsumerSubject() - { + protected String getConsumerSubject() { return "FOO.>"; } @Override - protected String getProducerSubject() - { + protected String getProducerSubject() { return "FOO.BAR.HUMBUG"; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsDurableTopicSelectorTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsDurableTopicSelectorTest.java index 7c2afd84cf..f8c68f262b 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsDurableTopicSelectorTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsDurableTopicSelectorTest.java @@ -21,12 +21,11 @@ import org.junit.Before; /** * adapted from: org.apache.activemq.JmsDurableTopicSelectorTest */ -public class JmsDurableTopicSelectorTest extends JmsTopicSelectorTest -{ +public class JmsDurableTopicSelectorTest extends JmsTopicSelectorTest { + @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { durable = true; super.setUp(); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsDurableTopicSendReceiveTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsDurableTopicSendReceiveTest.java index 06b9d5228b..0762edd1ef 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsDurableTopicSendReceiveTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsDurableTopicSendReceiveTest.java @@ -32,8 +32,7 @@ import org.junit.Test; /** * adapted from: org.apache.activemq.JmsDurableTopicSendReceiveTest */ -public class JmsDurableTopicSendReceiveTest extends JmsTopicSendReceiveTest -{ +public class JmsDurableTopicSendReceiveTest extends JmsTopicSendReceiveTest { protected Connection connection2; protected Session session2; @@ -50,8 +49,7 @@ public class JmsDurableTopicSendReceiveTest extends JmsTopicSendReceiveTest */ @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { this.durable = true; super.setUp(); } @@ -62,8 +60,7 @@ public class JmsDurableTopicSendReceiveTest extends JmsTopicSendReceiveTest * @throws Exception */ @Test - public void testSendWhileClosed() throws Exception - { + public void testSendWhileClosed() throws Exception { connection2 = factory.createConnection(); connection2.setClientID("test"); connection2.start(); @@ -93,9 +90,7 @@ public class JmsDurableTopicSendReceiveTest extends JmsTopicSendReceiveTest connection2.close(); } - - protected String getName() - { + protected String getName() { return "testSendWhileClosed"; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsDurableTopicTransactionTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsDurableTopicTransactionTest.java index f03e8264fb..53215acd6a 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsDurableTopicTransactionTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsDurableTopicTransactionTest.java @@ -21,14 +21,12 @@ import javax.jms.DeliveryMode; /** * adapted from: org.apache.activemq.JmsDurableTopicTransactionTest */ -public class JmsDurableTopicTransactionTest extends JmsTopicTransactionTest -{ +public class JmsDurableTopicTransactionTest extends JmsTopicTransactionTest { /** * @see JmsTransactionTestSupport#getJmsResourceProvider() */ - protected JmsResourceProvider getJmsResourceProvider() - { + protected JmsResourceProvider getJmsResourceProvider() { JmsResourceProvider provider = new JmsResourceProvider(); provider.setTopic(true); provider.setDeliveryMode(DeliveryMode.PERSISTENT); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsDurableTopicWildcardSendReceiveTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsDurableTopicWildcardSendReceiveTest.java index ae709c6c86..d4229307fe 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsDurableTopicWildcardSendReceiveTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsDurableTopicWildcardSendReceiveTest.java @@ -21,10 +21,9 @@ import javax.jms.DeliveryMode; /** * adapted from: org.apache.activemq.JmsDurableTopicWildcardSendReceiveTest */ -public class JmsDurableTopicWildcardSendReceiveTest extends JmsTopicSendReceiveTest -{ - public void setUp() throws Exception - { +public class JmsDurableTopicWildcardSendReceiveTest extends JmsTopicSendReceiveTest { + + public void setUp() throws Exception { topic = true; durable = true; deliveryMode = DeliveryMode.PERSISTENT; @@ -32,14 +31,12 @@ public class JmsDurableTopicWildcardSendReceiveTest extends JmsTopicSendReceiveT } @Override - protected String getConsumerSubject() - { + protected String getConsumerSubject() { return "FOO.>"; } @Override - protected String getProducerSubject() - { + protected String getProducerSubject() { return "FOO.BAR.HUMBUG"; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsQueueBrowserTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsQueueBrowserTest.java index 7c8cdcd647..382e1f9b59 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsQueueBrowserTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsQueueBrowserTest.java @@ -33,8 +33,8 @@ import org.junit.Test; /** * adapted from: org.apache.activemq.JmsQueueBrowserTest */ -public class JmsQueueBrowserTest extends BasicOpenWireTest -{ +public class JmsQueueBrowserTest extends BasicOpenWireTest { + /** * Tests the queue browser. Browses the messages then the consumer tries to * receive them. The messages should still be in the queue even when it was @@ -43,23 +43,17 @@ public class JmsQueueBrowserTest extends BasicOpenWireTest * @throws Exception */ @Test - public void testReceiveBrowseReceive() throws Exception - { - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + public void testReceiveBrowseReceive() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQQueue destination = (ActiveMQQueue) this.createDestination(session, ActiveMQDestination.QUEUE_TYPE); MessageProducer producer = session.createProducer(destination); MessageConsumer consumer = session.createConsumer(destination); connection.start(); - Message[] outbound = new Message[] - {session.createTextMessage("First Message"), - session.createTextMessage("Second Message"), - session.createTextMessage("Third Message")}; + Message[] outbound = new Message[]{session.createTextMessage("First Message"), session.createTextMessage("Second Message"), session.createTextMessage("Third Message")}; // lets consume any outstanding messages from previous test runs - while (consumer.receive(1000) != null) - { + while (consumer.receive(1000) != null) { } producer.send(outbound[0]); @@ -76,21 +70,17 @@ public class JmsQueueBrowserTest extends BasicOpenWireTest Enumeration enumeration = browser.getEnumeration(); // browse the second - assertTrue("should have received the second message", - enumeration.hasMoreElements()); + assertTrue("should have received the second message", enumeration.hasMoreElements()); assertEquals(outbound[1], enumeration.nextElement()); // browse the third. - assertTrue("Should have received the third message", - enumeration.hasMoreElements()); + assertTrue("Should have received the third message", enumeration.hasMoreElements()); assertEquals(outbound[2], enumeration.nextElement()); // There should be no more. boolean tooMany = false; - while (enumeration.hasMoreElements()) - { - System.out.println("Got extra message: " - + ((TextMessage) enumeration.nextElement()).getText()); + while (enumeration.hasMoreElements()) { + System.out.println("Got extra message: " + ((TextMessage) enumeration.nextElement()).getText()); tooMany = true; } assertFalse(tooMany); @@ -106,64 +96,53 @@ public class JmsQueueBrowserTest extends BasicOpenWireTest } @Test - public void testBatchSendBrowseReceive() throws Exception - { - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + public void testBatchSendBrowseReceive() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQQueue destination = (ActiveMQQueue) this.createDestination(session, ActiveMQDestination.QUEUE_TYPE); MessageProducer producer = session.createProducer(destination); MessageConsumer consumer = session.createConsumer(destination); connection.start(); TextMessage[] outbound = new TextMessage[10]; - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { outbound[i] = session.createTextMessage(i + " Message"); } // lets consume any outstanding messages from previous test runs - while (consumer.receive(1000) != null) - { + while (consumer.receive(1000) != null) { } consumer.close(); - for (int i = 0; i < outbound.length; i++) - { + for (int i = 0; i < outbound.length; i++) { producer.send(outbound[i]); } QueueBrowser browser = session.createBrowser(destination); Enumeration enumeration = browser.getEnumeration(); - for (int i = 0; i < outbound.length; i++) - { + for (int i = 0; i < outbound.length; i++) { assertTrue("should have a", enumeration.hasMoreElements()); assertEquals(outbound[i], enumeration.nextElement()); } browser.close(); - for (int i = 0; i < outbound.length; i++) - { + for (int i = 0; i < outbound.length; i++) { producer.send(outbound[i]); } // verify second batch is visible to browse browser = session.createBrowser(destination); enumeration = browser.getEnumeration(); - for (int j = 0; j < 2; j++) - { - for (int i = 0; i < outbound.length; i++) - { + for (int j = 0; j < 2; j++) { + for (int i = 0; i < outbound.length; i++) { assertTrue("should have a", enumeration.hasMoreElements()); - assertEquals("j=" + j + ", i=" + i, outbound[i].getText(), - ((TextMessage) enumeration.nextElement()).getText()); + assertEquals("j=" + j + ", i=" + i, outbound[i].getText(), ((TextMessage) enumeration.nextElement()).getText()); } } browser.close(); consumer = session.createConsumer(destination); - for (int i = 0; i < outbound.length * 2; i++) - { + for (int i = 0; i < outbound.length * 2; i++) { assertNotNull("Got message: " + i, consumer.receive(2000)); } consumer.close(); @@ -289,10 +268,8 @@ public class JmsQueueBrowserTest extends BasicOpenWireTest */ @Test - public void testBrowseReceive() throws Exception - { - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + public void testBrowseReceive() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQQueue destination = (ActiveMQQueue) this.createDestination(session, ActiveMQDestination.QUEUE_TYPE); connection.start(); @@ -301,15 +278,11 @@ public class JmsQueueBrowserTest extends BasicOpenWireTest MessageConsumer consumer = session.createConsumer(destination); System.out.println("created consumer ... "); // lets consume any outstanding messages from previous test runs - while (consumer.receive(1000) != null) - { + while (consumer.receive(1000) != null) { } consumer.close(); - Message[] outbound = new Message[] - {session.createTextMessage("First Message"), - session.createTextMessage("Second Message"), - session.createTextMessage("Third Message")}; + Message[] outbound = new Message[]{session.createTextMessage("First Message"), session.createTextMessage("Second Message"), session.createTextMessage("Third Message")}; MessageProducer producer = session.createProducer(destination); producer.send(outbound[0]); @@ -323,8 +296,7 @@ public class JmsQueueBrowserTest extends BasicOpenWireTest System.out.println("browsing first"); // browse the first message - assertTrue("should have received the first message", - enumeration.hasMoreElements()); + assertTrue("should have received the first message", enumeration.hasMoreElements()); System.out.println("we have more"); assertEquals(outbound[0], enumeration.nextElement()); @@ -340,10 +312,8 @@ public class JmsQueueBrowserTest extends BasicOpenWireTest } @Test - public void testLargeNumberOfMessages() throws Exception - { - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + public void testLargeNumberOfMessages() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQQueue destination = (ActiveMQQueue) this.createDestination(session, ActiveMQDestination.QUEUE_TYPE); connection.start(); @@ -351,8 +321,7 @@ public class JmsQueueBrowserTest extends BasicOpenWireTest int numberOfMessages = 4096; - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { producer.send(session.createTextMessage("Message: " + i)); } @@ -363,8 +332,7 @@ public class JmsQueueBrowserTest extends BasicOpenWireTest int numberBrowsed = 0; - while (enumeration.hasMoreElements()) - { + while (enumeration.hasMoreElements()) { Message browsed = (Message) enumeration.nextElement(); System.out.println("Browsed Message [{}]" + browsed.getJMSMessageID()); @@ -448,24 +416,18 @@ public class JmsQueueBrowserTest extends BasicOpenWireTest */ @Test - public void testBrowseClose() throws Exception - { - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + public void testBrowseClose() throws Exception { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQQueue destination = (ActiveMQQueue) this.createDestination(session, ActiveMQDestination.QUEUE_TYPE); connection.start(); - TextMessage[] outbound = new TextMessage[] - {session.createTextMessage("First Message"), - session.createTextMessage("Second Message"), - session.createTextMessage("Third Message")}; + TextMessage[] outbound = new TextMessage[]{session.createTextMessage("First Message"), session.createTextMessage("Second Message"), session.createTextMessage("Third Message")}; // create consumer MessageConsumer consumer = session.createConsumer(destination); // lets consume any outstanding messages from previous test runs - while (consumer.receive(1000) != null) - { + while (consumer.receive(1000) != null) { } consumer.close(); @@ -488,17 +450,11 @@ public class JmsQueueBrowserTest extends BasicOpenWireTest consumer = session.createConsumer(destination); // Receive the first message. TextMessage msg = (TextMessage) consumer.receive(1000); - assertEquals( - "Expected " + outbound[0].getText() + " but received " - + msg.getText(), outbound[0], msg); + assertEquals("Expected " + outbound[0].getText() + " but received " + msg.getText(), outbound[0], msg); msg = (TextMessage) consumer.receive(1000); - assertEquals( - "Expected " + outbound[1].getText() + " but received " - + msg.getText(), outbound[1], msg); + assertEquals("Expected " + outbound[1].getText() + " but received " + msg.getText(), outbound[1], msg); msg = (TextMessage) consumer.receive(1000); - assertEquals( - "Expected " + outbound[2].getText() + " but received " - + msg.getText(), outbound[2], msg); + assertEquals("Expected " + outbound[2].getText() + " but received " + msg.getText(), outbound[2], msg); consumer.close(); producer.close(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsQueueRequestReplyTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsQueueRequestReplyTest.java index b24c62b52b..39b55fa753 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsQueueRequestReplyTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsQueueRequestReplyTest.java @@ -21,8 +21,8 @@ import org.junit.Before; /** * adapted from: org.apache.activemq.JMSQueueRedeliverTest */ -public class JmsQueueRequestReplyTest extends JmsTopicRequestReplyTest -{ +public class JmsQueueRequestReplyTest extends JmsTopicRequestReplyTest { + /** * Set up the test with a queue. * @@ -30,8 +30,7 @@ public class JmsQueueRequestReplyTest extends JmsTopicRequestReplyTest */ @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { topic = false; super.setUp(); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsResourceProvider.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsResourceProvider.java index 3f848746c4..ceeb6b97de 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsResourceProvider.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsResourceProvider.java @@ -33,8 +33,8 @@ import org.apache.activemq.command.ActiveMQDestination; /** * adapted from: org.apache.activemq.test.JmsResourceProvider */ -public class JmsResourceProvider -{ +public class JmsResourceProvider { + private boolean transacted; private int ackMode = Session.AUTO_ACKNOWLEDGE; private boolean isTopic; @@ -47,11 +47,9 @@ public class JmsResourceProvider * * @see org.apache.activemq.test.JmsResourceProvider#createConnection(javax.jms.ConnectionFactory) */ - public Connection createConnection(ConnectionFactory cf) throws JMSException - { + public Connection createConnection(ConnectionFactory cf) throws JMSException { Connection connection = cf.createConnection(); - if (getClientID() != null) - { + if (getClientID() != null) { connection.setClientID(getClientID()); } return connection; @@ -60,23 +58,18 @@ public class JmsResourceProvider /** * @see org.apache.activemq.test.JmsResourceProvider#createSession(javax.jms.Connection) */ - public Session createSession(Connection conn) throws JMSException - { + public Session createSession(Connection conn) throws JMSException { System.out.println("createing a session tx ? " + transacted); return conn.createSession(transacted, ackMode); } /** * @see org.apache.activemq.test.JmsResourceProvider#createConsumer(javax.jms.Session, - * javax.jms.Destination) + * javax.jms.Destination) */ - public MessageConsumer createConsumer(Session session, - Destination destination) throws JMSException - { - if (isDurableSubscriber()) - { - return session.createDurableSubscriber((Topic) destination, - durableName); + public MessageConsumer createConsumer(Session session, Destination destination) throws JMSException { + if (isDurableSubscriber()) { + return session.createDurableSubscriber((Topic) destination, durableName); } return session.createConsumer(destination); } @@ -84,13 +77,12 @@ public class JmsResourceProvider /** * Creates a connection for a consumer. * - * @param ssp - * - ServerSessionPool + * @param ssp - ServerSessionPool * @return ConnectionConsumer */ public ConnectionConsumer createConnectionConsumer(Connection connection, - Destination destination, ServerSessionPool ssp) throws JMSException - { + Destination destination, + ServerSessionPool ssp) throws JMSException { return connection.createConnectionConsumer(destination, null, ssp, 1); } @@ -98,11 +90,9 @@ public class JmsResourceProvider * Creates a producer. * * @see org.apache.activemq.test.JmsResourceProvider#createProducer(javax.jms.Session, - * javax.jms.Destination) + * javax.jms.Destination) */ - public MessageProducer createProducer(Session session, - Destination destination) throws JMSException - { + public MessageProducer createProducer(Session session, Destination destination) throws JMSException { MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(deliveryMode); return producer; @@ -112,20 +102,14 @@ public class JmsResourceProvider * Creates a destination, which can either a topic or a queue. * * @see org.apache.activemq.test.JmsResourceProvider#createDestination(javax.jms.Session, - * java.lang.String) + * java.lang.String) */ - public Destination createDestination(Session session, - JmsTransactionTestSupport support) throws JMSException - { - if (isTopic) - { - return (Destination) support.createDestination(session, - ActiveMQDestination.TOPIC_TYPE); + public Destination createDestination(Session session, JmsTransactionTestSupport support) throws JMSException { + if (isTopic) { + return (Destination) support.createDestination(session, ActiveMQDestination.TOPIC_TYPE); } - else - { - return (Destination) support.createDestination(session, - ActiveMQDestination.QUEUE_TYPE); + else { + return (Destination) support.createDestination(session, ActiveMQDestination.QUEUE_TYPE); } } @@ -134,8 +118,7 @@ public class JmsResourceProvider * * @return isDurableSubscriber */ - public boolean isDurableSubscriber() - { + public boolean isDurableSubscriber() { return isTopic && durableName != null; } @@ -144,19 +127,16 @@ public class JmsResourceProvider * * @return Returns the ackMode. */ - public int getAckMode() - { + public int getAckMode() { return ackMode; } /** * Sets the acnknowledgement mode. * - * @param ackMode - * The ackMode to set. + * @param ackMode The ackMode to set. */ - public void setAckMode(int ackMode) - { + public void setAckMode(int ackMode) { this.ackMode = ackMode; } @@ -166,17 +146,14 @@ public class JmsResourceProvider * * @return Returns the isTopic. */ - public boolean isTopic() - { + public boolean isTopic() { return isTopic; } /** - * @param isTopic - * The isTopic to set. + * @param isTopic The isTopic to set. */ - public void setTopic(boolean isTopic) - { + public void setTopic(boolean isTopic) { this.isTopic = isTopic; } @@ -185,8 +162,7 @@ public class JmsResourceProvider * * @return Returns the transacted. */ - public boolean isTransacted() - { + public boolean isTransacted() { return transacted; } @@ -195,11 +171,9 @@ public class JmsResourceProvider * * @param transacted */ - public void setTransacted(boolean transacted) - { + public void setTransacted(boolean transacted) { this.transacted = transacted; - if (transacted) - { + if (transacted) { setAckMode(Session.SESSION_TRANSACTED); } } @@ -209,8 +183,7 @@ public class JmsResourceProvider * * @return deliveryMode */ - public int getDeliveryMode() - { + public int getDeliveryMode() { return deliveryMode; } @@ -219,8 +192,7 @@ public class JmsResourceProvider * * @param deliveryMode */ - public void setDeliveryMode(int deliveryMode) - { + public void setDeliveryMode(int deliveryMode) { this.deliveryMode = deliveryMode; } @@ -229,8 +201,7 @@ public class JmsResourceProvider * * @return clientID */ - public String getClientID() - { + public String getClientID() { return clientID; } @@ -239,8 +210,7 @@ public class JmsResourceProvider * * @param clientID */ - public void setClientID(String clientID) - { + public void setClientID(String clientID) { this.clientID = clientID; } @@ -249,8 +219,7 @@ public class JmsResourceProvider * * @return durableName */ - public String getDurableName() - { + public String getDurableName() { return durableName; } @@ -259,8 +228,7 @@ public class JmsResourceProvider * * @param durableName */ - public void setDurableName(String durableName) - { + public void setDurableName(String durableName) { this.durableName = durableName; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsSendReceiveTestSupport.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsSendReceiveTestSupport.java index b471415f95..45d7c8edab 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsSendReceiveTestSupport.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsSendReceiveTestSupport.java @@ -40,8 +40,8 @@ import org.junit.Test; /** * adapted from: org.apache.activemq.JmsSendReceiveTestSupport */ -public abstract class JmsSendReceiveTestSupport extends BasicOpenWireTest implements MessageListener -{ +public abstract class JmsSendReceiveTestSupport extends BasicOpenWireTest implements MessageListener { + protected int messageCount = 100; protected String[] data; protected Session session; @@ -50,8 +50,7 @@ public abstract class JmsSendReceiveTestSupport extends BasicOpenWireTest implem protected MessageProducer producer; protected Destination consumerDestination; protected Destination producerDestination; - protected List messages = Collections - .synchronizedList(new ArrayList()); + protected List messages = Collections.synchronizedList(new ArrayList()); protected boolean topic = true; protected boolean durable; protected int deliveryMode = DeliveryMode.PERSISTENT; @@ -61,16 +60,13 @@ public abstract class JmsSendReceiveTestSupport extends BasicOpenWireTest implem @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); String temp = System.getProperty("messageCount"); - if (temp != null) - { + if (temp != null) { int i = Integer.parseInt(temp); - if (i > 0) - { + if (i > 0) { messageCount = i; } } @@ -78,8 +74,7 @@ public abstract class JmsSendReceiveTestSupport extends BasicOpenWireTest implem System.out.println("Message count for test case is: " + messageCount); data = new String[messageCount]; - for (int i = 0; i < messageCount; i++) - { + for (int i = 0; i < messageCount; i++) { data[i] = "Text for message: " + i + " at " + new Date(); } } @@ -90,11 +85,9 @@ public abstract class JmsSendReceiveTestSupport extends BasicOpenWireTest implem * @throws Exception */ @Test - public void testSendReceive() throws Exception - { + public void testSendReceive() throws Exception { messages.clear(); - for (int i = 0; i < data.length; i++) - { + for (int i = 0; i < data.length; i++) { Message message = session.createTextMessage(data[i]); message.setStringProperty("stringProperty", data[i]); message.setIntProperty("intProperty", i); @@ -110,36 +103,29 @@ public abstract class JmsSendReceiveTestSupport extends BasicOpenWireTest implem /** * Tests if the messages received are valid. * - * @param receivedMessages - * - list of received messages. + * @param receivedMessages - list of received messages. * @throws JMSException */ - protected void assertMessagesReceivedAreValid(List receivedMessages) throws JMSException - { + protected void assertMessagesReceivedAreValid(List receivedMessages) throws JMSException { List copyOfMessages = Arrays.asList(receivedMessages.toArray()); int counter = 0; - if (data.length != copyOfMessages.size()) - { - for (Iterator iter = copyOfMessages.iterator(); iter.hasNext();) - { + if (data.length != copyOfMessages.size()) { + for (Iterator iter = copyOfMessages.iterator(); iter.hasNext(); ) { TextMessage message = (TextMessage) iter.next(); System.out.println("<== " + counter++ + " = " + message.getText()); } } - assertEquals("Not enough messages received", data.length, - receivedMessages.size()); + assertEquals("Not enough messages received", data.length, receivedMessages.size()); - for (int i = 0; i < data.length; i++) - { + for (int i = 0; i < data.length; i++) { TextMessage received = (TextMessage) receivedMessages.get(i); String text = received.getText(); String stringProperty = received.getStringProperty("stringProperty"); int intProperty = received.getIntProperty("intProperty"); - if (verbose) - { + if (verbose) { System.out.println("Received Text: " + text); } @@ -152,22 +138,17 @@ public abstract class JmsSendReceiveTestSupport extends BasicOpenWireTest implem /** * Waits for messages to be delivered. */ - protected void waitForMessagesToBeDelivered() - { + protected void waitForMessagesToBeDelivered() { long maxWaitTime = 60000; long waitTime = maxWaitTime; long start = (maxWaitTime <= 0) ? 0 : System.currentTimeMillis(); - synchronized (lock) - { - while (messages.size() < data.length && waitTime >= 0) - { - try - { + synchronized (lock) { + while (messages.size() < data.length && waitTime >= 0) { + try { lock.wait(200); } - catch (InterruptedException e) - { + catch (InterruptedException e) { e.printStackTrace(); } @@ -181,8 +162,7 @@ public abstract class JmsSendReceiveTestSupport extends BasicOpenWireTest implem * * @throws JMSException */ - protected void assertMessagesAreReceived() throws JMSException - { + protected void assertMessagesAreReceived() throws JMSException { waitForMessagesToBeDelivered(); assertMessagesReceivedAreValid(messages); } @@ -192,8 +172,7 @@ public abstract class JmsSendReceiveTestSupport extends BasicOpenWireTest implem * * @throws Exception */ - protected void messageSent() throws Exception - { + protected void messageSent() throws Exception { } @@ -202,45 +181,36 @@ public abstract class JmsSendReceiveTestSupport extends BasicOpenWireTest implem * * @see javax.jms.MessageListener#onMessage(javax.jms.Message) */ - public synchronized void onMessage(Message message) - { + public synchronized void onMessage(Message message) { consumeMessage(message, messages); } /** * Consumes messages. * - * @param message - * - message to be consumed. - * @param messageList - * -list of consumed messages. + * @param message - message to be consumed. + * @param messageList -list of consumed messages. */ - protected void consumeMessage(Message message, List messageList) - { - if (verbose) - { + protected void consumeMessage(Message message, List messageList) { + if (verbose) { System.out.println("Received message: " + message); } messageList.add(message); - if (messageList.size() >= data.length) - { - synchronized (lock) - { + if (messageList.size() >= data.length) { + synchronized (lock) { lock.notifyAll(); } } } - protected Message createMessage(int index) throws JMSException - { + protected Message createMessage(int index) throws JMSException { Message message = session.createTextMessage(data[index]); return message; } - protected void configureMessage(Message message) throws JMSException - { + protected void configureMessage(Message message) throws JMSException { } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicRedeliverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicRedeliverTest.java index d7c2a5bac2..a758be727e 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicRedeliverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicRedeliverTest.java @@ -34,8 +34,8 @@ import org.junit.Test; /** * adapted from: org.apache.activemq.JmsTopicRedeliverTest */ -public class JmsTopicRedeliverTest extends BasicOpenWireTest -{ +public class JmsTopicRedeliverTest extends BasicOpenWireTest { + protected Session session; protected Session consumeSession; protected MessageConsumer consumer; @@ -49,23 +49,19 @@ public class JmsTopicRedeliverTest extends BasicOpenWireTest @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - initRedeliveryDelay = ((ActiveMQConnection) connection) - .getRedeliveryPolicy().getInitialRedeliveryDelay(); + initRedeliveryDelay = ((ActiveMQConnection) connection).getRedeliveryPolicy().getInitialRedeliveryDelay(); - if (durable) - { + if (durable) { connection.setClientID(getClass().getName()); } System.out.println("Created connection: " + connection); session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - consumeSession = connection.createSession(false, - Session.CLIENT_ACKNOWLEDGE); + consumeSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); System.out.println("Created session: " + session); System.out.println("Created consumeSession: " + consumeSession); @@ -74,27 +70,17 @@ public class JmsTopicRedeliverTest extends BasicOpenWireTest System.out.println("Created producer: " + producer); - if (topic) - { - consumerDestination = this.createDestination(session, - ActiveMQDestination.TOPIC_TYPE); - producerDestination = this.createDestination(session, - ActiveMQDestination.TOPIC_TYPE); + if (topic) { + consumerDestination = this.createDestination(session, ActiveMQDestination.TOPIC_TYPE); + producerDestination = this.createDestination(session, ActiveMQDestination.TOPIC_TYPE); } - else - { - consumerDestination = this.createDestination(session, - ActiveMQDestination.QUEUE_TYPE); - producerDestination = this.createDestination(session, - ActiveMQDestination.QUEUE_TYPE); + else { + consumerDestination = this.createDestination(session, ActiveMQDestination.QUEUE_TYPE); + producerDestination = this.createDestination(session, ActiveMQDestination.QUEUE_TYPE); } - System.out.println("Created consumer destination: " - + consumerDestination + " of type: " - + consumerDestination.getClass()); - System.out.println("Created producer destination: " - + producerDestination + " of type: " - + producerDestination.getClass()); + System.out.println("Created consumer destination: " + consumerDestination + " of type: " + consumerDestination.getClass()); + System.out.println("Created producer destination: " + producerDestination + " of type: " + producerDestination.getClass()); consumer = createConsumer(getName()); connection.start(); @@ -107,15 +93,12 @@ public class JmsTopicRedeliverTest extends BasicOpenWireTest * @throws Exception */ @Test - public void testRecover() throws Exception - { + public void testRecover() throws Exception { String text = "TEST"; Message sendMessage = session.createTextMessage(text); - if (verbose) - { - System.out.println("About to send a message: " + sendMessage + " with text: " - + text); + if (verbose) { + System.out.println("About to send a message: " + sendMessage + " with text: " + text); } producer.send(producerDestination, sendMessage); @@ -141,13 +124,10 @@ public class JmsTopicRedeliverTest extends BasicOpenWireTest assertNull(consumer.receiveNoWait()); } - protected MessageConsumer createConsumer(String durableName) throws JMSException - { - if (durable) - { + protected MessageConsumer createConsumer(String durableName) throws JMSException { + if (durable) { System.out.println("Creating durable consumer " + durableName); - return consumeSession.createDurableSubscriber( - (Topic) consumerDestination, durableName); + return consumeSession.createDurableSubscriber((Topic) consumerDestination, durableName); } return consumeSession.createConsumer(consumerDestination); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicRequestReplyTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicRequestReplyTest.java index ae4814f231..8005a3456a 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicRequestReplyTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicRequestReplyTest.java @@ -40,8 +40,8 @@ import org.junit.Test; /** * adapted from: org.apache.activemq.JmsTopicRequestReplyTest */ -public class JmsTopicRequestReplyTest extends BasicOpenWireTest implements MessageListener -{ +public class JmsTopicRequestReplyTest extends BasicOpenWireTest implements MessageListener { + protected boolean useAsyncConsume; private Connection serverConnection; private Connection clientConnection; @@ -53,13 +53,11 @@ public class JmsTopicRequestReplyTest extends BasicOpenWireTest implements Messa private String clientSideClientID; @Test - public void testSendAndReceive() throws Exception - { + public void testSendAndReceive() throws Exception { clientConnection = createConnection(); clientConnection.setClientID("ClientConnection:" + name.getMethodName()); - Session session = clientConnection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + Session session = clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); clientConnection.start(); @@ -73,13 +71,10 @@ public class JmsTopicRequestReplyTest extends BasicOpenWireTest implements Messa // replyDestination); // assertEquals("clientID from the temporary destination must be the // same", clientSideClientID, value); - System.out - .println("Both the clientID and destination clientID match properly: " - + clientSideClientID); + System.out.println("Both the clientID and destination clientID match properly: " + clientSideClientID); /* build queues */ - MessageProducer requestProducer = session - .createProducer(requestDestination); + MessageProducer requestProducer = session.createProducer(requestDestination); MessageConsumer replyConsumer = session.createConsumer(replyDestination); /* build requestmessage */ @@ -92,28 +87,23 @@ public class JmsTopicRequestReplyTest extends BasicOpenWireTest implements Messa Message msg = replyConsumer.receive(5000); - if (msg instanceof TextMessage) - { + if (msg instanceof TextMessage) { TextMessage replyMessage = (TextMessage) msg; System.out.println("Received reply."); System.out.println(replyMessage.toString()); - assertEquals("Wrong message content", "Hello: Olivier", - replyMessage.getText()); + assertEquals("Wrong message content", "Hello: Olivier", replyMessage.getText()); } - else - { + else { fail("Should have received a reply by now"); } replyConsumer.close(); deleteTemporaryDestination(replyDestination); - assertEquals("Should not have had any failures: " + failures, 0, - failures.size()); + assertEquals("Should not have had any failures: " + failures, 0, failures.size()); } @Test - public void testSendAndReceiveWithDynamicallyCreatedProducer() throws Exception - { + public void testSendAndReceiveWithDynamicallyCreatedProducer() throws Exception { dynamicallyCreateProducer = true; testSendAndReceive(); } @@ -121,10 +111,8 @@ public class JmsTopicRequestReplyTest extends BasicOpenWireTest implements Messa /** * Use the asynchronous subscription mechanism */ - public void onMessage(Message message) - { - try - { + public void onMessage(Message message) { + try { TextMessage requestMessage = (TextMessage) message; System.out.println("Received request."); @@ -139,26 +127,22 @@ public class JmsTopicRequestReplyTest extends BasicOpenWireTest implements Messa // assertEquals("clientID from the temporary destination must be the // same", clientSideClientID, value); - TextMessage replyMessage = serverSession.createTextMessage("Hello: " - + requestMessage.getText()); + TextMessage replyMessage = serverSession.createTextMessage("Hello: " + requestMessage.getText()); replyMessage.setJMSCorrelationID(requestMessage.getJMSMessageID()); - if (dynamicallyCreateProducer) - { + if (dynamicallyCreateProducer) { replyProducer = serverSession.createProducer(replyDestination); replyProducer.send(replyMessage); } - else - { + else { replyProducer.send(replyDestination, replyMessage); } System.out.println("Sent reply."); System.out.println(replyMessage.toString()); } - catch (JMSException e) - { + catch (JMSException e) { onException(e); } } @@ -166,54 +150,42 @@ public class JmsTopicRequestReplyTest extends BasicOpenWireTest implements Messa /** * Use the synchronous subscription mechanism */ - protected void syncConsumeLoop(MessageConsumer requestConsumer) - { - try - { + protected void syncConsumeLoop(MessageConsumer requestConsumer) { + try { Message message = requestConsumer.receive(5000); - if (message != null) - { + if (message != null) { onMessage(message); } - else - { + else { System.err.println("No message received"); } } - catch (JMSException e) - { + catch (JMSException e) { onException(e); } } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); serverConnection = createConnection(); serverConnection.setClientID("serverConnection:" + name.getMethodName()); - serverSession = serverConnection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + serverSession = serverConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); replyProducer = serverSession.createProducer(null); requestDestination = createDestination(serverSession); /* build queues */ - final MessageConsumer requestConsumer = serverSession - .createConsumer(requestDestination); - if (useAsyncConsume) - { + final MessageConsumer requestConsumer = serverSession.createConsumer(requestDestination); + if (useAsyncConsume) { requestConsumer.setMessageListener(this); } - else - { - Thread thread = new Thread(new Runnable() - { - public void run() - { + else { + Thread thread = new Thread(new Runnable() { + public void run() { syncConsumeLoop(requestConsumer); } }); @@ -224,8 +196,7 @@ public class JmsTopicRequestReplyTest extends BasicOpenWireTest implements Messa @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { serverConnection.close(); clientConnection.stop(); @@ -234,39 +205,31 @@ public class JmsTopicRequestReplyTest extends BasicOpenWireTest implements Messa super.tearDown(); } - protected void onException(JMSException e) - { + protected void onException(JMSException e) { System.out.println("Caught: " + e); e.printStackTrace(); failures.add(e); } - protected Destination createDestination(Session session) throws JMSException - { - if (topic) - { + protected Destination createDestination(Session session) throws JMSException { + if (topic) { return this.createDestination(session, ActiveMQDestination.TOPIC_TYPE); } return this.createDestination(session, ActiveMQDestination.QUEUE_TYPE); } - protected Destination createTemporaryDestination(Session session) throws JMSException - { - if (topic) - { + protected Destination createTemporaryDestination(Session session) throws JMSException { + if (topic) { return session.createTemporaryTopic(); } return session.createTemporaryQueue(); } - protected void deleteTemporaryDestination(Destination dest) throws JMSException - { - if (topic) - { + protected void deleteTemporaryDestination(Destination dest) throws JMSException { + if (topic) { ((TemporaryTopic) dest).delete(); } - else - { + else { ((TemporaryQueue) dest).delete(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicSelectorTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicSelectorTest.java index bf082bad48..1d42383422 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicSelectorTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicSelectorTest.java @@ -34,8 +34,8 @@ import org.junit.Test; /** * adapted from: org.apache.activemq.JmsTopicSelectorTest */ -public class JmsTopicSelectorTest extends BasicOpenWireTest -{ +public class JmsTopicSelectorTest extends BasicOpenWireTest { + protected Session session; protected MessageConsumer consumer; protected MessageProducer producer; @@ -47,12 +47,10 @@ public class JmsTopicSelectorTest extends BasicOpenWireTest @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - if (durable) - { + if (durable) { connection.setClientID(getClass().getName()); } @@ -62,45 +60,33 @@ public class JmsTopicSelectorTest extends BasicOpenWireTest System.out.println("Created session: " + session); - if (topic) - { + if (topic) { consumerDestination = this.createDestination(session, ActiveMQDestination.TOPIC_TYPE); producerDestination = this.createDestination(session, ActiveMQDestination.TOPIC_TYPE); } - else - { + else { consumerDestination = this.createDestination(session, ActiveMQDestination.QUEUE_TYPE); producerDestination = this.createDestination(session, ActiveMQDestination.QUEUE_TYPE); } - System.out.println("Created consumer destination: " + consumerDestination - + " of type: " + consumerDestination.getClass()); - System.out.println("Created producer destination: " + producerDestination - + " of type: " + producerDestination.getClass()); + System.out.println("Created consumer destination: " + consumerDestination + " of type: " + consumerDestination.getClass()); + System.out.println("Created producer destination: " + producerDestination + " of type: " + producerDestination.getClass()); producer = session.createProducer(producerDestination); producer.setDeliveryMode(deliveryMode); - System.out.println("Created producer: " - + producer - + " delivery mode = " - + (deliveryMode == DeliveryMode.PERSISTENT ? "PERSISTENT" - : "NON_PERSISTENT")); + System.out.println("Created producer: " + producer + " delivery mode = " + (deliveryMode == DeliveryMode.PERSISTENT ? "PERSISTENT" : "NON_PERSISTENT")); connection.start(); } - protected MessageConsumer createConsumer(String selector) throws JMSException - { - if (durable) - { + protected MessageConsumer createConsumer(String selector) throws JMSException { + if (durable) { System.out.println("Creating durable consumer"); - return session.createDurableSubscriber((Topic) consumerDestination, - getName(), selector, false); + return session.createDurableSubscriber((Topic) consumerDestination, getName(), selector, false); } return session.createConsumer(consumerDestination, selector); } - public void sendMessages() throws Exception - { + public void sendMessages() throws Exception { TextMessage message = session.createTextMessage("1"); message.setIntProperty("id", 1); message.setJMSType("a"); @@ -142,11 +128,9 @@ public class JmsTopicSelectorTest extends BasicOpenWireTest producer.send(message); } - public void consumeMessages(int remaining) throws Exception - { + public void consumeMessages(int remaining) throws Exception { consumer = createConsumer(null); - for (int i = 0; i < remaining; i++) - { + for (int i = 0; i < remaining; i++) { consumer.receive(1000); } consumer.close(); @@ -154,17 +138,14 @@ public class JmsTopicSelectorTest extends BasicOpenWireTest } @Test - public void testEmptyPropertySelector() throws Exception - { + public void testEmptyPropertySelector() throws Exception { int remaining = 5; Message message = null; consumer = createConsumer(""); sendMessages(); - while (true) - { + while (true) { message = consumer.receive(1000); - if (message == null) - { + if (message == null) { break; } @@ -176,22 +157,18 @@ public class JmsTopicSelectorTest extends BasicOpenWireTest } @Test - public void testPropertySelector() throws Exception - { + public void testPropertySelector() throws Exception { int remaining = 5; Message message = null; consumer = createConsumer("stringProperty = 'a' and longProperty = 1 and booleanProperty = true"); sendMessages(); - while (true) - { + while (true) { message = consumer.receive(1000); - if (message == null) - { + if (message == null) { break; } String text = ((TextMessage) message).getText(); - if (!text.equals("1") && !text.equals("3")) - { + if (!text.equals("1") && !text.equals("3")) { fail("unexpected message: " + text); } remaining--; @@ -203,22 +180,18 @@ public class JmsTopicSelectorTest extends BasicOpenWireTest } @Test - public void testJMSPropertySelector() throws Exception - { + public void testJMSPropertySelector() throws Exception { int remaining = 5; Message message = null; consumer = createConsumer("JMSType = 'a' and stringProperty = 'a'"); sendMessages(); - while (true) - { + while (true) { message = consumer.receive(1000); - if (message == null) - { + if (message == null) { break; } String text = ((TextMessage) message).getText(); - if (!text.equals("1") && !text.equals("2") && !text.equals("3")) - { + if (!text.equals("1") && !text.equals("2") && !text.equals("3")) { fail("unexpected message: " + text); } remaining--; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicSendReceiveTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicSendReceiveTest.java index eff8403e4d..16d2ebe863 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicSendReceiveTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicSendReceiveTest.java @@ -28,16 +28,14 @@ import org.junit.Before; /** * adapted from: JmsTopicSendReceiveTest */ -public class JmsTopicSendReceiveTest extends JmsSendReceiveTestSupport -{ +public class JmsTopicSendReceiveTest extends JmsSendReceiveTestSupport { + @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - if (durable) - { + if (durable) { connection.setClientID(getClass().getName()); } @@ -50,33 +48,19 @@ public class JmsTopicSendReceiveTest extends JmsSendReceiveTestSupport producer = session.createProducer(null); producer.setDeliveryMode(deliveryMode); - System.out.println("Created producer: " - + producer - + " delivery mode = " - + (deliveryMode == DeliveryMode.PERSISTENT ? "PERSISTENT" - : "NON_PERSISTENT")); + System.out.println("Created producer: " + producer + " delivery mode = " + (deliveryMode == DeliveryMode.PERSISTENT ? "PERSISTENT" : "NON_PERSISTENT")); - if (topic) - { - consumerDestination = createDestination(session, - ActiveMQDestination.TOPIC_TYPE, getConsumerSubject()); - producerDestination = createDestination(session, - ActiveMQDestination.TOPIC_TYPE, getProducerSubject()); + if (topic) { + consumerDestination = createDestination(session, ActiveMQDestination.TOPIC_TYPE, getConsumerSubject()); + producerDestination = createDestination(session, ActiveMQDestination.TOPIC_TYPE, getProducerSubject()); } - else - { - consumerDestination = createDestination(session, - ActiveMQDestination.QUEUE_TYPE, getConsumerSubject()); - producerDestination = createDestination(session, - ActiveMQDestination.QUEUE_TYPE, getConsumerSubject()); + else { + consumerDestination = createDestination(session, ActiveMQDestination.QUEUE_TYPE, getConsumerSubject()); + producerDestination = createDestination(session, ActiveMQDestination.QUEUE_TYPE, getConsumerSubject()); } - System.out.println("Created consumer destination: " - + consumerDestination + " of type: " - + consumerDestination.getClass()); - System.out.println("Created producer destination: " - + producerDestination + " of type: " - + producerDestination.getClass()); + System.out.println("Created consumer destination: " + consumerDestination + " of type: " + consumerDestination.getClass()); + System.out.println("Created producer destination: " + producerDestination + " of type: " + producerDestination.getClass()); consumer = createConsumer(); consumer.setMessageListener(this); connection.start(); @@ -84,35 +68,27 @@ public class JmsTopicSendReceiveTest extends JmsSendReceiveTestSupport // log.info("Created connection: " + connection); } - protected String getConsumerSubject() - { + protected String getConsumerSubject() { return null; } - protected String getProducerSubject() - { + protected String getProducerSubject() { return null; } - protected MessageConsumer createConsumer() throws JMSException - { - if (durable) - { + protected MessageConsumer createConsumer() throws JMSException { + if (durable) { System.out.println("Creating durable consumer"); - return session.createDurableSubscriber((Topic) consumerDestination, - getName()); + return session.createDurableSubscriber((Topic) consumerDestination, getName()); } return session.createConsumer(consumerDestination); } - protected Session createConsumerSession() throws JMSException - { - if (useSeparateSession) - { + protected Session createConsumerSession() throws JMSException { + if (useSeparateSession) { return connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } - else - { + else { return session; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicSendReceiveWithTwoConnectionsTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicSendReceiveWithTwoConnectionsTest.java index a8af79081f..467eab62e1 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicSendReceiveWithTwoConnectionsTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicSendReceiveWithTwoConnectionsTest.java @@ -29,8 +29,7 @@ import org.junit.Before; /** * adapted from: JmsTopicSendReceiveWithTwoConnectionsTest */ -public class JmsTopicSendReceiveWithTwoConnectionsTest extends JmsSendReceiveTestSupport -{ +public class JmsTopicSendReceiveWithTwoConnectionsTest extends JmsSendReceiveTestSupport { protected Connection sendConnection; protected Connection receiveConnection; @@ -38,8 +37,7 @@ public class JmsTopicSendReceiveWithTwoConnectionsTest extends JmsSendReceiveTes @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); sendConnection = createSendConnection(); @@ -53,54 +51,42 @@ public class JmsTopicSendReceiveWithTwoConnectionsTest extends JmsSendReceiveTes producer = session.createProducer(null); producer.setDeliveryMode(deliveryMode); - if (topic) - { - consumerDestination = createDestination(session, - ActiveMQDestination.TOPIC_TYPE); - producerDestination = createDestination(session, - ActiveMQDestination.TOPIC_TYPE); + if (topic) { + consumerDestination = createDestination(session, ActiveMQDestination.TOPIC_TYPE); + producerDestination = createDestination(session, ActiveMQDestination.TOPIC_TYPE); } - else - { - consumerDestination = createDestination(session, - ActiveMQDestination.QUEUE_TYPE); - producerDestination = createDestination(session, - ActiveMQDestination.QUEUE_TYPE); + else { + consumerDestination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); + producerDestination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); } consumer = createConsumer(receiveSession, consumerDestination); consumer.setMessageListener(this); } - protected Session createReceiveSession(Connection receiveConnection) throws Exception - { + protected Session createReceiveSession(Connection receiveConnection) throws Exception { return receiveConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); } - protected Session createSendSession(Connection sendConnection) throws Exception - { + protected Session createSendSession(Connection sendConnection) throws Exception { return sendConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); } - protected Connection createReceiveConnection() throws Exception - { + protected Connection createReceiveConnection() throws Exception { return createConnection(); } - protected Connection createSendConnection() throws Exception - { + protected Connection createSendConnection() throws Exception { return createConnection(); } - protected MessageConsumer createConsumer(Session session, Destination dest) throws JMSException - { + protected MessageConsumer createConsumer(Session session, Destination dest) throws JMSException { return session.createConsumer(dest); } @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { session.close(); receiveSession.close(); sendConnection.close(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicTransactionTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicTransactionTest.java index e1cf82133e..b48223d778 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicTransactionTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicTransactionTest.java @@ -19,14 +19,13 @@ package org.apache.activemq.artemis.tests.integration.openwire.amq; /** * adapted from: org.apache.activemq.JmsTopicTransactionTest */ -public class JmsTopicTransactionTest extends JmsTransactionTestSupport -{ +public class JmsTopicTransactionTest extends JmsTransactionTestSupport { + /** * @see org.apache.activemq.JmsTransactionTestSupport#getJmsResourceProvider() */ @Override - protected JmsResourceProvider getJmsResourceProvider() - { + protected JmsResourceProvider getJmsResourceProvider() { JmsResourceProvider p = new JmsResourceProvider(); p.setTopic(true); p.setDurableName("testsub"); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicWildcardSendReceiveTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicWildcardSendReceiveTest.java index f5505d9464..92081710bc 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicWildcardSendReceiveTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTopicWildcardSendReceiveTest.java @@ -32,8 +32,7 @@ import org.junit.Test; /** * adapted from: org.apache.activemq.JmsTopicWildcardSendReceiveTest */ -public class JmsTopicWildcardSendReceiveTest extends JmsTopicSendReceiveTest -{ +public class JmsTopicWildcardSendReceiveTest extends JmsTopicSendReceiveTest { private String destination1String = "TEST.ONE.ONE"; private String destination2String = "TEST.ONE.ONE.ONE"; @@ -42,82 +41,66 @@ public class JmsTopicWildcardSendReceiveTest extends JmsTopicSendReceiveTest @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { topic = true; durable = false; deliveryMode = DeliveryMode.NON_PERSISTENT; super.setUp(); } - protected String getConsumerSubject() - { + protected String getConsumerSubject() { return "FOO.>"; } - protected String getProducerSubject() - { + protected String getProducerSubject() { return "FOO.BAR.HUMBUG"; } @Test - public void testReceiveWildcardTopicEndAsterisk() throws Exception - { + public void testReceiveWildcardTopicEndAsterisk() throws Exception { connection.start(); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination1 = (ActiveMQDestination) session - .createTopic(destination1String); - ActiveMQDestination destination3 = (ActiveMQDestination) session - .createTopic(destination3String); + ActiveMQDestination destination1 = (ActiveMQDestination) session.createTopic(destination1String); + ActiveMQDestination destination3 = (ActiveMQDestination) session.createTopic(destination3String); Message m = null; MessageConsumer consumer = null; String text = null; - ActiveMQDestination destination6 = (ActiveMQDestination) session - .createTopic("TEST.ONE.*"); + ActiveMQDestination destination6 = (ActiveMQDestination) session.createTopic("TEST.ONE.*"); consumer = session.createConsumer(destination6); sendMessage(session, destination1, destination1String); sendMessage(session, destination3, destination3String); m = consumer.receive(5000); assertNotNull(m); text = ((TextMessage) m).getText(); - if (!(text.equals(destination1String) || text.equals(destination3String))) - { + if (!(text.equals(destination1String) || text.equals(destination3String))) { fail("unexpected message:" + text); } m = consumer.receive(5000); assertNotNull(m); text = ((TextMessage) m).getText(); - if (!(text.equals(destination1String) || text.equals(destination3String))) - { + if (!(text.equals(destination1String) || text.equals(destination3String))) { fail("unexpected message:" + text); } assertNull(consumer.receiveNoWait()); } @Test - public void testReceiveWildcardTopicEndGreaterThan() throws Exception - { + public void testReceiveWildcardTopicEndGreaterThan() throws Exception { connection.start(); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination1 = (ActiveMQDestination) session - .createTopic(destination1String); - ActiveMQDestination destination2 = (ActiveMQDestination) session - .createTopic(destination2String); - ActiveMQDestination destination3 = (ActiveMQDestination) session - .createTopic(destination3String); + ActiveMQDestination destination1 = (ActiveMQDestination) session.createTopic(destination1String); + ActiveMQDestination destination2 = (ActiveMQDestination) session.createTopic(destination2String); + ActiveMQDestination destination3 = (ActiveMQDestination) session.createTopic(destination3String); Message m = null; MessageConsumer consumer = null; String text = null; - ActiveMQDestination destination7 = (ActiveMQDestination) session - .createTopic("TEST.ONE.>"); + ActiveMQDestination destination7 = (ActiveMQDestination) session.createTopic("TEST.ONE.>"); consumer = session.createConsumer(destination7); sendMessage(session, destination1, destination1String); sendMessage(session, destination2, destination2String); @@ -125,61 +108,48 @@ public class JmsTopicWildcardSendReceiveTest extends JmsTopicSendReceiveTest m = consumer.receive(1000); assertNotNull(m); text = ((TextMessage) m).getText(); - if (!(text.equals(destination1String) || text.equals(destination2String) || text - .equals(destination3String))) - { + if (!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { fail("unexpected message:" + text); } m = consumer.receive(1000); assertNotNull(m); - if (!(text.equals(destination1String) || text.equals(destination2String) || text - .equals(destination3String))) - { + if (!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { fail("unexpected message:" + text); } m = consumer.receive(1000); assertNotNull(m); - if (!(text.equals(destination1String) || text.equals(destination2String) || text - .equals(destination3String))) - { + if (!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { fail("unexpected message:" + text); } assertNull(consumer.receiveNoWait()); } @Test - public void testReceiveWildcardTopicMidAsterisk() throws Exception - { + public void testReceiveWildcardTopicMidAsterisk() throws Exception { connection.start(); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination1 = (ActiveMQDestination) session - .createTopic(destination1String); - ActiveMQDestination destination4 = (ActiveMQDestination) session - .createTopic(destination4String); + ActiveMQDestination destination1 = (ActiveMQDestination) session.createTopic(destination1String); + ActiveMQDestination destination4 = (ActiveMQDestination) session.createTopic(destination4String); Message m = null; MessageConsumer consumer = null; String text = null; - ActiveMQDestination destination8 = (ActiveMQDestination) session - .createTopic("TEST.*.ONE"); + ActiveMQDestination destination8 = (ActiveMQDestination) session.createTopic("TEST.*.ONE"); consumer = session.createConsumer(destination8); sendMessage(session, destination1, destination1String); sendMessage(session, destination4, destination4String); m = consumer.receive(1000); assertNotNull(m); text = ((TextMessage) m).getText(); - if (!(text.equals(destination1String) || text.equals(destination4String))) - { + if (!(text.equals(destination1String) || text.equals(destination4String))) { fail("unexpected message:" + text); } m = consumer.receive(1000); assertNotNull(m); text = ((TextMessage) m).getText(); - if (!(text.equals(destination1String) || text.equals(destination4String))) - { + if (!(text.equals(destination1String) || text.equals(destination4String))) { fail("unexpected message:" + text); } assertNull(consumer.receiveNoWait()); @@ -187,16 +157,12 @@ public class JmsTopicWildcardSendReceiveTest extends JmsTopicSendReceiveTest } @Test - public void testReceiveWildcardTopicMatchDoubleWildcard() throws Exception - { + public void testReceiveWildcardTopicMatchDoubleWildcard() throws Exception { connection.start(); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination1 = (ActiveMQDestination) session - .createTopic("a.*.>.>"); - ActiveMQDestination destination2 = (ActiveMQDestination) session - .createTopic("a.b"); + ActiveMQDestination destination1 = (ActiveMQDestination) session.createTopic("a.*.>.>"); + ActiveMQDestination destination2 = (ActiveMQDestination) session.createTopic("a.b"); Message m = null; MessageConsumer consumer = null; @@ -208,8 +174,7 @@ public class JmsTopicWildcardSendReceiveTest extends JmsTopicSendReceiveTest m = consumer.receive(1000); assertNotNull(m); text = ((TextMessage) m).getText(); - if (!(text.equals(destination1String) || text.equals(destination3String))) - { + if (!(text.equals(destination1String) || text.equals(destination3String))) { fail("unexpected message:" + text); } @@ -217,16 +182,12 @@ public class JmsTopicWildcardSendReceiveTest extends JmsTopicSendReceiveTest } @Test - public void testReceiveWildcardTopicMatchSinglePastTheEndWildcard() throws Exception - { + public void testReceiveWildcardTopicMatchSinglePastTheEndWildcard() throws Exception { connection.start(); - Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination1 = (ActiveMQDestination) session - .createTopic("a.>"); - ActiveMQDestination destination2 = (ActiveMQDestination) session - .createTopic("a"); + ActiveMQDestination destination1 = (ActiveMQDestination) session.createTopic("a.>"); + ActiveMQDestination destination2 = (ActiveMQDestination) session.createTopic("a"); Message m = null; MessageConsumer consumer = null; @@ -238,16 +199,14 @@ public class JmsTopicWildcardSendReceiveTest extends JmsTopicSendReceiveTest m = consumer.receive(1000); assertNotNull(m); text = ((TextMessage) m).getText(); - if (!(text.equals(destination1String) || text.equals(destination3String))) - { + if (!(text.equals(destination1String) || text.equals(destination3String))) { fail("unexpected message:" + text); } assertNull(consumer.receiveNoWait()); } - private void sendMessage(Session session, Destination destination, String text) throws JMSException - { + private void sendMessage(Session session, Destination destination, String text) throws JMSException { MessageProducer producer = session.createProducer(destination); producer.send(session.createTextMessage(text)); producer.close(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTransactionTestSupport.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTransactionTestSupport.java index 53d3254e96..173fe0bf00 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTransactionTestSupport.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/JmsTransactionTestSupport.java @@ -38,8 +38,8 @@ import org.junit.Test; /** * adapted from: org.apache.activemq.JmsTransactionTestSupport */ -public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implements MessageListener -{ +public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implements MessageListener { + private static final int MESSAGE_COUNT = 5; private static final String MESSAGE_TEXT = "message"; @@ -59,8 +59,7 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); resourceProvider = getJmsResourceProvider(); @@ -70,17 +69,14 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem reconnect(); } - protected void reconnect() throws Exception - { + protected void reconnect() throws Exception { - if (connection != null) - { + if (connection != null) { // Close the prev connection. connection.close(); } session = null; - connection = (ActiveMQConnection) resourceProvider - .createConnection(this.factory); + connection = (ActiveMQConnection) resourceProvider.createConnection(this.factory); reconnectSession(); connection.start(); } @@ -90,10 +86,8 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem * * @throws JMSException */ - protected void reconnectSession() throws JMSException - { - if (session != null) - { + protected void reconnectSession() throws JMSException { + if (session != null) { session.close(); } @@ -103,23 +97,19 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem consumer = resourceProvider.createConsumer(session, destination); } - protected void setSessionTransacted() - { + protected void setSessionTransacted() { resourceProvider.setTransacted(true); } - protected void beginTx() throws Exception - { + protected void beginTx() throws Exception { // no-op for local tx } - protected void commitTx() throws Exception - { + protected void commitTx() throws Exception { session.commit(); } - protected void rollbackTx() throws Exception - { + protected void rollbackTx() throws Exception { session.rollback(); } @@ -129,31 +119,24 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem * @throws Exception */ @Test - public void testSendReceiveTransactedBatches() throws Exception - { + public void testSendReceiveTransactedBatches() throws Exception { TextMessage message = session.createTextMessage("Batch Message"); - for (int j = 0; j < batchCount; j++) - { - System.out.println("Producing bacth " + j + " of " + batchSize - + " messages"); + for (int j = 0; j < batchCount; j++) { + System.out.println("Producing bacth " + j + " of " + batchSize + " messages"); beginTx(); - for (int i = 0; i < batchSize; i++) - { + for (int i = 0; i < batchSize; i++) { producer.send(message); } messageSent(); commitTx(); - System.out.println("Consuming bacth " + j + " of " + batchSize - + " messages"); + System.out.println("Consuming bacth " + j + " of " + batchSize + " messages"); beginTx(); - for (int i = 0; i < batchSize; i++) - { + for (int i = 0; i < batchSize; i++) { message = (TextMessage) consumer.receive(1000 * 5); - assertNotNull("Received only " + i + " messages in batch " + j, - message); + assertNotNull("Received only " + i + " messages in batch " + j, message); assertEquals("Batch Message", message.getText()); } @@ -162,8 +145,7 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem } } - protected void messageSent() throws Exception - { + protected void messageSent() throws Exception { } /** @@ -173,11 +155,8 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem * @throws Exception */ @Test - public void testSendRollback() throws Exception - { - Message[] outbound = new Message[] - {session.createTextMessage("First Message"), - session.createTextMessage("Second Message")}; + public void testSendRollback() throws Exception { + Message[] outbound = new Message[]{session.createTextMessage("First Message"), session.createTextMessage("Second Message")}; // sends a message beginTx(); @@ -200,13 +179,13 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem System.out.println("About to consume message 1"); Message message = consumer.receive(1000); messages.add(message); - System.out.println("Received: " + ((TextMessage)message).getText()); + System.out.println("Received: " + ((TextMessage) message).getText()); // receives the second message System.out.println("About to consume message 2"); message = consumer.receive(4000); messages.add(message); - System.out.println("Received: " + ((TextMessage)message).getText()); + System.out.println("Received: " + ((TextMessage) message).getText()); // validates that the rollbacked was not consumed commitTx(); @@ -221,10 +200,8 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem * @throws Exception */ @Test - public void testAckMessageInTx() throws Exception - { - Message[] outbound = new Message[] - {session.createTextMessage("First Message")}; + public void testAckMessageInTx() throws Exception { + Message[] outbound = new Message[]{session.createTextMessage("First Message")}; // sends a message beginTx(); @@ -257,11 +234,8 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem * @throws Exception */ @Test - public void testSendSessionClose() throws Exception - { - Message[] outbound = new Message[] - {session.createTextMessage("First Message"), - session.createTextMessage("Second Message")}; + public void testSendSessionClose() throws Exception { + Message[] outbound = new Message[]{session.createTextMessage("First Message"), session.createTextMessage("Second Message")}; // sends a message beginTx(); @@ -307,11 +281,8 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem * @throws Exception */ @Test - public void testSendSessionAndConnectionClose() throws Exception - { - Message[] outbound = new Message[] - {session.createTextMessage("First Message"), - session.createTextMessage("Second Message")}; + public void testSendSessionAndConnectionClose() throws Exception { + Message[] outbound = new Message[]{session.createTextMessage("First Message"), session.createTextMessage("Second Message")}; // sends a message beginTx(); @@ -359,16 +330,12 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem * @throws Exception */ @Test - public void testReceiveRollback() throws Exception - { - Message[] outbound = new Message[] - {session.createTextMessage("First Message"), - session.createTextMessage("Second Message")}; + public void testReceiveRollback() throws Exception { + Message[] outbound = new Message[]{session.createTextMessage("First Message"), session.createTextMessage("Second Message")}; // lets consume any outstanding messages from prev test runs beginTx(); - while (consumer.receive(1000) != null) - { + while (consumer.receive(1000) != null) { } commitTx(); @@ -415,16 +382,12 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem * @throws Exception */ @Test - public void testReceiveTwoThenRollback() throws Exception - { - Message[] outbound = new Message[] - {session.createTextMessage("First Message"), - session.createTextMessage("Second Message")}; + public void testReceiveTwoThenRollback() throws Exception { + Message[] outbound = new Message[]{session.createTextMessage("First Message"), session.createTextMessage("Second Message")}; // lets consume any outstanding messages from prev test runs beginTx(); - while (consumer.receive(1000) != null) - { + while (consumer.receive(1000) != null) { } commitTx(); @@ -460,8 +423,7 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem messages.add(message); assertEquals(outbound[0], message); message = (TextMessage) consumer.receive(5000); - assertNotNull("Should have re-received the second message again!", - message); + assertNotNull("Should have re-received the second message again!", message); System.out.println("received2: " + message.getText()); messages.add(message); assertEquals(outbound[1], message); @@ -482,18 +444,12 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem * @throws Exception */ @Test - public void testSendReceiveWithPrefetchOne() throws Exception - { + public void testSendReceiveWithPrefetchOne() throws Exception { setPrefetchToOne(); - Message[] outbound = new Message[] - {session.createTextMessage("First Message"), - session.createTextMessage("Second Message"), - session.createTextMessage("Third Message"), - session.createTextMessage("Fourth Message")}; + Message[] outbound = new Message[]{session.createTextMessage("First Message"), session.createTextMessage("Second Message"), session.createTextMessage("Third Message"), session.createTextMessage("Fourth Message")}; beginTx(); - for (int i = 0; i < outbound.length; i++) - { + for (int i = 0; i < outbound.length; i++) { // sends a message producer.send(outbound[i]); } @@ -501,8 +457,7 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem // receives the first message beginTx(); - for (int i = 0; i < outbound.length; i++) - { + for (int i = 0; i < outbound.length; i++) { System.out.println("About to consume message 1"); Message message = consumer.receive(1000); assertNotNull(message); @@ -520,10 +475,8 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem * @throws Exception */ @Test - public void testReceiveTwoThenRollbackManyTimes() throws Exception - { - for (int i = 0; i < 5; i++) - { + public void testReceiveTwoThenRollbackManyTimes() throws Exception { + for (int i = 0; i < 5; i++) { testReceiveTwoThenRollback(); } } @@ -535,8 +488,7 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem * @throws Exception */ @Test - public void testSendRollbackWithPrefetchOfOne() throws Exception - { + public void testSendRollbackWithPrefetchOfOne() throws Exception { setPrefetchToOne(); testSendRollback(); } @@ -548,8 +500,7 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem * @throws Exception */ @Test - public void testReceiveRollbackWithPrefetchOfOne() throws Exception - { + public void testReceiveRollbackWithPrefetchOfOne() throws Exception { setPrefetchToOne(); testReceiveRollback(); } @@ -558,20 +509,15 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem * Tests if the messages can still be received if the consumer is closed * (session is not closed). * - * @throws Exception - * see http://jira.codehaus.org/browse/AMQ-143 + * @throws Exception see http://jira.codehaus.org/browse/AMQ-143 */ @Test - public void testCloseConsumerBeforeCommit() throws Exception - { - TextMessage[] outbound = new TextMessage[] - {session.createTextMessage("First Message"), - session.createTextMessage("Second Message")}; + public void testCloseConsumerBeforeCommit() throws Exception { + TextMessage[] outbound = new TextMessage[]{session.createTextMessage("First Message"), session.createTextMessage("Second Message")}; // lets consume any outstanding messages from prev test runs beginTx(); - while (consumer.receiveNoWait() != null) - { + while (consumer.receiveNoWait() != null) { } commitTx(); @@ -604,8 +550,7 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem } @Test - public void testChangeMutableObjectInObjectMessageThenRollback() throws Exception - { + public void testChangeMutableObjectInObjectMessageThenRollback() throws Exception { ArrayList list = new ArrayList(); list.add("First"); Message outbound = session.createObjectMessage(list); @@ -622,13 +567,11 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem List body = assertReceivedObjectMessageWithListBody(message); // now lets try mutate it - try - { + try { message.setStringProperty("foo", "def"); fail("Cannot change properties of the object!"); } - catch (JMSException e) - { + catch (JMSException e) { System.out.println("Caught expected exception: " + e); e.printStackTrace(); } @@ -639,20 +582,16 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem beginTx(); message = consumer.receive(5000); List secondBody = assertReceivedObjectMessageWithListBody(message); - assertNotSame("Second call should return a different body", secondBody, - body); + assertNotSame("Second call should return a different body", secondBody, body); commitTx(); } @SuppressWarnings("unchecked") - protected List assertReceivedObjectMessageWithListBody( - Message message) throws JMSException - { + protected List assertReceivedObjectMessageWithListBody(Message message) throws JMSException { assertNotNull("Should have received a message!", message); assertEquals("foo header", "abc", message.getStringProperty("foo")); - assertTrue("Should be an object message but was: " + message, - message instanceof ObjectMessage); + assertTrue("Should be an object message but was: " + message, message instanceof ObjectMessage); ObjectMessage objectMessage = (ObjectMessage) message; List body = (List) objectMessage.getObject(); System.out.println("Received body: " + body); @@ -665,8 +604,7 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem /** * Sets the prefeftch policy to one. */ - protected void setPrefetchToOne() - { + protected void setPrefetchToOne() { ActiveMQPrefetchPolicy prefetchPolicy = getPrefetchPolicy(); prefetchPolicy.setQueuePrefetch(1); prefetchPolicy.setTopicPrefetch(1); @@ -674,18 +612,15 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem prefetchPolicy.setOptimizeDurableTopicPrefetch(1); } - protected ActiveMQPrefetchPolicy getPrefetchPolicy() - { + protected ActiveMQPrefetchPolicy getPrefetchPolicy() { return ((ActiveMQConnection) connection).getPrefetchPolicy(); } // This test won't work with xa tx so no beginTx() has been added. @Test - public void testMessageListener() throws Exception - { + public void testMessageListener() throws Exception { // send messages - for (int i = 0; i < MESSAGE_COUNT; i++) - { + for (int i = 0; i < MESSAGE_COUNT; i++) { producer.send(session.createTextMessage(MESSAGE_TEXT + i)); } commitTx(); @@ -703,54 +638,41 @@ public abstract class JmsTransactionTestSupport extends BasicOpenWireTest implem } @Override - public void onMessage(Message message) - { - if (!resendPhase) - { + public void onMessage(Message message) { + if (!resendPhase) { unackMessages.add(message); - if (unackMessages.size() == MESSAGE_COUNT) - { - try - { + if (unackMessages.size() == MESSAGE_COUNT) { + try { rollbackTx(); resendPhase = true; } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } } - else - { + else { ackMessages.add(message); - if (ackMessages.size() == MESSAGE_COUNT) - { - try - { + if (ackMessages.size() == MESSAGE_COUNT) { + try { commitTx(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } } } - private void waitReceiveUnack() throws Exception - { - for (int i = 0; i < 100 && !resendPhase; i++) - { + private void waitReceiveUnack() throws Exception { + for (int i = 0; i < 100 && !resendPhase; i++) { Thread.sleep(100); } assertTrue(resendPhase); } - private void waitReceiveAck() throws Exception - { - for (int i = 0; i < 100 && ackMessages.size() < MESSAGE_COUNT; i++) - { + private void waitReceiveAck() throws Exception { + for (int i = 0; i < 100 && ackMessages.size() < MESSAGE_COUNT; i++) { Thread.sleep(100); } assertFalse(ackMessages.size() < MESSAGE_COUNT); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/MessageListenerRedeliveryTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/MessageListenerRedeliveryTest.java index fe64870dfe..37a544f04a 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/MessageListenerRedeliveryTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/MessageListenerRedeliveryTest.java @@ -47,14 +47,13 @@ import org.junit.Test; /** * adapted from: org.apache.activemq.MessageListenerRedeliveryTest */ -public class MessageListenerRedeliveryTest extends BasicOpenWireTest -{ +public class MessageListenerRedeliveryTest extends BasicOpenWireTest { + private Connection redeliverConnection; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); redeliverConnection = createRetryConnection(); } @@ -64,18 +63,15 @@ public class MessageListenerRedeliveryTest extends BasicOpenWireTest */ @Override @After - public void tearDown() throws Exception - { - if (redeliverConnection != null) - { + public void tearDown() throws Exception { + if (redeliverConnection != null) { redeliverConnection.close(); redeliverConnection = null; } super.tearDown(); } - protected RedeliveryPolicy getRedeliveryPolicy() - { + protected RedeliveryPolicy getRedeliveryPolicy() { RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy(); redeliveryPolicy.setInitialRedeliveryDelay(0); redeliveryPolicy.setRedeliveryDelay(1000); @@ -85,56 +81,47 @@ public class MessageListenerRedeliveryTest extends BasicOpenWireTest return redeliveryPolicy; } - protected Connection createRetryConnection() throws Exception - { + protected Connection createRetryConnection() throws Exception { ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(urlString); factory.setRedeliveryPolicy(getRedeliveryPolicy()); return factory.createConnection(); } - private class TestMessageListener implements MessageListener - { + private class TestMessageListener implements MessageListener { + public int counter; private final Session session; - public TestMessageListener(Session session) - { + public TestMessageListener(Session session) { this.session = session; } @Override - public void onMessage(Message message) - { - try - { + public void onMessage(Message message) { + try { System.out.println("Message Received: " + message); counter++; - if (counter <= 4) - { + if (counter <= 4) { System.out.println("Message Rollback."); session.rollback(); } - else - { + else { System.out.println("Message Commit."); message.acknowledge(); session.commit(); } } - catch (JMSException e) - { + catch (JMSException e) { System.out.println("Error when rolling back transaction"); } } } @Test - public void testQueueRollbackConsumerListener() throws Exception - { + public void testQueueRollbackConsumerListener() throws Exception { redeliverConnection.start(); - Session session = redeliverConnection.createSession(true, - Session.CLIENT_ACKNOWLEDGE); + Session session = redeliverConnection.createSession(true, Session.CLIENT_ACKNOWLEDGE); String qname = "queue-testQueueRollbackConsumerListener"; Queue queue = session.createQueue(qname); this.makeSureCoreQueueExist(qname); @@ -151,34 +138,28 @@ public class MessageListenerRedeliveryTest extends BasicOpenWireTest TestMessageListener listener = new TestMessageListener(session); consumer.setMessageListener(listener); - try - { + try { Thread.sleep(500); } - catch (InterruptedException e) - { + catch (InterruptedException e) { } // first try.. should get 2 since there is no delay on the // first redeliver.. assertEquals(2, listener.counter); - try - { + try { Thread.sleep(1000); } - catch (InterruptedException e) - { + catch (InterruptedException e) { } // 2nd redeliver (redelivery after 1 sec) assertEquals(3, listener.counter); - try - { + try { Thread.sleep(2000); } - catch (InterruptedException e) - { + catch (InterruptedException e) { } // 3rd redeliver (redelivery after 2 seconds) - it should give up after // that @@ -188,22 +169,18 @@ public class MessageListenerRedeliveryTest extends BasicOpenWireTest producer.send(createTextMessage(session)); session.commit(); - try - { + try { Thread.sleep(500); } - catch (InterruptedException e) - { + catch (InterruptedException e) { } // it should be committed, so no redelivery assertEquals(5, listener.counter); - try - { + try { Thread.sleep(1500); } - catch (InterruptedException e) - { + catch (InterruptedException e) { } // no redelivery, counter should still be 4 assertEquals(5, listener.counter); @@ -212,12 +189,10 @@ public class MessageListenerRedeliveryTest extends BasicOpenWireTest } @Test - public void testQueueRollbackSessionListener() throws Exception - { + public void testQueueRollbackSessionListener() throws Exception { redeliverConnection.start(); - Session session = redeliverConnection.createSession(true, - Session.CLIENT_ACKNOWLEDGE); + Session session = redeliverConnection.createSession(true, Session.CLIENT_ACKNOWLEDGE); String qname = "queue-testQueueRollbackSessionListener"; Queue queue = session.createQueue(qname); this.makeSureCoreQueueExist(qname); @@ -234,34 +209,28 @@ public class MessageListenerRedeliveryTest extends BasicOpenWireTest TestMessageListener listener = new TestMessageListener(session); consumer.setMessageListener(listener); - try - { + try { Thread.sleep(500); } - catch (InterruptedException e) - { + catch (InterruptedException e) { } // first try assertEquals(2, listener.counter); - try - { + try { Thread.sleep(1000); } - catch (InterruptedException e) - { + catch (InterruptedException e) { } // second try (redelivery after 1 sec) assertEquals(3, listener.counter); - try - { + try { Thread.sleep(2000); } - catch (InterruptedException e) - { + catch (InterruptedException e) { } // third try (redelivery after 2 seconds) - it should give up after that @@ -271,23 +240,19 @@ public class MessageListenerRedeliveryTest extends BasicOpenWireTest producer.send(createTextMessage(session)); session.commit(); - try - { + try { Thread.sleep(500); } - catch (InterruptedException e) - { + catch (InterruptedException e) { // ignore } // it should be committed, so no redelivery assertEquals(5, listener.counter); - try - { + try { Thread.sleep(1500); } - catch (InterruptedException e) - { + catch (InterruptedException e) { // ignore } // no redelivery, counter should still be 4 @@ -297,12 +262,10 @@ public class MessageListenerRedeliveryTest extends BasicOpenWireTest } @Test - public void testQueueSessionListenerExceptionRetry() throws Exception - { + public void testQueueSessionListenerExceptionRetry() throws Exception { redeliverConnection.start(); - Session session = redeliverConnection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + Session session = redeliverConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); String qname = "queue-testQueueSessionListenerExceptionRetry"; Queue queue = session.createQueue(qname); this.makeSureCoreQueueExist(qname); @@ -318,23 +281,18 @@ public class MessageListenerRedeliveryTest extends BasicOpenWireTest final AtomicInteger count = new AtomicInteger(0); final int maxDeliveries = getRedeliveryPolicy().getMaximumRedeliveries(); final ArrayList received = new ArrayList(); - consumer.setMessageListener(new MessageListener() - { + consumer.setMessageListener(new MessageListener() { @Override - public void onMessage(Message message) - { + public void onMessage(Message message) { System.out.println("Message Received: " + message); - try - { + try { received.add(((TextMessage) message).getText()); } - catch (JMSException e) - { + catch (JMSException e) { e.printStackTrace(); fail(e.toString()); } - if (count.incrementAndGet() < maxDeliveries) - { + if (count.incrementAndGet() < maxDeliveries) { throw new RuntimeException(getName() + " force a redelivery"); } // new blood @@ -343,27 +301,22 @@ public class MessageListenerRedeliveryTest extends BasicOpenWireTest } }); - assertTrue("got message before retry expiry", - gotMessage.await(20, TimeUnit.SECONDS)); + assertTrue("got message before retry expiry", gotMessage.await(20, TimeUnit.SECONDS)); - for (int i = 0; i < maxDeliveries; i++) - { + for (int i = 0; i < maxDeliveries; i++) { assertEquals("got first redelivered: " + i, "1", received.get(i)); } - for (int i = maxDeliveries; i < maxDeliveries * 2; i++) - { + for (int i = maxDeliveries; i < maxDeliveries * 2; i++) { assertEquals("got first redelivered: " + i, "2", received.get(i)); } session.close(); } @Test - public void testQueueSessionListenerExceptionDlq() throws Exception - { + public void testQueueSessionListenerExceptionDlq() throws Exception { redeliverConnection.start(); - Session session = redeliverConnection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + Session session = redeliverConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); String qname = "queue-testQueueSessionListenerExceptionDlq"; Queue queue = session.createQueue(qname); this.makeSureCoreQueueExist(qname); @@ -376,11 +329,9 @@ public class MessageListenerRedeliveryTest extends BasicOpenWireTest this.makeSureCoreQueueExist("ActiveMQ.DLQ"); MessageConsumer dlqConsumer = session.createConsumer(dlqDestination); final CountDownLatch gotDlqMessage = new CountDownLatch(1); - dlqConsumer.setMessageListener(new MessageListener() - { + dlqConsumer.setMessageListener(new MessageListener() { @Override - public void onMessage(Message message) - { + public void onMessage(Message message) { System.out.println("DLQ Message Received: " + message); dlqMessage[0] = message; gotDlqMessage.countDown(); @@ -393,19 +344,16 @@ public class MessageListenerRedeliveryTest extends BasicOpenWireTest System.out.println("max redlivery: " + maxDeliveries); final CountDownLatch gotMessage = new CountDownLatch(maxDeliveries); - consumer.setMessageListener(new MessageListener() - { + consumer.setMessageListener(new MessageListener() { @Override - public void onMessage(Message message) - { + public void onMessage(Message message) { System.out.println("Message Received: " + message); gotMessage.countDown(); throw new RuntimeException(getName() + " force a redelivery"); } }); - assertTrue("got message before retry expiry", - gotMessage.await(20, TimeUnit.SECONDS)); + assertTrue("got message before retry expiry", gotMessage.await(20, TimeUnit.SECONDS)); // check DLQ assertTrue("got dlq message", gotDlqMessage.await(20, TimeUnit.SECONDS)); @@ -413,45 +361,37 @@ public class MessageListenerRedeliveryTest extends BasicOpenWireTest // check DLQ message cause is captured message = dlqMessage[0]; assertNotNull("dlq message captured", message); - String cause = message - .getStringProperty(ActiveMQMessage.DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY); + String cause = message.getStringProperty(ActiveMQMessage.DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY); System.out.println("DLQ'd message cause reported as: " + cause); - assertTrue("cause 'cause' exception is remembered", - cause.contains("RuntimeException")); + assertTrue("cause 'cause' exception is remembered", cause.contains("RuntimeException")); assertTrue("is correct exception", cause.contains(getName())); assertTrue("cause exception is remembered", cause.contains("Throwable")); - assertTrue("cause policy is remembered", - cause.contains("RedeliveryPolicy")); + assertTrue("cause policy is remembered", cause.contains("RedeliveryPolicy")); session.close(); } - private TextMessage createTextMessage(Session session, String text) throws JMSException - { + private TextMessage createTextMessage(Session session, String text) throws JMSException { return session.createTextMessage(text); } - private TextMessage createTextMessage(Session session) throws JMSException - { + private TextMessage createTextMessage(Session session) throws JMSException { return session.createTextMessage("Hello"); } - private MessageProducer createProducer(Session session, Destination queue) throws JMSException - { + private MessageProducer createProducer(Session session, Destination queue) throws JMSException { MessageProducer producer = session.createProducer(queue); producer.setDeliveryMode(getDeliveryMode()); return producer; } - protected int getDeliveryMode() - { + protected int getDeliveryMode() { return DeliveryMode.PERSISTENT; } - protected String getName() - { + protected String getName() { return "testQueueSessionListenerExceptionDlq"; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/ProducerFlowControlSendFailTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/ProducerFlowControlSendFailTest.java index c9042d1159..0eeb3e85c8 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/ProducerFlowControlSendFailTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/ProducerFlowControlSendFailTest.java @@ -41,50 +41,41 @@ import org.junit.Test; /** * adapted from: org.apache.activemq.ProducerFlowControlSendFailTest */ -public class ProducerFlowControlSendFailTest extends ProducerFlowControlTest -{ +public class ProducerFlowControlSendFailTest extends ProducerFlowControlTest { @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); } @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { super.tearDown(); } @Override - protected void extraServerConfig(Configuration serverConfig) - { + protected void extraServerConfig(Configuration serverConfig) { String match = "jms.queue.#"; Map asMap = serverConfig.getAddressesSettings(); - asMap.get(match) - .setMaxSizeBytes(1) - .setAddressFullMessagePolicy(AddressFullMessagePolicy.FAIL); + asMap.get(match).setMaxSizeBytes(1).setAddressFullMessagePolicy(AddressFullMessagePolicy.FAIL); } @Override - public void test2ndPublisherWithStandardConnectionThatIsBlocked() throws Exception - { + public void test2ndPublisherWithStandardConnectionThatIsBlocked() throws Exception { // with sendFailIfNoSpace set, there is no blocking of the connection } @Override - public void testAsyncPublisherRecoverAfterBlock() throws Exception - { + public void testAsyncPublisherRecoverAfterBlock() throws Exception { // sendFail means no flowControllwindow as there is no producer ack, just // an exception } @Override @Test - public void testPublisherRecoverAfterBlock() throws Exception - { + public void testPublisherRecoverAfterBlock() throws Exception { ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) getConnectionFactory(); // with sendFail, there must be no flowControllwindow // sendFail is an alternative flow control mechanism that does not block @@ -92,24 +83,18 @@ public class ProducerFlowControlSendFailTest extends ProducerFlowControlTest this.flowControlConnection = (ActiveMQConnection) factory.createConnection(); this.flowControlConnection.start(); - final Session session = this.flowControlConnection.createSession(false, - Session.CLIENT_ACKNOWLEDGE); + final Session session = this.flowControlConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); final MessageProducer producer = session.createProducer(queueA); final AtomicBoolean keepGoing = new AtomicBoolean(true); - Thread thread = new Thread("Filler") - { + Thread thread = new Thread("Filler") { @Override - public void run() - { - while (keepGoing.get()) - { - try - { + public void run() { + while (keepGoing.get()) { + try { producer.send(session.createTextMessage("Test message")); - if (gotResourceException.get()) - { + if (gotResourceException.get()) { System.out.println("got exception"); // do not flood the broker with requests when full as we // are sending async and they @@ -117,8 +102,7 @@ public class ProducerFlowControlSendFailTest extends ProducerFlowControlTest Thread.sleep(200); } } - catch (Exception e) - { + catch (Exception e) { // with async send, there will be no exceptions e.printStackTrace(); } @@ -132,11 +116,9 @@ public class ProducerFlowControlSendFailTest extends ProducerFlowControlTest // can receive 10 MessageConsumer consumer = session.createConsumer(queueA); TextMessage msg; - for (int idx = 0; idx < 10; ++idx) - { + for (int idx = 0; idx < 10; ++idx) { msg = (TextMessage) consumer.receive(1000); - if (msg != null) - { + if (msg != null) { msg.acknowledge(); } } @@ -145,35 +127,27 @@ public class ProducerFlowControlSendFailTest extends ProducerFlowControlTest } @Test - public void testPublisherRecoverAfterBlockWithSyncSend() throws Exception - { + public void testPublisherRecoverAfterBlockWithSyncSend() throws Exception { ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) getConnectionFactory(); factory.setExceptionListener(null); factory.setUseAsyncSend(false); this.flowControlConnection = (ActiveMQConnection) factory.createConnection(); this.flowControlConnection.start(); - final Session session = this.flowControlConnection.createSession(false, - Session.CLIENT_ACKNOWLEDGE); + final Session session = this.flowControlConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); final MessageProducer producer = session.createProducer(queueA); final AtomicBoolean keepGoing = new AtomicBoolean(true); final AtomicInteger exceptionCount = new AtomicInteger(0); - Thread thread = new Thread("Filler") - { + Thread thread = new Thread("Filler") { @Override - public void run() - { - while (keepGoing.get()) - { - try - { + public void run() { + while (keepGoing.get()) { + try { producer.send(session.createTextMessage("Test message")); } - catch (JMSException arg0) - { - if (arg0 instanceof ResourceAllocationException) - { + catch (JMSException arg0) { + if (arg0 instanceof ResourceAllocationException) { gotResourceException.set(true); exceptionCount.incrementAndGet(); } @@ -188,11 +162,9 @@ public class ProducerFlowControlSendFailTest extends ProducerFlowControlTest // can receive 10 MessageConsumer consumer = session.createConsumer(queueA); TextMessage msg; - for (int idx = 0; idx < 10; ++idx) - { + for (int idx = 0; idx < 10; ++idx) { msg = (TextMessage) consumer.receive(1000); - if (msg != null) - { + if (msg != null) { msg.acknowledge(); } } @@ -200,14 +172,10 @@ public class ProducerFlowControlSendFailTest extends ProducerFlowControlTest keepGoing.set(false); } - protected ConnectionFactory getConnectionFactory() throws Exception - { - factory.setExceptionListener(new ExceptionListener() - { - public void onException(JMSException arg0) - { - if (arg0 instanceof ResourceAllocationException) - { + protected ConnectionFactory getConnectionFactory() throws Exception { + factory.setExceptionListener(new ExceptionListener() { + public void onException(JMSException arg0) { + if (arg0 instanceof ResourceAllocationException) { gotResourceException.set(true); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/ProducerFlowControlTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/ProducerFlowControlTest.java index e658a1d5e7..a195097881 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/ProducerFlowControlTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/ProducerFlowControlTest.java @@ -42,8 +42,8 @@ import org.junit.Test; /** * adapted from: org.apache.activemq.ProducerFlowControlTest */ -public class ProducerFlowControlTest extends BasicOpenWireTest -{ +public class ProducerFlowControlTest extends BasicOpenWireTest { + ActiveMQQueue queueA = new ActiveMQQueue("QUEUE.A"); ActiveMQQueue queueB = new ActiveMQQueue("QUEUE.B"); protected ActiveMQConnection flowControlConnection; @@ -52,8 +52,7 @@ public class ProducerFlowControlTest extends BasicOpenWireTest private Thread asyncThread = null; @Test - public void test2ndPublisherWithProducerWindowSendConnectionThatIsBlocked() throws Exception - { + public void test2ndPublisherWithProducerWindowSendConnectionThatIsBlocked() throws Exception { factory.setProducerWindowSize(1024 * 64); flowControlConnection = (ActiveMQConnection) factory.createConnection(); flowControlConnection.start(); @@ -85,8 +84,7 @@ public class ProducerFlowControlTest extends BasicOpenWireTest } @Test - public void testPublisherRecoverAfterBlock() throws Exception - { + public void testPublisherRecoverAfterBlock() throws Exception { flowControlConnection = (ActiveMQConnection) factory.createConnection(); flowControlConnection.start(); @@ -96,22 +94,17 @@ public class ProducerFlowControlTest extends BasicOpenWireTest final AtomicBoolean done = new AtomicBoolean(true); final AtomicBoolean keepGoing = new AtomicBoolean(true); - Thread thread = new Thread("Filler") - { + Thread thread = new Thread("Filler") { int i; @Override - public void run() - { - while (keepGoing.get()) - { + public void run() { + while (keepGoing.get()) { done.set(false); - try - { + try { producer.send(session.createTextMessage("Test message " + ++i)); } - catch (JMSException e) - { + catch (JMSException e) { break; } } @@ -124,11 +117,9 @@ public class ProducerFlowControlTest extends BasicOpenWireTest // (done == false) MessageConsumer consumer = session.createConsumer(queueA); TextMessage msg; - for (int idx = 0; idx < 5; ++idx) - { + for (int idx = 0; idx < 5; ++idx) { msg = (TextMessage) consumer.receive(1000); - System.out.println("received: " + idx + ", msg: " - + msg.getJMSMessageID()); + System.out.println("received: " + idx + ", msg: " + msg.getJMSMessageID()); msg.acknowledge(); } Thread.sleep(1000); @@ -139,36 +130,29 @@ public class ProducerFlowControlTest extends BasicOpenWireTest } @Test - public void testAsyncPublisherRecoverAfterBlock() throws Exception - { + public void testAsyncPublisherRecoverAfterBlock() throws Exception { factory.setProducerWindowSize(1024 * 5); factory.setUseAsyncSend(true); flowControlConnection = (ActiveMQConnection) factory.createConnection(); flowControlConnection.start(); - final Session session = flowControlConnection.createSession(false, - Session.CLIENT_ACKNOWLEDGE); + final Session session = flowControlConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); final MessageProducer producer = session.createProducer(queueA); final AtomicBoolean done = new AtomicBoolean(true); final AtomicBoolean keepGoing = new AtomicBoolean(true); - Thread thread = new Thread("Filler") - { + Thread thread = new Thread("Filler") { int i; @Override - public void run() - { - while (keepGoing.get()) - { + public void run() { + while (keepGoing.get()) { done.set(false); - try - { + try { producer.send(session.createTextMessage("Test message " + ++i)); } - catch (JMSException e) - { + catch (JMSException e) { } } } @@ -180,8 +164,7 @@ public class ProducerFlowControlTest extends BasicOpenWireTest // (done == false) MessageConsumer consumer = session.createConsumer(queueA); TextMessage msg; - for (int idx = 0; idx < 5; ++idx) - { + for (int idx = 0; idx < 5; ++idx) { msg = (TextMessage) consumer.receive(1000); assertNotNull("Got a message", msg); System.out.println("received: " + idx + ", msg: " + msg.getJMSMessageID()); @@ -195,14 +178,12 @@ public class ProducerFlowControlTest extends BasicOpenWireTest } @Test - public void test2ndPublisherWithSyncSendConnectionThatIsBlocked() throws Exception - { + public void test2ndPublisherWithSyncSendConnectionThatIsBlocked() throws Exception { factory.setAlwaysSyncSend(true); flowControlConnection = (ActiveMQConnection) factory.createConnection(); flowControlConnection.start(); - Session session = flowControlConnection.createSession(false, - Session.CLIENT_ACKNOWLEDGE); + Session session = flowControlConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(queueB); // Test sending to Queue A @@ -227,14 +208,12 @@ public class ProducerFlowControlTest extends BasicOpenWireTest } @Test - public void testSimpleSendReceive() throws Exception - { + public void testSimpleSendReceive() throws Exception { factory.setAlwaysSyncSend(true); flowControlConnection = (ActiveMQConnection) factory.createConnection(); flowControlConnection.start(); - Session session = flowControlConnection.createSession(false, - Session.CLIENT_ACKNOWLEDGE); + Session session = flowControlConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(queueA); // Test sending to Queue B it should not block. @@ -255,8 +234,7 @@ public class ProducerFlowControlTest extends BasicOpenWireTest } @Test - public void test2ndPublisherWithStandardConnectionThatIsBlocked() throws Exception - { + public void test2ndPublisherWithStandardConnectionThatIsBlocked() throws Exception { flowControlConnection = (ActiveMQConnection) factory.createConnection(); flowControlConnection.start(); @@ -272,9 +250,7 @@ public class ProducerFlowControlTest extends BasicOpenWireTest assertFalse(pubishDoneToQeueuB.await(2, TimeUnit.SECONDS)); } - private void fillQueue(final ActiveMQQueue queue) throws JMSException, - InterruptedException - { + private void fillQueue(final ActiveMQQueue queue) throws JMSException, InterruptedException { final AtomicBoolean done = new AtomicBoolean(true); final AtomicBoolean keepGoing = new AtomicBoolean(true); @@ -282,27 +258,21 @@ public class ProducerFlowControlTest extends BasicOpenWireTest // flag to false. // Once the send starts to block it will not reset the done flag // anymore. - asyncThread = new Thread("Fill thread.") - { - public void run() - { + asyncThread = new Thread("Fill thread.") { + public void run() { Session session = null; - try - { + try { session = flowControlConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(queue); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - while (keepGoing.get()) - { + while (keepGoing.get()) { done.set(false); producer.send(session.createTextMessage("Hello World")); } } - catch (JMSException e) - { + catch (JMSException e) { } - finally - { + finally { safeClose(session); } } @@ -313,46 +283,35 @@ public class ProducerFlowControlTest extends BasicOpenWireTest keepGoing.set(false); } - protected void waitForBlockedOrResourceLimit(final AtomicBoolean done) throws InterruptedException - { - while (true) - { + protected void waitForBlockedOrResourceLimit(final AtomicBoolean done) throws InterruptedException { + while (true) { Thread.sleep(2000); System.out.println("check done: " + done.get() + " ex: " + gotResourceException.get()); // the producer is blocked once the done flag stays true or there is a // resource exception - if (done.get() || gotResourceException.get()) - { + if (done.get() || gotResourceException.get()) { break; } done.set(true); } } - private CountDownLatch asyncSendTo(final ActiveMQQueue queue, - final String message) throws JMSException - { + private CountDownLatch asyncSendTo(final ActiveMQQueue queue, final String message) throws JMSException { final CountDownLatch done = new CountDownLatch(1); - new Thread("Send thread.") - { - public void run() - { + new Thread("Send thread.") { + public void run() { Session session = null; - try - { - session = flowControlConnection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + try { + session = flowControlConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(queue); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); producer.send(session.createTextMessage(message)); done.countDown(); } - catch (JMSException e) - { + catch (JMSException e) { e.printStackTrace(); } - finally - { + finally { safeClose(session); } } @@ -361,19 +320,15 @@ public class ProducerFlowControlTest extends BasicOpenWireTest } @Override - protected void extraServerConfig(Configuration serverConfig) - { + protected void extraServerConfig(Configuration serverConfig) { String match = "jms.queue.#"; Map asMap = serverConfig.getAddressesSettings(); - asMap.get(match) - .setMaxSizeBytes(1) - .setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK); + asMap.get(match).setMaxSizeBytes(1).setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK); } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); this.makeSureCoreQueueExist("QUEUE.A"); this.makeSureCoreQueueExist("QUEUE.B"); @@ -381,28 +336,20 @@ public class ProducerFlowControlTest extends BasicOpenWireTest @Override @After - public void tearDown() throws Exception - { - try - { - if (flowControlConnection != null) - { - TcpTransport t = (TcpTransport) flowControlConnection.getTransport() - .narrow(TcpTransport.class); - t.getTransportListener() - .onException(new IOException("Disposed.")); - flowControlConnection.getTransport() - .stop(); + public void tearDown() throws Exception { + try { + if (flowControlConnection != null) { + TcpTransport t = (TcpTransport) flowControlConnection.getTransport().narrow(TcpTransport.class); + t.getTransportListener().onException(new IOException("Disposed.")); + flowControlConnection.getTransport().stop(); flowControlConnection.close(); } - if (asyncThread != null) - { + if (asyncThread != null) { asyncThread.join(); asyncThread = null; } } - finally - { + finally { super.tearDown(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/ReconnectWithSameClientIDTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/ReconnectWithSameClientIDTest.java index bef2cd559e..940903a682 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/ReconnectWithSameClientIDTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/ReconnectWithSameClientIDTest.java @@ -29,36 +29,29 @@ import org.junit.Test; /** * adapted from: org.apache.activemq.ReconnectWithSameClientIDTest */ -public class ReconnectWithSameClientIDTest extends BasicOpenWireTest -{ +public class ReconnectWithSameClientIDTest extends BasicOpenWireTest { + protected ActiveMQConnection sameIdConnection; protected boolean transacted; protected int authMode = Session.AUTO_ACKNOWLEDGE; @Test - public void testReconnectMultipleTimesWithSameClientID() throws Exception - { - try - { + public void testReconnectMultipleTimesWithSameClientID() throws Exception { + try { sameIdConnection = (ActiveMQConnection) this.factory.createConnection(); useConnection(sameIdConnection); // now lets create another which should fail - for (int i = 1; i < 11; i++) - { + for (int i = 1; i < 11; i++) { Connection connection2 = this.factory.createConnection(); - try - { + try { useConnection(connection2); - fail("Should have thrown InvalidClientIDException on attempt" - + i); + fail("Should have thrown InvalidClientIDException on attempt" + i); } - catch (InvalidClientIDException e) - { + catch (InvalidClientIDException e) { System.err.println("Caught expected: " + e); } - finally - { + finally { connection2.close(); } } @@ -69,28 +62,23 @@ public class ReconnectWithSameClientIDTest extends BasicOpenWireTest sameIdConnection = (ActiveMQConnection) factory.createConnection(); useConnection(connection); } - finally - { - if (sameIdConnection != null) - { + finally { + if (sameIdConnection != null) { sameIdConnection.close(); } } } @After - public void tearDown() throws Exception - { - if (sameIdConnection != null) - { + public void tearDown() throws Exception { + if (sameIdConnection != null) { sameIdConnection.close(); sameIdConnection = null; } super.tearDown(); } - protected void useConnection(Connection connection) throws JMSException - { + protected void useConnection(Connection connection) throws JMSException { connection.setClientID("foo"); connection.start(); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/RedeliveryPolicyTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/RedeliveryPolicyTest.java index 75a3635c41..5f14906748 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/RedeliveryPolicyTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/RedeliveryPolicyTest.java @@ -32,11 +32,10 @@ import org.junit.Test; /** * adapted from: org.apache.activemq.RedeliveryPolicyTest */ -public class RedeliveryPolicyTest extends BasicOpenWireTest -{ +public class RedeliveryPolicyTest extends BasicOpenWireTest { + @Test - public void testGetNext() throws Exception - { + public void testGetNext() throws Exception { RedeliveryPolicy policy = new RedeliveryPolicy(); policy.setInitialRedeliveryDelay(0); @@ -60,8 +59,7 @@ public class RedeliveryPolicyTest extends BasicOpenWireTest * @throws Exception */ @Test - public void testExponentialRedeliveryPolicyDelaysDeliveryOnRollback() throws Exception - { + public void testExponentialRedeliveryPolicyDelaysDeliveryOnRollback() throws Exception { // Receive a message with the JMS API RedeliveryPolicy policy = connection.getRedeliveryPolicy(); @@ -71,8 +69,7 @@ public class RedeliveryPolicyTest extends BasicOpenWireTest policy.setUseExponentialBackOff(true); connection.start(); - Session session = connection - .createSession(true, Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); ActiveMQQueue destination = new ActiveMQQueue("testExponentialRedeliveryPolicyDelaysDeliveryOnRollback"); this.makeSureCoreQueueExist("testExponentialRedeliveryPolicyDelaysDeliveryOnRollback"); MessageProducer producer = session.createProducer(destination); @@ -119,8 +116,7 @@ public class RedeliveryPolicyTest extends BasicOpenWireTest * @throws Exception */ @Test - public void testNornalRedeliveryPolicyDelaysDeliveryOnRollback() throws Exception - { + public void testNornalRedeliveryPolicyDelaysDeliveryOnRollback() throws Exception { // Receive a message with the JMS API RedeliveryPolicy policy = connection.getRedeliveryPolicy(); @@ -128,8 +124,7 @@ public class RedeliveryPolicyTest extends BasicOpenWireTest policy.setRedeliveryDelay(500); connection.start(); - Session session = connection - .createSession(true, Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); ActiveMQQueue destination = new ActiveMQQueue("testNornalRedeliveryPolicyDelaysDeliveryOnRollback"); this.makeSureCoreQueueExist("testNornalRedeliveryPolicyDelaysDeliveryOnRollback"); MessageProducer producer = session.createProducer(destination); @@ -174,8 +169,7 @@ public class RedeliveryPolicyTest extends BasicOpenWireTest * @throws Exception */ @Test - public void testDLQHandling() throws Exception - { + public void testDLQHandling() throws Exception { this.makeSureCoreQueueExist("ActiveMQ.DLQ"); // Receive a message with the JMS API RedeliveryPolicy policy = connection.getRedeliveryPolicy(); @@ -223,10 +217,8 @@ public class RedeliveryPolicyTest extends BasicOpenWireTest m = (TextMessage) dlqConsumer.receive(1000); assertNotNull(m); assertEquals("1st", m.getText()); - String cause = m - .getStringProperty(ActiveMQMessage.DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY); - assertTrue("cause exception has policy ref", - cause.contains("RedeliveryPolicy")); + String cause = m.getStringProperty(ActiveMQMessage.DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY); + assertTrue("cause exception has policy ref", cause.contains("RedeliveryPolicy")); session.commit(); } @@ -234,8 +226,7 @@ public class RedeliveryPolicyTest extends BasicOpenWireTest * @throws Exception */ @Test - public void testInfiniteMaximumNumberOfRedeliveries() throws Exception - { + public void testInfiniteMaximumNumberOfRedeliveries() throws Exception { // Receive a message with the JMS API RedeliveryPolicy policy = connection.getRedeliveryPolicy(); @@ -245,8 +236,7 @@ public class RedeliveryPolicyTest extends BasicOpenWireTest policy.setMaximumRedeliveries(-1); connection.start(); - Session session = connection - .createSession(true, Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); ActiveMQQueue destination = new ActiveMQQueue("TEST"); this.makeSureCoreQueueExist("TEST"); MessageProducer producer = session.createProducer(destination); @@ -302,8 +292,7 @@ public class RedeliveryPolicyTest extends BasicOpenWireTest * @throws Exception */ @Test - public void testMaximumRedeliveryDelay() throws Exception - { + public void testMaximumRedeliveryDelay() throws Exception { // Receive a message with the JMS API RedeliveryPolicy policy = connection.getRedeliveryPolicy(); @@ -316,8 +305,7 @@ public class RedeliveryPolicyTest extends BasicOpenWireTest policy.setUseExponentialBackOff(true); connection.start(); - Session session = connection - .createSession(true, Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); ActiveMQQueue destination = new ActiveMQQueue("TEST"); this.makeSureCoreQueueExist("TEST"); MessageProducer producer = session.createProducer(destination); @@ -331,8 +319,7 @@ public class RedeliveryPolicyTest extends BasicOpenWireTest TextMessage m; - for (int i = 0; i < 10; ++i) - { + for (int i = 0; i < 10; ++i) { // we should be able to get the 1st message redelivered until a // session.commit is called m = (TextMessage) consumer.receive(2000); @@ -358,8 +345,7 @@ public class RedeliveryPolicyTest extends BasicOpenWireTest * @throws Exception */ @Test - public void testZeroMaximumNumberOfRedeliveries() throws Exception - { + public void testZeroMaximumNumberOfRedeliveries() throws Exception { // Receive a message with the JMS API RedeliveryPolicy policy = connection.getRedeliveryPolicy(); @@ -369,8 +355,7 @@ public class RedeliveryPolicyTest extends BasicOpenWireTest policy.setMaximumRedeliveries(0); connection.start(); - Session session = connection - .createSession(true, Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); ActiveMQQueue destination = new ActiveMQQueue("TEST"); this.makeSureCoreQueueExist("TEST"); MessageProducer producer = session.createProducer(destination); @@ -398,8 +383,7 @@ public class RedeliveryPolicyTest extends BasicOpenWireTest } @Test - public void testInitialRedeliveryDelayZero() throws Exception - { + public void testInitialRedeliveryDelayZero() throws Exception { // Receive a message with the JMS API RedeliveryPolicy policy = connection.getRedeliveryPolicy(); policy.setInitialRedeliveryDelay(0); @@ -438,8 +422,7 @@ public class RedeliveryPolicyTest extends BasicOpenWireTest } @Test - public void testInitialRedeliveryDelayOne() throws Exception - { + public void testInitialRedeliveryDelayOne() throws Exception { // Receive a message with the JMS API RedeliveryPolicy policy = connection.getRedeliveryPolicy(); policy.setInitialRedeliveryDelay(1000); @@ -479,8 +462,7 @@ public class RedeliveryPolicyTest extends BasicOpenWireTest } @Test - public void testRedeliveryDelayOne() throws Exception - { + public void testRedeliveryDelayOne() throws Exception { // Receive a message with the JMS API RedeliveryPolicy policy = connection.getRedeliveryPolicy(); policy.setInitialRedeliveryDelay(0); @@ -525,8 +507,7 @@ public class RedeliveryPolicyTest extends BasicOpenWireTest } @Test - public void testRedeliveryPolicyPerDestination() throws Exception - { + public void testRedeliveryPolicyPerDestination() throws Exception { RedeliveryPolicy queuePolicy = new RedeliveryPolicy(); queuePolicy.setInitialRedeliveryDelay(0); queuePolicy.setRedeliveryDelay(1000); @@ -545,8 +526,7 @@ public class RedeliveryPolicyTest extends BasicOpenWireTest map.put(new ActiveMQQueue(">"), queuePolicy); connection.start(); - Session session = connection - .createSession(true, Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); ActiveMQQueue queue = new ActiveMQQueue("TEST"); ActiveMQTopic topic = new ActiveMQTopic("TEST"); this.makeSureCoreQueueExist("TEST"); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/TimeStampTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/TimeStampTest.java index 8daa6f440f..7976f77067 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/TimeStampTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/TimeStampTest.java @@ -29,12 +29,10 @@ import org.junit.Test; /** * adapted from: org.apache.activemq.TimeStampTest */ -public class TimeStampTest extends BasicOpenWireTest -{ +public class TimeStampTest extends BasicOpenWireTest { @Test - public void testTimestamp() throws Exception - { + public void testTimestamp() throws Exception { // Create a Session connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -56,8 +54,7 @@ public class TimeStampTest extends BasicOpenWireTest long afterSend = System.currentTimeMillis(); // assert message timestamp is in window - assertTrue(beforeSend <= sentMessage.getJMSTimestamp() - && sentMessage.getJMSTimestamp() <= afterSend); + assertTrue(beforeSend <= sentMessage.getJMSTimestamp() && sentMessage.getJMSTimestamp() <= afterSend); // Create a MessageConsumer from the Session to the Topic or Queue MessageConsumer consumer = session.createConsumer(destination); @@ -69,18 +66,10 @@ public class TimeStampTest extends BasicOpenWireTest assertEquals(sentMessage.getJMSMessageID(), receivedMessage.getJMSMessageID()); // assert message timestamp is in window - assertTrue( - "JMS Message Timestamp should be set during the send method: \n" - + " beforeSend = " + beforeSend + "\n" - + " getJMSTimestamp = " + receivedMessage.getJMSTimestamp() - + "\n" + " afterSend = " + afterSend + "\n", - beforeSend <= receivedMessage.getJMSTimestamp() - && receivedMessage.getJMSTimestamp() <= afterSend); + assertTrue("JMS Message Timestamp should be set during the send method: \n" + " beforeSend = " + beforeSend + "\n" + " getJMSTimestamp = " + receivedMessage.getJMSTimestamp() + "\n" + " afterSend = " + afterSend + "\n", beforeSend <= receivedMessage.getJMSTimestamp() && receivedMessage.getJMSTimestamp() <= afterSend); // assert message timestamp is unchanged - assertEquals( - "JMS Message Timestamp of received message should be the same as the sent message\n ", - sentMessage.getJMSTimestamp(), receivedMessage.getJMSTimestamp()); + assertEquals("JMS Message Timestamp of received message should be the same as the sent message\n ", sentMessage.getJMSTimestamp(), receivedMessage.getJMSTimestamp()); // Clean up producer.close(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/TransactionContextTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/TransactionContextTest.java index c4b7da47d5..2cfcf96b59 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/TransactionContextTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/TransactionContextTest.java @@ -29,108 +29,89 @@ import org.junit.Test; /** * adapted from: org.apache.activemq.TransactionContextTest */ -public class TransactionContextTest extends BasicOpenWireTest -{ +public class TransactionContextTest extends BasicOpenWireTest { + TransactionContext underTest; @Before - public void setup() throws Exception - { + public void setup() throws Exception { underTest = new TransactionContext(connection); } @Test - public void testSyncBeforeEndCalledOnceOnRollback() throws Exception - { + public void testSyncBeforeEndCalledOnceOnRollback() throws Exception { final AtomicInteger beforeEndCountA = new AtomicInteger(0); final AtomicInteger beforeEndCountB = new AtomicInteger(0); final AtomicInteger rollbackCountA = new AtomicInteger(0); final AtomicInteger rollbackCountB = new AtomicInteger(0); - underTest.addSynchronization(new Synchronization() - { + underTest.addSynchronization(new Synchronization() { @Override - public void beforeEnd() throws Exception - { - if (beforeEndCountA.getAndIncrement() == 0) - { + public void beforeEnd() throws Exception { + if (beforeEndCountA.getAndIncrement() == 0) { throw new TransactionRolledBackException("force rollback"); } } @Override - public void afterCommit() throws Exception - { + public void afterCommit() throws Exception { fail("exepcted rollback exception"); } @Override - public void afterRollback() throws Exception - { + public void afterRollback() throws Exception { rollbackCountA.incrementAndGet(); } }); - underTest.addSynchronization(new Synchronization() - { + underTest.addSynchronization(new Synchronization() { @Override - public void beforeEnd() throws Exception - { + public void beforeEnd() throws Exception { beforeEndCountB.getAndIncrement(); } @Override - public void afterCommit() throws Exception - { + public void afterCommit() throws Exception { fail("exepcted rollback exception"); } @Override - public void afterRollback() throws Exception - { + public void afterRollback() throws Exception { rollbackCountB.incrementAndGet(); } }); - try - { + try { underTest.commit(); fail("exepcted rollback exception"); } - catch (TransactionRolledBackException expected) - { + catch (TransactionRolledBackException expected) { } assertEquals("beforeEnd A called once", 1, beforeEndCountA.get()); assertEquals("beforeEnd B called once", 1, beforeEndCountA.get()); assertEquals("rollbackCount B 0", 1, rollbackCountB.get()); - assertEquals("rollbackCount A B", rollbackCountA.get(), - rollbackCountB.get()); + assertEquals("rollbackCount A B", rollbackCountA.get(), rollbackCountB.get()); } @Test - public void testSyncIndexCleared() throws Exception - { + public void testSyncIndexCleared() throws Exception { final AtomicInteger beforeEndCountA = new AtomicInteger(0); final AtomicInteger rollbackCountA = new AtomicInteger(0); - Synchronization sync = new Synchronization() - { + Synchronization sync = new Synchronization() { @Override - public void beforeEnd() throws Exception - { + public void beforeEnd() throws Exception { beforeEndCountA.getAndIncrement(); } @Override - public void afterCommit() throws Exception - { + public void afterCommit() throws Exception { fail("exepcted rollback exception"); } @Override - public void afterRollback() throws Exception - { + public void afterRollback() throws Exception { rollbackCountA.incrementAndGet(); } }; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/interop/GeneralInteropTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/interop/GeneralInteropTest.java index 429657c176..b88d9ea7c3 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/interop/GeneralInteropTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/interop/GeneralInteropTest.java @@ -41,21 +41,19 @@ import java.io.Serializable; * openwire clients, i.e. core producers sending messages * to be received by openwire receivers, and vice versa. */ -public class GeneralInteropTest extends BasicOpenWireTest -{ +public class GeneralInteropTest extends BasicOpenWireTest { + private ServerLocator locator; @Before @Override - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = this.createInVMNonHALocator(); } @Test - public void testReceivingFromCore() throws Exception - { + public void testReceivingFromCore() throws Exception { final String text = "HelloWorld"; //text messages @@ -77,11 +75,11 @@ public class GeneralInteropTest extends BasicOpenWireTest MapMessage mapMessage = (MapMessage) consumer.receive(5000); assertTrue(mapMessage.getBoolean("aboolean")); - assertEquals((byte)4, mapMessage.getByte("abyte")); + assertEquals((byte) 4, mapMessage.getByte("abyte")); byte[] bytes = mapMessage.getBytes("abytes"); assertEquals(2, bytes.length); - assertEquals((byte)4, bytes[0]); - assertEquals((byte)5, bytes[1]); + assertEquals((byte) 4, bytes[0]); + assertEquals((byte) 5, bytes[1]); assertEquals('a', mapMessage.getChar("achar")); Double doubleVal = mapMessage.getDouble("adouble"); assertTrue(doubleVal.equals(Double.valueOf(4.4))); @@ -108,7 +106,7 @@ public class GeneralInteropTest extends BasicOpenWireTest StreamMessage streamMessage = (StreamMessage) consumer.receive(5000); assertTrue(streamMessage.readBoolean()); - assertEquals((byte)2, streamMessage.readByte()); + assertEquals((byte) 2, streamMessage.readByte()); byte[] streamBytes = new byte[2]; streamMessage.readBytes(streamBytes); @@ -123,7 +121,7 @@ public class GeneralInteropTest extends BasicOpenWireTest assertTrue(streamFloat.equals(Float.valueOf(93.9F))); assertEquals(7657, streamMessage.readInt()); assertEquals(239999L, streamMessage.readLong()); - assertEquals((short)34222, streamMessage.readShort()); + assertEquals((short) 34222, streamMessage.readShort()); assertEquals("hello streammessage", streamMessage.readString()); //bytes messages @@ -134,15 +132,14 @@ public class GeneralInteropTest extends BasicOpenWireTest byte[] rawBytes = new byte[bytesData.length]; bytesMessage.readBytes(rawBytes); - for (int i = 0; i < bytesData.length; i++) - { + for (int i = 0; i < bytesData.length; i++) { assertEquals("failed at " + i, bytesData[i], rawBytes[i]); } assertTrue(bytesMessage.readBoolean()); assertEquals(99999L, bytesMessage.readLong()); assertEquals('h', bytesMessage.readChar()); assertEquals(987, bytesMessage.readInt()); - assertEquals((short)1099, bytesMessage.readShort()); + assertEquals((short) 1099, bytesMessage.readShort()); assertEquals("hellobytes", bytesMessage.readUTF()); //generic message @@ -154,13 +151,12 @@ public class GeneralInteropTest extends BasicOpenWireTest assertFalse(genericMessage.getBooleanProperty("booleanProperty")); assertEquals(99999L, genericMessage.getLongProperty("longProperty")); assertEquals(979, genericMessage.getIntProperty("intProperty")); - assertEquals((short)1099, genericMessage.getShortProperty("shortProperty")); + assertEquals((short) 1099, genericMessage.getShortProperty("shortProperty")); assertEquals("HelloMessage", genericMessage.getStringProperty("stringProperty")); } @Test - public void testMutipleReceivingFromCore() throws Exception - { + public void testMutipleReceivingFromCore() throws Exception { final String text = "HelloWorld"; final int num = 100; //text messages @@ -172,51 +168,43 @@ public class GeneralInteropTest extends BasicOpenWireTest final ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer) session.createConsumer(destination); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { TextMessage textMessage = (TextMessage) consumer.receive(5000); assertEquals(text + i, textMessage.getText()); } } - private void sendMultipleTextMessagesUsingCoreJms(String queueName, String text, int num) throws Exception - { + private void sendMultipleTextMessagesUsingCoreJms(String queueName, String text, int num) throws Exception { Connection jmsConn = null; - try - { + try { jmsConn = coreCf.createConnection(); Session session = jmsConn.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue(queueName); MessageProducer producer = session.createProducer(queue); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { TextMessage msg = session.createTextMessage(text + i); producer.send(msg); } } - finally - { - if (jmsConn != null) - { + finally { + if (jmsConn != null) { jmsConn.close(); } } } - private void sendMessageUsingCoreJms(String queueName) throws Exception - { + private void sendMessageUsingCoreJms(String queueName) throws Exception { Connection jmsConn = null; - try - { + try { jmsConn = coreCf.createConnection(); Session session = jmsConn.createSession(false, Session.AUTO_ACKNOWLEDGE); javax.jms.Message message = session.createMessage(); message.setBooleanProperty("booleanProperty", false); message.setLongProperty("longProperty", 99999L); - message.setByteProperty("byteProperty", (byte)5); + message.setByteProperty("byteProperty", (byte) 5); message.setIntProperty("intProperty", 979); - message.setShortProperty("shortProperty", (short)1099); + message.setShortProperty("shortProperty", (short) 1099); message.setStringProperty("stringProperty", "HelloMessage"); Queue queue = session.createQueue(queueName); @@ -224,21 +212,17 @@ public class GeneralInteropTest extends BasicOpenWireTest producer.send(message); } - finally - { - if (jmsConn != null) - { + finally { + if (jmsConn != null) { jmsConn.close(); } } } - private void sendBytesMessageUsingCoreJms(String queueName, byte[] data) throws Exception - { + private void sendBytesMessageUsingCoreJms(String queueName, byte[] data) throws Exception { Connection jmsConn = null; - try - { + try { jmsConn = coreCf.createConnection(); Session session = jmsConn.createSession(false, Session.AUTO_ACKNOWLEDGE); BytesMessage bytesMessage = session.createBytesMessage(); @@ -248,7 +232,7 @@ public class GeneralInteropTest extends BasicOpenWireTest bytesMessage.writeLong(99999L); bytesMessage.writeChar('h'); bytesMessage.writeInt(987); - bytesMessage.writeShort((short)1099); + bytesMessage.writeShort((short) 1099); bytesMessage.writeUTF("hellobytes"); Queue queue = session.createQueue(queueName); @@ -256,21 +240,17 @@ public class GeneralInteropTest extends BasicOpenWireTest producer.send(bytesMessage); } - finally - { - if (jmsConn != null) - { + finally { + if (jmsConn != null) { jmsConn.close(); } } } - private void sendObjectMessageUsingCoreJms(String queueName, Serializable object) throws Exception - { + private void sendObjectMessageUsingCoreJms(String queueName, Serializable object) throws Exception { Connection jmsConn = null; - try - { + try { jmsConn = coreCf.createConnection(); Session session = jmsConn.createSession(false, Session.AUTO_ACKNOWLEDGE); ObjectMessage objectMessage = session.createObjectMessage(object); @@ -280,33 +260,29 @@ public class GeneralInteropTest extends BasicOpenWireTest producer.send(objectMessage); } - finally - { - if (jmsConn != null) - { + finally { + if (jmsConn != null) { jmsConn.close(); } } } - private void sendStreamMessageUsingCoreJms(String queueName) throws Exception - { + private void sendStreamMessageUsingCoreJms(String queueName) throws Exception { Connection jmsConn = null; - try - { + try { jmsConn = coreCf.createConnection(); Session session = jmsConn.createSession(false, Session.AUTO_ACKNOWLEDGE); StreamMessage msg = session.createStreamMessage(); msg.writeBoolean(true); - msg.writeByte((byte)2); - msg.writeBytes(new byte[]{6,7}); + msg.writeByte((byte) 2); + msg.writeBytes(new byte[]{6, 7}); msg.writeChar('b'); - msg.writeDouble((double)6.5); - msg.writeFloat((float)93.9); + msg.writeDouble((double) 6.5); + msg.writeFloat((float) 93.9); msg.writeInt(7657); msg.writeLong(239999L); - msg.writeShort((short)34222); + msg.writeShort((short) 34222); msg.writeString("hello streammessage"); Queue queue = session.createQueue(queueName); @@ -314,33 +290,29 @@ public class GeneralInteropTest extends BasicOpenWireTest producer.send(msg); } - finally - { - if (jmsConn != null) - { + finally { + if (jmsConn != null) { jmsConn.close(); } } } - private void sendMapMessageUsingCoreJms(String queueName) throws Exception - { + private void sendMapMessageUsingCoreJms(String queueName) throws Exception { Connection jmsConn = null; - try - { + try { jmsConn = coreCf.createConnection(); Session session = jmsConn.createSession(false, Session.AUTO_ACKNOWLEDGE); MapMessage mapMessage = session.createMapMessage(); mapMessage.setBoolean("aboolean", true); - mapMessage.setByte("abyte", (byte)4); + mapMessage.setByte("abyte", (byte) 4); mapMessage.setBytes("abytes", new byte[]{4, 5}); mapMessage.setChar("achar", 'a'); mapMessage.setDouble("adouble", 4.4); mapMessage.setFloat("afloat", 4.5f); mapMessage.setInt("aint", 40); mapMessage.setLong("along", 80L); - mapMessage.setShort("ashort", (short)65); + mapMessage.setShort("ashort", (short) 65); mapMessage.setString("astring", "hello"); Queue queue = session.createQueue(queueName); @@ -348,21 +320,17 @@ public class GeneralInteropTest extends BasicOpenWireTest producer.send(mapMessage); } - finally - { - if (jmsConn != null) - { + finally { + if (jmsConn != null) { jmsConn.close(); } } } - private void sendTextMessageUsingCoreJms(String address, String text) throws Exception - { + private void sendTextMessageUsingCoreJms(String address, String text) throws Exception { Connection jmsConn = null; - try - { + try { jmsConn = coreCf.createConnection(); Session session = jmsConn.createSession(false, Session.AUTO_ACKNOWLEDGE); TextMessage msg = session.createTextMessage(text); @@ -371,10 +339,8 @@ public class GeneralInteropTest extends BasicOpenWireTest producer.send(msg); } - finally - { - if (jmsConn != null) - { + finally { + if (jmsConn != null) { jmsConn.close(); } } @@ -382,13 +348,11 @@ public class GeneralInteropTest extends BasicOpenWireTest } @Test - public void testSendingToCoreJms() throws Exception - { + public void testSendingToCoreJms() throws Exception { final String text = "HelloWorld"; Connection jmsConn = null; - try - { + try { jmsConn = coreCf.createConnection(); jmsConn.start(); @@ -439,7 +403,7 @@ public class GeneralInteropTest extends BasicOpenWireTest StreamMessage streamMessage = (StreamMessage) coreConsumer.receive(5000); assertTrue(streamMessage.readBoolean()); - assertEquals((byte)2, streamMessage.readByte()); + assertEquals((byte) 2, streamMessage.readByte()); byte[] streamBytes = new byte[2]; streamMessage.readBytes(streamBytes); @@ -454,7 +418,7 @@ public class GeneralInteropTest extends BasicOpenWireTest assertTrue(streamFloat.equals(Float.valueOf(93.9F))); assertEquals(7657, streamMessage.readInt()); assertEquals(239999L, streamMessage.readLong()); - assertEquals((short)34222, streamMessage.readShort()); + assertEquals((short) 34222, streamMessage.readShort()); assertEquals("hello streammessage", streamMessage.readString()); //bytes messages @@ -465,8 +429,7 @@ public class GeneralInteropTest extends BasicOpenWireTest byte[] rawBytes = new byte[bytesData.length]; bytesMessage.readBytes(rawBytes); - for (int i = 0; i < bytesData.length; i++) - { + for (int i = 0; i < bytesData.length; i++) { assertEquals(bytesData[i], rawBytes[i]); } @@ -479,27 +442,23 @@ public class GeneralInteropTest extends BasicOpenWireTest assertFalse(genericMessage.getBooleanProperty("booleanProperty")); assertEquals(99999L, genericMessage.getLongProperty("longProperty")); assertEquals(979, genericMessage.getIntProperty("intProperty")); - assertEquals((short)1099, genericMessage.getShortProperty("shortProperty")); + assertEquals((short) 1099, genericMessage.getShortProperty("shortProperty")); assertEquals("HelloMessage", genericMessage.getStringProperty("stringProperty")); } - finally - { - if (jmsConn != null) - { + finally { + if (jmsConn != null) { jmsConn.close(); } } } @Test - public void testMultipleSendingToCoreJms() throws Exception - { + public void testMultipleSendingToCoreJms() throws Exception { final String text = "HelloWorld"; final int num = 100; Connection jmsConn = null; - try - { + try { jmsConn = coreCf.createConnection(); jmsConn.start(); @@ -510,37 +469,31 @@ public class GeneralInteropTest extends BasicOpenWireTest //text messages sendMultipleTextMessagesUsingOpenWire(text, num); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { TextMessage txtMessage = (TextMessage) coreConsumer.receive(5000); assertEquals(text + i, txtMessage.getText()); } } - finally - { - if (jmsConn != null) - { + finally { + if (jmsConn != null) { jmsConn.close(); } } } - private void sendMultipleTextMessagesUsingOpenWire(String text, int num) throws Exception - { + private void sendMultipleTextMessagesUsingOpenWire(String text, int num) throws Exception { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); final ActiveMQMessageProducer producer = (ActiveMQMessageProducer) session.createProducer(destination); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { TextMessage textMessage = session.createTextMessage(text + i); producer.send(textMessage); } } - private void sendMessageUsingOpenWire(String queueName) throws Exception - { + private void sendMessageUsingOpenWire(String queueName) throws Exception { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); @@ -551,16 +504,15 @@ public class GeneralInteropTest extends BasicOpenWireTest message.setBooleanProperty("booleanProperty", false); message.setLongProperty("longProperty", 99999L); - message.setByteProperty("byteProperty", (byte)5); + message.setByteProperty("byteProperty", (byte) 5); message.setIntProperty("intProperty", 979); - message.setShortProperty("shortProperty", (short)1099); + message.setShortProperty("shortProperty", (short) 1099); message.setStringProperty("stringProperty", "HelloMessage"); producer.send(message); } - private void sendBytesMessageUsingOpenWire(byte[] bytesData) throws Exception - { + private void sendBytesMessageUsingOpenWire(byte[] bytesData) throws Exception { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); @@ -573,14 +525,13 @@ public class GeneralInteropTest extends BasicOpenWireTest bytesMessage.writeLong(99999L); bytesMessage.writeChar('h'); bytesMessage.writeInt(987); - bytesMessage.writeShort((short)1099); + bytesMessage.writeShort((short) 1099); bytesMessage.writeUTF("hellobytes"); producer.send(bytesMessage); } - private void sendStreamMessageUsingOpenWire(String queueName) throws Exception - { + private void sendStreamMessageUsingOpenWire(String queueName) throws Exception { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); @@ -589,21 +540,20 @@ public class GeneralInteropTest extends BasicOpenWireTest StreamMessage streamMessage = session.createStreamMessage(); streamMessage.writeBoolean(true); - streamMessage.writeByte((byte)2); - streamMessage.writeBytes(new byte[]{6,7}); + streamMessage.writeByte((byte) 2); + streamMessage.writeBytes(new byte[]{6, 7}); streamMessage.writeChar('b'); - streamMessage.writeDouble((double)6.5); - streamMessage.writeFloat((float)93.9); + streamMessage.writeDouble((double) 6.5); + streamMessage.writeFloat((float) 93.9); streamMessage.writeInt(7657); streamMessage.writeLong(239999L); - streamMessage.writeShort((short)34222); + streamMessage.writeShort((short) 34222); streamMessage.writeString("hello streammessage"); producer.send(streamMessage); } - private void sendObjectMessageUsingOpenWire(SimpleSerializable obj) throws Exception - { + private void sendObjectMessageUsingOpenWire(SimpleSerializable obj) throws Exception { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); @@ -615,8 +565,7 @@ public class GeneralInteropTest extends BasicOpenWireTest producer.send(objectMessage); } - private void sendMapMessageUsingOpenWire() throws Exception - { + private void sendMapMessageUsingOpenWire() throws Exception { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); @@ -625,21 +574,20 @@ public class GeneralInteropTest extends BasicOpenWireTest MapMessage mapMessage = session.createMapMessage(); mapMessage.setBoolean("aboolean", true); - mapMessage.setByte("abyte", (byte)4); + mapMessage.setByte("abyte", (byte) 4); mapMessage.setBytes("abytes", new byte[]{4, 5}); mapMessage.setChar("achar", 'a'); mapMessage.setDouble("adouble", 4.4); mapMessage.setFloat("afloat", 4.5f); mapMessage.setInt("aint", 40); mapMessage.setLong("along", 80L); - mapMessage.setShort("ashort", (short)65); + mapMessage.setShort("ashort", (short) 65); mapMessage.setString("astring", "hello"); producer.send(mapMessage); } - private void sendTextMessageUsingOpenWire(String text) throws Exception - { + private void sendTextMessageUsingOpenWire(String text) throws Exception { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); @@ -650,8 +598,8 @@ public class GeneralInteropTest extends BasicOpenWireTest producer.send(textMessage); } - private static class SimpleSerializable implements Serializable - { + private static class SimpleSerializable implements Serializable { + private static final long serialVersionUID = -1034113865185130710L; public String objName = "simple-serializable"; public int intVal = 9999; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/util/Wait.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/util/Wait.java index 3ac138d718..0275a68fb4 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/util/Wait.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/util/Wait.java @@ -21,33 +21,31 @@ import java.util.concurrent.TimeUnit; /** * Utility adapted from: org.apache.activemq.util.Wait */ -public class Wait -{ +public class Wait { + public static final long MAX_WAIT_MILLIS = 30 * 1000; public static final int SLEEP_MILLIS = 1000; - public interface Condition - { + public interface Condition { + boolean isSatisified() throws Exception; } - public static boolean waitFor(Condition condition) throws Exception - { + public static boolean waitFor(Condition condition) throws Exception { return waitFor(condition, MAX_WAIT_MILLIS); } - public static boolean waitFor(final Condition condition, final long duration) throws Exception - { + public static boolean waitFor(final Condition condition, final long duration) throws Exception { return waitFor(condition, duration, SLEEP_MILLIS); } - public static boolean waitFor(final Condition condition, final long duration, final int sleepMillis) throws Exception - { + public static boolean waitFor(final Condition condition, + final long duration, + final int sleepMillis) throws Exception { final long expiry = System.currentTimeMillis() + duration; boolean conditionSatisified = condition.isSatisified(); - while (!conditionSatisified && System.currentTimeMillis() < expiry) - { + while (!conditionSatisified && System.currentTimeMillis() < expiry) { TimeUnit.MILLISECONDS.sleep(sleepMillis); conditionSatisified = condition.isSatisified(); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/MultipleProducersPagingTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/MultipleProducersPagingTest.java index 40f2ccb9de..a57c781ba2 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/MultipleProducersPagingTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/MultipleProducersPagingTest.java @@ -52,8 +52,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class MultipleProducersPagingTest extends ActiveMQTestBase -{ +public class MultipleProducersPagingTest extends ActiveMQTestBase { + private static final int CONSUMER_WAIT_TIME_MS = 250; private static final int PRODUCERS = 5; private static final long MESSAGES_PER_PRODUCER = 2000; @@ -71,32 +71,17 @@ public class MultipleProducersPagingTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); executor = Executors.newCachedThreadPool(); - AddressSettings addressSettings = new AddressSettings() - .setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE) - .setPageSizeBytes(50000) - .setMaxSizeBytes(404850); + AddressSettings addressSettings = new AddressSettings().setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE).setPageSizeBytes(50000).setMaxSizeBytes(404850); - Configuration config = createBasicConfig() - .setPersistenceEnabled(false) - .setAddressesSettings(Collections.singletonMap("#", addressSettings)) - .setAcceptorConfigurations(Collections.singleton(new TransportConfiguration(NettyAcceptorFactory.class.getName()))) - .setConnectorConfigurations(Collections.singletonMap("netty", new TransportConfiguration(NettyConnectorFactory.class.getName()))); + Configuration config = createBasicConfig().setPersistenceEnabled(false).setAddressesSettings(Collections.singletonMap("#", addressSettings)).setAcceptorConfigurations(Collections.singleton(new TransportConfiguration(NettyAcceptorFactory.class.getName()))).setConnectorConfigurations(Collections.singletonMap("netty", new TransportConfiguration(NettyConnectorFactory.class.getName()))); final JMSConfiguration jmsConfig = new JMSConfigurationImpl(); - jmsConfig.getConnectionFactoryConfigurations().add(new ConnectionFactoryConfigurationImpl() - .setName("cf") - .setConnectorNames(Arrays.asList("netty")) - .setBindings("/cf")); - jmsConfig.getQueueConfigurations().add(new JMSQueueConfigurationImpl() - .setName("simple") - .setSelector("") - .setDurable(false) - .setBindings("/queue/simple")); + jmsConfig.getConnectionFactoryConfigurations().add(new ConnectionFactoryConfigurationImpl().setName("cf").setConnectorNames(Arrays.asList("netty")).setBindings("/cf")); + jmsConfig.getQueueConfigurations().add(new JMSQueueConfigurationImpl().setName("simple").setSelector("").setDurable(false).setBindings("/queue/simple")); jmsServer = new EmbeddedJMS(); jmsServer.setConfiguration(config); @@ -112,13 +97,10 @@ public class MultipleProducersPagingTest extends ActiveMQTestBase msgSent = new AtomicLong(0); } - @Test - public void testQueue() throws InterruptedException - { + public void testQueue() throws InterruptedException { executor.execute(new ConsumerRun()); - for (int i = 0; i < PRODUCERS; i++) - { + for (int i = 0; i < PRODUCERS; i++) { executor.execute(new ProducerRun()); } Assert.assertTrue("must take less than a minute to run", runnersLatch.await(1, TimeUnit.MINUTES)); @@ -126,68 +108,56 @@ public class MultipleProducersPagingTest extends ActiveMQTestBase Assert.assertEquals("number received", TOTAL_MSG, msgReceived.longValue()); } - private synchronized Session createSession() throws JMSException - { + private synchronized Session createSession() throws JMSException { Connection connection = cf.createConnection(); connections.add(connection); connection.start(); return connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } - final class ConsumerRun implements Runnable - { + final class ConsumerRun implements Runnable { @Override - public void run() - { - try - { + public void run() { + try { Session session = createSession(); MessageConsumer consumer = session.createConsumer(queue); barrierLatch.await(); - while (true) - { + while (true) { Message msg = consumer.receive(CONSUMER_WAIT_TIME_MS); if (msg == null) break; msgReceived.incrementAndGet(); } } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } - finally - { + finally { runnersLatch.countDown(); } } } - final class ProducerRun implements Runnable - { + final class ProducerRun implements Runnable { + @Override - public void run() - { - try - { + public void run() { + try { Session session = createSession(); MessageProducer producer = session.createProducer(queue); barrierLatch.await(); - for (int i = 0; i < MESSAGES_PER_PRODUCER; i++) - { + for (int i = 0; i < MESSAGES_PER_PRODUCER; i++) { producer.send(session.createTextMessage(this.hashCode() + " counter " + i)); msgSent.incrementAndGet(); } } - catch (Exception cause) - { + catch (Exception cause) { throw new RuntimeException(cause); } - finally - { + finally { runnersLatch.countDown(); } } @@ -195,11 +165,9 @@ public class MultipleProducersPagingTest extends ActiveMQTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { executor.shutdown(); - for (Connection conn : connections) - { + for (Connection conn : connections) { conn.close(); } connections.clear(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/NettyPagingSendTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/NettyPagingSendTest.java index 380c97ed94..26e0673296 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/NettyPagingSendTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/NettyPagingSendTest.java @@ -16,11 +16,10 @@ */ package org.apache.activemq.artemis.tests.integration.paging; -public class NettyPagingSendTest extends PagingSendTest -{ +public class NettyPagingSendTest extends PagingSendTest { + @Override - protected boolean isNetty() - { + protected boolean isNetty() { return true; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PageCountSyncOnNonTXTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PageCountSyncOnNonTXTest.java index d3d2ce910e..cd8be0beb3 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PageCountSyncOnNonTXTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PageCountSyncOnNonTXTest.java @@ -30,8 +30,7 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Before; import org.junit.Test; -public class PageCountSyncOnNonTXTest extends ActiveMQTestBase -{ +public class PageCountSyncOnNonTXTest extends ActiveMQTestBase { // We will add a random factor on the wait time private long timeToRun; @@ -40,29 +39,22 @@ public class PageCountSyncOnNonTXTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); timeToRun = 30000 + RandomUtil.randomPositiveInt() % 1000; } @Test - public void testSendNoTx() throws Exception - { + public void testSendNoTx() throws Exception { String QUEUE_NAME = "myQueue"; process = PageCountSyncServer.spawnVM(getTestDir(), timeToRun); ServerLocator locator = createNettyNonHALocator(); - try - { - locator = createNettyNonHALocator() - .setReconnectAttempts(0) - .setInitialConnectAttempts(10) - .setRetryInterval(500) - .setBlockOnDurableSend(false); + try { + locator = createNettyNonHALocator().setReconnectAttempts(0).setInitialConnectAttempts(10).setRetryInterval(500).setBlockOnDurableSend(false); ClientSessionFactory factory = locator.createSessionFactory(); ClientSession session = factory.createSession(true, true); @@ -71,27 +63,21 @@ public class PageCountSyncOnNonTXTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(QUEUE_NAME); session.start(); - ClientSession sessionTransacted = factory.createSession(false, false); ClientProducer producerTransacted = sessionTransacted.createProducer(QUEUE_NAME); ClientConsumer consumerTransacted = sessionTransacted.createConsumer(QUEUE_NAME); sessionTransacted.start(); - long start = System.currentTimeMillis(); long nmsgs = 0; - - try - { - while (true) - { + try { + while (true) { int size = RandomUtil.randomPositiveInt() % 1024; - if (size == 0) - { + if (size == 0) { size = 1024; } ClientMessage msg = session.createMessage(true); @@ -99,16 +85,13 @@ public class PageCountSyncOnNonTXTest extends ActiveMQTestBase producer.send(msg); - if (++nmsgs % 100 == 0) - { + if (++nmsgs % 100 == 0) { // complicating the test a bit with transacted sends and consuming producerTransacted.send(msg); - for (int i = 0; i < 50; i++) - { + for (int i = 0; i < 50; i++) { msg = consumerTransacted.receive(100); - if (msg != null) - { + if (msg != null) { msg.acknowledge(); } } @@ -116,44 +99,37 @@ public class PageCountSyncOnNonTXTest extends ActiveMQTestBase sessionTransacted.commit(); msg = consumer.receive(100); - if (msg != null) - { + if (msg != null) { msg.acknowledge(); } } - if (System.currentTimeMillis() - start > timeToRun) - { + if (System.currentTimeMillis() - start > timeToRun) { // this will ensure to capture a failure since the server will have crashed session.commit(); } } } - catch (Exception expected) - { + catch (Exception expected) { expected.printStackTrace(); } } - finally - { + finally { locator.close(); } assertEquals("Process didn't end as expected", 1, process.waitFor()); - ActiveMQServer server = PageCountSyncServer.createServer(getTestDir()); - try - { + try { server.start(); Thread.sleep(500); locator = createNettyNonHALocator(); - try - { + try { Queue queue = server.locateQueue(new SimpleString(QUEUE_NAME)); assertNotNull(queue); @@ -168,8 +144,7 @@ public class PageCountSyncOnNonTXTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < msgs; i++) - { + for (int i = 0; i < msgs; i++) { ClientMessage msg = consumer.receive(5000); assertNotNull(msg); // msg.acknowledge(); -- we don't ack @@ -180,21 +155,16 @@ public class PageCountSyncOnNonTXTest extends ActiveMQTestBase session.close(); - } - finally - { + finally { locator.close(); } - } - finally - { + finally { server.stop(); } } - } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PageCountSyncServer.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PageCountSyncServer.java index 9310705249..ab3e1bc010 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PageCountSyncServer.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PageCountSyncServer.java @@ -21,21 +21,18 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; /** * This is a sub process of the test {@link PageCountSyncOnNonTXTest} - * The System.out calls here are meant to be here as they will appear on the process output and test output. - * It helps to identify what happened on the test in case of failures. + * The System.out calls here are meant to be here as they will appear on the process output and test output. + * It helps to identify what happened on the test in case of failures. */ -public class PageCountSyncServer extends SpawnedServerSupport -{ - public static Process spawnVM(final String testDir, final long timeToRun) throws Exception - { +public class PageCountSyncServer extends SpawnedServerSupport { + + public static Process spawnVM(final String testDir, final long timeToRun) throws Exception { return SpawnedVMSupport.spawnVM(PageCountSyncServer.class.getName(), testDir, "" + timeToRun); } - public void perform(final String folder, final long timeToRun) throws Exception - { + public void perform(final String folder, final long timeToRun) throws Exception { - try - { + try { ActiveMQServer server = createServer(folder); server.start(); @@ -48,29 +45,24 @@ public class PageCountSyncServer extends SpawnedServerSupport System.out.println("Going down now!!!"); System.exit(1); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); System.exit(-1); } } - public static void main(String[] args) throws Exception - { + public static void main(String[] args) throws Exception { PageCountSyncServer ss = new PageCountSyncServer(); System.out.println("Args.length = " + args.length); - for (String arg: args) - { + for (String arg : args) { System.out.println("Argument: " + arg); } - if (args.length == 2) - { + if (args.length == 2) { ss.perform(args[0], Long.parseLong(args[1])); } - else - { + else { System.err.println("you were expected to pass getTestDir as an argument on SpawnVMSupport"); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PagingCounterTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PagingCounterTest.java index 3343a3febf..9fe1b68864 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PagingCounterTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PagingCounterTest.java @@ -36,8 +36,7 @@ import org.apache.activemq.artemis.core.transaction.impl.TransactionImpl; import org.junit.Before; import org.junit.Test; -public class PagingCounterTest extends ActiveMQTestBase -{ +public class PagingCounterTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -54,13 +53,11 @@ public class PagingCounterTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testCounter() throws Exception - { + public void testCounter() throws Exception { ClientSessionFactory sf = createSessionFactory(sl); ClientSession session = sf.createSession(); - try - { + try { Queue queue = server.createQueue(new SimpleString("A1"), new SimpleString("A1"), null, true, false); PageSubscriptionCounter counter = locateCounter(queue); @@ -79,21 +76,18 @@ public class PagingCounterTest extends ActiveMQTestBase assertEquals(1, counter.getValue()); } - finally - { + finally { sf.close(); session.close(); } } @Test - public void testCleanupCounter() throws Exception - { + public void testCleanupCounter() throws Exception { ClientSessionFactory sf = createSessionFactory(sl); ClientSession session = sf.createSession(); - try - { + try { Queue queue = server.createQueue(new SimpleString("A1"), new SimpleString("A1"), null, true, false); PageSubscriptionCounter counter = locateCounter(queue); @@ -102,13 +96,11 @@ public class PagingCounterTest extends ActiveMQTestBase Transaction tx = new TransactionImpl(server.getStorageManager()); - for (int i = 0; i < 2100; i++) - { + for (int i = 0; i < 2100; i++) { counter.increment(tx, 1); - if (i % 200 == 0) - { + if (i % 200 == 0) { tx.commit(); storage.waitOnOperations(); @@ -140,22 +132,18 @@ public class PagingCounterTest extends ActiveMQTestBase assertEquals(2100, counter.getValue()); } - finally - { + finally { sf.close(); session.close(); } } - @Test - public void testCleanupCounterNonPersistent() throws Exception - { + public void testCleanupCounterNonPersistent() throws Exception { ClientSessionFactory sf = createSessionFactory(sl); ClientSession session = sf.createSession(); - try - { + try { Queue queue = server.createQueue(new SimpleString("A1"), new SimpleString("A1"), null, true, false); PageSubscriptionCounter counter = locateCounter(queue); @@ -166,13 +154,11 @@ public class PagingCounterTest extends ActiveMQTestBase Transaction tx = new TransactionImpl(server.getStorageManager()); - for (int i = 0; i < 2100; i++) - { + for (int i = 0; i < 2100; i++) { counter.increment(tx, 1); - if (i % 200 == 0) - { + if (i % 200 == 0) { tx.commit(); storage.waitOnOperations(); @@ -204,16 +190,14 @@ public class PagingCounterTest extends ActiveMQTestBase assertEquals(0, counter.getValue()); } - finally - { + finally { sf.close(); session.close(); } } @Test - public void testRestartCounter() throws Exception - { + public void testRestartCounter() throws Exception { Queue queue = server.createQueue(new SimpleString("A1"), new SimpleString("A1"), null, true, false); PageSubscriptionCounter counter = locateCounter(queue); @@ -255,20 +239,15 @@ public class PagingCounterTest extends ActiveMQTestBase * @return * @throws Exception */ - private PageSubscriptionCounter locateCounter(Queue queue) throws Exception - { - PageSubscription subscription = server.getPagingManager() - .getPageStore(new SimpleString("A1")) - .getCursorProvider() - .getSubscription(queue.getID()); + private PageSubscriptionCounter locateCounter(Queue queue) throws Exception { + PageSubscription subscription = server.getPagingManager().getPageStore(new SimpleString("A1")).getCursorProvider().getSubscription(queue.getID()); PageSubscriptionCounter counter = subscription.getCounter(); return counter; } @Test - public void testPrepareCounter() throws Exception - { + public void testPrepareCounter() throws Exception { Xid xid = newXID(); Queue queue = server.createQueue(new SimpleString("A1"), new SimpleString("A1"), null, true, false); @@ -279,8 +258,7 @@ public class PagingCounterTest extends ActiveMQTestBase Transaction tx = new TransactionImpl(xid, server.getStorageManager(), 300); - for (int i = 0; i < 2000; i++) - { + for (int i = 0; i < 2000; i++) { counter.increment(tx, 1); } @@ -318,14 +296,11 @@ public class PagingCounterTest extends ActiveMQTestBase assertEquals(2000, counter.getValue()); - } - @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = newActiveMQServer(); @@ -333,16 +308,13 @@ public class PagingCounterTest extends ActiveMQTestBase sl = createInVMNonHALocator(); } - private ActiveMQServer newActiveMQServer() throws Exception - { + private ActiveMQServer newActiveMQServer() throws Exception { OperationContextImpl.clearContext(); ActiveMQServer server = super.createServer(true, false); - AddressSettings defaultSetting = new AddressSettings() - .setPageSizeBytes(10 * 1024) - .setMaxSizeBytes(20 * 1024); + AddressSettings defaultSetting = new AddressSettings().setPageSizeBytes(10 * 1024).setMaxSizeBytes(20 * 1024); server.getAddressSettingsRepository().addMatch("#", defaultSetting); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PagingReceiveTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PagingReceiveTest.java index a87a37f0c9..e1b10c61ca 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PagingReceiveTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PagingReceiveTest.java @@ -31,8 +31,7 @@ import org.apache.activemq.artemis.core.settings.impl.AddressSettings; import org.junit.Before; import org.junit.Test; -public class PagingReceiveTest extends ActiveMQTestBase -{ +public class PagingReceiveTest extends ActiveMQTestBase { private static final SimpleString ADDRESS = new SimpleString("jms.queue.catalog-service.price.change.bm"); @@ -40,15 +39,12 @@ public class PagingReceiveTest extends ActiveMQTestBase private ServerLocator locator; - protected boolean isNetty() - { + protected boolean isNetty() { return false; } - @Test - public void testReceive() throws Exception - { + public void testReceive() throws Exception { ClientMessage message = receiveMessage(); System.out.println("message received:" + message); @@ -57,16 +53,14 @@ public class PagingReceiveTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = internalCreateServer(); Queue queue = server.createQueue(ADDRESS, ADDRESS, null, true, false); queue.getPageSubscription().getPagingStore().startPaging(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { queue.getPageSubscription().getPagingStore().forceAnotherPage(); } @@ -74,13 +68,11 @@ public class PagingReceiveTest extends ActiveMQTestBase ClientSession session = sf.createSession(null, null, false, true, true, false, 0); ClientProducer prod = session.createProducer(ADDRESS); - for (int i = 0; i < 500; i++) - { + for (int i = 0; i < 500; i++) { ClientMessage msg = session.createMessage(true); msg.putIntProperty("key", i); prod.send(msg); - if (i > 0 && i % 10 == 0) - { + if (i > 0 && i % 10 == 0) { session.commit(); } } @@ -92,11 +84,9 @@ public class PagingReceiveTest extends ActiveMQTestBase internalCreateServer(); - } - private ActiveMQServer internalCreateServer() throws Exception - { + private ActiveMQServer internalCreateServer() throws Exception { final ActiveMQServer server = newActiveMQServer(); server.start(); @@ -107,8 +97,7 @@ public class PagingReceiveTest extends ActiveMQTestBase return server; } - private ClientMessage receiveMessage() throws Exception - { + private ClientMessage receiveMessage() throws Exception { final ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(null, null, false, true, true, false, 0); @@ -119,8 +108,7 @@ public class PagingReceiveTest extends ActiveMQTestBase session.commit(); - if (message != null) - { + if (message != null) { message.acknowledge(); } @@ -131,21 +119,14 @@ public class PagingReceiveTest extends ActiveMQTestBase return message; } - private ActiveMQServer newActiveMQServer() throws Exception - { + private ActiveMQServer newActiveMQServer() throws Exception { final ActiveMQServer server = createServer(true, isNetty()); - final AddressSettings settings = new AddressSettings() - .setMaxSizeBytes(67108864) - .setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE) - .setMaxRedeliveryDelay(3600000) - .setRedeliveryMultiplier(2.0) - .setRedeliveryDelay(500); + final AddressSettings settings = new AddressSettings().setMaxSizeBytes(67108864).setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE).setMaxRedeliveryDelay(3600000).setRedeliveryMultiplier(2.0).setRedeliveryDelay(500); server.getAddressSettingsRepository().addMatch("#", settings); return server; } - } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PagingSendTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PagingSendTest.java index 7bebe90906..db8a2eea0f 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PagingSendTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PagingSendTest.java @@ -46,23 +46,21 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class PagingSendTest extends ActiveMQTestBase -{ +public class PagingSendTest extends ActiveMQTestBase { + public static final SimpleString ADDRESS = new SimpleString("SimpleAddress"); private ServerLocator locator; private ActiveMQServer server; - protected boolean isNetty() - { + protected boolean isNetty() { return false; } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); Configuration config = new ConfigurationImpl(); server = newActiveMQServer(); @@ -72,13 +70,10 @@ public class PagingSendTest extends ActiveMQTestBase locator = createFactory(isNetty()); } - private ActiveMQServer newActiveMQServer() throws Exception - { + private ActiveMQServer newActiveMQServer() throws Exception { ActiveMQServer server = createServer(true, isNetty()); - AddressSettings defaultSetting = new AddressSettings() - .setPageSizeBytes(10 * 1024) - .setMaxSizeBytes(20 * 1024); + AddressSettings defaultSetting = new AddressSettings().setPageSizeBytes(10 * 1024).setMaxSizeBytes(20 * 1024); server.getAddressSettingsRepository().addMatch("#", defaultSetting); @@ -86,26 +81,21 @@ public class PagingSendTest extends ActiveMQTestBase } @Test - public void testSameMessageOverAndOverBlocking() throws Exception - { + public void testSameMessageOverAndOverBlocking() throws Exception { dotestSameMessageOverAndOver(true); } @Test - public void testSameMessageOverAndOverNonBlocking() throws Exception - { + public void testSameMessageOverAndOverNonBlocking() throws Exception { dotestSameMessageOverAndOver(false); } - public void dotestSameMessageOverAndOver(final boolean blocking) throws Exception - { + public void dotestSameMessageOverAndOver(final boolean blocking) throws Exception { // Making it synchronous, just because we want to stop sending messages as soon as the // page-store becomes in // page mode // and we could only guarantee that by setting it to synchronous - locator.setBlockOnNonDurableSend(blocking) - .setBlockOnDurableSend(blocking) - .setBlockOnAcknowledge(blocking); + locator.setBlockOnNonDurableSend(blocking).setBlockOnDurableSend(blocking).setBlockOnAcknowledge(blocking); ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(null, null, false, true, true, false, 0); @@ -119,8 +109,7 @@ public class PagingSendTest extends ActiveMQTestBase message = session.createMessage(true); message.getBodyBuffer().writeBytes(new byte[1024]); - for (int i = 0; i < 200; i++) - { + for (int i = 0; i < 200; i++) { producer.send(message); } @@ -132,14 +121,12 @@ public class PagingSendTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < 200; i++) - { + for (int i = 0; i < 200; i++) { ClientMessage message2 = consumer.receive(10000); Assert.assertNotNull(message2); - if (i == 100) - { + if (i == 100) { session.commit(); } @@ -152,8 +139,7 @@ public class PagingSendTest extends ActiveMQTestBase } @Test - public void testOrderOverTX() throws Exception - { + public void testOrderOverTX() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); ClientSession sessionConsumer = sf.createSession(true, true, 0); @@ -170,26 +156,20 @@ public class PagingSendTest extends ActiveMQTestBase // Consumer will be ready after we have commits final CountDownLatch ready = new CountDownLatch(1); - Thread tProducer = new Thread() - { + Thread tProducer = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { int commit = 0; - for (int i = 0; i < TOTAL_MESSAGES; i++) - { + for (int i = 0; i < TOTAL_MESSAGES; i++) { ClientMessage msg = sessionProducer.createMessage(true); msg.getBodyBuffer().writeBytes(new byte[1024]); msg.putIntProperty("count", i); producer.send(msg); - if (i % 100 == 0 && i > 0) - { + if (i % 100 == 0 && i > 0) { sessionProducer.commit(); - if (commit++ > 2) - { + if (commit++ > 2) { ready.countDown(); } } @@ -198,8 +178,7 @@ public class PagingSendTest extends ActiveMQTestBase sessionProducer.commit(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); errors.incrementAndGet(); } @@ -214,8 +193,7 @@ public class PagingSendTest extends ActiveMQTestBase assertTrue(ready.await(10, TimeUnit.SECONDS)); - for (int i = 0; i < TOTAL_MESSAGES; i++) - { + for (int i = 0; i < TOTAL_MESSAGES; i++) { ClientMessage msg = consumer.receive(10000); Assert.assertNotNull(msg); @@ -235,8 +213,7 @@ public class PagingSendTest extends ActiveMQTestBase } @Test - public void testPagingDoesNotDuplicateBatchMessages() throws Exception - { + public void testPagingDoesNotDuplicateBatchMessages() throws Exception { int batchSize = 20; ClientSessionFactory sf = createSessionFactory(locator); @@ -247,11 +224,9 @@ public class PagingSendTest extends ActiveMQTestBase session.createQueue(queueAddr, queueAddr, null, true); // Set up paging on the queue address - AddressSettings addressSettings = new AddressSettings() - .setPageSizeBytes(10 * 1024) - /** This actually causes the address to start paging messages after 10 x messages with 1024 payload is sent. - Presumably due to additional meta-data, message headers etc... **/ - .setMaxSizeBytes(16 * 1024); + AddressSettings addressSettings = new AddressSettings().setPageSizeBytes(10 * 1024) + /** This actually causes the address to start paging messages after 10 x messages with 1024 payload is sent. + Presumably due to additional meta-data, message headers etc... **/.setMaxSizeBytes(16 * 1024); server.getAddressSettingsRepository().addMatch("#", addressSettings); sendMessageBatch(batchSize, session, queueAddr); @@ -260,8 +235,7 @@ public class PagingSendTest extends ActiveMQTestBase checkBatchMessagesAreNotPagedTwice(queue); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { // execute the same count a couple times. This is to make sure the iterators have no impact regardless // the number of times they are called assertEquals(batchSize, processCountThroughIterator(queue)); @@ -270,8 +244,7 @@ public class PagingSendTest extends ActiveMQTestBase } @Test - public void testPagingDoesNotDuplicateBatchMessagesAfterPagingStarted() throws Exception - { + public void testPagingDoesNotDuplicateBatchMessagesAfterPagingStarted() throws Exception { int batchSize = 20; ClientSessionFactory sf = createSessionFactory(locator); @@ -282,17 +255,14 @@ public class PagingSendTest extends ActiveMQTestBase session.createQueue(queueAddr, queueAddr, null, true); // Set up paging on the queue address - AddressSettings addressSettings = new AddressSettings() - .setPageSizeBytes(10 * 1024) - /** This actually causes the address to start paging messages after 10 x messages with 1024 payload is sent. - Presumably due to additional meta-data, message headers etc... **/ - .setMaxSizeBytes(16 * 1024); + AddressSettings addressSettings = new AddressSettings().setPageSizeBytes(10 * 1024) + /** This actually causes the address to start paging messages after 10 x messages with 1024 payload is sent. + Presumably due to additional meta-data, message headers etc... **/.setMaxSizeBytes(16 * 1024); server.getAddressSettingsRepository().addMatch("#", addressSettings); int numberOfMessages = 0; // ensure the server is paging - while (!server.getPagingManager().getPageStore(queueAddr).isPaging()) - { + while (!server.getPagingManager().getPageStore(queueAddr).isPaging()) { sendMessageBatch(batchSize, session, queueAddr); numberOfMessages += batchSize; @@ -304,20 +274,19 @@ public class PagingSendTest extends ActiveMQTestBase Queue queue = server.locateQueue(queueAddr); checkBatchMessagesAreNotPagedTwice(queue); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { // execute the same count a couple times. This is to make sure the iterators have no impact regardless // the number of times they are called assertEquals(numberOfMessages, processCountThroughIterator(queue)); } } - public List sendMessageBatch(int batchSize, ClientSession session, SimpleString queueAddr) throws ActiveMQException - { + public List sendMessageBatch(int batchSize, + ClientSession session, + SimpleString queueAddr) throws ActiveMQException { List messageIds = new ArrayList(); ClientProducer producer = session.createProducer(queueAddr); - for (int i = 0; i < batchSize; i++) - { + for (int i = 0; i < batchSize; i++) { Message message = session.createMessage(true); message.getBodyBuffer().writeBytes(new byte[1024]); String id = UUID.randomUUID().toString(); @@ -336,22 +305,19 @@ public class PagingSendTest extends ActiveMQTestBase * this allows us to test only those messages that have been sent after the address has started paging (ignoring any * duplicates that may have happened before this point). */ - public void checkBatchMessagesAreNotPagedTwice(Queue queue) throws Exception - { + public void checkBatchMessagesAreNotPagedTwice(Queue queue) throws Exception { LinkedListIterator pageIterator = queue.totalIterator(); Set messageOrderSet = new HashSet(); int duplicates = 0; - while (pageIterator.hasNext()) - { + while (pageIterator.hasNext()) { MessageReference reference = pageIterator.next(); String id = reference.getMessage().getStringProperty("id"); // If add(id) returns true it means that this id was already added to this set. Hence a duplicate is found. - if (!messageOrderSet.add(id)) - { + if (!messageOrderSet.add(id)) { duplicates++; } } @@ -363,13 +329,11 @@ public class PagingSendTest extends ActiveMQTestBase * this allows us to test only those messages that have been sent after the address has started paging (ignoring any * duplicates that may have happened before this point). */ - protected int processCountThroughIterator(Queue queue) throws Exception - { + protected int processCountThroughIterator(Queue queue) throws Exception { LinkedListIterator pageIterator = queue.totalIterator(); int count = 0; - while (pageIterator.hasNext()) - { + while (pageIterator.hasNext()) { MessageReference reference = pageIterator.next(); count++; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PagingWithFailoverAndCountersTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PagingWithFailoverAndCountersTest.java index 13ea5bce36..2c62e7307e 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PagingWithFailoverAndCountersTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PagingWithFailoverAndCountersTest.java @@ -31,8 +31,7 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.After; import org.junit.Test; -public class PagingWithFailoverAndCountersTest extends ActiveMQTestBase -{ +public class PagingWithFailoverAndCountersTest extends ActiveMQTestBase { Process liveProcess; Process backupProcess; @@ -42,14 +41,12 @@ public class PagingWithFailoverAndCountersTest extends ActiveMQTestBase private static final int PORT1 = 5000; private static final int PORT2 = 5001; - private void startLive() throws Exception - { + private void startLive() throws Exception { assertNull(liveProcess); liveProcess = PagingWithFailoverServer.spawnVM(getTestDir(), PORT1, PORT2); } - private void startBackupInProcess() throws Exception - { + private void startBackupInProcess() throws Exception { assertNull(backupProcess); assertNull(inProcessBackup); inProcessBackup = new PagingWithFailoverServer(); @@ -58,36 +55,27 @@ public class PagingWithFailoverAndCountersTest extends ActiveMQTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { killLive(); killBackup(); super.tearDown(); } - private void killBackup() - { - try - { - if (backupProcess != null) - { + private void killBackup() { + try { + if (backupProcess != null) { backupProcess.destroy(); } } - catch (Throwable ignored) - { + catch (Throwable ignored) { } backupProcess = null; - - if (inProcessBackup != null) - { - try - { + if (inProcessBackup != null) { + try { inProcessBackup.getServer().stop(false); } - catch (Throwable ignored) - { + catch (Throwable ignored) { ignored.printStackTrace(); } @@ -96,29 +84,23 @@ public class PagingWithFailoverAndCountersTest extends ActiveMQTestBase } - private void killLive() - { - try - { - if (liveProcess != null) - { + private void killLive() { + try { + if (liveProcess != null) { liveProcess.destroy(); } } - catch (Throwable ignored) - { + catch (Throwable ignored) { } liveProcess = null; } - class TestThread extends Thread - { - public TestThread() - { + class TestThread extends Thread { + + public TestThread() { } - public TestThread(String name) - { + public TestThread(String name) { super(name); } @@ -126,60 +108,45 @@ public class PagingWithFailoverAndCountersTest extends ActiveMQTestBase final Object waitNotify = new Object(); private boolean failed = false; - public void failed(String message) - { + public void failed(String message) { System.err.println(message); failed = true; } - public boolean isFailed() - { + public boolean isFailed() { return failed; } - - public void stopTest() - { - synchronized (waitNotify) - { + public void stopTest() { + synchronized (waitNotify) { running = false; waitNotify.notifyAll(); } - while (this.isAlive()) - { - try - { + while (this.isAlive()) { + try { this.join(5000); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } - if (this.isAlive()) - { + if (this.isAlive()) { this.interrupt(); } } assertFalse(failed); } - public boolean isRunning(long timeWait) - { - synchronized (waitNotify) - { - try - { - if (timeWait > 0) - { + public boolean isRunning(long timeWait) { + synchronized (waitNotify) { + try { + if (timeWait > 0) { long timeout = System.currentTimeMillis() + timeWait; - while (running && timeout > System.currentTimeMillis()) - { + while (running && timeout > System.currentTimeMillis()) { waitNotify.wait(timeWait); } } } - catch (InterruptedException e) - { + catch (InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } @@ -188,8 +155,8 @@ public class PagingWithFailoverAndCountersTest extends ActiveMQTestBase } } - class ConsumerThread extends TestThread - { + class ConsumerThread extends TestThread { + ClientSessionFactory factory; String queueName; @@ -197,26 +164,21 @@ public class PagingWithFailoverAndCountersTest extends ActiveMQTestBase final AtomicInteger errors = new AtomicInteger(0); final int txSize; - ConsumerThread(ClientSessionFactory factory, String queueName, long delayEachMessage, int txSize) - { + ConsumerThread(ClientSessionFactory factory, String queueName, long delayEachMessage, int txSize) { this.factory = factory; this.queueName = queueName; this.txSize = txSize; } - public void run() - { - try - { + public void run() { + try { ClientSession session; - if (txSize == 0) - { + if (txSize == 0) { session = factory.createSession(true, true); } - else - { + else { session = factory.createSession(false, false); } @@ -227,80 +189,62 @@ public class PagingWithFailoverAndCountersTest extends ActiveMQTestBase int msgcount = 0; long currentMsg = 0; - while (isRunning(0)) - { - try - { + while (isRunning(0)) { + try { ClientMessage msg = cons.receive(100); - if (msg != null) - { + if (msg != null) { currentMsg = msg.getLongProperty("count"); - if (currentMsg < lastCommit) - { + if (currentMsg < lastCommit) { failed("Message received in duplicate out of order, LastCommit = " + lastCommit + ", currentMsg = " + currentMsg); } msg.acknowledge(); - if (txSize > 0 && msgcount > 0 && (msgcount % txSize == 0)) - { + if (txSize > 0 && msgcount > 0 && (msgcount % txSize == 0)) { session.commit(); - if (currentMsg > lastCommit) - { + if (currentMsg > lastCommit) { lastCommit = currentMsg; } - else - { + else { System.out.println("Ignoring setting lastCommit (" + lastCommit + ") <= currentMSG (" + currentMsg + ")"); } } msgcount++; } - if (msgcount % 100 == 0) - { + if (msgcount % 100 == 0) { System.out.println("received " + msgcount + " on " + queueName); } } - catch (Throwable e) - { + catch (Throwable e) { System.out.println("=====> expected Error at " + currentMsg + " with lastCommit=" + lastCommit); } } - session.close(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); errors.incrementAndGet(); } } } - class MonitorThread extends TestThread - { + class MonitorThread extends TestThread { - public MonitorThread() - { + public MonitorThread() { super("Monitor-thread"); } - public void run() - { + public void run() { ActiveMQServer server = inProcessBackup.getServer(); - try - { + try { waitForServerToStart(server); // The best to way to validate if the server is ready and operating is to send and consume at least one message // before we could do valid monitoring - try - { - ServerLocator locator = PagingWithFailoverServer.createLocator(PORT2) - .setInitialConnectAttempts(100) - .setRetryInterval(100); + try { + ServerLocator locator = PagingWithFailoverServer.createLocator(PORT2).setInitialConnectAttempts(100).setRetryInterval(100); ClientSessionFactory factory = locator.createSessionFactory(); ClientSession session = factory.createSession(); @@ -318,8 +262,7 @@ public class PagingWithFailoverAndCountersTest extends ActiveMQTestBase locator.close(); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); fail(e.getMessage()); } @@ -327,17 +270,14 @@ public class PagingWithFailoverAndCountersTest extends ActiveMQTestBase Queue queue2 = inProcessBackup.getServer().locateQueue(SimpleString.toSimpleString("cons2")); - while (isRunning(1)) - { + while (isRunning(1)) { long count = getMessageCount(queue2); - if (count < 0) - { + if (count < 0) { fail("count < 0 .... being " + count); } } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } @@ -345,14 +285,10 @@ public class PagingWithFailoverAndCountersTest extends ActiveMQTestBase } @Test - public void testValidateDeliveryAndCounters() throws Exception - { + public void testValidateDeliveryAndCounters() throws Exception { startLive(); - ServerLocator locator = PagingWithFailoverServer.createLocator(PORT1) - .setInitialConnectAttempts(100) - .setReconnectAttempts(-1) - .setRetryInterval(100); + ServerLocator locator = PagingWithFailoverServer.createLocator(PORT1).setInitialConnectAttempts(100).setReconnectAttempts(-1).setRetryInterval(100); ClientSessionFactory factory = locator.createSessionFactory(); @@ -376,34 +312,28 @@ public class PagingWithFailoverAndCountersTest extends ActiveMQTestBase long timeRun = System.currentTimeMillis() + 5000; long timeKill = System.currentTimeMillis() + 2000; - while (System.currentTimeMillis() < timeRun) - { + while (System.currentTimeMillis() < timeRun) { i++; - if (System.currentTimeMillis() > timeKill && liveProcess != null) - { + if (System.currentTimeMillis() > timeKill && liveProcess != null) { killLive(); monitor.start(); } - try - { + try { ClientMessage msg = session.createMessage(true); msg.putLongProperty("count", i); prod.send(msg); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } - try - { + try { tConsumer.stopTest(); monitor.stopTest(); } - finally - { + finally { killBackup(); killLive(); } @@ -413,8 +343,7 @@ public class PagingWithFailoverAndCountersTest extends ActiveMQTestBase verifyServer(); } - public void verifyServer() throws Exception - { + public void verifyServer() throws Exception { ServerLocator locator; ClientSessionFactory factory; ClientSession session; @@ -426,28 +355,21 @@ public class PagingWithFailoverAndCountersTest extends ActiveMQTestBase waitForServerToStart(server); Queue queue = server.locateQueue(SimpleString.toSimpleString("cons2")); - int messageCount = (int) getMessageCount(queue); assertTrue(messageCount >= 0); - locator = PagingWithFailoverServer.createLocator(PORT1) - .setInitialConnectAttempts(100) - .setReconnectAttempts(-1) - .setRetryInterval(100); + locator = PagingWithFailoverServer.createLocator(PORT1).setInitialConnectAttempts(100).setReconnectAttempts(-1).setRetryInterval(100); factory = locator.createSessionFactory(); - session = factory.createSession(); session.start(); - try - { + try { drainConsumer(session.createConsumer("cons2"), "cons2", messageCount); } - finally - { + finally { session.close(); factory.close(); locator.close(); @@ -455,10 +377,8 @@ public class PagingWithFailoverAndCountersTest extends ActiveMQTestBase } } - private void drainConsumer(ClientConsumer consumer, String name, int expectedCount) throws Exception - { - for (int i = 0; i < expectedCount; i++) - { + private void drainConsumer(ClientConsumer consumer, String name, int expectedCount) throws Exception { + for (int i = 0; i < expectedCount; i++) { ClientMessage msg = consumer.receive(5000); assertNotNull(msg); msg.acknowledge(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PagingWithFailoverBackup.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PagingWithFailoverBackup.java index 30f6ad06c7..928f8a87c3 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PagingWithFailoverBackup.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PagingWithFailoverBackup.java @@ -22,10 +22,9 @@ import org.apache.activemq.artemis.tests.util.SpawnedVMSupport; * There is no difference between this class and {@link PagingWithFailoverServer} * other than helping us identify it on the logs, as it will show with a different name through spawned logs */ -public class PagingWithFailoverBackup extends PagingWithFailoverServer -{ - public static Process spawnVM(final String testDir, final int thisPort, final int otherPort) throws Exception - { +public class PagingWithFailoverBackup extends PagingWithFailoverServer { + + public static Process spawnVM(final String testDir, final int thisPort, final int otherPort) throws Exception { return SpawnedVMSupport.spawnVM(PagingWithFailoverBackup.class.getName(), testDir, Integer.toString(thisPort), Integer.toString(otherPort), Boolean.toString(true)); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PagingWithFailoverServer.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PagingWithFailoverServer.java index e0ef5d14b8..2cc27e9f63 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PagingWithFailoverServer.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/PagingWithFailoverServer.java @@ -19,63 +19,56 @@ package org.apache.activemq.artemis.tests.integration.paging; import org.apache.activemq.artemis.tests.util.SpawnedVMSupport; import org.apache.activemq.artemis.core.server.ActiveMQServer; -public class PagingWithFailoverServer extends SpawnedServerSupport -{ - public static Process spawnVM(final String testDir, final int thisPort, final int otherPort) throws Exception - { +public class PagingWithFailoverServer extends SpawnedServerSupport { + + public static Process spawnVM(final String testDir, final int thisPort, final int otherPort) throws Exception { return spawnVM(testDir, thisPort, otherPort, false); } - public static Process spawnVM(final String testDir, final int thisPort, final int otherPort, final boolean isBackup) throws Exception - { + public static Process spawnVM(final String testDir, + final int thisPort, + final int otherPort, + final boolean isBackup) throws Exception { return SpawnedVMSupport.spawnVM(PagingWithFailoverServer.class.getName(), testDir, Integer.toString(thisPort), Integer.toString(otherPort), Boolean.toString(isBackup)); } - private ActiveMQServer server; - - public ActiveMQServer getServer() - { + public ActiveMQServer getServer() { return server; } - public void perform(final String folder, final int thisPort, final int otherPort, final boolean isBackup) throws Exception - { - try - { + public void perform(final String folder, + final int thisPort, + final int otherPort, + final boolean isBackup) throws Exception { + try { server = createServer(folder, thisPort, otherPort, isBackup); server.start(); System.out.println("Server started!!!"); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); System.exit(-1); } } - public static ActiveMQServer createServer(String folder, int thisPort, int otherPort, boolean isBackup) - { + public static ActiveMQServer createServer(String folder, int thisPort, int otherPort, boolean isBackup) { return createSharedFolderServer(folder, thisPort, otherPort, isBackup); } - public static void main(String[] arg) - { - if (arg.length != 4) - { + public static void main(String[] arg) { + if (arg.length != 4) { System.out.println("expected folder portThisServer portOtherServer isBackup"); } PagingWithFailoverServer server = new PagingWithFailoverServer(); - try - { + try { server.perform(arg[0], Integer.parseInt(arg[1]), Integer.parseInt(arg[2]), Boolean.parseBoolean(arg[3])); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); System.exit(-1); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/SpawnedServerSupport.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/SpawnedServerSupport.java index 3f0b08dbfe..68986de558 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/SpawnedServerSupport.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/paging/SpawnedServerSupport.java @@ -42,107 +42,59 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; /** * Support class for server that are using an external process on the testsuite */ -public class SpawnedServerSupport -{ +public class SpawnedServerSupport { - static ActiveMQServer createServer(String folder) - { + static ActiveMQServer createServer(String folder) { return ActiveMQServers.newActiveMQServer(createConfig(folder), true); } - static Configuration createConfig(String folder) - { - AddressSettings settings = new AddressSettings() - .setMaxDeliveryAttempts(-1) - .setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE) - .setPageSizeBytes(10 * 1024) - .setMaxSizeBytes(100 * 1024); + static Configuration createConfig(String folder) { + AddressSettings settings = new AddressSettings().setMaxDeliveryAttempts(-1).setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE).setPageSizeBytes(10 * 1024).setMaxSizeBytes(100 * 1024); - Configuration config = new ConfigurationImpl() - .setSecurityEnabled(false) - .setJournalMinFiles(2) - .setJournalFileSize(100 * 1024) - .setJournalType(ActiveMQTestBase.getDefaultJournalType()) - .setJournalCompactMinFiles(0) - .setJournalCompactPercentage(0) - .setClusterPassword(ActiveMQTestBase.CLUSTER_PASSWORD) - .setJournalDirectory(ActiveMQTestBase.getJournalDir(folder, 0, false)) - .setBindingsDirectory(ActiveMQTestBase.getBindingsDir(folder, 0, false)) - .setPagingDirectory(ActiveMQTestBase.getPageDir(folder, 0, false)) - .setLargeMessagesDirectory(ActiveMQTestBase.getLargeMessagesDir(folder, 0, false)) - .setPersistenceEnabled(true) - .addAddressesSetting("#", settings) - .addAcceptorConfiguration(new TransportConfiguration(ActiveMQTestBase.NETTY_ACCEPTOR_FACTORY)); + Configuration config = new ConfigurationImpl().setSecurityEnabled(false).setJournalMinFiles(2).setJournalFileSize(100 * 1024).setJournalType(ActiveMQTestBase.getDefaultJournalType()).setJournalCompactMinFiles(0).setJournalCompactPercentage(0).setClusterPassword(ActiveMQTestBase.CLUSTER_PASSWORD).setJournalDirectory(ActiveMQTestBase.getJournalDir(folder, 0, false)).setBindingsDirectory(ActiveMQTestBase.getBindingsDir(folder, 0, false)).setPagingDirectory(ActiveMQTestBase.getPageDir(folder, 0, false)).setLargeMessagesDirectory(ActiveMQTestBase.getLargeMessagesDir(folder, 0, false)).setPersistenceEnabled(true).addAddressesSetting("#", settings).addAcceptorConfiguration(new TransportConfiguration(ActiveMQTestBase.NETTY_ACCEPTOR_FACTORY)); return config; } - static Configuration createSharedFolderConfig(String folder, int thisport, int otherport, boolean isBackup) - { + static Configuration createSharedFolderConfig(String folder, int thisport, int otherport, boolean isBackup) { HAPolicyConfiguration haPolicyConfiguration = null; - if (isBackup) - { + if (isBackup) { haPolicyConfiguration = new SharedStoreSlavePolicyConfiguration(); - ((SharedStoreSlavePolicyConfiguration)haPolicyConfiguration).setAllowFailBack(false); + ((SharedStoreSlavePolicyConfiguration) haPolicyConfiguration).setAllowFailBack(false); } - else - { + else { haPolicyConfiguration = new SharedStoreMasterPolicyConfiguration(); } - Configuration config = createConfig(folder) - .clearAcceptorConfigurations() - .setJournalFileSize(15 * 1024 * 1024) - .addAcceptorConfiguration(createTransportConfigiguration(true, thisport)) - .addConnectorConfiguration("thisServer", createTransportConfigiguration(false, thisport)) - .addConnectorConfiguration("otherServer", createTransportConfigiguration(false, otherport)) - .setMessageExpiryScanPeriod(500) - .addClusterConfiguration(isBackup ? setupClusterConn("thisServer", "otherServer") : setupClusterConn("thisServer")) - .setHAPolicyConfiguration(haPolicyConfiguration); + Configuration config = createConfig(folder).clearAcceptorConfigurations().setJournalFileSize(15 * 1024 * 1024).addAcceptorConfiguration(createTransportConfigiguration(true, thisport)).addConnectorConfiguration("thisServer", createTransportConfigiguration(false, thisport)).addConnectorConfiguration("otherServer", createTransportConfigiguration(false, otherport)).setMessageExpiryScanPeriod(500).addClusterConfiguration(isBackup ? setupClusterConn("thisServer", "otherServer") : setupClusterConn("thisServer")).setHAPolicyConfiguration(haPolicyConfiguration); return config; } - protected static final ClusterConnectionConfiguration setupClusterConn(String connectorName, String... connectors) - { + protected static final ClusterConnectionConfiguration setupClusterConn(String connectorName, String... connectors) { List connectorList = new LinkedList(); - for (String conn : connectors) - { + for (String conn : connectors) { connectorList.add(conn); } - ClusterConnectionConfiguration ccc = new ClusterConnectionConfiguration() - .setName("cluster1") - .setAddress("jms") - .setConnectorName(connectorName) - .setRetryInterval(10) - .setDuplicateDetection(false) - .setMessageLoadBalancingType(MessageLoadBalancingType.STRICT) - .setConfirmationWindowSize(1) - .setStaticConnectors(connectorList); + ClusterConnectionConfiguration ccc = new ClusterConnectionConfiguration().setName("cluster1").setAddress("jms").setConnectorName(connectorName).setRetryInterval(10).setDuplicateDetection(false).setMessageLoadBalancingType(MessageLoadBalancingType.STRICT).setConfirmationWindowSize(1).setStaticConnectors(connectorList); return ccc; } - - public static ServerLocator createLocator(int port) - { + public static ServerLocator createLocator(int port) { TransportConfiguration config = createTransportConfigiguration(false, port); return ActiveMQClient.createServerLocator(true, config); } - - static TransportConfiguration createTransportConfigiguration(boolean acceptor, int port) - { + static TransportConfiguration createTransportConfigiguration(boolean acceptor, int port) { String className; - if (acceptor) - { + if (acceptor) { className = NettyAcceptorFactory.class.getName(); } - else - { + else { className = NettyConnectorFactory.class.getName(); } Map serverParams = new HashMap(); @@ -150,9 +102,7 @@ public class SpawnedServerSupport return new TransportConfiguration(className, serverParams); } - - static ActiveMQServer createSharedFolderServer(String folder, int thisPort, int otherPort, boolean isBackup) - { + static ActiveMQServer createSharedFolderServer(String folder, int thisPort, int otherPort, boolean isBackup) { return ActiveMQServers.newActiveMQServer(createSharedFolderConfig(folder, thisPort, otherPort, isBackup), true); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/AddressSettingsConfigurationStorageTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/AddressSettingsConfigurationStorageTest.java index 539b952297..a03c5a22b3 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/AddressSettingsConfigurationStorageTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/AddressSettingsConfigurationStorageTest.java @@ -28,21 +28,19 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -public class AddressSettingsConfigurationStorageTest extends StorageManagerTestBase -{ +public class AddressSettingsConfigurationStorageTest extends StorageManagerTestBase { + private Map mapExpectedAddresses; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); mapExpectedAddresses = new HashMap(); } - protected void addAddress(JournalStorageManager journal1, String address, AddressSettings setting) throws Exception - { + protected void addAddress(JournalStorageManager journal1, String address, AddressSettings setting) throws Exception { SimpleString str = new SimpleString(address); PersistedAddressSetting persistedSetting = new PersistedAddressSetting(str, setting); mapExpectedAddresses.put(str, persistedSetting); @@ -50,15 +48,12 @@ public class AddressSettingsConfigurationStorageTest extends StorageManagerTestB } @Test - public void testStoreSecuritySettings() throws Exception - { + public void testStoreSecuritySettings() throws Exception { createStorage(); AddressSettings setting = new AddressSettings(); - setting = new AddressSettings() - .setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK) - .setDeadLetterAddress(new SimpleString("some-test")); + setting = new AddressSettings().setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK).setDeadLetterAddress(new SimpleString("some-test")); addAddress(journal, "a2", setting); @@ -89,14 +84,12 @@ public class AddressSettingsConfigurationStorageTest extends StorageManagerTestB * @param journal1 * @throws Exception */ - private void checkAddresses(JournalStorageManager journal1) throws Exception - { + private void checkAddresses(JournalStorageManager journal1) throws Exception { List listSetting = journal1.recoverAddressSettings(); assertEquals(mapExpectedAddresses.size(), listSetting.size()); - for (PersistedAddressSetting el : listSetting) - { + for (PersistedAddressSetting el : listSetting) { PersistedAddressSetting el2 = mapExpectedAddresses.get(el.getAddressMatch()); assertEquals(el.getAddressMatch(), el2.getAddressMatch()); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/DeleteMessagesOnStartupTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/DeleteMessagesOnStartupTest.java index e80234702c..718dccc03c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/DeleteMessagesOnStartupTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/DeleteMessagesOnStartupTest.java @@ -33,15 +33,14 @@ import org.apache.activemq.artemis.core.server.impl.ServerMessageImpl; import org.junit.Assert; import org.junit.Test; -public class DeleteMessagesOnStartupTest extends StorageManagerTestBase -{ +public class DeleteMessagesOnStartupTest extends StorageManagerTestBase { + volatile boolean deleteMessages = false; ArrayList deletedMessage = new ArrayList(); @Test - public void testDeleteMessagesOnStartup() throws Exception - { + public void testDeleteMessagesOnStartup() throws Exception { createStorage(); Queue theQueue = new FakeQueue(new SimpleString("")); @@ -52,8 +51,7 @@ public class DeleteMessagesOnStartupTest extends StorageManagerTestBase journal.storeMessage(msg); - for (int i = 2; i < 100; i++) - { + for (int i = 2; i < 100; i++) { journal.storeMessage(new ServerMessageImpl(i, 100)); } @@ -71,20 +69,16 @@ public class DeleteMessagesOnStartupTest extends StorageManagerTestBase Assert.assertEquals(98, deletedMessage.size()); - for (Long messageID : deletedMessage) - { + for (Long messageID : deletedMessage) { Assert.assertTrue("messageID = " + messageID, messageID.longValue() >= 2 && messageID <= 99); } } @Override - protected JournalStorageManager createJournalStorageManager(Configuration configuration) - { - return new JournalStorageManager(configuration, execFactory, null) - { + protected JournalStorageManager createJournalStorageManager(Configuration configuration) { + return new JournalStorageManager(configuration, execFactory, null) { @Override - public void deleteMessage(final long messageID) throws Exception - { + public void deleteMessage(final long messageID) throws Exception { deletedMessage.add(messageID); super.deleteMessage(messageID); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/DeleteQueueRestartTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/DeleteQueueRestartTest.java index 0b96024e1e..f1e8cfccda 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/DeleteQueueRestartTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/DeleteQueueRestartTest.java @@ -31,8 +31,7 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Assert; import org.junit.Test; -public class DeleteQueueRestartTest extends ActiveMQTestBase -{ +public class DeleteQueueRestartTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -47,28 +46,22 @@ public class DeleteQueueRestartTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testDeleteQueueAndRestart() throws Exception - { + public void testDeleteQueueAndRestart() throws Exception { // This test could eventually pass, even when the queue was being deleted in the wrong order, // however it failed in 90% of the runs with 5 iterations. - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { setUp(); internalDeleteQueueAndRestart(); tearDown(); } } - private void internalDeleteQueueAndRestart() throws Exception - { + private void internalDeleteQueueAndRestart() throws Exception { ActiveMQServer server = createServer(true); server.start(); - ServerLocator locator = createInVMNonHALocator() - .setBlockOnDurableSend(true) - .setBlockOnNonDurableSend(true) - .setMinLargeMessageSize(1024 * 1024); + ServerLocator locator = createInVMNonHALocator().setBlockOnDurableSend(true).setBlockOnNonDurableSend(true).setMinLargeMessageSize(1024 * 1024); ClientSessionFactory factory = createSessionFactory(locator); @@ -78,8 +71,7 @@ public class DeleteQueueRestartTest extends ActiveMQTestBase ClientProducer prod = session.createProducer(DeleteQueueRestartTest.ADDRESS); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage msg = createBytesMessage(session, ActiveMQBytesMessage.TYPE, new byte[0], true); prod.send(msg); } @@ -87,19 +79,15 @@ public class DeleteQueueRestartTest extends ActiveMQTestBase final CountDownLatch count = new CountDownLatch(1); // Using another thread, as the deleteQueue is a blocked call - new Thread() - { + new Thread() { @Override - public void run() - { - try - { + public void run() { + try { session.deleteQueue(DeleteQueueRestartTest.ADDRESS); session.close(); count.countDown(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { } } }.start(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/DuplicateCacheTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/DuplicateCacheTest.java index f540c23bdd..0ac18a5f52 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/DuplicateCacheTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/DuplicateCacheTest.java @@ -25,27 +25,23 @@ import org.junit.After; import org.junit.Assert; import org.junit.Test; -public class DuplicateCacheTest extends StorageManagerTestBase -{ +public class DuplicateCacheTest extends StorageManagerTestBase { @After @Override - public void tearDown() throws Exception - { + public void tearDown() throws Exception { super.tearDown(); } @Test - public void testDuplicate() throws Exception - { + public void testDuplicate() throws Exception { createStorage(); DuplicateIDCache cache = new DuplicateIDCacheImpl(new SimpleString("test"), 2000, journal, true); TransactionImpl tx = new TransactionImpl(journal); - for (int i = 0; i < 5000; i++) - { + for (int i = 0; i < 5000; i++) { byte[] bytes = RandomUtil.randomBytes(); cache.addToCache(bytes, tx); @@ -55,8 +51,7 @@ public class DuplicateCacheTest extends StorageManagerTestBase tx = new TransactionImpl(journal); - for (int i = 0; i < 5000; i++) - { + for (int i = 0; i < 5000; i++) { byte[] bytes = RandomUtil.randomBytes(); cache.addToCache(bytes, tx); @@ -77,18 +72,15 @@ public class DuplicateCacheTest extends StorageManagerTestBase Assert.assertFalse(cache.contains(id)); } - @Test - public void testDuplicateNonPersistent() throws Exception - { + public void testDuplicateNonPersistent() throws Exception { createStorage(); DuplicateIDCache cache = new DuplicateIDCacheImpl(new SimpleString("test"), 2000, journal, false); TransactionImpl tx = new TransactionImpl(journal); - for (int i = 0; i < 5000; i++) - { + for (int i = 0; i < 5000; i++) { byte[] bytes = RandomUtil.randomBytes(); cache.addToCache(bytes, tx); @@ -96,8 +88,7 @@ public class DuplicateCacheTest extends StorageManagerTestBase tx.commit(); - for (int i = 0; i < 5000; i++) - { + for (int i = 0; i < 5000; i++) { byte[] bytes = RandomUtil.randomBytes(); cache.addToCache(bytes, null); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/ExportFormatTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/ExportFormatTest.java index 86406a865e..8833b92fd9 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/ExportFormatTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/ExportFormatTest.java @@ -31,8 +31,7 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Ignore; import org.junit.Test; -public class ExportFormatTest extends ActiveMQTestBase -{ +public class ExportFormatTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -72,9 +71,9 @@ public class ExportFormatTest extends ActiveMQTestBase "#File,JournalFileImpl: (activemq-data-2.amq id = 2, recordID = 2)"; @Test - @Ignore // Used to update the format, if you need to use this it means the data format was broken, Be careful on updating the format! - public void testCreateFormat() throws Exception - { + @Ignore + // Used to update the format, if you need to use this it means the data format was broken, Be careful on updating the format! + public void testCreateFormat() throws Exception { ActiveMQServer server = createServer(true); server.start(); @@ -85,8 +84,7 @@ public class ExportFormatTest extends ActiveMQTestBase session.createQueue("A1", "A1", true); ClientProducer producer = session.createProducer("A1"); - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { ClientMessage msg = session.createMessage(true); msg.putIntProperty("key", i); producer.send(msg); @@ -99,8 +97,7 @@ public class ExportFormatTest extends ActiveMQTestBase producer = session.createProducer("A1"); - for (int i = 5; i < 10; i++) - { + for (int i = 5; i < 10; i++) { ClientMessage msg = session.createMessage(true); msg.putIntProperty("key", i); producer.send(msg); @@ -121,17 +118,11 @@ public class ExportFormatTest extends ActiveMQTestBase } @Test - public void testConsumeFromFormat() throws Exception - { + public void testConsumeFromFormat() throws Exception { ActiveMQServer server = createServer(true); DecodeJournal.importJournal(server.getConfiguration().getJournalLocation().getAbsolutePath(), "activemq-data", "amq", 2, 102400, new StringReader(journalFile)); - DecodeJournal.importJournal(server.getConfiguration().getBindingsLocation().getAbsolutePath(), - "activemq-bindings", - "bindings", - 2, - 1048576, - new StringReader(bindingsFile)); + DecodeJournal.importJournal(server.getConfiguration().getBindingsLocation().getAbsolutePath(), "activemq-bindings", "bindings", 2, 1048576, new StringReader(bindingsFile)); server.start(); ServerLocator locator = createInVMNonHALocator(); @@ -140,8 +131,7 @@ public class ExportFormatTest extends ActiveMQTestBase session.start(); ClientConsumer consumer = session.createConsumer("A1"); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage msg = consumer.receive(5000); assertNotNull(msg); msg.acknowledge(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/JMSConnectionFactoryConfigurationStorageTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/JMSConnectionFactoryConfigurationStorageTest.java index 4cdc6f2bff..0bf1ec4ed7 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/JMSConnectionFactoryConfigurationStorageTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/JMSConnectionFactoryConfigurationStorageTest.java @@ -32,44 +32,36 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -public class JMSConnectionFactoryConfigurationStorageTest extends StorageManagerTestBase -{ +public class JMSConnectionFactoryConfigurationStorageTest extends StorageManagerTestBase { private Map mapExpectedCFs; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); mapExpectedCFs = new HashMap(); } - protected void addSetting(PersistedConnectionFactory setting) throws Exception - { + protected void addSetting(PersistedConnectionFactory setting) throws Exception { mapExpectedCFs.put(setting.getName(), setting); jmsJournal.storeConnectionFactory(setting); } @Test - public void testSettings() throws Exception - { + public void testSettings() throws Exception { createJMSStorage(); List transportConfigs = new ArrayList(); - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { transportConfigs.add("c1-" + i); transportConfigs.add("c2-" + i); } - - ConnectionFactoryConfiguration config = new ConnectionFactoryConfigurationImpl() - .setName("some-name") - .setConnectorNames(transportConfigs); + ConnectionFactoryConfiguration config = new ConnectionFactoryConfigurationImpl().setName("some-name").setConnectorNames(transportConfigs); addSetting(new PersistedConnectionFactory(config)); @@ -88,27 +80,21 @@ public class JMSConnectionFactoryConfigurationStorageTest extends StorageManager assertEquals(10, cf1.getConfig().getConnectorNames().size()); List configs = cf1.getConfig().getConnectorNames(); - for (int i = 0, j = 0; i < 10; i += 2, j++) - { + for (int i = 0, j = 0; i < 10; i += 2, j++) { assertEquals(configs.get(i), "c1-" + j); assertEquals(configs.get(i + 1), "c2-" + j); } } @Test - public void testSizeOfCF() throws Exception - { + public void testSizeOfCF() throws Exception { String[] str = new String[5]; - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { str[i] = "str" + i; } - ConnectionFactoryConfiguration config = new ConnectionFactoryConfigurationImpl() - .setName("some-name") - .setConnectorNames(new ArrayList()) - .setBindings(""); + ConnectionFactoryConfiguration config = new ConnectionFactoryConfigurationImpl().setName("some-name").setConnectorNames(new ArrayList()).setBindings(""); int size = config.getEncodeSize(); @@ -131,14 +117,12 @@ public class JMSConnectionFactoryConfigurationStorageTest extends StorageManager } @Test - public void testSettingsWithConnectorConfigs() throws Exception - { + public void testSettingsWithConnectorConfigs() throws Exception { createJMSStorage(); String[] str = new String[5]; - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { str[i] = "str" + i; } @@ -150,11 +134,7 @@ public class JMSConnectionFactoryConfigurationStorageTest extends StorageManager Map liveParams2 = new HashMap(); liveParams2.put(TransportConstants.PORT_PROP_NAME, 6665); - ConnectionFactoryConfiguration config = new ConnectionFactoryConfigurationImpl() - .setName("some-name") - .setConnectorNames(connectorConfigs) - .setBindings(str) - .setCallTimeout(RandomUtil.randomPositiveLong()); + ConnectionFactoryConfiguration config = new ConnectionFactoryConfigurationImpl().setName("some-name").setConnectorNames(connectorConfigs).setBindings(str).setCallTimeout(RandomUtil.randomPositiveLong()); List> connectors = new ArrayList>(); connectors.add(new Pair(RandomUtil.randomString(), null)); //config.setConnectorNames(connectors); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/JMSDynamicConfigTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/JMSDynamicConfigTest.java index 4bd3c8628c..1a1430d526 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/JMSDynamicConfigTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/JMSDynamicConfigTest.java @@ -27,12 +27,10 @@ import org.apache.activemq.artemis.core.persistence.impl.journal.OperationContex import org.apache.activemq.artemis.jms.server.config.ConnectionFactoryConfiguration; import org.apache.activemq.artemis.jms.server.config.impl.ConnectionFactoryConfigurationImpl; -public class JMSDynamicConfigTest extends JMSTestBase -{ +public class JMSDynamicConfigTest extends JMSTestBase { @Override - protected boolean usePersistence() - { + protected boolean usePersistence() { return true; } @@ -47,28 +45,22 @@ public class JMSDynamicConfigTest extends JMSTestBase // Public -------------------------------------------------------- @Test - public void testStart() throws Exception - { + public void testStart() throws Exception { ArrayList connectors = new ArrayList(); connectors.add("invm"); - ConnectionFactoryConfiguration cfg = new ConnectionFactoryConfigurationImpl() - .setName("tst") - .setConnectorNames(connectors) - .setBindings("tt"); + ConnectionFactoryConfiguration cfg = new ConnectionFactoryConfigurationImpl().setName("tst").setConnectorNames(connectors).setBindings("tt"); jmsServer.createConnectionFactory(true, cfg, "tst"); assertNotNull(namingContext.lookup("tst")); jmsServer.removeConnectionFactoryFromBindingRegistry("tst"); - try - { + try { namingContext.lookup("tst"); fail("failure expected"); } - catch (NamingException excepted) - { + catch (NamingException excepted) { } jmsServer.stop(); @@ -76,13 +68,11 @@ public class JMSDynamicConfigTest extends JMSTestBase OperationContextImpl.clearContext(); jmsServer.start(); - try - { + try { namingContext.lookup("tst"); fail("failure expected"); } - catch (NamingException excepted) - { + catch (NamingException excepted) { } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/JMSStorageManagerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/JMSStorageManagerTest.java index 753ad94094..9dbe0ba37c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/JMSStorageManagerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/JMSStorageManagerTest.java @@ -25,16 +25,14 @@ import org.apache.activemq.artemis.jms.persistence.config.PersistedDestination; import org.apache.activemq.artemis.jms.persistence.config.PersistedBindings; import org.apache.activemq.artemis.jms.persistence.config.PersistedType; -public class JMSStorageManagerTest extends StorageManagerTestBase -{ +public class JMSStorageManagerTest extends StorageManagerTestBase { + //https://issues.jboss.org/browse/HORNETQ-812 @Test - public void testJNDIPersistence() throws Exception - { + public void testJNDIPersistence() throws Exception { createJMSStorage(); - jmsJournal.storeDestination(new PersistedDestination(PersistedType.Queue, - "jndiPersistQueue", null, true)); + jmsJournal.storeDestination(new PersistedDestination(PersistedType.Queue, "jndiPersistQueue", null, true)); jmsJournal.addBindings(PersistedType.Queue, "jndiPersistQueue", "jndi-1"); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/RestartSMTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/RestartSMTest.java index 4a1db1fc0a..f5dea62b9c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/RestartSMTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/RestartSMTest.java @@ -36,8 +36,7 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; -public class RestartSMTest extends ActiveMQTestBase -{ +public class RestartSMTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @@ -56,16 +55,14 @@ public class RestartSMTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); execFactory = getOrderedExecutor(); } @Test - public void testRestartStorageManager() throws Exception - { + public void testRestartStorageManager() throws Exception { File testdir = new File(getTestDir()); deleteDirectory(testdir); @@ -73,8 +70,7 @@ public class RestartSMTest extends ActiveMQTestBase final JournalStorageManager journal = new JournalStorageManager(createDefaultInVMConfig(), execFactory, null); - try - { + try { journal.start(); @@ -102,15 +98,12 @@ public class RestartSMTest extends ActiveMQTestBase journal.start(); } - finally - { + finally { - try - { + try { journal.stop(); } - catch (Exception ex) - { + catch (Exception ex) { RestartSMTest.log.warn(ex.getMessage(), ex); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/RolesConfigurationStorageTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/RolesConfigurationStorageTest.java index 55f5f3e084..1ebf8ad369 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/RolesConfigurationStorageTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/RolesConfigurationStorageTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.persistence; + import org.junit.Before; import org.junit.Test; @@ -26,50 +27,30 @@ import java.util.Map; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.persistence.config.PersistedRoles; -public class RolesConfigurationStorageTest extends StorageManagerTestBase -{ +public class RolesConfigurationStorageTest extends StorageManagerTestBase { private Map mapExpectedSets; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); mapExpectedSets = new HashMap(); } - protected void addSetting(PersistedRoles setting) throws Exception - { + protected void addSetting(PersistedRoles setting) throws Exception { mapExpectedSets.put(setting.getAddressMatch(), setting); journal.storeSecurityRoles(setting); } @Test - public void testStoreSecuritySettings() throws Exception - { + public void testStoreSecuritySettings() throws Exception { createStorage(); + addSetting(new PersistedRoles("a#", "a1", "a1", "a1", "a1", "a1", "a1", "a1")); - addSetting(new PersistedRoles("a#", - "a1", - "a1", - "a1", - "a1", - "a1", - "a1", - "a1")); - - - addSetting(new PersistedRoles("a2", - "a1", - null, - "a1", - "a1", - "a1", - "a1", - "a1")); + addSetting(new PersistedRoles("a2", "a1", null, "a1", "a1", "a1", "a1", "a1")); journal.stop(); @@ -79,23 +60,9 @@ public class RolesConfigurationStorageTest extends StorageManagerTestBase checkSettings(); - addSetting(new PersistedRoles("a2", - "a1", - null, - "a1", - "a1", - "a1", - "a1", - "a1")); + addSetting(new PersistedRoles("a2", "a1", null, "a1", "a1", "a1", "a1", "a1")); - addSetting(new PersistedRoles("a3", - "a1", - null, - "a1", - "a1", - "a1", - "a1", - "a1")); + addSetting(new PersistedRoles("a3", "a1", null, "a1", "a1", "a1", "a1", "a1")); checkSettings(); @@ -115,14 +82,12 @@ public class RolesConfigurationStorageTest extends StorageManagerTestBase * @param journal * @throws Exception */ - private void checkSettings() throws Exception - { + private void checkSettings() throws Exception { List listSetting = journal.recoverPersistedRoles(); assertEquals(mapExpectedSets.size(), listSetting.size()); - for (PersistedRoles el : listSetting) - { + for (PersistedRoles el : listSetting) { PersistedRoles el2 = mapExpectedSets.get(el.getAddressMatch()); assertEquals(el, el2); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/StorageManagerTestBase.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/StorageManagerTestBase.java index 2945506593..5b2760f1a2 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/StorageManagerTestBase.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/StorageManagerTestBase.java @@ -33,8 +33,8 @@ import org.junit.Before; import java.util.ArrayList; import java.util.concurrent.ExecutorService; -public abstract class StorageManagerTestBase extends ActiveMQTestBase -{ +public abstract class StorageManagerTestBase extends ActiveMQTestBase { + protected ExecutorService executor; protected ExecutorFactory execFactory; @@ -45,8 +45,7 @@ public abstract class StorageManagerTestBase extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); execFactory = getOrderedExecutor(); @@ -54,32 +53,25 @@ public abstract class StorageManagerTestBase extends ActiveMQTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { Exception exception = null; - if (journal != null) - { - try - { + if (journal != null) { + try { journal.stop(); } - catch (Exception e) - { + catch (Exception e) { exception = e; } journal = null; } - if (jmsJournal != null) - { - try - { + if (jmsJournal != null) { + try { jmsJournal.stop(); } - catch (Exception e) - { + catch (Exception e) { if (exception != null) exception = e; } @@ -95,8 +87,7 @@ public abstract class StorageManagerTestBase extends ActiveMQTestBase /** * @throws Exception */ - protected void createStorage() throws Exception - { + protected void createStorage() throws Exception { journal = createJournalStorageManager(createDefaultInVMConfig()); journal.start(); @@ -109,8 +100,7 @@ public abstract class StorageManagerTestBase extends ActiveMQTestBase /** * @param configuration */ - protected JournalStorageManager createJournalStorageManager(Configuration configuration) - { + protected JournalStorageManager createJournalStorageManager(Configuration configuration) { JournalStorageManager jsm = new JournalStorageManager(configuration, execFactory, null); addActiveMQComponent(jsm); return jsm; @@ -119,8 +109,7 @@ public abstract class StorageManagerTestBase extends ActiveMQTestBase /** * @throws Exception */ - protected void createJMSStorage() throws Exception - { + protected void createJMSStorage() throws Exception { jmsJournal = new JMSJournalStorageManagerImpl(new TimeAndCounterIDGenerator(), createDefaultInVMConfig(), null); addActiveMQComponent(jmsJournal); jmsJournal.start(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/TransportConfigurationEncodingSupportTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/TransportConfigurationEncodingSupportTest.java index 6d911b826b..3ee521b2c5 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/TransportConfigurationEncodingSupportTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/TransportConfigurationEncodingSupportTest.java @@ -34,8 +34,7 @@ import org.apache.activemq.artemis.api.core.Pair; import org.junit.Assert; -public class TransportConfigurationEncodingSupportTest extends Assert -{ +public class TransportConfigurationEncodingSupportTest extends Assert { // Constants ----------------------------------------------------- @@ -48,8 +47,7 @@ public class TransportConfigurationEncodingSupportTest extends Assert // Public -------------------------------------------------------- @Test - public void testTransportConfiguration() throws Exception - { + public void testTransportConfiguration() throws Exception { Map params = new HashMap(); params.put(TransportConstants.PORT_PROP_NAME, 5665); params.put(TransportConstants.HOST_PROP_NAME, RandomUtil.randomString()); @@ -67,15 +65,13 @@ public class TransportConfigurationEncodingSupportTest extends Assert assertEquals(config.getName(), decoded.getName()); assertEquals(config.getFactoryClassName(), decoded.getFactoryClassName()); assertEquals(config.getParams().size(), decoded.getParams().size()); - for (String key : config.getParams().keySet()) - { + for (String key : config.getParams().keySet()) { assertEquals(config.getParams().get(key).toString(), decoded.getParams().get(key).toString()); } } @Test - public void testTransportConfigurations() throws Exception - { + public void testTransportConfigurations() throws Exception { List> connectorConfigs = new ArrayList>(); Map liveParams = new HashMap(); liveParams.put(TransportConstants.PORT_PROP_NAME, 5665); @@ -107,13 +103,11 @@ public class TransportConfigurationEncodingSupportTest extends Assert } // decoded TransportConfiguration have parameter values as String instead of primitive type - private static void assertEquivalent(TransportConfiguration expected, TransportConfiguration actual) - { + private static void assertEquivalent(TransportConfiguration expected, TransportConfiguration actual) { assertEquals(expected.getFactoryClassName(), actual.getFactoryClassName()); assertEquals(expected.getName(), actual.getName()); assertEquals(expected.getParams().size(), actual.getParams().size()); - for (Map.Entry entry : expected.getParams().entrySet()) - { + for (Map.Entry entry : expected.getParams().entrySet()) { String key = entry.getKey(); assertEquals(expected.getParams().get(key).toString(), actual.getParams().get(key).toString()); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/XmlImportExportTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/XmlImportExportTest.java index e99c72fd56..962490f6b6 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/XmlImportExportTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/persistence/XmlImportExportTest.java @@ -56,8 +56,8 @@ import org.junit.Test; /** * A test of the XML export/import functionality */ -public class XmlImportExportTest extends ActiveMQTestBase -{ +public class XmlImportExportTest extends ActiveMQTestBase { + public static final int CONSUMER_TIMEOUT = 5000; private static final String QUEUE_NAME = "A1"; private ServerLocator locator; @@ -67,8 +67,7 @@ public class XmlImportExportTest extends ActiveMQTestBase private InVMContext namingContext; @Test - public void testMessageProperties() throws Exception - { + public void testMessageProperties() throws Exception { ClientSession session = basicSetUp(); session.createQueue(QUEUE_NAME, QUEUE_NAME, true); @@ -76,15 +75,13 @@ public class XmlImportExportTest extends ActiveMQTestBase ClientProducer producer = session.createProducer(QUEUE_NAME); StringBuilder international = new StringBuilder(); - for (char x = 800; x < 1200; x++) - { + for (char x = 800; x < 1200; x++) { international.append(x); } String special = "\"<>'&"; - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { ClientMessage msg = session.createMessage(true); msg.getBodyBuffer().writeString("Bob the giant pig " + i); msg.putBooleanProperty("myBooleanProperty", Boolean.TRUE); @@ -127,8 +124,7 @@ public class XmlImportExportTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(QUEUE_NAME); session.start(); - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { ClientMessage msg = consumer.receive(CONSUMER_TIMEOUT); byte[] body = new byte[msg.getBodySize()]; msg.getBodyBuffer().readBytes(body); @@ -136,8 +132,7 @@ public class XmlImportExportTest extends ActiveMQTestBase assertEquals(msg.getBooleanProperty("myBooleanProperty"), Boolean.TRUE); assertEquals(msg.getByteProperty("myByteProperty"), new Byte("0")); byte[] bytes = msg.getBytesProperty("myBytesProperty"); - for (int j = 0; j < 5; j++) - { + for (int j = 0; j < 5; j++) { assertEquals(j, bytes[j]); } assertEquals(i * 1.6, msg.getDoubleProperty("myDoubleProperty"), 0.000001); @@ -160,8 +155,7 @@ public class XmlImportExportTest extends ActiveMQTestBase * @return ClientSession * @throws Exception */ - private ClientSession basicSetUp() throws Exception - { + private ClientSession basicSetUp() throws Exception { server = createServer(true); server.getConfiguration().getConnectorConfigurations().put("in-vm1", new TransportConfiguration(INVM_CONNECTOR_FACTORY)); server.getConfiguration().getConnectorConfigurations().put("in-vm2", new TransportConfiguration(INVM_CONNECTOR_FACTORY)); @@ -176,8 +170,7 @@ public class XmlImportExportTest extends ActiveMQTestBase } @Test - public void testMessageTypes() throws Exception - { + public void testMessageTypes() throws Exception { ClientSession session = basicSetUp(); @@ -185,7 +178,6 @@ public class XmlImportExportTest extends ActiveMQTestBase ClientProducer producer = session.createProducer(QUEUE_NAME); - ClientMessage msg = session.createMessage(Message.BYTES_TYPE, true); producer.send(msg); msg = session.createMessage(Message.DEFAULT_TYPE, true); @@ -239,8 +231,7 @@ public class XmlImportExportTest extends ActiveMQTestBase } @Test - public void testMessageAttributes() throws Exception - { + public void testMessageAttributes() throws Exception { ClientSession session = basicSetUp(); @@ -284,8 +275,7 @@ public class XmlImportExportTest extends ActiveMQTestBase } @Test - public void testBindingAttributes() throws Exception - { + public void testBindingAttributes() throws Exception { ClientSession session = basicSetUp(); session.createQueue("addressName1", "queueName1", true); @@ -323,8 +313,7 @@ public class XmlImportExportTest extends ActiveMQTestBase } @Test - public void testJmsConnectionFactoryBinding() throws Exception - { + public void testJmsConnectionFactoryBinding() throws Exception { final String clientId = "myClientId"; final long clientFailureCheckPeriod = 1; final long connectionTTl = 2; @@ -364,42 +353,7 @@ public class XmlImportExportTest extends ActiveMQTestBase ClientSession session = basicSetUp(); - jmsServer.createConnectionFactory(name, - ha, - type, - connectors, - clientId, - clientFailureCheckPeriod, - connectionTTl, - callTimeout, - callFailoverTimeout, - cacheLargeMessagesClient, - minLargeMessageSize, - compressLargeMessages, - consumerWindowSize, - consumerMaxRate, - confirmationWindowSize, - producerWindowSize, - producerMaxrate, - blockOnAcknowledge, - blockOnDurableSend, - blockOnNonDurableSend, - autoGroup, - preacknowledge, - loadBalancingPolicyClassName, - transactionBatchSize, - dupsOKBatchSize, - useGlobalPools, - scheduledThreadPoolMaxSize, - threadPoolMaxSize, - retryInterval, - retryIntervalMultiplier, - maxRetryInterval, - reconnectAttempts, - failoverOnInitialConnection, - groupId, - jndi_binding1, - jndi_binding2); + jmsServer.createConnectionFactory(name, ha, type, connectors, clientId, clientFailureCheckPeriod, connectionTTl, callTimeout, callFailoverTimeout, cacheLargeMessagesClient, minLargeMessageSize, compressLargeMessages, consumerWindowSize, consumerMaxRate, confirmationWindowSize, producerWindowSize, producerMaxrate, blockOnAcknowledge, blockOnDurableSend, blockOnNonDurableSend, autoGroup, preacknowledge, loadBalancingPolicyClassName, transactionBatchSize, dupsOKBatchSize, useGlobalPools, scheduledThreadPoolMaxSize, threadPoolMaxSize, retryInterval, retryIntervalMultiplier, maxRetryInterval, reconnectAttempts, failoverOnInitialConnection, groupId, jndi_binding1, jndi_binding2); jmsServer.createConnectionFactory("mySecondConnectionFactoryName", false, JMSFactoryType.CF, Arrays.asList("in-vm1", "in-vm2"), "mySecondConnectionFactoryName1", "mySecondConnectionFactoryName2"); @@ -431,10 +385,10 @@ public class XmlImportExportTest extends ActiveMQTestBase assertEquals(clientFailureCheckPeriod, hcf1.getClientFailureCheckPeriod()); assertEquals(connectionTTl, hcf1.getConnectionTTL()); assertEquals(callTimeout, hcf1.getCallTimeout()); -// Assert.assertEquals(callFailoverTimeout, hcf1.getCallFailoverTimeout()); // this value isn't currently persisted by org.apache.activemq.artemis.jms.server.config.impl.ConnectionFactoryConfigurationImpl.encode() -// Assert.assertEquals(cacheLargeMessagesClient, hcf1.isCacheLargeMessagesClient()); // this value isn't currently supported by org.apache.activemq.artemis.api.jms.management.JMSServerControl.createConnectionFactory(java.lang.String, boolean, boolean, int, java.lang.String, java.lang.String, java.lang.String, long, long, long, long, int, boolean, int, int, int, int, int, boolean, boolean, boolean, boolean, boolean, java.lang.String, int, int, boolean, int, int, long, double, long, int, boolean, java.lang.String) + // Assert.assertEquals(callFailoverTimeout, hcf1.getCallFailoverTimeout()); // this value isn't currently persisted by org.apache.activemq.artemis.jms.server.config.impl.ConnectionFactoryConfigurationImpl.encode() + // Assert.assertEquals(cacheLargeMessagesClient, hcf1.isCacheLargeMessagesClient()); // this value isn't currently supported by org.apache.activemq.artemis.api.jms.management.JMSServerControl.createConnectionFactory(java.lang.String, boolean, boolean, int, java.lang.String, java.lang.String, java.lang.String, long, long, long, long, int, boolean, int, int, int, int, int, boolean, boolean, boolean, boolean, boolean, java.lang.String, int, int, boolean, int, int, long, double, long, int, boolean, java.lang.String) assertEquals(minLargeMessageSize, hcf1.getMinLargeMessageSize()); -// Assert.assertEquals(compressLargeMessages, hcf1.isCompressLargeMessage()); // this value isn't currently handled properly by org.apache.activemq.artemis.jms.server.impl.JMSServerManagerImpl.createConnectionFactory(java.lang.String, boolean, org.apache.activemq.artemis.api.jms.JMSFactoryType, java.util.List, java.lang.String, long, long, long, long, boolean, int, boolean, int, int, int, int, int, boolean, boolean, boolean, boolean, boolean, java.lang.String, int, int, boolean, int, int, long, double, long, int, boolean, java.lang.String, java.lang.String...)() + // Assert.assertEquals(compressLargeMessages, hcf1.isCompressLargeMessage()); // this value isn't currently handled properly by org.apache.activemq.artemis.jms.server.impl.JMSServerManagerImpl.createConnectionFactory(java.lang.String, boolean, org.apache.activemq.artemis.api.jms.JMSFactoryType, java.util.List, java.lang.String, long, long, long, long, boolean, int, boolean, int, int, int, int, int, boolean, boolean, boolean, boolean, boolean, java.lang.String, int, int, boolean, int, int, long, double, long, int, boolean, java.lang.String, java.lang.String...)() assertEquals(consumerWindowSize, hcf1.getConsumerWindowSize()); assertEquals(consumerMaxRate, hcf1.getConsumerMaxRate()); assertEquals(confirmationWindowSize, hcf1.getConfirmationWindowSize()); @@ -464,8 +418,7 @@ public class XmlImportExportTest extends ActiveMQTestBase } @Test - public void testJmsDestination() throws Exception - { + public void testJmsDestination() throws Exception { ClientSession session = basicSetUp(); jmsServer.createQueue(true, "myQueue", null, true, "myQueueJndiBinding1", "myQueueJndiBinding2"); @@ -490,7 +443,6 @@ public class XmlImportExportTest extends ActiveMQTestBase XmlDataImporter xmlDataImporter = new XmlDataImporter(); xmlDataImporter.process(xmlInputStream, session); - assertNotNull(namingContext.lookup("myQueueJndiBinding1")); assertNotNull(namingContext.lookup("myQueueJndiBinding2")); assertNotNull(namingContext.lookup("myTopicJndiBinding1")); @@ -516,8 +468,7 @@ public class XmlImportExportTest extends ActiveMQTestBase } @Test - public void testLargeMessage() throws Exception - { + public void testLargeMessage() throws Exception { server = createServer(true); server.start(); locator = createInVMNonHALocator(); @@ -529,8 +480,7 @@ public class XmlImportExportTest extends ActiveMQTestBase fileMessage.setMessageID(1005); fileMessage.setDurable(true); - for (int i = 0; i < 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; i++) - { + for (int i = 0; i < 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; i++) { fileMessage.addBytes(new byte[]{getSamplebyte(i)}); } @@ -578,8 +528,7 @@ public class XmlImportExportTest extends ActiveMQTestBase assertEquals(2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, msg.getBodySize()); - for (int i = 0; i < 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; i++) - { + for (int i = 0; i < 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; i++) { assertEquals(getSamplebyte(i), msg.getBodyBuffer().readByte()); } @@ -588,8 +537,7 @@ public class XmlImportExportTest extends ActiveMQTestBase } @Test - public void testPartialQueue() throws Exception - { + public void testPartialQueue() throws Exception { ClientSession session = basicSetUp(); session.createQueue("myAddress", "myQueue1", true); @@ -637,26 +585,21 @@ public class XmlImportExportTest extends ActiveMQTestBase } @Test - public void testPagedMessageWithMissingBinding() throws Exception - { + public void testPagedMessageWithMissingBinding() throws Exception { final String MY_ADDRESS = "myAddress"; final String MY_QUEUE = "myQueue"; final String MY_QUEUE2 = "myQueue2"; ActiveMQServer server = createServer(true); - AddressSettings defaultSetting = new AddressSettings() - .setPageSizeBytes(10 * 1024) - .setMaxSizeBytes(20 * 1024); + AddressSettings defaultSetting = new AddressSettings().setPageSizeBytes(10 * 1024).setMaxSizeBytes(20 * 1024); server.getAddressSettingsRepository().addMatch("#", defaultSetting); server.start(); ServerLocator locator = createInVMNonHALocator() - // Making it synchronous, just because we want to stop sending messages as soon as the page-store becomes in - // page mode and we could only guarantee that by setting it to synchronous - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + // Making it synchronous, just because we want to stop sending messages as soon as the page-store becomes in + // page mode and we could only guarantee that by setting it to synchronous + .setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); ClientSessionFactory factory = locator.createSessionFactory(); ClientSession session = factory.createSession(false, true, true); @@ -669,8 +612,7 @@ public class XmlImportExportTest extends ActiveMQTestBase ClientMessage message = session.createMessage(true); message.getBodyBuffer().writeBytes(new byte[1024]); - for (int i = 0; i < 200; i++) - { + for (int i = 0; i < 200; i++) { producer.send(message); } @@ -699,8 +641,7 @@ public class XmlImportExportTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < 200; i++) - { + for (int i = 0; i < 200; i++) { message = consumer.receive(CONSUMER_TIMEOUT); assertNotNull(message); @@ -712,25 +653,20 @@ public class XmlImportExportTest extends ActiveMQTestBase } @Test - public void testPaging() throws Exception - { + public void testPaging() throws Exception { final String MY_ADDRESS = "myAddress"; final String MY_QUEUE = "myQueue"; server = createServer(true); - AddressSettings defaultSetting = new AddressSettings() - .setPageSizeBytes(10 * 1024) - .setMaxSizeBytes(20 * 1024); + AddressSettings defaultSetting = new AddressSettings().setPageSizeBytes(10 * 1024).setMaxSizeBytes(20 * 1024); server.getAddressSettingsRepository().addMatch("#", defaultSetting); server.start(); locator = createInVMNonHALocator() - // Making it synchronous, just because we want to stop sending messages as soon as the page-store becomes in - // page mode and we could only guarantee that by setting it to synchronous - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + // Making it synchronous, just because we want to stop sending messages as soon as the page-store becomes in + // page mode and we could only guarantee that by setting it to synchronous + .setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); factory = createSessionFactory(locator); ClientSession session = factory.createSession(false, true, true); @@ -742,8 +678,7 @@ public class XmlImportExportTest extends ActiveMQTestBase ClientMessage message = session.createMessage(true); message.getBodyBuffer().writeBytes(new byte[1024]); - for (int i = 0; i < 200; i++) - { + for (int i = 0; i < 200; i++) { producer.send(message); } @@ -770,8 +705,7 @@ public class XmlImportExportTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < 200; i++) - { + for (int i = 0; i < 200; i++) { message = consumer.receive(CONSUMER_TIMEOUT); assertNotNull(message); @@ -779,25 +713,20 @@ public class XmlImportExportTest extends ActiveMQTestBase } @Test - public void testPagedLargeMessage() throws Exception - { + public void testPagedLargeMessage() throws Exception { final String MY_ADDRESS = "myAddress"; final String MY_QUEUE = "myQueue"; ActiveMQServer server = createServer(true); - AddressSettings defaultSetting = new AddressSettings() - .setPageSizeBytes(10 * 1024) - .setMaxSizeBytes(20 * 1024); + AddressSettings defaultSetting = new AddressSettings().setPageSizeBytes(10 * 1024).setMaxSizeBytes(20 * 1024); server.getAddressSettingsRepository().addMatch("#", defaultSetting); server.start(); ServerLocator locator = createInVMNonHALocator() - // Making it synchronous, just because we want to stop sending messages as soon as the page-store becomes in - // page mode and we could only guarantee that by setting it to synchronous - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + // Making it synchronous, just because we want to stop sending messages as soon as the page-store becomes in + // page mode and we could only guarantee that by setting it to synchronous + .setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); ClientSessionFactory factory = locator.createSessionFactory(); ClientSession session = factory.createSession(false, true, true); @@ -809,8 +738,7 @@ public class XmlImportExportTest extends ActiveMQTestBase ClientMessage message = session.createMessage(true); message.getBodyBuffer().writeBytes(new byte[1024]); - for (int i = 0; i < 200; i++) - { + for (int i = 0; i < 200; i++) { producer.send(message); } @@ -819,8 +747,7 @@ public class XmlImportExportTest extends ActiveMQTestBase fileMessage.setMessageID(1005); fileMessage.setDurable(true); - for (int i = 0; i < 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; i++) - { + for (int i = 0; i < 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; i++) { fileMessage.addBytes(new byte[]{getSamplebyte(i)}); } @@ -855,8 +782,7 @@ public class XmlImportExportTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < 200; i++) - { + for (int i = 0; i < 200; i++) { message = consumer.receive(CONSUMER_TIMEOUT); assertNotNull(message); @@ -868,8 +794,7 @@ public class XmlImportExportTest extends ActiveMQTestBase assertEquals(2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, msg.getBodySize()); - for (int i = 0; i < 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; i++) - { + for (int i = 0; i < 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; i++) { assertEquals(getSamplebyte(i), msg.getBodyBuffer().readByte()); } @@ -879,15 +804,13 @@ public class XmlImportExportTest extends ActiveMQTestBase } @Test - public void testTransactional() throws Exception - { + public void testTransactional() throws Exception { ClientSession session = basicSetUp(); session.createQueue(QUEUE_NAME, QUEUE_NAME, true); ClientProducer producer = session.createProducer(QUEUE_NAME); - ClientMessage msg = session.createMessage(true); producer.send(msg); @@ -918,8 +841,7 @@ public class XmlImportExportTest extends ActiveMQTestBase } @Test - public void testBody() throws Exception - { + public void testBody() throws Exception { final String QUEUE_NAME = "A1"; ActiveMQServer server = createServer(true); server.start(); @@ -967,8 +889,7 @@ public class XmlImportExportTest extends ActiveMQTestBase } @Test - public void testBody2() throws Exception - { + public void testBody2() throws Exception { final String QUEUE_NAME = "A1"; ActiveMQServer server = createServer(true); server.start(); @@ -982,9 +903,8 @@ public class XmlImportExportTest extends ActiveMQTestBase ClientMessage msg = session.createMessage(true); byte[] bodyTst = new byte[10]; - for (int i = 0; i < 10; i++) - { - bodyTst[i] = (byte)(i + 1); + for (int i = 0; i < 10; i++) { + bodyTst[i] = (byte) (i + 1); } msg.getBodyBuffer().writeBytes(bodyTst); assertEquals(bodyTst.length, msg.getBodySize()); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/proton/ProtonTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/proton/ProtonTest.java index 2111baf8ca..036be19de3 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/proton/ProtonTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/proton/ProtonTest.java @@ -64,38 +64,28 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(Parameterized.class) -public class ProtonTest extends ActiveMQTestBase -{ +public class ProtonTest extends ActiveMQTestBase { // this will ensure that all tests in this class are run twice, // once with "true" passed to the class' constructor and once with "false" @Parameterized.Parameters(name = "{0}") - public static Collection getParameters() - { + public static Collection getParameters() { // these 3 are for comparison - return Arrays.asList(new Object[][]{ - {"AMQP", 0}, - {"ActiveMQ (InVM)", 1}, - {"ActiveMQ (Netty)", 2}, - {"AMQP_ANONYMOUS", 3} - }); + return Arrays.asList(new Object[][]{{"AMQP", 0}, {"ActiveMQ (InVM)", 1}, {"ActiveMQ (Netty)", 2}, {"AMQP_ANONYMOUS", 3}}); } ConnectionFactory factory; private final int protocol; - public ProtonTest(String name, int protocol) - { + public ProtonTest(String name, int protocol) { this.coreAddress = "jms.queue.exampleQueue"; this.protocol = protocol; - if (protocol == 0 || protocol == 3) - { + if (protocol == 0 || protocol == 3) { this.address = coreAddress; } - else - { + else { this.address = "exampleQueue"; } } @@ -107,8 +97,7 @@ public class ProtonTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); disableCheckThread(); server = this.createServer(true, true); @@ -147,33 +136,26 @@ public class ProtonTest extends ActiveMQTestBase @Override @After - public void tearDown() throws Exception - { - try - { - if (connection != null) - { + public void tearDown() throws Exception { + try { + if (connection != null) { connection.close(); } - for (long timeout = System.currentTimeMillis() + 1000; timeout > System.currentTimeMillis() && server.getRemotingService().getConnections().size() != 0; ) - { + for (long timeout = System.currentTimeMillis() + 1000; timeout > System.currentTimeMillis() && server.getRemotingService().getConnections().size() != 0; ) { Thread.sleep(1); } Assert.assertEquals("The remoting connection wasn't removed after connection.close()", 0, server.getRemotingService().getConnections().size()); server.stop(); } - finally - { + finally { super.tearDown(); } } - @Test - public void testTemporaryQueue() throws Throwable - { + public void testTemporaryQueue() throws Throwable { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); TemporaryQueue queue = session.createTemporaryQueue(); @@ -187,7 +169,7 @@ public class ProtonTest extends ActiveMQTestBase MessageConsumer cons = session.createConsumer(queue); connection.start(); - message = (TextMessage)cons.receive(5000); + message = (TextMessage) cons.receive(5000); Assert.assertNotNull(message); } @@ -206,35 +188,28 @@ public class ProtonTest extends ActiveMQTestBase } } */ - /** * This test eventually fails because of: https://issues.apache.org/jira/browse/QPID-4901 * * @throws Throwable */ // @Test TODO: re-enable this when we can get a version free of QPID-4901 bug - public void testBrowser() throws Throwable - { + public void testBrowser() throws Throwable { boolean success = false; - - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { // As this test was hunging, we added a protection here to fail it instead. // it seems something on the qpid client, so this failure belongs to them and we can ignore it on // our side (ActiveMQ) - success = runWithTimeout(new RunnerWithEX() - { + success = runWithTimeout(new RunnerWithEX() { @Override - public void run() throws Throwable - { + public void run() throws Throwable { int numMessages = 50; javax.jms.Queue queue = createQueue(address); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer p = session.createProducer(queue); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session.createTextMessage(); message.setText("msg:" + i); p.send(message); @@ -249,8 +224,7 @@ public class ProtonTest extends ActiveMQTestBase QueueBrowser browser = session.createBrowser(queue); Enumeration enumeration = browser.getEnumeration(); int count = 0; - while (enumeration.hasMoreElements()) - { + while (enumeration.hasMoreElements()) { Message msg = (Message) enumeration.nextElement(); Assert.assertNotNull("" + count, msg); Assert.assertTrue("" + msg, msg instanceof TextMessage); @@ -263,27 +237,23 @@ public class ProtonTest extends ActiveMQTestBase } }, 1000); - if (success) - { + if (success) { break; } - else - { + else { System.err.println("Had to make it fail!!!"); tearDown(); setUp(); } } - // There is a bug on the qpid client library currently, we can expect having to interrupt the thread on browsers. // but we can't have it on 10 iterations... something must be broken if that's the case Assert.assertTrue("Test had to interrupt on all occasions.. this is beyond the expected for the test", success); } @Test - public void testConnection() throws Exception - { + public void testConnection() throws Exception { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer cons = session.createConsumer(createQueue(address)); @@ -301,16 +271,14 @@ public class ProtonTest extends ActiveMQTestBase } @Test - public void testMessagesSentTransactional() throws Exception - { + public void testMessagesSentTransactional() throws Exception { int numMessages = 1000; javax.jms.Queue queue = createQueue(address); Session session = connection.createSession(true, Session.SESSION_TRANSACTED); MessageProducer p = session.createProducer(queue); byte[] bytes = new byte[2048]; new Random().nextBytes(bytes); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session.createTextMessage(); message.setText("msg:" + i); p.send(message); @@ -318,24 +286,21 @@ public class ProtonTest extends ActiveMQTestBase session.commit(); connection.close(); Queue q = (Queue) server.getPostOffice().getBinding(new SimpleString(coreAddress)).getBindable(); - for (long timeout = System.currentTimeMillis() + 5000; timeout > System.currentTimeMillis() && getMessageCount(q) != numMessages; ) - { + for (long timeout = System.currentTimeMillis() + 5000; timeout > System.currentTimeMillis() && getMessageCount(q) != numMessages; ) { Thread.sleep(1); } Assert.assertEquals(numMessages, getMessageCount(q)); } @Test - public void testMessagesSentTransactionalRolledBack() throws Exception - { + public void testMessagesSentTransactionalRolledBack() throws Exception { int numMessages = 1; javax.jms.Queue queue = createQueue(address); Session session = connection.createSession(true, Session.SESSION_TRANSACTED); MessageProducer p = session.createProducer(queue); byte[] bytes = new byte[2048]; new Random().nextBytes(bytes); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session.createTextMessage(); message.setText("msg:" + i); p.send(message); @@ -347,8 +312,7 @@ public class ProtonTest extends ActiveMQTestBase } @Test - public void testCancelMessages() throws Exception - { + public void testCancelMessages() throws Exception { int numMessages = 10; long time = System.currentTimeMillis(); javax.jms.Queue queue = createQueue(address); @@ -356,8 +320,7 @@ public class ProtonTest extends ActiveMQTestBase MessageProducer p = session.createProducer(queue); byte[] bytes = new byte[2048]; new Random().nextBytes(bytes); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session.createTextMessage(); message.setText("msg:" + i); p.send(message); @@ -365,9 +328,7 @@ public class ProtonTest extends ActiveMQTestBase connection.close(); Queue q = (Queue) server.getPostOffice().getBinding(new SimpleString(coreAddress)).getBindable(); - - for (long timeout = System.currentTimeMillis() + 5000; timeout > System.currentTimeMillis() && getMessageCount(q) != numMessages; ) - { + for (long timeout = System.currentTimeMillis() + 5000; timeout > System.currentTimeMillis() && getMessageCount(q) != numMessages; ) { Thread.sleep(1); } @@ -385,8 +346,7 @@ public class ProtonTest extends ActiveMQTestBase } @Test - public void testClientAckMessages() throws Exception - { + public void testClientAckMessages() throws Exception { int numMessages = 10; long time = System.currentTimeMillis(); javax.jms.Queue queue = createQueue(address); @@ -394,8 +354,7 @@ public class ProtonTest extends ActiveMQTestBase MessageProducer p = session.createProducer(queue); byte[] bytes = new byte[2048]; new Random().nextBytes(bytes); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage message = session.createTextMessage(); message.setText("msg:" + i); p.send(message); @@ -403,8 +362,7 @@ public class ProtonTest extends ActiveMQTestBase connection.close(); Queue q = (Queue) server.getPostOffice().getBinding(new SimpleString(coreAddress)).getBindable(); - for (long timeout = System.currentTimeMillis() + 5000; timeout > System.currentTimeMillis() && getMessageCount(q) != numMessages; ) - { + for (long timeout = System.currentTimeMillis() + 5000; timeout > System.currentTimeMillis() && getMessageCount(q) != numMessages; ) { Thread.sleep(1); } Assert.assertEquals(numMessages, getMessageCount(q)); @@ -412,11 +370,9 @@ public class ProtonTest extends ActiveMQTestBase connection = createConnection(); session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(queue); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { Message msg = consumer.receive(5000); - if (msg == null) - { + if (msg == null) { System.out.println("ProtonTest.testManyMessages"); } Assert.assertNotNull("" + i, msg); @@ -436,37 +392,30 @@ public class ProtonTest extends ActiveMQTestBase } @Test - public void testMessagesReceivedInParallel() throws Throwable - { + public void testMessagesReceivedInParallel() throws Throwable { final int numMessages = 50000; long time = System.currentTimeMillis(); final javax.jms.Queue queue = createQueue(address); final ArrayList exceptions = new ArrayList<>(); - Thread t = new Thread(new Runnable() - { + Thread t = new Thread(new Runnable() { @Override - public void run() - { + public void run() { Connection connectionConsumer = null; - try - { + try { // TODO the test may starve if using the same connection (dead lock maybe?) connectionConsumer = createConnection(); -// connectionConsumer = connection; + // connectionConsumer = connection; connectionConsumer.start(); Session sessionConsumer = connectionConsumer.createSession(false, Session.AUTO_ACKNOWLEDGE); final MessageConsumer consumer = sessionConsumer.createConsumer(queue); long n = 0; int count = numMessages; - while (count > 0) - { - try - { - if (++n % 1000 == 0) - { + while (count > 0) { + try { + if (++n % 1000 == 0) { System.out.println("received " + n + " messages"); } @@ -474,30 +423,24 @@ public class ProtonTest extends ActiveMQTestBase Assert.assertNotNull("Could not receive message count=" + count + " on consumer", m); count--; } - catch (JMSException e) - { + catch (JMSException e) { e.printStackTrace(); break; } } } - catch (Throwable e) - { + catch (Throwable e) { exceptions.add(e); e.printStackTrace(); } - finally - { - try - { + finally { + try { // if the createconnecion wasn't commented out - if (connectionConsumer != connection) - { + if (connectionConsumer != connection) { connectionConsumer.close(); } } - catch (Throwable ignored) - { + catch (Throwable ignored) { // NO OP } } @@ -510,8 +453,7 @@ public class ProtonTest extends ActiveMQTestBase MessageProducer p = session.createProducer(queue); p.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { BytesMessage message = session.createBytesMessage(); message.writeUTF("Hello world!!!!" + i); message.setIntProperty("count", i); @@ -519,8 +461,7 @@ public class ProtonTest extends ActiveMQTestBase } t.join(); - for (Throwable e : exceptions) - { + for (Throwable e : exceptions) { throw e; } Queue q = (Queue) server.getPostOffice().getBinding(new SimpleString(coreAddress)).getBindable(); @@ -528,7 +469,6 @@ public class ProtonTest extends ActiveMQTestBase connection.close(); Assert.assertEquals(0, getMessageCount(q)); - long taken = (System.currentTimeMillis() - time); System.out.println("Microbenchamrk ran in " + taken + " milliseconds, sending/receiving " + numMessages); @@ -538,10 +478,8 @@ public class ProtonTest extends ActiveMQTestBase } - @Test - public void testSimpleBinary() throws Throwable - { + public void testSimpleBinary() throws Throwable { final int numMessages = 500; long time = System.currentTimeMillis(); final javax.jms.Queue queue = createQueue(address); @@ -549,14 +487,12 @@ public class ProtonTest extends ActiveMQTestBase Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); byte[] bytes = new byte[0xf + 1]; - for (int i = 0; i <= 0xf; i++) - { + for (int i = 0; i <= 0xf; i++) { bytes[i] = (byte) i; } MessageProducer p = session.createProducer(queue); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { System.out.println("Sending " + i); BytesMessage message = session.createBytesMessage(); @@ -568,9 +504,7 @@ public class ProtonTest extends ActiveMQTestBase Session sessionConsumer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); final MessageConsumer consumer = sessionConsumer.createConsumer(queue); - - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { BytesMessage m = (BytesMessage) consumer.receive(5000); Assert.assertNotNull("Could not receive message count=" + i + " on consumer", m); @@ -580,21 +514,18 @@ public class ProtonTest extends ActiveMQTestBase byte[] bytesReceived = new byte[(int) size]; m.readBytes(bytesReceived); - System.out.println("Received " + ByteUtil.bytesToHex(bytesReceived, 1) + " count - " + m.getIntProperty("count")); Assert.assertArrayEquals(bytes, bytesReceived); } -// assertEquals(0, q.getMessageCount()); + // assertEquals(0, q.getMessageCount()); long taken = (System.currentTimeMillis() - time) / 1000; System.out.println("taken = " + taken); } - @Test - public void testSimpleDefault() throws Throwable - { + public void testSimpleDefault() throws Throwable { final int numMessages = 500; long time = System.currentTimeMillis(); final javax.jms.Queue queue = createQueue(address); @@ -602,14 +533,12 @@ public class ProtonTest extends ActiveMQTestBase Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); byte[] bytes = new byte[0xf + 1]; - for (int i = 0; i <= 0xf; i++) - { + for (int i = 0; i <= 0xf; i++) { bytes[i] = (byte) i; } MessageProducer p = session.createProducer(queue); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { System.out.println("Sending " + i); Message message = session.createMessage(); @@ -620,22 +549,18 @@ public class ProtonTest extends ActiveMQTestBase Session sessionConsumer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); final MessageConsumer consumer = sessionConsumer.createConsumer(queue); - - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { Message m = consumer.receive(5000); Assert.assertNotNull("Could not receive message count=" + i + " on consumer", m); } -// assertEquals(0, q.getMessageCount()); + // assertEquals(0, q.getMessageCount()); long taken = (System.currentTimeMillis() - time) / 1000; System.out.println("taken = " + taken); } - @Test - public void testSimpleMap() throws Throwable - { + public void testSimpleMap() throws Throwable { final int numMessages = 100; long time = System.currentTimeMillis(); final javax.jms.Queue queue = createQueue(address); @@ -643,8 +568,7 @@ public class ProtonTest extends ActiveMQTestBase Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer p = session.createProducer(queue); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { System.out.println("Sending " + i); MapMessage message = session.createMapMessage(); @@ -653,13 +577,10 @@ public class ProtonTest extends ActiveMQTestBase p.send(message); } - Session sessionConsumer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); final MessageConsumer consumer = sessionConsumer.createConsumer(queue); - - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { MapMessage m = (MapMessage) consumer.receive(5000); Assert.assertNotNull("Could not receive message count=" + i + " on consumer", m); @@ -667,23 +588,20 @@ public class ProtonTest extends ActiveMQTestBase Assert.assertEquals(i, m.getIntProperty("count")); } -// assertEquals(0, q.getMessageCount()); + // assertEquals(0, q.getMessageCount()); long taken = (System.currentTimeMillis() - time) / 1000; System.out.println("taken = " + taken); } - @Test - public void testSimpleStream() throws Throwable - { + public void testSimpleStream() throws Throwable { final int numMessages = 100; final javax.jms.Queue queue = createQueue(address); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer p = session.createProducer(queue); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { StreamMessage message = session.createStreamMessage(); message.writeInt(i); message.writeBoolean(true); @@ -691,13 +609,10 @@ public class ProtonTest extends ActiveMQTestBase p.send(message); } - Session sessionConsumer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); final MessageConsumer consumer = sessionConsumer.createConsumer(queue); - - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { StreamMessage m = (StreamMessage) consumer.receive(5000); Assert.assertNotNull("Could not receive message count=" + i + " on consumer", m); @@ -709,8 +624,7 @@ public class ProtonTest extends ActiveMQTestBase } @Test - public void testSimpleText() throws Throwable - { + public void testSimpleText() throws Throwable { final int numMessages = 100; long time = System.currentTimeMillis(); final javax.jms.Queue queue = createQueue(address); @@ -718,34 +632,28 @@ public class ProtonTest extends ActiveMQTestBase Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer p = session.createProducer(queue); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { System.out.println("Sending " + i); TextMessage message = session.createTextMessage("text" + i); p.send(message); } - Session sessionConsumer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); final MessageConsumer consumer = sessionConsumer.createConsumer(queue); - - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage m = (TextMessage) consumer.receive(5000); Assert.assertNotNull("Could not receive message count=" + i + " on consumer", m); Assert.assertEquals("text" + i, m.getText()); } -// assertEquals(0, q.getMessageCount()); + // assertEquals(0, q.getMessageCount()); long taken = (System.currentTimeMillis() - time) / 1000; System.out.println("taken = " + taken); } - @Test - public void testSimpleObject() throws Throwable - { + public void testSimpleObject() throws Throwable { final int numMessages = 1; long time = System.currentTimeMillis(); final javax.jms.Queue queue = createQueue(address); @@ -753,20 +661,16 @@ public class ProtonTest extends ActiveMQTestBase Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer p = session.createProducer(queue); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { System.out.println("Sending " + i); ObjectMessage message = session.createObjectMessage(new AnythingSerializable(i)); p.send(message); } - Session sessionConsumer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); final MessageConsumer consumer = sessionConsumer.createConsumer(queue); - - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ObjectMessage msg = (ObjectMessage) consumer.receive(5000); Assert.assertNotNull("Could not receive message count=" + i + " on consumer", msg); @@ -774,15 +678,13 @@ public class ProtonTest extends ActiveMQTestBase Assert.assertEquals(i, someSerialThing.getCount()); } -// assertEquals(0, q.getMessageCount()); + // assertEquals(0, q.getMessageCount()); long taken = (System.currentTimeMillis() - time) / 1000; System.out.println("taken = " + taken); } - @Test - public void testSelector() throws Exception - { + public void testSelector() throws Exception { javax.jms.Queue queue = createQueue(address); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer p = session.createProducer(queue); @@ -803,8 +705,7 @@ public class ProtonTest extends ActiveMQTestBase } @Test - public void testProperties() throws Exception - { + public void testProperties() throws Exception { javax.jms.Queue queue = createQueue(address); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer p = session.createProducer(queue); @@ -836,19 +737,15 @@ public class ProtonTest extends ActiveMQTestBase connection.close(); } - @Test - public void testUsingPlainAMQP() throws Exception - { - if (this.protocol != 0 && protocol != 3) - { + public void testUsingPlainAMQP() throws Exception { + if (this.protocol != 0 && protocol != 3) { return; } org.apache.qpid.amqp_1_0.client.Connection connection = null; - try - { + try { // Step 1. Create an amqp qpid 1.0 connection connection = new org.apache.qpid.amqp_1_0.client.Connection("localhost", 5672, null, null); @@ -874,22 +771,17 @@ public class ProtonTest extends ActiveMQTestBase // Step 8. acknowledge the message rec.acknowledge(m); } - finally - { - if (connection != null) - { + finally { + if (connection != null) { // Step 9. close the connection connection.close(); } } } - @Test - public void testUsingPlainAMQPSenderWithNonExistentQueue() throws Exception - { - if (this.protocol != 0 && protocol != 3) - { + public void testUsingPlainAMQPSenderWithNonExistentQueue() throws Exception { + if (this.protocol != 0 && protocol != 3) { return; } @@ -897,8 +789,7 @@ public class ProtonTest extends ActiveMQTestBase org.apache.qpid.amqp_1_0.client.Connection connection = null; - try - { + try { // Step 1. Create an amqp qpid 1.0 connection connection = new org.apache.qpid.amqp_1_0.client.Connection("localhost", 5672, null, null); @@ -926,22 +817,17 @@ public class ProtonTest extends ActiveMQTestBase // Step 8. acknowledge the message rec.acknowledge(m); } - finally - { - if (connection != null) - { + finally { + if (connection != null) { // Step 9. close the connection connection.close(); } } } - @Test - public void testUsingPlainAMQPReceiverWithNonExistentQueue() throws Exception - { - if (this.protocol != 0 && protocol != 3) - { + public void testUsingPlainAMQPReceiverWithNonExistentQueue() throws Exception { + if (this.protocol != 0 && protocol != 3) { return; } @@ -949,8 +835,7 @@ public class ProtonTest extends ActiveMQTestBase org.apache.qpid.amqp_1_0.client.Connection connection = null; - try - { + try { // Step 1. Create an amqp qpid 1.0 connection connection = new org.apache.qpid.amqp_1_0.client.Connection("localhost", 5672, null, null); @@ -978,82 +863,62 @@ public class ProtonTest extends ActiveMQTestBase // Step 8. acknowledge the message rec.acknowledge(m); } - finally - { - if (connection != null) - { + finally { + if (connection != null) { // Step 9. close the connection connection.close(); } } } - - private javax.jms.Queue createQueue(String address) - { - if (protocol == 0 || protocol == 3) - { + private javax.jms.Queue createQueue(String address) { + if (protocol == 0 || protocol == 3) { return new QueueImpl(address); } - else - { + else { return ActiveMQJMSClient.createQueue(address); } } - - private javax.jms.Connection createConnection() throws JMSException - { + private javax.jms.Connection createConnection() throws JMSException { Connection connection; - if (protocol == 3) - { + if (protocol == 3) { factory = new ConnectionFactoryImpl("localhost", 5672, null, null); connection = factory.createConnection(); - connection.setExceptionListener(new ExceptionListener() - { + connection.setExceptionListener(new ExceptionListener() { @Override - public void onException(JMSException exception) - { + public void onException(JMSException exception) { exception.printStackTrace(); } }); connection.start(); } - else if (protocol == 0) - { + else if (protocol == 0) { factory = new ConnectionFactoryImpl("localhost", 5672, "guest", "guest"); connection = factory.createConnection(); - connection.setExceptionListener(new ExceptionListener() - { + connection.setExceptionListener(new ExceptionListener() { @Override - public void onException(JMSException exception) - { + public void onException(JMSException exception) { exception.printStackTrace(); } }); connection.start(); } - else - { + else { TransportConfiguration transport; - - if (protocol == 1) - { + if (protocol == 1) { transport = new TransportConfiguration(INVM_CONNECTOR_FACTORY); } - else - { + else { transport = new TransportConfiguration(NETTY_CONNECTOR_FACTORY); } factory = new ActiveMQConnectionFactory(false, transport); connection = factory.createConnection("guest", "guest"); - connection.setExceptionListener(new ExceptionListener() - { + connection.setExceptionListener(new ExceptionListener() { @Override - public void onException(JMSException exception) - { + public void onException(JMSException exception) { exception.printStackTrace(); } }); @@ -1063,18 +928,15 @@ public class ProtonTest extends ActiveMQTestBase return connection; } + public static class AnythingSerializable implements Serializable { - public static class AnythingSerializable implements Serializable - { private int count; - public AnythingSerializable(int count) - { + public AnythingSerializable(int count) { this.count = count; } - public int getCount() - { + public int getCount() { return count; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQActivationTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQActivationTest.java index b2e070dc2a..2fa557866b 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQActivationTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQActivationTest.java @@ -22,8 +22,7 @@ import org.junit.Test; import org.apache.activemq.artemis.ra.ActiveMQResourceAdapter; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -public class ActiveMQActivationTest extends ActiveMQTestBase -{ +public class ActiveMQActivationTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -36,8 +35,7 @@ public class ActiveMQActivationTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testValidateJNDIParameters() throws Exception - { + public void testValidateJNDIParameters() throws Exception { ActiveMQResourceAdapter qResourceAdapter = new ActiveMQResourceAdapter(); ActiveMQActivationSpec spec = new ActiveMQActivationSpec(); spec.setResourceAdapter(qResourceAdapter); @@ -49,10 +47,8 @@ public class ActiveMQActivationTest extends ActiveMQTestBase assertEquals("d", spec.getParsedJndiParams().get("c")); assertEquals("a1,a2,a3", spec.getParsedJndiParams().get("url")); - } - // Package protected --------------------------------------------- // Protected ----------------------------------------------------- diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQClusteredTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQClusteredTest.java index 77b9441349..9f31308f45 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQClusteredTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQClusteredTest.java @@ -29,15 +29,13 @@ import org.junit.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -public class ActiveMQClusteredTest extends ActiveMQRAClusteredTestBase -{ +public class ActiveMQClusteredTest extends ActiveMQRAClusteredTestBase { /* * the second server has no queue so this tests for partial initialisation * */ @Test - public void testShutdownOnPartialConnect() throws Exception - { + public void testShutdownOnPartialConnect() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); qResourceAdapter.setHA(true); @@ -56,21 +54,20 @@ public class ActiveMQClusteredTest extends ActiveMQRAClusteredTestBase DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, false); qResourceAdapter.endpointActivation(endpointFactory, spec); //make sure thet activation didnt start, i.e. no MDB consumers - assertEquals(((Queue)server.getPostOffice().getBinding(MDBQUEUEPREFIXEDSIMPLE).getBindable()).getConsumerCount(), 0); + assertEquals(((Queue) server.getPostOffice().getBinding(MDBQUEUEPREFIXEDSIMPLE).getBindable()).getConsumerCount(), 0); qResourceAdapter.endpointDeactivation(endpointFactory, spec); qResourceAdapter.stop(); } - /** * https://bugzilla.redhat.com/show_bug.cgi?id=1029076 * Look at the logs for this test, if you see exceptions it's an issue. + * * @throws Exception */ @Test - public void testNonDurableInCluster() throws Exception - { + public void testNonDurableInCluster() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); qResourceAdapter.start(ctx); @@ -91,15 +88,13 @@ public class ActiveMQClusteredTest extends ActiveMQRAClusteredTestBase message.getBodyBuffer().writeString("test"); clientProducer.send(message); - - ActiveMQActivation activation = lookupActivation(qResourceAdapter); + ActiveMQActivation activation = lookupActivation(qResourceAdapter); SimpleString tempQueue = activation.getTopicTemporaryQueue(); assertNotNull(server.locateQueue(tempQueue)); assertNotNull(secondaryServer.locateQueue(tempQueue)); - latch.await(5, TimeUnit.SECONDS); assertNotNull(endpoint.lastMessage); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQMessageHandlerSecurityTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQMessageHandlerSecurityTest.java index 3d69447c18..883c6a6fdb 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQMessageHandlerSecurityTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQMessageHandlerSecurityTest.java @@ -28,17 +28,15 @@ import org.apache.activemq.artemis.ra.inflow.ActiveMQActivationSpec; import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManagerImpl; import org.junit.Test; -public class ActiveMQMessageHandlerSecurityTest extends ActiveMQRATestBase -{ +public class ActiveMQMessageHandlerSecurityTest extends ActiveMQRATestBase { + @Override - public boolean useSecurity() - { + public boolean useSecurity() { return true; } @Test - public void testSimpleMessageReceivedOnQueueWithSecurityFails() throws Exception - { + public void testSimpleMessageReceivedOnQueueWithSecurityFails() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); qResourceAdapter.start(ctx); @@ -62,8 +60,7 @@ public class ActiveMQMessageHandlerSecurityTest extends ActiveMQRATestBase } @Test - public void testSimpleMessageReceivedOnQueueWithSecuritySucceeds() throws Exception - { + public void testSimpleMessageReceivedOnQueueWithSecuritySucceeds() throws Exception { ActiveMQSecurityManagerImpl securityManager = (ActiveMQSecurityManagerImpl) server.getSecurityManager(); securityManager.getConfiguration().addUser("testuser", "testpassword"); securityManager.getConfiguration().addRole("testuser", "arole"); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQMessageHandlerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQMessageHandlerTest.java index 5761aa2516..a5636cfc80 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQMessageHandlerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQMessageHandlerTest.java @@ -40,18 +40,15 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase -{ +public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase { @Override - public boolean useSecurity() - { + public boolean useSecurity() { return false; } @Test - public void testSimpleMessageReceivedOnQueue() throws Exception - { + public void testSimpleMessageReceivedOnQueue() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); qResourceAdapter.start(ctx); @@ -82,8 +79,7 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase } @Test - public void testSimpleMessageReceivedOnQueueManyMessages() throws Exception - { + public void testSimpleMessageReceivedOnQueueManyMessages() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); qResourceAdapter.start(ctx); @@ -99,8 +95,7 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase qResourceAdapter.endpointActivation(endpointFactory, spec); ClientSession session = locator.createSessionFactory().createSession(); ClientProducer clientProducer = session.createProducer(MDBQUEUEPREFIXED); - for (int i = 0; i < 15; i++) - { + for (int i = 0; i < 15; i++) { ClientMessage message = session.createMessage(true); message.getBodyBuffer().writeString("teststring" + i); clientProducer.send(message); @@ -114,8 +109,7 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase } @Test - public void testSimpleMessageReceivedOnQueueManyMessagesAndInterrupt() throws Exception - { + public void testSimpleMessageReceivedOnQueueManyMessagesAndInterrupt() throws Exception { final int SIZE = 14; ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); @@ -133,8 +127,7 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase qResourceAdapter.endpointActivation(endpointFactory, spec); ClientSession session = locator.createSessionFactory().createSession(); ClientProducer clientProducer = session.createProducer(MDBQUEUEPREFIXED); - for (int i = 0; i < SIZE; i++) - { + for (int i = 0; i < SIZE; i++) { ClientMessage message = session.createMessage(true); message.getBodyBuffer().writeString("teststring" + i); clientProducer.send(message); @@ -153,8 +146,7 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase } @Test - public void testSimpleMessageReceivedOnQueueManyMessagesAndInterruptTimeout() throws Exception - { + public void testSimpleMessageReceivedOnQueueManyMessagesAndInterruptTimeout() throws Exception { final int SIZE = 14; ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); @@ -173,8 +165,7 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase qResourceAdapter.endpointActivation(endpointFactory, spec); ClientSession session = locator.createSessionFactory().createSession(); ClientProducer clientProducer = session.createProducer(MDBQUEUEPREFIXED); - for (int i = 0; i < SIZE; i++) - { + for (int i = 0; i < SIZE; i++) { ClientMessage message = session.createMessage(true); message.getBodyBuffer().writeString("teststring" + i); clientProducer.send(message); @@ -192,19 +183,18 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase qResourceAdapter.stop(); } + /** * @return */ - protected ActiveMQResourceAdapter newResourceAdapter() - { + protected ActiveMQResourceAdapter newResourceAdapter() { ActiveMQResourceAdapter qResourceAdapter = new ActiveMQResourceAdapter(); qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY); return qResourceAdapter; } @Test - public void testServerShutdownAndReconnect() throws Exception - { + public void testServerShutdownAndReconnect() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); qResourceAdapter.setReconnectAttempts(-1); qResourceAdapter.setCallTimeout(500L); @@ -214,23 +204,19 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase // This is just to register a listener final CountDownLatch failedLatch = new CountDownLatch(1); ClientSessionFactoryInternal factoryListener = (ClientSessionFactoryInternal) qResourceAdapter.getDefaultActiveMQConnectionFactory().getServerLocator().createSessionFactory(); - factoryListener.addFailureListener(new SessionFailureListener() - { + factoryListener.addFailureListener(new SessionFailureListener() { @Override - public void connectionFailed(ActiveMQException exception, boolean failedOver) - { + public void connectionFailed(ActiveMQException exception, boolean failedOver) { } @Override - public void connectionFailed(ActiveMQException exception, boolean failedOver, String scaleDownTargetNodeID) - { + public void connectionFailed(ActiveMQException exception, boolean failedOver, String scaleDownTargetNodeID) { connectionFailed(exception, failedOver); } @Override - public void beforeReconnect(ActiveMQException exception) - { + public void beforeReconnect(ActiveMQException exception) { failedLatch.countDown(); } }); @@ -254,7 +240,6 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase assertNotNull(endpoint.lastMessage); assertEquals(endpoint.lastMessage.getCoreMessage().getBodyBuffer().readString(), "teststring"); - server.stop(); assertTrue(failedLatch.await(5, TimeUnit.SECONDS)); @@ -265,27 +250,23 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase } @Test - public void testInvalidAckMode() throws Exception - { + public void testInvalidAckMode() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); qResourceAdapter.start(ctx); ActiveMQActivationSpec spec = new ActiveMQActivationSpec(); - try - { + try { spec.setAcknowledgeMode("CLIENT_ACKNOWLEDGE"); fail("should throw exception"); } - catch (java.lang.IllegalArgumentException e) - { + catch (java.lang.IllegalArgumentException e) { //pass } qResourceAdapter.stop(); } @Test - public void testSimpleMessageReceivedOnQueueInLocalTX() throws Exception - { + public void testSimpleMessageReceivedOnQueueInLocalTX() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); qResourceAdapter.setUseLocalTx(true); MyBootstrapContext ctx = new MyBootstrapContext(); @@ -309,7 +290,6 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase assertNull(endpoint.lastMessage); - latch = new CountDownLatch(1); endpoint.reset(latch); clientProducer.send(message); @@ -324,8 +304,7 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase } @Test - public void testSimpleMessageReceivedOnQueueWithSelector() throws Exception - { + public void testSimpleMessageReceivedOnQueueWithSelector() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); qResourceAdapter.start(ctx); @@ -361,8 +340,7 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase } @Test - public void testEndpointDeactivated() throws Exception - { + public void testEndpointDeactivated() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); qResourceAdapter.start(ctx); @@ -385,8 +363,7 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase } @Test - public void testMaxSessions() throws Exception - { + public void testMaxSessions() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); qResourceAdapter.start(ctx); @@ -408,8 +385,7 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase } @Test - public void testSimpleTopic() throws Exception - { + public void testSimpleTopic() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); qResourceAdapter.start(ctx); @@ -439,8 +415,7 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase } @Test - public void testDurableSubscription() throws Exception - { + public void testDurableSubscription() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); qResourceAdapter.start(ctx); @@ -496,8 +471,7 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase } @Test - public void testNonDurableSubscription() throws Exception - { + public void testNonDurableSubscription() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); qResourceAdapter.start(ctx); @@ -545,8 +519,7 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase //https://issues.jboss.org/browse/JBPAPP-8017 @Test - public void testNonDurableSubscriptionDeleteAfterCrash() throws Exception - { + public void testNonDurableSubscriptionDeleteAfterCrash() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); qResourceAdapter.start(ctx); @@ -589,8 +562,7 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase } @Test - public void testSelectorChangedWithTopic() throws Exception - { + public void testSelectorChangedWithTopic() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); @@ -652,8 +624,7 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase } @Test - public void testSharedSubscription() throws Exception - { + public void testSharedSubscription() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); qResourceAdapter.start(ctx); @@ -682,7 +653,6 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase spec2.setShareSubscriptions(true); spec2.setMaxSession(1); - CountDownLatch latch = new CountDownLatch(5); DummyMessageEndpoint endpoint = new DummyMessageEndpoint(latch); DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, false); @@ -696,8 +666,7 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase ClientSession session = locator.createSessionFactory().createSession(); ClientProducer clientProducer = session.createProducer("jms.topic.mdbTopic"); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage message = session.createMessage(true); message.getBodyBuffer().writeString("" + i); clientProducer.send(message); @@ -717,8 +686,7 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase } @Test - public void testNullSubscriptionName() throws Exception - { + public void testNullSubscriptionName() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); qResourceAdapter.start(ctx); @@ -733,26 +701,21 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase spec.setShareSubscriptions(true); spec.setMaxSession(1); - CountDownLatch latch = new CountDownLatch(5); DummyMessageEndpoint endpoint = new DummyMessageEndpoint(latch); DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, false); - try - { + try { qResourceAdapter.endpointActivation(endpointFactory, spec); fail(); } - catch (Exception e) - { + catch (Exception e) { assertTrue(e instanceof InvalidPropertyException); - assertEquals("subscriptionName", ((InvalidPropertyException)e).getInvalidPropertyDescriptors()[0].getName()); + assertEquals("subscriptionName", ((InvalidPropertyException) e).getInvalidPropertyDescriptors()[0].getName()); } } - @Test - public void testBadDestinationType() throws Exception - { + public void testBadDestinationType() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); qResourceAdapter.start(ctx); @@ -769,21 +732,18 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase CountDownLatch latch = new CountDownLatch(5); DummyMessageEndpoint endpoint = new DummyMessageEndpoint(latch); DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, false); - try - { + try { qResourceAdapter.endpointActivation(endpointFactory, spec); fail(); } - catch (Exception e) - { + catch (Exception e) { assertTrue(e instanceof InvalidPropertyException); - assertEquals("destinationType", ((InvalidPropertyException)e).getInvalidPropertyDescriptors()[0].getName()); + assertEquals("destinationType", ((InvalidPropertyException) e).getInvalidPropertyDescriptors()[0].getName()); } } @Test - public void testSelectorNotChangedWithTopic() throws Exception - { + public void testSelectorNotChangedWithTopic() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); qResourceAdapter.start(ctx); @@ -833,20 +793,17 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase } - class ExceptionDummyMessageEndpoint extends DummyMessageEndpoint - { + class ExceptionDummyMessageEndpoint extends DummyMessageEndpoint { + boolean throwException = true; - public ExceptionDummyMessageEndpoint(CountDownLatch latch) - { + public ExceptionDummyMessageEndpoint(CountDownLatch latch) { super(latch); } @Override - public void onMessage(Message message) - { - if (throwException) - { + public void onMessage(Message message) { + if (throwException) { throwException = false; throw new IllegalStateException("boo!"); } @@ -854,16 +811,15 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase } } - class MultipleEndpoints extends DummyMessageEndpoint - { + class MultipleEndpoints extends DummyMessageEndpoint { + private final CountDownLatch latch; private final CountDownLatch latchDone; private final boolean pause; AtomicInteger messages = new AtomicInteger(0); AtomicInteger interrupted = new AtomicInteger(0); - public MultipleEndpoints(CountDownLatch latch, CountDownLatch latchDone, boolean pause) - { + public MultipleEndpoints(CountDownLatch latch, CountDownLatch latchDone, boolean pause) { super(latch); this.latch = latch; this.latchDone = latchDone; @@ -871,46 +827,36 @@ public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase } @Override - public void beforeDelivery(Method method) throws NoSuchMethodException, ResourceException - { + public void beforeDelivery(Method method) throws NoSuchMethodException, ResourceException { } @Override - public void afterDelivery() throws ResourceException - { + public void afterDelivery() throws ResourceException { } @Override - public void release() - { + public void release() { } @Override - public void onMessage(Message message) - { - try - { + public void onMessage(Message message) { + try { latch.countDown(); - if (pause && messages.getAndIncrement() % 2 == 0) - { - try - { + if (pause && messages.getAndIncrement() % 2 == 0) { + try { IntegrationTestLogger.LOGGER.info("pausing for 2 secs"); Thread.sleep(2000); } - catch (InterruptedException e) - { + catch (InterruptedException e) { interrupted.incrementAndGet(); } } } - finally - { - if (latchDone != null) - { + finally { + if (latchDone != null) { latchDone.countDown(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQMessageHandlerXATest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQMessageHandlerXATest.java index eb64ecb23f..11af3cd84f 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQMessageHandlerXATest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQMessageHandlerXATest.java @@ -36,17 +36,15 @@ import java.lang.reflect.Method; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -public class ActiveMQMessageHandlerXATest extends ActiveMQRATestBase -{ +public class ActiveMQMessageHandlerXATest extends ActiveMQRATestBase { + @Override - public boolean useSecurity() - { + public boolean useSecurity() { return false; } @Test - public void testXACommit() throws Exception - { + public void testXACommit() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); qResourceAdapter.start(ctx); @@ -77,8 +75,7 @@ public class ActiveMQMessageHandlerXATest extends ActiveMQRATestBase } @Test - public void testXACommitWhenStopping() throws Exception - { + public void testXACommitWhenStopping() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); qResourceAdapter.start(ctx); @@ -117,8 +114,7 @@ public class ActiveMQMessageHandlerXATest extends ActiveMQRATestBase } @Test - public void testXACommitInterruptsWhenStopping() throws Exception - { + public void testXACommitInterruptsWhenStopping() throws Exception { ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); qResourceAdapter.start(ctx); @@ -157,8 +153,7 @@ public class ActiveMQMessageHandlerXATest extends ActiveMQRATestBase } @Test - public void testXARollback() throws Exception - { + public void testXARollback() throws Exception { setupDLQ(10); ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter(); qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY); @@ -196,103 +191,86 @@ public class ActiveMQMessageHandlerXATest extends ActiveMQRATestBase qResourceAdapter.stop(); } - class XADummyEndpoint extends DummyMessageEndpoint - { + class XADummyEndpoint extends DummyMessageEndpoint { + private Xid xid; - public XADummyEndpoint(CountDownLatch latch) - { + public XADummyEndpoint(CountDownLatch latch) { super(latch); xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); } @Override - public void beforeDelivery(Method method) throws NoSuchMethodException, ResourceException - { + public void beforeDelivery(Method method) throws NoSuchMethodException, ResourceException { super.beforeDelivery(method); - try - { + try { xaResource.start(xid, XAResource.TMNOFLAGS); } - catch (XAException e) - { + catch (XAException e) { throw new ResourceException(e.getMessage(), e); } } @Override - public void afterDelivery() throws ResourceException - { - try - { + public void afterDelivery() throws ResourceException { + try { xaResource.end(xid, XAResource.TMSUCCESS); } - catch (XAException e) - { + catch (XAException e) { throw new ResourceException(e.getMessage(), e); } super.afterDelivery(); } - public void rollback() throws XAException - { + public void rollback() throws XAException { xaResource.rollback(xid); } - public void prepare() throws XAException - { + public void prepare() throws XAException { xaResource.prepare(xid); } - public void commit() throws XAException - { + public void commit() throws XAException { xaResource.commit(xid, false); } } - class PausingXADummyEndpoint extends XADummyEndpoint - { + + class PausingXADummyEndpoint extends XADummyEndpoint { + private final CountDownLatch beforeDeliveryLatch; boolean interrupted = false; - public PausingXADummyEndpoint(CountDownLatch latch,CountDownLatch beforeDeliveryLatch) - { + public PausingXADummyEndpoint(CountDownLatch latch, CountDownLatch beforeDeliveryLatch) { super(latch); this.beforeDeliveryLatch = beforeDeliveryLatch; } @Override - public void beforeDelivery(Method method) throws NoSuchMethodException, ResourceException - { + public void beforeDelivery(Method method) throws NoSuchMethodException, ResourceException { super.beforeDelivery(method); beforeDeliveryLatch.countDown(); } @Override - public void onMessage(Message message) - { + public void onMessage(Message message) { super.onMessage(message); - try - { + try { Thread.sleep(2000); } - catch (InterruptedException e) - { + catch (InterruptedException e) { interrupted = true; } } @Override - public void release() - { - try - { + public void release() { + try { prepare(); commit(); } - catch (XAException e) - { + catch (XAException e) { e.printStackTrace(); } super.release(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQRAClusteredTestBase.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQRAClusteredTestBase.java index d52519ccbc..a2e69e1486 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQRAClusteredTestBase.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQRAClusteredTestBase.java @@ -28,8 +28,8 @@ import org.apache.activemq.artemis.jms.server.impl.JMSServerManagerImpl; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Before; -public class ActiveMQRAClusteredTestBase extends ActiveMQRATestBase -{ +public class ActiveMQRAClusteredTestBase extends ActiveMQRATestBase { + protected ActiveMQServer secondaryServer; protected JMSServerManagerImpl secondaryJmsServer; protected TransportConfiguration secondaryConnector; @@ -37,8 +37,7 @@ public class ActiveMQRAClusteredTestBase extends ActiveMQRATestBase @Before @Override - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); primaryConnector = new TransportConfiguration(INVM_CONNECTOR_FACTORY); @@ -53,21 +52,18 @@ public class ActiveMQRAClusteredTestBase extends ActiveMQRATestBase waitForTopology(secondaryServer, 2); } - protected Configuration createDefaultConfig(boolean netty) throws Exception - { + protected Configuration createDefaultConfig(boolean netty) throws Exception { return createSecondaryDefaultConfig(netty, false); } - protected Configuration createSecondaryDefaultConfig(boolean netty, boolean secondary) throws Exception - { + protected Configuration createSecondaryDefaultConfig(boolean netty, boolean secondary) throws Exception { HashMap invmMap = new HashMap(); HashMap nettyMap = new HashMap(); String primaryConnectorName = "invm2"; String secondaryConnectorName = "invm"; String directoryPrefix = "first"; - if (secondary) - { + if (secondary) { invmMap.put(TransportConstants.SERVER_ID_PROP_NAME, "1"); nettyMap.put("port", "5545"); primaryConnectorName = "invm"; @@ -75,18 +71,7 @@ public class ActiveMQRAClusteredTestBase extends ActiveMQRATestBase directoryPrefix = "second"; } - ConfigurationImpl configuration = createBasicConfig() - .setJMXManagementEnabled(false) - .clearAcceptorConfigurations() - .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, invmMap)) - .addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, nettyMap)) - .setJournalDirectory(getTestDir() + "/" + directoryPrefix + "Journal/") - .setBindingsDirectory(getTestDir() + "/" + directoryPrefix + "Bind/") - .setLargeMessagesDirectory(getTestDir() + "/" + directoryPrefix + "Large/") - .setPagingDirectory(getTestDir() + "/" + directoryPrefix + "Page/") - .addConnectorConfiguration(secondaryConnectorName, secondaryConnector) - .addConnectorConfiguration(primaryConnectorName, primaryConnector) - .addClusterConfiguration(ActiveMQTestBase.basicClusterConnectionConfig(secondaryConnectorName, primaryConnectorName)); + ConfigurationImpl configuration = createBasicConfig().setJMXManagementEnabled(false).clearAcceptorConfigurations().addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, invmMap)).addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, nettyMap)).setJournalDirectory(getTestDir() + "/" + directoryPrefix + "Journal/").setBindingsDirectory(getTestDir() + "/" + directoryPrefix + "Bind/").setLargeMessagesDirectory(getTestDir() + "/" + directoryPrefix + "Large/").setPagingDirectory(getTestDir() + "/" + directoryPrefix + "Page/").addConnectorConfiguration(secondaryConnectorName, secondaryConnector).addConnectorConfiguration(primaryConnectorName, primaryConnector).addClusterConfiguration(ActiveMQTestBase.basicClusterConnectionConfig(secondaryConnectorName, primaryConnectorName)); return configuration; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQRATestBase.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQRATestBase.java index 6254c4378b..f5895c1dd7 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQRATestBase.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQRATestBase.java @@ -45,8 +45,8 @@ import java.util.Map; import java.util.Timer; import java.util.concurrent.CountDownLatch; -public abstract class ActiveMQRATestBase extends JMSTestBase -{ +public abstract class ActiveMQRATestBase extends JMSTestBase { + protected ServerLocator locator; protected static final String MDBQUEUE = "mdbQueue"; @@ -56,8 +56,7 @@ public abstract class ActiveMQRATestBase extends JMSTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = createInVMNonHALocator(); createQueue(true, MDBQUEUE); @@ -65,60 +64,50 @@ public abstract class ActiveMQRATestBase extends JMSTestBase setupDLQ(1); } - protected void setupDLQ(int maxDeliveries) - { - AddressSettings settings = new AddressSettings() - .setDeadLetterAddress(SimpleString.toSimpleString("jms.queue." + DLQ)) - .setMaxDeliveryAttempts(maxDeliveries); + protected void setupDLQ(int maxDeliveries) { + AddressSettings settings = new AddressSettings().setDeadLetterAddress(SimpleString.toSimpleString("jms.queue." + DLQ)).setMaxDeliveryAttempts(maxDeliveries); server.getAddressSettingsRepository().addMatch("#", settings); } - protected ActiveMQActivation lookupActivation(ActiveMQResourceAdapter qResourceAdapter) - { + protected ActiveMQActivation lookupActivation(ActiveMQResourceAdapter qResourceAdapter) { Map activations = qResourceAdapter.getActivations(); assertEquals(1, activations.size()); return activations.values().iterator().next(); } - protected ActiveMQResourceAdapter newResourceAdapter() - { + protected ActiveMQResourceAdapter newResourceAdapter() { ActiveMQResourceAdapter qResourceAdapter = new ActiveMQResourceAdapter(); qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY); return qResourceAdapter; } + protected class DummyMessageEndpointFactory implements MessageEndpointFactory { - protected class DummyMessageEndpointFactory implements MessageEndpointFactory - { private DummyMessageEndpoint endpoint; private final boolean isDeliveryTransacted; - public DummyMessageEndpointFactory(DummyMessageEndpoint endpoint, boolean deliveryTransacted) - { + public DummyMessageEndpointFactory(DummyMessageEndpoint endpoint, boolean deliveryTransacted) { this.endpoint = endpoint; isDeliveryTransacted = deliveryTransacted; } @Override - public MessageEndpoint createEndpoint(XAResource xaResource) throws UnavailableException - { - if (xaResource != null) - { + public MessageEndpoint createEndpoint(XAResource xaResource) throws UnavailableException { + if (xaResource != null) { endpoint.setXAResource(xaResource); } return endpoint; } - public boolean isDeliveryTransacted(Method method) throws NoSuchMethodException - { + public boolean isDeliveryTransacted(Method method) throws NoSuchMethodException { return isDeliveryTransacted; } } - protected class DummyMessageEndpoint implements MessageEndpoint, MessageListener - { + protected class DummyMessageEndpoint implements MessageEndpoint, MessageListener { + public CountDownLatch latch; public ActiveMQMessage lastMessage; @@ -129,101 +118,93 @@ public abstract class ActiveMQRATestBase extends JMSTestBase volatile boolean inAfterDelivery = false; - public DummyMessageEndpoint(CountDownLatch latch) - { + public DummyMessageEndpoint(CountDownLatch latch) { this.latch = latch; } - public void beforeDelivery(Method method) throws NoSuchMethodException, ResourceException - { + public void beforeDelivery(Method method) throws NoSuchMethodException, ResourceException { } - public void afterDelivery() throws ResourceException - { - if (latch != null) - { + public void afterDelivery() throws ResourceException { + if (latch != null) { latch.countDown(); } } - public void release() - { + public void release() { released = true; } - public void onMessage(Message message) - { + public void onMessage(Message message) { lastMessage = (ActiveMQMessage) message; System.err.println(message); } - public void reset(CountDownLatch latch) - { + public void reset(CountDownLatch latch) { this.latch = latch; lastMessage = null; } - public void setXAResource(XAResource xaResource) - { + public void setXAResource(XAResource xaResource) { this.xaResource = xaResource; } } - public class MyBootstrapContext implements BootstrapContext - { + public class MyBootstrapContext implements BootstrapContext { + WorkManager workManager = new DummyWorkManager(); - public Timer createTimer() throws UnavailableException - { + public Timer createTimer() throws UnavailableException { return null; } @Override - public WorkManager getWorkManager() - { + public WorkManager getWorkManager() { return workManager; } @Override - public XATerminator getXATerminator() - { + public XATerminator getXATerminator() { return null; } - class DummyWorkManager implements WorkManager - { + class DummyWorkManager implements WorkManager { + @Override - public void doWork(Work work) throws WorkException - { + public void doWork(Work work) throws WorkException { } @Override - public void doWork(Work work, long l, ExecutionContext executionContext, WorkListener workListener) throws WorkException - { + public void doWork(Work work, + long l, + ExecutionContext executionContext, + WorkListener workListener) throws WorkException { } @Override - public long startWork(Work work) throws WorkException - { + public long startWork(Work work) throws WorkException { return 0; } @Override - public long startWork(Work work, long l, ExecutionContext executionContext, WorkListener workListener) throws WorkException - { + public long startWork(Work work, + long l, + ExecutionContext executionContext, + WorkListener workListener) throws WorkException { return 0; } @Override - public void scheduleWork(Work work) throws WorkException - { + public void scheduleWork(Work work) throws WorkException { work.run(); } @Override - public void scheduleWork(Work work, long l, ExecutionContext executionContext, WorkListener workListener) throws WorkException - { + public void scheduleWork(Work work, + long l, + ExecutionContext executionContext, + WorkListener workListener) throws WorkException { } } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/DummyTransaction.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/DummyTransaction.java index 011be40e92..a01da8f4ec 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/DummyTransaction.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/DummyTransaction.java @@ -31,43 +31,36 @@ import javax.transaction.xa.XAResource; * Time: 15:13 * To change this template use File | Settings | File Templates. */ -class DummyTransaction implements Transaction -{ +class DummyTransaction implements Transaction { + @Override - public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, SystemException - { + public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, SystemException { } @Override - public void rollback() throws IllegalStateException, SystemException - { + public void rollback() throws IllegalStateException, SystemException { } @Override - public void setRollbackOnly() throws IllegalStateException, SystemException - { + public void setRollbackOnly() throws IllegalStateException, SystemException { } @Override - public int getStatus() throws SystemException - { + public int getStatus() throws SystemException { return 0; } @Override - public boolean enlistResource(XAResource xaResource) throws RollbackException, IllegalStateException, SystemException - { + public boolean enlistResource(XAResource xaResource) throws RollbackException, IllegalStateException, SystemException { return false; } @Override - public boolean delistResource(XAResource xaResource, int i) throws IllegalStateException, SystemException - { + public boolean delistResource(XAResource xaResource, int i) throws IllegalStateException, SystemException { return false; } @Override - public void registerSynchronization(Synchronization synchronization) throws RollbackException, IllegalStateException, SystemException - { + public void registerSynchronization(Synchronization synchronization) throws RollbackException, IllegalStateException, SystemException { } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/DummyTransactionManager.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/DummyTransactionManager.java index d879a8728b..f46e7df1f6 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/DummyTransactionManager.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/DummyTransactionManager.java @@ -25,57 +25,48 @@ import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.TransactionManager; -public class DummyTransactionManager implements TransactionManager -{ +public class DummyTransactionManager implements TransactionManager { + protected static DummyTransactionManager tm = new DummyTransactionManager(); public Transaction tx; @Override - public void begin() throws NotSupportedException, SystemException - { + public void begin() throws NotSupportedException, SystemException { } @Override - public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException - { + public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException { } @Override - public void rollback() throws IllegalStateException, SecurityException, SystemException - { + public void rollback() throws IllegalStateException, SecurityException, SystemException { } @Override - public void setRollbackOnly() throws IllegalStateException, SystemException - { + public void setRollbackOnly() throws IllegalStateException, SystemException { } @Override - public int getStatus() throws SystemException - { + public int getStatus() throws SystemException { return 0; } @Override - public Transaction getTransaction() throws SystemException - { + public Transaction getTransaction() throws SystemException { return tx; } @Override - public void setTransactionTimeout(int i) throws SystemException - { + public void setTransactionTimeout(int i) throws SystemException { } @Override - public Transaction suspend() throws SystemException - { + public Transaction suspend() throws SystemException { return null; } @Override - public void resume(Transaction transaction) throws InvalidTransactionException, IllegalStateException, SystemException - { + public void resume(Transaction transaction) throws InvalidTransactionException, IllegalStateException, SystemException { } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/JMSContextTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/JMSContextTest.java index 011fd2889f..70c31f4bdb 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/JMSContextTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/JMSContextTest.java @@ -35,22 +35,20 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -public class JMSContextTest extends ActiveMQRATestBase -{ +public class JMSContextTest extends ActiveMQRATestBase { + private ActiveMQResourceAdapter resourceAdapter; ActiveMQRAConnectionManager qraConnectionManager = new ActiveMQRAConnectionManager(); private ActiveMQRAConnectionFactory qraConnectionFactory; - public TransactionManager getTm() - { + public TransactionManager getTm() { return DummyTransactionManager.tm; } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { useDummyTransactionManager(); super.setUp(); ActiveMQSecurityManagerImpl securityManager = (ActiveMQSecurityManagerImpl) server.getSecurityManager(); @@ -75,11 +73,9 @@ public class JMSContextTest extends ActiveMQRATestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { DummyTransactionManager.tm.tx = null; - if (resourceAdapter != null) - { + if (resourceAdapter != null) { resourceAdapter.stop(); } @@ -88,82 +84,66 @@ public class JMSContextTest extends ActiveMQRATestBase } @Test - public void testCreateContextThrowsException() throws Exception - { + public void testCreateContextThrowsException() throws Exception { JMSContext jmsctx = qraConnectionFactory.createContext(); - try - { + try { jmsctx.createContext(JMSContext.AUTO_ACKNOWLEDGE); fail("expected JMSRuntimeException"); } - catch (JMSRuntimeException e) - { + catch (JMSRuntimeException e) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("wrong exception thrown: " + e); } } @Test - public void testCreateXAContextThrowsException() throws Exception - { + public void testCreateXAContextThrowsException() throws Exception { JMSContext jmsctx = qraConnectionFactory.createXAContext(); - try - { + try { jmsctx.createContext(JMSContext.AUTO_ACKNOWLEDGE); fail("expected JMSRuntimeException"); } - catch (JMSRuntimeException e) - { + catch (JMSRuntimeException e) { //pass } - catch (Exception e) - { + catch (Exception e) { fail("wrong exception thrown: " + e); } } @Test - public void sessionTransactedTestActiveJTATx() throws Exception - { - try - { + public void sessionTransactedTestActiveJTATx() throws Exception { + try { qraConnectionFactory.createContext(JMSContext.SESSION_TRANSACTED); fail(); } - catch (JMSRuntimeException e) - { + catch (JMSRuntimeException e) { //pass } } @Test - public void sessionTransactedTestNoActiveJTATx() throws Exception - { + public void sessionTransactedTestNoActiveJTATx() throws Exception { ((DummyTransactionManager) ServiceUtils.getTransactionManager()).tx = new DummyTransaction(); JMSContext context = qraConnectionFactory.createContext(JMSContext.SESSION_TRANSACTED); assertEquals(context.getSessionMode(), JMSContext.AUTO_ACKNOWLEDGE); } @Test - public void clientAckTestActiveJTATx() throws Exception - { - try - { + public void clientAckTestActiveJTATx() throws Exception { + try { qraConnectionFactory.createContext(JMSContext.CLIENT_ACKNOWLEDGE); fail(); } - catch (JMSRuntimeException e) - { + catch (JMSRuntimeException e) { //pass } } @Test - public void clientAckTestNoActiveJTATx() throws Exception - { + public void clientAckTestNoActiveJTATx() throws Exception { ((DummyTransactionManager) ServiceUtils.getTransactionManager()).tx = new DummyTransaction(); JMSContext context = qraConnectionFactory.createContext(JMSContext.CLIENT_ACKNOWLEDGE); assertEquals(context.getSessionMode(), JMSContext.AUTO_ACKNOWLEDGE); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/OutgoingConnectionTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/OutgoingConnectionTest.java index bbd940013f..3498ec3daf 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/OutgoingConnectionTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/OutgoingConnectionTest.java @@ -57,15 +57,14 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -public class OutgoingConnectionTest extends ActiveMQRATestBase -{ +public class OutgoingConnectionTest extends ActiveMQRATestBase { + private ActiveMQResourceAdapter resourceAdapter; private ActiveMQRAConnectionFactory qraConnectionFactory; private ActiveMQRAManagedConnectionFactory mcf; @Override - public boolean useSecurity() - { + public boolean useSecurity() { return true; } @@ -73,8 +72,7 @@ public class OutgoingConnectionTest extends ActiveMQRATestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); ActiveMQSecurityManagerImpl securityManager = (ActiveMQSecurityManagerImpl) server.getSecurityManager(); securityManager.getConfiguration().addUser("testuser", "testpassword"); @@ -100,10 +98,8 @@ public class OutgoingConnectionTest extends ActiveMQRATestBase @Override @After - public void tearDown() throws Exception - { - if (resourceAdapter != null) - { + public void tearDown() throws Exception { + if (resourceAdapter != null) { resourceAdapter.stop(); } @@ -112,8 +108,7 @@ public class OutgoingConnectionTest extends ActiveMQRATestBase } @Test - public void testSimpleMessageSendAndReceiveXA() throws Exception - { + public void testSimpleMessageSendAndReceiveXA() throws Exception { Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); XAQueueConnection queueConnection = qraConnectionFactory.createXAQueueConnection(); XASession s = queueConnection.createXASession(); @@ -144,8 +139,7 @@ public class OutgoingConnectionTest extends ActiveMQRATestBase } @Test - public void testInexistentUserOnCreateConnection() throws Exception - { + public void testInexistentUserOnCreateConnection() throws Exception { resourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); resourceAdapter.start(ctx); @@ -154,50 +148,41 @@ public class OutgoingConnectionTest extends ActiveMQRATestBase ActiveMQRAConnectionFactory qraConnectionFactory = new ActiveMQRAConnectionFactoryImpl(mcf, qraConnectionManager); Connection conn = null; - try - { + try { conn = qraConnectionFactory.createConnection("IDont", "Exist"); fail("Exception was expected"); } - catch (JMSSecurityException expected) - { + catch (JMSSecurityException expected) { } conn = qraConnectionFactory.createConnection("testuser", "testpassword"); conn.close(); - - try - { + try { XAConnection xaconn = qraConnectionFactory.createXAConnection("IDont", "Exist"); fail("Exception was expected"); } - catch (JMSSecurityException expected) - { + catch (JMSSecurityException expected) { } XAConnection xaconn = qraConnectionFactory.createXAConnection("testuser", "testpassword"); xaconn.close(); - try - { + try { TopicConnection topicconn = qraConnectionFactory.createTopicConnection("IDont", "Exist"); fail("Exception was expected"); } - catch (JMSSecurityException expected) - { + catch (JMSSecurityException expected) { } TopicConnection topicconn = qraConnectionFactory.createTopicConnection("testuser", "testpassword"); topicconn.close(); - try - { + try { QueueConnection queueconn = qraConnectionFactory.createQueueConnection("IDont", "Exist"); fail("Exception was expected"); } - catch (JMSSecurityException expected) - { + catch (JMSSecurityException expected) { } QueueConnection queueconn = qraConnectionFactory.createQueueConnection("testuser", "testpassword"); @@ -205,12 +190,10 @@ public class OutgoingConnectionTest extends ActiveMQRATestBase mcf.stop(); - } @Test - public void testMultipleSessionsThrowsException() throws Exception - { + public void testMultipleSessionsThrowsException() throws Exception { resourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); resourceAdapter.start(ctx); @@ -219,19 +202,16 @@ public class OutgoingConnectionTest extends ActiveMQRATestBase ActiveMQRAConnectionFactory qraConnectionFactory = new ActiveMQRAConnectionFactoryImpl(mcf, qraConnectionManager); QueueConnection queueConnection = qraConnectionFactory.createQueueConnection(); Session s = queueConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - try - { + try { Session s2 = queueConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); fail("should throw javax,jms.IllegalStateException: Only allowed one session per connection. See the J2EE spec, e.g. J2EE1.4 Section 6.6"); } - catch (JMSException e) - { + catch (JMSException e) { } } @Test - public void testConnectionCredentials() throws Exception - { + public void testConnectionCredentials() throws Exception { resourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); resourceAdapter.start(ctx); @@ -247,8 +227,7 @@ public class OutgoingConnectionTest extends ActiveMQRATestBase } @Test - public void testConnectionCredentialsFail() throws Exception - { + public void testConnectionCredentialsFail() throws Exception { resourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); resourceAdapter.start(ctx); @@ -262,43 +241,37 @@ public class OutgoingConnectionTest extends ActiveMQRATestBase queueConnection.close(); mc.destroy(); - try - { + try { queueConnection = qraConnectionFactory.createQueueConnection("testuser", "testwrongpassword"); queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE).close(); fail("should throw esxception"); } - catch (JMSException e) - { + catch (JMSException e) { //pass } } @Test - public void testConnectionCredentialsFailRecovery() throws Exception - { + public void testConnectionCredentialsFailRecovery() throws Exception { resourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); resourceAdapter.start(ctx); ActiveMQRAManagedConnectionFactory mcf = new ActiveMQRAManagedConnectionFactory(); mcf.setResourceAdapter(resourceAdapter); ActiveMQRAConnectionFactory qraConnectionFactory = new ActiveMQRAConnectionFactoryImpl(mcf, qraConnectionManager); - try - { + try { QueueConnection queueConnection = qraConnectionFactory.createQueueConnection("testuser", "testwrongpassword"); queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE).close(); fail("should throw esxception"); } - catch (JMSException e) - { + catch (JMSException e) { //make sure the recovery is null assertNull(mcf.getResourceRecovery()); } } @Test - public void testConnectionCredentialsOKRecovery() throws Exception - { + public void testConnectionCredentialsOKRecovery() throws Exception { resourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); resourceAdapter.start(ctx); @@ -312,8 +285,7 @@ public class OutgoingConnectionTest extends ActiveMQRATestBase } @Test - public void testJMSContext() throws Exception - { + public void testJMSContext() throws Exception { resourceAdapter = newResourceAdapter(); MyBootstrapContext ctx = new MyBootstrapContext(); resourceAdapter.start(ctx); @@ -327,15 +299,14 @@ public class OutgoingConnectionTest extends ActiveMQRATestBase } @Test - public void testOutgoingXAResourceWrapper() throws Exception - { + public void testOutgoingXAResourceWrapper() throws Exception { XAQueueConnection queueConnection = qraConnectionFactory.createXAQueueConnection(); XASession s = queueConnection.createXASession(); XAResource resource = s.getXAResource(); assertTrue(resource instanceof ActiveMQXAResourceWrapper); - ActiveMQXAResourceWrapperImpl xaResourceWrapper = (ActiveMQXAResourceWrapperImpl) resource; + ActiveMQXAResourceWrapperImpl xaResourceWrapper = (ActiveMQXAResourceWrapperImpl) resource; assertTrue(xaResourceWrapper.getJndiName().equals("java://jmsXA NodeId:" + server.getNodeID())); assertTrue(xaResourceWrapper.getProductVersion().equals(VersionLoader.getVersion().getFullVersion())); assertTrue(xaResourceWrapper.getProductName().equals(ActiveMQResourceAdapter.PRODUCT_NAME)); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/OutgoingConnectionTestJTA.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/OutgoingConnectionTestJTA.java index 77d99f2e42..313f682ee6 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/OutgoingConnectionTestJTA.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/OutgoingConnectionTestJTA.java @@ -50,30 +50,28 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -public class OutgoingConnectionTestJTA extends ActiveMQRATestBase -{ +public class OutgoingConnectionTestJTA extends ActiveMQRATestBase { + protected ActiveMQResourceAdapter resourceAdapter; protected ActiveMQRAConnectionFactory qraConnectionFactory; protected ActiveMQRAManagedConnectionFactory mcf; ActiveMQRAConnectionManager qraConnectionManager = new ActiveMQRAConnectionManager(); @Override - public boolean useSecurity() - { + public boolean useSecurity() { return true; } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { useDummyTransactionManager(); super.setUp(); - ((ActiveMQSecurityManagerImpl)server.getSecurityManager()).getConfiguration().addUser("testuser", "testpassword"); - ((ActiveMQSecurityManagerImpl)server.getSecurityManager()).getConfiguration().addUser("guest", "guest"); - ((ActiveMQSecurityManagerImpl)server.getSecurityManager()).getConfiguration().setDefaultUser("guest"); - ((ActiveMQSecurityManagerImpl)server.getSecurityManager()).getConfiguration().addRole("testuser", "arole"); - ((ActiveMQSecurityManagerImpl)server.getSecurityManager()).getConfiguration().addRole("guest", "arole"); + ((ActiveMQSecurityManagerImpl) server.getSecurityManager()).getConfiguration().addUser("testuser", "testpassword"); + ((ActiveMQSecurityManagerImpl) server.getSecurityManager()).getConfiguration().addUser("guest", "guest"); + ((ActiveMQSecurityManagerImpl) server.getSecurityManager()).getConfiguration().setDefaultUser("guest"); + ((ActiveMQSecurityManagerImpl) server.getSecurityManager()).getConfiguration().addRole("testuser", "arole"); + ((ActiveMQSecurityManagerImpl) server.getSecurityManager()).getConfiguration().addRole("guest", "arole"); Role role = new Role("arole", true, true, true, true, true, true, true); Set roles = new HashSet(); roles.add(role); @@ -92,11 +90,9 @@ public class OutgoingConnectionTestJTA extends ActiveMQRATestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { ((DummyTransactionManager) ServiceUtils.getTransactionManager()).tx = null; - if (resourceAdapter != null) - { + if (resourceAdapter != null) { resourceAdapter.stop(); } @@ -105,8 +101,7 @@ public class OutgoingConnectionTestJTA extends ActiveMQRATestBase } @Test - public void testSimpleMessageSendAndReceiveTransacted() throws Exception - { + public void testSimpleMessageSendAndReceiveTransacted() throws Exception { setDummyTX(); setupDLQ(10); resourceAdapter = newResourceAdapter(); @@ -134,75 +129,59 @@ public class OutgoingConnectionTestJTA extends ActiveMQRATestBase s.commit(); } - public void testQueuSessionAckMode(boolean inTx) throws Exception - { - if (inTx) - { + public void testQueuSessionAckMode(boolean inTx) throws Exception { + if (inTx) { setDummyTX(); } QueueConnection queueConnection = qraConnectionFactory.createQueueConnection(); Session s = queueConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - if (inTx) - { + if (inTx) { assertEquals(Session.SESSION_TRANSACTED, s.getAcknowledgeMode()); } - else - { + else { assertEquals(Session.AUTO_ACKNOWLEDGE, s.getAcknowledgeMode()); } s.close(); s = queueConnection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE); - if (inTx) - { + if (inTx) { assertEquals(Session.SESSION_TRANSACTED, s.getAcknowledgeMode()); } - else - { + else { assertEquals(Session.DUPS_OK_ACKNOWLEDGE, s.getAcknowledgeMode()); } s.close(); //exception should be thrown if ack mode is SESSION_TRANSACTED or //CLIENT_ACKNOWLEDGE when in a JTA else ackmode should bee ignored - try - { + try { s = queueConnection.createSession(false, Session.SESSION_TRANSACTED); - if (inTx) - { + if (inTx) { assertEquals(s.getAcknowledgeMode(), Session.SESSION_TRANSACTED); } - else - { + else { fail("didn't get expected exception creating session with SESSION_TRANSACTED mode "); } s.close(); } - catch (JMSException e) - { - if (inTx) - { + catch (JMSException e) { + if (inTx) { fail("shouldn't throw exception " + e); } } - try - { + try { s = queueConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - if (inTx) - { + if (inTx) { assertEquals(s.getAcknowledgeMode(), Session.SESSION_TRANSACTED); } - else - { + else { fail("didn't get expected exception creating session with CLIENT_ACKNOWLEDGE mode"); } } - catch (JMSException e) - { - if (inTx) - { + catch (JMSException e) { + if (inTx) { fail("shouldn't throw exception " + e); } } @@ -210,16 +189,14 @@ public class OutgoingConnectionTestJTA extends ActiveMQRATestBase } @Test - public void testSimpleSendNoXAJMSContext() throws Exception - { + public void testSimpleSendNoXAJMSContext() throws Exception { Queue q = ActiveMQJMSClient.createQueue(MDBQUEUE); try (ClientSessionFactory sf = locator.createSessionFactory(); ClientSession session = sf.createSession(); ClientConsumer consVerify = session.createConsumer("jms.queue." + MDBQUEUE); JMSContext jmsctx = qraConnectionFactory.createContext(); - ) - { + ) { session.start(); // These next 4 lines could be written in a single line however it makes difficult for debugging JMSProducer producer = jmsctx.createProducer(); @@ -234,20 +211,17 @@ public class OutgoingConnectionTestJTA extends ActiveMQRATestBase } @Test - public void testQueueSessionAckModeJTA() throws Exception - { + public void testQueueSessionAckModeJTA() throws Exception { testQueuSessionAckMode(true); } @Test - public void testSessionAckModeNoJTA() throws Exception - { + public void testSessionAckModeNoJTA() throws Exception { testQueuSessionAckMode(false); } @Test - public void testSimpleMessageSendAndReceive() throws Exception - { + public void testSimpleMessageSendAndReceive() throws Exception { QueueConnection queueConnection = qraConnectionFactory.createQueueConnection(); Session s = queueConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue q = ActiveMQJMSClient.createQueue(MDBQUEUE); @@ -262,15 +236,13 @@ public class OutgoingConnectionTestJTA extends ActiveMQRATestBase } @Test - public void testSimpleSendNoXAJMS1() throws Exception - { + public void testSimpleSendNoXAJMS1() throws Exception { Queue q = ActiveMQJMSClient.createQueue(MDBQUEUE); try (ClientSessionFactory sf = locator.createSessionFactory(); ClientSession session = sf.createSession(); ClientConsumer consVerify = session.createConsumer("jms.queue." + MDBQUEUE); Connection conn = qraConnectionFactory.createConnection(); - ) - { + ) { Session jmsSess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); session.start(); MessageProducer producer = jmsSess.createProducer(q); @@ -284,8 +256,8 @@ public class OutgoingConnectionTestJTA extends ActiveMQRATestBase assertEquals("hello", msg.getStringProperty("strvalue")); } } - private void setDummyTX() - { + + private void setDummyTX() { ((DummyTransactionManager) ServiceUtils.getTransactionManager()).tx = new DummyTransaction(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ResourceAdapterTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ResourceAdapterTest.java index e87444771a..221b3da5ec 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ResourceAdapterTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ResourceAdapterTest.java @@ -45,11 +45,10 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; -public class ResourceAdapterTest extends ActiveMQRATestBase -{ +public class ResourceAdapterTest extends ActiveMQRATestBase { + @Test - public void testStartStopActivationManyTimes() throws Exception - { + public void testStartStopActivationManyTimes() throws Exception { ServerLocator locator = createInVMNonHALocator(); ClientSessionFactory factory = locator.createSessionFactory(); ClientSession session = factory.createSession(false, false, false); @@ -95,8 +94,7 @@ public class ResourceAdapterTest extends ActiveMQRATestBase Set factories = (Set) f.get(serverLocator); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { System.out.println(i); assertEquals(factories.size(), 0); activation.start(); @@ -116,8 +114,7 @@ public class ResourceAdapterTest extends ActiveMQRATestBase } @Test - public void testStartStop() throws Exception - { + public void testStartStop() throws Exception { ActiveMQResourceAdapter qResourceAdapter = new ActiveMQResourceAdapter(); qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY); ActiveMQRATestBase.MyBootstrapContext ctx = new ActiveMQRATestBase.MyBootstrapContext(); @@ -138,8 +135,7 @@ public class ResourceAdapterTest extends ActiveMQRATestBase } @Test - public void testSetters() throws Exception - { + public void testSetters() throws Exception { Boolean b = Boolean.TRUE; Long l = (long) 1000; Integer i = 1000; @@ -155,25 +151,11 @@ public class ResourceAdapterTest extends ActiveMQRATestBase String testpass = "testpass"; String testuser = "testuser"; ActiveMQResourceAdapter qResourceAdapter = new ActiveMQResourceAdapter(); - testParams(b, - l, - i, - d, - className, - backupConn, - testConfig, - testid, - testBalancer, - testParams, - testaddress, - testpass, - testuser, - qResourceAdapter); + testParams(b, l, i, d, className, backupConn, testConfig, testid, testBalancer, testParams, testaddress, testpass, testuser, qResourceAdapter); } @Test - public void testSetters2() throws Exception - { + public void testSetters2() throws Exception { Boolean b = Boolean.FALSE; Long l = (long) 2000; Integer i = 2000; @@ -189,20 +171,7 @@ public class ResourceAdapterTest extends ActiveMQRATestBase String testpass = "testpass2"; String testuser = "testuser2"; ActiveMQResourceAdapter qResourceAdapter = new ActiveMQResourceAdapter(); - testParams(b, - l, - i, - d, - className, - backupConn, - testConfig, - testid, - testBalancer, - testParams, - testaddress, - testpass, - testuser, - qResourceAdapter); + testParams(b, l, i, d, className, backupConn, testConfig, testid, testBalancer, testParams, testaddress, testpass, testuser, qResourceAdapter); } private void testParams(Boolean b, @@ -218,8 +187,7 @@ public class ResourceAdapterTest extends ActiveMQRATestBase String testaddress, String testpass, String testuser, - ActiveMQResourceAdapter qResourceAdapter) - { + ActiveMQResourceAdapter qResourceAdapter) { qResourceAdapter.setUseLocalTx(b); qResourceAdapter.setConnectorClassName(className); qResourceAdapter.setAutoGroup(b); @@ -292,8 +260,7 @@ public class ResourceAdapterTest extends ActiveMQRATestBase // https://issues.jboss.org/browse/JBPAPP-5790 @Test - public void testResourceAdapterSetup() throws Exception - { + public void testResourceAdapterSetup() throws Exception { ActiveMQResourceAdapter adapter = new ActiveMQResourceAdapter(); adapter.setDiscoveryAddress("231.1.1.1"); ActiveMQConnectionFactory factory = adapter.getDefaultActiveMQConnectionFactory(); @@ -346,8 +313,7 @@ public class ResourceAdapterTest extends ActiveMQRATestBase // https://issues.jboss.org/browse/JBPAPP-5836 @Test - public void testResourceAdapterSetupOverrideCFParams() throws Exception - { + public void testResourceAdapterSetupOverrideCFParams() throws Exception { ActiveMQResourceAdapter qResourceAdapter = new ActiveMQResourceAdapter(); qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY); qResourceAdapter.setConnectionParameters("server-id=0"); @@ -372,8 +338,7 @@ public class ResourceAdapterTest extends ActiveMQRATestBase } @Test - public void testRecoveryRegistrationOnFailure() throws Exception - { + public void testRecoveryRegistrationOnFailure() throws Exception { ActiveMQResourceAdapter qResourceAdapter = new ActiveMQResourceAdapter(); qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY); qResourceAdapter.setConnectionParameters("server-id=0"); @@ -400,8 +365,7 @@ public class ResourceAdapterTest extends ActiveMQRATestBase } @Test - public void testResourceAdapterSetupOverrideNoCFParams() throws Exception - { + public void testResourceAdapterSetupOverrideNoCFParams() throws Exception { ActiveMQResourceAdapter qResourceAdapter = new ActiveMQResourceAdapter(); qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY); qResourceAdapter.setConnectionParameters("server-id=0"); @@ -424,8 +388,7 @@ public class ResourceAdapterTest extends ActiveMQRATestBase } @Test - public void testResourceAdapterSetupNoOverrideDiscovery() throws Exception - { + public void testResourceAdapterSetupNoOverrideDiscovery() throws Exception { ActiveMQResourceAdapter qResourceAdapter = new ActiveMQResourceAdapter(); qResourceAdapter.setDiscoveryAddress("231.6.6.6"); qResourceAdapter.setDiscoveryPort(1234); @@ -450,14 +413,12 @@ public class ResourceAdapterTest extends ActiveMQRATestBase } @Test - public void testResourceAdapterSetupOverrideDiscovery() throws Exception - { + public void testResourceAdapterSetupOverrideDiscovery() throws Exception { ActiveMQResourceAdapter qResourceAdapter = new ActiveMQResourceAdapter(); qResourceAdapter.setDiscoveryAddress("231.7.7.7"); ActiveMQRATestBase.MyBootstrapContext ctx = new ActiveMQRATestBase.MyBootstrapContext(); - qResourceAdapter.start(ctx); ActiveMQActivationSpec spec = new ActiveMQActivationSpec(); spec.setResourceAdapter(qResourceAdapter); @@ -480,8 +441,7 @@ public class ResourceAdapterTest extends ActiveMQRATestBase } @Test - public void testResourceAdapterSetupNoHAOverride() throws Exception - { + public void testResourceAdapterSetupNoHAOverride() throws Exception { ActiveMQResourceAdapter qResourceAdapter = new ActiveMQResourceAdapter(); qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY); qResourceAdapter.setConnectionParameters("server-id=0"); @@ -504,8 +464,7 @@ public class ResourceAdapterTest extends ActiveMQRATestBase } @Test - public void testResourceAdapterSetupNoHADefault() throws Exception - { + public void testResourceAdapterSetupNoHADefault() throws Exception { ActiveMQResourceAdapter qResourceAdapter = new ActiveMQResourceAdapter(); qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY); qResourceAdapter.setConnectionParameters("server-id=0"); @@ -527,8 +486,7 @@ public class ResourceAdapterTest extends ActiveMQRATestBase } @Test - public void testResourceAdapterSetupHAOverride() throws Exception - { + public void testResourceAdapterSetupHAOverride() throws Exception { ActiveMQResourceAdapter qResourceAdapter = new ActiveMQResourceAdapter(); qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY); qResourceAdapter.setConnectionParameters("server-id=0"); @@ -550,8 +508,7 @@ public class ResourceAdapterTest extends ActiveMQRATestBase } @Test - public void testResourceAdapterSetupNoReconnectAttemptsOverride() throws Exception - { + public void testResourceAdapterSetupNoReconnectAttemptsOverride() throws Exception { ActiveMQResourceAdapter qResourceAdapter = new ActiveMQResourceAdapter(); qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY); qResourceAdapter.setConnectionParameters("server-id=0"); @@ -574,8 +531,7 @@ public class ResourceAdapterTest extends ActiveMQRATestBase } @Test - public void testResourceAdapterSetupReconnectAttemptDefault() throws Exception - { + public void testResourceAdapterSetupReconnectAttemptDefault() throws Exception { ActiveMQResourceAdapter qResourceAdapter = new ActiveMQResourceAdapter(); qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY); qResourceAdapter.setConnectionParameters("server-id=0"); @@ -597,8 +553,7 @@ public class ResourceAdapterTest extends ActiveMQRATestBase } @Test - public void testResourceAdapterSetupReconnectAttemptsOverride() throws Exception - { + public void testResourceAdapterSetupReconnectAttemptsOverride() throws Exception { ActiveMQResourceAdapter qResourceAdapter = new ActiveMQResourceAdapter(); qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY); qResourceAdapter.setConnectionParameters("server-id=0"); @@ -620,8 +575,7 @@ public class ResourceAdapterTest extends ActiveMQRATestBase } @Test - public void testMaskPassword() throws Exception - { + public void testMaskPassword() throws Exception { ActiveMQResourceAdapter qResourceAdapter = new ActiveMQResourceAdapter(); qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY); ActiveMQRATestBase.MyBootstrapContext ctx = new ActiveMQRATestBase.MyBootstrapContext(); @@ -657,8 +611,7 @@ public class ResourceAdapterTest extends ActiveMQRATestBase } @Test - public void testMaskPassword2() throws Exception - { + public void testMaskPassword2() throws Exception { ActiveMQResourceAdapter qResourceAdapter = new ActiveMQResourceAdapter(); qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY); ActiveMQRATestBase.MyBootstrapContext ctx = new ActiveMQRATestBase.MyBootstrapContext(); @@ -701,25 +654,21 @@ public class ResourceAdapterTest extends ActiveMQRATestBase } @Override - public boolean useSecurity() - { + public boolean useSecurity() { return false; } - class DummyEndpoint implements MessageEndpoint - { - public void beforeDelivery(Method method) throws NoSuchMethodException, ResourceException - { + class DummyEndpoint implements MessageEndpoint { + + public void beforeDelivery(Method method) throws NoSuchMethodException, ResourceException { // To change body of implemented methods use File | Settings | File Templates. } - public void afterDelivery() throws ResourceException - { + public void afterDelivery() throws ResourceException { // To change body of implemented methods use File | Settings | File Templates. } - public void release() - { + public void release() { // To change body of implemented methods use File | Settings | File Templates. } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/BatchDelayTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/BatchDelayTest.java index 9b2d635a5b..2548fc6393 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/BatchDelayTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/BatchDelayTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.remoting; + import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Assert; import org.junit.Before; @@ -36,8 +37,7 @@ import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants; import org.apache.activemq.artemis.core.server.ActiveMQServer; -public class BatchDelayTest extends ActiveMQTestBase -{ +public class BatchDelayTest extends ActiveMQTestBase { private static final int N = 1000; private static final long DELAY = 500; @@ -45,8 +45,7 @@ public class BatchDelayTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); Map params = new HashMap(); @@ -54,26 +53,22 @@ public class BatchDelayTest extends ActiveMQTestBase TransportConfiguration tc = new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params); - Configuration config = createBasicConfig() - .addAcceptorConfiguration(tc); + Configuration config = createBasicConfig().addAcceptorConfiguration(tc); server = createServer(false, config); server.start(); } - protected ClientSessionFactory createSessionFactory() throws Exception - { + protected ClientSessionFactory createSessionFactory() throws Exception { Map params = new HashMap(); params.put(TransportConstants.BATCH_DELAY, DELAY); - ServerLocator locator = - ActiveMQClient.createServerLocatorWithoutHA(createTransportConfiguration(true, false, params)); + ServerLocator locator = ActiveMQClient.createServerLocatorWithoutHA(createTransportConfiguration(true, false, params)); addServerLocator(locator); ClientSessionFactory sf = createSessionFactory(locator); return addSessionFactory(sf); } @Test - public void testSendReceiveMany() throws Exception - { + public void testSendReceiveMany() throws Exception { ClientSessionFactory sf = createSessionFactory(); ClientSession session = sf.createSession(); @@ -93,8 +88,7 @@ public class BatchDelayTest extends ActiveMQTestBase } @Test - public void testSendReceiveOne() throws Exception - { + public void testSendReceiveOne() throws Exception { ClientSessionFactory sf = createSessionFactory(); ClientSession session = sf.createSession(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/DestroyConsumerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/DestroyConsumerTest.java index 2509c362d2..ef232a6308 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/DestroyConsumerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/DestroyConsumerTest.java @@ -19,8 +19,7 @@ package org.apache.activemq.artemis.tests.integration.remoting; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Test; -public class DestroyConsumerTest extends ActiveMQTestBase -{ +public class DestroyConsumerTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -33,8 +32,7 @@ public class DestroyConsumerTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testFoo() - { + public void testFoo() { } // public void testDestroyConsumer() throws Exception diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/DirectDeliverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/DirectDeliverTest.java index c4ef3dc66f..6a06a88677 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/DirectDeliverTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/DirectDeliverTest.java @@ -38,8 +38,7 @@ import org.junit.Test; import java.util.HashMap; import java.util.Map; -public class DirectDeliverTest extends ActiveMQTestBase -{ +public class DirectDeliverTest extends ActiveMQTestBase { private ActiveMQServer server; @@ -47,8 +46,7 @@ public class DirectDeliverTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); Map params = new HashMap(); @@ -56,8 +54,7 @@ public class DirectDeliverTest extends ActiveMQTestBase TransportConfiguration tc = new TransportConfiguration(NettyAcceptorFactory.class.getName(), params); - Configuration config = createBasicConfig() - .addAcceptorConfiguration(tc); + Configuration config = createBasicConfig().addAcceptorConfiguration(tc); server = createServer(false, config); server.start(); @@ -66,8 +63,7 @@ public class DirectDeliverTest extends ActiveMQTestBase } @Test - public void testDirectDeliver() throws Exception - { + public void testDirectDeliver() throws Exception { final String foo = "foo"; ClientSessionFactory sf = createSessionFactory(locator); @@ -78,7 +74,7 @@ public class DirectDeliverTest extends ActiveMQTestBase Binding binding = server.getPostOffice().getBinding(new SimpleString(foo)); - Queue queue = (Queue)binding.getBindable(); + Queue queue = (Queue) binding.getBindable(); assertTrue(queue.isDirectDeliver()); @@ -88,8 +84,7 @@ public class DirectDeliverTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage msg = session.createMessage(true); prod.send(msg); @@ -102,8 +97,7 @@ public class DirectDeliverTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage msg = cons.receive(10000); assertNotNull(msg); @@ -111,7 +105,7 @@ public class DirectDeliverTest extends ActiveMQTestBase msg.acknowledge(); } - Thread.sleep((long)(QueueImpl.CHECK_QUEUE_SIZE_PERIOD * 1.5)); + Thread.sleep((long) (QueueImpl.CHECK_QUEUE_SIZE_PERIOD * 1.5)); //Add another message, should go direct ClientMessage msg = session.createMessage(true); @@ -123,15 +117,13 @@ public class DirectDeliverTest extends ActiveMQTestBase assertTrue(queue.isDirectDeliver()); //Send some more - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { msg = session.createMessage(true); prod.send(msg); } - for (int i = 0; i < numMessages + 1; i++) - { + for (int i = 0; i < numMessages + 1; i++) { msg = cons.receive(10000); assertNotNull(msg); @@ -143,8 +135,7 @@ public class DirectDeliverTest extends ActiveMQTestBase session.stop(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { msg = session.createMessage(true); prod.send(msg); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/NettyNetworkAddressTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/NettyNetworkAddressTest.java index 3e4784face..321c21844f 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/NettyNetworkAddressTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/NettyNetworkAddressTest.java @@ -20,30 +20,25 @@ import org.apache.activemq.artemis.core.remoting.impl.netty.NettyAcceptorFactory import org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnectorFactory; import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants; -public class NettyNetworkAddressTest extends NetworkAddressTestBase -{ +public class NettyNetworkAddressTest extends NetworkAddressTestBase { @Override - protected String getAcceptorFactoryClassName() - { + protected String getAcceptorFactoryClassName() { return NettyAcceptorFactory.class.getName(); } @Override - protected String getConnectorFactoryClassName() - { + protected String getConnectorFactoryClassName() { return NettyConnectorFactory.class.getName(); } @Override - protected String getHostPropertyKey() - { + protected String getHostPropertyKey() { return TransportConstants.HOST_PROP_NAME; } @Override - protected String getLocalPortProperty() - { + protected String getLocalPortProperty() { return TransportConstants.LOCAL_PORT_PROP_NAME; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/NettySynchronousCloseTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/NettySynchronousCloseTest.java index 7262ad3f5d..a197ad108a 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/NettySynchronousCloseTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/NettySynchronousCloseTest.java @@ -16,11 +16,10 @@ */ package org.apache.activemq.artemis.tests.integration.remoting; -public class NettySynchronousCloseTest extends SynchronousCloseTest -{ +public class NettySynchronousCloseTest extends SynchronousCloseTest { + @Override - protected boolean isNetty() - { + protected boolean isNetty() { return true; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/NetworkAddressTestBase.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/NetworkAddressTestBase.java index 6713680b3e..1fb4cef917 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/NetworkAddressTestBase.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/NetworkAddressTestBase.java @@ -38,8 +38,7 @@ import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; import org.junit.Assert; import org.junit.Test; -public abstract class NetworkAddressTestBase extends ActiveMQTestBase -{ +public abstract class NetworkAddressTestBase extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -47,38 +46,30 @@ public abstract class NetworkAddressTestBase extends ActiveMQTestBase // Static -------------------------------------------------------- - static - { - try - { + static { + try { Map map = NetworkAddressTestBase.getAddressForEachNetworkInterface(); StringBuilder s = new StringBuilder("using network settings:\n"); Set> set = map.entrySet(); - for (Entry entry : set) - { + for (Entry entry : set) { s.append(entry.getKey().getDisplayName() + ": " + entry.getValue().getHostAddress() + "\n"); } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } - public static Map getAddressForEachNetworkInterface() throws Exception - { + public static Map getAddressForEachNetworkInterface() throws Exception { Map map = new HashMap(); Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); - while (ifaces.hasMoreElements()) - { + while (ifaces.hasMoreElements()) { NetworkInterface iface = ifaces.nextElement(); Enumeration enumeration = iface.getInetAddresses(); - while (enumeration.hasMoreElements()) - { + while (enumeration.hasMoreElements()) { InetAddress inetAddress = enumeration.nextElement(); - if (inetAddress instanceof Inet4Address) - { + if (inetAddress instanceof Inet4Address) { map.put(iface, inetAddress); break; } @@ -93,11 +84,9 @@ public abstract class NetworkAddressTestBase extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testConnectToServerWithSameHost() throws Exception - { + public void testConnectToServerWithSameHost() throws Exception { Map map = NetworkAddressTestBase.getAddressForEachNetworkInterface(); - if (map.size() > 0) - { + if (map.size() > 0) { Set> set = map.entrySet(); Iterator> iterator = set.iterator(); InetAddress address = iterator.next().getValue(); @@ -107,23 +96,19 @@ public abstract class NetworkAddressTestBase extends ActiveMQTestBase } @Test - public void testConnectToServerAcceptingAllHosts() throws Exception - { + public void testConnectToServerAcceptingAllHosts() throws Exception { Map map = NetworkAddressTestBase.getAddressForEachNetworkInterface(); Set> set = map.entrySet(); - for (Entry entry : set) - { + for (Entry entry : set) { String host = entry.getValue().getHostAddress(); testConnection("0.0.0.0", host, true, 0); } } @Test - public void testConnectToServerAcceptingOnlyAnotherHost() throws Exception - { + public void testConnectToServerAcceptingOnlyAnotherHost() throws Exception { Map map = NetworkAddressTestBase.getAddressForEachNetworkInterface(); - if (map.size() <= 1) - { + if (map.size() <= 1) { System.err.println("There must be at least 1 network interfaces: test will not be executed"); return; } @@ -137,11 +122,9 @@ public abstract class NetworkAddressTestBase extends ActiveMQTestBase } @Test - public void testConnectToServerUsingLocalPort() throws Exception - { + public void testConnectToServerUsingLocalPort() throws Exception { Map map = NetworkAddressTestBase.getAddressForEachNetworkInterface(); - if (map.size() <= 1) - { + if (map.size() <= 1) { System.err.println("There must be at least 1 network interfaces: test will not be executed"); return; } @@ -155,11 +138,9 @@ public abstract class NetworkAddressTestBase extends ActiveMQTestBase } @Test - public void testConnectorToServerAcceptingAListOfHosts() throws Exception - { + public void testConnectorToServerAcceptingAListOfHosts() throws Exception { Map map = NetworkAddressTestBase.getAddressForEachNetworkInterface(); - if (map.size() <= 1) - { + if (map.size() <= 1) { System.err.println("There must be at least 2 network interfaces: test will not be executed"); return; } @@ -176,11 +157,9 @@ public abstract class NetworkAddressTestBase extends ActiveMQTestBase } @Test - public void testConnectorToServerAcceptingAListOfHosts_2() throws Exception - { + public void testConnectorToServerAcceptingAListOfHosts_2() throws Exception { Map map = NetworkAddressTestBase.getAddressForEachNetworkInterface(); - if (map.size() <= 2) - { + if (map.size() <= 2) { System.err.println("There must be at least 3 network interfaces: test will not be executed"); return; } @@ -198,8 +177,10 @@ public abstract class NetworkAddressTestBase extends ActiveMQTestBase testConnection(listOfHosts, entry3.getValue().getHostAddress(), false, 0); } - public void testConnection(final String acceptorHost, final String connectorHost, final boolean mustConnect, final int localPort) throws Exception - { + public void testConnection(final String acceptorHost, + final String connectorHost, + final boolean mustConnect, + final int localPort) throws Exception { System.out.println("acceptor=" + acceptorHost + ", connector=" + connectorHost + ", mustConnect=" + mustConnect); Map params = new HashMap(); @@ -211,24 +192,20 @@ public abstract class NetworkAddressTestBase extends ActiveMQTestBase Configuration config = createDefaultNettyConfig(); config.setAcceptorConfigurations(transportConfigs); ActiveMQServer messagingService = createServer(false, config); - try - { + try { messagingService.start(); params = new HashMap(); params.put(getHostPropertyKey(), connectorHost); - if (localPort != 0) - { + if (localPort != 0) { params.put(getLocalPortProperty(), localPort); } TransportConfiguration connectorConfig = new TransportConfiguration(getConnectorFactoryClassName(), params); ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(connectorConfig)); - if (mustConnect) - { + if (mustConnect) { ClientSessionFactory sf = createSessionFactory(locator); - if (localPort != 0) - { + if (localPort != 0) { Iterator iterator = messagingService.getRemotingService().getConnections().iterator(); Assert.assertTrue("no connection created", iterator.hasNext()); String address = iterator.next().getTransportConnection().getRemoteAddress(); @@ -237,20 +214,16 @@ public abstract class NetworkAddressTestBase extends ActiveMQTestBase sf.close(); System.out.println("connection OK"); } - else - { - try - { + else { + try { locator.createSessionFactory(); Assert.fail("session creation must fail because connector must not be able to connect to the server bound to another network interface"); } - catch (Exception e) - { + catch (Exception e) { } } } - finally - { + finally { messagingService.stop(); } } @@ -267,7 +240,6 @@ public abstract class NetworkAddressTestBase extends ActiveMQTestBase protected abstract String getLocalPortProperty(); - // Private ------------------------------------------------------- // Inner classes ------------------------------------------------- diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/PingTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/PingTest.java index b9ccbbea3f..35f83bd5d3 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/PingTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/PingTest.java @@ -44,8 +44,7 @@ import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -public class PingTest extends ActiveMQTestBase -{ +public class PingTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @@ -64,36 +63,31 @@ public class PingTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(false, createDefaultNettyConfig()); server.start(); } - class Listener implements SessionFailureListener - { + class Listener implements SessionFailureListener { + volatile ActiveMQException me; @Override - public void connectionFailed(final ActiveMQException me, boolean failedOver) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver) { this.me = me; } @Override - public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) { connectionFailed(me, failedOver); } - public ActiveMQException getException() - { + public ActiveMQException getException() { return me; } - public void beforeReconnect(final ActiveMQException exception) - { + public void beforeReconnect(final ActiveMQException exception) { } } @@ -101,8 +95,7 @@ public class PingTest extends ActiveMQTestBase * Test that no failure listeners are triggered in a non failure case with pinging going on */ @Test - public void testNoFailureWithPinging() throws Exception - { + public void testNoFailureWithPinging() throws Exception { ServerLocator locator = createNettyNonHALocator(); locator.setClientFailureCheckPeriod(PingTest.CLIENT_FAILURE_CHECK_PERIOD); @@ -114,23 +107,20 @@ public class PingTest extends ActiveMQTestBase PingTest.log.info("Created session"); - Assert.assertEquals(1, ((ClientSessionFactoryInternal)csf).numConnections()); + Assert.assertEquals(1, ((ClientSessionFactoryInternal) csf).numConnections()); Listener clientListener = new Listener(); session.addFailureListener(clientListener); RemotingConnection serverConn = null; - while (serverConn == null) - { + while (serverConn == null) { Set conns = server.getRemotingService().getConnections(); - if (!conns.isEmpty()) - { + if (!conns.isEmpty()) { serverConn = server.getRemotingService().getConnections().iterator().next(); } - else - { + else { // It's async so need to wait a while Thread.sleep(10); } @@ -163,8 +153,7 @@ public class PingTest extends ActiveMQTestBase * Test that no failure listeners are triggered in a non failure case with no pinging going on */ @Test - public void testNoFailureNoPinging() throws Exception - { + public void testNoFailureNoPinging() throws Exception { TransportConfiguration transportConfig = new TransportConfiguration(INVM_CONNECTOR_FACTORY); ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(transportConfig)); locator.setClientFailureCheckPeriod(-1); @@ -173,23 +162,20 @@ public class PingTest extends ActiveMQTestBase ClientSession session = csf.createSession(false, true, true); - Assert.assertEquals(1, ((ClientSessionFactoryInternal)csf).numConnections()); + Assert.assertEquals(1, ((ClientSessionFactoryInternal) csf).numConnections()); Listener clientListener = new Listener(); session.addFailureListener(clientListener); RemotingConnection serverConn = null; - while (serverConn == null) - { + while (serverConn == null) { Set conns = server.getRemotingService().getConnections(); - if (!conns.isEmpty()) - { + if (!conns.isEmpty()) { serverConn = server.getRemotingService().getConnections().iterator().next(); } - else - { + else { // It's async so need to wait a while Thread.sleep(10); } @@ -222,18 +208,14 @@ public class PingTest extends ActiveMQTestBase * Test that pinging is disabled for in-vm connection when using the default settings */ @Test - public void testNoPingingOnInVMConnection() throws Exception - { + public void testNoPingingOnInVMConnection() throws Exception { // server should receive one and only one ping from the client so that // the server connection TTL is configured with the client value final CountDownLatch requiredPings = new CountDownLatch(1); final CountDownLatch unwantedPings = new CountDownLatch(2); - server.getRemotingService().addIncomingInterceptor(new Interceptor() - { - public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException - { - if (packet.getType() == PacketImpl.PING) - { + server.getRemotingService().addIncomingInterceptor(new Interceptor() { + public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { + if (packet.getType() == PacketImpl.PING) { Assert.assertEquals(ActiveMQClient.DEFAULT_CONNECTION_TTL_INVM, ((Ping) packet).getConnectionTTL()); unwantedPings.countDown(); requiredPings.countDown(); @@ -248,7 +230,7 @@ public class PingTest extends ActiveMQTestBase ClientSession session = csf.createSession(false, true, true); - Assert.assertEquals(1, ((ClientSessionFactoryInternal)csf).numConnections()); + Assert.assertEquals(1, ((ClientSessionFactoryInternal) csf).numConnections()); Assert.assertTrue("server didn't received an expected ping from the client", requiredPings.await(5000, TimeUnit.MILLISECONDS)); @@ -265,15 +247,13 @@ public class PingTest extends ActiveMQTestBase * Test the server timing out a connection since it doesn't receive a ping in time */ @Test - public void testServerFailureNoPing() throws Exception - { + public void testServerFailureNoPing() throws Exception { TransportConfiguration transportConfig = new TransportConfiguration(INVM_CONNECTOR_FACTORY); ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(transportConfig)); locator.setClientFailureCheckPeriod(PingTest.CLIENT_FAILURE_CHECK_PERIOD); locator.setConnectionTTL(PingTest.CLIENT_FAILURE_CHECK_PERIOD * 2); ClientSessionFactoryImpl csf = (ClientSessionFactoryImpl) createSessionFactory(locator); - Listener clientListener = new Listener(); ClientSession session = csf.createSession(false, true, true); @@ -288,16 +268,13 @@ public class PingTest extends ActiveMQTestBase RemotingConnection serverConn = null; - while (serverConn == null) - { + while (serverConn == null) { Set conns = server.getRemotingService().getConnections(); - if (!conns.isEmpty()) - { + if (!conns.isEmpty()) { serverConn = server.getRemotingService().getConnections().iterator().next(); } - else - { + else { // It's async so need to wait a while Thread.sleep(10); } @@ -307,19 +284,16 @@ public class PingTest extends ActiveMQTestBase serverConn.addFailureListener(serverListener); - for (int i = 0; i < 1000; i++) - { + for (int i = 0; i < 1000; i++) { // a few tries to avoid a possible race caused by GCs or similar issues - if (server.getRemotingService().getConnections().isEmpty() && clientListener.getException() != null) - { + if (server.getRemotingService().getConnections().isEmpty() && clientListener.getException() != null) { break; } Thread.sleep(10); } - if (!server.getRemotingService().getConnections().isEmpty()) - { + if (!server.getRemotingService().getConnections().isEmpty()) { RemotingConnection serverConn2 = server.getRemotingService().getConnections().iterator().next(); PingTest.log.info("Serverconn2 is " + serverConn2); @@ -345,18 +319,14 @@ public class PingTest extends ActiveMQTestBase * Test the client triggering failure due to no ping from server received in time */ @Test - public void testClientFailureNoServerPing() throws Exception - { + public void testClientFailureNoServerPing() throws Exception { // server must received at least one ping from the client to pass // so that the server connection TTL is configured with the client value final CountDownLatch pingOnServerLatch = new CountDownLatch(2); - server.getRemotingService().addIncomingInterceptor(new Interceptor() - { + server.getRemotingService().addIncomingInterceptor(new Interceptor() { - public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException - { - if (packet.getType() == PacketImpl.PING) - { + public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { + if (packet.getType() == PacketImpl.PING) { pingOnServerLatch.countDown(); } return true; @@ -369,36 +339,29 @@ public class PingTest extends ActiveMQTestBase locator.setConnectionTTL(PingTest.CLIENT_FAILURE_CHECK_PERIOD * 2); ClientSessionFactory csf = createSessionFactory(locator); - ClientSession session = csf.createSession(false, true, true); - Assert.assertEquals(1, ((ClientSessionFactoryInternal)csf).numConnections()); + Assert.assertEquals(1, ((ClientSessionFactoryInternal) csf).numConnections()); final CountDownLatch clientLatch = new CountDownLatch(1); - SessionFailureListener clientListener = new SessionFailureListener() - { + SessionFailureListener clientListener = new SessionFailureListener() { @Override - public void connectionFailed(final ActiveMQException me, boolean failedOver) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver) { clientLatch.countDown(); } @Override - public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) { connectionFailed(me, failedOver); } - public void beforeReconnect(final ActiveMQException exception) - { + public void beforeReconnect(final ActiveMQException exception) { } }; final CountDownLatch serverLatch = new CountDownLatch(1); - CloseListener serverListener = new CloseListener() - { - public void connectionClosed() - { + CloseListener serverListener = new CloseListener() { + public void connectionClosed() { serverLatch.countDown(); } }; @@ -406,24 +369,20 @@ public class PingTest extends ActiveMQTestBase session.addFailureListener(clientListener); CoreRemotingConnection serverConn = null; - while (serverConn == null) - { + while (serverConn == null) { Set conns = server.getRemotingService().getConnections(); - if (!conns.isEmpty()) - { - serverConn = (CoreRemotingConnection)server.getRemotingService().getConnections().iterator().next(); + if (!conns.isEmpty()) { + serverConn = (CoreRemotingConnection) server.getRemotingService().getConnections().iterator().next(); } - else - { + else { // It's async so need to wait a while Thread.sleep(10); } } serverConn.addCloseListener(serverListener); - Assert.assertTrue("server has not received any ping from the client", - pingOnServerLatch.await(4000, TimeUnit.MILLISECONDS)); + Assert.assertTrue("server has not received any ping from the client", pingOnServerLatch.await(4000, TimeUnit.MILLISECONDS)); // we let the server receives at least 1 ping (so that it uses the client ConnectionTTL value) @@ -436,14 +395,11 @@ public class PingTest extends ActiveMQTestBase Assert.assertTrue(serverLatch.await(2 * RemotingServiceImpl.CONNECTION_TTL_CHECK_INTERVAL, TimeUnit.MILLISECONDS)); long start = System.currentTimeMillis(); - while (true) - { - if (!server.getRemotingService().getConnections().isEmpty() && System.currentTimeMillis() - start < 10000) - { + while (true) { + if (!server.getRemotingService().getConnections().isEmpty() && System.currentTimeMillis() - start < 10000) { Thread.sleep(500); } - else - { + else { break; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/ReconnectTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/ReconnectTest.java index 500e963239..7448393091 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/ReconnectTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/ReconnectTest.java @@ -34,23 +34,19 @@ import org.apache.activemq.artemis.core.client.impl.ClientSessionInternal; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -public class ReconnectTest extends ActiveMQTestBase -{ +public class ReconnectTest extends ActiveMQTestBase { @Test - public void testReconnectNetty() throws Exception - { + public void testReconnectNetty() throws Exception { internalTestReconnect(true); } @Test - public void testReconnectInVM() throws Exception - { + public void testReconnectInVM() throws Exception { internalTestReconnect(false); } - public void internalTestReconnect(final boolean isNetty) throws Exception - { + public void internalTestReconnect(final boolean isNetty) throws Exception { final int pingPeriod = 1000; ActiveMQServer server = createServer(false, isNetty); @@ -59,40 +55,29 @@ public class ReconnectTest extends ActiveMQTestBase ClientSessionInternal session = null; - try - { - ServerLocator locator = createFactory(isNetty) - .setClientFailureCheckPeriod(pingPeriod) - .setRetryInterval(500) - .setRetryIntervalMultiplier(1d) - .setReconnectAttempts(-1) - .setConfirmationWindowSize(1024 * 1024); + try { + ServerLocator locator = createFactory(isNetty).setClientFailureCheckPeriod(pingPeriod).setRetryInterval(500).setRetryIntervalMultiplier(1d).setReconnectAttempts(-1).setConfirmationWindowSize(1024 * 1024); ClientSessionFactory factory = createSessionFactory(locator); - - session = (ClientSessionInternal)factory.createSession(); + session = (ClientSessionInternal) factory.createSession(); final AtomicInteger count = new AtomicInteger(0); final CountDownLatch latch = new CountDownLatch(1); - session.addFailureListener(new SessionFailureListener() - { + session.addFailureListener(new SessionFailureListener() { @Override - public void connectionFailed(final ActiveMQException me, boolean failedOver) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver) { count.incrementAndGet(); latch.countDown(); } @Override - public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) { connectionFailed(me, failedOver); } - public void beforeReconnect(final ActiveMQException exception) - { + public void beforeReconnect(final ActiveMQException exception) { } }); @@ -112,14 +97,11 @@ public class ReconnectTest extends ActiveMQTestBase locator.close(); } - finally - { - try - { + finally { + try { session.close(); } - catch (Throwable e) - { + catch (Throwable e) { } server.stop(); @@ -128,116 +110,93 @@ public class ReconnectTest extends ActiveMQTestBase } @Test - public void testInterruptReconnectNetty() throws Exception - { + public void testInterruptReconnectNetty() throws Exception { internalTestInterruptReconnect(true, false); } @Test - public void testInterruptReconnectInVM() throws Exception - { + public void testInterruptReconnectInVM() throws Exception { internalTestInterruptReconnect(false, false); } @Test - public void testInterruptReconnectNettyInterruptMainThread() throws Exception - { + public void testInterruptReconnectNettyInterruptMainThread() throws Exception { internalTestInterruptReconnect(true, true); } @Test - public void testInterruptReconnectInVMInterruptMainThread() throws Exception - { + public void testInterruptReconnectInVMInterruptMainThread() throws Exception { internalTestInterruptReconnect(false, true); } - public void internalTestInterruptReconnect(final boolean isNetty, final boolean interruptMainThread) throws Exception - { + public void internalTestInterruptReconnect(final boolean isNetty, + final boolean interruptMainThread) throws Exception { final int pingPeriod = 1000; ActiveMQServer server = createServer(false, isNetty); server.start(); - try - { - ServerLocator locator = createFactory(isNetty) - .setClientFailureCheckPeriod(pingPeriod) - .setRetryInterval(500) - .setRetryIntervalMultiplier(1d) - .setReconnectAttempts(-1) - .setConfirmationWindowSize(1024 * 1024); - ClientSessionFactoryInternal factory = (ClientSessionFactoryInternal)locator.createSessionFactory(); + try { + ServerLocator locator = createFactory(isNetty).setClientFailureCheckPeriod(pingPeriod).setRetryInterval(500).setRetryIntervalMultiplier(1d).setReconnectAttempts(-1).setConfirmationWindowSize(1024 * 1024); + ClientSessionFactoryInternal factory = (ClientSessionFactoryInternal) locator.createSessionFactory(); // One for beforeReconnecto from the Factory, and one for the commit about to be done final CountDownLatch latchCommit = new CountDownLatch(2); final ArrayList threadToBeInterrupted = new ArrayList(); - factory.addFailureListener(new SessionFailureListener() - { + factory.addFailureListener(new SessionFailureListener() { @Override - public void connectionFailed(ActiveMQException exception, boolean failedOver) - { + public void connectionFailed(ActiveMQException exception, boolean failedOver) { } @Override - public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) { connectionFailed(me, failedOver); } @Override - public void beforeReconnect(ActiveMQException exception) - { + public void beforeReconnect(ActiveMQException exception) { latchCommit.countDown(); threadToBeInterrupted.add(Thread.currentThread()); System.out.println("Thread " + Thread.currentThread() + " reconnecting now"); } }); - - final ClientSessionInternal session = (ClientSessionInternal)factory.createSession(); + final ClientSessionInternal session = (ClientSessionInternal) factory.createSession(); final AtomicInteger count = new AtomicInteger(0); final CountDownLatch latch = new CountDownLatch(1); - session.addFailureListener(new SessionFailureListener() - { + session.addFailureListener(new SessionFailureListener() { - public void connectionFailed(final ActiveMQException me, boolean failedOver) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver) { count.incrementAndGet(); latch.countDown(); } @Override - public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) - { + public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) { connectionFailed(me, failedOver); } - public void beforeReconnect(final ActiveMQException exception) - { + public void beforeReconnect(final ActiveMQException exception) { } }); server.stop(); - Thread tcommitt = new Thread() - { - public void run() - { + Thread tcommitt = new Thread() { + public void run() { latchCommit.countDown(); - try - { + try { session.commit(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { e.printStackTrace(); } } @@ -249,14 +208,11 @@ public class ReconnectTest extends ActiveMQTestBase // There should be only one thread assertEquals(1, threadToBeInterrupted.size()); - if (interruptMainThread) - { + if (interruptMainThread) { tcommitt.interrupt(); } - else - { - for (Thread tint: threadToBeInterrupted) - { + else { + for (Thread tint : threadToBeInterrupted) { tint.interrupt(); } } @@ -266,8 +222,7 @@ public class ReconnectTest extends ActiveMQTestBase locator.close(); } - finally - { + finally { } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/SynchronousCloseTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/SynchronousCloseTest.java index b0f0db1497..d34b15b09a 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/SynchronousCloseTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/SynchronousCloseTest.java @@ -26,8 +26,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class SynchronousCloseTest extends ActiveMQTestBase -{ +public class SynchronousCloseTest extends ActiveMQTestBase { private ActiveMQServer server; @@ -43,30 +42,24 @@ public class SynchronousCloseTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - Configuration config = createDefaultConfig(isNetty()) - .setSecurityEnabled(false); + Configuration config = createDefaultConfig(isNetty()).setSecurityEnabled(false); server = createServer(false, config); server.start(); } - protected boolean isNetty() - { + protected boolean isNetty() { return false; } - protected ClientSessionFactory createSessionFactory() throws Exception - { + protected ClientSessionFactory createSessionFactory() throws Exception { ServerLocator locator; - if (isNetty()) - { + if (isNetty()) { locator = createNettyNonHALocator(); } - else - { + else { locator = createInVMNonHALocator(); } @@ -78,14 +71,12 @@ public class SynchronousCloseTest extends ActiveMQTestBase * DoS attack */ @Test - public void testSynchronousClose() throws Exception - { + public void testSynchronousClose() throws Exception { Assert.assertEquals(0, server.getActiveMQServerControl().listRemoteAddresses().length); ClientSessionFactory sf = createSessionFactory(); - for (int i = 0; i < 2000; i++) - { + for (int i = 0; i < 2000; i++) { ClientSession session = sf.createSession(false, true, true); session.close(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/replication/ReplicationOrderTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/replication/ReplicationOrderTest.java index 0f41ca09b2..9c7badefc2 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/replication/ReplicationOrderTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/replication/ReplicationOrderTest.java @@ -32,65 +32,53 @@ import org.apache.activemq.artemis.tests.integration.cluster.failover.FailoverTe import org.apache.activemq.artemis.tests.util.RandomUtil; import org.apache.activemq.artemis.tests.util.TransportConfigurationUtils; -public class ReplicationOrderTest extends FailoverTestBase -{ +public class ReplicationOrderTest extends FailoverTestBase { public static final int NUM = 300; @Test - public void testMixedPersistentAndNonPersistentMessagesOrderWithReplicatedBackup() throws Exception - { + public void testMixedPersistentAndNonPersistentMessagesOrderWithReplicatedBackup() throws Exception { doTestMixedPersistentAndNonPersistentMessagesOrderWithReplicatedBackup(false); } @Test - public void testTxMixedPersistentAndNonPersistentMessagesOrderWithReplicatedBackup() throws Exception - { + public void testTxMixedPersistentAndNonPersistentMessagesOrderWithReplicatedBackup() throws Exception { doTestMixedPersistentAndNonPersistentMessagesOrderWithReplicatedBackup(true); } - private void doTestMixedPersistentAndNonPersistentMessagesOrderWithReplicatedBackup(final boolean transactional) throws Exception - { + private void doTestMixedPersistentAndNonPersistentMessagesOrderWithReplicatedBackup(final boolean transactional) throws Exception { String address = RandomUtil.randomString(); String queue = RandomUtil.randomString(); ServerLocator locator = ActiveMQClient.createServerLocatorWithoutHA(getConnectorTransportConfiguration(true)); addServerLocator(locator); - locator.setBlockOnNonDurableSend(false) - .setBlockOnDurableSend(false); + locator.setBlockOnNonDurableSend(false).setBlockOnDurableSend(false); ClientSessionFactory csf = createSessionFactory(locator); ClientSession session = null; - if (transactional) - { + if (transactional) { session = csf.createSession(false, false); } - else - { + else { session = csf.createSession(true, true); } addClientSession(session); session.createQueue(address, queue, true); ClientProducer producer = session.createProducer(address); boolean durable = false; - for (int i = 0; i < ReplicationOrderTest.NUM; i++) - { + for (int i = 0; i < ReplicationOrderTest.NUM; i++) { ClientMessage msg = session.createMessage(durable); msg.putIntProperty("counter", i); producer.send(msg); - if (transactional) - { - if (i % 10 == 0) - { + if (transactional) { + if (i % 10 == 0) { session.commit(); durable = !durable; } } - else - { + else { durable = !durable; } } - if (transactional) - { + if (transactional) { session.commit(); } session.close(); @@ -100,8 +88,7 @@ public class ReplicationOrderTest extends FailoverTestBase session = csf.createSession(true, true); session.start(); ClientConsumer consumer = session.createConsumer(queue); - for (int i = 0; i < ReplicationOrderTest.NUM; i++) - { + for (int i = 0; i < ReplicationOrderTest.NUM; i++) { ClientMessage message = consumer.receive(1000); Assert.assertNotNull(message); Assert.assertEquals(i, message.getIntProperty("counter").intValue()); @@ -114,20 +101,17 @@ public class ReplicationOrderTest extends FailoverTestBase } @Override - protected void createConfigs() throws Exception - { + protected void createConfigs() throws Exception { createReplicatedConfigs(); } @Override - protected TransportConfiguration getConnectorTransportConfiguration(final boolean live) - { + protected TransportConfiguration getConnectorTransportConfiguration(final boolean live) { return TransportConfigurationUtils.getInVMConnector(live); } @Override - protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live) - { + protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live) { return TransportConfigurationUtils.getInVMAcceptor(live); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/replication/ReplicationTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/replication/ReplicationTest.java index d1f475562b..5b1a4b387e 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/replication/ReplicationTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/replication/ReplicationTest.java @@ -92,8 +92,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public final class ReplicationTest extends ActiveMQTestBase -{ +public final class ReplicationTest extends ActiveMQTestBase { private ThreadFactory tFactory; private ExecutorService executor; @@ -111,29 +110,25 @@ public final class ReplicationTest extends ActiveMQTestBase private ReplicationManager manager; private static final SimpleString ADDRESS = new SimpleString("foobar123"); - - private void setupServer(boolean backup, String... interceptors) throws Exception - { + private void setupServer(boolean backup, String... interceptors) throws Exception { this.setupServer(false, backup, null, interceptors); } - private void setupServer(boolean useNetty, boolean backup, + private void setupServer(boolean useNetty, + boolean backup, ExtraConfigurer extraConfig, - String... incomingInterceptors) throws Exception - { + String... incomingInterceptors) throws Exception { TransportConfiguration liveConnector = null; TransportConfiguration liveAcceptor = null; TransportConfiguration backupConnector = null; TransportConfiguration backupAcceptor = null; - if (useNetty) - { + if (useNetty) { liveConnector = TransportConfigurationUtils.getNettyConnector(true, 0); liveAcceptor = TransportConfigurationUtils.getNettyAcceptor(true, 0); backupConnector = TransportConfigurationUtils.getNettyConnector(false, 0); backupAcceptor = TransportConfigurationUtils.getNettyAcceptor(false, 0); } - else - { + else { liveConnector = TransportConfigurationUtils.getInVMConnector(true); backupConnector = TransportConfigurationUtils.getInVMConnector(false); backupAcceptor = TransportConfigurationUtils.getInVMAcceptor(false); @@ -141,96 +136,76 @@ public final class ReplicationTest extends ActiveMQTestBase Configuration liveConfig = createDefaultInVMConfig(); - Configuration backupConfig = createDefaultInVMConfig() - .setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration()) - .setBindingsDirectory(getBindingsDir(0, true)) - .setJournalDirectory(getJournalDir(0, true)) - .setPagingDirectory(getPageDir(0, true)) - .setLargeMessagesDirectory(getLargeMessagesDir(0, true)) - .setIncomingInterceptorClassNames(incomingInterceptors.length > 0 ? Arrays.asList(incomingInterceptors) : new ArrayList()); + Configuration backupConfig = createDefaultInVMConfig().setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration()).setBindingsDirectory(getBindingsDir(0, true)).setJournalDirectory(getJournalDir(0, true)).setPagingDirectory(getPageDir(0, true)).setLargeMessagesDirectory(getLargeMessagesDir(0, true)).setIncomingInterceptorClassNames(incomingInterceptors.length > 0 ? Arrays.asList(incomingInterceptors) : new ArrayList()); ReplicatedBackupUtils.configureReplicationPair(backupConfig, backupConnector, backupAcceptor, liveConfig, liveConnector, liveAcceptor); - if (extraConfig != null) - { + if (extraConfig != null) { extraConfig.config(liveConfig, backupConfig); } - if (backup) - { + if (backup) { liveServer = createServer(liveConfig); liveServer.start(); waitForComponent(liveServer); } backupServer = createServer(backupConfig); - if (useNetty) - { + if (useNetty) { locator = createNettyNonHALocator(); } - else - { + else { locator = createInVMNonHALocator(); } backupServer.start(); - if (backup) - { + if (backup) { ActiveMQTestBase.waitForRemoteBackup(null, 5, true, backupServer); } int count = 0; waitForReplication(count); } - private void waitForReplication(int count) throws InterruptedException - { + private void waitForReplication(int count) throws InterruptedException { if (liveServer == null) return; - while (liveServer.getReplicationManager() == null && count < 10) - { + while (liveServer.getReplicationManager() == null && count < 10) { Thread.sleep(50); count++; } } - private static void waitForComponent(ActiveMQComponent component) throws Exception - { + private static void waitForComponent(ActiveMQComponent component) throws Exception { waitForComponent(component, 3); } @Test - public void testBasicConnection() throws Exception - { + public void testBasicConnection() throws Exception { setupServer(true); waitForComponent(liveServer.getReplicationManager()); } @Test - public void testConnectIntoNonBackup() throws Exception - { + public void testConnectIntoNonBackup() throws Exception { setupServer(false); - try - { + try { ClientSessionFactory sf = createSessionFactory(locator); manager = new ReplicationManager((CoreRemotingConnection) sf.getConnection(), factory); addActiveMQComponent(manager); manager.start(); Assert.fail("Exception was expected"); } - catch (ActiveMQNotConnectedException nce) - { + catch (ActiveMQNotConnectedException nce) { // ok } - catch (ActiveMQException expected) - { + catch (ActiveMQException expected) { fail("Invalid Exception type:" + expected.getType()); } } @Test - public void testSendPackets() throws Exception - { + public void testSendPackets() throws Exception { setupServer(true); StorageManager storage = getStorage(); @@ -272,9 +247,7 @@ public final class ReplicationTest extends ActiveMQTestBase blockOnReplication(storage, manager); - PagingManager pagingManager = - createPageManager(backupServer.getStorageManager(), backupServer.getConfiguration(), - backupServer.getExecutorFactory(), backupServer.getAddressSettingsRepository()); + PagingManager pagingManager = createPageManager(backupServer.getStorageManager(), backupServer.getConfiguration(), backupServer.getExecutorFactory(), backupServer.getAddressSettingsRepository()); PagingStore store = pagingManager.getPageStore(dummy); store.start(); @@ -311,8 +284,7 @@ public final class ReplicationTest extends ActiveMQTestBase } @Test - public void testSendPacketsWithFailure() throws Exception - { + public void testSendPacketsWithFailure() throws Exception { final int nMsg = 100; final int stop = 37; setupServer(true, TestInterceptor.class.getName()); @@ -328,18 +300,15 @@ public final class ReplicationTest extends ActiveMQTestBase session.start(); session2.start(); - try - { + try { final ClientConsumer consumer = session2.createConsumer(ADDRESS); - for (int i = 0; i < nMsg; i++) - { + for (int i = 0; i < nMsg; i++) { ClientMessage message = session.createMessage(true); setBody(i, message); message.putIntProperty("counter", i); producer.send(message); - if (i == stop) - { + if (i == stop) { // Now we start intercepting the communication with the backup TestInterceptor.value.set(false); } @@ -350,8 +319,7 @@ public final class ReplicationTest extends ActiveMQTestBase msgRcvd.acknowledge(); } } - finally - { + finally { TestInterceptor.value.set(false); if (!session.isClosed()) session.close(); @@ -361,8 +329,7 @@ public final class ReplicationTest extends ActiveMQTestBase } @Test - public void testExceptionSettingActionBefore() throws Exception - { + public void testExceptionSettingActionBefore() throws Exception { OperationContext ctx = OperationContextImpl.getContext(factory); ctx.storeLineUp(); @@ -377,17 +344,14 @@ public final class ReplicationTest extends ActiveMQTestBase final CountDownLatch latch = new CountDownLatch(1); - ctx.executeOnCompletion(new IOCallback() - { - public void onError(final int errorCode, final String errorMessage) - { + ctx.executeOnCompletion(new IOCallback() { + public void onError(final int errorCode, final String errorMessage) { lastError.set(errorCode); msgsResult.add(errorMessage); latch.countDown(); } - public void done() - { + public void done() { } }); @@ -402,17 +366,14 @@ public final class ReplicationTest extends ActiveMQTestBase final CountDownLatch latch2 = new CountDownLatch(1); // Adding the Task after the exception should still throw an exception - ctx.executeOnCompletion(new IOCallback() - { - public void onError(final int errorCode, final String errorMessage) - { + ctx.executeOnCompletion(new IOCallback() { + public void onError(final int errorCode, final String errorMessage) { lastError.set(errorCode); msgsResult.add(errorMessage); latch2.countDown(); } - public void done() - { + public void done() { } }); @@ -426,14 +387,11 @@ public final class ReplicationTest extends ActiveMQTestBase final CountDownLatch latch3 = new CountDownLatch(1); - ctx.executeOnCompletion(new IOCallback() - { - public void onError(final int errorCode, final String errorMessage) - { + ctx.executeOnCompletion(new IOCallback() { + public void onError(final int errorCode, final String errorMessage) { } - public void done() - { + public void done() { latch3.countDown(); } }); @@ -443,16 +401,14 @@ public final class ReplicationTest extends ActiveMQTestBase } @Test - public void testClusterConnectionConfigs() throws Exception - { + public void testClusterConnectionConfigs() throws Exception { final long ttlOverride = 123456789; final long checkPeriodOverride = 987654321; ExtraConfigurer configurer = new ExtraConfigurer() { @Override - public void config(Configuration liveConfig, Configuration backupConfig) - { + public void config(Configuration liveConfig, Configuration backupConfig) { List ccList = backupConfig.getClusterConfigurations(); assertTrue(ccList.size() > 0); ClusterConnectionConfiguration cc = ccList.get(0); @@ -477,26 +433,21 @@ public final class ReplicationTest extends ActiveMQTestBase * @return * @throws Exception */ - private JournalStorageManager getStorage() throws Exception - { + private JournalStorageManager getStorage() throws Exception { return new JournalStorageManager(createDefaultInVMConfig(), factory, null); } /** * @param manager1 */ - private void blockOnReplication(final StorageManager storage, final ReplicationManager manager1) throws Exception - { + private void blockOnReplication(final StorageManager storage, final ReplicationManager manager1) throws Exception { final CountDownLatch latch = new CountDownLatch(1); - storage.afterCompleteOperations(new IOCallback() - { + storage.afterCompleteOperations(new IOCallback() { - public void onError(final int errorCode, final String errorMessage) - { + public void onError(final int errorCode, final String errorMessage) { } - public void done() - { + public void done() { latch.countDown(); } }); @@ -505,8 +456,7 @@ public final class ReplicationTest extends ActiveMQTestBase } @Test - public void testNoActions() throws Exception - { + public void testNoActions() throws Exception { setupServer(true); StorageManager storage = getStorage(); @@ -518,15 +468,12 @@ public final class ReplicationTest extends ActiveMQTestBase replicatedJournal.appendPrepareRecord(1, new FakeData(), false); final CountDownLatch latch = new CountDownLatch(1); - storage.afterCompleteOperations(new IOCallback() - { + storage.afterCompleteOperations(new IOCallback() { - public void onError(final int errorCode, final String errorMessage) - { + public void onError(final int errorCode, final String errorMessage) { } - public void done() - { + public void done() { latch.countDown(); } }); @@ -537,8 +484,7 @@ public final class ReplicationTest extends ActiveMQTestBase } @Test - public void testOrderOnNonPersistency() throws Exception - { + public void testOrderOnNonPersistency() throws Exception { setupServer(true); @@ -554,24 +500,19 @@ public final class ReplicationTest extends ActiveMQTestBase OperationContext ctx = storage.getContext(); - for (int i = 0; i < numberOfAdds; i++) - { + for (int i = 0; i < numberOfAdds; i++) { final int nAdd = i; - if (i % 2 == 0) - { + if (i % 2 == 0) { replicatedJournal.appendPrepareRecord(i, new FakeData(), false); } - ctx.executeOnCompletion(new IOCallback() - { + ctx.executeOnCompletion(new IOCallback() { - public void onError(final int errorCode, final String errorMessage) - { + public void onError(final int errorCode, final String errorMessage) { } - public void done() - { + public void done() { executions.add(nAdd); latch.countDown(); } @@ -580,28 +521,23 @@ public final class ReplicationTest extends ActiveMQTestBase Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); - for (int i = 0; i < numberOfAdds; i++) - { + for (int i = 0; i < numberOfAdds; i++) { Assert.assertEquals(i, executions.get(i).intValue()); } Assert.assertEquals(0, manager.getActiveTokens().size()); } - class FakeData implements EncodingSupport - { + class FakeData implements EncodingSupport { - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { } - public void encode(final ActiveMQBuffer buffer) - { + public void encode(final ActiveMQBuffer buffer) { buffer.writeBytes(new byte[5]); } - public int getEncodeSize() - { + public int getEncodeSize() { return 5; } @@ -609,8 +545,7 @@ public final class ReplicationTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); tFactory = new ActiveMQThreadFactory("ActiveMQ-ReplicationTest", false, this.getClass().getClassLoader()); @@ -628,8 +563,7 @@ public final class ReplicationTest extends ActiveMQTestBase */ @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { stopComponent(manager); manager = null; closeServerLocator(locator); @@ -650,13 +584,9 @@ public final class ReplicationTest extends ActiveMQTestBase protected PagingManager createPageManager(final StorageManager storageManager, final Configuration configuration, final ExecutorFactory executorFactory, - final HierarchicalRepository addressSettingsRepository) throws Exception - { + final HierarchicalRepository addressSettingsRepository) throws Exception { - PagingManager paging = new PagingManagerImpl(new PagingStoreFactoryNIO(storageManager, configuration.getPagingLocation(), - 1000, null, - executorFactory, false, null), - addressSettingsRepository); + PagingManager paging = new PagingManagerImpl(new PagingStoreFactoryNIO(storageManager, configuration.getPagingLocation(), 1000, null, executorFactory, false, null), addressSettingsRepository); paging.start(); return paging; @@ -665,171 +595,153 @@ public final class ReplicationTest extends ActiveMQTestBase // Private ------------------------------------------------------- // Inner classes ------------------------------------------------- - public static final class TestInterceptor implements Interceptor - { + public static final class TestInterceptor implements Interceptor { + static AtomicBoolean value = new AtomicBoolean(true); - public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException - { + public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { return TestInterceptor.value.get(); } } - static final class FakeJournal implements Journal - { + static final class FakeJournal implements Journal { - public void - appendAddRecord(final long id, final byte recordType, final byte[] record, final boolean sync) throws Exception - { + public void appendAddRecord(final long id, + final byte recordType, + final byte[] record, + final boolean sync) throws Exception { } public void appendAddRecord(final long id, final byte recordType, final EncodingSupport record, - final boolean sync) throws Exception - { + final boolean sync) throws Exception { } public void appendAddRecordTransactional(final long txID, final long id, final byte recordType, - final byte[] record) throws Exception - { + final byte[] record) throws Exception { } public void appendAddRecordTransactional(final long txID, final long id, final byte recordType, - final EncodingSupport record) throws Exception - { + final EncodingSupport record) throws Exception { } - public void appendCommitRecord(final long txID, final boolean sync) throws Exception - { + public void appendCommitRecord(final long txID, final boolean sync) throws Exception { } - public void appendDeleteRecord(final long id, final boolean sync) throws Exception - { + public void appendDeleteRecord(final long id, final boolean sync) throws Exception { } - public void appendDeleteRecordTransactional(final long txID, final long id, final byte[] record) throws Exception - { + public void appendDeleteRecordTransactional(final long txID, + final long id, + final byte[] record) throws Exception { } - public void - appendDeleteRecordTransactional(final long txID, final long id, final EncodingSupport record) throws Exception - { + public void appendDeleteRecordTransactional(final long txID, + final long id, + final EncodingSupport record) throws Exception { } - public void appendDeleteRecordTransactional(final long txID, final long id) throws Exception - { + public void appendDeleteRecordTransactional(final long txID, final long id) throws Exception { } - public void - appendPrepareRecord(final long txID, final EncodingSupport transactionData, final boolean sync) throws Exception - { + public void appendPrepareRecord(final long txID, + final EncodingSupport transactionData, + final boolean sync) throws Exception { } - public void - appendPrepareRecord(final long txID, final byte[] transactionData, final boolean sync) throws Exception - { + public void appendPrepareRecord(final long txID, + final byte[] transactionData, + final boolean sync) throws Exception { } - public void appendRollbackRecord(final long txID, final boolean sync) throws Exception - { + public void appendRollbackRecord(final long txID, final boolean sync) throws Exception { } - public void - appendUpdateRecord(final long id, final byte recordType, final byte[] record, final boolean sync) throws Exception - { + public void appendUpdateRecord(final long id, + final byte recordType, + final byte[] record, + final boolean sync) throws Exception { } public void appendUpdateRecord(final long id, final byte recordType, final EncodingSupport record, - final boolean sync) throws Exception - { + final boolean sync) throws Exception { } public void appendUpdateRecordTransactional(final long txID, final long id, final byte recordType, - final byte[] record) throws Exception - { + final byte[] record) throws Exception { } public void appendUpdateRecordTransactional(final long txID, final long id, final byte recordType, - final EncodingSupport record) throws Exception - { + final EncodingSupport record) throws Exception { } - public int getAlignment() throws Exception - { + public int getAlignment() throws Exception { return 0; } - public JournalLoadInformation load(final LoaderCallback reloadManager) throws Exception - { + public JournalLoadInformation load(final LoaderCallback reloadManager) throws Exception { return new JournalLoadInformation(); } public JournalLoadInformation load(final List committedRecords, final List preparedTransactions, - final TransactionFailureCallback transactionFailure) throws Exception - { + final TransactionFailureCallback transactionFailure) throws Exception { return new JournalLoadInformation(); } - public void perfBlast(final int pages) - { + public void perfBlast(final int pages) { } - public boolean isStarted() - { + public boolean isStarted() { return false; } - public void start() throws Exception - { + public void start() throws Exception { } - public void stop() throws Exception - { + public void stop() throws Exception { } - public JournalLoadInformation loadInternalOnly() throws Exception - { + public JournalLoadInformation loadInternalOnly() throws Exception { return new JournalLoadInformation(); } - public int getNumberOfRecords() - { + public int getNumberOfRecords() { return 0; } @@ -837,133 +749,117 @@ public final class ReplicationTest extends ActiveMQTestBase final byte recordType, final EncodingSupport record, final boolean sync, - final IOCompletion completionCallback) throws Exception - { + final IOCompletion completionCallback) throws Exception { } - public void appendCommitRecord(final long txID, final boolean sync, final IOCompletion callback) throws Exception - { + public void appendCommitRecord(final long txID, + final boolean sync, + final IOCompletion callback) throws Exception { } - public void - appendDeleteRecord(final long id, final boolean sync, final IOCompletion completionCallback) throws Exception - { + public void appendDeleteRecord(final long id, + final boolean sync, + final IOCompletion completionCallback) throws Exception { } public void appendPrepareRecord(final long txID, final EncodingSupport transactionData, final boolean sync, - final IOCompletion callback) throws Exception - { + final IOCompletion callback) throws Exception { } - public void - appendRollbackRecord(final long txID, final boolean sync, final IOCompletion callback) throws Exception - { + public void appendRollbackRecord(final long txID, + final boolean sync, + final IOCompletion callback) throws Exception { } public void appendUpdateRecord(final long id, final byte recordType, final EncodingSupport record, final boolean sync, - final IOCompletion completionCallback) throws Exception - { + final IOCompletion completionCallback) throws Exception { } - public void sync(final IOCompletion callback) - { + public void sync(final IOCompletion callback) { } - public void runDirectJournalBlast() throws Exception - { + public void runDirectJournalBlast() throws Exception { } - public int getUserVersion() - { + public int getUserVersion() { return 0; } @Override - public void - appendCommitRecord(long txID, boolean sync, IOCompletion callback, boolean lineUpContext) throws Exception - { + public void appendCommitRecord(long txID, + boolean sync, + IOCompletion callback, + boolean lineUpContext) throws Exception { } @Override - public void lineUpContext(IOCompletion callback) - { + public void lineUpContext(IOCompletion callback) { } @Override - public JournalLoadInformation loadSyncOnly(JournalState s) throws Exception - { + public JournalLoadInformation loadSyncOnly(JournalState s) throws Exception { return null; } @Override - public Map createFilesForBackupSync(long[] fileIds) throws Exception - { + public Map createFilesForBackupSync(long[] fileIds) throws Exception { return null; } @Override - public void synchronizationLock() - { + public void synchronizationLock() { } @Override - public void synchronizationUnlock() - { + public void synchronizationUnlock() { } @Override - public void forceMoveNextFile() throws Exception - { + public void forceMoveNextFile() throws Exception { } @Override - public JournalFile[] getDataFiles() - { + public JournalFile[] getDataFiles() { return null; } @Override - public SequentialFileFactory getFileFactory() - { + public SequentialFileFactory getFileFactory() { return null; } @Override - public int getFileSize() - { + public int getFileSize() { return 0; } @Override - public void scheduleCompactAndBlock(int timeout) throws Exception - { + public void scheduleCompactAndBlock(int timeout) throws Exception { } @Override - public void replicationSyncPreserveOldFiles() - { + public void replicationSyncPreserveOldFiles() { // no-op } @Override - public void replicationSyncFinished() - { + public void replicationSyncFinished() { // no-op } } - private interface ExtraConfigurer - { + private interface ExtraConfigurer { + void config(Configuration liveConfig, Configuration backupConfig); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/scheduling/DelayedMessageTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/scheduling/DelayedMessageTest.java index 2a59f29781..007d85086d 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/scheduling/DelayedMessageTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/scheduling/DelayedMessageTest.java @@ -31,8 +31,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class DelayedMessageTest extends ActiveMQTestBase -{ +public class DelayedMessageTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private ActiveMQServer server; @@ -45,8 +45,7 @@ public class DelayedMessageTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); initServer(); } @@ -54,8 +53,7 @@ public class DelayedMessageTest extends ActiveMQTestBase /** * @throws Exception */ - protected void initServer() throws Exception - { + protected void initServer() throws Exception { server = createServer(true, createDefaultInVMConfig()); server.start(); @@ -67,8 +65,7 @@ public class DelayedMessageTest extends ActiveMQTestBase } @Test - public void testDelayedRedeliveryDefaultOnClose() throws Exception - { + public void testDelayedRedeliveryDefaultOnClose() throws Exception { ClientSessionFactory sessionFactory = createSessionFactory(locator); ClientSession session = sessionFactory.createSession(false, false, false); @@ -82,8 +79,7 @@ public class DelayedMessageTest extends ActiveMQTestBase ActiveMQTestBase.forceGC(); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { ClientMessage tm = createDurableMessage(session1, "message" + i); producer.send(tm); } @@ -95,8 +91,7 @@ public class DelayedMessageTest extends ActiveMQTestBase ClientConsumer consumer2 = session2.createConsumer(qName); session2.start(); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { ClientMessage tm = consumer2.receive(500); tm.acknowledge(); @@ -117,8 +112,7 @@ public class DelayedMessageTest extends ActiveMQTestBase ClientConsumer consumer3 = session3.createConsumer(qName); session3.start(); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { ClientMessage tm = consumer3.receive(DelayedMessageTest.DELAY + 1000); Assert.assertNotNull(tm); @@ -130,19 +124,16 @@ public class DelayedMessageTest extends ActiveMQTestBase Assert.assertTrue(time - now >= DelayedMessageTest.DELAY); // Hudson can introduce a large degree of indeterminism - Assert.assertTrue(time - now + ">" + (DelayedMessageTest.DELAY + 1000), - time - now < DelayedMessageTest.DELAY + 1000); + Assert.assertTrue(time - now + ">" + (DelayedMessageTest.DELAY + 1000), time - now < DelayedMessageTest.DELAY + 1000); } session3.commit(); session3.close(); - } @Test - public void testDelayedRedeliveryDefaultOnRollback() throws Exception - { + public void testDelayedRedeliveryDefaultOnRollback() throws Exception { ClientSessionFactory sessionFactory = createSessionFactory(locator); ClientSession session = sessionFactory.createSession(false, false, false); @@ -154,8 +145,7 @@ public class DelayedMessageTest extends ActiveMQTestBase final int NUM_MESSAGES = 5; - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { ClientMessage tm = createDurableMessage(session1, "message" + i); producer.send(tm); } @@ -166,8 +156,7 @@ public class DelayedMessageTest extends ActiveMQTestBase session2.start(); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { ClientMessage tm = consumer2.receive(500); Assert.assertNotNull(tm); Assert.assertEquals("message" + i, tm.getBodyBuffer().readString()); @@ -180,8 +169,7 @@ public class DelayedMessageTest extends ActiveMQTestBase // This should redeliver with a delayed redelivery - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { ClientMessage tm = consumer2.receive(DelayedMessageTest.DELAY + 1000); Assert.assertNotNull(tm); @@ -190,19 +178,16 @@ public class DelayedMessageTest extends ActiveMQTestBase Assert.assertTrue(time - now >= DelayedMessageTest.DELAY); // Hudson can introduce a large degree of indeterminism - Assert.assertTrue(time - now + ">" + (DelayedMessageTest.DELAY + 1000), - time - now < DelayedMessageTest.DELAY + 1000); + Assert.assertTrue(time - now + ">" + (DelayedMessageTest.DELAY + 1000), time - now < DelayedMessageTest.DELAY + 1000); } session2.commit(); session2.close(); - } @Test - public void testDelayedRedeliveryWithStart() throws Exception - { + public void testDelayedRedeliveryWithStart() throws Exception { ClientSessionFactory sessionFactory = createSessionFactory(locator); ClientSession session = sessionFactory.createSession(false, false, false); @@ -214,8 +199,7 @@ public class DelayedMessageTest extends ActiveMQTestBase final int NUM_MESSAGES = 1; - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { ClientMessage tm = createDurableMessage(session1, "message" + i); producer.send(tm); } @@ -226,8 +210,7 @@ public class DelayedMessageTest extends ActiveMQTestBase session2.start(); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { ClientMessage tm = consumer2.receive(500); Assert.assertNotNull(tm); Assert.assertEquals("message" + i, tm.getBodyBuffer().readString()); @@ -236,7 +219,6 @@ public class DelayedMessageTest extends ActiveMQTestBase // Now rollback long now = System.currentTimeMillis(); - session2.rollback(); session2.close(); @@ -261,8 +243,7 @@ public class DelayedMessageTest extends ActiveMQTestBase // This should redeliver with a delayed redelivery - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { ClientMessage tm = consumer2.receive(DelayedMessageTest.DELAY + 1000); Assert.assertNotNull(tm); @@ -276,18 +257,12 @@ public class DelayedMessageTest extends ActiveMQTestBase session2.commit(); session2.close(); - } // Private ------------------------------------------------------- - private ClientMessage createDurableMessage(final ClientSession session, final String body) - { - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - true, - 0, - System.currentTimeMillis(), - (byte)1); + private ClientMessage createDurableMessage(final ClientSession session, final String body) { + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, true, 0, System.currentTimeMillis(), (byte) 1); message.getBodyBuffer().writeString(body); return message; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/scheduling/MultipliedDelayedMessageTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/scheduling/MultipliedDelayedMessageTest.java index ebd3bbf311..aae13c2ae1 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/scheduling/MultipliedDelayedMessageTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/scheduling/MultipliedDelayedMessageTest.java @@ -31,8 +31,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class MultipliedDelayedMessageTest extends ActiveMQTestBase -{ +public class MultipliedDelayedMessageTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private ActiveMQServer server; @@ -49,8 +49,7 @@ public class MultipliedDelayedMessageTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); initServer(); } @@ -58,25 +57,20 @@ public class MultipliedDelayedMessageTest extends ActiveMQTestBase /** * @throws Exception */ - protected void initServer() throws Exception - { + protected void initServer() throws Exception { server = createServer(true, createDefaultInVMConfig()); server.start(); // Create settings to enable multiplied redelivery delay AddressSettings addressSettings = server.getAddressSettingsRepository().getMatch("*"); - AddressSettings newAddressSettings = new AddressSettings() - .setRedeliveryDelay(DELAY) - .setRedeliveryMultiplier(MULTIPLIER) - .setMaxRedeliveryDelay(MAX_DELAY); + AddressSettings newAddressSettings = new AddressSettings().setRedeliveryDelay(DELAY).setRedeliveryMultiplier(MULTIPLIER).setMaxRedeliveryDelay(MAX_DELAY); newAddressSettings.merge(addressSettings); server.getAddressSettingsRepository().addMatch(queueName, newAddressSettings); locator = createInVMNonHALocator(); } @Test - public void testMultipliedDelayedRedeliveryOnClose() throws Exception - { + public void testMultipliedDelayedRedeliveryOnClose() throws Exception { ClientSessionFactory sessionFactory = createSessionFactory(locator); // Session for creating the queue @@ -99,8 +93,7 @@ public class MultipliedDelayedMessageTest extends ActiveMQTestBase tm = consumer.receive(500); Assert.assertNotNull(tm); - for (int i = 1; i <= 6; i++) - { + for (int i = 1; i <= 6; i++) { // Ack the message, but rollback the session to trigger redelivery with increasing delivery count long start = System.currentTimeMillis(); tm.acknowledge(); @@ -122,21 +115,21 @@ public class MultipliedDelayedMessageTest extends ActiveMQTestBase // Private ------------------------------------------------------- - private ClientMessage createDurableMessage(final ClientSession session, final String body) - { + private ClientMessage createDurableMessage(final ClientSession session, final String body) { ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, true, 0, System.currentTimeMillis(), (byte) 1); message.getBodyBuffer().writeString(body); return message; } // This is based on org.apache.activemq.artemis.core.server.impl.QueueImpl.calculateRedeliveryDelay() - private long calculateExpectedDelay(final long redeliveryDelay, final long maxRedeliveryDelay, final double redeliveryMultiplier, final int deliveryCount) - { + private long calculateExpectedDelay(final long redeliveryDelay, + final long maxRedeliveryDelay, + final double redeliveryMultiplier, + final int deliveryCount) { int tmpDeliveryCount = deliveryCount > 0 ? deliveryCount - 1 : 0; long delay = (long) (redeliveryDelay * (Math.pow(redeliveryMultiplier, tmpDeliveryCount))); - if (delay > maxRedeliveryDelay) - { + if (delay > maxRedeliveryDelay) { delay = maxRedeliveryDelay; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/scheduling/ScheduledMessageTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/scheduling/ScheduledMessageTest.java index 0f72076fce..11a9c67c0d 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/scheduling/ScheduledMessageTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/scheduling/ScheduledMessageTest.java @@ -41,8 +41,8 @@ import javax.transaction.xa.Xid; import java.util.ArrayList; import java.util.concurrent.atomic.AtomicInteger; -public class ScheduledMessageTest extends ActiveMQTestBase -{ +public class ScheduledMessageTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private final SimpleString atestq = new SimpleString("ascheduledtestq"); @@ -57,8 +57,7 @@ public class ScheduledMessageTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); startServer(); } @@ -66,8 +65,7 @@ public class ScheduledMessageTest extends ActiveMQTestBase /** * @throws Exception */ - protected void startServer() throws Exception - { + protected void startServer() throws Exception { configuration = createDefaultInVMConfig(); server = createServer(true, configuration); server.start(); @@ -75,68 +73,57 @@ public class ScheduledMessageTest extends ActiveMQTestBase } @Test - public void testRecoveredMessageDeliveredCorrectly() throws Exception - { + public void testRecoveredMessageDeliveredCorrectly() throws Exception { testMessageDeliveredCorrectly(true); } @Test - public void testMessageDeliveredCorrectly() throws Exception - { + public void testMessageDeliveredCorrectly() throws Exception { testMessageDeliveredCorrectly(false); } @Test - public void testScheduledMessagesDeliveredCorrectly() throws Exception - { + public void testScheduledMessagesDeliveredCorrectly() throws Exception { testScheduledMessagesDeliveredCorrectly(false); } @Test - public void testRecoveredScheduledMessagesDeliveredCorrectly() throws Exception - { + public void testRecoveredScheduledMessagesDeliveredCorrectly() throws Exception { testScheduledMessagesDeliveredCorrectly(true); } @Test - public void testScheduledMessagesDeliveredCorrectlyDifferentOrder() throws Exception - { + public void testScheduledMessagesDeliveredCorrectlyDifferentOrder() throws Exception { testScheduledMessagesDeliveredCorrectlyDifferentOrder(false); } @Test - public void testRecoveredScheduledMessagesDeliveredCorrectlyDifferentOrder() throws Exception - { + public void testRecoveredScheduledMessagesDeliveredCorrectlyDifferentOrder() throws Exception { testScheduledMessagesDeliveredCorrectlyDifferentOrder(true); } @Test - public void testScheduledAndNormalMessagesDeliveredCorrectly() throws Exception - { + public void testScheduledAndNormalMessagesDeliveredCorrectly() throws Exception { testScheduledAndNormalMessagesDeliveredCorrectly(false); } @Test - public void testRecoveredScheduledAndNormalMessagesDeliveredCorrectly() throws Exception - { + public void testRecoveredScheduledAndNormalMessagesDeliveredCorrectly() throws Exception { testScheduledAndNormalMessagesDeliveredCorrectly(true); } @Test - public void testTxMessageDeliveredCorrectly() throws Exception - { + public void testTxMessageDeliveredCorrectly() throws Exception { testTxMessageDeliveredCorrectly(false); } @Test - public void testRecoveredTxMessageDeliveredCorrectly() throws Exception - { + public void testRecoveredTxMessageDeliveredCorrectly() throws Exception { testTxMessageDeliveredCorrectly(true); } @Test - public void testPagedMessageDeliveredCorrectly() throws Exception - { + public void testPagedMessageDeliveredCorrectly() throws Exception { // then we create a client as normal ClientSessionFactory sessionFactory = createSessionFactory(locator); ClientSession session = sessionFactory.createSession(false, true, false); @@ -169,8 +156,7 @@ public class ScheduledMessageTest extends ActiveMQTestBase } @Test - public void testPagedMessageDeliveredMultipleConsumersCorrectly() throws Exception - { + public void testPagedMessageDeliveredMultipleConsumersCorrectly() throws Exception { AddressSettings qs = new AddressSettings().setRedeliveryDelay(5000L); server.getAddressSettingsRepository().addMatch(atestq.toString(), qs); // then we create a client as normal @@ -221,8 +207,7 @@ public class ScheduledMessageTest extends ActiveMQTestBase } @Test - public void testPagedMessageDeliveredMultipleConsumersAfterRecoverCorrectly() throws Exception - { + public void testPagedMessageDeliveredMultipleConsumersAfterRecoverCorrectly() throws Exception { AddressSettings qs = new AddressSettings().setRedeliveryDelay(5000L); server.getAddressSettingsRepository().addMatch(atestq.toString(), qs); @@ -285,19 +270,14 @@ public class ScheduledMessageTest extends ActiveMQTestBase session.close(); } - public void testMessageDeliveredCorrectly(final boolean recover) throws Exception - { + public void testMessageDeliveredCorrectly(final boolean recover) throws Exception { // then we create a client as normal ClientSessionFactory sessionFactory = createSessionFactory(locator); ClientSession session = sessionFactory.createSession(false, true, false); session.createQueue(atestq, atestq, null, true); ClientProducer producer = session.createProducer(atestq); - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte) 1); + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.getBodyBuffer().writeString("testINVMCoreClient"); message.setDurable(true); long time = System.currentTimeMillis(); @@ -306,8 +286,7 @@ public class ScheduledMessageTest extends ActiveMQTestBase producer.send(message); ScheduledMessageTest.log.info("Recover is " + recover); - if (recover) - { + if (recover) { producer.close(); session.close(); server.stop(); @@ -335,8 +314,7 @@ public class ScheduledMessageTest extends ActiveMQTestBase session.close(); } - public void testScheduledMessagesDeliveredCorrectly(final boolean recover) throws Exception - { + public void testScheduledMessagesDeliveredCorrectly(final boolean recover) throws Exception { ClientSessionFactory sessionFactory = createSessionFactory(locator); ClientSession session = sessionFactory.createSession(false, true, false); @@ -364,8 +342,7 @@ public class ScheduledMessageTest extends ActiveMQTestBase m5.putLongProperty(Message.HDR_SCHEDULED_DELIVERY_TIME, time); producer.send(m5); time -= 4000; - if (recover) - { + if (recover) { producer.close(); session.close(); server.stop(); @@ -415,8 +392,7 @@ public class ScheduledMessageTest extends ActiveMQTestBase session.close(); } - public void testScheduledMessagesDeliveredCorrectlyDifferentOrder(final boolean recover) throws Exception - { + public void testScheduledMessagesDeliveredCorrectlyDifferentOrder(final boolean recover) throws Exception { ClientSessionFactory sessionFactory = createSessionFactory(locator); ClientSession session = sessionFactory.createSession(false, true, false); @@ -445,8 +421,7 @@ public class ScheduledMessageTest extends ActiveMQTestBase producer.send(m5); time -= 2000; ClientConsumer consumer = null; - if (recover) - { + if (recover) { producer.close(); session.close(); server.stop(); @@ -496,10 +471,8 @@ public class ScheduledMessageTest extends ActiveMQTestBase session.close(); } - @Test - public void testManyMessagesSameTime() throws Exception - { + public void testManyMessagesSameTime() throws Exception { ClientSessionFactory sessionFactory = createSessionFactory(locator); ClientSession session = sessionFactory.createSession(false, false, false); @@ -508,8 +481,7 @@ public class ScheduledMessageTest extends ActiveMQTestBase long time = System.currentTimeMillis(); time += 1000; - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage message = session.createMessage(true); message.putIntProperty("value", i); message.putLongProperty(Message.HDR_SCHEDULED_DELIVERY_TIME, time); @@ -518,12 +490,10 @@ public class ScheduledMessageTest extends ActiveMQTestBase session.commit(); - session.start(); ClientConsumer consumer = session.createConsumer(atestq); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ClientMessage message = consumer.receive(15000); assertNotNull(message); message.acknowledge(); @@ -538,8 +508,7 @@ public class ScheduledMessageTest extends ActiveMQTestBase session.close(); } - public void testScheduledAndNormalMessagesDeliveredCorrectly(final boolean recover) throws Exception - { + public void testScheduledAndNormalMessagesDeliveredCorrectly(final boolean recover) throws Exception { ClientSessionFactory sessionFactory = createSessionFactory(locator); ClientSession session = sessionFactory.createSession(false, true, false); @@ -564,8 +533,7 @@ public class ScheduledMessageTest extends ActiveMQTestBase producer.send(m5); time -= 2000; ClientConsumer consumer = null; - if (recover) - { + if (recover) { producer.close(); session.close(); server.stop(); @@ -610,8 +578,7 @@ public class ScheduledMessageTest extends ActiveMQTestBase session.close(); } - public void testTxMessageDeliveredCorrectly(final boolean recover) throws Exception - { + public void testTxMessageDeliveredCorrectly(final boolean recover) throws Exception { Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); Xid xid2 = new XidImpl("xa2".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); @@ -626,8 +593,7 @@ public class ScheduledMessageTest extends ActiveMQTestBase producer.send(message); session.end(xid, XAResource.TMSUCCESS); session.prepare(xid); - if (recover) - { + if (recover) { producer.close(); session.close(); server.stop(); @@ -662,10 +628,8 @@ public class ScheduledMessageTest extends ActiveMQTestBase session.close(); } - @Test - public void testPendingACKOnPrepared() throws Exception - { + public void testPendingACKOnPrepared() throws Exception { int NUMBER_OF_MESSAGES = 100; @@ -676,8 +640,7 @@ public class ScheduledMessageTest extends ActiveMQTestBase ClientProducer producer = session.createProducer(atestq); long scheduled = System.currentTimeMillis() + 1000; - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { ClientMessage msg = session.createMessage(true); msg.putIntProperty("value", i); msg.putLongProperty(Message.HDR_SCHEDULED_DELIVERY_TIME, scheduled); @@ -686,9 +649,7 @@ public class ScheduledMessageTest extends ActiveMQTestBase session.close(); - - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { Xid xid = newXID(); session = sessionFactory.createSession(true, false, false); @@ -733,20 +694,17 @@ public class ScheduledMessageTest extends ActiveMQTestBase } @Test - public void testScheduledDeliveryTX() throws Exception - { + public void testScheduledDeliveryTX() throws Exception { scheduledDelivery(true); } @Test - public void testScheduledDeliveryNoTX() throws Exception - { + public void testScheduledDeliveryNoTX() throws Exception { scheduledDelivery(false); } @Test - public void testRedeliveryAfterPrepare() throws Exception - { + public void testRedeliveryAfterPrepare() throws Exception { AddressSettings qs = new AddressSettings().setRedeliveryDelay(5000L); server.getAddressSettingsRepository().addMatch(atestq.toString(), qs); @@ -756,8 +714,7 @@ public class ScheduledMessageTest extends ActiveMQTestBase session.createQueue(atestq, atestq, true); ClientProducer producer = session.createProducer(atestq); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage msg = session.createMessage(true); msg.putIntProperty("key", i); producer.send(msg); @@ -774,8 +731,7 @@ public class ScheduledMessageTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { Xid xid = newXID(); session.start(xid, XAResource.TMNOFLAGS); ClientMessage msg = consumer.receive(5000); @@ -792,8 +748,7 @@ public class ScheduledMessageTest extends ActiveMQTestBase server.stop(); - configuration = createDefaultInVMConfig() - .addAddressesSetting(atestq.toString(), qs); + configuration = createDefaultInVMConfig().addAddressesSetting(atestq.toString(), qs); server = createServer(true, configuration); server.start(); @@ -801,19 +756,15 @@ public class ScheduledMessageTest extends ActiveMQTestBase locator = createInVMNonHALocator(); final AtomicInteger count = new AtomicInteger(0); - Thread t = new Thread() - { + Thread t = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(false, false); session.start(); ClientConsumer cons = session.createConsumer(atestq); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage msg = cons.receive(100000); assertNotNull(msg); count.incrementAndGet(); @@ -823,8 +774,7 @@ public class ScheduledMessageTest extends ActiveMQTestBase session.close(); sf.close(); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); count.set(-1); } @@ -837,10 +787,8 @@ public class ScheduledMessageTest extends ActiveMQTestBase session = sessionFactory.createSession(true, false, false); - for (Xid xid : xids) - { - if (xid != null) - { + for (Xid xid : xids) { + if (xid != null) { session.rollback(xid); } } @@ -854,8 +802,7 @@ public class ScheduledMessageTest extends ActiveMQTestBase // Private ------------------------------------------------------- - private void scheduledDelivery(final boolean tx) throws Exception - { + private void scheduledDelivery(final boolean tx) throws Exception { ActiveMQTestBase.forceGC(); Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); @@ -867,8 +814,7 @@ public class ScheduledMessageTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(atestq); session.start(); - if (tx) - { + if (tx) { session.start(xid, XAResource.TMNOFLAGS); } @@ -914,21 +860,18 @@ public class ScheduledMessageTest extends ActiveMQTestBase tm9.putLongProperty(Message.HDR_SCHEDULED_DELIVERY_TIME, -3); producer.send(tm9); - if (tx) - { + if (tx) { session.end(xid, XAResource.TMSUCCESS); session.prepare(xid); session.commit(xid, false); } - else - { + else { session.commit(); } // First the non scheduled messages should be received - if (tx) - { + if (tx) { session.start(xid, XAResource.TMNOFLAGS); } @@ -990,8 +933,7 @@ public class ScheduledMessageTest extends ActiveMQTestBase Assert.assertTrue(now2 - now >= 7000); - if (tx) - { + if (tx) { session.end(xid, XAResource.TMSUCCESS); session.prepare(xid); session.commit(xid, false); @@ -1001,13 +943,8 @@ public class ScheduledMessageTest extends ActiveMQTestBase sessionFactory.close(); } - private ClientMessage createDurableMessage(final ClientSession session, final String body) - { - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - true, - 0, - System.currentTimeMillis(), - (byte) 1); + private ClientMessage createDurableMessage(final ClientSession session, final String body) { + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, true, 0, System.currentTimeMillis(), (byte) 1); message.getBodyBuffer().writeString(body); return message; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/security/NettySecurityClientTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/security/NettySecurityClientTest.java index fe4198fedd..c1a90125de 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/security/NettySecurityClientTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/security/NettySecurityClientTest.java @@ -29,76 +29,58 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class NettySecurityClientTest extends ActiveMQTestBase -{ +public class NettySecurityClientTest extends ActiveMQTestBase { private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private ActiveMQServer messagingService; @Test - public void testProducerConsumerClientWithoutSecurityManager() throws Exception - { + public void testProducerConsumerClientWithoutSecurityManager() throws Exception { doTestProducerConsumerClient(false); } @Test - public void testProducerConsumerClientWithSecurityManager() throws Exception - { + public void testProducerConsumerClientWithSecurityManager() throws Exception { doTestProducerConsumerClient(true); } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - ConfigurationImpl config = createBasicConfig() - .addAcceptorConfiguration(getNettyAcceptorTransportConfiguration(true)); + ConfigurationImpl config = createBasicConfig().addAcceptorConfiguration(getNettyAcceptorTransportConfiguration(true)); messagingService = createServer(false, config); messagingService.start(); waitForServerToStart(messagingService); } - private void doTestProducerConsumerClient(final boolean withSecurityManager) throws Exception - { + private void doTestProducerConsumerClient(final boolean withSecurityManager) throws Exception { String[] vmargs = new String[0]; - if (withSecurityManager) - { - URL securityPolicyURL = Thread.currentThread() - .getContextClassLoader() - .getResource("restricted-security-client.policy"); + if (withSecurityManager) { + URL securityPolicyURL = Thread.currentThread().getContextClassLoader().getResource("restricted-security-client.policy"); vmargs = new String[]{"-Djava.security.manager", "-Djava.security.policy=" + securityPolicyURL.getPath()}; } // spawn a JVM that creates a client with a security manager which sends and receives a // test message - Process p = SpawnedVMSupport.spawnVM(SimpleClient.class.getName(), - "-Xms512m", "-Xmx512m", - vmargs, - false, - true, - new String[]{NETTY_CONNECTOR_FACTORY}); + Process p = SpawnedVMSupport.spawnVM(SimpleClient.class.getName(), "-Xms512m", "-Xmx512m", vmargs, false, true, new String[]{NETTY_CONNECTOR_FACTORY}); InputStreamReader isr = new InputStreamReader(p.getInputStream()); BufferedReader br = new BufferedReader(isr); String line = null; - while ((line = br.readLine()) != null) - { + while ((line = br.readLine()) != null) { //System.out.println(line); line = line.replace('|', '\n'); - if (line.startsWith("Listening")) - { + if (line.startsWith("Listening")) { continue; } - else if ("OK".equals(line.trim())) - { + else if ("OK".equals(line.trim())) { break; } - else - { + else { //Assert.fail("Exception when starting the client: " + line); System.out.println(line); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/security/SecurityTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/security/SecurityTest.java index eafa0fecbf..15b5423580 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/security/SecurityTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/security/SecurityTest.java @@ -42,8 +42,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class SecurityTest extends ActiveMQTestBase -{ +public class SecurityTest extends ActiveMQTestBase { + /* * create session tests */ @@ -57,16 +57,14 @@ public class SecurityTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); locator = createInVMNonHALocator(); } @Test - public void testCreateSessionWithNullUserPass() throws Exception - { + public void testCreateSessionWithNullUserPass() throws Exception { ActiveMQServer server = createServer(); ActiveMQSecurityManagerImpl securityManager = (ActiveMQSecurityManagerImpl) server.getSecurityManager(); securityManager.getConfiguration().addUser("guest", "guest"); @@ -74,14 +72,12 @@ public class SecurityTest extends ActiveMQTestBase server.start(); ClientSessionFactory cf = createSessionFactory(locator); - try - { + try { ClientSession session = cf.createSession(false, true, true); session.close(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { Assert.fail("should not throw exception"); } } @@ -90,83 +86,69 @@ public class SecurityTest extends ActiveMQTestBase * @return * @throws Exception */ - private ActiveMQServer createServer() throws Exception - { - configuration = createDefaultInVMConfig() - .setSecurityEnabled(true); + private ActiveMQServer createServer() throws Exception { + configuration = createDefaultInVMConfig().setSecurityEnabled(true); ActiveMQServer server = createServer(false, configuration); return server; } @Test - public void testCreateSessionWithNullUserPassNoGuest() throws Exception - { + public void testCreateSessionWithNullUserPassNoGuest() throws Exception { ActiveMQServer server = createServer(); server.start(); ClientSessionFactory cf = createSessionFactory(locator); - try - { + try { cf.createSession(false, true, true); Assert.fail("should throw exception"); } - catch (ActiveMQSecurityException se) - { + catch (ActiveMQSecurityException se) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } } @Test - public void testCreateSessionWithCorrectUserWrongPass() throws Exception - { + public void testCreateSessionWithCorrectUserWrongPass() throws Exception { ActiveMQServer server = createServer(); ActiveMQSecurityManagerImpl securityManager = (ActiveMQSecurityManagerImpl) server.getSecurityManager(); securityManager.getConfiguration().addUser("newuser", "apass"); server.start(); ClientSessionFactory cf = createSessionFactory(locator); - try - { + try { cf.createSession("newuser", "awrongpass", false, true, true, false, -1); Assert.fail("should not throw exception"); } - catch (ActiveMQSecurityException se) - { + catch (ActiveMQSecurityException se) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } } @Test - public void testCreateSessionWithCorrectUserCorrectPass() throws Exception - { + public void testCreateSessionWithCorrectUserCorrectPass() throws Exception { ActiveMQServer server = createServer(); ActiveMQSecurityManagerImpl securityManager = (ActiveMQSecurityManagerImpl) server.getSecurityManager(); securityManager.getConfiguration().addUser("newuser", "apass"); server.start(); ClientSessionFactory cf = createSessionFactory(locator); - try - { + try { ClientSession session = cf.createSession("newuser", "apass", false, true, true, false, -1); session.close(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { Assert.fail("should not throw exception"); } } @Test - public void testCreateDurableQueueWithRole() throws Exception - { + public void testCreateDurableQueueWithRole() throws Exception { ActiveMQServer server = createServer(); server.start(); HierarchicalRepository> securityRepository = server.getSecurityRepository(); @@ -184,8 +166,7 @@ public class SecurityTest extends ActiveMQTestBase } @Test - public void testCreateDurableQueueWithoutRole() throws Exception - { + public void testCreateDurableQueueWithoutRole() throws Exception { ActiveMQServer server = createServer(); server.start(); @@ -199,25 +180,21 @@ public class SecurityTest extends ActiveMQTestBase securityManager.getConfiguration().addRole("auser", "arole"); ClientSessionFactory cf = createSessionFactory(locator); ClientSession session = cf.createSession("auser", "pass", false, true, true, false, -1); - try - { + try { session.createQueue(SecurityTest.addressA, SecurityTest.queueA, true); Assert.fail("should throw exception"); } - catch (ActiveMQSecurityException se) - { + catch (ActiveMQSecurityException se) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } session.close(); } @Test - public void testDeleteDurableQueueWithRole() throws Exception - { + public void testDeleteDurableQueueWithRole() throws Exception { ActiveMQServer server = createServer(); server.start(); HierarchicalRepository> securityRepository = server.getSecurityRepository(); @@ -236,8 +213,7 @@ public class SecurityTest extends ActiveMQTestBase } @Test - public void testDeleteDurableQueueWithoutRole() throws Exception - { + public void testDeleteDurableQueueWithoutRole() throws Exception { ActiveMQServer server = createServer(); server.start(); HierarchicalRepository> securityRepository = server.getSecurityRepository(); @@ -251,25 +227,21 @@ public class SecurityTest extends ActiveMQTestBase ClientSessionFactory cf = createSessionFactory(locator); ClientSession session = cf.createSession("auser", "pass", false, true, true, false, -1); session.createQueue(SecurityTest.addressA, SecurityTest.queueA, true); - try - { + try { session.deleteQueue(SecurityTest.queueA); Assert.fail("should throw exception"); } - catch (ActiveMQSecurityException se) - { + catch (ActiveMQSecurityException se) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } session.close(); } @Test - public void testCreateTempQueueWithRole() throws Exception - { + public void testCreateTempQueueWithRole() throws Exception { ActiveMQServer server = createServer(); server.start(); @@ -288,8 +260,7 @@ public class SecurityTest extends ActiveMQTestBase } @Test - public void testCreateTempQueueWithoutRole() throws Exception - { + public void testCreateTempQueueWithoutRole() throws Exception { ActiveMQServer server = createServer(); server.start(); @@ -303,25 +274,21 @@ public class SecurityTest extends ActiveMQTestBase securityManager.getConfiguration().addRole("auser", "arole"); ClientSessionFactory cf = createSessionFactory(locator); ClientSession session = cf.createSession("auser", "pass", false, true, true, false, -1); - try - { + try { session.createQueue(SecurityTest.addressA, SecurityTest.queueA, false); Assert.fail("should throw exception"); } - catch (ActiveMQSecurityException se) - { + catch (ActiveMQSecurityException se) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } session.close(); } @Test - public void testDeleteTempQueueWithRole() throws Exception - { + public void testDeleteTempQueueWithRole() throws Exception { ActiveMQServer server = createServer(); server.start(); HierarchicalRepository> securityRepository = server.getSecurityRepository(); @@ -340,8 +307,7 @@ public class SecurityTest extends ActiveMQTestBase } @Test - public void testDeleteTempQueueWithoutRole() throws Exception - { + public void testDeleteTempQueueWithoutRole() throws Exception { ActiveMQServer server = createServer(); server.start(); HierarchicalRepository> securityRepository = server.getSecurityRepository(); @@ -355,25 +321,21 @@ public class SecurityTest extends ActiveMQTestBase ClientSessionFactory cf = createSessionFactory(locator); ClientSession session = cf.createSession("auser", "pass", false, true, true, false, -1); session.createQueue(SecurityTest.addressA, SecurityTest.queueA, false); - try - { + try { session.deleteQueue(SecurityTest.queueA); Assert.fail("should throw exception"); } - catch (ActiveMQSecurityException se) - { + catch (ActiveMQSecurityException se) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } session.close(); } @Test - public void testSendWithRole() throws Exception - { + public void testSendWithRole() throws Exception { ActiveMQServer server = createServer(); server.start(); @@ -425,12 +387,10 @@ public class SecurityTest extends ActiveMQTestBase // This was added to validate https://issues.jboss.org/browse/SOA-3363 securityRepository.addMatch(SecurityTest.addressA, roles); boolean failed = false; - try - { + try { cp.send(session.createMessage(true)); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { failed = true; } // This was added to validate https://issues.jboss.org/browse/SOA-3363 ^^^^^ @@ -439,8 +399,7 @@ public class SecurityTest extends ActiveMQTestBase } @Test - public void testSendWithoutRole() throws Exception - { + public void testSendWithoutRole() throws Exception { ActiveMQServer server = createServer(); server.start(); @@ -457,24 +416,20 @@ public class SecurityTest extends ActiveMQTestBase ClientSession session = cf.createSession("auser", "pass", false, true, true, false, -1); session.createQueue(SecurityTest.addressA, SecurityTest.queueA, true); ClientProducer cp = session.createProducer(SecurityTest.addressA); - try - { + try { cp.send(session.createMessage(false)); } - catch (ActiveMQSecurityException se) - { + catch (ActiveMQSecurityException se) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } session.close(); } @Test - public void testNonBlockSendWithoutRole() throws Exception - { + public void testNonBlockSendWithoutRole() throws Exception { ActiveMQServer server = createServer(); server.start(); @@ -498,8 +453,7 @@ public class SecurityTest extends ActiveMQTestBase } @Test - public void testCreateConsumerWithRole() throws Exception - { + public void testCreateConsumerWithRole() throws Exception { ActiveMQServer server = createServer(); server.start(); HierarchicalRepository> securityRepository = server.getSecurityRepository(); @@ -527,8 +481,7 @@ public class SecurityTest extends ActiveMQTestBase } @Test - public void testCreateConsumerWithoutRole() throws Exception - { + public void testCreateConsumerWithoutRole() throws Exception { ActiveMQServer server = createServer(); server.start(); HierarchicalRepository> securityRepository = server.getSecurityRepository(); @@ -550,16 +503,13 @@ public class SecurityTest extends ActiveMQTestBase senSession.createQueue(SecurityTest.addressA, SecurityTest.queueA, true); ClientProducer cp = senSession.createProducer(SecurityTest.addressA); cp.send(session.createMessage(false)); - try - { + try { session.createConsumer(SecurityTest.queueA); } - catch (ActiveMQSecurityException se) - { + catch (ActiveMQSecurityException se) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } session.close(); @@ -567,11 +517,8 @@ public class SecurityTest extends ActiveMQTestBase } @Test - public void testSendMessageUpdateRoleCached() throws Exception - { - Configuration configuration = createDefaultInVMConfig() - .setSecurityEnabled(true) - .setSecurityInvalidationInterval(10000); + public void testSendMessageUpdateRoleCached() throws Exception { + Configuration configuration = createDefaultInVMConfig().setSecurityEnabled(true).setSecurityInvalidationInterval(10000); ActiveMQServer server = createServer(false, configuration); server.start(); HierarchicalRepository> securityRepository = server.getSecurityRepository(); @@ -595,16 +542,13 @@ public class SecurityTest extends ActiveMQTestBase senSession.createQueue(SecurityTest.addressA, SecurityTest.queueA, true); ClientProducer cp = senSession.createProducer(SecurityTest.addressA); cp.send(session.createMessage(false)); - try - { + try { session.createConsumer(SecurityTest.queueA); } - catch (ActiveMQSecurityException se) - { + catch (ActiveMQSecurityException se) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } @@ -623,11 +567,8 @@ public class SecurityTest extends ActiveMQTestBase } @Test - public void testSendMessageUpdateRoleCached2() throws Exception - { - Configuration configuration = createDefaultInVMConfig() - .setSecurityEnabled(true) - .setSecurityInvalidationInterval(0); + public void testSendMessageUpdateRoleCached2() throws Exception { + Configuration configuration = createDefaultInVMConfig().setSecurityEnabled(true).setSecurityInvalidationInterval(0); ActiveMQServer server = createServer(false, configuration); server.start(); @@ -652,16 +593,13 @@ public class SecurityTest extends ActiveMQTestBase senSession.createQueue(SecurityTest.addressA, SecurityTest.queueA, true); ClientProducer cp = senSession.createProducer(SecurityTest.addressA); cp.send(session.createMessage(false)); - try - { + try { session.createConsumer(SecurityTest.queueA); } - catch (ActiveMQSecurityException se) - { + catch (ActiveMQSecurityException se) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } @@ -674,16 +612,13 @@ public class SecurityTest extends ActiveMQTestBase // next createConsumer should fail securityManager.getConfiguration().removeRole("auser", "receiver"); - try - { + try { session.createConsumer(SecurityTest.queueA); } - catch (ActiveMQSecurityException se) - { + catch (ActiveMQSecurityException se) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } @@ -693,11 +628,8 @@ public class SecurityTest extends ActiveMQTestBase } @Test - public void testSendMessageUpdateSender() throws Exception - { - Configuration configuration = createDefaultInVMConfig() - .setSecurityEnabled(true) - .setSecurityInvalidationInterval(-1); + public void testSendMessageUpdateSender() throws Exception { + Configuration configuration = createDefaultInVMConfig().setSecurityEnabled(true).setSecurityInvalidationInterval(-1); ActiveMQServer server = createServer(false, configuration); server.start(); HierarchicalRepository> securityRepository = server.getSecurityRepository(); @@ -725,16 +657,13 @@ public class SecurityTest extends ActiveMQTestBase senSession.createQueue(SecurityTest.addressA, SecurityTest.queueA, true); ClientProducer cp = senSession.createProducer(SecurityTest.addressA); cp.send(session.createMessage(false)); - try - { + try { session.createConsumer(SecurityTest.queueA); } - catch (ActiveMQSecurityException se) - { + catch (ActiveMQSecurityException se) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } @@ -751,13 +680,11 @@ public class SecurityTest extends ActiveMQTestBase ClientProducer prod = sendingSession.createProducer(SecurityTest.addressA); prod.send(CreateMessage.createTextMessage(sendingSession, "Test", true)); prod.send(CreateMessage.createTextMessage(sendingSession, "Test", true)); - try - { + try { sendingSession.commit(); Assert.fail("Expected exception"); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { // I would expect the commit to fail, since there were failures registered } @@ -773,13 +700,11 @@ public class SecurityTest extends ActiveMQTestBase prod.send(CreateMessage.createTextMessage(sendingSession, "Test", true)); sendingSession.end(xid, XAResource.TMSUCCESS); - try - { + try { sendingSession.prepare(xid); Assert.fail("Exception was expected"); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } @@ -795,8 +720,7 @@ public class SecurityTest extends ActiveMQTestBase } @Test - public void testSendManagementWithRole() throws Exception - { + public void testSendManagementWithRole() throws Exception { ActiveMQServer server = createServer(); server.start(); @@ -817,8 +741,7 @@ public class SecurityTest extends ActiveMQTestBase } @Test - public void testSendManagementWithoutRole() throws Exception - { + public void testSendManagementWithoutRole() throws Exception { ActiveMQServer server = createServer(); server.start(); @@ -835,16 +758,13 @@ public class SecurityTest extends ActiveMQTestBase session.createQueue(configuration.getManagementAddress().toString(), SecurityTest.queueA, true); ClientProducer cp = session.createProducer(configuration.getManagementAddress()); cp.send(session.createMessage(false)); - try - { + try { cp.send(session.createMessage(false)); } - catch (ActiveMQSecurityException se) - { + catch (ActiveMQSecurityException se) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } session.close(); @@ -852,8 +772,7 @@ public class SecurityTest extends ActiveMQTestBase } @Test - public void testNonBlockSendManagementWithoutRole() throws Exception - { + public void testNonBlockSendManagementWithoutRole() throws Exception { ActiveMQServer server = createServer(); server.start(); @@ -878,8 +797,7 @@ public class SecurityTest extends ActiveMQTestBase } @Test - public void testComplexRoles() throws Exception - { + public void testComplexRoles() throws Exception { ActiveMQServer server = createServer(); server.start(); ActiveMQSecurityManagerImpl securityManager = (ActiveMQSecurityManagerImpl) server.getSecurityManager(); @@ -919,8 +837,7 @@ public class SecurityTest extends ActiveMQTestBase ClientSession andrewConnection = null; ClientSession frankConnection = null; ClientSession samConnection = null; - locator.setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true); + locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true); ClientSessionFactory factory = createSessionFactory(locator); ClientSession adminSession = factory.createSession("all", "all", false, true, true, false, -1); @@ -931,32 +848,26 @@ public class SecurityTest extends ActiveMQTestBase String usQueueName = "news.us.usQueue"; adminSession.createQueue(usQueueName, usQueueName, false); // Step 4. Try to create a JMS Connection without user/password. It will fail. - try - { + try { factory.createSession(false, true, true); Assert.fail("should throw exception"); } - catch (ActiveMQSecurityException se) - { + catch (ActiveMQSecurityException se) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } // Step 5. bill tries to make a connection using wrong password - try - { + try { billConnection = factory.createSession("bill", "activemq1", false, true, true, false, -1); Assert.fail("should throw exception"); } - catch (ActiveMQSecurityException se) - { + catch (ActiveMQSecurityException se) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } @@ -1017,8 +928,7 @@ public class SecurityTest extends ActiveMQTestBase } - public void _testComplexRoles2() throws Exception - { + public void _testComplexRoles2() throws Exception { ActiveMQServer server = createServer(); server.start(); ActiveMQSecurityManagerImpl securityManager = (ActiveMQSecurityManagerImpl) server.getSecurityManager(); @@ -1059,8 +969,7 @@ public class SecurityTest extends ActiveMQTestBase ClientSession frankConnection = null; ClientSession samConnection = null; ClientSessionFactory factory = createSessionFactory(locator); - factory.getServerLocator().setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true); + factory.getServerLocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true); ClientSession adminSession = factory.createSession("all", "all", false, true, true, false, -1); String genericQueueName = "genericQueue"; @@ -1070,32 +979,26 @@ public class SecurityTest extends ActiveMQTestBase String usQueueName = "news.us.usQueue"; adminSession.createQueue(usQueueName, usQueueName, false); // Step 4. Try to create a JMS Connection without user/password. It will fail. - try - { + try { factory.createSession(false, true, true); Assert.fail("should throw exception"); } - catch (ActiveMQSecurityException se) - { + catch (ActiveMQSecurityException se) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } // Step 5. bill tries to make a connection using wrong password - try - { + try { billConnection = factory.createSession("bill", "activemq1", false, true, true, false, -1); Assert.fail("should throw exception"); } - catch (ActiveMQSecurityException se) - { + catch (ActiveMQSecurityException se) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } @@ -1147,11 +1050,10 @@ public class SecurityTest extends ActiveMQTestBase } // Check the user connection has both send and receive permissions on the queue - private void checkUserSendAndReceive(final String genericQueueName, final ClientSession connection) throws Exception - { + private void checkUserSendAndReceive(final String genericQueueName, + final ClientSession connection) throws Exception { connection.start(); - try - { + try { ClientProducer prod = connection.createProducer(genericQueueName); ClientConsumer con = connection.createConsumer(genericQueueName); ClientMessage m = connection.createMessage(false); @@ -1160,28 +1062,24 @@ public class SecurityTest extends ActiveMQTestBase Assert.assertNotNull(rec); rec.acknowledge(); } - finally - { + finally { connection.stop(); } } // Check the user can receive message but cannot send message. - private void checkUserReceiveNoSend(final String queue, final ClientSession connection, - final ClientSession sendingConn) throws Exception - { + private void checkUserReceiveNoSend(final String queue, + final ClientSession connection, + final ClientSession sendingConn) throws Exception { connection.start(); - try - { + try { ClientProducer prod = connection.createProducer(queue); ClientMessage m = connection.createMessage(false); - try - { + try { prod.send(m); Assert.fail("should throw exception"); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { // pass } @@ -1192,67 +1090,56 @@ public class SecurityTest extends ActiveMQTestBase Assert.assertNotNull(rec); rec.acknowledge(); } - finally - { + finally { connection.stop(); } } - private void checkUserNoSendNoReceive(final String queue, final ClientSession connection, - final ClientSession sendingConn) throws Exception - { + private void checkUserNoSendNoReceive(final String queue, + final ClientSession connection, + final ClientSession sendingConn) throws Exception { connection.start(); - try - { + try { ClientProducer prod = connection.createProducer(queue); ClientMessage m = connection.createMessage(false); - try - { + try { prod.send(m); Assert.fail("should throw exception"); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { // pass } prod = sendingConn.createProducer(queue); prod.send(m); - try - { + try { connection.createConsumer(queue); Assert.fail("should throw exception"); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { // pass } } - finally - { + finally { connection.stop(); } } // Check the user can send message but cannot receive message - private void checkUserSendNoReceive(final String queue, final ClientSession connection) throws Exception - { + private void checkUserSendNoReceive(final String queue, final ClientSession connection) throws Exception { ClientProducer prod = connection.createProducer(queue); ClientMessage m = connection.createMessage(false); prod.send(m); - try - { + try { connection.createConsumer(queue); Assert.fail("should throw exception"); } - catch (ActiveMQSecurityException se) - { + catch (ActiveMQSecurityException se) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/security/SimpleClient.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/security/SimpleClient.java index ca51c6b5ef..fa33968be2 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/security/SimpleClient.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/security/SimpleClient.java @@ -30,15 +30,11 @@ import org.apache.activemq.artemis.tests.util.RandomUtil; /** * Code to be run in an external VM, via main() */ -final class SimpleClient -{ +final class SimpleClient { - public static void main(final String[] args) throws Exception - { - try - { - if (args.length != 1) - { + public static void main(final String[] args) throws Exception { + try { + if (args.length != 1) { throw new Exception("require 1 argument: connector factory class name"); } String connectorFactoryClassName = args[0]; @@ -47,8 +43,7 @@ final class SimpleClient String messageText = RandomUtil.randomString(); ServerLocator locator = ActiveMQClient.createServerLocatorWithoutHA(new TransportConfiguration(connectorFactoryClassName)); - try - { + try { ClientSessionFactory sf = locator.createSessionFactory(); ClientSession session = sf.createSession(false, true, true); @@ -56,25 +51,19 @@ final class SimpleClient ClientProducer producer = session.createProducer(queueName); ClientConsumer consumer = session.createConsumer(queueName); - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte) 1); + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.getBodyBuffer().writeString(messageText); producer.send(message); session.start(); ClientMessage receivedMsg = consumer.receive(5000); - if (receivedMsg == null) - { + if (receivedMsg == null) { throw new Exception("did not receive the message"); } String text = receivedMsg.getBodyBuffer().readString(); - if (text == null || !text.equals(messageText)) - { + if (text == null || !text.equals(messageText)) { throw new Exception("received " + text + ", was expecting " + messageText); } @@ -85,18 +74,15 @@ final class SimpleClient sf.close(); System.out.println("OK"); } - finally - { + finally { locator.close(); } } - catch (Throwable t) - { + catch (Throwable t) { String allStack = t.getMessage() + "|"; StackTraceElement[] stackTrace = t.getStackTrace(); - for (StackTraceElement stackTraceElement : stackTrace) - { + for (StackTraceElement stackTraceElement : stackTrace) { allStack += stackTraceElement.toString() + "|"; } // System.out.println(t.getClass().getName()); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/AIOFileLockTimeoutTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/AIOFileLockTimeoutTest.java index f4f3a78dfe..9d41688bfc 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/AIOFileLockTimeoutTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/AIOFileLockTimeoutTest.java @@ -18,16 +18,14 @@ package org.apache.activemq.artemis.tests.integration.server; import org.junit.Test; -public class AIOFileLockTimeoutTest extends FileLockTimeoutTest -{ +public class AIOFileLockTimeoutTest extends FileLockTimeoutTest { + @Test /** * When running this test from an IDE add this to the test command line so that the AssertionLoggerHandler works properly: * * -Djava.util.logging.manager=org.jboss.logmanager.LogManager -Dlogging.configuration=file:/tests/config/logging.properties - */ - public void testAIOFileLockExpiration() throws Exception - { + */ public void testAIOFileLockExpiration() throws Exception { doTest(true); } } \ No newline at end of file diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/AddressFullLoggingTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/AddressFullLoggingTest.java index 7850b24c17..d9469ba1ff 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/AddressFullLoggingTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/AddressFullLoggingTest.java @@ -40,11 +40,10 @@ import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -public class AddressFullLoggingTest extends ActiveMQTestBase -{ +public class AddressFullLoggingTest extends ActiveMQTestBase { + @BeforeClass - public static void prepareLogger() - { + public static void prepareLogger() { AssertionLoggerHandler.startCapture(); } @@ -53,26 +52,18 @@ public class AddressFullLoggingTest extends ActiveMQTestBase * When running this test from an IDE add this to the test command line so that the AssertionLoggerHandler works properly: * * -Djava.util.logging.manager=org.jboss.logmanager.LogManager -Dlogging.configuration=file:/tests/config/logging.properties - */ - public void testBlockLogging() throws Exception - { + */ public void testBlockLogging() throws Exception { final int MAX_MESSAGES = 200; final String MY_ADDRESS = "myAddress"; final String MY_QUEUE = "myQueue"; ActiveMQServer server = createServer(false); - AddressSettings defaultSetting = new AddressSettings() - .setPageSizeBytes(10 * 1024) - .setMaxSizeBytes(20 * 1024) - .setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK); + AddressSettings defaultSetting = new AddressSettings().setPageSizeBytes(10 * 1024).setMaxSizeBytes(20 * 1024).setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK); server.getAddressSettingsRepository().addMatch("#", defaultSetting); server.start(); - ServerLocator locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + ServerLocator locator = createInVMNonHALocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); ClientSessionFactory factory = createSessionFactory(locator); ClientSession session = factory.createSession(false, true, true); @@ -85,10 +76,8 @@ public class AddressFullLoggingTest extends ActiveMQTestBase message.getBodyBuffer().writeBytes(new byte[1024]); ExecutorService executor = Executors.newFixedThreadPool(1); - Callable sendMessageTask = new Callable() - { - public Object call() throws ActiveMQException - { + Callable sendMessageTask = new Callable() { + public Object call() throws ActiveMQException { producer.send(message); return null; } @@ -96,21 +85,17 @@ public class AddressFullLoggingTest extends ActiveMQTestBase int sendCount = 0; - for (int i = 0; i < MAX_MESSAGES; i++) - { + for (int i = 0; i < MAX_MESSAGES; i++) { Future future = executor.submit(sendMessageTask); - try - { + try { future.get(3, TimeUnit.SECONDS); sendCount++; } - catch (TimeoutException ex) - { + catch (TimeoutException ex) { // message sending has been blocked break; } - finally - { + finally { future.cancel(true); // may or may not desire this } } @@ -121,8 +106,7 @@ public class AddressFullLoggingTest extends ActiveMQTestBase session = factory.createSession(false, true, true); session.start(); ClientConsumer consumer = session.createConsumer(MY_QUEUE); - for (int i = 0; i < sendCount; i++) - { + for (int i = 0; i < sendCount; i++) { ClientMessage msg = consumer.receive(250); if (msg == null) break; @@ -139,8 +123,7 @@ public class AddressFullLoggingTest extends ActiveMQTestBase } @AfterClass - public static void clearLogger() - { + public static void clearLogger() { AssertionLoggerHandler.stopCapture(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ConnectionLimitTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ConnectionLimitTest.java index ef88e9e7eb..67ea3ba402 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ConnectionLimitTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ConnectionLimitTest.java @@ -33,14 +33,13 @@ import org.junit.Test; import java.util.HashMap; import java.util.Map; -public class ConnectionLimitTest extends ActiveMQTestBase -{ +public class ConnectionLimitTest extends ActiveMQTestBase { + private ActiveMQServer server; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); Map nettyParams = new HashMap(); @@ -49,47 +48,38 @@ public class ConnectionLimitTest extends ActiveMQTestBase Map invmParams = new HashMap(); invmParams.put(org.apache.activemq.artemis.core.remoting.impl.invm.TransportConstants.CONNECTIONS_ALLOWED, 1); - Configuration configuration = createBasicConfig() - .addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, nettyParams)) - .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, invmParams)); + Configuration configuration = createBasicConfig().addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, nettyParams)).addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, invmParams)); server = addServer(ActiveMQServers.newActiveMQServer(configuration, false)); server.start(); } @Test - public void testInVMConnectionLimit() throws Exception - { + public void testInVMConnectionLimit() throws Exception { ServerLocator locator = addServerLocator(createNonHALocator(false)); ClientSessionFactory clientSessionFactory = locator.createSessionFactory(); - try - { + try { ClientSessionFactory extraClientSessionFactory = locator.createSessionFactory(); fail("creating a session factory here should fail"); } - catch (Exception e) - { + catch (Exception e) { assertTrue(e instanceof ActiveMQNotConnectedException); } } @Test - public void testNettyConnectionLimit() throws Exception - { - ServerLocator locator = createNonHALocator(true) - .setCallTimeout(3000); + public void testNettyConnectionLimit() throws Exception { + ServerLocator locator = createNonHALocator(true).setCallTimeout(3000); ClientSessionFactory clientSessionFactory = locator.createSessionFactory(); ClientSession clientSession = addClientSession(clientSessionFactory.createSession()); ClientSessionFactory extraClientSessionFactory = locator.createSessionFactory(); - try - { + try { ClientSession extraClientSession = addClientSession(extraClientSessionFactory.createSession()); fail("creating a session here should fail"); } - catch (Exception e) - { + catch (Exception e) { assertTrue(e instanceof ActiveMQConnectionTimedOutException); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ExpiryRunnerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ExpiryRunnerTest.java index 498ec79f3f..f015ca6967 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ExpiryRunnerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ExpiryRunnerTest.java @@ -38,8 +38,8 @@ import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -public class ExpiryRunnerTest extends ActiveMQTestBase -{ +public class ExpiryRunnerTest extends ActiveMQTestBase { + private ActiveMQServer server; private ClientSession clientSession; @@ -54,25 +54,22 @@ public class ExpiryRunnerTest extends ActiveMQTestBase private ServerLocator locator; @Test - public void testBasicExpire() throws Exception - { + public void testBasicExpire() throws Exception { ClientProducer producer = clientSession.createProducer(qName); int numMessages = 100; long expiration = System.currentTimeMillis(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage m = createTextMessage(clientSession, "m" + i); m.setExpiration(expiration); producer.send(m); } Thread.sleep(1600); - Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(qName).getBindable()).getMessageCount()); - Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(qName).getBindable()).getDeliveringCount()); + Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getMessageCount()); + Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getDeliveringCount()); } @Test - public void testExpireFromMultipleQueues() throws Exception - { + public void testExpireFromMultipleQueues() throws Exception { ClientProducer producer = clientSession.createProducer(qName); clientSession.createQueue(qName2, qName2, null, false); AddressSettings addressSettings = new AddressSettings().setExpiryAddress(expiryAddress); @@ -80,8 +77,7 @@ public class ExpiryRunnerTest extends ActiveMQTestBase ClientProducer producer2 = clientSession.createProducer(qName2); int numMessages = 100; long expiration = System.currentTimeMillis(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage m = createTextMessage(clientSession, "m" + i); m.setExpiration(expiration); producer.send(m); @@ -90,47 +86,40 @@ public class ExpiryRunnerTest extends ActiveMQTestBase producer2.send(m); } Thread.sleep(1600); - Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(qName).getBindable()).getMessageCount()); - Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(qName).getBindable()).getDeliveringCount()); + Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getMessageCount()); + Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getDeliveringCount()); } @Test - public void testExpireHalf() throws Exception - { + public void testExpireHalf() throws Exception { ClientProducer producer = clientSession.createProducer(qName); int numMessages = 100; long expiration = System.currentTimeMillis(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage m = createTextMessage(clientSession, "m" + i); - if (i % 2 == 0) - { + if (i % 2 == 0) { m.setExpiration(expiration); } producer.send(m); } Thread.sleep(1600); - Assert.assertEquals(numMessages / 2, - ((Queue)server.getPostOffice().getBinding(qName).getBindable()).getMessageCount()); - Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(qName).getBindable()).getDeliveringCount()); + Assert.assertEquals(numMessages / 2, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getMessageCount()); + Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getDeliveringCount()); } @Test - public void testExpireConsumeHalf() throws Exception - { + public void testExpireConsumeHalf() throws Exception { ClientProducer producer = clientSession.createProducer(qName); int numMessages = 100; long expiration = System.currentTimeMillis() + 1000; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage m = createTextMessage(clientSession, "m" + i); m.setExpiration(expiration); producer.send(m); } ClientConsumer consumer = clientSession.createConsumer(qName); clientSession.start(); - for (int i = 0; i < numMessages / 2; i++) - { + for (int i = 0; i < numMessages / 2; i++) { ClientMessage cm = consumer.receive(500); Assert.assertNotNull("message not received " + i, cm); cm.acknowledge(); @@ -138,13 +127,12 @@ public class ExpiryRunnerTest extends ActiveMQTestBase } consumer.close(); Thread.sleep(2100); - Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(qName).getBindable()).getMessageCount()); - Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(qName).getBindable()).getDeliveringCount()); + Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getMessageCount()); + Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getDeliveringCount()); } @Test - public void testExpireToExpiryQueue() throws Exception - { + public void testExpireToExpiryQueue() throws Exception { AddressSettings addressSettings = new AddressSettings().setExpiryAddress(expiryAddress); server.getAddressSettingsRepository().addMatch(qName2.toString(), addressSettings); clientSession.deleteQueue(qName); @@ -153,26 +141,23 @@ public class ExpiryRunnerTest extends ActiveMQTestBase ClientProducer producer = clientSession.createProducer(qName); int numMessages = 100; long expiration = System.currentTimeMillis(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage m = createTextMessage(clientSession, "m" + i); m.setExpiration(expiration); producer.send(m); } Thread.sleep(1600); - Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(qName).getBindable()).getMessageCount()); - Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(qName).getBindable()).getDeliveringCount()); + Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getMessageCount()); + Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getDeliveringCount()); ClientConsumer consumer = clientSession.createConsumer(expiryQueue); clientSession.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage cm = consumer.receive(500); Assert.assertNotNull(cm); // assertEquals("m" + i, cm.getBody().getString()); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage cm = consumer.receive(500); Assert.assertNotNull(cm); // assertEquals("m" + i, cm.getBody().getString()); @@ -181,8 +166,7 @@ public class ExpiryRunnerTest extends ActiveMQTestBase } @Test - public void testExpireWhilstConsumingMessagesStillInOrder() throws Exception - { + public void testExpireWhilstConsumingMessagesStillInOrder() throws Exception { ClientProducer producer = clientSession.createProducer(qName); ClientConsumer consumer = clientSession.createConsumer(qName); CountDownLatch latch = new CountDownLatch(1); @@ -193,36 +177,29 @@ public class ExpiryRunnerTest extends ActiveMQTestBase long expiration = System.currentTimeMillis() + 1000; int numMessages = 0; long sendMessagesUntil = System.currentTimeMillis() + 2000; - do - { + do { ClientMessage m = createTextMessage(clientSession, "m" + numMessages++); m.setExpiration(expiration); producer.send(m); Thread.sleep(100); - } - while (System.currentTimeMillis() < sendMessagesUntil); + } while (System.currentTimeMillis() < sendMessagesUntil); Assert.assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); consumer.close(); consumer = clientSession.createConsumer(expiryQueue); - do - { + do { ClientMessage cm = consumer.receive(2000); - if (cm == null) - { + if (cm == null) { break; } String text = cm.getBodyBuffer().readString(); cm.acknowledge(); Assert.assertFalse(dummyMessageHandler.payloads.contains(text)); dummyMessageHandler.payloads.add(text); - } - while (true); + } while (true); - for (int i = 0; i < numMessages; i++) - { - if (dummyMessageHandler.payloads.isEmpty()) - { + for (int i = 0; i < numMessages; i++) { + if (dummyMessageHandler.payloads.isEmpty()) { break; } Assert.assertTrue("m" + i, dummyMessageHandler.payloads.remove("m" + i)); @@ -231,38 +208,35 @@ public class ExpiryRunnerTest extends ActiveMQTestBase thr.join(); } -// -// public static void main(final String[] args) throws Exception -// { -// for (int i = 0; i < 1000; i++) -// { -// TestSuite suite = new TestSuite(); -// ExpiryRunnerTest expiryRunnerTest = new ExpiryRunnerTest(); -// expiryRunnerTest.setName("testExpireWhilstConsuming"); -// suite.addTest(expiryRunnerTest); -// -// TestResult result = TestRunner.run(suite); -// if (result.errorCount() > 0 || result.failureCount() > 0) -// { -// System.exit(1); -// } -// } -// } + // + // public static void main(final String[] args) throws Exception + // { + // for (int i = 0; i < 1000; i++) + // { + // TestSuite suite = new TestSuite(); + // ExpiryRunnerTest expiryRunnerTest = new ExpiryRunnerTest(); + // expiryRunnerTest.setName("testExpireWhilstConsuming"); + // suite.addTest(expiryRunnerTest); + // + // TestResult result = TestRunner.run(suite); + // if (result.errorCount() > 0 || result.failureCount() > 0) + // { + // System.exit(1); + // } + // } + // } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - ConfigurationImpl configuration = (ConfigurationImpl) createDefaultInVMConfig() - .setMessageExpiryScanPeriod(1000); + ConfigurationImpl configuration = (ConfigurationImpl) createDefaultInVMConfig().setMessageExpiryScanPeriod(1000); server = addServer(ActiveMQServers.newActiveMQServer(configuration, false)); // start the server server.start(); // then we create a client as normal - locator = createInVMNonHALocator() - .setBlockOnAcknowledge(true); + locator = createInVMNonHALocator().setBlockOnAcknowledge(true); ClientSessionFactory sessionFactory = createSessionFactory(locator); @@ -276,29 +250,24 @@ public class ExpiryRunnerTest extends ActiveMQTestBase clientSession.createQueue(expiryAddress, expiryQueue, null, false); } - private static class DummyMessageHandler implements Runnable - { + private static class DummyMessageHandler implements Runnable { + List payloads = new ArrayList(); private final ClientConsumer consumer; private final CountDownLatch latch; - public DummyMessageHandler(final ClientConsumer consumer, final CountDownLatch latch) - { + public DummyMessageHandler(final ClientConsumer consumer, final CountDownLatch latch) { this.consumer = consumer; this.latch = latch; } - public void run() - { - while (true) - { - try - { + public void run() { + while (true) { + try { ClientMessage message = consumer.receive(5000); - if (message == null) - { + if (message == null) { break; } message.acknowledge(); @@ -306,8 +275,7 @@ public class ExpiryRunnerTest extends ActiveMQTestBase Thread.sleep(110); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/FakeStorageManager.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/FakeStorageManager.java index 94bb672725..69c5ec1165 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/FakeStorageManager.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/FakeStorageManager.java @@ -22,39 +22,36 @@ import java.util.List; import org.apache.activemq.artemis.core.persistence.impl.nullpm.NullStorageManager; import org.apache.activemq.artemis.core.server.ServerMessage; -public class FakeStorageManager extends NullStorageManager -{ +public class FakeStorageManager extends NullStorageManager { + List messageIds = new ArrayList(); List ackIds = new ArrayList(); @Override - public void storeMessage(final ServerMessage message) throws Exception - { + public void storeMessage(final ServerMessage message) throws Exception { messageIds.add(message.getMessageID()); } @Override - public void storeMessageTransactional(final long txID, final ServerMessage message) throws Exception - { + public void storeMessageTransactional(final long txID, final ServerMessage message) throws Exception { messageIds.add(message.getMessageID()); } @Override - public void deleteMessage(final long messageID) throws Exception - { + public void deleteMessage(final long messageID) throws Exception { messageIds.remove(messageID); } @Override - public void storeAcknowledge(final long queueID, final long messageID) throws Exception - { + public void storeAcknowledge(final long queueID, final long messageID) throws Exception { ackIds.add(messageID); } @Override - public void storeAcknowledgeTransactional(final long txID, final long queueID, final long messageiD) throws Exception - { + public void storeAcknowledgeTransactional(final long txID, + final long queueID, + final long messageiD) throws Exception { ackIds.add(messageiD); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/FileLockTimeoutTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/FileLockTimeoutTest.java index 4797e23781..95d2f8f0fd 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/FileLockTimeoutTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/FileLockTimeoutTest.java @@ -33,68 +33,51 @@ import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; -public class FileLockTimeoutTest extends ActiveMQTestBase -{ +public class FileLockTimeoutTest extends ActiveMQTestBase { + @BeforeClass - public static void prepareLogger() - { + public static void prepareLogger() { AssertionLoggerHandler.startCapture(); } @AfterClass - public static void clearLogger() - { + public static void clearLogger() { AssertionLoggerHandler.stopCapture(); } - protected void doTest(final boolean useAIO) throws Exception - { - if (useAIO) - { - Assert.assertTrue(String.format("libAIO is not loaded on %s %s %s", System.getProperty("os.name"), - System.getProperty("os.arch"), System.getProperty("os.version")), - LibaioContext.isLoaded() - ); + protected void doTest(final boolean useAIO) throws Exception { + if (useAIO) { + Assert.assertTrue(String.format("libAIO is not loaded on %s %s %s", System.getProperty("os.name"), System.getProperty("os.arch"), System.getProperty("os.version")), LibaioContext.isLoaded()); } - Configuration config = super.createDefaultInVMConfig() - .setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration()) - .clearAcceptorConfigurations(); + Configuration config = super.createDefaultInVMConfig().setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration()).clearAcceptorConfigurations(); ActiveMQServer server1 = createServer(true, config); - if (useAIO) - { + if (useAIO) { server1.getConfiguration().setJournalType(JournalType.ASYNCIO); } - else - { + else { server1.getConfiguration().setJournalType(JournalType.NIO); } server1.start(); server1.waitForActivation(10, TimeUnit.SECONDS); final ActiveMQServer server2 = createServer(true, config); - if (useAIO) - { + if (useAIO) { server2.getConfiguration().setJournalType(JournalType.ASYNCIO); } - else - { + else { server2.getConfiguration().setJournalType(JournalType.NIO); } server2.getConfiguration().setJournalLockAcquisitionTimeout(5000); // if something happens that causes the timeout to misbehave we don't want the test to hang ExecutorService service = Executors.newSingleThreadExecutor(); - Runnable r = new Runnable() - { + Runnable r = new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { server2.start(); } - catch (final Exception e) - { + catch (final Exception e) { throw new RuntimeException(e); } } @@ -102,12 +85,10 @@ public class FileLockTimeoutTest extends ActiveMQTestBase Future f = service.submit(r); - try - { + try { f.get(15, TimeUnit.SECONDS); } - catch (Exception e) - { + catch (Exception e) { IntegrationTestLogger.LOGGER.warn("aborting test because server is taking too long to start"); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/GracefulShutdownTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/GracefulShutdownTest.java index 356a2ad8ed..b7894a4e77 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/GracefulShutdownTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/GracefulShutdownTest.java @@ -28,13 +28,11 @@ import org.apache.activemq.artemis.core.server.ActiveMQServers; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Test; -public class GracefulShutdownTest extends ActiveMQTestBase -{ +public class GracefulShutdownTest extends ActiveMQTestBase { + @Test - public void testGracefulShutdown() throws Exception - { - Configuration config = createDefaultInVMConfig() - .setGracefulShutdownEnabled(true); + public void testGracefulShutdown() throws Exception { + Configuration config = createDefaultInVMConfig().setGracefulShutdownEnabled(true); final ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false)); @@ -46,16 +44,12 @@ public class GracefulShutdownTest extends ActiveMQTestBase ClientSession session = sf.createSession(true, true); - Thread t = new Thread(new Runnable() - { - public void run() - { - try - { + Thread t = new Thread(new Runnable() { + public void run() { + try { server.stop(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -65,8 +59,7 @@ public class GracefulShutdownTest extends ActiveMQTestBase t.start(); // wait for the thread to actually call stop() on the server - while (server.isStarted()) - { + while (server.isStarted()) { Thread.sleep(100); } @@ -77,13 +70,11 @@ public class GracefulShutdownTest extends ActiveMQTestBase session.start(); assertNotNull(session.createConsumer("testQueue").receive(500)); - try - { + try { sf.createSession(); fail("Creating a session here should fail because the acceptors should be paused"); } - catch (Exception e) - { + catch (Exception e) { assertTrue(e instanceof ActiveMQSessionCreationException); ActiveMQSessionCreationException activeMQSessionCreationException = (ActiveMQSessionCreationException) e; assertEquals(activeMQSessionCreationException.getType(), ActiveMQExceptionType.SESSION_CREATION_REJECTED); @@ -95,10 +86,8 @@ public class GracefulShutdownTest extends ActiveMQTestBase long start = System.currentTimeMillis(); // wait for the shutdown thread to complete, interrupt it if it takes too long - while (t.isAlive()) - { - if (System.currentTimeMillis() - start > 3000) - { + while (t.isAlive()) { + if (System.currentTimeMillis() - start > 3000) { t.interrupt(); break; } @@ -110,13 +99,10 @@ public class GracefulShutdownTest extends ActiveMQTestBase } @Test - public void testGracefulShutdownWithTimeout() throws Exception - { + public void testGracefulShutdownWithTimeout() throws Exception { long timeout = 10000; - Configuration config = createDefaultInVMConfig() - .setGracefulShutdownEnabled(true) - .setGracefulShutdownTimeout(timeout); + Configuration config = createDefaultInVMConfig().setGracefulShutdownEnabled(true).setGracefulShutdownTimeout(timeout); final ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false)); @@ -126,16 +112,12 @@ public class GracefulShutdownTest extends ActiveMQTestBase ClientSessionFactory sf = createSessionFactory(locator); - Thread t = new Thread(new Runnable() - { - public void run() - { - try - { + Thread t = new Thread(new Runnable() { + public void run() { + try { server.stop(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -146,18 +128,15 @@ public class GracefulShutdownTest extends ActiveMQTestBase t.start(); // wait for the thread to actually call stop() on the server - while (server.isStarted()) - { + while (server.isStarted()) { Thread.sleep(100); } - try - { + try { sf.createSession(); fail("Creating a session here should fail because the acceptors should be paused"); } - catch (Exception e) - { + catch (Exception e) { assertTrue(e instanceof ActiveMQSessionCreationException); ActiveMQSessionCreationException activeMQSessionCreationException = (ActiveMQSessionCreationException) e; assertEquals(activeMQSessionCreationException.getType(), ActiveMQExceptionType.SESSION_CREATION_REJECTED); @@ -167,8 +146,7 @@ public class GracefulShutdownTest extends ActiveMQTestBase assertTrue("thread should still be alive here waiting for the timeout to elapse", t.isAlive()); - while (t.isAlive()) - { + while (t.isAlive()) { Thread.sleep(100); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/LVQRecoveryTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/LVQRecoveryTest.java index 0ef5480a4b..657f766581 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/LVQRecoveryTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/LVQRecoveryTest.java @@ -36,8 +36,8 @@ import org.junit.Test; import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; -public class LVQRecoveryTest extends ActiveMQTestBase -{ +public class LVQRecoveryTest extends ActiveMQTestBase { + private ActiveMQServer server; private ClientSession clientSession; @@ -54,8 +54,7 @@ public class LVQRecoveryTest extends ActiveMQTestBase private ServerLocator locator; @Test - public void testMultipleMessagesAfterRecovery() throws Exception - { + public void testMultipleMessagesAfterRecovery() throws Exception { Xid xid = new XidImpl("bq1".getBytes(), 4, "gtid1".getBytes()); ClientProducer producer = clientSessionXa.createProducer(address); SimpleString messageId1 = new SimpleString("SMID1"); @@ -94,8 +93,7 @@ public class LVQRecoveryTest extends ActiveMQTestBase } @Test - public void testManyMessagesReceivedWithRollback() throws Exception - { + public void testManyMessagesReceivedWithRollback() throws Exception { Xid xid = new XidImpl("bq1".getBytes(), 4, "gtid1".getBytes()); ClientProducer producer = clientSession.createProducer(address); ClientConsumer consumer = clientSessionXa.createConsumer(qName1); @@ -165,29 +163,24 @@ public class LVQRecoveryTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); configuration = createDefaultInVMConfig(); server = createServer(true, configuration); server.start(); - qs = new AddressSettings() - .setLastValueQueue(true); + qs = new AddressSettings().setLastValueQueue(true); server.getAddressSettingsRepository().addMatch(address.toString(), qs); // then we create a client as normal - locator = createInVMNonHALocator() - .setBlockOnAcknowledge(true) - .setAckBatchSize(0); + locator = createInVMNonHALocator().setBlockOnAcknowledge(true).setAckBatchSize(0); ClientSessionFactory sessionFactory = createSessionFactory(locator); clientSession = sessionFactory.createSession(false, true, true); clientSessionXa = sessionFactory.createSession(true, false, false); clientSession.createQueue(address, qName1, null, true); } - private void restartServer() throws Exception - { + private void restartServer() throws Exception { server.stop(); server = null; server = createServer(true, configuration); @@ -198,9 +191,7 @@ public class LVQRecoveryTest extends ActiveMQTestBase server.getAddressSettingsRepository().addMatch(address.toString(), new AddressSettings().setLastValueQueue(true)); // then we create a client as normal locator.close(); - locator = createInVMNonHALocator() - .setBlockOnAcknowledge(true) - .setAckBatchSize(0); + locator = createInVMNonHALocator().setBlockOnAcknowledge(true).setAckBatchSize(0); ClientSessionFactory sessionFactory = createSessionFactory(locator); clientSession = sessionFactory.createSession(false, true, true); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/LVQTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/LVQTest.java index 133399c10d..24f1faa3bc 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/LVQTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/LVQTest.java @@ -33,8 +33,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class LVQTest extends ActiveMQTestBase -{ +public class LVQTest extends ActiveMQTestBase { + private ActiveMQServer server; private ClientSession clientSession; @@ -48,8 +48,7 @@ public class LVQTest extends ActiveMQTestBase private final SimpleString qName1 = new SimpleString("LVQTestQ1"); @Test - public void testSimple() throws Exception - { + public void testSimple() throws Exception { ClientProducer producer = clientSession.createProducer(address); ClientConsumer consumer = clientSession.createConsumer(qName1); ClientMessage m1 = createTextMessage(clientSession, "m1"); @@ -67,8 +66,7 @@ public class LVQTest extends ActiveMQTestBase } @Test - public void testMultipleMessages() throws Exception - { + public void testMultipleMessages() throws Exception { ClientProducer producer = clientSession.createProducer(address); ClientConsumer consumer = clientSession.createConsumer(qName1); SimpleString messageId1 = new SimpleString("SMID1"); @@ -97,8 +95,7 @@ public class LVQTest extends ActiveMQTestBase } @Test - public void testFirstMessageReceivedButAckedAfter() throws Exception - { + public void testFirstMessageReceivedButAckedAfter() throws Exception { ClientProducer producer = clientSession.createProducer(address); ClientConsumer consumer = clientSession.createConsumer(qName1); ClientMessage m1 = createTextMessage(clientSession, "m1"); @@ -120,8 +117,7 @@ public class LVQTest extends ActiveMQTestBase } @Test - public void testFirstMessageReceivedAndCancelled() throws Exception - { + public void testFirstMessageReceivedAndCancelled() throws Exception { ClientProducer producer = clientSession.createProducer(address); ClientConsumer consumer = clientSession.createConsumer(qName1); ClientMessage m1 = createTextMessage(clientSession, "m1"); @@ -146,8 +142,7 @@ public class LVQTest extends ActiveMQTestBase } @Test - public void testManyMessagesReceivedAndCancelled() throws Exception - { + public void testManyMessagesReceivedAndCancelled() throws Exception { ClientProducer producer = clientSession.createProducer(address); ClientConsumer consumer = clientSession.createConsumer(qName1); @@ -200,8 +195,7 @@ public class LVQTest extends ActiveMQTestBase } @Test - public void testSimpleInTx() throws Exception - { + public void testSimpleInTx() throws Exception { ClientProducer producer = clientSessionTxReceives.createProducer(address); ClientConsumer consumer = clientSessionTxReceives.createConsumer(qName1); @@ -220,8 +214,7 @@ public class LVQTest extends ActiveMQTestBase } @Test - public void testMultipleMessagesInTx() throws Exception - { + public void testMultipleMessagesInTx() throws Exception { ClientProducer producer = clientSessionTxReceives.createProducer(address); ClientConsumer consumer = clientSessionTxReceives.createConsumer(qName1); SimpleString messageId1 = new SimpleString("SMID1"); @@ -253,8 +246,7 @@ public class LVQTest extends ActiveMQTestBase } @Test - public void testMultipleMessagesInTxRollback() throws Exception - { + public void testMultipleMessagesInTxRollback() throws Exception { ClientProducer producer = clientSessionTxReceives.createProducer(address); ClientConsumer consumer = clientSessionTxReceives.createConsumer(qName1); SimpleString messageId1 = new SimpleString("SMID1"); @@ -300,8 +292,7 @@ public class LVQTest extends ActiveMQTestBase } @Test - public void testSingleTXRollback() throws Exception - { + public void testSingleTXRollback() throws Exception { ClientProducer producer = clientSessionTxReceives.createProducer(address); ClientConsumer consumer = clientSessionTxReceives.createConsumer(qName1); SimpleString messageId1 = new SimpleString("SMID1"); @@ -321,8 +312,7 @@ public class LVQTest extends ActiveMQTestBase } @Test - public void testMultipleMessagesInTxSend() throws Exception - { + public void testMultipleMessagesInTxSend() throws Exception { ClientProducer producer = clientSessionTxSends.createProducer(address); ClientConsumer consumer = clientSessionTxSends.createConsumer(qName1); SimpleString rh = new SimpleString("SMID1"); @@ -353,8 +343,7 @@ public class LVQTest extends ActiveMQTestBase } @Test - public void testMultipleMessagesPersistedCorrectly() throws Exception - { + public void testMultipleMessagesPersistedCorrectly() throws Exception { ClientProducer producer = clientSession.createProducer(address); ClientConsumer consumer = clientSession.createConsumer(qName1); SimpleString rh = new SimpleString("SMID1"); @@ -392,8 +381,7 @@ public class LVQTest extends ActiveMQTestBase } @Test - public void testMultipleMessagesPersistedCorrectlyInTx() throws Exception - { + public void testMultipleMessagesPersistedCorrectlyInTx() throws Exception { ClientProducer producer = clientSessionTxSends.createProducer(address); ClientConsumer consumer = clientSessionTxSends.createConsumer(qName1); SimpleString rh = new SimpleString("SMID1"); @@ -432,8 +420,7 @@ public class LVQTest extends ActiveMQTestBase } @Test - public void testMultipleAcksPersistedCorrectly() throws Exception - { + public void testMultipleAcksPersistedCorrectly() throws Exception { Queue queue = server.locateQueue(qName1); ClientProducer producer = clientSession.createProducer(address); @@ -493,8 +480,7 @@ public class LVQTest extends ActiveMQTestBase } @Test - public void testRemoveMessageThroughManagement() throws Exception - { + public void testRemoveMessageThroughManagement() throws Exception { Queue queue = server.locateQueue(qName1); ClientProducer producer = clientSession.createProducer(address); @@ -519,8 +505,7 @@ public class LVQTest extends ActiveMQTestBase } @Test - public void testMultipleAcksPersistedCorrectly2() throws Exception - { + public void testMultipleAcksPersistedCorrectly2() throws Exception { Queue queue = server.locateQueue(qName1); ClientProducer producer = clientSession.createProducer(address); @@ -548,8 +533,7 @@ public class LVQTest extends ActiveMQTestBase } @Test - public void testMultipleAcksPersistedCorrectlyInTx() throws Exception - { + public void testMultipleAcksPersistedCorrectlyInTx() throws Exception { ClientProducer producer = clientSessionTxReceives.createProducer(address); ClientConsumer consumer = clientSessionTxReceives.createConsumer(qName1); SimpleString rh = new SimpleString("SMID1"); @@ -607,8 +591,7 @@ public class LVQTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = addServer(ActiveMQServers.newActiveMQServer(createDefaultInVMConfig(), false)); @@ -617,9 +600,7 @@ public class LVQTest extends ActiveMQTestBase server.getAddressSettingsRepository().addMatch(address.toString(), new AddressSettings().setLastValueQueue(true)); // then we create a client as normalServer - ServerLocator locator = createInVMNonHALocator() - .setBlockOnAcknowledge(true) - .setAckBatchSize(0); + ServerLocator locator = createInVMNonHALocator().setBlockOnAcknowledge(true).setAckBatchSize(0); ClientSessionFactory sf = createSessionFactory(locator); clientSession = addClientSession(sf.createSession(false, true, true)); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/NIOFileLockTimeoutTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/NIOFileLockTimeoutTest.java index 6900c768a5..9e44c060f8 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/NIOFileLockTimeoutTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/NIOFileLockTimeoutTest.java @@ -18,16 +18,14 @@ package org.apache.activemq.artemis.tests.integration.server; import org.junit.Test; -public class NIOFileLockTimeoutTest extends FileLockTimeoutTest -{ +public class NIOFileLockTimeoutTest extends FileLockTimeoutTest { + @Test /** * When running this test from an IDE add this to the test command line so that the AssertionLoggerHandler works properly: * * -Djava.util.logging.manager=org.jboss.logmanager.LogManager -Dlogging.configuration=file:/tests/config/logging.properties - */ - public void testNIOFileLockExpiration() throws Exception - { + */ public void testNIOFileLockExpiration() throws Exception { doTest(false); } } \ No newline at end of file diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/PredefinedQueueTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/PredefinedQueueTest.java index 811fabd490..ebed9e6b43 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/PredefinedQueueTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/PredefinedQueueTest.java @@ -39,23 +39,21 @@ import org.junit.Test; import java.util.ArrayList; import java.util.List; -public class PredefinedQueueTest extends ActiveMQTestBase -{ +public class PredefinedQueueTest extends ActiveMQTestBase { + private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private Configuration configuration = null; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); configuration = createDefaultInVMConfig(); } @Test - public void testFailOnCreatePredefinedQueues() throws Exception - { + public void testFailOnCreatePredefinedQueues() throws Exception { final String testAddress = "testAddress"; final String queueName1 = "queue1"; @@ -64,17 +62,11 @@ public class PredefinedQueueTest extends ActiveMQTestBase final String queueName3 = "queue3"; - CoreQueueConfiguration queue1 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName1); + CoreQueueConfiguration queue1 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName1); - CoreQueueConfiguration queue2 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName2); + CoreQueueConfiguration queue2 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName2); - CoreQueueConfiguration queue3 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName3); + CoreQueueConfiguration queue3 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName3); List queueConfs = new ArrayList(); @@ -94,70 +86,54 @@ public class PredefinedQueueTest extends ActiveMQTestBase ClientSession session = addClientSession(sf.createSession(false, true, true)); - try - { + try { session.createQueue(testAddress, queueName1, null, false); Assert.fail("Should throw exception"); } - catch (ActiveMQQueueExistsException se) - { + catch (ActiveMQQueueExistsException se) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } - try - { + try { session.createQueue(testAddress, queueName2, null, false); Assert.fail("Should throw exception"); } - catch (ActiveMQQueueExistsException se) - { + catch (ActiveMQQueueExistsException se) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } - try - { + try { session.createQueue(testAddress, queueName3, null, false); Assert.fail("Should throw exception"); } - catch (ActiveMQQueueExistsException se) - { + catch (ActiveMQQueueExistsException se) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } } @Test - public void testDeploySameNames() throws Exception - { + public void testDeploySameNames() throws Exception { final String testAddress = "testAddress"; final String queueName1 = "queue1"; final String queueName2 = "queue2"; - CoreQueueConfiguration queue1 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName1); + CoreQueueConfiguration queue1 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName1); - CoreQueueConfiguration queue2 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName2); + CoreQueueConfiguration queue2 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName2); - configuration - .addQueueConfiguration(queue1) - .addQueueConfiguration(queue2); + configuration.addQueueConfiguration(queue1).addQueueConfiguration(queue2); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(configuration, false)); @@ -185,8 +161,7 @@ public class PredefinedQueueTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("testkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.putIntProperty(propKey, i); @@ -194,8 +169,7 @@ public class PredefinedQueueTest extends ActiveMQTestBase producer.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(200); Assert.assertNotNull(message); Assert.assertEquals(i, message.getObjectProperty(propKey)); @@ -212,8 +186,7 @@ public class PredefinedQueueTest extends ActiveMQTestBase } @Test - public void testDeployPreexistingQueues() throws Exception - { + public void testDeployPreexistingQueues() throws Exception { final String testAddress = "testAddress"; final String queueName1 = "queue1"; @@ -244,22 +217,13 @@ public class PredefinedQueueTest extends ActiveMQTestBase server.stop(); - CoreQueueConfiguration queue1 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName1); + CoreQueueConfiguration queue1 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName1); - CoreQueueConfiguration queue2 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName2); + CoreQueueConfiguration queue2 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName2); - CoreQueueConfiguration queue3 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName3); + CoreQueueConfiguration queue3 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName3); - configuration - .addQueueConfiguration(queue1) - .addQueueConfiguration(queue2) - .addQueueConfiguration(queue3); + configuration.addQueueConfiguration(queue1).addQueueConfiguration(queue2).addQueueConfiguration(queue3); server.start(); @@ -281,8 +245,7 @@ public class PredefinedQueueTest extends ActiveMQTestBase final SimpleString propKey = new SimpleString("testkey"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(false); message.putIntProperty(propKey, i); @@ -290,8 +253,7 @@ public class PredefinedQueueTest extends ActiveMQTestBase producer.send(message); } - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(200); Assert.assertNotNull(message); Assert.assertEquals(i, message.getObjectProperty(propKey)); @@ -314,31 +276,23 @@ public class PredefinedQueueTest extends ActiveMQTestBase } @Test - public void testDurableNonDurable() throws Exception - { + public void testDurableNonDurable() throws Exception { final String testAddress = "testAddress"; final String queueName1 = "queue1"; final String queueName2 = "queue2"; - CoreQueueConfiguration queue1 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName1) - .setDurable(false); + CoreQueueConfiguration queue1 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName1).setDurable(false); - CoreQueueConfiguration queue2 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName2); + CoreQueueConfiguration queue2 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName2); List queueConfs = new ArrayList(); queueConfs.add(queue1); queueConfs.add(queue2); - configuration - .addQueueConfiguration(queue1) - .addQueueConfiguration(queue2); + configuration.addQueueConfiguration(queue1).addQueueConfiguration(queue2); ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(configuration)); @@ -358,8 +312,7 @@ public class PredefinedQueueTest extends ActiveMQTestBase PredefinedQueueTest.log.info("sending messages"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(true); message.putIntProperty(propKey, i); @@ -391,8 +344,7 @@ public class PredefinedQueueTest extends ActiveMQTestBase Assert.assertNull(message); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { message = consumer2.receive(200); Assert.assertNotNull(message); Assert.assertEquals(i, message.getObjectProperty(propKey)); @@ -404,19 +356,14 @@ public class PredefinedQueueTest extends ActiveMQTestBase } @Test - public void testDeployWithFilter() throws Exception - { + public void testDeployWithFilter() throws Exception { final String testAddress = "testAddress"; final String queueName1 = "queue1"; final String filter = "cheese='camembert'"; - CoreQueueConfiguration queue1 = new CoreQueueConfiguration() - .setAddress(testAddress) - .setName(queueName1) - .setFilterString(filter) - .setDurable(false); + CoreQueueConfiguration queue1 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName1).setFilterString(filter).setDurable(false); configuration.addQueueConfiguration(queue1); @@ -438,8 +385,7 @@ public class PredefinedQueueTest extends ActiveMQTestBase PredefinedQueueTest.log.info("sending messages"); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(true); message.putStringProperty(new SimpleString("cheese"), new SimpleString("camembert")); @@ -453,8 +399,7 @@ public class PredefinedQueueTest extends ActiveMQTestBase ClientConsumer consumer1 = session.createConsumer(queueName1); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer1.receive(200); Assert.assertNotNull(message); Assert.assertEquals(i, message.getObjectProperty(propKey)); @@ -463,8 +408,7 @@ public class PredefinedQueueTest extends ActiveMQTestBase Assert.assertNull(consumer1.receiveImmediate()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message = session.createMessage(true); message.putStringProperty(new SimpleString("cheese"), new SimpleString("roquefort")); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ResourceLimitTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ResourceLimitTest.java index 72ebd73c45..9d4edce9bb 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ResourceLimitTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ResourceLimitTest.java @@ -30,16 +30,15 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Before; import org.junit.Test; -public class ResourceLimitTest extends ActiveMQTestBase -{ +public class ResourceLimitTest extends ActiveMQTestBase { + private ActiveMQServer server; private TransportConfiguration liveTC; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); ResourceLimitSettings resourceLimitSettings = new ResourceLimitSettings(); @@ -47,29 +46,24 @@ public class ResourceLimitTest extends ActiveMQTestBase resourceLimitSettings.setMaxConnections(1); resourceLimitSettings.setMaxQueues(1); - Configuration configuration = createBasicConfig() - .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY)) - .addResourceLimitSettings(resourceLimitSettings); + Configuration configuration = createBasicConfig().addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY)).addResourceLimitSettings(resourceLimitSettings); server = addServer(ActiveMQServers.newActiveMQServer(configuration, false)); server.start(); } @Test - public void testSessionLimitForUser() throws Exception - { + public void testSessionLimitForUser() throws Exception { ServerLocator locator = addServerLocator(createNonHALocator(false)); ClientSessionFactory clientSessionFactory = locator.createSessionFactory(); ClientSession clientSession = clientSessionFactory.createSession("myUser", "password", false, true, true, false, 0); - try - { + try { ClientSessionFactory extraClientSessionFactory = locator.createSessionFactory(); ClientSession extraClientSession = extraClientSessionFactory.createSession("myUser", "password", false, true, true, false, 0); fail("creating a session factory here should fail"); } - catch (Exception e) - { + catch (Exception e) { assertTrue(e instanceof ActiveMQSessionCreationException); } @@ -77,32 +71,27 @@ public class ResourceLimitTest extends ActiveMQTestBase clientSession = clientSessionFactory.createSession("myUser", "password", false, true, true, false, 0); - try - { + try { ClientSessionFactory extraClientSessionFactory = locator.createSessionFactory(); ClientSession extraClientSession = extraClientSessionFactory.createSession("myUser", "password", false, true, true, false, 0); fail("creating a session factory here should fail"); } - catch (Exception e) - { + catch (Exception e) { assertTrue(e instanceof ActiveMQSessionCreationException); } } @Test - public void testQueueLimitForUser() throws Exception - { + public void testQueueLimitForUser() throws Exception { ServerLocator locator = addServerLocator(createNonHALocator(false)); ClientSessionFactory clientSessionFactory = locator.createSessionFactory(); ClientSession clientSession = clientSessionFactory.createSession("myUser", "password", false, true, true, false, 0); clientSession.createQueue("address", "queue"); - try - { + try { clientSession.createQueue("address", "anotherQueue"); } - catch (Exception e) - { + catch (Exception e) { assertTrue(e instanceof ActiveMQSessionCreationException); } @@ -110,21 +99,17 @@ public class ResourceLimitTest extends ActiveMQTestBase clientSession.createQueue("address", "queue"); - try - { + try { clientSession.createQueue("address", "anotherQueue"); } - catch (Exception e) - { + catch (Exception e) { assertTrue(e instanceof ActiveMQSessionCreationException); } - try - { + try { clientSession.createSharedQueue(SimpleString.toSimpleString("address"), SimpleString.toSimpleString("anotherQueue"), false); } - catch (Exception e) - { + catch (Exception e) { assertTrue(e instanceof ActiveMQSessionCreationException); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ScaleDown3NodeTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ScaleDown3NodeTest.java index 72da63e5ea..b611a2eabf 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ScaleDown3NodeTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ScaleDown3NodeTest.java @@ -39,12 +39,11 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class ScaleDown3NodeTest extends ClusterTestBase -{ +public class ScaleDown3NodeTest extends ClusterTestBase { + @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); setupLiveServer(0, isFileStorage(), false, isNetty(), true); setupLiveServer(1, isFileStorage(), false, isNetty(), true); @@ -76,31 +75,26 @@ public class ScaleDown3NodeTest extends ClusterTestBase IntegrationTestLogger.LOGGER.info("==============================="); } - protected boolean isNetty() - { + protected boolean isNetty() { return true; } @Test - public void testBasicScaleDownWithDefaultReconnectAttempts() throws Exception - { + public void testBasicScaleDownWithDefaultReconnectAttempts() throws Exception { testBasicScaleDownInternal(ActiveMQDefaultConfiguration.getDefaultBridgeReconnectAttempts(), false); } @Test - public void testBasicScaleDownWithoutBridgeReconnect() throws Exception - { + public void testBasicScaleDownWithoutBridgeReconnect() throws Exception { testBasicScaleDownInternal(0, false); } @Test - public void testBasicScaleDownWithDefaultReconnectAttemptsAndLargeMessages() throws Exception - { + public void testBasicScaleDownWithDefaultReconnectAttemptsAndLargeMessages() throws Exception { testBasicScaleDownInternal(ActiveMQDefaultConfiguration.getDefaultBridgeReconnectAttempts(), true); } - private void testBasicScaleDownInternal(int reconnectAttempts, boolean large) throws Exception - { + private void testBasicScaleDownInternal(int reconnectAttempts, boolean large) throws Exception { AddressSettings addressSettings = new AddressSettings().setRedistributionDelay(0); servers[0].getAddressSettingsRepository().addMatch("#", addressSettings); servers[1].getAddressSettingsRepository().addMatch("#", addressSettings); @@ -128,15 +122,13 @@ public class ScaleDown3NodeTest extends ClusterTestBase Message message; - if (large) - { + if (large) { LargeServerMessageImpl fileMessage = new LargeServerMessageImpl((JournalStorageManager) servers[2].getStorageManager()); fileMessage.setMessageID(1005); fileMessage.setDurable(true); - for (int i = 0; i < 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; i++) - { + for (int i = 0; i < 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; i++) { fileMessage.addBytes(new byte[]{ActiveMQTestBase.getSamplebyte(i)}); } @@ -146,20 +138,17 @@ public class ScaleDown3NodeTest extends ClusterTestBase message = fileMessage; } - else - { + else { message = session.createMessage(false); } - for (int i = 0; i < TEST_SIZE; i++) - { + for (int i = 0; i < TEST_SIZE; i++) { ClientProducer producer = session.createProducer(addressName); producer.send(message); } - if (large) - { - ((LargeServerMessageImpl)message).deleteFile(); + if (large) { + ((LargeServerMessageImpl) message).deleteFile(); } // add a consumer to node 0 to trigger redistribution here @@ -170,16 +159,13 @@ public class ScaleDown3NodeTest extends ClusterTestBase long start = System.currentTimeMillis(); long messageCount = 0; - while (System.currentTimeMillis() - start < timeout) - { + while (System.currentTimeMillis() - start < timeout) { // ensure the message is not in the queue on node 2 messageCount = getMessageCount(snfQueue); - if (messageCount < TEST_SIZE) - { + if (messageCount < TEST_SIZE) { Thread.sleep(200); } - else - { + else { break; } } @@ -194,16 +180,13 @@ public class ScaleDown3NodeTest extends ClusterTestBase start = System.currentTimeMillis(); - while (System.currentTimeMillis() - start < timeout) - { + while (System.currentTimeMillis() - start < timeout) { // ensure the message is not in the queue on node 2 messageCount = getMessageCount(((LocalQueueBinding) servers[2].getPostOffice().getBinding(new SimpleString(queueName1))).getQueue()); - if (messageCount > 0) - { + if (messageCount > 0) { Thread.sleep(200); } - else - { + else { break; } } @@ -215,16 +198,13 @@ public class ScaleDown3NodeTest extends ClusterTestBase // allow some time for redistribution to move the message to node 1 start = System.currentTimeMillis(); - while (System.currentTimeMillis() - start < timeout) - { + while (System.currentTimeMillis() - start < timeout) { // ensure the message is not in the queue on node 2 messageCount = getMessageCount(((LocalQueueBinding) servers[1].getPostOffice().getBinding(new SimpleString(queueName1))).getQueue()); - if (messageCount < TEST_SIZE) - { + if (messageCount < TEST_SIZE) { Thread.sleep(200); } - else - { + else { break; } } @@ -232,16 +212,13 @@ public class ScaleDown3NodeTest extends ClusterTestBase // ensure the message is in queue 1 on node 1 as expected Assert.assertEquals(TEST_SIZE, messageCount); - for (int i = 0; i < TEST_SIZE; i++) - { + for (int i = 0; i < TEST_SIZE; i++) { ClientMessage clientMessage = consumers[0].getConsumer().receive(250); Assert.assertNotNull(clientMessage); - if (large) - { + if (large) { Assert.assertEquals(2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, clientMessage.getBodySize()); - for (int j = 0; j < 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; j++) - { + for (int j = 0; j < 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; j++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(j), clientMessage.getBodyBuffer().readByte()); } } @@ -256,8 +233,7 @@ public class ScaleDown3NodeTest extends ClusterTestBase } @Test - public void testScaleDownWithMultipleQueues() throws Exception - { + public void testScaleDownWithMultipleQueues() throws Exception { AddressSettings addressSettings = new AddressSettings().setRedistributionDelay(0); servers[0].getAddressSettingsRepository().addMatch("#", addressSettings); servers[1].getAddressSettingsRepository().addMatch("#", addressSettings); @@ -294,8 +270,7 @@ public class ScaleDown3NodeTest extends ClusterTestBase Message message; message = session.createMessage(false); - for (int i = 0; i < TEST_SIZE; i++) - { + for (int i = 0; i < TEST_SIZE; i++) { ClientProducer producer = session.createProducer(addressName); producer.send(message); } @@ -309,16 +284,13 @@ public class ScaleDown3NodeTest extends ClusterTestBase long start = System.currentTimeMillis(); long messageCount = 0; - while (System.currentTimeMillis() - start < timeout) - { + while (System.currentTimeMillis() - start < timeout) { // ensure the message is not in the queue on node 2 messageCount = getMessageCount(snfQueue); - if (messageCount < TEST_SIZE * 2) - { + if (messageCount < TEST_SIZE * 2) { Thread.sleep(200); } - else - { + else { break; } } @@ -334,17 +306,14 @@ public class ScaleDown3NodeTest extends ClusterTestBase start = System.currentTimeMillis(); - while (System.currentTimeMillis() - start < timeout) - { + while (System.currentTimeMillis() - start < timeout) { // ensure the messages are not in the queues on node 2 messageCount = getMessageCount(((LocalQueueBinding) servers[2].getPostOffice().getBinding(new SimpleString(queueName1))).getQueue()); messageCount += getMessageCount(((LocalQueueBinding) servers[2].getPostOffice().getBinding(new SimpleString(queueName3))).getQueue()); - if (messageCount > 0) - { + if (messageCount > 0) { Thread.sleep(200); } - else - { + else { break; } } @@ -359,17 +328,14 @@ public class ScaleDown3NodeTest extends ClusterTestBase // allow some time for redistribution to move the message to node 1 start = System.currentTimeMillis(); - while (System.currentTimeMillis() - start < timeout) - { + while (System.currentTimeMillis() - start < timeout) { // ensure the message is not in the queue on node 2 messageCount = getMessageCount(((LocalQueueBinding) servers[1].getPostOffice().getBinding(new SimpleString(queueName1))).getQueue()); messageCount += getMessageCount(((LocalQueueBinding) servers[1].getPostOffice().getBinding(new SimpleString(queueName3))).getQueue()); - if (messageCount < TEST_SIZE * 2) - { + if (messageCount < TEST_SIZE * 2) { Thread.sleep(200); } - else - { + else { break; } } @@ -377,8 +343,7 @@ public class ScaleDown3NodeTest extends ClusterTestBase // ensure the message is in queue 1 on node 1 as expected Assert.assertEquals(TEST_SIZE * 2, messageCount); - for (int i = 0; i < TEST_SIZE; i++) - { + for (int i = 0; i < TEST_SIZE; i++) { ClientMessage clientMessage = consumers[0].getConsumer().receive(250); Assert.assertNotNull(clientMessage); IntegrationTestLogger.LOGGER.info("Received: " + clientMessage); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ScaleDownDirectTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ScaleDownDirectTest.java index 4befa65698..6a94333c0a 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ScaleDownDirectTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ScaleDownDirectTest.java @@ -43,28 +43,22 @@ import java.util.Collection; * simulating what would happen during a real scale down. */ @RunWith(value = Parameterized.class) -public class ScaleDownDirectTest extends ClusterTestBase -{ - @Parameterized.Parameters(name = "isNetty={0}") - public static Collection getParameters() - { - return Arrays.asList(new Object[][]{ - {false}, {true} - }); - } +public class ScaleDownDirectTest extends ClusterTestBase { + @Parameterized.Parameters(name = "isNetty={0}") + public static Collection getParameters() { + return Arrays.asList(new Object[][]{{false}, {true}}); + } private final boolean isNetty; - public ScaleDownDirectTest(boolean isNetty) - { + public ScaleDownDirectTest(boolean isNetty) { this.isNetty = isNetty; } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); setupLiveServer(0, isFileStorage(), isNetty, true); setupLiveServer(1, isFileStorage(), isNetty, true); @@ -75,19 +69,16 @@ public class ScaleDownDirectTest extends ClusterTestBase } @Test - public void testSendMixedSmallMessages() throws Exception - { + public void testSendMixedSmallMessages() throws Exception { internalTest(100, 100); } @Test - public void testSendMixedLargelMessages() throws Exception - { + public void testSendMixedLargelMessages() throws Exception { internalTest(2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, 100); } - protected void internalTest(int bufferSize, int numberOfMessages) throws Exception - { + protected void internalTest(int bufferSize, int numberOfMessages) throws Exception { ClientSessionFactory sf = sfs[0]; ClientSession session = sf.createSession(true, true); @@ -97,13 +88,11 @@ public class ScaleDownDirectTest extends ClusterTestBase ClientProducer producer = session.createProducer("ad1"); byte[] buffer = new byte[bufferSize]; - for (int i = 0; i < bufferSize; i++) - { + for (int i = 0; i < bufferSize; i++) { buffer[i] = getSamplebyte(i); } - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage message = session.createMessage(true); message.putIntProperty("i", i); message.getBodyBuffer().writeBytes(buffer); @@ -112,8 +101,7 @@ public class ScaleDownDirectTest extends ClusterTestBase session.createQueue("ad1", "queue2", true); - for (int i = numberOfMessages; i < (numberOfMessages * 2); i++) - { + for (int i = numberOfMessages; i < (numberOfMessages * 2); i++) { ClientMessage message = session.createMessage(true); message.putIntProperty("i", i); message.getBodyBuffer().writeBytes(buffer); @@ -133,13 +121,11 @@ public class ScaleDownDirectTest extends ClusterTestBase ClientConsumer consumer1 = session.createConsumer("queue1"); session.start(); - - for (int i = 0; i < numberOfMessages * 2; i++) - { + for (int i = 0; i < numberOfMessages * 2; i++) { ClientMessage message = consumer1.receive(5000); assertNotNull(message); assertEquals(i, message.getIntProperty("i").intValue()); -// message.acknowledge(); + // message.acknowledge(); checkBody(message, bufferSize); @@ -150,12 +136,11 @@ public class ScaleDownDirectTest extends ClusterTestBase assertNull(messageCheckNull); ClientConsumer consumer2 = session.createConsumer("queue2"); - for (int i = numberOfMessages; i < numberOfMessages * 2; i++) - { + for (int i = numberOfMessages; i < numberOfMessages * 2; i++) { ClientMessage message = consumer2.receive(5000); assertNotNull(message); assertEquals(i, message.getIntProperty("i").intValue()); -// message.acknowledge(); + // message.acknowledge(); checkBody(message, bufferSize); } @@ -166,11 +151,8 @@ public class ScaleDownDirectTest extends ClusterTestBase assertNull(messageCheckNull); } - - @Test - public void testPaging() throws Exception - { + public void testPaging() throws Exception { final int CHUNK_SIZE = 50; int messageCount = 0; final String addressName = "testAddress"; @@ -183,19 +165,15 @@ public class ScaleDownDirectTest extends ClusterTestBase ClientSession session = addClientSession(sf.createSession(false, false)); ClientProducer producer = addClientProducer(session.createProducer(addressName)); - AddressSettings defaultSetting = new AddressSettings() - .setPageSizeBytes(10 * 1024) - .setMaxSizeBytes(20 * 1024); + AddressSettings defaultSetting = new AddressSettings().setPageSizeBytes(10 * 1024).setMaxSizeBytes(20 * 1024); servers[0].getAddressSettingsRepository().addMatch("#", defaultSetting); - while (!servers[0].getPagingManager().getPageStore(new SimpleString(addressName)).isPaging()) - { - for (int i = 0; i < CHUNK_SIZE; i++) - { + while (!servers[0].getPagingManager().getPageStore(new SimpleString(addressName)).isPaging()) { + for (int i = 0; i < CHUNK_SIZE; i++) { Message message = session.createMessage(true); message.getBodyBuffer().writeBytes(new byte[1024]); // The only purpose of this count here is for eventually debug messages on print-data / print-pages -// message.putIntProperty("count", messageCount); + // message.putIntProperty("count", messageCount); producer.send(message); messageCount++; } @@ -207,22 +185,18 @@ public class ScaleDownDirectTest extends ClusterTestBase servers[0].stop(); addConsumer(0, 1, queueName, null); - for (int i = 0; i < messageCount; i++) - { + for (int i = 0; i < messageCount; i++) { ClientMessage message = consumers[0].getConsumer().receive(500); Assert.assertNotNull(message); -// Assert.assertEquals(i, message.getIntProperty("count").intValue()); + // Assert.assertEquals(i, message.getIntProperty("count").intValue()); } Assert.assertNull(consumers[0].getConsumer().receiveImmediate()); removeConsumer(0); } - - @Test - public void testBasicScaleDown() throws Exception - { + public void testBasicScaleDown() throws Exception { final int TEST_SIZE = 2; final String addressName = "testAddress"; final String queueName1 = "testQueue1"; @@ -279,29 +253,21 @@ public class ScaleDownDirectTest extends ClusterTestBase removeConsumer(0); } - private void checkBody(ClientMessage message, int bufferSize) - { + private void checkBody(ClientMessage message, int bufferSize) { assertEquals(bufferSize, message.getBodySize()); byte[] body = new byte[message.getBodySize()]; message.getBodyBuffer().readBytes(body); - for (int bpos = 0; bpos < bufferSize; bpos++) - { - if (getSamplebyte(bpos) != body[bpos]) - { + for (int bpos = 0; bpos < bufferSize; bpos++) { + if (getSamplebyte(bpos) != body[bpos]) { fail("body comparison failure at " + message); } } } - private long performScaledown() throws Exception - { - ScaleDownHandler handler = new ScaleDownHandler(servers[0].getPagingManager(), servers[0].getPostOffice(), - servers[0].getNodeManager(), - servers[0].getClusterManager().getClusterController(), - servers[0].getStorageManager()); + private long performScaledown() throws Exception { + ScaleDownHandler handler = new ScaleDownHandler(servers[0].getPagingManager(), servers[0].getPostOffice(), servers[0].getNodeManager(), servers[0].getClusterManager().getClusterController(), servers[0].getStorageManager()); return handler.scaleDownMessages(sfs[1], servers[1].getNodeID()); } - } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ScaleDownTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ScaleDownTest.java index dacc488c88..f35fb616e6 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ScaleDownTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ScaleDownTest.java @@ -43,30 +43,24 @@ import java.util.Collection; import java.util.Map; @RunWith(value = Parameterized.class) -public class ScaleDownTest extends ClusterTestBase -{ +public class ScaleDownTest extends ClusterTestBase { + private boolean useScaleDownGroupName; // this will ensure that all tests in this class are run twice, // once with "true" passed to the class' constructor and once with "false" @Parameterized.Parameters(name = "useScaleDownGroupName={0}") - public static Collection getParameters() - { - return Arrays.asList(new Object[][]{ - {true}, - {false} - }); + public static Collection getParameters() { + return Arrays.asList(new Object[][]{{true}, {false}}); } - public ScaleDownTest(boolean useScaleDownGroupName) - { + public ScaleDownTest(boolean useScaleDownGroupName) { this.useScaleDownGroupName = useScaleDownGroupName; } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); setupLiveServer(0, isFileStorage(), isNetty(), true); setupLiveServer(1, isFileStorage(), isNetty(), true); @@ -74,8 +68,7 @@ public class ScaleDownTest extends ClusterTestBase haPolicyConfiguration0.setScaleDownConfiguration(new ScaleDownConfiguration()); LiveOnlyPolicyConfiguration haPolicyConfiguration1 = (LiveOnlyPolicyConfiguration) servers[1].getConfiguration().getHAPolicyConfiguration(); haPolicyConfiguration1.setScaleDownConfiguration(new ScaleDownConfiguration()); - if (useScaleDownGroupName) - { + if (useScaleDownGroupName) { haPolicyConfiguration0.getScaleDownConfiguration().setGroupName("bill"); haPolicyConfiguration1.getScaleDownConfiguration().setGroupName("bill"); } @@ -88,14 +81,12 @@ public class ScaleDownTest extends ClusterTestBase setupSessionFactory(1, isNetty()); } - protected boolean isNetty() - { + protected boolean isNetty() { return true; } @Test - public void testBasicScaleDown() throws Exception - { + public void testBasicScaleDown() throws Exception { final int TEST_SIZE = 2; final String addressName = "testAddress"; final String queueName1 = "testQueue1"; @@ -116,7 +107,7 @@ public class ScaleDownTest extends ClusterTestBase Assert.assertNotNull(clientMessage); clientMessage.acknowledge(); consumers[1].getSession().commit(); -// removeConsumer(1); + // removeConsumer(1); // at this point on node 0 there should be 2 messages in testQueue1 and 1 message in testQueue2 Assert.assertEquals(TEST_SIZE, getMessageCount(((LocalQueueBinding) servers[0].getPostOffice().getBinding(new SimpleString(queueName1))).getQueue())); @@ -152,8 +143,7 @@ public class ScaleDownTest extends ClusterTestBase } @Test - public void testStoreAndForward() throws Exception - { + public void testStoreAndForward() throws Exception { final int TEST_SIZE = 50; final String addressName1 = "testAddress1"; final String addressName2 = "testAddress2"; @@ -172,12 +162,10 @@ public class ScaleDownTest extends ClusterTestBase // find and pause the sf queue so no messages actually move from node 0 to node 1 String sfQueueName = null; - for (Map.Entry entry : servers[0].getPostOffice().getAllBindings().entrySet()) - { + for (Map.Entry entry : servers[0].getPostOffice().getAllBindings().entrySet()) { String temp = entry.getValue().getAddress().toString(); - if (temp.startsWith("sf.") && temp.endsWith(servers[1].getNodeID().toString())) - { + if (temp.startsWith("sf.") && temp.endsWith(servers[1].getNodeID().toString())) { // we found the sf queue for the other node // need to pause the sfQueue here ((LocalQueueBinding) entry.getValue()).getQueue().pause(); @@ -203,8 +191,7 @@ public class ScaleDownTest extends ClusterTestBase // get the messages from node 1 addConsumer(0, 1, queueName1, null); - for (int i = 0; i < TEST_SIZE; i++) - { + for (int i = 0; i < TEST_SIZE; i++) { ClientMessage clientMessage = consumers[0].getConsumer().receive(250); Assert.assertNotNull(clientMessage); clientMessage.acknowledge(); @@ -215,8 +202,7 @@ public class ScaleDownTest extends ClusterTestBase removeConsumer(0); addConsumer(0, 1, queueName2, null); - for (int i = 0; i < TEST_SIZE; i++) - { + for (int i = 0; i < TEST_SIZE; i++) { clientMessage = consumers[0].getConsumer().receive(250); Assert.assertNotNull(clientMessage); clientMessage.acknowledge(); @@ -228,8 +214,7 @@ public class ScaleDownTest extends ClusterTestBase } @Test - public void testScaleDownWithMissingQueue() throws Exception - { + public void testScaleDownWithMissingQueue() throws Exception { final int TEST_SIZE = 2; final String addressName = "testAddress"; final String queueName1 = "testQueue1"; @@ -280,8 +265,7 @@ public class ScaleDownTest extends ClusterTestBase } @Test - public void testMessageProperties() throws Exception - { + public void testMessageProperties() throws Exception { final int TEST_SIZE = 5; final String addressName = "testAddress"; final String queueName = "testQueue"; @@ -294,15 +278,13 @@ public class ScaleDownTest extends ClusterTestBase ClientProducer producer = addClientProducer(session.createProducer(addressName)); StringBuilder international = new StringBuilder(); - for (char x = 800; x < 1200; x++) - { + for (char x = 800; x < 1200; x++) { international.append(x); } String special = "\"<>'&"; - for (int i = 0; i < TEST_SIZE; i++) - { + for (int i = 0; i < TEST_SIZE; i++) { ClientMessage msg = session.createMessage(true); msg.getBodyBuffer().writeString("Bob the giant pig " + i); msg.putBooleanProperty("myBooleanProperty", Boolean.TRUE); @@ -327,8 +309,7 @@ public class ScaleDownTest extends ClusterTestBase ClientConsumer consumer = addClientConsumer(session.createConsumer(queueName)); session.start(); - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { ClientMessage msg = consumer.receive(250); byte[] body = new byte[msg.getBodySize()]; msg.getBodyBuffer().readBytes(body); @@ -336,8 +317,7 @@ public class ScaleDownTest extends ClusterTestBase Assert.assertEquals(msg.getBooleanProperty("myBooleanProperty"), Boolean.TRUE); Assert.assertEquals(msg.getByteProperty("myByteProperty"), new Byte("0")); byte[] bytes = msg.getBytesProperty("myBytesProperty"); - for (int j = 0; j < 5; j++) - { + for (int j = 0; j < 5; j++) { Assert.assertEquals(j, bytes[j]); } Assert.assertEquals(i * 1.6, msg.getDoubleProperty("myDoubleProperty"), 0.000001); @@ -353,8 +333,7 @@ public class ScaleDownTest extends ClusterTestBase } @Test - public void testLargeMessage() throws Exception - { + public void testLargeMessage() throws Exception { final String addressName = "testAddress"; final String queueName = "testQueue"; @@ -365,22 +344,18 @@ public class ScaleDownTest extends ClusterTestBase ClientSession session = addClientSession(sf.createSession(false, false)); ClientProducer producer = addClientProducer(session.createProducer(addressName)); - byte[] buffer = new byte[2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE]; - for (int i = 0; i < buffer.length; i++) - { + for (int i = 0; i < buffer.length; i++) { buffer[i] = getSamplebyte(i); } - for (int nmsg = 0; nmsg < 10; nmsg++) - { + for (int nmsg = 0; nmsg < 10; nmsg++) { ClientMessage message = session.createMessage(true); message.getBodyBuffer().writeBytes(buffer); producer.send(message); session.commit(); } - servers[0].stop(); sf = sfs[1]; @@ -388,16 +363,14 @@ public class ScaleDownTest extends ClusterTestBase ClientConsumer consumer = addClientConsumer(session.createConsumer(queueName)); session.start(); - for (int nmsg = 0; nmsg < 10; nmsg++) - { + for (int nmsg = 0; nmsg < 10; nmsg++) { ClientMessage msg = consumer.receive(250); Assert.assertNotNull(msg); Assert.assertEquals(2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, msg.getBodySize()); - for (int i = 0; i < 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; i++) - { + for (int i = 0; i < 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; i++) { byte byteRead = msg.getBodyBuffer().readByte(); Assert.assertEquals(msg + " Is different", ActiveMQTestBase.getSamplebyte(i), byteRead); } @@ -408,8 +381,7 @@ public class ScaleDownTest extends ClusterTestBase } @Test - public void testPaging() throws Exception - { + public void testPaging() throws Exception { final int CHUNK_SIZE = 50; int messageCount = 0; final String addressName = "testAddress"; @@ -422,15 +394,11 @@ public class ScaleDownTest extends ClusterTestBase ClientSession session = addClientSession(sf.createSession(false, false)); ClientProducer producer = addClientProducer(session.createProducer(addressName)); - AddressSettings defaultSetting = new AddressSettings() - .setPageSizeBytes(10 * 1024) - .setMaxSizeBytes(20 * 1024); + AddressSettings defaultSetting = new AddressSettings().setPageSizeBytes(10 * 1024).setMaxSizeBytes(20 * 1024); servers[0].getAddressSettingsRepository().addMatch("#", defaultSetting); - while (!servers[0].getPagingManager().getPageStore(new SimpleString(addressName)).isPaging()) - { - for (int i = 0; i < CHUNK_SIZE; i++) - { + while (!servers[0].getPagingManager().getPageStore(new SimpleString(addressName)).isPaging()) { + for (int i = 0; i < CHUNK_SIZE; i++) { Message message = session.createMessage(true); message.getBodyBuffer().writeBytes(new byte[1024]); producer.send(message); @@ -442,8 +410,7 @@ public class ScaleDownTest extends ClusterTestBase servers[0].stop(); addConsumer(0, 1, queueName, null); - for (int i = 0; i < messageCount; i++) - { + for (int i = 0; i < messageCount; i++) { Assert.assertNotNull(consumers[0].getConsumer().receive(250)); } @@ -452,8 +419,7 @@ public class ScaleDownTest extends ClusterTestBase } @Test - public void testOrderWithPaging() throws Exception - { + public void testOrderWithPaging() throws Exception { final int CHUNK_SIZE = 50; int messageCount = 0; final String addressName = "testAddress"; @@ -466,15 +432,11 @@ public class ScaleDownTest extends ClusterTestBase ClientSession session = addClientSession(sf.createSession(false, false)); ClientProducer producer = addClientProducer(session.createProducer(addressName)); - AddressSettings defaultSetting = new AddressSettings() - .setPageSizeBytes(10 * 1024) - .setMaxSizeBytes(20 * 1024); + AddressSettings defaultSetting = new AddressSettings().setPageSizeBytes(10 * 1024).setMaxSizeBytes(20 * 1024); servers[0].getAddressSettingsRepository().addMatch("#", defaultSetting); - while (!servers[0].getPagingManager().getPageStore(new SimpleString(addressName)).isPaging()) - { - for (int i = 0; i < CHUNK_SIZE; i++) - { + while (!servers[0].getPagingManager().getPageStore(new SimpleString(addressName)).isPaging()) { + for (int i = 0; i < CHUNK_SIZE; i++) { Message message = session.createMessage(true); message.getBodyBuffer().writeBytes(new byte[1024]); message.putIntProperty("order", i); @@ -487,8 +449,7 @@ public class ScaleDownTest extends ClusterTestBase servers[0].stop(); addConsumer(0, 1, queueName, null); - for (int i = 0; i < messageCount; i++) - { + for (int i = 0; i < messageCount; i++) { Assert.assertEquals(i, consumers[0].getConsumer().receive(250).getIntProperty("order").intValue()); } @@ -497,8 +458,7 @@ public class ScaleDownTest extends ClusterTestBase } @Test - public void testFilters() throws Exception - { + public void testFilters() throws Exception { final int TEST_SIZE = 50; final String addressName = "testAddress"; final String evenQueue = "evenQueue"; @@ -513,8 +473,7 @@ public class ScaleDownTest extends ClusterTestBase ClientSession session = addClientSession(sf.createSession(false, false)); ClientProducer producer = addClientProducer(session.createProducer(addressName)); - for (int i = 0; i < TEST_SIZE; i++) - { + for (int i = 0; i < TEST_SIZE; i++) { Message message = session.createMessage(false); if (i % 2 == 0) message.putStringProperty(ClusterTestBase.FILTER_PROP, new SimpleString("0")); @@ -528,17 +487,14 @@ public class ScaleDownTest extends ClusterTestBase addConsumer(0, 1, evenQueue, null); addConsumer(1, 1, oddQueue, null); - for (int i = 0; i < TEST_SIZE; i++) - { + for (int i = 0; i < TEST_SIZE; i++) { String compare; ClientMessage message; - if (i % 2 == 0) - { + if (i % 2 == 0) { message = consumers[0].getConsumer().receive(250); compare = "0"; } - else - { + else { message = consumers[1].getConsumer().receive(250); compare = "1"; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/SimpleStartStopTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/SimpleStartStopTest.java index f2dd72d7d3..a2a686eb6c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/SimpleStartStopTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/SimpleStartStopTest.java @@ -27,8 +27,7 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.jboss.logmanager.Level; import org.junit.Test; -public class SimpleStartStopTest extends ActiveMQTestBase -{ +public class SimpleStartStopTest extends ActiveMQTestBase { /** * Start / stopping the server shouldn't generate any errors. @@ -39,30 +38,24 @@ public class SimpleStartStopTest extends ActiveMQTestBase * @throws Exception */ @Test - public void testStartStopAndCleanupIDs() throws Exception - { + public void testStartStopAndCleanupIDs() throws Exception { AssertionLoggerHandler.clear(); AssertionLoggerHandler.startCapture(); - try - { + try { ActiveMQServer server = null; - for (int i = 0; i < 50; i++) - { + for (int i = 0; i < 50; i++) { server = createServer(true, false); server.start(); server.stop(false); } // There shouldn't be any error from starting / stopping the server - assertFalse("There shouldn't be any error for just starting / stopping the server", - AssertionLoggerHandler.hasLevel(Level.ERROR)); + assertFalse("There shouldn't be any error for just starting / stopping the server", AssertionLoggerHandler.hasLevel(Level.ERROR)); assertFalse(AssertionLoggerHandler.findText("AMQ224008")); - HashMap records = this.internalCountJournalLivingRecords(server.getConfiguration(), false); - AtomicInteger recordCount = records.get((int) JournalRecordIds.ID_COUNTER_RECORD); assertNotNull(recordCount); @@ -73,13 +66,10 @@ public class SimpleStartStopTest extends ActiveMQTestBase System.out.println("RecordCount::" + recordCount); - server.start(); - records = this.internalCountJournalLivingRecords(server.getConfiguration(), false); - recordCount = records.get((int) JournalRecordIds.ID_COUNTER_RECORD); assertNotNull(recordCount); @@ -91,8 +81,7 @@ public class SimpleStartStopTest extends ActiveMQTestBase server.stop(); } - finally - { + finally { AssertionLoggerHandler.stopCapture(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/SuppliedThreadPoolTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/SuppliedThreadPoolTest.java index 23c5f02567..3b0021987c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/SuppliedThreadPoolTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/SuppliedThreadPoolTest.java @@ -33,14 +33,14 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -public class SuppliedThreadPoolTest extends ActiveMQTestBase -{ +public class SuppliedThreadPoolTest extends ActiveMQTestBase { + private ActiveMQServer server; private ServiceRegistry serviceRegistry; + @Before - public void setup() throws Exception - { + public void setup() throws Exception { serviceRegistry = new ServiceRegistryImpl(); serviceRegistry.setExecutorService(Executors.newFixedThreadPool(1)); serviceRegistry.setScheduledExecutorService(Executors.newScheduledThreadPool(1)); @@ -50,17 +50,14 @@ public class SuppliedThreadPoolTest extends ActiveMQTestBase } @After - public void tearDown() throws Exception - { - if (server.isActive()) - { + public void tearDown() throws Exception { + if (server.isActive()) { server.stop(); } } @Test - public void testSuppliedThreadPoolsAreCorrectlySet() throws Exception - { + public void testSuppliedThreadPoolsAreCorrectlySet() throws Exception { assertEquals(serviceRegistry.getScheduledExecutorService(), server.getScheduledPool()); // To check the Executor is what we expect we must reflectively inspect the OrderedExecutorFactory. @@ -70,11 +67,10 @@ public class SuppliedThreadPoolTest extends ActiveMQTestBase } @Test - public void testServerDoesNotShutdownSuppliedThreadPoolsOnStop() throws Exception - { + public void testServerDoesNotShutdownSuppliedThreadPoolsOnStop() throws Exception { server.stop(); - ScheduledExecutorService scheduledExecutorService = server.getScheduledPool(); + ScheduledExecutorService scheduledExecutorService = server.getScheduledPool(); Field field = server.getExecutorFactory().getClass().getDeclaredField("parent"); field.setAccessible(true); @@ -90,8 +86,7 @@ public class SuppliedThreadPoolTest extends ActiveMQTestBase } @Test - public void testCanRestartWithSuppliedThreadPool() throws Exception - { + public void testCanRestartWithSuppliedThreadPool() throws Exception { server.stop(); server.start(); server.waitForActivation(100, TimeUnit.MILLISECONDS); @@ -99,11 +94,10 @@ public class SuppliedThreadPoolTest extends ActiveMQTestBase } @Test - public void testJobsGetScheduledToSuppliedThreadPool() throws Exception - { + public void testJobsGetScheduledToSuppliedThreadPool() throws Exception { server.stop(); - ScheduledThreadPoolExecutor scheduledExecutorService = (ScheduledThreadPoolExecutor) server.getScheduledPool(); + ScheduledThreadPoolExecutor scheduledExecutorService = (ScheduledThreadPoolExecutor) server.getScheduledPool(); Field field = server.getExecutorFactory().getClass().getDeclaredField("parent"); field.setAccessible(true); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/spring/ExampleListener.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/spring/ExampleListener.java index c417ccb1a6..da7b6472bb 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/spring/ExampleListener.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/spring/ExampleListener.java @@ -23,20 +23,17 @@ import javax.jms.TextMessage; import org.apache.activemq.artemis.utils.ReusableLatch; -public class ExampleListener implements MessageListener -{ +public class ExampleListener implements MessageListener { + public static String lastMessage = null; public static ReusableLatch latch = new ReusableLatch(); - public void onMessage(Message message) - { - try - { - lastMessage = ((TextMessage)message).getText(); + public void onMessage(Message message) { + try { + lastMessage = ((TextMessage) message).getText(); } - catch (JMSException e) - { + catch (JMSException e) { throw new RuntimeException(e); } System.out.println("MESSAGE RECEIVED: " + lastMessage); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/spring/MessageSender.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/spring/MessageSender.java index c105d8d2b4..adaae90d80 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/spring/MessageSender.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/spring/MessageSender.java @@ -23,35 +23,29 @@ import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; -public class MessageSender -{ +public class MessageSender { + private ConnectionFactory connectionFactory; private Destination destination; - public ConnectionFactory getConnectionFactory() - { + public ConnectionFactory getConnectionFactory() { return connectionFactory; } - public void setConnectionFactory(ConnectionFactory connectionFactory) - { + public void setConnectionFactory(ConnectionFactory connectionFactory) { this.connectionFactory = connectionFactory; } - public Destination getDestination() - { + public Destination getDestination() { return destination; } - public void setDestination(Destination destination) - { + public void setDestination(Destination destination) { this.destination = destination; } - public void send(String msg) - { - try - { + public void send(String msg) { + try { Connection conn = connectionFactory.createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(destination); @@ -59,8 +53,7 @@ public class MessageSender producer.send(message); conn.close(); } - catch (Exception ex) - { + catch (Exception ex) { ex.printStackTrace(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/spring/SpringIntegrationTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/spring/SpringIntegrationTest.java index 37b15423e6..0b0d1c83d3 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/spring/SpringIntegrationTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/spring/SpringIntegrationTest.java @@ -29,13 +29,12 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jms.listener.DefaultMessageListenerContainer; -public class SpringIntegrationTest extends ActiveMQTestBase -{ +public class SpringIntegrationTest extends ActiveMQTestBase { + IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); // Need to force GC as the connection on the spring needs to be cleared // otherwise the sprint thread may leak here @@ -43,12 +42,10 @@ public class SpringIntegrationTest extends ActiveMQTestBase } @Test - public void testSpring() throws Exception - { + public void testSpring() throws Exception { System.out.println("Creating bean factory..."); ApplicationContext context = null; - try - { + try { context = new ClassPathXmlApplicationContext(new String[]{"spring-jms-beans.xml"}); MessageSender sender = (MessageSender) context.getBean("MessageSender"); System.out.println("Sending message..."); @@ -59,30 +56,23 @@ public class SpringIntegrationTest extends ActiveMQTestBase Assert.assertEquals(ExampleListener.lastMessage, "Hello world"); ((ActiveMQConnectionFactory) sender.getConnectionFactory()).close(); } - finally - { - try - { - if (context != null) - { + finally { + try { + if (context != null) { DefaultMessageListenerContainer container = (DefaultMessageListenerContainer) context.getBean("listenerContainer"); container.stop(); } } - catch (Throwable ignored) - { + catch (Throwable ignored) { ignored.printStackTrace(); } - try - { - if (context != null) - { + try { + if (context != null) { EmbeddedJMS jms = (EmbeddedJMS) context.getBean("EmbeddedJms"); jms.stop(); } } - catch (Throwable ignored) - { + catch (Throwable ignored) { ignored.printStackTrace(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ssl/CoreClientOverOneWaySSLTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ssl/CoreClientOverOneWaySSLTest.java index 7b404436c4..70b2d7cc75 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ssl/CoreClientOverOneWaySSLTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ssl/CoreClientOverOneWaySSLTest.java @@ -50,19 +50,14 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) -public class CoreClientOverOneWaySSLTest extends ActiveMQTestBase -{ +public class CoreClientOverOneWaySSLTest extends ActiveMQTestBase { + @Parameterized.Parameters(name = "storeType={0}") - public static Collection getParameters() - { - return Arrays.asList(new Object[][]{ - {"JCEKS"}, - {"JKS"} - }); + public static Collection getParameters() { + return Arrays.asList(new Object[][]{{"JCEKS"}, {"JKS"}}); } - public CoreClientOverOneWaySSLTest(String storeType) - { + public CoreClientOverOneWaySSLTest(String storeType) { this.storeType = storeType; SERVER_SIDE_KEYSTORE = "server-side-keystore." + storeType.toLowerCase(); CLIENT_SIDE_TRUSTSTORE = "client-side-truststore." + storeType.toLowerCase(); @@ -70,7 +65,8 @@ public class CoreClientOverOneWaySSLTest extends ActiveMQTestBase public static final SimpleString QUEUE = new SimpleString("QueueOverSSL"); - /** These artifacts are required for testing 1-way SSL + /** + * These artifacts are required for testing 1-way SSL * * Commands to create the JKS artifacts: * keytool -genkey -keystore server-side-keystore.jks -storepass secureexample -keypass secureexample -dname "CN=ActiveMQ Artemis, OU=ActiveMQ Artemis, O=ActiveMQ Artemis, L=ActiveMQ Artemis, S=ActiveMQ Artemis, C=AMQ" @@ -92,8 +88,7 @@ public class CoreClientOverOneWaySSLTest extends ActiveMQTestBase private TransportConfiguration tc; @Test - public void testOneWaySSL() throws Exception - { + public void testOneWaySSL() throws Exception { createCustomSslServer(); String text = RandomUtil.randomString(); @@ -120,8 +115,7 @@ public class CoreClientOverOneWaySSLTest extends ActiveMQTestBase } @Test - public void testOneWaySSLWithBadClientCipherSuite() throws Exception - { + public void testOneWaySSLWithBadClientCipherSuite() throws Exception { createCustomSslServer(); tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true); tc.getParams().put(TransportConstants.TRUSTSTORE_PROVIDER_PROP_NAME, storeType); @@ -130,20 +124,17 @@ public class CoreClientOverOneWaySSLTest extends ActiveMQTestBase tc.getParams().put(TransportConstants.ENABLED_CIPHER_SUITES_PROP_NAME, "myBadCipherSuite"); ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc)); - try - { + try { createSessionFactory(locator); Assert.fail(); } - catch (ActiveMQNotConnectedException e) - { + catch (ActiveMQNotConnectedException e) { Assert.assertTrue(true); } } @Test - public void testOneWaySSLWithBadServerCipherSuite() throws Exception - { + public void testOneWaySSLWithBadServerCipherSuite() throws Exception { createCustomSslServer("myBadCipherSuite", null); tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true); tc.getParams().put(TransportConstants.TRUSTSTORE_PROVIDER_PROP_NAME, storeType); @@ -151,20 +142,17 @@ public class CoreClientOverOneWaySSLTest extends ActiveMQTestBase tc.getParams().put(TransportConstants.TRUSTSTORE_PASSWORD_PROP_NAME, PASSWORD); ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc)); - try - { + try { createSessionFactory(locator); Assert.fail(); } - catch (ActiveMQNotConnectedException e) - { + catch (ActiveMQNotConnectedException e) { Assert.assertTrue(true); } } @Test - public void testOneWaySSLWithMismatchedCipherSuites() throws Exception - { + public void testOneWaySSLWithMismatchedCipherSuites() throws Exception { createCustomSslServer(getEnabledCipherSuites()[0], "TLSv1.2"); tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true); tc.getParams().put(TransportConstants.TRUSTSTORE_PROVIDER_PROP_NAME, storeType); @@ -174,20 +162,17 @@ public class CoreClientOverOneWaySSLTest extends ActiveMQTestBase tc.getParams().put(TransportConstants.ENABLED_PROTOCOLS_PROP_NAME, "TLSv1.2"); ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc)); - try - { + try { createSessionFactory(locator); Assert.fail(); } - catch (ActiveMQNotConnectedException e) - { + catch (ActiveMQNotConnectedException e) { Assert.assertTrue(true); } } @Test - public void testOneWaySSLWithBadClientProtocol() throws Exception - { + public void testOneWaySSLWithBadClientProtocol() throws Exception { createCustomSslServer(); tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true); tc.getParams().put(TransportConstants.TRUSTSTORE_PROVIDER_PROP_NAME, storeType); @@ -196,20 +181,17 @@ public class CoreClientOverOneWaySSLTest extends ActiveMQTestBase tc.getParams().put(TransportConstants.ENABLED_PROTOCOLS_PROP_NAME, "myBadProtocol"); ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc)); - try - { + try { createSessionFactory(locator); Assert.fail(); } - catch (ActiveMQNotConnectedException e) - { + catch (ActiveMQNotConnectedException e) { Assert.assertTrue(true); } } @Test - public void testOneWaySSLWithBadServerProtocol() throws Exception - { + public void testOneWaySSLWithBadServerProtocol() throws Exception { createCustomSslServer(null, "myBadProtocol"); tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true); tc.getParams().put(TransportConstants.TRUSTSTORE_PROVIDER_PROP_NAME, storeType); @@ -217,20 +199,17 @@ public class CoreClientOverOneWaySSLTest extends ActiveMQTestBase tc.getParams().put(TransportConstants.TRUSTSTORE_PASSWORD_PROP_NAME, PASSWORD); ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc)); - try - { + try { createSessionFactory(locator); Assert.fail(); } - catch (ActiveMQNotConnectedException e) - { + catch (ActiveMQNotConnectedException e) { Assert.assertTrue(true); } } @Test - public void testOneWaySSLWithMismatchedProtocols() throws Exception - { + public void testOneWaySSLWithMismatchedProtocols() throws Exception { createCustomSslServer(null, "TLSv1"); tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true); tc.getParams().put(TransportConstants.TRUSTSTORE_PROVIDER_PROP_NAME, storeType); @@ -239,21 +218,18 @@ public class CoreClientOverOneWaySSLTest extends ActiveMQTestBase tc.getParams().put(TransportConstants.ENABLED_PROTOCOLS_PROP_NAME, "TLSv1.2"); ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc)); - try - { + try { createSessionFactory(locator); Assert.fail(); } - catch (ActiveMQNotConnectedException e) - { + catch (ActiveMQNotConnectedException e) { Assert.assertTrue(true); } } @Test // http://www.oracle.com/technetwork/topics/security/poodlecve-2014-3566-2339408.html - public void testPOODLE() throws Exception - { + public void testPOODLE() throws Exception { createCustomSslServer(null, "SSLv3"); tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true); tc.getParams().put(TransportConstants.TRUSTSTORE_PROVIDER_PROP_NAME, storeType); @@ -262,20 +238,17 @@ public class CoreClientOverOneWaySSLTest extends ActiveMQTestBase tc.getParams().put(TransportConstants.ENABLED_PROTOCOLS_PROP_NAME, "SSLv3"); ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc)); - try - { + try { createSessionFactory(locator); Assert.fail(); } - catch (ActiveMQNotConnectedException e) - { + catch (ActiveMQNotConnectedException e) { Assert.assertTrue(true); } } @Test - public void testOneWaySSLWithGoodClientCipherSuite() throws Exception - { + public void testOneWaySSLWithGoodClientCipherSuite() throws Exception { createCustomSslServer(); String text = RandomUtil.randomString(); @@ -288,12 +261,10 @@ public class CoreClientOverOneWaySSLTest extends ActiveMQTestBase ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc)); ClientSessionFactory sf = null; - try - { + try { sf = createSessionFactory(locator); } - catch (ActiveMQNotConnectedException e) - { + catch (ActiveMQNotConnectedException e) { Assert.fail(); } @@ -313,8 +284,7 @@ public class CoreClientOverOneWaySSLTest extends ActiveMQTestBase } @Test - public void testOneWaySSLWithGoodServerCipherSuite() throws Exception - { + public void testOneWaySSLWithGoodServerCipherSuite() throws Exception { createCustomSslServer(getSuitableCipherSuite(), null); String text = RandomUtil.randomString(); @@ -326,12 +296,10 @@ public class CoreClientOverOneWaySSLTest extends ActiveMQTestBase ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc)); ClientSessionFactory sf = null; - try - { + try { sf = createSessionFactory(locator); } - catch (ActiveMQNotConnectedException e) - { + catch (ActiveMQNotConnectedException e) { Assert.fail(); } @@ -351,8 +319,7 @@ public class CoreClientOverOneWaySSLTest extends ActiveMQTestBase } @Test - public void testOneWaySSLWithGoodClientProtocol() throws Exception - { + public void testOneWaySSLWithGoodClientProtocol() throws Exception { createCustomSslServer(); String text = RandomUtil.randomString(); @@ -364,13 +331,11 @@ public class CoreClientOverOneWaySSLTest extends ActiveMQTestBase ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc)); ClientSessionFactory sf = null; - try - { + try { sf = createSessionFactory(locator); Assert.assertTrue(true); } - catch (ActiveMQNotConnectedException e) - { + catch (ActiveMQNotConnectedException e) { Assert.fail(); } @@ -390,8 +355,7 @@ public class CoreClientOverOneWaySSLTest extends ActiveMQTestBase } @Test - public void testOneWaySSLWithGoodServerProtocol() throws Exception - { + public void testOneWaySSLWithGoodServerProtocol() throws Exception { createCustomSslServer(null, "TLSv1"); String text = RandomUtil.randomString(); @@ -402,13 +366,11 @@ public class CoreClientOverOneWaySSLTest extends ActiveMQTestBase ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc)); ClientSessionFactory sf = null; - try - { + try { sf = createSessionFactory(locator); Assert.assertTrue(true); } - catch (ActiveMQNotConnectedException e) - { + catch (ActiveMQNotConnectedException e) { Assert.fail(); } @@ -427,8 +389,7 @@ public class CoreClientOverOneWaySSLTest extends ActiveMQTestBase Assert.assertEquals(text, m.getBodyBuffer().readString()); } - public String getSuitableCipherSuite() throws Exception - { + public String getSuitableCipherSuite() throws Exception { String result = ""; String[] suites = getEnabledCipherSuites(); @@ -446,11 +407,9 @@ public class CoreClientOverOneWaySSLTest extends ActiveMQTestBase * TLS_DHE_DSS_WITH_AES_128_CBC_SHA * SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA */ - for (int i = 0; i < suites.length; i++) - { + for (int i = 0; i < suites.length; i++) { String suite = suites[i]; - if ((storeType.equals("JCEKS") && suite.contains("DHE_DSS_WITH")) || (!storeType.equals("JCEKS") && !suite.contains("ECDSA") && suite.contains("RSA"))) - { + if ((storeType.equals("JCEKS") && suite.contains("DHE_DSS_WITH")) || (!storeType.equals("JCEKS") && !suite.contains("ECDSA") && suite.contains("RSA"))) { result = suite; break; } @@ -460,38 +419,32 @@ public class CoreClientOverOneWaySSLTest extends ActiveMQTestBase return result; } - public String[] getEnabledCipherSuites() throws Exception - { + public String[] getEnabledCipherSuites() throws Exception { SSLContext context = SSLSupport.createContext(storeType, SERVER_SIDE_KEYSTORE, PASSWORD, storeType, CLIENT_SIDE_TRUSTSTORE, PASSWORD); SSLEngine engine = context.createSSLEngine(); return engine.getEnabledCipherSuites(); } @Test - public void testOneWaySSLWithoutTrustStore() throws Exception - { + public void testOneWaySSLWithoutTrustStore() throws Exception { createCustomSslServer(); tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true); ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc)); - try - { + try { createSessionFactory(locator); Assert.fail(); } - catch (ActiveMQNotConnectedException se) - { + catch (ActiveMQNotConnectedException se) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } } @Test - public void testOneWaySSLWithIncorrectTrustStorePassword() throws Exception - { + public void testOneWaySSLWithIncorrectTrustStorePassword() throws Exception { createCustomSslServer(); tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true); tc.getParams().put(TransportConstants.TRUSTSTORE_PROVIDER_PROP_NAME, storeType); @@ -499,69 +452,56 @@ public class CoreClientOverOneWaySSLTest extends ActiveMQTestBase tc.getParams().put(TransportConstants.TRUSTSTORE_PASSWORD_PROP_NAME, "invalid password"); ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc)); - try - { + try { ClientSessionFactory sf = createSessionFactory(locator); Assert.fail(); } - catch (ActiveMQNotConnectedException se) - { + catch (ActiveMQNotConnectedException se) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } } @Test - public void testOneWaySSLWithIncorrectTrustStorePath() throws Exception - { + public void testOneWaySSLWithIncorrectTrustStorePath() throws Exception { createCustomSslServer(); tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true); tc.getParams().put(TransportConstants.TRUSTSTORE_PATH_PROP_NAME, "incorrect path"); tc.getParams().put(TransportConstants.TRUSTSTORE_PASSWORD_PROP_NAME, PASSWORD); ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc)); - try - { + try { ClientSessionFactory sf = createSessionFactory(locator); Assert.fail(); } - catch (ActiveMQNotConnectedException se) - { + catch (ActiveMQNotConnectedException se) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } } // see https://jira.jboss.org/jira/browse/HORNETQ-234 @Test - public void testPlainConnectionToSSLEndpoint() throws Exception - { + public void testPlainConnectionToSSLEndpoint() throws Exception { createCustomSslServer(); tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, false); - ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc)) - .setCallTimeout(2000); - try - { + ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc)).setCallTimeout(2000); + try { createSessionFactory(locator); fail("expecting exception"); } - catch (ActiveMQNotConnectedException se) - { + catch (ActiveMQNotConnectedException se) { //ok } - catch (ActiveMQConnectionTimedOutException ctoe) - { + catch (ActiveMQConnectionTimedOutException ctoe) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } } @@ -570,36 +510,30 @@ public class CoreClientOverOneWaySSLTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); } - private void createCustomSslServer() throws Exception - { + private void createCustomSslServer() throws Exception { createCustomSslServer(null, null); } - private void createCustomSslServer(String cipherSuites, String protocols) throws Exception - { + private void createCustomSslServer(String cipherSuites, String protocols) throws Exception { Map params = new HashMap(); params.put(TransportConstants.SSL_ENABLED_PROP_NAME, true); params.put(TransportConstants.KEYSTORE_PROVIDER_PROP_NAME, storeType); params.put(TransportConstants.KEYSTORE_PATH_PROP_NAME, SERVER_SIDE_KEYSTORE); params.put(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, PASSWORD); - if (cipherSuites != null) - { + if (cipherSuites != null) { params.put(TransportConstants.ENABLED_CIPHER_SUITES_PROP_NAME, cipherSuites); } - if (protocols != null) - { + if (protocols != null) { params.put(TransportConstants.ENABLED_PROTOCOLS_PROP_NAME, protocols); } - ConfigurationImpl config = createBasicConfig() - .addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params)); + ConfigurationImpl config = createBasicConfig().addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params)); server = createServer(false, config); server.start(); waitForServerToStart(server); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ssl/CoreClientOverTwoWaySSLTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ssl/CoreClientOverTwoWaySSLTest.java index d478c88323..0704b6c6cf 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ssl/CoreClientOverTwoWaySSLTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ssl/CoreClientOverTwoWaySSLTest.java @@ -52,19 +52,14 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) -public class CoreClientOverTwoWaySSLTest extends ActiveMQTestBase -{ +public class CoreClientOverTwoWaySSLTest extends ActiveMQTestBase { + @Parameterized.Parameters(name = "storeType={0}") - public static Collection getParameters() - { - return Arrays.asList(new Object[][]{ - {"JCEKS"}, - {"JKS"} - }); + public static Collection getParameters() { + return Arrays.asList(new Object[][]{{"JCEKS"}, {"JKS"}}); } - public CoreClientOverTwoWaySSLTest(String storeType) - { + public CoreClientOverTwoWaySSLTest(String storeType) { this.storeType = storeType; SERVER_SIDE_KEYSTORE = "server-side-keystore." + storeType.toLowerCase(); SERVER_SIDE_TRUSTSTORE = "server-side-truststore." + storeType.toLowerCase(); @@ -74,7 +69,8 @@ public class CoreClientOverTwoWaySSLTest extends ActiveMQTestBase public static final SimpleString QUEUE = new SimpleString("QueueOverSSL"); - /** These artifacts are required for testing 2-way SSL + /** + * These artifacts are required for testing 2-way SSL * * Commands to create the JKS artifacts: * keytool -genkey -keystore client-side-keystore.jks -storepass secureexample -keypass secureexample -dname "CN=ActiveMQ Artemis, OU=ActiveMQ Artemis, O=ActiveMQ Artemis, L=ActiveMQ Artemis, S=ActiveMQ Artemis, C=AMQ" @@ -98,16 +94,12 @@ public class CoreClientOverTwoWaySSLTest extends ActiveMQTestBase private TransportConfiguration tc; - private class MyInterceptor implements Interceptor - { - public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException - { - if (packet.getType() == PacketImpl.SESS_SEND) - { - try - { - if (connection.getTransportConnection() instanceof NettyConnection) - { + private class MyInterceptor implements Interceptor { + + public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { + if (packet.getType() == PacketImpl.SESS_SEND) { + try { + if (connection.getTransportConnection() instanceof NettyConnection) { System.out.println("Passed through...."); NettyConnection nettyConnection = (NettyConnection) connection.getTransportConnection(); SslHandler sslHandler = (SslHandler) nettyConnection.getChannel().pipeline().get("ssl"); @@ -116,8 +108,7 @@ public class CoreClientOverTwoWaySSLTest extends ActiveMQTestBase Assert.assertNotNull(sslHandler.engine().getSession().getPeerCertificateChain()); } } - catch (SSLPeerUnverifiedException e) - { + catch (SSLPeerUnverifiedException e) { Assert.fail(e.getMessage()); } } @@ -126,8 +117,7 @@ public class CoreClientOverTwoWaySSLTest extends ActiveMQTestBase } @Test - public void testTwoWaySSL() throws Exception - { + public void testTwoWaySSL() throws Exception { String text = RandomUtil.randomString(); tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true); @@ -158,25 +148,21 @@ public class CoreClientOverTwoWaySSLTest extends ActiveMQTestBase } @Test - public void testTwoWaySSLWithoutClientKeyStore() throws Exception - { + public void testTwoWaySSLWithoutClientKeyStore() throws Exception { tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true); tc.getParams().put(TransportConstants.TRUSTSTORE_PROVIDER_PROP_NAME, storeType); tc.getParams().put(TransportConstants.TRUSTSTORE_PATH_PROP_NAME, CLIENT_SIDE_TRUSTSTORE); tc.getParams().put(TransportConstants.TRUSTSTORE_PASSWORD_PROP_NAME, PASSWORD); ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc)); - try - { + try { createSessionFactory(locator); Assert.fail(); } - catch (ActiveMQNotConnectedException se) - { + catch (ActiveMQNotConnectedException se) { //ok } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { Assert.fail("Invalid Exception type:" + e.getType()); } } @@ -185,8 +171,7 @@ public class CoreClientOverTwoWaySSLTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); Map params = new HashMap(); params.put(TransportConstants.SSL_ENABLED_PROP_NAME, true); @@ -197,8 +182,7 @@ public class CoreClientOverTwoWaySSLTest extends ActiveMQTestBase params.put(TransportConstants.TRUSTSTORE_PROVIDER_PROP_NAME, storeType); params.put(TransportConstants.KEYSTORE_PROVIDER_PROP_NAME, storeType); params.put(TransportConstants.NEED_CLIENT_AUTH_PROP_NAME, true); - ConfigurationImpl config = createBasicConfig() - .addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params)); + ConfigurationImpl config = createBasicConfig().addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params)); server = createServer(false, config); server.start(); waitForServerToStart(server); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/ConcurrentStompTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/ConcurrentStompTest.java index 6b1f6605a5..2379caf1b1 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/ConcurrentStompTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/ConcurrentStompTest.java @@ -29,8 +29,8 @@ import org.apache.activemq.artemis.core.protocol.stomp.Stomp; import org.junit.Assert; import org.junit.Test; -public class ConcurrentStompTest extends StompTestBase -{ +public class ConcurrentStompTest extends StompTestBase { + private Socket stompSocket_2; private ByteArrayOutputStream inputBuffer_2; @@ -39,10 +39,8 @@ public class ConcurrentStompTest extends StompTestBase * Send messages on 1 socket and receives them concurrently on another socket. */ @Test - public void testSendManyMessages() throws Exception - { - try - { + public void testSendManyMessages() throws Exception { + try { String connect = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(connect); @@ -59,32 +57,26 @@ public class ConcurrentStompTest extends StompTestBase final int count = 1000; final CountDownLatch latch = new CountDownLatch(count); - String subscribe = - "SUBSCRIBE\n" + - "destination:" + getQueuePrefix() + getQueueName() + "\n" + - "ack:auto\n\n" + - Stomp.NULL; + String subscribe = "SUBSCRIBE\n" + + "destination:" + getQueuePrefix() + getQueueName() + "\n" + + "ack:auto\n\n" + + Stomp.NULL; sendFrame(stompSocket_2, subscribe); Thread.sleep(2000); - new Thread() - { + new Thread() { @Override - public void run() - { + public void run() { int i = 0; - while (true) - { - try - { + while (true) { + try { String frame = receiveFrame(stompSocket_2, inputBuffer_2, 10000); Assert.assertTrue(frame.startsWith("MESSAGE")); Assert.assertTrue(frame.indexOf("destination:") > 0); System.out.println("<<< " + i++); latch.countDown(); } - catch (Exception e) - { + catch (Exception e) { break; } } @@ -92,8 +84,7 @@ public class ConcurrentStompTest extends StompTestBase }.start(); String send = "SEND\n" + "destination:" + getQueuePrefix() + getQueueName() + "\n"; - for (int i = 1; i <= count; i++) - { + for (int i = 1; i <= count; i++) { // Thread.sleep(1); System.out.println(">>> " + i); sendFrame(send + "count:" + i + "\n\n" + Stomp.NULL); @@ -102,45 +93,36 @@ public class ConcurrentStompTest extends StompTestBase assertTrue(latch.await(60, TimeUnit.SECONDS)); } - finally - { + finally { stompSocket_2.close(); inputBuffer_2.close(); } - } // Implementation methods // ------------------------------------------------------------------------- - public void sendFrame(Socket socket, String data) throws Exception - { + public void sendFrame(Socket socket, String data) throws Exception { byte[] bytes = data.getBytes(StandardCharsets.UTF_8); OutputStream outputStream = socket.getOutputStream(); - for (byte b : bytes) - { + for (byte b : bytes) { outputStream.write(b); } outputStream.flush(); } - public String receiveFrame(Socket socket, ByteArrayOutputStream input, long timeOut) throws Exception - { + public String receiveFrame(Socket socket, ByteArrayOutputStream input, long timeOut) throws Exception { socket.setSoTimeout((int) timeOut); InputStream is = socket.getInputStream(); int c = 0; - for (;;) - { + for (;;) { c = is.read(); - if (c < 0) - { + if (c < 0) { throw new IOException("socket closed."); } - else if (c == 0) - { + else if (c == 0) { c = is.read(); - if (c != '\n') - { + if (c != '\n') { byte[] ba = input.toByteArray(); System.out.println(new String(ba, StandardCharsets.UTF_8)); } @@ -149,8 +131,7 @@ public class ConcurrentStompTest extends StompTestBase input.reset(); return new String(ba, StandardCharsets.UTF_8); } - else - { + else { input.write(c); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/ExtraStompTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/ExtraStompTest.java index 725d0b7d92..a52ed03f9f 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/ExtraStompTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/ExtraStompTest.java @@ -57,28 +57,24 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -public class ExtraStompTest extends StompTestBase -{ +public class ExtraStompTest extends StompTestBase { + @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { autoCreateServer = false; super.setUp(); } @Test - public void testConnectionTTL() throws Exception - { - try - { + public void testConnectionTTL() throws Exception { + try { server = createServerWithTTL("2000"); server.start(); setUpAfterServer(); - String connect_frame = "CONNECT\n" + "login: brianm\n" - + "passcode: wombats\n" + "request-id: 1\n" + "\n" + Stomp.NULL; + String connect_frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n" + "request-id: 1\n" + "\n" + Stomp.NULL; sendFrame(connect_frame); String f = receiveFrame(10000); @@ -98,44 +94,37 @@ public class ExtraStompTest extends StompTestBase message = (TextMessage) consumer.receiveNoWait(); Assert.assertNull(message); } - finally - { + finally { cleanUp(); server.stop(); } } @Test - public void testEnableMessageID() throws Exception - { + public void testEnableMessageID() throws Exception { enableMessageIDTest(true); } @Test - public void testDisableMessageID() throws Exception - { + public void testDisableMessageID() throws Exception { enableMessageIDTest(false); } @Test - public void testDefaultEnableMessageID() throws Exception - { + public void testDefaultEnableMessageID() throws Exception { enableMessageIDTest(null); } //stomp sender -> large -> stomp receiver @Test - public void testSendReceiveLargePersistentMessages() throws Exception - { - try - { + public void testSendReceiveLargePersistentMessages() throws Exception { + try { server = createPersistentServerWithStompMinLargeSize(2048); server.start(); setUpAfterServer(); - String frame = "CONNECT\n" + "login: brianm\n" - + "passcode: wombats\n\n" + Stomp.NULL; + String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); frame = receiveFrame(10000); @@ -143,26 +132,21 @@ public class ExtraStompTest extends StompTestBase int count = 10; int szBody = 1024 * 1024; char[] contents = new char[szBody]; - for (int i = 0; i < szBody; i++) - { + for (int i = 0; i < szBody; i++) { contents[i] = 'A'; } String body = new String(contents); - frame = "SEND\n" + "destination:" + getQueuePrefix() + getQueueName() + "\n" - + "persistent:true\n" - + "\n\n" + body + Stomp.NULL; + frame = "SEND\n" + "destination:" + getQueuePrefix() + getQueueName() + "\n" + "persistent:true\n" + "\n\n" + body + Stomp.NULL; - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { sendFrame(frame); } frame = "SUBSCRIBE\n" + "destination:" + getQueuePrefix() + getQueueName() + "\n" + "ack:auto\n\nfff" + Stomp.NULL; sendFrame(frame); - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { frame = receiveFrame(60000); Assert.assertNotNull(frame); System.out.println("part of frame: " + frame.substring(0, 200)); @@ -186,13 +170,11 @@ public class ExtraStompTest extends StompTestBase frame = "DISCONNECT\n" + "\n\n" + Stomp.NULL; sendFrame(frame); } - catch (Exception ex) - { + catch (Exception ex) { ex.printStackTrace(); throw ex; } - finally - { + finally { cleanUp(); server.stop(); } @@ -200,10 +182,8 @@ public class ExtraStompTest extends StompTestBase //core sender -> large -> stomp receiver @Test - public void testReceiveLargePersistentMessagesFromCore() throws Exception - { - try - { + public void testReceiveLargePersistentMessagesFromCore() throws Exception { + try { server = createPersistentServerWithStompMinLargeSize(2048); server.start(); @@ -211,20 +191,17 @@ public class ExtraStompTest extends StompTestBase int msgSize = 3 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; char[] contents = new char[msgSize]; - for (int i = 0; i < msgSize; i++) - { + for (int i = 0; i < msgSize; i++) { contents[i] = 'B'; } String msg = new String(contents); int count = 10; - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { this.sendMessage(msg); } - String frame = "CONNECT\n" + "login: brianm\n" - + "passcode: wombats\n\n" + Stomp.NULL; + String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); frame = receiveFrame(10000); @@ -233,8 +210,7 @@ public class ExtraStompTest extends StompTestBase frame = "SUBSCRIBE\n" + "destination:" + getQueuePrefix() + getQueueName() + "\n" + "ack:auto\n\nfff" + Stomp.NULL; sendFrame(frame); - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { frame = receiveFrame(60000); Assert.assertNotNull(frame); System.out.println("part of frame: " + frame.substring(0, 250)); @@ -258,13 +234,11 @@ public class ExtraStompTest extends StompTestBase frame = "DISCONNECT\n" + "\n\n" + Stomp.NULL; sendFrame(frame); } - catch (Exception ex) - { + catch (Exception ex) { ex.printStackTrace(); throw ex; } - finally - { + finally { cleanUp(); server.stop(); } @@ -272,10 +246,8 @@ public class ExtraStompTest extends StompTestBase //stomp v12 sender -> large -> stomp v12 receiver @Test - public void testSendReceiveLargePersistentMessagesV12() throws Exception - { - try - { + public void testSendReceiveLargePersistentMessagesV12() throws Exception { + try { server = createPersistentServerWithStompMinLargeSize(2048); server.start(); @@ -287,8 +259,7 @@ public class ExtraStompTest extends StompTestBase int count = 10; int szBody = 1024 * 1024; char[] contents = new char[szBody]; - for (int i = 0; i < szBody; i++) - { + for (int i = 0; i < szBody; i++) { contents[i] = 'A'; } String body = new String(contents); @@ -298,8 +269,7 @@ public class ExtraStompTest extends StompTestBase frame.addHeader("persistent", "true"); frame.setBody(body); - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { connV12.sendFrame(frame); } @@ -310,8 +280,7 @@ public class ExtraStompTest extends StompTestBase connV12.sendFrame(subFrame); - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { ClientStompFrame receiveFrame = connV12.receiveFrame(30000); Assert.assertNotNull(receiveFrame); @@ -328,13 +297,11 @@ public class ExtraStompTest extends StompTestBase connV12.disconnect(); } - catch (Exception ex) - { + catch (Exception ex) { ex.printStackTrace(); throw ex; } - finally - { + finally { cleanUp(); server.stop(); } @@ -342,10 +309,8 @@ public class ExtraStompTest extends StompTestBase //core sender -> large -> stomp v12 receiver @Test - public void testReceiveLargePersistentMessagesFromCoreV12() throws Exception - { - try - { + public void testReceiveLargePersistentMessagesFromCoreV12() throws Exception { + try { server = createPersistentServerWithStompMinLargeSize(2048); server.start(); @@ -353,15 +318,13 @@ public class ExtraStompTest extends StompTestBase int msgSize = 3 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; char[] contents = new char[msgSize]; - for (int i = 0; i < msgSize; i++) - { + for (int i = 0; i < msgSize; i++) { contents[i] = 'B'; } String msg = new String(contents); int count = 10; - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { this.sendMessage(msg); } @@ -375,8 +338,7 @@ public class ExtraStompTest extends StompTestBase connV12.sendFrame(subFrame); - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { ClientStompFrame receiveFrame = connV12.receiveFrame(30000); Assert.assertNotNull(receiveFrame); @@ -393,13 +355,11 @@ public class ExtraStompTest extends StompTestBase connV12.disconnect(); } - catch (Exception ex) - { + catch (Exception ex) { ex.printStackTrace(); throw ex; } - finally - { + finally { cleanUp(); server.stop(); } @@ -407,10 +367,8 @@ public class ExtraStompTest extends StompTestBase //core sender -> large (compressed regular) -> stomp v10 receiver @Test - public void testReceiveLargeCompressedToRegularPersistentMessagesFromCore() throws Exception - { - try - { + public void testReceiveLargeCompressedToRegularPersistentMessagesFromCore() throws Exception { + try { server = createPersistentServerWithStompMinLargeSize(2048); server.start(); @@ -425,13 +383,11 @@ public class ExtraStompTest extends StompTestBase String leadingPart = msg.substring(0, 100); int count = 10; - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { this.sendMessage(msg); } - String frame = "CONNECT\n" + "login: brianm\n" - + "passcode: wombats\n\n" + Stomp.NULL; + String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); frame = receiveFrame(10000); @@ -440,8 +396,7 @@ public class ExtraStompTest extends StompTestBase frame = "SUBSCRIBE\n" + "destination:" + getQueuePrefix() + getQueueName() + "\n" + "ack:auto\n\nfff" + Stomp.NULL; sendFrame(frame); - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { frame = receiveFrame(60000); Assert.assertNotNull(frame); System.out.println("part of frame: " + frame.substring(0, 250)); @@ -465,13 +420,11 @@ public class ExtraStompTest extends StompTestBase frame = "DISCONNECT\n" + "\n\n" + Stomp.NULL; sendFrame(frame); } - catch (Exception ex) - { + catch (Exception ex) { ex.printStackTrace(); throw ex; } - finally - { + finally { cleanUp(); server.stop(); } @@ -479,10 +432,8 @@ public class ExtraStompTest extends StompTestBase //core sender -> large (compressed regular) -> stomp v12 receiver @Test - public void testReceiveLargeCompressedToRegularPersistentMessagesFromCoreV12() throws Exception - { - try - { + public void testReceiveLargeCompressedToRegularPersistentMessagesFromCoreV12() throws Exception { + try { server = createPersistentServerWithStompMinLargeSize(2048); server.start(); @@ -495,8 +446,7 @@ public class ExtraStompTest extends StompTestBase String msg = new String(contents); int count = 10; - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { this.sendMessage(msg); } @@ -510,8 +460,7 @@ public class ExtraStompTest extends StompTestBase connV12.sendFrame(subFrame); - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { ClientStompFrame receiveFrame = connV12.receiveFrame(30000); Assert.assertNotNull(receiveFrame); @@ -528,13 +477,11 @@ public class ExtraStompTest extends StompTestBase connV12.disconnect(); } - catch (Exception ex) - { + catch (Exception ex) { ex.printStackTrace(); throw ex; } - finally - { + finally { cleanUp(); server.stop(); } @@ -542,10 +489,8 @@ public class ExtraStompTest extends StompTestBase //core sender -> large (compressed large) -> stomp v12 receiver @Test - public void testReceiveLargeCompressedToLargePersistentMessagesFromCoreV12() throws Exception - { - try - { + public void testReceiveLargeCompressedToLargePersistentMessagesFromCoreV12() throws Exception { + try { server = createPersistentServerWithStompMinLargeSize(2048); server.start(); @@ -559,8 +504,7 @@ public class ExtraStompTest extends StompTestBase String msg = new String(contents); int count = 10; - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { this.sendMessage(msg); } @@ -574,8 +518,7 @@ public class ExtraStompTest extends StompTestBase connV12.sendFrame(subFrame); - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { ClientStompFrame receiveFrame = connV12.receiveFrame(30000); Assert.assertNotNull(receiveFrame); @@ -592,13 +535,11 @@ public class ExtraStompTest extends StompTestBase connV12.disconnect(); } - catch (Exception ex) - { + catch (Exception ex) { ex.printStackTrace(); throw ex; } - finally - { + finally { cleanUp(); server.stop(); } @@ -606,10 +547,8 @@ public class ExtraStompTest extends StompTestBase //core sender -> large (compressed large) -> stomp v10 receiver @Test - public void testReceiveLargeCompressedToLargePersistentMessagesFromCore() throws Exception - { - try - { + public void testReceiveLargeCompressedToLargePersistentMessagesFromCore() throws Exception { + try { server = createPersistentServerWithStompMinLargeSize(2048); server.start(); @@ -625,13 +564,11 @@ public class ExtraStompTest extends StompTestBase String leadingPart = msg.substring(0, 100); int count = 10; - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { this.sendMessage(msg); } - String frame = "CONNECT\n" + "login: brianm\n" - + "passcode: wombats\n\n" + Stomp.NULL; + String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); frame = receiveFrame(10000); @@ -640,8 +577,7 @@ public class ExtraStompTest extends StompTestBase frame = "SUBSCRIBE\n" + "destination:" + getQueuePrefix() + getQueueName() + "\n" + "ack:auto\n\nfff" + Stomp.NULL; sendFrame(frame); - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { frame = receiveFrame(60000); Assert.assertNotNull(frame); System.out.println("part of frame: " + frame.substring(0, 250)); @@ -665,20 +601,17 @@ public class ExtraStompTest extends StompTestBase frame = "DISCONNECT\n" + "\n\n" + Stomp.NULL; sendFrame(frame); } - catch (Exception ex) - { + catch (Exception ex) { ex.printStackTrace(); throw ex; } - finally - { + finally { cleanUp(); server.stop(); } } - protected JMSServerManager createPersistentServerWithStompMinLargeSize(int sz) throws Exception - { + protected JMSServerManager createPersistentServerWithStompMinLargeSize(int sz) throws Exception { Map params = new HashMap(); params.put(TransportConstants.PROTOCOLS_PROP_NAME, StompProtocolManagerFactory.STOMP_PROTOCOL_NAME); params.put(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_STOMP_PORT); @@ -686,48 +619,36 @@ public class ExtraStompTest extends StompTestBase params.put(TransportConstants.STOMP_MIN_LARGE_MESSAGE_SIZE, sz); TransportConfiguration stompTransport = new TransportConfiguration(NettyAcceptorFactory.class.getName(), params); - Configuration config = createBasicConfig() - .setPersistenceEnabled(true) - .addAcceptorConfiguration(stompTransport) - .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())); + Configuration config = createBasicConfig().setPersistenceEnabled(true).addAcceptorConfiguration(stompTransport).addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())); ActiveMQServer activeMQServer = addServer(ActiveMQServers.newActiveMQServer(config, defUser, defPass)); JMSConfiguration jmsConfig = new JMSConfigurationImpl(); - jmsConfig.getQueueConfigurations().add(new JMSQueueConfigurationImpl() - .setName(getQueueName()) - .setBindings(getQueueName())); - jmsConfig.getTopicConfigurations().add(new TopicConfigurationImpl() - .setName(getTopicName()) - .setBindings(getTopicName())); + jmsConfig.getQueueConfigurations().add(new JMSQueueConfigurationImpl().setName(getQueueName()).setBindings(getQueueName())); + jmsConfig.getTopicConfigurations().add(new TopicConfigurationImpl().setName(getTopicName()).setBindings(getTopicName())); server = new JMSServerManagerImpl(activeMQServer, jmsConfig); server.setRegistry(new JndiBindingRegistry((new InVMNamingContext()))); return server; } - private void enableMessageIDTest(Boolean enable) throws Exception - { - try - { + private void enableMessageIDTest(Boolean enable) throws Exception { + try { server = createServerWithExtraStompOptions(null, enable); server.start(); setUpAfterServer(); - String connect_frame = "CONNECT\n" + "login: brianm\n" - + "passcode: wombats\n" + "request-id: 1\n" + "\n" + Stomp.NULL; + String connect_frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n" + "request-id: 1\n" + "\n" + Stomp.NULL; sendFrame(connect_frame); String f = receiveFrame(10000); Assert.assertTrue(f.startsWith("CONNECTED")); Assert.assertTrue(f.indexOf("response-id:1") >= 0); - String frame = "SEND\n" + "destination:" + getQueuePrefix() - + getQueueName() + "\n\n" + "Hello World 1" + Stomp.NULL; + String frame = "SEND\n" + "destination:" + getQueuePrefix() + getQueueName() + "\n\n" + "Hello World 1" + Stomp.NULL; sendFrame(frame); - frame = "SEND\n" + "destination:" + getQueuePrefix() + getQueueName() - + "\n\n" + "Hello World 2" + Stomp.NULL; + frame = "SEND\n" + "destination:" + getQueuePrefix() + getQueueName() + "\n\n" + "Hello World 2" + Stomp.NULL; sendFrame(frame); @@ -735,17 +656,14 @@ public class ExtraStompTest extends StompTestBase Enumeration enu = browser.getEnumeration(); - while (enu.hasMoreElements()) - { + while (enu.hasMoreElements()) { Message msg = (Message) enu.nextElement(); String msgId = msg.getStringProperty("amqMessageId"); - if (enable != null && enable.booleanValue()) - { + if (enable != null && enable.booleanValue()) { assertNotNull(msgId); assertTrue(msgId.indexOf("STOMP") == 0); } - else - { + else { assertNull(msgId); } } @@ -763,92 +681,72 @@ public class ExtraStompTest extends StompTestBase message = (TextMessage) consumer.receive(2000); Assert.assertNull(message); } - finally - { + finally { cleanUp(); server.stop(); } } - protected JMSServerManager createServerWithTTL(String ttl) throws Exception - { + protected JMSServerManager createServerWithTTL(String ttl) throws Exception { return createServerWithExtraStompOptions(ttl, null); } - protected JMSServerManager createServerWithExtraStompOptions(String ttl, Boolean enableMessageID) throws Exception - { + protected JMSServerManager createServerWithExtraStompOptions(String ttl, Boolean enableMessageID) throws Exception { Map params = new HashMap(); params.put(TransportConstants.PROTOCOLS_PROP_NAME, StompProtocolManagerFactory.STOMP_PROTOCOL_NAME); params.put(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_STOMP_PORT); - if (ttl != null) - { + if (ttl != null) { params.put(TransportConstants.CONNECTION_TTL, ttl); } - if (enableMessageID != null) - { + if (enableMessageID != null) { params.put(TransportConstants.STOMP_ENABLE_MESSAGE_ID, enableMessageID); } params.put(TransportConstants.STOMP_CONSUMERS_CREDIT, "-1"); TransportConfiguration stompTransport = new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params); - Configuration config = createBasicConfig() - .setPersistenceEnabled(false) - .addAcceptorConfiguration(stompTransport) - .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY)); + Configuration config = createBasicConfig().setPersistenceEnabled(false).addAcceptorConfiguration(stompTransport).addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY)); ActiveMQServer activeMQServer = addServer(ActiveMQServers.newActiveMQServer(config, defUser, defPass)); JMSConfiguration jmsConfig = new JMSConfigurationImpl(); - jmsConfig.getQueueConfigurations().add(new JMSQueueConfigurationImpl() - .setName(getQueueName()) - .setDurable(false) - .setBindings(getQueueName())); - jmsConfig.getTopicConfigurations().add(new TopicConfigurationImpl() - .setName(getTopicName()) - .setBindings(getTopicName())); + jmsConfig.getQueueConfigurations().add(new JMSQueueConfigurationImpl().setName(getQueueName()).setDurable(false).setBindings(getQueueName())); + jmsConfig.getTopicConfigurations().add(new TopicConfigurationImpl().setName(getTopicName()).setBindings(getTopicName())); server = new JMSServerManagerImpl(activeMQServer, jmsConfig); server.setRegistry(new JndiBindingRegistry(new InVMNamingContext())); return server; } + public static class MyCoreInterceptor implements Interceptor { - public static class MyCoreInterceptor implements Interceptor - { static List incomingInterceptedFrames = new ArrayList(); @Override - public boolean intercept(Packet packet, RemotingConnection connection) - { + public boolean intercept(Packet packet, RemotingConnection connection) { incomingInterceptedFrames.add(packet); return true; } } + public static class MyIncomingStompFrameInterceptor implements StompFrameInterceptor { - public static class MyIncomingStompFrameInterceptor implements StompFrameInterceptor - { static List incomingInterceptedFrames = new ArrayList(); @Override - public boolean intercept(StompFrame stompFrame, RemotingConnection connection) - { + public boolean intercept(StompFrame stompFrame, RemotingConnection connection) { incomingInterceptedFrames.add(stompFrame); stompFrame.addHeader("incomingInterceptedProp", "incomingInterceptedVal"); return true; } } - - public static class MyOutgoingStompFrameInterceptor implements StompFrameInterceptor - { + public static class MyOutgoingStompFrameInterceptor implements StompFrameInterceptor { static List outgoingInterceptedFrames = new ArrayList(); @Override - public boolean intercept(StompFrame stompFrame, RemotingConnection connection) - { + public boolean intercept(StompFrame stompFrame, RemotingConnection connection) { outgoingInterceptedFrames.add(stompFrame); stompFrame.addHeader("outgoingInterceptedProp", "outgoingInterceptedVal"); return true; @@ -856,12 +754,10 @@ public class ExtraStompTest extends StompTestBase } @Test - public void stompFrameInterceptor() throws Exception - { + public void stompFrameInterceptor() throws Exception { MyIncomingStompFrameInterceptor.incomingInterceptedFrames.clear(); MyOutgoingStompFrameInterceptor.outgoingInterceptedFrames.clear(); - try - { + try { List incomingInterceptorList = new ArrayList(); incomingInterceptorList.add("org.apache.activemq.artemis.tests.integration.stomp.ExtraStompTest$MyIncomingStompFrameInterceptor"); incomingInterceptorList.add("org.apache.activemq.artemis.tests.integration.stomp.ExtraStompTest$MyCoreInterceptor"); @@ -907,8 +803,7 @@ public class ExtraStompTest extends StompTestBase sendFrame(frame); } - finally - { + finally { cleanUp(); server.stop(); } @@ -929,22 +824,19 @@ public class ExtraStompTest extends StompTestBase // Things are async, giving some time to things arrive before we actually assert while (MyIncomingStompFrameInterceptor.incomingInterceptedFrames.size() < 4 && MyOutgoingStompFrameInterceptor.outgoingInterceptedFrames.size() < 3 && - timeout > System.currentTimeMillis()) - { + timeout > System.currentTimeMillis()) { Thread.sleep(10); } Assert.assertEquals(4, MyIncomingStompFrameInterceptor.incomingInterceptedFrames.size()); Assert.assertEquals(3, MyOutgoingStompFrameInterceptor.outgoingInterceptedFrames.size()); - for (int i = 0; i < MyIncomingStompFrameInterceptor.incomingInterceptedFrames.size(); i++) - { + for (int i = 0; i < MyIncomingStompFrameInterceptor.incomingInterceptedFrames.size(); i++) { Assert.assertEquals(incomingCommands.get(i), MyIncomingStompFrameInterceptor.incomingInterceptedFrames.get(i).getCommand()); Assert.assertEquals("incomingInterceptedVal", MyIncomingStompFrameInterceptor.incomingInterceptedFrames.get(i).getHeader("incomingInterceptedProp")); } - for (int i = 0; i < MyOutgoingStompFrameInterceptor.outgoingInterceptedFrames.size(); i++) - { + for (int i = 0; i < MyOutgoingStompFrameInterceptor.outgoingInterceptedFrames.size(); i++) { Assert.assertEquals(outgoingCommands.get(i), MyOutgoingStompFrameInterceptor.outgoingInterceptedFrames.get(i).getCommand()); } @@ -952,8 +844,8 @@ public class ExtraStompTest extends StompTestBase Assert.assertEquals("outgoingInterceptedVal", MyOutgoingStompFrameInterceptor.outgoingInterceptedFrames.get(2).getHeader("outgoingInterceptedProp")); } - protected JMSServerManager createServerWithStompInterceptor(List stompIncomingInterceptor, List stompOutgoingInterceptor) throws Exception - { + protected JMSServerManager createServerWithStompInterceptor(List stompIncomingInterceptor, + List stompOutgoingInterceptor) throws Exception { Map params = new HashMap(); params.put(TransportConstants.PROTOCOLS_PROP_NAME, StompProtocolManagerFactory.STOMP_PROTOCOL_NAME); @@ -961,23 +853,13 @@ public class ExtraStompTest extends StompTestBase params.put(TransportConstants.STOMP_CONSUMERS_CREDIT, "-1"); TransportConfiguration stompTransport = new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params); - Configuration config = createBasicConfig() - .setPersistenceEnabled(false) - .addAcceptorConfiguration(stompTransport) - .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY)) - .setIncomingInterceptorClassNames(stompIncomingInterceptor) - .setOutgoingInterceptorClassNames(stompOutgoingInterceptor); + Configuration config = createBasicConfig().setPersistenceEnabled(false).addAcceptorConfiguration(stompTransport).addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY)).setIncomingInterceptorClassNames(stompIncomingInterceptor).setOutgoingInterceptorClassNames(stompOutgoingInterceptor); ActiveMQServer hornetQServer = addServer(ActiveMQServers.newActiveMQServer(config, defUser, defPass)); JMSConfiguration jmsConfig = new JMSConfigurationImpl(); - jmsConfig.getQueueConfigurations().add(new JMSQueueConfigurationImpl() - .setName(getQueueName()) - .setDurable(false) - .setBindings(getQueueName())); - jmsConfig.getTopicConfigurations().add(new TopicConfigurationImpl() - .setName(getTopicName()) - .setBindings(getTopicName())); + jmsConfig.getQueueConfigurations().add(new JMSQueueConfigurationImpl().setName(getQueueName()).setDurable(false).setBindings(getQueueName())); + jmsConfig.getTopicConfigurations().add(new TopicConfigurationImpl().setName(getTopicName()).setBindings(getTopicName())); server = new JMSServerManagerImpl(hornetQServer, jmsConfig); server.setRegistry(new JndiBindingRegistry(new InVMNamingContext())); return server; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/StompConnectionCleanupTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/StompConnectionCleanupTest.java index 12075f8ee8..b6b44f2ce2 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/StompConnectionCleanupTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/StompConnectionCleanupTest.java @@ -24,13 +24,12 @@ import javax.jms.MessageConsumer; import org.apache.activemq.artemis.core.protocol.stomp.Stomp; import org.apache.activemq.artemis.jms.server.JMSServerManager; -public class StompConnectionCleanupTest extends StompTestBase -{ +public class StompConnectionCleanupTest extends StompTestBase { + private static final long CONNECTION_TTL = 2000; @Test - public void testConnectionCleanup() throws Exception - { + public void testConnectionCleanup() throws Exception { String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); frame = receiveFrame(10000); @@ -56,31 +55,27 @@ public class StompConnectionCleanupTest extends StompTestBase long start = System.currentTimeMillis(); - while (true) - { + while (true) { int connCount = server.getActiveMQServer().getRemotingService().getConnections().size(); int sessionCount = server.getActiveMQServer().getSessions().size(); // All connections and sessions should be timed out including STOMP + JMS connection - if (connCount == 0 && sessionCount == 0) - { + if (connCount == 0 && sessionCount == 0) { break; } Thread.sleep(10); - if (System.currentTimeMillis() - start > 10000) - { + if (System.currentTimeMillis() - start > 10000) { fail("Timed out waiting for connection to be cleared up"); } } } @Test - public void testConnectionNotCleanedUp() throws Exception - { + public void testConnectionNotCleanedUp() throws Exception { String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); frame = receiveFrame(10000); @@ -96,8 +91,7 @@ public class StompConnectionCleanupTest extends StompTestBase long start = System.currentTimeMillis(); //Send msgs for an amount of time > connection_ttl make sure connection is not closed - while (true) - { + while (true) { //Send and receive a msg frame = "SEND\n" + "destination:" + getQueuePrefix() + getQueueName() + "\n\n" + "Hello World" + Stomp.NULL; @@ -108,8 +102,7 @@ public class StompConnectionCleanupTest extends StompTestBase Thread.sleep(100); - if (System.currentTimeMillis() - start > time) - { + if (System.currentTimeMillis() - start > time) { break; } } @@ -117,8 +110,7 @@ public class StompConnectionCleanupTest extends StompTestBase } @Override - protected JMSServerManager createServer() throws Exception - { + protected JMSServerManager createServer() throws Exception { JMSServerManager s = super.createServer(); s.getActiveMQServer().getConfiguration().setConnectionTTLOverride(CONNECTION_TTL); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/StompOverHttpTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/StompOverHttpTest.java index 13bebcbbc2..8e588f9aab 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/StompOverHttpTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/StompOverHttpTest.java @@ -34,12 +34,10 @@ import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; +public class StompOverHttpTest extends StompTest { -public class StompOverHttpTest extends StompTest -{ @Override - protected void addChannelHandlers(SocketChannel ch) - { + protected void addChannelHandlers(SocketChannel ch) { ch.pipeline().addLast(new HttpRequestEncoder()); ch.pipeline().addLast(new HttpResponseDecoder()); ch.pipeline().addLast(new HttpHandler()); @@ -49,37 +47,31 @@ public class StompOverHttpTest extends StompTest } @Override - public String receiveFrame(long timeOut) throws Exception - { + public String receiveFrame(long timeOut) throws Exception { //we are request/response so may need to send an empty request so we get responses piggy backed sendFrame(new byte[]{}); return super.receiveFrame(timeOut); } - class HttpHandler extends ChannelDuplexHandler - { + class HttpHandler extends ChannelDuplexHandler { + @Override - public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception - { - if (msg instanceof DefaultHttpContent) - { - DefaultHttpContent response = (DefaultHttpContent)msg; + public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception { + if (msg instanceof DefaultHttpContent) { + DefaultHttpContent response = (DefaultHttpContent) msg; ctx.fireChannelRead(response.content()); } } @Override - public void write(final ChannelHandlerContext ctx, final Object msg, ChannelPromise promise) throws Exception - { - if (msg instanceof ByteBuf) - { + public void write(final ChannelHandlerContext ctx, final Object msg, ChannelPromise promise) throws Exception { + if (msg instanceof ByteBuf) { ByteBuf buf = (ByteBuf) msg; FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "", buf); httpRequest.headers().add(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(buf.readableBytes())); ctx.write(httpRequest, promise); } - else - { + else { ctx.write(msg, promise); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/StompOverWebsocketTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/StompOverWebsocketTest.java index 25f6a28d99..38e9e69ba8 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/StompOverWebsocketTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/StompOverWebsocketTest.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.artemis.tests.integration.stomp; - import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; @@ -39,15 +38,12 @@ import io.netty.handler.codec.http.websocketx.WebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketVersion; import io.netty.handler.codec.string.StringDecoder; -public class StompOverWebsocketTest extends StompTest -{ - +public class StompOverWebsocketTest extends StompTest { private ChannelPromise handshakeFuture; @Override - protected void addChannelHandlers(SocketChannel ch) throws URISyntaxException - { + protected void addChannelHandlers(SocketChannel ch) throws URISyntaxException { ch.pipeline().addLast("http-codec", new HttpClientCodec()); ch.pipeline().addLast("aggregator", new HttpObjectAggregator(8192)); ch.pipeline().addLast(new WebsocketHandler(WebSocketClientHandshakerFactory.newHandshaker(new URI("ws://localhost:8080/websocket"), WebSocketVersion.V13, null, false, null))); @@ -55,93 +51,75 @@ public class StompOverWebsocketTest extends StompTest ch.pipeline().addLast(new StompClientHandler()); } - @Override - protected void handshake() throws InterruptedException - { + protected void handshake() throws InterruptedException { handshakeFuture.sync(); } - class WebsocketHandler extends ChannelDuplexHandler - { + class WebsocketHandler extends ChannelDuplexHandler { + private WebSocketClientHandshaker handshaker; - public WebsocketHandler(WebSocketClientHandshaker webSocketClientHandshaker) - { + public WebsocketHandler(WebSocketClientHandshaker webSocketClientHandshaker) { this.handshaker = webSocketClientHandshaker; } @Override - public void handlerAdded(ChannelHandlerContext ctx) throws Exception - { + public void handlerAdded(ChannelHandlerContext ctx) throws Exception { handshakeFuture = ctx.newPromise(); } @Override - public void channelActive(ChannelHandlerContext ctx) throws Exception - { + public void channelActive(ChannelHandlerContext ctx) throws Exception { handshaker.handshake(ctx.channel()); } @Override - public void channelInactive(ChannelHandlerContext ctx) throws Exception - { + public void channelInactive(ChannelHandlerContext ctx) throws Exception { System.out.println("WebSocket Client disconnected!"); } @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception - { + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { Channel ch = ctx.channel(); - if (!handshaker.isHandshakeComplete()) - { + if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ch, (FullHttpResponse) msg); System.out.println("WebSocket Client connected!"); handshakeFuture.setSuccess(); return; } - if (msg instanceof FullHttpResponse) - { + if (msg instanceof FullHttpResponse) { FullHttpResponse response = (FullHttpResponse) msg; - throw new Exception("Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ", content=" - + response.content().toString(StandardCharsets.UTF_8) + ')'); + throw new Exception("Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ", content=" + response.content().toString(StandardCharsets.UTF_8) + ')'); } WebSocketFrame frame = (WebSocketFrame) msg; - if (frame instanceof BinaryWebSocketFrame) - { + if (frame instanceof BinaryWebSocketFrame) { BinaryWebSocketFrame dataFrame = (BinaryWebSocketFrame) frame; super.channelRead(ctx, dataFrame.content()); } - else if (frame instanceof PongWebSocketFrame) - { + else if (frame instanceof PongWebSocketFrame) { System.out.println("WebSocket Client received pong"); } - else if (frame instanceof CloseWebSocketFrame) - { + else if (frame instanceof CloseWebSocketFrame) { System.out.println("WebSocket Client received closing"); ch.close(); } } @Override - public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception - { - try - { - if (msg instanceof String) - { + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + try { + if (msg instanceof String) { TextWebSocketFrame frame = new TextWebSocketFrame((String) msg); ctx.write(frame, promise); } - else - { + else { super.write(ctx, msg, promise); } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/StompTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/StompTest.java index 64a63cb476..b6b908a7d3 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/StompTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/StompTest.java @@ -39,13 +39,12 @@ import org.apache.activemq.artemis.tests.util.RandomUtil; import org.junit.Assert; import org.junit.Test; -public class StompTest extends StompTestBase -{ +public class StompTest extends StompTestBase { + private static final transient IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @Test - public void testSendManyMessages() throws Exception - { + public void testSendManyMessages() throws Exception { MessageConsumer consumer = session.createConsumer(queue); String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; @@ -55,18 +54,15 @@ public class StompTest extends StompTestBase Assert.assertTrue(frame.startsWith("CONNECTED")); int count = 1000; final CountDownLatch latch = new CountDownLatch(count); - consumer.setMessageListener(new MessageListener() - { + consumer.setMessageListener(new MessageListener() { - public void onMessage(Message arg0) - { + public void onMessage(Message arg0) { latch.countDown(); } }); frame = "SEND\n" + "destination:" + getQueuePrefix() + getQueueName() + "\n\n" + "Hello World" + Stomp.NULL; - for (int i = 1; i <= count; i++) - { + for (int i = 1; i <= count; i++) { // Thread.sleep(1); // System.out.println(">>> " + i); sendFrame(frame); @@ -76,8 +72,7 @@ public class StompTest extends StompTestBase } @Test - public void testConnect() throws Exception - { + public void testConnect() throws Exception { String connect_frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n" + @@ -92,8 +87,7 @@ public class StompTest extends StompTestBase } @Test - public void testDisconnectAndError() throws Exception - { + public void testDisconnectAndError() throws Exception { String connectFrame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n" + @@ -123,8 +117,7 @@ public class StompTest extends StompTestBase } @Test - public void testSendMessage() throws Exception - { + public void testSendMessage() throws Exception { MessageConsumer consumer = session.createConsumer(queue); @@ -152,8 +145,7 @@ public class StompTest extends StompTestBase } @Test - public void testSendMessageToNonExistentQueue() throws Exception - { + public void testSendMessageToNonExistentQueue() throws Exception { String nonExistentQueue = RandomUtil.randomString(); String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); @@ -191,8 +183,7 @@ public class StompTest extends StompTestBase * This is contrary to STOMP spec but we deal with it so we can work nicely with crappy STOMP clients */ @Test - public void testSendMessageWithLeadingNewLine() throws Exception - { + public void testSendMessageWithLeadingNewLine() throws Exception { MessageConsumer consumer = session.createConsumer(queue); @@ -224,8 +215,7 @@ public class StompTest extends StompTestBase } @Test - public void testSendMessageWithReceipt() throws Exception - { + public void testSendMessageWithReceipt() throws Exception { MessageConsumer consumer = session.createConsumer(queue); String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; @@ -260,8 +250,7 @@ public class StompTest extends StompTestBase } @Test - public void testSendMessageWithContentLength() throws Exception - { + public void testSendMessageWithContentLength() throws Exception { MessageConsumer consumer = session.createConsumer(queue); @@ -297,8 +286,7 @@ public class StompTest extends StompTestBase } @Test - public void testJMSXGroupIdCanBeSet() throws Exception - { + public void testJMSXGroupIdCanBeSet() throws Exception { MessageConsumer consumer = session.createConsumer(queue); @@ -326,8 +314,7 @@ public class StompTest extends StompTestBase } @Test - public void testSendMessageWithCustomHeadersAndSelector() throws Exception - { + public void testSendMessageWithCustomHeadersAndSelector() throws Exception { MessageConsumer consumer = session.createConsumer(queue, "foo = 'abc'"); @@ -356,8 +343,7 @@ public class StompTest extends StompTestBase } @Test - public void testSendMessageWithStandardHeaders() throws Exception - { + public void testSendMessageWithStandardHeaders() throws Exception { MessageConsumer consumer = session.createConsumer(queue); @@ -399,8 +385,7 @@ public class StompTest extends StompTestBase } @Test - public void testSendMessageWithLongHeaders() throws Exception - { + public void testSendMessageWithLongHeaders() throws Exception { MessageConsumer consumer = session.createConsumer(queue); String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; @@ -410,8 +395,7 @@ public class StompTest extends StompTestBase Assert.assertTrue(frame.startsWith("CONNECTED")); StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < 1024; i++) - { + for (int i = 0; i < 1024; i++) { buffer.append("a"); } String longHeader = "longHeader:" + buffer.toString() + "\n"; @@ -446,8 +430,7 @@ public class StompTest extends StompTestBase } @Test - public void testSubscribeWithAutoAck() throws Exception - { + public void testSubscribeWithAutoAck() throws Exception { String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); @@ -477,8 +460,7 @@ public class StompTest extends StompTestBase } @Test - public void testSubscribeWithAutoAckAndBytesMessage() throws Exception - { + public void testSubscribeWithAutoAckAndBytesMessage() throws Exception { String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); @@ -511,8 +493,7 @@ public class StompTest extends StompTestBase } @Test - public void testSubscribeWithMessageSentWithProperties() throws Exception - { + public void testSubscribeWithMessageSentWithProperties() throws Exception { String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); @@ -556,8 +537,7 @@ public class StompTest extends StompTestBase } @Test - public void testSubscribeWithID() throws Exception - { + public void testSubscribeWithID() throws Exception { String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); @@ -587,8 +567,7 @@ public class StompTest extends StompTestBase } @Test - public void testBodyWithUTF8() throws Exception - { + public void testBodyWithUTF8() throws Exception { String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); @@ -614,8 +593,7 @@ public class StompTest extends StompTestBase } @Test - public void testMessagesAreInOrder() throws Exception - { + public void testMessagesAreInOrder() throws Exception { int ctr = 10; String[] data = new String[ctr]; @@ -628,14 +606,12 @@ public class StompTest extends StompTestBase frame = "SUBSCRIBE\n" + "destination:" + getQueuePrefix() + getQueueName() + "\n" + "ack:auto\n\n" + Stomp.NULL; sendFrame(frame); - for (int i = 0; i < ctr; ++i) - { + for (int i = 0; i < ctr; ++i) { data[i] = getName() + i; sendMessage(data[i]); } - for (int i = 0; i < ctr; ++i) - { + for (int i = 0; i < ctr; ++i) { frame = receiveFrame(1000); Assert.assertTrue("Message not in order", frame.indexOf(data[i]) >= 0); } @@ -643,14 +619,12 @@ public class StompTest extends StompTestBase // sleep a while before publishing another set of messages waitForFrameToTakeEffect(); - for (int i = 0; i < ctr; ++i) - { + for (int i = 0; i < ctr; ++i) { data[i] = getName() + ":second:" + i; sendMessage(data[i]); } - for (int i = 0; i < ctr; ++i) - { + for (int i = 0; i < ctr; ++i) { frame = receiveFrame(1000); Assert.assertTrue("Message not in order", frame.indexOf(data[i]) >= 0); } @@ -660,8 +634,7 @@ public class StompTest extends StompTestBase } @Test - public void testSubscribeWithAutoAckAndSelector() throws Exception - { + public void testSubscribeWithAutoAckAndSelector() throws Exception { String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); @@ -690,8 +663,7 @@ public class StompTest extends StompTestBase } @Test - public void testSubscribeWithClientAck() throws Exception - { + public void testSubscribeWithClientAck() throws Exception { String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); @@ -724,8 +696,7 @@ public class StompTest extends StompTestBase } @Test - public void testRedeliveryWithClientAck() throws Exception - { + public void testRedeliveryWithClientAck() throws Exception { String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); @@ -752,19 +723,16 @@ public class StompTest extends StompTestBase } @Test - public void testSubscribeWithClientAckThenConsumingAgainWithAutoAckWithNoDisconnectFrame() throws Exception - { + public void testSubscribeWithClientAckThenConsumingAgainWithAutoAckWithNoDisconnectFrame() throws Exception { assertSubscribeWithClientAckThenConsumeWithAutoAck(false); } @Test - public void testSubscribeWithClientAckThenConsumingAgainWithAutoAckWithExplicitDisconnect() throws Exception - { + public void testSubscribeWithClientAckThenConsumingAgainWithAutoAckWithExplicitDisconnect() throws Exception { assertSubscribeWithClientAckThenConsumeWithAutoAck(true); } - protected void assertSubscribeWithClientAckThenConsumeWithAutoAck(boolean sendDisconnect) throws Exception - { + protected void assertSubscribeWithClientAckThenConsumeWithAutoAck(boolean sendDisconnect) throws Exception { String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); @@ -782,15 +750,13 @@ public class StompTest extends StompTestBase log.info("Reconnecting!"); - if (sendDisconnect) - { + if (sendDisconnect) { frame = "DISCONNECT\n" + "\n\n" + Stomp.NULL; sendFrame(frame); waitForFrameToTakeEffect(); reconnect(); } - else - { + else { reconnect(100); waitForFrameToTakeEffect(); } @@ -843,8 +809,7 @@ public class StompTest extends StompTestBase } @Test - public void testUnsubscribe() throws Exception - { + public void testUnsubscribe() throws Exception { String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); @@ -881,8 +846,7 @@ public class StompTest extends StompTestBase } @Test - public void testUnsubscribeWithID() throws Exception - { + public void testUnsubscribeWithID() throws Exception { String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); @@ -920,8 +884,7 @@ public class StompTest extends StompTestBase } @Test - public void testTransactionCommit() throws Exception - { + public void testTransactionCommit() throws Exception { MessageConsumer consumer = session.createConsumer(queue); String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; @@ -957,8 +920,7 @@ public class StompTest extends StompTestBase } @Test - public void testSuccessiveTransactionsWithSameID() throws Exception - { + public void testSuccessiveTransactionsWithSameID() throws Exception { MessageConsumer consumer = session.createConsumer(queue); String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; @@ -1009,8 +971,7 @@ public class StompTest extends StompTestBase } @Test - public void testBeginSameTransactionTwice() throws Exception - { + public void testBeginSameTransactionTwice() throws Exception { String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); @@ -1030,8 +991,7 @@ public class StompTest extends StompTestBase } @Test - public void testTransactionRollback() throws Exception - { + public void testTransactionRollback() throws Exception { MessageConsumer consumer = session.createConsumer(queue); String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; @@ -1081,8 +1041,7 @@ public class StompTest extends StompTestBase } @Test - public void testSubscribeToTopic() throws Exception - { + public void testSubscribeToTopic() throws Exception { String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); @@ -1127,14 +1086,12 @@ public class StompTest extends StompTestBase log.info("Received frame: " + frame); Assert.assertNull("No message should have been received since subscription was removed", frame); - frame = "DISCONNECT\n" + "\n\n" + Stomp.NULL; sendFrame(frame); } @Test - public void testSubscribeToNonExistentQueue() throws Exception - { + public void testSubscribeToNonExistentQueue() throws Exception { String nonExistentQueue = RandomUtil.randomString(); String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; @@ -1184,14 +1141,12 @@ public class StompTest extends StompTestBase log.info("Received frame: " + frame); Assert.assertNull("No message should have been received since subscription was removed", frame); - frame = "DISCONNECT\n" + "\n\n" + Stomp.NULL; sendFrame(frame); } @Test - public void testDurableSubscriberWithReconnection() throws Exception - { + public void testDurableSubscriberWithReconnection() throws Exception { String connectFame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n" + @@ -1250,8 +1205,7 @@ public class StompTest extends StompTestBase } @Test - public void testDurableSubscriber() throws Exception - { + public void testDurableSubscriber() throws Exception { String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n" + "client-id: myclientid\n\n" + Stomp.NULL; sendFrame(frame); @@ -1284,8 +1238,7 @@ public class StompTest extends StompTestBase } @Test - public void testSubscribeToTopicWithNoLocal() throws Exception - { + public void testSubscribeToTopicWithNoLocal() throws Exception { String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); @@ -1314,7 +1267,6 @@ public class StompTest extends StompTestBase log.info("Received frame: " + frame); Assert.assertNull("No message should have been received since subscription was removed", frame); - // send message on another JMS connection => it should be received sendMessage(getName(), topic); frame = receiveFrame(10000); @@ -1327,8 +1279,7 @@ public class StompTest extends StompTestBase } @Test - public void testClientAckNotPartOfTransaction() throws Exception - { + public void testClientAckNotPartOfTransaction() throws Exception { String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); @@ -1378,8 +1329,7 @@ public class StompTest extends StompTestBase // HORNETQ-1007 @Test - public void testMultiProtocolConsumers() throws Exception - { + public void testMultiProtocolConsumers() throws Exception { final int TIME_OUT = 5000; int count = 1000; @@ -1408,8 +1358,7 @@ public class StompTest extends StompTestBase MessageProducer producer = session.createProducer(topic); TextMessage message = session.createTextMessage(getName()); - for (int i = 1; i <= count; i++) - { + for (int i = 1; i <= count; i++) { producer.send(message); Assert.assertNotNull(consumer1.receive(TIME_OUT)); Assert.assertNotNull(consumer2.receive(TIME_OUT)); @@ -1445,8 +1394,7 @@ public class StompTest extends StompTestBase @Test //stomp should return an ERROR when acking a non-existent message - public void testUnexpectedAck() throws Exception - { + public void testUnexpectedAck() throws Exception { String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/StompTestBase.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/StompTestBase.java index d4ffb88f80..2e5650e608 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/StompTestBase.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/StompTestBase.java @@ -72,8 +72,8 @@ import org.apache.activemq.artemis.jms.server.impl.JMSServerManagerImpl; import org.junit.After; import org.junit.Before; -public abstract class StompTestBase extends ActiveMQTestBase -{ +public abstract class StompTestBase extends ActiveMQTestBase { + protected final int port = 61613; private ConnectionFactory connectionFactory; @@ -102,17 +102,14 @@ public abstract class StompTestBase extends ActiveMQTestBase private EventLoopGroup group; - // Implementation methods // ------------------------------------------------------------------------- @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); priorityQueue = new ArrayBlockingQueue(1000); - if (autoCreateServer) - { + if (autoCreateServer) { server = createServer(); addServer(server.getActiveMQServer()); server.start(); @@ -127,54 +124,41 @@ public abstract class StompTestBase extends ActiveMQTestBase } } - private void createBootstrap() - { + private void createBootstrap() { group = new NioEventLoopGroup(); bootstrap = new Bootstrap(); - bootstrap.group(group) - .channel(NioSocketChannel.class) - .option(ChannelOption.TCP_NODELAY, true) - .handler(new ChannelInitializer() - { - @Override - public void initChannel(SocketChannel ch) throws Exception - { - addChannelHandlers(ch); - } - }); + bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer() { + @Override + public void initChannel(SocketChannel ch) throws Exception { + addChannelHandlers(ch); + } + }); // Start the client. - try - { + try { channel = bootstrap.connect("localhost", port).sync().channel(); handshake(); } - catch (InterruptedException e) - { + catch (InterruptedException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } - protected void handshake() throws InterruptedException - { + protected void handshake() throws InterruptedException { } - - protected void addChannelHandlers(SocketChannel ch) throws URISyntaxException - { + protected void addChannelHandlers(SocketChannel ch) throws URISyntaxException { ch.pipeline().addLast("decoder", new StringDecoder(StandardCharsets.UTF_8)); ch.pipeline().addLast("encoder", new StringEncoder(StandardCharsets.UTF_8)); ch.pipeline().addLast(new StompClientHandler()); } - protected void setUpAfterServer() throws Exception - { + protected void setUpAfterServer() throws Exception { setUpAfterServer(false); } - protected void setUpAfterServer(boolean jmsCompressLarge) throws Exception - { + protected void setUpAfterServer(boolean jmsCompressLarge) throws Exception { connectionFactory = createConnectionFactory(); ActiveMQConnectionFactory activeMQConnectionFactory = (ActiveMQConnectionFactory) connectionFactory; @@ -193,29 +177,20 @@ public abstract class StompTestBase extends ActiveMQTestBase * @return * @throws Exception */ - protected JMSServerManager createServer() throws Exception - { + protected JMSServerManager createServer() throws Exception { Map params = new HashMap(); params.put(TransportConstants.PROTOCOLS_PROP_NAME, StompProtocolManagerFactory.STOMP_PROTOCOL_NAME); params.put(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_STOMP_PORT); params.put(TransportConstants.STOMP_CONSUMERS_CREDIT, "-1"); TransportConfiguration stompTransport = new TransportConfiguration(NettyAcceptorFactory.class.getName(), params); - Configuration config = createBasicConfig() - .setPersistenceEnabled(false) - .addAcceptorConfiguration(stompTransport) - .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())); + Configuration config = createBasicConfig().setPersistenceEnabled(false).addAcceptorConfiguration(stompTransport).addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())); ActiveMQServer activeMQServer = addServer(ActiveMQServers.newActiveMQServer(config, defUser, defPass)); JMSConfiguration jmsConfig = new JMSConfigurationImpl(); - jmsConfig.getQueueConfigurations().add(new JMSQueueConfigurationImpl() - .setName(getQueueName()) - .setDurable(false) - .setBindings(getQueueName())); - jmsConfig.getTopicConfigurations().add(new TopicConfigurationImpl() - .setName(getTopicName()) - .setBindings(getTopicName())); + jmsConfig.getQueueConfigurations().add(new JMSQueueConfigurationImpl().setName(getQueueName()).setDurable(false).setBindings(getQueueName())); + jmsConfig.getTopicConfigurations().add(new TopicConfigurationImpl().setName(getTopicName()).setBindings(getTopicName())); server = new JMSServerManagerImpl(activeMQServer, jmsConfig); server.setRegistry(new JndiBindingRegistry(new InVMNamingContext())); return server; @@ -223,14 +198,11 @@ public abstract class StompTestBase extends ActiveMQTestBase @Override @After - public void tearDown() throws Exception - { - if (autoCreateServer) - { + public void tearDown() throws Exception { + if (autoCreateServer) { connection.close(); - if (group != null) - { + if (group != null) { channel.close(); group.shutdownGracefully(0, 5000, TimeUnit.MILLISECONDS); } @@ -238,111 +210,93 @@ public abstract class StompTestBase extends ActiveMQTestBase super.tearDown(); } - protected void cleanUp() throws Exception - { + protected void cleanUp() throws Exception { connection.close(); - if (group != null) - { + if (group != null) { group.shutdown(); } } - protected void reconnect() throws Exception - { + protected void reconnect() throws Exception { reconnect(0); } - protected void reconnect(long sleep) throws Exception - { + protected void reconnect(long sleep) throws Exception { group.shutdown(); - if (sleep > 0) - { + if (sleep > 0) { Thread.sleep(sleep); } createBootstrap(); } - protected ConnectionFactory createConnectionFactory() - { + protected ConnectionFactory createConnectionFactory() { return new ActiveMQJMSConnectionFactory(false, new TransportConfiguration(InVMConnectorFactory.class.getName())); } - protected Socket createSocket() throws IOException - { + protected Socket createSocket() throws IOException { return new Socket("localhost", port); } - protected String getQueueName() - { + protected String getQueueName() { return "test"; } - protected String getQueuePrefix() - { + protected String getQueuePrefix() { return "jms.queue."; } - protected String getTopicName() - { + protected String getTopicName() { return "testtopic"; } - protected String getTopicPrefix() - { + protected String getTopicPrefix() { return "jms.topic."; } - - protected void assertChannelClosed() throws InterruptedException - { + protected void assertChannelClosed() throws InterruptedException { boolean closed = channel.closeFuture().await(5000); assertTrue("channel not closed", closed); } - public void sendFrame(String data) throws Exception - { + public void sendFrame(String data) throws Exception { channel.writeAndFlush(data); } - public void sendFrame(byte[] data) throws Exception - { + public void sendFrame(byte[] data) throws Exception { ByteBuf buffer = Unpooled.buffer(data.length); buffer.writeBytes(data); channel.writeAndFlush(buffer); } - public String receiveFrame(long timeOut) throws Exception - { + public String receiveFrame(long timeOut) throws Exception { String msg = (String) priorityQueue.poll(timeOut, TimeUnit.MILLISECONDS); return msg; } - public void sendMessage(String msg) throws Exception - { + public void sendMessage(String msg) throws Exception { sendMessage(msg, queue); } - public void sendMessage(String msg, Destination destination) throws Exception - { + public void sendMessage(String msg, Destination destination) throws Exception { MessageProducer producer = session.createProducer(destination); TextMessage message = session.createTextMessage(msg); producer.send(message); } - public void sendMessage(byte[] data, Destination destination) throws Exception - { + public void sendMessage(byte[] data, Destination destination) throws Exception { sendMessage(data, "foo", "xyz", destination); } - public void sendMessage(String msg, String propertyName, String propertyValue) throws Exception - { + public void sendMessage(String msg, String propertyName, String propertyValue) throws Exception { sendMessage(msg.getBytes(StandardCharsets.UTF_8), propertyName, propertyValue, queue); } - public void sendMessage(byte[] data, String propertyName, String propertyValue, Destination destination) throws Exception - { + public void sendMessage(byte[] data, + String propertyName, + String propertyValue, + Destination destination) throws Exception { MessageProducer producer = session.createProducer(destination); BytesMessage message = session.createBytesMessage(); message.setStringProperty(propertyName, propertyValue); @@ -350,51 +304,44 @@ public abstract class StompTestBase extends ActiveMQTestBase producer.send(message); } - protected void waitForReceipt() throws Exception - { + protected void waitForReceipt() throws Exception { String frame = receiveFrame(50000); assertNotNull(frame); assertTrue(frame.indexOf("RECEIPT") > -1); } - protected void waitForFrameToTakeEffect() throws InterruptedException - { + protected void waitForFrameToTakeEffect() throws InterruptedException { // bit of a dirty hack :) // another option would be to force some kind of receipt to be returned // from the frame Thread.sleep(500); } - class StompClientHandler extends SimpleChannelInboundHandler - { + class StompClientHandler extends SimpleChannelInboundHandler { + StringBuffer currentMessage = new StringBuffer(""); @Override - protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception - { + protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { currentMessage.append(msg); String fullMessage = currentMessage.toString(); - if (fullMessage.contains("\0\n")) - { + if (fullMessage.contains("\0\n")) { int messageEnd = fullMessage.indexOf("\0\n"); String actualMessage = fullMessage.substring(0, messageEnd); fullMessage = fullMessage.substring(messageEnd + 2); currentMessage = new StringBuffer(""); priorityQueue.add(actualMessage); - if (fullMessage.length() > 0) - { + if (fullMessage.length() > 0) { channelRead(ctx, fullMessage); } } } @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception - { + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } } - } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/StompWebSocketTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/StompWebSocketTest.java index dc11fccb13..012e7da129 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/StompWebSocketTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/StompWebSocketTest.java @@ -36,8 +36,8 @@ import org.junit.Test; import java.util.HashMap; import java.util.Map; -public class StompWebSocketTest extends ActiveMQTestBase -{ +public class StompWebSocketTest extends ActiveMQTestBase { + private JMSServerManager server; /** @@ -46,8 +46,7 @@ public class StompWebSocketTest extends ActiveMQTestBase * from http://github.com/jmesnil/stomp-websocket */ @Test - public void testConnect() throws Exception - { + public void testConnect() throws Exception { //Thread.sleep(10000000); } @@ -55,8 +54,7 @@ public class StompWebSocketTest extends ActiveMQTestBase //------------------------------------------------------------------------- @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { server = createServer(); server.start(); } @@ -65,20 +63,13 @@ public class StompWebSocketTest extends ActiveMQTestBase * @return * @throws Exception */ - private JMSServerManager createServer() throws Exception - { + private JMSServerManager createServer() throws Exception { Map params = new HashMap(); params.put(TransportConstants.PROTOCOLS_PROP_NAME, StompProtocolManagerFactory.STOMP_PROTOCOL_NAME); params.put(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_STOMP_PORT + 1); TransportConfiguration stompTransport = new TransportConfiguration(NettyAcceptorFactory.class.getName(), params); - Configuration config = createBasicConfig() - .addAcceptorConfiguration(stompTransport) - .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())) - .addQueueConfiguration(new CoreQueueConfiguration() - .setAddress(getQueueName()) - .setName(getQueueName()) - .setDurable(false)); + Configuration config = createBasicConfig().addAcceptorConfiguration(stompTransport).addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())).addQueueConfiguration(new CoreQueueConfiguration().setAddress(getQueueName()).setName(getQueueName()).setDurable(false)); ActiveMQServer activeMQServer = addServer(ActiveMQServers.newActiveMQServer(config)); @@ -88,8 +79,7 @@ public class StompWebSocketTest extends ActiveMQTestBase return server; } - protected String getQueueName() - { + protected String getQueueName() { return "/queue/test"; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/AbstractClientStompFrame.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/AbstractClientStompFrame.java index 90ac261da0..8bc7f95d47 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/AbstractClientStompFrame.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/AbstractClientStompFrame.java @@ -24,8 +24,8 @@ import java.util.Iterator; import java.util.List; import java.util.Set; -public abstract class AbstractClientStompFrame implements ClientStompFrame -{ +public abstract class AbstractClientStompFrame implements ClientStompFrame { + protected static final String HEADER_RECEIPT = "receipt"; protected static final Set validCommands = new HashSet(); @@ -34,8 +34,8 @@ public abstract class AbstractClientStompFrame implements ClientStompFrame protected Set headerKeys = new HashSet(); protected String body; protected String EOL = "\n"; - static - { + + static { validCommands.add("CONNECT"); validCommands.add("CONNECTED"); validCommands.add("SEND"); @@ -51,28 +51,24 @@ public abstract class AbstractClientStompFrame implements ClientStompFrame validCommands.add("ERROR"); } - public AbstractClientStompFrame(String command) - { + public AbstractClientStompFrame(String command) { this(command, true); } - public AbstractClientStompFrame(String command, boolean validate) - { - if (validate && (!validate(command))) throw new IllegalArgumentException("Invalid command " + command); + public AbstractClientStompFrame(String command, boolean validate) { + if (validate && (!validate(command))) + throw new IllegalArgumentException("Invalid command " + command); this.command = command; } - public boolean validate(String command) - { + public boolean validate(String command) { return validCommands.contains(command); } - public String toString() - { + public String toString() { StringBuffer sb = new StringBuffer("Frame: <" + command + ">" + "\n"); Iterator
    iter = headers.iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { Header h = iter.next(); sb.append(h.key + ":" + h.val + "\n"); } @@ -82,28 +78,24 @@ public abstract class AbstractClientStompFrame implements ClientStompFrame } @Override - public ByteBuffer toByteBuffer() - { - if (isPing()) - { + public ByteBuffer toByteBuffer() { + if (isPing()) { ByteBuffer buffer = ByteBuffer.allocateDirect(1); - buffer.put((byte)0x0A); + buffer.put((byte) 0x0A); buffer.rewind(); return buffer; } StringBuffer sb = new StringBuffer(); sb.append(command + EOL); int n = headers.size(); - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { sb.append(headers.get(i).key + ":" + headers.get(i).val + EOL); } sb.append(EOL); - if (body != null) - { + if (body != null) { sb.append(body); } - sb.append((char)0); + sb.append((char) 0); String data = sb.toString(); @@ -117,21 +109,18 @@ public abstract class AbstractClientStompFrame implements ClientStompFrame } @Override - public ByteBuffer toByteBufferWithExtra(String str) - { + public ByteBuffer toByteBufferWithExtra(String str) { StringBuffer sb = new StringBuffer(); sb.append(command + EOL); int n = headers.size(); - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { sb.append(headers.get(i).key + ":" + headers.get(i).val + EOL); } sb.append(EOL); - if (body != null) - { + if (body != null) { sb.append(body); } - sb.append((char)0); + sb.append((char) 0); sb.append(str); String data = sb.toString(); @@ -146,69 +135,57 @@ public abstract class AbstractClientStompFrame implements ClientStompFrame } @Override - public boolean needsReply() - { - if ("CONNECT".equals(command) || headerKeys.contains(HEADER_RECEIPT)) - { + public boolean needsReply() { + if ("CONNECT".equals(command) || headerKeys.contains(HEADER_RECEIPT)) { return true; } return false; } @Override - public void setCommand(String command) - { + public void setCommand(String command) { this.command = command; } @Override - public void addHeader(String key, String val) - { + public void addHeader(String key, String val) { headers.add(new Header(key, val)); headerKeys.add(key); } @Override - public void setBody(String body) - { + public void setBody(String body) { this.body = body; } @Override - public String getBody() - { + public String getBody() { return body; } - private class Header - { + private class Header { + public String key; public String val; - public Header(String key, String val) - { + public Header(String key, String val) { this.key = key; this.val = val; } } @Override - public String getCommand() - { + public String getCommand() { return command; } @Override - public String getHeader(String header) - { - if (headerKeys.contains(header)) - { + public String getHeader(String header) { + if (headerKeys.contains(header)) { Iterator
    iter = headers.iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { Header h = iter.next(); - if (h.key.equals(header)) - { + if (h.key.equals(header)) { return h.val; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/AbstractStompClientConnection.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/AbstractStompClientConnection.java index c533bf60fb..bac977b1a4 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/AbstractStompClientConnection.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/AbstractStompClientConnection.java @@ -27,8 +27,8 @@ import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; -public abstract class AbstractStompClientConnection implements StompClientConnection -{ +public abstract class AbstractStompClientConnection implements StompClientConnection { + public static final String STOMP_COMMAND = "STOMP"; public static final String ACCEPT_HEADER = "accept-version"; @@ -64,8 +64,7 @@ public abstract class AbstractStompClientConnection implements StompClientConnec protected boolean connected = false; private int serverPingCounter; - public AbstractStompClientConnection(String version, String host, int port) throws IOException - { + public AbstractStompClientConnection(String version, String host, int port) throws IOException { this.version = version; this.host = host; this.port = port; @@ -74,8 +73,7 @@ public abstract class AbstractStompClientConnection implements StompClientConnec initSocket(); } - private void initSocket() throws IOException - { + private void initSocket() throws IOException { socketChannel.configureBlocking(true); InetSocketAddress remoteAddr = new InetSocketAddress(host, port); socketChannel.connect(remoteAddr); @@ -83,37 +81,30 @@ public abstract class AbstractStompClientConnection implements StompClientConnec startReaderThread(); } - private void startReaderThread() - { + private void startReaderThread() { readBuffer = ByteBuffer.allocateDirect(10240); receiveList = new ArrayList(10240); new ReaderThread().start(); } - public ClientStompFrame sendFrame(ClientStompFrame frame) throws IOException, InterruptedException - { + public ClientStompFrame sendFrame(ClientStompFrame frame) throws IOException, InterruptedException { ClientStompFrame response = null; ByteBuffer buffer = frame.toByteBuffer(); - while (buffer.remaining() > 0) - { + while (buffer.remaining() > 0) { socketChannel.write(buffer); } //now response - if (frame.needsReply()) - { + if (frame.needsReply()) { response = receiveFrame(); //filter out server ping - while (response != null) - { - if (response.getCommand().equals("STOMP")) - { + while (response != null) { + if (response.getCommand().equals("STOMP")) { response = receiveFrame(); } - else - { + else { break; } } @@ -122,30 +113,24 @@ public abstract class AbstractStompClientConnection implements StompClientConnec return response; } - public ClientStompFrame sendWickedFrame(ClientStompFrame frame) throws IOException, InterruptedException - { + public ClientStompFrame sendWickedFrame(ClientStompFrame frame) throws IOException, InterruptedException { ClientStompFrame response = null; ByteBuffer buffer = frame.toByteBufferWithExtra("\n"); - while (buffer.remaining() > 0) - { + while (buffer.remaining() > 0) { socketChannel.write(buffer); } //now response - if (frame.needsReply()) - { + if (frame.needsReply()) { response = receiveFrame(); //filter out server ping - while (response != null) - { - if (response.getCommand().equals("STOMP")) - { + while (response != null) { + if (response.getCommand().equals("STOMP")) { response = receiveFrame(); } - else - { + else { break; } } @@ -153,56 +138,44 @@ public abstract class AbstractStompClientConnection implements StompClientConnec return response; } - public ClientStompFrame receiveFrame() throws InterruptedException - { + public ClientStompFrame receiveFrame() throws InterruptedException { return frameQueue.poll(10, TimeUnit.SECONDS); } - public ClientStompFrame receiveFrame(long timeout) throws InterruptedException - { + public ClientStompFrame receiveFrame(long timeout) throws InterruptedException { return frameQueue.poll(timeout, TimeUnit.MILLISECONDS); } //put bytes to byte array. - private void receiveBytes(int n) - { + private void receiveBytes(int n) { readBuffer.rewind(); - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { byte b = readBuffer.get(); - if (b == 0) - { + if (b == 0) { //a new frame got. int sz = receiveList.size(); - if (sz > 0) - { + if (sz > 0) { byte[] frameBytes = new byte[sz]; - for (int j = 0; j < sz; j++) - { + for (int j = 0; j < sz; j++) { frameBytes[j] = receiveList.get(j); } ClientStompFrame frame = factory.createFrame(new String(frameBytes, StandardCharsets.UTF_8)); - if (validateFrame(frame)) - { + if (validateFrame(frame)) { frameQueue.offer(frame); receiveList.clear(); } - else - { + else { receiveList.add(b); } } } - else - { - if (b == 10 && receiveList.size() == 0) - { + else { + if (b == 10 && receiveList.size() == 0) { //may be a ping incrementServerPing(); } - else - { + else { receiveList.add(b); } } @@ -211,50 +184,39 @@ public abstract class AbstractStompClientConnection implements StompClientConnec readBuffer.rewind(); } - @Override - public int getServerPingNumber() - { + public int getServerPingNumber() { return serverPingCounter; } - protected void incrementServerPing() - { + protected void incrementServerPing() { serverPingCounter++; } - private boolean validateFrame(ClientStompFrame f) - { + private boolean validateFrame(ClientStompFrame f) { String h = f.getHeader("content-length"); - if (h != null) - { + if (h != null) { int len = Integer.valueOf(h); - if (f.getBody().getBytes(StandardCharsets.UTF_8).length < len) - { + if (f.getBody().getBytes(StandardCharsets.UTF_8).length < len) { return false; } } return true; } - protected void close() throws IOException - { + protected void close() throws IOException { socketChannel.close(); } - private class ReaderThread extends Thread - { + private class ReaderThread extends Thread { + @Override - public void run() - { - try - { + public void run() { + try { int n = socketChannel.read(readBuffer); - while (n >= 0) - { - if (n > 0) - { + while (n >= 0) { + if (n > 0) { receiveBytes(n); } n = socketChannel.read(readBuffer); @@ -263,93 +225,75 @@ public abstract class AbstractStompClientConnection implements StompClientConnec close(); } - catch (IOException e) - { - try - { + catch (IOException e) { + try { close(); } - catch (IOException e1) - { + catch (IOException e1) { //ignore } } } } - public ClientStompFrame connect() throws Exception - { + public ClientStompFrame connect() throws Exception { return connect(null, null); } - public void destroy() - { - try - { + public void destroy() { + try { close(); } - catch (IOException e) - { + catch (IOException e) { } - finally - { + finally { this.connected = false; } } - public ClientStompFrame connect(String username, String password) throws Exception - { + public ClientStompFrame connect(String username, String password) throws Exception { throw new RuntimeException("connect method not implemented!"); } - public boolean isConnected() - { + public boolean isConnected() { return connected; } - public String getVersion() - { + public String getVersion() { return version; } - public int getFrameQueueSize() - { + public int getFrameQueueSize() { return this.frameQueue.size(); } @Override - public void startPinger(long interval) - { + public void startPinger(long interval) { pinger = new Pinger(interval); pinger.startPing(); } @Override - public void stopPinger() - { - if (pinger != null) - { + public void stopPinger() { + if (pinger != null) { pinger.stopPing(); - try - { + try { pinger.join(); } - catch (InterruptedException e) - { + catch (InterruptedException e) { e.printStackTrace(); } pinger = null; } } - private class Pinger extends Thread - { + private class Pinger extends Thread { + long pingInterval; ClientStompFrame pingFrame; volatile boolean stop = false; - public Pinger(long interval) - { + public Pinger(long interval) { this.pingInterval = interval; pingFrame = createFrame("STOMP"); pingFrame.setBody("\n"); @@ -357,31 +301,24 @@ public abstract class AbstractStompClientConnection implements StompClientConnec pingFrame.setPing(true); } - public void startPing() - { + public void startPing() { start(); } - public synchronized void stopPing() - { + public synchronized void stopPing() { stop = true; this.notify(); } - public void run() - { - synchronized (this) - { - while (!stop) - { - try - { + public void run() { + synchronized (this) { + while (!stop) { + try { sendFrame(pingFrame); this.wait(pingInterval); } - catch (Exception e) - { + catch (Exception e) { stop = true; e.printStackTrace(); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/ClientStompFrame.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/ClientStompFrame.java index 6c396738ca..53bced4ac1 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/ClientStompFrame.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/ClientStompFrame.java @@ -21,8 +21,7 @@ import java.nio.ByteBuffer; /** * pls use factory to create frames. */ -public interface ClientStompFrame -{ +public interface ClientStompFrame { ByteBuffer toByteBuffer(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/ClientStompFrameV10.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/ClientStompFrameV10.java index 7c2daf6434..52732360ff 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/ClientStompFrameV10.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/ClientStompFrameV10.java @@ -19,33 +19,28 @@ package org.apache.activemq.artemis.tests.integration.stomp.util; /** * pls use factory to create frames. */ -public class ClientStompFrameV10 extends AbstractClientStompFrame -{ - public ClientStompFrameV10(String command) - { +public class ClientStompFrameV10 extends AbstractClientStompFrame { + + public ClientStompFrameV10(String command) { super(command); } - public ClientStompFrameV10(String command, boolean validate) - { + public ClientStompFrameV10(String command, boolean validate) { super(command, validate); } @Override - public boolean isPing() - { + public boolean isPing() { return false; } @Override - public void setForceOneway() - { + public void setForceOneway() { throw new IllegalStateException("Doesn't apply with V1.0!"); } @Override - public void setPing(boolean b) - { + public void setPing(boolean b) { throw new IllegalStateException("Doesn't apply with V1.0!"); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/ClientStompFrameV11.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/ClientStompFrameV11.java index 1e57e39b04..c168922075 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/ClientStompFrameV11.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/ClientStompFrameV11.java @@ -17,12 +17,11 @@ package org.apache.activemq.artemis.tests.integration.stomp.util; /** - * pls use factory to create frames. + * pls use factory to create frames. */ -public class ClientStompFrameV11 extends AbstractClientStompFrame -{ - static - { +public class ClientStompFrameV11 extends AbstractClientStompFrame { + + static { validCommands.add("NACK"); validCommands.add("STOMP"); } @@ -30,46 +29,39 @@ public class ClientStompFrameV11 extends AbstractClientStompFrame boolean forceOneway = false; boolean isPing = false; - public ClientStompFrameV11(String command) - { + public ClientStompFrameV11(String command) { super(command); } - public ClientStompFrameV11(String command, boolean validate) - { + public ClientStompFrameV11(String command, boolean validate) { super(command, validate); } - public void setForceOneway() - { + public void setForceOneway() { forceOneway = true; } @Override - public boolean needsReply() - { - if (forceOneway) return false; + public boolean needsReply() { + if (forceOneway) + return false; - if ("CONNECT".equals(command) || "STOMP".equals(command) || headerKeys.contains(HEADER_RECEIPT)) - { + if ("CONNECT".equals(command) || "STOMP".equals(command) || headerKeys.contains(HEADER_RECEIPT)) { return true; } return false; } - public void setPing(boolean b) - { + public void setPing(boolean b) { isPing = b; } - public boolean isPing() - { + public boolean isPing() { return isPing; } @Override - public String toString() - { + public String toString() { return "[1.1]" + super.toString(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/ClientStompFrameV12.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/ClientStompFrameV12.java index 8d75a9375d..22ce99e2b5 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/ClientStompFrameV12.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/ClientStompFrameV12.java @@ -18,10 +18,9 @@ package org.apache.activemq.artemis.tests.integration.stomp.util; /** */ -public class ClientStompFrameV12 extends AbstractClientStompFrame -{ - static - { +public class ClientStompFrameV12 extends AbstractClientStompFrame { + + static { validCommands.add("NACK"); validCommands.add("STOMP"); } @@ -29,55 +28,47 @@ public class ClientStompFrameV12 extends AbstractClientStompFrame boolean forceOneway = false; boolean isPing = false; - public ClientStompFrameV12(String command) - { + public ClientStompFrameV12(String command) { this(command, true, true); } - public ClientStompFrameV12(String command, boolean newEol, boolean validate) - { + public ClientStompFrameV12(String command, boolean newEol, boolean validate) { super(command, validate); /** * Stomp 1.2 frames allow a carriage return (octet 13) to optionally * precedes the required line feed (octet 10) as their internal line breaks. * Stomp 1.0 and 1.1 only allow line feeds. */ - if (newEol) - { + if (newEol) { EOL = "\r\n"; } } - public void setForceOneway() - { + public void setForceOneway() { forceOneway = true; } @Override - public boolean needsReply() - { - if (forceOneway) return false; + public boolean needsReply() { + if (forceOneway) + return false; - if ("CONNECT".equals(command) || "STOMP".equals(command) || headerKeys.contains(HEADER_RECEIPT)) - { + if ("CONNECT".equals(command) || "STOMP".equals(command) || headerKeys.contains(HEADER_RECEIPT)) { return true; } return false; } - public void setPing(boolean b) - { + public void setPing(boolean b) { isPing = b; } - public boolean isPing() - { + public boolean isPing() { return isPing; } @Override - public String toString() - { + public String toString() { return "[1.2]" + super.toString(); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompClientConnection.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompClientConnection.java index 08274d718f..12f52d08e4 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompClientConnection.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompClientConnection.java @@ -21,8 +21,8 @@ import java.io.IOException; /** * pls use factory to create frames. */ -public interface StompClientConnection -{ +public interface StompClientConnection { + ClientStompFrame sendFrame(ClientStompFrame frame) throws IOException, InterruptedException; ClientStompFrame receiveFrame() throws InterruptedException; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompClientConnectionFactory.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompClientConnectionFactory.java index 982664b10c..3a40c99926 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompClientConnectionFactory.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompClientConnectionFactory.java @@ -18,28 +18,25 @@ package org.apache.activemq.artemis.tests.integration.stomp.util; import java.io.IOException; -public class StompClientConnectionFactory -{ +public class StompClientConnectionFactory { + //create a raw connection to the host. - public static StompClientConnection createClientConnection(String version, String host, int port) throws IOException - { - if ("1.0".equals(version)) - { + public static StompClientConnection createClientConnection(String version, + String host, + int port) throws IOException { + if ("1.0".equals(version)) { return new StompClientConnectionV10(host, port); } - if ("1.1".equals(version)) - { + if ("1.1".equals(version)) { return new StompClientConnectionV11(host, port); } - if ("1.2".equals(version)) - { + if ("1.2".equals(version)) { return new StompClientConnectionV12(host, port); } return null; } - public static void main(String[] args) throws Exception - { + public static void main(String[] args) throws Exception { StompClientConnection connection = StompClientConnectionFactory.createClientConnection("1.0", "localhost", 61613); System.out.println("created a new connection: " + connection); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompClientConnectionV10.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompClientConnectionV10.java index 474a3127ae..2c9dfe737a 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompClientConnectionV10.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompClientConnectionV10.java @@ -21,36 +21,30 @@ import java.io.IOException; /** * pls use factory to create frames. */ -public class StompClientConnectionV10 extends AbstractStompClientConnection -{ +public class StompClientConnectionV10 extends AbstractStompClientConnection { - public StompClientConnectionV10(String host, int port) throws IOException - { + public StompClientConnectionV10(String host, int port) throws IOException { super("1.0", host, port); } - public ClientStompFrame connect(String username, String passcode) throws IOException, InterruptedException - { + public ClientStompFrame connect(String username, String passcode) throws IOException, InterruptedException { ClientStompFrame frame = factory.newFrame(CONNECT_COMMAND); frame.addHeader(LOGIN_HEADER, username); frame.addHeader(PASSCODE_HEADER, passcode); ClientStompFrame response = this.sendFrame(frame); - if (response.getCommand().equals(CONNECTED_COMMAND)) - { + if (response.getCommand().equals(CONNECTED_COMMAND)) { connected = true; } - else - { + else { System.out.println("Connection failed with: " + response); connected = false; } return response; } - public void connect(String username, String passcode, String clientID) throws IOException, InterruptedException - { + public void connect(String username, String passcode, String clientID) throws IOException, InterruptedException { ClientStompFrame frame = factory.newFrame(CONNECT_COMMAND); frame.addHeader(LOGIN_HEADER, username); frame.addHeader(PASSCODE_HEADER, passcode); @@ -58,20 +52,17 @@ public class StompClientConnectionV10 extends AbstractStompClientConnection ClientStompFrame response = this.sendFrame(frame); - if (response.getCommand().equals(CONNECTED_COMMAND)) - { + if (response.getCommand().equals(CONNECTED_COMMAND)) { connected = true; } - else - { + else { System.out.println("Connection failed with: " + response); connected = false; } } @Override - public void disconnect() throws IOException, InterruptedException - { + public void disconnect() throws IOException, InterruptedException { ClientStompFrame frame = factory.newFrame(DISCONNECT_COMMAND); this.sendFrame(frame); @@ -81,25 +72,20 @@ public class StompClientConnectionV10 extends AbstractStompClientConnection } @Override - public ClientStompFrame createFrame( - String command) - { + public ClientStompFrame createFrame(String command) { return new ClientStompFrameV10(command); } @Override - public void startPinger(long interval) - { + public void startPinger(long interval) { } @Override - public void stopPinger() - { + public void stopPinger() { } @Override - public int getServerPingNumber() - { + public int getServerPingNumber() { return 0; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompClientConnectionV11.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompClientConnectionV11.java index f8faa188f8..481f7a1f55 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompClientConnectionV11.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompClientConnectionV11.java @@ -18,28 +18,24 @@ package org.apache.activemq.artemis.tests.integration.stomp.util; import java.io.IOException; -public class StompClientConnectionV11 extends AbstractStompClientConnection -{ - public StompClientConnectionV11(String host, int port) throws IOException - { +public class StompClientConnectionV11 extends AbstractStompClientConnection { + + public StompClientConnectionV11(String host, int port) throws IOException { super("1.1", host, port); } - public ClientStompFrame connect(String username, String passcode) throws IOException, InterruptedException - { + public ClientStompFrame connect(String username, String passcode) throws IOException, InterruptedException { ClientStompFrame frame = factory.newFrame(CONNECT_COMMAND); frame.addHeader(ACCEPT_HEADER, "1.1"); frame.addHeader(HOST_HEADER, "localhost"); - if (username != null) - { + if (username != null) { frame.addHeader(LOGIN_HEADER, username); frame.addHeader(PASSCODE_HEADER, passcode); } ClientStompFrame response = this.sendFrame(frame); - if (response.getCommand().equals(CONNECTED_COMMAND)) - { + if (response.getCommand().equals(CONNECTED_COMMAND)) { String version = response.getHeader(VERSION_HEADER); assert (version.equals("1.1")); @@ -47,30 +43,26 @@ public class StompClientConnectionV11 extends AbstractStompClientConnection this.passcode = passcode; this.connected = true; } - else - { + else { connected = false; } return response; } - public void connect(String username, String passcode, String clientID) throws IOException, InterruptedException - { + public void connect(String username, String passcode, String clientID) throws IOException, InterruptedException { ClientStompFrame frame = factory.newFrame(CONNECT_COMMAND); frame.addHeader(ACCEPT_HEADER, "1.1"); frame.addHeader(HOST_HEADER, "localhost"); frame.addHeader(CLIENT_ID_HEADER, clientID); - if (username != null) - { + if (username != null) { frame.addHeader(LOGIN_HEADER, username); frame.addHeader(PASSCODE_HEADER, passcode); } ClientStompFrame response = this.sendFrame(frame); - if (response.getCommand().equals(CONNECTED_COMMAND)) - { + if (response.getCommand().equals(CONNECTED_COMMAND)) { String version = response.getHeader(VERSION_HEADER); assert (version.equals("1.1")); @@ -78,27 +70,23 @@ public class StompClientConnectionV11 extends AbstractStompClientConnection this.passcode = passcode; this.connected = true; } - else - { + else { connected = false; } } - public void connect1(String username, String passcode) throws IOException, InterruptedException - { + public void connect1(String username, String passcode) throws IOException, InterruptedException { ClientStompFrame frame = factory.newFrame(STOMP_COMMAND); frame.addHeader(ACCEPT_HEADER, "1.0,1.1"); frame.addHeader(HOST_HEADER, "127.0.0.1"); - if (username != null) - { + if (username != null) { frame.addHeader(LOGIN_HEADER, username); frame.addHeader(PASSCODE_HEADER, passcode); } ClientStompFrame response = this.sendFrame(frame); - if (response.getCommand().equals(CONNECTED_COMMAND)) - { + if (response.getCommand().equals(CONNECTED_COMMAND)) { String version = response.getHeader(VERSION_HEADER); assert (version.equals("1.1")); @@ -106,16 +94,14 @@ public class StompClientConnectionV11 extends AbstractStompClientConnection this.passcode = passcode; this.connected = true; } - else - { + else { System.out.println("Connection failed with frame " + response); connected = false; } } @Override - public void disconnect() throws IOException, InterruptedException - { + public void disconnect() throws IOException, InterruptedException { stopPinger(); ClientStompFrame frame = factory.newFrame(DISCONNECT_COMMAND); @@ -123,8 +109,7 @@ public class StompClientConnectionV11 extends AbstractStompClientConnection ClientStompFrame result = this.sendFrame(frame); - if (result == null || (!"RECEIPT".equals(result.getCommand())) || (!"1".equals(result.getHeader("receipt-id")))) - { + if (result == null || (!"RECEIPT".equals(result.getCommand())) || (!"1".equals(result.getHeader("receipt-id")))) { throw new IOException("Disconnect failed! " + result); } @@ -134,10 +119,8 @@ public class StompClientConnectionV11 extends AbstractStompClientConnection } @Override - public ClientStompFrame createFrame(String command) - { + public ClientStompFrame createFrame(String command) { return factory.newFrame(command); } - } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompClientConnectionV12.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompClientConnectionV12.java index b08eb7b76e..f28743d0cb 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompClientConnectionV12.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompClientConnectionV12.java @@ -18,52 +18,45 @@ package org.apache.activemq.artemis.tests.integration.stomp.util; import java.io.IOException; -public class StompClientConnectionV12 extends AbstractStompClientConnection -{ +public class StompClientConnectionV12 extends AbstractStompClientConnection { - public StompClientConnectionV12(String host, int port) throws IOException - { + public StompClientConnectionV12(String host, int port) throws IOException { super("1.2", host, port); } @Override - public ClientStompFrame createFrame(String command) - { + public ClientStompFrame createFrame(String command) { return factory.newFrame(command); } - public ClientStompFrame connect(String username, String passcode) throws IOException, InterruptedException - { + public ClientStompFrame connect(String username, String passcode) throws IOException, InterruptedException { ClientStompFrame frame = factory.newFrame(CONNECT_COMMAND); frame.addHeader(ACCEPT_HEADER, "1.2"); frame.addHeader(HOST_HEADER, "localhost"); - if (username != null) - { + if (username != null) { frame.addHeader(LOGIN_HEADER, username); frame.addHeader(PASSCODE_HEADER, passcode); } ClientStompFrame response = this.sendFrame(frame); - if (response.getCommand().equals(CONNECTED_COMMAND)) - { + if (response.getCommand().equals(CONNECTED_COMMAND)) { String version = response.getHeader(VERSION_HEADER); - if (!version.equals("1.2")) throw new IllegalStateException("incorrect version!"); + if (!version.equals("1.2")) + throw new IllegalStateException("incorrect version!"); this.username = username; this.passcode = passcode; this.connected = true; } - else - { + else { connected = false; } return response; } @Override - public void disconnect() throws IOException, InterruptedException - { + public void disconnect() throws IOException, InterruptedException { stopPinger(); ClientStompFrame frame = factory.newFrame(DISCONNECT_COMMAND); @@ -71,8 +64,7 @@ public class StompClientConnectionV12 extends AbstractStompClientConnection ClientStompFrame result = this.sendFrame(frame); - if (result == null || (!"RECEIPT".equals(result.getCommand())) || (!"1".equals(result.getHeader("receipt-id")))) - { + if (result == null || (!"RECEIPT".equals(result.getCommand())) || (!"1".equals(result.getHeader("receipt-id")))) { throw new IOException("Disconnect failed! " + result); } @@ -82,38 +74,34 @@ public class StompClientConnectionV12 extends AbstractStompClientConnection } @Override - public void connect(String username, String passcode, String clientID) throws Exception - { + public void connect(String username, String passcode, String clientID) throws Exception { ClientStompFrame frame = factory.newFrame(CONNECT_COMMAND); frame.addHeader(ACCEPT_HEADER, "1.2"); frame.addHeader(HOST_HEADER, "localhost"); frame.addHeader(CLIENT_ID_HEADER, clientID); - if (username != null) - { + if (username != null) { frame.addHeader(LOGIN_HEADER, username); frame.addHeader(PASSCODE_HEADER, passcode); } ClientStompFrame response = this.sendFrame(frame); - if (response.getCommand().equals(CONNECTED_COMMAND)) - { + if (response.getCommand().equals(CONNECTED_COMMAND)) { String version = response.getHeader(VERSION_HEADER); - if (!version.equals("1.2")) throw new IllegalStateException("incorrect version!"); + if (!version.equals("1.2")) + throw new IllegalStateException("incorrect version!"); this.username = username; this.passcode = passcode; this.connected = true; } - else - { + else { connected = false; } } - public ClientStompFrame createAnyFrame(String command) - { + public ClientStompFrame createAnyFrame(String command) { return factory.newAnyFrame(command); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompFrameFactory.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompFrameFactory.java index 71fed39f05..3ec03cf2bb 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompFrameFactory.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompFrameFactory.java @@ -16,8 +16,7 @@ */ package org.apache.activemq.artemis.tests.integration.stomp.util; -public interface StompFrameFactory -{ +public interface StompFrameFactory { ClientStompFrame createFrame(String data); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompFrameFactoryFactory.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompFrameFactoryFactory.java index 8d2a59daa5..1bcec4f1f9 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompFrameFactoryFactory.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompFrameFactoryFactory.java @@ -16,22 +16,18 @@ */ package org.apache.activemq.artemis.tests.integration.stomp.util; -public class StompFrameFactoryFactory -{ - public static StompFrameFactory getFactory(String version) - { - if ("1.0".equals(version)) - { +public class StompFrameFactoryFactory { + + public static StompFrameFactory getFactory(String version) { + if ("1.0".equals(version)) { return new StompFrameFactoryV10(); } - if ("1.1".equals(version)) - { + if ("1.1".equals(version)) { return new StompFrameFactoryV11(); } - if ("1.2".equals(version)) - { + if ("1.2".equals(version)) { return new StompFrameFactoryV12(); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompFrameFactoryV10.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompFrameFactoryV10.java index c93545db26..93674acb98 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompFrameFactoryV10.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompFrameFactoryV10.java @@ -35,11 +35,9 @@ import java.util.StringTokenizer; * 12. RECEIPT * 13. ERROR */ -public class StompFrameFactoryV10 implements StompFrameFactory -{ +public class StompFrameFactoryV10 implements StompFrameFactory { - public ClientStompFrame createFrame(String data) - { + public ClientStompFrame createFrame(String data) { //split the string at "\n\n" String[] dataFields = data.split("\n\n"); @@ -48,30 +46,26 @@ public class StompFrameFactoryV10 implements StompFrameFactory String command = tokenizer.nextToken(); ClientStompFrame frame = new ClientStompFrameV10(command); - while (tokenizer.hasMoreTokens()) - { + while (tokenizer.hasMoreTokens()) { String header = tokenizer.nextToken(); String[] fields = header.split(":"); frame.addHeader(fields[0], fields[1]); } //body (without null byte) - if (dataFields.length == 2) - { + if (dataFields.length == 2) { frame.setBody(dataFields[1]); } return frame; } @Override - public ClientStompFrame newFrame(String command) - { + public ClientStompFrame newFrame(String command) { return new ClientStompFrameV10(command); } @Override - public ClientStompFrame newAnyFrame(String command) - { + public ClientStompFrame newAnyFrame(String command) { return new ClientStompFrameV10(command, false); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompFrameFactoryV11.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompFrameFactoryV11.java index 3e1052d328..173cf941b7 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompFrameFactoryV11.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompFrameFactoryV11.java @@ -19,29 +19,27 @@ package org.apache.activemq.artemis.tests.integration.stomp.util; import java.util.StringTokenizer; /** - * 1.1 frames - *
    - * 1. CONNECT/STOMP(new) - * 2. CONNECTED - * 3. SEND - * 4. SUBSCRIBE - * 5. UNSUBSCRIBE - * 6. BEGIN - * 7. COMMIT - * 8. ACK - * 9. NACK (new) - * 10. ABORT - * 11. DISCONNECT - * 12. MESSAGE - * 13. RECEIPT - * 14. ERROR + * 1.1 frames + *
    + * 1. CONNECT/STOMP(new) + * 2. CONNECTED + * 3. SEND + * 4. SUBSCRIBE + * 5. UNSUBSCRIBE + * 6. BEGIN + * 7. COMMIT + * 8. ACK + * 9. NACK (new) + * 10. ABORT + * 11. DISCONNECT + * 12. MESSAGE + * 13. RECEIPT + * 14. ERROR */ -public class StompFrameFactoryV11 implements StompFrameFactory -{ +public class StompFrameFactoryV11 implements StompFrameFactory { @Override - public ClientStompFrame createFrame(final String data) - { + public ClientStompFrame createFrame(final String data) { //split the string at "\n\n" String[] dataFields = data.split("\n\n"); @@ -50,82 +48,66 @@ public class StompFrameFactoryV11 implements StompFrameFactory String command = tokenizer.nextToken(); ClientStompFrame frame = new ClientStompFrameV11(command); - while (tokenizer.hasMoreTokens()) - { + while (tokenizer.hasMoreTokens()) { String header = tokenizer.nextToken(); String[] fields = splitAndDecodeHeader(header); frame.addHeader(fields[0], fields[1]); } //body (without null byte) - if (dataFields.length == 2) - { + if (dataFields.length == 2) { frame.setBody(dataFields[1]); } return frame; } - private String[] splitAndDecodeHeader(String header) - { + private String[] splitAndDecodeHeader(String header) { // split the header into the key and value at the ":" since there shouldn't be any unescaped colons in the header // except for the one separating the key and value String[] result = header.split(":"); - for (int j = 0; j < result.length; j++) - { + for (int j = 0; j < result.length; j++) { StringBuffer decodedHeader = new StringBuffer(); boolean isEsc = false; - for (int i = 0; i < result[j].length(); i++) - { + for (int i = 0; i < result[j].length(); i++) { char b = result[j].charAt(i); - switch (b) - { + switch (b) { //escaping - case '\\': - { - if (isEsc) - { + case '\\': { + if (isEsc) { //this is a backslash decodedHeader.append(b); isEsc = false; } - else - { + else { //begin escaping isEsc = true; } break; } - case 'c': - { - if (isEsc) - { + case 'c': { + if (isEsc) { decodedHeader.append(":"); isEsc = false; } - else - { + else { decodedHeader.append(b); } break; } - case 'n': - { - if (isEsc) - { + case 'n': { + if (isEsc) { decodedHeader.append('\n'); isEsc = false; } - else - { + else { decodedHeader.append(b); } break; } - default: - { + default: { decodedHeader.append(b); } } @@ -138,14 +120,12 @@ public class StompFrameFactoryV11 implements StompFrameFactory } @Override - public ClientStompFrame newFrame(String command) - { + public ClientStompFrame newFrame(String command) { return new ClientStompFrameV11(command); } @Override - public ClientStompFrame newAnyFrame(String command) - { + public ClientStompFrame newAnyFrame(String command) { return new ClientStompFrameV11(command, false); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompFrameFactoryV12.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompFrameFactoryV12.java index 0f669dbaf1..bab606fc7c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompFrameFactoryV12.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompFrameFactoryV12.java @@ -18,12 +18,10 @@ package org.apache.activemq.artemis.tests.integration.stomp.util; import java.util.StringTokenizer; -public class StompFrameFactoryV12 implements StompFrameFactory -{ +public class StompFrameFactoryV12 implements StompFrameFactory { @Override - public ClientStompFrame createFrame(String data) - { + public ClientStompFrame createFrame(String data) { //split the string at "\n\n" String[] dataFields = data.split("\n\n"); @@ -32,107 +30,86 @@ public class StompFrameFactoryV12 implements StompFrameFactory String command = tokenizer.nextToken(); ClientStompFrame frame = new ClientStompFrameV12(command); - while (tokenizer.hasMoreTokens()) - { + while (tokenizer.hasMoreTokens()) { String header = tokenizer.nextToken(); String[] fields = splitAndDecodeHeader(header); frame.addHeader(fields[0], fields[1]); } //body (without null byte) - if (dataFields.length == 2) - { + if (dataFields.length == 2) { frame.setBody(dataFields[1]); } return frame; } - public void printByteHeader(String headers) - { + public void printByteHeader(String headers) { StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < headers.length(); i++) - { + for (int i = 0; i < headers.length(); i++) { char c = headers.charAt(i); buffer.append((byte) c + " "); } System.out.println("header in byte : " + buffer.toString()); } - private String[] splitAndDecodeHeader(String header) - { + private String[] splitAndDecodeHeader(String header) { // split the header into the key and value at the ":" since there shouldn't be any unescaped colons in the header // except for the one separating the key and value String[] result = header.split(":"); - for (int j = 0; j < result.length; j++) - { + for (int j = 0; j < result.length; j++) { StringBuffer decodedHeader = new StringBuffer(); boolean isEsc = false; - for (int i = 0; i < result[j].length(); i++) - { + for (int i = 0; i < result[j].length(); i++) { char b = result[j].charAt(i); - switch (b) - { + switch (b) { //escaping - case '\\': - { - if (isEsc) - { + case '\\': { + if (isEsc) { //this is a backslash decodedHeader.append(b); isEsc = false; } - else - { + else { //begin escaping isEsc = true; } break; } - case 'c': - { - if (isEsc) - { + case 'c': { + if (isEsc) { decodedHeader.append(":"); isEsc = false; } - else - { + else { decodedHeader.append(b); } break; } - case 'n': - { - if (isEsc) - { + case 'n': { + if (isEsc) { decodedHeader.append('\n'); isEsc = false; } - else - { + else { decodedHeader.append(b); } break; } - case 'r': - { - if (isEsc) - { + case 'r': { + if (isEsc) { decodedHeader.append('\r'); isEsc = false; } - else - { + else { decodedHeader.append(b); } break; } - default: - { + default: { decodedHeader.append(b); } } @@ -145,14 +122,12 @@ public class StompFrameFactoryV12 implements StompFrameFactory } @Override - public ClientStompFrame newFrame(String command) - { + public ClientStompFrame newFrame(String command) { return new ClientStompFrameV12(command); } @Override - public ClientStompFrame newAnyFrame(String command) - { + public ClientStompFrame newAnyFrame(String command) { return new ClientStompFrameV12(command, true, false); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/v11/ExtraStompTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/v11/ExtraStompTest.java index 329c543075..58a08f533b 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/v11/ExtraStompTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/v11/ExtraStompTest.java @@ -28,16 +28,14 @@ import org.junit.Test; /* * Some Stomp tests against server with persistence enabled are put here. */ -public class ExtraStompTest extends StompV11TestBase -{ +public class ExtraStompTest extends StompV11TestBase { private StompClientConnection connV10; private StompClientConnection connV11; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { persistenceEnabled = true; super.setUp(); connV10 = StompClientConnectionFactory.createClientConnection("1.0", hostname, port); @@ -48,22 +46,18 @@ public class ExtraStompTest extends StompV11TestBase @Override @After - public void tearDown() throws Exception - { - try - { + public void tearDown() throws Exception { + try { connV10.disconnect(); connV11.disconnect(); } - finally - { + finally { super.tearDown(); } } @Test - public void testSendAndReceive10() throws Exception - { + public void testSendAndReceive10() throws Exception { String msg1 = "Hello World 1!"; String msg2 = "Hello World 2!"; @@ -126,8 +120,7 @@ public class ExtraStompTest extends StompV11TestBase } @Test - public void testSendAndReceive11() throws Exception - { + public void testSendAndReceive11() throws Exception { String msg1 = "Hello World 1!"; String msg2 = "Hello World 2!"; @@ -189,8 +182,7 @@ public class ExtraStompTest extends StompV11TestBase } @Test - public void testNoGarbageAfterPersistentMessageV10() throws Exception - { + public void testNoGarbageAfterPersistentMessageV10() throws Exception { ClientStompFrame subFrame = connV10.createFrame("SUBSCRIBE"); subFrame.addHeader("id", "a-sub"); subFrame.addHeader("destination", getQueuePrefix() + getQueueName()); @@ -236,9 +228,7 @@ public class ExtraStompTest extends StompV11TestBase } @Test - public void testNoGarbageOnPersistentRedeliveryV10() throws Exception - { - + public void testNoGarbageOnPersistentRedeliveryV10() throws Exception { ClientStompFrame frame = connV10.createFrame("SEND"); frame.addHeader("destination", getQueuePrefix() + getQueueName()); @@ -296,8 +286,7 @@ public class ExtraStompTest extends StompV11TestBase } @Test - public void testNoGarbageAfterPersistentMessageV11() throws Exception - { + public void testNoGarbageAfterPersistentMessageV11() throws Exception { ClientStompFrame subFrame = connV11.createFrame("SUBSCRIBE"); subFrame.addHeader("id", "a-sub"); subFrame.addHeader("destination", getQueuePrefix() + getQueueName()); @@ -340,8 +329,7 @@ public class ExtraStompTest extends StompV11TestBase } @Test - public void testNoGarbageOnPersistentRedeliveryV11() throws Exception - { + public void testNoGarbageOnPersistentRedeliveryV11() throws Exception { ClientStompFrame frame = connV11.createFrame("SEND"); frame.addHeader("destination", getQueuePrefix() + getQueueName()); frame.addHeader("content-length", "11"); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/v11/StompV11Test.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/v11/StompV11Test.java index 03d9034003..945da81737 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/v11/StompV11Test.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/v11/StompV11Test.java @@ -44,41 +44,35 @@ import org.junit.Test; /* * */ -public class StompV11Test extends StompV11TestBase -{ +public class StompV11Test extends StompV11TestBase { + private static final transient IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private StompClientConnection connV11; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); connV11 = StompClientConnectionFactory.createClientConnection("1.1", hostname, port); } @Override @After - public void tearDown() throws Exception - { - try - { + public void tearDown() throws Exception { + try { log.debug("Connection 11 : " + connV11.isConnected()); - if (connV11 != null && connV11.isConnected()) - { + if (connV11 != null && connV11.isConnected()) { connV11.disconnect(); } } - finally - { + finally { super.tearDown(); } } @Test - public void testConnection() throws Exception - { + public void testConnection() throws Exception { server.getActiveMQServer().getConfiguration().setSecurityEnabled(true); StompClientConnection connection = StompClientConnectionFactory.createClientConnection("1.0", hostname, port); @@ -123,8 +117,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testNegotiation() throws Exception - { + public void testNegotiation() throws Exception { // case 1 accept-version absent. It is a 1.0 connect ClientStompFrame frame = connV11.createFrame("CONNECT"); frame.addHeader("host", "127.0.0.1"); @@ -208,8 +201,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testSendAndReceive() throws Exception - { + public void testSendAndReceive() throws Exception { connV11.connect(defUser, defPass); ClientStompFrame frame = connV11.createFrame("SEND"); frame.addHeader("destination", getQueuePrefix() + getQueueName()); @@ -269,8 +261,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testHeaderContentType() throws Exception - { + public void testHeaderContentType() throws Exception { connV11.connect(defUser, defPass); ClientStompFrame frame = connV11.createFrame("SEND"); frame.addHeader("destination", getQueuePrefix() + getQueueName()); @@ -306,8 +297,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testHeaderContentLength() throws Exception - { + public void testHeaderContentLength() throws Exception { connV11.connect(defUser, defPass); ClientStompFrame frame = connV11.createFrame("SEND"); @@ -348,8 +338,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testHeaderEncoding() throws Exception - { + public void testHeaderEncoding() throws Exception { connV11.connect(defUser, defPass); ClientStompFrame frame = connV11.createFrame("SEND"); @@ -398,8 +387,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testHeartBeat() throws Exception - { + public void testHeartBeat() throws Exception { //no heart beat at all if heat-beat absent ClientStompFrame frame = connV11.createFrame("CONNECT"); frame.addHeader("host", "127.0.0.1"); @@ -461,13 +449,11 @@ public class StompV11Test extends StompV11TestBase frame.setBody("Hello World"); //send will fail - try - { + try { connV11.sendFrame(frame); fail("connection should have been destroyed by now"); } - catch (IOException e) - { + catch (IOException e) { //ignore } @@ -509,8 +495,7 @@ public class StompV11Test extends StompV11TestBase //server ping @Test - public void testHeartBeat2() throws Exception - { + public void testHeartBeat2() throws Exception { //heart-beat (1,1) ClientStompFrame frame = connV11.createFrame("CONNECT"); frame.addHeader("host", "127.0.0.1"); @@ -567,11 +552,9 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testSendWithHeartBeatsAndReceive() throws Exception - { + public void testSendWithHeartBeatsAndReceive() throws Exception { StompClientConnection newConn = null; - try - { + try { ClientStompFrame frame = connV11.createFrame("CONNECT"); frame.addHeader("host", "127.0.0.1"); frame.addHeader("login", this.defUser); @@ -587,16 +570,14 @@ public class StompV11Test extends StompV11TestBase frame.addHeader("destination", getQueuePrefix() + getQueueName()); frame.addHeader("content-type", "text/plain"); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { frame.setBody("Hello World " + i + "!"); connV11.sendFrame(frame); Thread.sleep(500); } // subscribe - newConn = StompClientConnectionFactory.createClientConnection("1.1", - hostname, port); + newConn = StompClientConnectionFactory.createClientConnection("1.1", hostname, port); newConn.connect(defUser, defPass); ClientStompFrame subFrame = newConn.createFrame("SUBSCRIBE"); @@ -610,8 +591,7 @@ public class StompV11Test extends StompV11TestBase frame = newConn.receiveFrame(); - while (frame != null) - { + while (frame != null) { cnt++; Thread.sleep(500); frame = newConn.receiveFrame(5000); @@ -624,8 +604,7 @@ public class StompV11Test extends StompV11TestBase unsubFrame.addHeader("id", "a-sub"); newConn.sendFrame(unsubFrame); } - finally - { + finally { if (newConn != null) newConn.disconnect(); connV11.disconnect(); @@ -633,15 +612,13 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testSendAndReceiveWithHeartBeats() throws Exception - { + public void testSendAndReceiveWithHeartBeats() throws Exception { connV11.connect(defUser, defPass); ClientStompFrame frame = connV11.createFrame("SEND"); frame.addHeader("destination", getQueuePrefix() + getQueueName()); frame.addHeader("content-type", "text/plain"); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { frame.setBody("Hello World " + i + "!"); connV11.sendFrame(frame); Thread.sleep(500); @@ -649,8 +626,7 @@ public class StompV11Test extends StompV11TestBase //subscribe StompClientConnection newConn = StompClientConnectionFactory.createClientConnection("1.1", hostname, port); - try - { + try { frame = newConn.createFrame("CONNECT"); frame.addHeader("host", "127.0.0.1"); frame.addHeader("login", this.defUser); @@ -675,8 +651,7 @@ public class StompV11Test extends StompV11TestBase frame = newConn.receiveFrame(); - while (frame != null) - { + while (frame != null) { cnt++; Thread.sleep(500); frame = newConn.receiveFrame(5000); @@ -689,18 +664,15 @@ public class StompV11Test extends StompV11TestBase unsubFrame.addHeader("id", "a-sub"); newConn.sendFrame(unsubFrame); } - finally - { + finally { newConn.disconnect(); } } @Test - public void testSendWithHeartBeatsAndReceiveWithHeartBeats() throws Exception - { + public void testSendWithHeartBeatsAndReceiveWithHeartBeats() throws Exception { StompClientConnection newConn = null; - try - { + try { ClientStompFrame frame = connV11.createFrame("CONNECT"); frame.addHeader("host", "127.0.0.1"); frame.addHeader("login", this.defUser); @@ -716,16 +688,14 @@ public class StompV11Test extends StompV11TestBase frame.addHeader("destination", getQueuePrefix() + getQueueName()); frame.addHeader("content-type", "text/plain"); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { frame.setBody("Hello World " + i + "!"); connV11.sendFrame(frame); Thread.sleep(500); } // subscribe - newConn = StompClientConnectionFactory.createClientConnection("1.1", - hostname, port); + newConn = StompClientConnectionFactory.createClientConnection("1.1", hostname, port); frame = newConn.createFrame("CONNECT"); frame.addHeader("host", "127.0.0.1"); frame.addHeader("login", this.defUser); @@ -750,8 +720,7 @@ public class StompV11Test extends StompV11TestBase frame = newConn.receiveFrame(); - while (frame != null) - { + while (frame != null) { cnt++; Thread.sleep(500); frame = newConn.receiveFrame(5000); @@ -763,8 +732,7 @@ public class StompV11Test extends StompV11TestBase unsubFrame.addHeader("id", "a-sub"); newConn.sendFrame(unsubFrame); } - finally - { + finally { if (newConn != null) newConn.disconnect(); connV11.disconnect(); @@ -772,8 +740,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testNack() throws Exception - { + public void testNack() throws Exception { connV11.connect(defUser, defPass); subscribe(connV11, "sub1", "client"); @@ -797,8 +764,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testNackWithWrongSubId() throws Exception - { + public void testNackWithWrongSubId() throws Exception { connV11.connect(defUser, defPass); subscribe(connV11, "sub1", "client"); @@ -826,8 +792,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testNackWithWrongMessageId() throws Exception - { + public void testNackWithWrongMessageId() throws Exception { connV11.connect(defUser, defPass); subscribe(connV11, "sub1", "client"); @@ -854,10 +819,8 @@ public class StompV11Test extends StompV11TestBase Assert.assertNotNull(message); } - @Test - public void testAck() throws Exception - { + public void testAck() throws Exception { connV11.connect(defUser, defPass); subscribe(connV11, "sub1", "client"); @@ -868,7 +831,6 @@ public class StompV11Test extends StompV11TestBase String messageID = frame.getHeader("message-id"); - ack(connV11, "sub1", messageID, null); unsubscribe(connV11, "sub1"); @@ -882,8 +844,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testAckWithWrongSubId() throws Exception - { + public void testAckWithWrongSubId() throws Exception { connV11.connect(defUser, defPass); subscribe(connV11, "sub1", "client"); @@ -894,7 +855,6 @@ public class StompV11Test extends StompV11TestBase String messageID = frame.getHeader("message-id"); - ack(connV11, "sub2", messageID, null); ClientStompFrame error = connV11.receiveFrame(); @@ -912,8 +872,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testAckWithWrongMessageId() throws Exception - { + public void testAckWithWrongMessageId() throws Exception { connV11.connect(defUser, defPass); subscribe(connV11, "sub1", "client"); @@ -941,8 +900,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testErrorWithReceipt() throws Exception - { + public void testErrorWithReceipt() throws Exception { connV11.connect(defUser, defPass); subscribe(connV11, "sub1", "client"); @@ -953,7 +911,6 @@ public class StompV11Test extends StompV11TestBase String messageID = frame.getHeader("message-id"); - ClientStompFrame ackFrame = connV11.createFrame("ACK"); //give it a wrong sub id ackFrame.addHeader("subscription", "sub2"); @@ -979,8 +936,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testErrorWithReceipt2() throws Exception - { + public void testErrorWithReceipt2() throws Exception { connV11.connect(defUser, defPass); subscribe(connV11, "sub1", "client"); @@ -991,7 +947,6 @@ public class StompV11Test extends StompV11TestBase String messageID = frame.getHeader("message-id"); - ClientStompFrame ackFrame = connV11.createFrame("ACK"); //give it a wrong sub id ackFrame.addHeader("subscription", "sub1"); @@ -1017,23 +972,20 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testAckModeClient() throws Exception - { + public void testAckModeClient() throws Exception { connV11.connect(defUser, defPass); subscribe(connV11, "sub1", "client"); int num = 50; //send a bunch of messages - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { this.sendMessage("client-ack" + i); } ClientStompFrame frame = null; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { frame = connV11.receiveFrame(); assertNotNull(frame); } @@ -1052,29 +1004,25 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testAckModeClient2() throws Exception - { + public void testAckModeClient2() throws Exception { connV11.connect(defUser, defPass); subscribe(connV11, "sub1", "client"); int num = 50; //send a bunch of messages - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { this.sendMessage("client-ack" + i); } ClientStompFrame frame = null; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { frame = connV11.receiveFrame(); assertNotNull(frame); //ack the 49th - if (i == num - 2) - { + if (i == num - 2) { this.ack(connV11, "sub1", frame); } } @@ -1092,23 +1040,20 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testAckModeAuto() throws Exception - { + public void testAckModeAuto() throws Exception { connV11.connect(defUser, defPass); subscribe(connV11, "sub1", "auto"); int num = 50; //send a bunch of messages - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { this.sendMessage("auto-ack" + i); } ClientStompFrame frame = null; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { frame = connV11.receiveFrame(); assertNotNull(frame); } @@ -1124,30 +1069,26 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testAckModeClientIndividual() throws Exception - { + public void testAckModeClientIndividual() throws Exception { connV11.connect(defUser, defPass); subscribe(connV11, "sub1", "client-individual"); int num = 50; //send a bunch of messages - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { this.sendMessage("client-individual-ack" + i); } ClientStompFrame frame = null; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { frame = connV11.receiveFrame(); assertNotNull(frame); System.out.println(i + " == received: " + frame); //ack on even numbers - if (i % 2 == 0) - { + if (i % 2 == 0) { this.ack(connV11, "sub1", frame); } } @@ -1160,8 +1101,7 @@ public class StompV11Test extends StompV11TestBase MessageConsumer consumer = session.createConsumer(queue); TextMessage message = null; - for (int i = 0; i < num / 2; i++) - { + for (int i = 0; i < num / 2; i++) { message = (TextMessage) consumer.receive(1000); Assert.assertNotNull(message); System.out.println("Legal: " + message.getText()); @@ -1173,8 +1113,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testTwoSubscribers() throws Exception - { + public void testTwoSubscribers() throws Exception { connV11.connect(defUser, defPass, "myclientid"); this.subscribeTopic(connV11, "sub1", "auto", null); @@ -1213,8 +1152,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testSendAndReceiveOnDifferentConnections() throws Exception - { + public void testSendAndReceiveOnDifferentConnections() throws Exception { connV11.connect(defUser, defPass); ClientStompFrame sendFrame = connV11.createFrame("SEND"); @@ -1240,8 +1178,7 @@ public class StompV11Test extends StompV11TestBase //----------------Note: tests below are adapted from StompTest @Test - public void testBeginSameTransactionTwice() throws Exception - { + public void testBeginSameTransactionTwice() throws Exception { connV11.connect(defUser, defPass); beginTransaction(connV11, "tx1"); @@ -1253,8 +1190,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testBodyWithUTF8() throws Exception - { + public void testBodyWithUTF8() throws Exception { connV11.connect(defUser, defPass); this.subscribe(connV11, getName(), "auto"); @@ -1273,8 +1209,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testClientAckNotPartOfTransaction() throws Exception - { + public void testClientAckNotPartOfTransaction() throws Exception { connV11.connect(defUser, defPass); this.subscribe(connV11, getName(), "client"); @@ -1306,8 +1241,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testDisconnectAndError() throws Exception - { + public void testDisconnectAndError() throws Exception { connV11.connect(defUser, defPass); this.subscribe(connV11, getName(), "client"); @@ -1317,45 +1251,36 @@ public class StompV11Test extends StompV11TestBase ClientStompFrame result = connV11.sendFrame(frame); - if (result == null || (!"RECEIPT".equals(result.getCommand())) || (!"1".equals(result.getHeader("receipt-id")))) - { + if (result == null || (!"RECEIPT".equals(result.getCommand())) || (!"1".equals(result.getHeader("receipt-id")))) { fail("Disconnect failed! " + result); } final CountDownLatch latch = new CountDownLatch(1); - Thread thr = new Thread() - { - public void run() - { + Thread thr = new Thread() { + public void run() { ClientStompFrame sendFrame = connV11.createFrame("SEND"); sendFrame.addHeader("destination", getQueuePrefix() + getQueueName()); sendFrame.setBody("Hello World"); - while (latch.getCount() != 0) - { - try - { + while (latch.getCount() != 0) { + try { connV11.sendFrame(sendFrame); Thread.sleep(500); } - catch (InterruptedException e) - { + catch (InterruptedException e) { //retry } - catch (ClosedChannelException e) - { + catch (ClosedChannelException e) { //ok. latch.countDown(); break; } - catch (IOException e) - { + catch (IOException e) { //ok. latch.countDown(); break; } - finally - { + finally { connV11.destroy(); } } @@ -1366,8 +1291,7 @@ public class StompV11Test extends StompV11TestBase latch.await(10, TimeUnit.SECONDS); long count = latch.getCount(); - if (count != 0) - { + if (count != 0) { latch.countDown(); } thr.join(); @@ -1376,8 +1300,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testDurableSubscriber() throws Exception - { + public void testDurableSubscriber() throws Exception { connV11.connect(defUser, defPass); this.subscribe(connV11, "sub1", "client", getName()); @@ -1391,8 +1314,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testDurableSubscriberWithReconnection() throws Exception - { + public void testDurableSubscriberWithReconnection() throws Exception { connV11.connect(defUser, defPass, "myclientid"); this.subscribeTopic(connV11, "sub1", "auto", getName()); @@ -1402,8 +1324,7 @@ public class StompV11Test extends StompV11TestBase ClientStompFrame result = connV11.sendFrame(frame); - if (result == null || (!"RECEIPT".equals(result.getCommand())) || (!"1".equals(result.getHeader("receipt-id")))) - { + if (result == null || (!"RECEIPT".equals(result.getCommand())) || (!"1".equals(result.getHeader("receipt-id")))) { fail("Disconnect failed! " + result); } @@ -1429,8 +1350,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testJMSXGroupIdCanBeSet() throws Exception - { + public void testJMSXGroupIdCanBeSet() throws Exception { MessageConsumer consumer = session.createConsumer(queue); connV11.connect(defUser, defPass); @@ -1450,8 +1370,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testMessagesAreInOrder() throws Exception - { + public void testMessagesAreInOrder() throws Exception { int ctr = 10; String[] data = new String[ctr]; @@ -1459,28 +1378,24 @@ public class StompV11Test extends StompV11TestBase this.subscribe(connV11, "sub1", "auto"); - for (int i = 0; i < ctr; ++i) - { + for (int i = 0; i < ctr; ++i) { data[i] = getName() + i; sendMessage(data[i]); } ClientStompFrame frame = null; - for (int i = 0; i < ctr; ++i) - { + for (int i = 0; i < ctr; ++i) { frame = connV11.receiveFrame(); Assert.assertTrue("Message not in order", frame.getBody().equals(data[i])); } - for (int i = 0; i < ctr; ++i) - { + for (int i = 0; i < ctr; ++i) { data[i] = getName() + ":second:" + i; sendMessage(data[i]); } - for (int i = 0; i < ctr; ++i) - { + for (int i = 0; i < ctr; ++i) { frame = connV11.receiveFrame(); Assert.assertTrue("Message not in order", frame.getBody().equals(data[i])); } @@ -1489,8 +1404,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testSubscribeWithAutoAckAndSelector() throws Exception - { + public void testSubscribeWithAutoAckAndSelector() throws Exception { connV11.connect(defUser, defPass); this.subscribe(connV11, "sub1", "auto", null, "foo = 'zzz'"); @@ -1506,8 +1420,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testRedeliveryWithClientAck() throws Exception - { + public void testRedeliveryWithClientAck() throws Exception { connV11.connect(defUser, defPass); this.subscribe(connV11, "subId", "client"); @@ -1528,18 +1441,15 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testSendManyMessages() throws Exception - { + public void testSendManyMessages() throws Exception { MessageConsumer consumer = session.createConsumer(queue); connV11.connect(defUser, defPass); int count = 1000; final CountDownLatch latch = new CountDownLatch(count); - consumer.setMessageListener(new MessageListener() - { - public void onMessage(Message arg0) - { + consumer.setMessageListener(new MessageListener() { + public void onMessage(Message arg0) { latch.countDown(); } }); @@ -1548,8 +1458,7 @@ public class StompV11Test extends StompV11TestBase frame.addHeader("destination", getQueuePrefix() + getQueueName()); frame.setBody("Hello World"); - for (int i = 1; i <= count; i++) - { + for (int i = 1; i <= count; i++) { connV11.sendFrame(frame); } @@ -1559,8 +1468,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testSendMessage() throws Exception - { + public void testSendMessage() throws Exception { MessageConsumer consumer = session.createConsumer(queue); connV11.connect(defUser, defPass); @@ -1585,8 +1493,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testSendMessageWithContentLength() throws Exception - { + public void testSendMessageWithContentLength() throws Exception { MessageConsumer consumer = session.createConsumer(queue); connV11.connect(defUser, defPass); @@ -1613,8 +1520,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testSendMessageWithCustomHeadersAndSelector() throws Exception - { + public void testSendMessageWithCustomHeadersAndSelector() throws Exception { MessageConsumer consumer = session.createConsumer(queue, "foo = 'abc'"); connV11.connect(defUser, defPass); @@ -1636,8 +1542,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testSendMessageWithLeadingNewLine() throws Exception - { + public void testSendMessageWithLeadingNewLine() throws Exception { MessageConsumer consumer = session.createConsumer(queue); connV11.connect(defUser, defPass); @@ -1665,8 +1570,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testSendMessageWithReceipt() throws Exception - { + public void testSendMessageWithReceipt() throws Exception { MessageConsumer consumer = session.createConsumer(queue); connV11.connect(defUser, defPass); @@ -1695,8 +1599,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testSendMessageWithStandardHeaders() throws Exception - { + public void testSendMessageWithStandardHeaders() throws Exception { MessageConsumer consumer = session.createConsumer(queue); connV11.connect(defUser, defPass); @@ -1731,15 +1634,13 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testSendMessageWithLongHeaders() throws Exception - { + public void testSendMessageWithLongHeaders() throws Exception { MessageConsumer consumer = session.createConsumer(queue); connV11.connect(defUser, defPass); StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < 2048; i++) - { + for (int i = 0; i < 2048; i++) { buffer.append("a"); } @@ -1773,8 +1674,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testSubscribeToTopic() throws Exception - { + public void testSubscribeToTopic() throws Exception { connV11.connect(defUser, defPass); this.subscribeTopic(connV11, "sub1", null, null, true); @@ -1798,8 +1698,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testSubscribeToTopicWithNoLocal() throws Exception - { + public void testSubscribeToTopicWithNoLocal() throws Exception { connV11.connect(defUser, defPass); this.subscribeTopic(connV11, "sub1", null, null, true, true); @@ -1831,8 +1730,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testSubscribeWithAutoAck() throws Exception - { + public void testSubscribeWithAutoAck() throws Exception { connV11.connect(defUser, defPass); this.subscribe(connV11, "sub1", "auto"); @@ -1854,8 +1752,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testSubscribeWithAutoAckAndBytesMessage() throws Exception - { + public void testSubscribeWithAutoAckAndBytesMessage() throws Exception { connV11.connect(defUser, defPass); this.subscribe(connV11, "sub1", "auto"); @@ -1879,8 +1776,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testSubscribeWithClientAck() throws Exception - { + public void testSubscribeWithClientAck() throws Exception { connV11.connect(defUser, defPass); this.subscribe(connV11, "sub1", "client"); @@ -1900,20 +1796,17 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testSubscribeWithClientAckThenConsumingAgainWithAutoAckWithExplicitDisconnect() throws Exception - { + public void testSubscribeWithClientAckThenConsumingAgainWithAutoAckWithExplicitDisconnect() throws Exception { assertSubscribeWithClientAckThenConsumeWithAutoAck(true); } @Test - public void testSubscribeWithClientAckThenConsumingAgainWithAutoAckWithNoDisconnectFrame() throws Exception - { + public void testSubscribeWithClientAckThenConsumingAgainWithAutoAckWithNoDisconnectFrame() throws Exception { assertSubscribeWithClientAckThenConsumeWithAutoAck(false); } @Test - public void testSubscribeWithID() throws Exception - { + public void testSubscribeWithID() throws Exception { connV11.connect(defUser, defPass); this.subscribe(connV11, "mysubid", "auto"); @@ -1928,8 +1821,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testSubscribeWithMessageSentWithProperties() throws Exception - { + public void testSubscribeWithMessageSentWithProperties() throws Exception { connV11.connect(defUser, defPass); this.subscribe(connV11, "sub1", "auto"); @@ -1964,8 +1856,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testSuccessiveTransactionsWithSameID() throws Exception - { + public void testSuccessiveTransactionsWithSameID() throws Exception { MessageConsumer consumer = session.createConsumer(queue); connV11.connect(defUser, defPass); @@ -2005,8 +1896,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testTransactionCommit() throws Exception - { + public void testTransactionCommit() throws Exception { MessageConsumer consumer = session.createConsumer(queue); connV11.connect(defUser, defPass); @@ -2035,8 +1925,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testTransactionRollback() throws Exception - { + public void testTransactionRollback() throws Exception { MessageConsumer consumer = session.createConsumer(queue); connV11.connect(defUser, defPass); @@ -2075,8 +1964,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testUnsubscribe() throws Exception - { + public void testUnsubscribe() throws Exception { connV11.connect(defUser, defPass); this.subscribe(connV11, "sub1", "auto"); @@ -2103,45 +1991,41 @@ public class StompV11Test extends StompV11TestBase //-----------------private help methods - private void abortTransaction(StompClientConnection conn, String txID) throws IOException, InterruptedException - { + private void abortTransaction(StompClientConnection conn, String txID) throws IOException, InterruptedException { ClientStompFrame abortFrame = conn.createFrame("ABORT"); abortFrame.addHeader("transaction", txID); conn.sendFrame(abortFrame); } - private void beginTransaction(StompClientConnection conn, String txID) throws IOException, InterruptedException - { + private void beginTransaction(StompClientConnection conn, String txID) throws IOException, InterruptedException { ClientStompFrame beginFrame = conn.createFrame("BEGIN"); beginFrame.addHeader("transaction", txID); conn.sendFrame(beginFrame); } - private void commitTransaction(StompClientConnection conn, String txID) throws IOException, InterruptedException - { + private void commitTransaction(StompClientConnection conn, String txID) throws IOException, InterruptedException { commitTransaction(conn, txID, false); } - private void commitTransaction(StompClientConnection conn, String txID, boolean receipt) throws IOException, InterruptedException - { + private void commitTransaction(StompClientConnection conn, + String txID, + boolean receipt) throws IOException, InterruptedException { ClientStompFrame beginFrame = conn.createFrame("COMMIT"); beginFrame.addHeader("transaction", txID); - if (receipt) - { + if (receipt) { beginFrame.addHeader("receipt", "1234"); } ClientStompFrame resp = conn.sendFrame(beginFrame); - if (receipt) - { + if (receipt) { assertEquals("1234", resp.getHeader("receipt-id")); } } - private void ack(StompClientConnection conn, String subId, - ClientStompFrame frame) throws IOException, InterruptedException - { + private void ack(StompClientConnection conn, + String subId, + ClientStompFrame frame) throws IOException, InterruptedException { String messageID = frame.getHeader("message-id"); ClientStompFrame ackFrame = conn.createFrame("ACK"); @@ -2150,27 +2034,26 @@ public class StompV11Test extends StompV11TestBase ackFrame.addHeader("message-id", messageID); ClientStompFrame response = conn.sendFrame(ackFrame); - if (response != null) - { + if (response != null) { throw new IOException("failed to ack " + response); } } - private void ack(StompClientConnection conn, String subId, String mid, String txID) throws IOException, InterruptedException - { + private void ack(StompClientConnection conn, + String subId, + String mid, + String txID) throws IOException, InterruptedException { ClientStompFrame ackFrame = conn.createFrame("ACK"); ackFrame.addHeader("subscription", subId); ackFrame.addHeader("message-id", mid); - if (txID != null) - { + if (txID != null) { ackFrame.addHeader("transaction", txID); } conn.sendFrame(ackFrame); } - private void nack(StompClientConnection conn, String subId, String mid) throws IOException, InterruptedException - { + private void nack(StompClientConnection conn, String subId, String mid) throws IOException, InterruptedException { ClientStompFrame ackFrame = conn.createFrame("NACK"); ackFrame.addHeader("subscription", subId); ackFrame.addHeader("message-id", mid); @@ -2178,135 +2061,135 @@ public class StompV11Test extends StompV11TestBase conn.sendFrame(ackFrame); } - private void subscribe(StompClientConnection conn, String subId, String ack) throws IOException, InterruptedException - { + private void subscribe(StompClientConnection conn, + String subId, + String ack) throws IOException, InterruptedException { subscribe(conn, subId, ack, null, null); } - private void subscribe(StompClientConnection conn, String subId, - String ack, String durableId) throws IOException, InterruptedException - { + private void subscribe(StompClientConnection conn, + String subId, + String ack, + String durableId) throws IOException, InterruptedException { subscribe(conn, subId, ack, durableId, null); } - private void subscribe(StompClientConnection conn, String subId, - String ack, String durableId, boolean receipt) throws IOException, InterruptedException - { + private void subscribe(StompClientConnection conn, + String subId, + String ack, + String durableId, + boolean receipt) throws IOException, InterruptedException { subscribe(conn, subId, ack, durableId, null, receipt); } - private void subscribe(StompClientConnection conn, String subId, String ack, - String durableId, String selector) throws IOException, - InterruptedException - { + private void subscribe(StompClientConnection conn, + String subId, + String ack, + String durableId, + String selector) throws IOException, InterruptedException { subscribe(conn, subId, ack, durableId, selector, false); } - private void subscribe(StompClientConnection conn, String subId, - String ack, String durableId, String selector, boolean receipt) throws IOException, InterruptedException - { + private void subscribe(StompClientConnection conn, + String subId, + String ack, + String durableId, + String selector, + boolean receipt) throws IOException, InterruptedException { ClientStompFrame subFrame = conn.createFrame("SUBSCRIBE"); subFrame.addHeader("id", subId); subFrame.addHeader("destination", getQueuePrefix() + getQueueName()); - if (ack != null) - { + if (ack != null) { subFrame.addHeader("ack", ack); } - if (durableId != null) - { + if (durableId != null) { subFrame.addHeader("durable-subscriber-name", durableId); } - if (selector != null) - { + if (selector != null) { subFrame.addHeader("selector", selector); } - if (receipt) - { + if (receipt) { subFrame.addHeader("receipt", "1234"); } subFrame = conn.sendFrame(subFrame); - if (receipt) - { + if (receipt) { assertEquals("1234", subFrame.getHeader("receipt-id")); } } - private void subscribeTopic(StompClientConnection conn, String subId, - String ack, String durableId) throws IOException, InterruptedException - { + private void subscribeTopic(StompClientConnection conn, + String subId, + String ack, + String durableId) throws IOException, InterruptedException { subscribeTopic(conn, subId, ack, durableId, false); } - private void subscribeTopic(StompClientConnection conn, String subId, - String ack, String durableId, boolean receipt) throws IOException, InterruptedException - { + private void subscribeTopic(StompClientConnection conn, + String subId, + String ack, + String durableId, + boolean receipt) throws IOException, InterruptedException { subscribeTopic(conn, subId, ack, durableId, receipt, false); } - private void subscribeTopic(StompClientConnection conn, String subId, - String ack, String durableId, boolean receipt, boolean noLocal) throws IOException, InterruptedException - { + private void subscribeTopic(StompClientConnection conn, + String subId, + String ack, + String durableId, + boolean receipt, + boolean noLocal) throws IOException, InterruptedException { ClientStompFrame subFrame = conn.createFrame("SUBSCRIBE"); subFrame.addHeader("id", subId); subFrame.addHeader("destination", getTopicPrefix() + getTopicName()); - if (ack != null) - { + if (ack != null) { subFrame.addHeader("ack", ack); } - if (durableId != null) - { + if (durableId != null) { subFrame.addHeader("durable-subscriber-name", durableId); } - if (receipt) - { + if (receipt) { subFrame.addHeader("receipt", "1234"); } - if (noLocal) - { + if (noLocal) { subFrame.addHeader("no-local", "true"); } ClientStompFrame frame = conn.sendFrame(subFrame); - if (receipt) - { + if (receipt) { assertTrue(frame.getHeader("receipt-id").equals("1234")); } } - private void unsubscribe(StompClientConnection conn, String subId) throws IOException, InterruptedException - { + private void unsubscribe(StompClientConnection conn, String subId) throws IOException, InterruptedException { ClientStompFrame subFrame = conn.createFrame("UNSUBSCRIBE"); subFrame.addHeader("id", subId); conn.sendFrame(subFrame); } - private void unsubscribe(StompClientConnection conn, String subId, - boolean receipt) throws IOException, InterruptedException - { + private void unsubscribe(StompClientConnection conn, + String subId, + boolean receipt) throws IOException, InterruptedException { ClientStompFrame subFrame = conn.createFrame("UNSUBSCRIBE"); subFrame.addHeader("id", subId); - if (receipt) - { + if (receipt) { subFrame.addHeader("receipt", "4321"); } ClientStompFrame f = conn.sendFrame(subFrame); - if (receipt) - { + if (receipt) { System.out.println("response: " + f); assertEquals("RECEIPT", f.getCommand()); assertEquals("4321", f.getHeader("receipt-id")); } } - protected void assertSubscribeWithClientAckThenConsumeWithAutoAck(boolean sendDisconnect) throws Exception - { + protected void assertSubscribeWithClientAckThenConsumeWithAutoAck(boolean sendDisconnect) throws Exception { connV11.connect(defUser, defPass); this.subscribe(connV11, "sub1", "client"); @@ -2319,13 +2202,11 @@ public class StompV11Test extends StompV11TestBase log.info("Reconnecting!"); - if (sendDisconnect) - { + if (sendDisconnect) { connV11.disconnect(); connV11 = StompClientConnectionFactory.createClientConnection("1.1", hostname, port); } - else - { + else { connV11.destroy(); connV11 = StompClientConnectionFactory.createClientConnection("1.1", hostname, port); } @@ -2355,8 +2236,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testSendMessageToNonExistentJmsQueueWithoutAutoCreation() throws Exception - { + public void testSendMessageToNonExistentJmsQueueWithoutAutoCreation() throws Exception { AddressSettings addressSettings = new AddressSettings(); addressSettings.setAutoCreateJmsQueues(false); server.getActiveMQServer().getAddressSettingsRepository().addMatch("#", addressSettings); @@ -2378,8 +2258,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testSendMessageToNonExistentJmsQueueWithAutoCreation() throws Exception - { + public void testSendMessageToNonExistentJmsQueueWithAutoCreation() throws Exception { connV11.connect(defUser, defPass); ClientStompFrame frame = connV11.createFrame("SEND"); @@ -2398,8 +2277,7 @@ public class StompV11Test extends StompV11TestBase } @Test - public void testSendAndReceiveWithEscapedCharactersInSenderId() throws Exception - { + public void testSendAndReceiveWithEscapedCharactersInSenderId() throws Exception { connV11.connect(defUser, defPass); ClientStompFrame frame = connV11.createFrame("SEND"); frame.addHeader("destination", getQueuePrefix() + getQueueName()); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/v11/StompV11TestBase.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/v11/StompV11TestBase.java index 8fee859476..034eb80543 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/v11/StompV11TestBase.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/v11/StompV11TestBase.java @@ -50,8 +50,8 @@ import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; -public abstract class StompV11TestBase extends ActiveMQTestBase -{ +public abstract class StompV11TestBase extends ActiveMQTestBase { + protected String hostname = "127.0.0.1"; protected int port = 61613; @@ -78,8 +78,7 @@ public abstract class StompV11TestBase extends ActiveMQTestBase // ------------------------------------------------------------------------- @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(); @@ -94,85 +93,70 @@ public abstract class StompV11TestBase extends ActiveMQTestBase } /** - * @return - * @throws Exception - */ - protected JMSServerManager createServer() throws Exception - { + * @return + * @throws Exception + */ + protected JMSServerManager createServer() throws Exception { Map params = new HashMap(); params.put(TransportConstants.PROTOCOLS_PROP_NAME, StompProtocolManagerFactory.STOMP_PROTOCOL_NAME); params.put(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_STOMP_PORT); params.put(TransportConstants.STOMP_CONSUMERS_CREDIT, "-1"); TransportConfiguration stompTransport = new TransportConfiguration(NettyAcceptorFactory.class.getName(), params); - Configuration config = createBasicConfig() - .setPersistenceEnabled(persistenceEnabled) - .addAcceptorConfiguration(stompTransport) - .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())); + Configuration config = createBasicConfig().setPersistenceEnabled(persistenceEnabled).addAcceptorConfiguration(stompTransport).addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())); ActiveMQServer activeMQServer = addServer(ActiveMQServers.newActiveMQServer(config, defUser, defPass)); JMSConfiguration jmsConfig = new JMSConfigurationImpl(); - jmsConfig.getQueueConfigurations().add(new JMSQueueConfigurationImpl() - .setName(getQueueName()) - .setBindings(getQueueName())); - jmsConfig.getTopicConfigurations().add(new TopicConfigurationImpl() - .setName(getTopicName()) - .setBindings(getTopicName())); + jmsConfig.getQueueConfigurations().add(new JMSQueueConfigurationImpl().setName(getQueueName()).setBindings(getQueueName())); + jmsConfig.getTopicConfigurations().add(new TopicConfigurationImpl().setName(getTopicName()).setBindings(getTopicName())); server = new JMSServerManagerImpl(activeMQServer, jmsConfig); server.setRegistry(new JndiBindingRegistry(new InVMNamingContext())); return server; } - protected ConnectionFactory createConnectionFactory() - { + protected ConnectionFactory createConnectionFactory() { return new ActiveMQJMSConnectionFactory(false, new TransportConfiguration(InVMConnectorFactory.class.getName())); } - protected String getQueueName() - { + protected String getQueueName() { return "test"; } - protected String getQueuePrefix() - { + protected String getQueuePrefix() { return "jms.queue."; } - protected String getTopicName() - { + protected String getTopicName() { return "testtopic"; } - protected String getTopicPrefix() - { + protected String getTopicPrefix() { return "jms.topic."; } - public void sendMessage(String msg) throws Exception - { + public void sendMessage(String msg) throws Exception { sendMessage(msg, queue); } - public void sendMessage(String msg, Destination destination) throws Exception - { + public void sendMessage(String msg, Destination destination) throws Exception { MessageProducer producer = session.createProducer(destination); TextMessage message = session.createTextMessage(msg); producer.send(message); } - public void sendMessage(byte[] data, Destination destination) throws Exception - { + public void sendMessage(byte[] data, Destination destination) throws Exception { sendMessage(data, "foo", "xyz", destination); } - public void sendMessage(String msg, String propertyName, String propertyValue) throws Exception - { + public void sendMessage(String msg, String propertyName, String propertyValue) throws Exception { sendMessage(msg.getBytes(StandardCharsets.UTF_8), propertyName, propertyValue, queue); } - public void sendMessage(byte[] data, String propertyName, String propertyValue, Destination destination) throws Exception - { + public void sendMessage(byte[] data, + String propertyName, + String propertyValue, + Destination destination) throws Exception { MessageProducer producer = session.createProducer(destination); BytesMessage message = session.createBytesMessage(); message.setStringProperty(propertyName, propertyValue); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/v12/StompV12Test.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/v12/StompV12Test.java index ca9ae783b0..59f4eb60b7 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/v12/StompV12Test.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/v12/StompV12Test.java @@ -47,41 +47,35 @@ import org.junit.Test; /** * Testing Stomp version 1.2 functionalities */ -public class StompV12Test extends StompV11TestBase -{ +public class StompV12Test extends StompV11TestBase { + private static final transient IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private StompClientConnectionV12 connV12; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); connV12 = (StompClientConnectionV12) StompClientConnectionFactory.createClientConnection("1.2", hostname, port); } @Override @After - public void tearDown() throws Exception - { - try - { + public void tearDown() throws Exception { + try { log.debug("Connection 1.2 : " + connV12.isConnected()); - if (connV12 != null && connV12.isConnected()) - { + if (connV12 != null && connV12.isConnected()) { connV12.disconnect(); } } - finally - { + finally { super.tearDown(); } } @Test - public void testConnection() throws Exception - { + public void testConnection() throws Exception { server.getActiveMQServer().getConfiguration().setSecurityEnabled(true); StompClientConnection connection = StompClientConnectionFactory.createClientConnection("1.0", hostname, port); @@ -119,8 +113,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testConnectionAsInSpec() throws Exception - { + public void testConnectionAsInSpec() throws Exception { StompClientConnection conn = StompClientConnectionFactory.createClientConnection("1.0", hostname, port); ClientStompFrame frame = conn.createFrame("CONNECT"); @@ -154,8 +147,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testNegotiation() throws Exception - { + public void testNegotiation() throws Exception { StompClientConnection conn = StompClientConnectionFactory.createClientConnection("1.0", hostname, port); // case 1 accept-version absent. It is a 1.0 connect ClientStompFrame frame = conn.createFrame("CONNECT"); @@ -240,8 +232,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testSendAndReceive() throws Exception - { + public void testSendAndReceive() throws Exception { connV12.connect(defUser, defPass); ClientStompFrame frame = connV12.createFrame("SEND"); frame.addHeader("destination", getQueuePrefix() + getQueueName()); @@ -302,8 +293,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testHeaderContentType() throws Exception - { + public void testHeaderContentType() throws Exception { connV12.connect(defUser, defPass); ClientStompFrame frame = connV12.createFrame("SEND"); frame.addHeader("destination", getQueuePrefix() + getQueueName()); @@ -339,8 +329,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testHeaderContentLength() throws Exception - { + public void testHeaderContentLength() throws Exception { connV12.connect(defUser, defPass); ClientStompFrame frame = connV12.createFrame("SEND"); @@ -399,8 +388,7 @@ public class StompV12Test extends StompV11TestBase //test that repetitive headers @Test - public void testHeaderRepetitive() throws Exception - { + public void testHeaderRepetitive() throws Exception { AddressSettings addressSettings = new AddressSettings(); addressSettings.setAutoCreateJmsQueues(false); server.getActiveMQServer().getAddressSettingsRepository().addMatch("#", addressSettings); @@ -468,8 +456,7 @@ public class StompV12Test extends StompV11TestBase //padding shouldn't be trimmed @Test - public void testHeadersPadding() throws Exception - { + public void testHeadersPadding() throws Exception { connV12.connect(defUser, defPass); ClientStompFrame frame = connV12.createFrame("SEND"); @@ -526,8 +513,7 @@ public class StompV12Test extends StompV11TestBase * Since 1.2 the CR ('\r') needs to be escaped. */ @Test - public void testHeaderEncoding() throws Exception - { + public void testHeaderEncoding() throws Exception { connV12.connect(defUser, defPass); ClientStompFrame frame = connV12.createFrame("SEND"); @@ -576,8 +562,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testHeartBeat() throws Exception - { + public void testHeartBeat() throws Exception { StompClientConnection conn = StompClientConnectionFactory.createClientConnection("1.2", hostname, port); //no heart beat at all if heat-beat absent ClientStompFrame frame = conn.createFrame("CONNECT"); @@ -640,13 +625,11 @@ public class StompV12Test extends StompV11TestBase frame.setBody("Hello World"); //send will fail - try - { + try { conn.sendFrame(frame); Assert.fail("connection should have been destroyed by now"); } - catch (IOException e) - { + catch (IOException e) { //ignore } @@ -685,8 +668,7 @@ public class StompV12Test extends StompV11TestBase //server ping @Test - public void testHeartBeat2() throws Exception - { + public void testHeartBeat2() throws Exception { //heart-beat (1,1) ClientStompFrame frame = connV12.createFrame("CONNECT"); frame.addHeader("host", "127.0.0.1"); @@ -741,11 +723,9 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testSendWithHeartBeatsAndReceive() throws Exception - { + public void testSendWithHeartBeatsAndReceive() throws Exception { StompClientConnection newConn = null; - try - { + try { ClientStompFrame frame = connV12.createFrame("CONNECT"); frame.addHeader("host", "127.0.0.1"); frame.addHeader("login", this.defUser); @@ -761,16 +741,14 @@ public class StompV12Test extends StompV11TestBase frame.addHeader("destination", getQueuePrefix() + getQueueName()); frame.addHeader("content-type", "text/plain"); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { frame.setBody("Hello World " + i + "!"); connV12.sendFrame(frame); Thread.sleep(500); } // subscribe - newConn = StompClientConnectionFactory.createClientConnection("1.2", - hostname, port); + newConn = StompClientConnectionFactory.createClientConnection("1.2", hostname, port); newConn.connect(defUser, defPass); ClientStompFrame subFrame = newConn.createFrame("SUBSCRIBE"); @@ -784,8 +762,7 @@ public class StompV12Test extends StompV11TestBase frame = newConn.receiveFrame(); - while (frame != null) - { + while (frame != null) { cnt++; Thread.sleep(500); frame = newConn.receiveFrame(5000); @@ -798,8 +775,7 @@ public class StompV12Test extends StompV11TestBase unsubFrame.addHeader("id", "a-sub"); newConn.sendFrame(unsubFrame); } - finally - { + finally { if (newConn != null) newConn.disconnect(); connV12.disconnect(); @@ -807,15 +783,13 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testSendAndReceiveWithHeartBeats() throws Exception - { + public void testSendAndReceiveWithHeartBeats() throws Exception { connV12.connect(defUser, defPass); ClientStompFrame frame = connV12.createFrame("SEND"); frame.addHeader("destination", getQueuePrefix() + getQueueName()); frame.addHeader("content-type", "text/plain"); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { frame.setBody("Hello World " + i + "!"); connV12.sendFrame(frame); Thread.sleep(500); @@ -823,8 +797,7 @@ public class StompV12Test extends StompV11TestBase //subscribe StompClientConnection newConn = StompClientConnectionFactory.createClientConnection("1.1", hostname, port); - try - { + try { frame = newConn.createFrame("CONNECT"); frame.addHeader("host", "127.0.0.1"); frame.addHeader("login", this.defUser); @@ -849,8 +822,7 @@ public class StompV12Test extends StompV11TestBase frame = newConn.receiveFrame(); - while (frame != null) - { + while (frame != null) { cnt++; Thread.sleep(500); frame = newConn.receiveFrame(5000); @@ -863,18 +835,15 @@ public class StompV12Test extends StompV11TestBase unsubFrame.addHeader("id", "a-sub"); newConn.sendFrame(unsubFrame); } - finally - { + finally { newConn.disconnect(); } } @Test - public void testSendWithHeartBeatsAndReceiveWithHeartBeats() throws Exception - { + public void testSendWithHeartBeatsAndReceiveWithHeartBeats() throws Exception { StompClientConnection newConn = null; - try - { + try { ClientStompFrame frame = connV12.createFrame("CONNECT"); frame.addHeader("host", "127.0.0.1"); frame.addHeader("login", this.defUser); @@ -890,16 +859,14 @@ public class StompV12Test extends StompV11TestBase frame.addHeader("destination", getQueuePrefix() + getQueueName()); frame.addHeader("content-type", "text/plain"); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { frame.setBody("Hello World " + i + "!"); connV12.sendFrame(frame); Thread.sleep(500); } // subscribe - newConn = StompClientConnectionFactory.createClientConnection("1.2", - hostname, port); + newConn = StompClientConnectionFactory.createClientConnection("1.2", hostname, port); frame = newConn.createFrame("CONNECT"); frame.addHeader("host", "127.0.0.1"); frame.addHeader("login", this.defUser); @@ -924,8 +891,7 @@ public class StompV12Test extends StompV11TestBase frame = newConn.receiveFrame(); - while (frame != null) - { + while (frame != null) { cnt++; Thread.sleep(500); frame = newConn.receiveFrame(5000); @@ -937,8 +903,7 @@ public class StompV12Test extends StompV11TestBase unsubFrame.addHeader("id", "a-sub"); newConn.sendFrame(unsubFrame); } - finally - { + finally { if (newConn != null) newConn.disconnect(); connV12.disconnect(); @@ -946,8 +911,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testNack() throws Exception - { + public void testNack() throws Exception { connV12.connect(defUser, defPass); subscribe(connV12, "sub1", "client"); @@ -971,8 +935,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testNackWithWrongSubId() throws Exception - { + public void testNackWithWrongSubId() throws Exception { connV12.connect(defUser, defPass); subscribe(connV12, "sub1", "client"); @@ -1000,8 +963,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testNackWithWrongMessageId() throws Exception - { + public void testNackWithWrongMessageId() throws Exception { connV12.connect(defUser, defPass); subscribe(connV12, "sub1", "client"); @@ -1031,8 +993,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testAck() throws Exception - { + public void testAck() throws Exception { connV12.connect(defUser, defPass); subscribe(connV12, "sub1", "client"); @@ -1058,8 +1019,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testAckNoIDHeader() throws Exception - { + public void testAckNoIDHeader() throws Exception { connV12.connect(defUser, defPass); subscribe(connV12, "sub1", "client-individual"); @@ -1091,8 +1051,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testAckWithWrongMessageId() throws Exception - { + public void testAckWithWrongMessageId() throws Exception { connV12.connect(defUser, defPass); subscribe(connV12, "sub1", "client"); @@ -1120,8 +1079,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testErrorWithReceipt() throws Exception - { + public void testErrorWithReceipt() throws Exception { connV12.connect(defUser, defPass); subscribe(connV12, "sub1", "client"); @@ -1132,7 +1090,6 @@ public class StompV12Test extends StompV11TestBase String messageID = frame.getHeader("message-id"); - ClientStompFrame ackFrame = connV12.createFrame("ACK"); //give it a wrong sub id ackFrame.addHeader("subscription", "sub2"); @@ -1158,8 +1115,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testErrorWithReceipt2() throws Exception - { + public void testErrorWithReceipt2() throws Exception { connV12.connect(defUser, defPass); subscribe(connV12, "sub1", "client"); @@ -1170,7 +1126,6 @@ public class StompV12Test extends StompV11TestBase String messageID = frame.getHeader("message-id"); - ClientStompFrame ackFrame = connV12.createFrame("ACK"); //give it a wrong sub id ackFrame.addHeader("subscription", "sub1"); @@ -1196,23 +1151,20 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testAckModeClient() throws Exception - { + public void testAckModeClient() throws Exception { connV12.connect(defUser, defPass); subscribe(connV12, "sub1", "client"); int num = 50; //send a bunch of messages - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { this.sendMessage("client-ack" + i); } ClientStompFrame frame = null; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { frame = connV12.receiveFrame(); Assert.assertNotNull(frame); } @@ -1231,29 +1183,25 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testAckModeClient2() throws Exception - { + public void testAckModeClient2() throws Exception { connV12.connect(defUser, defPass); subscribe(connV12, "sub1", "client"); int num = 50; //send a bunch of messages - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { this.sendMessage("client-ack" + i); } ClientStompFrame frame = null; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { frame = connV12.receiveFrame(); Assert.assertNotNull(frame); //ack the 49th - if (i == num - 2) - { + if (i == num - 2) { ack(connV12, frame); } } @@ -1272,23 +1220,20 @@ public class StompV12Test extends StompV11TestBase //when ack is missing the mode default to auto @Test - public void testAckModeDefault() throws Exception - { + public void testAckModeDefault() throws Exception { connV12.connect(defUser, defPass); subscribe(connV12, "sub1", null); int num = 50; //send a bunch of messages - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { this.sendMessage("auto-ack" + i); } ClientStompFrame frame = null; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { frame = connV12.receiveFrame(); Assert.assertNotNull(frame); } @@ -1304,23 +1249,20 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testAckModeAuto() throws Exception - { + public void testAckModeAuto() throws Exception { connV12.connect(defUser, defPass); subscribe(connV12, "sub1", "auto"); int num = 50; //send a bunch of messages - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { this.sendMessage("auto-ack" + i); } ClientStompFrame frame = null; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { frame = connV12.receiveFrame(); Assert.assertNotNull(frame); } @@ -1336,30 +1278,26 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testAckModeClientIndividual() throws Exception - { + public void testAckModeClientIndividual() throws Exception { connV12.connect(defUser, defPass); subscribe(connV12, "sub1", "client-individual"); int num = 50; //send a bunch of messages - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { this.sendMessage("client-individual-ack" + i); } ClientStompFrame frame = null; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { frame = connV12.receiveFrame(); Assert.assertNotNull(frame); System.out.println(i + " == received: " + frame); //ack on even numbers - if (i % 2 == 0) - { + if (i % 2 == 0) { ack(connV12, frame); } } @@ -1372,8 +1310,7 @@ public class StompV12Test extends StompV11TestBase MessageConsumer consumer = session.createConsumer(queue); TextMessage message = null; - for (int i = 0; i < num / 2; i++) - { + for (int i = 0; i < num / 2; i++) { message = (TextMessage) consumer.receive(1000); Assert.assertNotNull(message); System.out.println("Legal: " + message.getText()); @@ -1385,8 +1322,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testTwoSubscribers() throws Exception - { + public void testTwoSubscribers() throws Exception { connV12.connect(defUser, defPass, "myclientid"); this.subscribeTopic(connV12, "sub1", "auto", null); @@ -1425,8 +1361,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testSendAndReceiveOnDifferentConnections() throws Exception - { + public void testSendAndReceiveOnDifferentConnections() throws Exception { connV12.connect(defUser, defPass); ClientStompFrame sendFrame = connV12.createFrame("SEND"); @@ -1452,8 +1387,7 @@ public class StompV12Test extends StompV11TestBase //----------------Note: tests below are adapted from StompTest @Test - public void testBeginSameTransactionTwice() throws Exception - { + public void testBeginSameTransactionTwice() throws Exception { connV12.connect(defUser, defPass); beginTransaction(connV12, "tx1"); @@ -1465,8 +1399,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testBodyWithUTF8() throws Exception - { + public void testBodyWithUTF8() throws Exception { connV12.connect(defUser, defPass); this.subscribe(connV12, getName(), "auto"); @@ -1485,8 +1418,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testClientAckNotPartOfTransaction() throws Exception - { + public void testClientAckNotPartOfTransaction() throws Exception { connV12.connect(defUser, defPass); this.subscribe(connV12, getName(), "client"); @@ -1519,8 +1451,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testDisconnectAndError() throws Exception - { + public void testDisconnectAndError() throws Exception { connV12.connect(defUser, defPass); this.subscribe(connV12, getName(), "client"); @@ -1530,45 +1461,36 @@ public class StompV12Test extends StompV11TestBase ClientStompFrame result = connV12.sendFrame(frame); - if (result == null || (!"RECEIPT".equals(result.getCommand())) || (!"1".equals(result.getHeader("receipt-id")))) - { + if (result == null || (!"RECEIPT".equals(result.getCommand())) || (!"1".equals(result.getHeader("receipt-id")))) { Assert.fail("Disconnect failed! " + result); } final CountDownLatch latch = new CountDownLatch(1); - Thread thr = new Thread() - { - public void run() - { + Thread thr = new Thread() { + public void run() { ClientStompFrame sendFrame = connV12.createFrame("SEND"); sendFrame.addHeader("destination", getQueuePrefix() + getQueueName()); sendFrame.setBody("Hello World"); - while (latch.getCount() != 0) - { - try - { + while (latch.getCount() != 0) { + try { connV12.sendFrame(sendFrame); Thread.sleep(500); } - catch (InterruptedException e) - { + catch (InterruptedException e) { //retry } - catch (ClosedChannelException e) - { + catch (ClosedChannelException e) { //ok. latch.countDown(); break; } - catch (IOException e) - { + catch (IOException e) { //ok. latch.countDown(); break; } - finally - { + finally { connV12.destroy(); } } @@ -1579,8 +1501,7 @@ public class StompV12Test extends StompV11TestBase latch.await(10, TimeUnit.SECONDS); long count = latch.getCount(); - if (count != 0) - { + if (count != 0) { latch.countDown(); } thr.join(); @@ -1589,8 +1510,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testDurableSubscriber() throws Exception - { + public void testDurableSubscriber() throws Exception { connV12.connect(defUser, defPass); this.subscribe(connV12, "sub1", "client", getName()); @@ -1604,8 +1524,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testDurableSubscriberWithReconnection() throws Exception - { + public void testDurableSubscriberWithReconnection() throws Exception { connV12.connect(defUser, defPass, "myclientid"); this.subscribeTopic(connV12, "sub1", "auto", getName()); @@ -1615,8 +1534,7 @@ public class StompV12Test extends StompV11TestBase ClientStompFrame result = connV12.sendFrame(frame); - if (result == null || (!"RECEIPT".equals(result.getCommand())) || (!"1".equals(result.getHeader("receipt-id")))) - { + if (result == null || (!"RECEIPT".equals(result.getCommand())) || (!"1".equals(result.getHeader("receipt-id")))) { Assert.fail("Disconnect failed! " + result); } @@ -1642,8 +1560,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testJMSXGroupIdCanBeSet() throws Exception - { + public void testJMSXGroupIdCanBeSet() throws Exception { MessageConsumer consumer = session.createConsumer(queue); connV12.connect(defUser, defPass); @@ -1663,8 +1580,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testMessagesAreInOrder() throws Exception - { + public void testMessagesAreInOrder() throws Exception { int ctr = 10; String[] data = new String[ctr]; @@ -1672,28 +1588,24 @@ public class StompV12Test extends StompV11TestBase this.subscribe(connV12, "sub1", "auto"); - for (int i = 0; i < ctr; ++i) - { + for (int i = 0; i < ctr; ++i) { data[i] = getName() + i; sendMessage(data[i]); } ClientStompFrame frame = null; - for (int i = 0; i < ctr; ++i) - { + for (int i = 0; i < ctr; ++i) { frame = connV12.receiveFrame(); Assert.assertTrue("Message not in order", frame.getBody().equals(data[i])); } - for (int i = 0; i < ctr; ++i) - { + for (int i = 0; i < ctr; ++i) { data[i] = getName() + ":second:" + i; sendMessage(data[i]); } - for (int i = 0; i < ctr; ++i) - { + for (int i = 0; i < ctr; ++i) { frame = connV12.receiveFrame(); Assert.assertTrue("Message not in order", frame.getBody().equals(data[i])); } @@ -1702,8 +1614,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testSubscribeWithAutoAckAndSelector() throws Exception - { + public void testSubscribeWithAutoAckAndSelector() throws Exception { connV12.connect(defUser, defPass); this.subscribe(connV12, "sub1", "auto", null, "foo = 'zzz'"); @@ -1719,8 +1630,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testRedeliveryWithClientAck() throws Exception - { + public void testRedeliveryWithClientAck() throws Exception { connV12.connect(defUser, defPass); this.subscribe(connV12, "subId", "client"); @@ -1741,26 +1651,21 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testSendManyMessages() throws Exception - { + public void testSendManyMessages() throws Exception { MessageConsumer consumer = session.createConsumer(queue); connV12.connect(defUser, defPass); int count = 1000; final CountDownLatch latch = new CountDownLatch(count); - consumer.setMessageListener(new MessageListener() - { - public void onMessage(Message arg0) - { + consumer.setMessageListener(new MessageListener() { + public void onMessage(Message arg0) { TextMessage m = (TextMessage) arg0; latch.countDown(); - try - { + try { System.out.println("___> latch now: " + latch.getCount() + " m: " + m.getText()); } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("here failed"); e.printStackTrace(); } @@ -1771,8 +1676,7 @@ public class StompV12Test extends StompV11TestBase frame.addHeader("destination", getQueuePrefix() + getQueueName()); frame.setBody("Hello World"); - for (int i = 1; i <= count; i++) - { + for (int i = 1; i <= count; i++) { connV12.sendFrame(frame); } @@ -1782,8 +1686,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testSendMessage() throws Exception - { + public void testSendMessage() throws Exception { MessageConsumer consumer = session.createConsumer(queue); connV12.connect(defUser, defPass); @@ -1808,8 +1711,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testSendMessageWithContentLength() throws Exception - { + public void testSendMessageWithContentLength() throws Exception { MessageConsumer consumer = session.createConsumer(queue); connV12.connect(defUser, defPass); @@ -1836,8 +1738,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testSendMessageWithCustomHeadersAndSelector() throws Exception - { + public void testSendMessageWithCustomHeadersAndSelector() throws Exception { MessageConsumer consumer = session.createConsumer(queue, "foo = 'abc'"); connV12.connect(defUser, defPass); @@ -1859,8 +1760,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testSendMessageWithLeadingNewLine() throws Exception - { + public void testSendMessageWithLeadingNewLine() throws Exception { MessageConsumer consumer = session.createConsumer(queue); connV12.connect(defUser, defPass); @@ -1888,8 +1788,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testSendMessageWithReceipt() throws Exception - { + public void testSendMessageWithReceipt() throws Exception { MessageConsumer consumer = session.createConsumer(queue); connV12.connect(defUser, defPass); @@ -1918,8 +1817,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testSendMessageWithStandardHeaders() throws Exception - { + public void testSendMessageWithStandardHeaders() throws Exception { MessageConsumer consumer = session.createConsumer(queue); connV12.connect(defUser, defPass); @@ -1954,15 +1852,13 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testSendMessageWithLongHeaders() throws Exception - { + public void testSendMessageWithLongHeaders() throws Exception { MessageConsumer consumer = session.createConsumer(queue); connV12.connect(defUser, defPass); StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < 2048; i++) - { + for (int i = 0; i < 2048; i++) { buffer.append("a"); } @@ -1996,8 +1892,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testSubscribeToTopic() throws Exception - { + public void testSubscribeToTopic() throws Exception { connV12.connect(defUser, defPass); this.subscribeTopic(connV12, "sub1", null, null, true); @@ -2021,8 +1916,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testSubscribeToTopicWithNoLocal() throws Exception - { + public void testSubscribeToTopicWithNoLocal() throws Exception { connV12.connect(defUser, defPass); this.subscribeTopic(connV12, "sub1", null, null, true, true); @@ -2054,8 +1948,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testSubscribeWithAutoAck() throws Exception - { + public void testSubscribeWithAutoAck() throws Exception { connV12.connect(defUser, defPass); this.subscribe(connV12, "sub1", "auto"); @@ -2077,8 +1970,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testSubscribeWithAutoAckAndBytesMessage() throws Exception - { + public void testSubscribeWithAutoAckAndBytesMessage() throws Exception { connV12.connect(defUser, defPass); this.subscribe(connV12, "sub1", "auto"); @@ -2102,8 +1994,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testSubscribeWithClientAck() throws Exception - { + public void testSubscribeWithClientAck() throws Exception { connV12.connect(defUser, defPass); this.subscribe(connV12, "sub1", "client"); @@ -2123,20 +2014,17 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testSubscribeWithClientAckThenConsumingAgainWithAutoAckWithExplicitDisconnect() throws Exception - { + public void testSubscribeWithClientAckThenConsumingAgainWithAutoAckWithExplicitDisconnect() throws Exception { assertSubscribeWithClientAckThenConsumeWithAutoAck(true); } @Test - public void testSubscribeWithClientAckThenConsumingAgainWithAutoAckWithNoDisconnectFrame() throws Exception - { + public void testSubscribeWithClientAckThenConsumingAgainWithAutoAckWithNoDisconnectFrame() throws Exception { assertSubscribeWithClientAckThenConsumeWithAutoAck(false); } @Test - public void testSubscribeWithID() throws Exception - { + public void testSubscribeWithID() throws Exception { connV12.connect(defUser, defPass); this.subscribe(connV12, "mysubid", "auto"); @@ -2151,8 +2039,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testSubscribeWithMessageSentWithProperties() throws Exception - { + public void testSubscribeWithMessageSentWithProperties() throws Exception { connV12.connect(defUser, defPass); this.subscribe(connV12, "sub1", "auto"); @@ -2187,8 +2074,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testSuccessiveTransactionsWithSameID() throws Exception - { + public void testSuccessiveTransactionsWithSameID() throws Exception { MessageConsumer consumer = session.createConsumer(queue); connV12.connect(defUser, defPass); @@ -2228,8 +2114,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testTransactionCommit() throws Exception - { + public void testTransactionCommit() throws Exception { MessageConsumer consumer = session.createConsumer(queue); connV12.connect(defUser, defPass); @@ -2258,8 +2143,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testTransactionRollback() throws Exception - { + public void testTransactionRollback() throws Exception { MessageConsumer consumer = session.createConsumer(queue); connV12.connect(defUser, defPass); @@ -2298,8 +2182,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testUnsubscribe() throws Exception - { + public void testUnsubscribe() throws Exception { connV12.connect(defUser, defPass); this.subscribe(connV12, "sub1", "auto"); @@ -2325,8 +2208,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testDisconnectWithoutUnsubscribe() throws Exception - { + public void testDisconnectWithoutUnsubscribe() throws Exception { connV12.connect(defUser, defPass); this.subscribe(connV12, "sub1", "auto"); @@ -2374,44 +2256,39 @@ public class StompV12Test extends StompV11TestBase //-----------------private help methods - private void abortTransaction(StompClientConnection conn, String txID) throws IOException, InterruptedException - { + private void abortTransaction(StompClientConnection conn, String txID) throws IOException, InterruptedException { ClientStompFrame abortFrame = conn.createFrame("ABORT"); abortFrame.addHeader("transaction", txID); conn.sendFrame(abortFrame); } - private void beginTransaction(StompClientConnection conn, String txID) throws IOException, InterruptedException - { + private void beginTransaction(StompClientConnection conn, String txID) throws IOException, InterruptedException { ClientStompFrame beginFrame = conn.createFrame("BEGIN"); beginFrame.addHeader("transaction", txID); conn.sendFrame(beginFrame); } - private void commitTransaction(StompClientConnection conn, String txID) throws IOException, InterruptedException - { + private void commitTransaction(StompClientConnection conn, String txID) throws IOException, InterruptedException { commitTransaction(conn, txID, false); } - private void commitTransaction(StompClientConnection conn, String txID, boolean receipt) throws IOException, InterruptedException - { + private void commitTransaction(StompClientConnection conn, + String txID, + boolean receipt) throws IOException, InterruptedException { ClientStompFrame beginFrame = conn.createFrame("COMMIT"); beginFrame.addHeader("transaction", txID); - if (receipt) - { + if (receipt) { beginFrame.addHeader("receipt", "1234"); } ClientStompFrame resp = conn.sendFrame(beginFrame); - if (receipt) - { + if (receipt) { Assert.assertEquals("1234", resp.getHeader("receipt-id")); } } - private void ack(StompClientConnection conn, ClientStompFrame frame) throws IOException, InterruptedException - { + private void ack(StompClientConnection conn, ClientStompFrame frame) throws IOException, InterruptedException { String messageID = frame.getHeader("ack"); ClientStompFrame ackFrame = conn.createFrame("ACK"); @@ -2419,161 +2296,157 @@ public class StompV12Test extends StompV11TestBase ackFrame.addHeader("id", messageID); ClientStompFrame response = conn.sendFrame(ackFrame); - if (response != null) - { + if (response != null) { throw new IOException("failed to ack " + response); } } - private void ack(StompClientConnection conn, String mid, String txID) throws IOException, InterruptedException - { + private void ack(StompClientConnection conn, String mid, String txID) throws IOException, InterruptedException { ClientStompFrame ackFrame = conn.createFrame("ACK"); ackFrame.addHeader("id", mid); - if (txID != null) - { + if (txID != null) { ackFrame.addHeader("transaction", txID); } conn.sendFrame(ackFrame); } - private void nack(StompClientConnection conn, String mid) throws IOException, InterruptedException - { + private void nack(StompClientConnection conn, String mid) throws IOException, InterruptedException { ClientStompFrame ackFrame = conn.createFrame("NACK"); ackFrame.addHeader("id", mid); conn.sendFrame(ackFrame); } - private void subscribe(StompClientConnection conn, String subId, String ack) throws IOException, InterruptedException - { + private void subscribe(StompClientConnection conn, + String subId, + String ack) throws IOException, InterruptedException { subscribe(conn, subId, ack, null, null); } - private void subscribe(StompClientConnection conn, String subId, - String ack, String durableId) throws IOException, InterruptedException - { + private void subscribe(StompClientConnection conn, + String subId, + String ack, + String durableId) throws IOException, InterruptedException { subscribe(conn, subId, ack, durableId, null); } - private void subscribe(StompClientConnection conn, String subId, - String ack, String durableId, boolean receipt) throws IOException, InterruptedException - { + private void subscribe(StompClientConnection conn, + String subId, + String ack, + String durableId, + boolean receipt) throws IOException, InterruptedException { subscribe(conn, subId, ack, durableId, null, receipt); } - private void subscribe(StompClientConnection conn, String subId, String ack, - String durableId, String selector) throws IOException, - InterruptedException - { + private void subscribe(StompClientConnection conn, + String subId, + String ack, + String durableId, + String selector) throws IOException, InterruptedException { subscribe(conn, subId, ack, durableId, selector, false); } - private void subscribe(StompClientConnection conn, String subId, - String ack, String durableId, String selector, boolean receipt) throws IOException, InterruptedException - { + private void subscribe(StompClientConnection conn, + String subId, + String ack, + String durableId, + String selector, + boolean receipt) throws IOException, InterruptedException { ClientStompFrame subFrame = conn.createFrame("SUBSCRIBE"); subFrame.addHeader("id", subId); subFrame.addHeader("destination", getQueuePrefix() + getQueueName()); - if (ack != null) - { + if (ack != null) { subFrame.addHeader("ack", ack); } - if (durableId != null) - { + if (durableId != null) { subFrame.addHeader("durable-subscriber-name", durableId); } - if (selector != null) - { + if (selector != null) { subFrame.addHeader("selector", selector); } - if (receipt) - { + if (receipt) { subFrame.addHeader("receipt", "1234"); } subFrame = conn.sendFrame(subFrame); - if (receipt) - { + if (receipt) { Assert.assertEquals("1234", subFrame.getHeader("receipt-id")); } } - private void subscribeTopic(StompClientConnection conn, String subId, - String ack, String durableId) throws IOException, InterruptedException - { + private void subscribeTopic(StompClientConnection conn, + String subId, + String ack, + String durableId) throws IOException, InterruptedException { subscribeTopic(conn, subId, ack, durableId, false); } - private void subscribeTopic(StompClientConnection conn, String subId, - String ack, String durableId, boolean receipt) throws IOException, InterruptedException - { + private void subscribeTopic(StompClientConnection conn, + String subId, + String ack, + String durableId, + boolean receipt) throws IOException, InterruptedException { subscribeTopic(conn, subId, ack, durableId, receipt, false); } - private void subscribeTopic(StompClientConnection conn, String subId, - String ack, String durableId, boolean receipt, boolean noLocal) throws IOException, InterruptedException - { + private void subscribeTopic(StompClientConnection conn, + String subId, + String ack, + String durableId, + boolean receipt, + boolean noLocal) throws IOException, InterruptedException { ClientStompFrame subFrame = conn.createFrame("SUBSCRIBE"); subFrame.addHeader("id", subId); subFrame.addHeader("destination", getTopicPrefix() + getTopicName()); - if (ack != null) - { + if (ack != null) { subFrame.addHeader("ack", ack); } - if (durableId != null) - { + if (durableId != null) { subFrame.addHeader("durable-subscriber-name", durableId); } - if (receipt) - { + if (receipt) { subFrame.addHeader("receipt", "1234"); } - if (noLocal) - { + if (noLocal) { subFrame.addHeader("no-local", "true"); } ClientStompFrame frame = conn.sendFrame(subFrame); - if (receipt) - { + if (receipt) { Assert.assertTrue(frame.getHeader("receipt-id").equals("1234")); } } - private void unsubscribe(StompClientConnection conn, String subId) throws IOException, InterruptedException - { + private void unsubscribe(StompClientConnection conn, String subId) throws IOException, InterruptedException { ClientStompFrame subFrame = conn.createFrame("UNSUBSCRIBE"); subFrame.addHeader("id", subId); conn.sendFrame(subFrame); } - private void unsubscribe(StompClientConnection conn, String subId, - boolean receipt) throws IOException, InterruptedException - { + private void unsubscribe(StompClientConnection conn, + String subId, + boolean receipt) throws IOException, InterruptedException { ClientStompFrame subFrame = conn.createFrame("UNSUBSCRIBE"); subFrame.addHeader("id", subId); - if (receipt) - { + if (receipt) { subFrame.addHeader("receipt", "4321"); } ClientStompFrame f = conn.sendFrame(subFrame); - if (receipt) - { + if (receipt) { System.out.println("response: " + f); Assert.assertEquals("RECEIPT", f.getCommand()); Assert.assertEquals("4321", f.getHeader("receipt-id")); } } - protected void assertSubscribeWithClientAckThenConsumeWithAutoAck(boolean sendDisconnect) throws Exception - { + protected void assertSubscribeWithClientAckThenConsumeWithAutoAck(boolean sendDisconnect) throws Exception { connV12.connect(defUser, defPass); this.subscribe(connV12, "sub1", "client"); @@ -2586,13 +2459,11 @@ public class StompV12Test extends StompV11TestBase log.info("Reconnecting!"); - if (sendDisconnect) - { + if (sendDisconnect) { connV12.disconnect(); connV12 = (StompClientConnectionV12) StompClientConnectionFactory.createClientConnection("1.2", hostname, port); } - else - { + else { connV12.destroy(); connV12 = (StompClientConnectionV12) StompClientConnectionFactory.createClientConnection("1.2", hostname, port); } @@ -2622,8 +2493,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testSendMessageToNonExistentJmsQueueWithoutAutoCreation() throws Exception - { + public void testSendMessageToNonExistentJmsQueueWithoutAutoCreation() throws Exception { AddressSettings addressSettings = new AddressSettings(); addressSettings.setAutoCreateJmsQueues(false); server.getActiveMQServer().getAddressSettingsRepository().addMatch("#", addressSettings); @@ -2645,8 +2515,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testSendMessageToNonExistentJmsQueueWithAutoCreation() throws Exception - { + public void testSendMessageToNonExistentJmsQueueWithAutoCreation() throws Exception { connV12.connect(defUser, defPass); ClientStompFrame frame = connV12.createFrame("SEND"); @@ -2665,10 +2534,8 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testInvalidStompCommand() throws Exception - { - try - { + public void testInvalidStompCommand() throws Exception { + try { connV12.connect(defUser, defPass); ClientStompFrame frame = connV12.createAnyFrame("INVALID"); @@ -2679,8 +2546,7 @@ public class StompV12Test extends StompV11TestBase Assert.assertTrue(frame.getCommand().equals("ERROR")); } - finally - { + finally { //because the last frame is ERROR, the connection //might already have closed by the server. //this is expected so we ignore it. @@ -2689,8 +2555,7 @@ public class StompV12Test extends StompV11TestBase } @Test - public void testSendAndReceiveWithEscapedCharactersInSenderId() throws Exception - { + public void testSendAndReceiveWithEscapedCharactersInSenderId() throws Exception { connV12.connect(defUser, defPass); ClientStompFrame frame = connV12.createFrame("SEND"); frame.addHeader("destination", getQueuePrefix() + getQueueName()); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/transports/netty/ActiveMQFrameDecoder2Test.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/transports/netty/ActiveMQFrameDecoder2Test.java index 4b09f13f5a..a77018362c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/transports/netty/ActiveMQFrameDecoder2Test.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/transports/netty/ActiveMQFrameDecoder2Test.java @@ -28,8 +28,8 @@ import java.util.ArrayList; import java.util.List; import java.util.Random; -public class ActiveMQFrameDecoder2Test extends ActiveMQTestBase -{ +public class ActiveMQFrameDecoder2Test extends ActiveMQTestBase { + private static final int MSG_CNT = 10000; private static final int MSG_LEN = 1000; @@ -39,36 +39,29 @@ public class ActiveMQFrameDecoder2Test extends ActiveMQTestBase private static final Random rand = new Random(); @Test - public void testOrdinaryFragmentation() throws Exception - { + public void testOrdinaryFragmentation() throws Exception { final EmbeddedChannel decoder = new EmbeddedChannel(new ActiveMQFrameDecoder2()); final byte[] data = new byte[ActiveMQFrameDecoder2Test.MSG_LEN]; ActiveMQFrameDecoder2Test.rand.nextBytes(data); ByteBuf src = Unpooled.buffer(ActiveMQFrameDecoder2Test.MSG_CNT * (ActiveMQFrameDecoder2Test.MSG_LEN + 4)); - while (src.writerIndex() < src.capacity()) - { + while (src.writerIndex() < src.capacity()) { src.writeInt(ActiveMQFrameDecoder2Test.MSG_LEN); src.writeBytes(data); } List packets = new ArrayList(); - while (src.isReadable()) - { - int length = Math.min(ActiveMQFrameDecoder2Test.rand.nextInt(ActiveMQFrameDecoder2Test.FRAGMENT_MAX_LEN), - src.readableBytes()); + while (src.isReadable()) { + int length = Math.min(ActiveMQFrameDecoder2Test.rand.nextInt(ActiveMQFrameDecoder2Test.FRAGMENT_MAX_LEN), src.readableBytes()); packets.add(src.readBytes(length)); } int cnt = 0; - for (ByteBuf p : packets) - { + for (ByteBuf p : packets) { decoder.writeInbound(p); - for (;;) - { + for (;;) { ByteBuf frame = (ByteBuf) decoder.readInbound(); - if (frame == null) - { + if (frame == null) { break; } Assert.assertEquals(4, frame.readerIndex()); @@ -82,8 +75,7 @@ public class ActiveMQFrameDecoder2Test extends ActiveMQTestBase } @Test - public void testExtremeFragmentation() throws Exception - { + public void testExtremeFragmentation() throws Exception { final EmbeddedChannel decoder = new EmbeddedChannel(new ActiveMQFrameDecoder2()); decoder.writeInbound(Unpooled.wrappedBuffer(new byte[]{0})); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/transports/netty/NettyConnectorWithHTTPUpgradeTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/transports/netty/NettyConnectorWithHTTPUpgradeTest.java index 17509a6d7a..4138a5b0b6 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/transports/netty/NettyConnectorWithHTTPUpgradeTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/transports/netty/NettyConnectorWithHTTPUpgradeTest.java @@ -69,8 +69,7 @@ import static org.apache.activemq.artemis.tests.util.RandomUtil.randomString; /** * Test that Netty Connector can connect to a Web Server and upgrade from a HTTP request to its remoting protocol. */ -public class NettyConnectorWithHTTPUpgradeTest extends ActiveMQTestBase -{ +public class NettyConnectorWithHTTPUpgradeTest extends ActiveMQTestBase { private static final SimpleString QUEUE = new SimpleString("NettyConnectorWithHTTPUpgradeTest"); @@ -86,8 +85,7 @@ public class NettyConnectorWithHTTPUpgradeTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); HashMap httpParams = new HashMap(); // This prop controls the usage of HTTP Get + Upgrade from Netty connector @@ -95,8 +93,7 @@ public class NettyConnectorWithHTTPUpgradeTest extends ActiveMQTestBase httpParams.put(TransportConstants.PORT_PROP_NAME, HTTP_PORT); acceptorName = randomString(); - conf = createDefaultNettyConfig() - .addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, httpParams, acceptorName)); + conf = createDefaultNettyConfig().addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, httpParams, acceptorName)); server = addServer(ActiveMQServers.newActiveMQServer(conf, false)); @@ -109,15 +106,13 @@ public class NettyConnectorWithHTTPUpgradeTest extends ActiveMQTestBase } @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { stopWebServer(); super.tearDown(); } @Test - public void sendAndReceiveOverHTTPPort() throws Exception - { + public void sendAndReceiveOverHTTPPort() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(false, true, true); @@ -127,13 +122,8 @@ public class NettyConnectorWithHTTPUpgradeTest extends ActiveMQTestBase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - false, - 0, - System.currentTimeMillis(), - (byte) 1); + for (int i = 0; i < numMessages; i++) { + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1); message.getBodyBuffer().writeString("sendAndReceiveOverHTTPPort"); producer.send(message); } @@ -142,8 +132,7 @@ public class NettyConnectorWithHTTPUpgradeTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ClientMessage message2 = consumer.receive(); assertNotNull(message2); @@ -156,8 +145,7 @@ public class NettyConnectorWithHTTPUpgradeTest extends ActiveMQTestBase } @Test - public void HTTPUpgradeConnectorUsingNormalAcceptor() throws Exception - { + public void HTTPUpgradeConnectorUsingNormalAcceptor() throws Exception { HashMap params = new HashMap<>(); // create a new locator that points an HTTP-upgrade connector to the normal acceptor @@ -168,15 +156,13 @@ public class NettyConnectorWithHTTPUpgradeTest extends ActiveMQTestBase Exception e = null; - try - { + try { createSessionFactory(locator); // we shouldn't ever get here fail(); } - catch (Exception x) - { + catch (Exception x) { e = x; } @@ -187,71 +173,60 @@ public class NettyConnectorWithHTTPUpgradeTest extends ActiveMQTestBase assertTrue(((ActiveMQException) e).getType() == ActiveMQExceptionType.NOT_CONNECTED); } - private void startWebServer(int port) throws InterruptedException - { + private void startWebServer(int port) throws InterruptedException { bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE); - b.group(bossGroup, workerGroup) - .channel(NioServerSocketChannel.class) - .childHandler(new ChannelInitializer() - { - @Override - protected void initChannel(SocketChannel ch) throws Exception - { - // create a HTTP server - ChannelPipeline p = ch.pipeline(); - p.addLast("decoder", new HttpRequestDecoder()); - p.addLast("encoder", new HttpResponseEncoder()); - p.addLast("http-upgrade-handler", new SimpleChannelInboundHandler() - { - // handle HTTP GET + Upgrade with a handshake specific to ActiveMQ Artemis remoting. - @Override - protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception - { - if (msg instanceof HttpRequest) - { - HttpRequest request = (HttpRequest) msg; + b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel ch) throws Exception { + // create a HTTP server + ChannelPipeline p = ch.pipeline(); + p.addLast("decoder", new HttpRequestDecoder()); + p.addLast("encoder", new HttpResponseEncoder()); + p.addLast("http-upgrade-handler", new SimpleChannelInboundHandler() { + // handle HTTP GET + Upgrade with a handshake specific to ActiveMQ Artemis remoting. + @Override + protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { + if (msg instanceof HttpRequest) { + HttpRequest request = (HttpRequest) msg; - for (Map.Entry entry : request.headers()) - { - System.out.println(entry); - } - String upgrade = request.headers().get(UPGRADE); - String secretKey = request.headers().get(SEC_ACTIVEMQ_REMOTING_KEY); - - FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, SWITCHING_PROTOCOLS); - response.headers().set(UPGRADE, upgrade); - response.headers().set(SEC_ACTIVEMQ_REMOTING_ACCEPT, createExpectedResponse(MAGIC_NUMBER, secretKey)); - ctx.writeAndFlush(response); - - // when the handshake is successful, the HTTP handlers are removed - ctx.pipeline().remove("decoder"); - ctx.pipeline().remove("encoder"); - ctx.pipeline().remove(this); - - System.out.println("HTTP handshake sent, transferring channel"); - // transfer the control of the channel to the Netty Acceptor - NettyAcceptor acceptor = (NettyAcceptor) server.getRemotingService().getAcceptor(acceptorName); - acceptor.transfer(ctx.channel()); - // at this point, the HTTP upgrade process is over and the netty acceptor behaves like regular ones. + for (Map.Entry entry : request.headers()) { + System.out.println(entry); } - } - }); - } + String upgrade = request.headers().get(UPGRADE); + String secretKey = request.headers().get(SEC_ACTIVEMQ_REMOTING_KEY); - @Override - public void channelReadComplete(ChannelHandlerContext ctx) throws Exception - { - ctx.flush(); - } - }); + FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, SWITCHING_PROTOCOLS); + response.headers().set(UPGRADE, upgrade); + response.headers().set(SEC_ACTIVEMQ_REMOTING_ACCEPT, createExpectedResponse(MAGIC_NUMBER, secretKey)); + ctx.writeAndFlush(response); + + // when the handshake is successful, the HTTP handlers are removed + ctx.pipeline().remove("decoder"); + ctx.pipeline().remove("encoder"); + ctx.pipeline().remove(this); + + System.out.println("HTTP handshake sent, transferring channel"); + // transfer the control of the channel to the Netty Acceptor + NettyAcceptor acceptor = (NettyAcceptor) server.getRemotingService().getAcceptor(acceptorName); + acceptor.transfer(ctx.channel()); + // at this point, the HTTP upgrade process is over and the netty acceptor behaves like regular ones. + } + } + }); + } + + @Override + public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { + ctx.flush(); + } + }); b.bind(port).sync(); } - private void stopWebServer() - { + private void stopWebServer() { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/vertx/ActiveMQVertxUnitTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/vertx/ActiveMQVertxUnitTest.java index d5c94a5bca..0c19b73b26 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/vertx/ActiveMQVertxUnitTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/vertx/ActiveMQVertxUnitTest.java @@ -49,8 +49,8 @@ import org.vertx.java.spi.cluster.impl.hazelcast.HazelcastClusterManagerFactory; * This class tests the basics of ActiveMQ * vertx integration */ -public class ActiveMQVertxUnitTest extends ActiveMQTestBase -{ +public class ActiveMQVertxUnitTest extends ActiveMQTestBase { + protected PlatformManager vertxManager; protected ActiveMQServer server; @@ -70,29 +70,22 @@ public class ActiveMQVertxUnitTest extends ActiveMQTestBase protected String incomingVertxAddress3 = "org.apache.activemq.test.incoming3"; protected String outgoingVertxAddress2 = "org.apache.activemq.test.outgoing2"; - // Vertx is changing the classLoader to null.. this will preserve the original classloader ClassLoader contextClassLoader; //subclasses may override this method //in order to get a server with different connector services - @Before @Override - public void setUp() throws Exception - { + @Before + @Override + public void setUp() throws Exception { contextClassLoader = Thread.currentThread().getContextClassLoader(); createVertxService(); super.setUp(); //all queues - CoreQueueConfiguration qc1 = new CoreQueueConfiguration() - .setAddress(incomingQueue1) - .setName(incomingQueue1); - CoreQueueConfiguration qc2 = new CoreQueueConfiguration() - .setAddress(inOutQueue1) - .setName(inOutQueue1); - CoreQueueConfiguration qc3 = new CoreQueueConfiguration() - .setAddress(inOutQueue2) - .setName(inOutQueue2); + CoreQueueConfiguration qc1 = new CoreQueueConfiguration().setAddress(incomingQueue1).setName(incomingQueue1); + CoreQueueConfiguration qc2 = new CoreQueueConfiguration().setAddress(inOutQueue1).setName(inOutQueue1); + CoreQueueConfiguration qc3 = new CoreQueueConfiguration().setAddress(inOutQueue2).setName(inOutQueue2); //incoming HashMap config1 = new HashMap(); @@ -101,10 +94,7 @@ public class ActiveMQVertxUnitTest extends ActiveMQTestBase config1.put(VertxConstants.QUEUE_NAME, incomingQueue1); config1.put(VertxConstants.VERTX_ADDRESS, incomingVertxAddress1); - ConnectorServiceConfiguration inconf1 = new ConnectorServiceConfiguration() - .setFactoryClassName(VertxIncomingConnectorServiceFactory.class.getName()) - .setParams(config1) - .setName("test-vertx-incoming-connector1"); + ConnectorServiceConfiguration inconf1 = new ConnectorServiceConfiguration().setFactoryClassName(VertxIncomingConnectorServiceFactory.class.getName()).setParams(config1).setName("test-vertx-incoming-connector1"); //outgoing send style HashMap config2 = new HashMap(); @@ -113,10 +103,7 @@ public class ActiveMQVertxUnitTest extends ActiveMQTestBase config2.put(VertxConstants.QUEUE_NAME, inOutQueue1); config2.put(VertxConstants.VERTX_ADDRESS, incomingVertxAddress2); - ConnectorServiceConfiguration inconf2 = new ConnectorServiceConfiguration() - .setFactoryClassName(VertxIncomingConnectorServiceFactory.class.getName()) - .setParams(config2) - .setName("test-vertx-incoming-connector2"); + ConnectorServiceConfiguration inconf2 = new ConnectorServiceConfiguration().setFactoryClassName(VertxIncomingConnectorServiceFactory.class.getName()).setParams(config2).setName("test-vertx-incoming-connector2"); HashMap config3 = new HashMap(); config3.put(VertxConstants.HOST, host); @@ -124,10 +111,7 @@ public class ActiveMQVertxUnitTest extends ActiveMQTestBase config3.put(VertxConstants.QUEUE_NAME, inOutQueue1); config3.put(VertxConstants.VERTX_ADDRESS, outgoingVertxAddress1); - ConnectorServiceConfiguration outconf1 = new ConnectorServiceConfiguration() - .setFactoryClassName(VertxOutgoingConnectorServiceFactory.class.getName()) - .setParams(config3) - .setName("test-vertx-outgoing-connector1"); + ConnectorServiceConfiguration outconf1 = new ConnectorServiceConfiguration().setFactoryClassName(VertxOutgoingConnectorServiceFactory.class.getName()).setParams(config3).setName("test-vertx-outgoing-connector1"); //outgoing publish style HashMap config4 = new HashMap(); @@ -136,10 +120,7 @@ public class ActiveMQVertxUnitTest extends ActiveMQTestBase config4.put(VertxConstants.QUEUE_NAME, inOutQueue2); config4.put(VertxConstants.VERTX_ADDRESS, incomingVertxAddress3); - ConnectorServiceConfiguration inconf3 = new ConnectorServiceConfiguration() - .setFactoryClassName(VertxIncomingConnectorServiceFactory.class.getName()) - .setParams(config4) - .setName("test-vertx-incoming-connector3"); + ConnectorServiceConfiguration inconf3 = new ConnectorServiceConfiguration().setFactoryClassName(VertxIncomingConnectorServiceFactory.class.getName()).setParams(config4).setName("test-vertx-incoming-connector3"); HashMap config5 = new HashMap(); config5.put(VertxConstants.HOST, host); @@ -148,20 +129,9 @@ public class ActiveMQVertxUnitTest extends ActiveMQTestBase config5.put(VertxConstants.VERTX_ADDRESS, outgoingVertxAddress2); config5.put(VertxConstants.VERTX_PUBLISH, "true"); - ConnectorServiceConfiguration outconf2 = new ConnectorServiceConfiguration() - .setFactoryClassName(VertxOutgoingConnectorServiceFactory.class.getName()) - .setParams(config5) - .setName("test-vertx-outgoing-connector2"); + ConnectorServiceConfiguration outconf2 = new ConnectorServiceConfiguration().setFactoryClassName(VertxOutgoingConnectorServiceFactory.class.getName()).setParams(config5).setName("test-vertx-outgoing-connector2"); - Configuration configuration = createDefaultInVMConfig() - .addQueueConfiguration(qc1) - .addQueueConfiguration(qc2) - .addQueueConfiguration(qc3) - .addConnectorServiceConfiguration(inconf1) - .addConnectorServiceConfiguration(inconf2) - .addConnectorServiceConfiguration(outconf1) - .addConnectorServiceConfiguration(inconf3) - .addConnectorServiceConfiguration(outconf2); + Configuration configuration = createDefaultInVMConfig().addQueueConfiguration(qc1).addQueueConfiguration(qc2).addQueueConfiguration(qc3).addConnectorServiceConfiguration(inconf1).addConnectorServiceConfiguration(inconf2).addConnectorServiceConfiguration(outconf1).addConnectorServiceConfiguration(inconf3).addConnectorServiceConfiguration(outconf2); server = createServer(false, configuration); server.start(); @@ -169,11 +139,11 @@ public class ActiveMQVertxUnitTest extends ActiveMQTestBase /** * (vertx events) ===> (incomingQueue1) ===> (activemq consumer) + * * @throws Exception */ @Test - public void testIncomingEvents() throws Exception - { + public void testIncomingEvents() throws Exception { Vertx vertx = vertxManager.vertx(); //send a string message @@ -210,8 +180,7 @@ public class ActiveMQVertxUnitTest extends ActiveMQTestBase activeMQBuffer.readBytes(bytes); //bytes must match - for (int i = 0; i < len; i++) - { + for (int i = 0; i < len; i++) { assertEquals(content[i], bytes[i]); } @@ -236,13 +205,12 @@ public class ActiveMQVertxUnitTest extends ActiveMQTestBase byte[] recvBytes = new byte[len]; msg.getBodyBuffer().readBytes(recvBytes); //bytes must match - for (int i = 0; i < len; i++) - { + for (int i = 0; i < len; i++) { assertEquals(content[i], recvBytes[i]); } //send a byte - Byte aByte = new Byte((byte)15); + Byte aByte = new Byte((byte) 15); vertx.eventBus().send(incomingVertxAddress1, aByte); msg = receiveFromQueue(incomingQueue1); assertNotNull(msg); @@ -303,7 +271,7 @@ public class ActiveMQVertxUnitTest extends ActiveMQTestBase assertEquals(aLong, recvLong); //send a Short - Short aShort = new Short((short)321); + Short aShort = new Short((short) 321); vertx.eventBus().send(incomingVertxAddress1, aShort); msg = receiveFromQueue(incomingQueue1); assertNotNull(msg); @@ -314,18 +282,18 @@ public class ActiveMQVertxUnitTest extends ActiveMQTestBase //send a JsonObject String jsonObjectString = "{\n" + - "\"Image\": {\n" + - "\"Width\": 800,\n" + - "\"Height\": 600,\n" + - "\"Title\": \"View from 15th Floor\",\n" + - "\"Thumbnail\": {\n" + - "\"Url\": \"http://www.example.com/image/481989943\",\n" + - "\"Height\": 125,\n" + - "\"Width\": 100\n" + - "},\n" + - "\"IDs\": [116, 943, 234, 38793]\n" + - "}\n" + - "}"; + "\"Image\": {\n" + + "\"Width\": 800,\n" + + "\"Height\": 600,\n" + + "\"Title\": \"View from 15th Floor\",\n" + + "\"Thumbnail\": {\n" + + "\"Url\": \"http://www.example.com/image/481989943\",\n" + + "\"Height\": 125,\n" + + "\"Width\": 100\n" + + "},\n" + + "\"IDs\": [116, 943, 234, 38793]\n" + + "}\n" + + "}"; JsonObject aJsonObj = new JsonObject(jsonObjectString); vertx.eventBus().send(incomingVertxAddress1, aJsonObj); msg = receiveFromQueue(incomingQueue1); @@ -338,27 +306,27 @@ public class ActiveMQVertxUnitTest extends ActiveMQTestBase //send a JsonArray String jsonArrayString = "[\n" + - "{\n" + - "\"precision\": \"zip\",\n" + - "\"Latitude\": 37.7668,\n" + - "\"Longitude\": -122.3959,\n" + - "\"Address\": \"\",\n" + - "\"City\": \"SAN FRANCISCO\",\n" + - "\"State\": \"CA\",\n" + - "\"Zip\": \"94107\",\n" + - "\"Country\": \"US\"\n" + - "},\n" + - "{\n" + - "\"precision\": \"zip\",\n" + - "\"Latitude\": 37.371991,\n" + - "\"Longitude\": -122.026020,\n" + - "\"Address\": \"\",\n" + - "\"City\": \"SUNNYVALE\",\n" + - "\"State\": \"CA\",\n" + - "\"Zip\": \"94085\",\n" + - "\"Country\": \"US\"\n" + - "}\n" + - "]"; + "{\n" + + "\"precision\": \"zip\",\n" + + "\"Latitude\": 37.7668,\n" + + "\"Longitude\": -122.3959,\n" + + "\"Address\": \"\",\n" + + "\"City\": \"SAN FRANCISCO\",\n" + + "\"State\": \"CA\",\n" + + "\"Zip\": \"94107\",\n" + + "\"Country\": \"US\"\n" + + "},\n" + + "{\n" + + "\"precision\": \"zip\",\n" + + "\"Latitude\": 37.371991,\n" + + "\"Longitude\": -122.026020,\n" + + "\"Address\": \"\",\n" + + "\"City\": \"SUNNYVALE\",\n" + + "\"State\": \"CA\",\n" + + "\"Zip\": \"94085\",\n" + + "\"Country\": \"US\"\n" + + "}\n" + + "]"; JsonArray aJsonArray = new JsonArray(jsonArrayString); System.out.println("a json array string: " + aJsonArray); vertx.eventBus().send(incomingVertxAddress1, aJsonArray); @@ -396,11 +364,11 @@ public class ActiveMQVertxUnitTest extends ActiveMQTestBase * ===> (inOutQueue1) * ===> (outgoing handler) * ===> send to vertx (outgoingVertxAddress1) + * * @throws Exception */ @Test - public void testOutgoingEvents() throws Exception - { + public void testOutgoingEvents() throws Exception { Vertx vertx = vertxManager.vertx(); //regiser a handler to receive outgoing messages @@ -433,7 +401,7 @@ public class ActiveMQVertxUnitTest extends ActiveMQTestBase handler.checkByteArrayMessageReceived(byteArray); //send a byte - Byte aByte = new Byte((byte)15); + Byte aByte = new Byte((byte) 15); vertx.eventBus().send(incomingVertxAddress2, aByte); handler.checkByteMessageReceived(aByte); @@ -469,25 +437,25 @@ public class ActiveMQVertxUnitTest extends ActiveMQTestBase handler.checkLongMessageReceived(aLong); //send a Short - Short aShort = new Short((short)321); + Short aShort = new Short((short) 321); vertx.eventBus().send(incomingVertxAddress2, aShort); handler.checkShortMessageReceived(aShort); //send a JsonObject String jsonObjectString = "{\n" + - "\"Image\": {\n" + - "\"Width\": 800,\n" + - "\"Height\": 600,\n" + - "\"Title\": \"View from 15th Floor\",\n" + - "\"Thumbnail\": {\n" + - "\"Url\": \"http://www.example.com/image/481989943\",\n" + - "\"Height\": 125,\n" + - "\"Width\": 100\n" + - "},\n" + - "\"IDs\": [116, 943, 234, 38793]\n" + - "}\n" + - "}"; + "\"Image\": {\n" + + "\"Width\": 800,\n" + + "\"Height\": 600,\n" + + "\"Title\": \"View from 15th Floor\",\n" + + "\"Thumbnail\": {\n" + + "\"Url\": \"http://www.example.com/image/481989943\",\n" + + "\"Height\": 125,\n" + + "\"Width\": 100\n" + + "},\n" + + "\"IDs\": [116, 943, 234, 38793]\n" + + "}\n" + + "}"; JsonObject aJsonObj = new JsonObject(jsonObjectString); vertx.eventBus().send(incomingVertxAddress2, aJsonObj); @@ -495,27 +463,27 @@ public class ActiveMQVertxUnitTest extends ActiveMQTestBase //send a JsonArray String jsonArrayString = "[\n" + - "{\n" + - "\"precision\": \"zip\",\n" + - "\"Latitude\": 37.7668,\n" + - "\"Longitude\": -122.3959,\n" + - "\"Address\": \"\",\n" + - "\"City\": \"SAN FRANCISCO\",\n" + - "\"State\": \"CA\",\n" + - "\"Zip\": \"94107\",\n" + - "\"Country\": \"US\"\n" + - "},\n" + - "{\n" + - "\"precision\": \"zip\",\n" + - "\"Latitude\": 37.371991,\n" + - "\"Longitude\": -122.026020,\n" + - "\"Address\": \"\",\n" + - "\"City\": \"SUNNYVALE\",\n" + - "\"State\": \"CA\",\n" + - "\"Zip\": \"94085\",\n" + - "\"Country\": \"US\"\n" + - "}\n" + - "]"; + "{\n" + + "\"precision\": \"zip\",\n" + + "\"Latitude\": 37.7668,\n" + + "\"Longitude\": -122.3959,\n" + + "\"Address\": \"\",\n" + + "\"City\": \"SAN FRANCISCO\",\n" + + "\"State\": \"CA\",\n" + + "\"Zip\": \"94107\",\n" + + "\"Country\": \"US\"\n" + + "},\n" + + "{\n" + + "\"precision\": \"zip\",\n" + + "\"Latitude\": 37.371991,\n" + + "\"Longitude\": -122.026020,\n" + + "\"Address\": \"\",\n" + + "\"City\": \"SUNNYVALE\",\n" + + "\"State\": \"CA\",\n" + + "\"Zip\": \"94085\",\n" + + "\"Country\": \"US\"\n" + + "}\n" + + "]"; JsonArray aJsonArray = new JsonArray(jsonArrayString); vertx.eventBus().send(incomingVertxAddress2, aJsonArray); @@ -527,11 +495,11 @@ public class ActiveMQVertxUnitTest extends ActiveMQTestBase * ===> (inOutQueue2) * ===> (outgoing handler) * ===> public to vertx (outgoingVertxAddress2) + * * @throws Exception */ @Test - public void testOutgoingEvents2() throws Exception - { + public void testOutgoingEvents2() throws Exception { Vertx vertx = vertxManager.vertx(); //regiser two handlers to receive outgoing messages @@ -570,7 +538,7 @@ public class ActiveMQVertxUnitTest extends ActiveMQTestBase handler2.checkByteArrayMessageReceived(byteArray); //send a byte - Byte aByte = new Byte((byte)15); + Byte aByte = new Byte((byte) 15); vertx.eventBus().send(incomingVertxAddress3, aByte); handler1.checkByteMessageReceived(aByte); @@ -612,7 +580,7 @@ public class ActiveMQVertxUnitTest extends ActiveMQTestBase handler2.checkLongMessageReceived(aLong); //send a Short - Short aShort = new Short((short)321); + Short aShort = new Short((short) 321); vertx.eventBus().send(incomingVertxAddress3, aShort); handler1.checkShortMessageReceived(aShort); @@ -620,18 +588,18 @@ public class ActiveMQVertxUnitTest extends ActiveMQTestBase //send a JsonObject String jsonObjectString = "{\n" + - "\"Image\": {\n" + - "\"Width\": 800,\n" + - "\"Height\": 600,\n" + - "\"Title\": \"View from 15th Floor\",\n" + - "\"Thumbnail\": {\n" + - "\"Url\": \"http://www.example.com/image/481989943\",\n" + - "\"Height\": 125,\n" + - "\"Width\": 100\n" + - "},\n" + - "\"IDs\": [116, 943, 234, 38793]\n" + - "}\n" + - "}"; + "\"Image\": {\n" + + "\"Width\": 800,\n" + + "\"Height\": 600,\n" + + "\"Title\": \"View from 15th Floor\",\n" + + "\"Thumbnail\": {\n" + + "\"Url\": \"http://www.example.com/image/481989943\",\n" + + "\"Height\": 125,\n" + + "\"Width\": 100\n" + + "},\n" + + "\"IDs\": [116, 943, 234, 38793]\n" + + "}\n" + + "}"; JsonObject aJsonObj = new JsonObject(jsonObjectString); vertx.eventBus().send(incomingVertxAddress3, aJsonObj); @@ -640,27 +608,27 @@ public class ActiveMQVertxUnitTest extends ActiveMQTestBase //send a JsonArray String jsonArrayString = "[\n" + - "{\n" + - "\"precision\": \"zip\",\n" + - "\"Latitude\": 37.7668,\n" + - "\"Longitude\": -122.3959,\n" + - "\"Address\": \"\",\n" + - "\"City\": \"SAN FRANCISCO\",\n" + - "\"State\": \"CA\",\n" + - "\"Zip\": \"94107\",\n" + - "\"Country\": \"US\"\n" + - "},\n" + - "{\n" + - "\"precision\": \"zip\",\n" + - "\"Latitude\": 37.371991,\n" + - "\"Longitude\": -122.026020,\n" + - "\"Address\": \"\",\n" + - "\"City\": \"SUNNYVALE\",\n" + - "\"State\": \"CA\",\n" + - "\"Zip\": \"94085\",\n" + - "\"Country\": \"US\"\n" + - "}\n" + - "]"; + "{\n" + + "\"precision\": \"zip\",\n" + + "\"Latitude\": 37.7668,\n" + + "\"Longitude\": -122.3959,\n" + + "\"Address\": \"\",\n" + + "\"City\": \"SAN FRANCISCO\",\n" + + "\"State\": \"CA\",\n" + + "\"Zip\": \"94107\",\n" + + "\"Country\": \"US\"\n" + + "},\n" + + "{\n" + + "\"precision\": \"zip\",\n" + + "\"Latitude\": 37.371991,\n" + + "\"Longitude\": -122.026020,\n" + + "\"Address\": \"\",\n" + + "\"City\": \"SUNNYVALE\",\n" + + "\"State\": \"CA\",\n" + + "\"Zip\": \"94085\",\n" + + "\"Country\": \"US\"\n" + + "}\n" + + "]"; JsonArray aJsonArray = new JsonArray(jsonArrayString); vertx.eventBus().send(incomingVertxAddress3, aJsonArray); @@ -669,16 +637,14 @@ public class ActiveMQVertxUnitTest extends ActiveMQTestBase } - private ClientMessage receiveFromQueue(String queueName) throws Exception - { + private ClientMessage receiveFromQueue(String queueName) throws Exception { ClientMessage msg = null; ServerLocator locator = null; ClientSessionFactory sf = null; ClientSession session = null; - try - { + try { locator = createInVMNonHALocator(); sf = createSessionFactory(locator); @@ -689,159 +655,135 @@ public class ActiveMQVertxUnitTest extends ActiveMQTestBase msg = consumer.receive(60 * 1000); msg.acknowledge(); } - finally - { - if (session != null) - { + finally { + if (session != null) { session.commit(); session.close(); } - if (sf != null) sf.close(); - if (locator != null) locator.close(); + if (sf != null) + sf.close(); + if (locator != null) + locator.close(); } return msg; } - private void createVertxService() - { + private void createVertxService() { System.setProperty("vertx.clusterManagerFactory", HazelcastClusterManagerFactory.class.getName()); - vertxManager = PlatformLocator.factory.createPlatformManager(Integer.valueOf(port), - host); + vertxManager = PlatformLocator.factory.createPlatformManager(Integer.valueOf(port), host); -// vertxManager = PlatformLocator.factory.createPlatformManager(Integer.valueOf(port), -// host, quorumSize, haGroup + System.currentTimeMillis()); + // vertxManager = PlatformLocator.factory.createPlatformManager(Integer.valueOf(port), + // host, quorumSize, haGroup + System.currentTimeMillis()); } - private class VertxTestHandler implements Handler> - { + private class VertxTestHandler implements Handler> { + private volatile BaseMessage vertxMsg = null; private final Object lock = new Object(); @Override - public void handle(BaseMessage arg0) - { - synchronized (lock) - { + public void handle(BaseMessage arg0) { + synchronized (lock) { vertxMsg = arg0; lock.notify(); } } - public void checkJsonArrayMessageReceived(JsonArray aJsonArray) - { + public void checkJsonArrayMessageReceived(JsonArray aJsonArray) { BaseMessage msg = waitMessage(); - JsonArray body = (JsonArray)msg.body(); + JsonArray body = (JsonArray) msg.body(); assertEquals(aJsonArray, body); } - public void checkJsonObjectMessageReceived(final JsonObject aJsonObj) - { + public void checkJsonObjectMessageReceived(final JsonObject aJsonObj) { BaseMessage msg = waitMessage(); - JsonObject body = (JsonObject)msg.body(); + JsonObject body = (JsonObject) msg.body(); assertEquals(aJsonObj, body); } - public void checkShortMessageReceived(final Short aShort) - { + public void checkShortMessageReceived(final Short aShort) { BaseMessage msg = waitMessage(); - Short body = (Short)msg.body(); + Short body = (Short) msg.body(); assertEquals(aShort, body); } - public void checkLongMessageReceived(final Long aLong) - { + public void checkLongMessageReceived(final Long aLong) { BaseMessage msg = waitMessage(); - Long body = (Long)msg.body(); + Long body = (Long) msg.body(); assertEquals(aLong, body); } - public void checkIntegerMessageReceived(final Integer aInt) - { + public void checkIntegerMessageReceived(final Integer aInt) { BaseMessage msg = waitMessage(); - Integer body = (Integer)msg.body(); + Integer body = (Integer) msg.body(); assertEquals(aInt, body); } - public void checkFloatMessageReceived(final Float aFloat) - { + public void checkFloatMessageReceived(final Float aFloat) { BaseMessage msg = waitMessage(); - Float body = (Float)msg.body(); + Float body = (Float) msg.body(); assertEquals(aFloat, body); } - public void checkDoubleMessageReceived(final Double aDouble) - { + public void checkDoubleMessageReceived(final Double aDouble) { BaseMessage msg = waitMessage(); - Double body = (Double)msg.body(); + Double body = (Double) msg.body(); assertEquals(aDouble, body); } - public void checkCharacterMessageReceived(final Character aChar) - { + public void checkCharacterMessageReceived(final Character aChar) { BaseMessage msg = waitMessage(); - Character body = (Character)msg.body(); + Character body = (Character) msg.body(); assertEquals(aChar, body); } - public void checkByteMessageReceived(final Byte aByte) - { + public void checkByteMessageReceived(final Byte aByte) { BaseMessage msg = waitMessage(); - Byte body = (Byte)msg.body(); + Byte body = (Byte) msg.body(); assertEquals(aByte, body); } - public void checkByteArrayMessageReceived(final byte[] byteArray) - { + public void checkByteArrayMessageReceived(final byte[] byteArray) { BaseMessage msg = waitMessage(); - byte[] body = (byte[])msg.body(); + byte[] body = (byte[]) msg.body(); assertEquals(byteArray.length, body.length); - for (int i = 0; i < byteArray.length; i++) - { + for (int i = 0; i < byteArray.length; i++) { assertEquals(byteArray[i], body[i]); } } - public void checkBooleanMessageReceived(final Boolean boolValue) - { + public void checkBooleanMessageReceived(final Boolean boolValue) { BaseMessage msg = waitMessage(); - Boolean body = (Boolean)msg.body(); + Boolean body = (Boolean) msg.body(); assertEquals(boolValue, body); } - public void checkStringMessageReceived(final String str) - { + public void checkStringMessageReceived(final String str) { BaseMessage msg = waitMessage(); - String body = (String)msg.body(); + String body = (String) msg.body(); assertEquals(str, body); } - public void checkBufferMessageReceived(final Buffer buffer) - { + public void checkBufferMessageReceived(final Buffer buffer) { byte[] source = buffer.getBytes(); BaseMessage msg = waitMessage(); - Buffer body = (Buffer)msg.body(); + Buffer body = (Buffer) msg.body(); byte[] bytes = body.getBytes(); assertEquals(source.length, bytes.length); - for (int i = 0; i < bytes.length; i++) - { + for (int i = 0; i < bytes.length; i++) { assertEquals(source[i], bytes[i]); } } - private BaseMessage waitMessage() - { + private BaseMessage waitMessage() { BaseMessage msg = null; - synchronized (lock) - { + synchronized (lock) { long timeout = System.currentTimeMillis() + 10000; - while (vertxMsg == null && timeout > System.currentTimeMillis()) - { - try - { + while (vertxMsg == null && timeout > System.currentTimeMillis()) { + try { lock.wait(1000); } - catch (InterruptedException e) - { + catch (InterruptedException e) { } } msg = vertxMsg; @@ -853,9 +795,9 @@ public class ActiveMQVertxUnitTest extends ActiveMQTestBase } - @After @Override - public void tearDown() throws Exception - { + @After + @Override + public void tearDown() throws Exception { vertxManager.stop(); server.stop(); server = null; diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/xa/BasicXaRecoveryTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/xa/BasicXaRecoveryTest.java index 73d44b743f..b6d1f00b66 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/xa/BasicXaRecoveryTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/xa/BasicXaRecoveryTest.java @@ -47,8 +47,8 @@ import java.util.Arrays; import java.util.HashMap; import java.util.Map; -public class BasicXaRecoveryTest extends ActiveMQTestBase -{ +public class BasicXaRecoveryTest extends ActiveMQTestBase { + private static IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private final Map addressSettings = new HashMap(); @@ -73,13 +73,11 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); addressSettings.clear(); - configuration = createDefaultInVMConfig() - .setJMXManagementEnabled(true); + configuration = createDefaultInVMConfig().setJMXManagementEnabled(true); mbeanServer = MBeanServerFactory.createMBeanServer(); @@ -95,166 +93,138 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { MBeanServerFactory.releaseMBeanServer(mbeanServer); super.tearDown(); } @Test - public void testBasicSendWithCommit() throws Exception - { + public void testBasicSendWithCommit() throws Exception { testBasicSendWithCommit(false); } @Test - public void testBasicSendWithCommitWithServerStopped() throws Exception - { + public void testBasicSendWithCommitWithServerStopped() throws Exception { testBasicSendWithCommit(true); } @Test - public void testBasicSendWithRollback() throws Exception - { + public void testBasicSendWithRollback() throws Exception { testBasicSendWithRollback(false); } @Test - public void testBasicSendWithRollbackWithServerStopped() throws Exception - { + public void testBasicSendWithRollbackWithServerStopped() throws Exception { testBasicSendWithRollback(true); } @Test - public void testMultipleBeforeSendWithCommit() throws Exception - { + public void testMultipleBeforeSendWithCommit() throws Exception { testMultipleBeforeSendWithCommit(false); } @Test - public void testMultipleBeforeSendWithCommitWithServerStopped() throws Exception - { + public void testMultipleBeforeSendWithCommitWithServerStopped() throws Exception { testMultipleBeforeSendWithCommit(true); } @Test - public void testMultipleTxSendWithCommit() throws Exception - { + public void testMultipleTxSendWithCommit() throws Exception { testMultipleTxSendWithCommit(false); } @Test - public void testMultipleTxSendWithCommitWithServerStopped() throws Exception - { + public void testMultipleTxSendWithCommitWithServerStopped() throws Exception { testMultipleTxSendWithCommit(true); } @Test - public void testMultipleTxSendWithRollback() throws Exception - { + public void testMultipleTxSendWithRollback() throws Exception { testMultipleTxSendWithRollback(false); } @Test - public void testMultipleTxSendWithRollbackWithServerStopped() throws Exception - { + public void testMultipleTxSendWithRollbackWithServerStopped() throws Exception { testMultipleTxSendWithRollback(true); } @Test - public void testMultipleTxSendWithCommitAndRollback() throws Exception - { + public void testMultipleTxSendWithCommitAndRollback() throws Exception { testMultipleTxSendWithCommitAndRollback(false); } @Test - public void testMultipleTxSendWithCommitAndRollbackWithServerStopped() throws Exception - { + public void testMultipleTxSendWithCommitAndRollbackWithServerStopped() throws Exception { testMultipleTxSendWithCommitAndRollback(true); } @Test - public void testMultipleTxSameXidSendWithCommit() throws Exception - { + public void testMultipleTxSameXidSendWithCommit() throws Exception { testMultipleTxSameXidSendWithCommit(false); } @Test - public void testMultipleTxSameXidSendWithCommitWithServerStopped() throws Exception - { + public void testMultipleTxSameXidSendWithCommitWithServerStopped() throws Exception { testMultipleTxSameXidSendWithCommit(true); } @Test - public void testBasicReceiveWithCommit() throws Exception - { + public void testBasicReceiveWithCommit() throws Exception { testBasicReceiveWithCommit(false); } @Test - public void testBasicReceiveWithCommitWithServerStopped() throws Exception - { + public void testBasicReceiveWithCommitWithServerStopped() throws Exception { testBasicReceiveWithCommit(true); } @Test - public void testBasicReceiveWithRollback() throws Exception - { + public void testBasicReceiveWithRollback() throws Exception { testBasicReceiveWithRollback(false); } @Test - public void testBasicReceiveWithRollbackWithServerStopped() throws Exception - { + public void testBasicReceiveWithRollbackWithServerStopped() throws Exception { testBasicReceiveWithRollback(true); } @Test - public void testMultipleTxReceiveWithCommit() throws Exception - { + public void testMultipleTxReceiveWithCommit() throws Exception { testMultipleTxReceiveWithCommit(false); } @Test - public void testMultipleTxReceiveWithCommitWithServerStopped() throws Exception - { + public void testMultipleTxReceiveWithCommitWithServerStopped() throws Exception { testMultipleTxReceiveWithCommit(true); } @Test - public void testMultipleTxReceiveWithRollback() throws Exception - { + public void testMultipleTxReceiveWithRollback() throws Exception { testMultipleTxReceiveWithRollback(false); } @Test - public void testMultipleTxReceiveWithRollbackWithServerStopped() throws Exception - { + public void testMultipleTxReceiveWithRollbackWithServerStopped() throws Exception { testMultipleTxReceiveWithRollback(true); } @Test - public void testPagingServerRestarted() throws Exception - { + public void testPagingServerRestarted() throws Exception { verifyPaging(true); } @Test - public void testPaging() throws Exception - { + public void testPaging() throws Exception { verifyPaging(false); } - public void verifyPaging(final boolean restartServer) throws Exception - { + public void verifyPaging(final boolean restartServer) throws Exception { Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); SimpleString pageQueue = new SimpleString("pagequeue"); - AddressSettings pageAddressSettings = new AddressSettings() - .setMaxSizeBytes(100 * 1024) - .setPageSizeBytes(10 * 1024); + AddressSettings pageAddressSettings = new AddressSettings().setMaxSizeBytes(100 * 1024).setPageSizeBytes(10 * 1024); addressSettings.put(pageQueue.toString(), pageAddressSettings); @@ -266,8 +236,7 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase ClientProducer pageProducer = clientSession.createProducer(pageQueue); - for (int i = 0; i < 1000; i++) - { + for (int i = 0; i < 1000; i++) { ClientMessage m = createBytesMessage(new byte[512], true); pageProducer.send(m); } @@ -279,12 +248,10 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase BasicXaRecoveryTest.log.info("*** stopping and restarting"); - if (restartServer) - { + if (restartServer) { stopAndRestartServer(); } - else - { + else { recreateClients(); } @@ -304,8 +271,7 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase ClientConsumer pageConsumer = clientSession.createConsumer(pageQueue); - for (int i = 0; i < 1000; i++) - { + for (int i = 0; i < 1000; i++) { ClientMessage m = pageConsumer.receive(10000); Assert.assertNotNull(m); @@ -318,26 +284,21 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase } @Test - public void testRollbackPaging() throws Exception - { + public void testRollbackPaging() throws Exception { testRollbackPaging(false); } @Test - public void testRollbackPagingServerRestarted() throws Exception - { + public void testRollbackPagingServerRestarted() throws Exception { testRollbackPaging(true); } - public void testRollbackPaging(final boolean restartServer) throws Exception - { + public void testRollbackPaging(final boolean restartServer) throws Exception { Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); SimpleString pageQueue = new SimpleString("pagequeue"); - AddressSettings pageAddressSettings = new AddressSettings() - .setMaxSizeBytes(100 * 1024) - .setPageSizeBytes(10 * 1024); + AddressSettings pageAddressSettings = new AddressSettings().setMaxSizeBytes(100 * 1024).setPageSizeBytes(10 * 1024); addressSettings.put(pageQueue.toString(), pageAddressSettings); @@ -349,8 +310,7 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase ClientProducer pageProducer = clientSession.createProducer(pageQueue); - for (int i = 0; i < 1000; i++) - { + for (int i = 0; i < 1000; i++) { ClientMessage m = createBytesMessage(new byte[512], true); pageProducer.send(m); } @@ -358,12 +318,10 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase clientSession.end(xid, XAResource.TMSUCCESS); clientSession.prepare(xid); - if (restartServer) - { + if (restartServer) { stopAndRestartServer(); } - else - { + else { recreateClients(); } @@ -386,14 +344,12 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase } @Test - public void testNonPersistent() throws Exception - { + public void testNonPersistent() throws Exception { testNonPersistent(true); testNonPersistent(false); } - public void testNonPersistent(final boolean commit) throws Exception - { + public void testNonPersistent(final boolean commit) throws Exception { Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); ClientMessage m1 = createTextMessage("m1", false); @@ -419,21 +375,17 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase ActiveMQTestBase.assertEqualsByteArrays(xids[0].getGlobalTransactionId(), xid.getGlobalTransactionId()); xids = clientSession.recover(XAResource.TMENDRSCAN); Assert.assertEquals(xids.length, 0); - if (commit) - { + if (commit) { clientSession.commit(xid, false); } - else - { + else { clientSession.rollback(xid); } } @Test - public void testNonPersistentMultipleIDs() throws Exception - { - for (int i = 0; i < 10; i++) - { + public void testNonPersistentMultipleIDs() throws Exception { + for (int i = 0; i < 10; i++) { Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); ClientMessage m1 = createTextMessage("m1", false); @@ -449,8 +401,7 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase clientSession.end(xid, XAResource.TMSUCCESS); clientSession.prepare(xid); - if (i == 2) - { + if (i == 2) { clientSession.commit(xid, false); } @@ -465,8 +416,7 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase Assert.assertEquals(9, xids.length); } - public void testBasicSendWithCommit(final boolean stopServer) throws Exception - { + public void testBasicSendWithCommit(final boolean stopServer) throws Exception { Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); ClientMessage m1 = createTextMessage("m1"); @@ -482,12 +432,10 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase clientSession.end(xid, XAResource.TMSUCCESS); clientSession.prepare(xid); - if (stopServer) - { + if (stopServer) { stopAndRestartServer(); } - else - { + else { recreateClients(); } @@ -516,8 +464,7 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase Assert.assertEquals(m.getBodyBuffer().readString(), "m4"); } - public void testBasicSendWithRollback(final boolean stopServer) throws Exception - { + public void testBasicSendWithRollback(final boolean stopServer) throws Exception { Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); ClientMessage m1 = createTextMessage("m1"); @@ -535,12 +482,10 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase BasicXaRecoveryTest.log.info("shutting down server"); - if (stopServer) - { + if (stopServer) { stopAndRestartServer(); } - else - { + else { recreateClients(); } @@ -560,8 +505,7 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase Assert.assertNull(m); } - public void testMultipleBeforeSendWithCommit(final boolean stopServer) throws Exception - { + public void testMultipleBeforeSendWithCommit(final boolean stopServer) throws Exception { Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); ClientMessage m1 = createTextMessage("m1"); ClientMessage m2 = createTextMessage("m2"); @@ -586,12 +530,10 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase clientSession.end(xid, XAResource.TMSUCCESS); clientSession.prepare(xid); - if (stopServer) - { + if (stopServer) { stopAndRestartServer(); } - else - { + else { recreateClients(); } @@ -619,8 +561,7 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase Assert.assertEquals(m.getBodyBuffer().readString(), "m8"); } - public void testMultipleTxSendWithCommit(final boolean stopServer) throws Exception - { + public void testMultipleTxSendWithCommit(final boolean stopServer) throws Exception { Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); Xid xid2 = new XidImpl("xa2".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); ClientMessage m1 = createTextMessage("m1"); @@ -649,12 +590,10 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase clientSession.end(xid, XAResource.TMSUCCESS); clientSession.prepare(xid); - if (stopServer) - { + if (stopServer) { stopAndRestartServer(); } - else - { + else { recreateClients(); } @@ -693,8 +632,7 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase Assert.assertEquals(m.getBodyBuffer().readString(), "m4"); } - public void testMultipleTxSendWithRollback(final boolean stopServer) throws Exception - { + public void testMultipleTxSendWithRollback(final boolean stopServer) throws Exception { Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); Xid xid2 = new XidImpl("xa2".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); ClientMessage m1 = createTextMessage("m1"); @@ -723,12 +661,10 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase clientSession.end(xid, XAResource.TMSUCCESS); clientSession.prepare(xid); - if (stopServer) - { + if (stopServer) { stopAndRestartServer(); } - else - { + else { recreateClients(); } @@ -745,8 +681,7 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase Assert.assertNull(m); } - public void testMultipleTxSendWithCommitAndRollback(final boolean stopServer) throws Exception - { + public void testMultipleTxSendWithCommitAndRollback(final boolean stopServer) throws Exception { Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); Xid xid2 = new XidImpl("xa2".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); ClientMessage m1 = createTextMessage("m1"); @@ -775,12 +710,10 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase clientSession.end(xid, XAResource.TMSUCCESS); clientSession.prepare(xid); - if (stopServer) - { + if (stopServer) { stopAndRestartServer(); } - else - { + else { recreateClients(); } @@ -809,8 +742,7 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase Assert.assertNull(m); } - public void testMultipleTxSameXidSendWithCommit(final boolean stopServer) throws Exception - { + public void testMultipleTxSameXidSendWithCommit(final boolean stopServer) throws Exception { Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); ClientMessage m1 = createTextMessage("m1"); ClientMessage m2 = createTextMessage("m2"); @@ -837,12 +769,10 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase clientSession.end(xid, XAResource.TMSUCCESS); clientSession.prepare(xid); - if (stopServer) - { + if (stopServer) { stopAndRestartServer(); } - else - { + else { recreateClients(); } @@ -882,8 +812,7 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase Assert.assertEquals(m.getBodyBuffer().readString(), "m8"); } - public void testBasicReceiveWithCommit(final boolean stopServer) throws Exception - { + public void testBasicReceiveWithCommit(final boolean stopServer) throws Exception { Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); ClientMessage m1 = createTextMessage("m1"); ClientMessage m2 = createTextMessage("m2"); @@ -917,12 +846,10 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase clientSession.end(xid, XAResource.TMSUCCESS); Assert.assertEquals("Expected XA_OK", XAResource.XA_OK, clientSession.prepare(xid)); - if (stopServer) - { + if (stopServer) { stopAndRestartServer(); } - else - { + else { recreateClients(); } @@ -943,8 +870,7 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase checkQueueDeliveryCount(atestq, 0); } - private void checkQueueDeliveryCount(SimpleString thequeue, int expectedCount) throws Exception - { + private void checkQueueDeliveryCount(SimpleString thequeue, int expectedCount) throws Exception { QueueControl queueControl = ManagementControlHelper.createQueueControl(thequeue, thequeue, mbeanServer); int actualCount = queueControl.getDeliveringCount(); @@ -952,8 +878,7 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase assertEquals(expectedCount, actualCount); } - public void testBasicReceiveWithRollback(final boolean stopServer) throws Exception - { + public void testBasicReceiveWithRollback(final boolean stopServer) throws Exception { Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); ClientMessage m1 = createTextMessage("m1"); ClientMessage m2 = createTextMessage("m2"); @@ -989,12 +914,10 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase BasicXaRecoveryTest.log.info("stopping and restarting"); - if (stopServer) - { + if (stopServer) { stopAndRestartServer(); } - else - { + else { recreateClients(); } @@ -1024,8 +947,7 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase Assert.assertEquals(m.getBodyBuffer().readString(), "m4"); } - public void testMultipleTxReceiveWithCommit(final boolean stopServer) throws Exception - { + public void testMultipleTxReceiveWithCommit(final boolean stopServer) throws Exception { Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); Xid xid2 = new XidImpl("xa2".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); ClientMessage m1 = createTextMessage("m1"); @@ -1095,12 +1017,10 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase clientSession.end(xid, XAResource.TMSUCCESS); clientSession.prepare(xid); - if (stopServer) - { + if (stopServer) { stopAndRestartServer(); } - else - { + else { recreateClients(); } @@ -1114,8 +1034,7 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase Assert.assertNull(m); } - public void testMultipleTxReceiveWithRollback(final boolean stopServer) throws Exception - { + public void testMultipleTxReceiveWithRollback(final boolean stopServer) throws Exception { Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); Xid xid2 = new XidImpl("xa2".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); ClientMessage m1 = createTextMessage("m1"); @@ -1185,12 +1104,10 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase clientSession.end(xid, XAResource.TMSUCCESS); clientSession.prepare(xid); - if (stopServer) - { + if (stopServer) { stopAndRestartServer(); } - else - { + else { recreateClients(); } @@ -1218,8 +1135,7 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase Assert.assertEquals(m.getBodyBuffer().readString(), "m4"); } - protected void stopAndRestartServer() throws Exception - { + protected void stopAndRestartServer() throws Exception { // now stop and start the server clientSession.close(); clientSession = null; @@ -1232,85 +1148,63 @@ public class BasicXaRecoveryTest extends ActiveMQTestBase createClients(); } - private void addSettings() - { - for (Map.Entry setting : addressSettings.entrySet()) - { + private void addSettings() { + for (Map.Entry setting : addressSettings.entrySet()) { server.getAddressSettingsRepository().addMatch(setting.getKey(), setting.getValue()); } } - protected void recreateClients() throws Exception - { + protected void recreateClients() throws Exception { clientSession.close(); clientSession = null; createClients(); } - private ClientMessage createTextMessage(final String s) - { + private ClientMessage createTextMessage(final String s) { return createTextMessage(s, true); } - private ClientMessage createTextMessage(final String s, final boolean durable) - { - ClientMessage message = clientSession.createMessage(ActiveMQTextMessage.TYPE, - durable, - 0, - System.currentTimeMillis(), - (byte)1); + private ClientMessage createTextMessage(final String s, final boolean durable) { + ClientMessage message = clientSession.createMessage(ActiveMQTextMessage.TYPE, durable, 0, System.currentTimeMillis(), (byte) 1); message.getBodyBuffer().writeString(s); return message; } - private ClientMessage createBytesMessage(final byte[] b, final boolean durable) - { - ClientMessage message = clientSession.createMessage(ActiveMQBytesMessage.TYPE, - durable, - 0, - System.currentTimeMillis(), - (byte)1); + private ClientMessage createBytesMessage(final byte[] b, final boolean durable) { + ClientMessage message = clientSession.createMessage(ActiveMQBytesMessage.TYPE, durable, 0, System.currentTimeMillis(), (byte) 1); message.getBodyBuffer().writeBytes(b); return message; } - private void createClients() throws Exception - { + private void createClients() throws Exception { createClients(false, true); } - private void createClients(final boolean createQueue, final boolean commitACKs) throws Exception - { + private void createClients(final boolean createQueue, final boolean commitACKs) throws Exception { locator = createInVMNonHALocator(); sessionFactory = createSessionFactory(locator); clientSession = sessionFactory.createSession(true, false, commitACKs); - if (createQueue) - { + if (createQueue) { clientSession.createQueue(atestq, atestq, null, true); } clientProducer = clientSession.createProducer(atestq); clientConsumer = clientSession.createConsumer(atestq); } - private void assertEqualXids(final Xid[] xids, final Xid... origXids) - { + private void assertEqualXids(final Xid[] xids, final Xid... origXids) { Assert.assertEquals(xids.length, origXids.length); - for (Xid xid : xids) - { + for (Xid xid : xids) { boolean found = false; - for (Xid origXid : origXids) - { + for (Xid origXid : origXids) { found = Arrays.equals(origXid.getBranchQualifier(), xid.getBranchQualifier()); - if (found) - { + if (found) { Assert.assertEquals(xid.getFormatId(), origXid.getFormatId()); ActiveMQTestBase.assertEqualsByteArrays(xid.getBranchQualifier(), origXid.getBranchQualifier()); ActiveMQTestBase.assertEqualsByteArrays(xid.getGlobalTransactionId(), origXid.getGlobalTransactionId()); break; } } - if (!found) - { + if (!found) { Assert.fail("correct xid not found: " + xid); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/xa/BasicXaTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/xa/BasicXaTest.java index 683843fe6e..7d82a25c32 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/xa/BasicXaTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/xa/BasicXaTest.java @@ -45,8 +45,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class BasicXaTest extends ActiveMQTestBase -{ +public class BasicXaTest extends ActiveMQTestBase { + private static IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private final Map addressSettings = new HashMap(); @@ -65,8 +65,7 @@ public class BasicXaTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); addressSettings.clear(); @@ -86,8 +85,7 @@ public class BasicXaTest extends ActiveMQTestBase } @Test - public void testSendWithoutXID() throws Exception - { + public void testSendWithoutXID() throws Exception { // Since both resources have same RM, TM will probably use 1PC optimization ServerLocator locator = createInVMNonHALocator(); @@ -108,13 +106,10 @@ public class BasicXaTest extends ActiveMQTestBase assertNotNull("Send went through an invalid XA Session", cons.receiveImmediate()); } - @Test - public void testACKWithoutXID() throws Exception - { + public void testACKWithoutXID() throws Exception { // Since both resources have same RM, TM will probably use 1PC optimization - ClientSessionFactory factory = createSessionFactory(locator); ClientSession session = addClientSession(factory.createSession(false, true, true)); @@ -141,7 +136,6 @@ public class BasicXaTest extends ActiveMQTestBase session.close(); - session = addClientSession(factory.createSession(false, false, false)); session.start(); @@ -154,12 +148,10 @@ public class BasicXaTest extends ActiveMQTestBase } @Test - public void testIsSameRM() throws Exception - { + public void testIsSameRM() throws Exception { try (ServerLocator locator = createNettyNonHALocator(); - ServerLocator locator2 = createNettyNonHALocator()) - { + ServerLocator locator2 = createNettyNonHALocator()) { ClientSessionFactory nettyFactory = createSessionFactory(locator); ClientSessionFactory nettyFactory2 = createSessionFactory(locator2); ClientSession session1 = nettyFactory.createSession(true, false, false); @@ -171,8 +163,7 @@ public class BasicXaTest extends ActiveMQTestBase } @Test - public void testXAInterleaveResourceSuspendWorkCommit() throws Exception - { + public void testXAInterleaveResourceSuspendWorkCommit() throws Exception { Xid xid = newXID(); Xid xid2 = newXID(); ClientProducer clientProducer = clientSession.createProducer(atestq); @@ -199,8 +190,7 @@ public class BasicXaTest extends ActiveMQTestBase } @Test - public void testXAInterleaveResourceRollbackAfterPrepare() throws Exception - { + public void testXAInterleaveResourceRollbackAfterPrepare() throws Exception { Xid xid = newXID(); Xid xid2 = newXID(); Xid xid3 = newXID(); @@ -229,8 +219,7 @@ public class BasicXaTest extends ActiveMQTestBase } @Test - public void testSendPrepareDoesntRollbackOnClose() throws Exception - { + public void testSendPrepareDoesntRollbackOnClose() throws Exception { Xid xid = newXID(); ClientMessage m1 = createTextMessage(clientSession, "m1"); @@ -270,8 +259,7 @@ public class BasicXaTest extends ActiveMQTestBase } @Test - public void testReceivePrepareDoesntRollbackOnClose() throws Exception - { + public void testReceivePrepareDoesntRollbackOnClose() throws Exception { Xid xid = newXID(); ClientSession clientSession2 = sessionFactory.createSession(false, true, true); @@ -322,41 +310,35 @@ public class BasicXaTest extends ActiveMQTestBase } @Test - public void testReceiveRollback() throws Exception - { + public void testReceiveRollback() throws Exception { int numSessions = 100; ClientSession clientSession2 = sessionFactory.createSession(false, true, true); ClientProducer clientProducer = clientSession2.createProducer(atestq); - for (int i = 0; i < numSessions; i++) - { + for (int i = 0; i < numSessions; i++) { clientProducer.send(createTextMessage(clientSession2, "m" + i)); } ClientSession[] clientSessions = new ClientSession[numSessions]; ClientConsumer[] clientConsumers = new ClientConsumer[numSessions]; TxMessageHandler[] handlers = new TxMessageHandler[numSessions]; CountDownLatch latch = new CountDownLatch(numSessions * AddressSettings.DEFAULT_MAX_DELIVERY_ATTEMPTS); - for (int i = 0; i < clientSessions.length; i++) - { + for (int i = 0; i < clientSessions.length; i++) { clientSessions[i] = sessionFactory.createSession(true, false, false); clientConsumers[i] = clientSessions[i].createConsumer(atestq); handlers[i] = new TxMessageHandler(clientSessions[i], latch); clientConsumers[i].setMessageHandler(handlers[i]); } - for (ClientSession session : clientSessions) - { + for (ClientSession session : clientSessions) { session.start(); } boolean ok = latch.await(10, TimeUnit.SECONDS); Assert.assertTrue(ok); - for (TxMessageHandler messageHandler : handlers) - { + for (TxMessageHandler messageHandler : handlers) { Assert.assertFalse(messageHandler.failedToAck); } clientSession2.close(); - for (ClientSession session : clientSessions) - { + for (ClientSession session : clientSessions) { session.stop(); session.close(); } @@ -364,53 +346,45 @@ public class BasicXaTest extends ActiveMQTestBase } @Test - public void testSendMultipleQueues() throws Exception - { + public void testSendMultipleQueues() throws Exception { multipleQueuesInternalTest(true, false, false, false, false); } @Test - public void testSendMultipleQueuesOnePhase() throws Exception - { + public void testSendMultipleQueuesOnePhase() throws Exception { multipleQueuesInternalTest(true, false, false, false, true); multipleQueuesInternalTest(false, false, true, false, true); } @Test - public void testSendMultipleQueuesOnePhaseJoin() throws Exception - { + public void testSendMultipleQueuesOnePhaseJoin() throws Exception { multipleQueuesInternalTest(true, false, false, true, true); multipleQueuesInternalTest(false, false, true, true, true); } @Test - public void testSendMultipleQueuesTwoPhaseJoin() throws Exception - { + public void testSendMultipleQueuesTwoPhaseJoin() throws Exception { multipleQueuesInternalTest(true, false, false, true, false); multipleQueuesInternalTest(false, false, true, true, false); } @Test - public void testSendMultipleQueuesRecreate() throws Exception - { + public void testSendMultipleQueuesRecreate() throws Exception { multipleQueuesInternalTest(true, false, true, false, false); } @Test - public void testSendMultipleSuspend() throws Exception - { + public void testSendMultipleSuspend() throws Exception { multipleQueuesInternalTest(true, true, false, false, false); } @Test - public void testSendMultipleSuspendRecreate() throws Exception - { + public void testSendMultipleSuspendRecreate() throws Exception { multipleQueuesInternalTest(true, true, true, false, false); } @Test - public void testSendMultipleSuspendErrorCheck() throws Exception - { + public void testSendMultipleSuspendErrorCheck() throws Exception { ClientSession session = null; session = sessionFactory.createSession(true, false, false); @@ -419,13 +393,11 @@ public class BasicXaTest extends ActiveMQTestBase session.start(xid, XAResource.TMNOFLAGS); - try - { + try { session.start(xid, XAResource.TMRESUME); Assert.fail("XAException expected"); } - catch (XAException e) - { + catch (XAException e) { Assert.assertEquals(XAException.XAER_PROTO, e.errorCode); } @@ -433,8 +405,7 @@ public class BasicXaTest extends ActiveMQTestBase } @Test - public void testEmptyXID() throws Exception - { + public void testEmptyXID() throws Exception { Xid xid = newXID(); ClientSession session = sessionFactory.createSession(true, false, false); session.start(xid, XAResource.TMNOFLAGS); @@ -504,8 +475,7 @@ public class BasicXaTest extends ActiveMQTestBase } @Test - public void testFailXID() throws Exception - { + public void testFailXID() throws Exception { Xid xid = newXID(); ClientSession session = sessionFactory.createSession(true, false, false); session.start(xid, XAResource.TMNOFLAGS); @@ -517,22 +487,18 @@ public class BasicXaTest extends ActiveMQTestBase } @Test - public void testForgetUnknownXID() throws Exception - { - try - { + public void testForgetUnknownXID() throws Exception { + try { clientSession.forget(newXID()); Assert.fail("should throw a XAERR_NOTA XAException"); } - catch (XAException e) - { + catch (XAException e) { Assert.assertEquals(XAException.XAER_NOTA, e.errorCode); } } @Test - public void testForgetHeuristicallyCommittedXID() throws Exception - { + public void testForgetHeuristicallyCommittedXID() throws Exception { Xid xid = newXID(); clientSession.start(xid, XAResource.TMNOFLAGS); clientSession.end(xid, XAResource.TMSUCCESS); @@ -541,8 +507,7 @@ public class BasicXaTest extends ActiveMQTestBase String[] preparedTransactions = messagingService.getActiveMQServerControl().listPreparedTransactions(); Assert.assertEquals(1, preparedTransactions.length); System.out.println(preparedTransactions[0]); - Assert.assertTrue(messagingService.getActiveMQServerControl() - .commitPreparedTransaction(XidImpl.toBase64String(xid))); + Assert.assertTrue(messagingService.getActiveMQServerControl().commitPreparedTransaction(XidImpl.toBase64String(xid))); Assert.assertEquals(1, messagingService.getActiveMQServerControl().listHeuristicCommittedTransactions().length); clientSession.forget(xid); @@ -551,8 +516,7 @@ public class BasicXaTest extends ActiveMQTestBase } @Test - public void testForgetHeuristicallyRolledBackXID() throws Exception - { + public void testForgetHeuristicallyRolledBackXID() throws Exception { Xid xid = newXID(); clientSession.start(xid, XAResource.TMNOFLAGS); clientSession.end(xid, XAResource.TMSUCCESS); @@ -562,8 +526,7 @@ public class BasicXaTest extends ActiveMQTestBase Assert.assertEquals(1, preparedTransactions.length); System.out.println(preparedTransactions[0]); - Assert.assertTrue(messagingService.getActiveMQServerControl() - .rollbackPreparedTransaction(XidImpl.toBase64String(xid))); + Assert.assertTrue(messagingService.getActiveMQServerControl().rollbackPreparedTransaction(XidImpl.toBase64String(xid))); Assert.assertEquals(1, messagingService.getActiveMQServerControl().listHeuristicRolledBackTransactions().length); clientSession.forget(xid); @@ -572,32 +535,27 @@ public class BasicXaTest extends ActiveMQTestBase } @Test - public void testCommitHeuristicallyCommittedXID() throws Exception - { + public void testCommitHeuristicallyCommittedXID() throws Exception { doCompleteHeuristicallyCompletedXID(true, true); } @Test - public void testCommitHeuristicallyRolledBackXID() throws Exception - { + public void testCommitHeuristicallyRolledBackXID() throws Exception { doCompleteHeuristicallyCompletedXID(true, false); } @Test - public void testRollbacktHeuristicallyCommittedXID() throws Exception - { + public void testRollbacktHeuristicallyCommittedXID() throws Exception { doCompleteHeuristicallyCompletedXID(false, true); } @Test - public void testRollbackHeuristicallyRolledBackXID() throws Exception - { + public void testRollbackHeuristicallyRolledBackXID() throws Exception { doCompleteHeuristicallyCompletedXID(false, false); } @Test - public void testSimpleJoin() throws Exception - { + public void testSimpleJoin() throws Exception { SimpleString ADDRESS1 = new SimpleString("Address-1"); SimpleString ADDRESS2 = new SimpleString("Address-2"); @@ -615,8 +573,7 @@ public class BasicXaTest extends ActiveMQTestBase ClientProducer prodA = sessionA.createProducer(ADDRESS1); ClientProducer prodB = sessionB.createProducer(ADDRESS2); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { prodA.send(createTextMessage(sessionA, "A" + i)); prodB.send(createTextMessage(sessionB, "B" + i)); } @@ -638,8 +595,7 @@ public class BasicXaTest extends ActiveMQTestBase ClientConsumer cons2 = clientSession.createConsumer(ADDRESS2); clientSession.start(); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { ClientMessage msg = cons1.receive(1000); Assert.assertNotNull(msg); Assert.assertEquals("A" + i, getTextMessage(msg)); @@ -669,8 +625,7 @@ public class BasicXaTest extends ActiveMQTestBase final boolean suspend, final boolean recreateSession, final boolean isJoinSession, - final boolean onePhase) throws Exception - { + final boolean onePhase) throws Exception { int NUMBER_OF_MSGS = 100; int NUMBER_OF_QUEUES = 10; ClientSession session = null; @@ -679,40 +634,33 @@ public class BasicXaTest extends ActiveMQTestBase ClientSession newJoinSession = null; - try - { + try { session = sessionFactory.createSession(true, false, false); - if (createQueues) - { - for (int i = 0; i < NUMBER_OF_QUEUES; i++) - { + if (createQueues) { + for (int i = 0; i < NUMBER_OF_QUEUES; i++) { session.createQueue(ADDRESS, ADDRESS.concat(Integer.toString(i)), true); - if (isJoinSession) - { + if (isJoinSession) { clientSession.createQueue(ADDRESS.concat("-join"), ADDRESS.concat("-join." + i), true); } } } - for (int tr = 0; tr < 2; tr++) - { + for (int tr = 0; tr < 2; tr++) { Xid xid = newXID(); session.start(xid, XAResource.TMNOFLAGS); ClientProducer prod = session.createProducer(ADDRESS); - for (int nmsg = 0; nmsg < NUMBER_OF_MSGS; nmsg++) - { + for (int nmsg = 0; nmsg < NUMBER_OF_MSGS; nmsg++) { ClientMessage msg = createTextMessage(session, "SimpleMessage" + nmsg); prod.send(msg); } - if (suspend) - { + if (suspend) { session.end(xid, XAResource.TMSUSPEND); session.start(xid, XAResource.TMRESUME); } @@ -721,8 +669,7 @@ public class BasicXaTest extends ActiveMQTestBase prod.close(); - if (isJoinSession) - { + if (isJoinSession) { newJoinSession = sessionFactory.createSession(true, false, false); // This is a basic condition, or a real TM wouldn't be able to join both sessions in a single @@ -739,50 +686,42 @@ public class BasicXaTest extends ActiveMQTestBase session.end(xid, XAResource.TMSUCCESS); - if (isJoinSession) - { + if (isJoinSession) { newJoinSession.end(xid, XAResource.TMSUCCESS); newJoinSession.close(); } - if (!onePhase) - { + if (!onePhase) { session.prepare(xid); } - if (recreateSession) - { + if (recreateSession) { session.close(); session = sessionFactory.createSession(true, false, false); } - if (tr == 0) - { + if (tr == 0) { session.rollback(xid); } - else - { + else { session.commit(xid, onePhase); } } - for (int i = 0; i < 2; i++) - { + for (int i = 0; i < 2; i++) { Xid xid = newXID(); session.start(xid, XAResource.TMNOFLAGS); - for (int nqueues = 0; nqueues < NUMBER_OF_QUEUES; nqueues++) - { + for (int nqueues = 0; nqueues < NUMBER_OF_QUEUES; nqueues++) { ClientConsumer consumer = session.createConsumer(ADDRESS.concat(Integer.toString(nqueues))); session.start(); - for (int nmsg = 0; nmsg < NUMBER_OF_MSGS; nmsg++) - { + for (int nmsg = 0; nmsg < NUMBER_OF_MSGS; nmsg++) { ClientMessage msg = consumer.receive(1000); Assert.assertNotNull(msg); @@ -797,16 +736,14 @@ public class BasicXaTest extends ActiveMQTestBase Assert.assertEquals("one more", getTextMessage(msg)); msg.acknowledge(); - if (suspend) - { + if (suspend) { session.end(xid, XAResource.TMSUSPEND); session.start(xid, XAResource.TMRESUME); } Assert.assertEquals("one more", getTextMessage(msg)); - if (isJoinSession) - { + if (isJoinSession) { ClientSession newSession = sessionFactory.createSession(true, false, false); newSession.start(xid, XAResource.TMJOIN); @@ -835,33 +772,28 @@ public class BasicXaTest extends ActiveMQTestBase session.prepare(xid); - if (recreateSession) - { + if (recreateSession) { session.close(); session = sessionFactory.createSession(true, false, false); } - if (i == 0) - { + if (i == 0) { session.rollback(xid); } - else - { + else { session.commit(xid, false); } } } - finally - { - if (session != null) - { + finally { + if (session != null) { session.close(); } } } - private void doCompleteHeuristicallyCompletedXID(final boolean isCommit, final boolean heuristicCommit) throws Exception - { + private void doCompleteHeuristicallyCompletedXID(final boolean isCommit, + final boolean heuristicCommit) throws Exception { Xid xid = newXID(); clientSession.start(xid, XAResource.TMNOFLAGS); clientSession.end(xid, XAResource.TMSUCCESS); @@ -870,108 +802,82 @@ public class BasicXaTest extends ActiveMQTestBase String[] preparedTransactions = messagingService.getActiveMQServerControl().listPreparedTransactions(); Assert.assertEquals(1, preparedTransactions.length); - if (heuristicCommit) - { - Assert.assertTrue(messagingService.getActiveMQServerControl() - .commitPreparedTransaction(XidImpl.toBase64String(xid))); + if (heuristicCommit) { + Assert.assertTrue(messagingService.getActiveMQServerControl().commitPreparedTransaction(XidImpl.toBase64String(xid))); Assert.assertEquals(1, messagingService.getActiveMQServerControl().listHeuristicCommittedTransactions().length); } - else - { - Assert.assertTrue(messagingService.getActiveMQServerControl() - .rollbackPreparedTransaction(XidImpl.toBase64String(xid))); + else { + Assert.assertTrue(messagingService.getActiveMQServerControl().rollbackPreparedTransaction(XidImpl.toBase64String(xid))); Assert.assertEquals(1, messagingService.getActiveMQServerControl().listHeuristicRolledBackTransactions().length); } Assert.assertEquals(0, messagingService.getActiveMQServerControl().listPreparedTransactions().length); - try - { - if (isCommit) - { + try { + if (isCommit) { clientSession.commit(xid, false); } - else - { + else { clientSession.rollback(xid); } Assert.fail("neither commit not rollback must succeed on a heuristically completed tx"); } - catch (XAException e) - { - if (heuristicCommit) - { + catch (XAException e) { + if (heuristicCommit) { Assert.assertEquals(XAException.XA_HEURCOM, e.errorCode); } - else - { + else { Assert.assertEquals(XAException.XA_HEURRB, e.errorCode); } } - if (heuristicCommit) - { + if (heuristicCommit) { Assert.assertEquals(1, messagingService.getActiveMQServerControl().listHeuristicCommittedTransactions().length); } - else - { + else { Assert.assertEquals(1, messagingService.getActiveMQServerControl().listHeuristicRolledBackTransactions().length); } } + class TxMessageHandler implements MessageHandler { - class TxMessageHandler implements MessageHandler - { boolean failedToAck = false; final ClientSession session; private final CountDownLatch latch; - - public TxMessageHandler(final ClientSession session, final CountDownLatch latch) - { + public TxMessageHandler(final ClientSession session, final CountDownLatch latch) { this.latch = latch; this.session = session; } - public void onMessage(final ClientMessage message) - { - Xid xid = new XidImpl(UUIDGenerator.getInstance().generateStringUUID().getBytes(), - 1, - UUIDGenerator.getInstance().generateStringUUID().getBytes()); - try - { + public void onMessage(final ClientMessage message) { + Xid xid = new XidImpl(UUIDGenerator.getInstance().generateStringUUID().getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); + try { session.start(xid, XAResource.TMNOFLAGS); } - catch (XAException e) - { + catch (XAException e) { e.printStackTrace(); } - try - { + try { message.acknowledge(); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { BasicXaTest.log.error("Failed to process message", e); } - try - { + try { session.end(xid, XAResource.TMSUCCESS); session.rollback(xid); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); failedToAck = true; - try - { + try { session.close(); } - catch (ActiveMQException e1) - { + catch (ActiveMQException e1) { // } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/xa/XaTimeoutTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/xa/XaTimeoutTest.java index 9e999aa5c5..f244238df6 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/xa/XaTimeoutTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/xa/XaTimeoutTest.java @@ -53,8 +53,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -public class XaTimeoutTest extends ActiveMQTestBase -{ +public class XaTimeoutTest extends ActiveMQTestBase { private final Map addressSettings = new HashMap(); @@ -76,14 +75,11 @@ public class XaTimeoutTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); addressSettings.clear(); - configuration = createBasicConfig() - .setTransactionTimeoutScanPeriod(500) - .addAcceptorConfiguration(new TransportConfiguration(ActiveMQTestBase.INVM_ACCEPTOR_FACTORY)); + configuration = createBasicConfig().setTransactionTimeoutScanPeriod(500).addAcceptorConfiguration(new TransportConfiguration(ActiveMQTestBase.INVM_ACCEPTOR_FACTORY)); server = addServer(ActiveMQServers.newActiveMQServer(configuration, false)); // start the server server.start(); @@ -97,8 +93,7 @@ public class XaTimeoutTest extends ActiveMQTestBase } @Test - public void testSimpleTimeoutOnSendOnCommit() throws Exception - { + public void testSimpleTimeoutOnSendOnCommit() throws Exception { Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); ClientMessage m1 = createTextMessage(clientSession, "m1"); @@ -115,12 +110,10 @@ public class XaTimeoutTest extends ActiveMQTestBase CountDownLatch latch = new CountDownLatch(1); server.getResourceManager().getTransaction(xid).addOperation(new RollbackCompleteOperation(latch)); Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); - try - { + try { clientSession.commit(xid, true); } - catch (XAException e) - { + catch (XAException e) { Assert.assertTrue(e.errorCode == XAException.XAER_NOTA); } clientSession.start(); @@ -129,8 +122,7 @@ public class XaTimeoutTest extends ActiveMQTestBase } @Test - public void testSimpleTimeoutOnReceive() throws Exception - { + public void testSimpleTimeoutOnReceive() throws Exception { Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); ClientMessage m1 = createTextMessage(clientSession, "m1"); @@ -167,12 +159,10 @@ public class XaTimeoutTest extends ActiveMQTestBase CountDownLatch latch = new CountDownLatch(1); server.getResourceManager().getTransaction(xid).addOperation(new RollbackCompleteOperation(latch)); Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); - try - { + try { clientSession.commit(xid, true); } - catch (XAException e) - { + catch (XAException e) { Assert.assertTrue(e.errorCode == XAException.XAER_NOTA); } clientSession.setTransactionTimeout(0); @@ -200,8 +190,7 @@ public class XaTimeoutTest extends ActiveMQTestBase } @Test - public void testSimpleTimeoutOnSendAndReceive() throws Exception - { + public void testSimpleTimeoutOnSendAndReceive() throws Exception { Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); ClientMessage m1 = createTextMessage(clientSession, "m1"); @@ -246,12 +235,10 @@ public class XaTimeoutTest extends ActiveMQTestBase CountDownLatch latch = new CountDownLatch(1); server.getResourceManager().getTransaction(xid).addOperation(new RollbackCompleteOperation(latch)); Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); - try - { + try { clientSession.commit(xid, true); } - catch (XAException e) - { + catch (XAException e) { Assert.assertTrue(e.errorCode == XAException.XAER_NOTA); } clientSession.setTransactionTimeout(0); @@ -281,8 +268,7 @@ public class XaTimeoutTest extends ActiveMQTestBase } @Test - public void testPreparedTransactionNotTimedOut() throws Exception - { + public void testPreparedTransactionNotTimedOut() throws Exception { Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); ClientMessage m1 = createTextMessage(clientSession, "m1"); @@ -356,10 +342,8 @@ public class XaTimeoutTest extends ActiveMQTestBase clientSession2.close(); } - @Test - public void testTimeoutOnConsumerResend() throws Exception - { + public void testTimeoutOnConsumerResend() throws Exception { int numberOfMessages = 100; @@ -367,8 +351,7 @@ public class XaTimeoutTest extends ActiveMQTestBase { ClientSession simpleTXSession = sessionFactory.createTransactedSession(); ClientProducer producerTX = simpleTXSession.createProducer(atestq); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage m = createTextMessage(clientSession, "m-" + i); m.putIntProperty("msg", i); producerTX.send(m); @@ -392,12 +375,9 @@ public class XaTimeoutTest extends ActiveMQTestBase outProducerSession.setTransactionTimeout(2); clientSession.setTransactionTimeout(2); - MessageHandler handler = new MessageHandler() - { - public void onMessage(ClientMessage message) - { - try - { + MessageHandler handler = new MessageHandler() { + public void onMessage(ClientMessage message) { + try { latchReceives.countDown(); Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); @@ -415,63 +395,51 @@ public class XaTimeoutTest extends ActiveMQTestBase outProducer.send(msgOut); boolean rollback = false; - if (msgCount.getAndIncrement() == 0) - { + if (msgCount.getAndIncrement() == 0) { rollback = true; System.out.println("Forcing first message to time out"); Thread.sleep(5000); } - try - { + try { clientSession.end(xid, XAResource.TMSUCCESS); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } - try - { + try { outProducerSession.end(xidOut, XAResource.TMSUCCESS); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } - if (rollback) - { - try - { + if (rollback) { + try { clientSession.rollback(xid); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); clientSession.rollback(); } - try - { + try { outProducerSession.rollback(xidOut); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); outProducerSession.rollback(); } } - else - { + else { clientSession.prepare(xid); outProducerSession.prepare(xidOut); clientSession.commit(xid, false); outProducerSession.commit(xidOut, false); } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); errors.incrementAndGet(); } @@ -489,15 +457,13 @@ public class XaTimeoutTest extends ActiveMQTestBase clientConsumer = clientSession.createConsumer(this.atestq); assertNull(clientConsumer.receiveImmediate()); - clientConsumer.close(); clientConsumer = clientSession.createConsumer(outQueue); HashSet msgsIds = new HashSet(); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = clientConsumer.receive(1000); assertNotNull(msg); msg.acknowledge(); @@ -506,8 +472,7 @@ public class XaTimeoutTest extends ActiveMQTestBase assertNull(clientConsumer.receiveImmediate()); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { assertTrue(msgsIds.contains(i)); } @@ -515,7 +480,6 @@ public class XaTimeoutTest extends ActiveMQTestBase } - /** * In case a timeout happens the server's object may still have the previous XID. * for that reason a new start call is supposed to clean it up with a log.warn @@ -524,8 +488,7 @@ public class XaTimeoutTest extends ActiveMQTestBase * @throws Exception */ @Test - public void testChangeXID() throws Exception - { + public void testChangeXID() throws Exception { Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); Xid xid2 = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); @@ -535,8 +498,7 @@ public class XaTimeoutTest extends ActiveMQTestBase } @Test - public void testChangingTimeoutGetsPickedUp() throws Exception - { + public void testChangingTimeoutGetsPickedUp() throws Exception { Xid xid = new XidImpl("xa1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); ClientMessage m1 = createTextMessage(clientSession, "m1"); @@ -562,12 +524,10 @@ public class XaTimeoutTest extends ActiveMQTestBase clientProducer.send(m4); clientSession.end(xid, XAResource.TMSUCCESS); Assert.assertTrue(latch.await(2600, TimeUnit.MILLISECONDS)); - try - { + try { clientSession.commit(xid, true); } - catch (XAException e) - { + catch (XAException e) { Assert.assertTrue(e.errorCode == XAException.XAER_NOTA); } clientSession.start(); @@ -584,79 +544,61 @@ public class XaTimeoutTest extends ActiveMQTestBase } @Test - public void testMultipleTransactionsTimedOut() throws Exception - { + public void testMultipleTransactionsTimedOut() throws Exception { Xid[] xids = new XidImpl[100]; - for (int i = 0; i < xids.length; i++) - { + for (int i = 0; i < xids.length; i++) { xids[i] = new XidImpl(("xa" + i).getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); } ClientSession[] clientSessions = new ClientSession[xids.length]; - for (int i = 0; i < clientSessions.length; i++) - { + for (int i = 0; i < clientSessions.length; i++) { clientSessions[i] = sessionFactory.createSession(true, false, false); clientSessions[i].setTransactionTimeout(i < 50 ? 2 : 5000); } ClientProducer[] clientProducers = new ClientProducer[xids.length]; - for (int i = 0; i < clientProducers.length; i++) - { + for (int i = 0; i < clientProducers.length; i++) { clientProducers[i] = clientSessions[i].createProducer(atestq); } ClientMessage[] messages = new ClientMessage[xids.length]; - for (int i = 0; i < messages.length; i++) - { + for (int i = 0; i < messages.length; i++) { messages[i] = createTextMessage(clientSession, "m" + i); } - for (int i = 0; i < clientSessions.length; i++) - { + for (int i = 0; i < clientSessions.length; i++) { clientSessions[i].start(xids[i], XAResource.TMNOFLAGS); } - for (int i = 0; i < clientProducers.length; i++) - { + for (int i = 0; i < clientProducers.length; i++) { clientProducers[i].send(messages[i]); } - for (int i = 0; i < clientSessions.length; i++) - { + for (int i = 0; i < clientSessions.length; i++) { clientSessions[i].end(xids[i], XAResource.TMSUCCESS); } CountDownLatch[] latches = new CountDownLatch[xids.length]; - for (int i1 = 0; i1 < latches.length; i1++) - { + for (int i1 = 0; i1 < latches.length; i1++) { latches[i1] = new CountDownLatch(1); - server.getResourceManager() - .getTransaction(xids[i1]) - .addOperation(new RollbackCompleteOperation(latches[i1])); + server.getResourceManager().getTransaction(xids[i1]).addOperation(new RollbackCompleteOperation(latches[i1])); } - for (int i1 = 0; i1 < latches.length / 2; i1++) - { + for (int i1 = 0; i1 < latches.length / 2; i1++) { Assert.assertTrue(latches[i1].await(5, TimeUnit.SECONDS)); } - for (int i = 0; i < clientSessions.length / 2; i++) - { - try - { + for (int i = 0; i < clientSessions.length / 2; i++) { + try { clientSessions[i].commit(xids[i], true); } - catch (XAException e) - { + catch (XAException e) { Assert.assertTrue(e.errorCode == XAException.XAER_NOTA); } } - for (int i = 50; i < clientSessions.length; i++) - { + for (int i = 50; i < clientSessions.length; i++) { clientSessions[i].commit(xids[i], true); } - for (ClientSession session : clientSessions) - { + for (ClientSession session : clientSessions) { session.close(); } clientSession.start(); - for (int i = 0; i < clientSessions.length / 2; i++) - { + for (int i = 0; i < clientSessions.length / 2; i++) { ClientMessage m = clientConsumer.receiveImmediate(); Assert.assertNotNull(m); } @@ -666,26 +608,20 @@ public class XaTimeoutTest extends ActiveMQTestBase // HORNETQ-1117 - Test that will timeout on a XA transaction and then will perform another XA operation @Test - public void testTimeoutOnXACall() throws Exception - { + public void testTimeoutOnXACall() throws Exception { final CountDownLatch latch = new CountDownLatch(1); - class SomeInterceptor implements Interceptor - { + class SomeInterceptor implements Interceptor { /* (non-Javadoc) * @see Interceptor#intercept(org.apache.activemq.artemis.core.protocol.core.Packet, RemotingConnection) */ @Override - public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException - { - if (packet instanceof SessionXAStartMessage) - { - try - { + public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException { + if (packet instanceof SessionXAStartMessage) { + try { latch.await(1, TimeUnit.MINUTES); } - catch (InterruptedException e) - { + catch (InterruptedException e) { e.printStackTrace(); } } @@ -695,8 +631,7 @@ public class XaTimeoutTest extends ActiveMQTestBase } server.getRemotingService().addIncomingInterceptor(new SomeInterceptor()); - ServerLocator locatorTimeout = createInVMNonHALocator() - .setCallTimeout(300); + ServerLocator locatorTimeout = createInVMNonHALocator().setCallTimeout(300); ClientSessionFactory factoryTimeout = locatorTimeout.createSessionFactory(); final ClientSession sessionTimeout = factoryTimeout.createSession(true, false, false); @@ -705,12 +640,10 @@ public class XaTimeoutTest extends ActiveMQTestBase boolean expectedException = false; - try - { + try { sessionTimeout.start(xid, XAResource.TMNOFLAGS); } - catch (Exception e) - { + catch (Exception e) { expectedException = true; e.printStackTrace(); } @@ -729,18 +662,16 @@ public class XaTimeoutTest extends ActiveMQTestBase locatorTimeout.close(); } - final class RollbackCompleteOperation extends TransactionOperationAbstract - { + final class RollbackCompleteOperation extends TransactionOperationAbstract { + final CountDownLatch latch; - public RollbackCompleteOperation(final CountDownLatch latch) - { + public RollbackCompleteOperation(final CountDownLatch latch) { this.latch = latch; } @Override - public void afterRollback(final Transaction tx) - { + public void afterRollback(final Transaction tx) { latch.countDown(); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/JMSClusteredTestBase.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/JMSClusteredTestBase.java index bf15ee5f84..ed326cb1aa 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/JMSClusteredTestBase.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/JMSClusteredTestBase.java @@ -39,8 +39,7 @@ import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import java.util.ArrayList; -public class JMSClusteredTestBase extends ActiveMQTestBase -{ +public class JMSClusteredTestBase extends ActiveMQTestBase { private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; @@ -83,8 +82,7 @@ public class JMSClusteredTestBase extends ActiveMQTestBase /** * @throws Exception */ - protected Queue createQueue(final String name) throws Exception - { + protected Queue createQueue(final String name) throws Exception { jmsServer2.createQueue(false, name, null, true, "/queue/" + name); jmsServer1.createQueue(false, name, null, true, "/queue/" + name); @@ -94,13 +92,11 @@ public class JMSClusteredTestBase extends ActiveMQTestBase return (Queue) context1.lookup("/queue/" + name); } - protected Topic createTopic(final String name) throws Exception - { + protected Topic createTopic(final String name) throws Exception { return createTopic(name, false); } - protected Topic createTopic(final String name, boolean durable) throws Exception - { + protected Topic createTopic(final String name, boolean durable) throws Exception { jmsServer2.createTopic(durable, name, "/topic/" + name); jmsServer1.createTopic(durable, name, "/topic/" + name); @@ -109,8 +105,7 @@ public class JMSClusteredTestBase extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); setupServer2(); @@ -128,17 +123,14 @@ public class JMSClusteredTestBase extends ActiveMQTestBase waitForTopology(jmsServer2.getActiveMQServer(), 2); - cf1 = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(InVMConnectorFactory.class.getName(), - generateInVMParams(1))); - cf2 = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(InVMConnectorFactory.class.getName(), - generateInVMParams(2))); + cf1 = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(InVMConnectorFactory.class.getName(), generateInVMParams(1))); + cf2 = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(InVMConnectorFactory.class.getName(), generateInVMParams(2))); } /** * @throws Exception */ - private void setupServer2() throws Exception - { + private void setupServer2() throws Exception { Configuration configuration = createConfigServer(2, 1); JMSConfigurationImpl jmsconfig = new JMSConfigurationImpl(); @@ -153,8 +145,7 @@ public class JMSClusteredTestBase extends ActiveMQTestBase /** * @throws Exception */ - private void setupServer1() throws Exception - { + private void setupServer1() throws Exception { Configuration configuration = createConfigServer(1, 2); JMSConfigurationImpl jmsconfig = new JMSConfigurationImpl(); @@ -166,39 +157,22 @@ public class JMSClusteredTestBase extends ActiveMQTestBase jmsServer1.setRegistry(new JndiBindingRegistry(context1)); } - protected boolean enablePersistence() - { + protected boolean enablePersistence() { return false; } /** * @return */ - protected Configuration createConfigServer(final int source, final int destination) throws Exception - { + protected Configuration createConfigServer(final int source, final int destination) throws Exception { final String destinationLabel = "toServer" + destination; final String sourceLabel = "server" + source; - Configuration configuration = createDefaultInVMConfig(source) - .setSecurityEnabled(false) - .setJMXManagementEnabled(true) - .setPersistenceEnabled(false) - .addConnectorConfiguration(destinationLabel, new TransportConfiguration(InVMConnectorFactory.class.getName(), generateInVMParams(destination))) - .addConnectorConfiguration(sourceLabel, new TransportConfiguration(InVMConnectorFactory.class.getName(), generateInVMParams(source))) - .addClusterConfiguration(new ClusterConnectionConfiguration() - .setName(destinationLabel) - .setAddress("jms") - .setConnectorName(sourceLabel) - .setRetryInterval(1000) - .setMaxHops(MAX_HOPS) - .setConfirmationWindowSize(1024) - .setMessageLoadBalancingType(MessageLoadBalancingType.ON_DEMAND) - .setStaticConnectors(new ArrayList() - { - { - add(destinationLabel); - } - })); + Configuration configuration = createDefaultInVMConfig(source).setSecurityEnabled(false).setJMXManagementEnabled(true).setPersistenceEnabled(false).addConnectorConfiguration(destinationLabel, new TransportConfiguration(InVMConnectorFactory.class.getName(), generateInVMParams(destination))).addConnectorConfiguration(sourceLabel, new TransportConfiguration(InVMConnectorFactory.class.getName(), generateInVMParams(source))).addClusterConfiguration(new ClusterConnectionConfiguration().setName(destinationLabel).setAddress("jms").setConnectorName(sourceLabel).setRetryInterval(1000).setMaxHops(MAX_HOPS).setConfirmationWindowSize(1024).setMessageLoadBalancingType(MessageLoadBalancingType.ON_DEMAND).setStaticConnectors(new ArrayList() { + { + add(destinationLabel); + } + })); return configuration; } @@ -207,5 +181,4 @@ public class JMSClusteredTestBase extends ActiveMQTestBase // Inner classes ------------------------------------------------- - } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/JMSTestBase.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/JMSTestBase.java index 49560efa64..d46861723f 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/JMSTestBase.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/JMSTestBase.java @@ -51,8 +51,8 @@ import org.junit.After; import org.junit.Assert; import org.junit.Before; -public class JMSTestBase extends ActiveMQTestBase -{ +public class JMSTestBase extends ActiveMQTestBase { + protected ActiveMQServer server; protected JMSServerManagerImpl jmsServer; @@ -65,60 +65,48 @@ public class JMSTestBase extends ActiveMQTestBase private final Random random = new Random(); protected InVMNamingContext namingContext; - protected boolean useSecurity() - { + protected boolean useSecurity() { return false; } - protected boolean useJMX() - { + protected boolean useJMX() { return true; } - protected boolean usePersistence() - { + protected boolean usePersistence() { return false; } - protected final JMSContext addContext(JMSContext context0) - { + protected final JMSContext addContext(JMSContext context0) { contextSet.add(context0); return context0; } - protected final JMSContext createContext() - { + protected final JMSContext createContext() { return addContext(cf.createContext()); } - protected final JMSContext createContext(int sessionMode) - { + protected final JMSContext createContext(int sessionMode) { return addContext(cf.createContext(null, null, sessionMode)); } /** * @throws Exception */ - protected Queue createQueue(final String queueName) throws Exception - { + protected Queue createQueue(final String queueName) throws Exception { return createQueue(false, queueName); } - protected Topic createTopic(final String topicName) throws Exception - { + protected Topic createTopic(final String topicName) throws Exception { return createTopic(false, topicName); } - - protected long getMessageCount(JMSQueueControl control) throws Exception - { + protected long getMessageCount(JMSQueueControl control) throws Exception { control.flushExecutor(); return control.getMessageCount(); } - - protected long getMessageCount(QueueControl control) throws Exception - { + protected long getMessageCount(QueueControl control) throws Exception { control.flushExecutor(); return control.getMessageCount(); } @@ -126,15 +114,13 @@ public class JMSTestBase extends ActiveMQTestBase /** * @throws Exception */ - protected Queue createQueue(final boolean storeConfig, final String queueName) throws Exception - { + protected Queue createQueue(final boolean storeConfig, final String queueName) throws Exception { jmsServer.createQueue(storeConfig, queueName, null, true, "/jms/" + queueName); return (Queue) namingContext.lookup("/jms/" + queueName); } - protected Topic createTopic(final boolean storeConfig, final String topicName) throws Exception - { + protected Topic createTopic(final boolean storeConfig, final String topicName) throws Exception { jmsServer.createTopic(storeConfig, topicName, "/jms/" + topicName); return (Topic) namingContext.lookup("/jms/" + topicName); @@ -142,15 +128,12 @@ public class JMSTestBase extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); mbeanServer = MBeanServerFactory.createMBeanServer(); - Configuration config = createDefaultConfig(true) - .setSecurityEnabled(useSecurity()) - .addConnectorConfiguration("invm", new TransportConfiguration(INVM_CONNECTOR_FACTORY)); + Configuration config = createDefaultConfig(true).setSecurityEnabled(useSecurity()).addConnectorConfiguration("invm", new TransportConfiguration(INVM_CONNECTOR_FACTORY)); server = addServer(ActiveMQServers.newActiveMQServer(config, mbeanServer, usePersistence())); jmsServer = new JMSServerManagerImpl(server); @@ -162,14 +145,11 @@ public class JMSTestBase extends ActiveMQTestBase } @Override - protected Configuration createDefaultConfig(boolean netty) throws Exception - { - return super.createDefaultConfig(netty) - .setJMXManagementEnabled(true); + protected Configuration createDefaultConfig(boolean netty) throws Exception { + return super.createDefaultConfig(netty).setJMXManagementEnabled(true); } - protected void restartServer() throws Exception - { + protected void restartServer() throws Exception { namingContext = new InVMNamingContext(); jmsServer.setRegistry(new JndiBindingRegistry(namingContext)); jmsServer.start(); @@ -177,37 +157,29 @@ public class JMSTestBase extends ActiveMQTestBase registerConnectionFactory(); } - protected void killServer() throws Exception - { + protected void killServer() throws Exception { jmsServer.stop(); } @Override @After - public void tearDown() throws Exception - { - try - { - for (JMSContext jmsContext : contextSet) - { + public void tearDown() throws Exception { + try { + for (JMSContext jmsContext : contextSet) { jmsContext.close(); } } - catch (RuntimeException ignored) - { + catch (RuntimeException ignored) { // no-op } - finally - { + finally { contextSet.clear(); } - try - { + try { if (conn != null) conn.close(); } - catch (Exception e) - { + catch (Exception e) { // no-op } @@ -228,8 +200,7 @@ public class JMSTestBase extends ActiveMQTestBase super.tearDown(); } - protected void registerConnectionFactory() throws Exception - { + protected void registerConnectionFactory() throws Exception { List connectorConfigs = new ArrayList(); connectorConfigs.add(new TransportConfiguration(INVM_CONNECTOR_FACTORY)); @@ -243,15 +214,11 @@ public class JMSTestBase extends ActiveMQTestBase * @param jndiBindings * @throws Exception */ - protected void createCF(final List connectorConfigs, final String... jndiBindings) throws Exception - { + protected void createCF(final List connectorConfigs, + final String... jndiBindings) throws Exception { List connectorNames = registerConnectors(server, connectorConfigs); - ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl() - .setName(name.getMethodName()) - .setConnectorNames(connectorNames) - .setRetryInterval(1000) - .setReconnectAttempts(-1); + ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl().setName(name.getMethodName()).setConnectorNames(connectorNames).setRetryInterval(1000).setReconnectAttempts(-1); testCaseCfExtraConfig(configuration); jmsServer.createConnectionFactory(false, configuration, jndiBindings); } @@ -261,21 +228,16 @@ public class JMSTestBase extends ActiveMQTestBase * * @param configuration */ - protected void testCaseCfExtraConfig(ConnectionFactoryConfiguration configuration) - { + protected void testCaseCfExtraConfig(ConnectionFactoryConfiguration configuration) { // no-op } - protected final void sendMessages(JMSContext context, JMSProducer producer, Queue queue, final int total) - { - try - { - for (int j = 0; j < total; j++) - { + protected final void sendMessages(JMSContext context, JMSProducer producer, Queue queue, final int total) { + try { + for (int j = 0; j < total; j++) { StringBuilder sb = new StringBuilder(); - for (int m = 0; m < 200; m++) - { + for (int m = 0; m < 200; m++) { sb.append(random.nextLong()); } Message msg = context.createTextMessage(sb.toString()); @@ -283,24 +245,18 @@ public class JMSTestBase extends ActiveMQTestBase producer.send(queue, msg); } } - catch (JMSException cause) - { + catch (JMSException cause) { throw new JMSRuntimeException(cause.getMessage(), cause.getErrorCode(), cause); } } - protected void useDummyTransactionManager() - { + protected void useDummyTransactionManager() { ServiceUtils.setTransactionManager(new DummyTransactionManager()); } - protected final void receiveMessages(JMSConsumer consumer, final int start, final int msgCount, final boolean ack) - - { - try - { - for (int i = start; i < msgCount; i++) - { + protected final void receiveMessages(JMSConsumer consumer, final int start, final int msgCount, final boolean ack) { + try { + for (int i = start; i < msgCount; i++) { Message message = consumer.receive(100); Assert.assertNotNull("Expecting a message " + i, message); final int actual = message.getIntProperty("counter"); @@ -309,8 +265,7 @@ public class JMSTestBase extends ActiveMQTestBase message.acknowledge(); } } - catch (JMSException cause) - { + catch (JMSException cause) { throw new JMSRuntimeException(cause.getMessage(), cause.getErrorCode(), cause); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/NonSerializableFactory.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/NonSerializableFactory.java index 086165772d..aea3b70155 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/NonSerializableFactory.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/NonSerializableFactory.java @@ -27,79 +27,75 @@ import java.util.HashMap; import java.util.Hashtable; import java.util.Map; - /** * used by the default context when running in embedded local configuration */ -public final class NonSerializableFactory implements ObjectFactory -{ +public final class NonSerializableFactory implements ObjectFactory { - private NonSerializableFactory() - { + private NonSerializableFactory() { // Utility } -// public static void unbind(final Context ctx, final String strName) throws NamingException -// { -// Name name = ctx.getNameParser("").parse(strName); -// int size = name.size(); -// String atom = name.get(size - 1); -// Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1)); -// String key = new StringBuilder().append(parentCtx.getNameInNamespace()).append("/").append(atom).toString(); -// NonSerializableFactory.getWrapperMap().remove(key); -// Util.unbind(ctx, strName); -// } -// -// public static void rebind(final Context ctx, final String strName, final Object value) throws NamingException -// { -// Name name = ctx.getNameParser("").parse(strName); -// int size = name.size(); -// String atom = name.get(size - 1); -// Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1)); -// String key = new StringBuilder().append(parentCtx.getNameInNamespace()).append("/").append(atom).toString(); -// NonSerializableFactory.getWrapperMap().put(key, value); -// String className = value.getClass().getName(); -// String factory = NonSerializableFactory.class.getName(); -// StringRefAddr addr = new StringRefAddr("nns", key); -// Reference memoryRef = new Reference(className, addr, factory, null); -// parentCtx.rebind(atom, memoryRef); -// } -// -// public static void bind(final Context ctx, final String strName, final Object value) throws NamingException -// { -// Name name = ctx.getNameParser("").parse(strName); -// int size = name.size(); -// String atom = name.get(size - 1); -// Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1)); -// String key = new StringBuilder().append(parentCtx.getNameInNamespace()).append("/").append(atom).toString(); -// NonSerializableFactory.getWrapperMap().put(key, value); -// String className = value.getClass().getName(); -// String factory = NonSerializableFactory.class.getName(); -// StringRefAddr addr = new StringRefAddr("nns", key); -// Reference memoryRef = new Reference(className, addr, factory, null); -// -// parentCtx.bind(atom, memoryRef); -// } + // public static void unbind(final Context ctx, final String strName) throws NamingException + // { + // Name name = ctx.getNameParser("").parse(strName); + // int size = name.size(); + // String atom = name.get(size - 1); + // Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1)); + // String key = new StringBuilder().append(parentCtx.getNameInNamespace()).append("/").append(atom).toString(); + // NonSerializableFactory.getWrapperMap().remove(key); + // Util.unbind(ctx, strName); + // } + // + // public static void rebind(final Context ctx, final String strName, final Object value) throws NamingException + // { + // Name name = ctx.getNameParser("").parse(strName); + // int size = name.size(); + // String atom = name.get(size - 1); + // Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1)); + // String key = new StringBuilder().append(parentCtx.getNameInNamespace()).append("/").append(atom).toString(); + // NonSerializableFactory.getWrapperMap().put(key, value); + // String className = value.getClass().getName(); + // String factory = NonSerializableFactory.class.getName(); + // StringRefAddr addr = new StringRefAddr("nns", key); + // Reference memoryRef = new Reference(className, addr, factory, null); + // parentCtx.rebind(atom, memoryRef); + // } + // + // public static void bind(final Context ctx, final String strName, final Object value) throws NamingException + // { + // Name name = ctx.getNameParser("").parse(strName); + // int size = name.size(); + // String atom = name.get(size - 1); + // Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1)); + // String key = new StringBuilder().append(parentCtx.getNameInNamespace()).append("/").append(atom).toString(); + // NonSerializableFactory.getWrapperMap().put(key, value); + // String className = value.getClass().getName(); + // String factory = NonSerializableFactory.class.getName(); + // StringRefAddr addr = new StringRefAddr("nns", key); + // Reference memoryRef = new Reference(className, addr, factory, null); + // + // parentCtx.bind(atom, memoryRef); + // } - public static Object lookup(final String name) throws NamingException - { - if (NonSerializableFactory.getWrapperMap().get(name) == null) - { + public static Object lookup(final String name) throws NamingException { + if (NonSerializableFactory.getWrapperMap().get(name) == null) { throw new NamingException(name + " not found"); } return NonSerializableFactory.getWrapperMap().get(name); } - public Object getObjectInstance(final Object obj, final Name name, final Context nameCtx, final Hashtable env) throws Exception - { + public Object getObjectInstance(final Object obj, + final Name name, + final Context nameCtx, + final Hashtable env) throws Exception { Reference ref = (Reference) obj; RefAddr addr = ref.get("nns"); String key = (String) addr.getContent(); return NonSerializableFactory.getWrapperMap().get(key); } - public static Map getWrapperMap() - { + public static Map getWrapperMap() { return NonSerializableFactory.wrapperMap; } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/ReplicatedBackupUtils.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/ReplicatedBackupUtils.java index c20a0cf5e1..1a38a6ac70 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/ReplicatedBackupUtils.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/ReplicatedBackupUtils.java @@ -21,12 +21,12 @@ import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.core.config.ha.ReplicaPolicyConfiguration; import org.apache.activemq.artemis.core.config.ha.ReplicatedPolicyConfiguration; -public final class ReplicatedBackupUtils -{ +public final class ReplicatedBackupUtils { + public static final String LIVE_NODE_NAME = "amqLIVE"; public static final String BACKUP_NODE_NAME = "amqBackup"; - private ReplicatedBackupUtils() - { + + private ReplicatedBackupUtils() { // Utility class } @@ -35,28 +35,17 @@ public final class ReplicatedBackupUtils TransportConfiguration backupAcceptor, Configuration liveConfig, TransportConfiguration liveConnector, - TransportConfiguration liveAcceptor) - { - if (backupAcceptor != null) - { + TransportConfiguration liveAcceptor) { + if (backupAcceptor != null) { backupConfig.clearAcceptorConfigurations().addAcceptorConfiguration(backupAcceptor); } - if (liveAcceptor != null) - { + if (liveAcceptor != null) { liveConfig.clearAcceptorConfigurations().addAcceptorConfiguration(liveAcceptor); } - backupConfig.addConnectorConfiguration(BACKUP_NODE_NAME, backupConnector) - .addConnectorConfiguration(LIVE_NODE_NAME, liveConnector) - .addClusterConfiguration(ActiveMQTestBase.basicClusterConnectionConfig(BACKUP_NODE_NAME, LIVE_NODE_NAME)) - .setHAPolicyConfiguration(new ReplicaPolicyConfiguration()); + backupConfig.addConnectorConfiguration(BACKUP_NODE_NAME, backupConnector).addConnectorConfiguration(LIVE_NODE_NAME, liveConnector).addClusterConfiguration(ActiveMQTestBase.basicClusterConnectionConfig(BACKUP_NODE_NAME, LIVE_NODE_NAME)).setHAPolicyConfiguration(new ReplicaPolicyConfiguration()); - liveConfig.setName(LIVE_NODE_NAME) - .addConnectorConfiguration(LIVE_NODE_NAME, liveConnector) - .addConnectorConfiguration(BACKUP_NODE_NAME, backupConnector) - .setSecurityEnabled(false) - .addClusterConfiguration(ActiveMQTestBase.basicClusterConnectionConfig(LIVE_NODE_NAME, BACKUP_NODE_NAME)) - .setHAPolicyConfiguration(new ReplicatedPolicyConfiguration()); + liveConfig.setName(LIVE_NODE_NAME).addConnectorConfiguration(LIVE_NODE_NAME, liveConnector).addConnectorConfiguration(BACKUP_NODE_NAME, backupConnector).setSecurityEnabled(false).addClusterConfiguration(ActiveMQTestBase.basicClusterConnectionConfig(LIVE_NODE_NAME, BACKUP_NODE_NAME)).setHAPolicyConfiguration(new ReplicatedPolicyConfiguration()); } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/TransportConfigurationUtils.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/TransportConfigurationUtils.java index 0ded23555e..6aa3b451ef 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/TransportConfigurationUtils.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/TransportConfigurationUtils.java @@ -22,61 +22,49 @@ import java.util.Map; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.core.remoting.impl.invm.TransportConstants; -public final class TransportConfigurationUtils -{ +public final class TransportConfigurationUtils { - private TransportConfigurationUtils() - { + private TransportConfigurationUtils() { // Utility } - public static TransportConfiguration getInVMAcceptor(final boolean live) - { + public static TransportConfiguration getInVMAcceptor(final boolean live) { return transportConfiguration(ActiveMQTestBase.INVM_ACCEPTOR_FACTORY, live); } - public static TransportConfiguration getInVMConnector(final boolean live) - { + public static TransportConfiguration getInVMConnector(final boolean live) { return transportConfiguration(ActiveMQTestBase.INVM_CONNECTOR_FACTORY, live); } - public static TransportConfiguration getInVMAcceptor(final boolean live, int server) - { + public static TransportConfiguration getInVMAcceptor(final boolean live, int server) { return transportConfiguration(ActiveMQTestBase.INVM_ACCEPTOR_FACTORY, live, server); } - public static TransportConfiguration getInVMConnector(final boolean live, int server) - { + public static TransportConfiguration getInVMConnector(final boolean live, int server) { return transportConfiguration(ActiveMQTestBase.INVM_CONNECTOR_FACTORY, live, server); } - public static TransportConfiguration getNettyAcceptor(final boolean live, int server) - { + public static TransportConfiguration getNettyAcceptor(final boolean live, int server) { return transportConfiguration(ActiveMQTestBase.NETTY_ACCEPTOR_FACTORY, live, server); } - public static TransportConfiguration getNettyConnector(final boolean live, int server) - { + public static TransportConfiguration getNettyConnector(final boolean live, int server) { return transportConfiguration(ActiveMQTestBase.NETTY_CONNECTOR_FACTORY, live, server); } - public static TransportConfiguration getInVMAcceptor(final boolean live, int server, String name) - { + public static TransportConfiguration getInVMAcceptor(final boolean live, int server, String name) { return transportConfiguration(ActiveMQTestBase.INVM_ACCEPTOR_FACTORY, live, server, name); } - public static TransportConfiguration getInVMConnector(final boolean live, int server, String name) - { + public static TransportConfiguration getInVMConnector(final boolean live, int server, String name) { return transportConfiguration(ActiveMQTestBase.INVM_CONNECTOR_FACTORY, live, server, name); } - public static TransportConfiguration getNettyAcceptor(final boolean live, int server, String name) - { + public static TransportConfiguration getNettyAcceptor(final boolean live, int server, String name) { return transportConfiguration(ActiveMQTestBase.NETTY_ACCEPTOR_FACTORY, live, server, name); } - public static TransportConfiguration getNettyConnector(final boolean live, int server, String name) - { + public static TransportConfiguration getNettyConnector(final boolean live, int server, String name) { return transportConfiguration(ActiveMQTestBase.NETTY_CONNECTOR_FACTORY, live, server, name); } @@ -85,10 +73,8 @@ public final class TransportConfigurationUtils * @param live * @return */ - private static TransportConfiguration transportConfiguration(String classname, boolean live) - { - if (live) - { + private static TransportConfiguration transportConfiguration(String classname, boolean live) { + if (live) { return new TransportConfiguration(classname); } @@ -97,10 +83,8 @@ public final class TransportConfigurationUtils return new TransportConfiguration(classname, server1Params); } - private static TransportConfiguration transportConfiguration(String classname, boolean live, int server) - { - if (classname.contains("netty")) - { + private static TransportConfiguration transportConfiguration(String classname, boolean live, int server) { + if (classname.contains("netty")) { Map serverParams = new HashMap(); Integer port = live ? 61616 : 5545; serverParams.put(org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.PORT_PROP_NAME, port); @@ -112,10 +96,11 @@ public final class TransportConfigurationUtils return new TransportConfiguration(classname, serverParams); } - private static TransportConfiguration transportConfiguration(String classname, boolean live, int server, String name) - { - if (classname.contains("netty")) - { + private static TransportConfiguration transportConfiguration(String classname, + boolean live, + int server, + String name) { + if (classname.contains("netty")) { Map serverParams = new HashMap(); Integer port = live ? 61616 : 5545; serverParams.put(org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.PORT_PROP_NAME, port); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/transactions/DummyTransactionManagerLocator.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/transactions/DummyTransactionManagerLocator.java index 2fb92f175e..0b79b1fd72 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/transactions/DummyTransactionManagerLocator.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/transactions/DummyTransactionManagerLocator.java @@ -27,65 +27,55 @@ import javax.transaction.TransactionManager; import org.apache.activemq.artemis.service.extensions.transactions.TransactionManagerLocator; -public class DummyTransactionManagerLocator implements TransactionManagerLocator,TransactionManager -{ +public class DummyTransactionManagerLocator implements TransactionManagerLocator, TransactionManager { + @Override - public void begin() throws NotSupportedException, SystemException - { + public void begin() throws NotSupportedException, SystemException { } @Override - public void commit() throws HeuristicMixedException, HeuristicRollbackException, IllegalStateException, RollbackException, SecurityException, SystemException - { + public void commit() throws HeuristicMixedException, HeuristicRollbackException, IllegalStateException, RollbackException, SecurityException, SystemException { } @Override - public int getStatus() throws SystemException - { + public int getStatus() throws SystemException { return 0; } @Override - public Transaction getTransaction() throws SystemException - { + public Transaction getTransaction() throws SystemException { return null; } @Override - public void resume(Transaction transaction) throws IllegalStateException, InvalidTransactionException, SystemException - { + public void resume(Transaction transaction) throws IllegalStateException, InvalidTransactionException, SystemException { } @Override - public void rollback() throws IllegalStateException, SecurityException, SystemException - { + public void rollback() throws IllegalStateException, SecurityException, SystemException { } @Override - public void setRollbackOnly() throws IllegalStateException, SystemException - { + public void setRollbackOnly() throws IllegalStateException, SystemException { } @Override - public void setTransactionTimeout(int i) throws SystemException - { + public void setTransactionTimeout(int i) throws SystemException { } @Override - public Transaction suspend() throws SystemException - { + public Transaction suspend() throws SystemException { return null; } @Override - public TransactionManager getTransactionManager() - { + public TransactionManager getTransactionManager() { return this; } } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/transactions/TransactionManagerLocatorTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/transactions/TransactionManagerLocatorTest.java index 0204f14587..b0d996929a 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/transactions/TransactionManagerLocatorTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/transactions/TransactionManagerLocatorTest.java @@ -20,11 +20,10 @@ import org.apache.activemq.artemis.service.extensions.ServiceUtils; import org.junit.Assert; import org.junit.Test; -public class TransactionManagerLocatorTest extends Assert -{ +public class TransactionManagerLocatorTest extends Assert { + @Test - public void getTM() - { + public void getTM() { assertNotNull(ServiceUtils.getTransactionManager()); assertEquals(ServiceUtils.getTransactionManager().getClass(), DummyTransactionManagerLocator.class); } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/AcknowledgementTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/AcknowledgementTest.java index b072eaeda8..1ce2bf948a 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/AcknowledgementTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/AcknowledgementTest.java @@ -36,14 +36,13 @@ import org.junit.Test; import static java.util.concurrent.TimeUnit.MILLISECONDS; -public class AcknowledgementTest extends JMSTestCase -{ +public class AcknowledgementTest extends JMSTestCase { + /** * Topics shouldn't hold on to messages if there are no subscribers */ @Test - public void testPersistentMessagesForTopicDropped() throws Exception - { + public void testPersistentMessagesForTopicDropped() throws Exception { TopicConnection topicConn = createTopicConnection(); TopicSession sess = topicConn.createTopicSession(true, 0); TopicPublisher pub = sess.createPublisher(ActiveMQServerTestCase.topic1); @@ -62,8 +61,7 @@ public class AcknowledgementTest extends JMSTestCase * Topics shouldn't hold on to messages when the non-durable subscribers close */ @Test - public void testPersistentMessagesForTopicDropped2() throws Exception - { + public void testPersistentMessagesForTopicDropped2() throws Exception { TopicConnection topicConn = createTopicConnection(); topicConn.start(); TopicSession sess = topicConn.createTopicSession(true, 0); @@ -89,8 +87,7 @@ public class AcknowledgementTest extends JMSTestCase } @Test - public void testRollbackRecover() throws Exception - { + public void testRollbackRecover() throws Exception { TopicConnection topicConn = createTopicConnection(); TopicSession sess = topicConn.createTopicSession(true, 0); TopicPublisher pub = sess.createPublisher(ActiveMQServerTestCase.topic1); @@ -149,8 +146,7 @@ public class AcknowledgementTest extends JMSTestCase } @Test - public void testTransactionalAcknowledgement() throws Exception - { + public void testTransactionalAcknowledgement() throws Exception { Connection conn = createConnection(); Session producerSess = conn.createSession(true, Session.SESSION_TRANSACTED); @@ -163,8 +159,7 @@ public class AcknowledgementTest extends JMSTestCase final int NUM_MESSAGES = 20; // Send some messages - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); producer.send(m); } @@ -174,8 +169,7 @@ public class AcknowledgementTest extends JMSTestCase producerSess.rollback(); // Send some messages - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); producer.send(m); } @@ -186,11 +180,9 @@ public class AcknowledgementTest extends JMSTestCase assertRemainingMessages(NUM_MESSAGES); int count = 0; - while (true) - { + while (true) { Message m = consumer.receive(200); - if (m == null) - { + if (m == null) { break; } count++; @@ -205,8 +197,7 @@ public class AcknowledgementTest extends JMSTestCase assertRemainingMessages(NUM_MESSAGES); int i = 0; - for (; i < NUM_MESSAGES; i++) - { + for (; i < NUM_MESSAGES; i++) { consumer.receive(); } @@ -225,8 +216,7 @@ public class AcknowledgementTest extends JMSTestCase * Send some messages, don't acknowledge them and verify that they are re-sent on recovery. */ @Test - public void testClientAcknowledgeNoAcknowledgement() throws Exception - { + public void testClientAcknowledgeNoAcknowledgement() throws Exception { Connection conn = createConnection(); Session producerSess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); @@ -239,8 +229,7 @@ public class AcknowledgementTest extends JMSTestCase final int NUM_MESSAGES = 20; // Send some messages - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); producer.send(m); } @@ -250,11 +239,9 @@ public class AcknowledgementTest extends JMSTestCase log.trace("Sent messages"); int count = 0; - while (true) - { + while (true) { Message m = consumer.receive(1000); - if (m == null) - { + if (m == null) { break; } count++; @@ -275,8 +262,7 @@ public class AcknowledgementTest extends JMSTestCase Message m = null; int i = 0; - for (; i < NUM_MESSAGES; i++) - { + for (; i < NUM_MESSAGES; i++) { m = consumer.receive(); log.trace("Received message " + i); @@ -303,8 +289,7 @@ public class AcknowledgementTest extends JMSTestCase * Send some messages, acknowledge them individually and verify they are not resent after recovery. */ @Test - public void testIndividualClientAcknowledge() throws Exception - { + public void testIndividualClientAcknowledge() throws Exception { Connection conn = createConnection(); Session producerSess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); @@ -316,16 +301,14 @@ public class AcknowledgementTest extends JMSTestCase final int NUM_MESSAGES = 20; - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); producer.send(m); } assertRemainingMessages(NUM_MESSAGES); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = consumer.receive(200); ProxyAssertSupport.assertNotNull(m); @@ -349,8 +332,7 @@ public class AcknowledgementTest extends JMSTestCase * Send some messages, acknowledge them once after all have been received verify they are not resent after recovery */ @Test - public void testBulkClientAcknowledge() throws Exception - { + public void testBulkClientAcknowledge() throws Exception { Connection conn = createConnection(); Session producerSess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); @@ -363,8 +345,7 @@ public class AcknowledgementTest extends JMSTestCase final int NUM_MESSAGES = 20; // Send some messages - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); producer.send(m); } @@ -375,11 +356,9 @@ public class AcknowledgementTest extends JMSTestCase Message m = null; int count = 0; - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { m = consumer.receive(200); - if (m == null) - { + if (m == null) { break; } count++; @@ -412,11 +391,9 @@ public class AcknowledgementTest extends JMSTestCase * Send some messages, acknowledge some of them, and verify that the others are resent after delivery */ @Test - public void testPartialClientAcknowledge() throws Exception - { + public void testPartialClientAcknowledge() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session producerSess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); @@ -430,8 +407,7 @@ public class AcknowledgementTest extends JMSTestCase final int ACKED_MESSAGES = 11; // Send some messages - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); producer.send(m); } @@ -443,15 +419,12 @@ public class AcknowledgementTest extends JMSTestCase int count = 0; Message m = null; - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { m = consumer.receive(200); - if (m == null) - { + if (m == null) { break; } - if (count == ACKED_MESSAGES - 1) - { + if (count == ACKED_MESSAGES - 1) { m.acknowledge(); } count++; @@ -470,11 +443,9 @@ public class AcknowledgementTest extends JMSTestCase log.trace("Session recover called"); count = 0; - while (true) - { + while (true) { m = consumer.receive(200); - if (m == null) - { + if (m == null) { break; } count++; @@ -482,10 +453,8 @@ public class AcknowledgementTest extends JMSTestCase ProxyAssertSupport.assertEquals(NUM_MESSAGES - ACKED_MESSAGES, count); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } @@ -497,8 +466,7 @@ public class AcknowledgementTest extends JMSTestCase * Send some messages, consume them and verify the messages are not sent upon recovery */ @Test - public void testAutoAcknowledge() throws Exception - { + public void testAutoAcknowledge() throws Exception { Connection conn = createConnection(); Session producerSess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -513,8 +481,7 @@ public class AcknowledgementTest extends JMSTestCase final int NUM_MESSAGES = 20; // Send some messages - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); producer.send(m); } @@ -524,16 +491,14 @@ public class AcknowledgementTest extends JMSTestCase int count = 0; Message m = null; - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { assertRemainingMessages(NUM_MESSAGES - i); m = consumer.receive(200); assertRemainingMessages(NUM_MESSAGES - (i + 1)); - if (m == null) - { + if (m == null) { break; } count++; @@ -561,8 +526,7 @@ public class AcknowledgementTest extends JMSTestCase } @Test - public void testDupsOKAcknowledgeQueue() throws Exception - { + public void testDupsOKAcknowledgeQueue() throws Exception { Connection conn = createConnection(); Session producerSess = conn.createSession(false, Session.DUPS_OK_ACKNOWLEDGE); @@ -577,8 +541,7 @@ public class AcknowledgementTest extends JMSTestCase final int NUM_MESSAGES = 20; // Send some messages - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); producer.send(m); } @@ -588,12 +551,10 @@ public class AcknowledgementTest extends JMSTestCase int count = 0; Message m = null; - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { m = consumer.receive(200); - if (m == null) - { + if (m == null) { break; } count++; @@ -623,14 +584,12 @@ public class AcknowledgementTest extends JMSTestCase } @Test - public void testDupsOKAcknowledgeTopic() throws Exception - { + public void testDupsOKAcknowledgeTopic() throws Exception { final int BATCH_SIZE = 10; deployConnectionFactory(null, "MyConnectionFactory2", -1, -1, -1, -1, false, false, BATCH_SIZE, true, "mycf"); Connection conn = null; - try - { + try { ConnectionFactory myCF = (ConnectionFactory) ic.lookup("/mycf"); @@ -644,8 +603,7 @@ public class AcknowledgementTest extends JMSTestCase conn.start(); // Send some messages - for (int i = 0; i < 19; i++) - { + for (int i = 0; i < 19; i++) { Message m = producerSess.createMessage(); producer.send(m); } @@ -653,8 +611,7 @@ public class AcknowledgementTest extends JMSTestCase log.trace("Sent messages"); Message m = null; - for (int i = 0; i < 19; i++) - { + for (int i = 0; i < 19; i++) { m = consumer.receive(200); ProxyAssertSupport.assertNotNull(m); @@ -662,11 +619,9 @@ public class AcknowledgementTest extends JMSTestCase consumerSess.close(); } - finally - { + finally { - if (conn != null) - { + if (conn != null) { conn.close(); } @@ -679,8 +634,7 @@ public class AcknowledgementTest extends JMSTestCase * Send some messages, consume them and verify the messages are not sent upon recovery */ @Test - public void testLazyAcknowledge() throws Exception - { + public void testLazyAcknowledge() throws Exception { Connection conn = createConnection(); Session producerSess = conn.createSession(false, Session.DUPS_OK_ACKNOWLEDGE); @@ -693,8 +647,7 @@ public class AcknowledgementTest extends JMSTestCase final int NUM_MESSAGES = 20; // Send some messages - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); producer.send(m); } @@ -706,11 +659,9 @@ public class AcknowledgementTest extends JMSTestCase int count = 0; Message m = null; - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { m = consumer.receive(200); - if (m == null) - { + if (m == null) { break; } count++; @@ -740,8 +691,7 @@ public class AcknowledgementTest extends JMSTestCase } @Test - public void testMessageListenerAutoAck() throws Exception - { + public void testMessageListenerAutoAck() throws Exception { Connection conn = createConnection(); Session sessSend = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = sessSend.createProducer(queue1); @@ -794,8 +744,7 @@ public class AcknowledgementTest extends JMSTestCase * case using MessageListeners */ @Test - public void testRecoverAutoACK() throws Exception - { + public void testRecoverAutoACK() throws Exception { Connection conn = createConnection(); Session s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer p = s.createProducer(queue1); @@ -840,8 +789,7 @@ public class AcknowledgementTest extends JMSTestCase } @Test - public void testMessageListenerDupsOK() throws Exception - { + public void testMessageListenerDupsOK() throws Exception { Connection conn = createConnection(); Session sessSend = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = sessSend.createProducer(queue1); @@ -889,8 +837,7 @@ public class AcknowledgementTest extends JMSTestCase } @Test - public void testMessageListenerClientAck() throws Exception - { + public void testMessageListenerClientAck() throws Exception { Connection conn = createConnection(); Session sessSend = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = sessSend.createProducer(queue1); @@ -923,8 +870,7 @@ public class AcknowledgementTest extends JMSTestCase } @Test - public void testMessageListenerTransactionalAck() throws Exception - { + public void testMessageListenerTransactionalAck() throws Exception { Connection conn = createConnection(); Session sessSend = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = sessSend.createProducer(queue1); @@ -963,8 +909,8 @@ public class AcknowledgementTest extends JMSTestCase // Inner classes ------------------------------------------------- - private abstract class LatchListener implements MessageListener - { + private abstract class LatchListener implements MessageListener { + protected CountDownLatch latch = new CountDownLatch(1); protected Session sess; @@ -973,13 +919,11 @@ public class AcknowledgementTest extends JMSTestCase boolean failed; - LatchListener(final Session sess) - { + LatchListener(final Session sess) { this.sess = sess; } - public void waitForMessages() throws InterruptedException - { + public void waitForMessages() throws InterruptedException { ProxyAssertSupport.assertTrue("failed to receive all messages", latch.await(2000, MILLISECONDS)); } @@ -987,62 +931,50 @@ public class AcknowledgementTest extends JMSTestCase } - private class MessageListenerAutoAck extends LatchListener - { + private class MessageListenerAutoAck extends LatchListener { - MessageListenerAutoAck(final Session sess) - { + MessageListenerAutoAck(final Session sess) { super(sess); } @Override - public void onMessage(final Message m) - { - try - { + public void onMessage(final Message m) { + try { count++; TextMessage tm = (TextMessage) m; // Receive first three messages then recover() session // Only last message should be redelivered - if (count == 1) - { + if (count == 1) { assertRemainingMessages(3); - if (!"a".equals(tm.getText())) - { + if (!"a".equals(tm.getText())) { failed = true; latch.countDown(); } } - if (count == 2) - { + if (count == 2) { assertRemainingMessages(2); - if (!"b".equals(tm.getText())) - { + if (!"b".equals(tm.getText())) { failed = true; latch.countDown(); } } - if (count == 3) - { + if (count == 3) { assertRemainingMessages(1); - if (!"c".equals(tm.getText())) - { + if (!"c".equals(tm.getText())) { failed = true; latch.countDown(); } sess.recover(); } - if (count == 4) - { + if (count == 4) { assertRemainingMessages(1); - if (!"c".equals(tm.getText())) - { + if (!"c".equals(tm.getText())) { failed = true; latch.countDown(); } @@ -1050,8 +982,7 @@ public class AcknowledgementTest extends JMSTestCase } } - catch (Exception e) - { + catch (Exception e) { failed = true; latch.countDown(); } @@ -1059,63 +990,51 @@ public class AcknowledgementTest extends JMSTestCase } - private class MessageListenerDupsOK extends LatchListener - { + private class MessageListenerDupsOK extends LatchListener { - MessageListenerDupsOK(final Session sess) - { + MessageListenerDupsOK(final Session sess) { super(sess); } @Override - public void onMessage(final Message m) - { - try - { + public void onMessage(final Message m) { + try { count++; TextMessage tm = (TextMessage) m; // Receive first three messages then recover() session // Only last message should be redelivered - if (count == 1) - { + if (count == 1) { assertRemainingMessages(3); - if (!"a".equals(tm.getText())) - { + if (!"a".equals(tm.getText())) { failed = true; latch.countDown(); } } - if (count == 2) - { + if (count == 2) { assertRemainingMessages(3); - if (!"b".equals(tm.getText())) - { + if (!"b".equals(tm.getText())) { failed = true; latch.countDown(); } } - if (count == 3) - { + if (count == 3) { assertRemainingMessages(3); - if (!"c".equals(tm.getText())) - { + if (!"c".equals(tm.getText())) { failed = true; latch.countDown(); } sess.recover(); } - if (count == 4) - { + if (count == 4) { // Recover forces an ack, so there will be only one left assertRemainingMessages(1); - if (!"c".equals(tm.getText())) - { + if (!"c".equals(tm.getText())) { failed = true; latch.countDown(); } @@ -1123,8 +1042,7 @@ public class AcknowledgementTest extends JMSTestCase } } - catch (Exception e) - { + catch (Exception e) { failed = true; latch.countDown(); } @@ -1132,47 +1050,38 @@ public class AcknowledgementTest extends JMSTestCase } - private class MessageListenerClientAck extends LatchListener - { - MessageListenerClientAck(final Session sess) - { + private class MessageListenerClientAck extends LatchListener { + + MessageListenerClientAck(final Session sess) { super(sess); } @Override - public void onMessage(final Message m) - { - try - { + public void onMessage(final Message m) { + try { count++; TextMessage tm = (TextMessage) m; - if (count == 1) - { + if (count == 1) { assertRemainingMessages(3); - if (!"a".equals(tm.getText())) - { + if (!"a".equals(tm.getText())) { log.trace("Expected a but got " + tm.getText()); failed = true; latch.countDown(); } } - if (count == 2) - { + if (count == 2) { assertRemainingMessages(3); - if (!"b".equals(tm.getText())) - { + if (!"b".equals(tm.getText())) { log.trace("Expected b but got " + tm.getText()); failed = true; latch.countDown(); } } - if (count == 3) - { + if (count == 3) { assertRemainingMessages(3); - if (!"c".equals(tm.getText())) - { + if (!"c".equals(tm.getText())) { log.trace("Expected c but got " + tm.getText()); failed = true; latch.countDown(); @@ -1180,11 +1089,9 @@ public class AcknowledgementTest extends JMSTestCase log.trace("calling recover"); sess.recover(); } - if (count == 4) - { + if (count == 4) { assertRemainingMessages(3); - if (!"a".equals(tm.getText())) - { + if (!"a".equals(tm.getText())) { log.trace("Expected a but got " + tm.getText()); failed = true; latch.countDown(); @@ -1195,11 +1102,9 @@ public class AcknowledgementTest extends JMSTestCase log.trace("calling recover"); sess.recover(); } - if (count == 5) - { + if (count == 5) { assertRemainingMessages(2); - if (!"b".equals(tm.getText())) - { + if (!"b".equals(tm.getText())) { log.trace("Expected b but got " + tm.getText()); failed = true; latch.countDown(); @@ -1207,21 +1112,17 @@ public class AcknowledgementTest extends JMSTestCase log.trace("calling recover"); sess.recover(); } - if (count == 6) - { + if (count == 6) { assertRemainingMessages(2); - if (!"b".equals(tm.getText())) - { + if (!"b".equals(tm.getText())) { log.trace("Expected b but got " + tm.getText()); failed = true; latch.countDown(); } } - if (count == 7) - { + if (count == 7) { assertRemainingMessages(2); - if (!"c".equals(tm.getText())) - { + if (!"c".equals(tm.getText())) { log.trace("Expected c but got " + tm.getText()); failed = true; latch.countDown(); @@ -1232,8 +1133,7 @@ public class AcknowledgementTest extends JMSTestCase } } - catch (Exception e) - { + catch (Exception e) { log.error("Caught exception", e); failed = true; latch.countDown(); @@ -1242,66 +1142,52 @@ public class AcknowledgementTest extends JMSTestCase } - private class MessageListenerTransactionalAck extends LatchListener - { + private class MessageListenerTransactionalAck extends LatchListener { - MessageListenerTransactionalAck(final Session sess) - { + MessageListenerTransactionalAck(final Session sess) { super(sess); } @Override - public void onMessage(final Message m) - { - try - { + public void onMessage(final Message m) { + try { count++; TextMessage tm = (TextMessage) m; - if (count == 1) - { + if (count == 1) { assertRemainingMessages(3); - if (!"a".equals(tm.getText())) - { + if (!"a".equals(tm.getText())) { failed = true; latch.countDown(); } } - if (count == 2) - { + if (count == 2) { assertRemainingMessages(3); - if (!"b".equals(tm.getText())) - { + if (!"b".equals(tm.getText())) { failed = true; latch.countDown(); } } - if (count == 3) - { + if (count == 3) { assertRemainingMessages(3); - if (!"c".equals(tm.getText())) - { + if (!"c".equals(tm.getText())) { failed = true; latch.countDown(); } log.trace("Rollback"); sess.rollback(); } - if (count == 4) - { + if (count == 4) { assertRemainingMessages(3); - if (!"a".equals(tm.getText())) - { + if (!"a".equals(tm.getText())) { failed = true; latch.countDown(); } } - if (count == 5) - { + if (count == 5) { assertRemainingMessages(3); - if (!"b".equals(tm.getText())) - { + if (!"b".equals(tm.getText())) { failed = true; latch.countDown(); } @@ -1309,22 +1195,18 @@ public class AcknowledgementTest extends JMSTestCase sess.commit(); assertRemainingMessages(1); } - if (count == 6) - { + if (count == 6) { assertRemainingMessages(1); - if (!"c".equals(tm.getText())) - { + if (!"c".equals(tm.getText())) { failed = true; latch.countDown(); } log.trace("recover"); sess.rollback(); } - if (count == 7) - { + if (count == 7) { assertRemainingMessages(1); - if (!"c".equals(tm.getText())) - { + if (!"c".equals(tm.getText())) { failed = true; latch.countDown(); } @@ -1334,8 +1216,7 @@ public class AcknowledgementTest extends JMSTestCase latch.countDown(); } } - catch (Exception e) - { + catch (Exception e) { // log.error(e); failed = true; latch.countDown(); @@ -1345,8 +1226,7 @@ public class AcknowledgementTest extends JMSTestCase } @Test - public void testTransactionalIgnoreACK() throws Exception - { + public void testTransactionalIgnoreACK() throws Exception { Connection conn = createConnection(); Session producerSess = conn.createSession(true, Session.SESSION_TRANSACTED); @@ -1359,8 +1239,7 @@ public class AcknowledgementTest extends JMSTestCase final int NUM_MESSAGES = 20; // Send some messages - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); m.acknowledge(); // This is invalid but should be ignored accordingly to the javadoc producer.send(m); @@ -1371,8 +1250,7 @@ public class AcknowledgementTest extends JMSTestCase producerSess.rollback(); // Send some messages - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); m.acknowledge(); // / should be ignored producer.send(m); @@ -1384,11 +1262,9 @@ public class AcknowledgementTest extends JMSTestCase assertRemainingMessages(NUM_MESSAGES); int count = 0; - while (true) - { + while (true) { Message m = consumer.receive(200); - if (m == null) - { + if (m == null) { break; } m.acknowledge(); @@ -1404,8 +1280,7 @@ public class AcknowledgementTest extends JMSTestCase assertRemainingMessages(NUM_MESSAGES); int i = 0; - for (; i < NUM_MESSAGES; i++) - { + for (; i < NUM_MESSAGES; i++) { consumer.receive(); } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/ActiveMQServerTestCase.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/ActiveMQServerTestCase.java index cc6a2ddb6c..0b53ca9d7c 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/ActiveMQServerTestCase.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/ActiveMQServerTestCase.java @@ -59,8 +59,8 @@ import org.junit.runner.Description; * org.apache.activemq.tests.integration.jms at the integration-tests project. */ @Deprecated -public abstract class ActiveMQServerTestCase -{ +public abstract class ActiveMQServerTestCase { + public static final int MAX_TIMEOUT = 1000 * 10 /* seconds */; public static final int MIN_TIMEOUT = 1000 * 1 /* seconds */; @@ -71,19 +71,15 @@ public abstract class ActiveMQServerTestCase /** * Some testcases are time sensitive, and we need to make sure a GC would happen before certain scenarios */ - public static void forceGC() - { + public static void forceGC() { WeakReference dumbReference = new WeakReference(new Object()); // A loop that will wait GC, using the minimal time as possible - while (dumbReference.get() != null) - { + while (dumbReference.get() != null) { System.gc(); - try - { + try { Thread.sleep(500); } - catch (InterruptedException e) - { + catch (InterruptedException e) { } } } @@ -103,47 +99,39 @@ public abstract class ActiveMQServerTestCase private final Set contextSet = new HashSet(); @Rule - public TestRule watcher = new TestWatcher() - { + public TestRule watcher = new TestWatcher() { @Override - protected void starting(Description description) - { + protected void starting(Description description) { log.info(String.format("#*#*# Starting test: %s()...", description.getMethodName())); } @Override - protected void finished(Description description) - { + protected void finished(Description description) { log.info(String.format("#*#*# Finished test: %s()...", description.getMethodName())); } @Override - protected void failed(Throwable e, Description description) - { + protected void failed(Throwable e, Description description) { ActiveMQServerTestCase.tearDownAllServers(); } }; @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { System.setProperty("java.naming.factory.initial", getContextFactory()); - try - { + try { // create any new server we need ActiveMQServerTestCase.servers.add(ServerManagement.create()); // start the servers if needed - if (!ActiveMQServerTestCase.servers.get(0).isStarted()) - { + if (!ActiveMQServerTestCase.servers.get(0).isStarted()) { ActiveMQServerTestCase.servers.get(0).start(getConfiguration(), true); } // deploy the objects for this test deployAdministeredObjects(); lookUp(); } - catch (Exception e) - { + catch (Exception e) { // if we get here we need to clean up for the next test e.printStackTrace(); ActiveMQServerTestCase.servers.get(0).stop(); @@ -163,61 +151,50 @@ public abstract class ActiveMQServerTestCase } @After - public void tearDown() throws Exception - { - for (JMSContext context : contextSet) - { + public void tearDown() throws Exception { + for (JMSContext context : contextSet) { context.close(); } contextSet.clear(); - for (Connection localConn : connectionsSet) - { + for (Connection localConn : connectionsSet) { localConn.close(); } connectionsSet.clear(); } - public void stop() throws Exception - { + public void stop() throws Exception { ActiveMQServerTestCase.servers.get(0).stop(); } - public String getContextFactory() - { + public String getContextFactory() { return org.apache.activemq.artemis.jms.tests.tools.container.InVMInitialContextFactory.class.getCanonicalName(); } - public void start() throws Exception - { + public void start() throws Exception { System.setProperty("java.naming.factory.initial", getContextFactory()); ActiveMQServerTestCase.servers.get(0).start(getConfiguration(), false); } - public void startNoDelete() throws Exception - { + public void startNoDelete() throws Exception { System.setProperty("java.naming.factory.initial", getContextFactory()); ActiveMQServerTestCase.servers.get(0).start(getConfiguration(), false); } - public void stopServerPeer() throws Exception - { + public void stopServerPeer() throws Exception { ActiveMQServerTestCase.servers.get(0).stopServerPeer(); } - public void startServerPeer() throws Exception - { + public void startServerPeer() throws Exception { System.setProperty("java.naming.factory.initial", getContextFactory()); ActiveMQServerTestCase.servers.get(0).startServerPeer(); } - protected HashMap getConfiguration() - { + protected HashMap getConfiguration() { return new HashMap(); } - protected void deployAndLookupAdministeredObjects() throws Exception - { + protected void deployAndLookupAdministeredObjects() throws Exception { createTopic("Topic1"); createTopic("Topic2"); createTopic("Topic3"); @@ -229,8 +206,7 @@ public abstract class ActiveMQServerTestCase lookUp(); } - protected void deployAdministeredObjects() throws Exception - { + protected void deployAdministeredObjects() throws Exception { createTopic("Topic1"); createTopic("Topic2"); createTopic("Topic3"); @@ -243,8 +219,7 @@ public abstract class ActiveMQServerTestCase deployConnectionFactory(0, JMSFactoryType.XA_CF, "CF_XA_TRUE", "/CF_XA_TRUE"); } - private void lookUp() throws Exception - { + private void lookUp() throws Exception { InitialContext ic = getInitialContext(); ActiveMQServerTestCase.topic1 = (Topic) ic.lookup("/topic/Topic1"); ActiveMQServerTestCase.topic2 = (Topic) ic.lookup("/topic/Topic2"); @@ -255,8 +230,7 @@ public abstract class ActiveMQServerTestCase queue4 = (Queue) ic.lookup("/queue/Queue4"); } - protected void undeployAdministeredObjects() throws Exception - { + protected void undeployAdministeredObjects() throws Exception { removeAllMessages("Topic1", false); removeAllMessages("Topic2", false); removeAllMessages("Topic3", false); @@ -279,159 +253,127 @@ public abstract class ActiveMQServerTestCase } @AfterClass - public static final void tearDownAllServers() - { - for (Server s : servers) - { - try - { + public static final void tearDownAllServers() { + for (Server s : servers) { + try { s.stop(); } - catch (Exception cause) - { + catch (Exception cause) { // ignore } } servers.clear(); } - protected ActiveMQServer getJmsServer() throws Exception - { + protected ActiveMQServer getJmsServer() throws Exception { return ActiveMQServerTestCase.servers.get(0).getActiveMQServer(); } - protected JMSServerManager getJmsServerManager() throws Exception - { + protected JMSServerManager getJmsServerManager() throws Exception { return ActiveMQServerTestCase.servers.get(0).getJMSServerManager(); } - protected void checkNoSubscriptions(final Topic topic) throws Exception - { + protected void checkNoSubscriptions(final Topic topic) throws Exception { } - protected void drainDestination(final ConnectionFactory cf, final Destination dest) throws JMSException - { + protected void drainDestination(final ConnectionFactory cf, final Destination dest) throws JMSException { Connection conn = null; - try - { + try { conn = cf.createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer cons = sess.createConsumer(dest); Message m = null; conn.start(); log.trace("Draining messages from " + dest); - while (true) - { + while (true) { m = cons.receive(DRAIN_WAIT_TIME); - if (m == null) - { + if (m == null) { break; } log.trace("Drained message"); } } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } - public InitialContext getInitialContext() throws Exception - { + public InitialContext getInitialContext() throws Exception { return new InitialContext(ServerManagement.getJNDIEnvironment(0)); } - public ConnectionFactory getConnectionFactory() throws Exception - { + public ConnectionFactory getConnectionFactory() throws Exception { return (ConnectionFactory) getInitialContext().lookup("/ConnectionFactory"); } - public TopicConnectionFactory getTopicConnectionFactory() throws Exception - { + public TopicConnectionFactory getTopicConnectionFactory() throws Exception { return (TopicConnectionFactory) getInitialContext().lookup("/CF_TOPIC"); } - public XAConnectionFactory getXAConnectionFactory() throws Exception - { + public XAConnectionFactory getXAConnectionFactory() throws Exception { return (XAConnectionFactory) getInitialContext().lookup("/CF_XA_TRUE"); } - public void createQueue(final String name) throws Exception - { + public void createQueue(final String name) throws Exception { ActiveMQServerTestCase.servers.get(0).createQueue(name, null); } - public void createTopic(final String name) throws Exception - { + public void createTopic(final String name) throws Exception { ActiveMQServerTestCase.servers.get(0).createTopic(name, null); } - public void destroyQueue(final String name) throws Exception - { + public void destroyQueue(final String name) throws Exception { ActiveMQServerTestCase.servers.get(0).destroyQueue(name, null); } - public void destroyTopic(final String name) throws Exception - { + public void destroyTopic(final String name) throws Exception { ActiveMQServerTestCase.servers.get(0).destroyTopic(name, null); } - public void createQueue(final String name, final int i) throws Exception - { + public void createQueue(final String name, final int i) throws Exception { ActiveMQServerTestCase.servers.get(i).createQueue(name, null); } - public void createTopic(final String name, final int i) throws Exception - { + public void createTopic(final String name, final int i) throws Exception { ActiveMQServerTestCase.servers.get(i).createTopic(name, null); } - public void destroyQueue(final String name, final int i) throws Exception - { + public void destroyQueue(final String name, final int i) throws Exception { ActiveMQServerTestCase.servers.get(i).destroyQueue(name, null); } - public boolean checkNoMessageData() - { + public boolean checkNoMessageData() { return false; } - public boolean checkEmpty(final Queue queue) throws Exception - { + public boolean checkEmpty(final Queue queue) throws Exception { Long messageCount = ActiveMQServerTestCase.servers.get(0).getMessageCountForQueue(queue.getQueueName()); - if (messageCount > 0) - { + if (messageCount > 0) { removeAllMessages(queue.getQueueName(), true); } return true; } - public boolean checkEmpty(final Queue queue, final int i) - { + public boolean checkEmpty(final Queue queue, final int i) { return true; } - public boolean checkEmpty(final Topic topic) - { + public boolean checkEmpty(final Topic topic) { return true; } - protected void removeAllMessages(final String destName, final boolean isQueue) throws Exception - { + protected void removeAllMessages(final String destName, final boolean isQueue) throws Exception { ActiveMQServerTestCase.servers.get(0).removeAllMessages(destName, isQueue); } - protected boolean assertRemainingMessages(final int expected) throws Exception - { + protected boolean assertRemainingMessages(final int expected) throws Exception { String queueName = "Queue1"; Binding binding = servers.get(0).getActiveMQServer().getPostOffice().getBinding(SimpleString.toSimpleString("jms.queue." + queueName)); - if (binding != null && binding instanceof LocalQueueBinding) - { - ((LocalQueueBinding)binding).getQueue().flushExecutor(); + if (binding != null && binding instanceof LocalQueueBinding) { + ((LocalQueueBinding) binding).getQueue().flushExecutor(); } Long messageCount = ActiveMQServerTestCase.servers.get(0).getMessageCountForQueue(queueName); @@ -439,44 +381,39 @@ public abstract class ActiveMQServerTestCase return expected == messageCount.intValue(); } - protected static void assertActiveConnectionsOnTheServer(final int expectedSize) throws Exception - { - ProxyAssertSupport.assertEquals(expectedSize, ActiveMQServerTestCase.servers.get(0) - .getActiveMQServer() - .getActiveMQServerControl() - .getConnectionCount()); + protected static void assertActiveConnectionsOnTheServer(final int expectedSize) throws Exception { + ProxyAssertSupport.assertEquals(expectedSize, ActiveMQServerTestCase.servers.get(0).getActiveMQServer().getActiveMQServerControl().getConnectionCount()); } public static void deployConnectionFactory(final String clientId, final String objectName, - final String... jndiBindings) throws Exception - { + final String... jndiBindings) throws Exception { ActiveMQServerTestCase.servers.get(0).deployConnectionFactory(clientId, objectName, jndiBindings); } public static void deployConnectionFactory(final String objectName, final int prefetchSize, - final String... jndiBindings) throws Exception - { + final String... jndiBindings) throws Exception { ActiveMQServerTestCase.servers.get(0).deployConnectionFactory(objectName, prefetchSize, jndiBindings); } - public static void deployConnectionFactory(final int server, final String objectName, final int prefetchSize, - final String... jndiBindings) throws Exception - { + final String... jndiBindings) throws Exception { ActiveMQServerTestCase.servers.get(server).deployConnectionFactory(objectName, prefetchSize, jndiBindings); } - public static void deployConnectionFactory(final int server, final String objectName, final String... jndiBindings) throws Exception - { + public static void deployConnectionFactory(final int server, + final String objectName, + final String... jndiBindings) throws Exception { ActiveMQServerTestCase.servers.get(server).deployConnectionFactory(objectName, jndiBindings); } - public static void deployConnectionFactory(final int server, JMSFactoryType type, final String objectName, final String... jndiBindings) throws Exception - { + public static void deployConnectionFactory(final int server, + JMSFactoryType type, + final String objectName, + final String... jndiBindings) throws Exception { ActiveMQServerTestCase.servers.get(server).deployConnectionFactory(objectName, type, jndiBindings); } @@ -490,20 +427,8 @@ public abstract class ActiveMQServerTestCase final boolean supportsLoadBalancing, final int dupsOkBatchSize, final boolean blockOnAcknowledge, - final String... jndiBindings) throws Exception - { - ActiveMQServerTestCase.servers.get(0).deployConnectionFactory(clientId, - JMSFactoryType.CF, - objectName, - prefetchSize, - defaultTempQueueFullSize, - defaultTempQueuePageSize, - defaultTempQueueDownCacheSize, - supportsFailover, - supportsLoadBalancing, - dupsOkBatchSize, - blockOnAcknowledge, - jndiBindings); + final String... jndiBindings) throws Exception { + ActiveMQServerTestCase.servers.get(0).deployConnectionFactory(clientId, JMSFactoryType.CF, objectName, prefetchSize, defaultTempQueueFullSize, defaultTempQueuePageSize, defaultTempQueueDownCacheSize, supportsFailover, supportsLoadBalancing, dupsOkBatchSize, blockOnAcknowledge, jndiBindings); } public static void deployConnectionFactory(final String objectName, @@ -511,54 +436,42 @@ public abstract class ActiveMQServerTestCase final int defaultTempQueueFullSize, final int defaultTempQueuePageSize, final int defaultTempQueueDownCacheSize, - final String... jndiBindings) throws Exception - { - ActiveMQServerTestCase.servers.get(0).deployConnectionFactory(objectName, - prefetchSize, - defaultTempQueueFullSize, - defaultTempQueuePageSize, - defaultTempQueueDownCacheSize, - jndiBindings); + final String... jndiBindings) throws Exception { + ActiveMQServerTestCase.servers.get(0).deployConnectionFactory(objectName, prefetchSize, defaultTempQueueFullSize, defaultTempQueuePageSize, defaultTempQueueDownCacheSize, jndiBindings); } - public static void undeployConnectionFactory(final String objectName) throws Exception - { + public static void undeployConnectionFactory(final String objectName) throws Exception { ActiveMQServerTestCase.servers.get(0).undeployConnectionFactory(objectName); } - protected List listAllSubscribersForTopic(final String s) throws Exception - { + protected List listAllSubscribersForTopic(final String s) throws Exception { return ActiveMQServerTestCase.servers.get(0).listAllSubscribersForTopic(s); } - protected Long getMessageCountForQueue(final String s) throws Exception - { + protected Long getMessageCountForQueue(final String s) throws Exception { return ActiveMQServerTestCase.servers.get(0).getMessageCountForQueue(s); } - protected Set getSecurityConfig() throws Exception - { + protected Set getSecurityConfig() throws Exception { return ActiveMQServerTestCase.servers.get(0).getSecurityConfig(); } - protected void setSecurityConfig(final Set defConfig) throws Exception - { + protected void setSecurityConfig(final Set defConfig) throws Exception { ActiveMQServerTestCase.servers.get(0).setSecurityConfig(defConfig); } - protected void setSecurityConfigOnManager(final String destination, final boolean isQueue, final Set roles) throws Exception - { + protected void setSecurityConfigOnManager(final String destination, + final boolean isQueue, + final Set roles) throws Exception { ActiveMQServerTestCase.servers.get(0).configureSecurityForDestination(destination, isQueue, roles); } - protected final JMSContext addContext(JMSContext createContext) - { + protected final JMSContext addContext(JMSContext createContext) { contextSet.add(createContext); return createContext; } - protected final Connection addConnection(Connection conn) - { + protected final Connection addConnection(Connection conn) { connectionsSet.add(conn); return conn; } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/AutoAckMesageListenerTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/AutoAckMesageListenerTest.java index 84feb63b49..1a2c30908d 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/AutoAckMesageListenerTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/AutoAckMesageListenerTest.java @@ -29,8 +29,7 @@ import javax.jms.Session; import org.junit.Test; -public class AutoAckMesageListenerTest extends JMSTestCase -{ +public class AutoAckMesageListenerTest extends JMSTestCase { // Constants ----------------------------------------------------- @@ -45,12 +44,10 @@ public class AutoAckMesageListenerTest extends JMSTestCase // Public -------------------------------------------------------- @Test - public void testAutoAckMsgListenerQueue() throws Exception - { + public void testAutoAckMsgListenerQueue() throws Exception { Connection conn = null; - try - { + try { CountDownLatch latch = new CountDownLatch(1); conn = createConnection(); @@ -75,15 +72,12 @@ public class AutoAckMesageListenerTest extends JMSTestCase latch.await(10, TimeUnit.SECONDS); // check message listener status - if (listener.getPassed() == false) - { + if (listener.getPassed() == false) { throw new Exception("failed"); } } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -97,51 +91,42 @@ public class AutoAckMesageListenerTest extends JMSTestCase // Inner classes ------------------------------------------------- - private static class AutoAckMsgListener implements MessageListener - { + private static class AutoAckMsgListener implements MessageListener { + private boolean passed; private final Session session; private final CountDownLatch monitor; - public AutoAckMsgListener(CountDownLatch latch, Session session) - { + public AutoAckMsgListener(CountDownLatch latch, Session session) { this.monitor = latch; this.session = session; } // get state of test - public boolean getPassed() - { + public boolean getPassed() { return passed; } // will receive two messages - public void onMessage(Message message) - { - try - { - if (message.getBooleanProperty("last") == false) - { + public void onMessage(Message message) { + try { + if (message.getBooleanProperty("last") == false) { log.info("Received first message."); - if (message.getJMSRedelivered() == true) - { + if (message.getJMSRedelivered() == true) { // should not re-receive this one log.info("Error: received first message twice"); passed = false; } } - else - { - if (message.getJMSRedelivered() == false) - { + else { + if (message.getJMSRedelivered() == false) { // received second message for first time log.info("Received second message. Calling recover()"); session.recover(); } - else - { + else { // should be redelivered after recover log.info("Received second message again as expected"); passed = true; @@ -149,8 +134,7 @@ public class AutoAckMesageListenerTest extends JMSTestCase } } } - catch (JMSException e) - { + catch (JMSException e) { log.warn("Exception caught in message listener:\n" + e); passed = false; monitor.countDown(); diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/BrowserTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/BrowserTest.java index 97f35841c2..85ec7fd8c0 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/BrowserTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/BrowserTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.jms.tests; + import java.util.Enumeration; import javax.jms.Connection; @@ -35,71 +36,60 @@ import org.junit.After; import org.junit.Assert; import org.junit.Test; -public class BrowserTest extends JMSTestCase -{ +public class BrowserTest extends JMSTestCase { + Connection conn; + @Test - public void testCreateBrowserOnNullDestination() throws Exception - { + public void testCreateBrowserOnNullDestination() throws Exception { conn = getConnectionFactory().createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - try - { + try { session.createBrowser(null); ProxyAssertSupport.fail("should throw exception"); } - catch (InvalidDestinationException e) - { + catch (InvalidDestinationException e) { // OK } } @Test - public void testCreateBrowserOnNonExistentQueue() throws Exception - { + public void testCreateBrowserOnNonExistentQueue() throws Exception { Connection pconn = getConnectionFactory().createConnection(); - try - { + try { Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); - try - { - ps.createBrowser(new Queue() - { - public String getQueueName() throws JMSException - { + try { + ps.createBrowser(new Queue() { + public String getQueueName() throws JMSException { return "NoSuchQueue"; } }); ProxyAssertSupport.fail("should throw exception"); } - catch (InvalidDestinationException e) - { + catch (InvalidDestinationException e) { // OK } } - finally - { - if (pconn != null) - { + finally { + if (pconn != null) { pconn.close(); } } } @Test - public void testBrowse2() throws Exception - { + public void testBrowse2() throws Exception { conn = getConnectionFactory().createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(queue1); - ActiveMQConnectionFactory cf1 = (ActiveMQConnectionFactory)getConnectionFactory(); + ActiveMQConnectionFactory cf1 = (ActiveMQConnectionFactory) getConnectionFactory(); ClientSession coreSession = cf1.getServerLocator().createSessionFactory().createSession(true, true); @@ -113,19 +103,15 @@ public class BrowserTest extends JMSTestCase m.setIntProperty("cnt", 0); producer.send(m); - Assert.assertNotNull(browser.receiveImmediate()); coreSession.close(); - - drainDestination(getConnectionFactory(), queue1); } @Test - public void testBrowse() throws Exception - { + public void testBrowse() throws Exception { conn = getConnectionFactory().createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -153,10 +139,8 @@ public class BrowserTest extends JMSTestCase } @Test - public void testBrowseWithSelector() throws Exception - { - try - { + public void testBrowseWithSelector() throws Exception { + try { conn = getConnectionFactory().createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -165,24 +149,20 @@ public class BrowserTest extends JMSTestCase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { Message m = session.createMessage(); m.setIntProperty("test_counter", i + 1); producer.send(m); } } - finally - { + finally { removeAllMessages(queue1.getQueueName(), true); } } @Test - public void testGetEnumeration() throws Exception - { - try - { + public void testGetEnumeration() throws Exception { + try { conn = getConnectionFactory().createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -202,7 +182,7 @@ public class BrowserTest extends JMSTestCase ProxyAssertSupport.assertTrue(en.hasMoreElements()); - TextMessage rm = (TextMessage)en.nextElement(); + TextMessage rm = (TextMessage) en.nextElement(); ProxyAssertSupport.assertNotNull(rm); ProxyAssertSupport.assertEquals("A", rm.getText()); @@ -215,32 +195,27 @@ public class BrowserTest extends JMSTestCase ProxyAssertSupport.assertTrue(en.hasMoreElements()); - rm = (TextMessage)en.nextElement(); + rm = (TextMessage) en.nextElement(); ProxyAssertSupport.assertNotNull(rm); ProxyAssertSupport.assertEquals("A", rm.getText()); ProxyAssertSupport.assertFalse(en.hasMoreElements()); } - finally - { + finally { removeAllMessages(queue1.getQueueName(), true); } } @Override @After - public void tearDown() throws Exception - { - try - { - if (conn != null) - { + public void tearDown() throws Exception { + try { + if (conn != null) { conn.close(); } } - finally - { + finally { super.tearDown(); } } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/CTSMiscellaneousTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/CTSMiscellaneousTest.java index 014fc038d9..0aefc07683 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/CTSMiscellaneousTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/CTSMiscellaneousTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.jms.tests; + import java.util.ArrayList; import java.util.List; @@ -33,8 +34,7 @@ import org.junit.Test; /** * Safeguards for previously detected TCK failures. */ -public class CTSMiscellaneousTest extends JMSTest -{ +public class CTSMiscellaneousTest extends JMSTest { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -47,55 +47,18 @@ public class CTSMiscellaneousTest extends JMSTest // Constructors -------------------------------------------------- @Override @Before - public void setUp() throws Exception - { - try - { + public void setUp() throws Exception { + try { super.setUp(); // Deploy a connection factory with load balancing but no failover on node0 List bindings = new ArrayList(); bindings.add("StrictTCKConnectionFactory"); - getJmsServerManager().createConnectionFactory("StrictTCKConnectionFactory", - false, - JMSFactoryType.CF, - NETTY_CONNECTOR, - null, - ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, - ActiveMQClient.DEFAULT_CONNECTION_TTL, - ActiveMQClient.DEFAULT_CALL_TIMEOUT, - ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, - ActiveMQClient.DEFAULT_CACHE_LARGE_MESSAGE_CLIENT, - ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES, - ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, - ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, - true, - true, - true, - ActiveMQClient.DEFAULT_AUTO_GROUP, - ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, - ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_RETRY_INTERVAL, - ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, - ActiveMQClient.DEFAULT_MAX_RETRY_INTERVAL, - ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS, - ActiveMQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION, - null, - "/StrictTCKConnectionFactory"); + getJmsServerManager().createConnectionFactory("StrictTCKConnectionFactory", false, JMSFactoryType.CF, NETTY_CONNECTOR, null, ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, ActiveMQClient.DEFAULT_CONNECTION_TTL, ActiveMQClient.DEFAULT_CALL_TIMEOUT, ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, ActiveMQClient.DEFAULT_CACHE_LARGE_MESSAGE_CLIENT, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES, ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, true, true, true, ActiveMQClient.DEFAULT_AUTO_GROUP, ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_RETRY_INTERVAL, ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, ActiveMQClient.DEFAULT_MAX_RETRY_INTERVAL, ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS, ActiveMQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION, null, "/StrictTCKConnectionFactory"); - CTSMiscellaneousTest.cf = (ActiveMQConnectionFactory)getInitialContext().lookup("/StrictTCKConnectionFactory"); + CTSMiscellaneousTest.cf = (ActiveMQConnectionFactory) getInitialContext().lookup("/StrictTCKConnectionFactory"); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } @@ -107,12 +70,10 @@ public class CTSMiscellaneousTest extends JMSTest * when running with strictTCK we send them synchronously */ @Test - public void testNonPersistentMessagesSentSynchronously() throws Exception - { + public void testNonPersistentMessagesSentSynchronously() throws Exception { Connection c = null; - try - { + try { c = CTSMiscellaneousTest.cf.createConnection(); Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -124,17 +85,14 @@ public class CTSMiscellaneousTest extends JMSTest assertRemainingMessages(0); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { p.send(s.createMessage()); } assertRemainingMessages(numMessages); } - finally - { - if (c != null) - { + finally { + if (c != null) { c.close(); } @@ -144,8 +102,7 @@ public class CTSMiscellaneousTest extends JMSTest @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { super.tearDown(); ActiveMQServerTestCase.undeployConnectionFactory(CTSMiscellaneousTest.ORG_JBOSS_MESSAGING_SERVICE_LBCONNECTION_FACTORY); } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/ConnectionClosedTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/ConnectionClosedTest.java index 7f866a36fb..48117d1292 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/ConnectionClosedTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/ConnectionClosedTest.java @@ -34,8 +34,7 @@ import org.junit.Test; /** * All tests related to closing a Connection. */ -public class ConnectionClosedTest extends JMSTestCase -{ +public class ConnectionClosedTest extends JMSTestCase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -49,26 +48,25 @@ public class ConnectionClosedTest extends JMSTestCase // Public -------------------------------------------------------- @Test - public void testCloseOnce() throws Exception - { + public void testCloseOnce() throws Exception { Connection conn = createConnection(); conn.close(); } @Test - public void testCloseTwice() throws Exception - { + public void testCloseTwice() throws Exception { Connection conn = createConnection(); conn.close(); conn.close(); } - /** See TCK test: topicconntests.connNotStartedTopicTest */ + /** + * See TCK test: topicconntests.connNotStartedTopicTest + */ @Test - public void testCannotReceiveMessageOnStoppedConnection() throws Exception - { - TopicConnection conn1 = ((TopicConnectionFactory)topicCf).createTopicConnection(); - TopicConnection conn2 = ((TopicConnectionFactory)topicCf).createTopicConnection(); + public void testCannotReceiveMessageOnStoppedConnection() throws Exception { + TopicConnection conn1 = ((TopicConnectionFactory) topicCf).createTopicConnection(); + TopicConnection conn2 = ((TopicConnectionFactory) topicCf).createTopicConnection(); TopicSession sess1 = conn1.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); TopicSession sess2 = conn2.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); @@ -86,15 +84,13 @@ public class ConnectionClosedTest extends JMSTestCase final int NUM_MESSAGES = 10; - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = sess3.createTextMessage("hello"); prod.send(tm); } - for (int i = 0; i < NUM_MESSAGES; i++) - { - TextMessage tm = (TextMessage)sub1.receive(500); + for (int i = 0; i < NUM_MESSAGES; i++) { + TextMessage tm = (TextMessage) sub1.receive(500); ProxyAssertSupport.assertNotNull(tm); ProxyAssertSupport.assertEquals("hello", tm.getText()); } @@ -105,9 +101,8 @@ public class ConnectionClosedTest extends JMSTestCase conn2.start(); - for (int i = 0; i < NUM_MESSAGES; i++) - { - TextMessage tm = (TextMessage)sub2.receive(500); + for (int i = 0; i < NUM_MESSAGES; i++) { + TextMessage tm = (TextMessage) sub2.receive(500); ProxyAssertSupport.assertNotNull(tm); ProxyAssertSupport.assertEquals("hello", tm.getText()); } @@ -128,8 +123,7 @@ public class ConnectionClosedTest extends JMSTestCase * available at the time of the close. */ @Test - public void testCloseWhileReceiving() throws Exception - { + public void testCloseWhileReceiving() throws Exception { Connection conn = createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -138,31 +132,25 @@ public class ConnectionClosedTest extends JMSTestCase final MessageConsumer consumer = session.createConsumer(ActiveMQServerTestCase.topic1); - class TestRunnable implements Runnable - { + class TestRunnable implements Runnable { + public String failed; - public void run() - { - try - { + public void run() { + try { long start = System.currentTimeMillis(); Message m = consumer.receive(2100); - if (System.currentTimeMillis() - start >= 2000) - { + if (System.currentTimeMillis() - start >= 2000) { // It timed out failed = "Timed out"; } - else - { - if (m != null) - { + else { + if (m != null) { failed = "Message Not null"; } } } - catch (Exception e) - { + catch (Exception e) { log.error(e); failed = e.getMessage(); } @@ -179,44 +167,37 @@ public class ConnectionClosedTest extends JMSTestCase t.join(); - if (runnable.failed != null) - { + if (runnable.failed != null) { ProxyAssertSupport.fail(runnable.failed); } } @Test - public void testGetMetadataOnClosedConnection() throws Exception - { + public void testGetMetadataOnClosedConnection() throws Exception { Connection connection = createConnection(); connection.close(); - try - { + try { connection.getMetaData(); ProxyAssertSupport.fail("should throw exception"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } } @Test - public void testCreateSessionOnClosedConnection() throws Exception - { + public void testCreateSessionOnClosedConnection() throws Exception { Connection conn = createConnection(); conn.close(); - try - { + try { conn.createSession(false, Session.AUTO_ACKNOWLEDGE); ProxyAssertSupport.fail("Did not throw javax.jms.IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } } @@ -225,8 +206,7 @@ public class ConnectionClosedTest extends JMSTestCase * Test that close() hierarchically closes all child objects */ @Test - public void testCloseHierarchy() throws Exception - { + public void testCloseHierarchy() throws Exception { Connection conn = createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = sess.createConsumer(ActiveMQServerTestCase.topic1); @@ -241,62 +221,50 @@ public class ConnectionClosedTest extends JMSTestCase /* If the session is closed then any method invocation apart from close() * will throw an IllegalStateException */ - try - { + try { sess.createMessage(); ProxyAssertSupport.fail("Session is not closed"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { } - try - { + try { sess.getAcknowledgeMode(); ProxyAssertSupport.fail("should throw IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } - try - { + try { sess.getTransacted(); ProxyAssertSupport.fail("should throw IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } - try - { + try { sess.getMessageListener(); ProxyAssertSupport.fail("should throw IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } - try - { + try { sess.createProducer(queue1); ProxyAssertSupport.fail("should throw IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } - try - { + try { sess.createConsumer(queue1); ProxyAssertSupport.fail("should throw IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } @@ -305,84 +273,68 @@ public class ConnectionClosedTest extends JMSTestCase /* If the producer is closed then any method invocation apart from close() * will throw an IllegalStateException */ - try - { + try { producer.send(m); ProxyAssertSupport.fail("Producer is not closed"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { } - try - { + try { producer.getDisableMessageID(); ProxyAssertSupport.fail("should throw IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } - try - { + try { producer.getPriority(); ProxyAssertSupport.fail("should throw IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } - try - { + try { producer.getDestination(); ProxyAssertSupport.fail("should throw IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } - try - { + try { producer.getTimeToLive(); ProxyAssertSupport.fail("should throw IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } // ClientConsumer - try - { + try { consumer.getMessageSelector(); ProxyAssertSupport.fail("should throw exception"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } - try - { + try { consumer.getMessageListener(); ProxyAssertSupport.fail("should throw exception"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } - try - { + try { consumer.receive(); ProxyAssertSupport.fail("should throw exception"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/ConnectionFactoryTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/ConnectionFactoryTest.java index 24c04bfb7d..b656f932c0 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/ConnectionFactoryTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/ConnectionFactoryTest.java @@ -45,15 +45,14 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class ConnectionFactoryTest extends JMSTestCase -{ +public class ConnectionFactoryTest extends JMSTestCase { + private final Random random = new Random(); private String testClientId; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); testClientId = "amq" + random.nextInt(); } @@ -63,10 +62,9 @@ public class ConnectionFactoryTest extends JMSTestCase * created. */ @Test - public void testQueueConnectionFactory() throws Exception - { + public void testQueueConnectionFactory() throws Exception { deployConnectionFactory(0, JMSFactoryType.QUEUE_CF, "CF_QUEUE_XA_FALSE", "/CF_QUEUE_XA_FALSE"); - QueueConnectionFactory qcf = (QueueConnectionFactory)ic.lookup("/CF_QUEUE_XA_FALSE"); + QueueConnectionFactory qcf = (QueueConnectionFactory) ic.lookup("/CF_QUEUE_XA_FALSE"); QueueConnection qc = qcf.createQueueConnection(); qc.close(); undeployConnectionFactory("CF_QUEUE_XA_FALSE"); @@ -77,34 +75,30 @@ public class ConnectionFactoryTest extends JMSTestCase * created. */ @Test - public void testTopicConnectionFactory() throws Exception - { + public void testTopicConnectionFactory() throws Exception { deployConnectionFactory(0, JMSFactoryType.TOPIC_CF, "CF_TOPIC_XA_FALSE", "/CF_TOPIC_XA_FALSE"); - TopicConnectionFactory qcf = (TopicConnectionFactory)ic.lookup("/CF_TOPIC_XA_FALSE"); + TopicConnectionFactory qcf = (TopicConnectionFactory) ic.lookup("/CF_TOPIC_XA_FALSE"); TopicConnection tc = qcf.createTopicConnection(); tc.close(); undeployConnectionFactory("CF_TOPIC_XA_FALSE"); } @Test - public void testAdministrativelyConfiguredClientID() throws Exception - { + public void testAdministrativelyConfiguredClientID() throws Exception { // deploy a connection factory that has an administatively configured clientID ActiveMQServerTestCase.deployConnectionFactory(testClientId, "TestConnectionFactory", "TestConnectionFactory"); - ConnectionFactory cf = (ConnectionFactory)ic.lookup("/TestConnectionFactory"); + ConnectionFactory cf = (ConnectionFactory) ic.lookup("/TestConnectionFactory"); Connection c = cf.createConnection(); ProxyAssertSupport.assertEquals(testClientId, c.getClientID()); - try - { + try { c.setClientID("somethingelse"); ProxyAssertSupport.fail("should throw exception"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } c.close(); @@ -112,13 +106,12 @@ public class ConnectionFactoryTest extends JMSTestCase } @Test - public void testNoClientIDConfigured_1() throws Exception - { + public void testNoClientIDConfigured_1() throws Exception { // the ConnectionFactories that ship with ActiveMQ Artemis do not have their clientID // administratively configured. deployConnectionFactory(0, JMSFactoryType.TOPIC_CF, "CF_XA_FALSE", "/CF_XA_FALSE"); - ConnectionFactory cf = (ConnectionFactory)ic.lookup("/CF_XA_FALSE"); + ConnectionFactory cf = (ConnectionFactory) ic.lookup("/CF_XA_FALSE"); Connection c = cf.createConnection(); ProxyAssertSupport.assertNull(c.getClientID()); @@ -128,13 +121,12 @@ public class ConnectionFactoryTest extends JMSTestCase } @Test - public void testNoClientIDConfigured_2() throws Exception - { + public void testNoClientIDConfigured_2() throws Exception { // the ConnectionFactories that ship with ActiveMQ Artemis do not have their clientID // administratively configured. deployConnectionFactory(0, JMSFactoryType.TOPIC_CF, "CF_XA_FALSE", "/CF_XA_FALSE"); - ConnectionFactory cf = (ConnectionFactory)ic.lookup("/CF_XA_FALSE"); + ConnectionFactory cf = (ConnectionFactory) ic.lookup("/CF_XA_FALSE"); Connection c = cf.createConnection(); // set the client id immediately after the connection is created @@ -148,18 +140,16 @@ public class ConnectionFactoryTest extends JMSTestCase // Added for http://jira.jboss.org/jira/browse/JBMESSAGING-939 @Test - public void testDurableSubscriptionOnPreConfiguredConnectionFactory() throws Exception - { + public void testDurableSubscriptionOnPreConfiguredConnectionFactory() throws Exception { ActiveMQServerTestCase.deployConnectionFactory("TestConnectionFactory1", "cfTest", "/TestDurableCF"); createTopic("TestSubscriber"); Connection conn = null; - try - { - Topic topic = (Topic)ic.lookup("/topic/TestSubscriber"); - ConnectionFactory cf = (ConnectionFactory)ic.lookup("/TestDurableCF"); + try { + Topic topic = (Topic) ic.lookup("/topic/TestSubscriber"); + ConnectionFactory cf = (ConnectionFactory) ic.lookup("/TestDurableCF"); conn = cf.createConnection(); // I have to remove this asertion, as the test would work if doing this assertion @@ -171,26 +161,20 @@ public class ConnectionFactoryTest extends JMSTestCase session.createDurableSubscriber(topic, "durableSubscriberChangeSelectorTest", "TEST = 'test'", false); } - finally - { - try - { - if (conn != null) - { + finally { + try { + if (conn != null) { conn.close(); } } - catch (Exception e) - { + catch (Exception e) { log.warn(e.toString(), e); } - try - { + try { destroyTopic("TestSubscriber"); } - catch (Exception e) - { + catch (Exception e) { log.warn(e.toString(), e); } @@ -199,17 +183,15 @@ public class ConnectionFactoryTest extends JMSTestCase } @Test - public void testSlowConsumers() throws Exception - { + public void testSlowConsumers() throws Exception { ArrayList bindings = new ArrayList(); bindings.add("TestSlowConsumersCF"); ActiveMQServerTestCase.deployConnectionFactory(0, "TestSlowConsumersCF", 1, "TestSlowConsumersCF"); Connection conn = null; - try - { - ConnectionFactory cf = (ConnectionFactory)ic.lookup("/TestSlowConsumersCF"); + try { + ConnectionFactory cf = (ConnectionFactory) ic.lookup("/TestSlowConsumersCF"); conn = cf.createConnection(); @@ -221,18 +203,15 @@ public class ConnectionFactoryTest extends JMSTestCase final int numMessages = 500; - class FastListener implements MessageListener - { + class FastListener implements MessageListener { + int processed; - public void onMessage(final Message msg) - { + public void onMessage(final Message msg) { processed++; - if (processed == numMessages - 2) - { - synchronized (waitLock) - { + if (processed == numMessages - 2) { + synchronized (waitLock) { waitLock.notifyAll(); } } @@ -241,25 +220,20 @@ public class ConnectionFactoryTest extends JMSTestCase final FastListener fast = new FastListener(); - class SlowListener implements MessageListener - { + class SlowListener implements MessageListener { + int processed; - public void onMessage(final Message msg) - { + public void onMessage(final Message msg) { processed++; - synchronized (waitLock) - { + synchronized (waitLock) { // Should really cope with spurious wakeups - while (fast.processed != numMessages - 2) - { - try - { + while (fast.processed != numMessages - 2) { + try { waitLock.wait(20000); } - catch (InterruptedException e) - { + catch (InterruptedException e) { } } @@ -284,8 +258,7 @@ public class ConnectionFactoryTest extends JMSTestCase conn.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage tm = sessSend.createTextMessage("message" + i); prod.send(tm); @@ -294,16 +267,13 @@ public class ConnectionFactoryTest extends JMSTestCase // All the messages bar one should be consumed by the fast listener - since the slow listener shouldn't buffer // any. - synchronized (waitLock) - { + synchronized (waitLock) { // Should really cope with spurious wakeups - while (fast.processed != numMessages - 2) - { + while (fast.processed != numMessages - 2) { waitLock.wait(20000); } - while (slow.processed != 2) - { + while (slow.processed != 2) { waitLock.wait(20000); } } @@ -311,26 +281,20 @@ public class ConnectionFactoryTest extends JMSTestCase Assert.assertTrue(fast.processed == numMessages - 2); } - finally - { - try - { - if (conn != null) - { + finally { + try { + if (conn != null) { conn.close(); } } - catch (Exception e) - { + catch (Exception e) { log.warn(e.toString(), e); } - try - { + try { ActiveMQServerTestCase.undeployConnectionFactory("TestSlowConsumersCF"); } - catch (Exception e) - { + catch (Exception e) { log.warn(e.toString(), e); } @@ -339,8 +303,7 @@ public class ConnectionFactoryTest extends JMSTestCase } @Test - public void testFactoryTypes() throws Exception - { + public void testFactoryTypes() throws Exception { deployConnectionFactory(0, JMSFactoryType.CF, "ConnectionFactory", "/ConnectionFactory"); deployConnectionFactory(0, JMSFactoryType.QUEUE_XA_CF, "CF_QUEUE_XA_TRUE", "/CF_QUEUE_XA_TRUE"); deployConnectionFactory(0, JMSFactoryType.QUEUE_CF, "CF_QUEUE_XA_FALSE", "/CF_QUEUE_XA_FALSE"); @@ -356,62 +319,62 @@ public class ConnectionFactoryTest extends JMSTestCase ActiveMQConnectionFactory factory = null; - factory = (ActiveMQConnectionFactory)ic.lookup("/ConnectionFactory"); + factory = (ActiveMQConnectionFactory) ic.lookup("/ConnectionFactory"); Assert.assertTrue(factory instanceof ConnectionFactory); assertNTypes(factory, 4); - factory = (ActiveMQConnectionFactory)ic.lookup("/CF_XA_TRUE"); + factory = (ActiveMQConnectionFactory) ic.lookup("/CF_XA_TRUE"); Assert.assertTrue(factory instanceof XAConnectionFactory); assertNTypes(factory, 6); - factory = (ActiveMQConnectionFactory)ic.lookup("/CF_XA_FALSE"); + factory = (ActiveMQConnectionFactory) ic.lookup("/CF_XA_FALSE"); Assert.assertTrue(factory instanceof ConnectionFactory); assertNTypes(factory, 4); - factory = (ActiveMQConnectionFactory)ic.lookup("/CF_GENERIC"); + factory = (ActiveMQConnectionFactory) ic.lookup("/CF_GENERIC"); Assert.assertTrue(factory instanceof ConnectionFactory); assertNTypes(factory, 4); - factory = (ActiveMQConnectionFactory)ic.lookup("/CF_GENERIC_XA_TRUE"); + factory = (ActiveMQConnectionFactory) ic.lookup("/CF_GENERIC_XA_TRUE"); Assert.assertTrue(factory instanceof XAConnectionFactory); assertNTypes(factory, 6); - factory = (ActiveMQConnectionFactory)ic.lookup("/CF_GENERIC_XA_FALSE"); + factory = (ActiveMQConnectionFactory) ic.lookup("/CF_GENERIC_XA_FALSE"); Assert.assertTrue(factory instanceof ConnectionFactory); assertNTypes(factory, 4); - factory = (ActiveMQConnectionFactory)ic.lookup("/CF_QUEUE"); + factory = (ActiveMQConnectionFactory) ic.lookup("/CF_QUEUE"); Assert.assertTrue(factory instanceof QueueConnectionFactory); assertNTypes(factory, 3); - factory = (ActiveMQConnectionFactory)ic.lookup("/CF_QUEUE_XA_TRUE"); + factory = (ActiveMQConnectionFactory) ic.lookup("/CF_QUEUE_XA_TRUE"); Assert.assertTrue(factory instanceof XAQueueConnectionFactory); assertNTypes(factory, 4); - factory = (ActiveMQConnectionFactory)ic.lookup("/CF_QUEUE_XA_FALSE"); + factory = (ActiveMQConnectionFactory) ic.lookup("/CF_QUEUE_XA_FALSE"); Assert.assertTrue(factory instanceof QueueConnectionFactory); assertNTypes(factory, 3); - factory = (ActiveMQConnectionFactory)ic.lookup("/CF_TOPIC"); + factory = (ActiveMQConnectionFactory) ic.lookup("/CF_TOPIC"); Assert.assertTrue(factory instanceof TopicConnectionFactory); assertNTypes(factory, 3); - factory = (ActiveMQConnectionFactory)ic.lookup("/CF_TOPIC_XA_TRUE"); + factory = (ActiveMQConnectionFactory) ic.lookup("/CF_TOPIC_XA_TRUE"); Assert.assertTrue(factory instanceof XATopicConnectionFactory); assertNTypes(factory, 4); - factory = (ActiveMQConnectionFactory)ic.lookup("/CF_TOPIC_XA_FALSE"); + factory = (ActiveMQConnectionFactory) ic.lookup("/CF_TOPIC_XA_FALSE"); Assert.assertTrue(factory instanceof TopicConnectionFactory); assertNTypes(factory, 3); @@ -431,8 +394,7 @@ public class ConnectionFactoryTest extends JMSTestCase } @Test - public void testConnectionTypes() throws Exception - { + public void testConnectionTypes() throws Exception { deployConnectionFactory(0, JMSFactoryType.CF, "ConnectionFactory", "/ConnectionFactory"); deployConnectionFactory(0, JMSFactoryType.QUEUE_XA_CF, "CF_QUEUE_XA_TRUE", "/CF_QUEUE_XA_TRUE"); deployConnectionFactory(0, JMSFactoryType.XA_CF, "CF_XA_TRUE", "/CF_XA_TRUE"); @@ -447,27 +409,27 @@ public class ConnectionFactoryTest extends JMSTestCase XAQueueConnection xaQueueConnection = null; XATopicConnection xaTopicConnection = null; - ConnectionFactory genericFactory = (ConnectionFactory)ic.lookup("/ConnectionFactory"); + ConnectionFactory genericFactory = (ConnectionFactory) ic.lookup("/ConnectionFactory"); genericConnection = genericFactory.createConnection(); assertConnectionType(genericConnection, "generic"); - XAConnectionFactory xaFactory = (XAConnectionFactory)ic.lookup("/CF_XA_TRUE"); + XAConnectionFactory xaFactory = (XAConnectionFactory) ic.lookup("/CF_XA_TRUE"); xaConnection = xaFactory.createXAConnection(); assertConnectionType(xaConnection, "xa"); - QueueConnectionFactory queueCF = (QueueConnectionFactory)ic.lookup("/CF_QUEUE"); + QueueConnectionFactory queueCF = (QueueConnectionFactory) ic.lookup("/CF_QUEUE"); queueConnection = queueCF.createQueueConnection(); assertConnectionType(queueConnection, "queue"); - TopicConnectionFactory topicCF = (TopicConnectionFactory)ic.lookup("/CF_TOPIC"); + TopicConnectionFactory topicCF = (TopicConnectionFactory) ic.lookup("/CF_TOPIC"); topicConnection = topicCF.createTopicConnection(); assertConnectionType(topicConnection, "topic"); - XAQueueConnectionFactory xaQueueCF = (XAQueueConnectionFactory)ic.lookup("/CF_QUEUE_XA_TRUE"); + XAQueueConnectionFactory xaQueueCF = (XAQueueConnectionFactory) ic.lookup("/CF_QUEUE_XA_TRUE"); xaQueueConnection = xaQueueCF.createXAQueueConnection(); assertConnectionType(xaQueueConnection, "xa-queue"); - XATopicConnectionFactory xaTopicCF = (XATopicConnectionFactory)ic.lookup("/CF_TOPIC_XA_TRUE"); + XATopicConnectionFactory xaTopicCF = (XATopicConnectionFactory) ic.lookup("/CF_TOPIC_XA_TRUE"); xaTopicConnection = xaTopicCF.createXATopicConnection(); assertConnectionType(xaTopicConnection, "xa-topic"); @@ -486,10 +448,8 @@ public class ConnectionFactoryTest extends JMSTestCase undeployConnectionFactory("CF_TOPIC_XA_TRUE"); } - private void assertConnectionType(Connection conn, String type) - { - if ("generic".equals(type) || "queue".equals(type) || "topic".equals(type)) - { + private void assertConnectionType(Connection conn, String type) { + if ("generic".equals(type) || "queue".equals(type) || "topic".equals(type)) { //generic Assert.assertFalse(conn instanceof XAConnection); Assert.assertTrue(conn instanceof QueueConnection); @@ -497,52 +457,43 @@ public class ConnectionFactoryTest extends JMSTestCase Assert.assertTrue(conn instanceof TopicConnection); Assert.assertFalse(conn instanceof XATopicConnection); } - else if ("xa".equals(type) || "xa-queue".equals(type) || "xa-topic".equals(type)) - { + else if ("xa".equals(type) || "xa-queue".equals(type) || "xa-topic".equals(type)) { Assert.assertTrue(conn instanceof XAConnection); Assert.assertTrue(conn instanceof QueueConnection); Assert.assertTrue(conn instanceof XAQueueConnection); Assert.assertTrue(conn instanceof TopicConnection); Assert.assertTrue(conn instanceof XATopicConnection); } - else - { + else { Assert.fail("Unknown connection type: " + type); } } - private void assertNTypes(ActiveMQConnectionFactory factory, final int total) - { + private void assertNTypes(ActiveMQConnectionFactory factory, final int total) { StringBuilder text = new StringBuilder(); text.append(factory + "\n is instance of "); int num = 0; - if (factory instanceof ConnectionFactory) - { + if (factory instanceof ConnectionFactory) { num++; text.append("ConnectionFactory "); } - if (factory instanceof XAConnectionFactory) - { + if (factory instanceof XAConnectionFactory) { num++; text.append("XAConnectionFactory "); } - if (factory instanceof QueueConnectionFactory) - { + if (factory instanceof QueueConnectionFactory) { num++; text.append("QueueConnectionFactory "); } - if (factory instanceof TopicConnectionFactory) - { + if (factory instanceof TopicConnectionFactory) { num++; text.append("TopicConnectionFactory "); } - if (factory instanceof XAQueueConnectionFactory) - { + if (factory instanceof XAQueueConnectionFactory) { num++; text.append("XAQueueConnectionFactory "); } - if (factory instanceof XATopicConnectionFactory) - { + if (factory instanceof XATopicConnectionFactory) { num++; text.append("XATopicConnectionFactory "); } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/ConnectionTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/ConnectionTest.java index 1a3e48f5d2..7fee727cd4 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/ConnectionTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/ConnectionTest.java @@ -34,8 +34,7 @@ import org.junit.Test; * Connection tests. Contains all connection tests, except tests relating to closing a connection, * which go to ConnectionClosedTest. */ -public class ConnectionTest extends JMSTestCase -{ +public class ConnectionTest extends JMSTestCase { // Constants ----------------------------------------------------- private static final JmsTestLogger log = JmsTestLogger.LOGGER; @@ -51,10 +50,8 @@ public class ConnectionTest extends JMSTestCase // Public -------------------------------------------------------- @Test - public void testManyConnections() throws Exception - { - for (int i = 0; i < 100; i++) - { + public void testManyConnections() throws Exception { + for (int i = 0; i < 100; i++) { Connection conn = createConnection(); conn.close(); } @@ -65,8 +62,7 @@ public class ConnectionTest extends JMSTestCase // @Test - public void testGetClientID() throws Exception - { + public void testGetClientID() throws Exception { Connection connection = createConnection(); String clientID = connection.getClientID(); @@ -79,8 +75,7 @@ public class ConnectionTest extends JMSTestCase } @Test - public void testSetClientID() throws Exception - { + public void testSetClientID() throws Exception { Connection connection = createConnection(); final String clientID = "my-test-client-id"; @@ -90,13 +85,11 @@ public class ConnectionTest extends JMSTestCase ProxyAssertSupport.assertEquals(clientID, connection.getClientID()); Connection connection2 = createConnection(); - try - { + try { connection2.setClientID(clientID); Assert.fail("setClientID was expected to throw an exception"); } - catch (JMSException e) - { + catch (JMSException e) { // expected } @@ -106,11 +99,9 @@ public class ConnectionTest extends JMSTestCase } @Test - public void testSetClientAfterStart() throws Exception - { + public void testSetClientAfterStart() throws Exception { Connection connection = null; - try - { + try { connection = createConnection(); // we startthe connection @@ -120,21 +111,16 @@ public class ConnectionTest extends JMSTestCase connection.setClientID("testSetClientID_2"); ProxyAssertSupport.fail("Should throw a javax.jms.IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { } - catch (JMSException e) - { + catch (JMSException e) { ProxyAssertSupport.fail("Should raise a javax.jms.IllegalStateException, not a " + e); } - catch (java.lang.IllegalStateException e) - { + catch (java.lang.IllegalStateException e) { ProxyAssertSupport.fail("Should raise a javax.jms.IllegalStateException, not a java.lang.IllegalStateException"); } - finally - { - if (connection != null) - { + finally { + if (connection != null) { connection.close(); } } @@ -142,8 +128,7 @@ public class ConnectionTest extends JMSTestCase } @Test - public void testSetClientIDFail() throws Exception - { + public void testSetClientIDFail() throws Exception { final String clientID = "my-test-client-id"; // Setting a client id must be the first thing done to the connection @@ -151,13 +136,11 @@ public class ConnectionTest extends JMSTestCase Connection connection = createConnection(); connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - try - { + try { connection.setClientID(clientID); ProxyAssertSupport.fail(); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { ConnectionTest.log.trace("Caught exception ok"); } @@ -165,46 +148,41 @@ public class ConnectionTest extends JMSTestCase // TODO: This will probably go away, remove it enterily after we // make sure this rule can go away -// connection = createConnection(); -// connection.getClientID(); -// try -// { -// connection.setClientID(clientID); -// ProxyAssertSupport.fail(); -// } -// catch (javax.jms.IllegalStateException e) -// { -// } -// connection.close(); + // connection = createConnection(); + // connection.getClientID(); + // try + // { + // connection.setClientID(clientID); + // ProxyAssertSupport.fail(); + // } + // catch (javax.jms.IllegalStateException e) + // { + // } + // connection.close(); connection = createConnection(); ExceptionListener listener = connection.getExceptionListener(); - try - { + try { connection.setClientID(clientID); ProxyAssertSupport.fail(); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { } connection.close(); connection = createConnection(); connection.setExceptionListener(listener); - try - { + try { connection.setClientID(clientID); ProxyAssertSupport.fail(); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { } connection.close(); } @Test - public void testGetMetadata() throws Exception - { + public void testGetMetadata() throws Exception { Connection connection = createConnection(); ConnectionMetaData metaData = connection.getMetaData(); @@ -226,8 +204,7 @@ public class ConnectionTest extends JMSTestCase * Test creation of QueueSession */ @Test - public void testQueueConnection1() throws Exception - { + public void testQueueConnection1() throws Exception { QueueConnection qc = queueCf.createQueueConnection(); qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); @@ -239,8 +216,7 @@ public class ConnectionTest extends JMSTestCase * Test creation of TopicSession */ @Test - public void testTopicConnection() throws Exception - { + public void testTopicConnection() throws Exception { TopicConnection tc = topicCf.createTopicConnection(); tc.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); @@ -250,8 +226,7 @@ public class ConnectionTest extends JMSTestCase * Test ExceptionListener stuff */ @Test - public void testExceptionListener() throws Exception - { + public void testExceptionListener() throws Exception { Connection conn = createConnection(); ExceptionListener listener1 = new MyExceptionListener(); @@ -271,10 +246,8 @@ public class ConnectionTest extends JMSTestCase // This test is to check netty issue in https://jira.jboss.org/jira/browse/JBMESSAGING-1618 @Test - public void testConnectionListenerBug() throws Exception - { - for (int i = 0; i < 1000; i++) - { + public void testConnectionListenerBug() throws Exception { + for (int i = 0; i < 1000; i++) { Connection conn = createConnection(); MyExceptionListener listener = new MyExceptionListener(); @@ -292,32 +265,22 @@ public class ConnectionTest extends JMSTestCase * @throws Exception */ @Test - public void testDurableSubscriberOnQueueConnection() throws Exception - { - QueueConnection queueConnection = ((QueueConnectionFactory)queueCf).createQueueConnection(); + public void testDurableSubscriberOnQueueConnection() throws Exception { + QueueConnection queueConnection = ((QueueConnectionFactory) queueCf).createQueueConnection(); - try - { - queueConnection.createDurableConnectionConsumer(ActiveMQServerTestCase.topic1, - "subscriptionName", - "", - (ServerSessionPool)null, - 1); + try { + queueConnection.createDurableConnectionConsumer(ActiveMQServerTestCase.topic1, "subscriptionName", "", (ServerSessionPool) null, 1); ProxyAssertSupport.fail("Should throw a javax.jms.IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { } - catch (java.lang.IllegalStateException e) - { + catch (java.lang.IllegalStateException e) { ProxyAssertSupport.fail("Should throw a javax.jms.IllegalStateException"); } - catch (JMSException e) - { + catch (JMSException e) { ProxyAssertSupport.fail("Should throw a javax.jms.IllegalStateException, not a " + e); } - finally - { + finally { queueConnection.close(); } } @@ -330,12 +293,11 @@ public class ConnectionTest extends JMSTestCase // Inner classes ------------------------------------------------- - static class MyExceptionListener implements ExceptionListener - { + static class MyExceptionListener implements ExceptionListener { + JMSException exceptionReceived; - public void onException(final JMSException exception) - { + public void onException(final JMSException exception) { exceptionReceived = exception; ConnectionTest.log.trace("Received exception"); } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/ConsumerClosedTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/ConsumerClosedTest.java index 7ed4f677df..f6c96fc8c7 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/ConsumerClosedTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/ConsumerClosedTest.java @@ -24,8 +24,7 @@ import javax.naming.InitialContext; import org.junit.Test; -public class ConsumerClosedTest extends JMSTestCase -{ +public class ConsumerClosedTest extends JMSTestCase { // Constants ----------------------------------------------------- public static final int NUMBER_OF_MESSAGES = 10; @@ -41,20 +40,17 @@ public class ConsumerClosedTest extends JMSTestCase // Public -------------------------------------------------------- @Test - public void testMessagesSentDuringClose() throws Exception - { + public void testMessagesSentDuringClose() throws Exception { Connection c = null; - try - { + try { c = createConnection(); c.start(); Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer p = s.createProducer(queue1); - for (int i = 0; i < ConsumerClosedTest.NUMBER_OF_MESSAGES; i++) - { + for (int i = 0; i < ConsumerClosedTest.NUMBER_OF_MESSAGES; i++) { p.send(s.createTextMessage("message" + i)); } @@ -69,10 +65,8 @@ public class ConsumerClosedTest extends JMSTestCase assertRemainingMessages(ConsumerClosedTest.NUMBER_OF_MESSAGES); } - finally - { - if (c != null) - { + finally { + if (c != null) { c.close(); } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/DeliveryOrderTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/DeliveryOrderTest.java index 8a748dae54..794d472f08 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/DeliveryOrderTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/DeliveryOrderTest.java @@ -32,12 +32,10 @@ import org.junit.Test; import static java.util.concurrent.TimeUnit.MILLISECONDS; -public class DeliveryOrderTest extends JMSTestCase -{ +public class DeliveryOrderTest extends JMSTestCase { @Test - public void testOutOfOrder() throws Exception - { + public void testOutOfOrder() throws Exception { Connection conn = createConnection(); Session sess = conn.createSession(true, Session.SESSION_TRANSACTED); @@ -58,14 +56,12 @@ public class DeliveryOrderTest extends JMSTestCase conn.start(); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = sess.createTextMessage("message" + i); prod.send(tm); - if (i % 10 == 0) - { + if (i % 10 == 0) { sess.commit(); } } @@ -75,14 +71,13 @@ public class DeliveryOrderTest extends JMSTestCase Assert.assertTrue(latch.await(20000, MILLISECONDS)); - if (listener.failed) - { + if (listener.failed) { ProxyAssertSupport.fail("listener failed: " + listener.getError()); } } - class MyListener implements MessageListener - { + class MyListener implements MessageListener { + private int c; private final int num; @@ -95,27 +90,22 @@ public class DeliveryOrderTest extends JMSTestCase private final Session sess; - MyListener(final CountDownLatch latch, final Session sess, final int num) - { + MyListener(final CountDownLatch latch, final Session sess, final int num) { this.latch = latch; this.num = num; this.sess = sess; } - public void onMessage(final Message msg) - { + public void onMessage(final Message msg) { // preserve the first error - if (failed) - { + if (failed) { return; } - try - { + try { TextMessage tm = (TextMessage) msg; - if (!("message" + c).equals(tm.getText())) - { + if (!("message" + c).equals(tm.getText())) { // Failed failed = true; setError("Listener was supposed to get " + "message" + c + " but got " + tm.getText()); @@ -124,19 +114,16 @@ public class DeliveryOrderTest extends JMSTestCase c++; - if (c % 500 == 0) - { + if (c % 500 == 0) { sess.commit(); } - if (c == num) - { + if (c == num) { sess.commit(); latch.countDown(); } } - catch (JMSException e) - { + catch (JMSException e) { e.printStackTrace(); // Failed @@ -146,13 +133,11 @@ public class DeliveryOrderTest extends JMSTestCase } } - public synchronized String getError() - { + public synchronized String getError() { return error; } - private synchronized void setError(final String s) - { + private synchronized void setError(final String s) { error = s; } } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/DurableSubscriptionTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/DurableSubscriptionTest.java index 4f01c8e8a8..f75fa318e8 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/DurableSubscriptionTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/DurableSubscriptionTest.java @@ -37,8 +37,7 @@ import org.junit.Test; * Tests focused on durable subscription behavior. More durable subscription tests can be found in * MessageConsumerTest. */ -public class DurableSubscriptionTest extends JMSTestCase -{ +public class DurableSubscriptionTest extends JMSTestCase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -50,12 +49,10 @@ public class DurableSubscriptionTest extends JMSTestCase // Public -------------------------------------------------------- @Test - public void testSimplestDurableSubscription() throws Exception - { + public void testSimplestDurableSubscription() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); conn.setClientID("brookeburke"); @@ -103,10 +100,8 @@ public class DurableSubscriptionTest extends JMSTestCase s.unsubscribe("monicabelucci"); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -120,12 +115,10 @@ public class DurableSubscriptionTest extends JMSTestCase * Test with a different topic (a redeployed topic is a different topic). */ @Test - public void testDurableSubscriptionOnNewTopic() throws Exception - { + public void testDurableSubscriptionOnNewTopic() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); conn.setClientID("brookeburke"); @@ -156,10 +149,8 @@ public class DurableSubscriptionTest extends JMSTestCase s.unsubscribe("monicabelucci"); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -173,12 +164,10 @@ public class DurableSubscriptionTest extends JMSTestCase * Test with a different selector. */ @Test - public void testDurableSubscriptionDifferentSelector() throws Exception - { + public void testDurableSubscriptionDifferentSelector() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); conn.setClientID("brookeburke"); @@ -187,10 +176,7 @@ public class DurableSubscriptionTest extends JMSTestCase MessageProducer prod = s.createProducer(ActiveMQServerTestCase.topic1); prod.setDeliveryMode(DeliveryMode.PERSISTENT); - MessageConsumer durable = s.createDurableSubscriber(ActiveMQServerTestCase.topic1, - "monicabelucci", - "color = 'red' AND shape = 'square'", - false); + MessageConsumer durable = s.createDurableSubscriber(ActiveMQServerTestCase.topic1, "monicabelucci", "color = 'red' AND shape = 'square'", false); TextMessage tm = s.createTextMessage("A red square message"); tm.setStringProperty("color", "red"); @@ -236,54 +222,44 @@ public class DurableSubscriptionTest extends JMSTestCase s.unsubscribe("monicabelucci"); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testDurableSubscriptionOnTemporaryTopic() throws Exception - { + public void testDurableSubscriptionOnTemporaryTopic() throws Exception { Connection conn = null; conn = createConnection(); - try - { + try { conn.setClientID("doesn't actually matter"); Session s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); Topic temporaryTopic = s.createTemporaryTopic(); - try - { + try { s.createDurableSubscriber(temporaryTopic, "mySubscription"); ProxyAssertSupport.fail("this should throw exception"); } - catch (InvalidDestinationException e) - { + catch (InvalidDestinationException e) { // OK } } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testUnsubscribeDurableSubscription() throws Exception - { + public void testUnsubscribeDurableSubscription() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); conn.setClientID("ak47"); @@ -306,37 +282,31 @@ public class DurableSubscriptionTest extends JMSTestCase s.unsubscribe("uzzi"); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testInvalidSelectorException() throws Exception - { + public void testInvalidSelectorException() throws Exception { Connection c = createConnection(); c.setClientID("sofiavergara"); Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); - try - { + try { s.createDurableSubscriber(ActiveMQServerTestCase.topic1, "mysubscribption", "=TEST 'test'", true); ProxyAssertSupport.fail("this should fail"); } - catch (InvalidSelectorException e) - { + catch (InvalidSelectorException e) { // OK } } // See JMS 1.1. spec sec 6.11 @Test - public void testUnsubscribeWithActiveConsumer() throws Exception - { + public void testUnsubscribeWithActiveConsumer() throws Exception { Connection conn = createConnection(); conn.setClientID("zeke"); @@ -344,13 +314,11 @@ public class DurableSubscriptionTest extends JMSTestCase TopicSubscriber dursub = s.createDurableSubscriber(ActiveMQServerTestCase.topic1, "dursub0"); - try - { + try { s.unsubscribe("dursub0"); ProxyAssertSupport.fail(); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // Ok - it is illegal to ubscribe a subscription if it has active consumers } @@ -360,8 +328,7 @@ public class DurableSubscriptionTest extends JMSTestCase } @Test - public void testSubscribeWithActiveSubscription() throws Exception - { + public void testSubscribeWithActiveSubscription() throws Exception { Connection conn = createConnection(); conn.setClientID("zeke"); @@ -369,13 +336,11 @@ public class DurableSubscriptionTest extends JMSTestCase TopicSubscriber dursub1 = s.createDurableSubscriber(ActiveMQServerTestCase.topic1, "dursub1"); - try - { + try { s.createDurableSubscriber(ActiveMQServerTestCase.topic1, "dursub1"); ProxyAssertSupport.fail(); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // Ok - it is illegal to have more than one active subscriber on a subscrtiption at any one time } @@ -385,15 +350,13 @@ public class DurableSubscriptionTest extends JMSTestCase } @Test - public void testDurableSubscriptionWithPeriodsInName() throws Exception - { + public void testDurableSubscriptionWithPeriodsInName() throws Exception { Connection conn = createConnection(); conn.setClientID(".client.id.with.periods."); Session s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber subscriber = s.createDurableSubscriber(ActiveMQServerTestCase.topic1, - ".subscription.name.with.periods."); + TopicSubscriber subscriber = s.createDurableSubscriber(ActiveMQServerTestCase.topic1, ".subscription.name.with.periods."); s.createProducer(ActiveMQServerTestCase.topic1).send(s.createTextMessage("Subscription test")); @@ -410,14 +373,12 @@ public class DurableSubscriptionTest extends JMSTestCase } @Test - public void testNoLocal() throws Exception - { + public void testNoLocal() throws Exception { internalTestNoLocal(true); internalTestNoLocal(false); } - private void internalTestNoLocal(final boolean noLocal) throws Exception - { + private void internalTestNoLocal(final boolean noLocal) throws Exception { Connection conn1 = createConnection(); conn1.setClientID(".client.id.with.periods."); @@ -428,14 +389,8 @@ public class DurableSubscriptionTest extends JMSTestCase Session s1 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE); Session s2 = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber subscriber1 = s1.createDurableSubscriber(ActiveMQServerTestCase.topic1, - ".subscription.name.with.periods.", - null, - noLocal); - TopicSubscriber subscriber2 = s2.createDurableSubscriber(ActiveMQServerTestCase.topic1, - ".subscription.name.with.periods.", - null, - false); + TopicSubscriber subscriber1 = s1.createDurableSubscriber(ActiveMQServerTestCase.topic1, ".subscription.name.with.periods.", null, noLocal); + TopicSubscriber subscriber2 = s2.createDurableSubscriber(ActiveMQServerTestCase.topic1, ".subscription.name.with.periods.", null, false); s1.createProducer(ActiveMQServerTestCase.topic1).send(s1.createTextMessage("Subscription test")); @@ -443,12 +398,10 @@ public class DurableSubscriptionTest extends JMSTestCase Message m = subscriber1.receive(100L); - if (noLocal) - { + if (noLocal) { ProxyAssertSupport.assertNull(m); } - else - { + else { ProxyAssertSupport.assertNotNull(m); } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/JMSTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/JMSTest.java index 17135193e9..5df5887130 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/JMSTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/JMSTest.java @@ -34,35 +34,29 @@ import org.junit.Test; import static java.util.concurrent.TimeUnit.MILLISECONDS; - /** * The most comprehensive, yet simple, unit test. */ -public class JMSTest extends JMSTestCase -{ +public class JMSTest extends JMSTestCase { + Connection conn = null; @Override @After - public void tearDown() throws Exception - { - try - { - if (conn != null) - { + public void tearDown() throws Exception { + try { + if (conn != null) { conn.close(); conn = null; } } - finally - { + finally { super.tearDown(); } } @Test - public void test_NonPersistent_NonTransactional() throws Exception - { + public void test_NonPersistent_NonTransactional() throws Exception { conn = createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -92,8 +86,7 @@ public class JMSTest extends JMSTestCase } @Test - public void testCreateTextMessageNull() throws Exception - { + public void testCreateTextMessageNull() throws Exception { conn = createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -123,8 +116,7 @@ public class JMSTest extends JMSTestCase } @Test - public void testPersistent_NonTransactional() throws Exception - { + public void testPersistent_NonTransactional() throws Exception { conn = createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -152,8 +144,7 @@ public class JMSTest extends JMSTestCase } @Test - public void testNonPersistent_Transactional_Send() throws Exception - { + public void testNonPersistent_Transactional_Send() throws Exception { conn = createConnection(); Session session = conn.createSession(true, Session.SESSION_TRANSACTED); @@ -185,8 +176,7 @@ public class JMSTest extends JMSTestCase } @Test - public void testPersistent_Transactional_Send() throws Exception - { + public void testPersistent_Transactional_Send() throws Exception { conn = createConnection(); Session session = conn.createSession(true, Session.SESSION_TRANSACTED); @@ -218,8 +208,7 @@ public class JMSTest extends JMSTestCase } @Test - public void testNonPersistent_Transactional_Acknowledgment() throws Exception - { + public void testNonPersistent_Transactional_Acknowledgment() throws Exception { conn = createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -246,8 +235,7 @@ public class JMSTest extends JMSTestCase } @Test - public void testAsynchronous_to_Client() throws Exception - { + public void testAsynchronous_to_Client() throws Exception { conn = createConnection(); final Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -259,36 +247,29 @@ public class JMSTest extends JMSTestCase final AtomicReference message = new AtomicReference(); final CountDownLatch latch = new CountDownLatch(1); - new Thread(new Runnable() - { - public void run() - { - try - { + new Thread(new Runnable() { + public void run() { + try { // sleep a little bit to ensure that // prod.send will be called before cons.reveive Thread.sleep(500); - synchronized (session) - { + synchronized (session) { Message m = cons.receive(5000); - if (m != null) - { + if (m != null) { message.set(m); latch.countDown(); } } } - catch (Exception e) - { + catch (Exception e) { log.error("receive failed", e); } } }, "Receiving Thread").start(); - synchronized (session) - { + synchronized (session) { MessageProducer prod = session.createProducer(queue1); prod.setDeliveryMode(DeliveryMode.NON_PERSISTENT); @@ -305,8 +286,7 @@ public class JMSTest extends JMSTestCase } @Test - public void testMessageListener() throws Exception - { + public void testMessageListener() throws Exception { conn = createConnection(); Session sessionConsumer = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -316,10 +296,8 @@ public class JMSTest extends JMSTestCase final AtomicReference message = new AtomicReference(); final CountDownLatch latch = new CountDownLatch(1); - cons.setMessageListener(new MessageListener() - { - public void onMessage(final Message m) - { + cons.setMessageListener(new MessageListener() { + public void onMessage(final Message m) { message.set(m); latch.countDown(); } @@ -327,7 +305,6 @@ public class JMSTest extends JMSTestCase conn.start(); - Session sessionProducer = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = sessionProducer.createProducer(queue1); prod.setDeliveryMode(DeliveryMode.NON_PERSISTENT); @@ -342,8 +319,7 @@ public class JMSTest extends JMSTestCase } @Test - public void testClientAcknowledge() throws Exception - { + public void testClientAcknowledge() throws Exception { conn = createConnection(); Session session = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/JMSTestCase.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/JMSTestCase.java index fc16ad4f2c..ae695dcbf1 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/JMSTestCase.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/JMSTestCase.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.jms.tests; + import java.util.ArrayList; import javax.jms.Connection; @@ -36,16 +37,14 @@ import org.junit.Before; /** * @deprecated this infrastructure should not be used for new code. New tests should go into - * org.apache.activemq.tests.integration.jms at the integration-tests project. + * org.apache.activemq.tests.integration.jms at the integration-tests project. */ @Deprecated -public class JMSTestCase extends ActiveMQServerTestCase -{ +public class JMSTestCase extends ActiveMQServerTestCase { protected static final ArrayList NETTY_CONNECTOR = new ArrayList(); - static - { + static { NETTY_CONNECTOR.add("netty"); } @@ -63,8 +62,7 @@ public class JMSTestCase extends ActiveMQServerTestCase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); ic = getInitialContext(); @@ -72,158 +70,47 @@ public class JMSTestCase extends ActiveMQServerTestCase // All jms tests should use a specific cg which has blockOnAcknowledge = true and // both np and p messages are sent synchronously + getJmsServerManager().createConnectionFactory("testsuitecf", false, JMSFactoryType.CF, NETTY_CONNECTOR, null, ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, ActiveMQClient.DEFAULT_CONNECTION_TTL, ActiveMQClient.DEFAULT_CALL_TIMEOUT, ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, ActiveMQClient.DEFAULT_CACHE_LARGE_MESSAGE_CLIENT, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES, ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, true, true, true, ActiveMQClient.DEFAULT_AUTO_GROUP, ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_RETRY_INTERVAL, ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, ActiveMQClient.DEFAULT_MAX_RETRY_INTERVAL, ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS, ActiveMQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION, null, "/testsuitecf"); - getJmsServerManager().createConnectionFactory("testsuitecf", - false, - JMSFactoryType.CF, - NETTY_CONNECTOR, - null, - ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, - ActiveMQClient.DEFAULT_CONNECTION_TTL, - ActiveMQClient.DEFAULT_CALL_TIMEOUT, - ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, - ActiveMQClient.DEFAULT_CACHE_LARGE_MESSAGE_CLIENT, - ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES, - ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, - ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, - true, - true, - true, - ActiveMQClient.DEFAULT_AUTO_GROUP, - ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, - ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_RETRY_INTERVAL, - ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, - ActiveMQClient.DEFAULT_MAX_RETRY_INTERVAL, - ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS, - ActiveMQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION, - null, - "/testsuitecf"); + getJmsServerManager().createConnectionFactory("testsuitecf_queue", false, JMSFactoryType.QUEUE_CF, NETTY_CONNECTOR, null, ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, ActiveMQClient.DEFAULT_CONNECTION_TTL, ActiveMQClient.DEFAULT_CALL_TIMEOUT, ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, ActiveMQClient.DEFAULT_CACHE_LARGE_MESSAGE_CLIENT, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES, ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, true, true, true, ActiveMQClient.DEFAULT_AUTO_GROUP, ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_RETRY_INTERVAL, ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, ActiveMQClient.DEFAULT_MAX_RETRY_INTERVAL, ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS, ActiveMQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION, null, "/testsuitecf_queue"); - getJmsServerManager().createConnectionFactory("testsuitecf_queue", - false, - JMSFactoryType.QUEUE_CF, - NETTY_CONNECTOR, - null, - ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, - ActiveMQClient.DEFAULT_CONNECTION_TTL, - ActiveMQClient.DEFAULT_CALL_TIMEOUT, - ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, - ActiveMQClient.DEFAULT_CACHE_LARGE_MESSAGE_CLIENT, - ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES, - ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, - ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, - true, - true, - true, - ActiveMQClient.DEFAULT_AUTO_GROUP, - ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, - ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_RETRY_INTERVAL, - ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, - ActiveMQClient.DEFAULT_MAX_RETRY_INTERVAL, - ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS, - ActiveMQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION, - null, - "/testsuitecf_queue"); + getJmsServerManager().createConnectionFactory("testsuitecf_topic", false, JMSFactoryType.TOPIC_CF, NETTY_CONNECTOR, null, ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, ActiveMQClient.DEFAULT_CONNECTION_TTL, ActiveMQClient.DEFAULT_CALL_TIMEOUT, ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, ActiveMQClient.DEFAULT_CACHE_LARGE_MESSAGE_CLIENT, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES, ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, true, true, true, ActiveMQClient.DEFAULT_AUTO_GROUP, ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_RETRY_INTERVAL, ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, ActiveMQClient.DEFAULT_MAX_RETRY_INTERVAL, ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS, ActiveMQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION, null, "/testsuitecf_topic"); - getJmsServerManager().createConnectionFactory("testsuitecf_topic", - false, - JMSFactoryType.TOPIC_CF, - NETTY_CONNECTOR, - null, - ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, - ActiveMQClient.DEFAULT_CONNECTION_TTL, - ActiveMQClient.DEFAULT_CALL_TIMEOUT, - ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, - ActiveMQClient.DEFAULT_CACHE_LARGE_MESSAGE_CLIENT, - ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES, - ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, - ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, - true, - true, - true, - ActiveMQClient.DEFAULT_AUTO_GROUP, - ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, - ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_RETRY_INTERVAL, - ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, - ActiveMQClient.DEFAULT_MAX_RETRY_INTERVAL, - ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS, - ActiveMQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION, - null, - "/testsuitecf_topic"); - - cf = (ActiveMQJMSConnectionFactory)getInitialContext().lookup("/testsuitecf"); - queueCf = (ActiveMQQueueConnectionFactory)getInitialContext().lookup("/testsuitecf_queue"); - topicCf = (ActiveMQTopicConnectionFactory)getInitialContext().lookup("/testsuitecf_topic"); + cf = (ActiveMQJMSConnectionFactory) getInitialContext().lookup("/testsuitecf"); + queueCf = (ActiveMQQueueConnectionFactory) getInitialContext().lookup("/testsuitecf_queue"); + topicCf = (ActiveMQTopicConnectionFactory) getInitialContext().lookup("/testsuitecf_topic"); assertRemainingMessages(0); } - protected final JMSContext createContext() - { + protected final JMSContext createContext() { return addContext(cf.createContext()); } - - protected final Connection createConnection() throws JMSException - { + protected final Connection createConnection() throws JMSException { Connection c = cf.createConnection(); return addConnection(c); } - protected final TopicConnection createTopicConnection() throws JMSException - { + protected final TopicConnection createTopicConnection() throws JMSException { TopicConnection c = cf.createTopicConnection(); addConnection(c); return c; } - protected final QueueConnection createQueueConnection() throws JMSException - { + protected final QueueConnection createQueueConnection() throws JMSException { QueueConnection c = cf.createQueueConnection(); addConnection(c); return c; } - protected final XAConnection createXAConnection() throws JMSException - { + protected final XAConnection createXAConnection() throws JMSException { XAConnection c = cf.createXAConnection(); addConnection(c); return c; } - - protected final Connection createConnection(String user, String password) throws JMSException - { + protected final Connection createConnection(String user, String password) throws JMSException { Connection c = cf.createConnection(user, password); addConnection(c); return c; @@ -231,12 +118,10 @@ public class JMSTestCase extends ActiveMQServerTestCase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { super.tearDown(); getJmsServerManager().destroyConnectionFactory("testsuitecf"); - if (cf != null) - { + if (cf != null) { cf.close(); } @@ -245,8 +130,7 @@ public class JMSTestCase extends ActiveMQServerTestCase assertRemainingMessages(0); } - protected Connection createConnection(ConnectionFactory cf1) throws JMSException - { + protected Connection createConnection(ConnectionFactory cf1) throws JMSException { return addConnection(cf1.createConnection()); } } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/JmsTestLogger.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/JmsTestLogger.java index 6199f17d64..81ff1c812a 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/JmsTestLogger.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/JmsTestLogger.java @@ -21,8 +21,8 @@ import org.jboss.logging.Logger; import org.jboss.logging.annotations.MessageLogger; @MessageLogger(projectCode = "AMQTEST") -public interface JmsTestLogger extends BasicLogger -{ +public interface JmsTestLogger extends BasicLogger { + /** * The jms test logger. */ diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/MessageConsumerTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/MessageConsumerTest.java index 5222ad6d94..288014fb6a 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/MessageConsumerTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/MessageConsumerTest.java @@ -50,16 +50,13 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Assert; import org.junit.Test; -public class MessageConsumerTest extends JMSTestCase -{ +public class MessageConsumerTest extends JMSTestCase { @Test - public void testReceiveWithClientAckThenCloseSession() throws Exception - { + public void testReceiveWithClientAckThenCloseSession() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -68,8 +65,7 @@ public class MessageConsumerTest extends JMSTestCase final int NUM_MESSAGES = 5; - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = sess.createTextMessage("message" + i); prod.send(tm); @@ -81,8 +77,7 @@ public class MessageConsumerTest extends JMSTestCase conn.start(); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = (TextMessage) cons.receive(500); ProxyAssertSupport.assertNotNull(tm); @@ -94,10 +89,8 @@ public class MessageConsumerTest extends JMSTestCase sess2.close(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } @@ -106,12 +99,10 @@ public class MessageConsumerTest extends JMSTestCase } @Test - public void testRelayMessage() throws Exception - { + public void testRelayMessage() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); conn.start(); @@ -124,35 +115,29 @@ public class MessageConsumerTest extends JMSTestCase final int numMessages = 100; - class MyListener implements MessageListener - { + class MyListener implements MessageListener { + boolean failed; int count; - public synchronized void onMessage(final Message m) - { - try - { + public synchronized void onMessage(final Message m) { + try { prod.send(m); count++; - if (count == numMessages) - { + if (count == numMessages) { notify(); } } - catch (JMSException e) - { + catch (JMSException e) { failed = true; } } - synchronized void waitForMessages() throws Exception - { - while (count < numMessages) - { + synchronized void waitForMessages() throws Exception { + while (count < numMessages) { this.wait(); } } @@ -166,8 +151,7 @@ public class MessageConsumerTest extends JMSTestCase MessageProducer prod2 = sess2.createProducer(queue1); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { prod2.send(sess2.createMessage()); } @@ -177,10 +161,8 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertFalse(listener.failed); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } @@ -200,12 +182,10 @@ public class MessageConsumerTest extends JMSTestCase * cancelled but we need to prompt deliver() so the reconnected client gets it */ @Test - public void testRedeliveryToCompetingConsumerOnQueue() throws Exception - { + public void testRedeliveryToCompetingConsumerOnQueue() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session sessSend = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -249,10 +229,8 @@ public class MessageConsumerTest extends JMSTestCase tm3.acknowledge(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -262,14 +240,12 @@ public class MessageConsumerTest extends JMSTestCase * The simplest possible receive() test for a non-persistent message. */ @Test - public void testReceive() throws Exception - { + public void testReceive() throws Exception { Connection producerConnection = null; Connection consumerConnection = null; - try - { + try { producerConnection = createConnection(); consumerConnection = createConnection(); @@ -295,14 +271,11 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertEquals(tm.getText(), m.getText()); } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } - if (consumerConnection != null) - { + if (consumerConnection != null) { consumerConnection.close(); } } @@ -310,14 +283,12 @@ public class MessageConsumerTest extends JMSTestCase } @Test - public void testReceivePersistent() throws Exception - { + public void testReceivePersistent() throws Exception { Connection producerConnection = null; Connection consumerConnection = null; - try - { + try { producerConnection = createConnection(); consumerConnection = createConnection(); @@ -343,14 +314,11 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertEquals(tm.getText(), m.getText()); } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } - if (consumerConnection != null) - { + if (consumerConnection != null) { consumerConnection.close(); } } @@ -360,14 +328,12 @@ public class MessageConsumerTest extends JMSTestCase * The simplest possible receive(timeout) test. */ @Test - public void testReceiveTimeout() throws Exception - { + public void testReceiveTimeout() throws Exception { Connection producerConnection = null; Connection consumerConnection = null; - try - { + try { producerConnection = createConnection(); consumerConnection = createConnection(); @@ -391,14 +357,11 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertEquals(tm.getText(), m.getText()); } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } - if (consumerConnection != null) - { + if (consumerConnection != null) { consumerConnection.close(); } } @@ -408,14 +371,12 @@ public class MessageConsumerTest extends JMSTestCase * The simplest possible receiveNoWait() test. */ @Test - public void testReceiveNoWait() throws Exception - { + public void testReceiveNoWait() throws Exception { Connection producerConnection = null; Connection consumerConnection = null; - try - { + try { producerConnection = createConnection(); consumerConnection = createConnection(); @@ -448,14 +409,11 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertEquals(tm.getText(), m.getText()); } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } - if (consumerConnection != null) - { + if (consumerConnection != null) { consumerConnection.close(); } } @@ -465,14 +423,12 @@ public class MessageConsumerTest extends JMSTestCase * The simplest possible message listener test. */ @Test - public void testReceiveOnListener() throws Exception - { + public void testReceiveOnListener() throws Exception { Connection producerConnection = null; Connection consumerConnection = null; - try - { + try { producerConnection = createConnection(); consumerConnection = createConnection(); @@ -503,14 +459,11 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertEquals(tm.getText(), m.getText()); } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } - if (consumerConnection != null) - { + if (consumerConnection != null) { consumerConnection.close(); } } @@ -521,72 +474,56 @@ public class MessageConsumerTest extends JMSTestCase // @Test - public void testCreateConsumerOnNonExistentTopic() throws Exception - { + public void testCreateConsumerOnNonExistentTopic() throws Exception { Connection pconn = null; - try - { + try { pconn = createConnection(); Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); - try - { - ps.createConsumer(new Topic() - { - public String getTopicName() throws JMSException - { + try { + ps.createConsumer(new Topic() { + public String getTopicName() throws JMSException { return "NoSuchTopic"; } }); ProxyAssertSupport.fail("should throw exception"); } - catch (InvalidDestinationException e) - { + catch (InvalidDestinationException e) { // OK } } - finally - { - if (pconn != null) - { + finally { + if (pconn != null) { pconn.close(); } } } @Test - public void testCreateConsumerOnNonExistentQueue() throws Exception - { + public void testCreateConsumerOnNonExistentQueue() throws Exception { Connection pconn = null; - try - { + try { pconn = createConnection(); Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); - try - { - ps.createConsumer(new Queue() - { - public String getQueueName() throws JMSException - { + try { + ps.createConsumer(new Queue() { + public String getQueueName() throws JMSException { return "NoSuchQueue"; } }); ProxyAssertSupport.fail("should throw exception"); } - catch (InvalidDestinationException e) - { + catch (InvalidDestinationException e) { // OK } } - finally - { - if (pconn != null) - { + finally { + if (pconn != null) { pconn.close(); } } @@ -601,13 +538,11 @@ public class MessageConsumerTest extends JMSTestCase */ @Test - public void testAckAfterConsumerClosed() throws Exception - { + public void testAckAfterConsumerClosed() throws Exception { Connection connSend = null; Connection connReceive = null; - try - { + try { connSend = createConnection(); connSend.start(); @@ -649,28 +584,23 @@ public class MessageConsumerTest extends JMSTestCase log.trace("Done test"); } - finally - { - if (connSend != null) - { + finally { + if (connSend != null) { connSend.close(); } - if (connReceive != null) - { + if (connReceive != null) { connReceive.close(); } } } @Test - public void testClientAcknowledgmentOnClosedConsumer() throws Exception - { + public void testClientAcknowledgmentOnClosedConsumer() throws Exception { Connection producerConnection = null; Connection consumerConnection = null; - try - { + try { producerConnection = createConnection(); consumerConnection = createConnection(); @@ -699,38 +629,31 @@ public class MessageConsumerTest extends JMSTestCase m.acknowledge(); - try - { + try { queueConsumer.receive(2000); ProxyAssertSupport.fail("should throw exception"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } - if (consumerConnection != null) - { + if (consumerConnection != null) { consumerConnection.close(); } } } @Test - public void testSendMessageAndCloseConsumer1() throws Exception - { + public void testSendMessageAndCloseConsumer1() throws Exception { Connection producerConnection = null; Connection consumerConnection = null; - try - { + try { producerConnection = createConnection(); consumerConnection = createConnection(); @@ -759,14 +682,11 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertEquals(m.getJMSMessageID(), r.getJMSMessageID()); } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } - if (consumerConnection != null) - { + if (consumerConnection != null) { consumerConnection.close(); } } @@ -779,14 +699,12 @@ public class MessageConsumerTest extends JMSTestCase * way of checking the messages are back in the queue. */ @Test - public void testSendMessageAndCloseConsumer2() throws Exception - { + public void testSendMessageAndCloseConsumer2() throws Exception { Connection producerConnection = null; Connection consumerConnection = null; - try - { + try { producerConnection = createConnection(); consumerConnection = createConnection(); @@ -831,26 +749,21 @@ public class MessageConsumerTest extends JMSTestCase consumerSession.commit(); } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } - if (consumerConnection != null) - { + if (consumerConnection != null) { consumerConnection.close(); } } } @Test - public void testRedel0() throws Exception - { + public void testRedel0() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); conn.start(); @@ -886,10 +799,8 @@ public class MessageConsumerTest extends JMSTestCase sess.commit(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } @@ -900,12 +811,10 @@ public class MessageConsumerTest extends JMSTestCase } @Test - public void testRedel1() throws Exception - { + public void testRedel1() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); conn.start(); @@ -941,10 +850,8 @@ public class MessageConsumerTest extends JMSTestCase sess.commit(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } @@ -955,12 +862,10 @@ public class MessageConsumerTest extends JMSTestCase } @Test - public void testRedel2() throws Exception - { + public void testRedel2() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); conn.start(); @@ -996,10 +901,8 @@ public class MessageConsumerTest extends JMSTestCase sess.commit(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } @@ -1010,12 +913,10 @@ public class MessageConsumerTest extends JMSTestCase } @Test - public void testRedel3() throws Exception - { + public void testRedel3() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); conn.start(); @@ -1054,10 +955,8 @@ public class MessageConsumerTest extends JMSTestCase sess.commit(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } @@ -1069,12 +968,10 @@ public class MessageConsumerTest extends JMSTestCase } @Test - public void testRedel4() throws Exception - { + public void testRedel4() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); conn.start(); @@ -1118,10 +1015,8 @@ public class MessageConsumerTest extends JMSTestCase sess.commit(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } @@ -1133,12 +1028,10 @@ public class MessageConsumerTest extends JMSTestCase } @Test - public void testRedel5() throws Exception - { + public void testRedel5() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); conn.start(); @@ -1174,10 +1067,8 @@ public class MessageConsumerTest extends JMSTestCase rm4.acknowledge(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } @@ -1189,12 +1080,10 @@ public class MessageConsumerTest extends JMSTestCase } @Test - public void testRedel6() throws Exception - { + public void testRedel6() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); conn.start(); @@ -1238,10 +1127,8 @@ public class MessageConsumerTest extends JMSTestCase rm4.acknowledge(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } @@ -1256,12 +1143,10 @@ public class MessageConsumerTest extends JMSTestCase * http://www.jboss.org/index.html?module=bb&op=viewtopic&t=71350 */ @Test - public void testRedel7() throws Exception - { + public void testRedel7() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); conn.start(); @@ -1301,10 +1186,8 @@ public class MessageConsumerTest extends JMSTestCase r2.acknowledge(); r3.acknowledge(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } removeAllMessages(queue1.getQueueName(), true); @@ -1315,12 +1198,10 @@ public class MessageConsumerTest extends JMSTestCase * http://www.jboss.org/index.html?module=bb&op=viewtopic&t=71350 */ @Test - public void testRedel8() throws Exception - { + public void testRedel8() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -1350,23 +1231,19 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertNotNull(r2); ProxyAssertSupport.assertNotNull(r3); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testSendAndReceivePersistentDifferentConnections() throws Exception - { + public void testSendAndReceivePersistentDifferentConnections() throws Exception { Connection connSend = null; Connection connReceive = null; - try - { + try { connSend = createConnection(); connSend.start(); @@ -1411,14 +1288,11 @@ public class MessageConsumerTest extends JMSTestCase cons = sessReceive.createConsumer(queue1); } - finally - { - if (connSend != null) - { + finally { + if (connSend != null) { connSend.close(); } - if (connReceive != null) - { + if (connReceive != null) { connReceive.close(); } @@ -1427,14 +1301,12 @@ public class MessageConsumerTest extends JMSTestCase } @Test - public void testMultipleConcurrentConsumers() throws Exception - { + public void testMultipleConcurrentConsumers() throws Exception { Connection producerConnection = null; Connection consumerConnection = null; - try - { + try { producerConnection = createConnection(); consumerConnection = createConnection(); @@ -1450,10 +1322,9 @@ public class MessageConsumerTest extends JMSTestCase final int NUM_MESSAGES = 10; - class Receiver implements Runnable - { - Receiver(final MessageConsumer c1) - { + class Receiver implements Runnable { + + Receiver(final MessageConsumer c1) { cons = c1; } @@ -1461,28 +1332,22 @@ public class MessageConsumerTest extends JMSTestCase boolean failed; - public void run() - { - try - { - for (int i = 0; i < NUM_MESSAGES; i++) - { + public void run() { + try { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage m = (TextMessage) cons.receive(5000); - if (m == null) - { + if (m == null) { log.error("Didn't receive all the messages"); failed = true; break; } - if (!m.getText().equals("testing")) - { + if (!m.getText().equals("testing")) { failed = true; } } } - catch (Exception e) - { + catch (Exception e) { log.error("Failed in receiving messages", e); failed = true; } @@ -1510,8 +1375,7 @@ public class MessageConsumerTest extends JMSTestCase MessageProducer prod = prodSession.createProducer(ActiveMQServerTestCase.topic1); prod.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = prodSession.createTextMessage("testing"); prod.send(m); log.trace("Sent message to topic"); @@ -1530,26 +1394,21 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertTrue(!rec2.failed); ProxyAssertSupport.assertTrue(!rec3.failed); } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } - if (consumerConnection != null) - { + if (consumerConnection != null) { consumerConnection.close(); } } } @Test - public void testGetSelector() throws Exception - { + public void testGetSelector() throws Exception { Connection consumerConnection = null; - try - { + try { consumerConnection = createConnection(); Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -1560,22 +1419,18 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertEquals(selector, topicConsumer.getMessageSelector()); } - finally - { - if (consumerConnection != null) - { + finally { + if (consumerConnection != null) { consumerConnection.close(); } } } @Test - public void testGetSelectorOnClosedConsumer() throws Exception - { + public void testGetSelectorOnClosedConsumer() throws Exception { Connection consumerConnection = null; - try - { + try { consumerConnection = createConnection(); Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -1584,32 +1439,26 @@ public class MessageConsumerTest extends JMSTestCase topicConsumer.close(); - try - { + try { topicConsumer.getMessageSelector(); Assert.fail("must throw a JMS IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } } - finally - { - if (consumerConnection != null) - { + finally { + if (consumerConnection != null) { consumerConnection.close(); } } } @Test - public void testGetNoLocalOnClosedConsumer() throws Exception - { + public void testGetNoLocalOnClosedConsumer() throws Exception { Connection consumerConnection = null; - try - { + try { consumerConnection = createConnection(); TopicConnection tc = (TopicConnection) consumerConnection; @@ -1619,32 +1468,26 @@ public class MessageConsumerTest extends JMSTestCase topicConsumer.close(); - try - { + try { topicConsumer.getNoLocal(); Assert.fail("must throw a JMS IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } } - finally - { - if (consumerConnection != null) - { + finally { + if (consumerConnection != null) { consumerConnection.close(); } } } @Test - public void testGetTopic() throws Exception - { + public void testGetTopic() throws Exception { Connection consumerConnection = null; - try - { + try { consumerConnection = createConnection(); Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -1655,22 +1498,18 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertEquals(ActiveMQServerTestCase.topic1, t); } - finally - { - if (consumerConnection != null) - { + finally { + if (consumerConnection != null) { consumerConnection.close(); } } } @Test - public void testGetTopicOnClosedConsumer() throws Exception - { + public void testGetTopicOnClosedConsumer() throws Exception { Connection consumerConnection = null; - try - { + try { consumerConnection = createConnection(); Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -1679,32 +1518,26 @@ public class MessageConsumerTest extends JMSTestCase topicConsumer.close(); - try - { + try { ((TopicSubscriber) topicConsumer).getTopic(); Assert.fail("must throw a JMS IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } } - finally - { - if (consumerConnection != null) - { + finally { + if (consumerConnection != null) { consumerConnection.close(); } } } @Test - public void testGetQueue() throws Exception - { + public void testGetQueue() throws Exception { Connection consumerConnection = null; - try - { + try { consumerConnection = createConnection(); Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -1715,22 +1548,18 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertEquals(queue1, q); } - finally - { - if (consumerConnection != null) - { + finally { + if (consumerConnection != null) { consumerConnection.close(); } } } @Test - public void testGetQueueOnClosedConsumer() throws Exception - { + public void testGetQueueOnClosedConsumer() throws Exception { Connection consumerConnection = null; - try - { + try { consumerConnection = createConnection(); Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -1739,32 +1568,26 @@ public class MessageConsumerTest extends JMSTestCase queueConsumer.close(); - try - { + try { ((QueueReceiver) queueConsumer).getQueue(); Assert.fail("must throw a JMS IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } } - finally - { - if (consumerConnection != null) - { + finally { + if (consumerConnection != null) { consumerConnection.close(); } } } @Test - public void testReceiveOnTopicTimeoutNoMessage() throws Exception - { + public void testReceiveOnTopicTimeoutNoMessage() throws Exception { Connection consumerConnection = null; - try - { + try { consumerConnection = createConnection(); Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -1775,24 +1598,20 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertNull(m); } - finally - { - if (consumerConnection != null) - { + finally { + if (consumerConnection != null) { consumerConnection.close(); } } } @Test - public void testReceiveOnTopicConnectionStopped() throws Exception - { + public void testReceiveOnTopicConnectionStopped() throws Exception { Connection producerConnection = null; Connection consumerConnection = null; - try - { + try { producerConnection = createConnection(); consumerConnection = createConnection(); @@ -1806,18 +1625,14 @@ public class MessageConsumerTest extends JMSTestCase MessageConsumer topicConsumer = consumerSession.createConsumer(ActiveMQServerTestCase.topic1); final Message m = producerSession.createMessage(); - new Thread(new Runnable() - { - public void run() - { - try - { + new Thread(new Runnable() { + public void run() { + try { // this is needed to make sure the main thread has enough time to block Thread.sleep(1000); topicProducer.send(m); } - catch (Exception e) - { + catch (Exception e) { log.error(e); } } @@ -1825,28 +1640,23 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertNull(topicConsumer.receive(1500)); } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } - if (consumerConnection != null) - { + if (consumerConnection != null) { consumerConnection.close(); } } } @Test - public void testReceiveOnTopicTimeout() throws Exception - { + public void testReceiveOnTopicTimeout() throws Exception { Connection producerConnection = null; Connection consumerConnection = null; - try - { + try { producerConnection = createConnection(); consumerConnection = createConnection(); @@ -1862,18 +1672,14 @@ public class MessageConsumerTest extends JMSTestCase consumerConnection.start(); final Message m1 = producerSession.createMessage(); - new Thread(new Runnable() - { - public void run() - { - try - { + new Thread(new Runnable() { + public void run() { + try { // this is needed to make sure the main thread has enough time to block Thread.sleep(1000); topicProducer.send(m1); } - catch (Exception e) - { + catch (Exception e) { log.error(e); } } @@ -1882,28 +1688,23 @@ public class MessageConsumerTest extends JMSTestCase Message m2 = topicConsumer.receive(1500); ProxyAssertSupport.assertEquals(m1.getJMSMessageID(), m2.getJMSMessageID()); } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } - if (consumerConnection != null) - { + if (consumerConnection != null) { consumerConnection.close(); } } } @Test - public void testReceiveOnTopic() throws Exception - { + public void testReceiveOnTopic() throws Exception { Connection producerConnection = null; Connection consumerConnection = null; - try - { + try { producerConnection = createConnection(); consumerConnection = createConnection(); @@ -1919,18 +1720,14 @@ public class MessageConsumerTest extends JMSTestCase consumerConnection.start(); final Message m1 = producerSession.createMessage(); - new Thread(new Runnable() - { - public void run() - { - try - { + new Thread(new Runnable() { + public void run() { + try { // this is needed to make sure the main thread has enough time to block Thread.sleep(1000); topicProducer.send(m1); } - catch (Exception e) - { + catch (Exception e) { log.error(e); } } @@ -1940,28 +1737,23 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertEquals(m1.getJMSMessageID(), m2.getJMSMessageID()); } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } - if (consumerConnection != null) - { + if (consumerConnection != null) { consumerConnection.close(); } } } @Test - public void testReceiveNoWaitOnTopic() throws Exception - { + public void testReceiveNoWaitOnTopic() throws Exception { Connection producerConnection = null; Connection consumerConnection = null; - try - { + try { producerConnection = createConnection(); consumerConnection = createConnection(); @@ -1990,14 +1782,11 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertEquals(m1.getJMSMessageID(), m.getJMSMessageID()); } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } - if (consumerConnection != null) - { + if (consumerConnection != null) { consumerConnection.close(); } } @@ -2007,14 +1796,12 @@ public class MessageConsumerTest extends JMSTestCase * The test sends a burst of messages and verifies if the consumer receives all of them. */ @Test - public void testStressReceiveOnQueue() throws Exception - { + public void testStressReceiveOnQueue() throws Exception { Connection producerConnection = null; Connection consumerConnection = null; - try - { + try { producerConnection = createConnection(); consumerConnection = createConnection(); @@ -2031,39 +1818,30 @@ public class MessageConsumerTest extends JMSTestCase consumerConnection.start(); - new Thread(new Runnable() - { - public void run() - { - try - { - for (int i = 0; i < count; i++) - { + new Thread(new Runnable() { + public void run() { + try { + for (int i = 0; i < count; i++) { Message m = producerSession.createMessage(); queueProducer.send(m); } } - catch (Exception e) - { + catch (Exception e) { log.error(e); } } }, "ProducerTestThread").start(); - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { Message m = queueConsumer.receive(1500); ProxyAssertSupport.assertNotNull(m); } } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } - if (consumerConnection != null) - { + if (consumerConnection != null) { consumerConnection.close(); } @@ -2075,14 +1853,12 @@ public class MessageConsumerTest extends JMSTestCase * The test sends a burst of messages and verifies if the consumer receives all of them. */ @Test - public void testStressReceiveOnTopic() throws Exception - { + public void testStressReceiveOnTopic() throws Exception { Connection producerConnection = null; Connection consumerConnection = null; - try - { + try { producerConnection = createConnection(); consumerConnection = createConnection(); @@ -2099,56 +1875,45 @@ public class MessageConsumerTest extends JMSTestCase consumerConnection.start(); - new Thread(new Runnable() - { - public void run() - { - try - { + new Thread(new Runnable() { + public void run() { + try { // this is needed to make sure the main thread has enough time to block Thread.sleep(1000); - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { Message m = producerSession.createMessage(); topicProducer.send(m); } } - catch (Exception e) - { + catch (Exception e) { log.error(e); } } }, "ProducerTestThread").start(); - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { Message m = topicConsumer.receive(10000); ProxyAssertSupport.assertNotNull(m); } checkEmpty(ActiveMQServerTestCase.topic1); } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } - if (consumerConnection != null) - { + if (consumerConnection != null) { consumerConnection.close(); } } } @Test - public void testReceiveOnClose() throws Exception - { + public void testReceiveOnClose() throws Exception { Connection consumerConnection = null; - try - { + try { consumerConnection = createConnection(); Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -2157,22 +1922,17 @@ public class MessageConsumerTest extends JMSTestCase consumerConnection.start(); final CountDownLatch latch = new CountDownLatch(1); - Thread closerThread = new Thread(new Runnable() - { - public void run() - { - try - { + Thread closerThread = new Thread(new Runnable() { + public void run() { + try { // this is needed to make sure the main thread has enough time to block Thread.sleep(1000); topicConsumer.close(); } - catch (Exception e) - { + catch (Exception e) { log.error(e); } - finally - { + finally { latch.countDown(); } } @@ -2186,10 +1946,8 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertTrue(closed); } - finally - { - if (consumerConnection != null) - { + finally { + if (consumerConnection != null) { consumerConnection.close(); } } @@ -2198,8 +1956,7 @@ public class MessageConsumerTest extends JMSTestCase /** * to be used by testTimeoutReceiveOnClose */ - private class ThreadCloser extends Thread - { + private class ThreadCloser extends Thread { final Object waitMonitor; @@ -2209,8 +1966,10 @@ public class MessageConsumerTest extends JMSTestCase final AtomicBoolean running; - public ThreadCloser(final AtomicBoolean running, final Object waitMonitor, final long timeToSleep, final MessageConsumer topicConsumer) - { + public ThreadCloser(final AtomicBoolean running, + final Object waitMonitor, + final long timeToSleep, + final MessageConsumer topicConsumer) { this.running = running; this.waitMonitor = waitMonitor; this.timeToSleep = timeToSleep; @@ -2218,14 +1977,10 @@ public class MessageConsumerTest extends JMSTestCase } @Override - public void run() - { - try - { - synchronized (waitMonitor) - { - while (running.get()) - { + public void run() { + try { + synchronized (waitMonitor) { + while (running.get()) { waitMonitor.wait(); } } @@ -2233,8 +1988,7 @@ public class MessageConsumerTest extends JMSTestCase Thread.sleep(timeToSleep); topicConsumer.close(); } - catch (Exception e) - { + catch (Exception e) { log.error(e); e.printStackTrace(); } @@ -2244,8 +1998,7 @@ public class MessageConsumerTest extends JMSTestCase /** * to be used by testTimeoutReceiveOnClose */ - private class ThreadReceiver extends Thread - { + private class ThreadReceiver extends Thread { long timeToWait; @@ -2261,8 +2014,10 @@ public class MessageConsumerTest extends JMSTestCase final AtomicBoolean running; - public ThreadReceiver(final AtomicBoolean running, final Object waitMonitor, final long timeToWait, final MessageConsumer topicConsumer) - { + public ThreadReceiver(final AtomicBoolean running, + final Object waitMonitor, + final long timeToWait, + final MessageConsumer topicConsumer) { this.running = running; this.waitMonitor = waitMonitor; this.timeToWait = timeToWait; @@ -2270,14 +2025,10 @@ public class MessageConsumerTest extends JMSTestCase } @Override - public void run() - { - try - { - synchronized (waitMonitor) - { - while (running.get()) - { + public void run() { + try { + synchronized (waitMonitor) { + while (running.get()) { waitMonitor.wait(); } } @@ -2286,8 +2037,7 @@ public class MessageConsumerTest extends JMSTestCase t2 = System.currentTimeMillis(); } - catch (Exception e) - { + catch (Exception e) { log.error(e); e.printStackTrace(); } @@ -2295,12 +2045,10 @@ public class MessageConsumerTest extends JMSTestCase } @Test - public void testTimeoutReceiveOnClose() throws Exception - { + public void testTimeoutReceiveOnClose() throws Exception { Connection consumerConnection = null; - try - { + try { consumerConnection = createConnection(); Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -2310,8 +2058,7 @@ public class MessageConsumerTest extends JMSTestCase // This is a really weird test - the received object is always going to be null since no message is sent!! ActiveMQServerTestCase.forceGC(); // / If A GC need to be executed, it' s better to be executed now - if (log.isTraceEnabled()) - { + if (log.isTraceEnabled()) { log.trace("testTimeoutReceiveOnClose"); } @@ -2326,8 +2073,7 @@ public class MessageConsumerTest extends JMSTestCase closer.start(); receiver.start(); Thread.sleep(2000); - synchronized (monitor) - { + synchronized (monitor) { running.set(false); monitor.notifyAll(); } @@ -2337,13 +2083,10 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertNull(receiver.receivedObject); // We need to make sure the - ProxyAssertSupport.assertTrue("Receive was supposed to receive a notification before 2 seconds", - receiver.t2 - receiver.t1 <= 1500); + ProxyAssertSupport.assertTrue("Receive was supposed to receive a notification before 2 seconds", receiver.t2 - receiver.t1 <= 1500); } - finally - { - if (consumerConnection != null) - { + finally { + if (consumerConnection != null) { consumerConnection.close(); } } @@ -2354,14 +2097,12 @@ public class MessageConsumerTest extends JMSTestCase // @Test - public void testMessageListenerOnTopic() throws Exception - { + public void testMessageListenerOnTopic() throws Exception { Connection producerConnection = null; Connection consumerConnection = null; - try - { + try { producerConnection = createConnection(); consumerConnection = createConnection(); @@ -2388,28 +2129,23 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertEquals(m1.getJMSMessageID(), l.getNextMessage().getJMSMessageID()); } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } - if (consumerConnection != null) - { + if (consumerConnection != null) { consumerConnection.close(); } } } @Test - public void testMessageListenerOnTopicMultipleMessages() throws Exception - { + public void testMessageListenerOnTopicMultipleMessages() throws Exception { Connection producerConnection = null; Connection consumerConnection = null; - try - { + try { producerConnection = createConnection(); consumerConnection = createConnection(); @@ -2431,8 +2167,7 @@ public class MessageConsumerTest extends JMSTestCase consumerConnection.start(); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage m = producerSession.createTextMessage("body" + i); topicProducer.send(m); } @@ -2440,8 +2175,7 @@ public class MessageConsumerTest extends JMSTestCase l.waitForMessages(); int counter = 0; - for (Iterator i = l.getMessages().iterator(); i.hasNext(); counter++) - { + for (Iterator i = l.getMessages().iterator(); i.hasNext(); counter++) { TextMessage m = (TextMessage) i.next(); ProxyAssertSupport.assertEquals("body" + counter, m.getText()); } @@ -2449,29 +2183,24 @@ public class MessageConsumerTest extends JMSTestCase log.debug("testMessageListenerOnTopicMultipleMessages done"); } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } - if (consumerConnection != null) - { + if (consumerConnection != null) { consumerConnection.close(); } } } @Test - public void testMessageListenerOnQueueMultipleMessages() throws Exception - { + public void testMessageListenerOnQueueMultipleMessages() throws Exception { Connection producerConnection = null; Connection consumerConnection = null; - try - { + try { producerConnection = createConnection(); consumerConnection = createConnection(); @@ -2492,8 +2221,7 @@ public class MessageConsumerTest extends JMSTestCase consumerConnection.start(); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage m = producerSession.createTextMessage("body" + i); queueProducer.send(m); } @@ -2501,8 +2229,7 @@ public class MessageConsumerTest extends JMSTestCase l.waitForMessages(); int counter = 0; - for (Iterator i = l.getMessages().iterator(); i.hasNext(); counter++) - { + for (Iterator i = l.getMessages().iterator(); i.hasNext(); counter++) { TextMessage m = (TextMessage) i.next(); ProxyAssertSupport.assertEquals("body" + counter, m.getText()); } @@ -2510,28 +2237,23 @@ public class MessageConsumerTest extends JMSTestCase log.debug("testMessageListenerOnTopicMultipleMessages done"); } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } - if (consumerConnection != null) - { + if (consumerConnection != null) { consumerConnection.close(); } } } @Test - public void testSetMessageListenerTwice() throws Exception - { + public void testSetMessageListenerTwice() throws Exception { Connection producerConnection = null; Connection consumerConnection = null; - try - { + try { producerConnection = createConnection(); consumerConnection = createConnection(); @@ -2565,26 +2287,21 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertEquals(m1.getJMSMessageID(), listener2.getNextMessage().getJMSMessageID()); ProxyAssertSupport.assertEquals(0, listener1.size()); } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } - if (consumerConnection != null) - { + if (consumerConnection != null) { consumerConnection.close(); } } } @Test - public void testSetMessageListenerWhileReceiving() throws Exception - { + public void testSetMessageListenerWhileReceiving() throws Exception { Connection consumerConnection = null; - try - { + try { consumerConnection = createConnection(); Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -2592,16 +2309,12 @@ public class MessageConsumerTest extends JMSTestCase final MessageConsumer topicConsumer = consumerSession.createConsumer(ActiveMQServerTestCase.topic1); consumerConnection.start(); - Thread worker1 = new Thread(new Runnable() - { - public void run() - { - try - { + Thread worker1 = new Thread(new Runnable() { + public void run() { + try { topicConsumer.receive(3000); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -2611,21 +2324,17 @@ public class MessageConsumerTest extends JMSTestCase Thread.sleep(1000); - try - { + try { topicConsumer.setMessageListener(new MessageListenerImpl()); ProxyAssertSupport.fail("should have thrown JMSException"); } - catch (JMSException e) - { + catch (JMSException e) { // ok log.trace(e.getMessage()); } } - finally - { - if (consumerConnection != null) - { + finally { + if (consumerConnection != null) { consumerConnection.close(); } } @@ -2633,26 +2342,20 @@ public class MessageConsumerTest extends JMSTestCase // This is commented out until http:// jira.jboss.com/jira/browse/JBMESSAGING-983 is complete @Test - public void testStopConnectionDuringOnMessage() throws Exception - { - if (log.isTraceEnabled()) - { + public void testStopConnectionDuringOnMessage() throws Exception { + if (log.isTraceEnabled()) { log.trace("testStopConnectionWhileOnMessageIsExecuting"); } final AtomicInteger messagesReceived = new AtomicInteger(0); - MessageListener myListener = new MessageListener() - { - public void onMessage(final Message message) - { + MessageListener myListener = new MessageListener() { + public void onMessage(final Message message) { messagesReceived.incrementAndGet(); - try - { + try { Thread.sleep(100L); } - catch (InterruptedException e) - { + catch (InterruptedException e) { // Ignore } } @@ -2662,8 +2365,7 @@ public class MessageConsumerTest extends JMSTestCase Connection consumerConnection = null; - try - { + try { producerConnection = createConnection(); consumerConnection = createConnection(); @@ -2685,8 +2387,7 @@ public class MessageConsumerTest extends JMSTestCase log.trace("Sending the first batch of messages"); - for (int i = 0; i < MESSAGE_COUNT / 2; i++) - { + for (int i = 0; i < MESSAGE_COUNT / 2; i++) { queueProducer.send(producerSession.createTextMessage("Message #" + Integer.toString(i))); } @@ -2699,35 +2400,27 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertTrue("Should have received some messages before stopping", countAfterStop > 0); log.trace("Sending the second batch of messages"); - for (int i = MESSAGE_COUNT / 2; i < MESSAGE_COUNT; i++) - { + for (int i = MESSAGE_COUNT / 2; i < MESSAGE_COUNT; i++) { queueProducer.send(producerSession.createTextMessage("Message #" + Integer.toString(i))); } log.trace("Sleeping a bit to check that no messages are received"); Thread.sleep(2000); - ProxyAssertSupport.assertEquals("Should not receive any messages after the connection has been stopped", - countAfterStop, - messagesReceived.get()); + ProxyAssertSupport.assertEquals("Should not receive any messages after the connection has been stopped", countAfterStop, messagesReceived.get()); log.trace("Restarting consumer connection"); consumerConnection.start(); log.trace("Sleeping to allow remaining messages to arrive"); Thread.sleep(15000); - ProxyAssertSupport.assertEquals("Should have received all messages after restarting", - MESSAGE_COUNT, - messagesReceived.get()); + ProxyAssertSupport.assertEquals("Should have received all messages after restarting", MESSAGE_COUNT, messagesReceived.get()); } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } - if (consumerConnection != null) - { + if (consumerConnection != null) { consumerConnection.close(); } removeAllMessages(queue1.getQueueName(), true); @@ -2737,14 +2430,12 @@ public class MessageConsumerTest extends JMSTestCase // Test that stop doesn't in any way break subsequent close @Test - public void testCloseAfterStop() throws Exception - { + public void testCloseAfterStop() throws Exception { Connection producerConnection = null; Connection consumerConnection = null; - try - { + try { producerConnection = createConnection(); consumerConnection = createConnection(); @@ -2757,16 +2448,12 @@ public class MessageConsumerTest extends JMSTestCase MessageConsumer queueConsumer = consumerSession.createConsumer(queue1); - MessageListener myListener = new MessageListener() - { - public void onMessage(final Message message) - { - try - { + MessageListener myListener = new MessageListener() { + public void onMessage(final Message message) { + try { Thread.sleep(1); } - catch (InterruptedException e) - { + catch (InterruptedException e) { // Ignore } } @@ -2776,8 +2463,7 @@ public class MessageConsumerTest extends JMSTestCase consumerConnection.start(); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { queueProducer.send(producerSession.createTextMessage("Message #" + Integer.toString(i))); } @@ -2787,14 +2473,11 @@ public class MessageConsumerTest extends JMSTestCase consumerConnection = null; } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } - if (consumerConnection != null) - { + if (consumerConnection != null) { consumerConnection.close(); } removeAllMessages(queue1.getQueueName(), true); @@ -2806,14 +2489,12 @@ public class MessageConsumerTest extends JMSTestCase // @Test - public void testTwoConsumersNonTransacted() throws Exception - { + public void testTwoConsumersNonTransacted() throws Exception { Connection producerConnection = null; Connection consumerConnection = null; - try - { + try { producerConnection = createConnection(); Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -2847,28 +2528,23 @@ public class MessageConsumerTest extends JMSTestCase m = (TextMessage) queueConsumer.receive(1500); ProxyAssertSupport.assertEquals("Two", m.getText()); } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } - if (consumerConnection != null) - { + if (consumerConnection != null) { consumerConnection.close(); } } } @Test - public void testTwoConsumersTransacted() throws Exception - { + public void testTwoConsumersTransacted() throws Exception { Connection producerConnection = null; Connection consumerConnection = null; - try - { + try { producerConnection = createConnection(); Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -2903,14 +2579,11 @@ public class MessageConsumerTest extends JMSTestCase m = (TextMessage) queueConsumer.receive(1500); ProxyAssertSupport.assertEquals("Two", m.getText()); } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } - if (consumerConnection != null) - { + if (consumerConnection != null) { consumerConnection.close(); } removeAllMessages(queue1.getQueueName(), true); @@ -2922,18 +2595,15 @@ public class MessageConsumerTest extends JMSTestCase // @Test - public void testNoLocal() throws Exception - { - if (log.isTraceEnabled()) - { + public void testNoLocal() throws Exception { + if (log.isTraceEnabled()) { log.trace("testNoLocal"); } Connection conn1 = null; Connection conn2 = null; - try - { + try { conn1 = createConnection(); Session sess1 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -2958,27 +2628,23 @@ public class MessageConsumerTest extends JMSTestCase conn1.start(); conn2.start(); - class TestRunnable implements Runnable - { + class TestRunnable implements Runnable { + boolean exceptionThrown; public Message m; MessageConsumer consumer; - TestRunnable(final MessageConsumer consumer) - { + TestRunnable(final MessageConsumer consumer) { this.consumer = consumer; } - public void run() - { - try - { + public void run() { + try { m = consumer.receive(1500); } - catch (Exception e) - { + catch (Exception e) { exceptionThrown = true; } } @@ -3011,26 +2677,21 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertNotNull(tr2.m); ProxyAssertSupport.assertNotNull(tr3.m); } - finally - { - if (conn1 != null) - { + finally { + if (conn1 != null) { conn1.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } } @Test - public void testNoLocalMemoryExhaustion() throws Exception - { + public void testNoLocalMemoryExhaustion() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -3041,8 +2702,7 @@ public class MessageConsumerTest extends JMSTestCase final int numMessages = 100; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { prod.send(sess.createMessage()); } @@ -3054,10 +2714,8 @@ public class MessageConsumerTest extends JMSTestCase checkEmpty(ActiveMQServerTestCase.topic1); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -3068,12 +2726,10 @@ public class MessageConsumerTest extends JMSTestCase * Also see JMS 1.1 Spec. 6.12 */ @Test - public void testTopicRedelivery() throws Exception - { + public void testTopicRedelivery() throws Exception { Connection conn1 = null; - try - { + try { conn1 = createConnection(); conn1.start(); @@ -3119,10 +2775,8 @@ public class MessageConsumerTest extends JMSTestCase tm1 = (TextMessage) cons1.receive(1500); ProxyAssertSupport.assertNull(tm1); } - finally - { - if (conn1 != null) - { + finally { + if (conn1 != null) { log.trace("closing connection"); conn1.close(); } @@ -3135,13 +2789,11 @@ public class MessageConsumerTest extends JMSTestCase * See JMS spec. sec. 6.12 */ @Test - public void testNoRedeliveryOnNonDurableSubscriber() throws Exception - { + public void testNoRedeliveryOnNonDurableSubscriber() throws Exception { Connection conn1 = null; Connection conn2 = null; - try - { + try { conn1 = createConnection(); conn1.start(); @@ -3154,8 +2806,7 @@ public class MessageConsumerTest extends JMSTestCase MessageConsumer cons = sess1.createConsumer(ActiveMQServerTestCase.topic1); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = sess1.createTextMessage("helloxyz"); prod.send(ActiveMQServerTestCase.topic1, tm); } @@ -3163,11 +2814,9 @@ public class MessageConsumerTest extends JMSTestCase // receive but don't ack int count = 0; - while (true) - { + while (true) { TextMessage tm = (TextMessage) cons.receive(1000); - if (tm == null) - { + if (tm == null) { break; } ProxyAssertSupport.assertEquals(tm.getText(), "helloxyz"); @@ -3181,14 +2830,11 @@ public class MessageConsumerTest extends JMSTestCase checkEmpty(ActiveMQServerTestCase.topic1); } - finally - { - if (conn1 != null) - { + finally { + if (conn1 != null) { conn1.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } @@ -3196,13 +2842,11 @@ public class MessageConsumerTest extends JMSTestCase // Check messages have correct type after being resurrected from persistent storage @Test - public void testPersistedMessageType() throws Exception - { + public void testPersistedMessageType() throws Exception { Connection theConn = null; Connection theOtherConn = null; - try - { + try { theConn = createConnection(); theConn.start(); @@ -3268,28 +2912,23 @@ public class MessageConsumerTest extends JMSTestCase TextMessage tm2 = (TextMessage) theConsumer.receive(1500); ProxyAssertSupport.assertEquals("aardvark", tm2.getText()); } - finally - { - if (theConn != null) - { + finally { + if (theConn != null) { theConn.close(); } - if (theOtherConn != null) - { + if (theOtherConn != null) { theOtherConn.close(); } } } @Test - public void testDurableSubscriptionSimple() throws Exception - { + public void testDurableSubscriptionSimple() throws Exception { final String CLIENT_ID1 = "test-client-id1"; Connection conn1 = null; - try - { + try { conn1 = createConnection(); conn1.setClientID(CLIENT_ID1); @@ -3304,18 +2943,15 @@ public class MessageConsumerTest extends JMSTestCase final int NUM_MESSAGES = 50; - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = sess1.createTextMessage("hello"); prod.send(ActiveMQServerTestCase.topic1, tm); } int count = 0; - while (true) - { + while (true) { TextMessage tm = (TextMessage) durable.receive(1500); - if (tm == null) - { + if (tm == null) { break; } count++; @@ -3327,26 +2963,22 @@ public class MessageConsumerTest extends JMSTestCase sess1.unsubscribe("mySubscription"); } - finally - { - if (conn1 != null) - { + finally { + if (conn1 != null) { conn1.close(); } } } @Test - public void testDurableSubscriptionMultipleSubscriptions() throws Exception - { + public void testDurableSubscriptionMultipleSubscriptions() throws Exception { final String CLIENT_ID1 = "test-client-id1"; Connection conn1 = null; Connection conn2 = null; Connection conn3 = null; - try - { + try { conn1 = createConnection(); conn1.setClientID(CLIENT_ID1); @@ -3368,8 +3000,7 @@ public class MessageConsumerTest extends JMSTestCase final int NUM_MESSAGES = 50; - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = sess2.createTextMessage("hello"); producer.send(tm); } @@ -3385,11 +3016,9 @@ public class MessageConsumerTest extends JMSTestCase MessageConsumer durable3 = sess3.createDurableSubscriber(ActiveMQServerTestCase.topic1, "mySubscription2"); int count = 0; - while (true) - { + while (true) { TextMessage tm = (TextMessage) durable3.receive(1000); - if (tm == null) - { + if (tm == null) { break; } ProxyAssertSupport.assertEquals("hello", tm.getText()); @@ -3413,26 +3042,21 @@ public class MessageConsumerTest extends JMSTestCase sess3.unsubscribe("mySubscription1"); } - finally - { - if (conn1 != null) - { + finally { + if (conn1 != null) { conn1.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } - if (conn3 != null) - { + if (conn3 != null) { conn3.close(); } } } @Test - public void testDurableSubscriptionDataRemaining() throws Exception - { + public void testDurableSubscriptionDataRemaining() throws Exception { final String CLIENT_ID1 = "test-client-id1"; Connection conn1 = null; @@ -3447,8 +3071,7 @@ public class MessageConsumerTest extends JMSTestCase Session sess4; Session sess6 = null; - try - { + try { // Create a durable subscriber on one connection and close it conn1 = createConnection(); conn1.setClientID(CLIENT_ID1); @@ -3463,8 +3086,7 @@ public class MessageConsumerTest extends JMSTestCase MessageProducer prod2 = sess2.createProducer(null); prod2.setDeliveryMode(DeliveryMode.PERSISTENT); final int NUM_MESSAGES = 10; - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = sess2.createTextMessage("hello"); prod2.send(ActiveMQServerTestCase.topic1, tm); } @@ -3477,11 +3099,9 @@ public class MessageConsumerTest extends JMSTestCase sess3 = conn3.createSession(false, Session.AUTO_ACKNOWLEDGE); durable = sess3.createDurableSubscriber(ActiveMQServerTestCase.topic1, "mySubscription"); int count = 0; - while (true) - { + while (true) { TextMessage tm = (TextMessage) durable.receive(1000); - if (tm == null) - { + if (tm == null) { break; } ProxyAssertSupport.assertEquals("hello", tm.getText()); @@ -3510,8 +3130,7 @@ public class MessageConsumerTest extends JMSTestCase prod5.setDeliveryMode(DeliveryMode.PERSISTENT); log.debug("sending.1 " + NUM_MESSAGES + " messages"); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm2 = sess5.createTextMessage("hello"); prod5.send(ActiveMQServerTestCase.topic1, tm2); } @@ -3535,49 +3154,39 @@ public class MessageConsumerTest extends JMSTestCase durable.close(); } - finally - { - if (conn1 != null) - { + finally { + if (conn1 != null) { conn1.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } - if (conn3 != null) - { + if (conn3 != null) { conn3.close(); } - if (conn4 != null) - { + if (conn4 != null) { conn4.close(); } - if (conn5 != null) - { + if (conn5 != null) { conn5.close(); } - if (sess6 != null) - { + if (sess6 != null) { sess6.unsubscribe("mySubscription"); } - if (conn6 != null) - { + if (conn6 != null) { conn6.close(); } } } @Test - public void testDurableSubscriptionReconnect() throws Exception - { + public void testDurableSubscriptionReconnect() throws Exception { final String CLIENT_ID1 = "test-client-id1"; Connection conn1 = null; Connection conn2 = null; - try - { + try { conn1 = createConnection(); conn1.setClientID(CLIENT_ID1); @@ -3591,16 +3200,14 @@ public class MessageConsumerTest extends JMSTestCase final int NUM_MESSAGES = 2; - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = sess1.createTextMessage("hello"); prod.send(ActiveMQServerTestCase.topic1, tm); } final int NUM_TO_RECEIVE = NUM_MESSAGES - 1; - for (int i = 0; i < NUM_TO_RECEIVE; i++) - { + for (int i = 0; i < NUM_TO_RECEIVE; i++) { TextMessage tm = (TextMessage) durable.receive(3000); ProxyAssertSupport.assertNotNull(tm); } @@ -3622,11 +3229,9 @@ public class MessageConsumerTest extends JMSTestCase conn2.start(); int count = 0; - while (true) - { + while (true) { TextMessage tm = (TextMessage) durable2.receive(1500); - if (tm == null) - { + if (tm == null) { break; } count++; @@ -3638,30 +3243,25 @@ public class MessageConsumerTest extends JMSTestCase sess2.unsubscribe("mySubscription"); } - finally - { - if (conn1 != null) - { + finally { + if (conn1 != null) { conn1.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } } @Test - public void testDurableSubscriptionReconnectDifferentClientID() throws Exception - { + public void testDurableSubscriptionReconnectDifferentClientID() throws Exception { final String CLIENT_ID1 = "test-client-id1"; final String CLIENT_ID2 = "test-client-id2"; Connection conn1 = null; Connection conn2 = null; - try - { + try { conn1 = createConnection(); conn1.setClientID(CLIENT_ID1); @@ -3676,19 +3276,16 @@ public class MessageConsumerTest extends JMSTestCase final int NUM_MESSAGES = 50; - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = sess1.createTextMessage("hello"); prod.send(ActiveMQServerTestCase.topic1, tm); } final int NUM_TO_RECEIVE1 = 22; - for (int i = 0; i < NUM_TO_RECEIVE1; i++) - { + for (int i = 0; i < NUM_TO_RECEIVE1; i++) { TextMessage tm = (TextMessage) durable.receive(1500); - if (tm == null) - { + if (tm == null) { ProxyAssertSupport.fail(); } } @@ -3725,63 +3322,52 @@ public class MessageConsumerTest extends JMSTestCase sess1.unsubscribe("mySubscription"); } - finally - { - if (conn1 != null) - { + finally { + if (conn1 != null) { conn1.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } } @Test - public void testDurableSubscriptionInvalidUnsubscribe() throws Exception - { + public void testDurableSubscriptionInvalidUnsubscribe() throws Exception { final String CLIENT_ID1 = "test-client-id1"; Connection conn1 = null; - try - { + try { conn1 = createConnection(); conn1.setClientID(CLIENT_ID1); Session sess1 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE); - try - { + try { sess1.unsubscribe("non-existent subscription"); ProxyAssertSupport.fail(); } - catch (JMSException e) - { + catch (JMSException e) { } } - finally - { - if (conn1 != null) - { + finally { + if (conn1 != null) { conn1.close(); } } } @Test - public void testDurableSubscriptionClientIDNotSet() throws Exception - { + public void testDurableSubscriptionClientIDNotSet() throws Exception { // Client id must be set before creating a durable subscription // This assumes we are not setting it in the connection factory which // is currently true but may change in the future Connection conn1 = null; - try - { + try { conn1 = createConnection(); @@ -3789,34 +3375,28 @@ public class MessageConsumerTest extends JMSTestCase Session sess1 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE); - try - { + try { sess1.createDurableSubscriber(ActiveMQServerTestCase.topic1, "mySubscription"); ProxyAssertSupport.fail(); } - catch (JMSException e) - { + catch (JMSException e) { } } - finally - { - if (conn1 != null) - { + finally { + if (conn1 != null) { conn1.close(); } } } @Test - public void testRedeliveredDifferentSessions() throws Exception - { + public void testRedeliveredDifferentSessions() throws Exception { Connection producerConnection = null; Connection consumerConnection = null; - try - { + try { producerConnection = createConnection(); consumerConnection = createConnection(); @@ -3847,14 +3427,11 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertTrue(tm3.getJMSRedelivered()); } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } - if (consumerConnection != null) - { + if (consumerConnection != null) { consumerConnection.close(); } removeAllMessages(queue1.getQueueName(), true); @@ -3862,12 +3439,10 @@ public class MessageConsumerTest extends JMSTestCase } @Test - public void testRedelMessageListener1() throws Exception - { + public void testRedelMessageListener1() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); conn.start(); @@ -3900,22 +3475,18 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertFalse(listener.failed); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testRedelMessageListener2() throws Exception - { + public void testRedelMessageListener2() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); conn.start(); @@ -3949,10 +3520,8 @@ public class MessageConsumerTest extends JMSTestCase conn = null; } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -3960,8 +3529,7 @@ public class MessageConsumerTest extends JMSTestCase // http://jira.jboss.org/jira/browse/JBMESSAGING-1294 - commented out until 2.0 beta @Test - public void testExceptionMessageListener1() throws Exception - { + public void testExceptionMessageListener1() throws Exception { Connection conn = createConnection(); conn.start(); @@ -3991,8 +3559,7 @@ public class MessageConsumerTest extends JMSTestCase } @Test - public void testExceptionMessageListener2() throws Exception - { + public void testExceptionMessageListener2() throws Exception { Connection conn = createConnection(); conn.start(); @@ -4022,8 +3589,7 @@ public class MessageConsumerTest extends JMSTestCase } @Test - public void testExceptionMessageListener3() throws Exception - { + public void testExceptionMessageListener3() throws Exception { Connection conn = createConnection(); conn.start(); @@ -4055,12 +3621,10 @@ public class MessageConsumerTest extends JMSTestCase } @Test - public void testExceptionMessageListener4() throws Exception - { + public void testExceptionMessageListener4() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); conn.start(); @@ -4093,10 +3657,8 @@ public class MessageConsumerTest extends JMSTestCase conn = null; } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } @@ -4105,12 +3667,10 @@ public class MessageConsumerTest extends JMSTestCase } @Test - public void testExceptionMessageListenerCloseConnection() throws Exception - { + public void testExceptionMessageListenerCloseConnection() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); conn.start(); @@ -4139,10 +3699,8 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertTrue(listener.exception instanceof javax.jms.IllegalStateException); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } @@ -4151,12 +3709,10 @@ public class MessageConsumerTest extends JMSTestCase } @Test - public void testExceptionMessageListenerStopConnection() throws Exception - { + public void testExceptionMessageListenerStopConnection() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); conn.start(); @@ -4185,10 +3741,8 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertTrue(listener.exception instanceof javax.jms.IllegalStateException); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } @@ -4197,12 +3751,10 @@ public class MessageConsumerTest extends JMSTestCase } @Test - public void testExceptionMessageListenerStopSession() throws Exception - { + public void testExceptionMessageListenerStopSession() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); conn.start(); @@ -4231,10 +3783,8 @@ public class MessageConsumerTest extends JMSTestCase ProxyAssertSupport.assertTrue(listener.exception instanceof javax.jms.IllegalStateException); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } @@ -4249,90 +3799,77 @@ public class MessageConsumerTest extends JMSTestCase // Private ------------------------------------------------------- // Inner classes ------------------------------------------------- - private class ConnectionCloseMessageListener implements MessageListener - { + private class ConnectionCloseMessageListener implements MessageListener { + private Connection conn; private CountDownLatch latch; private JMSException exception; - public ConnectionCloseMessageListener(Connection conn, CountDownLatch latch) - { + public ConnectionCloseMessageListener(Connection conn, CountDownLatch latch) { this.conn = conn; this.latch = latch; } @Override - public void onMessage(Message message) - { - try - { + public void onMessage(Message message) { + try { conn.close(); } - catch (JMSException e) - { + catch (JMSException e) { this.exception = e; } latch.countDown(); } } - private class ConnectionStopMessageListener implements MessageListener - { + private class ConnectionStopMessageListener implements MessageListener { + private Connection conn; private CountDownLatch latch; private JMSException exception; - public ConnectionStopMessageListener(Connection conn, CountDownLatch latch) - { + public ConnectionStopMessageListener(Connection conn, CountDownLatch latch) { this.conn = conn; this.latch = latch; } @Override - public void onMessage(Message message) - { - try - { + public void onMessage(Message message) { + try { conn.stop(); } - catch (JMSException e) - { + catch (JMSException e) { this.exception = e; } latch.countDown(); } } - private class SessionCloseMessageListener implements MessageListener - { + private class SessionCloseMessageListener implements MessageListener { + private Session session; private CountDownLatch latch; private JMSException exception; - public SessionCloseMessageListener(Session session, CountDownLatch latch) - { + public SessionCloseMessageListener(Session session, CountDownLatch latch) { this.session = session; this.latch = latch; } @Override - public void onMessage(Message message) - { - try - { + public void onMessage(Message message) { + try { session.close(); } - catch (JMSException e) - { + catch (JMSException e) { this.exception = e; } latch.countDown(); } } + private class ExceptionRedelMessageListenerImpl implements MessageListener { - private class ExceptionRedelMessageListenerImpl implements MessageListener - { private final CountDownLatch latch = new CountDownLatch(1); private int count; @@ -4343,79 +3880,61 @@ public class MessageConsumerTest extends JMSTestCase String message = "ok"; - private void failed(final String msg) - { + private void failed(final String msg) { log.warn(msg); failed = true; message = msg; } - public void waitForMessages() throws InterruptedException - { + public void waitForMessages() throws InterruptedException { ActiveMQTestBase.waitForLatch(latch); } - public ExceptionRedelMessageListenerImpl(final Session sess) - { + public ExceptionRedelMessageListenerImpl(final Session sess) { this.sess = sess; } - public void onMessage(final Message m) - { + public void onMessage(final Message m) { TextMessage tm = (TextMessage) m; count++; - try - { - if (count == 1) - { - if (!"a".equals(tm.getText())) - { + try { + if (count == 1) { + if (!"a".equals(tm.getText())) { failed("Should be a but was " + tm.getText()); latch.countDown(); } throw new RuntimeException("Aardvark"); } - else if (count == 2) - { - if (sess.getAcknowledgeMode() == Session.AUTO_ACKNOWLEDGE || sess.getAcknowledgeMode() == Session.DUPS_OK_ACKNOWLEDGE) - { + else if (count == 2) { + if (sess.getAcknowledgeMode() == Session.AUTO_ACKNOWLEDGE || sess.getAcknowledgeMode() == Session.DUPS_OK_ACKNOWLEDGE) { // Message should be immediately redelivered - if (!"a".equals(tm.getText())) - { + if (!"a".equals(tm.getText())) { failed("Should be a but was " + tm.getText()); latch.countDown(); } - if (!tm.getJMSRedelivered()) - { + if (!tm.getJMSRedelivered()) { failed("Message was supposed to be a redelivery"); latch.countDown(); } } - else - { + else { // Transacted or CLIENT_ACKNOWLEDGE - next message should be delivered - if (!"b".equals(tm.getText())) - { + if (!"b".equals(tm.getText())) { failed("Should be b but was " + tm.getText()); latch.countDown(); } } } - else if (count == 3) - { - if (sess.getAcknowledgeMode() == Session.AUTO_ACKNOWLEDGE || sess.getAcknowledgeMode() == Session.DUPS_OK_ACKNOWLEDGE) - { - if (!"b".equals(tm.getText())) - { + else if (count == 3) { + if (sess.getAcknowledgeMode() == Session.AUTO_ACKNOWLEDGE || sess.getAcknowledgeMode() == Session.DUPS_OK_ACKNOWLEDGE) { + if (!"b".equals(tm.getText())) { failed("Should be b but was " + tm.getText()); latch.countDown(); } } - else - { - if (!"c".equals(tm.getText())) - { + else { + if (!"c".equals(tm.getText())) { failed("Should be c but was " + tm.getText()); latch.countDown(); } @@ -4423,27 +3942,22 @@ public class MessageConsumerTest extends JMSTestCase } } - else if (count == 4) - { - if (sess.getAcknowledgeMode() == Session.AUTO_ACKNOWLEDGE || sess.getAcknowledgeMode() == Session.DUPS_OK_ACKNOWLEDGE) - { - if (!"c".equals(tm.getText())) - { + else if (count == 4) { + if (sess.getAcknowledgeMode() == Session.AUTO_ACKNOWLEDGE || sess.getAcknowledgeMode() == Session.DUPS_OK_ACKNOWLEDGE) { + if (!"c".equals(tm.getText())) { failed("Should be c but was " + tm.getText()); latch.countDown(); } latch.countDown(); } - else - { + else { // Shouldn't get a 4th message failed("Shouldn't get a 4th message"); latch.countDown(); } } } - catch (JMSException e) - { + catch (JMSException e) { log.error(e.getMessage(), e); failed("Got a JMSException " + e.toString()); latch.countDown(); @@ -4451,8 +3965,8 @@ public class MessageConsumerTest extends JMSTestCase } } - private class RedelMessageListenerImpl implements MessageListener - { + private class RedelMessageListenerImpl implements MessageListener { + private Session sess; private int count; @@ -4465,130 +3979,106 @@ public class MessageConsumerTest extends JMSTestCase private final boolean transacted; - public RedelMessageListenerImpl(final boolean transacted) - { + public RedelMessageListenerImpl(final boolean transacted) { this.transacted = transacted; } /** * Blocks the calling thread until at least a message is received */ - public void waitForMessages() throws InterruptedException - { + public void waitForMessages() throws InterruptedException { ActiveMQTestBase.waitForLatch(latch); } - public void onMessage(final Message m) - { - try - { + public void onMessage(final Message m) { + try { TextMessage tm = (TextMessage) m; messageOrder += tm.getText() + " "; - if (count == 0) - { - if (!"a".equals(tm.getText())) - { + if (count == 0) { + if (!"a".equals(tm.getText())) { failed = true; latch.countDown(); } - if (transacted) - { + if (transacted) { sess.rollback(); messageOrder += "RB "; } - else - { + else { messageOrder += "RC "; sess.recover(); } } - if (count == 1) - { - if (!"a".equals(tm.getText())) - { + if (count == 1) { + if (!"a".equals(tm.getText())) { failed = true; latch.countDown(); } - if (!tm.getJMSRedelivered()) - { + if (!tm.getJMSRedelivered()) { failed = true; latch.countDown(); } } - if (count == 2) - { - if (!"b".equals(tm.getText())) - { + if (count == 2) { + if (!"b".equals(tm.getText())) { failed = true; latch.countDown(); } } - if (count == 3) - { - if (!"c".equals(tm.getText())) - { + if (count == 3) { + if (!"c".equals(tm.getText())) { failed = true; latch.countDown(); } - if (transacted) - { + if (transacted) { sess.commit(); } - else - { + else { tm.acknowledge(); } latch.countDown(); } count++; } - catch (JMSException e) - { + catch (JMSException e) { failed = true; latch.countDown(); } } } - private class MessageListenerImpl implements MessageListener - { + private class MessageListenerImpl implements MessageListener { + private final List messages = Collections.synchronizedList(new ArrayList()); private CountDownLatch latch = new CountDownLatch(1); - public MessageListenerImpl(final int count) - { + public MessageListenerImpl(final int count) { latch = new CountDownLatch(count); } - public MessageListenerImpl() - { + public MessageListenerImpl() { this(1); } /** * Blocks the calling thread until at least a message is received */ - public void waitForMessages() throws InterruptedException - { + public void waitForMessages() throws InterruptedException { ActiveMQTestBase.waitForLatch(latch); } - public void onMessage(final Message m) - { + public void onMessage(final Message m) { messages.add(m); log.trace("Added message " + m + " to my list"); latch.countDown(); } - public Message getNextMessage() - { + public Message getNextMessage() { Iterator i = messages.iterator(); - if (!i.hasNext()) - { + if (!i.hasNext()) { return null; } Message m = i.next(); @@ -4596,13 +4086,11 @@ public class MessageConsumerTest extends JMSTestCase return m; } - public List getMessages() - { + public List getMessages() { return messages; } - public int size() - { + public int size() { return messages.size(); } } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/MessageProducerTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/MessageProducerTest.java index 4e900a682f..7fa72b337e 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/MessageProducerTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/MessageProducerTest.java @@ -37,11 +37,10 @@ import org.apache.activemq.artemis.jms.tests.message.SimpleJMSTextMessage; import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; import org.junit.Test; -public class MessageProducerTest extends JMSTestCase -{ +public class MessageProducerTest extends JMSTestCase { + @Test - public void testSendForeignWithForeignDestinationSet() throws Exception - { + public void testSendForeignWithForeignDestinationSet() throws Exception { Connection conn = createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -65,8 +64,7 @@ public class MessageProducerTest extends JMSTestCase ProxyAssertSupport.assertNotNull(m); } - private static class SimpleDestination implements Destination, Serializable - { + private static class SimpleDestination implements Destination, Serializable { /** * @@ -75,24 +73,20 @@ public class MessageProducerTest extends JMSTestCase } @Test - public void testSendToQueuePersistent() throws Exception - { + public void testSendToQueuePersistent() throws Exception { sendToQueue(true); } @Test - public void testSendToQueueNonPersistent() throws Exception - { + public void testSendToQueueNonPersistent() throws Exception { sendToQueue(false); } - private void sendToQueue(final boolean persistent) throws Exception - { + private void sendToQueue(final boolean persistent) throws Exception { Connection pconn = null; Connection cconn = null; - try - { + try { pconn = createConnection(); cconn = createConnection(); @@ -111,38 +105,31 @@ public class MessageProducerTest extends JMSTestCase ProxyAssertSupport.assertEquals(m.getJMSMessageID(), r.getJMSMessageID()); ProxyAssertSupport.assertEquals("test", r.getText()); } - finally - { - if (pconn != null) - { + finally { + if (pconn != null) { pconn.close(); } - if (cconn != null) - { + if (cconn != null) { cconn.close(); } } } @Test - public void testTransactedSendPersistent() throws Exception - { + public void testTransactedSendPersistent() throws Exception { transactedSend(true); } @Test - public void testTransactedSendNonPersistent() throws Exception - { + public void testTransactedSendNonPersistent() throws Exception { transactedSend(false); } - private void transactedSend(final boolean persistent) throws Exception - { + private void transactedSend(final boolean persistent) throws Exception { Connection pconn = null; Connection cconn = null; - try - { + try { pconn = createConnection(); cconn = createConnection(); @@ -163,8 +150,7 @@ public class MessageProducerTest extends JMSTestCase ProxyAssertSupport.assertEquals(m.getJMSMessageID(), r.getJMSMessageID()); ProxyAssertSupport.assertEquals("test", r.getText()); } - finally - { + finally { pconn.close(); cconn.close(); } @@ -174,29 +160,25 @@ public class MessageProducerTest extends JMSTestCase // Since this test intermittently fails. // (As an aside, technically this test is invalid anyway since the sessions is used for sending // and consuming concurrently - and sessions are supposed to be single threaded) - private class Sender implements Runnable - { + private class Sender implements Runnable { + volatile Exception ex; MessageProducer prod; Message m; - Sender(final MessageProducer prod, final Message m) - { + Sender(final MessageProducer prod, final Message m) { this.prod = prod; this.m = m; } - public synchronized void run() - { - try - { + public synchronized void run() { + try { prod.send(m); } - catch (Exception e) - { + catch (Exception e) { log.error(e); ex = e; @@ -205,25 +187,21 @@ public class MessageProducerTest extends JMSTestCase } @Test - public void testPersistentSendToTopic() throws Exception - { + public void testPersistentSendToTopic() throws Exception { sendToTopic(true); } @Test - public void testNonPersistentSendToTopic() throws Exception - { + public void testNonPersistentSendToTopic() throws Exception { sendToTopic(false); } - private void sendToTopic(final boolean persistent) throws Exception - { + private void sendToTopic(final boolean persistent) throws Exception { Connection pconn = createConnection(); Connection cconn = createConnection(); - try - { + try { Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); Session cs = cconn.createSession(false, Session.AUTO_ACKNOWLEDGE); final MessageProducer p = ps.createProducer(ActiveMQServerTestCase.topic1); @@ -244,8 +222,7 @@ public class MessageProducerTest extends JMSTestCase TextMessage m2 = (TextMessage) c.receive(5000); - if (sender.ex != null) - { + if (sender.ex != null) { // If an exception was caught in sending we rethrow here so as not to lose it throw sender.ex; } @@ -255,8 +232,7 @@ public class MessageProducerTest extends JMSTestCase t.join(); } - finally - { + finally { pconn.close(); cconn.close(); } @@ -266,13 +242,11 @@ public class MessageProducerTest extends JMSTestCase * Test sending via anonymous producer */ @Test - public void testSendDestination() throws Exception - { + public void testSendDestination() throws Exception { Connection pconn = createConnection(); Connection cconn = createConnection(); - try - { + try { Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); Session cs = cconn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer c2 = cs.createConsumer(ActiveMQServerTestCase.topic2); @@ -282,16 +256,12 @@ public class MessageProducerTest extends JMSTestCase final MessageProducer anonProducer = ps.createProducer(null); - new Thread(new Runnable() - { - public void run() - { - try - { + new Thread(new Runnable() { + public void run() { + try { anonProducer.send(ActiveMQServerTestCase.topic2, m1); } - catch (Exception e) - { + catch (Exception e) { log.error(e); } } @@ -302,21 +272,18 @@ public class MessageProducerTest extends JMSTestCase log.debug("ending test"); } - finally - { + finally { pconn.close(); cconn.close(); } } @Test - public void testSendForeignMessage() throws Exception - { + public void testSendForeignMessage() throws Exception { Connection pconn = createConnection(); Connection cconn = createConnection(); - try - { + try { Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); Session cs = cconn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer p = ps.createProducer(queue1); @@ -334,77 +301,63 @@ public class MessageProducerTest extends JMSTestCase ProxyAssertSupport.assertEquals("something", rec.getText()); } - finally - { + finally { pconn.close(); cconn.close(); } } @Test - public void testGetDestination() throws Exception - { + public void testGetDestination() throws Exception { Connection pconn = createConnection(); - try - { + try { Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer p = ps.createProducer(ActiveMQServerTestCase.topic1); Destination dest = p.getDestination(); ProxyAssertSupport.assertEquals(dest, ActiveMQServerTestCase.topic1); } - finally - { + finally { pconn.close(); } } @Test - public void testGetDestinationOnClosedProducer() throws Exception - { + public void testGetDestinationOnClosedProducer() throws Exception { Connection pconn = createConnection(); - try - { + try { Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer p = ps.createProducer(ActiveMQServerTestCase.topic1); p.close(); - try - { + try { p.getDestination(); ProxyAssertSupport.fail("should throw exception"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } } - finally - { + finally { pconn.close(); } } @Test - public void testCreateProducerOnInexistentDestination() throws Exception - { + public void testCreateProducerOnInexistentDestination() throws Exception { Connection pconn = createConnection(); - try - { + try { Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); - try - { + try { ps.createProducer(ActiveMQJMSClient.createTopic("NoSuchTopic")); ProxyAssertSupport.fail("should throw exception"); } - catch (InvalidDestinationException e) - { + catch (InvalidDestinationException e) { // OK } } - finally - { + finally { pconn.close(); } } @@ -414,47 +367,39 @@ public class MessageProducerTest extends JMSTestCase // @Test - public void testGetDisableMessageID() throws Exception - { + public void testGetDisableMessageID() throws Exception { Connection pconn = createConnection(); - try - { + try { Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer p = ps.createProducer(ActiveMQServerTestCase.topic1); ProxyAssertSupport.assertFalse(p.getDisableMessageID()); } - finally - { + finally { pconn.close(); } } @Test - public void testGetDisableMessageIDOnClosedProducer() throws Exception - { + public void testGetDisableMessageIDOnClosedProducer() throws Exception { Connection pconn = createConnection(); - try - { + try { Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer p = ps.createProducer(ActiveMQServerTestCase.topic1); p.close(); - try - { + try { p.getDisableMessageID(); ProxyAssertSupport.fail("should throw exception"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } } - finally - { + finally { pconn.close(); } } @@ -464,32 +409,27 @@ public class MessageProducerTest extends JMSTestCase // @Test - public void testDefaultTimestampDisabled() throws Exception - { + public void testDefaultTimestampDisabled() throws Exception { Connection pconn = createConnection(); - try - { + try { Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer tp = ps.createProducer(ActiveMQServerTestCase.topic1); MessageProducer qp = ps.createProducer(queue1); ProxyAssertSupport.assertFalse(tp.getDisableMessageTimestamp()); ProxyAssertSupport.assertFalse(qp.getDisableMessageTimestamp()); } - finally - { + finally { pconn.close(); } } @Test - public void testSetTimestampDisabled() throws Exception - { + public void testSetTimestampDisabled() throws Exception { Connection pconn = createConnection(); Connection cconn = createConnection(); - try - { + try { Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); Session cs = cconn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer p = ps.createProducer(queue1); @@ -521,37 +461,31 @@ public class MessageProducerTest extends JMSTestCase ProxyAssertSupport.assertTrue(timestamp >= t1); ProxyAssertSupport.assertTrue(timestamp <= t2); } - finally - { + finally { pconn.close(); cconn.close(); } } @Test - public void testGetTimestampDisabledOnClosedProducer() throws Exception - { + public void testGetTimestampDisabledOnClosedProducer() throws Exception { Connection pconn = createConnection(); - try - { + try { Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer p = ps.createProducer(ActiveMQServerTestCase.topic1); p.close(); - try - { + try { p.getDisableMessageTimestamp(); ProxyAssertSupport.fail("should throw exception"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } } - finally - { + finally { pconn.close(); } } @@ -561,12 +495,10 @@ public class MessageProducerTest extends JMSTestCase // @Test - public void testDefaultDeliveryMode() throws Exception - { + public void testDefaultDeliveryMode() throws Exception { Connection pconn = createConnection(); - try - { + try { Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer tp = ps.createProducer(ActiveMQServerTestCase.topic1); MessageProducer qp = ps.createProducer(queue1); @@ -574,19 +506,16 @@ public class MessageProducerTest extends JMSTestCase ProxyAssertSupport.assertEquals(DeliveryMode.PERSISTENT, tp.getDeliveryMode()); ProxyAssertSupport.assertEquals(DeliveryMode.PERSISTENT, qp.getDeliveryMode()); } - finally - { + finally { pconn.close(); } } @Test - public void testSetDeliveryMode() throws Exception - { + public void testSetDeliveryMode() throws Exception { Connection pconn = createConnection(); - try - { + try { Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer p = ps.createProducer(ActiveMQServerTestCase.topic1); @@ -596,36 +525,30 @@ public class MessageProducerTest extends JMSTestCase p.setDeliveryMode(DeliveryMode.PERSISTENT); ProxyAssertSupport.assertEquals(DeliveryMode.PERSISTENT, p.getDeliveryMode()); } - finally - { + finally { pconn.close(); } } @Test - public void testGetDeliveryModeOnClosedProducer() throws Exception - { + public void testGetDeliveryModeOnClosedProducer() throws Exception { Connection pconn = createConnection(); - try - { + try { Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer p = ps.createProducer(ActiveMQServerTestCase.topic1); p.close(); - try - { + try { p.getDeliveryMode(); ProxyAssertSupport.fail("should throw exception"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } } - finally - { + finally { pconn.close(); } } @@ -635,12 +558,10 @@ public class MessageProducerTest extends JMSTestCase // @Test - public void testDefaultPriority() throws Exception - { + public void testDefaultPriority() throws Exception { Connection pconn = createConnection(); - try - { + try { Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer tp = ps.createProducer(ActiveMQServerTestCase.topic1); MessageProducer qp = ps.createProducer(queue1); @@ -648,19 +569,16 @@ public class MessageProducerTest extends JMSTestCase ProxyAssertSupport.assertEquals(4, tp.getPriority()); ProxyAssertSupport.assertEquals(4, qp.getPriority()); } - finally - { + finally { pconn.close(); } } @Test - public void testSetPriority() throws Exception - { + public void testSetPriority() throws Exception { Connection pconn = createConnection(); - try - { + try { Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer p = ps.createProducer(ActiveMQServerTestCase.topic1); @@ -670,36 +588,30 @@ public class MessageProducerTest extends JMSTestCase p.setPriority(0); ProxyAssertSupport.assertEquals(0, p.getPriority()); } - finally - { + finally { pconn.close(); } } @Test - public void testGetPriorityOnClosedProducer() throws Exception - { + public void testGetPriorityOnClosedProducer() throws Exception { Connection pconn = createConnection(); - try - { + try { Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer p = ps.createProducer(ActiveMQServerTestCase.topic1); p.close(); - try - { + try { p.getPriority(); ProxyAssertSupport.fail("should throw exception"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } } - finally - { + finally { pconn.close(); } } @@ -709,8 +621,7 @@ public class MessageProducerTest extends JMSTestCase // @Test - public void testDefaultTimeToLive() throws Exception - { + public void testDefaultTimeToLive() throws Exception { Connection pconn = createConnection(); Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer tp = ps.createProducer(ActiveMQServerTestCase.topic1); @@ -721,8 +632,7 @@ public class MessageProducerTest extends JMSTestCase } @Test - public void testSetTimeToLive() throws Exception - { + public void testSetTimeToLive() throws Exception { Connection pconn = createConnection(); Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer p = ps.createProducer(ActiveMQServerTestCase.topic1); @@ -735,8 +645,7 @@ public class MessageProducerTest extends JMSTestCase } @Test - public void testGetTimeToLiveOnClosedProducer() throws Exception - { + public void testGetTimeToLiveOnClosedProducer() throws Exception { Connection pconn = createConnection(); Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -744,20 +653,17 @@ public class MessageProducerTest extends JMSTestCase p.close(); - try - { + try { p.setTimeToLive(100L); ProxyAssertSupport.fail("should throw exception"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } } @Test - public void testProducerCloseInCompletionListener() throws Exception - { + public void testProducerCloseInCompletionListener() throws Exception { Connection pconn = createConnection(); Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -766,9 +672,7 @@ public class MessageProducerTest extends JMSTestCase CountDownLatch latch = new CountDownLatch(1); CloseCompletionListener listener = new CloseCompletionListener(p, latch); - - p.send(ps.createMessage(), DeliveryMode.NON_PERSISTENT, - Message.DEFAULT_PRIORITY, 0L, listener); + p.send(ps.createMessage(), DeliveryMode.NON_PERSISTENT, Message.DEFAULT_PRIORITY, 0L, listener); ProxyAssertSupport.assertTrue(latch.await(5, TimeUnit.SECONDS)); @@ -778,8 +682,7 @@ public class MessageProducerTest extends JMSTestCase } @Test - public void testConnectionCloseInCompletionListener() throws Exception - { + public void testConnectionCloseInCompletionListener() throws Exception { Connection pconn = createConnection(); Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -788,9 +691,7 @@ public class MessageProducerTest extends JMSTestCase CountDownLatch latch = new CountDownLatch(1); ConnectionCloseCompletionListener listener = new ConnectionCloseCompletionListener(pconn, latch); - - p.send(ps.createMessage(), DeliveryMode.NON_PERSISTENT, - Message.DEFAULT_PRIORITY, 0L, listener); + p.send(ps.createMessage(), DeliveryMode.NON_PERSISTENT, Message.DEFAULT_PRIORITY, 0L, listener); ProxyAssertSupport.assertTrue(latch.await(5, TimeUnit.SECONDS)); @@ -800,8 +701,7 @@ public class MessageProducerTest extends JMSTestCase } @Test - public void testSessionCloseInCompletionListener() throws Exception - { + public void testSessionCloseInCompletionListener() throws Exception { Connection pconn = createConnection(); Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -810,9 +710,7 @@ public class MessageProducerTest extends JMSTestCase CountDownLatch latch = new CountDownLatch(1); SessionCloseCompletionListener listener = new SessionCloseCompletionListener(ps, latch); - - p.send(ps.createMessage(), DeliveryMode.NON_PERSISTENT, - Message.DEFAULT_PRIORITY, 0L, listener); + p.send(ps.createMessage(), DeliveryMode.NON_PERSISTENT, Message.DEFAULT_PRIORITY, 0L, listener); ProxyAssertSupport.assertTrue(latch.await(5, TimeUnit.SECONDS)); @@ -827,99 +725,84 @@ public class MessageProducerTest extends JMSTestCase // Private ------------------------------------------------------- // Inner classes ------------------------------------------------- - private static class CloseCompletionListener implements CompletionListener - { + private static class CloseCompletionListener implements CompletionListener { + private MessageProducer p; private CountDownLatch latch; private JMSException exception; - public CloseCompletionListener(MessageProducer p, CountDownLatch latch) - { + public CloseCompletionListener(MessageProducer p, CountDownLatch latch) { this.p = p; this.latch = latch; } @Override - public void onCompletion(Message message) - { - try - { + public void onCompletion(Message message) { + try { p.close(); } - catch (JMSException e) - { + catch (JMSException e) { this.exception = e; } latch.countDown(); } @Override - public void onException(Message message, Exception exception) - { + public void onException(Message message, Exception exception) { } } - private static class ConnectionCloseCompletionListener implements CompletionListener - { + private static class ConnectionCloseCompletionListener implements CompletionListener { + private CountDownLatch latch; private JMSException exception; private Connection conn; - public ConnectionCloseCompletionListener(Connection conn, CountDownLatch latch) - { + public ConnectionCloseCompletionListener(Connection conn, CountDownLatch latch) { this.conn = conn; this.latch = latch; } @Override - public void onCompletion(Message message) - { - try - { + public void onCompletion(Message message) { + try { conn.close(); } - catch (JMSException e) - { + catch (JMSException e) { this.exception = e; } latch.countDown(); } @Override - public void onException(Message message, Exception exception) - { + public void onException(Message message, Exception exception) { } } - private static class SessionCloseCompletionListener implements CompletionListener - { + private static class SessionCloseCompletionListener implements CompletionListener { + private CountDownLatch latch; private JMSException exception; private Session session; - public SessionCloseCompletionListener(Session session, CountDownLatch latch) - { + public SessionCloseCompletionListener(Session session, CountDownLatch latch) { this.session = session; this.latch = latch; } @Override - public void onCompletion(Message message) - { - try - { + public void onCompletion(Message message) { + try { session.close(); } - catch (JMSException e) - { + catch (JMSException e) { this.exception = e; } latch.countDown(); } @Override - public void onException(Message message, Exception exception) - { + public void onException(Message message, Exception exception) { } } } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/MessageWithReadResolveTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/MessageWithReadResolveTest.java index f0973da5c2..48fc753e1c 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/MessageWithReadResolveTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/MessageWithReadResolveTest.java @@ -32,8 +32,7 @@ import org.junit.Test; *
    * See http://jira.jboss.com/jira/browse/JBMESSAGING-442 */ -public class MessageWithReadResolveTest extends JMSTestCase -{ +public class MessageWithReadResolveTest extends JMSTestCase { // Constants ----------------------------------------------------- @@ -48,8 +47,7 @@ public class MessageWithReadResolveTest extends JMSTestCase // Public -------------------------------------------------------- @Test - public void testSendReceiveMessage() throws Exception - { + public void testSendReceiveMessage() throws Exception { Connection conn = createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -89,30 +87,26 @@ public class MessageWithReadResolveTest extends JMSTestCase // Private ------------------------------------------------------- /* This class would trigger the exception when serialized with jboss serialization */ - public static class TestMessage implements Serializable - { + public static class TestMessage implements Serializable { + private static final long serialVersionUID = -5932581134414145967L; private final long id; private Object clazz; - public TestMessage(final long id, final boolean useSimpleObject) - { + public TestMessage(final long id, final boolean useSimpleObject) { this.id = id; - if (useSimpleObject) - { + if (useSimpleObject) { clazz = String.class; } - else - { + else { clazz = TestEnum.class; } } @Override - public String toString() - { + public String toString() { StringBuffer sb = new StringBuffer(); sb.append("TestMessage("); sb.append("id=" + id); @@ -121,20 +115,17 @@ public class MessageWithReadResolveTest extends JMSTestCase return sb.toString(); } - public long getID() - { + public long getID() { return id; } } - public static class TestEnum implements Serializable - { + public static class TestEnum implements Serializable { private static final long serialVersionUID = 4306026990380393029L; - public Object readResolve() - { + public Object readResolve() { return null; } } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/MiscellaneousTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/MiscellaneousTest.java index 5f6174114a..a30b7c948b 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/MiscellaneousTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/MiscellaneousTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.jms.tests; + import java.util.Enumeration; import javax.jms.Connection; @@ -34,8 +35,7 @@ import org.junit.Test; /** * Various use cases, added here while trying things or fixing forum issues. */ -public class MiscellaneousTest extends JMSTestCase -{ +public class MiscellaneousTest extends JMSTestCase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -46,8 +46,7 @@ public class MiscellaneousTest extends JMSTestCase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { removeAllMessages(queue1.getQueueName(), true); super.tearDown(); @@ -55,14 +54,11 @@ public class MiscellaneousTest extends JMSTestCase // Public -------------------------------------------------------- - @Test - public void testBrowser() throws Exception - { + public void testBrowser() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = session.createProducer(queue1); @@ -80,14 +76,12 @@ public class MiscellaneousTest extends JMSTestCase Enumeration e = browser.getEnumeration(); - TextMessage bm = (TextMessage)e.nextElement(); + TextMessage bm = (TextMessage) e.nextElement(); ProxyAssertSupport.assertEquals("message one", bm.getText()); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } @@ -99,22 +93,18 @@ public class MiscellaneousTest extends JMSTestCase * Test case for http://jira.jboss.org/jira/browse/JBMESSAGING-542 */ @Test - public void testClosingConsumerFromMessageListenerAutoAck() throws Exception - { + public void testClosingConsumerFromMessageListenerAutoAck() throws Exception { Connection c = null; - try - { + try { c = createConnection(); Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = s.createProducer(queue1); Message m = s.createMessage(); prod.send(m); } - finally - { - if (c != null) - { + finally { + if (c != null) { c.close(); } } @@ -123,18 +113,14 @@ public class MiscellaneousTest extends JMSTestCase Connection conn = createConnection(); Session s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); final MessageConsumer cons = s.createConsumer(queue1); - cons.setMessageListener(new MessageListener() - { - public void onMessage(final Message m) - { + cons.setMessageListener(new MessageListener() { + public void onMessage(final Message m) { // close the connection on the same thread that processed the message - try - { + try { cons.close(); result.setSuccess(); } - catch (Exception e) - { + catch (Exception e) { result.setFailure(e); } } @@ -160,22 +146,18 @@ public class MiscellaneousTest extends JMSTestCase * Test case for http://jira.jboss.org/jira/browse/JBMESSAGING-542 */ @Test - public void testClosingConsumerFromMessageListenerTransacted() throws Exception - { + public void testClosingConsumerFromMessageListenerTransacted() throws Exception { Connection c = null; - try - { + try { c = createConnection(); Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = s.createProducer(queue1); Message m = s.createMessage(); prod.send(m); } - finally - { - if (c != null) - { + finally { + if (c != null) { c.close(); } } @@ -184,18 +166,14 @@ public class MiscellaneousTest extends JMSTestCase Connection conn = createConnection(); Session s = conn.createSession(true, Session.SESSION_TRANSACTED); final MessageConsumer cons = s.createConsumer(queue1); - cons.setMessageListener(new MessageListener() - { - public void onMessage(final Message m) - { + cons.setMessageListener(new MessageListener() { + public void onMessage(final Message m) { // close the connection on the same thread that processed the message - try - { + try { cons.close(); result.setSuccess(); } - catch (Exception e) - { + catch (Exception e) { result.setFailure(e); } } @@ -217,12 +195,10 @@ public class MiscellaneousTest extends JMSTestCase // Test case for http://jira.jboss.com/jira/browse/JBMESSAGING-788 @Test - public void testGetDeliveriesForSession() throws Exception - { + public void testGetDeliveriesForSession() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session session1 = conn.createSession(true, Session.SESSION_TRANSACTED); @@ -239,10 +215,8 @@ public class MiscellaneousTest extends JMSTestCase session2.commit(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } @@ -258,22 +232,20 @@ public class MiscellaneousTest extends JMSTestCase // Inner classes ------------------------------------------------- - private class Result - { + private class Result { + private boolean success; private Exception e; private boolean resultSet; - public Result() - { + public Result() { success = false; e = null; } - public synchronized void setSuccess() - { + public synchronized void setSuccess() { success = true; resultSet = true; @@ -281,13 +253,11 @@ public class MiscellaneousTest extends JMSTestCase notify(); } - public synchronized boolean isSuccess() - { + public synchronized boolean isSuccess() { return success; } - public synchronized void setFailure(final Exception e) - { + public synchronized void setFailure(final Exception e) { this.e = e; resultSet = true; @@ -295,15 +265,12 @@ public class MiscellaneousTest extends JMSTestCase notify(); } - public synchronized Exception getFailure() - { + public synchronized Exception getFailure() { return e; } - public synchronized void waitForResult() throws Exception - { - while (!resultSet) - { + public synchronized void waitForResult() throws Exception { + while (!resultSet) { this.wait(); } } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/NonDurableSubscriberTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/NonDurableSubscriberTest.java index b075c9e79c..0f87f6c799 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/NonDurableSubscriberTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/NonDurableSubscriberTest.java @@ -28,8 +28,7 @@ import org.junit.Test; /** * Non-durable subscriber tests. */ -public class NonDurableSubscriberTest extends JMSTestCase -{ +public class NonDurableSubscriberTest extends JMSTestCase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -46,19 +45,16 @@ public class NonDurableSubscriberTest extends JMSTestCase * Test introduced as a result of a TCK failure. */ @Test - public void testNonDurableSubscriberOnNullTopic() throws Exception - { + public void testNonDurableSubscriberOnNullTopic() throws Exception { TopicConnection conn = createTopicConnection(); TopicSession ts = conn.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - try - { + try { ts.createSubscriber(null); ProxyAssertSupport.fail("this should fail"); } - catch (javax.jms.InvalidDestinationException e) - { + catch (javax.jms.InvalidDestinationException e) { // OK } } @@ -67,39 +63,33 @@ public class NonDurableSubscriberTest extends JMSTestCase * Test introduced as a result of a TCK failure. */ @Test - public void testNonDurableSubscriberInvalidUnsubscribe() throws Exception - { + public void testNonDurableSubscriberInvalidUnsubscribe() throws Exception { TopicConnection conn = createTopicConnection(); conn.setClientID("clientIDxyz123"); TopicSession ts = conn.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - try - { + try { ts.unsubscribe("invalid-subscription-name"); ProxyAssertSupport.fail("this should fail"); } - catch (javax.jms.InvalidDestinationException e) - { + catch (javax.jms.InvalidDestinationException e) { // OK } } @Test - public void testInvalidSelectorOnSubscription() throws Exception - { + public void testInvalidSelectorOnSubscription() throws Exception { TopicConnection c = createTopicConnection(); c.setClientID("something"); TopicSession s = c.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - try - { + try { s.createSubscriber(ActiveMQServerTestCase.topic1, "=TEST 'test'", false); ProxyAssertSupport.fail("this should fail"); } - catch (InvalidSelectorException e) - { + catch (InvalidSelectorException e) { // OK } } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/PersistenceTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/PersistenceTest.java index 4a7877ab20..69e2080921 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/PersistenceTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/PersistenceTest.java @@ -26,25 +26,22 @@ import javax.jms.TextMessage; import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; import org.junit.Test; -public class PersistenceTest extends JMSTestCase -{ +public class PersistenceTest extends JMSTestCase { + /** * Test that the messages in a persistent queue survive starting and stopping and server, */ @Test - public void testQueuePersistence() throws Exception - { + public void testQueuePersistence() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = sess.createProducer(queue1); prod.setDeliveryMode(DeliveryMode.PERSISTENT); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { TextMessage tm = sess.createTextMessage("message" + i); prod.send(tm); } @@ -62,22 +59,18 @@ public class PersistenceTest extends JMSTestCase sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); conn.start(); MessageConsumer cons = sess.createConsumer(queue1); - for (int i = 0; i < 10; i++) - { - TextMessage tm = (TextMessage)cons.receive(3000); + for (int i = 0; i < 10; i++) { + TextMessage tm = (TextMessage) cons.receive(3000); ProxyAssertSupport.assertNotNull(tm); - if (tm == null) - { + if (tm == null) { break; } ProxyAssertSupport.assertEquals("message" + i, tm.getText()); } } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -85,22 +78,18 @@ public class PersistenceTest extends JMSTestCase /** * Test that the JMSRedelivered and delivery count survives a restart - * */ @Test - public void testJMSRedeliveredRestart() throws Exception - { + public void testJMSRedeliveredRestart() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = sess.createProducer(queue1); prod.setDeliveryMode(DeliveryMode.PERSISTENT); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { TextMessage tm = sess.createTextMessage("message" + i); prod.send(tm); } @@ -111,9 +100,8 @@ public class PersistenceTest extends JMSTestCase conn.start(); - for (int i = 0; i < 10; i++) - { - TextMessage tm = (TextMessage)cons.receive(1000); + for (int i = 0; i < 10; i++) { + TextMessage tm = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(tm); @@ -127,9 +115,8 @@ public class PersistenceTest extends JMSTestCase // rollback sess2.rollback(); - for (int i = 0; i < 10; i++) - { - TextMessage tm = (TextMessage)cons.receive(1000); + for (int i = 0; i < 10; i++) { + TextMessage tm = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(tm); @@ -153,9 +140,8 @@ public class PersistenceTest extends JMSTestCase sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); conn.start(); cons = sess.createConsumer(queue1); - for (int i = 0; i < 10; i++) - { - TextMessage tm = (TextMessage)cons.receive(3000); + for (int i = 0; i < 10; i++) { + TextMessage tm = (TextMessage) cons.receive(3000); ProxyAssertSupport.assertNotNull(tm); @@ -166,10 +152,8 @@ public class PersistenceTest extends JMSTestCase ProxyAssertSupport.assertEquals(3, tm.getIntProperty("JMSXDeliveryCount")); } } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -179,12 +163,10 @@ public class PersistenceTest extends JMSTestCase * First test that message order survives a restart */ @Test - public void testMessageOrderPersistence_1() throws Exception - { + public void testMessageOrderPersistence_1() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session sessSend = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = sessSend.createProducer(queue1); @@ -226,64 +208,62 @@ public class PersistenceTest extends JMSTestCase MessageConsumer cons = sessReceive.createConsumer(queue1); { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("j", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("i", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("h", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("g", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("f", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("e", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("d", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("c", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("b", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("a", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(500); + TextMessage t = (TextMessage) cons.receive(500); ProxyAssertSupport.assertNull(t); } } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -293,12 +273,10 @@ public class PersistenceTest extends JMSTestCase * Second test that message order survives a restart */ @Test - public void testMessageOrderPersistence_2() throws Exception - { + public void testMessageOrderPersistence_2() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session sessSend = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = sessSend.createProducer(queue1); @@ -339,64 +317,62 @@ public class PersistenceTest extends JMSTestCase MessageConsumer cons = sessReceive.createConsumer(queue1); { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("j", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("h", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("i", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("f", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("g", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("d", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("e", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("a", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("b", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("c", t.getText()); } { - TextMessage t = (TextMessage)cons.receiveNoWait(); + TextMessage t = (TextMessage) cons.receiveNoWait(); ProxyAssertSupport.assertNull(t); } } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -406,12 +382,10 @@ public class PersistenceTest extends JMSTestCase * Test durable subscription state survives a server crash */ @Test - public void testDurableSubscriptionPersistence_1() throws Exception - { + public void testDurableSubscriptionPersistence_1() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); conn.setClientID("five"); @@ -442,7 +416,7 @@ public class PersistenceTest extends JMSTestCase ds = s.createDurableSubscriber(ActiveMQServerTestCase.topic1, "sub", null, false); - TextMessage rm = (TextMessage)ds.receive(3000); + TextMessage rm = (TextMessage) ds.receive(3000); ProxyAssertSupport.assertNotNull(rm); ProxyAssertSupport.assertEquals("thebody", rm.getText()); @@ -450,10 +424,8 @@ public class PersistenceTest extends JMSTestCase s.unsubscribe("sub"); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -463,12 +435,10 @@ public class PersistenceTest extends JMSTestCase * Test durable subscription state survives a restart */ @Test - public void testDurableSubscriptionPersistence_2() throws Exception - { + public void testDurableSubscriptionPersistence_2() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); conn.setClientID("Sausages"); @@ -482,8 +452,7 @@ public class PersistenceTest extends JMSTestCase MessageProducer prod = sessSend.createProducer(ActiveMQServerTestCase.topic1); prod.setDeliveryMode(DeliveryMode.PERSISTENT); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { TextMessage tm = sessSend.createTextMessage("message" + i); prod.send(tm); } @@ -507,28 +476,24 @@ public class PersistenceTest extends JMSTestCase sub2 = sessConsume.createDurableSubscriber(ActiveMQServerTestCase.topic1, "sub2", null, false); sub3 = sessConsume.createDurableSubscriber(ActiveMQServerTestCase.topic1, "sub3", null, false); - for (int i = 0; i < 10; i++) - { - TextMessage tm1 = (TextMessage)sub1.receive(3000); + for (int i = 0; i < 10; i++) { + TextMessage tm1 = (TextMessage) sub1.receive(3000); ProxyAssertSupport.assertNotNull(tm1); - if (tm1 == null) - { + if (tm1 == null) { break; } ProxyAssertSupport.assertEquals("message" + i, tm1.getText()); - TextMessage tm2 = (TextMessage)sub2.receive(3000); + TextMessage tm2 = (TextMessage) sub2.receive(3000); ProxyAssertSupport.assertNotNull(tm2); - if (tm2 == null) - { + if (tm2 == null) { break; } ProxyAssertSupport.assertEquals("message" + i, tm2.getText()); - TextMessage tm3 = (TextMessage)sub3.receive(3000); + TextMessage tm3 = (TextMessage) sub3.receive(3000); ProxyAssertSupport.assertNotNull(tm3); - if (tm3 == null) - { + if (tm3 == null) { break; } ProxyAssertSupport.assertEquals("message" + i, tm3.getText()); @@ -542,10 +507,8 @@ public class PersistenceTest extends JMSTestCase sessConsume.unsubscribe("sub2"); sessConsume.unsubscribe("sub3"); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/QueueReceiverTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/QueueReceiverTest.java index bf6dc98cd2..1b56ee21a3 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/QueueReceiverTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/QueueReceiverTest.java @@ -26,18 +26,16 @@ import javax.jms.TextMessage; import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; import org.junit.Test; -public class QueueReceiverTest extends JMSTestCase -{ +public class QueueReceiverTest extends JMSTestCase { + /** * com.sun.ts.tests.jms.ee.all.queueconn.QueueConnTest line 171 */ @Test - public void testCreateReceiverWithMessageSelector() throws Exception - { + public void testCreateReceiverWithMessageSelector() throws Exception { QueueConnection qc = null; - try - { + try { qc = createQueueConnection(); QueueSession qs = qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); @@ -58,14 +56,12 @@ public class QueueReceiverTest extends JMSTestCase qsender.send(m); - TextMessage rm = (TextMessage)qreceiver.receive(1000); + TextMessage rm = (TextMessage) qreceiver.receive(1000); ProxyAssertSupport.assertEquals("two", rm.getText()); } - finally - { - if (qc != null) - { + finally { + if (qc != null) { qc.close(); } Thread.sleep(2000); diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/QueueTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/QueueTest.java index f2f35d8b49..c4c4185c17 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/QueueTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/QueueTest.java @@ -29,19 +29,16 @@ import java.util.Set; import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; import org.junit.Test; -public class QueueTest extends JMSTestCase -{ +public class QueueTest extends JMSTestCase { /** * The simplest possible queue test. */ @Test - public void testQueue() throws Exception - { + public void testQueue() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -54,10 +51,8 @@ public class QueueTest extends JMSTestCase ProxyAssertSupport.assertEquals("payload", m.getText()); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -65,8 +60,7 @@ public class QueueTest extends JMSTestCase // http://jira.jboss.com/jira/browse/JBMESSAGING-1101 @Test - public void testBytesMessagePersistence() throws Exception - { + public void testBytesMessagePersistence() throws Exception { Connection conn = null; byte[] bytes = new byte[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 123, 55, 0, 12, -100, -11}; @@ -75,8 +69,7 @@ public class QueueTest extends JMSTestCase MessageProducer prod = sess.createProducer(queue1); prod.setDeliveryMode(DeliveryMode.PERSISTENT); - for (int i = 0; i < 1; i++) - { + for (int i = 0; i < 1; i++) { BytesMessage bm = sess.createBytesMessage(); bm.writeBytes(bytes); @@ -97,8 +90,7 @@ public class QueueTest extends JMSTestCase sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); conn.start(); MessageConsumer cons = sess.createConsumer(queue1); - for (int i = 0; i < 1; i++) - { + for (int i = 0; i < 1; i++) { BytesMessage bm = (BytesMessage) cons.receive(3000); ProxyAssertSupport.assertNotNull(bm); @@ -107,8 +99,7 @@ public class QueueTest extends JMSTestCase bm.readBytes(bytes2); - for (int j = 0; j < bytes.length; j++) - { + for (int j = 0; j < bytes.length; j++) { ProxyAssertSupport.assertEquals(bytes[j], bytes2[j]); } } @@ -116,17 +107,14 @@ public class QueueTest extends JMSTestCase // added for http://jira.jboss.org/jira/browse/JBMESSAGING-899 @Test - public void testClosedConsumerAfterStart() throws Exception - { + public void testClosedConsumerAfterStart() throws Exception { // This loop is to increase chances of a failure. - for (int counter = 0; counter < 20; counter++) - { + for (int counter = 0; counter < 20; counter++) { Connection conn1 = null; Connection conn2 = null; - try - { + try { conn1 = createConnection(); conn2 = createConnection(); @@ -135,8 +123,7 @@ public class QueueTest extends JMSTestCase MessageProducer p = s.createProducer(queue1); - for (int i = 0; i < 20; i++) - { + for (int i = 0; i < 20; i++) { p.send(s.createTextMessage("message " + i)); } @@ -157,15 +144,13 @@ public class QueueTest extends JMSTestCase // There is nothing much we can do about this Set texts = new HashSet(); - for (int i = 0; i < 20; i++) - { + for (int i = 0; i < 20; i++) { TextMessage txt = (TextMessage) c2.receive(5000); ProxyAssertSupport.assertNotNull(txt); texts.add(txt.getText()); } - for (int i = 0; i < 20; i++) - { + for (int i = 0; i < 20; i++) { ProxyAssertSupport.assertTrue(texts.contains("message " + i)); } @@ -173,14 +158,11 @@ public class QueueTest extends JMSTestCase checkEmpty(queue1); } - finally - { - if (conn1 != null) - { + finally { + if (conn1 != null) { conn1.close(); } - if (conn2 != null) - { + if (conn2 != null) { conn2.close(); } } @@ -188,8 +170,7 @@ public class QueueTest extends JMSTestCase } @Test - public void testRedeployQueue() throws Exception - { + public void testRedeployQueue() throws Exception { Connection conn = createConnection(); Session s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -197,8 +178,7 @@ public class QueueTest extends JMSTestCase MessageConsumer c = s.createConsumer(queue1); conn.start(); - for (int i = 0; i < 500; i++) - { + for (int i = 0; i < 500; i++) { p.send(s.createTextMessage("payload " + i)); } @@ -216,8 +196,7 @@ public class QueueTest extends JMSTestCase c = s.createConsumer(queue1); conn.start(); - for (int i = 0; i < 500; i++) - { + for (int i = 0; i < 500; i++) { TextMessage message = (TextMessage) c.receive(3000); ProxyAssertSupport.assertNotNull(message); ProxyAssertSupport.assertNotNull(message.getJMSDestination()); @@ -225,8 +204,7 @@ public class QueueTest extends JMSTestCase } @Test - public void testQueueName() throws Exception - { + public void testQueueName() throws Exception { ProxyAssertSupport.assertEquals("Queue1", queue1.getQueueName()); } } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/ReferenceableTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/ReferenceableTest.java index d85b7ec590..2cebf045d9 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/ReferenceableTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/ReferenceableTest.java @@ -42,8 +42,7 @@ import org.junit.Test; *
    * All administered objects should be referenceable and serializable as per spec 4.2 */ -public class ReferenceableTest extends JMSTestCase -{ +public class ReferenceableTest extends JMSTestCase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -56,8 +55,7 @@ public class ReferenceableTest extends JMSTestCase @SuppressWarnings("cast") @Test - public void testSerializable() throws Exception - { + public void testSerializable() throws Exception { ProxyAssertSupport.assertTrue(cf instanceof Serializable); ProxyAssertSupport.assertTrue(queue1 instanceof Serializable); @@ -67,8 +65,7 @@ public class ReferenceableTest extends JMSTestCase @SuppressWarnings("cast") @Test - public void testReferenceable() throws Exception - { + public void testReferenceable() throws Exception { ProxyAssertSupport.assertTrue(cf instanceof Referenceable); ProxyAssertSupport.assertTrue(queue1 instanceof Referenceable); @@ -77,8 +74,7 @@ public class ReferenceableTest extends JMSTestCase } @Test - public void testReferenceCF() throws Exception - { + public void testReferenceCF() throws Exception { Reference cfRef = ((Referenceable) cf).getReference(); String factoryName = cfRef.getFactoryClassName(); @@ -97,8 +93,7 @@ public class ReferenceableTest extends JMSTestCase } @Test - public void testReferenceQueue() throws Exception - { + public void testReferenceQueue() throws Exception { Reference queueRef = ((Referenceable) queue1).getReference(); String factoryName = queueRef.getFactoryClassName(); @@ -119,8 +114,7 @@ public class ReferenceableTest extends JMSTestCase } @Test - public void testReferenceTopic() throws Exception - { + public void testReferenceTopic() throws Exception { Reference topicRef = ((Referenceable) ActiveMQServerTestCase.topic1).getReference(); String factoryName = topicRef.getFactoryClassName(); @@ -140,8 +134,7 @@ public class ReferenceableTest extends JMSTestCase simpleSendReceive(cf, topic2); } - protected void simpleSendReceive(final ConnectionFactory cf1, final Destination dest) throws Exception - { + protected void simpleSendReceive(final ConnectionFactory cf1, final Destination dest) throws Exception { Connection conn = createConnection(cf1); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/SecurityTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/SecurityTest.java index 6b9482a7e6..5cbddd65b1 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/SecurityTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/SecurityTest.java @@ -30,14 +30,13 @@ import org.junit.Test; *
    * This test must be run with the Test security config. on the server */ -public class SecurityTest extends JMSTestCase -{ +public class SecurityTest extends JMSTestCase { + /** * Login with no user, no password Should allow login (equivalent to guest) */ @Test - public void testLoginNoUserNoPassword() throws Exception - { + public void testLoginNoUserNoPassword() throws Exception { createConnection(); createConnection(null, null); } @@ -47,8 +46,7 @@ public class SecurityTest extends JMSTestCase * Should allow login (equivalent to guest) */ @Test - public void testLoginNoUserNoPasswordWithNoGuest() throws Exception - { + public void testLoginNoUserNoPasswordWithNoGuest() throws Exception { createConnection(); createConnection(null, null); } @@ -58,8 +56,7 @@ public class SecurityTest extends JMSTestCase * Should allow */ @Test - public void testLoginValidUserAndPassword() throws Exception - { + public void testLoginValidUserAndPassword() throws Exception { createConnection("guest", "guest"); } @@ -68,15 +65,12 @@ public class SecurityTest extends JMSTestCase * Should allow */ @Test - public void testLoginValidUserInvalidPassword() throws Exception - { - try - { + public void testLoginValidUserInvalidPassword() throws Exception { + try { Connection conn1 = createConnection("guest", "not.the.valid.password"); ProxyAssertSupport.fail(); } - catch (JMSSecurityException e) - { + catch (JMSSecurityException e) { // Expected } } @@ -86,15 +80,12 @@ public class SecurityTest extends JMSTestCase * Should allow */ @Test - public void testLoginInvalidUserInvalidPassword() throws Exception - { - try - { + public void testLoginInvalidUserInvalidPassword() throws Exception { + try { Connection conn1 = createConnection("not.the.valid.user", "not.the.valid.password"); ProxyAssertSupport.fail(); } - catch (JMSSecurityException e) - { + catch (JMSSecurityException e) { // Expected } } @@ -105,21 +96,17 @@ public class SecurityTest extends JMSTestCase * user/pwd with preconfigured clientID, should return preconf */ @Test - public void testPreConfClientID() throws Exception - { + public void testPreConfClientID() throws Exception { Connection conn = null; - try - { + try { ActiveMQServerTestCase.deployConnectionFactory("dilbert-id", "preConfcf", "preConfcf"); ConnectionFactory cf = (ConnectionFactory) getInitialContext().lookup("preConfcf"); conn = cf.createConnection("guest", "guest"); String clientID = conn.getClientID(); ProxyAssertSupport.assertEquals("Invalid ClientID", "dilbert-id", clientID); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } ActiveMQServerTestCase.undeployConnectionFactory("preConfcf"); @@ -130,8 +117,7 @@ public class SecurityTest extends JMSTestCase * Try setting client ID */ @Test - public void testSetClientID() throws Exception - { + public void testSetClientID() throws Exception { Connection conn = createConnection(); conn.setClientID("myID"); String clientID = conn.getClientID(); @@ -142,25 +128,20 @@ public class SecurityTest extends JMSTestCase * Try setting client ID on preconfigured connection - should throw exception */ @Test - public void testSetClientIDPreConf() throws Exception - { + public void testSetClientIDPreConf() throws Exception { Connection conn = null; - try - { + try { ActiveMQServerTestCase.deployConnectionFactory("dilbert-id", "preConfcf", "preConfcf"); ConnectionFactory cf = (ConnectionFactory) getInitialContext().lookup("preConfcf"); conn = cf.createConnection("guest", "guest"); conn.setClientID("myID"); ProxyAssertSupport.fail(); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // Expected } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } ActiveMQServerTestCase.undeployConnectionFactory("preConfcf"); @@ -171,17 +152,14 @@ public class SecurityTest extends JMSTestCase * Try setting client ID after an operation has been performed on the connection */ @Test - public void testSetClientIDAfterOp() throws Exception - { + public void testSetClientIDAfterOp() throws Exception { Connection conn = createConnection(); conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - try - { + try { conn.setClientID("myID"); ProxyAssertSupport.fail(); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // Expected } } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/SessionTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/SessionTest.java index 165788e1fa..887fdecd6c 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/SessionTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/SessionTest.java @@ -38,8 +38,7 @@ import org.apache.activemq.artemis.core.settings.impl.AddressSettings; import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; import org.junit.Test; -public class SessionTest extends ActiveMQServerTestCase -{ +public class SessionTest extends ActiveMQServerTestCase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -51,8 +50,7 @@ public class SessionTest extends ActiveMQServerTestCase // Public -------------------------------------------------------- @Test - public void testCreateProducer() throws Exception - { + public void testCreateProducer() throws Exception { Connection conn = getConnectionFactory().createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); sess.createProducer(ActiveMQServerTestCase.topic1); @@ -60,8 +58,7 @@ public class SessionTest extends ActiveMQServerTestCase } @Test - public void testCreateProducerOnNullQueue() throws Exception - { + public void testCreateProducerOnNullQueue() throws Exception { Connection conn = getConnectionFactory().createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); Message m = sess.createTextMessage("something"); @@ -74,7 +71,7 @@ public class SessionTest extends ActiveMQServerTestCase conn.start(); // receiveNoWait is not guaranteed to return message immediately - TextMessage rm = (TextMessage)c.receive(1000); + TextMessage rm = (TextMessage) c.receive(1000); ProxyAssertSupport.assertEquals("something", rm.getText()); @@ -82,8 +79,7 @@ public class SessionTest extends ActiveMQServerTestCase } @Test - public void testCreateConsumer() throws Exception - { + public void testCreateConsumer() throws Exception { Connection conn = getConnectionFactory().createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -92,8 +88,7 @@ public class SessionTest extends ActiveMQServerTestCase } @Test - public void testGetSession2() throws Exception - { + public void testGetSession2() throws Exception { deployConnectionFactory(0, JMSFactoryType.CF, "ConnectionFactory", "/ConnectionFactory"); XAConnection conn = getXAConnectionFactory().createXAConnection(); XASession sess = conn.createXASession(); @@ -107,67 +102,57 @@ public class SessionTest extends ActiveMQServerTestCase // @Test - public void testCreateNonExistentQueue() throws Exception - { + public void testCreateNonExistentQueue() throws Exception { AddressSettings addressSettings = new AddressSettings(); addressSettings.setAutoCreateJmsQueues(false); getJmsServer().getAddressSettingsRepository().addMatch("#", addressSettings); Connection conn = getConnectionFactory().createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - try - { + try { sess.createQueue("QueueThatDoesNotExist"); ProxyAssertSupport.fail(); } - catch (JMSException e) - { + catch (JMSException e) { } conn.close(); } @Test - public void testCreateQueueOnATopicSession() throws Exception - { - TopicConnection c = (TopicConnection)getConnectionFactory().createConnection(); + public void testCreateQueueOnATopicSession() throws Exception { + TopicConnection c = (TopicConnection) getConnectionFactory().createConnection(); TopicSession s = c.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - try - { + try { s.createQueue("TestQueue"); ProxyAssertSupport.fail("should throw IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } c.close(); } @Test - public void testCreateQueueWhileTopicWithSameNameExists() throws Exception - { + public void testCreateQueueWhileTopicWithSameNameExists() throws Exception { AddressSettings addressSettings = new AddressSettings(); addressSettings.setAutoCreateJmsQueues(false); getJmsServer().getAddressSettingsRepository().addMatch("#", addressSettings); Connection conn = getConnectionFactory().createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - try - { + try { sess.createQueue("TestTopic"); ProxyAssertSupport.fail("should throw JMSException"); } - catch (JMSException e) - { + catch (JMSException e) { // OK } conn.close(); } @Test - public void testCreateQueue() throws Exception - { + public void testCreateQueue() throws Exception { Connection conn = getConnectionFactory().createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = sess.createQueue("Queue1"); @@ -186,60 +171,50 @@ public class SessionTest extends ActiveMQServerTestCase } @Test - public void testCreateNonExistentTopic() throws Exception - { + public void testCreateNonExistentTopic() throws Exception { Connection conn = getConnectionFactory().createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - try - { + try { sess.createTopic("TopicThatDoesNotExist"); ProxyAssertSupport.fail("should throw JMSException"); } - catch (JMSException e) - { + catch (JMSException e) { // OK } conn.close(); } @Test - public void testCreateTopicOnAQueueSession() throws Exception - { - QueueConnection c = (QueueConnection)getConnectionFactory().createConnection(); + public void testCreateTopicOnAQueueSession() throws Exception { + QueueConnection c = (QueueConnection) getConnectionFactory().createConnection(); QueueSession s = c.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); - try - { + try { s.createTopic("TestTopic"); ProxyAssertSupport.fail("should throw IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } c.close(); } @Test - public void testCreateTopicWhileQueueWithSameNameExists() throws Exception - { + public void testCreateTopicWhileQueueWithSameNameExists() throws Exception { Connection conn = getConnectionFactory().createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - try - { + try { sess.createTopic("TestQueue"); ProxyAssertSupport.fail("should throw JMSException"); } - catch (JMSException e) - { + catch (JMSException e) { // OK } conn.close(); } @Test - public void testCreateTopic() throws Exception - { + public void testCreateTopic() throws Exception { Connection conn = getConnectionFactory().createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -251,27 +226,23 @@ public class SessionTest extends ActiveMQServerTestCase MessageConsumer consumer = sess.createConsumer(topic); conn.start(); - class TestRunnable implements Runnable - { + class TestRunnable implements Runnable { + boolean exceptionThrown; public Message m; MessageConsumer consumer; - TestRunnable(final MessageConsumer consumer) - { + TestRunnable(final MessageConsumer consumer) { this.consumer = consumer; } - public void run() - { - try - { + public void run() { + try { m = consumer.receive(3000); } - catch (Exception e) - { + catch (Exception e) { exceptionThrown = true; } } @@ -293,8 +264,7 @@ public class SessionTest extends ActiveMQServerTestCase } @Test - public void testGetXAResource2() throws Exception - { + public void testGetXAResource2() throws Exception { XAConnection conn = getXAConnectionFactory().createXAConnection(); XASession sess = conn.createXASession(); @@ -303,8 +273,7 @@ public class SessionTest extends ActiveMQServerTestCase } @Test - public void testIllegalState() throws Exception - { + public void testIllegalState() throws Exception { // IllegalStateException should be thrown if commit or rollback // is invoked on a non transacted session Connection conn = getConnectionFactory().createConnection(); @@ -315,22 +284,18 @@ public class SessionTest extends ActiveMQServerTestCase Message m = sess.createTextMessage("hello"); prod.send(m); - try - { + try { sess.rollback(); ProxyAssertSupport.fail(); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { } - try - { + try { sess.commit(); ProxyAssertSupport.fail(); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { } conn.close(); @@ -343,8 +308,7 @@ public class SessionTest extends ActiveMQServerTestCase // @Test - public void testCreateTwoSessions() throws Exception - { + public void testCreateTwoSessions() throws Exception { Connection conn = getConnectionFactory().createConnection(); Session sessionOne = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); ProxyAssertSupport.assertFalse(sessionOne.getTransacted()); @@ -359,8 +323,7 @@ public class SessionTest extends ActiveMQServerTestCase } @Test - public void testCloseAndCreateSession() throws Exception - { + public void testCloseAndCreateSession() throws Exception { Connection c = getConnectionFactory().createConnection(); Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -374,8 +337,7 @@ public class SessionTest extends ActiveMQServerTestCase } @Test - public void testCloseNoClientAcknowledgment() throws Exception - { + public void testCloseNoClientAcknowledgment() throws Exception { // send a message to the queue Connection conn = getConnectionFactory().createConnection(); @@ -387,7 +349,7 @@ public class SessionTest extends ActiveMQServerTestCase s = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); conn.start(); - TextMessage m = (TextMessage)s.createConsumer(queue1).receive(1000); + TextMessage m = (TextMessage) s.createConsumer(queue1).receive(1000); ProxyAssertSupport.assertEquals("wont_ack", m.getText()); @@ -397,7 +359,7 @@ public class SessionTest extends ActiveMQServerTestCase // get the message again s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - m = (TextMessage)s.createConsumer(queue1).receive(1000); + m = (TextMessage) s.createConsumer(queue1).receive(1000); ProxyAssertSupport.assertEquals("wont_ack", m.getText()); @@ -405,8 +367,7 @@ public class SessionTest extends ActiveMQServerTestCase } @Test - public void testCloseInTransaction() throws Exception - { + public void testCloseInTransaction() throws Exception { // send a message to the queue Connection conn = getConnectionFactory().createConnection(); @@ -418,7 +379,7 @@ public class SessionTest extends ActiveMQServerTestCase Session session = conn.createSession(true, -1); conn.start(); - TextMessage m = (TextMessage)session.createConsumer(queue1).receive(1000); + TextMessage m = (TextMessage) session.createConsumer(queue1).receive(1000); ProxyAssertSupport.assertEquals("bex", m.getText()); @@ -439,7 +400,7 @@ public class SessionTest extends ActiveMQServerTestCase conn = getConnectionFactory().createConnection(); s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); conn.start(); - TextMessage rm = (TextMessage)s.createConsumer(queue1).receive(1000); + TextMessage rm = (TextMessage) s.createConsumer(queue1).receive(1000); ProxyAssertSupport.assertEquals("bex", rm.getText()); diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/TemporaryDestinationTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/TemporaryDestinationTest.java index c71c7a112a..9357b1c4fa 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/TemporaryDestinationTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/TemporaryDestinationTest.java @@ -30,8 +30,7 @@ import javax.naming.NamingException; import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; import org.junit.Test; -public class TemporaryDestinationTest extends JMSTestCase -{ +public class TemporaryDestinationTest extends JMSTestCase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -43,12 +42,10 @@ public class TemporaryDestinationTest extends JMSTestCase // Public -------------------------------------------------------- @Test - public void testTemp() throws Exception - { + public void testTemp() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session producerSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -75,13 +72,11 @@ public class TemporaryDestinationTest extends JMSTestCase ProxyAssertSupport.assertEquals(messageText, m2.getText()); - try - { + try { tempTopic.delete(); ProxyAssertSupport.fail(); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // Can't delete temp dest if there are open consumers } @@ -89,22 +84,18 @@ public class TemporaryDestinationTest extends JMSTestCase tempTopic.delete(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testTemporaryQueueBasic() throws Exception - { + public void testTemporaryQueueBasic() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session producerSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -131,10 +122,8 @@ public class TemporaryDestinationTest extends JMSTestCase ProxyAssertSupport.assertEquals(messageText, m2.getText()); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -144,44 +133,36 @@ public class TemporaryDestinationTest extends JMSTestCase * http://jira.jboss.com/jira/browse/JBMESSAGING-93 */ @Test - public void testTemporaryQueueOnClosedSession() throws Exception - { + public void testTemporaryQueueOnClosedSession() throws Exception { Connection producerConnection = null; - try - { + try { producerConnection = createConnection(); Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); producerSession.close(); - try - { + try { producerSession.createTemporaryQueue(); ProxyAssertSupport.fail("should throw exception"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } } } @Test - public void testTemporaryQueueDeleteWithConsumer() throws Exception - { + public void testTemporaryQueueDeleteWithConsumer() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session producerSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -192,35 +173,29 @@ public class TemporaryDestinationTest extends JMSTestCase MessageConsumer consumer = consumerSession.createConsumer(tempQueue); - try - { + try { tempQueue.delete(); ProxyAssertSupport.fail("Should throw JMSException"); } - catch (JMSException e) - { + catch (JMSException e) { // Should fail - you can't delete a temp queue if it has active consumers } consumer.close(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testTemporaryTopicDeleteWithConsumer() throws Exception - { + public void testTemporaryTopicDeleteWithConsumer() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session producerSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -231,35 +206,29 @@ public class TemporaryDestinationTest extends JMSTestCase MessageConsumer consumer = consumerSession.createConsumer(tempTopic); - try - { + try { tempTopic.delete(); ProxyAssertSupport.fail("Should throw JMSException"); } - catch (JMSException e) - { + catch (JMSException e) { // Should fail - you can't delete a temp topic if it has active consumers } consumer.close(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testTemporaryQueueDeleted() throws Exception - { + public void testTemporaryQueueDeleted() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session producerSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -293,31 +262,25 @@ public class TemporaryDestinationTest extends JMSTestCase tempQueue.delete(); conn.close(); conn = createConnection("guest", "guest"); - try - { + try { producer.send(m); ProxyAssertSupport.fail(); } - catch (JMSException e) - { + catch (JMSException e) { } } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testTemporaryTopicBasic() throws Exception - { + public void testTemporaryTopicBasic() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session producerSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -336,18 +299,14 @@ public class TemporaryDestinationTest extends JMSTestCase final Message m = producerSession.createTextMessage(messageText); - Thread t = new Thread(new Runnable() - { - public void run() - { - try - { + Thread t = new Thread(new Runnable() { + public void run() { + try { // this is needed to make sure the main thread has enough time to block Thread.sleep(500); producer.send(m); } - catch (Exception e) - { + catch (Exception e) { log.error(e); } } @@ -362,10 +321,8 @@ public class TemporaryDestinationTest extends JMSTestCase t.join(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -375,40 +332,33 @@ public class TemporaryDestinationTest extends JMSTestCase * http://jira.jboss.com/jira/browse/JBMESSAGING-93 */ @Test - public void testTemporaryTopicOnClosedSession() throws Exception - { + public void testTemporaryTopicOnClosedSession() throws Exception { Connection producerConnection = null; - try - { + try { producerConnection = createConnection(); Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); producerSession.close(); - try - { + try { producerSession.createTemporaryTopic(); ProxyAssertSupport.fail("should throw exception"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { // OK } } - finally - { - if (producerConnection != null) - { + finally { + if (producerConnection != null) { producerConnection.close(); } } } @Test - public void testTemporaryTopicShouldNotBeInJNDI() throws Exception - { + public void testTemporaryTopicShouldNotBeInJNDI() throws Exception { Connection producerConnection = createConnection(); Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -416,20 +366,17 @@ public class TemporaryDestinationTest extends JMSTestCase TemporaryTopic tempTopic = producerSession.createTemporaryTopic(); String topicName = tempTopic.getTopicName(); - try - { + try { ic.lookup("/topic/" + topicName); ProxyAssertSupport.fail("The temporary queue should not be bound to JNDI"); } - catch (NamingException e) - { + catch (NamingException e) { // Expected } } @Test - public void testTemporaryQueueShouldNotBeInJNDI() throws Exception - { + public void testTemporaryQueueShouldNotBeInJNDI() throws Exception { Connection producerConnection = createConnection(); Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -437,13 +384,11 @@ public class TemporaryDestinationTest extends JMSTestCase TemporaryQueue tempQueue = producerSession.createTemporaryQueue(); String queueName = tempQueue.getQueueName(); - try - { + try { ic.lookup("/queue/" + queueName); ProxyAssertSupport.fail("The temporary queue should not be bound to JNDI"); } - catch (NamingException e) - { + catch (NamingException e) { // Expected } } @@ -452,8 +397,7 @@ public class TemporaryDestinationTest extends JMSTestCase * https://jira.jboss.org/jira/browse/JBMESSAGING-1566 */ @Test - public void testCanNotCreateConsumerFromAnotherConnectionForTemporaryQueue() throws Exception - { + public void testCanNotCreateConsumerFromAnotherConnectionForTemporaryQueue() throws Exception { Connection conn = createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -464,13 +408,11 @@ public class TemporaryDestinationTest extends JMSTestCase Session sessFromAnotherConn = anotherConn.createSession(false, Session.AUTO_ACKNOWLEDGE); - try - { + try { sessFromAnotherConn.createConsumer(tempQueue); ProxyAssertSupport.fail("Only temporary destination's own connection is allowed to create MessageConsumers for them."); } - catch (JMSException e) - { + catch (JMSException e) { } conn.close(); @@ -481,8 +423,7 @@ public class TemporaryDestinationTest extends JMSTestCase * https://jira.jboss.org/jira/browse/JBMESSAGING-1566 */ @Test - public void testCanNotCreateConsumerFromAnotherCnnectionForTemporaryTopic() throws Exception - { + public void testCanNotCreateConsumerFromAnotherCnnectionForTemporaryTopic() throws Exception { Connection conn = createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -493,13 +434,11 @@ public class TemporaryDestinationTest extends JMSTestCase Session sessFromAnotherConn = anotherConn.createSession(false, Session.AUTO_ACKNOWLEDGE); - try - { + try { sessFromAnotherConn.createConsumer(tempTopic); ProxyAssertSupport.fail("Only temporary destination's own connection is allowed to create MessageConsumers for them."); } - catch (JMSException e) - { + catch (JMSException e) { } } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/TopicTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/TopicTest.java index 36d891eba3..9d616f80e1 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/TopicTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/TopicTest.java @@ -31,8 +31,7 @@ import java.io.Serializable; import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; import org.junit.Test; -public class TopicTest extends JMSTestCase -{ +public class TopicTest extends JMSTestCase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -47,8 +46,7 @@ public class TopicTest extends JMSTestCase * The simplest possible topic test. */ @Test - public void testTopic() throws Exception - { + public void testTopic() throws Exception { Connection conn = createConnection(); Session s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -63,8 +61,7 @@ public class TopicTest extends JMSTestCase } @Test - public void testTopic2() throws Exception - { + public void testTopic2() throws Exception { Connection conn = createConnection(); Session s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -79,8 +76,7 @@ public class TopicTest extends JMSTestCase } @Test - public void testTopicName() throws Exception - { + public void testTopicName() throws Exception { Topic topic = (Topic) ic.lookup("/topic/Topic1"); ProxyAssertSupport.assertEquals("Topic1", topic.getTopicName()); } @@ -89,8 +85,7 @@ public class TopicTest extends JMSTestCase * See http://jira.jboss.com/jira/browse/JBMESSAGING-399 */ @Test - public void testRace() throws Exception - { + public void testRace() throws Exception { Connection conn = createConnection(); Session sSend = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -118,8 +113,7 @@ public class TopicTest extends JMSTestCase conn.start(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { byte[] blah = new byte[10000]; String str = new String(blah); @@ -147,51 +141,44 @@ public class TopicTest extends JMSTestCase // Inner classes ------------------------------------------------- - static class Wibble2 implements Serializable - { + static class Wibble2 implements Serializable { + private static final long serialVersionUID = -5146179676719808756L; String s; } - static class TestListener implements MessageListener - { + static class TestListener implements MessageListener { + boolean failed; int count; int num; - TestListener(final int num) - { + TestListener(final int num) { this.num = num; } - public synchronized void onMessage(final Message m) - { + public synchronized void onMessage(final Message m) { ObjectMessage om = (ObjectMessage) m; - try - { + try { Wibble2 w = (Wibble2) om.getObject(); } - catch (Exception e) - { + catch (Exception e) { failed = true; } count++; - if (count == num) - { + if (count == num) { notify(); } } - synchronized void waitForMessages() throws Exception - { - while (count < num) - { + synchronized void waitForMessages() throws Exception { + while (count < num) { this.wait(); } } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/TransactedSessionTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/TransactedSessionTest.java index 73a0d2a11f..b7422dc67c 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/TransactedSessionTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/TransactedSessionTest.java @@ -32,16 +32,14 @@ import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; import org.junit.Assert; import org.junit.Test; -public class TransactedSessionTest extends JMSTestCase -{ +public class TransactedSessionTest extends JMSTestCase { + @Test - public void testSimpleRollback() throws Exception - { + public void testSimpleRollback() throws Exception { // send a message Connection conn = null; - try - { + try { conn = createConnection(); Session s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); s.createProducer(queue1).send(s.createTextMessage("one")); @@ -73,10 +71,8 @@ public class TransactedSessionTest extends JMSTestCase ProxyAssertSupport.assertEquals(1, i.intValue()); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } removeAllMessages(queue1.getQueueName(), true); @@ -84,12 +80,10 @@ public class TransactedSessionTest extends JMSTestCase } @Test - public void testRedeliveredFlagTopic() throws Exception - { + public void testRedeliveredFlagTopic() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session sessSend = conn.createSession(true, Session.SESSION_TRANSACTED); @@ -117,10 +111,8 @@ public class TransactedSessionTest extends JMSTestCase sess1.commit(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -130,12 +122,10 @@ public class TransactedSessionTest extends JMSTestCase * Test redelivery works ok for Topic */ @Test - public void testRedeliveredTopic() throws Exception - { + public void testRedeliveredTopic() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session sess = conn.createSession(true, Session.SESSION_TRANSACTED); @@ -164,22 +154,18 @@ public class TransactedSessionTest extends JMSTestCase sess.commit(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testReceivedRollbackTopic() throws Exception - { + public void testReceivedRollbackTopic() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session sess = conn.createSession(true, Session.SESSION_TRANSACTED); @@ -219,10 +205,8 @@ public class TransactedSessionTest extends JMSTestCase ProxyAssertSupport.assertEquals(mRec.getText(), mRec2.getText()); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -233,12 +217,10 @@ public class TransactedSessionTest extends JMSTestCase * Verify message are not received by consumer. */ @Test - public void testSendNoCommitTopic() throws Exception - { + public void testSendNoCommitTopic() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session producerSess = conn.createSession(true, Session.SESSION_TRANSACTED); @@ -251,8 +233,7 @@ public class TransactedSessionTest extends JMSTestCase final int NUM_MESSAGES = 10; // Send some messages - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); producer.send(m); } @@ -260,10 +241,8 @@ public class TransactedSessionTest extends JMSTestCase Message m = consumer.receive(500); ProxyAssertSupport.assertNull(m); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -274,12 +253,10 @@ public class TransactedSessionTest extends JMSTestCase * Verify message are received by consumer. */ @Test - public void testSendCommitTopic() throws Exception - { + public void testSendCommitTopic() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session producerSess = conn.createSession(true, Session.SESSION_TRANSACTED); @@ -292,8 +269,7 @@ public class TransactedSessionTest extends JMSTestCase final int NUM_MESSAGES = 10; // Send some messages - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); producer.send(m); } @@ -301,11 +277,9 @@ public class TransactedSessionTest extends JMSTestCase producerSess.commit(); int count = 0; - while (true) - { + while (true) { Message m = consumer.receive(500); - if (m == null) - { + if (m == null) { break; } count++; @@ -313,10 +287,8 @@ public class TransactedSessionTest extends JMSTestCase ProxyAssertSupport.assertEquals(NUM_MESSAGES, count); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -330,12 +302,10 @@ public class TransactedSessionTest extends JMSTestCase * Create a new connection, session and consumer - verify messages are not redelivered */ @Test - public void testAckCommitTopic() throws Exception - { + public void testAckCommitTopic() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session producerSess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -348,17 +318,14 @@ public class TransactedSessionTest extends JMSTestCase final int NUM_MESSAGES = 10; // Send some messages - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); producer.send(m); } int count = 0; - while (true) - { + while (true) { Message m = consumer.receive(500); - if (m == null) - { + if (m == null) { break; } count++; @@ -383,10 +350,8 @@ public class TransactedSessionTest extends JMSTestCase ProxyAssertSupport.assertNull(m); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -400,12 +365,10 @@ public class TransactedSessionTest extends JMSTestCase */ @Test - public void testSendRollbackTopic() throws Exception - { + public void testSendRollbackTopic() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session producerSess = conn.createSession(true, Session.SESSION_TRANSACTED); @@ -418,8 +381,7 @@ public class TransactedSessionTest extends JMSTestCase final int NUM_MESSAGES = 10; // Send some messages - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); producer.send(m); } @@ -430,10 +392,8 @@ public class TransactedSessionTest extends JMSTestCase ProxyAssertSupport.assertNull(m); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -443,12 +403,10 @@ public class TransactedSessionTest extends JMSTestCase * Make sure redelivered flag is set on redelivery via rollback */ @Test - public void testRedeliveredQueue() throws Exception - { + public void testRedeliveredQueue() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session sess = conn.createSession(true, Session.SESSION_TRANSACTED); @@ -473,10 +431,8 @@ public class TransactedSessionTest extends JMSTestCase sess.commit(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -489,12 +445,10 @@ public class TransactedSessionTest extends JMSTestCase * session. */ @Test - public void testRedeliveredQueue2() throws Exception - { + public void testRedeliveredQueue2() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session sendSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -535,18 +489,15 @@ public class TransactedSessionTest extends JMSTestCase ProxyAssertSupport.assertTrue(tm.getJMSRedelivered()); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testReceivedRollbackQueue() throws Exception - { + public void testReceivedRollbackQueue() throws Exception { Connection conn = createConnection(); Session sess = conn.createSession(true, Session.SESSION_TRANSACTED); @@ -600,12 +551,10 @@ public class TransactedSessionTest extends JMSTestCase * Verify message are not received by consumer. */ @Test - public void testSendNoCommitQueue() throws Exception - { + public void testSendNoCommitQueue() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session producerSess = conn.createSession(true, Session.CLIENT_ACKNOWLEDGE); @@ -618,18 +567,15 @@ public class TransactedSessionTest extends JMSTestCase final int NUM_MESSAGES = 10; // Send some messages - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); producer.send(m); } checkEmpty(queue1); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -640,12 +586,10 @@ public class TransactedSessionTest extends JMSTestCase * Verify message are received by consumer. */ @Test - public void testSendCommitQueue() throws Exception - { + public void testSendCommitQueue() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session producerSess = conn.createSession(true, Session.CLIENT_ACKNOWLEDGE); @@ -658,8 +602,7 @@ public class TransactedSessionTest extends JMSTestCase final int NUM_MESSAGES = 10; // Send some messages - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); producer.send(m); } @@ -667,11 +610,9 @@ public class TransactedSessionTest extends JMSTestCase producerSess.commit(); int count = 0; - while (true) - { + while (true) { Message m = consumer.receive(500); - if (m == null) - { + if (m == null) { break; } count++; @@ -679,10 +620,8 @@ public class TransactedSessionTest extends JMSTestCase ProxyAssertSupport.assertEquals(NUM_MESSAGES, count); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } removeAllMessages(queue1.getQueueName(), true); @@ -690,12 +629,10 @@ public class TransactedSessionTest extends JMSTestCase } - public void _testSendCommitQueueCommitsInOrder() throws Exception - { + public void _testSendCommitQueueCommitsInOrder() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session producerSess = conn.createSession(true, Session.CLIENT_ACKNOWLEDGE); @@ -712,47 +649,37 @@ public class TransactedSessionTest extends JMSTestCase int sentId = 0; boolean started = false; // Send some messages - while (true) - { - try - { + while (true) { + try { Message m = producerSess.createMessage(); m.setIntProperty("foo", sentId); sentId++; producer.send(m); - if (sentId == 1 || System.currentTimeMillis() - lastBatchTime > 50) - { + if (sentId == 1 || System.currentTimeMillis() - lastBatchTime > 50) { lastBatchTime = System.currentTimeMillis(); producerSess.commit(); } } - catch (JMSException e) - { + catch (JMSException e) { //ignore connection closed by consumer } // wait for the first message to be received before we continue sending - if (!started) - { + if (!started) { Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); started = true; } - else - { - if (myReceiver.failed) - { + else { + if (myReceiver.failed) { throw myReceiver.e; } } } - } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } removeAllMessages(queue1.getQueueName(), true); @@ -760,8 +687,8 @@ public class TransactedSessionTest extends JMSTestCase } - class myReceiver implements MessageListener - { + class myReceiver implements MessageListener { + int count = 0; boolean started = false; private final CountDownLatch startLatch; @@ -770,41 +697,33 @@ public class TransactedSessionTest extends JMSTestCase private final Connection conn; - public myReceiver(CountDownLatch startLatch, Connection conn) - { + public myReceiver(CountDownLatch startLatch, Connection conn) { this.startLatch = startLatch; this.conn = conn; } - public void onMessage(Message message) - { - if (!started) - { + public void onMessage(Message message) { + if (!started) { startLatch.countDown(); started = true; } - try - { + try { int foo = message.getIntProperty("foo"); - if (foo != count) - { + if (foo != count) { e = new Exception("received out of order expected " + count + " received " + foo); failed = true; conn.close(); } count++; } - catch (JMSException e) - { + catch (JMSException e) { this.e = e; failed = true; - try - { + try { conn.close(); } - catch (JMSException e1) - { + catch (JMSException e1) { e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } @@ -815,32 +734,26 @@ public class TransactedSessionTest extends JMSTestCase * Test IllegateStateException is thrown if commit is called on a non-transacted session */ @Test - public void testCommitIllegalState() throws Exception - { + public void testCommitIllegalState() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session producerSess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); boolean thrown = false; - try - { + try { producerSess.commit(); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { thrown = true; } ProxyAssertSupport.assertTrue(thrown); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -854,12 +767,10 @@ public class TransactedSessionTest extends JMSTestCase * Create a new connection, session and consumer - verify messages are redelivered */ @Test - public void testAckNoCommitQueue() throws Exception - { + public void testAckNoCommitQueue() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); @@ -873,18 +784,15 @@ public class TransactedSessionTest extends JMSTestCase final int NUM_MESSAGES = 10; // Send some messages - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); producer.send(m); } int count = 0; - while (true) - { + while (true) { Message m = consumer.receive(500); - if (m == null) - { + if (m == null) { break; } count++; @@ -905,11 +813,9 @@ public class TransactedSessionTest extends JMSTestCase count = 0; - while (true) - { + while (true) { Message m = consumer.receive(500); - if (m == null) - { + if (m == null) { break; } count++; @@ -917,10 +823,8 @@ public class TransactedSessionTest extends JMSTestCase ProxyAssertSupport.assertEquals(NUM_MESSAGES, count); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } removeAllMessages(queue1.getQueueName(), true); @@ -935,12 +839,10 @@ public class TransactedSessionTest extends JMSTestCase * Create a new connection, session and consumer - verify messages are not redelivered */ @Test - public void testAckCommitQueue() throws Exception - { + public void testAckCommitQueue() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session producerSess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -953,18 +855,15 @@ public class TransactedSessionTest extends JMSTestCase final int NUM_MESSAGES = 10; // Send some messages - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); producer.send(m); } int count = 0; - while (true) - { + while (true) { Message m = consumer.receive(500); - if (m == null) - { + if (m == null) { break; } count++; @@ -989,10 +888,8 @@ public class TransactedSessionTest extends JMSTestCase ProxyAssertSupport.assertNull(m); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -1006,12 +903,10 @@ public class TransactedSessionTest extends JMSTestCase */ @Test - public void testSendRollbackQueue() throws Exception - { + public void testSendRollbackQueue() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session producerSess = conn.createSession(true, Session.AUTO_ACKNOWLEDGE); @@ -1024,8 +919,7 @@ public class TransactedSessionTest extends JMSTestCase final int NUM_MESSAGES = 10; // Send some messages - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); producer.send(m); } @@ -1036,10 +930,8 @@ public class TransactedSessionTest extends JMSTestCase ProxyAssertSupport.assertNull(m); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -1052,19 +944,16 @@ public class TransactedSessionTest extends JMSTestCase */ @Test - public void testRollbackIllegalState() throws Exception - { + public void testRollbackIllegalState() throws Exception { Connection conn = createConnection(); Session producerSess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); boolean thrown = false; - try - { + try { producerSess.rollback(); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { thrown = true; } @@ -1081,12 +970,10 @@ public class TransactedSessionTest extends JMSTestCase */ @Test - public void testAckRollbackQueue() throws Exception - { + public void testAckRollbackQueue() throws Exception { Connection conn = null; - try - { + try { conn = createConnection(); Session producerSess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -1099,18 +986,15 @@ public class TransactedSessionTest extends JMSTestCase final int NUM_MESSAGES = 10; // Send some messages - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); producer.send(m); } int count = 0; - while (true) - { + while (true) { Message m = consumer.receive(500); - if (m == null) - { + if (m == null) { break; } count++; @@ -1132,11 +1016,9 @@ public class TransactedSessionTest extends JMSTestCase conn.start(); count = 0; - while (true) - { + while (true) { Message m = consumer.receive(500); - if (m == null) - { + if (m == null) { break; } count++; @@ -1145,10 +1027,8 @@ public class TransactedSessionTest extends JMSTestCase ProxyAssertSupport.assertEquals(NUM_MESSAGES, count); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } removeAllMessages(queue1.getQueueName(), true); @@ -1161,8 +1041,7 @@ public class TransactedSessionTest extends JMSTestCase */ @Test - public void testSendMultipleQueue() throws Exception - { + public void testSendMultipleQueue() throws Exception { Connection conn = createConnection(); Session producerSess = conn.createSession(true, Session.AUTO_ACKNOWLEDGE); @@ -1177,10 +1056,8 @@ public class TransactedSessionTest extends JMSTestCase // Send some messages - for (int j = 0; j < NUM_TX; j++) - { - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int j = 0; j < NUM_TX; j++) { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); producer.send(m); } @@ -1189,11 +1066,9 @@ public class TransactedSessionTest extends JMSTestCase } int count = 0; - while (true) - { + while (true) { Message m = consumer.receive(500); - if (m == null) - { + if (m == null) { break; } count++; diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/BodyIsAssignableFromTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/BodyIsAssignableFromTest.java index 1b174101b2..d75c7f42dd 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/BodyIsAssignableFromTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/BodyIsAssignableFromTest.java @@ -31,48 +31,40 @@ import java.util.Map; import org.junit.Assert; import org.junit.Test; -public class BodyIsAssignableFromTest extends MessageBodyTestCase -{ +public class BodyIsAssignableFromTest extends MessageBodyTestCase { @Test - public void testText() throws JMSException - { + public void testText() throws JMSException { bodyAssignableFrom(JmsMessageType.TEXT, String.class, CharSequence.class, Comparable.class, Serializable.class); bodyNotAssignableFrom(JmsMessageType.TEXT, List.class, StringBuilder.class, Map.class, File.class); } @Test - public void testMap() throws JMSException - { + public void testMap() throws JMSException { bodyAssignableFrom(JmsMessageType.MAP, Map.class, Object.class); bodyNotAssignableFrom(JmsMessageType.MAP, String.class, CharSequence.class, Comparable.class, Serializable.class); } @Test - public void testStream() throws JMSException - { + public void testStream() throws JMSException { bodyNotAssignableFrom(JmsMessageType.STREAM, Object.class, Serializable.class); } @Test - public void testByte() throws JMSException - { + public void testByte() throws JMSException { bodyAssignableFrom(JmsMessageType.BYTE, Object.class, byte[].class); bodyNotAssignableFrom(JmsMessageType.BYTE, String.class, CharSequence.class, Comparable.class); } @Test - public void testObject() throws JMSException - { - bodyAssignableFrom(JmsMessageType.OBJECT, Object.class, Serializable.class, - Comparable.class, Double.class); + public void testObject() throws JMSException { + bodyAssignableFrom(JmsMessageType.OBJECT, Object.class, Serializable.class, Comparable.class, Double.class); // we are sending a Double in the body, so the de-serialized Object will be an instanceof these: bodyAssignableFrom(JmsMessageType.OBJECT, Comparable.class, Double.class); bodyNotAssignableFrom(JmsMessageType.OBJECT, String.class, CharSequence.class, List.class); } - private void bodyAssignableFrom(JmsMessageType type, Class... clazz) throws JMSException - { + private void bodyAssignableFrom(JmsMessageType type, Class... clazz) throws JMSException { bodyAssignableFrom(type, true, clazz); } @@ -82,40 +74,31 @@ public class BodyIsAssignableFromTest extends MessageBodyTestCase * @param bool * @throws JMSException */ - private void bodyAssignableFrom(final JmsMessageType type, final boolean bool, Class... clazz) throws JMSException - { + private void bodyAssignableFrom(final JmsMessageType type, final boolean bool, Class... clazz) throws JMSException { Assert.assertNotNull("clazz!=null", clazz); Assert.assertTrue("clazz[] not empty", clazz.length > 0); Object body = createBodySendAndReceive(type); Message msg = queueConsumer.receive(500); Assert.assertNotNull("must have a msg", msg); Assert.assertEquals(type.toString(), msg.getStringProperty("type")); - for (Class c : clazz) - { + for (Class c : clazz) { Assert.assertEquals(msg + " " + type + " & " + c + ": " + bool, bool, msg.isBodyAssignableTo(c)); - if (bool) - { + if (bool) { Object receivedBody = msg.getBody(c); Assert.assertTrue("correct type " + c, c.isInstance(receivedBody)); - if (body.getClass().isAssignableFrom(byte[].class)) - { + if (body.getClass().isAssignableFrom(byte[].class)) { Arrays.equals((byte[]) body, (byte[]) receivedBody); } - else - { - Assert.assertEquals("clazz=" + c + ", bodies must match.. " + body.equals(receivedBody), body, - receivedBody); + else { + Assert.assertEquals("clazz=" + c + ", bodies must match.. " + body.equals(receivedBody), body, receivedBody); } } - else - { - try - { + else { + try { Object foo = msg.getBody(c); Assert.fail("expected a " + MessageFormatException.class); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { // expected } } @@ -126,18 +109,15 @@ public class BodyIsAssignableFromTest extends MessageBodyTestCase * @param type * @throws JMSException */ - private Object createBodySendAndReceive(JmsMessageType type) throws JMSException - { + private Object createBodySendAndReceive(JmsMessageType type) throws JMSException { Object res = null; Message msg = null; - switch (type) - { + switch (type) { case BYTE: BytesMessage mByte = queueProducerSession.createBytesMessage(); final int size = 20; byte[] resByte = new byte[size]; - for (int i = 0; i < size; i++) - { + for (int i = 0; i < size; i++) { resByte[i] = (byte) i; mByte.writeByte((byte) i); } @@ -176,8 +156,7 @@ public class BodyIsAssignableFromTest extends MessageBodyTestCase return res; } - private void bodyNotAssignableFrom(JmsMessageType type, Class... clazz) throws JMSException - { + private void bodyNotAssignableFrom(JmsMessageType type, Class... clazz) throws JMSException { bodyAssignableFrom(type, false, clazz); } } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/BytesMessageTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/BytesMessageTest.java index f675816dbd..12d2f22dba 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/BytesMessageTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/BytesMessageTest.java @@ -27,8 +27,7 @@ import org.junit.Before; /** * A test that sends/receives bytes messages to the JMS provider and verifies their integrity. */ -public class BytesMessageTest extends MessageTestBase -{ +public class BytesMessageTest extends MessageTestBase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -41,16 +40,14 @@ public class BytesMessageTest extends MessageTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); message = session.createBytesMessage(); } @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { message = null; super.tearDown(); } @@ -58,8 +55,7 @@ public class BytesMessageTest extends MessageTestBase // Protected ----------------------------------------------------- @Override - protected void prepareMessage(final Message m) throws JMSException - { + protected void prepareMessage(final Message m) throws JMSException { super.prepareMessage(m); BytesMessage bm = (BytesMessage) m; @@ -78,8 +74,7 @@ public class BytesMessageTest extends MessageTestBase } @Override - protected void assertEquivalent(final Message m, final int mode, final boolean redelivered) throws JMSException - { + protected void assertEquivalent(final Message m, final int mode, final boolean redelivered) throws JMSException { super.assertEquivalent(m, mode, redelivered); BytesMessage bm = (BytesMessage) m; diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/ExpiredMessageTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/ExpiredMessageTest.java index 4a765c165d..24c1b9cbd9 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/ExpiredMessageTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/ExpiredMessageTest.java @@ -27,12 +27,10 @@ import org.apache.activemq.artemis.jms.tests.JMSTestCase; import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; import org.junit.Test; -public class ExpiredMessageTest extends JMSTestCase -{ +public class ExpiredMessageTest extends JMSTestCase { @Test - public void testSimpleExpiration() throws Exception - { + public void testSimpleExpiration() throws Exception { Connection conn = getConnectionFactory().createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -58,8 +56,7 @@ public class ExpiredMessageTest extends JMSTestCase } @Test - public void testExpiredAndLivingMessages() throws Exception - { + public void testExpiredAndLivingMessages() throws Exception { Connection conn = getConnectionFactory().createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = session.createProducer(queue1); @@ -84,7 +81,7 @@ public class ExpiredMessageTest extends JMSTestCase Message receivedMessage = cons.receive(1000); ProxyAssertSupport.assertNotNull("did not receive living message", receivedMessage); ProxyAssertSupport.assertTrue(receivedMessage instanceof TextMessage); - ProxyAssertSupport.assertEquals(livingMessage.getText(), ((TextMessage)receivedMessage).getText()); + ProxyAssertSupport.assertEquals(livingMessage.getText(), ((TextMessage) receivedMessage).getText()); // we do not receive the expiring message ProxyAssertSupport.assertNull(cons.receive(1000)); @@ -93,8 +90,7 @@ public class ExpiredMessageTest extends JMSTestCase } @Test - public void testManyExpiredMessagesAtOnce() throws Exception - { + public void testManyExpiredMessagesAtOnce() throws Exception { Connection conn = getConnectionFactory().createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -106,8 +102,7 @@ public class ExpiredMessageTest extends JMSTestCase final int MESSAGE_COUNT = 100; - for (int i = 0; i < MESSAGE_COUNT; i++) - { + for (int i = 0; i < MESSAGE_COUNT; i++) { prod.send(m); } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSCorrelationIDHeaderTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSCorrelationIDHeaderTest.java index 3acc76948f..34606b6595 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSCorrelationIDHeaderTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSCorrelationIDHeaderTest.java @@ -21,8 +21,7 @@ import javax.jms.Message; import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; import org.junit.Test; -public class JMSCorrelationIDHeaderTest extends MessageHeaderTestBase -{ +public class JMSCorrelationIDHeaderTest extends MessageHeaderTestBase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -34,8 +33,7 @@ public class JMSCorrelationIDHeaderTest extends MessageHeaderTestBase // Public -------------------------------------------------------- @Test - public void testJMSDestination() throws Exception - { + public void testJMSDestination() throws Exception { Message m1 = queueProducerSession.createMessage(); // Test with correlation id containing a message id @@ -66,27 +64,22 @@ public class JMSCorrelationIDHeaderTest extends MessageHeaderTestBase } - // Package protected --------------------------------------------- // Protected ----------------------------------------------------- // Private ------------------------------------------------------- - private void assertByteArraysEqual(final byte[] bytes1, final byte[] bytes2) - { - if (bytes1 == null | bytes2 == null) - { + private void assertByteArraysEqual(final byte[] bytes1, final byte[] bytes2) { + if (bytes1 == null | bytes2 == null) { ProxyAssertSupport.fail(); } - if (bytes1.length != bytes2.length) - { + if (bytes1.length != bytes2.length) { ProxyAssertSupport.fail(); } - for (int i = 0; i < bytes1.length; i++) - { + for (int i = 0; i < bytes1.length; i++) { ProxyAssertSupport.assertEquals(bytes1[i], bytes2[i]); } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSDeliveryModeHeaderTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSDeliveryModeHeaderTest.java index b1a8979c88..5e35e8cbe2 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSDeliveryModeHeaderTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSDeliveryModeHeaderTest.java @@ -23,8 +23,7 @@ import javax.jms.Message; import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; -public class JMSDeliveryModeHeaderTest extends MessageHeaderTestBase -{ +public class JMSDeliveryModeHeaderTest extends MessageHeaderTestBase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -36,14 +35,12 @@ public class JMSDeliveryModeHeaderTest extends MessageHeaderTestBase // Public -------------------------------------------------------- @Test - public void testDefaultDeliveryMode() throws Exception - { + public void testDefaultDeliveryMode() throws Exception { ProxyAssertSupport.assertEquals(DeliveryMode.PERSISTENT, queueProducer.getDeliveryMode()); } @Test - public void testNonPersistentDeliveryMode() throws Exception - { + public void testNonPersistentDeliveryMode() throws Exception { queueProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); ProxyAssertSupport.assertEquals(DeliveryMode.NON_PERSISTENT, queueProducer.getDeliveryMode()); @@ -54,8 +51,7 @@ public class JMSDeliveryModeHeaderTest extends MessageHeaderTestBase } @Test - public void testPersistentDeliveryMode() throws Exception - { + public void testPersistentDeliveryMode() throws Exception { queueProducer.setDeliveryMode(DeliveryMode.PERSISTENT); ProxyAssertSupport.assertEquals(DeliveryMode.PERSISTENT, queueProducer.getDeliveryMode()); diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSDestinationHeaderTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSDestinationHeaderTest.java index 1987b9946e..cfc277ec3b 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSDestinationHeaderTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSDestinationHeaderTest.java @@ -21,8 +21,7 @@ import javax.jms.Message; import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; import org.junit.Test; -public class JMSDestinationHeaderTest extends MessageHeaderTestBase -{ +public class JMSDestinationHeaderTest extends MessageHeaderTestBase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -34,8 +33,7 @@ public class JMSDestinationHeaderTest extends MessageHeaderTestBase // Public -------------------------------------------------------- @Test - public void testJMSDestination() throws Exception - { + public void testJMSDestination() throws Exception { queueProducer.send(queueProducerSession.createMessage()); Message m = queueConsumer.receive(); ProxyAssertSupport.assertEquals(queue1, m.getJMSDestination()); diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSExpirationHeaderTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSExpirationHeaderTest.java index 273f2eb0f0..303513c357 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSExpirationHeaderTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSExpirationHeaderTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.jms.tests.message; + import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; @@ -28,8 +29,7 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -public class JMSExpirationHeaderTest extends MessageHeaderTestBase -{ +public class JMSExpirationHeaderTest extends MessageHeaderTestBase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -48,8 +48,7 @@ public class JMSExpirationHeaderTest extends MessageHeaderTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); expectedMessage = null; testFailed = false; @@ -58,24 +57,21 @@ public class JMSExpirationHeaderTest extends MessageHeaderTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { super.tearDown(); } // Tests --------------------------------------------------------- @Test - public void testZeroExpiration() throws Exception - { + public void testZeroExpiration() throws Exception { Message m = queueProducerSession.createMessage(); queueProducer.send(m); ProxyAssertSupport.assertEquals(0, queueConsumer.receive().getJMSExpiration()); } @Test - public void testNoExpirationOnTimeoutReceive() throws Exception - { + public void testNoExpirationOnTimeoutReceive() throws Exception { Message m = queueProducerSession.createMessage(); queueProducer.send(m, DeliveryMode.NON_PERSISTENT, 4, 5000); @@ -87,8 +83,7 @@ public class JMSExpirationHeaderTest extends MessageHeaderTestBase } @Test - public void testExpirationOnTimeoutReceive() throws Exception - { + public void testExpirationOnTimeoutReceive() throws Exception { Message m = queueProducerSession.createMessage(); queueProducer.send(m, DeliveryMode.NON_PERSISTENT, 4, 1000); @@ -99,8 +94,7 @@ public class JMSExpirationHeaderTest extends MessageHeaderTestBase } @Test - public void testExpirationOnReceiveNoWait() throws Exception - { + public void testExpirationOnReceiveNoWait() throws Exception { Message m = queueProducerSession.createMessage(); queueProducer.send(m, DeliveryMode.NON_PERSISTENT, 4, 1000); @@ -111,8 +105,7 @@ public class JMSExpirationHeaderTest extends MessageHeaderTestBase } @Test - public void testExpiredMessageDiscardingOnTimeoutReceive() throws Exception - { + public void testExpiredMessageDiscardingOnTimeoutReceive() throws Exception { Message m = queueProducerSession.createMessage(); queueProducer.send(m, DeliveryMode.NON_PERSISTENT, 4, 1000); @@ -121,20 +114,15 @@ public class JMSExpirationHeaderTest extends MessageHeaderTestBase // start the receiver thread final CountDownLatch latch = new CountDownLatch(1); - Thread receiverThread = new Thread(new Runnable() - { - public void run() - { - try - { + Thread receiverThread = new Thread(new Runnable() { + public void run() { + try { expectedMessage = queueConsumer.receive(100); } - catch (Exception e) - { + catch (Exception e) { log.trace("receive() exits with an exception", e); } - finally - { + finally { latch.countDown(); } } @@ -146,29 +134,23 @@ public class JMSExpirationHeaderTest extends MessageHeaderTestBase } @Test - public void testReceiveTimeoutPreservation() throws Exception - { + public void testReceiveTimeoutPreservation() throws Exception { final long timeToWaitForReceive = 5000; final CountDownLatch receiverLatch = new CountDownLatch(1); // start the receiver thread - Thread receiverThread = new Thread(new Runnable() - { - public void run() - { - try - { + Thread receiverThread = new Thread(new Runnable() { + public void run() { + try { long t1 = System.currentTimeMillis(); expectedMessage = queueConsumer.receive(timeToWaitForReceive); effectiveReceiveTime = System.currentTimeMillis() - t1; } - catch (Exception e) - { + catch (Exception e) { log.trace("receive() exits with an exception", e); } - finally - { + finally { receiverLatch.countDown(); } } @@ -178,12 +160,9 @@ public class JMSExpirationHeaderTest extends MessageHeaderTestBase final CountDownLatch senderLatch = new CountDownLatch(1); // start the sender thread - Thread senderThread = new Thread(new Runnable() - { - public void run() - { - try - { + Thread senderThread = new Thread(new Runnable() { + public void run() { + try { // wait for 3 secs Thread.sleep(3000); @@ -191,22 +170,19 @@ public class JMSExpirationHeaderTest extends MessageHeaderTestBase Message m = queueProducerSession.createMessage(); queueProducer.send(m, DeliveryMode.NON_PERSISTENT, 4, -1); - ActiveMQMessage msg = (ActiveMQMessage)m; + ActiveMQMessage msg = (ActiveMQMessage) m; - if (!msg.getCoreMessage().isExpired()) - { + if (!msg.getCoreMessage().isExpired()) { log.error("The message " + m + " should have expired"); testFailed = true; return; } } - catch (Exception e) - { + catch (Exception e) { log.error("This exception will fail the test", e); testFailed = true; } - finally - { + finally { senderLatch.countDown(); } } @@ -216,8 +192,7 @@ public class JMSExpirationHeaderTest extends MessageHeaderTestBase ActiveMQTestBase.waitForLatch(senderLatch); ActiveMQTestBase.waitForLatch(receiverLatch); - if (testFailed) - { + if (testFailed) { ProxyAssertSupport.fail("Test failed by the sender thread. Watch for exception in logs"); } @@ -234,8 +209,7 @@ public class JMSExpirationHeaderTest extends MessageHeaderTestBase } @Test - public void testNoExpirationOnReceive() throws Exception - { + public void testNoExpirationOnReceive() throws Exception { Message m = queueProducerSession.createMessage(); queueProducer.send(m, DeliveryMode.NON_PERSISTENT, 4, 5000); Message result = queueConsumer.receive(); @@ -243,8 +217,7 @@ public class JMSExpirationHeaderTest extends MessageHeaderTestBase } @Test - public void testExpirationOnReceive() throws Exception - { + public void testExpirationOnReceive() throws Exception { final AtomicBoolean received = new AtomicBoolean(true); queueProducer.send(queueProducerSession.createMessage(), DeliveryMode.NON_PERSISTENT, 4, 2000); @@ -257,35 +230,28 @@ public class JMSExpirationHeaderTest extends MessageHeaderTestBase final CountDownLatch latch = new CountDownLatch(1); // blocking read for a while to make sure I don't get anything, not even a null - Thread receiverThread = new Thread(new Runnable() - { - public void run() - { - try - { + Thread receiverThread = new Thread(new Runnable() { + public void run() { + try { log.trace("Attempting to receive"); expectedMessage = queueConsumer.receive(); // NOTE on close, the receive() call will return with null log.trace("Receive exited without exception:" + expectedMessage); - if (expectedMessage == null) - { + if (expectedMessage == null) { received.set(false); } } - catch (Exception e) - { + catch (Exception e) { log.trace("receive() exits with an exception", e); ProxyAssertSupport.fail(); } - catch (Throwable t) - { + catch (Throwable t) { log.trace("receive() exits with a throwable", t); ProxyAssertSupport.fail(); } - finally - { + finally { latch.countDown(); } } @@ -310,8 +276,7 @@ public class JMSExpirationHeaderTest extends MessageHeaderTestBase * queue/subscription, when delivery is attempted */ @Test - public void testExpiredMessageDoesNotGoBackOnQueue() throws Exception - { + public void testExpiredMessageDoesNotGoBackOnQueue() throws Exception { Message m = queueProducerSession.createMessage(); m.setStringProperty("weebles", "wobble but they don't fall down"); diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSMessageIDHeaderTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSMessageIDHeaderTest.java index 03bddebdcb..40d20663f3 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSMessageIDHeaderTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSMessageIDHeaderTest.java @@ -21,8 +21,7 @@ import javax.jms.Message; import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; import org.junit.Test; -public class JMSMessageIDHeaderTest extends MessageHeaderTestBase -{ +public class JMSMessageIDHeaderTest extends MessageHeaderTestBase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -34,8 +33,7 @@ public class JMSMessageIDHeaderTest extends MessageHeaderTestBase // Public -------------------------------------------------------- @Test - public void testJMSMessageIDPrefix() throws Exception - { + public void testJMSMessageIDPrefix() throws Exception { Message m = queueProducerSession.createMessage(); queueProducer.send(m); String messageID = queueConsumer.receive().getJMSMessageID(); @@ -45,10 +43,8 @@ public class JMSMessageIDHeaderTest extends MessageHeaderTestBase } @Test - public void testJMSMessageIDChangedAfterSendingMessage() throws Exception - { - try - { + public void testJMSMessageIDChangedAfterSendingMessage() throws Exception { + try { Message m = queueProducerSession.createMessage(); m.setJMSMessageID("ID:something"); @@ -56,17 +52,14 @@ public class JMSMessageIDHeaderTest extends MessageHeaderTestBase ProxyAssertSupport.assertFalse("ID:something".equals(m.getJMSMessageID())); } - finally - { + finally { removeAllMessages(queue1.getQueueName(), true); } } @Test - public void testJMSMessageID() throws Exception - { - try - { + public void testJMSMessageID() throws Exception { + try { Message m = queueProducerSession.createMessage(); ProxyAssertSupport.assertNull(m.getJMSMessageID()); @@ -75,8 +68,7 @@ public class JMSMessageIDHeaderTest extends MessageHeaderTestBase ProxyAssertSupport.assertNotNull(m.getJMSMessageID()); ProxyAssertSupport.assertTrue(m.getJMSMessageID().startsWith("ID:")); } - finally - { + finally { removeAllMessages(queue1.getQueueName(), true); } } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSPriorityHeaderTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSPriorityHeaderTest.java index 9fd3c5ffd2..5290e5e98e 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSPriorityHeaderTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSPriorityHeaderTest.java @@ -27,16 +27,15 @@ import org.apache.activemq.artemis.jms.tests.ActiveMQServerTestCase; import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; import org.junit.Test; -public class JMSPriorityHeaderTest extends ActiveMQServerTestCase -{ +public class JMSPriorityHeaderTest extends ActiveMQServerTestCase { + /* * Note - this test is testing our current implementation of message ordering since the spec * does not mandate that all higher priority messages are delivered first - this * is just how we currently do it */ @Test - public void testMessageOrder() throws Exception - { + public void testMessageOrder() throws Exception { Connection conn = getConnectionFactory().createConnection(); conn.start(); @@ -75,57 +74,57 @@ public class JMSPriorityHeaderTest extends ActiveMQServerTestCase MessageConsumer cons = sessReceive.createConsumer(queue1); { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("j", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("i", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("h", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("g", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("f", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("e", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("d", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("c", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("b", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("a", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(500); + TextMessage t = (TextMessage) cons.receive(500); ProxyAssertSupport.assertNull(t); } @@ -148,57 +147,57 @@ public class JMSPriorityHeaderTest extends ActiveMQServerTestCase cons = sessReceive.createConsumer(queue1); { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("j", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("h", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("i", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("f", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("g", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("d", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("e", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("a", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("b", t.getText()); } { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("c", t.getText()); } { - TextMessage t = (TextMessage)cons.receiveNoWait(); + TextMessage t = (TextMessage) cons.receiveNoWait(); ProxyAssertSupport.assertNull(t); } @@ -206,8 +205,7 @@ public class JMSPriorityHeaderTest extends ActiveMQServerTestCase } @Test - public void testSimple() throws Exception - { + public void testSimple() throws Exception { Connection conn = getConnectionFactory().createConnection(); conn.start(); @@ -228,7 +226,7 @@ public class JMSPriorityHeaderTest extends ActiveMQServerTestCase MessageConsumer cons = sessReceive.createConsumer(queue1); { - TextMessage t = (TextMessage)cons.receive(1000); + TextMessage t = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(t); ProxyAssertSupport.assertEquals("a", t.getText()); ProxyAssertSupport.assertEquals(7, t.getJMSPriority()); @@ -239,7 +237,7 @@ public class JMSPriorityHeaderTest extends ActiveMQServerTestCase Thread.sleep(2000); { - TextMessage t = (TextMessage)cons.receiveNoWait(); + TextMessage t = (TextMessage) cons.receiveNoWait(); ProxyAssertSupport.assertNull(t); } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSReplyToHeaderTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSReplyToHeaderTest.java index 29be2658ab..6a9c3ee9e4 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSReplyToHeaderTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSReplyToHeaderTest.java @@ -24,11 +24,9 @@ import javax.jms.TemporaryQueue; import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; /** - * * A JMSReplyToHeaderTest */ -public class JMSReplyToHeaderTest extends MessageHeaderTestBase -{ +public class JMSReplyToHeaderTest extends MessageHeaderTestBase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -40,8 +38,7 @@ public class JMSReplyToHeaderTest extends MessageHeaderTestBase // Public -------------------------------------------------------- @Test - public void testJMSDestinationSimple() throws Exception - { + public void testJMSDestinationSimple() throws Exception { Message m = queueProducerSession.createMessage(); TemporaryQueue tempQ = queueProducerSession.createTemporaryQueue(); m.setJMSReplyTo(tempQ); @@ -52,8 +49,7 @@ public class JMSReplyToHeaderTest extends MessageHeaderTestBase } @Test - public void testJMSDestinationNull() throws Exception - { + public void testJMSDestinationNull() throws Exception { Message m = queueProducerSession.createMessage(); m.setJMSReplyTo(null); diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSTimestampHeaderTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSTimestampHeaderTest.java index b7512787a2..ae16615b4b 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSTimestampHeaderTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSTimestampHeaderTest.java @@ -22,8 +22,7 @@ import javax.jms.Message; import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; -public class JMSTimestampHeaderTest extends MessageHeaderTestBase -{ +public class JMSTimestampHeaderTest extends MessageHeaderTestBase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -35,8 +34,7 @@ public class JMSTimestampHeaderTest extends MessageHeaderTestBase // Public -------------------------------------------------------- @Test - public void testJMSTimestamp() throws Exception - { + public void testJMSTimestamp() throws Exception { Message m = queueProducerSession.createMessage(); long t1 = System.currentTimeMillis(); @@ -49,8 +47,7 @@ public class JMSTimestampHeaderTest extends MessageHeaderTestBase } @Test - public void testDisabledTimestamp() throws Exception - { + public void testDisabledTimestamp() throws Exception { Message m = queueProducerSession.createMessage(); queueProducer.setDisableMessageTimestamp(true); diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSTypeHeaderTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSTypeHeaderTest.java index 4d47c0e0e7..8ef8fd8d60 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSTypeHeaderTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/JMSTypeHeaderTest.java @@ -22,8 +22,7 @@ import javax.jms.Message; import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; -public class JMSTypeHeaderTest extends MessageHeaderTestBase -{ +public class JMSTypeHeaderTest extends MessageHeaderTestBase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -35,8 +34,7 @@ public class JMSTypeHeaderTest extends MessageHeaderTestBase // Public -------------------------------------------------------- @Test - public void testJMSType() throws Exception - { + public void testJMSType() throws Exception { Message m = queueProducerSession.createMessage(); String originalType = "TYPE1"; m.setJMSType(originalType); @@ -46,8 +44,7 @@ public class JMSTypeHeaderTest extends MessageHeaderTestBase } @Test - public void testNULLJMSType() throws Exception - { + public void testNULLJMSType() throws Exception { Message m = queueProducerSession.createMessage(); queueProducer.send(m); ProxyAssertSupport.assertEquals(null, queueConsumer.receive(1000).getJMSType()); diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MapMessageTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MapMessageTest.java index 91492762dc..ae83d96cec 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MapMessageTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MapMessageTest.java @@ -28,8 +28,7 @@ import org.junit.Test; /** * A test that sends/receives map messages to the JMS provider and verifies their integrity. */ -public class MapMessageTest extends MessageTestBase -{ +public class MapMessageTest extends MessageTestBase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -42,8 +41,7 @@ public class MapMessageTest extends MessageTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); message = session.createMapMessage(); @@ -51,16 +49,14 @@ public class MapMessageTest extends MessageTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { message = null; super.tearDown(); } @Test - public void testNullValue() throws Exception - { + public void testNullValue() throws Exception { MapMessage m = session.createMapMessage(); m.setString("nullValue", null); @@ -77,8 +73,7 @@ public class MapMessageTest extends MessageTestBase // Protected ----------------------------------------------------- @Override - protected void prepareMessage(final Message m) throws JMSException - { + protected void prepareMessage(final Message m) throws JMSException { super.prepareMessage(m); MapMessage mm = (MapMessage) m; @@ -97,8 +92,7 @@ public class MapMessageTest extends MessageTestBase } @Override - protected void assertEquivalent(final Message m, final int mode, final boolean redelivery) throws JMSException - { + protected void assertEquivalent(final Message m, final int mode, final boolean redelivery) throws JMSException { super.assertEquivalent(m, mode, redelivery); MapMessage mm = (MapMessage) m; diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MessageBodyTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MessageBodyTest.java index 1843835b0f..cf85fe56b2 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MessageBodyTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MessageBodyTest.java @@ -33,12 +33,10 @@ import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; import org.junit.Assert; import org.junit.Test; -public class MessageBodyTest extends MessageBodyTestCase -{ +public class MessageBodyTest extends MessageBodyTestCase { @Test - public void testSMBodyReadable() throws Exception - { + public void testSMBodyReadable() throws Exception { byte bValue = 123; StreamMessage sm = queueProducerSession.createStreamMessage(); sm.writeByte(bValue); @@ -50,8 +48,7 @@ public class MessageBodyTest extends MessageBodyTestCase } @Test - public void testBytesMessage() throws Exception - { + public void testBytesMessage() throws Exception { BytesMessage m = queueProducerSession.createBytesMessage(); // some arbitrary values @@ -89,134 +86,106 @@ public class MessageBodyTest extends MessageBodyTestCase m.writeObject(myString); m.writeObject(myBytes); - try - { + try { m.writeObject(new Object()); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { // OK } // Reading should not be possible when message is read-write - try - { + try { m.readBoolean(); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotReadableException e) - { + catch (javax.jms.MessageNotReadableException e) { // OK } - try - { + try { m.readShort(); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotReadableException e) - { + catch (javax.jms.MessageNotReadableException e) { // OK } - try - { + try { m.readChar(); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotReadableException e) - { + catch (javax.jms.MessageNotReadableException e) { // OK } - try - { + try { m.readInt(); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotReadableException e) - { + catch (javax.jms.MessageNotReadableException e) { // OK } - try - { + try { m.readLong(); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotReadableException e) - { + catch (javax.jms.MessageNotReadableException e) { // OK } - try - { + try { m.readFloat(); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotReadableException e) - { + catch (javax.jms.MessageNotReadableException e) { // OK } - try - { + try { m.readDouble(); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotReadableException e) - { + catch (javax.jms.MessageNotReadableException e) { // OK } - try - { + try { m.readUTF(); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotReadableException e) - { + catch (javax.jms.MessageNotReadableException e) { // OK } - try - { + try { m.readUnsignedByte(); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotReadableException e) - { + catch (javax.jms.MessageNotReadableException e) { // OK } - try - { + try { m.readUnsignedShort(); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotReadableException e) - { + catch (javax.jms.MessageNotReadableException e) { // OK } - try - { + try { byte[] bytes = new byte[333]; m.readBytes(bytes); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotReadableException e) - { + catch (javax.jms.MessageNotReadableException e) { // OK } - try - { + try { byte[] bytes = new byte[333]; m.readBytes(bytes, 111); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotReadableException e) - { + catch (javax.jms.MessageNotReadableException e) { // OK } - try - { + try { m.getBodyLength(); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotReadableException e) - { + catch (javax.jms.MessageNotReadableException e) { // OK } @@ -269,217 +238,173 @@ public class MessageBodyTest extends MessageBodyTestCase ProxyAssertSupport.assertEquals(-1, ret); // Try and read past the end of the stream - try - { + try { m2.readBoolean(); ProxyAssertSupport.fail(); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { // OK } - try - { + try { m2.readByte(); ProxyAssertSupport.fail(); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { // OK } - try - { + try { m2.readChar(); ProxyAssertSupport.fail(); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { // OK } - try - { + try { m2.readDouble(); ProxyAssertSupport.fail(); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { // OK } - try - { + try { m2.readFloat(); ProxyAssertSupport.fail(); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { // OK } - try - { + try { m2.readInt(); ProxyAssertSupport.fail(); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { // OK } - try - { + try { m2.readLong(); ProxyAssertSupport.fail(); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { // OK } - try - { + try { m2.readShort(); ProxyAssertSupport.fail(); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { // OK } - try - { + try { m2.readUnsignedByte(); ProxyAssertSupport.fail(); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { // OK } - try - { + try { m2.readUnsignedShort(); ProxyAssertSupport.fail(); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { // OK } - try - { + try { m2.readUTF(); ProxyAssertSupport.fail(); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { // OK } // Message should not be writable in read-only mode - try - { + try { m2.writeBoolean(myBool); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotWriteableException e) - { + catch (javax.jms.MessageNotWriteableException e) { // OK } - try - { + try { m2.writeByte(myByte); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotWriteableException e) - { + catch (javax.jms.MessageNotWriteableException e) { // OK } - try - { + try { m2.writeShort(myShort); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotWriteableException e) - { + catch (javax.jms.MessageNotWriteableException e) { // OK } - try - { + try { m2.writeChar(myChar); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotWriteableException e) - { + catch (javax.jms.MessageNotWriteableException e) { // OK } - try - { + try { m2.writeInt(myInt); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotWriteableException e) - { + catch (javax.jms.MessageNotWriteableException e) { // OK } - try - { + try { m2.writeLong(myLong); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotWriteableException e) - { + catch (javax.jms.MessageNotWriteableException e) { // OK } - try - { + try { m2.writeFloat(myFloat); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotWriteableException e) - { + catch (javax.jms.MessageNotWriteableException e) { // OK } - try - { + try { m2.writeDouble(myDouble); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotWriteableException e) - { + catch (javax.jms.MessageNotWriteableException e) { // OK } - try - { + try { m2.writeUTF(myString); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotWriteableException e) - { + catch (javax.jms.MessageNotWriteableException e) { // OK } - try - { + try { m2.writeBytes(myBytes); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotWriteableException e) - { + catch (javax.jms.MessageNotWriteableException e) { // OK } - try - { + try { m2.writeObject(myString); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotWriteableException e) - { + catch (javax.jms.MessageNotWriteableException e) { // OK } @@ -502,13 +427,11 @@ public class MessageBodyTest extends MessageBodyTestCase m2.clearBody(); - try - { + try { m2.getBodyLength(); ProxyAssertSupport.fail(); } - catch (MessageNotReadableException e) - { + catch (MessageNotReadableException e) { // OK } @@ -526,8 +449,7 @@ public class MessageBodyTest extends MessageBodyTestCase } @Test - public void testMapMessage() throws Exception - { + public void testMapMessage() throws Exception { MapMessage m1 = queueProducerSession.createMapMessage(); // Some arbitrary values @@ -558,13 +480,11 @@ public class MessageBodyTest extends MessageBodyTestCase m1.setObject("myDouble", new Double(myDouble)); m1.setObject("myString", myString); - try - { + try { m1.setObject("myIllegal", new Object()); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageFormatException e) - { + catch (javax.jms.MessageFormatException e) { } queueProducer.send(m1); @@ -583,76 +503,60 @@ public class MessageBodyTest extends MessageBodyTestCase ProxyAssertSupport.assertEquals(myString, m2.getString("myString")); // Properties should now be read-only - try - { + try { m2.setBoolean("myBool", myBool); ProxyAssertSupport.fail(); } - catch (MessageNotWriteableException e) - { + catch (MessageNotWriteableException e) { } - try - { + try { m2.setByte("myByte", myByte); ProxyAssertSupport.fail(); } - catch (MessageNotWriteableException e) - { + catch (MessageNotWriteableException e) { } - try - { + try { m2.setShort("myShort", myShort); ProxyAssertSupport.fail(); } - catch (MessageNotWriteableException e) - { + catch (MessageNotWriteableException e) { } - try - { + try { m2.setInt("myInt", myInt); ProxyAssertSupport.fail(); } - catch (MessageNotWriteableException e) - { + catch (MessageNotWriteableException e) { } - try - { + try { m2.setLong("myLong", myLong); ProxyAssertSupport.fail(); } - catch (MessageNotWriteableException e) - { + catch (MessageNotWriteableException e) { } - try - { + try { m2.setFloat("myFloat", myFloat); ProxyAssertSupport.fail(); } - catch (MessageNotWriteableException e) - { + catch (MessageNotWriteableException e) { } - try - { + try { m2.setDouble("myDouble", myDouble); ProxyAssertSupport.fail(); } - catch (MessageNotWriteableException e) - { + catch (MessageNotWriteableException e) { } - try - { + try { m2.setString("myString", myString); ProxyAssertSupport.fail(); } - catch (MessageNotWriteableException e) - { + catch (MessageNotWriteableException e) { } ProxyAssertSupport.assertTrue(m2.itemExists("myBool")); @@ -669,8 +573,7 @@ public class MessageBodyTest extends MessageBodyTestCase HashSet itemNames = new HashSet(); @SuppressWarnings("unchecked") Enumeration en = m2.getMapNames(); - while (en.hasMoreElements()) - { + while (en.hasMoreElements()) { String propName = en.nextElement(); itemNames.add(propName); } @@ -692,58 +595,46 @@ public class MessageBodyTest extends MessageBodyTestCase ProxyAssertSupport.assertEquals(String.valueOf(myBool), m2.getString("myBool")); - try - { + try { m2.getByte("myBool"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getShort("myBool"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getInt("myBool"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getLong("myBool"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getFloat("myBool"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getDouble("myBool"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } // byte item can be read as short, int, long or String @@ -753,31 +644,25 @@ public class MessageBodyTest extends MessageBodyTestCase ProxyAssertSupport.assertEquals(myByte, m2.getLong("myByte")); ProxyAssertSupport.assertEquals(String.valueOf(myByte), m2.getString("myByte")); - try - { + try { m2.getBoolean("myByte"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getFloat("myByte"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getDouble("myByte"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } // short item can be read as int, long or String @@ -786,40 +671,32 @@ public class MessageBodyTest extends MessageBodyTestCase ProxyAssertSupport.assertEquals(myShort, m2.getLong("myShort")); ProxyAssertSupport.assertEquals(String.valueOf(myShort), m2.getString("myShort")); - try - { + try { m2.getByte("myShort"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getBoolean("myShort"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getFloat("myShort"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getDouble("myShort"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } // int item can be read as long or String @@ -827,107 +704,85 @@ public class MessageBodyTest extends MessageBodyTestCase ProxyAssertSupport.assertEquals(myInt, m2.getLong("myInt")); ProxyAssertSupport.assertEquals(String.valueOf(myInt), m2.getString("myInt")); - try - { + try { m2.getShort("myInt"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getByte("myInt"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getBoolean("myInt"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getFloat("myInt"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getDouble("myInt"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } // long item can be read as String ProxyAssertSupport.assertEquals(String.valueOf(myLong), m2.getString("myLong")); - try - { + try { m2.getInt("myLong"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getShort("myLong"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getByte("myLong"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getBoolean("myLong"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getFloat("myLong"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getDouble("myLong"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } // float can be read as double or String @@ -935,107 +790,85 @@ public class MessageBodyTest extends MessageBodyTestCase ProxyAssertSupport.assertEquals(String.valueOf(myFloat), m2.getString("myFloat")); ProxyAssertSupport.assertEquals(myFloat, m2.getDouble("myFloat"), 0); - try - { + try { m2.getInt("myFloat"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getShort("myFloat"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getLong("myFloat"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getByte("myFloat"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getBoolean("myFloat"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } // double can be read as String ProxyAssertSupport.assertEquals(String.valueOf(myDouble), m2.getString("myDouble")); - try - { + try { m2.getFloat("myDouble"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getInt("myDouble"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getShort("myDouble"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getByte("myDouble"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getBoolean("myDouble"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getFloat("myDouble"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } m2.clearBody(); @@ -1064,67 +897,54 @@ public class MessageBodyTest extends MessageBodyTestCase m3.getBoolean("myIllegal"); - try - { + try { m3.getByte("myIllegal"); ProxyAssertSupport.fail(); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } - try - { + try { m3.getShort("myIllegal"); ProxyAssertSupport.fail(); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } - try - { + try { m3.getInt("myIllegal"); ProxyAssertSupport.fail(); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } - try - { + try { m3.getLong("myIllegal"); ProxyAssertSupport.fail(); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } - try - { + try { m3.getFloat("myIllegal"); ProxyAssertSupport.fail(); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } - try - { + try { m3.getDouble("myIllegal"); ProxyAssertSupport.fail(); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } } - static class TestSerializable implements Serializable - { + static class TestSerializable implements Serializable { + private static final long serialVersionUID = -8641359255228705573L; String str; } @Test - public void testObjectMessage() throws Exception - { + public void testObjectMessage() throws Exception { TestSerializable obj = new TestSerializable(); obj.str = "abcdefg"; @@ -1157,13 +977,11 @@ public class MessageBodyTest extends MessageBodyTestCase ProxyAssertSupport.assertEquals("abcdefg", obj3.str); - try - { + try { m4.setObject(obj); ProxyAssertSupport.fail(); } - catch (MessageNotWriteableException e) - { + catch (MessageNotWriteableException e) { } m4.clearBody(); @@ -1177,8 +995,7 @@ public class MessageBodyTest extends MessageBodyTestCase } @Test - public void testStreamMessage() throws Exception - { + public void testStreamMessage() throws Exception { StreamMessage m = queueProducerSession.createStreamMessage(); // Some arbitrary values @@ -1215,80 +1032,62 @@ public class MessageBodyTest extends MessageBodyTestCase m.writeObject(myString); m.writeObject(myBytes); - try - { + try { m.writeObject(new Object()); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } // Reading should not be possible when message is read-write - try - { + try { m.readBoolean(); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotReadableException e) - { + catch (javax.jms.MessageNotReadableException e) { } - try - { + try { m.readShort(); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotReadableException e) - { + catch (javax.jms.MessageNotReadableException e) { } - try - { + try { m.readChar(); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotReadableException e) - { + catch (javax.jms.MessageNotReadableException e) { } - try - { + try { m.readInt(); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotReadableException e) - { + catch (javax.jms.MessageNotReadableException e) { } - try - { + try { m.readLong(); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotReadableException e) - { + catch (javax.jms.MessageNotReadableException e) { } - try - { + try { m.readFloat(); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotReadableException e) - { + catch (javax.jms.MessageNotReadableException e) { } - try - { + try { m.readDouble(); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotReadableException e) - { + catch (javax.jms.MessageNotReadableException e) { } - try - { + try { byte[] bytes = new byte[333]; m.readBytes(bytes); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotReadableException e) - { + catch (javax.jms.MessageNotReadableException e) { } queueProducer.send(m); @@ -1344,161 +1143,125 @@ public class MessageBodyTest extends MessageBodyTestCase ProxyAssertSupport.assertEquals(-1, ret); // Try and read past the end of the stream - try - { + try { m2.readBoolean(); ProxyAssertSupport.fail(); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { } - try - { + try { m2.readByte(); ProxyAssertSupport.fail(); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { } - try - { + try { m2.readChar(); ProxyAssertSupport.fail(); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { } - try - { + try { m2.readDouble(); ProxyAssertSupport.fail(); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { } - try - { + try { m2.readFloat(); ProxyAssertSupport.fail(); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { } - try - { + try { m2.readInt(); ProxyAssertSupport.fail(); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { } - try - { + try { m2.readLong(); ProxyAssertSupport.fail(); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { } - try - { + try { m2.readShort(); ProxyAssertSupport.fail(); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { } // Message should not be writable in read-only mode - try - { + try { m2.writeBoolean(myBool); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotWriteableException e) - { + catch (javax.jms.MessageNotWriteableException e) { } - try - { + try { m2.writeByte(myByte); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotWriteableException e) - { + catch (javax.jms.MessageNotWriteableException e) { } - try - { + try { m2.writeShort(myShort); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotWriteableException e) - { + catch (javax.jms.MessageNotWriteableException e) { } - try - { + try { m2.writeChar(myChar); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotWriteableException e) - { + catch (javax.jms.MessageNotWriteableException e) { } - try - { + try { m2.writeInt(myInt); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotWriteableException e) - { + catch (javax.jms.MessageNotWriteableException e) { } - try - { + try { m2.writeLong(myLong); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotWriteableException e) - { + catch (javax.jms.MessageNotWriteableException e) { } - try - { + try { m2.writeFloat(myFloat); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotWriteableException e) - { + catch (javax.jms.MessageNotWriteableException e) { } - try - { + try { m2.writeDouble(myDouble); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotWriteableException e) - { + catch (javax.jms.MessageNotWriteableException e) { } - try - { + try { m2.writeBytes(myBytes); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotWriteableException e) - { + catch (javax.jms.MessageNotWriteableException e) { } - try - { + try { m2.writeObject(myString); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageNotWriteableException e) - { + catch (javax.jms.MessageNotWriteableException e) { } m2.reset(); @@ -1516,14 +1279,12 @@ public class MessageBodyTest extends MessageBodyTestCase m2.clearBody(); - try - { + try { // Should now be write only m2.readBoolean(); ProxyAssertSupport.fail(); } - catch (MessageNotReadableException e) - { + catch (MessageNotReadableException e) { } m2.writeBoolean(myBool); @@ -1531,13 +1292,11 @@ public class MessageBodyTest extends MessageBodyTestCase m2.reset(); ProxyAssertSupport.assertEquals(myBool, m2.readBoolean()); - try - { + try { m2.readBoolean(); ProxyAssertSupport.fail(); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { } // Test that changing the received message doesn't affect the sent message @@ -1557,8 +1316,7 @@ public class MessageBodyTest extends MessageBodyTestCase } @Test - public void testTextMessage() throws Exception - { + public void testTextMessage() throws Exception { TextMessage m = queueProducerSession.createTextMessage(); // Arbitrary string with some Chinese characters to make sure UTF encoding @@ -1580,13 +1338,11 @@ public class MessageBodyTest extends MessageBodyTestCase ProxyAssertSupport.assertEquals(myString, m2.getText()); - try - { + try { m2.setText("Should be read-only"); ProxyAssertSupport.fail(); } - catch (MessageNotWriteableException e) - { + catch (MessageNotWriteableException e) { } m2.clearBody(); diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MessageBodyTestCase.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MessageBodyTestCase.java index a2961e5b17..edb25fcbc4 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MessageBodyTestCase.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MessageBodyTestCase.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.jms.tests.message; + import javax.jms.Connection; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; @@ -23,22 +24,20 @@ import javax.jms.Session; import org.apache.activemq.artemis.jms.tests.ActiveMQServerTestCase; import org.junit.Before; -public abstract class MessageBodyTestCase extends ActiveMQServerTestCase -{ +public abstract class MessageBodyTestCase extends ActiveMQServerTestCase { + protected Connection producerConnection, consumerConnection; protected Session queueProducerSession, queueConsumerSession; protected MessageProducer queueProducer; protected MessageConsumer queueConsumer; - enum JmsMessageType - { + enum JmsMessageType { TEXT, MAP, OBJECT, BYTE, STREAM; } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); producerConnection = addConnection(getConnectionFactory().createConnection()); diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MessageHeaderTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MessageHeaderTest.java index ba9849a546..f672de6704 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MessageHeaderTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MessageHeaderTest.java @@ -59,8 +59,7 @@ import org.apache.activemq.artemis.jms.client.ActiveMQTextMessage; import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; import org.junit.Test; -public class MessageHeaderTest extends MessageHeaderTestBase -{ +public class MessageHeaderTest extends MessageHeaderTestBase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -72,8 +71,7 @@ public class MessageHeaderTest extends MessageHeaderTestBase // Public -------------------------------------------------------- @Test - public void testClearMessage() throws Exception - { + public void testClearMessage() throws Exception { queueProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); Message message = queueProducerSession.createTextMessage("some message"); @@ -91,20 +89,17 @@ public class MessageHeaderTest extends MessageHeaderTestBase } @Test - public void testMessageOrderQueue() throws Exception - { + public void testMessageOrderQueue() throws Exception { final int NUM_MESSAGES = 10; queueProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = queueProducerSession.createMessage(); m.setIntProperty("count", i); queueProducer.send(m); } - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = queueConsumer.receive(3000); ProxyAssertSupport.assertNotNull(m); int count = m.getIntProperty("count"); @@ -112,15 +107,13 @@ public class MessageHeaderTest extends MessageHeaderTestBase } queueProducer.setDeliveryMode(DeliveryMode.PERSISTENT); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = queueProducerSession.createMessage(); m.setIntProperty("count2", i); queueProducer.send(m); } - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = queueConsumer.receive(3000); ProxyAssertSupport.assertNotNull(m); int count = m.getIntProperty("count2"); @@ -129,20 +122,17 @@ public class MessageHeaderTest extends MessageHeaderTestBase } @Test - public void testMessageOrderTopic() throws Exception - { + public void testMessageOrderTopic() throws Exception { final int NUM_MESSAGES = 10; topicProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = topicProducerSession.createMessage(); m.setIntProperty("count", i); topicProducer.send(m); } - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = topicConsumer.receive(3000); ProxyAssertSupport.assertNotNull(m); int count = m.getIntProperty("count"); @@ -150,15 +140,13 @@ public class MessageHeaderTest extends MessageHeaderTestBase } topicProducer.setDeliveryMode(DeliveryMode.PERSISTENT); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = topicProducerSession.createMessage(); m.setIntProperty("count2", i); topicProducer.send(m); } - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { Message m = topicConsumer.receive(3000); ProxyAssertSupport.assertNotNull(m); int count = m.getIntProperty("count2"); @@ -167,8 +155,7 @@ public class MessageHeaderTest extends MessageHeaderTestBase } @Test - public void testProperties() throws Exception - { + public void testProperties() throws Exception { Message m1 = queueProducerSession.createMessage(); // Some arbitrary values @@ -199,13 +186,11 @@ public class MessageHeaderTest extends MessageHeaderTestBase m1.setObjectProperty("myDouble", new Double(myDouble)); m1.setObjectProperty("myString", myString); - try - { + try { m1.setObjectProperty("myIllegal", new Object()); ProxyAssertSupport.fail(); } - catch (javax.jms.MessageFormatException e) - { + catch (javax.jms.MessageFormatException e) { } queueProducer.send(m1); @@ -224,76 +209,60 @@ public class MessageHeaderTest extends MessageHeaderTestBase ProxyAssertSupport.assertEquals(myString, m2.getStringProperty("myString")); // Properties should now be read-only - try - { + try { m2.setBooleanProperty("myBool", myBool); ProxyAssertSupport.fail(); } - catch (MessageNotWriteableException e) - { + catch (MessageNotWriteableException e) { } - try - { + try { m2.setByteProperty("myByte", myByte); ProxyAssertSupport.fail(); } - catch (MessageNotWriteableException e) - { + catch (MessageNotWriteableException e) { } - try - { + try { m2.setShortProperty("myShort", myShort); ProxyAssertSupport.fail(); } - catch (MessageNotWriteableException e) - { + catch (MessageNotWriteableException e) { } - try - { + try { m2.setIntProperty("myInt", myInt); ProxyAssertSupport.fail(); } - catch (MessageNotWriteableException e) - { + catch (MessageNotWriteableException e) { } - try - { + try { m2.setLongProperty("myLong", myLong); ProxyAssertSupport.fail(); } - catch (MessageNotWriteableException e) - { + catch (MessageNotWriteableException e) { } - try - { + try { m2.setFloatProperty("myFloat", myFloat); ProxyAssertSupport.fail(); } - catch (MessageNotWriteableException e) - { + catch (MessageNotWriteableException e) { } - try - { + try { m2.setDoubleProperty("myDouble", myDouble); ProxyAssertSupport.fail(); } - catch (MessageNotWriteableException e) - { + catch (MessageNotWriteableException e) { } - try - { + try { m2.setStringProperty("myString", myString); ProxyAssertSupport.fail(); } - catch (MessageNotWriteableException e) - { + catch (MessageNotWriteableException e) { } ProxyAssertSupport.assertTrue(m2.propertyExists("myBool")); @@ -309,8 +278,7 @@ public class MessageHeaderTest extends MessageHeaderTestBase Set propNames = new HashSet(); Enumeration en = m2.getPropertyNames(); - while (en.hasMoreElements()) - { + while (en.hasMoreElements()) { String propName = (String) en.nextElement(); propNames.add(propName); @@ -333,58 +301,46 @@ public class MessageHeaderTest extends MessageHeaderTestBase ProxyAssertSupport.assertEquals(String.valueOf(myBool), m2.getStringProperty("myBool")); - try - { + try { m2.getByteProperty("myBool"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getShortProperty("myBool"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getIntProperty("myBool"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getLongProperty("myBool"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getFloatProperty("myBool"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getDoubleProperty("myBool"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } // byte property can be read as short, int, long or String @@ -394,31 +350,25 @@ public class MessageHeaderTest extends MessageHeaderTestBase ProxyAssertSupport.assertEquals(myByte, m2.getLongProperty("myByte")); ProxyAssertSupport.assertEquals(String.valueOf(myByte), m2.getStringProperty("myByte")); - try - { + try { m2.getBooleanProperty("myByte"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getFloatProperty("myByte"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getDoubleProperty("myByte"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } // short property can be read as int, long or String @@ -427,40 +377,32 @@ public class MessageHeaderTest extends MessageHeaderTestBase ProxyAssertSupport.assertEquals(myShort, m2.getLongProperty("myShort")); ProxyAssertSupport.assertEquals(String.valueOf(myShort), m2.getStringProperty("myShort")); - try - { + try { m2.getByteProperty("myShort"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getBooleanProperty("myShort"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getFloatProperty("myShort"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getDoubleProperty("myShort"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } // int property can be read as long or String @@ -468,107 +410,85 @@ public class MessageHeaderTest extends MessageHeaderTestBase ProxyAssertSupport.assertEquals(myInt, m2.getLongProperty("myInt")); ProxyAssertSupport.assertEquals(String.valueOf(myInt), m2.getStringProperty("myInt")); - try - { + try { m2.getShortProperty("myInt"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getByteProperty("myInt"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getBooleanProperty("myInt"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getFloatProperty("myInt"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getDoubleProperty("myInt"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } // long property can be read as String ProxyAssertSupport.assertEquals(String.valueOf(myLong), m2.getStringProperty("myLong")); - try - { + try { m2.getIntProperty("myLong"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getShortProperty("myLong"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getByteProperty("myLong"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getBooleanProperty("myLong"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getFloatProperty("myLong"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getDoubleProperty("myLong"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } // float property can be read as double or String @@ -576,107 +496,85 @@ public class MessageHeaderTest extends MessageHeaderTestBase ProxyAssertSupport.assertEquals(String.valueOf(myFloat), m2.getStringProperty("myFloat")); ProxyAssertSupport.assertEquals(myFloat, m2.getDoubleProperty("myFloat"), 0); - try - { + try { m2.getIntProperty("myFloat"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getShortProperty("myFloat"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getLongProperty("myFloat"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getByteProperty("myFloat"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getBooleanProperty("myFloat"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } // double property can be read as String ProxyAssertSupport.assertEquals(String.valueOf(myDouble), m2.getStringProperty("myDouble")); - try - { + try { m2.getFloatProperty("myDouble"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getIntProperty("myDouble"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getShortProperty("myDouble"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getByteProperty("myDouble"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getBooleanProperty("myDouble"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getFloatProperty("myDouble"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } m2.clearProperties(); @@ -708,59 +606,46 @@ public class MessageHeaderTest extends MessageHeaderTestBase m3.getBooleanProperty("myIllegal"); - try - { + try { m3.getByteProperty("myIllegal"); ProxyAssertSupport.fail(); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } - try - { + try { m3.getShortProperty("myIllegal"); ProxyAssertSupport.fail(); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } - try - { + try { m3.getIntProperty("myIllegal"); ProxyAssertSupport.fail(); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } - try - { + try { m3.getLongProperty("myIllegal"); ProxyAssertSupport.fail(); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } - try - { + try { m3.getFloatProperty("myIllegal"); ProxyAssertSupport.fail(); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } - try - { + try { m3.getDoubleProperty("myIllegal"); ProxyAssertSupport.fail(); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } } @Test - public void testSendReceiveForeignMessage() throws JMSException - { + public void testSendReceiveForeignMessage() throws JMSException { log.trace("Starting da test"); @@ -790,14 +675,8 @@ public class MessageHeaderTest extends MessageHeaderTestBase } @Test - public void testCopyOnJBossMessage() throws JMSException - { - ClientMessage clientMessage = new ClientMessageImpl(ActiveMQTextMessage.TYPE, - true, - 0, - System.currentTimeMillis(), - (byte) 4, - 1000); + public void testCopyOnJBossMessage() throws JMSException { + ClientMessage clientMessage = new ClientMessageImpl(ActiveMQTextMessage.TYPE, true, 0, System.currentTimeMillis(), (byte) 4, 1000); ClientSession session = new FakeSession(clientMessage); ActiveMQMessage jbossMessage = ActiveMQMessage.createMessage(clientMessage, session); jbossMessage.clearProperties(); @@ -810,14 +689,8 @@ public class MessageHeaderTest extends MessageHeaderTestBase } @Test - public void testCopyOnForeignMessage() throws JMSException - { - ClientMessage clientMessage = new ClientMessageImpl(ActiveMQTextMessage.TYPE, - true, - 0, - System.currentTimeMillis(), - (byte) 4, - 1000); + public void testCopyOnForeignMessage() throws JMSException { + ClientMessage clientMessage = new ClientMessageImpl(ActiveMQTextMessage.TYPE, true, 0, System.currentTimeMillis(), (byte) 4, 1000); ClientSession session = new FakeSession(clientMessage); Message foreignMessage = new SimpleJMSMessage(); @@ -829,19 +702,12 @@ public class MessageHeaderTest extends MessageHeaderTestBase } @Test - public void testCopyOnForeignBytesMessage() throws JMSException - { - ClientMessage clientMessage = new ClientMessageImpl(ActiveMQTextMessage.TYPE, - true, - 0, - System.currentTimeMillis(), - (byte) 4, - 1000); + public void testCopyOnForeignBytesMessage() throws JMSException { + ClientMessage clientMessage = new ClientMessageImpl(ActiveMQTextMessage.TYPE, true, 0, System.currentTimeMillis(), (byte) 4, 1000); ClientSession session = new FakeSession(clientMessage); BytesMessage foreignBytesMessage = new SimpleJMSBytesMessage(); - for (int i = 0; i < 20; i++) - { + for (int i = 0; i < 20; i++) { foreignBytesMessage.writeByte((byte) i); } @@ -854,14 +720,8 @@ public class MessageHeaderTest extends MessageHeaderTestBase } @Test - public void testCopyOnForeignMapMessage() throws JMSException - { - ClientMessage clientMessage = new ClientMessageImpl(ActiveMQTextMessage.TYPE, - true, - 0, - System.currentTimeMillis(), - (byte) 4, - 1000); + public void testCopyOnForeignMapMessage() throws JMSException { + ClientMessage clientMessage = new ClientMessageImpl(ActiveMQTextMessage.TYPE, true, 0, System.currentTimeMillis(), (byte) 4, 1000); ClientSession session = new FakeSession(clientMessage); MapMessage foreignMapMessage = new SimpleJMSMapMessage(); foreignMapMessage.setInt("int", 1); @@ -873,14 +733,8 @@ public class MessageHeaderTest extends MessageHeaderTestBase } @Test - public void testCopyOnForeignObjectMessage() throws JMSException - { - ClientMessage clientMessage = new ClientMessageImpl(ActiveMQTextMessage.TYPE, - true, - 0, - System.currentTimeMillis(), - (byte) 4, - 1000); + public void testCopyOnForeignObjectMessage() throws JMSException { + ClientMessage clientMessage = new ClientMessageImpl(ActiveMQTextMessage.TYPE, true, 0, System.currentTimeMillis(), (byte) 4, 1000); ClientSession session = new FakeSession(clientMessage); ObjectMessage foreignObjectMessage = new SimpleJMSObjectMessage(); @@ -891,14 +745,8 @@ public class MessageHeaderTest extends MessageHeaderTestBase } @Test - public void testCopyOnForeignStreamMessage() throws JMSException - { - ClientMessage clientMessage = new ClientMessageImpl(ActiveMQTextMessage.TYPE, - true, - 0, - System.currentTimeMillis(), - (byte) 4, - 1000); + public void testCopyOnForeignStreamMessage() throws JMSException { + ClientMessage clientMessage = new ClientMessageImpl(ActiveMQTextMessage.TYPE, true, 0, System.currentTimeMillis(), (byte) 4, 1000); ClientSession session = new FakeSession(clientMessage); StreamMessage foreignStreamMessage = new SimpleJMSStreamMessage(); @@ -912,14 +760,8 @@ public class MessageHeaderTest extends MessageHeaderTestBase } @Test - public void testCopyOnForeignTextMessage() throws JMSException - { - ClientMessage clientMessage = new ClientMessageImpl(ActiveMQTextMessage.TYPE, - true, - 0, - System.currentTimeMillis(), - (byte) 4, - 1000); + public void testCopyOnForeignTextMessage() throws JMSException { + ClientMessage clientMessage = new ClientMessageImpl(ActiveMQTextMessage.TYPE, true, 0, System.currentTimeMillis(), (byte) 4, 1000); ClientSession session = new FakeSession(clientMessage); TextMessage foreignTextMessage = new SimpleJMSTextMessage(); @@ -929,8 +771,7 @@ public class MessageHeaderTest extends MessageHeaderTestBase } @Test - public void testForeignJMSDestination() throws JMSException - { + public void testForeignJMSDestination() throws JMSException { Message message = queueProducerSession.createMessage(); Destination foreignDestination = new ForeignDestination(); @@ -956,138 +797,128 @@ public class MessageHeaderTest extends MessageHeaderTestBase // Inner classes ------------------------------------------------- - private static class ForeignDestination implements Destination, Serializable - { + private static class ForeignDestination implements Destination, Serializable { + private static final long serialVersionUID = 5545509674580823610L; // A ForeignDestination equals any other ForeignDestination, for simplicity @Override - public boolean equals(final Object obj) - { + public boolean equals(final Object obj) { return obj instanceof ForeignDestination; } @Override - public int hashCode() - { + public int hashCode() { return 157; } } - class FakeSession implements ClientSession - { - public ClientConsumer createConsumer(final SimpleString queueName, final boolean browseOnly) throws ActiveMQException - { + class FakeSession implements ClientSession { + + public ClientConsumer createConsumer(final SimpleString queueName, + final boolean browseOnly) throws ActiveMQException { // TODO Auto-generated method stub return null; } - - public ClientConsumer createConsumer(final String queueName, final boolean browseOnly) throws ActiveMQException - { + public ClientConsumer createConsumer(final String queueName, final boolean browseOnly) throws ActiveMQException { // TODO Auto-generated method stub return null; } - public void createQueue(final String address, final String queueName) throws ActiveMQException - { + public void createQueue(final String address, final String queueName) throws ActiveMQException { // TODO Auto-generated method stub } private final ClientMessage message; - public FakeSession(final ClientMessage message) - { + public FakeSession(final ClientMessage message) { this.message = message; } public void createQueue(final SimpleString address, final SimpleString queueName, final SimpleString filterString, - final boolean durable) throws ActiveMQException - { + final boolean durable) throws ActiveMQException { } - public void createQueue(final SimpleString address, final SimpleString queueName, final boolean durable) throws ActiveMQException - { + public void createQueue(final SimpleString address, + final SimpleString queueName, + final boolean durable) throws ActiveMQException { } @Override - public void createSharedQueue(SimpleString address, SimpleString queueName, boolean durable) throws ActiveMQException - { + public void createSharedQueue(SimpleString address, + SimpleString queueName, + boolean durable) throws ActiveMQException { } @Override - public void createSharedQueue(SimpleString address, SimpleString queueName, SimpleString filter, boolean durable) throws ActiveMQException - { + public void createSharedQueue(SimpleString address, + SimpleString queueName, + SimpleString filter, + boolean durable) throws ActiveMQException { } - public void createQueue(final String address, final String queueName, final boolean durable) throws ActiveMQException - { + public void createQueue(final String address, + final String queueName, + final boolean durable) throws ActiveMQException { } public void createQueue(final SimpleString address, final SimpleString queueName, final boolean durable, - final boolean temporary) throws ActiveMQException - { + final boolean temporary) throws ActiveMQException { } public void createQueue(final String address, final String queueName, final boolean durable, - final boolean temporary) throws ActiveMQException - { + final boolean temporary) throws ActiveMQException { } public void createQueue(final String address, final String queueName, final String filterString, - final boolean durable) throws ActiveMQException - { + final boolean durable) throws ActiveMQException { } - public void createTemporaryQueue(final SimpleString address, final SimpleString queueName) throws ActiveMQException - { + public void createTemporaryQueue(final SimpleString address, + final SimpleString queueName) throws ActiveMQException { } - public void createTemporaryQueue(final String address, final String queueName) throws ActiveMQException - { + public void createTemporaryQueue(final String address, final String queueName) throws ActiveMQException { } public void createTemporaryQueue(final SimpleString address, final SimpleString queueName, - final SimpleString filter) throws ActiveMQException - { + final SimpleString filter) throws ActiveMQException { } - public void createTemporaryQueue(final String address, final String queueName, final String filter) throws ActiveMQException - { + public void createTemporaryQueue(final String address, + final String queueName, + final String filter) throws ActiveMQException { } - public void deleteQueue(final SimpleString queueName) throws ActiveMQException - { + public void deleteQueue(final SimpleString queueName) throws ActiveMQException { } - public void deleteQueue(final String queueName) throws ActiveMQException - { + public void deleteQueue(final String queueName) throws ActiveMQException { } - public ClientConsumer createConsumer(final SimpleString queueName) throws ActiveMQException - { + public ClientConsumer createConsumer(final SimpleString queueName) throws ActiveMQException { return null; } - public ClientConsumer createConsumer(final SimpleString queueName, final SimpleString filterString) throws ActiveMQException - { + public ClientConsumer createConsumer(final SimpleString queueName, + final SimpleString filterString) throws ActiveMQException { return null; } public ClientConsumer createConsumer(final SimpleString queueName, final SimpleString filterString, - final boolean browseOnly) throws ActiveMQException - { + final boolean browseOnly) throws ActiveMQException { return null; } @@ -1095,23 +926,21 @@ public class MessageHeaderTest extends MessageHeaderTestBase final SimpleString filterString, final int windowSize, final int maxRate, - final boolean browseOnly) throws ActiveMQException - { + final boolean browseOnly) throws ActiveMQException { return null; } - public ClientConsumer createConsumer(final String queueName) throws ActiveMQException - { + public ClientConsumer createConsumer(final String queueName) throws ActiveMQException { return null; } - public ClientConsumer createConsumer(final String queueName, final String filterString) throws ActiveMQException - { + public ClientConsumer createConsumer(final String queueName, final String filterString) throws ActiveMQException { return null; } - public ClientConsumer createConsumer(final String queueName, final String filterString, final boolean browseOnly) throws ActiveMQException - { + public ClientConsumer createConsumer(final String queueName, + final String filterString, + final boolean browseOnly) throws ActiveMQException { return null; } @@ -1119,28 +948,25 @@ public class MessageHeaderTest extends MessageHeaderTestBase final String filterString, final int windowSize, final int maxRate, - final boolean browseOnly) throws ActiveMQException - { + final boolean browseOnly) throws ActiveMQException { return null; } - public ClientConsumer createFileConsumer(final File directory, final SimpleString queueName) throws ActiveMQException - { + public ClientConsumer createFileConsumer(final File directory, + final SimpleString queueName) throws ActiveMQException { return null; } public ClientConsumer createFileConsumer(final File directory, final SimpleString queueName, - final SimpleString filterString) throws ActiveMQException - { + final SimpleString filterString) throws ActiveMQException { return null; } public ClientConsumer createFileConsumer(final File directory, final SimpleString queueName, final SimpleString filterString, - final boolean browseOnly) throws ActiveMQException - { + final boolean browseOnly) throws ActiveMQException { return null; } @@ -1149,26 +975,24 @@ public class MessageHeaderTest extends MessageHeaderTestBase final SimpleString filterString, final int windowSize, final int maxRate, - final boolean browseOnly) throws ActiveMQException - { + final boolean browseOnly) throws ActiveMQException { return null; } - public ClientConsumer createFileConsumer(final File directory, final String queueName) throws ActiveMQException - { + public ClientConsumer createFileConsumer(final File directory, final String queueName) throws ActiveMQException { return null; } - public ClientConsumer createFileConsumer(final File directory, final String queueName, final String filterString) throws ActiveMQException - { + public ClientConsumer createFileConsumer(final File directory, + final String queueName, + final String filterString) throws ActiveMQException { return null; } public ClientConsumer createFileConsumer(final File directory, final String queueName, final String filterString, - final boolean browseOnly) throws ActiveMQException - { + final boolean browseOnly) throws ActiveMQException { return null; } @@ -1177,111 +1001,90 @@ public class MessageHeaderTest extends MessageHeaderTestBase final String filterString, final int windowSize, final int maxRate, - final boolean browseOnly) throws ActiveMQException - { + final boolean browseOnly) throws ActiveMQException { return null; } - public ClientProducer createProducer() throws ActiveMQException - { + public ClientProducer createProducer() throws ActiveMQException { return null; } - public ClientProducer createProducer(final SimpleString address) throws ActiveMQException - { + public ClientProducer createProducer(final SimpleString address) throws ActiveMQException { return null; } - public ClientProducer createProducer(final SimpleString address, final int rate) throws ActiveMQException - { + public ClientProducer createProducer(final SimpleString address, final int rate) throws ActiveMQException { return null; } public ClientProducer createProducer(final SimpleString address, final int maxRate, final boolean blockOnNonDurableSend, - final boolean blockOnDurableSend) throws ActiveMQException - { + final boolean blockOnDurableSend) throws ActiveMQException { return null; } - public ClientProducer createProducer(final String address) throws ActiveMQException - { + public ClientProducer createProducer(final String address) throws ActiveMQException { return null; } - public ClientProducer createProducer(final String address, final int rate) throws ActiveMQException - { + public ClientProducer createProducer(final String address, final int rate) throws ActiveMQException { return null; } public ClientProducer createProducer(final String address, final int maxRate, final boolean blockOnNonDurableSend, - final boolean blockOnDurableSend) throws ActiveMQException - { + final boolean blockOnDurableSend) throws ActiveMQException { return null; } - public QueueQuery queueQuery(final SimpleString queueName) throws ActiveMQException - { + public QueueQuery queueQuery(final SimpleString queueName) throws ActiveMQException { return null; } - public AddressQuery addressQuery(final SimpleString address) throws ActiveMQException - { + public AddressQuery addressQuery(final SimpleString address) throws ActiveMQException { return null; } - public XAResource getXAResource() - { + public XAResource getXAResource() { return null; } - public void commit() throws ActiveMQException - { + public void commit() throws ActiveMQException { } - public boolean isRollbackOnly() - { + public boolean isRollbackOnly() { return false; } - public void rollback() throws ActiveMQException - { + public void rollback() throws ActiveMQException { } - public void rollback(final boolean considerLastMessageAsDelivered) throws ActiveMQException - { + public void rollback(final boolean considerLastMessageAsDelivered) throws ActiveMQException { } - public void close() throws ActiveMQException - { + public void close() throws ActiveMQException { } - public boolean isClosed() - { + public boolean isClosed() { return false; } - public boolean isAutoCommitSends() - { + public boolean isAutoCommitSends() { return false; } - public boolean isAutoCommitAcks() - { + public boolean isAutoCommitAcks() { return false; } - public boolean isBlockOnAcknowledge() - { + public boolean isBlockOnAcknowledge() { return false; } - public boolean isXA() - { + public boolean isXA() { return false; } @@ -1289,108 +1092,86 @@ public class MessageHeaderTest extends MessageHeaderTestBase final boolean durable, final long expiration, final long timestamp, - final byte priority) - { + final byte priority) { return message; } - public ClientMessage createMessage(final byte type, final boolean durable) - { + public ClientMessage createMessage(final byte type, final boolean durable) { return message; } - public ClientMessage createMessage(final boolean durable) - { + public ClientMessage createMessage(final boolean durable) { return message; } - public FakeSession start() throws ActiveMQException - { + public FakeSession start() throws ActiveMQException { return this; } - public void stop() throws ActiveMQException - { + public void stop() throws ActiveMQException { } - public void addFailureListener(final FailureListener listener) - { + public void addFailureListener(final FailureListener listener) { } - public void addFailoverListener(FailoverEventListener listener) - { + public void addFailoverListener(FailoverEventListener listener) { } - public boolean removeFailureListener(final FailureListener listener) - { + public boolean removeFailureListener(final FailureListener listener) { return false; } - public boolean removeFailoverListener(FailoverEventListener listener) - { + public boolean removeFailoverListener(FailoverEventListener listener) { return false; } - public int getVersion() - { + public int getVersion() { return 0; } - public FakeSession setSendAcknowledgementHandler(final SendAcknowledgementHandler handler) - { + public FakeSession setSendAcknowledgementHandler(final SendAcknowledgementHandler handler) { return this; } - public void commit(final Xid xid, final boolean b) throws XAException - { + public void commit(final Xid xid, final boolean b) throws XAException { } - public void end(final Xid xid, final int i) throws XAException - { + public void end(final Xid xid, final int i) throws XAException { } - public void forget(final Xid xid) throws XAException - { + public void forget(final Xid xid) throws XAException { } - public int getTransactionTimeout() throws XAException - { + public int getTransactionTimeout() throws XAException { return 0; } - public boolean isSameRM(final XAResource xaResource) throws XAException - { + public boolean isSameRM(final XAResource xaResource) throws XAException { return false; } - public int prepare(final Xid xid) throws XAException - { + public int prepare(final Xid xid) throws XAException { return 0; } - public Xid[] recover(final int i) throws XAException - { + public Xid[] recover(final int i) throws XAException { return new Xid[0]; } - public void rollback(final Xid xid) throws XAException - { + public void rollback(final Xid xid) throws XAException { } - public boolean setTransactionTimeout(final int i) throws XAException - { + public boolean setTransactionTimeout(final int i) throws XAException { return false; } - public void start(final Xid xid, final int i) throws XAException - { + public void start(final Xid xid, final int i) throws XAException { } /* (non-Javadoc) * @see ClientSession#createTransportBuffer(byte[]) */ - public ActiveMQBuffer createBuffer(final byte[] bytes) - { + public ActiveMQBuffer createBuffer(final byte[] bytes) { // TODO Auto-generated method stub return null; } @@ -1398,21 +1179,17 @@ public class MessageHeaderTest extends MessageHeaderTestBase /* (non-Javadoc) * @see ClientSession#createTransportBuffer(int) */ - public ActiveMQBuffer createBuffer(final int size) - { + public ActiveMQBuffer createBuffer(final int size) { // TODO Auto-generated method stub return null; } - - public void addFailureListener(final SessionFailureListener listener) - { + public void addFailureListener(final SessionFailureListener listener) { // TODO Auto-generated method stub } - public boolean removeFailureListener(final SessionFailureListener listener) - { + public boolean removeFailureListener(final SessionFailureListener listener) { // TODO Auto-generated method stub return false; } @@ -1420,8 +1197,7 @@ public class MessageHeaderTest extends MessageHeaderTestBase /* (non-Javadoc) * @see ClientSession#createQueue(org.apache.activemq.artemis.utils.SimpleString, org.apache.activemq.artemis.utils.SimpleString) */ - public void createQueue(SimpleString address, SimpleString queueName) throws ActiveMQException - { + public void createQueue(SimpleString address, SimpleString queueName) throws ActiveMQException { // TODO Auto-generated method stub } @@ -1429,8 +1205,7 @@ public class MessageHeaderTest extends MessageHeaderTestBase /* (non-Javadoc) * @see ClientSession#setClientID(java.lang.String) */ - public void setClientID(String clientID) - { + public void setClientID(String clientID) { // TODO Auto-generated method stub } @@ -1438,8 +1213,7 @@ public class MessageHeaderTest extends MessageHeaderTestBase /* (non-Javadoc) * @see ClientSession#addMetaData(java.lang.String, java.lang.String) */ - public void addMetaData(String key, String data) throws ActiveMQException - { + public void addMetaData(String key, String data) throws ActiveMQException { // TODO Auto-generated method stub } @@ -1447,15 +1221,13 @@ public class MessageHeaderTest extends MessageHeaderTestBase /* (non-Javadoc) * @see ClientSession#addUniqueMetaData(java.lang.String, java.lang.String) */ - public void addUniqueMetaData(String key, String data) throws ActiveMQException - { + public void addUniqueMetaData(String key, String data) throws ActiveMQException { // TODO Auto-generated method stub } @Override - public ClientSessionFactory getSessionFactory() - { + public ClientSessionFactory getSessionFactory() { return null; } } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MessageHeaderTestBase.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MessageHeaderTestBase.java index 5ce252785f..f57f9b9d90 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MessageHeaderTestBase.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MessageHeaderTestBase.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.jms.tests.message; + import java.util.Arrays; import java.util.Enumeration; @@ -43,8 +44,7 @@ import org.apache.activemq.artemis.jms.tests.ActiveMQServerTestCase; import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; import org.junit.Before; -public abstract class MessageHeaderTestBase extends ActiveMQServerTestCase -{ +public abstract class MessageHeaderTestBase extends ActiveMQServerTestCase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -52,8 +52,7 @@ public abstract class MessageHeaderTestBase extends ActiveMQServerTestCase /** * Loads the message header fields with significant values. */ - public static void configureMessage(final ActiveMQMessage m) throws JMSException - { + public static void configureMessage(final ActiveMQMessage m) throws JMSException { m.setJMSMessageID("ID:messageID777"); m.setJMSTimestamp(123456789L); m.setJMSCorrelationID("correlationID777"); @@ -63,8 +62,8 @@ public abstract class MessageHeaderTestBase extends ActiveMQServerTestCase m.setJMSExpiration(987654321L); m.setJMSPriority(9); m.setBooleanProperty("booleanProperty", true); - m.setByteProperty("byteProperty", (byte)2); - m.setShortProperty("shortProperty", (short)3); + m.setByteProperty("byteProperty", (byte) 2); + m.setShortProperty("shortProperty", (short) 3); m.setIntProperty("intProperty", 4); m.setLongProperty("longProperty", 5L); m.setFloatProperty("floatProperty", 6); @@ -77,8 +76,7 @@ public abstract class MessageHeaderTestBase extends ActiveMQServerTestCase * Makes sure two physically different message are equivalent: they have identical JMS fields and * body. */ - public static void ensureEquivalent(final Message m1, final ActiveMQMessage m2) throws JMSException - { + public static void ensureEquivalent(final Message m1, final ActiveMQMessage m2) throws JMSException { ProxyAssertSupport.assertTrue(m1 != m2); // Can't compare message id since not set until send @@ -88,35 +86,28 @@ public abstract class MessageHeaderTestBase extends ActiveMQServerTestCase byte[] corrIDBytes = null; String corrIDString = null; - try - { + try { corrIDBytes = m1.getJMSCorrelationIDAsBytes(); } - catch (JMSException e) - { + catch (JMSException e) { // correlation ID specified as String corrIDString = m1.getJMSCorrelationID(); } - if (corrIDBytes != null) - { + if (corrIDBytes != null) { ProxyAssertSupport.assertTrue(Arrays.equals(corrIDBytes, m2.getJMSCorrelationIDAsBytes())); } - else if (corrIDString != null) - { + else if (corrIDString != null) { ProxyAssertSupport.assertEquals(corrIDString, m2.getJMSCorrelationID()); } - else - { + else { // no correlation id - try - { + try { byte[] corrID2 = m2.getJMSCorrelationIDAsBytes(); ProxyAssertSupport.assertNull(corrID2); } - catch (JMSException e) - { + catch (JMSException e) { // correlatin ID specified as String String corrID2 = m2.getJMSCorrelationID(); ProxyAssertSupport.assertNull(corrID2); @@ -131,171 +122,141 @@ public abstract class MessageHeaderTestBase extends ActiveMQServerTestCase ProxyAssertSupport.assertEquals(m1.getJMSPriority(), m2.getJMSPriority()); int m1PropertyCount = 0, m2PropertyCount = 0; - for (Enumeration p = m1.getPropertyNames(); p.hasMoreElements();) - { + for (Enumeration p = m1.getPropertyNames(); p.hasMoreElements(); ) { String name = p.nextElement(); - if (!name.startsWith("JMSX")) - { + if (!name.startsWith("JMSX")) { m1PropertyCount++; } } - for (Enumeration p = m2.getPropertyNames(); p.hasMoreElements();) - { - String name = (String)p.nextElement(); + for (Enumeration p = m2.getPropertyNames(); p.hasMoreElements(); ) { + String name = (String) p.nextElement(); - if (!name.startsWith("JMSX")) - { + if (!name.startsWith("JMSX")) { m2PropertyCount++; } } ProxyAssertSupport.assertEquals(m1PropertyCount, m2PropertyCount); - for (Enumeration props = m1.getPropertyNames(); props.hasMoreElements();) - { + for (Enumeration props = m1.getPropertyNames(); props.hasMoreElements(); ) { boolean found = false; - String name = (String)props.nextElement(); + String name = (String) props.nextElement(); - if (name.startsWith("JMSX")) - { + if (name.startsWith("JMSX")) { // ignore continue; } boolean booleanProperty = false; - try - { + try { booleanProperty = m1.getBooleanProperty(name); found = true; } - catch (JMSException e) - { + catch (JMSException e) { // not a boolean } - if (found) - { + if (found) { ProxyAssertSupport.assertEquals(booleanProperty, m2.getBooleanProperty(name)); continue; } byte byteProperty = 0; - try - { + try { byteProperty = m1.getByteProperty(name); found = true; } - catch (JMSException e) - { + catch (JMSException e) { // not a byte } - if (found) - { + if (found) { ProxyAssertSupport.assertEquals(byteProperty, m2.getByteProperty(name)); continue; } short shortProperty = 0; - try - { + try { shortProperty = m1.getShortProperty(name); found = true; } - catch (JMSException e) - { + catch (JMSException e) { // not a short } - if (found) - { + if (found) { ProxyAssertSupport.assertEquals(shortProperty, m2.getShortProperty(name)); continue; } int intProperty = 0; - try - { + try { intProperty = m1.getIntProperty(name); found = true; } - catch (JMSException e) - { + catch (JMSException e) { // not an int } - if (found) - { + if (found) { ProxyAssertSupport.assertEquals(intProperty, m2.getIntProperty(name)); continue; } long longProperty = 0; - try - { + try { longProperty = m1.getLongProperty(name); found = true; } - catch (JMSException e) - { + catch (JMSException e) { // not a long } - if (found) - { + if (found) { ProxyAssertSupport.assertEquals(longProperty, m2.getLongProperty(name)); continue; } float floatProperty = 0; - try - { + try { floatProperty = m1.getFloatProperty(name); found = true; } - catch (JMSException e) - { + catch (JMSException e) { // not a float } - if (found) - { + if (found) { ProxyAssertSupport.assertTrue(floatProperty == m2.getFloatProperty(name)); continue; } double doubleProperty = 0; - try - { + try { doubleProperty = m1.getDoubleProperty(name); found = true; } - catch (JMSException e) - { + catch (JMSException e) { // not a double } - if (found) - { + if (found) { ProxyAssertSupport.assertTrue(doubleProperty == m2.getDoubleProperty(name)); continue; } String stringProperty = null; - try - { + try { stringProperty = m1.getStringProperty(name); found = true; } - catch (JMSException e) - { + catch (JMSException e) { // not a String } - if (found) - { + if (found) { ProxyAssertSupport.assertEquals(stringProperty, m2.getStringProperty(name)); continue; } @@ -304,87 +265,71 @@ public abstract class MessageHeaderTestBase extends ActiveMQServerTestCase } } - public static void ensureEquivalent(final BytesMessage m1, final ActiveMQBytesMessage m2) throws JMSException - { - MessageHeaderTestBase.ensureEquivalent((Message)m1, m2); + public static void ensureEquivalent(final BytesMessage m1, final ActiveMQBytesMessage m2) throws JMSException { + MessageHeaderTestBase.ensureEquivalent((Message) m1, m2); long len = m1.getBodyLength(); - for (int i = 0; i < len; i++) - { + for (int i = 0; i < len; i++) { ProxyAssertSupport.assertEquals(m1.readByte(), m2.readByte()); } - try - { + try { m1.readByte(); ProxyAssertSupport.fail("should throw MessageEOFException"); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { // OK } - try - { + try { m2.readByte(); ProxyAssertSupport.fail("should throw MessageEOFException"); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { // OK } } @SuppressWarnings("unchecked") - public static void ensureEquivalent(final MapMessage m1, final ActiveMQMapMessage m2) throws JMSException - { - MessageHeaderTestBase.ensureEquivalent((Message)m1, m2); + public static void ensureEquivalent(final MapMessage m1, final ActiveMQMapMessage m2) throws JMSException { + MessageHeaderTestBase.ensureEquivalent((Message) m1, m2); - for (Enumeration e = m1.getMapNames(); e.hasMoreElements();) - { + for (Enumeration e = m1.getMapNames(); e.hasMoreElements(); ) { String name = e.nextElement(); ProxyAssertSupport.assertEquals(m1.getObject(name), m2.getObject(name)); } - for (Enumeration e = m2.getMapNames(); e.hasMoreElements();) - { + for (Enumeration e = m2.getMapNames(); e.hasMoreElements(); ) { String name = e.nextElement(); ProxyAssertSupport.assertEquals(m2.getObject(name), m1.getObject(name)); } } - public static void ensureEquivalent(final ObjectMessage m1, final ActiveMQObjectMessage m2) throws JMSException - { - MessageHeaderTestBase.ensureEquivalent((Message)m1, m2); + public static void ensureEquivalent(final ObjectMessage m1, final ActiveMQObjectMessage m2) throws JMSException { + MessageHeaderTestBase.ensureEquivalent((Message) m1, m2); ProxyAssertSupport.assertEquals(m1.getObject(), m2.getObject()); } - public static void ensureEquivalent(final StreamMessage m1, final ActiveMQStreamMessage m2) throws JMSException - { - MessageHeaderTestBase.ensureEquivalent((Message)m1, m2); + public static void ensureEquivalent(final StreamMessage m1, final ActiveMQStreamMessage m2) throws JMSException { + MessageHeaderTestBase.ensureEquivalent((Message) m1, m2); m1.reset(); m2.reset(); boolean m1eof = false, m2eof = false; - while (true) - { + while (true) { byte b1, b2; - try - { + try { b1 = m1.readByte(); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { m1eof = true; break; } - try - { + try { b2 = m2.readByte(); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { m2eof = true; break; } @@ -392,36 +337,29 @@ public abstract class MessageHeaderTestBase extends ActiveMQServerTestCase ProxyAssertSupport.assertEquals(b1, b2); } - if (m1eof) - { - try - { + if (m1eof) { + try { m2.readByte(); ProxyAssertSupport.fail("should throw MessageEOFException"); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { // OK } } - if (m2eof) - { - try - { + if (m2eof) { + try { m1.readByte(); ProxyAssertSupport.fail("should throw MessageEOFException"); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { // OK } } } - public static void ensureEquivalent(final TextMessage m1, final ActiveMQTextMessage m2) throws JMSException - { - MessageHeaderTestBase.ensureEquivalent((Message)m1, m2); + public static void ensureEquivalent(final TextMessage m1, final ActiveMQTextMessage m2) throws JMSException { + MessageHeaderTestBase.ensureEquivalent((Message) m1, m2); ProxyAssertSupport.assertEquals(m1.getText(), m2.getText()); } @@ -442,8 +380,7 @@ public abstract class MessageHeaderTestBase extends ActiveMQServerTestCase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); producerConnection = addConnection(getConnectionFactory().createConnection()); diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MessagePropertyConversionTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MessagePropertyConversionTest.java index e91319b19f..1283c087b2 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MessagePropertyConversionTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MessagePropertyConversionTest.java @@ -38,8 +38,7 @@ import org.junit.Test; /** * Testing of message property conversion. See {@link javax.jms.Message} for details */ -public class MessagePropertyConversionTest extends ActiveMQServerTestCase -{ +public class MessagePropertyConversionTest extends ActiveMQServerTestCase { // Attributes ---------------------------------------------------- private Connection producerConnection, consumerConnection; @@ -56,8 +55,7 @@ public class MessagePropertyConversionTest extends ActiveMQServerTestCase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); producerConnection = getConnectionFactory().createConnection(); @@ -74,15 +72,13 @@ public class MessagePropertyConversionTest extends ActiveMQServerTestCase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { producerConnection.close(); consumerConnection.close(); } @Test - public void testObjectString() throws Exception - { + public void testObjectString() throws Exception { JMSContext ctx = addContext(getConnectionFactory().createContext()); JMSProducer producer = ctx.createProducer(); @@ -97,98 +93,78 @@ public class MessagePropertyConversionTest extends ActiveMQServerTestCase } @Test - public void msgNullPropertyConversionTests() throws Exception - { + public void msgNullPropertyConversionTests() throws Exception { JMSContext ctx = addContext(getConnectionFactory().createContext()); JMSProducer producer = ctx.createProducer(); - try - { + try { producer.setProperty(null, true); ProxyAssertSupport.fail("expected IllegalArgumentException"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { //pass } - try - { + try { producer.setProperty(null, "string"); ProxyAssertSupport.fail("expected IllegalArgumentException"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { //pass } - try - { + try { producer.setProperty(null, 1); ProxyAssertSupport.fail("expected IllegalArgumentException"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { //pass } - try - { + try { producer.setProperty(null, 1.0); ProxyAssertSupport.fail("expected IllegalArgumentException"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { //pass } - try - { + try { producer.setProperty(null, 1L); ProxyAssertSupport.fail("expected IllegalArgumentException"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { //pass } - try - { + try { producer.setProperty(null, 1.10f); ProxyAssertSupport.fail("expected IllegalArgumentException"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { //pass } - try - { + try { producer.setProperty(null, (byte) 1); ProxyAssertSupport.fail("expected IllegalArgumentException"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { //pass } - try - { + try { producer.setProperty(null, (short) 1); ProxyAssertSupport.fail("expected IllegalArgumentException"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { //pass } - try - { + try { producer.setProperty(null, new SimpleString("foo")); ProxyAssertSupport.fail("expected IllegalArgumentException"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { //pass } } @Test - public void msgPropertyConversionTests() throws Exception - { + public void msgPropertyConversionTests() throws Exception { JMSContext ctx = addContext(getConnectionFactory().createContext()); JMSProducer producer = ctx.createProducer(); @@ -214,629 +190,501 @@ public class MessagePropertyConversionTest extends ActiveMQServerTestCase producer.setProperty("anotherString", "1"); String myBool = producer.getStringProperty("aboolean"); - if (Boolean.valueOf(myBool).booleanValue() != bool) - { + if (Boolean.valueOf(myBool).booleanValue() != bool) { ProxyAssertSupport.fail("conversion from boolean to string failed"); } - try - { + try { producer.getByteProperty("aboolean"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("did not catch expected Exception -- boolean to byte"); } - try - { + try { producer.getShortProperty("aboolean"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - try - { + try { producer.getIntProperty("aboolean"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - try - { + try { producer.getLongProperty("aboolean"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - try - { + try { producer.getFloatProperty("aboolean"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } // invalid - boolean to double - try - { + try { producer.getDoubleProperty("aboolean"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } String myByte = producer.getStringProperty("abyte"); - if (Byte.valueOf(myByte).byteValue() != bValue) - { + if (Byte.valueOf(myByte).byteValue() != bValue) { ProxyAssertSupport.fail("conversion from byte to string failed"); } - if (producer.getShortProperty("abyte") != bValue) - { + if (producer.getShortProperty("abyte") != bValue) { ProxyAssertSupport.fail("conversion from byte to short failed"); } - if (producer.getIntProperty("abyte") != bValue) - { + if (producer.getIntProperty("abyte") != bValue) { ProxyAssertSupport.fail("conversion from byte to int failed"); } - if (producer.getLongProperty("abyte") != bValue) - { + if (producer.getLongProperty("abyte") != bValue) { ProxyAssertSupport.fail("conversion from byte to long failed"); } - try - { + try { producer.getBooleanProperty("abyte"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - try - { + try { producer.getFloatProperty("abyte"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - try - { + try { producer.getDoubleProperty("abyte"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } String myshort = producer.getStringProperty("ashort"); - if (Short.valueOf(myshort).shortValue() != nShort) - { + if (Short.valueOf(myshort).shortValue() != nShort) { ProxyAssertSupport.fail("conversion from short to string failed"); } - if (producer.getIntProperty("ashort") != nShort) - { + if (producer.getIntProperty("ashort") != nShort) { ProxyAssertSupport.fail("conversion from short to int failed"); } - if (producer.getLongProperty("ashort") != nShort) - { + if (producer.getLongProperty("ashort") != nShort) { ProxyAssertSupport.fail("conversion from short to long failed"); } - try - { + try { producer.getBooleanProperty("ashort"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - try - { + try { producer.getByteProperty("ashort"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - try - { + try { producer.getFloatProperty("ashort"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - try - { + try { producer.getDoubleProperty("ashort"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - if (Integer.valueOf(producer.getStringProperty("anint")).intValue() != nInt) - { + if (Integer.valueOf(producer.getStringProperty("anint")).intValue() != nInt) { ProxyAssertSupport.fail("conversion from int to string failed"); } - if (producer.getLongProperty("anint") != nInt) - { + if (producer.getLongProperty("anint") != nInt) { ProxyAssertSupport.fail("conversion from int to long failed"); } - try - { + try { producer.getBooleanProperty("anint"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - try - { + try { producer.getByteProperty("anint"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - try - { + try { producer.getShortProperty("anint"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - try - { + try { producer.getFloatProperty("anint"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - try - { + try { producer.getDoubleProperty("anint"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - if (Long.valueOf(producer.getStringProperty("along")).longValue() != nLong) - { + if (Long.valueOf(producer.getStringProperty("along")).longValue() != nLong) { ProxyAssertSupport.fail("conversion from long to string failed"); } - try - { + try { producer.getBooleanProperty("along"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - try - { + try { producer.getByteProperty("along"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - try - { + try { producer.getShortProperty("along"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - try - { + try { producer.getIntProperty("along"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - try - { + try { producer.getFloatProperty("along"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - try - { + try { producer.getDoubleProperty("along"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - if (Float.valueOf(producer.getStringProperty("afloat")).floatValue() != nFloat) - { + if (Float.valueOf(producer.getStringProperty("afloat")).floatValue() != nFloat) { ProxyAssertSupport.fail("conversion from float to string failed"); } - if (producer.getDoubleProperty("afloat") != nFloat) - { + if (producer.getDoubleProperty("afloat") != nFloat) { ProxyAssertSupport.fail("conversion from long to double failed"); } - try - { + try { producer.getBooleanProperty("afloat"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - try - { + try { producer.getByteProperty("afloat"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - try - { + try { producer.getShortProperty("afloat"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - try - { + try { producer.getIntProperty("afloat"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - try - { + try { producer.getLongProperty("afloat"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - if (Double.valueOf(producer.getStringProperty("adouble")).doubleValue() != nDouble) - { + if (Double.valueOf(producer.getStringProperty("adouble")).doubleValue() != nDouble) { ProxyAssertSupport.fail("conversion from double to string failed"); } - try - { + try { producer.getBooleanProperty("adouble"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - try - { + try { producer.getByteProperty("adouble"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - try - { + try { producer.getShortProperty("adouble"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - try - { + try { producer.getIntProperty("adouble"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - try - { + try { producer.getLongProperty("adouble"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } // invalid - double to float - try - { + try { producer.getFloatProperty("adouble"); ProxyAssertSupport.fail("MessageFormatRuntimeException expected"); } - catch (MessageFormatRuntimeException me) - { + catch (MessageFormatRuntimeException me) { //pass } - catch (Exception ee) - { + catch (Exception ee) { ProxyAssertSupport.fail("Caught unexpected exception: " + ee); } - if ((producer.getBooleanProperty("true")) != true) - { + if ((producer.getBooleanProperty("true")) != true) { ProxyAssertSupport.fail("conversion from string to boolean - expect true - failed"); } - if ((producer.getBooleanProperty("false")) != false) - { + if ((producer.getBooleanProperty("false")) != false) { ProxyAssertSupport.fail("conversion from string to boolean expect false - failed"); } - if (producer.getByteProperty("anotherString") != 1) - { + if (producer.getByteProperty("anotherString") != 1) { ProxyAssertSupport.fail("conversion from string to byte failed"); } - if (producer.getShortProperty("anotherString") != 1) - { + if (producer.getShortProperty("anotherString") != 1) { ProxyAssertSupport.fail("conversion from string to short failed"); } - if (producer.getIntProperty("anotherString") != 1) - { + if (producer.getIntProperty("anotherString") != 1) { ProxyAssertSupport.fail("conversion from string to int failed"); } - if (producer.getLongProperty("anotherString") != 1) - { + if (producer.getLongProperty("anotherString") != 1) { ProxyAssertSupport.fail("conversion from string to long failed"); } - if (producer.getFloatProperty("anotherString") != 1) - { + if (producer.getFloatProperty("anotherString") != 1) { ProxyAssertSupport.fail("conversion from string to float failed"); } - if (producer.getDoubleProperty("anotherString") != 1) - { + if (producer.getDoubleProperty("anotherString") != 1) { ProxyAssertSupport.fail("conversion from string to double failed"); } } @Test - public void testResetToNull() throws JMSException - { + public void testResetToNull() throws JMSException { Message m1 = queueProducerSession.createMessage(); m1.setStringProperty("key", "fish"); m1.setBooleanProperty("key", true); @@ -853,8 +701,7 @@ public class MessagePropertyConversionTest extends ActiveMQServerTestCase } @Test - public void testBooleanConversion() throws Exception - { + public void testBooleanConversion() throws Exception { Message m1 = queueProducerSession.createMessage(); boolean myBool = true; @@ -869,64 +716,51 @@ public class MessagePropertyConversionTest extends ActiveMQServerTestCase ProxyAssertSupport.assertEquals(myBool, m2.getBooleanProperty("myBool")); ProxyAssertSupport.assertEquals(String.valueOf(myBool), m2.getStringProperty("myBool")); - try - { + try { m2.getByteProperty("myBool"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getShortProperty("myBool"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getIntProperty("myBool"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getLongProperty("myBool"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getFloatProperty("myBool"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getDoubleProperty("myBool"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } } @Test - public void testByteConversion() throws Exception - { + public void testByteConversion() throws Exception { Message m1 = queueProducerSession.createMessage(); byte myByte = 13; @@ -943,37 +777,30 @@ public class MessagePropertyConversionTest extends ActiveMQServerTestCase ProxyAssertSupport.assertEquals(myByte, m2.getLongProperty("myByte")); ProxyAssertSupport.assertEquals(String.valueOf(myByte), m2.getStringProperty("myByte")); - try - { + try { m2.getBooleanProperty("myByte"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getFloatProperty("myByte"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getDoubleProperty("myByte"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } } @Test - public void testShortConversion() throws Exception - { + public void testShortConversion() throws Exception { Message m1 = queueProducerSession.createMessage(); short myShort = 15321; @@ -989,46 +816,37 @@ public class MessagePropertyConversionTest extends ActiveMQServerTestCase ProxyAssertSupport.assertEquals(myShort, m2.getLongProperty("myShort")); ProxyAssertSupport.assertEquals(String.valueOf(myShort), m2.getStringProperty("myShort")); - try - { + try { m2.getByteProperty("myShort"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getBooleanProperty("myShort"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getFloatProperty("myShort"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getDoubleProperty("myShort"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } } @Test - public void testIntConversion() throws Exception - { + public void testIntConversion() throws Exception { Message m1 = queueProducerSession.createMessage(); int myInt = 0x71ab6c80; @@ -1043,55 +861,44 @@ public class MessagePropertyConversionTest extends ActiveMQServerTestCase ProxyAssertSupport.assertEquals(myInt, m2.getLongProperty("myInt")); ProxyAssertSupport.assertEquals(String.valueOf(myInt), m2.getStringProperty("myInt")); - try - { + try { m2.getShortProperty("myInt"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getByteProperty("myInt"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getBooleanProperty("myInt"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getFloatProperty("myInt"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getDoubleProperty("myInt"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } } @Test - public void testLongConversion() throws Exception - { + public void testLongConversion() throws Exception { Message m1 = queueProducerSession.createMessage(); long myLong = 0x20bf1e3fb6fa31dfL; @@ -1105,64 +912,51 @@ public class MessagePropertyConversionTest extends ActiveMQServerTestCase ProxyAssertSupport.assertEquals(myLong, m2.getLongProperty("myLong")); ProxyAssertSupport.assertEquals(String.valueOf(myLong), m2.getStringProperty("myLong")); - try - { + try { m2.getIntProperty("myLong"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getShortProperty("myLong"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getByteProperty("myLong"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getBooleanProperty("myLong"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getFloatProperty("myLong"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getDoubleProperty("myLong"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } } @Test - public void testFloatConversion() throws Exception - { + public void testFloatConversion() throws Exception { Message m1 = queueProducerSession.createMessage(); float myFloat = Float.MAX_VALUE - 23465; @@ -1177,55 +971,44 @@ public class MessagePropertyConversionTest extends ActiveMQServerTestCase ProxyAssertSupport.assertEquals(String.valueOf(myFloat), m2.getStringProperty("myFloat")); ProxyAssertSupport.assertEquals(myFloat, m2.getDoubleProperty("myFloat"), 0); - try - { + try { m2.getIntProperty("myFloat"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getShortProperty("myFloat"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getLongProperty("myFloat"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getByteProperty("myFloat"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getBooleanProperty("myFloat"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } } @Test - public void testDoubleConversion() throws Exception - { + public void testDoubleConversion() throws Exception { Message m1 = queueProducerSession.createMessage(); double myDouble = Double.MAX_VALUE - 72387633; @@ -1239,64 +1022,51 @@ public class MessagePropertyConversionTest extends ActiveMQServerTestCase ProxyAssertSupport.assertEquals(myDouble, m2.getDoubleProperty("myDouble"), 0); ProxyAssertSupport.assertEquals(String.valueOf(myDouble), m2.getStringProperty("myDouble")); - try - { + try { m2.getFloatProperty("myDouble"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getIntProperty("myDouble"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getShortProperty("myDouble"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getByteProperty("myDouble"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getBooleanProperty("myDouble"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - try - { + try { m2.getFloatProperty("myDouble"); ProxyAssertSupport.fail(); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } } @Test - public void testStringConversion() throws Exception - { + public void testStringConversion() throws Exception { Message m1 = queueProducerSession.createMessage(); boolean myBool = true; @@ -1347,59 +1117,46 @@ public class MessagePropertyConversionTest extends ActiveMQServerTestCase ProxyAssertSupport.assertEquals(false, m4.getBooleanProperty("myIllegal")); - try - { + try { m4.getByteProperty("myIllegal"); ProxyAssertSupport.fail(); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } - try - { + try { m4.getShortProperty("myIllegal"); ProxyAssertSupport.fail(); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } - try - { + try { m4.getIntProperty("myIllegal"); ProxyAssertSupport.fail(); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } - try - { + try { m4.getLongProperty("myIllegal"); ProxyAssertSupport.fail(); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } - try - { + try { m4.getFloatProperty("myIllegal"); ProxyAssertSupport.fail(); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } - try - { + try { m4.getDoubleProperty("myIllegal"); ProxyAssertSupport.fail(); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } } @Test - public void testJMSXDeliveryCountConversion() throws Exception - { + public void testJMSXDeliveryCountConversion() throws Exception { Message m1 = queueProducerSession.createMessage(); queueProducer.send(m1); diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MessageTestBase.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MessageTestBase.java index c5acd9a29f..0cd90313ea 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MessageTestBase.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/MessageTestBase.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.jms.tests.message; + import javax.jms.Connection; import javax.jms.DeliveryMode; import javax.jms.JMSException; @@ -29,8 +30,7 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -public abstract class MessageTestBase extends ActiveMQServerTestCase -{ +public abstract class MessageTestBase extends ActiveMQServerTestCase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -53,8 +53,7 @@ public abstract class MessageTestBase extends ActiveMQServerTestCase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); conn = getConnectionFactory().createConnection(); @@ -67,15 +66,13 @@ public abstract class MessageTestBase extends ActiveMQServerTestCase } @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { if (conn != null) conn.close(); } @Test - public void testNonPersistentSend() throws Exception - { + public void testNonPersistentSend() throws Exception { prepareMessage(message); queueProd.setDeliveryMode(DeliveryMode.NON_PERSISTENT); @@ -94,8 +91,7 @@ public abstract class MessageTestBase extends ActiveMQServerTestCase } @Test - public void testPersistentSend() throws Exception - { + public void testPersistentSend() throws Exception { prepareMessage(message); queueProd.setDeliveryMode(DeliveryMode.PERSISTENT); @@ -111,8 +107,7 @@ public abstract class MessageTestBase extends ActiveMQServerTestCase } @Test - public void testRedelivery() throws Exception - { + public void testRedelivery() throws Exception { prepareMessage(message); session.close(); @@ -144,8 +139,7 @@ public abstract class MessageTestBase extends ActiveMQServerTestCase } @Test - public void testSendMoreThanOnce() throws Exception - { + public void testSendMoreThanOnce() throws Exception { prepareMessage(message); session.close(); @@ -174,22 +168,20 @@ public abstract class MessageTestBase extends ActiveMQServerTestCase queueCons.close(); session.close(); - } // Package protected --------------------------------------------- // Protected ----------------------------------------------------- - protected void prepareMessage(final Message m) throws JMSException - { + protected void prepareMessage(final Message m) throws JMSException { m.setBooleanProperty("booleanProperty", true); - m.setByteProperty("byteProperty", (byte)3); + m.setByteProperty("byteProperty", (byte) 3); m.setDoubleProperty("doubleProperty", 4.0); m.setFloatProperty("floatProperty", 5.0f); m.setIntProperty("intProperty", 6); m.setLongProperty("longProperty", 7); - m.setShortProperty("shortProperty", (short)8); + m.setShortProperty("shortProperty", (short) 8); m.setStringProperty("stringProperty", "this is a String property"); m.setJMSCorrelationID("this is the correlation ID"); @@ -197,21 +189,19 @@ public abstract class MessageTestBase extends ActiveMQServerTestCase m.setJMSType("someArbitraryType"); } - private void assertEquivalent(final Message m, final int mode) throws JMSException - { + private void assertEquivalent(final Message m, final int mode) throws JMSException { assertEquivalent(m, mode, false); } - protected void assertEquivalent(final Message m, final int mode, final boolean redelivered) throws JMSException - { + protected void assertEquivalent(final Message m, final int mode, final boolean redelivered) throws JMSException { ProxyAssertSupport.assertNotNull(m); ProxyAssertSupport.assertEquals(true, m.getBooleanProperty("booleanProperty")); - ProxyAssertSupport.assertEquals((byte)3, m.getByteProperty("byteProperty")); + ProxyAssertSupport.assertEquals((byte) 3, m.getByteProperty("byteProperty")); ProxyAssertSupport.assertEquals(new Double(4.0), new Double(m.getDoubleProperty("doubleProperty"))); ProxyAssertSupport.assertEquals(new Float(5.0f), new Float(m.getFloatProperty("floatProperty"))); ProxyAssertSupport.assertEquals(6, m.getIntProperty("intProperty")); ProxyAssertSupport.assertEquals(7, m.getLongProperty("longProperty")); - ProxyAssertSupport.assertEquals((short)8, m.getShortProperty("shortProperty")); + ProxyAssertSupport.assertEquals((short) 8, m.getShortProperty("shortProperty")); ProxyAssertSupport.assertEquals("this is a String property", m.getStringProperty("stringProperty")); ProxyAssertSupport.assertEquals("this is the correlation ID", m.getJMSCorrelationID()); diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/ObjectMessageDeliveryTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/ObjectMessageDeliveryTest.java index 9cb40de624..37c530a5c3 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/ObjectMessageDeliveryTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/ObjectMessageDeliveryTest.java @@ -31,11 +31,9 @@ import org.apache.activemq.artemis.jms.tests.ActiveMQServerTestCase; import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; /** - * * ObjectMessageDeliveryTest */ -public class ObjectMessageDeliveryTest extends ActiveMQServerTestCase -{ +public class ObjectMessageDeliveryTest extends ActiveMQServerTestCase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -46,8 +44,8 @@ public class ObjectMessageDeliveryTest extends ActiveMQServerTestCase // Public -------------------------------------------------------- - static class TestObject implements Serializable - { + static class TestObject implements Serializable { + private static final long serialVersionUID = -340663970717491155L; String text; @@ -57,12 +55,10 @@ public class ObjectMessageDeliveryTest extends ActiveMQServerTestCase * */ @Test - public void testTopic() throws Exception - { + public void testTopic() throws Exception { TopicConnection conn = getTopicConnectionFactory().createTopicConnection(); - try - { + try { TopicSession s = conn.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); TopicPublisher publisher = s.createPublisher(ActiveMQServerTestCase.topic1); TopicSubscriber sub = s.createSubscriber(ActiveMQServerTestCase.topic1); @@ -95,33 +91,31 @@ public class ObjectMessageDeliveryTest extends ActiveMQServerTestCase publisher.send(om3); - ObjectMessage rm1 = (ObjectMessage)sub.receive(ActiveMQServerTestCase.MAX_TIMEOUT); + ObjectMessage rm1 = (ObjectMessage) sub.receive(ActiveMQServerTestCase.MAX_TIMEOUT); - ObjectMessage rm2 = (ObjectMessage)sub.receive(ActiveMQServerTestCase.MAX_TIMEOUT); + ObjectMessage rm2 = (ObjectMessage) sub.receive(ActiveMQServerTestCase.MAX_TIMEOUT); - ObjectMessage rm3 = (ObjectMessage)sub.receive(ActiveMQServerTestCase.MAX_TIMEOUT); + ObjectMessage rm3 = (ObjectMessage) sub.receive(ActiveMQServerTestCase.MAX_TIMEOUT); ProxyAssertSupport.assertNotNull(rm1); - TestObject ro1 = (TestObject)rm1.getObject(); + TestObject ro1 = (TestObject) rm1.getObject(); ProxyAssertSupport.assertEquals(to1.text, ro1.text); ProxyAssertSupport.assertNotNull(rm1); - TestObject ro2 = (TestObject)rm2.getObject(); + TestObject ro2 = (TestObject) rm2.getObject(); ProxyAssertSupport.assertEquals(to2.text, ro2.text); ProxyAssertSupport.assertNotNull(rm2); - TestObject ro3 = (TestObject)rm3.getObject(); + TestObject ro3 = (TestObject) rm3.getObject(); ProxyAssertSupport.assertEquals(to3.text, ro3.text); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/ObjectMessageTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/ObjectMessageTest.java index 0431fcecf7..1a3e922934 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/ObjectMessageTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/ObjectMessageTest.java @@ -34,31 +34,27 @@ import org.junit.Test; /** * A test that sends/receives object messages to the JMS provider and verifies their integrity. */ -public class ObjectMessageTest extends MessageTestBase -{ +public class ObjectMessageTest extends MessageTestBase { + @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); message = session.createObjectMessage(); } @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { message = null; super.tearDown(); } @Test - public void testClassLoaderIsolation() throws Exception - { + public void testClassLoaderIsolation() throws Exception { ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); - try - { + try { queueProd.setDeliveryMode(DeliveryMode.PERSISTENT); ObjectMessage om = (ObjectMessage) message; @@ -80,20 +76,17 @@ public class ObjectMessageTest extends MessageTestBase ProxyAssertSupport.assertEquals("org.apache.activemq.artemis.jms.tests.message.SomeObject", testObject2.getClass().getName()); ProxyAssertSupport.assertNotSame(testObject, testObject2); ProxyAssertSupport.assertNotSame(testObject.getClass(), testObject2.getClass()); - ProxyAssertSupport.assertNotSame(testObject.getClass().getClassLoader(), testObject2.getClass() - .getClassLoader()); + ProxyAssertSupport.assertNotSame(testObject.getClass().getClassLoader(), testObject2.getClass().getClassLoader()); ProxyAssertSupport.assertSame(testClassLoader, testObject2.getClass().getClassLoader()); } - finally - { + finally { Thread.currentThread().setContextClassLoader(originalClassLoader); } } @Test - public void testVectorOnObjectMessage() throws Exception - { + public void testVectorOnObjectMessage() throws Exception { java.util.Vector vectorOnMessage = new java.util.Vector(); vectorOnMessage.add("world!"); ((ObjectMessage) message).setObject(vectorOnMessage); @@ -109,8 +102,7 @@ public class ObjectMessageTest extends MessageTestBase } @Test - public void testObjectIsolation() throws Exception - { + public void testObjectIsolation() throws Exception { ObjectMessage msgTest = session.createObjectMessage(); ArrayList list = new ArrayList(); list.add("hello"); @@ -163,8 +155,7 @@ public class ObjectMessageTest extends MessageTestBase } @Test - public void testReadOnEmptyObjectMessage() throws Exception - { + public void testReadOnEmptyObjectMessage() throws Exception { ObjectMessage obm = (ObjectMessage) message; ProxyAssertSupport.assertNull(obm.getObject()); @@ -178,8 +169,7 @@ public class ObjectMessageTest extends MessageTestBase // Protected ------------------------------------------------------------------------------------ @Override - protected void prepareMessage(final Message m) throws JMSException - { + protected void prepareMessage(final Message m) throws JMSException { super.prepareMessage(m); ObjectMessage om = (ObjectMessage) m; @@ -188,31 +178,26 @@ public class ObjectMessageTest extends MessageTestBase } @Override - protected void assertEquivalent(final Message m, final int mode, final boolean redelivery) throws JMSException - { + protected void assertEquivalent(final Message m, final int mode, final boolean redelivery) throws JMSException { super.assertEquivalent(m, mode, redelivery); ObjectMessage om = (ObjectMessage) m; ProxyAssertSupport.assertEquals("this is the serializable object", om.getObject()); } - protected static ClassLoader newClassLoader(final Class anyUserClass) throws Exception - { + protected static ClassLoader newClassLoader(final Class anyUserClass) throws Exception { URL classLocation = anyUserClass.getProtectionDomain().getCodeSource().getLocation(); StringTokenizer tokenString = new StringTokenizer(System.getProperty("java.class.path"), File.pathSeparator); String pathIgnore = System.getProperty("java.home"); - if (pathIgnore == null) - { + if (pathIgnore == null) { pathIgnore = classLocation.toString(); } ArrayList urls = new ArrayList(); - while (tokenString.hasMoreElements()) - { + while (tokenString.hasMoreElements()) { String value = tokenString.nextToken(); URL itemLocation = new File(value).toURI().toURL(); - if (!itemLocation.equals(classLocation) && itemLocation.toString().indexOf(pathIgnore) >= 0) - { + if (!itemLocation.equals(classLocation) && itemLocation.toString().indexOf(pathIgnore) >= 0) { urls.add(itemLocation); } } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SimpleJMSBytesMessage.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SimpleJMSBytesMessage.java index 0cf32e8928..232b11f225 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SimpleJMSBytesMessage.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SimpleJMSBytesMessage.java @@ -30,8 +30,7 @@ import javax.jms.MessageFormatException; import javax.jms.MessageNotReadableException; import javax.jms.MessageNotWriteableException; -public class SimpleJMSBytesMessage extends SimpleJMSMessage implements BytesMessage -{ +public class SimpleJMSBytesMessage extends SimpleJMSMessage implements BytesMessage { // Static ------------------------------------------------------- // Attributes ---------------------------------------------------- @@ -50,469 +49,356 @@ public class SimpleJMSBytesMessage extends SimpleJMSMessage implements BytesMess // Constructor --------------------------------------------------- - public SimpleJMSBytesMessage() - { + public SimpleJMSBytesMessage() { ostream = new ByteArrayOutputStream(); p = new DataOutputStream(ostream); } // BytesMessage implementation ----------------------------------- - public boolean readBoolean() throws JMSException - { + public boolean readBoolean() throws JMSException { checkRead(); - try - { + try { return m.readBoolean(); } - catch (EOFException e) - { + catch (EOFException e) { throw new MessageEOFException(""); } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public byte readByte() throws JMSException - { + public byte readByte() throws JMSException { checkRead(); - try - { + try { return m.readByte(); } - catch (EOFException e) - { + catch (EOFException e) { throw new MessageEOFException(""); } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public int readUnsignedByte() throws JMSException - { + public int readUnsignedByte() throws JMSException { checkRead(); - try - { + try { return m.readUnsignedByte(); } - catch (EOFException e) - { + catch (EOFException e) { throw new MessageEOFException(""); } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public short readShort() throws JMSException - { + public short readShort() throws JMSException { checkRead(); - try - { + try { return m.readShort(); } - catch (EOFException e) - { + catch (EOFException e) { throw new MessageEOFException(""); } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public int readUnsignedShort() throws JMSException - { + public int readUnsignedShort() throws JMSException { checkRead(); - try - { + try { return m.readUnsignedShort(); } - catch (EOFException e) - { + catch (EOFException e) { throw new MessageEOFException(""); } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public char readChar() throws JMSException - { + public char readChar() throws JMSException { checkRead(); - try - { + try { return m.readChar(); } - catch (EOFException e) - { + catch (EOFException e) { throw new MessageEOFException(""); } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public int readInt() throws JMSException - { + public int readInt() throws JMSException { checkRead(); - try - { + try { return m.readInt(); } - catch (EOFException e) - { + catch (EOFException e) { throw new MessageEOFException(""); } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public long readLong() throws JMSException - { + public long readLong() throws JMSException { checkRead(); - try - { + try { return m.readLong(); } - catch (EOFException e) - { + catch (EOFException e) { throw new MessageEOFException(""); } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public float readFloat() throws JMSException - { + public float readFloat() throws JMSException { checkRead(); - try - { + try { return m.readFloat(); } - catch (EOFException e) - { + catch (EOFException e) { throw new MessageEOFException(""); } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public double readDouble() throws JMSException - { + public double readDouble() throws JMSException { checkRead(); - try - { + try { return m.readDouble(); } - catch (EOFException e) - { + catch (EOFException e) { throw new MessageEOFException(""); } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public String readUTF() throws JMSException - { + public String readUTF() throws JMSException { checkRead(); - try - { + try { return m.readUTF(); } - catch (EOFException e) - { + catch (EOFException e) { throw new MessageEOFException(""); } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public int readBytes(final byte[] value) throws JMSException - { + public int readBytes(final byte[] value) throws JMSException { checkRead(); - try - { + try { return m.read(value); } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public int readBytes(final byte[] value, final int length) throws JMSException - { + public int readBytes(final byte[] value, final int length) throws JMSException { checkRead(); - try - { + try { return m.read(value, 0, length); } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public void writeBoolean(final boolean value) throws JMSException - { - if (!bodyWriteOnly) - { + public void writeBoolean(final boolean value) throws JMSException { + if (!bodyWriteOnly) { throw new MessageNotWriteableException("the message body is read-only"); } - try - { + try { p.writeBoolean(value); } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public void writeByte(final byte value) throws JMSException - { - if (!bodyWriteOnly) - { + public void writeByte(final byte value) throws JMSException { + if (!bodyWriteOnly) { throw new MessageNotWriteableException("the message body is read-only"); } - try - { + try { p.writeByte(value); } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public void writeShort(final short value) throws JMSException - { - if (!bodyWriteOnly) - { + public void writeShort(final short value) throws JMSException { + if (!bodyWriteOnly) { throw new MessageNotWriteableException("the message body is read-only"); } - try - { + try { p.writeShort(value); } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public void writeChar(final char value) throws JMSException - { - if (!bodyWriteOnly) - { + public void writeChar(final char value) throws JMSException { + if (!bodyWriteOnly) { throw new MessageNotWriteableException("the message body is read-only"); } - try - { + try { p.writeChar(value); } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public void writeInt(final int value) throws JMSException - { - if (!bodyWriteOnly) - { + public void writeInt(final int value) throws JMSException { + if (!bodyWriteOnly) { throw new MessageNotWriteableException("the message body is read-only"); } - try - { + try { p.writeInt(value); } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public void writeLong(final long value) throws JMSException - { - if (!bodyWriteOnly) - { + public void writeLong(final long value) throws JMSException { + if (!bodyWriteOnly) { throw new MessageNotWriteableException("the message body is read-only"); } - try - { + try { p.writeLong(value); } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public void writeFloat(final float value) throws JMSException - { - if (!bodyWriteOnly) - { + public void writeFloat(final float value) throws JMSException { + if (!bodyWriteOnly) { throw new MessageNotWriteableException("the message body is read-only"); } - try - { + try { p.writeFloat(value); } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public void writeDouble(final double value) throws JMSException - { - if (!bodyWriteOnly) - { + public void writeDouble(final double value) throws JMSException { + if (!bodyWriteOnly) { throw new MessageNotWriteableException("the message body is read-only"); } - try - { + try { p.writeDouble(value); } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public void writeUTF(final String value) throws JMSException - { - if (!bodyWriteOnly) - { + public void writeUTF(final String value) throws JMSException { + if (!bodyWriteOnly) { throw new MessageNotWriteableException("the message body is read-only"); } - try - { + try { p.writeUTF(value); } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public void writeBytes(final byte[] value) throws JMSException - { - if (!bodyWriteOnly) - { + public void writeBytes(final byte[] value) throws JMSException { + if (!bodyWriteOnly) { throw new MessageNotWriteableException("the message body is read-only"); } - try - { + try { p.write(value, 0, value.length); } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public void writeBytes(final byte[] value, final int offset, final int length) throws JMSException - { - if (!bodyWriteOnly) - { + public void writeBytes(final byte[] value, final int offset, final int length) throws JMSException { + if (!bodyWriteOnly) { throw new MessageNotWriteableException("the message body is read-only"); } - try - { + try { p.write(value, offset, length); } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public void writeObject(final Object value) throws JMSException - { - if (!bodyWriteOnly) - { + public void writeObject(final Object value) throws JMSException { + if (!bodyWriteOnly) { throw new MessageNotWriteableException("the message body is read-only"); } - try - { - if (value == null) - { + try { + if (value == null) { throw new NullPointerException("Attempt to write a new value"); } - if (value instanceof String) - { - p.writeUTF((String)value); + if (value instanceof String) { + p.writeUTF((String) value); } - else if (value instanceof Boolean) - { - p.writeBoolean(((Boolean)value).booleanValue()); + else if (value instanceof Boolean) { + p.writeBoolean(((Boolean) value).booleanValue()); } - else if (value instanceof Byte) - { - p.writeByte(((Byte)value).byteValue()); + else if (value instanceof Byte) { + p.writeByte(((Byte) value).byteValue()); } - else if (value instanceof Short) - { - p.writeShort(((Short)value).shortValue()); + else if (value instanceof Short) { + p.writeShort(((Short) value).shortValue()); } - else if (value instanceof Integer) - { - p.writeInt(((Integer)value).intValue()); + else if (value instanceof Integer) { + p.writeInt(((Integer) value).intValue()); } - else if (value instanceof Long) - { - p.writeLong(((Long)value).longValue()); + else if (value instanceof Long) { + p.writeLong(((Long) value).longValue()); } - else if (value instanceof Float) - { - p.writeFloat(((Float)value).floatValue()); + else if (value instanceof Float) { + p.writeFloat(((Float) value).floatValue()); } - else if (value instanceof Double) - { - p.writeDouble(((Double)value).doubleValue()); + else if (value instanceof Double) { + p.writeDouble(((Double) value).doubleValue()); } - else if (value instanceof byte[]) - { - p.write((byte[])value, 0, ((byte[])value).length); + else if (value instanceof byte[]) { + p.write((byte[]) value, 0, ((byte[]) value).length); } - else - { + else { throw new MessageFormatException("Invalid object for properties"); } } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public void reset() throws JMSException - { - try - { - if (bodyWriteOnly) - { + public void reset() throws JMSException { + try { + if (bodyWriteOnly) { p.flush(); internalArray = ostream.toByteArray(); ostream.close(); @@ -523,14 +409,12 @@ public class SimpleJMSBytesMessage extends SimpleJMSMessage implements BytesMess p = null; bodyWriteOnly = false; } - catch (IOException e) - { + catch (IOException e) { throw new JMSException("IOException"); } } - public long getBodyLength() throws JMSException - { + public long getBodyLength() throws JMSException { checkRead(); return internalArray.length; } @@ -548,17 +432,14 @@ public class SimpleJMSBytesMessage extends SimpleJMSMessage implements BytesMess * * @throws javax.jms.JMSException when not readable */ - private void checkRead() throws JMSException - { - if (bodyWriteOnly) - { + private void checkRead() throws JMSException { + if (bodyWriteOnly) { throw new MessageNotReadableException("readByte while the buffer is writeonly"); } // We have just received/reset() the message, and the client is trying to // read it - if (istream == null || m == null) - { + if (istream == null || m == null) { istream = new ByteArrayInputStream(internalArray); m = new DataInputStream(istream); } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SimpleJMSMapMessage.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SimpleJMSMapMessage.java index 45cf4890d4..6ae217b142 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SimpleJMSMapMessage.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SimpleJMSMapMessage.java @@ -26,8 +26,7 @@ import javax.jms.MapMessage; import javax.jms.MessageFormatException; import javax.jms.MessageNotWriteableException; -public class SimpleJMSMapMessage extends SimpleJMSMessage implements MapMessage -{ +public class SimpleJMSMapMessage extends SimpleJMSMessage implements MapMessage { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -40,18 +39,15 @@ public class SimpleJMSMapMessage extends SimpleJMSMessage implements MapMessage // Constructors -------------------------------------------------- - public SimpleJMSMapMessage() - { + public SimpleJMSMapMessage() { content = new HashMap(); } // MapMessage implementation ------------------------------------- - public void setBoolean(final String name, final boolean value) throws JMSException - { + public void setBoolean(final String name, final boolean value) throws JMSException { checkName(name); - if (bodyReadOnly) - { + if (bodyReadOnly) { throw new MessageNotWriteableException("Message is ReadOnly !"); } @@ -59,11 +55,9 @@ public class SimpleJMSMapMessage extends SimpleJMSMessage implements MapMessage } - public void setByte(final String name, final byte value) throws JMSException - { + public void setByte(final String name, final byte value) throws JMSException { checkName(name); - if (bodyReadOnly) - { + if (bodyReadOnly) { throw new MessageNotWriteableException("Message is ReadOnly !"); } @@ -71,11 +65,9 @@ public class SimpleJMSMapMessage extends SimpleJMSMessage implements MapMessage } - public void setShort(final String name, final short value) throws JMSException - { + public void setShort(final String name, final short value) throws JMSException { checkName(name); - if (bodyReadOnly) - { + if (bodyReadOnly) { throw new MessageNotWriteableException("Message is ReadOnly !"); } @@ -83,11 +75,9 @@ public class SimpleJMSMapMessage extends SimpleJMSMessage implements MapMessage } - public void setChar(final String name, final char value) throws JMSException - { + public void setChar(final String name, final char value) throws JMSException { checkName(name); - if (bodyReadOnly) - { + if (bodyReadOnly) { throw new MessageNotWriteableException("Message is ReadOnly !"); } @@ -95,11 +85,9 @@ public class SimpleJMSMapMessage extends SimpleJMSMessage implements MapMessage } - public void setInt(final String name, final int value) throws JMSException - { + public void setInt(final String name, final int value) throws JMSException { checkName(name); - if (bodyReadOnly) - { + if (bodyReadOnly) { throw new MessageNotWriteableException("Message is ReadOnly !"); } @@ -107,11 +95,9 @@ public class SimpleJMSMapMessage extends SimpleJMSMessage implements MapMessage } - public void setLong(final String name, final long value) throws JMSException - { + public void setLong(final String name, final long value) throws JMSException { checkName(name); - if (bodyReadOnly) - { + if (bodyReadOnly) { throw new MessageNotWriteableException("Message is ReadOnly !"); } @@ -119,11 +105,9 @@ public class SimpleJMSMapMessage extends SimpleJMSMessage implements MapMessage } - public void setFloat(final String name, final float value) throws JMSException - { + public void setFloat(final String name, final float value) throws JMSException { checkName(name); - if (bodyReadOnly) - { + if (bodyReadOnly) { throw new MessageNotWriteableException("Message is ReadOnly !"); } @@ -131,11 +115,9 @@ public class SimpleJMSMapMessage extends SimpleJMSMessage implements MapMessage } - public void setDouble(final String name, final double value) throws JMSException - { + public void setDouble(final String name, final double value) throws JMSException { checkName(name); - if (bodyReadOnly) - { + if (bodyReadOnly) { throw new MessageNotWriteableException("Message is ReadOnly !"); } @@ -143,11 +125,9 @@ public class SimpleJMSMapMessage extends SimpleJMSMessage implements MapMessage } - public void setString(final String name, final String value) throws JMSException - { + public void setString(final String name, final String value) throws JMSException { checkName(name); - if (bodyReadOnly) - { + if (bodyReadOnly) { throw new MessageNotWriteableException("Message is ReadOnly !"); } @@ -155,11 +135,9 @@ public class SimpleJMSMapMessage extends SimpleJMSMessage implements MapMessage } - public void setBytes(final String name, final byte[] value) throws JMSException - { + public void setBytes(final String name, final byte[] value) throws JMSException { checkName(name); - if (bodyReadOnly) - { + if (bodyReadOnly) { throw new MessageNotWriteableException("Message is ReadOnly !"); } @@ -167,21 +145,17 @@ public class SimpleJMSMapMessage extends SimpleJMSMessage implements MapMessage } - public void setBytes(final String name, final byte[] value, final int offset, final int length) throws JMSException - { + public void setBytes(final String name, final byte[] value, final int offset, final int length) throws JMSException { checkName(name); - if (bodyReadOnly) - { + if (bodyReadOnly) { throw new MessageNotWriteableException("Message is ReadOnly !"); } - if (offset + length > value.length) - { + if (offset + length > value.length) { throw new JMSException("Array is too small"); } byte[] temp = new byte[length]; - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { temp[i] = value[i + offset]; } @@ -189,374 +163,296 @@ public class SimpleJMSMapMessage extends SimpleJMSMessage implements MapMessage } - public void setObject(final String name, final Object value) throws JMSException - { + public void setObject(final String name, final Object value) throws JMSException { checkName(name); - if (bodyReadOnly) - { + if (bodyReadOnly) { throw new MessageNotWriteableException("Message is ReadOnly !"); } - if (value instanceof Boolean) - { + if (value instanceof Boolean) { content.put(name, value); } - else if (value instanceof Byte) - { + else if (value instanceof Byte) { content.put(name, value); } - else if (value instanceof Short) - { + else if (value instanceof Short) { content.put(name, value); } - else if (value instanceof Character) - { + else if (value instanceof Character) { content.put(name, value); } - else if (value instanceof Integer) - { + else if (value instanceof Integer) { content.put(name, value); } - else if (value instanceof Long) - { + else if (value instanceof Long) { content.put(name, value); } - else if (value instanceof Float) - { + else if (value instanceof Float) { content.put(name, value); } - else if (value instanceof Double) - { + else if (value instanceof Double) { content.put(name, value); } - else if (value instanceof String) - { + else if (value instanceof String) { content.put(name, value); } - else if (value instanceof byte[]) - { - content.put(name, ((byte[])value).clone()); + else if (value instanceof byte[]) { + content.put(name, ((byte[]) value).clone()); } - else - { + else { throw new MessageFormatException("Invalid object type."); } } - public boolean getBoolean(final String name) throws JMSException - { + public boolean getBoolean(final String name) throws JMSException { Object value; value = content.get(name); - if (value == null) - { + if (value == null) { return Boolean.valueOf(null).booleanValue(); } - if (value instanceof Boolean) - { - return ((Boolean)value).booleanValue(); + if (value instanceof Boolean) { + return ((Boolean) value).booleanValue(); } - else if (value instanceof String) - { - return Boolean.valueOf((String)value).booleanValue(); + else if (value instanceof String) { + return Boolean.valueOf((String) value).booleanValue(); } - else - { + else { throw new MessageFormatException("Invalid conversion"); } } - public byte getByte(final String name) throws JMSException - { + public byte getByte(final String name) throws JMSException { Object value; value = content.get(name); - if (value == null) - { + if (value == null) { return Byte.parseByte(null); } - if (value instanceof Byte) - { - return ((Byte)value).byteValue(); + if (value instanceof Byte) { + return ((Byte) value).byteValue(); } - else if (value instanceof String) - { - return Byte.parseByte((String)value); + else if (value instanceof String) { + return Byte.parseByte((String) value); } - else - { + else { throw new MessageFormatException("Invalid conversion"); } } - public short getShort(final String name) throws JMSException - { + public short getShort(final String name) throws JMSException { Object value; value = content.get(name); - if (value == null) - { + if (value == null) { return Short.parseShort(null); } - if (value instanceof Byte) - { - return ((Byte)value).shortValue(); + if (value instanceof Byte) { + return ((Byte) value).shortValue(); } - else if (value instanceof Short) - { - return ((Short)value).shortValue(); + else if (value instanceof Short) { + return ((Short) value).shortValue(); } - else if (value instanceof String) - { - return Short.parseShort((String)value); + else if (value instanceof String) { + return Short.parseShort((String) value); } - else - { + else { throw new MessageFormatException("Invalid conversion"); } } - public char getChar(final String name) throws JMSException - { + public char getChar(final String name) throws JMSException { Object value; value = content.get(name); - if (value == null) - { + if (value == null) { throw new NullPointerException("Invalid conversion"); } - if (value instanceof Character) - { - return ((Character)value).charValue(); + if (value instanceof Character) { + return ((Character) value).charValue(); } - else - { + else { throw new MessageFormatException("Invalid conversion"); } } - public int getInt(final String name) throws JMSException - { + public int getInt(final String name) throws JMSException { Object value; value = content.get(name); - if (value == null) - { + if (value == null) { return Integer.parseInt(null); } - if (value instanceof Byte) - { - return ((Byte)value).intValue(); + if (value instanceof Byte) { + return ((Byte) value).intValue(); } - else if (value instanceof Short) - { - return ((Short)value).intValue(); + else if (value instanceof Short) { + return ((Short) value).intValue(); } - else if (value instanceof Integer) - { - return ((Integer)value).intValue(); + else if (value instanceof Integer) { + return ((Integer) value).intValue(); } - else if (value instanceof String) - { - return Integer.parseInt((String)value); + else if (value instanceof String) { + return Integer.parseInt((String) value); } - else - { + else { throw new MessageFormatException("Invalid conversion"); } } - public long getLong(final String name) throws JMSException - { + public long getLong(final String name) throws JMSException { Object value; value = content.get(name); - if (value == null) - { + if (value == null) { return Long.parseLong(null); } - if (value instanceof Byte) - { - return ((Byte)value).longValue(); + if (value instanceof Byte) { + return ((Byte) value).longValue(); } - else if (value instanceof Short) - { - return ((Short)value).longValue(); + else if (value instanceof Short) { + return ((Short) value).longValue(); } - else if (value instanceof Integer) - { - return ((Integer)value).longValue(); + else if (value instanceof Integer) { + return ((Integer) value).longValue(); } - else if (value instanceof Long) - { - return ((Long)value).longValue(); + else if (value instanceof Long) { + return ((Long) value).longValue(); } - else if (value instanceof String) - { - return Long.parseLong((String)value); + else if (value instanceof String) { + return Long.parseLong((String) value); } - else - { + else { throw new MessageFormatException("Invalid conversion"); } } - public float getFloat(final String name) throws JMSException - { + public float getFloat(final String name) throws JMSException { Object value; value = content.get(name); - if (value == null) - { + if (value == null) { return Float.parseFloat(null); } - if (value instanceof Float) - { - return ((Float)value).floatValue(); + if (value instanceof Float) { + return ((Float) value).floatValue(); } - else if (value instanceof String) - { - return Float.parseFloat((String)value); + else if (value instanceof String) { + return Float.parseFloat((String) value); } - else - { + else { throw new MessageFormatException("Invalid conversion"); } } - public double getDouble(final String name) throws JMSException - { + public double getDouble(final String name) throws JMSException { Object value; value = content.get(name); - if (value == null) - { + if (value == null) { return Double.parseDouble(null); } - if (value instanceof Float) - { - return ((Float)value).doubleValue(); + if (value instanceof Float) { + return ((Float) value).doubleValue(); } - else if (value instanceof Double) - { - return ((Double)value).doubleValue(); + else if (value instanceof Double) { + return ((Double) value).doubleValue(); } - else if (value instanceof String) - { - return Double.parseDouble((String)value); + else if (value instanceof String) { + return Double.parseDouble((String) value); } - else - { + else { throw new MessageFormatException("Invalid conversion"); } } - public String getString(final String name) throws JMSException - { + public String getString(final String name) throws JMSException { Object value; value = content.get(name); - if (value == null) - { + if (value == null) { return null; } - if (value instanceof Boolean) - { - return ((Boolean)value).toString(); + if (value instanceof Boolean) { + return ((Boolean) value).toString(); } - else if (value instanceof Byte) - { - return ((Byte)value).toString(); + else if (value instanceof Byte) { + return ((Byte) value).toString(); } - else if (value instanceof Short) - { - return ((Short)value).toString(); + else if (value instanceof Short) { + return ((Short) value).toString(); } - else if (value instanceof Character) - { - return ((Character)value).toString(); + else if (value instanceof Character) { + return ((Character) value).toString(); } - else if (value instanceof Integer) - { - return ((Integer)value).toString(); + else if (value instanceof Integer) { + return ((Integer) value).toString(); } - else if (value instanceof Long) - { - return ((Long)value).toString(); + else if (value instanceof Long) { + return ((Long) value).toString(); } - else if (value instanceof Float) - { - return ((Float)value).toString(); + else if (value instanceof Float) { + return ((Float) value).toString(); } - else if (value instanceof Double) - { - return ((Double)value).toString(); + else if (value instanceof Double) { + return ((Double) value).toString(); } - else if (value instanceof String) - { - return (String)value; + else if (value instanceof String) { + return (String) value; } - else - { + else { throw new MessageFormatException("Invalid conversion"); } } - public byte[] getBytes(final String name) throws JMSException - { + public byte[] getBytes(final String name) throws JMSException { Object value; value = content.get(name); - if (value == null) - { + if (value == null) { return null; } - if (value instanceof byte[]) - { - return (byte[])value; + if (value instanceof byte[]) { + return (byte[]) value; } - else - { + else { throw new MessageFormatException("Invalid conversion"); } } - public Object getObject(final String name) throws JMSException - { + public Object getObject(final String name) throws JMSException { return content.get(name); } - public Enumeration getMapNames() throws JMSException - { + public Enumeration getMapNames() throws JMSException { return Collections.enumeration(new HashMap(content).keySet()); } - public boolean itemExists(final String name) throws JMSException - { + public boolean itemExists(final String name) throws JMSException { return content.containsKey(name); @@ -573,15 +469,12 @@ public class SimpleJMSMapMessage extends SimpleJMSMessage implements MapMessage * * @param name the name */ - private void checkName(final String name) - { - if (name == null) - { + private void checkName(final String name) { + if (name == null) { throw new IllegalArgumentException("Name must not be null."); } - if (name.equals("")) - { + if (name.equals("")) { throw new IllegalArgumentException("Name must not be an empty String."); } } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SimpleJMSMessage.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SimpleJMSMessage.java index 77017eb843..afdcd63a1d 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SimpleJMSMessage.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SimpleJMSMessage.java @@ -29,22 +29,20 @@ import javax.jms.Message; /** * Foreign message implementation. Used for testing only. */ -public class SimpleJMSMessage implements Message -{ +public class SimpleJMSMessage implements Message { + private boolean ignoreSetDestination; // Constructors -------------------------------------------------- - public SimpleJMSMessage() - { + public SimpleJMSMessage() { properties.put("JMSXDeliveryCount", new Integer(0)); } /* * This constructor is used to simulate an activemq message in which the set of the destination is ignored after receipt. */ - public SimpleJMSMessage(final Destination dest) - { + public SimpleJMSMessage(final Destination dest) { this(); ignoreSetDestination = true; destination = dest; @@ -54,25 +52,21 @@ public class SimpleJMSMessage implements Message private String messageID; - public String getJMSMessageID() throws JMSException - { + public String getJMSMessageID() throws JMSException { return messageID; } - public void setJMSMessageID(final String id) throws JMSException - { + public void setJMSMessageID(final String id) throws JMSException { messageID = id; } private long timestamp; - public long getJMSTimestamp() throws JMSException - { + public long getJMSTimestamp() throws JMSException { return timestamp; } - public void setJMSTimestamp(final long timestamp) throws JMSException - { + public void setJMSTimestamp(final long timestamp) throws JMSException { this.timestamp = timestamp; } @@ -86,304 +80,248 @@ public class SimpleJMSMessage implements Message private boolean isCorrelationIDBytes; - public byte[] getJMSCorrelationIDAsBytes() throws JMSException - { - if (!isCorrelationIDBytes) - { + public byte[] getJMSCorrelationIDAsBytes() throws JMSException { + if (!isCorrelationIDBytes) { throw new JMSException("CorrelationID is a String for this message"); } return correlationIDBytes; } - public void setJMSCorrelationIDAsBytes(final byte[] correlationID) throws JMSException - { - if (correlationID == null || correlationID.length == 0) - { + public void setJMSCorrelationIDAsBytes(final byte[] correlationID) throws JMSException { + if (correlationID == null || correlationID.length == 0) { throw new JMSException("Please specify a non-zero length byte[]"); } correlationIDBytes = correlationID; isCorrelationIDBytes = true; } - public void setJMSCorrelationID(final String correlationID) throws JMSException - { + public void setJMSCorrelationID(final String correlationID) throws JMSException { correlationIDString = correlationID; isCorrelationIDBytes = false; } - public String getJMSCorrelationID() throws JMSException - { + public String getJMSCorrelationID() throws JMSException { return correlationIDString; } private Destination replyTo; - public Destination getJMSReplyTo() throws JMSException - { + public Destination getJMSReplyTo() throws JMSException { return replyTo; } - public void setJMSReplyTo(final Destination replyTo) throws JMSException - { + public void setJMSReplyTo(final Destination replyTo) throws JMSException { this.replyTo = replyTo; } private Destination destination; - public Destination getJMSDestination() throws JMSException - { + public Destination getJMSDestination() throws JMSException { return destination; } - public void setJMSDestination(final Destination destination) throws JMSException - { - if (!ignoreSetDestination) - { + public void setJMSDestination(final Destination destination) throws JMSException { + if (!ignoreSetDestination) { this.destination = destination; } } private int deliveryMode = DeliveryMode.PERSISTENT; - public int getJMSDeliveryMode() throws JMSException - { + public int getJMSDeliveryMode() throws JMSException { return deliveryMode; } - public void setJMSDeliveryMode(final int deliveryMode) throws JMSException - { + public void setJMSDeliveryMode(final int deliveryMode) throws JMSException { this.deliveryMode = deliveryMode; } private boolean redelivered; - public boolean getJMSRedelivered() throws JMSException - { + public boolean getJMSRedelivered() throws JMSException { return redelivered; } - public void setJMSRedelivered(final boolean redelivered) throws JMSException - { + public void setJMSRedelivered(final boolean redelivered) throws JMSException { this.redelivered = redelivered; } private String type; - public String getJMSType() throws JMSException - { + public String getJMSType() throws JMSException { return type; } - public void setJMSType(final String type) throws JMSException - { + public void setJMSType(final String type) throws JMSException { this.type = type; } private long expiration; - public long getJMSExpiration() throws JMSException - { + public long getJMSExpiration() throws JMSException { return expiration; } - public void setJMSExpiration(final long expiration) throws JMSException - { + public void setJMSExpiration(final long expiration) throws JMSException { this.expiration = expiration; } private int priority; - public int getJMSPriority() throws JMSException - { + public int getJMSPriority() throws JMSException { return priority; } - public void setJMSPriority(final int priority) throws JMSException - { + public void setJMSPriority(final int priority) throws JMSException { this.priority = priority; } private final Map properties = new HashMap(); - public void clearProperties() throws JMSException - { + public void clearProperties() throws JMSException { properties.clear(); } - public boolean propertyExists(final String name) throws JMSException - { + public boolean propertyExists(final String name) throws JMSException { return properties.containsKey(name); } - public boolean getBooleanProperty(final String name) throws JMSException - { + public boolean getBooleanProperty(final String name) throws JMSException { Object prop = properties.get(name); - if (!(prop instanceof Boolean)) - { + if (!(prop instanceof Boolean)) { throw new JMSException("Not boolean"); } - return ((Boolean)properties.get(name)).booleanValue(); + return ((Boolean) properties.get(name)).booleanValue(); } - public byte getByteProperty(final String name) throws JMSException - { + public byte getByteProperty(final String name) throws JMSException { Object prop = properties.get(name); - if (!(prop instanceof Byte)) - { + if (!(prop instanceof Byte)) { throw new JMSException("Not byte"); } - return ((Byte)properties.get(name)).byteValue(); + return ((Byte) properties.get(name)).byteValue(); } - public short getShortProperty(final String name) throws JMSException - { + public short getShortProperty(final String name) throws JMSException { Object prop = properties.get(name); - if (!(prop instanceof Short)) - { + if (!(prop instanceof Short)) { throw new JMSException("Not short"); } - return ((Short)properties.get(name)).shortValue(); + return ((Short) properties.get(name)).shortValue(); } - public int getIntProperty(final String name) throws JMSException - { + public int getIntProperty(final String name) throws JMSException { Object prop = properties.get(name); - if (!(prop instanceof Integer)) - { + if (!(prop instanceof Integer)) { throw new JMSException("Not int"); } - return ((Integer)properties.get(name)).intValue(); + return ((Integer) properties.get(name)).intValue(); } - public long getLongProperty(final String name) throws JMSException - { + public long getLongProperty(final String name) throws JMSException { Object prop = properties.get(name); - if (!(prop instanceof Long)) - { + if (!(prop instanceof Long)) { throw new JMSException("Not long"); } - return ((Long)properties.get(name)).longValue(); + return ((Long) properties.get(name)).longValue(); } - public float getFloatProperty(final String name) throws JMSException - { + public float getFloatProperty(final String name) throws JMSException { Object prop = properties.get(name); - if (!(prop instanceof Float)) - { + if (!(prop instanceof Float)) { throw new JMSException("Not float"); } - return ((Float)properties.get(name)).floatValue(); + return ((Float) properties.get(name)).floatValue(); } - public double getDoubleProperty(final String name) throws JMSException - { + public double getDoubleProperty(final String name) throws JMSException { Object prop = properties.get(name); - if (!(prop instanceof Double)) - { + if (!(prop instanceof Double)) { throw new JMSException("Not double"); } - return ((Double)properties.get(name)).doubleValue(); + return ((Double) properties.get(name)).doubleValue(); } - public String getStringProperty(final String name) throws JMSException - { + public String getStringProperty(final String name) throws JMSException { Object prop = properties.get(name); - if (!(prop instanceof String)) - { + if (!(prop instanceof String)) { throw new JMSException("Not string"); } - return (String)properties.get(name); + return (String) properties.get(name); } - public Object getObjectProperty(final String name) throws JMSException - { + public Object getObjectProperty(final String name) throws JMSException { return properties.get(name); } - public Enumeration getPropertyNames() throws JMSException - { + public Enumeration getPropertyNames() throws JMSException { return Collections.enumeration(properties.keySet()); } - public void setBooleanProperty(final String name, final boolean value) throws JMSException - { + public void setBooleanProperty(final String name, final boolean value) throws JMSException { properties.put(name, new Boolean(value)); } - public void setByteProperty(final String name, final byte value) throws JMSException - { + public void setByteProperty(final String name, final byte value) throws JMSException { properties.put(name, new Byte(value)); } - public void setShortProperty(final String name, final short value) throws JMSException - { + public void setShortProperty(final String name, final short value) throws JMSException { properties.put(name, new Short(value)); } - public void setIntProperty(final String name, final int value) throws JMSException - { + public void setIntProperty(final String name, final int value) throws JMSException { properties.put(name, new Integer(value)); } - public void setLongProperty(final String name, final long value) throws JMSException - { + public void setLongProperty(final String name, final long value) throws JMSException { properties.put(name, new Long(value)); } - public void setFloatProperty(final String name, final float value) throws JMSException - { + public void setFloatProperty(final String name, final float value) throws JMSException { properties.put(name, new Float(value)); } - public void setDoubleProperty(final String name, final double value) throws JMSException - { + public void setDoubleProperty(final String name, final double value) throws JMSException { properties.put(name, new Double(value)); } - public void setStringProperty(final String name, final String value) throws JMSException - { + public void setStringProperty(final String name, final String value) throws JMSException { properties.put(name, value); } - public void setObjectProperty(final String name, final Object value) throws JMSException - { + public void setObjectProperty(final String name, final Object value) throws JMSException { properties.put(name, value); } - public void acknowledge() throws JMSException - { + public void acknowledge() throws JMSException { } - public void clearBody() throws JMSException - { + public void clearBody() throws JMSException { } @Override - public long getJMSDeliveryTime() throws JMSException - { - throw new UnsupportedOperationException("JMS 2.0 / not implemented"); + public long getJMSDeliveryTime() throws JMSException { + throw new UnsupportedOperationException("JMS 2.0 / not implemented"); } @Override - public void setJMSDeliveryTime(long deliveryTime) throws JMSException - { - throw new UnsupportedOperationException("JMS 2.0 / not implemented"); + public void setJMSDeliveryTime(long deliveryTime) throws JMSException { + throw new UnsupportedOperationException("JMS 2.0 / not implemented"); } @Override - public T getBody(Class c) throws JMSException - { - throw new UnsupportedOperationException("JMS 2.0 / not implemented"); + public T getBody(Class c) throws JMSException { + throw new UnsupportedOperationException("JMS 2.0 / not implemented"); } @Override - public boolean isBodyAssignableTo(Class c) throws JMSException - { - throw new UnsupportedOperationException("JMS 2.0 / not implemented"); + public boolean isBodyAssignableTo(Class c) throws JMSException { + throw new UnsupportedOperationException("JMS 2.0 / not implemented"); } - // Public -------------------------------------------------------- + // Public -------------------------------------------------------- // Package protected --------------------------------------------- diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SimpleJMSObjectMessage.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SimpleJMSObjectMessage.java index 0a80e9ccc3..32987d93af 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SimpleJMSObjectMessage.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SimpleJMSObjectMessage.java @@ -21,8 +21,7 @@ import java.io.Serializable; import javax.jms.JMSException; import javax.jms.ObjectMessage; -public class SimpleJMSObjectMessage extends SimpleJMSMessage implements ObjectMessage -{ +public class SimpleJMSObjectMessage extends SimpleJMSMessage implements ObjectMessage { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -35,13 +34,11 @@ public class SimpleJMSObjectMessage extends SimpleJMSMessage implements ObjectMe // ObjectMessage implementation ---------------------------------- - public void setObject(final Serializable object) throws JMSException - { + public void setObject(final Serializable object) throws JMSException { this.object = object; } - public Serializable getObject() throws JMSException - { + public Serializable getObject() throws JMSException { return object; } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SimpleJMSStreamMessage.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SimpleJMSStreamMessage.java index 4fa5b82f15..23a4e8d9d1 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SimpleJMSStreamMessage.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SimpleJMSStreamMessage.java @@ -26,8 +26,7 @@ import javax.jms.MessageNotReadableException; import javax.jms.MessageNotWriteableException; import javax.jms.StreamMessage; -public class SimpleJMSStreamMessage extends SimpleJMSMessage implements StreamMessage -{ +public class SimpleJMSStreamMessage extends SimpleJMSMessage implements StreamMessage { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -48,8 +47,7 @@ public class SimpleJMSStreamMessage extends SimpleJMSMessage implements StreamMe // Constructors -------------------------------------------------- - public SimpleJMSStreamMessage() - { + public SimpleJMSStreamMessage() { content = new ArrayList(); position = 0; size = 0; @@ -60,442 +58,348 @@ public class SimpleJMSStreamMessage extends SimpleJMSMessage implements StreamMe // StreamMessage implementation ---------------------------------- - public boolean readBoolean() throws JMSException - { - if (bodyWriteOnly) - { + public boolean readBoolean() throws JMSException { + if (bodyWriteOnly) { throw new MessageNotReadableException("The message body is writeonly"); } - try - { + try { Object value = content.get(position); offset = 0; - if (value == null) - { + if (value == null) { throw new NullPointerException("Value is null"); } - else if (value instanceof Boolean) - { + else if (value instanceof Boolean) { position++; - return ((Boolean)value).booleanValue(); + return ((Boolean) value).booleanValue(); } - else if (value instanceof String) - { - boolean result = Boolean.valueOf((String)value).booleanValue(); + else if (value instanceof String) { + boolean result = Boolean.valueOf((String) value).booleanValue(); position++; return result; } - else - { + else { throw new MessageFormatException("Invalid conversion"); } } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public byte readByte() throws JMSException - { - if (bodyWriteOnly) - { + public byte readByte() throws JMSException { + if (bodyWriteOnly) { throw new MessageNotReadableException("The message body is writeonly"); } - try - { + try { Object value = content.get(position); offset = 0; - if (value == null) - { + if (value == null) { throw new NullPointerException("Value is null"); } - else if (value instanceof Byte) - { + else if (value instanceof Byte) { position++; - return ((Byte)value).byteValue(); + return ((Byte) value).byteValue(); } - else if (value instanceof String) - { - byte result = Byte.parseByte((String)value); + else if (value instanceof String) { + byte result = Byte.parseByte((String) value); position++; return result; } - else - { + else { throw new MessageFormatException("Invalid conversion"); } } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public short readShort() throws JMSException - { - if (bodyWriteOnly) - { + public short readShort() throws JMSException { + if (bodyWriteOnly) { throw new MessageNotReadableException("The message body is writeonly"); } - try - { + try { Object value = content.get(position); offset = 0; - if (value == null) - { + if (value == null) { throw new NullPointerException("Value is null"); } - else if (value instanceof Byte) - { + else if (value instanceof Byte) { position++; - return ((Byte)value).shortValue(); + return ((Byte) value).shortValue(); } - else if (value instanceof Short) - { + else if (value instanceof Short) { position++; - return ((Short)value).shortValue(); + return ((Short) value).shortValue(); } - else if (value instanceof String) - { - short result = Short.parseShort((String)value); + else if (value instanceof String) { + short result = Short.parseShort((String) value); position++; return result; } - else - { + else { throw new MessageFormatException("Invalid conversion"); } } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public char readChar() throws JMSException - { - if (bodyWriteOnly) - { + public char readChar() throws JMSException { + if (bodyWriteOnly) { throw new MessageNotReadableException("The message body is writeonly"); } - try - { + try { Object value = content.get(position); offset = 0; - if (value == null) - { + if (value == null) { throw new NullPointerException("Value is null"); } - else if (value instanceof Character) - { + else if (value instanceof Character) { position++; - return ((Character)value).charValue(); + return ((Character) value).charValue(); } - else - { + else { throw new MessageFormatException("Invalid conversion"); } } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public int readInt() throws JMSException - { - if (bodyWriteOnly) - { + public int readInt() throws JMSException { + if (bodyWriteOnly) { throw new MessageNotReadableException("The message body is writeonly"); } - try - { + try { Object value = content.get(position); offset = 0; - if (value == null) - { + if (value == null) { throw new NullPointerException("Value is null"); } - else if (value instanceof Byte) - { + else if (value instanceof Byte) { position++; - return ((Byte)value).intValue(); + return ((Byte) value).intValue(); } - else if (value instanceof Short) - { + else if (value instanceof Short) { position++; - return ((Short)value).intValue(); + return ((Short) value).intValue(); } - else if (value instanceof Integer) - { + else if (value instanceof Integer) { position++; - return ((Integer)value).intValue(); + return ((Integer) value).intValue(); } - else if (value instanceof String) - { - int result = Integer.parseInt((String)value); + else if (value instanceof String) { + int result = Integer.parseInt((String) value); position++; return result; } - else - { + else { throw new MessageFormatException("Invalid conversion"); } } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public long readLong() throws JMSException - { - if (bodyWriteOnly) - { + public long readLong() throws JMSException { + if (bodyWriteOnly) { throw new MessageNotReadableException("The message body is writeonly"); } - try - { + try { Object value = content.get(position); offset = 0; - if (value == null) - { + if (value == null) { throw new NullPointerException("Value is null"); } - else if (value instanceof Byte) - { + else if (value instanceof Byte) { position++; - return ((Byte)value).longValue(); + return ((Byte) value).longValue(); } - else if (value instanceof Short) - { + else if (value instanceof Short) { position++; - return ((Short)value).longValue(); + return ((Short) value).longValue(); } - else if (value instanceof Integer) - { + else if (value instanceof Integer) { position++; - return ((Integer)value).longValue(); + return ((Integer) value).longValue(); } - else if (value instanceof Long) - { + else if (value instanceof Long) { position++; - return ((Long)value).longValue(); + return ((Long) value).longValue(); } - else if (value instanceof String) - { - long result = Long.parseLong((String)value); + else if (value instanceof String) { + long result = Long.parseLong((String) value); position++; return result; } - else - { + else { throw new MessageFormatException("Invalid conversion"); } } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public float readFloat() throws JMSException - { - if (bodyWriteOnly) - { + public float readFloat() throws JMSException { + if (bodyWriteOnly) { throw new MessageNotReadableException("The message body is writeonly"); } - try - { + try { Object value = content.get(position); offset = 0; - if (value == null) - { + if (value == null) { throw new NullPointerException("Value is null"); } - else if (value instanceof Float) - { + else if (value instanceof Float) { position++; - return ((Float)value).floatValue(); + return ((Float) value).floatValue(); } - else if (value instanceof String) - { - float result = Float.parseFloat((String)value); + else if (value instanceof String) { + float result = Float.parseFloat((String) value); position++; return result; } - else - { + else { throw new MessageFormatException("Invalid conversion"); } } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public double readDouble() throws JMSException - { - if (bodyWriteOnly) - { + public double readDouble() throws JMSException { + if (bodyWriteOnly) { throw new MessageNotReadableException("The message body is writeonly"); } - try - { + try { Object value = content.get(position); offset = 0; - if (value == null) - { + if (value == null) { throw new NullPointerException("Value is null"); } - else if (value instanceof Float) - { + else if (value instanceof Float) { position++; - return ((Float)value).doubleValue(); + return ((Float) value).doubleValue(); } - else if (value instanceof Double) - { + else if (value instanceof Double) { position++; - return ((Double)value).doubleValue(); + return ((Double) value).doubleValue(); } - else if (value instanceof String) - { - double result = Double.parseDouble((String)value); + else if (value instanceof String) { + double result = Double.parseDouble((String) value); position++; return result; } - else - { + else { throw new MessageFormatException("Invalid conversion"); } } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public String readString() throws JMSException - { - if (bodyWriteOnly) - { + public String readString() throws JMSException { + if (bodyWriteOnly) { throw new MessageNotReadableException("The message body is writeonly"); } - try - { + try { Object value = content.get(position); offset = 0; - if (value == null) - { + if (value == null) { position++; return null; } - else if (value instanceof Boolean) - { + else if (value instanceof Boolean) { position++; - return ((Boolean)value).toString(); + return ((Boolean) value).toString(); } - else if (value instanceof Byte) - { + else if (value instanceof Byte) { position++; - return ((Byte)value).toString(); + return ((Byte) value).toString(); } - else if (value instanceof Short) - { + else if (value instanceof Short) { position++; - return ((Short)value).toString(); + return ((Short) value).toString(); } - else if (value instanceof Character) - { + else if (value instanceof Character) { position++; - return ((Character)value).toString(); + return ((Character) value).toString(); } - else if (value instanceof Integer) - { + else if (value instanceof Integer) { position++; - return ((Integer)value).toString(); + return ((Integer) value).toString(); } - else if (value instanceof Long) - { + else if (value instanceof Long) { position++; - return ((Long)value).toString(); + return ((Long) value).toString(); } - else if (value instanceof Float) - { + else if (value instanceof Float) { position++; - return ((Float)value).toString(); + return ((Float) value).toString(); } - else if (value instanceof Double) - { + else if (value instanceof Double) { position++; - return ((Double)value).toString(); + return ((Double) value).toString(); } - else if (value instanceof String) - { + else if (value instanceof String) { position++; - return (String)value; + return (String) value; } - else - { + else { throw new MessageFormatException("Invalid conversion"); } } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public int readBytes(final byte[] value) throws JMSException - { - if (bodyWriteOnly) - { + public int readBytes(final byte[] value) throws JMSException { + if (bodyWriteOnly) { throw new MessageNotReadableException("The message body is writeonly"); } - try - { + try { Object myObj = content.get(position); - if (myObj == null) - { + if (myObj == null) { throw new NullPointerException("Value is null"); } - else if (!(myObj instanceof byte[])) - { + else if (!(myObj instanceof byte[])) { throw new MessageFormatException("Invalid conversion"); } - byte[] obj = (byte[])myObj; + byte[] obj = (byte[]) myObj; - if (obj.length == 0) - { + if (obj.length == 0) { position++; offset = 0; return 0; } - if (offset >= obj.length) - { + if (offset >= obj.length) { position++; offset = 0; return -1; } - if (obj.length - offset < value.length) - { - for (int i = 0; i < obj.length; i++) - { + if (obj.length - offset < value.length) { + for (int i = 0; i < obj.length; i++) { value[i] = obj[i + offset]; } @@ -504,10 +408,8 @@ public class SimpleJMSStreamMessage extends SimpleJMSMessage implements StreamMe return obj.length - offset; } - else - { - for (int i = 0; i < value.length; i++) - { + else { + for (int i = 0; i < value.length; i++) { value[i] = obj[i + offset]; } offset += value.length; @@ -516,207 +418,161 @@ public class SimpleJMSStreamMessage extends SimpleJMSMessage implements StreamMe } } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public Object readObject() throws JMSException - { - if (bodyWriteOnly) - { + public Object readObject() throws JMSException { + if (bodyWriteOnly) { throw new MessageNotReadableException("The message body is writeonly"); } - try - { + try { Object value = content.get(position); position++; offset = 0; return value; } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { throw new MessageEOFException(""); } } - public void writeBoolean(final boolean value) throws JMSException - { - if (!bodyWriteOnly) - { + public void writeBoolean(final boolean value) throws JMSException { + if (!bodyWriteOnly) { throw new MessageNotWriteableException("The message body is readonly"); } content.add(new Boolean(value)); } - public void writeByte(final byte value) throws JMSException - { - if (!bodyWriteOnly) - { + public void writeByte(final byte value) throws JMSException { + if (!bodyWriteOnly) { throw new MessageNotWriteableException("The message body is readonly"); } content.add(new Byte(value)); } - public void writeShort(final short value) throws JMSException - { - if (!bodyWriteOnly) - { + public void writeShort(final short value) throws JMSException { + if (!bodyWriteOnly) { throw new MessageNotWriteableException("The message body is readonly"); } content.add(new Short(value)); } - public void writeChar(final char value) throws JMSException - { - if (!bodyWriteOnly) - { + public void writeChar(final char value) throws JMSException { + if (!bodyWriteOnly) { throw new MessageNotWriteableException("The message body is readonly"); } content.add(new Character(value)); } - public void writeInt(final int value) throws JMSException - { - if (!bodyWriteOnly) - { + public void writeInt(final int value) throws JMSException { + if (!bodyWriteOnly) { throw new MessageNotWriteableException("The message body is readonly"); } content.add(new Integer(value)); } - public void writeLong(final long value) throws JMSException - { - if (!bodyWriteOnly) - { + public void writeLong(final long value) throws JMSException { + if (!bodyWriteOnly) { throw new MessageNotWriteableException("The message body is readonly"); } content.add(new Long(value)); } - public void writeFloat(final float value) throws JMSException - { - if (!bodyWriteOnly) - { + public void writeFloat(final float value) throws JMSException { + if (!bodyWriteOnly) { throw new MessageNotWriteableException("The message body is readonly"); } content.add(new Float(value)); } - public void writeDouble(final double value) throws JMSException - { - if (!bodyWriteOnly) - { + public void writeDouble(final double value) throws JMSException { + if (!bodyWriteOnly) { throw new MessageNotWriteableException("The message body is readonly"); } content.add(new Double(value)); } - public void writeString(final String value) throws JMSException - { - if (!bodyWriteOnly) - { + public void writeString(final String value) throws JMSException { + if (!bodyWriteOnly) { throw new MessageNotWriteableException("The message body is readonly"); } - if (value == null) - { + if (value == null) { content.add(null); } - else - { + else { content.add(value); } } - public void writeBytes(final byte[] value) throws JMSException - { - if (!bodyWriteOnly) - { + public void writeBytes(final byte[] value) throws JMSException { + if (!bodyWriteOnly) { throw new MessageNotWriteableException("The message body is readonly"); } content.add(value.clone()); } - public void writeBytes(final byte[] value, final int offset, final int length) throws JMSException - { - if (!bodyWriteOnly) - { + public void writeBytes(final byte[] value, final int offset, final int length) throws JMSException { + if (!bodyWriteOnly) { throw new MessageNotWriteableException("The message body is readonly"); } - if (offset + length > value.length) - { + if (offset + length > value.length) { throw new JMSException("Array is too small"); } byte[] temp = new byte[length]; - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { temp[i] = value[i + offset]; } content.add(temp); } - public void writeObject(final Object value) throws JMSException - { - if (!bodyWriteOnly) - { + public void writeObject(final Object value) throws JMSException { + if (!bodyWriteOnly) { throw new MessageNotWriteableException("The message body is readonly"); } - if (value == null) - { + if (value == null) { content.add(null); } - else if (value instanceof Boolean) - { + else if (value instanceof Boolean) { content.add(value); } - else if (value instanceof Byte) - { + else if (value instanceof Byte) { content.add(value); } - else if (value instanceof Short) - { + else if (value instanceof Short) { content.add(value); } - else if (value instanceof Character) - { + else if (value instanceof Character) { content.add(value); } - else if (value instanceof Integer) - { + else if (value instanceof Integer) { content.add(value); } - else if (value instanceof Long) - { + else if (value instanceof Long) { content.add(value); } - else if (value instanceof Float) - { + else if (value instanceof Float) { content.add(value); } - else if (value instanceof Double) - { + else if (value instanceof Double) { content.add(value); } - else if (value instanceof String) - { + else if (value instanceof String) { content.add(value); } - else if (value instanceof byte[]) - { - content.add(((byte[])value).clone()); + else if (value instanceof byte[]) { + content.add(((byte[]) value).clone()); } - else - { + else { throw new MessageFormatException("Invalid object type"); } } - public void reset() throws JMSException - { + public void reset() throws JMSException { bodyWriteOnly = false; position = 0; size = content.size(); diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SimpleJMSTextMessage.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SimpleJMSTextMessage.java index c827cf35b3..2e839dfa8d 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SimpleJMSTextMessage.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SimpleJMSTextMessage.java @@ -19,8 +19,7 @@ package org.apache.activemq.artemis.jms.tests.message; import javax.jms.JMSException; import javax.jms.TextMessage; -public class SimpleJMSTextMessage extends SimpleJMSMessage implements TextMessage -{ +public class SimpleJMSTextMessage extends SimpleJMSMessage implements TextMessage { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -31,25 +30,21 @@ public class SimpleJMSTextMessage extends SimpleJMSMessage implements TextMessag // Constructors -------------------------------------------------- - public SimpleJMSTextMessage() - { + public SimpleJMSTextMessage() { this(null); } - public SimpleJMSTextMessage(final String text) - { + public SimpleJMSTextMessage(final String text) { this.text = text; } // TextMessage implementation ------------------------------------ - public void setText(final String text) throws JMSException - { + public void setText(final String text) throws JMSException { this.text = text; } - public String getText() throws JMSException - { + public String getText() throws JMSException { return text; } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SomeObject.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SomeObject.java index 8f3c1504da..4ae8e183cd 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SomeObject.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/SomeObject.java @@ -21,8 +21,7 @@ import java.io.Serializable; /** * ObjectMessageTest needed a simple class to test ClassLoadingIsolations */ -public class SomeObject implements Serializable -{ +public class SomeObject implements Serializable { private static final long serialVersionUID = -2939720794544432834L; @@ -30,32 +29,26 @@ public class SomeObject implements Serializable int j; - public SomeObject(final int i, final int j) - { + public SomeObject(final int i, final int j) { this.i = i; this.j = j; } @Override - public boolean equals(final Object o) - { - if (this == o) - { + public boolean equals(final Object o) { + if (this == o) { return true; } - if (o == null || getClass() != o.getClass()) - { + if (o == null || getClass() != o.getClass()) { return false; } - SomeObject that = (SomeObject)o; + SomeObject that = (SomeObject) o; - if (i != that.i) - { + if (i != that.i) { return false; } - if (j != that.j) - { + if (j != that.j) { return false; } @@ -63,8 +56,7 @@ public class SomeObject implements Serializable } @Override - public int hashCode() - { + public int hashCode() { int result; result = i; result = 31 * result + j; diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/StreamMessageTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/StreamMessageTest.java index 35f9685a30..bdc8ea79bd 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/StreamMessageTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/StreamMessageTest.java @@ -28,8 +28,7 @@ import org.junit.Test; /** * A test that sends/receives stream messages to the JMS provider and verifies their integrity. */ -public class StreamMessageTest extends MessageTestBase -{ +public class StreamMessageTest extends MessageTestBase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -42,23 +41,20 @@ public class StreamMessageTest extends MessageTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); message = session.createStreamMessage(); } @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { message = null; super.tearDown(); } @Test - public void testNullValue() throws Exception - { + public void testNullValue() throws Exception { StreamMessage m = session.createStreamMessage(); m.writeString(null); @@ -75,8 +71,7 @@ public class StreamMessageTest extends MessageTestBase // Protected ----------------------------------------------------- @Override - protected void prepareMessage(final Message m) throws JMSException - { + protected void prepareMessage(final Message m) throws JMSException { super.prepareMessage(m); StreamMessage sm = (StreamMessage) m; @@ -95,8 +90,7 @@ public class StreamMessageTest extends MessageTestBase } @Override - protected void assertEquivalent(final Message m, final int mode, final boolean redelivery) throws JMSException - { + protected void assertEquivalent(final Message m, final int mode, final boolean redelivery) throws JMSException { super.assertEquivalent(m, mode, redelivery); StreamMessage sm = (StreamMessage) m; diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/TextMessageTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/TextMessageTest.java index 42a3ea6e05..09cc2fa5e8 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/TextMessageTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/TextMessageTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.jms.tests.message; + import org.junit.Before; import org.junit.After; @@ -29,8 +30,7 @@ import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; /** * A test that sends/receives text messages to the JMS provider and verifies their integrity. */ -public class TextMessageTest extends MessageTestBase -{ +public class TextMessageTest extends MessageTestBase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -43,27 +43,24 @@ public class TextMessageTest extends MessageTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); message = session.createTextMessage(); } @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { message = null; super.tearDown(); } @Test - public void testClearProperties() throws Exception - { - ((TextMessage)message).setText("something"); + public void testClearProperties() throws Exception { + ((TextMessage) message).setText("something"); queueProd.send(message); - TextMessage rm = (TextMessage)queueCons.receive(); + TextMessage rm = (TextMessage) queueCons.receive(); rm.clearProperties(); @@ -73,20 +70,18 @@ public class TextMessageTest extends MessageTestBase // Protected ----------------------------------------------------- @Override - protected void prepareMessage(final Message m) throws JMSException - { + protected void prepareMessage(final Message m) throws JMSException { super.prepareMessage(m); - TextMessage tm = (TextMessage)m; + TextMessage tm = (TextMessage) m; tm.setText("this is the payload"); } @Override - protected void assertEquivalent(final Message m, final int mode, final boolean redelivery) throws JMSException - { + protected void assertEquivalent(final Message m, final int mode, final boolean redelivery) throws JMSException { super.assertEquivalent(m, mode, redelivery); - TextMessage tm = (TextMessage)m; + TextMessage tm = (TextMessage) m; ProxyAssertSupport.assertEquals("this is the payload", tm.getText()); } } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignBytesMessageTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignBytesMessageTest.java index 09bb5f069d..33c8cd8520 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignBytesMessageTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignBytesMessageTest.java @@ -26,11 +26,10 @@ import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; /** * Tests the delivery/receipt of a foreign byte message */ -public class ForeignBytesMessageTest extends ForeignMessageTest -{ +public class ForeignBytesMessageTest extends ForeignMessageTest { + @Override - protected Message createForeignMessage() throws Exception - { + protected Message createForeignMessage() throws Exception { SimpleJMSBytesMessage m = new SimpleJMSBytesMessage(); log.debug("creating JMS Message type " + m.getClass().getName()); @@ -41,17 +40,15 @@ public class ForeignBytesMessageTest extends ForeignMessageTest } @Override - protected void assertEquivalent(final Message m, final int mode, final boolean redelivery) throws JMSException - { + protected void assertEquivalent(final Message m, final int mode, final boolean redelivery) throws JMSException { super.assertEquivalent(m, mode, redelivery); - BytesMessage byteMsg = (BytesMessage)m; + BytesMessage byteMsg = (BytesMessage) m; StringBuffer sb = new StringBuffer(); byte[] buffer = new byte[1024]; int n = byteMsg.readBytes(buffer); - while (n != -1) - { + while (n != -1) { sb.append(new String(buffer, 0, n)); n = byteMsg.readBytes(buffer); } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignMapMessageTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignMapMessageTest.java index c0ea0d4a0a..31e00832b3 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignMapMessageTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignMapMessageTest.java @@ -26,13 +26,12 @@ import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; /** * Tests the delivery/receipt of a foreign map message */ -public class ForeignMapMessageTest extends ForeignMessageTest -{ +public class ForeignMapMessageTest extends ForeignMessageTest { + private final String obj = new String("stringobject"); @Override - protected Message createForeignMessage() throws Exception - { + protected Message createForeignMessage() throws Exception { SimpleJMSMapMessage m = new SimpleJMSMapMessage(); log.debug("creating JMS Message type " + m.getClass().getName()); @@ -44,18 +43,17 @@ public class ForeignMapMessageTest extends ForeignMessageTest m.setInt("int1", 3); m.setLong("long1", 4L); m.setObject("object1", obj); - m.setShort("short1", (short)5); + m.setShort("short1", (short) 5); m.setString("string1", "stringvalue"); return m; } @Override - protected void assertEquivalent(final Message m, final int mode, final boolean redelivery) throws JMSException - { + protected void assertEquivalent(final Message m, final int mode, final boolean redelivery) throws JMSException { super.assertEquivalent(m, mode, redelivery); - MapMessage map = (MapMessage)m; + MapMessage map = (MapMessage) m; ProxyAssertSupport.assertTrue(map.getBoolean("boolean1")); ProxyAssertSupport.assertEquals(map.getChar("char1"), 'c'); @@ -64,7 +62,7 @@ public class ForeignMapMessageTest extends ForeignMessageTest ProxyAssertSupport.assertEquals(map.getInt("int1"), 3); ProxyAssertSupport.assertEquals(map.getLong("long1"), 4L); ProxyAssertSupport.assertEquals(map.getObject("object1"), obj); - ProxyAssertSupport.assertEquals(map.getShort("short1"), (short)5); + ProxyAssertSupport.assertEquals(map.getShort("short1"), (short) 5); ProxyAssertSupport.assertEquals(map.getString("string1"), "stringvalue"); } } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignMessageTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignMessageTest.java index 94154b0fe9..bacf8d9718 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignMessageTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignMessageTest.java @@ -32,26 +32,23 @@ import org.junit.Test; /** * Tests the delivery/receipt of a foreign message */ -public class ForeignMessageTest extends MessageTestBase -{ +public class ForeignMessageTest extends MessageTestBase { + @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); message = createForeignMessage(); } @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { super.tearDown(); message = null; } - protected Message createForeignMessage() throws Exception - { + protected Message createForeignMessage() throws Exception { SimpleJMSMessage m = new SimpleJMSMessage(); log.debug("creating JMS Message type " + m.getClass().getName()); @@ -59,8 +56,7 @@ public class ForeignMessageTest extends MessageTestBase } @Test - public void testForeignMessageSetDestination() throws Exception - { + public void testForeignMessageSetDestination() throws Exception { // create a Bytes foreign message SimpleJMSTextMessage txt = new SimpleJMSTextMessage("hello from Brazil!"); txt.setJMSDestination(null); @@ -74,10 +70,8 @@ public class ForeignMessageTest extends MessageTestBase ProxyAssertSupport.assertEquals("hello from Brazil!", txt.getText()); } - @Test - public void testForeignMessageCorrelationIDBytesDisabled() throws Exception - { + public void testForeignMessageCorrelationIDBytesDisabled() throws Exception { System.setProperty(ActiveMQJMSConstants.JMS_ACTIVEMQ_ENABLE_BYTE_ARRAY_JMS_CORRELATION_ID_PROPERTY_NAME, "false"); SimpleJMSMessage msg = new SimpleJMSMessage(); @@ -97,8 +91,7 @@ public class ForeignMessageTest extends MessageTestBase } @Test - public void testForeignMessageCorrelationID() throws Exception - { + public void testForeignMessageCorrelationID() throws Exception { System.setProperty(ActiveMQJMSConstants.JMS_ACTIVEMQ_ENABLE_BYTE_ARRAY_JMS_CORRELATION_ID_PROPERTY_NAME, "true"); SimpleJMSMessage msg = new SimpleJMSMessage(); @@ -120,20 +113,16 @@ public class ForeignMessageTest extends MessageTestBase Assert.assertNull(rec.getJMSCorrelationID()); } - private void assertByteArraysEqual(final byte[] bytes1, final byte[] bytes2) - { - if (bytes1 == null | bytes2 == null) - { + private void assertByteArraysEqual(final byte[] bytes1, final byte[] bytes2) { + if (bytes1 == null | bytes2 == null) { ProxyAssertSupport.fail(); } - if (bytes1.length != bytes2.length) - { + if (bytes1.length != bytes2.length) { ProxyAssertSupport.fail(); } - for (int i = 0; i < bytes1.length; i++) - { + for (int i = 0; i < bytes1.length; i++) { ProxyAssertSupport.assertEquals(bytes1[i], bytes2[i]); } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignObjectMessageTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignObjectMessageTest.java index 193ed24cd8..29a6b70337 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignObjectMessageTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignObjectMessageTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.jms.tests.message.foreign; + import org.junit.Before; import org.junit.After; @@ -28,14 +29,13 @@ import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; /** * Tests the delivery/receipt of a foreign object message */ -public class ForeignObjectMessageTest extends ForeignMessageTest -{ +public class ForeignObjectMessageTest extends ForeignMessageTest { + private ForeignTestObject testObj; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { testObj = new ForeignTestObject("hello", 2.2D); super.setUp(); @@ -43,15 +43,13 @@ public class ForeignObjectMessageTest extends ForeignMessageTest @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { super.tearDown(); testObj = null; } @Override - protected Message createForeignMessage() throws Exception - { + protected Message createForeignMessage() throws Exception { SimpleJMSObjectMessage m = new SimpleJMSObjectMessage(); log.debug("creating JMS Message type " + m.getClass().getName()); @@ -62,11 +60,10 @@ public class ForeignObjectMessageTest extends ForeignMessageTest } @Override - protected void assertEquivalent(final Message m, final int mode, final boolean redelivery) throws JMSException - { + protected void assertEquivalent(final Message m, final int mode, final boolean redelivery) throws JMSException { super.assertEquivalent(m, mode, redelivery); - ObjectMessage obj = (ObjectMessage)m; + ObjectMessage obj = (ObjectMessage) m; ProxyAssertSupport.assertNotNull(obj.getObject()); ProxyAssertSupport.assertEquals(obj.getObject(), testObj); diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignStreamMessageTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignStreamMessageTest.java index bb501a8535..1534c6f68d 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignStreamMessageTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignStreamMessageTest.java @@ -26,12 +26,10 @@ import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; /** * Tests the delivery/receipt of a foreign stream message */ -public class ForeignStreamMessageTest extends ForeignMessageTest -{ +public class ForeignStreamMessageTest extends ForeignMessageTest { @Override - protected Message createForeignMessage() throws Exception - { + protected Message createForeignMessage() throws Exception { SimpleJMSStreamMessage m = new SimpleJMSStreamMessage(); log.debug("creating JMS Message type " + m.getClass().getName()); @@ -44,18 +42,17 @@ public class ForeignStreamMessageTest extends ForeignMessageTest m.writeInt(3); m.writeLong(4L); m.writeObject("object"); - m.writeShort((short)5); + m.writeShort((short) 5); m.writeString("stringvalue"); return m; } @Override - protected void assertEquivalent(final Message m, final int mode, final boolean redelivery) throws JMSException - { + protected void assertEquivalent(final Message m, final int mode, final boolean redelivery) throws JMSException { super.assertEquivalent(m, mode, redelivery); - StreamMessage sm = (StreamMessage)m; + StreamMessage sm = (StreamMessage) m; ProxyAssertSupport.assertTrue(sm.readBoolean()); @@ -71,7 +68,7 @@ public class ForeignStreamMessageTest extends ForeignMessageTest ProxyAssertSupport.assertEquals(sm.readInt(), 3); ProxyAssertSupport.assertEquals(sm.readLong(), 4L); ProxyAssertSupport.assertEquals(sm.readObject(), "object"); - ProxyAssertSupport.assertEquals(sm.readShort(), (short)5); + ProxyAssertSupport.assertEquals(sm.readShort(), (short) 5); ProxyAssertSupport.assertEquals(sm.readString(), "stringvalue"); } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignTestObject.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignTestObject.java index fd035bdb43..a18eca4836 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignTestObject.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignTestObject.java @@ -21,46 +21,39 @@ import java.io.Serializable; /** * A Simple Serializable Object */ -public class ForeignTestObject implements Serializable -{ +public class ForeignTestObject implements Serializable { + private static final long serialVersionUID = -7503042537789321104L; private String s1; private double d1; - public ForeignTestObject(final String s, final double d) - { + public ForeignTestObject(final String s, final double d) { s1 = s; d1 = d; } - public double getD1() - { + public double getD1() { return d1; } - public void setD1(final double d1) - { + public void setD1(final double d1) { this.d1 = d1; } - public String getS1() - { + public String getS1() { return s1; } - public void setS1(final String s1) - { + public void setS1(final String s1) { this.s1 = s1; } @Override - public boolean equals(final Object o) - { - if (o instanceof ForeignTestObject) - { - ForeignTestObject to = (ForeignTestObject)o; + public boolean equals(final Object o) { + if (o instanceof ForeignTestObject) { + ForeignTestObject to = (ForeignTestObject) o; return s1.equals(to.getS1()) && d1 == to.getD1(); } @@ -68,8 +61,7 @@ public class ForeignTestObject implements Serializable } @Override - public int hashCode() - { + public int hashCode() { // TODO return 0; } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignTextMessageTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignTextMessageTest.java index dd634d7e96..780f4fc216 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignTextMessageTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/message/foreign/ForeignTextMessageTest.java @@ -26,23 +26,20 @@ import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport; /** * Tests the delivery/receipt of a foreign text message */ -public class ForeignTextMessageTest extends ForeignMessageTest -{ +public class ForeignTextMessageTest extends ForeignMessageTest { @Override - protected Message createForeignMessage() throws Exception - { + protected Message createForeignMessage() throws Exception { SimpleJMSTextMessage m = new SimpleJMSTextMessage(); m.setText("this is the payload"); return m; } @Override - protected void assertEquivalent(final Message m, final int mode, final boolean redelivery) throws JMSException - { + protected void assertEquivalent(final Message m, final int mode, final boolean redelivery) throws JMSException { super.assertEquivalent(m, mode, redelivery); - TextMessage tm = (TextMessage)m; + TextMessage tm = (TextMessage) m; ProxyAssertSupport.assertEquals("this is the payload", tm.getText()); } } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/selector/SelectorTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/selector/SelectorTest.java index 85469d7d16..0db8a3b436 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/selector/SelectorTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/selector/SelectorTest.java @@ -38,8 +38,7 @@ import org.junit.Test; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -public class SelectorTest extends ActiveMQServerTestCase -{ +public class SelectorTest extends ActiveMQServerTestCase { /** * Test case for http://jira.jboss.org/jira/browse/JBMESSAGING-105 @@ -50,12 +49,10 @@ public class SelectorTest extends ActiveMQServerTestCase * message is now attempted. The message should be redelivered. */ @Test - public void testSelectiveClosingConsumer() throws Exception - { + public void testSelectiveClosingConsumer() throws Exception { Connection conn = null; - try - { + try { conn = getConnectionFactory().createConnection(); conn.start(); @@ -95,24 +92,20 @@ public class SelectorTest extends ActiveMQServerTestCase ProxyAssertSupport.assertEquals(rec.getJMSMessageID(), blueMessage.getJMSMessageID()); ProxyAssertSupport.assertEquals("blue", rec.getStringProperty("color")); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testManyTopic() throws Exception - { + public void testManyTopic() throws Exception { String selector1 = "beatle = 'john'"; Connection conn = null; - try - { + try { conn = getConnectionFactory().createConnection(); conn.start(); @@ -122,8 +115,7 @@ public class SelectorTest extends ActiveMQServerTestCase MessageProducer prod = sess.createProducer(ActiveMQServerTestCase.topic1); - for (int j = 0; j < 100; j++) - { + for (int j = 0; j < 100; j++) { Message m = sess.createMessage(); m.setStringProperty("beatle", "john"); @@ -137,8 +129,7 @@ public class SelectorTest extends ActiveMQServerTestCase prod.send(m); } - for (int j = 0; j < 100; j++) - { + for (int j = 0; j < 100; j++) { Message m = cons1.receive(1000); ProxyAssertSupport.assertNotNull(m); @@ -150,24 +141,20 @@ public class SelectorTest extends ActiveMQServerTestCase ProxyAssertSupport.assertNull(m); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testManyQueue() throws Exception - { + public void testManyQueue() throws Exception { String selector1 = "beatle = 'john'"; Connection conn = null; - try - { + try { conn = getConnectionFactory().createConnection(); conn.start(); @@ -178,8 +165,7 @@ public class SelectorTest extends ActiveMQServerTestCase MessageProducer prod = sess.createProducer(queue1); - for (int j = 0; j < 100; j++) - { + for (int j = 0; j < 100; j++) { Message m = sess.createMessage(); m.setStringProperty("beatle", "john"); @@ -197,8 +183,7 @@ public class SelectorTest extends ActiveMQServerTestCase prod.send(m); } - for (int j = 0; j < 100; j++) - { + for (int j = 0; j < 100; j++) { Message m = cons1.receive(1000); ProxyAssertSupport.assertNotNull(m); @@ -218,8 +203,7 @@ public class SelectorTest extends ActiveMQServerTestCase MessageConsumer cons2 = sess.createConsumer(queue1, selector2); - for (int j = 0; j < 100; j++) - { + for (int j = 0; j < 100; j++) { m = cons2.receive(1000); ProxyAssertSupport.assertNotNull(m); @@ -229,19 +213,17 @@ public class SelectorTest extends ActiveMQServerTestCase ProxyAssertSupport.assertEquals("kermit the frog", m.getStringProperty("beatle")); } -// m = cons2.receiveNoWait(); -// -// if (m != null) -// { -// log.info("got " + m.getStringProperty("beatle") + " j: " + m.getIntProperty("wibble")); -// } + // m = cons2.receiveNoWait(); + // + // if (m != null) + // { + // log.info("got " + m.getStringProperty("beatle") + " j: " + m.getIntProperty("wibble")); + // } //ProxyAssertSupport.assertNull(m); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } @@ -251,14 +233,12 @@ public class SelectorTest extends ActiveMQServerTestCase // http://jira.jboss.org/jira/browse/JBMESSAGING-775 @Test - public void testManyQueueWithExpired() throws Exception - { + public void testManyQueueWithExpired() throws Exception { String selector1 = "beatle = 'john'"; Connection conn = null; - try - { + try { conn = getConnectionFactory().createConnection(); conn.start(); @@ -268,8 +248,7 @@ public class SelectorTest extends ActiveMQServerTestCase MessageProducer prod = sess.createProducer(queue1); - for (int j = 0; j < NUM_MESSAGES; j++) - { + for (int j = 0; j < NUM_MESSAGES; j++) { Message m = sess.createMessage(); m.setStringProperty("beatle", "john"); @@ -307,8 +286,7 @@ public class SelectorTest extends ActiveMQServerTestCase MessageConsumer cons1 = sess.createConsumer(queue1, selector1); - for (int j = 0; j < NUM_MESSAGES; j++) - { + for (int j = 0; j < NUM_MESSAGES; j++) { Message m = cons1.receive(1000); ProxyAssertSupport.assertNotNull(m); @@ -324,8 +302,7 @@ public class SelectorTest extends ActiveMQServerTestCase MessageConsumer cons2 = sess.createConsumer(queue1, selector2); - for (int j = 0; j < NUM_MESSAGES; j++) - { + for (int j = 0; j < NUM_MESSAGES; j++) { m = cons2.receive(1000); ProxyAssertSupport.assertNotNull(m); @@ -337,37 +314,31 @@ public class SelectorTest extends ActiveMQServerTestCase ProxyAssertSupport.assertNull(m); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testManyRedeliveriesTopic() throws Exception - { + public void testManyRedeliveriesTopic() throws Exception { String selector1 = "beatle = 'john'"; Connection conn = null; - try - { + try { conn = getConnectionFactory().createConnection(); conn.start(); - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer cons1 = sess.createConsumer(ActiveMQServerTestCase.topic1, selector1); MessageProducer prod = sess.createProducer(ActiveMQServerTestCase.topic1); - for (int j = 0; j < 10; j++) - { + for (int j = 0; j < 10; j++) { Message m = sess.createMessage(); m.setStringProperty("beatle", "john"); @@ -381,8 +352,7 @@ public class SelectorTest extends ActiveMQServerTestCase prod.send(m); } - for (int j = 0; j < 10; j++) - { + for (int j = 0; j < 10; j++) { Message m = cons1.receive(1000); ProxyAssertSupport.assertNotNull(m); @@ -395,38 +365,32 @@ public class SelectorTest extends ActiveMQServerTestCase sess.close(); } } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testManyRedeliveriesQueue() throws Exception - { + public void testManyRedeliveriesQueue() throws Exception { String selector1 = "beatle = 'john'"; Connection conn = null; - try - { + try { conn = getConnectionFactory().createConnection(); conn.start(); - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer cons1 = sess.createConsumer(queue1, selector1); MessageProducer prod = sess.createProducer(queue1); - for (int j = 0; j < 10; j++) - { + for (int j = 0; j < 10; j++) { TextMessage m = sess.createTextMessage("message-a-" + j); m.setStringProperty("beatle", "john"); @@ -440,8 +404,7 @@ public class SelectorTest extends ActiveMQServerTestCase prod.send(m); } - for (int j = 0; j < 10; j++) - { + for (int j = 0; j < 10; j++) { Message m = cons1.receive(1000); ProxyAssertSupport.assertNotNull(m); @@ -454,10 +417,8 @@ public class SelectorTest extends ActiveMQServerTestCase sess.close(); } } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } @@ -466,8 +427,7 @@ public class SelectorTest extends ActiveMQServerTestCase } @Test - public void testWithSelector() throws Exception - { + public void testWithSelector() throws Exception { String selector1 = "beatle = 'john'"; String selector2 = "beatle = 'paul'"; String selector3 = "beatle = 'george'"; @@ -476,8 +436,7 @@ public class SelectorTest extends ActiveMQServerTestCase Connection conn = null; - try - { + try { conn = getConnectionFactory().createConnection(); conn.start(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -541,22 +500,18 @@ public class SelectorTest extends ActiveMQServerTestCase ProxyAssertSupport.assertEquals("ringo", r4.getStringProperty("beatle")); ProxyAssertSupport.assertEquals("jesus", r5.getStringProperty("beatle")); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testManyConsumersWithDifferentSelectors() throws Exception - { + public void testManyConsumersWithDifferentSelectors() throws Exception { Connection conn = null; - try - { + try { conn = getConnectionFactory().createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer p = sess.createProducer(queue1); @@ -567,8 +522,7 @@ public class SelectorTest extends ActiveMQServerTestCase Session cs2 = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); final MessageConsumer c2 = cs2.createConsumer(queue1, "weight = 2"); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { Message m = sess.createTextMessage("message" + i); m.setIntProperty("weight", i % 2 + 1); p.send(m); @@ -581,55 +535,41 @@ public class SelectorTest extends ActiveMQServerTestCase final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); - new Thread(new Runnable() - { - public void run() - { - try - { - while (true) - { + new Thread(new Runnable() { + public void run() { + try { + while (true) { Message m = c.receive(1000); - if (m != null) - { + if (m != null) { received.add(m); } - else - { + else { latch.countDown(); return; } } } - catch (Exception e) - { + catch (Exception e) { log.error("receive failed", e); } } }, "consumer thread 1").start(); - new Thread(new Runnable() - { - public void run() - { - try - { - while (true) - { + new Thread(new Runnable() { + public void run() { + try { + while (true) { Message m = c2.receive(1000); - if (m != null) - { + if (m != null) { received2.add(m); } - else - { + else { latch2.countDown(); return; } } } - catch (Exception e) - { + catch (Exception e) { log.error("receive failed", e); } } @@ -639,35 +579,29 @@ public class SelectorTest extends ActiveMQServerTestCase ActiveMQTestBase.waitForLatch(latch2); ProxyAssertSupport.assertEquals(5, received.size()); - for (Message m : received) - { + for (Message m : received) { int value = m.getIntProperty("weight"); ProxyAssertSupport.assertEquals(value, 1); } ProxyAssertSupport.assertEquals(5, received2.size()); - for (Message m : received2) - { + for (Message m : received2) { int value = m.getIntProperty("weight"); ProxyAssertSupport.assertEquals(value, 2); } } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testDeliveryModeOnSelector() throws Exception - { + public void testDeliveryModeOnSelector() throws Exception { Connection conn = null; - try - { + try { conn = getConnectionFactory().createConnection(); conn.start(); @@ -688,7 +622,7 @@ public class SelectorTest extends ActiveMQServerTestCase msg = session.createTextMessage("Persistent"); prodPersistent.send(msg); - msg = (TextMessage)persistentConsumer.receive(2000); + msg = (TextMessage) persistentConsumer.receive(2000); ProxyAssertSupport.assertNotNull(msg); ProxyAssertSupport.assertEquals(DeliveryMode.PERSISTENT, msg.getJMSDeliveryMode()); ProxyAssertSupport.assertEquals("Persistent", msg.getText()); @@ -698,29 +632,25 @@ public class SelectorTest extends ActiveMQServerTestCase persistentConsumer.close(); MessageConsumer genericConsumer = session.createConsumer(queue1); - msg = (TextMessage)genericConsumer.receive(1000); + msg = (TextMessage) genericConsumer.receive(1000); ProxyAssertSupport.assertNotNull(msg); ProxyAssertSupport.assertEquals("NonPersistent", msg.getText()); ProxyAssertSupport.assertEquals(DeliveryMode.NON_PERSISTENT, msg.getJMSDeliveryMode()); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testJMSMessageIDOnSelector() throws Exception - { + public void testJMSMessageIDOnSelector() throws Exception { Connection conn = null; - try - { + try { conn = getConnectionFactory().createConnection(); conn.start(); @@ -740,7 +670,7 @@ public class SelectorTest extends ActiveMQServerTestCase conn.start(); - TextMessage rec = (TextMessage)cons.receive(10000); + TextMessage rec = (TextMessage) cons.receive(10000); assertNotNull(rec); @@ -749,22 +679,18 @@ public class SelectorTest extends ActiveMQServerTestCase assertNull(cons.receiveNoWait()); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testJMSPriorityOnSelector() throws Exception - { + public void testJMSPriorityOnSelector() throws Exception { Connection conn = null; - try - { + try { conn = getConnectionFactory().createConnection(); conn.start(); @@ -784,7 +710,7 @@ public class SelectorTest extends ActiveMQServerTestCase conn.start(); - TextMessage rec = (TextMessage)cons.receive(10000); + TextMessage rec = (TextMessage) cons.receive(10000); assertNotNull(rec); @@ -793,22 +719,18 @@ public class SelectorTest extends ActiveMQServerTestCase assertNull(cons.receiveNoWait()); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testJMSTimestampOnSelector() throws Exception - { + public void testJMSTimestampOnSelector() throws Exception { Connection conn = null; - try - { + try { conn = getConnectionFactory().createConnection(); conn.start(); @@ -830,7 +752,7 @@ public class SelectorTest extends ActiveMQServerTestCase conn.start(); - TextMessage rec = (TextMessage)cons.receive(10000); + TextMessage rec = (TextMessage) cons.receive(10000); assertNotNull(rec); @@ -839,22 +761,18 @@ public class SelectorTest extends ActiveMQServerTestCase assertNull(cons.receiveNoWait()); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testJMSExpirationOnSelector() throws Exception - { + public void testJMSExpirationOnSelector() throws Exception { Connection conn = null; - try - { + try { conn = getConnectionFactory().createConnection(); conn.start(); @@ -879,7 +797,7 @@ public class SelectorTest extends ActiveMQServerTestCase conn.start(); - TextMessage rec = (TextMessage)cons.receive(10000); + TextMessage rec = (TextMessage) cons.receive(10000); assertNotNull(rec); @@ -888,22 +806,18 @@ public class SelectorTest extends ActiveMQServerTestCase assertNull(cons.receiveNoWait()); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testJMSTypeOnSelector() throws Exception - { + public void testJMSTypeOnSelector() throws Exception { Connection conn = null; - try - { + try { conn = getConnectionFactory().createConnection(); conn.start(); @@ -925,7 +839,7 @@ public class SelectorTest extends ActiveMQServerTestCase conn.start(); - TextMessage rec = (TextMessage)cons.receive(10000); + TextMessage rec = (TextMessage) cons.receive(10000); assertNotNull(rec); @@ -934,22 +848,18 @@ public class SelectorTest extends ActiveMQServerTestCase assertNull(cons.receiveNoWait()); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } @Test - public void testJMSCorrelationIDOnSelector() throws Exception - { + public void testJMSCorrelationIDOnSelector() throws Exception { Connection conn = null; - try - { + try { conn = getConnectionFactory().createConnection(); conn.start(); @@ -971,7 +881,7 @@ public class SelectorTest extends ActiveMQServerTestCase conn.start(); - TextMessage rec = (TextMessage)cons.receive(10000); + TextMessage rec = (TextMessage) cons.receive(10000); assertNotNull(rec); @@ -980,27 +890,22 @@ public class SelectorTest extends ActiveMQServerTestCase assertNull(cons.receiveNoWait()); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } } - // Test case proposed by a customer on this user forum: // http://community.jboss.org/thread/153426?tstart=0 // This test needs to be moved away - public void disabled_testMultipleConsumers() throws Exception - { + public void disabled_testMultipleConsumers() throws Exception { Connection conn = null; - try - { + try { ConnectionFactory factory = getConnectionFactory(); - ActiveMQConnectionFactory hcf = (ActiveMQConnectionFactory)factory; + ActiveMQConnectionFactory hcf = (ActiveMQConnectionFactory) factory; hcf.setConsumerWindowSize(0); @@ -1055,10 +960,9 @@ public class SelectorTest extends ActiveMQServerTestCase msgProducer.close(); msgProducer = null; - MessageConsumer msgConsumer = session.createConsumer(queue1, "PROP2 = 'VALUE2'"); - tm = (TextMessage)msgConsumer.receive(5000); + tm = (TextMessage) msgConsumer.receive(5000); assertNotNull(tm); @@ -1069,7 +973,6 @@ public class SelectorTest extends ActiveMQServerTestCase conn.close(); // this should close the consumer, producer and session associated with the connection - // Reopen the connection and consumer conn = getConnectionFactory().createConnection(); @@ -1079,25 +982,23 @@ public class SelectorTest extends ActiveMQServerTestCase msgConsumer = session.createConsumer(queue1); - tm = (TextMessage)msgConsumer.receive(5000); + tm = (TextMessage) msgConsumer.receive(5000); Assert.assertEquals("1", tm.getText()); Assert.assertEquals("VALUE1", tm.getStringProperty("PROP1")); - - tm = (TextMessage)msgConsumer.receive(5000); + tm = (TextMessage) msgConsumer.receive(5000); Assert.assertEquals("2", tm.getText()); Assert.assertEquals("VALUE1", tm.getStringProperty("PROP1")); - tm = (TextMessage)msgConsumer.receive(5000); + tm = (TextMessage) msgConsumer.receive(5000); Assert.assertEquals("4", tm.getText()); Assert.assertEquals("VALUE2", tm.getStringProperty("PROP2")); - - tm = (TextMessage)msgConsumer.receive(5000); + tm = (TextMessage) msgConsumer.receive(5000); Assert.assertEquals("5", tm.getText()); Assert.assertEquals("VALUE1", tm.getStringProperty("PROP1")); - tm = (TextMessage)msgConsumer.receive(5000); + tm = (TextMessage) msgConsumer.receive(5000); Assert.assertEquals("6", tm.getText()); Assert.assertEquals("VALUE1", tm.getStringProperty("PROP1")); Assert.assertEquals("VALUE2", tm.getStringProperty("PROP2")); @@ -1105,10 +1006,8 @@ public class SelectorTest extends ActiveMQServerTestCase tm.acknowledge(); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/ServerManagement.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/ServerManagement.java index 7a9bf79bd4..2bf0c06a06 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/ServerManagement.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/ServerManagement.java @@ -29,8 +29,7 @@ import org.apache.activemq.artemis.jms.tests.tools.container.Server; * Collection of static methods to use to start/stop and interact with the in-memory JMS server. It * is also use to start/stop a remote server. */ -public class ServerManagement -{ +public class ServerManagement { // Constants ----------------------------------------------------- // logging levels used by the remote client to forward log output on a remote server @@ -60,13 +59,11 @@ public class ServerManagement * Makes sure that a "hollow" TestServer (either local or remote, depending on the nature of the * test), exists and it's ready to be started. */ - public static synchronized Server create() throws Exception - { + public static synchronized Server create() throws Exception { return new LocalTestServer(); } - public static void start(final int i, final String config, final boolean clearDatabase) throws Exception - { + public static void start(final int i, final String config, final boolean clearDatabase) throws Exception { ServerManagement.start(i, config, clearDatabase, true); } @@ -77,56 +74,44 @@ public class ServerManagement public static void start(final int i, final String config, final boolean clearDatabase, - final boolean startActiveMQServer) throws Exception - { + final boolean startActiveMQServer) throws Exception { throw new IllegalStateException("Method to start a server is not implemented"); } - public static synchronized void kill(final int i) throws Exception - { - if (i == 0) - { + public static synchronized void kill(final int i) throws Exception { + if (i == 0) { // Cannot kill server 0 if there are any other servers since it has the rmi registry in it - for (int j = 1; j < ServerManagement.servers.size(); j++) - { - if (ServerManagement.servers.get(j) != null) - { + for (int j = 1; j < ServerManagement.servers.size(); j++) { + if (ServerManagement.servers.get(j) != null) { throw new IllegalStateException("Cannot kill server 0, since server[" + j + "] still exists"); } } } - if (i > ServerManagement.servers.size()) - { + if (i > ServerManagement.servers.size()) { ServerManagement.log.error("server " + i + - " has not been created or has already been killed, so it cannot be killed"); + " has not been created or has already been killed, so it cannot be killed"); } - else - { + else { Server server = ServerManagement.servers.get(i); ServerManagement.log.info("invoking kill() on server " + i); - try - { + try { server.kill(); } - catch (Throwable t) - { + catch (Throwable t) { // This is likely to throw an exception since the server dies before the response is received } ServerManagement.log.info("Waiting for server to die"); - try - { - while (true) - { + try { + while (true) { server.ping(); ServerManagement.log.debug("server " + i + " still alive ..."); Thread.sleep(100); } } - catch (Throwable e) - { + catch (Throwable e) { // Ok } @@ -137,8 +122,7 @@ public class ServerManagement } - public static Hashtable getJNDIEnvironment(final int serverIndex) - { + public static Hashtable getJNDIEnvironment(final int serverIndex) { return InVMInitialContextFactory.getJNDIEnvironment(serverIndex); } } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/Constants.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/Constants.java index 565fb989b0..2e2e2bbc6e 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/Constants.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/Constants.java @@ -16,8 +16,7 @@ */ package org.apache.activemq.artemis.jms.tests.tools.container; -public class Constants -{ +public class Constants { // Constants ----------------------------------------------------- public static final String SERVER_INDEX_PROPERTY_NAME = "activemq.test.server.index"; diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/InVMContext.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/InVMContext.java index 73c380eae7..0dfd49e5c0 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/InVMContext.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/InVMContext.java @@ -38,8 +38,7 @@ import javax.naming.Reference; import org.apache.activemq.artemis.jms.tests.JmsTestLogger; -public class InVMContext implements Context, Serializable -{ +public class InVMContext implements Context, Serializable { // Constants ----------------------------------------------------- private static final long serialVersionUID = 385743957345L; @@ -58,168 +57,136 @@ public class InVMContext implements Context, Serializable // Constructors -------------------------------------------------- - public InVMContext() - { + public InVMContext() { map = Collections.synchronizedMap(new HashMap()); } - public InVMContext(final String nameInNamespace) - { + public InVMContext(final String nameInNamespace) { this(); this.nameInNamespace = nameInNamespace; } // Context implementation ---------------------------------------- - public Object lookup(final Name name) throws NamingException - { + public Object lookup(final Name name) throws NamingException { throw new UnsupportedOperationException(); } - public Object lookup(String name) throws NamingException - { + public Object lookup(String name) throws NamingException { name = trimSlashes(name); int i = name.indexOf("/"); String tok = i == -1 ? name : name.substring(0, i); Object value = map.get(tok); - if (value == null) - { + if (value == null) { throw new NameNotFoundException("Name not found: " + tok); } - if (value instanceof InVMContext && i != -1) - { - return ((InVMContext)value).lookup(name.substring(i)); + if (value instanceof InVMContext && i != -1) { + return ((InVMContext) value).lookup(name.substring(i)); } - if (value instanceof Reference) - { - Reference ref = (Reference)value; + if (value instanceof Reference) { + Reference ref = (Reference) value; RefAddr refAddr = ref.get("nns"); // we only deal with references create by NonSerializableFactory - String key = (String)refAddr.getContent(); + String key = (String) refAddr.getContent(); return NonSerializableFactory.lookup(key); } - else - { + else { return value; } } - public void bind(final Name name, final Object obj) throws NamingException - { + public void bind(final Name name, final Object obj) throws NamingException { throw new UnsupportedOperationException(); } - public void bind(final String name, final Object obj) throws NamingException - { + public void bind(final String name, final Object obj) throws NamingException { internalBind(name, obj, false); } - public void rebind(final Name name, final Object obj) throws NamingException - { + public void rebind(final Name name, final Object obj) throws NamingException { throw new UnsupportedOperationException(); } - public void rebind(final String name, final Object obj) throws NamingException - { + public void rebind(final String name, final Object obj) throws NamingException { internalBind(name, obj, true); } - public void unbind(final Name name) throws NamingException - { + public void unbind(final Name name) throws NamingException { unbind(name.toString()); } - public void unbind(String name) throws NamingException - { + public void unbind(String name) throws NamingException { name = trimSlashes(name); int i = name.indexOf("/"); boolean terminal = i == -1; - if (terminal) - { + if (terminal) { map.remove(name); } - else - { + else { String tok = name.substring(0, i); - InVMContext c = (InVMContext)map.get(tok); - if (c == null) - { + InVMContext c = (InVMContext) map.get(tok); + if (c == null) { throw new NameNotFoundException("Context not found: " + tok); } c.unbind(name.substring(i)); } } - public void rename(final Name oldName, final Name newName) throws NamingException - { + public void rename(final Name oldName, final Name newName) throws NamingException { throw new UnsupportedOperationException(); } - public void rename(final String oldName, final String newName) throws NamingException - { + public void rename(final String oldName, final String newName) throws NamingException { throw new UnsupportedOperationException(); } - public NamingEnumeration list(final Name name) throws NamingException - { + public NamingEnumeration list(final Name name) throws NamingException { throw new UnsupportedOperationException(); } - public NamingEnumeration list(final String name) throws NamingException - { + public NamingEnumeration list(final String name) throws NamingException { throw new UnsupportedOperationException(); } - public NamingEnumeration listBindings(final Name name) throws NamingException - { + public NamingEnumeration listBindings(final Name name) throws NamingException { throw new UnsupportedOperationException(); } - public NamingEnumeration listBindings(String contextName) throws NamingException - { + public NamingEnumeration listBindings(String contextName) throws NamingException { contextName = trimSlashes(contextName); - if (!"".equals(contextName) && !".".equals(contextName)) - { - try - { - return ((InVMContext)lookup(contextName)).listBindings(""); + if (!"".equals(contextName) && !".".equals(contextName)) { + try { + return ((InVMContext) lookup(contextName)).listBindings(""); } - catch (Throwable t) - { + catch (Throwable t) { throw new NamingException(t.getMessage()); } } List l = new ArrayList(); - for (String name : map.keySet()) - { + for (String name : map.keySet()) { Object object = map.get(name); l.add(new Binding(name, object)); } return new NamingEnumerationImpl(l.iterator()); } - public void destroySubcontext(final Name name) throws NamingException - { + public void destroySubcontext(final Name name) throws NamingException { destroySubcontext(name.toString()); } - public void destroySubcontext(final String name) throws NamingException - { + public void destroySubcontext(final String name) throws NamingException { map.remove(trimSlashes(name)); } - public Context createSubcontext(final Name name) throws NamingException - { + public Context createSubcontext(final Name name) throws NamingException { throw new UnsupportedOperationException(); } - public Context createSubcontext(String name) throws NamingException - { + public Context createSubcontext(String name) throws NamingException { name = trimSlashes(name); - if (map.get(name) != null) - { + if (map.get(name) != null) { throw new NameAlreadyBoundException(name); } InVMContext c = new InVMContext(getNameInNamespace()); @@ -227,59 +194,48 @@ public class InVMContext implements Context, Serializable return c; } - public Object lookupLink(final Name name) throws NamingException - { + public Object lookupLink(final Name name) throws NamingException { throw new UnsupportedOperationException(); } - public Object lookupLink(final String name) throws NamingException - { + public Object lookupLink(final String name) throws NamingException { throw new UnsupportedOperationException(); } - public NameParser getNameParser(final Name name) throws NamingException - { + public NameParser getNameParser(final Name name) throws NamingException { return getNameParser(name.toString()); } - public NameParser getNameParser(final String name) throws NamingException - { + public NameParser getNameParser(final String name) throws NamingException { return parser; } - public Name composeName(final Name name, final Name prefix) throws NamingException - { + public Name composeName(final Name name, final Name prefix) throws NamingException { throw new UnsupportedOperationException(); } - public String composeName(final String name, final String prefix) throws NamingException - { + public String composeName(final String name, final String prefix) throws NamingException { throw new UnsupportedOperationException(); } - public Object addToEnvironment(final String propName, final Object propVal) throws NamingException - { + public Object addToEnvironment(final String propName, final Object propVal) throws NamingException { throw new UnsupportedOperationException(); } - public Object removeFromEnvironment(final String propName) throws NamingException - { + public Object removeFromEnvironment(final String propName) throws NamingException { throw new UnsupportedOperationException(); } - public Hashtable getEnvironment() throws NamingException - { + public Hashtable getEnvironment() throws NamingException { Hashtable env = new Hashtable(); env.put("java.naming.factory.initial", InVMInitialContextFactory.class.getCanonicalName()); return env; } - public void close() throws NamingException - { + public void close() throws NamingException { } - public String getNameInNamespace() throws NamingException - { + public String getNameInNamespace() throws NamingException { return nameInNamespace; } @@ -291,23 +247,18 @@ public class InVMContext implements Context, Serializable // Private ------------------------------------------------------- - private String trimSlashes(String s) - { + private String trimSlashes(String s) { int i = 0; - while (true) - { - if (i == s.length() || s.charAt(i) != '/') - { + while (true) { + if (i == s.length() || s.charAt(i) != '/') { break; } i++; } s = s.substring(i); i = s.length() - 1; - while (true) - { - if (i == -1 || s.charAt(i) != '/') - { + while (true) { + if (i == -1 || s.charAt(i) != '/') { break; } i--; @@ -315,20 +266,17 @@ public class InVMContext implements Context, Serializable return s.substring(0, i + 1); } - private void internalBind(String name, final Object obj, final boolean rebind) throws NamingException - { + private void internalBind(String name, final Object obj, final boolean rebind) throws NamingException { InVMContext.log.debug("Binding " + name + " obj " + obj + " rebind " + rebind); name = trimSlashes(name); int i = name.lastIndexOf("/"); InVMContext c = this; - if (i != -1) - { + if (i != -1) { String path = name.substring(0, i); - c = (InVMContext)lookup(path); + c = (InVMContext) lookup(path); } name = name.substring(i + 1); - if (!rebind && c.map.get(name) != null) - { + if (!rebind && c.map.get(name) != null) { throw new NameAlreadyBoundException(name); } c.map.put(name, obj); @@ -336,37 +284,31 @@ public class InVMContext implements Context, Serializable // Inner classes ------------------------------------------------- - private static final class NamingEnumerationImpl implements NamingEnumeration - { + private static final class NamingEnumerationImpl implements NamingEnumeration { + private final Iterator iterator; - NamingEnumerationImpl(final Iterator bindingIterator) - { + NamingEnumerationImpl(final Iterator bindingIterator) { iterator = bindingIterator; } - public void close() throws NamingException - { + public void close() throws NamingException { throw new UnsupportedOperationException(); } - public boolean hasMore() throws NamingException - { + public boolean hasMore() throws NamingException { return iterator.hasNext(); } - public Binding next() throws NamingException - { + public Binding next() throws NamingException { return iterator.next(); } - public boolean hasMoreElements() - { + public boolean hasMoreElements() { return iterator.hasNext(); } - public Binding nextElement() - { + public Binding nextElement() { return iterator.next(); } } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/InVMInitialContextFactory.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/InVMInitialContextFactory.java index 5286b3f13d..e323f46942 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/InVMInitialContextFactory.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/InVMInitialContextFactory.java @@ -27,29 +27,25 @@ import javax.naming.spi.InitialContextFactory; /** * An in-VM JNDI InitialContextFactory. Lightweight JNDI implementation used for testing. */ -public class InVMInitialContextFactory implements InitialContextFactory -{ +public class InVMInitialContextFactory implements InitialContextFactory { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- private static Map initialContexts; - static - { + static { InVMInitialContextFactory.reset(); } - public static Hashtable getJNDIEnvironment() - { + public static Hashtable getJNDIEnvironment() { return InVMInitialContextFactory.getJNDIEnvironment(0); } /** * @return the JNDI environment to use to get this InitialContextFactory. */ - public static Hashtable getJNDIEnvironment(final int serverIndex) - { + public static Hashtable getJNDIEnvironment(final int serverIndex) { Hashtable env = new Hashtable(); env.put("java.naming.factory.initial", "org.apache.activemq.artemis.jms.tests.tools.container.InVMInitialContextFactory"); env.put(Constants.SERVER_INDEX_PROPERTY_NAME, Integer.toString(serverIndex)); @@ -62,26 +58,21 @@ public class InVMInitialContextFactory implements InitialContextFactory // Public -------------------------------------------------------- - public Context getInitialContext(final Hashtable environment) throws NamingException - { + public Context getInitialContext(final Hashtable environment) throws NamingException { // try first in the environment passed as argument ... - String s = (String)environment.get(Constants.SERVER_INDEX_PROPERTY_NAME); + String s = (String) environment.get(Constants.SERVER_INDEX_PROPERTY_NAME); - if (s == null) - { + if (s == null) { // ... then in the global environment s = System.getProperty(Constants.SERVER_INDEX_PROPERTY_NAME); - if (s == null) - { + if (s == null) { // try the thread name String tName = Thread.currentThread().getName(); - if (tName.contains("server")) - { + if (tName.contains("server")) { s = tName.substring(6); } - if (s == null) - { + if (s == null) { throw new NamingException("Cannot figure out server index!"); } } @@ -89,26 +80,22 @@ public class InVMInitialContextFactory implements InitialContextFactory int serverIndex; - try - { + try { serverIndex = Integer.parseInt(s); } - catch (Exception e) - { + catch (Exception e) { throw new NamingException("Failure parsing \"" + Constants.SERVER_INDEX_PROPERTY_NAME + - "\". " + - s + - " is not an integer"); + "\". " + + s + + " is not an integer"); } // Note! This MUST be synchronized - synchronized (InVMInitialContextFactory.initialContexts) - { + synchronized (InVMInitialContextFactory.initialContexts) { - InVMContext ic = (InVMContext)InVMInitialContextFactory.initialContexts.get(new Integer(serverIndex)); + InVMContext ic = (InVMContext) InVMInitialContextFactory.initialContexts.get(new Integer(serverIndex)); - if (ic == null) - { + if (ic == null) { ic = new InVMContext(s); ic.bind("java:/", new InVMContext(s)); InVMInitialContextFactory.initialContexts.put(new Integer(serverIndex), ic); @@ -118,8 +105,7 @@ public class InVMInitialContextFactory implements InitialContextFactory } } - public static void reset() - { + public static void reset() { InVMInitialContextFactory.initialContexts = new HashMap(); } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/InVMInitialContextFactoryBuilder.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/InVMInitialContextFactoryBuilder.java index 067c7119b8..b61639adc2 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/InVMInitialContextFactoryBuilder.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/InVMInitialContextFactoryBuilder.java @@ -24,8 +24,7 @@ import javax.naming.NamingException; import javax.naming.spi.InitialContextFactory; import javax.naming.spi.InitialContextFactoryBuilder; -public class InVMInitialContextFactoryBuilder implements InitialContextFactoryBuilder -{ +public class InVMInitialContextFactoryBuilder implements InitialContextFactoryBuilder { // Constants ------------------------------------------------------------------------------------ private static final JmsTestLogger log = JmsTestLogger.LOGGER; @@ -36,55 +35,44 @@ public class InVMInitialContextFactoryBuilder implements InitialContextFactoryBu // Constructors --------------------------------------------------------------------------------- - public InVMInitialContextFactoryBuilder() - { + public InVMInitialContextFactoryBuilder() { } // InitialContextFactoryBuilder implementation -------------------------------------------------- - public InitialContextFactory createInitialContextFactory(final Hashtable environment) throws NamingException - { + public InitialContextFactory createInitialContextFactory(final Hashtable environment) throws NamingException { InitialContextFactory icf = null; - if (environment != null) - { - String icfName = (String)environment.get("java.naming.factory.initial"); + if (environment != null) { + String icfName = (String) environment.get("java.naming.factory.initial"); - if (icfName != null) - { + if (icfName != null) { Class c = null; - try - { + try { c = Class.forName(icfName); } - catch (ClassNotFoundException e) - { + catch (ClassNotFoundException e) { InVMInitialContextFactoryBuilder.log.error("\"" + icfName + "\" cannot be loaded", e); throw new NamingException("\"" + icfName + "\" cannot be loaded"); } - try - { - icf = (InitialContextFactory)c.newInstance(); + try { + icf = (InitialContextFactory) c.newInstance(); } - catch (InstantiationException e) - { + catch (InstantiationException e) { InVMInitialContextFactoryBuilder.log.error(c.getName() + " cannot be instantiated", e); throw new NamingException(c.getName() + " cannot be instantiated"); } - catch (IllegalAccessException e) - { - InVMInitialContextFactoryBuilder.log.error(c.getName() + " instantiation generated an IllegalAccessException", - e); + catch (IllegalAccessException e) { + InVMInitialContextFactoryBuilder.log.error(c.getName() + " instantiation generated an IllegalAccessException", e); throw new NamingException(c.getName() + " instantiation generated an IllegalAccessException"); } } } - if (icf == null) - { + if (icf == null) { icf = new InVMInitialContextFactory(); } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/InVMNameParser.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/InVMNameParser.java index 62f0a3b563..2fe13bf3eb 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/InVMNameParser.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/InVMNameParser.java @@ -24,8 +24,7 @@ import javax.naming.Name; import javax.naming.NameParser; import javax.naming.NamingException; -public class InVMNameParser implements NameParser, Serializable -{ +public class InVMNameParser implements NameParser, Serializable { // Constants ----------------------------------------------------- private static final long serialVersionUID = 2925203703371001031L; @@ -34,8 +33,7 @@ public class InVMNameParser implements NameParser, Serializable static Properties syntax; - static - { + static { InVMNameParser.syntax = new Properties(); InVMNameParser.syntax.put("jndi.syntax.direction", "left_to_right"); InVMNameParser.syntax.put("jndi.syntax.ignorecase", "false"); @@ -48,13 +46,11 @@ public class InVMNameParser implements NameParser, Serializable // Public -------------------------------------------------------- - public static Properties getSyntax() - { + public static Properties getSyntax() { return InVMNameParser.syntax; } - public Name parse(final String name) throws NamingException - { + public Name parse(final String name) throws NamingException { return new CompoundName(name, InVMNameParser.syntax); } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/LocalTestServer.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/LocalTestServer.java index 77b19a26d1..67f744a1b0 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/LocalTestServer.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/LocalTestServer.java @@ -47,8 +47,7 @@ import org.apache.activemq.artemis.jms.server.impl.JMSServerManagerImpl; import org.apache.activemq.artemis.jms.tests.JmsTestLogger; import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManagerImpl; -public class LocalTestServer implements Server, Runnable -{ +public class LocalTestServer implements Server, Runnable { // Constants ------------------------------------------------------------------------------------ private boolean started = false; @@ -58,13 +57,11 @@ public class LocalTestServer implements Server, Runnable // Static --------------------------------------------------------------------------------------- - public static void setEnvironmentServerIndex(final int serverIndex) - { + public static void setEnvironmentServerIndex(final int serverIndex) { System.setProperty(Constants.SERVER_INDEX_PROPERTY_NAME, Integer.toString(serverIndex)); } - public static void clearEnvironmentServerIndex() - { + public static void clearEnvironmentServerIndex() { System.getProperty(Constants.SERVER_INDEX_PROPERTY_NAME, null); } @@ -74,8 +71,7 @@ public class LocalTestServer implements Server, Runnable // Constructors --------------------------------------------------------------------------------- - public LocalTestServer() - { + public LocalTestServer() { super(); serverIndex = 0; @@ -83,21 +79,17 @@ public class LocalTestServer implements Server, Runnable // Server implementation ------------------------------------------------------------------------ - public int getServerID() - { + public int getServerID() { return serverIndex; } public synchronized void start(final HashMap configuration, - final boolean clearJournal) throws Exception - { - if (isStarted()) - { + final boolean clearJournal) throws Exception { + if (isStarted()) { return; } - if (clearJournal) - { + if (clearJournal) { // Delete the Journal environment File dir = new File("target/data"); @@ -125,16 +117,12 @@ public class LocalTestServer implements Server, Runnable } - private static boolean deleteDirectory(final File directory) - { - if (directory.isDirectory()) - { + private static boolean deleteDirectory(final File directory) { + if (directory.isDirectory()) { String[] files = directory.list(); - for (int j = 0; j < files.length; j++) - { - if (!LocalTestServer.deleteDirectory(new File(directory, files[j]))) - { + for (int j = 0; j < files.length; j++) { + if (!LocalTestServer.deleteDirectory(new File(directory, files[j]))) { return false; } } @@ -143,8 +131,7 @@ public class LocalTestServer implements Server, Runnable return directory.delete(); } - public synchronized boolean stop() throws Exception - { + public synchronized boolean stop() throws Exception { jmsServerManager.stop(); started = false; unbindAll(); @@ -152,45 +139,36 @@ public class LocalTestServer implements Server, Runnable return true; } - public void ping() throws Exception - { - if (!isStarted()) - { + public void ping() throws Exception { + if (!isStarted()) { throw new RuntimeException("ok"); } } - public synchronized void kill() throws Exception - { + public synchronized void kill() throws Exception { stop(); } - public synchronized boolean isStarted() throws Exception - { + public synchronized boolean isStarted() throws Exception { return started; } - public synchronized void startServerPeer() throws Exception - { + public synchronized void startServerPeer() throws Exception { System.setProperty(Constants.SERVER_INDEX_PROPERTY_NAME, "" + getServerID()); getActiveMQServer().start(); } - public synchronized void stopServerPeer() throws Exception - { + public synchronized void stopServerPeer() throws Exception { System.setProperty(Constants.SERVER_INDEX_PROPERTY_NAME, "" + getServerID()); getActiveMQServer().stop(); // also unbind everything unbindAll(); } - private void unbindAll() throws Exception - { + private void unbindAll() throws Exception { Collection> bindings = allBindings.values(); - for (List binding : bindings) - { - for (String s : binding) - { + for (List binding : bindings) { + for (String s : binding) { getInitialContext().unbind(s); } } @@ -199,50 +177,45 @@ public class LocalTestServer implements Server, Runnable /** * Only for in-VM use! */ - public ActiveMQServer getServerPeer() - { + public ActiveMQServer getServerPeer() { return getActiveMQServer(); } - public void destroyQueue(final String name, final String jndiName) throws Exception - { + public void destroyQueue(final String name, final String jndiName) throws Exception { getJMSServerManager().destroyQueue(name); } - public void destroyTopic(final String name, final String jndiName) throws Exception - { + public void destroyTopic(final String name, final String jndiName) throws Exception { getJMSServerManager().destroyTopic(name); } - public void createQueue(final String name, final String jndiName) throws Exception - { + public void createQueue(final String name, final String jndiName) throws Exception { getJMSServerManager().createQueue(true, name, null, true, "/queue/" + (jndiName != null ? jndiName : name)); } - public void createTopic(final String name, final String jndiName) throws Exception - { + public void createTopic(final String name, final String jndiName) throws Exception { getJMSServerManager().createTopic(true, name, "/topic/" + (jndiName != null ? jndiName : name)); } - public void deployConnectionFactory(final String clientId, final String objectName, final String ... jndiBindings) throws Exception - { + public void deployConnectionFactory(final String clientId, + final String objectName, + final String... jndiBindings) throws Exception { deployConnectionFactory(clientId, JMSFactoryType.CF, objectName, -1, -1, -1, -1, false, false, -1, false, jndiBindings); } public void deployConnectionFactory(final String objectName, final int consumerWindowSize, - final String ... jndiBindings) throws Exception - { + final String... jndiBindings) throws Exception { deployConnectionFactory(null, JMSFactoryType.CF, objectName, consumerWindowSize, -1, -1, -1, false, false, -1, false, jndiBindings); } - public void deployConnectionFactory(final String objectName, final String ... jndiBindings) throws Exception - { + public void deployConnectionFactory(final String objectName, final String... jndiBindings) throws Exception { deployConnectionFactory(null, JMSFactoryType.CF, objectName, -1, -1, -1, -1, false, false, -1, false, jndiBindings); } - public void deployConnectionFactory(final String objectName, JMSFactoryType type, final String ... jndiBindings) throws Exception - { + public void deployConnectionFactory(final String objectName, + JMSFactoryType type, + final String... jndiBindings) throws Exception { deployConnectionFactory(null, type, objectName, -1, -1, -1, -1, false, false, -1, false, jndiBindings); } @@ -251,39 +224,15 @@ public class LocalTestServer implements Server, Runnable final int defaultTempQueueFullSize, final int defaultTempQueuePageSize, final int defaultTempQueueDownCacheSize, - final String ... jndiBindings) throws Exception - { - this.deployConnectionFactory(null, - JMSFactoryType.CF, - objectName, - prefetchSize, - defaultTempQueueFullSize, - defaultTempQueuePageSize, - defaultTempQueueDownCacheSize, - false, - false, - -1, - false, - jndiBindings); + final String... jndiBindings) throws Exception { + this.deployConnectionFactory(null, JMSFactoryType.CF, objectName, prefetchSize, defaultTempQueueFullSize, defaultTempQueuePageSize, defaultTempQueueDownCacheSize, false, false, -1, false, jndiBindings); } public void deployConnectionFactory(final String objectName, final boolean supportsFailover, final boolean supportsLoadBalancing, - final String ... jndiBindings) throws Exception - { - this.deployConnectionFactory(null, - JMSFactoryType.CF, - objectName, - -1, - -1, - -1, - -1, - supportsFailover, - supportsLoadBalancing, - -1, - false, - jndiBindings); + final String... jndiBindings) throws Exception { + this.deployConnectionFactory(null, JMSFactoryType.CF, objectName, -1, -1, -1, -1, supportsFailover, supportsLoadBalancing, -1, false, jndiBindings); } public void deployConnectionFactory(final String clientId, @@ -297,65 +246,28 @@ public class LocalTestServer implements Server, Runnable final boolean supportsLoadBalancing, final int dupsOkBatchSize, final boolean blockOnAcknowledge, - final String ... jndiBindings) throws Exception - { + final String... jndiBindings) throws Exception { List connectorConfigs = new ArrayList(); connectorConfigs.add(new TransportConfiguration(NettyConnectorFactory.class.getName())); ArrayList connectors = new ArrayList(); connectors.add("netty"); - getJMSServerManager().createConnectionFactory(objectName, - false, - type, - connectors, - clientId, - ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, - ActiveMQClient.DEFAULT_CONNECTION_TTL, - ActiveMQClient.DEFAULT_CALL_TIMEOUT, - ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, - ActiveMQClient.DEFAULT_CACHE_LARGE_MESSAGE_CLIENT, - ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, - ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES, - prefetchSize, - ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, - ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_WINDOW_SIZE, - ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, - blockOnAcknowledge, - true, - true, - ActiveMQClient.DEFAULT_AUTO_GROUP, - ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, - ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, - ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, - dupsOkBatchSize, - ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, - ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, - ActiveMQClient.DEFAULT_RETRY_INTERVAL, - ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, - ActiveMQClient.DEFAULT_MAX_RETRY_INTERVAL, - ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS, - ActiveMQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION, - null, - jndiBindings); + getJMSServerManager().createConnectionFactory(objectName, false, type, connectors, clientId, ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, ActiveMQClient.DEFAULT_CONNECTION_TTL, ActiveMQClient.DEFAULT_CALL_TIMEOUT, ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, ActiveMQClient.DEFAULT_CACHE_LARGE_MESSAGE_CLIENT, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES, prefetchSize, ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, blockOnAcknowledge, true, true, ActiveMQClient.DEFAULT_AUTO_GROUP, ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, dupsOkBatchSize, ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_RETRY_INTERVAL, ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, ActiveMQClient.DEFAULT_MAX_RETRY_INTERVAL, ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS, ActiveMQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION, null, jndiBindings); } - public void undeployConnectionFactory(final String objectName) throws Exception - { + public void undeployConnectionFactory(final String objectName) throws Exception { getJMSServerManager().destroyConnectionFactory(objectName); } - public void configureSecurityForDestination(final String destName, final boolean isQueue, final Set roles) throws Exception - { + public void configureSecurityForDestination(final String destName, + final boolean isQueue, + final Set roles) throws Exception { String destination = (isQueue ? "jms.queue." : "jms.topic.") + destName; - if (roles != null) - { + if (roles != null) { getActiveMQServer().getSecurityRepository().addMatch(destination, roles); } - else - { + else { getActiveMQServer().getSecurityRepository().removeMatch(destination); } } @@ -368,88 +280,67 @@ public class LocalTestServer implements Server, Runnable // Private -------------------------------------------------------------------------------------- - public ActiveMQServer getActiveMQServer() - { + public ActiveMQServer getActiveMQServer() { return jmsServerManager.getActiveMQServer(); } - public JMSServerManager getJMSServerManager() - { + public JMSServerManager getJMSServerManager() { return jmsServerManager; } - public InitialContext getInitialContext() throws Exception - { + public InitialContext getInitialContext() throws Exception { Properties props = new Properties(); - props.setProperty("java.naming.factory.initial", - "org.apache.activemq.artemis.jms.tests.tools.container.InVMInitialContextFactory"); + props.setProperty("java.naming.factory.initial", "org.apache.activemq.artemis.jms.tests.tools.container.InVMInitialContextFactory"); props.setProperty(Constants.SERVER_INDEX_PROPERTY_NAME, "" + getServerID()); return new InitialContext(props); } - public void run() - { - // bootstrap.run(); + public void run() { + // bootstrap.run(); started = true; } @Override - public Long getMessageCountForQueue(final String queueName) throws Exception - { - JMSQueueControl queue = (JMSQueueControl) getActiveMQServer().getManagementService() - .getResource(ResourceNames.JMS_QUEUE + queueName); - if (queue != null) - { + public Long getMessageCountForQueue(final String queueName) throws Exception { + JMSQueueControl queue = (JMSQueueControl) getActiveMQServer().getManagementService().getResource(ResourceNames.JMS_QUEUE + queueName); + if (queue != null) { queue.flushExecutor(); return queue.getMessageCount(); } - else - { + else { return -1L; } } - public void removeAllMessages(final String destination, final boolean isQueue) throws Exception - { - if (isQueue) - { - JMSQueueControl queue = (JMSQueueControl) getActiveMQServer().getManagementService() - .getResource(ResourceNames.JMS_QUEUE + destination); + public void removeAllMessages(final String destination, final boolean isQueue) throws Exception { + if (isQueue) { + JMSQueueControl queue = (JMSQueueControl) getActiveMQServer().getManagementService().getResource(ResourceNames.JMS_QUEUE + destination); queue.removeMessages(null); } - else - { - TopicControl topic = (TopicControl) getActiveMQServer().getManagementService() - .getResource(ResourceNames.JMS_TOPIC + destination); + else { + TopicControl topic = (TopicControl) getActiveMQServer().getManagementService().getResource(ResourceNames.JMS_TOPIC + destination); topic.removeMessages(null); } } - public List listAllSubscribersForTopic(final String s) throws Exception - { + public List listAllSubscribersForTopic(final String s) throws Exception { ObjectName objectName = ObjectNameBuilder.DEFAULT.getJMSTopicObjectName(s); - TopicControl topic = MBeanServerInvocationHandler.newProxyInstance(ManagementFactory.getPlatformMBeanServer(), - objectName, - TopicControl.class, - false); + TopicControl topic = MBeanServerInvocationHandler.newProxyInstance(ManagementFactory.getPlatformMBeanServer(), objectName, TopicControl.class, false); Object[] subInfos = topic.listAllSubscriptions(); List subs = new ArrayList(); - for (Object o : subInfos) - { - Object[] data = (Object[])o; - subs.add((String)data[2]); + for (Object o : subInfos) { + Object[] data = (Object[]) o; + subs.add((String) data[2]); } return subs; } - public Set getSecurityConfig() throws Exception - { + public Set getSecurityConfig() throws Exception { return getActiveMQServer().getSecurityRepository().getMatch("*"); } - public void setSecurityConfig(final Set defConfig) throws Exception - { + public void setSecurityConfig(final Set defConfig) throws Exception { getActiveMQServer().getSecurityRepository().removeMatch("#"); getActiveMQServer().getSecurityRepository().addMatch("#", defConfig); } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/NonSerializableFactory.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/NonSerializableFactory.java index 0d68a586c7..d17133132b 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/NonSerializableFactory.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/NonSerializableFactory.java @@ -31,74 +31,71 @@ import javax.naming.spi.ObjectFactory; /** * used by the default context when running in embedded local configuration */ -public final class NonSerializableFactory implements ObjectFactory -{ +public final class NonSerializableFactory implements ObjectFactory { - public NonSerializableFactory() - { + public NonSerializableFactory() { } -// public static void unbind(final Context ctx, final String strName) throws NamingException -// { -// Name name = ctx.getNameParser("").parse(strName); -// int size = name.size(); -// String atom = name.get(size - 1); -// Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1)); -// String key = new StringBuilder().append(parentCtx.getNameInNamespace()).append("/").append(atom).toString(); -// NonSerializableFactory.getWrapperMap().remove(key); -// Util.unbind(ctx, strName); -// } -// -// public static void rebind(final Context ctx, final String strName, final Object value) throws NamingException -// { -// Name name = ctx.getNameParser("").parse(strName); -// int size = name.size(); -// String atom = name.get(size - 1); -// Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1)); -// String key = new StringBuilder().append(parentCtx.getNameInNamespace()).append("/").append(atom).toString(); -// NonSerializableFactory.getWrapperMap().put(key, value); -// String className = value.getClass().getName(); -// String factory = NonSerializableFactory.class.getName(); -// StringRefAddr addr = new StringRefAddr("nns", key); -// Reference memoryRef = new Reference(className, addr, factory, null); -// parentCtx.rebind(atom, memoryRef); -// } -// -// public static void bind(final Context ctx, final String strName, final Object value) throws NamingException -// { -// Name name = ctx.getNameParser("").parse(strName); -// int size = name.size(); -// String atom = name.get(size - 1); -// Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1)); -// String key = new StringBuilder().append(parentCtx.getNameInNamespace()).append("/").append(atom).toString(); -// NonSerializableFactory.getWrapperMap().put(key, value); -// String className = value.getClass().getName(); -// String factory = NonSerializableFactory.class.getName(); -// StringRefAddr addr = new StringRefAddr("nns", key); -// Reference memoryRef = new Reference(className, addr, factory, null); -// -// parentCtx.bind(atom, memoryRef); -// } + // public static void unbind(final Context ctx, final String strName) throws NamingException + // { + // Name name = ctx.getNameParser("").parse(strName); + // int size = name.size(); + // String atom = name.get(size - 1); + // Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1)); + // String key = new StringBuilder().append(parentCtx.getNameInNamespace()).append("/").append(atom).toString(); + // NonSerializableFactory.getWrapperMap().remove(key); + // Util.unbind(ctx, strName); + // } + // + // public static void rebind(final Context ctx, final String strName, final Object value) throws NamingException + // { + // Name name = ctx.getNameParser("").parse(strName); + // int size = name.size(); + // String atom = name.get(size - 1); + // Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1)); + // String key = new StringBuilder().append(parentCtx.getNameInNamespace()).append("/").append(atom).toString(); + // NonSerializableFactory.getWrapperMap().put(key, value); + // String className = value.getClass().getName(); + // String factory = NonSerializableFactory.class.getName(); + // StringRefAddr addr = new StringRefAddr("nns", key); + // Reference memoryRef = new Reference(className, addr, factory, null); + // parentCtx.rebind(atom, memoryRef); + // } + // + // public static void bind(final Context ctx, final String strName, final Object value) throws NamingException + // { + // Name name = ctx.getNameParser("").parse(strName); + // int size = name.size(); + // String atom = name.get(size - 1); + // Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1)); + // String key = new StringBuilder().append(parentCtx.getNameInNamespace()).append("/").append(atom).toString(); + // NonSerializableFactory.getWrapperMap().put(key, value); + // String className = value.getClass().getName(); + // String factory = NonSerializableFactory.class.getName(); + // StringRefAddr addr = new StringRefAddr("nns", key); + // Reference memoryRef = new Reference(className, addr, factory, null); + // + // parentCtx.bind(atom, memoryRef); + // } - public static Object lookup(final String name) throws NamingException - { - if (NonSerializableFactory.getWrapperMap().get(name) == null) - { + public static Object lookup(final String name) throws NamingException { + if (NonSerializableFactory.getWrapperMap().get(name) == null) { throw new NamingException(name + " not found"); } return NonSerializableFactory.getWrapperMap().get(name); } - public Object getObjectInstance(final Object obj, final Name name, final Context nameCtx, final Hashtable env) throws Exception - { - Reference ref = (Reference)obj; + public Object getObjectInstance(final Object obj, + final Name name, + final Context nameCtx, + final Hashtable env) throws Exception { + Reference ref = (Reference) obj; RefAddr addr = ref.get("nns"); - String key = (String)addr.getContent(); + String key = (String) addr.getContent(); return NonSerializableFactory.getWrapperMap().get(key); } - public static Map getWrapperMap() - { + public static Map getWrapperMap() { return NonSerializableFactory.wrapperMap; } diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/Server.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/Server.java index b6ed8a8b3d..a006365c8c 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/Server.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/tools/container/Server.java @@ -30,8 +30,8 @@ import org.apache.activemq.artemis.jms.server.JMSServerManager; /** * The remote interface exposed by TestServer. */ -public interface Server extends Remote -{ +public interface Server extends Remote { + int getServerID() throws Exception; /** @@ -158,18 +158,13 @@ public interface Server extends Remote boolean supportsLoadBalancing, final String... jndiBindings) throws Exception; - void deployConnectionFactory(String clientID, String objectName, - final String... jndiBindings) throws Exception; + void deployConnectionFactory(String clientID, String objectName, final String... jndiBindings) throws Exception; - void deployConnectionFactory(String objectName, int prefetchSize, - final String... jndiBindings) throws Exception; + void deployConnectionFactory(String objectName, int prefetchSize, final String... jndiBindings) throws Exception; - void deployConnectionFactory(String objectName, - final String... jndiBindings) throws Exception; + void deployConnectionFactory(String objectName, final String... jndiBindings) throws Exception; - void deployConnectionFactory(String objectName, - JMSFactoryType type, - final String... jndiBindings) throws Exception; + void deployConnectionFactory(String objectName, JMSFactoryType type, final String... jndiBindings) throws Exception; void undeployConnectionFactory(String objectName) throws Exception; diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/util/JNDIUtilTest.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/util/JNDIUtilTest.java index 59059e8ce4..184402e3f3 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/util/JNDIUtilTest.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/util/JNDIUtilTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.jms.tests.util; + import org.junit.Before; import org.junit.Test; @@ -25,8 +26,7 @@ import javax.naming.NameNotFoundException; import org.apache.activemq.artemis.jms.tests.ActiveMQServerTestCase; import org.apache.activemq.artemis.utils.JNDIUtil; -public class JNDIUtilTest extends ActiveMQServerTestCase -{ +public class JNDIUtilTest extends ActiveMQServerTestCase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -40,59 +40,50 @@ public class JNDIUtilTest extends ActiveMQServerTestCase // Public -------------------------------------------------------- @Test - public void testRebind_1() throws Exception - { - try - { + public void testRebind_1() throws Exception { + try { ic.lookup("/nosuchsubcontext"); ProxyAssertSupport.fail("the name is not supposed to be there"); } - catch (NameNotFoundException e) - { + catch (NameNotFoundException e) { // OK } JNDIUtil.rebind(ic, "/nosuchsubcontext/sub1/sub2/sub3/name", new Integer(7)); - ProxyAssertSupport.assertEquals(7, ((Integer)ic.lookup("/nosuchsubcontext/sub1/sub2/sub3/name")).intValue()); + ProxyAssertSupport.assertEquals(7, ((Integer) ic.lookup("/nosuchsubcontext/sub1/sub2/sub3/name")).intValue()); } @Test - public void testRebind_2() throws Exception - { - try - { + public void testRebind_2() throws Exception { + try { ic.lookup("/doesnotexistyet"); ProxyAssertSupport.fail("the name is not supposed to be there"); } - catch (NameNotFoundException e) - { + catch (NameNotFoundException e) { // OK } JNDIUtil.rebind(ic, "/doesnotexistyet", new Integer(8)); - ProxyAssertSupport.assertEquals(8, ((Integer)ic.lookup("/doesnotexistyet")).intValue()); + ProxyAssertSupport.assertEquals(8, ((Integer) ic.lookup("/doesnotexistyet")).intValue()); ic.unbind("doesnotexistyet"); } @Test - public void testRebind_3() throws Exception - { - try - { + public void testRebind_3() throws Exception { + try { ic.lookup("doesnotexistyet"); ProxyAssertSupport.fail("the name is not supposed to be there"); } - catch (NameNotFoundException e) - { + catch (NameNotFoundException e) { // OK } JNDIUtil.rebind(ic, "doesnotexistyet", new Integer(9)); - ProxyAssertSupport.assertEquals(9, ((Integer)ic.lookup("/doesnotexistyet")).intValue()); + ProxyAssertSupport.assertEquals(9, ((Integer) ic.lookup("/doesnotexistyet")).intValue()); ic.unbind("doesnotexistyet"); } @@ -103,8 +94,7 @@ public class JNDIUtilTest extends ActiveMQServerTestCase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); // ServerManagement.start("none"); diff --git a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/util/ProxyAssertSupport.java b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/util/ProxyAssertSupport.java index 4d7c71586c..50b1d088b3 100644 --- a/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/util/ProxyAssertSupport.java +++ b/tests/jms-tests/src/test/java/org/apache/activemq/artemis/jms/tests/util/ProxyAssertSupport.java @@ -22,84 +22,65 @@ import org.junit.Assert; /** * This class will proxy any JUnit assertions and send then to our log outputs. */ -public class ProxyAssertSupport -{ +public class ProxyAssertSupport { + private static JmsTestLogger log = JmsTestLogger.LOGGER; - public static void assertTrue(final java.lang.String string, final boolean b) - { - try - { + public static void assertTrue(final java.lang.String string, final boolean b) { + try { Assert.assertTrue(string, b); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertTrue(final boolean b) - { - try - { + public static void assertTrue(final boolean b) { + try { Assert.assertTrue(b); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertFalse(final java.lang.String string, final boolean b) - { - try - { + public static void assertFalse(final java.lang.String string, final boolean b) { + try { Assert.assertFalse(string, b); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertFalse(final boolean b) - { - try - { + public static void assertFalse(final boolean b) { + try { Assert.assertFalse(b); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void fail(final java.lang.String string) - - { - try - { + public static void fail(final java.lang.String string) { + try { Assert.fail(string); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void fail() - { - try - { + public static void fail() { + try { Assert.fail(); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } @@ -107,27 +88,21 @@ public class ProxyAssertSupport public static void assertEquals(final java.lang.String string, final java.lang.Object object, - final java.lang.Object object1) - { - try - { + final java.lang.Object object1) { + try { Assert.assertEquals(string, object, object1); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertEquals(final java.lang.Object object, final java.lang.Object object1) - { - try - { + public static void assertEquals(final java.lang.Object object, final java.lang.Object object1) { + try { Assert.assertEquals(object, object1); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } @@ -135,287 +110,221 @@ public class ProxyAssertSupport public static void assertEquals(final java.lang.String string, final java.lang.String string1, - final java.lang.String string2) - { - try - { + final java.lang.String string2) { + try { Assert.assertEquals(string, string1, string2); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertEquals(final java.lang.String string, final java.lang.String string1) - { - try - { + public static void assertEquals(final java.lang.String string, final java.lang.String string1) { + try { Assert.assertEquals(string, string1); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertEquals(final java.lang.String string, final double v, final double v1, final double v2) - { - try - { + public static void assertEquals(final java.lang.String string, final double v, final double v1, final double v2) { + try { Assert.assertEquals(string, v, v1, v2); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertEquals(final double v, final double v1, final double v2) - { - try - { + public static void assertEquals(final double v, final double v1, final double v2) { + try { Assert.assertEquals(v, v1, v2); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertEquals(final java.lang.String string, final float v, final float v1, final float v2) - { - try - { + public static void assertEquals(final java.lang.String string, final float v, final float v1, final float v2) { + try { Assert.assertEquals(string, v, v1, v2); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertEquals(final float v, final float v1, final float v2) - { - try - { + public static void assertEquals(final float v, final float v1, final float v2) { + try { Assert.assertEquals(v, v1, v2); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertEquals(final java.lang.String string, final long l, final long l1) - { - try - { + public static void assertEquals(final java.lang.String string, final long l, final long l1) { + try { Assert.assertEquals(string, l, l1); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertEquals(final long l, final long l1) - { - try - { + public static void assertEquals(final long l, final long l1) { + try { Assert.assertEquals(l, l1); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertEquals(final java.lang.String string, final boolean b, final boolean b1) - { - try - { + public static void assertEquals(final java.lang.String string, final boolean b, final boolean b1) { + try { Assert.assertEquals(string, b, b1); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertEquals(final boolean b, final boolean b1) - { - try - { + public static void assertEquals(final boolean b, final boolean b1) { + try { Assert.assertEquals(b, b1); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertEquals(final java.lang.String string, final byte b, final byte b1) - { - try - { + public static void assertEquals(final java.lang.String string, final byte b, final byte b1) { + try { Assert.assertEquals(string, b, b1); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertEquals(final byte b, final byte b1) - { - try - { + public static void assertEquals(final byte b, final byte b1) { + try { Assert.assertEquals(b, b1); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertEquals(final java.lang.String string, final char c, final char c1) - { - try - { + public static void assertEquals(final java.lang.String string, final char c, final char c1) { + try { Assert.assertEquals(string, c, c1); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertEquals(final char c, final char c1) - { - try - { + public static void assertEquals(final char c, final char c1) { + try { Assert.assertEquals(c, c1); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertEquals(final java.lang.String string, final short i, final short i1) - { - try - { + public static void assertEquals(final java.lang.String string, final short i, final short i1) { + try { Assert.assertEquals(string, i, i1); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertEquals(final short i, final short i1) - { - try - { + public static void assertEquals(final short i, final short i1) { + try { Assert.assertEquals(i, i1); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertEquals(final java.lang.String string, final int i, final int i1) - { - try - { + public static void assertEquals(final java.lang.String string, final int i, final int i1) { + try { Assert.assertEquals(string, i, i1); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertEquals(final int i, final int i1) - { - try - { + public static void assertEquals(final int i, final int i1) { + try { Assert.assertEquals(i, i1); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertNotNull(final java.lang.Object object) - { - try - { + public static void assertNotNull(final java.lang.Object object) { + try { Assert.assertNotNull(object); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertNotNull(final java.lang.String string, final java.lang.Object object) - { - try - { + public static void assertNotNull(final java.lang.String string, final java.lang.Object object) { + try { Assert.assertNotNull(string, object); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertNull(final java.lang.Object object) - { - try - { + public static void assertNull(final java.lang.Object object) { + try { Assert.assertNull(object); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertNull(final java.lang.String string, final java.lang.Object object) - { - try - { + public static void assertNull(final java.lang.String string, final java.lang.Object object) { + try { Assert.assertNull(string, object); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } @@ -423,27 +332,21 @@ public class ProxyAssertSupport public static void assertSame(final java.lang.String string, final java.lang.Object object, - final java.lang.Object object1) - { - try - { + final java.lang.Object object1) { + try { Assert.assertSame(string, object, object1); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertSame(final java.lang.Object object, final java.lang.Object object1) - { - try - { + public static void assertSame(final java.lang.Object object, final java.lang.Object object1) { + try { Assert.assertSame(object, object1); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } @@ -451,27 +354,21 @@ public class ProxyAssertSupport public static void assertNotSame(final java.lang.String string, final java.lang.Object object, - final java.lang.Object object1) - { - try - { + final java.lang.Object object1) { + try { Assert.assertNotSame(string, object, object1); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } } - public static void assertNotSame(final java.lang.Object object, final java.lang.Object object1) - { - try - { + public static void assertNotSame(final java.lang.Object object, final java.lang.Object object1) { + try { Assert.assertNotSame(object, object1); } - catch (AssertionError e) - { + catch (AssertionError e) { ProxyAssertSupport.log.warn("AssertionFailure::" + e.toString(), e); throw e; } diff --git a/tests/joram-tests/src/test/java/org/apache/activemq/artemis/jms/AbstractAdmin.java b/tests/joram-tests/src/test/java/org/apache/activemq/artemis/jms/AbstractAdmin.java index d2ed90c8fb..1f2f9ccb74 100644 --- a/tests/joram-tests/src/test/java/org/apache/activemq/artemis/jms/AbstractAdmin.java +++ b/tests/joram-tests/src/test/java/org/apache/activemq/artemis/jms/AbstractAdmin.java @@ -24,82 +24,66 @@ import org.objectweb.jtests.jms.admin.Admin; /** * AbstractAdmin. */ -public class AbstractAdmin implements Admin -{ - public String getName() - { +public class AbstractAdmin implements Admin { + + public String getName() { return getClass().getName(); } - public void start() - { + public void start() { } - public void stop() throws Exception - { + public void stop() throws Exception { } - public InitialContext createContext() throws NamingException - { + public InitialContext createContext() throws NamingException { return new InitialContext(); } - public void createConnectionFactory(final String name) - { + public void createConnectionFactory(final String name) { throw new RuntimeException("FIXME NYI createConnectionFactory"); } - public void deleteConnectionFactory(final String name) - { + public void deleteConnectionFactory(final String name) { throw new RuntimeException("FIXME NYI deleteConnectionFactory"); } - public void createQueue(final String name) - { + public void createQueue(final String name) { throw new RuntimeException("FIXME NYI createQueue"); } - public void deleteQueue(final String name) - { + public void deleteQueue(final String name) { throw new RuntimeException("FIXME NYI deleteQueue"); } - public void createQueueConnectionFactory(final String name) - { + public void createQueueConnectionFactory(final String name) { createConnectionFactory(name); } - public void deleteQueueConnectionFactory(final String name) - { + public void deleteQueueConnectionFactory(final String name) { deleteConnectionFactory(name); } - public void createTopic(final String name) - { + public void createTopic(final String name) { throw new RuntimeException("FIXME NYI createTopic"); } - public void deleteTopic(final String name) - { + public void deleteTopic(final String name) { throw new RuntimeException("FIXME NYI deleteTopic"); } - public void createTopicConnectionFactory(final String name) - { + public void createTopicConnectionFactory(final String name) { createConnectionFactory(name); } - public void deleteTopicConnectionFactory(final String name) - { + public void deleteTopicConnectionFactory(final String name) { deleteConnectionFactory(name); } - public void startServer() - { + public void startServer() { } - public void stopServer() - { + public void stopServer() { } } diff --git a/tests/joram-tests/src/test/java/org/apache/activemq/artemis/jms/ActiveMQAdmin.java b/tests/joram-tests/src/test/java/org/apache/activemq/artemis/jms/ActiveMQAdmin.java index a090133d88..f02902c7bf 100644 --- a/tests/joram-tests/src/test/java/org/apache/activemq/artemis/jms/ActiveMQAdmin.java +++ b/tests/joram-tests/src/test/java/org/apache/activemq/artemis/jms/ActiveMQAdmin.java @@ -39,8 +39,7 @@ import org.apache.activemq.artemis.tests.util.SpawnedVMSupport; import org.junit.Assert; import org.objectweb.jtests.jms.admin.Admin; -public class ActiveMQAdmin implements Admin -{ +public class ActiveMQAdmin implements Admin { private ClientSession clientSession; @@ -63,49 +62,36 @@ public class ActiveMQAdmin implements Admin private final boolean serverLifeCycleActive; private static final String SERVER_LIVE_CYCLE_PROPERTY = "org.apache.activemq.artemis.jms.ActiveMQAdmin.serverLifeCycle"; - public ActiveMQAdmin() - { + public ActiveMQAdmin() { serverLifeCycleActive = Boolean.valueOf(System.getProperty(SERVER_LIVE_CYCLE_PROPERTY, "true")); - try - { + try { Hashtable env = new Hashtable(); env.put("java.naming.factory.initial", "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory"); env.put("java.naming.provider.url", "tcp://localhost:61616"); context = new InitialContext(env); } - catch (NamingException e) - { + catch (NamingException e) { e.printStackTrace(); } } - public void start() throws Exception - { + public void start() throws Exception { serverLocator = ActiveMQClient.createServerLocatorWithoutHA(new TransportConfiguration(NettyConnectorFactory.class.getName())); sf = serverLocator.createSessionFactory(); - clientSession = sf.createSession(ActiveMQDefaultConfiguration.getDefaultClusterUser(), - ActiveMQDefaultConfiguration.getDefaultClusterPassword(), - false, - true, - true, - false, - 1); + clientSession = sf.createSession(ActiveMQDefaultConfiguration.getDefaultClusterUser(), ActiveMQDefaultConfiguration.getDefaultClusterPassword(), false, true, true, false, 1); requestor = new ClientRequestor(clientSession, ActiveMQDefaultConfiguration.getDefaultManagementAddress()); clientSession.start(); } - public void stop() throws Exception - { + public void stop() throws Exception { requestor.close(); - if (sf != null) - { + if (sf != null) { sf.close(); } - if (serverLocator != null) - { + if (serverLocator != null) { serverLocator.close(); } @@ -113,133 +99,99 @@ public class ActiveMQAdmin implements Admin serverLocator = null; } - public void createConnectionFactory(final String name) - { + public void createConnectionFactory(final String name) { createConnection(name, 0); } - private void createConnection(final String name, final int cfType) - { - try - { - invokeSyncOperation(ResourceNames.JMS_SERVER, - "createConnectionFactory", - name, - false, - false, - cfType, - "netty", - name); + private void createConnection(final String name, final int cfType) { + try { + invokeSyncOperation(ResourceNames.JMS_SERVER, "createConnectionFactory", name, false, false, cfType, "netty", name); } - catch (Exception e) - { + catch (Exception e) { throw new IllegalStateException(e); } } - public Context createContext() throws NamingException - { + public Context createContext() throws NamingException { return context; } - public void createQueue(final String name) - { + public void createQueue(final String name) { Boolean result; - try - { + try { result = (Boolean) invokeSyncOperation(ResourceNames.JMS_SERVER, "createQueue", name, name); Assert.assertEquals(true, result.booleanValue()); } - catch (Exception e) - { + catch (Exception e) { throw new IllegalStateException(e); } } - public void createQueueConnectionFactory(final String name) - { + public void createQueueConnectionFactory(final String name) { createConnection(name, 1); } - public void createTopic(final String name) - { + public void createTopic(final String name) { Boolean result; - try - { + try { result = (Boolean) invokeSyncOperation(ResourceNames.JMS_SERVER, "createTopic", name, name); Assert.assertEquals(true, result.booleanValue()); } - catch (Exception e) - { + catch (Exception e) { throw new IllegalStateException(e); } } - public void createTopicConnectionFactory(final String name) - { + public void createTopicConnectionFactory(final String name) { createConnection(name, 2); } - public void deleteConnectionFactory(final String name) - { - try - { + public void deleteConnectionFactory(final String name) { + try { invokeSyncOperation(ResourceNames.JMS_SERVER, "destroyConnectionFactory", name); } - catch (Exception e) - { + catch (Exception e) { throw new IllegalStateException(e); } } - public void deleteQueue(final String name) - { + public void deleteQueue(final String name) { Boolean result; - try - { + try { result = (Boolean) invokeSyncOperation(ResourceNames.JMS_SERVER, "destroyQueue", name); Assert.assertEquals(true, result.booleanValue()); } - catch (Exception e) - { + catch (Exception e) { throw new IllegalStateException(e); } } - public void deleteQueueConnectionFactory(final String name) - { + public void deleteQueueConnectionFactory(final String name) { deleteConnectionFactory(name); } - public void deleteTopic(final String name) - { + public void deleteTopic(final String name) { Boolean result; - try - { + try { result = (Boolean) invokeSyncOperation(ResourceNames.JMS_SERVER, "destroyTopic", name); Assert.assertEquals(true, result.booleanValue()); } - catch (Exception e) - { + catch (Exception e) { throw new IllegalStateException(e); } } - public void deleteTopicConnectionFactory(final String name) - { + public void deleteTopicConnectionFactory(final String name) { deleteConnectionFactory(name); } - public String getName() - { + public String getName() { return this.getClass().getName(); } - public void startServer() throws Exception - { - if (!serverLifeCycleActive) - { + public void startServer() throws Exception { + if (!serverLifeCycleActive) { return; } @@ -249,34 +201,26 @@ public class ActiveMQAdmin implements Admin final BufferedReader br = new BufferedReader(isr); String line = null; - while ((line = br.readLine()) != null) - { + while ((line = br.readLine()) != null) { System.out.println("SERVER: " + line); - if ("OK".equals(line.trim())) - { - new Thread() - { + if ("OK".equals(line.trim())) { + new Thread() { @Override - public void run() - { - try - { + public void run() { + try { String line1 = null; - while ((line1 = br.readLine()) != null) - { + while ((line1 = br.readLine()) != null) { System.out.println("SERVER: " + line1); } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } }.start(); return; } - else if ("KO".equals(line.trim())) - { + else if ("KO".equals(line.trim())) { // something went wrong with the server, destroy it: serverProcess.destroy(); throw new IllegalStateException("Unable to start the spawned server :" + line); @@ -284,41 +228,35 @@ public class ActiveMQAdmin implements Admin } } - public void stopServer() throws Exception - { - if (!serverLifeCycleActive) - { + public void stopServer() throws Exception { + if (!serverLifeCycleActive) { return; } OutputStreamWriter osw = new OutputStreamWriter(serverProcess.getOutputStream()); osw.write("STOP\n"); osw.flush(); int exitValue = serverProcess.waitFor(); - if (exitValue != 0) - { + if (exitValue != 0) { serverProcess.destroy(); } } - private Object invokeSyncOperation(final String resourceName, final String operationName, final Object... parameters) throws Exception - { + private Object invokeSyncOperation(final String resourceName, + final String operationName, + final Object... parameters) throws Exception { ClientMessage message = clientSession.createMessage(false); ManagementHelper.putOperationInvocation(message, resourceName, operationName, parameters); ClientMessage reply; - try - { + try { reply = requestor.request(message, 3000); } - catch (Exception e) - { + catch (Exception e) { throw new IllegalStateException("Exception while invoking " + operationName + " on " + resourceName, e); } - if (reply == null) - { + if (reply == null) { throw new IllegalStateException("no reply received when invoking " + operationName + " on " + resourceName); } - if (!ManagementHelper.hasOperationSucceeded(reply)) - { + if (!ManagementHelper.hasOperationSucceeded(reply)) { throw new IllegalStateException("operation failed when invoking " + operationName + " on " + resourceName + diff --git a/tests/joram-tests/src/test/java/org/apache/activemq/artemis/jms/GenericAdmin.java b/tests/joram-tests/src/test/java/org/apache/activemq/artemis/jms/GenericAdmin.java index 1fce71ccb6..68b61fbbd3 100644 --- a/tests/joram-tests/src/test/java/org/apache/activemq/artemis/jms/GenericAdmin.java +++ b/tests/joram-tests/src/test/java/org/apache/activemq/artemis/jms/GenericAdmin.java @@ -27,102 +27,86 @@ import org.objectweb.jtests.jms.admin.Admin; * * @FIXME delegate to a JBoss defined admin class */ -public class GenericAdmin implements Admin -{ +public class GenericAdmin implements Admin { + public static final Logger log = Logger.getLogger(GenericAdmin.class); public static Admin delegate = new AbstractAdmin(); - public String getName() - { + public String getName() { String name = GenericAdmin.delegate.getName(); GenericAdmin.log.debug("Using admin '" + name + "' delegate=" + GenericAdmin.delegate); return name; } - public void start() throws Exception - { + public void start() throws Exception { } - public void stop() throws Exception - { + public void stop() throws Exception { } - public Context createContext() throws NamingException - { + public Context createContext() throws NamingException { Context ctx = GenericAdmin.delegate.createContext(); GenericAdmin.log.debug("Using initial context: " + ctx.getEnvironment()); return ctx; } - public void createConnectionFactory(final String name) - { + public void createConnectionFactory(final String name) { GenericAdmin.log.debug("createConnectionFactory '" + name + "'"); GenericAdmin.delegate.createConnectionFactory(name); } - public void deleteConnectionFactory(final String name) - { + public void deleteConnectionFactory(final String name) { GenericAdmin.log.debug("deleteConnectionFactory '" + name + "'"); GenericAdmin.delegate.deleteConnectionFactory(name); } - public void createQueue(final String name) - { + public void createQueue(final String name) { GenericAdmin.log.debug("createQueue '" + name + "'"); GenericAdmin.delegate.createQueue(name); } - public void deleteQueue(final String name) - { + public void deleteQueue(final String name) { GenericAdmin.log.debug("deleteQueue '" + name + "'"); GenericAdmin.delegate.deleteQueue(name); } - public void createQueueConnectionFactory(final String name) - { + public void createQueueConnectionFactory(final String name) { GenericAdmin.log.debug("createQueueConnectionFactory '" + name + "'"); GenericAdmin.delegate.createQueueConnectionFactory(name); } - public void deleteQueueConnectionFactory(final String name) - { + public void deleteQueueConnectionFactory(final String name) { GenericAdmin.log.debug("deleteQueueConnectionFactory '" + name + "'"); GenericAdmin.delegate.deleteQueueConnectionFactory(name); } - public void createTopic(final String name) - { + public void createTopic(final String name) { GenericAdmin.log.debug("createTopic '" + name + "'"); GenericAdmin.delegate.createTopic(name); } - public void deleteTopic(final String name) - { + public void deleteTopic(final String name) { GenericAdmin.log.debug("deleteTopic '" + name + "'"); GenericAdmin.delegate.deleteTopic(name); } - public void createTopicConnectionFactory(final String name) - { + public void createTopicConnectionFactory(final String name) { GenericAdmin.log.debug("createTopicConnectionFactory '" + name + "'"); GenericAdmin.delegate.createTopicConnectionFactory(name); } - public void deleteTopicConnectionFactory(final String name) - { + public void deleteTopicConnectionFactory(final String name) { GenericAdmin.log.debug("deleteTopicConnectionFactory '" + name + "'"); GenericAdmin.delegate.deleteTopicConnectionFactory(name); } - public void startServer() throws Exception - { + public void startServer() throws Exception { GenericAdmin.log.debug("startEmbeddedServer"); GenericAdmin.delegate.startServer(); } - public void stopServer() throws Exception - { + public void stopServer() throws Exception { GenericAdmin.log.debug("stopEmbeddedServer"); GenericAdmin.delegate.stopServer(); } diff --git a/tests/joram-tests/src/test/java/org/apache/activemq/artemis/jms/JoramAggregationTest.java b/tests/joram-tests/src/test/java/org/apache/activemq/artemis/jms/JoramAggregationTest.java index fdd3aebc10..c92e4f3358 100644 --- a/tests/joram-tests/src/test/java/org/apache/activemq/artemis/jms/JoramAggregationTest.java +++ b/tests/joram-tests/src/test/java/org/apache/activemq/artemis/jms/JoramAggregationTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.jms; + import java.io.IOException; import java.util.Properties; @@ -47,34 +48,15 @@ import org.objectweb.jtests.jms.conform.topic.TemporaryTopicTest; import org.objectweb.jtests.jms.framework.JMSTestCase; @RunWith(Suite.class) -@SuiteClasses({ -TopicConnectionTest.class, - ConnectionTest.class, - MessageBodyTest.class, - MessageDefaultTest.class, - MessageTypeTest.class, - MessageHeaderTest.class, - JMSXPropertyTest.class, - MessagePropertyConversionTest.class, - MessagePropertyTest.class, - QueueBrowserTest.class, - TemporaryQueueTest.class, - SelectorSyntaxTest.class, - SelectorTest.class, - QueueSessionTest.class, - SessionTest.class, - TopicSessionTest.class, - UnifiedSessionTest.class, - TemporaryTopicTest.class, - }) -public class JoramAggregationTest extends Assert -{ +@SuiteClasses({TopicConnectionTest.class, ConnectionTest.class, MessageBodyTest.class, MessageDefaultTest.class, MessageTypeTest.class, MessageHeaderTest.class, JMSXPropertyTest.class, MessagePropertyConversionTest.class, MessagePropertyTest.class, QueueBrowserTest.class, TemporaryQueueTest.class, SelectorSyntaxTest.class, SelectorTest.class, QueueSessionTest.class, SessionTest.class, TopicSessionTest.class, UnifiedSessionTest.class, TemporaryTopicTest.class,}) +public class JoramAggregationTest extends Assert { + /** * Should be overridden + * * @return */ - protected static Properties getProviderProperties() throws IOException - { + protected static Properties getProviderProperties() throws IOException { Properties props = new Properties(); props.load(ClassLoader.getSystemResourceAsStream(JMSTestCase.PROP_FILE_NAME)); return props; @@ -83,8 +65,7 @@ public class JoramAggregationTest extends Assert static Admin admin; @BeforeClass - public static void setUpServer() throws Exception - { + public static void setUpServer() throws Exception { JMSTestCase.startServer = false; // Admin step // gets the provider administration wrapper... @@ -94,8 +75,7 @@ public class JoramAggregationTest extends Assert } @AfterClass - public static void tearDownServer() throws Exception - { + public static void tearDownServer() throws Exception { admin.stopServer(); JMSTestCase.startServer = true; } diff --git a/tests/joram-tests/src/test/java/org/apache/activemq/artemis/jms/SpawnedJMSServer.java b/tests/joram-tests/src/test/java/org/apache/activemq/artemis/jms/SpawnedJMSServer.java index 583cb82867..205ac7fd6a 100644 --- a/tests/joram-tests/src/test/java/org/apache/activemq/artemis/jms/SpawnedJMSServer.java +++ b/tests/joram-tests/src/test/java/org/apache/activemq/artemis/jms/SpawnedJMSServer.java @@ -29,8 +29,7 @@ import org.apache.activemq.artemis.core.server.ActiveMQServers; import org.apache.activemq.artemis.jms.server.JMSServerManager; import org.apache.activemq.artemis.jms.server.impl.JMSServerManagerImpl; -public class SpawnedJMSServer -{ +public class SpawnedJMSServer { // Constants ----------------------------------------------------- @@ -38,14 +37,9 @@ public class SpawnedJMSServer // Static -------------------------------------------------------- - public static void main(final String[] args) throws Exception - { - try - { - Configuration config = new ConfigurationImpl() - .addAcceptorConfiguration(new TransportConfiguration(NettyAcceptorFactory.class.getName())) - .setSecurityEnabled(false) - .addConnectorConfiguration("netty", new TransportConfiguration(NettyConnectorFactory.class.getName())); + public static void main(final String[] args) throws Exception { + try { + Configuration config = new ConfigurationImpl().addAcceptorConfiguration(new TransportConfiguration(NettyAcceptorFactory.class.getName())).setSecurityEnabled(false).addConnectorConfiguration("netty", new TransportConfiguration(NettyConnectorFactory.class.getName())); // disable server persistence since JORAM tests do not restart server final ActiveMQServer server = ActiveMQServers.newActiveMQServer(config, false); @@ -63,28 +57,23 @@ public class SpawnedJMSServer System.out.println("OK"); String line = null; - while ((line = br.readLine()) != null) - { - if ("STOP".equals(line.trim())) - { + while ((line = br.readLine()) != null) { + if ("STOP".equals(line.trim())) { server.stop(); System.out.println("Server stopped"); System.exit(0); } - else - { + else { // stop anyway but with an error status System.exit(1); } } } - catch (Throwable t) - { + catch (Throwable t) { t.printStackTrace(); String allStack = t.getCause().getMessage() + "|"; StackTraceElement[] stackTrace = t.getCause().getStackTrace(); - for (StackTraceElement stackTraceElement : stackTrace) - { + for (StackTraceElement stackTraceElement : stackTrace) { allStack += stackTraceElement.toString() + "|"; } System.out.println(allStack); diff --git a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/admin/Admin.java b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/admin/Admin.java index 20d2a6f945..ea150f3fb6 100644 --- a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/admin/Admin.java +++ b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/admin/Admin.java @@ -25,8 +25,7 @@ import javax.naming.NamingException; * JMS Provider has to implement this * simple interface to be able to use the test suite. */ -public interface Admin -{ +public interface Admin { /** * Returns the name of the JMS Provider. @@ -44,16 +43,16 @@ public interface Admin /** * Creates a ConnectionFactory and makes it available - *from JNDI with name name. + * from JNDI with name name. * - * @since JMS 1.1 * @param name JNDI name of the ConnectionFactory + * @since JMS 1.1 */ void createConnectionFactory(String name); /** * Creates a QueueConnectionFactory and makes it available - *from JNDI with name name. + * from JNDI with name name. * * @param name JNDI name of the QueueConnectionFactory */ @@ -61,7 +60,7 @@ public interface Admin /** * Creates a TopicConnectionFactory and makes it available - *from JNDI with name name. + * from JNDI with name name. * * @param name JNDI name of the TopicConnectionFactory */ @@ -69,7 +68,7 @@ public interface Admin /** * Creates a Queue and makes it available - *from JNDI with name name. + * from JNDI with name name. * * @param name JNDI name of the Queue */ @@ -77,7 +76,7 @@ public interface Admin /** * Creates a Topic and makes it available - *from JNDI with name name. + * from JNDI with name name. * * @param name JNDI name of the Topic */ @@ -100,8 +99,8 @@ public interface Admin /** * Removes the ConnectionFactory of name name from JNDI and deletes it * - * @since JMS 1.1 * @param name JNDI name of the ConnectionFactory + * @since JMS 1.1 */ void deleteConnectionFactory(String name); diff --git a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/admin/AdminFactory.java b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/admin/AdminFactory.java index 213ac4a4bd..24c4dd6294 100644 --- a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/admin/AdminFactory.java +++ b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/admin/AdminFactory.java @@ -18,35 +18,29 @@ package org.objectweb.jtests.jms.admin; import java.util.Properties; -public class AdminFactory -{ +public class AdminFactory { + private static final String PROP_NAME = "jms.provider.admin.class"; - protected static String getAdminClassName(final Properties props) - { + protected static String getAdminClassName(final Properties props) { String adminClassName = props.getProperty(AdminFactory.PROP_NAME); return adminClassName; } - public static Admin getAdmin(final Properties props) - { + public static Admin getAdmin(final Properties props) { String adminClassName = AdminFactory.getAdminClassName(props); Admin admin = null; - if (adminClassName == null) - { + if (adminClassName == null) { throw new RuntimeException("Property " + AdminFactory.PROP_NAME + " has not been found in input props"); } - try - { + try { Class adminClass = Class.forName(adminClassName); - admin = (Admin)adminClass.newInstance(); + admin = (Admin) adminClass.newInstance(); } - catch (ClassNotFoundException e) - { + catch (ClassNotFoundException e) { throw new RuntimeException("Class " + adminClassName + " not found.", e); } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } return admin; diff --git a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/connection/ConnectionTest.java b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/connection/ConnectionTest.java index 53e6ae0bc6..26ed4bcf79 100644 --- a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/connection/ConnectionTest.java +++ b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/connection/ConnectionTest.java @@ -32,18 +32,15 @@ import org.objectweb.jtests.jms.framework.TestConfig; * * See JMS specifications, sec. 4.3.5 Closing a Connection */ -public class ConnectionTest extends PTPTestCase -{ +public class ConnectionTest extends PTPTestCase { /** * Test that invoking the acknowledge() method of a received message * from a closed connection's session must throw an IllegalStateException. */ @Test - public void testAcknowledge() - { - try - { + public void testAcknowledge() { + try { receiverConnection.stop(); receiverSession = receiverConnection.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE); receiver.close(); // Before assigning a new receiver, we need to close the old one... @@ -61,18 +58,14 @@ public class ConnectionTest extends PTPTestCase m.acknowledge(); Assert.fail("sec. 4.3.5 Invoking the acknowledge method of a received message from a closed " + "connection's session must throw a [javax.jms.]IllegalStateException.\n"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("sec. 4.3.5 Invoking the acknowledge method of a received message from a closed " + "connection's session must throw a [javax.jms.]IllegalStateException, not a " + - e); + e); } - catch (java.lang.IllegalStateException e) - { - Assert.fail("sec. 4.3.5 Invoking the acknowledge method of a received message from a closed " + "connection's session must throw an [javax.jms.]IllegalStateException " - + "[not a java.lang.IllegalStateException]"); + catch (java.lang.IllegalStateException e) { + Assert.fail("sec. 4.3.5 Invoking the acknowledge method of a received message from a closed " + "connection's session must throw an [javax.jms.]IllegalStateException " + "[not a java.lang.IllegalStateException]"); } } @@ -81,23 +74,18 @@ public class ConnectionTest extends PTPTestCase * throws a javax.jms.IllegalStateException. */ @Test - public void testUseClosedConnection() - { - try - { + public void testUseClosedConnection() { + try { senderConnection.close(); senderConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Assert.fail("Should raise a javax.jms.IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("Should raise a javax.jms.IllegalStateException, not a " + e); } - catch (java.lang.IllegalStateException e) - { + catch (java.lang.IllegalStateException e) { Assert.fail("Should raise a javax.jms.IllegalStateException, not a java.lang.IllegalStateException"); } } @@ -107,18 +95,15 @@ public class ConnectionTest extends PTPTestCase * Connection is stopped. */ @Test - public void testMessageSentWhenConnectionClosed() - { - try - { + public void testMessageSentWhenConnectionClosed() { + try { senderConnection.stop(); Message message = senderSession.createTextMessage(); sender.send(message); receiver.receive(TestConfig.TIMEOUT); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -127,18 +112,15 @@ public class ConnectionTest extends PTPTestCase * Test that closing a closed connectiondoes not throw an exception. */ @Test - public void testCloseClosedConnection() - { - try - { + public void testCloseClosedConnection() { + try { // senderConnection is already started // we close it once senderConnection.close(); // we close it a second time senderConnection.close(); } - catch (Exception e) - { + catch (Exception e) { Assert.fail("sec. 4.3.5 Closing a closed connection must not throw an exception.\n"); } } @@ -147,16 +129,13 @@ public class ConnectionTest extends PTPTestCase * Test that starting a started connection is ignored */ @Test - public void testStartStartedConnection() - { - try - { + public void testStartStartedConnection() { + try { // senderConnection is already started // start it again should be ignored senderConnection.start(); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -165,18 +144,15 @@ public class ConnectionTest extends PTPTestCase * Test that stopping a stopped connection is ignored */ @Test - public void testStopStoppedConnection() - { - try - { + public void testStopStoppedConnection() { + try { // senderConnection is started // we stop it once senderConnection.stop(); // stopping it a second time is ignored senderConnection.stop(); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -185,23 +161,17 @@ public class ConnectionTest extends PTPTestCase * Test that delivery of message is stopped if the message consumer connection is stopped */ @Test - public void testStopConsumerConnection() - { - try - { + public void testStopConsumerConnection() { + try { receiverConnection.stop(); - receiver.setMessageListener(new MessageListener() - { - public void onMessage(final Message m) - { - try - { + receiver.setMessageListener(new MessageListener() { + public void onMessage(final Message m) { + try { Assert.fail("The message must not be received, the consumer connection is stopped"); - Assert.assertEquals("test", ((TextMessage)m).getText()); + Assert.assertEquals("test", ((TextMessage) m).getText()); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -210,20 +180,16 @@ public class ConnectionTest extends PTPTestCase TextMessage message = senderSession.createTextMessage(); message.setText("test"); sender.send(message); - synchronized (this) - { - try - { + synchronized (this) { + try { Thread.sleep(1000); } - catch (Exception e) - { + catch (Exception e) { fail(e); } } } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } diff --git a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/connection/TopicConnectionTest.java b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/connection/TopicConnectionTest.java index f9461e68b3..129e6f9d3b 100644 --- a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/connection/TopicConnectionTest.java +++ b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/connection/TopicConnectionTest.java @@ -29,8 +29,7 @@ import org.objectweb.jtests.jms.framework.PubSubTestCase; * Test setting of client ID which is relevant only for Durable Subscribtion */ -public class TopicConnectionTest extends PubSubTestCase -{ +public class TopicConnectionTest extends PubSubTestCase { /** * Test that a call to setClientID will throw an @@ -39,18 +38,15 @@ public class TopicConnectionTest extends PubSubTestCase * http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/jms/Connection.html#setClientID(java.lang.String) */ @Test - public void testSetClientID_1() - { - try - { + public void testSetClientID_1() { + try { // we start from a clean state for the connection subscriberConnection.close(); subscriberConnection = null; subscriberConnection = subscriberTCF.createTopicConnection(); // if the JMS provider does not set a client ID, we do. - if (subscriberConnection.getClientID() == null) - { + if (subscriberConnection.getClientID() == null) { subscriberConnection.setClientID("testSetClientID_1"); Assert.assertEquals("testSetClientID_1", subscriberConnection.getClientID()); } @@ -61,15 +57,12 @@ public class TopicConnectionTest extends PubSubTestCase subscriberConnection.setClientID("another client ID"); Assert.fail("Should raise a javax.jms.IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("Should raise a javax.jms.IllegalStateException, not a " + e); } - catch (java.lang.IllegalStateException e) - { + catch (java.lang.IllegalStateException e) { Assert.fail("Should raise a javax.jms.IllegalStateException, not a java.lang.IllegalStateException"); } } @@ -82,18 +75,15 @@ public class TopicConnectionTest extends PubSubTestCase * http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/jms/Connection.html#setClientID(java.lang.String) */ @Test - public void testSetClientID_2() - { - try - { + public void testSetClientID_2() { + try { // we start from a clean state for the first connection subscriberConnection.close(); subscriberConnection = null; subscriberConnection = subscriberTCF.createTopicConnection(); // if the JMS provider has set a client ID, this test is not relevant - if (subscriberConnection.getClientID() != null) - { + if (subscriberConnection.getClientID() != null) { return; } @@ -104,15 +94,12 @@ public class TopicConnectionTest extends PubSubTestCase subscriberConnection.setClientID("testSetClientID_2"); Assert.fail("Should throw a javax.jms.IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("Should raise a javax.jms.IllegalStateException, not a " + e); } - catch (java.lang.IllegalStateException e) - { + catch (java.lang.IllegalStateException e) { Assert.fail("Should raise a javax.jms.IllegalStateException, not a java.lang.IllegalStateException"); } } diff --git a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/MessageBodyTest.java b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/MessageBodyTest.java index f360166743..d3a1c7b4ff 100644 --- a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/MessageBodyTest.java +++ b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/MessageBodyTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.objectweb.jtests.jms.conform.message; + import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageNotWriteableException; @@ -28,27 +29,21 @@ import org.objectweb.jtests.jms.framework.TestConfig; /** * Tests on message body. */ -public class MessageBodyTest extends PTPTestCase -{ +public class MessageBodyTest extends PTPTestCase { /** * Test that the TextMessage.clearBody() method does not clear the * message properties. */ @Test - public void testClearBody_2() - { - try - { + public void testClearBody_2() { + try { TextMessage message = senderSession.createTextMessage(); message.setStringProperty("prop", "foo"); message.clearBody(); - Assert.assertEquals("sec. 3.11.1 Clearing a message's body does not clear its property entries.\n", - "foo", - message.getStringProperty("prop")); + Assert.assertEquals("sec. 3.11.1 Clearing a message's body does not clear its property entries.\n", "foo", message.getStringProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -57,20 +52,14 @@ public class MessageBodyTest extends PTPTestCase * Test that the TextMessage.clearBody() effectively clear the body of the message */ @Test - public void testClearBody_1() - { - try - { + public void testClearBody_1() { + try { TextMessage message = senderSession.createTextMessage(); message.setText("bar"); message.clearBody(); - Assert.assertEquals("sec. 3 .11.1 the clearBody method of Message resets the value of the message body " + "to the 'empty' initial message value as set by the message type's create " - + "method provided by Session.\n", - null, - message.getText()); + Assert.assertEquals("sec. 3 .11.1 the clearBody method of Message resets the value of the message body " + "to the 'empty' initial message value as set by the message type's create " + "method provided by Session.\n", null, message.getText()); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -80,25 +69,21 @@ public class MessageBodyTest extends PTPTestCase * received message raises a javax.jms.MessageNotWriteableException. */ @Test - public void testWriteOnReceivedBody() - { - try - { + public void testWriteOnReceivedBody() { + try { TextMessage message = senderSession.createTextMessage(); message.setText("foo"); sender.send(message); Message m = receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue("The message should be an instance of TextMessage.\n", m instanceof TextMessage); - TextMessage msg = (TextMessage)m; + TextMessage msg = (TextMessage) m; msg.setText("bar"); Assert.fail("should raise a MessageNotWriteableException (sec. 3.11.2)"); } - catch (MessageNotWriteableException e) - { + catch (MessageNotWriteableException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } diff --git a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/MessageDefaultTest.java b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/MessageDefaultTest.java index 521c3aabfa..5beb7c03df 100644 --- a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/MessageDefaultTest.java +++ b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/MessageDefaultTest.java @@ -27,19 +27,15 @@ import org.objectweb.jtests.jms.framework.JMSTestCase; /** * Test the default constants of the javax.jms.Message interface. */ -public class MessageDefaultTest extends JMSTestCase -{ +public class MessageDefaultTest extends JMSTestCase { /** * test that the DEFAULT_DELIVERY_MODE of javax.jms.Message * corresponds to javax.jms.Delivery.PERSISTENT. */ @Test - public void testDEFAULT_DELIVERY_MODE() - { - Assert.assertEquals("The delivery mode is persistent by default.\n", - DeliveryMode.PERSISTENT, - Message.DEFAULT_DELIVERY_MODE); + public void testDEFAULT_DELIVERY_MODE() { + Assert.assertEquals("The delivery mode is persistent by default.\n", DeliveryMode.PERSISTENT, Message.DEFAULT_DELIVERY_MODE); } /** @@ -47,8 +43,7 @@ public class MessageDefaultTest extends JMSTestCase * corresponds to 4. */ @Test - public void testDEFAULT_PRIORITY() - { + public void testDEFAULT_PRIORITY() { Assert.assertEquals("The default priority is 4.\n", 4, Message.DEFAULT_PRIORITY); } } diff --git a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/MessageTypeTest.java b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/MessageTypeTest.java index ef668198a7..3c4878ac0f 100644 --- a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/MessageTypeTest.java +++ b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/MessageTypeTest.java @@ -37,19 +37,18 @@ import org.objectweb.jtests.jms.framework.TestConfig; *
    * JMS provides 6 types of messages which differs by the type of their body: *
      - *
    1. Message which doesn't have a body
    2. - *
    3. TextMessage with a String as body
    4. - *
    5. ObjectMessage with any Object as body
    6. - *
    7. BytesMessage with a body made of bytes
    8. - *
    9. MapMessage with name-value pairs of Java primitives in its body
    10. - *
    11. StreamMessage with a stream of Java primitives as body
    12. - *
    + *
  • Message which doesn't have a body
  • + *
  • TextMessage with a String as body
  • + *
  • ObjectMessage with any Object as body
  • + *
  • BytesMessage with a body made of bytes
  • + *
  • MapMessage with name-value pairs of Java primitives in its body
  • + *
  • StreamMessage with a stream of Java primitives as body
  • + * *
    * For each of this type of message, we test that a message can be sent and received * with an empty body or not. */ -public class MessageTypeTest extends PTPTestCase -{ +public class MessageTypeTest extends PTPTestCase { /** * Send a StreamMessage with 2 Java primitives in its body (a @@ -58,10 +57,8 @@ public class MessageTypeTest extends PTPTestCase * Receive it and test that the values of the primitives of the body are correct */ @Test - public void testStreamMessage_2() - { - try - { + public void testStreamMessage_2() { + try { StreamMessage message = senderSession.createStreamMessage(); message.writeString("pi"); message.writeDouble(3.14159); @@ -69,12 +66,11 @@ public class MessageTypeTest extends PTPTestCase Message m = receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue("The message should be an instance of StreamMessage.\n", m instanceof StreamMessage); - StreamMessage msg = (StreamMessage)m; + StreamMessage msg = (StreamMessage) m; Assert.assertEquals("pi", msg.readString()); Assert.assertEquals(3.14159, msg.readDouble(), 0); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -86,18 +82,15 @@ public class MessageTypeTest extends PTPTestCase * StreamMessage */ @Test - public void testStreamMessage_1() - { - try - { + public void testStreamMessage_1() { + try { StreamMessage message = senderSession.createStreamMessage(); sender.send(message); Message msg = receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue("The message should be an instance of StreamMessage.\n", msg instanceof StreamMessage); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -107,23 +100,20 @@ public class MessageTypeTest extends PTPTestCase * getDouble("foo") (the later returning a java.lang.Double and the former a double) */ @Test - public void testMapMessageConversion() - { - try - { + public void testMapMessageConversion() { + try { MapMessage message = senderSession.createMapMessage(); message.setDouble("pi", 3.14159); sender.send(message); Message m = receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue("The message should be an instance of MapMessage.\n", m instanceof MapMessage); - MapMessage msg = (MapMessage)m; + MapMessage msg = (MapMessage) m; Assert.assertTrue(msg.getObject("pi") instanceof Double); - Assert.assertEquals(3.14159, ((Double)msg.getObject("pi")).doubleValue(), 0); + Assert.assertEquals(3.14159, ((Double) msg.getObject("pi")).doubleValue(), 0); Assert.assertEquals(3.14159, msg.getDouble("pi"), 0); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -132,22 +122,19 @@ public class MessageTypeTest extends PTPTestCase * Test that the if the name parameter of the set methods of a MapMessage is null, * the method must throw the error java.lang.IllegalArgumentException. *
    + * * @since JMS 1.1 */ @Test - public void testNullInSetMethodsForMapMessage() - { - try - { + public void testNullInSetMethodsForMapMessage() { + try { MapMessage message = senderSession.createMapMessage(); message.setBoolean(null, true); Assert.fail("Should throw an IllegalArgumentException"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("Should throw an IllegalArgumentException, not a" + e); } } @@ -156,22 +143,19 @@ public class MessageTypeTest extends PTPTestCase * Test that the if the name parameter of the set methods of a MapMessage is an empty String, * the method must throw the error java.lang.IllegalArgumentException. *
    + * * @since JMS 1.1 */ @Test - public void testEmptyStringInSetMethodsForMapMessage() - { - try - { + public void testEmptyStringInSetMethodsForMapMessage() { + try { MapMessage message = senderSession.createMapMessage(); message.setBoolean("", true); Assert.fail("Should throw an IllegalArgumentException"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("Should throw an IllegalArgumentException, not a" + e); } } @@ -183,10 +167,8 @@ public class MessageTypeTest extends PTPTestCase * Also test that the same method returns the correct names of the map. */ @Test - public void testgetMapNames() - { - try - { + public void testgetMapNames() { + try { MapMessage message = senderSession.createMapMessage(); Enumeration e = message.getMapNames(); Assert.assertTrue("No map yet defined.\n", !e.hasMoreElements()); @@ -194,8 +176,7 @@ public class MessageTypeTest extends PTPTestCase e = message.getMapNames(); Assert.assertEquals("pi", e.nextElement()); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -207,10 +188,8 @@ public class MessageTypeTest extends PTPTestCase * Receive it and test that the values of the primitives of the body are correct */ @Test - public void testMapMessage_2() - { - try - { + public void testMapMessage_2() { + try { MapMessage message = senderSession.createMapMessage(); message.setString("name", "pi"); message.setDouble("value", 3.14159); @@ -218,12 +197,11 @@ public class MessageTypeTest extends PTPTestCase Message m = receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue("The message should be an instance of MapMessage.\n", m instanceof MapMessage); - MapMessage msg = (MapMessage)m; + MapMessage msg = (MapMessage) m; Assert.assertEquals("pi", msg.getString("name")); Assert.assertEquals(3.14159, msg.getDouble("value"), 0); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -235,18 +213,15 @@ public class MessageTypeTest extends PTPTestCase * MapMessage */ @Test - public void testMapMessage_1() - { - try - { + public void testMapMessage_1() { + try { MapMessage message = senderSession.createMapMessage(); sender.send(message); Message msg = receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue("The message should be an instance of MapMessage.\n", msg instanceof MapMessage); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -258,10 +233,8 @@ public class MessageTypeTest extends PTPTestCase * Receive it and test that the values of the primitives of the body are correct */ @Test - public void testObjectMessage_2() - { - try - { + public void testObjectMessage_2() { + try { Vector vector = new Vector(); vector.add("pi"); vector.add(new Double(3.14159)); @@ -272,11 +245,10 @@ public class MessageTypeTest extends PTPTestCase Message m = receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue("The message should be an instance of ObjectMessage.\n", m instanceof ObjectMessage); - ObjectMessage msg = (ObjectMessage)m; + ObjectMessage msg = (ObjectMessage) m; Assert.assertEquals(vector, msg.getObject()); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -288,18 +260,15 @@ public class MessageTypeTest extends PTPTestCase * ObjectMessage */ @Test - public void testObjectMessage_1() - { - try - { + public void testObjectMessage_1() { + try { ObjectMessage message = senderSession.createObjectMessage(); sender.send(message); Message msg = receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue("The message should be an instance of ObjectMessage.\n", msg instanceof ObjectMessage); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -311,10 +280,8 @@ public class MessageTypeTest extends PTPTestCase * Receive it and test that the values of the primitives of the body are correct */ @Test - public void testBytesMessage_2() - { - try - { + public void testBytesMessage_2() { + try { byte[] bytes = new String("pi").getBytes(); BytesMessage message = senderSession.createBytesMessage(); message.writeBytes(bytes); @@ -323,14 +290,13 @@ public class MessageTypeTest extends PTPTestCase Message m = receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue("The message should be an instance of BytesMessage.\n", m instanceof BytesMessage); - BytesMessage msg = (BytesMessage)m; + BytesMessage msg = (BytesMessage) m; byte[] receivedBytes = new byte[bytes.length]; msg.readBytes(receivedBytes); Assert.assertEquals(new String(bytes), new String(receivedBytes)); Assert.assertEquals(3.14159, msg.readDouble(), 0); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -342,18 +308,15 @@ public class MessageTypeTest extends PTPTestCase * BytesMessage */ @Test - public void testBytesMessage_1() - { - try - { + public void testBytesMessage_1() { + try { BytesMessage message = senderSession.createBytesMessage(); sender.send(message); Message msg = receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue("The message should be an instance of BytesMessage.\n", msg instanceof BytesMessage); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -365,21 +328,18 @@ public class MessageTypeTest extends PTPTestCase * the sent one. */ @Test - public void testTextMessage_2() - { - try - { + public void testTextMessage_2() { + try { TextMessage message = senderSession.createTextMessage(); message.setText("testTextMessage_2"); sender.send(message); Message m = receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue("The message should be an instance of TextMessage.\n", m instanceof TextMessage); - TextMessage msg = (TextMessage)m; + TextMessage msg = (TextMessage) m; Assert.assertEquals("testTextMessage_2", msg.getText()); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -391,18 +351,15 @@ public class MessageTypeTest extends PTPTestCase * TextMessage */ @Test - public void testTextMessage_1() - { - try - { + public void testTextMessage_1() { + try { TextMessage message = senderSession.createTextMessage(); sender.send(message); Message msg = receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue("The message should be an instance of TextMessage.\n", msg instanceof TextMessage); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } diff --git a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/headers/MessageHeaderTest.java b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/headers/MessageHeaderTest.java index 5c0f3ab9bb..1d051eb3e7 100644 --- a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/headers/MessageHeaderTest.java +++ b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/headers/MessageHeaderTest.java @@ -34,34 +34,27 @@ import org.junit.Test; import org.objectweb.jtests.jms.framework.PTPTestCase; import org.objectweb.jtests.jms.framework.TestConfig; - /** * Test the headers of a message */ -public class MessageHeaderTest extends PTPTestCase -{ +public class MessageHeaderTest extends PTPTestCase { /** * Test that the MessageProducer.setPriority() changes effectively * priority of the message. */ @Test - public void testJMSPriority_2() - { - try - { + public void testJMSPriority_2() { + try { Message message = senderSession.createMessage(); sender.send(message); sender.setPriority(9); sender.send(message); - Assert.assertEquals("sec. 3.4.9 After completion of the send it holds the value specified by the " + "method sending the message.\n", - 9, - message.getJMSPriority()); + Assert.assertEquals("sec. 3.4.9 After completion of the send it holds the value specified by the " + "method sending the message.\n", 9, message.getJMSPriority()); receiver.receive(TestConfig.TIMEOUT); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -72,22 +65,17 @@ public class MessageHeaderTest extends PTPTestCase * Message.DEFAULT_PRIORITY in this test). */ @Test - public void testJMSPriority_1() - { - try - { + public void testJMSPriority_1() { + try { Message message = senderSession.createMessage(); message.setJMSPriority(0); sender.send(message); Assert.assertTrue("sec. 3.4.9 When a message is sent this value is ignored.\n", message.getJMSPriority() != 0); - Assert.assertEquals("sec. 3.4.9 After completion of the send it holds the value specified by the " + "method sending the message.\n", - Message.DEFAULT_PRIORITY, - message.getJMSPriority()); + Assert.assertEquals("sec. 3.4.9 After completion of the send it holds the value specified by the " + "method sending the message.\n", Message.DEFAULT_PRIORITY, message.getJMSPriority()); receiver.receive(TestConfig.TIMEOUT); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -97,20 +85,15 @@ public class MessageHeaderTest extends PTPTestCase * for the sent message and the received one. */ @Test - public void testJMSExpiration() - { - try - { + public void testJMSExpiration() { + try { Message message = senderSession.createMessage(); sender.send(message); Message msg = receiver.receive(TestConfig.TIMEOUT); - Assert.assertEquals("sec. 3.4.9 When a message is received its JMSExpiration header field contains this same " + "value [i.e. set on return of the send method].\n", - message.getJMSExpiration(), - msg.getJMSExpiration()); + Assert.assertEquals("sec. 3.4.9 When a message is received its JMSExpiration header field contains this same " + "value [i.e. set on return of the send method].\n", message.getJMSExpiration(), msg.getJMSExpiration()); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -120,23 +103,17 @@ public class MessageHeaderTest extends PTPTestCase * and that it starts with "ID:". */ @Test - public void testJMSMessageID_2() - { - try - { + public void testJMSMessageID_2() { + try { Message message = senderSession.createMessage(); sender.send(message); - Assert.assertTrue("sec. 3.4.3 When the send method returns it contains a provider-assigned value.\n", - message.getJMSMessageID() != null); - Assert.assertTrue("sec. 3.4.3 All JMSMessageID values must start with the prefix 'ID:'.\n", - message.getJMSMessageID().startsWith("ID:")); + Assert.assertTrue("sec. 3.4.3 When the send method returns it contains a provider-assigned value.\n", message.getJMSMessageID() != null); + Assert.assertTrue("sec. 3.4.3 All JMSMessageID values must start with the prefix 'ID:'.\n", message.getJMSMessageID().startsWith("ID:")); Message msg = receiver.receive(TestConfig.TIMEOUT); - Assert.assertTrue("sec. 3.4.3 All JMSMessageID values must start with the prefix 'ID:'.\n", - msg.getJMSMessageID().startsWith("ID:")); + Assert.assertTrue("sec. 3.4.3 All JMSMessageID values must start with the prefix 'ID:'.\n", msg.getJMSMessageID().startsWith("ID:")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -146,19 +123,15 @@ public class MessageHeaderTest extends PTPTestCase * ignored when the message is sent. */ @Test - public void testJMSMessageID_1() - { - try - { + public void testJMSMessageID_1() { + try { Message message = senderSession.createMessage(); message.setJMSMessageID("ID:foo"); sender.send(message); - Assert.assertTrue("sec. 3.4.3 When a message is sent this value is ignored.\n", - !message.getJMSMessageID().equals("ID:foo")); + Assert.assertTrue("sec. 3.4.3 When a message is sent this value is ignored.\n", !message.getJMSMessageID().equals("ID:foo")); receiver.receive(TestConfig.TIMEOUT); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -169,26 +142,20 @@ public class MessageHeaderTest extends PTPTestCase * method (i.e. Message.DEFAULT_DELIVERY_MODE in this test when the message is received. */ @Test - public void testJMSDeliveryMode() - { - try - { + public void testJMSDeliveryMode() { + try { // sender has been created with the DEFAULT_DELIVERY_MODE which is PERSISTENT Assert.assertEquals(DeliveryMode.PERSISTENT, sender.getDeliveryMode()); Message message = senderSession.createMessage(); // send a message specfiying NON_PERSISTENT for the JMSDeliveryMode header field message.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT); sender.send(message); - Assert.assertTrue("sec. 3.4.2 When a message is sent this value is ignored", - message.getJMSDeliveryMode() != DeliveryMode.NON_PERSISTENT); - Assert.assertEquals("sec. 3.4.2 After completion of the send it holds the delivery mode specified " + "by the sending method (persistent by default).\n", - Message.DEFAULT_DELIVERY_MODE, - message.getJMSDeliveryMode()); + Assert.assertTrue("sec. 3.4.2 When a message is sent this value is ignored", message.getJMSDeliveryMode() != DeliveryMode.NON_PERSISTENT); + Assert.assertEquals("sec. 3.4.2 After completion of the send it holds the delivery mode specified " + "by the sending method (persistent by default).\n", Message.DEFAULT_DELIVERY_MODE, message.getJMSDeliveryMode()); receiver.receive(TestConfig.TIMEOUT); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -200,10 +167,8 @@ public class MessageHeaderTest extends PTPTestCase * Also test that the value of the header on the received message is the same that on the sent message. */ @Test - public void testJMSDestination() - { - try - { + public void testJMSDestination() { + try { admin.createQueue("anotherQueue"); Hashtable props = new Hashtable<>(); @@ -211,32 +176,25 @@ public class MessageHeaderTest extends PTPTestCase props.put("queue.anotherQueue", "anotherQueue"); Context ctx = new InitialContext(props); - Queue anotherQueue = (Queue)ctx.lookup("anotherQueue"); + Queue anotherQueue = (Queue) ctx.lookup("anotherQueue"); Assert.assertTrue(anotherQueue != senderQueue); // set the JMSDestination header field to the anotherQueue Destination Message message = senderSession.createMessage(); message.setJMSDestination(anotherQueue); sender.send(message); - Assert.assertTrue("sec. 3.4.1 When a message is sent this value is ignored.\n", - message.getJMSDestination() != anotherQueue); - Assert.assertEquals("sec. 3.4.1 After completion of the send it holds the destination object specified " + "by the sending method.\n", - senderQueue, - message.getJMSDestination()); + Assert.assertTrue("sec. 3.4.1 When a message is sent this value is ignored.\n", message.getJMSDestination() != anotherQueue); + Assert.assertEquals("sec. 3.4.1 After completion of the send it holds the destination object specified " + "by the sending method.\n", senderQueue, message.getJMSDestination()); Message msg = receiver.receive(TestConfig.TIMEOUT); - Assert.assertEquals("sec. 3.4.1 When a message is received, its destination value must be equivalent " + " to the value assigned when it was sent.\n", - ((Queue)message.getJMSDestination()).getQueueName(), - ((Queue)msg.getJMSDestination()).getQueueName()); + Assert.assertEquals("sec. 3.4.1 When a message is received, its destination value must be equivalent " + " to the value assigned when it was sent.\n", ((Queue) message.getJMSDestination()).getQueueName(), ((Queue) msg.getJMSDestination()).getQueueName()); admin.deleteQueue("anotherQueue"); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } - catch (NamingException e) - { + catch (NamingException e) { Assert.fail(e.getMessage()); } } @@ -247,10 +205,8 @@ public class MessageHeaderTest extends PTPTestCase * the
    getJMSReplyTo() method. */ @Test - public void testJMSReplyTo_1() - { - try - { + public void testJMSReplyTo_1() { + try { Message message = senderSession.createMessage(); message.setJMSReplyTo(senderQueue); sender.send(message); @@ -258,13 +214,10 @@ public class MessageHeaderTest extends PTPTestCase Message msg = receiver.receive(TestConfig.TIMEOUT); Destination dest = msg.getJMSReplyTo(); Assert.assertTrue("JMS ReplyTo header field should be a Queue", dest instanceof Queue); - Queue replyTo = (Queue)dest; - Assert.assertEquals("JMS ReplyTo header field should be equals to the sender queue", - replyTo.getQueueName(), - senderQueue.getQueueName()); + Queue replyTo = (Queue) dest; + Assert.assertEquals("JMS ReplyTo header field should be equals to the sender queue", replyTo.getQueueName(), senderQueue.getQueueName()); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -275,10 +228,8 @@ public class MessageHeaderTest extends PTPTestCase * (and not only as a Queue). */ @Test - public void testJMSReplyTo_2() - { - try - { + public void testJMSReplyTo_2() { + try { TemporaryQueue tempQueue = senderSession.createTemporaryQueue(); Message message = senderSession.createMessage(); message.setJMSReplyTo(tempQueue); @@ -287,13 +238,10 @@ public class MessageHeaderTest extends PTPTestCase Message msg = receiver.receive(TestConfig.TIMEOUT); Destination dest = msg.getJMSReplyTo(); Assert.assertTrue("JMS ReplyTo header field should be a TemporaryQueue", dest instanceof TemporaryQueue); - Queue replyTo = (Queue)dest; - Assert.assertEquals("JMS ReplyTo header field should be equals to the temporary queue", - replyTo.getQueueName(), - tempQueue.getQueueName()); + Queue replyTo = (Queue) dest; + Assert.assertEquals("JMS ReplyTo header field should be equals to the temporary queue", replyTo.getQueueName(), tempQueue.getQueueName()); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } diff --git a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/properties/JMSXPropertyTest.java b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/properties/JMSXPropertyTest.java index 41ae601268..a7e33eb832 100644 --- a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/properties/JMSXPropertyTest.java +++ b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/properties/JMSXPropertyTest.java @@ -31,34 +31,28 @@ import org.objectweb.jtests.jms.framework.TestConfig; /** * Test the JMSX defined properties. *
    - * See JMS Specification, sec. 3.5.9 JMS Defined Properties + * See JMS Specification, sec. 3.5.9 JMS Defined Properties */ -public class JMSXPropertyTest extends PTPTestCase -{ +public class JMSXPropertyTest extends PTPTestCase { /** * Test that the JMSX property JMSXGroupID is supported. */ @Test - public void testSupportsJMSXGroupID() - { - try - { + public void testSupportsJMSXGroupID() { + try { boolean found = false; ConnectionMetaData metaData = senderConnection.getMetaData(); Enumeration enumeration = metaData.getJMSXPropertyNames(); - while (enumeration.hasMoreElements()) - { - String jmsxPropertyName = (String)enumeration.nextElement(); - if (jmsxPropertyName.equals("JMSXGroupID")) - { + while (enumeration.hasMoreElements()) { + String jmsxPropertyName = (String) enumeration.nextElement(); + if (jmsxPropertyName.equals("JMSXGroupID")) { found = true; } } Assert.assertTrue("JMSXGroupID property is not supported", found); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -67,10 +61,8 @@ public class JMSXPropertyTest extends PTPTestCase * Test that the JMSX property JMSXGroupID works */ @Test - public void testJMSXGroupID_1() - { - try - { + public void testJMSXGroupID_1() { + try { String groupID = "testSupportsJMSXGroupID_1:group"; TextMessage message = senderSession.createTextMessage(); message.setStringProperty("JMSXGroupID", groupID); @@ -79,12 +71,11 @@ public class JMSXPropertyTest extends PTPTestCase Message m = receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue(m instanceof TextMessage); - TextMessage msg = (TextMessage)m; + TextMessage msg = (TextMessage) m; Assert.assertEquals(groupID, msg.getStringProperty("JMSXGroupID")); Assert.assertEquals("testSupportsJMSXGroupID_1", msg.getText()); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -93,15 +84,12 @@ public class JMSXPropertyTest extends PTPTestCase * Test that the JMSX property JMSXDeliveryCount works. */ @Test - public void testJMSXDeliveryCount() throws Exception - { - if (!supportsJMSXDeliveryCount()) - { + public void testJMSXDeliveryCount() throws Exception { + if (!supportsJMSXDeliveryCount()) { return; } - try - { + try { senderConnection.stop(); // senderSession has been created as non transacted // we create it again but as a transacted session @@ -117,8 +105,7 @@ public class JMSXPropertyTest extends PTPTestCase receiverSession = receiverConnection.createQueueSession(true, 0); Assert.assertEquals(true, receiverSession.getTransacted()); // we create again the receiver - if (receiver != null) - { + if (receiver != null) { receiver.close(); } receiver = receiverSession.createReceiver(receiverQueue); @@ -135,7 +122,7 @@ public class JMSXPropertyTest extends PTPTestCase Message m = receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue(m != null); Assert.assertTrue(m instanceof TextMessage); - TextMessage msg = (TextMessage)m; + TextMessage msg = (TextMessage) m; // ... which is the one which was sent... Assert.assertEquals("testJMSXDeliveryCount", msg.getText()); // ...and has not been redelivered @@ -150,7 +137,7 @@ public class JMSXPropertyTest extends PTPTestCase m = receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue(m != null); Assert.assertTrue(m instanceof TextMessage); - msg = (TextMessage)m; + msg = (TextMessage) m; // ... which is still the one which was sent... Assert.assertEquals("testJMSXDeliveryCount", msg.getText()); // .. but this time, it has been redelivered @@ -159,12 +146,10 @@ public class JMSXPropertyTest extends PTPTestCase jmsxDeliveryCount = msg.getIntProperty("JMSXDeliveryCount"); Assert.assertEquals(2, jmsxDeliveryCount); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } - catch (Exception e) - { + catch (Exception e) { fail(e); } } @@ -172,15 +157,12 @@ public class JMSXPropertyTest extends PTPTestCase /** * checks if the JMSX property JMSXDeliveryCount is supported. */ - private boolean supportsJMSXDeliveryCount() throws Exception - { + private boolean supportsJMSXDeliveryCount() throws Exception { ConnectionMetaData metaData = senderConnection.getMetaData(); Enumeration enumeration = metaData.getJMSXPropertyNames(); - while (enumeration.hasMoreElements()) - { - String jmsxPropertyName = (String)enumeration.nextElement(); - if (jmsxPropertyName.equals("JMSXDeliveryCount")) - { + while (enumeration.hasMoreElements()) { + String jmsxPropertyName = (String) enumeration.nextElement(); + if (jmsxPropertyName.equals("JMSXDeliveryCount")) { return true; } } diff --git a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/properties/MessagePropertyConversionTest.java b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/properties/MessagePropertyConversionTest.java index cc8b6e8c5e..25d8cddaa4 100644 --- a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/properties/MessagePropertyConversionTest.java +++ b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/properties/MessagePropertyConversionTest.java @@ -55,24 +55,20 @@ import org.objectweb.jtests.jms.framework.PTPTestCase; * The cases marked with a Y should throw a java.lang.MessageFormatException if the * String is not a correct representation of the column type (otherwise, it returns the property). */ -public class MessagePropertyConversionTest extends PTPTestCase -{ +public class MessagePropertyConversionTest extends PTPTestCase { /** * if a property is set as a java.lang.String, * it can also be read as a java.lang.String. */ @Test - public void testString2String() - { - try - { + public void testString2String() { + try { Message message = senderSession.createMessage(); message.setStringProperty("pi", "3.14159"); Assert.assertEquals("3.14159", message.getStringProperty("pi")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -84,20 +80,16 @@ public class MessagePropertyConversionTest extends PTPTestCase * (e.g. "not a number"). */ @Test - public void testString2Double_2() - { - try - { + public void testString2Double_2() { + try { Message message = senderSession.createMessage(); message.setStringProperty("pi", "not_a_number"); message.getDoubleProperty("pi"); Assert.fail("sec. 3.5.4 The String to numeric conversions must throw the java.lang.NumberFormatException " + " if the numeric's valueOf() method does not accept the String value as a valid representation.\n"); } - catch (java.lang.NumberFormatException e) - { + catch (java.lang.NumberFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -108,16 +100,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * is a correct representation of a double (e.g. "3.14159"). */ @Test - public void testString2Double_1() - { - try - { + public void testString2Double_1() { + try { Message message = senderSession.createMessage(); message.setStringProperty("pi", "3.14159"); Assert.assertEquals(3.14159, message.getDoubleProperty("pi"), 0); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -129,20 +118,16 @@ public class MessagePropertyConversionTest extends PTPTestCase * (e.g. "not_a_number"). */ @Test - public void testString2Float_2() - { - try - { + public void testString2Float_2() { + try { Message message = senderSession.createMessage(); message.setStringProperty("pi", "not_a_number"); message.getFloatProperty("pi"); Assert.fail("sec. 3.5.4 The String to numeric conversions must throw the java.lang.NumberFormatException " + " if the numeric's valueOf() method does not accept the String value as a valid representation.\n"); } - catch (java.lang.NumberFormatException e) - { + catch (java.lang.NumberFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -153,16 +138,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * is a correct representation of a float (e.g. "3.14159"). */ @Test - public void testString2Float_1() - { - try - { + public void testString2Float_1() { + try { Message message = senderSession.createMessage(); message.setStringProperty("pi", "3.14159"); Assert.assertEquals(3.14159F, message.getFloatProperty("pi"), 0); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -174,20 +156,16 @@ public class MessagePropertyConversionTest extends PTPTestCase * (e.g. "3.14159"). */ @Test - public void testString2Long_2() - { - try - { + public void testString2Long_2() { + try { Message message = senderSession.createMessage(); message.setStringProperty("pi", "3.14159"); message.getLongProperty("pi"); Assert.fail("sec. 3.5.4 The String to numeric conversions must throw the java.lang.NumberFormatException " + " if the numeric's valueOf() method does not accept the String value as a valid representation.\n"); } - catch (java.lang.NumberFormatException e) - { + catch (java.lang.NumberFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -198,16 +176,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * is a correct representation of a long (e.g. "0"). */ @Test - public void testString2Long_1() - { - try - { + public void testString2Long_1() { + try { Message message = senderSession.createMessage(); message.setStringProperty("prop", "0"); Assert.assertEquals(0L, message.getLongProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -219,20 +194,16 @@ public class MessagePropertyConversionTest extends PTPTestCase * (e.g. "3.14159"). */ @Test - public void testString2Int_2() - { - try - { + public void testString2Int_2() { + try { Message message = senderSession.createMessage(); message.setStringProperty("pi", "3.14159"); message.getIntProperty("pi"); Assert.fail("sec. 3.5.4 The String to numeric conversions must throw the java.lang.NumberFormatException " + " if the numeric's valueOf() method does not accept the String value as a valid representation.\n"); } - catch (java.lang.NumberFormatException e) - { + catch (java.lang.NumberFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -243,16 +214,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * is a correct representation of a int (e.g. "0"). */ @Test - public void testString2Int_1() - { - try - { + public void testString2Int_1() { + try { Message message = senderSession.createMessage(); message.setStringProperty("prop", "0"); Assert.assertEquals(0, message.getIntProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -264,20 +232,16 @@ public class MessagePropertyConversionTest extends PTPTestCase * (e.g. "3.14159"). */ @Test - public void testString2Short_2() - { - try - { + public void testString2Short_2() { + try { Message message = senderSession.createMessage(); message.setStringProperty("pi", "3.14159"); message.getShortProperty("pi"); Assert.fail("sec. 3.5.4 The String to numeric conversions must throw the java.lang.NumberFormatException " + " if the numeric's valueOf() method does not accept the String value as a valid representation.\n"); } - catch (java.lang.NumberFormatException e) - { + catch (java.lang.NumberFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -288,16 +252,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * is a correct representation of a short (e.g. "0"). */ @Test - public void testString2Short_1() - { - try - { + public void testString2Short_1() { + try { Message message = senderSession.createMessage(); message.setStringProperty("prop", "0"); - Assert.assertEquals((short)0, message.getShortProperty("prop")); + Assert.assertEquals((short) 0, message.getShortProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -309,20 +270,16 @@ public class MessagePropertyConversionTest extends PTPTestCase * (e.g. "3.14159"). */ @Test - public void testString2Byte_2() - { - try - { + public void testString2Byte_2() { + try { Message message = senderSession.createMessage(); message.setStringProperty("pi", "3.14159"); message.getByteProperty("pi"); Assert.fail("sec. 3.5.4 The String to numeric conversions must throw the java.lang.NumberFormatException " + " if the numeric's valueOf() method does not accept the String value as a valid representation.\n"); } - catch (java.lang.NumberFormatException e) - { + catch (java.lang.NumberFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -333,16 +290,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * is a correct representation of a byte (e.g. "0"). */ @Test - public void testString2Byte_1() - { - try - { + public void testString2Byte_1() { + try { Message message = senderSession.createMessage(); message.setStringProperty("prop", "0"); - Assert.assertEquals((byte)0, message.getByteProperty("prop")); + Assert.assertEquals((byte) 0, message.getByteProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -354,19 +308,15 @@ public class MessagePropertyConversionTest extends PTPTestCase * returns false (e.g. "test") */ @Test - public void testString2Boolean_2() - { - try - { + public void testString2Boolean_2() { + try { Message message = senderSession.createMessage(); message.setStringProperty("prop", "test"); Assert.assertEquals(false, message.getBooleanProperty("prop")); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -377,16 +327,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * is a correct representation of a boolean (e.g. "true"). */ @Test - public void testString2Boolean_1() - { - try - { + public void testString2Boolean_1() { + try { Message message = senderSession.createMessage(); message.setStringProperty("prop", "true"); Assert.assertEquals(true, message.getBooleanProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -396,16 +343,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * it can also be read as a java.lang.String. */ @Test - public void testDouble2String() - { - try - { + public void testDouble2String() { + try { Message message = senderSession.createMessage(); message.setDoubleProperty("prop", 127.0); Assert.assertEquals("127.0", message.getStringProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -415,16 +359,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * it can also be read as a double. */ @Test - public void testDouble2Double() - { - try - { + public void testDouble2Double() { + try { Message message = senderSession.createMessage(); message.setDoubleProperty("prop", 127.0); Assert.assertEquals(127.0, message.getDoubleProperty("prop"), 0); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -434,20 +375,16 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a float throws a javax.jms.MessageFormatException. */ @Test - public void testDouble2Float() - { - try - { + public void testDouble2Float() { + try { Message message = senderSession.createMessage(); message.setDoubleProperty("prop", 127.0); message.getFloatProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -457,20 +394,16 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a long throws a javax.jms.MessageFormatException. */ @Test - public void testDouble2Long() - { - try - { + public void testDouble2Long() { + try { Message message = senderSession.createMessage(); message.setDoubleProperty("prop", 127.0); message.getLongProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -480,20 +413,16 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as an int throws a javax.jms.MessageFormatException. */ @Test - public void testDouble2Int() - { - try - { + public void testDouble2Int() { + try { Message message = senderSession.createMessage(); message.setDoubleProperty("prop", 127.0); message.getIntProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -503,21 +432,17 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a short throws a javax.jms.MessageFormatException. */ @Test - public void testDouble2Short() - { - try - { + public void testDouble2Short() { + try { Message message = senderSession.createMessage(); // store a value that can't be converted to short message.setDoubleProperty("prop", 127.0); message.getShortProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -527,21 +452,17 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a byte throws a javax.jms.MessageFormatException. */ @Test - public void testDouble2Byte() - { - try - { + public void testDouble2Byte() { + try { Message message = senderSession.createMessage(); // store a value that can't be converted to byte message.setDoubleProperty("prop", 127.0); message.getByteProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -551,21 +472,17 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a boolean throws a javax.jms.MessageFormatException. */ @Test - public void testDouble2Boolean() - { - try - { + public void testDouble2Boolean() { + try { Message message = senderSession.createMessage(); // store a value that can be converted to boolean message.setDoubleProperty("prop", 127.0); message.getBooleanProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -575,16 +492,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * it can also be read as a String. */ @Test - public void testFloat2String() - { - try - { + public void testFloat2String() { + try { Message message = senderSession.createMessage(); message.setFloatProperty("prop", 127.0F); Assert.assertEquals("127.0", message.getStringProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -594,16 +508,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * it can also be read as a double. */ @Test - public void testFloat2Double() - { - try - { + public void testFloat2Double() { + try { Message message = senderSession.createMessage(); message.setFloatProperty("prop", 127.0F); Assert.assertEquals(127.0, message.getDoubleProperty("prop"), 0); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -613,16 +524,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * it can also be read as a float. */ @Test - public void testFloat2Float() - { - try - { + public void testFloat2Float() { + try { Message message = senderSession.createMessage(); message.setFloatProperty("prop", 127.0F); Assert.assertEquals(127.0F, message.getFloatProperty("prop"), 0); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -632,20 +540,16 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a long throws a javax.jms.MessageFormatException. */ @Test - public void testFloat2Long() - { - try - { + public void testFloat2Long() { + try { Message message = senderSession.createMessage(); message.setFloatProperty("prop", 127.0F); message.getLongProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -655,20 +559,16 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a int throws a javax.jms.MessageFormatException. */ @Test - public void testFloat2Int() - { - try - { + public void testFloat2Int() { + try { Message message = senderSession.createMessage(); message.setFloatProperty("prop", 127.0F); message.getIntProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -678,21 +578,17 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a short throws a javax.jms.MessageFormatException. */ @Test - public void testFloat2Short() - { - try - { + public void testFloat2Short() { + try { Message message = senderSession.createMessage(); // store a value that can't be converted to short message.setFloatProperty("prop", 127.0F); message.getShortProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -702,21 +598,17 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a byte throws a javax.jms.MessageFormatException. */ @Test - public void testFloat2Byte() - { - try - { + public void testFloat2Byte() { + try { Message message = senderSession.createMessage(); // store a value that can't be converted to byte message.setFloatProperty("prop", 127.0F); message.getByteProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -726,21 +618,17 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a boolean throws a javax.jms.MessageFormatException. */ @Test - public void testFloat2Boolean() - { - try - { + public void testFloat2Boolean() { + try { Message message = senderSession.createMessage(); // store a value that can be converted to boolean message.setFloatProperty("prop", 127.0F); message.getBooleanProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -750,16 +638,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * it can also be read as a String. */ @Test - public void testLong2String() - { - try - { + public void testLong2String() { + try { Message message = senderSession.createMessage(); message.setLongProperty("prop", 127L); Assert.assertEquals("127", message.getStringProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -769,20 +654,16 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a double throws a javax.jms.MessageFormatException. */ @Test - public void testLong2Double() - { - try - { + public void testLong2Double() { + try { Message message = senderSession.createMessage(); message.setLongProperty("prop", 127L); message.getDoubleProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -792,20 +673,16 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a float throws a javax.jms.MessageFormatException. */ @Test - public void testLong2Float() - { - try - { + public void testLong2Float() { + try { Message message = senderSession.createMessage(); message.setLongProperty("prop", 127L); message.getFloatProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -815,16 +692,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * it can also be read as a long. */ @Test - public void testLong2Long() - { - try - { + public void testLong2Long() { + try { Message message = senderSession.createMessage(); message.setLongProperty("prop", 127L); Assert.assertEquals(127L, message.getLongProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -834,20 +708,16 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as an int throws a javax.jms.MessageFormatException. */ @Test - public void testLong2Int() - { - try - { + public void testLong2Int() { + try { Message message = senderSession.createMessage(); message.setLongProperty("prop", 127L); message.getIntProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -857,21 +727,17 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a short throws a javax.jms.MessageFormatException. */ @Test - public void testLong2Short() - { - try - { + public void testLong2Short() { + try { Message message = senderSession.createMessage(); // store a value that can't be converted to short message.setLongProperty("prop", 127L); message.getShortProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -881,21 +747,17 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a byte throws a javax.jms.MessageFormatException. */ @Test - public void testLong2Byte() - { - try - { + public void testLong2Byte() { + try { Message message = senderSession.createMessage(); // store a value that can't be converted to byte message.setLongProperty("prop", 127L); message.getByteProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -905,21 +767,17 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a boolean throws a javax.jms.MessageFormatException. */ @Test - public void testLong2Boolean() - { - try - { + public void testLong2Boolean() { + try { Message message = senderSession.createMessage(); // store a value that can be converted to boolean message.setLongProperty("prop", 127L); message.getBooleanProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -929,16 +787,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * it can also be read as a String. */ @Test - public void testInt2String() - { - try - { + public void testInt2String() { + try { Message message = senderSession.createMessage(); message.setIntProperty("prop", 127); Assert.assertEquals("127", message.getStringProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -948,20 +803,16 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a double throws a javax.jms.MessageFormatException. */ @Test - public void testInt2Double() - { - try - { + public void testInt2Double() { + try { Message message = senderSession.createMessage(); message.setIntProperty("prop", 127); message.getDoubleProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -971,20 +822,16 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a float throws a javax.jms.MessageFormatException. */ @Test - public void testInt2Float() - { - try - { + public void testInt2Float() { + try { Message message = senderSession.createMessage(); message.setIntProperty("prop", 127); message.getFloatProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -994,16 +841,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * it can also be read as a long. */ @Test - public void testInt2Long() - { - try - { + public void testInt2Long() { + try { Message message = senderSession.createMessage(); message.setIntProperty("prop", 127); Assert.assertEquals(127L, message.getLongProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1013,16 +857,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * it can also be read as an int. */ @Test - public void testInt2Int() - { - try - { + public void testInt2Int() { + try { Message message = senderSession.createMessage(); message.setIntProperty("prop", 127); Assert.assertEquals(127, message.getIntProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1032,21 +873,17 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a short throws a javax.jms.MessageFormatException. */ @Test - public void testInt2Short() - { - try - { + public void testInt2Short() { + try { Message message = senderSession.createMessage(); // store a value that can't be converted to short message.setIntProperty("prop", Integer.MAX_VALUE); message.getShortProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1056,21 +893,17 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a byte throws a javax.jms.MessageFormatException. */ @Test - public void testInt2Byte() - { - try - { + public void testInt2Byte() { + try { Message message = senderSession.createMessage(); // store a value that can't be converted to byte message.setIntProperty("prop", Integer.MAX_VALUE); message.getByteProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1080,21 +913,17 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a boolean throws a javax.jms.MessageFormatException. */ @Test - public void testInt2Boolean() - { - try - { + public void testInt2Boolean() { + try { Message message = senderSession.createMessage(); // store a value that can be converted to boolean message.setIntProperty("prop", Integer.MAX_VALUE); message.getBooleanProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1104,16 +933,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * it can also be read as a String. */ @Test - public void testShort2String() - { - try - { + public void testShort2String() { + try { Message message = senderSession.createMessage(); - message.setShortProperty("prop", (short)127); + message.setShortProperty("prop", (short) 127); Assert.assertEquals("127", message.getStringProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1123,20 +949,16 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a double throws a javax.jms.MessageFormatException. */ @Test - public void testShort2Double() - { - try - { + public void testShort2Double() { + try { Message message = senderSession.createMessage(); - message.setShortProperty("prop", (short)127); + message.setShortProperty("prop", (short) 127); message.getDoubleProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1146,20 +968,16 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a float throws a javax.jms.MessageFormatException. */ @Test - public void testShort2Float() - { - try - { + public void testShort2Float() { + try { Message message = senderSession.createMessage(); - message.setShortProperty("prop", (short)127); + message.setShortProperty("prop", (short) 127); message.getFloatProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1169,16 +987,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * it can also be read as a long. */ @Test - public void testShort2Long() - { - try - { + public void testShort2Long() { + try { Message message = senderSession.createMessage(); - message.setShortProperty("prop", (short)127); + message.setShortProperty("prop", (short) 127); Assert.assertEquals(127L, message.getLongProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1188,16 +1003,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * it can also be read as an int. */ @Test - public void testShort2Int() - { - try - { + public void testShort2Int() { + try { Message message = senderSession.createMessage(); - message.setShortProperty("prop", (short)127); + message.setShortProperty("prop", (short) 127); Assert.assertEquals(127, message.getIntProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1207,16 +1019,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * it can also be read as a short. */ @Test - public void testShort2Short() - { - try - { + public void testShort2Short() { + try { Message message = senderSession.createMessage(); - message.setShortProperty("prop", (short)127); - Assert.assertEquals((short)127, message.getShortProperty("prop")); + message.setShortProperty("prop", (short) 127); + Assert.assertEquals((short) 127, message.getShortProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1226,20 +1035,16 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a byte throws a javax.jms.MessageFormatException. */ @Test - public void testShort2Byte() - { - try - { + public void testShort2Byte() { + try { Message message = senderSession.createMessage(); - message.setShortProperty("prop", (short)127); + message.setShortProperty("prop", (short) 127); message.getByteProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1249,21 +1054,17 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a boolean throws a javax.jms.MessageFormatException. */ @Test - public void testShort2Boolean() - { - try - { + public void testShort2Boolean() { + try { Message message = senderSession.createMessage(); // store a value that can't be converted to boolean - message.setShortProperty("prop", (short)127); + message.setShortProperty("prop", (short) 127); message.getBooleanProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1273,16 +1074,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * it can also be read as a String. */ @Test - public void testByte2String() - { - try - { + public void testByte2String() { + try { Message message = senderSession.createMessage(); - message.setByteProperty("prop", (byte)127); + message.setByteProperty("prop", (byte) 127); Assert.assertEquals("127", message.getStringProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1292,20 +1090,16 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a double throws a javax.jms.MessageFormatException. */ @Test - public void testByte2Double() - { - try - { + public void testByte2Double() { + try { Message message = senderSession.createMessage(); - message.setByteProperty("prop", (byte)127); + message.setByteProperty("prop", (byte) 127); message.getDoubleProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1315,20 +1109,16 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a float throws a javax.jms.MessageFormatException. */ @Test - public void testByte2Float() - { - try - { + public void testByte2Float() { + try { Message message = senderSession.createMessage(); - message.setByteProperty("prop", (byte)127); + message.setByteProperty("prop", (byte) 127); message.getFloatProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1338,16 +1128,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * it can also be read as a long. */ @Test - public void testByte2Long() - { - try - { + public void testByte2Long() { + try { Message message = senderSession.createMessage(); - message.setByteProperty("prop", (byte)127); + message.setByteProperty("prop", (byte) 127); Assert.assertEquals(127L, message.getLongProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1357,16 +1144,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * it can also be read as an int. */ @Test - public void testByte2Int() - { - try - { + public void testByte2Int() { + try { Message message = senderSession.createMessage(); - message.setByteProperty("prop", (byte)127); + message.setByteProperty("prop", (byte) 127); Assert.assertEquals(127, message.getIntProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1376,16 +1160,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * it can also be read as a short. */ @Test - public void testByte2Short() - { - try - { + public void testByte2Short() { + try { Message message = senderSession.createMessage(); - message.setByteProperty("prop", (byte)127); - Assert.assertEquals((short)127, message.getShortProperty("prop")); + message.setByteProperty("prop", (byte) 127); + Assert.assertEquals((short) 127, message.getShortProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1395,16 +1176,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * it can also be read as a byte. */ @Test - public void testByte2Byte() - { - try - { + public void testByte2Byte() { + try { Message message = senderSession.createMessage(); - message.setByteProperty("prop", (byte)127); - Assert.assertEquals((byte)127, message.getByteProperty("prop")); + message.setByteProperty("prop", (byte) 127); + Assert.assertEquals((byte) 127, message.getByteProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1414,21 +1192,17 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a boolean throws a javax.jms.MessageFormatException. */ @Test - public void testByte2Boolean() - { - try - { + public void testByte2Boolean() { + try { Message message = senderSession.createMessage(); // store a value that can't be converted to boolean - message.setByteProperty("prop", (byte)127); + message.setByteProperty("prop", (byte) 127); message.getBooleanProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1438,16 +1212,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * it can also be read as a String. */ @Test - public void testBoolean2String() - { - try - { + public void testBoolean2String() { + try { Message message = senderSession.createMessage(); message.setBooleanProperty("prop", true); Assert.assertEquals("true", message.getStringProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1457,21 +1228,17 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a double throws a javax.jms.MessageFormatException. */ @Test - public void testBoolean2Double() - { - try - { + public void testBoolean2Double() { + try { Message message = senderSession.createMessage(); // store a value that can't be converted to double message.setBooleanProperty("prop", true); message.getDoubleProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1481,21 +1248,17 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a float throws a javax.jms.MessageFormatException. */ @Test - public void testBoolean2Float() - { - try - { + public void testBoolean2Float() { + try { Message message = senderSession.createMessage(); // store a value that can't be converted to float message.setBooleanProperty("prop", true); message.getFloatProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1505,21 +1268,17 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a long throws a javax.jms.MessageFormatException. */ @Test - public void testBoolean2Long() - { - try - { + public void testBoolean2Long() { + try { Message message = senderSession.createMessage(); // store a value that can't be converted to long message.setBooleanProperty("true", true); message.getLongProperty("true"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1529,21 +1288,17 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a int throws a javax.jms.MessageFormatException. */ @Test - public void testBoolean2Int() - { - try - { + public void testBoolean2Int() { + try { Message message = senderSession.createMessage(); // store a value that can't be converted to int message.setBooleanProperty("prop", true); message.getIntProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1553,21 +1308,17 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a short throws a javax.jms.MessageFormatException. */ @Test - public void testBoolean2Short() - { - try - { + public void testBoolean2Short() { + try { Message message = senderSession.createMessage(); // store a value that can't be converted to short message.setBooleanProperty("prop", true); message.getShortProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1577,21 +1328,17 @@ public class MessagePropertyConversionTest extends PTPTestCase * to get is as a byte throws a javax.jms.MessageFormatException. */ @Test - public void testBoolean2Byte() - { - try - { + public void testBoolean2Byte() { + try { Message message = senderSession.createMessage(); // store a value that can't be converted to byte message.setBooleanProperty("prop", true); message.getByteProperty("prop"); Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -1601,16 +1348,13 @@ public class MessagePropertyConversionTest extends PTPTestCase * it can also be read as a boolean. */ @Test - public void testBoolean2Boolean() - { - try - { + public void testBoolean2Boolean() { + try { Message message = senderSession.createMessage(); message.setBooleanProperty("prop", true); Assert.assertEquals(true, message.getBooleanProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } diff --git a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/properties/MessagePropertyTest.java b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/properties/MessagePropertyTest.java index 2f061814c4..28257db3c6 100644 --- a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/properties/MessagePropertyTest.java +++ b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/properties/MessagePropertyTest.java @@ -31,10 +31,9 @@ import org.objectweb.jtests.jms.framework.PTPTestCase; /** * Test the javax.jms.Message properties. *
    - * See JMS Specification, sec. 3.5 Message Properties (p.32-37) + * See JMS Specification, sec. 3.5 Message Properties (p.32-37) */ -public class MessagePropertyTest extends PTPTestCase -{ +public class MessagePropertyTest extends PTPTestCase { /** * Test that any other class than Boolean, Byte, Short, Integer, Long, @@ -42,19 +41,15 @@ public class MessagePropertyTest extends PTPTestCase * method throws a javax.jms.MessageFormatException. */ @Test - public void testSetObjectProperty_2() - { - try - { + public void testSetObjectProperty_2() { + try { Message message = senderSession.createMessage(); message.setObjectProperty("prop", new Vector()); Assert.fail("sec. 3.5.5 An attempt to use any other class [than Boolean, Byte,...,String] must throw " + "a JMS MessageFormatException.\n"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("Should throw a javax.jms.MessageFormatException, not a " + e); } } @@ -64,16 +59,13 @@ public class MessagePropertyTest extends PTPTestCase * method, it can be retrieve directly as a double by Message.getFloatProperty() */ @Test - public void testSetObjectProperty_1() - { - try - { + public void testSetObjectProperty_1() { + try { Message message = senderSession.createMessage(); message.setObjectProperty("pi", new Float(3.14159f)); Assert.assertEquals(3.14159f, message.getFloatProperty("pi"), 0); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -83,17 +75,12 @@ public class MessagePropertyTest extends PTPTestCase * if a property by the specified name does not exits. */ @Test - public void testGetObjectProperty() - { - try - { + public void testGetObjectProperty() { + try { Message message = senderSession.createMessage(); - Assert.assertEquals("sec. 3.5.5 A null value is returned [by the getObjectProperty method] if a property by the specified " + "name does not exits.\n", - null, - message.getObjectProperty("prop")); + Assert.assertEquals("sec. 3.5.5 A null value is returned [by the getObjectProperty method] if a property by the specified " + "name does not exits.\n", null, message.getObjectProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -103,17 +90,12 @@ public class MessagePropertyTest extends PTPTestCase * if a property by the specified name does not exits. */ @Test - public void testGetStringProperty() - { - try - { + public void testGetStringProperty() { + try { Message message = senderSession.createMessage(); - Assert.assertEquals("sec. 3.5.5 A null value is returned [by the getStringProperty method] if a property by the specified " + "name does not exits.\n", - null, - message.getStringProperty("prop")); + Assert.assertEquals("sec. 3.5.5 A null value is returned [by the getStringProperty method] if a property by the specified " + "name does not exits.\n", null, message.getStringProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -123,19 +105,15 @@ public class MessagePropertyTest extends PTPTestCase * a java.lang.NullPointerException */ @Test - public void testGetDoubleProperty() - { - try - { + public void testGetDoubleProperty() { + try { Message message = senderSession.createMessage(); message.getDoubleProperty("prop"); Assert.fail("Should raise a NullPointerException.\n"); } - catch (NullPointerException e) - { + catch (NullPointerException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -145,19 +123,15 @@ public class MessagePropertyTest extends PTPTestCase * a java.lang.NullPointerException */ @Test - public void testGetFloatProperty() - { - try - { + public void testGetFloatProperty() { + try { Message message = senderSession.createMessage(); message.getFloatProperty("prop"); Assert.fail("Should raise a NullPointerException.\n"); } - catch (NullPointerException e) - { + catch (NullPointerException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -167,19 +141,15 @@ public class MessagePropertyTest extends PTPTestCase * a java.lang.NumberFormatException */ @Test - public void testGetLongProperty() - { - try - { + public void testGetLongProperty() { + try { Message message = senderSession.createMessage(); message.getLongProperty("prop"); Assert.fail("Should raise a NumberFormatException.\n"); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -189,19 +159,15 @@ public class MessagePropertyTest extends PTPTestCase * a java.lang.NumberFormatException */ @Test - public void testGetIntProperty() - { - try - { + public void testGetIntProperty() { + try { Message message = senderSession.createMessage(); message.getIntProperty("prop"); Assert.fail("Should raise a NumberFormatException.\n"); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -211,19 +177,15 @@ public class MessagePropertyTest extends PTPTestCase * a java.lang.NumberFormatException */ @Test - public void testGetShortProperty() - { - try - { + public void testGetShortProperty() { + try { Message message = senderSession.createMessage(); message.getShortProperty("prop"); Assert.fail("Should raise a NumberFormatException.\n"); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -233,19 +195,15 @@ public class MessagePropertyTest extends PTPTestCase * a java.lang.NumberFormatException */ @Test - public void testGetByteProperty() - { - try - { + public void testGetByteProperty() { + try { Message message = senderSession.createMessage(); message.getByteProperty("prop"); Assert.fail("Should raise a NumberFormatException.\n"); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -255,15 +213,12 @@ public class MessagePropertyTest extends PTPTestCase * returns false */ @Test - public void testGetBooleanProperty() - { - try - { + public void testGetBooleanProperty() { + try { Message message = senderSession.createMessage(); Assert.assertEquals(false, message.getBooleanProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -273,24 +228,19 @@ public class MessagePropertyTest extends PTPTestCase * the name of the JMS standard header fields (e.g. JMSCorrelationID). */ @Test - public void testGetPropertyNames() - { - try - { + public void testGetPropertyNames() { + try { Message message = senderSession.createMessage(); message.setJMSCorrelationID("foo"); Enumeration enumeration = message.getPropertyNames(); - while (enumeration.hasMoreElements()) - { - String propName = (String)enumeration.nextElement(); + while (enumeration.hasMoreElements()) { + String propName = (String) enumeration.nextElement(); boolean valid = !propName.startsWith("JMS") || propName.startsWith("JMSX"); Assert.assertTrue("sec. 3.5.6 The getPropertyNames method does not return the names of " + "the JMS standard header field [e.g. JMSCorrelationID]: " + - propName, - valid); + propName, valid); } } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -299,16 +249,13 @@ public class MessagePropertyTest extends PTPTestCase * Test that the Message.getPropertyNames() methods. */ @Test - public void testPropertyIteration() - { - try - { + public void testPropertyIteration() { + try { Message message = senderSession.createMessage(); Enumeration enumeration = message.getPropertyNames(); // there can be some properties already defined (e.g. JMSXDeliveryCount) int originalCount = 0; - while (enumeration.hasMoreElements()) - { + while (enumeration.hasMoreElements()) { enumeration.nextElement(); originalCount++; } @@ -316,20 +263,17 @@ public class MessagePropertyTest extends PTPTestCase enumeration = message.getPropertyNames(); boolean foundPiProperty = false; int newCount = 0; - while (enumeration.hasMoreElements()) - { - String propName = (String)enumeration.nextElement(); + while (enumeration.hasMoreElements()) { + String propName = (String) enumeration.nextElement(); newCount++; - if ("pi".equals(propName)) - { + if ("pi".equals(propName)) { foundPiProperty = true; } } Assert.assertEquals(originalCount + 1, newCount); Assert.assertTrue(foundPiProperty); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -339,19 +283,14 @@ public class MessagePropertyTest extends PTPTestCase * value of the Message's body. */ @Test - public void testClearProperties_2() - { - try - { + public void testClearProperties_2() { + try { TextMessage message = senderSession.createTextMessage(); message.setText("foo"); message.clearProperties(); - Assert.assertEquals("sec. 3.5.7 Clearing a message's property entries does not clear the value of its body.\n", - "foo", - message.getText()); + Assert.assertEquals("sec. 3.5.7 Clearing a message's property entries does not clear the value of its body.\n", "foo", message.getText()); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -361,19 +300,14 @@ public class MessagePropertyTest extends PTPTestCase * properties of the Message. */ @Test - public void testClearProperties_1() - { - try - { + public void testClearProperties_1() { + try { TextMessage message = senderSession.createTextMessage(); message.setStringProperty("prop", "foo"); message.clearProperties(); - Assert.assertEquals("sec. 3.5.7 A message's properties are deleted by the clearProperties method.\n", - null, - message.getStringProperty("prop")); + Assert.assertEquals("sec. 3.5.7 A message's properties are deleted by the clearProperties method.\n", null, message.getStringProperty("prop")); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } diff --git a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/queue/QueueBrowserTest.java b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/queue/QueueBrowserTest.java index 5323d9e788..cada29a358 100644 --- a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/queue/QueueBrowserTest.java +++ b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/queue/QueueBrowserTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.objectweb.jtests.jms.conform.queue; + import java.util.Enumeration; import javax.jms.JMSException; @@ -32,8 +33,7 @@ import org.objectweb.jtests.jms.framework.TestConfig; /** * Test the javax.jms.QueueBrowser features. */ -public class QueueBrowserTest extends PTPTestCase -{ +public class QueueBrowserTest extends PTPTestCase { /** * The QueueBrowser of the receiver's session @@ -49,10 +49,8 @@ public class QueueBrowserTest extends PTPTestCase * Test the QueueBrowser of the sender. */ @Test - public void testSenderBrowser() - { - try - { + public void testSenderBrowser() { + try { TextMessage message_1 = senderSession.createTextMessage(); message_1.setText("testBrowser:message_1"); TextMessage message_2 = senderSession.createTextMessage(); @@ -67,14 +65,13 @@ public class QueueBrowserTest extends PTPTestCase // ask the browser to browse the sender's session Enumeration enumeration = senderBrowser.getEnumeration(); int count = 0; - while (enumeration.hasMoreElements()) - { + while (enumeration.hasMoreElements()) { // one more message in the queue count++; // check that the message in the queue is one of the two which where sent Object obj = enumeration.nextElement(); Assert.assertTrue(obj instanceof TextMessage); - TextMessage msg = (TextMessage)obj; + TextMessage msg = (TextMessage) obj; Assert.assertTrue(msg.getText().startsWith("testBrowser:message_")); } // check that there is effectively 2 messages in the queue @@ -85,14 +82,14 @@ public class QueueBrowserTest extends PTPTestCase Message m = receiver.receive(TestConfig.TIMEOUT); // ... and check it is the first which was sent. Assert.assertTrue(m instanceof TextMessage); - TextMessage msg = (TextMessage)m; + TextMessage msg = (TextMessage) m; Assert.assertEquals("testBrowser:message_1", msg.getText()); // receive the second message... m = receiver.receive(TestConfig.TIMEOUT); // ... and check it is the second which was sent. Assert.assertTrue(m instanceof TextMessage); - msg = (TextMessage)m; + msg = (TextMessage) m; Assert.assertEquals("testBrowser:message_2", msg.getText()); // ask the browser to browse the sender's session @@ -102,8 +99,7 @@ public class QueueBrowserTest extends PTPTestCase // from the queue) Assert.assertTrue(!enumeration.hasMoreElements()); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -113,10 +109,8 @@ public class QueueBrowserTest extends PTPTestCase * browses only the messages matching this selector. */ @Test - public void testBrowserWithMessageSelector() - { - try - { + public void testBrowserWithMessageSelector() { + try { senderBrowser = senderSession.createBrowser(senderQueue, "pi = 3.14159"); receiver.close(); @@ -132,53 +126,44 @@ public class QueueBrowserTest extends PTPTestCase Enumeration enumeration = senderBrowser.getEnumeration(); int count = 0; - while (enumeration.hasMoreElements()) - { + while (enumeration.hasMoreElements()) { count++; Object obj = enumeration.nextElement(); Assert.assertTrue(obj instanceof TextMessage); - TextMessage msg = (TextMessage)obj; + TextMessage msg = (TextMessage) obj; Assert.assertEquals("testBrowserWithMessageSelector:message_2", msg.getText()); } Assert.assertEquals(1, count); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @Override @Before - public void setUp() throws Exception - { - try - { + public void setUp() throws Exception { + try { super.setUp(); receiverBrowser = receiverSession.createBrowser(receiverQueue); senderBrowser = senderSession.createBrowser(senderQueue); } - catch (JMSException e) - { + catch (JMSException e) { throw new RuntimeException(e); } } @Override @After - public void tearDown() throws Exception - { - try - { + public void tearDown() throws Exception { + try { receiverBrowser.close(); senderBrowser.close(); super.tearDown(); } - catch (JMSException ignored) - { + catch (JMSException ignored) { } - finally - { + finally { receiverBrowser = null; senderBrowser = null; } diff --git a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/queue/TemporaryQueueTest.java b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/queue/TemporaryQueueTest.java index 40f7200582..9132c46e0e 100644 --- a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/queue/TemporaryQueueTest.java +++ b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/queue/TemporaryQueueTest.java @@ -30,8 +30,7 @@ import org.objectweb.jtests.jms.framework.TestConfig; /** * Test the javax.jms.TemporaryQueue features. */ -public class TemporaryQueueTest extends PTPTestCase -{ +public class TemporaryQueueTest extends PTPTestCase { private TemporaryQueue tempQueue; @@ -41,10 +40,8 @@ public class TemporaryQueueTest extends PTPTestCase * Test a TemporaryQueue */ @Test - public void testTemporaryQueue() - { - try - { + public void testTemporaryQueue() { + try { // we stop both sender and receiver connections senderConnection.stop(); receiverConnection.stop(); @@ -64,11 +61,10 @@ public class TemporaryQueueTest extends PTPTestCase Message m = tempReceiver.receive(TestConfig.TIMEOUT); Assert.assertTrue(m instanceof TextMessage); - TextMessage msg = (TextMessage)m; + TextMessage msg = (TextMessage) m; Assert.assertEquals("testTemporaryQueue", msg.getText()); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } diff --git a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/selector/SelectorSyntaxTest.java b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/selector/SelectorSyntaxTest.java index 573651bde6..5c35673856 100644 --- a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/selector/SelectorSyntaxTest.java +++ b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/selector/SelectorSyntaxTest.java @@ -26,8 +26,8 @@ import org.objectweb.jtests.jms.framework.PTPTestCase; /** * Test the syntax of of message selector of JMS */ -public class SelectorSyntaxTest extends PTPTestCase -{ +public class SelectorSyntaxTest extends PTPTestCase { + /** * Test that identifiers that start with a valid Java identifier start character are valid. * A valid identifier means that the method Character.isJavaIdentifierStart returns @@ -36,23 +36,18 @@ public class SelectorSyntaxTest extends PTPTestCase * @see Character.isJavaIdentifierStart(char) */ @Test - public void testValidIdentifiersStart() - { + public void testValidIdentifiersStart() { String identifier = null; - try - { + try { identifier = "_correct"; - Assert.assertTrue(identifier + " starts with an invalid Java identifier start character", - Character.isJavaIdentifierStart(identifier.charAt(0))); + Assert.assertTrue(identifier + " starts with an invalid Java identifier start character", Character.isJavaIdentifierStart(identifier.charAt(0))); receiver = receiverSession.createReceiver(receiverQueue, identifier + " IS NULL"); identifier = "$correct"; - Assert.assertTrue(identifier + " starts with an invalid Java identifier start character", - Character.isJavaIdentifierStart(identifier.charAt(0))); + Assert.assertTrue(identifier + " starts with an invalid Java identifier start character", Character.isJavaIdentifierStart(identifier.charAt(0))); receiver = receiverSession.createReceiver(receiverQueue, identifier + " IS NULL"); } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail(identifier + " is a correct identifier. \n" + e); } } @@ -63,33 +58,26 @@ public class SelectorSyntaxTest extends PTPTestCase * @see #testValidIdentifiersStart() */ @Test - public void testInvalidIdentifiersStart() - { + public void testInvalidIdentifiersStart() { String identifier = null; - try - { + try { identifier = "1uncorrect"; - Assert.assertTrue(identifier + " starts with an invalid Java identifier start character", - !Character.isJavaIdentifierStart(identifier.charAt(0))); + Assert.assertTrue(identifier + " starts with an invalid Java identifier start character", !Character.isJavaIdentifierStart(identifier.charAt(0))); receiver = receiverSession.createReceiver(receiverQueue, identifier + " IS NULL"); Assert.fail(identifier + " starts with an invalid Java identifier start character"); } - catch (JMSException e) - { + catch (JMSException e) { } - try - { + try { identifier = "%uncorrect"; - Assert.assertTrue(identifier + " starts with an invalid Java identifier start character", - !Character.isJavaIdentifierStart(identifier.charAt(0))); + Assert.assertTrue(identifier + " starts with an invalid Java identifier start character", !Character.isJavaIdentifierStart(identifier.charAt(0))); receiver = receiverSession.createReceiver(receiverQueue, identifier + " IS NULL"); Assert.fail(identifier + " starts with an invalid Java identifier start character"); } - catch (JMSException e) - { + catch (JMSException e) { } } @@ -98,14 +86,11 @@ public class SelectorSyntaxTest extends PTPTestCase * Test that message selector can be an empty string. */ @Test - public void testEmptyStringAsSelector() - { - try - { + public void testEmptyStringAsSelector() { + try { receiver = receiverSession.createReceiver(receiverQueue, ""); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -114,18 +99,14 @@ public class SelectorSyntaxTest extends PTPTestCase * Test that identifiers can't be NULL. */ @Test - public void testIdentifierNULL() - { - try - { + public void testIdentifierNULL() { + try { receiver = receiverSession.createReceiver(receiverQueue, "NULL = ZERO"); Assert.fail("NULL is not a valid identifier"); } - catch (InvalidSelectorException e) - { + catch (InvalidSelectorException e) { } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -134,15 +115,12 @@ public class SelectorSyntaxTest extends PTPTestCase * Test that identifiers can't be TRUE. */ @Test - public void testIdentifierTRUE() - { - try - { + public void testIdentifierTRUE() { + try { receiver = receiverSession.createReceiver(receiverQueue, "TRUE > 0"); Assert.fail("TRUE is not a valid identifier"); } - catch (JMSException e) - { + catch (JMSException e) { } } @@ -150,15 +128,12 @@ public class SelectorSyntaxTest extends PTPTestCase * Test that identifiers can't be FALSE. */ @Test - public void testIdentifierFALSE() - { - try - { + public void testIdentifierFALSE() { + try { receiver = receiverSession.createReceiver(receiverQueue, "FALSE > 0"); Assert.fail("FALSE is not a valid identifier"); } - catch (JMSException e) - { + catch (JMSException e) { } } @@ -166,15 +141,12 @@ public class SelectorSyntaxTest extends PTPTestCase * Test that identifiers can't be NOT. */ @Test - public void testIdentifierNOT() - { - try - { + public void testIdentifierNOT() { + try { receiver = receiverSession.createReceiver(receiverQueue, "NOT > 0"); Assert.fail("NOT is not a valid identifier"); } - catch (JMSException e) - { + catch (JMSException e) { } } @@ -182,15 +154,12 @@ public class SelectorSyntaxTest extends PTPTestCase * Test that identifiers can't be AND. */ @Test - public void testIdentifierAND() - { - try - { + public void testIdentifierAND() { + try { receiver = receiverSession.createReceiver(receiverQueue, "AND > 0"); Assert.fail("AND is not a valid identifier"); } - catch (JMSException e) - { + catch (JMSException e) { } } @@ -198,15 +167,12 @@ public class SelectorSyntaxTest extends PTPTestCase * Test that identifiers can't be OR. */ @Test - public void testIdentifierOR() - { - try - { + public void testIdentifierOR() { + try { receiver = receiverSession.createReceiver(receiverQueue, "OR > 0"); Assert.fail("OR is not a valid identifier"); } - catch (JMSException e) - { + catch (JMSException e) { } } @@ -214,15 +180,12 @@ public class SelectorSyntaxTest extends PTPTestCase * Test that identifiers can't be BETWEEN. */ @Test - public void testIdentifierBETWEEN() - { - try - { + public void testIdentifierBETWEEN() { + try { receiver = receiverSession.createReceiver(receiverQueue, "BETWEEN > 0"); Assert.fail("BETWEEN is not a valid identifier"); } - catch (JMSException e) - { + catch (JMSException e) { } } @@ -230,15 +193,12 @@ public class SelectorSyntaxTest extends PTPTestCase * Test that identifiers can't be LIKE. */ @Test - public void testIdentifierLIKE() - { - try - { + public void testIdentifierLIKE() { + try { receiver = receiverSession.createReceiver(receiverQueue, "LIKE > 0"); Assert.fail("LIKE is not a valid identifier"); } - catch (JMSException e) - { + catch (JMSException e) { } } @@ -246,15 +206,12 @@ public class SelectorSyntaxTest extends PTPTestCase * Test that identifiers can't be IN. */ @Test - public void testIdentifierIN() - { - try - { + public void testIdentifierIN() { + try { receiver = receiverSession.createReceiver(receiverQueue, "IN > 0"); Assert.fail("IN is not a valid identifier"); } - catch (JMSException e) - { + catch (JMSException e) { } } @@ -262,15 +219,12 @@ public class SelectorSyntaxTest extends PTPTestCase * Test that identifiers can't be IS. */ @Test - public void testIdentifierIS() - { - try - { + public void testIdentifierIS() { + try { receiver = receiverSession.createReceiver(receiverQueue, "IS > 0"); Assert.fail("IS is not a valid identifier"); } - catch (JMSException e) - { + catch (JMSException e) { } } @@ -278,15 +232,12 @@ public class SelectorSyntaxTest extends PTPTestCase * Test that identifiers can't be ESCAPE. */ @Test - public void testIdentifierESCAPE() - { - try - { + public void testIdentifierESCAPE() { + try { receiver = receiverSession.createReceiver(receiverQueue, "ESCAPE > 0"); Assert.fail("ESCAPE is not a valid identifier"); } - catch (JMSException e) - { + catch (JMSException e) { } } @@ -294,15 +245,12 @@ public class SelectorSyntaxTest extends PTPTestCase * Test syntax of "identifier IS [NOT] NULL" */ @Test - public void testNull() - { - try - { + public void testNull() { + try { receiver = receiverSession.createReceiver(receiverQueue, "prop_name IS NULL"); receiver = receiverSession.createReceiver(receiverQueue, "prop_name IS NOT NULL"); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -311,17 +259,14 @@ public class SelectorSyntaxTest extends PTPTestCase * Test syntax of "identifier [NOT] LIKE pattern-value [ESCAPE escape-character]" */ @Test - public void testLike() - { - try - { + public void testLike() { + try { receiver = receiverSession.createReceiver(receiverQueue, "phone LIKE '12%3'"); receiver = receiverSession.createReceiver(receiverQueue, "word LIKE 'l_se'"); receiver = receiverSession.createReceiver(receiverQueue, "underscored LIKE '\\_%' ESCAPE '\\'"); receiver = receiverSession.createReceiver(receiverQueue, "phone NOT LIKE '12%3'"); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -330,15 +275,12 @@ public class SelectorSyntaxTest extends PTPTestCase * Test syntax of "identifier [NOT] IN (string-literal1, string-literal2,...)" */ @Test - public void testIn() - { - try - { + public void testIn() { + try { receiver = receiverSession.createReceiver(receiverQueue, "Country IN ('UK', 'US', 'France')"); receiver = receiverSession.createReceiver(receiverQueue, "Country NOT IN ('UK', 'US', 'France')"); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -347,15 +289,12 @@ public class SelectorSyntaxTest extends PTPTestCase * Test syntax of "arithmetic-expr1 [NOT] BETWEEN arithmetic-expr2 and arithmetic-expr3" */ @Test - public void testBetween() - { - try - { + public void testBetween() { + try { receiver = receiverSession.createReceiver(receiverQueue, "age BETWEEN 15 and 19"); receiver = receiverSession.createReceiver(receiverQueue, "age NOT BETWEEN 15 and 19"); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -364,16 +303,13 @@ public class SelectorSyntaxTest extends PTPTestCase * Test diffent syntax for approximate numeric literal (+6.2, -95.7, 7.) */ @Test - public void testApproximateNumericLiteral() - { - try - { + public void testApproximateNumericLiteral() { + try { receiver = receiverSession.createReceiver(receiverQueue, "average = +6.2"); receiver = receiverSession.createReceiver(receiverQueue, "average = -95.7"); receiver = receiverSession.createReceiver(receiverQueue, "average = 7."); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -382,16 +318,13 @@ public class SelectorSyntaxTest extends PTPTestCase * Test diffent syntax for exact numeric literal (+62, -957, 57) */ @Test - public void testExactNumericLiteral() - { - try - { + public void testExactNumericLiteral() { + try { receiver = receiverSession.createReceiver(receiverQueue, "average = +62"); receiver = receiverSession.createReceiver(receiverQueue, "max = -957"); receiver = receiverSession.createReceiver(receiverQueue, "max = 57"); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -400,16 +333,13 @@ public class SelectorSyntaxTest extends PTPTestCase * Test diffent syntax for zero as an exact or an approximate numeric literal (0, 0.0, 0.) */ @Test - public void testZero() - { - try - { + public void testZero() { + try { receiver = receiverSession.createReceiver(receiverQueue, "max = 0"); receiver = receiverSession.createReceiver(receiverQueue, "max = 0.0"); receiver = receiverSession.createReceiver(receiverQueue, "max = 0."); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -418,15 +348,12 @@ public class SelectorSyntaxTest extends PTPTestCase * Test diffent syntax for string literal ('literal' and 'literal''s') */ @Test - public void testString() - { - try - { + public void testString() { + try { receiver = receiverSession.createReceiver(receiverQueue, "string = 'literal'"); receiver = receiverSession.createReceiver(receiverQueue, "string = 'literal''s'"); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } diff --git a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/selector/SelectorTest.java b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/selector/SelectorTest.java index eb76a08e87..759cfca9dc 100644 --- a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/selector/SelectorTest.java +++ b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/selector/SelectorTest.java @@ -27,18 +27,15 @@ import org.objectweb.jtests.jms.framework.TestConfig; /** * Test the message selector features of JMS */ -public class SelectorTest extends PTPTestCase -{ +public class SelectorTest extends PTPTestCase { /** * Test that an empty string as a message selector indicates that there * is no message selector for the message consumer. */ @Test - public void testEmptyStringAsSelector() throws Exception - { - if (receiver != null) - { + public void testEmptyStringAsSelector() throws Exception { + if (receiver != null) { receiver.close(); } receiver = receiverSession.createReceiver(receiverQueue, ""); @@ -47,7 +44,7 @@ public class SelectorTest extends PTPTestCase message.setText("testEmptyStringAsSelector"); sender.send(message); - TextMessage msg = (TextMessage)receiver.receive(TestConfig.TIMEOUT); + TextMessage msg = (TextMessage) receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue("No message was received", msg != null); Assert.assertEquals("testEmptyStringAsSelector", msg.getText()); } @@ -56,15 +53,13 @@ public class SelectorTest extends PTPTestCase * Tats that String literals are well handled by the message selector. *
    *
      - *
    • "string = 'literal''s;" is true for "literal's" and false for "literal"
    • + *
    • "string = 'literal''s;" is true for "literal's" and false for "literal"
    • *
    */ @Test - public void testStringLiterals() throws Exception - { - if (receiver != null) - { + public void testStringLiterals() throws Exception { + if (receiver != null) { receiver.close(); } receiver = receiverSession.createReceiver(receiverQueue, "string = 'literal''s'"); @@ -79,7 +74,7 @@ public class SelectorTest extends PTPTestCase message.setText("testStringLiterals:2"); sender.send(message); - TextMessage msg = (TextMessage)receiver.receive(TestConfig.TIMEOUT); + TextMessage msg = (TextMessage) receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue("No message was received", msg != null); Assert.assertEquals("testStringLiterals:2", msg.getText()); } @@ -89,10 +84,8 @@ public class SelectorTest extends PTPTestCase * or 'NON_PERSISTENT' when used in a message selector (chapter 3.8.1.3). */ @Test - public void testJMSDeliveryModeInSelector() throws Exception - { - if (receiver != null) - { + public void testJMSDeliveryModeInSelector() throws Exception { + if (receiver != null) { receiver.close(); } receiver = receiverSession.createReceiver(receiverQueue, "JMSDeliveryMode = 'PERSISTENT'"); @@ -107,7 +100,7 @@ public class SelectorTest extends PTPTestCase // send a message in *persistent* sender.send(message, DeliveryMode.PERSISTENT, sender.getPriority(), sender.getTimeToLive()); - TextMessage msg = (TextMessage)receiver.receive(TestConfig.TIMEOUT); + TextMessage msg = (TextMessage) receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue("No message was received", msg != null); // only the message sent in persistent mode should be received. Assert.assertEquals(DeliveryMode.PERSISTENT, msg.getJMSDeliveryMode()); @@ -120,10 +113,8 @@ public class SelectorTest extends PTPTestCase * Based on the example of chapter 3.8.1.1 about identifiers. */ @Test - public void testIdentifierConversion() throws Exception - { - if (receiver != null) - { + public void testIdentifierConversion() throws Exception { + if (receiver != null) { receiver.close(); } receiver = receiverSession.createReceiver(receiverQueue, "NumberOfOrders > 1"); @@ -138,7 +129,7 @@ public class SelectorTest extends PTPTestCase message.setText("testIdentifierConversion:2"); sender.send(message); - TextMessage msg = (TextMessage)receiver.receive(TestConfig.TIMEOUT); + TextMessage msg = (TextMessage) receiver.receive(TestConfig.TIMEOUT); Assert.assertEquals("testIdentifierConversion:2", msg.getText()); } @@ -146,14 +137,12 @@ public class SelectorTest extends PTPTestCase * Test the message selector using the filter example provided by the JMS specifications. *
    *
      - *
    • "JMSType = 'car' AND color = 'blue' AND weight > 2500"
    • + *
    • "JMSType = 'car' AND color = 'blue' AND weight > 2500"
    • *
    */ @Test - public void testSelectorExampleFromSpecs() throws Exception - { - if (receiver != null) - { + public void testSelectorExampleFromSpecs() throws Exception { + if (receiver != null) { receiver.close(); } receiver = receiverSession.createReceiver(receiverQueue, "JMSType = 'car' AND color = 'blue' AND weight > 2500"); @@ -172,7 +161,7 @@ public class SelectorTest extends PTPTestCase message.setText("testSelectorExampleFromSpecs:2"); sender.send(message); - TextMessage msg = (TextMessage)receiver.receive(TestConfig.TIMEOUT); + TextMessage msg = (TextMessage) receiver.receive(TestConfig.TIMEOUT); Assert.assertEquals("testSelectorExampleFromSpecs:2", msg.getText()); } @@ -180,14 +169,12 @@ public class SelectorTest extends PTPTestCase * Test the ">" condition in message selector. *
    *
      - *
    • "weight > 2500" is true for 3000 and false for 1000
    • + *
    • "weight > 2500" is true for 3000 and false for 1000
    • *
    */ @Test - public void testGreaterThan() throws Exception - { - if (receiver != null) - { + public void testGreaterThan() throws Exception { + if (receiver != null) { receiver.close(); } receiver = receiverSession.createReceiver(receiverQueue, "weight > 2500"); @@ -202,7 +189,7 @@ public class SelectorTest extends PTPTestCase message.setText("testGreaterThan:2"); sender.send(message); - TextMessage msg = (TextMessage)receiver.receive(TestConfig.TIMEOUT); + TextMessage msg = (TextMessage) receiver.receive(TestConfig.TIMEOUT); Assert.assertEquals("testGreaterThan:2", msg.getText()); } @@ -210,14 +197,12 @@ public class SelectorTest extends PTPTestCase * Test the "=" condition in message selector. *
    *
      - *
    • "weight = 2500" is true for 2500 and false for 1000
    • + *
    • "weight = 2500" is true for 2500 and false for 1000
    • *
    */ @Test - public void testEquals() throws Exception - { - if (receiver != null) - { + public void testEquals() throws Exception { + if (receiver != null) { receiver.close(); } receiver = receiverSession.createReceiver(receiverQueue, "weight = 2500"); @@ -232,7 +217,7 @@ public class SelectorTest extends PTPTestCase message.setText("testEquals:2"); sender.send(message); - TextMessage msg = (TextMessage)receiver.receive(TestConfig.TIMEOUT); + TextMessage msg = (TextMessage) receiver.receive(TestConfig.TIMEOUT); Assert.assertEquals("testEquals:2", msg.getText()); } @@ -240,14 +225,12 @@ public class SelectorTest extends PTPTestCase * Test the "<>" (not equal) condition in message selector. *
    *
      - *
    • "weight <> 2500" is true for 1000 and false for 2500
    • + *
    • "weight <> 2500" is true for 1000 and false for 2500
    • *
    */ @Test - public void testNotEquals() throws Exception - { - if (receiver != null) - { + public void testNotEquals() throws Exception { + if (receiver != null) { receiver.close(); } receiver = receiverSession.createReceiver(receiverQueue, "weight <> 2500"); @@ -262,7 +245,7 @@ public class SelectorTest extends PTPTestCase message.setText("testEquals:2"); sender.send(message); - TextMessage msg = (TextMessage)receiver.receive(TestConfig.TIMEOUT); + TextMessage msg = (TextMessage) receiver.receive(TestConfig.TIMEOUT); Assert.assertEquals("testEquals:2", msg.getText()); } @@ -270,14 +253,12 @@ public class SelectorTest extends PTPTestCase * Test the BETWEEN condition in message selector. *
    *
      - *
    • "age BETWEEN 15 and 19" is true for 17 and false for 20
    • + *
    • "age BETWEEN 15 and 19" is true for 17 and false for 20
    • *
    */ @Test - public void testBetween() throws Exception - { - if (receiver != null) - { + public void testBetween() throws Exception { + if (receiver != null) { receiver.close(); } receiver = receiverSession.createReceiver(receiverQueue, "age BETWEEN 15 and 19"); @@ -292,7 +273,7 @@ public class SelectorTest extends PTPTestCase message.setText("testBetween:2"); sender.send(message); - TextMessage msg = (TextMessage)receiver.receive(TestConfig.TIMEOUT); + TextMessage msg = (TextMessage) receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue("Message not received", msg != null); Assert.assertTrue("Message of another test: " + msg.getText(), msg.getText().startsWith("testBetween")); Assert.assertEquals("testBetween:2", msg.getText()); @@ -302,14 +283,12 @@ public class SelectorTest extends PTPTestCase * Test the IN condition in message selector. *
    *
      - *
    • "Country IN ('UK', 'US', 'France')" is true for 'UK' and false for 'Peru'
    • + *
    • "Country IN ('UK', 'US', 'France')" is true for 'UK' and false for 'Peru'
    • *
    */ @Test - public void testIn() throws Exception - { - if (receiver != null) - { + public void testIn() throws Exception { + if (receiver != null) { receiver.close(); } receiver = receiverSession.createReceiver(receiverQueue, "Country IN ('UK', 'US', 'France')"); @@ -324,7 +303,7 @@ public class SelectorTest extends PTPTestCase message.setText("testIn:2"); sender.send(message); - TextMessage msg = (TextMessage)receiver.receive(TestConfig.TIMEOUT); + TextMessage msg = (TextMessage) receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue("Message not received", msg != null); Assert.assertTrue("Message of another test: " + msg.getText(), msg.getText().startsWith("testIn")); Assert.assertEquals("testIn:2", msg.getText()); @@ -334,14 +313,12 @@ public class SelectorTest extends PTPTestCase * Test the LIKE ... ESCAPE condition in message selector *
    *
      - *
    • "underscored LIKE '\_%' ESCAPE '\'" is true for '_foo' and false for 'bar'
    • + *
    • "underscored LIKE '\_%' ESCAPE '\'" is true for '_foo' and false for 'bar'
    • *
    */ @Test - public void testLikeEscape() throws Exception - { - if (receiver != null) - { + public void testLikeEscape() throws Exception { + if (receiver != null) { receiver.close(); } receiver = receiverSession.createReceiver(receiverQueue, "underscored LIKE '\\_%' ESCAPE '\\'"); @@ -356,7 +333,7 @@ public class SelectorTest extends PTPTestCase message.setText("testLikeEscape:2"); sender.send(message); - TextMessage msg = (TextMessage)receiver.receive(TestConfig.TIMEOUT); + TextMessage msg = (TextMessage) receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue("Message not received", msg != null); Assert.assertTrue("Message of another test: " + msg.getText(), msg.getText().startsWith("testLikeEscape")); Assert.assertEquals("testLikeEscape:2", msg.getText()); @@ -366,14 +343,12 @@ public class SelectorTest extends PTPTestCase * Test the LIKE condition with '_' in the pattern. *
    *
      - *
    • "word LIKE 'l_se'" is true for 'lose' and false for 'loose'
    • + *
    • "word LIKE 'l_se'" is true for 'lose' and false for 'loose'
    • *
    */ @Test - public void testLike_2() throws Exception - { - if (receiver != null) - { + public void testLike_2() throws Exception { + if (receiver != null) { receiver.close(); } receiver = receiverSession.createReceiver(receiverQueue, "word LIKE 'l_se'"); @@ -388,7 +363,7 @@ public class SelectorTest extends PTPTestCase message.setText("testLike_2:2"); sender.send(message); - TextMessage msg = (TextMessage)receiver.receive(TestConfig.TIMEOUT); + TextMessage msg = (TextMessage) receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue("Message not received", msg != null); Assert.assertTrue("Message of another test: " + msg.getText(), msg.getText().startsWith("testLike_2")); Assert.assertEquals("testLike_2:2", msg.getText()); @@ -398,14 +373,12 @@ public class SelectorTest extends PTPTestCase * Test the LIKE condition with '%' in the pattern. *
    *
      - *
    • "phone LIKE '12%3'" is true for '12993' and false for '1234'
    • + *
    • "phone LIKE '12%3'" is true for '12993' and false for '1234'
    • *
    */ @Test - public void testLike_1() throws Exception - { - if (receiver != null) - { + public void testLike_1() throws Exception { + if (receiver != null) { receiver.close(); } receiver = receiverSession.createReceiver(receiverQueue, "phone LIKE '12%3'"); @@ -420,7 +393,7 @@ public class SelectorTest extends PTPTestCase message.setText("testLike_1:2"); sender.send(message); - TextMessage msg = (TextMessage)receiver.receive(TestConfig.TIMEOUT); + TextMessage msg = (TextMessage) receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue("Message not received", msg != null); Assert.assertTrue("Message of another test: " + msg.getText(), msg.getText().startsWith("testLike_1")); Assert.assertEquals("testLike_1:2", msg.getText()); @@ -430,14 +403,12 @@ public class SelectorTest extends PTPTestCase * Test the NULL value in message selector. *
    *
      - *
    • "prop IS NULL"
    • + *
    • "prop IS NULL"
    • *
    */ @Test - public void testNull() throws Exception - { - if (receiver != null) - { + public void testNull() throws Exception { + if (receiver != null) { receiver.close(); } receiver = receiverSession.createReceiver(receiverQueue, "prop_name IS NULL"); @@ -451,7 +422,7 @@ public class SelectorTest extends PTPTestCase message.setText("testNull:2"); sender.send(message); - TextMessage msg = (TextMessage)receiver.receive(TestConfig.TIMEOUT); + TextMessage msg = (TextMessage) receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue(msg != null); Assert.assertEquals("testNull:2", msg.getText()); } diff --git a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/session/QueueSessionTest.java b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/session/QueueSessionTest.java index 50cdd6c31b..93e847feac 100644 --- a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/session/QueueSessionTest.java +++ b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/session/QueueSessionTest.java @@ -33,18 +33,15 @@ import org.objectweb.jtests.jms.framework.TestConfig; *
    * See JMS specifications, sec. 4.4 Session */ -public class QueueSessionTest extends PTPTestCase -{ +public class QueueSessionTest extends PTPTestCase { /** * Test that if we rollback a transaction which has consumed a message, * the message is effectively redelivered. */ @Test - public void testRollbackRececeivedMessage() - { - try - { + public void testRollbackRececeivedMessage() { + try { senderConnection.stop(); // senderSession has been created as non transacted // we create it again but as a transacted session @@ -60,8 +57,7 @@ public class QueueSessionTest extends PTPTestCase receiverSession = receiverConnection.createQueueSession(true, 0); Assert.assertEquals(true, receiverSession.getTransacted()); - if (receiver != null) - { + if (receiver != null) { receiver.close(); } // we create again the receiver @@ -79,7 +75,7 @@ public class QueueSessionTest extends PTPTestCase Message m = receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue(m != null); Assert.assertTrue(m instanceof TextMessage); - TextMessage msg = (TextMessage)m; + TextMessage msg = (TextMessage) m; // ... which is the one which was sent... Assert.assertEquals("testRollbackRececeivedMessage", msg.getText()); // ...and has not been redelivered @@ -92,15 +88,14 @@ public class QueueSessionTest extends PTPTestCase m = receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue(m != null); Assert.assertTrue(m instanceof TextMessage); - msg = (TextMessage)m; + msg = (TextMessage) m; // ... which is still the one which was sent... Assert.assertEquals("testRollbackRececeivedMessage", msg.getText()); // .. but this time, it has been redelivered Assert.assertEquals(true, msg.getJMSRedelivered()); } - catch (Exception e) - { + catch (Exception e) { fail(e); } } @@ -110,18 +105,14 @@ public class QueueSessionTest extends PTPTestCase * messaeg session throws a javax.jms.InvalidSelectorException. */ @Test - public void testCreateBrowser_2() - { - try - { + public void testCreateBrowser_2() { + try { senderSession.createBrowser(senderQueue, "definitely not a message selector!"); Assert.fail("Should throw a javax.jms.InvalidSelectorException.\n"); } - catch (InvalidSelectorException e) - { + catch (InvalidSelectorException e) { } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("Should throw a javax.jms.InvalidSelectorException, not a " + e); } } @@ -131,18 +122,14 @@ public class QueueSessionTest extends PTPTestCase * Queue throws a javax.jms.InvalidDestinationException. */ @Test - public void testCreateBrowser_1() - { - try - { - senderSession.createBrowser((Queue)null); + public void testCreateBrowser_1() { + try { + senderSession.createBrowser((Queue) null); Assert.fail("Should throw a javax.jms.InvalidDestinationException.\n"); } - catch (InvalidDestinationException e) - { + catch (InvalidDestinationException e) { } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("Should throw a javax.jms.InvalidDestinationException, not a " + e); } } @@ -152,18 +139,14 @@ public class QueueSessionTest extends PTPTestCase * message selector throws a javax.jms.InvalidSelectorException. */ @Test - public void testCreateReceiver_2() - { - try - { + public void testCreateReceiver_2() { + try { receiver = senderSession.createReceiver(senderQueue, "definitely not a message selector!"); Assert.fail("Should throw a javax.jms.InvalidSelectorException.\n"); } - catch (InvalidSelectorException e) - { + catch (InvalidSelectorException e) { } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("Should throw a javax.jms.InvalidSelectorException, not a " + e); } } @@ -173,19 +156,15 @@ public class QueueSessionTest extends PTPTestCase * Queue throws a javax.jms.InvalidDestinationException> */ @Test - public void testCreateReceiver_1() - { - try - { - receiver = senderSession.createReceiver((Queue)null); + public void testCreateReceiver_1() { + try { + receiver = senderSession.createReceiver((Queue) null); Assert.fail("Should throw a javax.jms.InvalidDestinationException.\n"); } - catch (InvalidDestinationException e) - { + catch (InvalidDestinationException e) { // expected } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("Should throw a javax.jms.InvalidDestinationException, not a " + e); } } diff --git a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/session/SessionTest.java b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/session/SessionTest.java index 94f6d11de7..f76510fe96 100644 --- a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/session/SessionTest.java +++ b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/session/SessionTest.java @@ -31,8 +31,7 @@ import org.objectweb.jtests.jms.framework.TestConfig; *
    * See JMS specifications, sec. 4.4 Session */ -public class SessionTest extends PTPTestCase -{ +public class SessionTest extends PTPTestCase { /** * Test that an attempt to call the recover() method on a @@ -40,10 +39,8 @@ public class SessionTest extends PTPTestCase * javax.jms.IllegalStateException. */ @Test - public void testRecoverTransactedSession() - { - try - { + public void testRecoverTransactedSession() { + try { // senderSession has been created as non transacted Assert.assertEquals(false, senderSession.getTransacted()); // we create it again but as a transacted session @@ -52,15 +49,12 @@ public class SessionTest extends PTPTestCase senderSession.recover(); Assert.fail("Should raise an IllegalStateException, the session is not transacted.\n"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { } - catch (java.lang.IllegalStateException e) - { + catch (java.lang.IllegalStateException e) { Assert.fail("Should raise a javax.jms.IllegalStateException, not a java.lang.IllegalStateException.\n"); } - catch (Exception e) - { + catch (Exception e) { Assert.fail("Should raise a javax.jms.IllegalStateException, not a " + e); } } @@ -71,10 +65,8 @@ public class SessionTest extends PTPTestCase * the messages sent in the transaction. */ @Test - public void testRollbackTransactedSession() - { - try - { + public void testRollbackTransactedSession() { + try { // re-create senderSession as a transacted session senderSession = senderConnection.createQueueSession(true, 0); sender = senderSession.createSender(senderQueue); @@ -88,12 +80,11 @@ public class SessionTest extends PTPTestCase // rollback the transaction -> the sent message shouldn't be received senderSession.rollback(); - TextMessage m = (TextMessage)receiver.receiveNoWait(); + TextMessage m = (TextMessage) receiver.receiveNoWait(); // test that no message has been received Assert.assertEquals(null, m); } - catch (Exception e) - { + catch (Exception e) { fail(e); } } @@ -104,10 +95,8 @@ public class SessionTest extends PTPTestCase * the messages sent in the transaction. */ @Test - public void testCommitTransactedSession() - { - try - { + public void testCommitTransactedSession() { + try { // re-create senderSession as a transacted session senderSession = senderConnection.createQueueSession(true, 0); sender = senderSession.createSender(senderQueue); @@ -118,19 +107,18 @@ public class SessionTest extends PTPTestCase // send a message within a transacted session sender.send(message); - TextMessage m = (TextMessage)receiver.receiveNoWait(); + TextMessage m = (TextMessage) receiver.receiveNoWait(); // test that no message has been received (the transaction has not been committed yet) Assert.assertEquals(null, m); // commit the transaction -> the sent message should be received senderSession.commit(); - m = (TextMessage)receiver.receive(TestConfig.TIMEOUT); + m = (TextMessage) receiver.receive(TestConfig.TIMEOUT); Assert.assertTrue(m != null); Assert.assertEquals("testCommitTransactedSession", m.getText()); } - catch (Exception e) - { + catch (Exception e) { fail(e); } } @@ -141,24 +129,19 @@ public class SessionTest extends PTPTestCase * javax.jms.IllegalStateException. */ @Test - public void testRollbackNonTransactedSession() - { - try - { + public void testRollbackNonTransactedSession() { + try { // senderSession has been created as non transacted in the setUp() method Assert.assertEquals(false, senderSession.getTransacted()); senderSession.rollback(); Assert.fail("Should raise an IllegalStateException, the session is not transacted.\n"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { } - catch (java.lang.IllegalStateException e) - { + catch (java.lang.IllegalStateException e) { Assert.fail("Should raise a javax.jms.IllegalStateException, not a java.lang.IllegalStateException.\n"); } - catch (Exception e) - { + catch (Exception e) { Assert.fail("Should raise a javax.jms.IllegalStateException, not a " + e); } } @@ -169,24 +152,19 @@ public class SessionTest extends PTPTestCase * javax.jms.IllegalStateException. */ @Test - public void testCommitNonTransactedSession() - { - try - { + public void testCommitNonTransactedSession() { + try { // senderSession has been created as non transacted in the setUp() method Assert.assertEquals(false, senderSession.getTransacted()); senderSession.commit(); Assert.fail("Should raise an IllegalStateException, the session is not transacted.\n"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { } - catch (java.lang.IllegalStateException e) - { + catch (java.lang.IllegalStateException e) { Assert.fail("Should raise a javax.jms.IllegalStateException, not a java.lang.IllegalStateException.\n"); } - catch (Exception e) - { + catch (Exception e) { Assert.fail("Should raise a javax.jms.IllegalStateException, not a " + e); } } @@ -196,18 +174,15 @@ public class SessionTest extends PTPTestCase * if the session is transacted, false else. */ @Test - public void testGetTransacted() - { - try - { + public void testGetTransacted() { + try { // senderSession has been created as non transacted Assert.assertEquals(false, senderSession.getTransacted()); // we re-create senderSession as a transacted session senderSession = senderConnection.createQueueSession(true, Session.AUTO_ACKNOWLEDGE); Assert.assertEquals(true, senderSession.getTransacted()); } - catch (Exception e) - { + catch (Exception e) { fail(e); } } @@ -217,12 +192,9 @@ public class SessionTest extends PTPTestCase * from a closed session must throw an IllegalStateException. */ @Test - public void testAcknowledge() - { - try - { - if (receiverSession != null) - { + public void testAcknowledge() { + try { + if (receiverSession != null) { receiverSession.close(); } receiverSession = receiverConnection.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE); @@ -236,17 +208,13 @@ public class SessionTest extends PTPTestCase m.acknowledge(); Assert.fail("sec. 4.4.1 Invoking the acknowledge method of a received message from a closed " + " session must throw an [javax.jms.]IllegalStateException.\n"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("Should raise a javax.jms.IllegalStateException, not a " + e); } - catch (java.lang.IllegalStateException e) - { - Assert.fail("sec. 4.4.1 Invoking the acknowledge method of a received message from a closed " + "session must throw an [javax.jms.]IllegalStateException, " - + "[not a java.lang.IllegalStateException]"); + catch (java.lang.IllegalStateException e) { + Assert.fail("sec. 4.4.1 Invoking the acknowledge method of a received message from a closed " + "session must throw an [javax.jms.]IllegalStateException, " + "[not a java.lang.IllegalStateException]"); } } @@ -255,20 +223,17 @@ public class SessionTest extends PTPTestCase * exception of a received message acknowledge() method. */ @Test - public void testUseMessage() - { - try - { + public void testUseMessage() { + try { TextMessage message = senderSession.createTextMessage(); message.setText("testUseMessage"); sender.send(message); - TextMessage m = (TextMessage)receiver.receive(TestConfig.TIMEOUT); + TextMessage m = (TextMessage) receiver.receive(TestConfig.TIMEOUT); receiverSession.close(); Assert.assertEquals("testUseMessage", m.getText()); } - catch (Exception e) - { + catch (Exception e) { Assert.fail("sec. 4.4.1 It is valid to continue to use message objects created or received via " + "the [closed] session.\n"); } } @@ -278,23 +243,18 @@ public class SessionTest extends PTPTestCase * throws a javax.jms.IllegalStateException. */ @Test - public void testUsedClosedSession() - { - try - { + public void testUsedClosedSession() { + try { senderSession.close(); senderSession.createMessage(); Assert.fail("sec. 4.4.1 An attempt to use [a closed session] must throw a [javax.jms.]IllegalStateException.\n"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("Should raise a javax.jms.IllegalStateException, not a " + e); } - catch (java.lang.IllegalStateException e) - { + catch (java.lang.IllegalStateException e) { Assert.fail("Should raise a javax.jms.IllegalStateException, not a java.lang.IllegalStateException"); } } @@ -304,18 +264,15 @@ public class SessionTest extends PTPTestCase * an exception. */ @Test - public void testCloseClosedSession() - { - try - { + public void testCloseClosedSession() { + try { // senderSession is already started // we close it once senderSession.close(); // we close it a second time senderSession.close(); } - catch (Exception e) - { + catch (Exception e) { Assert.fail("sec. 4.4.1 Closing a closed session must NOT throw an exception.\n"); } } diff --git a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/session/TopicSessionTest.java b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/session/TopicSessionTest.java index 84c55f3647..09ea38a0a4 100644 --- a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/session/TopicSessionTest.java +++ b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/session/TopicSessionTest.java @@ -34,18 +34,15 @@ import org.objectweb.jtests.jms.framework.TestConfig; *
    * See JMS specifications, sec. 4.4 Session */ -public class TopicSessionTest extends PubSubTestCase -{ +public class TopicSessionTest extends PubSubTestCase { /** * Test that if we rollback a transaction which has consumed a message, * the message is effectively redelivered. */ @Test - public void testRollbackReceivedMessage() - { - try - { + public void testRollbackReceivedMessage() { + try { publisherConnection.stop(); // publisherSession has been declared has non transacted // we recreate it as a transacted session @@ -76,7 +73,7 @@ public class TopicSessionTest extends PubSubTestCase Message msg1 = subscriber.receive(TestConfig.TIMEOUT); Assert.assertTrue("no message received", msg1 != null); Assert.assertTrue(msg1 instanceof TextMessage); - Assert.assertEquals("testRollbackReceivedMessage", ((TextMessage)msg1).getText()); + Assert.assertEquals("testRollbackReceivedMessage", ((TextMessage) msg1).getText()); // we rollback the transaction of subscriberSession subscriberSession.rollback(); @@ -85,13 +82,12 @@ public class TopicSessionTest extends PubSubTestCase Message msg2 = subscriber.receive(TestConfig.TIMEOUT); Assert.assertTrue("no message received after rollbacking subscriber session.", msg2 != null); Assert.assertTrue(msg2 instanceof TextMessage); - Assert.assertEquals("testRollbackReceivedMessage", ((TextMessage)msg2).getText()); + Assert.assertEquals("testRollbackReceivedMessage", ((TextMessage) msg2).getText()); // finally we commit the subscriberSession transaction subscriberSession.commit(); } - catch (Exception e) - { + catch (Exception e) { fail(e); } } @@ -101,10 +97,8 @@ public class TopicSessionTest extends PubSubTestCase * topic while it was inactive. */ @Test - public void testDurableSubscriber() - { - try - { + public void testDurableSubscriber() { + try { subscriber = subscriberSession.createDurableSubscriber(subscriberTopic, "testTopic"); subscriberConnection.close(); subscriberConnection = null; @@ -119,12 +113,11 @@ public class TopicSessionTest extends PubSubTestCase subscriber = subscriberSession.createDurableSubscriber(subscriberTopic, "testTopic"); subscriberConnection.start(); - TextMessage m = (TextMessage)subscriber.receive(TestConfig.TIMEOUT); + TextMessage m = (TextMessage) subscriber.receive(TestConfig.TIMEOUT); Assert.assertTrue(m != null); Assert.assertEquals("test", m.getText()); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -133,17 +126,14 @@ public class TopicSessionTest extends PubSubTestCase * Test the unsubscription of a durable subscriber. */ @Test - public void testUnsubscribe() - { - try - { + public void testUnsubscribe() { + try { subscriber = subscriberSession.createDurableSubscriber(subscriberTopic, "topic"); subscriber.close(); // nothing should happen when unsubscribing the durable subscriber subscriberSession.unsubscribe("topic"); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } @@ -153,18 +143,14 @@ public class TopicSessionTest extends PubSubTestCase * message selector throws a javax.jms.InvalidSelectorException. */ @Test - public void testCreateDurableSubscriber_2() - { - try - { + public void testCreateDurableSubscriber_2() { + try { subscriberSession.createDurableSubscriber(subscriberTopic, "topic", "definitely not a message selector!", true); Assert.fail("Should throw a javax.jms.InvalidSelectorException.\n"); } - catch (InvalidSelectorException e) - { + catch (InvalidSelectorException e) { } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("Should throw a javax.jms.InvalidSelectorException, not a " + e); } } @@ -174,18 +160,14 @@ public class TopicSessionTest extends PubSubTestCase * Topic throws a javax.jms.InvalidDestinationException. */ @Test - public void testCreateDurableSubscriber_1() - { - try - { - subscriberSession.createDurableSubscriber((Topic)null, "topic"); + public void testCreateDurableSubscriber_1() { + try { + subscriberSession.createDurableSubscriber((Topic) null, "topic"); Assert.fail("Should throw a javax.jms.InvalidDestinationException.\n"); } - catch (InvalidDestinationException e) - { + catch (InvalidDestinationException e) { } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("Should throw a javax.jms.InvalidDestinationException, not a " + e); } } @@ -195,18 +177,14 @@ public class TopicSessionTest extends PubSubTestCase * message selector throws a javax.jms.InvalidSelectorException. */ @Test - public void testCreateSubscriber_2() - { - try - { + public void testCreateSubscriber_2() { + try { subscriberSession.createSubscriber(subscriberTopic, "definitely not a message selector!", true); Assert.fail("Should throw a javax.jms.InvalidSelectorException.\n"); } - catch (InvalidSelectorException e) - { + catch (InvalidSelectorException e) { } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("Should throw a javax.jms.InvalidSelectorException, not a " + e); } } @@ -216,18 +194,14 @@ public class TopicSessionTest extends PubSubTestCase * Topic throws a javax.jms.InvalidDestinationException. */ @Test - public void testCreateSubscriber_1() - { - try - { - subscriberSession.createSubscriber((Topic)null); + public void testCreateSubscriber_1() { + try { + subscriberSession.createSubscriber((Topic) null); Assert.fail("Should throw a javax.jms.InvalidDestinationException.\n"); } - catch (InvalidDestinationException e) - { + catch (InvalidDestinationException e) { } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("Should throw a javax.jms.InvalidDestinationException, not a " + e); } } diff --git a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/session/UnifiedSessionTest.java b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/session/UnifiedSessionTest.java index 1276faa577..c8501b1588 100644 --- a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/session/UnifiedSessionTest.java +++ b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/session/UnifiedSessionTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.objectweb.jtests.jms.conform.session; + import javax.jms.JMSException; import javax.jms.QueueConnection; import javax.jms.QueueSession; @@ -36,8 +37,7 @@ import org.objectweb.jtests.jms.framework.UnifiedTestCase; * * @since JMS 1.1 */ -public class UnifiedSessionTest extends UnifiedTestCase -{ +public class UnifiedSessionTest extends UnifiedTestCase { /** * QueueConnection @@ -68,18 +68,14 @@ public class UnifiedSessionTest extends UnifiedTestCase * @since JMS 1.1 */ @Test - public void testCreateDurableConnectionConsumerOnQueueConnection() - { - try - { - queueConnection.createDurableConnectionConsumer(topic, "subscriptionName", "", (ServerSessionPool)null, 1); + public void testCreateDurableConnectionConsumerOnQueueConnection() { + try { + queueConnection.createDurableConnectionConsumer(topic, "subscriptionName", "", (ServerSessionPool) null, 1); Assert.fail("Should throw a javax.jms.IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("Should throw a javax.jms.IllegalStateException, not a " + e); } } @@ -93,18 +89,14 @@ public class UnifiedSessionTest extends UnifiedTestCase * @since JMS 1.1 */ @Test - public void testCreateDurableSubscriberOnQueueSession() - { - try - { + public void testCreateDurableSubscriberOnQueueSession() { + try { queueSession.createDurableSubscriber(topic, "subscriptionName"); Assert.fail("Should throw a javax.jms.IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("Should throw a javax.jms.IllegalStateException, not a " + e); } } @@ -118,18 +110,14 @@ public class UnifiedSessionTest extends UnifiedTestCase * @since JMS 1.1 */ @Test - public void testCreateTemporaryTopicOnQueueSession() - { - try - { + public void testCreateTemporaryTopicOnQueueSession() { + try { queueSession.createTemporaryTopic(); Assert.fail("Should throw a javax.jms.IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("Should throw a javax.jms.IllegalStateException, not a " + e); } } @@ -143,18 +131,14 @@ public class UnifiedSessionTest extends UnifiedTestCase * @since JMS 1.1 */ @Test - public void testCreateTopicOnQueueSession() - { - try - { + public void testCreateTopicOnQueueSession() { + try { queueSession.createTopic("topic_name"); Assert.fail("Should throw a javax.jms.IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("Should throw a javax.jms.IllegalStateException, not a " + e); } } @@ -168,18 +152,14 @@ public class UnifiedSessionTest extends UnifiedTestCase * @since JMS 1.1 */ @Test - public void testUnsubscribeOnQueueSession() - { - try - { + public void testUnsubscribeOnQueueSession() { + try { queueSession.unsubscribe("subscriptionName"); Assert.fail("Should throw a javax.jms.IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("Should throw a javax.jms.IllegalStateException, not a " + e); } } @@ -193,18 +173,14 @@ public class UnifiedSessionTest extends UnifiedTestCase * @since JMS 1.1 */ @Test - public void testCreateBrowserOnTopicSession() - { - try - { + public void testCreateBrowserOnTopicSession() { + try { topicSession.createBrowser(queue); Assert.fail("Should throw a javax.jms.IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("Should throw a javax.jms.IllegalStateException, not a " + e); } } @@ -218,18 +194,14 @@ public class UnifiedSessionTest extends UnifiedTestCase * @since JMS 1.1 */ @Test - public void testCreateQueueOnTopicSession() - { - try - { + public void testCreateQueueOnTopicSession() { + try { topicSession.createQueue("queue_name"); Assert.fail("Should throw a javax.jms.IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("Should throw a javax.jms.IllegalStateException, not a " + e); } } @@ -243,29 +215,23 @@ public class UnifiedSessionTest extends UnifiedTestCase * @since JMS 1.1 */ @Test - public void testCreateTemporaryQueueOnTopicSession() - { - try - { + public void testCreateTemporaryQueueOnTopicSession() { + try { topicSession.createTemporaryQueue(); Assert.fail("Should throw a javax.jms.IllegalStateException"); } - catch (javax.jms.IllegalStateException e) - { + catch (javax.jms.IllegalStateException e) { } - catch (JMSException e) - { + catch (JMSException e) { Assert.fail("Should throw a javax.jms.IllegalStateException, not a " + e); } } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - try - { + try { queueConnection = queueConnectionFactory.createQueueConnection(); queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); topicConnection = topicConnectionFactory.createTopicConnection(); @@ -274,26 +240,21 @@ public class UnifiedSessionTest extends UnifiedTestCase queueConnection.start(); topicConnection.start(); } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } } @Override @After - public void tearDown() throws Exception - { - try - { + public void tearDown() throws Exception { + try { queueConnection.close(); topicConnection.close(); } - catch (Exception ignored) - { + catch (Exception ignored) { } - finally - { + finally { queueConnection = null; queueSession = null; topicConnection = null; diff --git a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/topic/TemporaryTopicTest.java b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/topic/TemporaryTopicTest.java index 8af840a75e..da6b4170c8 100644 --- a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/topic/TemporaryTopicTest.java +++ b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/topic/TemporaryTopicTest.java @@ -30,8 +30,7 @@ import org.objectweb.jtests.jms.framework.TestConfig; /** * Test the javax.jms.TemporaryTopic features. */ -public class TemporaryTopicTest extends PubSubTestCase -{ +public class TemporaryTopicTest extends PubSubTestCase { private TemporaryTopic tempTopic; @@ -41,10 +40,8 @@ public class TemporaryTopicTest extends PubSubTestCase * Test a TemporaryTopic */ @Test - public void testTemporaryTopic() - { - try - { + public void testTemporaryTopic() { + try { // we stop both publisher and subscriber connections publisherConnection.stop(); subscriberConnection.stop(); @@ -64,11 +61,10 @@ public class TemporaryTopicTest extends PubSubTestCase Message m = tempSubscriber.receive(TestConfig.TIMEOUT); Assert.assertTrue(m instanceof TextMessage); - TextMessage msg = (TextMessage)m; + TextMessage msg = (TextMessage) m; Assert.assertEquals("testTemporaryTopic", msg.getText()); } - catch (JMSException e) - { + catch (JMSException e) { fail(e); } } diff --git a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/framework/JMSTestCase.java b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/framework/JMSTestCase.java index 03cba12dd1..9ef7a53ed7 100644 --- a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/framework/JMSTestCase.java +++ b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/framework/JMSTestCase.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.objectweb.jtests.jms.framework; + import javax.jms.JMSException; import java.io.IOException; import java.util.Properties; @@ -29,11 +30,11 @@ import org.objectweb.jtests.jms.admin.AdminFactory; * Class extending junit.framework.TestCase to * provide a new fail() method with an Exception * as parameter. - *
    + *
    * Every Test Case for JMS should extend this class instead of junit.framework.TestCase */ -public abstract class JMSTestCase extends Assert -{ +public abstract class JMSTestCase extends Assert { + public static final String PROP_FILE_NAME = "provider.properties"; public static boolean startServer = true; @@ -47,66 +48,56 @@ public abstract class JMSTestCase extends Assert * message of the failure will contained both the JMSException and its linked exception * (provided there's one). */ - public void fail(final Exception e) - { - if (e instanceof javax.jms.JMSException) - { - JMSException exception = (JMSException)e; + public void fail(final Exception e) { + if (e instanceof javax.jms.JMSException) { + JMSException exception = (JMSException) e; String message = e.toString(); Exception linkedException = exception.getLinkedException(); - if (linkedException != null) - { + if (linkedException != null) { message += " [linked exception: " + linkedException + "]"; } Assert.fail(message); } - else - { + else { Assert.fail(e.getMessage()); } } /** * Should be overridden + * * @return */ - protected Properties getProviderProperties() throws IOException - { + protected Properties getProviderProperties() throws IOException { Properties props = new Properties(); props.load(ClassLoader.getSystemResourceAsStream(JMSTestCase.PROP_FILE_NAME)); return props; } @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { // Admin step // gets the provider administration wrapper... Properties props = getProviderProperties(); admin = AdminFactory.getAdmin(props); - if (startServer) - { + if (startServer) { admin.startServer(); } admin.start(); } @After - public void tearDown() throws Exception - { - try - { + public void tearDown() throws Exception { + try { admin.stop(); - if (startServer) - { + if (startServer) { admin.stopServer(); } } - finally - { + finally { } } diff --git a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/framework/PTPTestCase.java b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/framework/PTPTestCase.java index ae76abaf3f..c4ac06da44 100644 --- a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/framework/PTPTestCase.java +++ b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/framework/PTPTestCase.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.objectweb.jtests.jms.framework; + import javax.jms.Queue; import javax.jms.QueueConnection; import javax.jms.QueueConnectionFactory; @@ -41,8 +42,7 @@ import org.junit.Before; * Classes which want that convenience should extend PTPTestCase instead of * JMSTestCase. */ -public abstract class PTPTestCase extends JMSTestCase -{ +public abstract class PTPTestCase extends JMSTestCase { protected Context ctx; @@ -107,30 +107,28 @@ public abstract class PTPTestCase extends JMSTestCase */ @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - try - { + try { // ...and creates administrated objects and binds them admin.createQueueConnectionFactory(PTPTestCase.QCF_NAME); admin.createQueue(PTPTestCase.QUEUE_NAME); Hashtable props = new Hashtable<>(); props.put(Context.INITIAL_CONTEXT_FACTORY, ActiveMQInitialContextFactory.class.getCanonicalName()); - props.put("connectionFactory." + PTPTestCase.QCF_NAME, "tcp://127.0.0.1:61616?type=QUEUE_CF"); + props.put("connectionFactory." + PTPTestCase.QCF_NAME, "tcp://127.0.0.1:61616?type=QUEUE_CF"); props.put("queue." + PTPTestCase.QUEUE_NAME, PTPTestCase.QUEUE_NAME); Context ctx = new InitialContext(props); - senderQCF = (QueueConnectionFactory)ctx.lookup(PTPTestCase.QCF_NAME); - senderQueue = (Queue)ctx.lookup(PTPTestCase.QUEUE_NAME); + senderQCF = (QueueConnectionFactory) ctx.lookup(PTPTestCase.QCF_NAME); + senderQueue = (Queue) ctx.lookup(PTPTestCase.QUEUE_NAME); senderConnection = senderQCF.createQueueConnection(); senderSession = senderConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); sender = senderSession.createSender(senderQueue); - receiverQCF = (QueueConnectionFactory)ctx.lookup(PTPTestCase.QCF_NAME); - receiverQueue = (Queue)ctx.lookup(PTPTestCase.QUEUE_NAME); + receiverQCF = (QueueConnectionFactory) ctx.lookup(PTPTestCase.QCF_NAME); + receiverQueue = (Queue) ctx.lookup(PTPTestCase.QUEUE_NAME); receiverConnection = receiverQCF.createQueueConnection(); receiverSession = receiverConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); receiver = receiverSession.createReceiver(receiverQueue); @@ -139,33 +137,28 @@ public abstract class PTPTestCase extends JMSTestCase receiverConnection.start(); // end of client step } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } } /** - * Close connections and delete administrated objects + * Close connections and delete administrated objects */ @Override @After - public void tearDown() throws Exception - { - try - { + public void tearDown() throws Exception { + try { senderConnection.close(); receiverConnection.close(); admin.deleteQueueConnectionFactory(PTPTestCase.QCF_NAME); admin.deleteQueue(PTPTestCase.QUEUE_NAME); } - catch (Exception ignored) - { + catch (Exception ignored) { ignored.printStackTrace(); } - finally - { + finally { senderQueue = null; sender = null; senderQCF = null; diff --git a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/framework/PubSubTestCase.java b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/framework/PubSubTestCase.java index a31db725af..d606e231aa 100644 --- a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/framework/PubSubTestCase.java +++ b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/framework/PubSubTestCase.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.objectweb.jtests.jms.framework; + import javax.jms.Session; import javax.jms.Topic; import javax.jms.TopicConnection; @@ -41,8 +42,7 @@ import org.junit.Before; * Classes which want that convenience should extend PubSubTestCase instead of * JMSTestCase. */ -public abstract class PubSubTestCase extends JMSTestCase -{ +public abstract class PubSubTestCase extends JMSTestCase { private Context ctx; @@ -107,12 +107,10 @@ public abstract class PubSubTestCase extends JMSTestCase */ @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - try - { + try { // ...and creates administrated objects and binds them admin.createTopicConnectionFactory(PubSubTestCase.TCF_NAME); admin.createTopic(PubSubTestCase.TOPIC_NAME); @@ -123,15 +121,15 @@ public abstract class PubSubTestCase extends JMSTestCase props.put("topic." + PubSubTestCase.TOPIC_NAME, PubSubTestCase.TOPIC_NAME); Context ctx = new InitialContext(props); - publisherTCF = (TopicConnectionFactory)ctx.lookup(PubSubTestCase.TCF_NAME); - publisherTopic = (Topic)ctx.lookup(PubSubTestCase.TOPIC_NAME); + publisherTCF = (TopicConnectionFactory) ctx.lookup(PubSubTestCase.TCF_NAME); + publisherTopic = (Topic) ctx.lookup(PubSubTestCase.TOPIC_NAME); publisherConnection = publisherTCF.createTopicConnection(); publisherConnection.setClientID("publisherConnection"); publisherSession = publisherConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); publisher = publisherSession.createPublisher(publisherTopic); - subscriberTCF = (TopicConnectionFactory)ctx.lookup(PubSubTestCase.TCF_NAME); - subscriberTopic = (Topic)ctx.lookup(PubSubTestCase.TOPIC_NAME); + subscriberTCF = (TopicConnectionFactory) ctx.lookup(PubSubTestCase.TCF_NAME); + subscriberTopic = (Topic) ctx.lookup(PubSubTestCase.TOPIC_NAME); subscriberConnection = subscriberTCF.createTopicConnection(); subscriberConnection.setClientID("subscriberConnection"); subscriberSession = subscriberConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); @@ -141,32 +139,27 @@ public abstract class PubSubTestCase extends JMSTestCase subscriberConnection.start(); // end of client step } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } } /** - * Close connections and delete administrated objects + * Close connections and delete administrated objects */ @Override @After - public void tearDown() throws Exception - { - try - { + public void tearDown() throws Exception { + try { publisherConnection.close(); subscriberConnection.close(); admin.deleteTopicConnectionFactory(PubSubTestCase.TCF_NAME); admin.deleteTopic(PubSubTestCase.TOPIC_NAME); } - catch (Exception ignored) - { + catch (Exception ignored) { } - finally - { + finally { publisherTopic = null; publisher = null; publisherTCF = null; diff --git a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/framework/TestConfig.java b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/framework/TestConfig.java index 62ff58e8ee..dcc948a5f8 100644 --- a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/framework/TestConfig.java +++ b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/framework/TestConfig.java @@ -21,8 +21,8 @@ import java.util.Properties; /** * Class used to provide configurable options in a convenient way */ -public class TestConfig -{ +public class TestConfig { + // name of the configuration file private static final String PROP_FILE_NAME = "test.properties"; @@ -35,24 +35,20 @@ public class TestConfig */ public static final long TIMEOUT; - static - { + static { // load tests.properties long tempTimeOut = 0; - try - { + try { Properties props = new Properties(); props.load(ClassLoader.getSystemResourceAsStream(TestConfig.PROP_FILE_NAME)); System.out.println("Found " + TestConfig.PROP_FILE_NAME); tempTimeOut = Long.parseLong(props.getProperty(TestConfig.PROP_NAME, "0")); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); tempTimeOut = 30000; } - finally - { + finally { TIMEOUT = tempTimeOut; } } diff --git a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/framework/UnifiedTestCase.java b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/framework/UnifiedTestCase.java index 6a71879553..39abba5be3 100644 --- a/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/framework/UnifiedTestCase.java +++ b/tests/joram-tests/src/test/java/org/objectweb/jtests/jms/framework/UnifiedTestCase.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.objectweb.jtests.jms.framework; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; @@ -46,8 +47,7 @@ import org.junit.Before; * * @since JMS 1.1 */ -public abstract class UnifiedTestCase extends JMSTestCase -{ +public abstract class UnifiedTestCase extends JMSTestCase { protected Context ctx; @@ -152,12 +152,10 @@ public abstract class UnifiedTestCase extends JMSTestCase */ @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - try - { + try { // ...and creates administrated objects and binds them admin.createConnectionFactory(UnifiedTestCase.CF_NAME); admin.createQueueConnectionFactory(UnifiedTestCase.QCF_NAME); @@ -177,47 +175,44 @@ public abstract class UnifiedTestCase extends JMSTestCase props.put("topic." + UnifiedTestCase.TOPIC_NAME, UnifiedTestCase.TOPIC_NAME); Context ctx = new InitialContext(props); - producerCF = (ConnectionFactory)ctx.lookup(UnifiedTestCase.CF_NAME); + producerCF = (ConnectionFactory) ctx.lookup(UnifiedTestCase.CF_NAME); // we see destination of the unified domain as a javax.jms.Destination // instead of a javax.jms.Queue to be more generic - producerDestination = (Destination)ctx.lookup(UnifiedTestCase.DESTINATION_NAME); + producerDestination = (Destination) ctx.lookup(UnifiedTestCase.DESTINATION_NAME); producerConnection = producerCF.createConnection(); producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); producer = producerSession.createProducer(producerDestination); - consumerCF = (ConnectionFactory)ctx.lookup(UnifiedTestCase.CF_NAME); + consumerCF = (ConnectionFactory) ctx.lookup(UnifiedTestCase.CF_NAME); // we see destination of the unified domain as a javax.jms.Destination // instead of a javax.jms.Queue to be more generic - consumerDestination = (Destination)ctx.lookup(UnifiedTestCase.DESTINATION_NAME); + consumerDestination = (Destination) ctx.lookup(UnifiedTestCase.DESTINATION_NAME); consumerConnection = consumerCF.createConnection(); consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); consumer = consumerSession.createConsumer(consumerDestination); - queueConnectionFactory = (QueueConnectionFactory)ctx.lookup(UnifiedTestCase.QCF_NAME); - queue = (Queue)ctx.lookup(UnifiedTestCase.QUEUE_NAME); + queueConnectionFactory = (QueueConnectionFactory) ctx.lookup(UnifiedTestCase.QCF_NAME); + queue = (Queue) ctx.lookup(UnifiedTestCase.QUEUE_NAME); - topicConnectionFactory = (TopicConnectionFactory)ctx.lookup(UnifiedTestCase.TCF_NAME); - topic = (Topic)ctx.lookup(UnifiedTestCase.TOPIC_NAME); + topicConnectionFactory = (TopicConnectionFactory) ctx.lookup(UnifiedTestCase.TCF_NAME); + topic = (Topic) ctx.lookup(UnifiedTestCase.TOPIC_NAME); producerConnection.start(); consumerConnection.start(); // end of client step } - catch (Exception e) - { + catch (Exception e) { throw new RuntimeException(e); } } /** - * Close connections and delete administrated objects + * Close connections and delete administrated objects */ @Override @After - public void tearDown() throws Exception - { - try - { + public void tearDown() throws Exception { + try { consumerConnection.close(); producerConnection.close(); @@ -228,11 +223,9 @@ public abstract class UnifiedTestCase extends JMSTestCase admin.deleteQueue(UnifiedTestCase.QUEUE_NAME); admin.deleteTopic(UnifiedTestCase.TOPIC_NAME); } - catch (Exception ignored) - { + catch (Exception ignored) { } - finally - { + finally { producerDestination = null; producer = null; producerCF = null; diff --git a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/journal/FakeJournalImplTest.java b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/journal/FakeJournalImplTest.java index a7f42102bc..5874e06ae5 100644 --- a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/journal/FakeJournalImplTest.java +++ b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/journal/FakeJournalImplTest.java @@ -20,14 +20,12 @@ import org.apache.activemq.artemis.core.io.SequentialFileFactory; import org.apache.activemq.artemis.tests.unit.core.journal.impl.fakes.FakeSequentialFileFactory; /** - * * A FakeJournalImplTest */ -public class FakeJournalImplTest extends JournalImplTestUnit -{ +public class FakeJournalImplTest extends JournalImplTestUnit { + @Override - protected SequentialFileFactory getFileFactory() throws Exception - { + protected SequentialFileFactory getFileFactory() throws Exception { return new FakeSequentialFileFactory(); } } diff --git a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/journal/JournalImplTestUnit.java b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/journal/JournalImplTestUnit.java index 17bf397904..ccd6933ef0 100644 --- a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/journal/JournalImplTestUnit.java +++ b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/journal/JournalImplTestUnit.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.performance.journal; + import java.util.ArrayList; import org.apache.activemq.artemis.core.journal.Journal; @@ -29,22 +30,20 @@ import org.junit.After; import org.junit.Assert; import org.junit.Test; -public abstract class JournalImplTestUnit extends JournalImplTestBase -{ +public abstract class JournalImplTestUnit extends JournalImplTestBase { + private static final UnitTestLogger log = UnitTestLogger.LOGGER; @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { super.tearDown(); Assert.assertEquals(0, LibaioContext.getTotalMaxIO()); } @Test - public void testAddUpdateDeleteManyLargeFileSize() throws Exception - { + public void testAddUpdateDeleteManyLargeFileSize() throws Exception { final int numberAdds = 1000; final int numberUpdates = 500; @@ -53,22 +52,19 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase long[] adds = new long[numberAdds]; - for (int i = 0; i < numberAdds; i++) - { + for (int i = 0; i < numberAdds; i++) { adds[i] = i; } long[] updates = new long[numberUpdates]; - for (int i = 0; i < numberUpdates; i++) - { + for (int i = 0; i < numberUpdates; i++) { updates[i] = i; } long[] deletes = new long[numberDeletes]; - for (int i = 0; i < numberDeletes; i++) - { + for (int i = 0; i < numberDeletes; i++) { deletes[i] = i; } @@ -87,8 +83,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testAddUpdateDeleteManySmallFileSize() throws Exception - { + public void testAddUpdateDeleteManySmallFileSize() throws Exception { final int numberAdds = 1000; final int numberUpdates = 500; @@ -97,22 +92,19 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase long[] adds = new long[numberAdds]; - for (int i = 0; i < numberAdds; i++) - { + for (int i = 0; i < numberAdds; i++) { adds[i] = i; } long[] updates = new long[numberUpdates]; - for (int i = 0; i < numberUpdates; i++) - { + for (int i = 0; i < numberUpdates; i++) { updates[i] = i; } long[] deletes = new long[numberDeletes]; - for (int i = 0; i < numberDeletes; i++) - { + for (int i = 0; i < numberDeletes; i++) { deletes[i] = i; } @@ -133,8 +125,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testReclaimAndReload() throws Exception - { + public void testReclaimAndReload() throws Exception { setup(2, 10 * 1024 * 1024, false); createJournal(); startJournal(); @@ -146,24 +137,21 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase int NUMBER_OF_RECORDS = 1000; - for (int count = 0; count < NUMBER_OF_RECORDS; count++) - { - journal.appendAddRecord(count, (byte)0, record, true); + for (int count = 0; count < NUMBER_OF_RECORDS; count++) { + journal.appendAddRecord(count, (byte) 0, record, true); - if (count >= NUMBER_OF_RECORDS / 2) - { + if (count >= NUMBER_OF_RECORDS / 2) { journal.appendDeleteRecord(count - NUMBER_OF_RECORDS / 2, true); } - if (count % 100 == 0) - { + if (count % 100 == 0) { JournalImplTestUnit.log.debug("Done: " + count); } } long end = System.currentTimeMillis(); - double rate = 1000 * (double)NUMBER_OF_RECORDS / (end - start); + double rate = 1000 * (double) NUMBER_OF_RECORDS / (end - start); JournalImplTestUnit.log.info("Rate of " + rate + " adds/removes per sec"); @@ -180,10 +168,8 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testSpeedNonTransactional() throws Exception - { - for (int i = 0; i < 1; i++) - { + public void testSpeedNonTransactional() throws Exception { + for (int i = 0; i < 1; i++) { setUp(); System.gc(); Thread.sleep(500); @@ -193,66 +179,58 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testSpeedTransactional() throws Exception - { + public void testSpeedTransactional() throws Exception { Journal journal = new JournalImpl(10 * 1024 * 1024, 10, 0, 0, getFileFactory(), "activemq-data", "amq", 5000); journal.start(); journal.load(new ArrayList(), null, null); - try - { + try { final int numMessages = 50050; - SimpleEncoding data = new SimpleEncoding(1024, (byte)'j'); + SimpleEncoding data = new SimpleEncoding(1024, (byte) 'j'); long start = System.currentTimeMillis(); int count = 0; double[] rates = new double[50]; - for (int i = 0; i < 50; i++) - { + for (int i = 0; i < 50; i++) { long startTrans = System.currentTimeMillis(); - for (int j = 0; j < 1000; j++) - { - journal.appendAddRecordTransactional(i, count++, (byte)0, data); + for (int j = 0; j < 1000; j++) { + journal.appendAddRecordTransactional(i, count++, (byte) 0, data); } journal.appendCommitRecord(i, true); long endTrans = System.currentTimeMillis(); - rates[i] = 1000 * (double)1000 / (endTrans - startTrans); + rates[i] = 1000 * (double) 1000 / (endTrans - startTrans); } long end = System.currentTimeMillis(); - for (double rate : rates) - { + for (double rate : rates) { JournalImplTestUnit.log.info("Transaction Rate = " + rate + " records/sec"); } - double rate = 1000 * (double)numMessages / (end - start); + double rate = 1000 * (double) numMessages / (end - start); JournalImplTestUnit.log.info("Rate " + rate + " records/sec"); } - finally - { + finally { journal.stop(); } } - private void internaltestSpeedNonTransactional() throws Exception - { + private void internaltestSpeedNonTransactional() throws Exception { final long numMessages = 10000; - int numFiles = (int)((numMessages * 1024 + 512) / (10 * 1024 * 1024) * 1.3); + int numFiles = (int) ((numMessages * 1024 + 512) / (10 * 1024 * 1024) * 1.3); - if (numFiles < 2) - { + if (numFiles < 2) { numFiles = 2; } @@ -265,18 +243,17 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase journal.load(new ArrayList(), null, null); JournalImplTestUnit.log.debug("Adding data"); - SimpleEncoding data = new SimpleEncoding(700, (byte)'j'); + SimpleEncoding data = new SimpleEncoding(700, (byte) 'j'); long start = System.currentTimeMillis(); - for (int i = 0; i < numMessages; i++) - { - journal.appendAddRecord(i, (byte)0, data, true); + for (int i = 0; i < numMessages; i++) { + journal.appendAddRecord(i, (byte) 0, data, true); } long end = System.currentTimeMillis(); - double rate = 1000 * (double)numMessages / (end - start); + double rate = 1000 * (double) numMessages / (end - start); JournalImplTestUnit.log.info("Rate " + rate + " records/sec"); diff --git a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/journal/RealJournalImplAIOTest.java b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/journal/RealJournalImplAIOTest.java index a73a84182c..78d4f8345b 100644 --- a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/journal/RealJournalImplAIOTest.java +++ b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/journal/RealJournalImplAIOTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.performance.journal; + import java.io.File; import org.apache.activemq.artemis.core.io.SequentialFileFactory; @@ -23,26 +24,23 @@ import org.apache.activemq.artemis.tests.unit.UnitTestLogger; import org.junit.Before; import org.junit.BeforeClass; -public class RealJournalImplAIOTest extends JournalImplTestUnit -{ +public class RealJournalImplAIOTest extends JournalImplTestUnit { + private static final UnitTestLogger log = UnitTestLogger.LOGGER; @BeforeClass - public static void hasAIO() - { + public static void hasAIO() { org.junit.Assume.assumeTrue("Test case needs AIO to run", AIOSequentialFileFactory.isSupported()); } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); } @Override - protected SequentialFileFactory getFileFactory() throws Exception - { + protected SequentialFileFactory getFileFactory() throws Exception { File file = new File(getTestDir()); RealJournalImplAIOTest.log.debug("deleting directory " + file); diff --git a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/journal/RealJournalImplNIOTest.java b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/journal/RealJournalImplNIOTest.java index bc0e7c2ddc..aa07bd3e0b 100644 --- a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/journal/RealJournalImplNIOTest.java +++ b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/journal/RealJournalImplNIOTest.java @@ -22,13 +22,12 @@ import org.apache.activemq.artemis.core.io.SequentialFileFactory; import org.apache.activemq.artemis.core.io.nio.NIOSequentialFileFactory; import org.apache.activemq.artemis.tests.unit.UnitTestLogger; -public class RealJournalImplNIOTest extends JournalImplTestUnit -{ +public class RealJournalImplNIOTest extends JournalImplTestUnit { + private static final UnitTestLogger log = UnitTestLogger.LOGGER; @Override - protected SequentialFileFactory getFileFactory() throws Exception - { + protected SequentialFileFactory getFileFactory() throws Exception { File file = new File(getTestDir()); RealJournalImplNIOTest.log.debug("deleting directory " + getTestDir()); diff --git a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/paging/MeasurePagingMultiThreadTest.java b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/paging/MeasurePagingMultiThreadTest.java index bac27c55bf..31133d2ea2 100644 --- a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/paging/MeasurePagingMultiThreadTest.java +++ b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/paging/MeasurePagingMultiThreadTest.java @@ -31,12 +31,10 @@ import org.junit.Test; import java.util.HashMap; import java.util.concurrent.CountDownLatch; -public class MeasurePagingMultiThreadTest extends ActiveMQTestBase -{ +public class MeasurePagingMultiThreadTest extends ActiveMQTestBase { @Test - public void testPagingMultipleSenders() throws Throwable - { + public void testPagingMultipleSenders() throws Throwable { final int NUMBER_OF_THREADS = 18; final int NUMBER_OF_MESSAGES = 50000; @@ -47,8 +45,7 @@ public class MeasurePagingMultiThreadTest extends ActiveMQTestBase ActiveMQServer messagingService = createServer(true, createDefaultInVMConfig(), 10 * 1024, 20 * 1024, settings); messagingService.start(); ServerLocator locator = createInVMNonHALocator(); - try - { + try { final ClientSessionFactory factory = createSessionFactory(locator); final SimpleString adr = new SimpleString("test-adr"); @@ -62,8 +59,7 @@ public class MeasurePagingMultiThreadTest extends ActiveMQTestBase final CountDownLatch latchStart = new CountDownLatch(1); - class Sender extends Thread - { + class Sender extends Thread { private final ClientSession session; @@ -73,8 +69,7 @@ public class MeasurePagingMultiThreadTest extends ActiveMQTestBase Throwable e; - public Sender() throws Exception - { + public Sender() throws Exception { session = factory.createSession(false, true, true); producer = session.createProducer(adr); msg = session.createMessage(true); @@ -83,16 +78,13 @@ public class MeasurePagingMultiThreadTest extends ActiveMQTestBase // run is not going to close sessions or anything, as we don't want to measure that time // so this will be done in a second time - public void cleanUp() throws Exception - { + public void cleanUp() throws Exception { session.close(); } @Override - public void run() - { - try - { + public void run() { + try { latchAlign.countDown(); ActiveMQTestBase.waitForLatch(latchStart); @@ -101,12 +93,11 @@ public class MeasurePagingMultiThreadTest extends ActiveMQTestBase long end = System.currentTimeMillis(); System.out.println("Thread " + Thread.currentThread().getName() + - " finished sending in " + - (end - start) + - " milliseconds"); + " finished sending in " + + (end - start) + + " milliseconds"); } - catch (Throwable e) - { + catch (Throwable e) { this.e = e; } @@ -115,8 +106,7 @@ public class MeasurePagingMultiThreadTest extends ActiveMQTestBase Sender[] senders = new Sender[NUMBER_OF_THREADS]; - for (int i = 0; i < NUMBER_OF_THREADS; i++) - { + for (int i = 0; i < NUMBER_OF_THREADS; i++) { senders[i] = new Sender(); senders[i].start(); } @@ -127,33 +117,28 @@ public class MeasurePagingMultiThreadTest extends ActiveMQTestBase latchStart.countDown(); - for (Thread t : senders) - { + for (Thread t : senders) { t.join(); } long timeEnd = System.currentTimeMillis(); System.out.println("Total Time: " + (timeEnd - timeStart) + - " milliseconds what represented " + - NUMBER_OF_MESSAGES * - NUMBER_OF_THREADS * - 1000 / - (timeEnd - timeStart) + - " per second"); + " milliseconds what represented " + + NUMBER_OF_MESSAGES * + NUMBER_OF_THREADS * + 1000 / (timeEnd - timeStart) + + " per second"); - for (Sender s : senders) - { - if (s.e != null) - { + for (Sender s : senders) { + if (s.e != null) { throw s.e; } s.cleanUp(); } } - finally - { + finally { locator.close(); messagingService.stop(); @@ -177,8 +162,7 @@ public class MeasurePagingMultiThreadTest extends ActiveMQTestBase private void sendInitialBatch(final SimpleString adr, final int nMessages, final int messageSize, - final ClientSessionFactory factory) throws ActiveMQException - { + final ClientSessionFactory factory) throws ActiveMQException { ClientSession session = factory.createSession(false, true, true); ClientProducer producer = session.createProducer(adr); ClientMessage msg = session.createMessage(true); @@ -194,10 +178,10 @@ public class MeasurePagingMultiThreadTest extends ActiveMQTestBase * @param msg * @throws ActiveMQException */ - private void sendMessages(final int nMessages, final ClientProducer producer, final ClientMessage msg) throws ActiveMQException - { - for (int i = 0; i < nMessages; i++) - { + private void sendMessages(final int nMessages, + final ClientProducer producer, + final ClientMessage msg) throws ActiveMQException { + for (int i = 0; i < nMessages; i++) { producer.send(msg); } } @@ -207,8 +191,7 @@ public class MeasurePagingMultiThreadTest extends ActiveMQTestBase * @param adr * @throws ActiveMQException */ - private void createDestination(final ClientSessionFactory factory, final SimpleString adr) throws ActiveMQException - { + private void createDestination(final ClientSessionFactory factory, final SimpleString adr) throws ActiveMQException { { ClientSession session = factory.createSession(false, false, false); session.createQueue(adr, adr, null, true); diff --git a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/AbstractSendReceivePerfTest.java b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/AbstractSendReceivePerfTest.java index 0575c7b7d6..7e3c16c3cb 100644 --- a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/AbstractSendReceivePerfTest.java +++ b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/AbstractSendReceivePerfTest.java @@ -41,35 +41,29 @@ import org.junit.Test; /** * Client-ack time */ -public abstract class AbstractSendReceivePerfTest extends JMSTestBase -{ +public abstract class AbstractSendReceivePerfTest extends JMSTestBase { + protected static final String Q_NAME = "test-queue-01"; private Queue queue; protected AtomicBoolean running = new AtomicBoolean(true); - @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); jmsServer.createQueue(false, Q_NAME, null, true, Q_NAME); queue = ActiveMQJMSClient.createQueue(Q_NAME); - AddressSettings settings = new AddressSettings() - .setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK) - .setMaxSizeBytes(Long.MAX_VALUE); + AddressSettings settings = new AddressSettings().setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK).setMaxSizeBytes(Long.MAX_VALUE); server.getAddressSettingsRepository().clear(); server.getAddressSettingsRepository().addMatch("#", settings); } - @Override - protected void registerConnectionFactory() throws Exception - { + protected void registerConnectionFactory() throws Exception { List connectorConfigs = new ArrayList(); connectorConfigs.add(new TransportConfiguration(NETTY_CONNECTOR_FACTORY)); @@ -78,16 +72,12 @@ public abstract class AbstractSendReceivePerfTest extends JMSTestBase cf = (ConnectionFactory) namingContext.lookup("/cf"); } - private static final java.util.logging.Logger LOGGER = java.util.logging.Logger.getLogger(AbstractSendReceivePerfTest.class.getName()); - @Test - public void testSendReceive() throws Exception - { + public void testSendReceive() throws Exception { long numberOfSamples = Long.getLong("HORNETQ_TEST_SAMPLES", 1000); - MessageReceiver receiver = new MessageReceiver(Q_NAME, numberOfSamples); receiver.start(); MessageSender sender = new MessageSender(Q_NAME); @@ -107,59 +97,44 @@ public abstract class AbstractSendReceivePerfTest extends JMSTestBase * to be called after a message is consumed * so the flow control of the test kicks in. */ - protected final void afterConsume(Message message) - { - if (message != null) - { + protected final void afterConsume(Message message) { + if (message != null) { pendingCredit.release(); } } - - protected final void beforeSend() - { - while (running.get()) - { - try - { - if (pendingCredit.tryAcquire(1, TimeUnit.SECONDS)) - { + protected final void beforeSend() { + while (running.get()) { + try { + if (pendingCredit.tryAcquire(1, TimeUnit.SECONDS)) { return; } - else - { + else { System.out.println("Couldn't get credits!"); } } - catch (Throwable e) - { + catch (Throwable e) { throw new RuntimeException(e.getMessage(), e); } } } + private class MessageReceiver extends Thread { - - - private class MessageReceiver extends Thread - { private final String qName; private final long numberOfSamples; public boolean failed = false; - public MessageReceiver(String qname, long numberOfSamples) throws Exception - { + public MessageReceiver(String qname, long numberOfSamples) throws Exception { super("Receiver " + qname); this.qName = qname; this.numberOfSamples = numberOfSamples; } @Override - public void run() - { - try - { + public void run() { + try { LOGGER.info("Receiver: Connecting"); Connection c = cf.createConnection(); @@ -167,13 +142,11 @@ public abstract class AbstractSendReceivePerfTest extends JMSTestBase c.close(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); failed = true; } - finally - { + finally { running.set(false); } } @@ -181,24 +154,21 @@ public abstract class AbstractSendReceivePerfTest extends JMSTestBase protected abstract void consumeMessages(Connection c, String qName) throws Exception; - private class MessageSender extends Thread - { + private class MessageSender extends Thread { + protected String qName; public boolean failed = false; - public MessageSender(String qname) throws Exception - { + public MessageSender(String qname) throws Exception { super("Sender " + qname); this.qName = qname; } @Override - public void run() - { - try - { + public void run() { + try { LOGGER.info("Sender: Connecting"); Connection c = cf.createConnection(); @@ -207,15 +177,12 @@ public abstract class AbstractSendReceivePerfTest extends JMSTestBase c.close(); } - catch (Exception e) - { + catch (Exception e) { failed = true; - if (e instanceof InterruptedException) - { + if (e instanceof InterruptedException) { LOGGER.info("Sender done."); } - else - { + else { e.printStackTrace(); } } @@ -223,21 +190,17 @@ public abstract class AbstractSendReceivePerfTest extends JMSTestBase } /* This will by default send non persistent messages */ - protected void sendMessages(Connection c, String qName) throws JMSException - { + protected void sendMessages(Connection c, String qName) throws JMSException { Session s = null; s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); LOGGER.info("Sender: Using AUTO-ACK session"); - Queue q = s.createQueue(qName); MessageProducer producer = s.createProducer(null); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - long sent = 0; - while (running.get()) - { + while (running.get()) { beforeSend(); producer.send(q, s.createTextMessage("Message_" + (sent++))); } diff --git a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/ClientACKPerf.java b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/ClientACKPerf.java index de801f4b02..9758346780 100644 --- a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/ClientACKPerf.java +++ b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/ClientACKPerf.java @@ -30,32 +30,25 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(Parameterized.class) -public class ClientACKPerf extends AbstractSendReceivePerfTest -{ +public class ClientACKPerf extends AbstractSendReceivePerfTest { @Parameterized.Parameters(name = "batchSize={0}") - public static Collection data() - { - List list = Arrays.asList(new Object[][]{ - {1}, - {2000}}); + public static Collection data() { + List list = Arrays.asList(new Object[][]{{1}, {2000}}); System.out.println("Size = " + list.size()); return list; } - public ClientACKPerf(int batchSize) - { + public ClientACKPerf(int batchSize) { super(); this.batchSize = batchSize; } - public final int batchSize; @Override - protected void consumeMessages(Connection c, String qName) throws Exception - { + protected void consumeMessages(Connection c, String qName) throws Exception { int mode = 0; mode = Session.CLIENT_ACKNOWLEDGE; @@ -71,45 +64,34 @@ public class ClientACKPerf extends AbstractSendReceivePerfTest long totalTimeACKTime = 0; - long start = System.currentTimeMillis(); long nmessages = 0; long timeout = System.currentTimeMillis() + 60 * 1000; - while (timeout > System.currentTimeMillis()) - { + while (timeout > System.currentTimeMillis()) { m = consumer.receive(5000); afterConsume(m); - - if (m == null) - { + if (m == null) { throw new Exception("Failed with m = null"); } - if (nmessages++ % batchSize == 0) - { + if (nmessages++ % batchSize == 0) { long startACK = System.nanoTime(); m.acknowledge(); long endACK = System.nanoTime(); totalTimeACKTime += (endACK - startACK); } - - if (nmessages % 10000 == 0) - { + if (nmessages % 10000 == 0) { printMsgsSec(start, nmessages, totalTimeACKTime); } } - printMsgsSec(start, nmessages, totalTimeACKTime); } - - - protected void printMsgsSec(final long start, final double nmessages, final double totalTimeACKTime) - { + protected void printMsgsSec(final long start, final double nmessages, final double totalTimeACKTime) { long end = System.currentTimeMillis(); double elapsed = ((double) end - (double) start) / 1000f; @@ -117,11 +99,9 @@ public class ClientACKPerf extends AbstractSendReceivePerfTest double messagesPerSecond = nmessages / elapsed; double nAcks = nmessages / batchSize; - System.out.println("batchSize=" + batchSize + ", numberOfMessages=" - + nmessages + ", elapsedTime=" + elapsed + " msgs/sec= " + messagesPerSecond + ",totalTimeAcking=" + String.format("%10.4f", totalTimeACKTime) + + System.out.println("batchSize=" + batchSize + ", numberOfMessages=" + nmessages + ", elapsedTime=" + elapsed + " msgs/sec= " + messagesPerSecond + ",totalTimeAcking=" + String.format("%10.4f", totalTimeACKTime) + ", avgACKTime=" + String.format("%10.4f", (totalTimeACKTime / nAcks))); } - } diff --git a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/MeasureCommitPerfTest.java b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/MeasureCommitPerfTest.java index fa637e6fe2..9c4a2674bc 100644 --- a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/MeasureCommitPerfTest.java +++ b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/MeasureCommitPerfTest.java @@ -20,30 +20,24 @@ import javax.jms.Connection; import javax.jms.JMSException; import javax.jms.Session; -public class MeasureCommitPerfTest extends AbstractSendReceivePerfTest -{ +public class MeasureCommitPerfTest extends AbstractSendReceivePerfTest { + @Override - protected void consumeMessages(Connection c, String qName) throws Exception - { + protected void consumeMessages(Connection c, String qName) throws Exception { } - /* This will by default send non persistent messages */ - protected void sendMessages(Connection c, String qName) throws JMSException - { + protected void sendMessages(Connection c, String qName) throws JMSException { Session s = c.createSession(true, Session.SESSION_TRANSACTED); - long timeout = System.currentTimeMillis() + 30 * 1000; long startMeasure = System.currentTimeMillis() + 5000; long start = 0; long committs = 0; - while (timeout > System.currentTimeMillis()) - { + while (timeout > System.currentTimeMillis()) { - if (start == 0 && System.currentTimeMillis() > startMeasure) - { + if (start == 0 && System.currentTimeMillis() > startMeasure) { System.out.println("heat up"); start = System.currentTimeMillis(); committs = 0; @@ -51,26 +45,23 @@ public class MeasureCommitPerfTest extends AbstractSendReceivePerfTest s.commit(); committs++; - if (start > 0 && committs % 1000 == 0) printCommitsSecond(start, committs); + if (start > 0 && committs % 1000 == 0) + printCommitsSecond(start, committs); } printCommitsSecond(start, committs); s.close(); } - - protected void printCommitsSecond(final long start, final double committs) - { + protected void printCommitsSecond(final long start, final double committs) { long end = System.currentTimeMillis(); double elapsed = ((double) end - (double) start) / 1000f; double commitsPerSecond = committs / elapsed; - System.out.println("end = " + end + ", start=" + start + ", numberOfMessages=" - + committs + ", elapsed=" + elapsed + " msgs/sec= " + commitsPerSecond); + System.out.println("end = " + end + ", start=" + start + ", numberOfMessages=" + committs + ", elapsed=" + elapsed + " msgs/sec= " + commitsPerSecond); } - } diff --git a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/PreACKPerf.java b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/PreACKPerf.java index 5a9856e06e..acb5354c8c 100644 --- a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/PreACKPerf.java +++ b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/PreACKPerf.java @@ -24,11 +24,10 @@ import javax.jms.Session; import org.apache.activemq.artemis.api.jms.ActiveMQJMSConstants; -public class PreACKPerf extends AbstractSendReceivePerfTest -{ +public class PreACKPerf extends AbstractSendReceivePerfTest { + @Override - protected void consumeMessages(Connection c, String qName) throws Exception - { + protected void consumeMessages(Connection c, String qName) throws Exception { int mode = 0; mode = ActiveMQJMSConstants.PRE_ACKNOWLEDGE; @@ -42,24 +41,20 @@ public class PreACKPerf extends AbstractSendReceivePerfTest Message m = null; - long start = System.currentTimeMillis(); long nmessages = 0; long timeout = System.currentTimeMillis() + 30 * 1000; - while (timeout > System.currentTimeMillis()) - { + while (timeout > System.currentTimeMillis()) { m = consumer.receive(5000); nmessages++; - if (m == null) - { + if (m == null) { throw new Exception("Failed with m = null"); } - if (nmessages % 10000 == 0) - { + if (nmessages % 10000 == 0) { printMsgsSec(start, nmessages); } @@ -70,20 +65,15 @@ public class PreACKPerf extends AbstractSendReceivePerfTest printMsgsSec(start, nmessages); } - - - protected void printMsgsSec(final long start, final double nmessages) - { + protected void printMsgsSec(final long start, final double nmessages) { long end = System.currentTimeMillis(); double elapsed = ((double) end - (double) start) / 1000f; double messagesPerSecond = nmessages / elapsed; - System.out.println("end = " + end + ", start=" + start + ", numberOfMessages=" - + nmessages + ", elapsed=" + elapsed + " msgs/sec= " + messagesPerSecond); + System.out.println("end = " + end + ", start=" + start + ", numberOfMessages=" + nmessages + ", elapsed=" + elapsed + " msgs/sec= " + messagesPerSecond); } - } diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/ClientAbstract.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/ClientAbstract.java index 045340fd74..48105058dd 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/ClientAbstract.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/ClientAbstract.java @@ -34,8 +34,7 @@ import org.apache.activemq.artemis.utils.UUIDGenerator; *

    * And this is dealing with XA directly for the purpose testing only. */ -public abstract class ClientAbstract extends Thread -{ +public abstract class ClientAbstract extends Thread { // Constants ----------------------------------------------------- private static final UnitTestLogger log = UnitTestLogger.LOGGER; @@ -62,57 +61,44 @@ public abstract class ClientAbstract extends Thread // Constructors -------------------------------------------------- - public ClientAbstract(ClientSessionFactory sf) - { + public ClientAbstract(ClientSessionFactory sf) { this.sf = sf; } // Public -------------------------------------------------------- - public ClientSession getConnection() - { + public ClientSession getConnection() { return session; } - public int getErrorsCount() - { + public int getErrorsCount() { return errors; } - public final void connect() - { - while (running) - { - try - { + public final void connect() { + while (running) { + try { disconnect(); session = sf.createXASession(); - if (activeXid != null) - { - synchronized (ClientAbstract.class) - { + if (activeXid != null) { + synchronized (ClientAbstract.class) { Xid[] xids = session.recover(XAResource.TMSTARTRSCAN); boolean found = false; - for (Xid recXid : xids) - { - if (recXid.equals(activeXid)) - { + for (Xid recXid : xids) { + if (recXid.equals(activeXid)) { // System.out.println("Calling commit after a prepare on " + this); found = true; callCommit(); } } - if (!found) - { - if (pendingCommit) - { + if (!found) { + if (pendingCommit) { onCommit(); } - else - { + else { onRollback(); } @@ -126,16 +112,13 @@ public abstract class ClientAbstract extends Thread break; } - catch (Exception e) - { + catch (Exception e) { ClientAbstract.log.warn("Can't connect to server, retrying"); disconnect(); - try - { + try { Thread.sleep(1000); } - catch (InterruptedException ignored) - { + catch (InterruptedException ignored) { // if an interruption was sent, we will respect it and leave the loop break; } @@ -144,13 +127,11 @@ public abstract class ClientAbstract extends Thread } @Override - public void run() - { + public void run() { connect(); } - protected void callCommit() throws Exception - { + protected void callCommit() throws Exception { pendingCommit = true; session.commit(activeXid, false); pendingCommit = false; @@ -158,35 +139,30 @@ public abstract class ClientAbstract extends Thread onCommit(); } - protected void callPrepare() throws Exception - { + protected void callPrepare() throws Exception { session.prepare(activeXid); } - public void beginTX() throws Exception - { + public void beginTX() throws Exception { activeXid = newXID(); session.start(activeXid, XAResource.TMNOFLAGS); } - public void endTX() throws Exception - { + public void endTX() throws Exception { session.end(activeXid, XAResource.TMSUCCESS); callPrepare(); callCommit(); } - public void setRunning(final boolean running) - { + public void setRunning(final boolean running) { this.running = running; } /** * @return */ - private XidImpl newXID() - { + private XidImpl newXID() { return new XidImpl("tst".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes()); } @@ -196,17 +172,13 @@ public abstract class ClientAbstract extends Thread protected abstract void onRollback(); - public void disconnect() - { - try - { - if (session != null) - { + public void disconnect() { + try { + if (session != null) { session.close(); } } - catch (Exception ignored) - { + catch (Exception ignored) { ignored.printStackTrace(); } diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/ClientNonDivertedSoakTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/ClientNonDivertedSoakTest.java index 616c10128a..fe9a3e6ba7 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/ClientNonDivertedSoakTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/ClientNonDivertedSoakTest.java @@ -32,8 +32,7 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Before; import org.junit.Test; -public class ClientNonDivertedSoakTest extends ActiveMQTestBase -{ +public class ClientNonDivertedSoakTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -45,8 +44,7 @@ public class ClientNonDivertedSoakTest extends ActiveMQTestBase public static final int MIN_MESSAGES_ON_QUEUE = 5000; - protected boolean isNetty() - { + protected boolean isNetty() { return false; } @@ -60,12 +58,10 @@ public class ClientNonDivertedSoakTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - Configuration config = createDefaultConfig(isNetty()) - .setJournalFileSize(10 * 1024 * 1024); + Configuration config = createDefaultConfig(isNetty()).setJournalFileSize(10 * 1024 * 1024); server = createServer(IS_JOURNAL, config, -1, -1, new HashMap()); @@ -88,8 +84,7 @@ public class ClientNonDivertedSoakTest extends ActiveMQTestBase } @Test - public void testSoakClient() throws Exception - { + public void testSoakClient() throws Exception { ServerLocator locator = createFactory(isNetty()); final ClientSessionFactory sf = createSessionFactory(locator); @@ -98,15 +93,13 @@ public class ClientNonDivertedSoakTest extends ActiveMQTestBase ClientProducer producer = session.createProducer(ADDRESS); - for (int i = 0; i < MIN_MESSAGES_ON_QUEUE; i++) - { + for (int i = 0; i < MIN_MESSAGES_ON_QUEUE; i++) { ClientMessage msg = session.createMessage(true); msg.putLongProperty("count", i); msg.getBodyBuffer().writeBytes(new byte[10 * 1024]); producer.send(msg); - if (i % 1000 == 0) - { + if (i % 1000 == 0) { System.out.println("Sent " + i + " messages"); session.commit(); } @@ -125,10 +118,8 @@ public class ClientNonDivertedSoakTest extends ActiveMQTestBase rec1.start(); long timeEnd = System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1); - while (timeEnd > System.currentTimeMillis()) - { - if (send.getErrorsCount() != 0 || rec1.getErrorsCount() != 0) - { + while (timeEnd > System.currentTimeMillis()) { + if (send.getErrorsCount() != 0 || rec1.getErrorsCount() != 0) { System.out.println("There are sequence errors in some of the clients, please look at the logs"); break; } diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/ClientSoakTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/ClientSoakTest.java index 107812e08d..1f770d96e4 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/ClientSoakTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/ClientSoakTest.java @@ -34,8 +34,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.concurrent.TimeUnit; -public class ClientSoakTest extends ActiveMQTestBase -{ +public class ClientSoakTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -51,8 +50,7 @@ public class ClientSoakTest extends ActiveMQTestBase public static final int MIN_MESSAGES_ON_QUEUE = 5000; - protected boolean isNetty() - { + protected boolean isNetty() { return true; } @@ -66,29 +64,17 @@ public class ClientSoakTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); clearDataRecreateServerDirs(); - Configuration config = createDefaultConfig(isNetty()) - .setJournalFileSize(10 * 1024 * 1024); + Configuration config = createDefaultConfig(isNetty()).setJournalFileSize(10 * 1024 * 1024); server = createServer(IS_JOURNAL, config, -1, -1, new HashMap()); - DivertConfiguration divert1 = new DivertConfiguration() - .setName("dv1") - .setRoutingName("nm1") - .setAddress(ClientSoakTest.ADDRESS.toString()) - .setForwardingAddress(ClientSoakTest.DIVERTED_AD1.toString()) - .setExclusive(true); + DivertConfiguration divert1 = new DivertConfiguration().setName("dv1").setRoutingName("nm1").setAddress(ClientSoakTest.ADDRESS.toString()).setForwardingAddress(ClientSoakTest.DIVERTED_AD1.toString()).setExclusive(true); - DivertConfiguration divert2 = new DivertConfiguration() - .setName("dv2") - .setRoutingName("nm2") - .setAddress(ClientSoakTest.ADDRESS.toString()) - .setForwardingAddress(ClientSoakTest.DIVERTED_AD2.toString()) - .setExclusive(true); + DivertConfiguration divert2 = new DivertConfiguration().setName("dv2").setRoutingName("nm2").setAddress(ClientSoakTest.ADDRESS.toString()).setForwardingAddress(ClientSoakTest.DIVERTED_AD2.toString()).setExclusive(true); ArrayList divertList = new ArrayList(); divertList.add(divert1); @@ -119,8 +105,7 @@ public class ClientSoakTest extends ActiveMQTestBase } @Test - public void testSoakClient() throws Exception - { + public void testSoakClient() throws Exception { final ServerLocator locator = createFactory(isNetty()); final ClientSessionFactory sf = createSessionFactory(locator); @@ -128,15 +113,13 @@ public class ClientSoakTest extends ActiveMQTestBase ClientProducer producer = session.createProducer(ADDRESS); - for (int i = 0; i < MIN_MESSAGES_ON_QUEUE; i++) - { + for (int i = 0; i < MIN_MESSAGES_ON_QUEUE; i++) { ClientMessage msg = session.createMessage(true); msg.putLongProperty("count", i); msg.getBodyBuffer().writeBytes(new byte[10 * 1024]); producer.send(msg); - if (i % 1000 == 0) - { + if (i % 1000 == 0) { System.out.println("Sent " + i + " messages"); session.commit(); } @@ -157,10 +140,8 @@ public class ClientSoakTest extends ActiveMQTestBase rec2.start(); long timeEnd = System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1); - while (timeEnd > System.currentTimeMillis()) - { - if (send.getErrorsCount() != 0 || rec1.getErrorsCount() != 0 || rec2.getErrorsCount() != 0) - { + while (timeEnd > System.currentTimeMillis()) { + if (send.getErrorsCount() != 0 || rec1.getErrorsCount() != 0 || rec2.getErrorsCount() != 0) { System.out.println("There are sequence errors in some of the clients, please look at the logs"); break; } diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/Receiver.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/Receiver.java index b36a6c6f2a..9a239fe69d 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/Receiver.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/Receiver.java @@ -25,8 +25,7 @@ import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.utils.ReusableLatch; -public class Receiver extends ClientAbstract -{ +public class Receiver extends ClientAbstract { // Constants ----------------------------------------------------- @@ -52,48 +51,39 @@ public class Receiver extends ClientAbstract protected ClientConsumer cons; - // Static -------------------------------------------------------- // Constructors -------------------------------------------------- - public Receiver(ClientSessionFactory sf, String queue) - { + public Receiver(ClientSessionFactory sf, String queue) { super(sf); this.queue = queue; } // Public -------------------------------------------------------- - public void run() - { + public void run() { super.run(); - while (running) - { - try - { + while (running) { + try { beginTX(); - for (int i = 0; i < 1000; i++) - { + for (int i = 0; i < 1000; i++) { ClientMessage msg = cons.receive(5000); - if (msg == null) - { + if (msg == null) { break; } msg.acknowledge(); - if (msg.getLongProperty("count") != msgs + pendingMsgs) - { + if (msg.getLongProperty("count") != msgs + pendingMsgs) { errors++; System.out.println("count should be " + (msgs + pendingMsgs) + " when it was " + msg.getLongProperty("count") + " on " + queue); } pendingMsgs++; - if (!minConsume.tryAcquire(1, 5, TimeUnit.SECONDS)) - { + if (!minConsume.tryAcquire(1, 5, TimeUnit.SECONDS)) { break; } @@ -101,12 +91,10 @@ public class Receiver extends ClientAbstract endTX(); } - catch (Exception e) - { + catch (Exception e) { connect(); } - } } @@ -114,8 +102,7 @@ public class Receiver extends ClientAbstract * @see org.apache.activemq.artemis.jms.example.ClientAbstract#connectClients() */ @Override - protected void connectClients() throws Exception - { + protected void connectClients() throws Exception { cons = session.createConsumer(queue); @@ -126,8 +113,7 @@ public class Receiver extends ClientAbstract * @see org.apache.activemq.artemis.jms.example.ClientAbstract#onCommit() */ @Override - protected void onCommit() - { + protected void onCommit() { msgs += pendingMsgs; this.currentDiff.addAndGet(-pendingMsgs); latchMax.countDown(pendingMsgs); @@ -138,33 +124,27 @@ public class Receiver extends ClientAbstract * @see org.apache.activemq.artemis.jms.example.ClientAbstract#onRollback() */ @Override - protected void onRollback() - { + protected void onRollback() { minConsume.release(pendingMsgs); pendingMsgs = 0; } - public String toString() - { + public String toString() { return "Receiver::" + this.queue + ", msgs=" + msgs + ", pending=" + pendingMsgs; } /** * @param pendingMsgs2 */ - public void messageProduced(int producedMessages) - { + public void messageProduced(int producedMessages) { minConsume.release(producedMessages); currentDiff.addAndGet(producedMessages); - if (currentDiff.get() > MAX_DIFF) - { + if (currentDiff.get() > MAX_DIFF) { latchMax.setCount(currentDiff.get() - MAX_DIFF); - try - { + try { latchMax.await(5, TimeUnit.SECONDS); } - catch (InterruptedException e) - { + catch (InterruptedException e) { e.printStackTrace(); } } diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/Sender.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/Sender.java index 9773b3365e..e1d18cfe49 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/Sender.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/Sender.java @@ -20,8 +20,7 @@ import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.apache.activemq.artemis.api.core.client.ClientProducer; import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; -public class Sender extends ClientAbstract -{ +public class Sender extends ClientAbstract { // Constants ----------------------------------------------------- @@ -43,29 +42,23 @@ public class Sender extends ClientAbstract // Public -------------------------------------------------------- - public Sender(final ClientSessionFactory sf, String queue, final Receiver[] receivers) - { + public Sender(final ClientSessionFactory sf, String queue, final Receiver[] receivers) { super(sf); this.receivers = receivers; this.queue = queue; } @Override - protected void connectClients() throws Exception - { + protected void connectClients() throws Exception { producer = session.createProducer(queue); } - public void run() - { + public void run() { super.run(); - while (running) - { - try - { + while (running) { + try { beginTX(); - for (int i = 0; i < 1000; i++) - { + for (int i = 0; i < 1000; i++) { ClientMessage msg = session.createMessage(true); msg.putLongProperty("count", pendingMsgs + msgs); msg.getBodyBuffer().writeBytes(new byte[10 * 1024]); @@ -74,8 +67,7 @@ public class Sender extends ClientAbstract } endTX(); } - catch (Exception e) - { + catch (Exception e) { connect(); } } @@ -85,11 +77,9 @@ public class Sender extends ClientAbstract * @see org.apache.activemq.artemis.jms.example.ClientAbstract#onCommit() */ @Override - protected void onCommit() - { + protected void onCommit() { this.msgs += pendingMsgs; - for (Receiver rec : receivers) - { + for (Receiver rec : receivers) { rec.messageProduced(pendingMsgs); } @@ -100,13 +90,11 @@ public class Sender extends ClientAbstract * @see org.apache.activemq.artemis.jms.example.ClientAbstract#onRollback() */ @Override - protected void onRollback() - { + protected void onRollback() { pendingMsgs = 0; } - public String toString() - { + public String toString() { return "Sender, msgs=" + msgs + ", pending=" + pendingMsgs; } diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/SimpleSendReceiveSoakTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/SimpleSendReceiveSoakTest.java index 21a4da9cd4..c2259a8190 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/SimpleSendReceiveSoakTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/SimpleSendReceiveSoakTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.soak.client; + import org.junit.Before; import org.junit.Test; @@ -33,8 +34,7 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.settings.impl.AddressSettings; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -public class SimpleSendReceiveSoakTest extends ActiveMQTestBase -{ +public class SimpleSendReceiveSoakTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -46,8 +46,7 @@ public class SimpleSendReceiveSoakTest extends ActiveMQTestBase public static final int MIN_MESSAGES_ON_QUEUE = 1000; - protected boolean isNetty() - { + protected boolean isNetty() { return false; } @@ -61,14 +60,12 @@ public class SimpleSendReceiveSoakTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); clearDataRecreateServerDirs(); - Configuration config = createDefaultConfig(isNetty()) - .setJournalFileSize(10 * 1024 * 1024); + Configuration config = createDefaultConfig(isNetty()).setJournalFileSize(10 * 1024 * 1024); server = createServer(IS_JOURNAL, config, -1, -1, new HashMap()); @@ -86,8 +83,7 @@ public class SimpleSendReceiveSoakTest extends ActiveMQTestBase } @Test - public void testSoakClientTransactions() throws Exception - { + public void testSoakClientTransactions() throws Exception { final ServerLocator locator = createFactory(isNetty()); final ClientSessionFactory sf = createSessionFactory(locator); @@ -100,8 +96,7 @@ public class SimpleSendReceiveSoakTest extends ActiveMQTestBase long msgReceivedID = 0; - for (int i = 0; i < MIN_MESSAGES_ON_QUEUE; i++) - { + for (int i = 0; i < MIN_MESSAGES_ON_QUEUE; i++) { ClientMessage msg = session.createMessage(IS_JOURNAL); msg.putLongProperty("count", msgId++); msg.getBodyBuffer().writeBytes(new byte[10 * 1024]); @@ -112,19 +107,16 @@ public class SimpleSendReceiveSoakTest extends ActiveMQTestBase ClientConsumer consumer = sessionConsumer.createConsumer(ADDRESS); sessionConsumer.start(); - for (int loopNumber = 0; loopNumber < 1000; loopNumber++) - { + for (int loopNumber = 0; loopNumber < 1000; loopNumber++) { System.out.println("Loop " + loopNumber); - for (int i = 0; i < MIN_MESSAGES_ON_QUEUE; i++) - { + for (int i = 0; i < MIN_MESSAGES_ON_QUEUE; i++) { ClientMessage msg = session.createMessage(IS_JOURNAL); msg.putLongProperty("count", msgId++); msg.getBodyBuffer().writeBytes(new byte[10 * 1024]); producer.send(msg); } - for (int i = 0; i < MIN_MESSAGES_ON_QUEUE; i++) - { + for (int i = 0; i < MIN_MESSAGES_ON_QUEUE; i++) { ClientMessage msg = consumer.receive(5000); assertNotNull(msg); msg.acknowledge(); diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/failover/RandomFailoverSoakTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/failover/RandomFailoverSoakTest.java index f8c3b16e70..0daa8cd730 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/failover/RandomFailoverSoakTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/failover/RandomFailoverSoakTest.java @@ -18,12 +18,10 @@ package org.apache.activemq.artemis.tests.soak.failover; import org.apache.activemq.artemis.tests.integration.cluster.reattach.RandomReattachTest; -public class RandomFailoverSoakTest extends RandomReattachTest -{ +public class RandomFailoverSoakTest extends RandomReattachTest { @Override - protected int getNumIterations() - { + protected int getNumIterations() { return 500; } diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/chunk/LargeMessageStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/chunk/LargeMessageStressTest.java index d229af2224..ff8dc3be9e 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/chunk/LargeMessageStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/chunk/LargeMessageStressTest.java @@ -19,8 +19,7 @@ package org.apache.activemq.artemis.tests.stress.chunk; import org.apache.activemq.artemis.tests.integration.largemessage.LargeMessageTestBase; import org.junit.Test; -public class LargeMessageStressTest extends LargeMessageTestBase -{ +public class LargeMessageStressTest extends LargeMessageTestBase { // Constants ----------------------------------------------------- @@ -33,23 +32,8 @@ public class LargeMessageStressTest extends LargeMessageTestBase // Public -------------------------------------------------------- @Test - public void testMessageChunkFilePersistenceOneHugeMessage() throws Exception - { - testChunks(false, - false, - false, - true, - true, - false, - false, - false, - true, - 1, - 200 * 1024L * 1024L + 1024L, - 120000, - 0, - 10 * 1024 * 1024, - 1024 * 1024); + public void testMessageChunkFilePersistenceOneHugeMessage() throws Exception { + testChunks(false, false, false, true, true, false, false, false, true, 1, 200 * 1024L * 1024L + 1024L, 120000, 0, 10 * 1024 * 1024, 1024 * 1024); } // Package protected --------------------------------------------- diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/client/SendStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/client/SendStressTest.java index 0fd503b4d9..d667786e2f 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/client/SendStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/client/SendStressTest.java @@ -27,8 +27,7 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Assert; import org.junit.Test; -public class SendStressTest extends ActiveMQTestBase -{ +public class SendStressTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -42,19 +41,16 @@ public class SendStressTest extends ActiveMQTestBase // Remove this method to re-enable those tests @Test - public void testStressSendNetty() throws Exception - { + public void testStressSendNetty() throws Exception { doTestStressSend(true); } @Test - public void testStressSendInVM() throws Exception - { + public void testStressSendInVM() throws Exception { doTestStressSend(false); } - public void doTestStressSend(final boolean netty) throws Exception - { + public void doTestStressSend(final boolean netty) throws Exception { ActiveMQServer server = createServer(false, netty); server.start(); ServerLocator locator = createNonHALocator(netty); @@ -66,8 +62,7 @@ public class SendStressTest extends ActiveMQTestBase final int numberOfMessages = 100000; - try - { + try { server.start(); session = sf.createSession(false, false); @@ -80,11 +75,9 @@ public class SendStressTest extends ActiveMQTestBase message.getBodyBuffer().writeBytes(new byte[1024]); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { producer.send(message); - if (i % batchSize == 0) - { + if (i % batchSize == 0) { System.out.println("Sent " + i); session.commit(); } @@ -100,14 +93,12 @@ public class SendStressTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = consumer.receive(5000); Assert.assertNotNull(msg); msg.acknowledge(); - if (i % batchSize == 0) - { + if (i % batchSize == 0) { System.out.println("Consumed " + i); session.commit(); } @@ -115,17 +106,13 @@ public class SendStressTest extends ActiveMQTestBase session.commit(); } - finally - { - if (session != null) - { - try - { + finally { + if (session != null) { + try { sf.close(); session.close(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/failover/MultiThreadRandomReattachStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/failover/MultiThreadRandomReattachStressTest.java index e527ddd611..91683fadfe 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/failover/MultiThreadRandomReattachStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/failover/MultiThreadRandomReattachStressTest.java @@ -18,11 +18,10 @@ package org.apache.activemq.artemis.tests.stress.failover; import org.apache.activemq.artemis.tests.integration.cluster.reattach.MultiThreadRandomReattachTest; -public class MultiThreadRandomReattachStressTest extends MultiThreadRandomReattachTest -{ +public class MultiThreadRandomReattachStressTest extends MultiThreadRandomReattachTest { + @Override - protected int getNumIterations() - { + protected int getNumIterations() { return 100; } diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/failover/RandomReattachStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/failover/RandomReattachStressTest.java index aeedc54193..854f3be395 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/failover/RandomReattachStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/failover/RandomReattachStressTest.java @@ -18,8 +18,7 @@ package org.apache.activemq.artemis.tests.stress.failover; import org.apache.activemq.artemis.tests.integration.cluster.reattach.RandomReattachTest; -public class RandomReattachStressTest extends RandomReattachTest -{ +public class RandomReattachStressTest extends RandomReattachTest { // Constants ----------------------------------------------------- @@ -36,8 +35,7 @@ public class RandomReattachStressTest extends RandomReattachTest // Protected ----------------------------------------------------- @Override - protected int getNumIterations() - { + protected int getNumIterations() { return 100; } diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AIOAllPossibilitiesCompactStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AIOAllPossibilitiesCompactStressTest.java index eddc347c16..3d584fdbb1 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AIOAllPossibilitiesCompactStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AIOAllPossibilitiesCompactStressTest.java @@ -22,8 +22,7 @@ import org.apache.activemq.artemis.core.io.SequentialFileFactory; import org.apache.activemq.artemis.core.io.aio.AIOSequentialFileFactory; import org.apache.activemq.artemis.core.journal.impl.JournalConstants; -public class AIOAllPossibilitiesCompactStressTest extends AllPossibilitiesCompactStressTest -{ +public class AIOAllPossibilitiesCompactStressTest extends AllPossibilitiesCompactStressTest { // Constants ----------------------------------------------------- @@ -43,19 +42,14 @@ public class AIOAllPossibilitiesCompactStressTest extends AllPossibilitiesCompac // Inner classes ------------------------------------------------- @Override - protected SequentialFileFactory getFileFactory() throws Exception - { + protected SequentialFileFactory getFileFactory() throws Exception { File file = new File(getTestDir()); deleteDirectory(file); file.mkdir(); - return new AIOSequentialFileFactory(getTestDirfile(), - JournalConstants.DEFAULT_JOURNAL_BUFFER_SIZE_AIO, - 1000000, 1000, - false); + return new AIOSequentialFileFactory(getTestDirfile(), JournalConstants.DEFAULT_JOURNAL_BUFFER_SIZE_AIO, 1000000, 1000, false); } - } diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AIOMultiThreadCompactorStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AIOMultiThreadCompactorStressTest.java index b2a31292d8..3b6fb7287a 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AIOMultiThreadCompactorStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AIOMultiThreadCompactorStressTest.java @@ -20,12 +20,10 @@ import org.apache.activemq.artemis.core.io.aio.AIOSequentialFileFactory; import org.apache.activemq.artemis.core.server.JournalType; import org.junit.BeforeClass; -public class AIOMultiThreadCompactorStressTest extends NIOMultiThreadCompactorStressTest -{ +public class AIOMultiThreadCompactorStressTest extends NIOMultiThreadCompactorStressTest { @BeforeClass - public static void hasAIO() - { + public static void hasAIO() { org.junit.Assume.assumeTrue("Test case needs AIO to run", AIOSequentialFileFactory.isSupported()); } @@ -33,8 +31,7 @@ public class AIOMultiThreadCompactorStressTest extends NIOMultiThreadCompactorSt * @return */ @Override - protected JournalType getJournalType() - { + protected JournalType getJournalType() { return JournalType.ASYNCIO; } diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AddAndRemoveStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AddAndRemoveStressTest.java index 7abc703bff..54ac07507f 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AddAndRemoveStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AddAndRemoveStressTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.stress.journal; + import java.util.ArrayList; import java.util.List; @@ -29,34 +30,27 @@ import org.apache.activemq.artemis.core.journal.impl.JournalImpl; import org.junit.Assert; import org.junit.Test; -public class AddAndRemoveStressTest extends ActiveMQTestBase -{ +public class AddAndRemoveStressTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- - private static final LoaderCallback dummyLoader = new LoaderCallback() - { + private static final LoaderCallback dummyLoader = new LoaderCallback() { - public void addPreparedTransaction(final PreparedTransactionInfo preparedTransaction) - { + public void addPreparedTransaction(final PreparedTransactionInfo preparedTransaction) { } - public void addRecord(final RecordInfo info) - { + public void addRecord(final RecordInfo info) { } - public void deleteRecord(final long id) - { + public void deleteRecord(final long id) { } - public void updateRecord(final RecordInfo info) - { + public void updateRecord(final RecordInfo info) { } public void failedTransaction(final long transactionID, final List records, - final List recordsToDelete) - { + final List recordsToDelete) { } }; @@ -73,52 +67,33 @@ public class AddAndRemoveStressTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testInsertAndLoad() throws Exception - { + public void testInsertAndLoad() throws Exception { SequentialFileFactory factory = new AIOSequentialFileFactory(getTestDirfile(), 1000); - JournalImpl impl = new JournalImpl(10 * 1024 * 1024, - AddAndRemoveStressTest.NUMBER_OF_FILES_ON_JOURNAL, - 0, - 0, - factory, - "amq", - "amq", - 1000); + JournalImpl impl = new JournalImpl(10 * 1024 * 1024, AddAndRemoveStressTest.NUMBER_OF_FILES_ON_JOURNAL, 0, 0, factory, "amq", "amq", 1000); impl.start(); impl.load(AddAndRemoveStressTest.dummyLoader); - for (long i = 1; i <= AddAndRemoveStressTest.NUMBER_OF_MESSAGES; i++) - { - if (i % 10000 == 0) - { + for (long i = 1; i <= AddAndRemoveStressTest.NUMBER_OF_MESSAGES; i++) { + if (i % 10000 == 0) { System.out.println("Append " + i); } - impl.appendAddRecord(i, (byte)0, new SimpleEncoding(1024, (byte)'f'), false); + impl.appendAddRecord(i, (byte) 0, new SimpleEncoding(1024, (byte) 'f'), false); } impl.stop(); factory = new AIOSequentialFileFactory(getTestDirfile(), 1000); - impl = new JournalImpl(10 * 1024 * 1024, - AddAndRemoveStressTest.NUMBER_OF_FILES_ON_JOURNAL, - 0, - 0, - factory, - "amq", - "amq", - 1000); + impl = new JournalImpl(10 * 1024 * 1024, AddAndRemoveStressTest.NUMBER_OF_FILES_ON_JOURNAL, 0, 0, factory, "amq", "amq", 1000); impl.start(); impl.load(AddAndRemoveStressTest.dummyLoader); - for (long i = 1; i <= AddAndRemoveStressTest.NUMBER_OF_MESSAGES; i++) - { - if (i % 10000 == 0) - { + for (long i = 1; i <= AddAndRemoveStressTest.NUMBER_OF_MESSAGES; i++) { + if (i % 10000 == 0) { System.out.println("Delete " + i); } @@ -128,14 +103,7 @@ public class AddAndRemoveStressTest extends ActiveMQTestBase impl.stop(); factory = new AIOSequentialFileFactory(getTestDirfile(), 1000); - impl = new JournalImpl(10 * 1024 * 1024, - AddAndRemoveStressTest.NUMBER_OF_FILES_ON_JOURNAL, - 0, - 0, - factory, - "amq", - "amq", - 1000); + impl = new JournalImpl(10 * 1024 * 1024, AddAndRemoveStressTest.NUMBER_OF_FILES_ON_JOURNAL, 0, 0, factory, "amq", "amq", 1000); impl.start(); @@ -146,8 +114,7 @@ public class AddAndRemoveStressTest extends ActiveMQTestBase impl.forceMoveNextFile(); - if (info.size() > 0) - { + if (info.size() > 0) { System.out.println("Info ID: " + info.get(0).id); } @@ -161,31 +128,21 @@ public class AddAndRemoveStressTest extends ActiveMQTestBase } @Test - public void testInsertUpdateAndLoad() throws Exception - { + public void testInsertUpdateAndLoad() throws Exception { SequentialFileFactory factory = new AIOSequentialFileFactory(getTestDirfile(), 1000); - JournalImpl impl = new JournalImpl(10 * 1024 * 1024, - AddAndRemoveStressTest.NUMBER_OF_FILES_ON_JOURNAL, - 0, - 0, - factory, - "amq", - "amq", - 1000); + JournalImpl impl = new JournalImpl(10 * 1024 * 1024, AddAndRemoveStressTest.NUMBER_OF_FILES_ON_JOURNAL, 0, 0, factory, "amq", "amq", 1000); impl.start(); impl.load(AddAndRemoveStressTest.dummyLoader); - for (long i = 1; i <= AddAndRemoveStressTest.NUMBER_OF_MESSAGES; i++) - { - if (i % 10000 == 0) - { + for (long i = 1; i <= AddAndRemoveStressTest.NUMBER_OF_MESSAGES; i++) { + if (i % 10000 == 0) { System.out.println("Append " + i); } - impl.appendAddRecord(i, (byte)21, new SimpleEncoding(40, (byte)'f'), false); - impl.appendUpdateRecord(i, (byte)22, new SimpleEncoding(40, (byte)'g'), false); + impl.appendAddRecord(i, (byte) 21, new SimpleEncoding(40, (byte) 'f'), false); + impl.appendUpdateRecord(i, (byte) 22, new SimpleEncoding(40, (byte) 'g'), false); } impl.stop(); @@ -197,10 +154,8 @@ public class AddAndRemoveStressTest extends ActiveMQTestBase impl.load(AddAndRemoveStressTest.dummyLoader); - for (long i = 1; i <= AddAndRemoveStressTest.NUMBER_OF_MESSAGES; i++) - { - if (i % 10000 == 0) - { + for (long i = 1; i <= AddAndRemoveStressTest.NUMBER_OF_MESSAGES; i++) { + if (i % 10000 == 0) { System.out.println("Delete " + i); } @@ -210,14 +165,7 @@ public class AddAndRemoveStressTest extends ActiveMQTestBase impl.stop(); factory = new AIOSequentialFileFactory(getTestDirfile(), 1000); - impl = new JournalImpl(10 * 1024 * 1024, - AddAndRemoveStressTest.NUMBER_OF_FILES_ON_JOURNAL, - 0, - 0, - factory, - "amq", - "amq", - 1000); + impl = new JournalImpl(10 * 1024 * 1024, AddAndRemoveStressTest.NUMBER_OF_FILES_ON_JOURNAL, 0, 0, factory, "amq", "amq", 1000); impl.start(); @@ -226,8 +174,7 @@ public class AddAndRemoveStressTest extends ActiveMQTestBase impl.load(info, trans, null); - if (info.size() > 0) - { + if (info.size() > 0) { System.out.println("Info ID: " + info.get(0).id); } diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AllPossibilitiesCompactStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AllPossibilitiesCompactStressTest.java index cd1e72eb34..00a5ac26c8 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AllPossibilitiesCompactStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AllPossibilitiesCompactStressTest.java @@ -16,12 +16,9 @@ */ package org.apache.activemq.artemis.tests.stress.journal; +public class AllPossibilitiesCompactStressTest extends MixupCompactorTestBase { -public class AllPossibilitiesCompactStressTest extends MixupCompactorTestBase -{ - - public void internalTest() throws Exception - { + public void internalTest() throws Exception { createJournal(); startJournal(); diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AllPossibilitiesCompactWithAddDeleteStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AllPossibilitiesCompactWithAddDeleteStressTest.java index 830b2bb90c..bfc2191e10 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AllPossibilitiesCompactWithAddDeleteStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AllPossibilitiesCompactWithAddDeleteStressTest.java @@ -16,11 +16,9 @@ */ package org.apache.activemq.artemis.tests.stress.journal; -public class AllPossibilitiesCompactWithAddDeleteStressTest extends MixupCompactorTestBase -{ +public class AllPossibilitiesCompactWithAddDeleteStressTest extends MixupCompactorTestBase { - public void internalTest() throws Exception - { + public void internalTest() throws Exception { createJournal(); startJournal(); diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/CompactingStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/CompactingStressTest.java index 49354e4b54..48895ba317 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/CompactingStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/CompactingStressTest.java @@ -35,8 +35,7 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Assert; import org.junit.Test; -public class CompactingStressTest extends ActiveMQTestBase -{ +public class CompactingStressTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -67,32 +66,27 @@ public class CompactingStressTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testCleanupAIO() throws Throwable - { - if (LibaioContext.isLoaded()) - { + public void testCleanupAIO() throws Throwable { + if (LibaioContext.isLoaded()) { internalTestCleanup(JournalType.ASYNCIO); } } @Test - public void testCleanupNIO() throws Throwable - { + public void testCleanupNIO() throws Throwable { internalTestCleanup(JournalType.NIO); tearDown(); setUp(); } - private void internalTestCleanup(final JournalType journalType) throws Throwable - { + private void internalTestCleanup(final JournalType journalType) throws Throwable { setupServer(journalType); ClientSession session = sf.createSession(false, true, true); ClientProducer prod = session.createProducer(CompactingStressTest.AD1); - for (int i = 0; i < 500; i++) - { + for (int i = 0; i < 500; i++) { prod.send(session.createMessage(true)); } @@ -105,12 +99,10 @@ public class CompactingStressTest extends ActiveMQTestBase session.start(); - for (int i = 0; i < 200; i++) - { + for (int i = 0; i < 200; i++) { System.out.println("Iteration " + i); // Sending non transactionally, so it would test non transactional stuff on the journal - for (int j = 0; j < 1000; j++) - { + for (int j = 0; j < 1000; j++) { Message msg = session.createMessage(true); msg.getBodyBuffer().writeBytes(new byte[1024]); @@ -120,8 +112,7 @@ public class CompactingStressTest extends ActiveMQTestBase // I need to guarantee a roundtrip to the server, to make sure everything is persisted session.commit(); - for (int j = 0; j < 1000; j++) - { + for (int j = 0; j < 1000; j++) { ClientMessage msg = cons.receive(2000); Assert.assertNotNull(msg); msg.acknowledge(); @@ -146,8 +137,7 @@ public class CompactingStressTest extends ActiveMQTestBase cons = session.createConsumer(CompactingStressTest.Q1); session.start(); - for (int i = 0; i < 500; i++) - { + for (int i = 0; i < 500; i++) { ClientMessage msg = cons.receive(1000); Assert.assertNotNull(msg); msg.acknowledge(); @@ -162,46 +152,38 @@ public class CompactingStressTest extends ActiveMQTestBase } @Test - public void testMultiProducerAndCompactAIO() throws Throwable - { - if (LibaioContext.isLoaded()) - { + public void testMultiProducerAndCompactAIO() throws Throwable { + if (LibaioContext.isLoaded()) { internalTestMultiProducer(JournalType.ASYNCIO); } } @Test - public void testMultiProducerAndCompactNIO() throws Throwable - { + public void testMultiProducerAndCompactNIO() throws Throwable { internalTestMultiProducer(JournalType.NIO); } - public void internalTestMultiProducer(final JournalType journalType) throws Throwable - { + public void internalTestMultiProducer(final JournalType journalType) throws Throwable { setupServer(journalType); ClientSession session = sf.createSession(false, false); - try - { + try { ClientProducer producer = session.createProducer(CompactingStressTest.AD3); ClientMessage msg = session.createMessage(true); - for (int i = 0; i < CompactingStressTest.TOT_AD3; i++) - { + for (int i = 0; i < CompactingStressTest.TOT_AD3; i++) { producer.send(msg); - if (i % 100 == 0) - { + if (i % 100 == 0) { session.commit(); } } session.commit(); } - finally - { + finally { session.close(); } @@ -216,34 +198,28 @@ public class CompactingStressTest extends ActiveMQTestBase final CountDownLatch latchReady = new CountDownLatch(2); final CountDownLatch latchStart = new CountDownLatch(1); - class FastProducer extends Thread - { + class FastProducer extends Thread { + Throwable e; - FastProducer() - { + FastProducer() { super("Fast-Thread"); } @Override - public void run() - { + public void run() { ClientSession session = null; ClientSession sessionSlow = null; latchReady.countDown(); - try - { + try { ActiveMQTestBase.waitForLatch(latchStart); session = sf.createSession(true, true); sessionSlow = sf.createSession(false, false); ClientProducer prod = session.createProducer(CompactingStressTest.AD2); ClientProducer slowProd = sessionSlow.createProducer(CompactingStressTest.AD1); - for (int i = 0; i < NUMBER_OF_FAST_MESSAGES; i++) - { - if (i % SLOW_INTERVAL == 0) - { - if (numberOfMessages.incrementAndGet() % 5 == 0) - { + for (int i = 0; i < NUMBER_OF_FAST_MESSAGES; i++) { + if (i % SLOW_INTERVAL == 0) { + if (numberOfMessages.incrementAndGet() % 5 == 0) { sessionSlow.commit(); } slowProd.send(session.createMessage(true)); @@ -254,72 +230,58 @@ public class CompactingStressTest extends ActiveMQTestBase } sessionSlow.commit(); } - catch (Throwable e) - { + catch (Throwable e) { this.e = e; } - finally - { - try - { + finally { + try { session.close(); } - catch (Throwable e) - { + catch (Throwable e) { this.e = e; } - try - { + try { sessionSlow.close(); } - catch (Throwable e) - { + catch (Throwable e) { this.e = e; } } } } - class FastConsumer extends Thread - { + class FastConsumer extends Thread { + Throwable e; - FastConsumer() - { + FastConsumer() { super("Fast-Consumer"); } @Override - public void run() - { + public void run() { ClientSession session = null; latchReady.countDown(); - try - { + try { ActiveMQTestBase.waitForLatch(latchStart); session = sf.createSession(true, true); session.start(); ClientConsumer cons = session.createConsumer(CompactingStressTest.Q2); - for (int i = 0; i < NUMBER_OF_FAST_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_FAST_MESSAGES; i++) { ClientMessage msg = cons.receive(60 * 1000); msg.acknowledge(); } Assert.assertNull(cons.receiveImmediate()); } - catch (Throwable e) - { + catch (Throwable e) { this.e = e; } - finally - { - try - { + finally { + try { session.close(); } - catch (Throwable e) - { + catch (Throwable e) { this.e = e; } } @@ -337,15 +299,13 @@ public class CompactingStressTest extends ActiveMQTestBase p1.join(); - if (p1.e != null) - { + if (p1.e != null) { throw p1.e; } f1.join(); - if (f1.e != null) - { + if (f1.e != null) { throw f1.e; } @@ -357,8 +317,7 @@ public class CompactingStressTest extends ActiveMQTestBase ClientSession sess = null; - try - { + try { sess = sf.createSession(true, true); @@ -366,8 +325,7 @@ public class CompactingStressTest extends ActiveMQTestBase sess.start(); - for (int i = 0; i < numberOfMessages.intValue(); i++) - { + for (int i = 0; i < numberOfMessages.intValue(); i++) { ClientMessage msg = cons.receive(60000); Assert.assertNotNull(msg); msg.acknowledge(); @@ -385,8 +343,7 @@ public class CompactingStressTest extends ActiveMQTestBase cons = sess.createConsumer(CompactingStressTest.Q3); - for (int i = 0; i < CompactingStressTest.TOT_AD3; i++) - { + for (int i = 0; i < CompactingStressTest.TOT_AD3; i++) { ClientMessage msg = cons.receive(60000); Assert.assertNotNull(msg); msg.acknowledge(); @@ -395,61 +352,43 @@ public class CompactingStressTest extends ActiveMQTestBase Assert.assertNull(cons.receiveImmediate()); } - finally - { - try - { + finally { + try { sess.close(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } } - private void setupServer(final JournalType journalType) throws Exception - { - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false) - .setJournalFileSize(ActiveMQDefaultConfiguration.getDefaultJournalFileSize()) - .setJournalType(journalType) - .setJournalCompactMinFiles(10) - .setJournalCompactPercentage(50); + private void setupServer(final JournalType journalType) throws Exception { + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false).setJournalFileSize(ActiveMQDefaultConfiguration.getDefaultJournalFileSize()).setJournalType(journalType).setJournalCompactMinFiles(10).setJournalCompactPercentage(50); server = createServer(true, config); server.start(); - - ServerLocator locator = createInVMNonHALocator() - .setBlockOnDurableSend(false) - .setBlockOnAcknowledge(false); + ServerLocator locator = createInVMNonHALocator().setBlockOnDurableSend(false).setBlockOnAcknowledge(false); sf = createSessionFactory(locator); ClientSession sess = addClientSession(sf.createSession()); - try - { + try { sess.createQueue(CompactingStressTest.AD1, CompactingStressTest.Q1, true); } - catch (Exception ignored) - { + catch (Exception ignored) { } - try - { + try { sess.createQueue(CompactingStressTest.AD2, CompactingStressTest.Q2, true); } - catch (Exception ignored) - { + catch (Exception ignored) { } - try - { + try { sess.createQueue(CompactingStressTest.AD3, CompactingStressTest.Q3, true); } - catch (Exception ignored) - { + catch (Exception ignored) { } sess.close(); diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/JournalCleanupCompactStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/JournalCleanupCompactStressTest.java index 3675cd8c43..8d7dcabada 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/JournalCleanupCompactStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/JournalCleanupCompactStressTest.java @@ -52,8 +52,7 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -public class JournalCleanupCompactStressTest extends ActiveMQTestBase -{ +public class JournalCleanupCompactStressTest extends ActiveMQTestBase { public static SimpleIDGenerator idGen = new SimpleIDGenerator(1); @@ -76,9 +75,7 @@ public class JournalCleanupCompactStressTest extends ActiveMQTestBase private JournalImpl journal; - ThreadFactory tFactory = new ActiveMQThreadFactory("SoakTest" + System.identityHashCode(this), - false, - JournalCleanupCompactStressTest.class.getClassLoader()); + ThreadFactory tFactory = new ActiveMQThreadFactory("SoakTest" + System.identityHashCode(this), false, JournalCleanupCompactStressTest.class.getClassLoader()); private ExecutorService threadPool; @@ -86,16 +83,13 @@ public class JournalCleanupCompactStressTest extends ActiveMQTestBase Executor testExecutor; - protected long getTotalTimeMilliseconds() - { + protected long getTotalTimeMilliseconds() { return TimeUnit.MINUTES.toMillis(2); } - @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); threadPool = Executors.newFixedThreadPool(20, tFactory); @@ -112,43 +106,27 @@ public class JournalCleanupCompactStressTest extends ActiveMQTestBase SequentialFileFactory factory; int maxAIO; - if (LibaioContext.isLoaded()) - { + if (LibaioContext.isLoaded()) { factory = new AIOSequentialFileFactory(dir, 10); maxAIO = ActiveMQDefaultConfiguration.getDefaultJournalMaxIoAio(); } - else - { + else { factory = new NIOSequentialFileFactory(dir, true, 1); maxAIO = ActiveMQDefaultConfiguration.getDefaultJournalMaxIoNio(); } - journal = new JournalImpl(50 * 1024, - 20, - 50, - ActiveMQDefaultConfiguration.getDefaultJournalCompactPercentage(), - factory, - "activemq-data", - "amq", - maxAIO) - { + journal = new JournalImpl(50 * 1024, 20, 50, ActiveMQDefaultConfiguration.getDefaultJournalCompactPercentage(), factory, "activemq-data", "amq", maxAIO) { @Override - protected void onCompactLockingTheJournal() throws Exception - { + protected void onCompactLockingTheJournal() throws Exception { } @Override - protected void onCompactStart() throws Exception - { - testExecutor.execute(new Runnable() - { - public void run() - { - try - { + protected void onCompactStart() throws Exception { + testExecutor.execute(new Runnable() { + public void run() { + try { // System.out.println("OnCompactStart enter"); - if (running) - { + if (running) { long id = idGen.generateID(); journal.appendAddRecord(id, (byte) 0, new byte[]{1, 2, 3}, false); journal.forceMoveNextFile(); @@ -156,8 +134,7 @@ public class JournalCleanupCompactStressTest extends ActiveMQTestBase } // System.out.println("OnCompactStart leave"); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); errors.incrementAndGet(); } @@ -175,17 +152,13 @@ public class JournalCleanupCompactStressTest extends ActiveMQTestBase @Override @After - public void tearDown() throws Exception - { - try - { - if (journal.isStarted()) - { + public void tearDown() throws Exception { + try { + if (journal.isStarted()) { journal.stop(); } } - catch (Exception e) - { + catch (Exception e) { // don't care :-) } @@ -193,8 +166,7 @@ public class JournalCleanupCompactStressTest extends ActiveMQTestBase } @Test - public void testAppend() throws Exception - { + public void testAppend() throws Exception { running = true; SlowAppenderNoTX t1 = new SlowAppenderNoTX(); @@ -204,8 +176,7 @@ public class JournalCleanupCompactStressTest extends ActiveMQTestBase FastAppenderTx[] appenders = new FastAppenderTx[NTHREADS]; FastUpdateTx[] updaters = new FastUpdateTx[NTHREADS]; - for (int i = 0; i < NTHREADS; i++) - { + for (int i = 0; i < NTHREADS; i++) { appenders[i] = new FastAppenderTx(); updaters[i] = new FastUpdateTx(appenders[i].queue); } @@ -214,16 +185,14 @@ public class JournalCleanupCompactStressTest extends ActiveMQTestBase Thread.sleep(1000); - for (int i = 0; i < NTHREADS; i++) - { + for (int i = 0; i < NTHREADS; i++) { appenders[i].start(); updaters[i].start(); } long timeToEnd = System.currentTimeMillis() + getTotalTimeMilliseconds(); - while (System.currentTimeMillis() < timeToEnd) - { + while (System.currentTimeMillis() < timeToEnd) { System.out.println("Append = " + numberOfRecords + ", Update = " + numberOfUpdates + @@ -245,23 +214,19 @@ public class JournalCleanupCompactStressTest extends ActiveMQTestBase // Release Semaphore after setting running to false or the threads may never finish maxRecords.release(MAX_WRITES - maxRecords.availablePermits()); - for (Thread t : appenders) - { + for (Thread t : appenders) { t.join(); } - for (Thread t : updaters) - { + for (Thread t : updaters) { t.join(); } t1.join(); final CountDownLatch latchExecutorDone = new CountDownLatch(1); - testExecutor.execute(new Runnable() - { - public void run() - { + testExecutor.execute(new Runnable() { + public void run() { latchExecutorDone.countDown(); } }); @@ -277,8 +242,7 @@ public class JournalCleanupCompactStressTest extends ActiveMQTestBase Collection records = journal.getRecords().keySet(); System.out.println("Deleting everything!"); - for (Long delInfo : records) - { + for (Long delInfo : records) { journal.appendDeleteRecord(delInfo, false); } @@ -296,29 +260,23 @@ public class JournalCleanupCompactStressTest extends ActiveMQTestBase /** * @throws Exception */ - private void reloadJournal() throws Exception - { + private void reloadJournal() throws Exception { assertEquals(0, errors.get()); ArrayList committedRecords = new ArrayList(); ArrayList preparedTransactions = new ArrayList(); - journal.load(committedRecords, preparedTransactions, new TransactionFailureCallback() - { - public void failedTransaction(long transactionID, List records, List recordsToDelete) - { + journal.load(committedRecords, preparedTransactions, new TransactionFailureCallback() { + public void failedTransaction(long transactionID, List records, List recordsToDelete) { } }); long appends = 0, updates = 0; - for (RecordInfo record : committedRecords) - { - if (record.isUpdate) - { + for (RecordInfo record : committedRecords) { + if (record.isUpdate) { updates++; } - else - { + else { appends++; } } @@ -326,36 +284,30 @@ public class JournalCleanupCompactStressTest extends ActiveMQTestBase assertEquals(numberOfRecords.get() - numberOfDeletes.get(), appends); } - private byte[] generateRecord() - { + private byte[] generateRecord() { int size = RandomUtil.randomPositiveInt() % 10000; - if (size == 0) - { + if (size == 0) { size = 10000; } return RandomUtil.randomBytes(size); } - class FastAppenderTx extends Thread - { + class FastAppenderTx extends Thread { + LinkedBlockingDeque queue = new LinkedBlockingDeque(); OperationContextImpl ctx = new OperationContextImpl(executorFactory.getExecutor()); - public FastAppenderTx() - { + public FastAppenderTx() { super("FastAppenderTX"); } @Override - public void run() - { + public void run() { rwLock.readLock().lock(); - try - { - while (running) - { + try { + while (running) { final int txSize = RandomUtil.randomMax(100); long txID = JournalCleanupCompactStressTest.idGen.generateID(); @@ -364,34 +316,28 @@ public class JournalCleanupCompactStressTest extends ActiveMQTestBase final long[] ids = new long[txSize]; - for (int i = 0; i < txSize; i++) - { + for (int i = 0; i < txSize; i++) { ids[i] = JournalCleanupCompactStressTest.idGen.generateID(); } journal.appendAddRecordTransactional(rollbackTXID, ids[0], (byte) 0, generateRecord()); journal.appendRollbackRecord(rollbackTXID, true); - for (int i = 0; i < txSize; i++) - { + for (int i = 0; i < txSize; i++) { long id = ids[i]; journal.appendAddRecordTransactional(txID, id, (byte) 0, generateRecord()); maxRecords.acquire(); } journal.appendCommitRecord(txID, true, ctx); - ctx.executeOnCompletion(new IOCallback() - { + ctx.executeOnCompletion(new IOCallback() { - public void onError(final int errorCode, final String errorMessage) - { + public void onError(final int errorCode, final String errorMessage) { } - public void done() - { + public void done() { numberOfRecords.addAndGet(txSize); - for (Long id : ids) - { + for (Long id : ids) { queue.add(id); } } @@ -403,61 +349,51 @@ public class JournalCleanupCompactStressTest extends ActiveMQTestBase rwLock.readLock().lock(); - } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); running = false; errors.incrementAndGet(); } - finally - { + finally { rwLock.readLock().unlock(); } } } - class FastUpdateTx extends Thread - { + class FastUpdateTx extends Thread { + final LinkedBlockingDeque queue; OperationContextImpl ctx = new OperationContextImpl(executorFactory.getExecutor()); - public FastUpdateTx(final LinkedBlockingDeque queue) - { + public FastUpdateTx(final LinkedBlockingDeque queue) { super("FastUpdateTX"); this.queue = queue; } @Override - public void run() - { + public void run() { rwLock.readLock().lock(); - try - { + try { int txSize = RandomUtil.randomMax(100); int txCount = 0; long[] ids = new long[txSize]; long txID = JournalCleanupCompactStressTest.idGen.generateID(); - while (running) - { + while (running) { Long id = queue.poll(10, TimeUnit.SECONDS); - if (id != null) - { + if (id != null) { ids[txCount++] = id; journal.appendUpdateRecordTransactional(txID, id, (byte) 0, generateRecord()); } - if (txCount == txSize || id == null) - { - if (txCount > 0) - { + if (txCount == txSize || id == null) { + if (txCount > 0) { journal.appendCommitRecord(txID, true, ctx); ctx.executeOnCompletion(new DeleteTask(ids)); } @@ -475,64 +411,53 @@ public class JournalCleanupCompactStressTest extends ActiveMQTestBase } } - if (txCount > 0) - { + if (txCount > 0) { journal.appendCommitRecord(txID, true); } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); running = false; errors.incrementAndGet(); } - finally - { + finally { rwLock.readLock().unlock(); } } } - class DeleteTask implements IOCallback - { + class DeleteTask implements IOCallback { + final long[] ids; - DeleteTask(final long[] ids) - { + DeleteTask(final long[] ids) { this.ids = ids; } - public void done() - { + public void done() { rwLock.readLock().lock(); numberOfUpdates.addAndGet(ids.length); - try - { - for (long id : ids) - { - if (id != 0) - { + try { + for (long id : ids) { + if (id != 0) { journal.appendDeleteRecord(id, false); maxRecords.release(); numberOfDeletes.incrementAndGet(); } } } - catch (Exception e) - { + catch (Exception e) { System.err.println("Can't delete id"); e.printStackTrace(); running = false; errors.incrementAndGet(); } - finally - { + finally { rwLock.readLock().unlock(); } } - public void onError(final int errorCode, final String errorMessage) - { + public void onError(final int errorCode, final String errorMessage) { } } @@ -541,26 +466,20 @@ public class JournalCleanupCompactStressTest extends ActiveMQTestBase * Adds stuff to the journal, but it will take a long time to remove them. * This will cause cleanup and compacting to happen more often */ - class SlowAppenderNoTX extends Thread - { + class SlowAppenderNoTX extends Thread { - public SlowAppenderNoTX() - { + public SlowAppenderNoTX() { super("SlowAppender"); } @Override - public void run() - { + public void run() { rwLock.readLock().lock(); - try - { - while (running) - { + try { + while (running) { long[] ids = new long[5]; // Append - for (int i = 0; running & i < ids.length; i++) - { + for (int i = 0; running & i < ids.length; i++) { System.out.println("append slow"); ids[i] = JournalCleanupCompactStressTest.idGen.generateID(); maxRecords.acquire(); @@ -574,8 +493,7 @@ public class JournalCleanupCompactStressTest extends ActiveMQTestBase rwLock.readLock().lock(); } // Delete - for (int i = 0; running & i < ids.length; i++) - { + for (int i = 0; running & i < ids.length; i++) { System.out.println("Deleting"); maxRecords.release(); journal.appendDeleteRecord(ids[i], false); @@ -583,13 +501,11 @@ public class JournalCleanupCompactStressTest extends ActiveMQTestBase } } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); System.exit(-1); } - finally - { + finally { rwLock.readLock().unlock(); } } diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/JournalRestartStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/JournalRestartStressTest.java index 6ca44864e0..c718719026 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/JournalRestartStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/JournalRestartStressTest.java @@ -35,8 +35,7 @@ import org.junit.Test; * and having multiple restarts, * To make sure the journal would survive at multiple restarts of the server */ -public class JournalRestartStressTest extends ActiveMQTestBase -{ +public class JournalRestartStressTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -49,8 +48,7 @@ public class JournalRestartStressTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testLoad() throws Throwable - { + public void testLoad() throws Throwable { ActiveMQServer server2 = createServer(true, false); server2.getConfiguration().setJournalFileSize(10 * 1024 * 1024); @@ -58,35 +56,28 @@ public class JournalRestartStressTest extends ActiveMQTestBase server2.getConfiguration().setJournalCompactMinFiles(3); server2.getConfiguration().setJournalCompactPercentage(50); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { server2.start(); - ServerLocator locator = createInVMNonHALocator() - .setMinLargeMessageSize(1024 * 1024) - .setBlockOnDurableSend(false); + ServerLocator locator = createInVMNonHALocator().setMinLargeMessageSize(1024 * 1024).setBlockOnDurableSend(false); ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(true, true); - try - { + try { session.createQueue("slow-queue", "slow-queue"); } - catch (Exception ignored) - { + catch (Exception ignored) { } session.start(); ClientConsumer consumer = session.createConsumer("slow-queue"); - while (true) - { + while (true) { System.out.println("Received message from previous"); ClientMessage msg = consumer.receiveImmediate(); - if (msg == null) - { + if (msg == null) { break; } msg.acknowledge(); @@ -110,8 +101,7 @@ public class JournalRestartStressTest extends ActiveMQTestBase * @throws InterruptedException * @throws Throwable */ - private void produceMessages(final ClientSessionFactory sf, final int NMSGS) throws Throwable - { + private void produceMessages(final ClientSessionFactory sf, final int NMSGS) throws Throwable { final int TIMEOUT = 5000; @@ -121,12 +111,10 @@ public class JournalRestartStressTest extends ActiveMQTestBase ClientProducer prod2 = sessionSend.createProducer("slow-queue"); - try - { + try { sessionSend.createQueue("Queue", "Queue", true); } - catch (Exception ignored) - { + catch (Exception ignored) { } final ClientSession sessionReceive = sf.createSession(true, true); @@ -134,35 +122,28 @@ public class JournalRestartStressTest extends ActiveMQTestBase final ArrayList errors = new ArrayList(); - Thread tReceive = new Thread() - { + Thread tReceive = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { ClientConsumer consumer = sessionReceive.createConsumer("Queue"); - for (int i = 0; i < NMSGS; i++) - { - if (i % 500 == 0) - { + for (int i = 0; i < NMSGS; i++) { + if (i % 500 == 0) { double percent = (double) i / (double) NMSGS; System.out.println("msgs " + i + " of " + NMSGS + ", " + (int) (percent * 100) + "%"); Thread.sleep(100); } ClientMessage msg = consumer.receive(TIMEOUT); - if (msg == null) - { + if (msg == null) { errors.add(new Exception("Didn't receive msgs")); break; } msg.acknowledge(); } } - catch (Exception e) - { + catch (Exception e) { errors.add(e); } } @@ -174,14 +155,12 @@ public class JournalRestartStressTest extends ActiveMQTestBase Random random = new Random(); - for (int i = 0; i < NMSGS; i++) - { + for (int i = 0; i < NMSGS; i++) { ClientMessage msg = sessionSend.createMessage(true); int size = RandomUtil.randomPositiveInt() % 10024; - if (size == 0) - { + if (size == 0) { size = 10 * 1024; } @@ -193,8 +172,7 @@ public class JournalRestartStressTest extends ActiveMQTestBase prod.send(msg); - if (i % 5000 == 0) - { + if (i % 5000 == 0) { prod2.send(msg); System.out.println("Sending slow message"); } @@ -206,8 +184,7 @@ public class JournalRestartStressTest extends ActiveMQTestBase sessionSend.close(); sf.close(); - for (Throwable e : errors) - { + for (Throwable e : errors) { throw e; } } diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/LargeJournalStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/LargeJournalStressTest.java index 46d309f996..ac0003880c 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/LargeJournalStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/LargeJournalStressTest.java @@ -35,8 +35,7 @@ import org.junit.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; -public class LargeJournalStressTest extends ActiveMQTestBase -{ +public class LargeJournalStressTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -63,19 +62,16 @@ public class LargeJournalStressTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testMultiProducerAndCompactAIO() throws Throwable - { + public void testMultiProducerAndCompactAIO() throws Throwable { internalTestMultiProducer(JournalType.ASYNCIO); } @Test - public void testMultiProducerAndCompactNIO() throws Throwable - { + public void testMultiProducerAndCompactNIO() throws Throwable { internalTestMultiProducer(JournalType.NIO); } - public void internalTestMultiProducer(final JournalType journalType) throws Throwable - { + public void internalTestMultiProducer(final JournalType journalType) throws Throwable { setupServer(journalType); @@ -86,38 +82,32 @@ public class LargeJournalStressTest extends ActiveMQTestBase final CountDownLatch latchReady = new CountDownLatch(2); final CountDownLatch latchStart = new CountDownLatch(1); - class FastProducer extends Thread - { + class FastProducer extends Thread { + Throwable e; - FastProducer() - { + FastProducer() { super("Fast-Thread"); } @Override - public void run() - { + public void run() { ClientSession session = null; ClientSession sessionSlow = null; latchReady.countDown(); - try - { + try { ActiveMQTestBase.waitForLatch(latchStart); session = sf.createSession(true, true); sessionSlow = sf.createSession(false, false); ClientProducer prod = session.createProducer(LargeJournalStressTest.AD2); ClientProducer slowProd = sessionSlow.createProducer(LargeJournalStressTest.AD1); - for (int i = 0; i < NUMBER_OF_FAST_MESSAGES; i++) - { - if (i % SLOW_INTERVAL == 0) - { + for (int i = 0; i < NUMBER_OF_FAST_MESSAGES; i++) { + if (i % SLOW_INTERVAL == 0) { System.out.println("Sending slow message, msgs = " + i + " slowMessages = " + numberOfMessages.get()); - if (numberOfMessages.incrementAndGet() % 5 == 0) - { + if (numberOfMessages.incrementAndGet() % 5 == 0) { sessionSlow.commit(); } slowProd.send(session.createMessage(true)); @@ -127,72 +117,58 @@ public class LargeJournalStressTest extends ActiveMQTestBase } sessionSlow.commit(); } - catch (Throwable e) - { + catch (Throwable e) { this.e = e; } - finally - { - try - { + finally { + try { session.close(); } - catch (Throwable e) - { + catch (Throwable e) { this.e = e; } - try - { + try { sessionSlow.close(); } - catch (Throwable e) - { + catch (Throwable e) { this.e = e; } } } } - class FastConsumer extends Thread - { + class FastConsumer extends Thread { + Throwable e; - FastConsumer() - { + FastConsumer() { super("Fast-Consumer"); } @Override - public void run() - { + public void run() { ClientSession session = null; latchReady.countDown(); - try - { + try { ActiveMQTestBase.waitForLatch(latchStart); session = sf.createSession(true, true); session.start(); ClientConsumer cons = session.createConsumer(LargeJournalStressTest.Q2); - for (int i = 0; i < NUMBER_OF_FAST_MESSAGES; i++) - { + for (int i = 0; i < NUMBER_OF_FAST_MESSAGES; i++) { ClientMessage msg = cons.receive(60 * 1000); msg.acknowledge(); } Assert.assertNull(cons.receiveImmediate()); } - catch (Throwable e) - { + catch (Throwable e) { this.e = e; } - finally - { - try - { + finally { + try { session.close(); } - catch (Throwable e) - { + catch (Throwable e) { this.e = e; } } @@ -210,15 +186,13 @@ public class LargeJournalStressTest extends ActiveMQTestBase p1.join(); - if (p1.e != null) - { + if (p1.e != null) { throw p1.e; } f1.join(); - if (f1.e != null) - { + if (f1.e != null) { throw f1.e; } @@ -234,8 +208,7 @@ public class LargeJournalStressTest extends ActiveMQTestBase sess.start(); - for (int i = 0; i < numberOfMessages.intValue(); i++) - { + for (int i = 0; i < numberOfMessages.intValue(); i++) { ClientMessage msg = cons.receive(10000); Assert.assertNotNull(msg); msg.acknowledge(); @@ -255,29 +228,19 @@ public class LargeJournalStressTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); clearDataRecreateServerDirs(); - locator = createInVMNonHALocator() - .setBlockOnAcknowledge(false) - .setBlockOnNonDurableSend(false) - .setBlockOnDurableSend(false); + locator = createInVMNonHALocator().setBlockOnAcknowledge(false).setBlockOnNonDurableSend(false).setBlockOnDurableSend(false); } /** * @throws Exception */ - private void setupServer(final JournalType journalType) throws Exception - { - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false) - .setJournalFileSize(ActiveMQDefaultConfiguration.getDefaultJournalFileSize()) - .setJournalType(journalType) - .setJournalCompactMinFiles(0) - .setJournalCompactPercentage(50); + private void setupServer(final JournalType journalType) throws Exception { + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false).setJournalFileSize(ActiveMQDefaultConfiguration.getDefaultJournalFileSize()).setJournalType(journalType).setJournalCompactMinFiles(0).setJournalCompactPercentage(50); server = createServer(true, config); @@ -287,20 +250,16 @@ public class LargeJournalStressTest extends ActiveMQTestBase ClientSession sess = sf.createSession(); - try - { + try { sess.createQueue(LargeJournalStressTest.AD1, LargeJournalStressTest.Q1, true); } - catch (Exception ignored) - { + catch (Exception ignored) { } - try - { + try { sess.createQueue(LargeJournalStressTest.AD2, LargeJournalStressTest.Q2, true); } - catch (Exception ignored) - { + catch (Exception ignored) { } sess.close(); @@ -310,17 +269,14 @@ public class LargeJournalStressTest extends ActiveMQTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { locator.close(); - if (sf != null) - { + if (sf != null) { sf.close(); } - if (server != null) - { + if (server != null) { server.stop(); } diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/MixupCompactorTestBase.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/MixupCompactorTestBase.java index f7edebe824..42750aef05 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/MixupCompactorTestBase.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/MixupCompactorTestBase.java @@ -33,8 +33,7 @@ import org.junit.Test; /** * This class will control mix up compactor between each operation of a test */ -public abstract class MixupCompactorTestBase extends JournalImplTestBase -{ +public abstract class MixupCompactorTestBase extends JournalImplTestBase { // Constants ----------------------------------------------------- @@ -63,8 +62,7 @@ public abstract class MixupCompactorTestBase extends JournalImplTestBase // Public -------------------------------------------------------- @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); tCompact = null; @@ -79,22 +77,18 @@ public abstract class MixupCompactorTestBase extends JournalImplTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { File testDir = new File(getTestDir()); - File[] files = testDir.listFiles(new FilenameFilter() - { + File[] files = testDir.listFiles(new FilenameFilter() { - public boolean accept(final File dir, final String name) - { + public boolean accept(final File dir, final String name) { return name.startsWith(filePrefix) && name.endsWith(fileExtension); } }); - for (File file : files) - { + for (File file : files) { Assert.assertEquals("File " + file + " doesn't have the expected number of bytes", fileSize, file.length()); } @@ -102,21 +96,16 @@ public abstract class MixupCompactorTestBase extends JournalImplTestBase } @Override - public void createJournal() throws Exception - { - journal = new JournalImpl(fileSize, minFiles, 0, 0, fileFactory, filePrefix, fileExtension, maxAIO) - { + public void createJournal() throws Exception { + journal = new JournalImpl(fileSize, minFiles, 0, 0, fileFactory, filePrefix, fileExtension, maxAIO) { @Override - public void onCompactDone() - { + public void onCompactDone() { startedCompactingLatch.countDown(); - try - { + try { releaseCompactingLatch.await(); } - catch (InterruptedException e) - { + catch (InterruptedException e) { e.printStackTrace(); } } @@ -126,9 +115,7 @@ public abstract class MixupCompactorTestBase extends JournalImplTestBase } @Test - public void testMixOperations() throws Exception - { - + public void testMixOperations() throws Exception { currentOperation = 0; internalTest(); @@ -136,22 +123,17 @@ public abstract class MixupCompactorTestBase extends JournalImplTestBase System.out.println("Using MAX_OPERATIONS = " + MAX_OPERATIONS); - for (int startAt = 0; startAt < MAX_OPERATIONS; startAt++) - { - for (int joinAt = startAt; joinAt < MAX_OPERATIONS; joinAt++) - { - for (int secondAt = joinAt; secondAt < MAX_OPERATIONS; secondAt++) - { + for (int startAt = 0; startAt < MAX_OPERATIONS; startAt++) { + for (int joinAt = startAt; joinAt < MAX_OPERATIONS; joinAt++) { + for (int secondAt = joinAt; secondAt < MAX_OPERATIONS; secondAt++) { System.out.println("start=" + startAt + ", join=" + joinAt + ", second=" + secondAt); - try - { + try { tearDown(); setUp(); testMix(startAt, joinAt, secondAt); } - catch (Throwable e) - { + catch (Throwable e) { throw new Exception("Error at compact=" + startCompactAt + ", joinCompactAt=" + joinCompactAt + @@ -163,8 +145,7 @@ public abstract class MixupCompactorTestBase extends JournalImplTestBase } } - protected int testMix(final int startAt, final int joinAt, final int secondAt) throws Exception - { + protected int testMix(final int startAt, final int joinAt, final int secondAt) throws Exception { startCompactAt = startAt; joinCompactAt = joinAt; secondCompactAt = secondAt; @@ -177,8 +158,7 @@ public abstract class MixupCompactorTestBase extends JournalImplTestBase } @Override - protected void beforeJournalOperation() throws Exception - { + protected void beforeJournalOperation() throws Exception { checkJournalOperation(); } @@ -186,18 +166,14 @@ public abstract class MixupCompactorTestBase extends JournalImplTestBase * @throws InterruptedException * @throws Exception */ - protected void checkJournalOperation() throws Exception - { - if (startCompactAt == currentOperation) - { + protected void checkJournalOperation() throws Exception { + if (startCompactAt == currentOperation) { threadCompact(); } - if (joinCompactAt == currentOperation) - { + if (joinCompactAt == currentOperation) { joinCompact(); } - if (secondCompactAt == currentOperation) - { + if (secondCompactAt == currentOperation) { journal.testCompact(); } @@ -206,8 +182,7 @@ public abstract class MixupCompactorTestBase extends JournalImplTestBase protected abstract void internalTest() throws Exception; - private void joinCompact() throws InterruptedException - { + private void joinCompact() throws InterruptedException { releaseCompactingLatch.countDown(); tCompact.join(); @@ -215,19 +190,14 @@ public abstract class MixupCompactorTestBase extends JournalImplTestBase tCompact = null; } - private void threadCompact() throws InterruptedException - { - tCompact = new Thread() - { + private void threadCompact() throws InterruptedException { + tCompact = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { journal.testCompact(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -239,8 +209,7 @@ public abstract class MixupCompactorTestBase extends JournalImplTestBase } @Override - protected SequentialFileFactory getFileFactory() throws Exception - { + protected SequentialFileFactory getFileFactory() throws Exception { return new NIOSequentialFileFactory(getTestDirfile(), 1); } } diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/MultiThreadConsumerStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/MultiThreadConsumerStressTest.java index c7f8e31a39..ab786b7fcf 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/MultiThreadConsumerStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/MultiThreadConsumerStressTest.java @@ -40,8 +40,7 @@ import java.util.concurrent.CountDownLatch; *
    * This test validates consuming / sending messages while compacting is working */ -public class MultiThreadConsumerStressTest extends ActiveMQTestBase -{ +public class MultiThreadConsumerStressTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -57,15 +56,13 @@ public class MultiThreadConsumerStressTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); setupServer(JournalType.NIO); } @Test - public void testProduceAndConsume() throws Throwable - { + public void testProduceAndConsume() throws Throwable { int numberOfConsumers = 5; // this test assumes numberOfConsumers == numberOfProducers int numberOfProducers = numberOfConsumers; @@ -79,8 +76,7 @@ public class MultiThreadConsumerStressTest extends ActiveMQTestBase ClientProducer producer = session.createProducer("compact"); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { producer.send(session.createMessage(true)); } @@ -96,8 +92,7 @@ public class MultiThreadConsumerStressTest extends ActiveMQTestBase ArrayList threads = new ArrayList(); ProducerThread[] prod = new ProducerThread[numberOfProducers]; - for (int i = 0; i < numberOfProducers; i++) - { + for (int i = 0; i < numberOfProducers; i++) { prod[i] = new ProducerThread(i, latchReady, latchStart, produceMessage, commitIntervalProduce); prod[i].start(); threads.add(prod[i]); @@ -105,8 +100,7 @@ public class MultiThreadConsumerStressTest extends ActiveMQTestBase ConsumerThread[] cons = new ConsumerThread[numberOfConsumers]; - for (int i = 0; i < numberOfConsumers; i++) - { + for (int i = 0; i < numberOfConsumers; i++) { cons[i] = new ConsumerThread(i, latchReady, latchStart, consumeMessage, commitIntervalConsume); cons[i].start(); threads.add(cons[i]); @@ -115,11 +109,9 @@ public class MultiThreadConsumerStressTest extends ActiveMQTestBase ActiveMQTestBase.waitForLatch(latchReady); latchStart.countDown(); - for (BaseThread t : threads) - { + for (BaseThread t : threads) { t.join(); - if (t.e != null) - { + if (t.e != null) { throw t.e; } } @@ -134,13 +126,11 @@ public class MultiThreadConsumerStressTest extends ActiveMQTestBase sess.start(); - for (int i = 0; i < numberOfMessagesExpected; i++) - { + for (int i = 0; i < numberOfMessagesExpected; i++) { ClientMessage msg = consumer.receive(5000); Assert.assertNotNull(msg); - if (i % 1000 == 0) - { + if (i % 1000 == 0) { System.out.println("Received #" + i + " on thread before end"); } msg.acknowledge(); @@ -152,34 +142,23 @@ public class MultiThreadConsumerStressTest extends ActiveMQTestBase } - private void setupServer(final JournalType journalType) throws Exception - { - Configuration config = createDefaultNettyConfig() - .setJournalType(journalType) - .setJournalFileSize(ActiveMQDefaultConfiguration.getDefaultJournalFileSize()) - .setJournalMinFiles(ActiveMQDefaultConfiguration.getDefaultJournalMinFiles()) - .setJournalCompactMinFiles(2) - .setJournalCompactPercentage(50); + private void setupServer(final JournalType journalType) throws Exception { + Configuration config = createDefaultNettyConfig().setJournalType(journalType).setJournalFileSize(ActiveMQDefaultConfiguration.getDefaultJournalFileSize()).setJournalMinFiles(ActiveMQDefaultConfiguration.getDefaultJournalMinFiles()).setJournalCompactMinFiles(2).setJournalCompactPercentage(50); server = createServer(true, config); server.start(); - ServerLocator locator = createNettyNonHALocator() - .setBlockOnDurableSend(false) - .setBlockOnNonDurableSend(false) - .setBlockOnAcknowledge(false); + ServerLocator locator = createNettyNonHALocator().setBlockOnDurableSend(false).setBlockOnNonDurableSend(false).setBlockOnAcknowledge(false); sf = createSessionFactory(locator); ClientSession sess = sf.createSession(); - try - { + try { sess.createQueue(ADDRESS, QUEUE, true); } - catch (Exception ignored) - { + catch (Exception ignored) { } sess.close(); @@ -194,8 +173,8 @@ public class MultiThreadConsumerStressTest extends ActiveMQTestBase // Public -------------------------------------------------------- - class BaseThread extends Thread - { + class BaseThread extends Thread { + Throwable e; final CountDownLatch latchReady; @@ -210,8 +189,7 @@ public class MultiThreadConsumerStressTest extends ActiveMQTestBase final CountDownLatch latchReady, final CountDownLatch latchStart, final int numberOfMessages, - final int commitInterval) - { + final int commitInterval) { super(name); this.latchReady = latchReady; this.latchStart = latchStart; @@ -221,35 +199,29 @@ public class MultiThreadConsumerStressTest extends ActiveMQTestBase } - class ProducerThread extends BaseThread - { + class ProducerThread extends BaseThread { + ProducerThread(final int id, final CountDownLatch latchReady, final CountDownLatch latchStart, final int numberOfMessages, - final int commitInterval) - { + final int commitInterval) { super("ClientProducer:" + id, latchReady, latchStart, numberOfMessages, commitInterval); } @Override - public void run() - { + public void run() { ClientSession session = null; latchReady.countDown(); - try - { + try { ActiveMQTestBase.waitForLatch(latchStart); session = sf.createSession(false, false); ClientProducer prod = session.createProducer(ADDRESS); - for (int i = 0; i < numberOfMessages; i++) - { - if (i % commitInterval == 0) - { + for (int i = 0; i < numberOfMessages; i++) { + if (i % commitInterval == 0) { session.commit(); } - if (i % 1000 == 0) - { + if (i % 1000 == 0) { // System.out.println(Thread.currentThread().getName() + "::received #" + i); } ClientMessage msg = session.createMessage(true); @@ -263,57 +235,47 @@ public class MultiThreadConsumerStressTest extends ActiveMQTestBase numberOfMessages + " messages"); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); this.e = e; } - finally - { - try - { + finally { + try { session.close(); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); } } } } - class ConsumerThread extends BaseThread - { + class ConsumerThread extends BaseThread { + ConsumerThread(final int id, final CountDownLatch latchReady, final CountDownLatch latchStart, final int numberOfMessages, - final int commitInterval) - { + final int commitInterval) { super("ClientConsumer:" + id, latchReady, latchStart, numberOfMessages, commitInterval); } @Override - public void run() - { + public void run() { ClientSession session = null; latchReady.countDown(); - try - { + try { ActiveMQTestBase.waitForLatch(latchStart); session = sf.createSession(false, false); session.start(); ClientConsumer cons = session.createConsumer(QUEUE); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = cons.receive(60 * 1000); msg.acknowledge(); - if (i % commitInterval == 0) - { + if (i % commitInterval == 0) { session.commit(); } - if (i % 1000 == 0) - { + if (i % 1000 == 0) { // System.out.println(Thread.currentThread().getName() + "::sent #" + i); } } @@ -325,18 +287,14 @@ public class MultiThreadConsumerStressTest extends ActiveMQTestBase session.commit(); } - catch (Throwable e) - { + catch (Throwable e) { this.e = e; } - finally - { - try - { + finally { + try { session.close(); } - catch (Throwable e) - { + catch (Throwable e) { this.e = e; } } diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/NIOMultiThreadCompactorStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/NIOMultiThreadCompactorStressTest.java index 4ad8f4ee1a..205022c52c 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/NIOMultiThreadCompactorStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/NIOMultiThreadCompactorStressTest.java @@ -45,8 +45,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase -{ +public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -62,28 +61,22 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase private ServerLocator locator; - protected int getNumberOfIterations() - { + protected int getNumberOfIterations() { return 3; } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(false) - .setBlockOnAcknowledge(false); + locator = createInVMNonHALocator().setBlockOnNonDurableSend(false).setBlockOnAcknowledge(false); } @Test - public void testMultiThreadCompact() throws Throwable - { + public void testMultiThreadCompact() throws Throwable { setupServer(getJournalType()); - for (int i = 0; i < getNumberOfIterations(); i++) - { + for (int i = 0; i < getNumberOfIterations(); i++) { System.out.println("######################################"); System.out.println("test # " + i); @@ -91,14 +84,7 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase stopServer(); NIOSequentialFileFactory factory = new NIOSequentialFileFactory(new File(getJournalDir()), 1); - JournalImpl journal = new JournalImpl(ActiveMQDefaultConfiguration.getDefaultJournalFileSize(), - 2, - 0, - 0, - factory, - "activemq-data", - "amq", - 100); + JournalImpl journal = new JournalImpl(ActiveMQDefaultConfiguration.getDefaultJournalFileSize(), 2, 0, 0, factory, "activemq-data", "amq", 100); List committedRecords = new ArrayList(); List preparedTransactions = new ArrayList(); @@ -111,16 +97,14 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase System.out.println("DataFiles = " + journal.getDataFilesCount()); - if (i % 2 == 0 && i > 0) - { + if (i % 2 == 0 && i > 0) { System.out.println("DataFiles = " + journal.getDataFilesCount()); journal.forceMoveNextFile(); journal.debugWait(); journal.checkReclaimStatus(); - if (journal.getDataFilesCount() != 0) - { + if (journal.getDataFilesCount() != 0) { System.out.println("DebugJournal:" + journal.debug()); } Assert.assertEquals(0, journal.getDataFilesCount()); @@ -137,8 +121,7 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase /** * @return */ - protected JournalType getJournalType() - { + protected JournalType getJournalType() { return JournalType.NIO; } @@ -146,8 +129,7 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase * @param xid * @throws ActiveMQException */ - private void addEmptyTransaction(final Xid xid) throws Exception - { + private void addEmptyTransaction(final Xid xid) throws Exception { ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(true, false, false); session.start(xid, XAResource.TMNOFLAGS); @@ -157,8 +139,7 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase sf.close(); } - private void checkEmptyXID(final Xid xid) throws Exception - { + private void checkEmptyXID(final Xid xid) throws Exception { ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(true, false, false); @@ -172,8 +153,7 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase sf.close(); } - public void internalTestProduceAndConsume() throws Throwable - { + public void internalTestProduceAndConsume() throws Throwable { addBogusData(100, "LAZY-QUEUE"); @@ -204,28 +184,16 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase ArrayList threads = new ArrayList(); ProducerThread[] prod = new ProducerThread[numberOfProducers]; - for (int i = 0; i < numberOfProducers; i++) - { - prod[i] = new ProducerThread(i, - latchReady, - latchStart, - transactionalOnConsume, - produceMessage, - commitIntervalProduce); + for (int i = 0; i < numberOfProducers; i++) { + prod[i] = new ProducerThread(i, latchReady, latchStart, transactionalOnConsume, produceMessage, commitIntervalProduce); prod[i].start(); threads.add(prod[i]); } ConsumerThread[] cons = new ConsumerThread[numberOfConsumers]; - for (int i = 0; i < numberOfConsumers; i++) - { - cons[i] = new ConsumerThread(i, - latchReady, - latchStart, - transactionalOnProduce, - consumeMessage, - commitIntervalConsume); + for (int i = 0; i < numberOfConsumers; i++) { + cons[i] = new ConsumerThread(i, latchReady, latchStart, transactionalOnProduce, consumeMessage, commitIntervalConsume); cons[i].start(); threads.add(cons[i]); } @@ -233,11 +201,9 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase ActiveMQTestBase.waitForLatch(latchReady); latchStart.countDown(); - for (BaseThread t : threads) - { + for (BaseThread t : threads) { t.join(); - if (t.e != null) - { + if (t.e != null) { throw t.e; } } @@ -264,21 +230,18 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase * @param queue * @throws ActiveMQException */ - private void drainQueue(final int numberOfMessagesExpected, final SimpleString queue) throws ActiveMQException - { + private void drainQueue(final int numberOfMessagesExpected, final SimpleString queue) throws ActiveMQException { ClientSession sess = sf.createSession(true, true); ClientConsumer consumer = sess.createConsumer(queue); sess.start(); - for (int i = 0; i < numberOfMessagesExpected; i++) - { + for (int i = 0; i < numberOfMessagesExpected; i++) { ClientMessage msg = consumer.receive(5000); Assert.assertNotNull(msg); - if (i % 100 == 0) - { + if (i % 100 == 0) { // System.out.println("Received #" + i + " on thread after start"); } msg.acknowledge(); @@ -292,20 +255,16 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase /** * @throws ActiveMQException */ - private void addBogusData(final int nmessages, final String queue) throws ActiveMQException - { + private void addBogusData(final int nmessages, final String queue) throws ActiveMQException { ClientSession session = sf.createSession(false, false); - try - { + try { session.createQueue(queue, queue, true); } - catch (Exception ignored) - { + catch (Exception ignored) { } ClientProducer prod = session.createProducer(queue); - for (int i = 0; i < nmessages; i++) - { + for (int i = 0; i < nmessages; i++) { ClientMessage msg = session.createMessage(true); msg.getBodyBuffer().writeBytes(new byte[1024]); prod.send(msg); @@ -320,39 +279,25 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase session.close(); } - protected void stopServer() throws Exception - { - try - { - if (server != null && server.isStarted()) - { + protected void stopServer() throws Exception { + try { + if (server != null && server.isStarted()) { server.stop(); } } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(System.out); // System.out => junit reports } sf = null; } - private void setupServer(JournalType journalType) throws Exception - { - if (!LibaioContext.isLoaded()) - { + private void setupServer(JournalType journalType) throws Exception { + if (!LibaioContext.isLoaded()) { journalType = JournalType.NIO; } - if (server == null) - { - Configuration config = createDefaultNettyConfig() - .setJournalFileSize(ActiveMQDefaultConfiguration.getDefaultJournalFileSize()) - .setJournalType(journalType) - .setJMXManagementEnabled(false) - .setJournalFileSize(ActiveMQDefaultConfiguration.getDefaultJournalFileSize()) - .setJournalMinFiles(ActiveMQDefaultConfiguration.getDefaultJournalMinFiles()) - .setJournalCompactMinFiles(ActiveMQDefaultConfiguration.getDefaultJournalCompactMinFiles()) - .setJournalCompactPercentage(ActiveMQDefaultConfiguration.getDefaultJournalCompactPercentage()) + if (server == null) { + Configuration config = createDefaultNettyConfig().setJournalFileSize(ActiveMQDefaultConfiguration.getDefaultJournalFileSize()).setJournalType(journalType).setJMXManagementEnabled(false).setJournalFileSize(ActiveMQDefaultConfiguration.getDefaultJournalFileSize()).setJournalMinFiles(ActiveMQDefaultConfiguration.getDefaultJournalMinFiles()).setJournalCompactMinFiles(ActiveMQDefaultConfiguration.getDefaultJournalCompactMinFiles()).setJournalCompactPercentage(ActiveMQDefaultConfiguration.getDefaultJournalCompactPercentage()) // This test is supposed to not sync.. All the ACKs are async, and it was supposed to not sync .setJournalSyncNonTransactional(false); @@ -364,20 +309,16 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase server.start(); - ServerLocator locator = createNettyNonHALocator() - .setBlockOnDurableSend(false) - .setBlockOnAcknowledge(false); + ServerLocator locator = createNettyNonHALocator().setBlockOnDurableSend(false).setBlockOnAcknowledge(false); sf = createSessionFactory(locator); ClientSession sess = sf.createSession(); - try - { + try { sess.createQueue(ADDRESS, QUEUE, true); } - catch (Exception ignored) - { + catch (Exception ignored) { } sess.close(); @@ -389,8 +330,8 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase // Public -------------------------------------------------------- - class BaseThread extends Thread - { + class BaseThread extends Thread { + Throwable e; final CountDownLatch latchReady; @@ -408,8 +349,7 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase final CountDownLatch latchStart, final boolean transactional, final int numberOfMessages, - final int commitInterval) - { + final int commitInterval) { super(name); this.transactional = transactional; this.latchReady = latchReady; @@ -420,39 +360,32 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase } - class ProducerThread extends BaseThread - { + class ProducerThread extends BaseThread { + ProducerThread(final int id, final CountDownLatch latchReady, final CountDownLatch latchStart, final boolean transactional, final int numberOfMessages, - final int commitInterval) - { + final int commitInterval) { super("ClientProducer:" + id, latchReady, latchStart, transactional, numberOfMessages, commitInterval); } @Override - public void run() - { + public void run() { ClientSession session = null; latchReady.countDown(); - try - { + try { ActiveMQTestBase.waitForLatch(latchStart); session = sf.createSession(!transactional, !transactional); ClientProducer prod = session.createProducer(ADDRESS); - for (int i = 0; i < numberOfMessages; i++) - { - if (transactional) - { - if (i % commitInterval == 0) - { + for (int i = 0; i < numberOfMessages; i++) { + if (transactional) { + if (i % commitInterval == 0) { session.commit(); } } - if (i % 100 == 0) - { + if (i % 100 == 0) { // System.out.println(Thread.currentThread().getName() + "::sent #" + i); } ClientMessage msg = session.createMessage(true); @@ -460,8 +393,7 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase prod.send(msg); } - if (transactional) - { + if (transactional) { session.commit(); } @@ -470,58 +402,48 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase numberOfMessages + " messages"); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); this.e = e; } - finally - { - try - { + finally { + try { session.close(); } - catch (Throwable e) - { + catch (Throwable e) { this.e = e; } } } } - class ConsumerThread extends BaseThread - { + class ConsumerThread extends BaseThread { + ConsumerThread(final int id, final CountDownLatch latchReady, final CountDownLatch latchStart, final boolean transactional, final int numberOfMessages, - final int commitInterval) - { + final int commitInterval) { super("ClientConsumer:" + id, latchReady, latchStart, transactional, numberOfMessages, commitInterval); } @Override - public void run() - { + public void run() { ClientSession session = null; latchReady.countDown(); - try - { + try { ActiveMQTestBase.waitForLatch(latchStart); session = sf.createSession(!transactional, !transactional); session.start(); ClientConsumer cons = session.createConsumer(QUEUE); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = cons.receive(60 * 1000); msg.acknowledge(); - if (i % commitInterval == 0) - { + if (i % commitInterval == 0) { session.commit(); } - if (i % 100 == 0) - { + if (i % 100 == 0) { // System.out.println(Thread.currentThread().getName() + "::received #" + i); } } @@ -533,18 +455,14 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase session.commit(); } - catch (Throwable e) - { + catch (Throwable e) { this.e = e; } - finally - { - try - { + finally { + try { session.close(); } - catch (Throwable e) - { + catch (Throwable e) { this.e = e; } } diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/XmlImportExportStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/XmlImportExportStressTest.java index 0a2b569cdb..9c733ac2b9 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/XmlImportExportStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/XmlImportExportStressTest.java @@ -33,13 +33,12 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Test; -public class XmlImportExportStressTest extends ActiveMQTestBase -{ +public class XmlImportExportStressTest extends ActiveMQTestBase { + public static final int CONSUMER_TIMEOUT = 5000; @Test - public void testHighVolume() throws Exception - { + public void testHighVolume() throws Exception { final String FILE_NAME = getTestDir() + "/export.out"; final String QUEUE_NAME = "A1"; @@ -57,19 +56,16 @@ public class XmlImportExportStressTest extends ActiveMQTestBase final int SIZE = 10240; final int COUNT = 20000; byte[] bodyTst = new byte[SIZE]; - for (int i = 0; i < SIZE; i++) - { + for (int i = 0; i < SIZE; i++) { bodyTst[i] = (byte) (i + 1); } msg.getBodyBuffer().writeBytes(bodyTst); assertEquals(bodyTst.length, msg.getBodySize()); - for (int i = 0; i < COUNT; i++) - { + for (int i = 0; i < COUNT; i++) { producer.send(msg); - if (i % 500 == 0) - { + if (i % 500 == 0) { System.out.println("Sent " + i); session.commit(); } @@ -109,14 +105,12 @@ public class XmlImportExportStressTest extends ActiveMQTestBase ClientConsumer consumer = session.createConsumer(QUEUE_NAME); session.start(); - for (int i = 0; i < COUNT; i++) - { + for (int i = 0; i < COUNT; i++) { msg = consumer.receive(CONSUMER_TIMEOUT); assertNotNull(msg); msg.acknowledge(); - if (i % 500 == 0) - { + if (i % 500 == 0) { System.out.println("Received " + i); session.commit(); } diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/paging/MultipleConsumersPageStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/paging/MultipleConsumersPageStressTest.java index 02f9cc795d..befef1c714 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/paging/MultipleConsumersPageStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/paging/MultipleConsumersPageStressTest.java @@ -37,8 +37,7 @@ import java.util.HashMap; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; -public class MultipleConsumersPageStressTest extends ActiveMQTestBase -{ +public class MultipleConsumersPageStressTest extends ActiveMQTestBase { private final UnitTestLogger log = UnitTestLogger.LOGGER; @@ -79,15 +78,13 @@ public class MultipleConsumersPageStressTest extends ActiveMQTestBase ArrayList exceptions = new ArrayList(); @Test - public void testOpenConsumerEveryTimeDefaultFlowControl0() throws Throwable - { + public void testOpenConsumerEveryTimeDefaultFlowControl0() throws Throwable { shareConnectionFactory = true; openConsumerOnEveryLoop = true; numberOfProducers = 1; numberOfConsumers = 1; - sharedLocator = createInVMNonHALocator() - .setConsumerWindowSize(0); + sharedLocator = createInVMNonHALocator().setConsumerWindowSize(0); sharedSf = createSessionFactory(sharedLocator); @@ -96,8 +93,7 @@ public class MultipleConsumersPageStressTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); HashMap settings = new HashMap(); @@ -110,8 +106,7 @@ public class MultipleConsumersPageStressTest extends ActiveMQTestBase } @Test - public void testOpenConsumerEveryTimeDefaultFlowControl() throws Throwable - { + public void testOpenConsumerEveryTimeDefaultFlowControl() throws Throwable { shareConnectionFactory = true; openConsumerOnEveryLoop = true; numberOfProducers = 1; @@ -128,24 +123,20 @@ public class MultipleConsumersPageStressTest extends ActiveMQTestBase } @Test - public void testReuseConsumersFlowControl0() throws Throwable - { + public void testReuseConsumersFlowControl0() throws Throwable { shareConnectionFactory = true; openConsumerOnEveryLoop = false; numberOfProducers = 1; numberOfConsumers = 1; - sharedLocator = createInVMNonHALocator() - .setConsumerWindowSize(0); + sharedLocator = createInVMNonHALocator().setConsumerWindowSize(0); sharedSf = createSessionFactory(sharedLocator); - try - { + try { internalMultipleConsumers(); } - catch (Throwable e) - { + catch (Throwable e) { TestConsumer tstConsumer = consumers.get(0); System.out.println("first retry: " + tstConsumer.consumer.receive(1000)); @@ -156,7 +147,6 @@ public class MultipleConsumersPageStressTest extends ActiveMQTestBase System.out.println(pagedServerQueue.debug()); - tstConsumer.session.commit(); System.out.println("Third retry:" + tstConsumer.consumer.receive(1000)); @@ -177,44 +167,36 @@ public class MultipleConsumersPageStressTest extends ActiveMQTestBase } - public void internalMultipleConsumers() throws Throwable - { - for (int i = 0; i < numberOfProducers; i++) - { + public void internalMultipleConsumers() throws Throwable { + for (int i = 0; i < numberOfProducers; i++) { producers.add(new TestProducer()); } - for (int i = 0; i < numberOfConsumers; i++) - { + for (int i = 0; i < numberOfConsumers; i++) { consumers.add(new TestConsumer()); } - for (Tester test : producers) - { + for (Tester test : producers) { test.start(); } Thread.sleep(2000); - for (Tester test : consumers) - { + for (Tester test : consumers) { test.start(); } - for (Tester test : consumers) - { + for (Tester test : consumers) { test.join(); } runningProducer = false; - for (Tester test : producers) - { + for (Tester test : producers) { test.join(); } - for (Throwable e : exceptions) - { + for (Throwable e : exceptions) { throw e; } @@ -234,38 +216,33 @@ public class MultipleConsumersPageStressTest extends ActiveMQTestBase // Inner classes ------------------------------------------------- - abstract class Tester extends Thread - { + abstract class Tester extends Thread { + Random random = new Random(); public abstract void close(); protected abstract boolean enabled(); - protected void exceptionHappened(final Throwable e) - { + protected void exceptionHappened(final Throwable e) { runningConsumer = false; runningProducer = false; e.printStackTrace(); exceptions.add(e); } - public int getNumberOfMessages() throws Exception - { + public int getNumberOfMessages() throws Exception { int numberOfMessages = random.nextInt(20); - if (numberOfMessages <= 0) - { + if (numberOfMessages <= 0) { return 1; } - else - { + else { return numberOfMessages; } } } - class TestConsumer extends Tester - { + class TestConsumer extends Tester { public ClientConsumer consumer = null; @@ -276,55 +253,45 @@ public class MultipleConsumersPageStressTest extends ActiveMQTestBase public ClientSessionFactory sf = null; @Override - public void close() - { - try - { + public void close() { + try { - if (!openConsumerOnEveryLoop) - { + if (!openConsumerOnEveryLoop) { consumer.close(); } session.rollback(); session.close(); - if (!shareConnectionFactory) - { + if (!shareConnectionFactory) { sf.close(); locator.close(); } } - catch (Exception ignored) - { + catch (Exception ignored) { } } @Override - protected boolean enabled() - { + protected boolean enabled() { return runningConsumer; } @Override - public int getNumberOfMessages() throws Exception - { - while (enabled()) - { + public int getNumberOfMessages() throws Exception { + while (enabled()) { int numberOfMessages = super.getNumberOfMessages(); int resultMessages = messagesAvailable.addAndGet(-numberOfMessages); - if (resultMessages < 0) - { + if (resultMessages < 0) { messagesAvailable.addAndGet(-numberOfMessages); numberOfMessages = 0; System.out.println("Negative, giving a little wait"); Thread.sleep(1000); } - if (numberOfMessages > 0) - { + if (numberOfMessages > 0) { return numberOfMessages; } } @@ -333,16 +300,12 @@ public class MultipleConsumersPageStressTest extends ActiveMQTestBase } @Override - public void run() - { - try - { - if (shareConnectionFactory) - { + public void run() { + try { + if (shareConnectionFactory) { session = sharedSf.createSession(false, false); } - else - { + else { locator = createInVMNonHALocator(); sf = createSessionFactory(locator); session = sf.createSession(false, false); @@ -352,42 +315,36 @@ public class MultipleConsumersPageStressTest extends ActiveMQTestBase session.start(); - if (!openConsumerOnEveryLoop) - { + if (!openConsumerOnEveryLoop) { consumer = session.createConsumer(MultipleConsumersPageStressTest.ADDRESS); } int count = 0; - while (enabled() && timeOut > System.currentTimeMillis()) - { + while (enabled() && timeOut > System.currentTimeMillis()) { - if (openConsumerOnEveryLoop) - { + if (openConsumerOnEveryLoop) { consumer = session.createConsumer(MultipleConsumersPageStressTest.ADDRESS); } int numberOfMessages = getNumberOfMessages(); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = consumer.receive(10000); - if (msg == null) - { + if (msg == null) { log.warn("msg " + count + - " was null, currentBatchSize=" + - numberOfMessages + - ", current msg being read=" + - i); + " was null, currentBatchSize=" + + numberOfMessages + + ", current msg being read=" + + i); } Assert.assertNotNull("msg " + count + - " was null, currentBatchSize=" + - numberOfMessages + - ", current msg being read=" + - i, msg); + " was null, currentBatchSize=" + + numberOfMessages + + ", current msg being read=" + + i, msg); - if (numberOfConsumers == 1 && numberOfProducers == 1) - { + if (numberOfConsumers == 1 && numberOfProducers == 1) { Assert.assertEquals(count, msg.getIntProperty("count").intValue()); } @@ -398,23 +355,21 @@ public class MultipleConsumersPageStressTest extends ActiveMQTestBase session.commit(); - if (openConsumerOnEveryLoop) - { + if (openConsumerOnEveryLoop) { consumer.close(); } } } - catch (Throwable e) - { + catch (Throwable e) { exceptionHappened(e); } } } - class TestProducer extends Tester - { + class TestProducer extends Tester { + ClientSession session = null; ClientSessionFactory sf = null; @@ -422,36 +377,28 @@ public class MultipleConsumersPageStressTest extends ActiveMQTestBase ServerLocator locator = null; @Override - public void close() - { - try - { + public void close() { + try { session.rollback(); session.close(); } - catch (Exception ignored) - { + catch (Exception ignored) { } } @Override - protected boolean enabled() - { + protected boolean enabled() { return runningProducer; } @Override - public void run() - { - try - { - if (shareConnectionFactory) - { + public void run() { + try { + if (shareConnectionFactory) { session = sharedSf.createSession(false, false); } - else - { + else { locator = createInVMNonHALocator(); sf = createSessionFactory(locator); session = sf.createSession(false, false); @@ -461,12 +408,10 @@ public class MultipleConsumersPageStressTest extends ActiveMQTestBase int count = 0; - while (enabled()) - { + while (enabled()) { int numberOfMessages = getNumberOfMessages(); - for (int i = 0; i < numberOfMessages; i++) - { + for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = session.createMessage(true); msg.putStringProperty("Test", "This is a simple test"); msg.putIntProperty("count", count++); @@ -477,8 +422,7 @@ public class MultipleConsumersPageStressTest extends ActiveMQTestBase session.commit(); } } - catch (Throwable e) - { + catch (Throwable e) { exceptionHappened(e); } } diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/paging/PageCursorStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/paging/PageCursorStressTest.java index 29c704f11f..b40976a30c 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/paging/PageCursorStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/paging/PageCursorStressTest.java @@ -53,8 +53,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; -public class PageCursorStressTest extends ActiveMQTestBase -{ +public class PageCursorStressTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -76,8 +75,7 @@ public class PageCursorStressTest extends ActiveMQTestBase // Read more cache than what would fit on the memory, and validate if the memory would be cleared through soft-caches @Test - public void testReadCache() throws Exception - { + public void testReadCache() throws Exception { final int NUM_MESSAGES = 100; @@ -85,13 +83,9 @@ public class PageCursorStressTest extends ActiveMQTestBase System.out.println("NumberOfPages = " + numberOfPages); - PageCursorProviderImpl cursorProvider = new PageCursorProviderImpl(lookupPageStore(ADDRESS), - server.getStorageManager(), - server.getExecutorFactory().getExecutor(), - 5); + PageCursorProviderImpl cursorProvider = new PageCursorProviderImpl(lookupPageStore(ADDRESS), server.getStorageManager(), server.getExecutorFactory().getExecutor(), 5); - for (int i = 0; i < numberOfPages; i++) - { + for (int i = 0; i < numberOfPages; i++) { PageCache cache = cursorProvider.getPageCache(i + 1); System.out.println("Page " + i + " had " + cache.getNumberOfMessages() + " messages"); @@ -105,8 +99,7 @@ public class PageCursorStressTest extends ActiveMQTestBase } @Test - public void testSimpleCursor() throws Exception - { + public void testSimpleCursor() throws Exception { final int NUM_MESSAGES = 100; @@ -122,8 +115,7 @@ public class PageCursorStressTest extends ActiveMQTestBase LinkedListIterator iterator = cursor.iterator(); int key = 0; - while ((msg = iterator.next()) != null) - { + while ((msg = iterator.next()) != null) { assertEquals(key++, msg.getMessage().getIntProperty("key").intValue()); cursor.confirmPosition(msg.getPosition()); } @@ -147,52 +139,41 @@ public class PageCursorStressTest extends ActiveMQTestBase } @Test - public void testSimpleCursorWithFilter() throws Exception - { + public void testSimpleCursorWithFilter() throws Exception { final int NUM_MESSAGES = 100; - PageSubscription cursorEven = createNonPersistentCursor(new Filter() - { + PageSubscription cursorEven = createNonPersistentCursor(new Filter() { - public boolean match(ServerMessage message) - { + public boolean match(ServerMessage message) { Boolean property = message.getBooleanProperty("even"); - if (property == null) - { + if (property == null) { return false; } - else - { + else { return property.booleanValue(); } } - public SimpleString getFilterString() - { + public SimpleString getFilterString() { return new SimpleString("even=true"); } }); - PageSubscription cursorOdd = createNonPersistentCursor(new Filter() - { + PageSubscription cursorOdd = createNonPersistentCursor(new Filter() { - public boolean match(ServerMessage message) - { + public boolean match(ServerMessage message) { Boolean property = message.getBooleanProperty("even"); - if (property == null) - { + if (property == null) { return false; } - else - { + else { return !property.booleanValue(); } } - public SimpleString getFilterString() - { + public SimpleString getFilterString() { return new SimpleString("even=true"); } @@ -211,8 +192,7 @@ public class PageCursorStressTest extends ActiveMQTestBase LinkedListIterator iteratorOdd = cursorOdd.iterator(); int key = 0; - while ((msg = iteratorEven.next()) != null) - { + while ((msg = iteratorEven.next()) != null) { System.out.println("Received" + msg); assertEquals(key, msg.getMessage().getIntProperty("key").intValue()); assertTrue(msg.getMessage().getBooleanProperty("even").booleanValue()); @@ -222,8 +202,7 @@ public class PageCursorStressTest extends ActiveMQTestBase assertEquals(NUM_MESSAGES, key); key = 1; - while ((msg = iteratorOdd.next()) != null) - { + while ((msg = iteratorOdd.next()) != null) { assertEquals(key, msg.getMessage().getIntProperty("key").intValue()); assertFalse(msg.getMessage().getBooleanProperty("even").booleanValue()); key += 2; @@ -243,8 +222,7 @@ public class PageCursorStressTest extends ActiveMQTestBase } @Test - public void testReadNextPage() throws Exception - { + public void testReadNextPage() throws Exception { final int NUM_MESSAGES = 1; @@ -260,8 +238,7 @@ public class PageCursorStressTest extends ActiveMQTestBase } @Test - public void testRestartWithHoleOnAck() throws Exception - { + public void testRestartWithHoleOnAck() throws Exception { final int NUM_MESSAGES = 1000; @@ -272,19 +249,14 @@ public class PageCursorStressTest extends ActiveMQTestBase PageCursorProvider cursorProvider = this.server.getPagingManager().getPageStore(ADDRESS).getCursorProvider(); System.out.println("cursorProvider = " + cursorProvider); - PageSubscription cursor = this.server.getPagingManager() - .getPageStore(ADDRESS) - .getCursorProvider() - .getSubscription(queue.getID()); + PageSubscription cursor = this.server.getPagingManager().getPageStore(ADDRESS).getCursorProvider().getSubscription(queue.getID()); System.out.println("Cursor: " + cursor); LinkedListIterator iterator = cursor.iterator(); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { PagedReference msg = iterator.next(); assertEquals(i, msg.getMessage().getIntProperty("key").intValue()); - if (i < 10 || i > 20) - { + if (i < 10 || i > 20) { cursor.ack(msg); } } @@ -300,15 +272,13 @@ public class PageCursorStressTest extends ActiveMQTestBase cursor = this.server.getPagingManager().getPageStore(ADDRESS).getCursorProvider().getSubscription(queue.getID()); iterator = cursor.iterator(); - for (int i = 10; i <= 20; i++) - { + for (int i = 10; i <= 20; i++) { PagedReference msg = iterator.next(); assertEquals(i, msg.getMessage().getIntProperty("key").intValue()); cursor.ack(msg); } - for (int i = 100; i < NUM_MESSAGES; i++) - { + for (int i = 100; i < NUM_MESSAGES; i++) { PagedReference msg = iterator.next(); assertEquals(i, msg.getMessage().getIntProperty("key").intValue()); cursor.ack(msg); @@ -322,8 +292,7 @@ public class PageCursorStressTest extends ActiveMQTestBase } @Test - public void testRestartWithHoleOnAckAndTransaction() throws Exception - { + public void testRestartWithHoleOnAckAndTransaction() throws Exception { final int NUM_MESSAGES = 1000; int numberOfPages = addMessages(NUM_MESSAGES, 10 * 1024); @@ -333,10 +302,7 @@ public class PageCursorStressTest extends ActiveMQTestBase PageCursorProvider cursorProvider = this.server.getPagingManager().getPageStore(ADDRESS).getCursorProvider(); System.out.println("cursorProvider = " + cursorProvider); - PageSubscription cursor = this.server.getPagingManager() - .getPageStore(ADDRESS) - .getCursorProvider() - .getSubscription(queue.getID()); + PageSubscription cursor = this.server.getPagingManager().getPageStore(ADDRESS).getCursorProvider().getSubscription(queue.getID()); System.out.println("Cursor: " + cursor); @@ -344,12 +310,10 @@ public class PageCursorStressTest extends ActiveMQTestBase LinkedListIterator iterator = cursor.iterator(); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { PagedReference msg = iterator.next(); assertEquals(i, msg.getMessage().getIntProperty("key").intValue()); - if (i < 10 || i > 20) - { + if (i < 10 || i > 20) { cursor.ackTx(tx, msg); } } @@ -367,15 +331,13 @@ public class PageCursorStressTest extends ActiveMQTestBase tx = new TransactionImpl(server.getStorageManager(), 60 * 1000); iterator = cursor.iterator(); - for (int i = 10; i <= 20; i++) - { + for (int i = 10; i <= 20; i++) { PagedReference msg = iterator.next(); assertEquals(i, msg.getMessage().getIntProperty("key").intValue()); cursor.ackTx(tx, msg); } - for (int i = 100; i < NUM_MESSAGES; i++) - { + for (int i = 100; i < NUM_MESSAGES; i++) { PagedReference msg = iterator.next(); assertEquals(i, msg.getMessage().getIntProperty("key").intValue()); cursor.ackTx(tx, msg); @@ -391,8 +353,7 @@ public class PageCursorStressTest extends ActiveMQTestBase } @Test - public void testConsumeLivePage() throws Exception - { + public void testConsumeLivePage() throws Exception { PagingStoreImpl pageStore = lookupPageStore(ADDRESS); pageStore.startPaging(); @@ -404,10 +365,7 @@ public class PageCursorStressTest extends ActiveMQTestBase PageCursorProvider cursorProvider = this.server.getPagingManager().getPageStore(ADDRESS).getCursorProvider(); System.out.println("cursorProvider = " + cursorProvider); - PageSubscription cursor = this.server.getPagingManager() - .getPageStore(ADDRESS) - .getCursorProvider() - .getSubscription(queue.getID()); + PageSubscription cursor = this.server.getPagingManager().getPageStore(ADDRESS).getCursorProvider().getSubscription(queue.getID()); System.out.println("Cursor: " + cursor); @@ -415,8 +373,7 @@ public class PageCursorStressTest extends ActiveMQTestBase LinkedListIterator iterator = cursor.iterator(); - for (int i = 0; i < NUM_MESSAGES; i++) - { + for (int i = 0; i < NUM_MESSAGES; i++) { // if (i % 100 == 0) System.out.println("read/written " + i); @@ -447,13 +404,11 @@ public class PageCursorStressTest extends ActiveMQTestBase cursor = this.server.getPagingManager().getPageStore(ADDRESS).getCursorProvider().getSubscription(queue.getID()); iterator = cursor.iterator(); - for (int i = 0; i < NUM_MESSAGES * 2; i++) - { + for (int i = 0; i < NUM_MESSAGES * 2; i++) { if (i % 100 == 0) System.out.println("Paged " + i); - if (i >= NUM_MESSAGES) - { + if (i >= NUM_MESSAGES) { ActiveMQBuffer buffer = RandomUtil.randomBuffer(messageSize, i + 1L); @@ -479,13 +434,11 @@ public class PageCursorStressTest extends ActiveMQTestBase cursor = this.server.getPagingManager().getPageStore(ADDRESS).getCursorProvider().getSubscription(queue.getID()); iterator = cursor.iterator(); - for (int i = 0; i < NUM_MESSAGES * 3; i++) - { + for (int i = 0; i < NUM_MESSAGES * 3; i++) { if (i % 100 == 0) System.out.println("Paged " + i); - if (i >= NUM_MESSAGES * 2 - 1) - { + if (i >= NUM_MESSAGES * 2 - 1) { ActiveMQBuffer buffer = RandomUtil.randomBuffer(messageSize, i + 1L); @@ -529,10 +482,8 @@ public class PageCursorStressTest extends ActiveMQTestBase } - @Test - public void testConsumeLivePageMultiThread() throws Exception - { + public void testConsumeLivePageMultiThread() throws Exception { final PagingStoreImpl pageStore = lookupPageStore(ADDRESS); pageStore.startPaging(); @@ -548,10 +499,7 @@ public class PageCursorStressTest extends ActiveMQTestBase PageCursorProvider cursorProvider = this.server.getPagingManager().getPageStore(ADDRESS).getCursorProvider(); System.out.println("cursorProvider = " + cursorProvider); - PageSubscription cursor = this.server.getPagingManager() - .getPageStore(ADDRESS) - .getCursorProvider() - .getSubscription(queue.getID()); + PageSubscription cursor = this.server.getPagingManager().getPageStore(ADDRESS).getCursorProvider().getSubscription(queue.getID()); System.out.println("Cursor: " + cursor); @@ -559,29 +507,23 @@ public class PageCursorStressTest extends ActiveMQTestBase final AtomicInteger exceptions = new AtomicInteger(0); - Thread t1 = new Thread() - { + Thread t1 = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { int count = 0; - for (int txCount = 0; txCount < NUM_TX; txCount++) - { + for (int txCount = 0; txCount < NUM_TX; txCount++) { Transaction tx = null; - if (txCount % 2 == 0) - { + if (txCount % 2 == 0) { tx = new TransactionImpl(storage); } RoutingContext ctx = generateCTX(tx); - for (int i = 0; i < MSGS_TX; i++) - { + for (int i = 0; i < MSGS_TX; i++) { //System.out.println("Sending " + count); ActiveMQBuffer buffer = RandomUtil.randomBuffer(messageSize, count); @@ -593,15 +535,13 @@ public class PageCursorStressTest extends ActiveMQTestBase Assert.assertTrue(pageStore.page(msg, ctx.getTransaction(), ctx.getContextListing(ADDRESS), lock)); } - if (tx != null) - { + if (tx != null) { tx.commit(); } } } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); exceptions.incrementAndGet(); } @@ -610,22 +550,17 @@ public class PageCursorStressTest extends ActiveMQTestBase t1.start(); - LinkedListIterator iterator = cursor.iterator(); - for (int i = 0; i < TOTAL_MSG; i++) - { + for (int i = 0; i < TOTAL_MSG; i++) { assertEquals(0, exceptions.get()); PagedReference ref = null; - for (int repeat = 0; repeat < 5; repeat++) - { + for (int repeat = 0; repeat < 5; repeat++) { ref = iterator.next(); - if (ref == null) - { + if (ref == null) { Thread.sleep(1000); } - else - { + else { break; } } @@ -641,18 +576,15 @@ public class PageCursorStressTest extends ActiveMQTestBase assertEquals(0, exceptions.get()); } - private RoutingContextImpl generateCTX() - { + private RoutingContextImpl generateCTX() { return generateCTX(null); } - private RoutingContextImpl generateCTX(Transaction tx) - { + private RoutingContextImpl generateCTX(Transaction tx) { RoutingContextImpl ctx = new RoutingContextImpl(tx); ctx.addQueue(ADDRESS, queue); - for (Queue q : this.queueList) - { + for (Queue q : this.queueList) { ctx.addQueue(ADDRESS, q); } @@ -662,23 +594,19 @@ public class PageCursorStressTest extends ActiveMQTestBase /** * @throws Exception */ - private void waitCleanup() throws Exception - { + private void waitCleanup() throws Exception { // The cleanup is done asynchronously, so we need to wait some time long timeout = System.currentTimeMillis() + 10000; - while (System.currentTimeMillis() < timeout && lookupPageStore(ADDRESS).getNumberOfPages() != 1) - { + while (System.currentTimeMillis() < timeout && lookupPageStore(ADDRESS).getNumberOfPages() != 1) { Thread.sleep(100); } - assertTrue("expected " + lookupPageStore(ADDRESS).getNumberOfPages(), - lookupPageStore(ADDRESS).getNumberOfPages() <= 2); + assertTrue("expected " + lookupPageStore(ADDRESS).getNumberOfPages(), lookupPageStore(ADDRESS).getNumberOfPages() <= 2); } @Test - public void testLazyCommit() throws Exception - { + public void testLazyCommit() throws Exception { PagingStoreImpl pageStore = lookupPageStore(ADDRESS); pageStore.startPaging(); @@ -690,10 +618,7 @@ public class PageCursorStressTest extends ActiveMQTestBase PageCursorProvider cursorProvider = this.server.getPagingManager().getPageStore(ADDRESS).getCursorProvider(); System.out.println("cursorProvider = " + cursorProvider); - PageSubscription cursor = this.server.getPagingManager() - .getPageStore(ADDRESS) - .getCursorProvider() - .getSubscription(queue.getID()); + PageSubscription cursor = this.server.getPagingManager().getPageStore(ADDRESS).getCursorProvider().getSubscription(queue.getID()); LinkedListIterator iterator = cursor.iterator(); System.out.println("Cursor: " + cursor); @@ -709,8 +634,7 @@ public class PageCursorStressTest extends ActiveMQTestBase System.out.println("Number of pages - " + pageStore.getNumberOfPages()); // First consume what's already there without any tx as nothing was committed - for (int i = 100; i < 200; i++) - { + for (int i = 100; i < 200; i++) { PagedReference pos = iterator.next(); assertNotNull("Null at position " + i, pos); assertEquals(i, pos.getMessage().getIntProperty("key").intValue()); @@ -723,8 +647,7 @@ public class PageCursorStressTest extends ActiveMQTestBase storage.waitOnOperations(); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { PagedReference pos = iterator.next(); assertNotNull("Null at position " + i, pos); assertEquals(i, pos.getMessage().getIntProperty("key").intValue()); @@ -742,14 +665,12 @@ public class PageCursorStressTest extends ActiveMQTestBase } - private int tstProperty(ServerMessage msg) - { + private int tstProperty(ServerMessage msg) { return msg.getIntProperty("key").intValue(); } @Test - public void testMultipleIterators() throws Exception - { + public void testMultipleIterators() throws Exception { final int NUM_MESSAGES = 10; @@ -807,24 +728,20 @@ public class PageCursorStressTest extends ActiveMQTestBase assertTrue(iter2.hasNext()); - } - private int addMessages(final int numMessages, final int messageSize) throws Exception - { + private int addMessages(final int numMessages, final int messageSize) throws Exception { return addMessages(0, numMessages, messageSize); } - private int addMessages(final int start, final int numMessages, final int messageSize) throws Exception - { + private int addMessages(final int start, final int numMessages, final int messageSize) throws Exception { PagingStoreImpl pageStore = lookupPageStore(ADDRESS); pageStore.startPaging(); RoutingContext ctx = generateCTX(); - for (int i = start; i < start + numMessages; i++) - { + for (int i = start; i < start + numMessages; i++) { if (i % 100 == 0) System.out.println("Paged " + i); ActiveMQBuffer buffer = RandomUtil.randomBuffer(messageSize, i + 1L); @@ -846,8 +763,7 @@ public class PageCursorStressTest extends ActiveMQTestBase * @return * @throws Exception */ - private PagingStoreImpl lookupPageStore(SimpleString address) throws Exception - { + private PagingStoreImpl lookupPageStore(SimpleString address) throws Exception { return (PagingStoreImpl) server.getPagingManager().getPageStore(address); } @@ -857,8 +773,7 @@ public class PageCursorStressTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); OperationContextImpl.clearContext(); queueList = new ArrayList(); @@ -870,12 +785,10 @@ public class PageCursorStressTest extends ActiveMQTestBase /** * @throws Exception */ - private void createServer() throws Exception - { + private void createServer() throws Exception { OperationContextImpl.clearContext(); - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(true); + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(true); server = createServer(true, config, PAGE_SIZE, PAGE_MAX, new HashMap()); @@ -883,13 +796,11 @@ public class PageCursorStressTest extends ActiveMQTestBase queueList.clear(); - try - { + try { queue = server.createQueue(ADDRESS, ADDRESS, null, true, false); queue.pause(); } - catch (Exception ignored) - { + catch (Exception ignored) { } } @@ -897,8 +808,7 @@ public class PageCursorStressTest extends ActiveMQTestBase * @return * @throws Exception */ - private PageSubscription createNonPersistentCursor(Filter filter) throws Exception - { + private PageSubscription createNonPersistentCursor(Filter filter) throws Exception { long id = server.getStorageManager().generateID(); FakeQueue queue = new FakeQueue(new SimpleString(filter.toString()), id); queueList.add(queue); @@ -914,8 +824,7 @@ public class PageCursorStressTest extends ActiveMQTestBase * @return * @throws Exception */ - private PageCursorProvider lookupCursorProvider() throws Exception - { + private PageCursorProvider lookupCursorProvider() throws Exception { return lookupPageStore(ADDRESS).getCursorProvider(); } @@ -933,15 +842,13 @@ public class PageCursorStressTest extends ActiveMQTestBase long pgParameter, int start, final int NUM_MESSAGES, - final int messageSize) throws Exception - { + final int messageSize) throws Exception { TransactionImpl txImpl = new TransactionImpl(pgParameter, null, storage); RoutingContext ctx = generateCTX(txImpl); - for (int i = start; i < start + NUM_MESSAGES; i++) - { + for (int i = start; i < start + NUM_MESSAGES; i++) { ActiveMQBuffer buffer = RandomUtil.randomBuffer(messageSize, i + 1L); ServerMessage msg = new ServerMessageImpl(storage.generateID(), buffer.writerIndex()); msg.getBodyBuffer().writeBytes(buffer, 0, buffer.writerIndex()); diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/paging/PageStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/paging/PageStressTest.java index 994c4e38a2..de3d545678 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/paging/PageStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/paging/PageStressTest.java @@ -38,18 +38,15 @@ import org.junit.Test; /** * This is an integration-tests that will take some time to run. */ -public class PageStressTest extends ActiveMQTestBase -{ +public class PageStressTest extends ActiveMQTestBase { + private ActiveMQServer server; private ServerLocator locator; @Test - public void testStopDuringDepage() throws Exception - { - Configuration config = createDefaultInVMConfig() - .setJournalSyncNonTransactional(false) - .setJournalSyncTransactional(false); + public void testStopDuringDepage() throws Exception { + Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false).setJournalSyncTransactional(false); HashMap settings = new HashMap(); @@ -71,10 +68,8 @@ public class PageStressTest extends ActiveMQTestBase ClientMessage message = createBytesMessage(session, ActiveMQBytesMessage.TYPE, new byte[700], true); - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { - if (i % 10000 == 0) - { + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { + if (i % 10000 == 0) { System.out.println("Sent " + i); } prod.send(message); @@ -88,19 +83,15 @@ public class PageStressTest extends ActiveMQTestBase int msgs = 0; ClientMessage msg; - do - { + do { msg = consumer.receive(10000); - if (msg != null) - { + if (msg != null) { msg.acknowledge(); - if (++msgs % 1000 == 0) - { + if (++msgs % 1000 == 0) { System.out.println("Received " + msgs); } } - } - while (msg != null); + } while (msg != null); session.commit(); @@ -122,20 +113,16 @@ public class PageStressTest extends ActiveMQTestBase session.start(); - do - { + do { msg = consumer.receive(10000); - if (msg != null) - { + if (msg != null) { msg.acknowledge(); session.commit(); - if (++msgs % 1000 == 0) - { + if (++msgs % 1000 == 0) { System.out.println("Received " + msgs); } } - } - while (msg != null); + } while (msg != null); System.out.println("msgs second time: " + msgs); @@ -143,12 +130,10 @@ public class PageStressTest extends ActiveMQTestBase } @Test - public void testPageOnMultipleDestinations() throws Exception - { + public void testPageOnMultipleDestinations() throws Exception { HashMap settings = new HashMap<>(); - AddressSettings setting = new AddressSettings() - .setMaxSizeBytes(20 * 1024 * 1024); + AddressSettings setting = new AddressSettings().setMaxSizeBytes(20 * 1024 * 1024); settings.put("page-adr", setting); server = addServer(createServer(true, createDefaultInVMConfig(), 10 * 1024 * 1024, 20 * 1024 * 1024, settings)); @@ -171,10 +156,8 @@ public class PageStressTest extends ActiveMQTestBase int NUMBER_OF_MESSAGES = 60000; - for (int i = 0; i < NUMBER_OF_MESSAGES; i++) - { - if (i % 10000 == 0) - { + for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { + if (i % 10000 == 0) { System.out.println(i); } prod.send(message); @@ -186,11 +169,9 @@ public class PageStressTest extends ActiveMQTestBase int[] counters = new int[2]; - ClientConsumer[] consumers = new ClientConsumer[]{session.createConsumer(queue[0]), - session.createConsumer(queue[1])}; + ClientConsumer[] consumers = new ClientConsumer[]{session.createConsumer(queue[0]), session.createConsumer(queue[1])}; - while (true) - { + while (true) { int msgs1 = readMessages(session, consumers[0], queue[0]); int msgs2 = readMessages(session, consumers[1], queue[1]); counters[0] += msgs1; @@ -198,8 +179,7 @@ public class PageStressTest extends ActiveMQTestBase System.out.println("msgs1 = " + msgs1 + " msgs2 = " + msgs2); - if (msgs1 + msgs2 == 0) - { + if (msgs1 + msgs2 == 0) { break; } } @@ -211,27 +191,24 @@ public class PageStressTest extends ActiveMQTestBase Assert.assertEquals(NUMBER_OF_MESSAGES, counters[1]); } - private int readMessages(final ClientSession session, final ClientConsumer consumer, final SimpleString queue) throws ActiveMQException - { + private int readMessages(final ClientSession session, + final ClientConsumer consumer, + final SimpleString queue) throws ActiveMQException { session.start(); int msgs = 0; ClientMessage msg = null; - do - { + do { msg = consumer.receive(1000); - if (msg != null) - { + if (msg != null) { msg.acknowledge(); - if (++msgs % 10000 == 0) - { + if (++msgs % 10000 == 0) { System.out.println("received " + msgs); session.commit(); } } - } - while (msg != null); + } while (msg != null); session.commit(); @@ -242,23 +219,16 @@ public class PageStressTest extends ActiveMQTestBase // Protected ----------------------------------------------------- @Override - protected Configuration createDefaultInVMConfig() throws Exception - { - Configuration config = super.createDefaultInVMConfig() - .setJournalFileSize(10 * 1024 * 1024) - .setJournalMinFiles(5); + protected Configuration createDefaultInVMConfig() throws Exception { + Configuration config = super.createDefaultInVMConfig().setJournalFileSize(10 * 1024 * 1024).setJournalMinFiles(5); return config; } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - locator = createInVMNonHALocator() - .setBlockOnAcknowledge(true) - .setBlockOnDurableSend(false) - .setBlockOnNonDurableSend(false); + locator = createInVMNonHALocator().setBlockOnAcknowledge(true).setBlockOnDurableSend(false).setBlockOnNonDurableSend(false); } } diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/remote/PingStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/remote/PingStressTest.java index cb05fa953b..bd4a1186b2 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/remote/PingStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/remote/PingStressTest.java @@ -34,8 +34,8 @@ import org.junit.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -public class PingStressTest extends ActiveMQTestBase -{ +public class PingStressTest extends ActiveMQTestBase { + private static final UnitTestLogger log = UnitTestLogger.LOGGER; private static final long PING_INTERVAL = 500; @@ -44,25 +44,20 @@ public class PingStressTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(false, createDefaultNettyConfig()); server.start(); } - protected int getNumberOfIterations() - { + protected int getNumberOfIterations() { return 20; } @Test - public void testMultiThreadOpenAndCloses() throws Exception - { - for (int i = 0; i < getNumberOfIterations(); i++) - { - if (i > 0) - { + public void testMultiThreadOpenAndCloses() throws Exception { + for (int i = 0; i < getNumberOfIterations(); i++) { + if (i > 0) { tearDown(); setUp(); } @@ -74,69 +69,53 @@ public class PingStressTest extends ActiveMQTestBase /* * Test the client triggering failure due to no pong received in time */ - private void internalTest() throws Exception - { - Interceptor noPongInterceptor = new Interceptor() - { - public boolean intercept(final Packet packet, final RemotingConnection conn) throws ActiveMQException - { + private void internalTest() throws Exception { + Interceptor noPongInterceptor = new Interceptor() { + public boolean intercept(final Packet packet, final RemotingConnection conn) throws ActiveMQException { PingStressTest.log.info("In interceptor, packet is " + packet.getType()); - if (packet.getType() == PacketImpl.PING) - { + if (packet.getType() == PacketImpl.PING) { PingStressTest.log.info("Ignoring Ping packet.. it will be dropped"); return false; } - else - { + else { return true; } } }; server.getRemotingService().addIncomingInterceptor(noPongInterceptor); - ServerLocator locator = createNettyNonHALocator() - .setClientFailureCheckPeriod(PingStressTest.PING_INTERVAL) - .setConnectionTTL((long) (PingStressTest.PING_INTERVAL * 1.5)) - .setCallTimeout(PingStressTest.PING_INTERVAL * 10); + ServerLocator locator = createNettyNonHALocator().setClientFailureCheckPeriod(PingStressTest.PING_INTERVAL).setConnectionTTL((long) (PingStressTest.PING_INTERVAL * 1.5)).setCallTimeout(PingStressTest.PING_INTERVAL * 10); final ClientSessionFactory csf1 = createSessionFactory(locator); - final int numberOfSessions = 1; final int numberOfThreads = 30; final CountDownLatch flagStart = new CountDownLatch(1); final CountDownLatch flagAligned = new CountDownLatch(numberOfThreads); - class LocalThread extends Thread - { + class LocalThread extends Thread { + Throwable failure; int threadNumber; - public LocalThread(final int i) - { + public LocalThread(final int i) { super("LocalThread i = " + i); threadNumber = i; } @Override - public void run() - { - try - { + public void run() { + try { - ServerLocator locator = createNettyNonHALocator() - .setClientFailureCheckPeriod(PingStressTest.PING_INTERVAL) - .setConnectionTTL((long) (PingStressTest.PING_INTERVAL * 1.5)) - .setCallTimeout(PingStressTest.PING_INTERVAL * 10); + ServerLocator locator = createNettyNonHALocator().setClientFailureCheckPeriod(PingStressTest.PING_INTERVAL).setConnectionTTL((long) (PingStressTest.PING_INTERVAL * 1.5)).setCallTimeout(PingStressTest.PING_INTERVAL * 10); final ClientSessionFactory csf2 = createSessionFactory(locator); // Start all at once to make concurrency worst flagAligned.countDown(); flagStart.await(); - for (int i = 0; i < numberOfSessions; i++) - { + for (int i = 0; i < numberOfSessions; i++) { System.out.println(getName() + " Session = " + i); ClientSession session; @@ -145,12 +124,10 @@ public class PingStressTest extends ActiveMQTestBase // on the test, sharing it with other threads // (playing a possible user behaviour where you share the Factories among threads, versus not sharing // them) - if (RandomUtil.randomBoolean()) - { + if (RandomUtil.randomBoolean()) { session = csf1.createSession(false, false, false); } - else - { + else { session = csf2.createSession(false, false, false); } @@ -164,8 +141,7 @@ public class PingStressTest extends ActiveMQTestBase locator.close(); } } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); failure = e; } @@ -174,8 +150,7 @@ public class PingStressTest extends ActiveMQTestBase LocalThread[] threads = new LocalThread[numberOfThreads]; - for (int i = 0; i < numberOfThreads; i++) - { + for (int i = 0; i < numberOfThreads; i++) { threads[i] = new LocalThread(i); threads[i].start(); } @@ -184,17 +159,14 @@ public class PingStressTest extends ActiveMQTestBase flagStart.countDown(); Throwable e = null; - for (LocalThread t : threads) - { + for (LocalThread t : threads) { t.join(); - if (t.failure != null) - { + if (t.failure != null) { e = t.failure; } } - if (e != null) - { + if (e != null) { throw new Exception("Test Failed", e); } diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/stomp/StompStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/stomp/StompStressTest.java index 16b8b72ad5..1a7b7648d9 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/stomp/StompStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/stomp/StompStressTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.stress.stomp; + import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Before; import org.junit.After; @@ -43,8 +44,8 @@ import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.ActiveMQServers; -public class StompStressTest extends ActiveMQTestBase -{ +public class StompStressTest extends ActiveMQTestBase { + private static final int COUNT = 1000; private final int port = 61613; @@ -58,8 +59,7 @@ public class StompStressTest extends ActiveMQTestBase private ActiveMQServer server; @Test - public void testSendAndReceiveMessage() throws Exception - { + public void testSendAndReceiveMessage() throws Exception { String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); @@ -71,14 +71,12 @@ public class StompStressTest extends ActiveMQTestBase frame = "SEND\n" + "destination:" + destination + "\n"; - for (int i = 0; i < COUNT; i++) - { + for (int i = 0; i < COUNT; i++) { System.out.println(">>> " + i); sendFrame(frame + "count:" + i + "\n\n" + Stomp.NULL); } - for (int i = 0; i < COUNT; i++) - { + for (int i = 0; i < COUNT; i++) { System.out.println("<<< " + i); frame = receiveFrame(10000); Assert.assertTrue(frame.startsWith("MESSAGE")); @@ -94,8 +92,7 @@ public class StompStressTest extends ActiveMQTestBase // ------------------------------------------------------------------------- @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); server = createServer(); @@ -105,79 +102,59 @@ public class StompStressTest extends ActiveMQTestBase inputBuffer = new ByteArrayOutputStream(); } - private ActiveMQServer createServer() throws Exception - { + private ActiveMQServer createServer() throws Exception { Map params = new HashMap(); params.put(TransportConstants.PROTOCOLS_PROP_NAME, StompProtocolManagerFactory.STOMP_PROTOCOL_NAME); params.put(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_STOMP_PORT); TransportConfiguration stompTransport = new TransportConfiguration(NettyAcceptorFactory.class.getName(), params); - Configuration config = createBasicConfig() - .setPersistenceEnabled(false) - .addAcceptorConfiguration(stompTransport) - .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())) - .addQueueConfiguration(new CoreQueueConfiguration() - .setAddress(destination) - .setName(destination) - .setDurable(false)); + Configuration config = createBasicConfig().setPersistenceEnabled(false).addAcceptorConfiguration(stompTransport).addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())).addQueueConfiguration(new CoreQueueConfiguration().setAddress(destination).setName(destination).setDurable(false)); return addServer(ActiveMQServers.newActiveMQServer(config)); } @Override @After - public void tearDown() throws Exception - { - if (stompSocket != null) - { + public void tearDown() throws Exception { + if (stompSocket != null) { stompSocket.close(); } super.tearDown(); } - protected Socket createSocket() throws IOException - { + protected Socket createSocket() throws IOException { return new Socket("127.0.0.1", port); } - public void sendFrame(String data) throws Exception - { + public void sendFrame(String data) throws Exception { byte[] bytes = data.getBytes(StandardCharsets.UTF_8); OutputStream outputStream = stompSocket.getOutputStream(); - for (byte b : bytes) - { + for (byte b : bytes) { outputStream.write(b); } outputStream.flush(); } - public void sendFrame(byte[] data) throws Exception - { + public void sendFrame(byte[] data) throws Exception { OutputStream outputStream = stompSocket.getOutputStream(); - for (byte element : data) - { + for (byte element : data) { outputStream.write(element); } outputStream.flush(); } - public String receiveFrame(long timeOut) throws Exception - { - stompSocket.setSoTimeout((int)timeOut); + public String receiveFrame(long timeOut) throws Exception { + stompSocket.setSoTimeout((int) timeOut); InputStream is = stompSocket.getInputStream(); int c = 0; - for (;;) - { + for (;;) { c = is.read(); - if (c < 0) - { + if (c < 0) { throw new IOException("socket closed."); } - else if (c == 0) - { + else if (c == 0) { c = is.read(); - if (c != '\n') - { + if (c != '\n') { byte[] ba = inputBuffer.toByteArray(); System.out.println(new String(ba, StandardCharsets.UTF_8)); } @@ -186,8 +163,7 @@ public class StompStressTest extends ActiveMQTestBase inputBuffer.reset(); return new String(ba, StandardCharsets.UTF_8); } - else - { + else { inputBuffer.write(c); } } diff --git a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/journal/impl/AIOJournalImplTest.java b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/journal/impl/AIOJournalImplTest.java index 717188af3c..f407d9eb75 100644 --- a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/journal/impl/AIOJournalImplTest.java +++ b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/journal/impl/AIOJournalImplTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.timing.core.journal.impl; + import java.io.File; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; @@ -22,17 +23,15 @@ import org.apache.activemq.artemis.core.io.SequentialFileFactory; import org.apache.activemq.artemis.core.io.aio.AIOSequentialFileFactory; import org.junit.BeforeClass; -public class AIOJournalImplTest extends JournalImplTestUnit -{ +public class AIOJournalImplTest extends JournalImplTestUnit { + @BeforeClass - public static void hasAIO() - { + public static void hasAIO() { org.junit.Assume.assumeTrue("Test case needs AIO to run", AIOSequentialFileFactory.isSupported()); } @Override - protected SequentialFileFactory getFileFactory() throws Exception - { + protected SequentialFileFactory getFileFactory() throws Exception { File file = new File(getTestDir()); ActiveMQTestBase.deleteDirectory(file); diff --git a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/journal/impl/FakeJournalImplTest.java b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/journal/impl/FakeJournalImplTest.java index 9e1fb68c4f..4c272bf948 100644 --- a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/journal/impl/FakeJournalImplTest.java +++ b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/journal/impl/FakeJournalImplTest.java @@ -19,11 +19,10 @@ package org.apache.activemq.artemis.tests.timing.core.journal.impl; import org.apache.activemq.artemis.tests.unit.core.journal.impl.fakes.FakeSequentialFileFactory; import org.apache.activemq.artemis.core.io.SequentialFileFactory; -public class FakeJournalImplTest extends JournalImplTestUnit -{ +public class FakeJournalImplTest extends JournalImplTestUnit { + @Override - protected SequentialFileFactory getFileFactory() throws Exception - { + protected SequentialFileFactory getFileFactory() throws Exception { return new FakeSequentialFileFactory(); } } diff --git a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/journal/impl/JournalImplTestUnit.java b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/journal/impl/JournalImplTestUnit.java index 3ae3255922..d93c0eb3bc 100644 --- a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/journal/impl/JournalImplTestUnit.java +++ b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/journal/impl/JournalImplTestUnit.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.timing.core.journal.impl; + import java.util.ArrayList; import org.apache.activemq.artemis.core.journal.PreparedTransactionInfo; @@ -26,22 +27,20 @@ import org.junit.After; import org.junit.Assert; import org.junit.Test; -public abstract class JournalImplTestUnit extends JournalImplTestBase -{ +public abstract class JournalImplTestUnit extends JournalImplTestBase { + private static final UnitTestLogger log = UnitTestLogger.LOGGER; @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { super.tearDown(); Assert.assertEquals(0, LibaioContext.getTotalMaxIO()); } @Test - public void testAddUpdateDeleteManyLargeFileSize() throws Exception - { + public void testAddUpdateDeleteManyLargeFileSize() throws Exception { final int numberAdds = 10000; final int numberUpdates = 5000; @@ -50,22 +49,19 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase long[] adds = new long[numberAdds]; - for (int i = 0; i < numberAdds; i++) - { + for (int i = 0; i < numberAdds; i++) { adds[i] = i; } long[] updates = new long[numberUpdates]; - for (int i = 0; i < numberUpdates; i++) - { + for (int i = 0; i < numberUpdates; i++) { updates[i] = i; } long[] deletes = new long[numberDeletes]; - for (int i = 0; i < numberDeletes; i++) - { + for (int i = 0; i < numberDeletes; i++) { deletes[i] = i; } @@ -84,8 +80,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testAddUpdateDeleteManySmallFileSize() throws Exception - { + public void testAddUpdateDeleteManySmallFileSize() throws Exception { final int numberAdds = 10000; final int numberUpdates = 5000; @@ -94,22 +89,19 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase long[] adds = new long[numberAdds]; - for (int i = 0; i < numberAdds; i++) - { + for (int i = 0; i < numberAdds; i++) { adds[i] = i; } long[] updates = new long[numberUpdates]; - for (int i = 0; i < numberUpdates; i++) - { + for (int i = 0; i < numberUpdates; i++) { updates[i] = i; } long[] deletes = new long[numberDeletes]; - for (int i = 0; i < numberDeletes; i++) - { + for (int i = 0; i < numberDeletes; i++) { deletes[i] = i; } @@ -129,8 +121,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testReclaimAndReload() throws Exception - { + public void testReclaimAndReload() throws Exception { setup(2, 10 * 1024 * 1024, false); createJournal(); startJournal(); @@ -142,24 +133,21 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase int NUMBER_OF_RECORDS = 1000; - for (int count = 0; count < NUMBER_OF_RECORDS; count++) - { - journal.appendAddRecord(count, (byte)0, record, false); + for (int count = 0; count < NUMBER_OF_RECORDS; count++) { + journal.appendAddRecord(count, (byte) 0, record, false); - if (count >= NUMBER_OF_RECORDS / 2) - { + if (count >= NUMBER_OF_RECORDS / 2) { journal.appendDeleteRecord(count - NUMBER_OF_RECORDS / 2, false); } - if (count % 100 == 0) - { + if (count % 100 == 0) { JournalImplTestUnit.log.debug("Done: " + count); } } long end = System.currentTimeMillis(); - double rate = 1000 * (double)NUMBER_OF_RECORDS / (end - start); + double rate = 1000 * (double) NUMBER_OF_RECORDS / (end - start); JournalImplTestUnit.log.debug("Rate of " + rate + " adds/removes per sec"); diff --git a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/journal/impl/NIOJournalImplTest.java b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/journal/impl/NIOJournalImplTest.java index 842ad3b8ea..8048fb1a28 100644 --- a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/journal/impl/NIOJournalImplTest.java +++ b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/journal/impl/NIOJournalImplTest.java @@ -22,13 +22,12 @@ import org.apache.activemq.artemis.core.io.SequentialFileFactory; import org.apache.activemq.artemis.core.io.nio.NIOSequentialFileFactory; import org.apache.activemq.artemis.tests.unit.UnitTestLogger; -public class NIOJournalImplTest extends JournalImplTestUnit -{ +public class NIOJournalImplTest extends JournalImplTestUnit { + private static final UnitTestLogger log = UnitTestLogger.LOGGER; @Override - protected SequentialFileFactory getFileFactory() throws Exception - { + protected SequentialFileFactory getFileFactory() throws Exception { File file = new File(getTemporaryDir()); return new NIOSequentialFileFactory(file, 1); diff --git a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/server/impl/QueueConcurrentTest.java b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/server/impl/QueueConcurrentTest.java index ef07209379..deb32b5481 100644 --- a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/server/impl/QueueConcurrentTest.java +++ b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/server/impl/QueueConcurrentTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.timing.core.server.impl; + import java.util.ArrayList; import java.util.List; @@ -33,29 +34,26 @@ import org.junit.Before; import org.junit.Test; /** - * * A concurrent QueueTest * * All the concurrent queue tests go in here */ -public class QueueConcurrentTest extends ActiveMQTestBase -{ +public class QueueConcurrentTest extends ActiveMQTestBase { + private static final UnitTestLogger log = UnitTestLogger.LOGGER; private FakeQueueFactory queueFactory = new FakeQueueFactory(); @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); queueFactory = new FakeQueueFactory(); } @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { queueFactory.stop(); super.tearDown(); } @@ -64,17 +62,8 @@ public class QueueConcurrentTest extends ActiveMQTestBase * Concurrent set consumer not busy, busy then, call deliver while messages are being added and consumed */ @Test - public void testConcurrentAddsDeliver() throws Exception - { - QueueImpl queue = (QueueImpl)queueFactory.createQueue(1, - new SimpleString("address1"), - new SimpleString("queue1"), - null, - null, - null, - false, - false, - false); + public void testConcurrentAddsDeliver() throws Exception { + QueueImpl queue = (QueueImpl) queueFactory.createQueue(1, new SimpleString("address1"), new SimpleString("queue1"), null, null, null, false, false, false); FakeConsumer consumer = new FakeConsumer(); @@ -98,13 +87,11 @@ public class QueueConcurrentTest extends ActiveMQTestBase queue.deliverNow(); - if (sender.getException() != null) - { + if (sender.getException() != null) { throw sender.getException(); } - if (toggler.getException() != null) - { + if (toggler.getException() != null) { throw toggler.getException(); } @@ -118,8 +105,8 @@ public class QueueConcurrentTest extends ActiveMQTestBase // Inner classes --------------------------------------------------------------- - class Sender extends Thread - { + class Sender extends Thread { + private volatile Exception e; private final Queue queue; @@ -128,32 +115,27 @@ public class QueueConcurrentTest extends ActiveMQTestBase private int i; - public Exception getException() - { + public Exception getException() { return e; } private final List refs = new ArrayList(); - public List getReferences() - { + public List getReferences() { return refs; } - Sender(final Queue queue, final long testTime) - { + Sender(final Queue queue, final long testTime) { this.testTime = testTime; this.queue = queue; } @Override - public void run() - { + public void run() { long start = System.currentTimeMillis(); - while (System.currentTimeMillis() - start < testTime) - { + while (System.currentTimeMillis() - start < testTime) { ServerMessage message = generateMessage(i); MessageReference ref = message.createReference(queue); @@ -167,8 +149,8 @@ public class QueueConcurrentTest extends ActiveMQTestBase } } - class Toggler extends Thread - { + class Toggler extends Thread { + private volatile Exception e; private final QueueImpl queue; @@ -181,18 +163,15 @@ public class QueueConcurrentTest extends ActiveMQTestBase private int numToggles; - public int getNumToggles() - { + public int getNumToggles() { return numToggles; } - public Exception getException() - { + public Exception getException() { return e; } - Toggler(final QueueImpl queue, final FakeConsumer consumer, final long testTime) - { + Toggler(final QueueImpl queue, final FakeConsumer consumer, final long testTime) { this.testTime = testTime; this.queue = queue; @@ -201,18 +180,14 @@ public class QueueConcurrentTest extends ActiveMQTestBase } @Override - public void run() - { + public void run() { long start = System.currentTimeMillis(); - while (System.currentTimeMillis() - start < testTime) - { - if (toggle) - { + while (System.currentTimeMillis() - start < testTime) { + if (toggle) { consumer.setStatusImmediate(HandleStatus.BUSY); } - else - { + else { consumer.setStatusImmediate(HandleStatus.HANDLED); queue.deliverNow(); diff --git a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/server/impl/QueueImplTest.java b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/server/impl/QueueImplTest.java index fa2f841a05..a2120e81e9 100644 --- a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/server/impl/QueueImplTest.java +++ b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/server/impl/QueueImplTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.timing.core.server.impl; + import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Before; import org.junit.After; @@ -38,8 +39,8 @@ import org.apache.activemq.artemis.core.server.MessageReference; import org.apache.activemq.artemis.core.server.impl.QueueImpl; import org.apache.activemq.artemis.tests.unit.core.server.impl.fakes.FakeConsumer; -public class QueueImplTest extends ActiveMQTestBase -{ +public class QueueImplTest extends ActiveMQTestBase { + private static final SimpleString queue1 = new SimpleString("queue1"); private static final long TIMEOUT = 10000; @@ -50,8 +51,7 @@ public class QueueImplTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); scheduledExecutor = new ScheduledThreadPoolExecutor(1); @@ -59,8 +59,7 @@ public class QueueImplTest extends ActiveMQTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { scheduledExecutor.shutdownNow(); super.tearDown(); @@ -69,21 +68,8 @@ public class QueueImplTest extends ActiveMQTestBase // The tests ---------------------------------------------------------------- @Test - public void testScheduledNoConsumer() throws Exception - { - QueueImpl queue = new QueueImpl(1, - new SimpleString("address1"), - new SimpleString("queue1"), - null, - null, - false, - true, - false, - scheduledExecutor, - null, - null, - null, - Executors.newSingleThreadExecutor()); + public void testScheduledNoConsumer() throws Exception { + QueueImpl queue = new QueueImpl(1, new SimpleString("address1"), new SimpleString("queue1"), null, null, false, true, false, scheduledExecutor, null, null, null, Executors.newSingleThreadExecutor()); // Send one scheduled @@ -147,25 +133,11 @@ public class QueueImplTest extends ActiveMQTestBase } @Test - public void testScheduled() throws Exception - { - QueueImpl queue = new QueueImpl(1, - new SimpleString("address1"), - new SimpleString("queue1"), - null, - null, - false, - true, - false, - scheduledExecutor, - null, - null, - null, - Executors.newSingleThreadExecutor()); + public void testScheduled() throws Exception { + QueueImpl queue = new QueueImpl(1, new SimpleString("address1"), new SimpleString("queue1"), null, null, false, true, false, scheduledExecutor, null, null, null, Executors.newSingleThreadExecutor()); FakeConsumer consumer = null; - // Send one scheduled long now = System.currentTimeMillis(); @@ -207,7 +179,6 @@ public class QueueImplTest extends ActiveMQTestBase queue.deliverNow(); - List refs = new ArrayList(); refs.add(ref2); @@ -248,36 +219,20 @@ public class QueueImplTest extends ActiveMQTestBase } @Test - public void testDeliveryScheduled() throws Exception - { + public void testDeliveryScheduled() throws Exception { final CountDownLatch countDownLatch = new CountDownLatch(1); - Consumer consumer = new FakeConsumer() - { + Consumer consumer = new FakeConsumer() { @Override - public synchronized HandleStatus handle(final MessageReference reference) - { + public synchronized HandleStatus handle(final MessageReference reference) { countDownLatch.countDown(); return HandleStatus.HANDLED; } @Override - public void disconnect() - { + public void disconnect() { } }; - QueueImpl queue = new QueueImpl(1, - new SimpleString("address1"), - QueueImplTest.queue1, - null, - null, - false, - true, - false, - scheduledExecutor, - null, - null, - null, - Executors.newSingleThreadExecutor()); + QueueImpl queue = new QueueImpl(1, new SimpleString("address1"), QueueImplTest.queue1, null, null, false, true, false, scheduledExecutor, null, null, null, Executors.newSingleThreadExecutor()); MessageReference messageReference = generateReference(queue, 1); queue.addConsumer(consumer); messageReference.setScheduledDeliveryTime(System.currentTimeMillis() + 2000); diff --git a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/jms/bridge/impl/JMSBridgeImplTest.java b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/jms/bridge/impl/JMSBridgeImplTest.java index efe2815eaa..9e9fd09267 100644 --- a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/jms/bridge/impl/JMSBridgeImplTest.java +++ b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/jms/bridge/impl/JMSBridgeImplTest.java @@ -70,8 +70,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; -public class JMSBridgeImplTest extends ActiveMQTestBase -{ +public class JMSBridgeImplTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- private static final UnitTestLogger log = UnitTestLogger.LOGGER; @@ -89,82 +88,57 @@ public class JMSBridgeImplTest extends ActiveMQTestBase // Static -------------------------------------------------------- - protected static TransactionManager newTransactionManager() - { - return new TransactionManager() - { - public Transaction suspend() throws SystemException - { + protected static TransactionManager newTransactionManager() { + return new TransactionManager() { + public Transaction suspend() throws SystemException { return null; } - public void setTransactionTimeout(final int arg0) throws SystemException - { + public void setTransactionTimeout(final int arg0) throws SystemException { } - public void setRollbackOnly() throws IllegalStateException, SystemException - { + public void setRollbackOnly() throws IllegalStateException, SystemException { } - public void rollback() throws IllegalStateException, SecurityException, SystemException - { + public void rollback() throws IllegalStateException, SecurityException, SystemException { } - public void resume(final Transaction arg0) throws InvalidTransactionException, - IllegalStateException, - SystemException - { + public void resume(final Transaction arg0) throws InvalidTransactionException, IllegalStateException, SystemException { } - public Transaction getTransaction() throws SystemException - { + public Transaction getTransaction() throws SystemException { return null; } - public int getStatus() throws SystemException - { + public int getStatus() throws SystemException { return 0; } - public void commit() throws RollbackException, - HeuristicMixedException, - HeuristicRollbackException, - SecurityException, - IllegalStateException, - SystemException - { + public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException { } - public void begin() throws NotSupportedException, SystemException - { + public void begin() throws NotSupportedException, SystemException { } }; } - private static DestinationFactory newDestinationFactory(final Destination dest) - { - return new DestinationFactory() - { - public Destination createDestination() throws Exception - { + private static DestinationFactory newDestinationFactory(final Destination dest) { + return new DestinationFactory() { + public Destination createDestination() throws Exception { return dest; } }; } - private static ConnectionFactoryFactory newConnectionFactoryFactory(final ConnectionFactory cf) - { - return new ConnectionFactoryFactory() - { - public ConnectionFactory createConnectionFactory() throws Exception - { + private static ConnectionFactoryFactory newConnectionFactoryFactory(final ConnectionFactory cf) { + return new ConnectionFactoryFactory() { + public ConnectionFactory createConnectionFactory() throws Exception { return cf; } }; } - private static ConnectionFactory createConnectionFactory() - { + private static ConnectionFactory createConnectionFactory() { ActiveMQJMSConnectionFactory cf = (ActiveMQJMSConnectionFactory) ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(InVMConnectorFactory.class.getName())); // Note! We disable automatic reconnection on the session factory. The bridge needs to do the reconnection @@ -179,15 +153,12 @@ public class JMSBridgeImplTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testStartWithRepeatedFailure() throws Exception - { - ActiveMQJMSConnectionFactory failingSourceCF = new ActiveMQJMSConnectionFactory(false, new TransportConfiguration(InVMConnectorFactory.class.getName())) - { + public void testStartWithRepeatedFailure() throws Exception { + ActiveMQJMSConnectionFactory failingSourceCF = new ActiveMQJMSConnectionFactory(false, new TransportConfiguration(InVMConnectorFactory.class.getName())) { private static final long serialVersionUID = 2834937512213001068L; @Override - public Connection createConnection() throws JMSException - { + public Connection createConnection() throws JMSException { throw new JMSException("unable to create a conn"); } }; @@ -225,23 +196,18 @@ public class JMSBridgeImplTest extends ActiveMQTestBase } @Test - public void testStartWithFailureThenSuccess() throws Exception - { - ActiveMQJMSConnectionFactory failingSourceCF = new ActiveMQJMSConnectionFactory(false, new TransportConfiguration(InVMConnectorFactory.class.getName())) - { + public void testStartWithFailureThenSuccess() throws Exception { + ActiveMQJMSConnectionFactory failingSourceCF = new ActiveMQJMSConnectionFactory(false, new TransportConfiguration(InVMConnectorFactory.class.getName())) { private static final long serialVersionUID = 4657153922210359725L; boolean firstTime = true; @Override - public Connection createConnection() throws JMSException - { - if (firstTime) - { + public Connection createConnection() throws JMSException { + if (firstTime) { firstTime = false; throw new JMSException("unable to create a conn"); } - else - { + else { return super.createConnection(); } } @@ -287,8 +253,7 @@ public class JMSBridgeImplTest extends ActiveMQTestBase * expires even if the maxBatchSize is not reached */ @Test - public void testSendMessagesWhenMaxBatchTimeExpires() throws Exception - { + public void testSendMessagesWhenMaxBatchTimeExpires() throws Exception { int maxBatchSize = 2; long maxBatchTime = 500; @@ -320,11 +285,9 @@ public class JMSBridgeImplTest extends ActiveMQTestBase Session targetSess = targetConn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = targetSess.createConsumer(targetDF.createDestination()); final List messages = new LinkedList(); - MessageListener listener = new MessageListener() - { + MessageListener listener = new MessageListener() { - public void onMessage(final Message message) - { + public void onMessage(final Message message) { messages.add(message); } }; @@ -349,8 +312,7 @@ public class JMSBridgeImplTest extends ActiveMQTestBase } @Test - public void testSendMessagesWithMaxBatchSize() throws Exception - { + public void testSendMessagesWithMaxBatchSize() throws Exception { final int numMessages = 10; ConnectionFactoryFactory sourceCFF = JMSBridgeImplTest.newConnectionFactoryFactory(JMSBridgeImplTest.createConnectionFactory()); @@ -382,10 +344,8 @@ public class JMSBridgeImplTest extends ActiveMQTestBase MessageConsumer consumer = targetSess.createConsumer(targetDF.createDestination()); final List messages = new LinkedList(); final CountDownLatch latch = new CountDownLatch(numMessages); - MessageListener listener = new MessageListener() - { - public void onMessage(final Message message) - { + MessageListener listener = new MessageListener() { + public void onMessage(final Message message) { messages.add(message); latch.countDown(); } @@ -398,8 +358,7 @@ public class JMSBridgeImplTest extends ActiveMQTestBase MessageProducer producer = sourceSess.createProducer(sourceDF.createDestination()); - for (int i = 0; i < numMessages - 1; i++) - { + for (int i = 0; i < numMessages - 1; i++) { TextMessage msg = sourceSess.createTextMessage(); producer.send(msg); JMSBridgeImplTest.log.info("sent message " + i); @@ -426,19 +385,16 @@ public class JMSBridgeImplTest extends ActiveMQTestBase } @Test - public void testAutoAckOnSourceBatchOfOne() throws Exception - { + public void testAutoAckOnSourceBatchOfOne() throws Exception { doTestAutoAckOnSource(1); } @Test - public void testAutoAckOnSourceBatchOfTen() throws Exception - { + public void testAutoAckOnSourceBatchOfTen() throws Exception { doTestAutoAckOnSource(10); } - public void doTestAutoAckOnSource(int maxBatchSize) throws Exception - { + public void doTestAutoAckOnSource(int maxBatchSize) throws Exception { final int numMessages = maxBatchSize; ConnectionFactoryFactory sourceCFF = JMSBridgeImplTest.newConnectionFactoryFactory(JMSBridgeImplTest.createConnectionFactory()); @@ -470,8 +426,7 @@ public class JMSBridgeImplTest extends ActiveMQTestBase MessageProducer producer = sourceSess.createProducer(sourceDF.createDestination()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { TextMessage msg = sourceSess.createTextMessage(); producer.send(msg); JMSBridgeImplTest.log.info("sent message " + i); @@ -479,11 +434,7 @@ public class JMSBridgeImplTest extends ActiveMQTestBase sourceConn.close(); - JMSQueueControl jmsQueueControl = MBeanServerInvocationHandler.newProxyInstance( - ManagementFactory.getPlatformMBeanServer(), - ObjectNameBuilder.DEFAULT.getJMSQueueObjectName(JMSBridgeImplTest.SOURCE), - JMSQueueControl.class, - false); + JMSQueueControl jmsQueueControl = MBeanServerInvocationHandler.newProxyInstance(ManagementFactory.getPlatformMBeanServer(), ObjectNameBuilder.DEFAULT.getJMSQueueObjectName(JMSBridgeImplTest.SOURCE), JMSQueueControl.class, false); assertNotEquals(jmsQueueControl.getDeliveringCount(), numMessages); bridge.stop(); @@ -491,16 +442,13 @@ public class JMSBridgeImplTest extends ActiveMQTestBase } @Test - public void testExceptionOnSourceAndRetrySucceeds() throws Exception - { + public void testExceptionOnSourceAndRetrySucceeds() throws Exception { final AtomicReference sourceConn = new AtomicReference(); - ActiveMQJMSConnectionFactory failingSourceCF = new ActiveMQJMSConnectionFactory(false, new TransportConfiguration(InVMConnectorFactory.class.getName())) - { + ActiveMQJMSConnectionFactory failingSourceCF = new ActiveMQJMSConnectionFactory(false, new TransportConfiguration(InVMConnectorFactory.class.getName())) { private static final long serialVersionUID = -8866390811966688830L; @Override - public Connection createConnection() throws JMSException - { + public Connection createConnection() throws JMSException { sourceConn.set(super.createConnection()); return sourceConn.get(); } @@ -544,30 +492,24 @@ public class JMSBridgeImplTest extends ActiveMQTestBase } @Test - public void testExceptionOnSourceAndRetryFails() throws Exception - { + public void testExceptionOnSourceAndRetryFails() throws Exception { final AtomicReference sourceConn = new AtomicReference(); - ActiveMQJMSConnectionFactory failingSourceCF = - new ActiveMQJMSConnectionFactory(false, new TransportConfiguration(INVM_CONNECTOR_FACTORY)) - { - private static final long serialVersionUID = 8216804886099984645L; - boolean firstTime = true; + ActiveMQJMSConnectionFactory failingSourceCF = new ActiveMQJMSConnectionFactory(false, new TransportConfiguration(INVM_CONNECTOR_FACTORY)) { + private static final long serialVersionUID = 8216804886099984645L; + boolean firstTime = true; - @Override - public Connection createConnection() throws JMSException - { - if (firstTime) - { - firstTime = false; - sourceConn.set(super.createConnection()); - return sourceConn.get(); - } - else - { - throw new JMSException("exception while retrying to connect"); - } + @Override + public Connection createConnection() throws JMSException { + if (firstTime) { + firstTime = false; + sourceConn.set(super.createConnection()); + return sourceConn.get(); } - }; + else { + throw new JMSException("exception while retrying to connect"); + } + } + }; // Note! We disable automatic reconnection on the session factory. The bridge needs to do the reconnection failingSourceCF.setReconnectAttempts(0); failingSourceCF.setBlockOnNonDurableSend(true); @@ -610,12 +552,10 @@ public class JMSBridgeImplTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - Configuration config = createBasicConfig() - .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())); + Configuration config = createBasicConfig().addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())); InVMNamingContext context = new InVMNamingContext(); jmsServer = new JMSServerManagerImpl(addServer(ActiveMQServers.newActiveMQServer(config, false))); jmsServer.setRegistry(new JndiBindingRegistry(context)); @@ -627,8 +567,7 @@ public class JMSBridgeImplTest extends ActiveMQTestBase } @Test - public void testTransactionManagerNotSetForDuplicatesOK() throws Exception - { + public void testTransactionManagerNotSetForDuplicatesOK() throws Exception { ConnectionFactoryFactory sourceCFF = JMSBridgeImplTest.newConnectionFactoryFactory(JMSBridgeImplTest.createConnectionFactory()); ConnectionFactoryFactory targetCFF = JMSBridgeImplTest.newConnectionFactoryFactory(JMSBridgeImplTest.createConnectionFactory()); @@ -660,8 +599,7 @@ public class JMSBridgeImplTest extends ActiveMQTestBase } @Test - public void testThrowErrorWhenTMNotSetForOnceOnly() throws Exception - { + public void testThrowErrorWhenTMNotSetForOnceOnly() throws Exception { thrown.expect(RuntimeException.class); ConnectionFactoryFactory sourceCFF = JMSBridgeImplTest.newConnectionFactoryFactory(JMSBridgeImplTest.createConnectionFactory()); diff --git a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/ReusableLatchTest.java b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/ReusableLatchTest.java index 7b2f3ee2bc..52a6b8a290 100644 --- a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/ReusableLatchTest.java +++ b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/ReusableLatchTest.java @@ -23,11 +23,10 @@ import org.junit.Assert; import org.apache.activemq.artemis.utils.ReusableLatch; -public class ReusableLatchTest extends ActiveMQTestBase -{ +public class ReusableLatchTest extends ActiveMQTestBase { + @Test - public void testTimeout() throws Exception - { + public void testTimeout() throws Exception { ReusableLatch latch = new ReusableLatch(); latch.countUp(); diff --git a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/TokenBucketLimiterImplTest.java b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/TokenBucketLimiterImplTest.java index 2cea80c48b..a3b84264ce 100644 --- a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/TokenBucketLimiterImplTest.java +++ b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/TokenBucketLimiterImplTest.java @@ -26,84 +26,71 @@ import org.apache.activemq.artemis.utils.TokenBucketLimiterImpl; import org.junit.Assert; import org.junit.Test; -public class TokenBucketLimiterImplTest extends ActiveMQTestBase -{ +public class TokenBucketLimiterImplTest extends ActiveMQTestBase { + private static final UnitTestLogger log = UnitTestLogger.LOGGER; @Test - public void testRateWithSpin1() throws Exception - { + public void testRateWithSpin1() throws Exception { testRate(1, true); } @Test - public void testRateWithSpin10() throws Exception - { + public void testRateWithSpin10() throws Exception { testRate(10, true); } @Test - public void testRateWithSpin100() throws Exception - { + public void testRateWithSpin100() throws Exception { testRate(100, true); } @Test - public void testRateWithSpin1000() throws Exception - { + public void testRateWithSpin1000() throws Exception { testRate(1000, true); } @Test - public void testRateWithSpin10000() throws Exception - { + public void testRateWithSpin10000() throws Exception { testRate(10000, true); } @Test - public void testRateWithSpin100000() throws Exception - { + public void testRateWithSpin100000() throws Exception { testRate(100000, true); } @Test - public void testRateWithoutSpin1() throws Exception - { + public void testRateWithoutSpin1() throws Exception { testRate(1, false); } @Test - public void testRateWithoutSpin10() throws Exception - { + public void testRateWithoutSpin10() throws Exception { testRate(10, false); } @Test - public void testRateWithoutSpin100() throws Exception - { + public void testRateWithoutSpin100() throws Exception { testRate(100, false); } @Test - public void testRateWithoutSpin1000() throws Exception - { + public void testRateWithoutSpin1000() throws Exception { testRate(1000, false); } @Test - public void testRateWithoutSpin10000() throws Exception - { + public void testRateWithoutSpin10000() throws Exception { testRate(10000, false); } @Test - public void testRateWithoutSpin100000() throws Exception - { + public void testRateWithoutSpin100000() throws Exception { testRate(100000, false); } - private void testRate(final int rate, final boolean spin) throws Exception - { + private void testRate(final int rate, final boolean spin) throws Exception { final double error = 0.05; // Allow for 5% error TokenBucketLimiterImpl tbl = new TokenBucketLimiterImpl(rate, spin); @@ -115,20 +102,17 @@ public class TokenBucketLimiterImplTest extends ActiveMQTestBase final long measureTime = 5000; // Do some initial testing .. to ramp up the calculations - while (System.currentTimeMillis() - start < measureTime) - { + while (System.currentTimeMillis() - start < measureTime) { tbl.limit(); } // wait some time Thread.sleep(2000); - // start measuring again start = System.currentTimeMillis(); - while (System.currentTimeMillis() - start < measureTime) - { + while (System.currentTimeMillis() - start < measureTime) { tbl.limit(); // when using a low rate (1 for instance), the very last could come after or very close to 5 seconds @@ -138,8 +122,7 @@ public class TokenBucketLimiterImplTest extends ActiveMQTestBase long end = System.currentTimeMillis(); - if (rate == 1) - { + if (rate == 1) { // in 5 seconds you may get exactly 6 buckets.. // Count... 1, 2, 3, 4, 5, 6 // Time.... 0, 1, 2, 3, 4, 5 @@ -148,8 +131,7 @@ public class TokenBucketLimiterImplTest extends ActiveMQTestBase Assert.assertTrue(count == 5 || count == 6); } - else - { + else { double actualRate = (double) (1000 * count) / measureTime; Assert.assertTrue("actual rate = " + actualRate + " expected=" + rate, actualRate > rate * (1 - error)); @@ -159,32 +141,26 @@ public class TokenBucketLimiterImplTest extends ActiveMQTestBase } @Test - public void testVerifyMaxRate1() throws Exception - { + public void testVerifyMaxRate1() throws Exception { testVerifyRate(1, 1, 5000); } @Test - public void testVerifyMaxRate5() throws Exception - { + public void testVerifyMaxRate5() throws Exception { testVerifyRate(5, 1, 5000); } @Test - public void testVerifyMaxRate50() throws Exception - { + public void testVerifyMaxRate50() throws Exception { testVerifyRate(50, 1, 5000); } @Test - public void testVerifyMaxRate50_per_5seconds() throws Exception - { + public void testVerifyMaxRate50_per_5seconds() throws Exception { testVerifyRate(50, 5, 20000); } - - public void testVerifyRate(final int rate, final int window, final int timeRunning) throws Exception - { + public void testVerifyRate(final int rate, final int window, final int timeRunning) throws Exception { final double error = 1.05; // Allow for 5% error final AtomicBoolean running = new AtomicBoolean(true); @@ -195,28 +171,22 @@ public class TokenBucketLimiterImplTest extends ActiveMQTestBase TokenBucketLimiterImpl tbl = new TokenBucketLimiterImpl(rate, false, TimeUnit.SECONDS, window); - Thread t = new Thread() - { - public void run() - { + Thread t = new Thread() { + public void run() { int lastRun = 0; long lastTime = System.currentTimeMillis(); - while (running.get()) - { + while (running.get()) { int tmpValue = iterations.get(); - if (lastRun != 0) - { + if (lastRun != 0) { int consumed = tmpValue - lastRun; double calculatedRate = consumed * window * 1000 / ((System.currentTimeMillis() - lastTime)); - if (calculatedRate > rate * error) - { + if (calculatedRate > rate * error) { System.out.println("got more than " + rate + " tokens / second"); rateError.set(true); } - else if (calculatedRate > rate) - { + else if (calculatedRate > rate) { System.out.println("got more than " + rate + " tokens / second but still on the error marging" + "make sure it's ok though, if you see to many of this message it's an issue"); } @@ -224,12 +194,10 @@ public class TokenBucketLimiterImplTest extends ActiveMQTestBase } lastTime = System.currentTimeMillis(); lastRun = tmpValue; - try - { + try { Thread.sleep(window * 1000); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -238,14 +206,11 @@ public class TokenBucketLimiterImplTest extends ActiveMQTestBase t.start(); - long timeout; timeout = System.currentTimeMillis() + 3000; - - while (timeout > System.currentTimeMillis()) - { + while (timeout > System.currentTimeMillis()) { tbl.limit(); iterations.incrementAndGet(); } @@ -254,14 +219,11 @@ public class TokenBucketLimiterImplTest extends ActiveMQTestBase timeout = System.currentTimeMillis() + timeRunning; - - while (timeout > System.currentTimeMillis()) - { + while (timeout > System.currentTimeMillis()) { tbl.limit(); iterations.incrementAndGet(); } - running.set(false); t.join(); diff --git a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/UTF8Test.java b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/UTF8Test.java index 3996e32e26..244c04c204 100644 --- a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/UTF8Test.java +++ b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/UTF8Test.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.timing.util; + import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.ActiveMQBuffers; import org.junit.After; @@ -26,35 +27,23 @@ import org.junit.Assert; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.UTF8Util; -public class UTF8Test extends ActiveMQTestBase -{ +public class UTF8Test extends ActiveMQTestBase { - private final String str = "abcdef&^*&!^ghijkl\uB5E2\uCAC7\uB2BB\uB7DD\uB7C7\uB3A3\uBCE4\uB5A5" + "abcdef&^*&!^ghijkl\uB5E2\uCAC7\uB2BB\uB7DD\uB7C7\uB3A3\uBCE4\uB5A5" - + "abcdef&^*&!^ghijkl\uB5E2\uCAC7\uB2BB\uB7DD\uB7C7\uB3A3\uBCE4\uB5A5" - + "abcdef&^*&!^ghijkl\uB5E2\uCAC7\uB2BB\uB7DD\uB7C7\uB3A3\uBCE4\uB5A5" - + "abcdef&^*&!^ghijkl\uB5E2\uCAC7\uB2BB\uB7DD\uB7C7\uB3A3\uBCE4\uB5A5" - + "abcdef&^*&!^ghijkl\uB5E2\uCAC7\uB2BB\uB7DD\uB7C7\uB3A3\uBCE4\uB5A5" - + "abcdef&^*&!^ghijkl\uB5E2\uCAC7\uB2BB\uB7DD\uB7C7\uB3A3\uBCE4\uB5A5" - + "abcdef&^*&!^ghijkl\uB5E2\uCAC7\uB2BB\uB7DD\uB7C7\uB3A3\uBCE4\uB5A5" - + "abcdef&^*&!^ghijkl\uB5E2\uCAC7\uB2BB\uB7DD\uB7C7\uB3A3\uBCE4\uB5A5"; + private final String str = "abcdef&^*&!^ghijkl\uB5E2\uCAC7\uB2BB\uB7DD\uB7C7\uB3A3\uBCE4\uB5A5" + "abcdef&^*&!^ghijkl\uB5E2\uCAC7\uB2BB\uB7DD\uB7C7\uB3A3\uBCE4\uB5A5" + "abcdef&^*&!^ghijkl\uB5E2\uCAC7\uB2BB\uB7DD\uB7C7\uB3A3\uBCE4\uB5A5" + "abcdef&^*&!^ghijkl\uB5E2\uCAC7\uB2BB\uB7DD\uB7C7\uB3A3\uBCE4\uB5A5" + "abcdef&^*&!^ghijkl\uB5E2\uCAC7\uB2BB\uB7DD\uB7C7\uB3A3\uBCE4\uB5A5" + "abcdef&^*&!^ghijkl\uB5E2\uCAC7\uB2BB\uB7DD\uB7C7\uB3A3\uBCE4\uB5A5" + "abcdef&^*&!^ghijkl\uB5E2\uCAC7\uB2BB\uB7DD\uB7C7\uB3A3\uBCE4\uB5A5" + "abcdef&^*&!^ghijkl\uB5E2\uCAC7\uB2BB\uB7DD\uB7C7\uB3A3\uBCE4\uB5A5" + "abcdef&^*&!^ghijkl\uB5E2\uCAC7\uB2BB\uB7DD\uB7C7\uB3A3\uBCE4\uB5A5"; final int TIMES = 5; final long numberOfIteractions = 1000000; @Test - public void testWriteUTF() throws Exception - { + public void testWriteUTF() throws Exception { ActiveMQBuffer buffer = ActiveMQBuffers.fixedBuffer(10 * 1024); long start = System.currentTimeMillis(); - for (int c = 0; c < TIMES; c++) - { - for (long i = 0; i < numberOfIteractions; i++) - { - if (i == 10000) - { + for (int c = 0; c < TIMES; c++) { + for (long i = 0; i < numberOfIteractions; i++) { + if (i == 10000) { start = System.currentTimeMillis(); } @@ -69,20 +58,16 @@ public class UTF8Test extends ActiveMQTestBase } @Test - public void testReadUTF() throws Exception - { + public void testReadUTF() throws Exception { ActiveMQBuffer buffer = ActiveMQBuffers.fixedBuffer(10 * 1024); buffer.writeUTF(str); long start = System.currentTimeMillis(); - for (int c = 0; c < TIMES; c++) - { - for (long i = 0; i < numberOfIteractions; i++) - { - if (i == 10000) - { + for (int c = 0; c < TIMES; c++) { + for (long i = 0; i < numberOfIteractions; i++) { + if (i == 10000) { start = System.currentTimeMillis(); } @@ -100,8 +85,7 @@ public class UTF8Test extends ActiveMQTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { UTF8Util.clearBuffer(); super.tearDown(); } diff --git a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/UUIDTest.java b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/UUIDTest.java index 4cf65095f3..dc53f85e82 100644 --- a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/UUIDTest.java +++ b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/UUIDTest.java @@ -18,8 +18,7 @@ package org.apache.activemq.artemis.tests.timing.util; import org.apache.activemq.artemis.utils.UUIDGenerator; -public class UUIDTest extends org.apache.activemq.artemis.tests.unit.util.UUIDTest -{ +public class UUIDTest extends org.apache.activemq.artemis.tests.unit.util.UUIDTest { // Constants ----------------------------------------------------- @@ -27,12 +26,10 @@ public class UUIDTest extends org.apache.activemq.artemis.tests.unit.util.UUIDTe // Static -------------------------------------------------------- - public static void main(String[] args) - { + public static void main(String[] args) { long start = System.currentTimeMillis(); int count = 10000; - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { // System.out.println(i + " " + UUIDGenerator.asString(UUIDGenerator.getHardwareAddress())); byte[] address = UUIDGenerator.getHardwareAddress(); } @@ -41,8 +38,7 @@ public class UUIDTest extends org.apache.activemq.artemis.tests.unit.util.UUIDTe } @Override - protected int getTimes() - { + protected int getTimes() { return 1000000; } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/UnitTestLogger.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/UnitTestLogger.java index a63c135f6e..68c2e76991 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/UnitTestLogger.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/UnitTestLogger.java @@ -21,8 +21,8 @@ import org.jboss.logging.Logger; import org.jboss.logging.annotations.MessageLogger; @MessageLogger(projectCode = "AMQTEST") -public interface UnitTestLogger extends BasicLogger -{ +public interface UnitTestLogger extends BasicLogger { + /** * The unit test logger. */ diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/asyncio/AIOTestBase.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/asyncio/AIOTestBase.java index adfccaa605..988c1d5e6f 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/asyncio/AIOTestBase.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/asyncio/AIOTestBase.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.unit.core.asyncio; + import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -33,8 +34,7 @@ import org.junit.Before; /** * The base class for AIO Tests */ -public abstract class AIOTestBase extends ActiveMQTestBase -{ +public abstract class AIOTestBase extends ActiveMQTestBase { // The AIO Test must use a local filesystem. Sometimes $HOME is on a NFS on // most enterprise systems @@ -42,44 +42,37 @@ public abstract class AIOTestBase extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - Assert.assertTrue(String.format("libAIO is not loaded on %s %s %s", System.getProperty("os.name"), - System.getProperty("os.arch"), System.getProperty("os.version")), - LibaioContext.isLoaded()); + Assert.assertTrue(String.format("libAIO is not loaded on %s %s %s", System.getProperty("os.name"), System.getProperty("os.arch"), System.getProperty("os.version")), LibaioContext.isLoaded()); } @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { Assert.assertEquals(0, LibaioContext.getTotalMaxIO()); super.tearDown(); } - protected void encodeBufer(final ByteBuffer buffer) - { + protected void encodeBufer(final ByteBuffer buffer) { buffer.clear(); int size = buffer.limit(); - for (int i = 0; i < size - 1; i++) - { - buffer.put((byte)('a' + i % 20)); + for (int i = 0; i < size - 1; i++) { + buffer.put((byte) ('a' + i % 20)); } - buffer.put((byte)'\n'); + buffer.put((byte) '\n'); } - protected void preAlloc(final LibaioFile controller, final long size) throws ActiveMQException - { + protected void preAlloc(final LibaioFile controller, final long size) throws ActiveMQException { controller.fill(size); } - protected static class CountDownCallback implements IOCallback - { + protected static class CountDownCallback implements IOCallback { + private final CountDownLatch latch; private final List outputList; @@ -91,8 +84,7 @@ public abstract class AIOTestBase extends ActiveMQTestBase public CountDownCallback(final CountDownLatch latch, final AtomicInteger errors, final List outputList, - final int order) - { + final int order) { this.latch = latch; this.outputList = outputList; @@ -108,45 +100,36 @@ public abstract class AIOTestBase extends ActiveMQTestBase final AtomicInteger timesDoneCalled = new AtomicInteger(0); - public void done() - { - if (outputList != null) - { + public void done() { + if (outputList != null) { outputList.add(order); } doneCalled = true; timesDoneCalled.incrementAndGet(); - if (latch != null) - { + if (latch != null) { latch.countDown(); } } - public void onError(final int errorCode, final String errorMessage) - { + public void onError(final int errorCode, final String errorMessage) { errorCalled++; - if (outputList != null) - { + if (outputList != null) { outputList.add(order); } - if (errors != null) - { + if (errors != null) { errors.incrementAndGet(); } - if (latch != null) - { + if (latch != null) { // even thought an error happened, we need to inform the latch, // or the test won't finish latch.countDown(); } } - public static void checkResults(final int numberOfElements, final ArrayList result) - { + public static void checkResults(final int numberOfElements, final ArrayList result) { Assert.assertEquals(numberOfElements, result.size()); int i = 0; - for (Integer resultI : result) - { + for (Integer resultI : result) { Assert.assertEquals(i++, resultI.intValue()); } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/asyncio/MultiThreadAsynchronousFileTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/asyncio/MultiThreadAsynchronousFileTest.java index c9d3ce4280..469d2a2639 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/asyncio/MultiThreadAsynchronousFileTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/asyncio/MultiThreadAsynchronousFileTest.java @@ -43,11 +43,10 @@ import java.util.concurrent.atomic.AtomicInteger; * II - Find the class on the list (you will find it if you already tried running this testcase before) * III - Add -Djava.library.path=/native/src/.libs */ -public class MultiThreadAsynchronousFileTest extends AIOTestBase -{ +public class MultiThreadAsynchronousFileTest extends AIOTestBase { + @BeforeClass - public static void hasAIO() - { + public static void hasAIO() { org.junit.Assume.assumeTrue("Test case needs AIO to run", AIOSequentialFileFactory.isSupported()); } @@ -63,53 +62,45 @@ public class MultiThreadAsynchronousFileTest extends AIOTestBase ExecutorService pollerExecutor; - private static void debug(final String msg) - { + private static void debug(final String msg) { UnitTestLogger.LOGGER.info(msg); } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - pollerExecutor = Executors.newCachedThreadPool(new ActiveMQThreadFactory("ActiveMQ-AIO-poller-pool" + System.identityHashCode(this), - false, this.getClass().getClassLoader())); + pollerExecutor = Executors.newCachedThreadPool(new ActiveMQThreadFactory("ActiveMQ-AIO-poller-pool" + System.identityHashCode(this), false, this.getClass().getClassLoader())); executor = Executors.newSingleThreadExecutor(); } @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { executor.shutdown(); pollerExecutor.shutdown(); super.tearDown(); } @Test - public void testMultipleASynchronousWrites() throws Throwable - { + public void testMultipleASynchronousWrites() throws Throwable { executeTest(false); } @Test - public void testMultipleSynchronousWrites() throws Throwable - { + public void testMultipleSynchronousWrites() throws Throwable { executeTest(true); } - private void executeTest(final boolean sync) throws Throwable - { + private void executeTest(final boolean sync) throws Throwable { MultiThreadAsynchronousFileTest.debug(sync ? "Sync test:" : "Async test"); AIOSequentialFileFactory factory = new AIOSequentialFileFactory(getTestDirfile(), 21000); factory.start(); factory.disableBufferReuse(); - AIOSequentialFile file = (AIOSequentialFile)factory.createSequentialFile(fileName); + AIOSequentialFile file = (AIOSequentialFile) factory.createSequentialFile(fileName); file.open(); - try - { + try { MultiThreadAsynchronousFileTest.debug("Preallocating file"); file.fill(MultiThreadAsynchronousFileTest.NUMBER_OF_THREADS * @@ -119,8 +110,7 @@ public class MultiThreadAsynchronousFileTest extends AIOTestBase CountDownLatch latchStart = new CountDownLatch(MultiThreadAsynchronousFileTest.NUMBER_OF_THREADS + 1); ArrayList list = new ArrayList(MultiThreadAsynchronousFileTest.NUMBER_OF_THREADS); - for (int i = 0; i < MultiThreadAsynchronousFileTest.NUMBER_OF_THREADS; i++) - { + for (int i = 0; i < MultiThreadAsynchronousFileTest.NUMBER_OF_THREADS; i++) { ThreadProducer producer = new ThreadProducer("Thread " + i, latchStart, file, sync); list.add(producer); producer.start(); @@ -131,11 +121,9 @@ public class MultiThreadAsynchronousFileTest extends AIOTestBase long startTime = System.currentTimeMillis(); - for (ThreadProducer producer : list) - { + for (ThreadProducer producer : list) { producer.join(); - if (producer.failed != null) - { + if (producer.failed != null) { throw producer.failed; } } @@ -144,29 +132,25 @@ public class MultiThreadAsynchronousFileTest extends AIOTestBase MultiThreadAsynchronousFileTest.debug((sync ? "Sync result:" : "Async result:") + " Records/Second = " + MultiThreadAsynchronousFileTest.NUMBER_OF_THREADS * MultiThreadAsynchronousFileTest.NUMBER_OF_LINES * - 1000 / - (endTime - startTime) + + 1000 / (endTime - startTime) + " total time = " + (endTime - startTime) + " total number of records = " + - MultiThreadAsynchronousFileTest.NUMBER_OF_THREADS * - MultiThreadAsynchronousFileTest.NUMBER_OF_LINES); + MultiThreadAsynchronousFileTest.NUMBER_OF_THREADS * MultiThreadAsynchronousFileTest.NUMBER_OF_LINES); } - finally - { + finally { file.close(); factory.stop(); } } - private int getNewPosition() - { + private int getNewPosition() { return position.addAndGet(1); } - class ThreadProducer extends Thread - { + class ThreadProducer extends Thread { + Throwable failed = null; CountDownLatch latchStart; @@ -178,8 +162,7 @@ public class MultiThreadAsynchronousFileTest extends AIOTestBase public ThreadProducer(final String name, final CountDownLatch latchStart, final AIOSequentialFile libaio, - final boolean sync) - { + final boolean sync) { super(name); this.latchStart = latchStart; this.libaio = libaio; @@ -187,24 +170,20 @@ public class MultiThreadAsynchronousFileTest extends AIOTestBase } @Override - public void run() - { + public void run() { super.run(); ByteBuffer buffer = null; buffer = LibaioContext.newAlignedBuffer(MultiThreadAsynchronousFileTest.SIZE, 512); - try - { + try { // I'm always reusing the same buffer, as I don't want any noise from // malloc on the measurement // Encoding buffer - MultiThreadAsynchronousFileTest.addString("Thread name=" + Thread.currentThread().getName() + ";" + "\n", - buffer); - for (int local = buffer.position(); local < buffer.capacity() - 1; local++) - { + MultiThreadAsynchronousFileTest.addString("Thread name=" + Thread.currentThread().getName() + ";" + "\n", buffer); + for (int local = buffer.position(); local < buffer.capacity() - 1; local++) { buffer.put((byte) ' '); } buffer.put((byte) '\n'); @@ -214,60 +193,49 @@ public class MultiThreadAsynchronousFileTest extends AIOTestBase CountDownLatch latchFinishThread = null; - if (!sync) - { + if (!sync) { latchFinishThread = new CountDownLatch(MultiThreadAsynchronousFileTest.NUMBER_OF_LINES); } LinkedList list = new LinkedList(); - for (int i = 0; i < MultiThreadAsynchronousFileTest.NUMBER_OF_LINES; i++) - { + for (int i = 0; i < MultiThreadAsynchronousFileTest.NUMBER_OF_LINES; i++) { - if (sync) - { + if (sync) { latchFinishThread = new CountDownLatch(1); } CountDownCallback callback = new CountDownCallback(latchFinishThread, null, null, 0); - if (!sync) - { + if (!sync) { list.add(callback); } addData(libaio, buffer, callback); - if (sync) - { + if (sync) { waitForLatch(latchFinishThread); assertTrue(callback.doneCalled); assertFalse(callback.errorCalled != 0); } } - if (!sync) - { + if (!sync) { waitForLatch(latchFinishThread); } - for (CountDownCallback callback : list) - { + for (CountDownCallback callback : list) { assertTrue(callback.doneCalled); assertFalse(callback.errorCalled != 0); } - for (CountDownCallback callback : list) - { + for (CountDownCallback callback : list) { assertTrue(callback.doneCalled); assertFalse(callback.errorCalled != 0); } } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); failed = e; } - finally - { - synchronized (MultiThreadAsynchronousFileTest.class) - { + finally { + synchronized (MultiThreadAsynchronousFileTest.class) { LibaioContext.freeBuffer(buffer); } } @@ -275,14 +243,14 @@ public class MultiThreadAsynchronousFileTest extends AIOTestBase } } - private static void addString(final String str, final ByteBuffer buffer) - { + private static void addString(final String str, final ByteBuffer buffer) { byte[] bytes = str.getBytes(); buffer.put(bytes); } - private void addData(final AIOSequentialFile aio, final ByteBuffer buffer, final IOCallback callback) throws Exception - { + private void addData(final AIOSequentialFile aio, + final ByteBuffer buffer, + final IOCallback callback) throws Exception { aio.writeDirect(buffer, true, callback); } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/client/impl/LargeMessageBufferTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/client/impl/LargeMessageBufferTest.java index 7c488e82d0..88fb109942 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/client/impl/LargeMessageBufferTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/client/impl/LargeMessageBufferTest.java @@ -51,8 +51,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -public class LargeMessageBufferTest extends ActiveMQTestBase -{ +public class LargeMessageBufferTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -68,8 +67,7 @@ public class LargeMessageBufferTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); tmpFileCounter++; @@ -80,36 +78,29 @@ public class LargeMessageBufferTest extends ActiveMQTestBase // Test Simple getBytes @Test - public void testGetBytes() throws Exception - { + public void testGetBytes() throws Exception { LargeMessageControllerImpl buffer = create15BytesSample(); - for (int i = 1; i <= 15; i++) - { - try - { + for (int i = 1; i <= 15; i++) { + try { Assert.assertEquals(i, buffer.readByte()); } - catch (Exception e) - { + catch (Exception e) { throw new Exception("Exception at position " + i, e); } } - try - { + try { buffer.readByte(); Assert.fail("supposed to throw an exception"); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { } } // Test for void getBytes(final int index, final byte[] dst) @Test - public void testGetBytesIByteArray() throws Exception - { + public void testGetBytesIByteArray() throws Exception { LargeMessageControllerImpl buffer = create15BytesSample(); byte[] bytes = new byte[15]; @@ -117,23 +108,20 @@ public class LargeMessageBufferTest extends ActiveMQTestBase validateAgainstSample(bytes); - try - { + try { buffer = create15BytesSample(); bytes = new byte[16]; buffer.getBytes(0, bytes); Assert.fail("supposed to throw an exception"); } - catch (java.lang.IndexOutOfBoundsException e) - { + catch (java.lang.IndexOutOfBoundsException e) { } } // testing void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) @Test - public void testGetBytesILChannelBufferII() throws Exception - { + public void testGetBytesILChannelBufferII() throws Exception { LargeMessageControllerImpl buffer = create15BytesSample(); ActiveMQBuffer dstBuffer = ActiveMQBuffers.fixedBuffer(20); @@ -150,34 +138,28 @@ public class LargeMessageBufferTest extends ActiveMQTestBase // testing void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) @Test - public void testReadIntegers() throws Exception - { + public void testReadIntegers() throws Exception { LargeMessageControllerImpl buffer = createBufferWithIntegers(3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); - for (int i = 1; i <= 15; i++) - { + for (int i = 1; i <= 15; i++) { Assert.assertEquals(i, buffer.readInt()); } - try - { + try { buffer.readByte(); Assert.fail("supposed to throw an exception"); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { } } @Test - public void testReadIntegersOverStream() throws Exception - { + public void testReadIntegersOverStream() throws Exception { LargeMessageControllerImpl buffer = createBufferWithIntegers(3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); ActiveMQBufferInputStream is = new ActiveMQBufferInputStream(buffer); DataInputStream dataInput = new DataInputStream(is); - for (int i = 1; i <= 15; i++) - { + for (int i = 1; i <= 15; i++) { Assert.assertEquals(i, dataInput.readInt()); } @@ -187,34 +169,28 @@ public class LargeMessageBufferTest extends ActiveMQTestBase // testing void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) @Test - public void testReadLongs() throws Exception - { + public void testReadLongs() throws Exception { LargeMessageControllerImpl buffer = createBufferWithLongs(3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); - for (int i = 1; i <= 15; i++) - { + for (int i = 1; i <= 15; i++) { Assert.assertEquals(i, buffer.readLong()); } - try - { + try { buffer.readByte(); Assert.fail("supposed to throw an exception"); } - catch (IndexOutOfBoundsException e) - { + catch (IndexOutOfBoundsException e) { } } @Test - public void testReadLongsOverStream() throws Exception - { + public void testReadLongsOverStream() throws Exception { LargeMessageControllerImpl buffer = createBufferWithLongs(3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); ActiveMQBufferInputStream is = new ActiveMQBufferInputStream(buffer); DataInputStream dataInput = new DataInputStream(is); - for (int i = 1; i <= 15; i++) - { + for (int i = 1; i <= 15; i++) { Assert.assertEquals(i, dataInput.readLong()); } @@ -223,8 +199,7 @@ public class LargeMessageBufferTest extends ActiveMQTestBase } @Test - public void testReadData() throws Exception - { + public void testReadData() throws Exception { ActiveMQBuffer dynamic = ActiveMQBuffers.dynamicBuffer(1); String str1 = RandomUtil.randomString(); @@ -245,14 +220,12 @@ public class LargeMessageBufferTest extends ActiveMQTestBase Assert.assertEquals(f1, readBuffer.readFloat(), 0.000001); } - private File getTestFile() - { + private File getTestFile() { return new File(getTestDir(), "temp." + tmpFileCounter + ".file"); } @Test - public void testReadDataOverCached() throws Exception - { + public void testReadDataOverCached() throws Exception { clearDataRecreateServerDirs(); ActiveMQBuffer dynamic = ActiveMQBuffers.dynamicBuffer(1); @@ -285,8 +258,7 @@ public class LargeMessageBufferTest extends ActiveMQTestBase } @Test - public void testReadPartialData() throws Exception - { + public void testReadPartialData() throws Exception { final LargeMessageControllerImpl buffer = new LargeMessageControllerImpl(new FakeConsumerInternal(), 10, 10); @@ -295,8 +267,7 @@ public class LargeMessageBufferTest extends ActiveMQTestBase byte[] bytes = new byte[30]; buffer.readBytes(bytes, 0, 5); - for (byte i = 0; i < 5; i++) - { + for (byte i = 0; i < 5; i++) { Assert.assertEquals(i, bytes[i]); } @@ -304,26 +275,20 @@ public class LargeMessageBufferTest extends ActiveMQTestBase final AtomicInteger errorCount = new AtomicInteger(0); - Thread t = new Thread() - { + Thread t = new Thread() { @Override - public void run() - { + public void run() { - try - { + try { latchGo.countDown(); buffer.readBytes(new byte[5]); } - catch (IndexOutOfBoundsException ignored) - { + catch (IndexOutOfBoundsException ignored) { } - catch (IllegalAccessError ignored) - { + catch (IllegalAccessError ignored) { } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); errorCount.incrementAndGet(); } @@ -343,36 +308,26 @@ public class LargeMessageBufferTest extends ActiveMQTestBase } @Test - public void testInterruptData() throws Exception - { + public void testInterruptData() throws Exception { LargeMessageControllerImpl readBuffer = splitBuffer(3, new byte[]{0, 1, 2, 3, 4}); byte[] bytes = new byte[30]; readBuffer.readBytes(bytes, 0, 5); - for (byte i = 0; i < 5; i++) - { + for (byte i = 0; i < 5; i++) { Assert.assertEquals(i, bytes[i]); } } @Test - public void testSplitBufferOnFile() throws Exception - { - LargeMessageControllerImpl outBuffer = new LargeMessageControllerImpl(new FakeConsumerInternal(), - 1024 * 1024, - 1, - getTestFile(), - 1024); - try - { + public void testSplitBufferOnFile() throws Exception { + LargeMessageControllerImpl outBuffer = new LargeMessageControllerImpl(new FakeConsumerInternal(), 1024 * 1024, 1, getTestFile(), 1024); + try { long count = 0; - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { byte[] buffer = new byte[10240]; - for (int j = 0; j < 10240; j++) - { + for (int j = 0; j < 10240; j++) { buffer[j] = getSamplebyte(count++); } outBuffer.addPacket(buffer, 1, true); @@ -380,31 +335,25 @@ public class LargeMessageBufferTest extends ActiveMQTestBase outBuffer.readerIndex(0); - for (int i = 0; i < 10240 * 10; i++) - { + for (int i = 0; i < 10240 * 10; i++) { assertEquals("position " + i, getSamplebyte(i), outBuffer.readByte()); } outBuffer.readerIndex(0); - for (int i = 0; i < 10240 * 10; i++) - { + for (int i = 0; i < 10240 * 10; i++) { assertEquals("position " + i, getSamplebyte(i), outBuffer.readByte()); } } - finally - { + finally { outBuffer.close(); } } @Test - public void testStreamData() throws Exception - { - final LargeMessageControllerImpl outBuffer = new LargeMessageControllerImpl(new FakeConsumerInternal(), - 1024 * 11 + 123, - 1000); + public void testStreamData() throws Exception { + final LargeMessageControllerImpl outBuffer = new LargeMessageControllerImpl(new FakeConsumerInternal(), 1024 * 11 + 123, 1000); final PipedOutputStream output = new PipedOutputStream(); final PipedInputStream input = new PipedInputStream(output); @@ -419,36 +368,28 @@ public class LargeMessageBufferTest extends ActiveMQTestBase final AtomicInteger count = new AtomicInteger(0); final AtomicInteger totalBytes = new AtomicInteger(0); - Thread treader = new Thread("treader") - { + Thread treader = new Thread("treader") { @Override - public void run() - { - try - { + public void run() { + try { byte[] line = new byte[1024]; int dataRead = 0; - while (dataRead >= 0) - { + while (dataRead >= 0) { dataRead = input.read(line); - if (dataRead > 0) - { + if (dataRead > 0) { totalBytes.addAndGet(dataRead); - if (count.incrementAndGet() == 3) - { + if (count.incrementAndGet() == 3) { done1.countDown(); } } } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); errors.incrementAndGet(); } - finally - { + finally { done1.countDown(); done2.countDown(); } @@ -458,8 +399,7 @@ public class LargeMessageBufferTest extends ActiveMQTestBase treader.setDaemon(true); treader.start(); - for (int i = 0; i < 3; i++) - { + for (int i = 0; i < 3; i++) { outBuffer.addPacket(new byte[1024], 1, true); } @@ -467,18 +407,14 @@ public class LargeMessageBufferTest extends ActiveMQTestBase final CountDownLatch waiting = new CountDownLatch(1); - Thread twaiter = new Thread("twaiter") - { + Thread twaiter = new Thread("twaiter") { @Override - public void run() - { - try - { + public void run() { + try { outBuffer.waitCompletion(0); waiting.countDown(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); errors.incrementAndGet(); } @@ -493,8 +429,7 @@ public class LargeMessageBufferTest extends ActiveMQTestBase Assert.assertEquals(3, count.get()); Assert.assertEquals(1024 * 3, totalBytes.get()); - for (int i = 0; i < 8; i++) - { + for (int i = 0; i < 8; i++) { outBuffer.addPacket(new byte[1024], 1, true); } @@ -518,73 +453,58 @@ public class LargeMessageBufferTest extends ActiveMQTestBase } @Test - public void testStreamDataWaitCompletionOnCompleteBuffer() throws Exception - { + public void testStreamDataWaitCompletionOnCompleteBuffer() throws Exception { final LargeMessageControllerImpl outBuffer = create15BytesSample(); - outBuffer.saveBuffer(new OutputStream() - { + outBuffer.saveBuffer(new OutputStream() { @Override - public void write(final int b) throws IOException - { + public void write(final int b) throws IOException { // nohting to be done } }); } @Test - public void testStreamDataWaitCompletionOnInCompleteBuffer() throws Exception - { + public void testStreamDataWaitCompletionOnInCompleteBuffer() throws Exception { final LargeMessageControllerImpl outBuffer = new LargeMessageControllerImpl(new FakeConsumerInternal(), 5, 1000); + class FakeOutputStream extends OutputStream { - class FakeOutputStream extends OutputStream - { @Override - public void write(int b) throws IOException - { + public void write(int b) throws IOException { } } outBuffer.setOutputStream(new FakeOutputStream()); long time = System.currentTimeMillis(); - try - { + try { outBuffer.waitCompletion(0); fail("supposed to throw an exception"); } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { } assertTrue("It was supposed to wait at least 1 second", System.currentTimeMillis() - time > 1000); } - @Test - public void testStreamDataWaitCompletionOnSlowComingBuffer() throws Exception - { + public void testStreamDataWaitCompletionOnSlowComingBuffer() throws Exception { final LargeMessageControllerImpl outBuffer = new LargeMessageControllerImpl(new FakeConsumerInternal(), 5, 1000); + class FakeOutputStream extends OutputStream { - class FakeOutputStream extends OutputStream - { @Override - public void write(int b) throws IOException - { + public void write(int b) throws IOException { } } outBuffer.setOutputStream(new FakeOutputStream()); - Thread sender = new Thread() - { + Thread sender = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { Thread.sleep(100); outBuffer.addPacket(new byte[]{0}, 1, true); Thread.sleep(100); @@ -592,8 +512,7 @@ public class LargeMessageBufferTest extends ActiveMQTestBase Thread.sleep(200); outBuffer.addPacket(new byte[]{0}, 1, false); } - catch (Exception e) - { + catch (Exception e) { } } }; @@ -604,8 +523,7 @@ public class LargeMessageBufferTest extends ActiveMQTestBase } @Test - public void testErrorOnSetStreaming() throws Exception - { + public void testErrorOnSetStreaming() throws Exception { long start = System.currentTimeMillis(); final LargeMessageControllerImpl outBuffer = new LargeMessageControllerImpl(new FakeConsumerInternal(), 5, 30000); @@ -614,11 +532,9 @@ public class LargeMessageBufferTest extends ActiveMQTestBase final CountDownLatch latchBytesWritten1 = new CountDownLatch(5); final CountDownLatch latchBytesWritten2 = new CountDownLatch(10); - outBuffer.setOutputStream(new OutputStream() - { + outBuffer.setOutputStream(new OutputStream() { @Override - public void write(final int b) throws IOException - { + public void write(final int b) throws IOException { latchBytesWritten1.countDown(); latchBytesWritten2.countDown(); } @@ -626,13 +542,11 @@ public class LargeMessageBufferTest extends ActiveMQTestBase ActiveMQTestBase.waitForLatch(latchBytesWritten1); - try - { + try { outBuffer.readByte(); Assert.fail("supposed to throw an exception"); } - catch (IllegalAccessError ignored) - { + catch (IllegalAccessError ignored) { } Assert.assertTrue("It waited too much", System.currentTimeMillis() - start < 30000); @@ -640,11 +554,9 @@ public class LargeMessageBufferTest extends ActiveMQTestBase } @Test - public void testReadBytesOnStreaming() throws Exception - { + public void testReadBytesOnStreaming() throws Exception { byte[] byteArray = new byte[1024]; - for (int i = 0; i < byteArray.length; i++) - { + for (int i = 0; i < byteArray.length; i++) { byteArray[i] = getSamplebyte(i); } @@ -652,19 +564,16 @@ public class LargeMessageBufferTest extends ActiveMQTestBase ActiveMQBufferInputStream is = new ActiveMQBufferInputStream(splitbuffer); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { assertEquals(getSamplebyte(i), (byte) is.read()); } - for (int i = 100; i < byteArray.length; i += 10) - { + for (int i = 100; i < byteArray.length; i += 10) { byte[] readBytes = new byte[10]; int size = is.read(readBytes); - for (int j = 0; j < size; j++) - { + for (int j = 0; j < size; j++) { assertEquals(getSamplebyte(i + j), readBytes[j]); } } @@ -674,65 +583,58 @@ public class LargeMessageBufferTest extends ActiveMQTestBase /** * @return */ - private LargeMessageControllerImpl create15BytesSample() throws Exception - { + private LargeMessageControllerImpl create15BytesSample() throws Exception { return splitBuffer(5, new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}); } - private LargeMessageControllerImpl createBufferWithIntegers(final int splitFactor, final int... values) throws Exception - { + private LargeMessageControllerImpl createBufferWithIntegers(final int splitFactor, + final int... values) throws Exception { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(values.length * 4); DataOutputStream dataOut = new DataOutputStream(byteOut); - for (int value : values) - { + for (int value : values) { dataOut.writeInt(value); } return splitBuffer(splitFactor, byteOut.toByteArray()); } - private LargeMessageControllerImpl createBufferWithLongs(final int splitFactor, final long... values) throws Exception - { + private LargeMessageControllerImpl createBufferWithLongs(final int splitFactor, + final long... values) throws Exception { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(values.length * 8); DataOutputStream dataOut = new DataOutputStream(byteOut); - for (long value : values) - { + for (long value : values) { dataOut.writeLong(value); } return splitBuffer(splitFactor, byteOut.toByteArray()); } - private LargeMessageControllerImpl splitBuffer(final int splitFactor, final byte[] bytes) throws Exception - { + private LargeMessageControllerImpl splitBuffer(final int splitFactor, final byte[] bytes) throws Exception { return splitBuffer(splitFactor, bytes, null); } - private LargeMessageControllerImpl splitBuffer(final int splitFactor, final byte[] bytes, final File file) throws Exception - { + private LargeMessageControllerImpl splitBuffer(final int splitFactor, + final byte[] bytes, + final File file) throws Exception { LargeMessageControllerImpl outBuffer = new LargeMessageControllerImpl(new FakeConsumerInternal(), bytes.length, 5000, file); ByteArrayInputStream input = new ByteArrayInputStream(bytes); - while (true) - { + while (true) { byte[] splitElement = new byte[splitFactor]; int size = input.read(splitElement); - if (size <= 0) - { + if (size <= 0) { break; } - if (size < splitFactor) - { + if (size < splitFactor) { byte[] newSplit = new byte[size]; System.arraycopy(splitElement, 0, newSplit, 0, size); outBuffer.addPacket(newSplit, 1, input.available() > 0); } - else - { + else { outBuffer.addPacket(splitElement, 1, input.available() > 0); } } @@ -744,10 +646,8 @@ public class LargeMessageBufferTest extends ActiveMQTestBase /** * @param bytes */ - private void validateAgainstSample(final byte[] bytes) - { - for (int i = 1; i <= 15; i++) - { + private void validateAgainstSample(final byte[] bytes) { + for (int i = 1; i <= 15; i++) { Assert.assertEquals(i, bytes[i - 1]); } } @@ -760,160 +660,129 @@ public class LargeMessageBufferTest extends ActiveMQTestBase // Inner classes ------------------------------------------------- - static class FakeConsumerInternal implements ClientConsumerInternal - { + static class FakeConsumerInternal implements ClientConsumerInternal { - public ConsumerContext getConsumerContext() - { + public ConsumerContext getConsumerContext() { return new ActiveMQConsumerContext(0); } - - public void close() throws ActiveMQException - { + public void close() throws ActiveMQException { } - public Exception getLastException() - { + public Exception getLastException() { return null; } - public MessageHandler getMessageHandler() throws ActiveMQException - { + public MessageHandler getMessageHandler() throws ActiveMQException { return null; } - public boolean isClosed() - { + public boolean isClosed() { return false; } - public ClientMessage receive() throws ActiveMQException - { + public ClientMessage receive() throws ActiveMQException { return null; } - public ClientMessage receive(final long timeout) throws ActiveMQException - { + public ClientMessage receive(final long timeout) throws ActiveMQException { return null; } - public ClientMessage receiveImmediate() throws ActiveMQException - { + public ClientMessage receiveImmediate() throws ActiveMQException { return null; } - public FakeConsumerInternal setMessageHandler(final MessageHandler handler) throws ActiveMQException - { + public FakeConsumerInternal setMessageHandler(final MessageHandler handler) throws ActiveMQException { return this; } - public void acknowledge(final ClientMessage message) throws ActiveMQException - { + public void acknowledge(final ClientMessage message) throws ActiveMQException { } @Override - public void individualAcknowledge(ClientMessage message) throws ActiveMQException - { + public void individualAcknowledge(ClientMessage message) throws ActiveMQException { } - public void cleanUp() throws ActiveMQException - { + public void cleanUp() throws ActiveMQException { } - public void clear(boolean waitForOnMessage) throws ActiveMQException - { + public void clear(boolean waitForOnMessage) throws ActiveMQException { } - public void clearAtFailover() - { + public void clearAtFailover() { } - public void flowControl(final int messageBytes, final boolean discountSlowConsumer) throws ActiveMQException - { + public void flowControl(final int messageBytes, final boolean discountSlowConsumer) throws ActiveMQException { } - public void flushAcks() throws ActiveMQException - { + public void flushAcks() throws ActiveMQException { } - public int getBufferSize() - { + public int getBufferSize() { return 0; } - public int getClientWindowSize() - { + public int getClientWindowSize() { return 0; } - public SimpleString getFilterString() - { + public SimpleString getFilterString() { return null; } - public long getID() - { + public long getID() { return 0; } - public SimpleString getQueueName() - { + public SimpleString getQueueName() { return null; } - public boolean isBrowseOnly() - { + public boolean isBrowseOnly() { return false; } @Override - public void handleMessage(ClientMessageInternal message) throws Exception - { + public void handleMessage(ClientMessageInternal message) throws Exception { } @Override - public void handleLargeMessage(ClientLargeMessageInternal clientLargeMessage, long largeMessageSize) throws Exception - { + public void handleLargeMessage(ClientLargeMessageInternal clientLargeMessage, + long largeMessageSize) throws Exception { } @Override - public void handleLargeMessageContinuation(byte[] chunk, int flowControlSize, boolean isContinues) throws Exception - { + public void handleLargeMessageContinuation(byte[] chunk, + int flowControlSize, + boolean isContinues) throws Exception { } - public void start() - { - + public void start() { } - public void stop() throws ActiveMQException - { - + public void stop() throws ActiveMQException { } - public void stop(boolean waitForOnMessage) throws ActiveMQException - { + public void stop(boolean waitForOnMessage) throws ActiveMQException { } - public ClientSession.QueueQuery getQueueInfo() - { + public ClientSession.QueueQuery getQueueInfo() { return null; } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.client.impl.ClientConsumerInternal#getNonXAsession() */ - public ClientSessionInternal getSession() - { + public ClientSessionInternal getSession() { return null; } @@ -921,8 +790,7 @@ public class LargeMessageBufferTest extends ActiveMQTestBase /* (non-Javadoc) * @see org.apache.activemq.artemis.core.client.impl.ClientConsumerInternal#prepareForClose() */ - public Thread prepareForClose(FutureLatch future) throws ActiveMQException - { + public Thread prepareForClose(FutureLatch future) throws ActiveMQException { return null; } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/ConfigurationValidationTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/ConfigurationValidationTest.java index e9efd47388..a87c71c008 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/ConfigurationValidationTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/ConfigurationValidationTest.java @@ -26,8 +26,7 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.XMLUtil; import org.w3c.dom.Element; -public class ConfigurationValidationTest extends ActiveMQTestBase -{ +public class ConfigurationValidationTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -44,8 +43,7 @@ public class ConfigurationValidationTest extends ActiveMQTestBase * It runs fine on the CLI with the proper env setting. */ @Test - public void testMinimalConfiguration() throws Exception - { + public void testMinimalConfiguration() throws Exception { String xml = "" + ""; Element element = XMLUtil.stringToElement(xml); Assert.assertNotNull(element); @@ -53,8 +51,7 @@ public class ConfigurationValidationTest extends ActiveMQTestBase } @Test - public void testFullConfiguration() throws Exception - { + public void testFullConfiguration() throws Exception { FileConfiguration fc = new FileConfiguration(); FileDeploymentManager deploymentManager = new FileDeploymentManager("ConfigurationTest-full-config.xml"); deploymentManager.addDeployable(fc); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/ConnectorsServiceTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/ConnectorsServiceTest.java index 518be5b5fe..4ef03ce4fe 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/ConnectorsServiceTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/ConnectorsServiceTest.java @@ -33,15 +33,14 @@ import org.apache.activemq.artemis.tests.unit.core.config.impl.fakes.FakeConnect import org.junit.Before; import org.junit.Test; -public class ConnectorsServiceTest extends ActiveMQTestBase -{ +public class ConnectorsServiceTest extends ActiveMQTestBase { + private Configuration configuration; private ServiceRegistry serviceRegistry; @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { // Setup Configuration configuration = new ConfigurationImpl(); serviceRegistry = new ServiceRegistryImpl(); @@ -49,15 +48,12 @@ public class ConnectorsServiceTest extends ActiveMQTestBase /** * Test that the connectors added via the service registry are added to the connectorsService, + * * @throws Exception */ @Test - public void testConnectorsServiceUsesInjectedConnectorServiceFactory() throws Exception - { - ConnectorServiceConfiguration connectorServiceConfiguration = new ConnectorServiceConfiguration() - .setFactoryClassName(null) - .setParams(new HashMap()) - .setName("myfact"); + public void testConnectorsServiceUsesInjectedConnectorServiceFactory() throws Exception { + ConnectorServiceConfiguration connectorServiceConfiguration = new ConnectorServiceConfiguration().setFactoryClassName(null).setParams(new HashMap()).setName("myfact"); // Creates a fake connector service factory that returns the fake connector service object ConnectorService connectorService = new FakeConnectorService(); @@ -73,15 +69,12 @@ public class ConnectorsServiceTest extends ActiveMQTestBase /** * Test that the connectors added via the config are added to the connectors service. + * * @throws Exception */ @Test - public void testConnectorsServiceUsesConfiguredConnectorServices() throws Exception - { - ConnectorServiceConfiguration connectorServiceConfiguration = new ConnectorServiceConfiguration() - .setFactoryClassName(FakeConnectorServiceFactory.class.getCanonicalName()) - .setParams(new HashMap()) - .setName("myfact"); + public void testConnectorsServiceUsesConfiguredConnectorServices() throws Exception { + ConnectorServiceConfiguration connectorServiceConfiguration = new ConnectorServiceConfiguration().setFactoryClassName(FakeConnectorServiceFactory.class.getCanonicalName()).setParams(new HashMap()).setName("myfact"); List connectorServiceConfigurations = new ArrayList(); connectorServiceConfigurations.add(connectorServiceConfiguration); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/TransportConfigurationTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/TransportConfigurationTest.java index 82b14e2e6f..dccd5c2b47 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/TransportConfigurationTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/TransportConfigurationTest.java @@ -23,8 +23,7 @@ import org.junit.Assert; import org.apache.activemq.artemis.api.core.TransportConfiguration; -public class TransportConfigurationTest extends ActiveMQTestBase -{ +public class TransportConfigurationTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -37,8 +36,7 @@ public class TransportConfigurationTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testSplitNullAddress() throws Exception - { + public void testSplitNullAddress() throws Exception { String[] addresses = TransportConfiguration.splitHosts(null); Assert.assertNotNull(addresses); @@ -46,8 +44,7 @@ public class TransportConfigurationTest extends ActiveMQTestBase } @Test - public void testSplitSingleAddress() throws Exception - { + public void testSplitSingleAddress() throws Exception { String[] addresses = TransportConfiguration.splitHosts("localhost"); Assert.assertNotNull(addresses); @@ -56,8 +53,7 @@ public class TransportConfigurationTest extends ActiveMQTestBase } @Test - public void testSplitManyAddresses() throws Exception - { + public void testSplitManyAddresses() throws Exception { String[] addresses = TransportConfiguration.splitHosts("localhost, 127.0.0.1, 192.168.0.10"); Assert.assertNotNull(addresses); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/fakes/FakeConnectorService.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/fakes/FakeConnectorService.java index 72a4a73b0c..b335c40ac5 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/fakes/FakeConnectorService.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/fakes/FakeConnectorService.java @@ -18,27 +18,23 @@ package org.apache.activemq.artemis.tests.unit.core.config.impl.fakes; import org.apache.activemq.artemis.core.server.ConnectorService; -public class FakeConnectorService implements ConnectorService -{ +public class FakeConnectorService implements ConnectorService { + @Override - public String getName() - { + public String getName() { return null; } @Override - public void start() throws Exception - { + public void start() throws Exception { } @Override - public void stop() throws Exception - { + public void stop() throws Exception { } @Override - public boolean isStarted() - { + public boolean isStarted() { return false; } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/fakes/FakeConnectorServiceFactory.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/fakes/FakeConnectorServiceFactory.java index a88a6f395b..af7b94de4d 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/fakes/FakeConnectorServiceFactory.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/fakes/FakeConnectorServiceFactory.java @@ -26,39 +26,37 @@ import org.apache.activemq.artemis.core.postoffice.PostOffice; import org.apache.activemq.artemis.core.server.ConnectorService; import org.apache.activemq.artemis.core.server.ConnectorServiceFactory; -public class FakeConnectorServiceFactory implements ConnectorServiceFactory -{ +public class FakeConnectorServiceFactory implements ConnectorServiceFactory { + private ConnectorService connectorService; - public FakeConnectorServiceFactory() - { + public FakeConnectorServiceFactory() { this.connectorService = new FakeConnectorService(); } @Override - public ConnectorService createConnectorService(String connectorName, Map configuration, StorageManager storageManager, PostOffice postOffice, ScheduledExecutorService scheduledThreadPool) - { - if (connectorService == null) - { + public ConnectorService createConnectorService(String connectorName, + Map configuration, + StorageManager storageManager, + PostOffice postOffice, + ScheduledExecutorService scheduledThreadPool) { + if (connectorService == null) { return new FakeConnectorService(); } return connectorService; } @Override - public Set getAllowableProperties() - { + public Set getAllowableProperties() { return new HashSet(); } @Override - public Set getRequiredProperties() - { + public Set getRequiredProperties() { return new HashSet(); } - public ConnectorService getConnectorService() - { + public ConnectorService getConnectorService() { return connectorService; } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/AlignedJournalImplTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/AlignedJournalImplTest.java index e08ef556a1..bac9b89f77 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/AlignedJournalImplTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/AlignedJournalImplTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.unit.core.journal.impl; + import org.apache.activemq.artemis.tests.unit.core.journal.impl.fakes.FakeSequentialFileFactory; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Before; @@ -44,34 +45,27 @@ import org.apache.activemq.artemis.core.journal.impl.JournalImpl; import org.apache.activemq.artemis.tests.unit.UnitTestLogger; import org.apache.activemq.artemis.tests.unit.core.journal.impl.fakes.SimpleEncoding; -public class AlignedJournalImplTest extends ActiveMQTestBase -{ +public class AlignedJournalImplTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- - private static final LoaderCallback dummyLoader = new LoaderCallback() - { + private static final LoaderCallback dummyLoader = new LoaderCallback() { - public void addPreparedTransaction(final PreparedTransactionInfo preparedTransaction) - { + public void addPreparedTransaction(final PreparedTransactionInfo preparedTransaction) { } - public void addRecord(final RecordInfo info) - { + public void addRecord(final RecordInfo info) { } - public void deleteRecord(final long id) - { + public void deleteRecord(final long id) { } - public void updateRecord(final RecordInfo info) - { + public void updateRecord(final RecordInfo info) { } public void failedTransaction(final long transactionID, final List records, - final List recordsToDelete) - { + final List recordsToDelete) { } }; @@ -95,8 +89,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase // This test just validates basic alignment on the FakeSequentialFile itself @Test - public void testBasicAlignment() throws Exception - { + public void testBasicAlignment() throws Exception { FakeSequentialFileFactory factory = new FakeSequentialFileFactory(200, true); @@ -104,20 +97,17 @@ public class AlignedJournalImplTest extends ActiveMQTestBase file.open(); - try - { + try { ByteBuffer buffer = ByteBuffer.allocateDirect(200); - for (int i = 0; i < 200; i++) - { - buffer.put(i, (byte)1); + for (int i = 0; i < 200; i++) { + buffer.put(i, (byte) 1); } file.writeDirect(buffer, true); buffer = ByteBuffer.allocate(400); - for (int i = 0; i < 400; i++) - { - buffer.put(i, (byte)2); + for (int i = 0; i < 400; i++) { + buffer.put(i, (byte) 2); } file.writeDirect(buffer, true); @@ -128,47 +118,40 @@ public class AlignedJournalImplTest extends ActiveMQTestBase file.read(buffer); - for (int i = 0; i < 200; i++) - { - Assert.assertEquals((byte)1, buffer.get(i)); + for (int i = 0; i < 200; i++) { + Assert.assertEquals((byte) 1, buffer.get(i)); } - for (int i = 201; i < 600; i++) - { - Assert.assertEquals("Position " + i, (byte)2, buffer.get(i)); + for (int i = 201; i < 600; i++) { + Assert.assertEquals("Position " + i, (byte) 2, buffer.get(i)); } } - catch (Exception ignored) - { + catch (Exception ignored) { } } @Test - public void testInconsistentAlignment() throws Exception - { + public void testInconsistentAlignment() throws Exception { factory = new FakeSequentialFileFactory(512, true); - try - { + try { journalImpl = new JournalImpl(2000, 2, 0, 0, factory, "tt", "tt", 1000); Assert.fail("Expected IllegalArgumentException"); } - catch (IllegalArgumentException ignored) - { + catch (IllegalArgumentException ignored) { // expected } } @Test - public void testSimpleAdd() throws Exception - { + public void testSimpleAdd() throws Exception { final int JOURNAL_SIZE = 1060; setupAndLoadJournal(JOURNAL_SIZE, 10); - journalImpl.appendAddRecord(13, (byte)14, new SimpleEncoding(1, (byte)15), false); + journalImpl.appendAddRecord(13, (byte) 14, new SimpleEncoding(1, (byte) 15), false); journalImpl.forceMoveNextFile(); @@ -189,8 +172,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase } @Test - public void testAppendAndUpdateRecords() throws Exception - { + public void testAppendAndUpdateRecords() throws Exception { final int JOURNAL_SIZE = 1060; @@ -199,20 +181,17 @@ public class AlignedJournalImplTest extends ActiveMQTestBase Assert.assertEquals(0, records.size()); Assert.assertEquals(0, transactions.size()); - for (int i = 0; i < 25; i++) - { + for (int i = 0; i < 25; i++) { byte[] bytes = new byte[5]; - for (int j = 0; j < bytes.length; j++) - { - bytes[j] = (byte)i; + for (int j = 0; j < bytes.length; j++) { + bytes[j] = (byte) i; } - journalImpl.appendAddRecord(i * 100L, (byte)i, bytes, false); + journalImpl.appendAddRecord(i * 100L, (byte) i, bytes, false); } - for (int i = 25; i < 50; i++) - { - EncodingSupport support = new SimpleEncoding(5, (byte)i); - journalImpl.appendAddRecord(i * 100L, (byte)i, support, false); + for (int i = 25; i < 50; i++) { + EncodingSupport support = new SimpleEncoding(5, (byte) i); + journalImpl.appendAddRecord(i * 100L, (byte) i, support, false); } setupAndLoadJournal(JOURNAL_SIZE, 1024); @@ -220,55 +199,46 @@ public class AlignedJournalImplTest extends ActiveMQTestBase Assert.assertEquals(50, records.size()); int i = 0; - for (RecordInfo recordItem : records) - { + for (RecordInfo recordItem : records) { Assert.assertEquals(i * 100L, recordItem.id); Assert.assertEquals(i, recordItem.getUserRecordType()); Assert.assertEquals(5, recordItem.data.length); - for (int j = 0; j < 5; j++) - { - Assert.assertEquals((byte)i, recordItem.data[j]); + for (int j = 0; j < 5; j++) { + Assert.assertEquals((byte) i, recordItem.data[j]); } i++; } - for (i = 40; i < 50; i++) - { + for (i = 40; i < 50; i++) { byte[] bytes = new byte[10]; - for (int j = 0; j < 10; j++) - { - bytes[j] = (byte)'x'; + for (int j = 0; j < 10; j++) { + bytes[j] = (byte) 'x'; } - journalImpl.appendUpdateRecord(i * 100L, (byte)i, bytes, false); + journalImpl.appendUpdateRecord(i * 100L, (byte) i, bytes, false); } setupAndLoadJournal(JOURNAL_SIZE, 1024); i = 0; - for (RecordInfo recordItem : records) - { + for (RecordInfo recordItem : records) { - if (i < 50) - { + if (i < 50) { Assert.assertEquals(i * 100L, recordItem.id); Assert.assertEquals(i, recordItem.getUserRecordType()); Assert.assertEquals(5, recordItem.data.length); - for (int j = 0; j < 5; j++) - { - Assert.assertEquals((byte)i, recordItem.data[j]); + for (int j = 0; j < 5; j++) { + Assert.assertEquals((byte) i, recordItem.data[j]); } } - else - { + else { Assert.assertEquals((i - 10) * 100L, recordItem.id); Assert.assertEquals(i - 10, recordItem.getUserRecordType()); Assert.assertTrue(recordItem.isUpdate); Assert.assertEquals(10, recordItem.data.length); - for (int j = 0; j < 10; j++) - { - Assert.assertEquals((byte)'x', recordItem.data[j]); + for (int j = 0; j < 10; j++) { + Assert.assertEquals((byte) 'x', recordItem.data[j]); } } @@ -280,8 +250,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase } @Test - public void testPartialDelete() throws Exception - { + public void testPartialDelete() throws Exception { final int JOURNAL_SIZE = 10000; setupAndLoadJournal(JOURNAL_SIZE, 100); @@ -298,9 +267,8 @@ public class AlignedJournalImplTest extends ActiveMQTestBase UnitTestLogger.LOGGER.debug("_______________________________"); - for (int i = 0; i < 50; i++) - { - journalImpl.appendAddRecord(i, (byte)1, new SimpleEncoding(1, (byte)'x'), false); + for (int i = 0; i < 50; i++) { + journalImpl.appendAddRecord(i, (byte) 1, new SimpleEncoding(1, (byte) 'x'), false); } journalImpl.forceMoveNextFile(); @@ -311,8 +279,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase Assert.assertEquals(3, factory.listFiles("tt").size()); - for (int i = 10; i < 50; i++) - { + for (int i = 10; i < 50; i++) { journalImpl.appendDeleteRecord(i, false); } @@ -327,8 +294,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase } @Test - public void testAddAndDeleteReclaimWithoutTransactions() throws Exception - { + public void testAddAndDeleteReclaimWithoutTransactions() throws Exception { final int JOURNAL_SIZE = 10000; setupAndLoadJournal(JOURNAL_SIZE, 1); @@ -345,9 +311,8 @@ public class AlignedJournalImplTest extends ActiveMQTestBase UnitTestLogger.LOGGER.debug("_______________________________"); - for (int i = 0; i < 50; i++) - { - journalImpl.appendAddRecord(i, (byte)1, new SimpleEncoding(1, (byte)'x'), false); + for (int i = 0; i < 50; i++) { + journalImpl.appendAddRecord(i, (byte) 1, new SimpleEncoding(1, (byte) 'x'), false); } // as the request to a new file is asynchronous, we need to make sure the @@ -356,14 +321,13 @@ public class AlignedJournalImplTest extends ActiveMQTestBase Assert.assertEquals(2, factory.listFiles("tt").size()); - for (int i = 0; i < 50; i++) - { + for (int i = 0; i < 50; i++) { journalImpl.appendDeleteRecord(i, false); } journalImpl.forceMoveNextFile(); - journalImpl.appendAddRecord(1000, (byte)1, new SimpleEncoding(1, (byte)'x'), false); + journalImpl.appendAddRecord(1000, (byte) 1, new SimpleEncoding(1, (byte) 'x'), false); journalImpl.debugWait(); @@ -392,8 +356,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase } @Test - public void testReloadWithTransaction() throws Exception - { + public void testReloadWithTransaction() throws Exception { final int JOURNAL_SIZE = 2000; setupAndLoadJournal(JOURNAL_SIZE, 100); @@ -401,22 +364,20 @@ public class AlignedJournalImplTest extends ActiveMQTestBase Assert.assertEquals(0, records.size()); Assert.assertEquals(0, transactions.size()); - journalImpl.appendAddRecordTransactional(1, 1, (byte)1, new SimpleEncoding(1, (byte)1)); + journalImpl.appendAddRecordTransactional(1, 1, (byte) 1, new SimpleEncoding(1, (byte) 1)); setupAndLoadJournal(JOURNAL_SIZE, 100); Assert.assertEquals(0, records.size()); Assert.assertEquals(0, transactions.size()); - try - { + try { journalImpl.appendCommitRecord(1L, false); // This was supposed to throw an exception, as the transaction was // forgotten (interrupted by a reload). Assert.fail("Supposed to throw exception"); } - catch (Exception e) - { + catch (Exception e) { UnitTestLogger.LOGGER.warn(e); } @@ -428,8 +389,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase } @Test - public void testReloadWithInterruptedTransaction() throws Exception - { + public void testReloadWithInterruptedTransaction() throws Exception { final int JOURNAL_SIZE = 1100; setupAndLoadJournal(JOURNAL_SIZE, 100); @@ -439,9 +399,8 @@ public class AlignedJournalImplTest extends ActiveMQTestBase Assert.assertEquals(0, records.size()); Assert.assertEquals(0, transactions.size()); - for (int i = 0; i < 10; i++) - { - journalImpl.appendAddRecordTransactional(77L, 1, (byte)1, new SimpleEncoding(1, (byte)1)); + for (int i = 0; i < 10; i++) { + journalImpl.appendAddRecordTransactional(77L, 1, (byte) 1, new SimpleEncoding(1, (byte) 1)); journalImpl.forceMoveNextFile(); } @@ -449,7 +408,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase Assert.assertEquals(12, factory.listFiles("tt").size()); - journalImpl.appendAddRecordTransactional(78L, 1, (byte)1, new SimpleEncoding(1, (byte)1)); + journalImpl.appendAddRecordTransactional(78L, 1, (byte) 1, new SimpleEncoding(1, (byte) 1)); Assert.assertEquals(12, factory.listFiles("tt").size()); @@ -458,22 +417,19 @@ public class AlignedJournalImplTest extends ActiveMQTestBase Assert.assertEquals(0, records.size()); Assert.assertEquals(0, transactions.size()); Assert.assertEquals(2, incompleteTransactions.size()); - Assert.assertEquals((Long)77L, incompleteTransactions.get(0)); - Assert.assertEquals((Long)78L, incompleteTransactions.get(1)); + Assert.assertEquals((Long) 77L, incompleteTransactions.get(0)); + Assert.assertEquals((Long) 78L, incompleteTransactions.get(1)); - try - { + try { journalImpl.appendCommitRecord(77L, false); // This was supposed to throw an exception, as the transaction was // forgotten (interrupted by a reload). Assert.fail("Supposed to throw exception"); } - catch (Exception e) - { + catch (Exception e) { UnitTestLogger.LOGGER.debug("Expected exception " + e, e); } - setupAndLoadJournal(JOURNAL_SIZE, 100); journalImpl.forceMoveNextFile(); @@ -487,8 +443,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase } @Test - public void testReloadWithCompletedTransaction() throws Exception - { + public void testReloadWithCompletedTransaction() throws Exception { final int JOURNAL_SIZE = 2000; setupAndLoadJournal(JOURNAL_SIZE, 100); @@ -496,9 +451,8 @@ public class AlignedJournalImplTest extends ActiveMQTestBase Assert.assertEquals(0, records.size()); Assert.assertEquals(0, transactions.size()); - for (int i = 0; i < 10; i++) - { - journalImpl.appendAddRecordTransactional(1, i, (byte)1, new SimpleEncoding(1, (byte)1)); + for (int i = 0; i < 10; i++) { + journalImpl.appendAddRecordTransactional(1, i, (byte) 1, new SimpleEncoding(1, (byte) 1)); journalImpl.forceMoveNextFile(); } @@ -519,19 +473,18 @@ public class AlignedJournalImplTest extends ActiveMQTestBase Assert.assertEquals(12, factory.listFiles("tt").size()); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { journalImpl.appendDeleteRecordTransactional(2L, i); journalImpl.forceMoveNextFile(); } journalImpl.appendCommitRecord(2L, false); - journalImpl.appendAddRecord(100, (byte)1, new SimpleEncoding(5, (byte)1), false); + journalImpl.appendAddRecord(100, (byte) 1, new SimpleEncoding(5, (byte) 1), false); journalImpl.forceMoveNextFile(); - journalImpl.appendAddRecord(101, (byte)1, new SimpleEncoding(5, (byte)1), false); + journalImpl.appendAddRecord(101, (byte) 1, new SimpleEncoding(5, (byte) 1), false); journalImpl.checkReclaimStatus(); @@ -545,8 +498,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase } @Test - public void testTotalSize() throws Exception - { + public void testTotalSize() throws Exception { final int JOURNAL_SIZE = 2000; setupAndLoadJournal(JOURNAL_SIZE, 100); @@ -554,10 +506,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase Assert.assertEquals(0, records.size()); Assert.assertEquals(0, transactions.size()); - journalImpl.appendAddRecordTransactional(1L, - 2L, - (byte)3, - new SimpleEncoding(1900 - JournalImpl.SIZE_ADD_RECORD_TX - 1, (byte)4)); + journalImpl.appendAddRecordTransactional(1L, 2L, (byte) 3, new SimpleEncoding(1900 - JournalImpl.SIZE_ADD_RECORD_TX - 1, (byte) 4)); journalImpl.appendCommitRecord(1L, false); @@ -570,8 +519,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase } @Test - public void testReloadInvalidCheckSizeOnTransaction() throws Exception - { + public void testReloadInvalidCheckSizeOnTransaction() throws Exception { final int JOURNAL_SIZE = 2000; setupAndLoadJournal(JOURNAL_SIZE, 100); @@ -581,9 +529,8 @@ public class AlignedJournalImplTest extends ActiveMQTestBase Assert.assertEquals(0, records.size()); Assert.assertEquals(0, transactions.size()); - for (int i = 0; i < 2; i++) - { - journalImpl.appendAddRecordTransactional(1L, i, (byte)0, new SimpleEncoding(1, (byte)15)); + for (int i = 0; i < 2; i++) { + journalImpl.appendAddRecordTransactional(1L, i, (byte) 0, new SimpleEncoding(1, (byte) 15)); } journalImpl.appendCommitRecord(1L, false); @@ -635,8 +582,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase } @Test - public void testPartiallyBrokenFile() throws Exception - { + public void testPartiallyBrokenFile() throws Exception { final int JOURNAL_SIZE = 20000; setupAndLoadJournal(JOURNAL_SIZE, 100); @@ -646,10 +592,9 @@ public class AlignedJournalImplTest extends ActiveMQTestBase Assert.assertEquals(0, records.size()); Assert.assertEquals(0, transactions.size()); - for (int i = 0; i < 20; i++) - { - journalImpl.appendAddRecordTransactional(1L, i, (byte)0, new SimpleEncoding(1, (byte)15)); - journalImpl.appendAddRecordTransactional(2L, i + 20L, (byte)0, new SimpleEncoding(1, (byte)15)); + for (int i = 0; i < 20; i++) { + journalImpl.appendAddRecordTransactional(1L, i, (byte) 0, new SimpleEncoding(1, (byte) 15)); + journalImpl.appendAddRecordTransactional(2L, i + 20L, (byte) 0, new SimpleEncoding(1, (byte) 15)); } journalImpl.appendCommitRecord(1L, false); @@ -697,8 +642,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase } @Test - public void testReduceFreeFiles() throws Exception - { + public void testReduceFreeFiles() throws Exception { final int JOURNAL_SIZE = 2000; setupAndLoadJournal(JOURNAL_SIZE, 100, 10); @@ -709,9 +653,8 @@ public class AlignedJournalImplTest extends ActiveMQTestBase Assert.assertEquals(10, factory.listFiles("tt").size()); - for (int i = 0; i < 10; i++) - { - journalImpl.appendAddRecord(i, (byte)0, new SimpleEncoding(1, (byte)0), false); + for (int i = 0; i < 10; i++) { + journalImpl.appendAddRecord(i, (byte) 0, new SimpleEncoding(1, (byte) 0), false); journalImpl.forceMoveNextFile(); } @@ -721,8 +664,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase Assert.assertEquals(12, factory.listFiles("tt").size()); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { journalImpl.appendDeleteRecord(i, false); } @@ -738,8 +680,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase } @Test - public void testReloadIncompleteTransaction() throws Exception - { + public void testReloadIncompleteTransaction() throws Exception { final int JOURNAL_SIZE = 2000; setupAndLoadJournal(JOURNAL_SIZE, 1); @@ -749,14 +690,12 @@ public class AlignedJournalImplTest extends ActiveMQTestBase Assert.assertEquals(0, records.size()); Assert.assertEquals(0, transactions.size()); - for (int i = 0; i < 10; i++) - { - journalImpl.appendAddRecordTransactional(1L, i, (byte)0, new SimpleEncoding(1, (byte)15)); + for (int i = 0; i < 10; i++) { + journalImpl.appendAddRecordTransactional(1L, i, (byte) 0, new SimpleEncoding(1, (byte) 15)); } - for (int i = 10; i < 20; i++) - { - journalImpl.appendAddRecordTransactional(1L, i, (byte)0, new SimpleEncoding(1, (byte)15)); + for (int i = 10; i < 20; i++) { + journalImpl.appendAddRecordTransactional(1L, i, (byte) 0, new SimpleEncoding(1, (byte) 15)); } journalImpl.appendCommitRecord(1L, false); @@ -800,8 +739,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase } @Test - public void testPrepareAloneOnSeparatedFile() throws Exception - { + public void testPrepareAloneOnSeparatedFile() throws Exception { final int JOURNAL_SIZE = 20000; setupAndLoadJournal(JOURNAL_SIZE, 100); @@ -809,24 +747,22 @@ public class AlignedJournalImplTest extends ActiveMQTestBase Assert.assertEquals(0, records.size()); Assert.assertEquals(0, transactions.size()); - for (int i = 0; i < 10; i++) - { - journalImpl.appendAddRecordTransactional(1L, i, (byte)0, new SimpleEncoding(1, (byte)15)); + for (int i = 0; i < 10; i++) { + journalImpl.appendAddRecordTransactional(1L, i, (byte) 0, new SimpleEncoding(1, (byte) 15)); } journalImpl.forceMoveNextFile(); - SimpleEncoding xidEncoding = new SimpleEncoding(10, (byte)'a'); + SimpleEncoding xidEncoding = new SimpleEncoding(10, (byte) 'a'); journalImpl.appendPrepareRecord(1L, xidEncoding, false); journalImpl.appendCommitRecord(1L, false); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { journalImpl.appendDeleteRecordTransactional(2L, i); } journalImpl.appendCommitRecord(2L, false); - journalImpl.appendAddRecord(100L, (byte)0, new SimpleEncoding(1, (byte)10), false); // Add + journalImpl.appendAddRecord(100L, (byte) 0, new SimpleEncoding(1, (byte) 10), false); // Add // anything // to // keep @@ -842,8 +778,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase } @Test - public void testCommitWithMultipleFiles() throws Exception - { + public void testCommitWithMultipleFiles() throws Exception { final int JOURNAL_SIZE = 20000; setupAndLoadJournal(JOURNAL_SIZE, 100); @@ -851,21 +786,17 @@ public class AlignedJournalImplTest extends ActiveMQTestBase Assert.assertEquals(0, records.size()); Assert.assertEquals(0, transactions.size()); - for (int i = 0; i < 50; i++) - { - if (i == 10) - { + for (int i = 0; i < 50; i++) { + if (i == 10) { journalImpl.forceMoveNextFile(); } - journalImpl.appendAddRecordTransactional(1L, i, (byte)0, new SimpleEncoding(1, (byte)15)); + journalImpl.appendAddRecordTransactional(1L, i, (byte) 0, new SimpleEncoding(1, (byte) 15)); } journalImpl.appendCommitRecord(1L, false); - for (int i = 0; i < 10; i++) - { - if (i == 5) - { + for (int i = 0; i < 10; i++) { + if (i == 5) { journalImpl.forceMoveNextFile(); } journalImpl.appendDeleteRecordTransactional(2L, i); @@ -882,8 +813,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase } @Test - public void testSimplePrepare() throws Exception - { + public void testSimplePrepare() throws Exception { final int JOURNAL_SIZE = 3 * 1024; setupAndLoadJournal(JOURNAL_SIZE, 1); @@ -891,11 +821,11 @@ public class AlignedJournalImplTest extends ActiveMQTestBase Assert.assertEquals(0, records.size()); Assert.assertEquals(0, transactions.size()); - SimpleEncoding xid = new SimpleEncoding(10, (byte)1); + SimpleEncoding xid = new SimpleEncoding(10, (byte) 1); - journalImpl.appendAddRecord(10L, (byte)0, new SimpleEncoding(10, (byte)0), false); + journalImpl.appendAddRecord(10L, (byte) 0, new SimpleEncoding(10, (byte) 0), false); - journalImpl.appendDeleteRecordTransactional(1L, 10L, new SimpleEncoding(100, (byte)'j')); + journalImpl.appendDeleteRecordTransactional(1L, 10L, new SimpleEncoding(100, (byte) 'j')); journalImpl.appendPrepareRecord(1, xid, false); @@ -907,21 +837,18 @@ public class AlignedJournalImplTest extends ActiveMQTestBase Assert.assertEquals(1, transactions.get(0).recordsToDelete.size()); Assert.assertEquals(1, records.size()); - for (RecordInfo record : transactions.get(0).recordsToDelete) - { + for (RecordInfo record : transactions.get(0).recordsToDelete) { byte[] data = record.data; Assert.assertEquals(100, data.length); - for (byte element : data) - { - Assert.assertEquals((byte)'j', element); + for (byte element : data) { + Assert.assertEquals((byte) 'j', element); } } Assert.assertEquals(10, transactions.get(0).extraData.length); - for (int i = 0; i < 10; i++) - { - Assert.assertEquals((byte)1, transactions.get(0).extraData[i]); + for (int i = 0; i < 10; i++) { + Assert.assertEquals((byte) 1, transactions.get(0).extraData[i]); } journalImpl.appendCommitRecord(1L, false); @@ -936,8 +863,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase } @Test - public void testReloadWithPreparedTransaction() throws Exception - { + public void testReloadWithPreparedTransaction() throws Exception { final int JOURNAL_SIZE = 3 * 1024; setupAndLoadJournal(JOURNAL_SIZE, 1); @@ -945,15 +871,14 @@ public class AlignedJournalImplTest extends ActiveMQTestBase Assert.assertEquals(0, records.size()); Assert.assertEquals(0, transactions.size()); - for (int i = 0; i < 10; i++) - { - journalImpl.appendAddRecordTransactional(1, i, (byte)1, new SimpleEncoding(50, (byte)1)); + for (int i = 0; i < 10; i++) { + journalImpl.appendAddRecordTransactional(1, i, (byte) 1, new SimpleEncoding(50, (byte) 1)); journalImpl.forceMoveNextFile(); } journalImpl.debugWait(); - SimpleEncoding xid1 = new SimpleEncoding(10, (byte)1); + SimpleEncoding xid1 = new SimpleEncoding(10, (byte) 1); journalImpl.appendPrepareRecord(1L, xid1, false); @@ -965,9 +890,8 @@ public class AlignedJournalImplTest extends ActiveMQTestBase Assert.assertEquals(1, transactions.size()); Assert.assertEquals(10, transactions.get(0).extraData.length); - for (int i = 0; i < 10; i++) - { - Assert.assertEquals((byte)1, transactions.get(0).extraData[i]); + for (int i = 0; i < 10; i++) { + Assert.assertEquals((byte) 1, transactions.get(0).extraData[i]); } journalImpl.checkReclaimStatus(); @@ -984,12 +908,11 @@ public class AlignedJournalImplTest extends ActiveMQTestBase journalImpl.checkReclaimStatus(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { journalImpl.appendDeleteRecordTransactional(2L, i); } - SimpleEncoding xid2 = new SimpleEncoding(15, (byte)2); + SimpleEncoding xid2 = new SimpleEncoding(15, (byte) 2); journalImpl.appendPrepareRecord(2L, xid2, false); @@ -999,8 +922,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase Assert.assertEquals(15, transactions.get(0).extraData.length); - for (byte element : transactions.get(0).extraData) - { + for (byte element : transactions.get(0).extraData) { Assert.assertEquals(2, element); } @@ -1026,8 +948,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase } @Test - public void testReloadInvalidPrepared() throws Exception - { + public void testReloadInvalidPrepared() throws Exception { final int JOURNAL_SIZE = 3000; setupAndLoadJournal(JOURNAL_SIZE, 100); @@ -1035,12 +956,11 @@ public class AlignedJournalImplTest extends ActiveMQTestBase Assert.assertEquals(0, records.size()); Assert.assertEquals(0, transactions.size()); - for (int i = 0; i < 10; i++) - { - journalImpl.appendAddRecordTransactional(1, i, (byte)1, new SimpleEncoding(50, (byte)1)); + for (int i = 0; i < 10; i++) { + journalImpl.appendAddRecordTransactional(1, i, (byte) 1, new SimpleEncoding(50, (byte) 1)); } - journalImpl.appendPrepareRecord(1L, new SimpleEncoding(13, (byte)0), false); + journalImpl.appendPrepareRecord(1L, new SimpleEncoding(13, (byte) 0), false); setupAndLoadJournal(JOURNAL_SIZE, 100); Assert.assertEquals(0, records.size()); @@ -1078,15 +998,13 @@ public class AlignedJournalImplTest extends ActiveMQTestBase } @Test - public void testReclaimAfterRollabck() throws Exception - { + public void testReclaimAfterRollabck() throws Exception { final int JOURNAL_SIZE = 2000; setupAndLoadJournal(JOURNAL_SIZE, 1); - for (int i = 0; i < 10; i++) - { - journalImpl.appendAddRecordTransactional(1L, i, (byte)0, new SimpleEncoding(1, (byte)0)); + for (int i = 0; i < 10; i++) { + journalImpl.appendAddRecordTransactional(1L, i, (byte) 0, new SimpleEncoding(1, (byte) 0)); journalImpl.forceMoveNextFile(); } @@ -1108,15 +1026,13 @@ public class AlignedJournalImplTest extends ActiveMQTestBase // It should be ok to write records on AIO, and later read then on NIO @Test - public void testDecreaseAlignment() throws Exception - { + public void testDecreaseAlignment() throws Exception { final int JOURNAL_SIZE = 512 * 4; setupAndLoadJournal(JOURNAL_SIZE, 512); - for (int i = 0; i < 10; i++) - { - journalImpl.appendAddRecordTransactional(1L, i, (byte)0, new SimpleEncoding(1, (byte)0)); + for (int i = 0; i < 10; i++) { + journalImpl.appendAddRecordTransactional(1L, i, (byte) 0, new SimpleEncoding(1, (byte) 0)); } journalImpl.appendCommitRecord(1L, false); @@ -1132,15 +1048,13 @@ public class AlignedJournalImplTest extends ActiveMQTestBase // It should be ok to write records on NIO, and later read then on AIO @Test - public void testIncreaseAlignment() throws Exception - { + public void testIncreaseAlignment() throws Exception { final int JOURNAL_SIZE = 512 * 4; setupAndLoadJournal(JOURNAL_SIZE, 1); - for (int i = 0; i < 10; i++) - { - journalImpl.appendAddRecordTransactional(1L, i, (byte)0, new SimpleEncoding(1, (byte)0)); + for (int i = 0; i < 10; i++) { + journalImpl.appendAddRecordTransactional(1L, i, (byte) 0, new SimpleEncoding(1, (byte) 0)); } journalImpl.appendCommitRecord(1L, false); @@ -1155,17 +1069,16 @@ public class AlignedJournalImplTest extends ActiveMQTestBase } @Test - public void testEmptyPrepare() throws Exception - { + public void testEmptyPrepare() throws Exception { final int JOURNAL_SIZE = 512 * 4; setupAndLoadJournal(JOURNAL_SIZE, 1); - journalImpl.appendPrepareRecord(2L, new SimpleEncoding(10, (byte)'j'), false); + journalImpl.appendPrepareRecord(2L, new SimpleEncoding(10, (byte) 'j'), false); journalImpl.forceMoveNextFile(); - journalImpl.appendAddRecord(1L, (byte)0, new SimpleEncoding(10, (byte)'k'), false); + journalImpl.appendAddRecord(1L, (byte) 0, new SimpleEncoding(10, (byte) 'k'), false); setupAndLoadJournal(JOURNAL_SIZE, 1); @@ -1199,8 +1112,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase } @Test - public void testReclaimingAfterConcurrentAddsAndDeletes() throws Exception - { + public void testReclaimingAfterConcurrentAddsAndDeletes() throws Exception { final int JOURNAL_SIZE = 10 * 1024; setupAndLoadJournal(JOURNAL_SIZE, 1); @@ -1215,52 +1127,41 @@ public class AlignedJournalImplTest extends ActiveMQTestBase final int NUMBER_OF_ELEMENTS = 500; - Thread t1 = new Thread() - { + Thread t1 = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { latchReady.countDown(); ActiveMQTestBase.waitForLatch(latchStart); - for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) - { - journalImpl.appendAddRecordTransactional(i, i, (byte)1, new SimpleEncoding(50, (byte)1)); + for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) { + journalImpl.appendAddRecordTransactional(i, i, (byte) 1, new SimpleEncoding(50, (byte) 1)); journalImpl.appendCommitRecord(i, false); queueDelete.offer(i); } finishedOK.incrementAndGet(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } }; - Thread t2 = new Thread() - { + Thread t2 = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { latchReady.countDown(); ActiveMQTestBase.waitForLatch(latchStart); - for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) - { + for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) { Integer toDelete = queueDelete.poll(10, TimeUnit.SECONDS); - if (toDelete == null) - { + if (toDelete == null) { break; } journalImpl.appendDeleteRecord(toDelete, false); } finishedOK.incrementAndGet(); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -1292,8 +1193,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase } @Test - public void testAlignmentOverReload() throws Exception - { + public void testAlignmentOverReload() throws Exception { factory = new FakeSequentialFileFactory(512, false); journalImpl = new JournalImpl(512 + 512 * 3, 20, 0, 0, factory, "amq", "amq", 1000); @@ -1302,10 +1202,10 @@ public class AlignedJournalImplTest extends ActiveMQTestBase journalImpl.load(AlignedJournalImplTest.dummyLoader); - journalImpl.appendAddRecord(1L, (byte)0, new SimpleEncoding(100, (byte)'a'), false); - journalImpl.appendAddRecord(2L, (byte)0, new SimpleEncoding(100, (byte)'b'), false); - journalImpl.appendAddRecord(3L, (byte)0, new SimpleEncoding(100, (byte)'b'), false); - journalImpl.appendAddRecord(4L, (byte)0, new SimpleEncoding(100, (byte)'b'), false); + journalImpl.appendAddRecord(1L, (byte) 0, new SimpleEncoding(100, (byte) 'a'), false); + journalImpl.appendAddRecord(2L, (byte) 0, new SimpleEncoding(100, (byte) 'b'), false); + journalImpl.appendAddRecord(3L, (byte) 0, new SimpleEncoding(100, (byte) 'b'), false); + journalImpl.appendAddRecord(4L, (byte) 0, new SimpleEncoding(100, (byte) 'b'), false); journalImpl.stop(); @@ -1345,8 +1245,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); records = new ArrayList(); @@ -1363,8 +1262,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { stopComponent(journalImpl); if (factory != null) factory.stop(); @@ -1383,20 +1281,18 @@ public class AlignedJournalImplTest extends ActiveMQTestBase // Private ------------------------------------------------------- - private void setupAndLoadJournal(final int journalSize, final int alignment) throws Exception - { + private void setupAndLoadJournal(final int journalSize, final int alignment) throws Exception { setupAndLoadJournal(journalSize, alignment, 2); } - private void setupAndLoadJournal(final int journalSize, final int alignment, final int numberOfMinimalFiles) throws Exception - { - if (factory == null) - { + private void setupAndLoadJournal(final int journalSize, + final int alignment, + final int numberOfMinimalFiles) throws Exception { + if (factory == null) { factory = new FakeSequentialFileFactory(alignment, true); } - if (journalImpl != null) - { + if (journalImpl != null) { journalImpl.stop(); } @@ -1408,12 +1304,10 @@ public class AlignedJournalImplTest extends ActiveMQTestBase transactions.clear(); incompleteTransactions.clear(); - journalImpl.load(records, transactions, new TransactionFailureCallback() - { + journalImpl.load(records, transactions, new TransactionFailureCallback() { public void failedTransaction(final long transactionID, final List records, - final List recordsToDelete) - { + final List recordsToDelete) { System.out.println("records.length = " + records.size()); incompleteTransactions.add(transactionID); } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/CleanBufferTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/CleanBufferTest.java index c2f88acf44..f21757be64 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/CleanBufferTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/CleanBufferTest.java @@ -28,8 +28,7 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Assert; import org.junit.Test; -public class CleanBufferTest extends ActiveMQTestBase -{ +public class CleanBufferTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -42,18 +41,15 @@ public class CleanBufferTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testCleanOnNIO() - { + public void testCleanOnNIO() { SequentialFileFactory factory = new NIOSequentialFileFactory(new File("Whatever"), 1); testBuffer(factory); } @Test - public void testCleanOnAIO() - { - if (LibaioContext.isLoaded()) - { + public void testCleanOnAIO() { + if (LibaioContext.isLoaded()) { SequentialFileFactory factory = new AIOSequentialFileFactory(new File("Whatever"), 50); testBuffer(factory); @@ -61,29 +57,24 @@ public class CleanBufferTest extends ActiveMQTestBase } @Test - public void testCleanOnFake() - { + public void testCleanOnFake() { SequentialFileFactory factory = new FakeSequentialFileFactory(); testBuffer(factory); } - private void testBuffer(final SequentialFileFactory factory) - { + private void testBuffer(final SequentialFileFactory factory) { factory.start(); ByteBuffer buffer = factory.newBuffer(100); - try - { - for (byte b = 0; b < 100; b++) - { + try { + for (byte b = 0; b < 100; b++) { buffer.put(b); } buffer.rewind(); - for (byte b = 0; b < 100; b++) - { + for (byte b = 0; b < 100; b++) { Assert.assertEquals(b, buffer.get()); } @@ -93,20 +84,16 @@ public class CleanBufferTest extends ActiveMQTestBase buffer.rewind(); - for (byte b = 0; b < 100; b++) - { - if (b < 10) - { + for (byte b = 0; b < 100; b++) { + if (b < 10) { Assert.assertEquals(0, buffer.get()); } - else - { + else { Assert.assertEquals(b, buffer.get()); } } } - finally - { + finally { factory.releaseBuffer(buffer); factory.stop(); } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/FakeJournalImplTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/FakeJournalImplTest.java index eabb89e73a..ecf44c1006 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/FakeJournalImplTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/FakeJournalImplTest.java @@ -19,17 +19,15 @@ package org.apache.activemq.artemis.tests.unit.core.journal.impl; import org.apache.activemq.artemis.tests.unit.core.journal.impl.fakes.FakeSequentialFileFactory; import org.apache.activemq.artemis.core.io.SequentialFileFactory; -public class FakeJournalImplTest extends JournalImplTestUnit -{ +public class FakeJournalImplTest extends JournalImplTestUnit { + @Override - protected SequentialFileFactory getFileFactory() throws Exception - { + protected SequentialFileFactory getFileFactory() throws Exception { return new FakeSequentialFileFactory(); } @Override - protected int getAlignment() - { + protected int getAlignment() { return 1; } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/FakeSequentialFileFactoryTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/FakeSequentialFileFactoryTest.java index aee1e067a6..8612ae4564 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/FakeSequentialFileFactoryTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/FakeSequentialFileFactoryTest.java @@ -19,12 +19,10 @@ package org.apache.activemq.artemis.tests.unit.core.journal.impl; import org.apache.activemq.artemis.tests.unit.core.journal.impl.fakes.FakeSequentialFileFactory; import org.apache.activemq.artemis.core.io.SequentialFileFactory; -public class FakeSequentialFileFactoryTest extends SequentialFileFactoryTestBase -{ +public class FakeSequentialFileFactoryTest extends SequentialFileFactoryTestBase { @Override - protected SequentialFileFactory createFactory(String folder) - { + protected SequentialFileFactory createFactory(String folder) { return new FakeSequentialFileFactory(); } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/FileFactoryTestBase.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/FileFactoryTestBase.java index 73bf1483fc..5d29205c98 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/FileFactoryTestBase.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/FileFactoryTestBase.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.unit.core.journal.impl; + import java.nio.ByteBuffer; import org.apache.activemq.artemis.core.io.SequentialFile; @@ -23,16 +24,15 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Assert; import org.junit.Before; -public abstract class FileFactoryTestBase extends ActiveMQTestBase -{ +public abstract class FileFactoryTestBase extends ActiveMQTestBase { + protected abstract SequentialFileFactory createFactory(); protected SequentialFileFactory factory; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); factory = createFactory(); @@ -40,8 +40,7 @@ public abstract class FileFactoryTestBase extends ActiveMQTestBase // Protected --------------------------------- - protected void checkFill(final SequentialFile file, final int size) throws Exception - { + protected void checkFill(final SequentialFile file, final int size) throws Exception { file.fill(size); file.close(); @@ -62,8 +61,7 @@ public abstract class FileFactoryTestBase extends ActiveMQTestBase bb.get(bytes); - for (int i = 0; i < size; i++) - { + for (int i = 0; i < size; i++) { // log.debug(" i is " + i); Assert.assertEquals(0, bytes[i]); } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/JournalAsyncTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/JournalAsyncTest.java index f72c68a61d..22395e8ba4 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/JournalAsyncTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/JournalAsyncTest.java @@ -31,8 +31,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class JournalAsyncTest extends ActiveMQTestBase -{ +public class JournalAsyncTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -53,19 +52,16 @@ public class JournalAsyncTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testAsynchronousCommit() throws Exception - { + public void testAsynchronousCommit() throws Exception { doAsynchronousTest(true); } @Test - public void testAsynchronousRollback() throws Exception - { + public void testAsynchronousRollback() throws Exception { doAsynchronousTest(false); } - public void doAsynchronousTest(final boolean isCommit) throws Exception - { + public void doAsynchronousTest(final boolean isCommit) throws Exception { final int JOURNAL_SIZE = 20000; setupJournal(JOURNAL_SIZE, 100, 5); @@ -74,33 +70,27 @@ public class JournalAsyncTest extends ActiveMQTestBase final CountDownLatch latch = new CountDownLatch(1); - class LocalThread extends Thread - { + class LocalThread extends Thread { + Exception e; @Override - public void run() - { - try - { - for (int i = 0; i < 10; i++) - { + public void run() { + try { + for (int i = 0; i < 10; i++) { journalImpl.appendAddRecordTransactional(1L, i, (byte) 1, new SimpleEncoding(1, (byte) 0)); } latch.countDown(); factory.setHoldCallbacks(false, null); - if (isCommit) - { + if (isCommit) { journalImpl.appendCommitRecord(1L, true); } - else - { + else { journalImpl.appendRollbackRecord(1L, true); } } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); this.e = e; } @@ -122,8 +112,7 @@ public class JournalAsyncTest extends ActiveMQTestBase t.join(); - if (t.e != null) - { + if (t.e != null) { throw t.e; } } @@ -131,8 +120,7 @@ public class JournalAsyncTest extends ActiveMQTestBase // If a callback error already arrived, we should just throw the exception // right away @Test - public void testPreviousError() throws Exception - { + public void testPreviousError() throws Exception { final int JOURNAL_SIZE = 20000; setupJournal(JOURNAL_SIZE, 100, 5); @@ -147,35 +135,30 @@ public class JournalAsyncTest extends ActiveMQTestBase factory.setGenerateErrors(false); factory.setHoldCallbacks(false, null); - try - { + try { journalImpl.appendAddRecordTransactional(1L, 2, (byte) 1, new SimpleEncoding(1, (byte) 0)); Assert.fail("Exception expected"); // An exception already happened in one // of the elements on this transaction. // We can't accept any more elements on // the transaction } - catch (Exception ignored) - { + catch (Exception ignored) { } } @Test - public void testSyncNonTransaction() throws Exception - { + public void testSyncNonTransaction() throws Exception { final int JOURNAL_SIZE = 20000; setupJournal(JOURNAL_SIZE, 100, 5); factory.setGenerateErrors(true); - try - { + try { journalImpl.appendAddRecord(1L, (byte) 0, new SimpleEncoding(1, (byte) 0), true); Assert.fail("Exception expected"); } - catch (Exception ignored) - { + catch (Exception ignored) { } @@ -187,8 +170,7 @@ public class JournalAsyncTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); records = new ArrayList(); @@ -203,16 +185,12 @@ public class JournalAsyncTest extends ActiveMQTestBase @Override @After - public void tearDown() throws Exception - { - if (journalImpl != null) - { - try - { + public void tearDown() throws Exception { + if (journalImpl != null) { + try { journalImpl.stop(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } @@ -220,15 +198,14 @@ public class JournalAsyncTest extends ActiveMQTestBase } // Private ------------------------------------------------------- - private void setupJournal(final int journalSize, final int alignment, final int numberOfMinimalFiles) throws Exception - { - if (factory == null) - { + private void setupJournal(final int journalSize, + final int alignment, + final int numberOfMinimalFiles) throws Exception { + if (factory == null) { factory = new FakeSequentialFileFactory(alignment, true); } - if (journalImpl != null) - { + if (journalImpl != null) { journalImpl.stop(); } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/JournalImplTestBase.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/JournalImplTestBase.java index 7e1347e92d..d67a2b2c03 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/JournalImplTestBase.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/JournalImplTestBase.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.unit.core.journal.impl; + import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; @@ -39,8 +40,8 @@ import org.junit.After; import org.junit.Assert; import org.junit.Before; -public abstract class JournalImplTestBase extends ActiveMQTestBase -{ +public abstract class JournalImplTestBase extends ActiveMQTestBase { + protected List records = new LinkedList(); protected TestableJournal journal; @@ -71,8 +72,7 @@ public abstract class JournalImplTestBase extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); resetFileFactory(); @@ -86,12 +86,10 @@ public abstract class JournalImplTestBase extends ActiveMQTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { stopComponent(journal); - if (fileFactory != null) - { + if (fileFactory != null) { fileFactory.stop(); } @@ -102,17 +100,14 @@ public abstract class JournalImplTestBase extends ActiveMQTestBase super.tearDown(); } - protected void resetFileFactory() throws Exception - { - if (fileFactory != null) - { + protected void resetFileFactory() throws Exception { + if (fileFactory != null) { fileFactory.stop(); } fileFactory = getFileFactory(); } - protected void checkAndReclaimFiles() throws Exception - { + protected void checkAndReclaimFiles() throws Exception { journal.debugWait(); boolean originalAutoReclaim = journal.isAutoReclaim(); journal.setAutoReclaim(true); @@ -126,37 +121,30 @@ public abstract class JournalImplTestBase extends ActiveMQTestBase // Private // --------------------------------------------------------------------------------- - protected void setup(final int minFreeFiles, final int fileSize, final boolean sync, final int maxAIO) - { + protected void setup(final int minFreeFiles, final int fileSize, final boolean sync, final int maxAIO) { minFiles = minFreeFiles; this.fileSize = fileSize; this.sync = sync; this.maxAIO = maxAIO; } - protected void setup(final int minFreeFiles, final int fileSize, final boolean sync) - { + protected void setup(final int minFreeFiles, final int fileSize, final boolean sync) { minFiles = minFreeFiles; this.fileSize = fileSize; this.sync = sync; maxAIO = 50; } - public void createJournal() throws Exception - { - journal = new JournalImpl(fileSize, minFiles, 0, 0, fileFactory, filePrefix, fileExtension, maxAIO) - { + public void createJournal() throws Exception { + journal = new JournalImpl(fileSize, minFiles, 0, 0, fileFactory, filePrefix, fileExtension, maxAIO) { @Override - public void onCompactDone() - { + public void onCompactDone() { latchDone.countDown(); System.out.println("Waiting on Compact"); - try - { + try { latchWait.await(); } - catch (InterruptedException e) - { + catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Waiting on Compact Done"); @@ -169,21 +157,16 @@ public abstract class JournalImplTestBase extends ActiveMQTestBase // It will start compacting, but it will let the thread in wait mode at onCompactDone, so we can validate command // executions - protected void startCompact() throws Exception - { + protected void startCompact() throws Exception { latchDone.setCount(1); latchWait.setCount(1); - this.compactThread = new Thread() - { + this.compactThread = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { journal.testCompact(); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); } } @@ -194,27 +177,22 @@ public abstract class JournalImplTestBase extends ActiveMQTestBase latchDone.await(); } - protected void finishCompact() throws Exception - { + protected void finishCompact() throws Exception { latchWait.countDown(); compactThread.join(); } - protected void startJournal() throws Exception - { + protected void startJournal() throws Exception { journal.start(); } - protected void stopJournal() throws Exception - { + protected void stopJournal() throws Exception { stopJournal(true); } - protected void stopJournal(final boolean reclaim) throws Exception - { + protected void stopJournal(final boolean reclaim) throws Exception { // We do a reclaim in here - if (reclaim) - { + if (reclaim) { checkAndReclaimFiles(); } @@ -224,23 +202,15 @@ public abstract class JournalImplTestBase extends ActiveMQTestBase /** * @throws Exception */ - protected void exportImportJournal() throws Exception - { + protected void exportImportJournal() throws Exception { System.out.println("Exporting to " + getTestDir() + "/output.log"); - EncodeJournal.exportJournal(getTestDir(), - this.filePrefix, - this.fileExtension, - this.minFiles, - this.fileSize, - getTestDir() + "/output.log"); + EncodeJournal.exportJournal(getTestDir(), this.filePrefix, this.fileExtension, this.minFiles, this.fileSize, getTestDir() + "/output.log"); File dir = new File(getTestDir()); - FilenameFilter fnf = new FilenameFilter() - { - public boolean accept(final File file, final String name) - { + FilenameFilter fnf = new FilenameFilter() { + public boolean accept(final File file, final String name) { return name.endsWith("." + fileExtension); } }; @@ -249,27 +219,19 @@ public abstract class JournalImplTestBase extends ActiveMQTestBase File[] files = dir.listFiles(fnf); - for (File file : files) - { + for (File file : files) { System.out.println("Deleting " + file); file.delete(); } - DecodeJournal.importJournal(getTestDir(), - filePrefix, - fileExtension, - minFiles, - fileSize, - getTestDir() + "/output.log"); + DecodeJournal.importJournal(getTestDir(), filePrefix, fileExtension, minFiles, fileSize, getTestDir() + "/output.log"); } - protected void loadAndCheck() throws Exception - { + protected void loadAndCheck() throws Exception { loadAndCheck(false); } - protected void loadAndCheck(final boolean printDebugJournal) throws Exception - { + protected void loadAndCheck(final boolean printDebugJournal) throws Exception { List committedRecords = new ArrayList(); List preparedTransactions = new ArrayList(); @@ -278,8 +240,7 @@ public abstract class JournalImplTestBase extends ActiveMQTestBase checkRecordsEquivalent(records, committedRecords); - if (printDebugJournal) - { + if (printDebugJournal) { printJournalLists(records, committedRecords); } @@ -287,10 +248,8 @@ public abstract class JournalImplTestBase extends ActiveMQTestBase List prepared = new ArrayList(); - for (Map.Entry entry : transactions.entrySet()) - { - if (entry.getValue().prepared) - { + for (Map.Entry entry : transactions.entrySet()) { + if (entry.getValue().prepared) { PreparedTransactionInfo info = new PreparedTransactionInfo(entry.getKey(), null); info.records.addAll(entry.getValue().records); @@ -304,56 +263,47 @@ public abstract class JournalImplTestBase extends ActiveMQTestBase checkTransactionsEquivalent(prepared, preparedTransactions); } - protected void load() throws Exception - { + protected void load() throws Exception { journal.load(null, null, null); } - protected void beforeJournalOperation() throws Exception - { + protected void beforeJournalOperation() throws Exception { } - protected void add(final long... arguments) throws Exception - { + protected void add(final long... arguments) throws Exception { addWithSize(recordLength, arguments); } - protected void addWithSize(final int size, final long... arguments) throws Exception - { - for (long element : arguments) - { + protected void addWithSize(final int size, final long... arguments) throws Exception { + for (long element : arguments) { byte[] record = generateRecord(size); beforeJournalOperation(); - journal.appendAddRecord(element, (byte)0, record, sync); + journal.appendAddRecord(element, (byte) 0, record, sync); - records.add(new RecordInfo(element, (byte)0, record, false, (short)0)); + records.add(new RecordInfo(element, (byte) 0, record, false, (short) 0)); } journal.debugWait(); } - protected void update(final long... arguments) throws Exception - { - for (long element : arguments) - { + protected void update(final long... arguments) throws Exception { + for (long element : arguments) { byte[] updateRecord = generateRecord(recordLength); beforeJournalOperation(); - journal.appendUpdateRecord(element, (byte)0, updateRecord, sync); + journal.appendUpdateRecord(element, (byte) 0, updateRecord, sync); - records.add(new RecordInfo(element, (byte)0, updateRecord, true, (short)0)); + records.add(new RecordInfo(element, (byte) 0, updateRecord, true, (short) 0)); } journal.debugWait(); } - protected void delete(final long... arguments) throws Exception - { - for (long element : arguments) - { + protected void delete(final long... arguments) throws Exception { + for (long element : arguments) { beforeJournalOperation(); journal.appendDeleteRecord(element, sync); @@ -364,72 +314,63 @@ public abstract class JournalImplTestBase extends ActiveMQTestBase journal.debugWait(); } - protected void addTx(final long txID, final long... arguments) throws Exception - { + protected void addTx(final long txID, final long... arguments) throws Exception { TransactionHolder tx = getTransaction(txID); - for (long element : arguments) - { + for (long element : arguments) { // SIZE_BYTE + SIZE_LONG + SIZE_LONG + SIZE_INT + record.length + // SIZE_BYTE byte[] record = generateRecord(recordLength - (JournalImpl.SIZE_ADD_RECORD_TX + 1)); beforeJournalOperation(); - journal.appendAddRecordTransactional(txID, element, (byte)0, record); + journal.appendAddRecordTransactional(txID, element, (byte) 0, record); - tx.records.add(new RecordInfo(element, (byte)0, record, false, (short)0)); + tx.records.add(new RecordInfo(element, (byte) 0, record, false, (short) 0)); } journal.debugWait(); } - protected void updateTx(final long txID, final long... arguments) throws Exception - { + protected void updateTx(final long txID, final long... arguments) throws Exception { TransactionHolder tx = getTransaction(txID); - for (long element : arguments) - { + for (long element : arguments) { byte[] updateRecord = generateRecord(recordLength - (JournalImpl.SIZE_ADD_RECORD_TX + 1)); beforeJournalOperation(); - journal.appendUpdateRecordTransactional(txID, element, (byte)0, updateRecord); + journal.appendUpdateRecordTransactional(txID, element, (byte) 0, updateRecord); - tx.records.add(new RecordInfo(element, (byte)0, updateRecord, true, (short)0)); + tx.records.add(new RecordInfo(element, (byte) 0, updateRecord, true, (short) 0)); } journal.debugWait(); } - protected void deleteTx(final long txID, final long... arguments) throws Exception - { + protected void deleteTx(final long txID, final long... arguments) throws Exception { TransactionHolder tx = getTransaction(txID); - for (long element : arguments) - { + for (long element : arguments) { beforeJournalOperation(); journal.appendDeleteRecordTransactional(txID, element); - tx.deletes.add(new RecordInfo(element, (byte)0, null, true, (short)0)); + tx.deletes.add(new RecordInfo(element, (byte) 0, null, true, (short) 0)); } journal.debugWait(); } - protected void prepare(final long txID, final EncodingSupport xid) throws Exception - { + protected void prepare(final long txID, final EncodingSupport xid) throws Exception { TransactionHolder tx = transactions.get(txID); - if (tx == null) - { + if (tx == null) { tx = new TransactionHolder(); transactions.put(txID, tx); } - if (tx.prepared) - { + if (tx.prepared) { throw new IllegalStateException("Transaction is already prepared"); } @@ -442,12 +383,10 @@ public abstract class JournalImplTestBase extends ActiveMQTestBase journal.debugWait(); } - protected void commit(final long txID) throws Exception - { + protected void commit(final long txID) throws Exception { TransactionHolder tx = transactions.remove(txID); - if (tx == null) - { + if (tx == null) { throw new IllegalStateException("Cannot find tx " + txID); } @@ -457,20 +396,17 @@ public abstract class JournalImplTestBase extends ActiveMQTestBase records.addAll(tx.records); - for (RecordInfo l : tx.deletes) - { + for (RecordInfo l : tx.deletes) { removeRecordsForID(l.id); } journal.debugWait(); } - protected void rollback(final long txID) throws Exception - { + protected void rollback(final long txID) throws Exception { TransactionHolder tx = transactions.remove(txID); - if (tx == null) - { + if (tx == null) { throw new IllegalStateException("Cannot find tx " + txID); } @@ -481,25 +417,20 @@ public abstract class JournalImplTestBase extends ActiveMQTestBase journal.debugWait(); } - protected void removeRecordsForID(final long id) - { - for (ListIterator iter = records.listIterator(); iter.hasNext();) - { + protected void removeRecordsForID(final long id) { + for (ListIterator iter = records.listIterator(); iter.hasNext(); ) { RecordInfo info = iter.next(); - if (info.id == id) - { + if (info.id == id) { iter.remove(); } } } - protected TransactionHolder getTransaction(final long txID) - { + protected TransactionHolder getTransaction(final long txID) { TransactionHolder tx = transactions.get(txID); - if (tx == null) - { + if (tx == null) { tx = new TransactionHolder(); transactions.put(txID, tx); @@ -509,16 +440,14 @@ public abstract class JournalImplTestBase extends ActiveMQTestBase } protected void checkTransactionsEquivalent(final List expected, - final List actual) - { + final List actual) { Assert.assertEquals("Lists not same length", expected.size(), actual.size()); Iterator iterExpected = expected.iterator(); Iterator iterActual = actual.iterator(); - while (iterExpected.hasNext()) - { + while (iterExpected.hasNext()) { PreparedTransactionInfo rexpected = iterExpected.next(); PreparedTransactionInfo ractual = iterActual.next(); @@ -533,8 +462,7 @@ public abstract class JournalImplTestBase extends ActiveMQTestBase Iterator iterDeletesActual = ractual.recordsToDelete.iterator(); - while (iterDeletesExpected.hasNext()) - { + while (iterDeletesExpected.hasNext()) { long lexpected = iterDeletesExpected.next().id; long lactual = iterDeletesActual.next().id; @@ -544,10 +472,8 @@ public abstract class JournalImplTestBase extends ActiveMQTestBase } } - protected void checkRecordsEquivalent(final List expected, final List actual) - { - if (expected.size() != actual.size()) - { + protected void checkRecordsEquivalent(final List expected, final List actual) { + if (expected.size() != actual.size()) { printJournalLists(expected, actual); } @@ -557,14 +483,12 @@ public abstract class JournalImplTestBase extends ActiveMQTestBase Iterator iterActual = actual.iterator(); - while (iterExpected.hasNext()) - { + while (iterExpected.hasNext()) { RecordInfo rexpected = iterExpected.next(); RecordInfo ractual = iterActual.next(); - if (rexpected.id != ractual.id || rexpected.isUpdate != ractual.isUpdate) - { + if (rexpected.id != ractual.id || rexpected.isUpdate != ractual.isUpdate) { printJournalLists(expected, actual); } @@ -580,45 +504,38 @@ public abstract class JournalImplTestBase extends ActiveMQTestBase * @param expected * @param actual */ - protected void printJournalLists(final List expected, final List actual) - { + protected void printJournalLists(final List expected, final List actual) { System.out.println("***********************************************"); System.out.println("Expected list:"); - for (RecordInfo info : expected) - { + for (RecordInfo info : expected) { System.out.println("Record " + info.id + " isUpdate = " + info.isUpdate); } - if (actual != null) - { + if (actual != null) { System.out.println("***********************************************"); System.out.println("Actual list:"); - for (RecordInfo info : actual) - { + for (RecordInfo info : actual) { System.out.println("Record " + info.id + " isUpdate = " + info.isUpdate); } } System.out.println("***********************************************"); } - protected byte[] generateRecord(final int length) - { + protected byte[] generateRecord(final int length) { byte[] record = new byte[length]; - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { // record[i] = RandomUtil.randomByte(); record[i] = ActiveMQTestBase.getSamplebyte(i); } return record; } - protected String debugJournal() throws Exception - { - return "***************************************************\n" + ((JournalImpl)journal).debug() + - "***************************************************\n"; + protected String debugJournal() throws Exception { + return "***************************************************\n" + ((JournalImpl) journal).debug() + + "***************************************************\n"; } - static final class TransactionHolder - { + static final class TransactionHolder { + List records = new ArrayList(); List deletes = new ArrayList(); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/JournalImplTestUnit.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/JournalImplTestUnit.java index b009092538..47752e4316 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/JournalImplTestUnit.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/JournalImplTestUnit.java @@ -33,15 +33,13 @@ import org.junit.After; import org.junit.Assert; import org.junit.Test; -public abstract class JournalImplTestUnit extends JournalImplTestBase -{ +public abstract class JournalImplTestUnit extends JournalImplTestBase { + @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { List files = fileFactory.listFiles(fileExtension); - for (String file : files) - { + for (String file : files) { SequentialFile seqFile = fileFactory.createSequentialFile(file); Assert.assertEquals(fileSize, seqFile.size()); } @@ -53,65 +51,53 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase // ============= @Test - public void testState() throws Exception - { + public void testState() throws Exception { setup(10, 10 * 1024, true); createJournal(); - try - { + try { load(); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { stopJournal(); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } startJournal(); - try - { + try { startJournal(); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } stopJournal(); startJournal(); load(); - try - { + try { load(); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } - try - { + try { startJournal(); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // OK } stopJournal(); } @Test - public void testRestartJournal() throws Exception - { + public void testRestartJournal() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -120,94 +106,77 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase startJournal(); load(); byte[] record = new byte[1000]; - for (int i = 0; i < record.length; i++) - { + for (int i = 0; i < record.length; i++) { record[i] = (byte) 'a'; } // Appending records after restart should be valid (not throwing any // exceptions) - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { journal.appendAddRecord(1, (byte) 1, new SimpleEncoding(2, (byte) 'a'), false); } stopJournal(); } @Test - public void testParams() throws Exception - { - try - { + public void testParams() throws Exception { + try { new JournalImpl(JournalImpl.MIN_FILE_SIZE - 1, 10, 0, 0, fileFactory, filePrefix, fileExtension, 1); Assert.fail("Should throw exception"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { // Ok } - try - { + try { new JournalImpl(10 * 1024, 1, 0, 0, fileFactory, filePrefix, fileExtension, 1); Assert.fail("Should throw exception"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { // Ok } - try - { + try { new JournalImpl(10 * 1024, 10, 0, 0, null, filePrefix, fileExtension, 1); Assert.fail("Should throw exception"); } - catch (NullPointerException e) - { + catch (NullPointerException e) { // Ok } - try - { + try { new JournalImpl(10 * 1024, 10, 0, 0, fileFactory, null, fileExtension, 1); Assert.fail("Should throw exception"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { // Ok } - try - { + try { new JournalImpl(10 * 1024, 10, 0, 0, fileFactory, filePrefix, null, 1); Assert.fail("Should throw exception"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { // Ok } - try - { + try { new JournalImpl(10 * 1024, 10, 0, 0, fileFactory, filePrefix, null, 0); Assert.fail("Should throw exception"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { // Ok } } - @Test - public void testVersionCheck() throws Exception - { + public void testVersionCheck() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -219,15 +188,13 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase List files = fileFactory.listFiles(fileExtension); - for (String fileStr : files) - { + for (String fileStr : files) { SequentialFile file = fileFactory.createSequentialFile(fileStr); ByteBuffer buffer = fileFactory.newBuffer(JournalImpl.SIZE_HEADER); - for (int i = 0; i < JournalImpl.SIZE_HEADER; i++) - { + for (int i = 0; i < JournalImpl.SIZE_HEADER; i++) { buffer.put(Byte.MAX_VALUE); } @@ -247,29 +214,24 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase startJournal(); boolean exceptionHappened = false; - try - { + try { load(); } - catch (ActiveMQIOErrorException ioe) - { + catch (ActiveMQIOErrorException ioe) { exceptionHappened = true; } - catch (ActiveMQException e) - { + catch (ActiveMQException e) { Assert.fail("invalid exception type:" + e.getType()); } Assert.assertTrue("Exception was expected", exceptionHappened); stopJournal(); - } // Validates the if the journal will work when the IDs are over MaxInt @Test - public void testMaxInt() throws Exception - { + public void testMaxInt() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -282,8 +244,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase List files = fileFactory.listFiles(fileExtension); long fileID = Integer.MAX_VALUE; - for (String fileStr : files) - { + for (String fileStr : files) { SequentialFile file = fileFactory.createSequentialFile(fileStr); file.open(); @@ -299,8 +260,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase load(); - for (long i = 0; i < 100; i++) - { + for (long i = 0; i < 100; i++) { add(i); stopJournal(); @@ -314,12 +274,9 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } - @Test - public void testFilesImmediatelyAfterload() throws Exception - { - try - { + public void testFilesImmediatelyAfterload() throws Exception { + try { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -329,8 +286,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase Assert.assertEquals(10, files.size()); - for (String file : files) - { + for (String file : files) { Assert.assertTrue(file.startsWith(filePrefix)); } @@ -347,8 +303,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase Assert.assertEquals(20, files.size()); - for (String file : files) - { + for (String file : files) { Assert.assertTrue(file.startsWith(filePrefix)); } @@ -367,8 +322,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase Assert.assertEquals(17, files.size()); - for (String file : files) - { + for (String file : files) { Assert.assertTrue(file.startsWith(filePrefix)); } @@ -387,15 +341,13 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase Assert.assertEquals(11, files.size()); - for (String file : files) - { + for (String file : files) { Assert.assertTrue(file.startsWith(filePrefix)); } stopJournal(); } - finally - { + finally { filePrefix = "amq"; fileExtension = "amq"; @@ -403,8 +355,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testEmptyReopen() throws Exception - { + public void testEmptyReopen() throws Exception { setup(2, 10 * 1024, true); createJournal(); startJournal(); @@ -425,8 +376,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase Assert.assertEquals(2, files2.size()); - for (String file : files1) - { + for (String file : files1) { Assert.assertTrue(files2.contains(file)); } @@ -434,8 +384,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testCreateFilesOnLoad() throws Exception - { + public void testCreateFilesOnLoad() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -458,8 +407,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase Assert.assertEquals(20, files2.size()); - for (String file : files1) - { + for (String file : files1) { Assert.assertTrue(files2.contains(file)); } @@ -467,8 +415,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testReduceFreeFiles() throws Exception - { + public void testReduceFreeFiles() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -489,16 +436,14 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase Assert.assertEquals(10, files2.size()); - for (String file : files1) - { + for (String file : files1) { Assert.assertTrue(files2.contains(file)); } stopJournal(); } - private int calculateRecordsPerFile(final int fileSize, final int alignment, int recordSize) - { + private int calculateRecordsPerFile(final int fileSize, final int alignment, int recordSize) { recordSize = calculateRecordSize(recordSize, alignment); int headerSize = calculateRecordSize(JournalImpl.SIZE_HEADER, alignment); return (fileSize - headerSize) / recordSize; @@ -507,32 +452,26 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase /** * Use: calculateNumberOfFiles (fileSize, numberOfRecords, recordSize, numberOfRecords2, recordSize2, , ...., numberOfRecordsN, recordSizeN); */ - private int calculateNumberOfFiles(final int fileSize, final int alignment, final int... record) throws Exception - { + private int calculateNumberOfFiles(final int fileSize, final int alignment, final int... record) throws Exception { int headerSize = calculateRecordSize(JournalImpl.SIZE_HEADER, alignment); int currentPosition = headerSize; int totalFiles = 0; - for (int i = 0; i < record.length; i += 2) - { + for (int i = 0; i < record.length; i += 2) { int numberOfRecords = record[i]; int recordSize = calculateRecordSize(record[i + 1], alignment); - while (numberOfRecords > 0) - { + while (numberOfRecords > 0) { int recordsFit = (fileSize - currentPosition) / recordSize; - if (numberOfRecords < recordsFit) - { + if (numberOfRecords < recordsFit) { currentPosition = currentPosition + numberOfRecords * recordSize; numberOfRecords = 0; } - else if (recordsFit > 0) - { + else if (recordsFit > 0) { currentPosition = currentPosition + recordsFit * recordSize; numberOfRecords -= recordsFit; } - else - { + else { totalFiles++; currentPosition = headerSize; } @@ -544,8 +483,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testCheckCreateMoreFiles() throws Exception - { + public void testCheckCreateMoreFiles() throws Exception { setup(2, 10 * 1024, true); createJournal(); startJournal(); @@ -562,15 +500,11 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase // Fill all the files - for (int i = 0; i < 91; i++) - { + for (int i = 0; i < 91; i++) { add(i); } - int numberOfFiles = calculateNumberOfFiles(10 * 1024, - journal.getAlignment(), - 91, - JournalImpl.SIZE_ADD_RECORD + recordLength); + int numberOfFiles = calculateNumberOfFiles(10 * 1024, journal.getAlignment(), 91, JournalImpl.SIZE_ADD_RECORD + recordLength); Assert.assertEquals(numberOfFiles, journal.getDataFilesCount()); Assert.assertEquals(0, journal.getFreeFilesCount()); @@ -583,22 +517,17 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase Assert.assertEquals(1, journal.getOpenedFilesCount()); - for (String file : files1) - { + for (String file : files1) { Assert.assertTrue(files2.contains(file)); } // Now add some more - for (int i = 90; i < 95; i++) - { + for (int i = 90; i < 95; i++) { add(i); } - numberOfFiles = calculateNumberOfFiles(10 * 1024, - journal.getAlignment(), - 95, - JournalImpl.SIZE_ADD_RECORD + recordLength); + numberOfFiles = calculateNumberOfFiles(10 * 1024, journal.getAlignment(), 95, JournalImpl.SIZE_ADD_RECORD + recordLength); Assert.assertEquals(numberOfFiles, journal.getDataFilesCount()); Assert.assertEquals(0, journal.getFreeFilesCount()); @@ -609,22 +538,17 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase Assert.assertEquals(numberOfFiles + 2, files3.size()); Assert.assertEquals(1, journal.getOpenedFilesCount()); - for (String file : files1) - { + for (String file : files1) { Assert.assertTrue(files3.contains(file)); } // And a load more - for (int i = 95; i < 200; i++) - { + for (int i = 95; i < 200; i++) { add(i); } - numberOfFiles = calculateNumberOfFiles(10 * 1024, - journal.getAlignment(), - 200, - JournalImpl.SIZE_ADD_RECORD + recordLength); + numberOfFiles = calculateNumberOfFiles(10 * 1024, journal.getAlignment(), 200, JournalImpl.SIZE_ADD_RECORD + recordLength); Assert.assertEquals(numberOfFiles, journal.getDataFilesCount()); Assert.assertEquals(0, journal.getFreeFilesCount()); @@ -635,8 +559,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase Assert.assertEquals(numberOfFiles + 2, files4.size()); Assert.assertEquals(1, journal.getOpenedFilesCount()); - for (String file : files1) - { + for (String file : files1) { Assert.assertTrue(files4.contains(file)); } @@ -645,8 +568,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase // Validate the methods that are used on assertions @Test - public void testCalculations() throws Exception - { + public void testCalculations() throws Exception { Assert.assertEquals(0, calculateNumberOfFiles(10 * 1024, 1, 1, 10, 2, 20)); Assert.assertEquals(0, calculateNumberOfFiles(10 * 1024, 512, 1, 1)); @@ -659,8 +581,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testReclaim() throws Exception - { + public void testReclaim() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -675,16 +596,13 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase Assert.assertEquals(1, journal.getOpenedFilesCount()); Assert.assertEquals(0, journal.getIDMapSize()); - int addRecordsPerFile = calculateRecordsPerFile(10 * 1024, - journal.getAlignment(), - JournalImpl.SIZE_ADD_RECORD + 1 + recordLength); + int addRecordsPerFile = calculateRecordsPerFile(10 * 1024, journal.getAlignment(), JournalImpl.SIZE_ADD_RECORD + 1 + recordLength); System.out.println(JournalImpl.SIZE_ADD_RECORD + 1 + recordLength); // Fills exactly 10 files int initialNumberOfAddRecords = addRecordsPerFile * 10; - for (int i = 0; i < initialNumberOfAddRecords; i++) - { + for (int i = 0; i < initialNumberOfAddRecords; i++) { add(i); } @@ -699,15 +617,13 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase Assert.assertEquals(11, files4.size()); Assert.assertEquals(1, journal.getOpenedFilesCount()); - for (String file : files1) - { + for (String file : files1) { Assert.assertTrue(files4.contains(file)); } // Now delete half of them - for (int i = 0; i < initialNumberOfAddRecords / 2; i++) - { + for (int i = 0; i < initialNumberOfAddRecords / 2; i++) { delete(i); } @@ -716,8 +632,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase // Make sure the deletes aren't in the current file - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { add(initialNumberOfAddRecords + i); } @@ -741,15 +656,13 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase // Now delete the rest - for (int i = initialNumberOfAddRecords / 2; i < initialNumberOfAddRecords + 10; i++) - { + for (int i = initialNumberOfAddRecords / 2; i < initialNumberOfAddRecords + 10; i++) { delete(i); } // And fill the current file - for (int i = 110; i < 120; i++) - { + for (int i = 110; i < 120; i++) { add(i); delete(i); } @@ -769,11 +682,9 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testReclaimAddUpdateDeleteDifferentFiles1() throws Exception - { + public void testReclaimAddUpdateDeleteDifferentFiles1() throws Exception { // Make sure there is one record per file - setup(2, calculateRecordSize(JournalImpl.SIZE_HEADER, getAlignment()) + calculateRecordSize(JournalImpl.SIZE_ADD_RECORD + 1 + recordLength, - getAlignment()), true); + setup(2, calculateRecordSize(JournalImpl.SIZE_HEADER, getAlignment()) + calculateRecordSize(JournalImpl.SIZE_ADD_RECORD + 1 + recordLength, getAlignment()), true); createJournal(); startJournal(); load(); @@ -809,11 +720,9 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testReclaimAddUpdateDeleteDifferentFiles2() throws Exception - { + public void testReclaimAddUpdateDeleteDifferentFiles2() throws Exception { // Make sure there is one record per file - setup(2, calculateRecordSize(JournalImpl.SIZE_HEADER, getAlignment()) + calculateRecordSize(JournalImpl.SIZE_ADD_RECORD + 1 + recordLength, - getAlignment()), true); + setup(2, calculateRecordSize(JournalImpl.SIZE_HEADER, getAlignment()) + calculateRecordSize(JournalImpl.SIZE_ADD_RECORD + 1 + recordLength, getAlignment()), true); createJournal(); startJournal(); @@ -847,21 +756,18 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testReclaimTransactionalAddCommit() throws Exception - { + public void testReclaimTransactionalAddCommit() throws Exception { testReclaimTransactionalAdd(true); } @Test - public void testReclaimTransactionalAddRollback() throws Exception - { + public void testReclaimTransactionalAddRollback() throws Exception { testReclaimTransactionalAdd(false); } // TODO commit and rollback, also transactional deletes - private void testReclaimTransactionalAdd(final boolean commit) throws Exception - { + private void testReclaimTransactionalAdd(final boolean commit) throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -876,24 +782,20 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase Assert.assertEquals(1, journal.getOpenedFilesCount()); Assert.assertEquals(0, journal.getIDMapSize()); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { addTx(1, i); } - Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 100, recordLength), - journal.getDataFilesCount()); + Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 100, recordLength), journal.getDataFilesCount()); Assert.assertEquals(0, journal.getFreeFilesCount()); Assert.assertEquals(0, journal.getIDMapSize()); List files2 = fileFactory.listFiles(fileExtension); - Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 100, recordLength) + 2, - files2.size()); + Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 100, recordLength) + 2, files2.size()); Assert.assertEquals(1, journal.getOpenedFilesCount()); - for (String file : files1) - { + for (String file : files1) { Assert.assertTrue(files2.contains(file)); } @@ -901,42 +803,35 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase // Make sure nothing reclaimed - Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 100, recordLength), - journal.getDataFilesCount()); + Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 100, recordLength), journal.getDataFilesCount()); Assert.assertEquals(0, journal.getFreeFilesCount()); Assert.assertEquals(0, journal.getIDMapSize()); List files3 = fileFactory.listFiles(fileExtension); - Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 100, recordLength) + 2, - files3.size()); + Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 100, recordLength) + 2, files3.size()); Assert.assertEquals(1, journal.getOpenedFilesCount()); - for (String file : files1) - { + for (String file : files1) { Assert.assertTrue(files3.contains(file)); } // Add a load more updates - for (int i = 100; i < 200; i++) - { + for (int i = 100; i < 200; i++) { updateTx(1, i); } - Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 200, recordLength), - journal.getDataFilesCount()); + Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 200, recordLength), journal.getDataFilesCount()); Assert.assertEquals(0, journal.getFreeFilesCount()); Assert.assertEquals(0, journal.getIDMapSize()); List files4 = fileFactory.listFiles(fileExtension); - Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 200, recordLength) + 2, - files4.size()); + Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 200, recordLength) + 2, files4.size()); Assert.assertEquals(1, journal.getOpenedFilesCount()); - for (String file : files1) - { + for (String file : files1) { Assert.assertTrue(files4.contains(file)); } @@ -944,8 +839,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase // Make sure nothing reclaimed - Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 200, recordLength), - journal.getDataFilesCount()); + Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 200, recordLength), journal.getDataFilesCount()); Assert.assertEquals(0, journal.getFreeFilesCount()); Assert.assertEquals(0, journal.getIDMapSize()); @@ -954,117 +848,70 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase Assert.assertEquals(24, files5.size()); Assert.assertEquals(1, journal.getOpenedFilesCount()); - for (String file : files1) - { + for (String file : files1) { Assert.assertTrue(files5.contains(file)); } // Now delete them - for (int i = 0; i < 200; i++) - { + for (int i = 0; i < 200; i++) { deleteTx(1, i); } - Assert.assertEquals(calculateNumberOfFiles(fileSize, - journal.getAlignment(), - 200, - recordLength, - 200, - JournalImpl.SIZE_DELETE_RECORD_TX), journal.getDataFilesCount()); + Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 200, recordLength, 200, JournalImpl.SIZE_DELETE_RECORD_TX), journal.getDataFilesCount()); Assert.assertEquals(0, journal.getFreeFilesCount()); Assert.assertEquals(0, journal.getIDMapSize()); List files7 = fileFactory.listFiles(fileExtension); - Assert.assertEquals(calculateNumberOfFiles(fileSize, - journal.getAlignment(), - 200, - recordLength, - 200, - JournalImpl.SIZE_DELETE_RECORD_TX) + 2, files7.size()); + Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 200, recordLength, 200, JournalImpl.SIZE_DELETE_RECORD_TX) + 2, files7.size()); Assert.assertEquals(1, journal.getOpenedFilesCount()); - for (String file : files1) - { + for (String file : files1) { Assert.assertTrue(files7.contains(file)); } checkAndReclaimFiles(); - Assert.assertEquals(calculateNumberOfFiles(fileSize, - journal.getAlignment(), - 200, - recordLength, - 200, - JournalImpl.SIZE_DELETE_RECORD_TX), journal.getDataFilesCount()); + Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 200, recordLength, 200, JournalImpl.SIZE_DELETE_RECORD_TX), journal.getDataFilesCount()); Assert.assertEquals(0, journal.getFreeFilesCount()); Assert.assertEquals(0, journal.getIDMapSize()); List files8 = fileFactory.listFiles(fileExtension); - Assert.assertEquals(calculateNumberOfFiles(fileSize, - journal.getAlignment(), - 200, - recordLength, - 200, - JournalImpl.SIZE_DELETE_RECORD_TX) + 2, files8.size()); + Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 200, recordLength, 200, JournalImpl.SIZE_DELETE_RECORD_TX) + 2, files8.size()); Assert.assertEquals(1, journal.getOpenedFilesCount()); - for (String file : files1) - { + for (String file : files1) { Assert.assertTrue(files8.contains(file)); } // Commit - if (commit) - { + if (commit) { commit(1); } - else - { + else { rollback(1); } // Add more records to make sure we get to the next file - for (int i = 200; i < 210; i++) - { + for (int i = 200; i < 210; i++) { add(i); } - Assert.assertEquals(calculateNumberOfFiles(fileSize, - journal.getAlignment(), - 200, - recordLength, - 200, - JournalImpl.SIZE_DELETE_RECORD_TX, - 1, - JournalImpl.SIZE_COMMIT_RECORD, - 10, - JournalImpl.SIZE_ADD_RECORD + recordLength), - journal.getDataFilesCount()); + Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 200, recordLength, 200, JournalImpl.SIZE_DELETE_RECORD_TX, 1, JournalImpl.SIZE_COMMIT_RECORD, 10, JournalImpl.SIZE_ADD_RECORD + recordLength), journal.getDataFilesCount()); Assert.assertEquals(0, journal.getFreeFilesCount()); Assert.assertEquals(10, journal.getIDMapSize()); List files9 = fileFactory.listFiles(fileExtension); - Assert.assertEquals(calculateNumberOfFiles(fileSize, - journal.getAlignment(), - 200, - recordLength, - 200, - JournalImpl.SIZE_DELETE_RECORD_TX, - 1, - JournalImpl.SIZE_COMMIT_RECORD, - 10, - JournalImpl.SIZE_ADD_RECORD + recordLength) + 2, files9.size()); + Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 200, recordLength, 200, JournalImpl.SIZE_DELETE_RECORD_TX, 1, JournalImpl.SIZE_COMMIT_RECORD, 10, JournalImpl.SIZE_ADD_RECORD + recordLength) + 2, files9.size()); Assert.assertEquals(1, journal.getOpenedFilesCount()); - for (String file : files1) - { + for (String file : files1) { Assert.assertTrue(files9.contains(file)); } @@ -1085,10 +932,8 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testReclaimTransactionalSimple() throws Exception - { - setup(2, calculateRecordSize(JournalImpl.SIZE_HEADER, getAlignment()) + calculateRecordSize(recordLength, - getAlignment()), true); + public void testReclaimTransactionalSimple() throws Exception { + setup(2, calculateRecordSize(JournalImpl.SIZE_HEADER, getAlignment()) + calculateRecordSize(recordLength, getAlignment()), true); createJournal(); startJournal(); load(); @@ -1195,8 +1040,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testAddDeleteCommitTXIDMap1() throws Exception - { + public void testAddDeleteCommitTXIDMap1() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -1234,8 +1078,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testAddCommitTXIDMap1() throws Exception - { + public void testAddCommitTXIDMap1() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -1266,8 +1109,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testAddDeleteCommitTXIDMap2() throws Exception - { + public void testAddDeleteCommitTXIDMap2() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -1305,8 +1147,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testAddDeleteRollbackTXIDMap1() throws Exception - { + public void testAddDeleteRollbackTXIDMap1() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -1344,8 +1185,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testAddRollbackTXIDMap1() throws Exception - { + public void testAddRollbackTXIDMap1() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -1376,8 +1216,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testAddDeleteRollbackTXIDMap2() throws Exception - { + public void testAddDeleteRollbackTXIDMap2() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -1415,8 +1254,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testAddDeleteIDMap() throws Exception - { + public void testAddDeleteIDMap() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -1448,10 +1286,8 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testCommitRecordsInFileReclaim() throws Exception - { - setup(2, calculateRecordSize(JournalImpl.SIZE_HEADER, getAlignment()) + calculateRecordSize(recordLength, - getAlignment()), true); + public void testCommitRecordsInFileReclaim() throws Exception { + setup(2, calculateRecordSize(JournalImpl.SIZE_HEADER, getAlignment()) + calculateRecordSize(recordLength, getAlignment()), true); createJournal(); startJournal(); load(); @@ -1521,10 +1357,8 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase // file 3: add 3 @Test - public void testCommitRecordsInFileNoReclaim() throws Exception - { - setup(2, calculateRecordSize(JournalImpl.SIZE_HEADER, getAlignment()) + calculateRecordSize(recordLength, - getAlignment()) + + public void testCommitRecordsInFileNoReclaim() throws Exception { + setup(2, calculateRecordSize(JournalImpl.SIZE_HEADER, getAlignment()) + calculateRecordSize(recordLength, getAlignment()) + 512, true); createJournal(); startJournal(); @@ -1549,8 +1383,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase Assert.assertEquals(3, files2.size()); - Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 2, recordLength), - journal.getDataFilesCount()); + Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 2, recordLength), journal.getDataFilesCount()); Assert.assertEquals(0, journal.getFreeFilesCount()); Assert.assertEquals(1, journal.getOpenedFilesCount()); Assert.assertEquals(1, journal.getIDMapSize()); @@ -1559,20 +1392,10 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase List files3 = fileFactory.listFiles(fileExtension); - Assert.assertEquals(calculateNumberOfFiles(fileSize, - journal.getAlignment(), - 2, - recordLength, - 1, - JournalImpl.SIZE_COMMIT_RECORD + 1) + 2, files3.size()); + Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 2, recordLength, 1, JournalImpl.SIZE_COMMIT_RECORD + 1) + 2, files3.size()); Assert.assertEquals(1, journal.getOpenedFilesCount()); - Assert.assertEquals(calculateNumberOfFiles(fileSize, - journal.getAlignment(), - 2, - recordLength, - 1, - JournalImpl.SIZE_COMMIT_RECORD), journal.getDataFilesCount()); + Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 2, recordLength, 1, JournalImpl.SIZE_COMMIT_RECORD), journal.getDataFilesCount()); Assert.assertEquals(0, journal.getFreeFilesCount()); Assert.assertEquals(2, journal.getIDMapSize()); @@ -1580,24 +1403,10 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase List files4 = fileFactory.listFiles(fileExtension); - Assert.assertEquals(calculateNumberOfFiles(fileSize, - journal.getAlignment(), - 2, - recordLength, - 1, - JournalImpl.SIZE_COMMIT_RECORD + 1, - 1, - JournalImpl.SIZE_DELETE_RECORD + 1) + 2, files4.size()); + Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 2, recordLength, 1, JournalImpl.SIZE_COMMIT_RECORD + 1, 1, JournalImpl.SIZE_DELETE_RECORD + 1) + 2, files4.size()); Assert.assertEquals(1, journal.getOpenedFilesCount()); - Assert.assertEquals(calculateNumberOfFiles(fileSize, - journal.getAlignment(), - 2, - recordLength, - 1, - JournalImpl.SIZE_COMMIT_RECORD + 1, - 1, - JournalImpl.SIZE_DELETE_RECORD + 1), journal.getDataFilesCount()); + Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 2, recordLength, 1, JournalImpl.SIZE_COMMIT_RECORD + 1, 1, JournalImpl.SIZE_DELETE_RECORD + 1), journal.getDataFilesCount()); Assert.assertEquals(0, journal.getFreeFilesCount()); Assert.assertEquals(1, journal.getIDMapSize()); @@ -1632,10 +1441,8 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testRollbackRecordsInFileNoReclaim() throws Exception - { - setup(2, calculateRecordSize(JournalImpl.SIZE_HEADER, getAlignment()) + calculateRecordSize(recordLength, - getAlignment()) + + public void testRollbackRecordsInFileNoReclaim() throws Exception { + setup(2, calculateRecordSize(JournalImpl.SIZE_HEADER, getAlignment()) + calculateRecordSize(recordLength, getAlignment()) + 512, true); createJournal(); startJournal(); @@ -1667,20 +1474,10 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase rollback(1); // in file 1 - Assert.assertEquals(calculateNumberOfFiles(fileSize, - journal.getAlignment(), - 2, - recordLength, - 1, - JournalImpl.SIZE_ROLLBACK_RECORD + 1), journal.getDataFilesCount()); + Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 2, recordLength, 1, JournalImpl.SIZE_ROLLBACK_RECORD + 1), journal.getDataFilesCount()); Assert.assertEquals(1, journal.getOpenedFilesCount()); - Assert.assertEquals(calculateNumberOfFiles(fileSize, - journal.getAlignment(), - 2, - recordLength, - 1, - JournalImpl.SIZE_ROLLBACK_RECORD + 1), journal.getDataFilesCount()); + Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 2, recordLength, 1, JournalImpl.SIZE_ROLLBACK_RECORD + 1), journal.getDataFilesCount()); Assert.assertEquals(0, journal.getFreeFilesCount()); Assert.assertEquals(1, journal.getIDMapSize()); @@ -1688,24 +1485,10 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase List files4 = fileFactory.listFiles(fileExtension); - Assert.assertEquals(calculateNumberOfFiles(fileSize, - journal.getAlignment(), - 2, - recordLength, - 1, - JournalImpl.SIZE_ROLLBACK_RECORD + 1, - 1, - JournalImpl.SIZE_DELETE_RECORD + 1) + 2, files4.size()); + Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 2, recordLength, 1, JournalImpl.SIZE_ROLLBACK_RECORD + 1, 1, JournalImpl.SIZE_DELETE_RECORD + 1) + 2, files4.size()); Assert.assertEquals(1, journal.getOpenedFilesCount()); - Assert.assertEquals(calculateNumberOfFiles(fileSize, - journal.getAlignment(), - 2, - recordLength, - 1, - JournalImpl.SIZE_ROLLBACK_RECORD + 1, - 1, - JournalImpl.SIZE_DELETE_RECORD + 1), journal.getDataFilesCount()); + Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 2, recordLength, 1, JournalImpl.SIZE_ROLLBACK_RECORD + 1, 1, JournalImpl.SIZE_DELETE_RECORD + 1), journal.getDataFilesCount()); Assert.assertEquals(0, journal.getFreeFilesCount()); Assert.assertEquals(0, journal.getIDMapSize()); @@ -1750,10 +1533,8 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testEmptyPrepare() throws Exception - { - setup(2, calculateRecordSize(JournalImpl.SIZE_HEADER, getAlignment()) + calculateRecordSize(recordLength, - getAlignment()) + + public void testEmptyPrepare() throws Exception { + setup(2, calculateRecordSize(JournalImpl.SIZE_HEADER, getAlignment()) + calculateRecordSize(recordLength, getAlignment()) + 512, true); createJournal(); startJournal(); @@ -1787,10 +1568,8 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testPrepareNoReclaim() throws Exception - { - setup(2, calculateRecordSize(JournalImpl.SIZE_HEADER, getAlignment()) + calculateRecordSize(recordLength, - getAlignment()) + + public void testPrepareNoReclaim() throws Exception { + setup(2, calculateRecordSize(JournalImpl.SIZE_HEADER, getAlignment()) + calculateRecordSize(recordLength, getAlignment()) + 512, true); createJournal(); startJournal(); @@ -1815,8 +1594,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase Assert.assertEquals(3, files2.size()); - Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 2, recordLength), - journal.getDataFilesCount()); + Assert.assertEquals(calculateNumberOfFiles(fileSize, journal.getAlignment(), 2, recordLength), journal.getDataFilesCount()); Assert.assertEquals(0, journal.getFreeFilesCount()); Assert.assertEquals(1, journal.getOpenedFilesCount()); Assert.assertEquals(1, journal.getIDMapSize()); @@ -1887,8 +1665,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testPrepareReclaim() throws Exception - { + public void testPrepareReclaim() throws Exception { setup(2, 100 * 1024, true); createJournal(); startJournal(); @@ -2098,8 +1875,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase // ======================= @Test - public void testSimpleAdd() throws Exception - { + public void testSimpleAdd() throws Exception { setup(2, 10 * 1024, true); createJournal(); startJournal(); @@ -2113,8 +1889,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testMultipleAdd() throws Exception - { + public void testMultipleAdd() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2127,8 +1902,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testMultipleAddNonContiguous() throws Exception - { + public void testMultipleAddNonContiguous() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2142,8 +1916,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testSimpleAddUpdate() throws Exception - { + public void testSimpleAddUpdate() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2157,8 +1930,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testMultipleAddUpdate() throws Exception - { + public void testMultipleAddUpdate() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2172,8 +1944,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testMultipleAddUpdateAll() throws Exception - { + public void testMultipleAddUpdateAll() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2187,8 +1958,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testMultipleAddUpdateNonContiguous() throws Exception - { + public void testMultipleAddUpdateNonContiguous() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2202,8 +1972,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testMultipleAddUpdateAllNonContiguous() throws Exception - { + public void testMultipleAddUpdateAllNonContiguous() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2217,8 +1986,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testSimpleAddUpdateDelete() throws Exception - { + public void testSimpleAddUpdateDelete() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2233,8 +2001,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testSimpleAddUpdateDeleteTransactional() throws Exception - { + public void testSimpleAddUpdateDeleteTransactional() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2252,8 +2019,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testMultipleAddUpdateDelete() throws Exception - { + public void testMultipleAddUpdateDelete() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2268,8 +2034,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testMultipleAddUpdateDeleteAll() throws Exception - { + public void testMultipleAddUpdateDeleteAll() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2284,8 +2049,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testMultipleAddUpdateDeleteNonContiguous() throws Exception - { + public void testMultipleAddUpdateDeleteNonContiguous() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2300,8 +2064,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testMultipleAddUpdateDeleteAllNonContiguous() throws Exception - { + public void testMultipleAddUpdateDeleteAllNonContiguous() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2316,8 +2079,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testMultipleAddUpdateDeleteDifferentOrder() throws Exception - { + public void testMultipleAddUpdateDeleteDifferentOrder() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2332,15 +2094,13 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testMultipleAddUpdateDeleteDifferentRecordLengths() throws Exception - { + public void testMultipleAddUpdateDeleteDifferentRecordLengths() throws Exception { setup(10, 20480, true); createJournal(); startJournal(); load(); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { byte[] record = generateRecord(RandomUtil.randomInterval(1500, 10000)); journal.appendAddRecord(i, (byte) 0, record, false); @@ -2348,8 +2108,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase records.add(new RecordInfo(i, (byte) 0, record, false, (short) 0)); } - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { byte[] record = generateRecord(10 + RandomUtil.randomInterval(1500, 10000)); journal.appendUpdateRecord(i, (byte) 0, record, false); @@ -2357,8 +2116,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase records.add(new RecordInfo(i, (byte) 0, record, true, (short) 0)); } - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { journal.appendDeleteRecord(i, false); removeRecordsForID(i); @@ -2372,8 +2130,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testAddUpdateDeleteRestartAndContinue() throws Exception - { + public void testAddUpdateDeleteRestartAndContinue() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2401,8 +2158,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testSimpleAddTXReload() throws Exception - { + public void testSimpleAddTXReload() throws Exception { setup(2, 10 * 1024, true); createJournal(); startJournal(); @@ -2418,8 +2174,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testSimpleAddTXXAReload() throws Exception - { + public void testSimpleAddTXXAReload() throws Exception { setup(2, 10 * 1024, true); createJournal(); startJournal(); @@ -2438,8 +2193,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testAddUpdateDeleteTransactionalRestartAndContinue() throws Exception - { + public void testAddUpdateDeleteTransactionalRestartAndContinue() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2470,8 +2224,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testFillFileExactly() throws Exception - { + public void testFillFileExactly() throws Exception { recordLength = 500; int numRecords = 2; @@ -2517,8 +2270,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase // =================== @Test - public void testSimpleTransaction() throws Exception - { + public void testSimpleTransaction() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2534,8 +2286,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testTransactionDontDeleteAll() throws Exception - { + public void testTransactionDontDeleteAll() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2551,8 +2302,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testTransactionDeleteAll() throws Exception - { + public void testTransactionDeleteAll() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2568,8 +2318,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testTransactionUpdateFromBeforeTx() throws Exception - { + public void testTransactionUpdateFromBeforeTx() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2585,8 +2334,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testTransactionDeleteFromBeforeTx() throws Exception - { + public void testTransactionDeleteFromBeforeTx() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2602,8 +2350,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testTransactionChangesNotVisibleOutsideTX() throws Exception - { + public void testTransactionChangesNotVisibleOutsideTX() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2619,8 +2366,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testMultipleTransactionsDifferentIDs() throws Exception - { + public void testMultipleTransactionsDifferentIDs() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2648,8 +2394,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testMultipleInterleavedTransactionsDifferentIDs() throws Exception - { + public void testMultipleInterleavedTransactionsDifferentIDs() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2676,8 +2421,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testMultipleInterleavedTransactionsSameIDs() throws Exception - { + public void testMultipleInterleavedTransactionsSameIDs() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2703,8 +2447,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testTransactionMixed() throws Exception - { + public void testTransactionMixed() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2723,8 +2466,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testTransactionAddDeleteDifferentOrder() throws Exception - { + public void testTransactionAddDeleteDifferentOrder() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2739,8 +2481,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testAddOutsideTXThenUpdateInsideTX() throws Exception - { + public void testAddOutsideTXThenUpdateInsideTX() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2755,8 +2496,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testAddOutsideTXThenDeleteInsideTX() throws Exception - { + public void testAddOutsideTXThenDeleteInsideTX() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2771,8 +2511,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testRollback() throws Exception - { + public void testRollback() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2787,8 +2526,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testRollbackMultiple() throws Exception - { + public void testRollbackMultiple() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2805,8 +2543,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testIsolation1() throws Exception - { + public void testIsolation1() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2821,20 +2558,17 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testIsolation2() throws Exception - { + public void testIsolation2() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); load(); addTx(1, 1, 2, 3); - try - { + try { update(1); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // Ok } @@ -2845,20 +2579,17 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testIsolation3() throws Exception - { + public void testIsolation3() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); load(); addTx(1, 1, 2, 3); - try - { + try { delete(1); Assert.fail("Should throw exception"); } - catch (IllegalStateException e) - { + catch (IllegalStateException e) { // Ok } @@ -2872,8 +2603,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase // ======== @Test - public void testXASimpleNotPrepared() throws Exception - { + public void testXASimpleNotPrepared() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2888,8 +2618,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testXASimplePrepared() throws Exception - { + public void testXASimplePrepared() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2908,8 +2637,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testXASimpleCommit() throws Exception - { + public void testXASimpleCommit() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2929,8 +2657,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testXASimpleRollback() throws Exception - { + public void testXASimpleRollback() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2950,8 +2677,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testXAChangesNotVisibleNotPrepared() throws Exception - { + public void testXAChangesNotVisibleNotPrepared() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2967,8 +2693,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testXAChangesNotVisiblePrepared() throws Exception - { + public void testXAChangesNotVisiblePrepared() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -2988,8 +2713,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testXAChangesNotVisibleRollback() throws Exception - { + public void testXAChangesNotVisibleRollback() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -3010,8 +2734,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testXAChangesisibleCommit() throws Exception - { + public void testXAChangesisibleCommit() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -3032,8 +2755,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testXAMultiple() throws Exception - { + public void testXAMultiple() throws Exception { setup(10, 10 * 1024, true); createJournal(); startJournal(); @@ -3060,8 +2782,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testTransactionOnDifferentFiles() throws Exception - { + public void testTransactionOnDifferentFiles() throws Exception { setup(2, 512 + 2 * 1024, true); createJournal(); @@ -3089,8 +2810,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testReclaimAfterUpdate() throws Exception - { + public void testReclaimAfterUpdate() throws Exception { setup(2, 60 * 1024, true); createJournal(); @@ -3099,23 +2819,19 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase int transactionID = 0; - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { add(i); - if (i % 10 == 0 && i > 0) - { + if (i % 10 == 0 && i > 0) { journal.forceMoveNextFile(); } update(i); } - for (int i = 100; i < 200; i++) - { + for (int i = 100; i < 200; i++) { addTx(transactionID, i); - if (i % 10 == 0 && i > 0) - { + if (i % 10 == 0 && i > 0) { journal.forceMoveNextFile(); } commit(transactionID++); @@ -3137,8 +2853,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase journal.forceMoveNextFile(); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { delete(i); } @@ -3146,8 +2861,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase System.out.println(journal.debug()); System.out.println("*****************************************"); - for (int i = 100; i < 200; i++) - { + for (int i = 100; i < 200; i++) { updateTx(transactionID, i); } @@ -3163,8 +2877,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase System.out.println(journal.debug()); System.out.println("*****************************************"); - for (int i = 100; i < 200; i++) - { + for (int i = 100; i < 200; i++) { updateTx(transactionID, i); deleteTx(transactionID, i); } @@ -3202,8 +2915,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testAddTexThenUpdate() throws Exception - { + public void testAddTexThenUpdate() throws Exception { setup(2, 60 * 1024, true); createJournal(); @@ -3225,8 +2937,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase } @Test - public void testLoadTruncatedFile() throws Exception - { + public void testLoadTruncatedFile() throws Exception { setup(2, 2 * 1024, true); createJournal(); startJournal(); @@ -3234,12 +2945,10 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase String testDir = getTestDir(); new File(testDir + File.separator + filePrefix + "-1." + fileExtension).createNewFile(); - try - { + try { load(); } - catch (Exception e) - { + catch (Exception e) { Assert.fail("Unexpected exception: " + e.toString()); } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/ReclaimerTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/ReclaimerTest.java index 858227a9ce..4d3009fb7e 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/ReclaimerTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/ReclaimerTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.unit.core.journal.impl; + import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Before; @@ -32,24 +33,22 @@ import org.apache.activemq.artemis.core.journal.impl.JournalFile; import org.apache.activemq.artemis.core.journal.impl.JournalImpl; import org.apache.activemq.artemis.core.journal.impl.Reclaimer; -public class ReclaimerTest extends ActiveMQTestBase -{ +public class ReclaimerTest extends ActiveMQTestBase { + private JournalFile[] files; private Reclaimer reclaimer; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); reclaimer = new Reclaimer(); } @Test - public void testOneFilePosNegAll() throws Exception - { + public void testOneFilePosNegAll() throws Exception { setup(1); setupPosNeg(0, 10, 10); @@ -60,8 +59,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testOneFilePosNegNotAll() throws Exception - { + public void testOneFilePosNegNotAll() throws Exception { setup(1); setupPosNeg(0, 10, 7); @@ -72,8 +70,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testOneFilePosOnly() throws Exception - { + public void testOneFilePosOnly() throws Exception { setup(1); setupPosNeg(0, 10); @@ -84,8 +81,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testOneFileNegOnly() throws Exception - { + public void testOneFileNegOnly() throws Exception { setup(1); setupPosNeg(0, 0, 10); @@ -96,8 +92,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testTwoFilesPosNegAllDifferentFiles() throws Exception - { + public void testTwoFilesPosNegAllDifferentFiles() throws Exception { setup(2); setupPosNeg(0, 10); @@ -111,8 +106,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testTwoFilesPosNegAllSameFiles() throws Exception - { + public void testTwoFilesPosNegAllSameFiles() throws Exception { setup(2); setupPosNeg(0, 10, 10); @@ -126,8 +120,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testTwoFilesPosNegMixedFiles() throws Exception - { + public void testTwoFilesPosNegMixedFiles() throws Exception { setup(2); setupPosNeg(0, 10, 7); @@ -140,8 +133,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testTwoFilesPosNegAllFirstFile() throws Exception - { + public void testTwoFilesPosNegAllFirstFile() throws Exception { setup(2); setupPosNeg(0, 10, 10); @@ -154,8 +146,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testTwoFilesPosNegAllSecondFile() throws Exception - { + public void testTwoFilesPosNegAllSecondFile() throws Exception { setup(2); setupPosNeg(0, 10); @@ -168,8 +159,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testTwoFilesPosOnly() throws Exception - { + public void testTwoFilesPosOnly() throws Exception { setup(2); setupPosNeg(0, 10); @@ -182,8 +172,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testTwoFilesxyz() throws Exception - { + public void testTwoFilesxyz() throws Exception { setup(2); setupPosNeg(0, 10); @@ -198,8 +187,7 @@ public class ReclaimerTest extends ActiveMQTestBase // Can-can-can @Test - public void testThreeFiles1() throws Exception - { + public void testThreeFiles1() throws Exception { setup(3); setupPosNeg(0, 10, 10, 0, 0); @@ -214,8 +202,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles2() throws Exception - { + public void testThreeFiles2() throws Exception { setup(3); setupPosNeg(0, 10, 7, 0, 0); @@ -230,8 +217,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles3() throws Exception - { + public void testThreeFiles3() throws Exception { setup(3); setupPosNeg(0, 10, 1, 0, 0); @@ -246,8 +232,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles3_1() throws Exception - { + public void testThreeFiles3_1() throws Exception { setup(3); setupPosNeg(0, 10, 1, 0, 0); @@ -262,8 +247,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles3_2() throws Exception - { + public void testThreeFiles3_2() throws Exception { setup(3); setupPosNeg(0, 10, 1, 0, 0); @@ -280,8 +264,7 @@ public class ReclaimerTest extends ActiveMQTestBase // Cant-can-can @Test - public void testThreeFiles4() throws Exception - { + public void testThreeFiles4() throws Exception { setup(3); setupPosNeg(0, 10, 3, 0, 0); @@ -296,8 +279,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles5() throws Exception - { + public void testThreeFiles5() throws Exception { setup(3); setupPosNeg(0, 10, 3, 0, 0); @@ -312,8 +294,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles6() throws Exception - { + public void testThreeFiles6() throws Exception { setup(3); setupPosNeg(0, 10, 0, 0, 0); @@ -328,8 +309,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles7() throws Exception - { + public void testThreeFiles7() throws Exception { setup(3); setupPosNeg(0, 10, 0, 0, 0); @@ -346,8 +326,7 @@ public class ReclaimerTest extends ActiveMQTestBase // Cant can cant @Test - public void testThreeFiles8() throws Exception - { + public void testThreeFiles8() throws Exception { setup(3); setupPosNeg(0, 10, 3, 0, 0); @@ -362,8 +341,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles9() throws Exception - { + public void testThreeFiles9() throws Exception { setup(3); setupPosNeg(0, 10, 3, 0, 0); @@ -378,8 +356,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles10() throws Exception - { + public void testThreeFiles10() throws Exception { setup(3); setupPosNeg(0, 10, 3, 0, 0); @@ -394,8 +371,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles11() throws Exception - { + public void testThreeFiles11() throws Exception { setup(3); setupPosNeg(0, 10, 0, 0, 0); @@ -410,8 +386,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles12() throws Exception - { + public void testThreeFiles12() throws Exception { setup(3); setupPosNeg(0, 10, 0, 0, 0); @@ -428,8 +403,7 @@ public class ReclaimerTest extends ActiveMQTestBase // Cant-cant-cant @Test - public void testThreeFiles13() throws Exception - { + public void testThreeFiles13() throws Exception { setup(3); setupPosNeg(0, 10, 3, 0, 0); @@ -444,8 +418,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles14() throws Exception - { + public void testThreeFiles14() throws Exception { setup(3); setupPosNeg(0, 10, 3, 0, 0); @@ -460,8 +433,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles15() throws Exception - { + public void testThreeFiles15() throws Exception { setup(3); setupPosNeg(0, 10, 3, 0, 0); @@ -476,8 +448,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles16() throws Exception - { + public void testThreeFiles16() throws Exception { setup(3); setupPosNeg(0, 10, 3, 0, 0); @@ -492,8 +463,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles17() throws Exception - { + public void testThreeFiles17() throws Exception { setup(3); setupPosNeg(0, 10, 3, 0, 0); @@ -508,8 +478,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles18() throws Exception - { + public void testThreeFiles18() throws Exception { setup(3); setupPosNeg(0, 10, 3, 0, 0); @@ -524,8 +493,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles19() throws Exception - { + public void testThreeFiles19() throws Exception { setup(3); setupPosNeg(0, 10, 3, 0, 0); @@ -540,8 +508,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles20() throws Exception - { + public void testThreeFiles20() throws Exception { setup(3); setupPosNeg(0, 10, 3, 0, 0); @@ -556,8 +523,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles21() throws Exception - { + public void testThreeFiles21() throws Exception { setup(3); setupPosNeg(0, 10, 0, 0, 0); @@ -574,8 +540,7 @@ public class ReclaimerTest extends ActiveMQTestBase // Can-can-cant @Test - public void testThreeFiles22() throws Exception - { + public void testThreeFiles22() throws Exception { setup(3); setupPosNeg(0, 10, 10, 0, 0); @@ -590,8 +555,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles23() throws Exception - { + public void testThreeFiles23() throws Exception { setup(3); setupPosNeg(0, 10, 10, 0, 0); @@ -606,8 +570,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles24() throws Exception - { + public void testThreeFiles24() throws Exception { setup(3); setupPosNeg(0, 10, 7, 0, 0); @@ -622,8 +585,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles25() throws Exception - { + public void testThreeFiles25() throws Exception { setup(3); setupPosNeg(0, 10, 7, 0, 0); @@ -638,8 +600,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles26() throws Exception - { + public void testThreeFiles26() throws Exception { setup(3); setupPosNeg(0, 10, 7, 0, 0); @@ -656,8 +617,7 @@ public class ReclaimerTest extends ActiveMQTestBase // Can-cant-cant @Test - public void testThreeFiles27() throws Exception - { + public void testThreeFiles27() throws Exception { setup(3); setupPosNeg(0, 10, 10, 0, 0); @@ -672,8 +632,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles28() throws Exception - { + public void testThreeFiles28() throws Exception { setup(3); setupPosNeg(0, 10, 10, 0, 0); @@ -688,8 +647,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles29() throws Exception - { + public void testThreeFiles29() throws Exception { setup(3); setupPosNeg(0, 10, 10, 0, 0); @@ -704,8 +662,7 @@ public class ReclaimerTest extends ActiveMQTestBase } @Test - public void testThreeFiles30() throws Exception - { + public void testThreeFiles30() throws Exception { setup(3); setupPosNeg(0, 10, 10, 0, 0); @@ -722,33 +679,27 @@ public class ReclaimerTest extends ActiveMQTestBase // Private // ------------------------------------------------------------------------ - private void setup(final int numFiles) - { + private void setup(final int numFiles) { files = new JournalFile[numFiles]; - for (int i = 0; i < numFiles; i++) - { + for (int i = 0; i < numFiles; i++) { files[i] = new MockJournalFile(); } } - private void setupPosNeg(final int fileNumber, final int pos, final int... neg) - { + private void setupPosNeg(final int fileNumber, final int pos, final int... neg) { JournalFile file = files[fileNumber]; int totalDep = file.getTotalNegativeToOthers(); - for (int i = 0; i < pos; i++) - { + for (int i = 0; i < pos; i++) { file.incPosCount(); } - for (int i = 0; i < neg.length; i++) - { + for (int i = 0; i < neg.length; i++) { JournalFile reclaimable2 = files[i]; - for (int j = 0; j < neg[i]; j++) - { + for (int j = 0; j < neg[i]; j++) { file.incNegCount(reclaimable2); totalDep++; } @@ -757,24 +708,20 @@ public class ReclaimerTest extends ActiveMQTestBase assertEquals(totalDep, file.getTotalNegativeToOthers()); } - private void assertCanDelete(final int... fileNumber) - { - for (int num : fileNumber) - { + private void assertCanDelete(final int... fileNumber) { + for (int num : fileNumber) { Assert.assertTrue(files[num].isCanReclaim()); } } - private void assertCantDelete(final int... fileNumber) - { - for (int num : fileNumber) - { + private void assertCantDelete(final int... fileNumber) { + for (int num : fileNumber) { Assert.assertFalse(files[num].isCanReclaim()); } } - static final class MockJournalFile implements JournalFile - { + static final class MockJournalFile implements JournalFile { + private final Set transactionIDs = new HashSet(); private final Set transactionTerminationIDs = new HashSet(); @@ -791,45 +738,36 @@ public class ReclaimerTest extends ActiveMQTestBase private int totalDep; - public void extendOffset(final int delta) - { + public void extendOffset(final int delta) { } - public SequentialFile getFile() - { + public SequentialFile getFile() { return null; } - public long getOffset() - { + public long getOffset() { return 0; } - public long getFileID() - { + public long getFileID() { return 0; } - public void setOffset(final long offset) - { + public void setOffset(final long offset) { } - public int getNegCount(final JournalFile file) - { + public int getNegCount(final JournalFile file) { Integer count = negCounts.get(file); - if (count != null) - { + if (count != null) { return count.intValue(); } - else - { + else { return 0; } } - public void incNegCount(final JournalFile file) - { + public void incNegCount(final JournalFile file) { Integer count = negCounts.get(file); int c = count == null ? 1 : count.intValue() + 1; @@ -839,144 +777,120 @@ public class ReclaimerTest extends ActiveMQTestBase totalDep++; } - public int getPosCount() - { + public int getPosCount() { return posCount; } - public void incPosCount() - { + public void incPosCount() { posCount++; } - public void decPosCount() - { + public void decPosCount() { posCount--; } - public boolean isCanReclaim() - { + public boolean isCanReclaim() { return canDelete; } - public void setCanReclaim(final boolean canDelete) - { + public void setCanReclaim(final boolean canDelete) { this.canDelete = canDelete; } - public void addTransactionID(final long id) - { + public void addTransactionID(final long id) { transactionIDs.add(id); } - public void addTransactionPrepareID(final long id) - { + public void addTransactionPrepareID(final long id) { transactionPrepareIDs.add(id); } - public void addTransactionTerminationID(final long id) - { + public void addTransactionTerminationID(final long id) { transactionTerminationIDs.add(id); } - public boolean containsTransactionID(final long id) - { + public boolean containsTransactionID(final long id) { return transactionIDs.contains(id); } - public boolean containsTransactionPrepareID(final long id) - { + public boolean containsTransactionPrepareID(final long id) { return transactionPrepareIDs.contains(id); } - public boolean containsTransactionTerminationID(final long id) - { + public boolean containsTransactionTerminationID(final long id) { return transactionTerminationIDs.contains(id); } - public Set getTranactionTerminationIDs() - { + public Set getTranactionTerminationIDs() { return transactionTerminationIDs; } - public Set getTransactionPrepareIDs() - { + public Set getTransactionPrepareIDs() { return transactionPrepareIDs; } - public Set getTransactionsIDs() - { + public Set getTransactionsIDs() { return transactionIDs; } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.journal.impl.JournalFile#decPendingTransaction() */ - public void decPendingTransaction() - { + public void decPendingTransaction() { } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.journal.impl.JournalFile#getPendingTransactions() */ - public int getPendingTransactions() - { + public int getPendingTransactions() { return 0; } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.journal.impl.JournalFile#incPendingTransaction() */ - public void incPendingTransaction() - { + public void incPendingTransaction() { } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.journal.impl.JournalFile#getOrderingID() */ - public int getOrderingID() - { + public int getOrderingID() { return 0; } - public void addSize(final int bytes) - { + public void addSize(final int bytes) { } @Override - public void decSize(final int bytes) - { + public void decSize(final int bytes) { } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.journal.impl.JournalFile#getSize() */ - public int getLiveSize() - { + public int getLiveSize() { return 0; } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.journal.impl.JournalFile#isNeedCleanup() */ - public boolean isNeedCleanup() - { + public boolean isNeedCleanup() { return needCleanup; } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.journal.impl.JournalFile#resetNegCount(org.apache.activemq.artemis.core.journal.impl.JournalFile) */ - public boolean resetNegCount(final JournalFile file) - { + public boolean resetNegCount(final JournalFile file) { return false; } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.journal.impl.JournalFile#setNeedCleanup(boolean) */ - public void setNeedCleanup(final boolean needCleanup) - { + public void setNeedCleanup(final boolean needCleanup) { this.needCleanup = needCleanup; } @@ -984,32 +898,28 @@ public class ReclaimerTest extends ActiveMQTestBase /* (non-Javadoc) * @see org.apache.activemq.artemis.core.journal.impl.JournalFile#getRecordID() */ - public int getRecordID() - { + public int getRecordID() { return 0; } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.journal.impl.JournalFile#getTotalNegativeToOthers() */ - public int getTotalNegativeToOthers() - { + public int getTotalNegativeToOthers() { return totalDep; } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.journal.impl.JournalFile#getJournalVersion() */ - public int getJournalVersion() - { + public int getJournalVersion() { return JournalImpl.FORMAT_VERSION; } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.journal.impl.JournalFile#getTotNeg() */ - public int getTotNeg() - { + public int getTotNeg() { // TODO Auto-generated method stub return 0; } @@ -1017,8 +927,7 @@ public class ReclaimerTest extends ActiveMQTestBase /* (non-Javadoc) * @see org.apache.activemq.artemis.core.journal.impl.JournalFile#setTotNeg(int) */ - public void setTotNeg(int totNeg) - { + public void setTotNeg(int totNeg) { // TODO Auto-generated method stub } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/SequentialFileFactoryTestBase.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/SequentialFileFactoryTestBase.java index 60ca28d79d..18b8a9c2a0 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/SequentialFileFactoryTestBase.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/SequentialFileFactoryTestBase.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.unit.core.journal.impl; + import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -32,12 +33,11 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public abstract class SequentialFileFactoryTestBase extends ActiveMQTestBase -{ +public abstract class SequentialFileFactoryTestBase extends ActiveMQTestBase { + @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); factory = createFactory(getTestDir()); @@ -47,8 +47,7 @@ public abstract class SequentialFileFactoryTestBase extends ActiveMQTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { factory.stop(); factory = null; @@ -65,8 +64,7 @@ public abstract class SequentialFileFactoryTestBase extends ActiveMQTestBase protected SequentialFileFactory factory; @Test - public void listFilesOnNonExistentFolder() throws Exception - { + public void listFilesOnNonExistentFolder() throws Exception { SequentialFileFactory fileFactory = createFactory("./target/dontexist"); List list = fileFactory.listFiles("tmp"); Assert.assertNotNull(list); @@ -74,14 +72,12 @@ public abstract class SequentialFileFactoryTestBase extends ActiveMQTestBase } @Test - public void testCreateAndListFiles() throws Exception - { + public void testCreateAndListFiles() throws Exception { List expectedFiles = new ArrayList(); final int numFiles = 10; - for (int i = 0; i < numFiles; i++) - { + for (int i = 0; i < numFiles; i++) { String fileName = UUID.randomUUID().toString() + ".amq"; expectedFiles.add(fileName); @@ -108,8 +104,7 @@ public abstract class SequentialFileFactoryTestBase extends ActiveMQTestBase Assert.assertEquals(expectedFiles.size(), fileNames.size()); - for (String fileName : expectedFiles) - { + for (String fileName : expectedFiles) { Assert.assertTrue(fileNames.contains(fileName)); } @@ -130,14 +125,12 @@ public abstract class SequentialFileFactoryTestBase extends ActiveMQTestBase } @Test - public void testFill() throws Exception - { + public void testFill() throws Exception { SequentialFile sf = factory.createSequentialFile("fill.amq"); sf.open(); - try - { + try { checkFill(sf, 2048); @@ -145,15 +138,13 @@ public abstract class SequentialFileFactoryTestBase extends ActiveMQTestBase checkFill(sf, 512 * 4); } - finally - { + finally { sf.close(); } } @Test - public void testDelete() throws Exception - { + public void testDelete() throws Exception { SequentialFile sf = factory.createSequentialFile("delete-me.amq"); sf.open(); @@ -183,8 +174,7 @@ public abstract class SequentialFileFactoryTestBase extends ActiveMQTestBase } @Test - public void testRename() throws Exception - { + public void testRename() throws Exception { SequentialFile sf = factory.createSequentialFile("test1.amq"); sf.open(); @@ -216,8 +206,7 @@ public abstract class SequentialFileFactoryTestBase extends ActiveMQTestBase } @Test - public void testWriteandRead() throws Exception - { + public void testWriteandRead() throws Exception { SequentialFile sf = factory.createSequentialFile("write.amq"); sf.open(); @@ -261,22 +250,19 @@ public abstract class SequentialFileFactoryTestBase extends ActiveMQTestBase int bytesRead = sf.read(rb1); Assert.assertEquals(calculateRecordSize(bytes1.length, sf.getAlignment()), bytesRead); - for (int i = 0; i < bytes1.length; i++) - { + for (int i = 0; i < bytes1.length; i++) { Assert.assertEquals(bytes1[i], rb1.get(i)); } bytesRead = sf.read(rb2); Assert.assertEquals(calculateRecordSize(bytes2.length, sf.getAlignment()), bytesRead); - for (int i = 0; i < bytes2.length; i++) - { + for (int i = 0; i < bytes2.length; i++) { Assert.assertEquals(bytes2[i], rb2.get(i)); } bytesRead = sf.read(rb3); Assert.assertEquals(calculateRecordSize(bytes3.length, sf.getAlignment()), bytesRead); - for (int i = 0; i < bytes3.length; i++) - { + for (int i = 0; i < bytes3.length; i++) { Assert.assertEquals(bytes3[i], rb3.get(i)); } @@ -285,14 +271,12 @@ public abstract class SequentialFileFactoryTestBase extends ActiveMQTestBase } @Test - public void testPosition() throws Exception - { + public void testPosition() throws Exception { SequentialFile sf = factory.createSequentialFile("position.amq"); sf.open(); - try - { + try { sf.fill(3 * 512); @@ -332,8 +316,7 @@ public abstract class SequentialFileFactoryTestBase extends ActiveMQTestBase ByteBuffer rb2 = factory.newBuffer(rbytes2.length); ByteBuffer rb3 = factory.newBuffer(rbytes3.length); - sf.position(calculateRecordSize(bytes1.length, sf.getAlignment()) + calculateRecordSize(bytes2.length, - sf.getAlignment())); + sf.position(calculateRecordSize(bytes1.length, sf.getAlignment()) + calculateRecordSize(bytes2.length, sf.getAlignment())); int bytesRead = sf.read(rb3); Assert.assertEquals(rb3.limit(), bytesRead); @@ -357,21 +340,17 @@ public abstract class SequentialFileFactoryTestBase extends ActiveMQTestBase ActiveMQTestBase.assertEqualsByteArrays(bytes1, rbytes1); } - finally - { - try - { + finally { + try { sf.close(); } - catch (Exception ignored) - { + catch (Exception ignored) { } } } @Test - public void testOpenClose() throws Exception - { + public void testOpenClose() throws Exception { SequentialFile sf = factory.createSequentialFile("openclose.amq"); sf.open(); @@ -389,15 +368,13 @@ public abstract class SequentialFileFactoryTestBase extends ActiveMQTestBase sf.close(); - try - { + try { sf.write(wrapBuffer(bytes1), true); Assert.fail("Should throw exception"); } - catch (Exception e) - { + catch (Exception e) { } sf.open(); @@ -409,13 +386,11 @@ public abstract class SequentialFileFactoryTestBase extends ActiveMQTestBase // Private --------------------------------- - private ActiveMQBuffer wrapBuffer(final byte[] bytes) - { + private ActiveMQBuffer wrapBuffer(final byte[] bytes) { return ActiveMQBuffers.wrappedBuffer(bytes); } - protected void checkFill(final SequentialFile file, final int size) throws Exception - { + protected void checkFill(final SequentialFile file, final int size) throws Exception { file.fill(size); file.close(); @@ -430,8 +405,7 @@ public abstract class SequentialFileFactoryTestBase extends ActiveMQTestBase Assert.assertEquals(calculateRecordSize(size, file.getAlignment()), bytesRead); - for (int i = 0; i < size; i++) - { + for (int i = 0; i < size; i++) { // log.debug(" i is " + i); Assert.assertEquals(0, bb.get(i)); } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/TimedBufferTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/TimedBufferTest.java index 21866c6cf1..f80beed78c 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/TimedBufferTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/TimedBufferTest.java @@ -32,8 +32,7 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Assert; import org.junit.Test; -public class TimedBufferTest extends ActiveMQTestBase -{ +public class TimedBufferTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -47,28 +46,22 @@ public class TimedBufferTest extends ActiveMQTestBase // Public -------------------------------------------------------- - IOCallback dummyCallback = new IOCallback() - { + IOCallback dummyCallback = new IOCallback() { - public void done() - { + public void done() { } - public void onError(final int errorCode, final String errorMessage) - { + public void onError(final int errorCode, final String errorMessage) { } }; - @Test - public void testFillBuffer() - { + public void testFillBuffer() { final ArrayList buffers = new ArrayList(); final AtomicInteger flushTimes = new AtomicInteger(0); - class TestObserver implements TimedBufferObserver - { - public void flushBuffer(final ByteBuffer buffer, final boolean sync, final List callbacks) - { + class TestObserver implements TimedBufferObserver { + + public void flushBuffer(final ByteBuffer buffer, final boolean sync, final List callbacks) { buffers.add(buffer); flushTimes.incrementAndGet(); } @@ -76,13 +69,11 @@ public class TimedBufferTest extends ActiveMQTestBase /* (non-Javadoc) * @see org.apache.activemq.artemis.utils.timedbuffer.TimedBufferObserver#newBuffer(int, int) */ - public ByteBuffer newBuffer(final int minSize, final int maxSize) - { + public ByteBuffer newBuffer(final int minSize, final int maxSize) { return ByteBuffer.allocate(maxSize); } - public int getRemainingBytes() - { + public int getRemainingBytes() { return 1024 * 1024; } } @@ -91,17 +82,14 @@ public class TimedBufferTest extends ActiveMQTestBase timedBuffer.start(); - try - { + try { timedBuffer.setObserver(new TestObserver()); int x = 0; - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { byte[] bytes = new byte[10]; - for (int j = 0; j < 10; j++) - { + for (int j = 0; j < 10; j++) { bytes[j] = ActiveMQTestBase.getSamplebyte(x++); } @@ -123,27 +111,23 @@ public class TimedBufferTest extends ActiveMQTestBase flushedBuffer.rewind(); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), flushedBuffer.get()); } } - finally - { + finally { timedBuffer.stop(); } } @Test - public void testTimingAndFlush() throws Exception - { + public void testTimingAndFlush() throws Exception { final ArrayList buffers = new ArrayList(); final AtomicInteger flushTimes = new AtomicInteger(0); - class TestObserver implements TimedBufferObserver - { - public void flushBuffer(final ByteBuffer buffer, final boolean sync, final List callbacks) - { + class TestObserver implements TimedBufferObserver { + + public void flushBuffer(final ByteBuffer buffer, final boolean sync, final List callbacks) { buffers.add(buffer); flushTimes.incrementAndGet(); } @@ -151,13 +135,11 @@ public class TimedBufferTest extends ActiveMQTestBase /* (non-Javadoc) * @see org.apache.activemq.artemis.utils.timedbuffer.TimedBufferObserver#newBuffer(int, int) */ - public ByteBuffer newBuffer(final int minSize, final int maxSize) - { + public ByteBuffer newBuffer(final int minSize, final int maxSize) { return ByteBuffer.allocate(maxSize); } - public int getRemainingBytes() - { + public int getRemainingBytes() { return 1024 * 1024; } } @@ -166,16 +148,14 @@ public class TimedBufferTest extends ActiveMQTestBase timedBuffer.start(); - try - { + try { timedBuffer.setObserver(new TestObserver()); int x = 0; byte[] bytes = new byte[10]; - for (int j = 0; j < 10; j++) - { + for (int j = 0; j < 10; j++) { bytes[j] = ActiveMQTestBase.getSamplebyte(x++); } @@ -189,8 +169,7 @@ public class TimedBufferTest extends ActiveMQTestBase Assert.assertEquals(0, flushTimes.get()); bytes = new byte[10]; - for (int j = 0; j < 10; j++) - { + for (int j = 0; j < 10; j++) { bytes[j] = ActiveMQTestBase.getSamplebyte(x++); } @@ -211,13 +190,11 @@ public class TimedBufferTest extends ActiveMQTestBase flushedBuffer.rewind(); - for (int i = 0; i < 20; i++) - { + for (int i = 0; i < 20; i++) { Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), flushedBuffer.get()); } } - finally - { + finally { timedBuffer.stop(); } @@ -226,51 +203,44 @@ public class TimedBufferTest extends ActiveMQTestBase /** * This test will verify if the system will switch to spin case the system can't perform sleeps timely * due to proper kernel installations + * * @throws Exception */ @Test - public void testVerifySwitchToSpin() throws Exception - { - class TestObserver implements TimedBufferObserver - { - public void flushBuffer(final ByteBuffer buffer, final boolean sync, final List callbacks) - { + public void testVerifySwitchToSpin() throws Exception { + class TestObserver implements TimedBufferObserver { + + public void flushBuffer(final ByteBuffer buffer, final boolean sync, final List callbacks) { } /* (non-Javadoc) * @see org.apache.activemq.artemis.utils.timedbuffer.TimedBufferObserver#newBuffer(int, int) */ - public ByteBuffer newBuffer(final int minSize, final int maxSize) - { + public ByteBuffer newBuffer(final int minSize, final int maxSize) { return ByteBuffer.allocate(maxSize); } - public int getRemainingBytes() - { + public int getRemainingBytes() { return 1024 * 1024; } } final CountDownLatch sleptLatch = new CountDownLatch(1); - TimedBuffer timedBuffer = new TimedBuffer(100, TimedBufferTest.ONE_SECOND_IN_NANOS / 1000, false) - { + TimedBuffer timedBuffer = new TimedBuffer(100, TimedBufferTest.ONE_SECOND_IN_NANOS / 1000, false) { @Override - protected void stopSpin() - { + protected void stopSpin() { // keeps spinning forever } @Override - protected void sleep(int sleepMillis, int sleepNanos) throws InterruptedException - { + protected void sleep(int sleepMillis, int sleepNanos) throws InterruptedException { Thread.sleep(10); } @Override - public synchronized void setUseSleep(boolean param) - { + public synchronized void setUseSleep(boolean param) { super.setUseSleep(param); sleptLatch.countDown(); } @@ -279,16 +249,14 @@ public class TimedBufferTest extends ActiveMQTestBase timedBuffer.start(); - try - { + try { timedBuffer.setObserver(new TestObserver()); int x = 0; byte[] bytes = new byte[10]; - for (int j = 0; j < 10; j++) - { + for (int j = 0; j < 10; j++) { bytes[j] = ActiveMQTestBase.getSamplebyte(x++); } @@ -301,63 +269,54 @@ public class TimedBufferTest extends ActiveMQTestBase assertFalse(timedBuffer.isUseSleep()); } - finally - { + finally { timedBuffer.stop(); } } - /** * This test will verify if the system will switch to spin case the system can't perform sleeps timely * due to proper kernel installations + * * @throws Exception */ @Test - public void testStillSleeps() throws Exception - { - class TestObserver implements TimedBufferObserver - { - public void flushBuffer(final ByteBuffer buffer, final boolean sync, final List callbacks) - { + public void testStillSleeps() throws Exception { + class TestObserver implements TimedBufferObserver { + + public void flushBuffer(final ByteBuffer buffer, final boolean sync, final List callbacks) { } /* (non-Javadoc) * @see org.apache.activemq.artemis.utils.timedbuffer.TimedBufferObserver#newBuffer(int, int) */ - public ByteBuffer newBuffer(final int minSize, final int maxSize) - { + public ByteBuffer newBuffer(final int minSize, final int maxSize) { return ByteBuffer.allocate(maxSize); } - public int getRemainingBytes() - { + public int getRemainingBytes() { return 1024 * 1024; } } final CountDownLatch sleptLatch = new CountDownLatch(TimedBuffer.MAX_CHECKS_ON_SLEEP); - TimedBuffer timedBuffer = new TimedBuffer(100, TimedBufferTest.ONE_SECOND_IN_NANOS / 1000, false) - { + TimedBuffer timedBuffer = new TimedBuffer(100, TimedBufferTest.ONE_SECOND_IN_NANOS / 1000, false) { @Override - protected void stopSpin() - { + protected void stopSpin() { // keeps spinning forever } @Override - protected void sleep(int sleepMillis, int sleepNanos) throws InterruptedException - { + protected void sleep(int sleepMillis, int sleepNanos) throws InterruptedException { sleptLatch.countDown(); // no sleep } @Override - public synchronized void setUseSleep(boolean param) - { + public synchronized void setUseSleep(boolean param) { super.setUseSleep(param); sleptLatch.countDown(); } @@ -366,16 +325,14 @@ public class TimedBufferTest extends ActiveMQTestBase timedBuffer.start(); - try - { + try { timedBuffer.setObserver(new TestObserver()); int x = 0; byte[] bytes = new byte[10]; - for (int j = 0; j < 10; j++) - { + for (int j = 0; j < 10; j++) { bytes[j] = ActiveMQTestBase.getSamplebyte(x++); } @@ -392,8 +349,7 @@ public class TimedBufferTest extends ActiveMQTestBase assertTrue(timedBuffer.isUseSleep()); } - finally - { + finally { timedBuffer.stop(); } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/fakes/FakeSequentialFileFactory.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/fakes/FakeSequentialFileFactory.java index 75a95351c5..820c93c41b 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/fakes/FakeSequentialFileFactory.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/fakes/FakeSequentialFileFactory.java @@ -33,8 +33,7 @@ import org.apache.activemq.artemis.core.io.SequentialFile; import org.apache.activemq.artemis.core.io.SequentialFileFactory; import org.apache.activemq.artemis.core.io.buffer.TimedBuffer; -public class FakeSequentialFileFactory implements SequentialFileFactory -{ +public class FakeSequentialFileFactory implements SequentialFileFactory { private final Map fileMap = new ConcurrentHashMap(); @@ -50,39 +49,32 @@ public class FakeSequentialFileFactory implements SequentialFileFactory private final List callbacksInHold; - public FakeSequentialFileFactory(final int alignment, final boolean supportsCallback) - { + public FakeSequentialFileFactory(final int alignment, final boolean supportsCallback) { this.alignment = alignment; this.supportsCallback = supportsCallback; callbacksInHold = new ArrayList(); } - public FakeSequentialFileFactory() - { + public FakeSequentialFileFactory() { this(1, false); } @Override - public int getMaxIO() - { + public int getMaxIO() { return 1; } - // Public -------------------------------------------------------- - public SequentialFile createSequentialFile(final String fileName) - { + public SequentialFile createSequentialFile(final String fileName) { FakeSequentialFile sf = fileMap.get(fileName); - if (sf == null || sf.data == null) - { + if (sf == null || sf.data == null) { sf = newSequentialFile(fileName); fileMap.put(fileName, sf); } - else - { + else { sf.getData().position(0); // log.debug("positioning data to 0"); @@ -91,27 +83,22 @@ public class FakeSequentialFileFactory implements SequentialFileFactory return sf; } - public void clearBuffer(final ByteBuffer buffer) - { + public void clearBuffer(final ByteBuffer buffer) { final int limit = buffer.limit(); buffer.rewind(); - for (int i = 0; i < limit; i++) - { + for (int i = 0; i < limit; i++) { buffer.put((byte) 0); } buffer.rewind(); } - public List listFiles(final String extension) - { + public List listFiles(final String extension) { List files = new ArrayList(); - for (String s : fileMap.keySet()) - { - if (s.endsWith("." + extension)) - { + for (String s : fileMap.keySet()) { + if (s.endsWith("." + extension)) { files.add(s); } } @@ -119,32 +106,26 @@ public class FakeSequentialFileFactory implements SequentialFileFactory return files; } - public Map getFileMap() - { + public Map getFileMap() { return fileMap; } - public void clear() - { + public void clear() { fileMap.clear(); } - public boolean isSupportsCallbacks() - { + public boolean isSupportsCallbacks() { return supportsCallback; } - public ByteBuffer newBuffer(int size) - { - if (size % alignment != 0) - { + public ByteBuffer newBuffer(int size) { + if (size % alignment != 0) { size = (size / alignment + 1) * alignment; } return ByteBuffer.allocate(size); } - public int calculateBlockSize(final int position) - { + public int calculateBlockSize(final int position) { int alignment = getAlignment(); int pos = (position / alignment + (position % alignment != 0 ? 1 : 0)) * alignment; @@ -152,62 +133,51 @@ public class FakeSequentialFileFactory implements SequentialFileFactory return pos; } - public ByteBuffer wrapBuffer(final byte[] bytes) - { + public ByteBuffer wrapBuffer(final byte[] bytes) { return ByteBuffer.wrap(bytes); } - public synchronized boolean isHoldCallbacks() - { + public synchronized boolean isHoldCallbacks() { return holdCallbacks; } public synchronized void setHoldCallbacks(final boolean holdCallbacks, - final ListenerHoldCallback holdCallbackListener) - { + final ListenerHoldCallback holdCallbackListener) { this.holdCallbacks = holdCallbacks; this.holdCallbackListener = holdCallbackListener; } - public boolean isGenerateErrors() - { + public boolean isGenerateErrors() { return generateErrors; } - public void setGenerateErrors(final boolean generateErrors) - { + public void setGenerateErrors(final boolean generateErrors) { this.generateErrors = generateErrors; } - public synchronized void flushAllCallbacks() - { - for (Runnable action : callbacksInHold) - { + public synchronized void flushAllCallbacks() { + for (Runnable action : callbacksInHold) { action.run(); } callbacksInHold.clear(); } - public synchronized void flushCallback(final int position) - { + public synchronized void flushCallback(final int position) { Runnable run = callbacksInHold.get(position); run.run(); callbacksInHold.remove(run); } - public synchronized void setCallbackAsError(final int position) - { + public synchronized void setCallbackAsError(final int position) { callbacksInHold.get(position).setSendError(true); } - public synchronized int getNumberOfCallbacks() - { + public synchronized int getNumberOfCallbacks() { return callbacksInHold.size(); } - public int getAlignment() - { + public int getAlignment() { return alignment; } @@ -215,8 +185,7 @@ public class FakeSequentialFileFactory implements SequentialFileFactory // Protected ----------------------------------------------------- - protected FakeSequentialFile newSequentialFile(final String fileName) - { + protected FakeSequentialFile newSequentialFile(final String fileName) { return new FakeSequentialFile(fileName); } @@ -227,13 +196,12 @@ public class FakeSequentialFileFactory implements SequentialFileFactory /** * This listener will return a message to the test with each callback added */ - public interface ListenerHoldCallback - { + public interface ListenerHoldCallback { + void callbackAdded(final ByteBuffer bytes); } - private class CallbackRunnable implements Runnable - { + private class CallbackRunnable implements Runnable { final FakeSequentialFile file; @@ -243,113 +211,92 @@ public class FakeSequentialFileFactory implements SequentialFileFactory volatile boolean sendError; - CallbackRunnable(final FakeSequentialFile file, final ByteBuffer bytes, final IOCallback callback) - { + CallbackRunnable(final FakeSequentialFile file, final ByteBuffer bytes, final IOCallback callback) { this.file = file; this.bytes = bytes; this.callback = callback; } - public void run() - { + public void run() { - if (sendError) - { + if (sendError) { callback.onError(ActiveMQExceptionType.UNSUPPORTED_PACKET.getCode(), "Fake aio error"); } - else - { - try - { + else { + try { file.data.put(bytes); - if (callback != null) - { + if (callback != null) { callback.done(); } } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); callback.onError(ActiveMQExceptionType.GENERIC_EXCEPTION.getCode(), e.getMessage()); } } } - public void setSendError(final boolean sendError) - { + public void setSendError(final boolean sendError) { this.sendError = sendError; } } - public class FakeSequentialFile implements SequentialFile - { + public class FakeSequentialFile implements SequentialFile { + private volatile boolean open; private String fileName; private ByteBuffer data; - public ByteBuffer getData() - { + public ByteBuffer getData() { return data; } - public boolean isOpen() - { + public boolean isOpen() { return open; } - public void flush() - { + public void flush() { } - public FakeSequentialFile(final String fileName) - { + public FakeSequentialFile(final String fileName) { this.fileName = fileName; } - public synchronized void close() - { + public synchronized void close() { open = false; - if (data != null) - { + if (data != null) { data.position(0); } notifyAll(); } - public void delete() - { - if (open) - { + public void delete() { + if (open) { close(); } fileMap.remove(fileName); } - public String getFileName() - { + public String getFileName() { return fileName; } - public void open() throws Exception - { + public void open() throws Exception { open(1, true); } - public synchronized void open(final int currentMaxIO, final boolean useExecutor) throws Exception - { + public synchronized void open(final int currentMaxIO, final boolean useExecutor) throws Exception { open = true; checkAndResize(0); } - public void fill(final int size) throws Exception - { - if (!open) - { + public void fill(final int size) throws Exception { + if (!open) { throw new IllegalStateException("Is closed"); } @@ -357,8 +304,7 @@ public class FakeSequentialFileFactory implements SequentialFileFactory // log.debug("size is " + size + " pos is " + pos); - for (int i = 0; i < size; i++) - { + for (int i = 0; i < size; i++) { byte[] array = data.array(); array[i] = 0; @@ -366,15 +312,12 @@ public class FakeSequentialFileFactory implements SequentialFileFactory } } - public int read(final ByteBuffer bytes) throws Exception - { + public int read(final ByteBuffer bytes) throws Exception { return read(bytes, null); } - public int read(final ByteBuffer bytes, final IOCallback callback) throws Exception - { - if (!open) - { + public int read(final ByteBuffer bytes, final IOCallback callback) throws Exception { + if (!open) { throw new IllegalStateException("Is closed"); } @@ -386,8 +329,7 @@ public class FakeSequentialFileFactory implements SequentialFileFactory bytes.rewind(); - if (callback != null) - { + if (callback != null) { callback.done(); } @@ -395,10 +337,8 @@ public class FakeSequentialFileFactory implements SequentialFileFactory } @Override - public void position(final long pos) - { - if (!open) - { + public void position(final long pos) { + if (!open) { throw new IllegalStateException("Is closed"); } @@ -407,15 +347,12 @@ public class FakeSequentialFileFactory implements SequentialFileFactory data.position((int) pos); } - public long position() - { + public long position() { return data.position(); } - public synchronized void writeDirect(final ByteBuffer bytes, final boolean sync, final IOCallback callback) - { - if (!open) - { + public synchronized void writeDirect(final ByteBuffer bytes, final boolean sync, final IOCallback callback) { + if (!open) { throw new IllegalStateException("Is closed"); } @@ -429,66 +366,52 @@ public class FakeSequentialFileFactory implements SequentialFileFactory CallbackRunnable action = new CallbackRunnable(this, bytes, callback); - if (generateErrors) - { + if (generateErrors) { action.setSendError(true); } - if (holdCallbacks) - { + if (holdCallbacks) { addCallback(bytes, action); } - else - { + else { action.run(); } } - public void sync() throws IOException - { - if (supportsCallback) - { + public void sync() throws IOException { + if (supportsCallback) { throw new IllegalStateException("sync is not supported when supportsCallback=true"); } } - public long size() throws Exception - { - if (data == null) - { + public long size() throws Exception { + if (data == null) { return 0; } - else - { + else { return data.limit(); } } - public void writeDirect(final ByteBuffer bytes, final boolean sync) throws Exception - { + public void writeDirect(final ByteBuffer bytes, final boolean sync) throws Exception { writeDirect(bytes, sync, null); } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.io.SequentialFile#writeInternal(java.nio.ByteBuffer) */ - public void writeInternal(ByteBuffer bytes) throws Exception - { + public void writeInternal(ByteBuffer bytes) throws Exception { writeDirect(bytes, true); } - - private void checkAndResize(final int size) - { + private void checkAndResize(final int size) { int oldpos = data == null ? 0 : data.position(); - if (data == null || data.array().length < size) - { + if (data == null || data.array().length < size) { byte[] newBytes = new byte[size]; - if (data != null) - { + if (data != null) { System.arraycopy(data.array(), 0, newBytes, 0, data.array().length); } @@ -502,40 +425,32 @@ public class FakeSequentialFileFactory implements SequentialFileFactory * @param bytes * @param action */ - private void addCallback(final ByteBuffer bytes, final CallbackRunnable action) - { - synchronized (FakeSequentialFileFactory.this) - { + private void addCallback(final ByteBuffer bytes, final CallbackRunnable action) { + synchronized (FakeSequentialFileFactory.this) { callbacksInHold.add(action); - if (holdCallbackListener != null) - { + if (holdCallbackListener != null) { holdCallbackListener.callbackAdded(bytes); } } } - public int getAlignment() throws Exception - { + public int getAlignment() throws Exception { return alignment; } - public int calculateBlockStart(final int position) throws Exception - { + public int calculateBlockStart(final int position) throws Exception { int pos = (position / alignment + (position % alignment != 0 ? 1 : 0)) * alignment; return pos; } @Override - public String toString() - { + public String toString() { return "FakeSequentialFile:" + fileName; } - private void checkAlignment(final long position) - { - if (position % alignment != 0) - { + private void checkAlignment(final long position) { + if (position % alignment != 0) { throw new IllegalStateException("Position is not aligned to " + alignment); } } @@ -543,8 +458,7 @@ public class FakeSequentialFileFactory implements SequentialFileFactory /* (non-Javadoc) * @see org.apache.activemq.artemis.core.io.SequentialFile#renameTo(org.apache.activemq.artemis.core.io.SequentialFile) */ - public void renameTo(final String newFileName) throws Exception - { + public void renameTo(final String newFileName) throws Exception { fileMap.remove(fileName); fileName = newFileName; fileMap.put(newFileName, this); @@ -553,42 +467,36 @@ public class FakeSequentialFileFactory implements SequentialFileFactory /* (non-Javadoc) * @see org.apache.activemq.artemis.core.io.SequentialFile#fits(int) */ - public boolean fits(final int size) - { + public boolean fits(final int size) { return data.position() + size <= data.limit(); } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.io.SequentialFile#setBuffering(boolean) */ - public void setBuffering(final boolean buffering) - { + public void setBuffering(final boolean buffering) { } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.io.SequentialFile#lockBuffer() */ - public void disableAutoFlush() - { + public void disableAutoFlush() { } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.io.SequentialFile#unlockBuffer() */ - public void enableAutoFlush() - { + public void enableAutoFlush() { } - public SequentialFile cloneFile() - { + public SequentialFile cloneFile() { return null; // To change body of implemented methods use File | Settings | File Templates. } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.io.SequentialFile#write(org.apache.activemq.artemis.spi.core.remoting.ActiveMQBuffer, boolean, org.apache.activemq.artemis.core.journal.IOCallback) */ - public void write(final ActiveMQBuffer bytes, final boolean sync, final IOCallback callback) throws Exception - { + public void write(final ActiveMQBuffer bytes, final boolean sync, final IOCallback callback) throws Exception { bytes.writerIndex(bytes.capacity()); bytes.readerIndex(0); writeDirect(bytes.toByteBuffer(), sync, callback); @@ -598,8 +506,7 @@ public class FakeSequentialFileFactory implements SequentialFileFactory /* (non-Javadoc) * @see org.apache.activemq.artemis.core.io.SequentialFile#write(org.apache.activemq.artemis.spi.core.remoting.ActiveMQBuffer, boolean) */ - public void write(final ActiveMQBuffer bytes, final boolean sync) throws Exception - { + public void write(final ActiveMQBuffer bytes, final boolean sync) throws Exception { bytes.writerIndex(bytes.capacity()); bytes.readerIndex(0); writeDirect(bytes.toByteBuffer(), sync); @@ -608,8 +515,7 @@ public class FakeSequentialFileFactory implements SequentialFileFactory /* (non-Javadoc) * @see org.apache.activemq.artemis.core.io.SequentialFile#write(org.apache.activemq.artemis.core.journal.EncodingSupport, boolean, org.apache.activemq.artemis.core.journal.IOCompletion) */ - public void write(final EncodingSupport bytes, final boolean sync, final IOCallback callback) throws Exception - { + public void write(final EncodingSupport bytes, final boolean sync, final IOCallback callback) throws Exception { ByteBuffer buffer = newBuffer(bytes.getEncodeSize()); ActiveMQBuffer outbuffer = ActiveMQBuffers.wrappedBuffer(buffer); bytes.encode(outbuffer); @@ -619,8 +525,7 @@ public class FakeSequentialFileFactory implements SequentialFileFactory /* (non-Javadoc) * @see org.apache.activemq.artemis.core.io.SequentialFile#write(org.apache.activemq.artemis.core.journal.EncodingSupport, boolean) */ - public void write(final EncodingSupport bytes, final boolean sync) throws Exception - { + public void write(final EncodingSupport bytes, final boolean sync) throws Exception { ByteBuffer buffer = newBuffer(bytes.getEncodeSize()); ActiveMQBuffer outbuffer = ActiveMQBuffers.wrappedBuffer(buffer); bytes.encode(outbuffer); @@ -630,8 +535,7 @@ public class FakeSequentialFileFactory implements SequentialFileFactory /* (non-Javadoc) * @see org.apache.activemq.artemis.core.io.SequentialFile#exists() */ - public boolean exists() - { + public boolean exists() { FakeSequentialFile file = fileMap.get(fileName); return file != null && file.data != null && file.data.capacity() > 0; @@ -640,82 +544,68 @@ public class FakeSequentialFileFactory implements SequentialFileFactory /* (non-Javadoc) * @see org.apache.activemq.artemis.core.io.SequentialFile#setTimedBuffer(org.apache.activemq.artemis.core.io.buffer.TimedBuffer) */ - public void setTimedBuffer(final TimedBuffer buffer) - { + public void setTimedBuffer(final TimedBuffer buffer) { } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.io.SequentialFile#copyTo(org.apache.activemq.artemis.core.io.SequentialFile) */ - public void copyTo(SequentialFile newFileName) - { + public void copyTo(SequentialFile newFileName) { // TODO Auto-generated method stub } @Override - public File getJavaFile() - { + public File getJavaFile() { throw new UnsupportedOperationException(); } } @Override - public void createDirs() throws Exception - { + public void createDirs() throws Exception { // nothing to be done on the fake Sequential file } @Override - public void releaseBuffer(final ByteBuffer buffer) - { + public void releaseBuffer(final ByteBuffer buffer) { } @Override - public void stop() - { + public void stop() { } @Override - public void activateBuffer(final SequentialFile file) - { + public void activateBuffer(final SequentialFile file) { } @Override - public void start() - { + public void start() { } @Override - public void deactivateBuffer() - { + public void deactivateBuffer() { } @Override - public void flush() - { + public void flush() { } @Override - public void onIOError(Exception exception, String message, SequentialFile file) - { + public void onIOError(Exception exception, String message, SequentialFile file) { } @Override - public ByteBuffer allocateDirectBuffer(int size) - { + public ByteBuffer allocateDirectBuffer(int size) { return ByteBuffer.allocateDirect(size); } @Override - public void releaseDirectBuffer(ByteBuffer buffer) - { + public void releaseDirectBuffer(ByteBuffer buffer) { } @Override - public File getDirectory() - { + public File getDirectory() { // TODO Auto-generated method stub return null; } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/fakes/SimpleEncoding.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/fakes/SimpleEncoding.java index 1e90c077b6..87acb21f77 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/fakes/SimpleEncoding.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/fakes/SimpleEncoding.java @@ -22,8 +22,7 @@ import org.apache.activemq.artemis.core.journal.EncodingSupport; /** * Provides a SimpleEncoding with a Fake Payload */ -public class SimpleEncoding implements EncodingSupport -{ +public class SimpleEncoding implements EncodingSupport { // Constants ----------------------------------------------------- @@ -36,29 +35,24 @@ public class SimpleEncoding implements EncodingSupport // Constructors -------------------------------------------------- - public SimpleEncoding(final int size, final byte bytetosend) - { + public SimpleEncoding(final int size, final byte bytetosend) { this.size = size; this.bytetosend = bytetosend; } // Public -------------------------------------------------------- - public void decode(final ActiveMQBuffer buffer) - { + public void decode(final ActiveMQBuffer buffer) { throw new UnsupportedOperationException(); } - public void encode(final ActiveMQBuffer buffer) - { - for (int i = 0; i < size; i++) - { + public void encode(final ActiveMQBuffer buffer) { + for (int i = 0; i < size; i++) { buffer.writeByte(bytetosend); } } - public int getEncodeSize() - { + public int getEncodeSize() { return size; } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/message/impl/MessageImplTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/message/impl/MessageImplTest.java index a2ebd6c6c2..18f37e6ccb 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/message/impl/MessageImplTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/message/impl/MessageImplTest.java @@ -31,16 +31,13 @@ import org.apache.activemq.artemis.tests.util.RandomUtil; import org.junit.Assert; import org.junit.Test; -public class MessageImplTest extends ActiveMQTestBase -{ +public class MessageImplTest extends ActiveMQTestBase { + @Test - public void getSetAttributes() - { - for (int j = 0; j < 10; j++) - { + public void getSetAttributes() { + for (int j = 0; j < 10; j++) { byte[] bytes = new byte[1000]; - for (int i = 0; i < bytes.length; i++) - { + for (int i = 0; i < bytes.length; i++) { bytes[i] = RandomUtil.randomByte(); } @@ -84,8 +81,7 @@ public class MessageImplTest extends ActiveMQTestBase } @Test - public void testExpired() - { + public void testExpired() { Message message = new ClientMessageImpl(); Assert.assertEquals(0, message.getExpiration()); @@ -105,10 +101,8 @@ public class MessageImplTest extends ActiveMQTestBase } @Test - public void testProperties() - { - for (int j = 0; j < 10; j++) - { + public void testProperties() { + for (int j = 0; j < 10; j++) { Message msg = new ClientMessageImpl(); SimpleString prop1 = new SimpleString("prop1"); @@ -228,17 +222,15 @@ public class MessageImplTest extends ActiveMQTestBase } @Test - public void testMessageCopyIssue() throws Exception - { - for (long i = 0; i < 300; i++) - { - if (i % 10 == 0) System.out.println("#test " + i); + public void testMessageCopyIssue() throws Exception { + for (long i = 0; i < 300; i++) { + if (i % 10 == 0) + System.out.println("#test " + i); internalMessageCopy(); } } - private void internalMessageCopy() throws Exception - { + private void internalMessageCopy() throws Exception { final long RUNS = 2; final ServerMessageImpl msg = new ServerMessageImpl(123, 18); @@ -253,28 +245,22 @@ public class MessageImplTest extends ActiveMQTestBase final CountDownLatch latchAlign = new CountDownLatch(T1_number + T2_number); final CountDownLatch latchReady = new CountDownLatch(1); - class T1 extends Thread - { + class T1 extends Thread { + @Override - public void run() - { + public void run() { latchAlign.countDown(); - try - { + try { latchReady.await(); } - catch (Exception ignored) - { + catch (Exception ignored) { } - for (int i = 0; i < RUNS; i++) - { - try - { + for (int i = 0; i < RUNS; i++) { + try { ServerMessageImpl newMsg = (ServerMessageImpl) msg.copy(); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); errors.incrementAndGet(); } @@ -285,38 +271,30 @@ public class MessageImplTest extends ActiveMQTestBase final String bigString; { StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < 500; i++) - { + for (int i = 0; i < 500; i++) { buffer.append(" "); } bigString = buffer.toString(); } + class T2 extends Thread { - class T2 extends Thread - { @Override - public void run() - { + public void run() { latchAlign.countDown(); - try - { + try { latchReady.await(); } - catch (Exception ignored) - { + catch (Exception ignored) { } - for (int i = 0; i < RUNS; i++) - { - try - { + for (int i = 0; i < RUNS; i++) { + try { SessionSendMessage ssm = new SessionSendMessage(msg); ActiveMQBuffer buf = ssm.encode(null); simulateRead(buf); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); errors.incrementAndGet(); } @@ -324,18 +302,15 @@ public class MessageImplTest extends ActiveMQTestBase } } - ArrayList threads = new ArrayList(); - for (int i = 0; i < T1_number; i++) - { + for (int i = 0; i < T1_number; i++) { T1 t = new T1(); threads.add(t); t.start(); } - for (int i = 0; i < T2_number; i++) - { + for (int i = 0; i < T2_number; i++) { T2 t2 = new T2(); threads.add(t2); t2.start(); @@ -345,17 +320,14 @@ public class MessageImplTest extends ActiveMQTestBase latchReady.countDown(); - for (Thread t : threads) - { + for (Thread t : threads) { t.join(); } Assert.assertEquals(0, errors.get()); } - - private void simulateRead(ActiveMQBuffer buf) - { + private void simulateRead(ActiveMQBuffer buf) { buf.setIndex(buf.capacity() / 2, buf.capacity() / 2); // ok this is not actually happening during the read process, but changing this shouldn't affect the buffer on copy @@ -363,7 +335,6 @@ public class MessageImplTest extends ActiveMQTestBase buf.writeBytes(new byte[1024]); } - // Protected ------------------------------------------------------------------------------- // Private ---------------------------------------------------------------------------------- diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PagePositionTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PagePositionTest.java index 550846ec50..755e41c938 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PagePositionTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PagePositionTest.java @@ -19,8 +19,7 @@ package org.apache.activemq.artemis.tests.unit.core.paging.impl; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Test; -public class PagePositionTest extends ActiveMQTestBase -{ +public class PagePositionTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -33,8 +32,7 @@ public class PagePositionTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testNextSequenceOf() - { + public void testNextSequenceOf() { } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PageTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PageTest.java index 5accdac05e..aa06ea02d1 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PageTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PageTest.java @@ -36,8 +36,7 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Assert; import org.junit.Test; -public class PageTest extends ActiveMQTestBase -{ +public class PageTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -49,22 +48,19 @@ public class PageTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testPageWithNIO() throws Exception - { + public void testPageWithNIO() throws Exception { recreateDirectory(getTestDir()); testAdd(new NIOSequentialFileFactory(getTestDirfile(), 1), 1000); } @Test - public void testDamagedDataWithNIO() throws Exception - { + public void testDamagedDataWithNIO() throws Exception { recreateDirectory(getTestDir()); testDamagedPage(new NIOSequentialFileFactory(getTestDirfile(), 1), 1000); } @Test - public void testPageFakeWithoutCallbacks() throws Exception - { + public void testPageFakeWithoutCallbacks() throws Exception { testAdd(new FakeSequentialFileFactory(1, false), 10); } @@ -72,16 +68,14 @@ public class PageTest extends ActiveMQTestBase * Validate if everything we add is recovered */ @Test - public void testDamagedPage() throws Exception - { + public void testDamagedPage() throws Exception { testDamagedPage(new FakeSequentialFileFactory(1, false), 100); } /** * Validate if everything we add is recovered */ - protected void testAdd(final SequentialFileFactory factory, final int numberOfElements) throws Exception - { + protected void testAdd(final SequentialFileFactory factory, final int numberOfElements) throws Exception { SequentialFile file = factory.createSequentialFile("00010.page"); @@ -110,15 +104,10 @@ public class PageTest extends ActiveMQTestBase Assert.assertEquals(numberOfElements, impl.getNumberOfMessages()); - for (int i = 0; i < msgs.size(); i++) - { + for (int i = 0; i < msgs.size(); i++) { Assert.assertEquals(simpleDestination, msgs.get(i).getMessage().getAddress()); - ActiveMQTestBase.assertEqualsByteArrays(buffers.get(i).toByteBuffer().array(), msgs.get(i) - .getMessage() - .getBodyBuffer() - .toByteBuffer() - .array()); + ActiveMQTestBase.assertEqualsByteArrays(buffers.get(i).toByteBuffer().array(), msgs.get(i).getMessage().getBodyBuffer().toByteBuffer().array()); } impl.delete(null); @@ -127,8 +116,7 @@ public class PageTest extends ActiveMQTestBase } - protected void testDamagedPage(final SequentialFileFactory factory, final int numberOfElements) throws Exception - { + protected void testDamagedPage(final SequentialFileFactory factory, final int numberOfElements) throws Exception { SequentialFile file = factory.createSequentialFile("00010.page"); @@ -161,8 +149,7 @@ public class PageTest extends ActiveMQTestBase ByteBuffer buffer = ByteBuffer.allocate((int) (positionB - file.position())); - for (int i = 0; i < buffer.capacity(); i++) - { + for (int i = 0; i < buffer.capacity(); i++) { buffer.put((byte) 'Z'); } @@ -182,15 +169,10 @@ public class PageTest extends ActiveMQTestBase Assert.assertEquals(numberOfElements, impl.getNumberOfMessages()); - for (int i = 0; i < msgs.size(); i++) - { + for (int i = 0; i < msgs.size(); i++) { Assert.assertEquals(simpleDestination, msgs.get(i).getMessage().getAddress()); - ActiveMQTestBase.assertEqualsByteArrays(buffers.get(i).toByteBuffer().array(), msgs.get(i) - .getMessage() - .getBodyBuffer() - .toByteBuffer() - .array()); + ActiveMQTestBase.assertEqualsByteArrays(buffers.get(i).toByteBuffer().array(), msgs.get(i).getMessage().getBodyBuffer().toByteBuffer().array()); } impl.delete(null); @@ -209,19 +191,16 @@ public class PageTest extends ActiveMQTestBase * @throws Exception */ protected ArrayList addPageElements(final SimpleString simpleDestination, - final Page page, - final int numberOfElements) throws Exception - { + final Page page, + final int numberOfElements) throws Exception { ArrayList buffers = new ArrayList(); int initialNumberOfMessages = page.getNumberOfMessages(); - for (int i = 0; i < numberOfElements; i++) - { + for (int i = 0; i < numberOfElements; i++) { ServerMessage msg = new ServerMessageImpl(i, 100); - for (int j = 0; j < 10; j++) - { + for (int j = 0; j < 10; j++) { msg.getBodyBuffer().writeByte((byte) 'b'); } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PagingManagerImplTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PagingManagerImplTest.java index 96499665a0..5f2175376b 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PagingManagerImplTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PagingManagerImplTest.java @@ -43,21 +43,19 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class PagingManagerImplTest extends ActiveMQTestBase -{ +public class PagingManagerImplTest extends ActiveMQTestBase { + private final ReadLock lock = new ReentrantReadWriteLock().readLock(); @Test - public void testPagingManager() throws Exception - { + public void testPagingManager() throws Exception { HierarchicalRepository addressSettings = new HierarchicalObjectRepository(); addressSettings.setDefault(new AddressSettings().setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE)); final StorageManager storageManager = new NullStorageManager(); - PagingStoreFactoryNIO storeFactory = - new PagingStoreFactoryNIO(storageManager, getPageDirFile(), 100, null, getOrderedExecutor(), true, null); + PagingStoreFactoryNIO storeFactory = new PagingStoreFactoryNIO(storageManager, getPageDirFile(), 100, null, getOrderedExecutor(), true, null); PagingManagerImpl managerImpl = new PagingManagerImpl(storeFactory, addressSettings); @@ -84,11 +82,7 @@ public class PagingManagerImplTest extends ActiveMQTestBase Assert.assertEquals(1, msgs.size()); - ActiveMQTestBase.assertEqualsByteArrays(msg.getBodyBuffer().writerIndex(), msg.getBodyBuffer().toByteBuffer().array(), msgs.get(0) - .getMessage() - .getBodyBuffer() - .toByteBuffer() - .array()); + ActiveMQTestBase.assertEqualsByteArrays(msg.getBodyBuffer().writerIndex(), msg.getBodyBuffer().toByteBuffer().array(), msgs.get(0).getMessage().getBodyBuffer().toByteBuffer().array()); Assert.assertTrue(store.isPaging()); @@ -101,8 +95,7 @@ public class PagingManagerImplTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); File fileJournalDir = new File(getJournalDir()); fileJournalDir.mkdirs(); @@ -111,8 +104,9 @@ public class PagingManagerImplTest extends ActiveMQTestBase pageDirDir.mkdirs(); } - protected ServerMessage createMessage(final long messageId, final SimpleString destination, final ByteBuffer buffer) - { + protected ServerMessage createMessage(final long messageId, + final SimpleString destination, + final ByteBuffer buffer) { ServerMessage msg = new ServerMessageImpl(messageId, 200); msg.setAddress(destination); @@ -122,12 +116,10 @@ public class PagingManagerImplTest extends ActiveMQTestBase return msg; } - protected ByteBuffer createRandomBuffer(final int size) - { + protected ByteBuffer createRandomBuffer(final int size) { ByteBuffer buffer = ByteBuffer.allocate(size); - for (int j = 0; j < buffer.limit(); j++) - { + for (int j = 0; j < buffer.limit(); j++) { buffer.put(RandomUtil.randomByte()); } return buffer; diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PagingStoreImplTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PagingStoreImplTest.java index 3863c128cb..13908b07d7 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PagingStoreImplTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PagingStoreImplTest.java @@ -63,18 +63,15 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class PagingStoreImplTest extends ActiveMQTestBase -{ +public class PagingStoreImplTest extends ActiveMQTestBase { private static final SimpleString destinationTestName = new SimpleString("test"); private final ReadLock lock = new ReentrantReadWriteLock().readLock(); protected ExecutorService executor; - @Test - public void testAddAndRemoveMessages() - { + public void testAddAndRemoveMessages() { long id1 = RandomUtil.randomLong(); long id2 = RandomUtil.randomLong(); PageTransactionInfo trans = new PageTransactionInfoImpl(id2); @@ -84,8 +81,7 @@ public class PagingStoreImplTest extends ActiveMQTestBase // anything between 2 and 100 int nr1 = RandomUtil.randomPositiveInt() % 98 + 2; - for (int i = 0; i < nr1; i++) - { + for (int i = 0; i < nr1; i++) { trans.increment(1, 0); } @@ -105,14 +101,10 @@ public class PagingStoreImplTest extends ActiveMQTestBase } @Test - public void testDoubleStart() throws Exception - { + public void testDoubleStart() throws Exception { SequentialFileFactory factory = new FakeSequentialFileFactory(); - PagingStore storeImpl = - new PagingStoreImpl(PagingStoreImplTest.destinationTestName, null, 100, createMockManager(), - createStorageManagerMock(), factory, null, PagingStoreImplTest.destinationTestName, - new AddressSettings().setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE), getExecutorFactory().getExecutor(), true); + PagingStore storeImpl = new PagingStoreImpl(PagingStoreImplTest.destinationTestName, null, 100, createMockManager(), createStorageManagerMock(), factory, null, PagingStoreImplTest.destinationTestName, new AddressSettings().setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE), getExecutorFactory().getExecutor(), true); storeImpl.start(); @@ -126,26 +118,20 @@ public class PagingStoreImplTest extends ActiveMQTestBase } @Test - public void testPageWithNIO() throws Exception - { + public void testPageWithNIO() throws Exception { ActiveMQTestBase.recreateDirectory(getTestDir()); testConcurrentPaging(new NIOSequentialFileFactory(new File(getTestDir()), 1), 1); } @Test - public void testStore() throws Exception - { + public void testStore() throws Exception { SequentialFileFactory factory = new FakeSequentialFileFactory(); PagingStoreFactory storeFactory = new FakeStoreFactory(factory); AddressSettings addressSettings = new AddressSettings().setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE); - PagingStore storeImpl = - new PagingStoreImpl(PagingStoreImplTest.destinationTestName, null, 100, createMockManager(), - createStorageManagerMock(), factory, storeFactory, - PagingStoreImplTest.destinationTestName, addressSettings, - getExecutorFactory().getExecutor(), true); + PagingStore storeImpl = new PagingStoreImpl(PagingStoreImplTest.destinationTestName, null, 100, createMockManager(), createStorageManagerMock(), factory, storeFactory, PagingStoreImplTest.destinationTestName, addressSettings, getExecutorFactory().getExecutor(), true); storeImpl.start(); @@ -173,10 +159,7 @@ public class PagingStoreImplTest extends ActiveMQTestBase storeImpl.sync(); - storeImpl = - new PagingStoreImpl(PagingStoreImplTest.destinationTestName, null, 100, createMockManager(), - createStorageManagerMock(), factory, null, PagingStoreImplTest.destinationTestName, - addressSettings, getExecutorFactory().getExecutor(), true); + storeImpl = new PagingStoreImpl(PagingStoreImplTest.destinationTestName, null, 100, createMockManager(), createStorageManagerMock(), factory, null, PagingStoreImplTest.destinationTestName, addressSettings, getExecutorFactory().getExecutor(), true); storeImpl.start(); @@ -185,19 +168,14 @@ public class PagingStoreImplTest extends ActiveMQTestBase } @Test - public void testDepageOnCurrentPage() throws Exception - { + public void testDepageOnCurrentPage() throws Exception { SequentialFileFactory factory = new FakeSequentialFileFactory(); SimpleString destination = new SimpleString("test"); PagingStoreFactory storeFactory = new FakeStoreFactory(factory); - PagingStoreImpl storeImpl = - new PagingStoreImpl(PagingStoreImplTest.destinationTestName, null, 100, createMockManager(), - createStorageManagerMock(), factory, storeFactory, - PagingStoreImplTest.destinationTestName, new AddressSettings().setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE), - getExecutorFactory().getExecutor(), true); + PagingStoreImpl storeImpl = new PagingStoreImpl(PagingStoreImplTest.destinationTestName, null, 100, createMockManager(), createStorageManagerMock(), factory, storeFactory, PagingStoreImplTest.destinationTestName, new AddressSettings().setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE), getExecutorFactory().getExecutor(), true); storeImpl.start(); @@ -209,8 +187,7 @@ public class PagingStoreImplTest extends ActiveMQTestBase int numMessages = 10; - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ActiveMQBuffer buffer = createRandomBuffer(i + 1L, 10); @@ -218,8 +195,7 @@ public class PagingStoreImplTest extends ActiveMQTestBase ServerMessage msg = createMessage(i, storeImpl, destination, buffer); final RoutingContextImpl ctx = new RoutingContextImpl(null); - Assert.assertTrue(storeImpl.page(msg, ctx.getTransaction(), ctx.getContextListing(storeImpl.getStoreName()), - lock)); + Assert.assertTrue(storeImpl.page(msg, ctx.getTransaction(), ctx.getContextListing(storeImpl.getStoreName()), lock)); } @@ -242,14 +218,12 @@ public class PagingStoreImplTest extends ActiveMQTestBase Assert.assertEquals(0, storeImpl.getNumberOfPages()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { ActiveMQBuffer horn1 = buffers.get(i); ActiveMQBuffer horn2 = msg.get(i).getMessage().getBodyBuffer(); horn1.resetReaderIndex(); horn2.resetReaderIndex(); - for (int j = 0; j < horn1.writerIndex(); j++) - { + for (int j = 0; j < horn1.writerIndex(); j++) { Assert.assertEquals(horn1.readByte(), horn2.readByte()); } } @@ -257,18 +231,13 @@ public class PagingStoreImplTest extends ActiveMQTestBase } @Test - public void testDepageMultiplePages() throws Exception - { + public void testDepageMultiplePages() throws Exception { SequentialFileFactory factory = new FakeSequentialFileFactory(); SimpleString destination = new SimpleString("test"); PagingStoreFactory storeFactory = new FakeStoreFactory(factory); - PagingStoreImpl store = - new PagingStoreImpl(PagingStoreImplTest.destinationTestName, null, 100, createMockManager(), - createStorageManagerMock(), factory, storeFactory, - PagingStoreImplTest.destinationTestName, new AddressSettings().setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE), - getExecutorFactory().getExecutor(), true); + PagingStoreImpl store = new PagingStoreImpl(PagingStoreImplTest.destinationTestName, null, 100, createMockManager(), createStorageManagerMock(), factory, storeFactory, PagingStoreImplTest.destinationTestName, new AddressSettings().setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE), getExecutorFactory().getExecutor(), true); store.start(); @@ -280,15 +249,13 @@ public class PagingStoreImplTest extends ActiveMQTestBase List buffers = new ArrayList(); - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { ActiveMQBuffer buffer = createRandomBuffer(i + 1L, 10); buffers.add(buffer); - if (i == 5) - { + if (i == 5) { store.forceAnotherPage(); } @@ -304,8 +271,7 @@ public class PagingStoreImplTest extends ActiveMQTestBase int sequence = 0; - for (int pageNr = 0; pageNr < 2; pageNr++) - { + for (int pageNr = 0; pageNr < 2; pageNr++) { Page page = store.depage(); System.out.println("numberOfPages = " + store.getNumberOfPages()); @@ -318,8 +284,7 @@ public class PagingStoreImplTest extends ActiveMQTestBase Assert.assertEquals(5, msg.size()); - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { Assert.assertEquals(sequence++, msg.get(i).getMessage().getMessageID()); ActiveMQTestBase.assertEqualsBuffers(18, buffers.get(pageNr * 5 + i), msg.get(i).getMessage().getBodyBuffer()); } @@ -387,15 +352,14 @@ public class PagingStoreImplTest extends ActiveMQTestBase } @Test - public void testConcurrentDepage() throws Exception - { + public void testConcurrentDepage() throws Exception { SequentialFileFactory factory = new FakeSequentialFileFactory(1, false); testConcurrentPaging(factory, 10); } - protected void testConcurrentPaging(final SequentialFileFactory factory, final int numberOfThreads) throws Exception - { + protected void testConcurrentPaging(final SequentialFileFactory factory, + final int numberOfThreads) throws Exception { PagingStoreFactory storeFactory = new FakeStoreFactory(factory); final int MAX_SIZE = 1024 * 10; @@ -410,14 +374,9 @@ public class PagingStoreImplTest extends ActiveMQTestBase final ArrayList readPages = new ArrayList(); - AddressSettings settings = new AddressSettings() - .setPageSizeBytes(MAX_SIZE) - .setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE); + AddressSettings settings = new AddressSettings().setPageSizeBytes(MAX_SIZE).setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE); - final PagingStore storeImpl = - new PagingStoreImpl(PagingStoreImplTest.destinationTestName, null, 100, createMockManager(), - createStorageManagerMock(), factory, storeFactory, new SimpleString("test"), - settings, getExecutorFactory().getExecutor(), true); + final PagingStore storeImpl = new PagingStoreImpl(PagingStoreImplTest.destinationTestName, null, 100, createMockManager(), createStorageManagerMock(), factory, storeFactory, new SimpleString("test"), settings, getExecutorFactory().getExecutor(), true); storeImpl.start(); @@ -430,20 +389,16 @@ public class PagingStoreImplTest extends ActiveMQTestBase final SimpleString destination = new SimpleString("test"); - class WriterThread extends Thread - { + class WriterThread extends Thread { Exception e; @Override - public void run() - { + public void run() { - try - { + try { boolean firstTime = true; - while (true) - { + while (true) { long id = messageIdGenerator.incrementAndGet(); // Each thread will Keep paging until all the messages are depaged. @@ -451,58 +406,48 @@ public class PagingStoreImplTest extends ActiveMQTestBase // Just using the internal API to remove it from the page file system ServerMessage msg = createMessage(id, storeImpl, destination, createRandomBuffer(id, 5)); final RoutingContextImpl ctx2 = new RoutingContextImpl(null); - if (storeImpl.page(msg, ctx2.getTransaction(), ctx2.getContextListing(storeImpl.getStoreName()), lock)) - { + if (storeImpl.page(msg, ctx2.getTransaction(), ctx2.getContextListing(storeImpl.getStoreName()), lock)) { buffers.put(id, msg); } - else - { + else { break; } - if (firstTime) - { + if (firstTime) { // We have at least one data paged. So, we can start depaging now latchStart.countDown(); firstTime = false; } } } - catch (Exception e1) - { + catch (Exception e1) { e1.printStackTrace(); this.e = e1; } - finally - { + finally { aliveProducers.decrementAndGet(); } } } - final class ReaderThread extends Thread - { + final class ReaderThread extends Thread { + Exception e; @Override - public void run() - { - try - { + public void run() { + try { // Wait every producer to produce at least one message ActiveMQTestBase.waitForLatch(latchStart); - while (aliveProducers.get() > 0) - { + while (aliveProducers.get() > 0) { Page page = storeImpl.depage(); - if (page != null) - { + if (page != null) { readPages.add(page); } } } - catch (Exception e1) - { + catch (Exception e1) { e1.printStackTrace(); this.e = e1; } @@ -511,8 +456,7 @@ public class PagingStoreImplTest extends ActiveMQTestBase WriterThread[] producerThread = new WriterThread[numberOfThreads]; - for (int i = 0; i < numberOfThreads; i++) - { + for (int i = 0; i < numberOfThreads; i++) { producerThread[i] = new WriterThread(); producerThread[i].start(); } @@ -520,32 +464,27 @@ public class PagingStoreImplTest extends ActiveMQTestBase ReaderThread consumer = new ReaderThread(); consumer.start(); - for (int i = 0; i < numberOfThreads; i++) - { + for (int i = 0; i < numberOfThreads; i++) { producerThread[i].join(); - if (producerThread[i].e != null) - { + if (producerThread[i].e != null) { throw producerThread[i].e; } } consumer.join(); - if (consumer.e != null) - { + if (consumer.e != null) { throw consumer.e; } final ConcurrentMap buffers2 = new ConcurrentHashMap(); - for (Page page : readPages) - { + for (Page page : readPages) { page.open(); List msgs = page.read(new NullStorageManager()); page.close(); - for (PagedMessage msg : msgs) - { + for (PagedMessage msg : msgs) { long id = msg.getMessage().getBodyBuffer().readLong(); msg.getMessage().getBodyBuffer().resetReaderIndex(); @@ -563,19 +502,14 @@ public class PagingStoreImplTest extends ActiveMQTestBase Assert.assertTrue(files.size() != 0); - for (String file : files) - { + for (String file : files) { SequentialFile fileTmp = factory.createSequentialFile(file); fileTmp.open(); - Assert.assertTrue("The page file size (" + fileTmp.size() + ") shouldn't be > " + MAX_SIZE, - fileTmp.size() <= MAX_SIZE); + Assert.assertTrue("The page file size (" + fileTmp.size() + ") shouldn't be > " + MAX_SIZE, fileTmp.size() <= MAX_SIZE); fileTmp.close(); } - PagingStore storeImpl2 = - new PagingStoreImpl(PagingStoreImplTest.destinationTestName, null, 100, createMockManager(), - createStorageManagerMock(), factory, storeFactory, new SimpleString("test"), - settings, getExecutorFactory().getExecutor(), true); + PagingStore storeImpl2 = new PagingStoreImpl(PagingStoreImplTest.destinationTestName, null, 100, createMockManager(), createStorageManagerMock(), factory, storeFactory, new SimpleString("test"), settings, getExecutorFactory().getExecutor(), true); storeImpl2.start(); int numberOfPages = storeImpl2.getNumberOfPages(); @@ -588,8 +522,7 @@ public class PagingStoreImplTest extends ActiveMQTestBase Assert.assertEquals(numberOfPages, storeImpl2.getNumberOfPages()); long lastMessageId = messageIdGenerator.incrementAndGet(); - ServerMessage lastMsg = - createMessage(lastMessageId, storeImpl, destination, createRandomBuffer(lastMessageId, 5)); + ServerMessage lastMsg = createMessage(lastMessageId, storeImpl, destination, createRandomBuffer(lastMessageId, 5)); storeImpl2.forceAnotherPage(); @@ -598,11 +531,9 @@ public class PagingStoreImplTest extends ActiveMQTestBase buffers2.put(lastMessageId, lastMsg); Page lastPage = null; - while (true) - { + while (true) { Page page = storeImpl2.depage(); - if (page == null) - { + if (page == null) { break; } @@ -614,17 +545,13 @@ public class PagingStoreImplTest extends ActiveMQTestBase page.close(); - for (PagedMessage msg : msgs) - { + for (PagedMessage msg : msgs) { long id = msg.getMessage().getBodyBuffer().readLong(); ServerMessage msgWritten = buffers2.remove(id); Assert.assertNotNull(msgWritten); Assert.assertEquals(msg.getMessage().getAddress(), msgWritten.getAddress()); - ActiveMQTestBase.assertEqualsByteArrays(msgWritten.getBodyBuffer().writerIndex(), msgWritten.getBodyBuffer() - .toByteBuffer() - .array(), - msg.getMessage().getBodyBuffer().toByteBuffer().array()); + ActiveMQTestBase.assertEqualsByteArrays(msgWritten.getBodyBuffer().writerIndex(), msgWritten.getBodyBuffer().toByteBuffer().array(), msg.getMessage().getBodyBuffer().toByteBuffer().array()); } } @@ -642,8 +569,7 @@ public class PagingStoreImplTest extends ActiveMQTestBase } @Test - public void testRestartPage() throws Throwable - { + public void testRestartPage() throws Throwable { clearDataRecreateServerDirs(); SequentialFileFactory factory = new NIOSequentialFileFactory(new File(getPageDir()), 1); @@ -651,14 +577,9 @@ public class PagingStoreImplTest extends ActiveMQTestBase final int MAX_SIZE = 1024 * 10; - AddressSettings settings = new AddressSettings() - .setPageSizeBytes(MAX_SIZE) - .setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE); + AddressSettings settings = new AddressSettings().setPageSizeBytes(MAX_SIZE).setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE); - final PagingStore storeImpl = - new PagingStoreImpl(PagingStoreImplTest.destinationTestName, null, 100, createMockManager(), - createStorageManagerMock(), factory, storeFactory, new SimpleString("test"), - settings, getExecutorFactory().getExecutor(), true); + final PagingStore storeImpl = new PagingStoreImpl(PagingStoreImplTest.destinationTestName, null, 100, createMockManager(), createStorageManagerMock(), factory, storeFactory, new SimpleString("test"), settings, getExecutorFactory().getExecutor(), true); storeImpl.start(); @@ -679,8 +600,7 @@ public class PagingStoreImplTest extends ActiveMQTestBase } @Test - public void testOrderOnPaging() throws Throwable - { + public void testOrderOnPaging() throws Throwable { clearDataRecreateServerDirs(); SequentialFileFactory factory = new NIOSequentialFileFactory(new File(getPageDir()), 1); @@ -688,14 +608,9 @@ public class PagingStoreImplTest extends ActiveMQTestBase final int MAX_SIZE = 1024 * 10; - AddressSettings settings = new AddressSettings() - .setPageSizeBytes(MAX_SIZE) - .setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE); + AddressSettings settings = new AddressSettings().setPageSizeBytes(MAX_SIZE).setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE); - final PagingStore store = - new PagingStoreImpl(PagingStoreImplTest.destinationTestName, null, 100, createMockManager(), - createStorageManagerMock(), factory, storeFactory, new SimpleString("test"), - settings, getExecutorFactory().getExecutor(), false); + final PagingStore store = new PagingStoreImpl(PagingStoreImplTest.destinationTestName, null, 100, createMockManager(), createStorageManagerMock(), factory, storeFactory, new SimpleString("test"), settings, getExecutorFactory().getExecutor(), false); store.start(); @@ -714,22 +629,17 @@ public class PagingStoreImplTest extends ActiveMQTestBase final List errors = new ArrayList(); - class WriterThread extends Thread - { + class WriterThread extends Thread { - public WriterThread() - { + public WriterThread() { super("PageWriter"); } @Override - public void run() - { + public void run() { - try - { - for (long i = 0; i < NUMBER_OF_MESSAGES; i++) - { + try { + for (long i = 0; i < NUMBER_OF_MESSAGES; i++) { // Each thread will Keep paging until all the messages are depaged. // This is possible because the depage thread is not actually reading the pages. // Just using the internal API to remove it from the page file system @@ -737,51 +647,41 @@ public class PagingStoreImplTest extends ActiveMQTestBase msg.putLongProperty("count", i); final RoutingContextImpl ctx2 = new RoutingContextImpl(null); - while (!store.page(msg, ctx2.getTransaction(), ctx2.getContextListing(store.getStoreName()), - lock)) - { + while (!store.page(msg, ctx2.getTransaction(), ctx2.getContextListing(store.getStoreName()), lock)) { store.startPaging(); } - if (i == 0) - { + if (i == 0) { producedLatch.countDown(); } } } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); errors.add(e); } } } - class ReaderThread extends Thread - { - public ReaderThread() - { + class ReaderThread extends Thread { + + public ReaderThread() { super("PageReader"); } @Override - public void run() - { - try - { + public void run() { + try { long msgsRead = 0; - while (msgsRead < NUMBER_OF_MESSAGES) - { + while (msgsRead < NUMBER_OF_MESSAGES) { Page page = store.depage(); - if (page != null) - { + if (page != null) { page.open(); List messages = page.read(new NullStorageManager()); - for (PagedMessage pgmsg : messages) - { + for (PagedMessage pgmsg : messages) { ServerMessage msg = pgmsg.getMessage(); Assert.assertEquals(msgsRead++, msg.getMessageID()); @@ -792,16 +692,14 @@ public class PagingStoreImplTest extends ActiveMQTestBase page.close(); page.delete(null); } - else - { + else { System.out.println("Depaged!!!! numerOfMessages = " + msgsRead + " of " + NUMBER_OF_MESSAGES); Thread.sleep(500); } } } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); errors.add(e); } @@ -818,8 +716,7 @@ public class PagingStoreImplTest extends ActiveMQTestBase store.stop(); - for (Throwable e : errors) - { + for (Throwable e : errors) { throw e; } } @@ -827,32 +724,28 @@ public class PagingStoreImplTest extends ActiveMQTestBase /** * @return */ - protected PagingManager createMockManager() - { + protected PagingManager createMockManager() { return new FakePagingManager(); } - private StorageManager createStorageManagerMock() - { + private StorageManager createStorageManagerMock() { return new NullStorageManager(); } - private ExecutorFactory getExecutorFactory() - { - return new ExecutorFactory() - { + private ExecutorFactory getExecutorFactory() { + return new ExecutorFactory() { @Override - public Executor getExecutor() - { + public Executor getExecutor() { return executor; } }; } - private ServerMessage createMessage(final long id, final PagingStore store, final SimpleString destination, - final ActiveMQBuffer buffer) - { + private ServerMessage createMessage(final long id, + final PagingStore store, + final SimpleString destination, + final ActiveMQBuffer buffer) { ServerMessage msg = new ServerMessageImpl(id, 50 + buffer.capacity()); msg.setAddress(destination); @@ -867,8 +760,7 @@ public class PagingStoreImplTest extends ActiveMQTestBase return msg; } - protected ActiveMQBuffer createRandomBuffer(final long id, final int size) - { + protected ActiveMQBuffer createRandomBuffer(final long id, final int size) { return RandomUtil.randomBuffer(size, id); } @@ -876,79 +768,64 @@ public class PagingStoreImplTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); executor = Executors.newSingleThreadExecutor(); } @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { executor.shutdown(); super.tearDown(); } - static final class FakeStoreFactory implements PagingStoreFactory - { + static final class FakeStoreFactory implements PagingStoreFactory { final SequentialFileFactory factory; - public FakeStoreFactory() - { + public FakeStoreFactory() { factory = new FakeSequentialFileFactory(); } - public FakeStoreFactory(final SequentialFileFactory factory) - { + public FakeStoreFactory(final SequentialFileFactory factory) { this.factory = factory; } @Override - public SequentialFileFactory newFileFactory(final SimpleString destinationName) throws Exception - { + public SequentialFileFactory newFileFactory(final SimpleString destinationName) throws Exception { return factory; } @Override - public PagingStore newStore(final SimpleString destinationName, final AddressSettings addressSettings) - { + public PagingStore newStore(final SimpleString destinationName, final AddressSettings addressSettings) { return null; } @Override - public List - reloadStores(final HierarchicalRepository addressSettingsRepository) throws Exception - { + public List reloadStores(final HierarchicalRepository addressSettingsRepository) throws Exception { return null; } @Override - public void setPagingManager(final PagingManager manager) - { + public void setPagingManager(final PagingManager manager) { } @Override - public void stop() throws InterruptedException - { + public void stop() throws InterruptedException { } - public void beforePageRead() throws Exception - { + public void beforePageRead() throws Exception { } - public void afterPageRead() throws Exception - { + public void afterPageRead() throws Exception { } - public ByteBuffer allocateDirectBuffer(final int size) - { + public ByteBuffer allocateDirectBuffer(final int size) { return ByteBuffer.allocateDirect(size); } - public void freeDirectuffer(final ByteBuffer buffer) - { + public void freeDirectuffer(final ByteBuffer buffer) { } } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/persistence/impl/BatchIDGeneratorUnitTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/persistence/impl/BatchIDGeneratorUnitTest.java index f89d61c080..30d7f2ade1 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/persistence/impl/BatchIDGeneratorUnitTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/persistence/impl/BatchIDGeneratorUnitTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.unit.core.persistence.impl; + import java.io.File; import java.util.ArrayList; @@ -33,12 +34,10 @@ import org.apache.activemq.artemis.core.persistence.impl.nullpm.NullStorageManag import org.junit.Assert; import org.junit.Test; -public class BatchIDGeneratorUnitTest extends ActiveMQTestBase -{ +public class BatchIDGeneratorUnitTest extends ActiveMQTestBase { @Test - public void testSequence() throws Exception - { + public void testSequence() throws Exception { NIOSequentialFileFactory factory = new NIOSequentialFileFactory(new File(getTestDir()), 1); Journal journal = new JournalImpl(10 * 1024, 2, 0, 0, factory, "activemq-bindings", "bindings", 1); @@ -76,13 +75,10 @@ public class BatchIDGeneratorUnitTest extends ActiveMQTestBase long lastId = id5; boolean close = true; - for (int i = 0; i < 100000; i++) - { - if (i % 1000 == 0) - { + for (int i = 0; i < 100000; i++) { + if (i % 1000 == 0) { // interchanging closes and simulated crashes - if (close) - { + if (close) { batch.persistCurrentID(); } @@ -111,16 +107,13 @@ public class BatchIDGeneratorUnitTest extends ActiveMQTestBase batch = new BatchingIDGenerator(0, 1000, getJournalStorageManager(journal)); loadIDs(journal, batch); - Assert.assertEquals("No Ids were generated, so the currentID was supposed to stay the same", - lastId, - batch.getCurrentID()); + Assert.assertEquals("No Ids were generated, so the currentID was supposed to stay the same", lastId, batch.getCurrentID()); journal.stop(); } - protected void loadIDs(final Journal journal, final BatchingIDGenerator batch) throws Exception - { + protected void loadIDs(final Journal journal, final BatchingIDGenerator batch) throws Exception { ArrayList records = new ArrayList(); ArrayList tx = new ArrayList(); @@ -129,36 +122,28 @@ public class BatchIDGeneratorUnitTest extends ActiveMQTestBase Assert.assertEquals(0, tx.size()); - Assert.assertTrue("Contains " + records.size(), records.size() > 0); + Assert.assertTrue("Contains " + records.size(), records.size() > 0); - for (RecordInfo record : records) - { - if (record.userRecordType == JournalRecordIds.ID_COUNTER_RECORD) - { + for (RecordInfo record : records) { + if (record.userRecordType == JournalRecordIds.ID_COUNTER_RECORD) { ActiveMQBuffer buffer = ActiveMQBuffers.wrappedBuffer(record.data); batch.loadState(record.id, buffer); } } } - private StorageManager getJournalStorageManager(final Journal bindingsJournal) - { - NullStorageManager storageManager = new NullStorageManager() - { + private StorageManager getJournalStorageManager(final Journal bindingsJournal) { + NullStorageManager storageManager = new NullStorageManager() { @Override - public synchronized void storeID(long journalID, long id) throws Exception - { - bindingsJournal.appendAddRecord(journalID, JournalRecordIds.ID_COUNTER_RECORD, - BatchingIDGenerator.createIDEncodingSupport(id), true); + public synchronized void storeID(long journalID, long id) throws Exception { + bindingsJournal.appendAddRecord(journalID, JournalRecordIds.ID_COUNTER_RECORD, BatchingIDGenerator.createIDEncodingSupport(id), true); } }; - try - { + try { storageManager.start(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } return storageManager; diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/persistence/impl/OperationContextUnitTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/persistence/impl/OperationContextUnitTest.java index f4abbaad50..719da0a9cb 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/persistence/impl/OperationContextUnitTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/persistence/impl/OperationContextUnitTest.java @@ -29,8 +29,7 @@ import org.apache.activemq.artemis.core.persistence.impl.journal.OperationContex import org.junit.Assert; import org.junit.Test; -public class OperationContextUnitTest extends ActiveMQTestBase -{ +public class OperationContextUnitTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -43,52 +42,46 @@ public class OperationContextUnitTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testCompleteTaskAfterPaging() throws Exception - { + public void testCompleteTaskAfterPaging() throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); - try - { + try { OperationContextImpl impl = new OperationContextImpl(executor); final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); - impl.executeOnCompletion(new IOCallback() - { + impl.executeOnCompletion(new IOCallback() { - public void onError(int errorCode, String errorMessage) - { + public void onError(int errorCode, String errorMessage) { } - public void done() - { + public void done() { latch1.countDown(); } }); assertTrue(latch1.await(10, TimeUnit.SECONDS)); - for (int i = 0; i < 10; i++) impl.storeLineUp(); - for (int i = 0; i < 3; i++) impl.pageSyncLineUp(); + for (int i = 0; i < 10; i++) + impl.storeLineUp(); + for (int i = 0; i < 3; i++) + impl.pageSyncLineUp(); - impl.executeOnCompletion(new IOCallback() - { + impl.executeOnCompletion(new IOCallback() { - public void onError(int errorCode, String errorMessage) - { + public void onError(int errorCode, String errorMessage) { } - public void done() - { + public void done() { latch2.countDown(); } }); - assertFalse(latch2.await(1, TimeUnit.MILLISECONDS)); - for (int i = 0; i < 9; i++) impl.done(); - for (int i = 0; i < 2; i++) impl.pageSyncDone(); - + for (int i = 0; i < 9; i++) + impl.done(); + for (int i = 0; i < 2; i++) + impl.pageSyncDone(); assertFalse(latch2.await(1, TimeUnit.MILLISECONDS)); @@ -98,25 +91,21 @@ public class OperationContextUnitTest extends ActiveMQTestBase assertTrue(latch2.await(10, TimeUnit.SECONDS)); } - finally - { + finally { executor.shutdown(); } } @Test - public void testCaptureExceptionOnExecutor() throws Exception - { + public void testCaptureExceptionOnExecutor() throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); executor.shutdown(); final CountDownLatch latch = new CountDownLatch(1); - final OperationContextImpl impl = new OperationContextImpl(executor) - { + final OperationContextImpl impl = new OperationContextImpl(executor) { @Override - public void complete() - { + public void complete() { super.complete(); latch.countDown(); } @@ -127,17 +116,13 @@ public class OperationContextUnitTest extends ActiveMQTestBase final AtomicInteger numberOfFailures = new AtomicInteger(0); - Thread t = new Thread() - { + Thread t = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { impl.waitCompletion(5000); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); numberOfFailures.incrementAndGet(); } @@ -158,17 +143,14 @@ public class OperationContextUnitTest extends ActiveMQTestBase } @Test - public void testCaptureExceptionOnFailure() throws Exception - { + public void testCaptureExceptionOnFailure() throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); final CountDownLatch latch = new CountDownLatch(1); - final OperationContextImpl context = new OperationContextImpl(executor) - { + final OperationContextImpl context = new OperationContextImpl(executor) { @Override - public void complete() - { + public void complete() { super.complete(); latch.countDown(); } @@ -179,17 +161,13 @@ public class OperationContextUnitTest extends ActiveMQTestBase final AtomicInteger failures = new AtomicInteger(0); - Thread t = new Thread() - { + Thread t = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { context.waitCompletion(5000); } - catch (Throwable e) - { + catch (Throwable e) { e.printStackTrace(); failures.incrementAndGet(); } @@ -213,16 +191,13 @@ public class OperationContextUnitTest extends ActiveMQTestBase final AtomicInteger operations = new AtomicInteger(0); // We should be up to date with lineUps and executions. this should now just finish processing - context.executeOnCompletion(new IOCallback() - { + context.executeOnCompletion(new IOCallback() { - public void done() - { + public void done() { operations.incrementAndGet(); } - public void onError(final int errorCode, final String errorMessage) - { + public void onError(final int errorCode, final String errorMessage) { failures.incrementAndGet(); } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/AddressImplTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/AddressImplTest.java index 11545a8ef3..1ad0f79b9b 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/AddressImplTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/AddressImplTest.java @@ -25,11 +25,10 @@ import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.postoffice.Address; import org.apache.activemq.artemis.core.postoffice.impl.AddressImpl; -public class AddressImplTest extends ActiveMQTestBase -{ +public class AddressImplTest extends ActiveMQTestBase { + @Test - public void testNoDots() - { + public void testNoDots() { SimpleString s1 = new SimpleString("abcde"); SimpleString s2 = new SimpleString("abcde"); Address a1 = new AddressImpl(s1); @@ -38,8 +37,7 @@ public class AddressImplTest extends ActiveMQTestBase } @Test - public void testDotsSameLength2() - { + public void testDotsSameLength2() { SimpleString s1 = new SimpleString("a.b"); SimpleString s2 = new SimpleString("a.b"); Address a1 = new AddressImpl(s1); @@ -48,8 +46,7 @@ public class AddressImplTest extends ActiveMQTestBase } @Test - public void testA() - { + public void testA() { SimpleString s1 = new SimpleString("a.b.c"); SimpleString s2 = new SimpleString("a.b.c.d.e.f.g.h.i.j.k.l.m.n.*"); Address a1 = new AddressImpl(s1); @@ -58,8 +55,7 @@ public class AddressImplTest extends ActiveMQTestBase } @Test - public void testB() - { + public void testB() { SimpleString s1 = new SimpleString("a.b.c.d"); SimpleString s2 = new SimpleString("a.b.x.e"); SimpleString s3 = new SimpleString("a.b.c.*"); @@ -71,8 +67,7 @@ public class AddressImplTest extends ActiveMQTestBase } @Test - public void testC() - { + public void testC() { SimpleString s1 = new SimpleString("a.b.c.d"); SimpleString s2 = new SimpleString("a.b.c.x"); SimpleString s3 = new SimpleString("a.b.*.d"); @@ -84,8 +79,7 @@ public class AddressImplTest extends ActiveMQTestBase } @Test - public void testD() - { + public void testD() { SimpleString s1 = new SimpleString("a.b.c.d.e"); SimpleString s2 = new SimpleString("a.b.c.x.e"); SimpleString s3 = new SimpleString("a.b.*.d.*"); @@ -97,8 +91,7 @@ public class AddressImplTest extends ActiveMQTestBase } @Test - public void testE() - { + public void testE() { SimpleString s1 = new SimpleString("a.b.c.d.e.f"); SimpleString s2 = new SimpleString("a.b.c.x.e.f"); SimpleString s3 = new SimpleString("a.b.*.d.*.f"); @@ -110,8 +103,7 @@ public class AddressImplTest extends ActiveMQTestBase } @Test - public void testF() - { + public void testF() { SimpleString s1 = new SimpleString("a.b.c.d.e.f"); SimpleString s2 = new SimpleString("a.b.c.x.e.f"); SimpleString s3 = new SimpleString("#"); @@ -123,8 +115,7 @@ public class AddressImplTest extends ActiveMQTestBase } @Test - public void testG() - { + public void testG() { SimpleString s1 = new SimpleString("a.b.c.d.e.f"); SimpleString s2 = new SimpleString("a.b.c.x.e.f"); SimpleString s3 = new SimpleString("a.#"); @@ -136,8 +127,7 @@ public class AddressImplTest extends ActiveMQTestBase } @Test - public void testH() - { + public void testH() { SimpleString s1 = new SimpleString("a.b.c.d.e.f"); SimpleString s2 = new SimpleString("a.b.c.x.e.f"); SimpleString s3 = new SimpleString("#.b.#"); @@ -149,8 +139,7 @@ public class AddressImplTest extends ActiveMQTestBase } @Test - public void testI() - { + public void testI() { SimpleString s1 = new SimpleString("a.b.c.d.e.f"); SimpleString s2 = new SimpleString("a.b.c.x.e.f"); SimpleString s3 = new SimpleString("a.#.b.#"); @@ -162,8 +151,7 @@ public class AddressImplTest extends ActiveMQTestBase } @Test - public void testJ() - { + public void testJ() { SimpleString s1 = new SimpleString("a.b.c.d.e.f"); SimpleString s2 = new SimpleString("a.b.c.x.e.f"); SimpleString s3 = new SimpleString("a.#.c.d.e.f"); @@ -175,8 +163,7 @@ public class AddressImplTest extends ActiveMQTestBase } @Test - public void testK() - { + public void testK() { SimpleString s1 = new SimpleString("a.b.c.d.e.f"); SimpleString s2 = new SimpleString("a.b.c.d.e.x"); SimpleString s3 = new SimpleString("a.#.c.d.e.*"); @@ -188,8 +175,7 @@ public class AddressImplTest extends ActiveMQTestBase } @Test - public void testL() - { + public void testL() { SimpleString s1 = new SimpleString("a.b.c.d.e.f"); SimpleString s2 = new SimpleString("a.b.c.d.e.x"); SimpleString s3 = new SimpleString("a.#.c.d.*.f"); @@ -201,8 +187,7 @@ public class AddressImplTest extends ActiveMQTestBase } @Test - public void testM() - { + public void testM() { SimpleString s1 = new SimpleString("a.b.c"); SimpleString s2 = new SimpleString("a.b.x.e"); SimpleString s3 = new SimpleString("a.b.c.#"); @@ -214,8 +199,7 @@ public class AddressImplTest extends ActiveMQTestBase } @Test - public void testN() - { + public void testN() { SimpleString s1 = new SimpleString("usd.stock"); SimpleString s2 = new SimpleString("a.b.x.e"); SimpleString s3 = new SimpleString("*.stock.#"); @@ -227,8 +211,7 @@ public class AddressImplTest extends ActiveMQTestBase } @Test - public void testO() - { + public void testO() { SimpleString s1 = new SimpleString("a.b.c.d"); SimpleString s2 = new SimpleString("a.b.x.e"); SimpleString s3 = new SimpleString("a.b.c.*"); @@ -240,8 +223,7 @@ public class AddressImplTest extends ActiveMQTestBase } @Test - public void testP() - { + public void testP() { SimpleString s1 = new SimpleString("a.b.c.d"); SimpleString s3 = new SimpleString("a.b.c#"); Address a1 = new AddressImpl(s1); @@ -250,8 +232,7 @@ public class AddressImplTest extends ActiveMQTestBase } @Test - public void testQ() - { + public void testQ() { SimpleString s1 = new SimpleString("a.b.c.d"); SimpleString s3 = new SimpleString("#a.b.c"); Address a1 = new AddressImpl(s1); @@ -260,8 +241,7 @@ public class AddressImplTest extends ActiveMQTestBase } @Test - public void testR() - { + public void testR() { SimpleString s1 = new SimpleString("a.b.c.d"); SimpleString s3 = new SimpleString("#*a.b.c"); Address a1 = new AddressImpl(s1); @@ -270,8 +250,7 @@ public class AddressImplTest extends ActiveMQTestBase } @Test - public void testS() - { + public void testS() { SimpleString s1 = new SimpleString("a.b.c.d"); SimpleString s3 = new SimpleString("a.b.c*"); Address a1 = new AddressImpl(s1); @@ -280,8 +259,7 @@ public class AddressImplTest extends ActiveMQTestBase } @Test - public void testT() - { + public void testT() { SimpleString s1 = new SimpleString("a.b.c.d"); SimpleString s3 = new SimpleString("*a.b.c"); Address a1 = new AddressImpl(s1); @@ -290,8 +268,7 @@ public class AddressImplTest extends ActiveMQTestBase } @Test - public void testU() - { + public void testU() { SimpleString s1 = new SimpleString("a.b.c.d"); SimpleString s3 = new SimpleString("*a.b.c"); Address a1 = new AddressImpl(s1); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/BindingsImplTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/BindingsImplTest.java index 478ba5b144..b79cb7f181 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/BindingsImplTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/BindingsImplTest.java @@ -42,8 +42,7 @@ import org.apache.activemq.artemis.core.server.impl.ServerMessageImpl; import org.apache.activemq.artemis.core.transaction.Transaction; import org.apache.activemq.artemis.core.transaction.TransactionOperation; -public class BindingsImplTest extends ActiveMQTestBase -{ +public class BindingsImplTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -55,27 +54,22 @@ public class BindingsImplTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testRemoveWhileRouting() throws Exception - { + public void testRemoveWhileRouting() throws Exception { // It would require many iterations before getting a failure - for (int i = 0; i < 500; i++) - { + for (int i = 0; i < 500; i++) { internalTest(true); } } @Test - public void testRemoveWhileRedistributing() throws Exception - { + public void testRemoveWhileRedistributing() throws Exception { // It would require many iterations before getting a failure - for (int i = 0; i < 500; i++) - { + for (int i = 0; i < 500; i++) { internalTest(false); } } - private void internalTest(final boolean route) throws Exception - { + private void internalTest(final boolean route) throws Exception { final FakeBinding fake = new FakeBinding(new SimpleString("a")); final Bindings bind = new BindingsImpl(null, null, null); @@ -83,17 +77,13 @@ public class BindingsImplTest extends ActiveMQTestBase bind.addBinding(new FakeBinding(new SimpleString("a"))); bind.addBinding(new FakeBinding(new SimpleString("a"))); - Thread t = new Thread() - { + Thread t = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { bind.removeBinding(fake); } - catch (Exception e) - { + catch (Exception e) { e.printStackTrace(); } } @@ -102,215 +92,176 @@ public class BindingsImplTest extends ActiveMQTestBase Queue queue = new FakeQueue(new SimpleString("a")); t.start(); - for (int i = 0; i < 100; i++) - { - if (route) - { + for (int i = 0; i < 100; i++) { + if (route) { bind.route(new ServerMessageImpl(i, 100), new RoutingContextImpl(new FakeTransaction())); } - else - { + else { bind.redistribute(new ServerMessageImpl(i, 100), queue, new RoutingContextImpl(new FakeTransaction())); } } } - private final class FakeTransaction implements Transaction - { + private final class FakeTransaction implements Transaction { - public void addOperation(final TransactionOperation sync) - { + public void addOperation(final TransactionOperation sync) { } - public boolean hasTimedOut(long currentTime, int defaultTimeout) - { + public boolean hasTimedOut(long currentTime, int defaultTimeout) { return false; } - public void commit() throws Exception - { + public void commit() throws Exception { } - public void commit(final boolean onePhase) throws Exception - { + public void commit(final boolean onePhase) throws Exception { } - public long getCreateTime() - { + public long getCreateTime() { return 0; } - public long getID() - { + public long getID() { return 0; } - public Object getProperty(final int index) - { + public Object getProperty(final int index) { return null; } @Override - public boolean isContainsPersistent() - { + public boolean isContainsPersistent() { return false; } - public State getState() - { + public State getState() { return null; } - public Xid getXid() - { + public Xid getXid() { return null; } - public void markAsRollbackOnly(final ActiveMQException exception) - { + public void markAsRollbackOnly(final ActiveMQException exception) { } - public void prepare() throws Exception - { + public void prepare() throws Exception { } - public void putProperty(final int index, final Object property) - { + public void putProperty(final int index, final Object property) { } - public void removeOperation(final TransactionOperation sync) - { + public void removeOperation(final TransactionOperation sync) { } - public void resume() - { + public void resume() { } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.transaction.Transaction#rollback() */ - public void rollback() throws Exception - { + public void rollback() throws Exception { } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.transaction.Transaction#setState(org.apache.activemq.artemis.core.transaction.Transaction.State) */ - public void setState(final State state) - { + public void setState(final State state) { } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.transaction.Transaction#suspend() */ - public void suspend() - { + public void suspend() { } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.transaction.Transaction#getDistinctQueues() */ - public Set getDistinctQueues() - { + public Set getDistinctQueues() { return Collections.emptySet(); } - public void setContainsPersistent() - { - + public void setContainsPersistent() { } - public void setTimeout(int timeout) - { + public void setTimeout(int timeout) { } - public List getAllOperations() - { + public List getAllOperations() { return null; } - public void setWaitBeforeCommit(boolean waitBeforeCommit) - { + public void setWaitBeforeCommit(boolean waitBeforeCommit) { } @Override - public RefsOperation createRefsOperation(Queue queue) - { + public RefsOperation createRefsOperation(Queue queue) { // TODO Auto-generated method stub return null; } } - private final class FakeFilter implements Filter - { + private final class FakeFilter implements Filter { /* (non-Javadoc) * @see org.apache.activemq.artemis.core.filter.Filter#getFilterString() */ - public SimpleString getFilterString() - { + public SimpleString getFilterString() { return null; } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.filter.Filter#match(org.apache.activemq.artemis.core.server.ServerMessage) */ - public boolean match(final ServerMessage message) - { + public boolean match(final ServerMessage message) { return false; } } - private final class FakeBinding implements Binding - { - - public void close() throws Exception - { + private final class FakeBinding implements Binding { + public void close() throws Exception { } @Override - public void unproposed(SimpleString groupID) - { + public void unproposed(SimpleString groupID) { } final SimpleString name; - FakeBinding(final SimpleString name) - { + FakeBinding(final SimpleString name) { this.name = name; } - public SimpleString getAddress() - { + public SimpleString getAddress() { return null; } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.postoffice.Binding#getBindable() */ - public Bindable getBindable() - { + public Bindable getBindable() { return null; } @@ -318,8 +269,7 @@ public class BindingsImplTest extends ActiveMQTestBase /* (non-Javadoc) * @see org.apache.activemq.artemis.core.postoffice.Binding#getClusterName() */ - public SimpleString getClusterName() - { + public SimpleString getClusterName() { return null; } @@ -327,37 +277,32 @@ public class BindingsImplTest extends ActiveMQTestBase /* (non-Javadoc) * @see org.apache.activemq.artemis.core.postoffice.Binding#getDistance() */ - public int getDistance() - { + public int getDistance() { return 0; } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.postoffice.Binding#getFilter() */ - public Filter getFilter() - { + public Filter getFilter() { return new FakeFilter(); } - public long getID() - { + public long getID() { return 0; } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.postoffice.Binding#getRoutingName() */ - public SimpleString getRoutingName() - { + public SimpleString getRoutingName() { return name; } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.postoffice.Binding#getType() */ - public BindingType getType() - { + public BindingType getType() { return null; } @@ -365,23 +310,19 @@ public class BindingsImplTest extends ActiveMQTestBase /* (non-Javadoc) * @see org.apache.activemq.artemis.core.postoffice.Binding#getUniqueName() */ - public SimpleString getUniqueName() - { + public SimpleString getUniqueName() { return null; } - public boolean isExclusive() - { + public boolean isExclusive() { return false; } - public boolean isHighAcceptPriority(final ServerMessage message) - { + public boolean isHighAcceptPriority(final ServerMessage message) { return false; } - public void route(final ServerMessage message, final RoutingContext context) throws Exception - { + public void route(final ServerMessage message, final RoutingContext context) throws Exception { } @@ -389,24 +330,20 @@ public class BindingsImplTest extends ActiveMQTestBase * @see org.apache.activemq.artemis.core.postoffice.Binding#toManagementString() */ @Override - public String toManagementString() - { + public String toManagementString() { return null; } @Override - public boolean isConnected() - { + public boolean isConnected() { return true; } @Override - public void routeWithAck(ServerMessage message, RoutingContext context) - { + public void routeWithAck(ServerMessage message, RoutingContext context) { } - } // Package protected --------------------------------------------- diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/DuplicateDetectionUnitTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/DuplicateDetectionUnitTest.java index 75bbc350ae..af6fc72217 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/DuplicateDetectionUnitTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/DuplicateDetectionUnitTest.java @@ -45,8 +45,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class DuplicateDetectionUnitTest extends ActiveMQTestBase -{ +public class DuplicateDetectionUnitTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -61,16 +60,14 @@ public class DuplicateDetectionUnitTest extends ActiveMQTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { executor.shutdown(); super.tearDown(); } @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); executor = Executors.newSingleThreadExecutor(); factory = new OrderedExecutorFactory(executor); @@ -79,13 +76,11 @@ public class DuplicateDetectionUnitTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testReloadDuplication() throws Exception - { + public void testReloadDuplication() throws Exception { JournalStorageManager journal = null; - try - { + try { clearDataRecreateServerDirs(); SimpleString ADDRESS = new SimpleString("address"); @@ -104,21 +99,13 @@ public class DuplicateDetectionUnitTest extends ActiveMQTestBase HashMap>> mapDups = new HashMap>>(); FakePagingManager pagingManager = new FakePagingManager(); - journal.loadMessageJournal(postOffice, - pagingManager, - new ResourceManagerImpl(0, 0, scheduledThreadPool), - null, - mapDups, - null, - null, - new PostOfficeJournalLoader(postOffice, pagingManager, null, null, null, null, null, null)); + journal.loadMessageJournal(postOffice, pagingManager, new ResourceManagerImpl(0, 0, scheduledThreadPool), null, mapDups, null, null, new PostOfficeJournalLoader(postOffice, pagingManager, null, null, null, null, null, null)); Assert.assertEquals(0, mapDups.size()); DuplicateIDCacheImpl cacheID = new DuplicateIDCacheImpl(ADDRESS, 10, journal, true); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { cacheID.addToCache(RandomUtil.randomBytes(), null); } @@ -128,14 +115,7 @@ public class DuplicateDetectionUnitTest extends ActiveMQTestBase journal.start(); journal.loadBindingJournal(new ArrayList(), new ArrayList()); - journal.loadMessageJournal(postOffice, - pagingManager, - new ResourceManagerImpl(0, 0, scheduledThreadPool), - null, - mapDups, - null, - null, - new PostOfficeJournalLoader(postOffice, pagingManager, null, null, null, null, null, null)); + journal.loadMessageJournal(postOffice, pagingManager, new ResourceManagerImpl(0, 0, scheduledThreadPool), null, mapDups, null, null, new PostOfficeJournalLoader(postOffice, pagingManager, null, null, null, null, null, null)); Assert.assertEquals(1, mapDups.size()); @@ -146,8 +126,7 @@ public class DuplicateDetectionUnitTest extends ActiveMQTestBase cacheID = new DuplicateIDCacheImpl(ADDRESS, 10, journal, true); cacheID.load(values); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { cacheID.addToCache(RandomUtil.randomBytes(), null); } @@ -159,14 +138,7 @@ public class DuplicateDetectionUnitTest extends ActiveMQTestBase journal.start(); journal.loadBindingJournal(new ArrayList(), new ArrayList()); - journal.loadMessageJournal(postOffice, - pagingManager, - new ResourceManagerImpl(0, 0, scheduledThreadPool), - null, - mapDups, - null, - null, - new PostOfficeJournalLoader(postOffice, pagingManager, null, null, null, null, null, null)); + journal.loadMessageJournal(postOffice, pagingManager, new ResourceManagerImpl(0, 0, scheduledThreadPool), null, mapDups, null, null, new PostOfficeJournalLoader(postOffice, pagingManager, null, null, null, null, null, null)); Assert.assertEquals(1, mapDups.size()); @@ -174,16 +146,12 @@ public class DuplicateDetectionUnitTest extends ActiveMQTestBase Assert.assertEquals(10, values.size()); } - finally - { - if (journal != null) - { - try - { + finally { + if (journal != null) { + try { journal.stop(); } - catch (Throwable ignored) - { + catch (Throwable ignored) { } } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/FakeQueue.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/FakeQueue.java index 8745e194a5..970e89d260 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/FakeQueue.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/FakeQueue.java @@ -33,102 +33,85 @@ import org.apache.activemq.artemis.core.transaction.Transaction; import org.apache.activemq.artemis.utils.LinkedListIterator; import org.apache.activemq.artemis.utils.ReferenceCounter; -public class FakeQueue implements Queue -{ +public class FakeQueue implements Queue { @Override - public boolean isInternalQueue() - { + public boolean isInternalQueue() { // no-op return false; } @Override - public void deleteQueue(boolean removeConsumers) throws Exception - { + public void deleteQueue(boolean removeConsumers) throws Exception { } - public void unproposed(SimpleString groupID) - { + public void unproposed(SimpleString groupID) { } @Override - public void setConsumersRefCount(ReferenceCounter referenceCounter) - { + public void setConsumersRefCount(ReferenceCounter referenceCounter) { } @Override - public void setInternalQueue(boolean internalQueue) - { + public void setInternalQueue(boolean internalQueue) { // no-op } @Override - public void cancel(Transaction tx, MessageReference ref, boolean ignoreRedeliveryCheck) - { + public void cancel(Transaction tx, MessageReference ref, boolean ignoreRedeliveryCheck) { // no-op } PageSubscription subs; - public boolean isDirectDeliver() - { + public boolean isDirectDeliver() { // no-op return false; } - public void close() - { + public void close() { // no-op } - public void forceCheckQueueSize() - { + public void forceCheckQueueSize() { // no-op } - public void reload(MessageReference ref) - { + public void reload(MessageReference ref) { // no-op } - public boolean flushExecutor() - { + public boolean flushExecutor() { return true; } - public void addHead(MessageReference ref) - { + public void addHead(MessageReference ref) { // no-op } - public void addHead(List ref) - { + public void addHead(List ref) { // no-op } - public void addTail(MessageReference ref, boolean direct) - { + public void addTail(MessageReference ref, boolean direct) { // no-op } - public void addTail(MessageReference ref) - { + public void addTail(MessageReference ref) { // no-op } - public void resetAllIterators() - { + public void resetAllIterators() { // no-op } @@ -139,493 +122,422 @@ public class FakeQueue implements Queue private long messageCount; - public FakeQueue(final SimpleString name) - { + public FakeQueue(final SimpleString name) { this(name, 0); } - public FakeQueue(final SimpleString name, final long id) - { + public FakeQueue(final SimpleString name, final long id) { this.name = name; this.id = id; } @Override - public void acknowledge(final MessageReference ref) throws Exception - { + public void acknowledge(final MessageReference ref) throws Exception { // no-op } @Override - public void acknowledge(final Transaction tx, final MessageReference ref) throws Exception - { + public void acknowledge(final Transaction tx, final MessageReference ref) throws Exception { // no-op } @Override - public void addConsumer(final Consumer consumer) throws Exception - { + public void addConsumer(final Consumer consumer) throws Exception { // no-op } @Override - public void addRedistributor(final long delay) - { + public void addRedistributor(final long delay) { // no-op } @Override - public void cancel(final MessageReference reference, final long timeBase) throws Exception - { + public void cancel(final MessageReference reference, final long timeBase) throws Exception { // no-op } @Override - public void cancel(final Transaction tx, final MessageReference ref) - { + public void cancel(final Transaction tx, final MessageReference ref) { // no-op } @Override - public void cancelRedistributor() throws Exception - { + public void cancelRedistributor() throws Exception { // no-op } @Override - public boolean changeReferencePriority(final long messageID, final byte newPriority) throws Exception - { + public boolean changeReferencePriority(final long messageID, final byte newPriority) throws Exception { // no-op return false; } @Override - public int changeReferencesPriority(Filter filter, byte newPriority) throws Exception - { + public int changeReferencesPriority(Filter filter, byte newPriority) throws Exception { // no-op return 0; } @Override - public boolean checkRedelivery(final MessageReference ref, final long timeBase, final boolean check) throws Exception - { + public boolean checkRedelivery(final MessageReference ref, + final long timeBase, + final boolean check) throws Exception { // no-op return false; } @Override - public int deleteAllReferences() throws Exception - { + public int deleteAllReferences() throws Exception { // no-op return 0; } @Override - public int deleteMatchingReferences(final Filter filter) throws Exception - { + public int deleteMatchingReferences(final Filter filter) throws Exception { // no-op return 0; } @Override - public boolean deleteReference(final long messageID) throws Exception - { + public boolean deleteReference(final long messageID) throws Exception { // no-op return false; } @Override - public void deliverAsync() - { + public void deliverAsync() { // no-op } @Override - public void expire(final MessageReference ref) throws Exception - { + public void expire(final MessageReference ref) throws Exception { // no-op } @Override - public boolean expireReference(final long messageID) throws Exception - { + public boolean expireReference(final long messageID) throws Exception { // no-op return false; } @Override - public void expireReferences() throws Exception - { + public void expireReferences() throws Exception { // no-op } @Override - public int expireReferences(final Filter filter) throws Exception - { + public int expireReferences(final Filter filter) throws Exception { // no-op return 0; } @Override - public int getConsumerCount() - { + public int getConsumerCount() { // no-op return 0; } @Override - public ReferenceCounter getConsumersRefCount() - { + public ReferenceCounter getConsumersRefCount() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override - public Set getConsumers() - { + public Set getConsumers() { // no-op return null; } @Override - public int getDeliveringCount() - { + public int getDeliveringCount() { // no-op return 0; } @Override - public Filter getFilter() - { + public Filter getFilter() { // no-op return null; } @Override - public long getMessageCount() - { + public long getMessageCount() { return messageCount; } - public void setMessageCount(long messageCount) - { + public void setMessageCount(long messageCount) { this.messageCount = messageCount; } @Override - public long getMessagesAdded() - { + public long getMessagesAdded() { // no-op return 0; } @Override - public long getMessagesAcknowledged() - { + public long getMessagesAcknowledged() { // no-op return 0; } @Override - public void resetMessagesAdded() - { + public void resetMessagesAdded() { // no-op } @Override - public void resetMessagesAcknowledged() - { + public void resetMessagesAcknowledged() { // no-op } @Override - public void incrementMesssagesAdded() - { + public void incrementMesssagesAdded() { } @Override - public void deliverScheduledMessages() - { + public void deliverScheduledMessages() { } @Override - public SimpleString getName() - { + public SimpleString getName() { return name; } - public SimpleString getAddress() - { + public SimpleString getAddress() { // no-op return null; } @Override - public long getID() - { + public long getID() { return id; } @Override - public MessageReference getReference(final long id1) - { + public MessageReference getReference(final long id1) { // no-op return null; } @Override - public int getScheduledCount() - { + public int getScheduledCount() { // no-op return 0; } @Override - public List getScheduledMessages() - { + public List getScheduledMessages() { // no-op return null; } @Override - public boolean isDurable() - { + public boolean isDurable() { // no-op return false; } @Override - public boolean isPaused() - { + public boolean isPaused() { // no-op return false; } @Override - public boolean isTemporary() - { + public boolean isTemporary() { // no-op return false; } @Override - public boolean isAutoCreated() - { + public boolean isAutoCreated() { return false; } @Override - public LinkedListIterator iterator() - { + public LinkedListIterator iterator() { // no-op return null; } @Override - public boolean moveReference(final long messageID, final SimpleString toAddress) throws Exception - { + public boolean moveReference(final long messageID, final SimpleString toAddress) throws Exception { // no-op return false; } @Override - public int moveReferences(final Filter filter, final SimpleString toAddress) throws Exception - { + public int moveReferences(final Filter filter, final SimpleString toAddress) throws Exception { // no-op return 0; } @Override - public void pause() - { + public void pause() { // no-op } @Override - public void reacknowledge(final Transaction tx, final MessageReference ref) throws Exception - { + public void reacknowledge(final Transaction tx, final MessageReference ref) throws Exception { // no-op } - public void referenceHandled() - { + public void referenceHandled() { // no-op } - public void removeConsumer(final Consumer consumer) - { + public void removeConsumer(final Consumer consumer) { } - public MessageReference removeFirstReference(final long id1) throws Exception - { + public MessageReference removeFirstReference(final long id1) throws Exception { // no-op return null; } - public MessageReference removeReferenceWithID(final long id1) throws Exception - { + public MessageReference removeReferenceWithID(final long id1) throws Exception { // no-op return null; } - public void resume() - { + public void resume() { // no-op } - public boolean sendMessageToDeadLetterAddress(final long messageID) throws Exception - { + public boolean sendMessageToDeadLetterAddress(final long messageID) throws Exception { // no-op return false; } - public int sendMessagesToDeadLetterAddress(Filter filter) throws Exception - { + public int sendMessagesToDeadLetterAddress(Filter filter) throws Exception { // no-op return 0; } - @Override - public SimpleString getExpiryAddress() - { + public SimpleString getExpiryAddress() { return null; } @Override - public void route(final ServerMessage message, final RoutingContext context) throws Exception - { + public void route(final ServerMessage message, final RoutingContext context) throws Exception { // no-op } @Override - public void routeWithAck(ServerMessage message, RoutingContext context) - { + public void routeWithAck(ServerMessage message, RoutingContext context) { } - public boolean hasMatchingConsumer(final ServerMessage message) - { + public boolean hasMatchingConsumer(final ServerMessage message) { // no-op return false; } - public Executor getExecutor() - { + public Executor getExecutor() { // no-op return null; } - public void addLast(MessageReference ref, boolean direct) - { + public void addLast(MessageReference ref, boolean direct) { // no-op } @Override - public PageSubscription getPageSubscription() - { + public PageSubscription getPageSubscription() { return subs; } - public void setPageSubscription(PageSubscription sub) - { + public void setPageSubscription(PageSubscription sub) { this.subs = sub; } @Override - public boolean moveReference(long messageID, SimpleString toAddress, boolean rejectDuplicates) throws Exception - { + public boolean moveReference(long messageID, SimpleString toAddress, boolean rejectDuplicates) throws Exception { // no-op return false; } @Override - public int deleteAllReferences(int flushLimit) throws Exception - { + public int deleteAllReferences(int flushLimit) throws Exception { return 0; } @Override - public int deleteMatchingReferences(int flushLImit, Filter filter) throws Exception - { + public int deleteMatchingReferences(int flushLImit, Filter filter) throws Exception { return 0; } @Override - public int moveReferences(int flushLimit, Filter filter, SimpleString toAddress, boolean rejectDuplicates) throws Exception - { + public int moveReferences(int flushLimit, + Filter filter, + SimpleString toAddress, + boolean rejectDuplicates) throws Exception { return 0; } @Override - public void forceDelivery() - { + public void forceDelivery() { // no-op } @Override - public void deleteQueue() throws Exception - { + public void deleteQueue() throws Exception { // no-op } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.server.Queue#destroyPaging() */ - public void destroyPaging() - { + public void destroyPaging() { } /* (non-Javadoc) * @see org.apache.activemq.artemis.core.server.Queue#getDeliveringMessages() */ @Override - public Map> getDeliveringMessages() - { + public Map> getDeliveringMessages() { return null; } @Override - public LinkedListIterator totalIterator() - { + public LinkedListIterator totalIterator() { // TODO Auto-generated method stub return null; } @Override - public void postAcknowledge(MessageReference ref) - { + public void postAcknowledge(MessageReference ref) { } @Override - public float getRate() - { + public float getRate() { return 0.0f; } @Override - public SimpleString getUser() - { + public SimpleString getUser() { return null; } } \ No newline at end of file diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/QueueComparatorTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/QueueComparatorTest.java index 68702cf972..9562f0d364 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/QueueComparatorTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/QueueComparatorTest.java @@ -26,11 +26,10 @@ import org.apache.activemq.artemis.core.server.impl.ScaleDownHandler; import org.junit.Assert; import org.junit.Test; -public class QueueComparatorTest -{ +public class QueueComparatorTest { + @Test - public void testQueueSorting() - { + public void testQueueSorting() { FakeQueue queue1 = new FakeQueue(new SimpleString("1")); queue1.setMessageCount(1); FakeQueue queue2 = new FakeQueue(new SimpleString("2")); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/WildcardAddressManagerUnitTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/WildcardAddressManagerUnitTest.java index 160668670c..6c298f66e2 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/WildcardAddressManagerUnitTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/WildcardAddressManagerUnitTest.java @@ -34,41 +34,33 @@ import org.apache.activemq.artemis.core.server.RoutingContext; import org.apache.activemq.artemis.core.server.ServerMessage; import org.junit.Test; - /** * This test is replicating the behaviour from https://issues.jboss.org/browse/HORNETQ-988. */ -public class WildcardAddressManagerUnitTest extends ActiveMQTestBase -{ - +public class WildcardAddressManagerUnitTest extends ActiveMQTestBase { @Test - public void testUnitOnWildCardFailingScenario() throws Exception - { + public void testUnitOnWildCardFailingScenario() throws Exception { int errors = 0; WildcardAddressManager ad = new WildcardAddressManager(new BindingFactoryFake()); ad.addBinding(new BindingFake("jms.topic.Topic1", "jms.topic.Topic1")); ad.addBinding(new BindingFake("jms.topic.Topic1", "one")); ad.addBinding(new BindingFake("jms.topic.*", "two")); ad.removeBinding(SimpleString.toSimpleString("one"), null); - try - { + try { ad.removeBinding(SimpleString.toSimpleString("two"), null); } - catch (Throwable e) - { + catch (Throwable e) { // We are not failing the test here as this test is replicating the exact scenario // that was happening under https://issues.jboss.org/browse/HORNETQ-988 // In which this would be ignored errors++; e.printStackTrace(); } - try - { + try { ad.addBinding(new BindingFake("jms.topic.Topic1", "three")); } - catch (Throwable e) - { + catch (Throwable e) { // We are not failing the test here as this test is replicating the exact scenario // that was happening under https://issues.jboss.org/browse/HORNETQ-988 // In which this would be ignored @@ -79,180 +71,150 @@ public class WildcardAddressManagerUnitTest extends ActiveMQTestBase assertEquals("Exception happened during the process", 0, errors); } - class BindingFactoryFake implements BindingsFactory - { - public Bindings createBindings(SimpleString address) throws Exception - { + class BindingFactoryFake implements BindingsFactory { + + public Bindings createBindings(SimpleString address) throws Exception { return new BindignsFake(); } } - class BindingFake implements Binding - { + class BindingFake implements Binding { final SimpleString address; final SimpleString id; - public BindingFake(String addressParameter, String id) - { + public BindingFake(String addressParameter, String id) { this(SimpleString.toSimpleString(addressParameter), SimpleString.toSimpleString(id)); } - public BindingFake(SimpleString addressParameter, SimpleString id) - { + public BindingFake(SimpleString addressParameter, SimpleString id) { this.address = addressParameter; this.id = id; } - @Override - public void unproposed(SimpleString groupID) - { + public void unproposed(SimpleString groupID) { } @Override - public SimpleString getAddress() - { + public SimpleString getAddress() { return address; } @Override - public Bindable getBindable() - { + public Bindable getBindable() { return null; } @Override - public BindingType getType() - { + public BindingType getType() { return null; } @Override - public SimpleString getUniqueName() - { + public SimpleString getUniqueName() { return id; } @Override - public SimpleString getRoutingName() - { + public SimpleString getRoutingName() { return null; } @Override - public SimpleString getClusterName() - { + public SimpleString getClusterName() { return null; } @Override - public Filter getFilter() - { + public Filter getFilter() { return null; } @Override - public boolean isHighAcceptPriority(ServerMessage message) - { + public boolean isHighAcceptPriority(ServerMessage message) { return false; } @Override - public boolean isExclusive() - { + public boolean isExclusive() { return false; } @Override - public long getID() - { + public long getID() { return 0; } @Override - public int getDistance() - { + public int getDistance() { return 0; } @Override - public void route(ServerMessage message, RoutingContext context) throws Exception - { + public void route(ServerMessage message, RoutingContext context) throws Exception { } @Override - public void close() throws Exception - { + public void close() throws Exception { } @Override - public String toManagementString() - { + public String toManagementString() { return "FakeBiding Address=" + this.address; } @Override - public boolean isConnected() - { + public boolean isConnected() { return true; } @Override - public void routeWithAck(ServerMessage message, RoutingContext context) - { + public void routeWithAck(ServerMessage message, RoutingContext context) { } } + class BindignsFake implements Bindings { - class BindignsFake implements Bindings - { ArrayList bindings = new ArrayList(); - @Override - public Collection getBindings() - { + public Collection getBindings() { return bindings; } @Override - public void addBinding(Binding binding) - { + public void addBinding(Binding binding) { bindings.add(binding); } @Override - public void removeBinding(Binding binding) - { + public void removeBinding(Binding binding) { bindings.remove(binding); } @Override - public void setMessageLoadBalancingType(MessageLoadBalancingType messageLoadBalancingType) - { + public void setMessageLoadBalancingType(MessageLoadBalancingType messageLoadBalancingType) { } @Override - public void unproposed(SimpleString groupID) - { + public void unproposed(SimpleString groupID) { } @Override - public boolean redistribute(ServerMessage message, Queue originatingQueue, RoutingContext context) throws Exception - { + public boolean redistribute(ServerMessage message, + Queue originatingQueue, + RoutingContext context) throws Exception { return false; } @Override - public void route(ServerMessage message, RoutingContext context) throws Exception - { + public void route(ServerMessage message, RoutingContext context) throws Exception { System.out.println("routing message: " + message); } } - } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/ActiveMQBufferTestBase.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/ActiveMQBufferTestBase.java index 4e9c3e9b47..d028085b56 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/ActiveMQBufferTestBase.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/ActiveMQBufferTestBase.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.unit.core.remoting; + import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Before; @@ -27,8 +28,7 @@ import org.junit.Assert; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.tests.util.RandomUtil; -public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase -{ +public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -43,8 +43,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); wrapper = createBuffer(); @@ -52,8 +51,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { wrapper = null; super.tearDown(); @@ -62,14 +60,12 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase protected abstract ActiveMQBuffer createBuffer(); @Test - public void testNullString() throws Exception - { + public void testNullString() throws Exception { Assert.assertNull(putAndGetNullableString(null)); } @Test - public void testEmptyString() throws Exception - { + public void testEmptyString() throws Exception { String result = putAndGetNullableString(""); Assert.assertNotNull(result); @@ -77,8 +73,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase } @Test - public void testNonEmptyString() throws Exception - { + public void testNonEmptyString() throws Exception { String junk = RandomUtil.randomString(); String result = putAndGetNullableString(junk); @@ -88,14 +83,12 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase } @Test - public void testNullSimpleString() throws Exception - { + public void testNullSimpleString() throws Exception { Assert.assertNull(putAndGetNullableSimpleString(null)); } @Test - public void testEmptySimpleString() throws Exception - { + public void testEmptySimpleString() throws Exception { SimpleString emptySimpleString = new SimpleString(""); SimpleString result = putAndGetNullableSimpleString(emptySimpleString); @@ -104,8 +97,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase } @Test - public void testNonEmptySimpleString() throws Exception - { + public void testNonEmptySimpleString() throws Exception { SimpleString junk = RandomUtil.randomSimpleString(); SimpleString result = putAndGetNullableSimpleString(junk); @@ -114,8 +106,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase } @Test - public void testByte() throws Exception - { + public void testByte() throws Exception { byte b = RandomUtil.randomByte(); wrapper.writeByte(b); @@ -123,22 +114,20 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase } @Test - public void testUnsignedByte() throws Exception - { - byte b = (byte)0xff; + public void testUnsignedByte() throws Exception { + byte b = (byte) 0xff; wrapper.writeByte(b); Assert.assertEquals(255, wrapper.readUnsignedByte()); - b = (byte)0xf; + b = (byte) 0xf; wrapper.writeByte(b); Assert.assertEquals(b, wrapper.readUnsignedByte()); } @Test - public void testBytes() throws Exception - { + public void testBytes() throws Exception { byte[] bytes = RandomUtil.randomBytes(); wrapper.writeBytes(bytes); @@ -148,8 +137,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase } @Test - public void testBytesWithLength() throws Exception - { + public void testBytesWithLength() throws Exception { byte[] bytes = RandomUtil.randomBytes(); // put only half of the bytes wrapper.writeBytes(bytes, 0, bytes.length / 2); @@ -160,32 +148,28 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase } @Test - public void testPutTrueBoolean() throws Exception - { + public void testPutTrueBoolean() throws Exception { wrapper.writeBoolean(true); Assert.assertTrue(wrapper.readBoolean()); } @Test - public void testPutFalseBoolean() throws Exception - { + public void testPutFalseBoolean() throws Exception { wrapper.writeBoolean(false); Assert.assertFalse(wrapper.readBoolean()); } @Test - public void testChar() throws Exception - { + public void testChar() throws Exception { wrapper.writeChar('a'); Assert.assertEquals('a', wrapper.readChar()); } @Test - public void testInt() throws Exception - { + public void testInt() throws Exception { int i = RandomUtil.randomInt(); wrapper.writeInt(i); @@ -193,8 +177,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase } @Test - public void testIntAtPosition() throws Exception - { + public void testIntAtPosition() throws Exception { int firstInt = RandomUtil.randomInt(); int secondInt = RandomUtil.randomInt(); @@ -208,8 +191,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase } @Test - public void testLong() throws Exception - { + public void testLong() throws Exception { long l = RandomUtil.randomLong(); wrapper.writeLong(l); @@ -217,8 +199,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase } @Test - public void testUnsignedShort() throws Exception - { + public void testUnsignedShort() throws Exception { short s1 = Short.MAX_VALUE; wrapper.writeShort(s1); @@ -247,16 +228,14 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase } @Test - public void testShort() throws Exception - { - wrapper.writeShort((short)1); + public void testShort() throws Exception { + wrapper.writeShort((short) 1); - Assert.assertEquals((short)1, wrapper.readShort()); + Assert.assertEquals((short) 1, wrapper.readShort()); } @Test - public void testDouble() throws Exception - { + public void testDouble() throws Exception { double d = RandomUtil.randomDouble(); wrapper.writeDouble(d); @@ -264,8 +243,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase } @Test - public void testFloat() throws Exception - { + public void testFloat() throws Exception { float f = RandomUtil.randomFloat(); wrapper.writeFloat(f); @@ -273,8 +251,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase } @Test - public void testUTF() throws Exception - { + public void testUTF() throws Exception { String str = RandomUtil.randomString(); wrapper.writeUTF(str); @@ -282,8 +259,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase } @Test - public void testArray() throws Exception - { + public void testArray() throws Exception { byte[] bytes = RandomUtil.randomBytes(128); wrapper.writeBytes(bytes); @@ -293,8 +269,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase } @Test - public void testRewind() throws Exception - { + public void testRewind() throws Exception { int i = RandomUtil.randomInt(); wrapper.writeInt(i); @@ -306,8 +281,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase } @Test - public void testRemaining() throws Exception - { + public void testRemaining() throws Exception { int capacity = wrapper.capacity(); // fill 1/3 of the buffer @@ -320,8 +294,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase } @Test - public void testPosition() throws Exception - { + public void testPosition() throws Exception { Assert.assertEquals(0, wrapper.writerIndex()); byte[] bytes = RandomUtil.randomBytes(128); @@ -339,15 +312,13 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase // Private ------------------------------------------------------- - private String putAndGetNullableString(final String nullableString) throws Exception - { + private String putAndGetNullableString(final String nullableString) throws Exception { wrapper.writeNullableString(nullableString); return wrapper.readNullableString(); } - private SimpleString putAndGetNullableSimpleString(final SimpleString nullableSimpleString) throws Exception - { + private SimpleString putAndGetNullableSimpleString(final SimpleString nullableSimpleString) throws Exception { wrapper.writeNullableSimpleString(nullableSimpleString); return wrapper.readNullableSimpleString(); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/invm/InVMConnectorFactoryTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/invm/InVMConnectorFactoryTest.java index d01012ebf9..3fe6af144e 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/invm/InVMConnectorFactoryTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/invm/InVMConnectorFactoryTest.java @@ -26,11 +26,10 @@ import org.junit.Test; import static org.junit.Assert.assertTrue; -public class InVMConnectorFactoryTest -{ +public class InVMConnectorFactoryTest { + @Test - public void testCreateConnectorSetsDefaults() - { + public void testCreateConnectorSetsDefaults() { // Test defaults are added when TransportConfig params are empty TransportConfiguration tc = new TransportConfiguration(InVMConnectorFactory.class.getName(), new HashMap()); assertTrue(tc.getParams().equals(InVMConnector.DEFAULT_CONFIG)); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/ChannelBufferWrapper2Test.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/ChannelBufferWrapper2Test.java index e008c760ff..8a1183e3c7 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/ChannelBufferWrapper2Test.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/ChannelBufferWrapper2Test.java @@ -23,8 +23,7 @@ import org.apache.activemq.artemis.tests.unit.core.remoting.ActiveMQBufferTestBa /** * Same as ChannelBufferWrapperTest, but using a different constructor */ -public class ChannelBufferWrapper2Test extends ActiveMQBufferTestBase -{ +public class ChannelBufferWrapper2Test extends ActiveMQBufferTestBase { // Constants ----------------------------------------------------- @@ -39,8 +38,7 @@ public class ChannelBufferWrapper2Test extends ActiveMQBufferTestBase // BufferWrapperBase overrides ----------------------------------- @Override - protected ActiveMQBuffer createBuffer() - { + protected ActiveMQBuffer createBuffer() { return ActiveMQBuffers.dynamicBuffer(512); } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyAcceptorFactoryTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyAcceptorFactoryTest.java index 26d981fa67..470122860a 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyAcceptorFactoryTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyAcceptorFactoryTest.java @@ -34,52 +34,38 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Assert; import org.junit.Test; -public class NettyAcceptorFactoryTest extends ActiveMQTestBase -{ +public class NettyAcceptorFactoryTest extends ActiveMQTestBase { + @Test - public void testCreateAcceptor() throws Exception - { + public void testCreateAcceptor() throws Exception { NettyAcceptorFactory factory = new NettyAcceptorFactory(); Map params = new HashMap(); - BufferHandler handler = new BufferHandler() - { + BufferHandler handler = new BufferHandler() { - public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) - { + public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) { } }; - ConnectionLifeCycleListener listener = new ConnectionLifeCycleListener() - { + ConnectionLifeCycleListener listener = new ConnectionLifeCycleListener() { - public void connectionException(final Object connectionID, final ActiveMQException me) - { + public void connectionException(final Object connectionID, final ActiveMQException me) { } - public void connectionDestroyed(final Object connectionID) - { + public void connectionDestroyed(final Object connectionID) { } - public void connectionCreated(ActiveMQComponent component, final Connection connection, final String protocol) - { + public void connectionCreated(ActiveMQComponent component, + final Connection connection, + final String protocol) { } - public void connectionReadyForWrites(Object connectionID, boolean ready) - { + public void connectionReadyForWrites(Object connectionID, boolean ready) { } - }; - Acceptor acceptor = factory.createAcceptor("netty", - null, - params, - handler, - listener, - Executors.newCachedThreadPool(), - Executors.newScheduledThreadPool(ActiveMQDefaultConfiguration.getDefaultScheduledThreadPoolMaxSize()), - null); + Acceptor acceptor = factory.createAcceptor("netty", null, params, handler, listener, Executors.newCachedThreadPool(), Executors.newScheduledThreadPool(ActiveMQDefaultConfiguration.getDefaultScheduledThreadPoolMaxSize()), null); Assert.assertTrue(acceptor instanceof NettyAcceptor); } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyAcceptorTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyAcceptorTest.java index 67f1b23c6b..7743020193 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyAcceptorTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyAcceptorTest.java @@ -37,14 +37,13 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class NettyAcceptorTest extends ActiveMQTestBase -{ +public class NettyAcceptorTest extends ActiveMQTestBase { + private ScheduledExecutorService pool2; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); ActiveMQTestBase.checkFreePort(TransportConstants.DEFAULT_PORT); @@ -52,14 +51,11 @@ public class NettyAcceptorTest extends ActiveMQTestBase @Override @After - public void tearDown() throws Exception - { - try - { + public void tearDown() throws Exception { + try { ActiveMQTestBase.checkFreePort(TransportConstants.DEFAULT_PORT); } - finally - { + finally { if (pool2 != null) pool2.shutdownNow(); super.tearDown(); @@ -67,44 +63,32 @@ public class NettyAcceptorTest extends ActiveMQTestBase } @Test - public void testStartStop() throws Exception - { - BufferHandler handler = new BufferHandler() - { + public void testStartStop() throws Exception { + BufferHandler handler = new BufferHandler() { - public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) - { + public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) { } }; Map params = new HashMap(); - ConnectionLifeCycleListener listener = new ConnectionLifeCycleListener() - { + ConnectionLifeCycleListener listener = new ConnectionLifeCycleListener() { - public void connectionException(final Object connectionID, final ActiveMQException me) - { + public void connectionException(final Object connectionID, final ActiveMQException me) { } - public void connectionDestroyed(final Object connectionID) - { + public void connectionDestroyed(final Object connectionID) { } - public void connectionCreated(final ActiveMQComponent component, final Connection connection, final String protocol) - { + public void connectionCreated(final ActiveMQComponent component, + final Connection connection, + final String protocol) { } - public void connectionReadyForWrites(Object connectionID, boolean ready) - { + public void connectionReadyForWrites(Object connectionID, boolean ready) { } }; pool2 = Executors.newScheduledThreadPool(ActiveMQDefaultConfiguration.getDefaultScheduledThreadPoolMaxSize()); - NettyAcceptor acceptor = new NettyAcceptor("netty", - null, - params, - handler, - listener, - pool2, - null); + NettyAcceptor acceptor = new NettyAcceptor("netty", null, params, handler, listener, pool2, null); addActiveMQComponent(acceptor); acceptor.start(); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyConnectionTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyConnectionTest.java index aef1083e48..a4e6810a7f 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyConnectionTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyConnectionTest.java @@ -34,13 +34,12 @@ import org.apache.activemq.artemis.spi.core.remoting.ConnectionLifeCycleListener import org.junit.Assert; import org.junit.Test; -public class NettyConnectionTest extends ActiveMQTestBase -{ +public class NettyConnectionTest extends ActiveMQTestBase { + private static final Map emptyMap = Collections.emptyMap(); @Test - public void testGetID() throws Exception - { + public void testGetID() throws Exception { Channel channel = createChannel(); NettyConnection conn = new NettyConnection(emptyMap, channel, new MyListener(), false, false); @@ -48,8 +47,7 @@ public class NettyConnectionTest extends ActiveMQTestBase } @Test - public void testWrite() throws Exception - { + public void testWrite() throws Exception { ActiveMQBuffer buff = ActiveMQBuffers.wrappedBuffer(ByteBuffer.allocate(128)); EmbeddedChannel channel = createChannel(); @@ -62,8 +60,7 @@ public class NettyConnectionTest extends ActiveMQTestBase } @Test - public void testCreateBuffer() throws Exception - { + public void testCreateBuffer() throws Exception { EmbeddedChannel channel = createChannel(); NettyConnection conn = new NettyConnection(emptyMap, channel, new MyListener(), false, false); @@ -75,31 +72,27 @@ public class NettyConnectionTest extends ActiveMQTestBase } - private static EmbeddedChannel createChannel() - { + private static EmbeddedChannel createChannel() { return new EmbeddedChannel(new ChannelInboundHandlerAdapter()); } - class MyListener implements ConnectionLifeCycleListener - { + class MyListener implements ConnectionLifeCycleListener { - public void connectionCreated(final ActiveMQComponent component, final Connection connection, final String protocol) - { + public void connectionCreated(final ActiveMQComponent component, + final Connection connection, + final String protocol) { } - public void connectionDestroyed(final Object connectionID) - { + public void connectionDestroyed(final Object connectionID) { } - public void connectionException(final Object connectionID, final ActiveMQException me) - { + public void connectionException(final Object connectionID, final ActiveMQException me) { } - public void connectionReadyForWrites(Object connectionID, boolean ready) - { + public void connectionReadyForWrites(Object connectionID, boolean ready) { } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyConnectorFactoryTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyConnectorFactoryTest.java index 7a7edf89a9..b391b2c292 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyConnectorFactoryTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyConnectorFactoryTest.java @@ -26,11 +26,10 @@ import org.junit.Test; import static org.junit.Assert.assertTrue; -public class NettyConnectorFactoryTest -{ +public class NettyConnectorFactoryTest { + @Test - public void testCreateConnectorSetsDefaults() - { + public void testCreateConnectorSetsDefaults() { // Test defaults are added when TransportConfig params are empty TransportConfiguration tc = new TransportConfiguration(NettyConnectorFactory.class.getName(), new HashMap()); assertTrue(tc.getParams().equals(NettyConnector.DEFAULT_CONFIG)); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyConnectorTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyConnectorTest.java index 303d03a7d7..ca9bf0d74e 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyConnectorTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyConnectorTest.java @@ -34,43 +34,32 @@ import org.apache.activemq.artemis.spi.core.remoting.BufferHandler; import org.apache.activemq.artemis.spi.core.remoting.Connection; import org.apache.activemq.artemis.spi.core.remoting.ConnectionLifeCycleListener; -public class NettyConnectorTest extends ActiveMQTestBase -{ +public class NettyConnectorTest extends ActiveMQTestBase { @Test - public void testStartStop() throws Exception - { - BufferHandler handler = new BufferHandler() - { - public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) - { + public void testStartStop() throws Exception { + BufferHandler handler = new BufferHandler() { + public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) { } }; Map params = new HashMap(); - ConnectionLifeCycleListener listener = new ConnectionLifeCycleListener() - { - public void connectionException(final Object connectionID, final ActiveMQException me) - { + ConnectionLifeCycleListener listener = new ConnectionLifeCycleListener() { + public void connectionException(final Object connectionID, final ActiveMQException me) { } - public void connectionDestroyed(final Object connectionID) - { + public void connectionDestroyed(final Object connectionID) { } - public void connectionCreated(final ActiveMQComponent component, final Connection connection, final String protocol) - { + public void connectionCreated(final ActiveMQComponent component, + final Connection connection, + final String protocol) { } - public void connectionReadyForWrites(Object connectionID, boolean ready) - { + + public void connectionReadyForWrites(Object connectionID, boolean ready) { } }; - NettyConnector connector = new NettyConnector(params, - handler, - listener, - Executors.newCachedThreadPool(), - Executors.newCachedThreadPool(), - Executors.newScheduledThreadPool(5)); + NettyConnector connector = new NettyConnector(params, handler, listener, Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), Executors.newScheduledThreadPool(5)); connector.start(); Assert.assertTrue(connector.isStarted()); @@ -79,73 +68,51 @@ public class NettyConnectorTest extends ActiveMQTestBase } @Test - public void testNullParams() throws Exception - { - BufferHandler handler = new BufferHandler() - { - public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) - { + public void testNullParams() throws Exception { + BufferHandler handler = new BufferHandler() { + public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) { } }; Map params = new HashMap(); - ConnectionLifeCycleListener listener = new ConnectionLifeCycleListener() - { - public void connectionException(final Object connectionID, final ActiveMQException me) - { + ConnectionLifeCycleListener listener = new ConnectionLifeCycleListener() { + public void connectionException(final Object connectionID, final ActiveMQException me) { } - public void connectionDestroyed(final Object connectionID) - { + public void connectionDestroyed(final Object connectionID) { } - public void connectionCreated(final ActiveMQComponent component, final Connection connection, final String protocol) - { + public void connectionCreated(final ActiveMQComponent component, + final Connection connection, + final String protocol) { } - public void connectionReadyForWrites(Object connectionID, boolean ready) - { + public void connectionReadyForWrites(Object connectionID, boolean ready) { } }; - try - { - new NettyConnector(params, - null, - listener, - Executors.newCachedThreadPool(), - Executors.newCachedThreadPool(), - Executors.newScheduledThreadPool(5)); + try { + new NettyConnector(params, null, listener, Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), Executors.newScheduledThreadPool(5)); Assert.fail("Should throw Exception"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { // Ok } - try - { - new NettyConnector(params, - handler, - null, - Executors.newCachedThreadPool(), - Executors.newCachedThreadPool(), - Executors.newScheduledThreadPool(5)); + try { + new NettyConnector(params, handler, null, Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), Executors.newScheduledThreadPool(5)); Assert.fail("Should throw Exception"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { // Ok } } + @Test - public void testJavaSystemPropertyOverrides() throws Exception - { - BufferHandler handler = new BufferHandler() - { - public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) - { + public void testJavaSystemPropertyOverrides() throws Exception { + BufferHandler handler = new BufferHandler() { + public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) { } }; Map params = new HashMap(); @@ -154,31 +121,23 @@ public class NettyConnectorTest extends ActiveMQTestBase params.put(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, "bad password"); params.put(TransportConstants.TRUSTSTORE_PATH_PROP_NAME, "bad path"); params.put(TransportConstants.TRUSTSTORE_PASSWORD_PROP_NAME, "bad password"); - ConnectionLifeCycleListener listener = new ConnectionLifeCycleListener() - { - public void connectionException(final Object connectionID, final ActiveMQException me) - { + ConnectionLifeCycleListener listener = new ConnectionLifeCycleListener() { + public void connectionException(final Object connectionID, final ActiveMQException me) { } - public void connectionDestroyed(final Object connectionID) - { + public void connectionDestroyed(final Object connectionID) { } - public void connectionCreated(final ActiveMQComponent component, final Connection connection, final String protocol) - { + public void connectionCreated(final ActiveMQComponent component, + final Connection connection, + final String protocol) { } - public void connectionReadyForWrites(Object connectionID, boolean ready) - { + + public void connectionReadyForWrites(Object connectionID, boolean ready) { } }; - NettyConnector connector = new NettyConnector(params, - handler, - listener, - Executors.newCachedThreadPool(), - Executors.newCachedThreadPool(), - Executors.newScheduledThreadPool(5)); - + NettyConnector connector = new NettyConnector(params, handler, listener, Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), Executors.newScheduledThreadPool(5)); System.setProperty(NettyConnector.JAVAX_KEYSTORE_PATH_PROP_NAME, "client-side-keystore.jks"); System.setProperty(NettyConnector.JAVAX_KEYSTORE_PASSWORD_PROP_NAME, "secureexample"); @@ -190,13 +149,11 @@ public class NettyConnectorTest extends ActiveMQTestBase connector.close(); Assert.assertFalse(connector.isStarted()); } + @Test - public void testActiveMQSystemPropertyOverrides() throws Exception - { - BufferHandler handler = new BufferHandler() - { - public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) - { + public void testActiveMQSystemPropertyOverrides() throws Exception { + BufferHandler handler = new BufferHandler() { + public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) { } }; Map params = new HashMap(); @@ -205,31 +162,23 @@ public class NettyConnectorTest extends ActiveMQTestBase params.put(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, "bad password"); params.put(TransportConstants.TRUSTSTORE_PATH_PROP_NAME, "bad path"); params.put(TransportConstants.TRUSTSTORE_PASSWORD_PROP_NAME, "bad password"); - ConnectionLifeCycleListener listener = new ConnectionLifeCycleListener() - { - public void connectionException(final Object connectionID, final ActiveMQException me) - { + ConnectionLifeCycleListener listener = new ConnectionLifeCycleListener() { + public void connectionException(final Object connectionID, final ActiveMQException me) { } - public void connectionDestroyed(final Object connectionID) - { + public void connectionDestroyed(final Object connectionID) { } - public void connectionCreated(final ActiveMQComponent component, final Connection connection, final String protocol) - { + public void connectionCreated(final ActiveMQComponent component, + final Connection connection, + final String protocol) { } - public void connectionReadyForWrites(Object connectionID, boolean ready) - { + + public void connectionReadyForWrites(Object connectionID, boolean ready) { } }; - NettyConnector connector = new NettyConnector(params, - handler, - listener, - Executors.newCachedThreadPool(), - Executors.newCachedThreadPool(), - Executors.newScheduledThreadPool(5)); - + NettyConnector connector = new NettyConnector(params, handler, listener, Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), Executors.newScheduledThreadPool(5)); System.setProperty(NettyConnector.JAVAX_KEYSTORE_PATH_PROP_NAME, "bad path"); System.setProperty(NettyConnector.JAVAX_KEYSTORE_PASSWORD_PROP_NAME, "bad password"); @@ -241,7 +190,6 @@ public class NettyConnectorTest extends ActiveMQTestBase System.setProperty(NettyConnector.ACTIVEMQ_TRUSTSTORE_PATH_PROP_NAME, "client-side-truststore.jks"); System.setProperty(NettyConnector.ACTIVEMQ_TRUSTSTORE_PASSWORD_PROP_NAME, "secureexample"); - connector.start(); Assert.assertTrue(connector.isStarted()); connector.close(); @@ -249,42 +197,31 @@ public class NettyConnectorTest extends ActiveMQTestBase } @Test - public void testBadCipherSuite() throws Exception - { - BufferHandler handler = new BufferHandler() - { - public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) - { + public void testBadCipherSuite() throws Exception { + BufferHandler handler = new BufferHandler() { + public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) { } }; Map params = new HashMap(); params.put(TransportConstants.SSL_ENABLED_PROP_NAME, true); params.put(TransportConstants.ENABLED_CIPHER_SUITES_PROP_NAME, "myBadCipherSuite"); - ConnectionLifeCycleListener listener = new ConnectionLifeCycleListener() - { - public void connectionException(final Object connectionID, final ActiveMQException me) - { + ConnectionLifeCycleListener listener = new ConnectionLifeCycleListener() { + public void connectionException(final Object connectionID, final ActiveMQException me) { } - public void connectionDestroyed(final Object connectionID) - { + public void connectionDestroyed(final Object connectionID) { } - public void connectionCreated(final ActiveMQComponent component, final Connection connection, final String protocol) - { + public void connectionCreated(final ActiveMQComponent component, + final Connection connection, + final String protocol) { } - public void connectionReadyForWrites(Object connectionID, boolean ready) - { + + public void connectionReadyForWrites(Object connectionID, boolean ready) { } }; - NettyConnector connector = new NettyConnector(params, - handler, - listener, - Executors.newCachedThreadPool(), - Executors.newCachedThreadPool(), - Executors.newScheduledThreadPool(5)); - + NettyConnector connector = new NettyConnector(params, handler, listener, Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), Executors.newScheduledThreadPool(5)); connector.start(); Assert.assertTrue(connector.isStarted()); @@ -294,42 +231,31 @@ public class NettyConnectorTest extends ActiveMQTestBase } @Test - public void testBadProtocol() throws Exception - { - BufferHandler handler = new BufferHandler() - { - public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) - { + public void testBadProtocol() throws Exception { + BufferHandler handler = new BufferHandler() { + public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) { } }; Map params = new HashMap(); params.put(TransportConstants.SSL_ENABLED_PROP_NAME, true); params.put(TransportConstants.ENABLED_PROTOCOLS_PROP_NAME, "myBadProtocol"); - ConnectionLifeCycleListener listener = new ConnectionLifeCycleListener() - { - public void connectionException(final Object connectionID, final ActiveMQException me) - { + ConnectionLifeCycleListener listener = new ConnectionLifeCycleListener() { + public void connectionException(final Object connectionID, final ActiveMQException me) { } - public void connectionDestroyed(final Object connectionID) - { + public void connectionDestroyed(final Object connectionID) { } - public void connectionCreated(final ActiveMQComponent component, final Connection connection, final String protocol) - { + public void connectionCreated(final ActiveMQComponent component, + final Connection connection, + final String protocol) { } - public void connectionReadyForWrites(Object connectionID, boolean ready) - { + + public void connectionReadyForWrites(Object connectionID, boolean ready) { } }; - NettyConnector connector = new NettyConnector(params, - handler, - listener, - Executors.newCachedThreadPool(), - Executors.newCachedThreadPool(), - Executors.newScheduledThreadPool(5)); - + NettyConnector connector = new NettyConnector(params, handler, listener, Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), Executors.newScheduledThreadPool(5)); connector.start(); Assert.assertTrue(connector.isStarted()); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/ssl/SSLSupportTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/ssl/SSLSupportTest.java index b0835639ce..cb2655296f 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/ssl/SSLSupportTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/ssl/SSLSupportTest.java @@ -30,19 +30,14 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) -public class SSLSupportTest extends ActiveMQTestBase -{ +public class SSLSupportTest extends ActiveMQTestBase { + @Parameterized.Parameters(name = "storeType={0}") - public static Collection getParameters() - { - return Arrays.asList(new Object[][]{ - {"JCEKS"}, - {"JKS"} - }); + public static Collection getParameters() { + return Arrays.asList(new Object[][]{{"JCEKS"}, {"JKS"}}); } - public SSLSupportTest(String storeType) - { + public SSLSupportTest(String storeType) { this.storeType = storeType; keyStorePath = "server-side-keystore." + storeType.toLowerCase(); trustStorePath = "server-side-truststore." + storeType.toLowerCase(); @@ -70,75 +65,62 @@ public class SSLSupportTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); keyStorePassword = "secureexample"; trustStorePassword = keyStorePassword; } @Test - public void testContextWithRightParameters() throws Exception - { + public void testContextWithRightParameters() throws Exception { SSLSupport.createContext(storeType, keyStorePath, keyStorePassword, storeType, trustStorePath, trustStorePassword); } // This is valid as it will create key and trust managers with system defaults @Test - public void testContextWithNullParameters() throws Exception - { + public void testContextWithNullParameters() throws Exception { SSLSupport.createContext(null, null, null, null, null, null); } @Test - public void testContextWithKeyStorePathAsURL() throws Exception - { + public void testContextWithKeyStorePathAsURL() throws Exception { URL url = Thread.currentThread().getContextClassLoader().getResource(keyStorePath); SSLSupport.createContext(storeType, url.toString(), keyStorePassword, storeType, trustStorePath, trustStorePassword); } @Test - public void testContextWithKeyStorePathAsFile() throws Exception - { + public void testContextWithKeyStorePathAsFile() throws Exception { URL url = Thread.currentThread().getContextClassLoader().getResource(keyStorePath); File file = new File(url.toURI()); SSLSupport.createContext(storeType, file.getAbsolutePath(), keyStorePassword, storeType, trustStorePath, trustStorePassword); } @Test - public void testContextWithBadKeyStorePath() throws Exception - { - try - { + public void testContextWithBadKeyStorePath() throws Exception { + try { SSLSupport.createContext(storeType, "not a keystore", keyStorePassword, storeType, trustStorePath, trustStorePassword); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { } } @Test - public void testContextWithNullKeyStorePath() throws Exception - { - try - { + public void testContextWithNullKeyStorePath() throws Exception { + try { SSLSupport.createContext(storeType, null, keyStorePassword, storeType, trustStorePath, trustStorePassword); } - catch (Exception e) - { + catch (Exception e) { Assert.fail(); } } @Test - public void testContextWithKeyStorePathAsRelativePath() throws Exception - { + public void testContextWithKeyStorePathAsRelativePath() throws Exception { // this test is dependent on a path relative to the tests directory. // it will fail if launch from somewhere else (or from an IDE) File currentDir = new File(System.getProperty("user.dir")); - if (!currentDir.getAbsolutePath().endsWith("tests")) - { + if (!currentDir.getAbsolutePath().endsWith("tests")) { return; } @@ -146,41 +128,32 @@ public class SSLSupportTest extends ActiveMQTestBase } @Test - public void testContextWithBadKeyStorePassword() throws Exception - { - try - { + public void testContextWithBadKeyStorePassword() throws Exception { + try { SSLSupport.createContext(storeType, keyStorePath, "bad password", storeType, trustStorePath, trustStorePassword); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { } } @Test - public void testContextWithBadTrustStorePath() throws Exception - { - try - { + public void testContextWithBadTrustStorePath() throws Exception { + try { SSLSupport.createContext(storeType, keyStorePath, keyStorePassword, storeType, "not a trust store", trustStorePassword); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { } } @Test - public void testContextWithBadTrustStorePassword() throws Exception - { - try - { + public void testContextWithBadTrustStorePassword() throws Exception { + try { SSLSupport.createContext(storeType, keyStorePath, keyStorePassword, storeType, trustStorePath, "bad passord"); Assert.fail(); } - catch (Exception e) - { + catch (Exception e) { } } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/server/impl/RemotingServiceImplTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/server/impl/RemotingServiceImplTest.java index 8486f922ad..37a2b940b4 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/server/impl/RemotingServiceImplTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/server/impl/RemotingServiceImplTest.java @@ -34,8 +34,8 @@ import org.junit.Test; import static org.junit.Assert.assertTrue; -public class RemotingServiceImplTest -{ +public class RemotingServiceImplTest { + private ServiceRegistry serviceRegistry; private RemotingServiceImpl remotingService; @@ -43,8 +43,7 @@ public class RemotingServiceImplTest private Configuration configuration; @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { serviceRegistry = new ServiceRegistryImpl(); configuration = new ConfigurationImpl(); configuration.setAcceptorConfigurations(new HashSet()); @@ -55,10 +54,8 @@ public class RemotingServiceImplTest * Tests that the service registry gets propaged into remotingService. */ @Test - public void testPropagatingInterceptors() throws Exception - { - for (int i = 0; i < 5; i++) - { + public void testPropagatingInterceptors() throws Exception { + for (int i = 0; i < 5; i++) { serviceRegistry.addIncomingInterceptor(new FakeInterceptor()); } @@ -74,8 +71,7 @@ public class RemotingServiceImplTest * defined in the configuration. */ @Test - public void testSetInterceptorsAddsBothInterceptorsFromConfigAndServiceRegistry() throws Exception - { + public void testSetInterceptorsAddsBothInterceptorsFromConfigAndServiceRegistry() throws Exception { Method method = RemotingServiceImpl.class.getDeclaredMethod("setInterceptors", Configuration.class); Field incomingInterceptors = RemotingServiceImpl.class.getDeclaredField("incomingInterceptors"); Field outgoingInterceptors = RemotingServiceImpl.class.getDeclaredField("outgoingInterceptors"); @@ -94,8 +90,8 @@ public class RemotingServiceImplTest method.invoke(remotingService, configuration); - assertTrue(((List) incomingInterceptors.get(remotingService)).size() == 2 ); - assertTrue(((List) outgoingInterceptors.get(remotingService)).size() == 2 ); + assertTrue(((List) incomingInterceptors.get(remotingService)).size() == 2); + assertTrue(((List) outgoingInterceptors.get(remotingService)).size() == 2); assertTrue(((List) incomingInterceptors.get(remotingService)).contains(serviceRegistry.getIncomingInterceptors(null).get(0))); assertTrue(((List) outgoingInterceptors.get(remotingService)).contains(serviceRegistry.getOutgoingInterceptors(null).get(0))); } @@ -105,8 +101,7 @@ public class RemotingServiceImplTest * are added to the RemotingServiceImpl on creation */ @Test - public void testInterceptorsAreAddedOnCreationOfServiceRegistry() throws Exception - { + public void testInterceptorsAreAddedOnCreationOfServiceRegistry() throws Exception { Field incomingInterceptors = RemotingServiceImpl.class.getDeclaredField("incomingInterceptors"); Field outgoingInterceptors = RemotingServiceImpl.class.getDeclaredField("outgoingInterceptors"); @@ -123,8 +118,8 @@ public class RemotingServiceImplTest remotingService = new RemotingServiceImpl(null, configuration, null, null, null, null, null, serviceRegistry); - assertTrue(((List) incomingInterceptors.get(remotingService)).size() == 2 ); - assertTrue(((List) outgoingInterceptors.get(remotingService)).size() == 2 ); + assertTrue(((List) incomingInterceptors.get(remotingService)).size() == 2); + assertTrue(((List) outgoingInterceptors.get(remotingService)).size() == 2); assertTrue(((List) incomingInterceptors.get(remotingService)).contains(serviceRegistry.getIncomingInterceptors(null).get(0))); assertTrue(((List) outgoingInterceptors.get(remotingService)).contains(serviceRegistry.getOutgoingInterceptors(null).get(0))); } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/server/impl/fake/FakeInterceptor.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/server/impl/fake/FakeInterceptor.java index cabb0a3118..f8028ea61f 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/server/impl/fake/FakeInterceptor.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/server/impl/fake/FakeInterceptor.java @@ -21,12 +21,10 @@ import org.apache.activemq.artemis.api.core.Interceptor; import org.apache.activemq.artemis.core.protocol.core.Packet; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; -public class FakeInterceptor implements Interceptor -{ +public class FakeInterceptor implements Interceptor { @Override - public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException - { + public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException { return false; } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/security/impl/ActiveMQSecurityManagerImplTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/security/impl/ActiveMQSecurityManagerImplTest.java index c729d271b9..ea8ca0ccc7 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/security/impl/ActiveMQSecurityManagerImplTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/security/impl/ActiveMQSecurityManagerImplTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.unit.core.security.impl; + import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Before; import org.junit.After; @@ -32,14 +33,13 @@ import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManagerImpl /** * tests ActiveMQSecurityManagerImpl */ -public class ActiveMQSecurityManagerImplTest extends ActiveMQTestBase -{ +public class ActiveMQSecurityManagerImplTest extends ActiveMQTestBase { + private ActiveMQSecurityManagerImpl securityManager; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); securityManager = new ActiveMQSecurityManagerImpl(); @@ -47,16 +47,14 @@ public class ActiveMQSecurityManagerImplTest extends ActiveMQTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { securityManager = null; super.tearDown(); } @Test - public void testDefaultSecurity() - { + public void testDefaultSecurity() { securityManager.getConfiguration().addUser("guest", "password"); securityManager.getConfiguration().addRole("guest", "guest"); securityManager.getConfiguration().setDefaultUser("guest"); @@ -86,35 +84,29 @@ public class ActiveMQSecurityManagerImplTest extends ActiveMQTestBase } @Test - public void testAddingUsers() - { + public void testAddingUsers() { securityManager.getConfiguration().addUser("newuser1", "newpassword1"); Assert.assertTrue(securityManager.validateUser("newuser1", "newpassword1")); Assert.assertFalse(securityManager.validateUser("newuser1", "guest")); Assert.assertFalse(securityManager.validateUser("newuser1", null)); - try - { + try { securityManager.getConfiguration().addUser("newuser2", null); Assert.fail("password cannot be null"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { // pass } - try - { + try { securityManager.getConfiguration().addUser(null, "newpassword2"); Assert.fail("password cannot be null"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { // pass } } @Test - public void testRemovingUsers() - { + public void testRemovingUsers() { securityManager.getConfiguration().addUser("newuser1", "newpassword1"); Assert.assertTrue(securityManager.validateUser("newuser1", "newpassword1")); securityManager.getConfiguration().removeUser("newuser1"); @@ -122,8 +114,7 @@ public class ActiveMQSecurityManagerImplTest extends ActiveMQTestBase } @Test - public void testRemovingInvalidUsers() - { + public void testRemovingInvalidUsers() { securityManager.getConfiguration().addUser("newuser1", "newpassword1"); Assert.assertTrue(securityManager.validateUser("newuser1", "newpassword1")); securityManager.getConfiguration().removeUser("nonuser"); @@ -131,8 +122,7 @@ public class ActiveMQSecurityManagerImplTest extends ActiveMQTestBase } @Test - public void testAddingRoles() - { + public void testAddingRoles() { securityManager.getConfiguration().addUser("newuser1", "newpassword1"); securityManager.getConfiguration().addRole("newuser1", "role1"); securityManager.getConfiguration().addRole("newuser1", "role2"); @@ -156,8 +146,7 @@ public class ActiveMQSecurityManagerImplTest extends ActiveMQTestBase } @Test - public void testRemovingRoles() - { + public void testRemovingRoles() { securityManager.getConfiguration().addUser("newuser1", "newpassword1"); securityManager.getConfiguration().addRole("newuser1", "role1"); securityManager.getConfiguration().addRole("newuser1", "role2"); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/cluster/impl/ClusterConnectionBridgeTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/cluster/impl/ClusterConnectionBridgeTest.java index 60471e0a55..f33e0798e8 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/cluster/impl/ClusterConnectionBridgeTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/cluster/impl/ClusterConnectionBridgeTest.java @@ -21,27 +21,24 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.core.server.cluster.impl.ClusterConnectionBridge; import org.junit.Test; -public class ClusterConnectionBridgeTest extends ActiveMQTestBase -{ +public class ClusterConnectionBridgeTest extends ActiveMQTestBase { + @Test - public void testCreateSelectorFromAddressForNormalMatches() - { + public void testCreateSelectorFromAddressForNormalMatches() { String address = "jms.my.address"; String expectedSelector = ManagementHelper.HDR_ADDRESS + " LIKE '" + address + "%'"; assertEquals(expectedSelector, ClusterConnectionBridge.createSelectorFromAddress(address)); } @Test - public void testCreateSelectorFromAddressForExclusions() - { + public void testCreateSelectorFromAddressForExclusions() { String address = "jms.my.address"; String expectedSelector = ManagementHelper.HDR_ADDRESS + " NOT LIKE '" + address + "%'"; assertEquals(expectedSelector, ClusterConnectionBridge.createSelectorFromAddress("!" + address)); } @Test - public void testCreateSelectorFromListForNormalMatches() - { + public void testCreateSelectorFromListForNormalMatches() { String address1 = "jms.test1.address"; String address2 = "jms.test2.address"; String addresses = address1 + "," + address2; @@ -56,8 +53,7 @@ public class ClusterConnectionBridgeTest extends ActiveMQTestBase } @Test - public void testCreateSelectorFromListForExclusions() - { + public void testCreateSelectorFromListForExclusions() { String address1 = "jms.test1.address"; String address2 = "jms.test2.address"; String addresses = "!" + address1 + "," + "!" + address2; @@ -72,8 +68,7 @@ public class ClusterConnectionBridgeTest extends ActiveMQTestBase } @Test - public void testCreateSelectorFromListForExclusionsAndNormalMatches() - { + public void testCreateSelectorFromListForExclusionsAndNormalMatches() { String address1 = "jms.test1.address"; String address2 = "jms.test2.address"; String address3 = "jms.test3.address"; @@ -93,8 +88,7 @@ public class ClusterConnectionBridgeTest extends ActiveMQTestBase } @Test - public void testCreateSelectorFromListIgnoresEmptyStrings() - { + public void testCreateSelectorFromListIgnoresEmptyStrings() { String address1 = "jms.test1.address"; String address2 = "jms.test2.address"; String addresses = address1 + ",!" + address2 + ",,,"; diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/cluster/impl/RemoteQueueBindImplTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/cluster/impl/RemoteQueueBindImplTest.java index 18f45223c6..fae2d051b9 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/cluster/impl/RemoteQueueBindImplTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/cluster/impl/RemoteQueueBindImplTest.java @@ -25,8 +25,7 @@ import org.apache.activemq.artemis.core.server.Queue; import org.apache.activemq.artemis.core.server.cluster.impl.RemoteQueueBindingImpl; import org.apache.activemq.artemis.tests.util.RandomUtil; -public class RemoteQueueBindImplTest extends ActiveMQTestBase -{ +public class RemoteQueueBindImplTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -39,8 +38,7 @@ public class RemoteQueueBindImplTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testAddRemoveConsumer() throws Exception - { + public void testAddRemoveConsumer() throws Exception { final long id = RandomUtil.randomLong(); final SimpleString address = RandomUtil.randomSimpleString(); @@ -51,25 +49,15 @@ public class RemoteQueueBindImplTest extends ActiveMQTestBase final Queue storeAndForwardQueue = new FakeQueue(null); final SimpleString bridgeName = RandomUtil.randomSimpleString(); final int distance = 0; - RemoteQueueBindingImpl binding = new RemoteQueueBindingImpl(id, - address, - uniqueName, - routingName, - remoteQueueID, - filterString, - storeAndForwardQueue, - bridgeName, - distance); + RemoteQueueBindingImpl binding = new RemoteQueueBindingImpl(id, address, uniqueName, routingName, remoteQueueID, filterString, storeAndForwardQueue, bridgeName, distance); - for (int i = 0; i < 100; i++) - { + for (int i = 0; i < 100; i++) { binding.addConsumer(new SimpleString("B" + i + " refs = new ArrayList(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { MessageReference ref = generateReference(queue, i); refs.add(ref); @@ -261,8 +245,7 @@ public class QueueImplTest extends ActiveMQTestBase } @Test - public void testBusyConsumer() throws Exception - { + public void testBusyConsumer() throws Exception { QueueImpl queue = getTemporaryQueue(); FakeConsumer consumer = new FakeConsumer(); @@ -275,8 +258,7 @@ public class QueueImplTest extends ActiveMQTestBase List refs = new ArrayList(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { MessageReference ref = generateReference(queue, i); refs.add(ref); @@ -306,8 +288,7 @@ public class QueueImplTest extends ActiveMQTestBase } @Test - public void testBusyConsumerThenAddMoreMessages() throws Exception - { + public void testBusyConsumerThenAddMoreMessages() throws Exception { QueueImpl queue = getTemporaryQueue(); FakeConsumer consumer = new FakeConsumer(); @@ -320,8 +301,7 @@ public class QueueImplTest extends ActiveMQTestBase List refs = new ArrayList(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { MessageReference ref = generateReference(queue, i); refs.add(ref); @@ -340,8 +320,7 @@ public class QueueImplTest extends ActiveMQTestBase Assert.assertEquals(0, queue.getDeliveringCount()); Assert.assertTrue(consumer.getReferences().isEmpty()); - for (int i = numMessages; i < numMessages * 2; i++) - { + for (int i = numMessages; i < numMessages * 2; i++) { MessageReference ref = generateReference(queue, i); refs.add(ref); @@ -356,8 +335,7 @@ public class QueueImplTest extends ActiveMQTestBase consumer.setStatusImmediate(HandleStatus.HANDLED); - for (int i = numMessages * 2; i < numMessages * 3; i++) - { + for (int i = numMessages * 2; i < numMessages * 3; i++) { MessageReference ref = generateReference(queue, i); refs.add(ref); @@ -374,16 +352,14 @@ public class QueueImplTest extends ActiveMQTestBase } @Test - public void testaddHeadadd() throws Exception - { + public void testaddHeadadd() throws Exception { QueueImpl queue = getTemporaryQueue(); final int numMessages = 10; List refs1 = new ArrayList(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { MessageReference ref = generateReference(queue, i); refs1.add(ref); @@ -393,8 +369,7 @@ public class QueueImplTest extends ActiveMQTestBase LinkedList refs2 = new LinkedList(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { MessageReference ref = generateReference(queue, i + numMessages); refs2.addFirst(ref); @@ -404,8 +379,7 @@ public class QueueImplTest extends ActiveMQTestBase List refs3 = new ArrayList(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { MessageReference ref = generateReference(queue, i + 2 * numMessages); refs3.add(ref); @@ -429,16 +403,14 @@ public class QueueImplTest extends ActiveMQTestBase } @Test - public void testChangeConsumersAndDeliver() throws Exception - { + public void testChangeConsumersAndDeliver() throws Exception { QueueImpl queue = getTemporaryQueue(); final int numMessages = 10; List refs = new ArrayList(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { MessageReference ref = generateReference(queue, i); refs.add(ref); @@ -470,15 +442,13 @@ public class QueueImplTest extends ActiveMQTestBase cons1.getReferences().clear(); - for (MessageReference ref : refs) - { + for (MessageReference ref : refs) { queue.acknowledge(ref); } refs.clear(); - for (int i = 0; i < 2 * numMessages; i++) - { + for (int i = 0; i < 2 * numMessages; i++) { MessageReference ref = generateReference(queue, i); refs.add(ref); @@ -499,8 +469,7 @@ public class QueueImplTest extends ActiveMQTestBase cons1.getReferences().clear(); cons2.getReferences().clear(); - for (MessageReference ref : refs) - { + for (MessageReference ref : refs) { queue.acknowledge(ref); } refs.clear(); @@ -511,8 +480,7 @@ public class QueueImplTest extends ActiveMQTestBase Assert.assertEquals(3, queue.getConsumerCount()); - for (int i = 0; i < 3 * numMessages; i++) - { + for (int i = 0; i < 3 * numMessages; i++) { MessageReference ref = generateReference(queue, i); refs.add(ref); @@ -537,14 +505,12 @@ public class QueueImplTest extends ActiveMQTestBase cons3.getReferences().clear(); cons2.getReferences().clear(); - for (MessageReference ref : refs) - { + for (MessageReference ref : refs) { queue.acknowledge(ref); } refs.clear(); - for (int i = 0; i < 2 * numMessages; i++) - { + for (int i = 0; i < 2 * numMessages; i++) { MessageReference ref = generateReference(queue, i); refs.add(ref); @@ -566,14 +532,12 @@ public class QueueImplTest extends ActiveMQTestBase cons2.getReferences().clear(); - for (MessageReference ref : refs) - { + for (MessageReference ref : refs) { queue.acknowledge(ref); } refs.clear(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { MessageReference ref = generateReference(queue, i); refs.add(ref); @@ -591,10 +555,8 @@ public class QueueImplTest extends ActiveMQTestBase } - @Test - public void testRoundRobinWithQueueing() throws Exception - { + public void testRoundRobinWithQueueing() throws Exception { QueueImpl queue = getTemporaryQueue(); final int numMessages = 10; @@ -605,8 +567,7 @@ public class QueueImplTest extends ActiveMQTestBase // Test first with queueing - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { MessageReference ref = generateReference(queue, i); refs.add(ref); @@ -626,13 +587,11 @@ public class QueueImplTest extends ActiveMQTestBase // Need to make sure the consumers will receive the messages before we do these assertions long timeout = System.currentTimeMillis() + 5000; - while (cons1.getReferences().size() != numMessages / 2 && timeout > System.currentTimeMillis()) - { + while (cons1.getReferences().size() != numMessages / 2 && timeout > System.currentTimeMillis()) { Thread.sleep(1); } - while (cons2.getReferences().size() != numMessages / 2 && timeout > System.currentTimeMillis()) - { + while (cons2.getReferences().size() != numMessages / 2 && timeout > System.currentTimeMillis()) { Thread.sleep(1); } @@ -640,8 +599,7 @@ public class QueueImplTest extends ActiveMQTestBase Assert.assertEquals(numMessages / 2, cons2.getReferences().size()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { MessageReference ref; ref = i % 2 == 0 ? cons1.getReferences().get(i / 2) : cons2.getReferences().get(i / 2); @@ -651,16 +609,14 @@ public class QueueImplTest extends ActiveMQTestBase } @Test - public void testWithPriorities() throws Exception - { + public void testWithPriorities() throws Exception { QueueImpl queue = getTemporaryQueue(); final int numMessages = 10; List refs = new ArrayList(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { MessageReference ref = generateReference(queue, i); ref.getMessage().setPriority((byte) i); @@ -684,28 +640,24 @@ public class QueueImplTest extends ActiveMQTestBase Assert.assertEquals(refs.size(), receivedRefs.size()); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { Assert.assertEquals(refs.get(i), receivedRefs.get(9 - i)); } } @Test - public void testConsumerWithFiltersDirect() throws Exception - { + public void testConsumerWithFiltersDirect() throws Exception { testConsumerWithFilters(true); } @Test - public void testConsumerWithFiltersQueueing() throws Exception - { + public void testConsumerWithFiltersQueueing() throws Exception { testConsumerWithFilters(false); } @Test - public void testConsumerWithFilterAddAndRemove() - { + public void testConsumerWithFilterAddAndRemove() { QueueImpl queue = getTemporaryQueue(); Filter filter = new FakeFilter("fruit", "orange"); @@ -714,16 +666,14 @@ public class QueueImplTest extends ActiveMQTestBase } @Test - public void testIterator() - { + public void testIterator() { QueueImpl queue = getTemporaryQueue(); final int numMessages = 20; List refs = new ArrayList(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { MessageReference ref = generateReference(queue, i); queue.addTail(ref); @@ -735,15 +685,13 @@ public class QueueImplTest extends ActiveMQTestBase Iterator iterator = queue.iterator(); List list = new ArrayList(); - while (iterator.hasNext()) - { + while (iterator.hasNext()) { list.add(iterator.next()); } assertRefListsIdenticalRefs(refs, list); } - private void awaitExecution() - { + private void awaitExecution() { FutureLatch future = new FutureLatch(); executor.execute(future); @@ -752,8 +700,7 @@ public class QueueImplTest extends ActiveMQTestBase } @Test - public void testConsumeWithFiltersAddAndRemoveConsumer() throws Exception - { + public void testConsumeWithFiltersAddAndRemoveConsumer() throws Exception { QueueImpl queue = getTemporaryQueue(); @@ -827,8 +774,7 @@ public class QueueImplTest extends ActiveMQTestBase } @Test - public void testBusyConsumerWithFilterFirstCallBusy() throws Exception - { + public void testBusyConsumerWithFilterFirstCallBusy() throws Exception { QueueImpl queue = getTemporaryQueue(); FakeConsumer consumer = new FakeConsumer(FilterImpl.createFilter("color = 'green'")); @@ -841,8 +787,7 @@ public class QueueImplTest extends ActiveMQTestBase List refs = new ArrayList(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { MessageReference ref = generateReference(queue, i); ref.getMessage().putStringProperty("color", "green"); refs.add(ref); @@ -862,15 +807,13 @@ public class QueueImplTest extends ActiveMQTestBase List receeivedRefs = consumer.getReferences(); int currId = 0; - for (MessageReference receeivedRef : receeivedRefs) - { + for (MessageReference receeivedRef : receeivedRefs) { Assert.assertEquals("messages received out of order", receeivedRef.getMessage().getMessageID(), currId++); } } @Test - public void testBusyConsumerWithFilterThenAddMoreMessages() throws Exception - { + public void testBusyConsumerWithFilterThenAddMoreMessages() throws Exception { QueueImpl queue = getTemporaryQueue(); FakeConsumer consumer = new FakeConsumer(FilterImpl.createFilter("color = 'green'")); @@ -883,8 +826,7 @@ public class QueueImplTest extends ActiveMQTestBase List refs = new ArrayList(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { MessageReference ref = generateReference(queue, i); ref.getMessage().putStringProperty("color", "red"); refs.add(ref); @@ -903,8 +845,7 @@ public class QueueImplTest extends ActiveMQTestBase Assert.assertEquals(0, queue.getDeliveringCount()); Assert.assertTrue(consumer.getReferences().isEmpty()); - for (int i = numMessages; i < numMessages * 2; i++) - { + for (int i = numMessages; i < numMessages * 2; i++) { MessageReference ref = generateReference(queue, i); refs.add(ref); @@ -919,8 +860,7 @@ public class QueueImplTest extends ActiveMQTestBase consumer.setStatusImmediate(null); - for (int i = numMessages * 2; i < numMessages * 3; i++) - { + for (int i = numMessages * 2; i < numMessages * 3; i++) { MessageReference ref = generateReference(queue, i); refs.add(ref); @@ -937,22 +877,19 @@ public class QueueImplTest extends ActiveMQTestBase List receeivedRefs = consumer.getReferences(); int currId = 10; - for (MessageReference receeivedRef : receeivedRefs) - { + for (MessageReference receeivedRef : receeivedRefs) { Assert.assertEquals("messages received out of order", receeivedRef.getMessage().getMessageID(), currId++); } } @Test - public void testConsumerWithFilterThenAddMoreMessages() throws Exception - { + public void testConsumerWithFilterThenAddMoreMessages() throws Exception { QueueImpl queue = getTemporaryQueue(); final int numMessages = 10; List refs = new ArrayList(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { MessageReference ref = generateReference(queue, i); ref.getMessage().putStringProperty("color", "red"); refs.add(ref); @@ -970,8 +907,7 @@ public class QueueImplTest extends ActiveMQTestBase Assert.assertEquals(0, queue.getScheduledCount()); Assert.assertEquals(0, queue.getDeliveringCount()); - for (int i = numMessages; i < numMessages * 2; i++) - { + for (int i = numMessages; i < numMessages * 2; i++) { MessageReference ref = generateReference(queue, i); refs.add(ref); @@ -989,8 +925,7 @@ public class QueueImplTest extends ActiveMQTestBase Assert.assertEquals(0, queue.getScheduledCount()); Assert.assertEquals(10, queue.getDeliveringCount()); - for (int i = numMessages * 2; i < numMessages * 3; i++) - { + for (int i = numMessages * 2; i < numMessages * 3; i++) { MessageReference ref = generateReference(queue, i); refs.add(ref); @@ -1008,16 +943,14 @@ public class QueueImplTest extends ActiveMQTestBase // Private ------------------------------------------------------------------------------ - private void testConsumerWithFilters(final boolean direct) throws Exception - { + private void testConsumerWithFilters(final boolean direct) throws Exception { QueueImpl queue = getTemporaryQueue(); Filter filter = new FakeFilter("fruit", "orange"); FakeConsumer consumer = new FakeConsumer(filter); - if (direct) - { + if (direct) { queue.addConsumer(consumer); } @@ -1063,14 +996,12 @@ public class QueueImplTest extends ActiveMQTestBase queue.addTail(ref6); - if (!direct) - { + if (!direct) { queue.addConsumer(consumer); queue.deliverNow(); } - Assert.assertEquals(6, getMessageCount(queue)); awaitExecution(); @@ -1100,8 +1031,7 @@ public class QueueImplTest extends ActiveMQTestBase } @Test - public void testMessageOrder() throws Exception - { + public void testMessageOrder() throws Exception { FakeConsumer consumer = new FakeConsumer(); QueueImpl queue = getTemporaryQueue(); MessageReference messageReference = generateReference(queue, 1); @@ -1122,8 +1052,7 @@ public class QueueImplTest extends ActiveMQTestBase } @Test - public void testMessagesAdded() throws Exception - { + public void testMessagesAdded() throws Exception { QueueImpl queue = getTemporaryQueue(); MessageReference messageReference = generateReference(queue, 1); MessageReference messageReference2 = generateReference(queue, 2); @@ -1135,8 +1064,7 @@ public class QueueImplTest extends ActiveMQTestBase } @Test - public void testGetReference() throws Exception - { + public void testGetReference() throws Exception { QueueImpl queue = getTemporaryQueue(); MessageReference messageReference = generateReference(queue, 1); MessageReference messageReference2 = generateReference(queue, 2); @@ -1149,8 +1077,7 @@ public class QueueImplTest extends ActiveMQTestBase } @Test - public void testGetNonExistentReference() throws Exception - { + public void testGetNonExistentReference() throws Exception { QueueImpl queue = getTemporaryQueue(); MessageReference messageReference = generateReference(queue, 1); MessageReference messageReference2 = generateReference(queue, 2); @@ -1168,8 +1095,7 @@ public class QueueImplTest extends ActiveMQTestBase * @throws Exception */ @Test - public void testPauseAndResumeWithAsync() throws Exception - { + public void testPauseAndResumeWithAsync() throws Exception { QueueImpl queue = getTemporaryQueue(); // pauses the queue @@ -1179,8 +1105,7 @@ public class QueueImplTest extends ActiveMQTestBase List refs = new ArrayList(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { MessageReference ref = generateReference(queue, i); refs.add(ref); @@ -1226,8 +1151,7 @@ public class QueueImplTest extends ActiveMQTestBase */ @Test - public void testPauseAndResumeWithDirect() throws Exception - { + public void testPauseAndResumeWithDirect() throws Exception { QueueImpl queue = getTemporaryQueue(); // Now add a consumer @@ -1242,8 +1166,7 @@ public class QueueImplTest extends ActiveMQTestBase List refs = new ArrayList(); - for (int i = 0; i < numMessages; i++) - { + for (int i = 0; i < numMessages; i++) { MessageReference ref = generateReference(queue, i); refs.add(ref); queue.addTail(ref); @@ -1260,7 +1183,6 @@ public class QueueImplTest extends ActiveMQTestBase // brings the queue to resumed state. queue.resume(); - awaitExecution(); // resuming delivery of messages @@ -1271,8 +1193,7 @@ public class QueueImplTest extends ActiveMQTestBase } @Test - public void testResetMessagesAdded() throws Exception - { + public void testResetMessagesAdded() throws Exception { QueueImpl queue = getTemporaryQueue(); MessageReference messageReference = generateReference(queue, 1); MessageReference messageReference2 = generateReference(queue, 2); @@ -1283,8 +1204,8 @@ public class QueueImplTest extends ActiveMQTestBase Assert.assertEquals(0, getMessagesAdded(queue)); } - class AddtoQueueRunner implements Runnable - { + class AddtoQueueRunner implements Runnable { + QueueImpl queue; MessageReference messageReference; @@ -1298,22 +1219,18 @@ public class QueueImplTest extends ActiveMQTestBase public AddtoQueueRunner(final boolean first, final QueueImpl queue, final MessageReference messageReference, - final CountDownLatch countDownLatch) - { + final CountDownLatch countDownLatch) { this.queue = queue; this.messageReference = messageReference; this.countDownLatch = countDownLatch; this.first = first; } - public void run() - { - if (first) - { + public void run() { + if (first) { queue.addHead(messageReference); } - else - { + else { queue.addTail(messageReference); } added = true; @@ -1322,23 +1239,17 @@ public class QueueImplTest extends ActiveMQTestBase } @Test - public void testTotalIteratorOrder() throws Exception - { + public void testTotalIteratorOrder() throws Exception { final String MY_ADDRESS = "myAddress"; final String MY_QUEUE = "myQueue"; ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(createDefaultInVMConfig(), true)); - AddressSettings defaultSetting = new AddressSettings() - .setPageSizeBytes(10 * 1024) - .setMaxSizeBytes(20 * 1024); + AddressSettings defaultSetting = new AddressSettings().setPageSizeBytes(10 * 1024).setMaxSizeBytes(20 * 1024); server.getAddressSettingsRepository().addMatch("#", defaultSetting); server.start(); - ServerLocator locator = createInVMNonHALocator() - .setBlockOnNonDurableSend(true) - .setBlockOnDurableSend(true) - .setBlockOnAcknowledge(true); + ServerLocator locator = createInVMNonHALocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true); ClientSessionFactory factory = createSessionFactory(locator); ClientSession session = addClientSession(factory.createSession(false, true, true)); @@ -1347,8 +1258,7 @@ public class QueueImplTest extends ActiveMQTestBase ClientProducer producer = addClientProducer(session.createProducer(MY_ADDRESS)); - for (int i = 0; i < 50; i++) - { + for (int i = 0; i < 50; i++) { ClientMessage message = session.createMessage(true); message.getBodyBuffer().writeBytes(new byte[1024]); message.putIntProperty("order", i); @@ -1363,61 +1273,40 @@ public class QueueImplTest extends ActiveMQTestBase Queue queue = ((LocalQueueBinding) server.getPostOffice().getBinding(new SimpleString(MY_QUEUE))).getQueue(); LinkedListIterator totalIterator = queue.totalIterator(); - try - { + try { int i = 0; - while (totalIterator.hasNext()) - { + while (totalIterator.hasNext()) { MessageReference ref = totalIterator.next(); Assert.assertEquals(i++, ref.getMessage().getIntProperty("order").intValue()); } } - finally - { + finally { totalIterator.close(); server.stop(); } } - private QueueImpl getNonDurableQueue() - { + private QueueImpl getNonDurableQueue() { return getQueue(QueueImplTest.queue1, false, false, null); } - private QueueImpl getDurableQueue() - { + private QueueImpl getDurableQueue() { return getQueue(QueueImplTest.queue1, true, false, null); } - private QueueImpl getNamedQueue(SimpleString name) - { + private QueueImpl getNamedQueue(SimpleString name) { return getQueue(name, false, true, null); } - private QueueImpl getFilteredQueue(Filter filter) - { + private QueueImpl getFilteredQueue(Filter filter) { return getQueue(QueueImplTest.queue1, false, true, filter); } - private QueueImpl getTemporaryQueue() - { + private QueueImpl getTemporaryQueue() { return getQueue(QueueImplTest.queue1, false, true, null); } - private QueueImpl getQueue(SimpleString name, boolean durable, boolean temporary, Filter filter) - { - return new QueueImpl(1, - QueueImplTest.address1, - name, - filter, - null, - durable, - temporary, - false, - scheduledExecutor, - new FakePostOffice(), - null, - null, - executor); + private QueueImpl getQueue(SimpleString name, boolean durable, boolean temporary, Filter filter) { + return new QueueImpl(1, QueueImplTest.address1, name, filter, null, durable, temporary, false, scheduledExecutor, new FakePostOffice(), null, null, executor); } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/fakes/FakeConsumer.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/fakes/FakeConsumer.java index e85cdddc17..dc109b143a 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/fakes/FakeConsumer.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/fakes/FakeConsumer.java @@ -25,8 +25,8 @@ import org.apache.activemq.artemis.core.server.Consumer; import org.apache.activemq.artemis.core.server.HandleStatus; import org.apache.activemq.artemis.core.server.MessageReference; -public class FakeConsumer implements Consumer -{ +public class FakeConsumer implements Consumer { + private HandleStatus statusToReturn = HandleStatus.HANDLED; private HandleStatus newStatus; @@ -37,110 +37,88 @@ public class FakeConsumer implements Consumer private final Filter filter; - public FakeConsumer() - { + public FakeConsumer() { filter = null; } - public FakeConsumer(final Filter filter) - { + public FakeConsumer(final Filter filter) { this.filter = filter; } - public Filter getFilter() - { + public Filter getFilter() { return filter; } - public String debug() - { + public String debug() { return toString(); } - public synchronized MessageReference waitForNextReference(long timeout) - { - while (references.isEmpty() && timeout > 0) - { + public synchronized MessageReference waitForNextReference(long timeout) { + while (references.isEmpty() && timeout > 0) { long start = System.currentTimeMillis(); - try - { + try { wait(); } - catch (InterruptedException e) - { + catch (InterruptedException e) { } timeout -= System.currentTimeMillis() - start; } - if (timeout <= 0) - { + if (timeout <= 0) { throw new IllegalStateException("Timed out waiting for reference"); } return references.removeFirst(); } - public synchronized void setStatusImmediate(final HandleStatus newStatus) - { + public synchronized void setStatusImmediate(final HandleStatus newStatus) { statusToReturn = newStatus; } - public synchronized void setStatusDelayed(final HandleStatus newStatus, final int numReferences) - { + public synchronized void setStatusDelayed(final HandleStatus newStatus, final int numReferences) { this.newStatus = newStatus; delayCountdown = numReferences; } - public synchronized List getReferences() - { + public synchronized List getReferences() { return references; } - public synchronized void clearReferences() - { + public synchronized void clearReferences() { references.clear(); } - public synchronized HandleStatus handle(final MessageReference reference) - { - if (statusToReturn == HandleStatus.BUSY) - { + public synchronized HandleStatus handle(final MessageReference reference) { + if (statusToReturn == HandleStatus.BUSY) { return HandleStatus.BUSY; } - if (filter != null) - { - if (filter.match(reference.getMessage())) - { + if (filter != null) { + if (filter.match(reference.getMessage())) { references.addLast(reference); reference.getQueue().referenceHandled(); notify(); return HandleStatus.HANDLED; } - else - { + else { return HandleStatus.NO_MATCH; } } - if (newStatus != null) - { - if (delayCountdown == 0) - { + if (newStatus != null) { + if (delayCountdown == 0) { statusToReturn = newStatus; newStatus = null; } - else - { + else { delayCountdown--; } } - if (statusToReturn == HandleStatus.HANDLED) - { + if (statusToReturn == HandleStatus.HANDLED) { reference.getQueue().referenceHandled(); references.addLast(reference); notify(); @@ -150,28 +128,22 @@ public class FakeConsumer implements Consumer } @Override - public void proceedDeliver(MessageReference ref) throws Exception - { + public void proceedDeliver(MessageReference ref) throws Exception { // no op } @Override - public String toManagementString() - { + public String toManagementString() { return toString(); } @Override - public void disconnect() - { + public void disconnect() { //To change body of implemented methods use File | Settings | File Templates. } - public List getDeliveringMessages() - { + public List getDeliveringMessages() { return Collections.emptyList(); } - - } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/fakes/FakeFilter.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/fakes/FakeFilter.java index 1f2870e44a..51f07808c2 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/fakes/FakeFilter.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/fakes/FakeFilter.java @@ -20,36 +20,30 @@ import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.filter.Filter; import org.apache.activemq.artemis.core.server.ServerMessage; -public class FakeFilter implements Filter -{ +public class FakeFilter implements Filter { + private String headerName; private Object headerValue; - public FakeFilter(final String headerName, final Object headerValue) - { + public FakeFilter(final String headerName, final Object headerValue) { this.headerName = headerName; this.headerValue = headerValue; } - public FakeFilter() - { + public FakeFilter() { } - public boolean match(final ServerMessage message) - { - if (headerName != null) - { + public boolean match(final ServerMessage message) { + if (headerName != null) { Object value = message.getObjectProperty(new SimpleString(headerName)); - if (value instanceof SimpleString) - { - value = ((SimpleString)value).toString(); + if (value instanceof SimpleString) { + value = ((SimpleString) value).toString(); } - if (value != null && headerValue.equals(value)) - { + if (value != null && headerValue.equals(value)) { return true; } @@ -59,8 +53,7 @@ public class FakeFilter implements Filter return true; } - public SimpleString getFilterString() - { + public SimpleString getFilterString() { return null; } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/fakes/FakeJournalLoader.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/fakes/FakeJournalLoader.java index b5afa9fc3a..32ad718299 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/fakes/FakeJournalLoader.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/fakes/FakeJournalLoader.java @@ -33,61 +33,56 @@ import org.apache.activemq.artemis.core.server.impl.JournalLoader; import org.apache.activemq.artemis.core.transaction.ResourceManager; import org.apache.activemq.artemis.core.transaction.Transaction; -public class FakeJournalLoader implements JournalLoader -{ +public class FakeJournalLoader implements JournalLoader { + @Override - public void handleNoMessageReferences(Map messages) - { + public void handleNoMessageReferences(Map messages) { } @Override - public void handleAddMessage(Map> queueMap) throws Exception - { + public void handleAddMessage(Map> queueMap) throws Exception { } @Override - public void initQueues(Map queueBindingInfosMap, List queueBindingInfos) throws Exception - { + public void initQueues(Map queueBindingInfosMap, + List queueBindingInfos) throws Exception { } @Override - public void handleGroupingBindings(List groupingInfos) - { + public void handleGroupingBindings(List groupingInfos) { } @Override - public void handleDuplicateIds(Map>> duplicateIDMap) throws Exception - { + public void handleDuplicateIds(Map>> duplicateIDMap) throws Exception { } @Override - public void postLoad(Journal messageJournal, ResourceManager resourceManager, Map>> duplicateIDMap) - { + public void postLoad(Journal messageJournal, + ResourceManager resourceManager, + Map>> duplicateIDMap) { } @Override - public void handlePreparedSendMessage(ServerMessage message, Transaction tx, long queueID) - { + public void handlePreparedSendMessage(ServerMessage message, Transaction tx, long queueID) { } @Override - public void handlePreparedAcknowledge(long messageID, List referencesToAck, long queueID) - { + public void handlePreparedAcknowledge(long messageID, List referencesToAck, long queueID) { } @Override - public void handlePreparedTransaction(Transaction tx, List referencesToAck, Xid xid, ResourceManager resourceManager) - { + public void handlePreparedTransaction(Transaction tx, + List referencesToAck, + Xid xid, + ResourceManager resourceManager) { } @Override - public void recoverPendingPageCounters(List pendingNonTXPageCounter) throws Exception - { + public void recoverPendingPageCounters(List pendingNonTXPageCounter) throws Exception { } @Override - public void cleanUp() - { + public void cleanUp() { } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/fakes/FakePostOffice.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/fakes/FakePostOffice.java index 2113290965..dc51f0e9c8 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/fakes/FakePostOffice.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/fakes/FakePostOffice.java @@ -35,159 +35,141 @@ import org.apache.activemq.artemis.core.server.ServerMessage; import org.apache.activemq.artemis.core.server.impl.MessageReferenceImpl; import org.apache.activemq.artemis.core.transaction.Transaction; -public class FakePostOffice implements PostOffice -{ +public class FakePostOffice implements PostOffice { @Override - public boolean isStarted() - { + public boolean isStarted() { return false; } @Override - public Set getAddresses() - { + public Set getAddresses() { return null; } @Override - public void start() throws Exception - { - + public void start() throws Exception { } @Override - public void stop() throws Exception - { - + public void stop() throws Exception { } @Override - public void addBinding(final Binding binding) throws Exception - { - + public void addBinding(final Binding binding) throws Exception { } @Override - public Binding getBinding(final SimpleString uniqueName) - { + public Binding getBinding(final SimpleString uniqueName) { return null; } @Override - public Bindings getBindingsForAddress(final SimpleString address) throws Exception - { + public Bindings getBindingsForAddress(final SimpleString address) throws Exception { return null; } @Override - public Map getAllBindings() - { + public Map getAllBindings() { return null; } - public Bindings lookupBindingsForAddress(final SimpleString address) throws Exception - { + public Bindings lookupBindingsForAddress(final SimpleString address) throws Exception { return null; } @Override - public DuplicateIDCache getDuplicateIDCache(final SimpleString address) - { + public DuplicateIDCache getDuplicateIDCache(final SimpleString address) { return new DuplicateIDCacheImpl(address, 2000, new NullStorageManager(), false); } @Override - public Bindings getMatchingBindings(final SimpleString address) - { + public Bindings getMatchingBindings(final SimpleString address) { return null; } @Override - public Object getNotificationLock() - { + public Object getNotificationLock() { return null; } @Override - public void startExpiryScanner() - { + public void startExpiryScanner() { } @Override - public boolean isAddressBound(SimpleString address) throws Exception - { + public boolean isAddressBound(SimpleString address) throws Exception { return false; } @Override - public Binding removeBinding(final SimpleString uniqueName, final Transaction tx) throws Exception - { + public Binding removeBinding(final SimpleString uniqueName, final Transaction tx) throws Exception { return null; } @Override - public void sendQueueInfoToQueue(final SimpleString queueName, final SimpleString address) throws Exception - { - + public void sendQueueInfoToQueue(final SimpleString queueName, final SimpleString address) throws Exception { } - public Pair redistribute(final ServerMessage message, final Queue originatingQueue, final Transaction tx) throws Exception - { + public Pair redistribute(final ServerMessage message, + final Queue originatingQueue, + final Transaction tx) throws Exception { return null; } - public MessageReference reroute(final ServerMessage message, final Queue queue, final Transaction tx) throws Exception - { + public MessageReference reroute(final ServerMessage message, + final Queue queue, + final Transaction tx) throws Exception { message.incrementRefCount(); return new MessageReferenceImpl(); } - public void route(ServerMessage message, QueueCreator creator, RoutingContext context, boolean direct) throws Exception - { - + public void route(ServerMessage message, + QueueCreator creator, + RoutingContext context, + boolean direct) throws Exception { } - public void route(ServerMessage message, QueueCreator creator, Transaction tx, boolean direct) throws Exception - { - + public void route(ServerMessage message, QueueCreator creator, Transaction tx, boolean direct) throws Exception { } @Override - public void route(ServerMessage message, QueueCreator creator, RoutingContext context, boolean direct, boolean rejectDuplicates) throws Exception - { - + public void route(ServerMessage message, + QueueCreator creator, + RoutingContext context, + boolean direct, + boolean rejectDuplicates) throws Exception { } @Override - public void route(ServerMessage message, QueueCreator creator, Transaction tx, boolean direct, boolean rejectDuplicates) throws Exception - { - + public void route(ServerMessage message, + QueueCreator creator, + Transaction tx, + boolean direct, + boolean rejectDuplicates) throws Exception { } @Override - public void processRoute(ServerMessage message, RoutingContext context, boolean direct) throws Exception - { + public void processRoute(ServerMessage message, RoutingContext context, boolean direct) throws Exception { } @Override - public void route(ServerMessage message, QueueCreator queueCreator, boolean direct) throws Exception - { + public void route(ServerMessage message, QueueCreator queueCreator, boolean direct) throws Exception { } } \ No newline at end of file diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/fakes/FakeQueueFactory.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/fakes/FakeQueueFactory.java index efca9c9e82..288b6f9900 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/fakes/FakeQueueFactory.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/fakes/FakeQueueFactory.java @@ -28,8 +28,8 @@ import org.apache.activemq.artemis.core.server.Queue; import org.apache.activemq.artemis.core.server.QueueFactory; import org.apache.activemq.artemis.core.server.impl.QueueImpl; -public class FakeQueueFactory implements QueueFactory -{ +public class FakeQueueFactory implements QueueFactory { + private final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); private final ExecutorService executor = Executors.newSingleThreadExecutor(); @@ -44,32 +44,16 @@ public class FakeQueueFactory implements QueueFactory final SimpleString user, final boolean durable, final boolean temporary, - final boolean autoCreated) - { - return new QueueImpl(persistenceID, - address, - name, - filter, - subscription, - user, - durable, - temporary, - autoCreated, - scheduledExecutor, - postOffice, - null, - null, - executor); + final boolean autoCreated) { + return new QueueImpl(persistenceID, address, name, filter, subscription, user, durable, temporary, autoCreated, scheduledExecutor, postOffice, null, null, executor); } - public void setPostOffice(final PostOffice postOffice) - { + public void setPostOffice(final PostOffice postOffice) { this.postOffice = postOffice; } - public void stop() throws Exception - { + public void stop() throws Exception { scheduledExecutor.shutdown(); executor.shutdown(); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/ActiveMQDestinationTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/ActiveMQDestinationTest.java index 00a3c910b2..5bc48a919c 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/ActiveMQDestinationTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/ActiveMQDestinationTest.java @@ -28,8 +28,7 @@ import org.junit.Assert; import org.apache.activemq.artemis.jms.client.ActiveMQDestination; import org.apache.activemq.artemis.tests.util.RandomUtil; -public class ActiveMQDestinationTest extends ActiveMQTestBase -{ +public class ActiveMQDestinationTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -41,8 +40,7 @@ public class ActiveMQDestinationTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testEquals() throws Exception - { + public void testEquals() throws Exception { String destinationName = RandomUtil.randomString(); String address = ActiveMQDestination.JMS_QUEUE_ADDRESS_PREFIX + destinationName; ActiveMQDestination destination = (ActiveMQDestination) ActiveMQDestination.fromAddress(address); @@ -56,38 +54,33 @@ public class ActiveMQDestinationTest extends ActiveMQTestBase } @Test - public void testFromAddressWithQueueAddressPrefix() throws Exception - { + public void testFromAddressWithQueueAddressPrefix() throws Exception { String destinationName = RandomUtil.randomString(); String address = ActiveMQDestination.JMS_QUEUE_ADDRESS_PREFIX + destinationName; ActiveMQDestination destination = (ActiveMQDestination) ActiveMQDestination.fromAddress(address); Assert.assertTrue(destination instanceof Queue); - Assert.assertEquals(destinationName, ((Queue)destination).getQueueName()); + Assert.assertEquals(destinationName, ((Queue) destination).getQueueName()); } @Test - public void testFromAddressWithTopicAddressPrefix() throws Exception - { + public void testFromAddressWithTopicAddressPrefix() throws Exception { String destinationName = RandomUtil.randomString(); String address = ActiveMQDestination.JMS_TOPIC_ADDRESS_PREFIX + destinationName; ActiveMQDestination destination = (ActiveMQDestination) ActiveMQDestination.fromAddress(address); Assert.assertTrue(destination instanceof Topic); - Assert.assertEquals(destinationName, ((Topic)destination).getTopicName()); + Assert.assertEquals(destinationName, ((Topic) destination).getTopicName()); } @Test - public void testFromAddressWithInvalidPrefix() throws Exception - { + public void testFromAddressWithInvalidPrefix() throws Exception { String invalidPrefix = "junk"; String destinationName = RandomUtil.randomString(); String address = invalidPrefix + destinationName; - try - { + try { ActiveMQDestination.fromAddress(address); Assert.fail("IllegalArgumentException"); } - catch (JMSRuntimeException e) - { + catch (JMSRuntimeException e) { } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/ActiveMQMapMessageTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/ActiveMQMapMessageTest.java index 248eaeb1b9..962449cebc 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/ActiveMQMapMessageTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/ActiveMQMapMessageTest.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.unit.jms.client; + import javax.jms.MessageFormatException; import org.apache.activemq.artemis.tests.util.RandomUtil; @@ -24,8 +25,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class ActiveMQMapMessageTest extends ActiveMQTestBase -{ +public class ActiveMQMapMessageTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -34,8 +34,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); itemName = RandomUtil.randomString(); @@ -48,8 +47,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testClearBody() throws Exception - { + public void testClearBody() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setBoolean(itemName, true); @@ -61,45 +59,37 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetType() throws Exception - { + public void testGetType() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); Assert.assertEquals(ActiveMQMapMessage.TYPE, message.getType()); } @Test - public void testCheckItemNameIsNull() throws Exception - { + public void testCheckItemNameIsNull() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); - try - { + try { message.setBoolean(null, true); Assert.fail("item name can not be null"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { } } @Test - public void testCheckItemNameIsEmpty() throws Exception - { + public void testCheckItemNameIsEmpty() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); - try - { + try { message.setBoolean("", true); Assert.fail("item name can not be empty"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { } } @Test - public void testGetBooleanFromBoolean() throws Exception - { + public void testGetBooleanFromBoolean() throws Exception { boolean value = true; ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -109,15 +99,13 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetBooleanFromNull() throws Exception - { + public void testGetBooleanFromNull() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); Assert.assertEquals(false, message.getBoolean(itemName)); } @Test - public void testGetBooleanFromString() throws Exception - { + public void testGetBooleanFromString() throws Exception { boolean value = true; ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -127,24 +115,20 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetBooleanFromInvalidType() throws Exception - { + public void testGetBooleanFromInvalidType() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setFloat(itemName, RandomUtil.randomFloat()); - try - { + try { message.getBoolean(itemName); Assert.fail("MessageFormatException"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } } @Test - public void testGetByteFromByte() throws Exception - { + public void testGetByteFromByte() throws Exception { byte value = RandomUtil.randomByte(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -154,23 +138,19 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetByteFromNull() throws Exception - { + public void testGetByteFromNull() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); - try - { + try { message.getByte(itemName); Assert.fail("NumberFormatException"); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } } @Test - public void testGetByteFromString() throws Exception - { + public void testGetByteFromString() throws Exception { byte value = RandomUtil.randomByte(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -180,24 +160,20 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetByteFromInvalidType() throws Exception - { + public void testGetByteFromInvalidType() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setFloat(itemName, RandomUtil.randomFloat()); - try - { + try { message.getByte(itemName); Assert.fail("MessageFormatException"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } } @Test - public void testGetShortFromByte() throws Exception - { + public void testGetShortFromByte() throws Exception { byte value = RandomUtil.randomByte(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -207,8 +183,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetShortFromShort() throws Exception - { + public void testGetShortFromShort() throws Exception { short value = RandomUtil.randomShort(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -218,23 +193,19 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetShortFromNull() throws Exception - { + public void testGetShortFromNull() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); - try - { + try { message.getShort(itemName); Assert.fail("NumberFormatException"); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } } @Test - public void testGetShortFromString() throws Exception - { + public void testGetShortFromString() throws Exception { short value = RandomUtil.randomShort(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -244,24 +215,20 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetShortFromInvalidType() throws Exception - { + public void testGetShortFromInvalidType() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setFloat(itemName, RandomUtil.randomFloat()); - try - { + try { message.getShort(itemName); Assert.fail("MessageFormatException"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } } @Test - public void testGetIntFromByte() throws Exception - { + public void testGetIntFromByte() throws Exception { byte value = RandomUtil.randomByte(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -271,8 +238,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetIntFromShort() throws Exception - { + public void testGetIntFromShort() throws Exception { short value = RandomUtil.randomShort(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -282,8 +248,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetIntFromInt() throws Exception - { + public void testGetIntFromInt() throws Exception { int value = RandomUtil.randomInt(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -293,23 +258,19 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetIntFromNull() throws Exception - { + public void testGetIntFromNull() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); - try - { + try { message.getInt(itemName); Assert.fail("NumberFormatException"); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } } @Test - public void testGetIntFromString() throws Exception - { + public void testGetIntFromString() throws Exception { int value = RandomUtil.randomInt(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -319,24 +280,20 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetIntFromInvalidType() throws Exception - { + public void testGetIntFromInvalidType() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setFloat(itemName, RandomUtil.randomFloat()); - try - { + try { message.getInt(itemName); Assert.fail("MessageFormatException"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } } @Test - public void testGetCharFromChar() throws Exception - { + public void testGetCharFromChar() throws Exception { char value = RandomUtil.randomChar(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -346,39 +303,32 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetCharFromNull() throws Exception - { + public void testGetCharFromNull() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); - try - { + try { message.getChar(itemName); Assert.fail("NullPointerException"); } - catch (NullPointerException e) - { + catch (NullPointerException e) { } } @Test - public void testGetCharFromInvalidType() throws Exception - { + public void testGetCharFromInvalidType() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setFloat(itemName, RandomUtil.randomFloat()); - try - { + try { message.getChar(itemName); Assert.fail("MessageFormatException"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } } @Test - public void testGetLongFromByte() throws Exception - { + public void testGetLongFromByte() throws Exception { byte value = RandomUtil.randomByte(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -388,8 +338,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetLongFromShort() throws Exception - { + public void testGetLongFromShort() throws Exception { short value = RandomUtil.randomShort(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -399,8 +348,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetLongFromInt() throws Exception - { + public void testGetLongFromInt() throws Exception { int value = RandomUtil.randomInt(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -410,8 +358,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetLongFromLong() throws Exception - { + public void testGetLongFromLong() throws Exception { long value = RandomUtil.randomLong(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -421,23 +368,19 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetLongFromNull() throws Exception - { + public void testGetLongFromNull() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); - try - { + try { message.getLong(itemName); Assert.fail("NumberFormatException"); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } } @Test - public void testGetLongFromString() throws Exception - { + public void testGetLongFromString() throws Exception { long value = RandomUtil.randomLong(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -447,24 +390,20 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetLongFromInvalidType() throws Exception - { + public void testGetLongFromInvalidType() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setFloat(itemName, RandomUtil.randomFloat()); - try - { + try { message.getLong(itemName); Assert.fail("MessageFormatException"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } } @Test - public void testGetFloatFromFloat() throws Exception - { + public void testGetFloatFromFloat() throws Exception { float value = RandomUtil.randomFloat(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -474,23 +413,19 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetFloatFromNull() throws Exception - { + public void testGetFloatFromNull() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); - try - { + try { message.getFloat(itemName); Assert.fail("NullPointerException"); } - catch (NullPointerException e) - { + catch (NullPointerException e) { } } @Test - public void testGetFloatFromString() throws Exception - { + public void testGetFloatFromString() throws Exception { float value = RandomUtil.randomFloat(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -500,24 +435,20 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetFloatFromInvalidType() throws Exception - { + public void testGetFloatFromInvalidType() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setChar(itemName, RandomUtil.randomChar()); - try - { + try { message.getFloat(itemName); Assert.fail("MessageFormatException"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } } @Test - public void testGetDoubleFromFloat() throws Exception - { + public void testGetDoubleFromFloat() throws Exception { float value = RandomUtil.randomFloat(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -527,8 +458,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetDoubleFromDouble() throws Exception - { + public void testGetDoubleFromDouble() throws Exception { double value = RandomUtil.randomDouble(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -538,23 +468,19 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetDoubleFromNull() throws Exception - { + public void testGetDoubleFromNull() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); - try - { + try { message.getDouble(itemName); Assert.fail("NullPointerException"); } - catch (NullPointerException e) - { + catch (NullPointerException e) { } } @Test - public void testGetDoubleFromString() throws Exception - { + public void testGetDoubleFromString() throws Exception { double value = RandomUtil.randomDouble(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -564,24 +490,20 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetDoubleFromInvalidType() throws Exception - { + public void testGetDoubleFromInvalidType() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setChar(itemName, RandomUtil.randomChar()); - try - { + try { message.getDouble(itemName); Assert.fail("MessageFormatException"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } } @Test - public void testGetStringFromBoolean() throws Exception - { + public void testGetStringFromBoolean() throws Exception { boolean value = RandomUtil.randomBoolean(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -591,8 +513,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetStringFromByte() throws Exception - { + public void testGetStringFromByte() throws Exception { byte value = RandomUtil.randomByte(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -602,8 +523,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetStringFromChar() throws Exception - { + public void testGetStringFromChar() throws Exception { char value = RandomUtil.randomChar(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -613,8 +533,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetStringFromShort() throws Exception - { + public void testGetStringFromShort() throws Exception { short value = RandomUtil.randomShort(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -624,8 +543,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetStringFromInt() throws Exception - { + public void testGetStringFromInt() throws Exception { int value = RandomUtil.randomInt(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -635,8 +553,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetStringFromLong() throws Exception - { + public void testGetStringFromLong() throws Exception { long value = RandomUtil.randomLong(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -646,8 +563,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetStringFromFloat() throws Exception - { + public void testGetStringFromFloat() throws Exception { float value = RandomUtil.randomFloat(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -657,8 +573,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetStringFromDouble() throws Exception - { + public void testGetStringFromDouble() throws Exception { double value = RandomUtil.randomByte(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -668,16 +583,14 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetStringFromNull() throws Exception - { + public void testGetStringFromNull() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); Assert.assertNull(message.getString(itemName)); } @Test - public void testGetStringFromString() throws Exception - { + public void testGetStringFromString() throws Exception { String value = RandomUtil.randomString(); ActiveMQMapMessage message = new ActiveMQMapMessage(); @@ -687,8 +600,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetBytesFromBytes() throws Exception - { + public void testGetBytesFromBytes() throws Exception { byte[] value = RandomUtil.randomBytes(); ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setBytes(itemName, value); @@ -697,32 +609,27 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testGetBytesFromNull() throws Exception - { + public void testGetBytesFromNull() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); Assert.assertNull(message.getBytes(itemName)); } @Test - public void testGetBytesFromInvalidType() throws Exception - { + public void testGetBytesFromInvalidType() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setChar(itemName, RandomUtil.randomChar()); - try - { + try { message.getBytes(itemName); Assert.fail("MessageFormatException"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } } @Test - public void testSetObjectFromBoolean() throws Exception - { + public void testSetObjectFromBoolean() throws Exception { boolean value = RandomUtil.randomBoolean(); ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setObject(itemName, value); @@ -731,61 +638,51 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase } @Test - public void testSetObjectFromByte() throws Exception - { + public void testSetObjectFromByte() throws Exception { doTestSetObject(RandomUtil.randomByte()); } @Test - public void testSetObjectFromShort() throws Exception - { + public void testSetObjectFromShort() throws Exception { doTestSetObject(RandomUtil.randomShort()); } @Test - public void testSetObjectFromChar() throws Exception - { + public void testSetObjectFromChar() throws Exception { doTestSetObject(RandomUtil.randomChar()); } @Test - public void testSetObjectFromInt() throws Exception - { + public void testSetObjectFromInt() throws Exception { doTestSetObject(RandomUtil.randomInt()); } @Test - public void testSetObjectFromLong() throws Exception - { + public void testSetObjectFromLong() throws Exception { doTestSetObject(RandomUtil.randomLong()); } @Test - public void testSetObjectFromFloat() throws Exception - { + public void testSetObjectFromFloat() throws Exception { doTestSetObject(RandomUtil.randomFloat()); } @Test - public void testSetObjectFromDouble() throws Exception - { + public void testSetObjectFromDouble() throws Exception { doTestSetObject(RandomUtil.randomDouble()); } @Test - public void testSetObjectFromString() throws Exception - { + public void testSetObjectFromString() throws Exception { doTestSetObject(RandomUtil.randomString()); } @Test - public void testSetObjectFromBytes() throws Exception - { + public void testSetObjectFromBytes() throws Exception { doTestSetObject(RandomUtil.randomBytes()); } - private void doTestSetObject(final Object value) throws Exception - { + private void doTestSetObject(final Object value) throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setObject(itemName, value); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/ActiveMQStreamMessageTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/ActiveMQStreamMessageTest.java index 7d66e14fa4..b319dfbc64 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/ActiveMQStreamMessageTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/ActiveMQStreamMessageTest.java @@ -29,8 +29,7 @@ import org.junit.Assert; import org.apache.activemq.artemis.jms.client.ActiveMQStreamMessage; import org.apache.activemq.artemis.tests.util.RandomUtil; -public class ActiveMQStreamMessageTest extends ActiveMQTestBase -{ +public class ActiveMQStreamMessageTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -42,15 +41,13 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testGetType() throws Exception - { + public void testGetType() throws Exception { ActiveMQStreamMessage message = new ActiveMQStreamMessage(); Assert.assertEquals(ActiveMQStreamMessage.TYPE, message.getType()); } @Test - public void testReadBooleanFromBoolean() throws Exception - { + public void testReadBooleanFromBoolean() throws Exception { boolean value = RandomUtil.randomBoolean(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -61,8 +58,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadBooleanFromString() throws Exception - { + public void testReadBooleanFromString() throws Exception { boolean value = RandomUtil.randomBoolean(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -73,56 +69,43 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadBooleanFromInvalidType() throws Exception - { - doReadTypeFromInvalidType(RandomUtil.randomFloat(), new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testReadBooleanFromInvalidType() throws Exception { + doReadTypeFromInvalidType(RandomUtil.randomFloat(), new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readBoolean(); } }); } @Test - public void testReadBooleanFromEmptyMessage() throws Exception - { - doReadTypeFromEmptyMessage(new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testReadBooleanFromEmptyMessage() throws Exception { + doReadTypeFromEmptyMessage(new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readBoolean(); } }); } @Test - public void testReadCharFromInvalidType() throws Exception - { - doReadTypeFromInvalidType(RandomUtil.randomFloat(), new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testReadCharFromInvalidType() throws Exception { + doReadTypeFromInvalidType(RandomUtil.randomFloat(), new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readChar(); } }); } @Test - public void testReadCharFromEmptyMessage() throws Exception - { - doReadTypeFromEmptyMessage(new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testReadCharFromEmptyMessage() throws Exception { + doReadTypeFromEmptyMessage(new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readChar(); } }); } @Test - public void testReadByteFromByte() throws Exception - { + public void testReadByteFromByte() throws Exception { byte value = RandomUtil.randomByte(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -133,8 +116,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadByteFromString() throws Exception - { + public void testReadByteFromString() throws Exception { byte value = RandomUtil.randomByte(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -145,32 +127,25 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadByteFromInvalidType() throws Exception - { - doReadTypeFromInvalidType(RandomUtil.randomFloat(), new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testReadByteFromInvalidType() throws Exception { + doReadTypeFromInvalidType(RandomUtil.randomFloat(), new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readByte(); } }); } @Test - public void testReadByteFromEmptyMessage() throws Exception - { - doReadTypeFromEmptyMessage(new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testReadByteFromEmptyMessage() throws Exception { + doReadTypeFromEmptyMessage(new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readByte(); } }); } @Test - public void testReadBytesFromBytes() throws Exception - { + public void testReadBytesFromBytes() throws Exception { byte[] value = RandomUtil.randomBytes(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -184,8 +159,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadBytesFromBytes_2() throws Exception - { + public void testReadBytesFromBytes_2() throws Exception { byte[] value = RandomUtil.randomBytes(512); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -199,24 +173,18 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadBytesFromInvalidType() throws Exception - { - doReadTypeFromInvalidType(RandomUtil.randomBoolean(), new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testReadBytesFromInvalidType() throws Exception { + doReadTypeFromInvalidType(RandomUtil.randomBoolean(), new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readByte(); } }); } @Test - public void testReadBytesFromEmptyMessage() throws Exception - { - doReadTypeFromEmptyMessage(new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testReadBytesFromEmptyMessage() throws Exception { + doReadTypeFromEmptyMessage(new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { byte[] bytes = new byte[1]; return message.readBytes(bytes); } @@ -224,8 +192,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadShortFromByte() throws Exception - { + public void testReadShortFromByte() throws Exception { byte value = RandomUtil.randomByte(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -236,8 +203,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadShortFromShort() throws Exception - { + public void testReadShortFromShort() throws Exception { short value = RandomUtil.randomShort(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -248,8 +214,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadShortFromString() throws Exception - { + public void testReadShortFromString() throws Exception { short value = RandomUtil.randomShort(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -260,32 +225,25 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadShortFromInvalidType() throws Exception - { - doReadTypeFromInvalidType(RandomUtil.randomFloat(), new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testReadShortFromInvalidType() throws Exception { + doReadTypeFromInvalidType(RandomUtil.randomFloat(), new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readShort(); } }); } @Test - public void testReadShortFromEmptyMessage() throws Exception - { - doReadTypeFromEmptyMessage(new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testReadShortFromEmptyMessage() throws Exception { + doReadTypeFromEmptyMessage(new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readShort(); } }); } @Test - public void testReadIntFromByte() throws Exception - { + public void testReadIntFromByte() throws Exception { byte value = RandomUtil.randomByte(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -296,8 +254,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadIntFromShort() throws Exception - { + public void testReadIntFromShort() throws Exception { short value = RandomUtil.randomShort(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -308,8 +265,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadIntFromInt() throws Exception - { + public void testReadIntFromInt() throws Exception { int value = RandomUtil.randomInt(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -320,8 +276,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadIntFromString() throws Exception - { + public void testReadIntFromString() throws Exception { int value = RandomUtil.randomInt(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -332,32 +287,25 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadIntFromInvalidType() throws Exception - { - doReadTypeFromInvalidType(RandomUtil.randomFloat(), new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testReadIntFromInvalidType() throws Exception { + doReadTypeFromInvalidType(RandomUtil.randomFloat(), new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readInt(); } }); } @Test - public void testReadIntFromEmptyMessage() throws Exception - { - doReadTypeFromEmptyMessage(new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testReadIntFromEmptyMessage() throws Exception { + doReadTypeFromEmptyMessage(new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readInt(); } }); } @Test - public void testReadCharFromChar() throws Exception - { + public void testReadCharFromChar() throws Exception { char value = RandomUtil.randomChar(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -368,26 +316,22 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadCharFromNull() throws Exception - { + public void testReadCharFromNull() throws Exception { ActiveMQStreamMessage message = new ActiveMQStreamMessage(); message.writeString(null); message.reset(); - try - { + try { message.readChar(); fail(); } - catch (NullPointerException e) - { + catch (NullPointerException e) { } } @Test - public void testReadLongFromByte() throws Exception - { + public void testReadLongFromByte() throws Exception { byte value = RandomUtil.randomByte(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -398,8 +342,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadLongFromShort() throws Exception - { + public void testReadLongFromShort() throws Exception { short value = RandomUtil.randomShort(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -410,8 +353,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadLongFromInt() throws Exception - { + public void testReadLongFromInt() throws Exception { int value = RandomUtil.randomInt(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -422,8 +364,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadLongFromLong() throws Exception - { + public void testReadLongFromLong() throws Exception { long value = RandomUtil.randomLong(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -434,8 +375,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadLongFromString() throws Exception - { + public void testReadLongFromString() throws Exception { long value = RandomUtil.randomLong(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -446,32 +386,25 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadLongFromInvalidType() throws Exception - { - doReadTypeFromInvalidType(RandomUtil.randomFloat(), new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testReadLongFromInvalidType() throws Exception { + doReadTypeFromInvalidType(RandomUtil.randomFloat(), new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readLong(); } }); } @Test - public void testReadLongFromEmptyMessage() throws Exception - { - doReadTypeFromEmptyMessage(new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testReadLongFromEmptyMessage() throws Exception { + doReadTypeFromEmptyMessage(new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readLong(); } }); } @Test - public void testReadFloatFromFloat() throws Exception - { + public void testReadFloatFromFloat() throws Exception { float value = RandomUtil.randomFloat(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -482,8 +415,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadFloatFromString() throws Exception - { + public void testReadFloatFromString() throws Exception { float value = RandomUtil.randomFloat(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -494,32 +426,25 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadFloatFromInvalidType() throws Exception - { - doReadTypeFromInvalidType(RandomUtil.randomBoolean(), new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testReadFloatFromInvalidType() throws Exception { + doReadTypeFromInvalidType(RandomUtil.randomBoolean(), new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readFloat(); } }); } @Test - public void testReadFloatFromEmptyMessage() throws Exception - { - doReadTypeFromEmptyMessage(new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testReadFloatFromEmptyMessage() throws Exception { + doReadTypeFromEmptyMessage(new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readFloat(); } }); } @Test - public void testReadDoubleFromFloat() throws Exception - { + public void testReadDoubleFromFloat() throws Exception { float value = RandomUtil.randomFloat(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -530,8 +455,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadDoubleFromDouble() throws Exception - { + public void testReadDoubleFromDouble() throws Exception { double value = RandomUtil.randomDouble(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -542,8 +466,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadDoubleFromString() throws Exception - { + public void testReadDoubleFromString() throws Exception { double value = RandomUtil.randomDouble(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -554,32 +477,25 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadDoubleFromInvalidType() throws Exception - { - doReadTypeFromInvalidType(RandomUtil.randomBoolean(), new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testReadDoubleFromInvalidType() throws Exception { + doReadTypeFromInvalidType(RandomUtil.randomBoolean(), new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readDouble(); } }); } @Test - public void testReadDoubleFromEmptyMessage() throws Exception - { - doReadTypeFromEmptyMessage(new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testReadDoubleFromEmptyMessage() throws Exception { + doReadTypeFromEmptyMessage(new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readDouble(); } }); } @Test - public void testReadStringFromBoolean() throws Exception - { + public void testReadStringFromBoolean() throws Exception { boolean value = RandomUtil.randomBoolean(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -590,8 +506,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadStringFromChar() throws Exception - { + public void testReadStringFromChar() throws Exception { char value = RandomUtil.randomChar(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -602,8 +517,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadStringFromByte() throws Exception - { + public void testReadStringFromByte() throws Exception { byte value = RandomUtil.randomByte(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -614,21 +528,18 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testString() throws Exception - { + public void testString() throws Exception { String value = RandomUtil.randomString(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); message.writeString(value); message.reset(); - try - { + try { message.readByte(); fail("must throw a NumberFormatException"); } - catch (NumberFormatException e) - { + catch (NumberFormatException e) { } // we can read the String without resetting the message @@ -636,8 +547,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadStringFromShort() throws Exception - { + public void testReadStringFromShort() throws Exception { short value = RandomUtil.randomShort(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -648,8 +558,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadStringFromInt() throws Exception - { + public void testReadStringFromInt() throws Exception { int value = RandomUtil.randomInt(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -660,8 +569,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadStringFromLong() throws Exception - { + public void testReadStringFromLong() throws Exception { long value = RandomUtil.randomLong(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -672,8 +580,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadStringFromFloat() throws Exception - { + public void testReadStringFromFloat() throws Exception { float value = RandomUtil.randomFloat(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -684,8 +591,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadStringFromDouble() throws Exception - { + public void testReadStringFromDouble() throws Exception { double value = RandomUtil.randomDouble(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -696,8 +602,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadStringFromString() throws Exception - { + public void testReadStringFromString() throws Exception { String value = RandomUtil.randomString(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); @@ -708,8 +613,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadStringFromNullString() throws Exception - { + public void testReadStringFromNullString() throws Exception { ActiveMQStreamMessage message = new ActiveMQStreamMessage(); message.writeString(null); @@ -719,61 +623,46 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadStringFromEmptyMessage() throws Exception - { - doReadTypeFromEmptyMessage(new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testReadStringFromEmptyMessage() throws Exception { + doReadTypeFromEmptyMessage(new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readString(); } }); } @Test - public void testWriteObjectWithBoolean() throws Exception - { - doWriteObjectWithType(RandomUtil.randomBoolean(), new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testWriteObjectWithBoolean() throws Exception { + doWriteObjectWithType(RandomUtil.randomBoolean(), new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readBoolean(); } }); } @Test - public void testWriteObjectWithChar() throws Exception - { - doWriteObjectWithType(RandomUtil.randomChar(), new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testWriteObjectWithChar() throws Exception { + doWriteObjectWithType(RandomUtil.randomChar(), new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readChar(); } }); } @Test - public void testWriteObjectWithByte() throws Exception - { - doWriteObjectWithType(RandomUtil.randomByte(), new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testWriteObjectWithByte() throws Exception { + doWriteObjectWithType(RandomUtil.randomByte(), new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readByte(); } }); } @Test - public void testWriteObjectWithBytes() throws Exception - { + public void testWriteObjectWithBytes() throws Exception { final byte[] value = RandomUtil.randomBytes(); - doWriteObjectWithType(value, new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + doWriteObjectWithType(value, new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { byte[] bytes = new byte[value.length]; message.readBytes(bytes); return bytes; @@ -782,103 +671,80 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testWriteObjectWithShort() throws Exception - { - doWriteObjectWithType(RandomUtil.randomShort(), new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testWriteObjectWithShort() throws Exception { + doWriteObjectWithType(RandomUtil.randomShort(), new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readShort(); } }); } @Test - public void testWriteObjectWithInt() throws Exception - { - doWriteObjectWithType(RandomUtil.randomInt(), new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testWriteObjectWithInt() throws Exception { + doWriteObjectWithType(RandomUtil.randomInt(), new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readInt(); } }); } @Test - public void testWriteObjectWithLong() throws Exception - { - doWriteObjectWithType(RandomUtil.randomLong(), new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testWriteObjectWithLong() throws Exception { + doWriteObjectWithType(RandomUtil.randomLong(), new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readLong(); } }); } @Test - public void testWriteObjectWithFloat() throws Exception - { - doWriteObjectWithType(RandomUtil.randomFloat(), new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testWriteObjectWithFloat() throws Exception { + doWriteObjectWithType(RandomUtil.randomFloat(), new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readFloat(); } }); } @Test - public void testWriteObjectWithDouble() throws Exception - { - doWriteObjectWithType(RandomUtil.randomDouble(), new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testWriteObjectWithDouble() throws Exception { + doWriteObjectWithType(RandomUtil.randomDouble(), new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readDouble(); } }); } @Test - public void testWriteObjectWithString() throws Exception - { - doWriteObjectWithType(RandomUtil.randomString(), new TypeReader() - { - public Object readType(final ActiveMQStreamMessage message) throws Exception - { + public void testWriteObjectWithString() throws Exception { + doWriteObjectWithType(RandomUtil.randomString(), new TypeReader() { + public Object readType(final ActiveMQStreamMessage message) throws Exception { return message.readString(); } }); } @Test - public void testWriteObjectWithNull() throws Exception - { + public void testWriteObjectWithNull() throws Exception { ActiveMQStreamMessage message = new ActiveMQStreamMessage(); message.writeObject(null); } @Test - public void testWriteObjectWithInvalidType() throws Exception - { + public void testWriteObjectWithInvalidType() throws Exception { ActiveMQStreamMessage message = new ActiveMQStreamMessage(); - try - { + try { message.writeObject(new ArrayList()); Assert.fail("MessageFormatException"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } } @Test - public void testReadObjectFromBoolean() throws Exception - { + public void testReadObjectFromBoolean() throws Exception { boolean value = RandomUtil.randomBoolean(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); message.writeBoolean(value); @@ -889,8 +755,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadObjectFromChar() throws Exception - { + public void testReadObjectFromChar() throws Exception { char value = RandomUtil.randomChar(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); message.writeChar(value); @@ -901,8 +766,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadObjectFromByte() throws Exception - { + public void testReadObjectFromByte() throws Exception { byte value = RandomUtil.randomByte(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); message.writeByte(value); @@ -913,21 +777,19 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadObjectFromBytes() throws Exception - { + public void testReadObjectFromBytes() throws Exception { byte[] value = RandomUtil.randomBytes(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); message.writeBytes(value); message.reset(); - byte[] v = (byte[])message.readObject(); + byte[] v = (byte[]) message.readObject(); ActiveMQTestBase.assertEqualsByteArrays(value, v); } @Test - public void testReadObjectFromShort() throws Exception - { + public void testReadObjectFromShort() throws Exception { short value = RandomUtil.randomShort(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); message.writeShort(value); @@ -938,8 +800,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadObjectFromInt() throws Exception - { + public void testReadObjectFromInt() throws Exception { int value = RandomUtil.randomInt(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); message.writeInt(value); @@ -950,8 +811,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadObjectFromLong() throws Exception - { + public void testReadObjectFromLong() throws Exception { long value = RandomUtil.randomLong(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); message.writeLong(value); @@ -962,8 +822,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadObjectFromFloat() throws Exception - { + public void testReadObjectFromFloat() throws Exception { float value = RandomUtil.randomFloat(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); message.writeFloat(value); @@ -974,8 +833,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadObjectFromDouble() throws Exception - { + public void testReadObjectFromDouble() throws Exception { double value = RandomUtil.randomDouble(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); message.writeDouble(value); @@ -986,8 +844,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase } @Test - public void testReadObjectFromString() throws Exception - { + public void testReadObjectFromString() throws Exception { String value = RandomUtil.randomString(); ActiveMQStreamMessage message = new ActiveMQStreamMessage(); message.writeString(value); @@ -999,60 +856,51 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase // Private ------------------------------------------------------- - private void doReadTypeFromEmptyMessage(final TypeReader reader) throws Exception - { + private void doReadTypeFromEmptyMessage(final TypeReader reader) throws Exception { ActiveMQStreamMessage message = new ActiveMQStreamMessage(); message.reset(); - try - { + try { reader.readType(message); Assert.fail("MessageEOFException"); } - catch (MessageEOFException e) - { + catch (MessageEOFException e) { } } - private void doReadTypeFromInvalidType(final Object invalidValue, final TypeReader reader) throws Exception - { + private void doReadTypeFromInvalidType(final Object invalidValue, final TypeReader reader) throws Exception { ActiveMQStreamMessage message = new ActiveMQStreamMessage(); message.writeObject(invalidValue); message.reset(); - try - { + try { reader.readType(message); Assert.fail("MessageFormatException"); } - catch (MessageFormatException e) - { + catch (MessageFormatException e) { } } - private void doWriteObjectWithType(final Object value, final TypeReader reader) throws Exception - { + private void doWriteObjectWithType(final Object value, final TypeReader reader) throws Exception { ActiveMQStreamMessage message = new ActiveMQStreamMessage(); message.writeObject(value); message.reset(); Object v = reader.readType(message); - if (value instanceof byte[]) - { + if (value instanceof byte[]) { ActiveMQTestBase.assertEqualsByteArrays((byte[]) value, (byte[]) v); } - else - { + else { Assert.assertEquals(value, v); } } // Inner classes ------------------------------------------------- - private interface TypeReader - { + private interface TypeReader { + Object readType(ActiveMQStreamMessage message) throws Exception; } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/JMSExceptionHelperTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/JMSExceptionHelperTest.java index de1d00f104..bc83e963ea 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/JMSExceptionHelperTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/JMSExceptionHelperTest.java @@ -33,8 +33,7 @@ import org.apache.activemq.artemis.jms.client.JMSExceptionHelper; import org.junit.Assert; import org.junit.Test; -public class JMSExceptionHelperTest extends ActiveMQTestBase -{ +public class JMSExceptionHelperTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -46,74 +45,62 @@ public class JMSExceptionHelperTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testCONNECTION_TIMEDOUT() throws Exception - { + public void testCONNECTION_TIMEDOUT() throws Exception { doConvertException(CONNECTION_TIMEDOUT, JMSException.class); } @Test - public void testILLEGAL_STATE() throws Exception - { + public void testILLEGAL_STATE() throws Exception { doConvertException(ActiveMQExceptionType.ILLEGAL_STATE, IllegalStateException.class); } @Test - public void testINTERNAL_ERROR() throws Exception - { + public void testINTERNAL_ERROR() throws Exception { doConvertException(ActiveMQExceptionType.INTERNAL_ERROR, JMSException.class); } @Test - public void testINVALID_FILTER_EXPRESSION() throws Exception - { + public void testINVALID_FILTER_EXPRESSION() throws Exception { doConvertException(INVALID_FILTER_EXPRESSION, InvalidSelectorException.class); } @Test - public void testNOT_CONNECTED() throws Exception - { + public void testNOT_CONNECTED() throws Exception { doConvertException(ActiveMQExceptionType.NOT_CONNECTED, JMSException.class); } @Test - public void testOBJECT_CLOSED() throws Exception - { + public void testOBJECT_CLOSED() throws Exception { doConvertException(ActiveMQExceptionType.OBJECT_CLOSED, IllegalStateException.class); } @Test - public void testQUEUE_DOES_NOT_EXIST() throws Exception - { + public void testQUEUE_DOES_NOT_EXIST() throws Exception { doConvertException(ActiveMQExceptionType.QUEUE_DOES_NOT_EXIST, InvalidDestinationException.class); } @Test - public void testQUEUE_EXISTS() throws Exception - { + public void testQUEUE_EXISTS() throws Exception { doConvertException(ActiveMQExceptionType.QUEUE_EXISTS, InvalidDestinationException.class); } @Test - public void testSECURITY_EXCEPTION() throws Exception - { + public void testSECURITY_EXCEPTION() throws Exception { doConvertException(ActiveMQExceptionType.SECURITY_EXCEPTION, JMSSecurityException.class); } @Test - public void testUNSUPPORTED_PACKET() throws Exception - { + public void testUNSUPPORTED_PACKET() throws Exception { doConvertException(ActiveMQExceptionType.UNSUPPORTED_PACKET, IllegalStateException.class); } @Test - public void testDefault() throws Exception - { + public void testDefault() throws Exception { doConvertException(GENERIC_EXCEPTION, JMSException.class); } private void doConvertException(final ActiveMQExceptionType errorCode, - final Class expectedException) - { + final Class expectedException) { ActiveMQException me = new ActiveMQException(errorCode); Exception e = JMSExceptionHelper.convertFromActiveMQException(me); Assert.assertNotNull(e); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/SelectorTranslatorTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/SelectorTranslatorTest.java index e73d13be05..f2f89c8317 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/SelectorTranslatorTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/SelectorTranslatorTest.java @@ -23,33 +23,29 @@ import org.junit.Assert; import org.apache.activemq.artemis.jms.client.SelectorTranslator; -public class SelectorTranslatorTest extends ActiveMQTestBase -{ +public class SelectorTranslatorTest extends ActiveMQTestBase { + @Test - public void testParseNull() - { + public void testParseNull() { Assert.assertNull(SelectorTranslator.convertToActiveMQFilterString(null)); } @Test - public void testParseSimple() - { + public void testParseSimple() { final String selector = "color = 'red'"; Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); } @Test - public void testParseMoreComplex() - { + public void testParseMoreComplex() { final String selector = "color = 'red' OR cheese = 'stilton' OR (age = 3 AND shoesize = 12)"; Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); } @Test - public void testParseJMSDeliveryMode() - { + public void testParseJMSDeliveryMode() { String selector = "JMSDeliveryMode='NON_PERSISTENT'"; Assert.assertEquals("AMQDurable='NON_DURABLE'", SelectorTranslator.convertToActiveMQFilterString(selector)); @@ -60,20 +56,17 @@ public class SelectorTranslatorTest extends ActiveMQTestBase selector = "color = 'red' AND 'NON_PERSISTENT' = JMSDeliveryMode"; - Assert.assertEquals("color = 'red' AND 'NON_DURABLE' = AMQDurable", - SelectorTranslator.convertToActiveMQFilterString(selector)); + Assert.assertEquals("color = 'red' AND 'NON_DURABLE' = AMQDurable", SelectorTranslator.convertToActiveMQFilterString(selector)); selector = "color = 'red' AND 'PERSISTENT' = JMSDeliveryMode"; - Assert.assertEquals("color = 'red' AND 'DURABLE' = AMQDurable", - SelectorTranslator.convertToActiveMQFilterString(selector)); + Assert.assertEquals("color = 'red' AND 'DURABLE' = AMQDurable", SelectorTranslator.convertToActiveMQFilterString(selector)); checkNoSubstitute("JMSDeliveryMode"); } @Test - public void testParseJMSPriority() - { + public void testParseJMSPriority() { String selector = "JMSPriority=5"; Assert.assertEquals("AMQPriority=5", SelectorTranslator.convertToActiveMQFilterString(selector)); @@ -84,21 +77,18 @@ public class SelectorTranslatorTest extends ActiveMQTestBase selector = " JMSPriority = 7 OR 1 = JMSPriority AND (JMSPriority= 1 + 4)"; - Assert.assertEquals(" AMQPriority = 7 OR 1 = AMQPriority AND (AMQPriority= 1 + 4)", - SelectorTranslator.convertToActiveMQFilterString(selector)); + Assert.assertEquals(" AMQPriority = 7 OR 1 = AMQPriority AND (AMQPriority= 1 + 4)", SelectorTranslator.convertToActiveMQFilterString(selector)); checkNoSubstitute("JMSPriority"); selector = "animal = 'lion' JMSPriority = 321 OR animal_name = 'xyzJMSPriorityxyz'"; - Assert.assertEquals("animal = 'lion' AMQPriority = 321 OR animal_name = 'xyzJMSPriorityxyz'", - SelectorTranslator.convertToActiveMQFilterString(selector)); + Assert.assertEquals("animal = 'lion' AMQPriority = 321 OR animal_name = 'xyzJMSPriorityxyz'", SelectorTranslator.convertToActiveMQFilterString(selector)); } @Test - public void testParseJMSMessageID() - { + public void testParseJMSMessageID() { String selector = "JMSMessageID='ID:AMQ-12435678"; Assert.assertEquals("AMQUserID='ID:AMQ-12435678", SelectorTranslator.convertToActiveMQFilterString(selector)); @@ -123,8 +113,7 @@ public class SelectorTranslatorTest extends ActiveMQTestBase } @Test - public void testParseJMSTimestamp() - { + public void testParseJMSTimestamp() { String selector = "JMSTimestamp=12345678"; Assert.assertEquals("AMQTimestamp=12345678", SelectorTranslator.convertToActiveMQFilterString(selector)); @@ -135,21 +124,18 @@ public class SelectorTranslatorTest extends ActiveMQTestBase selector = " JMSTimestamp=12345678 OR 78766 = JMSTimestamp AND (JMSTimestamp= 1 + 4878787)"; - Assert.assertEquals(" AMQTimestamp=12345678 OR 78766 = AMQTimestamp AND (AMQTimestamp= 1 + 4878787)", - SelectorTranslator.convertToActiveMQFilterString(selector)); + Assert.assertEquals(" AMQTimestamp=12345678 OR 78766 = AMQTimestamp AND (AMQTimestamp= 1 + 4878787)", SelectorTranslator.convertToActiveMQFilterString(selector)); checkNoSubstitute("JMSTimestamp"); selector = "animal = 'lion' JMSTimestamp = 321 OR animal_name = 'xyzJMSTimestampxyz'"; - Assert.assertEquals("animal = 'lion' AMQTimestamp = 321 OR animal_name = 'xyzJMSTimestampxyz'", - SelectorTranslator.convertToActiveMQFilterString(selector)); + Assert.assertEquals("animal = 'lion' AMQTimestamp = 321 OR animal_name = 'xyzJMSTimestampxyz'", SelectorTranslator.convertToActiveMQFilterString(selector)); } @Test - public void testParseJMSExpiration() - { + public void testParseJMSExpiration() { String selector = "JMSExpiration=12345678"; Assert.assertEquals("AMQExpiration=12345678", SelectorTranslator.convertToActiveMQFilterString(selector)); @@ -160,21 +146,18 @@ public class SelectorTranslatorTest extends ActiveMQTestBase selector = " JMSExpiration=12345678 OR 78766 = JMSExpiration AND (JMSExpiration= 1 + 4878787)"; - Assert.assertEquals(" AMQExpiration=12345678 OR 78766 = AMQExpiration AND (AMQExpiration= 1 + 4878787)", - SelectorTranslator.convertToActiveMQFilterString(selector)); + Assert.assertEquals(" AMQExpiration=12345678 OR 78766 = AMQExpiration AND (AMQExpiration= 1 + 4878787)", SelectorTranslator.convertToActiveMQFilterString(selector)); checkNoSubstitute("JMSExpiration"); selector = "animal = 'lion' JMSExpiration = 321 OR animal_name = 'xyzJMSExpirationxyz'"; - Assert.assertEquals("animal = 'lion' AMQExpiration = 321 OR animal_name = 'xyzJMSExpirationxyz'", - SelectorTranslator.convertToActiveMQFilterString(selector)); + Assert.assertEquals("animal = 'lion' AMQExpiration = 321 OR animal_name = 'xyzJMSExpirationxyz'", SelectorTranslator.convertToActiveMQFilterString(selector)); } @Test - public void testParseJMSCorrelationID() - { + public void testParseJMSCorrelationID() { String selector = "JMSCorrelationID='ID:AMQ-12435678"; Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); @@ -199,8 +182,7 @@ public class SelectorTranslatorTest extends ActiveMQTestBase } @Test - public void testParseJMSType() - { + public void testParseJMSType() { String selector = "JMSType='aardvark'"; Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); @@ -224,12 +206,9 @@ public class SelectorTranslatorTest extends ActiveMQTestBase checkNoSubstitute("JMSType"); } - - // Private ------------------------------------------------------------------------------------- - private void checkNoSubstitute(final String fieldName) - { + private void checkNoSubstitute(final String fieldName) { String selector = "Other" + fieldName + " = 767868"; Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/misc/ManifestTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/misc/ManifestTest.java index 16d0406272..c4d2b4bd89 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/misc/ManifestTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/misc/ManifestTest.java @@ -35,8 +35,7 @@ import org.apache.activemq.artemis.core.server.ActiveMQServers; import org.apache.activemq.artemis.jms.client.ActiveMQConnectionMetaData; import org.apache.activemq.artemis.tests.unit.UnitTestLogger; -public class ManifestTest extends ActiveMQTestBase -{ +public class ManifestTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- @@ -48,8 +47,7 @@ public class ManifestTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testManifestEntries() throws Exception - { + public void testManifestEntries() throws Exception { Properties props = System.getProperties(); String userDir = props.getProperty("build.lib"); @@ -66,8 +64,7 @@ public class ManifestTest extends ActiveMQTestBase // Open a connection and get ConnectionMetaData Connection conn = null; - try - { + try { ActiveMQServer server = ActiveMQServers.newActiveMQServer(createBasicConfig()); ConnectionMetaData meta = new ActiveMQConnectionMetaData(server.getVersion()); @@ -77,10 +74,8 @@ public class ManifestTest extends ActiveMQTestBase Assert.assertEquals(meta.getProviderVersion(), attrs.getValue("ActiveMQ-Version")); } - finally - { - if (conn != null) - { + finally { + if (conn != null) { conn.close(); } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/referenceable/ConnectionFactoryObjectFactoryTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/referenceable/ConnectionFactoryObjectFactoryTest.java index c173323871..5e464a6cba 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/referenceable/ConnectionFactoryObjectFactoryTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/referenceable/ConnectionFactoryObjectFactoryTest.java @@ -19,8 +19,7 @@ package org.apache.activemq.artemis.tests.unit.jms.referenceable; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Test; -public class ConnectionFactoryObjectFactoryTest extends ActiveMQTestBase -{ +public class ConnectionFactoryObjectFactoryTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -32,8 +31,7 @@ public class ConnectionFactoryObjectFactoryTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testDummy() - { + public void testDummy() { } // public void testReference() throws Exception diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/referenceable/DestinationObjectFactoryTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/referenceable/DestinationObjectFactoryTest.java index 6f06664cf4..a7e68e83c1 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/referenceable/DestinationObjectFactoryTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/referenceable/DestinationObjectFactoryTest.java @@ -28,8 +28,7 @@ import org.apache.activemq.artemis.jms.client.ActiveMQDestination; import org.apache.activemq.artemis.jms.referenceable.DestinationObjectFactory; import org.apache.activemq.artemis.tests.util.RandomUtil; -public class DestinationObjectFactoryTest extends ActiveMQTestBase -{ +public class DestinationObjectFactoryTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -41,8 +40,7 @@ public class DestinationObjectFactoryTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testReference() throws Exception - { + public void testReference() throws Exception { ActiveMQDestination queue = (ActiveMQDestination) ActiveMQJMSClient.createQueue(RandomUtil.randomString()); Reference reference = queue.getReference(); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ActiveMQResourceAdapterConfigTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ActiveMQResourceAdapterConfigTest.java index c12f044a94..808214c401 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ActiveMQResourceAdapterConfigTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ActiveMQResourceAdapterConfigTest.java @@ -33,14 +33,13 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; - /** * This test is used to generate the commented out configs in the src/config/ra.xml. If you add a setter to the ActiveMQResourceAdapter * this test should fail, if it does paste the new commented out configs into the ra.xml file and in here. don't forget to * add a description for each new property added and try and put it in the config some where appropriate. */ -public class ActiveMQResourceAdapterConfigTest extends ActiveMQTestBase -{ +public class ActiveMQResourceAdapterConfigTest extends ActiveMQTestBase { + private static String config = "" + "\n" + " \n" + @@ -387,18 +386,14 @@ public class ActiveMQResourceAdapterConfigTest extends ActiveMQTestBase " " + " "; - private static String rootConfig = "" + config + commentedOutConfigs + ""; @Test - public void testConfiguration() throws Exception - { + public void testConfiguration() throws Exception { Method[] methods = ActiveMQResourceAdapter.class.getMethods(); Map methodList = new HashMap(); - for (Method method : methods) - { - if (method.getName().startsWith("set")) - { + for (Method method : methods) { + if (method.getName().startsWith("set")) { methodList.put(method.getName(), method); } } @@ -411,8 +406,7 @@ public class ActiveMQResourceAdapterConfigTest extends ActiveMQTestBase NodeList nl = docEle.getElementsByTagName("config-property"); - for (int i = 0; i < nl.getLength(); i++) - { + for (int i = 0; i < nl.getLength(); i++) { Element el = (Element) nl.item(i); NodeList elementsByTagName = el.getElementsByTagName("config-property-name"); assertEquals(el.toString(), elementsByTagName.getLength(), 1); @@ -428,12 +422,10 @@ public class ActiveMQResourceAdapterConfigTest extends ActiveMQTestBase String configPropertyTypeName = configPropertyTypeNode.getTextContent(); assertEquals(configPropertyTypeName, c.getName()); } - if (!methodList.isEmpty()) - { + if (!methodList.isEmpty()) { StringBuffer newConfig = new StringBuffer(commentedOutConfigs); newConfig.append("\n"); - for (Method method : methodList.values()) - { + for (Method method : methodList.values()) { newConfig.append(" \" \" + \n"); newConfig.append(" \" ***add***\" + \n"); newConfig.append(" \" ").append(method.getName().substring(3)).append("\" + \n"); @@ -444,8 +436,7 @@ public class ActiveMQResourceAdapterConfigTest extends ActiveMQTestBase System.out.println(newConfig); fail("methods not shown please see previous and add"); } - else - { + else { System.out.println(commentedOutConfigs); } } @@ -454,24 +445,19 @@ public class ActiveMQResourceAdapterConfigTest extends ActiveMQTestBase * @param setter * @return */ - private Class lookupType(Method setter) - { + private Class lookupType(Method setter) { Class clzz = setter.getParameterTypes()[0]; - if (clzz == Boolean.class) - { + if (clzz == Boolean.class) { return Boolean.TYPE; } - else if (clzz == Long.class) - { + else if (clzz == Long.class) { return Long.TYPE; } - else if (clzz == Integer.class) - { + else if (clzz == Integer.class) { return Integer.TYPE; } - else - { + else { return clzz; } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/BootstrapContext.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/BootstrapContext.java index 9fcac0ee3c..30f385da48 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/BootstrapContext.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/BootstrapContext.java @@ -25,57 +25,47 @@ import javax.resource.spi.work.WorkListener; import javax.resource.spi.work.WorkManager; import java.util.Timer; -public class BootstrapContext implements javax.resource.spi.BootstrapContext -{ - public Timer createTimer() throws UnavailableException - { +public class BootstrapContext implements javax.resource.spi.BootstrapContext { + + public Timer createTimer() throws UnavailableException { return null; } - public WorkManager getWorkManager() - { - return new WorkManager() - { - public void doWork(final Work work) throws WorkException - { + public WorkManager getWorkManager() { + return new WorkManager() { + public void doWork(final Work work) throws WorkException { } public void doWork(final Work work, final long l, final ExecutionContext executionContext, - final WorkListener workListener) throws WorkException - { + final WorkListener workListener) throws WorkException { } - public long startWork(final Work work) throws WorkException - { + public long startWork(final Work work) throws WorkException { return 0; } public long startWork(final Work work, final long l, final ExecutionContext executionContext, - final WorkListener workListener) throws WorkException - { + final WorkListener workListener) throws WorkException { return 0; } - public void scheduleWork(final Work work) throws WorkException - { + public void scheduleWork(final Work work) throws WorkException { work.run(); } public void scheduleWork(final Work work, final long l, final ExecutionContext executionContext, - final WorkListener workListener) throws WorkException - { + final WorkListener workListener) throws WorkException { } }; } - public XATerminator getXATerminator() - { + public XATerminator getXATerminator() { return null; } } \ No newline at end of file diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ConnectionFactoryPropertiesTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ConnectionFactoryPropertiesTest.java index 733fc80925..5a104ce111 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ConnectionFactoryPropertiesTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ConnectionFactoryPropertiesTest.java @@ -28,14 +28,12 @@ import org.junit.Test; import static java.beans.Introspector.getBeanInfo; -public class ConnectionFactoryPropertiesTest extends ActiveMQTestBase -{ +public class ConnectionFactoryPropertiesTest extends ActiveMQTestBase { private static final SortedSet UNSUPPORTED_CF_PROPERTIES; private static final SortedSet UNSUPPORTED_RA_PROPERTIES; - static - { + static { UNSUPPORTED_CF_PROPERTIES = new TreeSet(); UNSUPPORTED_CF_PROPERTIES.add("discoveryGroupName"); @@ -68,42 +66,33 @@ public class ConnectionFactoryPropertiesTest extends ActiveMQTestBase } @Test - public void testCompareConnectionFactoryAndResourceAdapterProperties() throws Exception - { + public void testCompareConnectionFactoryAndResourceAdapterProperties() throws Exception { SortedSet connectionFactoryProperties = findAllPropertyNames(ActiveMQConnectionFactory.class); connectionFactoryProperties.removeAll(UNSUPPORTED_CF_PROPERTIES); SortedSet raProperties = findAllPropertyNames(ActiveMQResourceAdapter.class); raProperties.removeAll(UNSUPPORTED_RA_PROPERTIES); - compare("ActiveMQ Connection Factory", connectionFactoryProperties, - "ActiveMQ Resource Adapter", raProperties); + compare("ActiveMQ Connection Factory", connectionFactoryProperties, "ActiveMQ Resource Adapter", raProperties); } - private static void compare(String name1, SortedSet set1, - String name2, SortedSet set2) - { + private static void compare(String name1, SortedSet set1, String name2, SortedSet set2) { Set onlyInSet1 = new TreeSet(set1); onlyInSet1.removeAll(set2); Set onlyInSet2 = new TreeSet(set2); onlyInSet2.removeAll(set1); - if (!onlyInSet1.isEmpty() || !onlyInSet2.isEmpty()) - { + if (!onlyInSet1.isEmpty() || !onlyInSet2.isEmpty()) { fail(String.format("in %s only: %s\nin %s only: %s", name1, onlyInSet1, name2, onlyInSet2)); } assertEquals(set2, set1); } - private SortedSet findAllPropertyNames(Class clazz) throws Exception - { + private SortedSet findAllPropertyNames(Class clazz) throws Exception { SortedSet names = new TreeSet(); - for (PropertyDescriptor propDesc : getBeanInfo(clazz).getPropertyDescriptors()) - { - if (propDesc == null - || propDesc.getWriteMethod() == null) - { + for (PropertyDescriptor propDesc : getBeanInfo(clazz).getPropertyDescriptors()) { + if (propDesc == null || propDesc.getWriteMethod() == null) { continue; } names.add(propDesc.getDisplayName()); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/MessageEndpointFactory.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/MessageEndpointFactory.java index 445e24a29c..993af61f70 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/MessageEndpointFactory.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/MessageEndpointFactory.java @@ -21,18 +21,15 @@ import javax.resource.spi.endpoint.MessageEndpoint; import javax.transaction.xa.XAResource; import java.lang.reflect.Method; -public class MessageEndpointFactory implements javax.resource.spi.endpoint.MessageEndpointFactory -{ +public class MessageEndpointFactory implements javax.resource.spi.endpoint.MessageEndpointFactory { @Override - public MessageEndpoint createEndpoint(final XAResource arg0) throws UnavailableException - { + public MessageEndpoint createEndpoint(final XAResource arg0) throws UnavailableException { return null; } @Override - public boolean isDeliveryTransacted(final Method arg0) throws NoSuchMethodException - { + public boolean isDeliveryTransacted(final Method arg0) throws NoSuchMethodException { return false; } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ResourceAdapterTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ResourceAdapterTest.java index fbe65546cc..b47634095b 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ResourceAdapterTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ResourceAdapterTest.java @@ -43,8 +43,7 @@ import org.apache.activemq.artemis.ra.inflow.ActiveMQActivationSpec; import org.junit.Assert; import org.junit.Test; -public class ResourceAdapterTest extends ActiveMQTestBase -{ +public class ResourceAdapterTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -57,16 +56,14 @@ public class ResourceAdapterTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testDefaultConnectionFactory() throws Exception - { + public void testDefaultConnectionFactory() throws Exception { ActiveMQResourceAdapter ra = new ActiveMQResourceAdapter(); ra.setConnectorClassName(InVMConnectorFactory.class.getName()); ActiveMQConnectionFactory factory = ra.getDefaultActiveMQConnectionFactory(); Assert.assertEquals(factory.getCallTimeout(), ActiveMQClient.DEFAULT_CALL_TIMEOUT); Assert.assertEquals(factory.getClientFailureCheckPeriod(), ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD); Assert.assertEquals(factory.getClientID(), null); - Assert.assertEquals(factory.getConnectionLoadBalancingPolicyClassName(), - ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME); + Assert.assertEquals(factory.getConnectionLoadBalancingPolicyClassName(), ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME); Assert.assertEquals(factory.getConnectionTTL(), ActiveMQClient.DEFAULT_CONNECTION_TTL); Assert.assertEquals(factory.getConsumerMaxRate(), ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE); Assert.assertEquals(factory.getConsumerWindowSize(), ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE); @@ -77,8 +74,7 @@ public class ResourceAdapterTest extends ActiveMQTestBase // by default, reconnect attempts is set to -1 Assert.assertEquals(-1, factory.getReconnectAttempts()); Assert.assertEquals(factory.getRetryInterval(), ActiveMQClient.DEFAULT_RETRY_INTERVAL); - Assert.assertEquals(factory.getRetryIntervalMultiplier(), ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, - 0.00001); + Assert.assertEquals(factory.getRetryIntervalMultiplier(), ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, 0.00001); Assert.assertEquals(factory.getScheduledThreadPoolMaxSize(), ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE); Assert.assertEquals(factory.getThreadPoolMaxSize(), ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE); Assert.assertEquals(factory.getTransactionBatchSize(), ActiveMQClient.DEFAULT_ACK_BATCH_SIZE); @@ -91,8 +87,7 @@ public class ResourceAdapterTest extends ActiveMQTestBase } @Test - public void test2DefaultConnectionFactorySame() throws Exception - { + public void test2DefaultConnectionFactorySame() throws Exception { ActiveMQResourceAdapter ra = new ActiveMQResourceAdapter(); ra.setConnectorClassName(InVMConnectorFactory.class.getName()); ActiveMQConnectionFactory factory = ra.getDefaultActiveMQConnectionFactory(); @@ -101,16 +96,14 @@ public class ResourceAdapterTest extends ActiveMQTestBase } @Test - public void testCreateConnectionFactoryNoOverrides() throws Exception - { + public void testCreateConnectionFactoryNoOverrides() throws Exception { ActiveMQResourceAdapter ra = new ActiveMQResourceAdapter(); ra.setConnectorClassName(InVMConnectorFactory.class.getName()); ActiveMQConnectionFactory factory = ra.createActiveMQConnectionFactory(new ConnectionFactoryProperties()); Assert.assertEquals(factory.getCallTimeout(), ActiveMQClient.DEFAULT_CALL_TIMEOUT); Assert.assertEquals(factory.getClientFailureCheckPeriod(), ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD); Assert.assertEquals(factory.getClientID(), null); - Assert.assertEquals(factory.getConnectionLoadBalancingPolicyClassName(), - ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME); + Assert.assertEquals(factory.getConnectionLoadBalancingPolicyClassName(), ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME); Assert.assertEquals(factory.getConnectionTTL(), ActiveMQClient.DEFAULT_CONNECTION_TTL); Assert.assertEquals(factory.getConsumerMaxRate(), ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE); Assert.assertEquals(factory.getConsumerWindowSize(), ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE); @@ -121,8 +114,7 @@ public class ResourceAdapterTest extends ActiveMQTestBase // by default, reconnect attempts is set to -1 Assert.assertEquals(-1, factory.getReconnectAttempts()); Assert.assertEquals(factory.getRetryInterval(), ActiveMQClient.DEFAULT_RETRY_INTERVAL); - Assert.assertEquals(factory.getRetryIntervalMultiplier(), ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, - 0.000001); + Assert.assertEquals(factory.getRetryIntervalMultiplier(), ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, 0.000001); Assert.assertEquals(factory.getScheduledThreadPoolMaxSize(), ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE); Assert.assertEquals(factory.getThreadPoolMaxSize(), ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE); Assert.assertEquals(factory.getTransactionBatchSize(), ActiveMQClient.DEFAULT_ACK_BATCH_SIZE); @@ -135,8 +127,7 @@ public class ResourceAdapterTest extends ActiveMQTestBase } @Test - public void testDefaultConnectionFactoryOverrides() throws Exception - { + public void testDefaultConnectionFactoryOverrides() throws Exception { ActiveMQResourceAdapter ra = new ActiveMQResourceAdapter(); ra.setConnectorClassName(InVMConnectorFactory.class.getName()); ra.setAutoGroup(!ActiveMQClient.DEFAULT_AUTO_GROUP); @@ -191,8 +182,7 @@ public class ResourceAdapterTest extends ActiveMQTestBase } @Test - public void testCreateConnectionFactoryOverrides() throws Exception - { + public void testCreateConnectionFactoryOverrides() throws Exception { ActiveMQResourceAdapter ra = new ActiveMQResourceAdapter(); ra.setConnectorClassName(InVMConnectorFactory.class.getName()); ConnectionFactoryProperties connectionFactoryProperties = new ConnectionFactoryProperties(); @@ -248,8 +238,7 @@ public class ResourceAdapterTest extends ActiveMQTestBase } @Test - public void testCreateConnectionFactoryOverrideConnector() throws Exception - { + public void testCreateConnectionFactoryOverrideConnector() throws Exception { ActiveMQResourceAdapter ra = new ActiveMQResourceAdapter(); ra.setConnectorClassName(InVMConnectorFactory.class.getName()); ConnectionFactoryProperties connectionFactoryProperties = new ConnectionFactoryProperties(); @@ -262,8 +251,7 @@ public class ResourceAdapterTest extends ActiveMQTestBase } @Test - public void testCreateConnectionFactoryOverrideDiscovery() throws Exception - { + public void testCreateConnectionFactoryOverrideDiscovery() throws Exception { ActiveMQResourceAdapter ra = new ActiveMQResourceAdapter(); ra.setConnectorClassName(InVMConnectorFactory.class.getName()); ConnectionFactoryProperties connectionFactoryProperties = new ConnectionFactoryProperties(); @@ -281,8 +269,7 @@ public class ResourceAdapterTest extends ActiveMQTestBase } @Test - public void testCreateConnectionFactoryMultipleConnectors() - { + public void testCreateConnectionFactoryMultipleConnectors() { ActiveMQResourceAdapter ra = new ActiveMQResourceAdapter(); ra.setConnectorClassName(NETTY_CONNECTOR_FACTORY + "," + INVM_CONNECTOR_FACTORY + "," + NETTY_CONNECTOR_FACTORY); ActiveMQConnectionFactory factory = ra.createActiveMQConnectionFactory(new ConnectionFactoryProperties()); @@ -298,8 +285,7 @@ public class ResourceAdapterTest extends ActiveMQTestBase } @Test - public void testCreateConnectionFactoryMultipleConnectorsAndParams() - { + public void testCreateConnectionFactoryMultipleConnectorsAndParams() { ActiveMQResourceAdapter ra = new ActiveMQResourceAdapter(); ra.setConnectorClassName(NETTY_CONNECTOR_FACTORY + "," + INVM_CONNECTOR_FACTORY + "," + NETTY_CONNECTOR_FACTORY); ra.setConnectionParameters("host=host1;port=61616, serverid=0, host=host2;port=61617"); @@ -321,8 +307,7 @@ public class ResourceAdapterTest extends ActiveMQTestBase } @Test - public void testCreateConnectionFactoryMultipleConnectorsOverride() - { + public void testCreateConnectionFactoryMultipleConnectorsOverride() { ActiveMQResourceAdapter ra = new ActiveMQResourceAdapter(); ra.setConnectorClassName(NETTY_CONNECTOR_FACTORY + "," + INVM_CONNECTOR_FACTORY + "," + NETTY_CONNECTOR_FACTORY); ConnectionFactoryProperties overrideProperties = new ConnectionFactoryProperties(); @@ -344,8 +329,7 @@ public class ResourceAdapterTest extends ActiveMQTestBase } @Test - public void testCreateConnectionFactoryMultipleConnectorsOverrideAndParams() - { + public void testCreateConnectionFactoryMultipleConnectorsOverrideAndParams() { ActiveMQResourceAdapter ra = new ActiveMQResourceAdapter(); ra.setConnectorClassName(NETTY_CONNECTOR_FACTORY + "," + INVM_CONNECTOR_FACTORY + "," + NETTY_CONNECTOR_FACTORY); ra.setConnectionParameters("host=host1;port=61616, serverid=0, host=host2;port=61617"); @@ -384,38 +368,23 @@ public class ResourceAdapterTest extends ActiveMQTestBase } @Test - public void testCreateConnectionFactoryThrowsException() throws Exception - { + public void testCreateConnectionFactoryThrowsException() throws Exception { ActiveMQResourceAdapter ra = new ActiveMQResourceAdapter(); ConnectionFactoryProperties connectionFactoryProperties = new ConnectionFactoryProperties(); - try - { + try { ra.createActiveMQConnectionFactory(connectionFactoryProperties); Assert.fail("should throw exception"); } - catch (IllegalArgumentException e) - { + catch (IllegalArgumentException e) { // pass } } @Test - public void testValidateProperties() throws Exception - { - validateGettersAndSetters(new ActiveMQResourceAdapter(), - "backupTransportConfiguration", - "connectionParameters", - "jndiParams"); - validateGettersAndSetters(new ActiveMQRAManagedConnectionFactory(), - "connectionParameters", - "sessionDefaultType", - "backupConnectionParameters", - "jndiParams"); - validateGettersAndSetters(new ActiveMQActivationSpec(), - "connectionParameters", - "acknowledgeMode", - "subscriptionDurability", - "jndiParams"); + public void testValidateProperties() throws Exception { + validateGettersAndSetters(new ActiveMQResourceAdapter(), "backupTransportConfiguration", "connectionParameters", "jndiParams"); + validateGettersAndSetters(new ActiveMQRAManagedConnectionFactory(), "connectionParameters", "sessionDefaultType", "backupConnectionParameters", "jndiParams"); + validateGettersAndSetters(new ActiveMQActivationSpec(), "connectionParameters", "acknowledgeMode", "subscriptionDurability", "jndiParams"); ActiveMQActivationSpec spec = new ActiveMQActivationSpec(); @@ -451,12 +420,10 @@ public class ResourceAdapterTest extends ActiveMQTestBase } @Test - public void testStartActivation() throws Exception - { + public void testStartActivation() throws Exception { ActiveMQServer server = createServer(false); - try - { + try { server.start(); ServerLocator locator = createInVMNonHALocator(); @@ -502,21 +469,18 @@ public class ResourceAdapterTest extends ActiveMQTestBase locator.close(); } - finally - { + finally { server.stop(); } } @Test - public void testForConnectionLeakDuringActivationWhenSessionCreationFails() throws Exception - { + public void testForConnectionLeakDuringActivationWhenSessionCreationFails() throws Exception { ActiveMQServer server = createServer(false); ActiveMQResourceAdapter ra = null; ActiveMQActivation activation = null; - try - { + try { server.getConfiguration().setSecurityEnabled(true); server.start(); @@ -545,19 +509,16 @@ public class ResourceAdapterTest extends ActiveMQTestBase activation = new ActiveMQActivation(ra, new MessageEndpointFactory(), spec); - try - { + try { activation.start(); } - catch (Exception e) - { + catch (Exception e) { // ignore } assertEquals(0, server.getRemotingService().getConnections().size()); } - finally - { + finally { if (activation != null) activation.stop(); if (ra != null) diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/ActiveMQBufferInputStreamTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/ActiveMQBufferInputStreamTest.java index 600e518bb6..c35fa01f22 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/ActiveMQBufferInputStreamTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/ActiveMQBufferInputStreamTest.java @@ -22,15 +22,12 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.ActiveMQBufferInputStream; import org.junit.Test; -public class ActiveMQBufferInputStreamTest extends ActiveMQTestBase -{ +public class ActiveMQBufferInputStreamTest extends ActiveMQTestBase { @Test - public void testReadBytes() throws Exception - { + public void testReadBytes() throws Exception { byte[] bytes = new byte[10 * 1024]; - for (int i = 0; i < bytes.length; i++) - { + for (int i = 0; i < bytes.length; i++) { bytes[i] = getSamplebyte(i); } @@ -38,18 +35,15 @@ public class ActiveMQBufferInputStreamTest extends ActiveMQTestBase ActiveMQBufferInputStream is = new ActiveMQBufferInputStream(buffer); // First read byte per byte - for (int i = 0; i < 1024; i++) - { + for (int i = 0; i < 1024; i++) { assertEquals(getSamplebyte(i), is.read()); } // Second, read in chunks - for (int i = 1; i < 10; i++) - { + for (int i = 1; i < 10; i++) { bytes = new byte[1024]; is.read(bytes); - for (int j = 0; j < bytes.length; j++) - { + for (int j = 0; j < bytes.length; j++) { assertEquals(getSamplebyte(i * 1024 + j), bytes[j]); } @@ -57,7 +51,6 @@ public class ActiveMQBufferInputStreamTest extends ActiveMQTestBase assertEquals(-1, is.read()); - bytes = new byte[1024]; int sizeRead = is.read(bytes); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/FakePagingManager.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/FakePagingManager.java index 3033a7160b..e51252f619 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/FakePagingManager.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/FakePagingManager.java @@ -26,125 +26,101 @@ import org.apache.activemq.artemis.core.paging.PagingStore; import org.apache.activemq.artemis.core.postoffice.PostOffice; import org.apache.activemq.artemis.core.server.ServerMessage; -public final class FakePagingManager implements PagingManager -{ +public final class FakePagingManager implements PagingManager { - public void activate() - { + public void activate() { } - public long addSize(final long size) - { + public long addSize(final long size) { return 0; } - public void addTransaction(final PageTransactionInfo pageTransaction) - { + public void addTransaction(final PageTransactionInfo pageTransaction) { } - public PagingStore createPageStore(final SimpleString destination) throws Exception - { + public PagingStore createPageStore(final SimpleString destination) throws Exception { return null; } - public long getTotalMemory() - { + public long getTotalMemory() { return 0; } - public SimpleString[] getStoreNames() - { + public SimpleString[] getStoreNames() { return null; } - public long getMaxMemory() - { + public long getMaxMemory() { return 0; } - public PagingStore getPageStore(final SimpleString address) throws Exception - { + public PagingStore getPageStore(final SimpleString address) throws Exception { return null; } - public void deletePageStore(SimpleString storeName) throws Exception - { + public void deletePageStore(SimpleString storeName) throws Exception { } - public PageTransactionInfo getTransaction(final long transactionID) - { + public PageTransactionInfo getTransaction(final long transactionID) { return null; } - public boolean isBackup() - { + public boolean isBackup() { return false; } - public boolean isGlobalPageMode() - { + public boolean isGlobalPageMode() { return false; } - public boolean isPaging(final SimpleString destination) throws Exception - { + public boolean isPaging(final SimpleString destination) throws Exception { return false; } - public boolean page(final ServerMessage message, final boolean duplicateDetection) throws Exception - { + public boolean page(final ServerMessage message, final boolean duplicateDetection) throws Exception { return false; } - public boolean page(final ServerMessage message, final long transactionId, final boolean duplicateDetection) throws Exception - { + public boolean page(final ServerMessage message, + final long transactionId, + final boolean duplicateDetection) throws Exception { return false; } - public void reloadStores() throws Exception - { + public void reloadStores() throws Exception { } - public void removeTransaction(final long transactionID) - { + public void removeTransaction(final long transactionID) { } - public void setGlobalPageMode(final boolean globalMode) - { + public void setGlobalPageMode(final boolean globalMode) { } - public void setPostOffice(final PostOffice postOffice) - { + public void setPostOffice(final PostOffice postOffice) { } - public void resumeDepages() - { + public void resumeDepages() { } - public void sync(final Collection destinationsToSync) throws Exception - { + public void sync(final Collection destinationsToSync) throws Exception { } - public boolean isStarted() - { + public boolean isStarted() { return false; } - public void start() throws Exception - { + public void start() throws Exception { } - public void stop() throws Exception - { + public void stop() throws Exception { } /* * (non-Javadoc) * @see org.apache.activemq.artemis.core.paging.PagingManager#isGlobalFull() */ - public boolean isGlobalFull() - { + public boolean isGlobalFull() { return false; } @@ -152,8 +128,7 @@ public final class FakePagingManager implements PagingManager * (non-Javadoc) * @see org.apache.activemq.artemis.core.paging.PagingManager#getTransactions() */ - public Map getTransactions() - { + public Map getTransactions() { return null; } @@ -161,37 +136,31 @@ public final class FakePagingManager implements PagingManager * (non-Javadoc) * @see org.apache.activemq.artemis.core.paging.PagingManager#processReload() */ - public void processReload() - { + public void processReload() { } @Override - public void disableCleanup() - { + public void disableCleanup() { } @Override - public void resumeCleanup() - { + public void resumeCleanup() { } /* * (non-Javadoc) * @see org.apache.activemq.artemis.core.settings.HierarchicalRepositoryChangeListener#onChange() */ - public void onChange() - { + public void onChange() { } @Override - public void lock() - { + public void lock() { // no-op } @Override - public void unlock() - { + public void unlock() { // no-op } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/InVMContext.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/InVMContext.java index 3640ac2445..526f0fc8e2 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/InVMContext.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/InVMContext.java @@ -39,8 +39,7 @@ import javax.naming.Reference; import org.apache.activemq.artemis.tests.unit.UnitTestLogger; -public class InVMContext implements Context, Serializable -{ +public class InVMContext implements Context, Serializable { // Constants ----------------------------------------------------- private static final long serialVersionUID = 385743957345L; @@ -57,169 +56,137 @@ public class InVMContext implements Context, Serializable // Constructors -------------------------------------------------- - public InVMContext() - { + public InVMContext() { map = Collections.synchronizedMap(new HashMap()); } - public InVMContext(final String nameInNamespace) - { + public InVMContext(final String nameInNamespace) { this(); this.nameInNamespace = nameInNamespace; } // Context implementation ---------------------------------------- - public Object lookup(final Name name) throws NamingException - { + public Object lookup(final Name name) throws NamingException { throw new UnsupportedOperationException(); } - public Object lookup(String name) throws NamingException - { + public Object lookup(String name) throws NamingException { name = trimSlashes(name); int i = name.indexOf("/"); String tok = i == -1 ? name : name.substring(0, i); Object value = map.get(tok); - if (value == null) - { + if (value == null) { throw new NameNotFoundException("Name not found: " + tok); } - if (value instanceof InVMContext && i != -1) - { - return ((InVMContext)value).lookup(name.substring(i)); + if (value instanceof InVMContext && i != -1) { + return ((InVMContext) value).lookup(name.substring(i)); } - if (value instanceof Reference) - { - Reference ref = (Reference)value; + if (value instanceof Reference) { + Reference ref = (Reference) value; RefAddr refAddr = ref.get("nns"); // we only deal with references create by NonSerializableFactory - String key = (String)refAddr.getContent(); + String key = (String) refAddr.getContent(); return NonSerializableFactory.lookup(key); } - else - { + else { return value; } } - public void bind(final Name name, final Object obj) throws NamingException - { + public void bind(final Name name, final Object obj) throws NamingException { throw new UnsupportedOperationException(); } - public void bind(final String name, final Object obj) throws NamingException - { + public void bind(final String name, final Object obj) throws NamingException { internalBind(name, obj, false); } - public void rebind(final Name name, final Object obj) throws NamingException - { + public void rebind(final Name name, final Object obj) throws NamingException { throw new UnsupportedOperationException(); } - public void rebind(final String name, final Object obj) throws NamingException - { + public void rebind(final String name, final Object obj) throws NamingException { internalBind(name, obj, true); } - public void unbind(final Name name) throws NamingException - { + public void unbind(final Name name) throws NamingException { unbind(name.toString()); } - public void unbind(String name) throws NamingException - { + public void unbind(String name) throws NamingException { name = trimSlashes(name); int i = name.indexOf("/"); boolean terminal = i == -1; - if (terminal) - { + if (terminal) { map.remove(name); } - else - { + else { String tok = name.substring(0, i); - InVMContext c = (InVMContext)map.get(tok); - if (c == null) - { + InVMContext c = (InVMContext) map.get(tok); + if (c == null) { throw new NameNotFoundException("Context not found: " + tok); } c.unbind(name.substring(i)); } } - public void rename(final Name oldName, final Name newName) throws NamingException - { + public void rename(final Name oldName, final Name newName) throws NamingException { throw new UnsupportedOperationException(); } - public void rename(final String oldName, final String newName) throws NamingException - { + public void rename(final String oldName, final String newName) throws NamingException { throw new UnsupportedOperationException(); } - public NamingEnumeration list(final Name name) throws NamingException - { + public NamingEnumeration list(final Name name) throws NamingException { throw new UnsupportedOperationException(); } - public NamingEnumeration list(final String name) throws NamingException - { + public NamingEnumeration list(final String name) throws NamingException { throw new UnsupportedOperationException(); } - public NamingEnumeration listBindings(final Name name) throws NamingException - { + public NamingEnumeration listBindings(final Name name) throws NamingException { throw new UnsupportedOperationException(); } - public NamingEnumeration listBindings(String contextName) throws NamingException - { + public NamingEnumeration listBindings(String contextName) throws NamingException { contextName = trimSlashes(contextName); - if (!"".equals(contextName) && !".".equals(contextName)) - { - try - { - return ((InVMContext)lookup(contextName)).listBindings(""); + if (!"".equals(contextName) && !".".equals(contextName)) { + try { + return ((InVMContext) lookup(contextName)).listBindings(""); } - catch (Throwable t) - { + catch (Throwable t) { throw new NamingException(t.getMessage()); } } List l = new ArrayList(); - for (Object element : map.keySet()) - { - String name = (String)element; + for (Object element : map.keySet()) { + String name = (String) element; Object object = map.get(name); l.add(new Binding(name, object)); } return new NamingEnumerationImpl(l.iterator()); } - public void destroySubcontext(final Name name) throws NamingException - { + public void destroySubcontext(final Name name) throws NamingException { destroySubcontext(name.toString()); } - public void destroySubcontext(final String name) throws NamingException - { + public void destroySubcontext(final String name) throws NamingException { map.remove(trimSlashes(name)); } - public Context createSubcontext(final Name name) throws NamingException - { + public Context createSubcontext(final Name name) throws NamingException { throw new UnsupportedOperationException(); } - public Context createSubcontext(String name) throws NamingException - { + public Context createSubcontext(String name) throws NamingException { name = trimSlashes(name); - if (map.get(name) != null) - { + if (map.get(name) != null) { throw new NameAlreadyBoundException(name); } InVMContext c = new InVMContext(getNameInNamespace()); @@ -227,59 +194,48 @@ public class InVMContext implements Context, Serializable return c; } - public Object lookupLink(final Name name) throws NamingException - { + public Object lookupLink(final Name name) throws NamingException { throw new UnsupportedOperationException(); } - public Object lookupLink(final String name) throws NamingException - { + public Object lookupLink(final String name) throws NamingException { throw new UnsupportedOperationException(); } - public NameParser getNameParser(final Name name) throws NamingException - { + public NameParser getNameParser(final Name name) throws NamingException { return getNameParser(name.toString()); } - public NameParser getNameParser(final String name) throws NamingException - { + public NameParser getNameParser(final String name) throws NamingException { return parser; } - public Name composeName(final Name name, final Name prefix) throws NamingException - { + public Name composeName(final Name name, final Name prefix) throws NamingException { throw new UnsupportedOperationException(); } - public String composeName(final String name, final String prefix) throws NamingException - { + public String composeName(final String name, final String prefix) throws NamingException { throw new UnsupportedOperationException(); } - public Object addToEnvironment(final String propName, final Object propVal) throws NamingException - { + public Object addToEnvironment(final String propName, final Object propVal) throws NamingException { throw new UnsupportedOperationException(); } - public Object removeFromEnvironment(final String propName) throws NamingException - { + public Object removeFromEnvironment(final String propName) throws NamingException { throw new UnsupportedOperationException(); } - public Hashtable getEnvironment() throws NamingException - { + public Hashtable getEnvironment() throws NamingException { Hashtable env = new Hashtable(); env.put("java.naming.factory.initial", "org.apache.activemq.artemis.jms.tests.tools.container.InVMInitialContextFactory"); return env; } - public void close() throws NamingException - { + public void close() throws NamingException { } - public String getNameInNamespace() throws NamingException - { + public String getNameInNamespace() throws NamingException { return nameInNamespace; } @@ -291,23 +247,18 @@ public class InVMContext implements Context, Serializable // Private ------------------------------------------------------- - private String trimSlashes(String s) - { + private String trimSlashes(String s) { int i = 0; - while (true) - { - if (i == s.length() || s.charAt(i) != '/') - { + while (true) { + if (i == s.length() || s.charAt(i) != '/') { break; } i++; } s = s.substring(i); i = s.length() - 1; - while (true) - { - if (i == -1 || s.charAt(i) != '/') - { + while (true) { + if (i == -1 || s.charAt(i) != '/') { break; } i--; @@ -315,20 +266,17 @@ public class InVMContext implements Context, Serializable return s.substring(0, i + 1); } - private void internalBind(String name, final Object obj, final boolean rebind) throws NamingException - { + private void internalBind(String name, final Object obj, final boolean rebind) throws NamingException { UnitTestLogger.LOGGER.debug("Binding " + name + " obj " + obj + " rebind " + rebind); name = trimSlashes(name); int i = name.lastIndexOf("/"); InVMContext c = this; - if (i != -1) - { + if (i != -1) { String path = name.substring(0, i); - c = (InVMContext)lookup(path); + c = (InVMContext) lookup(path); } name = name.substring(i + 1); - if (!rebind && c.map.get(name) != null) - { + if (!rebind && c.map.get(name) != null) { throw new NameAlreadyBoundException(name); } c.map.put(name, obj); @@ -336,37 +284,31 @@ public class InVMContext implements Context, Serializable // Inner classes ------------------------------------------------- - private class NamingEnumerationImpl implements NamingEnumeration - { + private class NamingEnumerationImpl implements NamingEnumeration { + private final Iterator iterator; - NamingEnumerationImpl(final Iterator bindingIterator) - { + NamingEnumerationImpl(final Iterator bindingIterator) { iterator = bindingIterator; } - public void close() throws NamingException - { + public void close() throws NamingException { throw new UnsupportedOperationException(); } - public boolean hasMore() throws NamingException - { + public boolean hasMore() throws NamingException { return iterator.hasNext(); } - public T next() throws NamingException - { + public T next() throws NamingException { return iterator.next(); } - public boolean hasMoreElements() - { + public boolean hasMoreElements() { return iterator.hasNext(); } - public T nextElement() - { + public T nextElement() { return iterator.next(); } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/InVMNameParser.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/InVMNameParser.java index d1cb09aaea..ebaaa62f83 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/InVMNameParser.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/InVMNameParser.java @@ -24,8 +24,7 @@ import javax.naming.Name; import javax.naming.NameParser; import javax.naming.NamingException; -public class InVMNameParser implements NameParser, Serializable -{ +public class InVMNameParser implements NameParser, Serializable { // Constants ----------------------------------------------------- private static final long serialVersionUID = 2925203703371001031L; @@ -34,8 +33,7 @@ public class InVMNameParser implements NameParser, Serializable static Properties syntax; - static - { + static { InVMNameParser.syntax = new Properties(); InVMNameParser.syntax.put("jndi.syntax.direction", "left_to_right"); InVMNameParser.syntax.put("jndi.syntax.ignorecase", "false"); @@ -48,13 +46,11 @@ public class InVMNameParser implements NameParser, Serializable // Public -------------------------------------------------------- - public static Properties getSyntax() - { + public static Properties getSyntax() { return InVMNameParser.syntax; } - public Name parse(final String name) throws NamingException - { + public Name parse(final String name) throws NamingException { return new CompoundName(name, InVMNameParser.syntax); } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/InVMNamingContext.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/InVMNamingContext.java index 19e794a792..8b7df6dddd 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/InVMNamingContext.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/InVMNamingContext.java @@ -39,8 +39,7 @@ import javax.naming.Reference; import org.apache.activemq.artemis.tests.unit.UnitTestLogger; -public class InVMNamingContext implements Context, Serializable -{ +public class InVMNamingContext implements Context, Serializable { // Constants ----------------------------------------------------- private static final long serialVersionUID = 385743957345L; @@ -57,169 +56,137 @@ public class InVMNamingContext implements Context, Serializable // Constructors -------------------------------------------------- - public InVMNamingContext() - { + public InVMNamingContext() { map = Collections.synchronizedMap(new HashMap()); } - public InVMNamingContext(final String nameInNamespace) - { + public InVMNamingContext(final String nameInNamespace) { this(); this.nameInNamespace = nameInNamespace; } // Context implementation ---------------------------------------- - public Object lookup(final Name name) throws NamingException - { + public Object lookup(final Name name) throws NamingException { throw new UnsupportedOperationException(); } - public Object lookup(String name) throws NamingException - { + public Object lookup(String name) throws NamingException { name = trimSlashes(name); int i = name.indexOf("/"); String tok = i == -1 ? name : name.substring(0, i); Object value = map.get(tok); - if (value == null) - { + if (value == null) { throw new NameNotFoundException("Name not found: " + tok); } - if (value instanceof InVMNamingContext && i != -1) - { - return ((InVMNamingContext)value).lookup(name.substring(i)); + if (value instanceof InVMNamingContext && i != -1) { + return ((InVMNamingContext) value).lookup(name.substring(i)); } - if (value instanceof Reference) - { - Reference ref = (Reference)value; + if (value instanceof Reference) { + Reference ref = (Reference) value; RefAddr refAddr = ref.get("nns"); // we only deal with references create by NonSerializableFactory - String key = (String)refAddr.getContent(); + String key = (String) refAddr.getContent(); return NonSerializableFactory.lookup(key); } - else - { + else { return value; } } - public void bind(final Name name, final Object obj) throws NamingException - { + public void bind(final Name name, final Object obj) throws NamingException { throw new UnsupportedOperationException(); } - public void bind(final String name, final Object obj) throws NamingException - { + public void bind(final String name, final Object obj) throws NamingException { internalBind(name, obj, false); } - public void rebind(final Name name, final Object obj) throws NamingException - { + public void rebind(final Name name, final Object obj) throws NamingException { throw new UnsupportedOperationException(); } - public void rebind(final String name, final Object obj) throws NamingException - { + public void rebind(final String name, final Object obj) throws NamingException { internalBind(name, obj, true); } - public void unbind(final Name name) throws NamingException - { + public void unbind(final Name name) throws NamingException { unbind(name.toString()); } - public void unbind(String name) throws NamingException - { + public void unbind(String name) throws NamingException { name = trimSlashes(name); int i = name.indexOf("/"); boolean terminal = i == -1; - if (terminal) - { + if (terminal) { map.remove(name); } - else - { + else { String tok = name.substring(0, i); - InVMNamingContext c = (InVMNamingContext)map.get(tok); - if (c == null) - { + InVMNamingContext c = (InVMNamingContext) map.get(tok); + if (c == null) { throw new NameNotFoundException("Context not found: " + tok); } c.unbind(name.substring(i)); } } - public void rename(final Name oldName, final Name newName) throws NamingException - { + public void rename(final Name oldName, final Name newName) throws NamingException { throw new UnsupportedOperationException(); } - public void rename(final String oldName, final String newName) throws NamingException - { + public void rename(final String oldName, final String newName) throws NamingException { throw new UnsupportedOperationException(); } - public NamingEnumeration list(final Name name) throws NamingException - { + public NamingEnumeration list(final Name name) throws NamingException { throw new UnsupportedOperationException(); } - public NamingEnumeration list(final String name) throws NamingException - { + public NamingEnumeration list(final String name) throws NamingException { throw new UnsupportedOperationException(); } - public NamingEnumeration listBindings(final Name name) throws NamingException - { + public NamingEnumeration listBindings(final Name name) throws NamingException { throw new UnsupportedOperationException(); } - public NamingEnumeration listBindings(String contextName) throws NamingException - { + public NamingEnumeration listBindings(String contextName) throws NamingException { contextName = trimSlashes(contextName); - if (!"".equals(contextName) && !".".equals(contextName)) - { - try - { - return ((InVMNamingContext)lookup(contextName)).listBindings(""); + if (!"".equals(contextName) && !".".equals(contextName)) { + try { + return ((InVMNamingContext) lookup(contextName)).listBindings(""); } - catch (Throwable t) - { + catch (Throwable t) { throw new NamingException(t.getMessage()); } } List l = new ArrayList(); - for (Object element : map.keySet()) - { - String name = (String)element; + for (Object element : map.keySet()) { + String name = (String) element; Object object = map.get(name); l.add(new Binding(name, object)); } return new NamingEnumerationImpl(l.iterator()); } - public void destroySubcontext(final Name name) throws NamingException - { + public void destroySubcontext(final Name name) throws NamingException { destroySubcontext(name.toString()); } - public void destroySubcontext(final String name) throws NamingException - { + public void destroySubcontext(final String name) throws NamingException { map.remove(trimSlashes(name)); } - public Context createSubcontext(final Name name) throws NamingException - { + public Context createSubcontext(final Name name) throws NamingException { throw new UnsupportedOperationException(); } - public Context createSubcontext(String name) throws NamingException - { + public Context createSubcontext(String name) throws NamingException { name = trimSlashes(name); - if (map.get(name) != null) - { + if (map.get(name) != null) { throw new NameAlreadyBoundException(name); } InVMNamingContext c = new InVMNamingContext(getNameInNamespace()); @@ -227,59 +194,48 @@ public class InVMNamingContext implements Context, Serializable return c; } - public Object lookupLink(final Name name) throws NamingException - { + public Object lookupLink(final Name name) throws NamingException { throw new UnsupportedOperationException(); } - public Object lookupLink(final String name) throws NamingException - { + public Object lookupLink(final String name) throws NamingException { throw new UnsupportedOperationException(); } - public NameParser getNameParser(final Name name) throws NamingException - { + public NameParser getNameParser(final Name name) throws NamingException { return getNameParser(name.toString()); } - public NameParser getNameParser(final String name) throws NamingException - { + public NameParser getNameParser(final String name) throws NamingException { return parser; } - public Name composeName(final Name name, final Name prefix) throws NamingException - { + public Name composeName(final Name name, final Name prefix) throws NamingException { throw new UnsupportedOperationException(); } - public String composeName(final String name, final String prefix) throws NamingException - { + public String composeName(final String name, final String prefix) throws NamingException { throw new UnsupportedOperationException(); } - public Object addToEnvironment(final String propName, final Object propVal) throws NamingException - { + public Object addToEnvironment(final String propName, final Object propVal) throws NamingException { throw new UnsupportedOperationException(); } - public Object removeFromEnvironment(final String propName) throws NamingException - { + public Object removeFromEnvironment(final String propName) throws NamingException { throw new UnsupportedOperationException(); } - public Hashtable getEnvironment() throws NamingException - { + public Hashtable getEnvironment() throws NamingException { Hashtable env = new Hashtable(); env.put("java.naming.factory.initial", "org.apache.activemq.artemis.jms.tests.tools.container.InVMInitialContextFactory"); return env; } - public void close() throws NamingException - { + public void close() throws NamingException { } - public String getNameInNamespace() throws NamingException - { + public String getNameInNamespace() throws NamingException { return nameInNamespace; } @@ -291,23 +247,18 @@ public class InVMNamingContext implements Context, Serializable // Private ------------------------------------------------------- - private String trimSlashes(String s) - { + private String trimSlashes(String s) { int i = 0; - while (true) - { - if (i == s.length() || s.charAt(i) != '/') - { + while (true) { + if (i == s.length() || s.charAt(i) != '/') { break; } i++; } s = s.substring(i); i = s.length() - 1; - while (true) - { - if (i == -1 || s.charAt(i) != '/') - { + while (true) { + if (i == -1 || s.charAt(i) != '/') { break; } i--; @@ -315,20 +266,17 @@ public class InVMNamingContext implements Context, Serializable return s.substring(0, i + 1); } - private void internalBind(String name, final Object obj, final boolean rebind) throws NamingException - { + private void internalBind(String name, final Object obj, final boolean rebind) throws NamingException { UnitTestLogger.LOGGER.debug("Binding " + name + " obj " + obj + " rebind " + rebind); name = trimSlashes(name); int i = name.lastIndexOf("/"); InVMNamingContext c = this; - if (i != -1) - { + if (i != -1) { String path = name.substring(0, i); - c = (InVMNamingContext)lookup(path); + c = (InVMNamingContext) lookup(path); } name = name.substring(i + 1); - if (!rebind && c.map.get(name) != null) - { + if (!rebind && c.map.get(name) != null) { throw new NameAlreadyBoundException(name); } c.map.put(name, obj); @@ -336,37 +284,31 @@ public class InVMNamingContext implements Context, Serializable // Inner classes ------------------------------------------------- - private class NamingEnumerationImpl implements NamingEnumeration - { + private class NamingEnumerationImpl implements NamingEnumeration { + private final Iterator iterator; - NamingEnumerationImpl(final Iterator bindingIterator) - { + NamingEnumerationImpl(final Iterator bindingIterator) { iterator = bindingIterator; } - public void close() throws NamingException - { + public void close() throws NamingException { throw new UnsupportedOperationException(); } - public boolean hasMore() throws NamingException - { + public boolean hasMore() throws NamingException { return iterator.hasNext(); } - public T next() throws NamingException - { + public T next() throws NamingException { return iterator.next(); } - public boolean hasMoreElements() - { + public boolean hasMoreElements() { return iterator.hasNext(); } - public T nextElement() - { + public T nextElement() { return iterator.next(); } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/LinkedListTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/LinkedListTest.java index 63b0df7994..5f180e71ed 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/LinkedListTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/LinkedListTest.java @@ -28,36 +28,32 @@ import org.apache.activemq.artemis.utils.LinkedListIterator; import org.junit.Before; import org.junit.Test; -public class LinkedListTest extends ActiveMQTestBase -{ +public class LinkedListTest extends ActiveMQTestBase { + private LinkedListImpl list; @Override @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); list = new LinkedListImpl(); } @Test - public void testAddAndRemove() - { + public void testAddAndRemove() { final AtomicInteger count = new AtomicInteger(0); - class MyObject - { + class MyObject { + private final byte[] payload; - MyObject() - { + MyObject() { count.incrementAndGet(); payload = new byte[10 * 1024]; } @Override - protected void finalize() throws Exception - { + protected void finalize() throws Exception { count.decrementAndGet(); } } @@ -65,37 +61,31 @@ public class LinkedListTest extends ActiveMQTestBase LinkedListImpl objs = new LinkedListImpl(); // Initial add - for (int i = 0; i < 1000; i++) - { + for (int i = 0; i < 1000; i++) { objs.addTail(new MyObject()); } LinkedListIterator iter = objs.iterator(); - for (int i = 0; i < 5000; i++) - { + for (int i = 0; i < 5000; i++) { - for (int add = 0; add < 1000; add++) - { + for (int add = 0; add < 1000; add++) { objs.addTail(new MyObject()); } - for (int remove = 0; remove < 1000; remove++) - { + for (int remove = 0; remove < 1000; remove++) { assertNotNull(iter.next()); iter.remove(); } - if (i % 1000 == 0) - { + if (i % 1000 == 0) { assertCount(1000, count); } } assertCount(1000, count); - while (iter.hasNext()) - { + while (iter.hasNext()) { iter.next(); iter.remove(); } @@ -105,29 +95,24 @@ public class LinkedListTest extends ActiveMQTestBase } @Test - public void testAddHeadAndRemove() - { + public void testAddHeadAndRemove() { final AtomicInteger count = new AtomicInteger(0); - class MyObject - { + class MyObject { public int payload; - MyObject(int payloadcount) - { + MyObject(int payloadcount) { count.incrementAndGet(); this.payload = payloadcount; } @Override - protected void finalize() throws Exception - { + protected void finalize() throws Exception { count.decrementAndGet(); } @Override - public String toString() - { + public String toString() { return "" + payload; } } @@ -135,8 +120,7 @@ public class LinkedListTest extends ActiveMQTestBase LinkedListImpl objs = new LinkedListImpl(); // Initial add - for (int i = 1000; i >= 0; i--) - { + for (int i = 1000; i >= 0; i--) { objs.addHead(new MyObject(i)); } assertCount(1001, count); @@ -144,12 +128,10 @@ public class LinkedListTest extends ActiveMQTestBase LinkedListIterator iter = objs.iterator(); int countLoop = 0; - for (countLoop = 0; countLoop <= 1000; countLoop++) - { + for (countLoop = 0; countLoop <= 1000; countLoop++) { MyObject obj = iter.next(); assertEquals(countLoop, obj.payload); - if (countLoop == 500 || countLoop == 1000) - { + if (countLoop == 500 || countLoop == 1000) { iter.remove(); } } @@ -159,10 +141,8 @@ public class LinkedListTest extends ActiveMQTestBase iter = objs.iterator(); countLoop = 0; - while (iter.hasNext()) - { - if (countLoop == 500 || countLoop == 1000) - { + while (iter.hasNext()) { + if (countLoop == 500 || countLoop == 1000) { System.out.println("Jumping " + countLoop); countLoop++; } @@ -171,7 +151,6 @@ public class LinkedListTest extends ActiveMQTestBase countLoop++; } - assertCount(999, count); // it's needed to add this line here because IBM JDK calls finalize on all objects in list @@ -183,28 +162,22 @@ public class LinkedListTest extends ActiveMQTestBase /** * @param count */ - private void assertCount(final int expected, final AtomicInteger count) - { + private void assertCount(final int expected, final AtomicInteger count) { long timeout = System.currentTimeMillis() + 15000; int seqCount = 0; - while (timeout > System.currentTimeMillis() && count.get() != expected) - { + while (timeout > System.currentTimeMillis() && count.get() != expected) { seqCount++; - if (seqCount > 5) - { + if (seqCount > 5) { LinkedList toOME = new LinkedList(); int someCount = 0; - try - { + try { WeakReference ref = new WeakReference(new Object()); - while (ref.get() != null) - { + while (ref.get() != null) { toOME.add("sdlfkjshadlfkjhas dlfkjhas dlfkjhads lkjfhads lfkjhads flkjashdf " + someCount++); } } - catch (Throwable expectedThrowable) - { + catch (Throwable expectedThrowable) { } toOME.clear(); @@ -216,21 +189,18 @@ public class LinkedListTest extends ActiveMQTestBase } @Test - public void testAddTail() - { + public void testAddTail() { int num = 10; assertEquals(0, list.size()); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addTail(i); assertEquals(i + 1, list.size()); } - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { assertEquals(i, list.poll().intValue()); assertEquals(num - i - 1, list.size()); @@ -238,21 +208,18 @@ public class LinkedListTest extends ActiveMQTestBase } @Test - public void testAddHead() - { + public void testAddHead() { int num = 10; assertEquals(0, list.size()); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addHead(i); assertEquals(i + 1, list.size()); } - for (int i = num - 1; i >= 0; i--) - { + for (int i = num - 1; i >= 0; i--) { assertEquals(i, list.poll().intValue()); assertEquals(i, list.size()); @@ -260,68 +227,56 @@ public class LinkedListTest extends ActiveMQTestBase } @Test - public void testAddHeadAndTail() - { + public void testAddHeadAndTail() { int num = 10; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addHead(i); } - for (int i = num; i < num * 2; i++) - { + for (int i = num; i < num * 2; i++) { list.addTail(i); } - for (int i = num * 2; i < num * 3; i++) - { + for (int i = num * 2; i < num * 3; i++) { list.addHead(i); } - for (int i = num * 3; i < num * 4; i++) - { + for (int i = num * 3; i < num * 4; i++) { list.addTail(i); } - for (int i = num * 3 - 1; i >= num * 2; i--) - { + for (int i = num * 3 - 1; i >= num * 2; i--) { assertEquals(i, list.poll().intValue()); } - for (int i = num - 1; i >= 0; i--) - { + for (int i = num - 1; i >= 0; i--) { assertEquals(i, list.poll().intValue()); } - for (int i = num; i < num * 2; i++) - { + for (int i = num; i < num * 2; i++) { assertEquals(i, list.poll().intValue()); } - for (int i = num * 3; i < num * 4; i++) - { + for (int i = num * 3; i < num * 4; i++) { assertEquals(i, list.poll().intValue()); } } @Test - public void testPoll() - { + public void testPoll() { int num = 10; assertNull(list.poll()); assertNull(list.poll()); assertNull(list.poll()); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addTail(i); } - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { assertEquals(i, list.poll().intValue()); } @@ -329,13 +284,11 @@ public class LinkedListTest extends ActiveMQTestBase assertNull(list.poll()); assertNull(list.poll()); - for (int i = num; i < num * 2; i++) - { + for (int i = num; i < num * 2; i++) { list.addHead(i); } - for (int i = num * 2 - 1; i >= num; i--) - { + for (int i = num * 2 - 1; i >= num; i--) { assertEquals(i, list.poll().intValue()); } @@ -346,37 +299,32 @@ public class LinkedListTest extends ActiveMQTestBase } @Test - public void testIterateNoElements() - { + public void testIterateNoElements() { LinkedListIterator iter = list.iterator(); assertNotNull(iter); assertNoSuchElementIsThrown(iter); - try - { + try { iter.remove(); fail("Should throw NoSuchElementException"); } - catch (NoSuchElementException e) - { + catch (NoSuchElementException e) { // OK } } @Test - public void testCreateIteratorBeforeAddElements() - { + public void testCreateIteratorBeforeAddElements() { int num = 10; LinkedListIterator iter = list.iterator(); assertNotNull(iter); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addTail(i); } @@ -384,12 +332,10 @@ public class LinkedListTest extends ActiveMQTestBase } @Test - public void testCreateIteratorAfterAddElements() - { + public void testCreateIteratorAfterAddElements() { int num = 10; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addTail(i); } @@ -401,12 +347,10 @@ public class LinkedListTest extends ActiveMQTestBase } @Test - public void testIterateThenAddMoreAndIterateAgain() - { + public void testIterateThenAddMoreAndIterateAgain() { int num = 10; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addTail(i); } @@ -414,8 +358,7 @@ public class LinkedListTest extends ActiveMQTestBase assertNotNull(iter); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { assertTrue(iter.hasNext()); assertEquals(i, iter.next().intValue()); } @@ -425,13 +368,11 @@ public class LinkedListTest extends ActiveMQTestBase // Add more - for (int i = num; i < num * 2; i++) - { + for (int i = num; i < num * 2; i++) { list.addTail(i); } - for (int i = num; i < num * 2; i++) - { + for (int i = num; i < num * 2; i++) { assertTrue(iter.hasNext()); assertEquals(i, iter.next().intValue()); } @@ -441,30 +382,25 @@ public class LinkedListTest extends ActiveMQTestBase // Add some more at head - for (int i = num * 2; i < num * 3; i++) - { + for (int i = num * 2; i < num * 3; i++) { list.addHead(i); } iter = list.iterator(); - for (int i = num * 3 - 1; i >= num * 2; i--) - { + for (int i = num * 3 - 1; i >= num * 2; i--) { assertTrue(iter.hasNext()); assertEquals(i, iter.next().intValue()); } - for (int i = 0; i < num * 2; i++) - { + for (int i = 0; i < num * 2; i++) { assertTrue(iter.hasNext()); assertEquals(i, iter.next().intValue()); } assertFalse(iter.hasNext()); } - private void testIterate1(int num, LinkedListIterator iter) - { - for (int i = 0; i < num; i++) - { + private void testIterate1(int num, LinkedListIterator iter) { + for (int i = 0; i < num; i++) { assertTrue(iter.hasNext()); assertEquals(i, iter.next().intValue()); } @@ -476,58 +412,48 @@ public class LinkedListTest extends ActiveMQTestBase /** * @param iter */ - private void assertNoSuchElementIsThrown(LinkedListIterator iter) - { - try - { + private void assertNoSuchElementIsThrown(LinkedListIterator iter) { + try { iter.next(); fail("Should throw NoSuchElementException"); } - catch (NoSuchElementException e) - { + catch (NoSuchElementException e) { // OK } } @Test - public void testRemoveAll() - { + public void testRemoveAll() { int num = 10; LinkedListIterator iter = list.iterator(); - try - { + try { iter.remove(); fail("Should throw NoSuchElementException"); } - catch (NoSuchElementException e) - { + catch (NoSuchElementException e) { // OK } - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addTail(i); } assertEquals(num, list.size()); - try - { + try { iter.remove(); fail("Should throw NoSuchElementException"); } - catch (NoSuchElementException e) - { + catch (NoSuchElementException e) { // OK } - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { assertTrue(iter.hasNext()); assertEquals(i, iter.next().intValue()); iter.remove(); @@ -538,46 +464,38 @@ public class LinkedListTest extends ActiveMQTestBase } @Test - public void testRemoveOdd() - { + public void testRemoveOdd() { int num = 10; LinkedListIterator iter = list.iterator(); - try - { + try { iter.remove(); fail("Should throw NoSuchElementException"); } - catch (NoSuchElementException e) - { + catch (NoSuchElementException e) { // OK } - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addTail(i); } - try - { + try { iter.remove(); fail("Should throw NoSuchElementException"); } - catch (NoSuchElementException e) - { + catch (NoSuchElementException e) { // OK } int size = num; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { assertTrue(iter.hasNext()); assertEquals(i, iter.next().intValue()); - if (i % 2 == 0) - { + if (i % 2 == 0) { iter.remove(); size--; } @@ -585,10 +503,8 @@ public class LinkedListTest extends ActiveMQTestBase } iter = list.iterator(); - for (int i = 0; i < num; i++) - { - if (i % 2 == 1) - { + for (int i = 0; i < num; i++) { + if (i % 2 == 1) { assertTrue(iter.hasNext()); assertEquals(i, iter.next().intValue()); } @@ -598,22 +514,19 @@ public class LinkedListTest extends ActiveMQTestBase } @Test - public void testRemoveHead1() - { + public void testRemoveHead1() { int num = 10; LinkedListIterator iter = list.iterator(); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addTail(i); } iter.next(); iter.remove(); - for (int i = 1; i < num; i++) - { + for (int i = 1; i < num; i++) { assertTrue(iter.hasNext()); assertEquals(i, iter.next().intValue()); } @@ -622,12 +535,10 @@ public class LinkedListTest extends ActiveMQTestBase } @Test - public void testRemoveHead2() - { + public void testRemoveHead2() { int num = 10; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addTail(i); } @@ -638,8 +549,7 @@ public class LinkedListTest extends ActiveMQTestBase iter = list.iterator(); - for (int i = 1; i < num; i++) - { + for (int i = 1; i < num; i++) { assertTrue(iter.hasNext()); assertEquals(i, iter.next().intValue()); } @@ -648,31 +558,26 @@ public class LinkedListTest extends ActiveMQTestBase } @Test - public void testRemoveHead3() - { + public void testRemoveHead3() { int num = 10; LinkedListIterator iter = list.iterator(); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addTail(i); } - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { assertTrue(iter.hasNext()); assertEquals(i, iter.next().intValue()); iter.remove(); } - for (int i = num; i < num * 2; i++) - { + for (int i = num; i < num * 2; i++) { list.addTail(i); } - for (int i = num; i < num * 2; i++) - { + for (int i = num; i < num * 2; i++) { assertTrue(iter.hasNext()); assertEquals(i, iter.next().intValue()); iter.remove(); @@ -681,19 +586,16 @@ public class LinkedListTest extends ActiveMQTestBase } @Test - public void testRemoveTail1() - { + public void testRemoveTail1() { int num = 10; LinkedListIterator iter = list.iterator(); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addTail(i); } - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { assertTrue(iter.hasNext()); assertEquals(i, iter.next().intValue()); } @@ -705,8 +607,7 @@ public class LinkedListTest extends ActiveMQTestBase iter = list.iterator(); - for (int i = 0; i < num - 1; i++) - { + for (int i = 0; i < num - 1; i++) { assertTrue(iter.hasNext()); assertEquals(i, iter.next().intValue()); } @@ -715,19 +616,16 @@ public class LinkedListTest extends ActiveMQTestBase } @Test - public void testRemoveMiddle() - { + public void testRemoveMiddle() { int num = 10; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addTail(i); } LinkedListIterator iter = list.iterator(); - for (int i = 0; i < num / 2; i++) - { + for (int i = 0; i < num / 2; i++) { assertTrue(iter.hasNext()); assertEquals(i, iter.next().intValue()); } @@ -737,10 +635,8 @@ public class LinkedListTest extends ActiveMQTestBase iter = list.iterator(); - for (int i = 0; i < num; i++) - { - if (i != num / 2 - 1) - { + for (int i = 0; i < num; i++) { + if (i != num / 2 - 1) { assertTrue(iter.hasNext()); assertEquals(i, iter.next().intValue()); } @@ -750,19 +646,16 @@ public class LinkedListTest extends ActiveMQTestBase } @Test - public void testRemoveTail2() - { + public void testRemoveTail2() { int num = 10; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addTail(i); } LinkedListIterator iter = list.iterator(); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { assertTrue(iter.hasNext()); assertEquals(i, iter.next().intValue()); } @@ -772,19 +665,16 @@ public class LinkedListTest extends ActiveMQTestBase // Remove the last one, that's element 9 iter.remove(); - try - { + try { iter.remove(); fail("Should throw exception"); } - catch (NoSuchElementException e) - { + catch (NoSuchElementException e) { } iter = list.iterator(); - for (int i = 0; i < num - 1; i++) - { + for (int i = 0; i < num - 1; i++) { assertTrue(iter.hasNext()); assertEquals(i, iter.next().intValue()); } @@ -793,19 +683,16 @@ public class LinkedListTest extends ActiveMQTestBase } @Test - public void testRemoveTail3() - { + public void testRemoveTail3() { int num = 10; LinkedListIterator iter = list.iterator(); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addTail(i); } - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { assertTrue(iter.hasNext()); assertEquals(i, iter.next().intValue()); } @@ -815,30 +702,26 @@ public class LinkedListTest extends ActiveMQTestBase // This should remove the 9th element and move the iterator back to position 8 iter.remove(); - for (int i = num; i < num * 2; i++) - { + for (int i = num; i < num * 2; i++) { list.addTail(i); } assertTrue(iter.hasNext()); assertEquals(8, iter.next().intValue()); - for (int i = num; i < num * 2; i++) - { + for (int i = num; i < num * 2; i++) { assertTrue(iter.hasNext()); assertEquals(i, iter.next().intValue()); } } @Test - public void testRemoveHeadAndTail1() - { + public void testRemoveHeadAndTail1() { LinkedListIterator iter = list.iterator(); int num = 10; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addTail(i); assertTrue(iter.hasNext()); assertEquals(i, iter.next().intValue()); @@ -848,14 +731,12 @@ public class LinkedListTest extends ActiveMQTestBase } @Test - public void testRemoveHeadAndTail2() - { + public void testRemoveHeadAndTail2() { LinkedListIterator iter = list.iterator(); int num = 10; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addHead(i); assertEquals(1, list.size()); assertTrue(iter.hasNext()); @@ -866,20 +747,16 @@ public class LinkedListTest extends ActiveMQTestBase } @Test - public void testRemoveHeadAndTail3() - { + public void testRemoveHeadAndTail3() { LinkedListIterator iter = list.iterator(); int num = 10; - for (int i = 0; i < num; i++) - { - if (i % 2 == 0) - { + for (int i = 0; i < num; i++) { + if (i % 2 == 0) { list.addHead(i); } - else - { + else { list.addTail(i); } assertEquals(1, list.size()); @@ -891,19 +768,16 @@ public class LinkedListTest extends ActiveMQTestBase } @Test - public void testRemoveInTurn() - { + public void testRemoveInTurn() { LinkedListIterator iter = list.iterator(); int num = 10; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addTail(i); } - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { assertTrue(iter.hasNext()); assertEquals(i, iter.next().intValue()); iter.remove(); @@ -915,13 +789,11 @@ public class LinkedListTest extends ActiveMQTestBase } @Test - public void testClear() - { + public void testClear() { int num = 10; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addTail(i); } @@ -937,16 +809,13 @@ public class LinkedListTest extends ActiveMQTestBase assertFalse(iter.hasNext()); - try - { + try { iter.next(); } - catch (NoSuchElementException e) - { + catch (NoSuchElementException e) { } - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addTail(i); } @@ -954,15 +823,13 @@ public class LinkedListTest extends ActiveMQTestBase iter = list.iterator(); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { assertTrue(iter.hasNext()); assertEquals(i, iter.next().intValue()); } assertFalse(iter.hasNext()); - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { assertEquals(i, list.poll().intValue()); } assertNull(list.poll()); @@ -971,12 +838,10 @@ public class LinkedListTest extends ActiveMQTestBase } @Test - public void testMultipleIterators1() - { + public void testMultipleIterators1() { int num = 10; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addTail(i); } @@ -984,14 +849,12 @@ public class LinkedListTest extends ActiveMQTestBase LinkedListIterator iter2 = list.iterator(); LinkedListIterator iter3 = list.iterator(); - for (int i = 0; i < num; ) - { + for (int i = 0; i < num; ) { assertTrue(iter1.hasNext()); assertEquals(i++, iter1.next().intValue()); iter1.remove(); - if (i == 10) - { + if (i == 10) { break; } @@ -1006,12 +869,10 @@ public class LinkedListTest extends ActiveMQTestBase } @Test - public void testRepeat() - { + public void testRepeat() { int num = 10; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addTail(i); } @@ -1048,12 +909,10 @@ public class LinkedListTest extends ActiveMQTestBase } @Test - public void testRepeatAndRemove() - { + public void testRepeatAndRemove() { int num = 10; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addTail(i); } @@ -1105,12 +964,10 @@ public class LinkedListTest extends ActiveMQTestBase } @Test - public void testMultipleIterators2() - { + public void testMultipleIterators2() { int num = 10; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addTail(i); } @@ -1243,27 +1100,23 @@ public class LinkedListTest extends ActiveMQTestBase } @Test - public void testResizing() - { + public void testResizing() { int numIters = 1000; List> iters = new java.util.LinkedList>(); int num = 10; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { list.addTail(i); } - for (int i = 0; i < numIters; i++) - { + for (int i = 0; i < numIters; i++) { LinkedListIterator iter = list.iterator(); iters.add(iter); - for (int j = 0; j < num / 2; j++) - { + for (int j = 0; j < num / 2; j++) { assertTrue(iter.hasNext()); assertEquals(j, iter.next().intValue()); @@ -1275,10 +1128,8 @@ public class LinkedListTest extends ActiveMQTestBase // Close the odd ones boolean b = false; - for (LinkedListIterator iter : iters) - { - if (b) - { + for (LinkedListIterator iter : iters) { + if (b) { iter.close(); } b = !b; @@ -1289,10 +1140,8 @@ public class LinkedListTest extends ActiveMQTestBase // close the even ones b = true; - for (LinkedListIterator iter : iters) - { - if (b) - { + for (LinkedListIterator iter : iters) { + if (b) { iter.close(); } b = !b; diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/MemorySizeTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/MemorySizeTest.java index 4bd536c054..b6e08ef9c0 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/MemorySizeTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/MemorySizeTest.java @@ -25,23 +25,18 @@ import org.apache.activemq.artemis.core.server.impl.ServerMessageImpl; import org.apache.activemq.artemis.tests.unit.UnitTestLogger; import org.apache.activemq.artemis.utils.MemorySize; -public class MemorySizeTest extends Assert -{ +public class MemorySizeTest extends Assert { + @Test - public void testObjectSizes() throws Exception - { - UnitTestLogger.LOGGER.info("Server message size is " + MemorySize.calculateSize(new MemorySize.ObjectFactory() - { - public Object createObject() - { + public void testObjectSizes() throws Exception { + UnitTestLogger.LOGGER.info("Server message size is " + MemorySize.calculateSize(new MemorySize.ObjectFactory() { + public Object createObject() { return new ServerMessageImpl(1, 1000); } })); - UnitTestLogger.LOGGER.info("Message reference size is " + MemorySize.calculateSize(new MemorySize.ObjectFactory() - { - public Object createObject() - { + UnitTestLogger.LOGGER.info("Message reference size is " + MemorySize.calculateSize(new MemorySize.ObjectFactory() { + public Object createObject() { return new MessageReferenceImpl(); } })); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/NonSerializableFactory.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/NonSerializableFactory.java index 6697684e0b..a7d21d2b2f 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/NonSerializableFactory.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/NonSerializableFactory.java @@ -30,74 +30,71 @@ import java.util.Map; /** * used by the default context when running in embedded local configuration */ -public class NonSerializableFactory implements ObjectFactory -{ +public class NonSerializableFactory implements ObjectFactory { - public NonSerializableFactory() - { + public NonSerializableFactory() { } -// public static void unbind(final Context ctx, final String strName) throws NamingException -// { -// Name name = ctx.getNameParser("").parse(strName); -// int size = name.size(); -// String atom = name.get(size - 1); -// Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1)); -// String key = new StringBuilder().append(parentCtx.getNameInNamespace()).append("/").append(atom).toString(); -// NonSerializableFactory.getWrapperMap().remove(key); -// Util.unbind(ctx, strName); -// } + // public static void unbind(final Context ctx, final String strName) throws NamingException + // { + // Name name = ctx.getNameParser("").parse(strName); + // int size = name.size(); + // String atom = name.get(size - 1); + // Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1)); + // String key = new StringBuilder().append(parentCtx.getNameInNamespace()).append("/").append(atom).toString(); + // NonSerializableFactory.getWrapperMap().remove(key); + // Util.unbind(ctx, strName); + // } -// public static void rebind(final Context ctx, final String strName, final Object value) throws NamingException -// { -// Name name = ctx.getNameParser("").parse(strName); -// int size = name.size(); -// String atom = name.get(size - 1); -// Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1)); -// String key = new StringBuilder().append(parentCtx.getNameInNamespace()).append("/").append(atom).toString(); -// NonSerializableFactory.getWrapperMap().put(key, value); -// String className = value.getClass().getName(); -// String factory = NonSerializableFactory.class.getName(); -// StringRefAddr addr = new StringRefAddr("nns", key); -// Reference memoryRef = new Reference(className, addr, factory, null); -// parentCtx.rebind(atom, memoryRef); -// } + // public static void rebind(final Context ctx, final String strName, final Object value) throws NamingException + // { + // Name name = ctx.getNameParser("").parse(strName); + // int size = name.size(); + // String atom = name.get(size - 1); + // Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1)); + // String key = new StringBuilder().append(parentCtx.getNameInNamespace()).append("/").append(atom).toString(); + // NonSerializableFactory.getWrapperMap().put(key, value); + // String className = value.getClass().getName(); + // String factory = NonSerializableFactory.class.getName(); + // StringRefAddr addr = new StringRefAddr("nns", key); + // Reference memoryRef = new Reference(className, addr, factory, null); + // parentCtx.rebind(atom, memoryRef); + // } -// public static void bind(final Context ctx, final String strName, final Object value) throws NamingException -// { -// Name name = ctx.getNameParser("").parse(strName); -// int size = name.size(); -// String atom = name.get(size - 1); -// Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1)); -// String key = new StringBuilder().append(parentCtx.getNameInNamespace()).append("/").append(atom).toString(); -// NonSerializableFactory.getWrapperMap().put(key, value); -// String className = value.getClass().getName(); -// String factory = NonSerializableFactory.class.getName(); -// StringRefAddr addr = new StringRefAddr("nns", key); -// Reference memoryRef = new Reference(className, addr, factory, null); -// -// parentCtx.bind(atom, memoryRef); -// } + // public static void bind(final Context ctx, final String strName, final Object value) throws NamingException + // { + // Name name = ctx.getNameParser("").parse(strName); + // int size = name.size(); + // String atom = name.get(size - 1); + // Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1)); + // String key = new StringBuilder().append(parentCtx.getNameInNamespace()).append("/").append(atom).toString(); + // NonSerializableFactory.getWrapperMap().put(key, value); + // String className = value.getClass().getName(); + // String factory = NonSerializableFactory.class.getName(); + // StringRefAddr addr = new StringRefAddr("nns", key); + // Reference memoryRef = new Reference(className, addr, factory, null); + // + // parentCtx.bind(atom, memoryRef); + // } - public static Object lookup(final String name) throws NamingException - { - if (NonSerializableFactory.getWrapperMap().get(name) == null) - { + public static Object lookup(final String name) throws NamingException { + if (NonSerializableFactory.getWrapperMap().get(name) == null) { throw new NamingException(name + " not found"); } return NonSerializableFactory.getWrapperMap().get(name); } - public Object getObjectInstance(final Object obj, final Name name, final Context nameCtx, final Hashtable env) throws Exception - { + public Object getObjectInstance(final Object obj, + final Name name, + final Context nameCtx, + final Hashtable env) throws Exception { Reference ref = (Reference) obj; RefAddr addr = ref.get("nns"); String key = (String) addr.getContent(); return NonSerializableFactory.getWrapperMap().get(key); } - public static Map getWrapperMap() - { + public static Map getWrapperMap() { return NonSerializableFactory.wrapperMap; } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/ObjectInputStreamWithClassLoaderTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/ObjectInputStreamWithClassLoaderTest.java index fa08d6f5d0..7592c15e09 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/ObjectInputStreamWithClassLoaderTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/ObjectInputStreamWithClassLoaderTest.java @@ -40,33 +40,28 @@ import org.junit.Assert; import org.apache.activemq.artemis.utils.ObjectInputStreamWithClassLoader; -public class ObjectInputStreamWithClassLoaderTest extends ActiveMQTestBase -{ +public class ObjectInputStreamWithClassLoaderTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- // Static -------------------------------------------------------- - public static ClassLoader newClassLoader(final Class anyUserClass) throws Exception - { + public static ClassLoader newClassLoader(final Class anyUserClass) throws Exception { ProtectionDomain protectionDomain = anyUserClass.getProtectionDomain(); CodeSource codeSource = protectionDomain.getCodeSource(); URL classLocation = codeSource.getLocation(); StringTokenizer tokenString = new StringTokenizer(System.getProperty("java.class.path"), File.pathSeparator); String pathIgnore = System.getProperty("java.home"); - if (pathIgnore == null) - { + if (pathIgnore == null) { pathIgnore = classLocation.toString(); } List urls = new ArrayList(); - while (tokenString.hasMoreElements()) - { + while (tokenString.hasMoreElements()) { String value = tokenString.nextToken(); URL itemLocation = new File(value).toURI().toURL(); - if (!itemLocation.equals(classLocation) && itemLocation.toString().indexOf(pathIgnore) >= 0) - { + if (!itemLocation.equals(classLocation) && itemLocation.toString().indexOf(pathIgnore) >= 0) { urls.add(itemLocation); } } @@ -83,12 +78,10 @@ public class ObjectInputStreamWithClassLoaderTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testClassLoaderIsolation() throws Exception - { + public void testClassLoaderIsolation() throws Exception { ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); - try - { + try { AnObject obj = new AnObjectImpl(); byte[] bytes = ObjectInputStreamWithClassLoaderTest.toBytes(obj); @@ -105,49 +98,35 @@ public class ObjectInputStreamWithClassLoaderTest extends ActiveMQTestBase Assert.assertNotSame(obj.getClass().getClassLoader(), deserializedObj.getClass().getClassLoader()); Assert.assertSame(testClassLoader, deserializedObj.getClass().getClassLoader()); } - finally - { + finally { Thread.currentThread().setContextClassLoader(originalClassLoader); } } @Test - public void testClassLoaderIsolationWithProxy() throws Exception - { + public void testClassLoaderIsolationWithProxy() throws Exception { - ClassLoader originalClassLoader = Thread.currentThread() - .getContextClassLoader(); - try - { - AnObject originalProxy = (AnObject) Proxy.newProxyInstance( - AnObject.class.getClassLoader(), - new Class[]{AnObject.class}, - new AnObjectInvocationHandler()); + ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); + try { + AnObject originalProxy = (AnObject) Proxy.newProxyInstance(AnObject.class.getClassLoader(), new Class[]{AnObject.class}, new AnObjectInvocationHandler()); originalProxy.setMyInt(100); - byte[] bytes = ObjectInputStreamWithClassLoaderTest - .toBytes(originalProxy); + byte[] bytes = ObjectInputStreamWithClassLoaderTest.toBytes(originalProxy); - ClassLoader testClassLoader = ObjectInputStreamWithClassLoaderTest - .newClassLoader(this.getClass()); + ClassLoader testClassLoader = ObjectInputStreamWithClassLoaderTest.newClassLoader(this.getClass()); Thread.currentThread().setContextClassLoader(testClassLoader); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); - ObjectInputStreamWithClassLoader ois = new ObjectInputStreamWithClassLoader( - bais); + ObjectInputStreamWithClassLoader ois = new ObjectInputStreamWithClassLoader(bais); - Runnable toRun = (Runnable) testClassLoader.loadClass( - ProxyReader.class.getName()).newInstance(); + Runnable toRun = (Runnable) testClassLoader.loadClass(ProxyReader.class.getName()).newInstance(); toRun.getClass().getField("ois").set(toRun, ois); - toRun.getClass().getField("testClassLoader") - .set(toRun, testClassLoader); - toRun.getClass().getField("originalProxy") - .set(toRun, originalProxy); + toRun.getClass().getField("testClassLoader").set(toRun, testClassLoader); + toRun.getClass().getField("originalProxy").set(toRun, originalProxy); toRun.run(); } - finally - { + finally { Thread.currentThread().setContextClassLoader(originalClassLoader); } @@ -159,68 +138,55 @@ public class ObjectInputStreamWithClassLoaderTest extends ActiveMQTestBase // Private ------------------------------------------------------- - public static class ProxyReader implements Runnable - { + public static class ProxyReader implements Runnable { + public java.io.ObjectInputStream ois; public Object originalProxy; public ClassLoader testClassLoader; // We don't have access to the junit framework on the classloader where this is running - void myAssertNotSame(Object obj, Object obj2) - { - if (obj == obj2) - { + void myAssertNotSame(Object obj, Object obj2) { + if (obj == obj2) { throw new RuntimeException("Expected to be different objects"); } } // We don't have access to the junit framework on the classloader where this is running - void myAssertSame(Object obj, Object obj2) - { - if (obj != obj2) - { + void myAssertSame(Object obj, Object obj2) { + if (obj != obj2) { throw new RuntimeException("Expected to be the same objects"); } } - public void run() - { + public void run() { - try - { + try { Object deserializedObj = ois.readObject(); System.out.println("Deserialized Object " + deserializedObj); myAssertNotSame(originalProxy, deserializedObj); - myAssertNotSame(originalProxy.getClass(), - deserializedObj.getClass()); - myAssertNotSame(originalProxy.getClass().getClassLoader(), - deserializedObj.getClass().getClassLoader()); - myAssertSame(testClassLoader, deserializedObj.getClass() - .getClassLoader()); + myAssertNotSame(originalProxy.getClass(), deserializedObj.getClass()); + myAssertNotSame(originalProxy.getClass().getClassLoader(), deserializedObj.getClass().getClassLoader()); + myAssertSame(testClassLoader, deserializedObj.getClass().getClassLoader()); AnObject myInterface = (AnObject) deserializedObj; - if (myInterface.getMyInt() != 200) - { + if (myInterface.getMyInt() != 200) { throw new RuntimeException("invalid result"); } } - catch (ClassNotFoundException e) - { + catch (ClassNotFoundException e) { throw new RuntimeException(e.getMessage(), e); } - catch (IOException e) - { + catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } } - private static byte[] toBytes(final Object obj) throws IOException - { + private static byte[] toBytes(final Object obj) throws IOException { Assert.assertTrue(obj instanceof Serializable); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); @@ -231,8 +197,8 @@ public class ObjectInputStreamWithClassLoaderTest extends ActiveMQTestBase // Inner classes ------------------------------------------------- - private interface AnObject extends Serializable - { + private interface AnObject extends Serializable { + int getMyInt(); void setMyInt(int value); @@ -242,53 +208,46 @@ public class ObjectInputStreamWithClassLoaderTest extends ActiveMQTestBase void setMyLong(long value); } - private static class AnObjectImpl implements AnObject - { + private static class AnObjectImpl implements AnObject { + private static final long serialVersionUID = -5172742084489525256L; int myInt = 0; long myLong = 0L; @Override - public int getMyInt() - { + public int getMyInt() { return myInt; } @Override - public void setMyInt(int value) - { + public void setMyInt(int value) { this.myInt = value; } @Override - public long getMyLong() - { + public long getMyLong() { return myLong; } @Override - public void setMyLong(long value) - { + public void setMyLong(long value) { this.myLong = value; } } - private static class AnObjectInvocationHandler implements InvocationHandler, Serializable - { + private static class AnObjectInvocationHandler implements InvocationHandler, Serializable { + private static final long serialVersionUID = -3875973764178767452L; private final AnObject anObject = new AnObjectImpl(); @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable - { + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object obj = method.invoke(anObject, args); - if (obj instanceof Integer) - { + if (obj instanceof Integer) { return ((Integer) obj).intValue() * 2; } - else - { + else { return obj; } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/ReusableLatchTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/ReusableLatchTest.java index 70e1e1128f..97d8904dcb 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/ReusableLatchTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/ReusableLatchTest.java @@ -24,34 +24,29 @@ import org.apache.activemq.artemis.utils.ReusableLatch; import org.junit.Assert; import org.junit.Test; -public class ReusableLatchTest extends ActiveMQTestBase -{ +public class ReusableLatchTest extends ActiveMQTestBase { + @Test - public void testLatchWithParameterizedDown() throws Exception - { + public void testLatchWithParameterizedDown() throws Exception { ReusableLatch latch = new ReusableLatch(1000); latch.countDown(5000); assertTrue(latch.await(1000)); - assertEquals(0, latch.getCount()); } @Test - public void testLatchOnSingleThread() throws Exception - { + public void testLatchOnSingleThread() throws Exception { ReusableLatch latch = new ReusableLatch(); - for (int i = 1; i <= 100; i++) - { + for (int i = 1; i <= 100; i++) { latch.countUp(); Assert.assertEquals(i, latch.getCount()); } - for (int i = 100; i > 0; i--) - { + for (int i = 100; i > 0; i--) { Assert.assertEquals(i, latch.getCount()); latch.countDown(); Assert.assertEquals(i - 1, latch.getCount()); @@ -71,8 +66,7 @@ public class ReusableLatchTest extends ActiveMQTestBase * @throws Exception */ @Test - public void testLatchOnMultiThread() throws Exception - { + public void testLatchOnMultiThread() throws Exception { final ReusableLatch latch = new ReusableLatch(); latch.countUp(); // We hold at least one, so ThreadWaits won't go away @@ -80,56 +74,47 @@ public class ReusableLatchTest extends ActiveMQTestBase final int numberOfThreads = 100; final int numberOfAdds = 100; - class ThreadWait extends Thread - { + class ThreadWait extends Thread { + private volatile boolean waiting = true; @Override - public void run() - { - try - { - if (!latch.await(5000)) - { + public void run() { + try { + if (!latch.await(5000)) { UnitTestLogger.LOGGER.error("Latch timed out"); } } - catch (Exception e) - { + catch (Exception e) { UnitTestLogger.LOGGER.error(e); } waiting = false; } } - class ThreadAdd extends Thread - { + class ThreadAdd extends Thread { + private final CountDownLatch latchReady; private final CountDownLatch latchStart; - ThreadAdd(final CountDownLatch latchReady, final CountDownLatch latchStart) - { + ThreadAdd(final CountDownLatch latchReady, final CountDownLatch latchStart) { this.latchReady = latchReady; this.latchStart = latchStart; } @Override - public void run() - { - try - { + public void run() { + try { latchReady.countDown(); // Everybody should start at the same time, to worse concurrency // effects latchStart.await(); - for (int i = 0; i < numberOfAdds; i++) - { + for (int i = 0; i < numberOfAdds; i++) { latch.countUp(); } } - catch (Exception e) - { + catch (Exception e) { UnitTestLogger.LOGGER.error(e.getMessage(), e); } } @@ -141,8 +126,7 @@ public class ReusableLatchTest extends ActiveMQTestBase ThreadAdd[] threadAdds = new ThreadAdd[numberOfThreads]; ThreadWait[] waits = new ThreadWait[numberOfThreads]; - for (int i = 0; i < numberOfThreads; i++) - { + for (int i = 0; i < numberOfThreads; i++) { threadAdds[i] = new ThreadAdd(latchReady, latchStart); threadAdds[i].start(); waits[i] = new ThreadWait(); @@ -152,46 +136,39 @@ public class ReusableLatchTest extends ActiveMQTestBase latchReady.await(); latchStart.countDown(); - for (int i = 0; i < numberOfThreads; i++) - { + for (int i = 0; i < numberOfThreads; i++) { threadAdds[i].join(); } - for (int i = 0; i < numberOfThreads; i++) - { + for (int i = 0; i < numberOfThreads; i++) { Assert.assertTrue(waits[i].waiting); } Assert.assertEquals(numberOfThreads * numberOfAdds + 1, latch.getCount()); - class ThreadDown extends Thread - { + class ThreadDown extends Thread { + private final CountDownLatch latchReady; private final CountDownLatch latchStart; - ThreadDown(final CountDownLatch latchReady, final CountDownLatch latchStart) - { + ThreadDown(final CountDownLatch latchReady, final CountDownLatch latchStart) { this.latchReady = latchReady; this.latchStart = latchStart; } @Override - public void run() - { - try - { + public void run() { + try { latchReady.countDown(); // Everybody should start at the same time, to worse concurrency // effects latchStart.await(); - for (int i = 0; i < numberOfAdds; i++) - { + for (int i = 0; i < numberOfAdds; i++) { latch.countDown(); } } - catch (Exception e) - { + catch (Exception e) { UnitTestLogger.LOGGER.error(e.getMessage(), e); } } @@ -202,8 +179,7 @@ public class ReusableLatchTest extends ActiveMQTestBase ThreadDown[] down = new ThreadDown[numberOfThreads]; - for (int i = 0; i < numberOfThreads; i++) - { + for (int i = 0; i < numberOfThreads; i++) { down[i] = new ThreadDown(latchReady, latchStart); down[i].start(); } @@ -211,46 +187,40 @@ public class ReusableLatchTest extends ActiveMQTestBase latchReady.await(); latchStart.countDown(); - for (int i = 0; i < numberOfThreads; i++) - { + for (int i = 0; i < numberOfThreads; i++) { down[i].join(); } Assert.assertEquals(1, latch.getCount()); - for (int i = 0; i < numberOfThreads; i++) - { + for (int i = 0; i < numberOfThreads; i++) { Assert.assertTrue(waits[i].waiting); } latch.countDown(); - for (int i = 0; i < numberOfThreads; i++) - { + for (int i = 0; i < numberOfThreads; i++) { waits[i].join(); } Assert.assertEquals(0, latch.getCount()); - for (int i = 0; i < numberOfThreads; i++) - { + for (int i = 0; i < numberOfThreads; i++) { Assert.assertFalse(waits[i].waiting); } } @Test - public void testReuseLatch() throws Exception - { + public void testReuseLatch() throws Exception { final ReusableLatch latch = new ReusableLatch(5); - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { latch.countDown(); } latch.countUp(); - class ThreadWait extends Thread - { + class ThreadWait extends Thread { + private volatile boolean waiting = false; private volatile Exception e; @@ -258,19 +228,15 @@ public class ReusableLatchTest extends ActiveMQTestBase private final CountDownLatch readyLatch = new CountDownLatch(1); @Override - public void run() - { + public void run() { waiting = true; readyLatch.countDown(); - try - { - if (!latch.await(1000)) - { + try { + if (!latch.await(1000)) { UnitTestLogger.LOGGER.error("Latch timed out!", new Exception("trace")); } } - catch (Exception e) - { + catch (Exception e) { UnitTestLogger.LOGGER.error(e); this.e = e; } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/SoftValueMapTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/SoftValueMapTest.java index 703f4891c6..9e13967b32 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/SoftValueMapTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/SoftValueMapTest.java @@ -20,8 +20,7 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.SoftValueHashMap; import org.junit.Test; -public class SoftValueMapTest extends ActiveMQTestBase -{ +public class SoftValueMapTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- @@ -34,8 +33,7 @@ public class SoftValueMapTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testEvictions() - { + public void testEvictions() { forceGC(); long maxMemory = Runtime.getRuntime().maxMemory() - Runtime.getRuntime().freeMemory(); @@ -46,8 +44,7 @@ public class SoftValueMapTest extends ActiveMQTestBase final int MAX_ELEMENTS = 1000; - for (long i = 0; i < MAX_ELEMENTS; i++) - { + for (long i = 0; i < MAX_ELEMENTS; i++) { softCache.put(i, new Value(new byte[bufferSize])); } @@ -58,23 +55,19 @@ public class SoftValueMapTest extends ActiveMQTestBase System.out.println("Soft cache has " + softCache.size() + " elements"); } - @Test - public void testEvictionsLeastUsed() - { + public void testEvictionsLeastUsed() { forceGC(); SoftValueHashMap softCache = new SoftValueHashMap(200); - for (long i = 0; i < 100; i++) - { + for (long i = 0; i < 100; i++) { Value v = new Value(new byte[1]); v.setLive(true); softCache.put(i, v); } - for (long i = 100; i < 200; i++) - { + for (long i = 100; i < 200; i++) { Value v = new Value(new byte[1]); softCache.put(i, v); } @@ -85,8 +78,7 @@ public class SoftValueMapTest extends ActiveMQTestBase // these are live, so they shouldn't go - for (long i = 0; i < 100; i++) - { + for (long i = 0; i < 100; i++) { assertNotNull(softCache.get(i)); } @@ -102,13 +94,11 @@ public class SoftValueMapTest extends ActiveMQTestBase } @Test - public void testEvictOldestElement() - { + public void testEvictOldestElement() { Value one = new Value(new byte[100]); Value two = new Value(new byte[100]); Value three = new Value(new byte[100]); - SoftValueHashMap softCache = new SoftValueHashMap(2); softCache.put(3, three); softCache.put(2, two); @@ -118,35 +108,30 @@ public class SoftValueMapTest extends ActiveMQTestBase assertEquals(two, softCache.get(2)); assertEquals(one, softCache.get(1)); - } - class Value implements SoftValueHashMap.ValueCache - { + class Value implements SoftValueHashMap.ValueCache { + byte[] payload; boolean live; - Value(byte[] payload) - { + Value(byte[] payload) { this.payload = payload; } /* (non-Javadoc) * @see org.apache.activemq.artemis.utils.SoftValueHashMap.ValueCache#isLive() */ - public boolean isLive() - { + public boolean isLive() { return live; } - public void setLive(boolean live) - { + public void setLive(boolean live) { this.live = live; } } - // Package protected --------------------------------------------- // Protected ----------------------------------------------------- diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/UTF8Test.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/UTF8Test.java index 8dcda85558..ae143d47da 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/UTF8Test.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/UTF8Test.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.artemis.tests.unit.util; + import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.ActiveMQBuffers; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; @@ -35,12 +36,10 @@ import org.apache.activemq.artemis.utils.DataConstants; import org.apache.activemq.artemis.utils.Random; import org.apache.activemq.artemis.utils.UTF8Util; -public class UTF8Test extends ActiveMQTestBase -{ +public class UTF8Test extends ActiveMQTestBase { @Test - public void testValidateUTF() throws Exception - { + public void testValidateUTF() throws Exception { ActiveMQBuffer buffer = ActiveMQBuffers.fixedBuffer(60 * 1024); byte[] bytes = new byte[20000]; @@ -58,10 +57,8 @@ public class UTF8Test extends ActiveMQTestBase } @Test - public void testValidateUTFOnDataInput() throws Exception - { - for (int i = 0; i < 100; i++) - { + public void testValidateUTFOnDataInput() throws Exception { + for (int i = 0; i < 100; i++) { Random random = new Random(); // Random size between 15k and 20K @@ -72,9 +69,7 @@ public class UTF8Test extends ActiveMQTestBase String str = new String(bytes); // The maximum size the encoded UTF string would reach is str.length * 3 (look at the UTF8 implementation) - testValidateUTFOnDataInputStream(str, - ActiveMQBuffers.wrappedBuffer(ByteBuffer.allocate(str.length() * 3 + - DataConstants.SIZE_SHORT))); + testValidateUTFOnDataInputStream(str, ActiveMQBuffers.wrappedBuffer(ByteBuffer.allocate(str.length() * 3 + DataConstants.SIZE_SHORT))); testValidateUTFOnDataInputStream(str, ActiveMQBuffers.dynamicBuffer(100)); @@ -82,8 +77,7 @@ public class UTF8Test extends ActiveMQTestBase } } - private void testValidateUTFOnDataInputStream(final String str, final ActiveMQBuffer wrap) throws Exception - { + private void testValidateUTFOnDataInputStream(final String str, final ActiveMQBuffer wrap) throws Exception { UTF8Util.saveUTF(wrap, str); DataInputStream data = new DataInputStream(new ByteArrayInputStream(wrap.toByteBuffer().array())); @@ -105,13 +99,11 @@ public class UTF8Test extends ActiveMQTestBase } @Test - public void testBigSize() throws Exception - { + public void testBigSize() throws Exception { char[] chars = new char[0xffff + 1]; - for (int i = 0; i < chars.length; i++) - { + for (int i = 0; i < chars.length; i++) { chars[i] = ' '; } @@ -119,33 +111,28 @@ public class UTF8Test extends ActiveMQTestBase ActiveMQBuffer buffer = ActiveMQBuffers.fixedBuffer(0xffff + 4); - try - { + try { UTF8Util.saveUTF(buffer, str); Assert.fail("String is too big, supposed to throw an exception"); } - catch (Exception ignored) - { + catch (Exception ignored) { } Assert.assertEquals("A buffer was supposed to be untouched since the string was too big", 0, buffer.writerIndex()); chars = new char[25000]; - for (int i = 0; i < chars.length; i++) - { + for (int i = 0; i < chars.length; i++) { chars[i] = 0x810; } str = new String(chars); - try - { + try { UTF8Util.saveUTF(buffer, str); Assert.fail("Encoded String is too big, supposed to throw an exception"); } - catch (Exception ignored) - { + catch (Exception ignored) { } Assert.assertEquals("A buffer was supposed to be untouched since the string was too big", 0, buffer.writerIndex()); @@ -153,9 +140,8 @@ public class UTF8Test extends ActiveMQTestBase // Testing a string right on the limit chars = new char[0xffff]; - for (int i = 0; i < chars.length; i++) - { - chars[i] = (char)(i % 100 + 1); + for (int i = 0; i < chars.length; i++) { + chars[i] = (char) (i % 100 + 1); } str = new String(chars); @@ -172,8 +158,7 @@ public class UTF8Test extends ActiveMQTestBase @Override @After - public void tearDown() throws Exception - { + public void tearDown() throws Exception { UTF8Util.clearBuffer(); super.tearDown(); } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/UUIDGeneratorTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/UUIDGeneratorTest.java index f8016232c7..48282e32de 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/UUIDGeneratorTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/UUIDGeneratorTest.java @@ -21,8 +21,7 @@ import org.apache.activemq.artemis.utils.UUIDGenerator; import org.junit.Assert; import org.junit.Test; -public class UUIDGeneratorTest extends ActiveMQTestBase -{ +public class UUIDGeneratorTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -34,15 +33,12 @@ public class UUIDGeneratorTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testGetHardwareAddress() throws Exception - { + public void testGetHardwareAddress() throws Exception { String javaVersion = System.getProperty("java.vm.version"); - if (javaVersion.startsWith("1.5")) - { + if (javaVersion.startsWith("1.5")) { Assert.assertNull(UUIDGenerator.getHardwareAddress()); } - else if (javaVersion.startsWith("1.6")) - { + else if (javaVersion.startsWith("1.6")) { byte[] bytes = UUIDGenerator.getHardwareAddress(); Assert.assertNotNull(bytes); Assert.assertTrue(bytes.length == 6); @@ -50,8 +46,7 @@ public class UUIDGeneratorTest extends ActiveMQTestBase } @Test - public void testZeroPaddedBytes() throws Exception - { + public void testZeroPaddedBytes() throws Exception { Assert.assertNull(UUIDGenerator.getZeroPaddedSixBytes(null)); Assert.assertNull(UUIDGenerator.getZeroPaddedSixBytes(new byte[0])); Assert.assertNull(UUIDGenerator.getZeroPaddedSixBytes(new byte[7])); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/UUIDTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/UUIDTest.java index 0c03f7dc90..62cb3a031d 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/UUIDTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/UUIDTest.java @@ -27,18 +27,16 @@ import org.junit.Assert; import org.apache.activemq.artemis.utils.UUID; import org.apache.activemq.artemis.utils.UUIDGenerator; -public class UUIDTest extends ActiveMQTestBase -{ +public class UUIDTest extends ActiveMQTestBase { + static final int MANY_TIMES = 100000; @Test - public void testManyUUIDs() throws Exception - { + public void testManyUUIDs() throws Exception { Set uuidsSet = new HashSet(); UUIDGenerator gen = UUIDGenerator.getInstance(); - for (int i = 0; i < getTimes(); i++) - { + for (int i = 0; i < getTimes(); i++) { uuidsSet.add(gen.generateStringUUID()); } @@ -46,17 +44,14 @@ public class UUIDTest extends ActiveMQTestBase Assert.assertEquals(getTimes(), uuidsSet.size()); } - protected int getTimes() - { + protected int getTimes() { return MANY_TIMES; } @Test - public void testStringToUuidConversion() - { + public void testStringToUuidConversion() { UUIDGenerator gen = UUIDGenerator.getInstance(); - for (int i = 0; i < MANY_TIMES; i++) - { + for (int i = 0; i < MANY_TIMES; i++) { final UUID uuid = gen.generateUUID(); final String uuidString = uuid.toString(); byte[] data2 = UUID.stringToBytes(uuidString); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/VersionLoaderTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/VersionLoaderTest.java index d9b93af311..e9c447db00 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/VersionLoaderTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/VersionLoaderTest.java @@ -25,8 +25,7 @@ import org.apache.activemq.artemis.utils.VersionLoader; import org.junit.Assert; import org.junit.Test; -public class VersionLoaderTest extends ActiveMQTestBase -{ +public class VersionLoaderTest extends ActiveMQTestBase { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- @@ -38,22 +37,17 @@ public class VersionLoaderTest extends ActiveMQTestBase // Public -------------------------------------------------------- @Test - public void testLoadVersion() throws Exception - { + public void testLoadVersion() throws Exception { Version version = VersionLoader.getVersion(); Properties props = new Properties(); props.load(ClassLoader.getSystemResourceAsStream(VersionLoader.DEFAULT_PROP_FILE_NAME)); Assert.assertEquals(props.get("activemq.version.versionName"), version.getVersionName()); - Assert.assertEquals(Integer.parseInt(props.getProperty("activemq.version.majorVersion")), - version.getMajorVersion()); - Assert.assertEquals(Integer.parseInt(props.getProperty("activemq.version.minorVersion")), - version.getMinorVersion()); - Assert.assertEquals(Integer.parseInt(props.getProperty("activemq.version.microVersion")), - version.getMicroVersion()); - Assert.assertEquals(Integer.parseInt(new StringTokenizer(props.getProperty("activemq.version.incrementingVersion"), ",").nextToken()), - version.getIncrementingVersion()); + Assert.assertEquals(Integer.parseInt(props.getProperty("activemq.version.majorVersion")), version.getMajorVersion()); + Assert.assertEquals(Integer.parseInt(props.getProperty("activemq.version.minorVersion")), version.getMinorVersion()); + Assert.assertEquals(Integer.parseInt(props.getProperty("activemq.version.microVersion")), version.getMicroVersion()); + Assert.assertEquals(Integer.parseInt(new StringTokenizer(props.getProperty("activemq.version.incrementingVersion"), ",").nextToken()), version.getIncrementingVersion()); } // Z implementation ---------------------------------------------- diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/util/CreateMessage.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/util/CreateMessage.java index 937ca1229e..6309ce15b6 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/util/CreateMessage.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/util/CreateMessage.java @@ -21,43 +21,26 @@ import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.jms.client.ActiveMQBytesMessage; import org.apache.activemq.artemis.jms.client.ActiveMQTextMessage; -public final class CreateMessage -{ +public final class CreateMessage { - private CreateMessage() - { + private CreateMessage() { // Utility class } - public static ClientMessage createTextMessage(final String s, final ClientSession clientSession) - { - ClientMessage message = clientSession.createMessage(ActiveMQTextMessage.TYPE, - true, - 0, - System.currentTimeMillis(), - (byte) 4); + public static ClientMessage createTextMessage(final String s, final ClientSession clientSession) { + ClientMessage message = clientSession.createMessage(ActiveMQTextMessage.TYPE, true, 0, System.currentTimeMillis(), (byte) 4); message.getBodyBuffer().writeString(s); return message; } - public static ClientMessage createBytesMessage(final ClientSession session, final byte[] b, final boolean durable) - { - ClientMessage message = session.createMessage(ActiveMQBytesMessage.TYPE, - durable, - 0, - System.currentTimeMillis(), - (byte) 1); + public static ClientMessage createBytesMessage(final ClientSession session, final byte[] b, final boolean durable) { + ClientMessage message = session.createMessage(ActiveMQBytesMessage.TYPE, durable, 0, System.currentTimeMillis(), (byte) 1); message.getBodyBuffer().writeBytes(b); return message; } - public static ClientMessage createTextMessage(final ClientSession session, final String s, final boolean durable) - { - ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, - durable, - 0, - System.currentTimeMillis(), - (byte) 1); + public static ClientMessage createTextMessage(final ClientSession session, final String s, final boolean durable) { + ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, durable, 0, System.currentTimeMillis(), (byte) 1); message.getBodyBuffer().writeString(s); return message; } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/util/SpawnedVMSupport.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/util/SpawnedVMSupport.java index c05ee02d8a..01bbd681a5 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/util/SpawnedVMSupport.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/util/SpawnedVMSupport.java @@ -34,52 +34,46 @@ import org.junit.Assert; import static java.util.concurrent.TimeUnit.SECONDS; -public final class SpawnedVMSupport -{ +public final class SpawnedVMSupport { + private static final UnitTestLogger log = UnitTestLogger.LOGGER; - public static Process spawnVM(final String className, final String... args) throws Exception - { + public static Process spawnVM(final String className, final String... args) throws Exception { return SpawnedVMSupport.spawnVM(className, new String[0], true, args); } - public static Process spawnVM(final String className, final boolean logOutput, final String... args) throws Exception - { + public static Process spawnVM(final String className, + final boolean logOutput, + final String... args) throws Exception { return SpawnedVMSupport.spawnVM(className, new String[0], logOutput, args); } - public static Process spawnVM(final String className, final String[] vmargs, final String... args) throws Exception - { + public static Process spawnVM(final String className, final String[] vmargs, final String... args) throws Exception { return SpawnedVMSupport.spawnVM(className, vmargs, true, args); } public static Process spawnVM(final String className, final String[] vmargs, final boolean logOutput, - final String... args) throws Exception - { + final String... args) throws Exception { return SpawnedVMSupport.spawnVM(className, "-Xms512m", "-Xmx512m", vmargs, logOutput, true, args); } - public static Process spawnVM(final String className, final String memoryArg1, final String memoryArg2, final String[] vmargs, final boolean logOutput, final boolean logErrorOutput, - final String... args) throws Exception - { + final String... args) throws Exception { ProcessBuilder builder = new ProcessBuilder(); final String javaPath = Paths.get(System.getProperty("java.home"), "bin", "java").toAbsolutePath().toString(); builder.command(javaPath, memoryArg1, memoryArg2, "-cp", System.getProperty("java.class.path")); List commandList = builder.command(); - if (vmargs != null) - { - for (String arg : vmargs) - { + if (vmargs != null) { + for (String arg : vmargs) { commandList.add(arg); } } @@ -87,30 +81,25 @@ public final class SpawnedVMSupport commandList.add("-Djava.io.tmpdir=" + System.getProperty("java.io.tmpdir", "./tmp")); commandList.add("-Djava.library.path=" + System.getProperty("java.library.path", "./native/bin")); - String loggingConfigFile = System.getProperty("java.util.logging.config.file"); - if (loggingConfigFile != null) - { + if (loggingConfigFile != null) { commandList.add("-Djava.util.logging.config.file=" + loggingConfigFile + " "); } String loggingPlugin = System.getProperty("org.jboss.logging.Logger.pluginClass"); - if (loggingPlugin != null) - { + if (loggingPlugin != null) { commandList.add("-Dorg.jboss.logging.Logger.pluginClass=" + loggingPlugin + " "); } commandList.add(className); - for (String arg : args) - { + for (String arg : args) { commandList.add(arg); } Process process = builder.start(); - if (logOutput) - { + if (logOutput) { SpawnedVMSupport.startLogger(className, process); } @@ -122,7 +111,6 @@ public final class SpawnedVMSupport return process; - } /** @@ -130,8 +118,7 @@ public final class SpawnedVMSupport * @param process * @throws ClassNotFoundException */ - public static void startLogger(final String className, final Process process) throws ClassNotFoundException - { + public static void startLogger(final String className, final Process process) throws ClassNotFoundException { ProcessLogger outputLogger = new ProcessLogger(true, process.getInputStream(), className); outputLogger.start(); } @@ -142,34 +129,27 @@ public final class SpawnedVMSupport * seconds for the process to exit, then an Exception is thrown. In any case, * the process is destroyed before the method returns. */ - public static void assertProcessExits(final boolean sameValue, final int value, final Process p) throws InterruptedException, - ExecutionException, - TimeoutException - { + public static void assertProcessExits(final boolean sameValue, + final int value, + final Process p) throws InterruptedException, ExecutionException, TimeoutException { ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); - Future future = executor.submit(new Callable() - { + Future future = executor.submit(new Callable() { - public Integer call() throws Exception - { + public Integer call() throws Exception { p.waitFor(); return p.exitValue(); } }); - try - { + try { int exitValue = future.get(10, SECONDS); - if (sameValue) - { + if (sameValue) { Assert.assertSame(value, exitValue); } - else - { + else { Assert.assertNotSame(value, exitValue); } } - finally - { + finally { p.destroy(); } } @@ -177,16 +157,15 @@ public final class SpawnedVMSupport /** * Redirect the input stream to a logger (as debug logs) */ - static class ProcessLogger extends Thread - { + static class ProcessLogger extends Thread { + private final InputStream is; private final String className; private final boolean print; - ProcessLogger(final boolean print, final InputStream is, final String className) throws ClassNotFoundException - { + ProcessLogger(final boolean print, final InputStream is, final String className) throws ClassNotFoundException { this.is = is; this.print = print; this.className = className; @@ -194,23 +173,18 @@ public final class SpawnedVMSupport } @Override - public void run() - { - try - { + public void run() { + try { InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = null; - while ((line = br.readLine()) != null) - { - if (print) - { + while ((line = br.readLine()) != null) { + if (print) { System.out.println(className + ":" + line); } } } - catch (IOException ioe) - { + catch (IOException ioe) { ioe.printStackTrace(); } }

  • Date" + j + "
    " + value + "